From 5c1bb7bfa99af77e44d05de93f7158345d732a4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Sat, 13 Jul 2024 15:19:22 -0700 Subject: [PATCH 01/12] Data update --- Lang/8080-Assembly/Square-but-not-cube | 1 + Lang/AArch64-Assembly/Pi | 1 + Lang/ABC/Look-and-say-sequence | 1 + Lang/ABC/Population-count | 1 + Lang/ABC/Square-but-not-cube | 1 + Lang/ALGOL-68/00-LANG.txt | 31 +- Lang/ALGOL-68/Draw-a-cuboid | 1 + Lang/ALGOL-68/Perlin-noise | 1 + Lang/ALGOL-68/Sleeping-Beauty-problem | 1 + Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort | 1 + Lang/ALGOL-W/Eulers-constant-0.5772... | 1 + .../Find-the-intersection-of-two-lines | 1 + ...Pseudo-random-numbers-Middle-square-method | 1 + Lang/ANSI-BASIC/Damm-algorithm | 1 + Lang/ANSI-BASIC/Formatted-numeric-output | 1 + Lang/ANSI-BASIC/Function-definition | 1 + Lang/ANSI-BASIC/Monty-Hall-problem | 1 + Lang/ANSI-BASIC/Random-numbers | 1 + Lang/ANSI-BASIC/Real-constants-and-functions | 1 + Lang/ANSI-BASIC/Sorting-algorithms-Quicksort | 1 + Lang/APL/Display-a-linear-combination | 1 + Lang/APL/Pisano-period | 1 + Lang/APL/Word-ladder | 1 + Lang/ARM-Assembly/Pi | 1 + Lang/Ada/00-LANG.txt | 4 +- Lang/Ada/Abelian-sandpile-model | 1 + Lang/Ada/Achilles-numbers | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Ada/Ascending-primes | 1 + Lang/Ada/Brace-expansion | 1 + Lang/Ada/Color-wheel | 1 + Lang/Ada/Combinations-and-permutations | 1 + Lang/Ada/Eulers-constant-0.5772... | 1 + Lang/Ada/FTP | 1 + Lang/Ada/Hex-words | 1 + ...he-characters-that-can-be-used-for-symbols | 1 + .../Largest-number-divisible-by-its-digits | 1 + Lang/Ada/Magic-constant | 1 + Lang/Ada/Mind-boggling-card-trick | 1 + Lang/Ada/Musical-scale | 1 + Lang/Ada/Next-highest-int-from-digits | 1 + Lang/Ada/Penneys-game | 1 + Lang/Ada/Permutations-by-swapping | 1 + Lang/Ada/Play-recorded-sounds | 1 + Lang/Ada/Poker-hand-analyser | 1 + Lang/Ada/Record-sound | 1 + ...e-instances-of-a-character-within-a-string | 1 + Lang/Ada/Sierpinski-square-curve | 1 + Lang/Ada/Sorting-algorithms-Permutation-sort | 1 + Lang/Ada/UPC | 1 + Lang/Ada/War-card-game | 1 + Lang/Ada/Weird-numbers | 1 + Lang/Ada/Word-ladder | 1 + Lang/Ada/Word-search | 1 + Lang/Ada/Word-wheel | 1 + Lang/AmigaBASIC/00-LANG.txt | 2 + .../Display-a-linear-combination | 1 + Lang/Applesoft-BASIC/Repeat | 1 + Lang/Asymptote/Jensens-Device | 1 + Lang/Asymptote/Towers-of-Hanoi | 1 + Lang/AutoHotKey-V2/00-LANG.txt | 1 - Lang/AutoHotKey-V2/00-META.yaml | 2 - Lang/AutoHotKey-V2/Hello-world-Graphical | 1 - Lang/Autohotkey-V2/00-LANG.txt | 16 + Lang/Autohotkey-V2/00-META.yaml | 2 + Lang/Autohotkey-V2/Hello-world-Graphical | 1 + Lang/BASIC/00-LANG.txt | 32 +- Lang/BASIC/Damm-algorithm | 1 - Lang/BASIC/Function-definition | 1 - Lang/BASIC/Gray-code | 1 - Lang/BASIC/Monty-Hall-problem | 1 - Lang/BASIC/Ordered-words | 1 + Lang/BASIC/Sorting-algorithms-Quicksort | 1 - Lang/BASIC256/Kronecker-product | 1 + Lang/BASIC256/Multiple-regression | 1 + Lang/BASIC256/Nested-templated-data | 1 + .../Ramer-Douglas-Peucker-line-simplification | 1 + Lang/BASIC256/Sexy-primes | 1 + Lang/Bruijn/Harmonic-series | 1 + Lang/Bruijn/Towers-of-Hanoi | 1 + ...-a-variable-to-a-class-instance-at-runtime | 1 + Lang/C++/Bitcoin-address-validation | 1 + Lang/C++/Bitcoin-public-point-to-address | 1 + Lang/C++/Catmull-Clark-subdivision-surface | 1 + Lang/C++/Compiler-virtual-machine-interpreter | 1 + ...bers-indexing-permutations-of-a-collection | 1 + .../Im-a-software-engineer-get-me-out-of-here | 1 + Lang/C++/P-Adic-square-roots | 1 + Lang/C++/Simple-database | 1 + Lang/C++/Sort-an-outline-at-every-level | 1 + Lang/C-sharp/Additive-primes | 1 + Lang/C-sharp/Cyclops-numbers | 1 + Lang/C-sharp/Summarize-primes | 1 + Lang/C-sharp/Tau-function | 1 + Lang/C-sharp/Tau-number | 1 + Lang/C-sharp/Tree-from-nesting-levels | 1 + Lang/C-sharp/Ultra-useful-primes | 1 + Lang/C-sharp/Variable-declaration-reset | 1 + Lang/C-sharp/Yellowstone-sequence | 1 + Lang/C/Hunt-the-Wumpus | 1 + Lang/C/Pig-the-dice-game-Player | 1 + Lang/COBOL/Nim-game | 1 + Lang/COBOL/Parametric-polymorphism | 1 + Lang/Chapel/Function-definition | 1 + Lang/Chapel/Maze-generation | 1 + Lang/Chapel/Repeat | 1 + .../Display-a-linear-combination | 1 + .../Fibonacci-n-step-number-sequences | 1 + Lang/Chipmunk-Basic/Jensens-Device | 1 + Lang/Chipmunk-Basic/Multiple-regression | 1 + Lang/Chipmunk-Basic/Nested-templated-data | 1 + Lang/Chipmunk-Basic/Price-fraction | 1 + Lang/Chipmunk-Basic/Proper-divisors | 1 + Lang/Chipmunk-Basic/Rate-counter | 1 + Lang/Chipmunk-Basic/Vector | 1 + Lang/Commodore-BASIC/N-queens-problem | 1 + Lang/Common-Lisp/Blum-integer | 1 + Lang/Common-Lisp/Factorial-primes | 1 + Lang/Cowgol/Display-a-linear-combination | 1 + Lang/Dart/15-puzzle-solver | 1 + Lang/Dart/Jensens-Device | 1 + Lang/Dart/Solve-a-Numbrix-puzzle | 1 + Lang/Draco/Display-a-linear-combination | 1 + Lang/EMal/Babbage-problem | 1 + Lang/EMal/Bifid-cipher | 1 + Lang/EMal/Mutual-recursion | 1 + Lang/EMal/Sorting-algorithms-Bogosort | 1 + Lang/EMal/Tree-traversal | 1 + Lang/EMal/User-input-Text | 1 + Lang/EasyLang/00-LANG.txt | 6 +- Lang/EasyLang/Abelian-sandpile-model | 1 + Lang/EasyLang/Abelian-sandpile-model-Identity | 1 + Lang/EasyLang/Approximate-equality | 1 + Lang/EasyLang/Arithmetic-Complex | 1 + Lang/EasyLang/Greatest-subsequential-sum | 1 + .../Guess-the-number-With-feedback-player- | 1 + Lang/EasyLang/Halt-and-catch-fire | 1 + Lang/EasyLang/Hamming-numbers | 1 + .../Hofstadter-Figure-Figure-sequences | 1 + Lang/EasyLang/IBAN | 1 + Lang/EasyLang/Iterated-digits-squaring | 1 + Lang/EasyLang/JortSort | 1 + Lang/EasyLang/Kronecker-product | 1 + .../EasyLang/Kronecker-product-based-fractals | 1 + .../Largest-int-from-concatenated-ints | 1 + Lang/EasyLang/Last-letter-first-letter | 1 + Lang/EasyLang/Longest-increasing-subsequence | 1 + Lang/EasyLang/Ludic-numbers | 1 + Lang/EasyLang/Map-range | 1 + Lang/EasyLang/Move-to-front-algorithm | 1 + Lang/EasyLang/Multisplit | 1 + Lang/EasyLang/Negative-base-numbers | 1 + Lang/EasyLang/Non-continuous-subsequences | 1 + Lang/EasyLang/Non-decimal-radices-Input | 1 + Lang/EasyLang/Number-reversal-game | 1 + .../Partition-an-integer-x-into-n-primes | 1 + Lang/EasyLang/Pascal-matrix-generation | 1 + .../Pathological-floating-point-problems | 1 + Lang/EasyLang/Peripheral-drift-illusion | 1 + .../Permutations-Rank-of-a-permutation | 1 + Lang/EasyLang/Phrase-reversals | 1 + Lang/EasyLang/Pierpont-primes | 1 + Lang/EasyLang/Pinstripe-Display | 1 + Lang/EasyLang/Plasma-effect | 1 + Lang/EasyLang/Pythagorean-quadruples | 1 + Lang/EasyLang/Range-expansion | 1 + Lang/EasyLang/Rock-paper-scissors | 1 + Lang/EasyLang/Ruth-Aaron-numbers | 1 + .../Sailors-coconuts-and-a-monkey-problem | 1 + Lang/EasyLang/Scope-Function-names-and-labels | 1 + ...e-instances-of-a-character-within-a-string | 1 + Lang/EasyLang/Self-numbers | 1 + Lang/EasyLang/Show-the-epoch | 1 + Lang/EasyLang/Sierpinski-triangle | 1 + .../Sort-a-list-of-object-identifiers | 1 + Lang/EasyLang/Sort-an-integer-array | 1 + Lang/EasyLang/Sort-numbers-lexicographically | 1 + Lang/EasyLang/Sorting-Algorithms-Circle-Sort | 1 + .../EasyLang/Sorting-algorithms-Cocktail-sort | 1 + Lang/EasyLang/Sorting-algorithms-Comb-sort | 1 + Lang/EasyLang/Sorting-algorithms-Pancake-sort | 1 + .../Sorting-algorithms-Permutation-sort | 1 + Lang/EasyLang/Sorting-algorithms-Shell-sort | 1 + Lang/EasyLang/Sorting-algorithms-Strand-sort | 1 + Lang/EasyLang/Stair-climbing-puzzle | 1 + Lang/EasyLang/Stem-and-leaf-plot | 1 + Lang/EasyLang/Taxicab-numbers | 1 + Lang/EasyLang/Tokenize-a-string-with-escaping | 1 + Lang/EasyLang/Top-rank-per-group | 1 + .../Verify-distribution-uniformity-Naive | 1 + Lang/EasyLang/Zig-zag-matrix | 1 + Lang/Ecstasy/00-LANG.txt | 5 +- Lang/Ecstasy/100-prisoners | 1 + Lang/Ecstasy/Assertions | 1 + Lang/Ecstasy/Pointers-and-references | 1 + Lang/Ecstasy/Program-name | 1 + Lang/Ecstasy/Reflection-List-methods | 1 + Lang/Ecstasy/Reflection-List-properties | 1 + Lang/Ecstasy/Search-a-list | 1 + Lang/Ecstasy/Send-an-unknown-method-call | 1 + Lang/Ecstasy/Singleton | 1 + Lang/Ecstasy/String-case | 1 + Lang/Ecstasy/String-comparison | 1 + Lang/Ecstasy/String-concatenation | 1 + Lang/Ecstasy/String-length | 1 + Lang/Ecstasy/Substring | 1 + Lang/Ecstasy/Substring-Top-and-tail | 1 + Lang/Ecstasy/System-time | 1 + Lang/Elixir/Parallel-brute-force | 1 + Lang/Elm/Caesar-cipher | 1 + Lang/Emacs-Lisp/Abbreviations-automatic | 1 + Lang/Emacs-Lisp/Anagrams | 1 + Lang/Emacs-Lisp/Compare-length-of-two-strings | 1 + Lang/Emacs-Lisp/Date-manipulation | 1 + .../Determine-if-a-string-is-numeric | 1 + Lang/Emacs-Lisp/Determine-sentence-type | 1 + Lang/Emacs-Lisp/Ordered-words | 1 + Lang/Emacs-Lisp/Snake | 1 + Lang/Emacs-Lisp/Substitution-cipher | 1 + Lang/Fortran/Sleeping-Beauty-problem | 1 + Lang/Free-Pascal-Lazarus/Bin-given-limits | 1 + .../Closures-Value-capture | 1 + .../Free-Pascal-Lazarus/Parallel-calculations | 1 + Lang/FreeBASIC/B-zier-curves-Intersections | 1 + Lang/FreeBASIC/Constrained-genericity | 1 + Lang/FreeBASIC/Execute-Computer-Zero | 1 + Lang/FreeBASIC/Execute-SNUSP | 1 + Lang/FreeBASIC/Execute-a-Markov-algorithm | 1 + Lang/FreeBASIC/Imaginary-base-numbers | 1 + Lang/FreeBASIC/Nested-templated-data | 1 + Lang/FreeBASIC/Padovan-sequence | 1 + Lang/FreeBASIC/Pseudo-random-numbers-PCG32 | 1 + .../Pseudo-random-numbers-Splitmix64 | 1 + .../Pseudo-random-numbers-Xorshift-star | 1 + .../Runtime-evaluation-In-an-environment | 1 + Lang/FreeBASIC/Solve-the-no-connection-puzzle | 1 + Lang/FreeBASIC/Write-to-Windows-event-log | 1 + Lang/Frink/24-game | 1 + Lang/FutureBasic/24-game | 1 + Lang/FutureBasic/ASCII-art-diagram-converter | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/FutureBasic/Biorhythms | 1 + Lang/FutureBasic/Brilliant-numbers | 1 + .../Check-output-device-is-a-terminal | 1 + Lang/FutureBasic/Combinations | 1 + Lang/FutureBasic/Copy-stdin-to-stdout | 1 + Lang/FutureBasic/Determine-sentence-type | 1 + Lang/FutureBasic/Floyds-triangle | 1 + Lang/FutureBasic/Function-prototype | 1 + Lang/FutureBasic/Go-Fish | 1 + Lang/FutureBasic/Honeycombs | 1 + Lang/FutureBasic/Monty-Hall-problem | 1 + Lang/FutureBasic/Record-sound | 1 + Lang/GW-BASIC/Damm-algorithm | 1 + Lang/GW-BASIC/Display-a-linear-combination | 1 + Lang/GW-BASIC/Gray-code | 1 + Lang/GW-BASIC/Jensens-Device | 1 + Lang/GW-BASIC/Nested-templated-data | 1 + Lang/GW-BASIC/Primality-by-trial-division | 1 + Lang/GW-BASIC/Vector | 1 + Lang/Gambas/Jensens-Device | 1 + Lang/Gambas/M-bius-function | 1 + Lang/Gambas/Proper-divisors | 1 + Lang/Go/Factorial-primes | 1 + Lang/Java/Arena-storage-pool | 1 + Lang/Java/Bitcoin-public-point-to-address | 1 + Lang/Java/Catmull-Clark-subdivision-surface | 1 + .../Java/Compiler-virtual-machine-interpreter | 1 + .../Im-a-software-engineer-get-me-out-of-here | 1 + Lang/Java/P-Adic-square-roots | 1 + Lang/Java/Topic-variable | 1 + Lang/Jq/00-LANG.txt | 5 + Lang/Jq/2048 | 1 + Lang/Jq/24-game | 1 + Lang/Jq/Averages-Simple-moving-average | 1 + Lang/Jq/Bitwise-operations | 1 + Lang/Jq/CRC-32 | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/Jq/Deconvolution-1D | 1 + Lang/Jq/Display-an-outline-as-a-nested-table | 1 + Lang/Jq/Draw-a-cuboid | 1 + Lang/Jq/Entropy-Narcissist | 1 + Lang/Jq/Factors-of-a-Mersenne-number | 1 + Lang/Jq/File-size-distribution | 1 + ...Find-Chess960-starting-position-identifier | 1 + Lang/Jq/Find-duplicate-files | 1 + Lang/Jq/French-Republican-calendar | 1 + Lang/Jq/Generate-random-chess-position | 1 + Lang/Jq/Giuga-numbers | 1 + Lang/Jq/Graph-colouring | 1 + Lang/Jq/Introspection | 1 + Lang/Jq/Knights-tour | 1 + Lang/Jq/Levenshtein-distance-Alignment | 1 + Lang/Jq/Mayan-calendar | 1 + Lang/Jq/Mind-boggling-card-trick | 1 + Lang/Jq/Minimal-steps-down-to-1 | 1 + Lang/Jq/Modified-random-distribution | 1 + Lang/Jq/Multiplicative-order | 1 + Lang/Jq/Nonoblock | 1 + Lang/Jq/Nonogram-solver | 1 + Lang/Jq/P-value-correction | 1 + Lang/Jq/Palindromic-gapful-numbers | 1 + Lang/Jq/Peaceful-chess-queen-armies | 1 + Lang/Jq/Pentomino-tiling | 1 + Lang/Jq/Perlin-noise | 1 + Lang/Jq/Pisano-period | 1 + Lang/Jq/Poker-hand-analyser | 1 + Lang/Jq/Polynomial-regression | 1 + ...bers-Combined-recursive-generator-MRG32k3a | 1 + Lang/Jq/Pseudo-random-numbers-PCG32 | 1 + Lang/Jq/Pseudo-random-numbers-Xorshift-star | 1 + .../Ramer-Douglas-Peucker-line-simplification | 1 + Lang/Jq/Random-sentence-from-book | 1 + ...tta-Code-Rank-languages-by-number-of-users | 1 + Lang/Jq/Set-puzzle | 1 + Lang/Jq/Set-right-adjacent-bits | 1 + Lang/Jq/Sierpinski-pentagon | 1 + Lang/Jq/Sleeping-Beauty-problem | 1 + Lang/Jq/Solve-a-Hidato-puzzle | 1 + Lang/Jq/Solve-a-Holy-Knights-tour | 1 + Lang/Jq/Solve-a-Numbrix-puzzle | 1 + Lang/Jq/Sort-an-outline-at-every-level | 1 + Lang/Jq/Thieles-interpolation-formula | 1 + Lang/Jq/Tic-tac-toe | 1 + Lang/Jq/War-card-game | 1 + Lang/Jq/Wordiff | 1 + Lang/K/Find-common-directory-path | 1 + Lang/K/Monty-Hall-problem | 1 + Lang/Kotlin/00-LANG.txt | 2 +- Lang/Kotlin/Compare-length-of-two-strings | 1 + Lang/Kotlin/Factorial-primes | 1 + Lang/Langur/00-LANG.txt | 4 +- Lang/Langur/Babbage-problem | 1 + Lang/Langur/I-before-E-except-after-C | 1 + Lang/Langur/Safe-addition | 1 + Lang/Langur/String-interpolation-included- | 1 + Lang/Liberty-BASIC/Poker-hand-analyser | 1 + Lang/Lilypond/00-LANG.txt | 10 +- Lang/Locomotive-Basic/00-LANG.txt | 12 +- Lang/Locomotive-Basic/Abelian-sandpile-model | 1 + Lang/Locomotive-Basic/Draw-a-cuboid | 1 + Lang/MACRO-11/Square-but-not-cube | 1 + Lang/Mia/Loops-While | 1 + Lang/Minimal-BASIC/Jensens-Device | 1 + Lang/Minimal-BASIC/Monty-Hall-problem | 1 + Lang/Modula-2/Gray-code | 1 + Lang/Modula-2/Monty-Hall-problem | 1 + Lang/Modula-3/Additive-primes | 1 + Lang/Nascom-BASIC/Damm-algorithm | 1 + Lang/Oberon/100-doors | 1 - Lang/Odin/Quine | 1 + Lang/PHP/Water-collected-between-towers | 1 + Lang/PL-M/Draw-a-cuboid | 1 + Lang/PL-M/Nested-function | 1 + Lang/POV-Ray/Bitmap | 1 + Lang/POV-Ray/Maze-generation | 1 + Lang/Pascal/Count-the-coins | 1 + Lang/PascalABC.NET/00-LANG.txt | 2 +- Lang/PascalABC.NET/15-puzzle-game | 1 + Lang/PascalABC.NET/99-bottles-of-beer | 1 + Lang/PascalABC.NET/A+B | 1 + Lang/PascalABC.NET/Abstract-type | 1 + Lang/PascalABC.NET/Accumulator-factory | 1 + Lang/PascalABC.NET/Ackermann-function | 1 + ...-a-variable-to-a-class-instance-at-runtime | 1 + Lang/PascalABC.NET/Address-of-a-variable | 1 + Lang/PascalABC.NET/Anagrams | 1 + Lang/PascalABC.NET/Anonymous-recursion | 1 + .../Apply-a-callback-to-an-array | 1 + Lang/PascalABC.NET/Arithmetic-Complex | 1 + Lang/PascalABC.NET/Arithmetic-Integer | 1 + Lang/PascalABC.NET/Array-concatenation | 1 + Lang/PascalABC.NET/Arrays | 1 + Lang/PascalABC.NET/Assertions | 1 + Lang/PascalABC.NET/Associative-array-Creation | 1 + .../PascalABC.NET/Associative-array-Iteration | 1 + Lang/PascalABC.NET/Balanced-brackets | 1 + Lang/PascalABC.NET/Binary-digits | 1 + Lang/PascalABC.NET/Binary-search | 1 + Lang/PascalABC.NET/Bitwise-operations | 1 + Lang/PascalABC.NET/Break-OO-privacy | 1 + Lang/PascalABC.NET/CSV-data-manipulation | 1 + Lang/PascalABC.NET/Calculating-the-value-of-e | 1 + Lang/PascalABC.NET/Call-an-object-method | 1 + Lang/PascalABC.NET/Character-codes | 1 + Lang/PascalABC.NET/Classes | 1 + Lang/PascalABC.NET/Closest-pair-problem | 1 + Lang/PascalABC.NET/Collections | 1 + Lang/PascalABC.NET/Command-line-arguments | 1 + Lang/PascalABC.NET/Comments | 1 + Lang/PascalABC.NET/Compare-a-list-of-strings | 1 + .../Compare-length-of-two-strings | 1 + Lang/PascalABC.NET/Compound-data-type | 1 + Lang/PascalABC.NET/Concurrent-computing | 1 + Lang/PascalABC.NET/Conditional-structures | 1 + Lang/PascalABC.NET/Constrained-genericity | 1 + Lang/PascalABC.NET/Copy-a-string | 1 + Lang/PascalABC.NET/Copy-stdin-to-stdout | 1 + Lang/PascalABC.NET/Count-in-factors | 1 + Lang/PascalABC.NET/Count-in-octal | 1 + .../Count-occurrences-of-a-substring | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + .../Create-an-object-at-a-given-address | 1 + Lang/PascalABC.NET/Date-format | 1 + Lang/PascalABC.NET/Day-of-the-week | 1 + .../Define-a-primitive-data-type | 1 + .../Determine-if-a-string-is-numeric | 1 + Lang/PascalABC.NET/Determine-sentence-type | 1 + .../Doubly-linked-list-Definition | 1 + .../Doubly-linked-list-Element-definition | 1 + .../Doubly-linked-list-Element-insertion | 1 + .../Doubly-linked-list-Traversal | 1 + Lang/PascalABC.NET/Dragon-curve | 1 + Lang/PascalABC.NET/Draw-a-pixel | 1 + Lang/PascalABC.NET/Draw-a-rotating-cube | 1 + Lang/PascalABC.NET/Empty-program | 1 + Lang/PascalABC.NET/Enumerations | 1 + Lang/PascalABC.NET/Even-or-odd | 1 + Lang/PascalABC.NET/Exceptions | 1 + .../Extreme-floating-point-values | 1 + Lang/PascalABC.NET/Factorial | 1 + Lang/PascalABC.NET/Factors-of-an-integer | 1 + Lang/PascalABC.NET/File-input-output | 1 + Lang/PascalABC.NET/File-size | 1 + Lang/PascalABC.NET/Filter | 1 + Lang/PascalABC.NET/Find-common-directory-path | 1 + Lang/PascalABC.NET/Find-limit-of-recursion | 1 + Lang/PascalABC.NET/First-class-functions | 1 + Lang/PascalABC.NET/FizzBuzz | 1 + Lang/PascalABC.NET/Flatten-a-list | 1 + Lang/PascalABC.NET/Floyds-triangle | 1 + Lang/PascalABC.NET/Formatted-numeric-output | 1 + Lang/PascalABC.NET/Function-definition | 1 + Lang/PascalABC.NET/General-FizzBuzz | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/PascalABC.NET/Generic-swap | 1 + Lang/PascalABC.NET/Greatest-common-divisor | 1 + Lang/PascalABC.NET/Guess-the-number | 1 + Lang/PascalABC.NET/Hash-from-two-arrays | 1 + Lang/PascalABC.NET/Hello-world-Line-printer | 1 + .../Hello-world-Newline-omission | 1 + Lang/PascalABC.NET/Hello-world-Standard-error | 1 + Lang/PascalABC.NET/Identity-matrix | 1 + Lang/PascalABC.NET/Include-a-file | 1 + Lang/PascalABC.NET/Infinity | 1 + Lang/PascalABC.NET/Inheritance-Multiple | 1 + Lang/PascalABC.NET/Inheritance-Single | 1 + Lang/PascalABC.NET/Input-loop | 1 + Lang/PascalABC.NET/Integer-comparison | 1 + Lang/PascalABC.NET/JSON | 1 + Lang/PascalABC.NET/Jump-anywhere | 1 + Lang/PascalABC.NET/Knuth-shuffle | 1 + Lang/PascalABC.NET/Least-common-multiple | 1 + Lang/PascalABC.NET/List-comprehensions | 1 + Lang/PascalABC.NET/Literals-Floating-point | 1 + Lang/PascalABC.NET/Literals-String | 1 + Lang/PascalABC.NET/Longest-common-subsequence | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/PascalABC.NET/Loops-Break | 1 + Lang/PascalABC.NET/Loops-Continue | 1 + Lang/PascalABC.NET/Loops-Do-while | 1 + Lang/PascalABC.NET/Loops-Downward-for | 1 + Lang/PascalABC.NET/Loops-For | 1 + .../Loops-For-with-a-specified-step | 1 + Lang/PascalABC.NET/Loops-Foreach | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/PascalABC.NET/Loops-N-plus-one-half | 1 + Lang/PascalABC.NET/Loops-Nested | 1 + Lang/PascalABC.NET/Loops-While | 1 + Lang/PascalABC.NET/Loops-With-multiple-ranges | 1 + Lang/PascalABC.NET/Loops-Wrong-ranges | 1 + Lang/PascalABC.NET/Man-or-boy-test | 1 + Lang/PascalABC.NET/Memory-allocation | 1 + Lang/PascalABC.NET/Mouse-position | 1 + Lang/PascalABC.NET/Nested-function | 1 + Lang/PascalABC.NET/Nth | 1 + Lang/PascalABC.NET/Null-object | 1 + Lang/PascalABC.NET/Object-serialization | 1 + Lang/PascalABC.NET/Palindrome-detection | 1 + Lang/PascalABC.NET/Parametric-polymorphism | 1 + Lang/PascalABC.NET/Pick-random-element | 1 + Lang/PascalABC.NET/Pointers-and-references | 1 + Lang/PascalABC.NET/Polymorphic-copy | 1 + Lang/PascalABC.NET/Polymorphism | 1 + Lang/PascalABC.NET/Power-set | 1 + .../PascalABC.NET/Primality-by-trial-division | 1 + Lang/PascalABC.NET/Prime-decomposition | 1 + Lang/PascalABC.NET/Program-name | 1 + Lang/PascalABC.NET/Program-termination | 1 + Lang/PascalABC.NET/Queue-Definition | 1 + Lang/PascalABC.NET/Queue-Usage | 1 + Lang/PascalABC.NET/Quine | 1 + Lang/PascalABC.NET/Quoting-constructs | 1 + Lang/PascalABC.NET/Radical-of-an-integer | 1 + .../Read-a-file-character-by-character-UTF8 | 1 + Lang/PascalABC.NET/Read-a-file-line-by-line | 1 + .../Read-a-specific-line-from-a-file | 1 + Lang/PascalABC.NET/Read-entire-file | 1 + .../Real-constants-and-functions | 1 + Lang/PascalABC.NET/Reflection-List-methods | 1 + Lang/PascalABC.NET/Reflection-List-properties | 1 + Lang/PascalABC.NET/Regular-expressions | 1 + Lang/PascalABC.NET/Remove-duplicate-elements | 1 + Lang/PascalABC.NET/Remove-lines-from-a-file | 1 + Lang/PascalABC.NET/Rename-a-file | 1 + Lang/PascalABC.NET/Repeat | 1 + Lang/PascalABC.NET/Repeat-a-string | 1 + Lang/PascalABC.NET/Return-multiple-values | 1 + Lang/PascalABC.NET/Reverse-a-string | 1 + Lang/PascalABC.NET/Reverse-words-in-a-string | 1 + Lang/PascalABC.NET/Roman-numerals-Decode | 1 + Lang/PascalABC.NET/Roman-numerals-Encode | 1 + .../Rosetta-Code-Rank-languages-by-popularity | 1 + Lang/PascalABC.NET/Rot-13 | 1 + Lang/PascalABC.NET/Scope-modifiers | 1 + .../PascalABC.NET/Send-an-unknown-method-call | 1 + .../Sequence-of-primes-by-trial-division | 1 + Lang/PascalABC.NET/Sieve-of-Eratosthenes | 1 + .../PascalABC.NET/Simple-windowed-application | 1 + .../Singly-linked-list-Element-definition | 1 + .../Singly-linked-list-Element-insertion | 1 + Lang/PascalABC.NET/Sleep | 1 + .../Sort-an-array-of-composite-structures | 1 + Lang/PascalABC.NET/Sort-an-integer-array | 1 + Lang/PascalABC.NET/Sort-three-variables | 1 + .../Sort-using-a-custom-comparator | 1 + .../Sorting-algorithms-Quicksort | 1 + Lang/PascalABC.NET/Special-variables | 1 + Lang/PascalABC.NET/Stack | 1 + Lang/PascalABC.NET/Stack-traces | 1 + Lang/PascalABC.NET/String-append | 1 + Lang/PascalABC.NET/String-case | 1 + Lang/PascalABC.NET/String-concatenation | 1 + .../String-interpolation-included- | 1 + Lang/PascalABC.NET/String-length | 1 + Lang/PascalABC.NET/String-matching | 1 + Lang/PascalABC.NET/String-prepend | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/PascalABC.NET/Strip-block-comments | 1 + .../Strip-comments-from-a-string | 1 + ...odes-and-extended-characters-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/PascalABC.NET/Substitution-cipher | 1 + Lang/PascalABC.NET/Substring | 1 + Lang/PascalABC.NET/Substring-Top-and-tail | 1 + Lang/PascalABC.NET/Sudan-function | 1 + .../PascalABC.NET/Sum-and-product-of-an-array | 1 + Lang/PascalABC.NET/Sum-digits-of-an-integer | 1 + Lang/PascalABC.NET/Sum-multiples-of-3-and-5 | 1 + Lang/PascalABC.NET/Sum-of-a-series | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + Lang/PascalABC.NET/Sum-of-squares | 1 + Lang/PascalABC.NET/Symmetric-difference | 1 + Lang/PascalABC.NET/System-time | 1 + .../Take-notes-on-the-command-line | 1 + Lang/PascalABC.NET/Tau-function | 1 + Lang/PascalABC.NET/Tau-number | 1 + Lang/PascalABC.NET/Temperature-conversion | 1 + .../Terminal-control-Clear-the-screen | 1 + .../Terminal-control-Coloured-text | 1 + .../Terminal-control-Cursor-movement | 1 + .../Terminal-control-Cursor-positioning | 1 + .../PascalABC.NET/Terminal-control-Dimensions | 1 + ...inal-control-Display-an-extended-character | 1 + .../Terminal-control-Hiding-the-cursor | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/PascalABC.NET/Test-a-function | 1 + Lang/PascalABC.NET/Time-a-function | 1 + Lang/PascalABC.NET/Tokenize-a-string | 1 + Lang/PascalABC.NET/Top-rank-per-group | 1 + Lang/PascalABC.NET/Towers-of-Hanoi | 1 + .../PascalABC.NET/Trabb-Pardo-Knuth-algorithm | 1 + ...rate-English-text-using-the-Greek-alphabet | 1 + Lang/PascalABC.NET/Tree-datastructures | 1 + Lang/PascalABC.NET/Tree-traversal | 1 + Lang/PascalABC.NET/Trigonometric-functions | 1 + Lang/PascalABC.NET/Truncate-a-file | 1 + Lang/PascalABC.NET/Twos-complement | 1 + Lang/PascalABC.NET/URL-decoding | 1 + Lang/PascalABC.NET/URL-encoding | 1 + Lang/PascalABC.NET/Undefined-values | 1 + Lang/PascalABC.NET/Unicode-strings | 1 + Lang/PascalABC.NET/Unicode-variable-names | 1 + Lang/PascalABC.NET/User-input-Text | 1 + Lang/PascalABC.NET/Variables | 1 + Lang/PascalABC.NET/Variadic-function | 1 + Lang/PascalABC.NET/Vector | 1 + Lang/PascalABC.NET/Vector-products | 1 + .../Walk-a-directory-Non-recursively | 1 + .../Walk-a-directory-Recursively | 1 + Lang/PascalABC.NET/Window-creation | 1 + Lang/PascalABC.NET/Word-frequency | 1 + Lang/PascalABC.NET/Word-wrap | 1 + Lang/PascalABC.NET/Write-entire-file | 1 + Lang/PascalABC.NET/Write-to-Windows-event-log | 1 + Lang/PascalABC.NET/XML-DOM-serialization | 1 + Lang/PascalABC.NET/XML-Input | 1 + Lang/PascalABC.NET/XML-Output | 1 + Lang/PascalABC.NET/Zero-to-the-zero-power | 1 + Lang/Perl/Search-in-paragraphs-text | 1 + Lang/Prog8/Quine | 1 + Lang/PureBasic/M-bius-function | 1 + Lang/Python/Rhonda-numbers | 1 + Lang/QB64/Fibonacci-n-step-number-sequences | 1 + Lang/QB64/Multiple-regression | 1 + Lang/QB64/Price-fraction | 1 + Lang/QBasic/Display-a-linear-combination | 1 + Lang/QBasic/Fibonacci-n-step-number-sequences | 1 + Lang/QBasic/Jensens-Device | 1 + Lang/QBasic/Nested-templated-data | 1 + .../Ramer-Douglas-Peucker-line-simplification | 1 + Lang/QBasic/Vector | 1 + Lang/Quackery/00-LANG.txt | 2 +- .../Dinesmans-multiple-dwelling-problem | 1 + ...stribution-of-0-digits-in-factorial-series | 1 + Lang/Quackery/Dutch-national-flag-problem | 1 + Lang/Quackery/Flipping-bits-game | 1 + ...m-multiple-of-m-where-digital-sum-equals-m | 1 + Lang/Quackery/Password-generator | 1 + Lang/Quackery/Solve-the-no-connection-puzzle | 1 + Lang/QuickBASIC/Function-definition | 1 + Lang/QuickBASIC/Monty-Hall-problem | 1 + Lang/QuickBASIC/Random-numbers | 1 + Lang/QuickBASIC/Sorting-algorithms-Quicksort | 1 + Lang/R/Arithmetic-derivative | 1 + Lang/R/Compare-length-of-two-strings | 1 + Lang/R/Conjugate-transpose | 1 + Lang/R/Golden-ratio-Convergence | 1 + Lang/REXX/00-LANG.txt | 8 +- Lang/REXX/Eulers-constant-0.5772... | 1 + Lang/Red/00-LANG.txt | 3 + Lang/Refal/Copy-stdin-to-stdout | 1 + Lang/Refal/Damm-algorithm | 1 + Lang/Refal/Determine-sentence-type | 1 + Lang/Refal/Disarium-numbers | 1 + Lang/Refal/Discordian-date | 1 + Lang/Refal/Factors-of-an-integer | 1 + Lang/Refal/Flatten-a-list | 1 + Lang/Refal/General-FizzBuzz | 1 + Lang/Refal/Letter-frequency | 1 + Lang/Refal/McNuggets-problem | 1 + Lang/Refal/Nested-templated-data | 1 + Lang/Refal/One-dimensional-cellular-automata | 1 + Lang/Refal/Palindrome-detection | 1 + Lang/Refal/Population-count | 1 + Lang/Refal/Repeat | 1 + ...racter-string-based-on-change-of-character | 1 + Lang/Refal/Square-but-not-cube | 1 + Lang/Refal/Word-ladder | 1 + Lang/Rockstar/00-LANG.txt | 6 +- Lang/Run-BASIC/Nested-templated-data | 1 + Lang/S-BASIC/Copy-a-string | 1 + Lang/S-BASIC/Factorial | 1 + Lang/S-BASIC/Loops-Break | 1 + Lang/SETL/Brilliant-numbers | 1 + Lang/SETL/Damm-algorithm | 1 + Lang/SETL/General-FizzBuzz | 1 + Lang/SETL/Levenshtein-distance | 1 + Lang/SETL/Luhn-test-of-credit-card-numbers | 1 + Lang/SETL/Monty-Hall-problem | 1 + Lang/SETL/Nested-templated-data | 1 + Lang/SETL/Ordered-words | 1 + Lang/SETL/Pisano-period | 1 + Lang/SETL/Show-ASCII-table | 1 + ...racter-string-based-on-change-of-character | 1 + Lang/SETL/Word-ladder | 1 + Lang/Sed/00-LANG.txt | 2 + ...ing-gaps-between-consecutive-Niven-numbers | 1 + Lang/Sidef/Jaro-Winkler-distance | 1 + ...rs-whose-neighboring-pairs-are-tetraprimes | 1 + Lang/Sidef/Smarandache-Wellin-primes | 1 + Lang/Sidef/Wagstaff-primes | 1 + .../Call-a-foreign-language-function | 1 + Lang/Standard-ML/Pi | 1 + Lang/SuperCollider/00-LANG.txt | 128 +++- Lang/SuperCollider/Semordnilap | 1 - Lang/Swift/Compare-length-of-two-strings | 1 + Lang/Swift/Pseudo-random-numbers-Splitmix64 | 1 + Lang/Transd/Compare-length-of-two-strings | 1 - Lang/True-BASIC/100-prisoners | 1 + Lang/True-BASIC/Multiple-regression | 1 + Lang/True-BASIC/Vector | 1 + Lang/TypeScript/Deal-cards-for-FreeCell | 1 + Lang/UNIX-Shell/Pi | 1 + Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Uiua/00-LANG.txt | 16 +- Lang/Uiua/15-puzzle-solver | 1 + Lang/Uiua/ADFGVX-cipher | 1 + Lang/Uiua/ASCII-art-diagram-converter | 1 + Lang/Uiua/Abbreviations-automatic | 1 + Lang/Uiua/Abelian-sandpile-model | 1 + Lang/Uiua/Align-columns | 1 + Lang/Uiua/Anti-primes | 1 + Lang/Uiua/Arithmetic-geometric-mean | 1 + Lang/Uiua/Array-concatenation | 1 + Lang/Uiua/Array-length | 1 + Lang/Uiua/Ascending-primes | 1 + Lang/Uiua/Averages-Mean-time-of-day | 1 + Lang/Uiua/Barnsley-fern | 1 + Lang/Uiua/Benfords-law | 1 + Lang/Uiua/Bifid-cipher | 1 + Lang/Uiua/Binary-digits | 1 + Lang/Uiua/Bulls-and-cows-Player | 1 + Lang/Uiua/CSV-data-manipulation | 1 + Lang/Uiua/Calkin-Wilf-sequence | 1 + .../Cartesian-product-of-two-or-more-lists | 1 + Lang/Uiua/Combinations | 1 + .../Uiua/Convert-seconds-to-compound-duration | 1 + Lang/Uiua/Conways-Game-of-Life | 1 + .../Uiua/Determine-if-a-string-is-collapsible | 1 + Lang/Uiua/Dutch-national-flag-problem | 1 + Lang/Uiua/Factorial | 1 + Lang/Uiua/Factors-of-an-integer | 1 + Lang/Uiua/Find-the-missing-permutation | 1 + Lang/Uiua/Flatten-a-list | 1 + Lang/Uiua/Flipping-bits-game | 1 + Lang/Uiua/Forest-fire | 1 + Lang/Uiua/Greatest-common-divisor | 1 + Lang/Uiua/Identity-matrix | 1 + Lang/Uiua/Increment-a-numerical-string | 1 + Lang/Uiua/Integer-sequence | 1 + Lang/Uiua/Langtons-ant | 1 + Lang/Uiua/Largest-int-from-concatenated-ints | 1 + Lang/Uiua/Least-common-multiple | 1 + Lang/Uiua/Levenshtein-distance | 1 + Lang/Uiua/List-comprehensions | 1 + Lang/Uiua/Look-and-say-sequence | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Uiua/Luhn-test-of-credit-card-numbers | 1 + Lang/Uiua/Mandelbrot-set | 1 + Lang/Uiua/Matrix-multiplication | 1 + Lang/Uiua/Maze-solving | 1 + Lang/Uiua/McNuggets-problem | 1 + Lang/Uiua/Middle-three-digits | 1 + Lang/Uiua/Motzkin-numbers | 1 + Lang/Uiua/N-queens-problem | 1 + ...-which-are-not-the-sum-of-distinct-squares | 1 + Lang/Uiua/One-dimensional-cellular-automata | 1 + Lang/Uiua/Ordered-words | 1 + Lang/Uiua/Permutations | 1 + Lang/Uiua/Pick-random-element | 1 + Lang/Uiua/RPG-attributes-generator | 1 + Lang/Uiua/Random-numbers | 1 + Lang/Uiua/Run-length-encoding | 1 + Lang/Uiua/Smith-numbers | 1 + Lang/Uiua/Solve-a-Hidato-puzzle | 1 + Lang/Uiua/Solve-a-Numbrix-puzzle | 1 + Lang/Uiua/Sort-disjoint-sublist | 1 + ...racter-string-based-on-change-of-character | 1 + Lang/Uiua/Square-free-integers | 1 + Lang/Uiua/Stem-and-leaf-plot | 1 + Lang/Uiua/String-case | 1 + Lang/Uiua/String-concatenation | 1 + Lang/Uiua/String-interpolation-included- | 1 + Lang/Uiua/String-matching | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Uiua/Sudoku | 1 + Lang/Uiua/Sum-multiples-of-3-and-5 | 1 + Lang/Uiua/Summarize-primes | 1 + Lang/Uiua/Test-a-function | 1 + Lang/Uiua/Truncatable-primes | 1 + ...rnational-Securities-Identification-Number | 1 + Lang/Uiua/Water-collected-between-towers | 1 + Lang/Uiua/Yellowstone-sequence | 1 + Lang/Uiua/Zebra-puzzle | 1 + Lang/Uxntal/Quine | 1 + Lang/Uxntal/Weird-numbers | 1 + Lang/Vim-Script/Hello-world-Graphical | 1 + Lang/Vim-Script/Here-document | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Vim-Script/Loops-For | 1 + Lang/Vim-Script/XML-Input | 1 + Lang/Wren/00-LANG.txt | 2 +- Lang/XBasic/Euler-method | 1 + Lang/XBasic/M-bius-function | 1 + Lang/XBasic/Nim-game | 1 + Lang/XBasic/Sorting-algorithms-Quicksort | 1 + Lang/XPL0/Draw-a-clock | 1 + Lang/XPL0/Poker-hand-analyser | 1 + Lang/YAMLScript/00-LANG.txt | 3 +- Lang/Yabasic/Display-a-linear-combination | 1 + Lang/Yabasic/Kronecker-product | 1 + Lang/Yabasic/Multiple-regression | 1 + Lang/Yabasic/Nested-templated-data | 1 + Lang/Yabasic/Sexy-primes | 1 + Lang/Yabasic/Sorting-algorithms-Counting-sort | 1 + Lang/Yabasic/Sorting-algorithms-Stooge-sort | 1 + Lang/Zig/15-puzzle-game | 1 + Lang/Zig/9-billion-names-of-God-the-integer | 1 + Lang/Zig/A+B | 1 + Lang/Zig/Determine-if-a-string-is-numeric | 1 + Lang/Zig/Egyptian-division | 1 + Lang/Zig/Integer-sequence | 1 + Lang/Zig/Monty-Hall-problem | 1 + Lang/Zig/Solve-the-no-connection-puzzle | 1 + Task/100-doors/APL/100-doors-2.apl | 4 +- Task/100-doors/APL/100-doors-3.apl | 1 + Task/100-doors/Langur/100-doors-1.langur | 10 +- Task/100-doors/Langur/100-doors-2.langur | 2 +- Task/100-doors/Langur/100-doors-3.langur | 2 +- Task/100-doors/Oberon/100-doors.oberon | 27 - Task/100-doors/V-(Vlang)/100-doors-2.v | 9 +- Task/100-doors/V-(Vlang)/100-doors-3.v | 5 + .../Ecstasy/100-prisoners.ecstasy | 49 ++ .../True-BASIC/100-prisoners.basic | 40 ++ .../PascalABC.NET/15-puzzle-game.pas | 178 ++++++ Task/15-puzzle-game/Zig/15-puzzle-game.zig | 91 +++ .../Dart/15-puzzle-solver.dart | 78 +++ .../Uiua/15-puzzle-solver.uiua | 47 ++ Task/2048/Jq/2048.jq | 127 ++++ Task/2048/Wren/2048.wren | 7 - Task/24-game/Frink/24-game.frink | 15 + Task/24-game/FutureBasic/24-game.basic | 310 ++++++++++ Task/24-game/Jq/24-game.jq | 90 +++ ...zzle.v => 4-rings-or-4-squares-puzzle-1.v} | 0 .../V-(Vlang)/4-rings-or-4-squares-puzzle-2.v | 38 ++ .../Zig/4-rings-or-4-squares-puzzle-6.zig | 50 ++ .../9-billion-names-of-god-the-integer-1.zig | 63 ++ .../9-billion-names-of-god-the-integer-2.zig | 35 ++ .../8th/99-bottles-of-beer-1.8th | 26 + .../8th/99-bottles-of-beer-2.8th | 12 + .../8th/99-bottles-of-beer.8th | 20 - ...s-of-beer.oxy => 99-bottles-of-beer-1.oxy} | 0 .../Oxygene/99-bottles-of-beer-2.oxy | 21 + .../PascalABC.NET/99-bottles-of-beer-1.pas | 10 + .../PascalABC.NET/99-bottles-of-beer-2.pas | 10 + Task/A+B/PascalABC.NET/a+b.pas | 3 + Task/A+B/Zig/a+b.zig | 25 + Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua | 11 + .../ascii-art-diagram-converter.basic | 93 +++ .../Uiua/ascii-art-diagram-converter.uiua | 26 + .../Emacs-Lisp/abbreviations-automatic.l | 36 ++ .../Uiua/abbreviations-automatic.uiua | 17 + .../abelian-sandpile-model-identity.easy | 60 ++ .../Ada/abelian-sandpile-model.ada | 67 +++ .../EasyLang/abelian-sandpile-model.easy | 35 ++ .../abelian-sandpile-model.basic | 27 + .../Uiua/abelian-sandpile-model.uiua | 10 + Task/Abstract-type/11l/abstract-type.11l | 4 +- .../PascalABC.NET/abstract-type-1.pas | 20 + .../PascalABC.NET/abstract-type-2.pas | 22 + .../PascalABC.NET/accumulator-factory.pas | 12 + .../Achilles-numbers/Ada/achilles-numbers.ada | 205 +++++++ .../PascalABC.NET/ackermann-function.pas | 16 + ...ariable-to-a-class-instance-at-runtime.cpp | 34 ++ ...ariable-to-a-class-instance-at-runtime.pas | 19 + .../ALGOL-68/additive-primes.alg | 3 +- .../C-sharp/additive-primes.cs | 86 +++ .../Langur/additive-primes.langur | 22 +- .../Modula-3/additive-primes.mod3 | 44 ++ .../PascalABC.NET/address-of-a-variable.pas | 6 + Task/Align-columns/Uiua/align-columns.uiua | 17 + .../00-TASK.txt | 3 + Task/Amb/Langur/amb.langur | 12 +- Task/Anagrams/Emacs-Lisp/anagrams-1.l | 87 +++ Task/Anagrams/Emacs-Lisp/anagrams-2.l | 74 +++ Task/Anagrams/PascalABC.NET/anagrams.pas | 7 + .../PascalABC.NET/anonymous-recursion-1.pas | 13 + .../PascalABC.NET/anonymous-recursion-2.pas | 13 + Task/Anti-primes/Langur/anti-primes.langur | 22 +- Task/Anti-primes/Uiua/anti-primes.uiua | 8 + .../apply-a-callback-to-an-array.langur | 2 +- .../apply-a-callback-to-an-array.pas | 5 + .../EasyLang/approximate-equality.easy | 20 + ...bitrary-precision-integers-included-.basic | 64 ++ ...itrary-precision-integers-included-.langur | 10 +- .../Java/arena-storage-pool.java | 19 + .../EasyLang/arithmetic-complex.easy | 19 + .../PascalABC.NET/arithmetic-complex.pas | 14 + .../EMal/arithmetic-integer.emal | 1 - .../PascalABC.NET/arithmetic-integer.pas | 10 + .../R/arithmetic-derivative.r | 31 + ...arithmetic-geometric-mean-calculate-pi.ada | 34 ++ .../Uiua/arithmetic-geometric-mean.uiua | 3 + .../Langur/array-concatenation.langur | 8 +- .../PascalABC.NET/array-concatenation.pas | 5 + .../Uiua/array-concatenation.uiua | 1 + .../{array-length.pas => array-length-1.pas} | 0 .../PascalABC.NET/array-length-2.pas | 4 + Task/Array-length/Uiua/array-length.uiua | 1 + Task/Arrays/Ada/arrays.ada | 11 +- Task/Arrays/Langur/arrays.langur | 28 +- Task/Arrays/PascalABC.NET/arrays.pas | 19 + .../Ascending-primes/Ada/ascending-primes.ada | 62 ++ .../Uiua/ascending-primes.uiua | 2 + Task/Assertions/Ecstasy/assertions.ecstasy | 6 + Task/Assertions/PascalABC.NET/assertions.pas | 5 + .../Langur/associative-array-creation.langur | 14 +- .../associative-array-creation.pas | 7 + .../associative-array-iteration.pas | 11 + .../Langur/averages-arithmetic-mean.langur | 4 +- .../Uiua/averages-mean-time-of-day.uiua | 24 + .../Jq/averages-simple-moving-average.jq | 30 + .../b-zier-curves-intersections-1.basic | 162 +++++ .../b-zier-curves-intersections-2.basic | 215 +++++++ .../Babbage-problem/EMal/babbage-problem.emal | 9 + .../Langur/babbage-problem.langur | 6 + .../PascalABC.NET/balanced-brackets.pas | 29 + Task/Barnsley-fern/Uiua/barnsley-fern.uiua | 11 + Task/Benfords-law/Uiua/benfords-law.uiua | 4 + Task/Bifid-cipher/EMal/bifid-cipher.emal | 82 +++ Task/Bifid-cipher/Uiua/bifid-cipher-1.uiua | 9 + Task/Bifid-cipher/Uiua/bifid-cipher-2.uiua | 9 + .../Free-Pascal-Lazarus/bin-given-limits.pas | 56 ++ .../PascalABC.NET/binary-digits.pas | 4 + Task/Binary-digits/Uiua/binary-digits.uiua | 2 + .../Binary-search/Chapel/binary-search.chapel | 10 +- .../PascalABC.NET/binary-search.pas | 61 ++ Task/Biorhythms/FutureBasic/biorhythms.basic | 110 ++++ .../C++/bitcoin-address-validation.cpp | 88 +++ ...java => bitcoin-address-validation-1.java} | 0 .../Java/bitcoin-address-validation-2.java | 71 +++ .../C++/bitcoin-public-point-to-address.cpp | 103 ++++ .../Java/bitcoin-public-point-to-address.java | 99 ++++ .../Rust/bitcoin-public-point-to-address.rust | 2 +- .../11l/bitmap-b-zier-curves-cubic.11l | 11 +- .../11l/bitmap-bresenhams-line-algorithm.11l | 11 +- .../11l/bitmap-midpoint-circle-algorithm.11l | 11 +- .../11l/bitmap-read-a-ppm-file.11l | 11 +- .../11l/bitmap-write-a-ppm-file.11l | 11 +- .../Ada/bitmap-write-a-ppm-file.ada | 3 + Task/Bitmap/11l/bitmap.11l | 11 +- Task/Bitmap/POV-Ray/bitmap.povray | 74 +++ .../Jq/bitwise-operations.jq | 32 + .../PascalABC.NET/bitwise-operations.pas | 9 + .../Common-Lisp/blum-integer.lisp | 47 ++ .../Langur/box-the-compass.langur | 10 +- Task/Brace-expansion/Ada/brace-expansion.ada | 58 ++ .../PascalABC.NET/break-oo-privacy.pas | 15 + .../FutureBasic/brilliant-numbers.basic | 70 +++ .../SETL/brilliant-numbers.setl | 65 ++ .../Ada/bulls-and-cows-player.ada | 2 +- .../Uiua/bulls-and-cows-player.uiua | 18 + Task/CRC-32/Jq/crc-32-1.jq | 2 + Task/CRC-32/Jq/crc-32-2.jq | 34 ++ .../PascalABC.NET/csv-data-manipulation.pas | 9 + .../Uiua/csv-data-manipulation.uiua | 11 + Task/CUSIP/Langur/cusip-1.langur | 26 +- Task/CUSIP/Langur/cusip-2.langur | 36 +- Task/Caesar-cipher/Elm/caesar-cipher.elm | 88 +++ .../Caesar-cipher/Langur/caesar-cipher.langur | 14 +- .../COBOL/calculating-the-value-of-e.cobol | 36 +- .../Langur/calculating-the-value-of-e.langur | 19 +- .../calculating-the-value-of-e.pas | 19 + .../Uiua/calkin-wilf-sequence.uiua | 28 + .../call-a-foreign-language-function.ml | 6 + .../Langur/call-a-function-1.langur | 3 +- .../Langur/call-a-function-2.langur | 3 +- .../Langur/call-a-function-3.langur | 3 +- .../Langur/call-a-function-4.langur | 5 +- .../Langur/call-a-function-5.langur | 4 +- .../Langur/call-a-function-6.langur | 8 +- .../Langur/call-a-function-7.langur | 4 - .../PascalABC.NET/call-an-object-method.pas | 16 + ...tesian-product-of-two-or-more-lists.langur | 16 +- ...artesian-product-of-two-or-more-lists.uiua | 9 + .../Langur/catalan-numbers.langur | 10 +- .../C++/catmull-clark-subdivision-surface.cpp | 261 ++++++++ .../catmull-clark-subdivision-surface.java | 257 ++++++++ .../Langur/character-codes.langur | 20 +- .../PascalABC.NET/character-codes.pas | 6 + .../check-output-device-is-a-terminal.basic | 17 + .../Langur/check-that-file-exists.langur | 16 +- .../11l/cheryls-birthday-1.11l | 7 +- ...les-of-given-radius-through-two-points.11l | 9 +- Task/Classes/PascalABC.NET/classes.pas | 16 + .../PascalABC.NET/closest-pair-problem.pas | 24 + .../closures-value-capture.pas | 26 + ...capture.go => closures-value-capture-1.go} | 0 .../Go/closures-value-capture-2.go | 14 + .../Collections/PascalABC.NET/collections.pas | 25 + Task/Color-wheel/Ada/color-wheel.ada | 89 +++ .../Ada/combinations-and-permutations.ada | 69 +++ Task/Combinations/EasyLang/combinations.easy | 14 +- .../FutureBasic/combinations.basic | 16 + Task/Combinations/J/combinations-10.j | 1 + Task/Combinations/J/combinations-6.j | 8 +- Task/Combinations/J/combinations-7.j | 8 +- Task/Combinations/J/combinations-8.j | 1 + Task/Combinations/J/combinations-9.j | 1 + Task/Combinations/Uiua/combinations.uiua | 10 + .../PascalABC.NET/command-line-arguments.pas | 4 + Task/Comments/FutureBasic/comments.basic | 1 - Task/Comments/PascalABC.NET/comments.pas | 7 + .../compare-a-list-of-strings.pas | 12 + .../compare-length-of-two-strings.l | 7 + .../compare-length-of-two-strings.kotlin | 16 + .../compare-length-of-two-strings.pas | 10 + .../R/compare-length-of-two-strings.r | 13 + .../Swift/compare-length-of-two-strings.swift | 4 + .../compare-length-of-two-strings.transd | 11 - Task/Compiler-AST-interpreter/00-TASK.txt | 4 +- Task/Compiler-code-generator/00-TASK.txt | 262 +++++++- Task/Compiler-lexical-analyzer/00-TASK.txt | 2 - Task/Compiler-syntax-analyzer/00-TASK.txt | 4 +- .../00-TASK.txt | 10 +- .../compiler-virtual-machine-interpreter.cpp | 190 ++++++ .../compiler-virtual-machine-interpreter.java | 173 ++++++ .../PascalABC.NET/compound-data-type.pas | 16 + .../PascalABC.NET/concurrent-computing.pas | 8 + .../Langur/conditional-structures-1.langur | 8 +- .../Langur/conditional-structures-2.langur | 2 +- .../Langur/conditional-structures-3.langur | 2 +- .../Langur/conditional-structures-4.langur | 18 +- .../Langur/conditional-structures-5.langur | 2 +- .../Langur/conditional-structures-6.langur | 4 +- .../Langur/conditional-structures-7.langur | 4 +- .../PascalABC.NET/conditional-structures.pas | 28 + .../R/conjugate-transpose.r | 69 +++ .../FreeBASIC/constrained-genericity.basic | 63 ++ .../PascalABC.NET/constrained-genericity.pas | 23 + ...ithmetic-construct-from-rational-number.jq | 57 ++ .../convert-decimal-number-to-rational.11l | 9 +- ...onvert-seconds-to-compound-duration.langur | 22 +- .../convert-seconds-to-compound-duration.uiua | 9 + .../Chapel/conways-game-of-life.chapel | 128 ++-- .../Uiua/conways-game-of-life.uiua | 4 + .../PascalABC.NET/copy-a-string.pas | 4 + .../Copy-a-string/S-BASIC/copy-a-string.basic | 23 + .../C/copy-stdin-to-stdout.c | 6 +- .../FutureBasic/copy-stdin-to-stdout.basic | 13 + ...tdout.java => copy-stdin-to-stdout-1.java} | 0 .../Java/copy-stdin-to-stdout-2.java | 5 + .../PascalABC.NET/copy-stdin-to-stdout.pas | 2 + .../Refal/copy-stdin-to-stdout.refal | 6 + .../PascalABC.NET/count-in-factors.pas | 25 + .../Langur/count-in-octal.langur | 6 +- .../PascalABC.NET/count-in-octal.pas | 3 + .../count-occurrences-of-a-substring.alg | 11 +- .../count-occurrences-of-a-substring.l | 23 +- .../count-occurrences-of-a-substring.langur | 4 +- .../count-occurrences-of-a-substring.pas | 6 + ...nt-the-coins.ada => count-the-coins-1.ada} | 0 .../Count-the-coins/Ada/count-the-coins-2.ada | 26 + .../Pascal/count-the-coins.pas | 24 + Task/Create-a-file/Seed7/create-a-file.seed7 | 4 +- ...ate-a-two-dimensional-array-at-runtime.pas | 8 + .../create-an-object-at-a-given-address.pas | 12 + .../C-sharp/cyclops-numbers.cs | 191 ++++++ .../ANSI-BASIC/damm-algorithm.basic | 28 + .../{BASIC => GW-BASIC}/damm-algorithm.basic | 0 .../Nascom-BASIC/damm-algorithm.basic | 23 + .../Damm-algorithm/Refal/damm-algorithm.refal | 38 ++ Task/Damm-algorithm/SETL/damm-algorithm.setl | 26 + Task/Date-format/Langur/date-format-1.langur | 7 +- Task/Date-format/Langur/date-format-2.langur | 5 +- Task/Date-format/Langur/date-format-3.langur | 2 - .../Date-format/PascalABC.NET/date-format.pas | 5 + .../Emacs-Lisp/date-manipulation-1.l | 40 ++ .../Emacs-Lisp/date-manipulation-2.l | 41 ++ .../Langur/date-manipulation.langur | 40 +- .../PascalABC.NET/day-of-the-week.pas | 5 + .../11l/de-bruijn-sequences.11l | 2 +- .../TypeScript/deal-cards-for-freecell.ts | 133 +++++ Task/Death-Star/11l/death-star.11l | 8 +- .../Langur/deceptive-numbers.langur | 20 +- Task/Deconvolution-1D/Jq/deconvolution-1d.jq | 22 + .../define-a-primitive-data-type.pas | 27 + .../Langur/detect-division-by-zero.langur | 8 +- .../determine-if-a-string-is-collapsible.uiua | 13 + .../determine-if-a-string-is-numeric-1.l | 12 + .../determine-if-a-string-is-numeric-2.l | 17 + .../determine-if-a-string-is-numeric.pas | 11 + ...> determine-if-a-string-is-numeric-1.rust} | 0 .../determine-if-a-string-is-numeric-2.rust | 34 ++ .../Zig/determine-if-a-string-is-numeric.zig | 32 + .../Emacs-Lisp/determine-sentence-type.l | 28 + .../FutureBasic/determine-sentence-type.basic | 16 + .../PascalABC.NET/determine-sentence-type.pas | 18 + .../Refal/determine-sentence-type.refal | 17 + .../11l/dijkstras-algorithm.11l | 10 +- ...nesmans-multiple-dwelling-problem.quackery | 38 ++ .../Refal/disarium-numbers.refal | 32 + .../Refal/discordian-date.refal | 62 ++ .../APL/display-a-linear-combination.apl | 11 + .../display-a-linear-combination.basic | 22 + .../display-a-linear-combination.basic | 38 ++ .../display-a-linear-combination.cowgol | 60 ++ .../Draco/display-a-linear-combination.draco | 44 ++ .../display-a-linear-combination.basic | 24 + .../QBasic/display-a-linear-combination.basic | 37 ++ .../display-a-linear-combination.basic | 38 ++ .../display-an-outline-as-a-nested-table.jq | 135 +++++ ...n-of-0-digits-in-factorial-series.quackery | 29 + .../doubly-linked-list-definition.pas | 75 +++ .../doubly-linked-list-element-definition.pas | 4 + .../doubly-linked-list-element-insertion.pas | 33 ++ .../doubly-linked-list-traversal.pas | 9 + .../PascalABC.NET/dragon-curve.pas | 34 ++ Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 | 48 ++ Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg | 58 ++ Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq | 27 + .../Locomotive-Basic/draw-a-cuboid.basic | 6 + Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm | 81 +++ .../PascalABC.NET/draw-a-pixel.pas | 6 + .../PascalABC.NET/draw-a-rotating-cube.pas | 6 + ...w-a-sphere.basic => draw-a-sphere-1.basic} | 0 .../Locomotive-Basic/draw-a-sphere-2.basic | 32 + .../dutch-national-flag-problem.quackery | 16 + .../Uiua/dutch-national-flag-problem.uiua | 3 + Task/Eertree/11l/eertree.11l | 2 +- .../Zig/egyptian-division.zig | 52 ++ .../PascalABC.NET/empty-program.pas | 1 + .../Jq/entropy-narcissist.jq | 11 + .../PascalABC.NET/enumerations.pas | 6 + .../Langur/environment-variables-1.langur | 3 - ...-2.langur => environment-variables.langur} | 0 .../Esthetic-numbers/11l/esthetic-numbers.11l | 2 +- Task/Euler-method/XBasic/euler-method.basic | 43 ++ .../ALGOL-W/eulers-constant-0.5772....alg | 89 +++ .../Ada/eulers-constant-0.5772....ada | 47 ++ .../REXX/eulers-constant-0.5772....rexx | 272 +++++++++ .../Even-or-odd/PascalABC.NET/even-or-odd.pas | 14 + ...n-exception-thrown-in-a-nested-call.langur | 20 +- Task/Exceptions/Langur/exceptions-1.langur | 4 +- Task/Exceptions/Langur/exceptions-3.langur | 6 +- .../Exceptions/PascalABC.NET/exceptions-1.pas | 1 + .../Exceptions/PascalABC.NET/exceptions-2.pas | 1 + .../Exceptions/PascalABC.NET/exceptions-3.pas | 6 + .../FreeBASIC/execute-computer-zero.basic | 120 ++++ Task/Execute-HQ9+/11l/execute-hq9+.11l | 2 +- .../FreeBASIC/execute-snusp.basic | 77 +++ .../11l/execute-a-markov-algorithm.11l | 9 +- .../execute-a-markov-algorithm.basic | 139 +++++ .../Seed7/execute-a-system-command.seed7 | 2 +- .../Langur/extend-your-language-2.langur | 7 - ...e-1.langur => extend-your-language.langur} | 2 +- .../extreme-floating-point-values.pas | 14 + Task/FTP/Ada/ftp.ada | 57 ++ ...-indexing-permutations-of-a-collection.cpp | 138 +++++ ...indexing-permutations-of-a-collection.java | 2 +- .../Common-Lisp/factorial-primes.lisp | 27 + Task/Factorial-primes/Go/factorial-primes.go | 59 ++ .../Kotlin/factorial-primes.kotlin | 43 ++ Task/Factorial/Langur/factorial-1.langur | 4 +- Task/Factorial/Langur/factorial-2.langur | 4 +- Task/Factorial/Langur/factorial-3.langur | 12 +- Task/Factorial/Langur/factorial-4.langur | 4 +- Task/Factorial/PascalABC.NET/factorial.pas | 19 + Task/Factorial/S-BASIC/factorial-1.basic | 13 + Task/Factorial/S-BASIC/factorial-2.basic | 7 + Task/Factorial/Uiua/factorial.uiua | 1 + .../Jq/factors-of-a-mersenne-number.jq | 61 ++ .../PascalABC.NET/factors-of-an-integer.pas | 16 + .../Refal/factors-of-an-integer.refal | 13 + .../Uiua/factors-of-an-integer.uiua | 2 + .../Langur/farey-sequence.langur | 24 +- ...=> feigenbaum-constant-calculation-1.rexx} | 0 .../feigenbaum-constant-calculation-2.rexx | 63 ++ .../Langur/fermat-numbers.langur | 33 +- .../fibonacci-n-step-number-sequences.basic | 34 ++ .../fibonacci-n-step-number-sequences.qb64 | 37 ++ .../fibonacci-n-step-number-sequences.basic | 35 ++ .../Haskell/fibonacci-sequence-15.hs | 47 +- .../Haskell/fibonacci-sequence-16.hs | 67 ++- .../Haskell/fibonacci-sequence-17.hs | 37 +- .../Haskell/fibonacci-sequence-18.hs | 3 +- .../Haskell/fibonacci-sequence-19.hs | 2 +- .../Haskell/fibonacci-sequence-20.hs | 1 + .../Langur/fibonacci-sequence.langur | 4 +- .../PARI-GP/fibonacci-sequence-14.parigp | 2 +- .../PARI-GP/fibonacci-sequence-15.parigp | 2 +- .../PARI-GP/fibonacci-sequence-16.parigp | 8 +- .../PARI-GP/fibonacci-sequence-17.parigp | 10 +- .../PARI-GP/fibonacci-sequence-18.parigp | 8 +- .../PARI-GP/fibonacci-sequence-19.parigp | 1 + .../PL-0/fibonacci-sequence.pl0 | 2 +- .../FutureBasic/file-input-output.basic | 52 +- .../PascalABC.NET/file-input-output.pas | 4 + .../Jq/file-size-distribution.jq | 15 + Task/File-size/PascalABC.NET/file-size.pas | 6 + Task/Filter/Langur/filter.langur | 6 +- Task/Filter/PascalABC.NET/filter.pas | 5 + ...d-chess960-starting-position-identifier.jq | 82 +++ .../K/find-common-directory-path.k | 6 + .../find-common-directory-path.pas | 21 + .../Jq/find-duplicate-files.jq | 9 + .../find-if-a-point-is-within-a-triangle.11l | 9 +- .../PascalABC.NET/find-limit-of-recursion.pas | 9 + .../find-the-intersection-of-two-lines.alg | 33 ++ .../find-the-intersection-of-two-lines-4.py | 19 + .../Uiua/find-the-missing-permutation.uiua | 2 + .../PascalABC.NET/first-class-functions.pas | 15 + ...square-in-base-n-with-n-unique-digits.uiua | 27 +- Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp | 33 +- Task/FizzBuzz/Common-Lisp/fizzbuzz-9.lisp | 20 + Task/FizzBuzz/Langur/fizzbuzz-1.langur | 3 - Task/FizzBuzz/Langur/fizzbuzz-2.langur | 3 - Task/FizzBuzz/Langur/fizzbuzz.langur | 3 + Task/FizzBuzz/PascalABC.NET/fizzbuzz.pas | 10 + Task/FizzBuzz/Q/fizzbuzz-1.q | 2 +- Task/FizzBuzz/Q/fizzbuzz-2.q | 2 +- Task/FizzBuzz/Q/fizzbuzz-3.q | 27 +- Task/FizzBuzz/Uiua/fizzbuzz.uiua | 2 +- .../{flatten-a-list.l => flatten-a-list-1.l} | 0 .../Emacs-Lisp/flatten-a-list-2.l | 1 + .../PascalABC.NET/flatten-a-list.pas | 16 + .../Flatten-a-list/Refal/flatten-a-list.refal | 10 + Task/Flatten-a-list/Uiua/flatten-a-list.uiua | 1 + .../Quackery/flipping-bits-game.quackery | 60 ++ .../Uiua/flipping-bits-game.uiua | 19 + .../Ada/flow-control-structures-2.ada | 4 +- .../Ada/flow-control-structures-3.ada | 15 +- .../Ada/flow-control-structures-4.ada | 8 + .../Ada/flow-control-structures-5.ada | 7 + .../FutureBasic/floyds-triangle.basic | 18 + .../PascalABC.NET/floyds-triangle.pas | 19 + .../Floyds-triangle/Uiua/floyds-triangle.uiua | 26 +- Task/Forest-fire/Uiua/forest-fire.uiua | 9 + .../ANSI-BASIC/formatted-numeric-output.basic | 12 + .../formatted-numeric-output.pas | 4 + Task/Fractal-tree/11l/fractal-tree.11l | 2 +- .../Jq/french-republican-calendar.jq | 149 +++++ .../ANSI-BASIC/function-definition.basic | 13 + .../Chapel/function-definition-1.chapel | 4 + .../Chapel/function-definition-2.chapel | 4 + .../Langur/function-definition-1.langur | 3 +- .../Langur/function-definition-2.langur | 3 +- .../Langur/function-definition-3.langur | 3 +- .../Langur/function-definition-4.langur | 2 - .../Langur/function-definition-5.langur | 1 - .../PascalABC.NET/function-definition.pas | 1 + .../function-definition.basic | 0 .../FutureBasic/function-prototype.basic | 3 + .../Gamma-function/REXX/gamma-function-3.rexx | 517 ++++++++++++++++ .../PascalABC.NET/general-fizzbuzz.pas | 14 + .../Refal/general-fizzbuzz.refal | 54 ++ .../SETL/general-fizzbuzz.setl | 9 + .../generate-lower-case-ascii-alphabet.pas | 5 + .../Jq/generate-random-chess-position.jq | 94 +++ Task/Generic-swap/Langur/generic-swap.langur | 10 +- .../PascalABC.NET/generic-swap.pas | 10 + Task/Giuga-numbers/Jq/giuga-numbers.jq | 24 + Task/Go-Fish/FutureBasic/go-fish.basic | 559 ++++++++++++++++++ .../R/golden-ratio-convergence.r | 8 + Task/Graph-colouring/Jq/graph-colouring.jq | 100 ++++ Task/Gray-code/FreeBASIC/gray-code.basic | 8 - .../{BASIC => GW-BASIC}/gray-code.basic | 0 Task/Gray-code/Liberty-BASIC/gray-code.basic | 1 - Task/Gray-code/Modula-2/gray-code.mod2 | 57 ++ Task/Grayscale-image/11l/grayscale-image.11l | 11 +- .../PascalABC.NET/greatest-common-divisor.pas | 18 + .../greatest-common-divisor.uiua} | 0 .../EasyLang/greatest-subsequential-sum.easy | 23 + ...uess-the-number-with-feedback-player-.easy | 21 + .../Langur/guess-the-number.langur | 8 +- .../PascalABC.NET/guess-the-number.pas | 13 + .../EasyLang/halt-and-catch-fire.easy | 2 + .../EasyLang/hamming-numbers.easy | 27 + .../Bruijn/harmonic-series.bruijn | 16 + .../Langur/hash-from-two-arrays-1.langur | 2 +- .../Langur/hash-from-two-arrays-2.langur | 9 +- .../PascalABC.NET/hash-from-two-arrays.pas | 6 + .../hello-world-graphical.ahk | 0 .../Vim-Script/hello-world-graphical-1.vim | 1 + .../Vim-Script/hello-world-graphical-2.vim | 1 + .../hello-world-line-printer.pas | 12 + .../hello-world-newline-omission.pas | 2 + .../hello-world-standard-error.pas | 2 + ...-world-text.pas => hello-world-text-1.pas} | 0 .../PascalABC.NET/hello-world-text-2.pas | 4 + .../PascalABC.NET/hello-world-text-3.pas | 2 + .../Langur/here-document-1.langur | 2 +- .../Langur/here-document-2.langur | 2 +- .../Langur/here-document-3.langur | 2 +- .../Langur/here-document-4.langur | 2 +- .../Vim-Script/here-document-1.vim | 5 + .../Vim-Script/here-document-2.vim | 6 + Task/Hex-words/Ada/hex-words.ada | 149 +++++ .../hofstadter-figure-figure-sequences.easy | 47 ++ Task/Honeycombs/FutureBasic/honeycombs.basic | 115 ++++ Task/Huffman-coding/11l/huffman-coding.11l | 9 +- Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c | 129 ++++ .../Langur/i-before-e-except-after-c.langur | 24 + Task/IBAN/EasyLang/iban.easy | 63 ++ .../Langur/isbn13-check-digit.langur | 18 +- .../Standard-ML/isbn13-check-digit-1.ml | 22 + ...check-digit.ml => isbn13-check-digit-2.ml} | 2 +- .../Kotlin/identity-matrix.kotlin | 17 +- .../PascalABC.NET/identity-matrix.pas | 5 + .../Identity-matrix/Uiua/identity-matrix.uiua | 2 + ...haracters-that-can-be-used-for-symbols.ada | 12 + ...aracters-that-can-be-used-for-symbols.wren | 1 + ...a-software-engineer-get-me-out-of-here.cpp | 236 ++++++++ ...-software-engineer-get-me-out-of-here.java | 211 +++++++ .../FreeBASIC/imaginary-base-numbers.basic | 168 ++++++ .../PascalABC.NET/include-a-file-1.pas | 5 + .../PascalABC.NET/include-a-file-2.pas | 1 + ...ps-between-consecutive-niven-numbers.sidef | 12 + .../Uiua/increment-a-numerical-string.uiua | 2 + Task/Infinity/PascalABC.NET/infinity.pas | 2 + .../PascalABC.NET/inheritance-multiple.pas | 19 + .../PascalABC.NET/inheritance-single.pas | 6 + Task/Input-loop/PascalABC.NET/input-loop.pas | 6 + .../PascalABC.NET/integer-comparison.pas | 8 + .../Kotlin/integer-sequence.kotlin | 17 +- ...er-sequence.pas => integer-sequence-1.pas} | 0 .../PascalABC.NET/integer-sequence-2.pas | 1 + .../Uiua/integer-sequence.uiua | 1 + .../Integer-sequence/Zig/integer-sequence.zig | 9 + Task/Introspection/Jq/introspection.jq | 23 + Task/Inverted-index/Ada/inverted-index-7.ada | 4 +- .../EasyLang/iterated-digits-squaring.easy | 38 ++ Task/JSON/PascalABC.NET/json.pas | 20 + .../Sidef/jaro-winkler-distance.sidef | 26 + .../Asymptote/jensens-device.asymptote | 5 + .../BASIC256/jensens-device.basic | 6 +- .../Chipmunk-Basic/jensens-device.basic | 11 + Task/Jensens-Device/Dart/jensens-device.dart | 14 + .../GW-BASIC/jensens-device.basic | 11 + .../Gambas/jensens-device.gambas | 17 + .../Minimal-BASIC/jensens-device.basic | 12 + .../QBasic/jensens-device.basic | 12 + .../Yabasic/jensens-device.basic | 5 +- Task/JortSort/EasyLang/jortsort.easy | 16 + .../Josephus-problem/Ada/josephus-problem.ada | 16 +- .../PascalABC.NET/jump-anywhere.pas | 15 + Task/Knights-tour/Jq/knights-tour.jq | 50 ++ .../PascalABC.NET/knuth-shuffle.pas | 11 + Task/Kosaraju/11l/kosaraju.11l | 4 +- .../kronecker-product-based-fractals.easy | 38 ++ .../BASIC256/kronecker-product.basic | 42 ++ .../EasyLang/kronecker-product.easy | 15 + .../Yabasic/kronecker-product.basic | 42 ++ Task/Langtons-ant/Uiua/langtons-ant.uiua | 14 + .../largest-int-from-concatenated-ints.easy | 23 + .../largest-int-from-concatenated-ints.uiua | 2 + ...largest-number-divisible-by-its-digits.ada | 48 ++ ...gest-number-divisible-by-its-digits-1.cpp} | 0 ...rgest-number-divisible-by-its-digits-2.cpp | 44 ++ ...est-number-divisible-by-its-digits-1.java} | 0 ...gest-number-divisible-by-its-digits-2.java | 56 ++ .../EasyLang/last-letter-first-letter.easy | 43 ++ .../11l/latin-squares-in-reduced-form.11l | 4 +- .../PascalABC.NET/least-common-multiple.pas | 12 + .../Standard-ML/least-common-multiple-1.ml | 4 + ...multiple.ml => least-common-multiple-2.ml} | 0 .../Uiua/least-common-multiple.uiua | 4 + .../Emacs-Lisp/letter-frequency.l | 23 +- .../Langur/letter-frequency.langur | 10 +- .../Refal/letter-frequency.refal | 48 ++ .../Jq/levenshtein-distance-alignment.jq | 44 ++ .../JavaScript/levenshtein-distance-2.js | 162 ++--- .../SETL/levenshtein-distance.setl | 26 + .../Uiua/levenshtein-distance.uiua | 15 + .../PascalABC.NET/list-comprehensions.pas | 2 + .../Uiua/list-comprehensions.uiua | 3 + .../PascalABC.NET/literals-floating-point.pas | 3 + .../PascalABC.NET/literals-string.pas | 4 + .../Langur/logical-operations.langur | 46 +- .../EasyLang/longest-common-subsequence.easy | 2 +- .../longest-common-subsequence.pas | 30 + .../Langur/longest-common-substring.langur | 22 +- .../longest-increasing-subsequence.easy | 37 ++ .../ABC/look-and-say-sequence.abc | 19 + .../EasyLang/look-and-say-sequence.easy | 1 - .../Uiua/look-and-say-sequence.uiua | 2 + ...op-over-multiple-arrays-simultaneously.pas | 12 + ...p-over-multiple-arrays-simultaneously-5.py | 5 + ...p-over-multiple-arrays-simultaneously.uiua | 1 + ...op-over-multiple-arrays-simultaneously.vim | 6 + Task/Loops-Break/Langur/loops-break.langur | 6 +- .../Loops-Break/PascalABC.NET/loops-break.pas | 10 + Task/Loops-Break/S-BASIC/loops-break-1.basic | 13 + Task/Loops-Break/S-BASIC/loops-break-2.basic | 14 + .../Langur/loops-continue.langur | 6 +- .../PascalABC.NET/loops-continue.pas | 12 + .../PascalABC.NET/loops-do-while.pas | 7 + .../loops-do-while-2.basic | 6 - ...-do-while-1.basic => loops-do-while.basic} | 0 .../Langur/loops-downward-for-1.langur | 4 +- .../Langur/loops-downward-for-2.langur | 4 +- .../PascalABC.NET/loops-downward-for.pas | 3 + .../loops-for-with-a-specified-step.langur | 4 +- .../loops-for-with-a-specified-step.pas | 7 + Task/Loops-For/Langur/loops-for-1.langur | 4 +- Task/Loops-For/Langur/loops-for-2.langur | 4 +- Task/Loops-For/Langur/loops-for-3.langur | 4 +- Task/Loops-For/PascalABC.NET/loops-for.pas | 7 + Task/Loops-For/Vim-Script/loops-for-1.vim | 6 + Task/Loops-For/Vim-Script/loops-for-2.vim | 3 + .../Loops-Foreach/Langur/loops-foreach.langur | 18 +- .../PascalABC.NET/loops-foreach.pas | 3 + ...increment-loop-index-within-loop-body.easy | 7 +- ...-increment-loop-index-within-loop-body.pas | 17 + .../PascalABC.NET/loops-n-plus-one-half.pas | 3 + .../PascalABC.NET/loops-nested.pas | 16 + Task/Loops-While/Langur/loops-while.langur | 8 +- Task/Loops-While/Mia/loops-while.mia | 5 + .../Loops-While/PascalABC.NET/loops-while.pas | 7 + .../loops-with-multiple-ranges.pas | 20 + .../Langur/loops-wrong-ranges.langur | 21 +- .../PascalABC.NET/loops-wrong-ranges.pas | 15 + .../Langur/lucas-lehmer-test.langur | 21 +- .../Ludic-numbers/EasyLang/ludic-numbers.easy | 27 + .../luhn-test-of-credit-card-numbers.langur | 22 +- .../Lua/luhn-test-of-credit-card-numbers.lua | 49 +- .../luhn-test-of-credit-card-numbers.setl | 18 + .../luhn-test-of-credit-card-numbers.uiua | 6 + .../Gambas/m-bius-function.gambas | 27 + .../PureBasic/m-bius-function.basic | 30 + .../XBasic/m-bius-function.basic | 31 + .../Raku/md5-implementation.raku | 5 +- Task/Magic-constant/Ada/magic-constant.ada | 68 +++ .../Seed7/make-directory-path-1.seed7 | 7 - .../Seed7/make-directory-path-2.seed7 | 10 - .../Seed7/make-directory-path.seed7 | 21 + .../PascalABC.NET/man-or-boy-test.pas | 13 + Task/Mandelbrot-set/Dart/mandelbrot-set.dart | 44 +- Task/Mandelbrot-set/Uiua/mandelbrot-set.uiua | 9 + Task/Map-range/EasyLang/map-range.easy | 6 + .../EasyLang/matrix-multiplication.easy | 11 +- .../Uiua/matrix-multiplication.uiua | 8 + Task/Mayan-calendar/Jq/mayan-calendar.jq | 105 ++++ Task/Maze-generation/11l/maze-generation.11l | 2 +- .../Chapel/maze-generation.chapel | 56 ++ .../POV-Ray/maze-generation.povray | 181 ++++++ .../Maze-generation/Uiua/maze-generation.uiua | 44 +- Task/Maze-solving/Uiua/maze-solving.uiua | 26 + .../Refal/mcnuggets-problem.refal | 37 ++ .../Uiua/mcnuggets-problem.uiua | 4 + .../PascalABC.NET/memory-allocation.pas | 16 + Task/Menu/Langur/menu.langur | 24 +- .../Uiua/middle-three-digits.uiua | 9 + ...exx => miller-rabin-primality-test-1.rexx} | 0 .../REXX/miller-rabin-primality-test-2.rexx | 167 ++++++ .../Ada/mind-boggling-card-trick.ada | 100 ++++ .../Jq/mind-boggling-card-trick.jq | 105 ++++ .../Jq/minimal-steps-down-to-1.jq | 82 +++ ...e-of-m-where-digital-sum-equals-m.quackery | 14 + .../Jq/modified-random-distribution.jq | 50 ++ .../ANSI-BASIC/monty-hall-problem.basic | 41 ++ .../Euphoria/monty-hall-problem.euphoria | 4 +- .../FutureBasic/monty-hall-problem.basic | 60 ++ .../Monty-Hall-problem/K/monty-hall-problem.k | 3 + .../Liberty-BASIC/monty-hall-problem.basic | 1 - .../Minimal-BASIC/monty-hall-problem.basic | 47 ++ .../Modula-2/monty-hall-problem.mod2 | 58 ++ .../monty-hall-problem.basic | 0 .../Run-BASIC/monty-hall-problem.basic | 2 - .../SETL/monty-hall-problem.setl | 29 + .../True-BASIC/monty-hall-problem.basic | 22 +- .../XPL0/monty-hall-problem.xpl0 | 4 +- .../Zig/monty-hall-problem.zig | 29 + .../Motzkin-numbers/Uiua/motzkin-numbers.uiua | 12 + .../PascalABC.NET/mouse-position.pas | 7 + .../EasyLang/move-to-front-algorithm.easy | 39 ++ .../BASIC256/multiple-regression.basic | 70 +++ .../Chipmunk-Basic/multiple-regression.basic | 68 +++ .../QB64/multiple-regression.qb64 | 71 +++ .../True-BASIC/multiple-regression.basic | 80 +++ .../Yabasic/multiple-regression.basic | 77 +++ .../11l/multiplicative-order.11l | 7 +- .../Jq/multiplicative-order.jq | 181 ++++++ Task/Multisplit/EasyLang/multisplit.easy | 17 + .../Langur/munchausen-numbers.langur | 4 +- ...numbers.rust => munchausen-numbers-1.rust} | 0 .../Rust/munchausen-numbers-2.rust | 35 ++ Task/Musical-scale/Ada/musical-scale.ada | 74 +++ .../EMal/mutual-recursion.emal | 8 + Task/N-queens-problem/C/n-queens-problem-1.c | 96 ++- Task/N-queens-problem/C/n-queens-problem-2.c | 45 +- Task/N-queens-problem/C/n-queens-problem-3.c | 101 +--- Task/N-queens-problem/C/n-queens-problem-4.c | 138 +++-- Task/N-queens-problem/C/n-queens-problem-5.c | 69 +++ .../Commodore-BASIC/n-queens-problem.basic | 55 ++ .../Pascal/n-queens-problem-1.pas | 109 +--- .../Pascal/n-queens-problem-2.pas | 183 +++--- .../Pascal/n-queens-problem-3.pas | 112 ++++ .../Python/n-queens-problem-7.py | 30 +- .../Python/n-queens-problem-8.py | 38 +- .../Uiua/n-queens-problem.uiua | 4 + .../EasyLang/negative-base-numbers.easy | 32 + Task/Nested-function/PL-M/nested-function.plm | 74 +++ .../PascalABC.NET/nested-function.pas | 21 + .../BASIC256/nested-templated-data.basic | 31 + .../nested-templated-data.basic | 30 + .../FreeBASIC/nested-templated-data.basic | 26 + .../GW-BASIC/nested-templated-data.basic | 28 + .../QBasic/nested-templated-data.basic | 33 ++ .../Refal/nested-templated-data.refal | 17 + .../Run-BASIC/nested-templated-data.basic | 31 + .../SETL/nested-templated-data.setl | 21 + .../Yabasic/nested-templated-data.basic | 31 + Task/Next-highest-int-from-digits/00-TASK.txt | 9 +- .../Ada/next-highest-int-from-digits.ada | 125 ++++ .../Phix/next-highest-int-from-digits-1.phix | 38 +- .../Phix/next-highest-int-from-digits-2.phix | 52 +- Task/Nim-game/11l/nim-game.11l | 2 +- Task/Nim-game/COBOL/nim-game.cobol | 25 + Task/Nim-game/XBasic/nim-game.basic | 24 + .../EasyLang/non-continuous-subsequences.easy | 18 + .../EasyLang/non-decimal-radices-input.easy | 10 + Task/Nonoblock/Jq/nonoblock.jq | 23 + Task/Nonogram-solver/Jq/nonogram-solver.jq | 255 ++++++++ Task/Nth-root/Langur/nth-root.langur | 14 +- Task/Nth/PascalABC.NET/nth.pas | 9 + Task/Null-object/Chapel/null-object.chapel | 2 +- Task/Null-object/Langur/null-object.langur | 10 +- .../Null-object/PascalABC.NET/null-object.pas | 6 + .../EasyLang/number-reversal-game.easy | 36 ++ ...h-are-not-the-sum-of-distinct-squares.uiua | 7 + .../PascalABC.NET/object-serialization.pas | 32 + .../C/one-dimensional-cellular-automata-3.c | 40 ++ .../one-dimensional-cellular-automata.refal | 39 ++ .../one-dimensional-cellular-automata.uiua | 4 + Task/Ordered-words/BASIC/ordered-words.basic | 17 + Task/Ordered-words/Emacs-Lisp/ordered-words.l | 75 +++ Task/Ordered-words/SETL/ordered-words.setl | 20 + Task/Ordered-words/Uiua/ordered-words.uiua | 4 + .../EasyLang/ormiston-triples.easy | 3 +- .../Phix/ormiston-triples-1.phix | 198 +++---- .../Phix/ormiston-triples-2.phix | 82 ++- .../11l/own-digits-power-sum.11l | 2 +- .../C++/p-adic-numbers-basic.cpp | 58 +- .../Java/p-adic-numbers-basic.java | 35 +- Task/P-Adic-square-roots/00-TASK.txt | 1 + .../C++/p-adic-square-roots.cpp | 309 ++++++++++ .../Java/p-adic-square-roots.java | 336 +++++++++++ .../Jq/p-value-correction.jq | 153 +++++ .../FreeBASIC/padovan-sequence.basic | 80 +++ ...e-detection.l => palindrome-detection-1.l} | 0 .../Emacs-Lisp/palindrome-detection-2.l | 3 + .../Langur/palindrome-detection.langur | 10 +- .../PascalABC.NET/palindrome-detection.pas | 6 + .../Refal/palindrome-detection.refal | 37 ++ .../Run-BASIC/palindrome-detection.basic | 13 +- ...ction.uiua => palindrome-detection-1.uiua} | 0 .../Uiua/palindrome-detection-2.uiua | 2 + Task/Palindromic-gapful-numbers/00-TASK.txt | 20 +- .../Jq/palindromic-gapful-numbers.jq | 68 +++ .../Elixir/parallel-brute-force.elixir | 47 ++ .../parallel-calculations.pas | 82 +++ .../COBOL/parametric-polymorphism.cobol | 34 ++ .../PascalABC.NET/parametric-polymorphism.pas | 31 + .../partition-an-integer-x-into-n-primes.easy | 55 ++ .../EasyLang/pascal-matrix-generation.easy | 49 ++ .../Quackery/password-generator.quackery | 34 ++ .../pathological-floating-point-problems.easy | 51 ++ .../Jq/peaceful-chess-queen-armies.jq | 81 +++ .../Langur/pells-equation.langur | 40 +- Task/Penneys-game/Ada/penneys-game.ada | 102 ++++ Task/Pentomino-tiling/Jq/pentomino-tiling.jq | 178 ++++++ ...percentage-difference-between-images-3.ada | 2 +- .../11l/percolation-bond-percolation.11l | 9 +- .../11l/percolation-mean-cluster-density.11l | 2 +- .../11l/percolation-site-percolation.11l | 3 +- .../percolation-site-percolation.basic | 53 +- .../ALGOL-60/perfect-numbers.alg | 10 +- .../EasyLang/perfect-numbers.easy | 13 +- .../S-BASIC/perfect-numbers.basic | 6 +- .../EasyLang/peripheral-drift-illusion.easy | 27 + Task/Perlin-noise/ALGOL-68/perlin-noise.alg | 77 +++ Task/Perlin-noise/Jq/perlin-noise.jq | 99 ++++ .../permutations-rank-of-a-permutation.easy | 59 ++ .../Ada/permutations-by-swapping.ada | 28 + Task/Permutations/Langur/permutations.langur | 50 +- Task/Permutations/Uiua/permutations.uiua | 6 + .../EasyLang/phrase-reversals.easy | 18 + Task/Pi/AArch64-Assembly/pi.aarch64 | 146 +++++ Task/Pi/ARM-Assembly/pi.arm | 155 +++++ Task/Pi/Standard-ML/pi.ml | 27 + Task/Pi/UNIX-Shell/pi.sh | 48 ++ .../PascalABC.NET/pick-random-element.pas | 4 + .../Uiua/pick-random-element.uiua | 1 + .../EasyLang/pierpont-primes.easy | 47 ++ .../C/pig-the-dice-game-player.c | 179 ++++++ .../EasyLang/pinstripe-display.easy | 10 + Task/Pisano-period/APL/pisano-period.apl | 17 + Task/Pisano-period/Jq/pisano-period.jq | 114 ++++ Task/Pisano-period/SETL/pisano-period.setl | 79 +++ .../Plasma-effect/EasyLang/plasma-effect.easy | 20 + .../Ada/play-recorded-sounds.ada | 39 ++ .../EasyLang/plot-coordinate-pairs.easy | 8 +- .../Ecstasy/pointers-and-references.ecstasy | 18 + .../PascalABC.NET/pointers-and-references.pas | 29 + .../Ada/poker-hand-analyser.ada | 162 +++++ .../Jq/poker-hand-analyser.jq | 65 ++ .../Liberty-BASIC/poker-hand-analyser.basic | 371 ++++++++++++ .../XPL0/poker-hand-analyser.xpl0 | 86 +++ .../Polymorphic-copy/Ada/polymorphic-copy.ada | 8 +- .../PascalABC.NET/polymorphic-copy.pas | 33 ++ .../PascalABC.NET/polymorphism.pas | 36 ++ .../Jq/polynomial-regression.jq | 47 ++ .../Population-count/ABC/population-count.abc | 25 + .../Refal/population-count.refal | 41 ++ Task/Power-set/PascalABC.NET/power-set.pas | 16 + .../Chipmunk-Basic/price-fraction.basic | 22 + .../Langur/price-fraction-1.langur | 33 ++ .../Langur/price-fraction-2.langur | 35 ++ .../Langur/price-fraction.langur | 26 - Task/Price-fraction/QB64/price-fraction.qb64 | 19 + .../primality-by-trial-division.basic | 11 + .../primality-by-trial-division-1.langur | 8 +- .../primality-by-trial-division-2.langur | 16 +- .../primality-by-trial-division.pas | 18 + .../PascalABC.NET/prime-decomposition.pas | 19 + .../REXX/prime-decomposition-1.rexx | 82 +++ .../REXX/prime-decomposition-3.rexx | 69 +++ ...se-neighboring-pairs-are-tetraprimes.sidef | 34 ++ Task/Priority-queue/Zig/priority-queue-1.zig | 26 +- .../11l/problem-of-apollonius.11l | 9 +- .../EasyLang/problem-of-apollonius.easy | 2 +- .../Program-name/Ecstasy/program-name.ecstasy | 7 + .../PascalABC.NET/program-name.pas | 3 + .../PascalABC.NET/program-termination.pas | 5 + .../Chipmunk-Basic/proper-divisors.basic | 35 ++ .../EasyLang/proper-divisors.easy | 12 +- .../Gambas/proper-divisors.gambas | 47 ++ .../Langur/proper-divisors.langur | 34 +- ...s-combined-recursive-generator-mrg32k3a.jq | 15 + ...do-random-numbers-middle-square-method.alg | 15 + .../pseudo-random-numbers-pcg32.basic | 49 ++ .../Jq/pseudo-random-numbers-pcg32.jq | 50 ++ .../pseudo-random-numbers-splitmix64.basic | 44 ++ .../pseudo-random-numbers-splitmix64.swift | 34 ++ .../pseudo-random-numbers-xorshift-star.basic | 43 ++ .../Jq/pseudo-random-numbers-xorshift-star.jq | 38 ++ .../EasyLang/pythagorean-quadruples.easy | 28 + .../D/pythagorean-triples-1.d | 4 +- .../PascalABC.NET/queue-definition.pas | 39 ++ .../Queue-Usage/PascalABC.NET/queue-usage.pas | 7 + Task/Quine/Odin/quine.odin | 16 + Task/Quine/PascalABC.NET/quine.pas | 1 + Task/Quine/Prog8/quine.prog8 | 9 + Task/Quine/Uxntal/quine.uxnatl | 16 + .../PascalABC.NET/quoting-constructs-1.pas | 1 + .../PascalABC.NET/quoting-constructs-2.pas | 1 + .../PascalABC.NET/quoting-constructs-3.pas | 2 + .../PascalABC.NET/quoting-constructs-4.pas | 5 + Task/RIPEMD-160/Java/ripemd-160-2.java | 2 +- .../Uiua/rpg-attributes-generator.uiua | 4 + .../PascalABC.NET/radical-of-an-integer.pas | 41 ++ ...eger.rexx => radical-of-an-integer-1.rexx} | 4 + .../REXX/radical-of-an-integer-2.rexx | 361 +++++++++++ ...-douglas-peucker-line-simplification.basic | 67 +++ ...mer-douglas-peucker-line-simplification.jq | 29 + ...-douglas-peucker-line-simplification.basic | 67 +++ .../ANSI-BASIC/random-numbers.basic | 19 + .../QuickBASIC/random-numbers.basic | 7 + Task/Random-numbers/Uiua/random-numbers.uiua | 6 + .../Jq/random-sentence-from-book.jq | 107 ++++ .../EasyLang/range-expansion.easy | 20 + .../EasyLang/range-extraction.easy | 28 +- Task/Rare-numbers/Langur/rare-numbers.langur | 33 +- .../Chipmunk-Basic/rate-counter.basic | 17 + .../11l/ray-casting-algorithm.11l | 24 +- ...ead-a-file-character-by-character-utf8.pas | 6 + .../C/read-a-file-line-by-line-1.c | 45 +- .../read-a-file-line-by-line.pas | 6 + .../read-a-specific-line-from-a-file.pas | 4 + .../PascalABC.NET/read-entire-file.pas | 3 + .../real-constants-and-functions.basic | 25 + .../real-constants-and-functions.basic | 35 +- .../real-constants-and-functions.pas | 13 + .../real-constants-and-functions.basic | 2 +- .../real-constants-and-functions.ml | 21 +- .../XBasic/real-constants-and-functions.basic | 5 +- Task/Record-sound/00-TASK.txt | 1 + Task/Record-sound/Ada/record-sound.ada | 33 ++ .../FutureBasic/record-sound.basic | 138 +++++ .../Ecstasy/reflection-list-methods.ecstasy | 14 + .../PascalABC.NET/reflection-list-methods.pas | 7 + .../reflection-list-properties.ecstasy | 7 + .../reflection-list-properties.pas | 19 + .../Langur/regular-expressions-2.langur | 2 +- .../PascalABC.NET/regular-expressions.pas | 10 + .../remove-duplicate-elements.pas | 17 + .../remove-lines-from-a-file.pas | 9 + .../PascalABC.NET/rename-a-file.pas | 9 + .../PascalABC.NET/repeat-a-string.pas | 2 + Task/Repeat/Applesoft-BASIC/repeat.basic | 20 + Task/Repeat/Chapel/repeat-1.chapel | 13 + Task/Repeat/Chapel/repeat-2.chapel | 13 + Task/Repeat/Chapel/repeat-3.chapel | 13 + Task/Repeat/PascalABC.NET/repeat.pas | 7 + Task/Repeat/Refal/repeat.refal | 12 + .../PascalABC.NET/return-multiple-values.pas | 6 + .../Langur/reverse-a-string.langur | 2 +- .../PascalABC.NET/reverse-a-string.pas | 3 + .../reverse-words-in-a-string.pas | 3 + Task/Rhonda-numbers/Python/rhonda-numbers.py | 47 ++ .../EasyLang/rock-paper-scissors.easy | 24 + .../JavaScript/roman-numerals-decode-8.js | 70 +-- .../PascalABC.NET/roman-numerals-decode.pas | 39 ++ .../JavaScript/roman-numerals-encode-4.js | 47 +- .../PascalABC.NET/roman-numerals-encode.pas | 21 + .../Ada/rosetta-code-count-examples.ada | 13 +- .../rosetta-code-find-unimplemented-tasks.ada | 68 +-- ...-code-rank-languages-by-number-of-users.jq | 14 + ...etta-code-rank-languages-by-popularity.ada | 180 +++++- ...tta-code-rank-languages-by-popularity.java | 31 +- ...etta-code-rank-languages-by-popularity.pas | 13 + Task/Rot-13/PascalABC.NET/rot-13.pas | 19 + .../Uiua/run-length-encoding.uiua | 10 + ...runtime-evaluation-in-an-environment.basic | 10 + .../EasyLang/ruth-aaron-numbers.easy | 40 ++ Task/SEDOLs/Langur/sedols.langur | 34 +- Task/SHA-256/Java/sha-256.java | 2 +- Task/SHA-256/V-(Vlang)/sha-256.v | 6 +- .../Safe-addition/Langur/safe-addition.langur | 1 + ...sailors-coconuts-and-a-monkey-problem.easy | 18 + .../scope-function-names-and-labels.easy | 13 + .../Wren/scope-function-names-and-labels.wren | 13 +- .../PascalABC.NET/scope-modifiers-1.pas | 1 + .../PascalABC.NET/scope-modifiers-2.pas | 1 + .../PascalABC.NET/scope-modifiers-3.pas | 1 + .../PascalABC.NET/scope-modifiers-4.pas | 1 + .../Ecstasy/search-a-list.ecstasy | 12 + .../Perl/search-in-paragraphs-text.pl | 15 + ...stances-of-a-character-within-a-string.ada | 42 ++ ...tances-of-a-character-within-a-string.easy | 20 + Task/Self-numbers/EasyLang/self-numbers.easy | 47 ++ Task/Semiprime/REXX/semiprime-4.rexx | 59 ++ .../SuperCollider/semordnilap-1.sc | 12 - .../SuperCollider/semordnilap-2.sc | 6 - Task/Semordnilap/Uiua/semordnilap.uiua | 4 +- .../send-an-unknown-method-call.ecstasy | 21 + .../send-an-unknown-method-call.pas | 10 + .../sequence-of-primes-by-trial-division.pas | 4 + Task/Set-puzzle/Jq/set-puzzle.jq | 77 +++ .../Jq/set-right-adjacent-bits.jq | 27 + Task/Sexy-primes/BASIC256/sexy-primes.basic | 70 +++ Task/Sexy-primes/FreeBASIC/sexy-primes.basic | 12 +- Task/Sexy-primes/Yabasic/sexy-primes.basic | 66 +++ .../Langur/show-ascii-table.langur | 8 +- .../SETL/show-ascii-table.setl | 9 + .../EasyLang/show-the-epoch.easy | 2 + .../Jq/sierpinski-pentagon.jq | 59 ++ .../Ada/sierpinski-square-curve.ada | 49 ++ .../EasyLang/sierpinski-triangle.easy | 14 + .../EasyLang/sieve-of-eratosthenes.easy | 18 +- .../Erlang/sieve-of-eratosthenes-6.erl | 20 + .../Langur/sieve-of-eratosthenes.langur | 20 +- .../OCaml/sieve-of-eratosthenes-7.ocaml | 16 + .../OCaml/sieve-of-eratosthenes-8.ocaml | 3 + .../PascalABC.NET/sieve-of-eratosthenes.pas | 17 + Task/Simple-database/11l/simple-database.11l | 9 +- Task/Simple-database/C++/simple-database.cpp | 147 +++++ .../simple-windowed-application.pas | 13 + Task/Singleton/Ecstasy/singleton.ecstasy | 15 + .../singly-linked-list-element-definition.pas | 4 + .../singly-linked-list-element-insertion.pas | 33 ++ Task/Sleep/PascalABC.NET/sleep.pas | 6 + .../ALGOL-68/sleeping-beauty-problem.alg | 19 + .../Fortran/sleeping-beauty-problem.f | 43 ++ .../FutureBasic/sleeping-beauty-problem.basic | 18 +- .../Jq/sleeping-beauty-problem.jq | 25 + .../Sidef/smarandache-wellin-primes.sidef | 32 + .../Smith-numbers/EasyLang/smith-numbers.easy | 8 +- Task/Smith-numbers/Uiua/smith-numbers-1.uiua | 7 + Task/Smith-numbers/Uiua/smith-numbers-2.uiua | 3 + Task/Snake/Emacs-Lisp/snake.l | 1 + Task/Snake/Locomotive-Basic/snake.basic | 29 +- Task/Solve-a-Hidato-puzzle/00-TASK.txt | 2 +- .../Jq/solve-a-hidato-puzzle.jq | 74 +++ .../Uiua/solve-a-hidato-puzzle.uiua | 22 + .../Jq/solve-a-holy-knights-tour.jq | 83 +++ .../Dart/solve-a-numbrix-puzzle.dart | 92 +++ .../Jq/solve-a-numbrix-puzzle.jq | 80 +++ .../Uiua/solve-a-numbrix-puzzle.uiua | 22 + .../solve-the-no-connection-puzzle.basic | 51 ++ .../solve-the-no-connection-puzzle.quackery | 24 + .../Zig/solve-the-no-connection-puzzle-1.zig | 53 ++ .../Zig/solve-the-no-connection-puzzle-2.zig | 54 ++ .../sort-a-list-of-object-identifiers.easy | 28 + .../sort-an-array-of-composite-structures.pas | 10 + .../EasyLang/sort-an-integer-array.easy | 12 + .../PascalABC.NET/sort-an-integer-array.pas | 4 + .../C++/sort-an-outline-at-every-level.cpp | 258 ++++++++ .../Jq/sort-an-outline-at-every-level.jq | 169 ++++++ .../Uiua/sort-disjoint-sublist.uiua | 1 + .../sort-numbers-lexicographically.easy | 14 + .../PascalABC.NET/sort-three-variables.pas | 14 + .../sort-using-a-custom-comparator.pas | 10 + .../sorting-algorithms-circle-sort.alg | 67 +++ .../sorting-algorithms-circle-sort.easy | 31 + .../EMal/sorting-algorithms-bogosort.emal | 19 + .../sorting-algorithms-cocktail-sort.easy | 25 + .../sorting-algorithms-comb-sort.easy | 17 + .../sorting-algorithms-counting-sort.langur | 16 +- .../sorting-algorithms-counting-sort.basic | 72 +++ .../sorting-algorithms-insertion-sort-3.lisp | 24 + ...orting-algorithms-insertion-sort-1.kotlin} | 0 ...sorting-algorithms-insertion-sort-2.kotlin | 16 + .../sorting-algorithms-merge-sort.ml | 9 +- .../sorting-algorithms-pancake-sort.easy | 48 ++ .../sorting-algorithms-permutation-sort.ada | 39 ++ .../sorting-algorithms-permutation-sort.easy | 49 ++ .../11l/sorting-algorithms-quicksort.11l | 2 +- .../sorting-algorithms-quicksort.basic | 51 ++ .../sorting-algorithms-quicksort.easy | 29 +- .../sorting-algorithms-quicksort.pas | 41 ++ .../Python/sorting-algorithms-quicksort-8.py | 9 + .../sorting-algorithms-quicksort.basic | 0 .../XBasic/sorting-algorithms-quicksort.basic | 75 +++ .../sorting-algorithms-shell-sort.easy | 18 + .../11l/sorting-algorithms-stooge-sort.11l | 2 +- .../sorting-algorithms-stooge-sort.easy | 4 +- .../sorting-algorithms-stooge-sort.basic | 38 ++ .../sorting-algorithms-strand-sort.easy | 43 ++ .../PascalABC.NET/special-variables-1.pas | 4 + .../PascalABC.NET/special-variables-2.pas | 7 + .../PascalABC.NET/special-variables-3.pas | 4 + ...-string-based-on-change-of-character.refal | 16 + ...r-string-based-on-change-of-character.setl | 17 + ...r-string-based-on-change-of-character.uiua | 1 + .../8080-Assembly/square-but-not-cube.8080 | 91 +++ .../ABC/square-but-not-cube.abc | 11 + .../MACRO-11/square-but-not-cube.macro11 | 53 ++ .../Refal/square-but-not-cube.refal | 21 + .../Uiua/square-free-integers.uiua | 6 + .../PascalABC.NET/stack-traces.pas | 14 + Task/Stack/PascalABC.NET/stack.pas | 11 + .../EasyLang/stair-climbing-puzzle.easy | 15 + .../Phix/steffensens-method.phix | 108 ++-- .../EasyLang/stem-and-leaf-plot.easy | 24 + .../Uiua/stem-and-leaf-plot.uiua | 10 + .../String-append/Langur/string-append.langur | 6 +- .../PascalABC.NET/string-append.pas | 6 + Task/String-case/Ecstasy/string-case.ecstasy | 7 + .../String-case/PascalABC.NET/string-case.pas | 4 + Task/String-case/Uiua/string-case.uiua | 4 + Task/String-case/Zig/string-case.zig | 2 +- .../Ecstasy/string-comparison.ecstasy | 54 ++ ...ncatenation.c => string-concatenation-1.c} | 0 .../C/string-concatenation-2.c | 14 + .../Ecstasy/string-concatenation.ecstasy | 31 + .../PascalABC.NET/string-concatenation.pas | 4 + .../Uiua/string-concatenation.uiua | 3 + .../string-interpolation-included--1.langur | 2 + .../string-interpolation-included--2.langur | 1 + .../string-interpolation-included--3.langur | 3 + .../string-interpolation-included-.pas | 3 + .../Phix/string-interpolation-included-.phix | 8 +- .../Uiua/string-interpolation-included-.uiua | 1 + .../String-length/EasyLang/string-length.easy | 4 - .../Ecstasy/string-length.ecstasy | 10 + .../PascalABC.NET/string-length.pas | 6 + .../PascalABC.NET/string-matching.pas | 9 + .../Uiua/string-matching-1.uiua | 1 + .../Uiua/string-matching-2.uiua | 1 + .../Uiua/string-matching-3.uiua | 1 + .../Uiua/string-matching-4.uiua | 1 + .../PascalABC.NET/string-prepend.pas | 4 + ...trip-a-set-of-characters-from-a-string.pas | 6 + ...rip-a-set-of-characters-from-a-string.uiua | 3 + .../PascalABC.NET/strip-block-comments.pas | 21 + .../strip-comments-from-a-string.pas | 7 + ...d-extended-characters-from-a-string.langur | 8 +- ...-and-extended-characters-from-a-string.pas | 7 + ...-whitespace-from-a-string-top-and-tail.pas | 6 + .../Emacs-Lisp/substitution-cipher.l | 41 ++ .../PascalABC.NET/substitution-cipher.pas | 14 + .../Ecstasy/substring-top-and-tail.ecstasy | 13 + .../PascalABC.NET/substring-top-and-tail.pas | 7 + Task/Substring/Ecstasy/substring.ecstasy | 60 ++ Task/Substring/PascalABC.NET/substring.pas | 13 + .../PascalABC.NET/sudan-function.pas | 12 + Task/Sudoku/Uiua/sudoku.uiua | 26 + .../Langur/sum-and-product-of-an-array.langur | 8 +- .../sum-and-product-of-an-array.pas | 3 + .../sum-digits-of-an-integer.pas | 17 + .../sum-multiples-of-3-and-5.pas | 3 + .../Uiua/sum-multiples-of-3-and-5-1.uiua | 8 + .../Uiua/sum-multiples-of-3-and-5-2.uiua | 3 + .../Langur/sum-of-a-series-1.langur | 4 +- .../Langur/sum-of-a-series-2.langur | 4 +- .../PascalABC.NET/sum-of-a-series.pas | 2 + ...elements-below-main-diagonal-of-matrix.pas | 14 + .../PascalABC.NET/sum-of-squares.pas | 3 + .../11l/summarize-and-say-sequence.11l | 2 +- .../C-sharp/summarize-primes.cs | 61 ++ .../Uiua/summarize-primes.uiua | 4 + .../Pascal/symmetric-difference-1.pas | 2 +- .../PascalABC.NET/symmetric-difference.pas | 7 + Task/System-time/Ecstasy/system-time.ecstasy | 8 + .../System-time/PascalABC.NET/system-time.pas | 2 + .../take-notes-on-the-command-line.pas | 11 + .../take-notes-on-the-command-line-1.sh | 16 +- Task/Tarjan/11l/tarjan.11l | 2 +- Task/Tau-function/C-sharp/tau-function.cs | 51 ++ .../PascalABC.NET/tau-function.pas | 4 + Task/Tau-function/REXX/tau-function.rexx | 74 ++- Task/Tau-number/C-sharp/tau-number.cs | 59 ++ Task/Tau-number/PascalABC.NET/tau-number.pas | 12 + Task/Tau-number/REXX/tau-number.rexx | 81 +-- .../EasyLang/taxicab-numbers.easy | 34 ++ .../Teacup-rim-text/REXX/teacup-rim-text.rexx | 72 ++- .../PascalABC.NET/temperature-conversion.pas | 5 + .../terminal-control-clear-the-screen.pas | 2 + .../terminal-control-coloured-text.pas | 8 + .../terminal-control-cursor-movement.pas | 22 + .../terminal-control-cursor-positioning.pas | 6 + .../terminal-control-dimensions.pas | 5 + ...-control-display-an-extended-character.pas | 5 + .../terminal-control-hiding-the-cursor.pas | 10 + ...inal-control-ringing-the-terminal-bell.pas | 2 + .../JavaScript/ternary-logic-3.js | 3 +- .../JavaScript/ternary-logic-4.js | 14 +- .../JavaScript/ternary-logic-5.js | 26 +- .../Ternary-logic/Langur/ternary-logic.langur | 42 +- .../PascalABC.NET/test-a-function.pas | 13 + .../Test-a-function/Uiua/test-a-function.uiua | 6 + .../Jq/thieles-interpolation-formula.jq | 42 ++ Task/Tic-tac-toe/J/tic-tac-toe.j | 103 +--- Task/Tic-tac-toe/Jq/tic-tac-toe.jq | 151 +++++ .../PascalABC.NET/time-a-function.pas | 14 + .../tokenize-a-string-with-escaping.easy | 20 + .../PascalABC.NET/tokenize-a-string.pas | 5 + .../EasyLang/top-rank-per-group.easy | 58 ++ .../PascalABC.NET/top-rank-per-group.pas | 25 + Task/Topic-variable/Java/topic-variable.java | 42 ++ Task/Towers-of-Hanoi/11l/towers-of-hanoi.11l | 2 +- .../Asymptote/towers-of-hanoi.asymptote | 12 + .../Bruijn/towers-of-hanoi.bruijn | 10 + .../JavaScript/towers-of-hanoi-4.js | 18 +- .../PascalABC.NET/towers-of-hanoi.pas | 9 + .../trabb-pardo-knuth-algorithm.pas | 10 + .../UNIX-Shell/trabb-pardo-knuth-algorithm.sh | 18 + ...-english-text-using-the-greek-alphabet.pas | 37 ++ .../11l/tree-datastructures.11l | 9 +- .../PascalABC.NET/tree-datastructures.pas | 41 ++ .../C-sharp/tree-from-nesting-levels.cs | 70 +++ Task/Tree-traversal/11l/tree-traversal.11l | 8 +- Task/Tree-traversal/EMal/tree-traversal.emal | 63 ++ .../PascalABC.NET/tree-traversal.pas | 61 ++ Task/Tree-traversal/Rust/tree-traversal.rust | 39 +- .../PascalABC.NET/trigonometric-functions.pas | 20 + .../Phix/trigonometric-functions.phix | 28 +- .../REXX/truncatable-primes.rexx | 112 ++-- .../Uiua/truncatable-primes.uiua | 10 + .../PascalABC.NET/truncate-a-file.pas | 14 + .../PascalABC.NET/twos-complement.pas | 5 + Task/UPC/Ada/upc.ada | 162 +++++ Task/URL-decoding/Langur/url-decoding.langur | 8 +- .../PascalABC.NET/url-decoding.pas | 9 + Task/URL-encoding/Langur/url-encoding.langur | 12 +- .../PascalABC.NET/url-encoding.pas | 4 + .../Langur/utf-8-encode-and-decode.langur | 10 +- .../C-sharp/ultra-useful-primes.cs | 82 +++ .../PascalABC.NET/undefined-values.pas | 9 + .../PascalABC.NET/unicode-strings.pas | 6 + .../PascalABC.NET/unicode-variable-names.pas | 5 + ...chine.py => universal-turing-machine-1.py} | 0 .../Python/universal-turing-machine-2.py | 24 + .../User-input-Text/EMal/user-input-text.emal | 9 + .../PascalABC.NET/user-input-text.pas | 3 + ...al-securities-identification-number.langur | 32 +- ...onal-securities-identification-number.rexx | 70 ++- ...onal-securities-identification-number.uiua | 19 + .../REXX/van-eck-sequence-1.rexx | 34 +- .../REXX/van-eck-sequence-2.rexx | 44 +- .../C-sharp/variable-declaration-reset.cs | 37 ++ Task/Variables/PascalABC.NET/variables-1.pas | 1 + Task/Variables/PascalABC.NET/variables-2.pas | 1 + Task/Variables/PascalABC.NET/variables-3.pas | 1 + Task/Variables/PascalABC.NET/variables-4.pas | 1 + Task/Variables/PascalABC.NET/variables-5.pas | 6 + Task/Variables/PascalABC.NET/variables-6.pas | 5 + .../PascalABC.NET/variadic-function.pas | 11 + .../PascalABC.NET/vector-products.pas | 26 + .../Vector-products/REXX/vector-products.rexx | 45 +- Task/Vector/Chipmunk-Basic/vector.basic | 37 ++ Task/Vector/GW-BASIC/vector.basic | 37 ++ Task/Vector/PascalABC.NET/vector.pas | 31 + Task/Vector/QBasic/vector.basic | 39 ++ Task/Vector/True-BASIC/vector.basic | 40 ++ .../verify-distribution-uniformity-naive.easy | 47 ++ .../Sidef/wagstaff-primes.sidef | 20 + .../walk-a-directory-non-recursively.pas | 4 + .../walk-a-directory-recursively.pas | 4 + Task/War-card-game/00-TASK.txt | 1 - Task/War-card-game/Ada/war-card-game.ada | 146 +++++ Task/War-card-game/Jq/war-card-game.jq | 113 ++++ .../PHP/water-collected-between-towers.php | 60 ++ .../Uiua/water-collected-between-towers.uiua | 10 + Task/Weird-numbers/Ada/weird-numbers-1.ada | 109 ++++ Task/Weird-numbers/Ada/weird-numbers-2.ada | 105 ++++ .../{weird-numbers.py => weird-numbers-1.py} | 0 Task/Weird-numbers/Python/weird-numbers-2.py | 51 ++ .../Weird-numbers/Uxntal/weird-numbers.uxnatl | 85 +++ .../PascalABC.NET/window-creation.pas | 5 + Task/Wireworld/11l/wireworld.11l | 9 +- .../PascalABC.NET/word-frequency.pas | 3 + Task/Word-ladder/APL/word-ladder.apl | 23 + Task/Word-ladder/Ada/word-ladder.ada | 146 +++++ Task/Word-ladder/Refal/word-ladder.refal | 95 +++ Task/Word-ladder/SETL/word-ladder.setl | 45 ++ Task/Word-search/Ada/word-search.ada | 259 ++++++++ Task/Word-wheel/Ada/word-wheel.ada | 56 ++ .../Lua/{word-wheel.lua => word-wheel-1.lua} | 0 Task/Word-wheel/Lua/word-wheel-2.lua | 15 + Task/Word-wrap/PascalABC.NET/word-wrap.pas | 40 ++ Task/Wordiff/Jq/wordiff.jq | 108 ++++ .../PascalABC.NET/write-entire-file.pas | 2 + .../write-to-windows-event-log.basic | 36 ++ .../write-to-windows-event-log.pas | 7 + .../PascalABC.NET/xml-dom-serialization.pas | 19 + Task/XML-Input/PascalABC.NET/xml-input.pas | 20 + Task/XML-Input/Vim-Script/xml-input.vim | 9 + Task/XML-Output/PascalABC.NET/xml-output.pas | 20 + .../C-sharp/yellowstone-sequence.cs | 73 +++ .../Uiua/yellowstone-sequence.uiua | 6 + ...in-and-yang.basic => yin-and-yang-1.basic} | 0 .../AmigaBASIC/yin-and-yang-2.basic | 21 + Task/Zebra-puzzle/Phix/zebra-puzzle.phix | 157 ++--- Task/Zebra-puzzle/Uiua/zebra-puzzle.uiua | 32 + .../11l/zeckendorf-arithmetic.11l | 2 +- .../PascalABC.NET/zero-to-the-zero-power.pas | 2 + .../EasyLang/zig-zag-matrix.easy | 31 + 2011 files changed, 35081 insertions(+), 3229 deletions(-) create mode 120000 Lang/8080-Assembly/Square-but-not-cube create mode 120000 Lang/AArch64-Assembly/Pi create mode 120000 Lang/ABC/Look-and-say-sequence create mode 120000 Lang/ABC/Population-count create mode 120000 Lang/ABC/Square-but-not-cube create mode 120000 Lang/ALGOL-68/Draw-a-cuboid create mode 120000 Lang/ALGOL-68/Perlin-noise create mode 120000 Lang/ALGOL-68/Sleeping-Beauty-problem create mode 120000 Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort create mode 120000 Lang/ALGOL-W/Eulers-constant-0.5772... create mode 120000 Lang/ALGOL-W/Find-the-intersection-of-two-lines create mode 120000 Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method create mode 120000 Lang/ANSI-BASIC/Damm-algorithm create mode 120000 Lang/ANSI-BASIC/Formatted-numeric-output create mode 120000 Lang/ANSI-BASIC/Function-definition create mode 120000 Lang/ANSI-BASIC/Monty-Hall-problem create mode 120000 Lang/ANSI-BASIC/Random-numbers create mode 120000 Lang/ANSI-BASIC/Real-constants-and-functions create mode 120000 Lang/ANSI-BASIC/Sorting-algorithms-Quicksort create mode 120000 Lang/APL/Display-a-linear-combination create mode 120000 Lang/APL/Pisano-period create mode 120000 Lang/APL/Word-ladder create mode 120000 Lang/ARM-Assembly/Pi create mode 120000 Lang/Ada/Abelian-sandpile-model create mode 120000 Lang/Ada/Achilles-numbers create mode 120000 Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Ada/Ascending-primes create mode 120000 Lang/Ada/Brace-expansion create mode 120000 Lang/Ada/Color-wheel create mode 120000 Lang/Ada/Combinations-and-permutations create mode 120000 Lang/Ada/Eulers-constant-0.5772... create mode 120000 Lang/Ada/FTP create mode 120000 Lang/Ada/Hex-words create mode 120000 Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols create mode 120000 Lang/Ada/Largest-number-divisible-by-its-digits create mode 120000 Lang/Ada/Magic-constant create mode 120000 Lang/Ada/Mind-boggling-card-trick create mode 120000 Lang/Ada/Musical-scale create mode 120000 Lang/Ada/Next-highest-int-from-digits create mode 120000 Lang/Ada/Penneys-game create mode 120000 Lang/Ada/Permutations-by-swapping create mode 120000 Lang/Ada/Play-recorded-sounds create mode 120000 Lang/Ada/Poker-hand-analyser create mode 120000 Lang/Ada/Record-sound create mode 120000 Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string create mode 120000 Lang/Ada/Sierpinski-square-curve create mode 120000 Lang/Ada/Sorting-algorithms-Permutation-sort create mode 120000 Lang/Ada/UPC create mode 120000 Lang/Ada/War-card-game create mode 120000 Lang/Ada/Weird-numbers create mode 120000 Lang/Ada/Word-ladder create mode 120000 Lang/Ada/Word-search create mode 120000 Lang/Ada/Word-wheel create mode 120000 Lang/Applesoft-BASIC/Display-a-linear-combination create mode 120000 Lang/Applesoft-BASIC/Repeat create mode 120000 Lang/Asymptote/Jensens-Device create mode 120000 Lang/Asymptote/Towers-of-Hanoi delete mode 100644 Lang/AutoHotKey-V2/00-LANG.txt delete mode 100644 Lang/AutoHotKey-V2/00-META.yaml delete mode 120000 Lang/AutoHotKey-V2/Hello-world-Graphical create mode 100644 Lang/Autohotkey-V2/00-LANG.txt create mode 100644 Lang/Autohotkey-V2/00-META.yaml create mode 120000 Lang/Autohotkey-V2/Hello-world-Graphical delete mode 120000 Lang/BASIC/Damm-algorithm delete mode 120000 Lang/BASIC/Function-definition delete mode 120000 Lang/BASIC/Gray-code delete mode 120000 Lang/BASIC/Monty-Hall-problem create mode 120000 Lang/BASIC/Ordered-words delete mode 120000 Lang/BASIC/Sorting-algorithms-Quicksort create mode 120000 Lang/BASIC256/Kronecker-product create mode 120000 Lang/BASIC256/Multiple-regression create mode 120000 Lang/BASIC256/Nested-templated-data create mode 120000 Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification create mode 120000 Lang/BASIC256/Sexy-primes create mode 120000 Lang/Bruijn/Harmonic-series create mode 120000 Lang/Bruijn/Towers-of-Hanoi create mode 120000 Lang/C++/Add-a-variable-to-a-class-instance-at-runtime create mode 120000 Lang/C++/Bitcoin-address-validation create mode 120000 Lang/C++/Bitcoin-public-point-to-address create mode 120000 Lang/C++/Catmull-Clark-subdivision-surface create mode 120000 Lang/C++/Compiler-virtual-machine-interpreter create mode 120000 Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection create mode 120000 Lang/C++/Im-a-software-engineer-get-me-out-of-here create mode 120000 Lang/C++/P-Adic-square-roots create mode 120000 Lang/C++/Simple-database create mode 120000 Lang/C++/Sort-an-outline-at-every-level create mode 120000 Lang/C-sharp/Additive-primes create mode 120000 Lang/C-sharp/Cyclops-numbers create mode 120000 Lang/C-sharp/Summarize-primes create mode 120000 Lang/C-sharp/Tau-function create mode 120000 Lang/C-sharp/Tau-number create mode 120000 Lang/C-sharp/Tree-from-nesting-levels create mode 120000 Lang/C-sharp/Ultra-useful-primes create mode 120000 Lang/C-sharp/Variable-declaration-reset create mode 120000 Lang/C-sharp/Yellowstone-sequence create mode 120000 Lang/C/Hunt-the-Wumpus create mode 120000 Lang/C/Pig-the-dice-game-Player create mode 120000 Lang/COBOL/Nim-game create mode 120000 Lang/COBOL/Parametric-polymorphism create mode 120000 Lang/Chapel/Function-definition create mode 120000 Lang/Chapel/Maze-generation create mode 120000 Lang/Chapel/Repeat create mode 120000 Lang/Chipmunk-Basic/Display-a-linear-combination create mode 120000 Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences create mode 120000 Lang/Chipmunk-Basic/Jensens-Device create mode 120000 Lang/Chipmunk-Basic/Multiple-regression create mode 120000 Lang/Chipmunk-Basic/Nested-templated-data create mode 120000 Lang/Chipmunk-Basic/Price-fraction create mode 120000 Lang/Chipmunk-Basic/Proper-divisors create mode 120000 Lang/Chipmunk-Basic/Rate-counter create mode 120000 Lang/Chipmunk-Basic/Vector create mode 120000 Lang/Commodore-BASIC/N-queens-problem create mode 120000 Lang/Common-Lisp/Blum-integer create mode 120000 Lang/Common-Lisp/Factorial-primes create mode 120000 Lang/Cowgol/Display-a-linear-combination create mode 120000 Lang/Dart/15-puzzle-solver create mode 120000 Lang/Dart/Jensens-Device create mode 120000 Lang/Dart/Solve-a-Numbrix-puzzle create mode 120000 Lang/Draco/Display-a-linear-combination create mode 120000 Lang/EMal/Babbage-problem create mode 120000 Lang/EMal/Bifid-cipher create mode 120000 Lang/EMal/Mutual-recursion create mode 120000 Lang/EMal/Sorting-algorithms-Bogosort create mode 120000 Lang/EMal/Tree-traversal create mode 120000 Lang/EMal/User-input-Text create mode 120000 Lang/EasyLang/Abelian-sandpile-model create mode 120000 Lang/EasyLang/Abelian-sandpile-model-Identity create mode 120000 Lang/EasyLang/Approximate-equality create mode 120000 Lang/EasyLang/Arithmetic-Complex create mode 120000 Lang/EasyLang/Greatest-subsequential-sum create mode 120000 Lang/EasyLang/Guess-the-number-With-feedback-player- create mode 120000 Lang/EasyLang/Halt-and-catch-fire create mode 120000 Lang/EasyLang/Hamming-numbers create mode 120000 Lang/EasyLang/Hofstadter-Figure-Figure-sequences create mode 120000 Lang/EasyLang/IBAN create mode 120000 Lang/EasyLang/Iterated-digits-squaring create mode 120000 Lang/EasyLang/JortSort create mode 120000 Lang/EasyLang/Kronecker-product create mode 120000 Lang/EasyLang/Kronecker-product-based-fractals create mode 120000 Lang/EasyLang/Largest-int-from-concatenated-ints create mode 120000 Lang/EasyLang/Last-letter-first-letter create mode 120000 Lang/EasyLang/Longest-increasing-subsequence create mode 120000 Lang/EasyLang/Ludic-numbers create mode 120000 Lang/EasyLang/Map-range create mode 120000 Lang/EasyLang/Move-to-front-algorithm create mode 120000 Lang/EasyLang/Multisplit create mode 120000 Lang/EasyLang/Negative-base-numbers create mode 120000 Lang/EasyLang/Non-continuous-subsequences create mode 120000 Lang/EasyLang/Non-decimal-radices-Input create mode 120000 Lang/EasyLang/Number-reversal-game create mode 120000 Lang/EasyLang/Partition-an-integer-x-into-n-primes create mode 120000 Lang/EasyLang/Pascal-matrix-generation create mode 120000 Lang/EasyLang/Pathological-floating-point-problems create mode 120000 Lang/EasyLang/Peripheral-drift-illusion create mode 120000 Lang/EasyLang/Permutations-Rank-of-a-permutation create mode 120000 Lang/EasyLang/Phrase-reversals create mode 120000 Lang/EasyLang/Pierpont-primes create mode 120000 Lang/EasyLang/Pinstripe-Display create mode 120000 Lang/EasyLang/Plasma-effect create mode 120000 Lang/EasyLang/Pythagorean-quadruples create mode 120000 Lang/EasyLang/Range-expansion create mode 120000 Lang/EasyLang/Rock-paper-scissors create mode 120000 Lang/EasyLang/Ruth-Aaron-numbers create mode 120000 Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem create mode 120000 Lang/EasyLang/Scope-Function-names-and-labels create mode 120000 Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string create mode 120000 Lang/EasyLang/Self-numbers create mode 120000 Lang/EasyLang/Show-the-epoch create mode 120000 Lang/EasyLang/Sierpinski-triangle create mode 120000 Lang/EasyLang/Sort-a-list-of-object-identifiers create mode 120000 Lang/EasyLang/Sort-an-integer-array create mode 120000 Lang/EasyLang/Sort-numbers-lexicographically create mode 120000 Lang/EasyLang/Sorting-Algorithms-Circle-Sort create mode 120000 Lang/EasyLang/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/EasyLang/Sorting-algorithms-Comb-sort create mode 120000 Lang/EasyLang/Sorting-algorithms-Pancake-sort create mode 120000 Lang/EasyLang/Sorting-algorithms-Permutation-sort create mode 120000 Lang/EasyLang/Sorting-algorithms-Shell-sort create mode 120000 Lang/EasyLang/Sorting-algorithms-Strand-sort create mode 120000 Lang/EasyLang/Stair-climbing-puzzle create mode 120000 Lang/EasyLang/Stem-and-leaf-plot create mode 120000 Lang/EasyLang/Taxicab-numbers create mode 120000 Lang/EasyLang/Tokenize-a-string-with-escaping create mode 120000 Lang/EasyLang/Top-rank-per-group create mode 120000 Lang/EasyLang/Verify-distribution-uniformity-Naive create mode 120000 Lang/EasyLang/Zig-zag-matrix create mode 120000 Lang/Ecstasy/100-prisoners create mode 120000 Lang/Ecstasy/Assertions create mode 120000 Lang/Ecstasy/Pointers-and-references create mode 120000 Lang/Ecstasy/Program-name create mode 120000 Lang/Ecstasy/Reflection-List-methods create mode 120000 Lang/Ecstasy/Reflection-List-properties create mode 120000 Lang/Ecstasy/Search-a-list create mode 120000 Lang/Ecstasy/Send-an-unknown-method-call create mode 120000 Lang/Ecstasy/Singleton create mode 120000 Lang/Ecstasy/String-case create mode 120000 Lang/Ecstasy/String-comparison create mode 120000 Lang/Ecstasy/String-concatenation create mode 120000 Lang/Ecstasy/String-length create mode 120000 Lang/Ecstasy/Substring create mode 120000 Lang/Ecstasy/Substring-Top-and-tail create mode 120000 Lang/Ecstasy/System-time create mode 120000 Lang/Elixir/Parallel-brute-force create mode 120000 Lang/Elm/Caesar-cipher create mode 120000 Lang/Emacs-Lisp/Abbreviations-automatic create mode 120000 Lang/Emacs-Lisp/Anagrams create mode 120000 Lang/Emacs-Lisp/Compare-length-of-two-strings create mode 120000 Lang/Emacs-Lisp/Date-manipulation create mode 120000 Lang/Emacs-Lisp/Determine-if-a-string-is-numeric create mode 120000 Lang/Emacs-Lisp/Determine-sentence-type create mode 120000 Lang/Emacs-Lisp/Ordered-words create mode 120000 Lang/Emacs-Lisp/Snake create mode 120000 Lang/Emacs-Lisp/Substitution-cipher create mode 120000 Lang/Fortran/Sleeping-Beauty-problem create mode 120000 Lang/Free-Pascal-Lazarus/Bin-given-limits create mode 120000 Lang/Free-Pascal-Lazarus/Closures-Value-capture create mode 120000 Lang/Free-Pascal-Lazarus/Parallel-calculations create mode 120000 Lang/FreeBASIC/B-zier-curves-Intersections create mode 120000 Lang/FreeBASIC/Constrained-genericity create mode 120000 Lang/FreeBASIC/Execute-Computer-Zero create mode 120000 Lang/FreeBASIC/Execute-SNUSP create mode 120000 Lang/FreeBASIC/Execute-a-Markov-algorithm create mode 120000 Lang/FreeBASIC/Imaginary-base-numbers create mode 120000 Lang/FreeBASIC/Nested-templated-data create mode 120000 Lang/FreeBASIC/Padovan-sequence create mode 120000 Lang/FreeBASIC/Pseudo-random-numbers-PCG32 create mode 120000 Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 create mode 120000 Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star create mode 120000 Lang/FreeBASIC/Runtime-evaluation-In-an-environment create mode 120000 Lang/FreeBASIC/Solve-the-no-connection-puzzle create mode 120000 Lang/FreeBASIC/Write-to-Windows-event-log create mode 120000 Lang/Frink/24-game create mode 120000 Lang/FutureBasic/24-game create mode 120000 Lang/FutureBasic/ASCII-art-diagram-converter create mode 120000 Lang/FutureBasic/Arbitrary-precision-integers-included- create mode 120000 Lang/FutureBasic/Biorhythms create mode 120000 Lang/FutureBasic/Brilliant-numbers create mode 120000 Lang/FutureBasic/Check-output-device-is-a-terminal create mode 120000 Lang/FutureBasic/Combinations create mode 120000 Lang/FutureBasic/Copy-stdin-to-stdout create mode 120000 Lang/FutureBasic/Determine-sentence-type create mode 120000 Lang/FutureBasic/Floyds-triangle create mode 120000 Lang/FutureBasic/Function-prototype create mode 120000 Lang/FutureBasic/Go-Fish create mode 120000 Lang/FutureBasic/Honeycombs create mode 120000 Lang/FutureBasic/Monty-Hall-problem create mode 120000 Lang/FutureBasic/Record-sound create mode 120000 Lang/GW-BASIC/Damm-algorithm create mode 120000 Lang/GW-BASIC/Display-a-linear-combination create mode 120000 Lang/GW-BASIC/Gray-code create mode 120000 Lang/GW-BASIC/Jensens-Device create mode 120000 Lang/GW-BASIC/Nested-templated-data create mode 120000 Lang/GW-BASIC/Primality-by-trial-division create mode 120000 Lang/GW-BASIC/Vector create mode 120000 Lang/Gambas/Jensens-Device create mode 120000 Lang/Gambas/M-bius-function create mode 120000 Lang/Gambas/Proper-divisors create mode 120000 Lang/Go/Factorial-primes create mode 120000 Lang/Java/Arena-storage-pool create mode 120000 Lang/Java/Bitcoin-public-point-to-address create mode 120000 Lang/Java/Catmull-Clark-subdivision-surface create mode 120000 Lang/Java/Compiler-virtual-machine-interpreter create mode 120000 Lang/Java/Im-a-software-engineer-get-me-out-of-here create mode 120000 Lang/Java/P-Adic-square-roots create mode 120000 Lang/Java/Topic-variable create mode 120000 Lang/Jq/2048 create mode 120000 Lang/Jq/24-game create mode 120000 Lang/Jq/Averages-Simple-moving-average create mode 120000 Lang/Jq/Bitwise-operations create mode 120000 Lang/Jq/CRC-32 create mode 120000 Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Jq/Deconvolution-1D create mode 120000 Lang/Jq/Display-an-outline-as-a-nested-table create mode 120000 Lang/Jq/Draw-a-cuboid create mode 120000 Lang/Jq/Entropy-Narcissist create mode 120000 Lang/Jq/Factors-of-a-Mersenne-number create mode 120000 Lang/Jq/File-size-distribution create mode 120000 Lang/Jq/Find-Chess960-starting-position-identifier create mode 120000 Lang/Jq/Find-duplicate-files create mode 120000 Lang/Jq/French-Republican-calendar create mode 120000 Lang/Jq/Generate-random-chess-position create mode 120000 Lang/Jq/Giuga-numbers create mode 120000 Lang/Jq/Graph-colouring create mode 120000 Lang/Jq/Introspection create mode 120000 Lang/Jq/Knights-tour create mode 120000 Lang/Jq/Levenshtein-distance-Alignment create mode 120000 Lang/Jq/Mayan-calendar create mode 120000 Lang/Jq/Mind-boggling-card-trick create mode 120000 Lang/Jq/Minimal-steps-down-to-1 create mode 120000 Lang/Jq/Modified-random-distribution create mode 120000 Lang/Jq/Multiplicative-order create mode 120000 Lang/Jq/Nonoblock create mode 120000 Lang/Jq/Nonogram-solver create mode 120000 Lang/Jq/P-value-correction create mode 120000 Lang/Jq/Palindromic-gapful-numbers create mode 120000 Lang/Jq/Peaceful-chess-queen-armies create mode 120000 Lang/Jq/Pentomino-tiling create mode 120000 Lang/Jq/Perlin-noise create mode 120000 Lang/Jq/Pisano-period create mode 120000 Lang/Jq/Poker-hand-analyser create mode 120000 Lang/Jq/Polynomial-regression create mode 120000 Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a create mode 120000 Lang/Jq/Pseudo-random-numbers-PCG32 create mode 120000 Lang/Jq/Pseudo-random-numbers-Xorshift-star create mode 120000 Lang/Jq/Ramer-Douglas-Peucker-line-simplification create mode 120000 Lang/Jq/Random-sentence-from-book create mode 120000 Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users create mode 120000 Lang/Jq/Set-puzzle create mode 120000 Lang/Jq/Set-right-adjacent-bits create mode 120000 Lang/Jq/Sierpinski-pentagon create mode 120000 Lang/Jq/Sleeping-Beauty-problem create mode 120000 Lang/Jq/Solve-a-Hidato-puzzle create mode 120000 Lang/Jq/Solve-a-Holy-Knights-tour create mode 120000 Lang/Jq/Solve-a-Numbrix-puzzle create mode 120000 Lang/Jq/Sort-an-outline-at-every-level create mode 120000 Lang/Jq/Thieles-interpolation-formula create mode 120000 Lang/Jq/Tic-tac-toe create mode 120000 Lang/Jq/War-card-game create mode 120000 Lang/Jq/Wordiff create mode 120000 Lang/K/Find-common-directory-path create mode 120000 Lang/K/Monty-Hall-problem create mode 120000 Lang/Kotlin/Compare-length-of-two-strings create mode 120000 Lang/Kotlin/Factorial-primes create mode 120000 Lang/Langur/Babbage-problem create mode 120000 Lang/Langur/I-before-E-except-after-C create mode 120000 Lang/Langur/Safe-addition create mode 120000 Lang/Langur/String-interpolation-included- create mode 120000 Lang/Liberty-BASIC/Poker-hand-analyser create mode 120000 Lang/Locomotive-Basic/Abelian-sandpile-model create mode 120000 Lang/Locomotive-Basic/Draw-a-cuboid create mode 120000 Lang/MACRO-11/Square-but-not-cube create mode 120000 Lang/Mia/Loops-While create mode 120000 Lang/Minimal-BASIC/Jensens-Device create mode 120000 Lang/Minimal-BASIC/Monty-Hall-problem create mode 120000 Lang/Modula-2/Gray-code create mode 120000 Lang/Modula-2/Monty-Hall-problem create mode 120000 Lang/Modula-3/Additive-primes create mode 120000 Lang/Nascom-BASIC/Damm-algorithm delete mode 120000 Lang/Oberon/100-doors create mode 120000 Lang/Odin/Quine create mode 120000 Lang/PHP/Water-collected-between-towers create mode 120000 Lang/PL-M/Draw-a-cuboid create mode 120000 Lang/PL-M/Nested-function create mode 120000 Lang/POV-Ray/Bitmap create mode 120000 Lang/POV-Ray/Maze-generation create mode 120000 Lang/Pascal/Count-the-coins create mode 120000 Lang/PascalABC.NET/15-puzzle-game create mode 120000 Lang/PascalABC.NET/99-bottles-of-beer create mode 120000 Lang/PascalABC.NET/A+B create mode 120000 Lang/PascalABC.NET/Abstract-type create mode 120000 Lang/PascalABC.NET/Accumulator-factory create mode 120000 Lang/PascalABC.NET/Ackermann-function create mode 120000 Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime create mode 120000 Lang/PascalABC.NET/Address-of-a-variable create mode 120000 Lang/PascalABC.NET/Anagrams create mode 120000 Lang/PascalABC.NET/Anonymous-recursion create mode 120000 Lang/PascalABC.NET/Apply-a-callback-to-an-array create mode 120000 Lang/PascalABC.NET/Arithmetic-Complex create mode 120000 Lang/PascalABC.NET/Arithmetic-Integer create mode 120000 Lang/PascalABC.NET/Array-concatenation create mode 120000 Lang/PascalABC.NET/Arrays create mode 120000 Lang/PascalABC.NET/Assertions create mode 120000 Lang/PascalABC.NET/Associative-array-Creation create mode 120000 Lang/PascalABC.NET/Associative-array-Iteration create mode 120000 Lang/PascalABC.NET/Balanced-brackets create mode 120000 Lang/PascalABC.NET/Binary-digits create mode 120000 Lang/PascalABC.NET/Binary-search create mode 120000 Lang/PascalABC.NET/Bitwise-operations create mode 120000 Lang/PascalABC.NET/Break-OO-privacy create mode 120000 Lang/PascalABC.NET/CSV-data-manipulation create mode 120000 Lang/PascalABC.NET/Calculating-the-value-of-e create mode 120000 Lang/PascalABC.NET/Call-an-object-method create mode 120000 Lang/PascalABC.NET/Character-codes create mode 120000 Lang/PascalABC.NET/Classes create mode 120000 Lang/PascalABC.NET/Closest-pair-problem create mode 120000 Lang/PascalABC.NET/Collections create mode 120000 Lang/PascalABC.NET/Command-line-arguments create mode 120000 Lang/PascalABC.NET/Comments create mode 120000 Lang/PascalABC.NET/Compare-a-list-of-strings create mode 120000 Lang/PascalABC.NET/Compare-length-of-two-strings create mode 120000 Lang/PascalABC.NET/Compound-data-type create mode 120000 Lang/PascalABC.NET/Concurrent-computing create mode 120000 Lang/PascalABC.NET/Conditional-structures create mode 120000 Lang/PascalABC.NET/Constrained-genericity create mode 120000 Lang/PascalABC.NET/Copy-a-string create mode 120000 Lang/PascalABC.NET/Copy-stdin-to-stdout create mode 120000 Lang/PascalABC.NET/Count-in-factors create mode 120000 Lang/PascalABC.NET/Count-in-octal create mode 120000 Lang/PascalABC.NET/Count-occurrences-of-a-substring create mode 120000 Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/PascalABC.NET/Create-an-object-at-a-given-address create mode 120000 Lang/PascalABC.NET/Date-format create mode 120000 Lang/PascalABC.NET/Day-of-the-week create mode 120000 Lang/PascalABC.NET/Define-a-primitive-data-type create mode 120000 Lang/PascalABC.NET/Determine-if-a-string-is-numeric create mode 120000 Lang/PascalABC.NET/Determine-sentence-type create mode 120000 Lang/PascalABC.NET/Doubly-linked-list-Definition create mode 120000 Lang/PascalABC.NET/Doubly-linked-list-Element-definition create mode 120000 Lang/PascalABC.NET/Doubly-linked-list-Element-insertion create mode 120000 Lang/PascalABC.NET/Doubly-linked-list-Traversal create mode 120000 Lang/PascalABC.NET/Dragon-curve create mode 120000 Lang/PascalABC.NET/Draw-a-pixel create mode 120000 Lang/PascalABC.NET/Draw-a-rotating-cube create mode 120000 Lang/PascalABC.NET/Empty-program create mode 120000 Lang/PascalABC.NET/Enumerations create mode 120000 Lang/PascalABC.NET/Even-or-odd create mode 120000 Lang/PascalABC.NET/Exceptions create mode 120000 Lang/PascalABC.NET/Extreme-floating-point-values create mode 120000 Lang/PascalABC.NET/Factorial create mode 120000 Lang/PascalABC.NET/Factors-of-an-integer create mode 120000 Lang/PascalABC.NET/File-input-output create mode 120000 Lang/PascalABC.NET/File-size create mode 120000 Lang/PascalABC.NET/Filter create mode 120000 Lang/PascalABC.NET/Find-common-directory-path create mode 120000 Lang/PascalABC.NET/Find-limit-of-recursion create mode 120000 Lang/PascalABC.NET/First-class-functions create mode 120000 Lang/PascalABC.NET/FizzBuzz create mode 120000 Lang/PascalABC.NET/Flatten-a-list create mode 120000 Lang/PascalABC.NET/Floyds-triangle create mode 120000 Lang/PascalABC.NET/Formatted-numeric-output create mode 120000 Lang/PascalABC.NET/Function-definition create mode 120000 Lang/PascalABC.NET/General-FizzBuzz create mode 120000 Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/PascalABC.NET/Generic-swap create mode 120000 Lang/PascalABC.NET/Greatest-common-divisor create mode 120000 Lang/PascalABC.NET/Guess-the-number create mode 120000 Lang/PascalABC.NET/Hash-from-two-arrays create mode 120000 Lang/PascalABC.NET/Hello-world-Line-printer create mode 120000 Lang/PascalABC.NET/Hello-world-Newline-omission create mode 120000 Lang/PascalABC.NET/Hello-world-Standard-error create mode 120000 Lang/PascalABC.NET/Identity-matrix create mode 120000 Lang/PascalABC.NET/Include-a-file create mode 120000 Lang/PascalABC.NET/Infinity create mode 120000 Lang/PascalABC.NET/Inheritance-Multiple create mode 120000 Lang/PascalABC.NET/Inheritance-Single create mode 120000 Lang/PascalABC.NET/Input-loop create mode 120000 Lang/PascalABC.NET/Integer-comparison create mode 120000 Lang/PascalABC.NET/JSON create mode 120000 Lang/PascalABC.NET/Jump-anywhere create mode 120000 Lang/PascalABC.NET/Knuth-shuffle create mode 120000 Lang/PascalABC.NET/Least-common-multiple create mode 120000 Lang/PascalABC.NET/List-comprehensions create mode 120000 Lang/PascalABC.NET/Literals-Floating-point create mode 120000 Lang/PascalABC.NET/Literals-String create mode 120000 Lang/PascalABC.NET/Longest-common-subsequence create mode 120000 Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/PascalABC.NET/Loops-Break create mode 120000 Lang/PascalABC.NET/Loops-Continue create mode 120000 Lang/PascalABC.NET/Loops-Do-while create mode 120000 Lang/PascalABC.NET/Loops-Downward-for create mode 120000 Lang/PascalABC.NET/Loops-For create mode 120000 Lang/PascalABC.NET/Loops-For-with-a-specified-step create mode 120000 Lang/PascalABC.NET/Loops-Foreach create mode 120000 Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/PascalABC.NET/Loops-N-plus-one-half create mode 120000 Lang/PascalABC.NET/Loops-Nested create mode 120000 Lang/PascalABC.NET/Loops-While create mode 120000 Lang/PascalABC.NET/Loops-With-multiple-ranges create mode 120000 Lang/PascalABC.NET/Loops-Wrong-ranges create mode 120000 Lang/PascalABC.NET/Man-or-boy-test create mode 120000 Lang/PascalABC.NET/Memory-allocation create mode 120000 Lang/PascalABC.NET/Mouse-position create mode 120000 Lang/PascalABC.NET/Nested-function create mode 120000 Lang/PascalABC.NET/Nth create mode 120000 Lang/PascalABC.NET/Null-object create mode 120000 Lang/PascalABC.NET/Object-serialization create mode 120000 Lang/PascalABC.NET/Palindrome-detection create mode 120000 Lang/PascalABC.NET/Parametric-polymorphism create mode 120000 Lang/PascalABC.NET/Pick-random-element create mode 120000 Lang/PascalABC.NET/Pointers-and-references create mode 120000 Lang/PascalABC.NET/Polymorphic-copy create mode 120000 Lang/PascalABC.NET/Polymorphism create mode 120000 Lang/PascalABC.NET/Power-set create mode 120000 Lang/PascalABC.NET/Primality-by-trial-division create mode 120000 Lang/PascalABC.NET/Prime-decomposition create mode 120000 Lang/PascalABC.NET/Program-name create mode 120000 Lang/PascalABC.NET/Program-termination create mode 120000 Lang/PascalABC.NET/Queue-Definition create mode 120000 Lang/PascalABC.NET/Queue-Usage create mode 120000 Lang/PascalABC.NET/Quine create mode 120000 Lang/PascalABC.NET/Quoting-constructs create mode 120000 Lang/PascalABC.NET/Radical-of-an-integer create mode 120000 Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 create mode 120000 Lang/PascalABC.NET/Read-a-file-line-by-line create mode 120000 Lang/PascalABC.NET/Read-a-specific-line-from-a-file create mode 120000 Lang/PascalABC.NET/Read-entire-file create mode 120000 Lang/PascalABC.NET/Real-constants-and-functions create mode 120000 Lang/PascalABC.NET/Reflection-List-methods create mode 120000 Lang/PascalABC.NET/Reflection-List-properties create mode 120000 Lang/PascalABC.NET/Regular-expressions create mode 120000 Lang/PascalABC.NET/Remove-duplicate-elements create mode 120000 Lang/PascalABC.NET/Remove-lines-from-a-file create mode 120000 Lang/PascalABC.NET/Rename-a-file create mode 120000 Lang/PascalABC.NET/Repeat create mode 120000 Lang/PascalABC.NET/Repeat-a-string create mode 120000 Lang/PascalABC.NET/Return-multiple-values create mode 120000 Lang/PascalABC.NET/Reverse-a-string create mode 120000 Lang/PascalABC.NET/Reverse-words-in-a-string create mode 120000 Lang/PascalABC.NET/Roman-numerals-Decode create mode 120000 Lang/PascalABC.NET/Roman-numerals-Encode create mode 120000 Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity create mode 120000 Lang/PascalABC.NET/Rot-13 create mode 120000 Lang/PascalABC.NET/Scope-modifiers create mode 120000 Lang/PascalABC.NET/Send-an-unknown-method-call create mode 120000 Lang/PascalABC.NET/Sequence-of-primes-by-trial-division create mode 120000 Lang/PascalABC.NET/Sieve-of-Eratosthenes create mode 120000 Lang/PascalABC.NET/Simple-windowed-application create mode 120000 Lang/PascalABC.NET/Singly-linked-list-Element-definition create mode 120000 Lang/PascalABC.NET/Singly-linked-list-Element-insertion create mode 120000 Lang/PascalABC.NET/Sleep create mode 120000 Lang/PascalABC.NET/Sort-an-array-of-composite-structures create mode 120000 Lang/PascalABC.NET/Sort-an-integer-array create mode 120000 Lang/PascalABC.NET/Sort-three-variables create mode 120000 Lang/PascalABC.NET/Sort-using-a-custom-comparator create mode 120000 Lang/PascalABC.NET/Sorting-algorithms-Quicksort create mode 120000 Lang/PascalABC.NET/Special-variables create mode 120000 Lang/PascalABC.NET/Stack create mode 120000 Lang/PascalABC.NET/Stack-traces create mode 120000 Lang/PascalABC.NET/String-append create mode 120000 Lang/PascalABC.NET/String-case create mode 120000 Lang/PascalABC.NET/String-concatenation create mode 120000 Lang/PascalABC.NET/String-interpolation-included- create mode 120000 Lang/PascalABC.NET/String-length create mode 120000 Lang/PascalABC.NET/String-matching create mode 120000 Lang/PascalABC.NET/String-prepend create mode 120000 Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/PascalABC.NET/Strip-block-comments create mode 120000 Lang/PascalABC.NET/Strip-comments-from-a-string create mode 120000 Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/PascalABC.NET/Substitution-cipher create mode 120000 Lang/PascalABC.NET/Substring create mode 120000 Lang/PascalABC.NET/Substring-Top-and-tail create mode 120000 Lang/PascalABC.NET/Sudan-function create mode 120000 Lang/PascalABC.NET/Sum-and-product-of-an-array create mode 120000 Lang/PascalABC.NET/Sum-digits-of-an-integer create mode 120000 Lang/PascalABC.NET/Sum-multiples-of-3-and-5 create mode 120000 Lang/PascalABC.NET/Sum-of-a-series create mode 120000 Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/PascalABC.NET/Sum-of-squares create mode 120000 Lang/PascalABC.NET/Symmetric-difference create mode 120000 Lang/PascalABC.NET/System-time create mode 120000 Lang/PascalABC.NET/Take-notes-on-the-command-line create mode 120000 Lang/PascalABC.NET/Tau-function create mode 120000 Lang/PascalABC.NET/Tau-number create mode 120000 Lang/PascalABC.NET/Temperature-conversion create mode 120000 Lang/PascalABC.NET/Terminal-control-Clear-the-screen create mode 120000 Lang/PascalABC.NET/Terminal-control-Coloured-text create mode 120000 Lang/PascalABC.NET/Terminal-control-Cursor-movement create mode 120000 Lang/PascalABC.NET/Terminal-control-Cursor-positioning create mode 120000 Lang/PascalABC.NET/Terminal-control-Dimensions create mode 120000 Lang/PascalABC.NET/Terminal-control-Display-an-extended-character create mode 120000 Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor create mode 120000 Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/PascalABC.NET/Test-a-function create mode 120000 Lang/PascalABC.NET/Time-a-function create mode 120000 Lang/PascalABC.NET/Tokenize-a-string create mode 120000 Lang/PascalABC.NET/Top-rank-per-group create mode 120000 Lang/PascalABC.NET/Towers-of-Hanoi create mode 120000 Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet create mode 120000 Lang/PascalABC.NET/Tree-datastructures create mode 120000 Lang/PascalABC.NET/Tree-traversal create mode 120000 Lang/PascalABC.NET/Trigonometric-functions create mode 120000 Lang/PascalABC.NET/Truncate-a-file create mode 120000 Lang/PascalABC.NET/Twos-complement create mode 120000 Lang/PascalABC.NET/URL-decoding create mode 120000 Lang/PascalABC.NET/URL-encoding create mode 120000 Lang/PascalABC.NET/Undefined-values create mode 120000 Lang/PascalABC.NET/Unicode-strings create mode 120000 Lang/PascalABC.NET/Unicode-variable-names create mode 120000 Lang/PascalABC.NET/User-input-Text create mode 120000 Lang/PascalABC.NET/Variables create mode 120000 Lang/PascalABC.NET/Variadic-function create mode 120000 Lang/PascalABC.NET/Vector create mode 120000 Lang/PascalABC.NET/Vector-products create mode 120000 Lang/PascalABC.NET/Walk-a-directory-Non-recursively create mode 120000 Lang/PascalABC.NET/Walk-a-directory-Recursively create mode 120000 Lang/PascalABC.NET/Window-creation create mode 120000 Lang/PascalABC.NET/Word-frequency create mode 120000 Lang/PascalABC.NET/Word-wrap create mode 120000 Lang/PascalABC.NET/Write-entire-file create mode 120000 Lang/PascalABC.NET/Write-to-Windows-event-log create mode 120000 Lang/PascalABC.NET/XML-DOM-serialization create mode 120000 Lang/PascalABC.NET/XML-Input create mode 120000 Lang/PascalABC.NET/XML-Output create mode 120000 Lang/PascalABC.NET/Zero-to-the-zero-power create mode 120000 Lang/Perl/Search-in-paragraphs-text create mode 120000 Lang/Prog8/Quine create mode 120000 Lang/PureBasic/M-bius-function create mode 120000 Lang/Python/Rhonda-numbers create mode 120000 Lang/QB64/Fibonacci-n-step-number-sequences create mode 120000 Lang/QB64/Multiple-regression create mode 120000 Lang/QB64/Price-fraction create mode 120000 Lang/QBasic/Display-a-linear-combination create mode 120000 Lang/QBasic/Fibonacci-n-step-number-sequences create mode 120000 Lang/QBasic/Jensens-Device create mode 120000 Lang/QBasic/Nested-templated-data create mode 120000 Lang/QBasic/Ramer-Douglas-Peucker-line-simplification create mode 120000 Lang/QBasic/Vector create mode 120000 Lang/Quackery/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Quackery/Distribution-of-0-digits-in-factorial-series create mode 120000 Lang/Quackery/Dutch-national-flag-problem create mode 120000 Lang/Quackery/Flipping-bits-game create mode 120000 Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m create mode 120000 Lang/Quackery/Password-generator create mode 120000 Lang/Quackery/Solve-the-no-connection-puzzle create mode 120000 Lang/QuickBASIC/Function-definition create mode 120000 Lang/QuickBASIC/Monty-Hall-problem create mode 120000 Lang/QuickBASIC/Random-numbers create mode 120000 Lang/QuickBASIC/Sorting-algorithms-Quicksort create mode 120000 Lang/R/Arithmetic-derivative create mode 120000 Lang/R/Compare-length-of-two-strings create mode 120000 Lang/R/Conjugate-transpose create mode 120000 Lang/R/Golden-ratio-Convergence create mode 120000 Lang/REXX/Eulers-constant-0.5772... create mode 120000 Lang/Refal/Copy-stdin-to-stdout create mode 120000 Lang/Refal/Damm-algorithm create mode 120000 Lang/Refal/Determine-sentence-type create mode 120000 Lang/Refal/Disarium-numbers create mode 120000 Lang/Refal/Discordian-date create mode 120000 Lang/Refal/Factors-of-an-integer create mode 120000 Lang/Refal/Flatten-a-list create mode 120000 Lang/Refal/General-FizzBuzz create mode 120000 Lang/Refal/Letter-frequency create mode 120000 Lang/Refal/McNuggets-problem create mode 120000 Lang/Refal/Nested-templated-data create mode 120000 Lang/Refal/One-dimensional-cellular-automata create mode 120000 Lang/Refal/Palindrome-detection create mode 120000 Lang/Refal/Population-count create mode 120000 Lang/Refal/Repeat create mode 120000 Lang/Refal/Split-a-character-string-based-on-change-of-character create mode 120000 Lang/Refal/Square-but-not-cube create mode 120000 Lang/Refal/Word-ladder create mode 120000 Lang/Run-BASIC/Nested-templated-data create mode 120000 Lang/S-BASIC/Copy-a-string create mode 120000 Lang/S-BASIC/Factorial create mode 120000 Lang/S-BASIC/Loops-Break create mode 120000 Lang/SETL/Brilliant-numbers create mode 120000 Lang/SETL/Damm-algorithm create mode 120000 Lang/SETL/General-FizzBuzz create mode 120000 Lang/SETL/Levenshtein-distance create mode 120000 Lang/SETL/Luhn-test-of-credit-card-numbers create mode 120000 Lang/SETL/Monty-Hall-problem create mode 120000 Lang/SETL/Nested-templated-data create mode 120000 Lang/SETL/Ordered-words create mode 120000 Lang/SETL/Pisano-period create mode 120000 Lang/SETL/Show-ASCII-table create mode 120000 Lang/SETL/Split-a-character-string-based-on-change-of-character create mode 120000 Lang/SETL/Word-ladder create mode 120000 Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers create mode 120000 Lang/Sidef/Jaro-Winkler-distance create mode 120000 Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes create mode 120000 Lang/Sidef/Smarandache-Wellin-primes create mode 120000 Lang/Sidef/Wagstaff-primes create mode 120000 Lang/Standard-ML/Call-a-foreign-language-function create mode 120000 Lang/Standard-ML/Pi delete mode 120000 Lang/SuperCollider/Semordnilap create mode 120000 Lang/Swift/Compare-length-of-two-strings create mode 120000 Lang/Swift/Pseudo-random-numbers-Splitmix64 delete mode 120000 Lang/Transd/Compare-length-of-two-strings create mode 120000 Lang/True-BASIC/100-prisoners create mode 120000 Lang/True-BASIC/Multiple-regression create mode 120000 Lang/True-BASIC/Vector create mode 120000 Lang/TypeScript/Deal-cards-for-FreeCell create mode 120000 Lang/UNIX-Shell/Pi create mode 120000 Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Uiua/15-puzzle-solver create mode 120000 Lang/Uiua/ADFGVX-cipher create mode 120000 Lang/Uiua/ASCII-art-diagram-converter create mode 120000 Lang/Uiua/Abbreviations-automatic create mode 120000 Lang/Uiua/Abelian-sandpile-model create mode 120000 Lang/Uiua/Align-columns create mode 120000 Lang/Uiua/Anti-primes create mode 120000 Lang/Uiua/Arithmetic-geometric-mean create mode 120000 Lang/Uiua/Array-concatenation create mode 120000 Lang/Uiua/Array-length create mode 120000 Lang/Uiua/Ascending-primes create mode 120000 Lang/Uiua/Averages-Mean-time-of-day create mode 120000 Lang/Uiua/Barnsley-fern create mode 120000 Lang/Uiua/Benfords-law create mode 120000 Lang/Uiua/Bifid-cipher create mode 120000 Lang/Uiua/Binary-digits create mode 120000 Lang/Uiua/Bulls-and-cows-Player create mode 120000 Lang/Uiua/CSV-data-manipulation create mode 120000 Lang/Uiua/Calkin-Wilf-sequence create mode 120000 Lang/Uiua/Cartesian-product-of-two-or-more-lists create mode 120000 Lang/Uiua/Combinations create mode 120000 Lang/Uiua/Convert-seconds-to-compound-duration create mode 120000 Lang/Uiua/Conways-Game-of-Life create mode 120000 Lang/Uiua/Determine-if-a-string-is-collapsible create mode 120000 Lang/Uiua/Dutch-national-flag-problem create mode 120000 Lang/Uiua/Factorial create mode 120000 Lang/Uiua/Factors-of-an-integer create mode 120000 Lang/Uiua/Find-the-missing-permutation create mode 120000 Lang/Uiua/Flatten-a-list create mode 120000 Lang/Uiua/Flipping-bits-game create mode 120000 Lang/Uiua/Forest-fire create mode 120000 Lang/Uiua/Greatest-common-divisor create mode 120000 Lang/Uiua/Identity-matrix create mode 120000 Lang/Uiua/Increment-a-numerical-string create mode 120000 Lang/Uiua/Integer-sequence create mode 120000 Lang/Uiua/Langtons-ant create mode 120000 Lang/Uiua/Largest-int-from-concatenated-ints create mode 120000 Lang/Uiua/Least-common-multiple create mode 120000 Lang/Uiua/Levenshtein-distance create mode 120000 Lang/Uiua/List-comprehensions create mode 120000 Lang/Uiua/Look-and-say-sequence create mode 120000 Lang/Uiua/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Uiua/Luhn-test-of-credit-card-numbers create mode 120000 Lang/Uiua/Mandelbrot-set create mode 120000 Lang/Uiua/Matrix-multiplication create mode 120000 Lang/Uiua/Maze-solving create mode 120000 Lang/Uiua/McNuggets-problem create mode 120000 Lang/Uiua/Middle-three-digits create mode 120000 Lang/Uiua/Motzkin-numbers create mode 120000 Lang/Uiua/N-queens-problem create mode 120000 Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares create mode 120000 Lang/Uiua/One-dimensional-cellular-automata create mode 120000 Lang/Uiua/Ordered-words create mode 120000 Lang/Uiua/Permutations create mode 120000 Lang/Uiua/Pick-random-element create mode 120000 Lang/Uiua/RPG-attributes-generator create mode 120000 Lang/Uiua/Random-numbers create mode 120000 Lang/Uiua/Run-length-encoding create mode 120000 Lang/Uiua/Smith-numbers create mode 120000 Lang/Uiua/Solve-a-Hidato-puzzle create mode 120000 Lang/Uiua/Solve-a-Numbrix-puzzle create mode 120000 Lang/Uiua/Sort-disjoint-sublist create mode 120000 Lang/Uiua/Split-a-character-string-based-on-change-of-character create mode 120000 Lang/Uiua/Square-free-integers create mode 120000 Lang/Uiua/Stem-and-leaf-plot create mode 120000 Lang/Uiua/String-case create mode 120000 Lang/Uiua/String-concatenation create mode 120000 Lang/Uiua/String-interpolation-included- create mode 120000 Lang/Uiua/String-matching create mode 120000 Lang/Uiua/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Uiua/Sudoku create mode 120000 Lang/Uiua/Sum-multiples-of-3-and-5 create mode 120000 Lang/Uiua/Summarize-primes create mode 120000 Lang/Uiua/Test-a-function create mode 120000 Lang/Uiua/Truncatable-primes create mode 120000 Lang/Uiua/Validate-International-Securities-Identification-Number create mode 120000 Lang/Uiua/Water-collected-between-towers create mode 120000 Lang/Uiua/Yellowstone-sequence create mode 120000 Lang/Uiua/Zebra-puzzle create mode 120000 Lang/Uxntal/Quine create mode 120000 Lang/Uxntal/Weird-numbers create mode 120000 Lang/Vim-Script/Hello-world-Graphical create mode 120000 Lang/Vim-Script/Here-document create mode 120000 Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Vim-Script/Loops-For create mode 120000 Lang/Vim-Script/XML-Input create mode 120000 Lang/XBasic/Euler-method create mode 120000 Lang/XBasic/M-bius-function create mode 120000 Lang/XBasic/Nim-game create mode 120000 Lang/XBasic/Sorting-algorithms-Quicksort create mode 120000 Lang/XPL0/Draw-a-clock create mode 120000 Lang/XPL0/Poker-hand-analyser create mode 120000 Lang/Yabasic/Display-a-linear-combination create mode 120000 Lang/Yabasic/Kronecker-product create mode 120000 Lang/Yabasic/Multiple-regression create mode 120000 Lang/Yabasic/Nested-templated-data create mode 120000 Lang/Yabasic/Sexy-primes create mode 120000 Lang/Yabasic/Sorting-algorithms-Counting-sort create mode 120000 Lang/Yabasic/Sorting-algorithms-Stooge-sort create mode 120000 Lang/Zig/15-puzzle-game create mode 120000 Lang/Zig/9-billion-names-of-God-the-integer create mode 120000 Lang/Zig/A+B create mode 120000 Lang/Zig/Determine-if-a-string-is-numeric create mode 120000 Lang/Zig/Egyptian-division create mode 120000 Lang/Zig/Integer-sequence create mode 120000 Lang/Zig/Monty-Hall-problem create mode 120000 Lang/Zig/Solve-the-no-connection-puzzle create mode 100644 Task/100-doors/APL/100-doors-3.apl delete mode 100644 Task/100-doors/Oberon/100-doors.oberon create mode 100644 Task/100-doors/V-(Vlang)/100-doors-3.v create mode 100644 Task/100-prisoners/Ecstasy/100-prisoners.ecstasy create mode 100644 Task/100-prisoners/True-BASIC/100-prisoners.basic create mode 100644 Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas create mode 100644 Task/15-puzzle-game/Zig/15-puzzle-game.zig create mode 100644 Task/15-puzzle-solver/Dart/15-puzzle-solver.dart create mode 100644 Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua create mode 100644 Task/2048/Jq/2048.jq create mode 100644 Task/24-game/Frink/24-game.frink create mode 100644 Task/24-game/FutureBasic/24-game.basic create mode 100644 Task/24-game/Jq/24-game.jq rename Task/4-rings-or-4-squares-puzzle/V-(Vlang)/{4-rings-or-4-squares-puzzle.v => 4-rings-or-4-squares-puzzle-1.v} (100%) create mode 100644 Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v create mode 100644 Task/4-rings-or-4-squares-puzzle/Zig/4-rings-or-4-squares-puzzle-6.zig create mode 100644 Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-1.zig create mode 100644 Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig create mode 100644 Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th create mode 100644 Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th delete mode 100644 Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th rename Task/99-bottles-of-beer/Oxygene/{99-bottles-of-beer.oxy => 99-bottles-of-beer-1.oxy} (100%) create mode 100644 Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy create mode 100644 Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas create mode 100644 Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas create mode 100644 Task/A+B/PascalABC.NET/a+b.pas create mode 100644 Task/A+B/Zig/a+b.zig create mode 100644 Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua create mode 100644 Task/ASCII-art-diagram-converter/FutureBasic/ascii-art-diagram-converter.basic create mode 100644 Task/ASCII-art-diagram-converter/Uiua/ascii-art-diagram-converter.uiua create mode 100644 Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.l create mode 100644 Task/Abbreviations-automatic/Uiua/abbreviations-automatic.uiua create mode 100644 Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy create mode 100644 Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.ada create mode 100644 Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy create mode 100644 Task/Abelian-sandpile-model/Locomotive-Basic/abelian-sandpile-model.basic create mode 100644 Task/Abelian-sandpile-model/Uiua/abelian-sandpile-model.uiua create mode 100644 Task/Abstract-type/PascalABC.NET/abstract-type-1.pas create mode 100644 Task/Abstract-type/PascalABC.NET/abstract-type-2.pas create mode 100644 Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas create mode 100644 Task/Achilles-numbers/Ada/achilles-numbers.ada create mode 100644 Task/Ackermann-function/PascalABC.NET/ackermann-function.pas create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas create mode 100644 Task/Additive-primes/C-sharp/additive-primes.cs create mode 100644 Task/Additive-primes/Modula-3/additive-primes.mod3 create mode 100644 Task/Address-of-a-variable/PascalABC.NET/address-of-a-variable.pas create mode 100644 Task/Align-columns/Uiua/align-columns.uiua create mode 100644 Task/Anagrams/Emacs-Lisp/anagrams-1.l create mode 100644 Task/Anagrams/Emacs-Lisp/anagrams-2.l create mode 100644 Task/Anagrams/PascalABC.NET/anagrams.pas create mode 100644 Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-1.pas create mode 100644 Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-2.pas create mode 100644 Task/Anti-primes/Uiua/anti-primes.uiua create mode 100644 Task/Apply-a-callback-to-an-array/PascalABC.NET/apply-a-callback-to-an-array.pas create mode 100644 Task/Approximate-equality/EasyLang/approximate-equality.easy create mode 100644 Task/Arbitrary-precision-integers-included-/FutureBasic/arbitrary-precision-integers-included-.basic create mode 100644 Task/Arena-storage-pool/Java/arena-storage-pool.java create mode 100644 Task/Arithmetic-Complex/EasyLang/arithmetic-complex.easy create mode 100644 Task/Arithmetic-Complex/PascalABC.NET/arithmetic-complex.pas create mode 100644 Task/Arithmetic-Integer/PascalABC.NET/arithmetic-integer.pas create mode 100644 Task/Arithmetic-derivative/R/arithmetic-derivative.r create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Ada/arithmetic-geometric-mean-calculate-pi.ada create mode 100644 Task/Arithmetic-geometric-mean/Uiua/arithmetic-geometric-mean.uiua create mode 100644 Task/Array-concatenation/PascalABC.NET/array-concatenation.pas create mode 100644 Task/Array-concatenation/Uiua/array-concatenation.uiua rename Task/Array-length/PascalABC.NET/{array-length.pas => array-length-1.pas} (100%) create mode 100644 Task/Array-length/PascalABC.NET/array-length-2.pas create mode 100644 Task/Array-length/Uiua/array-length.uiua create mode 100644 Task/Arrays/PascalABC.NET/arrays.pas create mode 100644 Task/Ascending-primes/Ada/ascending-primes.ada create mode 100644 Task/Ascending-primes/Uiua/ascending-primes.uiua create mode 100644 Task/Assertions/Ecstasy/assertions.ecstasy create mode 100644 Task/Assertions/PascalABC.NET/assertions.pas create mode 100644 Task/Associative-array-Creation/PascalABC.NET/associative-array-creation.pas create mode 100644 Task/Associative-array-Iteration/PascalABC.NET/associative-array-iteration.pas create mode 100644 Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua create mode 100644 Task/Averages-Simple-moving-average/Jq/averages-simple-moving-average.jq create mode 100644 Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-1.basic create mode 100644 Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-2.basic create mode 100644 Task/Babbage-problem/EMal/babbage-problem.emal create mode 100644 Task/Babbage-problem/Langur/babbage-problem.langur create mode 100644 Task/Balanced-brackets/PascalABC.NET/balanced-brackets.pas create mode 100644 Task/Barnsley-fern/Uiua/barnsley-fern.uiua create mode 100644 Task/Benfords-law/Uiua/benfords-law.uiua create mode 100644 Task/Bifid-cipher/EMal/bifid-cipher.emal create mode 100644 Task/Bifid-cipher/Uiua/bifid-cipher-1.uiua create mode 100644 Task/Bifid-cipher/Uiua/bifid-cipher-2.uiua create mode 100644 Task/Bin-given-limits/Free-Pascal-Lazarus/bin-given-limits.pas create mode 100644 Task/Binary-digits/PascalABC.NET/binary-digits.pas create mode 100644 Task/Binary-digits/Uiua/binary-digits.uiua create mode 100644 Task/Binary-search/PascalABC.NET/binary-search.pas create mode 100644 Task/Biorhythms/FutureBasic/biorhythms.basic create mode 100644 Task/Bitcoin-address-validation/C++/bitcoin-address-validation.cpp rename Task/Bitcoin-address-validation/Java/{bitcoin-address-validation.java => bitcoin-address-validation-1.java} (100%) create mode 100644 Task/Bitcoin-address-validation/Java/bitcoin-address-validation-2.java create mode 100644 Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp create mode 100644 Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java create mode 100644 Task/Bitmap/POV-Ray/bitmap.povray create mode 100644 Task/Bitwise-operations/Jq/bitwise-operations.jq create mode 100644 Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas create mode 100644 Task/Blum-integer/Common-Lisp/blum-integer.lisp create mode 100644 Task/Brace-expansion/Ada/brace-expansion.ada create mode 100644 Task/Break-OO-privacy/PascalABC.NET/break-oo-privacy.pas create mode 100644 Task/Brilliant-numbers/FutureBasic/brilliant-numbers.basic create mode 100644 Task/Brilliant-numbers/SETL/brilliant-numbers.setl create mode 100644 Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua create mode 100644 Task/CRC-32/Jq/crc-32-1.jq create mode 100644 Task/CRC-32/Jq/crc-32-2.jq create mode 100644 Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas create mode 100644 Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua create mode 100644 Task/Caesar-cipher/Elm/caesar-cipher.elm create mode 100644 Task/Calculating-the-value-of-e/PascalABC.NET/calculating-the-value-of-e.pas create mode 100644 Task/Calkin-Wilf-sequence/Uiua/calkin-wilf-sequence.uiua create mode 100644 Task/Call-a-foreign-language-function/Standard-ML/call-a-foreign-language-function.ml delete mode 100644 Task/Call-a-function/Langur/call-a-function-7.langur create mode 100644 Task/Call-an-object-method/PascalABC.NET/call-an-object-method.pas create mode 100644 Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua create mode 100644 Task/Catmull-Clark-subdivision-surface/C++/catmull-clark-subdivision-surface.cpp create mode 100644 Task/Catmull-Clark-subdivision-surface/Java/catmull-clark-subdivision-surface.java create mode 100644 Task/Character-codes/PascalABC.NET/character-codes.pas create mode 100644 Task/Check-output-device-is-a-terminal/FutureBasic/check-output-device-is-a-terminal.basic create mode 100644 Task/Classes/PascalABC.NET/classes.pas create mode 100644 Task/Closest-pair-problem/PascalABC.NET/closest-pair-problem.pas create mode 100644 Task/Closures-Value-capture/Free-Pascal-Lazarus/closures-value-capture.pas rename Task/Closures-Value-capture/Go/{closures-value-capture.go => closures-value-capture-1.go} (100%) create mode 100644 Task/Closures-Value-capture/Go/closures-value-capture-2.go create mode 100644 Task/Collections/PascalABC.NET/collections.pas create mode 100644 Task/Color-wheel/Ada/color-wheel.ada create mode 100644 Task/Combinations-and-permutations/Ada/combinations-and-permutations.ada create mode 100644 Task/Combinations/FutureBasic/combinations.basic create mode 100644 Task/Combinations/J/combinations-10.j create mode 100644 Task/Combinations/J/combinations-8.j create mode 100644 Task/Combinations/J/combinations-9.j create mode 100644 Task/Combinations/Uiua/combinations.uiua create mode 100644 Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas create mode 100644 Task/Comments/PascalABC.NET/comments.pas create mode 100644 Task/Compare-a-list-of-strings/PascalABC.NET/compare-a-list-of-strings.pas create mode 100644 Task/Compare-length-of-two-strings/Emacs-Lisp/compare-length-of-two-strings.l create mode 100644 Task/Compare-length-of-two-strings/Kotlin/compare-length-of-two-strings.kotlin create mode 100644 Task/Compare-length-of-two-strings/PascalABC.NET/compare-length-of-two-strings.pas create mode 100644 Task/Compare-length-of-two-strings/R/compare-length-of-two-strings.r create mode 100644 Task/Compare-length-of-two-strings/Swift/compare-length-of-two-strings.swift delete mode 100644 Task/Compare-length-of-two-strings/Transd/compare-length-of-two-strings.transd create mode 100644 Task/Compiler-virtual-machine-interpreter/C++/compiler-virtual-machine-interpreter.cpp create mode 100644 Task/Compiler-virtual-machine-interpreter/Java/compiler-virtual-machine-interpreter.java create mode 100644 Task/Compound-data-type/PascalABC.NET/compound-data-type.pas create mode 100644 Task/Concurrent-computing/PascalABC.NET/concurrent-computing.pas create mode 100644 Task/Conditional-structures/PascalABC.NET/conditional-structures.pas create mode 100644 Task/Conjugate-transpose/R/conjugate-transpose.r create mode 100644 Task/Constrained-genericity/FreeBASIC/constrained-genericity.basic create mode 100644 Task/Constrained-genericity/PascalABC.NET/constrained-genericity.pas create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Jq/continued-fraction-arithmetic-construct-from-rational-number.jq create mode 100644 Task/Convert-seconds-to-compound-duration/Uiua/convert-seconds-to-compound-duration.uiua create mode 100644 Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua create mode 100644 Task/Copy-a-string/PascalABC.NET/copy-a-string.pas create mode 100644 Task/Copy-a-string/S-BASIC/copy-a-string.basic create mode 100644 Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic rename Task/Copy-stdin-to-stdout/Java/{copy-stdin-to-stdout.java => copy-stdin-to-stdout-1.java} (100%) create mode 100644 Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java create mode 100644 Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas create mode 100644 Task/Copy-stdin-to-stdout/Refal/copy-stdin-to-stdout.refal create mode 100644 Task/Count-in-factors/PascalABC.NET/count-in-factors.pas create mode 100644 Task/Count-in-octal/PascalABC.NET/count-in-octal.pas create mode 100644 Task/Count-occurrences-of-a-substring/PascalABC.NET/count-occurrences-of-a-substring.pas rename Task/Count-the-coins/Ada/{count-the-coins.ada => count-the-coins-1.ada} (100%) create mode 100644 Task/Count-the-coins/Ada/count-the-coins-2.ada create mode 100644 Task/Count-the-coins/Pascal/count-the-coins.pas create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/PascalABC.NET/create-a-two-dimensional-array-at-runtime.pas create mode 100644 Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas create mode 100644 Task/Cyclops-numbers/C-sharp/cyclops-numbers.cs create mode 100644 Task/Damm-algorithm/ANSI-BASIC/damm-algorithm.basic rename Task/Damm-algorithm/{BASIC => GW-BASIC}/damm-algorithm.basic (100%) create mode 100644 Task/Damm-algorithm/Nascom-BASIC/damm-algorithm.basic create mode 100644 Task/Damm-algorithm/Refal/damm-algorithm.refal create mode 100644 Task/Damm-algorithm/SETL/damm-algorithm.setl delete mode 100644 Task/Date-format/Langur/date-format-3.langur create mode 100644 Task/Date-format/PascalABC.NET/date-format.pas create mode 100644 Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.l create mode 100644 Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.l create mode 100644 Task/Day-of-the-week/PascalABC.NET/day-of-the-week.pas create mode 100644 Task/Deal-cards-for-FreeCell/TypeScript/deal-cards-for-freecell.ts create mode 100644 Task/Deconvolution-1D/Jq/deconvolution-1d.jq create mode 100644 Task/Define-a-primitive-data-type/PascalABC.NET/define-a-primitive-data-type.pas create mode 100644 Task/Determine-if-a-string-is-collapsible/Uiua/determine-if-a-string-is-collapsible.uiua create mode 100644 Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-1.l create mode 100644 Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-2.l create mode 100644 Task/Determine-if-a-string-is-numeric/PascalABC.NET/determine-if-a-string-is-numeric.pas rename Task/Determine-if-a-string-is-numeric/Rust/{determine-if-a-string-is-numeric.rust => determine-if-a-string-is-numeric-1.rust} (100%) create mode 100644 Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric-2.rust create mode 100644 Task/Determine-if-a-string-is-numeric/Zig/determine-if-a-string-is-numeric.zig create mode 100644 Task/Determine-sentence-type/Emacs-Lisp/determine-sentence-type.l create mode 100644 Task/Determine-sentence-type/FutureBasic/determine-sentence-type.basic create mode 100644 Task/Determine-sentence-type/PascalABC.NET/determine-sentence-type.pas create mode 100644 Task/Determine-sentence-type/Refal/determine-sentence-type.refal create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Quackery/dinesmans-multiple-dwelling-problem.quackery create mode 100644 Task/Disarium-numbers/Refal/disarium-numbers.refal create mode 100644 Task/Discordian-date/Refal/discordian-date.refal create mode 100644 Task/Display-a-linear-combination/APL/display-a-linear-combination.apl create mode 100644 Task/Display-a-linear-combination/Applesoft-BASIC/display-a-linear-combination.basic create mode 100644 Task/Display-a-linear-combination/Chipmunk-Basic/display-a-linear-combination.basic create mode 100644 Task/Display-a-linear-combination/Cowgol/display-a-linear-combination.cowgol create mode 100644 Task/Display-a-linear-combination/Draco/display-a-linear-combination.draco create mode 100644 Task/Display-a-linear-combination/GW-BASIC/display-a-linear-combination.basic create mode 100644 Task/Display-a-linear-combination/QBasic/display-a-linear-combination.basic create mode 100644 Task/Display-a-linear-combination/Yabasic/display-a-linear-combination.basic create mode 100644 Task/Display-an-outline-as-a-nested-table/Jq/display-an-outline-as-a-nested-table.jq create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/Quackery/distribution-of-0-digits-in-factorial-series.quackery create mode 100644 Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas create mode 100644 Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas create mode 100644 Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas create mode 100644 Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas create mode 100644 Task/Dragon-curve/PascalABC.NET/dragon-curve.pas create mode 100644 Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 create mode 100644 Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg create mode 100644 Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq create mode 100644 Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic create mode 100644 Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm create mode 100644 Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas create mode 100644 Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas rename Task/Draw-a-sphere/Locomotive-Basic/{draw-a-sphere.basic => draw-a-sphere-1.basic} (100%) create mode 100644 Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic create mode 100644 Task/Dutch-national-flag-problem/Quackery/dutch-national-flag-problem.quackery create mode 100644 Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua create mode 100644 Task/Egyptian-division/Zig/egyptian-division.zig create mode 100644 Task/Empty-program/PascalABC.NET/empty-program.pas create mode 100644 Task/Entropy-Narcissist/Jq/entropy-narcissist.jq create mode 100644 Task/Enumerations/PascalABC.NET/enumerations.pas delete mode 100644 Task/Environment-variables/Langur/environment-variables-1.langur rename Task/Environment-variables/Langur/{environment-variables-2.langur => environment-variables.langur} (100%) create mode 100644 Task/Euler-method/XBasic/euler-method.basic create mode 100644 Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg create mode 100644 Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....ada create mode 100644 Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx create mode 100644 Task/Even-or-odd/PascalABC.NET/even-or-odd.pas create mode 100644 Task/Exceptions/PascalABC.NET/exceptions-1.pas create mode 100644 Task/Exceptions/PascalABC.NET/exceptions-2.pas create mode 100644 Task/Exceptions/PascalABC.NET/exceptions-3.pas create mode 100644 Task/Execute-Computer-Zero/FreeBASIC/execute-computer-zero.basic create mode 100644 Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic create mode 100644 Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic delete mode 100644 Task/Extend-your-language/Langur/extend-your-language-2.langur rename Task/Extend-your-language/Langur/{extend-your-language-1.langur => extend-your-language.langur} (86%) create mode 100644 Task/Extreme-floating-point-values/PascalABC.NET/extreme-floating-point-values.pas create mode 100644 Task/FTP/Ada/ftp.ada create mode 100644 Task/Factorial-base-numbers-indexing-permutations-of-a-collection/C++/factorial-base-numbers-indexing-permutations-of-a-collection.cpp create mode 100644 Task/Factorial-primes/Common-Lisp/factorial-primes.lisp create mode 100644 Task/Factorial-primes/Go/factorial-primes.go create mode 100644 Task/Factorial-primes/Kotlin/factorial-primes.kotlin create mode 100644 Task/Factorial/PascalABC.NET/factorial.pas create mode 100644 Task/Factorial/S-BASIC/factorial-1.basic create mode 100644 Task/Factorial/S-BASIC/factorial-2.basic create mode 100644 Task/Factorial/Uiua/factorial.uiua create mode 100644 Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq create mode 100644 Task/Factors-of-an-integer/PascalABC.NET/factors-of-an-integer.pas create mode 100644 Task/Factors-of-an-integer/Refal/factors-of-an-integer.refal create mode 100644 Task/Factors-of-an-integer/Uiua/factors-of-an-integer.uiua rename Task/Feigenbaum-constant-calculation/REXX/{feigenbaum-constant-calculation.rexx => feigenbaum-constant-calculation-1.rexx} (100%) create mode 100644 Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx create mode 100644 Task/Fibonacci-n-step-number-sequences/Chipmunk-Basic/fibonacci-n-step-number-sequences.basic create mode 100644 Task/Fibonacci-n-step-number-sequences/QB64/fibonacci-n-step-number-sequences.qb64 create mode 100644 Task/Fibonacci-n-step-number-sequences/QBasic/fibonacci-n-step-number-sequences.basic create mode 100644 Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs create mode 100644 Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-19.parigp create mode 100644 Task/File-input-output/PascalABC.NET/file-input-output.pas create mode 100644 Task/File-size-distribution/Jq/file-size-distribution.jq create mode 100644 Task/File-size/PascalABC.NET/file-size.pas create mode 100644 Task/Filter/PascalABC.NET/filter.pas create mode 100644 Task/Find-Chess960-starting-position-identifier/Jq/find-chess960-starting-position-identifier.jq create mode 100644 Task/Find-common-directory-path/K/find-common-directory-path.k create mode 100644 Task/Find-common-directory-path/PascalABC.NET/find-common-directory-path.pas create mode 100644 Task/Find-duplicate-files/Jq/find-duplicate-files.jq create mode 100644 Task/Find-limit-of-recursion/PascalABC.NET/find-limit-of-recursion.pas create mode 100644 Task/Find-the-intersection-of-two-lines/ALGOL-W/find-the-intersection-of-two-lines.alg create mode 100644 Task/Find-the-intersection-of-two-lines/Python/find-the-intersection-of-two-lines-4.py create mode 100644 Task/Find-the-missing-permutation/Uiua/find-the-missing-permutation.uiua create mode 100644 Task/First-class-functions/PascalABC.NET/first-class-functions.pas create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-9.lisp delete mode 100644 Task/FizzBuzz/Langur/fizzbuzz-1.langur delete mode 100644 Task/FizzBuzz/Langur/fizzbuzz-2.langur create mode 100644 Task/FizzBuzz/Langur/fizzbuzz.langur create mode 100644 Task/FizzBuzz/PascalABC.NET/fizzbuzz.pas rename Task/Flatten-a-list/Emacs-Lisp/{flatten-a-list.l => flatten-a-list-1.l} (100%) create mode 100644 Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-2.l create mode 100644 Task/Flatten-a-list/PascalABC.NET/flatten-a-list.pas create mode 100644 Task/Flatten-a-list/Refal/flatten-a-list.refal create mode 100644 Task/Flatten-a-list/Uiua/flatten-a-list.uiua create mode 100644 Task/Flipping-bits-game/Quackery/flipping-bits-game.quackery create mode 100644 Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua create mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-4.ada create mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-5.ada create mode 100644 Task/Floyds-triangle/FutureBasic/floyds-triangle.basic create mode 100644 Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas create mode 100644 Task/Forest-fire/Uiua/forest-fire.uiua create mode 100644 Task/Formatted-numeric-output/ANSI-BASIC/formatted-numeric-output.basic create mode 100644 Task/Formatted-numeric-output/PascalABC.NET/formatted-numeric-output.pas create mode 100644 Task/French-Republican-calendar/Jq/french-republican-calendar.jq create mode 100644 Task/Function-definition/ANSI-BASIC/function-definition.basic create mode 100644 Task/Function-definition/Chapel/function-definition-1.chapel create mode 100644 Task/Function-definition/Chapel/function-definition-2.chapel delete mode 100644 Task/Function-definition/Langur/function-definition-4.langur delete mode 100644 Task/Function-definition/Langur/function-definition-5.langur create mode 100644 Task/Function-definition/PascalABC.NET/function-definition.pas rename Task/Function-definition/{BASIC => QuickBASIC}/function-definition.basic (100%) create mode 100644 Task/Function-prototype/FutureBasic/function-prototype.basic create mode 100644 Task/Gamma-function/REXX/gamma-function-3.rexx create mode 100644 Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas create mode 100644 Task/General-FizzBuzz/Refal/general-fizzbuzz.refal create mode 100644 Task/General-FizzBuzz/SETL/general-fizzbuzz.setl create mode 100644 Task/Generate-lower-case-ASCII-alphabet/PascalABC.NET/generate-lower-case-ascii-alphabet.pas create mode 100644 Task/Generate-random-chess-position/Jq/generate-random-chess-position.jq create mode 100644 Task/Generic-swap/PascalABC.NET/generic-swap.pas create mode 100644 Task/Giuga-numbers/Jq/giuga-numbers.jq create mode 100644 Task/Go-Fish/FutureBasic/go-fish.basic create mode 100644 Task/Golden-ratio-Convergence/R/golden-ratio-convergence.r create mode 100644 Task/Graph-colouring/Jq/graph-colouring.jq rename Task/Gray-code/{BASIC => GW-BASIC}/gray-code.basic (100%) create mode 100644 Task/Gray-code/Modula-2/gray-code.mod2 create mode 100644 Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas rename Task/Greatest-common-divisor/{TypeScript/greatest-common-divisor-3.ts => Uiua/greatest-common-divisor.uiua} (100%) create mode 100644 Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy create mode 100644 Task/Guess-the-number-With-feedback-player-/EasyLang/guess-the-number-with-feedback-player-.easy create mode 100644 Task/Guess-the-number/PascalABC.NET/guess-the-number.pas create mode 100644 Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy create mode 100644 Task/Hamming-numbers/EasyLang/hamming-numbers.easy create mode 100644 Task/Harmonic-series/Bruijn/harmonic-series.bruijn create mode 100644 Task/Hash-from-two-arrays/PascalABC.NET/hash-from-two-arrays.pas rename Task/Hello-world-Graphical/{AutoHotKey-V2 => Autohotkey-V2}/hello-world-graphical.ahk (100%) create mode 100644 Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-1.vim create mode 100644 Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-2.vim create mode 100644 Task/Hello-world-Line-printer/PascalABC.NET/hello-world-line-printer.pas create mode 100644 Task/Hello-world-Newline-omission/PascalABC.NET/hello-world-newline-omission.pas create mode 100644 Task/Hello-world-Standard-error/PascalABC.NET/hello-world-standard-error.pas rename Task/Hello-world-Text/PascalABC.NET/{hello-world-text.pas => hello-world-text-1.pas} (100%) create mode 100644 Task/Hello-world-Text/PascalABC.NET/hello-world-text-2.pas create mode 100644 Task/Hello-world-Text/PascalABC.NET/hello-world-text-3.pas create mode 100644 Task/Here-document/Vim-Script/here-document-1.vim create mode 100644 Task/Here-document/Vim-Script/here-document-2.vim create mode 100644 Task/Hex-words/Ada/hex-words.ada create mode 100644 Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy create mode 100644 Task/Honeycombs/FutureBasic/honeycombs.basic create mode 100644 Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c create mode 100644 Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur create mode 100644 Task/IBAN/EasyLang/iban.easy create mode 100644 Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml rename Task/ISBN13-check-digit/Standard-ML/{isbn13-check-digit.ml => isbn13-check-digit-2.ml} (98%) create mode 100644 Task/Identity-matrix/PascalABC.NET/identity-matrix.pas create mode 100644 Task/Identity-matrix/Uiua/identity-matrix.uiua create mode 100644 Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.ada create mode 100644 Task/Im-a-software-engineer-get-me-out-of-here/C++/im-a-software-engineer-get-me-out-of-here.cpp create mode 100644 Task/Im-a-software-engineer-get-me-out-of-here/Java/im-a-software-engineer-get-me-out-of-here.java create mode 100644 Task/Imaginary-base-numbers/FreeBASIC/imaginary-base-numbers.basic create mode 100644 Task/Include-a-file/PascalABC.NET/include-a-file-1.pas create mode 100644 Task/Include-a-file/PascalABC.NET/include-a-file-2.pas create mode 100644 Task/Increasing-gaps-between-consecutive-Niven-numbers/Sidef/increasing-gaps-between-consecutive-niven-numbers.sidef create mode 100644 Task/Increment-a-numerical-string/Uiua/increment-a-numerical-string.uiua create mode 100644 Task/Infinity/PascalABC.NET/infinity.pas create mode 100644 Task/Inheritance-Multiple/PascalABC.NET/inheritance-multiple.pas create mode 100644 Task/Inheritance-Single/PascalABC.NET/inheritance-single.pas create mode 100644 Task/Input-loop/PascalABC.NET/input-loop.pas create mode 100644 Task/Integer-comparison/PascalABC.NET/integer-comparison.pas rename Task/Integer-sequence/PascalABC.NET/{integer-sequence.pas => integer-sequence-1.pas} (100%) create mode 100644 Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas create mode 100644 Task/Integer-sequence/Uiua/integer-sequence.uiua create mode 100644 Task/Integer-sequence/Zig/integer-sequence.zig create mode 100644 Task/Introspection/Jq/introspection.jq create mode 100644 Task/Iterated-digits-squaring/EasyLang/iterated-digits-squaring.easy create mode 100644 Task/JSON/PascalABC.NET/json.pas create mode 100644 Task/Jaro-Winkler-distance/Sidef/jaro-winkler-distance.sidef create mode 100644 Task/Jensens-Device/Asymptote/jensens-device.asymptote create mode 100644 Task/Jensens-Device/Chipmunk-Basic/jensens-device.basic create mode 100644 Task/Jensens-Device/Dart/jensens-device.dart create mode 100644 Task/Jensens-Device/GW-BASIC/jensens-device.basic create mode 100644 Task/Jensens-Device/Gambas/jensens-device.gambas create mode 100644 Task/Jensens-Device/Minimal-BASIC/jensens-device.basic create mode 100644 Task/Jensens-Device/QBasic/jensens-device.basic create mode 100644 Task/JortSort/EasyLang/jortsort.easy create mode 100644 Task/Jump-anywhere/PascalABC.NET/jump-anywhere.pas create mode 100644 Task/Knights-tour/Jq/knights-tour.jq create mode 100644 Task/Knuth-shuffle/PascalABC.NET/knuth-shuffle.pas create mode 100644 Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy create mode 100644 Task/Kronecker-product/BASIC256/kronecker-product.basic create mode 100644 Task/Kronecker-product/EasyLang/kronecker-product.easy create mode 100644 Task/Kronecker-product/Yabasic/kronecker-product.basic create mode 100644 Task/Langtons-ant/Uiua/langtons-ant.uiua create mode 100644 Task/Largest-int-from-concatenated-ints/EasyLang/largest-int-from-concatenated-ints.easy create mode 100644 Task/Largest-int-from-concatenated-ints/Uiua/largest-int-from-concatenated-ints.uiua create mode 100644 Task/Largest-number-divisible-by-its-digits/Ada/largest-number-divisible-by-its-digits.ada rename Task/Largest-number-divisible-by-its-digits/C++/{largest-number-divisible-by-its-digits.cpp => largest-number-divisible-by-its-digits-1.cpp} (100%) create mode 100644 Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits-2.cpp rename Task/Largest-number-divisible-by-its-digits/Java/{largest-number-divisible-by-its-digits.java => largest-number-divisible-by-its-digits-1.java} (100%) create mode 100644 Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits-2.java create mode 100644 Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy create mode 100644 Task/Least-common-multiple/PascalABC.NET/least-common-multiple.pas create mode 100644 Task/Least-common-multiple/Standard-ML/least-common-multiple-1.ml rename Task/Least-common-multiple/Standard-ML/{least-common-multiple.ml => least-common-multiple-2.ml} (100%) create mode 100644 Task/Least-common-multiple/Uiua/least-common-multiple.uiua create mode 100644 Task/Letter-frequency/Refal/letter-frequency.refal create mode 100644 Task/Levenshtein-distance-Alignment/Jq/levenshtein-distance-alignment.jq create mode 100644 Task/Levenshtein-distance/SETL/levenshtein-distance.setl create mode 100644 Task/Levenshtein-distance/Uiua/levenshtein-distance.uiua create mode 100644 Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas create mode 100644 Task/List-comprehensions/Uiua/list-comprehensions.uiua create mode 100644 Task/Literals-Floating-point/PascalABC.NET/literals-floating-point.pas create mode 100644 Task/Literals-String/PascalABC.NET/literals-string.pas create mode 100644 Task/Longest-common-subsequence/PascalABC.NET/longest-common-subsequence.pas create mode 100644 Task/Longest-increasing-subsequence/EasyLang/longest-increasing-subsequence.easy create mode 100644 Task/Look-and-say-sequence/ABC/look-and-say-sequence.abc create mode 100644 Task/Look-and-say-sequence/Uiua/look-and-say-sequence.uiua create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/PascalABC.NET/loop-over-multiple-arrays-simultaneously.pas create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-5.py create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Uiua/loop-over-multiple-arrays-simultaneously.uiua create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Vim-Script/loop-over-multiple-arrays-simultaneously.vim create mode 100644 Task/Loops-Break/PascalABC.NET/loops-break.pas create mode 100644 Task/Loops-Break/S-BASIC/loops-break-1.basic create mode 100644 Task/Loops-Break/S-BASIC/loops-break-2.basic create mode 100644 Task/Loops-Continue/PascalABC.NET/loops-continue.pas create mode 100644 Task/Loops-Do-while/PascalABC.NET/loops-do-while.pas delete mode 100644 Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while-2.basic rename Task/Loops-Do-while/Sinclair-ZX81-BASIC/{loops-do-while-1.basic => loops-do-while.basic} (100%) create mode 100644 Task/Loops-Downward-for/PascalABC.NET/loops-downward-for.pas create mode 100644 Task/Loops-For-with-a-specified-step/PascalABC.NET/loops-for-with-a-specified-step.pas create mode 100644 Task/Loops-For/PascalABC.NET/loops-for.pas create mode 100644 Task/Loops-For/Vim-Script/loops-for-1.vim create mode 100644 Task/Loops-For/Vim-Script/loops-for-2.vim create mode 100644 Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/PascalABC.NET/loops-increment-loop-index-within-loop-body.pas create mode 100644 Task/Loops-N-plus-one-half/PascalABC.NET/loops-n-plus-one-half.pas create mode 100644 Task/Loops-Nested/PascalABC.NET/loops-nested.pas create mode 100644 Task/Loops-While/Mia/loops-while.mia create mode 100644 Task/Loops-While/PascalABC.NET/loops-while.pas create mode 100644 Task/Loops-With-multiple-ranges/PascalABC.NET/loops-with-multiple-ranges.pas create mode 100644 Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas create mode 100644 Task/Ludic-numbers/EasyLang/ludic-numbers.easy create mode 100644 Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl create mode 100644 Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua create mode 100644 Task/M-bius-function/Gambas/m-bius-function.gambas create mode 100644 Task/M-bius-function/PureBasic/m-bius-function.basic create mode 100644 Task/M-bius-function/XBasic/m-bius-function.basic create mode 100644 Task/Magic-constant/Ada/magic-constant.ada delete mode 100644 Task/Make-directory-path/Seed7/make-directory-path-1.seed7 delete mode 100644 Task/Make-directory-path/Seed7/make-directory-path-2.seed7 create mode 100644 Task/Make-directory-path/Seed7/make-directory-path.seed7 create mode 100644 Task/Man-or-boy-test/PascalABC.NET/man-or-boy-test.pas create mode 100644 Task/Mandelbrot-set/Uiua/mandelbrot-set.uiua create mode 100644 Task/Map-range/EasyLang/map-range.easy create mode 100644 Task/Matrix-multiplication/Uiua/matrix-multiplication.uiua create mode 100644 Task/Mayan-calendar/Jq/mayan-calendar.jq create mode 100644 Task/Maze-generation/Chapel/maze-generation.chapel create mode 100644 Task/Maze-generation/POV-Ray/maze-generation.povray create mode 100644 Task/Maze-solving/Uiua/maze-solving.uiua create mode 100644 Task/McNuggets-problem/Refal/mcnuggets-problem.refal create mode 100644 Task/McNuggets-problem/Uiua/mcnuggets-problem.uiua create mode 100644 Task/Memory-allocation/PascalABC.NET/memory-allocation.pas create mode 100644 Task/Middle-three-digits/Uiua/middle-three-digits.uiua rename Task/Miller-Rabin-primality-test/REXX/{miller-rabin-primality-test.rexx => miller-rabin-primality-test-1.rexx} (100%) create mode 100644 Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx create mode 100644 Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.ada create mode 100644 Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq create mode 100644 Task/Minimal-steps-down-to-1/Jq/minimal-steps-down-to-1.jq create mode 100644 Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Quackery/minimum-multiple-of-m-where-digital-sum-equals-m.quackery create mode 100644 Task/Modified-random-distribution/Jq/modified-random-distribution.jq create mode 100644 Task/Monty-Hall-problem/ANSI-BASIC/monty-hall-problem.basic create mode 100644 Task/Monty-Hall-problem/FutureBasic/monty-hall-problem.basic create mode 100644 Task/Monty-Hall-problem/K/monty-hall-problem.k create mode 100644 Task/Monty-Hall-problem/Minimal-BASIC/monty-hall-problem.basic create mode 100644 Task/Monty-Hall-problem/Modula-2/monty-hall-problem.mod2 rename Task/Monty-Hall-problem/{BASIC => QuickBASIC}/monty-hall-problem.basic (100%) create mode 100644 Task/Monty-Hall-problem/SETL/monty-hall-problem.setl create mode 100644 Task/Monty-Hall-problem/Zig/monty-hall-problem.zig create mode 100644 Task/Motzkin-numbers/Uiua/motzkin-numbers.uiua create mode 100644 Task/Mouse-position/PascalABC.NET/mouse-position.pas create mode 100644 Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy create mode 100644 Task/Multiple-regression/BASIC256/multiple-regression.basic create mode 100644 Task/Multiple-regression/Chipmunk-Basic/multiple-regression.basic create mode 100644 Task/Multiple-regression/QB64/multiple-regression.qb64 create mode 100644 Task/Multiple-regression/True-BASIC/multiple-regression.basic create mode 100644 Task/Multiple-regression/Yabasic/multiple-regression.basic create mode 100644 Task/Multiplicative-order/Jq/multiplicative-order.jq create mode 100644 Task/Multisplit/EasyLang/multisplit.easy rename Task/Munchausen-numbers/Rust/{munchausen-numbers.rust => munchausen-numbers-1.rust} (100%) create mode 100644 Task/Munchausen-numbers/Rust/munchausen-numbers-2.rust create mode 100644 Task/Musical-scale/Ada/musical-scale.ada create mode 100644 Task/Mutual-recursion/EMal/mutual-recursion.emal create mode 100644 Task/N-queens-problem/C/n-queens-problem-5.c create mode 100644 Task/N-queens-problem/Commodore-BASIC/n-queens-problem.basic create mode 100644 Task/N-queens-problem/Pascal/n-queens-problem-3.pas create mode 100644 Task/N-queens-problem/Uiua/n-queens-problem.uiua create mode 100644 Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy create mode 100644 Task/Nested-function/PL-M/nested-function.plm create mode 100644 Task/Nested-function/PascalABC.NET/nested-function.pas create mode 100644 Task/Nested-templated-data/BASIC256/nested-templated-data.basic create mode 100644 Task/Nested-templated-data/Chipmunk-Basic/nested-templated-data.basic create mode 100644 Task/Nested-templated-data/FreeBASIC/nested-templated-data.basic create mode 100644 Task/Nested-templated-data/GW-BASIC/nested-templated-data.basic create mode 100644 Task/Nested-templated-data/QBasic/nested-templated-data.basic create mode 100644 Task/Nested-templated-data/Refal/nested-templated-data.refal create mode 100644 Task/Nested-templated-data/Run-BASIC/nested-templated-data.basic create mode 100644 Task/Nested-templated-data/SETL/nested-templated-data.setl create mode 100644 Task/Nested-templated-data/Yabasic/nested-templated-data.basic create mode 100644 Task/Next-highest-int-from-digits/Ada/next-highest-int-from-digits.ada create mode 100644 Task/Nim-game/COBOL/nim-game.cobol create mode 100644 Task/Nim-game/XBasic/nim-game.basic create mode 100644 Task/Non-continuous-subsequences/EasyLang/non-continuous-subsequences.easy create mode 100644 Task/Non-decimal-radices-Input/EasyLang/non-decimal-radices-input.easy create mode 100644 Task/Nonoblock/Jq/nonoblock.jq create mode 100644 Task/Nonogram-solver/Jq/nonogram-solver.jq create mode 100644 Task/Nth/PascalABC.NET/nth.pas create mode 100644 Task/Null-object/PascalABC.NET/null-object.pas create mode 100644 Task/Number-reversal-game/EasyLang/number-reversal-game.easy create mode 100644 Task/Numbers-which-are-not-the-sum-of-distinct-squares/Uiua/numbers-which-are-not-the-sum-of-distinct-squares.uiua create mode 100644 Task/Object-serialization/PascalABC.NET/object-serialization.pas create mode 100644 Task/One-dimensional-cellular-automata/C/one-dimensional-cellular-automata-3.c create mode 100644 Task/One-dimensional-cellular-automata/Refal/one-dimensional-cellular-automata.refal create mode 100644 Task/One-dimensional-cellular-automata/Uiua/one-dimensional-cellular-automata.uiua create mode 100644 Task/Ordered-words/BASIC/ordered-words.basic create mode 100644 Task/Ordered-words/Emacs-Lisp/ordered-words.l create mode 100644 Task/Ordered-words/SETL/ordered-words.setl create mode 100644 Task/Ordered-words/Uiua/ordered-words.uiua create mode 100644 Task/P-Adic-square-roots/C++/p-adic-square-roots.cpp create mode 100644 Task/P-Adic-square-roots/Java/p-adic-square-roots.java create mode 100644 Task/P-value-correction/Jq/p-value-correction.jq create mode 100644 Task/Padovan-sequence/FreeBASIC/padovan-sequence.basic rename Task/Palindrome-detection/Emacs-Lisp/{palindrome-detection.l => palindrome-detection-1.l} (100%) create mode 100644 Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-2.l create mode 100644 Task/Palindrome-detection/PascalABC.NET/palindrome-detection.pas create mode 100644 Task/Palindrome-detection/Refal/palindrome-detection.refal rename Task/Palindrome-detection/Uiua/{palindrome-detection.uiua => palindrome-detection-1.uiua} (100%) create mode 100644 Task/Palindrome-detection/Uiua/palindrome-detection-2.uiua create mode 100644 Task/Palindromic-gapful-numbers/Jq/palindromic-gapful-numbers.jq create mode 100644 Task/Parallel-brute-force/Elixir/parallel-brute-force.elixir create mode 100644 Task/Parallel-calculations/Free-Pascal-Lazarus/parallel-calculations.pas create mode 100644 Task/Parametric-polymorphism/COBOL/parametric-polymorphism.cobol create mode 100644 Task/Parametric-polymorphism/PascalABC.NET/parametric-polymorphism.pas create mode 100644 Task/Partition-an-integer-x-into-n-primes/EasyLang/partition-an-integer-x-into-n-primes.easy create mode 100644 Task/Pascal-matrix-generation/EasyLang/pascal-matrix-generation.easy create mode 100644 Task/Password-generator/Quackery/password-generator.quackery create mode 100644 Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy create mode 100644 Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq create mode 100644 Task/Penneys-game/Ada/penneys-game.ada create mode 100644 Task/Pentomino-tiling/Jq/pentomino-tiling.jq create mode 100644 Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy create mode 100644 Task/Perlin-noise/ALGOL-68/perlin-noise.alg create mode 100644 Task/Perlin-noise/Jq/perlin-noise.jq create mode 100644 Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy create mode 100644 Task/Permutations-by-swapping/Ada/permutations-by-swapping.ada create mode 100644 Task/Permutations/Uiua/permutations.uiua create mode 100644 Task/Phrase-reversals/EasyLang/phrase-reversals.easy create mode 100644 Task/Pi/AArch64-Assembly/pi.aarch64 create mode 100644 Task/Pi/ARM-Assembly/pi.arm create mode 100644 Task/Pi/Standard-ML/pi.ml create mode 100644 Task/Pi/UNIX-Shell/pi.sh create mode 100644 Task/Pick-random-element/PascalABC.NET/pick-random-element.pas create mode 100644 Task/Pick-random-element/Uiua/pick-random-element.uiua create mode 100644 Task/Pierpont-primes/EasyLang/pierpont-primes.easy create mode 100644 Task/Pig-the-dice-game-Player/C/pig-the-dice-game-player.c create mode 100644 Task/Pinstripe-Display/EasyLang/pinstripe-display.easy create mode 100644 Task/Pisano-period/APL/pisano-period.apl create mode 100644 Task/Pisano-period/Jq/pisano-period.jq create mode 100644 Task/Pisano-period/SETL/pisano-period.setl create mode 100644 Task/Plasma-effect/EasyLang/plasma-effect.easy create mode 100644 Task/Play-recorded-sounds/Ada/play-recorded-sounds.ada create mode 100644 Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy create mode 100644 Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas create mode 100644 Task/Poker-hand-analyser/Ada/poker-hand-analyser.ada create mode 100644 Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq create mode 100644 Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic create mode 100644 Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 create mode 100644 Task/Polymorphic-copy/PascalABC.NET/polymorphic-copy.pas create mode 100644 Task/Polymorphism/PascalABC.NET/polymorphism.pas create mode 100644 Task/Polynomial-regression/Jq/polynomial-regression.jq create mode 100644 Task/Population-count/ABC/population-count.abc create mode 100644 Task/Population-count/Refal/population-count.refal create mode 100644 Task/Power-set/PascalABC.NET/power-set.pas create mode 100644 Task/Price-fraction/Chipmunk-Basic/price-fraction.basic create mode 100644 Task/Price-fraction/Langur/price-fraction-1.langur create mode 100644 Task/Price-fraction/Langur/price-fraction-2.langur delete mode 100644 Task/Price-fraction/Langur/price-fraction.langur create mode 100644 Task/Price-fraction/QB64/price-fraction.qb64 create mode 100644 Task/Primality-by-trial-division/GW-BASIC/primality-by-trial-division.basic create mode 100644 Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas create mode 100644 Task/Prime-decomposition/PascalABC.NET/prime-decomposition.pas create mode 100644 Task/Prime-decomposition/REXX/prime-decomposition-3.rexx create mode 100644 Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Sidef/prime-numbers-whose-neighboring-pairs-are-tetraprimes.sidef create mode 100644 Task/Program-name/Ecstasy/program-name.ecstasy create mode 100644 Task/Program-name/PascalABC.NET/program-name.pas create mode 100644 Task/Program-termination/PascalABC.NET/program-termination.pas create mode 100644 Task/Proper-divisors/Chipmunk-Basic/proper-divisors.basic create mode 100644 Task/Proper-divisors/Gambas/proper-divisors.gambas create mode 100644 Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Jq/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.jq create mode 100644 Task/Pseudo-random-numbers-Middle-square-method/ALGOL-W/pseudo-random-numbers-middle-square-method.alg create mode 100644 Task/Pseudo-random-numbers-PCG32/FreeBASIC/pseudo-random-numbers-pcg32.basic create mode 100644 Task/Pseudo-random-numbers-PCG32/Jq/pseudo-random-numbers-pcg32.jq create mode 100644 Task/Pseudo-random-numbers-Splitmix64/FreeBASIC/pseudo-random-numbers-splitmix64.basic create mode 100644 Task/Pseudo-random-numbers-Splitmix64/Swift/pseudo-random-numbers-splitmix64.swift create mode 100644 Task/Pseudo-random-numbers-Xorshift-star/FreeBASIC/pseudo-random-numbers-xorshift-star.basic create mode 100644 Task/Pseudo-random-numbers-Xorshift-star/Jq/pseudo-random-numbers-xorshift-star.jq create mode 100644 Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy create mode 100644 Task/Queue-Definition/PascalABC.NET/queue-definition.pas create mode 100644 Task/Queue-Usage/PascalABC.NET/queue-usage.pas create mode 100644 Task/Quine/Odin/quine.odin create mode 100644 Task/Quine/PascalABC.NET/quine.pas create mode 100644 Task/Quine/Prog8/quine.prog8 create mode 100644 Task/Quine/Uxntal/quine.uxnatl create mode 100644 Task/Quoting-constructs/PascalABC.NET/quoting-constructs-1.pas create mode 100644 Task/Quoting-constructs/PascalABC.NET/quoting-constructs-2.pas create mode 100644 Task/Quoting-constructs/PascalABC.NET/quoting-constructs-3.pas create mode 100644 Task/Quoting-constructs/PascalABC.NET/quoting-constructs-4.pas create mode 100644 Task/RPG-attributes-generator/Uiua/rpg-attributes-generator.uiua create mode 100644 Task/Radical-of-an-integer/PascalABC.NET/radical-of-an-integer.pas rename Task/Radical-of-an-integer/REXX/{radical-of-an-integer.rexx => radical-of-an-integer-1.rexx} (93%) create mode 100644 Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx create mode 100644 Task/Ramer-Douglas-Peucker-line-simplification/BASIC256/ramer-douglas-peucker-line-simplification.basic create mode 100644 Task/Ramer-Douglas-Peucker-line-simplification/Jq/ramer-douglas-peucker-line-simplification.jq create mode 100644 Task/Ramer-Douglas-Peucker-line-simplification/QBasic/ramer-douglas-peucker-line-simplification.basic create mode 100644 Task/Random-numbers/ANSI-BASIC/random-numbers.basic create mode 100644 Task/Random-numbers/QuickBASIC/random-numbers.basic create mode 100644 Task/Random-numbers/Uiua/random-numbers.uiua create mode 100644 Task/Random-sentence-from-book/Jq/random-sentence-from-book.jq create mode 100644 Task/Range-expansion/EasyLang/range-expansion.easy create mode 100644 Task/Rate-counter/Chipmunk-Basic/rate-counter.basic create mode 100644 Task/Read-a-file-character-by-character-UTF8/PascalABC.NET/read-a-file-character-by-character-utf8.pas create mode 100644 Task/Read-a-file-line-by-line/PascalABC.NET/read-a-file-line-by-line.pas create mode 100644 Task/Read-a-specific-line-from-a-file/PascalABC.NET/read-a-specific-line-from-a-file.pas create mode 100644 Task/Read-entire-file/PascalABC.NET/read-entire-file.pas create mode 100644 Task/Real-constants-and-functions/ANSI-BASIC/real-constants-and-functions.basic create mode 100644 Task/Real-constants-and-functions/PascalABC.NET/real-constants-and-functions.pas create mode 100644 Task/Record-sound/Ada/record-sound.ada create mode 100644 Task/Record-sound/FutureBasic/record-sound.basic create mode 100644 Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy create mode 100644 Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas create mode 100644 Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy create mode 100644 Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas create mode 100644 Task/Regular-expressions/PascalABC.NET/regular-expressions.pas create mode 100644 Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas create mode 100644 Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas create mode 100644 Task/Rename-a-file/PascalABC.NET/rename-a-file.pas create mode 100644 Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas create mode 100644 Task/Repeat/Applesoft-BASIC/repeat.basic create mode 100644 Task/Repeat/Chapel/repeat-1.chapel create mode 100644 Task/Repeat/Chapel/repeat-2.chapel create mode 100644 Task/Repeat/Chapel/repeat-3.chapel create mode 100644 Task/Repeat/PascalABC.NET/repeat.pas create mode 100644 Task/Repeat/Refal/repeat.refal create mode 100644 Task/Return-multiple-values/PascalABC.NET/return-multiple-values.pas create mode 100644 Task/Reverse-a-string/PascalABC.NET/reverse-a-string.pas create mode 100644 Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas create mode 100644 Task/Rhonda-numbers/Python/rhonda-numbers.py create mode 100644 Task/Rock-paper-scissors/EasyLang/rock-paper-scissors.easy create mode 100644 Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode.pas create mode 100644 Task/Roman-numerals-Encode/PascalABC.NET/roman-numerals-encode.pas create mode 100644 Task/Rosetta-Code-Rank-languages-by-number-of-users/Jq/rosetta-code-rank-languages-by-number-of-users.jq create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/PascalABC.NET/rosetta-code-rank-languages-by-popularity.pas create mode 100644 Task/Rot-13/PascalABC.NET/rot-13.pas create mode 100644 Task/Run-length-encoding/Uiua/run-length-encoding.uiua create mode 100644 Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic create mode 100644 Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy create mode 100644 Task/Safe-addition/Langur/safe-addition.langur create mode 100644 Task/Sailors-coconuts-and-a-monkey-problem/EasyLang/sailors-coconuts-and-a-monkey-problem.easy create mode 100644 Task/Scope-Function-names-and-labels/EasyLang/scope-function-names-and-labels.easy create mode 100644 Task/Scope-modifiers/PascalABC.NET/scope-modifiers-1.pas create mode 100644 Task/Scope-modifiers/PascalABC.NET/scope-modifiers-2.pas create mode 100644 Task/Scope-modifiers/PascalABC.NET/scope-modifiers-3.pas create mode 100644 Task/Scope-modifiers/PascalABC.NET/scope-modifiers-4.pas create mode 100644 Task/Search-a-list/Ecstasy/search-a-list.ecstasy create mode 100644 Task/Search-in-paragraphs-text/Perl/search-in-paragraphs-text.pl create mode 100644 Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada/selectively-replace-multiple-instances-of-a-character-within-a-string.ada create mode 100644 Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/EasyLang/selectively-replace-multiple-instances-of-a-character-within-a-string.easy create mode 100644 Task/Self-numbers/EasyLang/self-numbers.easy create mode 100644 Task/Semiprime/REXX/semiprime-4.rexx delete mode 100644 Task/Semordnilap/SuperCollider/semordnilap-1.sc delete mode 100644 Task/Semordnilap/SuperCollider/semordnilap-2.sc create mode 100644 Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy create mode 100644 Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas create mode 100644 Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas create mode 100644 Task/Set-puzzle/Jq/set-puzzle.jq create mode 100644 Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq create mode 100644 Task/Sexy-primes/BASIC256/sexy-primes.basic create mode 100644 Task/Sexy-primes/Yabasic/sexy-primes.basic create mode 100644 Task/Show-ASCII-table/SETL/show-ascii-table.setl create mode 100644 Task/Show-the-epoch/EasyLang/show-the-epoch.easy create mode 100644 Task/Sierpinski-pentagon/Jq/sierpinski-pentagon.jq create mode 100644 Task/Sierpinski-square-curve/Ada/sierpinski-square-curve.ada create mode 100644 Task/Sierpinski-triangle/EasyLang/sierpinski-triangle.easy create mode 100644 Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-6.erl create mode 100644 Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ocaml create mode 100644 Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ocaml create mode 100644 Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas create mode 100644 Task/Simple-database/C++/simple-database.cpp create mode 100644 Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas create mode 100644 Task/Singleton/Ecstasy/singleton.ecstasy create mode 100644 Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas create mode 100644 Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas create mode 100644 Task/Sleep/PascalABC.NET/sleep.pas create mode 100644 Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg create mode 100644 Task/Sleeping-Beauty-problem/Fortran/sleeping-beauty-problem.f create mode 100644 Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq create mode 100644 Task/Smarandache-Wellin-primes/Sidef/smarandache-wellin-primes.sidef create mode 100644 Task/Smith-numbers/Uiua/smith-numbers-1.uiua create mode 100644 Task/Smith-numbers/Uiua/smith-numbers-2.uiua create mode 100644 Task/Snake/Emacs-Lisp/snake.l create mode 100644 Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq create mode 100644 Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua create mode 100644 Task/Solve-a-Holy-Knights-tour/Jq/solve-a-holy-knights-tour.jq create mode 100644 Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart create mode 100644 Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq create mode 100644 Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua create mode 100644 Task/Solve-the-no-connection-puzzle/FreeBASIC/solve-the-no-connection-puzzle.basic create mode 100644 Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery create mode 100644 Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig create mode 100644 Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig create mode 100644 Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy create mode 100644 Task/Sort-an-array-of-composite-structures/PascalABC.NET/sort-an-array-of-composite-structures.pas create mode 100644 Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy create mode 100644 Task/Sort-an-integer-array/PascalABC.NET/sort-an-integer-array.pas create mode 100644 Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp create mode 100644 Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq create mode 100644 Task/Sort-disjoint-sublist/Uiua/sort-disjoint-sublist.uiua create mode 100644 Task/Sort-numbers-lexicographically/EasyLang/sort-numbers-lexicographically.easy create mode 100644 Task/Sort-three-variables/PascalABC.NET/sort-three-variables.pas create mode 100644 Task/Sort-using-a-custom-comparator/PascalABC.NET/sort-using-a-custom-comparator.pas create mode 100644 Task/Sorting-Algorithms-Circle-Sort/ALGOL-68/sorting-algorithms-circle-sort.alg create mode 100644 Task/Sorting-Algorithms-Circle-Sort/EasyLang/sorting-algorithms-circle-sort.easy create mode 100644 Task/Sorting-algorithms-Bogosort/EMal/sorting-algorithms-bogosort.emal create mode 100644 Task/Sorting-algorithms-Cocktail-sort/EasyLang/sorting-algorithms-cocktail-sort.easy create mode 100644 Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy create mode 100644 Task/Sorting-algorithms-Counting-sort/Yabasic/sorting-algorithms-counting-sort.basic create mode 100644 Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-3.lisp rename Task/Sorting-algorithms-Insertion-sort/Kotlin/{sorting-algorithms-insertion-sort.kotlin => sorting-algorithms-insertion-sort-1.kotlin} (100%) create mode 100644 Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort-2.kotlin create mode 100644 Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy create mode 100644 Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.ada create mode 100644 Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy create mode 100644 Task/Sorting-algorithms-Quicksort/ANSI-BASIC/sorting-algorithms-quicksort.basic create mode 100644 Task/Sorting-algorithms-Quicksort/PascalABC.NET/sorting-algorithms-quicksort.pas create mode 100644 Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-8.py rename Task/Sorting-algorithms-Quicksort/{BASIC => QuickBASIC}/sorting-algorithms-quicksort.basic (100%) create mode 100644 Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic create mode 100644 Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy create mode 100644 Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic create mode 100644 Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy create mode 100644 Task/Special-variables/PascalABC.NET/special-variables-1.pas create mode 100644 Task/Special-variables/PascalABC.NET/special-variables-2.pas create mode 100644 Task/Special-variables/PascalABC.NET/special-variables-3.pas create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Refal/split-a-character-string-based-on-change-of-character.refal create mode 100644 Task/Split-a-character-string-based-on-change-of-character/SETL/split-a-character-string-based-on-change-of-character.setl create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Uiua/split-a-character-string-based-on-change-of-character.uiua create mode 100644 Task/Square-but-not-cube/8080-Assembly/square-but-not-cube.8080 create mode 100644 Task/Square-but-not-cube/ABC/square-but-not-cube.abc create mode 100644 Task/Square-but-not-cube/MACRO-11/square-but-not-cube.macro11 create mode 100644 Task/Square-but-not-cube/Refal/square-but-not-cube.refal create mode 100644 Task/Square-free-integers/Uiua/square-free-integers.uiua create mode 100644 Task/Stack-traces/PascalABC.NET/stack-traces.pas create mode 100644 Task/Stack/PascalABC.NET/stack.pas create mode 100644 Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy create mode 100644 Task/Stem-and-leaf-plot/EasyLang/stem-and-leaf-plot.easy create mode 100644 Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua create mode 100644 Task/String-append/PascalABC.NET/string-append.pas create mode 100644 Task/String-case/Ecstasy/string-case.ecstasy create mode 100644 Task/String-case/PascalABC.NET/string-case.pas create mode 100644 Task/String-case/Uiua/string-case.uiua create mode 100644 Task/String-comparison/Ecstasy/string-comparison.ecstasy rename Task/String-concatenation/C/{string-concatenation.c => string-concatenation-1.c} (100%) create mode 100644 Task/String-concatenation/C/string-concatenation-2.c create mode 100644 Task/String-concatenation/Ecstasy/string-concatenation.ecstasy create mode 100644 Task/String-concatenation/PascalABC.NET/string-concatenation.pas create mode 100644 Task/String-concatenation/Uiua/string-concatenation.uiua create mode 100644 Task/String-interpolation-included-/Langur/string-interpolation-included--1.langur create mode 100644 Task/String-interpolation-included-/Langur/string-interpolation-included--2.langur create mode 100644 Task/String-interpolation-included-/Langur/string-interpolation-included--3.langur create mode 100644 Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas create mode 100644 Task/String-interpolation-included-/Uiua/string-interpolation-included-.uiua create mode 100644 Task/String-length/Ecstasy/string-length.ecstasy create mode 100644 Task/String-length/PascalABC.NET/string-length.pas create mode 100644 Task/String-matching/PascalABC.NET/string-matching.pas create mode 100644 Task/String-matching/Uiua/string-matching-1.uiua create mode 100644 Task/String-matching/Uiua/string-matching-2.uiua create mode 100644 Task/String-matching/Uiua/string-matching-3.uiua create mode 100644 Task/String-matching/Uiua/string-matching-4.uiua create mode 100644 Task/String-prepend/PascalABC.NET/string-prepend.pas create mode 100644 Task/Strip-a-set-of-characters-from-a-string/PascalABC.NET/strip-a-set-of-characters-from-a-string.pas create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Uiua/strip-a-set-of-characters-from-a-string.uiua create mode 100644 Task/Strip-block-comments/PascalABC.NET/strip-block-comments.pas create mode 100644 Task/Strip-comments-from-a-string/PascalABC.NET/strip-comments-from-a-string.pas create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/PascalABC.NET/strip-control-codes-and-extended-characters-from-a-string.pas create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET/strip-whitespace-from-a-string-top-and-tail.pas create mode 100644 Task/Substitution-cipher/Emacs-Lisp/substitution-cipher.l create mode 100644 Task/Substitution-cipher/PascalABC.NET/substitution-cipher.pas create mode 100644 Task/Substring-Top-and-tail/Ecstasy/substring-top-and-tail.ecstasy create mode 100644 Task/Substring-Top-and-tail/PascalABC.NET/substring-top-and-tail.pas create mode 100644 Task/Substring/Ecstasy/substring.ecstasy create mode 100644 Task/Substring/PascalABC.NET/substring.pas create mode 100644 Task/Sudan-function/PascalABC.NET/sudan-function.pas create mode 100644 Task/Sudoku/Uiua/sudoku.uiua create mode 100644 Task/Sum-and-product-of-an-array/PascalABC.NET/sum-and-product-of-an-array.pas create mode 100644 Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer.pas create mode 100644 Task/Sum-multiples-of-3-and-5/PascalABC.NET/sum-multiples-of-3-and-5.pas create mode 100644 Task/Sum-multiples-of-3-and-5/Uiua/sum-multiples-of-3-and-5-1.uiua create mode 100644 Task/Sum-multiples-of-3-and-5/Uiua/sum-multiples-of-3-and-5-2.uiua create mode 100644 Task/Sum-of-a-series/PascalABC.NET/sum-of-a-series.pas create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/PascalABC.NET/sum-of-elements-below-main-diagonal-of-matrix.pas create mode 100644 Task/Sum-of-squares/PascalABC.NET/sum-of-squares.pas create mode 100644 Task/Summarize-primes/C-sharp/summarize-primes.cs create mode 100644 Task/Summarize-primes/Uiua/summarize-primes.uiua create mode 100644 Task/Symmetric-difference/PascalABC.NET/symmetric-difference.pas create mode 100644 Task/System-time/Ecstasy/system-time.ecstasy create mode 100644 Task/System-time/PascalABC.NET/system-time.pas create mode 100644 Task/Take-notes-on-the-command-line/PascalABC.NET/take-notes-on-the-command-line.pas create mode 100644 Task/Tau-function/C-sharp/tau-function.cs create mode 100644 Task/Tau-function/PascalABC.NET/tau-function.pas create mode 100644 Task/Tau-number/C-sharp/tau-number.cs create mode 100644 Task/Tau-number/PascalABC.NET/tau-number.pas create mode 100644 Task/Taxicab-numbers/EasyLang/taxicab-numbers.easy create mode 100644 Task/Temperature-conversion/PascalABC.NET/temperature-conversion.pas create mode 100644 Task/Terminal-control-Clear-the-screen/PascalABC.NET/terminal-control-clear-the-screen.pas create mode 100644 Task/Terminal-control-Coloured-text/PascalABC.NET/terminal-control-coloured-text.pas create mode 100644 Task/Terminal-control-Cursor-movement/PascalABC.NET/terminal-control-cursor-movement.pas create mode 100644 Task/Terminal-control-Cursor-positioning/PascalABC.NET/terminal-control-cursor-positioning.pas create mode 100644 Task/Terminal-control-Dimensions/PascalABC.NET/terminal-control-dimensions.pas create mode 100644 Task/Terminal-control-Display-an-extended-character/PascalABC.NET/terminal-control-display-an-extended-character.pas create mode 100644 Task/Terminal-control-Hiding-the-cursor/PascalABC.NET/terminal-control-hiding-the-cursor.pas create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/PascalABC.NET/terminal-control-ringing-the-terminal-bell.pas create mode 100644 Task/Test-a-function/PascalABC.NET/test-a-function.pas create mode 100644 Task/Test-a-function/Uiua/test-a-function.uiua create mode 100644 Task/Thieles-interpolation-formula/Jq/thieles-interpolation-formula.jq create mode 100644 Task/Tic-tac-toe/Jq/tic-tac-toe.jq create mode 100644 Task/Time-a-function/PascalABC.NET/time-a-function.pas create mode 100644 Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy create mode 100644 Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas create mode 100644 Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy create mode 100644 Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas create mode 100644 Task/Topic-variable/Java/topic-variable.java create mode 100644 Task/Towers-of-Hanoi/Asymptote/towers-of-hanoi.asymptote create mode 100644 Task/Towers-of-Hanoi/Bruijn/towers-of-hanoi.bruijn create mode 100644 Task/Towers-of-Hanoi/PascalABC.NET/towers-of-hanoi.pas create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/PascalABC.NET/trabb-pardo-knuth-algorithm.pas create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/UNIX-Shell/trabb-pardo-knuth-algorithm.sh create mode 100644 Task/Transliterate-English-text-using-the-Greek-alphabet/PascalABC.NET/transliterate-english-text-using-the-greek-alphabet.pas create mode 100644 Task/Tree-datastructures/PascalABC.NET/tree-datastructures.pas create mode 100644 Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs create mode 100644 Task/Tree-traversal/EMal/tree-traversal.emal create mode 100644 Task/Tree-traversal/PascalABC.NET/tree-traversal.pas create mode 100644 Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas create mode 100644 Task/Truncatable-primes/Uiua/truncatable-primes.uiua create mode 100644 Task/Truncate-a-file/PascalABC.NET/truncate-a-file.pas create mode 100644 Task/Twos-complement/PascalABC.NET/twos-complement.pas create mode 100644 Task/UPC/Ada/upc.ada create mode 100644 Task/URL-decoding/PascalABC.NET/url-decoding.pas create mode 100644 Task/URL-encoding/PascalABC.NET/url-encoding.pas create mode 100644 Task/Ultra-useful-primes/C-sharp/ultra-useful-primes.cs create mode 100644 Task/Undefined-values/PascalABC.NET/undefined-values.pas create mode 100644 Task/Unicode-strings/PascalABC.NET/unicode-strings.pas create mode 100644 Task/Unicode-variable-names/PascalABC.NET/unicode-variable-names.pas rename Task/Universal-Turing-machine/Python/{universal-turing-machine.py => universal-turing-machine-1.py} (100%) create mode 100644 Task/Universal-Turing-machine/Python/universal-turing-machine-2.py create mode 100644 Task/User-input-Text/EMal/user-input-text.emal create mode 100644 Task/User-input-Text/PascalABC.NET/user-input-text.pas create mode 100644 Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua create mode 100644 Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs create mode 100644 Task/Variables/PascalABC.NET/variables-1.pas create mode 100644 Task/Variables/PascalABC.NET/variables-2.pas create mode 100644 Task/Variables/PascalABC.NET/variables-3.pas create mode 100644 Task/Variables/PascalABC.NET/variables-4.pas create mode 100644 Task/Variables/PascalABC.NET/variables-5.pas create mode 100644 Task/Variables/PascalABC.NET/variables-6.pas create mode 100644 Task/Variadic-function/PascalABC.NET/variadic-function.pas create mode 100644 Task/Vector-products/PascalABC.NET/vector-products.pas create mode 100644 Task/Vector/Chipmunk-Basic/vector.basic create mode 100644 Task/Vector/GW-BASIC/vector.basic create mode 100644 Task/Vector/PascalABC.NET/vector.pas create mode 100644 Task/Vector/QBasic/vector.basic create mode 100644 Task/Vector/True-BASIC/vector.basic create mode 100644 Task/Verify-distribution-uniformity-Naive/EasyLang/verify-distribution-uniformity-naive.easy create mode 100644 Task/Wagstaff-primes/Sidef/wagstaff-primes.sidef create mode 100644 Task/Walk-a-directory-Non-recursively/PascalABC.NET/walk-a-directory-non-recursively.pas create mode 100644 Task/Walk-a-directory-Recursively/PascalABC.NET/walk-a-directory-recursively.pas create mode 100644 Task/War-card-game/Ada/war-card-game.ada create mode 100644 Task/War-card-game/Jq/war-card-game.jq create mode 100644 Task/Water-collected-between-towers/PHP/water-collected-between-towers.php create mode 100644 Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua create mode 100644 Task/Weird-numbers/Ada/weird-numbers-1.ada create mode 100644 Task/Weird-numbers/Ada/weird-numbers-2.ada rename Task/Weird-numbers/Python/{weird-numbers.py => weird-numbers-1.py} (100%) create mode 100644 Task/Weird-numbers/Python/weird-numbers-2.py create mode 100644 Task/Weird-numbers/Uxntal/weird-numbers.uxnatl create mode 100644 Task/Window-creation/PascalABC.NET/window-creation.pas create mode 100644 Task/Word-frequency/PascalABC.NET/word-frequency.pas create mode 100644 Task/Word-ladder/APL/word-ladder.apl create mode 100644 Task/Word-ladder/Ada/word-ladder.ada create mode 100644 Task/Word-ladder/Refal/word-ladder.refal create mode 100644 Task/Word-ladder/SETL/word-ladder.setl create mode 100644 Task/Word-search/Ada/word-search.ada create mode 100644 Task/Word-wheel/Ada/word-wheel.ada rename Task/Word-wheel/Lua/{word-wheel.lua => word-wheel-1.lua} (100%) create mode 100644 Task/Word-wheel/Lua/word-wheel-2.lua create mode 100644 Task/Word-wrap/PascalABC.NET/word-wrap.pas create mode 100644 Task/Wordiff/Jq/wordiff.jq create mode 100644 Task/Write-entire-file/PascalABC.NET/write-entire-file.pas create mode 100644 Task/Write-to-Windows-event-log/FreeBASIC/write-to-windows-event-log.basic create mode 100644 Task/Write-to-Windows-event-log/PascalABC.NET/write-to-windows-event-log.pas create mode 100644 Task/XML-DOM-serialization/PascalABC.NET/xml-dom-serialization.pas create mode 100644 Task/XML-Input/PascalABC.NET/xml-input.pas create mode 100644 Task/XML-Input/Vim-Script/xml-input.vim create mode 100644 Task/XML-Output/PascalABC.NET/xml-output.pas create mode 100644 Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs create mode 100644 Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua rename Task/Yin-and-yang/AmigaBASIC/{yin-and-yang.basic => yin-and-yang-1.basic} (100%) create mode 100644 Task/Yin-and-yang/AmigaBASIC/yin-and-yang-2.basic create mode 100644 Task/Zebra-puzzle/Uiua/zebra-puzzle.uiua create mode 100644 Task/Zero-to-the-zero-power/PascalABC.NET/zero-to-the-zero-power.pas create mode 100644 Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy diff --git a/Lang/8080-Assembly/Square-but-not-cube b/Lang/8080-Assembly/Square-but-not-cube new file mode 120000 index 0000000000..e8de867485 --- /dev/null +++ b/Lang/8080-Assembly/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/8080-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Pi b/Lang/AArch64-Assembly/Pi new file mode 120000 index 0000000000..34be149f2d --- /dev/null +++ b/Lang/AArch64-Assembly/Pi @@ -0,0 +1 @@ +../../Task/Pi/AArch64-Assembly \ No newline at end of file diff --git a/Lang/ABC/Look-and-say-sequence b/Lang/ABC/Look-and-say-sequence new file mode 120000 index 0000000000..68b9661932 --- /dev/null +++ b/Lang/ABC/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/ABC \ No newline at end of file diff --git a/Lang/ABC/Population-count b/Lang/ABC/Population-count new file mode 120000 index 0000000000..6bd44c7e1e --- /dev/null +++ b/Lang/ABC/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/ABC \ No newline at end of file diff --git a/Lang/ABC/Square-but-not-cube b/Lang/ABC/Square-but-not-cube new file mode 120000 index 0000000000..23a046e711 --- /dev/null +++ b/Lang/ABC/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/ABC \ No newline at end of file diff --git a/Lang/ALGOL-68/00-LANG.txt b/Lang/ALGOL-68/00-LANG.txt index c77464279f..4aa1cbcf81 100644 --- a/Lang/ALGOL-68/00-LANG.txt +++ b/Lang/ALGOL-68/00-LANG.txt @@ -67,7 +67,7 @@ A syntax chart is available [http://www.softwarepreservation.org/projects/ALGOL/ *Oct. 1968: Penultimate Draft Report on the Algorithmic Language ALGOL 68 - Chapters 1-9 - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck and C.H.A. Koster. *Dec. 1968: Report on the Algorithmic Language ALGOL 68 - Offprint from Numerische Mathematik, 14, 79-218 (1969); Springer-Verlag. - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck and C.H.A. Koster. *Sep 1973: Revised Report on the Algorithmic Language Algol 68 - Springer-Verlag 1976 - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck, C.H.A. Koster, M. Sintzoff, C.H. Lindsey, L.G.L.T. Meertens and R.G. Fisker. -==Coding style of samples== +==Coding style of samples, alphabets and stropping== Click "Expand" for more details.
@@ -96,23 +96,30 @@ not too much else is required. Examples: END FINISH |} +

'''Alphabets''' +

+Notionally, Algol 68 source is written in two alphabets. The reserved words, mode indicants (type names) and operators that are non-symbolic (.e.g. '''and''', '''or''', ...) are generally referred to as "bold words" and usually shown in a bold font in literature. Words that are identifiers (used for "variable" names, procedure names, structure member names, ...) are in a separate, non-bold font.
+The [https://www.softwarepreservation.org/projects/ALGOL/manual/a68s.txt/view Manual for CMU ALGOL 68S (on softwarepreservation.org)] refers to the non-bold words as being in timid face.

'''Examples of different program representations'''

At the time when ALGOL 68 was defined some predominant computers had 24 or 36 bit words, with 6 bit character sets. Hence it was desirable that -ALGOL 68 should be able to run on machines with only uppercase. +ALGOL 68 should be able to run on machines with only uppercase. +As multiple fonts were generally unavailable, a method of identifying the bold words was required.
The official spec provided for different representations of the same -program. Quote stropping (enclosing the bold words in single quotes) +program. +Quote stropping (enclosing the bold words in single quotes) and Point stropping (preceeding the bold words with a dot) -were used. A variant of Point stropping called RES stropping was also defined. -In RES stropping some language-defined bold words are not preceded by a dot. +were used.
+A variant of Point stropping called RES stropping was also defined. +In RES stropping some language-defined bold words are not preceded by a dot.
A pragmatic comment may have been required to indicate which -stropping convention was to be used, as in some of the examples below. +stropping convention was to be used, as in some of the examples below.
Upper stropping (representing the bold words by upper case and -non-bold words in lower case) was introduced by Algol 68R. Upper stropping -is used by Algol 68RS and is one of the options for Algol 68G. -Rutgers ALGOL 68 uses quote stropping. Most of the samples -on Rosetta Code use Upper stropping. +non-bold words in lower case) was introduced by Algol 68R.
+Upper stropping is used by Algol 68RS and is one of the options for Algol 68G.
+Rutgers ALGOL 68 uses quote stropping.
+Most of the samples on Rosetta Code use Upper stropping.

Examples (pragmatic comments to set the stropping regime not shown): {|border="1" style="border-collapse: collapse; border: 2px double grey;" align="left" || Algol68 as typically published @@ -281,5 +288,9 @@ For more details about Primaries and Secondaries refer to [[Operator_precedence# [https://rosettacode.org/wiki/Category:ALGOL_68-rows Row (array) related]
[https://rosettacode.org/wiki/Category:ALGOL_68-l-system L-System related] +== Tools == +[[Syntax_highlighting_using_Mediawiki_formatting#ALGOL 68|Format an upper-stropped Algol 68 source with Mediawiki markup]]
+[[Compiler/Simple_file_inclusion_pre_processor#ALGOL 68|Implement ''read'' and ''include'' pragmatic-comments for compilers that don't support file inclusion]] + {{language programming paradigm|Concurrent}} {{language programming paradigm|Imperative}} \ No newline at end of file diff --git a/Lang/ALGOL-68/Draw-a-cuboid b/Lang/ALGOL-68/Draw-a-cuboid new file mode 120000 index 0000000000..3102af7fc7 --- /dev/null +++ b/Lang/ALGOL-68/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Perlin-noise b/Lang/ALGOL-68/Perlin-noise new file mode 120000 index 0000000000..8bd6981103 --- /dev/null +++ b/Lang/ALGOL-68/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sleeping-Beauty-problem b/Lang/ALGOL-68/Sleeping-Beauty-problem new file mode 120000 index 0000000000..b5873d4f8d --- /dev/null +++ b/Lang/ALGOL-68/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort b/Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort new file mode 120000 index 0000000000..de6d7c8e6a --- /dev/null +++ b/Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort @@ -0,0 +1 @@ +../../Task/Sorting-Algorithms-Circle-Sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Eulers-constant-0.5772... b/Lang/ALGOL-W/Eulers-constant-0.5772... new file mode 120000 index 0000000000..809de9e1fd --- /dev/null +++ b/Lang/ALGOL-W/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Find-the-intersection-of-two-lines b/Lang/ALGOL-W/Find-the-intersection-of-two-lines new file mode 120000 index 0000000000..0514984ef6 --- /dev/null +++ b/Lang/ALGOL-W/Find-the-intersection-of-two-lines @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-two-lines/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method b/Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..e6f0e36a5b --- /dev/null +++ b/Lang/ALGOL-W/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/ALGOL-W \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Damm-algorithm b/Lang/ANSI-BASIC/Damm-algorithm new file mode 120000 index 0000000000..e4b39fdaa1 --- /dev/null +++ b/Lang/ANSI-BASIC/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Formatted-numeric-output b/Lang/ANSI-BASIC/Formatted-numeric-output new file mode 120000 index 0000000000..e876b7e939 --- /dev/null +++ b/Lang/ANSI-BASIC/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Function-definition b/Lang/ANSI-BASIC/Function-definition new file mode 120000 index 0000000000..c45352eba7 --- /dev/null +++ b/Lang/ANSI-BASIC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Monty-Hall-problem b/Lang/ANSI-BASIC/Monty-Hall-problem new file mode 120000 index 0000000000..8f9a29cbcc --- /dev/null +++ b/Lang/ANSI-BASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Random-numbers b/Lang/ANSI-BASIC/Random-numbers new file mode 120000 index 0000000000..1de5221db0 --- /dev/null +++ b/Lang/ANSI-BASIC/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Real-constants-and-functions b/Lang/ANSI-BASIC/Real-constants-and-functions new file mode 120000 index 0000000000..02cced5726 --- /dev/null +++ b/Lang/ANSI-BASIC/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Sorting-algorithms-Quicksort b/Lang/ANSI-BASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..acf4c89afe --- /dev/null +++ b/Lang/ANSI-BASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ANSI-BASIC \ No newline at end of file diff --git a/Lang/APL/Display-a-linear-combination b/Lang/APL/Display-a-linear-combination new file mode 120000 index 0000000000..0e1867473a --- /dev/null +++ b/Lang/APL/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/APL \ No newline at end of file diff --git a/Lang/APL/Pisano-period b/Lang/APL/Pisano-period new file mode 120000 index 0000000000..d81ff37307 --- /dev/null +++ b/Lang/APL/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/APL \ No newline at end of file diff --git a/Lang/APL/Word-ladder b/Lang/APL/Word-ladder new file mode 120000 index 0000000000..6de9f38d51 --- /dev/null +++ b/Lang/APL/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/Pi b/Lang/ARM-Assembly/Pi new file mode 120000 index 0000000000..97b44cbcc1 --- /dev/null +++ b/Lang/ARM-Assembly/Pi @@ -0,0 +1 @@ +../../Task/Pi/ARM-Assembly \ No newline at end of file diff --git a/Lang/Ada/00-LANG.txt b/Lang/Ada/00-LANG.txt index 85a16e96c0..f17f9738ab 100644 --- a/Lang/Ada/00-LANG.txt +++ b/Lang/Ada/00-LANG.txt @@ -17,4 +17,6 @@ The language is named after [[wp:Ada_Lovelace|Augusta Ada King, Countess of Love {{Language programming paradigm|Distributed}} {{Language programming paradigm|Generic}} {{Language programming paradigm|Imperative}} -{{Language programming paradigm|Object-oriented}} \ No newline at end of file +{{Language programming paradigm|Object-oriented}} +==Todo== +* [[Tasks not implemented in Ada]] \ No newline at end of file diff --git a/Lang/Ada/Abelian-sandpile-model b/Lang/Ada/Abelian-sandpile-model new file mode 120000 index 0000000000..adfb5aa625 --- /dev/null +++ b/Lang/Ada/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Ada \ No newline at end of file diff --git a/Lang/Ada/Achilles-numbers b/Lang/Ada/Achilles-numbers new file mode 120000 index 0000000000..8a02102d36 --- /dev/null +++ b/Lang/Ada/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..14bdbe4c3d --- /dev/null +++ b/Lang/Ada/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Ada \ No newline at end of file diff --git a/Lang/Ada/Ascending-primes b/Lang/Ada/Ascending-primes new file mode 120000 index 0000000000..cee2b86585 --- /dev/null +++ b/Lang/Ada/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Brace-expansion b/Lang/Ada/Brace-expansion new file mode 120000 index 0000000000..b881365fa7 --- /dev/null +++ b/Lang/Ada/Brace-expansion @@ -0,0 +1 @@ +../../Task/Brace-expansion/Ada \ No newline at end of file diff --git a/Lang/Ada/Color-wheel b/Lang/Ada/Color-wheel new file mode 120000 index 0000000000..3d78384078 --- /dev/null +++ b/Lang/Ada/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Ada \ No newline at end of file diff --git a/Lang/Ada/Combinations-and-permutations b/Lang/Ada/Combinations-and-permutations new file mode 120000 index 0000000000..3f163f203e --- /dev/null +++ b/Lang/Ada/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Ada \ No newline at end of file diff --git a/Lang/Ada/Eulers-constant-0.5772... b/Lang/Ada/Eulers-constant-0.5772... new file mode 120000 index 0000000000..b0e75cb33e --- /dev/null +++ b/Lang/Ada/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../Ada \ No newline at end of file diff --git a/Lang/Ada/FTP b/Lang/Ada/FTP new file mode 120000 index 0000000000..1d406ce7cd --- /dev/null +++ b/Lang/Ada/FTP @@ -0,0 +1 @@ +../../Task/FTP/Ada \ No newline at end of file diff --git a/Lang/Ada/Hex-words b/Lang/Ada/Hex-words new file mode 120000 index 0000000000..da49cf2b4d --- /dev/null +++ b/Lang/Ada/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Ada \ No newline at end of file diff --git a/Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols b/Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols new file mode 120000 index 0000000000..29e378f3f1 --- /dev/null +++ b/Lang/Ada/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada \ No newline at end of file diff --git a/Lang/Ada/Largest-number-divisible-by-its-digits b/Lang/Ada/Largest-number-divisible-by-its-digits new file mode 120000 index 0000000000..d61b3cb8be --- /dev/null +++ b/Lang/Ada/Largest-number-divisible-by-its-digits @@ -0,0 +1 @@ +../../Task/Largest-number-divisible-by-its-digits/Ada \ No newline at end of file diff --git a/Lang/Ada/Magic-constant b/Lang/Ada/Magic-constant new file mode 120000 index 0000000000..bd59423b8e --- /dev/null +++ b/Lang/Ada/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Ada \ No newline at end of file diff --git a/Lang/Ada/Mind-boggling-card-trick b/Lang/Ada/Mind-boggling-card-trick new file mode 120000 index 0000000000..11ae4366fc --- /dev/null +++ b/Lang/Ada/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/Ada \ No newline at end of file diff --git a/Lang/Ada/Musical-scale b/Lang/Ada/Musical-scale new file mode 120000 index 0000000000..a792f4144a --- /dev/null +++ b/Lang/Ada/Musical-scale @@ -0,0 +1 @@ +../../Task/Musical-scale/Ada \ No newline at end of file diff --git a/Lang/Ada/Next-highest-int-from-digits b/Lang/Ada/Next-highest-int-from-digits new file mode 120000 index 0000000000..e996a777e6 --- /dev/null +++ b/Lang/Ada/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/Ada \ No newline at end of file diff --git a/Lang/Ada/Penneys-game b/Lang/Ada/Penneys-game new file mode 120000 index 0000000000..00a5e1d496 --- /dev/null +++ b/Lang/Ada/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Ada \ No newline at end of file diff --git a/Lang/Ada/Permutations-by-swapping b/Lang/Ada/Permutations-by-swapping new file mode 120000 index 0000000000..9140cf7f43 --- /dev/null +++ b/Lang/Ada/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Ada \ No newline at end of file diff --git a/Lang/Ada/Play-recorded-sounds b/Lang/Ada/Play-recorded-sounds new file mode 120000 index 0000000000..2365ca211b --- /dev/null +++ b/Lang/Ada/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/Ada \ No newline at end of file diff --git a/Lang/Ada/Poker-hand-analyser b/Lang/Ada/Poker-hand-analyser new file mode 120000 index 0000000000..fc5a66b995 --- /dev/null +++ b/Lang/Ada/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Ada \ No newline at end of file diff --git a/Lang/Ada/Record-sound b/Lang/Ada/Record-sound new file mode 120000 index 0000000000..af45b7783f --- /dev/null +++ b/Lang/Ada/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Ada \ No newline at end of file diff --git a/Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..5077dd9033 --- /dev/null +++ b/Lang/Ada/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada \ No newline at end of file diff --git a/Lang/Ada/Sierpinski-square-curve b/Lang/Ada/Sierpinski-square-curve new file mode 120000 index 0000000000..32cee5f712 --- /dev/null +++ b/Lang/Ada/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/Ada \ No newline at end of file diff --git a/Lang/Ada/Sorting-algorithms-Permutation-sort b/Lang/Ada/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..0f333c5ec8 --- /dev/null +++ b/Lang/Ada/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Ada \ No newline at end of file diff --git a/Lang/Ada/UPC b/Lang/Ada/UPC new file mode 120000 index 0000000000..374da7b0aa --- /dev/null +++ b/Lang/Ada/UPC @@ -0,0 +1 @@ +../../Task/UPC/Ada \ No newline at end of file diff --git a/Lang/Ada/War-card-game b/Lang/Ada/War-card-game new file mode 120000 index 0000000000..dd4f92afee --- /dev/null +++ b/Lang/Ada/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Ada \ No newline at end of file diff --git a/Lang/Ada/Weird-numbers b/Lang/Ada/Weird-numbers new file mode 120000 index 0000000000..98491ade1a --- /dev/null +++ b/Lang/Ada/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-ladder b/Lang/Ada/Word-ladder new file mode 120000 index 0000000000..495c24dbcd --- /dev/null +++ b/Lang/Ada/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-search b/Lang/Ada/Word-search new file mode 120000 index 0000000000..32f00f4762 --- /dev/null +++ b/Lang/Ada/Word-search @@ -0,0 +1 @@ +../../Task/Word-search/Ada \ No newline at end of file diff --git a/Lang/Ada/Word-wheel b/Lang/Ada/Word-wheel new file mode 120000 index 0000000000..47f67698e0 --- /dev/null +++ b/Lang/Ada/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/Ada \ No newline at end of file diff --git a/Lang/AmigaBASIC/00-LANG.txt b/Lang/AmigaBASIC/00-LANG.txt index 94b3e71ee7..c2e6f48854 100644 --- a/Lang/AmigaBASIC/00-LANG.txt +++ b/Lang/AmigaBASIC/00-LANG.txt @@ -11,5 +11,7 @@ Execution speed however was not a particular strength of AmigaBASIC. Some 8-bit AmigaBASIC was superseded by [[wp:ARexx|ARexx]], a REXX-style scripting language, from AmigaOS version 2.0 onwards. The 1.x AmigaBASIC binary also works on AmigaOS 2, but not on AmigaOS 3. +Microsoft [[QuickBASIC]] (1985) and QBasic (1991) look very similar to AmigaBASIC, so their syntax highlighting rules mostly also work for AmigaBASIC code. + ==See Also== *[https://archive.org/search.php?query=amiga%20basic Scanned AmigaBASIC books at archive.org] \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Display-a-linear-combination b/Lang/Applesoft-BASIC/Display-a-linear-combination new file mode 120000 index 0000000000..d72f6d3a78 --- /dev/null +++ b/Lang/Applesoft-BASIC/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Repeat b/Lang/Applesoft-BASIC/Repeat new file mode 120000 index 0000000000..eb0c08d923 --- /dev/null +++ b/Lang/Applesoft-BASIC/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Asymptote/Jensens-Device b/Lang/Asymptote/Jensens-Device new file mode 120000 index 0000000000..621c474cd7 --- /dev/null +++ b/Lang/Asymptote/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Asymptote \ No newline at end of file diff --git a/Lang/Asymptote/Towers-of-Hanoi b/Lang/Asymptote/Towers-of-Hanoi new file mode 120000 index 0000000000..62a6e4d923 --- /dev/null +++ b/Lang/Asymptote/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Asymptote \ No newline at end of file diff --git a/Lang/AutoHotKey-V2/00-LANG.txt b/Lang/AutoHotKey-V2/00-LANG.txt deleted file mode 100644 index a333f928af..0000000000 --- a/Lang/AutoHotKey-V2/00-LANG.txt +++ /dev/null @@ -1 +0,0 @@ -{{stub}}{{language|AutoHotKey V2}} \ No newline at end of file diff --git a/Lang/AutoHotKey-V2/00-META.yaml b/Lang/AutoHotKey-V2/00-META.yaml deleted file mode 100644 index 316ebe0ccb..0000000000 --- a/Lang/AutoHotKey-V2/00-META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -from: http://rosettacode.org/wiki/Category:AutoHotKey_V2 diff --git a/Lang/AutoHotKey-V2/Hello-world-Graphical b/Lang/AutoHotKey-V2/Hello-world-Graphical deleted file mode 120000 index 89783bc714..0000000000 --- a/Lang/AutoHotKey-V2/Hello-world-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Graphical/AutoHotKey-V2 \ No newline at end of file diff --git a/Lang/Autohotkey-V2/00-LANG.txt b/Lang/Autohotkey-V2/00-LANG.txt new file mode 100644 index 0000000000..b3e33b65ab --- /dev/null +++ b/Lang/Autohotkey-V2/00-LANG.txt @@ -0,0 +1,16 @@ +{{stub}}AutoHotkey V2 is an [[open source]] programming language for Microsoft [[Windows]]. + +AutoHotkey v2 is a major update to the AutoHotkey language, which includes numerous new features and improvements. + +== Citations == + +* [https://www.autohotkey.com/docs/v2/ Documentation] +* [http://autohotkey.com/download Downloads] +* [http://autohotkey.com/docs/scripts/ Script Showcase] +* [http://autohotkey.com/boards/ New Community forum] +* [http://www.autohotkey.com/forum/ Archived Community forum] +* [http://ahkscript.org/foundation AutoHotkey Foundation LLC] +* [[wp:AutoHotkey|AutoHotkey on Wikipedia]] +* #ahk on [http://webchat.freenode.net/?channels=%23ahk Freenode Web interface] +* [[:Category:AutoHotkey_Originated]] +{{language|Ayrch}} \ No newline at end of file diff --git a/Lang/Autohotkey-V2/00-META.yaml b/Lang/Autohotkey-V2/00-META.yaml new file mode 100644 index 0000000000..651d1bc21b --- /dev/null +++ b/Lang/Autohotkey-V2/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Autohotkey_V2 diff --git a/Lang/Autohotkey-V2/Hello-world-Graphical b/Lang/Autohotkey-V2/Hello-world-Graphical new file mode 120000 index 0000000000..0375a8eeb7 --- /dev/null +++ b/Lang/Autohotkey-V2/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Autohotkey-V2 \ No newline at end of file diff --git a/Lang/BASIC/00-LANG.txt b/Lang/BASIC/00-LANG.txt index 8f4f969193..745f847ac8 100644 --- a/Lang/BASIC/00-LANG.txt +++ b/Lang/BASIC/00-LANG.txt @@ -12,11 +12,25 @@ BASIC became popular, with many different implementations for various computers. ==Links== *[[wp:BASIC|Wikipedia:BASIC]] +**[[wp:ASIC]] +**[[wp:Atari BASIC]] **[[wp:BASIC-PLUS]] +**[[wp:Basic-256]] +**[[wp:Batari BASIC]] +**[[wp:BBC BASIC]] **[[wp:Benton Harbor BASIC]] +**[[wp:Beta BASIC]] **[[wp:CBASIC]] **[[wp:Chipmunk Basic]] +**[[wp:DarkBASIC]] **[[wp:Dartmouth BASIC]] +**[[wp:FreeBASIC]] +**[[wp:FutureBASIC]] +**[[wp:GFA BASIC]] +**[[wp:GLBasic]] +**[[wp:Integer BASIC]] +**[[wp:Liberty BASIC]] +**[[wp:Locomotive BASIC]] **[[wp:Microsoft BASIC]] ***[[wp:Altair BASIC]] ***[[wp:Amiga BASIC]] @@ -24,13 +38,29 @@ BASIC became popular, with many different implementations for various computers. ***[[wp:Atari Microsoft BASIC]] ***[[wp:Commodore BASIC]] ***[[wp:IBM BASIC]] -***[[wp:TRS-80 Level II BASIC ]] +***[[wp:MS BASIC for Macintosh]] +***[[wp:MSX BASIC]] +***[[wp:Small Basic]] +***[[wp:QBasic]] +***[[wp:QuickBASIC]]‎ +***[[wp:TRS-80 Level II BASIC]] +***[[wp:Visual Basic‎]] **[[wp:PowerBASIC]] **[[wp:PureBasic]] +**[[wp:QB64‎]] +**[[wp:Quite BASIC]]‎ +**[[wp:RapidQ]] +**[[wp:Realbasic]] **[[wp:Rocky Mountain BASIC]] +**[[wp:Run BASIC]] **[[wp:S-BASIC]] +**[[wp:ScriptBasic]] **[[wp:Sinclair BASIC]] +**[[wp:SmileBASIC‎]] **[[wp:SuperBASIC]] **[[wp:TI BASIC (TI 99/4A)]] +**[[wp:Tiny BASIC‎]] **[[wp:True BASIC]] +**[[wp:UBASIC]] +**[[wp:Yabasic]] {{language programming paradigm|Procedural}} \ No newline at end of file diff --git a/Lang/BASIC/Damm-algorithm b/Lang/BASIC/Damm-algorithm deleted file mode 120000 index 41ee6d1c36..0000000000 --- a/Lang/BASIC/Damm-algorithm +++ /dev/null @@ -1 +0,0 @@ -../../Task/Damm-algorithm/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Function-definition b/Lang/BASIC/Function-definition deleted file mode 120000 index a052c63292..0000000000 --- a/Lang/BASIC/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Gray-code b/Lang/BASIC/Gray-code deleted file mode 120000 index f0bc6f352f..0000000000 --- a/Lang/BASIC/Gray-code +++ /dev/null @@ -1 +0,0 @@ -../../Task/Gray-code/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Monty-Hall-problem b/Lang/BASIC/Monty-Hall-problem deleted file mode 120000 index ba5a5a279d..0000000000 --- a/Lang/BASIC/Monty-Hall-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Monty-Hall-problem/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Ordered-words b/Lang/BASIC/Ordered-words new file mode 120000 index 0000000000..dd2f98d4e6 --- /dev/null +++ b/Lang/BASIC/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Sorting-algorithms-Quicksort b/Lang/BASIC/Sorting-algorithms-Quicksort deleted file mode 120000 index f7976ecb9f..0000000000 --- a/Lang/BASIC/Sorting-algorithms-Quicksort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Quicksort/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Kronecker-product b/Lang/BASIC256/Kronecker-product new file mode 120000 index 0000000000..dd258524fe --- /dev/null +++ b/Lang/BASIC256/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Multiple-regression b/Lang/BASIC256/Multiple-regression new file mode 120000 index 0000000000..4d8b79e98b --- /dev/null +++ b/Lang/BASIC256/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Nested-templated-data b/Lang/BASIC256/Nested-templated-data new file mode 120000 index 0000000000..f5ddb43f39 --- /dev/null +++ b/Lang/BASIC256/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification b/Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..9a890661d4 --- /dev/null +++ b/Lang/BASIC256/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Sexy-primes b/Lang/BASIC256/Sexy-primes new file mode 120000 index 0000000000..86fc0a12b9 --- /dev/null +++ b/Lang/BASIC256/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/BASIC256 \ No newline at end of file diff --git a/Lang/Bruijn/Harmonic-series b/Lang/Bruijn/Harmonic-series new file mode 120000 index 0000000000..b39ae4ae88 --- /dev/null +++ b/Lang/Bruijn/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Towers-of-Hanoi b/Lang/Bruijn/Towers-of-Hanoi new file mode 120000 index 0000000000..96dafe6af8 --- /dev/null +++ b/Lang/Bruijn/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Bruijn \ No newline at end of file diff --git a/Lang/C++/Add-a-variable-to-a-class-instance-at-runtime b/Lang/C++/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..61888079c6 --- /dev/null +++ b/Lang/C++/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/C++ \ No newline at end of file diff --git a/Lang/C++/Bitcoin-address-validation b/Lang/C++/Bitcoin-address-validation new file mode 120000 index 0000000000..fdb6fa9bf8 --- /dev/null +++ b/Lang/C++/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/C++ \ No newline at end of file diff --git a/Lang/C++/Bitcoin-public-point-to-address b/Lang/C++/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..1229c8b30f --- /dev/null +++ b/Lang/C++/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/C++ \ No newline at end of file diff --git a/Lang/C++/Catmull-Clark-subdivision-surface b/Lang/C++/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..dbaa0ac83b --- /dev/null +++ b/Lang/C++/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/C++ \ No newline at end of file diff --git a/Lang/C++/Compiler-virtual-machine-interpreter b/Lang/C++/Compiler-virtual-machine-interpreter new file mode 120000 index 0000000000..94f3cd637b --- /dev/null +++ b/Lang/C++/Compiler-virtual-machine-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-virtual-machine-interpreter/C++ \ No newline at end of file diff --git a/Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection new file mode 120000 index 0000000000..9b984d5ea4 --- /dev/null +++ b/Lang/C++/Factorial-base-numbers-indexing-permutations-of-a-collection @@ -0,0 +1 @@ +../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/C++ \ No newline at end of file diff --git a/Lang/C++/Im-a-software-engineer-get-me-out-of-here b/Lang/C++/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..7c9de1375f --- /dev/null +++ b/Lang/C++/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/C++ \ No newline at end of file diff --git a/Lang/C++/P-Adic-square-roots b/Lang/C++/P-Adic-square-roots new file mode 120000 index 0000000000..a25d0f7d5c --- /dev/null +++ b/Lang/C++/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/C++ \ No newline at end of file diff --git a/Lang/C++/Simple-database b/Lang/C++/Simple-database new file mode 120000 index 0000000000..60394bf013 --- /dev/null +++ b/Lang/C++/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/C++ \ No newline at end of file diff --git a/Lang/C++/Sort-an-outline-at-every-level b/Lang/C++/Sort-an-outline-at-every-level new file mode 120000 index 0000000000..5467a50bff --- /dev/null +++ b/Lang/C++/Sort-an-outline-at-every-level @@ -0,0 +1 @@ +../../Task/Sort-an-outline-at-every-level/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Additive-primes b/Lang/C-sharp/Additive-primes new file mode 120000 index 0000000000..d958846baf --- /dev/null +++ b/Lang/C-sharp/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Cyclops-numbers b/Lang/C-sharp/Cyclops-numbers new file mode 120000 index 0000000000..c4380e8ccd --- /dev/null +++ b/Lang/C-sharp/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Summarize-primes b/Lang/C-sharp/Summarize-primes new file mode 120000 index 0000000000..de1b22714d --- /dev/null +++ b/Lang/C-sharp/Summarize-primes @@ -0,0 +1 @@ +../../Task/Summarize-primes/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Tau-function b/Lang/C-sharp/Tau-function new file mode 120000 index 0000000000..aa9069413d --- /dev/null +++ b/Lang/C-sharp/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Tau-number b/Lang/C-sharp/Tau-number new file mode 120000 index 0000000000..0980d5ce28 --- /dev/null +++ b/Lang/C-sharp/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Tree-from-nesting-levels b/Lang/C-sharp/Tree-from-nesting-levels new file mode 120000 index 0000000000..e46b1553ea --- /dev/null +++ b/Lang/C-sharp/Tree-from-nesting-levels @@ -0,0 +1 @@ +../../Task/Tree-from-nesting-levels/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Ultra-useful-primes b/Lang/C-sharp/Ultra-useful-primes new file mode 120000 index 0000000000..2258e0373a --- /dev/null +++ b/Lang/C-sharp/Ultra-useful-primes @@ -0,0 +1 @@ +../../Task/Ultra-useful-primes/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Variable-declaration-reset b/Lang/C-sharp/Variable-declaration-reset new file mode 120000 index 0000000000..ec0809da88 --- /dev/null +++ b/Lang/C-sharp/Variable-declaration-reset @@ -0,0 +1 @@ +../../Task/Variable-declaration-reset/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Yellowstone-sequence b/Lang/C-sharp/Yellowstone-sequence new file mode 120000 index 0000000000..793ce587ba --- /dev/null +++ b/Lang/C-sharp/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/C-sharp \ No newline at end of file diff --git a/Lang/C/Hunt-the-Wumpus b/Lang/C/Hunt-the-Wumpus new file mode 120000 index 0000000000..e7186ced48 --- /dev/null +++ b/Lang/C/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/C \ No newline at end of file diff --git a/Lang/C/Pig-the-dice-game-Player b/Lang/C/Pig-the-dice-game-Player new file mode 120000 index 0000000000..28ecb509a8 --- /dev/null +++ b/Lang/C/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/C \ No newline at end of file diff --git a/Lang/COBOL/Nim-game b/Lang/COBOL/Nim-game new file mode 120000 index 0000000000..9a7c582b48 --- /dev/null +++ b/Lang/COBOL/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Parametric-polymorphism b/Lang/COBOL/Parametric-polymorphism new file mode 120000 index 0000000000..44f214df50 --- /dev/null +++ b/Lang/COBOL/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/COBOL \ No newline at end of file diff --git a/Lang/Chapel/Function-definition b/Lang/Chapel/Function-definition new file mode 120000 index 0000000000..589b4afa2c --- /dev/null +++ b/Lang/Chapel/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Maze-generation b/Lang/Chapel/Maze-generation new file mode 120000 index 0000000000..b4c55cfddb --- /dev/null +++ b/Lang/Chapel/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Repeat b/Lang/Chapel/Repeat new file mode 120000 index 0000000000..3c555a4885 --- /dev/null +++ b/Lang/Chapel/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Chapel \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Display-a-linear-combination b/Lang/Chipmunk-Basic/Display-a-linear-combination new file mode 120000 index 0000000000..76f3965566 --- /dev/null +++ b/Lang/Chipmunk-Basic/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences b/Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..24e6f1fb75 --- /dev/null +++ b/Lang/Chipmunk-Basic/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Jensens-Device b/Lang/Chipmunk-Basic/Jensens-Device new file mode 120000 index 0000000000..927dca2f6f --- /dev/null +++ b/Lang/Chipmunk-Basic/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Multiple-regression b/Lang/Chipmunk-Basic/Multiple-regression new file mode 120000 index 0000000000..82844a944e --- /dev/null +++ b/Lang/Chipmunk-Basic/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Nested-templated-data b/Lang/Chipmunk-Basic/Nested-templated-data new file mode 120000 index 0000000000..a7e95ed6f1 --- /dev/null +++ b/Lang/Chipmunk-Basic/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Price-fraction b/Lang/Chipmunk-Basic/Price-fraction new file mode 120000 index 0000000000..895d56d4cf --- /dev/null +++ b/Lang/Chipmunk-Basic/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Proper-divisors b/Lang/Chipmunk-Basic/Proper-divisors new file mode 120000 index 0000000000..e83b2b6ef0 --- /dev/null +++ b/Lang/Chipmunk-Basic/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Rate-counter b/Lang/Chipmunk-Basic/Rate-counter new file mode 120000 index 0000000000..214d671194 --- /dev/null +++ b/Lang/Chipmunk-Basic/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Vector b/Lang/Chipmunk-Basic/Vector new file mode 120000 index 0000000000..68aa51b11b --- /dev/null +++ b/Lang/Chipmunk-Basic/Vector @@ -0,0 +1 @@ +../../Task/Vector/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Commodore-BASIC/N-queens-problem b/Lang/Commodore-BASIC/N-queens-problem new file mode 120000 index 0000000000..d5a4ff5b7a --- /dev/null +++ b/Lang/Commodore-BASIC/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Common-Lisp/Blum-integer b/Lang/Common-Lisp/Blum-integer new file mode 120000 index 0000000000..854dbaeee7 --- /dev/null +++ b/Lang/Common-Lisp/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Factorial-primes b/Lang/Common-Lisp/Factorial-primes new file mode 120000 index 0000000000..cc0d935af1 --- /dev/null +++ b/Lang/Common-Lisp/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Common-Lisp \ No newline at end of file diff --git a/Lang/Cowgol/Display-a-linear-combination b/Lang/Cowgol/Display-a-linear-combination new file mode 120000 index 0000000000..7e169cd6fe --- /dev/null +++ b/Lang/Cowgol/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Cowgol \ No newline at end of file diff --git a/Lang/Dart/15-puzzle-solver b/Lang/Dart/15-puzzle-solver new file mode 120000 index 0000000000..9e8e216a39 --- /dev/null +++ b/Lang/Dart/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Dart \ No newline at end of file diff --git a/Lang/Dart/Jensens-Device b/Lang/Dart/Jensens-Device new file mode 120000 index 0000000000..973fbf791f --- /dev/null +++ b/Lang/Dart/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Dart \ No newline at end of file diff --git a/Lang/Dart/Solve-a-Numbrix-puzzle b/Lang/Dart/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..38339de00c --- /dev/null +++ b/Lang/Dart/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Dart \ No newline at end of file diff --git a/Lang/Draco/Display-a-linear-combination b/Lang/Draco/Display-a-linear-combination new file mode 120000 index 0000000000..bbaeb41c31 --- /dev/null +++ b/Lang/Draco/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Draco \ No newline at end of file diff --git a/Lang/EMal/Babbage-problem b/Lang/EMal/Babbage-problem new file mode 120000 index 0000000000..8a7db13311 --- /dev/null +++ b/Lang/EMal/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/EMal \ No newline at end of file diff --git a/Lang/EMal/Bifid-cipher b/Lang/EMal/Bifid-cipher new file mode 120000 index 0000000000..1dbee9fec8 --- /dev/null +++ b/Lang/EMal/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/EMal \ No newline at end of file diff --git a/Lang/EMal/Mutual-recursion b/Lang/EMal/Mutual-recursion new file mode 120000 index 0000000000..cb3ebc8ca5 --- /dev/null +++ b/Lang/EMal/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/EMal \ No newline at end of file diff --git a/Lang/EMal/Sorting-algorithms-Bogosort b/Lang/EMal/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..8dc8cc02d3 --- /dev/null +++ b/Lang/EMal/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/EMal \ No newline at end of file diff --git a/Lang/EMal/Tree-traversal b/Lang/EMal/Tree-traversal new file mode 120000 index 0000000000..b693d069a6 --- /dev/null +++ b/Lang/EMal/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/EMal \ No newline at end of file diff --git a/Lang/EMal/User-input-Text b/Lang/EMal/User-input-Text new file mode 120000 index 0000000000..3c00cf11ba --- /dev/null +++ b/Lang/EMal/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/EMal \ No newline at end of file diff --git a/Lang/EasyLang/00-LANG.txt b/Lang/EasyLang/00-LANG.txt index aa156f93c8..ba3b92e229 100644 --- a/Lang/EasyLang/00-LANG.txt +++ b/Lang/EasyLang/00-LANG.txt @@ -1,19 +1,19 @@ {{language |exec=interpreted -|site=https://easylang.dev/ +|site=https://easylang.online/ |parampass=value, reference |safety=safe |express=explicit |checking=static |tags=learning, web canvas}} -[https://easylang.dev/ide/ '''Browser IDE'''] +[https://easylang.online/ide/ '''Browser IDE'''] ''Easylang'' is a (beginners) programming language with built-in commands for graphics output. The statically typed language has a reduced syntax and semantics. Variables do not have to be declared, the data type is encoded in the variable name - as was usual in the earlier home computer BASIC. The data types are strings and numbers (floating point), arrays of strings and numbers, and arrays of arrays. Arrays are 1-based and can grow. Programs compiled into an AST tree run in the browser or in the browser IDE. [https://easylang.dev/ide/ A browser IDE] with different tutorials, one for beginners, makes programming and learning to program as easy as possible. -The finished programs can be easily integrated into a [https://easylang.dev/apps/ website]. +The finished programs can be easily integrated into a [https://easylang.online/apps/ website]. ==Todo== [[Tasks not implemented in EasyLang]] \ No newline at end of file diff --git a/Lang/EasyLang/Abelian-sandpile-model b/Lang/EasyLang/Abelian-sandpile-model new file mode 120000 index 0000000000..c97f3c3aa6 --- /dev/null +++ b/Lang/EasyLang/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abelian-sandpile-model-Identity b/Lang/EasyLang/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..c44f8cb53d --- /dev/null +++ b/Lang/EasyLang/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Approximate-equality b/Lang/EasyLang/Approximate-equality new file mode 120000 index 0000000000..916cbf0873 --- /dev/null +++ b/Lang/EasyLang/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Arithmetic-Complex b/Lang/EasyLang/Arithmetic-Complex new file mode 120000 index 0000000000..547a37cd78 --- /dev/null +++ b/Lang/EasyLang/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Greatest-subsequential-sum b/Lang/EasyLang/Greatest-subsequential-sum new file mode 120000 index 0000000000..679d3c6deb --- /dev/null +++ b/Lang/EasyLang/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Guess-the-number-With-feedback-player- b/Lang/EasyLang/Guess-the-number-With-feedback-player- new file mode 120000 index 0000000000..56ad8fd02a --- /dev/null +++ b/Lang/EasyLang/Guess-the-number-With-feedback-player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback-player-/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Halt-and-catch-fire b/Lang/EasyLang/Halt-and-catch-fire new file mode 120000 index 0000000000..fe61f64c40 --- /dev/null +++ b/Lang/EasyLang/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hamming-numbers b/Lang/EasyLang/Hamming-numbers new file mode 120000 index 0000000000..6f52ef2c78 --- /dev/null +++ b/Lang/EasyLang/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hofstadter-Figure-Figure-sequences b/Lang/EasyLang/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..d5a34b275d --- /dev/null +++ b/Lang/EasyLang/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/IBAN b/Lang/EasyLang/IBAN new file mode 120000 index 0000000000..961014b963 --- /dev/null +++ b/Lang/EasyLang/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Iterated-digits-squaring b/Lang/EasyLang/Iterated-digits-squaring new file mode 120000 index 0000000000..193be9fcba --- /dev/null +++ b/Lang/EasyLang/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/JortSort b/Lang/EasyLang/JortSort new file mode 120000 index 0000000000..69c9d425de --- /dev/null +++ b/Lang/EasyLang/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kronecker-product b/Lang/EasyLang/Kronecker-product new file mode 120000 index 0000000000..1246c0ce28 --- /dev/null +++ b/Lang/EasyLang/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kronecker-product-based-fractals b/Lang/EasyLang/Kronecker-product-based-fractals new file mode 120000 index 0000000000..563af0ba71 --- /dev/null +++ b/Lang/EasyLang/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Largest-int-from-concatenated-ints b/Lang/EasyLang/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..10e1335e8a --- /dev/null +++ b/Lang/EasyLang/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Last-letter-first-letter b/Lang/EasyLang/Last-letter-first-letter new file mode 120000 index 0000000000..0b195a1260 --- /dev/null +++ b/Lang/EasyLang/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Longest-increasing-subsequence b/Lang/EasyLang/Longest-increasing-subsequence new file mode 120000 index 0000000000..eabf95f750 --- /dev/null +++ b/Lang/EasyLang/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ludic-numbers b/Lang/EasyLang/Ludic-numbers new file mode 120000 index 0000000000..1d6fc2e015 --- /dev/null +++ b/Lang/EasyLang/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Map-range b/Lang/EasyLang/Map-range new file mode 120000 index 0000000000..7f2fe886c3 --- /dev/null +++ b/Lang/EasyLang/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Move-to-front-algorithm b/Lang/EasyLang/Move-to-front-algorithm new file mode 120000 index 0000000000..8c3f8fe7f9 --- /dev/null +++ b/Lang/EasyLang/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Multisplit b/Lang/EasyLang/Multisplit new file mode 120000 index 0000000000..3f480eaeea --- /dev/null +++ b/Lang/EasyLang/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Negative-base-numbers b/Lang/EasyLang/Negative-base-numbers new file mode 120000 index 0000000000..750b2fa4de --- /dev/null +++ b/Lang/EasyLang/Negative-base-numbers @@ -0,0 +1 @@ +../../Task/Negative-base-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Non-continuous-subsequences b/Lang/EasyLang/Non-continuous-subsequences new file mode 120000 index 0000000000..1ddebfbef7 --- /dev/null +++ b/Lang/EasyLang/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Non-decimal-radices-Input b/Lang/EasyLang/Non-decimal-radices-Input new file mode 120000 index 0000000000..15845b7041 --- /dev/null +++ b/Lang/EasyLang/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Number-reversal-game b/Lang/EasyLang/Number-reversal-game new file mode 120000 index 0000000000..a55399f2e0 --- /dev/null +++ b/Lang/EasyLang/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Partition-an-integer-x-into-n-primes b/Lang/EasyLang/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..21cc93eeed --- /dev/null +++ b/Lang/EasyLang/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pascal-matrix-generation b/Lang/EasyLang/Pascal-matrix-generation new file mode 120000 index 0000000000..2a45a12baf --- /dev/null +++ b/Lang/EasyLang/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pathological-floating-point-problems b/Lang/EasyLang/Pathological-floating-point-problems new file mode 120000 index 0000000000..feb17cf372 --- /dev/null +++ b/Lang/EasyLang/Pathological-floating-point-problems @@ -0,0 +1 @@ +../../Task/Pathological-floating-point-problems/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Peripheral-drift-illusion b/Lang/EasyLang/Peripheral-drift-illusion new file mode 120000 index 0000000000..6922becd71 --- /dev/null +++ b/Lang/EasyLang/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Permutations-Rank-of-a-permutation b/Lang/EasyLang/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..0512aed3af --- /dev/null +++ b/Lang/EasyLang/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Phrase-reversals b/Lang/EasyLang/Phrase-reversals new file mode 120000 index 0000000000..3631697399 --- /dev/null +++ b/Lang/EasyLang/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pierpont-primes b/Lang/EasyLang/Pierpont-primes new file mode 120000 index 0000000000..6e3e44c04c --- /dev/null +++ b/Lang/EasyLang/Pierpont-primes @@ -0,0 +1 @@ +../../Task/Pierpont-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pinstripe-Display b/Lang/EasyLang/Pinstripe-Display new file mode 120000 index 0000000000..db25917458 --- /dev/null +++ b/Lang/EasyLang/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Plasma-effect b/Lang/EasyLang/Plasma-effect new file mode 120000 index 0000000000..5f845f7e61 --- /dev/null +++ b/Lang/EasyLang/Plasma-effect @@ -0,0 +1 @@ +../../Task/Plasma-effect/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pythagorean-quadruples b/Lang/EasyLang/Pythagorean-quadruples new file mode 120000 index 0000000000..63bc250851 --- /dev/null +++ b/Lang/EasyLang/Pythagorean-quadruples @@ -0,0 +1 @@ +../../Task/Pythagorean-quadruples/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Range-expansion b/Lang/EasyLang/Range-expansion new file mode 120000 index 0000000000..b1e04fdc47 --- /dev/null +++ b/Lang/EasyLang/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Rock-paper-scissors b/Lang/EasyLang/Rock-paper-scissors new file mode 120000 index 0000000000..f5bc56ac98 --- /dev/null +++ b/Lang/EasyLang/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ruth-Aaron-numbers b/Lang/EasyLang/Ruth-Aaron-numbers new file mode 120000 index 0000000000..8c50b35963 --- /dev/null +++ b/Lang/EasyLang/Ruth-Aaron-numbers @@ -0,0 +1 @@ +../../Task/Ruth-Aaron-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem b/Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem new file mode 120000 index 0000000000..13c2416787 --- /dev/null +++ b/Lang/EasyLang/Sailors-coconuts-and-a-monkey-problem @@ -0,0 +1 @@ +../../Task/Sailors-coconuts-and-a-monkey-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Scope-Function-names-and-labels b/Lang/EasyLang/Scope-Function-names-and-labels new file mode 120000 index 0000000000..159b6679bd --- /dev/null +++ b/Lang/EasyLang/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..c9738f521a --- /dev/null +++ b/Lang/EasyLang/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Self-numbers b/Lang/EasyLang/Self-numbers new file mode 120000 index 0000000000..219b2abf44 --- /dev/null +++ b/Lang/EasyLang/Self-numbers @@ -0,0 +1 @@ +../../Task/Self-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Show-the-epoch b/Lang/EasyLang/Show-the-epoch new file mode 120000 index 0000000000..67a6b1a9c5 --- /dev/null +++ b/Lang/EasyLang/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sierpinski-triangle b/Lang/EasyLang/Sierpinski-triangle new file mode 120000 index 0000000000..36520550cb --- /dev/null +++ b/Lang/EasyLang/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-a-list-of-object-identifiers b/Lang/EasyLang/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..6767e4212b --- /dev/null +++ b/Lang/EasyLang/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-an-integer-array b/Lang/EasyLang/Sort-an-integer-array new file mode 120000 index 0000000000..b6e22e35fd --- /dev/null +++ b/Lang/EasyLang/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sort-numbers-lexicographically b/Lang/EasyLang/Sort-numbers-lexicographically new file mode 120000 index 0000000000..096e63b030 --- /dev/null +++ b/Lang/EasyLang/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-Algorithms-Circle-Sort b/Lang/EasyLang/Sorting-Algorithms-Circle-Sort new file mode 120000 index 0000000000..575205820f --- /dev/null +++ b/Lang/EasyLang/Sorting-Algorithms-Circle-Sort @@ -0,0 +1 @@ +../../Task/Sorting-Algorithms-Circle-Sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Cocktail-sort b/Lang/EasyLang/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..6ea90a8bea --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Comb-sort b/Lang/EasyLang/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..105d051508 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Pancake-sort b/Lang/EasyLang/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..7f8da5bd54 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Permutation-sort b/Lang/EasyLang/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..858ffd0315 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Shell-sort b/Lang/EasyLang/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..f5b30c5803 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Strand-sort b/Lang/EasyLang/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..005353ca66 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stair-climbing-puzzle b/Lang/EasyLang/Stair-climbing-puzzle new file mode 120000 index 0000000000..e0c07f706d --- /dev/null +++ b/Lang/EasyLang/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stem-and-leaf-plot b/Lang/EasyLang/Stem-and-leaf-plot new file mode 120000 index 0000000000..cf4dace06c --- /dev/null +++ b/Lang/EasyLang/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Taxicab-numbers b/Lang/EasyLang/Taxicab-numbers new file mode 120000 index 0000000000..7035ad16c4 --- /dev/null +++ b/Lang/EasyLang/Taxicab-numbers @@ -0,0 +1 @@ +../../Task/Taxicab-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Tokenize-a-string-with-escaping b/Lang/EasyLang/Tokenize-a-string-with-escaping new file mode 120000 index 0000000000..1059b903ad --- /dev/null +++ b/Lang/EasyLang/Tokenize-a-string-with-escaping @@ -0,0 +1 @@ +../../Task/Tokenize-a-string-with-escaping/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Top-rank-per-group b/Lang/EasyLang/Top-rank-per-group new file mode 120000 index 0000000000..861db59645 --- /dev/null +++ b/Lang/EasyLang/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Verify-distribution-uniformity-Naive b/Lang/EasyLang/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..bc6d548e1b --- /dev/null +++ b/Lang/EasyLang/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Zig-zag-matrix b/Lang/EasyLang/Zig-zag-matrix new file mode 120000 index 0000000000..59c91477d5 --- /dev/null +++ b/Lang/EasyLang/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/EasyLang \ No newline at end of file diff --git a/Lang/Ecstasy/00-LANG.txt b/Lang/Ecstasy/00-LANG.txt index 7358e7f1ea..9c977a310d 100644 --- a/Lang/Ecstasy/00-LANG.txt +++ b/Lang/Ecstasy/00-LANG.txt @@ -25,4 +25,7 @@ The primary benefits of Ecstasy are: * A security model designed for the serverless cloud, using lightweight software containers and dependency injection (IOC/DI) * A reified generic type system with support for unions, intersection, and difference types, first-class tuples and functions, type inference, and type-safe mixins * Built-in concurrency support, with first-class support for object immutability, and the elimination of shared-mutable data -* All of the modern capabilities that developers have grown to depend on, such as: [[garbage collection|Automatic memory management]], an integrated module system, first-class lambdas and functions, partial binding and currying, cross-platform portability, and an open source development model \ No newline at end of file +* All of the modern capabilities that developers have grown to depend on, such as: [[garbage collection|Automatic memory management]], an integrated module system, first-class lambdas and functions, partial binding and currying, cross-platform portability, and an open source development model + +==TODO== +* [[Tasks not implemented in Ecstasy]] \ No newline at end of file diff --git a/Lang/Ecstasy/100-prisoners b/Lang/Ecstasy/100-prisoners new file mode 120000 index 0000000000..e9fb2d2f70 --- /dev/null +++ b/Lang/Ecstasy/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Assertions b/Lang/Ecstasy/Assertions new file mode 120000 index 0000000000..0802d10c0c --- /dev/null +++ b/Lang/Ecstasy/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Pointers-and-references b/Lang/Ecstasy/Pointers-and-references new file mode 120000 index 0000000000..9b85919b2d --- /dev/null +++ b/Lang/Ecstasy/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Program-name b/Lang/Ecstasy/Program-name new file mode 120000 index 0000000000..6411623f47 --- /dev/null +++ b/Lang/Ecstasy/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Reflection-List-methods b/Lang/Ecstasy/Reflection-List-methods new file mode 120000 index 0000000000..f4010fce77 --- /dev/null +++ b/Lang/Ecstasy/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Reflection-List-properties b/Lang/Ecstasy/Reflection-List-properties new file mode 120000 index 0000000000..40ec86fd95 --- /dev/null +++ b/Lang/Ecstasy/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Search-a-list b/Lang/Ecstasy/Search-a-list new file mode 120000 index 0000000000..f6044e825c --- /dev/null +++ b/Lang/Ecstasy/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Send-an-unknown-method-call b/Lang/Ecstasy/Send-an-unknown-method-call new file mode 120000 index 0000000000..5d1a4cbed5 --- /dev/null +++ b/Lang/Ecstasy/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Singleton b/Lang/Ecstasy/Singleton new file mode 120000 index 0000000000..8c9a0eb1b2 --- /dev/null +++ b/Lang/Ecstasy/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-case b/Lang/Ecstasy/String-case new file mode 120000 index 0000000000..75c8cc65c2 --- /dev/null +++ b/Lang/Ecstasy/String-case @@ -0,0 +1 @@ +../../Task/String-case/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-comparison b/Lang/Ecstasy/String-comparison new file mode 120000 index 0000000000..2a690e7c01 --- /dev/null +++ b/Lang/Ecstasy/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-concatenation b/Lang/Ecstasy/String-concatenation new file mode 120000 index 0000000000..a8fc37bb41 --- /dev/null +++ b/Lang/Ecstasy/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/String-length b/Lang/Ecstasy/String-length new file mode 120000 index 0000000000..e3f6d6a12a --- /dev/null +++ b/Lang/Ecstasy/String-length @@ -0,0 +1 @@ +../../Task/String-length/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Substring b/Lang/Ecstasy/Substring new file mode 120000 index 0000000000..59160f9d22 --- /dev/null +++ b/Lang/Ecstasy/Substring @@ -0,0 +1 @@ +../../Task/Substring/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/Substring-Top-and-tail b/Lang/Ecstasy/Substring-Top-and-tail new file mode 120000 index 0000000000..cf035aa347 --- /dev/null +++ b/Lang/Ecstasy/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Ecstasy \ No newline at end of file diff --git a/Lang/Ecstasy/System-time b/Lang/Ecstasy/System-time new file mode 120000 index 0000000000..4b0a593cce --- /dev/null +++ b/Lang/Ecstasy/System-time @@ -0,0 +1 @@ +../../Task/System-time/Ecstasy \ No newline at end of file diff --git a/Lang/Elixir/Parallel-brute-force b/Lang/Elixir/Parallel-brute-force new file mode 120000 index 0000000000..154ccc9bb9 --- /dev/null +++ b/Lang/Elixir/Parallel-brute-force @@ -0,0 +1 @@ +../../Task/Parallel-brute-force/Elixir \ No newline at end of file diff --git a/Lang/Elm/Caesar-cipher b/Lang/Elm/Caesar-cipher new file mode 120000 index 0000000000..e2f4604523 --- /dev/null +++ b/Lang/Elm/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Elm \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Abbreviations-automatic b/Lang/Emacs-Lisp/Abbreviations-automatic new file mode 120000 index 0000000000..917fbde092 --- /dev/null +++ b/Lang/Emacs-Lisp/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Anagrams b/Lang/Emacs-Lisp/Anagrams new file mode 120000 index 0000000000..0bf987f884 --- /dev/null +++ b/Lang/Emacs-Lisp/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Compare-length-of-two-strings b/Lang/Emacs-Lisp/Compare-length-of-two-strings new file mode 120000 index 0000000000..2aa87a97f8 --- /dev/null +++ b/Lang/Emacs-Lisp/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Date-manipulation b/Lang/Emacs-Lisp/Date-manipulation new file mode 120000 index 0000000000..d88e6a9576 --- /dev/null +++ b/Lang/Emacs-Lisp/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Determine-if-a-string-is-numeric b/Lang/Emacs-Lisp/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..2314291eaa --- /dev/null +++ b/Lang/Emacs-Lisp/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Determine-sentence-type b/Lang/Emacs-Lisp/Determine-sentence-type new file mode 120000 index 0000000000..633b068253 --- /dev/null +++ b/Lang/Emacs-Lisp/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Ordered-words b/Lang/Emacs-Lisp/Ordered-words new file mode 120000 index 0000000000..444b596fcd --- /dev/null +++ b/Lang/Emacs-Lisp/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Snake b/Lang/Emacs-Lisp/Snake new file mode 120000 index 0000000000..b334d7a373 --- /dev/null +++ b/Lang/Emacs-Lisp/Snake @@ -0,0 +1 @@ +../../Task/Snake/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Substitution-cipher b/Lang/Emacs-Lisp/Substitution-cipher new file mode 120000 index 0000000000..93f7ee4d63 --- /dev/null +++ b/Lang/Emacs-Lisp/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Fortran/Sleeping-Beauty-problem b/Lang/Fortran/Sleeping-Beauty-problem new file mode 120000 index 0000000000..35b7547112 --- /dev/null +++ b/Lang/Fortran/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Fortran \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Bin-given-limits b/Lang/Free-Pascal-Lazarus/Bin-given-limits new file mode 120000 index 0000000000..090d25165e --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Closures-Value-capture b/Lang/Free-Pascal-Lazarus/Closures-Value-capture new file mode 120000 index 0000000000..4b2493493f --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Parallel-calculations b/Lang/Free-Pascal-Lazarus/Parallel-calculations new file mode 120000 index 0000000000..191ed1dae7 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/FreeBASIC/B-zier-curves-Intersections b/Lang/FreeBASIC/B-zier-curves-Intersections new file mode 120000 index 0000000000..e1718d7dc9 --- /dev/null +++ b/Lang/FreeBASIC/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Constrained-genericity b/Lang/FreeBASIC/Constrained-genericity new file mode 120000 index 0000000000..1fc68e6907 --- /dev/null +++ b/Lang/FreeBASIC/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Execute-Computer-Zero b/Lang/FreeBASIC/Execute-Computer-Zero new file mode 120000 index 0000000000..018dffe9b4 --- /dev/null +++ b/Lang/FreeBASIC/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Execute-SNUSP b/Lang/FreeBASIC/Execute-SNUSP new file mode 120000 index 0000000000..7b179aedb8 --- /dev/null +++ b/Lang/FreeBASIC/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Execute-a-Markov-algorithm b/Lang/FreeBASIC/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..7f61263c19 --- /dev/null +++ b/Lang/FreeBASIC/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Imaginary-base-numbers b/Lang/FreeBASIC/Imaginary-base-numbers new file mode 120000 index 0000000000..00ee9d8fe6 --- /dev/null +++ b/Lang/FreeBASIC/Imaginary-base-numbers @@ -0,0 +1 @@ +../../Task/Imaginary-base-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Nested-templated-data b/Lang/FreeBASIC/Nested-templated-data new file mode 120000 index 0000000000..064256a2d8 --- /dev/null +++ b/Lang/FreeBASIC/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Padovan-sequence b/Lang/FreeBASIC/Padovan-sequence new file mode 120000 index 0000000000..efb5ea56df --- /dev/null +++ b/Lang/FreeBASIC/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-PCG32 b/Lang/FreeBASIC/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..8a007fed91 --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 b/Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..233c73713f --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star b/Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..a40446f6c8 --- /dev/null +++ b/Lang/FreeBASIC/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Runtime-evaluation-In-an-environment b/Lang/FreeBASIC/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..80c5a69b35 --- /dev/null +++ b/Lang/FreeBASIC/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Solve-the-no-connection-puzzle b/Lang/FreeBASIC/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..b14a0d6097 --- /dev/null +++ b/Lang/FreeBASIC/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Write-to-Windows-event-log b/Lang/FreeBASIC/Write-to-Windows-event-log new file mode 120000 index 0000000000..8993ae4828 --- /dev/null +++ b/Lang/FreeBASIC/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/FreeBASIC \ No newline at end of file diff --git a/Lang/Frink/24-game b/Lang/Frink/24-game new file mode 120000 index 0000000000..843d6f51e2 --- /dev/null +++ b/Lang/Frink/24-game @@ -0,0 +1 @@ +../../Task/24-game/Frink \ No newline at end of file diff --git a/Lang/FutureBasic/24-game b/Lang/FutureBasic/24-game new file mode 120000 index 0000000000..f1ea3d0684 --- /dev/null +++ b/Lang/FutureBasic/24-game @@ -0,0 +1 @@ +../../Task/24-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/ASCII-art-diagram-converter b/Lang/FutureBasic/ASCII-art-diagram-converter new file mode 120000 index 0000000000..cb5711ff54 --- /dev/null +++ b/Lang/FutureBasic/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arbitrary-precision-integers-included- b/Lang/FutureBasic/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..ca9deb04e2 --- /dev/null +++ b/Lang/FutureBasic/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Biorhythms b/Lang/FutureBasic/Biorhythms new file mode 120000 index 0000000000..db55b5c43b --- /dev/null +++ b/Lang/FutureBasic/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Brilliant-numbers b/Lang/FutureBasic/Brilliant-numbers new file mode 120000 index 0000000000..0ee49e027a --- /dev/null +++ b/Lang/FutureBasic/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Check-output-device-is-a-terminal b/Lang/FutureBasic/Check-output-device-is-a-terminal new file mode 120000 index 0000000000..e2e8c9c4eb --- /dev/null +++ b/Lang/FutureBasic/Check-output-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-output-device-is-a-terminal/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Combinations b/Lang/FutureBasic/Combinations new file mode 120000 index 0000000000..d7395ea4d1 --- /dev/null +++ b/Lang/FutureBasic/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Copy-stdin-to-stdout b/Lang/FutureBasic/Copy-stdin-to-stdout new file mode 120000 index 0000000000..9a5df43082 --- /dev/null +++ b/Lang/FutureBasic/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-sentence-type b/Lang/FutureBasic/Determine-sentence-type new file mode 120000 index 0000000000..fce2322962 --- /dev/null +++ b/Lang/FutureBasic/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Floyds-triangle b/Lang/FutureBasic/Floyds-triangle new file mode 120000 index 0000000000..134b2be232 --- /dev/null +++ b/Lang/FutureBasic/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Function-prototype b/Lang/FutureBasic/Function-prototype new file mode 120000 index 0000000000..00a31e111b --- /dev/null +++ b/Lang/FutureBasic/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Go-Fish b/Lang/FutureBasic/Go-Fish new file mode 120000 index 0000000000..cc2210d25a --- /dev/null +++ b/Lang/FutureBasic/Go-Fish @@ -0,0 +1 @@ +../../Task/Go-Fish/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Honeycombs b/Lang/FutureBasic/Honeycombs new file mode 120000 index 0000000000..306c30d982 --- /dev/null +++ b/Lang/FutureBasic/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Monty-Hall-problem b/Lang/FutureBasic/Monty-Hall-problem new file mode 120000 index 0000000000..0d9da7e7cc --- /dev/null +++ b/Lang/FutureBasic/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Record-sound b/Lang/FutureBasic/Record-sound new file mode 120000 index 0000000000..7ce89c688d --- /dev/null +++ b/Lang/FutureBasic/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/FutureBasic \ No newline at end of file diff --git a/Lang/GW-BASIC/Damm-algorithm b/Lang/GW-BASIC/Damm-algorithm new file mode 120000 index 0000000000..b0cc19e6df --- /dev/null +++ b/Lang/GW-BASIC/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Display-a-linear-combination b/Lang/GW-BASIC/Display-a-linear-combination new file mode 120000 index 0000000000..8162367d7b --- /dev/null +++ b/Lang/GW-BASIC/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Gray-code b/Lang/GW-BASIC/Gray-code new file mode 120000 index 0000000000..a45f2031ed --- /dev/null +++ b/Lang/GW-BASIC/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Jensens-Device b/Lang/GW-BASIC/Jensens-Device new file mode 120000 index 0000000000..0236b00319 --- /dev/null +++ b/Lang/GW-BASIC/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Nested-templated-data b/Lang/GW-BASIC/Nested-templated-data new file mode 120000 index 0000000000..bb39849801 --- /dev/null +++ b/Lang/GW-BASIC/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Primality-by-trial-division b/Lang/GW-BASIC/Primality-by-trial-division new file mode 120000 index 0000000000..2b782a101b --- /dev/null +++ b/Lang/GW-BASIC/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Vector b/Lang/GW-BASIC/Vector new file mode 120000 index 0000000000..6d1d7a6796 --- /dev/null +++ b/Lang/GW-BASIC/Vector @@ -0,0 +1 @@ +../../Task/Vector/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Jensens-Device b/Lang/Gambas/Jensens-Device new file mode 120000 index 0000000000..cf682dd548 --- /dev/null +++ b/Lang/Gambas/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Gambas \ No newline at end of file diff --git a/Lang/Gambas/M-bius-function b/Lang/Gambas/M-bius-function new file mode 120000 index 0000000000..4846367944 --- /dev/null +++ b/Lang/Gambas/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Proper-divisors b/Lang/Gambas/Proper-divisors new file mode 120000 index 0000000000..c95a4aae71 --- /dev/null +++ b/Lang/Gambas/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/Gambas \ No newline at end of file diff --git a/Lang/Go/Factorial-primes b/Lang/Go/Factorial-primes new file mode 120000 index 0000000000..5b25426fd0 --- /dev/null +++ b/Lang/Go/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Go \ No newline at end of file diff --git a/Lang/Java/Arena-storage-pool b/Lang/Java/Arena-storage-pool new file mode 120000 index 0000000000..11592b83c1 --- /dev/null +++ b/Lang/Java/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Java \ No newline at end of file diff --git a/Lang/Java/Bitcoin-public-point-to-address b/Lang/Java/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..cbdcab404f --- /dev/null +++ b/Lang/Java/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Java \ No newline at end of file diff --git a/Lang/Java/Catmull-Clark-subdivision-surface b/Lang/Java/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..cc0173bf86 --- /dev/null +++ b/Lang/Java/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/Java \ No newline at end of file diff --git a/Lang/Java/Compiler-virtual-machine-interpreter b/Lang/Java/Compiler-virtual-machine-interpreter new file mode 120000 index 0000000000..8a6c333099 --- /dev/null +++ b/Lang/Java/Compiler-virtual-machine-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-virtual-machine-interpreter/Java \ No newline at end of file diff --git a/Lang/Java/Im-a-software-engineer-get-me-out-of-here b/Lang/Java/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..5e4c7fd308 --- /dev/null +++ b/Lang/Java/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/Java \ No newline at end of file diff --git a/Lang/Java/P-Adic-square-roots b/Lang/Java/P-Adic-square-roots new file mode 120000 index 0000000000..768922bdbb --- /dev/null +++ b/Lang/Java/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Java \ No newline at end of file diff --git a/Lang/Java/Topic-variable b/Lang/Java/Topic-variable new file mode 120000 index 0000000000..25c03be6d5 --- /dev/null +++ b/Lang/Java/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Java \ No newline at end of file diff --git a/Lang/Jq/00-LANG.txt b/Lang/Jq/00-LANG.txt index 3eba7f05c0..a2d6626be7 100644 --- a/Lang/Jq/00-LANG.txt +++ b/Lang/Jq/00-LANG.txt @@ -7,9 +7,14 @@ jq was originally designed and developed by Stephen Dolan. ==jq Modules at rosettacode.org== * [[:Category:Jq/assert.jq|assert.jq]] - module to support assertions +* [[:Category:Jq/bitwise.jq|bitwise.jq]] - bit streams, bit arrays, and integers * [[:Category:Jq/fibonacci.jq|fibonacci.jq]] - Fibonacci sequence and Fibonacci coding * [[:Category:Jq/peg.jq|peg.jq]] - Parsing Expression Grammar foundations * [[:Category:Jq/polynomials.jq|polynomials.jq]] - polynomials as JSON arrays +* [[:Category:Jq/rational.jq|rational.jq]] - rational numbers + +* [[:Category:Jq/Date.jq|Date.jq]] - Gregorian calendar from the year 1 +* [[:Category:Jq/MRG32k3a.jq|MRG32k3a.jq]] - MRG32k3a Combined Recursive Pseudo-Random Number Generator * [[:Category:Jq/RealSet.jq|RealSet.jq]] - Union of finite real intervals ==Todo== diff --git a/Lang/Jq/2048 b/Lang/Jq/2048 new file mode 120000 index 0000000000..e78d154a28 --- /dev/null +++ b/Lang/Jq/2048 @@ -0,0 +1 @@ +../../Task/2048/Jq \ No newline at end of file diff --git a/Lang/Jq/24-game b/Lang/Jq/24-game new file mode 120000 index 0000000000..1db8a29eb4 --- /dev/null +++ b/Lang/Jq/24-game @@ -0,0 +1 @@ +../../Task/24-game/Jq \ No newline at end of file diff --git a/Lang/Jq/Averages-Simple-moving-average b/Lang/Jq/Averages-Simple-moving-average new file mode 120000 index 0000000000..7c27d5bee2 --- /dev/null +++ b/Lang/Jq/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Jq \ No newline at end of file diff --git a/Lang/Jq/Bitwise-operations b/Lang/Jq/Bitwise-operations new file mode 120000 index 0000000000..eff5a2f904 --- /dev/null +++ b/Lang/Jq/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Jq \ No newline at end of file diff --git a/Lang/Jq/CRC-32 b/Lang/Jq/CRC-32 new file mode 120000 index 0000000000..800ab8f0ad --- /dev/null +++ b/Lang/Jq/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Jq \ No newline at end of file diff --git a/Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..90c56c3b3a --- /dev/null +++ b/Lang/Jq/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Jq \ No newline at end of file diff --git a/Lang/Jq/Deconvolution-1D b/Lang/Jq/Deconvolution-1D new file mode 120000 index 0000000000..4f872c1005 --- /dev/null +++ b/Lang/Jq/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Jq \ No newline at end of file diff --git a/Lang/Jq/Display-an-outline-as-a-nested-table b/Lang/Jq/Display-an-outline-as-a-nested-table new file mode 120000 index 0000000000..37137659b6 --- /dev/null +++ b/Lang/Jq/Display-an-outline-as-a-nested-table @@ -0,0 +1 @@ +../../Task/Display-an-outline-as-a-nested-table/Jq \ No newline at end of file diff --git a/Lang/Jq/Draw-a-cuboid b/Lang/Jq/Draw-a-cuboid new file mode 120000 index 0000000000..2af657c230 --- /dev/null +++ b/Lang/Jq/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Jq \ No newline at end of file diff --git a/Lang/Jq/Entropy-Narcissist b/Lang/Jq/Entropy-Narcissist new file mode 120000 index 0000000000..f142d7e681 --- /dev/null +++ b/Lang/Jq/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/Jq \ No newline at end of file diff --git a/Lang/Jq/Factors-of-a-Mersenne-number b/Lang/Jq/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..e34af6567d --- /dev/null +++ b/Lang/Jq/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Jq \ No newline at end of file diff --git a/Lang/Jq/File-size-distribution b/Lang/Jq/File-size-distribution new file mode 120000 index 0000000000..d42e94402e --- /dev/null +++ b/Lang/Jq/File-size-distribution @@ -0,0 +1 @@ +../../Task/File-size-distribution/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-Chess960-starting-position-identifier b/Lang/Jq/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..ea292cff65 --- /dev/null +++ b/Lang/Jq/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/Jq \ No newline at end of file diff --git a/Lang/Jq/Find-duplicate-files b/Lang/Jq/Find-duplicate-files new file mode 120000 index 0000000000..289f08d02f --- /dev/null +++ b/Lang/Jq/Find-duplicate-files @@ -0,0 +1 @@ +../../Task/Find-duplicate-files/Jq \ No newline at end of file diff --git a/Lang/Jq/French-Republican-calendar b/Lang/Jq/French-Republican-calendar new file mode 120000 index 0000000000..d495d14d71 --- /dev/null +++ b/Lang/Jq/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Jq \ No newline at end of file diff --git a/Lang/Jq/Generate-random-chess-position b/Lang/Jq/Generate-random-chess-position new file mode 120000 index 0000000000..a6ff2b1df0 --- /dev/null +++ b/Lang/Jq/Generate-random-chess-position @@ -0,0 +1 @@ +../../Task/Generate-random-chess-position/Jq \ No newline at end of file diff --git a/Lang/Jq/Giuga-numbers b/Lang/Jq/Giuga-numbers new file mode 120000 index 0000000000..b5850902a3 --- /dev/null +++ b/Lang/Jq/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Graph-colouring b/Lang/Jq/Graph-colouring new file mode 120000 index 0000000000..07b418f3a3 --- /dev/null +++ b/Lang/Jq/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/Jq \ No newline at end of file diff --git a/Lang/Jq/Introspection b/Lang/Jq/Introspection new file mode 120000 index 0000000000..cdb6f22cc1 --- /dev/null +++ b/Lang/Jq/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Jq \ No newline at end of file diff --git a/Lang/Jq/Knights-tour b/Lang/Jq/Knights-tour new file mode 120000 index 0000000000..ca47275558 --- /dev/null +++ b/Lang/Jq/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Jq \ No newline at end of file diff --git a/Lang/Jq/Levenshtein-distance-Alignment b/Lang/Jq/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..b331da38ff --- /dev/null +++ b/Lang/Jq/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/Jq \ No newline at end of file diff --git a/Lang/Jq/Mayan-calendar b/Lang/Jq/Mayan-calendar new file mode 120000 index 0000000000..aa0964c1d8 --- /dev/null +++ b/Lang/Jq/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/Jq \ No newline at end of file diff --git a/Lang/Jq/Mind-boggling-card-trick b/Lang/Jq/Mind-boggling-card-trick new file mode 120000 index 0000000000..11a1e6dd3d --- /dev/null +++ b/Lang/Jq/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/Jq \ No newline at end of file diff --git a/Lang/Jq/Minimal-steps-down-to-1 b/Lang/Jq/Minimal-steps-down-to-1 new file mode 120000 index 0000000000..d05488db25 --- /dev/null +++ b/Lang/Jq/Minimal-steps-down-to-1 @@ -0,0 +1 @@ +../../Task/Minimal-steps-down-to-1/Jq \ No newline at end of file diff --git a/Lang/Jq/Modified-random-distribution b/Lang/Jq/Modified-random-distribution new file mode 120000 index 0000000000..5585f4b8dd --- /dev/null +++ b/Lang/Jq/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/Jq \ No newline at end of file diff --git a/Lang/Jq/Multiplicative-order b/Lang/Jq/Multiplicative-order new file mode 120000 index 0000000000..72c4d667a9 --- /dev/null +++ b/Lang/Jq/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Jq \ No newline at end of file diff --git a/Lang/Jq/Nonoblock b/Lang/Jq/Nonoblock new file mode 120000 index 0000000000..f2323057e5 --- /dev/null +++ b/Lang/Jq/Nonoblock @@ -0,0 +1 @@ +../../Task/Nonoblock/Jq \ No newline at end of file diff --git a/Lang/Jq/Nonogram-solver b/Lang/Jq/Nonogram-solver new file mode 120000 index 0000000000..2ae5949d16 --- /dev/null +++ b/Lang/Jq/Nonogram-solver @@ -0,0 +1 @@ +../../Task/Nonogram-solver/Jq \ No newline at end of file diff --git a/Lang/Jq/P-value-correction b/Lang/Jq/P-value-correction new file mode 120000 index 0000000000..4685fd057d --- /dev/null +++ b/Lang/Jq/P-value-correction @@ -0,0 +1 @@ +../../Task/P-value-correction/Jq \ No newline at end of file diff --git a/Lang/Jq/Palindromic-gapful-numbers b/Lang/Jq/Palindromic-gapful-numbers new file mode 120000 index 0000000000..3f1d4b0a65 --- /dev/null +++ b/Lang/Jq/Palindromic-gapful-numbers @@ -0,0 +1 @@ +../../Task/Palindromic-gapful-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Peaceful-chess-queen-armies b/Lang/Jq/Peaceful-chess-queen-armies new file mode 120000 index 0000000000..7c675a3306 --- /dev/null +++ b/Lang/Jq/Peaceful-chess-queen-armies @@ -0,0 +1 @@ +../../Task/Peaceful-chess-queen-armies/Jq \ No newline at end of file diff --git a/Lang/Jq/Pentomino-tiling b/Lang/Jq/Pentomino-tiling new file mode 120000 index 0000000000..cce133df04 --- /dev/null +++ b/Lang/Jq/Pentomino-tiling @@ -0,0 +1 @@ +../../Task/Pentomino-tiling/Jq \ No newline at end of file diff --git a/Lang/Jq/Perlin-noise b/Lang/Jq/Perlin-noise new file mode 120000 index 0000000000..eb52c317a2 --- /dev/null +++ b/Lang/Jq/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/Jq \ No newline at end of file diff --git a/Lang/Jq/Pisano-period b/Lang/Jq/Pisano-period new file mode 120000 index 0000000000..223468a26a --- /dev/null +++ b/Lang/Jq/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Jq \ No newline at end of file diff --git a/Lang/Jq/Poker-hand-analyser b/Lang/Jq/Poker-hand-analyser new file mode 120000 index 0000000000..fd9738ce61 --- /dev/null +++ b/Lang/Jq/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Jq \ No newline at end of file diff --git a/Lang/Jq/Polynomial-regression b/Lang/Jq/Polynomial-regression new file mode 120000 index 0000000000..56985e2ba4 --- /dev/null +++ b/Lang/Jq/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a b/Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a new file mode 120000 index 0000000000..8a1fa69d52 --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-PCG32 b/Lang/Jq/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..c80dea5d5d --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-Xorshift-star b/Lang/Jq/Pseudo-random-numbers-Xorshift-star new file mode 120000 index 0000000000..54ff010417 --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-Xorshift-star @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Xorshift-star/Jq \ No newline at end of file diff --git a/Lang/Jq/Ramer-Douglas-Peucker-line-simplification b/Lang/Jq/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..2692c011c6 --- /dev/null +++ b/Lang/Jq/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Jq \ No newline at end of file diff --git a/Lang/Jq/Random-sentence-from-book b/Lang/Jq/Random-sentence-from-book new file mode 120000 index 0000000000..677f7ffdcc --- /dev/null +++ b/Lang/Jq/Random-sentence-from-book @@ -0,0 +1 @@ +../../Task/Random-sentence-from-book/Jq \ No newline at end of file diff --git a/Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users b/Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users new file mode 120000 index 0000000000..41c301e751 --- /dev/null +++ b/Lang/Jq/Rosetta-Code-Rank-languages-by-number-of-users @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-number-of-users/Jq \ No newline at end of file diff --git a/Lang/Jq/Set-puzzle b/Lang/Jq/Set-puzzle new file mode 120000 index 0000000000..4d4860ff33 --- /dev/null +++ b/Lang/Jq/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Set-right-adjacent-bits b/Lang/Jq/Set-right-adjacent-bits new file mode 120000 index 0000000000..74d85af7c9 --- /dev/null +++ b/Lang/Jq/Set-right-adjacent-bits @@ -0,0 +1 @@ +../../Task/Set-right-adjacent-bits/Jq \ No newline at end of file diff --git a/Lang/Jq/Sierpinski-pentagon b/Lang/Jq/Sierpinski-pentagon new file mode 120000 index 0000000000..25b52521df --- /dev/null +++ b/Lang/Jq/Sierpinski-pentagon @@ -0,0 +1 @@ +../../Task/Sierpinski-pentagon/Jq \ No newline at end of file diff --git a/Lang/Jq/Sleeping-Beauty-problem b/Lang/Jq/Sleeping-Beauty-problem new file mode 120000 index 0000000000..56204d6c76 --- /dev/null +++ b/Lang/Jq/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-a-Hidato-puzzle b/Lang/Jq/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..e3f6b38721 --- /dev/null +++ b/Lang/Jq/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-a-Holy-Knights-tour b/Lang/Jq/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..d69331eff1 --- /dev/null +++ b/Lang/Jq/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Jq \ No newline at end of file diff --git a/Lang/Jq/Solve-a-Numbrix-puzzle b/Lang/Jq/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..29721632e1 --- /dev/null +++ b/Lang/Jq/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Jq \ No newline at end of file diff --git a/Lang/Jq/Sort-an-outline-at-every-level b/Lang/Jq/Sort-an-outline-at-every-level new file mode 120000 index 0000000000..bce371340d --- /dev/null +++ b/Lang/Jq/Sort-an-outline-at-every-level @@ -0,0 +1 @@ +../../Task/Sort-an-outline-at-every-level/Jq \ No newline at end of file diff --git a/Lang/Jq/Thieles-interpolation-formula b/Lang/Jq/Thieles-interpolation-formula new file mode 120000 index 0000000000..25d4327e8c --- /dev/null +++ b/Lang/Jq/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Jq \ No newline at end of file diff --git a/Lang/Jq/Tic-tac-toe b/Lang/Jq/Tic-tac-toe new file mode 120000 index 0000000000..29e18a13ef --- /dev/null +++ b/Lang/Jq/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Jq \ No newline at end of file diff --git a/Lang/Jq/War-card-game b/Lang/Jq/War-card-game new file mode 120000 index 0000000000..428c4a1307 --- /dev/null +++ b/Lang/Jq/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Jq \ No newline at end of file diff --git a/Lang/Jq/Wordiff b/Lang/Jq/Wordiff new file mode 120000 index 0000000000..61aa15852c --- /dev/null +++ b/Lang/Jq/Wordiff @@ -0,0 +1 @@ +../../Task/Wordiff/Jq \ No newline at end of file diff --git a/Lang/K/Find-common-directory-path b/Lang/K/Find-common-directory-path new file mode 120000 index 0000000000..21e1ffcdd3 --- /dev/null +++ b/Lang/K/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/K \ No newline at end of file diff --git a/Lang/K/Monty-Hall-problem b/Lang/K/Monty-Hall-problem new file mode 120000 index 0000000000..8fb0f9e98b --- /dev/null +++ b/Lang/K/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/K \ No newline at end of file diff --git a/Lang/Kotlin/00-LANG.txt b/Lang/Kotlin/00-LANG.txt index 5f33d4bd2a..95d9b59867 100644 --- a/Lang/Kotlin/00-LANG.txt +++ b/Lang/Kotlin/00-LANG.txt @@ -4,7 +4,7 @@ |site=http://kotlinlang.org |hopl=no }} -Kotlin is a statically-typed programming language that runs on the [[JVM]] and can also be compiled to JavaScript. It is being developed by JetBrains with assistance from open source contributors and is intended for industrial use. +Kotlin is a statically-typed programming language that runs on the [[runs on vm::Java Virtual Machine]] (JVM) and can also be compiled to JavaScript. It is being developed by JetBrains with assistance from open source contributors and is intended for industrial use. In addition, a separate team at JetBrains is developing a version of Kotlin which compiles (via LLVM) directly to machine code for various platforms. The first Technology Preview for this version was rolled out in April 2017. diff --git a/Lang/Kotlin/Compare-length-of-two-strings b/Lang/Kotlin/Compare-length-of-two-strings new file mode 120000 index 0000000000..a8c0b8d6cf --- /dev/null +++ b/Lang/Kotlin/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Factorial-primes b/Lang/Kotlin/Factorial-primes new file mode 120000 index 0000000000..36b19250f9 --- /dev/null +++ b/Lang/Kotlin/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Kotlin \ No newline at end of file diff --git a/Lang/Langur/00-LANG.txt b/Lang/Langur/00-LANG.txt index c2da20439a..0c64770672 100644 --- a/Lang/Langur/00-LANG.txt +++ b/Lang/Langur/00-LANG.txt @@ -3,9 +3,9 @@ |hopl=no }} -Langur is an open-source imperative/functional programming language. The name langur begins with a lowercase letter when it does not start a sentence. +Langur is an open-source programming language that natively uses decimal floating point, and deals with extremely large and small numbers. Its principles of design are accuracy in calculation and a concise, expressive syntax. The name langur begins with a lowercase letter when it does not start a sentence. -Langur code can be run with script files or with its REPL. The recommended file name extension is .langur. +Langur code can be run from executable files, or you can use the REPL. The recommended file name extension is .langur. Langur uses a hash mark for single line comments. Therefore, script files may begin with a shebang to tell a Linux shell where to find the interpreter. diff --git a/Lang/Langur/Babbage-problem b/Lang/Langur/Babbage-problem new file mode 120000 index 0000000000..662297217a --- /dev/null +++ b/Lang/Langur/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/Langur \ No newline at end of file diff --git a/Lang/Langur/I-before-E-except-after-C b/Lang/Langur/I-before-E-except-after-C new file mode 120000 index 0000000000..a4c67c55c7 --- /dev/null +++ b/Lang/Langur/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Langur \ No newline at end of file diff --git a/Lang/Langur/Safe-addition b/Lang/Langur/Safe-addition new file mode 120000 index 0000000000..9cd478ca7f --- /dev/null +++ b/Lang/Langur/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Langur \ No newline at end of file diff --git a/Lang/Langur/String-interpolation-included- b/Lang/Langur/String-interpolation-included- new file mode 120000 index 0000000000..e0b5bfaf9c --- /dev/null +++ b/Lang/Langur/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Langur \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Poker-hand-analyser b/Lang/Liberty-BASIC/Poker-hand-analyser new file mode 120000 index 0000000000..3ed8c3b507 --- /dev/null +++ b/Lang/Liberty-BASIC/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Lilypond/00-LANG.txt b/Lang/Lilypond/00-LANG.txt index 5c24c70c93..9afe2b1bd9 100644 --- a/Lang/Lilypond/00-LANG.txt +++ b/Lang/Lilypond/00-LANG.txt @@ -1,9 +1 @@ -{{stub}} -{{language|lilypond -|site=http://www.lilypond.org/ -|hopl=no -}} - -The lilypond language is used by the lilypond score production software for describing the layout of musical score sheets. - -[[Category:Musical Notation]] \ No newline at end of file +#REDIRECT [[:Category:LilyPond]] \ No newline at end of file diff --git a/Lang/Locomotive-Basic/00-LANG.txt b/Lang/Locomotive-Basic/00-LANG.txt index 04db5b5ea8..5045a1b047 100644 --- a/Lang/Locomotive-Basic/00-LANG.txt +++ b/Lang/Locomotive-Basic/00-LANG.txt @@ -7,9 +7,9 @@ '''Locomotive BASIC''' is a variant of BASIC that is built into the ROM of the [[wp:Amstrad CPC|Amstrad CPC]] series of home computers introduced in 1984. In the 1980s, the CPC was a popular, slightly more expensive alternative to the Commodore C64/C128. It was not just suited for games but also office work because of its high resolution display and [[wp:CP/M|CP/M]] support. -The easiest way to use Locomotive BASIC today is [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic], a very fast implementation in JavaScript which also allows easy pasting of code from Rosetta Code. Note that programs will run much faster in CPCBasic than on a real CPC. To slow down a program, add an extra delay loop to the main loop, e.g.:for delay=1 to 5:frame:nextwhich will pause for five frames or 0.1 seconds. +The easiest way to use Locomotive BASIC today is [https://benchmarko.github.io/CPCBasic/cpcbasic.html CPCBasic], a very fast implementation in JavaScript which also allows easy pasting of code from Rosetta Code. Note that programs will run much faster in CPCBasic than on a real CPC. To slow down a program, add an extra delay loop to the main loop, e.g. for delay=1 to 5:frame:nextwhich will pause for five frames or 0.1 seconds. -[https://www.retrovm.com/ CPCBox] is another option for the web browser, a whole-machine JavaScript CPC emulator mainly for games which has good compatibility but which lacks copy and paste support. +[https://retroshowcase.gr/cpcbox-master/ CPCBox] is another option for the web browser, a whole-machine JavaScript CPC emulator mainly for games which has good compatibility but which lacks copy and paste support. Locomotive BASIC can also be used via native CPC emulators such as [http://www.winape.net/ WinAPE] (Windows) or [http://sourceforge.net/projects/javacpc/ JavaCPC] (Windows/macOS/Linux). All these CPC emulators are also perfectly legal because Amstrad has given their permission for distributing CPC ROM images with emulators. @@ -19,14 +19,14 @@ Either use the CPCBasic browser-based Locomotive Basic emulator (https://benchma In CPCBasic, enter your program, e.g. -10 print "Hello World!" +10 print "Hello World!" into the "CPC Basic" text box at the top and then press the Run button below it. Output goes to the blue CPC screen below. You can also interact with the CPC screen directly if you first click on it with the mouse. The Reset button stops a running program and returns you to the Ready prompt. In a native emulator, just type -10 print "Hello World!" -run +10 print "Hello World!" +run to run your first Locomotive BASIC program. @@ -56,7 +56,7 @@ As on many other 8-bit machines of the era, BASIC programs are often extended wi Memory on the CPC 464 and 664 is subdivided into four 16 kB blocks (0 to 3), with block 3 at &c000 normally reserved for the screen. The CPC 6128 features a second 64 kB bank (blocks 4 to 7) which can be accessed from BASIC with [[wp:Bank switching|bank switching]] in block 1 (&4000 and &7fff), e.g. -out &7fff,&x11000100 +out &7fff,&x11000100 would make block 4 accessible in the address space of block 1.http://k1.dyndns.org/Vintage/Schneider%20CPC/Das%20Schneider%20CPC%20Systembuch/z87.htm This way, the entire 128 kB of memory can be used by BASIC. Alternatively, RSX commands for bank switching and copying between banks are included on the system discs and discussed in chapter 8 of the CPC user manual.http://www.cpcwiki.eu/index.php/User_Manual Even on the 64 kB models, it is possible to do [[wp:Multiple buffering|double buffering]] in BASIC by reserving another RAM block for the screen, drawing into the hidden screen, and then setting the CRTC screen address to the currently hidden screen with the BASIC [[wp:I/o port|port I/O]] command OUT. diff --git a/Lang/Locomotive-Basic/Abelian-sandpile-model b/Lang/Locomotive-Basic/Abelian-sandpile-model new file mode 120000 index 0000000000..e00a530896 --- /dev/null +++ b/Lang/Locomotive-Basic/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Locomotive-Basic \ No newline at end of file diff --git a/Lang/Locomotive-Basic/Draw-a-cuboid b/Lang/Locomotive-Basic/Draw-a-cuboid new file mode 120000 index 0000000000..cbfb396b7f --- /dev/null +++ b/Lang/Locomotive-Basic/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Locomotive-Basic \ No newline at end of file diff --git a/Lang/MACRO-11/Square-but-not-cube b/Lang/MACRO-11/Square-but-not-cube new file mode 120000 index 0000000000..7130b2c620 --- /dev/null +++ b/Lang/MACRO-11/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/MACRO-11 \ No newline at end of file diff --git a/Lang/Mia/Loops-While b/Lang/Mia/Loops-While new file mode 120000 index 0000000000..acad4e8591 --- /dev/null +++ b/Lang/Mia/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Mia \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Jensens-Device b/Lang/Minimal-BASIC/Jensens-Device new file mode 120000 index 0000000000..f729ff931e --- /dev/null +++ b/Lang/Minimal-BASIC/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Monty-Hall-problem b/Lang/Minimal-BASIC/Monty-Hall-problem new file mode 120000 index 0000000000..e997b4d558 --- /dev/null +++ b/Lang/Minimal-BASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Modula-2/Gray-code b/Lang/Modula-2/Gray-code new file mode 120000 index 0000000000..8cb45ff695 --- /dev/null +++ b/Lang/Modula-2/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Monty-Hall-problem b/Lang/Modula-2/Monty-Hall-problem new file mode 120000 index 0000000000..9ad6c8767a --- /dev/null +++ b/Lang/Modula-2/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-3/Additive-primes b/Lang/Modula-3/Additive-primes new file mode 120000 index 0000000000..b81b571c35 --- /dev/null +++ b/Lang/Modula-3/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Modula-3 \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Damm-algorithm b/Lang/Nascom-BASIC/Damm-algorithm new file mode 120000 index 0000000000..5a6439a18c --- /dev/null +++ b/Lang/Nascom-BASIC/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Oberon/100-doors b/Lang/Oberon/100-doors deleted file mode 120000 index 9d190b3c16..0000000000 --- a/Lang/Oberon/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Oberon \ No newline at end of file diff --git a/Lang/Odin/Quine b/Lang/Odin/Quine new file mode 120000 index 0000000000..53e4cf3687 --- /dev/null +++ b/Lang/Odin/Quine @@ -0,0 +1 @@ +../../Task/Quine/Odin \ No newline at end of file diff --git a/Lang/PHP/Water-collected-between-towers b/Lang/PHP/Water-collected-between-towers new file mode 120000 index 0000000000..524c5ae99b --- /dev/null +++ b/Lang/PHP/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/PHP \ No newline at end of file diff --git a/Lang/PL-M/Draw-a-cuboid b/Lang/PL-M/Draw-a-cuboid new file mode 120000 index 0000000000..c6084a0c66 --- /dev/null +++ b/Lang/PL-M/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Nested-function b/Lang/PL-M/Nested-function new file mode 120000 index 0000000000..2fbc4399dd --- /dev/null +++ b/Lang/PL-M/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/PL-M \ No newline at end of file diff --git a/Lang/POV-Ray/Bitmap b/Lang/POV-Ray/Bitmap new file mode 120000 index 0000000000..90fece7e75 --- /dev/null +++ b/Lang/POV-Ray/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/POV-Ray \ No newline at end of file diff --git a/Lang/POV-Ray/Maze-generation b/Lang/POV-Ray/Maze-generation new file mode 120000 index 0000000000..724f710098 --- /dev/null +++ b/Lang/POV-Ray/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/POV-Ray \ No newline at end of file diff --git a/Lang/Pascal/Count-the-coins b/Lang/Pascal/Count-the-coins new file mode 120000 index 0000000000..8d7999b667 --- /dev/null +++ b/Lang/Pascal/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Pascal \ No newline at end of file diff --git a/Lang/PascalABC.NET/00-LANG.txt b/Lang/PascalABC.NET/00-LANG.txt index d9efe4d43e..48e9f6ce41 100644 --- a/Lang/PascalABC.NET/00-LANG.txt +++ b/Lang/PascalABC.NET/00-LANG.txt @@ -16,4 +16,4 @@ begin end. -{{unimpl_Page|PacalABC.NET}} \ No newline at end of file +{{unimpl_Page|PascalABC.NET}} \ No newline at end of file diff --git a/Lang/PascalABC.NET/15-puzzle-game b/Lang/PascalABC.NET/15-puzzle-game new file mode 120000 index 0000000000..caf890e56b --- /dev/null +++ b/Lang/PascalABC.NET/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/99-bottles-of-beer b/Lang/PascalABC.NET/99-bottles-of-beer new file mode 120000 index 0000000000..bc29442ab5 --- /dev/null +++ b/Lang/PascalABC.NET/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/A+B b/Lang/PascalABC.NET/A+B new file mode 120000 index 0000000000..7a5a9db498 --- /dev/null +++ b/Lang/PascalABC.NET/A+B @@ -0,0 +1 @@ +../../Task/A+B/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Abstract-type b/Lang/PascalABC.NET/Abstract-type new file mode 120000 index 0000000000..305270825e --- /dev/null +++ b/Lang/PascalABC.NET/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Accumulator-factory b/Lang/PascalABC.NET/Accumulator-factory new file mode 120000 index 0000000000..dd94a031d6 --- /dev/null +++ b/Lang/PascalABC.NET/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Ackermann-function b/Lang/PascalABC.NET/Ackermann-function new file mode 120000 index 0000000000..c2fa2dd278 --- /dev/null +++ b/Lang/PascalABC.NET/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime b/Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..ec0970f459 --- /dev/null +++ b/Lang/PascalABC.NET/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Address-of-a-variable b/Lang/PascalABC.NET/Address-of-a-variable new file mode 120000 index 0000000000..8477592c7b --- /dev/null +++ b/Lang/PascalABC.NET/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Anagrams b/Lang/PascalABC.NET/Anagrams new file mode 120000 index 0000000000..2bec53abb4 --- /dev/null +++ b/Lang/PascalABC.NET/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Anonymous-recursion b/Lang/PascalABC.NET/Anonymous-recursion new file mode 120000 index 0000000000..7a2a34d4d5 --- /dev/null +++ b/Lang/PascalABC.NET/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Apply-a-callback-to-an-array b/Lang/PascalABC.NET/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..88f34b5a9e --- /dev/null +++ b/Lang/PascalABC.NET/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-Complex b/Lang/PascalABC.NET/Arithmetic-Complex new file mode 120000 index 0000000000..bccd03a873 --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-Integer b/Lang/PascalABC.NET/Arithmetic-Integer new file mode 120000 index 0000000000..30d5138cbd --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Array-concatenation b/Lang/PascalABC.NET/Array-concatenation new file mode 120000 index 0000000000..bfe26798bc --- /dev/null +++ b/Lang/PascalABC.NET/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arrays b/Lang/PascalABC.NET/Arrays new file mode 120000 index 0000000000..62dfb07030 --- /dev/null +++ b/Lang/PascalABC.NET/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Assertions b/Lang/PascalABC.NET/Assertions new file mode 120000 index 0000000000..bdc3ed57c2 --- /dev/null +++ b/Lang/PascalABC.NET/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Associative-array-Creation b/Lang/PascalABC.NET/Associative-array-Creation new file mode 120000 index 0000000000..fc1bef5cdb --- /dev/null +++ b/Lang/PascalABC.NET/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Associative-array-Iteration b/Lang/PascalABC.NET/Associative-array-Iteration new file mode 120000 index 0000000000..2f1ab21d84 --- /dev/null +++ b/Lang/PascalABC.NET/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Balanced-brackets b/Lang/PascalABC.NET/Balanced-brackets new file mode 120000 index 0000000000..4b5678c4d8 --- /dev/null +++ b/Lang/PascalABC.NET/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Binary-digits b/Lang/PascalABC.NET/Binary-digits new file mode 120000 index 0000000000..e0597a5dc1 --- /dev/null +++ b/Lang/PascalABC.NET/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Binary-search b/Lang/PascalABC.NET/Binary-search new file mode 120000 index 0000000000..aa5ba91c87 --- /dev/null +++ b/Lang/PascalABC.NET/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Bitwise-operations b/Lang/PascalABC.NET/Bitwise-operations new file mode 120000 index 0000000000..acc6123f1c --- /dev/null +++ b/Lang/PascalABC.NET/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Break-OO-privacy b/Lang/PascalABC.NET/Break-OO-privacy new file mode 120000 index 0000000000..29ee336925 --- /dev/null +++ b/Lang/PascalABC.NET/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/CSV-data-manipulation b/Lang/PascalABC.NET/CSV-data-manipulation new file mode 120000 index 0000000000..ab9f191d41 --- /dev/null +++ b/Lang/PascalABC.NET/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Calculating-the-value-of-e b/Lang/PascalABC.NET/Calculating-the-value-of-e new file mode 120000 index 0000000000..c544f3c00f --- /dev/null +++ b/Lang/PascalABC.NET/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Call-an-object-method b/Lang/PascalABC.NET/Call-an-object-method new file mode 120000 index 0000000000..0c1cf230d7 --- /dev/null +++ b/Lang/PascalABC.NET/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Character-codes b/Lang/PascalABC.NET/Character-codes new file mode 120000 index 0000000000..1888f78c06 --- /dev/null +++ b/Lang/PascalABC.NET/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Classes b/Lang/PascalABC.NET/Classes new file mode 120000 index 0000000000..08756ef03a --- /dev/null +++ b/Lang/PascalABC.NET/Classes @@ -0,0 +1 @@ +../../Task/Classes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Closest-pair-problem b/Lang/PascalABC.NET/Closest-pair-problem new file mode 120000 index 0000000000..4b7bc32806 --- /dev/null +++ b/Lang/PascalABC.NET/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Collections b/Lang/PascalABC.NET/Collections new file mode 120000 index 0000000000..c3fa3dc417 --- /dev/null +++ b/Lang/PascalABC.NET/Collections @@ -0,0 +1 @@ +../../Task/Collections/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Command-line-arguments b/Lang/PascalABC.NET/Command-line-arguments new file mode 120000 index 0000000000..f229191025 --- /dev/null +++ b/Lang/PascalABC.NET/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Comments b/Lang/PascalABC.NET/Comments new file mode 120000 index 0000000000..5e528e6991 --- /dev/null +++ b/Lang/PascalABC.NET/Comments @@ -0,0 +1 @@ +../../Task/Comments/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compare-a-list-of-strings b/Lang/PascalABC.NET/Compare-a-list-of-strings new file mode 120000 index 0000000000..b8b040023f --- /dev/null +++ b/Lang/PascalABC.NET/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compare-length-of-two-strings b/Lang/PascalABC.NET/Compare-length-of-two-strings new file mode 120000 index 0000000000..92be62a3df --- /dev/null +++ b/Lang/PascalABC.NET/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Compound-data-type b/Lang/PascalABC.NET/Compound-data-type new file mode 120000 index 0000000000..89ad664595 --- /dev/null +++ b/Lang/PascalABC.NET/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Concurrent-computing b/Lang/PascalABC.NET/Concurrent-computing new file mode 120000 index 0000000000..ced9fcccc5 --- /dev/null +++ b/Lang/PascalABC.NET/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Conditional-structures b/Lang/PascalABC.NET/Conditional-structures new file mode 120000 index 0000000000..6186fdd1f8 --- /dev/null +++ b/Lang/PascalABC.NET/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Constrained-genericity b/Lang/PascalABC.NET/Constrained-genericity new file mode 120000 index 0000000000..4d89cf348d --- /dev/null +++ b/Lang/PascalABC.NET/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Copy-a-string b/Lang/PascalABC.NET/Copy-a-string new file mode 120000 index 0000000000..d102da9b43 --- /dev/null +++ b/Lang/PascalABC.NET/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Copy-stdin-to-stdout b/Lang/PascalABC.NET/Copy-stdin-to-stdout new file mode 120000 index 0000000000..08f7b00296 --- /dev/null +++ b/Lang/PascalABC.NET/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-in-factors b/Lang/PascalABC.NET/Count-in-factors new file mode 120000 index 0000000000..42811aa9aa --- /dev/null +++ b/Lang/PascalABC.NET/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-in-octal b/Lang/PascalABC.NET/Count-in-octal new file mode 120000 index 0000000000..8965e8c25f --- /dev/null +++ b/Lang/PascalABC.NET/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Count-occurrences-of-a-substring b/Lang/PascalABC.NET/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..d67adab506 --- /dev/null +++ b/Lang/PascalABC.NET/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime b/Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..2c7befc65f --- /dev/null +++ b/Lang/PascalABC.NET/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Create-an-object-at-a-given-address b/Lang/PascalABC.NET/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..aa2e5f2ab2 --- /dev/null +++ b/Lang/PascalABC.NET/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Date-format b/Lang/PascalABC.NET/Date-format new file mode 120000 index 0000000000..176b256586 --- /dev/null +++ b/Lang/PascalABC.NET/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Day-of-the-week b/Lang/PascalABC.NET/Day-of-the-week new file mode 120000 index 0000000000..3300b037b4 --- /dev/null +++ b/Lang/PascalABC.NET/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Define-a-primitive-data-type b/Lang/PascalABC.NET/Define-a-primitive-data-type new file mode 120000 index 0000000000..684571f697 --- /dev/null +++ b/Lang/PascalABC.NET/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-if-a-string-is-numeric b/Lang/PascalABC.NET/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..3ddeb93c61 --- /dev/null +++ b/Lang/PascalABC.NET/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Determine-sentence-type b/Lang/PascalABC.NET/Determine-sentence-type new file mode 120000 index 0000000000..dc0284a0e0 --- /dev/null +++ b/Lang/PascalABC.NET/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Definition b/Lang/PascalABC.NET/Doubly-linked-list-Definition new file mode 120000 index 0000000000..f2561705cf --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Element-definition b/Lang/PascalABC.NET/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..50c9d03e8c --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Element-insertion b/Lang/PascalABC.NET/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..28af162224 --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Doubly-linked-list-Traversal b/Lang/PascalABC.NET/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..9cc3d51b16 --- /dev/null +++ b/Lang/PascalABC.NET/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Dragon-curve b/Lang/PascalABC.NET/Dragon-curve new file mode 120000 index 0000000000..1a8a6239bd --- /dev/null +++ b/Lang/PascalABC.NET/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Draw-a-pixel b/Lang/PascalABC.NET/Draw-a-pixel new file mode 120000 index 0000000000..cdcb7e2918 --- /dev/null +++ b/Lang/PascalABC.NET/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Draw-a-rotating-cube b/Lang/PascalABC.NET/Draw-a-rotating-cube new file mode 120000 index 0000000000..9092790488 --- /dev/null +++ b/Lang/PascalABC.NET/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Empty-program b/Lang/PascalABC.NET/Empty-program new file mode 120000 index 0000000000..9a2aa557cd --- /dev/null +++ b/Lang/PascalABC.NET/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Enumerations b/Lang/PascalABC.NET/Enumerations new file mode 120000 index 0000000000..3fbeab7aac --- /dev/null +++ b/Lang/PascalABC.NET/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Even-or-odd b/Lang/PascalABC.NET/Even-or-odd new file mode 120000 index 0000000000..4191597943 --- /dev/null +++ b/Lang/PascalABC.NET/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exceptions b/Lang/PascalABC.NET/Exceptions new file mode 120000 index 0000000000..b4b7999bea --- /dev/null +++ b/Lang/PascalABC.NET/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Extreme-floating-point-values b/Lang/PascalABC.NET/Extreme-floating-point-values new file mode 120000 index 0000000000..438be3c964 --- /dev/null +++ b/Lang/PascalABC.NET/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factorial b/Lang/PascalABC.NET/Factorial new file mode 120000 index 0000000000..64716300fa --- /dev/null +++ b/Lang/PascalABC.NET/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factors-of-an-integer b/Lang/PascalABC.NET/Factors-of-an-integer new file mode 120000 index 0000000000..b2f675ad56 --- /dev/null +++ b/Lang/PascalABC.NET/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/File-input-output b/Lang/PascalABC.NET/File-input-output new file mode 120000 index 0000000000..aa29aa165d --- /dev/null +++ b/Lang/PascalABC.NET/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/File-size b/Lang/PascalABC.NET/File-size new file mode 120000 index 0000000000..cb4f56c334 --- /dev/null +++ b/Lang/PascalABC.NET/File-size @@ -0,0 +1 @@ +../../Task/File-size/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Filter b/Lang/PascalABC.NET/Filter new file mode 120000 index 0000000000..b6b1f56f68 --- /dev/null +++ b/Lang/PascalABC.NET/Filter @@ -0,0 +1 @@ +../../Task/Filter/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-common-directory-path b/Lang/PascalABC.NET/Find-common-directory-path new file mode 120000 index 0000000000..48495d80e3 --- /dev/null +++ b/Lang/PascalABC.NET/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Find-limit-of-recursion b/Lang/PascalABC.NET/Find-limit-of-recursion new file mode 120000 index 0000000000..8e738ede74 --- /dev/null +++ b/Lang/PascalABC.NET/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/First-class-functions b/Lang/PascalABC.NET/First-class-functions new file mode 120000 index 0000000000..d4c191f6d3 --- /dev/null +++ b/Lang/PascalABC.NET/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/FizzBuzz b/Lang/PascalABC.NET/FizzBuzz new file mode 120000 index 0000000000..9af47ffeb0 --- /dev/null +++ b/Lang/PascalABC.NET/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Flatten-a-list b/Lang/PascalABC.NET/Flatten-a-list new file mode 120000 index 0000000000..951e9e626d --- /dev/null +++ b/Lang/PascalABC.NET/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Floyds-triangle b/Lang/PascalABC.NET/Floyds-triangle new file mode 120000 index 0000000000..741db9a754 --- /dev/null +++ b/Lang/PascalABC.NET/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Formatted-numeric-output b/Lang/PascalABC.NET/Formatted-numeric-output new file mode 120000 index 0000000000..d5385037bc --- /dev/null +++ b/Lang/PascalABC.NET/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Function-definition b/Lang/PascalABC.NET/Function-definition new file mode 120000 index 0000000000..cc1ff414b4 --- /dev/null +++ b/Lang/PascalABC.NET/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/General-FizzBuzz b/Lang/PascalABC.NET/General-FizzBuzz new file mode 120000 index 0000000000..655ae97e52 --- /dev/null +++ b/Lang/PascalABC.NET/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet b/Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..8ef0c3c6f0 --- /dev/null +++ b/Lang/PascalABC.NET/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Generic-swap b/Lang/PascalABC.NET/Generic-swap new file mode 120000 index 0000000000..35fd1c3542 --- /dev/null +++ b/Lang/PascalABC.NET/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Greatest-common-divisor b/Lang/PascalABC.NET/Greatest-common-divisor new file mode 120000 index 0000000000..27dc1c21f9 --- /dev/null +++ b/Lang/PascalABC.NET/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Guess-the-number b/Lang/PascalABC.NET/Guess-the-number new file mode 120000 index 0000000000..7fff26f7e2 --- /dev/null +++ b/Lang/PascalABC.NET/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hash-from-two-arrays b/Lang/PascalABC.NET/Hash-from-two-arrays new file mode 120000 index 0000000000..06b09f8bf9 --- /dev/null +++ b/Lang/PascalABC.NET/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hello-world-Line-printer b/Lang/PascalABC.NET/Hello-world-Line-printer new file mode 120000 index 0000000000..87d7f6b37c --- /dev/null +++ b/Lang/PascalABC.NET/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hello-world-Newline-omission b/Lang/PascalABC.NET/Hello-world-Newline-omission new file mode 120000 index 0000000000..2c094828d8 --- /dev/null +++ b/Lang/PascalABC.NET/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Hello-world-Standard-error b/Lang/PascalABC.NET/Hello-world-Standard-error new file mode 120000 index 0000000000..4b2452f23e --- /dev/null +++ b/Lang/PascalABC.NET/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Identity-matrix b/Lang/PascalABC.NET/Identity-matrix new file mode 120000 index 0000000000..e498197ea6 --- /dev/null +++ b/Lang/PascalABC.NET/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Include-a-file b/Lang/PascalABC.NET/Include-a-file new file mode 120000 index 0000000000..5762928418 --- /dev/null +++ b/Lang/PascalABC.NET/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Infinity b/Lang/PascalABC.NET/Infinity new file mode 120000 index 0000000000..e5b6807ad7 --- /dev/null +++ b/Lang/PascalABC.NET/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Inheritance-Multiple b/Lang/PascalABC.NET/Inheritance-Multiple new file mode 120000 index 0000000000..f3f065b097 --- /dev/null +++ b/Lang/PascalABC.NET/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Inheritance-Single b/Lang/PascalABC.NET/Inheritance-Single new file mode 120000 index 0000000000..2843b9d512 --- /dev/null +++ b/Lang/PascalABC.NET/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Input-loop b/Lang/PascalABC.NET/Input-loop new file mode 120000 index 0000000000..8086164ab5 --- /dev/null +++ b/Lang/PascalABC.NET/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Integer-comparison b/Lang/PascalABC.NET/Integer-comparison new file mode 120000 index 0000000000..b60ac826c4 --- /dev/null +++ b/Lang/PascalABC.NET/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/JSON b/Lang/PascalABC.NET/JSON new file mode 120000 index 0000000000..e24e87ebee --- /dev/null +++ b/Lang/PascalABC.NET/JSON @@ -0,0 +1 @@ +../../Task/JSON/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Jump-anywhere b/Lang/PascalABC.NET/Jump-anywhere new file mode 120000 index 0000000000..cb395144b9 --- /dev/null +++ b/Lang/PascalABC.NET/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Knuth-shuffle b/Lang/PascalABC.NET/Knuth-shuffle new file mode 120000 index 0000000000..a80c329b34 --- /dev/null +++ b/Lang/PascalABC.NET/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Least-common-multiple b/Lang/PascalABC.NET/Least-common-multiple new file mode 120000 index 0000000000..446b96ac48 --- /dev/null +++ b/Lang/PascalABC.NET/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/List-comprehensions b/Lang/PascalABC.NET/List-comprehensions new file mode 120000 index 0000000000..e9fa93e9e6 --- /dev/null +++ b/Lang/PascalABC.NET/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Literals-Floating-point b/Lang/PascalABC.NET/Literals-Floating-point new file mode 120000 index 0000000000..e11300a194 --- /dev/null +++ b/Lang/PascalABC.NET/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Literals-String b/Lang/PascalABC.NET/Literals-String new file mode 120000 index 0000000000..2f02c8af92 --- /dev/null +++ b/Lang/PascalABC.NET/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Longest-common-subsequence b/Lang/PascalABC.NET/Longest-common-subsequence new file mode 120000 index 0000000000..1dfbd5ef9d --- /dev/null +++ b/Lang/PascalABC.NET/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously b/Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..52655fded4 --- /dev/null +++ b/Lang/PascalABC.NET/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Break b/Lang/PascalABC.NET/Loops-Break new file mode 120000 index 0000000000..75f285786e --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Continue b/Lang/PascalABC.NET/Loops-Continue new file mode 120000 index 0000000000..75da2856ce --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Do-while b/Lang/PascalABC.NET/Loops-Do-while new file mode 120000 index 0000000000..a15c938618 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Downward-for b/Lang/PascalABC.NET/Loops-Downward-for new file mode 120000 index 0000000000..c2c6306f3a --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-For b/Lang/PascalABC.NET/Loops-For new file mode 120000 index 0000000000..bf236f094e --- /dev/null +++ b/Lang/PascalABC.NET/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-For-with-a-specified-step b/Lang/PascalABC.NET/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..5244453d5c --- /dev/null +++ b/Lang/PascalABC.NET/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Foreach b/Lang/PascalABC.NET/Loops-Foreach new file mode 120000 index 0000000000..68b06931af --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body b/Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..f5d20bce59 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-N-plus-one-half b/Lang/PascalABC.NET/Loops-N-plus-one-half new file mode 120000 index 0000000000..95fe8496ec --- /dev/null +++ b/Lang/PascalABC.NET/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Nested b/Lang/PascalABC.NET/Loops-Nested new file mode 120000 index 0000000000..d1a88ee15f --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-While b/Lang/PascalABC.NET/Loops-While new file mode 120000 index 0000000000..19d817b9f2 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-With-multiple-ranges b/Lang/PascalABC.NET/Loops-With-multiple-ranges new file mode 120000 index 0000000000..1b3c0e8a85 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Loops-Wrong-ranges b/Lang/PascalABC.NET/Loops-Wrong-ranges new file mode 120000 index 0000000000..cd717ae408 --- /dev/null +++ b/Lang/PascalABC.NET/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Man-or-boy-test b/Lang/PascalABC.NET/Man-or-boy-test new file mode 120000 index 0000000000..f9b9ccb7a0 --- /dev/null +++ b/Lang/PascalABC.NET/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Memory-allocation b/Lang/PascalABC.NET/Memory-allocation new file mode 120000 index 0000000000..b7e94af0dd --- /dev/null +++ b/Lang/PascalABC.NET/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Mouse-position b/Lang/PascalABC.NET/Mouse-position new file mode 120000 index 0000000000..207ee7b935 --- /dev/null +++ b/Lang/PascalABC.NET/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Nested-function b/Lang/PascalABC.NET/Nested-function new file mode 120000 index 0000000000..406d1380f0 --- /dev/null +++ b/Lang/PascalABC.NET/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Nth b/Lang/PascalABC.NET/Nth new file mode 120000 index 0000000000..2151e00c8d --- /dev/null +++ b/Lang/PascalABC.NET/Nth @@ -0,0 +1 @@ +../../Task/Nth/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Null-object b/Lang/PascalABC.NET/Null-object new file mode 120000 index 0000000000..39b6da0acb --- /dev/null +++ b/Lang/PascalABC.NET/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Object-serialization b/Lang/PascalABC.NET/Object-serialization new file mode 120000 index 0000000000..07426b45b7 --- /dev/null +++ b/Lang/PascalABC.NET/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Palindrome-detection b/Lang/PascalABC.NET/Palindrome-detection new file mode 120000 index 0000000000..cc92721e9f --- /dev/null +++ b/Lang/PascalABC.NET/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Parametric-polymorphism b/Lang/PascalABC.NET/Parametric-polymorphism new file mode 120000 index 0000000000..7c242be133 --- /dev/null +++ b/Lang/PascalABC.NET/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pick-random-element b/Lang/PascalABC.NET/Pick-random-element new file mode 120000 index 0000000000..9dd6351bad --- /dev/null +++ b/Lang/PascalABC.NET/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pointers-and-references b/Lang/PascalABC.NET/Pointers-and-references new file mode 120000 index 0000000000..6985ca1666 --- /dev/null +++ b/Lang/PascalABC.NET/Pointers-and-references @@ -0,0 +1 @@ +../../Task/Pointers-and-references/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Polymorphic-copy b/Lang/PascalABC.NET/Polymorphic-copy new file mode 120000 index 0000000000..7ed8b814ad --- /dev/null +++ b/Lang/PascalABC.NET/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Polymorphism b/Lang/PascalABC.NET/Polymorphism new file mode 120000 index 0000000000..4996bdacfd --- /dev/null +++ b/Lang/PascalABC.NET/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Power-set b/Lang/PascalABC.NET/Power-set new file mode 120000 index 0000000000..042d839f30 --- /dev/null +++ b/Lang/PascalABC.NET/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Primality-by-trial-division b/Lang/PascalABC.NET/Primality-by-trial-division new file mode 120000 index 0000000000..62ca027b6e --- /dev/null +++ b/Lang/PascalABC.NET/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Prime-decomposition b/Lang/PascalABC.NET/Prime-decomposition new file mode 120000 index 0000000000..ea96188341 --- /dev/null +++ b/Lang/PascalABC.NET/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Program-name b/Lang/PascalABC.NET/Program-name new file mode 120000 index 0000000000..6bdce5a90a --- /dev/null +++ b/Lang/PascalABC.NET/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Program-termination b/Lang/PascalABC.NET/Program-termination new file mode 120000 index 0000000000..63645717ea --- /dev/null +++ b/Lang/PascalABC.NET/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Queue-Definition b/Lang/PascalABC.NET/Queue-Definition new file mode 120000 index 0000000000..efb10e6df2 --- /dev/null +++ b/Lang/PascalABC.NET/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Queue-Usage b/Lang/PascalABC.NET/Queue-Usage new file mode 120000 index 0000000000..eab42cf449 --- /dev/null +++ b/Lang/PascalABC.NET/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Quine b/Lang/PascalABC.NET/Quine new file mode 120000 index 0000000000..98ce8f9f2f --- /dev/null +++ b/Lang/PascalABC.NET/Quine @@ -0,0 +1 @@ +../../Task/Quine/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Quoting-constructs b/Lang/PascalABC.NET/Quoting-constructs new file mode 120000 index 0000000000..971db935d4 --- /dev/null +++ b/Lang/PascalABC.NET/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Radical-of-an-integer b/Lang/PascalABC.NET/Radical-of-an-integer new file mode 120000 index 0000000000..430a252ecf --- /dev/null +++ b/Lang/PascalABC.NET/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 b/Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 new file mode 120000 index 0000000000..a425a12499 --- /dev/null +++ b/Lang/PascalABC.NET/Read-a-file-character-by-character-UTF8 @@ -0,0 +1 @@ +../../Task/Read-a-file-character-by-character-UTF8/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-a-file-line-by-line b/Lang/PascalABC.NET/Read-a-file-line-by-line new file mode 120000 index 0000000000..bd96f90ae1 --- /dev/null +++ b/Lang/PascalABC.NET/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-a-specific-line-from-a-file b/Lang/PascalABC.NET/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..28703147aa --- /dev/null +++ b/Lang/PascalABC.NET/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Read-entire-file b/Lang/PascalABC.NET/Read-entire-file new file mode 120000 index 0000000000..20a95b9d77 --- /dev/null +++ b/Lang/PascalABC.NET/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Real-constants-and-functions b/Lang/PascalABC.NET/Real-constants-and-functions new file mode 120000 index 0000000000..a6e7dce16d --- /dev/null +++ b/Lang/PascalABC.NET/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reflection-List-methods b/Lang/PascalABC.NET/Reflection-List-methods new file mode 120000 index 0000000000..7e40bca2fa --- /dev/null +++ b/Lang/PascalABC.NET/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reflection-List-properties b/Lang/PascalABC.NET/Reflection-List-properties new file mode 120000 index 0000000000..ed60f425f0 --- /dev/null +++ b/Lang/PascalABC.NET/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Regular-expressions b/Lang/PascalABC.NET/Regular-expressions new file mode 120000 index 0000000000..a3ccbe1574 --- /dev/null +++ b/Lang/PascalABC.NET/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Remove-duplicate-elements b/Lang/PascalABC.NET/Remove-duplicate-elements new file mode 120000 index 0000000000..6f37a5852e --- /dev/null +++ b/Lang/PascalABC.NET/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Remove-lines-from-a-file b/Lang/PascalABC.NET/Remove-lines-from-a-file new file mode 120000 index 0000000000..6e76bee372 --- /dev/null +++ b/Lang/PascalABC.NET/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Rename-a-file b/Lang/PascalABC.NET/Rename-a-file new file mode 120000 index 0000000000..e7599165d6 --- /dev/null +++ b/Lang/PascalABC.NET/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Repeat b/Lang/PascalABC.NET/Repeat new file mode 120000 index 0000000000..e16283f972 --- /dev/null +++ b/Lang/PascalABC.NET/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Repeat-a-string b/Lang/PascalABC.NET/Repeat-a-string new file mode 120000 index 0000000000..c21e0bfde3 --- /dev/null +++ b/Lang/PascalABC.NET/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Return-multiple-values b/Lang/PascalABC.NET/Return-multiple-values new file mode 120000 index 0000000000..5178c8dd1d --- /dev/null +++ b/Lang/PascalABC.NET/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reverse-a-string b/Lang/PascalABC.NET/Reverse-a-string new file mode 120000 index 0000000000..8e67838296 --- /dev/null +++ b/Lang/PascalABC.NET/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Reverse-words-in-a-string b/Lang/PascalABC.NET/Reverse-words-in-a-string new file mode 120000 index 0000000000..aa82b64f3b --- /dev/null +++ b/Lang/PascalABC.NET/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Roman-numerals-Decode b/Lang/PascalABC.NET/Roman-numerals-Decode new file mode 120000 index 0000000000..990d667ad0 --- /dev/null +++ b/Lang/PascalABC.NET/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Roman-numerals-Encode b/Lang/PascalABC.NET/Roman-numerals-Encode new file mode 120000 index 0000000000..c8f15e15fa --- /dev/null +++ b/Lang/PascalABC.NET/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity b/Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..55aa7d4f0c --- /dev/null +++ b/Lang/PascalABC.NET/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Rot-13 b/Lang/PascalABC.NET/Rot-13 new file mode 120000 index 0000000000..f7c9e778c9 --- /dev/null +++ b/Lang/PascalABC.NET/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Scope-modifiers b/Lang/PascalABC.NET/Scope-modifiers new file mode 120000 index 0000000000..eb11f44070 --- /dev/null +++ b/Lang/PascalABC.NET/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Send-an-unknown-method-call b/Lang/PascalABC.NET/Send-an-unknown-method-call new file mode 120000 index 0000000000..2e049c05b3 --- /dev/null +++ b/Lang/PascalABC.NET/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sequence-of-primes-by-trial-division b/Lang/PascalABC.NET/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..4182c218d4 --- /dev/null +++ b/Lang/PascalABC.NET/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sieve-of-Eratosthenes b/Lang/PascalABC.NET/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c9a2623742 --- /dev/null +++ b/Lang/PascalABC.NET/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Simple-windowed-application b/Lang/PascalABC.NET/Simple-windowed-application new file mode 120000 index 0000000000..a619cd32f7 --- /dev/null +++ b/Lang/PascalABC.NET/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Singly-linked-list-Element-definition b/Lang/PascalABC.NET/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..71d3f5d628 --- /dev/null +++ b/Lang/PascalABC.NET/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Singly-linked-list-Element-insertion b/Lang/PascalABC.NET/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..f60548d528 --- /dev/null +++ b/Lang/PascalABC.NET/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sleep b/Lang/PascalABC.NET/Sleep new file mode 120000 index 0000000000..d8f830cd4f --- /dev/null +++ b/Lang/PascalABC.NET/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-an-array-of-composite-structures b/Lang/PascalABC.NET/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..e0459e8577 --- /dev/null +++ b/Lang/PascalABC.NET/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-an-integer-array b/Lang/PascalABC.NET/Sort-an-integer-array new file mode 120000 index 0000000000..e2137f1191 --- /dev/null +++ b/Lang/PascalABC.NET/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-three-variables b/Lang/PascalABC.NET/Sort-three-variables new file mode 120000 index 0000000000..2143247222 --- /dev/null +++ b/Lang/PascalABC.NET/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sort-using-a-custom-comparator b/Lang/PascalABC.NET/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..a2ade4323b --- /dev/null +++ b/Lang/PascalABC.NET/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sorting-algorithms-Quicksort b/Lang/PascalABC.NET/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..d84582d974 --- /dev/null +++ b/Lang/PascalABC.NET/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Special-variables b/Lang/PascalABC.NET/Special-variables new file mode 120000 index 0000000000..00db4953ba --- /dev/null +++ b/Lang/PascalABC.NET/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Stack b/Lang/PascalABC.NET/Stack new file mode 120000 index 0000000000..71f695fe1b --- /dev/null +++ b/Lang/PascalABC.NET/Stack @@ -0,0 +1 @@ +../../Task/Stack/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Stack-traces b/Lang/PascalABC.NET/Stack-traces new file mode 120000 index 0000000000..b6976dc3e0 --- /dev/null +++ b/Lang/PascalABC.NET/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-append b/Lang/PascalABC.NET/String-append new file mode 120000 index 0000000000..78fd361243 --- /dev/null +++ b/Lang/PascalABC.NET/String-append @@ -0,0 +1 @@ +../../Task/String-append/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-case b/Lang/PascalABC.NET/String-case new file mode 120000 index 0000000000..980e55192e --- /dev/null +++ b/Lang/PascalABC.NET/String-case @@ -0,0 +1 @@ +../../Task/String-case/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-concatenation b/Lang/PascalABC.NET/String-concatenation new file mode 120000 index 0000000000..d7b52bf492 --- /dev/null +++ b/Lang/PascalABC.NET/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-interpolation-included- b/Lang/PascalABC.NET/String-interpolation-included- new file mode 120000 index 0000000000..6a1179d384 --- /dev/null +++ b/Lang/PascalABC.NET/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-length b/Lang/PascalABC.NET/String-length new file mode 120000 index 0000000000..1bc629e3ec --- /dev/null +++ b/Lang/PascalABC.NET/String-length @@ -0,0 +1 @@ +../../Task/String-length/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-matching b/Lang/PascalABC.NET/String-matching new file mode 120000 index 0000000000..f031375ab5 --- /dev/null +++ b/Lang/PascalABC.NET/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/String-prepend b/Lang/PascalABC.NET/String-prepend new file mode 120000 index 0000000000..205b3e4638 --- /dev/null +++ b/Lang/PascalABC.NET/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string b/Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..5548033cde --- /dev/null +++ b/Lang/PascalABC.NET/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-block-comments b/Lang/PascalABC.NET/Strip-block-comments new file mode 120000 index 0000000000..7a95085577 --- /dev/null +++ b/Lang/PascalABC.NET/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-comments-from-a-string b/Lang/PascalABC.NET/Strip-comments-from-a-string new file mode 120000 index 0000000000..c415553cce --- /dev/null +++ b/Lang/PascalABC.NET/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string b/Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..3175c3c416 --- /dev/null +++ b/Lang/PascalABC.NET/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..075fc6a71b --- /dev/null +++ b/Lang/PascalABC.NET/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Substitution-cipher b/Lang/PascalABC.NET/Substitution-cipher new file mode 120000 index 0000000000..5c9f1bb54c --- /dev/null +++ b/Lang/PascalABC.NET/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Substring b/Lang/PascalABC.NET/Substring new file mode 120000 index 0000000000..f2a607112d --- /dev/null +++ b/Lang/PascalABC.NET/Substring @@ -0,0 +1 @@ +../../Task/Substring/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Substring-Top-and-tail b/Lang/PascalABC.NET/Substring-Top-and-tail new file mode 120000 index 0000000000..b64b9c4948 --- /dev/null +++ b/Lang/PascalABC.NET/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sudan-function b/Lang/PascalABC.NET/Sudan-function new file mode 120000 index 0000000000..2a6cccd8a5 --- /dev/null +++ b/Lang/PascalABC.NET/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-and-product-of-an-array b/Lang/PascalABC.NET/Sum-and-product-of-an-array new file mode 120000 index 0000000000..5bf49387d6 --- /dev/null +++ b/Lang/PascalABC.NET/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-digits-of-an-integer b/Lang/PascalABC.NET/Sum-digits-of-an-integer new file mode 120000 index 0000000000..84d553224a --- /dev/null +++ b/Lang/PascalABC.NET/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-multiples-of-3-and-5 b/Lang/PascalABC.NET/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..3792b87fe0 --- /dev/null +++ b/Lang/PascalABC.NET/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-of-a-series b/Lang/PascalABC.NET/Sum-of-a-series new file mode 120000 index 0000000000..1c91b8532b --- /dev/null +++ b/Lang/PascalABC.NET/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..055fd11a3e --- /dev/null +++ b/Lang/PascalABC.NET/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Sum-of-squares b/Lang/PascalABC.NET/Sum-of-squares new file mode 120000 index 0000000000..0d6573d1ec --- /dev/null +++ b/Lang/PascalABC.NET/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Symmetric-difference b/Lang/PascalABC.NET/Symmetric-difference new file mode 120000 index 0000000000..6a0af3805f --- /dev/null +++ b/Lang/PascalABC.NET/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/System-time b/Lang/PascalABC.NET/System-time new file mode 120000 index 0000000000..b4cf3d92cb --- /dev/null +++ b/Lang/PascalABC.NET/System-time @@ -0,0 +1 @@ +../../Task/System-time/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Take-notes-on-the-command-line b/Lang/PascalABC.NET/Take-notes-on-the-command-line new file mode 120000 index 0000000000..ce2c9c51c4 --- /dev/null +++ b/Lang/PascalABC.NET/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tau-function b/Lang/PascalABC.NET/Tau-function new file mode 120000 index 0000000000..fcb633b959 --- /dev/null +++ b/Lang/PascalABC.NET/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tau-number b/Lang/PascalABC.NET/Tau-number new file mode 120000 index 0000000000..4be8374dc0 --- /dev/null +++ b/Lang/PascalABC.NET/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Temperature-conversion b/Lang/PascalABC.NET/Temperature-conversion new file mode 120000 index 0000000000..607c5a8aa1 --- /dev/null +++ b/Lang/PascalABC.NET/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Clear-the-screen b/Lang/PascalABC.NET/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..ba3f668e83 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Coloured-text b/Lang/PascalABC.NET/Terminal-control-Coloured-text new file mode 120000 index 0000000000..26edde266f --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Cursor-movement b/Lang/PascalABC.NET/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..75b038bfd2 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Cursor-positioning b/Lang/PascalABC.NET/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..440e989070 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Dimensions b/Lang/PascalABC.NET/Terminal-control-Dimensions new file mode 120000 index 0000000000..294b1506e4 --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Display-an-extended-character b/Lang/PascalABC.NET/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..51ff55a04f --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor b/Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..0f79ee5b6d --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell b/Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..dbea7c8c1b --- /dev/null +++ b/Lang/PascalABC.NET/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Test-a-function b/Lang/PascalABC.NET/Test-a-function new file mode 120000 index 0000000000..561aaeccdd --- /dev/null +++ b/Lang/PascalABC.NET/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Time-a-function b/Lang/PascalABC.NET/Time-a-function new file mode 120000 index 0000000000..2c161d3642 --- /dev/null +++ b/Lang/PascalABC.NET/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tokenize-a-string b/Lang/PascalABC.NET/Tokenize-a-string new file mode 120000 index 0000000000..790ef58cc8 --- /dev/null +++ b/Lang/PascalABC.NET/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Top-rank-per-group b/Lang/PascalABC.NET/Top-rank-per-group new file mode 120000 index 0000000000..09da721479 --- /dev/null +++ b/Lang/PascalABC.NET/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Towers-of-Hanoi b/Lang/PascalABC.NET/Towers-of-Hanoi new file mode 120000 index 0000000000..2c8ecfee74 --- /dev/null +++ b/Lang/PascalABC.NET/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm b/Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..c211c9d9e3 --- /dev/null +++ b/Lang/PascalABC.NET/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet b/Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..d24a02b5a0 --- /dev/null +++ b/Lang/PascalABC.NET/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tree-datastructures b/Lang/PascalABC.NET/Tree-datastructures new file mode 120000 index 0000000000..2b711cc827 --- /dev/null +++ b/Lang/PascalABC.NET/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Tree-traversal b/Lang/PascalABC.NET/Tree-traversal new file mode 120000 index 0000000000..7b8540d436 --- /dev/null +++ b/Lang/PascalABC.NET/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Trigonometric-functions b/Lang/PascalABC.NET/Trigonometric-functions new file mode 120000 index 0000000000..90b97e3cc1 --- /dev/null +++ b/Lang/PascalABC.NET/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Truncate-a-file b/Lang/PascalABC.NET/Truncate-a-file new file mode 120000 index 0000000000..e41951adf8 --- /dev/null +++ b/Lang/PascalABC.NET/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Twos-complement b/Lang/PascalABC.NET/Twos-complement new file mode 120000 index 0000000000..b0daea87d5 --- /dev/null +++ b/Lang/PascalABC.NET/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/URL-decoding b/Lang/PascalABC.NET/URL-decoding new file mode 120000 index 0000000000..bb79d3d611 --- /dev/null +++ b/Lang/PascalABC.NET/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/URL-encoding b/Lang/PascalABC.NET/URL-encoding new file mode 120000 index 0000000000..4e193b1e1d --- /dev/null +++ b/Lang/PascalABC.NET/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Undefined-values b/Lang/PascalABC.NET/Undefined-values new file mode 120000 index 0000000000..799f03aa4e --- /dev/null +++ b/Lang/PascalABC.NET/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Unicode-strings b/Lang/PascalABC.NET/Unicode-strings new file mode 120000 index 0000000000..1596fd402d --- /dev/null +++ b/Lang/PascalABC.NET/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Unicode-variable-names b/Lang/PascalABC.NET/Unicode-variable-names new file mode 120000 index 0000000000..356bcbe63e --- /dev/null +++ b/Lang/PascalABC.NET/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/User-input-Text b/Lang/PascalABC.NET/User-input-Text new file mode 120000 index 0000000000..c49d403c30 --- /dev/null +++ b/Lang/PascalABC.NET/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Variables b/Lang/PascalABC.NET/Variables new file mode 120000 index 0000000000..fb0f3cb656 --- /dev/null +++ b/Lang/PascalABC.NET/Variables @@ -0,0 +1 @@ +../../Task/Variables/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Variadic-function b/Lang/PascalABC.NET/Variadic-function new file mode 120000 index 0000000000..c1bc454958 --- /dev/null +++ b/Lang/PascalABC.NET/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Vector b/Lang/PascalABC.NET/Vector new file mode 120000 index 0000000000..d45a06a593 --- /dev/null +++ b/Lang/PascalABC.NET/Vector @@ -0,0 +1 @@ +../../Task/Vector/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Vector-products b/Lang/PascalABC.NET/Vector-products new file mode 120000 index 0000000000..8bc6e1a1f1 --- /dev/null +++ b/Lang/PascalABC.NET/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Walk-a-directory-Non-recursively b/Lang/PascalABC.NET/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..117d045320 --- /dev/null +++ b/Lang/PascalABC.NET/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Walk-a-directory-Recursively b/Lang/PascalABC.NET/Walk-a-directory-Recursively new file mode 120000 index 0000000000..6fba185f99 --- /dev/null +++ b/Lang/PascalABC.NET/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Window-creation b/Lang/PascalABC.NET/Window-creation new file mode 120000 index 0000000000..c656ea2a7f --- /dev/null +++ b/Lang/PascalABC.NET/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Word-frequency b/Lang/PascalABC.NET/Word-frequency new file mode 120000 index 0000000000..eed444f9fc --- /dev/null +++ b/Lang/PascalABC.NET/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Word-wrap b/Lang/PascalABC.NET/Word-wrap new file mode 120000 index 0000000000..b2cbb831f8 --- /dev/null +++ b/Lang/PascalABC.NET/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Write-entire-file b/Lang/PascalABC.NET/Write-entire-file new file mode 120000 index 0000000000..fb24fa3029 --- /dev/null +++ b/Lang/PascalABC.NET/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Write-to-Windows-event-log b/Lang/PascalABC.NET/Write-to-Windows-event-log new file mode 120000 index 0000000000..556c794eaf --- /dev/null +++ b/Lang/PascalABC.NET/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/XML-DOM-serialization b/Lang/PascalABC.NET/XML-DOM-serialization new file mode 120000 index 0000000000..ac8822f809 --- /dev/null +++ b/Lang/PascalABC.NET/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/XML-Input b/Lang/PascalABC.NET/XML-Input new file mode 120000 index 0000000000..6c693b433f --- /dev/null +++ b/Lang/PascalABC.NET/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/XML-Output b/Lang/PascalABC.NET/XML-Output new file mode 120000 index 0000000000..c33649037e --- /dev/null +++ b/Lang/PascalABC.NET/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Zero-to-the-zero-power b/Lang/PascalABC.NET/Zero-to-the-zero-power new file mode 120000 index 0000000000..315543b2a3 --- /dev/null +++ b/Lang/PascalABC.NET/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PascalABC.NET \ No newline at end of file diff --git a/Lang/Perl/Search-in-paragraphs-text b/Lang/Perl/Search-in-paragraphs-text new file mode 120000 index 0000000000..3327049060 --- /dev/null +++ b/Lang/Perl/Search-in-paragraphs-text @@ -0,0 +1 @@ +../../Task/Search-in-paragraphs-text/Perl \ No newline at end of file diff --git a/Lang/Prog8/Quine b/Lang/Prog8/Quine new file mode 120000 index 0000000000..d19dfe3196 --- /dev/null +++ b/Lang/Prog8/Quine @@ -0,0 +1 @@ +../../Task/Quine/Prog8 \ No newline at end of file diff --git a/Lang/PureBasic/M-bius-function b/Lang/PureBasic/M-bius-function new file mode 120000 index 0000000000..86603635cf --- /dev/null +++ b/Lang/PureBasic/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PureBasic \ No newline at end of file diff --git a/Lang/Python/Rhonda-numbers b/Lang/Python/Rhonda-numbers new file mode 120000 index 0000000000..26cc73526d --- /dev/null +++ b/Lang/Python/Rhonda-numbers @@ -0,0 +1 @@ +../../Task/Rhonda-numbers/Python \ No newline at end of file diff --git a/Lang/QB64/Fibonacci-n-step-number-sequences b/Lang/QB64/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..dbe9d19cad --- /dev/null +++ b/Lang/QB64/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/QB64 \ No newline at end of file diff --git a/Lang/QB64/Multiple-regression b/Lang/QB64/Multiple-regression new file mode 120000 index 0000000000..f5a655fb07 --- /dev/null +++ b/Lang/QB64/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/QB64 \ No newline at end of file diff --git a/Lang/QB64/Price-fraction b/Lang/QB64/Price-fraction new file mode 120000 index 0000000000..b2a7164220 --- /dev/null +++ b/Lang/QB64/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/QB64 \ No newline at end of file diff --git a/Lang/QBasic/Display-a-linear-combination b/Lang/QBasic/Display-a-linear-combination new file mode 120000 index 0000000000..e9d158c960 --- /dev/null +++ b/Lang/QBasic/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Fibonacci-n-step-number-sequences b/Lang/QBasic/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..77136c7137 --- /dev/null +++ b/Lang/QBasic/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Jensens-Device b/Lang/QBasic/Jensens-Device new file mode 120000 index 0000000000..199e4d7809 --- /dev/null +++ b/Lang/QBasic/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Nested-templated-data b/Lang/QBasic/Nested-templated-data new file mode 120000 index 0000000000..ddf5a87c1b --- /dev/null +++ b/Lang/QBasic/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Ramer-Douglas-Peucker-line-simplification b/Lang/QBasic/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..574b7acaf0 --- /dev/null +++ b/Lang/QBasic/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Vector b/Lang/QBasic/Vector new file mode 120000 index 0000000000..7bbf551f69 --- /dev/null +++ b/Lang/QBasic/Vector @@ -0,0 +1 @@ +../../Task/Vector/QBasic \ No newline at end of file diff --git a/Lang/Quackery/00-LANG.txt b/Lang/Quackery/00-LANG.txt index 498188387d..e36ac3a936 100644 --- a/Lang/Quackery/00-LANG.txt +++ b/Lang/Quackery/00-LANG.txt @@ -19,7 +19,7 @@ To compile this definition of quackery, build takes a The words is, [, and ] are builders; they can be found in the builders dictionary, which extends the functionality of build beyond building a flat nest for do to evaluate. is takes the item that do most recently added to its output nest, and adds it to the names dictionary, along with the string that follows it, "quackery" as its name. The syntax of Quackery is; words and numbers are sequences of printable characters, separated by spaces and carriage returns unless a builder treats the text that follows it otherwise. The builder builds is equivalent to is for adding new words and behaviours to the builders dictionary. -Evaluation of a nest proceeds from left to right unless a control flow operator redirects it. done causes doto stop evaluating a nest and return to the nest that pointed to it immediately, rather than at the end of the nest. again restarts the evaluation of that nest, non-recursively. The word recurse does it recursively. if and iff conditionally (depending on the item on the top of the Quackery stack) skip over the next one and two items in the nest respectively. else skips over one item, unconditionally. As with the other provided control flow operators, these words are nests, not operators, that make use of the "meta-control flow" operators, which grant the behaviours described above to words that use them. (They modify items on the return stack, rather than acting on the Quackery engine's various pointers registers directly, so their changes are enacted upon exiting the nest that called them.) +Evaluation of a nest proceeds from left to right unless a control flow operator redirects it. done causes doto stop evaluating a nest and return to the nest that pointed to it immediately, rather than at the end of the nest. again restarts the evaluation of that nest, non-recursively. The word recurse does it recursively. if and iff conditionally (depending on the item on the top of the Quackery stack) skip over the next one and two items in the nest respectively. else skips over one item, unconditionally. As with the other provided control flow operators, these words are nests, not operators, that make use of the "meta-control flow" operators, which grant the behaviours described above to words that use them. (They modify items on the return stack, rather than acting on the Quackery engine's various registers directly, so their changes are enacted upon exiting the nest that called them.) There are no variables in Quackery. Instead, there are stack management words to rearrange the uppermost items on the Quackery stack as required, and nameable ancillary stacks that fulfil the roles of variables. diff --git a/Lang/Quackery/Dinesmans-multiple-dwelling-problem b/Lang/Quackery/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..2061e87b20 --- /dev/null +++ b/Lang/Quackery/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Distribution-of-0-digits-in-factorial-series b/Lang/Quackery/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..8627f3195b --- /dev/null +++ b/Lang/Quackery/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Dutch-national-flag-problem b/Lang/Quackery/Dutch-national-flag-problem new file mode 120000 index 0000000000..133393cf2e --- /dev/null +++ b/Lang/Quackery/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Flipping-bits-game b/Lang/Quackery/Flipping-bits-game new file mode 120000 index 0000000000..fd3aa38458 --- /dev/null +++ b/Lang/Quackery/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..ddb9ece049 --- /dev/null +++ b/Lang/Quackery/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Password-generator b/Lang/Quackery/Password-generator new file mode 120000 index 0000000000..8d0efee13f --- /dev/null +++ b/Lang/Quackery/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Solve-the-no-connection-puzzle b/Lang/Quackery/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..d37f201a93 --- /dev/null +++ b/Lang/Quackery/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Quackery \ No newline at end of file diff --git a/Lang/QuickBASIC/Function-definition b/Lang/QuickBASIC/Function-definition new file mode 120000 index 0000000000..0251617973 --- /dev/null +++ b/Lang/QuickBASIC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Monty-Hall-problem b/Lang/QuickBASIC/Monty-Hall-problem new file mode 120000 index 0000000000..5a322fee75 --- /dev/null +++ b/Lang/QuickBASIC/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Random-numbers b/Lang/QuickBASIC/Random-numbers new file mode 120000 index 0000000000..8332f543fa --- /dev/null +++ b/Lang/QuickBASIC/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/QuickBASIC \ No newline at end of file diff --git a/Lang/QuickBASIC/Sorting-algorithms-Quicksort b/Lang/QuickBASIC/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..573bd236b2 --- /dev/null +++ b/Lang/QuickBASIC/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/QuickBASIC \ No newline at end of file diff --git a/Lang/R/Arithmetic-derivative b/Lang/R/Arithmetic-derivative new file mode 120000 index 0000000000..b37750c7e7 --- /dev/null +++ b/Lang/R/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/R \ No newline at end of file diff --git a/Lang/R/Compare-length-of-two-strings b/Lang/R/Compare-length-of-two-strings new file mode 120000 index 0000000000..834feb9f20 --- /dev/null +++ b/Lang/R/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/R \ No newline at end of file diff --git a/Lang/R/Conjugate-transpose b/Lang/R/Conjugate-transpose new file mode 120000 index 0000000000..573e26fb04 --- /dev/null +++ b/Lang/R/Conjugate-transpose @@ -0,0 +1 @@ +../../Task/Conjugate-transpose/R \ No newline at end of file diff --git a/Lang/R/Golden-ratio-Convergence b/Lang/R/Golden-ratio-Convergence new file mode 120000 index 0000000000..c3444860a4 --- /dev/null +++ b/Lang/R/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/R \ No newline at end of file diff --git a/Lang/REXX/00-LANG.txt b/Lang/REXX/00-LANG.txt index 26a483d9aa..e8f90b2e8c 100644 --- a/Lang/REXX/00-LANG.txt +++ b/Lang/REXX/00-LANG.txt @@ -36,7 +36,7 @@ The '''REXX''' language was influenced by the computer programming languages: &n * '''[[CRX REXX]]'''   (Compact REXX) is a classic REXX first written by Dr. Brian Marks. -* '''[[CTC REXX]]'''   is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation,   a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). +* '''[[CTC REXX]]'''   is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation,   a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). The last version was published in 1996. CTC doesn't exist anymore. * '''[[KEXX]]'''   is a subset of REXX that is bundled with KEDIT and written by Keven J. Kearney of Mansfield Software Group, Inc., a license is required to use this product.   KEXX only executes under the KEDIT licensed product.   KEDIT is an XEDIT clone (an editor from IBM for VM/CMS program products). @@ -75,7 +75,7 @@ The '''REXX''' language was influenced by the computer programming languages: &n * '''[[Regina REXX]]'''   is an implementation first created by Anders Christensen (in 1992) and is now maintained by others, notably Mark Hessling.   Regina REXX runs on more different platforms than any other REXX,   too many to name here.   It can be downloaded freely. -* '''[[Reginald REXX]]'''   is a REXX developed by Jeff Glatt.   It can be downloaded freely. +* '''[[Reginald REXX]]'''   is a REXX developed by Jeff Glatt.   It can be downloaded freely. According to Rexxinfo.org, Reginald is out of maintenance. * '''[[REXX/imc]]'''   a classic REXX developed by Ian M. Collier (imc) for Linux/Unix. @@ -84,10 +84,10 @@ The '''REXX''' language was influenced by the computer programming languages: &n * '''REXX/Personal'''   is another name for   '''Personal REXX'''     (see above). -* '''[[ROO oo-REXX]]'''   an object-oriented REXX developed by Keith Watts of Kilowatt Software, Inc.     It can be downloaded freely.   '''ROO'''   is also known as   '''ROO!'''. +* '''[[ROO oo-REXX]]'''   an object-oriented REXX developed by Keith Watts of Kilowatt Software, Inc.     It can be downloaded freely.   '''ROO'''   is also known as   '''ROO!'''. According to Rexxinfo.org, Roo! is out of maintenance. -* '''[[R4 REXX]]'''   a classic REXX developed by Keith Watts of Kilowatt Software, Inc.     It was also known as '''Portable REXX'''.   It can be downloaded freely. +* '''[[R4 REXX]]'''   a classic REXX developed by Keith Watts of Kilowatt Software, Inc.     It was also known as '''Portable REXX'''.   It can be downloaded freely. According to Rexxinfo.org, R4 is out of maintenance. * '''[[T/REXX, a REXX compiler for CMS]]'''   is an implementation of classic REXX written by Leigh Lundin and Mark Woodruff   (according to Wikipedia). diff --git a/Lang/REXX/Eulers-constant-0.5772... b/Lang/REXX/Eulers-constant-0.5772... new file mode 120000 index 0000000000..4dd79a59f3 --- /dev/null +++ b/Lang/REXX/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../REXX \ No newline at end of file diff --git a/Lang/Red/00-LANG.txt b/Lang/Red/00-LANG.txt index 1cb6089084..bde0f4b81e 100644 --- a/Lang/Red/00-LANG.txt +++ b/Lang/Red/00-LANG.txt @@ -8,6 +8,9 @@ Like Rebol, Red has a low memory footprint, is garbage collected, and has a [htt Red embeds several DSLs, among which Red/System (C semantics meet Red syntax), dedicated to low-level and system programming. It is also used as an intermediate language (IL) when Red is compiled. The Red executable is able to build Red/System files directly (`*.reds`) as well as Red files (`*.red`), and Red/System code may be embedded freely in Red code. +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Red Tasks not implemented in Red] + ==Useful links== * [http://www.red-lang.org Red Language Website] * [https://twitter.com/red_lang @red_lang] on Twitter. diff --git a/Lang/Refal/Copy-stdin-to-stdout b/Lang/Refal/Copy-stdin-to-stdout new file mode 120000 index 0000000000..974e13964c --- /dev/null +++ b/Lang/Refal/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Refal \ No newline at end of file diff --git a/Lang/Refal/Damm-algorithm b/Lang/Refal/Damm-algorithm new file mode 120000 index 0000000000..9b99056b8a --- /dev/null +++ b/Lang/Refal/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Refal \ No newline at end of file diff --git a/Lang/Refal/Determine-sentence-type b/Lang/Refal/Determine-sentence-type new file mode 120000 index 0000000000..13809ebd86 --- /dev/null +++ b/Lang/Refal/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Refal \ No newline at end of file diff --git a/Lang/Refal/Disarium-numbers b/Lang/Refal/Disarium-numbers new file mode 120000 index 0000000000..7389ead892 --- /dev/null +++ b/Lang/Refal/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Refal \ No newline at end of file diff --git a/Lang/Refal/Discordian-date b/Lang/Refal/Discordian-date new file mode 120000 index 0000000000..e18bd824ca --- /dev/null +++ b/Lang/Refal/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Refal \ No newline at end of file diff --git a/Lang/Refal/Factors-of-an-integer b/Lang/Refal/Factors-of-an-integer new file mode 120000 index 0000000000..b8b431c369 --- /dev/null +++ b/Lang/Refal/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Refal \ No newline at end of file diff --git a/Lang/Refal/Flatten-a-list b/Lang/Refal/Flatten-a-list new file mode 120000 index 0000000000..b2445ac726 --- /dev/null +++ b/Lang/Refal/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Refal \ No newline at end of file diff --git a/Lang/Refal/General-FizzBuzz b/Lang/Refal/General-FizzBuzz new file mode 120000 index 0000000000..019727fd06 --- /dev/null +++ b/Lang/Refal/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/Refal \ No newline at end of file diff --git a/Lang/Refal/Letter-frequency b/Lang/Refal/Letter-frequency new file mode 120000 index 0000000000..e9c48e99dd --- /dev/null +++ b/Lang/Refal/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Refal \ No newline at end of file diff --git a/Lang/Refal/McNuggets-problem b/Lang/Refal/McNuggets-problem new file mode 120000 index 0000000000..90628a4989 --- /dev/null +++ b/Lang/Refal/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Refal \ No newline at end of file diff --git a/Lang/Refal/Nested-templated-data b/Lang/Refal/Nested-templated-data new file mode 120000 index 0000000000..ceaf039a10 --- /dev/null +++ b/Lang/Refal/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Refal \ No newline at end of file diff --git a/Lang/Refal/One-dimensional-cellular-automata b/Lang/Refal/One-dimensional-cellular-automata new file mode 120000 index 0000000000..89b9ba280e --- /dev/null +++ b/Lang/Refal/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Refal \ No newline at end of file diff --git a/Lang/Refal/Palindrome-detection b/Lang/Refal/Palindrome-detection new file mode 120000 index 0000000000..87f1ace89c --- /dev/null +++ b/Lang/Refal/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Refal \ No newline at end of file diff --git a/Lang/Refal/Population-count b/Lang/Refal/Population-count new file mode 120000 index 0000000000..3cdd939b69 --- /dev/null +++ b/Lang/Refal/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Refal \ No newline at end of file diff --git a/Lang/Refal/Repeat b/Lang/Refal/Repeat new file mode 120000 index 0000000000..1cdb36e096 --- /dev/null +++ b/Lang/Refal/Repeat @@ -0,0 +1 @@ +../../Task/Repeat/Refal \ No newline at end of file diff --git a/Lang/Refal/Split-a-character-string-based-on-change-of-character b/Lang/Refal/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..8a3aec8866 --- /dev/null +++ b/Lang/Refal/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Refal \ No newline at end of file diff --git a/Lang/Refal/Square-but-not-cube b/Lang/Refal/Square-but-not-cube new file mode 120000 index 0000000000..a50417a708 --- /dev/null +++ b/Lang/Refal/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/Refal \ No newline at end of file diff --git a/Lang/Refal/Word-ladder b/Lang/Refal/Word-ladder new file mode 120000 index 0000000000..b43f6deb31 --- /dev/null +++ b/Lang/Refal/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/Refal \ No newline at end of file diff --git a/Lang/Rockstar/00-LANG.txt b/Lang/Rockstar/00-LANG.txt index 9dc3cbc2f7..c22e2c3636 100644 --- a/Lang/Rockstar/00-LANG.txt +++ b/Lang/Rockstar/00-LANG.txt @@ -1,4 +1,8 @@ -{{stub}}{{language|Rockstar}} +{{stub}} +{{language|Rockstar +|site=https://codewithrockstar.com/ +|hopl=no +}} Rockstar was created by a rockin' dude named Dylan Beattie. diff --git a/Lang/Run-BASIC/Nested-templated-data b/Lang/Run-BASIC/Nested-templated-data new file mode 120000 index 0000000000..e2c607e939 --- /dev/null +++ b/Lang/Run-BASIC/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Run-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Copy-a-string b/Lang/S-BASIC/Copy-a-string new file mode 120000 index 0000000000..cf54fdae2e --- /dev/null +++ b/Lang/S-BASIC/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Factorial b/Lang/S-BASIC/Factorial new file mode 120000 index 0000000000..3c6e9121ba --- /dev/null +++ b/Lang/S-BASIC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Loops-Break b/Lang/S-BASIC/Loops-Break new file mode 120000 index 0000000000..4109f93543 --- /dev/null +++ b/Lang/S-BASIC/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/S-BASIC \ No newline at end of file diff --git a/Lang/SETL/Brilliant-numbers b/Lang/SETL/Brilliant-numbers new file mode 120000 index 0000000000..8c8cbe8558 --- /dev/null +++ b/Lang/SETL/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Damm-algorithm b/Lang/SETL/Damm-algorithm new file mode 120000 index 0000000000..8e8b8d193a --- /dev/null +++ b/Lang/SETL/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/SETL \ No newline at end of file diff --git a/Lang/SETL/General-FizzBuzz b/Lang/SETL/General-FizzBuzz new file mode 120000 index 0000000000..c26977365f --- /dev/null +++ b/Lang/SETL/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/SETL \ No newline at end of file diff --git a/Lang/SETL/Levenshtein-distance b/Lang/SETL/Levenshtein-distance new file mode 120000 index 0000000000..5a234fcd60 --- /dev/null +++ b/Lang/SETL/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/SETL \ No newline at end of file diff --git a/Lang/SETL/Luhn-test-of-credit-card-numbers b/Lang/SETL/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..d5c47a10ed --- /dev/null +++ b/Lang/SETL/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/SETL \ No newline at end of file diff --git a/Lang/SETL/Monty-Hall-problem b/Lang/SETL/Monty-Hall-problem new file mode 120000 index 0000000000..0740052c5e --- /dev/null +++ b/Lang/SETL/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/SETL \ No newline at end of file diff --git a/Lang/SETL/Nested-templated-data b/Lang/SETL/Nested-templated-data new file mode 120000 index 0000000000..58fd3f508a --- /dev/null +++ b/Lang/SETL/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/SETL \ No newline at end of file diff --git a/Lang/SETL/Ordered-words b/Lang/SETL/Ordered-words new file mode 120000 index 0000000000..efd35b209e --- /dev/null +++ b/Lang/SETL/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/SETL \ No newline at end of file diff --git a/Lang/SETL/Pisano-period b/Lang/SETL/Pisano-period new file mode 120000 index 0000000000..735d169166 --- /dev/null +++ b/Lang/SETL/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/SETL \ No newline at end of file diff --git a/Lang/SETL/Show-ASCII-table b/Lang/SETL/Show-ASCII-table new file mode 120000 index 0000000000..5c4e8348ce --- /dev/null +++ b/Lang/SETL/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/SETL \ No newline at end of file diff --git a/Lang/SETL/Split-a-character-string-based-on-change-of-character b/Lang/SETL/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..ff9aa0b4dd --- /dev/null +++ b/Lang/SETL/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/SETL \ No newline at end of file diff --git a/Lang/SETL/Word-ladder b/Lang/SETL/Word-ladder new file mode 120000 index 0000000000..c8dccafa85 --- /dev/null +++ b/Lang/SETL/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/SETL \ No newline at end of file diff --git a/Lang/Sed/00-LANG.txt b/Lang/Sed/00-LANG.txt index 23390cea6c..5d2641e2db 100644 --- a/Lang/Sed/00-LANG.txt +++ b/Lang/Sed/00-LANG.txt @@ -6,5 +6,7 @@ a non interactive tool for text manipulation and filtering. One implementation is [[GNU Sed]] +See [[Tasks not implemented in sed]] + [[Category:Editor]] [[Category:Utility]] \ No newline at end of file diff --git a/Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers b/Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers new file mode 120000 index 0000000000..b80a20c4f5 --- /dev/null +++ b/Lang/Sidef/Increasing-gaps-between-consecutive-Niven-numbers @@ -0,0 +1 @@ +../../Task/Increasing-gaps-between-consecutive-Niven-numbers/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Jaro-Winkler-distance b/Lang/Sidef/Jaro-Winkler-distance new file mode 120000 index 0000000000..48f92f7ccd --- /dev/null +++ b/Lang/Sidef/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..1f840ef9e4 --- /dev/null +++ b/Lang/Sidef/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Smarandache-Wellin-primes b/Lang/Sidef/Smarandache-Wellin-primes new file mode 120000 index 0000000000..056e5bc295 --- /dev/null +++ b/Lang/Sidef/Smarandache-Wellin-primes @@ -0,0 +1 @@ +../../Task/Smarandache-Wellin-primes/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Wagstaff-primes b/Lang/Sidef/Wagstaff-primes new file mode 120000 index 0000000000..d0053cfbed --- /dev/null +++ b/Lang/Sidef/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Sidef \ No newline at end of file diff --git a/Lang/Standard-ML/Call-a-foreign-language-function b/Lang/Standard-ML/Call-a-foreign-language-function new file mode 120000 index 0000000000..1f398efa97 --- /dev/null +++ b/Lang/Standard-ML/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Pi b/Lang/Standard-ML/Pi new file mode 120000 index 0000000000..f806ddbcae --- /dev/null +++ b/Lang/Standard-ML/Pi @@ -0,0 +1 @@ +../../Task/Pi/Standard-ML \ No newline at end of file diff --git a/Lang/SuperCollider/00-LANG.txt b/Lang/SuperCollider/00-LANG.txt index f804a4a144..d6b538fcd2 100644 --- a/Lang/SuperCollider/00-LANG.txt +++ b/Lang/SuperCollider/00-LANG.txt @@ -9,4 +9,130 @@ The programming language was originally devised by James McCartney and has been [https://github.com/supercollider/supercollider SuperCollider at GitHub] -[http://supercollider.github.io/ SuperCollider Homepage] \ No newline at end of file +[http://supercollider.github.io/ SuperCollider Homepage] + + +

+Some additional notes on SuperCollider 2024-06-21 + +From the SuperCollider GitHub website: https://supercollider.github.io/ :
+Quote:
+A PLATFORM FOR AUDIO SYNTHESIS AND ALGORITHMIC COMPOSITION,
+      USED BY MUSICIANS, ARTISTS AND RESEARCHERS WORKING WITH SOUND. +

+FREE AND OPEN SOURCE SOFTWARE FOR WINDOWS, MACOS AND LINUX. +

+SuperCollider features three major components:
+scsynth – A real-time audio server
+sclang – An interpreted programming language
+scide – An editor for sclang with an integrated help system
+End-Quote.
+
+Some people try to squeeze a musical composition into 140 characters: (but just for the challenge):
+Don't judge SuperCollider or the language by these examples, they are just for fun.
+ +f={|t|Pbind(\note,Pseq([-1,1,6,8,9,1,-1,8,6,1,9,8]+5,319),\dur,t)};Ptpar([0,f.(1/6),12,f.(0.1672)],1).play + +Listen to the results here: https://supercollider.github.io/assets/audio/sc-140/06_batuhanbozkurt_celesteh.mp3
+You can see/hear more at: https://supercollider.github.io/sc-140.html
+
+
+As of today (2024-06-21) the current version of SuperCollider for all supported platforms is: 3.13.0 +

+While SClang (SuperCollider language) and its companion components are designed for the creation of sounds and music, the language is a full featured programming language. +

+The language is OO, to the extent that everything is an object, even numbers.
+In this snippet: 123 + 456 the 123 is an object, + is a method on the class of that object, and 456 is a parameter to that method.
+Even though + is a method the syntax of the addition is what you would typically expect. +

+The print function in SClang is a method called postln, which first appears in the root of the class tree: Object.
+
+Some examples, showing two possible call formats: + +postln("Hello World"); // prints: Hello World +"Hello World".postln; // prints: Hello World +postln(1001); // prints: 1001 +1001.postln; // prints: 1001 +postln(123 + 456); // prints: 579 +(123 + 456).postln; // prints: 579 + + +The method postln, adds a new-line after printing the text, if you don't want the new-line, use: post. +

+ +SuperCollider from the command line (not used much) + +SuperCollider scripts are stored in files with an extension of .scd. +These are typically referred to as supercollider documents, hence .scd. +

+99.99% of the time, you will execute code from within the IDE (scide).
+
+It is possible but not typical, to run a script from the command line, for example:
+ > sclang.exe ABC_problem.scd
+This will output the expected results. +See code at: https://rosettacode.org/wiki/ABC_problem#SuperCollider

+However, before executing your code, sclang will compile its class library, and you will see all of the messages about the compilation, before you see the output from your code. +

+Also, once your code is finished, you will be stuck as sclang is still waiting for more input from a file, not the keyboard. The second problem can be solved by adding exit(0); to the end of your script (.scd file); +

+SuperCollider comes packaged with QT, and has classes that represent GUI objects, for example:
+ > sclang.exe Barnsley_fern.scd
+Will open a window and draw the Barnsley Fern.
+See code at: https://rosettacode.org/wiki/Barnsley_fern#SuperCollider
+You will have to use Ctrl-c to kill the sclang process, you cannot add exit(0) to you script as the exit would happen before the GUI was fully created. +

+It is theoretically possible to create a thread within your script which waits until all work is done and then for it to execute exit(0); but you are just giving yourself extra work. +

+You can also run sclang without giving it a file, then it will accept input from the keyboard. + > sclang.exe
+You will get this prompt sc3> now you can type in ONE LINE OF CODE. +For example, the following line of code has three statements, the end result is printing the sum of the two numbers:
+sc3> var v1=123; var v2=456; postf("v1+v2=%\n", v1+v2);
+v1+v2=579
+-> v1+v2=579
+
+The line with the arrow: -> v1+v2=579, is sclang printing the value of the last expression executed +

+Summary: You can start sclang from the command line and type in some code, or you could give sclang a script to run, both will work, but it is much more productive to use scide. +Using sclang from the command line is like playing your guitar with winter gloves on, you could do it, but why make life difficult? +

+If you have composed (written code for) a long piece of music, and now you want to execute the code from the command line, yes, you can do it, but it isn't going to sound any different than it would if you execute the code from within scide.

+Also, scide offers the ability to 'live code', i.e. execute some code to make some music, and change the code as the music is playing, so the music evolves as you change the code. +

+ +SuperCollider from the IDE
+Start scide, or 'open' a SuperCollider Document (*.scd), if scide is 'associated' with that file type.
+See: https://doc.sccode.org/Guides/SCIde.html
+After you start scide, it starts sclang, which compiles the SuperCollider classes.
+Now you can start coding.
+
+How to execute code (borrowed from the page at the URL above)
+
+To evaluate code, use one of the following keyboard commands:
+Ctrl+Return
+Most used, "smart" code evaluation:
+Normally, the current line will be evaluated (where the cursor is).
+If the cursor is within a region, the entire region will be evaluated. See below for explanation of regions.
+If some code is selected, the selection will be evaluated.
+
+Shift+Return +

+Evaluates either the current line, or the selection (if any). Use this to evaluate a single line within a region without the need to select it.
+Regions make it quick and easy to evaluate larger portions of code. A region is surrounded by parentheses; to be interpreted as a region, the parenthesis must each be the only character on a line.
+ +( +Pbind( + \degree, Pseries(0, 1, 8), + \dur, 0.25 +).play; +) + +If the cursor is anywhere between the outermost parentheses, pressing Ctrl+Return will automatically evaluate the entire contents within the parentheses, starting with Pbind and ending with play;.
+

+To quickly evaluate a portion of code, you can also double-click on any bracket (round, squared, or curly), which will select everything between this and the other matching bracket, so you can quickly evaluate it. +

+To stop any running code, use the Ctrl+. shortcut (Ctrl+Period).
+This will stop all the code scheduled on the clocks, as well as all the sound processes on the audio server. +

+ +... more coming soon ... \ No newline at end of file diff --git a/Lang/SuperCollider/Semordnilap b/Lang/SuperCollider/Semordnilap deleted file mode 120000 index ace051dba8..0000000000 --- a/Lang/SuperCollider/Semordnilap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Semordnilap/SuperCollider \ No newline at end of file diff --git a/Lang/Swift/Compare-length-of-two-strings b/Lang/Swift/Compare-length-of-two-strings new file mode 120000 index 0000000000..d53f307b7e --- /dev/null +++ b/Lang/Swift/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Swift \ No newline at end of file diff --git a/Lang/Swift/Pseudo-random-numbers-Splitmix64 b/Lang/Swift/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..7f3d66c35a --- /dev/null +++ b/Lang/Swift/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Swift \ No newline at end of file diff --git a/Lang/Transd/Compare-length-of-two-strings b/Lang/Transd/Compare-length-of-two-strings deleted file mode 120000 index 28f3956c3e..0000000000 --- a/Lang/Transd/Compare-length-of-two-strings +++ /dev/null @@ -1 +0,0 @@ -../../Task/Compare-length-of-two-strings/Transd \ No newline at end of file diff --git a/Lang/True-BASIC/100-prisoners b/Lang/True-BASIC/100-prisoners new file mode 120000 index 0000000000..b793e357f7 --- /dev/null +++ b/Lang/True-BASIC/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Multiple-regression b/Lang/True-BASIC/Multiple-regression new file mode 120000 index 0000000000..ca0e5c404e --- /dev/null +++ b/Lang/True-BASIC/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Vector b/Lang/True-BASIC/Vector new file mode 120000 index 0000000000..4da227d0fe --- /dev/null +++ b/Lang/True-BASIC/Vector @@ -0,0 +1 @@ +../../Task/Vector/True-BASIC \ No newline at end of file diff --git a/Lang/TypeScript/Deal-cards-for-FreeCell b/Lang/TypeScript/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..04eefe17ef --- /dev/null +++ b/Lang/TypeScript/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/TypeScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/Pi b/Lang/UNIX-Shell/Pi new file mode 120000 index 0000000000..854a52d02a --- /dev/null +++ b/Lang/UNIX-Shell/Pi @@ -0,0 +1 @@ +../../Task/Pi/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm b/Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..d9c18fe35b --- /dev/null +++ b/Lang/UNIX-Shell/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/UNIX-Shell \ No newline at end of file diff --git a/Lang/Uiua/00-LANG.txt b/Lang/Uiua/00-LANG.txt index 2a4f3f689f..820e780454 100644 --- a/Lang/Uiua/00-LANG.txt +++ b/Lang/Uiua/00-LANG.txt @@ -1,6 +1,13 @@ {{language -|site=https://www.uiua.org/}} -{{language programming paradigm|functional}} +|exec=bytecode +|site=https://www.uiua.org/ +|checking=dynamic +|gc=yes +|express=implicit +|LCT=yes}} +{{language programming paradigm|array}} +{{language programming paradigm|functional|array}} + Uiua (''wee-wuh'') is a general purpose, stack-based, array-oriented programming language with a focus on simplicity, beauty, and tacit code. Uiua has a simple, context-free, LL(3) grammar. Code runs from right to left, top to bottom, with only one precedence rule. As operators are to the left of their operands, Uiua code reads a little bit like a Lisp, but with fewer parentheses. @@ -11,4 +18,7 @@ Uiua's one and only composite data type, the array, is based on those of APL, J, Unlike other array languages, Uiua does not have monadic and dyadic versions of each glyph. Every glyph does only one thing, so you don't need to parse an entire expression to know which version it is. -Find out more, and run code in your browser at https://www.uiua.org \ No newline at end of file +Find out more, and run code in your browser at https://www.uiua.org + +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Uiua Tasks not implemented in Uiua] \ No newline at end of file diff --git a/Lang/Uiua/15-puzzle-solver b/Lang/Uiua/15-puzzle-solver new file mode 120000 index 0000000000..d2c4541287 --- /dev/null +++ b/Lang/Uiua/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Uiua \ No newline at end of file diff --git a/Lang/Uiua/ADFGVX-cipher b/Lang/Uiua/ADFGVX-cipher new file mode 120000 index 0000000000..3b808ce65e --- /dev/null +++ b/Lang/Uiua/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/Uiua \ No newline at end of file diff --git a/Lang/Uiua/ASCII-art-diagram-converter b/Lang/Uiua/ASCII-art-diagram-converter new file mode 120000 index 0000000000..7868ebc205 --- /dev/null +++ b/Lang/Uiua/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Abbreviations-automatic b/Lang/Uiua/Abbreviations-automatic new file mode 120000 index 0000000000..4ed38ebb71 --- /dev/null +++ b/Lang/Uiua/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Abelian-sandpile-model b/Lang/Uiua/Abelian-sandpile-model new file mode 120000 index 0000000000..511d6d21ce --- /dev/null +++ b/Lang/Uiua/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Align-columns b/Lang/Uiua/Align-columns new file mode 120000 index 0000000000..90d8156011 --- /dev/null +++ b/Lang/Uiua/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Anti-primes b/Lang/Uiua/Anti-primes new file mode 120000 index 0000000000..caaf04d665 --- /dev/null +++ b/Lang/Uiua/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Arithmetic-geometric-mean b/Lang/Uiua/Arithmetic-geometric-mean new file mode 120000 index 0000000000..6adeb66a11 --- /dev/null +++ b/Lang/Uiua/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Array-concatenation b/Lang/Uiua/Array-concatenation new file mode 120000 index 0000000000..48fabf1a40 --- /dev/null +++ b/Lang/Uiua/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Array-length b/Lang/Uiua/Array-length new file mode 120000 index 0000000000..7c3be21b34 --- /dev/null +++ b/Lang/Uiua/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ascending-primes b/Lang/Uiua/Ascending-primes new file mode 120000 index 0000000000..83b9f7be7a --- /dev/null +++ b/Lang/Uiua/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Averages-Mean-time-of-day b/Lang/Uiua/Averages-Mean-time-of-day new file mode 120000 index 0000000000..970582690e --- /dev/null +++ b/Lang/Uiua/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Barnsley-fern b/Lang/Uiua/Barnsley-fern new file mode 120000 index 0000000000..39f57d2d79 --- /dev/null +++ b/Lang/Uiua/Barnsley-fern @@ -0,0 +1 @@ +../../Task/Barnsley-fern/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Benfords-law b/Lang/Uiua/Benfords-law new file mode 120000 index 0000000000..c9f7d29ef6 --- /dev/null +++ b/Lang/Uiua/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bifid-cipher b/Lang/Uiua/Bifid-cipher new file mode 120000 index 0000000000..7118fdadf7 --- /dev/null +++ b/Lang/Uiua/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Binary-digits b/Lang/Uiua/Binary-digits new file mode 120000 index 0000000000..126c2d6665 --- /dev/null +++ b/Lang/Uiua/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Bulls-and-cows-Player b/Lang/Uiua/Bulls-and-cows-Player new file mode 120000 index 0000000000..b45c91dd88 --- /dev/null +++ b/Lang/Uiua/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Uiua \ No newline at end of file diff --git a/Lang/Uiua/CSV-data-manipulation b/Lang/Uiua/CSV-data-manipulation new file mode 120000 index 0000000000..78747e6f49 --- /dev/null +++ b/Lang/Uiua/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Calkin-Wilf-sequence b/Lang/Uiua/Calkin-Wilf-sequence new file mode 120000 index 0000000000..23330ada15 --- /dev/null +++ b/Lang/Uiua/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Cartesian-product-of-two-or-more-lists b/Lang/Uiua/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..bff2250b36 --- /dev/null +++ b/Lang/Uiua/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Combinations b/Lang/Uiua/Combinations new file mode 120000 index 0000000000..1300366dbb --- /dev/null +++ b/Lang/Uiua/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Convert-seconds-to-compound-duration b/Lang/Uiua/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..7c892696f2 --- /dev/null +++ b/Lang/Uiua/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Conways-Game-of-Life b/Lang/Uiua/Conways-Game-of-Life new file mode 120000 index 0000000000..577dcf20b1 --- /dev/null +++ b/Lang/Uiua/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Determine-if-a-string-is-collapsible b/Lang/Uiua/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..9891000cca --- /dev/null +++ b/Lang/Uiua/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Dutch-national-flag-problem b/Lang/Uiua/Dutch-national-flag-problem new file mode 120000 index 0000000000..198949a01a --- /dev/null +++ b/Lang/Uiua/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Factorial b/Lang/Uiua/Factorial new file mode 120000 index 0000000000..5664c30904 --- /dev/null +++ b/Lang/Uiua/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Factors-of-an-integer b/Lang/Uiua/Factors-of-an-integer new file mode 120000 index 0000000000..c83bd4a95a --- /dev/null +++ b/Lang/Uiua/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Find-the-missing-permutation b/Lang/Uiua/Find-the-missing-permutation new file mode 120000 index 0000000000..e1361833f3 --- /dev/null +++ b/Lang/Uiua/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Flatten-a-list b/Lang/Uiua/Flatten-a-list new file mode 120000 index 0000000000..8d22eb4f6e --- /dev/null +++ b/Lang/Uiua/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Flipping-bits-game b/Lang/Uiua/Flipping-bits-game new file mode 120000 index 0000000000..4647df0617 --- /dev/null +++ b/Lang/Uiua/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Forest-fire b/Lang/Uiua/Forest-fire new file mode 120000 index 0000000000..1c1ded9f8f --- /dev/null +++ b/Lang/Uiua/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Greatest-common-divisor b/Lang/Uiua/Greatest-common-divisor new file mode 120000 index 0000000000..ed42b8017f --- /dev/null +++ b/Lang/Uiua/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Identity-matrix b/Lang/Uiua/Identity-matrix new file mode 120000 index 0000000000..73bc76c89c --- /dev/null +++ b/Lang/Uiua/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Increment-a-numerical-string b/Lang/Uiua/Increment-a-numerical-string new file mode 120000 index 0000000000..5102531751 --- /dev/null +++ b/Lang/Uiua/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Integer-sequence b/Lang/Uiua/Integer-sequence new file mode 120000 index 0000000000..71a2ec5539 --- /dev/null +++ b/Lang/Uiua/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Langtons-ant b/Lang/Uiua/Langtons-ant new file mode 120000 index 0000000000..ea25fbedff --- /dev/null +++ b/Lang/Uiua/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Largest-int-from-concatenated-ints b/Lang/Uiua/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..1440573f32 --- /dev/null +++ b/Lang/Uiua/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Least-common-multiple b/Lang/Uiua/Least-common-multiple new file mode 120000 index 0000000000..83973eef06 --- /dev/null +++ b/Lang/Uiua/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Levenshtein-distance b/Lang/Uiua/Levenshtein-distance new file mode 120000 index 0000000000..2d4dd26520 --- /dev/null +++ b/Lang/Uiua/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Uiua \ No newline at end of file diff --git a/Lang/Uiua/List-comprehensions b/Lang/Uiua/List-comprehensions new file mode 120000 index 0000000000..bf7b708e56 --- /dev/null +++ b/Lang/Uiua/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Look-and-say-sequence b/Lang/Uiua/Look-and-say-sequence new file mode 120000 index 0000000000..f3d748e2f9 --- /dev/null +++ b/Lang/Uiua/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Loop-over-multiple-arrays-simultaneously b/Lang/Uiua/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..59937c5207 --- /dev/null +++ b/Lang/Uiua/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Luhn-test-of-credit-card-numbers b/Lang/Uiua/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..6eae093c92 --- /dev/null +++ b/Lang/Uiua/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Mandelbrot-set b/Lang/Uiua/Mandelbrot-set new file mode 120000 index 0000000000..da1b6d50fa --- /dev/null +++ b/Lang/Uiua/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Matrix-multiplication b/Lang/Uiua/Matrix-multiplication new file mode 120000 index 0000000000..8ecd583efc --- /dev/null +++ b/Lang/Uiua/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Maze-solving b/Lang/Uiua/Maze-solving new file mode 120000 index 0000000000..02af57731f --- /dev/null +++ b/Lang/Uiua/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Uiua \ No newline at end of file diff --git a/Lang/Uiua/McNuggets-problem b/Lang/Uiua/McNuggets-problem new file mode 120000 index 0000000000..93b54a1053 --- /dev/null +++ b/Lang/Uiua/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Middle-three-digits b/Lang/Uiua/Middle-three-digits new file mode 120000 index 0000000000..5c8f171c17 --- /dev/null +++ b/Lang/Uiua/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Motzkin-numbers b/Lang/Uiua/Motzkin-numbers new file mode 120000 index 0000000000..bef04d5aa9 --- /dev/null +++ b/Lang/Uiua/Motzkin-numbers @@ -0,0 +1 @@ +../../Task/Motzkin-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/N-queens-problem b/Lang/Uiua/N-queens-problem new file mode 120000 index 0000000000..d8b56e5e2a --- /dev/null +++ b/Lang/Uiua/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..fd1772b308 --- /dev/null +++ b/Lang/Uiua/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/Uiua \ No newline at end of file diff --git a/Lang/Uiua/One-dimensional-cellular-automata b/Lang/Uiua/One-dimensional-cellular-automata new file mode 120000 index 0000000000..5df7e9b84a --- /dev/null +++ b/Lang/Uiua/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ordered-words b/Lang/Uiua/Ordered-words new file mode 120000 index 0000000000..7046edd964 --- /dev/null +++ b/Lang/Uiua/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Permutations b/Lang/Uiua/Permutations new file mode 120000 index 0000000000..850f4f7144 --- /dev/null +++ b/Lang/Uiua/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pick-random-element b/Lang/Uiua/Pick-random-element new file mode 120000 index 0000000000..e85c1a21e1 --- /dev/null +++ b/Lang/Uiua/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Uiua \ No newline at end of file diff --git a/Lang/Uiua/RPG-attributes-generator b/Lang/Uiua/RPG-attributes-generator new file mode 120000 index 0000000000..96e8262b6d --- /dev/null +++ b/Lang/Uiua/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Random-numbers b/Lang/Uiua/Random-numbers new file mode 120000 index 0000000000..bc115ba91a --- /dev/null +++ b/Lang/Uiua/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Run-length-encoding b/Lang/Uiua/Run-length-encoding new file mode 120000 index 0000000000..b6eee5ca86 --- /dev/null +++ b/Lang/Uiua/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Smith-numbers b/Lang/Uiua/Smith-numbers new file mode 120000 index 0000000000..3e4afb53bf --- /dev/null +++ b/Lang/Uiua/Smith-numbers @@ -0,0 +1 @@ +../../Task/Smith-numbers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Solve-a-Hidato-puzzle b/Lang/Uiua/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..961a795fe0 --- /dev/null +++ b/Lang/Uiua/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Solve-a-Numbrix-puzzle b/Lang/Uiua/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..d5e755e9d5 --- /dev/null +++ b/Lang/Uiua/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sort-disjoint-sublist b/Lang/Uiua/Sort-disjoint-sublist new file mode 120000 index 0000000000..247b8fbb37 --- /dev/null +++ b/Lang/Uiua/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Split-a-character-string-based-on-change-of-character b/Lang/Uiua/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..61d4dd8555 --- /dev/null +++ b/Lang/Uiua/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Square-free-integers b/Lang/Uiua/Square-free-integers new file mode 120000 index 0000000000..7a649e9779 --- /dev/null +++ b/Lang/Uiua/Square-free-integers @@ -0,0 +1 @@ +../../Task/Square-free-integers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Stem-and-leaf-plot b/Lang/Uiua/Stem-and-leaf-plot new file mode 120000 index 0000000000..cfafe7201a --- /dev/null +++ b/Lang/Uiua/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-case b/Lang/Uiua/String-case new file mode 120000 index 0000000000..4362c13413 --- /dev/null +++ b/Lang/Uiua/String-case @@ -0,0 +1 @@ +../../Task/String-case/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-concatenation b/Lang/Uiua/String-concatenation new file mode 120000 index 0000000000..cd5c2325bd --- /dev/null +++ b/Lang/Uiua/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-interpolation-included- b/Lang/Uiua/String-interpolation-included- new file mode 120000 index 0000000000..e880f170b4 --- /dev/null +++ b/Lang/Uiua/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Uiua \ No newline at end of file diff --git a/Lang/Uiua/String-matching b/Lang/Uiua/String-matching new file mode 120000 index 0000000000..d45ce27782 --- /dev/null +++ b/Lang/Uiua/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Strip-a-set-of-characters-from-a-string b/Lang/Uiua/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..951d176969 --- /dev/null +++ b/Lang/Uiua/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sudoku b/Lang/Uiua/Sudoku new file mode 120000 index 0000000000..be7e18a94a --- /dev/null +++ b/Lang/Uiua/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Sum-multiples-of-3-and-5 b/Lang/Uiua/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..1949126562 --- /dev/null +++ b/Lang/Uiua/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Summarize-primes b/Lang/Uiua/Summarize-primes new file mode 120000 index 0000000000..4ad940883d --- /dev/null +++ b/Lang/Uiua/Summarize-primes @@ -0,0 +1 @@ +../../Task/Summarize-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Test-a-function b/Lang/Uiua/Test-a-function new file mode 120000 index 0000000000..4e61b05504 --- /dev/null +++ b/Lang/Uiua/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Truncatable-primes b/Lang/Uiua/Truncatable-primes new file mode 120000 index 0000000000..b02bf04462 --- /dev/null +++ b/Lang/Uiua/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Validate-International-Securities-Identification-Number b/Lang/Uiua/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..6d28391590 --- /dev/null +++ b/Lang/Uiua/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Water-collected-between-towers b/Lang/Uiua/Water-collected-between-towers new file mode 120000 index 0000000000..cfd5fa722a --- /dev/null +++ b/Lang/Uiua/Water-collected-between-towers @@ -0,0 +1 @@ +../../Task/Water-collected-between-towers/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Yellowstone-sequence b/Lang/Uiua/Yellowstone-sequence new file mode 120000 index 0000000000..0bae4da70f --- /dev/null +++ b/Lang/Uiua/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Zebra-puzzle b/Lang/Uiua/Zebra-puzzle new file mode 120000 index 0000000000..cd343323b4 --- /dev/null +++ b/Lang/Uiua/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Uiua \ No newline at end of file diff --git a/Lang/Uxntal/Quine b/Lang/Uxntal/Quine new file mode 120000 index 0000000000..9f3a4ca4d4 --- /dev/null +++ b/Lang/Uxntal/Quine @@ -0,0 +1 @@ +../../Task/Quine/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Weird-numbers b/Lang/Uxntal/Weird-numbers new file mode 120000 index 0000000000..1bddac81d2 --- /dev/null +++ b/Lang/Uxntal/Weird-numbers @@ -0,0 +1 @@ +../../Task/Weird-numbers/Uxntal \ No newline at end of file diff --git a/Lang/Vim-Script/Hello-world-Graphical b/Lang/Vim-Script/Hello-world-Graphical new file mode 120000 index 0000000000..799696cc16 --- /dev/null +++ b/Lang/Vim-Script/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Here-document b/Lang/Vim-Script/Here-document new file mode 120000 index 0000000000..4f2967d090 --- /dev/null +++ b/Lang/Vim-Script/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously b/Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..3e8729e53b --- /dev/null +++ b/Lang/Vim-Script/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loops-For b/Lang/Vim-Script/Loops-For new file mode 120000 index 0000000000..427dcdb8bf --- /dev/null +++ b/Lang/Vim-Script/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/XML-Input b/Lang/Vim-Script/XML-Input new file mode 120000 index 0000000000..57be30dc70 --- /dev/null +++ b/Lang/Vim-Script/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Vim-Script \ No newline at end of file diff --git a/Lang/Wren/00-LANG.txt b/Lang/Wren/00-LANG.txt index 1dbc2e611b..ea9fd010ee 100644 --- a/Lang/Wren/00-LANG.txt +++ b/Lang/Wren/00-LANG.txt @@ -15,7 +15,7 @@ It is under development on [https://github.com/wren-lang/wren GitHub] and is ful The CLI tool (Wren CLI) has its own repository and is the main focus of examples written for RC. The latest version 0.4.0 is available as a pre-built standalone executable for 64-bit Linux, MacOS and Windows and can be downloaded from [https://github.com/wren-lang/wren-cli/releases here]. -As a language mainly designed for embedding, Wren's standard library is (of necessity) quite small and I have therefore decided to create some additional modules to assist with writing Rosetta Code tasks so the same code does not have to be written or copy/pasted time and time again thereby bloating a task's script code unnecessarily. The ones written so far are listed below: +As a language mainly designed for embedding, Wren's standard library is (of necessity) quite small and I ([[User:PureFox|PureFox]]) have therefore decided to create some additional modules to assist with writing Rosetta Code tasks so the same code does not have to be written or copy/pasted time and time again thereby bloating a task's script code unnecessarily. The ones written so far are listed below: {| class="wikitable" ! No. !! Module name !! !! No. !! Module name diff --git a/Lang/XBasic/Euler-method b/Lang/XBasic/Euler-method new file mode 120000 index 0000000000..546ca521e8 --- /dev/null +++ b/Lang/XBasic/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/XBasic \ No newline at end of file diff --git a/Lang/XBasic/M-bius-function b/Lang/XBasic/M-bius-function new file mode 120000 index 0000000000..09886c7873 --- /dev/null +++ b/Lang/XBasic/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Nim-game b/Lang/XBasic/Nim-game new file mode 120000 index 0000000000..49a494ab0c --- /dev/null +++ b/Lang/XBasic/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Sorting-algorithms-Quicksort b/Lang/XBasic/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..baefc61c90 --- /dev/null +++ b/Lang/XBasic/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/XBasic \ No newline at end of file diff --git a/Lang/XPL0/Draw-a-clock b/Lang/XPL0/Draw-a-clock new file mode 120000 index 0000000000..7d1040eda3 --- /dev/null +++ b/Lang/XPL0/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Poker-hand-analyser b/Lang/XPL0/Poker-hand-analyser new file mode 120000 index 0000000000..5fc0329088 --- /dev/null +++ b/Lang/XPL0/Poker-hand-analyser @@ -0,0 +1 @@ +../../Task/Poker-hand-analyser/XPL0 \ No newline at end of file diff --git a/Lang/YAMLScript/00-LANG.txt b/Lang/YAMLScript/00-LANG.txt index 1ead096361..eae1577f6a 100644 --- a/Lang/YAMLScript/00-LANG.txt +++ b/Lang/YAMLScript/00-LANG.txt @@ -7,6 +7,7 @@ '''[https://yamlscript.org YAMLScript]''' is a new programming language that uses [https://yaml.org/ YAML] as its syntax. It is a complete, functional, general purpose language, but can also be easily embedded in YAML files to make them dynamic at load time. Most existing YAML files and all JSON files are already valid YAMLScript programs. YAMLScript has a compiler/interpreter CLI program called [https://github.com/yaml/yamlscript/releases ys] and is also available in several programming languages as a binding module to the [https://github.com/yaml/yamlscript/releases libyamlscript.so] shared library: * [https://clojars.org/org.yamlscript/clj-yamlscript Clojure] +* [https://github.com/yaml/yamlscript-go Go] * [https://clojars.org/org.yamlscript/yamlscript Java] * [https://www.npmjs.com/package/@yaml/yamlscript NodeJS] * [https://metacpan.org/pod/YAMLScript Perl] @@ -19,7 +20,7 @@ Run this command to install the ys command line YAMLScript runner/loader/compiler program. - curl -sSL yamlscript.org/install | bash + curl -s https://yamlscript.org/install | bash That will install $HOME/.local/bin/ys. If $HOME/.local/bin is not in your PATH, run: diff --git a/Lang/Yabasic/Display-a-linear-combination b/Lang/Yabasic/Display-a-linear-combination new file mode 120000 index 0000000000..3089327b6e --- /dev/null +++ b/Lang/Yabasic/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Kronecker-product b/Lang/Yabasic/Kronecker-product new file mode 120000 index 0000000000..64e2f55421 --- /dev/null +++ b/Lang/Yabasic/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Multiple-regression b/Lang/Yabasic/Multiple-regression new file mode 120000 index 0000000000..047c89f1aa --- /dev/null +++ b/Lang/Yabasic/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Nested-templated-data b/Lang/Yabasic/Nested-templated-data new file mode 120000 index 0000000000..026a122d79 --- /dev/null +++ b/Lang/Yabasic/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Sexy-primes b/Lang/Yabasic/Sexy-primes new file mode 120000 index 0000000000..a3fa026246 --- /dev/null +++ b/Lang/Yabasic/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Sorting-algorithms-Counting-sort b/Lang/Yabasic/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c5fee45d6b --- /dev/null +++ b/Lang/Yabasic/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Sorting-algorithms-Stooge-sort b/Lang/Yabasic/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..920cab2b30 --- /dev/null +++ b/Lang/Yabasic/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Yabasic \ No newline at end of file diff --git a/Lang/Zig/15-puzzle-game b/Lang/Zig/15-puzzle-game new file mode 120000 index 0000000000..67842297fa --- /dev/null +++ b/Lang/Zig/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/Zig \ No newline at end of file diff --git a/Lang/Zig/9-billion-names-of-God-the-integer b/Lang/Zig/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..891e6336a6 --- /dev/null +++ b/Lang/Zig/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Zig \ No newline at end of file diff --git a/Lang/Zig/A+B b/Lang/Zig/A+B new file mode 120000 index 0000000000..99c5298cb2 --- /dev/null +++ b/Lang/Zig/A+B @@ -0,0 +1 @@ +../../Task/A+B/Zig \ No newline at end of file diff --git a/Lang/Zig/Determine-if-a-string-is-numeric b/Lang/Zig/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..1317ba1b29 --- /dev/null +++ b/Lang/Zig/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Zig \ No newline at end of file diff --git a/Lang/Zig/Egyptian-division b/Lang/Zig/Egyptian-division new file mode 120000 index 0000000000..fbc8453acb --- /dev/null +++ b/Lang/Zig/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Zig \ No newline at end of file diff --git a/Lang/Zig/Integer-sequence b/Lang/Zig/Integer-sequence new file mode 120000 index 0000000000..43f4f97f8b --- /dev/null +++ b/Lang/Zig/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Monty-Hall-problem b/Lang/Zig/Monty-Hall-problem new file mode 120000 index 0000000000..5c32ef8986 --- /dev/null +++ b/Lang/Zig/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Zig \ No newline at end of file diff --git a/Lang/Zig/Solve-the-no-connection-puzzle b/Lang/Zig/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..4b3367c677 --- /dev/null +++ b/Lang/Zig/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Zig \ No newline at end of file diff --git a/Task/100-doors/APL/100-doors-2.apl b/Task/100-doors/APL/100-doors-2.apl index ba6d739dae..bff8982b24 100644 --- a/Task/100-doors/APL/100-doors-2.apl +++ b/Task/100-doors/APL/100-doors-2.apl @@ -1,3 +1 @@ -⍝⍝ Also works with GNU APL after introduction of -⍝⍝ the ⍸ function with SVN r1368, Dec 03 2020 -⍸≠⌿0=(⍳100)∘.|⍳100 +≠⌿0=(⍳100)∘.|⍳100 diff --git a/Task/100-doors/APL/100-doors-3.apl b/Task/100-doors/APL/100-doors-3.apl new file mode 100644 index 0000000000..5fcad5e104 --- /dev/null +++ b/Task/100-doors/APL/100-doors-3.apl @@ -0,0 +1 @@ +⍸≠⌿0=(⍳100)∘.|⍳100 diff --git a/Task/100-doors/Langur/100-doors-1.langur b/Task/100-doors/Langur/100-doors-1.langur index 48e130366a..caac5fccf7 100644 --- a/Task/100-doors/Langur/100-doors-1.langur +++ b/Task/100-doors/Langur/100-doors-1.langur @@ -1,9 +1,9 @@ -var .doors = [false] * 100 +var doors = [false] * 100 -for .i of .doors { - for .j = .i; .j <= len(.doors); .j += .i { - .doors[.j] = not .doors[.j] +for i of doors { + for j = i; j <= len(doors); j += i { + doors[j] = not doors[j] } } -writeln for[=[]] .i of .doors { if(.doors[.i]: _for ~= [.i]) } +writeln for[=[]] i of doors { if doors[i]: _for = more(_for, i) } diff --git a/Task/100-doors/Langur/100-doors-2.langur b/Task/100-doors/Langur/100-doors-2.langur index f120dd60c3..f0f96dadfb 100644 --- a/Task/100-doors/Langur/100-doors-2.langur +++ b/Task/100-doors/Langur/100-doors-2.langur @@ -1 +1 @@ -writeln foldfrom(fn(.a, .b, .c) if(.b: .a~[.c]; .a), [], .doors, series 1..len .doors) +writeln foldfrom(fn a, b, c: if(b: a~[c]; a), [], doors, series(1..len(doors))) diff --git a/Task/100-doors/Langur/100-doors-3.langur b/Task/100-doors/Langur/100-doors-3.langur index d1c575957b..67108b6065 100644 --- a/Task/100-doors/Langur/100-doors-3.langur +++ b/Task/100-doors/Langur/100-doors-3.langur @@ -1 +1 @@ -writeln map fn{^2}, 1..10 +writeln map(fn{^2}, 1..10) diff --git a/Task/100-doors/Oberon/100-doors.oberon b/Task/100-doors/Oberon/100-doors.oberon deleted file mode 100644 index ddec2b2de8..0000000000 --- a/Task/100-doors/Oberon/100-doors.oberon +++ /dev/null @@ -1,27 +0,0 @@ -MODULE Doors; - IMPORT Out; - - PROCEDURE Do*; (* In Oberon an asterisk after an identifier is an export mark *) - CONST N = 100; len = N + 1; - VAR i, j: INTEGER; - closed: ARRAY len OF BOOLEAN; (* Arrays in Oberon always start with index 0; closed[0] is not used *) - BEGIN - FOR i := 1 TO N DO closed[i] := TRUE END; - FOR i := 1 TO N DO - j := 1; - WHILE j < len DO - IF j MOD i = 0 THEN closed[j] := ~closed[j] END; INC(j) (* ~ = NOT *) - END - END; - (* Print a state diagram of all doors *) - FOR i := 1 TO N DO - IF (i - 1) MOD 10 = 0 THEN Out.Ln END; - IF closed[i] THEN Out.String("- ") ELSE Out.String("+ ") END - END; Out.Ln; - (* Print the numbers of the open doors *) - FOR i := 1 TO N DO - IF ~closed[i] THEN Out.Int(i, 0); Out.Char(" ") END - END; Out.Ln - END Do; - -END Doors. diff --git a/Task/100-doors/V-(Vlang)/100-doors-2.v b/Task/100-doors/V-(Vlang)/100-doors-2.v index 6ec392d9a6..35ff929ac5 100644 --- a/Task/100-doors/V-(Vlang)/100-doors-2.v +++ b/Task/100-doors/V-(Vlang)/100-doors-2.v @@ -11,11 +11,10 @@ fn main(){ doors[current - 1] = true increment++ door_nbr += 2 * increment + 1 - } + print('O') + } else { + print('=') + } } - doors.map( fn( it bool) bool { // graphically represent opened doors - print( if it {( 'O')} else {('=')} ) - return it - }) println('') } diff --git a/Task/100-doors/V-(Vlang)/100-doors-3.v b/Task/100-doors/V-(Vlang)/100-doors-3.v new file mode 100644 index 0000000000..bce04b6c59 --- /dev/null +++ b/Task/100-doors/V-(Vlang)/100-doors-3.v @@ -0,0 +1,5 @@ +fn main() { + for i in 1..11 { + print ( " Door ${i*i} is open.\n" ) + } +} diff --git a/Task/100-prisoners/Ecstasy/100-prisoners.ecstasy b/Task/100-prisoners/Ecstasy/100-prisoners.ecstasy new file mode 100644 index 0000000000..9f66539ddd --- /dev/null +++ b/Task/100-prisoners/Ecstasy/100-prisoners.ecstasy @@ -0,0 +1,49 @@ +module OneHundredPrisoners { + @Inject Console console; + + void run() { + console.print($"# of executions: {attempts}"); + console.print($"Optimal play success rate: {simulate(tryOpt)}%"); + console.print($" Random play success rate: {simulate(tryRnd)}%"); + } + + Int attempts = 10000; + + Dec simulate(function Boolean(Int[]) allFoundNumber) { + Int[] drawers = new Int[100](i->i); + Int pardoned = 0; + for (Int i : 1..attempts) { + if (allFoundNumber(drawers.shuffled())) { + ++pardoned; + } + } + return (pardoned * 1000000 / attempts).toDec() / 10000; + } + + Boolean tryRnd(Int[] drawers) { + Inmates: for (Int inmate : 0..<100) { + Int[] choices = drawers.shuffled(); + for (Int attempt : 0..<50) { + if (drawers[choices[attempt]] == inmate) { + continue Inmates; + } + } + return False; + } + return True; + } + + Boolean tryOpt(Int[] drawers) { + Inmates: for (Int inmate : 0..<100) { + Int choice = inmate; + for (Int attempt : 0..<50) { + if (drawers[choice] == inmate) { + continue Inmates; + } + choice = drawers[choice]; + } + return False; + } + return True; + } +} diff --git a/Task/100-prisoners/True-BASIC/100-prisoners.basic b/Task/100-prisoners/True-BASIC/100-prisoners.basic new file mode 100644 index 0000000000..eacc0cac4a --- /dev/null +++ b/Task/100-prisoners/True-BASIC/100-prisoners.basic @@ -0,0 +1,40 @@ +FUNCTION trials(prisoners, iterations, optimal) + DIM drawers(100) + FOR i = 1 TO prisoners + LET drawers(i) = i + NEXT i + FOR i = 1 TO iterations + FOR k = 1 TO prisoners + LET x = RND+1 + LET p = drawers(x) + LET drawers(x) = drawers(k) + LET drawers(k) = p + NEXT k + FOR prisoner = 1 TO prisoners + LET found = false + IF optimal<>0 THEN LET drawer = prisoner ELSE LET drawer = RND+1 + FOR j = 1 TO prisoners/2 + LET drawer = drawers(drawer) + IF drawer = prisoner THEN + LET found = true + EXIT FOR + END IF + IF (NOT optimal<>0) THEN LET drawer = RND+1 + NEXT j + IF (NOT found<>0) THEN EXIT FOR + NEXT prisoner + LET pardoned = pardoned+found + NEXT i + LET trials = (100*pardoned/iterations) +END FUNCTION + +LET false = 0 +LET true = 1 +LET iterations = 10000 +PRINT "Simulation count: "; iterations +FOR prisoners = 10 TO 100 STEP 90 + LET randon = trials(prisoners,iterations,false) + LET optimal = trials(prisoners,iterations,true) + PRINT "Prisoners: "; prisoners; ", random: "; randon; ", optimal: "; optimal +NEXT prisoners +END diff --git a/Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas b/Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas new file mode 100644 index 0000000000..2d5275fb8f --- /dev/null +++ b/Task/15-puzzle-game/PascalABC.NET/15-puzzle-game.pas @@ -0,0 +1,178 @@ +// Игра в 15 PABCWork.NET\Samples\Games\15.pas +uses GraphABC,ABCObjects,ABCButtons; + +const +/// размер поля + n = 4; +/// размер фишки + sz = 100; +/// зазор между фишками + zz = 10; +/// отступ от левого и правого краев + x0 = 20; +/// отступ от верхнего и нижнего краев + y0 = 20; + +var + p: array [1..n,1..n] of SquareABC; + digits: array [1..n*n-1] of integer; + + MeshButton: ButtonABC; + StatusRect: RectangleABC; + + EmptyCellX,EmptyCellY: integer; + MovesCount: integer; + EndOfGame: boolean; // True если все фишки стоят на своих местах + +// Поменять местами две фишки +procedure Swap(var p,p1: SquareABC); +begin + PABCSystem.Swap(p,p1); + var i := p.Left; + p.Left := p1.Left; + p1.Left := i; + i := p.Top; + p.Top := p1.Top; + p1.Top := i; +end; + +// Определить, являются ли клетки соседями +function Neighbours(x1,y1,x2,y2: integer): boolean; +begin + Result := (Abs(x1-x2)=1) and (y1=y2) or (Abs(y1-y2)=1) and (x1=x2) +end; + +// Заполнить вспомогательный массив цифр +procedure FillDigitsArr; +begin + for var i:=1 to n*n-1 do + digits[i] := i; +end; + +// Перемешать вспомогательный массив цифр. Количество обменов должно быть четным +procedure MixDigitsArr; +var x: integer; +begin + for var i:=1 to n*n-1 do + begin + repeat + x := Random(15)+1; + until x<>i; + Swap(digits[i],digits[x]); + end; + if n mod 2=0 then + Swap(digits[1],digits[2]); // количество обменов должно быть четным +end; + +// Заполнить двумерный массив фишек. Вместо пустой ячейки - белая фишка с числом 0 +procedure Fill15ByDigitsArr; +begin + Swap(p[EmptyCellY,EmptyCellX],p[n,n]); // Переместить пустую фишку в правый нижний угол + EmptyCellX := n; + EmptyCellY := n; + var i := 1; + for var y:=1 to n do + for var x:=1 to n do + begin + if x*y=n*n then exit; + p[y,x].Number := digits[i]; + i += 1; + end; +end; + +// Перемешать массив фишек +procedure Mix15; +begin + MixDigitsArr; + Fill15ByDigitsArr; + MovesCount := 0; + EndOfGame := False; + StatusRect.Text := 'Количество ходов: '+IntToStr(MovesCount); + StatusRect.Color := RGB(200,200,255); +end; + +// Создать массив фишек +procedure Create15; +begin + EmptyCellX := n; + EmptyCellY := n; + for var x:=1 to n do + for var y:=1 to n do + begin + p[y,x] := new SquareABC(x0+(x-1)*(sz+zz),y0+(y-1)*(sz+zz),sz,clMoneyGreen); + p[y,x].BorderColor := clGreen; + p[y,x].BorderWidth := 2; + p[y,x].TextScale := 0.7; + end; + p[EmptyCellY,EmptyCellX].Color := clWhite; + p[EmptyCellY,EmptyCellX].BorderColor := clWhite; + FillDigitsArr; + MixDigitsArr; + Fill15ByDigitsArr; +end; + +// Проверить, все ли фишки стоят на своих местах +function IsSolution: boolean; +begin + Result:=True; + var i:=1; + for var y:=1 to n do + for var x:=1 to n do + begin + if p[y,x].Number<>i then + begin + Result:=False; + break; + end; + i += 1; + if i=n*n then i:=0; + end; +end; + +procedure MouseDown(x,y,mb: integer); +begin + if EndOfGame then // Если все фишки на своих местах, то не реагировать на мышь и ждать нажатия кнопки "Перемешать" + exit; + if ObjectUnderPoint(x,y)=nil then // Eсли мы щелкнули не на объекте, то не реагировать на мышь + exit; + var fx := (x-x0) div (sz+zz) + 1; // Вычислить координаты на доске для ячейки, на которой мы щелкнули мышью + var fy := (y-y0) div (sz+zz) + 1; + if (fx>n) or (fy>n) then + exit; + if Neighbours(fx,fy,EmptyCellX,EmptyCellY) then // Если ячейка соседствует с пустой, то поменять их местами + begin + Swap(p[EmptyCellY,EmptyCellX],p[fy,fx]); + EmptyCellX := fx; + EmptyCellY := fy; + Inc(MovesCount); + StatusRect.Text := 'Количество ходов: ' + MovesCount; + if IsSolution then + begin + StatusRect.Text := 'Победа! Сделано ходов: ' + MovesCount; + StatusRect.Color := RGB(255,200,200); + EndOfGame := True; + end + end; +end; + +begin + SetSmoothingOff; + Window.Title := 'Игра в 15'; + Window.IsFixedSize := True; + SetWindowSize(2*x0+(sz+zz)*n-zz,2*y0+(sz+zz)*n-zz+90); + + EndOfGame := False; + Create15; + + MeshButton := ButtonABC.Create((WindowWidth-200) div 2,2*y0+(sz+zz)*n-zz,200,'Перемешать',clLightGray); + MeshButton.OnClick := Mix15; + StatusRect := new RectangleABC(0,WindowHeight-40,WindowWidth,40,RGB(200,200,255)); + StatusRect.TextVisible := True; + StatusRect.Text := 'Количество ходов: '+IntToStr(MovesCount); + StatusRect.BorderWidth := 2; + StatusRect.BorderColor := RGB(80,80,255); + + MovesCount := 0; + + OnMouseDown := MouseDown; +end. diff --git a/Task/15-puzzle-game/Zig/15-puzzle-game.zig b/Task/15-puzzle-game/Zig/15-puzzle-game.zig new file mode 100644 index 0000000000..11d3ca114f --- /dev/null +++ b/Task/15-puzzle-game/Zig/15-puzzle-game.zig @@ -0,0 +1,91 @@ +const std = @import("std"); +const stdout = std.io.getStdOut().writer(); + +const tokens = [16][]const u8{ " 1", " 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", "10", "11", "12", "13", "14", "15", " " }; + +const empty_token = 15; +var empty: u8 = empty_token; +var cells: [16]u8 = undefined; +var invalid: bool = false; + +const Move = enum { no, up, down, left, right }; + +fn showBoard() !void { + try stdout.writeAll("\n"); + + var solved = true; + var i: u8 = 0; + while (i < 16) : (i += 1) { + try stdout.print(" {s} ", .{tokens[cells[i]]}); + if ((i + 1) % 4 == 0) try stdout.writeAll("\n"); + if (i != cells[i]) solved = false; + } + + try stdout.writeAll("\n"); + + if (solved) { + try stdout.writeAll("\n\n** You did it! **\n\n"); + std.posix.exit(0); + } +} + +fn updateToken(move: Move) !void { + const newEmpty = switch (move) { + Move.up => if (empty / 4 < 3) empty + 4 else empty, + Move.down => if (empty / 4 > 0) empty - 4 else empty, + Move.left => if (empty % 4 < 3) empty + 1 else empty, + Move.right => if (empty % 4 > 0) empty - 1 else empty, + else => empty, + }; + + if (empty == newEmpty) { + invalid = true; + } else { + invalid = false; + cells[empty] = cells[newEmpty]; + cells[newEmpty] = empty_token; + empty = newEmpty; + } +} + +fn waitForMove() !Move { + const reader = std.io.getStdIn().reader(); + if (invalid) try stdout.writeAll("(invalid) "); + try stdout.writeAll("enter u/d/l/r or q: "); + const input = try reader.readBytesNoEof(2); + switch (std.ascii.toLower(input[0])) { + 'q' => std.posix.exit(0), + 'u' => return Move.up, + 'd' => return Move.down, + 'l' => return Move.left, + 'r' => return Move.right, + else => return Move.no, + } +} + +fn shuffle(moves: u8) !void { + var random = std.rand.DefaultPrng.init(@intCast(std.time.microTimestamp())); + const rand = random.random(); + var n: u8 = 0; + while (n < moves) { + const move: Move = rand.enumValue(Move); + try updateToken(move); + if (!invalid) n += 1; + } + invalid = false; +} + +pub fn main() !void { + var n: u8 = 0; + while (n < 16) : (n += 1) { + cells[n] = n; + } + + try shuffle(50); + try showBoard(); + + while (true) { + try updateToken(try waitForMove()); + try showBoard(); + } +} diff --git a/Task/15-puzzle-solver/Dart/15-puzzle-solver.dart b/Task/15-puzzle-solver/Dart/15-puzzle-solver.dart new file mode 100644 index 0000000000..27546c8101 --- /dev/null +++ b/Task/15-puzzle-solver/Dart/15-puzzle-solver.dart @@ -0,0 +1,78 @@ +import 'package:collection/collection.dart'; + +typedef OffsetFunction = int Function(int a, int b); +Function eq = const ListEquality().equals; + +/// Solve Random 15 Puzzles +class FifteenSolver { + static const target = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0]; + static const trN = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]; + static const tcN = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]; + var pos0 = List.filled(100, 0); + var moves = List.filled(100, 0); + var dirs = List.filled(100, ''); + int step = 0, best = 0; + var board = List.generate(100, (int i) => List.filled(16, 0)); + + bool isFinished() { + if (moves[step] < best) return nextMove(); + if (eq(board[step], target)) { + print("Solution found in $step moves :${dirs.join('')}"); + return true; + } + return (moves[step] == best) ? nextMove() : false; + } + + var passNumber = 0; + + /// Try all valid moves from here, but don't retrace your steps. + /// Return true if a solution is found. + bool nextMove() { + // if (passNumber++ ~/ 100000 == 0) print("${dirs.join('')}"); + return (dirs[step] != 'u' && pos0[step] ~/ 4 < 3 && down()) || + (dirs[step] != 'd' && pos0[step] ~/ 4 > 0 && up()) || + (dirs[step] != 'l' && pos0[step] % 4 < 3 && right()) || + (dirs[step] != 'r' && pos0[step] % 4 > 0 && left()) || + false; + } + + bool move(int offset, String dir, List rcArray, OffsetFunction rcFunc) { + final int ix = pos0[step] + offset; + final n = board[step][ix]; + pos0[step + 1] = pos0[step] + offset; + board[step + 1] = board[step].toList() + ..[pos0[step]] = n + ..[ix] = 0; + dirs[step + 1] = dir; + moves[step + 1] = moves[step] + rcFunc(rcArray[n], pos0[step]); + step++; + if (isFinished()) return true; + step--; + return false; + } + + bool right() => move(1, 'r', tcN, (a, b) => (a <= b % 4 ? 0 : 1)); + bool left() => move(-1, 'l', tcN, (a, b) => (a >= b % 4 ? 0 : 1)); + bool down() => move(4, 'd', trN, (a, b) => (a <= b ~/ 4 ? 0 : 1)); + bool up() => move(-4, 'u', trN, (a, b) => (a >= b ~/ 4 ? 0 : 1)); + + void solve(List initBoard) { + pos0[0] = initBoard.indexOf(0); + board[0] = initBoard; + while (!isFinished()) best++; + } +} + +void main(List args) { + print("running"); + // test values + // final start = [5, 1, 2, 3, 6, 10, 7, 4, 13, 9, 11, 8, 14, 0, 15, 12]; + // final start = [9, 1, 2, 4, 13, 6, 5, 7, 3, 11, 14, 15, 10, 0, 8, 12]; + // final start = [10, 3, 1, 4, 13, 5, 8, 7, 9, 6, 0, 11, 14, 15, 12, 2]; + // required solution + final start = [15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2]; + // Extra credit + // final start = [0, 12, 9, 13, 15, 11, 10, 14, 3, 7, 2, 5, 4, 8, 6, 1]; + print(start); + FifteenSolver().solve(start); +} diff --git a/Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua b/Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua new file mode 100644 index 0000000000..b557fe56b6 --- /dev/null +++ b/Task/15-puzzle-solver/Uiua/15-puzzle-solver.uiua @@ -0,0 +1,47 @@ +# Solve a 15 puzzle https://rosettacode.org/wiki/15_puzzle_solver#Uiua +# Experimental! +T ← ↯4_4 ↻1⇡16 +# Return shuffled copy of the input. +Shuffle ← ⊏⊸(⍏[⍥⚂]⧻) +# Positions of the numbers (not 0) +Pos ← ≡(⊢⊚⌕)↘1⇡16¤ + +# Applying a very gentle weighting to certain cells massively +# speeds up the algorithm +Weights ← [[2 1 1 2] [2 1 1 2] [2 1 1 2] [2 1 1 1]] +Distance ← /+×⊡:Weights:≡/+⌵-⊙.∩Pos +Heuristic ← Distance T + +# Four possible neighbours +Nfour ← [[1 0] [¯1 0] [0 1] [0 ¯1]] +# Actual neighbours at a point. +ValidN ← ≡(⊂)⊙¤:⟜(▽⊸(≥0≡/↧)▽⊸(<4≡/↥)+Nfour)¤ +# Precalculate them. +ValidNs ← ⊞(□ ValidN⊟)⇡4 ⇡4 + +# Get the valid (from to) moves from this cell. +Moves ← °□⊡:ValidNs⊢⊚⌕0 +# Swap the values at the indexes [0 1] [a b 2 3] -> [b a 2 3] +Swap ← ⍜(⊡|∘◌) ⊃(⇌⊙∘|⊡) +# List the possible next positions for a position +Next ← ⊙◌≡(Swap ⊙.)⊙¤⊸Moves +Solve ← ( + &p"Running..."&p. + ⍜nowastar(Next|Heuristic|≍T) + &p$"_ seconds" + # Track the movement of the 0 between adjacent steps. + ≡(/-)◫2◇≡(⊢⊚⌕0)⇌⊢ + # Map each to a direction string and join. + /⊂⇌≡⍣("d" °¯1_0|"u" °1_0|"r" °0_¯1|"l" °0_1|∘) +) + +# Uncomment one of the following lines to try random grids +# ⍥(Swap⊡⊸(⌊×⚂⧻)⊸Moves)90 T +# [[2 14 6 4] [5 1 3 8] [9 10 7 11] [13 0 15 12]] # Simple 40 shuffles +# [[5 1 2 3] [6 10 7 4] [13 9 11 8] [14 0 15 12]] # Simple 12 steps +# [[9 1 2 4] [13 6 5 7] [3 11 14 15] [10 0 8 12]] # 34 steps +# [[10 3 1 4] [13 5 8 7] [9 6 0 11] [14 15 12 2]] # 38 steps (a few seconds) +[[15 14 1 6] [9 11 4 12] [0 10 7 3] [13 8 5 2]] # Main Challenge +# [[0 12 9 13] [15 11 10 14] [3 7 2 5] [4 8 6 1]] # Extra Credit + +Solve diff --git a/Task/2048/Jq/2048.jq b/Task/2048/Jq/2048.jq new file mode 100644 index 0000000000..367500faf2 --- /dev/null +++ b/Task/2048/Jq/2048.jq @@ -0,0 +1,127 @@ +include "MRG32k3a" {search: "."}; # see comment above + +### Generic functions + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +# Create an m x n matrix with initial values specified by . +def matrix($m; $n): + if $m == 0 then [] + else . as $init + | if $m == 1 then [range(0;$n) | $init] + elif $m > 0 then + matrix(1; $n) as $row + | [range(0; $m) | $row ] + else error("matrix\($m);\($n)) invalid") + end + end; + + +### The 2048 Game +# Left-squish the input array in accordance with the game requirements for a single row +def squish: + def squish($n): + def s: + if length == 0 then [range(0;$n)|null] + elif .[0] == null then .[1:] | s + elif length == 1 then . + [range(0; $n - 1)|null] + elif .[0] == .[1] then [.[0] + .[1]] + (.[2:]|squish($n-1)) + else .[0:1] + (.[1:]|squish($n-1)) + end; + s; + squish(length); + +# Input: a matrix of rows +def squish_left: + [.[] | squish]; + +def squish_right: + [.[] | reverse | squish | reverse]; + +def squish_up: + transpose + | [.[] | squish] + | transpose; + +def squish_down: + transpose + | [.[] | reverse | squish | reverse] + | transpose; + +# Gather the [i,j] co-ordinates of all the null values in the input matrix +def gather: + if length == 0 then error end + | (.[0] | length) as $cols + | [range(0;length) as $i + | range(0; $cols) as $j + | select(.[$i][$j] == null) | [$i,$j]] + | if length == 0 then error end ; + +# Input: {matrix} +# Add a random 2 or 4 if possible, else error +# Output: includes .prng for the PRN generator +def add_random: + (.matrix | gather) as $gather + | ($gather | length) as $n + | if $n == 0 then error end + | if .prng == null then .prng = seed(now | tostring | sub("^.*[.]";"") | tonumber) end + | .prng |= nextFloat + | $gather[.prng.nextFloat * $n | trunc] as [$i,$j] + | .prng |= nextFloat + | (if (.prng.nextFloat) < 0.1 then 4 else 2 end) as $exmachina + | .matrix[$i][$j] = $exmachina ; + +def prompt: "[ijkl] or [wasd] or q to quit or n to restart:"; + +def direction: + {"i": "up", "j": "left", "k": "down", "l": "right", + "w": "up", "a": "left", "s": "down", "d": "right", + "q": "quit", + "n": "restart" + }; + +# Recognize $goal as the goal +def play($goal): + + # Pretty print + def pp: + .matrix[] | map(. // "." | lpad(4)) | join(" "); + + def won: + any(.matrix[][]; . == $goal); + + def lost: + .matrix + | (squish_left == .) and (squish_right == .) and + (squish_up == .) and (squish_down == .); + + def round: + pp, + if lost then "Sorry! Better luck next time.", play($goal) + else prompt, + ( (try input catch halt) as $in + | .matrix as $matrix # for checking if a move is legal + | .emit = null + | direction[$in | ascii_downcase] as $direction + | if $direction == "up" then .matrix |= squish_up + elif $direction == "down" then .matrix |= squish_down + elif $direction == "left" then .matrix |= squish_left + elif $direction == "right" then .matrix |= squish_right + elif $direction == "quit" then .emit = "bye" + elif $direction == "restart" then .emit = "restart" + else .emit = "unknown direction \($direction) ... please try again." + end + | if .emit == "bye" then .emit, halt + elif .emit == "restart" then "Restarting...", play($goal) + elif .emit != null then .emit, round + elif .matrix == $matrix then "Disallowed direction! Please try again.", round + elif won then pp, "Congratulations!", play($goal) + else add_random | round + end) + end; + + { matrix: (null | matrix(4;4))} + | .matrix[2] = [null,2,2,2] + | round; + +play(2048) diff --git a/Task/2048/Wren/2048.wren b/Task/2048/Wren/2048.wren index ddff0c113d..b92bc4948d 100644 --- a/Task/2048/Wren/2048.wren +++ b/Task/2048/Wren/2048.wren @@ -20,13 +20,6 @@ class G2048 { for (j in 0..3) _board[i][j] = Tile.new(0, false) } _rand = Random.new() - initializeBoard() - } - - initializeBoard() { - for (y in 0..3) { - for (x in 0..3) _board[x][y] = Tile.new(0, false) - } } loop() { diff --git a/Task/24-game/Frink/24-game.frink b/Task/24-game/Frink/24-game.frink new file mode 100644 index 0000000000..a7a123bc86 --- /dev/null +++ b/Task/24-game/Frink/24-game.frink @@ -0,0 +1,15 @@ +ops = ["+", "-", "*", "/"] + +chosen = new array[[4], {|x| random[1,9]}] +println[chosen] + +for d = chosen.lexicographicPermute[] + multifor o = [ops, ops, ops] + { + str = "((" + d@0 + o@0 + d@1 + ")" + o@1 + d@2 + ")" + o@2 + d@3 + if eval[str] == 24 + println[str] + str = "(" + d@0 + o@0 + d@1 + ")" + o@1 + "(" + d@2 + + o@2 + d@3 + ")" + if eval[str] == 24 + println[str] + } diff --git a/Task/24-game/FutureBasic/24-game.basic b/Task/24-game/FutureBasic/24-game.basic new file mode 100644 index 0000000000..68da1c6faa --- /dev/null +++ b/Task/24-game/FutureBasic/24-game.basic @@ -0,0 +1,310 @@ +include resources "24 Game Icon.icns" + +#build CompilerOptions @"-Wno-unused-variable" + +_mEdit = 2 +editmenu _mEdit + +begin globals +long gPosition +end globals + +void local fn EraseErrorText + + CGRect r + r = fn CGRectMake(10, 200, 400, 15) + rect fill r,fn ColorBlack + +end fn + +local fn ArcRandom( a as long, b as long ) as long + long i + cln i = (arc4random()%(b-a+1))+a; +end fn = fn floor(i) + +local fn GetRandomNumbers as CFStringRef + + // 96 number groups + + CFArrayRef combos = @[¬ + + // The first 32 are easy + @"1 2 3 4", @"2 4 6 8", @"1 2 4 8", @"1 3 4 6", @"1 2 6 8", + @"2 3 4 8", @"1 3 6 9", @"1 2 7 8", @"2 3 6 8", @"1 4 6 8", + @"2 2 3 9", @"3 4 6 6", @"2 3 3 8", @"1 5 6 6", @"2 4 4 6", + @"1 3 8 8", @"2 2 6 9", @"3 3 6 9", @"1 2 5 9", @"2 4 5 5", + @"1 3 5 9", @"2 2 4 9", @"1 2 3 6", @"1 2 2 9", @"1 2 3 9", + @"1 2 4 6", @"1 2 4 4", @"1 2 2 6", @"1 3 3 6", @"1 1 4 6", + @"1 1 2 8", @"1 1 3 8", + // The middle 32 are medium + @"1 5 5 9", @"4 4 6 9", @"2 3 7 9",@"3 5 8 8", @"1 6 6 8", + @"3 3 5 6", @"1 4 5 8", @"3 3 6 7",@"2 5 5 8", @"4 4 7 9", + @"1 5 6 9", @"3 3 8 9", @"2 6 6 7",@"4 5 7 8", @"2 2 5 9", + @"2 4 6 7", @"1 5 6 8", @"3 4 7 7",@"2 5 6 6", @"3 4 5 9", + @"1 6 7 9", @"2 3 7 8", @"1 4 6 9",@"2 3 5 9", @"3 4 4 8", + @"2 5 8 9", @"1 4 8 9", @"3 3 4 9",@"2 6 7 9", @"1 3 5 7", + @"1 3 6 6", @"2 2 5 7", + // The last 32 are hard + @"1 5 7 9",@"3 4 7 9", @"2 5 7 8", @"3 4 8 9", @"3 4 5 8", + @"2 6 6 9",@"4 4 5 7", @"2 4 6 9", @"1 4 7 7", @"2 3 8 9", + @"2 3 4 7",@"3 3 4 8", @"1 3 7 9", @"2 4 5 9", @"1 3 6 8", + @"2 4 4 9",@"1 5 8 9", @"3 3 5 9", @"2 6 8 9", @"1 4 4 7", + @"2 3 6 7",@"1 3 5 8", @"2 4 7 8", @"1 3 4 7", @"2 3 5 6", + @"1 4 5 6",@"3 3 5 7", @"2 2 3 6", @"3 3 7 7", @"3 3 7 9", + @"4 4 8 9",@"2 4 8 9"] + + long i = fn ArcRandom( 0, len(combos) - 1 ) + gPosition = i + +end fn = combos[i] + + +local fn EvaluateMath( equation as CFStringRef ) as CFStringRef + equation = fn StringByReplacingOccurrencesOfString( lcase(equation), @"x", @"*" ) + + CFStringRef result = NULL + RegularExpressionRef regex = fn RegularExpressionWithPattern( @"[0-9.]+", NSRegularExpressionCaseInsensitive, NULL ) + CFArrayRef matches = fn RegularExpressionMatches( regex, equation, 0, fn CFRangeMake( 0, len(equation) ) ) + NSInteger intConversions = 0 + TextCheckingResultRef match + CFRange originalRange + CFRange adjustedRange + CFStringRef value + + for match in matches + originalRange = fn TextCheckingResultRange( match ) + adjustedRange = fn CFRangeMake( ( originalRange.location + ( intConversions * len( @".0") ) ), originalRange.length ) + value = fn StringSubstringWithRange( equation, adjustedRange ) + if fn StringContainsString( value, @"." ) + continue + else + equation = fn StringByReplacingCharactersInRange( equation, adjustedRange, fn StringWithFormat( @"%@.0", value ) ) + intConversions++ + end if + next + ExceptionRef e + try + ExpressionRef expression = fn ExpressionWithFormat( equation ) + CFNumberRef number = fn ExpressionValueWithObject( expression, NULL, NULL ) + result = fn StringWithFormat( @"%.3f", dblval( number ) ) + end try + + catch (e) + result = fn StringWithFormat( @"%@", e ) : exit fn + end catch + // Test if result is an integer and, if so, return result as an integer + if( fn StringDoubleValue( result ) == fn floorf( fn StringDoubleValue( result ) ) ) + result = fn ArrayFirstObject( fn StringComponentsSeparatedByString( result, @"." ) ) + end if +end fn = result + + +local fn QuitOrPlayAlert(GameResult as CFStringRef) + alert -2,,GameResult,@"You won!",@"Quit;Play Again" + AlertButtonSetKeyEquivalent( 2, 2, @"\e" ) + short result + result = alert 2 + if ( result != NSAlertSecondButtonReturn ) then appterminate +end fn + + +local fn BuildWindow + CGRect r = fn CGRectMake( 0, 0, 580, 250) + window 1, @"24 Game", r + windowcenter(1) + WindowSetBackgroundColor(1,fn ColorBlack) + +end fn + +///////// Start ////////// + +fn BuildWindow + + +short d(4), i +CFStringRef CheckForDuplicates(97) +for i = 1 to 96 + CheckForDuplicates(i) = @"" +next i + +short DuplicatesCounter +DuplicatesCounter = 0 + + +"Main" + +cls +text ,,fn colorWhite + +print +print %(10,15),"Given four numbers and using just the +, -, *, and / operators; and the" +print %(10,30),"possible use of parenthesis (), enter an expression that equates to 24." +print %(10,45),"You must use all your numbers and only those numbers." +print %(10,60),"Examples: 9618 Solution 9 + 6 + 1 + 8 or 3173 Solution (3 * 7) - (1 - 4)" +print +print %(10,85),"Enter Q to quit or S to skip to the next number." + +"GetFourNumbers" + +CFArrayRef randomNumbers : randomNumbers= fn StringComponentsSeparatedByString( fn GetRandomNumbers, @" " ) +CFStringRef RandomNumberblock : RandomNumberblock = @"" +CFStringRef RandomNumberblockAdd : RandomNumberblockAdd = @"" + +for i = 0 to 3 + // create a string from the 4 numbers + RandomNumberblockAdd = randomNumbers[i] + RandomNumberblock = fn StringByAppendingString(RandomNumberblock,RandomNumberblockAdd) + RandomNumberblock = fn StringByAppendingString(RandomNumberblock,@" ") +next i + + +if DuplicatesCounter = > 96 + // reset counter when last number is retrieved and start from the first number block + DuplicatesCounter = 0 + for i = 1 to 96 + CheckForDuplicates(i) = @"" + next i +end if + +for i = 1 to 96 + // check the current numbers with the numbers already used + if fn StringIsEqual(RandomNumberblock,CheckForDuplicates(i)) + RandomNumberblock = fn StringWithString(CheckForDuplicates(DuplicatesCounter)) + goto "GetFourNumbers" + end if +next i + +DuplicatesCounter ++ +CheckForDuplicates(DuplicatesCounter) = fn StringWithString(RandomNumberblock) + +d(1) = fn StringIntegerValue( randomNumbers[0] ) +d(2) = fn StringIntegerValue( randomNumbers[1] ) +d(3) = fn StringIntegerValue( randomNumbers[2] ) +d(4) = fn StringIntegerValue( randomNumbers[3] ) + +short dots = 0 + +//d(1) = 9:d(2) = 6:d(3) = 1:d(4) = 8 // Uncomment to test with 9618 numbers. Solution 9 + 6 + 1 + 8 +//d(1) = 6:d(2) = 5:d(3) = 3:d(4) = 8 // Uncomment to test with 6538 numbers. Solution 6 / ( 5 - 3 ) * 8 +//d(1) = 3:d(2) = 1:d(3) = 7:d(4) = 3 // Uncomment to test with 3773 numbers. Solution ((3 * 1) * 7) + 3 +//d(1) = 4:d(2) = 2:d(3) = 7:d(4) = 1 // Uncomment to test with 4271 numbers. Solution (4 * ( 7 - 2 + 1 ) +// NOTE: When using these test numbers, also uncomment dots = 0 below here to prevent misleading dot displays + + +if gPosition <= 32 then dots = 1 +if gPosition > 32 and gPosition < 65 then dots = 2 +if gPosition > 64 then dots = 3 + +//dots = 0 uncomment when testing the numbers above to prevent misleading dot displays + +print +text ,,fn colorGreen +print %(15,110),"These are your numbers, difficulty level "; +// @"\U000026AA" is white unicode dot - Easy difficulty (One-Dot) +// @"\U0001F534" is red unicode dot - Medium difficulty (Two-Dots) +// @"\U0001F7E1" is yellow unicode dot - Hard difficulty (Three-Dots) + +if dots = 1 then print @"\U000026AA Easy" +if dots = 2 then print @"\U0001F534 \U0001F534 Medium" +if dots = 3 then print @"\U0001F7E1 \U0001F7E1 \U0001F7E1 Hard" + +print %(55,125) +text ,18,fn colorGreen +for i = 1 to 4 + print d(i); " "; +next + +print + +text ,12,fn colorWhite +printf @"\n\n\n" + +CFStringRef expr +bool TryAgain : TryAgain = _false +CFStringRef MessageText +CFStringRef UserInput = NULL + +"InputExpression" + +if TryAgain + MessageText = fn StringWithFormat( @"Enter math expression: [ '%@' was incorrect ]", expr ) + UserInput = input %(10, 190), MessageText, @"123456789+-*/()qs", YES,, 0 +else + UserInput = input %(10, 190), @"Enter math expression:", @"123456789+-*/()qs", YES,, 0 +end if + +if ( UserInput == NULL ) then "InputExpression" +expr = UserInput +if expr = @"" then "InputExpression" +if fn StringIsEqual(ucase(expr) , @"Q") then appterminate +if fn StringIsEqual(ucase(expr) , @"S") then "Main" + + +//check expr for validity + +short j +bool GotAllNumbers : GotAllNumbers = _false +short ThisNumberPosition : ThisNumberPosition = 0 +short GotaNumber : GotaNumber = 0 +short TotalNumbers : TotalNumbers = 0 + +short ExtraNumbers:ExtraNumbers = 0 + +for i = 1 to len$(fn stringpascalstring(expr)) + if asc(mid$(fn stringpascalstring(expr),i,1)) > 48 && asc(mid$(fn stringpascalstring(expr),i,1)) < 58 + ExtraNumbers ++ + end if +next i + +if ExtraNumbers > 4 + fn EraseErrorText + text ,,fn colorRed + TryAgain = _true + print %(10,200);"Error! Extra numbers not allowed": goto "InputExpression" + text ,,fn colorWhite +end if + + +for i = 1 to 4 + GotaNumber = 0 + for j = 0 to len(expr) -1 + ThisNumberPosition = instr( j, expr, right(str( d(i)),1 )) + ThisNumberPosition ++ + if ThisNumberPosition then GotaNumber = _true + next j + if GotaNumber then TotalNumbers ++ +next i + +if TotalNumbers => 4 then GotAllNumbers = _true + +if GotAllNumbers = _false + fn EraseErrorText + text ,,fn colorRed + TryAgain = _true + print %(10,200);"ERROR! Must use all your numbers and only those numbers." : goto "InputExpression" + text ,,fn colorWhite +end if + +fn EraseErrorText + + +if fn EvaluateMath( expr ) = _false + text ,,fn colorRed + TryAgain = _true + Print %(10,200);"Error! Incorrect math sequence." + goto "InputExpression" + text ,,fn colorWhite +end if + +CFStringRef GameResult +if fn StringIntegerValue( fn EvaluateMath( expr ) ) == 24 then GameResult = @"Correct" else GameResult = @"Incorrect" + +if GameResult = @"Incorrect" + TryAgain = _true + goto "InputExpression" +end if + +fn QuitOrPlayAlert(GameResult) +goto "Main" + +handleevents diff --git a/Task/24-game/Jq/24-game.jq b/Task/24-game/Jq/24-game.jq new file mode 100644 index 0000000000..09ce6dfc30 --- /dev/null +++ b/Task/24-game/Jq/24-game.jq @@ -0,0 +1,90 @@ +### The MRG32k3a combined recursive PRNG - see above +import "MRG32k3a" as MRG {search: "."}; + +### Generic utilities +def sum(stream): reduce stream as $x (0; .+$x); + +# like while/2 but emit the final term rather than the first one +def whilst(cond; update): + def _whilst: + if cond then update | (., _whilst) else empty end; + _whilst; + +### Reverse Polish Notation +# An array of the allowed operators +def operators: "+-*/" | split(""); + +# If $a and $b are numbers and $c an operator, then "$a $b $c" is evaluated as an RPN expression. +# Output: {emit, result} with .emit == null if there is a valid result. +def applyOperator($a; $b; $c): + if ([$a,$b] | map(type) | unique) == ["number"] + then + if $c == "+" then {result: ($a + $b)} + elif $c == "-" then {result: ($a - $b)} + elif $c == "*" then {result: ($a * $b)} + elif ($c == "/") then {result: ($b / $a)} + else {emit: "unrecognized operator: \($c)"} + end + else {emit: "invalid number"} + end; + +# Input: an array representing an RPN expression. +# Output: {emit, result} as per applyOperator/3 +# Example: [1,2,3,"+","+"] | evaluate #=> 6 +def evaluate: + if length == 1 + then if .[0]|type == "number" then {result: .[0]} + else {emit: "invalid RPN expression"} + end + elif length < 3 then {emit: "invalid RPN expression: \(. | join(" "))"} + else . as $in + | (first( range(0; length) as $i | select(any( operators[]; . == $in[$i]) ) | $i) // null) as $ix + | if $ix == null then {emit: "invalid RPN expression"} + else applyOperator(.[$ix-2]; .[$ix-1]; .[$ix]) as $result + | if $result.result then .[:$ix-2] + [$result.result] + .[$ix+1:] | evaluate + else $result + end + end + end; + +### The "24 Game" + +# . is the putative RPN string to be checked. +# $four is the string of the four expected digits, in order. +# Output: {emit, result} with .emit set to "Correct!" if .result == 24 +def check($four): + if (gsub("[^1-9]";"") | explode | sort | implode) != $four + then {emit: "You must use each of the four digits \($four | split("") | join(" ")) exactly once:"} + else . as $in + | {s: [], emit: null} + | [$in | split("")[] | select(. != " ") + | . as $in | explode[0] | if . >= 48 and . <= 57 then . - 48 else $in end] + | evaluate + | if .result + then if .result|round == 24 then .emit = "Correct!" + else .emit = "Value \(.result) is not 24." + end + else .emit += "\nTry again, or enter . to start again, or q to quit." + end + end ; + +def run: + # Populate .digits with four non-negative digits selected at random, with replacement: + {digits: (9 | MRG::prn(4) | map(. + 1))} + | (.digits | sort | join("")) as $four + | "At the prompt, enter an RPN string (e.g. 64*1+1-), or . for a new set of four digits, or q to quit.", + "Make 24 using these digits, once each, in any order: \(.digits):", + ( whilst( .stop | not; + .emit = null + | . as $state + | try input catch halt + | if IN( "q", "quit") then halt + elif . == "." then $state | .stop = true + else check($four) + | if .result then .stop = true end + end ) + | select(.emit).emit ), + # rerun + run; + +run diff --git a/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle.v b/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-1.v similarity index 100% rename from Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle.v rename to Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-1.v diff --git a/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v b/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v new file mode 100644 index 0000000000..f44447a8e6 --- /dev/null +++ b/Task/4-rings-or-4-squares-puzzle/V-(Vlang)/4-rings-or-4-squares-puzzle-2.v @@ -0,0 +1,38 @@ +import math.bits + +fn main ( ) { + mut n := 0 + mut t := []u8{len:7} + + n = solve ( 0, mut t, 1, 7, true ) + println ( "$n unique solutions in 1 to 7" ) + n = solve ( 0, mut t, 3, 9, true ) + println("$n unique solutions in 3 to 9") + n = solve ( 0, mut t, 0, 9, false ) + println("$n non-unique solutions in 0 to 9") +} + +fn solve ( lvl u8, mut t []u8, low u8, high u8,unique bool ) int { + if lvl==7 { + return int(suma(t) && (!unique || isunique( t ))) + } + mut cnt:=0 + for v := low; v <= high; v++ { + t[lvl] = v + cnt += solve ( lvl + 1, mut t, low, high, unique ) + } + return cnt +} + +@[inline] +fn isunique ( t []u8 ) bool { + return bits.ones_count_32(u32(1)<4} {d}\n", .{ num, r.getLast() }); + } +} diff --git a/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig b/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig new file mode 100644 index 0000000000..3b8f04f057 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Zig/9-billion-names-of-god-the-integer-2.zig @@ -0,0 +1,35 @@ +const std = @import("std"); +const print = std.debug.print; +const bigint = std.math.big.int.Managed; +const eql = std.mem.eql; +const Array = std.ArrayList; +const Array1 = Array(bigint); +var gpa = std.heap.GeneralPurposeAllocator(.{}){}; +const allocator = gpa.allocator(); + +fn calc ( n:usize, p:*Array1) !void { + for ( 1..n+1 ) |k| { + var d:i64 = @intCast(n); + d -= @intCast(k*(3*k - 1)/2); + inline for ( 0..2 ) |_| { + if ( d < 0 ) return; + if (k&1>0) try p.items[n].add ( &p.items[n], &p.items[@intCast(d)] ) + else try p.items[n].sub ( &p.items[n], &p.items[@intCast(d)] ); + d -= @intCast(k); + } + } +} + +fn main() !void { + const s = [_]usize{ 23, 123, 1234, 12345, 123456 }; + var p = Array1.init ( allocator ); + try p.append ( try bigint.initSet ( allocator, 1 ) ); + var i:usize=1; + for ( s )|m|{ + while (i<=m):(i+=1){ + try p.append( try bigint.init(allocator) ); + try calc( i, &p ); + } + print("P({d}) = {d}\n", .{m,p.items[m]} ); + } +} diff --git a/Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th new file mode 100644 index 0000000000..f07c88a955 --- /dev/null +++ b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-1.8th @@ -0,0 +1,26 @@ +\ 99 bottles of beer on the wall: +[ + "no more bottles" , + "one bottle" , + ( dup . " bottles" ) +] var, bottles + +: .bottles + dup 2 n:min bottles @ caseof ; + +: .beer + .bottles . " of beer" . ; + +: .wall + .beer " on the wall" . ; + +: .take + " Take one down and pass it around" . ; + +: beers + .wall ", " . .beer '; putc cr + n:1- 0 max .take ", " . + .wall '. putc cr drop ; + +' beers 1 99 loop- +bye diff --git a/Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th new file mode 100644 index 0000000000..f736dda979 --- /dev/null +++ b/Task/99-bottles-of-beer/8th/99-bottles-of-beer-2.8th @@ -0,0 +1,12 @@ +[ + ( "Just one more bottle of beer on the wall, one bottle of beer.\n" . ) , + ( I dup "%d bottles of beer on the wall, %d bottles of beer.\n" s:strfmt . ) +] constant lyrics + +: app:main + ( + dup lyrics [2,99] rot ' n:cmp a:pigeon w:exec + n:1- "Take one down, pass it around, %d bottles of beer on the wall.\n\n" s:strfmt . + ) 1 99 loop- + + "No more bottles of beer on the wall, no more bottles of beer.\n" . ; diff --git a/Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th b/Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th deleted file mode 100644 index fa816e4a36..0000000000 --- a/Task/99-bottles-of-beer/8th/99-bottles-of-beer.8th +++ /dev/null @@ -1,20 +0,0 @@ -\ 99 bottles of beer on the wall: -: allout "no more bottles" ; -: just-one "1 bottle" ; -: yeah! dup . " bottles" ; - -[ - ' allout , - ' just-one , - ' yeah! , -] var, bottles - -: .bottles dup 2 n:min bottles @ swap caseof ; -: .beer .bottles . " of beer" . ; -: .wall .beer " on the wall" . ; -: .take " Take one down and pass it around" . ; -: beers .wall ", " . .beer '; putc cr - n:1- 0 max .take ", " . - .wall '. putc cr drop ; - -' beers 1 99 loop- bye diff --git a/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer.oxy b/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-1.oxy similarity index 100% rename from Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer.oxy rename to Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-1.oxy diff --git a/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy b/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy new file mode 100644 index 0000000000..5fc3a8fccb --- /dev/null +++ b/Task/99-bottles-of-beer/Oxygene/99-bottles-of-beer-2.oxy @@ -0,0 +1,21 @@ +namespace _99_beers; + +method bottles(number: Integer): String; +begin +if (number = 1) then + Result := "bottle" + else + Result := "bottles"; +end; + +begin + for n: Integer := 99 downto 1 do + begin + writeLn($"{n} {bottles(n)} of beer on the wall,"); + writeLn($"{n} {bottles(n)} of beer,"); + writeLn($"Take one down, and pass it around,"); + writeLn($"{n-1} {bottles(n-1)} of beer on the wall."); + writeLn(); + end; + readLn; +end. diff --git a/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas new file mode 100644 index 0000000000..f455395d06 --- /dev/null +++ b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-1.pas @@ -0,0 +1,10 @@ +begin + for var i:=99 to 1 step -1 do + begin + Println(i,'bottles of beer on the wall'); + Println(i,'bottles of beer'); + Println('Take one down, pass it around'); + Println(i-1,'bottles of beer on the wall'); + Println + end; +end. diff --git a/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas new file mode 100644 index 0000000000..3ce09c9fc9 --- /dev/null +++ b/Task/99-bottles-of-beer/PascalABC.NET/99-bottles-of-beer-2.pas @@ -0,0 +1,10 @@ +begin + for var i:=99 to 1 step -1 do + begin + writeLn($'{i} bottles of beer on the wall'); + writeLn($'{i} bottles of beer'); + writeLn($'Take one down, pass it around'); + writeLn($'{i-1}bottles of beer on the wall'); + writeLn + end; +end. diff --git a/Task/A+B/PascalABC.NET/a+b.pas b/Task/A+B/PascalABC.NET/a+b.pas new file mode 100644 index 0000000000..ac390aa674 --- /dev/null +++ b/Task/A+B/PascalABC.NET/a+b.pas @@ -0,0 +1,3 @@ +## +var (a,b) := ReadInteger2; +Writeln(a + b); diff --git a/Task/A+B/Zig/a+b.zig b/Task/A+B/Zig/a+b.zig new file mode 100644 index 0000000000..fc0d17b9f6 --- /dev/null +++ b/Task/A+B/Zig/a+b.zig @@ -0,0 +1,25 @@ +const std = @import("std"); +const stdout = std.io.getStdOut().writer(); + +const Input = enum { a, b }; + +pub fn main() !void { + var buf: [1024]u8 = undefined; + const reader = std.io.getStdIn().reader(); + const input = try reader.readUntilDelimiter(&buf, '\n'); + const values = std.mem.trim(u8, input, "\x20"); + + var count: usize = 0; + var split: usize = 0; + for (values, 0..) |c, i| { + if (!std.ascii.isDigit(c)) { + count += 1; + if (count == 1) split = i; + } + } + + const a = try std.fmt.parseInt(u64, values[0..split], 10); + const b = try std.fmt.parseInt(u64, values[split + count ..], 10); + + try stdout.print("{d}\n", .{a + b}); +} diff --git a/Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua b/Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua new file mode 100644 index 0000000000..d163a20723 --- /dev/null +++ b/Task/ADFGVX-cipher/Uiua/adfgvx-cipher.uiua @@ -0,0 +1,11 @@ +A ← ↯∞_2⊞⊟."ADFGVX" +P ← ⊏⍏[⍥⚂]⧻."ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" +K ← "PACKHORSE" +Sw ← ⊜□≠" ". +Polybius ← setinv(/⊂⊡≡(⊚⌕):⊙:¤P A|⊏:P≡(⊢⊚⌕)⊙¤∩≡□↯∞_2:A) +SortByK ← setinv(⊏⍏⟜(⍉⬚" "↯⊟∞⧻)K|▽≠" "./⊂⍉⊏⍏⍏K) +Str ← setinv(/$"_ _"Sw/⊂≡(⊂:" ")|≡(⊢°□◇⬚" "↯⊟∞)/↥≡◇⧻.Sw) +Pt ← "ATTACKAT1200AM" +&p $"Key = _\nPolybius:\n_\nPlaintext = _"K↯⊟.√⧻.P Pt +&p$"Crypttext = _". Str SortByK Polybius Pt +&p$"Plaintext = _" °Polybius °SortByK °Str diff --git a/Task/ASCII-art-diagram-converter/FutureBasic/ascii-art-diagram-converter.basic b/Task/ASCII-art-diagram-converter/FutureBasic/ascii-art-diagram-converter.basic new file mode 100644 index 0000000000..53358adc2d --- /dev/null +++ b/Task/ASCII-art-diagram-converter/FutureBasic/ascii-art-diagram-converter.basic @@ -0,0 +1,93 @@ +// RosettaCode Editing ASCII Art Diagram Converter + +include "NSLog.incl" + +local fn HexToBinary( hexString as CFStringRef ) as CFStringRef + NSUInteger i + CFMutableStringRef binaryString = fn MutableStringNew + CFDictionaryRef hexToBinaryMap = @{ + @"0": @"0000", @"1": @"0001", @"2": @"0010", @"3": @"0011", + @"4": @"0100", @"5": @"0101", @"6": @"0110", @"7": @"0111", + @"8": @"1000", @"9": @"1001", @"A": @"1010", @"B": @"1011", + @"C": @"1100", @"D": @"1101", @"E": @"1110", @"F": @"1111"} + + for i = 0 to len(hexString) - 1 + CFStringRef hexDigit = ucase( fn StringSubstringWithRange( hexString, fn CFRangeMake( i, 1 ) ) ) + CFStringRef binaryDigit = ucase( hexToBinaryMap[hexDigit] ) + if ( binaryDigit ) + MutableStringAppendString( binaryString, binaryDigit ) + end if + next +end fn = binaryString + +local fn ParseASCIIArt + CFStringRef header = @"¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n¬ + | ID |\n¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n¬ + |QR| Opcode |AA|TC|RD|RA| Z | RCODE |\n¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n¬ + | QDCOUNT |\n¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n¬ + | ANCOUNT |\n¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n¬ + | NSCOUNT |\n¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+\n¬ + | ARCOUNT |\n¬ + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + + NSInteger i = 0, tempBits + CFMutableArrayRef table = fn MutableArrayNew + RegularExpressionRef regex = fn RegularExpressionWithPattern( @"\\| *\\w+ *", 0, NULL ) + CFArrayRef matches = fn RegularExpressionMatches( regex, header, 0, fn CFRangeMake( 0, len(header) ) ) + TextCheckingResultRef match + CFDictionaryRef dict + CFStringRef tempName, binaryStr + CFRange tempRange + + for match in matches + CFRange range = fn TextCheckingResultRange( match ) + CFCharacterSetRef charSet = fn CharacterSetWithCharactersInString( @"| " ) + CFStringRef name = fn StringByTrimmingCharactersInSet( fn StringSubstringWithRange( header, range ), charSet ) + NSInteger bits = range.length / 3 + ValueRef rangeVal = fn ValueWithRange( fn CFRangeMake( i, bits ) ) + CFDictionaryRef item = @{@"name":name, @"bits":fn NumberWithInteger( bits ), @"range":rangeVal} + MutableArrayAddObject( table, item ) + i += bits + next + + NSLog( @"\nRFC 1035 message diagram header:\n%@\n", header ) + + CFStringRef hexStr = @"78477bbf5496e12e1bf169a4" + CFStringRef binStr = fn HexToBinary( @"78477bbf5496e12e1bf169a4" ) + + NSLog( @" Decoded:" ) + NSLog( @" Name Bits Start End" ) + NSLog( @" ======= ==== ===== ===" ) + + for dict in table + tempName = dict[@"name"] + tempBits = fn NumberIntegerValue( dict[@"bits"] ) + tempRange = fn ValueRange( dict[@"range"] ) + NSLog( @"%8s %5ld %6ld %4ld", fn StringUTF8String( tempName ), tempBits, tempRange.location, tempRange.location + tempRange.length - 1 ) + next + + NSLog( @"\n Test string in hex:\n %@\n", hexStr ) + NSLog( @" Test string in binary:\n %@\n", binStr ) + + NSLog( @" Unpacked:" ) + NSLog( @" Name Size Bit Pattern" ) + NSLog( @" ======= ==== ================" ) + + for dict in table + tempName = dict[@"name"] + tempBits = fn NumberIntegerValue( dict[@"bits"] ) + tempRange = fn ValueRange( dict[@"range"] ) + binaryStr = fn StringSubstringWithRange( binStr, fn CFRangeMake( tempRange.location, tempBits ) ) + NSLog( @"%8s %5ld %-7s", fn StringUTF8String( tempName ), tempBits, fn StringUTF8String( binaryStr ) ) + next +end fn + +fn ParseASCIIArt + +HandleEvents diff --git a/Task/ASCII-art-diagram-converter/Uiua/ascii-art-diagram-converter.uiua b/Task/ASCII-art-diagram-converter/Uiua/ascii-art-diagram-converter.uiua new file mode 100644 index 0000000000..ab69945cb9 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/Uiua/ascii-art-diagram-converter.uiua @@ -0,0 +1,26 @@ +HtoB ← /⊂⋯⊗:"0123456789abcdef" +Fields ← ( + ⊜□≠@|./⊂▽⊸≡(¬∊@+)⊜∘≠@\n. + ⊃(≡(÷3+1◇⧻)|≡(□(◇▽⊸⍚≥@A))) +) +T ← $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + $ | ID | + $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + $ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | + $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + $ | QDCOUNT | + $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + $ | ANCOUNT | + $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + $ | NSCOUNT | + $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + $ | ARCOUNT | + $ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + +◫2⊂0\+Fields T # Get field starts and ends. +HtoB "78477bbf5496e12e1bf169a4" +⍚⊏⊙¤≡(□↘⊙⇡°⊟), # Split the bits. +≡⊂:≡⊂:⊙(≡(⊂:⊟⊙(-1)°⊟⟜/-)) # Arrange the table. +&p$"Field\tBits\tStart\tEnd\tValue" +&p$"-----\t----\t-----\t---\t-----" +≡(&p$"_\t_\t_\t_\t_"⊃(⊡0|⊡1|⊡2|⊡3|⊡4)) diff --git a/Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.l b/Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.l new file mode 100644 index 0000000000..8877dc684b --- /dev/null +++ b/Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.l @@ -0,0 +1,36 @@ +(defun abbreviate-list (list-of-days abbreviation-length) + "Take each element of LIST-OF-DAYS and abbreviate to ABBREVIATION-LENGTH." + (let ((abbrev-list) + (abbrev-element)) + (dolist (one-element list-of-days) ; loop through each day of week +;; if the day of week is at least as long as the abbreviation + (if (>= (length one-element) abbreviation-length) ; if day >= abbreviation length + (setq abbrev-element (substring one-element 0 abbreviation-length)) ; abbreviate the day of the week + (setq abbrev-element one-element)) ; otherwise don't abbreviate + (push abbrev-element abbrev-list)) ; put the abbreviated/non-abbreviated day on our list + abbrev-list)) ; return the list of abbreviated days + +(defun cycle-days (list-of-days) + "Find shortest unique abbreviation in LIST-OF-DAYS list." + (let ((abbrev-list) + (abbrev-length 1) + (current-abbrev) + (looking-for-shortest-list t)) + (if (= (length list-of-days) 0) ; if list-of-days is empty (i.e., blank line) + (setq looking-for-shortest-list nil)) ; then don't look for the shortest unique abbreviations + (while looking-for-shortest-list ; as long as we are looking for the shortest unique abbreviations + (setq abbrev-list (abbreviate-list list-of-days abbrev-length)) ; get a list of abbreviated day names + (if (= (length list-of-days) (length (seq-uniq abbrev-list))) ; if abbreviated list has no duplicates + (progn + (message (format "%d %s" abbrev-length list-of-days)) ; then in echo buffer show length and days + (setq looking-for-shortest-list nil)) ; also, then don't look for the shortest unique abbreviations + (setq abbrev-length (+ abbrev-length 1)))))) ; else increase the length of the abbreviation; loop to while + +(defun days-of-week () + "Find minimum abbreviation length of days of week." + (let ((current-line-list)) + (find-file "Days_of_week.txt") ; open file or switch to buffer + (beginning-of-buffer) ; go to the top of the buffer + (dolist (current-line (split-string (buffer-string) "\n")) ; go line by line through buffer + (setq current-line-list (split-string current-line " ")) ; change each line into list of days of week + (cycle-days current-line-list)))) diff --git a/Task/Abbreviations-automatic/Uiua/abbreviations-automatic.uiua b/Task/Abbreviations-automatic/Uiua/abbreviations-automatic.uiua new file mode 100644 index 0000000000..983c4fa405 --- /dev/null +++ b/Task/Abbreviations-automatic/Uiua/abbreviations-automatic.uiua @@ -0,0 +1,17 @@ +# Experimental! +# Find shortest distinct abbreviation length per line + +Lines ← {"Sunday Monday Tuesday Wednesday Thursday Friday Saturday" + "sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk" + "" + "Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata" + "sunnudagur mánadagur tÿsdaguy mikudagur hósdagur friggjadagur leygardagur" + "Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh"} + +# Return 1+max_common_prefix +AbbrevLen ← +1/↥◹(/↥↘1)⊞(/+\↧⬚@ =∩°□). +Split ← ⊜□⊸(≠@ ) +RemoveEmpty ← ▽⊸(≡(≠0◇⧻)) +Line ← ⊂⊂:": " °⋕:⊸(/(⊂⊂) " "≡(⬚@ ↙:°□)⊙¤)⟜AbbrevLen ◇Split +≡⍚Line RemoveEmpty Lines +≡&p diff --git a/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy b/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy new file mode 100644 index 0000000000..3e0c4d008f --- /dev/null +++ b/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy @@ -0,0 +1,60 @@ +proc out s[] . . + for r = 0 to 2 + for c to 3 + write s[c + 3 * r] & " " + . + print "" + . + print "" +. +proc stab . m[] . + n = sqrt len m[] + repeat + stable = 1 + for p to len m[] + if m[p] >= 4 + stable = 0 + m[p] -= 4 + if p > n + m[p - n] += 1 + . + if p mod n <> 0 + m[p + 1] += 1 + . + if p <= len m[] - n + m[p + n] += 1 + . + if p mod n <> 1 + m[p - 1] += 1 + . + . + . + until stable = 1 + . +. +func[] add s1[] s2[] . + for i to len s1[] + r[] &= s1[i] + s2[i] + . + stab r[] + return r[] +. +print "avalanche:" +s4[] = [ 4 3 3 3 1 2 0 2 3 ] +stab s4[] +out s4[] +# +s1[] = [ 1 2 0 2 1 1 0 1 3 ] +s2[] = [ 2 1 3 1 0 1 0 1 0 ] +if add s1[] s2[] = add s2[] s1[] + print "s1 + s2 = s2 + s1" +. +# +s3[] = [ 3 3 3 3 3 3 3 3 3 ] +s3_id[] = [ 2 1 2 1 0 1 2 1 2 ] +if add s3[] s3_id[] = s3[] + print "s3 + s3_id = s3" +. +if add s3_id[] s3_id[] = s3_id[] + print "s3_id + s3_id = s3_id" +. diff --git a/Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.ada b/Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.ada new file mode 100644 index 0000000000..10aa915326 --- /dev/null +++ b/Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.ada @@ -0,0 +1,67 @@ +pragma Ada_2022; +with Ada.Command_Line; use Ada.Command_Line; +with Ada.Text_IO; use Ada.Text_IO; +procedure Abelian_Sandpile is + type Grid_2D is array (Positive range <>, Positive range <>) of Natural; + + procedure Write_PPM (Grid : Grid_2D; Filename : String) is + PPM_File : File_Type; + begin + Create (PPM_File, Out_File, Filename); + Put_Line (PPM_File, "P3"); + Put_Line (PPM_File, Grid'Length (1)'Image & Grid'Length (2)'Image); + Put_Line (PPM_File, "7"); + for Y in 1 .. Grid'Length (2) loop + for X in 1 .. Grid'Length (1) loop + case Grid (X, Y) is + when 0 => Put_Line (PPM_File, "0 0 0"); -- black + when 1 => Put_Line (PPM_File, "0 7 0"); -- green + when 2 => Put_Line (PPM_File, "7 0 7"); -- lilac + when 3 => Put_Line (PPM_File, "7 7 0"); -- yellow + when others => Put_Line (PPM_File, "0 0 7"); -- blue, shouldn't happen + end case; + end loop; + end loop; + Close (PPM_File); + end Write_PPM; +begin + if Argument_Count /= 2 then + Put_Line ("Error: Must specify "); + else + declare + Initial_Height : constant Positive := Positive'Value (Argument (1)); + Grid_Size : constant Positive := Positive'Value (Argument (2)); + Sandpile : Grid_2D (1 .. Grid_Size, 1 .. Grid_Size) := [others => [others => 0]]; + More_To_Do : Boolean := True; + Overspill : Natural; + begin + Sandpile (Grid_Size / 2, Grid_Size / 2) := Initial_Height; + while More_To_Do loop + More_To_Do := False; + for X in 1 .. Grid_Size loop + for Y in 1 .. Grid_Size loop + if Sandpile (X, Y) >= 4 then + Overspill := Sandpile (X, Y) / 4; + Sandpile (X, Y) := @ mod 4; + More_To_Do := True; + if X > 1 then + Sandpile (X - 1, Y) := @ + Overspill; + end if; + if Y > 1 then + Sandpile (X, Y - 1) := @ + Overspill; + end if; + if X < Grid_Size then + Sandpile (X + 1, Y) := @ + Overspill; + end if; + if Y < Grid_Size then + Sandpile (X, Y + 1) := @ + Overspill; + end if; + end if; + end loop; + end loop; + end loop; + if Grid_Size < 16 then Put_Line (Sandpile'Image); end if; + Write_PPM (Sandpile, "sandpile.ppm"); + end; + end if; +end Abelian_Sandpile; diff --git a/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy b/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy new file mode 100644 index 0000000000..c77b7a2530 --- /dev/null +++ b/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy @@ -0,0 +1,35 @@ +n = 77 +len m[] n * n +m[n * n div 2 + 1] = 10000 +# +proc show . . + sc = 100 / n + for r range0 n + for c range0 n + move c * sc r * sc + p = r * n + c + 1 + color 222 * m[p] + rect sc sc + . + . + sleep 0 +. +proc run . . + repeat + mp[] = m[] + stable = 1 + for p to len mp[] + if mp[p] >= 4 + stable = 0 + m[p] -= 4 + m[p - n] += 1 + m[p + 1] += 1 + m[p + n] += 1 + m[p - 1] += 1 + . + . + show + until stable = 1 + . +. +run diff --git a/Task/Abelian-sandpile-model/Locomotive-Basic/abelian-sandpile-model.basic b/Task/Abelian-sandpile-model/Locomotive-Basic/abelian-sandpile-model.basic new file mode 100644 index 0000000000..6406a507ab --- /dev/null +++ b/Task/Abelian-sandpile-model/Locomotive-Basic/abelian-sandpile-model.basic @@ -0,0 +1,27 @@ +10 mode 1:defint a-z +20 height=15000:size=100 +30 ink 0,0:ink 1,18:ink 2,8:ink 3,24 +40 dim grid(size+1,size+1) +50 grid(size/2,size/2)=height +60 moretodo=1 +70 while moretodo +80 moretodo=0 +90 for x=1 to size +100 for y=1 to size +110 if grid(x,y)<4 then 190 +120 overspill=int(grid(x,y)/4) +130 grid(x,y)=grid(x,y) mod 4 +140 moretodo=1 +150 if x>1 then grid(x-1,y)=grid(x-1,y)+overspill +160 if y>1 then grid(x,y-1)=grid(x,y-1)+overspill +170 if x= 4 -- slightly faster +⟜Scale&p⍜now⍥Abelian₄ 100G 0 +⟜Scale&p⍜now⍥Abelian₄ 900⊙, +Scale⍥Abelian₄∞⊙, # Run to completion diff --git a/Task/Abstract-type/11l/abstract-type.11l b/Task/Abstract-type/11l/abstract-type.11l index ed88d4b041..2374f37287 100644 --- a/Task/Abstract-type/11l/abstract-type.11l +++ b/Task/Abstract-type/11l/abstract-type.11l @@ -1,6 +1,6 @@ T AbstractQueue - F.virtual.abstract enqueue(Int item) -> N + F.virtual.abstract enqueue(Int item) -> Void T PrintQueue(AbstractQueue) - F.virtual.assign enqueue(Int item) -> N + F.virtual.assign enqueue(Int item) -> Void print(item) diff --git a/Task/Abstract-type/PascalABC.NET/abstract-type-1.pas b/Task/Abstract-type/PascalABC.NET/abstract-type-1.pas new file mode 100644 index 0000000000..4ea14e8f5f --- /dev/null +++ b/Task/Abstract-type/PascalABC.NET/abstract-type-1.pas @@ -0,0 +1,20 @@ +type + MyAbstract = abstract class + public + procedure Proc1; abstract; + procedure Proc2; + begin + end; + end; + MyClass = class(MyAbstract) + public + procedure Proc1; override; + begin + end; + end; + + +begin + var a := new MyClass; + a.Proc1; +end. diff --git a/Task/Abstract-type/PascalABC.NET/abstract-type-2.pas b/Task/Abstract-type/PascalABC.NET/abstract-type-2.pas new file mode 100644 index 0000000000..aaa3e079db --- /dev/null +++ b/Task/Abstract-type/PascalABC.NET/abstract-type-2.pas @@ -0,0 +1,22 @@ +type + IMyInterface = interface + procedure Proc1; + procedure Proc2; + end; + MyClass = class(IMyInterface) + public + procedure Proc1; + begin + Print(1); + end; + procedure Proc2; + begin + Print(2); + end; + end; + +begin + var a: IMyInterface := new MyClass; + a.Proc1; + a.Proc2; +end. diff --git a/Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas b/Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas new file mode 100644 index 0000000000..86c0cbcc7d --- /dev/null +++ b/Task/Accumulator-factory/PascalABC.NET/accumulator-factory.pas @@ -0,0 +1,12 @@ +function foo(n: real): real -> real := + i -> begin + n += i; + Result := n; + end; + +begin + var x := foo(1); + x(5); + foo(3); + print(x(2.3)); +end. diff --git a/Task/Achilles-numbers/Ada/achilles-numbers.ada b/Task/Achilles-numbers/Ada/achilles-numbers.ada new file mode 100644 index 0000000000..054f448da3 --- /dev/null +++ b/Task/Achilles-numbers/Ada/achilles-numbers.ada @@ -0,0 +1,205 @@ +pragma Ada_2022; + +with Ada.Text_IO; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Long_Elementary_Functions; +use Ada.Numerics.Long_Elementary_Functions; +with Ada.Strings; use Ada.Strings; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +with Prime_Numbers; + +procedure Achilles_Numbers is + + package Long_Integer_Prime_Numbers is new Prime_Numbers + (Integer, 0, 1, 2); + use Long_Integer_Prime_Numbers; + + -- A powerful number N is such that for every primer factor P of it + -- P^2 also divides N + -- Is_Powerful function decomposes the given number N in its prime factors + -- and then it checks if each factor squared is a divisor of N + function Is_Powerful (Number : Natural) return Boolean is + List : constant Number_List := Decompose (Integer (Number)); + begin + for Index in List'Range loop + declare + N : constant Long_Long_Integer := Long_Long_Integer (Number); + F : constant Long_Long_Integer := Long_Long_Integer (List (Index)); + begin + if N mod (F * F) /= 0 then + return False; + end if; + end; + end loop; + + return True; + end Is_Powerful; + + -- The Is_Power function checks if a given number N can be written + -- as a power of two integers that are > 1 + -- It makes use of the mathematical expression N = A^B + -- taking Log(N) = Log (A^B) equals to B = Log (N) / Log (A) + -- where the solutions are when B is an integer > 1 + function Is_Power (N : Integer) return Boolean is + + function Is_Almost_Equal (A : Long_Float; + B : Long_Float) return Boolean is + Epsilon : constant := 0.000_000_000_000_001; + begin + if abs (A - B) < Epsilon then + return True; + else + return False; + end if; + end Is_Almost_Equal; + + A : Integer := 2; + B : Long_Float; + Log_Of_N : constant Long_Float := Log (Long_Float (N), 2.0); + begin + if N = 1 then + return True; + end if; + + while True loop + B := Log_Of_N / Log (Long_Float (A), 2.0); + + if Is_Almost_Equal (B, Long_Float (Integer (B))) + and then Integer (B) > 1 + then + return True; + end if; + + exit when A * A > N; + A := @ + 1; + end loop; + + return False; + + end Is_Power; + + -- An Achilles number is a powerful number that can't be expressed + -- as a power + function Is_Achilles (N : Integer) return Boolean is + begin + if Is_Powerful (N) then + if Is_Power (N) = False then + return True; + end if; + end if; + + return False; + end Is_Achilles; + + -- Calculates the Euler totient of a number + function Totient (N : Integer) return Integer is + Tot : Integer := N; + I : Integer; + N2 : Integer := N; + begin + I := 2; + while I * I <= N2 loop + if N2 mod I = 0 then + while N2 mod I = 0 loop + N2 := N2 / I; + end loop; + Tot := Tot - Tot / I; + end if; + + if I = 2 then + I := 1; + end if; + I := I + 2; + end loop; + + if N2 > 1 then + Tot := Tot - Tot / N2; + end if; + + return Tot; + end Totient; + + -- A Strong Achilles number is an Achilles number whose Euler Totient + -- is also an Achilles number + function Is_Strong_Achilles (N : Integer) return Boolean is + begin + if Is_Achilles (N) then + if Is_Achilles (Totient (N)) then + return True; + end if; + end if; + + return False; + end Is_Strong_Achilles; + + -- Counts the digits in a number by taking the string from + -- its 'Image attribute, trimming it and counting the characters + function Count_Digits (N : Integer) return Natural is + Integer_Str : constant String := Trim (N'Image, Both); + begin + return Integer_Str'Length; + end Count_Digits; + +begin + -- Find the first 50 Achilles numbers + declare + N : Integer := 1; + Count : Integer := 1; + begin + Ada.Text_IO.Put_Line ("First 50 Achilles numbers:"); + + while Count <= 50 loop + + if Is_Achilles (N) then + Count := @ + 1; + Ada.Text_IO.Put (N'Image & " "); + end if; + + N := @ + 1; + end loop; + + Ada.Text_IO.New_Line; + end; + + -- Find the first 20 Strong Achilles numbers + declare + N : Integer := 1; + Count : Integer := 1; + begin + Ada.Text_IO.Put_Line ("First 20 Strong Achilles numbers:"); + + while Count <= 20 loop + + if Is_Strong_Achilles (N) then + Count := @ + 1; + Ada.Text_IO.Put (N'Image & " "); + end if; + + N := @ + 1; + end loop; + + Ada.Text_IO.New_Line; + end; + + -- Count numbers with digits + declare + Counts : array (2 .. 6) of Natural := [others => 0]; + N : Integer := 1; + begin + Ada.Text_IO.Put_Line ("Number of Achilles numbers with:"); + + while Count_Digits (N) <= Counts'Last loop + + -- Ada.Text_IO.Put_Line ("Testing: " & N'Image); + + if Is_Achilles (N) then + Counts (Count_Digits (N)) := @ + 1; + end if; + N := @ + 1; + end loop; + + for I in Counts'Range loop + Ada.Text_IO.Put_Line (I'Image & " digits: " & Counts (I)'Image); + end loop; + end; +end Achilles_Numbers; diff --git a/Task/Ackermann-function/PascalABC.NET/ackermann-function.pas b/Task/Ackermann-function/PascalABC.NET/ackermann-function.pas new file mode 100644 index 0000000000..1343534204 --- /dev/null +++ b/Task/Ackermann-function/PascalABC.NET/ackermann-function.pas @@ -0,0 +1,16 @@ +function Ackermann(m,n: integer): integer; +begin + if (m < 0) or (n < 0) then + raise new System.ArgumentOutOfRangeException(); + if m = 0 then + Result := n + 1 + else if n = 0 then + Result := Ackermann(m - 1, 1) + else Result := Ackermann(m - 1, Ackermann(m, n - 1)) +end; + +begin + for var m := 0 to 3 do + for var n := 0 to 4 do + Println($'Ackermann({m}, {n}) = {Ackermann(m,n)}'); +end. diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp b/Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp new file mode 100644 index 0000000000..1f83768ae0 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/C++/add-a-variable-to-a-class-instance-at-runtime.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +class Demonstration { +public: + Demonstration() { + variables = { }; + } + + std::map variables; +}; + +int main() { + Demonstration demo; + std::cout << "Create two variables at runtime:" << std::endl; + for ( uint32_t i = 1; i <= 2; ++i ) { + std::cout << " Variable number " << i << ":" << std::endl; + std::cout << " Enter name: " << std::endl; + std::string name; + std::cin >> name; + std::cout << " Enter value: " << std::endl; + double value; + std::cin >> value; + demo.variables[name] = value; + } + + std::cout << std::endl; + std::cout << "Two new runtime variables appear to have been created." << std::endl; + for ( const auto &[key, value] : demo.variables ) { + std::cout << "Variable " << key << " = " << value << std::endl; + } +} diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas b/Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas new file mode 100644 index 0000000000..3a8fa42045 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/PascalABC.NET/add-a-variable-to-a-class-instance-at-runtime.pas @@ -0,0 +1,19 @@ +type + MyClass = class + private + dict := new Dictionary; + public + procedure Add(name: string; value: object) := dict[name] := value; + property Items[name: string]: object read dict[name]; default; + end; + +begin + var obj := new MyClass; + obj.Add('Name','PascalABC.NET'); + obj.Add('Age',16); + Println(obj['Name'],obj['Age']); + var obj1 := new MyClass; + obj1.Add('X',2.3); + obj1.Add('Y',3.8); + Println(obj1['X'],obj1['Y']); +end. diff --git a/Task/Additive-primes/ALGOL-68/additive-primes.alg b/Task/Additive-primes/ALGOL-68/additive-primes.alg index 0c87382bc0..134ae5080f 100644 --- a/Task/Additive-primes/ALGOL-68/additive-primes.alg +++ b/Task/Additive-primes/ALGOL-68/additive-primes.alg @@ -20,5 +20,6 @@ BEGIN # find additive primes - primes whose digit sum is also prime # FI FI OD; - print( ( newline, "Found ", whole( additive count, 0 ), " additive primes below ", whole( UPB prime + 1, 0 ), newline ) ) + print( ( newline, "Found ", whole( additive count, 0 ) ) ); + print( ( " additive primes below ", whole( UPB prime + 1, 0 ), newline ) ) END diff --git a/Task/Additive-primes/C-sharp/additive-primes.cs b/Task/Additive-primes/C-sharp/additive-primes.cs new file mode 100644 index 0000000000..d076d0709c --- /dev/null +++ b/Task/Additive-primes/C-sharp/additive-primes.cs @@ -0,0 +1,86 @@ +internal class Program +{ + private static void Main(string[] args) + { + long primeCandidate = 1; + long additivePrimeCount = 0; + Console.WriteLine("Additive Primes"); + + while (primeCandidate < 500) + { + if (IsAdditivePrime(primeCandidate)) + { + additivePrimeCount++; + + Console.Write($"{primeCandidate,-3} "); + + if (additivePrimeCount % 10 == 0) + { + Console.WriteLine(); + } + } + + primeCandidate++; + } + + Console.WriteLine(); + Console.WriteLine($"Found {additivePrimeCount} additive primes less than 500"); + } + + private static bool IsAdditivePrime(long number) + { + if (IsPrime(number) && IsPrime(DigitSum(number))) + { + return true; + } + + return false; + } + + private static bool IsPrime(long number) + { + if (number < 2) + { + return false; + } + + if (number % 2 == 0) + { + return number == 2; + } + + if (number % 3 == 0) + { + return number == 3; + } + + int delta = 2; + long k = 5; + + while (k * k <= number) + { + if (number % k == 0) + { + return false; + } + + k += delta; + delta = 6 - delta; + } + + return true; + } + + private static long DigitSum(long n) + { + long sum = 0; + + while (n > 0) + { + sum += n % 10; + n /= 10; + } + + return sum; + } +} diff --git a/Task/Additive-primes/Langur/additive-primes.langur b/Task/Additive-primes/Langur/additive-primes.langur index cc42b1cb23..19042c8a58 100644 --- a/Task/Additive-primes/Langur/additive-primes.langur +++ b/Task/Additive-primes/Langur/additive-primes.langur @@ -1,18 +1,20 @@ -val .isPrime = fn(.i) .i == 2 or .i > 2 and - not any fn(.x) .i div .x, pseries 2 .. .i ^/ 2 +val isPrime = fn(i) { + i == 2 or i > 2 and + not any(fn x: i div x, pseries(2 .. i ^/ 2)) +} -val .sumDigits = fn(.i) fold fn{+}, s2n string .i +val sumDigits = fn i: fold(fn{+}, s2n(string(i))) writeln "Additive primes less than 500:" -var .count = 0 +var cnt = 0 -for .i in [2] ~ series(3..500, 2) { - if .isPrime(.i) and .isPrime(.sumDigits(.i)) { - write $"\{.i:3} " - .count += 1 - if .count div 10: writeln() +for i in [2] ~ series(3..500, 2) { + if isPrime(i) and isPrime(sumDigits(i)) { + write "{{i:3}} " + cnt += 1 + if cnt div 10: writeln() } } -writeln $"\n\n\{.count} additive primes found.\n" +writeln "\n\n{{cnt}} additive primes found.\n" diff --git a/Task/Additive-primes/Modula-3/additive-primes.mod3 b/Task/Additive-primes/Modula-3/additive-primes.mod3 new file mode 100644 index 0000000000..7c2695e0cb --- /dev/null +++ b/Task/Additive-primes/Modula-3/additive-primes.mod3 @@ -0,0 +1,44 @@ +MODULE AdditivePrimes EXPORTS Main; + +IMPORT SIO,Fmt; + +CONST + Max = 500; + +VAR + Count:CARDINAL := 0; + Prime:ARRAY[2..Max] OF BOOLEAN; + +PROCEDURE DigitSum(N:CARDINAL):CARDINAL = + BEGIN + IF N < 10 THEN RETURN N + ELSE RETURN (N MOD 10) + DigitSum(N DIV 10) END; + END DigitSum; + +PROCEDURE Sieve() = + VAR J:CARDINAL; + BEGIN + FOR I := 2 TO Max DO Prime[I] := TRUE END; + FOR I := 2 TO Max DIV 2 DO + IF Prime[I] THEN + J := I*2; + WHILE J <= Max DO + Prime[J] := FALSE; + INC(J,I) + END + END + END; + END Sieve; + +BEGIN + Sieve(); + FOR N := 2 TO Max DO + IF Prime[N] AND Prime[DigitSum(N)] THEN + SIO.PutText(Fmt.F("%4s",Fmt.Int(N))); + INC(Count); + IF Count MOD 10 = 0 THEN SIO.Nl() END + END + END; + SIO.PutText(Fmt.F("\nThere are %s additive primes less than %s.\n", + Fmt.Int(Count),Fmt.Int(Max))); +END AdditivePrimes. diff --git a/Task/Address-of-a-variable/PascalABC.NET/address-of-a-variable.pas b/Task/Address-of-a-variable/PascalABC.NET/address-of-a-variable.pas new file mode 100644 index 0000000000..dae77114a9 --- /dev/null +++ b/Task/Address-of-a-variable/PascalABC.NET/address-of-a-variable.pas @@ -0,0 +1,6 @@ +begin + var i: integer := 3; + var p: ^integer := @i; + p^ += 2; + Print(p^,i); +end. diff --git a/Task/Align-columns/Uiua/align-columns.uiua b/Task/Align-columns/Uiua/align-columns.uiua new file mode 100644 index 0000000000..147119d5cb --- /dev/null +++ b/Task/Align-columns/Uiua/align-columns.uiua @@ -0,0 +1,17 @@ +# Split the text at $ and then justify each word 3 ways +N ← {"Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + "are$delineated$by$a$single$'dollar'$character,$write$a$program" + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + "column$are$separated$by$at$least$one$space." + "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + "justified,$right$justified,$or$center$justified$within$its$column."} +Ls ← ≡⍚(⊜□≠@$.)N # Get the word arrays +P ← +1/↥≡◇⧻/◇⊂Ls # Padding = Max length + 1 +PadL ← /↥⬚@ ⊟↯P@ +PadR ← ⍜⇌PadL +PadC ← PadL⊂↯:@ ⌊÷2-:P⧻. +Format! ← ≡&p≡(□/⊂≡◇^!°□) +# Demonstration of use of an array macro, which actually just resolves to +# ⊃(Format!PadC|Format!PadR|Format!PadL)Ls +Fall‼! ←^ $"⊃(_)"/⊂≡($"Format!_ |"°□)⇌ +Fall‼!PadL PadR PadC Ls diff --git a/Task/Aliquot-sequence-classifications/00-TASK.txt b/Task/Aliquot-sequence-classifications/00-TASK.txt index 0d3ab821b5..31c44d6d5f 100644 --- a/Task/Aliquot-sequence-classifications/00-TASK.txt +++ b/Task/Aliquot-sequence-classifications/00-TASK.txt @@ -30,3 +30,6 @@ Show all output on this page. *   [[Amicable pairs]]

+;External links: +* [https://www.youtube.com/watch?v=OtYKDzXwDEE An amazing thing about 276], Numberphile + diff --git a/Task/Amb/Langur/amb.langur b/Task/Amb/Langur/amb.langur index 99fb78c1fc..3adeaad38f 100644 --- a/Task/Amb/Langur/amb.langur +++ b/Task/Amb/Langur/amb.langur @@ -1,15 +1,15 @@ -val .wordsets = [ +val wordsets = [ fw/the that a/, fw/frog elephant thing/, fw/walked treaded grows/, fw/slowly quickly/, ] -val .alljoin = fn(.words) for[=true] .i of len(.words)-1 { - if last(.words[.i]) != first(.words[.i+1]): break = false +val alljoin = fn words: for[=true] i of len(words)-1 { + if words[i][-1] != words[i+1][1]: break = false } -# .amb expects 2 or more arguments -val .amb = fn(...[2 .. -1] .words) if(.alljoin(.words): join " ", .words) +# amb expects 2 or more arguments +val amb = fn ...[2..] words: if alljoin(words) { join " ", words } -writeln join "\n", filter mapX .amb, .wordsets... +writeln join("\n", filter(mapX(amb, wordsets...))) diff --git a/Task/Anagrams/Emacs-Lisp/anagrams-1.l b/Task/Anagrams/Emacs-Lisp/anagrams-1.l new file mode 100644 index 0000000000..9920fae43d --- /dev/null +++ b/Task/Anagrams/Emacs-Lisp/anagrams-1.l @@ -0,0 +1,87 @@ +(defun code-letters (str) + "Sort STR into alphabetized list of individual letters." + (sort (split-string str "" t) #'string<)) + +(defun code-letters-to-string (str) + "Sort STR alphabetically and combine into one string." + (apply #'concat (code-letters str))) + +(defun remove-periods (str) + "Remove periods (full stops) from STR." + (string-replace "." "" str)) + +(defun list-pair (str) + "Create paired list from STR, STR (unchanged) and alphabetized order of STR." + ;; Remove periods from alphabetized order to make regex matching easier + (let ((letter-list (remove-periods (code-letters-to-string str)))) + (list letter-list str))) + +(defun pair-up (words) + "Make list of lists of paired words, one alphabetized one original." + (let ((paired-list) + (temp-pair)) + (dolist (word words) + (setq temp-pair (list-pair word)) + (push temp-pair paired-list)) + paired-list)) + +(defun create-list-of-numbers (my-list) + "Create list of numbers from MY-LIST." + (let ((list-of-numbers)) + (dolist (one-pair my-list) + (push (car one-pair) list-of-numbers)) + list-of-numbers)) + +(defun get-largest-number (my-list) + "Find largest number in MY-LIST." + (let ((list-of-numbers)) + (setq list-of-numbers (create-list-of-numbers my-list)) + (apply #'max list-of-numbers))) + +(defun make-list-matching-words (coded-word-and-original number-and-code-pair) + "List original words whose code matches code in NUMBER-AND-CODE-PAIR." + (dolist (word-pair coded-word-and-original) + ;; test if coded word in CODED-WORD-AND-ORIGINAL matches + ;; coded word in NUMBER-AND-CODE-PAIR + (when (string= (nth 0 word-pair) (nth 1 number-and-code-pair)) + ;; insert the original word + (insert (format "%s " (nth 1 word-pair))))) + (insert "\n")) + +(defun count-anagrams () + "Count the number of anagrams in file wordlist.txt" + (let ((coded-word-and-original) + (just-coded-words) + (unique-coded-words) + (count-and-code) + (number-of-anagrams) + (largest-number)) + ;; Path below needs to be adapted to individual case + (find-file "~/Documents/Elisp/wordlist.txt") + (beginning-of-buffer) + ;; create list of lists of coded words and originals + (setq coded-word-and-original (pair-up (split-string (buffer-string) "\n"))) + (find-file "temp-all-coded") + (erase-buffer) + (dolist (number-and-code-pair coded-word-and-original) + ;; make list of just the coded words + (push (nth 0 number-and-code-pair) just-coded-words)) + (dolist (one-word just-coded-words) + ;; write list of coded words to buffer for later processing + (insert (format "%s\n" one-word))) + ;; create a list of coded words with no repetitions + (setq unique-coded-words (seq-uniq just-coded-words)) + (dolist (one-code unique-coded-words) + (find-file "temp-all-coded") + (beginning-of-buffer) + ;; count the number of times ONE-CODE appears in buffer + (setq number-of-anagrams (how-many (format "^%s$" one-code))) + (if (>= number-of-anagrams 1) ; eliminate "words" of zero length + (push (list number-of-anagrams one-code) count-and-code))) + (find-file "anagram-listing") + (erase-buffer) + (setq largest-number (get-largest-number count-and-code)) + (dolist (number-and-code-pair count-and-code) + ;; when the number in NUMBER-AND-CODE-PAIR = largest number of anagrams + (when (= (nth 0 number-and-code-pair) largest-number) + (make-list-matching-words coded-word-and-original number-and-code-pair))))) diff --git a/Task/Anagrams/Emacs-Lisp/anagrams-2.l b/Task/Anagrams/Emacs-Lisp/anagrams-2.l new file mode 100644 index 0000000000..4a6a2b9b3d --- /dev/null +++ b/Task/Anagrams/Emacs-Lisp/anagrams-2.l @@ -0,0 +1,74 @@ +(defun code-letters (str) + "Sort STR into alphabetized list of individual letters." + (sort (split-string str "" t) #'string<)) + +(defun code-letters-to-string (str) + "Sort STR alphabetically and combine into one string." + (apply #'concat (code-letters str))) + +(defun add-to-hash (key value table) + "If KEY exists, add VALUE to list of values. +If KEY does not exist, associate value with KEY." + (let ((current-values)) + (if (gethash key table) + (progn + (setq current-values (gethash key table)) + (setq current-values (push value current-values)) + (puthash key current-values table)) + (puthash key (list value) table)))) + +(defun create-list-of-numbers (hash-table) + "Create a list of numbers from HASH-TABLE." + (let ((current-number) + (list-of-numbers)) + (setq list-of-numbers (list)) ; omit? + (maphash (lambda (key value) + (setq current-number (car (gethash key hash-table))) + (push current-number list-of-numbers)) + hash-table) + list-of-numbers)) + +(defun find-largest-number-in-hash (hash-table) + "Find largest number in HASH-TABLE." + (let ((list-of-numbers)) + (setq list-of-numbers (create-list-of-numbers hash-table)) + (apply #'max list-of-numbers))) + +(defun find-longest-lists-of-anagrams (&optional file) + "Find the set(s) of largest number of anagrams in file wordlist.txt" + (let ((largest-number) + (hash-key) + (dictionary-table (make-hash-table :test 'equal))) + ;; Path and filename below needs to be adapted to individual case if + ;; FILE is *not* passed to this function + (with-temp-buffer + (insert-file-contents (or file "~/Documents/Elisp/wordlist.txt")) + (beginning-of-buffer) + ;; set up hash table with key and word(s) + ;; key = letters of word, but with letters in + ;; alphabetical order. Create list word(s) associated + ;; with key. + (dolist (current-word (split-string (buffer-string) "\n")) + (setq hash-key (code-letters-to-string current-word)) + (add-to-hash hash-key current-word dictionary-table)) + ;; Count number of anagram words + (maphash (lambda (key value) + "Add number of anagram words to VALUE." + (add-to-hash key (length (gethash key dictionary-table)) dictionary-table)) + dictionary-table) + ;; find the size of the largest list(s) of anagrams + (setq largest-number (find-largest-number-in-hash dictionary-table))) + ;; set up empty buffer to show results + (with-current-buffer (pop-to-buffer "anagram-listing") + (erase-buffer) + ;; show results + (maphash (lambda (key value) + "Display longest lists of anagrams." + (when (= largest-number (car (gethash key dictionary-table))) + (mapc + (lambda (element) + "Insert ELEMENT followed by one space in buffer." + (insert (format "%s " element))) + (cdr (gethash key dictionary-table))) + (insert "\n"))) + dictionary-table)))) diff --git a/Task/Anagrams/PascalABC.NET/anagrams.pas b/Task/Anagrams/PascalABC.NET/anagrams.pas new file mode 100644 index 0000000000..937517fc8e --- /dev/null +++ b/Task/Anagrams/PascalABC.NET/anagrams.pas @@ -0,0 +1,7 @@ +begin + var s := System.Net.WebClient.Create.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); + var words := s.Split; + var groups := words.GroupBy(word -> word.Order.JoinToString); + var maxCount := groups.Max(gr -> gr.Count); + groups.Where(gr -> gr.Count = maxCount).PrintLines; +end. diff --git a/Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-1.pas b/Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-1.pas new file mode 100644 index 0000000000..6b5e0f0b76 --- /dev/null +++ b/Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-1.pas @@ -0,0 +1,13 @@ +function Fib(n: integer): integer; +begin + if n <= 0 then + raise new System.ArgumentOutOfRangeException('Must be > 0','n'); + var fibHelper: (integer,integer,integer) -> integer; + fibHelper := (n,a,b) -> n = 1 ? a : fibHelper(n-1, b, a + b); + Result := fibHelper(n,1,1); +end; + +begin + for var i:=1 to 10 do + Fib(i).Print; +end. diff --git a/Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-2.pas b/Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-2.pas new file mode 100644 index 0000000000..70ab8a191f --- /dev/null +++ b/Task/Anonymous-recursion/PascalABC.NET/anonymous-recursion-2.pas @@ -0,0 +1,13 @@ +function Fib(n: integer): integer; + function fibHelper(n,a,b: integer): integer := + n = 1 ? a : fibHelper(n-1, b, a + b); +begin + if n <= 0 then + raise new System.ArgumentOutOfRangeException('Must be > 0','n'); + Result := fibHelper(n,1,1); +end; + +begin + for var i:=1 to 10 do + Fib(i).Print; +end. diff --git a/Task/Anti-primes/Langur/anti-primes.langur b/Task/Anti-primes/Langur/anti-primes.langur index 1bd79d0c33..42efda2dc6 100644 --- a/Task/Anti-primes/Langur/anti-primes.langur +++ b/Task/Anti-primes/Langur/anti-primes.langur @@ -1,18 +1,18 @@ -val .countDivisors = fn(.n) { - if .n < 2: return 1 - for[=2] .i = 2; .i <= .n\2; .i += 1 { - if .n div .i : _for += 1 +val countDivisors = fn(n) { + if n < 2: return 1 + for[=2] i = 2; i <= n\2; i += 1 { + if n div i: _for += 1 } } writeln "The first 20 anti-primes are:" -var .maxDiv, .count = 0, 0 -for .n = 1; .count < 20; .n += 1 { - val .d = .countDivisors(.n) - if .d > .maxDiv { - write .n, " " - .maxDiv = .d - .count += 1 +var maxDiv, cnt = 0, 0 +for n = 1; cnt < 20; n += 1 { + val d = countDivisors(n) + if d > maxDiv { + write n, " " + maxDiv = d + cnt += 1 } } writeln() diff --git a/Task/Anti-primes/Uiua/anti-primes.uiua b/Task/Anti-primes/Uiua/anti-primes.uiua new file mode 100644 index 0000000000..167480c2c1 --- /dev/null +++ b/Task/Anti-primes/Uiua/anti-primes.uiua @@ -0,0 +1,8 @@ +# slightly faster than the simplistic /+=0◿+1⇡. +NDivs ← ⟨+2/+=0◿(↘1+1⇡⌊÷2).|1⟩<2. +⇌⊙◌◌⍢( + # Inc n, get NDiv: if >m, join n to accum, store new m. + ⟨◌|⟜(⊂⊢)⍜(⊡1|◌):⟩:⟜ x * x).ToArray; + a.ForEach(x -> Print(x)); +end. diff --git a/Task/Approximate-equality/EasyLang/approximate-equality.easy b/Task/Approximate-equality/EasyLang/approximate-equality.easy new file mode 100644 index 0000000000..910f89b4d4 --- /dev/null +++ b/Task/Approximate-equality/EasyLang/approximate-equality.easy @@ -0,0 +1,20 @@ +func aeq a b . + return if abs (a - b) <= abs a * 1e-14 +. +proc test a b . . + write a & " " & b & " -> " + if aeq a b = 1 + print "true" + else + print "false" + . +. +numfmt 10 0 +test 100000000000000.01 100000000000000.011 +test 100.01 100.011 +test 10000000000000.001 / 10000 1000000000.0000001 +test 0.001 0.0010000001 +test 1.01e-22 0 +test sqrt 2 * sqrt 2 2 +test -sqrt 2 * sqrt 2 -2 +test 3.14159265358979323846 3.14159265358979324 diff --git a/Task/Arbitrary-precision-integers-included-/FutureBasic/arbitrary-precision-integers-included-.basic b/Task/Arbitrary-precision-integers-included-/FutureBasic/arbitrary-precision-integers-included-.basic new file mode 100644 index 0000000000..60598c768c --- /dev/null +++ b/Task/Arbitrary-precision-integers-included-/FutureBasic/arbitrary-precision-integers-included-.basic @@ -0,0 +1,64 @@ +/* + +Uses GMP for Multiple Precision Arithmetic +Install GMP using terminal and Homebrew command, "brew install gmp" +before running this app in FutureBasic. + +Homebrew available here, https://brew.sh + +*/ + + +include "NSLog.incl" + +void local fn GMPoutput + CFStringRef sourcePath = fn StringByAppendingPathComponent( @"/tmp/", @"temp.m" ) + CFStringRef executablePath = fn StringByAppendingPathComponent( @"/tmp/", @"temp" ) + CFStringRef gmpStr = @"#import \n#import \n¬ + int main(int argc, const char * argv[]) {\n¬ + @autoreleasepool {\n¬ + mpz_t a;\n¬ + mpz_init_set_ui(a, 5);\n¬ + mpz_pow_ui(a, a, 1 << 18);\n¬ + size_t len = mpz_sizeinbase(a, 10);\n¬ + printf(\"GMP says size is: %zu\\n\", len);\n¬ + char *s = mpz_get_str(0, 10, a);\n¬ + size_t trueLen = strlen(s);\n¬ + printf(\" Actual size is: %zu\\n\", trueLen);\n¬ + printf(\"First & Last 20 digits: %.20s…%s\\n\", s, s + trueLen - 20);\n¬ + }\n¬ + return 0;\n¬ + }" + fn StringWriteToURL( gmpStr, fn URLFileURLWithPath( sourcePath ), YES, NSUTF8StringEncoding, NULL ) + + TaskRef task = fn TaskInit + TaskSetExecutableURL( task, fn URLFileURLWithPath( @"usr/bin/clang" ) ) + CFArrayRef arguments = @[@"-o", executablePath, sourcePath, @"-lgmp", @"-fobjc-arc"] + TaskSetArguments( task, arguments ) + PipeRef pipe = fn PipeInit + TaskSetStandardInput( task, pipe ) + fn TaskLaunch( task, NULL ) + TaskWaitUntilExit( task ) + + if ( fn TaskTerminationStatus( task ) == 0 ) + TaskRef executionTask = fn TaskInit + TaskSetExecutableURL( executionTask, fn URLFileURLWithPath( executablePath ) ) + PipeRef executionPipe = fn PipeInit + TaskSetStandardOutput( executionTask, executionPipe ) + FileHandleRef executionFileHandle = fn PipeFileHandleForReading( executionPipe ) + fn TaskLaunch( executionTask, NULL ) + TaskWaitUntilExit( executionTask ) + CFDataRef outputData = fn FileHandleReadDataToEndOfFile( executionFileHandle, NULL ) + CFStringRef outputStr = fn StringWithData( outputData, NSUTF8StringEncoding ) + NSLog( @"%@", outputStr ) + else + alert 1,, @"GMP required but not installed" + end if + + fn FileManagerRemoveItemAtURL( fn URLFileURLWithPath( sourcePath ) ) + fn FileManagerRemoveItemAtURL( fn URLFileURLWithPath( executablePath ) ) +end fn + +fn GMPoutput + +HandleEvents diff --git a/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur b/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur index 94c3c2d9ff..ac88ad929c 100644 --- a/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur +++ b/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur @@ -1,9 +1,9 @@ -val .xs = string 5 ^ 4 ^ 3 ^ 2 +val xs = string(5 ^ 4 ^ 3 ^ 2) -val .len = len .xs -writeln .len, " digits" +writeln len(xs), " digits" + +if len(xs) > 39 and s2s(xs, 1..20) == "62060698786608744707" and + s2s(xs, -20 .. -1) == "92256259918212890625" { -if .len > 39 and s2s(.xs, 1..20) == "62060698786608744707" and - s2s(.xs, .len-19 .. .len) == "92256259918212890625" { writeln "SUCCESS" } diff --git a/Task/Arena-storage-pool/Java/arena-storage-pool.java b/Task/Arena-storage-pool/Java/arena-storage-pool.java new file mode 100644 index 0000000000..2bfb0bc428 --- /dev/null +++ b/Task/Arena-storage-pool/Java/arena-storage-pool.java @@ -0,0 +1,19 @@ +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +public final class ArenaStoragePool { + + public static void main(String[] args) { + List storagePool = new ArrayList(); + storagePool.addLast(42); + storagePool.addLast("Hello World"); + storagePool.addFirst(BigInteger.ZERO); + + System.out.println(storagePool); + + storagePool = null; + System.gc(); + } + +} diff --git a/Task/Arithmetic-Complex/EasyLang/arithmetic-complex.easy b/Task/Arithmetic-Complex/EasyLang/arithmetic-complex.easy new file mode 100644 index 0000000000..2e8ba7e31a --- /dev/null +++ b/Task/Arithmetic-Complex/EasyLang/arithmetic-complex.easy @@ -0,0 +1,19 @@ +func[] add a[] b[] . + return [ a[1] + b[1] a[2] + b[2] ] +. +func[] mult a[] b[] . + return [ a[1] * b[1] - a[2] * b[2] a[1] * b[2] + a[2] * b[1] ] +. +func[] inv a[] . + denom = a[1] * a[1] + a[2] * a[2] + return [ a[1] / denom (-a[2] / denom) ] +. +func[] neg a[] . + return [ -a[1] (-a[2]) ] +. +a[] = [ 1 1 ] +b[] = [ pi 1.2 ] +print add a[] b[] +print mult a[] b[] +print neg a[] +print inv a[] diff --git a/Task/Arithmetic-Complex/PascalABC.NET/arithmetic-complex.pas b/Task/Arithmetic-Complex/PascalABC.NET/arithmetic-complex.pas new file mode 100644 index 0000000000..7a815bfcc7 --- /dev/null +++ b/Task/Arithmetic-Complex/PascalABC.NET/arithmetic-complex.pas @@ -0,0 +1,14 @@ +begin + var a := Cplx(1,2); + var b := Cplx(3,4); + Println(a + b); + Println(a - b); + Println(a * b); + Println(a / b); + Println(-a); + Println(1/a); + Println(a.Real,a.Imaginary); + Println(a.Conjugate); + Println(Abs(a)); + Println(a ** b); +end. diff --git a/Task/Arithmetic-Integer/EMal/arithmetic-integer.emal b/Task/Arithmetic-Integer/EMal/arithmetic-integer.emal index 88c6e2ec31..ace44f0c7e 100644 --- a/Task/Arithmetic-Integer/EMal/arithmetic-integer.emal +++ b/Task/Arithmetic-Integer/EMal/arithmetic-integer.emal @@ -23,7 +23,6 @@ fun main = int by List args writeLine("integer quotient: " + (a / b)) # truncates towards 0 writeLine("remainder: " + (a % b)) # matches sign of first operand writeLine("exponentiation: " + (a ** b)) - writeLine("logarithm: " + (a // b)) writeLine("divmod: " + divmod(a, b)) return 0 end diff --git a/Task/Arithmetic-Integer/PascalABC.NET/arithmetic-integer.pas b/Task/Arithmetic-Integer/PascalABC.NET/arithmetic-integer.pas new file mode 100644 index 0000000000..e67c8a33bb --- /dev/null +++ b/Task/Arithmetic-Integer/PascalABC.NET/arithmetic-integer.pas @@ -0,0 +1,10 @@ +begin + var (a,b) := ReadInteger2; + Println($'{a} + {b} = {a + b}'); + Println($'{a} - {b} = {a - b}'); + Println($'{a} * {b} = {a * b}'); + Println($'{a} / {b} = {a / b}'); + Println($'{a} div {b} = {a div b}'); + Println($'{a} mod {b} = {a mod b}'); + Println($'{a} ** {b} = {a ** b}'); +end. diff --git a/Task/Arithmetic-derivative/R/arithmetic-derivative.r b/Task/Arithmetic-derivative/R/arithmetic-derivative.r new file mode 100644 index 0000000000..e86c844300 --- /dev/null +++ b/Task/Arithmetic-derivative/R/arithmetic-derivative.r @@ -0,0 +1,31 @@ +library(gmp) #for big number factorization + +arithmetic_derivative<-function(x){ + if (x==0|x==1|x==-1){ + D=0 + } + else{ + n=ifelse(x<0,-x,x) + prime_decomposition <-as.numeric(factorize(n)) + if (length(prime_decomposition)==1){ + D<- 1 + } + else{ + D<-sum(prime_decomposition[c(1,2)]) + if (length(prime_decomposition)>2){ + cumulative_prod <-cumprod(prime_decomposition) + for (i in 3:length(prime_decomposition)){ + D<- D * prime_decomposition[i] + cumulative_prod[i-1] + } + } + } + + } + sign(x)*D +} + +print(t(matrix(sapply(-99:100,arithmetic_derivative),nrow=10))) + +for (k in 1:20){ + x <- 10**k + cat(paste0("D(",x,")/7 = ",arithmetic_derivative(x)/7,"\n"),sep = "")} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Ada/arithmetic-geometric-mean-calculate-pi.ada b/Task/Arithmetic-geometric-mean-Calculate-Pi/Ada/arithmetic-geometric-mean-calculate-pi.ada new file mode 100644 index 0000000000..92bbf6746a --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Ada/arithmetic-geometric-mean-calculate-pi.ada @@ -0,0 +1,34 @@ +-- Use the Arithmetic-geometric mean to calculate Pi +-- J. Carter 2024 May + +with Ada.Numerics.Generic_Elementary_Functions; +with Ada.Text_IO; +with System; + +procedure AGM_Pi is + type Real is digits System.Max_Digits; + + package Math is new Ada.Numerics.Generic_Elementary_Functions (Float_Type => Real); + + A : Real := 1.0; + B : Real := Math.Sqrt (0.5); + T : Real := 0.25; + N : Real := 1.0; + Prev_A : Real; + Pi : Real; + Prev_Pi : Real := 0.0; +begin -- AGM_Pi + Calculate : loop + Prev_A := A; + A := (A + B) / 2.0; + B := Math.Sqrt (Prev_A * B); + T := T - N * (A - Prev_A) ** 2; + N := N + N; + Pi := (A + B) ** 2 / (4.0 * T); + Ada.Text_IO.Put_Line (Item => Pi'Image); + + exit Calculate when abs (Prev_Pi - Pi) < 10.0 ** (-(Real'Digits - 1) ); + + Prev_Pi := Pi; + end loop Calculate; +end AGM_Pi; diff --git a/Task/Arithmetic-geometric-mean/Uiua/arithmetic-geometric-mean.uiua b/Task/Arithmetic-geometric-mean/Uiua/arithmetic-geometric-mean.uiua new file mode 100644 index 0000000000..6a89ccb923 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Uiua/arithmetic-geometric-mean.uiua @@ -0,0 +1,3 @@ +# Calculate the arithmetic-geometric mean +Agm ← ⊙◌◌⍢(⊃(√×|÷2+)|<⌵-) +Agm 1 ÷:1√2 0.0000001 diff --git a/Task/Array-concatenation/Langur/array-concatenation.langur b/Task/Array-concatenation/Langur/array-concatenation.langur index 1ac9ef60b4..a94a31915b 100644 --- a/Task/Array-concatenation/Langur/array-concatenation.langur +++ b/Task/Array-concatenation/Langur/array-concatenation.langur @@ -1,4 +1,4 @@ -val .a = [1, 2, 3] -val .b = [7, 8, 9] -val .c = .a ~ .b -writeln .c +val a = [1, 2, 3] +val b = [7, 8, 9] +val c = a ~ b +writeln c diff --git a/Task/Array-concatenation/PascalABC.NET/array-concatenation.pas b/Task/Array-concatenation/PascalABC.NET/array-concatenation.pas new file mode 100644 index 0000000000..45499f1327 --- /dev/null +++ b/Task/Array-concatenation/PascalABC.NET/array-concatenation.pas @@ -0,0 +1,5 @@ +## +var a := |1,2,3,4|; +var b := Arr(5..8); +var c := a + b; +c.Println; diff --git a/Task/Array-concatenation/Uiua/array-concatenation.uiua b/Task/Array-concatenation/Uiua/array-concatenation.uiua new file mode 100644 index 0000000000..54cb6c7141 --- /dev/null +++ b/Task/Array-concatenation/Uiua/array-concatenation.uiua @@ -0,0 +1 @@ +⊂[1 2 3] [4 5 6] diff --git a/Task/Array-length/PascalABC.NET/array-length.pas b/Task/Array-length/PascalABC.NET/array-length-1.pas similarity index 100% rename from Task/Array-length/PascalABC.NET/array-length.pas rename to Task/Array-length/PascalABC.NET/array-length-1.pas diff --git a/Task/Array-length/PascalABC.NET/array-length-2.pas b/Task/Array-length/PascalABC.NET/array-length-2.pas new file mode 100644 index 0000000000..a804662be2 --- /dev/null +++ b/Task/Array-length/PascalABC.NET/array-length-2.pas @@ -0,0 +1,4 @@ +// Array length. Mikhalkovich Stanislav: May 16, 2024 +## +var a := |'apple','orange'|; +a.Length.Print; diff --git a/Task/Array-length/Uiua/array-length.uiua b/Task/Array-length/Uiua/array-length.uiua new file mode 100644 index 0000000000..cc0a198a7f --- /dev/null +++ b/Task/Array-length/Uiua/array-length.uiua @@ -0,0 +1 @@ +⧻{"apple" "orange"} diff --git a/Task/Arrays/Ada/arrays.ada b/Task/Arrays/Ada/arrays.ada index b713c838f7..b9a90bba0b 100644 --- a/Task/Arrays/Ada/arrays.ada +++ b/Task/Arrays/Ada/arrays.ada @@ -1,9 +1,10 @@ procedure Array_Test is - A, B : array (1..20) of Integer; + type Example_Array_Type is array (1..20) of Integer; + A, B : Example_Array_Type; -- Ada array indices may begin at any value, not just 0 or 1 - C : array (-37..20) of integer + C : array (-37..20) of Integer; -- Ada arrays may be indexed by enumerated types, which are -- discrete non-numeric types @@ -26,7 +27,7 @@ procedure Array_Test is Const : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3); Centered : Arr (-50..50) := (0 => 1, Others => 0); - Result : Integer + Result : Integer; begin A := (others => 0); -- Assign whole array @@ -37,7 +38,7 @@ begin A (3..5) := (2, 4, -1); -- Assign a constant slice A (3..5) := A (4..6); -- It is OK to overlap slices when assigned - Fingers_Extended'First := False; -- Set first element of array - Fingers_Extended'Last := False; -- Set last element of array + Fingers_Extended(Fingers'First) := False; -- Set first element of array + Fingers_Extended(Fingers'Last) := False; -- Set last element of array end Array_Test; diff --git a/Task/Arrays/Langur/arrays.langur b/Task/Arrays/Langur/arrays.langur index 3013d73448..5b0916e890 100644 --- a/Task/Arrays/Langur/arrays.langur +++ b/Task/Arrays/Langur/arrays.langur @@ -1,24 +1,24 @@ -var .a1 = [1, 2, 3, "abc"] -val .a2 = series 4..10 -val .a3 = .a1 ~ .a2 +var a1 = [1, 2, 3, "abc"] +val a2 = series(4..10) +val a3 = a1 ~ a2 writeln "initial values ..." -writeln ".a1: ", .a1 -writeln ".a2: ", .a2 -writeln ".a3: ", .a3 +writeln "a1: ", a1 +writeln "a2: ", a2 +writeln "a3: ", a3 writeln() -.a1[4] = .a2[4] -writeln "after setting .a1[4] = .a2[4] ..." -writeln ".a1: ", .a1 -writeln ".a2: ", .a2 -writeln ".a3: ", .a3 +a1[4] = a2[4] +writeln "after setting a1[4] = a2[4] ..." +writeln "a1: ", a1 +writeln "a2: ", a2 +writeln "a3: ", a3 writeln() -writeln ".a2[1]: ", .a2[1] +writeln "a2[1]: ", a2[1] writeln() writeln "using index alternate ..." -writeln ".a2[5; 0]: ", .a2[5; 0] -writeln ".a2[10; 0]: ", .a2[10; 0] +writeln "a2[5; 0]: ", a2[5; 0] +writeln "a2[10; 0]: ", a2[10; 0] writeln() diff --git a/Task/Arrays/PascalABC.NET/arrays.pas b/Task/Arrays/PascalABC.NET/arrays.pas new file mode 100644 index 0000000000..f62890edc5 --- /dev/null +++ b/Task/Arrays/PascalABC.NET/arrays.pas @@ -0,0 +1,19 @@ +begin + // Static old-style arrays + var a: array [1..3] of integer := (1,2,3); + Println(a[1]); + + // dynamic arrays - zero based indices + var a1: array of integer := new integer[3](1,3,5); + Println(a1[0]); + + // dynamic arrays + var a2 := |1,3,5|; // literal array + SetLength(a2,4); + a2[^1] := 7; // "push" new value; ^1 - the first element from the end + + // Lists are dynamically resizing arrays + var lst := new List(a1); + lst.Add(7); + Println(lst[^1]); +end. diff --git a/Task/Ascending-primes/Ada/ascending-primes.ada b/Task/Ascending-primes/Ada/ascending-primes.ada new file mode 100644 index 0000000000..f3cbb7f3fa --- /dev/null +++ b/Task/Ascending-primes/Ada/ascending-primes.ada @@ -0,0 +1,62 @@ +pragma Ada_2022; + +with Ada.Text_IO; +with Ada.Containers.Vectors; +with Fifo; + +procedure Ascending_Primes is + + subtype Prime is Positive range 2 .. Positive'Last with + Dynamic_Predicate => + (for all I in 2 .. (Prime / 2) => (Prime mod I) /= 0); + + package Prime_Vectors is new + Ada.Containers.Vectors + (Index_Type => Natural, + Element_Type => Prime); + + package Positive_Fifo is new Fifo (Positive); + use Positive_Fifo; + + -- Helper queue and vector for primes found + Queue : Fifo_Type; + Primes : Prime_Vectors.Vector; + +begin + -- Initialise the queue with the first nine numbers + for Index in 1 .. 9 loop + Queue.Push (Index); + end loop; + + -- Read the canditate numbers from the queue + -- check if they are prime and generate + -- the next possible candidates from them + while not Queue.Is_Empty loop + declare + Candidate : Positive; + Next_Digit : Positive; + begin + Queue.Pop (Candidate); + + if Candidate in Prime then + Primes.Append (Candidate); + end if; + + -- Generate the next possible candidates + -- from the current one + Next_Digit := Candidate mod 10 + 1; + while Next_Digit <= 9 loop + Queue.Push (Candidate * 10 + Next_Digit); + Next_Digit := @ + 1; + end loop; + + end; + end loop; + + -- Print the final list of prime numbers + for P of Primes loop + Ada.Text_IO.Put (P'Image); + end loop; + Ada.Text_IO.New_Line; + +end Ascending_Primes; diff --git a/Task/Ascending-primes/Uiua/ascending-primes.uiua b/Task/Ascending-primes/Uiua/ascending-primes.uiua new file mode 100644 index 0000000000..a92ef59960 --- /dev/null +++ b/Task/Ascending-primes/Uiua/ascending-primes.uiua @@ -0,0 +1,2 @@ +/◇⊂{⍥(/◇⊂≡(□+×10:↘+1◿10,⇡10).)8 +1⇡9} # Build ascending numbers. +⊏⊸⍏▽⊸≡(=1⧻°/×) # Find primes and sort. diff --git a/Task/Assertions/Ecstasy/assertions.ecstasy b/Task/Assertions/Ecstasy/assertions.ecstasy new file mode 100644 index 0000000000..12b6825568 --- /dev/null +++ b/Task/Assertions/Ecstasy/assertions.ecstasy @@ -0,0 +1,6 @@ +module test { + void run() { + Int x = 7; + assert x == 42; + } +} diff --git a/Task/Assertions/PascalABC.NET/assertions.pas b/Task/Assertions/PascalABC.NET/assertions.pas new file mode 100644 index 0000000000..ee22dd0991 --- /dev/null +++ b/Task/Assertions/PascalABC.NET/assertions.pas @@ -0,0 +1,5 @@ +begin + var a := 3; + Assert(a = 3); + Assert(a = 4, 'Bad assert!'); +end. diff --git a/Task/Associative-array-Creation/Langur/associative-array-creation.langur b/Task/Associative-array-Creation/Langur/associative-array-creation.langur index 86b466f1a4..0ae1824628 100644 --- a/Task/Associative-array-Creation/Langur/associative-array-creation.langur +++ b/Task/Associative-array-Creation/Langur/associative-array-creation.langur @@ -1,12 +1,12 @@ -var .hash = h{1: "abc", "1": 789} +var h = {1: "abc", "1": 789} # may assign with existing or non-existing hash key (if hash is mutable) -.hash[7] = 49 +h[7] = 49 -writeln .hash[1] -writeln .hash[7] -writeln .hash["1"] +writeln h[1] +writeln h[7] +writeln h["1"] # using an alternate value in case of invalid index; prevents exception -writeln .hash[1; 42] -writeln .hash[2; 42] +writeln h[1; 42] +writeln h[2; 42] diff --git a/Task/Associative-array-Creation/PascalABC.NET/associative-array-creation.pas b/Task/Associative-array-Creation/PascalABC.NET/associative-array-creation.pas new file mode 100644 index 0000000000..3c5b9e0348 --- /dev/null +++ b/Task/Associative-array-Creation/PascalABC.NET/associative-array-creation.pas @@ -0,0 +1,7 @@ +begin + var zoo := new Dictionary; + zoo['crocodile'] := 2; + zoo['jiraffe'] := 3; + zoo['behemoth'] := 1; + zoo.Println; +end. diff --git a/Task/Associative-array-Iteration/PascalABC.NET/associative-array-iteration.pas b/Task/Associative-array-Iteration/PascalABC.NET/associative-array-iteration.pas new file mode 100644 index 0000000000..0d9d5f7fa5 --- /dev/null +++ b/Task/Associative-array-Iteration/PascalABC.NET/associative-array-iteration.pas @@ -0,0 +1,11 @@ +begin + var zoo := new Dictionary; + zoo['crocodile'] := 2; + zoo['jiraffe'] := 3; + zoo['behemoth'] := 1; + foreach var kv in zoo do + Println(kv.Key, kv.Value); + Println; + foreach var key in zoo.Keys do + Println(key,zoo[key]); +end. diff --git a/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur b/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur index 6c700294e7..f313eb66b4 100644 --- a/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur +++ b/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur @@ -1,4 +1,4 @@ -val .mean = fn(.x) fold(fn{+}, .x) / len(.x) +val umean = fn x:fold(fn{+}, x) / len(x) -writeln " custom: ", .mean([7, 3, 12]) +writeln " custom: ", umean([7, 3, 12]) writeln "built-in: ", mean([7, 3, 12]) diff --git a/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua b/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua new file mode 100644 index 0000000000..291cc80510 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua @@ -0,0 +1,24 @@ +# Find mean time of day using 'mean angle' + +ParseTS ← setinv(/(+×60)⊜⋕≠@:.|/(◇⊂◇⊂)@:≡(□↙¯2⊂"00"°⋕)⌊[⍥(⊃÷◿60)2]) +RpS ← ×π÷180÷240 1 # Radians per second +SpD ← ×× 24 60 60 # Seconds per day +Cos ← setinv(∿+η|-:η°∿) +# Polar to (complex) cartesian, and inverse. +PtoC ← setinv( + ℂ⍜⊟×⊃∿Cos:°⊟ +| √+∩(×.),⟜:°ℂ + ⍤("undefined for r=0")≠0. + ⊟⟜(⍥¯<0:°Cos÷) +) + +Ts ← "23:00:17, 23:40:20, 00:12:45, 00:17:19" +⊜(PtoC ⊟1 ×RpS ParseTS)¬⦷", ".Ts # Get TSs as unit complex numbers. +⁅÷RpS⊡1°PtoC÷⊃(⧻|/+) # Average them and convert back to seconds. +°ParseTS+×SpD<0. # Ensure its >0, format as TS. + + +{{out}} +
+"23:47:43"
+
diff --git a/Task/Averages-Simple-moving-average/Jq/averages-simple-moving-average.jq b/Task/Averages-Simple-moving-average/Jq/averages-simple-moving-average.jq new file mode 100644 index 0000000000..f71cc8455e --- /dev/null +++ b/Task/Averages-Simple-moving-average/Jq/averages-simple-moving-average.jq @@ -0,0 +1,30 @@ +# The input should be a JSON object with a key named "period". +# The output is a JSON object with a key named "average" giving the SMA. +def sma($x): + def average: + .n as $n + | if $n == null or $n == 0 then . + {n: 1, average: $x} + else .average |= (. * $n + $x) / ($n + 1) + | .n += 1 + end; + + if . == null or (.period and .period < 1) + then "The initial call to sma/1 must specify the period properly" | error + elif .n and .n < 0 then "Invalid value of .n" | error + elif (.period | isinfinite) then average + elif .n == null or .n == 0 then . + {n: 1, average: $x, array: [$x]} + else .n as $n + | if $n < .period + then .array += [$x] + | .n += 1 + else .array |= .[1:] + [$x] + end + | .average = (.array | (add/length)) + end; + +# Call sma($x) for the 11 numbers 0, 1, ... 10. +def example($period): + reduce range(0;11) as $x({period: $period}; sma($x)) + | .average ; + +example(11), example(infinite) diff --git a/Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-1.basic b/Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-1.basic new file mode 100644 index 0000000000..f872c7192b --- /dev/null +++ b/Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-1.basic @@ -0,0 +1,162 @@ +' The control points of a planar quadratic Bézier curve form a +' triangle--called the "control polygon"--that completely contains +' the curve. Furthermore, the rectangle formed by the minimum and +' maximum x and y values of the control polygon completely contain +' the polygon, and therefore also the curve. +' +' Thus a simple method for narrowing down where intersections might +' be is: subdivide both curves until you find "small enough" regions +' where these rectangles overlap. + +#define Min(a, b) iif((a) < (b), (a), (b)) +#define Max(a, b) iif((a) > (b), (a), (b)) + +' Note that these are all mutable as we need to pass by reference. +Type Punto + x As Double + y As Double +End Type + +Type QuadSpline + c0 As Double + c1 As Double + c2 As Double ' Non-parametric spline +End Type + +Type QuadCurve + x As QuadSpline + y As QuadSpline ' Planar parametric spline +End Type + +' Subdivision by de Casteljau's algorithm +Sub subdivideQuadSpline(q As QuadSpline, t As Double, u As QuadSpline, v As QuadSpline) + Dim As Double s = 1.0 - t + Dim As Double c0 = q.c0 + Dim As Double c1 = q.c1 + Dim As Double c2 = q.c2 + u.c0 = c0 + v.c2 = c2 + u.c1 = s * c0 + t * c1 + v.c1 = s * c1 + t * c2 + u.c2 = s * u.c1 + t * v.c1 + v.c0 = u.c2 +End Sub + +Sub subdivideQuadCurve(q As QuadCurve, t As Double, u As QuadCurve, v As QuadCurve) + subdivideQuadSpline(q.x, t, u.x, v.x) + subdivideQuadSpline(q.y, t, u.y, v.y) +End Sub + +' It is assumed that xa0 <= xa1, ya0 <= ya1, xb0 <= xb1, and yb0 <= yb1. +Function rectsOverlap(xa0 As Double, ya0 As Double, xa1 As Double, ya1 As Double, _ + xb0 As Double, yb0 As Double, xb1 As Double, yb1 As Double) As Boolean + Return (xb0 <= xa1 And xa0 <= xb1 And yb0 <= ya1 And ya0 <= yb1) +End Function + +Function max3(x As Double, y As Double, z As Double) As Double + Return Max(Max(x, y), z) +End Function + +Function min3(x As Double, y As Double, z As Double) As Double + Return Min(Min(x, y), z) +End Function + +' This accepts the point as an intersection if the boxes are small enough. +Sub testIntersect(p As QuadCurve, q As QuadCurve, tol As Double, _ + Byref exclude As Boolean, Byref accept As Boolean, Byref intersect As Punto) + Dim As Double pxmin = min3(p.x.c0, p.x.c1, p.x.c2) + Dim As Double pymin = min3(p.y.c0, p.y.c1, p.y.c2) + Dim As Double pxmax = max3(p.x.c0, p.x.c1, p.x.c2) + Dim As Double pymax = max3(p.y.c0, p.y.c1, p.y.c2) + + Dim As Double qxmin = min3(q.x.c0, q.x.c1, q.x.c2) + Dim As Double qymin = min3(q.y.c0, q.y.c1, q.y.c2) + Dim As Double qxmax = max3(q.x.c0, q.x.c1, q.x.c2) + Dim As Double qymax = max3(q.y.c0, q.y.c1, q.y.c2) + exclude = True + accept = False + If rectsOverlap(pxmin, pymin, pxmax, pymax, qxmin, qymin, qxmax, qymax) Then + exclude = False + Dim As Double xmin = Max(pxmin, qxmin) + Dim As Double xmax = Min(pxmax, qxmax) + Assert(xmax >= xmin) + If xmax - xmin <= tol Then + Dim As Double ymin = Max(pymin, qymin) + Dim As Double ymax = Min(pymax, qymax) + Assert(ymax >= ymin) + If ymax - ymin <= tol Then + accept = True + intersect.x = 0.5 * xmin + 0.5 * xmax + intersect.y = 0.5 * ymin + 0.5 * ymax + End If + End If + End If +End Sub + +Function seemsToBeDuplicate(intersects() As Punto, icount As Integer, _ + xy As Punto, spacing As Double) As Boolean + Dim As Boolean seemsToBeDup = False + Dim As Integer i = 0 + While Not seemsToBeDup And i <> icount + Dim As Punto pt = intersects(i) + seemsToBeDup = Abs(pt.x - xy.x) < spacing And Abs(pt.y - xy.y) < spacing + i += 1 + Wend + Return seemsToBeDup +End Function + +Sub findIntersects(p As QuadCurve, q As QuadCurve, tol As Double, _ + spacing As Double, intersects() As Punto) + Dim As Integer numIntersects = 0 + Type workset + p As QuadCurve + q As QuadCurve + End Type + Dim As workset workload(64) + Dim As Integer numWorksets = 1 + workload(0) = Type(p, q) + + ' Quit looking after having emptied the workload. + While numWorksets <> 0 + Dim As workset work = workload(numWorksets-1) + numWorksets -= 1 + Dim As Boolean exclude, accept + Dim As Punto intersect + testIntersect(work.p, work.q, tol, exclude, accept, intersect) + If accept Then + ' To avoid detecting the same intersection twice, require some + ' space between intersections. + If Not seemsToBeDuplicate(intersects(), numIntersects, intersect, spacing) Then + intersects(numIntersects) = intersect + numIntersects += 1 + End If + Elseif Not exclude Then + Dim As QuadCurve p0, p1, q0, q1 + subdivideQuadCurve(work.p, 0.5, p0, p1) + subdivideQuadCurve(work.q, 0.5, q0, q1) + workload(numWorksets) = Type(p0, q0) + numWorksets += 1 + workload(numWorksets) = Type(p0, q1) + numWorksets += 1 + workload(numWorksets) = Type(p1, q0) + numWorksets += 1 + workload(numWorksets) = Type(p1, q1) + numWorksets += 1 + End If + Wend +End Sub + +Dim As QuadCurve p, q +p.x = Type(-1.0, 0.0, 1.0) +p.y = Type( 0.0, 10.0, 0.0) +q.x = Type( 2.0, -8.0, 2.0) +q.y = Type( 1.0, 2.0, 3.0) +Dim As Double tol = 0.0000001 +Dim As Double spacing = tol * 10.0 +Dim As Punto intersects(4) +findIntersects(p, q, tol, spacing, intersects()) +For i As Integer = 0 To 3 + Print "("; intersects(i).x; ", "; intersects(i).y; ")" +Next i + +Sleep diff --git a/Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-2.basic b/Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-2.basic new file mode 100644 index 0000000000..41eedb795f --- /dev/null +++ b/Task/B-zier-curves-Intersections/FreeBASIC/b-zier-curves-intersections-2.basic @@ -0,0 +1,215 @@ +' In this program, both of the curves are adaptively "flattened": +' that is, converted to a piecewise linear approximation. Then the +' problem is reduced to finding intersections of line segments. +' +' How efficient or inefficient the method is I will not try to answer. +' (And I do sometimes compute things "too often", although a really good +' optimizer might fix that.) +' +' I will use the symmetric power basis that was introduced by J. Sánchez-Reyes: +' +' J. Sánchez-Reyes, ‘The symmetric analogue of the polynomial power +' basis’, ACM Transactions on Graphics, vol 16 no 3, July 1997, page 319. +' +' J. Sánchez-Reyes, ‘Applications of the polynomial s-power basis +' in geometry processing’, ACM Transactions on Graphics, vol 19 +' no 1, January 2000, page 35. +' +' Flattening a quadratic that is represented in this basis has a few +' advantages, which I will not go into here. */ + +Type bernstein_spline + b0 As Double + b1 As Double + b2 As Double +End Type + +Type spower_spline + c0 As Double + c1 As Double + c2 As Double +End Type + +Type spower_curve + x As spower_spline + y As spower_spline +End Type + +' Convert a non-parametric spline from Bernstein basis to s-power. +Function bernstein_spline_to_spower(S As bernstein_spline) As spower_spline + Dim As spower_spline T + T.c0 = S.b0 + T.c1 = (2 * S.b1) - S.b0 - S.b2 + T.c2 = S.b2 + Return T +End Function + +' Compose (c0, c1, c2) with (t0, t1). This will map the portion [t0,t1] onto +' [0,1]. (To get these expressions, I did not use the general-degree methods +' described by Sánchez-Reyes, but instead used Maxima, some while ago.) +' +' This method is an alternative to de Casteljau subdivision, and can be done +' with the coefficients in any basis. Instead of breaking the spline into two +' pieces at a parameter value t, it gives you the portion lying between two +' parameter values. In general that requires two applications of de Casteljau +' subdivision. On the other hand, subdivision requires two applications of the +' following. +Function spower_spline_portion(S As spower_spline, t0 As Double, t1 As Double) As spower_spline + Dim As Double t0_t0 = t0 * t0 + Dim As Double t0_t1 = t0 * t1 + Dim As Double t1_t1 = t1 * t1 + Dim As Double c2p1m0 = S.c2 + S.c1 - S.c0 + + Dim As spower_spline T + T.c0 = S.c0 + (c2p1m0 * t0) - (S.c1 * t0_t0) + T.c1 = (S.c1 * t1_t1) - (2 * S.c1 * t0_t1) + (S.c1 * t0_t0) + T.c2 = S.c0 + (c2p1m0 * t1) - (S.c1 * t1_t1) + Return T +End Function + +Function spower_curve_portion(C As spower_curve, t0 As Double, t1 As Double) As spower_curve + Dim As spower_curve D + D.x = spower_spline_portion(C.x, t0, t1) + D.y = spower_spline_portion(C.y, t0, t1) + Return D +End Function + +' Given a parametric curve, is it "flat enough" to have its quadratic +' terms removed? +Function flat_enough(C As spower_curve, tol As Double) As Boolean + ' The degree-2 s-power polynomials are 1-t, t(1-t), t. We want to + ' remove the terms in t(1-t). The maximum of t(1-t) is 1/4, reached + ' at t=1/2. That accounts for the 1/8=0.125 in the following: + Dim As Double cx0 = C.x.c0 + Dim As Double cx1 = C.x.c1 + Dim As Double cx2 = C.x.c2 + Dim As Double cy0 = C.y.c0 + Dim As Double cy1 = C.y.c1 + Dim As Double cy2 = C.y.c2 + Dim As Double dx = cx2 - cx0 + Dim As Double dy = cy2 - cy0 + Dim As Double error_squared = 0.125 * ((cx1 * cx1) + (cy1 * cy1)) + Dim As Double length_squared = (dx * dx) + (dy * dy) + Return (error_squared <= length_squared * tol * tol) +End Function + +' Given two line segments, do they intersect? One solution to this problem is +' to use the implicitization method employed in the Maxima example, except to +' do it with linear instead of quadratic curves. That is what I do here, with +' the the roles of who gets implicitized alternated. If both ways you get as +' answer a parameter in [0,1], then the segments intersect. +Sub test_line_segment_intersection(ax0 As Double, ax1 As Double, _ + ay0 As Double, ay1 As Double, bx0 As Double, bx1 As Double, _ + by0 As Double, by1 As Double, Byref they_intersect As Boolean, _ + Byref x As Double, Byref y As Double) + Dim As Double anumer = ((bx1 - bx0) * ay0 - (by1 - by0) * ax0 _ + + bx0 * by1 - bx1 * by0) + Dim As Double bnumer = -((ax1 - ax0) * by0 - (ay1 - ay0) * bx0 _ + + ax0 * ay1 - ax1 * ay0) + Dim As Double denom = ((ax1 - ax0) * (by1 - by0) _ + - (ay1 - ay0) * (bx1 - bx0)) + Dim As Double ta = anumer / denom ' Parameter of segment a. + Dim As Double tb = bnumer / denom ' Parameter of segment b. + they_intersect = (0 <= ta And ta <= 1 And 0 <= tb And tb <= 1) + If they_intersect Then + x = ((1 - ta) * ax0) + (ta * ax1) + y = ((1 - ta) * ay0) + (ta * ay1) + End If +End Sub + +Function too_close(x As Double, y As Double, xs() As Double, ys() As Double, _ + num_points As Integer, spacing As Double) As Boolean + Dim As Boolean tooclose = False + Dim As Integer i = 0 + While Not tooclose And i <> num_points + tooclose = (Abs(x - xs(i)) < spacing And Abs(y - ys(i)) < spacing) + i += 1 + Wend + Return tooclose +End Function + +Sub recursion(tp0 As Double, tp1 As Double, tq0 As Double, tq1 As Double, _ + P As spower_curve, Q As spower_curve, tol As Double, spacing As Double, _ + max_points As Integer, xs() As Double, ys() As Double, Byref num_points As Integer) + If num_points = max_points Then + ' do nothing + Elseif Not flat_enough(spower_curve_portion(P, tp0, tp1), tol) Then + Dim As Double tp_half = (0.5 * tp0) + (0.5 * tp1) + If Not flat_enough(spower_curve_portion(Q, tq0, tq1), tol) Then + Dim As Double tq_half = (0.5 * tq0) + (0.5 * tq1) + recursion(tp0, tp_half, tq0, tq_half, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + recursion(tp0, tp_half, tq_half, tq1, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + recursion(tp_half, tp1, tq0, tq_half, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + recursion(tp_half, tp1, tq_half, tq1, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + Else + recursion(tp0, tp_half, tq0, tq1, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + recursion(tp_half, tp1, tq0, tq1, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + End If + Elseif Not flat_enough(spower_curve_portion(Q, tq0, tq1), tol) Then + Dim As Double tq_half = (0.5 * tq0) + (0.5 * tq1) + recursion(tp0, tp1, tq0, tq_half, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + recursion(tp0, tp1, tq_half, tq1, P, Q, tol, _ + spacing, max_points, xs(), ys(), num_points) + Else + Dim As spower_curve P1 = spower_curve_portion(P, tp0, tp1) + Dim As spower_curve Q1 = spower_curve_portion(Q, tq0, tq1) + Dim As Boolean they_intersect + Dim As Double x, y + test_line_segment_intersection(P1.x.c0, P1.x.c2, _ + P1.y.c0, P1.y.c2, _ + Q1.x.c0, Q1.x.c2, _ + Q1.y.c0, Q1.y.c2, _ + they_intersect, x, y) + If they_intersect And Not too_close(x, y, xs(), ys(), num_points, spacing) Then + xs(num_points) = x + ys(num_points) = y + num_points += 1 + End If +End If +End Sub + +Sub find_intersections(P As spower_curve, Q As spower_curve, _ + flatness_tolerance As Double, point_spacing As Double, _ + max_points As Integer, xs() As Double, ys() As Double, _ + Byref num_points As Integer) + num_points = 0 + recursion(0, 1, 0, 1, P, Q, flatness_tolerance, point_spacing, _ + max_points, xs(), ys(), num_points) +End Sub + +Dim As bernstein_spline bPx = Type(-1, 0, 1) +Dim As bernstein_spline bPy = Type(0, 10, 0) +Dim As bernstein_spline bQx = Type(2, -8, 2) +Dim As bernstein_spline bQy = Type(1, 2, 3) + +Dim As spower_spline Px = bernstein_spline_to_spower(bPx) +Dim As spower_spline Py = bernstein_spline_to_spower(bPy) +Dim As spower_spline Qx = bernstein_spline_to_spower(bQx) +Dim As spower_spline Qy = bernstein_spline_to_spower(bQy) + +Dim As spower_curve P = Type(Px, Py) +Dim As spower_curve Q = Type(Qx, Qy) + +Dim As Double flatness_tolerance = 0.001 +Dim As Double point_spacing = 0.000001 ' Max norm minimum spacing. + +Const max_points As Integer = 10 +Dim As Double xs(max_points) +Dim As Double ys(max_points) +Dim As Integer num_points + +find_intersections(P, Q, flatness_tolerance, point_spacing, _ +max_points, xs(), ys(), num_points) + +For i As Integer = 0 To num_points - 1 + Print "("; xs(i); ", "; ys(i); ")" +Next i + +Sleep diff --git a/Task/Babbage-problem/EMal/babbage-problem.emal b/Task/Babbage-problem/EMal/babbage-problem.emal new file mode 100644 index 0000000000..8b22bbe9f6 --- /dev/null +++ b/Task/Babbage-problem/EMal/babbage-problem.emal @@ -0,0 +1,9 @@ +^| + | Since the number must end with 269696 we can safely start counting from its square root; + | we are only interested in its integer part. + | We assign a value to a variable with "←". + | The modulo symbol for getting the remainder of a division is "%". + |^ +int i ← int!√269696 +while i² % 1000000 ≠ 269696 do ++i end +writeLine(i) diff --git a/Task/Babbage-problem/Langur/babbage-problem.langur b/Task/Babbage-problem/Langur/babbage-problem.langur new file mode 100644 index 0000000000..688d15f17d --- /dev/null +++ b/Task/Babbage-problem/Langur/babbage-problem.langur @@ -0,0 +1,6 @@ +for i = 2; i < 100000 ; i += 2 { + if i*i rem 1000000 == 269696 { + writeln "{{i}} ^ 2 == {{i^2}}" + break + } +} diff --git a/Task/Balanced-brackets/PascalABC.NET/balanced-brackets.pas b/Task/Balanced-brackets/PascalABC.NET/balanced-brackets.pas new file mode 100644 index 0000000000..f40f52b72a --- /dev/null +++ b/Task/Balanced-brackets/PascalABC.NET/balanced-brackets.pas @@ -0,0 +1,29 @@ +function GenBracketExpr(n: integer): string; +begin + var a := Arr('[',']')*n; + Shuffle(a); + Result := a.JoinToString +end; + +function IsBalanced(s: string): boolean; +begin + Result := True; + var st := new Stack; + foreach var c in s do + if c = '[' then + st.Push(c) + else if (st.Count > 0) and (st.Peek = '[') then + st.Pop + else begin + Result := False; + exit + end; +end; + +begin + loop 10 do + begin + var s := GenBracketExpr(Random(2,5)); + Println(s, IsBalanced(s)); + end; +end. diff --git a/Task/Barnsley-fern/Uiua/barnsley-fern.uiua b/Task/Barnsley-fern/Uiua/barnsley-fern.uiua new file mode 100644 index 0000000000..a2d94aeac6 --- /dev/null +++ b/Task/Barnsley-fern/Uiua/barnsley-fern.uiua @@ -0,0 +1,11 @@ +Fs ← [[[0 0 0] [0 0.16 0]] + [[0.85 0.04 0] [¯0.04 0.85 1.6]] + [[0.2 ¯0.26 0] [0.23 0.22 1.6]] + [[¯0.15 0.28 0] [0.26 0.24 0.44]]] +Ps ← [1 86 93 100] +PickF ← (⊡:Fs⊢⊚ x).named("y", "x") + x++ + if x æ side + x ← 0 + y++ + end + end + end + fun asText = text by block + text result = "" + for int y ← 0; y < me.grid.length; y++ + for int x ← 0; x < me.grid[y].length; x++ + result.append(" " + me.grid[y][x]) + end + result.appendLine() + end + return result + end +end +type BifidCipher +model + PolybiusSquare square + new by PolybiusSquare ←square do end + fun encrypt ← text by text value + List row ← int[].with(value.length * 2) + int y ← 0 + int x ← value.length + for each text char in value + Pair p ← me.square.map[char] + row[y++] ← p.y + row[x++] ← p.x + end + text encrypted + for int i ← 0; i < row.length; i += 2 + encrypted.append(me.square.grid[row[i]][row[i + 1]]) + end + return encrypted + end + fun decrypt ← text by text value + List row ← int[] + for each text char in value + Pair p ← me.square.map[char] + row.append(p.y) + row.append(p.x) + end + int y ← 0 + int x ← value.length + text decrypted + for int i ← 0; i < value.length; i++ + decrypted.append(me.square.grid[row[y++]][row[x++]]) + end + return decrypted + end +end +type Main +List pairs ← Pair[ + text%PolybiusSquare("ATTACKATDAWN" => PolybiusSquare(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ")).named("sample", "square"), + text%PolybiusSquare("FLEEATONCE" => PolybiusSquare(5, "BGWKZQPNDSIOAXEFCLUMTHYVR")).named("sample", "square"), + text%PolybiusSquare("ATTACKATDAWN" => PolybiusSquare(5, "BGWKZQPNDSIOAXEFCLUMTHYVR")).named("sample", "square"), + text%PolybiusSquare("The invasion will start on the first of January".upper().replace(" ", "") => + PolybiusSquare(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")).named("sample", "square")] +for each Pair pair in pairs + writeLine("Using Polybius square:") + write(pair.square) + BifidCipher cipher ← BifidCipher(pair.square) + write("Encrypting '" + pair.sample + "'") + text encrypted ← cipher.encrypt(pair.sample) + write(" => '" + encrypted + "'") + text decrypted ← cipher.decrypt(encrypted) + writeLine(" => '" + decrypted + "'") + writeLine() +end diff --git a/Task/Bifid-cipher/Uiua/bifid-cipher-1.uiua b/Task/Bifid-cipher/Uiua/bifid-cipher-1.uiua new file mode 100644 index 0000000000..7a2d0a35ce --- /dev/null +++ b/Task/Bifid-cipher/Uiua/bifid-cipher-1.uiua @@ -0,0 +1,9 @@ +S ← "ABCDEFGHIKLMNOPQRSTUVWXYZ" +P ← ↯⊟.√⧻.S +Prep ← ▽∊:S.∧⍜⊡⋅@I⊚⌕@J.⌵ +Bifid ← setinv( + ⊡:⟜(↯∞_2/⊂⇌⍉≡(⊢⊚⌕)Prep:¤)P +| ⊡:⟜(⍉⇌↯2_∞/⊂≡(⊢⊚⌕):¤)P +) +°Bifid.Bifid. "This is it" +°Bifid.Bifid. "The invasion will start on the first of January" diff --git a/Task/Bifid-cipher/Uiua/bifid-cipher-2.uiua b/Task/Bifid-cipher/Uiua/bifid-cipher-2.uiua new file mode 100644 index 0000000000..c9ef4c623e --- /dev/null +++ b/Task/Bifid-cipher/Uiua/bifid-cipher-2.uiua @@ -0,0 +1,9 @@ +S ← "GLYPHABCDEFIJKMNOQRSTUVWXZ0123456789" +P ← ↯⊟.√⧻.S +Prep ← ▽∊:S.⌵ +Bifid ← setinv( + ⊡:⟜(↯∞_2/⊂⇌⍉≡(⊢⊚⌕)Prep:¤)P +| ⊡:⟜(⍉⇌↯2_∞/⊂≡(⊢⊚⌕):¤)P +) +°Bifid.Bifid. "This is it" +°Bifid.Bifid. "The invasion will start at 0600 on the 1st of January" diff --git a/Task/Bin-given-limits/Free-Pascal-Lazarus/bin-given-limits.pas b/Task/Bin-given-limits/Free-Pascal-Lazarus/bin-given-limits.pas new file mode 100644 index 0000000000..393a72a5e5 --- /dev/null +++ b/Task/Bin-given-limits/Free-Pascal-Lazarus/bin-given-limits.pas @@ -0,0 +1,56 @@ +Program bin_given_limits; + +const + limits1: array of integer = (23, 37, 43, 53, 67, 83); + data1: array of integer = (95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, + 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, + 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55); + limits2: array of integer = (14, 18, 249, 312, 389, 392, 513, 591, 634, 720); + data2: array of integer = (445, 814, 519, 697, 700, 130, 255, 889, 481, 122, + 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, + 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, + 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, + 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38,985, 948, 58, 213, 799, + 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, + 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, + 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, + 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, + 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, + 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, + 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, + 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, + 918, 8, 374, 101, 684, 727, 749); + + procedure print_bins(bins, limits: array of integer); + var + i: integer; + begin + writeln(' < ', limits[0]: 3, ' := ', bins[0]: 2); + for i := 0 to high(bins) - 2 do + writeln('>= ', limits[i]: 3, ' .. < ', limits[i + 1]: 3, ' := ', bins[i + 1]: 2); + writeln('>= ', limits[high(limits)]: 3, ' := ', bins[high(bins)]: 2); + end; + + procedure do_bins(limits, Data: array of integer); + var + bins: array of integer; + i, b: integer; + begin + setlength(bins, high(limits) + 2); + for i in Data do + if i < limits[0] then Inc(bins[0]) + else + begin + for b := 1 to high(limits) do + if ((i >= limits[b - 1]) and (i < limits[b])) then Inc(bins[b]); + if i >= limits[high(limits)] then + Inc(bins[high(bins)]); + end; + print_bins(bins, limits); + end; + +begin + do_bins(limits1, data1); + writeln; + do_bins(limits2, data2); +end. diff --git a/Task/Binary-digits/PascalABC.NET/binary-digits.pas b/Task/Binary-digits/PascalABC.NET/binary-digits.pas new file mode 100644 index 0000000000..b64947cea0 --- /dev/null +++ b/Task/Binary-digits/PascalABC.NET/binary-digits.pas @@ -0,0 +1,4 @@ +begin + foreach var number in |5, 50, 9000| do + Writeln($'{number,4} - {Convert.ToString(number,2)}'); +end. diff --git a/Task/Binary-digits/Uiua/binary-digits.uiua b/Task/Binary-digits/Uiua/binary-digits.uiua new file mode 100644 index 0000000000..046c62302b --- /dev/null +++ b/Task/Binary-digits/Uiua/binary-digits.uiua @@ -0,0 +1,2 @@ +GetBits ← &pf@\n≡&pf ⇌⋯ +≡GetBits 5_50_9000 diff --git a/Task/Binary-search/Chapel/binary-search.chapel b/Task/Binary-search/Chapel/binary-search.chapel index c03efcb729..e5ab05d298 100644 --- a/Task/Binary-search/Chapel/binary-search.chapel +++ b/Task/Binary-search/Chapel/binary-search.chapel @@ -1,7 +1,9 @@ -proc binsearch(A:[], value) { - var low = A.domain.dim(1).low; - var high = A.domain.dim(1).high; - while (low <= high) { +proc binsearch(A : [], value) +{ + var low = A.domain.dim(0).low; + var high = A.domain.dim(0).high; + while (low <= high) + { var mid = (low + high) / 2; if A(mid) > value then diff --git a/Task/Binary-search/PascalABC.NET/binary-search.pas b/Task/Binary-search/PascalABC.NET/binary-search.pas new file mode 100644 index 0000000000..40e56953b1 --- /dev/null +++ b/Task/Binary-search/PascalABC.NET/binary-search.pas @@ -0,0 +1,61 @@ +function BinarySearch(a: array of integer; x: integer): integer; +begin + var (l,r) := (0, a.Length-1); + repeat + var mid := (l + r) div 2; + if x = a[mid] then + begin + Result := mid; + exit + end; + if x > a[mid] then + l := mid + 1 + else r := mid - 1; + until l > r; + Result := -1; +end; + +function BinarySearchRecursive(a: array of integer; x: integer): integer; + function BinarySearchHelper(a: array of integer; x: integer; l,r: integer): integer; + begin + if l > r then + Result := -1 + else begin + var mid := (l + r) div 2; + if x = a[mid] then + Result := mid + else if x < a[mid] then + Result := BinarySearchHelper(a, x, l, mid - 1) + else Result := BinarySearchHelper(a, x, mid + 1, r) + end; + end; +begin + Result := BinarySearchHelper(a,x,0,a.Length-1); +end; + +begin + var a := ArrRandomInteger(10,1,20); + a.Sort; + a.Println; + var x := 10; + var ind := BinarySearch(a,x); + if ind >= 0 then + Println($'{x} found at index {ind}') + else Println($'{x} not found'); + + ind := BinarySearchRecursive(a,x); + if ind >= 0 then + Println($'{x} found at index {ind}') + else Println($'{x} not found'); + + x := a.RandomElement; + ind := BinarySearch(a,x); + if ind >= 0 then + Println($'{x} found at index {ind}') + else Println($'{x} not found'); + + ind := BinarySearchRecursive(a,x); + if ind >= 0 then + Println($'{x} found at index {ind}') + else Println($'{x} not found'); +end. diff --git a/Task/Biorhythms/FutureBasic/biorhythms.basic b/Task/Biorhythms/FutureBasic/biorhythms.basic new file mode 100644 index 0000000000..2d27b3e9b9 --- /dev/null +++ b/Task/Biorhythms/FutureBasic/biorhythms.basic @@ -0,0 +1,110 @@ +/* +Biorhythms task for Rosetta Code +https://rosettacode.org/wiki/Biorhythms + +Translated from FreeBasic to FutureBasic +Rich Love May 24, 2024 + +*/ + + + +local fn Gregorian(db As str255) As short + short M, Y, D + Y = val(Left$(db,4)) : M = Val(Mid$(db,6,2)) : D = Val(Right$(db,2)) + short N = (M+9) - Int((M+9)/12) * 12 + short W = Y - Int(N/10) + short G = 365 * W + Int(W/4) - Int(W/100) + Int(W/400) + G += Int((N*306+5)/10)+(D-1) +end fn = G + + +void local fn Biorhythm(Birthdate As str255, Targetdate As str255) + + str255 TextArray(4,2) + TextArray(0,0) = "up and rising" + TextArray(1,0) = "up but falling" + TextArray(2,0) = "down and falling" + TextArray(3,0) = "down but rising" + TextArray(0,1) = "peak" + TextArray(1,1) = "transition" + TextArray(2,1) = "valley" + TextArray(3,1) = "transition" + + + short DaysBetween = fn Gregorian(Targetdate) - fn Gregorian(Birthdate) + 1 + short positionP = DaysBetween Mod 23 + short positionE = DaysBetween Mod 28 + short positionM = DaysBetween Mod 33 + short quadrantP = Int(4 * positionP / 23) + short quadrantE = Int(4 * positionE / 28) + short quadrantM = Int(4 * positionM / 33) + short percentageP = Fix(100 * Sin(2 * (pi * positionP) / 23)) + short percentageE = Fix(100 * Sin(2 * (pi * positionE) / 28)) + short percentageM = Fix(100 * Sin(2 * (pi * positionM) / 33)) + + str255 textP, textE, textM, Header1Text, Header2Text + + + Select Case percentageP + Case > 95 + textP = "Physical day " + str$(positionP) + " : " + "peak" + Case < -95 + textP = "Physical day " + str$(positionP) + " : " + "valley" + Case -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 + textP = "Physical day " + str$(positionP) + " : " + "critical transition" + Case Else + textP = "Physical day " + str$(positionP) + " : " + str$(percentageP) + "% (" + TextArray(quadrantP,0) + ")" + End Select + + Select Case percentageE + Case > 95 + textE = "Emotional day " + STR$(positionE) + " : " + "peak" + Case < -95 + textE = "Emotional day " + STR$(positionE) + " : " + "valley" + Case -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 + textE = "Emotional day " + STR$(positionE) + " : " + "critical transition" + Case Else + textE = "Emotional day " + STR$(positionE) + " : " + str$(percentageE) + "% (" + TextArray(quadrantE,0) + ")" + End Select + + Select Case percentageM + Case > 95 + textM = "Mental day " + str$(positionM)+ " : " + "peak" + Case < - 95 + textM = "Mental day " + str$(positionM) + " : " + "valley" + Case -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 + textM = "Mental day " + str$(positionM) + " : " + "critical transition" + Case Else + textM = "Mental day " + str$(positionM) + " : " + str$(percentageM) + "% (" + TextArray(quadrantM,0) + ")" + End Select + + Header1Text = "Born " + Birthdate + ", Target " + Targetdate + Header2Text = "Day " + str$(DaysBetween) + + Print Header1Text + Print Header2Text + Print textP + Print textE + Print textM + Print +end fn + +window 1, @"Biorhythms" +windowcenter(1) +WindowSetBackgroundColor(1,fn ColorBlack) + +print + +// Lets do four different birthdates and target dates +text ,,fn colorCyan +fn Biorhythm("1943-03-09", "1972-07-11") +text ,,fn colorGreen +fn Biorhythm("1809-02-12", "1863-11-19") // DOB for Abraham Lincoln +text ,,fn colorYellow +fn Biorhythm("1809-01-12", "1863-11-19") +text ,,fn colorWhite +fn Biorhythm("1943-03-09", "1972-07-11") // Bobby Fisher Chess Tournament + + +handleevents diff --git a/Task/Bitcoin-address-validation/C++/bitcoin-address-validation.cpp b/Task/Bitcoin-address-validation/C++/bitcoin-address-validation.cpp new file mode 100644 index 0000000000..654b6e7721 --- /dev/null +++ b/Task/Bitcoin-address-validation/C++/bitcoin-address-validation.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "SHA256.cpp" +SHA256 sha256{ }; + +const std::string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + +std::map base_map = + { { '0', 0 }, { '1', 1 }, { '2', 2 }, { '3', 3 }, { '4', 4 }, { '5', 5 }, { '6', 6 }, { '7', 7 }, + { '8', 8 }, { '9', 9 }, { 'a', 10 }, { 'b', 11 }, { 'c', 12 }, { 'd', 13 }, { 'e', 14 }, { 'f', 15 }, + { 'A', 10 }, { 'B', 11 }, { 'C', 12 }, { 'D', 13 }, { 'E', 14 }, { 'F', 15 } }; + +std::vector hex_to_bytes(const std::string& text) { + std::vector bytes(text.size() / 2, 0); + for ( uint64_t i = 0; i < text.size(); i += 2 ) { + const uint32_t first_digit = base_map[text[i]]; + const uint32_t second_digit = base_map[text[i + 1]]; + bytes[i / 2] = ( first_digit << 4 ) + second_digit; + } + return bytes; +} + +std::string vector_to_ascii_string(const std::vector& bytes) { + std::string result = ""; + for ( uint32_t i = 0; i < bytes.size(); ++i ) { + result += static_cast(bytes[i]); + } + return result; +} + +std::vector decode_base_58(const std::string& text) { + std::vector result(25, 0); + for ( const char& ch : text ) { + std::string::size_type index = ALPHABET.find(ch); + if ( index == static_cast(-1) ) { + throw std::invalid_argument("Invalid character found in bitcoin address"); + } + for ( uint64_t i = result.size() - 1; i > 0; i-- ) { + index += 58 * result[i]; + result[i] = index & 0xFF; + index >>= 8; + } + if ( index != 0 ) { + throw std::invalid_argument("Bitcoin address is too long"); + } + } + return result; +} + +bool is_valid(const std::string& address) { + if ( address.size() < 26 || address.size() > 35 ) { + throw std::invalid_argument("Invalid length of bitcoin address"); + } + + std::vector decoded = decode_base_58(address); + std::vector first21(decoded.begin(), decoded.begin() + 21); + + // Convert the 'first21' into a suitable ASCII string for the first SHA256 hash + std::string text = vector_to_ascii_string(first21); + std::string hash_1 = sha256.message_digest(text); + // Convert 'hashOne' into a suitable ASCII string for the second SHA256 hash + std::vector bytes_1 = hex_to_bytes(hash_1); + std::string ascii_1 = vector_to_ascii_string(bytes_1); + std::string hash_2 = sha256.message_digest(ascii_1); + + std::vector bytes_2 = hex_to_bytes(hash_2); + std::vector checksum(bytes_2.begin(), bytes_2.begin() + 4); + std::vector last4(decoded.begin() + 21, decoded.begin() + 25); + return checksum == last4; +} + +int main() { + const std::vector addresses = { "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", + "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" }; + + for ( const std::string& address : addresses ) { + std::cout << address << " : " << std::boolalpha << is_valid(address) << std::endl; + } +} diff --git a/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation-1.java similarity index 100% rename from Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java rename to Task/Bitcoin-address-validation/Java/bitcoin-address-validation-1.java diff --git a/Task/Bitcoin-address-validation/Java/bitcoin-address-validation-2.java b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation-2.java new file mode 100644 index 0000000000..ab07ecd8b0 --- /dev/null +++ b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation-2.java @@ -0,0 +1,71 @@ +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; + +public final class BitcoinAddressValidation { + + public static void main(String[] args) { + List addresses = List.of ( "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", + "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" ); + + for ( String address : addresses ) { + System.out.println(address + " : " + isValid(address)); + } + } + + private static boolean isValid(String address) { + if ( address.length() < 26 || address.length() > 35 ) { + throw new AssertionError("Invalid length of bitcoin address"); + } + + byte[] decoded = decodeBase58(address); + byte[] first21 = Arrays.copyOfRange(decoded, 0, 21); + // Convert 'first21' into an ASCII string for the first SHA256 hash + String text = new String(first21, StandardCharsets.ISO_8859_1); + String hashOne = SHA256.messageDigest(text); + // Convert 'hashOne' into an ASCII string for the second SHA256 hash + byte[] bytesOne = hexToBytes(hashOne); + String asciiOne = new String(bytesOne, StandardCharsets.ISO_8859_1); + String hashTwo = SHA256.messageDigest(asciiOne); + + byte[] bytesTwo = hexToBytes(hashTwo); + byte[] checksum = Arrays.copyOfRange(bytesTwo, 0, 4); + byte[] last4 = Arrays.copyOfRange(decoded, 21, 25); + return Arrays.equals(last4, checksum); + } + + private static byte[] decodeBase58(String text) { + byte[] result = new byte[25]; + for ( char ch : text.toCharArray() ) { + int index = ALPHABET.indexOf(ch); + if ( index == -1 ) { + throw new AssertionError("Invalid character found in bitcoin address: " + ch); + } + for ( int i = result.length - 1; i > 0; i-- ) { + index += 58 * (int) ( result[i] & 0xFF ); + result[i] = (byte) ( index & 0xFF ); + index >>= 8; + } + if ( index != 0 ) { + throw new AssertionError("Bitcoin address is too long"); + } + } + return result; + } + + private static byte[] hexToBytes(String text) { + byte[] bytes = new byte[text.length() / 2]; + for ( int i = 0; i < text.length(); i += 2 ) { + final int firstDigit = Character.digit(text.charAt(i), 16); + final int secondDigit = Character.digit(text.charAt(i + 1), 16); + bytes[i / 2] = (byte) ( ( firstDigit << 4 ) + secondDigit ); + } + return bytes; + } + + private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + +} diff --git a/Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp b/Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp new file mode 100644 index 0000000000..3a5ee44ffc --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/C++/bitcoin-public-point-to-address.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include + +#include "SHA256.cpp" +#include "RIPEMD160.cpp" +SHA256 sha256{ }; +RIPEMD160 ripemd160{ }; + +const std::string BITCOIN_SPECIAL_VALUE = "04"; +const std::string BITCOIN_VERSION_NUMBER = "00"; + +std::map base_map = + { { '0', 0 }, { '1', 1 }, { '2', 2 }, { '3', 3 }, { '4', 4 }, { '5', 5 }, { '6', 6 }, { '7', 7 }, + { '8', 8 }, { '9', 9 }, { 'a', 10 }, { 'b', 11 }, { 'c', 12 }, { 'd', 13 }, { 'e', 14 }, { 'f', 15 }, + { 'A', 10 }, { 'B', 11 }, { 'C', 12 }, { 'D', 13 }, { 'E', 14 }, { 'F', 15 } }; + +std::vector hex_to_bytes(const std::string& text) { + std::vector bytes(text.size() / 2, 0); + for ( uint64_t i = 0; i < text.size(); i += 2 ) { + const uint32_t first_digit = base_map[text[i]]; + const uint32_t second_digit = base_map[text[i + 1]]; + bytes[i / 2] = ( first_digit << 4 ) + second_digit; + } + return bytes; +} + +std::string vector_to_ascii_string(const std::vector& bytes) { + std::string result = ""; + for ( uint64_t i = 0; i < bytes.size(); ++i ) { + result += static_cast(bytes[i]); + } + return result; +} + +std::vector compute_message_bytes(const std::string& text) { + // Convert the hexadecimal string 'text' into a suitable ASCII string for the SHA256 hash + std::vector bytes_1 = hex_to_bytes(text); + std::string ascii_1 = vector_to_ascii_string(bytes_1); + std::string hexSHA256 = sha256.message_digest(ascii_1); + // Convert the hexadecimal string 'hexSHA256' into a suitable ASCII string for the RIPEMD160 hash + std::vector bytes_2 = hex_to_bytes(hexSHA256); + std::string ascii_2 = vector_to_ascii_string(bytes_2); + std::string hexRIPEMD160 = BITCOIN_VERSION_NUMBER + ripemd160.message_digest(ascii_2); + return hex_to_bytes(hexRIPEMD160); +} + +std::vector compute_checksum(const std::vector& bytes) { + // Convert the given byte array into a suitable ASCII string for the first SHA256 hash + std::string ascii_1 = vector_to_ascii_string(bytes); + std::string hex_1 = sha256.message_digest(ascii_1); + // Convert the hexadecimal string 'hex1' into a suitable ASCII string for the second SHA256 hash + std::vector bytes_1 = hex_to_bytes(hex_1); + std::string ascii_2 = vector_to_ascii_string(bytes_1); + std::string hex_2 = sha256.message_digest(ascii_2); + std::vector bytes_2 = hex_to_bytes(hex_2); + std::vector result(bytes_2.begin(), bytes_2.begin() + 4); + return result; +} + +// Return the given byte array encoded into a base58 starting with most one '1' +std::string encode_base_58(std::vector bytes) { + const std::string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + const uint32_t ALPHABET_SIZE = ALPHABET.size(); + + std::string result(34, ' '); + for ( int64_t n = result.size() - 1; n >= 0; --n ) { + uint32_t c = 0; + for ( uint64_t i = 0; i < bytes.size(); ++i ) { + c = c * 256 + bytes[i]; + bytes[i] = c / ALPHABET_SIZE; + c %= ALPHABET_SIZE; + } + result[n] = ALPHABET[c]; + } + + while ( result.starts_with("11") ) { + result = result.substr(1); + } + return result; +} + +// Return the encoded address of the given coordinates. +std::string encode_address(const std::string& x, const std::string& y) { + std::string public_point = BITCOIN_SPECIAL_VALUE + x + y; + if ( public_point.size() != 130 ) { + throw std::invalid_argument("Invalid public point string"); + } + + std::vector message_bytes = compute_message_bytes(public_point); + std::vector checksum = compute_checksum(message_bytes); + message_bytes.insert(message_bytes.end(), checksum.begin(), checksum.end()); + return encode_base_58(message_bytes); +} + +int main() { + std::string x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; + std::string y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; + + std::cout << encode_address(x, y) << std::endl; +} diff --git a/Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java b/Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java new file mode 100644 index 0000000000..6f28ff3d99 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Java/bitcoin-public-point-to-address.java @@ -0,0 +1,99 @@ +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.stream.Collectors; + +public final class BitcoinPublicPointToAddess { + + public static void main(String[] args) { + String x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352"; + String y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6"; + + if ( areValidCoordinates(x, y) ) { + System.out.println(encodeAddress(x, y)); + } else { + System.out.println("Invalid Bitcoin public point coordinates"); + } + } + + // Return the encoded address of the given coordinates. + private static String encodeAddress(String x, String y) { + String publicPoint = BITCOIN_SPECIAL_VALUE + x + y; + if ( publicPoint.length() != 130 ) { + throw new AssertionError("Invalid public point string: " + publicPoint); + } + + byte[] messageBytes = computeMessageBytes(publicPoint); + byte[] checksum = computeChecksum(messageBytes); + messageBytes = Arrays.copyOf(messageBytes, messageBytes.length + 4); + System.arraycopy(checksum, 0, messageBytes, 21, checksum.length); + return encodeBase58(messageBytes); + } + + // Return the given byte array encoded into a base58 starting with most one '1' + private static String encodeBase58(byte[] bytes) { + final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + final int ALPHABET_SIZE = ALPHABET.length(); + + String[] temp = new String[34]; + for ( int n = temp.length - 1; n >= 0; n-- ) { + int c = 0; + for ( int i = 0; i < bytes.length; i++ ) { + c = c * 256 + (int) ( bytes[i] & 0xFF ); + bytes[i] = (byte) ( c / ALPHABET_SIZE ); + c %= ALPHABET_SIZE; + } + temp[n] = ALPHABET.substring(c, c + 1); + } + + String result = Arrays.stream(temp).collect(Collectors.joining("")); + while ( result.startsWith("11") ) { + result = result.substring(1); + } + return result; + } + + // Return whether the given coordinates are those of a point on the secp256k1 elliptic curve + private static boolean areValidCoordinates(String x, String y) { + BigInteger modulus = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16); + BigInteger X = new BigInteger(x, 16); + BigInteger Y = new BigInteger(y, 16); + return Y.multiply(Y).mod(modulus).equals(X.multiply(X).multiply(X).add(BigInteger.valueOf(7)).mod(modulus)); + } + + private static byte[] computeMessageBytes(String text) { + // Convert the hexadecimal string 'text' into a suitable ASCII string for the SHA256 hash + byte[] bytesOne = hexToBytes(text); + String asciiOne = new String(bytesOne, StandardCharsets.ISO_8859_1); + String hexSHA256 = SHA256.messageDigest(asciiOne); + // Convert the hexadecimal string 'hexSHA256' into a suitable ASCII string for the RIPEMD160 hash + byte[] bytesTwo = hexToBytes(hexSHA256); + String asciiTwo = new String(bytesTwo, StandardCharsets.ISO_8859_1); + String hexRIPEMD160 = BITCOIN_VERSION_NUMBER + RIPEMD160.messageDigest(asciiTwo); + return hexToBytes(hexRIPEMD160); + } + + private static byte[] computeChecksum(byte[] bytes) { + // Convert the given byte array into a suitable ASCII string for the first SHA256 hash + String asciiOne = new String(bytes, StandardCharsets.ISO_8859_1); + String hexOne = SHA256.messageDigest(asciiOne); + // Convert the hexadecimal string 'hex1' into a suitable ASCII string for the second SHA256 hash + byte[] bytesOne = hexToBytes(hexOne); + String asciiTwo = new String(bytesOne, StandardCharsets.ISO_8859_1); + String hexTwo = SHA256.messageDigest(asciiTwo); + return Arrays.copyOfRange(hexToBytes(hexTwo), 0, 4); + } + + private static byte[] hexToBytes(String text) { + byte[] bytes = new byte[text.length() / 2]; + for ( int i = 0; i < text.length(); i += 2 ) { + final int firstDigit = Character.digit(text.charAt(i), 16); + final int secondDigit = Character.digit(text.charAt(i + 1), 16); + bytes[i / 2] = (byte) ( ( firstDigit << 4 ) + secondDigit );; + } + return bytes; + } + + private static final String BITCOIN_SPECIAL_VALUE = "04"; + private static final String BITCOIN_VERSION_NUMBER = "00"; +} diff --git a/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust b/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust index e9c6c90584..57c7e6ba02 100644 --- a/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust +++ b/Task/Bitcoin-public-point-to-address/Rust/bitcoin-public-point-to-address.rust @@ -1,5 +1,5 @@ use ring::digest::{digest, SHA256}; -use ripemd160::{Digest, Ripemd160}; +use ripemd::{Digest, Ripemd160}; use hex::FromHex; diff --git a/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l b/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l index 7d538ce4eb..4d73742931 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l +++ b/Task/Bitmap-B-zier-curves-Cubic/11l/bitmap-b-zier-curves-cubic.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b - - F (r, g, b) - .r = r - .g = g - .b = b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l b/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l index 3c00cb16f4..928f45dde9 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l +++ b/Task/Bitmap-Bresenhams-line-algorithm/11l/bitmap-bresenhams-line-algorithm.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/11l/bitmap-midpoint-circle-algorithm.11l b/Task/Bitmap-Midpoint-circle-algorithm/11l/bitmap-midpoint-circle-algorithm.11l index 0759dfdcb4..299883e44c 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/11l/bitmap-midpoint-circle-algorithm.11l +++ b/Task/Bitmap-Midpoint-circle-algorithm/11l/bitmap-midpoint-circle-algorithm.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l b/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l index eb8c2c11c4..93aeb15ba7 100644 --- a/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l +++ b/Task/Bitmap-Read-a-PPM-file/11l/bitmap-read-a-ppm-file.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l b/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l index 31e28a4f57..ab83896090 100644 --- a/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l +++ b/Task/Bitmap-Write-a-PPM-file/11l/bitmap-write-a-ppm-file.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada index 8eb4b7a790..c3611189b3 100644 --- a/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada +++ b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada @@ -1,6 +1,9 @@ with Ada.Characters.Latin_1; with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; +with Bitmap_Store; use Bitmap_Store; +-- This package is defined in the Bitmap task. + procedure Put_PPM (File : File_Type; Picture : Image) is use Ada.Characters.Latin_1; Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); diff --git a/Task/Bitmap/11l/bitmap.11l b/Task/Bitmap/11l/bitmap.11l index 1c27ab573c..6939493b36 100644 --- a/Task/Bitmap/11l/bitmap.11l +++ b/Task/Bitmap/11l/bitmap.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Bitmap/POV-Ray/bitmap.povray b/Task/Bitmap/POV-Ray/bitmap.povray new file mode 100644 index 0000000000..2578b0aa32 --- /dev/null +++ b/Task/Bitmap/POV-Ray/bitmap.povray @@ -0,0 +1,74 @@ +//cmd: +w300 +h300 +am2 +a0.01 + +#version 3.7; + +#global_settings {assumed_gamma 1} +#default{ finish{ ambient 0.1 diffuse 0.9 }} +background {rgb 0} + + +#macro mapInit(DimX, DimY) + #local Map = array[DimX][DimY]; + mapFillSolid(Map, rgb<0,0,0>) + Map +#end + + +#macro mapFillSolid(Map, Colour) + mapFillRect(Map,<0,0>,, Colour) +#end + + +#macro mapFillRect(Map, RectLowerLeft, RectUpperRight, Colour) + #for (X, RectLowerLeft.x, RectUpperRight.x - 1) + #for (Y, RectLowerLeft.y, RectUpperRight.y - 1) + #local Map[X][Y] = Colour; + #end + #end +#end + + +#macro mapSetPixel(Map, Pixel, Colour) + #local Map[Pixel.x][Pixel.y] = Colour; +#end + + +#macro mapGetPixel(Map, Pixel) + Map[Pixel.x][Pixel.y] +#end + + +#macro mapObject(Map) + // to visualize the map, each pixel is rendered as a sphere + #for (X,0,dimension_size(Map,1)-1) + #for (Y,0,dimension_size(Map,2)-1) + sphere{ + , 0.5 + pigment{colour Map[X][Y]} + } + #end + #end +#end + +//== Scene + +#declare DimX = 100; +#declare DimY = 100; +#declare ImgMap = mapInit(DimX, DimY); +mapFillSolid(ImgMap, rgb<1, 0, 0>) +mapSetPixel(ImgMap, <25,25>, rgb<1,1,1>) +mapFillRect(ImgMap, <50,50>, <75,75>, rgb<0,0,1>) + +#debug concat("Colour at: <", vstr(2,<25,25>,", ",0,0),"> is: <", vstr(3, mapGetPixel(ImgMap, <25,25>),", ",0,0),">\n") + +mapObject(ImgMap) + +camera{ + location + look_at + right x*image_width/image_height +} +light_source{ + + rgb 1 +} diff --git a/Task/Bitwise-operations/Jq/bitwise-operations.jq b/Task/Bitwise-operations/Jq/bitwise-operations.jq new file mode 100644 index 0000000000..4724c12f65 --- /dev/null +++ b/Task/Bitwise-operations/Jq/bitwise-operations.jq @@ -0,0 +1,32 @@ +include "bitwise" {search: "."}; # adjust as required + +def leftshift($n; $width): + [(range(0,$n)| 0), limit($width - $n; bitwise)][:$width] | to_int; + +# Using a width of $width bits: x << n | x >> ($width-n) +def rotateLeft($x; $n; $width): + $x | bitwise_or(leftshift($n; $width); rightshift($width-$n)); + +# Using a width of $width bits: x << n | x >> ($width-n) +def rotateRight($x; $n; $width): + $x | bitwise_or(rightshift($n); leftshift($width-$n; $width) ); + +def task($x; $y): + def isInteger: type == "number" and . == round; + if ($x|isInteger|not) or ($y|isInteger|not) or + $x < 0 or $y < 0 or $x > 4294967295 or $y > 4294967295 + then "Operands must be in the range of a 32-bit unsigned integer" | error + else + " x = \($x)", + " y = \($y)", + " x & y = \(bitwise_and($x; $y))", + " x | y = \(bitwise_or($x; $y))", + " x ^ y = \(null | xor(x; $y))", + "~x = \(32 | flip($x))", + " x << y = \($x | leftshift($y))", + " x >> y = \($x | rightshift($y))", + " x rl y = \(rotateLeft($x; $y; 32))", + " x rr y = \(rotateRight($x; $y; 32))" + end; + +task(10; 2) diff --git a/Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas b/Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas new file mode 100644 index 0000000000..b1805c5213 --- /dev/null +++ b/Task/Bitwise-operations/PascalABC.NET/bitwise-operations.pas @@ -0,0 +1,9 @@ +begin + var (a,b) := ReadInteger2; + Println($'not {a} = {not a}'); + Println($'{a} and {b} = {a and b}'); + Println($'{a} or {b} = {a or b}'); + Println($'{a} xor {b} = {a xor b}'); + Println($'{a} shl {b} = {a shl b}'); + Println($'{a} shr {b} = {a shr b}'); +end. diff --git a/Task/Blum-integer/Common-Lisp/blum-integer.lisp b/Task/Blum-integer/Common-Lisp/blum-integer.lisp new file mode 100644 index 0000000000..6f3c559ebb --- /dev/null +++ b/Task/Blum-integer/Common-Lisp/blum-integer.lisp @@ -0,0 +1,47 @@ +(defun is-factor (x y) + (zerop (mod x y))) + +(defun is-congruent (num a n) + (= (mod num n) a)) + +(defun is-prime (n) + (cond ((< n 4) (or (= n 2) (= n 3))) + ((or (zerop (mod n 2)) (zerop (mod n 3))) nil) + (t (loop for i from 5 to (floor (sqrt n)) by 6 + never (or (is-factor n i) + (is-factor n (+ i 2))))))) + +(defun first-factor (n) + (loop for i from 2 to (floor (sqrt n)) + thereis (if (is-factor n i) i nil))) + +(defun is-blum (n) + (let ((factor (first-factor n))) + (and factor + (is-congruent factor 3 4) + (/= factor (/ n factor)) + (is-congruent (/ n factor) 3 4) + (is-prime factor) + (is-prime (/ n factor))))) + +(defun main () + (let ((n 0) + (i 1) + (blums '()) + (counts '())) + (dotimes (i 10) (push (cons i 0) counts)) + (loop while (<= n 400000) + do (setf i (+ i 2)) + (when (is-blum i) + (incf n) + (incf (cdr (assoc (mod i 10) counts))) + (when (<= n 50) + (push i blums) + (when (= n 50) + (format t "First 50 Blum integers:~%") + (format t "~{~5d~5d~5d~5d~5d~5d~5d~5d~5d~5d~%~}~%" (reverse blums)))) + (if (find n '(26828 100000 200000 300000 400000)) + (format t "The ~7:dth Blum integer is: ~9:d~%" n i)))) + (format t "~%% distribution of the first 400,000 Blum integers:~%") + (dolist (x '(1 3 7 9)) + (format t "~3$% end in ~a~%" (/ (cdr (assoc x counts)) 4000) x)))) diff --git a/Task/Box-the-compass/Langur/box-the-compass.langur b/Task/Box-the-compass/Langur/box-the-compass.langur index d0f6962819..997f98881a 100644 --- a/Task/Box-the-compass/Langur/box-the-compass.langur +++ b/Task/Box-the-compass/Langur/box-the-compass.langur @@ -1,4 +1,4 @@ -val .box = ["North", "North by east", "North-northeast", "Northeast by north", +val box = ["North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", @@ -7,7 +7,7 @@ val .box = ["North", "North by east", "North-northeast", "Northeast by north", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west"] -val .angles = [ +val angles = [ 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, @@ -16,7 +16,7 @@ val .angles = [ writeln "index degrees compass point" writeln "----- ------- -------------" -for .phi in .angles { - val .i = trunc(.phi * 32 / 360 + 0.5) rem 32 + 1 - writeln $"\{.i:5} \{.phi:r2:6} \{.box[.i]}" +for phi in angles { + val i = trunc(phi * 32 / 360 + 0.5) rem 32 + 1 + writeln "{{i:5}} {{phi:r2:6}} {{box[i]}}" } diff --git a/Task/Brace-expansion/Ada/brace-expansion.ada b/Task/Brace-expansion/Ada/brace-expansion.ada new file mode 100644 index 0000000000..93ddba1ca7 --- /dev/null +++ b/Task/Brace-expansion/Ada/brace-expansion.ada @@ -0,0 +1,58 @@ +pragma Ada_2022; +with Ada.Containers; use Ada.Containers; +with Ada.Containers.Vectors; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +procedure Brace_Expansion is + procedure Expand_Braces (Str : Unbounded_String) is + package Position_Vectors is new Ada.Containers.Vectors (Natural, Natural); + Escaped : Boolean := False; + Depth : Integer := 0; + Brace_Points : Position_Vectors.Vector; + Braces_To_Parse : Position_Vectors.Vector; + Prefix, Suffix, Option : Unbounded_String := Null_Unbounded_String; + begin + for Idx in 1 .. Length (Str) loop + case Element (Str, Idx) is + when '\' => Escaped := not Escaped; + when '{' => + Depth := Depth + 1; + if not Escaped and then Depth = 1 then + Brace_Points.Clear; + Brace_Points.Append (Idx); + end if; + when ',' => + if not Escaped and then Depth = 1 then + Brace_Points.Append (Idx); + end if; + when '}' => + if not Escaped and then Depth = 1 and then Brace_Points.Length > 1 then + Braces_To_Parse.Clear; + Braces_To_Parse.Append_Vector (Brace_Points); + Braces_To_Parse.Append (Idx); + end if; + Depth := Depth - 1; + when others => null; + end case; + if Element (Str, Idx) /= '\' then + Escaped := False; + end if; + end loop; + if Braces_To_Parse.Length > 0 then + Prefix := Unbounded_Slice (Str, 1, Braces_To_Parse (0) - 1); + Suffix := Unbounded_Slice (Str, Braces_To_Parse.Last_Element + 1, Length (Str)); + for Idx in 1 .. Braces_To_Parse.Length - 1 loop + Option := Unbounded_Slice (Str, Braces_To_Parse (Natural (Idx - 1)) + 1, Braces_To_Parse (Natural (Idx)) - 1); + Expand_Braces (Prefix & Option & Suffix); + end loop; + else + Put_Line (Str'Image); + end if; + end Expand_Braces; + function "+"(S : String) return Unbounded_String renames To_Unbounded_String; +begin + Expand_Braces (+"~/{Downloads,Pictures}/*.{jpg,gif,png}"); + Expand_Braces (+"It{{em,alic}iz,erat}e{d,}, please."); + Expand_Braces (+"{,{,gotta have{ ,\, again\, }}more }cowbell!"); + Expand_Braces (+"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"); +end Brace_Expansion; diff --git a/Task/Break-OO-privacy/PascalABC.NET/break-oo-privacy.pas b/Task/Break-OO-privacy/PascalABC.NET/break-oo-privacy.pas new file mode 100644 index 0000000000..a54bbcb2d0 --- /dev/null +++ b/Task/Break-OO-privacy/PascalABC.NET/break-oo-privacy.pas @@ -0,0 +1,15 @@ +uses System.Reflection; + +type MyClass = class +private + x: integer := 5; +public + procedure PrintFields := Print(x); +end; + +begin + var a := new MyClass; + var fi := a.GetType.GetField('x', BindingFlags.Instance or BindingFlags.NonPublic); + fi.SetValue(a,777); + a.PrintFields; +end. diff --git a/Task/Brilliant-numbers/FutureBasic/brilliant-numbers.basic b/Task/Brilliant-numbers/FutureBasic/brilliant-numbers.basic new file mode 100644 index 0000000000..0cfbf2b186 --- /dev/null +++ b/Task/Brilliant-numbers/FutureBasic/brilliant-numbers.basic @@ -0,0 +1,70 @@ +#build Optimization 3 +#build Architecture "Apple Silicon" +// #build Architecture "Intel" +// #build Architecture "Universal" + +local fn isPrime( v as Uint64 ) as bool + if v < 2 then exit fn = NO + select 0 + if ( ( v - 2 ) == 0 || ( v - 3 ) == 0 ) then exit fn = YES + if ( ( v % 2 ) == 0 || ( v % 3 ) == 0 ) then exit fn = NO + end select + + Uint64 f = 5 + while f*f <= v + if v mod f == 0 then exit fn = no + f += 2 + if v mod f == 0 then exit fn = no + f += 4 + wend +end fn = yes + +local fn FirstPrimeFactor( n as UInt64 ) as UInt64 + UInt64 i + if n mod 2 == 0 then exit fn = 2 + if n mod 3 == 0 then exit fn = 3 + i = 5 + while i*i <= n + if n mod i == 0 then exit fn = i + i += 2 + if n mod i == 0 then exit fn = i + i += 4 + wend +end fn = n + +local fn DoBrilliants( expoLimit as UInt64 ) as CFMutableStringRef + UInt64 count = 0, n = 0, ff, sf, expo = 0 + CFMutableStringRef mutStr = fn MutableStringWithString( @"\nFirst 100 brilliant numbers:\n" ) + + do + ff = fn FirstPrimeFactor( n ) + sf = n/ff + if fn IsPrime( sf ) && len( str(ff) ) == len( str(sf) ) + MutableStringAppendFormat( mutStr, @"%7u\b", n ) + count++ + if count mod 10 == 0 then MutableStringAppendFormat( mutStr, @"\n" ) + end if + n++ + until count == 100 + + MutableStringAppendFormat( mutStr, @"\n" ) : count = 0 : n = 0 + + while ( expo != expoLimit ) + ff = fn FirstPrimeFactor( n ) + sf = n/ff + if fn IsPrime( sf ) && len( str(ff) ) = len( str(sf) ) + count++ + if ( n >= 10^expo ) + MutableStringAppendFormat( mutStr, @"%10u (%6d * %-6d) => 10^%d is brilliant at Position No. %d\n", n, ff, sf, expo, count ) + expo++ + end if + end if + n++ + wend +end fn = mutStr + +CFTimeInterval t : t = fn CACurrentMediaTime +CFStringRef brilliants : brilliants = fn DoBrilliants( 7 ) +printf @"%@\n\t\tTime = %.f milliseconds", brilliants, (fn CACurrentMediaTime - t) * 1000 + +HandleEvents diff --git a/Task/Brilliant-numbers/SETL/brilliant-numbers.setl b/Task/Brilliant-numbers/SETL/brilliant-numbers.setl new file mode 100644 index 0000000000..91c2fbfb10 --- /dev/null +++ b/Task/Brilliant-numbers/SETL/brilliant-numbers.setl @@ -0,0 +1,65 @@ +program brilliant_numbers; + init bs := brilliant(4); + + print('First 100 brilliant numbers:'); + loop for n in bs(1..100) do + nprint(lpad(str n, 6)); + if (c +:= 1) mod 10 = 0 then + print; + end if; + end loop; + + loop doing o +:= 1; while exists n = bs(i) | n >= 10**o do + print('First brilliant number >= ' + lpad(str(10**o), 10) + + ': ' + lpad(str n, 10) + ' at position ' + lpad(str i,6)); + end loop; + + proc brilliant(orders); + primes := sieve(10**orders); + groups := group_by_digit_count(primes); + + b := []; + loop for group in groups do + loop for i in [1..#group] do + loop for j in [1..i] do + b with:= group(i) * group(j); + end loop; + end loop; + end loop; + return [x : x in {x : x in b}]; + end proc; + + proc group_by_digit_count(nums); + magn := 10; + groups := []; + group := []; + loop for n in nums do + if n>=magn then + magn *:= 10; + groups with:= group; + group := []; + end if; + group with:= n; + end loop; + if group /= [] then + groups with:= group; + end if; + return groups; + end proc; + + proc sieve(n); + ps := [True] * n; + p := 2; + loop while p*p <= n do + if ps(p) then + c := p*p; + loop while c<=n do + ps(c) := False; + c +:= p; + end loop; + end if; + p +:= 1; + end loop; + return [i : i in [2..n] | ps(i)]; + end proc; +end program; diff --git a/Task/Bulls-and-cows-Player/Ada/bulls-and-cows-player.ada b/Task/Bulls-and-cows-Player/Ada/bulls-and-cows-player.ada index 4034dfea1c..584bad4836 100644 --- a/Task/Bulls-and-cows-Player/Ada/bulls-and-cows-player.ada +++ b/Task/Bulls-and-cows-Player/Ada/bulls-and-cows-player.ada @@ -127,7 +127,7 @@ procedure Bulls_Player is function Has_To_Be_Removed (Position : Positive) return Boolean is Testant : constant Sequence := V.Element (Position); Bull_Score : Natural := 0; - Cows_Score : Natural := 0; + Cow_Score : Natural := 0; begin for I in Testant'Range loop for J in S'Range loop diff --git a/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua b/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua new file mode 100644 index 0000000000..afd3791852 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua @@ -0,0 +1,18 @@ +# Sets and plays a game of Bulls and Cows (Mastermind) + +T ← [⍥(+1⌊×⚂9)4] # Random target +# Score a guess against a target, or vice versa :-). +Score ← ( + :⟜/+=,, # Find bulls. + ⊟⊙(/+↧∩(≡/+⊞=+1⇡9)∩▽⊙:.¬) # Find cows. +) +&p $"_ <- Target\n" T +⍥(☇1⊞⊂.)2+1⇡9 # Proposed targets [1-9 1-9 1-9 1-9] +⍢( + + ⟜(&p$"_\t_",,⟜(Score T)⊡⊸(⌊×⚂⧻)) # Pick from Ps, and play it against T + ▽:⟜(≡≍⊙¤≡Score⊙¤) # Only keep Ps that match that score +| >1⧻ +) +&p↯21@- +&p $"_\t_" :⊸(⟨"UHOH"|"good"⟩≍T)⊢ diff --git a/Task/CRC-32/Jq/crc-32-1.jq b/Task/CRC-32/Jq/crc-32-1.jq new file mode 100644 index 0000000000..38abfc0ed9 --- /dev/null +++ b/Task/CRC-32/Jq/crc-32-1.jq @@ -0,0 +1,2 @@ +def div($j): + ((. - (. % $j)) / $j) | round; diff --git a/Task/CRC-32/Jq/crc-32-2.jq b/Task/CRC-32/Jq/crc-32-2.jq new file mode 100644 index 0000000000..20a741ca65 --- /dev/null +++ b/Task/CRC-32/Jq/crc-32-2.jq @@ -0,0 +1,34 @@ +include "bitwise" {search: "."}; # see above + +# non-negative decimal integer to hex string +def hex: + def stream: + recurse(if . >= 16 then ./16|floor else empty end) | . % 16 ; + [stream] | reverse + | map(if . < 10 then 48 + . else . + 87 end) | implode ; + +### CRC-32 + +def crc32Table: + reduce range(0; 256) as $i ([]; + . + [reduce range(0; 8) as $j ($i; + if bitwise_and(.;1) == 1 + then bitwise_xor(rightshift(1); 3988292384) # 0xedb88320 + else rightshift( 1 ) + end) ] ); + +# Input: an ASCII string +# Output: its CRC-32 +def crc32: + explode as $s + | crc32Table as $table + | reduce range(0; $s|length) as $i (4294967295 ; # ~0 + # 0xff is 255 + bitwise_and(.; 255 ) as $crb + | bitwise_xor( $table[bitwise_xor($crb; $s[$i])] ; rightshift(8)) ) + | flip(32) ; + +def task: + crc32 | hex; + +"The quick brown fox jumps over the lazy dog" | task diff --git a/Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas b/Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas new file mode 100644 index 0000000000..c2a30c8cee --- /dev/null +++ b/Task/CSV-data-manipulation/PascalABC.NET/csv-data-manipulation.pas @@ -0,0 +1,9 @@ +begin + var lines := ReadLines('data.csv').Select((line,i) -> begin + if i = 0 then + Result := line + ',SUM' + else Result := line + ',' + line.Split(',').Sum(x -> x.ToInteger); + end); + WriteLines('outdata.csv',lines); + lines.PrintLines; +end. diff --git a/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua b/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua new file mode 100644 index 0000000000..9e4022ca99 --- /dev/null +++ b/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua @@ -0,0 +1,11 @@ +# Simple CSV manipulation + +# Effect of running `&fras "example.csv"` +$ C1,C2,C3,C4,C5 +$ 1,5,9,13,17 +$ 2,6,10,14,18 +$ 3,7,11,15,19 +$ 4,8,12,16,20 + +&p⍜°csv(⍜⍉⊂:⊂□"SUM"≡(□⍜⋕/+)↘1.) +# Save using `&fwa "example.csv"` diff --git a/Task/CUSIP/Langur/cusip-1.langur b/Task/CUSIP/Langur/cusip-1.langur index 7153ac3e7b..544bb91265 100644 --- a/Task/CUSIP/Langur/cusip-1.langur +++ b/Task/CUSIP/Langur/cusip-1.langur @@ -1,23 +1,23 @@ -val .isCusip = fn(.s) { - if .s is not string or len(.s) != 9 { +val isCusip = fn(s) { + if s is not string or len(s) != 9 { return false } - val .basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" + val basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" - val .sum = for[=0] .i of 8 { - var .v = index(s2s(.s, .i), .basechars) - if not .v: return false - .v = .v[1]-1 - if .i div 2: .v *= 2 - _for += .v \ 10 + .v rem 10 + val sum = for[=0] i of 8 { + var v = index(s2s(s, i), basechars) + if not v: return false + v = v[1]-1 + if i div 2: v *= 2 + _for += v \ 10 + v rem 10 } - .s[9]-'0' == (10-(.sum rem 10)) rem 10 + s[9]-'0' == (10-(sum rem 10)) rem 10 } -val .candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ +val candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ -for .c in .candidates { - writeln .c, ": ", if(.isCusip(.c): "good" ; "bad") +for c in candidates { + writeln c, ": ", if(isCusip(c): "good" ; "bad") } diff --git a/Task/CUSIP/Langur/cusip-2.langur b/Task/CUSIP/Langur/cusip-2.langur index 792cec79d2..ce7d178e29 100644 --- a/Task/CUSIP/Langur/cusip-2.langur +++ b/Task/CUSIP/Langur/cusip-2.langur @@ -1,35 +1,37 @@ -val .isCusip = fn(.s) { - if .s is not string or len(.s) != 9 { +val isCusip = fn(s) { + if s is not string or len(s) != 9 { return false } - val .sum = for[=0] .i of 8 { - val .c = .s[.i] - var .v = 0 + val basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" - switch[and] .c { + val sum = for[=0] i of 8 { + val c = s[i] + var v = 0 + + switch[and] c { case >= '0', <= '9': - .v = .c-'0' + v = c-'0' case >= 'A', <= 'Z': - .v = .c-55 # .c-'A'+10 + v = c-55 # c-'A'+10 - case '*': .v = 36 - case '@': .v = 37 - case '#': .v = 38 + case '*': v = 36 + case '@': v = 37 + case '#': v = 38 default: return false } - if .i div 2: .v *= 2 - _for += .v \ 10 + .v rem 10 + if i div 2: v *= 2 + _for += v \ 10 + v rem 10 } - .s[9]-'0' == (10-(.sum rem 10)) rem 10 + s[9]-'0' == (10-(sum rem 10)) rem 10 } -val .candidates = w/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ +val candidates = fw/037833100 17275R102 38259P508 594918104 68389X106 68389X105/ -for .c in .candidates { - writeln .c, ": ", if(.isCusip(.c): "good" ; "bad") +for c in candidates { + writeln c, ": ", if(isCusip(c): "good" ; "bad") } diff --git a/Task/Caesar-cipher/Elm/caesar-cipher.elm b/Task/Caesar-cipher/Elm/caesar-cipher.elm new file mode 100644 index 0000000000..b4a7c073f9 --- /dev/null +++ b/Task/Caesar-cipher/Elm/caesar-cipher.elm @@ -0,0 +1,88 @@ +module Main exposing (main) + +import Browser +import Html exposing (Html, h2, div, p, input, button, text, textarea) +import Html.Attributes exposing (style, class, placeholder, value) +import Html.Events exposing (onInput, onClick) + + +-- MAIN + +main = + Browser.sandbox { init = init, update = update, view = view } + + +-- MODEL + +type alias Model = + { codeKey : Int + , normtext : String + } + + +init : Model +init = + { codeKey = 3 + , normtext = "" } + + +-- UPDATE + +type Msg + = Change String + | DecKey + | IncKey + + +update : Msg -> Model -> Model +update msg model = + case msg of + DecKey -> + { model | codeKey = model.codeKey - 1} + IncKey -> + { model | codeKey = model.codeKey + 1} + Change newContent -> + { model | normtext = String.toUpper newContent } + + + +encodeChar : Int -> Char -> Char +encodeChar codeKey character = + if Char.isUpper character then + Char.fromCode (modBy 26 (Char.toCode character - 65 + codeKey) + 65) + + else if Char.isLower character then + Char.fromCode (modBy 26 (Char.toCode (Char.toUpper character) - 65 + codeKey) + 65) + + else + character + + +encodeText : Int -> String -> String +encodeText codeKey normtext = + String.map (encodeChar codeKey) normtext + + +subheads aKey = + if aKey > 0 then "Original" + else if aKey < 0 then "Encrypted text" + else "?" + +-- VIEW + +view : Model -> Html Msg +view model = + div [] + [ div [] + [h2 [class "h2style"] [text (subheads model.codeKey)] + , textarea [ class "textframe", placeholder "Write here your text!" + , value model.normtext, onInput Change ] [] + ] + , div [] + [h2 [class "h2style"] [text (subheads (negate model.codeKey))] + , textarea [ class "textframe", value (encodeText model.codeKey model.normtext) ] []] + , div [class "keystyle"] [ button [ class "butstyle", onClick DecKey ] [ text "-1" ] + , text (" Key " ++ String.fromInt model.codeKey) + , button [ class "butstyle", onClick IncKey ] [ text "+1" ] + ] + ] diff --git a/Task/Caesar-cipher/Langur/caesar-cipher.langur b/Task/Caesar-cipher/Langur/caesar-cipher.langur index 2b965df756..3161281621 100644 --- a/Task/Caesar-cipher/Langur/caesar-cipher.langur +++ b/Task/Caesar-cipher/Langur/caesar-cipher.langur @@ -1,10 +1,10 @@ -val .rot = fn(.s, .key) { - cp2s map(fn(.c) rotate(rotate(.c, .key, 'a'..'z'), .key, 'A'..'Z'), s2cp .s) +val rot = fn(s, key) { + cp2s map(fn(c) { rotate(rotate(c, key, 'a'..'z'), key, 'A'..'Z') }, s2cp(s)) } -val .s = "A quick brown fox jumped over something." -val .key = 3 +val s = "A quick brown fox jumped over something, you know." +val key = 3 -writeln " original: ", .s -writeln "encrypted: ", .rot(.s, .key) -writeln "decrypted: ", .rot(.rot(.s, .key), -.key) +writeln " original: ", s +writeln "encrypted: ", rot(s, key) +writeln "decrypted: ", rot(rot(s, key), -key) diff --git a/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cobol b/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cobol index 6a72c6a31e..d20ba6e3fe 100644 --- a/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cobol +++ b/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cobol @@ -1,25 +1,23 @@ - >>SOURCE FORMAT IS FIXED IDENTIFICATION DIVISION. - PROGRAM-ID. EULER. + PROGRAM-ID. euler. DATA DIVISION. WORKING-STORAGE SECTION. - 01 EPSILON USAGE COMPUTATIONAL-2 VALUE 1.0E-15. - 01 FACT USAGE BINARY-DOUBLE UNSIGNED VALUE 1. - 01 N USAGE BINARY-INT UNSIGNED. - 01 E USAGE COMPUTATIONAL-2 VALUE 2.0. - 01 E0 USAGE COMPUTATIONAL-2 value 0.0. - 01 RESULT-MESSAGE. - 03 FILLER PIC X(4) VALUE 'e = '. - 03 RESULT-VALUE PIC 9.9(18) USAGE DISPLAY. + 77 epsilon USAGE FLOAT-LONG VALUE IS 1.0E-15. + 77 fact USAGE IS BINARY-DOUBLE UNSIGNED VALUE IS 1. + 77 n USAGE IS BINARY-LONG UNSIGNED. + 77 e USAGE IS FLOAT-LONG VALUE IS 2.0. + 77 e0 USAGE IS FLOAT-LONG VALUE IS 0.0. + 01 result-message. + 03 FILLER PICTURE IS X(4) VALUE IS 'e = '. + 03 result-value PICTURE IS 9.9(18) USAGE IS DISPLAY. PROCEDURE DIVISION. - MAIN SECTION. - PERFORM - VARYING N FROM 2 BY 1 - UNTIL FUNCTION ABS(E - E0) < EPSILON - MOVE E TO E0 - COMPUTE FACT = FACT * N - COMPUTE E = E + 1.0 / FACT + PERFORM WITH TEST BEFORE VARYING n FROM 2 BY 1 + UNTIL FUNCTION ABS(e - e0) IS LESS THAN epsilon + MOVE e TO e0 + MULTIPLY n BY fact + COMPUTE e = e + 1.0 / fact END-PERFORM. - MOVE E TO RESULT-VALUE. - DISPLAY RESULT-MESSAGE. + MOVE e TO result-value. + DISPLAY result-message. STOP RUN. + END PROGRAM euler. diff --git a/Task/Calculating-the-value-of-e/Langur/calculating-the-value-of-e.langur b/Task/Calculating-the-value-of-e/Langur/calculating-the-value-of-e.langur index 6fda7d65b0..b56040b204 100644 --- a/Task/Calculating-the-value-of-e/Langur/calculating-the-value-of-e.langur +++ b/Task/Calculating-the-value-of-e/Langur/calculating-the-value-of-e.langur @@ -1,17 +1,14 @@ mode divMaxScale = 104 -val .epsilon = 1.0e-104 +val epsilon = 1e-104 -var .e = 2 +var e = 2 -for .fact, .n = 1, 2 ; ; .n += 1 { - val .e0 = .e - .fact *= .n - .e += 1 / .fact - if abs(.e - .e0) < .epsilon: break +for fact, n = 1, 2 ; ; n += 1 { + val e0 = e + fact *= n + e += 1 / fact + if abs(e - e0) < epsilon: break } -writeln ".e = ", .e - -# compare to built-in constant e -writeln " e = ", e +writeln "e = ", e diff --git a/Task/Calculating-the-value-of-e/PascalABC.NET/calculating-the-value-of-e.pas b/Task/Calculating-the-value-of-e/PascalABC.NET/calculating-the-value-of-e.pas new file mode 100644 index 0000000000..e59efe7c9a --- /dev/null +++ b/Task/Calculating-the-value-of-e/PascalABC.NET/calculating-the-value-of-e.pas @@ -0,0 +1,19 @@ +function MyExp(x: real): real; +const eps = 1e-15; +begin + var y := 1.0; + var s := y; + var i := 1; + while y > eps do + begin + y *= x / i; + s += y; + i += 1; + end; + Result := s; +end; + +begin + Println(MyExp(1)); + Println(Exp(1)); +end. diff --git a/Task/Calkin-Wilf-sequence/Uiua/calkin-wilf-sequence.uiua b/Task/Calkin-Wilf-sequence/Uiua/calkin-wilf-sequence.uiua new file mode 100644 index 0000000000..12ed65ccf7 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Uiua/calkin-wilf-sequence.uiua @@ -0,0 +1,28 @@ +# Generate Calkin-Wilf sequence, then use continued fractions +# to discover position in the sequence of any given a/b. + +Gcd ← ⊙◌⍢(⟜◿:|±,)°⊟ +Reduce ← ÷⊸Gcd # Reduce a rational [a b] to its normal form. +Add ← Reduce ⊟⊓/+(⊢⇌)∩×⇌,, # Add pair of rationals [a b] [c d] +Subtract ← Add ⊙⍜⊢¯ # Difference of pair of rationals [a b] [c d] +Multiply ← Reduce × # Multiply pair of rationals [a b] [c d] +Divide ← Multiply ⊙⇌ +Floor ← Reduce ⊟:1⌊/÷⇌ + +CwNext ← ⇌Subtract:⟜(Add1_1Multiply2_1Floor) +&p"First twenty terms of Calkin-Wilf sequence:" +&p/◇⊂≡(□$"_/_ "°⊟)⇌[⍥(CwNext.)20 [1 1]] + +Cf ← ⇌Subtract⟜(.⊟:1⌊÷:°⊟) + +ContFracRat ← ⇌≡⊢↘1[⍢(Cf|≠0⊡1)] # Continued Fraction for rational [a b]. +OddContFrac ← ⍥(⊂:1⍜(↙¯1|-1))¬◿2⧻.ContFracRat # Force length to be odd. +CwPos ← °⋯⇌∧(⊂↯°⊟)⍉⊟⟜(¬◿2⇡⧻):[] OddContFrac # Calculate pos as described. +&p"" +{[9 4] [83116 51639]} +≡◇(&p $"_/_ is at position _ in the sequence"°⊟⟜CwPos) +&p"" +# And show that the relation works in reverse +ContFracInt ← ⍥(⊂0)=0⊢⟜(⊜⧻.+1)⋯ +CwAt ← /(Add⇌)≡(⇌⊟1)⇌ContFracInt +&p$"The number at position _ is _/_"⟜(°⊟CwAt)123456789 diff --git a/Task/Call-a-foreign-language-function/Standard-ML/call-a-foreign-language-function.ml b/Task/Call-a-foreign-language-function/Standard-ML/call-a-foreign-language-function.ml new file mode 100644 index 0000000000..c9de9e4fa6 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Standard-ML/call-a-foreign-language-function.ml @@ -0,0 +1,6 @@ +local + val libc = Foreign.loadLibrary "libc.so.6" + val sym = Foreign.getSymbol libc "strdup" +in + val strdup = Foreign.buildCall1(sym, (Foreign.cString), Foreign.cString) +end diff --git a/Task/Call-a-function/Langur/call-a-function-1.langur b/Task/Call-a-function/Langur/call-a-function-1.langur index 018fdb5723..45f808f68d 100644 --- a/Task/Call-a-function/Langur/call-a-function-1.langur +++ b/Task/Call-a-function/Langur/call-a-function-1.langur @@ -1,2 +1 @@ -.x() -# call user-defined function +x() diff --git a/Task/Call-a-function/Langur/call-a-function-2.langur b/Task/Call-a-function/Langur/call-a-function-2.langur index 5848452119..cab69e190b 100644 --- a/Task/Call-a-function/Langur/call-a-function-2.langur +++ b/Task/Call-a-function/Langur/call-a-function-2.langur @@ -1,2 +1 @@ -write(.key, ": ", .value) -# call built-in with parentheses +write(somestring) diff --git a/Task/Call-a-function/Langur/call-a-function-3.langur b/Task/Call-a-function/Langur/call-a-function-3.langur index 5da32ae269..2b3c4cce69 100644 --- a/Task/Call-a-function/Langur/call-a-function-3.langur +++ b/Task/Call-a-function/Langur/call-a-function-3.langur @@ -1,2 +1 @@ -write .key, ": ", .value -# call built-in with unbounded list +writeln a, b, c diff --git a/Task/Call-a-function/Langur/call-a-function-4.langur b/Task/Call-a-function/Langur/call-a-function-4.langur index bc02bc601c..80e14451fb 100644 --- a/Task/Call-a-function/Langur/call-a-function-4.langur +++ b/Task/Call-a-function/Langur/call-a-function-4.langur @@ -1,3 +1,2 @@ -writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4] -# unbounded lists on writeln and join -# later function join takes remaining arguments +a -> len +# passes a to the len() function diff --git a/Task/Call-a-function/Langur/call-a-function-5.langur b/Task/Call-a-function/Langur/call-a-function-5.langur index f7b4acd094..7faa408981 100644 --- a/Task/Call-a-function/Langur/call-a-function-5.langur +++ b/Task/Call-a-function/Langur/call-a-function-5.langur @@ -1,3 +1 @@ -writeln "numbers: ", join(", ", [.a1, .a2, .a3, .a4]), " === " -# unbounded list on writeln -# join using parentheses so it doesn't take remaining arguments +val fibonacci = fn x:if x < 2 { x } else { fn((x - 1)) + fn((x - 2)) } diff --git a/Task/Call-a-function/Langur/call-a-function-6.langur b/Task/Call-a-function/Langur/call-a-function-6.langur index e124e037e9..1efc364d84 100644 --- a/Task/Call-a-function/Langur/call-a-function-6.langur +++ b/Task/Call-a-function/Langur/call-a-function-6.langur @@ -1,7 +1 @@ -val .sum = foldfrom( - fn(.sum, .i, .c) .sum + number(.c, 36) * .weight[.i], - 0, - pseries len .code, - split .code, -) -# split, pseries, and len using unbounded lists, ending before comma preceding line return +mapX(amb, wordsets...) diff --git a/Task/Call-a-function/Langur/call-a-function-7.langur b/Task/Call-a-function/Langur/call-a-function-7.langur deleted file mode 100644 index 803ab6fdcd..0000000000 --- a/Task/Call-a-function/Langur/call-a-function-7.langur +++ /dev/null @@ -1,4 +0,0 @@ -for .key in sort(keys .tests) { - ... -} -# unbounded list on keys bounded by closing parenthesis of sort diff --git a/Task/Call-an-object-method/PascalABC.NET/call-an-object-method.pas b/Task/Call-an-object-method/PascalABC.NET/call-an-object-method.pas new file mode 100644 index 0000000000..010e6cf3f9 --- /dev/null +++ b/Task/Call-an-object-method/PascalABC.NET/call-an-object-method.pas @@ -0,0 +1,16 @@ +type + Point = auto class // class with autogenerated constructor + x,y: real; + static function RandomPoint := new Point(Random(-10..10),Random(-10..10)); + procedure Print; + begin + Writeln($'{x} {y}'); + end; + end; + +begin + var p := new Point(2,3); + p.Print; // instance method call + p := Point.RandomPoint; // static method call + p.Print; +end. diff --git a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur index 18aee6b560..88328fabe6 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur +++ b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur @@ -1,16 +1,16 @@ -val .X = fn(... .x) .x +val X = fn ...x:x -writeln mapX(.X, [1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]] -writeln mapX(.X, [3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]] -writeln mapX(.X, [1, 2], []) == [] -writeln mapX(.X, [], [1, 2]) == [] +writeln mapX(X, [1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]] +writeln mapX(X, [3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]] +writeln mapX(X, [1, 2], []) == [] +writeln mapX(X, [], [1, 2]) == [] writeln() -writeln mapX .X, [1776, 1789], [7, 12], [4, 14, 23], [0, 1] +writeln mapX(X, [1776, 1789], [7, 12], [4, 14, 23], [0, 1]) writeln() -writeln mapX .X, [1, 2, 3], [30], [500, 100] +writeln mapX(X, [1, 2, 3], [30], [500, 100]) writeln() -writeln mapX .X, [1, 2, 3], [], [500, 100] +writeln mapX(X, [1, 2, 3], [], [500, 100]) writeln() diff --git a/Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua b/Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua new file mode 100644 index 0000000000..2895add665 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Uiua/cartesian-product-of-two-or-more-lists.uiua @@ -0,0 +1,9 @@ +# Cartesian products + +☇1⊞⊂[1 2] [3 4] +☇1⊞⊂[3 4] [1 2] +☇1⊞⊂[3 4] [] +C ← /◇(☇1⊞⊂) +≡⍚C{{[1776 1789] [7 12] [4 14 23] [0 1]} + {[1 2 3] [30] [500 100]} + {[1 2 3] [] [500 100]}} diff --git a/Task/Catalan-numbers/Langur/catalan-numbers.langur b/Task/Catalan-numbers/Langur/catalan-numbers.langur index b5b6f9f98e..81d8b2e82f 100644 --- a/Task/Catalan-numbers/Langur/catalan-numbers.langur +++ b/Task/Catalan-numbers/Langur/catalan-numbers.langur @@ -1,9 +1,9 @@ -val .factorial = fn(.x) if(.x < 2: 1; .x x self(.x - 1)) +val factorial = fn x:if(x < 2: 1; x * self(x - 1)) -val .catalan = fn(.n) .factorial(2 x .n) / .factorial(.n+1) / .factorial(.n) +val catalan = fn n:factorial(2 * n) / factorial(n+1) / factorial(n) -for .i in 0..15 { - writeln $"\.i:2;: \(.catalan(.i):10)" +for i in 0..15 { + writeln "{{i:2}}: {{catalan(i):10}}" } -writeln "10000: ", .catalan(10000) +writeln "10000: ", catalan(10000) diff --git a/Task/Catmull-Clark-subdivision-surface/C++/catmull-clark-subdivision-surface.cpp b/Task/Catmull-Clark-subdivision-surface/C++/catmull-clark-subdivision-surface.cpp new file mode 100644 index 0000000000..1fab0fe9be --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/C++/catmull-clark-subdivision-surface.cpp @@ -0,0 +1,261 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// A point of the current Catmull-Clark surface. +class Point { +public: + Point() : x(0.0), y(0.0), z(0.0) { } + Point(const double& aX, const double& aY, const double& aZ) : x(aX), y(aY), z(aZ) { } + + Point add(const Point& other) const { + return Point(x + other.x, y + other.y, z + other.z); + } + + Point multiply(const double& factor) const { + return Point(x * factor, y * factor, z * factor); + } + + Point divide(const double& factor) const { + return multiply(1.0 / factor); + } + + bool operator<(const Point& other) const { + return ( x < other.x ) || ( ( x == other.x && y < other.y ) ) + || ( x == other.x && y == other.y && z < other.z ); + } + + bool operator==(const Point& other) const { + return x == other.x && y == other.y && z == other.z; + } + + Point& operator=(const Point& other) { + if ( *this != other ) { + x = other.x; y = other.y; z = other.z; + } + return *this; + } + + std::string to_string() const { + return "(" + format(x) + ", " + format(y) + ", " + format(z) + ")"; + } + +private: + std::string format(const double& value) const { + std::stringstream stream; + stream << std::fixed << std::setprecision(3) << value; + return ( value >= 0 ) ? " " + stream.str() : stream.str(); + } + + double x, y, z; +}; + +// Return the centroid point of the given vector of points. +Point centroid(const std::vector& points) { + Point sum; + for ( const Point& point : points ) { + sum = sum.add(point); + } + return sum.divide(points.size()); +} + +// An edge of the current Catmull-Clark surface. +class Edge { +public: + Edge(Point aBegin, Point aEnd) { + if ( aEnd < aBegin ) { + std::swap(aBegin, aEnd); + } + begin = aBegin; end = aEnd; + + mid_edge = centroid({ begin, end }); + hole_edge = false; + } + + bool contains(const Point& point) const { + return point == begin || point == end; + } + + bool operator<(const Edge other) const { + return ( begin < other.begin ) || ( begin == other.begin && end < other.end ); + } + + bool operator==(const Edge& other) const { + return contains(other.begin) && contains(other.end); + } + + bool hole_edge; + Point begin, end, mid_edge, edge_point; +}; + +// A face of the current Catmull-Clark surface. +class Face { +public: + Face(std::vector aVertices) { + vertices = aVertices; + face_point = centroid(vertices); + + for ( uint64_t i = 0; i < vertices.size() - 1; ++i ) { + edges.emplace_back(Edge(vertices[i], vertices[i + 1])); + } + edges.emplace_back(Edge(vertices.back(), vertices.front())); + } + + bool contains(const Point& vertex) const { + return std::find(vertices.begin(), vertices.end(), vertex) != vertices.end(); + } + + bool contains(Edge edge) const { + return contains(edge.begin) && contains(edge.end); + } + + std::string toString() const { + std::string result = "Face: "; + for ( uint64_t i = 0; i < vertices.size() - 1; ++i ) { + result += vertices[i].to_string() + ", "; + } + return result + vertices.back().to_string(); + } + + std::vector vertices; + std::vector edges; + Point face_point; +}; + +// Return a map containing, for each vertex, +// the new vertex created by the current iteration of the Catmull-Clark surface subdivision algorithm. +std::map next_vertices(const std::vector& edges, const std::vector& faces) { + std::map next_vertices = { }; + std::set vertices = { }; + for ( const Face& face : faces ) { + for ( const Point& vertex : face.vertices ) { + vertices.emplace(vertex); + } + } + + for ( const Point& vertex : vertices ) { + std::vector faces_for_vertex = { }; + for ( const Face& face : faces ) { + if ( face.contains(vertex) ) { + faces_for_vertex.emplace_back(face); + } + } + + std::set edges_for_vertex = { }; + for ( const Edge& edge : edges ) { + if ( edge.contains(vertex) ) { + edges_for_vertex.emplace(edge); + } + } + + if ( faces_for_vertex.size() != edges_for_vertex.size() ) { + std::vector mid_edge_of_hole_edges = { }; + for ( const Edge& edge : edges_for_vertex ) { + if ( edge.hole_edge ) { + mid_edge_of_hole_edges.emplace_back(edge.mid_edge); + } + } + mid_edge_of_hole_edges.emplace_back(vertex); + next_vertices[vertex] = centroid(mid_edge_of_hole_edges); + } else { + const uint64_t face_count = faces_for_vertex.size(); + const double multiple_1 = static_cast(( face_count - 3 ) / face_count); + const double multiple_2 = 1.0 / face_count; + const double multiple_3 = 2.0 / face_count; + + Point next_vertex_1 = vertex.multiply(multiple_1); + std::vector face_points = { }; + for ( const Face& face : faces_for_vertex ) { + face_points.emplace_back(face.face_point); + } + Point next_vertex_2 = centroid(face_points).multiply(multiple_2); + std::vector mid_edges = { }; + for ( const Edge& edge : edges_for_vertex ) { + mid_edges.emplace_back(edge.mid_edge); + } + Point next_vertex_3 = centroid(mid_edges).multiply(multiple_3); + Point next_vertex_4 = next_vertex_1.add(next_vertex_2); + + next_vertices[vertex] = next_vertex_4.add(next_vertex_3); + } + } + return next_vertices; +} + +// The Catmull-Clarke surface subdivision algorithm. +std::vector catmull_clark_surface_subdivision(std::vector& faces) { + // Determine, for each edge, whether or not it is an edge of a hole, and set its edge point accordingly. + for ( Face& face : faces ) { + for ( Edge& edge : face.edges ) { + std::vector face_points_for_edge = { }; + for ( const Face& search_face : faces ) { + if ( search_face.contains(edge) ) { + face_points_for_edge.emplace_back(search_face.face_point); + } + } + + if ( face_points_for_edge.size() == 2 ) { + edge.hole_edge = false; + edge.edge_point = centroid({ edge.mid_edge, centroid(face_points_for_edge) }); + } else { + edge.hole_edge = true; + edge.edge_point = edge.mid_edge; + } + } + } + + std::vector edges = { }; + for ( const Face& face : faces ) { + for ( const Edge& edge : face.edges ) { + edges.emplace_back(edge); + } + } + std::map next_vertex_map = next_vertices(edges, faces); + + std::vector next_faces = { }; + for ( Face face : faces ) { // The face may contain any number of points + if ( face.vertices.size() >= 3 ) { // A face with 2 or fewer points does not contribute to the surface + Point face_point = face.face_point; + for ( uint64_t i = 0; i < face.vertices.size(); ++i ) { + next_faces.emplace_back(Face({ + next_vertex_map[face.vertices[i]], + face.edges[i].edge_point, + face_point, + face.edges[( i - 1 + face.vertices.size() ) % face.vertices.size()].edge_point})); + } + } + } + return next_faces; +} + +// Display the current Catmull-Clark surface on the console. +void displaySurface(const std::vector faces) { + std::cout << "Surface {" << std::endl; + for ( const Face& face : faces ) { + std::cout << face.toString() << std::endl; + } + std::cout << "}" << std::endl << std::endl; +} + +int main() { + std::vector faces = { + Face({ Point(-1.0, 1.0, 1.0), Point(-1.0, -1.0, 1.0), Point( 1.0, -1.0, 1.0), Point( 1.0, 1.0, 1.0) }), + Face({ Point( 1.0, 1.0, 1.0), Point( 1.0, -1.0, 1.0), Point( 1.0, -1.0, -1.0), Point( 1.0, 1.0, -1.0) }), + Face({ Point( 1.0, 1.0, -1.0), Point( 1.0, -1.0, -1.0), Point(-1.0, -1.0, -1.0), Point(-1.0, 1.0, -1.0) }), + Face({ Point(-1.0, 1.0, -1.0), Point(-1.0, 1.0, 1.0), Point( 1.0, 1.0, 1.0), Point( 1.0, 1.0, -1.0) }), + Face({ Point(-1.0, 1.0, -1.0), Point(-1.0, -1.0, -1.0), Point(-1.0, -1.0, 1.0), Point(-1.0, 1.0, 1.0) }), + Face({ Point(-1.0, -1.0, -1.0), Point(-1.0, -1.0, 1.0), Point( 1.0, -1.0, 1.0), Point( 1.0, -1.0, -1.0) })}; + + displaySurface(faces); + const uint32_t iterations = 1; + for ( uint32_t i = 0; i < iterations; ++i ) { + faces = catmull_clark_surface_subdivision(faces); + } + displaySurface(faces); +} diff --git a/Task/Catmull-Clark-subdivision-surface/Java/catmull-clark-subdivision-surface.java b/Task/Catmull-Clark-subdivision-surface/Java/catmull-clark-subdivision-surface.java new file mode 100644 index 0000000000..2d363ef4da --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/Java/catmull-clark-subdivision-surface.java @@ -0,0 +1,257 @@ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; + +public final class CatmullClarkSurfaceSubdivision { + + public static void main(String[] args) { + List faces = List.of( new Face(List.of( new Point(-1.0, 1.0, 1.0), + new Point(-1.0, -1.0, 1.0), + new Point( 1.0, -1.0, 1.0), + new Point( 1.0, 1.0, 1.0) )), + + new Face(List.of( new Point( 1.0, 1.0, 1.0), + new Point( 1.0, -1.0, 1.0), + new Point( 1.0, -1.0, -1.0), + new Point( 1.0, 1.0, -1.0) )), + + new Face(List.of( new Point( 1.0, 1.0, -1.0), + new Point( 1.0, -1.0, -1.0), + new Point(-1.0, -1.0, -1.0), + new Point(-1.0, 1.0, -1.0) )), + + new Face(List.of( new Point(-1.0, 1.0, -1.0), + new Point(-1.0, 1.0, 1.0), + new Point( 1.0, 1.0, 1.0), + new Point( 1.0, 1.0, -1.0) )), + + new Face(List.of( new Point(-1.0, 1.0, -1.0), + new Point(-1.0, -1.0, -1.0), + new Point(-1.0, -1.0, 1.0), + new Point(-1.0, 1.0, 1.0) )), + + new Face(List.of( new Point(-1.0, -1.0, -1.0), + new Point(-1.0, -1.0, 1.0), + new Point( 1.0, -1.0, 1.0), + new Point( 1.0, -1.0, -1.0) )) ); + + displaySurface(faces); + final int iterations = 1; + for ( int i = 0; i < iterations; i++ ) { + faces = catmullClarkSurfaceSubdivision(faces); + } + displaySurface(faces); + } + + // The Catmull-Clarke surface subdivision algorithm. + private static List catmullClarkSurfaceSubdivision(List faces) { + // Determine, for each edge, whether or not it is an edge of a hole, and set its edge point accordingly. + List edges = faces.stream().map( face -> face.edges.stream() ).flatMap(Function.identity()).toList(); + for ( Edge edge : edges ) { + List facePointsForEdge = + faces.stream().filter( face -> face.contains(edge) ).map( face -> face.facePoint ).toList(); + if ( facePointsForEdge.size() == 2 ) { + edge.holeEdge = false; + edge.edgePoint = centroid(List.of( edge.midEdge, centroid(facePointsForEdge) )); + } else { + edge.holeEdge = true; + edge.edgePoint = edge.midEdge; + } + } + + Map nextVertices = nextVertices(edges, faces); + + List nextFaces = new ArrayList(); + for ( Face face : faces ) { // The face may contain any number of points + if ( face.vertices.size() >= 3 ) { // A face with 2 or fewer points does not contribute to the surface + Point facePoint = face.facePoint; + for ( int i = 0; i < face.vertices.size(); i++ ) { + nextFaces.addLast( new Face(List.of( + nextVertices.get(face.vertices.get(i)), + face.edges.get(i).edgePoint, + facePoint, + face.edges.get(Math.floorMod(i - 1, face.vertices.size())).edgePoint )) ); + } + } + } + return nextFaces; + } + + // Return a map containing, for each vertex, + // the new vertex created by the current iteration of the Catmull-Clark surface subdivision algorithm. + private static Map nextVertices(List edges, List faces) { + Map nextVertices = new HashMap(); + List vertices = + faces.stream().map( face -> face.vertices.stream() ).flatMap(Function.identity()).distinct().toList(); + + for ( Point vertex : vertices ) { + List facesForVertex = faces.stream().filter( face -> face.contains(vertex) ).toList(); + List edgesForVertex = edges.stream().filter( edge -> edge.contains(vertex) ).distinct().toList(); + + if ( facesForVertex.size() != edgesForVertex.size() ) { + List midEdgeOfHoleEdges = edgesForVertex.stream().filter( edge -> edge.holeEdge ) + .map( edge -> edge.midEdge ).collect(Collectors.toList()); + midEdgeOfHoleEdges.add(vertex); + nextVertices.put(vertex, centroid(midEdgeOfHoleEdges)); + } else { + final int faceCount = facesForVertex.size(); + final double multipleOne = (double) ( faceCount - 3 ) / faceCount; + final double multipleTwo = 1.0 / faceCount; + final double multipleThree = 2.0 / faceCount; + + Point nextVertexOne = vertex.multiply(multipleOne); + List facePoints = facesForVertex.stream().map( face -> face.facePoint ).toList(); + Point nextVertexTwo = centroid(facePoints).multiply(multipleTwo); + List midEdges = edgesForVertex.stream().map( edge -> edge.midEdge ).toList(); + Point nextVertexThree = centroid(midEdges).multiply(multipleThree); + Point nextVertexFour = nextVertexOne.add(nextVertexTwo); + + nextVertices.put(vertex, nextVertexFour.add(nextVertexThree)); + } + } + return nextVertices; + } + + // Return the centroid point of the given list of points. + private static Point centroid(List points) { + return points.stream().reduce(Point.ZERO, (left, right) -> left.add(right) ).divide(points.size()); + } + + // Display the current Catmull-Clark surface on the console. + private static void displaySurface(List faces) { + System.out.println("Surface {"); + faces.stream().forEach(System.out::println); + System.out.println("}" + System.lineSeparator()); + } + + // A point of the current Catmull-Clark surface. + private static final class Point implements Comparable { + + public Point(double aX, double aY, double aZ) { + x = aX; y = aY; z = aZ; + } + + @Override + public int compareTo(Point other) { + if ( x == other.x ) { + if ( y == other.y ) { + return Double.compare(z, other.z); + } + return Double.compare(y, other.y); + } + return Double.compare(x, other.x); + } + + @Override + public boolean equals(Object other) { + return switch ( other ) { + case Point point -> x == point.x && y == point.y && z == point.z; + default -> false; + }; + } + + @Override + public int hashCode() { + return Objects.hash(x, y, z); + } + + public Point add(Point other) { + return new Point(x + other.x, y + other.y, z + other.z); + } + + public Point multiply(double factor) { + return new Point(x * factor, y * factor, z * factor); + } + + public Point divide(double factor) { + return multiply(1.0 / factor); + } + + public String toString() { + return "(" + format(x) + ", " + format(y) + ", " + format(z) + ")"; + } + + public static Point ZERO = new Point(0.0, 0.0, 0.0); + + private String format(double value) { + return ( value >= 0 ) ? String.format(" %.3f", value) : String.format("%.3f", value); + } + + private final double x, y, z; + + } + + // An edge of the current Catmull-Clark surface. + private static final class Edge { + + public Edge(Point aBegin, Point aEnd) { + if ( aBegin.compareTo(aEnd) <= 0 ) { + begin = aBegin; end = aEnd; + } else { + begin = aEnd; end = aBegin; + } + + midEdge = centroid(List.of( begin, end )); + } + + @Override + public boolean equals(Object other) { + return switch ( other ) { + case Edge edge -> begin.equals(edge.begin) && end.equals(edge.end); + default -> false; + }; + } + + @Override + public int hashCode() { + return Objects.hash(begin, end); + } + + public boolean contains(Point point) { + return point.equals(begin) || point.equals(end); + } + + public boolean holeEdge; + public Point edgePoint; + + public final Point begin, end, midEdge; + + } + + // A face of the current Catmull-Clark surface. + private static final class Face { + + public Face(List aVertices) { + vertices = new ArrayList(aVertices); + facePoint = centroid(vertices); + + edges = new ArrayList(); + for ( int i = 0; i < vertices.size() - 1; i++ ) { + edges.addLast( new Edge(vertices.get(i), vertices.get(i + 1)) ); + } + edges.addLast( new Edge(vertices.getLast(), vertices.getFirst()) );; + } + + public boolean contains(Point vertex) { + return vertices.contains(vertex); + } + + public boolean contains(Edge edge) { + return contains(edge.begin) && contains(edge.end); + } + + public String toString() { + return "Face: " + vertices.stream().map( point -> point.toString() ).collect(Collectors.joining("; ")); + } + + public final List vertices; + public final Point facePoint; + public final List edges; + + } + +} diff --git a/Task/Character-codes/Langur/character-codes.langur b/Task/Character-codes/Langur/character-codes.langur index 14eaab6abe..e24d7430fe 100644 --- a/Task/Character-codes/Langur/character-codes.langur +++ b/Task/Character-codes/Langur/character-codes.langur @@ -1,11 +1,11 @@ -val .a1 = 'a' -val .a2 = 97 -val .a3 = "a"[1] -val .a4 = s2cp "a", 1 -val .a5 = [.a1, .a2, .a3, .a4] +val a1 = 'a' +val a2 = 97 +val a3 = "a"[1] +val a4 = s2cp("a", 1) +val a5 = [a1, a2, a3, a4] -writeln .a1 == .a2 -writeln .a2 == .a3 -writeln .a3 == .a4 -writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4, .a5] -writeln "letters: ", join ", ", map cp2s, [.a1, .a2, .a3, .a4, .a5] +writeln a1 == a2 +writeln a2 == a3 +writeln a3 == a4 +writeln "numbers: ", join(", ", map(string, [a1, a2, a3, a4, a5])) +writeln "letters: ", join(", ", map(cp2s, [a1, a2, a3, a4, a5])) diff --git a/Task/Character-codes/PascalABC.NET/character-codes.pas b/Task/Character-codes/PascalABC.NET/character-codes.pas new file mode 100644 index 0000000000..deacfdd34e --- /dev/null +++ b/Task/Character-codes/PascalABC.NET/character-codes.pas @@ -0,0 +1,6 @@ +begin + var c := 'a'; + var i := c.Code; + Println(i); + Println(Chr(i)) +end. diff --git a/Task/Check-output-device-is-a-terminal/FutureBasic/check-output-device-is-a-terminal.basic b/Task/Check-output-device-is-a-terminal/FutureBasic/check-output-device-is-a-terminal.basic new file mode 100644 index 0000000000..28d25d962b --- /dev/null +++ b/Task/Check-output-device-is-a-terminal/FutureBasic/check-output-device-is-a-terminal.basic @@ -0,0 +1,17 @@ +include "NSLog.incl" + +local fn IsOutputDeviceTerminal as BOOL + int fileDescriptor + + cln fileDescriptor = fileno( stdout ); +end fn = fn isatty( fileDescriptor ) != 0 + +BOOL isTerminal : isTerminal = fn IsOutputDeviceTerminal + +if (isTerminal) + NSLog( @"Output is directed to a terminal." ) +else + NSLog( @"Output is not directed to a terminal." ) +end if + +HandleEvents diff --git a/Task/Check-that-file-exists/Langur/check-that-file-exists.langur b/Task/Check-that-file-exists/Langur/check-that-file-exists.langur index 841b121d3c..a275544023 100644 --- a/Task/Check-that-file-exists/Langur/check-that-file-exists.langur +++ b/Task/Check-that-file-exists/Langur/check-that-file-exists.langur @@ -1,7 +1,7 @@ -val .printresult = impure fn(.file) { - write .file, ": " - if val .p = prop(.file) { - if .p'isdir { +val printresult = impure fn(file) { + write file, ": " + if val p = prop(file) { + if p'isdir { writeln "is directory" } else { writeln "is file" @@ -11,7 +11,7 @@ val .printresult = impure fn(.file) { } } -.printresult("input.txt") -.printresult("/input.txt") -.printresult("docs") -.printresult("/docs") +printresult "input.txt" +printresult "/input.txt" +printresult "docs" +printresult "/docs" diff --git a/Task/Cheryls-birthday/11l/cheryls-birthday-1.11l b/Task/Cheryls-birthday/11l/cheryls-birthday-1.11l index 3412eb1266..c8d7794b3e 100644 --- a/Task/Cheryls-birthday/11l/cheryls-birthday-1.11l +++ b/Task/Cheryls-birthday/11l/cheryls-birthday-1.11l @@ -1,9 +1,4 @@ -T Date - String month - Int day - F (month, day) - .month = month - .day = day +T Date = (String month, Int day) V dates = [Date(‘May’, 15), Date(‘May’, 16), Date(‘May’, 19), Date(‘June’, 17), Date(‘June’, 18), Date(‘July’, 14), Date(‘July’, 16), Date(‘August’, 14), Date(‘August’, 15), Date(‘August’, 17)] diff --git a/Task/Circles-of-given-radius-through-two-points/11l/circles-of-given-radius-through-two-points.11l b/Task/Circles-of-given-radius-through-two-points/11l/circles-of-given-radius-through-two-points.11l index 1efeac8878..5bc57a434f 100644 --- a/Task/Circles-of-given-radius-through-two-points/11l/circles-of-given-radius-through-two-points.11l +++ b/Task/Circles-of-given-radius-through-two-points/11l/circles-of-given-radius-through-two-points.11l @@ -1,14 +1,7 @@ -T Circle - Float x, y, r - +T Circle((Float x, Float y, Float r)) F String() R ‘Circle(x=#.6, y=#.6, r=#.6)’.format(.x, .y, .r) - F (x, y, r) - .x = x - .y = y - .r = r - T Error String msg F (msg) diff --git a/Task/Classes/PascalABC.NET/classes.pas b/Task/Classes/PascalABC.NET/classes.pas new file mode 100644 index 0000000000..7d5590bdae --- /dev/null +++ b/Task/Classes/PascalABC.NET/classes.pas @@ -0,0 +1,16 @@ +type Person = class + Name: string; + Age: integer; +public + constructor (Name: string; Age: integer); + begin + Self.Name := Name; + Self.Age := Age; + end; + procedure Output := Print($'{Name} {Age}'); +end; + +begin + var p := new Person('John',18); + p.Output +end. diff --git a/Task/Closest-pair-problem/PascalABC.NET/closest-pair-problem.pas b/Task/Closest-pair-problem/PascalABC.NET/closest-pair-problem.pas new file mode 100644 index 0000000000..5d83e6b24a --- /dev/null +++ b/Task/Closest-pair-problem/PascalABC.NET/closest-pair-problem.pas @@ -0,0 +1,24 @@ +type Point = auto class + x,y: real; + function Distance(p: Point): real := Sqrt((x-p.x)**2 + (y-p.y)**2); +end; + +function Pnt(x,y: real) := new Point(x,y); + +function RandomPoint: Point := Pnt(RandomReal(0,10),RandomReal(0,10)); + +function ClosestPair(points: array of Point): (Point,Point); +begin + var pairs := points.Combinations(2); + var pair := pairs.MinBy(pair -> pair[0].Distance(pair[1])); + Result := (pair[0],pair[1]); +end; + +begin + var points := ArrGen(10,i -> RandomPoint); + points.Println; + + var ClPair := ClosestPair(points); + + Println(ClPair,ClPair[0].Distance(ClPair[1])); +end. diff --git a/Task/Closures-Value-capture/Free-Pascal-Lazarus/closures-value-capture.pas b/Task/Closures-Value-capture/Free-Pascal-Lazarus/closures-value-capture.pas new file mode 100644 index 0000000000..58142c4cd7 --- /dev/null +++ b/Task/Closures-Value-capture/Free-Pascal-Lazarus/closures-value-capture.pas @@ -0,0 +1,26 @@ +program testthis; +{$mode objfpc}{$modeswitch functionreferences}{$modeswitch anonymousfunctions} +type + TFuncIntResult = reference to function: Integer; + +// use function that returns anonymous method to avoid capturing the loop variable +function CreateFunc(i: Integer): TFuncIntResult; +begin + Result := + function: Integer + begin + Result := i * i; + end; +end; + +var + Funcs: array[0..9] of TFuncIntResult; + i: integer; +begin + // create 10 anonymous functions + for i := Low(Funcs) to High(Funcs) do + Funcs[i] := CreateFunc(i); + // call all 10 functions + for i := Low(Funcs) to High(Funcs) do + Writeln(Funcs[i]()); +end. diff --git a/Task/Closures-Value-capture/Go/closures-value-capture.go b/Task/Closures-Value-capture/Go/closures-value-capture-1.go similarity index 100% rename from Task/Closures-Value-capture/Go/closures-value-capture.go rename to Task/Closures-Value-capture/Go/closures-value-capture-1.go diff --git a/Task/Closures-Value-capture/Go/closures-value-capture-2.go b/Task/Closures-Value-capture/Go/closures-value-capture-2.go new file mode 100644 index 0000000000..432b04a5de --- /dev/null +++ b/Task/Closures-Value-capture/Go/closures-value-capture-2.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func main() { + fs := make([]func() int, 10) + for i := range fs { + fs[i] = func() int { + return i * i + } + } + fmt.Println("func #0:", fs[0]()) + fmt.Println("func #3:", fs[3]()) +} diff --git a/Task/Collections/PascalABC.NET/collections.pas b/Task/Collections/PascalABC.NET/collections.pas new file mode 100644 index 0000000000..5b1d1d7212 --- /dev/null +++ b/Task/Collections/PascalABC.NET/collections.pas @@ -0,0 +1,25 @@ +begin + // build-in array + var a: array of integer := new integer[5] (1,2,3,4,5); + // build-in multidimensional array + var aa: array [,] of integer := new integer[4,3]((1,2,3),(4,5,6),(7,8,9),(1,2,3)); + // List is a resizable array + var lst := new List(a); + lst.Add(1); + lst.AddRange(|2,3|); + // HashSet is an unordered set, SortedSet is ordered + var hs := new HashSet; + var ss := new SortedSet; + hs.Add(1); ss.Add(2); + // Dictionary is an unordered map, SortedDictionary is ordered + var d := new Dictionary; + d['str1'] := 1; d['str2'] := 3; + var sd := new SortedDictionary; + sd['str1'] := 1; sd['str2'] := 3; + + // Stack and Queue + var s := new Stack; + s.Push(1); s.Push(2); s.Push(3); + var q := new Queue; + q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); +end. diff --git a/Task/Color-wheel/Ada/color-wheel.ada b/Task/Color-wheel/Ada/color-wheel.ada new file mode 100644 index 0000000000..24fc322aeb --- /dev/null +++ b/Task/Color-wheel/Ada/color-wheel.ada @@ -0,0 +1,89 @@ +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; +procedure Color_Wheel is + type Colour_Level is mod 2 ** 8; + type RGB is record + R, G, B : Colour_Level; + end record; + BLACK : constant RGB := (0, 0, 0); + type Image_Grid is array (Integer range <>, Integer range <>) of RGB; + + Diameter : constant Integer := 480; + Radius : constant Integer := Diameter / 2; + Radius_Fl : constant Float := Float (Radius); + Image : Image_Grid (-Radius .. Radius, -Radius .. Radius); + V : constant Float := 1.0; + + procedure Write_PPM (Grid : Image_Grid; Filename : String) is + PPM_File : File_Type; + begin + Create (PPM_File, Out_File, Filename); + Put_Line (PPM_File, "P3"); + Put_Line (PPM_File, Grid'Length (1)'Image & Grid'Length (2)'Image); + Put_Line (PPM_File, "255"); + for Y in reverse -Radius .. Radius loop + for X in -Radius .. Radius loop + Put_Line (PPM_File, Grid (X, Y).R'Image & Grid (X, Y).G'Image & Grid (X, Y).B'Image); + end loop; + end loop; + Close (PPM_File); + end Write_PPM; + + function Atan2 (Y, X : Float) return Float is + Res : Float; + begin + if X > 0.0 then Res := Arctan (Y / X); + elsif X < 0.0 and then Y >= 0.0 then Res := Arctan (Y / X) + Pi; + elsif X < 0.0 and then Y < 0.0 then Res := Arctan (Y / X) - Pi; + elsif X = 0.0 and then Y > 0.0 then Res := Pi / 2.0; + elsif X = 0.0 and then Y > 0.0 then Res := -Pi / 2.0; + else Res := -Pi / 2.0; -- Technically: Undefined + end if; + return Res; + end Atan2; +begin + for Y in -Radius .. Radius loop + for X in -Radius .. Radius loop + declare + XX : constant Float := Float (X); + YY : constant Float := Float (Y); + Dist : constant Float := Sqrt (XX ** 2 + YY ** 2); + Hue_Int, Hue_Frac, P, Q, T : Float; + Point : RGB; + begin + if Dist <= Radius_Fl then + declare + Sat : constant Float := Dist / Radius_Fl; + Hue : Float := Atan2 (YY, XX); + RR, GG, BB : Float; + begin + if Hue < 0.0 then Hue := Hue + 2.0 * Pi; end if; + Hue := (Hue * 180.0 / Pi) / 60.0; + Hue_Int := Float'Floor (Hue); + Hue_Frac := Hue - Hue_Int; + P := V - Sat; + Q := V - Sat * Hue_Frac; + T := V - Sat * (V - Hue_Frac); + case Integer (Hue_Int) is + when 0 => RR := V; GG := T; BB := P; + when 1 => RR := Q; GG := V; BB := P; + when 2 => RR := P; GG := V; BB := T; + when 3 => RR := P; GG := Q; BB := V; + when 4 => RR := T; GG := P; BB := V; + when 5 => RR := V; GG := P; BB := Q; + when others => null; + end case; + Point.R := Colour_Level (Integer (Float'Floor (RR * 255.0))); + Point.G := Colour_Level (Integer (Float'Floor (GG * 255.0))); + Point.B := Colour_Level (Integer (Float'Floor (BB * 255.0))); + Image (X, Y) := Point; + end; + else + Image (X, Y) := BLACK; + end if; + end; + end loop; + end loop; + Write_PPM (Image, "color_wheel.ppm"); +end Color_Wheel; diff --git a/Task/Combinations-and-permutations/Ada/combinations-and-permutations.ada b/Task/Combinations-and-permutations/Ada/combinations-and-permutations.ada new file mode 100644 index 0000000000..a93710e140 --- /dev/null +++ b/Task/Combinations-and-permutations/Ada/combinations-and-permutations.ada @@ -0,0 +1,69 @@ +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Big_Numbers.Big_Integers; +use Ada.Numerics.Big_Numbers.Big_Integers; +with Interfaces; use Interfaces; + +procedure Combs_Perms is + + function U64_Perm (N, K : Unsigned_64) return Unsigned_64 is + P : Unsigned_64 := 1; + begin + if K = 0 then + P := 0; + else + for I in 0 .. K - 1 loop + P := P * (N - I); + end loop; + end if; + return P; + end U64_Perm; + + function Big_Perm (N, K : Natural) return Big_Natural is + P : Big_Natural := 1; + begin + if K = 0 then + P := 0; + else + for I in 0 .. K - 1 loop + P := P * To_Big_Integer (N - I); + end loop; + end if; + return P; + end Big_Perm; + + function U64_Comb (N, K : Unsigned_64) return Unsigned_64 is + Adj_K : constant Unsigned_64 := (if N - K < K then N - K else K); + C : Unsigned_64 := U64_Perm (N, Adj_K); + begin + if K = 0 then + C := 0; + else + for I in reverse 1 .. Adj_K loop + C := C / I; + end loop; + end if; + return C; + end U64_Comb; + + function Big_Comb (N, K : Natural) return Big_Natural is + Adj_K : constant Natural := (if N - K < K then N - K else K); + C : Big_Natural := Big_Perm (N, Adj_K); + begin + for I in reverse 1 .. Adj_K loop + C := C / To_Big_Integer (I); + end loop; + return C; + end Big_Comb; + +begin + Put_Line ("P(1, 0) =" & U64_Perm (1, 0)'Image); + Put_Line ("P(12, 4) =" & U64_Perm (12, 4)'Image); + Put_Line ("P(60, 20) =" & U64_Perm (60, 20)'Image); + Put_Line ("P(105, 103) =" & Big_Perm (105, 103)'Image); + Put_Line ("P(15000, 333) =" & Big_Perm (10000, 333)'Image); + + Put_Line ("C(10, 5) =" & U64_Comb (10, 5)'Image); + Put_Line ("C(60, 30) =" & Big_Comb (60, 30)'Image); + Put_Line ("C(900, 674) =" & Big_Comb (900, 674)'Image); +end Combs_Perms; diff --git a/Task/Combinations/EasyLang/combinations.easy b/Task/Combinations/EasyLang/combinations.easy index 17b909ce4a..3ac717f830 100644 --- a/Task/Combinations/EasyLang/combinations.easy +++ b/Task/Combinations/EasyLang/combinations.easy @@ -3,13 +3,13 @@ m = 3 len result[] m # proc combinations pos val . . - if pos <= m - for i = val to n - m - result[pos] = pos + i - combinations pos + 1 i - . - else + if pos > m print result[] + return + . + for i = val to pos + n - m + result[pos] = i + combinations pos + 1 i + 1 . . -combinations 1 0 +combinations 1 1 diff --git a/Task/Combinations/FutureBasic/combinations.basic b/Task/Combinations/FutureBasic/combinations.basic new file mode 100644 index 0000000000..6953e2870c --- /dev/null +++ b/Task/Combinations/FutureBasic/combinations.basic @@ -0,0 +1,16 @@ +void local fn Combinations( currStr as CFStringRef, start as int, stp as int, depth as int ) + int i + + for i = start to stp + if depth = 0 then printf @"%@ %d", currStr, i + fn Combinations( fn StringWithFormat( @"%@ %d", currStr, i ), i+1, stp, depth-1 ) + next +end fn + +int n : n = 3 +int m : m = 5 + +printf @" %d combinations of integers 0 through %d are:", n, m-1 +fn Combinations( @"", 0, m-1, n-1 ) + +HandleEvents diff --git a/Task/Combinations/J/combinations-10.j b/Task/Combinations/J/combinations-10.j new file mode 100644 index 0000000000..13e4c36a64 --- /dev/null +++ b/Task/Combinations/J/combinations-10.j @@ -0,0 +1 @@ +combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) diff --git a/Task/Combinations/J/combinations-6.j b/Task/Combinations/J/combinations-6.j index 980099ca22..73e2b25046 100644 --- a/Task/Combinations/J/combinations-6.j +++ b/Task/Combinations/J/combinations-6.j @@ -1,7 +1 @@ - combr=: dyad define - if.(x=#y) +. x=1 do. - y - else. - (({.y) ,. (x-1) combr (}.y)) , (x combr }.y) - end. -) +combr=: ((0,.$:&.<:),1+($:<:))` ([:i.<:,[) @.(>:+.0=[)M. diff --git a/Task/Combinations/J/combinations-7.j b/Task/Combinations/J/combinations-7.j index 13e4c36a64..399595ae74 100644 --- a/Task/Combinations/J/combinations-7.j +++ b/Task/Combinations/J/combinations-7.j @@ -1 +1,7 @@ -combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) + combr1=: dyad define + if.(x=#y) +. x=1 do. + y + else. + (({.y) ,. (x-1) combr (}.y)) , (x combr }.y) + end. +) diff --git a/Task/Combinations/J/combinations-8.j b/Task/Combinations/J/combinations-8.j new file mode 100644 index 0000000000..ec65fe462f --- /dev/null +++ b/Task/Combinations/J/combinations-8.j @@ -0,0 +1 @@ +combr1=: (({.@],.<:@($:}.)),($:}.))` ] @.((= #)+.1=[) diff --git a/Task/Combinations/J/combinations-9.j b/Task/Combinations/J/combinations-9.j new file mode 100644 index 0000000000..b5d40efaeb --- /dev/null +++ b/Task/Combinations/J/combinations-9.j @@ -0,0 +1 @@ +comb3=: ((= +/"1) |.@:I.@# ]) #:@i.@(2&^) diff --git a/Task/Combinations/Uiua/combinations.uiua b/Task/Combinations/Uiua/combinations.uiua new file mode 100644 index 0000000000..cd3971ba40 --- /dev/null +++ b/Task/Combinations/Uiua/combinations.uiua @@ -0,0 +1,10 @@ +# both from https://github.com/Omnikar/uiua-math/blob/main/lib.ua +PowerSet ← ⍚▽⋯⇡ⁿ:2⧻⟜¤ +Perms ← ☇1⍉∧(≡↻⇡⟜↯+1⟜⊂):¤¤°⊂ + +Permute ← ≡⊏⊙¤⊸(Perms⇡⧻) # Optional helper function. + +# Order is unimportant here. If order is important prepend `☇1≡Permute` to the results. +Choose ← ≡°□▽=⊙(⊸(≡◇⧻)PowerSet) + +⊏⊸⍏Choose 3 ⇡5 # Choose and sort results diff --git a/Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas b/Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas new file mode 100644 index 0000000000..657c2b12b1 --- /dev/null +++ b/Task/Command-line-arguments/PascalABC.NET/command-line-arguments.pas @@ -0,0 +1,4 @@ +begin + for var i:=1 to ParamCount do + Print(ParamStr(i)); +end. diff --git a/Task/Comments/FutureBasic/comments.basic b/Task/Comments/FutureBasic/comments.basic index d05a6c06d6..52cd38da36 100644 --- a/Task/Comments/FutureBasic/comments.basic +++ b/Task/Comments/FutureBasic/comments.basic @@ -1,5 +1,4 @@ // Single line comment -' Single line comment rem Single line comment /* Single line comment */ diff --git a/Task/Comments/PascalABC.NET/comments.pas b/Task/Comments/PascalABC.NET/comments.pas new file mode 100644 index 0000000000..3af3369dfc --- /dev/null +++ b/Task/Comments/PascalABC.NET/comments.pas @@ -0,0 +1,7 @@ +(* This is a + multiline comment *) + +{ This is also a + multiline comment } + +// This is a single line comment diff --git a/Task/Compare-a-list-of-strings/PascalABC.NET/compare-a-list-of-strings.pas b/Task/Compare-a-list-of-strings/PascalABC.NET/compare-a-list-of-strings.pas new file mode 100644 index 0000000000..dd7dd8fda0 --- /dev/null +++ b/Task/Compare-a-list-of-strings/PascalABC.NET/compare-a-list-of-strings.pas @@ -0,0 +1,12 @@ +function IsSorted(lst: sequence of string): boolean + := lst.Order.SequenceEqual(lst); + +function IsStrictAscending(lst: sequence of string): boolean + := lst.Pairwise.All(x -> x[0] < x[1]); + +begin + var strings := |'abc','abc','abc','abc'|; + Print(AllEqual(strings)); + var strings1 := |'abc','abd','ade','aef'|; + Print(IsStrictAscending(strings1)); +end. diff --git a/Task/Compare-length-of-two-strings/Emacs-Lisp/compare-length-of-two-strings.l b/Task/Compare-length-of-two-strings/Emacs-Lisp/compare-length-of-two-strings.l new file mode 100644 index 0000000000..2438b3da54 --- /dev/null +++ b/Task/Compare-length-of-two-strings/Emacs-Lisp/compare-length-of-two-strings.l @@ -0,0 +1,7 @@ +(defun sort-list-by-string-length (list-of-strings) + "Order LIST-OF-STRINGS from longest to shortest." + (sort list-of-strings 'longer-string)) ; sort by "longer-string" function below + +(defun longer-string (string-1 string-2) + "Test if STRING-1 is longer than STRING-2." + (> (length string-1) (length string-2))) ; is STRING-1 longer than STRING-2? diff --git a/Task/Compare-length-of-two-strings/Kotlin/compare-length-of-two-strings.kotlin b/Task/Compare-length-of-two-strings/Kotlin/compare-length-of-two-strings.kotlin new file mode 100644 index 0000000000..4e17dbcda7 --- /dev/null +++ b/Task/Compare-length-of-two-strings/Kotlin/compare-length-of-two-strings.kotlin @@ -0,0 +1,16 @@ +fun main() { + printTwoStrings("a short string", "a fairly long string") + printStringsInDescendingLengthOrder(listOf("abcd", "123456789", "abcdef", "1234567")) +} + +fun printTwoStrings(a: String, b: String) { + val (shorter, longer) = if (a.length < b.length) Pair(a, b) else Pair(b, a) + println("%3d: %s".format(longer.length, longer)) + println("%3d: %s".format(shorter.length, shorter)) +} + +fun printStringsInDescendingLengthOrder(strings: Collection) { + strings.sortedByDescending(String::length).forEach { + println("%3d: %s".format(it.length, it)) + } +} diff --git a/Task/Compare-length-of-two-strings/PascalABC.NET/compare-length-of-two-strings.pas b/Task/Compare-length-of-two-strings/PascalABC.NET/compare-length-of-two-strings.pas new file mode 100644 index 0000000000..db7a579134 --- /dev/null +++ b/Task/Compare-length-of-two-strings/PascalABC.NET/compare-length-of-two-strings.pas @@ -0,0 +1,10 @@ +begin + var (s1,s2) := ('Bye','Hello'); + if s1.Length < s2.Length then + Swap(s1,s2); + Println(s1,s1.Length); + Println(s2,s2.Length); + Println; + var strArr := |'wolf','cat','crocodile','tiger'|; + strArr.OrderByDescending(s -> s.Length).PrintLines(s -> $'{s,9} - {s.Length}'); +end. diff --git a/Task/Compare-length-of-two-strings/R/compare-length-of-two-strings.r b/Task/Compare-length-of-two-strings/R/compare-length-of-two-strings.r new file mode 100644 index 0000000000..8fc11937e0 --- /dev/null +++ b/Task/Compare-length-of-two-strings/R/compare-length-of-two-strings.r @@ -0,0 +1,13 @@ +length_of_strings <- function(list_of_strings){ + string_size = nchar(list_of_strings) + string_order = order(string_size,decreasing = T) + + for (k in string_order){ + cat("\n") + cat(paste0("string : ", list_of_strings[k]," | length : ", string_size[k] , " character(s)")) + } +} + +list_of_strings = c("abcd","123456789","abcdef","1234567") + +length_of_strings(list_of_strings) diff --git a/Task/Compare-length-of-two-strings/Swift/compare-length-of-two-strings.swift b/Task/Compare-length-of-two-strings/Swift/compare-length-of-two-strings.swift new file mode 100644 index 0000000000..7cb09c4575 --- /dev/null +++ b/Task/Compare-length-of-two-strings/Swift/compare-length-of-two-strings.swift @@ -0,0 +1,4 @@ + let list = ["abcd", "abcd🤦‍♂️", "123456789", "abcdef", "1234567"] + list.sorted { $0.count > $1.count }.forEach { string in + print("\(string) has \(string.count) characters") + } diff --git a/Task/Compare-length-of-two-strings/Transd/compare-length-of-two-strings.transd b/Task/Compare-length-of-two-strings/Transd/compare-length-of-two-strings.transd deleted file mode 100644 index ec3fe02caf..0000000000 --- a/Task/Compare-length-of-two-strings/Transd/compare-length-of-two-strings.transd +++ /dev/null @@ -1,11 +0,0 @@ -#lang transd - -MainModule: { - v: ["abcd","123456789","abcdef","1234567"], - - _start: (λ - (for s in (sort v (λ l String() r String() - (ret (< (size r) (size l))))) do - (lout width: 10 s " : " (size s) " code points") ) - ) -} diff --git a/Task/Compiler-AST-interpreter/00-TASK.txt b/Task/Compiler-AST-interpreter/00-TASK.txt index 36979628c5..dfc0b2f7ea 100644 --- a/Task/Compiler-AST-interpreter/00-TASK.txt +++ b/Task/Compiler-AST-interpreter/00-TASK.txt @@ -1,9 +1,9 @@ -AST interpreter +{{task heading|AST interpreter}} An AST interpreter interprets an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)] produced by a [[Compiler/syntax_analyzer|Syntax Analyzer]]. -{{task heading}} +;Task Take the AST output from the Syntax analyzer [[Compiler/syntax_analyzer|task]], and interpret it as appropriate. Refer to the [[Compiler/syntax_analyzer|Syntax analyzer task]] for details of the AST. diff --git a/Task/Compiler-code-generator/00-TASK.txt b/Task/Compiler-code-generator/00-TASK.txt index 2db4f795f3..abd11dcc6f 100644 --- a/Task/Compiler-code-generator/00-TASK.txt +++ b/Task/Compiler-code-generator/00-TASK.txt @@ -1,5 +1,265 @@ -Code Generator +{{task heading|Code Generator}} A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. +;Task + +Take the output of the Syntax analyzer [[Compiler/syntax_analyzer|task]] - which is a [[Flatten_a_list|flattened]] Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the +[[Compiler/virtual_machine_interpreter|Virtual machine interpreter]]. The output is in text format, and represents virtual assembly code. + +The program should read input from a file and/or stdin, and write output to a file and/or +stdout. + +;Example - given the simple program (below), stored in a file called while.t, create the list of tokens, using one of the Lexical analyzer [[Compiler/lexical_analyzer|solutions]] + + lex < while.t > while.lex + +;Run one of the Syntax analyzer [[Compiler/syntax_analyzer|solutions]]: + + parse < while.lex > while.ast + +;while.ast can be input into the code generator. + +;The following table shows the input to lex, lex output, the AST produced by the parser, and the generated virtual assembly code. + + Run as: lex < while.t | parse | gen + +{| class="wikitable" +|- +! Input to lex +! Output from lex, input to parse +! Output from parse +! Output from gen, input to VM +|- +| style="vertical-align:top" | +count = 1; +while (count < 10) { + print("count is: ", count, "\n"); + count = count + 1; +} + +| style="vertical-align:top" | +
+    1      1   Identifier      count
+    1      7   Op_assign
+    1      9   Integer              1
+    1     10   Semicolon
+    2      1   Keyword_while
+    2      7   LeftParen
+    2      8   Identifier      count
+    2     14   Op_less
+    2     16   Integer             10
+    2     18   RightParen
+    2     20   LeftBrace
+    3      5   Keyword_print
+    3     10   LeftParen
+    3     11   String          "count is: "
+    3     23   Comma
+    3     25   Identifier      count
+    3     30   Comma
+    3     32   String          "\n"
+    3     36   RightParen
+    3     37   Semicolon
+    4      5   Identifier      count
+    4     11   Op_assign
+    4     13   Identifier      count
+    4     19   Op_add
+    4     21   Integer              1
+    4     22   Semicolon
+    5      1   RightBrace
+    6      1   End_of_input
+ +| style="vertical-align:top" | +
Sequence
+Sequence
+;
+Assign
+Identifier    count
+Integer       1
+While
+Less
+Identifier    count
+Integer       10
+Sequence
+Sequence
+;
+Sequence
+Sequence
+Sequence
+;
+Prts
+String        "count is: "
+;
+Prti
+Identifier    count
+;
+Prts
+String        "\n"
+;
+Assign
+Identifier    count
+Add
+Identifier    count
+Integer       1
+ +| style="vertical-align:top" | +
Datasize: 1 Strings: 2
+"count is: "
+"\n"
+   0 push  1
+   5 store [0]
+  10 fetch [0]
+  15 push  10
+  20 lt
+  21 jz     (43) 65
+  26 push  0
+  31 prts
+  32 fetch [0]
+  37 prti
+  38 push  1
+  43 prts
+  44 fetch [0]
+  49 push  1
+  54 add
+  55 store [0]
+  60 jmp    (-51) 10
+  65 halt
+|} + +; Input format: + +As shown in the table, above, the output from the [[Compiler/syntax_analyzer|syntax analyzer]] is a flattened AST. + +In the AST, Identifier, Integer, and String, are terminal nodes, e.g, they do not have child nodes. + +Loading this data into an internal parse tree should be as simple as: + + +def load_ast() + line = readline() + # Each line has at least one token + line_list = tokenize the line, respecting double quotes + + text = line_list[0] # first token is always the node type + + if text == ";" + return None + + node_type = text # could convert to internal form if desired + + # A line with two tokens is a leaf node + # Leaf nodes are: Identifier, Integer String + # The 2nd token is the value + if len(line_list) > 1 + return make_leaf(node_type, line_list[1]) + + left = load_ast() + right = load_ast() + return make_node(node_type, left, right) + + +; Output format - refer to the table above + +* The first line is the header: Size of data, and number of constant strings. +** size of data is the number of 32-bit unique variables used. In this example, one variable, '''count''' +** number of constant strings is just that - how many there are +* After that, the constant strings +* Finally, the assembly code + +;Registers: + +* sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer array. + +* pc: the program counter - points to the current instruction to be performed. The code is an array of bytes. + +;Data: + +32-bit integers and strings + +;Instructions: + +Each instruction is one byte. The following instructions also have a 32-bit integer operand: + + fetch [index] + +where index is an index into the data array. + + store [index] + +where index is an index into the data array. + + push n + +where value is a 32-bit integer that will be pushed onto the stack. + + jmp (n) addr + +where (n) is a 32-bit integer specifying the distance between the current location and the +desired location. addr is an unsigned value of the actual code address. + + jz (n) addr + +where (n) is a 32-bit integer specifying the distance between the current location and the +desired location. addr is an unsigned value of the actual code address. + +The following instructions do not have an operand. They perform their operation directly +against the stack: + +For the following instructions, the operation is performed against the top two entries in +the stack: + + add + sub + mul + div + mod + lt + gt + le + ge + eq + ne + and + or + +For the following instructions, the operation is performed against the top entry in the +stack: + + neg + not + + prtc + +Print the word at stack top as a character. + + prti + +Print the word at stack top as an integer. + + prts + +Stack top points to an index into the string pool. Print that entry. + + halt + +Unconditional stop. + +; Additional examples + +Your solution should pass all the test cases above and the additional tests found '''[[Compiler/Sample_programs|Here]]'''. + +{{task heading|Reference}} + +The C and Python versions can be considered reference implementations. + +;Related Tasks + +* [[Compiler/lexical_analyzer|Lexical Analyzer task]] +* [[Compiler/syntax_analyzer|Syntax Analyzer task]] +* [[Compiler/virtual_machine_interpreter|Virtual Machine Interpreter task]] +* [[Compiler/AST_interpreter|AST Interpreter task]] + +
+__TOC__ + diff --git a/Task/Compiler-lexical-analyzer/00-TASK.txt b/Task/Compiler-lexical-analyzer/00-TASK.txt index 400132cd5a..c746bdc789 100644 --- a/Task/Compiler-lexical-analyzer/00-TASK.txt +++ b/Task/Compiler-lexical-analyzer/00-TASK.txt @@ -4,8 +4,6 @@ Definition from [https://en.wikipedia.org/wiki/Lexical_analysis Wikipedia]: : ''Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is also used to refer to the first stage of a lexer).'' -{{task heading}} - Create a lexical analyzer for the simple programming language specified below. The program should read input from a file and/or stdin, and write output to a file and/or stdout. If the language being used has a lexer module/library/class, it would be great diff --git a/Task/Compiler-syntax-analyzer/00-TASK.txt b/Task/Compiler-syntax-analyzer/00-TASK.txt index 543426c5ba..81e1d6fc05 100644 --- a/Task/Compiler-syntax-analyzer/00-TASK.txt +++ b/Task/Compiler-syntax-analyzer/00-TASK.txt @@ -1,10 +1,8 @@ -Syntax Analyzer +{{task heading|Syntax Analyzer}} A Syntax analyzer transforms a token stream (from the [[Compiler/lexical_analyzer|Lexical analyzer]]) into a Syntax tree, based on a grammar. -{{task heading}} - Take the output from the Lexical analyzer [[Compiler/lexical_analyzer|task]], and convert it to an [https://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree (AST)], based on the grammar below. The output should be in a [[Flatten_a_list|flattened format.]] diff --git a/Task/Compiler-virtual-machine-interpreter/00-TASK.txt b/Task/Compiler-virtual-machine-interpreter/00-TASK.txt index 9d3bfd9853..f2c48936bc 100644 --- a/Task/Compiler-virtual-machine-interpreter/00-TASK.txt +++ b/Task/Compiler-virtual-machine-interpreter/00-TASK.txt @@ -1,9 +1,7 @@ -Virtual Machine Interpreter +{{task heading|Virtual Machine Interpreter}} A virtual machine implements a computer in software. -{{task heading}} - Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the [[Compiler/code_generator|task]]. This is a byte-coded, 32-bit word stack based virtual machine. @@ -11,7 +9,7 @@ byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, and write output to a file and/or stdout. -Input format: +{{task heading|Input format}} Given the following program: @@ -67,7 +65,7 @@ Next comes the actual virtual assembly code. The first number is the code addre instruction. After that is the instruction mnemonic, followed by optional operands, depending on the instruction. -Registers: +{{task heading|Registers}} sp: the stack pointer - points to the next top of stack. The stack is a 32-bit integer @@ -81,7 +79,7 @@ Data: data string pool -Instructions: +{{task heading|Instructions}} Each instruction is one byte. The following instructions also have a 32-bit integer operand: diff --git a/Task/Compiler-virtual-machine-interpreter/C++/compiler-virtual-machine-interpreter.cpp b/Task/Compiler-virtual-machine-interpreter/C++/compiler-virtual-machine-interpreter.cpp new file mode 100644 index 0000000000..0d2720106f --- /dev/null +++ b/Task/Compiler-virtual-machine-interpreter/C++/compiler-virtual-machine-interpreter.cpp @@ -0,0 +1,190 @@ +#include +#include +#include +#include +#include +#include +#include + +std::vector split_string(const std::string& text, const char& delimiter) { + std::vector lines; + std::istringstream stream(text); + std::string line; + while ( std::getline(stream, line, delimiter) ) { + if ( ! line.empty() ) { + lines.emplace_back(line); + } + } + return lines; +} + +std::string parseString(const std::string& text) { + std::string result = ""; + uint32_t i = 0; + while ( i < text.length() ) { + if ( text[i] == '\\' && i + 1 < text.length() ) { + if ( text[i + 1] == 'n' ) { + result += "\n"; + i++; + } else if ( text[i + 1] == '\\') { + result += "\\"; + i++; + } + } else { + result += text[i]; + } + i++; + } + + return result; +} + +void add_to_codes(const uint32_t& number, std::vector& codes) { + for ( uint32_t i = 0; i < 32; i += 8 ) { + codes.emplace_back((number >> i) & 0xff); + } +} + +uint32_t operand(const uint32_t& index, const std::vector& codes) { + uint32_t result = 0; + for ( uint32_t i = index + 3; i >= index; --i ) { + result = ( result << 8 ) + codes[i]; + } + + return result; +} + +struct VirtualMachineInfo { + uint32_t data_size; + std::vector vm_strings; + std::vector codes; +}; + +enum class Op_code { + HALT, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE, EQ, NE, AND, OR, NEG, NOT, + PRTC, PRTI, PRTS, FETCH, STORE, PUSH, JMP, JZ +}; + +std::unordered_map string_to_enum = { + { "halt", Op_code::HALT }, { "add", Op_code::ADD }, { "sub", Op_code::SUB }, + { "mul", Op_code::MUL }, { "div", Op_code::DIV }, { "mod", Op_code::MOD }, + { "lt", Op_code::LT }, { "gt", Op_code::GT }, { "le", Op_code::LE }, + { "ge", Op_code::GE }, { "eq", Op_code::EQ }, { "ne", Op_code::NE }, + { "and", Op_code::AND }, { "or", Op_code::OR }, { "neg", Op_code::NEG }, + { "not", Op_code::NOT }, { "prtc", Op_code::PRTC }, { "prti", Op_code::PRTI }, + { "prts", Op_code::PRTS }, { "fetch", Op_code::FETCH }, { "store", Op_code::STORE }, + { "push", Op_code::PUSH }, { "jmp", Op_code::JMP }, { "jz", Op_code::JZ } +}; + +VirtualMachineInfo load_code(const std::string& file_path) { + std::ifstream stream(file_path); + std::vector lines; + std::string line; + + while ( std::getline(stream, line) ) { + lines.emplace_back(line); + } + + line = lines.front(); + if ( line.substr(0, 3) == "lex" ) { + lines.erase(lines.begin()); + line = lines.front(); + } + + std::vector sections = split_string(line, ' '); + const uint32_t data_size = std::stoi(sections[1]); + const uint32_t string_count = std::stoi(sections[3]); + + std::vector vm_strings = { }; + for ( uint32_t i = 1; i <= string_count; ++i ) { + std::string content = lines[i].substr(1, lines[i].length() - 2); + vm_strings.emplace_back(parseString(content)); + } + + uint32_t offset = 0; + std::vector codes = { }; + for ( uint32_t i = string_count + 1; i < lines.size(); ++i ) { + sections = split_string(lines[i], ' '); + offset = std::stoi(sections[0]); + Op_code op_code = string_to_enum[sections[1]]; + codes.emplace_back(static_cast(op_code)); + + switch ( op_code ) { + case Op_code::FETCH : + case Op_code::STORE : + add_to_codes(std::stoi(sections[2] + .substr(1, sections[2].length() - 2)), codes); break; + case Op_code::PUSH : add_to_codes(std::stoi(sections[2]), codes); break; + case Op_code::JMP : + case Op_code::JZ : add_to_codes(std::stoi(sections[3]) - offset - 1, codes); break; + default : break; + } + } + + return VirtualMachineInfo(data_size, vm_strings, codes); +} + +void runVirtualMachine( + const uint32_t& data_size, const std::vector& vm_strings, const std::vector& codes) { + const uint32_t word_size = 4; + std::vector stack(data_size, 0); + uint32_t index = 0; + Op_code op_code; + + while ( op_code != Op_code::HALT ) { + op_code = static_cast(codes[index]); + index++; + + switch ( op_code ) { + case Op_code::HALT : break; + case Op_code::ADD : stack[stack.size() - 2] += stack.back(); stack.pop_back(); break; + case Op_code::SUB : stack[stack.size() - 2] -= stack.back(); stack.pop_back(); break; + case Op_code::MUL : stack[stack.size() - 2] *= stack.back(); stack.pop_back(); break; + case Op_code::DIV : stack[stack.size() - 2] /= stack.back(); stack.pop_back(); break; + case Op_code::MOD : stack[stack.size() - 2] %= stack.back(); stack.pop_back(); break; + case Op_code::LT : { stack[stack.size() - 2] = ( stack[stack.size() - 2] < stack.back() ) ? 1 : 0; + stack.pop_back(); break; + } + case Op_code::GT : { stack[stack.size() - 2] = ( stack[stack.size() - 2] > stack.back() ) ? 1 : 0; + stack.pop_back(); break; + } + case Op_code::LE : { stack[stack.size() - 2] = ( stack[stack.size() - 2] <= stack.back() ) ? 1 : 0; + stack.pop_back(); break; + } + case Op_code::GE : { stack[stack.size() - 2] = ( stack[stack.size() - 2] >= stack.back() ) ? 1 : 0; + stack.pop_back(); break; + } + case Op_code::EQ : { stack[stack.size() - 2] = ( stack[stack.size() - 2] == stack.back() ) ? 1 : 0; + stack.pop_back(); break; + } + case Op_code::NE : { stack[stack.size() - 2] = ( stack[stack.size() - 2] != stack.back() ) ? 1 : 0; + stack.pop_back(); break; + } + case Op_code::AND : { uint32_t value = ( stack[stack.size() - 2] != 0 && stack.back() != 0 ) ? 1 : 0; + stack[stack.size() - 2] = value; stack.pop_back(); break; + } + case Op_code::OR : { uint32_t value = ( stack[stack.size() - 2] != 0 || stack.back() != 0 ) ? 1 : 0; + stack[stack.size() - 2] = value; stack.pop_back(); break; + } + case Op_code::NEG : stack.back() = -stack.back(); break; + case Op_code::NOT : stack.back() = ( stack.back() == 0 ) ? 1 : 0; break; + case Op_code::PRTC : std::cout << static_cast(stack.back()); stack.pop_back(); break; + case Op_code::PRTI : std::cout << stack.back(); stack.pop_back(); break; + case Op_code::PRTS : std::cout << vm_strings[stack.back()]; stack.pop_back(); break; + case Op_code::FETCH : stack.emplace_back(stack[operand(index, codes)]); index += word_size; break; + case Op_code::STORE : { stack[operand(index, codes)] = stack.back(); index += word_size; + stack.pop_back(); break; + } + case Op_code::PUSH : stack.emplace_back(operand(index, codes)); index += word_size; break; + case Op_code::JMP : index += operand(index, codes); break; + case Op_code::JZ : { index += ( stack.back() == 0 ) ? operand(index, codes) : word_size; + stack.pop_back(); break; + } + } + } +} + +int main() { + VirtualMachineInfo info = load_code("Compiler Test Cases/AsciiMandlebrot.txt"); + runVirtualMachine(info.data_size, info.vm_strings, info.codes); +} diff --git a/Task/Compiler-virtual-machine-interpreter/Java/compiler-virtual-machine-interpreter.java b/Task/Compiler-virtual-machine-interpreter/Java/compiler-virtual-machine-interpreter.java new file mode 100644 index 0000000000..25affabb2b --- /dev/null +++ b/Task/Compiler-virtual-machine-interpreter/Java/compiler-virtual-machine-interpreter.java @@ -0,0 +1,173 @@ +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public final class CompilerVirtualMachineInterpreter { + + public static void main(String[] args) throws IOException { + Path filePath = Path.of("Compiler Test Cases/AsciiMandlebrot.txt"); + VirtualMachineInfo info = loadCode(filePath); + runVirtualMachine(info.dataSize, info.vmStrings, info.codes()); + } + + private static void runVirtualMachine(int dataSize, List vmStrings, List codes) { + final int wordSize = 4; + Stack stack = new Stack(); + for ( int i = 0; i < dataSize; i++ ) { + stack.push(0); + } + + int index = 0; + OpCode opCode = null; + + while ( opCode != OpCode.HALT ) { + opCode = OpCode.havingCode(codes.get(index)); + index += 1; + + switch ( opCode ) { + case HALT -> { } + case ADD -> stack.set(stack.size() - 2, stack.get(stack.size() - 2) + stack.pop()); + case SUB -> stack.set(stack.size() - 2, stack.get(stack.size() - 2) - stack.pop()); + case MUL -> stack.set(stack.size() - 2, stack.get(stack.size() - 2) * stack.pop()); + case DIV -> stack.set(stack.size() - 2, stack.get(stack.size() - 2) / stack.pop()); + case MOD -> stack.set(stack.size() - 2, Math.floorMod(stack.get(stack.size() - 2), stack.pop())); + case LT -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) < stack.pop() ) ? 1 : 0); + case GT -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) > stack.pop() ) ? 1 : 0); + case LE -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) <= stack.pop() ) ? 1 : 0); + case GE -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) >= stack.pop() ) ? 1 : 0); + case EQ -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) == stack.pop() ) ? 1 : 0); + case NE -> stack.set(stack.size() - 2, ( stack.get(stack.size() - 2) != stack.pop() ) ? 1 : 0); + case AND -> { final int value = ( stack.get(stack.size() - 2) != 0 && stack.pop() != 0 ) ? 1 : 0; + stack.set(stack.size() - 1, value); + } + case OR -> { final int value = ( stack.get(stack.size() - 2) != 0 || stack.pop() != 0 ) ? 1 : 0; + stack.set(stack.size() - 1, value); + } + case NEG -> stack.set(stack.size() - 1, -stack.peek()); + case NOT -> stack.set(stack.size() - 1, ( stack.peek() == 0 ) ? 1 : 0); + case PRTC -> System.out.print((char) stack.pop().intValue()); + case PRTI -> System.out.print(stack.pop()); + case PRTS -> System.out.print(vmStrings.get(stack.pop())); + case FETCH -> { stack.push(stack.get(operand(index, codes))); index += wordSize; } + case STORE -> { stack.set(operand(index, codes), stack.pop()); index += wordSize; } + case PUSH -> { stack.push(operand(index, codes)); index += wordSize; } + case JMP -> index += operand(index, codes); + case JZ -> index += ( stack.pop() == 0 ) ? operand(index, codes) : wordSize; + } + } + } + + private static VirtualMachineInfo loadCode(Path filePath) throws IOException { + List lines = Files.readAllLines(filePath, StandardCharsets.UTF_8); + + String line = lines.getFirst(); + if ( line.startsWith("lex") ) { + lines.removeFirst(); + line = lines.getFirst(); + } + + String[] sections = line.trim().split(" "); + final int dataSize = Integer.parseInt(sections[1]); + final int stringCount = Integer.parseInt(sections[3]); + + List VMstrings = new ArrayList(); + for ( int i = 1; i <= stringCount; i++ ) { + String content = lines.get(i).substring(1, lines.get(i).length() - 1); + VMstrings.addLast(parseString(content)); + } + + int offset = 0; + List codes = new ArrayList(); + for ( int i = stringCount + 1; i < lines.size(); i++ ) { + sections = lines.get(i).trim().split("\\s+"); + offset = Integer.parseInt(sections[0]); + OpCode opCode = OpCode.valueOf(sections[1].toUpperCase()); + codes.addLast(opCode.byteCode()); + + switch ( opCode ) { + case FETCH, STORE -> addToCodes(Integer.parseInt(sections[2] + .substring(1, sections[2].length() - 1)), codes); + case PUSH -> addToCodes(Integer.parseInt(sections[2]), codes); + case JMP, JZ -> addToCodes(Integer.parseInt(sections[3]) - offset - 1, codes); + default -> { } + } + } + + return new VirtualMachineInfo(dataSize, VMstrings, codes); + } + + private static int operand(int index, List codes) { + byteBuffer.clear(); + for ( int i = index; i < index + 4; i++ ) { + byteBuffer.put(codes.get(i)); + } + byteBuffer.flip(); + + return byteBuffer.getInt(); + } + + private static void addToCodes(int number, List codes) { + byteBuffer.clear(); + byteBuffer.putInt(number); + byteBuffer.flip(); + for ( byte bb : byteBuffer.array() ) { + codes.addLast(bb); + } + } + + private static String parseString(String text) { + StringBuilder result = new StringBuilder(); + int i = 0; + while ( i < text.length() ) { + if ( text.charAt(i) == '\\' && i + 1 < text.length() ) { + if ( text.charAt(i + 1) == 'n' ) { + result.append("\n"); + i += 1; + } else if ( text.charAt(i + 1) == '\\') { + result.append("\\"); + i += 1; + } + } else { + result.append(text.charAt(i)); + } + i += 1; + } + + return result.toString(); + } + + private static ByteBuffer byteBuffer = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN); + + private static enum OpCode { + + HALT(0), ADD(1), SUB(2), MUL(3), DIV(4), MOD(5), LT(6), GT(7), LE(8), GE(9), EQ(10), NE(11), + AND(12), OR(13), NEG(14), NOT(15), + PRTC(16), PRTI(17), PRTS(18), FETCH(19), STORE(20), PUSH(21), JMP(22), JZ(23); + + public byte byteCode() { + return (byte) byteCode; + } + + public static OpCode havingCode(Byte byteCode) { + return op_codes[(int) byteCode]; + } + + private OpCode(int aByteCode) { + byteCode = aByteCode; + } + + private int byteCode; + + private static OpCode[] op_codes = values(); + + } + + private static record VirtualMachineInfo(int dataSize, List vmStrings, List codes) {} + +} diff --git a/Task/Compound-data-type/PascalABC.NET/compound-data-type.pas b/Task/Compound-data-type/PascalABC.NET/compound-data-type.pas new file mode 100644 index 0000000000..b6b8293f37 --- /dev/null +++ b/Task/Compound-data-type/PascalABC.NET/compound-data-type.pas @@ -0,0 +1,16 @@ +type + Point = class + x,y: integer; + constructor(x,y: integer) := (Self.x,Self.y) := (x,y); + end; + PointRec = record + x,y: integer; + constructor(x,y: integer) := (Self.x,Self.y) := (x,y); + end; + +begin + var p := new Point(2,3); + Println(p.x,p.y); + var pr := new PointRec(4,5); + Println(pr.x,pr.y); +end. diff --git a/Task/Concurrent-computing/PascalABC.NET/concurrent-computing.pas b/Task/Concurrent-computing/PascalABC.NET/concurrent-computing.pas new file mode 100644 index 0000000000..4f5e24c6c3 --- /dev/null +++ b/Task/Concurrent-computing/PascalABC.NET/concurrent-computing.pas @@ -0,0 +1,8 @@ +uses System.Threading.Tasks; + +begin + Task.Run(() -> Print('Enjoy')); + Task.Run(() -> Print('Rosetta')); + Task.Run(() -> Print('Code')); + Sleep(100); +end. diff --git a/Task/Conditional-structures/Langur/conditional-structures-1.langur b/Task/Conditional-structures/Langur/conditional-structures-1.langur index f0a3414467..b8bceebc82 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-1.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-1.langur @@ -1,9 +1,9 @@ -if .x == 0 { +if x == 0 { ... -} else if .x > 0 { - val .y = 100 +} else if x > 0 { + val y = 100 ... } else { - val .y = 70 + val y = 70 ... } diff --git a/Task/Conditional-structures/Langur/conditional-structures-2.langur b/Task/Conditional-structures/Langur/conditional-structures-2.langur index d6d6ef7252..99b9dcafd7 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-2.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-2.langur @@ -1 +1 @@ -if(.x > .y: ...; .x < .y: ...; /* else */ ...) +if(x > y: ...; x < y: ...; /* else */ ...) diff --git a/Task/Conditional-structures/Langur/conditional-structures-3.langur b/Task/Conditional-structures/Langur/conditional-structures-3.langur index 6c6913c8fb..93a2b6daad 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-3.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-3.langur @@ -1 +1 @@ -if .x > .y: break +if x > y: break diff --git a/Task/Conditional-structures/Langur/conditional-structures-4.langur b/Task/Conditional-structures/Langur/conditional-structures-4.langur index 8be040d87e..940aec9a71 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-4.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-4.langur @@ -1,25 +1,25 @@ -switch .x, .y, .z { +switch x, y, z { case true: ... # any are true case false, _: ... - # .x == false + # x == false case _, null, true: ... - # .y == null or .z == true + # y == null or z == true case xor _, true, true: ... - # .y == true xor .z == true + # y == true xor z == true } switch 0 { - case .x, .y: ... - # .x or .y equals 0 + case x, y: ... + # x or y equals 0 ... } -switch[and] .x, .y, .z { +switch[and] x, y, z { case true: ... # all are true case false, _: ... - # .x == false + # x == false case _, null, true: ... - # .y == null and .z == true + # y == null and z == true } diff --git a/Task/Conditional-structures/Langur/conditional-structures-5.langur b/Task/Conditional-structures/Langur/conditional-structures-5.langur index 8ee9423979..a0c932ff9e 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-5.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-5.langur @@ -1,4 +1,4 @@ -switch .x { +switch x { case true: # implicit fallthrough case null: 0 diff --git a/Task/Conditional-structures/Langur/conditional-structures-6.langur b/Task/Conditional-structures/Langur/conditional-structures-6.langur index 90ba731409..bc35af9767 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-6.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-6.langur @@ -1,6 +1,6 @@ -switch .x { +switch x { case true: - if .y > 100 { + if y > 100 { fallthrough } else { 120 diff --git a/Task/Conditional-structures/Langur/conditional-structures-7.langur b/Task/Conditional-structures/Langur/conditional-structures-7.langur index 7a0f665429..27300db645 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-7.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-7.langur @@ -1,4 +1,4 @@ -switch(.x, .y, .z; +switch(x, y, z; true: ... ; # any are equal to true - _, >= .z: ...; # .y >= .z + _, >= z: ...; # y >= z ... ) # default diff --git a/Task/Conditional-structures/PascalABC.NET/conditional-structures.pas b/Task/Conditional-structures/PascalABC.NET/conditional-structures.pas new file mode 100644 index 0000000000..3b34271cf4 --- /dev/null +++ b/Task/Conditional-structures/PascalABC.NET/conditional-structures.pas @@ -0,0 +1,28 @@ +// if statement +if condition then + operator; + +if condition then + operator +else operator; + +if condition then + operator +else if condition then + operator +else operator; + +// case statement +case Month of + 3..5: Print('Spring'); + 6..8: Print('Summer'); + 9..11: Print('Autumn'); + 12,1,2: Print('Winter'); + else throw ArgumentException('Bad Month') +end; + +// ternary operator +var min := if a < b then a else b; + +// ternary operator in C style +var min := a < b ? a : b; diff --git a/Task/Conjugate-transpose/R/conjugate-transpose.r b/Task/Conjugate-transpose/R/conjugate-transpose.r new file mode 100644 index 0000000000..543b6a5d72 --- /dev/null +++ b/Task/Conjugate-transpose/R/conjugate-transpose.r @@ -0,0 +1,69 @@ +conjugate_transpose<- function(M){ + t(Conj(M))} + +is_hermitian <- function(M,eps=10**-10){ + all(abs(M-conjugate_transpose(M)) 0 Then + Stuff = fb.Item(fb.max) + fb.max -= 1 + End If +End Sub + +Type Gourmand + WeightGain As physical + SleepTime As physical +End Type + +Sub eats(Byref g As Gourmand, Byref stuff As ActualFood) + g.WeightGain += stuff.size * stuff.quantity * 0.75 + stuff.size = 0 + stuff.quantity = 0 +End Sub + +' Test +Dim As foodbox Hamper +Dim As Gourmand MrG +Dim As ActualFood Course + +put_(Hamper, food.pudding, 3, 7) +put_(Hamper, food.pie, 7, 3) +GetNext(Hamper, Course) +eats(MrG, Course) + +Print MrG.WeightGain ' result 15.75 + +Sleep diff --git a/Task/Constrained-genericity/PascalABC.NET/constrained-genericity.pas b/Task/Constrained-genericity/PascalABC.NET/constrained-genericity.pas new file mode 100644 index 0000000000..c7488df595 --- /dev/null +++ b/Task/Constrained-genericity/PascalABC.NET/constrained-genericity.pas @@ -0,0 +1,23 @@ +function Min(a: array of T): T; where T: IComparable; +begin + Result := a[0]; + for var i:=1 to a.Length - 1 do + if a[i].CompareTo(Result) < 0 then + Result := a[i]; +end; + +type Point = record(IComparable) + x,y: integer; + constructor (xx,yy: integer) := (x,y) := (xx,yy); + function CompareTo(p: Point): integer; + begin + Result := x.CompareTo(p.x); + if Result = 0 then + Result := y.CompareTo(p.y); + end; +end; + +begin + var a := Arr(new Point(2,3),new Point(1,4), new Point(3,1)); + Print(Min(a)); +end. diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Jq/continued-fraction-arithmetic-construct-from-rational-number.jq b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Jq/continued-fraction-arithmetic-construct-from-rational-number.jq new file mode 100644 index 0000000000..2b9225ddfc --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Jq/continued-fraction-arithmetic-construct-from-rational-number.jq @@ -0,0 +1,57 @@ +### Generic utilities + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; +def rpad($len): tostring | ($len - length) as $l | . + (" " * $l); + +# If $j is 0, then an error condition is raised; +# otherwise, assuming infinite-precision integer arithmetic, +# if the input and $j are integers, then the result will be a pair of integers. +def divmod($i; $j): + ($i % $j) as $mod + | [($i - $mod) / $j, $mod] ; + +def whilst(cond; update): + def _whilst: + if cond then update | (., _whilst) else empty end; + _whilst; + + +### Continued fractions + +# $a/$b +def toContFrac($a; $b): + {$a,$b} + | whilst( .b != 0; + divmod(.a; .b) as [$d, $r] + | .a = .b + | .b = $r + | .d = $d + | if .a == 1 then .b = 0 end) + | .d ; + +def examples: [ + {heading: "Examples ->", + group: [ [1, 2], [3, 1], [23, 8], [13, 11], [22, 7], [-151, 77] ], + lengths: [4,2] }, + + {heading: "Sqrt(2) ->", + group: [ [14142, 10000], [141421, 100000], [1414214, 1000000], [14142136, 10000000] ], + lengths: [8,8]}, + + {heading: "Pi ->", + group: [ [31, 10], [314, 100], [3142, 1000], [31428, 10000], [314285, 100000], [3142857, 1000000], + [31428571, 10000000], [314285714,100000000]], + lengths: [9, 9] } +]; + +def task: + examples[] + | .lengths as $lengths + | .heading, + (foreach .group[] as [$a, $b] (.; + .emit = "\($a|lpad($lengths[0])) / \($b|rpad($lengths[1]))" + | .emit += " = " + ([toContFrac($a;$b)] | join(" ")) ) + | .emit ), + ""; + +task diff --git a/Task/Convert-decimal-number-to-rational/11l/convert-decimal-number-to-rational.11l b/Task/Convert-decimal-number-to-rational/11l/convert-decimal-number-to-rational.11l index c0c5e0a9b5..dbb3d0b787 100644 --- a/Task/Convert-decimal-number-to-rational/11l/convert-decimal-number-to-rational.11l +++ b/Task/Convert-decimal-number-to-rational/11l/convert-decimal-number-to-rational.11l @@ -1,11 +1,4 @@ -T Rational - Int numerator - Int denominator - - F (numerator, denominator) - .numerator = numerator - .denominator = denominator - +T Rational((Int numerator, Int denominator)) F String() I .denominator == 1 R String(.numerator) diff --git a/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur b/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur index e635d318a0..baca41f3e5 100644 --- a/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur +++ b/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur @@ -1,17 +1,17 @@ -val .duration = fn(var .sec) { +val d = fn(var sec) { [ fw/wk d hr min sec/, - for[=[]] .dm in [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60] { - _for ~= [.sec \ .dm] - .sec rem= .dm - } ~ [.sec], + for[=[]] dm in [7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60] { + _for ~= [sec \ dm] + sec rem= dm + } ~ [sec], ] } -for .seconds in [7259, 86400, 6000000] { - val .dur = .duration(.seconds) - write $"\.seconds:7; sec = " - writeln join ", ", for[=[]] .k of .dur[1] { - if .dur[2][.k] != 0: _for ~= [$"\.dur[2][.k]; \.dur[1][.k];"] - } +for seconds in [7259, 86400, 6000000] { + val dur = d(seconds) + write "{{seconds:7}} sec = " + writeln join(", ", for[=[]] k of dur[1] { + if dur[2][k] != 0: _for ~= ["{{dur[2][k]}} {{dur[1][k]}}"] + }) } diff --git a/Task/Convert-seconds-to-compound-duration/Uiua/convert-seconds-to-compound-duration.uiua b/Task/Convert-seconds-to-compound-duration/Uiua/convert-seconds-to-compound-duration.uiua new file mode 100644 index 0000000000..6383b22a67 --- /dev/null +++ b/Task/Convert-seconds-to-compound-duration/Uiua/convert-seconds-to-compound-duration.uiua @@ -0,0 +1,9 @@ +# Builds a string representation of a time period + +Units ← {"second" "minute" "hour" "day" "week"} +Durations ← [60 60 24 7 9999] + +Parts ← ⇌◌∧(⊙⊂⊃(⌊÷|◿))Durations⊙[] # seconds -> [S M H D W] +Sunit ← /⍚$"_ _"⍥⍜(⊡1|⍚⊂⊙@s)≠□"1"⊢. # Stringify a unit +String ← /◇$"_, _"⇌≡Sunit▽⊃(±|⍉⇌⊟Units°⋕) Parts +≡(&p$"_s \t= _"⟜(□String))[7259 86400 6000000 14000000 31449599 31449601] diff --git a/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel b/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel index 2a26b5bc69..f62d37fe29 100644 --- a/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel +++ b/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel @@ -1,66 +1,90 @@ -config const gridHeight: int = 3; -config const gridWidth: int = 3; +config const gridHeight : int = 3; +config const gridWidth : int = 3; -enum State { dead = 0, alive = 1 }; +enum state { dead = 0, alive = 1 }; -class ConwaysGameofLife { +class ConwaysGameofLife +{ + var gridDomain : domain(2, int); + var computeDomain : subdomain(gridDomain); + var grid : [gridDomain] state; - var gridDomain: domain(2); - var computeDomain: subdomain( gridDomain ); - var grid: [gridDomain] int; + proc init(height : int, width : int) + { + this.gridDomain = {0..#height+2, 0..#width+2}; + this.computeDomain = this.gridDomain.expand(-1); + } - proc ConwaysGameofLife( height: int, width: int ) { - this.gridDomain = {0..#height+2, 0..#width+2}; - this.computeDomain = this.gridDomain.expand( -1 ); - } - proc step(){ + proc step() : void + { + var tempGrid: [this.computeDomain] state; - var tempGrid: [this.computeDomain] State; - forall (i,j) in this.computeDomain { - var isAlive = this.grid[i,j] == State.alive; - var numAlive = (+ reduce this.grid[ i-1..i+1, j-1..j+1 ]) - if isAlive then 1 else 0; - tempGrid[i,j] = if ( (2 == numAlive && isAlive) || numAlive == 3 ) then State.alive else State.dead ; - } + forall (i,j) in this.computeDomain + { + var isAlive = this.grid[i,j] == state.alive; + var numAlive = (+ reduce this.grid[i-1..i+1, j-1..j+1]:int) - if isAlive then 1 else 0; + tempGrid[i,j] = if ( (2 == numAlive && isAlive) || numAlive == 3 ) then state.alive else state.dead ; + } - this.grid[this.computeDomain] = tempGrid; + this.grid[this.computeDomain] = tempGrid; + } - } + + proc this(i : int, j : int) ref : state + { + return this.grid[i,j]; + } - proc this( i: int, j: int ) ref : State { - return this.grid[i,j]; - } - proc prettyPrint(): string { - var str: string; - for i in this.gridDomain.dim(1) { - if i == 0 || i == gridDomain.dim(1).last { - for j in this.gridDomain.dim(2) { - str += "-"; - } - } else { - for j in this.gridDomain.dim(2) { - if j == 0 || j == this.gridDomain.dim(2).last { - str += "|"; - } else { - str += if this.grid[i,j] == State.alive then "#" else " "; - } - } - } - str += "\n"; - } - return str; - } + proc prettyPrint() : string + { + var str : string; + for i in this.gridDomain.dim(0) + { + if i == 0 || i == gridDomain.dim(0).last + { + for j in this.gridDomain.dim(1) + { + str += "-"; + } + } + else + { + for j in this.gridDomain.dim(1) + { + if j == 0 || j == this.gridDomain.dim(1).last + { + str += "|"; + } + else + { + str += if this.grid[i,j] == state.alive then "#" else " "; + } + } + } + + str += "\n"; + } + + return str; + } + } -proc main{ - var game = new ConwaysGameofLife( gridHeight, gridWidth ); - game[gridHeight/2 + 1, gridWidth/2 ] = State.alive; - game[gridHeight/2 + 1, gridWidth/2 + 1 ] = State.alive; - game[gridHeight/2 + 1, gridWidth/2 + 2 ] = State.alive; - for i in 1..3 { - writeln( game.prettyPrint() ); - game.step(); - } + +proc main() +{ + var game = new ConwaysGameofLife(gridHeight, gridWidth); + + game[gridHeight/2 + 1, gridWidth/2 ] = state.alive; + game[gridHeight/2 + 1, gridWidth/2 + 1 ] = state.alive; + game[gridHeight/2 + 1, gridWidth/2 + 2 ] = state.alive; + + for i in 1..3 + { + writeln(game.prettyPrint()); + game.step(); + } } diff --git a/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua b/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua new file mode 100644 index 0000000000..c2e9680614 --- /dev/null +++ b/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua @@ -0,0 +1,4 @@ +Life ← ↥⊙↧∩=3,2-,/+≡↻☇1-1⇡3_3¤. +⁅×0.6 ∵⋅⚂ ↯⟜⊚ 50 # Init +⇌◌⍥(⟜⊂Life)300⟜¤ # Run +≡(▽⟜≡▽4) # Upscale diff --git a/Task/Copy-a-string/PascalABC.NET/copy-a-string.pas b/Task/Copy-a-string/PascalABC.NET/copy-a-string.pas new file mode 100644 index 0000000000..92afc0925c --- /dev/null +++ b/Task/Copy-a-string/PascalABC.NET/copy-a-string.pas @@ -0,0 +1,4 @@ +begin + var s: string := 'Hello'; + var s1 := s; +end. diff --git a/Task/Copy-a-string/S-BASIC/copy-a-string.basic b/Task/Copy-a-string/S-BASIC/copy-a-string.basic new file mode 100644 index 0000000000..81d04da265 --- /dev/null +++ b/Task/Copy-a-string/S-BASIC/copy-a-string.basic @@ -0,0 +1,23 @@ +var original, copy = string +based referenced = string +var strloc = integer + +rem - position referenced string on top of original string +location var strloc = original +base referenced at strloc + +original = "Hello, World" +copy = original + +print "Original : ", original +print "Copy : ", copy +print "Referenced: ", referenced +print + +original = "Goodbye, World" + +print "Original : ", original rem - changed +print "Copy : ", copy rem - unchanged +print "Referenced: ", referenced rem - changed + +end diff --git a/Task/Copy-stdin-to-stdout/C/copy-stdin-to-stdout.c b/Task/Copy-stdin-to-stdout/C/copy-stdin-to-stdout.c index fc9c56899d..6d839bdaa4 100644 --- a/Task/Copy-stdin-to-stdout/C/copy-stdin-to-stdout.c +++ b/Task/Copy-stdin-to-stdout/C/copy-stdin-to-stdout.c @@ -1,8 +1,8 @@ #include -int main(){ - char c; - while ( (c=getchar()) != EOF ){ +int main() { + int c; + while ((c = getchar()) != EOF) { putchar(c); } return 0; diff --git a/Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic b/Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic new file mode 100644 index 0000000000..277e5331b6 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/FutureBasic/copy-stdin-to-stdout.basic @@ -0,0 +1,13 @@ +// Create file handles for standard input and output +FileHandleRef stdIn = fn FileHandleWithStandardInput +FileHandleRef stdOut = fn FileHandleWithStandardOutput + +// Continuously read from standard input… +while (YES) + CFDataRef availableData = fn FileHandleAvailableData( stdIn ) + if ( fn DataLength( availableData ) == 0 ) + break // End of input + end if + // … and write to standard output + fn FileHandleWriteData( stdOut, availableData, NULL ) +wend diff --git a/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout.java b/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-1.java similarity index 100% rename from Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout.java rename to Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-1.java diff --git a/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java b/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java new file mode 100644 index 0000000000..df4b2adbe3 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Java/copy-stdin-to-stdout-2.java @@ -0,0 +1,5 @@ +public class CopyStdinToStdout { + public static void main(String[] args) throws java.io.IOException { + System.in.transferTo(System.out); + } +} diff --git a/Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas b/Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas new file mode 100644 index 0000000000..1b297471d0 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/PascalABC.NET/copy-stdin-to-stdout.pas @@ -0,0 +1,2 @@ +## +Console.OpenStandardInput().CopyTo(Console.OpenStandardOutput()); diff --git a/Task/Copy-stdin-to-stdout/Refal/copy-stdin-to-stdout.refal b/Task/Copy-stdin-to-stdout/Refal/copy-stdin-to-stdout.refal new file mode 100644 index 0000000000..51e03c086c --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Refal/copy-stdin-to-stdout.refal @@ -0,0 +1,6 @@ +$ENTRY Go { + , : { + 0 = ; + e.Line = >; + }; +}; diff --git a/Task/Count-in-factors/PascalABC.NET/count-in-factors.pas b/Task/Count-in-factors/PascalABC.NET/count-in-factors.pas new file mode 100644 index 0000000000..13d05e3e0a --- /dev/null +++ b/Task/Count-in-factors/PascalABC.NET/count-in-factors.pas @@ -0,0 +1,25 @@ +// https://rosettacode.org/wiki/Count_in_factors#PascalABC.NET + +function Factorize(x: integer): List; +begin + Result := new List; + if x = 1 then + begin + Result.Add(1); + exit + end; + var i := 2; + repeat + if x.Divs(i) then + begin + Result.Add(i); + x := x div i; + end + else i += 1; + until x = 1; +end; + +begin + var n := 22; + (1..n).PrintLines(x -> $'{x,3}: {Factorize(x).JoinToString('' * '')}') +end. diff --git a/Task/Count-in-octal/Langur/count-in-octal.langur b/Task/Count-in-octal/Langur/count-in-octal.langur index 75aba01e45..b8c0281275 100644 --- a/Task/Count-in-octal/Langur/count-in-octal.langur +++ b/Task/Count-in-octal/Langur/count-in-octal.langur @@ -1,5 +1,5 @@ -val .limit = 70000 +val limit = 70 -for .i of .limit { - writeln $"10x\.i; == 8x\.i:8x;" +for i of limit { + writeln "10x{{i}} == 8x{{i:8x}}" } diff --git a/Task/Count-in-octal/PascalABC.NET/count-in-octal.pas b/Task/Count-in-octal/PascalABC.NET/count-in-octal.pas new file mode 100644 index 0000000000..8c972a5d55 --- /dev/null +++ b/Task/Count-in-octal/PascalABC.NET/count-in-octal.pas @@ -0,0 +1,3 @@ +## +for var i:=0 to 20 do + Println(Convert.ToString(i,8)); diff --git a/Task/Count-occurrences-of-a-substring/ALGOL-68/count-occurrences-of-a-substring.alg b/Task/Count-occurrences-of-a-substring/ALGOL-68/count-occurrences-of-a-substring.alg index b78cae0a28..cb0dc4354e 100644 --- a/Task/Count-occurrences-of-a-substring/ALGOL-68/count-occurrences-of-a-substring.alg +++ b/Task/Count-occurrences-of-a-substring/ALGOL-68/count-occurrences-of-a-substring.alg @@ -1,5 +1,3 @@ -#!/usr/local/bin/a68g --script # - PROC count string in string = (STRING needle, haystack)INT: ( INT start:=LWB haystack, next, out:=0; FOR count WHILE string in string(needle, next, haystack[start:]) DO @@ -9,9 +7,8 @@ PROC count string in string = (STRING needle, haystack)INT: ( out ); -printf(($d" "$, - count string in string("th", "the three truths"), # expect 3 # - count string in string("abab", "ababababab"), # expect 2 # - count string in string("a*b", "abaabba*bbaba*bbab"), # expect 2 # - $l$ +print(( + whole( count string in string("th", "the three truths"), 0 ) # expect 3 #, " ", + whole( count string in string("abab", "ababababab"), 0 ) # expect 2 #, " ", + whole( count string in string("a*b", "abaabba*bbaba*bbab"), 0 ) # expect 2 #, newline )) diff --git a/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.l b/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.l index e5b07110f7..0789fc7e91 100644 --- a/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.l +++ b/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.l @@ -1,5 +1,20 @@ +;; version 1, which takes advantage of the how-many function, +;; which runs only in a buffer + (defun count-substrings (text substring) - (with-temp-buffer - (insert text) - (goto-char (point-min)) - (how-many substring))) + "Count non-overlapping occurrences of SUBSTRING in TEXT." + (with-temp-buffer ; create a temporary buffer, which will be deleted when function finishes + (insert text) ; insert TEXT into the empty buffer + (goto-char (point-min)) ; go to the beginning of the buffer + (how-many substring))) ; count how many occurrences of SUBSTRING + + +;; version 2, which operates on a string + +(defun count-substrings (text substring) + "Count non-overlapping occurences of SUBSTRING in TEXT." + (let ((substrings)) ; empty list to add occurrences of SUBSTRING as we find them + (while (string-match substring text) ; as long as we can find SUBSTRING in TEXT + (push (match-string 0 text) substrings) ; add the SUBSTRING we found to the list of substrings + (setq text (replace-match "" nil nil text))) ; remove SUBSTRING from text, and repeat while loop + (length substrings))) ; count number of items in substrings list diff --git a/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur b/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur index 2af267a23c..868b9d305f 100644 --- a/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur +++ b/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur @@ -1,2 +1,2 @@ -writeln len indices "th", "the three truths" -writeln len indices "abab", "ababababab" +writeln len(indices("th", "the three truths")) +writeln len(indices("abab", "ababababab")) diff --git a/Task/Count-occurrences-of-a-substring/PascalABC.NET/count-occurrences-of-a-substring.pas b/Task/Count-occurrences-of-a-substring/PascalABC.NET/count-occurrences-of-a-substring.pas new file mode 100644 index 0000000000..865822f8f1 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/PascalABC.NET/count-occurrences-of-a-substring.pas @@ -0,0 +1,6 @@ +function CountSubstrings(s,subs: string): integer := s.IndicesOf(subs).Count; + +begin + Print(CountSubstrings('the three truths','th')); + Print(CountSubstrings('ababababab','abab')); +end. diff --git a/Task/Count-the-coins/Ada/count-the-coins.ada b/Task/Count-the-coins/Ada/count-the-coins-1.ada similarity index 100% rename from Task/Count-the-coins/Ada/count-the-coins.ada rename to Task/Count-the-coins/Ada/count-the-coins-1.ada diff --git a/Task/Count-the-coins/Ada/count-the-coins-2.ada b/Task/Count-the-coins/Ada/count-the-coins-2.ada new file mode 100644 index 0000000000..41b7305e62 --- /dev/null +++ b/Task/Count-the-coins/Ada/count-the-coins-2.ada @@ -0,0 +1,26 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Main is + count: Integer; +begin + count := 0; + for penny in 0 .. 100 loop + for nickel in 0 .. 20 loop + for dime in 0 .. 10 loop + for quarter in 0 .. 4 loop + if (penny + 5 * nickel + 10 * dime + 25 * quarter = 100) + then + Put_Line(Integer'Image(count+1) & ": " & + Integer'Image(penny) & " pennies, " & + Integer'Image(nickel) & " nickels, " & + Integer'Image(dime) & " dimes, " & + Integer'Image(quarter) & " quarters"); + count := count + 1; + end if; + end loop; + end loop; + end loop; + end loop; + + Put_Line("The number of ways to make change for a dollar is: " & Integer'Image(count)); +end Main; diff --git a/Task/Count-the-coins/Pascal/count-the-coins.pas b/Task/Count-the-coins/Pascal/count-the-coins.pas new file mode 100644 index 0000000000..2aa438bdf5 --- /dev/null +++ b/Task/Count-the-coins/Pascal/count-the-coins.pas @@ -0,0 +1,24 @@ +program countTheCoins; + +{$mode objfpc}{$H+} + +var + count, quarter, dime, nickel, penny: integer; + +begin + count := 0; + + for penny := 0 to 100 do + for nickel := 0 to 20 do + for dime := 0 to 10 do + for quarter := 0 to 4 do + if (penny + 5 * nickel + 10 * dime + 25 * quarter = 100) then + begin + writeln(penny, ' pennies ', nickel, ' nickels ', dime, ' dimes ', quarter, ' quarters'); + count := count + 1; + end; + + + writeln('The number of ways to make change for a dollar is: ', count); // 242 ways to make change for a dollar + +end. diff --git a/Task/Create-a-file/Seed7/create-a-file.seed7 b/Task/Create-a-file/Seed7/create-a-file.seed7 index 755a9fcf51..e2f09790eb 100644 --- a/Task/Create-a-file/Seed7/create-a-file.seed7 +++ b/Task/Create-a-file/Seed7/create-a-file.seed7 @@ -7,8 +7,8 @@ const proc: main is func begin aFile := open("output.txt", "w"); close(aFile); - mkdir("docs"); + makeDir("docs"); aFile := open("/output.txt", "w"); close(aFile); - mkdir("/docs"); + makeDir("/docs"); end func; diff --git a/Task/Create-a-two-dimensional-array-at-runtime/PascalABC.NET/create-a-two-dimensional-array-at-runtime.pas b/Task/Create-a-two-dimensional-array-at-runtime/PascalABC.NET/create-a-two-dimensional-array-at-runtime.pas new file mode 100644 index 0000000000..1efbedf6b8 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/PascalABC.NET/create-a-two-dimensional-array-at-runtime.pas @@ -0,0 +1,8 @@ +begin + var (m,n) := ReadInteger2; + var a: array[,] of integer := new integer[m,n]; + a[0,0] := 1; a[m-1,n-1] := 55; + a.Println; + var a1 := MatrRandomInteger(m,n); + a1.Println; +end. diff --git a/Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas b/Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas new file mode 100644 index 0000000000..1feef12947 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/PascalABC.NET/create-an-object-at-a-given-address.pas @@ -0,0 +1,12 @@ +begin + var pi: ^integer; + New(pi); + pi^ := 3; + Writeln(pi,' ',pi^); + pi^ := 5; + Writeln(pi,' ',pi^); + var pi1: ^integer := pi; + pi1^ := 666; + Writeln(pi1,' ',pi1^); + Writeln(pi,' ',pi^); +end. diff --git a/Task/Cyclops-numbers/C-sharp/cyclops-numbers.cs b/Task/Cyclops-numbers/C-sharp/cyclops-numbers.cs new file mode 100644 index 0000000000..272a948842 --- /dev/null +++ b/Task/Cyclops-numbers/C-sharp/cyclops-numbers.cs @@ -0,0 +1,191 @@ +internal class Program +{ + private static void Main(string[] args) + { + long number = 1; + int displayMax = 50; + long highBar = 10_000_000; + + List cyclops = []; + int cyclopsCount = 0; + long firstCyclopsOverHighBar = 0; + int firstCyclopsOverHighBarIndex = 0; + List primeCyclops = []; + int primeCyclopsCount = 0; + long firstPrimeCyclopsOverHighBar = 0; + int firstPrimeCyclopsOverHighBarIndex = 0; + List primeBlindCyclops = []; + int primeBlindCyclopsCount = 0; + long firstPrimeBlindCyclopsOverHighBar = 0; + int firstPrimeBlindCyclopsOverHighBarIndex = 0; + List primePalindroneCyclops = []; + int primePalindromCyclopsCount = 0; + long firstPrimePalindromeCyclopsOverHighBar = 0; + int firstPrimePalindromeCyclopsOverHighBarIndex = 0; + + while (firstCyclopsOverHighBarIndex == 0 || cyclopsCount < displayMax + || firstPrimeCyclopsOverHighBarIndex == 0 || primeCyclopsCount < displayMax + || firstPrimeBlindCyclopsOverHighBarIndex == 0 || primeBlindCyclopsCount < displayMax + || firstPrimePalindromeCyclopsOverHighBarIndex == 0 || primePalindromCyclopsCount < displayMax) + { + if (IsCyclopsNumber(number)) + { + cyclopsCount++; + + if (cyclops.Count < displayMax) + { + cyclops.Add(number); + } + + if (firstCyclopsOverHighBarIndex == 0 && number > highBar) + { + firstCyclopsOverHighBar = number; + firstCyclopsOverHighBarIndex = cyclopsCount; + } + + if (IsPrime(number)) + { + primeCyclopsCount++; + + if (firstPrimeCyclopsOverHighBarIndex == 0 && number > highBar) + { + firstPrimeCyclopsOverHighBar = number; + firstPrimeCyclopsOverHighBarIndex = primeCyclopsCount; + } + + if (primeCyclops.Count < displayMax) + { + primeCyclops.Add(number); + } + + if (IsPrime(BlindCyclopsNumber(number))) + { + primeBlindCyclopsCount++; + + if (firstPrimeBlindCyclopsOverHighBarIndex == 0 && number > highBar) + { + firstPrimeBlindCyclopsOverHighBar = number; + firstPrimeBlindCyclopsOverHighBarIndex = primeBlindCyclopsCount; + } + + if (primeBlindCyclops.Count < displayMax) + { + primeBlindCyclops.Add(number); + } + } + + if (IsPalindrome(number.ToString())) + { + primePalindromCyclopsCount++; + + if (firstPrimePalindromeCyclopsOverHighBarIndex == 0 && number > highBar) + { + firstPrimePalindromeCyclopsOverHighBar = number; + firstPrimePalindromeCyclopsOverHighBarIndex = primePalindromCyclopsCount; + } + + if (primePalindroneCyclops.Count < displayMax) + { + primePalindroneCyclops.Add(number); + } + } + } + } + + number++; + } + + DisplayNumberSequence(cyclops, $"First {displayMax} Cyclops Numbers", highBar, firstCyclopsOverHighBarIndex, firstCyclopsOverHighBar); + DisplayNumberSequence(primeCyclops, $"First {displayMax} Prime Cyclops Numbers", highBar, firstPrimeCyclopsOverHighBarIndex, firstPrimeCyclopsOverHighBar); + DisplayNumberSequence(primeBlindCyclops, $"First {displayMax} Blind Prime Cyclops Numbers", highBar, firstPrimeBlindCyclopsOverHighBarIndex, firstPrimeBlindCyclopsOverHighBar); + DisplayNumberSequence(primePalindroneCyclops, $"First {displayMax} Palidrome Cyclops Numbers", highBar, firstPrimePalindromeCyclopsOverHighBarIndex, firstPrimePalindromeCyclopsOverHighBar); + } + + private static void DisplayNumberSequence(List numbers, string title, + long highBar, long firstIndexOverHighBar, long firstOverHighBar) + { + Console.WriteLine(title); + + for (int i = 0; i < numbers.Count; i++) + { + Console.Write($"{numbers[i],-7} "); + + if ((i + 1) % 10 == 0) + { + Console.WriteLine(); + } + } + + Console.WriteLine($"The first such number > {highBar} is the {firstIndexOverHighBar}th: {firstOverHighBar}"); + Console.WriteLine(); + } + + private static bool IsCyclopsNumber(long number ) + { + string numberAsString = number.ToString(); + int numberLength = numberAsString.Length; + int middleDigit = numberLength / 2; + + if (numberLength > 1 && numberLength % 2 !=0 // the number has an odd number of digits greater than one + && numberAsString.Count(c => c == '0') == 1 // there is only one zero + && numberAsString[middleDigit] == '0') // Zero is the middle digit + { + return true; + } + return false; + } + + private static bool IsPalindrome(string stringInput) + { + if (stringInput != null && stringInput.Length > 0) + { + var reversedString = new string(stringInput.ToCharArray().Reverse().ToArray()); + return stringInput == reversedString; + } + + return false; + } + + private static long BlindCyclopsNumber(long number) + { + string numberAsString = number.ToString(); + int numberLength = numberAsString.Length; + int middleDigit = numberLength / 2; + string blindNumber = string.Concat(numberAsString.AsSpan(0, middleDigit), numberAsString.AsSpan(middleDigit + 1, numberLength - (middleDigit + 1))); + return long.Parse(blindNumber); + } + + private static bool IsPrime(long number) + { + if (number < 2) + { + return false; + } + + if (number % 2 == 0) + { + return number == 2; + } + + if (number % 3 == 0) + { + return number == 3; + } + + int delta = 2; + long k = 5; + + while (k * k <= number) + { + if (number % k == 0) + { + return false; + } + + k += delta; + delta = 6 - delta; + } + + return true; + } +} diff --git a/Task/Damm-algorithm/ANSI-BASIC/damm-algorithm.basic b/Task/Damm-algorithm/ANSI-BASIC/damm-algorithm.basic new file mode 100644 index 0000000000..1635dfd92a --- /dev/null +++ b/Task/Damm-algorithm/ANSI-BASIC/damm-algorithm.basic @@ -0,0 +1,28 @@ +100 REM Damm algorithm +110 OPTION BASE 0 +120 DIM DT(9, 9) +130 FOR Y = 0 TO 9 +140 FOR X = 0 TO 9 +150 READ DT(X, Y) +160 NEXT X +170 NEXT Y +180 INPUT N$ +190 DO WHILE N$ <> "" +200 LET D = 0 +210 FOR I = 1 TO LEN(N$) +220 LET D = DT(VAL(MID$(N$, I, 1)), D) +230 NEXT I +240 IF D <> 0 THEN PRINT "FAIL" ELSE PRINT "PASS" +250 INPUT N$ +260 LOOP +270 DATA 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 +280 DATA 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 +290 DATA 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 +300 DATA 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 +310 DATA 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 +320 DATA 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 +330 DATA 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 +340 DATA 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 +350 DATA 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 +360 DATA 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 +370 END diff --git a/Task/Damm-algorithm/BASIC/damm-algorithm.basic b/Task/Damm-algorithm/GW-BASIC/damm-algorithm.basic similarity index 100% rename from Task/Damm-algorithm/BASIC/damm-algorithm.basic rename to Task/Damm-algorithm/GW-BASIC/damm-algorithm.basic diff --git a/Task/Damm-algorithm/Nascom-BASIC/damm-algorithm.basic b/Task/Damm-algorithm/Nascom-BASIC/damm-algorithm.basic new file mode 100644 index 0000000000..a37329be57 --- /dev/null +++ b/Task/Damm-algorithm/Nascom-BASIC/damm-algorithm.basic @@ -0,0 +1,23 @@ +10 REM Damm algorithm +20 DIM DT(9,9) +30 FOR Y=0 TO 9:FOR X=0 TO 9 +40 READ DT(X,Y) +50 NEXT X:NEXT Y +60 N$="":INPUT N$:IF N$="" THEN 130 +70 D=0 +80 FOR I=1 TO LEN(N$) +90 D=DT(VAL(MID$(N$,I,1)),D) +100 NEXT I +110 IF D THEN PRINT "FAIL":GOTO 60 +120 PRINT "PASS":GOTO 60 +130 END +140 DATA 0,3,1,7,5,9,8,6,4,2 +150 DATA 7,0,9,2,1,5,4,8,6,3 +160 DATA 4,2,0,6,8,7,1,3,5,9 +170 DATA 1,7,5,0,9,8,3,4,2,6 +180 DATA 6,1,2,3,0,4,5,9,7,8 +190 DATA 3,6,7,4,2,0,9,5,8,1 +200 DATA 5,8,6,9,7,2,0,1,3,4 +210 DATA 8,9,4,5,3,6,2,0,1,7 +220 DATA 9,4,3,8,6,1,7,2,0,5 +230 DATA 2,5,8,1,4,3,6,7,9,0 diff --git a/Task/Damm-algorithm/Refal/damm-algorithm.refal b/Task/Damm-algorithm/Refal/damm-algorithm.refal new file mode 100644 index 0000000000..5c36573e41 --- /dev/null +++ b/Task/Damm-algorithm/Refal/damm-algorithm.refal @@ -0,0 +1,38 @@ +$ENTRY Go { + = + + + ; +}; + +Test { + e.Ds = >; +}; + +Damm { + ('0') = Pass; + (s.Int) = Fail; + (s.Int) s.D e.Ds, + >: (e.Row), + e.Row>: s.Next + = ; + e.Ds = ; +}; + +DammTable { + = ('0317598642') + ('7092154863') + ('4206871359') + ('1750983426') + ('6123045978') + ('3674209581') + ('5869720134') + ('8945362017') + ('9438617205') + ('2581436790') +}; + +Item { + 0 t.I e.X = t.I; + s.N t.I e.X = e.X>; +}; diff --git a/Task/Damm-algorithm/SETL/damm-algorithm.setl b/Task/Damm-algorithm/SETL/damm-algorithm.setl new file mode 100644 index 0000000000..d48cef7478 --- /dev/null +++ b/Task/Damm-algorithm/SETL/damm-algorithm.setl @@ -0,0 +1,26 @@ +program damm_algorithm; + tests := [5724, 5727, 112946, 112949]; + + loop for test in tests do + print(str test + ': ' + if damm test then 'Pass' else 'Fail' end); + end loop; + + op damm(n); + dt := [[0,3,1,7,5,9,8,6,4,2], + [7,0,9,2,1,5,4,8,6,3], + [4,2,0,6,8,7,1,3,5,9], + [1,7,5,0,9,8,3,4,2,6], + [6,1,2,3,0,4,5,9,7,8], + [3,6,7,3,2,0,9,5,8,1], + [5,8,6,9,7,2,0,1,3,4], + [8,9,4,5,3,6,2,0,1,7], + [9,4,3,8,6,1,7,2,0,5], + [2,5,8,1,4,3,6,7,9,0]]; + + i := 0; + loop for d in str n do + i := dt(i+1)(val d+1); + end loop; + return i=0; + end op; +end program; diff --git a/Task/Date-format/Langur/date-format-1.langur b/Task/Date-format/Langur/date-format-1.langur index d68390fe38..9375725f6a 100644 --- a/Task/Date-format/Langur/date-format-1.langur +++ b/Task/Date-format/Langur/date-format-1.langur @@ -1,5 +1,2 @@ -var .now = dt// -var .format1 = "2006-01-02" -var .format2 = "Monday, January 2, 2006" -writeln $"\.now:dt.format1;" -writeln $"\.now:dt.format2;" +writeln string(dt//, "2006-01-02") +writeln string(dt//, "Monday, January 2, 2006") diff --git a/Task/Date-format/Langur/date-format-2.langur b/Task/Date-format/Langur/date-format-2.langur index 58006f8abc..b8821ea941 100644 --- a/Task/Date-format/Langur/date-format-2.langur +++ b/Task/Date-format/Langur/date-format-2.langur @@ -1,3 +1,2 @@ -var .now = dt// -writeln $"\.now:dt(2006-01-02);" -writeln $"\.now:dt(Monday, January 2, 2006);" +writeln "{{dt//:dt(2006-01-02)}}" +writeln "{{dt//:dt(Monday, January 2, 2006)}}" diff --git a/Task/Date-format/Langur/date-format-3.langur b/Task/Date-format/Langur/date-format-3.langur deleted file mode 100644 index 473f375e18..0000000000 --- a/Task/Date-format/Langur/date-format-3.langur +++ /dev/null @@ -1,2 +0,0 @@ -writeln string dt//, "2006-01-02" -writeln string dt//, "Monday, January 2, 2006" diff --git a/Task/Date-format/PascalABC.NET/date-format.pas b/Task/Date-format/PascalABC.NET/date-format.pas new file mode 100644 index 0000000000..b03b9f6d40 --- /dev/null +++ b/Task/Date-format/PascalABC.NET/date-format.pas @@ -0,0 +1,5 @@ +begin + var today := DateTime.Now; + Println(today.ToString('yyyy-MM-dd')); + Println($'{today:D}'); +end. diff --git a/Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.l b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.l new file mode 100644 index 0000000000..ead4f0f34d --- /dev/null +++ b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.l @@ -0,0 +1,40 @@ +(defun fix-time-string (calendar-string) + "If CALENDAR-STRING has no space between time and am/a.m./pm/p.m., add a space. + Return string with space between time and am/a.m./pm/p.m." + (replace-regexp-in-string "\\([[:digit:]]\\)\\([ap]\\)" "\\1 \\2" calendar-string)) + +(defun is-pm (calendar-string) + "Test if CALENDAR-STRING has PM/pm/P.M/p.m in it." + (string-match-p "[Pp][.]?[Mm]" calendar-string)) + +(defun is-hour-1-to-11 (a-calendar-list) + "Test if hour in A-CALENDAR-LIST is between 1 and 11." + (let ((hour-value)) + (setq hour-value (nth 2 a-calendar-list)) + (and (>= hour-value 1) (<= hour-value 11)))) + +(defun adjust-if-pm (time-as-string) + "If TIME-AS-STRING includes pm/PM, and hour is 1 to 11, add 12 hours. + Return CALENDAR-LIST modified if date is pm and hour is 1-11; otherwise + return CALENDAR-LIST of original TIME-AS-STRING." + (let ((calendar-list)) + (setq calendar-list (parse-time-string time-as-string)) + (if (and (is-pm time-as-string) (is-hour-1-to-11 calendar-list)) + (decoded-time-add calendar-list (make-decoded-time :hour 12)) + calendar-list))) + +(defun add-hours (calendar-list number-of-hours) + "Add NUMBER-OF-HOURS to CALENDAR-LIST." + (decoded-time-add calendar-list (make-decoded-time :hour number-of-hours))) + +(defun calc-future-time (string-calendar-date number-of-hours-in-future) + "Calculate future time by adding NUMBER-OF-HOURS-IN-FUTURE to STRING-CALENDAR-DATE ." + (let ((fixed-calendar-string) + (24-hour-calendar-list) + (calendar-list-future-time) + (coded-future-time)) + (setq fixed-calendar-string (fix-time-string string-calendar-date)) + (setq 24-hour-calendar-list (adjust-if-pm fixed-calendar-string)) + (setq calendar-list-future-time (add-hours 24-hour-calendar-list number-of-hours-in-future)) + (setq coded-future-time (encode-time calendar-list-future-time)) + (format-time-string "%B %e %Y %R %p %Z" coded-future-time))) diff --git a/Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.l b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.l new file mode 100644 index 0000000000..5ebd017876 --- /dev/null +++ b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.l @@ -0,0 +1,41 @@ +(defun fix-time-string (calendar-string) + "If CALENDAR-STRING has no space between time and a.m./p.m., add a space." + (replace-regexp-in-string "\\([[:digit:]]\\)\\([ap]\\)" "\\1 \\2" calendar-string)) + +(defun is-pm (calendar-string) + "Test if CALENDAR-STRING has PM/pm in it." + (string-match-p "[Pp][Mm]" time-as-string)) + +(defun is-hour-1-to-11 (a-calendar-list) + "Test if hour in A-CALENDAR-LIST is between 1 and 11." + (let ((hour-value)) + (setq hour-value (nth 2 a-calendar-list)) + (and (>= hour-value 1) (<= hour-value 11)))) + +(defun adjust-if-pm (time-as-string) + "If TIME-AS-STRING includes pm/PM, and hour is 1 to 11, add 12 hours. + Return time as integer of seconds past the epoch." + (let ((calendar-list) + (temp-time-stamp) + (time-stamp-as-integer)) + (setq calendar-list (parse-time-string time-as-string)) + (setq temp-time-stamp (encode-time calendar-list)) + (setq time-stamp-as-integer (time-convert temp-time-stamp 'integer)) + (if (and (is-pm time-as-string) (is-hour-1-to-11 calendar-list)) + (+ time-stamp-as-integer (* 12 60 60)) ; return time + 12 hours, so that hour is 13-23 + time-stamp-as-integer))) ; return time unchanged, leaving hour 0-12 + +(defun add-seconds (start-time-stamp-integer number-of-seconds) + "Add NUMBER-OF-HOURS to START-TIME-STAMP-INTEGER." + (+ start-time-stamp-integer number-of-seconds)) + +(defun calc-future-time (string-calendar-date number-of-seconds-in-future) + "Calculate future time by adding NUMBER-OF-SECONDS-IN-FUTURE to STRING-CALENDAR-DATE ." + (let ((fixed-calendar-string) + (time-stamp-as-integer) + (coded-current-time) + (future-time-as-integer)) + (setq fixed-calendar-string (fix-time-string string-calendar-date)) + (setq time-stamp-as-integer (adjust-if-pm fixed-calendar-string)) + (setq future-time-as-integer (add-seconds time-stamp-as-integer number-of-seconds-in-future)) + (format-time-string "%B %e %Y %R %p %Z" future-time-as-integer))) diff --git a/Task/Date-manipulation/Langur/date-manipulation.langur b/Task/Date-manipulation/Langur/date-manipulation.langur index 60e530d81b..d25c9c940e 100644 --- a/Task/Date-manipulation/Langur/date-manipulation.langur +++ b/Task/Date-manipulation/Langur/date-manipulation.langur @@ -1,24 +1,24 @@ -val .input = "March 7 2009 7:30pm -05:00" -val .iformat = "January 2 2006 3:04pm -07:00" -val .oformat = "January 2 2006 3:04pm MST" +val input = "March 7 2009 7:30pm -05:00" +val iformat = "January 2 2006 3:04pm -07:00" +val oformat = "January 2 2006 3:04pm MST" -val .d1 = datetime .input, .iformat -val .d2 = .d1 + dr/PT12H/ -val .d3 = datetime .d2, "US/Arizona" -val .d4 = datetime .d2, zls -val .d5 = datetime .d2, "Z" -val .d6 = datetime .d2, "+02:30" -val .d7 = datetime .d2, "EST" +val d1 = datetime(input, iformat) +val d2 = d1 + dr/T12h/ +val d3 = datetime(d2, "US/Arizona") +val d4 = datetime(d2, zls) +val d5 = datetime(d2, "Z") +val d6 = datetime(d2, "+02:30") +val d7 = datetime(d2, "EST") -writeln "input string: ", .input -writeln "input format string: ", .iformat -writeln "output format string: ", .oformat +writeln "input string: ", input +writeln "input format string: ", iformat +writeln "output format string: ", oformat writeln() -writeln $"original: \.d1; (\.d1:dt.oformat;)" -writeln $"+12 hours: \.d2; (\.d2:dt.oformat;)" -writeln $"in Arizona: \.d3; (\.d3:dt.oformat;)" -writeln $"in local time zone: \.d4; (\.d4:dt.oformat;)" -writeln $"in UTC: \.d5; (\.d5:dt.oformat;)" -writeln $"+02:30 time zone: \.d6; (\.d6:dt.oformat;)" -writeln $"in EST: \.d7; (\.d7:dt.oformat;)" +writeln "original: {{d1}} ({{d1:dt oformat}})" +writeln "+12 hours: {{d2}} ({{d2:dt oformat}})" +writeln "in Arizona: {{d3}} ({{d3:dt oformat}})" +writeln "in local time zone: {{d4}} ({{d4:dt oformat}})" +writeln "in UTC: {{d5}} ({{d5:dt oformat}})" +writeln "+02:30 time zone: {{d6}} ({{d6:dt oformat}})" +writeln "in EST: {{d7}} ({{d7:dt oformat}})" diff --git a/Task/Day-of-the-week/PascalABC.NET/day-of-the-week.pas b/Task/Day-of-the-week/PascalABC.NET/day-of-the-week.pas new file mode 100644 index 0000000000..276296d710 --- /dev/null +++ b/Task/Day-of-the-week/PascalABC.NET/day-of-the-week.pas @@ -0,0 +1,5 @@ +const Sunday = System.DayOfWeek.Sunday; + +begin + (2008..2121).Where(y -> DateTime.Create(y,12,25).DayOfWeek = Sunday).Println +end. diff --git a/Task/De-Bruijn-sequences/11l/de-bruijn-sequences.11l b/Task/De-Bruijn-sequences/11l/de-bruijn-sequences.11l index 00a2e2ffdf..26c684e6d5 100644 --- a/Task/De-Bruijn-sequences/11l/de-bruijn-sequences.11l +++ b/Task/De-Bruijn-sequences/11l/de-bruijn-sequences.11l @@ -5,7 +5,7 @@ F deBruijn(k, n) V a = [Byte(0)] * (k * n) [Byte] seq - F db(Int t, Int p) -> N + F db(Int t, Int p) -> Void I t > @n I @n % p == 0 @seq.extend(@a[1 .< p + 1]) diff --git a/Task/Deal-cards-for-FreeCell/TypeScript/deal-cards-for-freecell.ts b/Task/Deal-cards-for-FreeCell/TypeScript/deal-cards-for-freecell.ts new file mode 100644 index 0000000000..127f2fd09c --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/TypeScript/deal-cards-for-freecell.ts @@ -0,0 +1,133 @@ +/* TypeScript code for dealing Microsoft FreeCell / FreeCell Pro deals. + * Copyright by Shlomi Fish, 2011. + * Released under the MIT/Expat License + * ( http://en.wikipedia.org/wiki/MIT_License ). + */ +function perl_range(start: number, end: number): number[] { + const ret: number[] = []; + + for (let i = start; i <= end; ++i) { + ret.push(i); + } + + return ret; +} + +// 33 bit +const MAX_SEED: bigint = (BigInt(1) << BigInt(31 + 2)) - BigInt(1); +const X = BigInt(1) << BigInt(32); + +/* + * Microsoft C Run-time-Library-compatible Random Number Generator + * */ +class MSRand { + private gamenumber: string; + private _seed: bigint; + private _seedx: bigint; + constructor(args) { + const that = this; + that.gamenumber = args.gamenumber; + const _seed = BigInt(that.gamenumber); + that._seed = _seed; + that._seedx = _seed < X ? _seed : _seed - X; + return; + } + public getSeed(): bigint { + const that = this; + return that._seed; + } + private setSeed(seed: bigint): void { + const that = this; + that._seed = seed; + return; + } + + private _rando(): bigint { + const that = this; + that._seedx = + (that._seedx * BigInt(214013) + BigInt(2531011)) & MAX_SEED; + return (that._seedx >> BigInt(16)) & BigInt(0x7fff); + } + private _randp(): bigint { + const that = this; + that._seedx = + (that._seedx * BigInt(214013) + BigInt(2531011)) & MAX_SEED; + return (that._seedx >> BigInt(16)) & BigInt(0xffff); + } + public raw_rand(): bigint { + const that = this; + + if (that._seed < X) { + const ret = that._rando(); + return that._seed < BigInt(0x8) << BigInt(28) + ? ret + : ret | BigInt(0x8000); + } else { + return that._randp() + BigInt(1); + } + } + public max_rand(mymax: bigint): bigint { + const that = this; + return that.raw_rand() % mymax; + } + public shuffle(deck: Array): Array { + const that = this; + if (deck.length) { + let i = deck.length; + while (--i) { + const j = Number(that.max_rand(BigInt(i + 1))); + const tmp = deck[i]; + deck[i] = deck[j]; + deck[j] = tmp; + } + } + return deck; + } +} +/* + * Microsoft Windows Freecell / Freecell Pro boards generation. + * + * See: + * + * - http://rosettacode.org/wiki/Deal_cards_for_FreeCell + * + * - http://www.solitairelaboratory.com/mshuffle.txt + * + * Under MIT/Expat Licence. + * + * */ + +export function deal_ms_fc_board(gamenumber: string): string { + const randomizer = new MSRand({ + gamenumber: gamenumber, + }); + const num_cols: number = 8; + + const columns: Array> = perl_range(0, num_cols - 1).map( + () => { + return []; + }, + ); + let deck: Array = perl_range(0, 4 * 13 - 1); + + randomizer.shuffle(deck); + + deck = deck.reverse(); + + for (let i = 0; i < 52; ++i) { + columns[i % num_cols].push(deck[i]); + } + + function render_card(card: number): String { + const suit = card % 4; + const rank = Math.floor(card / 4); + + return "A23456789TJQK".charAt(rank) + "CDHS".charAt(suit); + } + + function render_column(col: Array): String { + return ": " + col.map(render_card).join(" ") + "\n"; + } + + return columns.map(render_column).join(""); +} diff --git a/Task/Death-Star/11l/death-star.11l b/Task/Death-Star/11l/death-star.11l index 23b604e42c..629b3b6f51 100644 --- a/Task/Death-Star/11l/death-star.11l +++ b/Task/Death-Star/11l/death-star.11l @@ -1,10 +1,4 @@ -T Sphere - Float cx, cy, cz, r - F (cx, cy, cz, r) - .cx = cx - .cy = cy - .cz = cz - .r = r +T Sphere = (Float cx, Float cy, Float cz, Float r) F dotp(v1, v2) V d = dot(v1, v2) diff --git a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur index c54868c2f7..acba2f2f8c 100644 --- a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur +++ b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur @@ -1,14 +1,16 @@ -val .isPrime = fn(.i) .i == 2 or .i > 2 and - not any fn(.x) .i div .x, pseries 2 .. .i ^/ 2 +val isPrime = fn(i) { + i == 2 or i > 2 and + not any(fn x: i div x, pseries(2 .. i ^/ 2)) +} -var .nums = [] -var .repunit = 111_111 +var nums = [] +var repunit = 111_111 -for .n = 9; len(.nums) < 10; .n += 2 { - .repunit = .repunit * 100 + 11 - if not .isPrime(.n) and .repunit div .n { - .nums = more .nums, .n +for n = 9; len(nums) < 10; n += 2 { + repunit = repunit * 100 + 11 + if not isPrime(n) and repunit div n { + nums = more(nums, n) } } -writeln .nums +writeln nums diff --git a/Task/Deconvolution-1D/Jq/deconvolution-1d.jq b/Task/Deconvolution-1D/Jq/deconvolution-1d.jq new file mode 100644 index 0000000000..49402b22d4 --- /dev/null +++ b/Task/Deconvolution-1D/Jq/deconvolution-1d.jq @@ -0,0 +1,22 @@ +def deconv($g; $f): + { h: [range(0; ($g|length) - ($f|length) + 1) | 0] } + | reduce range ( 0;.h|length) as $n (.; + .h[$n] = $g[$n] + | (if $n >= ($f|length) then $n - ($f|length) + 1 else 0 end) as $lower + | .i = $lower + | until(.i >= $n; + .h[$n] -= .h[.i] * $f[$n - .i] + | .i += 1 ) + | .h[$n] /= $f[0] ) + | .h ; + +### The tasks + +def h: [-8, -9, -3, -1, -6, 7]; +def f: [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1]; +def g: [24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7]; + +h, +deconv(g; f), +f, +deconv(g; h) diff --git a/Task/Define-a-primitive-data-type/PascalABC.NET/define-a-primitive-data-type.pas b/Task/Define-a-primitive-data-type/PascalABC.NET/define-a-primitive-data-type.pas new file mode 100644 index 0000000000..9c6fe7bcd7 --- /dev/null +++ b/Task/Define-a-primitive-data-type/PascalABC.NET/define-a-primitive-data-type.pas @@ -0,0 +1,27 @@ +type RangeInt = record + n: integer; +public + constructor(nn: integer); + begin + if nn not in 1..10 then + raise new System.ArgumentOutOfRangeException; + n := nn; + end; + function ToString: string; override := n.ToString; + static function operator implicit (n: integer): RangeInt := new RangeInt(n); + static function operator+(a,b: RangeInt): RangeInt := a.n + b.n; + static function operator-(a,b: RangeInt): RangeInt := a.n - b.n; + static function operator*(a,b: RangeInt): RangeInt := a.n * b.n; + static function operator/(a,b: RangeInt): real := a.n / b.n; + static function operator div(a,b: RangeInt): RangeInt := a.n div b.n; + static function operator mod(a,b: RangeInt): RangeInt := a.n mod b.n; +end; + +function RInt(n: integer) := new RangeInt(n); + +begin + var a: RangeInt := 7; + var b: RangeInt := 3; + Print(a + b, a - b, a div b, a mod b); + Print(a * b); // ArgumentOutOfRangeException exception +end. diff --git a/Task/Detect-division-by-zero/Langur/detect-division-by-zero.langur b/Task/Detect-division-by-zero/Langur/detect-division-by-zero.langur index e93045e0fb..86121c3cf6 100644 --- a/Task/Detect-division-by-zero/Langur/detect-division-by-zero.langur +++ b/Task/Detect-division-by-zero/Langur/detect-division-by-zero.langur @@ -1,5 +1,5 @@ -val .div = fn(.x, .y) { - [.x / .y, true] +val dz = fn(x, y) { + [x / y, true] catch { if _err'msg -> re/division by 0/ { [0, false] @@ -10,5 +10,5 @@ val .div = fn(.x, .y) { } } -writeln .div(3, 2) -writeln .div(3, 0) +writeln dz(3, 2) +writeln dz(3, 0) diff --git a/Task/Determine-if-a-string-is-collapsible/Uiua/determine-if-a-string-is-collapsible.uiua b/Task/Determine-if-a-string-is-collapsible/Uiua/determine-if-a-string-is-collapsible.uiua new file mode 100644 index 0000000000..0133fc0a7b --- /dev/null +++ b/Task/Determine-if-a-string-is-collapsible/Uiua/determine-if-a-string-is-collapsible.uiua @@ -0,0 +1,13 @@ +S ← {"" + "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln" + "..1111111111111111111111111111111111111111111111111111111111111117777888" + "I never give 'em hell, I just tell the truth, and they think it's hell. " + " --- Harry S Truman " + "The better the 4-wheel drive, the further you'll be from help when ya get stuck!" + "headmistressship" + "aardvark" + "😍😀🙌💃😍😍😍🙌" + "unnecessary bookkeeping"} + +Collapse ← ⊜⊢+1⊛. +≡(&p""≡(&p$"_ chars \t«_»" ⊸⧻°□))≡(⊟⟜⍜°□Collapse)S diff --git a/Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-1.l b/Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-1.l new file mode 100644 index 0000000000..bb17cf908b --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-1.l @@ -0,0 +1,12 @@ +(defun string-valid-number-p (str) + "Test if STR is a numeric string. +Eliminate strings with commas in them because ELisp numbers do +not contain commas. Then check if remaining strings would be +valid ELisp numbers if the quotation marks were removed." + (and + ;; no comma in string, because ELisp numbers do not have commas + ;; we need to eliminate any string with a comma, because the + ;; numberp function below will not weed out commas + (not (string-match-p "," str)) + ;; no errors from numberp function testing if a number + (ignore-errors (numberp (read str))))) diff --git a/Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-2.l b/Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-2.l new file mode 100644 index 0000000000..ab8b39e2d0 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-2.l @@ -0,0 +1,17 @@ +(setq valid-strings '("3" "0" "-0" "2." "1000" "-4" "-5." "6.2" "-8.45" "+15e2" "-15e2" "#b101100" "#o54" "#x2c" "1500.0" "#24r1k" "3")) + +(setq invalid-strings '("3cat" "1,000" "5.6.7" "cat3" "def" "zero")) + +(with-current-buffer (pop-to-buffer "my-test") + (erase-buffer) + (insert "Test for valid strings:\n") + (dolist (test-string valid-strings) + (let ((test-result)) + (setq test-result (string-valid-number-p test-string)) + (insert (format "%-8s - %s \n" test-string test-result)))) + (insert "\n" "\n") + (insert "Test for invalid strings:\n") + (dolist (test-string invalid-strings) + (let ((test-result)) + (setq test-result (string-valid-number-p test-string)) + (insert (format "%-5s - %s \n" test-string test-result))))) diff --git a/Task/Determine-if-a-string-is-numeric/PascalABC.NET/determine-if-a-string-is-numeric.pas b/Task/Determine-if-a-string-is-numeric/PascalABC.NET/determine-if-a-string-is-numeric.pas new file mode 100644 index 0000000000..47846ad8c7 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/PascalABC.NET/determine-if-a-string-is-numeric.pas @@ -0,0 +1,11 @@ +function IsNumeric(s: string): boolean; +begin + var i: integer; + Result := integer.TryParse(s,i) +end; + +begin + var s := '123'; + if IsNumeric(s) then + Print('string is numeric') +end. diff --git a/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric.rust b/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric-1.rust similarity index 100% rename from Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric.rust rename to Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric-1.rust diff --git a/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric-2.rust b/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric-2.rust new file mode 100644 index 0000000000..6fa45d5e64 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Rust/determine-if-a-string-is-numeric-2.rust @@ -0,0 +1,34 @@ +use std::str::FromStr; + +fn parsable(s: &str) -> bool { + s.parse::().is_ok() +} + +fn main() { + let test_cases = [ + "142857", + "3.14", + "not of this earth!" + ]; + + let types: &[(&str, fn(&str) -> bool)] = &[ + ("i32", parsable:: as fn(&str) -> bool), + ("i64", parsable:: as fn(&str) -> bool), + ("i128", parsable:: as fn(&str) -> bool), + + ("f64", parsable:: as fn(&str) -> bool), + ]; + + println!(""); + for &case in &test_cases { + for &(type_name, parse_fn) in types { + println!( + "'{}' {} be parsed as {}", + case, + if parse_fn(case) { "can" } else { "_cannot_" }, + type_name + ); + } + println!(""); + } +} diff --git a/Task/Determine-if-a-string-is-numeric/Zig/determine-if-a-string-is-numeric.zig b/Task/Determine-if-a-string-is-numeric/Zig/determine-if-a-string-is-numeric.zig new file mode 100644 index 0000000000..5c2a0ce361 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Zig/determine-if-a-string-is-numeric.zig @@ -0,0 +1,32 @@ +const std = @import("std"); +const stdout = std.io.getStdOut().writer(); + +fn isNumeric(str: []const u8) bool { + const num = std.mem.trim(u8, str, "\x20"); + _ = std.fmt.parseFloat(f64, num) catch return false; + return true; +} + +pub fn main() !void { + const s1 = " 123"; + const s2 = " +123"; + const s3 = " 12.3"; + const s4 = "-12.3"; + const s5 = "12e-3"; + const s6 = "=12-3"; + const s7 = "abcde"; + const s8 = "12cde"; + const s9 = "NaN"; + const s10 = "0xFF"; + + try stdout.print("Is {s} numeric? {}\n", .{ s1, isNumeric(s1) }); + try stdout.print("Is {s} numeric? {}\n", .{ s2, isNumeric(s2) }); + try stdout.print("Is {s} numeric? {}\n", .{ s3, isNumeric(s3) }); + try stdout.print("Is {s} numeric? {}\n", .{ s4, isNumeric(s4) }); + try stdout.print("Is {s} numeric? {}\n", .{ s5, isNumeric(s5) }); + try stdout.print("Is {s} numeric? {}\n", .{ s6, isNumeric(s6) }); + try stdout.print("Is {s} numeric? {}\n", .{ s7, isNumeric(s7) }); + try stdout.print("Is {s} numeric? {}\n", .{ s8, isNumeric(s8) }); + try stdout.print("Is {s} numeric? {}\n", .{ s9, isNumeric(s9) }); + try stdout.print("Is {s} numeric? {}\n", .{ s10, isNumeric(s10) }); +} diff --git a/Task/Determine-sentence-type/Emacs-Lisp/determine-sentence-type.l b/Task/Determine-sentence-type/Emacs-Lisp/determine-sentence-type.l new file mode 100644 index 0000000000..955366ef7c --- /dev/null +++ b/Task/Determine-sentence-type/Emacs-Lisp/determine-sentence-type.l @@ -0,0 +1,28 @@ +(defun get-last-character (str) + "Return the last character of STR." + (let ((str-length)) + (setq str-length (length str)) + (substring str (- str-length 1) str-length))) + +(defun classify-sentence (str) + "Classify the type of sentence based on final punctuation." + (let ((last-character (get-last-character str))) + (cond ((string= last-character ".") (format "S - %s" str)) + ((string= last-character "!") (format "E - %s" str)) + ((string= last-character "?") (format "Q - %s" str)) + (t (format "N - %s" str))))) + +(defun classify-multiple-sentences (str) + "Classify each sentence as Q, S, E, or N." + ;; sentence boundary is defined as: + ;; a period (full stop), comma, or question mark + ;; followed by one space + ;; followed by a capital letter + ;; while the above will work for this exercise, it won't + ;; work in other situations. See the Perl code in this section + ;; for cases that the above will not cover. + (let ((regex-sentence-boundary "\\([.?!]\\) \\([[:upper:]]\\)")) + ;; split the text into list of individual sentences + (dolist (one-sentence (split-string (replace-regexp-in-string regex-sentence-boundary "\\1\n\\2" str) "\n")) + ;; classify each sentence + (insert (format "\n%s" (classify-sentence one-sentence)))))) diff --git a/Task/Determine-sentence-type/FutureBasic/determine-sentence-type.basic b/Task/Determine-sentence-type/FutureBasic/determine-sentence-type.basic new file mode 100644 index 0000000000..1de7fb970c --- /dev/null +++ b/Task/Determine-sentence-type/FutureBasic/determine-sentence-type.basic @@ -0,0 +1,16 @@ +local fn SentenceType( sentence as CFStringRef ) as CFStringRef + CFStringRef type + select ( fn StringCharacterAtIndex( sentence, len(sentence)-1 ) ) + case _"?" : type = @"Q" + case _"." : type = @"S" + case _"!" : type = @"E" + case else : type = @"N" + end select +end fn = type + +print fn SentenceType( @"hi there, how are you today?" ) +print fn SentenceType( @"I'd like to present to you the washing machine 9001." ) +print fn SentenceType( @"You have been nominated to win one of these!" ) +print fn SentenceType( @"Just make sure you don't break it" ) + +HandleEvents diff --git a/Task/Determine-sentence-type/PascalABC.NET/determine-sentence-type.pas b/Task/Determine-sentence-type/PascalABC.NET/determine-sentence-type.pas new file mode 100644 index 0000000000..0e19ebfe52 --- /dev/null +++ b/Task/Determine-sentence-type/PascalABC.NET/determine-sentence-type.pas @@ -0,0 +1,18 @@ +function SentenceType(s: string): char; +begin + case s[^1] of + '?': Result := 'Q'; + '!': Result := 'E'; + '.': Result := 'S'; + else Result := 'N'; + end; +end; + +begin + var ss := Arr('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'); + foreach var s in ss do + Println(s,'->',SentenceType(s)); +end. diff --git a/Task/Determine-sentence-type/Refal/determine-sentence-type.refal b/Task/Determine-sentence-type/Refal/determine-sentence-type.refal new file mode 100644 index 0000000000..c1480b665e --- /dev/null +++ b/Task/Determine-sentence-type/Refal/determine-sentence-type.refal @@ -0,0 +1,17 @@ +$ENTRY Go { + , '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': e.Sentences + = >; +}; + +SentenceTypes { + e.X '?' = Q; + e.X '? ' e.Y = Q ; + e.X '.' = S; + e.X '. ' e.Y = S ; + e.X '!' = E; + e.X '! ' e.Y = E ; + e.X = N; +} diff --git a/Task/Dijkstras-algorithm/11l/dijkstras-algorithm.11l b/Task/Dijkstras-algorithm/11l/dijkstras-algorithm.11l index 40debc616d..5725c46344 100644 --- a/Task/Dijkstras-algorithm/11l/dijkstras-algorithm.11l +++ b/Task/Dijkstras-algorithm/11l/dijkstras-algorithm.11l @@ -1,12 +1,4 @@ -T Edge - String start - String end - Int cost - - F (start, end, cost) - .start = start - .end = end - .cost = cost +T Edge = (String start, String end, Int cost) T Graph [Edge] edges diff --git a/Task/Dinesmans-multiple-dwelling-problem/Quackery/dinesmans-multiple-dwelling-problem.quackery b/Task/Dinesmans-multiple-dwelling-problem/Quackery/dinesmans-multiple-dwelling-problem.quackery new file mode 100644 index 0000000000..42d42566ee --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Quackery/dinesmans-multiple-dwelling-problem.quackery @@ -0,0 +1,38 @@ + [ stack ] is problem ( --> s ) + + [ temp share 0 peek ] is baker ( --> n ) + [ temp share 1 peek ] is cooper ( --> n ) + [ temp share 2 peek ] is fletcher ( --> n ) + [ temp share 3 peek ] is miller ( --> n ) + [ temp share 4 peek ] is smith ( --> n ) + + [ temp share size = ] is top ( n --> b ) + [ 1 = ] is bottom ( n --> b ) + [ > ] is higher ( n n --> b ) + [ - abs 1 = ] is adjacent ( n n --> b ) + + [ if ]done[ ] is exclude ( b --> ) + [ not if ]done[ ] is require ( b --> ) + [ temp share nested join ] is include ( [ --> [ ) + + [ ]'[ ' include join + problem put + [] + ' [ 1 2 3 4 5 ] + permutations + witheach + [ temp put + problem share do + temp release ] + problem release + say " B C F M S" cr + witheach [ echo cr ] ] is solve ( --> ) + + solve + [ baker top exclude + cooper bottom exclude + fletcher top + fletcher bottom or exclude + miller cooper higher require + smith fletcher adjacent exclude + fletcher cooper adjacent exclude ] diff --git a/Task/Disarium-numbers/Refal/disarium-numbers.refal b/Task/Disarium-numbers/Refal/disarium-numbers.refal new file mode 100644 index 0000000000..24e17b740b --- /dev/null +++ b/Task/Disarium-numbers/Refal/disarium-numbers.refal @@ -0,0 +1,32 @@ +$ENTRY Go { + = ; +}; + +Digits { + 0 = ; + s.N, : (s.R) s.D = s.D; +}; + +Pow { + s.N 0 = 1; + s.N s.P = <* s.N >>; +}; + +PowSum { + () e.P = 0; + (s.I e.X) e.P = <+ >>; + e.X = ; +}; + +Disarium { + e.N, >: e.N = True; + e.N = False; +}; + +FindDisarium { + 0 s.N = ; + s.I s.N, : { + True = <+ s.N 1>>; + False = >; + }; +}; diff --git a/Task/Discordian-date/Refal/discordian-date.refal b/Task/Discordian-date/Refal/discordian-date.refal new file mode 100644 index 0000000000..1702d7bf77 --- /dev/null +++ b/Task/Discordian-date/Refal/discordian-date.refal @@ -0,0 +1,62 @@ +$ENTRY Go { + , >: s.GY + , >: s.GM + , >: s.GD + , : { + True e.Desc = ; + False = ; + }; +}; + +DisDate { + s.GY 2 29, : True = + True 'St. Tib\'s day in the YOLD ' >; + + s.GY s.GM s.GD, : '-' = False; + s.GY s.GM s.GD, : '+' = False; + s.GY s.GM s.GD, : '-' = False; + s.GY s.GM s.GD, >>: '+' = False; + + s.GY s.GM s.GD, + <+ > s.GD>: s.DOY, + 73>: (s.DS1) s.DD1, + <+ s.DS1 1>: s.DS, + <+ s.DD1 1>: s.DD, + <+ 5> 1>: s.DWD, + + >: (e.Weekday), + >: (e.Season), + + e.Weekday ', day ' ' of ' + e.Season ' in the YOLD ' >: e.Desc, + s.DD: { + 5, >: (e.H) = True e.Desc ': celebrate ' e.H; + 50, >: (e.H) = True e.Desc ': celebrate ' e.H; + s.X = True e.Desc; + }; +}; + +Item { + 1 t.I e.X = t.I; + s.N t.I e.X = e.X>; +}; + +IsLeapYear { + s.GY, : 0 = True; + s.GY, : 0 = False; + s.GY, : 0 = True; + s.GY = False; +}; + +MonthOffset { = 0 31 59 90 120 151 181 212 243 273 304 334; }; +MonthLength { = 31 28 31 30 31 30 31 31 30 31 30 31; }; + +Weekday { = ('Sweetmorn') ('Boomtime') ('Pungenday') + ('Prickle-Prickle') ('Setting Orange'); }; + +Seasons { = ('Chaos') ('Discord') ('Confusion') ('Bureaucracy') + ('The Aftermath'); }; + +Holy5 { = ('Mungday') ('Mojoday') ('Syaday') ('Zaraday') ('Maladay'); }; +Holy50 { = ('Chaoflux') ('Discoflux') ('Confuflux') + ('Bureflux') ('Afflux'); }; diff --git a/Task/Display-a-linear-combination/APL/display-a-linear-combination.apl b/Task/Display-a-linear-combination/APL/display-a-linear-combination.apl new file mode 100644 index 0000000000..d082f38e2b --- /dev/null +++ b/Task/Display-a-linear-combination/APL/display-a-linear-combination.apl @@ -0,0 +1,11 @@ + lincomb←{ + fmtco←{ + mul←(⍵≠1)/(⍕|⍵),'*' + mul,'e(',(⍕⍺),')' + } + + co←⊃¨fmtco/¨(⍵≠0)/(⍳⍴,⍵),¨|⍵ + sgn←'-+'[1+(×⍵)/×⍵] + lc←(('+'=⊃)↓⊢)∊sgn,¨co + 0=⍴lc:'0' ⋄ lc + } diff --git a/Task/Display-a-linear-combination/Applesoft-BASIC/display-a-linear-combination.basic b/Task/Display-a-linear-combination/Applesoft-BASIC/display-a-linear-combination.basic new file mode 100644 index 0000000000..1c3a5cdce5 --- /dev/null +++ b/Task/Display-a-linear-combination/Applesoft-BASIC/display-a-linear-combination.basic @@ -0,0 +1,22 @@ + 100 READ UX,UY + 110 DIM SCALARS(UX,UY) + 120 FOR N = 1 TO UX + 130 FOR M = 1 TO UY + 140 READ SCALARS(N,M) + 150 NEXT M,N + 160 DATA10,4 + 170 DATA1,2,3,0,0,1,2,3 + 180 DATA1,0,3,4,1,2,0,0 + 190 DATA0,0,0,0,0,0,0,0 + 200 DATA1,1,1,0,-1,-1,-1,0 + 210 DATA-1,-2,0,-3,-1,0,0,0 + 220 FOR N = 1 TO UX + 230 CADENA$ = "" + 240 FOR M = 1 TO UY + 250 SCALAR = SCALARS(N,M) + 260 IF SCALAR THEN CADENA$ = CADENA$ + CHR$ (44 - SGN (SCALAR)) + MID$ ( STR$ ( ABS (SCALAR)) + "*",1,255 * ( ABS (SCALAR) < > 1)) + "E" + STR$ (M) + 270 NEXT M + 280 IF CADENA$ = "" THEN CADENA$ = "0" + 290 IF LEFT$ (CADENA$,1) = "+" THEN CADENA$ = RIGHT$ (CADENA$, LEN (CADENA$) - 1) + 300 PRINT CADENA$ + 310 NEXT N diff --git a/Task/Display-a-linear-combination/Chipmunk-Basic/display-a-linear-combination.basic b/Task/Display-a-linear-combination/Chipmunk-Basic/display-a-linear-combination.basic new file mode 100644 index 0000000000..43ca40866a --- /dev/null +++ b/Task/Display-a-linear-combination/Chipmunk-Basic/display-a-linear-combination.basic @@ -0,0 +1,38 @@ +100 dim scalars(10,4) +110 scalars(1,1) = 1 : scalars(1,2) = 2 : scalars(1,3) = 3 +120 scalars(2,1) = 0 : scalars(2,2) = 1 : scalars(2,3) = 2 : scalars(2,4) = 3 +130 scalars(3,1) = 1 : scalars(3,2) = 0 : scalars(3,3) = 3 : scalars(3,4) = 4 +140 scalars(4,1) = 1 : scalars(4,2) = 2 : scalars(4,3) = 0 +150 scalars(5,1) = 0 : scalars(5,2) = 0 : scalars(5,3) = 0 +160 scalars(6,1) = 0 +170 scalars(7,1) = 1 : scalars(7,2) = 1 : scalars(7,3) = 1 +180 scalars(8,1) = -1 : scalars(8,2) = -1 : scalars(8,3) = -1 +190 scalars(9,1) = -1 : scalars(9,2) = -2 : scalars(9,3) = 0 : scalars(9,4) = -3 +200 scalars(10,1) = -1 +210 cls +220 for n = 1 to ubound(scalars) +230 cadena$ = "" +240 scalar = 0 +250 for m = 1 to ubound(scalars,2) +260 scalar = scalars(n,m) +270 if scalar <> 0 then +280 if scalar = 1 then +290 cadena$ = cadena$+"+e"+str$(m) +300 else +310 if scalar = -1 then +320 cadena$ = cadena$+"-e"+str$(m) +330 else +340 if scalar > 0 then +350 cadena$ = cadena$+chr$(43)+str$(scalar)+"*e"+str$(m) +360 else +370 cadena$ = cadena$+str$(scalar)+"*e"+str$(m) +380 endif +390 endif +400 endif +410 endif +420 next m +430 if cadena$ = "" then cadena$ = "0" +440 if left$(cadena$,1) = "+" then cadena$ = right$(cadena$,len(cadena$)-1) +450 print cadena$ +460 next n +470 end diff --git a/Task/Display-a-linear-combination/Cowgol/display-a-linear-combination.cowgol b/Task/Display-a-linear-combination/Cowgol/display-a-linear-combination.cowgol new file mode 100644 index 0000000000..70ebd193ef --- /dev/null +++ b/Task/Display-a-linear-combination/Cowgol/display-a-linear-combination.cowgol @@ -0,0 +1,60 @@ +include "cowgol.coh"; + +sub abs(n: int32): (r: uint32) is + if n < 0 + then r := (-n) as uint32; + else r := n as uint32; + end if; +end sub; + +sub lincomb(scalar: [int32], size: intptr) is + var first: uint8 := 1; + var item: uint8 := 1; + + sub print_sign() is + if first == 1 then + if [scalar] < 0 then print("-"); end if; + else + if [scalar] < 0 + then print(" - "); + else print(" + "); + end if; + end if; + end sub; + + sub print_term() is + if [scalar] == 0 then return; end if; + print_sign(); + if abs([scalar]) > 1 then + print_i32(abs([scalar])); + print("*"); + end if; + print("e("); + print_i8(item); + print(")"); + first := 0; + end sub; + + while size > 0 loop + print_term(); + scalar := @next scalar; + size := size - 1; + item := item + 1; + end loop; + + if first == 1 then + print("0"); + end if; + print_nl(); +end sub; + +var a1: int32[] := {1, 2, 3}; lincomb(&a1[0], @sizeof a1); +var a2: int32[] := {0, 1, 2, 3}; lincomb(&a2[0], @sizeof a2); +var a3: int32[] := {1, 0, 3, 4}; lincomb(&a3[0], @sizeof a3); +var a4: int32[] := {1, 2, 0}; lincomb(&a4[0], @sizeof a4); +var a5: int32[] := {0, 0, 0}; lincomb(&a5[0], @sizeof a5); +var a6: int32[] := {0}; lincomb(&a6[0], @sizeof a6); +var a7: int32[] := {1, 1, 1}; lincomb(&a7[0], @sizeof a7); +var a8: int32[] := {-1, -1, -1}; lincomb(&a8[0], @sizeof a8); +var a9: int32[] := {-1, -2, 0, 3}; lincomb(&a9[0], @sizeof a9); +var a10: int32[] := {-1}; lincomb(&a10[0], @sizeof a10); diff --git a/Task/Display-a-linear-combination/Draco/display-a-linear-combination.draco b/Task/Display-a-linear-combination/Draco/display-a-linear-combination.draco new file mode 100644 index 0000000000..68a3d6f49b --- /dev/null +++ b/Task/Display-a-linear-combination/Draco/display-a-linear-combination.draco @@ -0,0 +1,44 @@ +proc abs(int n) int: if n<0 then -n else n fi corp + +proc write_term(word index; int scalar; bool first) void: + if first then + if scalar<0 then write("-") fi + else + write(if scalar<0 then " - " else " + " fi) + fi; + if abs(scalar)>1 then + write(abs(scalar), '*') + fi; + write("e(",index,")") +corp + +proc lincomb([*]int terms) void: + bool first; + word index; + first := true; + + for index from 0 upto dim(terms,1)-1 do + if terms[index] /= 0 then + write_term(index+1, terms[index], first); + first := false + fi + od; + + writeln(if first then "0" else "" fi) +corp + +proc main() void: + [3]int a1 = (1,2,3); + [4]int a2 = (0,1,2,3); + [4]int a3 = (1,0,3,4); + [3]int a4 = (1,2,0); + [3]int a5 = (0,0,0); + [1]int a6 = (0); + [3]int a7 = (1,1,1); + [3]int a8 = (-1,-1,-1); + [4]int a9 = (-1,-2,0,3); + [1]int a10 = (-1); + lincomb(a1); lincomb(a2); lincomb(a3); lincomb(a4); + lincomb(a5); lincomb(a6); lincomb(a7); lincomb(a8); + lincomb(a9); lincomb(a10) +corp diff --git a/Task/Display-a-linear-combination/GW-BASIC/display-a-linear-combination.basic b/Task/Display-a-linear-combination/GW-BASIC/display-a-linear-combination.basic new file mode 100644 index 0000000000..f877d660ac --- /dev/null +++ b/Task/Display-a-linear-combination/GW-BASIC/display-a-linear-combination.basic @@ -0,0 +1,24 @@ +100 DIM SKLS(10, 4) +110 SKLS(1, 1) = 1: SKLS(1, 2) = 2: SKLS(1, 3) = 3 +120 SKLS(2, 1) = 0: SKLS(2, 2) = 1: SKLS(2, 3) = 2: SKLS(2, 4) = 3 +130 SKLS(3, 1) = 1: SKLS(3, 2) = 0: SKLS(3, 3) = 3: SKLS(3, 4) = 4 +140 SKLS(4, 1) = 1: SKLS(4, 2) = 2: SKLS(4, 3) = 0 +150 SKLS(5, 1) = 0: SKLS(5, 2) = 0: SKLS(5, 3) = 0 +160 SKLS(6, 1) = 0 +170 SKLS(7, 1) = 1: SKLS(7, 2) = 1: SKLS(7, 3) = 1 +180 SKLS(8, 1) = -1: SKLS(8, 2) = -1: SKLS(8, 3) = -1 +190 SKLS(9, 1) = -1: SKLS(9, 2) = -2: SKLS(9, 3) = 0: SKLS(9, 4) = -3 +200 SKLS(10, 1) = -1 +210 CLS +220 FOR N = 1 TO 10 +230 CAD$ = "" +240 SCL = 0 +250 FOR M = 1 TO 4 +260 SCL = SKLS(N, M) +270 IF SCL <> 0 THEN IF SCL = 1 THEN CAD$ = CAD$ + "+e" + STR$(M) ELSE IF SCL = -1 THEN CAD$ = CAD$ + "-e" + STR$(M) ELSE IF SCL > 0 THEN CAD$ = CAD$ + CHR$(43) + STR$(SCL) + "*e" + STR$(M) ELSE CAD$ = CAD$ + STR$(SCL) + "*e" + STR$(M) +280 NEXT M +290 IF CAD$ = "" THEN CAD$ = "0" +300 IF LEFT$(CAD$, 1) = "+" THEN CAD$ = RIGHT$(CAD$, LEN(CAD$) - 1) +310 PRINT CAD$ +320 NEXT N +330 END diff --git a/Task/Display-a-linear-combination/QBasic/display-a-linear-combination.basic b/Task/Display-a-linear-combination/QBasic/display-a-linear-combination.basic new file mode 100644 index 0000000000..f4fec89a91 --- /dev/null +++ b/Task/Display-a-linear-combination/QBasic/display-a-linear-combination.basic @@ -0,0 +1,37 @@ +DIM scalars(1 TO 10, 1 TO 4) +scalars(1, 1) = 1: scalars(1, 2) = 2: scalars(1, 3) = 3 +scalars(2, 1) = 0: scalars(2, 2) = 1: scalars(2, 3) = 2: scalars(2, 4) = 3 +scalars(3, 1) = 1: scalars(3, 2) = 0: scalars(3, 3) = 3: scalars(3, 4) = 4 +scalars(4, 1) = 1: scalars(4, 2) = 2: scalars(4, 3) = 0 +scalars(5, 1) = 0: scalars(5, 2) = 0: scalars(5, 3) = 0 +scalars(6, 1) = 0 +scalars(7, 1) = 1: scalars(7, 2) = 1: scalars(7, 3) = 1 +scalars(8, 1) = -1: scalars(8, 2) = -1: scalars(8, 3) = -1 +scalars(9, 1) = -1: scalars(9, 2) = -2: scalars(9, 3) = 0: scalars(9, 4) = -3 +scalars(10, 1) = -1 + +CLS +FOR n = 1 TO UBOUND(scalars) + cadena$ = "" + scalar = 0 + FOR m = 1 TO UBOUND(scalars, 2) + scalar = scalars(n, m) + IF scalar <> 0 THEN + IF scalar = 1 THEN + cadena$ = cadena$ + "+e" + STR$(m) + ELSEIF scalar = -1 THEN + cadena$ = cadena$ + "-e" + STR$(m) + ELSE + IF scalar > 0 THEN + cadena$ = cadena$ + CHR$(43) + STR$(scalar) + "*e" + STR$(m) + ELSE + cadena$ = cadena$ + STR$(scalar) + "*e" + STR$(m) + END IF + END IF + END IF + NEXT m + IF cadena$ = "" THEN cadena$ = "0" + IF LEFT$(cadena$, 1) = "+" THEN cadena$ = RIGHT$(cadena$, LEN(cadena$) - 1) + PRINT cadena$ +NEXT n +END diff --git a/Task/Display-a-linear-combination/Yabasic/display-a-linear-combination.basic b/Task/Display-a-linear-combination/Yabasic/display-a-linear-combination.basic new file mode 100644 index 0000000000..930d85eff3 --- /dev/null +++ b/Task/Display-a-linear-combination/Yabasic/display-a-linear-combination.basic @@ -0,0 +1,38 @@ +dim scalars(10,4) +scalars(1,1) = 1: scalars(1,2) = 2: scalars(1,3) = 3 +scalars(2,1) = 0: scalars(2,2) = 1: scalars(2,3) = 2: scalars(2,4) = 3 +scalars(3,1) = 1: scalars(3,2) = 0: scalars(3,3) = 3: scalars(3,4) = 4 +scalars(4,1) = 1: scalars(4,2) = 2: scalars(4,3) = 0 +scalars(5,1) = 0: scalars(5,2) = 0: scalars(5,3) = 0 +scalars(6,1) = 0 +scalars(7,1) = 1: scalars(7,2) = 1: scalars(7,3) = 1 +scalars(8,1) = -1: scalars(8,2) = -1: scalars(8,3) = -1 +scalars(9,1) = -1: scalars(9,2) = -2: scalars(9,3) = 0: scalars(9,4) = -3 +scalars(10,1) = -1 + +for n = 1 to arraysize(scalars(),1) + cadena$ = "" + + for m = 1 to arraysize(scalars(),2) + scalar = scalars(n, m) + if scalar <> 0 then + if scalar = 1 then + cadena$ = cadena$ + "+e" + str$(m) + else + if scalar = -1 then + cadena$ = cadena$ + "-e" + str$(m) + else + if scalar > 0 then + cadena$ = cadena$ + chr$(43) + str$(scalar) + "*e" + str$(m) + else + cadena$ = cadena$ + str$(scalar) + "*e" + str$(m) + fi + fi + fi + fi + next m + if cadena$ = "" cadena$ = "0" + if left$(cadena$, 1) = "+" cadena$ = right$(cadena$, len(cadena$)-1) + print cadena$ +next n +end diff --git a/Task/Display-an-outline-as-a-nested-table/Jq/display-an-outline-as-a-nested-table.jq b/Task/Display-an-outline-as-a-nested-table/Jq/display-an-outline-as-a-nested-table.jq new file mode 100644 index 0000000000..2c53129326 --- /dev/null +++ b/Task/Display-an-outline-as-a-nested-table/Jq/display-an-outline-as-a-nested-table.jq @@ -0,0 +1,135 @@ +def NNode($name; $children): {$name, $children}; +def INode($level; $name): {$level, $name}; + +# Input: {iNodes, n} where n is an NNode +# Output: the children of .n are updated +def toNest($start; $level): + if $level == 0 then .n.name = .iNodes[0].name end + | first( foreach (range( $start + 1; .iNodes|length), null) as $i (.; + if $i == null then .emit = true + elif .iNodes[$i].level == $level+1 + then (.n = NNode(.iNodes[$i].name; []) + | toNest($i; $level+1) + | .n) as $n + | .n.children += [$n] + | .emit = false + elif (.iNodes[$i].level <= $level) + then .emit = true + end; + if .emit then . else empty end) ) ; + +def makeIndent($outline; $tab): + (outline|split("\n")) as $lines + | reduce range(0; $lines|length) as $i ([]; + $lines[$i] as $line + | ($line|sub("^ *";"")) as $line2 + | ((($line|length) - ($line2|length)) / $tab | floor) as $level + | . + [INode($level; $line2)] ); + +# Input: NNode +def toMarkup($cols; $depth): + . as $n + | "|-" as $l1 + | "| |" as $l2 + + # input: {span} + | def colSpan($nn): + reduce range(0; $nn.children|length) as $i (.; + if ($i > 0) then .span += 1 end + | colSpan($nn.children[$i] )) + ; # end colSpan + + def nestedFor($nn; $level; $maxLevel; $col): + if $level == 1 and $maxLevel > $level + then reduce range(0; $nn.children|length) as $i (.; + $nn.children[$i] as $c + | nestedFor($c; 2; $maxLevel; $i) ) + elif $level < $maxLevel + then reduce $nn.children[] as $c (.; + nestedFor($c; $level+1; $maxLevel; $col) ) + elif $nn.children|length > 0 + then reduce range(0; $nn.children|length) as $i (.; + $nn.children[$i] as $c + | .span = 1 + | colSpan($c) + | (if $maxLevel == 1 then $i + 1 else $col + 1 end) as $cn + | .lines += ["| style=\"background: \($cols[$cn]) \" colspan=\(.span) | \($c.name)"] ) + else .lines += [$l2] + end + ; # end nestedFor + + reduce $n.children[] as $c (.span = 1; colSpan($c) ) + | .lines = ["{| class=\"wikitable\" style=\"text-align: center;\""] + | .lines += [$l1] + | .span = 1 + | colSpan($n) + | "| style=\"background: \(cols[0]) \" colSpan=\(.span) | \($n.name)" as $s + | .lines += [$s] + | .lines += [$l1] + + | reduce range(1; $depth) as $maxLevel (.; + nestedFor($n; 1; $maxLevel; 0) + | if $maxLevel < $depth-1 then .lines += [$l1] end) + | .lines += ["|}"] + | .lines|join("\n") ; + +def yellow: "#ffffe6;"; +def orange: "#ffebd2;"; +def green: "#f0fff0;"; +def blue: "#e6ffff;"; +def pink: "#ffeeff;"; + +### Examples + +def outline: +"Display an outline as a nested table.\n" + +" Parse the outline to a tree,\n" + +" measuring the indent of each line,\n" + +" translating the indentation to a nested structure,\n" + +" and padding the tree to even depth.\n" + +" count the leaves descending from each node,\n" + +" defining the width of a leaf as 1,\n" + +" and the width of a parent node as a sum.\n" + +" (The sum of the widths of its children) \n" + +" and write out a table with 'colspan' values\n" + +" either as a wiki table,\n" + +" or as HTML."; + + +def cols: [yellow, orange, green, blue, pink]; +def iNodes: makeIndent(outline; 4); +def n: NNode(""; []); + +def outline2: +"Display an outline as a nested table.\n" + +" Parse the outline to a tree,\n" + +" measuring the indent of each line,\n" + +" translating the indentation to a nested structure,\n" + +" and padding the tree to even depth.\n" + +" count the leaves descending from each node,\n" + +" defining the width of a leaf as 1,\n" + +" and the width of a parent node as a sum.\n" + +" (The sum of the widths of its children) \n" + +" Propagating the sums upward as necessary.\n" + +" and write out a table with 'colspan' values\n" + +" either as a wiki table,\n" + +" or as HTML.\n" + +" Optionally add color to the nodes.\n" ; + +def cols2: [blue, yellow, orange, green, pink]; + +def iNodes2: makeIndent(outline2; 4); + +def task1: + { iNodes: iNodes, n: n} + | toNest(0; 0) + | .n + | toMarkup(cols; 4) ; + +def task2: + { iNodes: iNodes2, n: n} + | toNest(0; 0) + | .n + | toMarkup(cols2; 4) ; + +task1, task2 diff --git a/Task/Distribution-of-0-digits-in-factorial-series/Quackery/distribution-of-0-digits-in-factorial-series.quackery b/Task/Distribution-of-0-digits-in-factorial-series/Quackery/distribution-of-0-digits-in-factorial-series.quackery new file mode 100644 index 0000000000..82ac1c78a8 --- /dev/null +++ b/Task/Distribution-of-0-digits-in-factorial-series/Quackery/distribution-of-0-digits-in-factorial-series.quackery @@ -0,0 +1,29 @@ + [ $ "bigrat.qky" loadfile ] now! + + [ stack ] is digits ( --> s ) + [ stack ] is zeroes ( --> s ) + + [ 0 digits put + 0 zeroes put + [ 1 digits tally + 10 /mod 0 = + zeroes tally + dup 0 = until ] + drop + zeroes take + digits take + reduce ] is zeroprop ( n --> n/d ) + + [ dup dip + [ 0 n->v + 1 ] + times + [ i^ 1+ * + dup zeroprop + rot dip v+ ] + drop + rot n->v v/ ] is distribution ( n --> n/d ) + + 100 distribution 10 point$ echo$ cr + 1000 distribution 10 point$ echo$ cr + 10000 distribution 10 point$ echo$ cr diff --git a/Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas b/Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas new file mode 100644 index 0000000000..a97277863b --- /dev/null +++ b/Task/Doubly-linked-list-Definition/PascalABC.NET/doubly-linked-list-definition.pas @@ -0,0 +1,75 @@ +type Node = auto class + data: T; + prev,next: Node; +end; + +type + MyLinkedList = class + first, last: Node; + procedure AddFirst(x: T); + begin + if first = nil then + begin + first := new Node(x,nil,nil); + last := first + end + else + begin + var p := new Node(x,nil,first); + first.prev := p; + first := p; + end; + end; + procedure AddLast(x: T); + begin + if first = nil then + begin + first := new Node(x,nil,nil); + last := first + end + else + begin + var p := new Node(x,last,nil); + last.next := p; + last := p; + end; + end; + procedure AddAfter(p: Node; x: T); + begin + if last = p then + AddLast(x) + else begin + var pp := new Node(x,p,p.next); + p.next := pp; + pp.next.prev := pp; + end + end; + procedure PrintList(); + begin + var p := first; + while p<>nil do + begin + Print(p.data); + p := p.next; + end; + end; + procedure PrintBack(); + begin + var p := last; + while p<>nil do + begin + Print(p.data); + p := p.prev; + end; + end; + end; + +begin + var lst := new MyLinkedList; + lst.AddFirst(2); lst.AddFirst(3); + lst.AddLast(5); + lst.AddAfter(lst.first,555); + lst.PrintList; + Println; + lst.PrintBack; +end. diff --git a/Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas b/Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas new file mode 100644 index 0000000000..41706415b2 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/PascalABC.NET/doubly-linked-list-element-definition.pas @@ -0,0 +1,4 @@ +type Node = auto class + data: T; + prev,next: Node; +end; diff --git a/Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas b/Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas new file mode 100644 index 0000000000..3b2f5422ce --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/PascalABC.NET/doubly-linked-list-element-insertion.pas @@ -0,0 +1,33 @@ +type Node = auto class + data: T; + prev,next: Node; +end; + +type + MyLinkedList = class + first, last: Node; + procedure AddLast(x: T); + begin + if first = nil then + begin + first := new Node(x,nil,nil); + last := first + end + else + begin + var p := new Node(x,last,nil); + last.next := p; + last := p; + end; + end; + procedure AddAfter(p: Node; x: T); + begin + if last = p then + AddLast(x) + else begin + var pp := new Node(x,p,p.next); + p.next := pp; + pp.prev.next := pp; + end + end; + end; diff --git a/Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas b/Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas new file mode 100644 index 0000000000..5e67b3187f --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/PascalABC.NET/doubly-linked-list-traversal.pas @@ -0,0 +1,9 @@ +begin + var lst := new LinkedList(1..10); + var current := lst.First; + while current <> nil do + begin + Print(current.Value); + current := current.Next; + end; +end. diff --git a/Task/Dragon-curve/PascalABC.NET/dragon-curve.pas b/Task/Dragon-curve/PascalABC.NET/dragon-curve.pas new file mode 100644 index 0000000000..7ac53bfab2 --- /dev/null +++ b/Task/Dragon-curve/PascalABC.NET/dragon-curve.pas @@ -0,0 +1,34 @@ +uses Turtle; + +var + Atom,FStr,XStr,YStr: string; + angle,len,x0,y0: real; + n: integer; + +procedure Init1; // Dragon +begin + (Atom,FStr,XStr,YStr) := ('fx','f','x+yf+','-fx-y'); + (angle,len,n,x0,y0) := (90,3,15,300,450); +end; + +procedure RunStr(s: string; n: integer); +begin + foreach var c in s do + case c of + '+': Turn(angle); + '-': Turn(-angle); + 'f','F': if n>0 then RunStr(FStr,n-1) else Forw(len); + 'x','X': if n>0 then RunStr(XStr,n-1); + 'y','Y': if n>0 then RunStr(YStr,n-1); + else Print('error') + end; +end; + +begin + Init1; + ToPoint(x0,y0); + SetWidth(0.5); + Down; + RunStr(Atom,n); + Up; +end. diff --git a/Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 b/Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 new file mode 100644 index 0000000000..bc2a9acaa1 --- /dev/null +++ b/Task/Draw-a-clock/XPL0/draw-a-clock.xpl0 @@ -0,0 +1,48 @@ +include xpllib; \for DrawCircle, DrawLine, LineWidth, MovePen, Deg2Rad +def X0=400, Y0=300; \center coordinate +int Hour, Minute, Second; + +proc DrawHand(Angle, Length, Width, Color); +real Angle, Length; +int Width, Color; +int X, Y; +[X:= fix(Length*Sin(Angle)); + Y:= fix(Length*Cos(Angle)); +LineWidth:= Width; +MovePen(X0, Y0); +DrawLine(X0+X, Y0-Y, Color); +]; + +proc DrawClock; \Show analog clock with current time +real Angle; +int N, X, Y; +[DrawCircle(X0, Y0, 299, LCyan, true); +Angle:= 0.; +for N:= 0 to 59 do \draw tick marks + [X:= fix(260.*Cos(Angle)); + Y:= fix(260.*Sin(Angle)); + DrawCircle(X+X0, Y+Y0, if rem(N/5) then 4 else 8, Black, true); + Angle:= Angle + 6.*Deg2Rad; + ]; +Angle:= float((Hour*60+Minute)/2) * Deg2Rad; +DrawHand(Angle, 210., 8, Black); +Angle:= float((Minute*60+Second)/10) * Deg2Rad; +DrawHand(Angle, 240., 5, Black); +Angle:= float(Second*6) * Deg2Rad; +DrawHand(Angle, 260., 3, LRed); +DrawCircle(X0, Y0, 8, Black, true); +]; + +int Second0; +char Time; +[SetVid($103); \800x600x8 +InitDraw; +repeat Time:= GetDateTime; + Hour:= Time(3); + if Hour>=12 then Hour:= Hour-12; + Minute:= Time(4); + Second:= Time(5); + if Second # Second0 then + [Second0:= Second; DrawClock]; +until KeyHit; +] diff --git a/Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg b/Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg new file mode 100644 index 0000000000..604f0aa481 --- /dev/null +++ b/Task/Draw-a-cuboid/ALGOL-68/draw-a-cuboid.alg @@ -0,0 +1,58 @@ +BEGIN # draw some cuboids using ASCII art # + + # draws a cuboid standing on one edge using ASCII art # + PROC aa cuboid = ( INT h, w, l )VOID: + BEGIN + # top line # + FOR i TO l DO print( ( " " ) ) OD; + FOR i TO w + 1 DO print( ( "_" ) ) OD; + print( ( newline ) ); + # rest of the top face and part of the visible side # + INT face width := 0; + INT edge pos := 0; + FOR i TO l DO + FOR j TO l - i DO print( ( " " ) ) OD; + print( ( "/" ) ); + FOR j TO w DO print( ( IF i = l THEN "_" ELSE " " FI ) ) OD; + print( ( "/" ) ); + edge pos +:= 1; + IF edge pos <= h THEN + # drsw the back edge # + face width := 2 * ( edge pos - 1 ); + FOR j TO face width DO print( ( " " ) ) OD; + print( ( "\" ) ) + ELSE + # draw the bottom edge # + FOR j TO face width + 1 DO print( ( " " ) ) OD; + print( ( "/" ) ) + FI; + print( ( newline ) ) + OD; + # other vidible face # + FOR i TO h DO + FOR j TO i - 1 DO print( ( " " ) ) OD; + print( ( "\" ) ); + FOR j TO w DO print( ( IF i = h THEN "_" ELSE " " FI ) ) OD; + print( ( "\" ) ); + edge pos +:= 1; + IF edge pos <= h THEN + # drsw the back edge # + FOR j TO face width + 1 DO print( ( " " ) ) OD; + print( ( "\" ) ) + ELSE + # draw the bottom edge # + FOR j TO face width DO print( ( " " ) ) OD; + face width -:= 2; + print( ( "/" ) ) + FI; + print( ( newline ) ) + OD + + END # aa cuboid # ; + + aa cuboid( 3, 2, 4 ); + aa cuboid( 4, 3, 2 ); + aa cuboid( 2, 4, 3 ); + aa cuboid( 2, 3, 4 ) + +END diff --git a/Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq b/Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq new file mode 100644 index 0000000000..6f59cbd05c --- /dev/null +++ b/Task/Draw-a-cuboid/Jq/draw-a-cuboid.jq @@ -0,0 +1,27 @@ +def cubLine($n; $dx; $dy; $cde): + def s: if . == 0 then "" else . * " " end; # for jaq + reduce range(1; 9*$dx) as $d ("\($n|s)\($cde[0:1])"; + . + $cde[1:2] ) + + $cde[0:1] + + ("\($dy|s)\($cde[2:])"); + +def cuboid($dx; $dy; $dz): + "cuboid \($dx) \($dy) \($dz):", + # top + cubLine($dy+1; $dx; 0; "+-"), + # top and side + (range(1; 1+$dy) as $i | cubLine($dy-$i+1; $dx; $i-1; "/ |")), + cubLine(0; $dx; $dy; "+-|"), + # front and side + (range(1; 4*$dz -$dy-2) as $i | cubLine(0; $dx; $dy; "| |")), + cubLine(0; $dx; $dy; "| +"), + # front and bottom + (range(1; 1+$dy) as $i | cubLine(0; $dx; $dy-$i; "| /")), + # bottom + cubLine(0; $dx; 0; "+-\n"); + +cuboid(2; 3; 4), +"", +cuboid(1; 1; 1), +"", +cuboid(6; 2; 1) diff --git a/Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic b/Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic new file mode 100644 index 0000000000..c7b41f6d6b --- /dev/null +++ b/Task/Draw-a-cuboid/Locomotive-Basic/draw-a-cuboid.basic @@ -0,0 +1,6 @@ +10 mode 2: origin 100,0: w=120: height=w*1.5: depth=w*2 +20 x=80: y=10 +30 plot x,y +40 drawr 0,height: drawr w,0: drawr 0,-height: drawr -w,0: rem front +50 plot x,y+height: drawr depth/2,height: drawr w,0: drawr 0,-height: drawr -w,-height +60 plot x+w,y+height: drawr depth/2,height diff --git a/Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm b/Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm new file mode 100644 index 0000000000..09220af2ea --- /dev/null +++ b/Task/Draw-a-cuboid/PL-M/draw-a-cuboid.plm @@ -0,0 +1,81 @@ +100H: /* DRAW SOME CUBOIDS USING ASCII ART */ + + /* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */ + BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; + PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; + PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END; + + /* TASK */ + + /* DRAWS A CUBOID STANDING ON ONE EDGE USING ASCII ART */ + DRAW$CUBOID: PROCEDURE( H, W, L ); + DECLARE ( H, W, L ) BYTE; + DECLARE ( I, J, FACE$WIDTH, EDGE$POS ) BYTE; + + BACKSLASH: PROCEDURE; CALL PR$CHAR( 92 ); END; /* PRINTS A BACKSLASH */ + REPEAT$CHAR: PROCEDURE( CH, COUNT ); /* PRINTS CH COUNT TIMES */ + DECLARE ( CH, COUNT ) BYTE; + DECLARE I BYTE; + IF COUNT > 0 THEN DO; + DO I = 1 TO COUNT; CALL PR$CHAR( CH ); END; + END; + END REPEAT$CHAR; + UNDERSCORES: PROCEDURE( COUNT ); /* PRINTS COUNT UNDERSCORES */ + DECLARE COUNT BYTE; + CALL REPEAT$CHAR( 95, COUNT ); + END UNDERSCORES; + + /* TOP LINE */ + CALL REPEAT$CHAR( ' ', L ); CALL UNDERSCORES( W + 1 ); CALL PR$NL; + /* REST OF THE TOP FACE AND PART OF THE VISIBLE SIDE */ + FACE$WIDTH = 0; + EDGE$POS = 0; + DO I = 1 TO L; + CALL REPEAT$CHAR( ' ', L - I ); + CALL PR$CHAR( '/' ); + IF I = L THEN CALL UNDERSCORES( W ); + ELSE CALL REPEAT$CHAR( ' ', W ); + CALL PR$CHAR( '/' ); + EDGE$POS = EDGE$POS + 1; + IF EDGE$POS <= H THEN DO; + /* DRAW THE BACK EDGE */ + FACE$WIDTH = 2 * ( EDGE$POS - 1 ); + CALL REPEAT$CHAR( ' ', FACE$WIDTH ); + CALL BACKSLASH; + END; + ELSE DO; + /* DRAW THE BOTTOM EDGE AND THE MORE OF THE VISIBLE SIDE */ + CALL REPEAT$CHAR( ' ', FACE$WIDTH + 1 ); + CALL PR$CHAR( '/' ); + END; + CALL PR$NL; + END; + /* OTHER VISIBLE FACE */ + DO I = 1 TO H; + CALL REPEAT$CHAR( ' ', I - 1 ); + CALL BACKSLASH; + IF I = H THEN CALL UNDERSCORES( W ); + ELSE CALL REPEAT$CHAR( ' ', W ); + CALL BACKSLASH; + EDGE$POS = EDGE$POS + 1; + IF EDGE$POS <= H THEN DO; + /* DRAW THE BACK EDGE */ + CALL REPEAT$CHAR( ' ', FACE$WIDTH + 1 ); + CALL BACKSLASH; + END; + ELSE DO; + /* DRAW THE BOTTOM EDGE */ + CALL REPEAT$CHAR( ' ', FACE$WIDTH ); + FACE$WIDTH = FACE$WIDTH - 2; + CALL PR$CHAR( '/' ); + END; + CALL PR$NL; + END; + END DRAW$CUBOID; + + CALL DRAW$CUBOID( 3, 2, 4 ); + CALL DRAW$CUBOID( 4, 3, 2 ); + CALL DRAW$CUBOID( 2, 4, 3 ); + CALL DRAW$CUBOID( 2, 3, 4 ); + +EOF diff --git a/Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas b/Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas new file mode 100644 index 0000000000..caaee3cf72 --- /dev/null +++ b/Task/Draw-a-pixel/PascalABC.NET/draw-a-pixel.pas @@ -0,0 +1,6 @@ +uses GraphWPF; + +begin + Window.SetSize(320,240); + SetPixel(100,100,Colors.Red); +end. diff --git a/Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas b/Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas new file mode 100644 index 0000000000..37d716f15c --- /dev/null +++ b/Task/Draw-a-rotating-cube/PascalABC.NET/draw-a-rotating-cube.pas @@ -0,0 +1,6 @@ +uses Graph3D; + +begin + var Cube := Box(Origin,Sz3D(3,3,3),Colors.Green); + Cube.AnimRotate(OrtZ,180).Forever.Begin +end. diff --git a/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere.basic b/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-1.basic similarity index 100% rename from Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere.basic rename to Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-1.basic diff --git a/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic b/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic new file mode 100644 index 0000000000..c343edc95d --- /dev/null +++ b/Task/Draw-a-sphere/Locomotive-Basic/draw-a-sphere-2.basic @@ -0,0 +1,32 @@ +10 MODE 2:ORIGIN 320,200:INK 0,0:INK 1,26 +20 DIM v(2),vec(2) +30 v(0)=30:v(1)=30:v(2)=-50 +40 lung=SQR(v(0)*v(0)+v(1)*v(1)+v(2)*v(2)) +50 v(0)=v(0)/lung +60 v(1)=v(1)/lung +70 v(2)=v(2)/lung +80 r=180:k=1.5:ambient=0.03 +90 FOR i=INT(-r) TO INT(r) +100 x=i +110 FOR j=INT(-2*r) TO INT(2*r) +120 y=j/2 +130 IF (x*x+y*y<=r*r) THEN GOSUB 1000 +140 NEXT j +160 NEXT i +170 END +1000 vec(0)=x +1010 vec(1)=y +1020 vec(2)=SQR(r*r-x*x-y*y) +1030 GOSUB 2000 +1040 GOSUB 3000 +1050 b=(d^k+ambient)/(1+ambient) +1060 IF b>rnd THEN PLOT x,-y +1100 RETURN +2000 lung=SQR(vec(0)*vec(0)+vec(1)*vec(1)+vec(2)*vec(2)) +2010 vec(0)=vec(0)/lung +2020 vec(1)=vec(1)/lung +2030 vec(2)=vec(2)/lung +2040 RETURN +3000 d=v(0)*vec(0)+v(1)*vec(1)+v(2)*vec(2) +3010 IF d<0 THEN d=-d ELSE d=0 +3020 RETURN diff --git a/Task/Dutch-national-flag-problem/Quackery/dutch-national-flag-problem.quackery b/Task/Dutch-national-flag-problem/Quackery/dutch-national-flag-problem.quackery new file mode 100644 index 0000000000..288a537074 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Quackery/dutch-national-flag-problem.quackery @@ -0,0 +1,16 @@ + [ 1 ] is red ( --> n ) + [ 2 ] is white ( --> n ) + [ 3 ] is blue ( --> n ) + + randomise + + [] ' [ red white blue ] + witheach + [ nested swap + 5 random times [ over join ] + swap join ] + + dup [ shuffle 2dup != until ] nip + + say "Before sorting: " dup echo cr + say " After sorting: " sortwith [ dip do do > ] echo cr diff --git a/Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua b/Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua new file mode 100644 index 0000000000..354f52209c --- /dev/null +++ b/Task/Dutch-national-flag-problem/Uiua/dutch-national-flag-problem.uiua @@ -0,0 +1,3 @@ +&p.[⍥(⊡⌊×3⚂"RWB")30] # Build it. +&p.⊏▽⊸>2⍏⊛.⊂"RWB" # Sort it, providing model for sort order. +&p⨬("oops"|"good")≍⊏⊸⍏.⊛ # Confirm it's sorted. diff --git a/Task/Eertree/11l/eertree.11l b/Task/Eertree/11l/eertree.11l index cbb87d6fd0..9cf90c9c9a 100644 --- a/Task/Eertree/11l/eertree.11l +++ b/Task/Eertree/11l/eertree.11l @@ -48,7 +48,7 @@ F eertree(s) F subPalindromes(tree) [String] s - F children(Int n, String =p) -> N + F children(Int n, String =p) -> Void L(c, n) @tree[n].edges p = c‘’p‘’c @s [+]= p diff --git a/Task/Egyptian-division/Zig/egyptian-division.zig b/Task/Egyptian-division/Zig/egyptian-division.zig new file mode 100644 index 0000000000..b6eed56815 --- /dev/null +++ b/Task/Egyptian-division/Zig/egyptian-division.zig @@ -0,0 +1,52 @@ +const std = @import("std"); + +pub fn egyptianDivision(dividend: u64, divisor: u64) [2]u64 { + const SIZE = 64; + var powers = [_]u64{0} ** SIZE; + var doublings = [_]u64{0} ** SIZE; + + var i: u64 = 0; + + while (i < SIZE) { + powers[i] = std.math.shl(u64, 1, i); + doublings[i] = std.math.shl(u64, divisor, i); + if (doublings[i] > dividend) { + break; + } + i += 1; + } + + var accumulator: u64 = 0; + var answer: u64 = 0; + i -= 1; + while (i >= 0) { + if (accumulator + doublings[i] <= dividend) { + accumulator += doublings[i]; + answer += powers[i]; + } + if (i > 0) { + i -= 1; + } else { + break; + } + } + var remainder = dividend - accumulator; + return .{ answer, remainder }; +} + +test "Expect 10, 0 from egyptianDivision(20, 2)" { + var output = egyptianDivision(20, 2); + try std.testing.expect(output[0] == 10); + try std.testing.expect(output[1] == 0); +} + +test "Expect 580 divided by 34 is 17 and the remainder is 2" { + var output = egyptianDivision(580, 34); + try std.testing.expect(output[0] == 17); + try std.testing.expect(output[1] == 2); +} + +pub fn main() !void { + var result = egyptianDivision(20, 2); + std.debug.print("20 divided by 2 is {} with remainder {}\n", .{ result[0], result[1] }); +} diff --git a/Task/Empty-program/PascalABC.NET/empty-program.pas b/Task/Empty-program/PascalABC.NET/empty-program.pas new file mode 100644 index 0000000000..ba38a01c6c --- /dev/null +++ b/Task/Empty-program/PascalABC.NET/empty-program.pas @@ -0,0 +1 @@ +## diff --git a/Task/Entropy-Narcissist/Jq/entropy-narcissist.jq b/Task/Entropy-Narcissist/Jq/entropy-narcissist.jq new file mode 100644 index 0000000000..882d3833c9 --- /dev/null +++ b/Task/Entropy-Narcissist/Jq/entropy-narcissist.jq @@ -0,0 +1,11 @@ +def chars: explode[] | [.] | implode; + +def bow(stream): + reduce stream as $word ({}; .[($word|tostring)] += 1); + +def sum(s): reduce s as $x (0; .+$x); + +length as $l +| bow(chars) +| sum(keys[] as $k | .[$k] as $c | $c * ($c|log2) ) +| ($l|log2) - ./$l diff --git a/Task/Enumerations/PascalABC.NET/enumerations.pas b/Task/Enumerations/PascalABC.NET/enumerations.pas new file mode 100644 index 0000000000..5a84af8534 --- /dev/null +++ b/Task/Enumerations/PascalABC.NET/enumerations.pas @@ -0,0 +1,6 @@ +type MyEnum = (One, Two = 2, Three = 3); + +begin + var my: MyEnum := One; + Print(my); +end. diff --git a/Task/Environment-variables/Langur/environment-variables-1.langur b/Task/Environment-variables/Langur/environment-variables-1.langur deleted file mode 100644 index 6491b51cb7..0000000000 --- a/Task/Environment-variables/Langur/environment-variables-1.langur +++ /dev/null @@ -1,3 +0,0 @@ -writeln "HOME: ", _env["HOME"] -writeln "PATH: ", _env["PATH"] -writeln "USER: ", _env["USER"] diff --git a/Task/Environment-variables/Langur/environment-variables-2.langur b/Task/Environment-variables/Langur/environment-variables.langur similarity index 100% rename from Task/Environment-variables/Langur/environment-variables-2.langur rename to Task/Environment-variables/Langur/environment-variables.langur diff --git a/Task/Esthetic-numbers/11l/esthetic-numbers.11l b/Task/Esthetic-numbers/11l/esthetic-numbers.11l index 63303794c8..27c380b3dc 100644 --- a/Task/Esthetic-numbers/11l/esthetic-numbers.11l +++ b/Task/Esthetic-numbers/11l/esthetic-numbers.11l @@ -13,7 +13,7 @@ F isEsthetic(=n, b) F listEsths(Int64 n1, n2, m1, m2; perLine, all) [Int64] esths - F dfs(Int64 n, m, i) -> N + F dfs(Int64 n, m, i) -> Void I i C n .. m @esths.append(i) I i == 0 | i > m {R} diff --git a/Task/Euler-method/XBasic/euler-method.basic b/Task/Euler-method/XBasic/euler-method.basic new file mode 100644 index 0000000000..25778eeb35 --- /dev/null +++ b/Task/Euler-method/XBasic/euler-method.basic @@ -0,0 +1,43 @@ +PROGRAM "Euclidean rhythm" +VERSION "0.0001" +IMPORT "xma" + +DECLARE FUNCTION Entry () +DECLARE FUNCTION Euler (paso) + +FUNCTION Entry () + PRINT "Time "; + tiempo! = 0.0 + DO WHILE tiempo! <= 100.1 + PRINT FORMAT$ ("#######", tiempo!); + tiempo! = tiempo! + 10.0 + LOOP + PRINT + + PRINT "Dif eq "; + tiempo! = 0.0 + DO WHILE tiempo! <= 100.1 + temperatura! = 20.0 + (100.0 - 20.0) * EXP(-0.07 * tiempo!) + PRINT FORMAT$ ("####.##", temperatura!); + tiempo! = tiempo! + 10.0 + LOOP + PRINT + + Euler(2) + Euler(5) + Euler(10) +END FUNCTION + +FUNCTION Euler (paso) + tiempo! = 0 + temperatura! = 100.0 + PRINT FORMAT$ ("Step ## ", paso); + + DO WHILE tiempo! <= 100 + IF (tiempo! MOD 10) = 0 THEN PRINT FORMAT$ ("####.##", temperatura!); + temperatura! = temperatura! + SINGLE(paso) * (-0.07 * (temperatura! - 20.0)) + tiempo! = tiempo! + paso + LOOP + PRINT +END FUNCTION +END PROGRAM diff --git a/Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg b/Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg new file mode 100644 index 0000000000..4b49f4d0c2 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../ALGOL-W/eulers-constant-0.5772....alg @@ -0,0 +1,89 @@ +begin % calculate Euler's constant, translated from the XPL0 sample % + % which is translated from the C sample % + + long real A, B, H, N2, R, U, V; + long real array S ( 0 :: 1 ); + long real array B2( 0 :: 9 ); + long real Epsilon; + integer K, K2, M, N; + + Epsilon := 1'-6; + + % set output format % + i_w := 1; s_w := 0; r_w := 18; r_d := 15; r_format := "A"; + + write( "From the definition, error 3e-10" ); + N := 400; H := 1.0; + for K1 := 2 until N do H := H + 1.0 / K1; + comment Faster convergence: Negoi, 1997 ; + A := Ln( N + 0.5 + 1.0/( 24.0 * N ) ); + write( "Hn ", H ); + write( "gamma ", H - A ); write( "K = ", N ); write(); + + write( "Sweeney, 1963, error 3e-10" ); + N := 21; S( 0 ) := 0; S( 1 ) := N; + R := N; K:= 1; + while begin K := K + 1; + R := R * N / K; + S( K rem 2 ) := S( K rem 2 ) + R / K; + R > Epsilon + end + do begin end; + write( "gamma ", S( 1 ) - S( 0 ) - ln( N ) );write( "K = ", K ); write(); + + write( "Bailey, 1988" ); + N := 5; A := 1; H := 1; + N2 := 2 ** N; + R := 1; K := 1; + while begin K := K + 1; + R := R * N2 / K; + H := H + 1 / K; + B := A; A := A + R * H; + abs( B - A ) > Epsilon + end + do begin end; + A := A * N2 / Exp(N2); + write( "gamma ", A - N * Ln( 2 ) ); write( "K = ", K ); write(); + + write( "Brent-McMillan, 1980" ); + N := 13; A := -Ln( N ); + B := 1; U := A; V := B; + N2 := N * N; K2 := 0; K := 0; + while begin K2 := K2 + 2 * K + 1; + K := K + 1; + A := A * N2 / K; + B := B * N2 / K2; + A := ( A + B ) / K; + U := U + A; + V := V + B; + abs( A ) > Epsilon + end + do begin end; + write( "gamma ", U / V ); write( "K = ", K ); write(); + + write( "How Euler did it in 1735" ); + comment Bernoulli numbers with even indices; + + B2( 0 ) := 1; B2( 1 ) := 1 / 6; B2( 2 ) := -1 / 30; + B2( 3 ) := 1 / 42; B2( 4 ) := -1 / 30; B2( 5 ) := 5 / 66; + B2( 6 ) := -691 / 2730; B2( 7 ) := 7 / 6; B2( 8 ) := -3617 / 510; + B2( 9 ) := 43867 / 98; + M := 7; N := 10; + comment Nth harmonic number; + H := 1; + for K1 := 2 until N do H := H + 1 / K1; + write( "Hn ", H ); + H := H - Ln( N ); + write( " -ln ", H ); + comment Expansion C:= -digamma(1); + A := -1 / ( 2 * N ); + N2 := N * N; + R := 1; + for K1 := 1 until M do begin + R := R * N2; + A := A + B2( K1 ) / (2 * K1 * R ) + end for_K1; + write( "err ", A ); write( "gamma ", H + A ); write( "K = ", N + M ); + write(); + write( "C = 0.57721566490153286..." ); write() +end. diff --git a/Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....ada b/Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....ada new file mode 100644 index 0000000000..b27ada83d7 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....ada @@ -0,0 +1,47 @@ +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Long_Elementary_Functions; use Ada.Numerics.Long_Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Eulers_Constant is + + function Euler_Vacca (Iterations : Integer) return Long_Float is + Gamma : Long_Float := 1.0; + Term : Long_Float; + Power : Long_Integer; + Sign : Long_Float; + begin + Gamma := 0.5 - (1.0 / 3.0); + for I in 2 .. Iterations loop + Power := 2 ** Natural (I); + Sign := -1.0; + Term := 0.0; + for Domin in Power .. (2 * Power - 1) loop + Sign := - (Sign); + Term := Term + Sign / Long_Float (Domin); + end loop; + Gamma := Gamma + (Long_Float (I) * Term); + end loop; + return Gamma; + end Euler_Vacca; + + -- Ada Float type is IEEE 754 32-bit, giving 9 decimal digits of precision + Euler_Castellanos_Float : constant Float := + (((80.0 ** 3) + 92.0) / + (61.0 ** 4)) ** (1.0 / 6.0); + + -- Ada Long_Float type is IEEE 754 32-bit, giving 14 decimal digits of precision + Euler_Castellanos_Long_Float : constant Long_Float := + (990.0 ** 3 - 55.0 ** 3 - 79.0 ** 2 - 16.0) / + 70.0 ** 5; + + Iters : Integer; +begin + Put_Line ("Its. Vacca"); + Iters := 2; + while Iters <= 32 loop + Put_Line (Iters'Image & " " & Euler_Vacca (Iters)'Image); + Iters := Iters + 2; + end loop; + Put_Line ("Castellanos approximation for standard Float (9 digits): " & Euler_Castellanos_Float'Image); + Put_Line ("Castellanos approximation for Long Float (14 digits): " & Euler_Castellanos_Long_Float'Image); +end Eulers_Constant; diff --git a/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx b/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx new file mode 100644 index 0000000000..6a6280da94 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx @@ -0,0 +1,272 @@ +arg n; if n = '' then n = 100; numeric digits n +parse version version; say version; glob. = '' +say 'Euler-Mascheroni constant to' n 'decimal places' +say 'Method Brent-McMillan' +say +call time('r'); a = Brent(); e = format(time('e'),,3) +say 'Brent ' a '('e 'seconds)' +call time('r'); a = TrueValue(); e = format(time('e'),,3) +say 'True value' a '('e 'seconds)' +exit + +Brent: +procedure expose glob. +numeric digits Digits()+2 +-- Brent McMillan +n = Ceil((Digits()*Ln(10)+Ln(Pi()))*0.25); m = Ceil(2.07*Digits()) +n2 = n*n; ak = -Ln(n); bk = 1; s = ak; v = 1 +do k = 1 to m + bk = bk*n2/(k*k); ak = (ak*n2/k+bk)/k + s = s+ak; v = v+bk +end +y = s/v +numeric digits Digits()-2 +return y+0 + +TrueValue: +procedure expose glob. +return 0.5772156649015328606065120900824024310421593359399235988057672348848677267776646709369470632917467495+0 + +E: +-- Euler number +procedure expose glob. +p = Digits() +-- In memory? +if glob.e.p <> '' then + return glob.e.p +if p < 101 then +-- Fast value + glob.e.p = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516643+0 +else do + numeric digits Digits()+2 +-- Taylor + y = 2; t = 1; v = y + do n = 2 + t = t/n; y = y+t + if y = v then + leave + v = y + end + numeric digits Digits()-2 + glob.e.p = y+0 +end +return glob.e.p + +Fact: +-- Factorial n! +procedure expose glob. +arg x +-- Validity +if \ Whole(x) then + return 'X' +if x < 0 then + return 'X' +-- Current in memory? +if glob.fact.x <> '' then + return glob.fact.x +w = x-1 +-- Previous in memory? +if glob.fact.w = '' then do +-- Loop cf definition + y = 1 + do n = 2 to x + y = y*n + end + glob.fact.x = y +end +else +-- Multiply + glob.fact.x = glob.fact.w*x +return glob.fact.x + +Ln2: +-- Natural log of 2 constant +procedure expose glob. +-- Fast value +y = 0.6931471805599453094172321214581765680755001343602552541206800094933936219696947156058633269964186875 +return y+0 + +Ln4: +-- Natural log of 4 constant +procedure expose glob. +-- Fast value +y = 1.386294361119890618834464242916353136151000268720510508241360018986787243939389431211726653992837375 +return y+0 + +Ln8: +-- Natural log of 8 constant +procedure expose glob. +-- Fast value +y = 2.079441541679835928251696364374529704226500403080765762362040028480180865909084146817589980989256063 +return y+0 + +Ln10: +-- Natural log of 10 constant +procedure expose glob. +-- Fast value +y = 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959830 +return y+0 + +Pi: +-- Pi constant +procedure expose glob. +p = Digits() +-- In memory? +if glob.pi.p <> '' then + return glob.pi.p +if p < 101 then +-- Fast value + glob.pi.p = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707+0 +else do + numeric digits Digits()+2 + if p < 201 then do +-- Chudnovsky + y = 0 + do n = 0 + v = y; y = y + Fact(6*n)*(13591409+545140134*n)/(Fact(3*n)*Fact(n)**3*-640320**(3*n)) + if y = v then + leave + end + y = 4270934400/(Sqrt(10005)*y) + end + else do +-- Agmean + y = 0.25; a = 1; g = Sqrt(0.5); n = 1 + do until a = v + v = a + x = (a+g)*0.5; g = Sqrt(a*g) + y = y-n*(x-a)**2; n = n+n; a = x + end + y = a*a/y + end + numeric digits Digits()-2 + glob.pi.p = y+0 +end +return glob.pi.p + +Ceil: +-- Ceiling +procedure expose glob. +arg x +-- Formulas +if Whole(x) then + return x +else + return Trunc(x)+(x>=0) + +Ln: +-- Natural logarithm base e +procedure expose glob. +arg x +-- Validity +if x <= 0 then + return 'X' +-- Fast values +if x = 1 then + return 0 +p = Digits() +-- In memory? +if glob.ln.x.p <> '' then + return glob.ln.x.p +-- Precalculated values +if x = 2 & p < 101 then do + glob.ln.x.p = Ln2() + return glob.ln.x.p +end +if x = 4 & p < 101 then do + glob.ln.x.p = Ln4() + return glob.ln.x.p +end +if x = 8 & p < 101 then do + glob.ln.x.p = Ln8() + return glob.ln.x.p +end +if x = 10 & p < 101 then do + glob.ln.x.p = Ln10() + return glob.ln.x.p +end +numeric digits p+2 +-- Argument reduction +z = x; i = 0; e = 1/E() +if z < 0.5 then do + y = 1/z + do while y > 1.5 + y = y*e; i = i-1 + end + z = 1/y +end +if z > 1.5 then do + do while z > 1.5 + z = z*e; i = i+1 + end +end +-- Taylor series +q = (z-1)/(z+1); f = q; y = q; v = q; q = q*q +do n = 3 by 2 + f = f*q; y = y+f/n + if y = v then + leave + v = y +end +numeric digits p +-- Inverse reduction +glob.ln.x.p = 2*y+i +return glob.ln.x.p + +Sqrt: +-- Square root x^(1/2) +procedure expose glob. +arg x +-- Validity +if x < 0 then + return 'X' +-- Fast values +if x = 0 then + return 0 +if x = 1 then + return 1 +p = Digits() +-- Predefined values +if x = 2 & p < 101 then + return Sqrt2() +if x = 3 & p < 101 then + return Sqrt3() +if x = 5 & p < 101 then + return Sqrt5() +numeric digits p+2 +-- Argument reduction to [0,100) +i = Xpon(x); i = (i-(i<0))%2; x = x/100**i +-- First guess 1 digit accurate +t = '2.5 6.5 12.5 20.5 30.5 42.5 56.5 72.5 90.5 100' +do y = 1 until word(t,y) > x +end +-- Dynamic precision +d = Digits() +do n = 1 while d > 2 + d.n = d; d = d%2+1 +end +d.n = 2 +-- Method Heron +do k = n to 1 by -1 + numeric digits d.k + y = (y+x/y)*0.5 +end +numeric digits p +return y*10**i + +Whole: +-- Is a number integer? +procedure expose glob. +arg x +-- Formula +return Datatype(x,'w') + +Xpon: +-- Exponent +procedure expose glob. +arg x +-- Formula +if x = 0 then + return 0 +else + return Right(x*1E+99999,6)-99999 diff --git a/Task/Even-or-odd/PascalABC.NET/even-or-odd.pas b/Task/Even-or-odd/PascalABC.NET/even-or-odd.pas new file mode 100644 index 0000000000..d3cc8e5417 --- /dev/null +++ b/Task/Even-or-odd/PascalABC.NET/even-or-odd.pas @@ -0,0 +1,14 @@ +function IsOddRemainder(x: integer) := x mod 2 <> 0; + +function IsEvenRemainder(x: integer) := x mod 2 = 0; + +function IsOddBitwise(x: integer) := x and 1 = 1; + +function IsEvenBitwise(x: integer) := x and 1 = 0; + +begin + var x := 3; + Println(x.IsEven,x.IsOdd); // Standard Predicates + Println(IsEvenRemainder(x),IsOddRemainder(x)); + Println(IsEvenBitwise(x),IsOddBitwise(x)); +end. diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur index 0094318f1c..e376e53714 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur @@ -1,15 +1,15 @@ -val .U0 = h{"msg": "U0"} -val .U1 = h{"msg": "U1"} +val U0 = {"msg": "U0"} +val U1 = {"msg": "U1"} -val .baz = fn(.i) throw if(.i==0: .U0; .U1) -val .bar = fn(.i) .baz(.i) +val baz = fn i: throw if(i==0: U0; U1) +val bar = fn i: baz(i) -val .foo = impure fn() { - for .i in [0, 1] { - .bar(.i) +val foo = impure fn() { + for i in [0, 1] { + bar(i) catch { - if _err'msg == .U0'msg { - writeln "caught .U0 in .foo()" + if _err'msg == U0'msg { + writeln "caught U0 in foo()" } else { throw } @@ -17,4 +17,4 @@ val .foo = impure fn() { } } -.foo() +foo() diff --git a/Task/Exceptions/Langur/exceptions-1.langur b/Task/Exceptions/Langur/exceptions-1.langur index a61a70b482..d9858c6b98 100644 --- a/Task/Exceptions/Langur/exceptions-1.langur +++ b/Task/Exceptions/Langur/exceptions-1.langur @@ -1,7 +1,7 @@ throw "not a math exception" -catch[.e] { - if .e'cat == "math" { +catch[e] { + if e'cat == "math" { # change result... } else { # rethrow the exception diff --git a/Task/Exceptions/Langur/exceptions-3.langur b/Task/Exceptions/Langur/exceptions-3.langur index e3e28e19f6..8a26842677 100644 --- a/Task/Exceptions/Langur/exceptions-3.langur +++ b/Task/Exceptions/Langur/exceptions-3.langur @@ -1,3 +1,3 @@ -val .safediv = fn(.x, .y) { .x / .y ; catch : 0 } -.safediv(7, 7) # 1 -.safediv(7, 0) # 0 +val safediv = fn(x, y) { x / y ; catch : 0 } +safediv(7, 7) # 1 +safediv(7, 0) # 0 diff --git a/Task/Exceptions/PascalABC.NET/exceptions-1.pas b/Task/Exceptions/PascalABC.NET/exceptions-1.pas new file mode 100644 index 0000000000..3234ceef1c --- /dev/null +++ b/Task/Exceptions/PascalABC.NET/exceptions-1.pas @@ -0,0 +1 @@ +type MyException = class(Exception) end; diff --git a/Task/Exceptions/PascalABC.NET/exceptions-2.pas b/Task/Exceptions/PascalABC.NET/exceptions-2.pas new file mode 100644 index 0000000000..d48f94c6ed --- /dev/null +++ b/Task/Exceptions/PascalABC.NET/exceptions-2.pas @@ -0,0 +1 @@ +raise new MyException; diff --git a/Task/Exceptions/PascalABC.NET/exceptions-3.pas b/Task/Exceptions/PascalABC.NET/exceptions-3.pas new file mode 100644 index 0000000000..15454868bd --- /dev/null +++ b/Task/Exceptions/PascalABC.NET/exceptions-3.pas @@ -0,0 +1,6 @@ +try + ... +except + on e: MyException do + statement +end; diff --git a/Task/Execute-Computer-Zero/FreeBASIC/execute-computer-zero.basic b/Task/Execute-Computer-Zero/FreeBASIC/execute-computer-zero.basic new file mode 100644 index 0000000000..ba59ec50ab --- /dev/null +++ b/Task/Execute-Computer-Zero/FreeBASIC/execute-computer-zero.basic @@ -0,0 +1,120 @@ +' Define the opcodes +Enum + NOP = 0 + LDA + STA + ADD + SUV + BRZ + JMP + STP +End Enum + +Function instr_(op As Ubyte, v As Ubyte) As Ubyte + Return (32 * op) + v +End Function + +Function NOP_(v As Ubyte) As Ubyte + Return instr_(NOP, v) +End Function + +Function LDA_(v As Ubyte) As Ubyte + Return instr_(LDA, v) +End Function + +Function STA_(v As Ubyte) As Ubyte + Return instr_(STA, v) +End Function + +Function ADD_(v As Ubyte) As Ubyte + Return instr_(ADD, v) +End Function + +Function SUB_(v As Ubyte) As Ubyte + Return instr_(SUV, v) +End Function + +Function BRZ_(v As Ubyte) As Ubyte + Return instr_(BRZ, v) +End Function + +Function JMP_(v As Ubyte) As Ubyte + Return instr_(JMP, v) +End Function + +Function STP_(v As Ubyte) As Ubyte + Return instr_(STP, v) +End Function + +Sub execute(nombre As String, program() As Ubyte) + ' Initialize memory and program counter + Dim As Ubyte m(Ubound(program)) + Dim As Short m_pos = -1 + + For i As Ubyte = Lbound(program) To Ubound(program) + m(m_pos + 1) = program(i) + m_pos += 1 + Next + + Dim As Boolean running = True + Dim As Ubyte pc = 0 + Dim As Ubyte a = 0 + Dim As Ubyte op + Dim As Ubyte operand + + While running + op = m(pc) \ 32 + operand = m(pc) Mod 32 + pc = (pc + 1) Mod 32 + + Select Case op + Case NOP + ' No operation + Case LDA + a = m(operand) + Case STA + m(operand) = a + Case ADD + a = (a + m(operand)) Mod 256 + If a > 255 Then a = 0 + Case SUV + a = (a - m(operand)) Mod 256 + If a < 0 Then a = 255 + Case BRZ + If a = 0 Then pc = operand + Case JMP + pc = operand + Case Else + ' Stop + running = False + Print Space(12 - Len(nombre)) & nombre & ": " & a + End Select + Wend +End Sub + +' Test programs +Dim poly1(4) As Ubyte = {LDA_(3), ADD_(4), STP_(0), 2, 2} +execute("2+2", poly1()) + +Dim poly2(13) As Ubyte = {LDA_(12), ADD_(10), STA_(12), LDA_(11), SUB_(13), STA_(11), BRZ_(8), JMP_(0), LDA_(12), STP_(0), 8, 7, 0, 1} +execute("7*8", poly2()) + +Dim poly3(0 To ...) As Ubyte = {LDA_(14), STA_(15), ADD_(13), STA_(14), LDA_(15), STA_(13), LDA_(16), SUB_(17), BRZ_(11), STA_(16), JMP_(0), LDA_(14), STP_(0), 1, 1, 0, 8, 1} +execute("fibonacci", poly3()) + +Dim poly4(0 To ...) As Ubyte = {LDA_(13), ADD_(15), STA_(5), ADD_(16), STA_(7), NOP_(0), STA_(14), NOP_(0), BRZ_(11), STA_(15), JMP_(0), LDA_(14), STP_(0), LDA_(0), 0, 28, 1, 0, 0, 0, 6, 0, 2, 26, 5, 20, 3, 30, 1, 22, 4, 24} +execute("linkedList", poly4()) + +Dim poly5(0 To ...) As Ubyte = {NOP_(0), NOP_(0), STP_(0), 0, LDA_(3), SUB_(29), BRZ_(18), LDA_(3), STA_(29), BRZ_(14), LDA_(1), ADD_(31), STA_(1), JMP_(2), LDA_(0), ADD_(31), STA_(0), JMP_(2), LDA_(3), STA_(29), LDA_(1), ADD_(30), ADD_(3), STA_(1), LDA_(0), ADD_(30), ADD_(3), STA_(0), JMP_(2), 0, 1, 3} +execute("prisoner", poly5()) + +Dim poly6(0 To ...) As Ubyte = {LDA_(3), SUB_(4), STP_(0), 0, 255} +execute("0-255", poly6()) + +Dim poly7(0 To ...) As Ubyte = {LDA_(3), SUB_(4), STP_(0), 0, 1} +execute("0-1", poly7()) + +Dim poly8(0 To ...) As Ubyte = {LDA_(3), ADD_(4), STP_(0), 1, 255} +execute("1+255", poly8()) + +Sleep diff --git a/Task/Execute-HQ9+/11l/execute-hq9+.11l b/Task/Execute-HQ9+/11l/execute-hq9+.11l index f78b71196e..61c3364c3b 100644 --- a/Task/Execute-HQ9+/11l/execute-hq9+.11l +++ b/Task/Execute-HQ9+/11l/execute-hq9+.11l @@ -38,7 +38,7 @@ F incr() :start: src = File(:argv[1]).read() -[Char = (() -> N)] dispatch +[Char = (() -> Void)] dispatch dispatch[Char(‘h’)] = hello dispatch[Char(‘q’)] = quine dispatch[Char(‘9’)] = bottles diff --git a/Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic b/Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic new file mode 100644 index 0000000000..2a3ce48e9f --- /dev/null +++ b/Task/Execute-SNUSP/FreeBASIC/execute-snusp.basic @@ -0,0 +1,77 @@ +' Rosetta Code problem: https://rosettacode.org/wiki/Execute_SNUSP +' by Jjuanhdez, 05/2024 +' The interpreter below implements Core SNUSP: + +Const HW = "/++++!/===========?\>++.>+.+++++++..+++" & Chr(10) & _ +"\+++\ | /+>+++++++>/ /++++++++++<<.++>./" & Chr(10) & _ +"$+++/ | \+++++++++>\ \+++++.>.+++.-----\" & Chr(10) & _ +" \==-<<<<+>+++/ /=.>.+>.--------.-/" + +Dim Shared As Integer ipf, ipc ' instruction pointers in row and column +Dim Shared As Integer direcc ' direction (0 = right, 1 = down, 2 = left, 3 = up) + +Sub Paso() + If direcc And 1 Then + ipf += 1 - (direcc And 2) + Else + ipc += 1 - (direcc And 2) + End If +End Sub + +Sub SNUSP (dsLen As Integer, SNUSPcode As String) + Dim As Ubyte ad(dsLen - 1) ' data store + Dim As Integer dp ' data pointer + Dim As String cb(dsLen) ' two-way code storage + Dim As String fila, op, linea + Dim As Integer r, i, j + + dp = 0 + i = 1 + j = 1 + ipf = 0 + ipc = 0 + direcc = 0 + + While i <= Len(SNUSPcode) + If Mid(SNUSPcode, i, 1) = Chr(10) Then + cb(j) = linea + linea = "" + j += 1 + Else + linea &= Mid(SNUSPcode, i, 1) + End If + i += 1 + Wend + cb(j) = linea + + For r = 0 To Ubound(cb) + fila = cb(r) + ipc = Instr(fila, "$") - 1 + If ipc >= 0 Then + ipf = r + Exit For + End If + Next r + + While ipf >= 0 And ipf <= Ubound(cb) And ipc >= 0 And ipc < Len(cb(ipf)) + op = Mid(cb(ipf), ipc + 1, 1) + Select Case op + Case ">": dp += 1 ' RIGTH + Case "<": dp -= 1 ' LEFT + Case "+": ad(dp) += 1 ' INCR + Case "-": ad(dp) -= 1 ' DECR + Case ",": Input ad(dp) ' READ + Case ".": Print Chr(ad(dp)); ' WRITE + Case "/": direcc = Not direcc ' RULD + Case "\": direcc Xor= 1 ' LURD + Case "!": Paso ' SKIP + Case "?": If ad(dp) = 0 Then Paso ' SKIPZ + End Select + Paso + Wend + Print Chr(ad(dp)); +End Sub + +SNUSP(5, HW) + +Sleep diff --git a/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l b/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l index 5c8a789dc8..4c3cf6cc78 100644 --- a/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l +++ b/Task/Execute-a-Markov-algorithm/11l/execute-a-markov-algorithm.11l @@ -1,11 +1,4 @@ -T Rule - String pattern - String replacement - Bool terminating - F (pattern, replacement, terminating) - .pattern = pattern - .replacement = replacement - .terminating = terminating +T Rule = (String pattern, String replacement, Bool terminating) F parse(rules) [Rule] result diff --git a/Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic b/Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic new file mode 100644 index 0000000000..8d0a5ec743 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/FreeBASIC/execute-a-markov-algorithm.basic @@ -0,0 +1,139 @@ +Sub Markov (rules As String, entrada As String, expected As String) + Dim As String subs(), reps(), lines() + Dim As String sub_, rep, li, res + Dim As Integer i, k + Dim As Integer start = 1, finish = 1 + + While finish <= Len(rules) + If Mid(rules, finish, 1) = Chr(10) Then + Redim Preserve lines(Ubound(lines) + 1) + lines(Ubound(lines)) = Mid(rules, start, finish - start) + start = finish + 1 + End If + finish += 1 + Wend + For i = 0 To Ubound(lines) + li = lines(i) + If Len(li) > 0 And Asc(li, 1) <> Asc("#") Then + k = Instr(li, " -> ") + If k > 0 Then + Redim Preserve subs(Ubound(subs) + 1) + subs(Ubound(subs)) = Trim(Mid(li, 1, k - 1)) + Redim Preserve reps(Ubound(reps) + 1) + reps(Ubound(reps)) = Trim(Mid(li, k + 4)) + End If + End If + Next i + + res = entrada + Dim As Boolean term = False, found = False + Do + found = False + For i = 0 To Ubound(subs) + sub_ = subs(i) + k = Instr(res, sub_) + If k > 0 Then + found = True + rep = reps(i) + If Len(rep) > 0 And Asc(rep, 1) = Asc(".") Then + rep = Mid(rep, 2) + term = True + End If + Mid(res, k, Len(sub_)) = rep + Exit For + End If + If Not term Then Exit For + Next i + If Not term Or Not found Then Exit Do + Loop + Print """"; entrada;""""; ", "; """"; expected; """"; ", "; Iif(res = expected, "**ERROR**", "ok") +End Sub + +Dim As String ruleset1 = _ +"# This rules file is extracted from Wikipedia:" & _ +"# http://en.wikipedia.org/wiki/Markov_Algorithm" & _ +"A -> apple" & _ +"B -> bag" & _ +"S -> shop" & _ +"T -> the" & _ +"the shop -> my brother" & _ +"a never used -> .terminating rule" +Markov(ruleset1,"I bought a B of As from T S.","I bought a bag of apples from my brother.") + +Dim As String ruleset2 = _ +"# Slightly modified from the rules on Wikipedia" & _ +"A -> apple" & _ +"B -> bag" & _ +"S -> .shop" & _ +"T -> the" & _ +"the shop -> my brother" & _ +"a never used -> .terminating rule" +Markov(ruleset2,"I bought a B of As from T S.","I bought a bag of apples from T shop.") + +Dim As String ruleset3 = _ +"# BNF Syntax testing rules" & _ +"A -> apple" & _ +"WWWW -> with" & _ +"Bgage -> ->.*" & _ +"B -> bag" & _ +"->.* -> money" & _ +"W -> WW" & _ +"S -> .shop" & _ +"T -> the" & _ +"the shop -> my brother" & _ +"a never used -> .terminating rule""" +Markov(ruleset3,"I bought a B of As W my Bgage from T S.","I bought a bag of apples with my money from T shop.") + +Dim As String ruleset4 = _ +"### Unary Multiplication Engine, for testing Markov Algorithm implementations" & _ +"### By Donal Fellows." & _ +"# Unary addition engine" & _ +"_+1 -> _1+" & _ +"1+1 -> 11+" & _ +"# Pass for converting from the splitting of multiplication into ordinary" & _ +"# addition" & _ +"1! -> !1" & _ +",! -> !+" & _ +"_! -> _" & _ +"# Unary multiplication by duplicating left side, right side times" & _ +"1*1 -> x,@y" & _ +"1x -> xX" & _ +"X, -> 1,1" & _ +"X1 -> 1X" & _ +"_x -> _X" & _ +",x -> ,X" & _ +"y1 -> 1y" & _ +"y_ -> _" & _ +"# Next phase of applying" & _ +"1@1 -> x,@y" & _ +"1@_ -> @_" & _ +",@_ -> !_" & _ +"++ -> +" & _ +"# Termination cleanup for addition" & _ +"_1 -> 1" & _ +"1+_ -> 1" & _ +"_+_ -> " +Markov(ruleset4,"_1111*11111_","11111111111111111111") + +Dim As String ruleset5 = _ +"# Turing machine: three-state busy beaver" & _ +"#" & _ +"# state A, symbol 0 => write 1, move right, new state B" & _ +"A0 -> 1B" & _ +"# state A, symbol 1 => write 1, move left, new state C" & _ +"0A1 -> C01" & _ +"1A1 -> C11" & _ +"# state B, symbol 0 => write 1, move left, new state A" & _ +"0B0 -> A01" & _ +"1B0 -> A11" & _ +"# state B, symbol 1 => write 1, move right, new state B" & _ +"B1 -> 1B" & _ +"# state C, symbol 0 => write 1, move left, new state B" & _ +"0C0 -> B01" & _ +"1C0 -> B11" & _ +"# state C, symbol 1 => write 1, move left, halt" & _ +"0C1 -> H01" & _ +"1C1 -> H11" +Markov(ruleset5,"000000A000000","00011H1111000") + +Sleep diff --git a/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 b/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 index eafaacc2ca..7de9dc25a3 100644 --- a/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 +++ b/Task/Execute-a-system-command/Seed7/execute-a-system-command.seed7 @@ -3,5 +3,5 @@ $ include "seed7_05.s7i"; const proc: main is func begin - cmd_sh("ls"); + shellCmd("ls"); end func; diff --git a/Task/Extend-your-language/Langur/extend-your-language-2.langur b/Task/Extend-your-language/Langur/extend-your-language-2.langur deleted file mode 100644 index ee25f3a906..0000000000 --- a/Task/Extend-your-language/Langur/extend-your-language-2.langur +++ /dev/null @@ -1,7 +0,0 @@ -switch[and] .x, .y { - case true: ... # both true - case true, false: ... # first true, second false - case false, true: ... # first false, second true - case null, _: ... # first null - default: ... # other -} diff --git a/Task/Extend-your-language/Langur/extend-your-language-1.langur b/Task/Extend-your-language/Langur/extend-your-language.langur similarity index 86% rename from Task/Extend-your-language/Langur/extend-your-language-1.langur rename to Task/Extend-your-language/Langur/extend-your-language.langur index 45647137b3..13bd34e454 100644 --- a/Task/Extend-your-language/Langur/extend-your-language-1.langur +++ b/Task/Extend-your-language/Langur/extend-your-language.langur @@ -1,4 +1,4 @@ -switch[and] .x nxor, .y nxor { +switch[and] x nxor, y nxor { case true: ... # both true case true, false: ... # first true, second false case false, true: ... # first false, second true diff --git a/Task/Extreme-floating-point-values/PascalABC.NET/extreme-floating-point-values.pas b/Task/Extreme-floating-point-values/PascalABC.NET/extreme-floating-point-values.pas new file mode 100644 index 0000000000..3cb7d97575 --- /dev/null +++ b/Task/Extreme-floating-point-values/PascalABC.NET/extreme-floating-point-values.pas @@ -0,0 +1,14 @@ +begin + Println(1.0/real.PositiveInfinity); // 0 + Println(1.0/real.NegativeInfinity); // 0 + Println(0.0/0.0); // NaN + Println(1.0/0.0); // Infinity + Println(-1.0/0.0); // -Infinity + Println(real.NegativeInfinity < real.PositiveInfinity); // True + Println(real.NegativeInfinity + real.PositiveInfinity); // NaN + Println(real.PositiveInfinity + real.PositiveInfinity); // Infinity + Println(real.PositiveInfinity / real.PositiveInfinity); // NaN + Println(Sqrt(-1)); // NaN + Println(real.NaN = real.NaN); // False + Println(real.IsNaN(Sqrt(-1))); // True +end. diff --git a/Task/FTP/Ada/ftp.ada b/Task/FTP/Ada/ftp.ada new file mode 100644 index 0000000000..a7565b49eb --- /dev/null +++ b/Task/FTP/Ada/ftp.ada @@ -0,0 +1,57 @@ +with Ada.Text_IO; +with Sf.Network.Ftp; +with Sf.Network.IpAddress; +with Sf.System.Time; + +procedure Main is + use Sf; use Sf.Network; use Sf.Network.Ftp; + FTP_Error : exception; + + FTP_Object : constant sfFtp_Ptr := create; + + procedure Check_Response (FTP_Response : sfFtpResponse_Ptr) is + Message : constant String := Response.getMessage (FTP_Response); + begin + Response.destroy (FTP_Response); + if not Response.isOk (FTP_Response) then + raise FTP_Error with Message; + else + Ada.Text_IO.Put_Line ("OK: " & Message); + end if; + end Check_Response; + + procedure List_Directory (Path : String) is + Response : sfFtpListingResponse_Ptr; + begin + Response := getDirectoryListing (FTP_Object, Path); + if ListingResponse.isOk (Response) then + for Index in 0 .. ListingResponse.getCount (Response) - 1 loop + Ada.Text_IO.Put_Line (ListingResponse.getName (Response, Index)); + end loop; + else + Ada.Text_IO.Put_Line (ListingResponse.getMessage (Response)); + end if; + ListingResponse.destroy (Response); + end List_Directory; + +begin + + Check_Response + (connect (FTP_Object, + server => IpAddress.fromString ("speedtest.tele2.net"), + port => 21, + timeout => Sf.System.Time.sfSeconds (30.0))); + + Check_Response (loginAnonymous (FTP_Object)); + + Check_Response (changeDirectory (FTP_Object, "/upload")); + Check_Response (changeDirectory (FTP_Object, "/")); + + List_Directory ("."); + + Check_Response (download (FTP_Object, + remoteFile => "100KB.zip", + localPath => ".", + mode => sfFtpBinary)); + destroy (FTP_Object); +end Main; diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/C++/factorial-base-numbers-indexing-permutations-of-a-collection.cpp b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/C++/factorial-base-numbers-indexing-permutations-of-a-collection.cpp new file mode 100644 index 0000000000..cb53769288 --- /dev/null +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/C++/factorial-base-numbers-indexing-permutations-of-a-collection.cpp @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +#include + +std::string stringify(const std::string& text) { + return text; +} + +std::string stringify(const uint32_t& number) { + return std::to_string(number); +} + +template +std::string to_string(const std::vector& factoradic, const std::string& delimiter) { + std::string result = ""; + for ( uint32_t i = 0; i < factoradic.size() - 1; ++i ) { + result += stringify(factoradic[i]) + delimiter; + } + result += stringify(factoradic.back()); + return result; +} + +uint32_t factorial(const uint32_t& n) { + uint32_t factorial = 1; + for ( uint32_t i = 2; i <= n; ++i ) { + factorial *= i; + } + return factorial; +} + +void increment(std::vector& factoradic) { + uint64_t index = factoradic.size() - 1; + while ( index >= 0 && factoradic[index] == factoradic.size() - index ) { + factoradic[index] = 0; + index -= 1; + } + if ( index >= 0 ) { + factoradic[index] += 1; + } +} + +std::vector split_string(const std::string& text, const char& delimiter) { + std::vector lines; + std::istringstream stream(text); + std::string line; + while ( std::getline(stream, line, delimiter) ) { + if ( ! line.empty() ) { + lines.emplace_back(line); + } + } + return lines; +} + +std::vector convert_to_vector_of_integer(const std::string& text) { + std::vector result = { }; + std::vector numbers = split_string(text, '.'); + for ( const std::string& number : numbers ) { + result.emplace_back(std::stoi(number)); + } + return result; +} + +template +std::vector permutation(std::vector elements, const std::vector& factoradic) { + uint32_t m = 0; + for ( const uint32_t& g : factoradic ) { + const T element = elements[m + g]; + elements.erase(elements.begin() + m + g); + elements.insert(elements.begin() + m, element); + m += 1; + } + return elements; +} + +int main() { + // Part 1 + std::vector elements = convert_to_vector_of_integer("0.1.2.3"); + std::vector factoradic = convert_to_vector_of_integer("0.0.0"); + for ( uint32_t i = 0; i < factorial(4); ++i ) { + std::vector rotated = permutation(elements, factoradic); + std::cout << to_string(factoradic, ".") + " --> " + to_string(rotated, " ") << std::endl; + increment(factoradic); + } + std::cout << std::endl; + + // Part 2 + std::cout << "Generating the permutations of 11 digits:" << std::endl; + const uint32_t limit = factorial(11); + elements = convert_to_vector_of_integer("0.1.2.3.4.5.6.7.8.9.10"); + factoradic = convert_to_vector_of_integer("0.0.0.0.0.0.0.0.0.0"); + for ( uint32_t i = 0; i < limit; ++i ) { + std::vector rotated = permutation(elements, factoradic); + if ( i < 3 || i > limit - 4 ) { + std::cout << to_string(factoradic, ".") + " --> " + to_string(rotated, " ") + << std::endl; + } else if ( i == 3 ) { + std::cout << " [ ... ] " << std::endl; + } + increment(factoradic); + } + std::cout << "Number of permutations is 11! = " << limit << std::endl << std::endl; + + // Part 3 + std::vector codes = { "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", +"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1" }; + + std::vector cards = { "A♠", "K♠", "Q♠", "J♠", "10♠", "9♠", "8♠", "7♠", "6♠", "5♠", "4♠", "3♠", "2♠", + "A♥", "K♥", "Q♥", "J♥", "10♥", "9♥", "8♥", "7♥", "6♥", "5♥", "4♥", "3♥", "2♥", + "A♦", "K♦", "Q♦", "J♦", "10♦", "9♦", "8♦", "7♦", "6♦", "5♦", "4♦", "3♦", "2♦", + "A♣", "K♣", "Q♣", "J♣", "10♣", "9♣", "8♣", "7♣", "6♣", "5♣", "4♣", "3♣", "2♣" + }; + + std::cout << "Original deck of cards:" << std::endl; + std::cout << to_string(cards, " ") << std::endl << std::endl; + std::cout << "Task shuffles:" << std::endl; + for ( const std::string& code : codes ) { + std::cout << code + " --> " << std::endl; + factoradic = convert_to_vector_of_integer(code); + std::cout << to_string(permutation(cards, factoradic), " ") + << std::endl << std::endl; + } + + std::cout << "Random shuffle:" << std::endl;; + std::random_device random; + std::mt19937 generator(random()); + + factoradic.clear(); + for ( uint32_t i = 0; i < cards.size() - 1; ++i ) { + std::uniform_int_distribution distribution(0, cards.size() - i - 1); + factoradic.emplace_back(distribution(generator)); + } + + std::cout << to_string(factoradic, ".") + " --> " << std::endl; + std::cout << to_string(permutation(cards, factoradic), " ") << std::endl; +} diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java index 9e7609637e..3f126f2202 100644 --- a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/Java/factorial-base-numbers-indexing-permutations-of-a-collection.java @@ -58,7 +58,7 @@ public final class FactorialBaseNumbersIndexingPermutations { System.out.println("Random shuffle:"); ThreadLocalRandom random = ThreadLocalRandom.current(); factoradic.clear(); - for ( int i = 0; i < 52; i++ ) { + for ( int i = 0; i < cards.size() - 1; i++ ) { factoradic.add(random.nextInt(cards.size() - i)); } System.out.println(toString(factoradic, ".") + " --> "); diff --git a/Task/Factorial-primes/Common-Lisp/factorial-primes.lisp b/Task/Factorial-primes/Common-Lisp/factorial-primes.lisp new file mode 100644 index 0000000000..0e28867922 --- /dev/null +++ b/Task/Factorial-primes/Common-Lisp/factorial-primes.lisp @@ -0,0 +1,27 @@ +(defun factorial (x) + (if (= x 1) + x + (* x (factorial (- x 1))))) + +(defun is-factor (x y) + (zerop (mod x y))) + +(defun is-prime (n) + (cond ((< n 4) (or (= n 2) (= n 3))) + ((or (zerop (mod n 2)) (zerop (mod n 3))) nil) + (t (loop for i from 5 to (floor (sqrt n)) by 6 + never (or (is-factor n i) + (is-factor n (+ i 2))))))) + +(defun main (&optional (limit 10)) + (let ((n 0) + (f 0)) + (loop while (< n limit) + for i from 1 + do (setf f (factorial i)) + (when (is-prime (+ f 1)) + (incf n) + (format t "~2d: ~2d! + 1 = ~12d~%" n i (+ f 1))) + (when (is-prime (- f 1)) + (incf n) + (format t "~2d: ~2d! - 1 = ~12d~%" n i (- f 1)))))) diff --git a/Task/Factorial-primes/Go/factorial-primes.go b/Task/Factorial-primes/Go/factorial-primes.go new file mode 100644 index 0000000000..a808dfb619 --- /dev/null +++ b/Task/Factorial-primes/Go/factorial-primes.go @@ -0,0 +1,59 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + n, count := 0, 0 + + for count < 10 { + n++ + f := factorial(n) + + if isPrime(f.Sub(f, big.NewInt(1))) { + count++ + fmt.Printf("%2d: %2d! - 1 = %s\n", count, n, f.String()) + } + + if isPrime(f.Add(f, big.NewInt(2))) { + count++ + fmt.Printf("%2d: %2d! + 1 = %s\n", count, n, f.String()) + } + } +} + +func factorial(n int) *big.Int { + result := big.NewInt(1) + + for i := 2; i <= n; i++ { + result.Mul(result, big.NewInt(int64(i))) + } + + return result +} + +func isPrime(num *big.Int) bool { + if num.Cmp(big.NewInt(2)) < 0 { + return false + } + + if num.Cmp(big.NewInt(2)) == 0 { + return true + } + + if new(big.Int).Mod(num, big.NewInt(2)).Cmp(big.NewInt(0)) == 0 { + return false + } + + sqrt := new(big.Int).Sqrt(num) + + for i := big.NewInt(3); i.Cmp(sqrt) <= 0; i.Add(i, big.NewInt(2)) { + if new(big.Int).Mod(num, i).Cmp(big.NewInt(0)) == 0 { + return false + } + } + + return true +} diff --git a/Task/Factorial-primes/Kotlin/factorial-primes.kotlin b/Task/Factorial-primes/Kotlin/factorial-primes.kotlin new file mode 100644 index 0000000000..22db036df6 --- /dev/null +++ b/Task/Factorial-primes/Kotlin/factorial-primes.kotlin @@ -0,0 +1,43 @@ +import java.math.BigInteger +import java.math.BigInteger.ONE + +enum class Difference(private val displayText: String) { + MINUS_ONE("- 1"), PLUS_ONE("+ 1"); + + override fun toString(): String { + return displayText + } +} + +fun main() { + var currentFactorial = ONE + var highestFactor = 1L + var found = 0 + + while(found < 30) { + if ((currentFactorial - ONE).isProbablePrime(25)) { + printlnFactorialPrime(currentFactorial - ONE, highestFactor, Difference.MINUS_ONE) + found++ + } + if ((currentFactorial + ONE).isProbablePrime(25)) { + printlnFactorialPrime(currentFactorial + ONE, highestFactor, Difference.PLUS_ONE) + found++ + } + + highestFactor++ + currentFactorial *= BigInteger.valueOf(highestFactor) + } +} + +fun printlnFactorialPrime(factorialPrime: BigInteger, base: Long, difference: Difference) = + println("${base}! $difference = ${factorialPrime.shortenIfNecessary()}") + +fun BigInteger.shortenIfNecessary(): String { + val digits = toString() + val length = digits.length + return if (length <= 40) { + digits + } else { + "${digits.take(20)}...${digits.takeLast(20)} ($length digits)" + } +} diff --git a/Task/Factorial/Langur/factorial-1.langur b/Task/Factorial/Langur/factorial-1.langur index 8d8674f4b4..607783ad36 100644 --- a/Task/Factorial/Langur/factorial-1.langur +++ b/Task/Factorial/Langur/factorial-1.langur @@ -1,2 +1,2 @@ -val .factorial = fn(.n) fold(fn{*}, 2 .. .n) -writeln .factorial(7) +val factorial = fn n: fold(fn{*}, 2 .. n) +writeln factorial(7) diff --git a/Task/Factorial/Langur/factorial-2.langur b/Task/Factorial/Langur/factorial-2.langur index a40e149332..862defdc58 100644 --- a/Task/Factorial/Langur/factorial-2.langur +++ b/Task/Factorial/Langur/factorial-2.langur @@ -1,2 +1,2 @@ -val .factorial = fn(.x) if(.x < 2: 1; .x * self(.x - 1)) -writeln .factorial(7) +val factorial = fn x: if(x < 2: 1; x * fn((x - 1))) +writeln factorial(7) diff --git a/Task/Factorial/Langur/factorial-3.langur b/Task/Factorial/Langur/factorial-3.langur index a630ad30d4..69f55844e4 100644 --- a/Task/Factorial/Langur/factorial-3.langur +++ b/Task/Factorial/Langur/factorial-3.langur @@ -1,9 +1,9 @@ -val .factorial = fn(.i) { - var .answer = 1 - for .x in 2 .. .i { - .answer *= .x +val factorial = fn(i) { + var answer = 1 + for x in 2 .. i { + answer *= x } - .answer + answer } -writeln .factorial(7) +writeln factorial(7) diff --git a/Task/Factorial/Langur/factorial-4.langur b/Task/Factorial/Langur/factorial-4.langur index 482796f7ea..676ccfbd38 100644 --- a/Task/Factorial/Langur/factorial-4.langur +++ b/Task/Factorial/Langur/factorial-4.langur @@ -1,2 +1,2 @@ -val .factorial = fn(.n) for[=1] .x in .n { _for *= .x } -writeln .factorial(7) +val factorial = fn n: for[=1] x in n { _for *= x } +writeln factorial(7) diff --git a/Task/Factorial/PascalABC.NET/factorial.pas b/Task/Factorial/PascalABC.NET/factorial.pas new file mode 100644 index 0000000000..87563d6ab2 --- /dev/null +++ b/Task/Factorial/PascalABC.NET/factorial.pas @@ -0,0 +1,19 @@ +function FactIter(n: integer): BigInteger; +begin + Result := 1; + for var i:=2 to n do + Result *= i; +end; + +function FactRec(n: integer): BigInteger; +begin + if n = 0 then + Result := 1 + else Result := n * FactRec(n - 1); +end; + + +begin + for var i:=1 to 20 do + Println(i,FactRec(i),FactIter(i)); +end. diff --git a/Task/Factorial/S-BASIC/factorial-1.basic b/Task/Factorial/S-BASIC/factorial-1.basic new file mode 100644 index 0000000000..3899ac1bd1 --- /dev/null +++ b/Task/Factorial/S-BASIC/factorial-1.basic @@ -0,0 +1,13 @@ +function factorial(n=real.double)=real.double + if n = 0 then n = 1 else n = n * factorial(n-1) +end = n + +var i=integer +print "Factorial Calculator" +print " n n!" +print "----------------------" +for i=1 to 15 + print using "## #,###,###,###,###";i;factorial(i) +next i + +end diff --git a/Task/Factorial/S-BASIC/factorial-2.basic b/Task/Factorial/S-BASIC/factorial-2.basic new file mode 100644 index 0000000000..91fbb1fce5 --- /dev/null +++ b/Task/Factorial/S-BASIC/factorial-2.basic @@ -0,0 +1,7 @@ +function factorial(n=real.double)=real.double + var i, f = real.double + f = 1 + for i = 1 to n + f = f * i + next i +end = f diff --git a/Task/Factorial/Uiua/factorial.uiua b/Task/Factorial/Uiua/factorial.uiua new file mode 100644 index 0000000000..7b2a3e07ea --- /dev/null +++ b/Task/Factorial/Uiua/factorial.uiua @@ -0,0 +1 @@ +Factorial = /×+1⇡ diff --git a/Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq b/Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq new file mode 100644 index 0000000000..2846586599 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Jq/factors-of-a-mersenne-number.jq @@ -0,0 +1,61 @@ +# Generic filters: + +# Integer division (for gojq and jaq) +# If $j is 0, then an error condition is raised; +# otherwise, assuming infinite-precision integer arithmetic, +# if the input and $j are integers, then the result will be an integer. +def idivide($j): + (. % $j) as $mod + | (. - $mod) / $j | round; + +# Convert the input integer to a stream of 0s and 1s, least significant bit first +def bitwise: + recurse( if . >= 2 then idivide(2) else empty end) | . % 2; + +def is_prime: + . as $n + | if ($n < 2) then false + elif ($n % 2 == 0) then $n == 2 + elif ($n % 3 == 0) then $n == 3 + elif ($n % 5 == 0) then $n == 5 + elif ($n % 7 == 0) then $n == 7 + elif ($n % 11 == 0) then $n == 11 + elif ($n % 13 == 0) then $n == 13 + elif ($n % 17 == 0) then $n == 17 + elif ($n % 19 == 0) then $n == 19 + else sqrt as $s + | 23 + | until( . > $s or ($n % . == 0); . + 2) + | . > $s + end; + +### Factors of Mersene numbers + +def trialFactor($base; $exp; $mod): + [$exp | bitwise] as $bits + | ($bits|length) as $length + | reduce range( 0; $length) as $i (1; + (. * . * (if $bits[$length-$i-1] == 1 then $base else 1 end)) % $mod ) + | . == 1 ; + +def mersenneFactor($p): + ((pow(2;$p) - 1) | sqrt | floor) as $limit + | {k: 1} + | until ((2*.k*$p - 1) >= $limit or .emit; + (2*.k*$p + 1 ) as $q + | if ($q%8 == 1 or $q%8 == 7) and trialFactor(2; $p; $q) and ($q | is_prime) + then .emit = $q # q is a factor of 2^p - 1 + else .k += 1 + end) + | if .emit then .emit else null end; + +### Examples: + +def m: [3, 5, 11, 17, 23, 29, 31, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929]; + +m[] +| mersenneFactor(.) as $f +| "2^\(.) - 1 is " + + if $f then "composite (factor \($f))" + else "prime" + end diff --git a/Task/Factors-of-an-integer/PascalABC.NET/factors-of-an-integer.pas b/Task/Factors-of-an-integer/PascalABC.NET/factors-of-an-integer.pas new file mode 100644 index 0000000000..8e3be19d51 --- /dev/null +++ b/Task/Factors-of-an-integer/PascalABC.NET/factors-of-an-integer.pas @@ -0,0 +1,16 @@ +function Factors(n: integer): List; +begin + var res := HSet(1,n); + for var i:=2 to n.Sqrt.Trunc do + if n.Divs(i) then + begin + res.Add(i); + res.Add(n div i); + end; + Result := res.Order.ToList; +end; + +begin + foreach var x in |45,53,64| do + Println(x,Factors(x)); +end. diff --git a/Task/Factors-of-an-integer/Refal/factors-of-an-integer.refal b/Task/Factors-of-an-integer/Refal/factors-of-an-integer.refal new file mode 100644 index 0000000000..86b75f81c5 --- /dev/null +++ b/Task/Factors-of-an-integer/Refal/factors-of-an-integer.refal @@ -0,0 +1,13 @@ +$ENTRY Go { + = >; +} + +Factors { + s.N = ; + (s.N s.D), >: '-' = ; + (s.N s.D), : { + (s.D) 0 = s.D; + (s.F) 0 = s.D )> s.F; + (s.X) s.Y = )>; + }; +}; diff --git a/Task/Factors-of-an-integer/Uiua/factors-of-an-integer.uiua b/Task/Factors-of-an-integer/Uiua/factors-of-an-integer.uiua new file mode 100644 index 0000000000..a36731f5c3 --- /dev/null +++ b/Task/Factors-of-an-integer/Uiua/factors-of-an-integer.uiua @@ -0,0 +1,2 @@ +Factors ← ◴⊂⟜(⇌÷)⊸(▽:⟜≡(=0◿)⊙¤⊸(↘1⇡+1⌊√)) +⍚Factors {45 53 64} diff --git a/Task/Farey-sequence/Langur/farey-sequence.langur b/Task/Farey-sequence/Langur/farey-sequence.langur index 046064cc89..2743d7c155 100644 --- a/Task/Farey-sequence/Langur/farey-sequence.langur +++ b/Task/Farey-sequence/Langur/farey-sequence.langur @@ -1,23 +1,23 @@ -val .farey = fn(.n) { - var .a, .b, .c, .d = 0, 1, 1, .n - while[=[[0, 1]]] .c <= .n { - val .k = (.n + .b) // .d - .a, .b, .c, .d = .c, .d, .k * .c - .a, .k * .d - .b - _while ~= [[.a, .b]] +val farey = fn(n) { + var a, b, c, d = 0, 1, 1, n + while[=[[0, 1]]] c <= n { + val k = (n + b) // d + a, b, c, d = c, d, k * c - a, k * d - b + _while ~= [[a, b]] } } -val .testFarey = impure fn() { +val testFarey = fn*() { writeln "Farey sequence for orders 1 through 11" - for .i of 11 { - writeln $"\.i:2;: ", join " ", map(fn(.f) $"\.f[1];/\.f[2];", .farey(.i)) + for i of 11 { + writeln "{{i:2}}: ", join(" ", map(fn f: "{{f[1]}}/{{f[2]}}", farey(i))) } } -.testFarey() +testFarey() writeln() writeln "count of Farey sequence fractions for 100 to 1000 by hundreds" -for .i = 100; .i <= 1000; .i += 100 { - writeln $"\.i:4;: ", len(.farey(.i)) +for i = 100; i <= 1000; i += 100 { + writeln "{{i:4}}: ", len(farey(i)) } diff --git a/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation.rexx b/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-1.rexx similarity index 100% rename from Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation.rexx rename to Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-1.rexx diff --git a/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx b/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx new file mode 100644 index 0000000000..81e8fa6e36 --- /dev/null +++ b/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx @@ -0,0 +1,63 @@ +arg n; if n = '' then n = 30; numeric digits n +parse version version; say version; glob. = '' +say 'First Fiegenbaum constant, correct to about 11 decimals' +say 'Using algorithm cf RosettaCode' +say +call time('r'); a = Original(); e = format(time('e'),,3) +say 'Original ' a '('e 'seconds)' +call time('r'); a = Optimized(); e = format(time('e'),,3) +say 'Optimized ' a '('e 'seconds)' +call time('r'); a = TrueValue(); e = format(time('e'),,3) +say 'True value' a '('e 'seconds)' +exit + +Original: +procedure expose glob. +/* Outer 2 loops with a fixed value */ +numeric digits digits()+2 +im = 20; jm = 10 +a1 = 1; a2 = 0; d1 = 3.2 +do i = 2 to im + a = a1 + (a1-a2)/d1 + do j = 1 to jm + x = 0; y = 0 + do k = 1 to 2**i + y = 1 - 2*x*y; x = a - x*x + end + a = a - x/y + end + d = (a1-a2) / (a-a1) + parse value d a1 a with d1 a2 a1 +end +numeric digits digits()-2 +return d+0 + +Optimized: +procedure expose glob. +/* Center loop stops on achieving desired accuracy */ +numeric digits digits()+4; numeric fuzz 4 +/* Only outer loop maximum */ +im = 20 +a1 = 1; a2 = 0; d1 = 3.2 +do i = 2 to im + a = a1 + (a1-a2)/d1; v = 0 + do forever + x = 0; y = 0 + do 2**i + y = 1 - 2*x*y; x = a - x*x + end + a = a - x/y +/* Stop second loop when a does not change anymore */ + if a = v then + leave + v = a + end + d = (a1-a2) / (a-a1) + parse value d a1 a with d1 a2 a1 +end +numeric digits digits()-4 +return d+0 + +TrueValue: +procedure expose glob. +return 4.66920160910299067185320382046620161725818557747576863274565134300413433021131473713868974402394801381716+0 diff --git a/Task/Fermat-numbers/Langur/fermat-numbers.langur b/Task/Fermat-numbers/Langur/fermat-numbers.langur index 84749505e2..c530d67ef7 100644 --- a/Task/Fermat-numbers/Langur/fermat-numbers.langur +++ b/Task/Fermat-numbers/Langur/fermat-numbers.langur @@ -1,28 +1,29 @@ -val .fermat = fn(.i) 2 ^ 2 ^ .i + 1 +val fermat = fn i: 2 ^ 2 ^ i + 1 +val sz = '\u2080' # small zero code point -val .factors = fn(var .x) { - for[.f=[]] .i, .s = 2, trunc .x ^/ 2; .i < .s; .i += 1 { - if .x div .i { - .f ~= [.i] - .x \= .i - .s = trunc .x ^/ 2 +val factors = fn(var x) { + for[f=[]] i, s = 2, trunc(x ^/ 2); i < s; i += 1 { + if x div i { + f ~= [i] + x \= i + s = trunc(x ^/ 2) } - } ~ [.x] + } ~ [x] } writeln "first 10 Fermat numbers" -for .i in 0..9 { - writeln $"F\(.i + 16x2080:cp) = \(.fermat(.i))" +for i in 0..9 { + writeln "F{{i + sz:cp}} = {{fermat(i)}}" } writeln() writeln "factors of first few Fermat numbers" -for .i in 0..9 { - val .ferm = .fermat(.i) - val .fac = .factors(.ferm) - if len(.fac) == 1 { - writeln $"F\(.i + 16x2080:cp) is prime" +for i in 0..9 { + val ferm = fermat(i) + val fac = factors(ferm) + if len(fac) == 1 { + writeln "F{{i + sz:cp}} is prime" } else { - writeln $"F\(.i + 16x2080:cp) factors: ", .fac + writeln "F{{i + sz:cp}} factors: {{fac}}" } } diff --git a/Task/Fibonacci-n-step-number-sequences/Chipmunk-Basic/fibonacci-n-step-number-sequences.basic b/Task/Fibonacci-n-step-number-sequences/Chipmunk-Basic/fibonacci-n-step-number-sequences.basic new file mode 100644 index 0000000000..ec56103a56 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Chipmunk-Basic/fibonacci-n-step-number-sequences.basic @@ -0,0 +1,34 @@ +100 sub fib(a()) +110 erase f +120 dim f(24) +130 b = 0 +140 for x = 1 to ubound(a) +150 b = b+1 +160 f(x) = a(x) +170 next x +180 for i = b to 12+b +190 print using "#### ";f(i-b+1); +200 for j = (i-b+1) to i +210 f(i+1) = f(i+1)+f(j) +220 next j +230 next i +240 print +250 end sub +260 cls +270 print " fibonacci =>"; +280 dim a(2) +290 a(1) = 1 : a(2) = 1 +300 fib(a()) +310 print " tribonacci =>"; +320 dim a(3) +330 a(1) = 1 : a(2) = 1 : a(3) = 2 +340 fib(a()) +350 print " tetranacci =>"; +360 dim c(4) +370 c(1) = 1 : c(2) = 1 : c(3) = 2 : c(4) = 4 +380 fib(c()) +390 print " lucas =>"; +400 dim d(2) +410 d(1) = 2 : d(2) = 1 +420 fib(d()) +430 end diff --git a/Task/Fibonacci-n-step-number-sequences/QB64/fibonacci-n-step-number-sequences.qb64 b/Task/Fibonacci-n-step-number-sequences/QB64/fibonacci-n-step-number-sequences.qb64 new file mode 100644 index 0000000000..b435ca561c --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/QB64/fibonacci-n-step-number-sequences.qb64 @@ -0,0 +1,37 @@ +Rem $Dynamic + +Cls +Print " fibonacci =>"; +Dim a(1 To 2) As Integer +a(1) = 1 +a(2) = 1 +Call fib(a()) +Print " tribonacci =>"; +ReDim _Preserve a(1 To 3) +a(3) = 2 +Call fib(a()) +Print " tetranacci =>"; +ReDim _Preserve a(1 To 4) +a(4) = 4 +Call fib(a()) +Print " lucas =>"; +ReDim a(1 To 2) +a(1) = 2 +a(2) = 1 +Call fib(a()) +End + +Sub fib (a() As Integer) + Dim f(24) + b = 0 + For x = 1 To UBound(a) + b = b + 1 + f(x) = a(x) + Next x + For i = b To 12 + b + Print Using "#### "; f(i - b + 1); + For j = (i - b + 1) To i + f(i + 1) = f(i + 1) + f(j) + Next j + Next i +End Sub diff --git a/Task/Fibonacci-n-step-number-sequences/QBasic/fibonacci-n-step-number-sequences.basic b/Task/Fibonacci-n-step-number-sequences/QBasic/fibonacci-n-step-number-sequences.basic new file mode 100644 index 0000000000..187dffd3ca --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/QBasic/fibonacci-n-step-number-sequences.basic @@ -0,0 +1,35 @@ +DECLARE SUB fib (a() AS INTEGER) + +CLS +PRINT " fibonacci =>"; +DIM a(1 TO 2) AS INTEGER +a(1) = 1: a(2) = 1 +CALL fib(a()) +PRINT " tribonacci =>"; +DIM b(1 TO 3) AS INTEGER +b(1) = 1: b(2) = 1: b(3) = 2 +CALL fib(b()) +PRINT " tetranacci =>"; +DIM c(1 TO 4) AS INTEGER +c(1) = 1: c(2) = 1: c(3) = 2: c(4) = 4 +CALL fib(c()) +PRINT " lucas =>"; +DIM d(1 TO 2) AS INTEGER +d(1) = 2: d(2) = 1 +CALL fib(d()) +END + +SUB fib (a() AS INTEGER) + DIM f(24) + b = 0 + FOR x = 1 TO UBOUND(a) + b = b + 1 + f(x) = a(x) + NEXT x + FOR i = b TO 12 + b + PRINT USING "#### "; f(i - b + 1); + FOR j = (i - b + 1) TO i + f(i + 1) = f(i + 1) + f(j) + NEXT j + NEXT i +END SUB diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs index 7d1f929f9b..8206515707 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs @@ -1,44 +1,7 @@ -import Data.List (transpose) +import Data.List (unfoldr) -fib - :: (Integral b, Num a) - => b -> a -fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately --- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1 -fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n) +fibs :: [Integer] +fibs = unfoldr (\(x, y) -> Just (x, (y, x + y))) (0, 1) --- Code adapted from Matrix exponentiation operator task --------------------- -(<+>) - :: Num c - => [c] -> [c] -> [c] -(<+>) = zipWith (+) - -(<*>) - :: Num a - => [a] -> [a] -> a -(<*>) = (sum .) . zipWith (*) - -newtype Mat a = Mat - { unMat :: [[a]] - } deriving (Eq) - -instance Show a => - Show (Mat a) where - show xm = "Mat " ++ show (unMat xm) - -instance Num a => - Num (Mat a) where - negate xm = Mat $ map (map negate) $ unMat xm - xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym) - xm * ym = - Mat - [ [ xs Main.<*> ys -- to distinguish from standard applicative operator - | ys <- transpose $ unMat ym ] - | xs <- unMat xm ] - fromInteger n = Mat [[fromInteger n]] - abs = undefined - signum = undefined - --- TEST ---------------------------------------------------------------------- -main :: IO () -main = (print . take 10 . show . fib) (10 ^ 5) +fib n :: Integer -> Integer +fib n = fibs !! n diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs index 593d8551aa..7d1f929f9b 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs @@ -1,35 +1,44 @@ -import Control.Arrow ((&&&)) +import Data.List (transpose) -fibstep :: (Integer, Integer) -> (Integer, Integer) -fibstep (a, b) = (b, a + b) +fib + :: (Integral b, Num a) + => b -> a +fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately +-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1 +fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n) -fibnums :: [Integer] -fibnums = map fst $ iterate fibstep (0, 1) +-- Code adapted from Matrix exponentiation operator task --------------------- +(<+>) + :: Num c + => [c] -> [c] -> [c] +(<+>) = zipWith (+) -fibN2 :: Integer -> (Integer, Integer) -fibN2 m - | m < 10 = iterate fibstep (0, 1) !! fromIntegral m -fibN2 m = fibN2_next (n, r) (fibN2 n) - where - (n, r) = quotRem m 3 +(<*>) + :: Num a + => [a] -> [a] -> a +(<*>) = (sum .) . zipWith (*) -fibN2_next (n, r) (f, g) - | r == 0 = (a, b) -- 3n ,3n+1 - | r == 1 = (b, c) -- 3n+1,3n+2 - | r == 2 = (c, d) -- 3n+2,3n+3 (*) - where - a = - 5 * f ^ 3 + - if even n - then 3 * f - else (-3 * f) -- 3n - b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 - c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 - d = - 5 * g ^ 3 + - if even n - then (-3 * g) - else 3 * g -- 3(n+1) (*) +newtype Mat a = Mat + { unMat :: [[a]] + } deriving (Eq) +instance Show a => + Show (Mat a) where + show xm = "Mat " ++ show (unMat xm) + +instance Num a => + Num (Mat a) where + negate xm = Mat $ map (map negate) $ unMat xm + xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym) + xm * ym = + Mat + [ [ xs Main.<*> ys -- to distinguish from standard applicative operator + | ys <- transpose $ unMat ym ] + | xs <- unMat xm ] + fromInteger n = Mat [[fromInteger n]] + abs = undefined + signum = undefined + +-- TEST ---------------------------------------------------------------------- main :: IO () -main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) +main = (print . take 10 . show . fib) (10 ^ 5) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs index c69d736bc9..593d8551aa 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs @@ -1,2 +1,35 @@ - *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) -(208988,"19532821287077577316") +import Control.Arrow ((&&&)) + +fibstep :: (Integer, Integer) -> (Integer, Integer) +fibstep (a, b) = (b, a + b) + +fibnums :: [Integer] +fibnums = map fst $ iterate fibstep (0, 1) + +fibN2 :: Integer -> (Integer, Integer) +fibN2 m + | m < 10 = iterate fibstep (0, 1) !! fromIntegral m +fibN2 m = fibN2_next (n, r) (fibN2 n) + where + (n, r) = quotRem m 3 + +fibN2_next (n, r) (f, g) + | r == 0 = (a, b) -- 3n ,3n+1 + | r == 1 = (b, c) -- 3n+1,3n+2 + | r == 2 = (c, d) -- 3n+2,3n+3 (*) + where + a = + 5 * f ^ 3 + + if even n + then 3 * f + else (-3 * f) -- 3n + b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 + c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 + d = + 5 * g ^ 3 + + if even n + then (-3 * g) + else 3 * g -- 3(n+1) (*) + +main :: IO () +main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs index 7f0a39dbc2..c69d736bc9 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs @@ -1 +1,2 @@ -f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth + *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) +(208988,"19532821287077577316") diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs index dd052ec7a3..7f0a39dbc2 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs @@ -1 +1 @@ -g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth +f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs new file mode 100644 index 0000000000..dd052ec7a3 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs @@ -0,0 +1 @@ +g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth diff --git a/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur b/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur index fa8ff6700e..1eaa61b5f6 100644 --- a/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur +++ b/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur @@ -1,3 +1,3 @@ -val .fibonacci = fn(.x) if(.x < 2: .x ; self(.x - 1) + self(.x - 2)) +val fibonacci = fn x:if(x < 2: x ; fn((x - 1)) + fn((x - 2))) -writeln map .fibonacci, series 2..20 +writeln map(fibonacci, series(2..20)) diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.parigp b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.parigp index 5af4b4f310..94a6418871 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.parigp +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.parigp @@ -1 +1 @@ -fib(n)=n--;polchebyshev(n,2,I/2)*I^n; +fib(n)=real(2/sqrt(5)/I^n*sinh(n*log(I*(1+sqrt(5))/2)))\/1; diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.parigp b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.parigp index 8620df4d05..5af4b4f310 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.parigp +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.parigp @@ -1 +1 @@ -fib(n)=abs(polchebyshev(n-1,2,I/2)); +fib(n)=n--;polchebyshev(n,2,I/2)*I^n; diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.parigp b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.parigp index 49a2f5b231..8620df4d05 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.parigp +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.parigp @@ -1,7 +1 @@ -matantihadamard(n)={ - matrix(n,n,i,j, - my(t=j-i+1); - if(t<1,t%2,t<3) - ); -} -fib(n)=matdet(matantihadamard(n)) +fib(n)=abs(polchebyshev(n-1,2,I/2)); diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.parigp b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.parigp index 78ccd47534..49a2f5b231 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.parigp +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.parigp @@ -1,7 +1,7 @@ -fib(n)= -{ - my(g=2^(n+1)-1); - sum(i=2^(n-1),2^n-1, - bitor(i,i<<1)==g +matantihadamard(n)={ + matrix(n,n,i,j, + my(t=j-i+1); + if(t<1,t%2,t<3) ); } +fib(n)=matdet(matantihadamard(n)) diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.parigp b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.parigp index 2f2e9ab577..78ccd47534 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.parigp +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.parigp @@ -1 +1,7 @@ -fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k +fib(n)= +{ + my(g=2^(n+1)-1); + sum(i=2^(n-1),2^n-1, + bitor(i,i<<1)==g + ); +} diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-19.parigp b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-19.parigp new file mode 100644 index 0000000000..2f2e9ab577 --- /dev/null +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-19.parigp @@ -0,0 +1 @@ +fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k diff --git a/Task/Fibonacci-sequence/PL-0/fibonacci-sequence.pl0 b/Task/Fibonacci-sequence/PL-0/fibonacci-sequence.pl0 index ef184c2558..c65591c33a 100644 --- a/Task/Fibonacci-sequence/PL-0/fibonacci-sequence.pl0 +++ b/Task/Fibonacci-sequence/PL-0/fibonacci-sequence.pl0 @@ -8,5 +8,5 @@ begin tmp := b; b := a + b; a := tmp; i := i + 1 end; - ! b; + ! b end. diff --git a/Task/File-input-output/FutureBasic/file-input-output.basic b/Task/File-input-output/FutureBasic/file-input-output.basic index ecd46eda24..6fc45a678d 100644 --- a/Task/File-input-output/FutureBasic/file-input-output.basic +++ b/Task/File-input-output/FutureBasic/file-input-output.basic @@ -1,39 +1,57 @@ /* Rosetta Code File input/output example -FutureBasic 7.0.14 +FutureBasic 7.0.24 Rich Love -9/25/22 - -Before running this, use TextEdit to create a file called input.txt on your desktop. -Format as plain text and create a few lines of text. -Then save. +5/11/24 */ output file "FileInputOutput.app" + +void Local fn doIt CFURLRef ParentDirectory // Create a url for the desktop ParentDirectory = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) -CFURLRef inputURL // Create a url for input.txt on the desktop -inputURL = fn URLByAppendingPathComponent( ParentDirectory, @"input.txt" ) - CFURLRef outputURL // Create a url for output.txt on the desktop outputURL = fn URLByAppendingPathComponent( ParentDirectory, @"output.txt" ) -open "O", 1, outputURL -open "I", 2, inputURL + +CFURLRef inputURL = openpanel( 1, @"Open a text file",@"txt") +if inputURL = NULL then end str255 dataLine +dataLine = "" +if fn FileManagerContentsAtURL(inputURL) <> NULL +open "I", 1, inputURL +open "O", 2, outputURL -While Not Eof(2) - Line Input #2, dataLine - Print #1, dataLine +While Not Eof(1) +Line Input #1, dataLine +Print #2, dataLine Wend - -Close #1 Close #2 - +Close #1 +alert 3,,@"File created on Desktop",@"output.txt",@"OK" end +else +alert 3,,@"File Not Found on Desktop",@"input.txt",@"OK" +end +end if + +end fn + +void local fn DoAppEvent( ev as long ) +select (ev) +case _appDidFinishLaunching +fn doIt +end select +end fn + + +on AppEvent fn DoAppEvent + + +handleevents diff --git a/Task/File-input-output/PascalABC.NET/file-input-output.pas b/Task/File-input-output/PascalABC.NET/file-input-output.pas new file mode 100644 index 0000000000..d29ad1ed55 --- /dev/null +++ b/Task/File-input-output/PascalABC.NET/file-input-output.pas @@ -0,0 +1,4 @@ +begin + var s := ReadAllText('input.txt'); + WriteAllText('output.txt',s); +end. diff --git a/Task/File-size-distribution/Jq/file-size-distribution.jq b/Task/File-size-distribution/Jq/file-size-distribution.jq new file mode 100644 index 0000000000..efa5ac0150 --- /dev/null +++ b/Task/File-size-distribution/Jq/file-size-distribution.jq @@ -0,0 +1,15 @@ +# bag of words +def bow(stream): + reduce stream as $word ({}; .[($word|tostring)] += 1); + +# `stream` is expected to be a stream of non-negative numbers or numeric strings. +# The output is a stream of [bucket, count] pairs, sorted by the value of `bucket`. +# No sorting except for the sorting of these bucket boundaries takes place. +def histogram(stream): + bow(stream) + | to_entries + | map( [(.key | tonumber), .value] ) + | sort_by(.[0]) + | .[]; + +histogram(.[] | .size | if . == 0 then 0 else 1 + (log10 | trunc) end) diff --git a/Task/File-size/PascalABC.NET/file-size.pas b/Task/File-size/PascalABC.NET/file-size.pas new file mode 100644 index 0000000000..f4a99b6adb --- /dev/null +++ b/Task/File-size/PascalABC.NET/file-size.pas @@ -0,0 +1,6 @@ +uses System.IO; + +begin + FileInfo.Create('input.txt').Length.Println; + FileInfo.Create('/input.txt').Length.Println; +end. diff --git a/Task/Filter/Langur/filter.langur b/Task/Filter/Langur/filter.langur index ab9e005e2b..330dbc2ec2 100644 --- a/Task/Filter/Langur/filter.langur +++ b/Task/Filter/Langur/filter.langur @@ -1,4 +1,4 @@ -val .list = series 7 +val zlist = series(7) -writeln " list: ", .list -writeln "filtered: ", filter fn{div 2}, .list +writeln " list: ", zlist +writeln "filtered: ", filter(fn{div 2}, zlist) diff --git a/Task/Filter/PascalABC.NET/filter.pas b/Task/Filter/PascalABC.NET/filter.pas new file mode 100644 index 0000000000..3af872fd92 --- /dev/null +++ b/Task/Filter/PascalABC.NET/filter.pas @@ -0,0 +1,5 @@ +begin + var a := Arr(1..10); + var even := a.Where(x -> x mod 2 = 0); + even.Print +end. diff --git a/Task/Find-Chess960-starting-position-identifier/Jq/find-chess960-starting-position-identifier.jq b/Task/Find-Chess960-starting-position-identifier/Jq/find-chess960-starting-position-identifier.jq new file mode 100644 index 0000000000..d0b15801d3 --- /dev/null +++ b/Task/Find-Chess960-starting-position-identifier/Jq/find-chess960-starting-position-identifier.jq @@ -0,0 +1,82 @@ +### Generic functions + +# Output: a stream of the characters (glyphs) of the input string +def chars: split("")[]; + +def count(s): reduce s as $x (0; .+1); + +# Variant of index/1 +def index($target; $offset): + if $offset >= length then null + else (.[$offset:]|index($target)) as $ix + | if $ix then $ix + $offset + else null + end + end; + +### Chess: + +def glyphs: "♜♞♝♛♚♖♘♗♕♔"; + +def letters: "RNBQKRNBQK"; + +def names: { "R": "rook", "N": "knight", "B": "bishop", "Q": "queen", "K": "king" }; + +# a map of glyphs to letters +def g2lMap: + [glyphs,letters] + | map(split("")) + | transpose + | map( {(.[0]): .[1]}) + | add; + +# convert glyphs to letters +# Input: pieces (a string) +# Output: a string +def g2l: + g2lMap as $g2lMap + | reduce chars as $p (""; . + $g2lMap[$p] ); + +def ntable: + { "01":0, "02":1, "03":2, "04":3, "12":4, "13":5, "14":6, "23":7, "24":8, "34":9 }; + +# Input: pieces, a string +def spid: + # convert glyphs to letters + g2l as $pieces + # check for errors + | last( + if $pieces|length != 8 then "There must be exactly 8 pieces." | error end, + ("KQ"|split("")[] as $one + | if 1 != count( $pieces|chars | select(. == $one)) then "There must be one \(names[$one])" | error end), + ("RNB" | split("")[] as $two + | if 2 != count( $pieces|chars | select(. == $two)) then "There must be two \(names[$two])" | error end)) + | ($pieces | index("R")) as $r1 + | ($pieces | index("R"; $r1 + 1)) as $r2 + | ($pieces|index("K")) as $k + | if ($k < $r1 or $k > $r2) then "The king must be between the rooks." | error end + | ($pieces|index("B")) as $b1 + | ($pieces|index("B"; $b1 + 1)) as $b2 + | if (($b2 - $b1) % 2 == 0) then "The bishops must be on opposite color squares." | error end + + # compute SP_ID + | ($pieces|sub("Q"; "")|gsub("B"; "")) as $piecesN + | ($piecesN|index("N")) as $n1 + | ($piecesN|index("N"; $n1+1)) as $n2 + + | ntable["\($n1)\($n2)"] as $N + + | ($pieces|gsub("B"; "")) as $piecesQ + | ($piecesQ|index("Q")) as $Q + | ("0246" | index($b1|tostring)) as $D + | if $D == null + then {D: ("0246"|index($b2|tostring)), + L: ("1357"|index($b1|tostring)) } + else {D: $D, + L: ("1357"|index($b2|tostring))} + end + | 96*$N + 16*$Q + 4*.D + .L ; + +# The task +"♕♘♖♗♗♘♔♖", "♖♘♗♕♔♗♘♖", "♜♛♞♝♝♚♜♞", "♜♞♛♝♝♚♜♞" +| "\(.) or \(g2l) has SP-ID of \(spid)" diff --git a/Task/Find-common-directory-path/K/find-common-directory-path.k b/Task/Find-common-directory-path/K/find-common-directory-path.k new file mode 100644 index 0000000000..6b7ec47690 --- /dev/null +++ b/Task/Find-common-directory-path/K/find-common-directory-path.k @@ -0,0 +1,6 @@ +fcp:{"/"/(+/*\1=#'?'+y\'x)#("/"\ x@0)} + +/example usage + l:("/home/user1/tmp/coverage/test"; "/home/user1/tmp/covert/operator"; "/home/user1/tmp/coven/members") + fcp[l;"/"] +"/home/user1/tmp" diff --git a/Task/Find-common-directory-path/PascalABC.NET/find-common-directory-path.pas b/Task/Find-common-directory-path/PascalABC.NET/find-common-directory-path.pas new file mode 100644 index 0000000000..7bdbcc5ad1 --- /dev/null +++ b/Task/Find-common-directory-path/PascalABC.NET/find-common-directory-path.pas @@ -0,0 +1,21 @@ +function CommonPrefix(arrs: array of array of string): array of string; +begin + var min: integer := arrs.Min(a -> a.Length); + // транспонируем эту часть + var at := ArrGen(min, j -> ArrGen(arrs.Length, i -> arrs[i][j])); + Result := at.TakeWhile(x -> x.Skip(1).All(y -> y = x.First)).Select(a -> a[0]).ToArray +end; + +function CommonDirectoryPath(paths: array of string; sep: char := '/'): string; +begin + var arrs := paths.Select(a -> a.Split(sep)).ToArray; + Result := CommonPrefix(arrs).JoinToString(sep); +end; + +begin + //CommonPrefix(||'ww','ee'|,|'ww','ee','hh'|,|'ww','ee','tt'||).Print + print(CommonDirectoryPath(| + '/home/user1/tmp/coverage/test', + '/home/user1/tmp/covert/operator', + '/home/user1/tmp/coven/members'|)) +end. diff --git a/Task/Find-duplicate-files/Jq/find-duplicate-files.jq b/Task/Find-duplicate-files/Jq/find-duplicate-files.jq new file mode 100644 index 0000000000..cccd6d21d4 --- /dev/null +++ b/Task/Find-duplicate-files/Jq/find-duplicate-files.jq @@ -0,0 +1,9 @@ +# The following jq program assumes the input consists of a JSON array of objects having +# keys named "hash" and "filename". +def dictionary(stream; f; g): + reduce stream as $x ({}; .[($x|f)] += [$x|g]); + +dictionary(inputs[]; .hash; .filename) +| to_entries[].value +| select(length > 1) +| [.[]] diff --git a/Task/Find-if-a-point-is-within-a-triangle/11l/find-if-a-point-is-within-a-triangle.11l b/Task/Find-if-a-point-is-within-a-triangle/11l/find-if-a-point-is-within-a-triangle.11l index 307688a44b..1259c17d99 100644 --- a/Task/Find-if-a-point-is-within-a-triangle/11l/find-if-a-point-is-within-a-triangle.11l +++ b/Task/Find-if-a-point-is-within-a-triangle/11l/find-if-a-point-is-within-a-triangle.11l @@ -14,14 +14,7 @@ F distanceSquarePointToSegment(p1, p2, p) R pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength R sqlen(p - p2) -T Triangle - (Float, Float) p1, p2, p3 - - F (p1, p2, p3) - .p1 = p1 - .p2 = p2 - .p3 = p3 - +T Triangle((DVec2 p1, DVec2 p2, DVec2 p3)) F String() R ‘Triangle[’(.p1)‘, ’(.p2)‘, ’(.p3)‘]’ diff --git a/Task/Find-limit-of-recursion/PascalABC.NET/find-limit-of-recursion.pas b/Task/Find-limit-of-recursion/PascalABC.NET/find-limit-of-recursion.pas new file mode 100644 index 0000000000..a6e57f4e83 --- /dev/null +++ b/Task/Find-limit-of-recursion/PascalABC.NET/find-limit-of-recursion.pas @@ -0,0 +1,9 @@ +procedure Recur(i: integer); +begin + System.Console.WriteLine(i); + Recur(i + 1); +end; + +begin + Recur(0); +end. diff --git a/Task/Find-the-intersection-of-two-lines/ALGOL-W/find-the-intersection-of-two-lines.alg b/Task/Find-the-intersection-of-two-lines/ALGOL-W/find-the-intersection-of-two-lines.alg new file mode 100644 index 0000000000..db5ca3d348 --- /dev/null +++ b/Task/Find-the-intersection-of-two-lines/ALGOL-W/find-the-intersection-of-two-lines.alg @@ -0,0 +1,33 @@ +begin % find the intersection of two lines % + + record Point ( real x, y ); + record Line ( real m, c ); % y = mx + c % + + % returns the line that passes through p1 and p2 % + reference(Line) procedure findLine ( reference(Point) value p1, p2 ) ; + if x(p1) = x(p2) then begin % the line is verticval % + Line( 0, x(p1) ) + end + else begin % the line is not vertical % + real m1; + m1 := ( y(p1) - y(p2) ) / ( x(p1) - x(p2) ); + Line( m1, y(p1) - ( m1 * x(p1) ) ) + end findLine ; + + % returns the intersection of two lines % + % - the lines must be distinct and not parallel % + reference(Point) procedure intersection ( reference(Line) value l1, l2 ) ; + begin + real x; + x := ( c(l2) - c(l1) ) / ( m(l1) - m(l2) ); + Point( x, ( m(l1) * x ) + c(l1) ) + end intersection ; + + begin % find the intersection of the lines as per the task % + reference(Point) i; + i := intersection( findLine( Point( 4.0, 0.0 ), Point( 6.0, 10.0 ) ) + , findLine( Point( 0.0, 3.0 ), Point( 10.0, 7.0 ) ) + ); + write( r_format := "A", r_w := 8, r_d := 4, x(i), y(i) ) + end +end. diff --git a/Task/Find-the-intersection-of-two-lines/Python/find-the-intersection-of-two-lines-4.py b/Task/Find-the-intersection-of-two-lines/Python/find-the-intersection-of-two-lines-4.py new file mode 100644 index 0000000000..ca6053b96f --- /dev/null +++ b/Task/Find-the-intersection-of-two-lines/Python/find-the-intersection-of-two-lines-4.py @@ -0,0 +1,19 @@ +import pygame as pg + +def segment_intersection(a, b, c, d): + """ returns a pygame.Vector2 or None if there is no intersection """ + ab, cd, ac = a - b, c - d, a - c + if not (denom:= ab.x * cd.y - ab.y * cd.x): + return + + t = (ac.x * cd.y - ac.y * cd.x) / denom + u = -(ab.x * ac.y - ab.y * ac.x) / denom + if 0 <= t <= 1 and 0 <= u <= 1: + return a.lerp(b, t) + + +if __name__ == '__main__': + a,b = pg.Vector2(4,0), pg.Vector2(6,10) # try (4, 0), (6, 4) + c,d = pg.Vector2(0,3), pg.Vector2(10,7) # for non intersecting test + pt = segment_intersection(a, b, c, d) + print(pt) diff --git a/Task/Find-the-missing-permutation/Uiua/find-the-missing-permutation.uiua b/Task/Find-the-missing-permutation/Uiua/find-the-missing-permutation.uiua new file mode 100644 index 0000000000..166b1bdb66 --- /dev/null +++ b/Task/Find-the-missing-permutation/Uiua/find-the-missing-permutation.uiua @@ -0,0 +1,2 @@ +Perms ← ⊜∘⊸≠@ "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" +/⊂≡(▽-⟜/↥:⊕⊃⊢⧻⊛.)⍉ Perms diff --git a/Task/First-class-functions/PascalABC.NET/first-class-functions.pas b/Task/First-class-functions/PascalABC.NET/first-class-functions.pas new file mode 100644 index 0000000000..091decbbb2 --- /dev/null +++ b/Task/First-class-functions/PascalABC.NET/first-class-functions.pas @@ -0,0 +1,15 @@ +function Cube(x: real) := x**3; +function CubeRoot(x: real) := x**(1/3); + +function Composition(f1,f2: T -> T): T -> T := x -> f1(f2(x)); + +begin + var A := Arr(Sin,Cos,Cube); + var B := Arr(ArcSin,ArcCos,CubeRoot); + for var i:=0 to A.Length-1 do + Println(Composition(A[i],B[i])(0.5)); + + // Build-in composition f1 * f2 + foreach var (f1,f2) in A.Zip(B) do + Println((f1 * f2)(0.5)); +end. diff --git a/Task/First-perfect-square-in-base-n-with-n-unique-digits/Uiua/first-perfect-square-in-base-n-with-n-unique-digits.uiua b/Task/First-perfect-square-in-base-n-with-n-unique-digits/Uiua/first-perfect-square-in-base-n-with-n-unique-digits.uiua index f1237f1504..d4f0b612f4 100644 --- a/Task/First-perfect-square-in-base-n-with-n-unique-digits/Uiua/first-perfect-square-in-base-n-with-n-unique-digits.uiua +++ b/Task/First-perfect-square-in-base-n-with-n-unique-digits/Uiua/first-perfect-square-in-base-n-with-n-unique-digits.uiua @@ -1,15 +1,14 @@ -BaseN ← setinv(↘2⍢(⊂⊂:⊙(⊃(↙1)(↘2))⊂⊃(⌊÷)◿°⊟↙2.)(>0 ⊢↘1)⊟|/+×ⁿ:⊙(⇌⇡⧻.)) -IsPan ← =⧻◴: # IsPan 3 [0 1 2] -# Smallest pan number for given base -# = [1 0 2 3 4...] in base n -MinPanBase ← °BaseN ⟜(↙:⊂[1 0]↘2⇡+1.) -MinPanSqrBase ← ⊙◌⍢(+1)(¬IsPan :BaseN ,×.) ⌊√MinPanBase. -ShowMinPan ← ( - ≡( - &pf "\t" &pf . &pf "Base " - MinPanSqrBase . - &p BaseN : &pf "\t" &pf. × &pf "\t" &pf. . - ) -) +Base₁₀ ← /+×ⁿ:⊙(⇌⇡⧻.) # (b, [digits]) -> n +BaseN ← ⊙◌⊂⍢(⊙⊂⌊⊃÷◿⊃⋅⋅∘⊙⊙∘|≤⊙⋅∘)⊙[]: # (b, n) -> [digits] -⍜now (ShowMinPan ↘2⇡13) +IsPan ← =⧻◴: # IsPan 3 [0 1 2] -> true +# Smallest pan number for given base +# will always be = [1 0 2 3 4...] in base n +MinPanBase ← Base₁₀ ⟜(↙:⊂1_0↘2⇡+1.) +# Take sqrt of the smallest pan number and inc until found. +MinPanSqrBase ← ⊙◌⍢(+1|¬IsPan:BaseN,×.) ⌊√MinPanBase. +ShowMinPan ← ( + ⊃(⊙∘|⋅(×.)|BaseN ⊙(×.)) ⟜MinPanSqrBase + &p $"Base _\t_\t_\t_\t" +) +⍜now (≡ShowMinPan ↘2⇡13) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp index 2afcb58497..be01ddcb5d 100644 --- a/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp @@ -1,20 +1,15 @@ -;; Project : FizzBuzz +(defun range (min max) + (loop + :for x :from min :to max + :collect x)) -(defun fizzbuzz (&optional n) - (let ((n (or n 1))) - (if (> n 100) - nil - (progn - (let ((mult-3 (is-mult-p n 3)) - (mult-5 (is-mult-p n 5))) - (if mult-3 - (princ "Fizz")) - (if mult-5 - (princ "Buzz")) - (if (not (or mult-3 mult-5)) - (princ n)) - (princ #\linefeed) - (fizzbuzz (+ n 1))))))) -(defun is-mult-p (n multiple) - (= (rem n multiple) 0)) -(fizzbuzz 1) +(defun fizzbuzz () + (map 'nil #'(lambda (n) + (princ + (cond + ((zerop (mod n 15)) "FizzBuzz!") + ((zerop (mod n 5)) "Buzz!") + ((zerop (mod n 3)) "Fizz!") + (t n)) + (terpri))) + (range 1 100))) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-9.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-9.lisp new file mode 100644 index 0000000000..2afcb58497 --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-9.lisp @@ -0,0 +1,20 @@ +;; Project : FizzBuzz + +(defun fizzbuzz (&optional n) + (let ((n (or n 1))) + (if (> n 100) + nil + (progn + (let ((mult-3 (is-mult-p n 3)) + (mult-5 (is-mult-p n 5))) + (if mult-3 + (princ "Fizz")) + (if mult-5 + (princ "Buzz")) + (if (not (or mult-3 mult-5)) + (princ n)) + (princ #\linefeed) + (fizzbuzz (+ n 1))))))) +(defun is-mult-p (n multiple) + (= (rem n multiple) 0)) +(fizzbuzz 1) diff --git a/Task/FizzBuzz/Langur/fizzbuzz-1.langur b/Task/FizzBuzz/Langur/fizzbuzz-1.langur deleted file mode 100644 index d5e5445c4f..0000000000 --- a/Task/FizzBuzz/Langur/fizzbuzz-1.langur +++ /dev/null @@ -1,3 +0,0 @@ -for .i of 100 { - writeln switch(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i) -} diff --git a/Task/FizzBuzz/Langur/fizzbuzz-2.langur b/Task/FizzBuzz/Langur/fizzbuzz-2.langur deleted file mode 100644 index 462cdfb81b..0000000000 --- a/Task/FizzBuzz/Langur/fizzbuzz-2.langur +++ /dev/null @@ -1,3 +0,0 @@ -for .i of 100 { - writeln if(.i div 15: "FizzBuzz"; .i div 5: "Buzz"; .i div 3: "Fizz"; .i) -} diff --git a/Task/FizzBuzz/Langur/fizzbuzz.langur b/Task/FizzBuzz/Langur/fizzbuzz.langur new file mode 100644 index 0000000000..d932f4e024 --- /dev/null +++ b/Task/FizzBuzz/Langur/fizzbuzz.langur @@ -0,0 +1,3 @@ +for i of 100 { + writeln switch(0; i rem 15: "FizzBuzz"; i rem 5: "Buzz"; i rem 3: "Fizz"; i) +} diff --git a/Task/FizzBuzz/PascalABC.NET/fizzbuzz.pas b/Task/FizzBuzz/PascalABC.NET/fizzbuzz.pas new file mode 100644 index 0000000000..88b4afba1d --- /dev/null +++ b/Task/FizzBuzz/PascalABC.NET/fizzbuzz.pas @@ -0,0 +1,10 @@ +begin + for var i:=1 to 100 do + if i mod 15 = 0 then + Print('FizzBuzz') + else if i mod 3 = 0 then + Print('Fizz') + else if i mod 5 = 0 then + Print('Buzz') + else Print(i) +end. diff --git a/Task/FizzBuzz/Q/fizzbuzz-1.q b/Task/FizzBuzz/Q/fizzbuzz-1.q index ddc5895375..5f657a4e59 100644 --- a/Task/FizzBuzz/Q/fizzbuzz-1.q +++ b/Task/FizzBuzz/Q/fizzbuzz-1.q @@ -1 +1 @@ -{(2 sv not x mod/:5 3)'[;`fizz;`buzz;`fizzbuzz]`$string x} +{(`$string x)^`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0} diff --git a/Task/FizzBuzz/Q/fizzbuzz-2.q b/Task/FizzBuzz/Q/fizzbuzz-2.q index 0dc95fabd9..66d6c2f2af 100644 --- a/Task/FizzBuzz/Q/fizzbuzz-2.q +++ b/Task/FizzBuzz/Q/fizzbuzz-2.q @@ -1,4 +1,4 @@ q)/ Fizzbuzz -q)fb:{(2 sv not x mod/:5 3)'[;`fizz;`buzz;`fizzbuzz]`$string x} +q)fb:{(`$string x)^`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0} q)fb 1+til 20 `1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz diff --git a/Task/FizzBuzz/Q/fizzbuzz-3.q b/Task/FizzBuzz/Q/fizzbuzz-3.q index 091461983f..e9e1c43a46 100644 --- a/Task/FizzBuzz/Q/fizzbuzz-3.q +++ b/Task/FizzBuzz/Q/fizzbuzz-3.q @@ -1,17 +1,18 @@ q)show x:1+til 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -q)x mod/:5 3 -1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 -1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 -q)not x mod/:5 3 -00001000010000100001b -00100100100100100100b -q)show i:2 sv not x mod/:5 3 / binary decode -0 0 1 0 2 1 0 0 1 2 0 1 0 0 3 0 0 1 0 2 -q)(`$string x;`fizz;`buzz;`fizzbuzz) +q)x mod\:15 5 3 +1 1 1 +2 2 2 +3 3 0 +4 4 1 +5 0 2 +6 1 0 +.. +q)(x mod\:15 5 3)?'0 +3 3 2 3 1 2 3 3 2 1 3 2 3 3 0 3 3 2 3 1 +q)`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0 / substitutions +```fizz``buzz`fizz```fizz`buzz``fizz```fizzbuzz```fizz``buzz +q)`$string x / numbers => symbols `1`2`3`4`5`6`7`8`9`10`11`12`13`14`15`16`17`18`19`20 -`fizz -`buzz -`fizzbuzz -q)i'[`$string x;`fizz;`buzz;`fizzbuzz] / Case iterator +q)(`$string x)^`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0 / replace nulls with numbers `1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz diff --git a/Task/FizzBuzz/Uiua/fizzbuzz.uiua b/Task/FizzBuzz/Uiua/fizzbuzz.uiua index cfe142f2d5..c870fe1baa 100644 --- a/Task/FizzBuzz/Uiua/fizzbuzz.uiua +++ b/Task/FizzBuzz/Uiua/fizzbuzz.uiua @@ -1 +1 @@ -⟨⟨⟨&p|&p"Fizz"◌⟩=0◿3.|&p"Buzz"◌⟩=0◿5.|&p"Fizzbuzz"◌⟩=0◿15.+1⇡100 +⟨&p|&p"Fizz"|&p"Buzz"|&p"Fizzbuzz"⟩°⋯⍉=0⊞◿3_5.+1⇡100 diff --git a/Task/Flatten-a-list/Emacs-Lisp/flatten-a-list.l b/Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-1.l similarity index 100% rename from Task/Flatten-a-list/Emacs-Lisp/flatten-a-list.l rename to Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-1.l diff --git a/Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-2.l b/Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-2.l new file mode 100644 index 0000000000..939c2dd810 --- /dev/null +++ b/Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-2.l @@ -0,0 +1 @@ +(flatten-tree mylist) diff --git a/Task/Flatten-a-list/PascalABC.NET/flatten-a-list.pas b/Task/Flatten-a-list/PascalABC.NET/flatten-a-list.pas new file mode 100644 index 0000000000..4c3aff9618 --- /dev/null +++ b/Task/Flatten-a-list/PascalABC.NET/flatten-a-list.pas @@ -0,0 +1,16 @@ +function Flatten(lst: List): List; +begin + Result := new List; + foreach var x in lst do + if x is List then + Result.Addrange(Flatten(x as List)) + else Result.Add(x) +end; + +function LstObj(params a: array of object): List := new List(a); + +begin + var lst := LstObj(1,LstObj(2, LstObj(3,4), LstObj(5,6)), LstObj(LstObj(7,8), 9)); + Println(lst); + Println(Flatten(lst)); +end. diff --git a/Task/Flatten-a-list/Refal/flatten-a-list.refal b/Task/Flatten-a-list/Refal/flatten-a-list.refal new file mode 100644 index 0000000000..b60af64c4b --- /dev/null +++ b/Task/Flatten-a-list/Refal/flatten-a-list.refal @@ -0,0 +1,10 @@ +$ENTRY Go { + , ((1) 2 ((3 4) 5) ((())) (((6))) 7 8 ()): e.List + = ' > +}; + +Flatten { + = ; + s.I e.X = s.I ; + (e.X) e.Y = ; +}; diff --git a/Task/Flatten-a-list/Uiua/flatten-a-list.uiua b/Task/Flatten-a-list/Uiua/flatten-a-list.uiua new file mode 100644 index 0000000000..346aa99a26 --- /dev/null +++ b/Task/Flatten-a-list/Uiua/flatten-a-list.uiua @@ -0,0 +1 @@ +⍥/◇⊂∞{{1} 2 {{3 4} 5} {{{}}} {{{6}}} 7 8 {}} diff --git a/Task/Flipping-bits-game/Quackery/flipping-bits-game.quackery b/Task/Flipping-bits-game/Quackery/flipping-bits-game.quackery new file mode 100644 index 0000000000..85e6f72690 --- /dev/null +++ b/Task/Flipping-bits-game/Quackery/flipping-bits-game.quackery @@ -0,0 +1,60 @@ + [ [] over times + [ over [] swap times + [ 2 random join ] + nested join ] + nip ] is makeboard ( n --> [ ) + + [ [] swap witheach [ not join ] ] is invert ( [ --> [ ) + + [ 2dup peek invert unrot poke ] is fliprow ( [ n --> [ ) + + [ dip transpose fliprow transpose ] is flipcolumn ( [ n --> [ ) + + [ dup + [ dup size dup * times + [ dup size random + 2 random iff + fliprow + else flipcolumn ] + 2dup != until ] + nip ] is mix ( [ --> [ ) + + [ say " " + dup size times + [ sp i^ char a + emit ] + witheach + [ cr sp i^ echo say ":" + witheach + [ sp echo ] ] ] is display ( [ --> ) + + [ cr $ "a..., or 0...: " + input $ "." join + trim 0 peek lower + 2dup char a rot over + + within iff + [ nip char a - + ' flipcolumn ] + done + 2dup char 0 rot over + + within iff + [ nip char 0 - + ' fliprow ] + done + drop again ] is getmove ( n --> n x ) + + [ 0 temp put + makeboard + dup mix + [ say "Moves: " + temp share echo cr + 1 temp tally + 2dup swap + say "Target" cr + display cr cr + say "Current" cr + display cr + dup size getmove do cr + 2dup = until ] + 2drop + temp take + say "Moves taken: " echo ] is flipbits ( n --> ) diff --git a/Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua b/Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua new file mode 100644 index 0000000000..a38d6ba848 --- /dev/null +++ b/Task/Flipping-bits-game/Uiua/flipping-bits-game.uiua @@ -0,0 +1,19 @@ +S ← 9 +Fr ← ⊙◌⍜⊡¬⊙. +Fc ← ⊙◌⍉Fr⊙(⍉.) +Shuffle ← ⍥(⟨Fr|Fc⟩<0.5⚂ ⌊×S⚂)×3S +T ← Shuffle ↯S_S 0 # Target setup. Omit `Shuffle` for plain grid. +D ← /+/+⌵-T + +# Could use A*, but this is easily solved without it. +# ◌astar(⊂⊃(≡Fr|≡Fc)⇡S¤|÷S D|=0D) +⟜[∘] Shuffle T # Shuffle and keep a copy for the output. +◌⍢( + + ⊂⊃(≡Fr|≡Fc)⇡S¤ # All neighbours. + ⊚=/↧.≡D. # Find min dist, get indices that give that. + ⊡⊢ # Pick first one. ⊡(⊡⌊×⚂⧻.) to pick at random. + ⊙⊂. # Save a copy of the new state. +| ≠0D +) +⟜($"_ steps."-1⧻)⇌ diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-2.ada b/Task/Flow-control-structures/Ada/flow-control-structures-2.ada index 158400ca3d..b793ba8f93 100644 --- a/Task/Flow-control-structures/Ada/flow-control-structures-2.ada +++ b/Task/Flow-control-structures/Ada/flow-control-structures-2.ada @@ -2,7 +2,9 @@ Outer: loop -- do something loop + if Finished then + exit Outer; -- exits both the inner and outer loops + end if; -- do something else - exit Outer; -- exits both the inner and outer loops end loop; end loop Outer; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-3.ada b/Task/Flow-control-structures/Ada/flow-control-structures-3.ada index 1af014edb3..ed66f3714c 100644 --- a/Task/Flow-control-structures/Ada/flow-control-structures-3.ada +++ b/Task/Flow-control-structures/Ada/flow-control-structures-3.ada @@ -1,7 +1,8 @@ -select - delay 10.0; - Put_Line ("Cannot finish this in 10s"); -then abort - -- do some lengthy calculation - ... -end select; +Outer: +loop + -- do something + loop + exit Outer when Finished; + -- do something else + end loop; +end loop Outer; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-4.ada b/Task/Flow-control-structures/Ada/flow-control-structures-4.ada new file mode 100644 index 0000000000..ef06de0b59 --- /dev/null +++ b/Task/Flow-control-structures/Ada/flow-control-structures-4.ada @@ -0,0 +1,8 @@ +procedure Foo is +begin + -- do something + if Nothing_More_To_Do then + return; + end if; + -- do more +end Foo; diff --git a/Task/Flow-control-structures/Ada/flow-control-structures-5.ada b/Task/Flow-control-structures/Ada/flow-control-structures-5.ada new file mode 100644 index 0000000000..1af014edb3 --- /dev/null +++ b/Task/Flow-control-structures/Ada/flow-control-structures-5.ada @@ -0,0 +1,7 @@ +select + delay 10.0; + Put_Line ("Cannot finish this in 10s"); +then abort + -- do some lengthy calculation + ... +end select; diff --git a/Task/Floyds-triangle/FutureBasic/floyds-triangle.basic b/Task/Floyds-triangle/FutureBasic/floyds-triangle.basic new file mode 100644 index 0000000000..cd7e9cb937 --- /dev/null +++ b/Task/Floyds-triangle/FutureBasic/floyds-triangle.basic @@ -0,0 +1,18 @@ +void local fn FloydsTriangle( rows as int ) + int col, row, num = 1 + + printf @"%d rows:", rows + for row = 1 to rows + for col = 1 to row + printf @"%4d\b", num + num++ + next + print + next + print +end fn + +fn FloydsTriangle( 5 ) +fn FloydsTriangle( 14 ) + +HandleEvents diff --git a/Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas b/Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas new file mode 100644 index 0000000000..4bdce7f681 --- /dev/null +++ b/Task/Floyds-triangle/PascalABC.NET/floyds-triangle.pas @@ -0,0 +1,19 @@ +procedure FloydTriangle(rows: integer); +begin + var r := 1; + for var i:=1 to rows do + begin + for var j:=1 to i do + begin + Write(r: (j>8 ? 4 : 3)); + r += 1; + end; + Writeln + end; +end; + +begin + FloydTriangle(5); + Writeln; + FloydTriangle(14); +end. diff --git a/Task/Floyds-triangle/Uiua/floyds-triangle.uiua b/Task/Floyds-triangle/Uiua/floyds-triangle.uiua index 98661007d6..041e5d1781 100644 --- a/Task/Floyds-triangle/Uiua/floyds-triangle.uiua +++ b/Task/Floyds-triangle/Uiua/floyds-triangle.uiua @@ -1,19 +1,13 @@ -Floyd ← ⇌⍥(⊂⍚(+⇡∩(+1)⊃⧻(⊢⇌))⊢.):{[1]}-1 - -JoinUsing ← ↘1/◇⊂≡(□◇⊂)↯:⊙(⧻.)□ -PadL ← ⊂/⊂↯:" " -Lengths ← ⍚∵◇∵(⧻°⋕)°□ - -PrintIt ← ( - # Create table of [last row sizes] [this row sizes] [this row numbers] - ⊢⊞⊂⊢⊢↙¯1.⍉[Lengths.] - +Floyd ← ⊜□⇌/(⊂↯.:)⟜(+1⇡/+)+1⇡ +Print ← ( + ≡(□≡(°⋕)) # Stringify terms. + ≡(⊢⬚""↯⊟∞:°□)⟜(◇/↥⧻) # Pad rows with "" to same dims. + ≡⊟¤+1≡◇⧻⊡¯1. # Find pads and couple with each. ≡( - # Calculate last row sizes - this row sizes and use to calculate paddings - ⍉⊟⊃(-:↙:⊙(⧻.)∩°□°⊟↙2)(°⋕°□⊢↘2) - &pJoinUsing " " ≡(⍚PadL°⊟) + ≡(□/◇⊂↙¯⟜(⊂↯⊙@ )∩°□°⊟)⍉ # Prepad each term. + &p/⍚⊂ # Join each row and print. ) ) - -PrintIt Floyd 4 -PrintIt Floyd 14 +Print Floyd 4 +&p"" +Print Floyd 14 diff --git a/Task/Forest-fire/Uiua/forest-fire.uiua b/Task/Forest-fire/Uiua/forest-fire.uiua new file mode 100644 index 0000000000..785847abee --- /dev/null +++ b/Task/Forest-fire/Uiua/forest-fire.uiua @@ -0,0 +1,9 @@ +S ← 60 +Pt ← 0.01 +Pf ← 0.00005 +⊞(0|⋅0)⟜NsOnFire.)200] +⇌≡∵⨬(0_0_0|0_1_0|1_0_0) +≡(▽⟜≡▽2) # Upscale diff --git a/Task/Formatted-numeric-output/ANSI-BASIC/formatted-numeric-output.basic b/Task/Formatted-numeric-output/ANSI-BASIC/formatted-numeric-output.basic new file mode 100644 index 0000000000..8cee480fb1 --- /dev/null +++ b/Task/Formatted-numeric-output/ANSI-BASIC/formatted-numeric-output.basic @@ -0,0 +1,12 @@ +100 REM Formatted numeric output +110 LET N = 7.125 +120 PRINT USING ("%%%%.###"): N +130 PRINT USING ("****.###"): N +140 PRINT USING ("####.###"): N +150 PRINT USING ("+%%%.###"): N +160 PRINT USING ("+%%%.###"): -N +170 PRINT USING (".###^^^^^"): N +180 PRINT USING ("#.###^^^^^"): N +190 PRINT USING ("##.###^^^^^"): N +200 PRINT USING ("+.###^^^^^"): -N +210 END diff --git a/Task/Formatted-numeric-output/PascalABC.NET/formatted-numeric-output.pas b/Task/Formatted-numeric-output/PascalABC.NET/formatted-numeric-output.pas new file mode 100644 index 0000000000..dea857165e --- /dev/null +++ b/Task/Formatted-numeric-output/PascalABC.NET/formatted-numeric-output.pas @@ -0,0 +1,4 @@ +## +var Pi := 3.1415926536; +Println($'{Pi,8:f2}'); +Println($'{Pi,-8:f3}!'); diff --git a/Task/Fractal-tree/11l/fractal-tree.11l b/Task/Fractal-tree/11l/fractal-tree.11l index 813cda8321..9c40657170 100644 --- a/Task/Fractal-tree/11l/fractal-tree.11l +++ b/Task/Fractal-tree/11l/fractal-tree.11l @@ -6,7 +6,7 @@ StartingAngle = 1.5 * math:pi DeltaAngle = 0.2 * math:pi -F drawTree(outfile, Float x, Float y; len, theta) -> N +F drawTree(outfile, Float x, y; len, theta) -> Void I len >= 1 V x2 = x + len * cos(theta) V y2 = y + len * sin(theta) diff --git a/Task/French-Republican-calendar/Jq/french-republican-calendar.jq b/Task/French-Republican-calendar/Jq/french-republican-calendar.jq new file mode 100644 index 0000000000..dde45845bc --- /dev/null +++ b/Task/French-Republican-calendar/Jq/french-republican-calendar.jq @@ -0,0 +1,149 @@ +include "Date" {search: "."}; + +### Generic functions + +def assertEq($p;$q): + if $p == $q + then . + else debug("assertion violation: \($p) != \($q)") as $debug | . + end; + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def trim: sub("^ *";"") | sub(" *$";""); + +# Input: string such as "12 Mar 2012" +# Output: Date +def parseDayMonthYear: + def months: + {Jan:1, Feb:2, Mar:3, Apr: 4, May: 5, Jun: 6, + Jul:7, Aug:8, Sep:9, Oct:10, Nov:11, Dec:12}; + capture("(?[0-9]+) *(?[A-Za-z]+) *(?[0-9]+)") + | .month |= months[ .[:3] ] + | map_values(tonumber) + | {year, month, day}; + +### French Republican Calendar (FRC) + +def introductionDate: Date(1792; 9; 22); + +# Use the 'continuous method' for years after 1805 +def isLeapYearFRC: + (. + 1) + | (. % 4 == 0) and ((. % 100 != 0) or (. % 400 == 0)); + +# If the numbers $year, $month, and $day specify a valid date +# in the French Republican Calendar, then emit {$year, $month, $day}; +# otherwise generate an informative error message. +def FrenchRCDate($year; $month; $day): + def err(msg): "Invalid date (\(msg)): FrenchRCDate(\($year); \($month); \($day))" | error; + if ($year <= 0 or $month < 1 or $month > 13) then err(if $year <= 0 then "year" else "month" end) end + | if $month < 13 + then if $day < 1 or $day > 30 then err("day") end + else ($year | isLeapYearFRC) as $leap + | if $leap and ($day < 1 or $day > 6) then err("invalid day in leap year") end + | if ($leap|not) and ($day < 1 or $day > 5) then err("invalid day in non-leap year") end + end + | {$year, $month, $day}; + +# for convenience we treat 'Sansculottide' as an extra month with 5 or 6 days +def months: + ["Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal", + "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide"] ; + +def intercal: + ["Fête de la vertu", "Fête du génie", "Fête du travail", + "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution"]; + +# Input: a string specifying a FRC date +def parse: + . as $frcDate + | (trim|split(" ")) as $splits + | if $splits|length == 3 + then (months | index($splits[1]) + 1) as $month + | if $month < 1 or $month > 13 then "Invalid month." | error end + | ($splits[2]|tonumber) as $year + | if $year < 1 then "Invalid year." | error end + | (if ($month < 13) then 30 elif $year|isLeapYearFRC then 6 else 5 end) as $monthLength + | ($splits[0] | tonumber) as $day + | if $day < 1 or $day > $monthLength then "Invalid day." | error end + | FrenchRCDate($year; $month; $day) + + elif ($splits|length | IN(4,5)) + then $splits[-1] as $yearStr + | ($yearStr|tonumber) as $year + | if $year < 1 then "Invalid year." | error end + | ($frcDate | trim[0: -($yearStr|length + 1)] ) as $scDay + | (intercal | index($scDay) + 1) as $day + | (if $year | isLeapYearFRC then 6 else 5 end) as $maxDay + | if $day < 1 or $day > $maxDay then "Invalid day." | error end + | FrenchRCDate($year; 13; $day) + else "Invalid French Republican date." | error + end +; + +# Input: Date (Gregorian) +# Output: +def fromLocalDate: + # $start and $finish should be two Date objects + def daysFrom($start; $finish): + ($finish|daysBeforeDate) - ($start|daysBeforeDate); + + (daysFrom(introductionDate; .) + 1) as $daysDiff + | if ($daysDiff <= 0) then "Date can't be before 22 September 1792." | error end + | {year: 1, startDay: 1} + | until(.done; + (.startDay + (if .year|isLeapYearFRC then 365 else 364 end)) as $endDay + | if ($daysDiff >= .startDay and $daysDiff <= $endDay) then .done = true + else .year += 1 + | .startDay = $endDay + 1 + end ) + | ($daysDiff - .startDay) as $remDays + | (($remDays / 30)|floor) as $month + | ($remDays - $month * 30) as $day + | FrenchRCDate(.year; $month + 1; $day + 1) +; + +# Input: an FRC Date +def toString: + if .month < 13 then "\(.day) \(months[.month - 1]) \(.year)" + else "\(intercal[.day - 1]) \(.year)" + end; + +# Input: an FRC Date +def toLocalDate: + (reduce range(1; .year) as $i (0; . + (if $i|isLeapYearFRC then 366 else 365 end))) as $sumDays + | ((.month - 1) * 30 + .day - 1) as $dayInYear + | introductionDate | addDays($sumDays + $dayInYear) ; + + +### Examples + +def dates: [ + "22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803", + "31 December 1805", "18 March 1871", "25 August 1944", "19 September 2016", + "22 September 2017", "28 September 2017" +]; + +def task: + def format: + "\(.day) \(monthNames[.month]) \(.year)"; + + dates as $dates + | reduce range(0; $dates|length) as $i ({}; + .date = $dates[$i] + | .thisDate = (.date|parseDayMonthYear) + | .frcd = (.thisDate|fromLocalDate) + | .frcDates[$i] = (.frcd|toString) + | .emit += "\(.date|lpad(26)) => \(.frcDates[$i])\n") + | .emit, + + # now process the other way around + range(0; $dates|length) as $i + | .frcDates[$i] as $frcDate + | ($frcDate|parse|toLocalDate|format) as $lds + | assertEq($dates[$i]; $lds) + | "\($frcDate|lpad(26)) => \($lds)" +; + +task diff --git a/Task/Function-definition/ANSI-BASIC/function-definition.basic b/Task/Function-definition/ANSI-BASIC/function-definition.basic new file mode 100644 index 0000000000..9caf26d3c9 --- /dev/null +++ b/Task/Function-definition/ANSI-BASIC/function-definition.basic @@ -0,0 +1,13 @@ +100 DEF Multiply(A, B) = A * B +110 DECLARE FUNCTION MultiplyI +120 DECLARE EXTERNAL FUNCTION MultiplyE +130 PRINT Multiply(3, 1.23456) +140 PRINT MultiplyI(3, 1.23456) +150 PRINT MultiplyE(3, 1.23456) +160 FUNCTION MultiplyI(X, Y) +170 LET MultiplyI = X * Y +180 END FUNCTION +190 END +200 EXTERNAL FUNCTION MultiplyE(A, B) +210 LET MultiplyE = A * B +220 END FUNCTION diff --git a/Task/Function-definition/Chapel/function-definition-1.chapel b/Task/Function-definition/Chapel/function-definition-1.chapel new file mode 100644 index 0000000000..dce621a59f --- /dev/null +++ b/Task/Function-definition/Chapel/function-definition-1.chapel @@ -0,0 +1,4 @@ +proc multiply(a, b) +{ + return a * b; +} diff --git a/Task/Function-definition/Chapel/function-definition-2.chapel b/Task/Function-definition/Chapel/function-definition-2.chapel new file mode 100644 index 0000000000..cd4150861a --- /dev/null +++ b/Task/Function-definition/Chapel/function-definition-2.chapel @@ -0,0 +1,4 @@ +proc multiply(a : ?t ... 2) +{ + return a(0) * a(1) +} diff --git a/Task/Function-definition/Langur/function-definition-1.langur b/Task/Function-definition/Langur/function-definition-1.langur index 5f5be48e73..5878a47bf8 100644 --- a/Task/Function-definition/Langur/function-definition-1.langur +++ b/Task/Function-definition/Langur/function-definition-1.langur @@ -1,2 +1 @@ -val .multiply = fn(.x, .y) { .x * .y } -.multiply(3, 4) +val multiply = fn{*} diff --git a/Task/Function-definition/Langur/function-definition-2.langur b/Task/Function-definition/Langur/function-definition-2.langur index acbe918263..cfdc4aa62b 100644 --- a/Task/Function-definition/Langur/function-definition-2.langur +++ b/Task/Function-definition/Langur/function-definition-2.langur @@ -1,2 +1 @@ -val .multiply = fn(.x, .y) .x * .y -.multiply(3, 4) +val multiply = fn a, b: a * b diff --git a/Task/Function-definition/Langur/function-definition-3.langur b/Task/Function-definition/Langur/function-definition-3.langur index d66762792a..0445f67e8d 100644 --- a/Task/Function-definition/Langur/function-definition-3.langur +++ b/Task/Function-definition/Langur/function-definition-3.langur @@ -1,2 +1 @@ -val .multiply = fn{*} -.multiply(3, 4) +val multiply = fn(a, b) { a * b } diff --git a/Task/Function-definition/Langur/function-definition-4.langur b/Task/Function-definition/Langur/function-definition-4.langur deleted file mode 100644 index 69bbd2fc56..0000000000 --- a/Task/Function-definition/Langur/function-definition-4.langur +++ /dev/null @@ -1,2 +0,0 @@ -val .times3 = fn{* 3} -map .times3, [1, 2, 3] diff --git a/Task/Function-definition/Langur/function-definition-5.langur b/Task/Function-definition/Langur/function-definition-5.langur deleted file mode 100644 index 3f55f3d068..0000000000 --- a/Task/Function-definition/Langur/function-definition-5.langur +++ /dev/null @@ -1 +0,0 @@ -val .writeit = impure fn(.x) { writeln .x } diff --git a/Task/Function-definition/PascalABC.NET/function-definition.pas b/Task/Function-definition/PascalABC.NET/function-definition.pas new file mode 100644 index 0000000000..5cdaeef57d --- /dev/null +++ b/Task/Function-definition/PascalABC.NET/function-definition.pas @@ -0,0 +1 @@ +function multiply(a,b: real): real := a + b; diff --git a/Task/Function-definition/BASIC/function-definition.basic b/Task/Function-definition/QuickBASIC/function-definition.basic similarity index 100% rename from Task/Function-definition/BASIC/function-definition.basic rename to Task/Function-definition/QuickBASIC/function-definition.basic diff --git a/Task/Function-prototype/FutureBasic/function-prototype.basic b/Task/Function-prototype/FutureBasic/function-prototype.basic new file mode 100644 index 0000000000..547ce06eff --- /dev/null +++ b/Task/Function-prototype/FutureBasic/function-prototype.basic @@ -0,0 +1,3 @@ +def fn NoArgs +def fn TwoArgs( a as long, b as long ) +def fn VarArgs( n as long, ... ) diff --git a/Task/Gamma-function/REXX/gamma-function-3.rexx b/Task/Gamma-function/REXX/gamma-function-3.rexx new file mode 100644 index 0000000000..5b4f4665cd --- /dev/null +++ b/Task/Gamma-function/REXX/gamma-function-3.rexx @@ -0,0 +1,517 @@ +parse version version; say version; glob. = '' +say 'Gamma function in arbitrary precision' +say +say '(Half)integers formulas' +w = '-99.5 -10.5 -5.5 -2.5 -1.5 -0.5 0.5 1 1.5 2 2.5 5 5.5 10 10.5 99 99.5' +numeric digits 100 +do i = 1 to words(w) + x = word(w,i); call time('r'); r = Gamma(x); e = format(time('e'),,3) + say 'Formulas' format(x,4,1) r '('e 'seconds)' +end +say +say 'Lanczos (max 60 digits) vs Spouge (no limit) vs Stirling (no limit) approximation' +w = '-12.8 -6.4 -3.2 -1.6 -0.8 -0.4 -0.2 -0.1 0.1 0.2 0.4 0.8 1.6 3.2 6.4 12.8' +do i = 1 to words(w) + x = word(w,i) + numeric digits 60 + call time('r'); r = Gamma(x); e = format(time('e'),,3) + say 'Lanczos ' format(x,4,1) r '('e 'seconds)' + numeric digits 61 + call time('r'); r = Gamma(x); e = format(time('e'),,3) + say 'Spouge ' format(x,4,1) r '('e 'seconds)' + if x > 0 then do + call time('r'); r = Stirling(x); e = format(time('e'),,3) + say 'Stirling' format(x,4,1) r '('e 'seconds)' + end +end +say +say 'Same for a bigger number' +w = '-99.9 99.9' +do i = 1 to words(w) + x = word(w,i) + numeric digits 60 + call time('r'); r = Gamma(x); e = format(time('e'),,3) + say 'Lanczos ' format(x,4,1) r '('e 'seconds)' + numeric digits 100 + call time('r'); r = Gamma(x); e = format(time('e'),,3) + say 'Spouge ' format(x,4,1) r '('e 'seconds)' + if x > 0 then do + call time('r'); r = Stirling(x); e = format(time('e'),,3) + say 'Stirling' format(x,4,1) r '('e 'seconds)' + end +end +exit + +Gamma: +/* Gamma */ +procedure expose glob. +arg x +/* Validity */ +if x < 1 & Whole(x) then + return 'X' +/* Formulas for negative and positive (half)integers */ +if x < 0 then do + if Half(x) then do + numeric digits Digits()+2 + i = Abs(Floor(x)); y = (-1)**i*2**(2*i)*Fact(i)*Sqrt(Pi())/Fact(2*i) + numeric digits Digits()-2 + return y+0 + end +end +if x > 0 then do + if Whole(x) then + return Fact(x-1) + if Half(x) then do + numeric digits Digits()+2 + i = Floor(x); y = Fact(2*i)*Sqrt(Pi())/(2**(2*i)*Fact(i)) + numeric digits Digits()-2 + return y+0 + end +end +p = Digits() +if p < 61 then do +/* Lanczos with predefined coefficients */ +/* Map negative x to positive x */ + if x < 0 then + return Pi()/(Gamma(1-x)*Sin(Pi()*x)) +/* Argument reduction to interval (0.5,1.5) */ + numeric digits p+2 + c = Trunc(x); x = x-c + if x < 0.5 then do + x = x+1; c = c-1 + end +/* Series coefficients 1/Gamma(x) in 80 digits Fransen & Wrigge */ + c.1 = 1.00000000000000000000000000000000000000000000000000000000000000000000000000000000 + c.2 = 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 + c.3 = -0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 + c.4 = -0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 + c.5 = 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 + c.6 = -0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 + c.7 = -0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 + c.8 = 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 + c.9 = -0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 + c.10 = -0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 + c.11 = 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 + c.12 = -0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 + c.13 = -0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 + c.14 = 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 + c.15 = -0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 + c.16 = 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 + c.17 = 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 + c.18 = -0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 + c.19 = 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 + c.20 = 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 + c.21 = -0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 + c.22 = 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 + c.23 = -0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 + c.24 = -0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 + c.25 = 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 + c.26 = -0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 + c.27 = 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 + c.28 = 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 + c.29 = -0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 + c.30 = 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 + c.31 = 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 + c.32 = -0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 + c.33 = 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 + c.34 = -0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 + c.35 = -0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 + c.36 = 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 + c.37 = -0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 + c.38 = 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 + c.39 = 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 + c.40 = -0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 + c.41 = 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 + c.42 = -0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 + c.43 = 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 + c.44 = 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 + c.45 = -0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 + c.46 = 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 + c.47 = -0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 + c.48 = -0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 + c.49 = 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 + c.50 = -0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 + c.51 = 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 + c.52 = 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 +/* Series expansion */ + x = x-1; s = 0 + do k = 52 by -1 to 1 + s = s*x+c.k + end + y = 1/s +/* Undo reduction */ + if c = -1 then + y = y/x + else do + do i = 1 to c + y = (x+i)*y + end + end +end +else do + x = x-1 +/* Spouge */ +/* Estimate digits and iterations */ + q = Floor(p*1.5); a = Floor(p*1.3) + numeric digits q +/* Series */ + s = 0 + do k = 1 to a-1 + s = s+((-1)**(k-1)*Power(a-k,k-0.5)*Exp(a-k))/(Fact(k-1)*(x+k)) + end + s = s+Sqrt(2*Pi()); y = Power(x+a,x+0.5)*Exp(-a-x)*s +end +/* Normalize */ +numeric digits p +return y+0 + +Stirling: +/* Sterling */ +procedure expose glob. +arg x +return sqrt(2*pi()/x) * power(x/e(),x) + +E: +/* Euler number */ +procedure expose glob. +p = Digits() +/* In memory? */ +if glob.e.p <> '' then + return glob.e.p +if p < 101 then +/* Fast value */ + glob.e.p = 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759457138217852516643+0 +else do + numeric digits Digits()+2 +/* Taylor series */ + y = 2; t = 1; v = y + do n = 2 + t = t/n; y = y+t + if y = v then + leave + v = y + end + numeric digits Digits()-2 + glob.e.p = y+0 +end +return glob.e.p + +Exp: +/* Exponential e^x */ +procedure expose glob. +arg x +numeric digits Digits()+2 +/* Fast values */ +if Whole(x) then + return E()**x +/* Argument reduction */ +i = x%1 +if Abs(x-i) > 0.5 then + i = i+Sign(x) +/* Taylor series */ +x = x-i; y = 1; t = 1; v = y +do n = 1 + t = (t*x)/n; y = y+t + if y = v then + leave + v = y +end +/* Inverse reduction */ +y = y*e()**i +numeric digits Digits()-2 +return y+0 + +Fact: +/* Factorial n! */ +procedure expose glob. +arg x +/* Validity */ +if \ Whole(x) then + return 'X' +if x < 0 then + return 'X' +/* Current in memory? */ +if glob.fact.x <> '' then + return glob.fact.x +w = x-1 +/* Previous in memory? */ +if glob.fact.w = '' then do +/* Loop cf definition */ + y = 1 + do n = 2 to x + y = y*n + end + glob.fact.x = y +end +else +/* Multiply */ + glob.fact.x = glob.fact.w*x +return glob.fact.x + +Floor: +/* Floor */ +procedure expose glob. +arg x +/* Formula */ +if Whole(x) then + return x +else + return Trunc(x)-(x<0) + +Frac: +/* Fractional part */ +procedure expose glob. +arg x +/* Formula */ +return x-x%1 + +Half: +/* Is a number half integer? */ +procedure expose glob. +arg x +/* Formula */ +return (Frac(Abs(x))=0.5) + +Ln: +/* Natural logarithm base e */ +procedure expose glob. +arg x +/* Validity */ +if x <= 0 then + return 'X' +/* Fast values */ +if x = 1 then + return 0 +p = Digits() +/* In memory? */ +if glob.ln.x.p <> '' then + return glob.ln.x.p +/* Precalculated values */ +if x = 2 & p < 101 then do + glob.ln.x.p = Ln2() + return glob.ln.x.p +end +if x = 4 & p < 101 then do + glob.ln.x.p = Ln4() + return glob.ln.x.p +end +if x = 8 & p < 101 then do + glob.ln.x.p = Ln8() + return glob.ln.x.p +end +if x = 10 & p < 101 then do + glob.ln.x.p = Ln10() + return glob.ln.x.p +end +numeric digits p+2 +/* Argument reduction */ +z = x; i = 0; e = 1/E() +if z < 0.5 then do + y = 1/z + do while y > 1.5 + y = y*e; i = i-1 + end + z = 1/y +end +if z > 1.5 then do + do while z > 1.5 + z = z*e; i = i+1 + end +end +/* Taylor series */ +q = (z-1)/(z+1); f = q; y = q; v = q; q = q*q +do n = 3 by 2 + f = f*q; y = y+f/n + if y = v then + leave + v = y +end +numeric digits p +/* Inverse reduction */ +glob.ln.x.p = 2*y+i +return glob.ln.x.p + +Power: +/* Power function x^y */ +procedure expose glob. +arg x,y +/* Validity */ +if x < 0 then + return 'X' +/* Fast values */ +if x = 0 then + return 0 +if y = 0 then + return 1 +/* Fast formula */ +if Whole(y) then + return x**y +/* Formulas */ +if Abs(y//1) = 0.5 then + return Sqrt(x)**Sign(y)*x**(y%1) +else + return Exp(y*Ln(x)) + +Sin: +/* Sine */ +procedure expose glob. +arg x +numeric digits Digits()+2 +/* Argument reduction */ +u = Pi(); x = x//(2*u) +if Abs(x) > u then + x = x-Sign(x)*2*u +/* Taylor series */ +t = x; y = x; x = x*x; v = y +do n = 2 by 2 + t = -t*x/(n*(n+1)); y = y+t + if y = v then + leave + v = y +end +numeric digits Digits()-2 +return y+0 + +Sqrt: +/* Square root x^(1/2) */ +procedure expose glob. +arg x +/* Validity */ +if x < 0 then + return 'X' +/* Fast values */ +if x = 0 then + return 0 +if x = 1 then + return 1 +p = Digits() +/* Predefined values */ +if x = 2 & p < 101 then + return Sqrt2() +if x = 3 & p < 101 then + return Sqrt3() +if x = 5 & p < 101 then + return Sqrt5() +numeric digits p+2 +/* Argument reduction to [0,100) */ +i = Xpon(x); i = (i-(i<0))%2; x = x/100**i +/* First guess 1 digit accurate */ +t = '2.5 6.5 12.5 20.5 30.5 42.5 56.5 72.5 90.5 100' +do y = 1 until word(t,y) > x +end +/* Dynamic precision */ +d = Digits() +do n = 1 while d > 2 + d.n = d; d = d%2+1 +end +d.n = 2 +/* Method Heron */ +do k = n to 1 by -1 + numeric digits d.k + y = (y+x/y)*0.5 +end +numeric digits p +return y*10**i + +Whole: +/* Is a number integer? */ +procedure expose glob. +arg x +/* Formula */ +return Datatype(x,'w') + +Xpon: +/* Exponent */ +procedure expose glob. +arg x +/* Formula */ +if x = 0 then + return 0 +else + return Right(x*1E+99999,6)-99999 + +Ln2: +/* Natural log of 2 */ +procedure expose glob. +/* Fast value */ +y = 0.6931471805599453094172321214581765680755001343602552541206800094933936219696947156058633269964186875 +return y+0 + +Ln4: +/* Natural log of 4 */ +procedure expose glob. +/* Fast value */ +y = 1.386294361119890618834464242916353136151000268720510508241360018986787243939389431211726653992837375 +return y+0 + +Ln8: +/* Natural log of 8 */ +procedure expose glob. +/* Fast value */ +y = 2.079441541679835928251696364374529704226500403080765762362040028480180865909084146817589980989256063 +return y+0 + +Ln10: +/* Natural log of 10 */ +procedure expose glob. +/* Fast value */ +y = 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959830 +return y+0 + +Pi: +/* Pi */ +procedure expose glob. +p = Digits() +/* In memory? */ +if glob.pi.p <> '' then + return glob.pi.p +if p < 101 then +/* Fast value */ + glob.pi.p = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707+0 +else do + numeric digits Digits()+2 + if p < 201 then do +/* Method Chudnovsky series */ + y = 0 + do n = 0 + v = y; y = y + Fact(6*n)*(13591409+545140134*n)/(Fact(3*n)*Fact(n)**3*-640320**(3*n)) + if y = v then + leave + end + y = 4270934400/(Sqrt(10005)*y) + end + else do +/* Method Agmean series */ + y = 0.25; a = 1; g = Sqrt(0.5); n = 1 + do until a = v + v = a + x = (a+g)*0.5; g = Sqrt(a*g) + y = y-n*(x-a)**2; n = n+n; a = x + end + y = a*a/y + end + numeric digits Digits()-2 + glob.pi.p = y+0 +end +return glob.pi.p + +Sqrt2: +/* Square root of 2 */ +procedure expose glob. +/* Fast value */ +y = 1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573 +return y+0 + +Sqrt3: +/* Square root of 3 */ +procedure expose glob. +/* Fast value */ +y = 1.732050807568877293527446341505872366942805253810380628055806979451933016908800037081146186757248576 +return y+0 + +Sqrt5: +/* Square root of 5 */ +procedure expose glob. +/* Fast value */ +y = 2.236067977499789696409173668731276235440618359611525724270897245410520925637804899414414408378782275 +return y+0 diff --git a/Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas b/Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas new file mode 100644 index 0000000000..dc3d777a26 --- /dev/null +++ b/Task/General-FizzBuzz/PascalABC.NET/general-fizzbuzz.pas @@ -0,0 +1,14 @@ +## +for var i:=1 to 20 do +begin + var s := ''; + if i mod 3 = 0 then + s += 'Fizz'; + if i mod 5 = 0 then + s += 'Buzz'; + if i mod 7 = 0 then + s += 'Baxx'; + if s = '' then + Println(i) + else Println(s); +end diff --git a/Task/General-FizzBuzz/Refal/general-fizzbuzz.refal b/Task/General-FizzBuzz/Refal/general-fizzbuzz.refal new file mode 100644 index 0000000000..7519a97553 --- /dev/null +++ b/Task/General-FizzBuzz/Refal/general-fizzbuzz.refal @@ -0,0 +1,54 @@ +$ENTRY Go { + , >: s.Max + , : e.Factors + , : e.Nums + = ; +}; + +Fizz { + s.I e.Facs, : { + = >; + e.X = ; + }; +} + +Fac { + (s.Fac e.FacWord) s.I, : { + 0 = e.FacWord; + s.X = ; + }; +}; + +ReadFactors { + , : { + 0 = ; = ; + e.Line = () ; + }; +}; + +Line { + e.X, : (e.Num) e.Word = + ; +}; + +Split { + s.C e.X s.C e.Y = (e.X) e.Y; + s.C e.X = (e.X); +}; + +Trim { + s.C = ; + s.C s.C e.X = ; + s.C e.X s.C = ; + s.C s.I e.X = s.I ; +}; + +Iota { + s.End s.End = s.End; + s.Start s.End = s.Start s.End>; +}; + +Each { + s.F (e.Arg) = ; + s.F (e.Arg) t.I e.X = ; +}; diff --git a/Task/General-FizzBuzz/SETL/general-fizzbuzz.setl b/Task/General-FizzBuzz/SETL/general-fizzbuzz.setl new file mode 100644 index 0000000000..4caf8b65f4 --- /dev/null +++ b/Task/General-FizzBuzz/SETL/general-fizzbuzz.setl @@ -0,0 +1,9 @@ +program general_fizzbuzz; + fizzbuzz(20, {[3,"Fizz"], [5,"Buzz"], [7,"Baxx"]}); + + proc fizzbuzz(maxno, factors); + loop for i in [1..maxno] do + print(+/[word : word = factors(f) | i mod f=0] ? str i); + end loop; + end proc; +end program; diff --git a/Task/Generate-lower-case-ASCII-alphabet/PascalABC.NET/generate-lower-case-ascii-alphabet.pas b/Task/Generate-lower-case-ASCII-alphabet/PascalABC.NET/generate-lower-case-ascii-alphabet.pas new file mode 100644 index 0000000000..ab01a49532 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/PascalABC.NET/generate-lower-case-ascii-alphabet.pas @@ -0,0 +1,5 @@ +## +var a := Arr('a'..'z'); +a.Println; +var s := ('a'..'z').JoinToString(' ');; +s.Println diff --git a/Task/Generate-random-chess-position/Jq/generate-random-chess-position.jq b/Task/Generate-random-chess-position/Jq/generate-random-chess-position.jq new file mode 100644 index 0000000000..56cc2d10dd --- /dev/null +++ b/Task/Generate-random-chess-position/Jq/generate-random-chess-position.jq @@ -0,0 +1,94 @@ +### Pseuo-random numbers + +# Output: a prn in range(0;$n) where $n is `.` +def prn: + if . == 1 then 0 + else . as $n + | ([1, (($n-1)|tostring|length)]|max) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def sample: + if length == 0 # e.g. null or [] + then null + else .[length|prn] + end; + +def randFloat: + (1000|prn) / 1000; + +### Chess + +def isEmpty: . == "." or . == "•"; + +def grid: + [range(0;4) | (".","•") ] as $black + | [range(0;4) | ("•", ".")] as $white + | [range(0;4) | ($black, $white)] ; + +# input: {grid} +def placeKings: + .done = false + | until(.done; + [8 | prn, prn, prn, prn] as [$r1, $c1, $r2, $c2] + | if $r1 != $r2 and (($r1 - $r2)|length) > 1 and (($c1 - $c2)|length) > 1 + then .grid[$r1][$c1] = "K" + | .grid[$r2][$c2] = "k" + | .done = true + else . + end ) + | del(.done); + +# input: {grid} +def placePieces($pieces; $isPawn): + ($pieces|length|prn) as $numToPlace + | .n = -1 + | until(.n == $numToPlace; + .n += 1 + | .done = false + | until(.done; + .r = (8 | prn) + | .c = (8 | prn) + | if (.grid[.r][.c] | isEmpty) and (($isPawn and (.r == 7 or .r == 0))|not) + then .done = true + else . + end ) + | .grid[.r][.c] = $pieces[.n:.n+1] ) ; + +def toFen: + { grid, + fen: "", + countEmpty: 0 } + | reduce range (0;8) as $r (.; + reduce range(0;8) as $c (.; + .grid[$r][$c] as $ch + | .emit += " \($ch) " + | if ($ch | isEmpty) + then .countEmpty += 1 + else + if .countEmpty > 0 + then .fen += (.countEmpty|tostring) + | .countEmpty = 0 + end + | .fen += $ch + end ) + | if .countEmpty > 0 + then .fen += (.countEmpty|tostring) + | .countEmpty = 0 + end + | .fen += "/" + | .emit += "\n" ) + | .emit, + .fen + " w - - 0 1" ; + +def createFen: + {grid: grid} + | placeKings + | placePieces("PPPPPPPP"; true) + | placePieces("pppppppp"; true) + | placePieces("RNBQBNR"; false) + | placePieces("rnbqbnr"; false) + | toFen; + +createFen diff --git a/Task/Generic-swap/Langur/generic-swap.langur b/Task/Generic-swap/Langur/generic-swap.langur index 72306571e6..936f15ccbf 100644 --- a/Task/Generic-swap/Langur/generic-swap.langur +++ b/Task/Generic-swap/Langur/generic-swap.langur @@ -1,7 +1,7 @@ -var .abc = [1, 2, 3] -var .def = [5, 6, 7] +var abc = [1, 2, 3] +var def = [5, 6, 7] -.abc[3], .def[3] = .def[3], .abc[3] +abc[3], def[3] = def[3], abc[3] -writeln .abc -writeln .def +writeln abc +writeln def diff --git a/Task/Generic-swap/PascalABC.NET/generic-swap.pas b/Task/Generic-swap/PascalABC.NET/generic-swap.pas new file mode 100644 index 0000000000..38de981788 --- /dev/null +++ b/Task/Generic-swap/PascalABC.NET/generic-swap.pas @@ -0,0 +1,10 @@ +procedure Swap (var a,b: T) := (a,b) := (b,a); + +begin + var (i,j) := (1,2); + Swap(i,j); + Println(i,j); + var (s1,s2) := ('PascalABC.NET','Hello'); + Swap(s1,s2); + Println(s1,s2); +end. diff --git a/Task/Giuga-numbers/Jq/giuga-numbers.jq b/Task/Giuga-numbers/Jq/giuga-numbers.jq new file mode 100644 index 0000000000..09d889298a --- /dev/null +++ b/Task/Giuga-numbers/Jq/giuga-numbers.jq @@ -0,0 +1,24 @@ +# `div/1` is defined firstly to take advantage of gojq's infinite-precision +# integer arithmetic, and secondly to ensure jaq returns an integer. +def div($j): + (. - (. % $j)) / $j | round; # round is for the sake of jaq + +# For convenience +def div($i; $j): $i|div($j); + +def is_giuga: + . as $m + | sqrt as $limit + | {n: $m, f: 2} + | until(.ans; + if (.n % .f) == 0 + then if ((div($m; .f) - 1) % .f) != 0 then .ans = 0 + else .n = div(.n; .f) + | if .f > .n then .ans = 1 end + end + else .f += 1 + | if .f > $limit then .ans = 0 end + end) + | .ans == 1 ; + +limit(4; range(4; infinite) | select(is_giuga)) diff --git a/Task/Go-Fish/FutureBasic/go-fish.basic b/Task/Go-Fish/FutureBasic/go-fish.basic new file mode 100644 index 0000000000..7b2722e3ce --- /dev/null +++ b/Task/Go-Fish/FutureBasic/go-fish.basic @@ -0,0 +1,559 @@ +/* + +Go Fish +-- Rich Love -- + +FutureBasic app For Macintosh +Get the latest FutureBasic here +http://www.brilorsoftware.com/fb/pages/home.html + +*/ + + +_window = 1 +begin enum 1 + _scrollView + _textView +end enum + +override _forLoopsAlwaysExecuteAtLeastOnce = _true + +begin globals + +str255 cards +cards = "A234567890JQK" +short play(13), Computer(13), deck(13), guess(13), poss(13), asked(13) +str255 YourName, Someone +//bool gNeedToClearScreen +short Points(2) : Points(0) = 0 : Points(1) = 0 +short i, k, j, CardNumber +short RemainingCards + +end globals + + +local fn CheckForFaceCard(TheCard as short) as str255 + str255 WantsCard + WantsCard = str$(TheCard) + + if TheCard = 0 then WantsCard = "10" + if TheCard = 11 then WantsCard = "jack" + if TheCard = 12 then WantsCard = "Queen" + if TheCard = 13 then WantsCard = "King" + if TheCard = 1 then WantsCard = "Ace" +end fn = WantsCard + + +void local fn PrintViewScrollToBottom( printView as ViewRef ) + BeginCCode + NSScrollView *scrollView = [printView enclosingScrollView]; + NSClipView *clipView = [scrollView contentView]; + [clipView scrollToPoint:NSMakePoint(0,printView.frame.size.height-scrollView.contentSize.height + 20)]; + [scrollView reflectScrolledClipView:clipView]; + EndC +end fn + + +void local fn DealCards + + RemainingCards -= 1 + short sc + sc = rnd(RemainingCards) + 1 // 5/2/24 Rich added + 1 + + For k = 1 To 13 + sc -= deck(k) + If sc <= 0 Then exit fn + Next k + +End fn + +void local fn youGoFishing + + fn DealCards + + str255 WantsCard + WantsCard = fn CheckForFaceCard(k) + + if WantsCard = "0" then WantsCard = "10" + + Print " " + WantsCard + "." + deck(k) -= 1 + play(k) += 1 + +End fn + + +void local fn cpuGoFishing + + fn DealCards + Print " a card from the deck." + if k > 13 then k = 13 + deck(k) -= 1 + Computer(k) += 1 + +End fn + + +void local fn CheckForCompletedBook + + For i = 1 To 13 + If play(i) <> 4 + Else + text ,,fn colorcyan + + str255 WantsCard + WantsCard = Mid$(cards,i,1) + + if WantsCard = "j" || WantsCard = "J" then WantsCard = "Jack" + if WantsCard = "q" || WantsCard = "Q" then WantsCard = "Queen" + if WantsCard = "k" || WantsCard = "K" then WantsCard = "King" + if WantsCard = "a" || WantsCard = "A" then WantsCard = "Ace" + if WantsCard = "0" then WantsCard = "10" + + Print YourName + " completed the book of " + WantsCard + "'s." + text ,,fn colorWhite + play(i) = 0 + Points(0) += 1 + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + End If + Next i + +End fn + +local fn CheckCPUForCompletedBook + + For i = 1 To 13 + + If Computer(i) <> 4 + Else + text ,,fn colorCyan + str255 WantsCard + WantsCard = Mid$(cards,i,1) + + if WantsCard = "j" || WantsCard = "J" then WantsCard = "Jack" + if WantsCard = "q" || WantsCard = "Q" then WantsCard = "Queen" + if WantsCard = "k" || WantsCard = "K" then WantsCard = "King" + if WantsCard = "a" || WantsCard = "A" then WantsCard = "Ace" + if WantsCard = "0" then WantsCard = "10" + + Print "CPU completed the book of " + WantsCard + "'s." + + text ,,fn colorWhite + Computer(i) = 0 + Points(1) += 1 + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + End If + Next i + +End fn + + +local fn InitCards + + cards = "A234567890JQK" + RemainingCards = 4 * len$(cards) // the length of cards is 13. There are 4 suits of cards. so RemainingCards is 52 + i = 0:k = 0:j = 0:CardNumber = 0 + + For i = 0 to 1 + Points(i) = 0 + next i + + For i = 1 TO 13 // Reset each element to 0 + play(i) = 0 + Computer(i) = 0 + deck(i) = 0 + guess(i) = 0 + poss(i) = 0 + asked(i) = 0 + + NEXT i + + + For i = 1 To 13 + deck(i) = 4 + Next i + For i = 1 To 9 + fn DealCards + deck(k) -= 1 + Computer(k) += 1 + fn DealCards + deck(k) -= 1 + play(k) += 1 + Next i + + fn CheckForCompletedBook // Rich added 5/1/24 + fn CheckCPUForCompletedBook // Rich added 5/5/24 +end fn + + +local fn QuitOrPlayAlert(GameResult as CFStringRef) + + alert -2,,GameResult,@"Game Over",@"Quit;Play Again" + AlertButtonSetKeyEquivalent( 2, 2, @"\e" ) + short result + result = alert 2 + if ( result != NSAlertSecondButtonReturn ) then end + +end fn + +local fn QuitOrResumeAlert(GameResult as CFStringRef) + + alert -3,,GameResult,@"Quit the game?",@"Quit;Resume game" + AlertButtonSetKeyEquivalent( 3, 2, @"\e" ) + short result + result = alert 3 + if ( result != NSAlertSecondButtonReturn ) then end + +end fn + +local fn CheckForEndGame as boolean + + bool PlayAgain = _False + short np = 0, nc = 0 + For i = 1 To 13 + np += play(i) + nc += Computer(i) + Next i + + If RemainingCards = 0 || np = 0 || nc = 0 + + text ,,fn colorRed + Print "*** Game Over! ***" + Print + If Points(0) < Points(1) + Print "The CPU has won." + print:print + fn QuitOrPlayAlert(@"the CPU won!") + PlayAgain = _True + Else if Points(0) > Points(1) + Print YourName + " has won." + print:print + fn QuitOrPlayAlert(@"You Won!") + PlayAgain = _True + Else + Print "­It's a tie!" + fn QuitOrPlayAlert(@"It's a tie!.") + PlayAgain = _True + End If + fn PrintViewScrollToBottom( fn WindowPrintView(1) ) + + End If + + PlayAgain = _True + +End If + +End fn = PlayAgain + + +void local fn Intro + + text ,,fn colorGreen + Print " __ _ _ " + Print " __ _ ___ / _(_)___| |__ " + Print " / ` |/ _ \ | |_| / __| //_ \ " + Print "| (_) | (_) | | _| \__ \ | | | " + Print " \__, |\___/ |_| |_|___/_| |_| " + Print " |___/ " + Print "" + + text ,,fn colorCyan + print %(301,90),"( x to exit the game )" + text ,,fn colorWhite + + print " Go Fish Rules:" + print + print " You are playing against the CPU." + print " You are dealt nine cards to start with." + print " The remaining cards are placed face down in the center of the table" + print " to form the draw pile (the fish pond)." + print " On your turn, you ask the CPU For a card." + print " You must already have at least one card of a given rank to ask For more." + print " (A rank is one or more of any card.)" + print " If the CPU has any cards of the named rank, it must hand over all such cards," + print " and you can then ask again." + print " If the CPU has no cards of the named rank, a card will be drawn from the pile," + print " and placed in your hand, which then ends your turn." + print " A book is a collection of four cards in a given rank." + print " Whenever you complete a book, it will be removed from your hand." + print " If at any time, your hand is empty, a new card will be drawn from the pile." + print " The game ends when every book is complete," + print " or there are no more cards left in the pile." + print " The player with the most books wins." + + + CFStringRef UserInput + "InputYourName" + UserInput = input % (300, 70), @"What's your name?: " + if ( UserInput == NULL ) then "InputYourName" // Rich added this 5/1/24 + fn CFStringGetPascalString (UserInput, @YourName, 256, _kCFStringEncodingMacRoman) + cls + + if YourName = "X" || YourName = "x" || YourName = chr$(127) then fn QuitOrResumeAlert(@"EXIT") + +End fn + + +local fn WhatCardInputHeight as short + + CGRect mainScreenFrame = fn ScreenMainFrame + float InputHeight = int(mainScreenFrame.size.height - 120) + +end fn = InputHeight + + +local fn BuildWindow + + // ---> Get the size of the Main Screen. <--- + CGRect mainScreenFrame = fn ScreenMainFrame + float msh = mainScreenFrame.size.height + CGRect r = fn CGRectMake( 0, 0, 600, int(msh) - 110) + + window 1, @"Go Fish", r + windowcenter(1) + WindowSetBackgroundColor(1,fn ColorBlack) + +end fn + +//--- Start --- + +fn BuildWindow + +fn Intro + +fn InitCards + +str255 AddTheS +bool RequestCard = _false +short v = 0 +short po = 0 +boolean ShowHand = _false +str255 WantsCard + +"Main" + +ShowHand = _false + +str255 RequestedCard + +While ShowHand = _false + text ,,fn colorGreen + Print Chr$(10) + "Points >> "; + text ,,fn colorYellow + print YourName + ": "; + text ,,fn colorGreen + print Points(0); + text ,,fn colorOrange + print " CPU: "; + text ,,fn colorGreen + print Points(1) + text ,,fn colorWhite + Print Chr$(10) + " " + str$(RemainingCards) + " remaining cards" + text ,,fn colorWhite + + + /* + // Uncomment this to see the CPUs cards For testing + Print Chr$(10) + "CPU Cards: "; + For i = 1 To 13 + if Computer(i) <> 0 + For j = 1 To Computer(i) + if Mid$(cards,i,1) = "0" + Print @"10"; " "; + else + Print Mid$(cards,i,1); " "; + end if + Next j + End If + Next i + Print + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + */ + + + Print Chr$(10) + "Your Cards: "; + For i = 1 To 13 + if play(i) <> 0 + For j = 1 To play(i) + if Mid$(cards,i,1) = "0" + Print @"10"; " "; + else + Print Mid$(cards,i,1); " "; + end if + Next j + End If + Next i + Print + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + + RequestCard = _false + + While RequestCard = _false + if fn CheckForEndGame = _True then cls:fn InitCards:goto "Loop" + + Someone = YourName + + CFStringRef UserInput = 0 + "InputCard" + UserInput = input % (20, fn WhatCardInputHeight),@"What card do you want? " + if ( UserInput == NULL ) then "InputCard" // Rich added this 5/1/24 + fn CFStringGetPascalString (UserInput, @RequestedCard, 256, _kCFStringEncodingMacRoman) + if RequestedCard = "10" then RequestedCard = "0"// card zero is a 10 + text ,,fn ColorYellow + Print + + WantsCard = RequestedCard + + if WantsCard = "j" || WantsCard = "J" then WantsCard = "Jack" + if WantsCard = "q" || WantsCard = "Q" then WantsCard = "Queen" + if WantsCard = "k" || WantsCard = "K" then WantsCard = "King" + if WantsCard = "a" || WantsCard = "A" then WantsCard = "Ace" + if WantsCard = "0" then WantsCard = "10" + + print "-------------------------------------" + print + str255 AorAn + AorAn = "a" + if WantsCard = "Ace" then AorAn = "an" + print YourName + " asked For " + AorAn + " " + WantsCard + print + text ,,fn ColorWhite + + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + + if RequestedCard = "X" || RequestedCard = "x" then fn QuitOrResumeAlert(@"EXIT") + + If RequestedCard <> "" Then CardNumber = Instr$(1,cards, Ucase$(RequestedCard)): RequestCard = _true + + If CardNumber = 0 + text,,fn ColorRed + Print "Sorry, that is not a valid card.": RequestCard = _false + print + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + Else if play(CardNumber) = 0 Then text ,,fn colorRed: Print "You don//t have that card!": text ,,fn colorRed: RequestCard = _false + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + text,,fn ColorWhite + + End If + + Wend + + guess(CardNumber) = 1 + + If Computer(CardNumber) = 0 + Print Someone + ","; + text ,,fn colorRed + Print " Go fish!" + text ,,fn colorWhite + Print Someone + " got a";: fn youGoFishing + print + fn CheckForCompletedBook + ShowHand = _true + Else + v = Computer(CardNumber) + Computer(CardNumber) = 0 + play(CardNumber) += v + if v > 1 then AddTheS = "s" else AddTheS = "" + Print Someone + " got" + str$(v) + " card" + AddTheS + fn CheckForCompletedBook + fn PrintViewScrollToBottom( fn WindowPrintView(1)) + ShowHand = _false + End If + +Wend + + + +Someone = "CPU" +For i = 1 To 13 + asked(i) = 0 +Next i + +bool CPUsTurn = _false + +While CPUsTurn = _false + if fn CheckForEndGame = _True then cls:fn InitCards:goto "Loop" + + po = 0 + For i = 1 To 13 + If (Computer(i) > 0) && (guess(i) > 0) Then poss(i) = 1: po += 1 + Next i + + short whilecounter + WhileCounter = 0 + + + If po = 0 + // this k is the go fish card. + + k = rnd(12) +1 + while Computer(k) = 0 || asked(k) + whilecounter ++ + k = rnd(12) +1 + if WhileCounter > 100 then k = 0: exit while //5/5/24 Rich added this to prevent hangs + wend + + Else + + k = rnd(12) + 1 + while poss(k) = 0 + k = rnd(12) + 1 + if WhileCounter > 100 then k = 0: exit while //5/5/24 Rich added this to prevent hangs + wend + + guess(k) = 0 + asked(k) = 1 + + end if + + + if k = 0 then "Loop" //5/5/24 Rich added this to prevent hangs + + WantsCard = fn CheckForFaceCard(k) + + if WantsCard = "j" || WantsCard = "J" then WantsCard = "Jack" + if WantsCard = "q" || WantsCard = "Q" then WantsCard = "Queen" + if WantsCard = "k" || WantsCard = "K" then WantsCard = "King" + if WantsCard = "a" || WantsCard = "A" then WantsCard = "Ace" + if WantsCard = "0" then WantsCard = "10" + + text ,,fn ColorOrange + + print "-------------------------------------" + + + + Print:Print Someone + " wants your " + wantsCard + "'s." + print + + text ,,fn ColorWhite + + asked(k) = 1 + + + If play(k) = 0 + Print Someone + ", "; + text ,,fn colorRed: Print "go fish!" + text ,,fn colorWhite:Print Someone + " got";: fn cpuGoFishing + + fn CheckCPUForCompletedBook + CPUsTurn = _true + + Else + + v = play(k) + play(k) = 0 + Computer(k) += v + if v > 1 then AddTheS = "s" else AddTheS = "" + Print Someone + " got" + str$(v) + " card" + AddTheS + fn CheckCPUForCompletedBook + CPUsTurn = _false + End If + + +Wend + +"Loop" +goto "Main" + +handleevents diff --git a/Task/Golden-ratio-Convergence/R/golden-ratio-convergence.r b/Task/Golden-ratio-Convergence/R/golden-ratio-convergence.r new file mode 100644 index 0000000000..602f93267d --- /dev/null +++ b/Task/Golden-ratio-Convergence/R/golden-ratio-convergence.r @@ -0,0 +1,8 @@ +phi <- c(1, 1+1/1) + +while (abs(phi[length(phi)]-phi[length(phi)-1])>10**-5){ +phi <- c(phi, 1+1/phi[length(phi)]) +} + +print(paste("Result : ", phi[length(phi)], " after ", length(phi)-1 , "iterations.")) +print(paste("Error is approximately : ", phi[length(phi)]-(1+sqrt(5))/2 )) diff --git a/Task/Graph-colouring/Jq/graph-colouring.jq b/Task/Graph-colouring/Jq/graph-colouring.jq new file mode 100644 index 0000000000..fa4dfa15df --- /dev/null +++ b/Task/Graph-colouring/Jq/graph-colouring.jq @@ -0,0 +1,100 @@ +# Add a single edge assuming it is not already there +# Input: a JSON object with at least the key .start +def addEdge($n1; $n2): + # adjust to starting node number + ($n1 - .start) as $n1 + | ($n2 - .start) as $n2 + | .nbr[$n1] += [$n2] + | if $n1 != $n2 then .nbr[$n2] += [$n1] end ; + +# Build a Graph object from $start and $edges assuming there are no isolated edges +def Graph($start; $edges): + ([$edges[][]] | unique | length) as $nns + | {$start, # node numbering starts from $start + $nns, # number of nodes + $edges, # array of edges + nbr: [range(0;$nns) | [] ] # .nbr[$i] will be the array of neighbors of node $i + } + | reduce $edges[] as $e (.; addEdge($e[0]; $e[1])); + +# Use greedy algorithm +def greedyColoring: + # create a list with a color for each node + .cols = [range(0; .nns) | -1] # -1 denotes no color assigned + | .cols[0] = 0 # first node assigned color 0 + # create a bool list to keep track of which colors are available + | .available = [range(0; .nns) | false] + # assign colors to all nodes after the first + | reduce range(1; .nns) as $i (.; + # iterate through neighbors and mark their colors as available + reduce .nbr[$i][] as $j (.; + if .cols[$j] != -1 then .available[.cols[$j]] = true end ) + # find the first available color + | (.available | index(false)) as $c + | if $c + then .cols[$i] = $c # assign it to the current node + # reset the colors of the neighbors to unavailable + # before the next iteration + | reduce .nbr[$i][] as $j (.; + if (.cols[$j] != -1) then .available[.cols[$j]] = false end ) + else debug("greedyColoring unexpectedly did not find 'false'") + end ) + | .cols; + +# (n)umber of node and its (v)alence i.e. number of neighbors +def NodeVal($n; $v): {$n, $v}; + + +### Example graphs + +def Graph1: + {start: 0, + edges: [[0, 1], [1, 2], [2, 0], [3, 3]]} ; + +def Graph2: + {start: 1, + edges: + [[1, 6], [1, 7], [1, 8], [2, 5], [2, 7], [2, 8], + [3, 5], [3, 6], [3, 8], [4, 5], [4, 6], [4, 7]] }; + +def Graph3: + {start: 1, + edges: + [[1, 4], [1, 6], [1, 8], [3, 2], [3, 6], [3, 8], + [5, 2], [5, 4], [5, 8], [7, 2], [7, 4], [7, 6]] }; + +def Graph4: + {start: 1, + edges: + [[1, 6], [7, 1], [8, 1], [5, 2], [2, 7], [2, 8], + [3, 5], [6, 3], [3, 8], [4, 5], [4, 6], [4, 7]] }; + +# Use `Function` to find a coloring for each of the examples given as an array: +def task(Function): + . as $examples + | length as $n + | range(0; $n) as $i + | $examples[$i] as $g + | "\nExample \($i+1)", + ( $g + | Graph( .start; .edges ) + | Function as $cols + | .ecount = 0 # counts edges + | .emit = null + | reduce .edges[] as $e (.; + if ($e[0] != $e[1]) + then .emit += " Edge \($e[0])-\($e[1]) -> Color \($cols[$e[0] - .start]), \($cols[$e[1] - .start])\n" + | .ecount += 1 + else .emit += " Node \($e[0]) -> Color \($cols[$e[0] - .start])\n" + end) + | .emit, + (reduce $cols[] as $col (.maxCol = 0; # maximum color number used + if ($col > .maxCol) then .maxCol = $col end) + | + " Number of nodes : \(.nns)", + " Number of edges : \(.ecount)", + " Number of colors : \(.maxCol+1)" + ) ) ; + +"Using the greedyColoring algorithm", +([Graph1, Graph2, Graph3, Graph4] | task(greedyColoring)) diff --git a/Task/Gray-code/FreeBASIC/gray-code.basic b/Task/Gray-code/FreeBASIC/gray-code.basic index 95722fd32a..54d111804c 100644 --- a/Task/Gray-code/FreeBASIC/gray-code.basic +++ b/Task/Gray-code/FreeBASIC/gray-code.basic @@ -2,31 +2,23 @@ ' compile with: fbc -s console Function gray2bin(g As UInteger) As UInteger - Dim As UInteger b = g - While g g Shr= 1 b Xor= g Wend - Return b - End Function Function bin2gray(b As UInteger) As UInteger - Return b Xor (b Shr 1) - End Function ' ------=< MAIN >=------ Dim As UInteger i - Print " i binary gray gra2bin" Print String(32,"=") - For i = 0 To 31 Print Using "## --> "; i; print Bin(i,5); " --> "; diff --git a/Task/Gray-code/BASIC/gray-code.basic b/Task/Gray-code/GW-BASIC/gray-code.basic similarity index 100% rename from Task/Gray-code/BASIC/gray-code.basic rename to Task/Gray-code/GW-BASIC/gray-code.basic diff --git a/Task/Gray-code/Liberty-BASIC/gray-code.basic b/Task/Gray-code/Liberty-BASIC/gray-code.basic index 14888831e6..44f2129ea9 100644 --- a/Task/Gray-code/Liberty-BASIC/gray-code.basic +++ b/Task/Gray-code/Liberty-BASIC/gray-code.basic @@ -7,7 +7,6 @@ B$ =Gray2Bin$( G$) print B$; " in pure binary." next r - end function Bin2Gray$( bin$) ' Given a binary number as a string, returns Gray code as a string. diff --git a/Task/Gray-code/Modula-2/gray-code.mod2 b/Task/Gray-code/Modula-2/gray-code.mod2 new file mode 100644 index 0000000000..135aaa93e7 --- /dev/null +++ b/Task/Gray-code/Modula-2/gray-code.mod2 @@ -0,0 +1,57 @@ +MODULE GrayCode; + +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SWholeIO IMPORT + WriteInt; +FROM Conversions IMPORT + LongBaseToStr; +FROM FormatString IMPORT + FormatString; (* for justifying *) + +VAR + I, G, D: CARDINAL; + Ok: BOOLEAN; + BinS, OutBinS: ARRAY[0 .. 5] OF CHAR; + +PROCEDURE Encode(V: CARDINAL): CARDINAL; +BEGIN + RETURN V BXOR (V SHR 1) +END Encode; + +PROCEDURE Decode(V: CARDINAL): CARDINAL; +VAR + Result: CARDINAL; +BEGIN + Result := 0; + WHILE V > 0 DO + Result := Result BXOR V; + V := V SHR 1 + END; + RETURN Result +END Decode; + +BEGIN + WriteString("decimal binary gray decoded"); + WriteLn; + FOR I := 0 TO 31 DO + G := Encode(I); + D := Decode(G); + WriteInt(I, 4); + WriteString(" "); + Ok := LongBaseToStr(I, 2, BinS); + Ok := FormatString("%'05s", OutBinS, BinS); + (* Padded with 0; width: 5; type: string *) + WriteString(OutBinS); + WriteString(" "); + Ok := LongBaseToStr(G, 2, BinS); + Ok := FormatString("%'05s", OutBinS, BinS); + WriteString(OutBinS); + WriteString(" "); + Ok := LongBaseToStr(D, 2, BinS); + Ok := FormatString("%'05s", OutBinS, BinS); + WriteString(OutBinS); + WriteInt(D, 4); + WriteLn; + END +END GrayCode. diff --git a/Task/Grayscale-image/11l/grayscale-image.11l b/Task/Grayscale-image/11l/grayscale-image.11l index 2d3c981e9e..3f4f195f10 100644 --- a/Task/Grayscale-image/11l/grayscale-image.11l +++ b/Task/Grayscale-image/11l/grayscale-image.11l @@ -1,13 +1,4 @@ -T Colour - Byte r, g, b - - F (r, g, b) - .r = r - .g = g - .b = b - - F ==(other) - R .r == other.r & .g == other.g & .b == other.b +T Colour = BVec3 V black = Colour(0, 0, 0) V white = Colour(255, 255, 255) diff --git a/Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas b/Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas new file mode 100644 index 0000000000..7457c48563 --- /dev/null +++ b/Task/Greatest-common-divisor/PascalABC.NET/greatest-common-divisor.pas @@ -0,0 +1,18 @@ +function GCD(a,b: integer): integer; +begin + while b > 0 do + (a,b) := (b,a mod b); + Result := a; +end; + +function GCDRec(a,b: integer): integer; +begin + if b = 0 then + Result := a + else Result := GCDRec(b, a mod b); +end; + +begin + Println(GCD(72,30),GCDRec(72,30)); + Println(GCD(49865, 69811),GCDRec(49865, 69811)); +end. diff --git a/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts b/Task/Greatest-common-divisor/Uiua/greatest-common-divisor.uiua similarity index 100% rename from Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts rename to Task/Greatest-common-divisor/Uiua/greatest-common-divisor.uiua diff --git a/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy b/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy new file mode 100644 index 0000000000..acb989f2c7 --- /dev/null +++ b/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy @@ -0,0 +1,23 @@ +proc max_subseq . seq[] start stop maxsum . + maxsum = 0 + i = 1 + start = 1 + stop = 0 + for j to len seq[] + sum += seq[j] + if sum < 0 + i = j + 1 + sum = 0 + elif sum > maxsum + start = i + stop = j + maxsum = sum + . + . +. +a[] = [ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] +max_subseq a[] a b sum +print "Max sum = " & sum +for i = a to b + write a[i] & " " +. diff --git a/Task/Guess-the-number-With-feedback-player-/EasyLang/guess-the-number-with-feedback-player-.easy b/Task/Guess-the-number-With-feedback-player-/EasyLang/guess-the-number-with-feedback-player-.easy new file mode 100644 index 0000000000..b22b0d8067 --- /dev/null +++ b/Task/Guess-the-number-With-feedback-player-/EasyLang/guess-the-number-with-feedback-player-.easy @@ -0,0 +1,21 @@ +min = 1 +max = 100 +print "Think of a number between " & min & " and " & max +print "I will try to guess your number." +repeat + guess = (min + max) div 2 + print "My guess is " & guess + write "Is it higher than, lower than or equal to your number? " + answer$ = input + print answer$ + ans$ = substr answer$ 1 1 + until ans$ = "e" + if ans$ = "l" + min = guess + 1 + elif ans$ = "h" + max = guess - 1 + else + print "Sorry, i didn't understand your answer." + . +. +print "Goodbye." diff --git a/Task/Guess-the-number/Langur/guess-the-number.langur b/Task/Guess-the-number/Langur/guess-the-number.langur index 236a07c78b..fe84301d0f 100644 --- a/Task/Guess-the-number/Langur/guess-the-number.langur +++ b/Task/Guess-the-number/Langur/guess-the-number.langur @@ -1,13 +1,13 @@ writeln "Guess a number from 1 to 10" -val .n = string random 10 +val n = string(random(10)) for { - val .guess = read ">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, "" - if .guess == "" { + val guess = read(">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, "") + if guess == "" { writeln "too much bad data" break } - if .guess == .n { + if guess == n { writeln "That's it." break } diff --git a/Task/Guess-the-number/PascalABC.NET/guess-the-number.pas b/Task/Guess-the-number/PascalABC.NET/guess-the-number.pas new file mode 100644 index 0000000000..454da1cca8 --- /dev/null +++ b/Task/Guess-the-number/PascalABC.NET/guess-the-number.pas @@ -0,0 +1,13 @@ +begin + var randomNumber := Random(1..10); + Println('I''m thinking of a number between 1 and 10. Can you guess it?'); + while True do + begin + Print('Guess:'); + var x := ReadlnInteger; + if x = randomNumber then + break; + Println('That''s not it. Guess again.'); + end; + Println('Congrats!! You guessed right!6'); +end. diff --git a/Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy b/Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy new file mode 100644 index 0000000000..cb387a3101 --- /dev/null +++ b/Task/Halt-and-catch-fire/EasyLang/halt-and-catch-fire.easy @@ -0,0 +1,2 @@ +a[] = [ ] +print a[1] diff --git a/Task/Hamming-numbers/EasyLang/hamming-numbers.easy b/Task/Hamming-numbers/EasyLang/hamming-numbers.easy new file mode 100644 index 0000000000..5f54b97603 --- /dev/null +++ b/Task/Hamming-numbers/EasyLang/hamming-numbers.easy @@ -0,0 +1,27 @@ +func hamming lim . + len h[] lim + h[1] = 1 + x2 = 2 ; x3 = 3 ; x5 = 5 + i = 1 ; j = 1 ; k = 1 + for n = 2 to lim + h[n] = lower x2 lower x3 x5 + if x2 = h[n] + i += 1 + x2 = 2 * h[i] + . + if x3 = h[n] + j += 1 + x3 = 3 * h[j] + . + if x5 = h[n] + k += 1 + x5 = 5 * h[k] + . + . + return h[lim] +. +for nr = 1 to 20 + write hamming nr & " " +. +print "" +print hamming 1691 diff --git a/Task/Harmonic-series/Bruijn/harmonic-series.bruijn b/Task/Harmonic-series/Bruijn/harmonic-series.bruijn new file mode 100644 index 0000000000..747d370e68 --- /dev/null +++ b/Task/Harmonic-series/Bruijn/harmonic-series.bruijn @@ -0,0 +1,16 @@ +:import std/List . +:import std/Combinator . +:import std/Math/Rational Q +:import std/Number N + +# fun Church iteration hack +harmonic [0 &[[(Q.add 1 op) : N.++0]] start [[1]]] ⧗ Unary → Rational + op (+1) : N.--0 + start (+0.0f) : (+1) + +custom-gt? &[[[N.gt? 2 (N.mul 0 N.++1)]]] ⧗ Rational → Νumber → Boolean + +main [φ cons first-20 first-10-above (harmonic <$> (iterate [[[1 (2 1 0)]]] (+0u)))] + first-20 take (+20) + first-10-above [take (+10) first-above] + first-above [find-index [custom-gt? 0 1] 1] <$> (iterate N.inc (+0)) diff --git a/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-1.langur b/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-1.langur index 3c66fddceb..2091d73583 100644 --- a/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-1.langur +++ b/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-1.langur @@ -1 +1 @@ -writeln(hash fw/a b c d/, [1, 2, 3, 4]) +writeln hash(fw/a b c d/, [1, 2, 3, 4]) diff --git a/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur b/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur index a638f45f67..02fa5dea1e 100644 --- a/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur +++ b/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur @@ -1,6 +1,5 @@ -val .new = foldfrom( - fn(.hash, .key, .value) more .hash, h{.key: .value}, - h{}, fw/a b c d/, [1, 2, 3, 4], +val new = foldfrom( + fn h, key, value:more(h, {key: value}), + {:}, fw/a b c d/, [1, 2, 3, 4], ) - -writeln .new +writeln new diff --git a/Task/Hash-from-two-arrays/PascalABC.NET/hash-from-two-arrays.pas b/Task/Hash-from-two-arrays/PascalABC.NET/hash-from-two-arrays.pas new file mode 100644 index 0000000000..20f1a2c478 --- /dev/null +++ b/Task/Hash-from-two-arrays/PascalABC.NET/hash-from-two-arrays.pas @@ -0,0 +1,6 @@ +begin + var Keys := Arr('aa','bb','cc'); + var Values := Arr(1..3); + var dct := Dict(Keys.Zip(Values)); + dct.Println; +end. diff --git a/Task/Hello-world-Graphical/AutoHotKey-V2/hello-world-graphical.ahk b/Task/Hello-world-Graphical/Autohotkey-V2/hello-world-graphical.ahk similarity index 100% rename from Task/Hello-world-Graphical/AutoHotKey-V2/hello-world-graphical.ahk rename to Task/Hello-world-Graphical/Autohotkey-V2/hello-world-graphical.ahk diff --git a/Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-1.vim b/Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-1.vim new file mode 100644 index 0000000000..0c12485895 --- /dev/null +++ b/Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-1.vim @@ -0,0 +1 @@ +:call popup_notification("Hello world", {}) diff --git a/Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-2.vim b/Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-2.vim new file mode 100644 index 0000000000..0f6224a5a4 --- /dev/null +++ b/Task/Hello-world-Graphical/Vim-Script/hello-world-graphical-2.vim @@ -0,0 +1 @@ +:echow "Hello world" diff --git a/Task/Hello-world-Line-printer/PascalABC.NET/hello-world-line-printer.pas b/Task/Hello-world-Line-printer/PascalABC.NET/hello-world-line-printer.pas new file mode 100644 index 0000000000..6d74b7d4b5 --- /dev/null +++ b/Task/Hello-world-Line-printer/PascalABC.NET/hello-world-line-printer.pas @@ -0,0 +1,12 @@ +{$reference 'System.Drawing.dll'} + +uses System.Drawing; +uses System.Drawing.Printing; + +begin + var doc := new PrintDocument(); + doc.PrintPage += (s,e) -> begin + e.Graphics.DrawString('Hello World!', new Font('Arial', 14), Brushes.Black, 0, 0); + end; + doc.Print; +end. diff --git a/Task/Hello-world-Newline-omission/PascalABC.NET/hello-world-newline-omission.pas b/Task/Hello-world-Newline-omission/PascalABC.NET/hello-world-newline-omission.pas new file mode 100644 index 0000000000..70fe199707 --- /dev/null +++ b/Task/Hello-world-Newline-omission/PascalABC.NET/hello-world-newline-omission.pas @@ -0,0 +1,2 @@ +## +Write('Goodbye, World!'); diff --git a/Task/Hello-world-Standard-error/PascalABC.NET/hello-world-standard-error.pas b/Task/Hello-world-Standard-error/PascalABC.NET/hello-world-standard-error.pas new file mode 100644 index 0000000000..44d1e224dd --- /dev/null +++ b/Task/Hello-world-Standard-error/PascalABC.NET/hello-world-standard-error.pas @@ -0,0 +1,2 @@ +## +Console.Error.WriteLine('Goodbye, World!'); diff --git a/Task/Hello-world-Text/PascalABC.NET/hello-world-text.pas b/Task/Hello-world-Text/PascalABC.NET/hello-world-text-1.pas similarity index 100% rename from Task/Hello-world-Text/PascalABC.NET/hello-world-text.pas rename to Task/Hello-world-Text/PascalABC.NET/hello-world-text-1.pas diff --git a/Task/Hello-world-Text/PascalABC.NET/hello-world-text-2.pas b/Task/Hello-world-Text/PascalABC.NET/hello-world-text-2.pas new file mode 100644 index 0000000000..609ebe662f --- /dev/null +++ b/Task/Hello-world-Text/PascalABC.NET/hello-world-text-2.pas @@ -0,0 +1,4 @@ +program HelloWorld; +begin + writeln('Hello World!'); +end. diff --git a/Task/Hello-world-Text/PascalABC.NET/hello-world-text-3.pas b/Task/Hello-world-Text/PascalABC.NET/hello-world-text-3.pas new file mode 100644 index 0000000000..858e451b6c --- /dev/null +++ b/Task/Hello-world-Text/PascalABC.NET/hello-world-text-3.pas @@ -0,0 +1,2 @@ +## +println('Hello World!'); diff --git a/Task/Here-document/Langur/here-document-1.langur b/Task/Here-document/Langur/here-document-1.langur index 1c58f00525..a44fa5c4c8 100644 --- a/Task/Here-document/Langur/here-document-1.langur +++ b/Task/Here-document/Langur/here-document-1.langur @@ -1,4 +1,4 @@ -val .s = qs:block END +val s = qs:block END We put our text here. Here we are, Doc. END diff --git a/Task/Here-document/Langur/here-document-2.langur b/Task/Here-document/Langur/here-document-2.langur index 779240b08a..750f6d00f9 100644 --- a/Task/Here-document/Langur/here-document-2.langur +++ b/Task/Here-document/Langur/here-document-2.langur @@ -1,4 +1,4 @@ -val .s = qs:lead:block END +val s = qs:lead:block END We put our text here. Here we are, Doc. END diff --git a/Task/Here-document/Langur/here-document-3.langur b/Task/Here-document/Langur/here-document-3.langur index d576eaddd9..d90990f75e 100644 --- a/Task/Here-document/Langur/here-document-3.langur +++ b/Task/Here-document/Langur/here-document-3.langur @@ -1,4 +1,4 @@ -val .re = re:block END +val r = re:block END a regex pattern here Still here, Doc. END diff --git a/Task/Here-document/Langur/here-document-4.langur b/Task/Here-document/Langur/here-document-4.langur index 150246b3d6..4aab9b4c7f 100644 --- a/Task/Here-document/Langur/here-document-4.langur +++ b/Task/Here-document/Langur/here-document-4.langur @@ -1,4 +1,4 @@ -val .re = re:x:block END +val r = re:x:block END a free-spacing regex pattern here Somewhere, Doc. END diff --git a/Task/Here-document/Vim-Script/here-document-1.vim b/Task/Here-document/Vim-Script/here-document-1.vim new file mode 100644 index 0000000000..1c51292a24 --- /dev/null +++ b/Task/Here-document/Vim-Script/here-document-1.vim @@ -0,0 +1,5 @@ +let hw =<< END +Hello + World +END +echo join(hw, "\n") diff --git a/Task/Here-document/Vim-Script/here-document-2.vim b/Task/Here-document/Vim-Script/here-document-2.vim new file mode 100644 index 0000000000..69a9eb10fe --- /dev/null +++ b/Task/Here-document/Vim-Script/here-document-2.vim @@ -0,0 +1,6 @@ +let d58 = "5 6 7 8" +let d =<< eval DOZEN + 1 2 3 4 {d58} + 9 10 11 12 +DOZEN +call append(line('$'), d) diff --git a/Task/Hex-words/Ada/hex-words.ada b/Task/Hex-words/Ada/hex-words.ada new file mode 100644 index 0000000000..a6fca096c0 --- /dev/null +++ b/Task/Hex-words/Ada/hex-words.ada @@ -0,0 +1,149 @@ +-- Hex Words: find words of 4 or more characters, all characters of which are hex digits +-- J. Carter 2024 May + +with Ada.Characters.Handling; +with Ada.Containers.Vectors; +with Ada.Strings.Unbounded; +with Ada.Text_IO; + +procedure Hex_Words is + use Ada.Strings.Unbounded; + + subtype Hex_Digit is Character range 'a' .. 'f'; + subtype Digit_Value is Integer range 0 .. 9; + + function Hex_Word (Line : in String) return Boolean is + (Line'Length > 3 and (for all C of Line => C in Hex_Digit) ); + + function Digital_Root (Number : in Natural) return Digit_Value; + -- Returns the decimal digital root of Number + + function Four_Distinct (Word : in String) return Boolean with + Pre => Hex_Word (Word); + -- Returns True if Word has at least 4 distinct letters; False otherwise + + function Image (Number : in Natural) return String with + Post => Image'Result'Length = 9; + -- Returns the blank-filled decimal image of Number + + type Word_Info is record + Word : Unbounded_String; + Value : Natural; + Root : Digit_Value; + end record; + + function Root_Less (Left : in Word_Info; Right : in Word_Info) return Boolean is + (if Left.Root /= Right.Root then Left.Root < Right.Root else Left.Word < Right.Word); + + function Value_Greater (Left : in Word_Info; Right : in Word_Info) return Boolean is + (if Left.Value /= Right.Value then Left.Value > Right.Value else Left.Word < Right.Word); + + package Word_Lists is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Word_Info); + + package Root_Sorting is new Word_Lists.Generic_Sorting ("<" => Root_Less); + package Value_Sorting is new Word_Lists.Generic_Sorting ("<" => Value_Greater); + + function Digital_Root (Number : in Natural) return Digit_Value is + function Digit_Sum return Natural; + -- Sums the digits of the decimal representation of Number + + function Digit_Sum return Natural is + Image : constant String := Number'Image; + + Sum : Natural := 0; + begin -- Digit_Sum + All_Digits : for I in 2 .. Image'Last loop + Sum := Sum + Character'Pos (Image (I) ) - Character'Pos ('0'); + end loop All_Digits; + + return Sum; + end Digit_Sum; + + Sum : Natural := Digit_Sum; + begin -- Digital_Root + if Sum in Digit_Value then + return Sum; + end if; + + return Digital_Root (Sum); + end Digital_Root; + + function Four_Distinct (Word : in String) return Boolean is + type Hex_Set is array (Hex_Digit) of Boolean; + + Set : Hex_Set := (others => False); + Count : Natural := 0; + begin -- Four_Distinct + Check_All : for C of Word loop + Set (C) := True; + end loop Check_All; + + Count_Them : for B of Set loop + if B then + Count := Count + 1; + end if; + end loop Count_Them; + + return Count > 3; + end Four_Distinct; + + function Image (Number : in Natural) return String is + Result : constant String := Number'Image; + begin -- Image + return (1 .. 9 - Result'Length => ' ') & Result; + end Image; + + Input : Ada.Text_IO.File_Type; + Info : Word_Info; + Word : Word_Lists.Vector; + Distinct : Word_Lists.Vector; +begin -- Hex_Words + Ada.Text_IO.Open (File => Input, Mode => Ada.Text_IO.In_File, Name => "unixdict.txt"); + + All_Words : loop + exit All_Words when Ada.Text_IO.End_Of_File (Input); + + One_Word : declare + Line : constant String := Ada.Characters.Handling.To_Lower (Ada.Text_IO.Get_Line (Input) ); + begin -- One_Word + if Hex_Word (Line) then + Info.Word := To_Unbounded_String (Line); + Info.Value := Integer'Value ("16#" & Line & '#'); + Info.Root := Digital_Root (Info.Value); + Word.Append (New_Item => Info); + + if Four_Distinct (Line) then + Distinct.Append (New_Item => Info); + end if; + end if; + end One_Word; + end loop All_Words; + + Ada.Text_IO.Close (File => Input); + + Root_Sorting.Sort (Container => Word); + Value_Sorting.Sort (Container => Distinct); + + Print_All : for I in 1 .. Word.Last_Index loop + Print_One : declare + Info : Word_Info renames Word.Element (I); + begin -- Print_One + Ada.Text_IO.Put_Line + (Item => To_String (Info.Word) & (1 .. 6 - Length (Info.Word) => ' ') & Image (Info.Value) & Info.Root'Image); + end Print_One; + end loop Print_All; + + Ada.Text_IO.Put_Line (Item => Word.Last_Index'Image & " total words"); + Ada.Text_IO.New_Line; + + Output_Distinct : for I in 1 ..Distinct.Last_Index loop + One_Distinct : declare + Info : Word_Info renames Distinct.Element (I); + begin -- One_Distinct + Ada.Text_IO.Put_Line + (Item => To_String (Info.Word) & (1 .. 6 - Length (Info.Word) => ' ') & Image (Info.Value) & Info.Root'Image); + end One_Distinct; + end loop Output_Distinct; + + Ada.Text_IO.Put_Line (Item => Distinct.Last_Index'Image & " words with 4 or more distinct letters"); +end Hex_Words; diff --git a/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy b/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy new file mode 100644 index 0000000000..5cd6bf9baf --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy @@ -0,0 +1,47 @@ +global rs[] ss[] . +procdecl RS_append . . +func R n . + while n > len rs[] + RS_append + . + return rs[n] +. +func S n . + while n > len ss[] + RS_append + . + return ss[n] +. +proc RS_append . . + n = len rs[] + r = R n + S n + s = S len ss[] + rs[] &= r + repeat + s += 1 + until s = r + ss[] &= s + . + ss[] &= r + 1 +. +rs[] = [ 1 ] +ss[] = [ 2 ] +write "R(1 .. 10): " +for i to 10 + write R i & " " +. +print "" +len seen[] 1000 +for i to 40 + seen[R i] = 1 +. +for i to 960 + seen[S i] = 1 +. +for i to 1000 + if seen[i] = 0 + print i & " not seen" + return + . +. +print "first 1000 ok" diff --git a/Task/Honeycombs/FutureBasic/honeycombs.basic b/Task/Honeycombs/FutureBasic/honeycombs.basic new file mode 100644 index 0000000000..ee756dca3e --- /dev/null +++ b/Task/Honeycombs/FutureBasic/honeycombs.basic @@ -0,0 +1,115 @@ +void local fn BuildWindow + long tag, index + CFStringRef title + CFMutableStringRef letters = fn MutableStringWithString( @"ABCDEFGHIJKLMNOPQRSTUVWXYZ" ) + + window 1, @"Honeycombs", (0,0,419,443), NSWindowStyleMaskTitled + WindowSetBackgroundColor( 1, fn ColorWhite ) + + CGrect r = {20,339,95,85} + for tag = 1 to 20 + subclass button tag,,, @"", r,, NSBezelStyleSmallSquare + index = rnd(len(letters)-1) + title = mid(letters,index,1) + ButtonSetTitle( tag, title ) + ButtonSetKeyEquivalent( tag, lcase(title) ) + MutableStringDeleteCharacters( letters, fn RangeMake( index, 1 ) ) + ButtonSetTransparent( tag, YES ) + r = fn CGRectOffset( r, 0, -82 ) + if ( tag mod 4 == 0 ) + r.origin.x += 71 + if ( r.origin.y < -21.0 ) + r.origin.y = 339 + else + r.origin.y = 298 + end if + end if + next + + textlabel 21,, (18,20,383,24) + ControlSetFont( 21, fn FontSystemFontOfSize(20) ) + ControlSetAlignment( 21, NSTextAlignmentCenter ) +end fn + +void local fn ViewDrawRect( tag as long ) + CGRect r = fn ViewBounds( tag ) + ColorRef titleColor, fillColor + + if ( fn ControlIsEnabled( tag ) ) + titleColor = fn ColorRed + fillColor = fn ColorYellow + else + titleColor = fn ColorBlack + fillColor = fn ColorMagenta + end if + + BezierPathRef path = fn BezierPathInit + BezierPathSetLineWidth( path, 5.0 ) + BezierpathSetLineCapStyle( path, NSRoundLineCapStyle ) + + CGPoint pt = {0,41} + BezierPathMoveToPoint( path, pt ) + + pt.x += 23.67 : pt.y += 41 + BezierPathLineToPoint( path, pt ) + + pt.x += 47.34 + BezierPathLineToPoint( path, pt ) + + pt.x += 23.67 : pt.y -= 41 + BezierPathLineToPoint( path, pt ) + + pt.x -= 23.67 : pt.y -= 41 + BezierPathLineToPoint( path, pt ) + + pt.x -= 47.34 + BezierPathLineToPoint( path, pt ) + + pt.x -= 23.67 : pt.y += 41 + BezierPathLineToPoint( path, pt ) + + ColorSet( fillColor ) + BezierPathFill( path ) + + ColorSet( fn ColorBlack ) + BezierPathStroke( path ) + + CFStringRef title = fn ButtonTitle( tag ) + CFDictionaryRef attrs = @{ + NSFontAttributeName:fn FontWithName( @"Helvetica-Bold", 52), + NSForegroundColorAttributeName:titleColor} + + CFMutableAttributedStringRef aString = fn MutableAttributedStringWithAttributes( title, attrs ) + MutableAttributedStringSetAlignment( aString, NSTextAlignmentCenter ) + r.origin.y += 10 + AttributedStringDrawInRect( aString, r ) +end fn + +void local fn Finished + long tag + for tag = 1 to 20 + if ( fn ControlIsEnabled( tag ) ) then exit fn + next + end +end fn + +void local fn ButtonAction( tag as long ) + CFStringRef string = fn StringByAppendingString( fn ControlStringValue(21), fn ButtonTitle(tag) ) + ControlSetStringValue( 21, string ) + ControlSetEnabled( tag, NO ) + fn Finished +end fn + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _btnClick : fn ButtonAction( tag ) + case _viewDrawRect : fn ViewDrawRect( tag ) + end select +end fn + +random +fn BuildWindow + +on Dialog fn DoDialog + +HandleEvents diff --git a/Task/Huffman-coding/11l/huffman-coding.11l b/Task/Huffman-coding/11l/huffman-coding.11l index f8277da1fb..814945f8e7 100644 --- a/Task/Huffman-coding/11l/huffman-coding.11l +++ b/Task/Huffman-coding/11l/huffman-coding.11l @@ -1,11 +1,4 @@ -T Element - Int weight - [(Char, String)] symbols - - F (weight, symbols) - .weight = weight - .symbols = symbols - +T Element((Int weight, [(Char, String)] symbols)) F <(other) R (.weight, .symbols) < (other.weight, other.symbols) diff --git a/Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c b/Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c new file mode 100644 index 0000000000..79b70d3cf7 --- /dev/null +++ b/Task/Hunt-the-Wumpus/C/hunt-the-wumpus.c @@ -0,0 +1,129 @@ +#include +#include +#include + +#define NUM_ROOMS 20 +#define ARROWS 5 + +typedef enum { false, true } bool; + +typedef struct { + int connected[3]; + bool has_wumpus; + bool has_bat; + bool has_pit; +} Room; + +Room cave[NUM_ROOMS + 1]; // Cave rooms are numbered from 1 to 20 + +void initialize_cave() { + int i, j; + // Initialize cave rooms + for (i = 1; i <= NUM_ROOMS; i++) { + for (j = 0; j < 3; j++) { + cave[i].connected[j] = (i + j) % NUM_ROOMS + 1; // Circular connections + } + cave[i].has_wumpus = false; + cave[i].has_bat = false; + cave[i].has_pit = false; + } + // Randomly place wumpus, bats, and pits + cave[rand() % NUM_ROOMS + 1].has_wumpus = true; + for (i = 0; i < 2; i++) { + cave[rand() % NUM_ROOMS + 1].has_bat = true; + cave[rand() % NUM_ROOMS + 1].has_pit = true; + } +} + +void sense(int room) { + printf("You are in room %d.\n", room); + int i, adjacent_room; + for (i = 0; i < 3; i++) { + adjacent_room = cave[room].connected[i]; + if (cave[adjacent_room].has_wumpus) + printf("You smell something terrible nearby.\n"); + if (cave[adjacent_room].has_bat) + printf("You hear a rustling.\n"); + if (cave[adjacent_room].has_pit) + printf("You feel a cold wind blowing from a nearby cavern.\n"); + } +} + +void move(int *room) { + int choice; + printf("Choose an adjacent room to move into: "); + scanf("%d", &choice); + if (choice < 1 || choice > 3) { + printf("Invalid choice. Please choose a number between 1 and 3.\n"); + move(room); + return; + } + *room = cave[*room].connected[choice - 1]; +} + +void shoot(int room, int *arrows, bool *game_over) { + int choice, adjacent_room; + printf("Choose an adjacent room to shoot into: "); + scanf("%d", &choice); + if (choice < 1 || choice > 3) { + printf("Invalid choice. Please choose a number between 1 and 3.\n"); + shoot(room, arrows, game_over); + return; + } + adjacent_room = cave[room].connected[choice - 1]; + if (cave[adjacent_room].has_wumpus) { + printf("Congratulations! You've killed the Wumpus!\n"); + *game_over = true; + return; + } + else { + if (rand() % 4 != 0) { // 75% chance of waking up the wumpus + if (cave[adjacent_room].has_wumpus) { + printf("The Wumpus has woken up and eaten you!\n"); + *game_over = true; + return; + } + } + printf("You missed! The Wumpus is still asleep.\n"); + } + (*arrows)--; +} + +int main() { + srand(time(NULL)); + initialize_cave(); + int current_room = 1; + int arrows = ARROWS; + bool game_over = false; + + printf("Welcome to Hunt the Wumpus!\n"); + + while (!game_over) { + sense(current_room); + printf("Choose your action:\n"); + printf("1. Move to an adjacent room\n"); + printf("2. Shoot into an adjacent room\n"); + + int choice; + printf("Enter your choice (1 or 2): "); + scanf("%d", &choice); + + switch(choice) { + case 1: + move(¤t_room); + break; + case 2: + if (arrows > 0) { + shoot(current_room, &arrows, &game_over); + } else { + printf("You're out of arrows! You lost the game.\n"); + game_over = true; + } + break; + default: + printf("Invalid choice. Please choose 1 or 2.\n"); + } + } + + return 0; +} diff --git a/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur b/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur new file mode 100644 index 0000000000..3393c6b40c --- /dev/null +++ b/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur @@ -0,0 +1,24 @@ +val words = split("\n", readfile("./data/unixdict.txt")) -> rest + +val print = impure fn(support, against) { + val ratio = support / against + writeln "{{support}} / {{against}} = {{ratio : r2}}:", (ratio < 2) * " NOT", " PLAUSIBLE" + return if(ratio >= 2: 1; 0) +} + +val ks = fw/ei cei ie cie/ +var cnt = {:} + +for w in words { + for k in ks { + cnt[k; 0] += if(k in w: 1; 0) + } +} + +var support = cnt'ie - cnt'cie +var against = cnt'ei - cnt'cei + +var result = print(support, against) +result += print(cnt'cei, cnt'cie) + +writeln "Overall:", (result < 2) * " NOT", " PLAUSIBLE\n" diff --git a/Task/IBAN/EasyLang/iban.easy b/Task/IBAN/EasyLang/iban.easy new file mode 100644 index 0000000000..20ac406d24 --- /dev/null +++ b/Task/IBAN/EasyLang/iban.easy @@ -0,0 +1,63 @@ +cc$[] = [ "AD" "AE" "AL" "AO" "AT" "AZ" "BA" "BE" "BF" "BG" "BH" "BI" "BJ" "BR" "CG" "CH" "CI" "CM" "CR" "CV" "CY" "CZ" "DE" "DK" "DO" "DZ" "EE" "EG" "ES" "FI" "FO" "FR" "GA" "GB" "GE" "GI" "GL" "GR" "GT" "HR" "HU" "IE" "IL" "IR" "IS" "IT" "JO" "KW" "KZ" "LB" "LI" "LT" "LU" "LV" "MC" "MD" "ME" "MG" "MK" "ML" "MR" "MT" "MU" "MZ" "NL" "NO" "PK" "PL" "PS" "PT" "QA" "RO" "RS" "SA" "SE" "SI" "SK" "SM" "SN" "TN" "TR" "UA" "VG" ] +ln[] = [ 24 23 28 25 20 28 20 16 27 22 22 16 28 29 27 21 28 27 21 25 28 24 22 18 28 24 20 27 24 18 18 27 27 22 22 23 18 27 28 21 28 22 23 26 26 27 30 30 20 28 21 20 20 21 27 24 22 27 19 28 27 31 30 25 18 15 24 28 29 25 29 24 22 24 24 19 24 27 28 24 26 29 24 ] +# +func validcc iban$ . + c$ = substr iban$ 1 2 + for i to len cc$[] + if c$ = cc$[i] + return if len iban$ = ln[i] + . + . + return 0 +. +func mod97 s$ . + while s$ <> "" + h$ = r div 10 + h$ &= r mod 10 + h$ &= substr s$ 1 13 + s$ = substr s$ 14 9999 + r = number h$ mod 97 + . + return r +. +func isvalid hiban$ . + for c$ in strchars hiban$ + c = strcode c$ + if c > 32 + if c >= 97 and c < 122 + c -= 32 + c$ = strchar c + elif c < 48 or c > 57 and c < 65 or c > 90 + return 0 + . + miban$ &= c$ + . + . + if validcc miban$ = 0 + return 0 + . + for c$ in strchars substr miban$ 5 999 & substr miban$ 1 4 + c = strcode c$ + if c >= 65 and c <= 90 + t$ &= (c - 55) div 10 + t$ &= (c - 55) mod 10 + else + t$ &= c$ + . + . + return if mod97 t$ = 1 +. +proc check s$ . . + write s$ & " is " + if isvalid s$ = 1 + print "valid" + else + print "not valid" + . +. +check "GB82 WEST 1234 5698 7654 32" +check "GB82WEST12345698765432" +check "gb82 west 1234 5698 7654 32" +check "GB82 TEST 1234 5698 7654 32" +check "GB82 WEST 1243 5698 7654 32" +check "GB82 west 1243 5698 7654 32" diff --git a/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur b/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur index a4415c04d1..d8bb48c1ff 100644 --- a/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur +++ b/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur @@ -1,18 +1,18 @@ -val .isbn13checkdigit = fn(var .s) { - .s = replace(.s, RE/[\- ]/) - .s -> re/^[0-9]{13}$/ and - fold(fn{+}, map [_, fn{*3}], s2n .s) div 10 +val isbn13checkdigit = fn(var s) { + s = replace(s, RE/[\- ]/) + s -> re/^[0-9]{13}$/ and + fold(fn{+}, map([_, fn{*3}], s2n(s))) div 10 } -val .tests = h{ +val tests = { "978-0596528126": true, "978-0596528120": false, "978-1788399081": true, "978-1788399083": false, } -for .key of .tests { - val .pass = .isbn13checkdigit(.key) - write .key, ": ", if(.pass: "good"; "bad") - writeln if(.pass == .tests[.key]: ""; " (ISBN-13 CHECK DIGIT TEST FAILED)") +for key of tests { + val pass = isbn13checkdigit(key) + write key, ": ", if(pass: "good"; "bad") + writeln if(pass == tests[key]: ""; " (ISBN-13 CHECK DIGIT TEST FAILED)") } diff --git a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml new file mode 100644 index 0000000000..55acb3f3db --- /dev/null +++ b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-1.ml @@ -0,0 +1,22 @@ +(* these type decorations are optional, you could just as well put: + fun isValidISBN s = +*) +fun isValidISBN (s : string) : bool = + let + val digits = List.filter Char.isDigit (explode s) + val nums = map (fn x => ord x - ord #"0") digits + val len = length nums + fun sumISBN [] = raise Domain + | sumISBN [x] = x + | sumISBN (x1::x2::xs) = x1 + 3*x2 + sumISBN xs + in + len = 13 andalso sumISBN nums mod 10 = 0 + end + +val test = ["978-1734314502", "978-1734314509", + "978-1788399081", "978-1788399083"] + +fun printTest (s : string) : unit = + (print s; print (if isValidISBN s then ": good\n" else ": bad\n")) + +fun main () = app printTest test diff --git a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-2.ml similarity index 98% rename from Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml rename to Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-2.ml index 14abd4e5fc..c81cfd25c5 100644 --- a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml +++ b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit-2.ml @@ -1,4 +1,4 @@ -local +let fun check (c, p as (m, n)) = if Char.isDigit c then (not m, (if m then 3 * (ord c - 48) else ord c - 48) + n) diff --git a/Task/Identity-matrix/Kotlin/identity-matrix.kotlin b/Task/Identity-matrix/Kotlin/identity-matrix.kotlin index 8e873fc892..4b0278fd6e 100644 --- a/Task/Identity-matrix/Kotlin/identity-matrix.kotlin +++ b/Task/Identity-matrix/Kotlin/identity-matrix.kotlin @@ -1,17 +1,16 @@ -// version 1.0.6 - -fun main(args: Array) { +fun main() { print("Enter size of matrix : ") - val n = readLine()!!.toInt() + val n = readln().toInt() println() - val identity = Array(n) { IntArray(n) } // create n x n matrix of integers - - // enter 1s in diagonal elements - for(i in 0 until n) identity[i][i] = 1 + val identity = Array(n) { i -> + IntArray(n) { j -> + if (i == j) 1 else 0 + } + } // print identity matrix if n <= 40 if (n <= 40) - for (i in 0 until n) println(identity[i].joinToString(" ")) + for (row in identity) println(row.joinToString(" ")) else println("Matrix is too big to display on 80 column console") } diff --git a/Task/Identity-matrix/PascalABC.NET/identity-matrix.pas b/Task/Identity-matrix/PascalABC.NET/identity-matrix.pas new file mode 100644 index 0000000000..ba0f8caad4 --- /dev/null +++ b/Task/Identity-matrix/PascalABC.NET/identity-matrix.pas @@ -0,0 +1,5 @@ +begin + var n := ReadInteger; + var matrix: array [,] of integer := MatrGen(n,n,(i,j) -> i = j ? 1 : 0); + matrix.Println +end. diff --git a/Task/Identity-matrix/Uiua/identity-matrix.uiua b/Task/Identity-matrix/Uiua/identity-matrix.uiua new file mode 100644 index 0000000000..2c76013a8d --- /dev/null +++ b/Task/Identity-matrix/Uiua/identity-matrix.uiua @@ -0,0 +1,2 @@ +IdMatrix ← ⊞=.⇡ +IdMatrix 7 diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.ada b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.ada new file mode 100644 index 0000000000..d2d6842033 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.ada @@ -0,0 +1,12 @@ +with Ada.Strings.Maps; use Ada.Strings.Maps; +with Ada.Text_IO; + +procedure Show_Valid_Identifiers is + Valid_First_Character : constant Character_Set := To_Set (Ranges => (1 => ('a', 'z'), 2 => ('A', 'Z'))); + Valid_Last_Character : constant Character_Set := Valid_First_Character or To_Set (Ranges => (1 => ('0', '9'))); + Valid_Middle_Character : constant Character_Set := Valid_Last_Character or To_Set ('_'); +begin + Ada.Text_IO.Put_Line ("Valid for the first character: " & String (To_Sequence (Valid_First_Character))); + Ada.Text_IO.Put_Line ("Valid for any middle character: " & String (To_Sequence (Valid_Middle_Character))); + Ada.Text_IO.Put_Line ("Valid for the last character: " & String (To_Sequence (Valid_Last_Character))); +end Show_Valid_Identifiers; diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren index 381544e810..8e2277f929 100644 --- a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Wren/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.wren @@ -1,3 +1,4 @@ for (i in 97..122) System.write(String.fromByte(i)) for (i in 65..90) System.write(String.fromByte(i)) +for (i in 48..57) System.write(String.fromByte(i)) System.print("_") diff --git a/Task/Im-a-software-engineer-get-me-out-of-here/C++/im-a-software-engineer-get-me-out-of-here.cpp b/Task/Im-a-software-engineer-get-me-out-of-here/C++/im-a-software-engineer-get-me-out-of-here.cpp new file mode 100644 index 0000000000..5a053ff371 --- /dev/null +++ b/Task/Im-a-software-engineer-get-me-out-of-here/C++/im-a-software-engineer-get-me-out-of-here.cpp @@ -0,0 +1,236 @@ +#include +#include +#include +#include +#include + +const std::string gmooh = R"( +.........00000......... +......00003130000...... +....000321322221000.... +...00231222432132200... +..0041433223233211100.. +..0232231612142618530.. +.003152122326114121200. +.031252235216111132210. +.022211246332311115210. +00113232262121317213200 +03152118212313211411110 +03231234121132221411410 +03513213411311414112320 +00427534125412213211400 +.013322444412122123210. +.015132331312411123120. +.003333612214233913300. +..0219126511415312570.. +..0021321524341325100.. +...00211415413523200... +....000122111322000.... +......00001120000...... +.........00000.........)"; + +std::vector split_string(const std::string& text, const char& delimiter) { + std::vector lines; + std::istringstream stream(text); + std::string line; + while ( std::getline(stream, line, delimiter) ) { + if ( ! line.empty() ) { + lines.emplace_back(line); + } + } + return lines; +} + +const std::vector GMOOH = split_string(gmooh, '\n'); +const int32_t WIDTH = GMOOH[0].length(); +const int32_t HEIGHT = GMOOH.size(); + +class Cell { +public: + Cell(const int32_t& aRow, const int32_t& aCol) : row(aRow), col(aCol) { } + + std::string to_string() const { + return "(" + std::to_string(row) + ", " + std::to_string(col) + ")"; + } + + int32_t row, col; +}; + +class Cell_With_Cost { +public: + Cell_With_Cost(const int32_t& aFrom_Row, const int32_t& aFrom_Col, const int32_t& aCost) + : from_row(aFrom_Row), from_col(aFrom_Col), cost(aCost) { } + + std::string to_string() const { + return "(" + std::to_string(from_row) + ", " + std::to_string(from_col) + " : " + std::to_string(cost) + ")"; + } + + bool operator==(const Cell_With_Cost& other) const { + return cost == other.cost && from_row == other.from_row && from_col == other.from_col; + } + + int32_t from_row, from_col, cost; +}; + +const Cell_With_Cost ZERO_CELL_WITH_COST = Cell_With_Cost(0, 0, 0); + +const std::vector directions = { Cell(1, -1), Cell(1, 0), Cell(1, 1), + Cell(0, -1), Cell(0, 1), + Cell(-1, -1), Cell(-1, 0), Cell(-1, 1) }; + +std::vector> routes = { }; + +void print_vector(const std::vector& cells) { + std::cout << "["; + for ( uint64_t i = 0; i < cells.size() - 1; ++i ) { + std::cout << cells[i].to_string() << ", "; + } + std::cout << cells.back().to_string() << "]" << std::endl; +} + +std::vector create_route_to_cell(int32_t row, int32_t col) { + std::vector route = { }; + route.emplace_back(Cell(row, col)); + + while ( true ) { + Cell_With_Cost current_cell = routes[row][col]; + if ( current_cell.cost == 0 ) { + break; + } + + row = current_cell.from_row; + col = current_cell.from_col; + route.insert(route.begin(), Cell(row, col)); + } + return route; +} + +void show_cells_with_longest_route_from_HQ() { + int32_t maximum_cost = INT_MIN; + std::vector cells = { }; + for ( int32_t col = 0; col < WIDTH; ++col ) { + for ( int32_t row = 0; row < HEIGHT; ++row ) { + if ( GMOOH[row][col] >= '0' ) { + Cell_With_Cost current_cell = routes[row][col]; + if ( ! ( current_cell == ZERO_CELL_WITH_COST ) ) { + const int32_t cost = current_cell.cost; + if ( cost >= maximum_cost) { + if ( cost > maximum_cost ) { + cells.clear(); + maximum_cost = cost; + } + cells.emplace_back(Cell(row, col)); + } + } + } + } + } + + std::cout << "There are " << cells.size() << " cells that require " << maximum_cost + << " days to receive reinforcements from HQ:" << std::endl; + for ( const Cell& cell : cells ) { + print_vector(create_route_to_cell(cell.row, cell.col)); + } +} + +void show_unreachable_cells() { + std::vector unreachableCells = { }; + for ( int32_t col = 0; col < WIDTH; ++col ) { + for ( int32_t row = 0; row < HEIGHT; ++row ) { + if ( GMOOH[row][col] >= '0' && routes[row][col] == ZERO_CELL_WITH_COST ) { + unreachableCells.emplace_back(Cell(row, col)); + } + } + } + + std::cout << "The following cells are unreachable:" << std::endl; + print_vector(unreachableCells); +} + +void search_from_cell(int32_t row, int32_t col) { + routes = { static_cast(HEIGHT), std::vector(WIDTH, ZERO_CELL_WITH_COST) }; + routes[row][col] = Cell_With_Cost(row, col, 0); + + std::vector route = { }; + int32_t cost = 0; + + while ( true ) { + const int32_t start_digit = GMOOH[row][col] - '0'; + for ( Cell direction : directions ) { + const int32_t next_row = row + start_digit * direction.row; + const int32_t next_col = col + start_digit * direction.col; + if ( next_col >= 0 && next_col < WIDTH && next_row >= 0 && next_row < HEIGHT + && GMOOH[next_row][next_col] >= '0' ) { + Cell_With_Cost current_cell = routes[next_row][next_col]; + if ( current_cell == ZERO_CELL_WITH_COST || current_cell.cost > cost + 1 ) { + routes[next_row][next_col] = Cell_With_Cost(row, col, cost + 1); + if ( GMOOH[next_row][next_col] > '0' ) { + route.emplace_back(Cell_With_Cost(next_row, next_col, cost + 1)); + } + } + } + } + + if ( route.empty() ) { // All routes have been searched + break; + } + + Cell_With_Cost next_cell = route.front(); + route.erase(route.begin()); + row = next_cell.from_row; + col = next_cell.from_col; + cost = next_cell.cost; + } +} + +void show_shortest_routes_to_safety() { + int32_t minimum_cost = INT_MAX; + std::vector route = { }; + for ( int32_t col = 0; col < WIDTH; ++col ) { + for ( int32_t row = 0; row < HEIGHT; ++row ) { + if ( GMOOH[row][col] == '0' ) { + Cell_With_Cost current_cell = routes[row][col]; + if ( ! ( current_cell == ZERO_CELL_WITH_COST ) ) { + const int32_t cost = current_cell.cost; + if ( cost <= minimum_cost ) { + if ( cost < minimum_cost ) { + route.clear(); + minimum_cost = cost; + } + route.emplace_back(Cell(row, col)); + } + } + } + } + } + + const std::string are_is = ( route.size() > 1 ) ? "are " : "is "; + const std::string plural = ( route.size() > 1 ) ? "s" : ""; + std::cout << "There " << are_is << route.size() << " shortest route" << plural + << " of " << minimum_cost << " days to safety:" << std::endl; + for ( const Cell& cell : route ) { + print_vector(create_route_to_cell(cell.row, cell.col)); + } +} + +int main() { + search_from_cell(11, 11); + show_shortest_routes_to_safety(); + std::cout << std::endl; + + search_from_cell(21, 11); + std::cout << "The shortest route from (21, 11) to (1, 11):" << std::endl; + print_vector((create_route_to_cell(1, 11))); + std::cout << std::endl; + + search_from_cell(1, 11); + std::cout << "The shortest route from (1, 11) to (21, 11):" << std::endl; + print_vector((create_route_to_cell(21, 11))); + std::cout << std::endl; + + search_from_cell(11, 11); + show_unreachable_cells(); + std::cout << std::endl; + + show_cells_with_longest_route_from_HQ(); +} diff --git a/Task/Im-a-software-engineer-get-me-out-of-here/Java/im-a-software-engineer-get-me-out-of-here.java b/Task/Im-a-software-engineer-get-me-out-of-here/Java/im-a-software-engineer-get-me-out-of-here.java new file mode 100644 index 0000000000..5efa32bba9 --- /dev/null +++ b/Task/Im-a-software-engineer-get-me-out-of-here/Java/im-a-software-engineer-get-me-out-of-here.java @@ -0,0 +1,211 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public final class ImASoftwareEngineerGetMeOutOfHere { + + public static void main(String[] args) { + searchFromCell(11, 11); + showShortestRoutesToSafety(); + System.out.println(); + + searchFromCell(21, 11); + System.out.println("The shortest route from (21, 11) to (1, 11):"); + System.out.println(createRouteToCell(1, 11)); + System.out.println(); + + searchFromCell(1, 11); + System.out.println("The shortest route from (1, 11) to (21, 11):"); + System.out.println(createRouteToCell(21, 11)); + System.out.println(); + + searchFromCell(11, 11); + showUnreachableCells(); + System.out.println(); + + showCellsWithLongestRouteFromHQ(); + } + + private static void searchFromCell(int row, int col) { + routes = IntStream.range(0, HEIGHT).boxed() + .map( i -> new ArrayList(Collections.nCopies(WIDTH, CellWithCost.ZERO)) ) + .collect(Collectors.toList()); + routes.get(row).set(col, new CellWithCost(row, col, 0)); + + List route = new ArrayList(); + int cost = 0; + + while ( true ) { + final int startDigit = Character.digit(GMOOH[row].charAt(col), 10); + for ( Cell direction : directions ) { + final int nextRow = row + startDigit * direction.row; + final int nextCol = col + startDigit * direction.col; + if ( nextCol >= 0 && nextCol < WIDTH && nextRow >= 0 && nextRow < HEIGHT + && Character.digit(GMOOH[nextRow].charAt(nextCol), 10) >= 0 ) { + CellWithCost currentCell = routes.get(nextRow).get(nextCol); + if ( currentCell.equals(CellWithCost.ZERO) || currentCell.cost > cost + 1 ) { + routes.get(nextRow).set(nextCol, new CellWithCost(row, col, cost + 1)); + if ( Character.digit(GMOOH[nextRow].charAt(nextCol), 10) > 0 ) { + route.addLast( new CellWithCost(nextRow, nextCol, cost + 1) ); + } + } + } + } + + if ( route.isEmpty() ) { // All routes have been searched + break; + } + + CellWithCost nextCell = route.removeFirst(); + row = nextCell.fromRow; + col = nextCell.fromCol; + cost = nextCell.cost; + } + } + + private static void showShortestRoutesToSafety() { + int minimumCost = Integer.MAX_VALUE; + List cells = new ArrayList(); + for ( int col = 0; col < WIDTH; col++ ) { + for ( int row = 0; row < HEIGHT; row++ ) { + if ( Character.digit(GMOOH[row].charAt(col), 10) == 0 ) { + CellWithCost currentCell = routes.get(row).get(col); + if ( ! currentCell.equals(CellWithCost.ZERO) ) { + final int cost = currentCell.cost; + if ( cost <= minimumCost ) { + if ( cost < minimumCost ) { + cells.clear(); + minimumCost = cost; + } + cells.addLast( new Cell(row, col) ); + } + } + } + } + } + + String areIs = ( cells.size() > 1 ) ? "are " : "is "; + String plural = ( cells.size() > 1 ) ? "s" : ""; + System.out.println("There " + areIs + cells.size() + " shortest route" + plural + + " of " + minimumCost + " days to safety:"); + for ( Cell cell : cells ) { + System.out.println(createRouteToCell(cell.row, cell.col)); + } + } + + private static List createRouteToCell(int row, int col) { + List route = new ArrayList(); + route.addLast( new Cell(row, col) ); + + while ( true ) { + CellWithCost currentCell = routes.get(row).get(col); + if ( currentCell.cost == 0 ) { + break; + } + + row = currentCell.fromRow; + col = currentCell.fromCol; + route.addFirst( new Cell(row, col) ); + } + return route; + } + + private static void showUnreachableCells() { + List unreachableCells = new ArrayList(); + for ( int col = 0; col < WIDTH; col++ ) { + for ( int row = 0; row < HEIGHT; row++ ) { + if ( Character.digit(GMOOH[row].charAt(col), 10) >= 0 + && routes.get(row).get(col).equals(CellWithCost.ZERO) ) { + unreachableCells.addLast( new Cell(row, col) ); + } + } + } + + System.out.println("The following cells are unreachable:"); + System.out.println(unreachableCells); + } + + private static void showCellsWithLongestRouteFromHQ() { + int maximumCost = Integer.MIN_VALUE; + List cells = new ArrayList(); + for ( int col = 0; col < WIDTH; col++ ) { + for ( int row = 0; row < HEIGHT; row++ ) { + if ( Character.digit(GMOOH[row].charAt(col), 10) >= 0 ) { + CellWithCost currentCell = routes.get(row).get(col); + if ( ! currentCell.equals(CellWithCost.ZERO) ) { + final int cost = currentCell.cost; + if ( cost >= maximumCost) { + if ( cost > maximumCost ) { + cells.clear(); + maximumCost = cost; + } + cells.addLast( new Cell(row, col) ); + } + } + } + } + } + + System.out.println("There are " + cells.size() + " cells that require " + maximumCost + + " days to receive reinforcements from HQ:"); + for ( Cell cell : cells ) { + System.out.println(createRouteToCell(cell.row, cell.col)); + } + } + + private static List> routes; + + private static final List directions = List.of( new Cell(1, -1), new Cell(1, 0), new Cell(1, 1), + new Cell(0, -1), new Cell(0, 1), + new Cell(-1, -1), new Cell(-1, 0), new Cell(-1, 1) ); + + private static record CellWithCost(int fromRow, int fromCol, int cost) { + + public boolean equals(CellWithCost other) { + return cost == other.cost && fromRow == other.fromRow && fromCol == other.fromCol; + } + + public static CellWithCost ZERO = new CellWithCost(0, 0, 0); + + } + + private static record Cell(int row, int col) { + + public String toString() { + return "(" + row + ", " + col + ")"; + } + + } + + private static final String[] GMOOH = """ + .........00000......... + ......00003130000...... + ....000321322221000.... + ...00231222432132200... + ..0041433223233211100.. + ..0232231612142618530.. + .003152122326114121200. + .031252235216111132210. + .022211246332311115210. + 00113232262121317213200 + 03152118212313211411110 + 03231234121132221411410 + 03513213411311414112320 + 00427534125412213211400 + .013322444412122123210. + .015132331312411123120. + .003333612214233913300. + ..0219126511415312570.. + ..0021321524341325100.. + ...00211415413523200... + ....000122111322000.... + ......00001120000...... + .........00000......... + """.split("\n"); + + private static final int WIDTH = GMOOH[0].length(); + private static final int HEIGHT = GMOOH.length; + +} diff --git a/Task/Imaginary-base-numbers/FreeBASIC/imaginary-base-numbers.basic b/Task/Imaginary-base-numbers/FreeBASIC/imaginary-base-numbers.basic new file mode 100644 index 0000000000..27125de4df --- /dev/null +++ b/Task/Imaginary-base-numbers/FreeBASIC/imaginary-base-numbers.basic @@ -0,0 +1,168 @@ +#define ceil(x) (-((-x*2.0-0.5) Shr 1)) + +Type Complex + real As Double + imag As Double +End Type + +Type QuaterImaginary + b2i As String +End Type + +Dim Shared As Complex c1, c2 + +Function StrReverse(Byval txt As String) As String + Dim result As String + For i As Integer = Len(txt) To 1 Step -1 + result &= Mid(txt, i, 1) + Next i + Return result +End Function + +Function ToChar(n As Integer) As String + Return Chr(n + Asc("0")) +End Function + +Function ComplexMul(lhs As Complex, rhs As Complex) As Complex + Dim As Complex result + result.real = rhs.real * lhs.real - rhs.imag * lhs.imag + result.imag = rhs.real * lhs.imag + rhs.imag * lhs.real + Return result +End Function + +Function ComplexMulR(lhs As Complex, rhs As Double) As Complex + Dim As Complex result + result.real = lhs.real * rhs + result.imag = lhs.imag * rhs + Return result +End Function + +Function ComplexInv(c As Complex) As Complex + Dim As Double denom + Dim As Complex result + denom = c.real * c.real + c.imag * c.imag + result.real = c.real / denom + result.imag = -c.imag / denom + Return result +End Function + +Function ComplexDiv(lhs As Complex, rhs As Complex) As Complex + Return ComplexMul(lhs, ComplexInv(rhs)) +End Function + +Function ComplexNeg(c As Complex) As Complex + Dim As Complex result + result.real = -c.real + result.imag = -c.imag + Return result +End Function + +Function ComplexSum(lhs As Complex, rhs As Complex) As Complex + Dim As Complex result + result.real = lhs.real + rhs.real + result.imag = lhs.imag + rhs.imag + Return result +End Function + +Function ToQuaterImaginary(c As Complex) As QuaterImaginary + Dim As Integer re, im, fi, rem_, index + Dim As Double f + Dim As Complex t + Dim As QuaterImaginary result + Dim As String sb + re = Int(c.real) + im = Int(c.imag) + fi = -1 + While re <> 0 + rem_ = (re Mod -4) + re = re \ (-4) + If rem_ < 0 Then + rem_ = 4 + rem_ + re += 1 + End If + sb &= ToChar(rem_) & "0" + Wend + If im <> 0 Then + t = ComplexDiv(Type(0.0, c.imag), Type(0.0, 2.0)) + f = t.real + im = Ceil(f) + f = -4.0 * (f - Cdbl(im)) + index = 1 + While im <> 0 + rem_ = im Mod -4 + im \= -4 + If rem_ < 0 Then + rem_ = 4 + rem_ + im += 1 + End If + If index < Len(sb) Then + Mid(sb, index + 1, 1) = ToChar(rem_) + Else + sb &= "0" & ToChar(rem_) + End If + index += 2 + Wend + fi = Int(f) + End If + sb = StrReverse(sb) + If fi <> -1 Then sb &= "." & ToChar(fi) + sb = Ltrim(sb, "0") + If Left(sb, 1) = "." Then sb = "0" & sb + result.b2i = sb + Return result +End Function + +Function ToComplex(qi As QuaterImaginary) As Complex + Dim As Integer j, pointPos, posLen, b2iLen + Dim As Double k + Dim As Complex sum, prod + pointPos = Instr(qi.b2i, ".") + posLen = Iif(pointPos = 0, Len(qi.b2i), pointPos - 1) + sum.real = 0.0 + sum.imag = 0.0 + prod.real = 1.0 + prod.imag = 0.0 + For j = 0 To posLen - 1 + k = Val(Mid(qi.b2i, posLen - j, 1)) + If k > 0.0 Then sum = ComplexSum(sum, ComplexMulR(prod, k)) + prod = ComplexMul(prod, Type(0.0, 2.0)) + Next + If pointPos <> 0 Then + prod = ComplexInv(Type(0.0, 2.0)) + b2iLen = Len(qi.b2i) + For j = posLen + 1 To b2iLen - 1 + k = Val(Mid(qi.b2i, j + 1, 1)) + If k > 0.0 Then sum = ComplexSum(sum, ComplexMulR(prod, k)) + prod = ComplexMul(prod, ComplexInv(Type(0.0, 2.0))) + Next + End If + Return sum +End Function + +Dim As QuaterImaginary qi +Dim As Integer i +For i = 1 To 16 + c1.real = Cdbl(i) + c1.imag = 0.0 + qi = ToQuaterImaginary(c1) + c2 = ToComplex(qi) + Print c1.real; "i -> "; qi.b2i; " -> "; c2.real; "i"; + c1 = ComplexNeg(c1) + qi = ToQuaterImaginary(c1) + c2 = ToComplex(qi) + Print c1.real; "i -> "; qi.b2i; " -> "; c2.real; "i" +Next +Print +For i = 1 To 16 + c1.real = 0.0 + c1.imag = Cdbl(i) + qi = ToQuaterImaginary(c1) + c2 = ToComplex(qi) + Print c1.imag; "i -> "; qi.b2i; " -> "; c2.imag; "i"; + c1 = ComplexNeg(c1) + qi = ToQuaterImaginary(c1) + c2 = ToComplex(qi) + Print c1.imag; "i -> "; qi.b2i; " -> "; c2.imag; "i" +Next + +Sleep diff --git a/Task/Include-a-file/PascalABC.NET/include-a-file-1.pas b/Task/Include-a-file/PascalABC.NET/include-a-file-1.pas new file mode 100644 index 0000000000..6dcd659652 --- /dev/null +++ b/Task/Include-a-file/PascalABC.NET/include-a-file-1.pas @@ -0,0 +1,5 @@ +{$include a.inc} + +begin + Hello +end. diff --git a/Task/Include-a-file/PascalABC.NET/include-a-file-2.pas b/Task/Include-a-file/PascalABC.NET/include-a-file-2.pas new file mode 100644 index 0000000000..ae2d6061f5 --- /dev/null +++ b/Task/Include-a-file/PascalABC.NET/include-a-file-2.pas @@ -0,0 +1 @@ +procedure Hello := Print('Hello'); diff --git a/Task/Increasing-gaps-between-consecutive-Niven-numbers/Sidef/increasing-gaps-between-consecutive-niven-numbers.sidef b/Task/Increasing-gaps-between-consecutive-Niven-numbers/Sidef/increasing-gaps-between-consecutive-niven-numbers.sidef new file mode 100644 index 0000000000..d2d19b6612 --- /dev/null +++ b/Task/Increasing-gaps-between-consecutive-Niven-numbers/Sidef/increasing-gaps-between-consecutive-niven-numbers.sidef @@ -0,0 +1,12 @@ +var threshold = 10_000_000 + +say "Gap Index of gap Starting Niven" +for (var (n=1, index=0, gap=0, prev=1); index <= threshold; ++n) { + n.is_div(n.digits_sum) || next + if ((var diff = (n - prev)) > gap) { + gap = diff + printf("%3d %15s %15s\n", gap, index, prev) + } + prev = n + ++index +} diff --git a/Task/Increment-a-numerical-string/Uiua/increment-a-numerical-string.uiua b/Task/Increment-a-numerical-string/Uiua/increment-a-numerical-string.uiua new file mode 100644 index 0000000000..eaabfbd1b3 --- /dev/null +++ b/Task/Increment-a-numerical-string/Uiua/increment-a-numerical-string.uiua @@ -0,0 +1,2 @@ +IncString ← ⍜⋕(+1) +IncString "99" diff --git a/Task/Infinity/PascalABC.NET/infinity.pas b/Task/Infinity/PascalABC.NET/infinity.pas new file mode 100644 index 0000000000..6ba97dc78a --- /dev/null +++ b/Task/Infinity/PascalABC.NET/infinity.pas @@ -0,0 +1,2 @@ +## +Write(real.PositiveInfinity); diff --git a/Task/Inheritance-Multiple/PascalABC.NET/inheritance-multiple.pas b/Task/Inheritance-Multiple/PascalABC.NET/inheritance-multiple.pas new file mode 100644 index 0000000000..6409dc0ced --- /dev/null +++ b/Task/Inheritance-Multiple/PascalABC.NET/inheritance-multiple.pas @@ -0,0 +1,19 @@ +type + IMy1 = interface + procedure My1; + end; + IMy2 = interface + procedure My2; + end; + MyClass = class(IMy1,IMy2) + public + procedure My1 := Writeln('My1'); + procedure My2 := Writeln('My2'); + end; + MyClassD = class(MyClass,IMy1,IMy2) + end; + +begin + var my := new MyClassD; + my.My1; my.My2; +end. diff --git a/Task/Inheritance-Single/PascalABC.NET/inheritance-single.pas b/Task/Inheritance-Single/PascalABC.NET/inheritance-single.pas new file mode 100644 index 0000000000..fa5f1a7069 --- /dev/null +++ b/Task/Inheritance-Single/PascalABC.NET/inheritance-single.pas @@ -0,0 +1,6 @@ +type + Animal = class end; + Dog = class(Animal) end; + Cat = class(Animal) end; + Lab = class(Dog) end; + Collie = class(Dog) end; diff --git a/Task/Input-loop/PascalABC.NET/input-loop.pas b/Task/Input-loop/PascalABC.NET/input-loop.pas new file mode 100644 index 0000000000..7214f03b64 --- /dev/null +++ b/Task/Input-loop/PascalABC.NET/input-loop.pas @@ -0,0 +1,6 @@ +begin + var f := OpenRead('a.txt'); + while not f.Eof do + Println(f.ReadString); + f.Close; +end. diff --git a/Task/Integer-comparison/PascalABC.NET/integer-comparison.pas b/Task/Integer-comparison/PascalABC.NET/integer-comparison.pas new file mode 100644 index 0000000000..9902a57821 --- /dev/null +++ b/Task/Integer-comparison/PascalABC.NET/integer-comparison.pas @@ -0,0 +1,8 @@ +begin + var (a,b) := ReadInteger2('Enter a,b:'); + if a < b then + Println($'{a} is less then {b}') + else if a > b then + Println($'{a} is greater then {b}') + else Println($'{a} is equal to then {b}') +end. diff --git a/Task/Integer-sequence/Kotlin/integer-sequence.kotlin b/Task/Integer-sequence/Kotlin/integer-sequence.kotlin index 72fec53d9d..f4dbecd12e 100644 --- a/Task/Integer-sequence/Kotlin/integer-sequence.kotlin +++ b/Task/Integer-sequence/Kotlin/integer-sequence.kotlin @@ -1,15 +1,10 @@ import java.math.BigInteger -// version 1.0.5-2 +fun main() { + // Using a 64-bit unsigned type, print until 18446744073709551615 + (1u..ULong.MAX_VALUE).forEach { println(it) } -fun main(args: Array) { - // print until 2147483647 - (0..Int.MAX_VALUE).forEach { println(it) } - - // print forever - var n = BigInteger.ZERO - while (true) { - println(n) - n += BigInteger.ONE - } + // Using unlimited-size integers, print forever + var n = BigInteger.ONE + while (true) println(n++) } diff --git a/Task/Integer-sequence/PascalABC.NET/integer-sequence.pas b/Task/Integer-sequence/PascalABC.NET/integer-sequence-1.pas similarity index 100% rename from Task/Integer-sequence/PascalABC.NET/integer-sequence.pas rename to Task/Integer-sequence/PascalABC.NET/integer-sequence-1.pas diff --git a/Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas b/Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas new file mode 100644 index 0000000000..7b206716fb --- /dev/null +++ b/Task/Integer-sequence/PascalABC.NET/integer-sequence-2.pas @@ -0,0 +1 @@ +## 1.Step.Print diff --git a/Task/Integer-sequence/Uiua/integer-sequence.uiua b/Task/Integer-sequence/Uiua/integer-sequence.uiua new file mode 100644 index 0000000000..008b417081 --- /dev/null +++ b/Task/Integer-sequence/Uiua/integer-sequence.uiua @@ -0,0 +1 @@ +⍢(&p.+1)1 1 diff --git a/Task/Integer-sequence/Zig/integer-sequence.zig b/Task/Integer-sequence/Zig/integer-sequence.zig new file mode 100644 index 0000000000..b3e6c9abd9 --- /dev/null +++ b/Task/Integer-sequence/Zig/integer-sequence.zig @@ -0,0 +1,9 @@ +const stdout = @import("std").io.getStdOut().writer(); + +pub fn main() !void { + var i: u128 = 1; + + while (true) : (i += 1) { + try stdout.print("{}, ", .{i}); + } +} diff --git a/Task/Introspection/Jq/introspection.jq b/Task/Introspection/Jq/introspection.jq new file mode 100644 index 0000000000..62605aed02 --- /dev/null +++ b/Task/Introspection/Jq/introspection.jq @@ -0,0 +1,23 @@ +def checkVersion: + $version + | capture("^[^- ]*(?[- ])(?[0-9]*)[.](?[0-9]*)") // {jq: 0} + | if .jq == 0 then "unrecognized version identification: \($version)" | error + elif .jq == "-" # jq + and (.major < "1" or (.major == "1" and .minor < "5")) + then "version \($version) is too old" | error + elif .jq == " " # gojq + and (.major == "0" and (.minor | tonumber) < 12) + then "version \($version) is too old" | error + else . + end; + + checkVersion + + # Check that abs/0 is defined + | (builtins | index("abs/0")) as $ix + | if $ix == null then "abs/0 not available" | error else . end + + # Is bloop a global variable? + | if ($ARGS.named | has("bloop")) then $ARGS.named["bloop"] | abs + else "There is no globally defined variable name $bloop." | error + end diff --git a/Task/Inverted-index/Ada/inverted-index-7.ada b/Task/Inverted-index/Ada/inverted-index-7.ada index 7146057dd2..d12c9b489b 100644 --- a/Task/Inverted-index/Ada/inverted-index-7.ada +++ b/Task/Inverted-index/Ada/inverted-index-7.ada @@ -68,8 +68,8 @@ package body Generic_Inverted_Index is procedure Iterate(The_Sources: Vector) is begin - for Some_Element in The_Sources loop - Do_Something(Element(Some_Element)); + for Some_Element of The_Sources loop + Do_Something(Some_Element); end loop; end Iterate; diff --git a/Task/Iterated-digits-squaring/EasyLang/iterated-digits-squaring.easy b/Task/Iterated-digits-squaring/EasyLang/iterated-digits-squaring.easy new file mode 100644 index 0000000000..e28ec70bb3 --- /dev/null +++ b/Task/Iterated-digits-squaring/EasyLang/iterated-digits-squaring.easy @@ -0,0 +1,38 @@ +fastfunc ends89 n . + repeat + s = 0 + while n > 0 + d = n mod 10 + s += d * d + n = n div 10 + . + n = s + if n = 89 + return 1 + . + until n = 1 + . + return 0 +. +k = 8 +arrbase sums[] 0 +len sums[] k * 81 + 1 +sums[0] = 1 +for n = 1 to k + for i = n * 81 downto 1 + for j = 1 to 9 + s = j * j + if s > i + break 1 + . + sums[i] += sums[i - s] + . + . +. +cnt = 0 +for i = 1 to k * 81 + if ends89 i = 1 + cnt += sums[i] + . +. +print cnt diff --git a/Task/JSON/PascalABC.NET/json.pas b/Task/JSON/PascalABC.NET/json.pas new file mode 100644 index 0000000000..cec8dbb76f --- /dev/null +++ b/Task/JSON/PascalABC.NET/json.pas @@ -0,0 +1,20 @@ +{$reference System.Web.Extensions.dll} +uses System.Web.Script.Serialization; + +begin + var serializer := new JavaScriptSerializer; + var people := new Dictionary; + people.Add('1', 'John'); + people.Add('2', 'Susan'); + var json := serializer.Serialize(people); + Println(json); + var res := serializer.Deserialize&>(json); + Println(TypeName(res)); + Println(res); + + var jsonObject := serializer.DeserializeObject('{ "foo": 1, "bar": [10, "apples"] }') + as Dictionary; + Println(jsonObject); + var arr := jsonObject['bar'] as array of object; + arr.Println; +end. diff --git a/Task/Jaro-Winkler-distance/Sidef/jaro-winkler-distance.sidef b/Task/Jaro-Winkler-distance/Sidef/jaro-winkler-distance.sidef new file mode 100644 index 0000000000..0e03bd574e --- /dev/null +++ b/Task/Jaro-Winkler-distance/Sidef/jaro-winkler-distance.sidef @@ -0,0 +1,26 @@ +func jaro_winkler_distance(s,t) { + + var jaro_similarity = jaro(s, t) + + var prefix = 0 + for i in (0 .. min(3, s.len, t.len)) { + s.char(i) == t.char(i) ? ++prefix : break + } + + 1 - (prefix * 0.1 * (1 - jaro_similarity) + jaro_similarity) +} + +# usage: +# sidef script.sf < unixdict.txt + +var words = ARGF.slurp.words + +%w(accomodate definately goverment occured publically recieve seperate untill wich).each {|word| + + var result = Hash(words.map { (_, jaro_winkler_distance(word, _)) }...) + + say "\nClosest 5 dictionary words with a Jaro-Winkler distance < .15 from #{word}:" + result.grep {|_,v| v < .15 }.sort_by{|_,v| v }.head(5).each_2d {|k,v| + printf("%15s : %0.4f\n", k, v) + } +} diff --git a/Task/Jensens-Device/Asymptote/jensens-device.asymptote b/Task/Jensens-Device/Asymptote/jensens-device.asymptote new file mode 100644 index 0000000000..6aa8d24907 --- /dev/null +++ b/Task/Jensens-Device/Asymptote/jensens-device.asymptote @@ -0,0 +1,5 @@ +real temp = 0; +for(int i = 1; i <= 100; ++i) { + temp += 1/i; +} +write(temp); diff --git a/Task/Jensens-Device/BASIC256/jensens-device.basic b/Task/Jensens-Device/BASIC256/jensens-device.basic index 57eca3f589..4ab66b031f 100644 --- a/Task/Jensens-Device/BASIC256/jensens-device.basic +++ b/Task/Jensens-Device/BASIC256/jensens-device.basic @@ -1,3 +1,6 @@ +call Evaluation() +end + subroutine Evaluation() lo = 1 : hi = 100 : temp = 0 for i = lo to hi @@ -5,6 +8,3 @@ subroutine Evaluation() next i print temp end subroutine - -call Evaluation() -end diff --git a/Task/Jensens-Device/Chipmunk-Basic/jensens-device.basic b/Task/Jensens-Device/Chipmunk-Basic/jensens-device.basic new file mode 100644 index 0000000000..d04c6d6fef --- /dev/null +++ b/Task/Jensens-Device/Chipmunk-Basic/jensens-device.basic @@ -0,0 +1,11 @@ +100 call evaluation +110 end +120 sub evaluation() +130 lo = 1 +140 hi = 100 +150 temp = 0 +160 for i = lo to hi +170 temp = temp+(1/i) +180 next i +190 print temp +200 end sub diff --git a/Task/Jensens-Device/Dart/jensens-device.dart b/Task/Jensens-Device/Dart/jensens-device.dart new file mode 100644 index 0000000000..410c0687cb --- /dev/null +++ b/Task/Jensens-Device/Dart/jensens-device.dart @@ -0,0 +1,14 @@ +double i = 0; +double sum(int lo, int hi, double Function() term) { + double temp = 0; + for (i = lo.toDouble(); i <= hi; i++) temp += term(); + return temp; +} + +double termFunc() { + return 1.0 / i; +} + +void main() { + print(sum(1, 100, termFunc)); +} diff --git a/Task/Jensens-Device/GW-BASIC/jensens-device.basic b/Task/Jensens-Device/GW-BASIC/jensens-device.basic new file mode 100644 index 0000000000..951bc5e857 --- /dev/null +++ b/Task/Jensens-Device/GW-BASIC/jensens-device.basic @@ -0,0 +1,11 @@ +100 GOSUB 120 +110 END +120 REM Evaluation +130 LET A = 1 +140 LET B = 100 +150 LET T = 0 +160 FOR I = A TO B +170 LET T = T + (1/I) +180 NEXT I +190 PRINT T +200 RETURN diff --git a/Task/Jensens-Device/Gambas/jensens-device.gambas b/Task/Jensens-Device/Gambas/jensens-device.gambas new file mode 100644 index 0000000000..ecfb8848c9 --- /dev/null +++ b/Task/Jensens-Device/Gambas/jensens-device.gambas @@ -0,0 +1,17 @@ +Sub Evaluation() + + Dim i As Integer, lo As Integer = 1, hi As Integer = 100 + Dim tmp As Float = 0 + + For i = lo To hi + tmp += (1 / i) + Next + Print tmp + +End Sub + +Public Sub Main() + + Evaluation + +End diff --git a/Task/Jensens-Device/Minimal-BASIC/jensens-device.basic b/Task/Jensens-Device/Minimal-BASIC/jensens-device.basic new file mode 100644 index 0000000000..bab897a7b5 --- /dev/null +++ b/Task/Jensens-Device/Minimal-BASIC/jensens-device.basic @@ -0,0 +1,12 @@ +100 GOSUB 120 +110 GOTO 210 +120 REM Evaluation +130 LET A = 1 +140 LET B = 100 +150 LET T = 0 +160 FOR I = A TO B +170 LET T = T+(1/I) +180 NEXT I +190 PRINT T +200 RETURN +210 END diff --git a/Task/Jensens-Device/QBasic/jensens-device.basic b/Task/Jensens-Device/QBasic/jensens-device.basic new file mode 100644 index 0000000000..336575755d --- /dev/null +++ b/Task/Jensens-Device/QBasic/jensens-device.basic @@ -0,0 +1,12 @@ +CALL EVALUATION +END + +SUB Evaluation + LET lo = 1 + LET hi = 100 + LET temp = 0 + FOR i = lo TO hi + LET temp = temp + (1 / i) + NEXT i + PRINT temp +END SUB diff --git a/Task/Jensens-Device/Yabasic/jensens-device.basic b/Task/Jensens-Device/Yabasic/jensens-device.basic index 5296d4d9e6..8df2e59253 100644 --- a/Task/Jensens-Device/Yabasic/jensens-device.basic +++ b/Task/Jensens-Device/Yabasic/jensens-device.basic @@ -1,3 +1,6 @@ +Evaluation() +end + sub Evaluation() lo = 1 : hi = 100 : temp = 0 for i = lo to hi @@ -5,5 +8,3 @@ sub Evaluation() next i print temp end sub - -Evaluation() diff --git a/Task/JortSort/EasyLang/jortsort.easy b/Task/JortSort/EasyLang/jortsort.easy new file mode 100644 index 0000000000..eff2004f35 --- /dev/null +++ b/Task/JortSort/EasyLang/jortsort.easy @@ -0,0 +1,16 @@ +proc sort . d[] . + for i = 1 to len d[] - 1 + for j = i + 1 to len d[] + if d[j] < d[i] + swap d[j] d[i] + . + . + . +. +func jortsort arr[] . + orig[] = arr[] + sort arr[] + return if orig[] = arr[] +. +print jortsort [ 2 4 6 ] +print jortsort [ 4 2 6 ] diff --git a/Task/Josephus-problem/Ada/josephus-problem.ada b/Task/Josephus-problem/Ada/josephus-problem.ada index 4691ba817b..f17eb315f4 100644 --- a/Task/Josephus-problem/Ada/josephus-problem.ada +++ b/Task/Josephus-problem/Ada/josephus-problem.ada @@ -2,14 +2,14 @@ with Ada.Command_Line, Ada.Text_IO; procedure Josephus is - function Arg(Idx, Default: Positive) return Positive is -- read Argument(Idx) + function Arg(Index, Default: Positive) return Natural is -- read Argument(Index) (if Ada.Command_Line.Argument_Count >= Index - then Positive'Value(Ada.Command_Line.Argument(Index)) else Default); + then Natural'Value(Ada.Command_Line.Argument(Index)) else Default); - Prisoners: constant Positive := Arg(Idx => 1, Default => 41); - Steps: constant Positive := Arg(Idx => 2, Default => 3); - Survivors: constant Positive := Arg(Idx => 3, Default => 1); - Print: Boolean := (Arg(Idx => 4, Default => 1) = 1); + Prisoners: constant Positive := Arg(Index => 1, Default => 41); + Steps: constant Positive := Arg(Index => 2, Default => 3); + Survivors: constant Positive := Arg(Index => 3, Default => 1); + Print: Boolean := (Arg(Index => 4, Default => 1) = 1); subtype Index_Type is Natural range 0 .. Prisoners-1; Next: array(Index_Type) of Index_Type; @@ -20,8 +20,8 @@ begin ("N =" & Positive'Image(Prisoners) & ", K =" & Positive'Image(Steps) & (if Survivors > 1 then ", #survivors =" & Positive'Image(Survivors) else "")); - for Idx in Next'Range loop -- initialize Next - Next(Idx) := (Idx+1) mod Prisoners; + for Index in Next'Range loop -- initialize Next + Next(Index) := (Index+1) mod Prisoners; end loop; if Print then Ada.Text_IO.Put("Executed: "); diff --git a/Task/Jump-anywhere/PascalABC.NET/jump-anywhere.pas b/Task/Jump-anywhere/PascalABC.NET/jump-anywhere.pas new file mode 100644 index 0000000000..b4267993a6 --- /dev/null +++ b/Task/Jump-anywhere/PascalABC.NET/jump-anywhere.pas @@ -0,0 +1,15 @@ +label finish; + +begin + var a := MatrRandomInteger(3,4); + var found := False; + for var i:=0 to a.RowCount-1 do + for var j:=0 to a.ColCount-1 do + if a[i,j] = 10 then + begin + found := True; + goto finish; + end; +finish: + Print(found); +end. diff --git a/Task/Knights-tour/Jq/knights-tour.jq b/Task/Knights-tour/Jq/knights-tour.jq new file mode 100644 index 0000000000..92064b6305 --- /dev/null +++ b/Task/Knights-tour/Jq/knights-tour.jq @@ -0,0 +1,50 @@ +# The number of columns +def boardSize: 8; + +# {x,y} with .x >= 0 and .y >= 0 +def Square($x; $y): {$x, $y}; + +# Input: a Square assuming .x <= 25 +def notate: + .x as $x + | "abcdefghijklmnopqrstuvwxyz"[$x:$x+1] + "\(.y + 1)"; + +# Input: a Square +# Output: a stream of possible Squares reachable from . +def knightMoves: + def axisMoves: [1, 2, -1, -2]; + + # Is the input Square on the board? + def onBoard: + 0 <= .x and .x < boardSize and 0 <= .y and .y < boardSize; + + . as $s + | axisMoves + | combinations(2) + | select( (.[0]|length) != (.[1]|length) ) # abs + | Square($s.x + .[0]; $s.y + .[1]) + | select(onBoard) ; + +# $moves should be a non-empty array specifying an initial fragment of a possible tour +def knightTour($moves): + # Find the array of relevant possible one-step moves from the Square specified by . + def findMoves: + [ knightMoves | select( IN($moves[]) | not) ] ; + + ($moves[-1] | findMoves) as $fm + | if $fm == [] then $moves + else ($fm | min_by( findMoves|length )) as $next + | knightTour($moves + [$next]) + end ; + +def knightTourFrom($start): + knightTour([$start]) ; + +def example($square): + knightTourFrom($square) + | (_nwise(boardSize) | map("\(.x),\(.y)") | join(" ")), + "\nAlgebraic notation:", + (_nwise(boardSize) | map( notate ) | join(" ")) + ; + +example(Square(1; 1)) diff --git a/Task/Knuth-shuffle/PascalABC.NET/knuth-shuffle.pas b/Task/Knuth-shuffle/PascalABC.NET/knuth-shuffle.pas new file mode 100644 index 0000000000..6a208684e7 --- /dev/null +++ b/Task/Knuth-shuffle/PascalABC.NET/knuth-shuffle.pas @@ -0,0 +1,11 @@ +procedure Shuffle(a: array of T); +begin + for var i := a.Length - 1 downto 1 do + Swap(a[i], a[Random(i + 1)]); +end; + +begin + var a := Arr(1..9); + Shuffle(a); + a.Print; +end. diff --git a/Task/Kosaraju/11l/kosaraju.11l b/Task/Kosaraju/11l/kosaraju.11l index c23d8b7325..d3d13d5ea4 100644 --- a/Task/Kosaraju/11l/kosaraju.11l +++ b/Task/Kosaraju/11l/kosaraju.11l @@ -5,7 +5,7 @@ F kosaraju(g) V x = size V t = [[Int]()] * size - F visit(Int u) -> N + F visit(Int u) -> Void I !@vis[u] @vis[u] = 1B L(v) @g[u] @@ -18,7 +18,7 @@ F kosaraju(g) visit(u) V c = [0] * size - F assign(Int u, root) -> N + F assign(Int u, root) -> Void I @vis[u] @vis[u] = 0B @c[u] = root diff --git a/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy b/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy new file mode 100644 index 0000000000..30c4fe6ab0 --- /dev/null +++ b/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy @@ -0,0 +1,38 @@ +func[][] krpr a[][] b[][] . + for m = 1 to len a[][] + for p = 1 to len b[][] + r[][] &= [ ] + for n = 1 to len a[m][] + for q = 1 to len b[p][] + r[$][] &= a[m][n] * b[p][q] + . + . + . + . + return r[][] +. +func[][] krpow a[][] n . + r[][] = [ [ 1 ] ] + for i to n + r[][] = krpr a[][] r[][] + . + return r[][] +. +proc show p[][] . . + clear + n = len p[][] + sc = 100 / n + for r to n + for c to n + x = (c - 1) * sc + y = (r - 1) * sc + move x y + if p[r][c] = 1 + rect sc sc + . + . + . +. +show krpow [ [ 1 1 1 ] [ 1 0 1 ] [ 1 1 1 ] ] 5 +sleep 2 +show krpow [ [ 0 1 0 ] [ 1 1 1 ] [ 0 1 0 ] ] 5 diff --git a/Task/Kronecker-product/BASIC256/kronecker-product.basic b/Task/Kronecker-product/BASIC256/kronecker-product.basic new file mode 100644 index 0000000000..e8e357e6f5 --- /dev/null +++ b/Task/Kronecker-product/BASIC256/kronecker-product.basic @@ -0,0 +1,42 @@ +arraybase 1 +dim a(2, 2) +a[1,1] = 1 : a[1,2] = 2 : a[2,1] = 3 : a[2,2] = 4 +dim b(2, 2) +b[1,1] = 0 : b[1,2] = 5 : b[2,1] = 6 : b[2,2] = 7 +call kronecker_product(a, b) + +print +dim x(3, 3) +x[1,1] = 0 : x[1,2] = 1 : x[1,3] = 0 +x[2,1] = 1 : x[2,2] = 1 : x[2,3] = 1 +x[3,1] = 0 : x[3,2] = 1 : x[3,3] = 0 +dim y(3, 4) +y[1,1] = 1 : y[1,2] = 1 : y[1,3] = 1 : y[1,4] = 1 +y[2,1] = 1 : y[2,2] = 0 : y[2,3] = 0 : y[2,4] = 1 +y[3,1] = 1 : y[3,2] = 1 : y[3,3] = 1 : y[3,4] = 1 +call kronecker_product(x, y) +end + +subroutine kronecker_product(a, b) + ua1 = a[?][] + ua2 = a[][?] + + ub1 = b[?][] + ub2 = b[][?] + + for i = 1 to ua1 + for k = 1 to ub1 + print "["; + for j = 1 to ua2 + for l = 1 to ub2 + print rjust(a[i, j] * b[k, l], 2); + if j = ua1 and l = ub2 then + print "]" + else + print " "; + endif + next + next + next + next +end subroutine diff --git a/Task/Kronecker-product/EasyLang/kronecker-product.easy b/Task/Kronecker-product/EasyLang/kronecker-product.easy new file mode 100644 index 0000000000..a7f264cb44 --- /dev/null +++ b/Task/Kronecker-product/EasyLang/kronecker-product.easy @@ -0,0 +1,15 @@ +func[][] krpr a[][] b[][] . + for m = 1 to len a[][] + for p = 1 to len b[][] + r[][] &= [ ] + for n = 1 to len a[m][] + for q = 1 to len b[p][] + r[$][] &= a[m][n] * b[p][q] + . + . + . + . + return r[][] +. +print krpr [ [ 1 2 ] [ 3 4 ] ] [ [ 0 5 ] [ 6 7 ] ] +print krpr [ [ 0 1 0 ] [ 1 1 1 ] [ 0 1 0 ] ] [ [ 1 1 1 1 ] [ 1 0 0 1 ] [ 1 1 1 1 ] ] diff --git a/Task/Kronecker-product/Yabasic/kronecker-product.basic b/Task/Kronecker-product/Yabasic/kronecker-product.basic new file mode 100644 index 0000000000..07bfd6f99f --- /dev/null +++ b/Task/Kronecker-product/Yabasic/kronecker-product.basic @@ -0,0 +1,42 @@ +print +dim a(2, 2) +a(1,1) = 1 : a(1,2) = 2 : a(2,1) = 3 : a(2,2) = 4 +dim b(2, 2) +b(1,1) = 0 : b(1,2) = 5 : b(2,1) = 6 : b(2,2) = 7 +kronecker_product(a, b) + +print +dim a(3, 3) +a(1,1) = 0 : a(1,2) = 1 : a(1,3) = 0 +a(2,1) = 1 : a(2,2) = 1 : a(2,3) = 1 +a(3,1) = 0 : a(3,2) = 1 : a(3,3) = 0 +dim b(3, 4) +b(1,1) = 1 : b(1,2) = 1 : b(1,3) = 1 : b(1,4) = 1 +b(2,1) = 1 : b(2,2) = 0 : b(2,3) = 0 : b(2,4) = 1 +b(3,1) = 1 : b(3,2) = 1 : b(3,3) = 1 : b(3,4) = 1 +kronecker_product(a, b) +end + +sub kronecker_product(a, b) + local i, j, k, l + ua1 = arraysize(a(), 1) + ua2 = arraysize(a(), 2) + ub1 = arraysize(b(), 1) + ub2 = arraysize(b(), 2) + + for i = 1 to ua1 + for k = 1 to ub1 + print "["; + for j = 1 to ua2 + for l = 1 to ub2 + print a(i, j) * b(k, l) using "##"; + if j = ua1 and l = ub2 then + print "]" + else + print " "; + endif + next + next + next + next +end sub diff --git a/Task/Langtons-ant/Uiua/langtons-ant.uiua b/Task/Langtons-ant/Uiua/langtons-ant.uiua new file mode 100644 index 0000000000..a5117b76c4 --- /dev/null +++ b/Task/Langtons-ant/Uiua/langtons-ant.uiua @@ -0,0 +1,14 @@ +# Draw Langton's Ant. + +N ← 100 +# initialise dir pos map +[¯1 0] [50 50] ↯N_N 1 +# Run until out of bounds +⍢( + ⊙(⟜(⍜⊡(-:1))) + ⟨⍜(⊡1|¯)⇌|⇌⍜(⊡1|¯)⟩:⊙(⊡,,) + ⟜+ +| ≥0⋅/↧ +) +# Scale up +▽⟜≡▽4◌◌ diff --git a/Task/Largest-int-from-concatenated-ints/EasyLang/largest-int-from-concatenated-ints.easy b/Task/Largest-int-from-concatenated-ints/EasyLang/largest-int-from-concatenated-ints.easy new file mode 100644 index 0000000000..58f2ca1bef --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/EasyLang/largest-int-from-concatenated-ints.easy @@ -0,0 +1,23 @@ +func con a b . + t = 10 + while b >= t + t *= 10 + . + return a * t + b +. +func$ max a[] . + n = len a[] + for i to n - 1 + for j = i + 1 to n + if con a[i] a[j] < con a[j] a[i] + swap a[i] a[j] + . + . + . + for v in a[] + r$ &= v + . + return r$ +. +print max [ 1 34 3 98 9 76 45 4 ] +print max [ 54 546 548 60 ] diff --git a/Task/Largest-int-from-concatenated-ints/Uiua/largest-int-from-concatenated-ints.uiua b/Task/Largest-int-from-concatenated-ints/Uiua/largest-int-from-concatenated-ints.uiua new file mode 100644 index 0000000000..be87ff429a --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Uiua/largest-int-from-concatenated-ints.uiua @@ -0,0 +1,2 @@ +A ← {[212 21221] [1 34 3 98 9 76 45 4][54 546 548 60]} +≡(⋕/◇⊂⊏⊸(⍖≡↯[/↥≡⧻]).°⋕)A diff --git a/Task/Largest-number-divisible-by-its-digits/Ada/largest-number-divisible-by-its-digits.ada b/Task/Largest-number-divisible-by-its-digits/Ada/largest-number-divisible-by-its-digits.ada new file mode 100644 index 0000000000..442f3edee6 --- /dev/null +++ b/Task/Largest-number-divisible-by-its-digits/Ada/largest-number-divisible-by-its-digits.ada @@ -0,0 +1,48 @@ +-- Largest number divisible by its digits; analysis under Raku +-- J. Carter 2024 May + +with Ada.Text_IO; + +procedure LNDBID is + Magic : constant := 9 * 8 * 7; + + function Good (Number : in Positive) return Boolean; + -- Returns True if Number's decimal representation has only unique digits and is evenly divisible by each of its digits + + function Good (Number : in Positive) return Boolean is + subtype Digit is Character range '1' .. '9'; + + type Count_List is array (Digit) of Natural; + + Count : Count_List := (Digit => 0); + + Raw : String renames Number'Image; + Image : String renames Raw (2 .. Raw'Last); + begin -- Good + if (for some D of Image => D in '0' | '5') then + return False; + end if; + + Count_Them : for D of Image loop + Count (D) := Count (D) + 1; + end loop Count_Them; + + if (for some V of Count => V > 1) then + return False; + end if; + + return (for all D of Image => Number rem (Character'Pos (D) - Character'Pos ('0') ) = 0); + end Good; + + Number : Positive := Magic * (9876432 / Magic); +begin -- LNDBID + Check : loop + if Good (Number) then + Ada.Text_IO.Put_Line (Item => Number'Image); + + return; + end if; + + Number := Number - Magic; + end loop Check; +end LNDBID; diff --git a/Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits.cpp b/Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits-1.cpp similarity index 100% rename from Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits.cpp rename to Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits-1.cpp diff --git a/Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits-2.cpp b/Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits-2.cpp new file mode 100644 index 0000000000..f5419a2916 --- /dev/null +++ b/Task/Largest-number-divisible-by-its-digits/C++/largest-number-divisible-by-its-digits-2.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +#include + +std::string to_hex_string(const uint64_t& hexadecimal) { + std::stringstream stream; + stream << std::hex << hexadecimal; + return stream.str(); +} + +bool is_lynch_bell(const uint64_t& hexadecimal) { + std::string hex_string = to_hex_string(hexadecimal); + if ( hex_string.find('0') != std::string::npos ) { + return false; + } + + std::unordered_set distinct_digits = { }; + for ( const char ch : hex_string ) { + distinct_digits.insert(( ch >= 'a') ? ( ch - 'a' + 10 ) : ( ch - '0' )); + } + if ( distinct_digits.size() < hex_string.size() ) { + return false; + } + + for ( const uint32_t& digit : distinct_digits ) { + if ( hexadecimal % digit > 0 ) { + return false; + } + } + return true; +} + +int main() { + const uint64_t hex_divisor = 15 * 14 * 13 * 12 * 11; + + uint64_t hexadecimal = ( 0xfedcba987654321L / hex_divisor ) * hex_divisor; + while ( ! is_lynch_bell(hexadecimal) ) { + hexadecimal -= hex_divisor; + } + std::cout << "The largest hexadecimal Lynch-Bell number is " << to_hex_string(hexadecimal) << std::endl; +} diff --git a/Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits.java b/Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits-1.java similarity index 100% rename from Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits.java rename to Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits-1.java diff --git a/Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits-2.java b/Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits-2.java new file mode 100644 index 0000000000..9189c73708 --- /dev/null +++ b/Task/Largest-number-divisible-by-its-digits/Java/largest-number-divisible-by-its-digits-2.java @@ -0,0 +1,56 @@ +import java.util.Arrays; +import java.util.List; + +public final class LargestNumberDivisibleByItsDigits { + + public static void main(String[] args) { + // Base 10 + final int decimalDivisor = 9 * 8 * 7; + int decimal = ( 9876432 / decimalDivisor ) * decimalDivisor; + + while ( ! isLynchBellDecimal(decimal) ) { + decimal -= decimalDivisor; + } + System.out.println("The largest decimal Lynch-Bell number is " + decimal); + + // Base 16 + final long hexDivisor = 15L * 14 * 13 * 12 * 11; + + long hexadecimal = ( 0xfedcba987654321L / hexDivisor ) * hexDivisor; + while ( ! isLynchBellHex(hexadecimal) ) { + hexadecimal -= hexDivisor; + } + System.out.println("The largest hexadecimal Lynch-Bell number is " + Long.toHexString(hexadecimal)); + } + + private static boolean isLynchBellDecimal(int decimal) { + String decimalString = Integer.toString(decimal); + if ( decimalString.contains("0") || decimalString.contains("5") ) { + return false; + } + + List distinctDigits = + Arrays.stream(decimalString.split("")).map( s -> Integer.valueOf(s) ).distinct().toList(); + if ( distinctDigits.size() < decimalString.length() ) { + return false; + } + + return distinctDigits.stream().allMatch( i -> ( decimal % i ) == 0 ); + } + + private static boolean isLynchBellHex(long hexadecimal) { + String hexString = Long.toHexString(hexadecimal); + if ( hexString.contains("0") ) { + return false; + } + + List distinctDigits = + Arrays.stream(hexString.split("")).map( s -> Integer.valueOf(s, 16) ).distinct().toList(); + if ( distinctDigits.size() < hexString.length() ) { + return false; + } + + return distinctDigits.stream().allMatch( i -> ( hexadecimal % i ) == 0 ); + } + +} diff --git a/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy b/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy new file mode 100644 index 0000000000..fc6da4d81f --- /dev/null +++ b/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy @@ -0,0 +1,43 @@ +repeat + s$ = input + until s$ = "" + for n$ in strsplit s$ " " + pok$[] &= n$ + . +. +# +chain$[] = [ ] +proc search lng . . + if lng > len chain$[] + chain$[] = [ ] + for j to lng + chain$[] &= pok$[j] + . + . + lastc$ = substr pok$[lng] len pok$[lng] 1 + for i = lng + 1 to len pok$[] + if substr pok$[i] 1 1 = lastc$ + swap pok$[i] pok$[lng + 1] + search lng + 1 + swap pok$[i] pok$[lng + 1] + . + . +. +for i to len pok$[] + swap pok$[i] pok$[1] + search 1 + swap pok$[i] pok$[1] +. +for p$ in chain$[] + write p$ & " " +. +# +input_data +audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon +cresselia croagunk darmanitan deino emboar emolga exeggcute gabite +girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan +kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine +nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 +porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking +sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko +tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask diff --git a/Task/Latin-Squares-in-reduced-form/11l/latin-squares-in-reduced-form.11l b/Task/Latin-Squares-in-reduced-form/11l/latin-squares-in-reduced-form.11l index de09bb38e8..e6c75a51df 100644 --- a/Task/Latin-Squares-in-reduced-form/11l/latin-squares-in-reduced-form.11l +++ b/Task/Latin-Squares-in-reduced-form/11l/latin-squares-in-reduced-form.11l @@ -6,7 +6,7 @@ F dList(n, =start) a.sort_range(1..) V first = a[1] [[Int]] r - F recurse(Int last) -> N + F recurse(Int last) -> Void I (last == @first) L(v) @a[1..] I L.index + 1 == v @@ -41,7 +41,7 @@ F reducedLatinSquares(n, echo) rlatin[0][j] = j + 1 V count = 0 - F recurse(Int i) -> N + F recurse(Int i) -> Void V rows = dList(@n, i) L(r) 0 .< rows.len diff --git a/Task/Least-common-multiple/PascalABC.NET/least-common-multiple.pas b/Task/Least-common-multiple/PascalABC.NET/least-common-multiple.pas new file mode 100644 index 0000000000..6435af5741 --- /dev/null +++ b/Task/Least-common-multiple/PascalABC.NET/least-common-multiple.pas @@ -0,0 +1,12 @@ +function GCD(a,b: integer): integer; +begin + while b > 0 do + (a,b) := (b,a mod b); + Result := a; +end; + +function LCM(a,b: integer): integer := a = 0 ? 0 : a div GCD(a,b) * b; + +begin + Println(LCM(12,18)); +end. diff --git a/Task/Least-common-multiple/Standard-ML/least-common-multiple-1.ml b/Task/Least-common-multiple/Standard-ML/least-common-multiple-1.ml new file mode 100644 index 0000000000..f8dab0fca7 --- /dev/null +++ b/Task/Least-common-multiple/Standard-ML/least-common-multiple-1.ml @@ -0,0 +1,4 @@ +fun gcd (0,n) = n + | gcd (m,n) = gcd(n mod m, m) + +fun lcm (m,n) = abs(x * y) div gcd (m, n) diff --git a/Task/Least-common-multiple/Standard-ML/least-common-multiple.ml b/Task/Least-common-multiple/Standard-ML/least-common-multiple-2.ml similarity index 100% rename from Task/Least-common-multiple/Standard-ML/least-common-multiple.ml rename to Task/Least-common-multiple/Standard-ML/least-common-multiple-2.ml diff --git a/Task/Least-common-multiple/Uiua/least-common-multiple.uiua b/Task/Least-common-multiple/Uiua/least-common-multiple.uiua new file mode 100644 index 0000000000..8fac60e0d5 --- /dev/null +++ b/Task/Least-common-multiple/Uiua/least-common-multiple.uiua @@ -0,0 +1,4 @@ +# Greatest Common Divisor using Euclidean algorithm +Gcd ← ⊙◌⍢(⟜◿:|±,) +# Least Common Multiple +Lcm ← ÷⊃(Gcd|⌵×) diff --git a/Task/Letter-frequency/Emacs-Lisp/letter-frequency.l b/Task/Letter-frequency/Emacs-Lisp/letter-frequency.l index 3daa2b94ea..3d9cd34ac1 100644 --- a/Task/Letter-frequency/Emacs-Lisp/letter-frequency.l +++ b/Task/Letter-frequency/Emacs-Lisp/letter-frequency.l @@ -1,14 +1,15 @@ (defun tally-letter-frequency-in-file () - (let ((alphabet "abcdefghijklmnopqrstuvwxyz") - (current-letter) - (count) - (case-fold-search t)) ; ignores case - (find-file "~/Documents/Elisp/MobyDick.txt") ; identify file to work with - (while (>= (length alphabet) 1) ; as long as there is at least 1 letter left in alphabet - (beginning-of-buffer) + "Open a file and count the number of times each letter appears." + (let ((alphabet "abcdefghijklmnopqrstuvwxyz") ; variable to hold letters we will be counting + (current-letter) ; variable to hold current letter we will be counting + (count) ; variable to count how many times current letter appears + (case-fold-search t)) ; ignores case + (find-file "~/Documents/Elisp/MobyDick.txt") ; open file in a buffer (or switch to buffer if file is already open) + (while (>= (length alphabet) 1) ; as long as there is at least 1 letter left in alphabet + (beginning-of-buffer) ; go to the beginning of the buffer (setq current-letter (substring alphabet 0 1)) ; set current-letter to first letter of alphabet - (setq count (how-many current-letter)) ; count how many of this letter in file - (end-of-buffer) - (insert (format "\n%s%s - %7d" current-letter (upcase current-letter) count)) - (setq alphabet (substring alphabet 1 nil))) ; remove first letter from alphabet + (setq count (how-many current-letter)) ; count how many of this letter in file + (end-of-buffer) ; go to the end of the buffer + (insert (format "\n%s%s - %7d" current-letter (upcase current-letter) count)) ; write how many times that letter appears + (setq alphabet (substring alphabet 1 nil))) ; remove first letter from alphabet (insert "\n"))) diff --git a/Task/Letter-frequency/Langur/letter-frequency.langur b/Task/Letter-frequency/Langur/letter-frequency.langur index 085e7258f8..c21156b15c 100644 --- a/Task/Letter-frequency/Langur/letter-frequency.langur +++ b/Task/Letter-frequency/Langur/letter-frequency.langur @@ -1,8 +1,8 @@ -val .countLetters = fn(.s) { - for[=h{}] .s2 in split(replace(.s, RE/\P{L}/)) { - _for[.s2; 0] += 1 +val countLetters = fn(s) { + for[={:}] s2 in split(replace(s, RE/\P{L}/)) { + _for[s2; 0] += 1 } } -val .counts = .countLetters(readfile "./fuzz.txt") -writeln join "\n", map fn(.k) $"\.k;: \.counts[.k];", keys .counts +val counts = countLetters(readfile("./fuzz.txt")) +writeln join("\n", map(fn(k) { "{{k}}: {{counts[k]}}" }, keys(counts))) diff --git a/Task/Letter-frequency/Refal/letter-frequency.refal b/Task/Letter-frequency/Refal/letter-frequency.refal new file mode 100644 index 0000000000..9319452d9f --- /dev/null +++ b/Task/Letter-frequency/Refal/letter-frequency.refal @@ -0,0 +1,48 @@ +$ENTRY Go { + , : { + = ; + e.File, : e.Text, + : e.Counts + = >; + }; +}; + +Letters { + = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; +}; + +ShowLetterCounts { + (e.T) = ; + (e.T) s.L e.Ls, + : s.UL, : s.ULN, + : s.LL, : s.LLN, + <+ s.ULN s.LLN>: s.Total + = > + ; +}; + +ReadFile { + s.Chan e.Filename = + + ; + (s.Chan), : { + 0 = ; + e.Line = e.Line '\n' ; + }; +}; + +Tally { + (e.T) = e.T; + (e.T) s.X e.Xs = ) e.Xs>; + e.Xs = ; +} + +Inc { + (e.1 (s.I s.N) e.2) s.I = e.1 (s.I <+ 1 s.N>) e.2; + (e.X) s.I = e.X (s.I 1); +}; + +Item { + (e.1 (s.I s.N) e.2) s.I = s.N; + (e.X) s.I = 0; +}; diff --git a/Task/Levenshtein-distance-Alignment/Jq/levenshtein-distance-alignment.jq b/Task/Levenshtein-distance-Alignment/Jq/levenshtein-distance-alignment.jq new file mode 100644 index 0000000000..4b89daf811 --- /dev/null +++ b/Task/Levenshtein-distance-Alignment/Jq/levenshtein-distance-alignment.jq @@ -0,0 +1,44 @@ +def reverseString: explode | reverse | implode; + +def levenshteinAlign($x; $y): + def min($a;$b): [$a,$b]|min; + + ($x|length + 1) as $a1 + | ($y|length + 1) as $b1 + | ($x | ascii_downcase) as $a + | ($y | ascii_downcase) as $b + | [range(0; $b1) | 0] as $zeros + | {costs: [range(0; $a1) | $zeros]} + | reduce range(0; $b1) as $j (.; .costs[0][$j] = $j) + | reduce range(1; $a1) as $i (.; + .costs[$i][0] = $i + | reduce range(1; $b1) as $j (.; + (.costs[$i - 1][$j - 1] + (if $a[$i - 1: $i] == $b[$j - 1: $j] then 0 else 1 end)) as $temp + | .costs[$i][$j] = min( $temp; 1 + min(.costs[$i - 1][$j]; .costs[$i][$j - 1] )) )) + + # walk back through matrix to figure out path + | .aPathRev = "" + | .bPathRev = "" + | .i = ($a|length) + | .j = ($b|length) + | until (.i == 0 or .j == 0; + (.costs[.i - 1][.j - 1] + (if $a[.i - 1: .i] == $b[.j - 1: .j] then 0 else 1 end)) as $temp + | .costs[.i][.j] as $cij + | if $cij == $temp + then .i += -1 + | .aPathRev += $a[.i: .i+1] + | .j += -1 + | .bPathRev += $b[.j: .j+1] + elif $cij == 1 + .costs[.i-1][.j] + then .i += -1 + | .aPathRev += $a[.i:.i+1] + | .bPathRev += "-" + elif $cij == 1 + .costs[.i][.j-1] + then .aPathRev += "-" + | .j += -1 + | .bPathRev += $b[.j: .j+1] + end) + | [.aPathRev, .bPathRev ] | map(reverseString); + +levenshteinAlign("place"; "palace"), +levenshteinAlign("rosettacode";"raisethysword") diff --git a/Task/Levenshtein-distance/JavaScript/levenshtein-distance-2.js b/Task/Levenshtein-distance/JavaScript/levenshtein-distance-2.js index 62203cea9b..c9624b62d5 100644 --- a/Task/Levenshtein-distance/JavaScript/levenshtein-distance-2.js +++ b/Task/Levenshtein-distance/JavaScript/levenshtein-distance-2.js @@ -1,32 +1,44 @@ (() => { - 'use strict'; + "use strict"; + + // ------------ LEVENSHTEIN EDIT DISTANCE ------------ // levenshtein :: String -> String -> Int - const levenshtein = sa => sb => { - const cs = chars(sa); - const go = (ns, c) => { - const calc = z => tpl => { - const [c1, x, y] = Array.from(tpl); - return minimum([ - succ(y), - succ(z), - x + (c !== c1 ? 1 : 0) - ]); + const levenshtein = sa => + // The Levenshtein edit distance + // between two given strings. + sb => { + const cs = [...sa]; + const go = (ns, c) => { + const calc = z => tpl => { + const [c1, x, y] = Array.from(tpl); + + return Math.min( + 1 + y, + 1 + z, + x + ( + c1 === c + ? 0 + : 1 + ) + ); + }; + const [n, ...ns1] = ns; + + return scanl(calc)(1 + n)( + zip3(cs)(ns)(ns1) + ); }; - const [n, ns1] = [ns[0], ns.slice(1)]; - return scanl(calc)(succ(n))( - zip3(cs)(ns)(ns1) + + return last( + [...sb].reduce( + go, + enumFromTo(0)(cs.length) + ) ); }; - return last( - chars(sb).reduce( - go, - enumFromTo(0)(cs.length) - ) - ); - }; - // ----------------------- TEST ------------------------ + // ---------------------- TEST ----------------------- const main = () => [ ["kitten", "sitting"], ["sitting", "kitten"], @@ -35,38 +47,7 @@ ].map(uncurry(levenshtein)); - // ----------------- GENERIC FUNCTIONS ----------------- - - // Tuple (,) :: a -> b -> (a, b) - const Tuple = a => - b => ({ - type: 'Tuple', - '0': a, - '1': b, - length: 2 - }); - - - // TupleN :: a -> b ... -> (a, b ... ) - function TupleN() { - const - args = Array.from(arguments), - n = args.length; - return 2 < n ? Object.assign( - args.reduce((a, x, i) => Object.assign(a, { - [i]: x - }), { - type: 'Tuple' + n.toString(), - length: n - }) - ) : args.reduce((f, x) => f(x), Tuple); - }; - - - // chars :: String -> [Char] - const chars = s => - s.split(''); - + // ---------------- GENERIC FUNCTIONS ---------------- // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => @@ -76,68 +57,53 @@ // last :: [a] -> a - const last = xs => ( + const last = xs => { // The last item of a list. - ys => 0 < ys.length ? ( - ys.slice(-1)[0] - ) : undefined - )(xs); + const n = xs.length; - - // minimum :: Ord a => [a] -> a - const minimum = xs => ( - // The least value of xs. - ys => 0 < ys.length ? ( - ys.slice(1) - .reduce((a, y) => y < a ? y : a, ys[0]) - ) : undefined - )(xs); - - - // length :: [a] -> Int - const length = xs => - // Returns Infinity over objects without finite - // length. This enables zip and zipWith to choose - // the shorter argument when one is non-finite, - // like cycle, repeat etc - 'GeneratorFunction' !== xs.constructor.constructor.name ? ( - xs.length - ) : Infinity; + return 0 < n + ? xs[n - 1] + : null; + }; // scanl :: (b -> a -> b) -> b -> [a] -> [b] - const scanl = f => startValue => xs => - xs.reduce((a, x) => { - const v = f(a[0])(x); - return Tuple(v)(a[1].concat(v)); - }, Tuple(startValue)([startValue]))[1]; + const scanl = f => + // The series of interim values arising + // from a catamorphism. Parallel to foldl. + startValue => xs => + xs.reduce( + (a, x) => { + const v = f(a[0])(x); - - // succ :: Enum a => a -> a - const succ = x => - 1 + x; + return [v, a[1].concat(v)]; + }, [startValue, [startValue]] + )[1]; // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => // A function over a pair, derived // from a curried function. - function () { + (...args) => { const - args = arguments, - xy = Boolean(args.length % 2) ? ( - args[0] - ) : args; - return f(xy[0])(xy[1]); + [x, y] = Boolean(args.length % 2) + ? args[0] + : args; + + return f(x)(y); }; // zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] const zip3 = xs => - ys => zs => xs - .slice(0, Math.min(...[xs, ys, zs].map(length))) - .map((x, i) => TupleN(x, ys[i], zs[i])); + ys => zs => xs.slice( + 0, + Math.min(...[xs, ys, zs].map(x => x.length)) + ) + .map((x, i) => [x, ys[i], zs[i]]); + // MAIN --- - return JSON.stringify(main()) + return JSON.stringify(main()); })(); diff --git a/Task/Levenshtein-distance/SETL/levenshtein-distance.setl b/Task/Levenshtein-distance/SETL/levenshtein-distance.setl new file mode 100644 index 0000000000..4d9a4a07c3 --- /dev/null +++ b/Task/Levenshtein-distance/SETL/levenshtein-distance.setl @@ -0,0 +1,26 @@ +program levenshtein_distance; + tests := {['kitten', 'sitting'], ['rosettacode', 'raisethysword']}; + loop for dest = tests(src) do + print(src + ' -> ' + dest + ': ' + str levenshtein(src, dest)); + end loop; + + proc levenshtein(s, t); + d := {}; + loop for i in [1..#s] do + d(i,0) := i; + end loop; + loop for j in [1..#t] do + d(0,j) := j; + end loop; + loop for j in [1..#t] do + loop for i in [1..#s] do + d(i,j) := min/[ + (d(i-1,j) ? 0) + 1, + (d(i,j-1) ? 0) + 1, + (d(i-1,j-1) ? 0) + if s(i) = t(j) then 0 else 1 end + ]; + end loop; + end loop; + return d(#s, #t); + end proc; +end program; diff --git a/Task/Levenshtein-distance/Uiua/levenshtein-distance.uiua b/Task/Levenshtein-distance/Uiua/levenshtein-distance.uiua new file mode 100644 index 0000000000..992383e0b3 --- /dev/null +++ b/Task/Levenshtein-distance/Uiua/levenshtein-distance.uiua @@ -0,0 +1,15 @@ +Lev ← |1 memo( + ±/↧≡◇⧻. + ⨬( + /↥≡◇⧻ # If either is zero, return length of other + | /≍≡◇⊢. # Both start with same letter? + ⨬( + # NO: 1 + min(Lev of (tail a, tail b), (tail a, b), (a, tail b)) + +1/↧≡Lev[⊃(⍚↘1|⍜⊢⍚↘1|⍜(⊡1|⍚↘1))] + | + Lev ⍚↘1 # YES: = Lev of (tail a, tail b) + ) + ) +) +Lev {"kitten" "sitting"} +Lev {"rosettacode" "raisethysword"} diff --git a/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas b/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas new file mode 100644 index 0000000000..3c888aa14f --- /dev/null +++ b/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas @@ -0,0 +1,2 @@ +## +(1..20).CartesianPower(3).Where(\(x,y,z) -> (x*x + y*y = z*z) and (x < y)).PrintLines diff --git a/Task/List-comprehensions/Uiua/list-comprehensions.uiua b/Task/List-comprehensions/Uiua/list-comprehensions.uiua new file mode 100644 index 0000000000..e4bed8401a --- /dev/null +++ b/Task/List-comprehensions/Uiua/list-comprehensions.uiua @@ -0,0 +1,3 @@ +☇1⊞≡⊂⊞⊂..+1⇡20 # Cartesian product, flattened. +▽⊸≡(=1/↧/≥◫2) # Keep triplets which are in ascending order. +▽⊸≡(=⊃(/+⊏0_1|⊡2)×.) # Keep pythagorean triplets. diff --git a/Task/Literals-Floating-point/PascalABC.NET/literals-floating-point.pas b/Task/Literals-Floating-point/PascalABC.NET/literals-floating-point.pas new file mode 100644 index 0000000000..f755fdbcca --- /dev/null +++ b/Task/Literals-Floating-point/PascalABC.NET/literals-floating-point.pas @@ -0,0 +1,3 @@ +1.0 +1e3 +2.5E-4 diff --git a/Task/Literals-String/PascalABC.NET/literals-string.pas b/Task/Literals-String/PascalABC.NET/literals-string.pas new file mode 100644 index 0000000000..c329e34bb9 --- /dev/null +++ b/Task/Literals-String/PascalABC.NET/literals-string.pas @@ -0,0 +1,4 @@ +## +var s1 := 'Hello'; +var s2 := 'quotes ''in'' string'; +var s3 := 'chars with a'#13#10'given code in string'; diff --git a/Task/Logical-operations/Langur/logical-operations.langur b/Task/Logical-operations/Langur/logical-operations.langur index bdcc9fcb79..ef567db8c9 100644 --- a/Task/Logical-operations/Langur/logical-operations.langur +++ b/Task/Logical-operations/Langur/logical-operations.langur @@ -1,24 +1,26 @@ -val .test = fn(.a, .b) join("\n", [ - $"not \.a;: \{not .a}", - $"\.a; and \.b;: \.a and .b;", - $"\.a; or \.b;: \.a or .b;", - $"\.a; nand \.b;: \.a nand .b;", - $"\.a; nor \.b;: \.a nor .b;", - $"\.a; xor \.b;: \.a xor .b;", - $"\.a; nxor \.b;: \.a nxor .b;", - "", +val test = fn(a, b) { + join("\n", [ + "not {{a}}: {{not a}}", + "{{a}} and {{b}}: {{a and b}}", + "{{a}} nand {{b}}: {{a nand b}}", + "{{a}} or {{b}}: {{a or b}}", + "{{a}} nor {{b}}: {{a nor b}}", + "{{a}} xor {{b}}: {{a xor b}}", + "{{a}} nxor {{b}}: {{a nxor b}}", + "", + + "not? {{a}}: {{not? a}}", + "{{a}} and? {{b}}: {{a and? b}}", + "{{a}} nand? {{b}}: {{a nand? b}}", + "{{a}} or? {{b}}: {{a or? b}}", + "{{a}} nor? {{b}}: {{a nor? b}}", + "{{a}} xor? {{b}}: {{a xor? b}}", + "{{a}} nxor? {{b}}: {{a nxor? b}}", + "\n", + ]) +} - $"not? \.a;: \{not? .a}", - $"\.a; and? \.b;: \.a and? .b;", - $"\.a; or? \.b;: \.a or? .b;", - $"\.a; nand? \.b;: \.a nand? .b;", - $"\.a; nor? \.b;: \.a nor? .b;", - $"\.a; xor? \.b;: \.a xor? .b;", - $"\.a; nxor? \.b;: \.a nxor? .b;", - "\n", -]) - -val .tests = [ +val tests = [ [true, false], [false, true], [true, true], @@ -32,6 +34,6 @@ val .tests = [ [null, null], ] -for .t in .tests { - write .test(.t[1], .t[2]) +for t in tests { + write test(t[1], t[2]) } diff --git a/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy b/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy index 91136e30d9..b7a1c9c571 100644 --- a/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy +++ b/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy @@ -1,5 +1,5 @@ func$ right a$ n . - return substr a$ -n n + return substr a$ (len a$ - n + 1) n . func$ left a$ n . if n < 0 diff --git a/Task/Longest-common-subsequence/PascalABC.NET/longest-common-subsequence.pas b/Task/Longest-common-subsequence/PascalABC.NET/longest-common-subsequence.pas new file mode 100644 index 0000000000..dd3ca9502b --- /dev/null +++ b/Task/Longest-common-subsequence/PascalABC.NET/longest-common-subsequence.pas @@ -0,0 +1,30 @@ +function Lengths(x,y: string): array[,] of integer; +begin + var (m,n) := (x.Length,y.Length); + var C := new integer[m+1, n+1]; // filled with zeroes + for var i:=1 to m do + for var j:=1 to n do + if x[i] = y[j] then + C[i,j] := C[i-1,j-1] + 1 + else C[i,j] := max(C[i,j-1], C[i-1,j]); + Result := C; +end; + +function lcshelper(x,y: string; i,j: integer): string; +begin + var C := Lengths(x,y); + if (i = 0) or (j = 0) then + Result := '' + else if X[i] = Y[j] then + Result := lcshelper(X, Y, i-1, j-1) + X[i] + else if C[i,j-1] > C[i-1,j] then + Result := lcshelper(X, Y, i, j-1) + else Result := lcshelper(X, Y, i-1, j) +end; + +function lcs(x,y: string) := lcshelper(x,y,x.Length,y.Length); + +begin + Println(lcs('1234','1224533324')); + Println(lcs('thisisatest','testing123testing')); +end. diff --git a/Task/Longest-common-substring/Langur/longest-common-substring.langur b/Task/Longest-common-substring/Langur/longest-common-substring.langur index 8cb9c31797..951978e86f 100644 --- a/Task/Longest-common-substring/Langur/longest-common-substring.langur +++ b/Task/Longest-common-substring/Langur/longest-common-substring.langur @@ -1,16 +1,16 @@ -val .lcs = fn(.s1, .s2) { - var .l, .r, .sublen = 1, 0, 0 - for .i of .s1 { - for .j in .i .. len(.s1) { - if not matching(s2s(.s1, .i .. .j), .s2): break - if .sublen <= .j - .i { - .l, .r = .i, .j - .sublen = .j - .i +val lcs = fn(s1, s2) { + var l, r, sublen = 1, 0, 0 + for i of s1 { + for j in i .. len(s1) { + if not matching(s2s(s1, i .. j), s2): break + if sublen <= j - i { + l, r = i, j + sublen = j - i } } } - if .r == 0: return "" - s2s .s1, .l .. .r + if r == 0: return "" + s2s s1, l .. r } -writeln .lcs("thisisatest", "testing123testing") +writeln lcs("thisisatest", "testing123testing") diff --git a/Task/Longest-increasing-subsequence/EasyLang/longest-increasing-subsequence.easy b/Task/Longest-increasing-subsequence/EasyLang/longest-increasing-subsequence.easy new file mode 100644 index 0000000000..139bb77f76 --- /dev/null +++ b/Task/Longest-increasing-subsequence/EasyLang/longest-increasing-subsequence.easy @@ -0,0 +1,37 @@ +func[] lis x[] . + n = len x[] + len p[] n + len m[] n + for i to n + lo = 1 + hi = lng + while lo <= hi + mid = (lo + hi) div 2 + if x[m[mid]] < x[i] + lo = mid + 1 + else + hi = mid - 1 + . + . + if lo > 1 + p[i] = m[lo - 1] + . + m[lo] = i + if lo > lng + lng = lo + . + . + len res[] lng + if lng > 0 + k = m[lng] + for i = lng downto 1 + res[i] = x[k] + k = p[k] + . + . + return res[] +. +tests[][] = [ [ 3 2 6 4 5 1 ] [ 0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15 ] ] +for x to len tests[][] + print lis tests[x][] +. diff --git a/Task/Look-and-say-sequence/ABC/look-and-say-sequence.abc b/Task/Look-and-say-sequence/ABC/look-and-say-sequence.abc new file mode 100644 index 0000000000..ddf99eaef0 --- /dev/null +++ b/Task/Look-and-say-sequence/ABC/look-and-say-sequence.abc @@ -0,0 +1,19 @@ +HOW TO RETURN look.and.say seq: + PUT "" IN result + PUT 0 IN n + PUT "" IN c + FOR ch IN seq: + SELECT: + c=ch: + PUT n+1 IN n + ELSE: + IF n>0: PUT result^"`n`"^c IN result + PUT 1 IN n + PUT ch IN c + RETURN result^"`n`"^c + +PUT "1" IN item + +FOR i IN {1..14}: + WRITE item/ + PUT look.and.say item IN item diff --git a/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy b/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy index 2a924dee19..94c6316232 100644 --- a/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy +++ b/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy @@ -1,5 +1,4 @@ proc lookandsay . a$ . - s$ = "" c = 1 p$ = substr a$ 1 1 for i = 2 to len a$ diff --git a/Task/Look-and-say-sequence/Uiua/look-and-say-sequence.uiua b/Task/Look-and-say-sequence/Uiua/look-and-say-sequence.uiua new file mode 100644 index 0000000000..2c91933898 --- /dev/null +++ b/Task/Look-and-say-sequence/Uiua/look-and-say-sequence.uiua @@ -0,0 +1,2 @@ +Rle ← /◇⊂≡⍚(⊂⊃(°⋕⧻|⊢))⊜□⊸(+1⊛) +⇌[⍥(⍚Rle.)10□] "1" diff --git a/Task/Loop-over-multiple-arrays-simultaneously/PascalABC.NET/loop-over-multiple-arrays-simultaneously.pas b/Task/Loop-over-multiple-arrays-simultaneously/PascalABC.NET/loop-over-multiple-arrays-simultaneously.pas new file mode 100644 index 0000000000..c2252b2610 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/PascalABC.NET/loop-over-multiple-arrays-simultaneously.pas @@ -0,0 +1,12 @@ +begin + var a1 := Arr('a','b','c'); + var a2 := Arr('A','B','C'); + var a3 := Arr(1,2,3); + for var i:=0 to a1.Length-1 do + Writeln(a1[i],a2[i],a3[i]); + Writeln; + foreach var (x,y,z) in a1.Zip(a2,a3) do + Writeln(x,y,z); + Writeln; + a1.Zip(a2,a3).PrintLines(t -> t[0]+t[1]+t[2]); +end. diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-5.py b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-5.py new file mode 100644 index 0000000000..533838e409 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-5.py @@ -0,0 +1,5 @@ +a1 = ['a', 'b', 'c'] +a2 = ['A', 'B', 'C'] +a3 = [1, 2, 3] +for i in range(len(a1)): + print(a1[i] + a2[i] + str(a3[i])) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Uiua/loop-over-multiple-arrays-simultaneously.uiua b/Task/Loop-over-multiple-arrays-simultaneously/Uiua/loop-over-multiple-arrays-simultaneously.uiua new file mode 100644 index 0000000000..be1c9e378f --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Uiua/loop-over-multiple-arrays-simultaneously.uiua @@ -0,0 +1 @@ +≡(⊂⊂) "abc" "ABC" "123" diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Vim-Script/loop-over-multiple-arrays-simultaneously.vim b/Task/Loop-over-multiple-arrays-simultaneously/Vim-Script/loop-over-multiple-arrays-simultaneously.vim new file mode 100644 index 0000000000..5272194e0b --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Vim-Script/loop-over-multiple-arrays-simultaneously.vim @@ -0,0 +1,6 @@ +let a1 = ['a', 'b', 'c'] +let a2 = ['A', 'B', 'C'] +let a3 = [1, 2, 3] +for i in range(0, len(a1) - 1) + echo a1[i] .. a2[i] .. a3[i] +endfor diff --git a/Task/Loops-Break/Langur/loops-break.langur b/Task/Loops-Break/Langur/loops-break.langur index ec8897cb73..7733b80fed 100644 --- a/Task/Loops-Break/Langur/loops-break.langur +++ b/Task/Loops-Break/Langur/loops-break.langur @@ -1,5 +1,5 @@ for { - val .i = random 0..19 - write .i, " " - if .i == 10 { writeln(); break } + val i = random(0..19) + write i, " " + if i == 10 { writeln(); break } } diff --git a/Task/Loops-Break/PascalABC.NET/loops-break.pas b/Task/Loops-Break/PascalABC.NET/loops-break.pas new file mode 100644 index 0000000000..849c5593e4 --- /dev/null +++ b/Task/Loops-Break/PascalABC.NET/loops-break.pas @@ -0,0 +1,10 @@ +begin + while True do + begin + var x := Random(0,19); + Print(x); + if x = 10 then + break; + Print(Random(0,19)); + end; +end. diff --git a/Task/Loops-Break/S-BASIC/loops-break-1.basic b/Task/Loops-Break/S-BASIC/loops-break-1.basic new file mode 100644 index 0000000000..24f1eddf52 --- /dev/null +++ b/Task/Loops-Break/S-BASIC/loops-break-1.basic @@ -0,0 +1,13 @@ +var n = integer + +while (1 = 1) do + begin + n = int(rnd(1) * 20) + print n; + if n = 10 then goto 0_done + n = int(rnd(1) * 20) + print n + end +0_done print " That's all!" + +end diff --git a/Task/Loops-Break/S-BASIC/loops-break-2.basic b/Task/Loops-Break/S-BASIC/loops-break-2.basic new file mode 100644 index 0000000000..a4ab30ae07 --- /dev/null +++ b/Task/Loops-Break/S-BASIC/loops-break-2.basic @@ -0,0 +1,14 @@ +var n = integer + +repeat + begin + n = int(rnd(1) * 20) + print n; + if n <> 10 then + print int(rnd(1) * 20) + end +until n = 10 + +print " That's all!" + +end diff --git a/Task/Loops-Continue/Langur/loops-continue.langur b/Task/Loops-Continue/Langur/loops-continue.langur index 6cb0ac4dee..f255b18d30 100644 --- a/Task/Loops-Continue/Langur/loops-continue.langur +++ b/Task/Loops-Continue/Langur/loops-continue.langur @@ -1,5 +1,5 @@ -for .i of 10 { - write .i - if .i div 5 { writeln(); next } +for i of 10 { + write i + if i div 5 { writeln(); next } write ", " } diff --git a/Task/Loops-Continue/PascalABC.NET/loops-continue.pas b/Task/Loops-Continue/PascalABC.NET/loops-continue.pas new file mode 100644 index 0000000000..f6e8c98877 --- /dev/null +++ b/Task/Loops-Continue/PascalABC.NET/loops-continue.pas @@ -0,0 +1,12 @@ +begin + for var i:=1 to 10 do + begin + Write(i); + if i mod 5 = 0 then + begin + Writeln; + continue + end; + Write(', '); + end; +end. diff --git a/Task/Loops-Do-while/PascalABC.NET/loops-do-while.pas b/Task/Loops-Do-while/PascalABC.NET/loops-do-while.pas new file mode 100644 index 0000000000..fc9076dbda --- /dev/null +++ b/Task/Loops-Do-while/PascalABC.NET/loops-do-while.pas @@ -0,0 +1,7 @@ +begin + var a := 0; + repeat + a += 1; + Print(a); + until a mod 6 = 0; +end. diff --git a/Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while-2.basic b/Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while-2.basic deleted file mode 100644 index 933db6e6c5..0000000000 --- a/Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while-2.basic +++ /dev/null @@ -1,6 +0,0 @@ -10 REM Loops/Do-while -20 LET I = 0 -30 LET I = I + 1 -40 PRINT I -50 IF (I / 6) * 6 <> I THEN GOTO 30 -60 END diff --git a/Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while-1.basic b/Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while.basic similarity index 100% rename from Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while-1.basic rename to Task/Loops-Do-while/Sinclair-ZX81-BASIC/loops-do-while.basic diff --git a/Task/Loops-Downward-for/Langur/loops-downward-for-1.langur b/Task/Loops-Downward-for/Langur/loops-downward-for-1.langur index bfbdf6d896..3da248bfae 100644 --- a/Task/Loops-Downward-for/Langur/loops-downward-for-1.langur +++ b/Task/Loops-Downward-for/Langur/loops-downward-for-1.langur @@ -1,3 +1,3 @@ -for .i in 10..0 { - writeln .i +for i in 10..0 { + writeln i } diff --git a/Task/Loops-Downward-for/Langur/loops-downward-for-2.langur b/Task/Loops-Downward-for/Langur/loops-downward-for-2.langur index 7417b2f17f..8c69aae949 100644 --- a/Task/Loops-Downward-for/Langur/loops-downward-for-2.langur +++ b/Task/Loops-Downward-for/Langur/loops-downward-for-2.langur @@ -1,3 +1,3 @@ -for .i = 10; .i > -1; .i -= 1 { - writeln .i +for i = 10; i > -1; i -= 1 { + writeln i } diff --git a/Task/Loops-Downward-for/PascalABC.NET/loops-downward-for.pas b/Task/Loops-Downward-for/PascalABC.NET/loops-downward-for.pas new file mode 100644 index 0000000000..b13c08d2b2 --- /dev/null +++ b/Task/Loops-Downward-for/PascalABC.NET/loops-downward-for.pas @@ -0,0 +1,3 @@ +## +for var i:=10 downto 0 do + Print(i); diff --git a/Task/Loops-For-with-a-specified-step/Langur/loops-for-with-a-specified-step.langur b/Task/Loops-For-with-a-specified-step/Langur/loops-for-with-a-specified-step.langur index 2a6ab6d93e..bd20903a7f 100644 --- a/Task/Loops-For-with-a-specified-step/Langur/loops-for-with-a-specified-step.langur +++ b/Task/Loops-For-with-a-specified-step/Langur/loops-for-with-a-specified-step.langur @@ -1,3 +1,3 @@ -for .i = 1; .i < 10; .i += 2 { - writeln .i +for i = 1; i < 10; i += 2 { + writeln i } diff --git a/Task/Loops-For-with-a-specified-step/PascalABC.NET/loops-for-with-a-specified-step.pas b/Task/Loops-For-with-a-specified-step/PascalABC.NET/loops-for-with-a-specified-step.pas new file mode 100644 index 0000000000..6f406a3d66 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/PascalABC.NET/loops-for-with-a-specified-step.pas @@ -0,0 +1,7 @@ +begin + for var i:=1 to 10 step 2 do + Print(i); + Println; + for var i:=20 to 1 step -3 do + Print(i); +end. diff --git a/Task/Loops-For/Langur/loops-for-1.langur b/Task/Loops-For/Langur/loops-for-1.langur index faf638231a..1c4053bfc5 100644 --- a/Task/Loops-For/Langur/loops-for-1.langur +++ b/Task/Loops-For/Langur/loops-for-1.langur @@ -1,5 +1,5 @@ -for .i = 0; .i < 5; .i += 1 { - for .j = 0; .j <= .i; .j += 1 { +for i = 0; i < 5; i += 1 { + for j = 0; j <= i; j += 1 { write "*" } writeln() diff --git a/Task/Loops-For/Langur/loops-for-2.langur b/Task/Loops-For/Langur/loops-for-2.langur index 3d2d45c2d0..0e7ff47e68 100644 --- a/Task/Loops-For/Langur/loops-for-2.langur +++ b/Task/Loops-For/Langur/loops-for-2.langur @@ -1,5 +1,5 @@ -for .i of 5 { - for of .i { +for i of 5 { + for of i { write "*" } writeln() diff --git a/Task/Loops-For/Langur/loops-for-3.langur b/Task/Loops-For/Langur/loops-for-3.langur index d52639ebf5..0c62403bc2 100644 --- a/Task/Loops-For/Langur/loops-for-3.langur +++ b/Task/Loops-For/Langur/loops-for-3.langur @@ -1,3 +1,3 @@ -for .i of 5 { - writeln "*" * .i +for i of 5 { + writeln "*" * i } diff --git a/Task/Loops-For/PascalABC.NET/loops-for.pas b/Task/Loops-For/PascalABC.NET/loops-for.pas new file mode 100644 index 0000000000..a87216ea7a --- /dev/null +++ b/Task/Loops-For/PascalABC.NET/loops-for.pas @@ -0,0 +1,7 @@ +## +for var i:=1 to 5 do +begin + for var j:=1 to i do + Write('*'); + Writeln +end; diff --git a/Task/Loops-For/Vim-Script/loops-for-1.vim b/Task/Loops-For/Vim-Script/loops-for-1.vim new file mode 100644 index 0000000000..ad46a6c764 --- /dev/null +++ b/Task/Loops-For/Vim-Script/loops-for-1.vim @@ -0,0 +1,6 @@ +for i in range(1, 5) + call append(line('$'), '') + for j in range(1, i) + call setline(line('$'), getline('$') .. '*') + endfor +endfor diff --git a/Task/Loops-For/Vim-Script/loops-for-2.vim b/Task/Loops-For/Vim-Script/loops-for-2.vim new file mode 100644 index 0000000000..e80fbf9b77 --- /dev/null +++ b/Task/Loops-For/Vim-Script/loops-for-2.vim @@ -0,0 +1,3 @@ +for i in range(1, 5) + echoc repeat('*', i) +endfor diff --git a/Task/Loops-Foreach/Langur/loops-foreach.langur b/Task/Loops-Foreach/Langur/loops-foreach.langur index 0306b4b976..b393ec64e9 100644 --- a/Task/Loops-Foreach/Langur/loops-foreach.langur +++ b/Task/Loops-Foreach/Langur/loops-foreach.langur @@ -1,17 +1,17 @@ -for .i in [1, 2, 3] { - writeln .i +for i in [1, 2, 3] { + writeln i } -val .abc = "abc" +val abc = "abc" -for .i in .abc { - writeln .i +for i in abc { + writeln i } -for .i of .abc { - writeln .abc[.i] +for i of abc { + writeln abc[i] } -for .i in .abc { - writeln cp2s .i +for i in abc { + writeln cp2s(i) } diff --git a/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas b/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas new file mode 100644 index 0000000000..754dbfc90b --- /dev/null +++ b/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas @@ -0,0 +1,3 @@ +## +foreach var s in |'Pascal','ABC','.NET'| do + Print(s); diff --git a/Task/Loops-Increment-loop-index-within-loop-body/EasyLang/loops-increment-loop-index-within-loop-body.easy b/Task/Loops-Increment-loop-index-within-loop-body/EasyLang/loops-increment-loop-index-within-loop-body.easy index 210317dd18..6575777e2d 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/EasyLang/loops-increment-loop-index-within-loop-body.easy +++ b/Task/Loops-Increment-loop-index-within-loop-body/EasyLang/loops-increment-loop-index-within-loop-body.easy @@ -1,13 +1,10 @@ fastfunc isprim num . - if num mod 2 = 0 and num > 2 - return 0 - . - i = 3 + i = 2 while i <= sqrt num if num mod i = 0 return 0 . - i += 2 + i += 1 . return 1 . diff --git a/Task/Loops-Increment-loop-index-within-loop-body/PascalABC.NET/loops-increment-loop-index-within-loop-body.pas b/Task/Loops-Increment-loop-index-within-loop-body/PascalABC.NET/loops-increment-loop-index-within-loop-body.pas new file mode 100644 index 0000000000..12a0633a37 --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/PascalABC.NET/loops-increment-loop-index-within-loop-body.pas @@ -0,0 +1,17 @@ +function IsPrime(n: BigInteger) + := (2..n.Sqrt.Round).All(x -> n mod x <> 0); + +begin + var i := 1; + var n := 42bi; + while i <= 42 do + begin + if IsPrime(n) then + begin + Println($'{i,3} {n,15}'); + i += 1; + n += n - 1; + end; + n += 1; + end; +end. diff --git a/Task/Loops-N-plus-one-half/PascalABC.NET/loops-n-plus-one-half.pas b/Task/Loops-N-plus-one-half/PascalABC.NET/loops-n-plus-one-half.pas new file mode 100644 index 0000000000..429ebdd949 --- /dev/null +++ b/Task/Loops-N-plus-one-half/PascalABC.NET/loops-n-plus-one-half.pas @@ -0,0 +1,3 @@ +## +for var i:=1 to 10 do + Write(i, i = 10 ? '' : ', '); diff --git a/Task/Loops-Nested/PascalABC.NET/loops-nested.pas b/Task/Loops-Nested/PascalABC.NET/loops-nested.pas new file mode 100644 index 0000000000..e4dc21d0d2 --- /dev/null +++ b/Task/Loops-Nested/PascalABC.NET/loops-nested.pas @@ -0,0 +1,16 @@ +label 1; + +begin + var a: array [,] of integer := MatrRandomInteger(3,4,1,10); + a.Println; + + var found := False; + for var i:=0 to a.RowCount-1 do + for var j:=0 to a.ColCount-1 do + if a[i,j] = 5 then + begin + found := True; + goto 1; + end; + 1: Println(found); +end. diff --git a/Task/Loops-While/Langur/loops-while.langur b/Task/Loops-While/Langur/loops-while.langur index 600f93e7fc..1f18ddc634 100644 --- a/Task/Loops-While/Langur/loops-while.langur +++ b/Task/Loops-While/Langur/loops-while.langur @@ -1,5 +1,5 @@ -var .i = 1024 -while .i > 0 { - writeln .i - .i \= 2 +var i = 1024 +while i > 0 { + writeln i + i \= 2 } diff --git a/Task/Loops-While/Mia/loops-while.mia b/Task/Loops-While/Mia/loops-while.mia new file mode 100644 index 0000000000..61cd5b0957 --- /dev/null +++ b/Task/Loops-While/Mia/loops-while.mia @@ -0,0 +1,5 @@ +i = 1024 +while i > 0 { + print i + i = i :/ 2 +} diff --git a/Task/Loops-While/PascalABC.NET/loops-while.pas b/Task/Loops-While/PascalABC.NET/loops-while.pas new file mode 100644 index 0000000000..de30e15776 --- /dev/null +++ b/Task/Loops-While/PascalABC.NET/loops-while.pas @@ -0,0 +1,7 @@ +## +var n := 1024; +while n > 0 do +begin + Println(n); + n := n div 2; +end; diff --git a/Task/Loops-With-multiple-ranges/PascalABC.NET/loops-with-multiple-ranges.pas b/Task/Loops-With-multiple-ranges/PascalABC.NET/loops-with-multiple-ranges.pas new file mode 100644 index 0000000000..9c32b9fc5a --- /dev/null +++ b/Task/Loops-With-multiple-ranges/PascalABC.NET/loops-with-multiple-ranges.pas @@ -0,0 +1,20 @@ +## +var (x,y,z) := (+5,-5,-2); +var (one,three,seven) := (1,3,7); + +var seq := (-three .. Round(3 ** 3)).Step(three) + + (-seven .. +seven).Step(x) + + (555 .. 550 - y) + + (22 .. -28).Step(-three) + + (1927 .. 1939) + + (x .. y).Step(z) + + (Round(11 ** x) .. Round(11 ** x) + one); + +var sum := seq.Sum(x -> Abs(x)); + +var prod := 1; +foreach var t in seq do + if (Abs(prod) < 2bi ** 27) and (t <> 0) then + prod *= t; +Println('sum =',sum); +Println('prod =',prod); diff --git a/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur b/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur index 7d224fefcf..211984fe9b 100644 --- a/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur +++ b/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur @@ -1,4 +1,4 @@ -val .data = qs:block END +val data = qs:block END start stop increment comment -2 2 1 Normal -2 2 0 Zero increment @@ -11,21 +11,22 @@ val .data = qs:block END 0 0 0 Start equal stop equal zero: zero increment END -var .table = submatches(RE/([^ ]+) +([^ ]+) +([^ ]+) +(.+)\n?/, .data) +# Process data string into table. +# We could have just started with a list of lists, of course. +var table = submatches(RE/([^ ]+) +([^ ]+) +([^ ]+) +(.+)\n?/, data) -val .f = fn(.x) number .x -for .i in 2..len(.table) { - .table[.i] = map [.f, .f, .f, _], .table[.i] +for i in 2..len(table) { + table[i] = map([number, number, number, _], table[i]) } -for .test in rest(.table) { - val .start, .stop, .inc, .comment = .test +for test in rest(table) { + val start, stop, inc, comment = test { - val .series = series(.start .. .stop, .inc) + val s = series(start .. stop, inc) catch { - writeln $"\.comment;\nERROR: \._err["msg"]:L200(...);\n" + writeln "{{comment}}\nERROR: {{_err'msg:L200(...)}}\n" } else { - writeln $"\.comment;\nresult: \.series;\n" + writeln "{{comment}}\nresult: {{s}}\n" } } } diff --git a/Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas b/Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas new file mode 100644 index 0000000000..2071d0b607 --- /dev/null +++ b/Task/Loops-Wrong-ranges/PascalABC.NET/loops-wrong-ranges.pas @@ -0,0 +1,15 @@ +procedure DisplayRange(first, last, step: integer); +begin + Print($'({first,2}, {last,2}, {step,2}): '); + if step = 0 then + Println('not allowed') + else Println(Range(first, last, step)); +end; + +begin + var ranges := |(-2, 2, 1), (-2, 2, 0), (-2, 2, -1), + (-2, 2, 10), (2, -2, 1), (2, 2, 1), + (2, 2, -1), (2, 2, 0), (0, 0, 0)|; + foreach var (f, l, s) in ranges do + DisplayRange(f,l,s); +end. diff --git a/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur b/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur index 48ba9c07fe..f7a86123a0 100644 --- a/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur +++ b/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur @@ -1,15 +1,16 @@ -val .isPrime = fn(.i) .i == 2 or - .i > 2 and not any(fn(.x) .i div .x, - pseries 2 .. .i ^/ 2) +val isPrime = fn(i) { + i == 2 or i > 2 and + not any(fn x:i div x, pseries(2 .. i ^/ 2)) +} -val .isMersennePrime = fn(.p) { - if .p == 2: return true - if not .isPrime(.p): return false +val isMersennePrime = fn(p) { + if p == 2: return true + if not isPrime(p): return false - val .mp = 2 ^ .p - 1 - for[.s=4] of 3 .. .p { - .s = (.s ^ 2 - 2) rem .mp + val mp = 2 ^ p - 1 + for[s=4] of 3 .. p { + s = (s ^ 2 - 2) rem mp } == 0 } -writeln join " ", map fn(.x) $"M\.x;", filter .isMersennePrime, series 2300 +writeln join(" ", map(fn x:"M{{x}}", filter(isMersennePrime, series(2300)))) diff --git a/Task/Ludic-numbers/EasyLang/ludic-numbers.easy b/Task/Ludic-numbers/EasyLang/ludic-numbers.easy new file mode 100644 index 0000000000..06bb876321 --- /dev/null +++ b/Task/Ludic-numbers/EasyLang/ludic-numbers.easy @@ -0,0 +1,27 @@ +proc initLudicArray n . res[] . + len res[] n + res[1] = 1 + for i = 2 to n + k = 0 + for j = i - 1 downto 2 + k = k * res[j] div (res[j] - 1) + 1 + . + res[i] = k + 2 + . +. +initLudicArray 2005 arr[] +for i = 1 to 25 + write arr[i] & " " +. +print "" +print "" +i = 1 +while arr[i] <= 1000 + cnt += 1 + i += 1 +. +print cnt +print "" +for i = 2000 to 2005 + write arr[i] & " " +. diff --git a/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur b/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur index e67b35d78d..61b17ec279 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur +++ b/Task/Luhn-test-of-credit-card-numbers/Langur/luhn-test-of-credit-card-numbers.langur @@ -1,22 +1,22 @@ -val .luhntest = fn(.s) { - val .t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] - val .numbers = s2n .s - val .oddeven = len(.numbers) rem 2 +val luhntest = fn(s) { + val t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] + val numbers = s -> s2n + val oddeven = len(numbers) rem 2 - for[=0] .i of .numbers { - _for += if(.i rem 2 == .oddeven: .numbers[.i]; .t[.numbers[.i]+1]) + for[=0] i of numbers { + _for += if(i rem 2 == oddeven: numbers[i]; t[numbers[i]+1]) } div 10 } -val .tests = h{ +val tests = { "49927398716": true, "49927398717": false, "1234567812345678": false, "1234567812345670": true, } -for .key of .tests { - val .pass = .luhntest(.key) - write .key, ": ", .pass - writeln if(.pass == .tests[.key]: ""; " (LUHN TEST FAILED)") +for key in sort(keys(tests)) { + val pass = luhntest(key) + write key, ": ", pass + writeln if(pass == tests[key]: ""; " (LUHN TEST FAILED)") } diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua index 3f987b4d70..0898194946 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua @@ -1,31 +1,20 @@ -function luhn(n) - n=string.reverse(n) - print(n) - local s1=0 - --sum odd digits - for i=1,n:len(),2 do - s1=s1+n:sub(i,i) - end - --evens - local s2=0 - for i=2,n:len(),2 do - local doubled=n:sub(i,i)*2 - doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end) - s2=s2+doubled - end - print(s1) - print(s2) - local total=s1+s2 - if total%10==0 then - return true - end - return false -end +function luhn_test(cc_number) + assert(type(cc_number) == 'string') + local sum = 0 + local is_odd = true + for idx = #cc_number , 1 , -1 do -- reverse order + -- extract single character as string then convert to integer + local digit = cc_number:sub(idx, idx) + 0 + if is_odd then + sum = sum + digit + else + sum = sum + ((digit * 2) % 10) + (digit // 5) + end -- if + is_odd = not is_odd -- toggle between odd and even + end -- for + return (sum % 10) == 0 +end -- function luhn_test --- Note that this function takes strings, not numbers. --- 16-digit numbers tend to be problematic --- when looking at individual digits. -print(luhn'49927398716') -print(luhn'49927398717') -print(luhn'1234567812345678') -print(luhn'1234567812345670') +for _, val in ipairs{"49927398716", "49927398717", "1234567812345678", "1234567812345670"} do + print(val, luhn_test(val)) +end -- for diff --git a/Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl b/Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl new file mode 100644 index 0000000000..73d45aa270 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/SETL/luhn-test-of-credit-card-numbers.setl @@ -0,0 +1,18 @@ +program luhn_test; + tests := [ + 49927398716, + 49927398717, + 1234567812345678, + 1234567812345670 + ]; + + loop for test in tests do + print(test, if luhn test then "pass" else "fail" end); + end loop; + + op luhn(n); + fac := 2; + digits := [val d * (fac := 3-fac) : d in reverse str n]; + return 0 = +/[d - if d>9 then 9 else 0 end : d in digits] mod 10; + end op; +end program; diff --git a/Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua b/Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua new file mode 100644 index 0000000000..46ed815ca7 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Uiua/luhn-test-of-credit-card-numbers.uiua @@ -0,0 +1,6 @@ +Luhn ← =0◿10+⊃(/+⊢|/+∵(⍥(-9)>9.×2)⊡1)⍉⬚0↯∞_2⇌ +T ← {"49927398716" + "49927398717" + "1234567812345678" + "1234567812345670"} +≡◇(Luhn ≡⋕) T diff --git a/Task/M-bius-function/Gambas/m-bius-function.gambas b/Task/M-bius-function/Gambas/m-bius-function.gambas new file mode 100644 index 0000000000..b62750334b --- /dev/null +++ b/Task/M-bius-function/Gambas/m-bius-function.gambas @@ -0,0 +1,27 @@ +Public Sub Main() + + Dim outstr As String = " . " + + For i As Integer = 1 To 200 + If mobius(i) >= 0 Then outstr &= " " + outstr &= Str(mobius(i)) & " " + If i Mod 10 = 9 Then + Print outstr + outstr = "" + End If + Next + +End + +Function mobius(n As Integer) As Integer + + If n = 1 Then Return 1 + For d As Integer = 2 To Int(Sqr(n)) + If n Mod d = 0 Then + If n Mod (d * d) = 0 Then Return 0 + Return -mobius(n / d) + End If + Next + Return -1 + +End Function diff --git a/Task/M-bius-function/PureBasic/m-bius-function.basic b/Task/M-bius-function/PureBasic/m-bius-function.basic new file mode 100644 index 0000000000..3959515d0e --- /dev/null +++ b/Task/M-bius-function/PureBasic/m-bius-function.basic @@ -0,0 +1,30 @@ +Procedure.i mobius(n) + If n = 1: + ProcedureReturn 1 + EndIf + For d = 2 To Int(Sqr(n)) + If Mod(n, d) = 0: + If Mod(n, d * d) = 0: + ProcedureReturn 0 + EndIf + ProcedureReturn -mobius(n / d) + EndIf + Next d + ProcedureReturn -1 +EndProcedure + +OpenConsole() +outstr$ = " . " +For i = 1 To 200 + If mobius(i) >= 0: + outstr$ = outstr$ + " " + EndIf + outstr$ = outstr$ + Str(mobius(i)) + " " + If Mod(i, 10) = 9: + PrintN(outstr$) + outstr$ = "" + EndIf +Next i + +PrintN(#CRLF$ + "Press ENTER to exit"): Input() +CloseConsole() diff --git a/Task/M-bius-function/XBasic/m-bius-function.basic b/Task/M-bius-function/XBasic/m-bius-function.basic new file mode 100644 index 0000000000..7c3fec5047 --- /dev/null +++ b/Task/M-bius-function/XBasic/m-bius-function.basic @@ -0,0 +1,31 @@ +PROGRAM "Möbius function" +VERSION "0.0000" +IMPORT "xma" + + +DECLARE FUNCTION Entry () +DECLARE FUNCTION mobius (n) + +FUNCTION Entry () + outstr$ = " . " + FOR i = 1 TO 200 + IF mobius(i) >= 0 THEN outstr$ = outstr$ + outstr$ = outstr$ + STR$(mobius(i)) + " " + IF i MOD 10 = 9 THEN + PRINT outstr$ + outstr$ = "" + END IF + NEXT i +END FUNCTION + +FUNCTION mobius (n) + IF n = 1 THEN RETURN 1 + FOR d = 2 TO INT(SQRT(n)) + IF n MOD d = 0 THEN + IF n MOD (d*d) = 0 THEN RETURN 0 + RETURN -mobius(n/d) + END IF + NEXT d + RETURN -1 +END FUNCTION +END PROGRAM diff --git a/Task/MD5-Implementation/Raku/md5-implementation.raku b/Task/MD5-Implementation/Raku/md5-implementation.raku index 7d3d56b8c0..96ff90376b 100644 --- a/Task/MD5-Implementation/Raku/md5-implementation.raku +++ b/Task/MD5-Implementation/Raku/md5-implementation.raku @@ -1,7 +1,6 @@ proto md5($msg) returns Blob is export {*} multi md5(Str $msg) { md5 $msg.encode } multi md5(Blob $msg) { - my \bits = 8 * $msg.elems; my buf8 $buf .= new; $buf.write-uint32: $buf.elems, $_, LittleEndian for reduce -> Blob $blob, blob32 $X { @@ -29,9 +28,9 @@ multi md5(Blob $msg) { (BEGIN blob32.new: 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476), |map { blob32.new: @$_ }, { - $^b.push(blob8.new(@$_).read-uint32(0)) for (@$msg, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64)) + $^b.push(blob8.new(@$_).read-uint32(0)) for (@$msg, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64)) .flat.rotor(4); - $b.write-uint64: $b.elems, bits, LittleEndian; + $b.write-uint64: $b.elems, 8*$msg.elems, LittleEndian; $b; }(buf32.new) .rotor(16); diff --git a/Task/Magic-constant/Ada/magic-constant.ada b/Task/Magic-constant/Ada/magic-constant.ada new file mode 100644 index 0000000000..eada801d57 --- /dev/null +++ b/Task/Magic-constant/Ada/magic-constant.ada @@ -0,0 +1,68 @@ +-- Magic constants +-- J. Carter 2024 May + +with Ada.Text_IO; +with System; + +procedure Magic_Constant is + type Big_U is mod System.Max_Binary_Modulus; + + function Magic (Order : in Big_U) return Big_U with + Pre => Order > 2; + -- Returns the constant for the magic square of order Order + + function Order (Guess : in Big_U) return Big_U; + -- Returns the order of the smallest magic square with constant > Guess + + function Image (N : in Big_U; Width : in Positive) return String; + -- Returns a blank-filled image of N of at least width characters + + function Magic (Order : in Big_U) return Big_U is + (Order * (Order ** 2 + 1) / 2); + + function Order (Guess : in Big_U) return Big_U is + Min : Big_U := 3; + Max : Big_U := 5_850_000; + Mid : Big_U; + Prev : Big_U := 0; + begin -- Order + Search : loop + Mid := Min + (Max - Min) / 2; + + exit Search when Mid = Prev; + + Prev := Mid; + + if Magic (Mid) > Guess and (Mid = 3 or else Magic (Mid - 1) <= Guess) then + return Mid; + end if; + + if Magic (Mid) > Guess then + Max := Mid; + else + Min := Mid; + end if; + end loop Search; + + raise Program_Error with "Order: no solution for" & Guess'Image; + end Order; + + function Image (N : in Big_U; Width : in Positive) return String is + Raw : String renames N'Image; + Img : String renames Raw (2 .. Raw'Last); + begin -- Image + return (1 .. Width - Img'Length => ' ') & Img; + end Image; +begin -- Magic_Constant + First_20 : for N in Big_U range 3 .. 22 loop + Ada.Text_IO.Put_Line (Item => Image (N, 2) & Image (Magic (N), 5) ); + end loop First_20; + + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (Item => "1000" & Magic (1000)'Image); + Ada.Text_IO.New_Line; + + Ten_To : for P in 1 .. (if Big_U'Size < 64 then 9 elsif Big_U'Size < 128 then 18 else 20) loop + Ada.Text_IO.Put_Line (Item => "10 ** " & Image (Big_U (P), 2) & Image (Order (10 ** P), 8) ); + end loop Ten_To; +end Magic_Constant; diff --git a/Task/Make-directory-path/Seed7/make-directory-path-1.seed7 b/Task/Make-directory-path/Seed7/make-directory-path-1.seed7 deleted file mode 100644 index 1fd23c97f7..0000000000 --- a/Task/Make-directory-path/Seed7/make-directory-path-1.seed7 +++ /dev/null @@ -1,7 +0,0 @@ -$ include "seed7_05.s7i"; - include "cli_cmds.s7i"; - -const proc: main is func - begin - doMkdirCmd(argv(PROGRAM), TRUE); - end func; diff --git a/Task/Make-directory-path/Seed7/make-directory-path-2.seed7 b/Task/Make-directory-path/Seed7/make-directory-path-2.seed7 deleted file mode 100644 index 54ab614118..0000000000 --- a/Task/Make-directory-path/Seed7/make-directory-path-2.seed7 +++ /dev/null @@ -1,10 +0,0 @@ -$ include "seed7_05.s7i"; - include "cli_cmds.s7i"; - -const proc: main is func - local - var string: parameters is ""; - begin - parameters := join(argv(PROGRAM), " "); - doMkdir(parameters); - end func; diff --git a/Task/Make-directory-path/Seed7/make-directory-path.seed7 b/Task/Make-directory-path/Seed7/make-directory-path.seed7 new file mode 100644 index 0000000000..13dbfb7ff9 --- /dev/null +++ b/Task/Make-directory-path/Seed7/make-directory-path.seed7 @@ -0,0 +1,21 @@ +$ include "seed7_05.s7i"; + include "osfiles.s7i"; + +const proc: makeDirectoryPath (in string: dirPath) is func + begin + makeParentDirs(dirPath); + if fileTypeSL(dirPath) <> FILE_DIR then + makeDir(dirPath); + end if; + end func; + +const proc: main is func + begin + if length(argv(PROGRAM)) <> 1 then + writeln("usage: makeDirectoryPath path"); + elsif succeeds(makeDirectoryPath(convDosPath(argv(PROGRAM)[1]))) then + writeln("Directory path now exists"); + else + writeln("Failed to create directory path"); + end if; + end func; diff --git a/Task/Man-or-boy-test/PascalABC.NET/man-or-boy-test.pas b/Task/Man-or-boy-test/PascalABC.NET/man-or-boy-test.pas new file mode 100644 index 0000000000..f9b73c30f1 --- /dev/null +++ b/Task/Man-or-boy-test/PascalABC.NET/man-or-boy-test.pas @@ -0,0 +1,13 @@ +function A(k: integer; x1, x2, x3, x4, x5: function: integer): integer; +begin + var B: function: integer; + B := () -> begin + k := k - 1; + Result := A(k, B, x1, x2, x3, x4); + end; + Result := if k <= 0 then x4() + x5() else B() +end; + +begin + Print(A(10, () -> 1, () -> -1, () -> -1, () -> 1, () -> 0)) +end. diff --git a/Task/Mandelbrot-set/Dart/mandelbrot-set.dart b/Task/Mandelbrot-set/Dart/mandelbrot-set.dart index 596617a8a7..7fc985c03e 100644 --- a/Task/Mandelbrot-set/Dart/mandelbrot-set.dart +++ b/Task/Mandelbrot-set/Dart/mandelbrot-set.dart @@ -1,35 +1,35 @@ class Complex { - double _r,_i; + double _r, _i; - Complex(this._r,this._i); - double get r => _r; - double get i => _i; - String toString() => "($r,$i)"; + Complex(this._r, this._i); + get r => _r; + get i => _i; + toString() => "($r,$i)"; - Complex operator +(Complex other) => new Complex(r+other.r,i+other.i); - Complex operator *(Complex other) => - new Complex(r*other.r-i*other.i,r*other.i+other.r*i); - double abs() => r*r+i*i; + operator +(Complex other) => Complex(r + other.r, i + other.i); + operator *(Complex other) => + Complex(r * other.r - i * other.i, r * other.i + other.r * i); + abs() => r * r + i * i; } void main() { - double start_x=-1.5; - double start_y=-1.0; - double step_x=0.03; - double step_y=0.1; + const startX = -1.5; + const startY = -1.0; + const stepX = 0.03; + const stepY = 0.1; - for(int y=0;y<20;y++) { - String line=""; - for(int x=0;x<70;x++) { - Complex c=new Complex(start_x+step_x*x,start_y+step_y*y); - Complex z=new Complex(0.0, 0.0); - for(int i=0;i<100;i++) { - z=z*(z)+c; - if(z.abs()>2) { + for (int y = 0; y < 20; y++) { + String line = ""; + for (int x = 0; x < 70; x++) { + var c = Complex(startX + stepX * x, startY + stepY * y); + var z = Complex(0.0, 0.0); + for (int i = 0; i < 100; i++) { + z = z * z + c; + if (z.abs() > 2) { break; } } - line+=z.abs()>2 ? " " : "*"; + line += z.abs() > 2 ? " " : "*"; } print(line); } diff --git a/Task/Mandelbrot-set/Uiua/mandelbrot-set.uiua b/Task/Mandelbrot-set/Uiua/mandelbrot-set.uiua new file mode 100644 index 0000000000..1ab364b82e --- /dev/null +++ b/Task/Mandelbrot-set/Uiua/mandelbrot-set.uiua @@ -0,0 +1,9 @@ +Size ← 800 +Cs ← ÷ 5[5_5_5 4_5_5 4_5_5 3_5_5 5_3_5 3_3_5 2_5_0 5_2_2 2_2_5 0_0_0] +# Initialise complex co-ordinates. +×2.5 ⊞ℂ:-1/4. ÷:-÷2,⇡.⟜(↯:0⊟.)Size +# Iterate 50 times (a, b, got_there) -> (a*a+b, b, got_there) +# got_there counts when corresponding value in b hits 2. +⍥⊃(+×.|⋅∘|+<2⌵⊙◌)50 0 +# Scale the results down and display +⊏:Cs⌈×9÷:⟜(/↥/↥)ₙ2◌◌ diff --git a/Task/Map-range/EasyLang/map-range.easy b/Task/Map-range/EasyLang/map-range.easy new file mode 100644 index 0000000000..6e2c4c89cd --- /dev/null +++ b/Task/Map-range/EasyLang/map-range.easy @@ -0,0 +1,6 @@ +func map_range a1 a2 b1 b2 s . + return b1 + (s - a1) * (b2 - b1) / (a2 - a1) +. +for i = 0 to 10 + print i & " -> " & map_range 0 10 -1 0 i +. diff --git a/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy b/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy index 72b50c1d7c..aaa1da88b9 100644 --- a/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy +++ b/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy @@ -1,5 +1,4 @@ -proc matmul . m1[][] m2[][] r[][] . - r[][] = [ ] +func[][] matmul m1[][] m2[][] . for i to len m1[][] r[][] &= [ ] for j = 1 to len m2[1][] @@ -9,8 +8,8 @@ proc matmul . m1[][] m2[][] r[][] . . . . + return r[][] . -mat1[][] = [ [ 1 2 3 ] [ 4 5 6 ] ] -mat2[][] = [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] -matmul mat1[][] mat2[][] erg[][] -print erg[][] +a[][] = [ [ 1 2 3 ] [ 4 5 6 ] ] +b[][] = [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] +print matmul a[][] b[][] diff --git a/Task/Matrix-multiplication/Uiua/matrix-multiplication.uiua b/Task/Matrix-multiplication/Uiua/matrix-multiplication.uiua new file mode 100644 index 0000000000..7e3097a8a2 --- /dev/null +++ b/Task/Matrix-multiplication/Uiua/matrix-multiplication.uiua @@ -0,0 +1,8 @@ +MatMul ← ≡(≡(/+×)¤:⍉)¤ +[[2 1 4] + [0 1 1]] + +[[6 3 ¯1 0] + [1 1 0 4] + [¯2 5 0 2]] +MatMul diff --git a/Task/Mayan-calendar/Jq/mayan-calendar.jq b/Task/Mayan-calendar/Jq/mayan-calendar.jq new file mode 100644 index 0000000000..c5fdcc2844 --- /dev/null +++ b/Task/Mayan-calendar/Jq/mayan-calendar.jq @@ -0,0 +1,105 @@ +### General utilities + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; +def rpad($len): tostring | ($len - length) as $l | . + (" " * $l); + +# days_between("2020-01-01"; "2020-01-02") #=> 1 +# days_between("2020-01-02"; "2020-01-01") #=> -1 +def days_between($yyyymmddBefore; $yyyymmddAfter): + (yyyymmddBefore | strptime("%Y-%m-%d") | mktime) as $before + | (yyyymmddAfter | strptime("%Y-%m-%d") | mktime) as $after + # leap seconds are always inserted + | (($after - $before) / (24*60*60) | floor) ; + +### `Date` objects + +def Date($year; $month; $day): {$year, $month, $day}; + +# Convert a Date object to a string yyyy-mm-dd +# Other inputs are (currently) unscathed. +def yyyymmdd: + if type == "object" then "\(.year)-\(.month)-\(.day)" + else . + end; + +### Mayan Calendar + +def sacred: + "Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw" + | split(" "); + +def civil: + "Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in Muwan’ Pax K’ayab Kumk’u Wayeb’" + | split(" "); + +def CREATION_TZOLKIN: "2012-12-21"; + +# Input: Date or yyyy-mm-dd +def tzolkin: + (days_between(CREATION_TZOLKIN; yyyymmdd)) as $diff + | {rem: ($diff % 13)} + | if .rem < 0 then .rem += 13 end + | .num = (if .rem <= 9 then .rem + 4 else .rem - 9 end) + | .rem = $diff % 20 + | if .rem <= 0 then .rem += 20 end + | [.num, sacred[.rem-1] ] ; + +# Input: Date or yyyy-mm-dd +def haab: + def ZERO_HAAB: "2019-04-02"; + (days_between(ZERO_HAAB; yyyymmdd)) as $diff + | {rem: ($diff % 365)} + | if .rem < 0 then .rem += 365 end + | .month = civil[((.rem+1)/20)|floor] + | .last = (if .month == "Wayeb'" then 5 else 20 end) + | .d = .rem%20 + 1 + | if .d < .last then [(.d|tostring), .month] + else ["Chum", .month] + end; + +# Input: Date or yyyy-mm-dd +def longCount: + {diff: days_between(CREATION_TZOLKIN; yyyymmdd)} + | .diff += 13*400*360 + | .baktun = ((.diff/(400*360)) | floor) + | .diff = .diff % (400*360) + | .katun = ((.diff/(20 * 360))|floor) + | .diff = .diff % (20*360) + | .tun = ((.diff/360)|floor) + | .diff = .diff % 360 + | .winal = ((.diff/20)|floor) + | .kin = .diff % 20 + | [.baktun, .katun, .tun, .winal, .kin] + | join("."); + +# Input: Date or yyyy-mm-dd +def lord: + {diff: days_between(CREATION_TZOLKIN; yyyymmdd)} + | .rem = .diff % 9 + | if .rem <= 0 then .rem += 9 end + | "G\(.rem)"; + + +def dates: [ + "1961-10-06", + "1963-11-21", + "2004-06-19", + "2012-12-18", + "2012-12-21", + "2019-01-19", + "2019-03-27", + "2020-02-29", + "2020-03-01", + "2071-05-16" +]; + +" Gregorian Tzolk’in Haab’ Long Lord of", +" Date # Name Day Month Count the Night", +"---------- -------- ------------- -------------- ---------", +# Date.default = Date.isoDate +(dates[] + | tzolkin as [$n, $s] + | haab as [$d, $m] + | [., ($n | lpad(4)), ($s | rpad(8)), ($d|lpad(4)), ($m|rpad(8)), (longCount|lpad(20)), (lord|lpad(6))] + | join(" ") +) diff --git a/Task/Maze-generation/11l/maze-generation.11l b/Task/Maze-generation/11l/maze-generation.11l index b9c8f0c56d..3364852bb2 100644 --- a/Task/Maze-generation/11l/maze-generation.11l +++ b/Task/Maze-generation/11l/maze-generation.11l @@ -3,7 +3,7 @@ F make_maze(w = 16, h = 8) V ver = [[‘| ’] * w [+] [String(‘|’)]] * h [+] [[String]()] V hor = [[‘+--’] * w [+] [String(‘+’)]] * (h + 1) - F walk(Int x, Int y) -> N + F walk(Int x, Int y) -> Void @vis[y][x] = 1 V d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] random:shuffle(&d) diff --git a/Task/Maze-generation/Chapel/maze-generation.chapel b/Task/Maze-generation/Chapel/maze-generation.chapel new file mode 100644 index 0000000000..b2304bd9bd --- /dev/null +++ b/Task/Maze-generation/Chapel/maze-generation.chapel @@ -0,0 +1,56 @@ +use Random; + +config const rows: int = 9; +config const cols: int = 16; +if rows < 1 || cols < 1 { + writeln("Maze must be at least 1x1 in size."); + exit(1); +} + +enum direction {N = 1, E = 2, S = 3, W = 4}; + +record Cell { + var spaces: [direction.N .. direction.W] bool; + var visited: bool; +} + +const dirs = [ + ((-1, 0), direction.N, direction.S), // ((rowDir, colDir), myWall, neighbourWall) + ((0, 1), direction.E, direction.W), + ((1, 0), direction.S, direction.N), + ((0, -1), direction.W, direction.E) +]; + +var maze: [1..rows, 1..cols] Cell; +var startingCell = (choose(maze.dim(0)), choose(maze.dim(1))); + +checkCell(maze, startingCell); +displayMaze(maze); + +proc checkCell(ref maze, cell) { + maze[cell].visited = true; + for dir in permute(dirs) { + var (offset, thisDir, neighbourDir) = dir; + var neighbour = cell + offset; + if maze.domain.contains(neighbour) && !maze[neighbour].visited { + maze[cell].spaces[thisDir] = true; + maze[neighbour].spaces[neighbourDir] = true; + checkCell(maze, neighbour); + } + } +} + +proc displayMaze(maze) { + for row in maze.dim(0) { + for col in maze.dim(1) { + write(if maze[row, col].spaces[direction.N] then "+ " else "+---"); + } + writeln("+"); + for col in maze.dim(1) { + write(if maze[row, col].spaces[direction.W] then " " else "| "); + } + writeln("|"); + } + write("+---" * maze.dim(1).size); + writeln("+"); +} diff --git a/Task/Maze-generation/POV-Ray/maze-generation.povray b/Task/Maze-generation/POV-Ray/maze-generation.povray new file mode 100644 index 0000000000..d358c4ed68 --- /dev/null +++ b/Task/Maze-generation/POV-Ray/maze-generation.povray @@ -0,0 +1,181 @@ +#version 3.7; + +global_settings { + assumed_gamma 1 +} + +#declare Rows = 15; +#declare Cols = 17; + +#declare Seed = seed(2); // A seed produces a fixed sequence of pseudorandom numbers + +#declare Wall = prism { + 0, 0.8, 7, + <0, -0.5>, <0.05, -0.45>, <0.05, 0.45>, <0, 0.5>, + <-0.05, 0.45>, <-0.05, -0.45>, <0, -0.5> + texture { + pigment { + brick colour rgb 1, colour rgb <0.8, 0.25, 0.1> // Colour mortar, colour brick + brick_size 3*<0.25, 0.0525, 0.125> + mortar 3*0.01 // Size of the mortar + } + normal { wrinkles 0.75 scale 0.01 } + finish { diffuse 0.9 phong 0.2 } + } +} + +#macro Fisher_Yates_Shuffle(Stack, Start, Top) + #for (I, Top, Start+1, -1) + #local J = floor(rand(Seed)*I + 0.5); + #if (J != I) // Waste of time swapping an element with itself + #local Src_Row = Stack[I][0]; + #local Src_Col = Stack[I][1]; + #local Dst_Row = Stack[I][2]; + #local Dst_Col = Stack[I][3]; + #declare Stack[I][0] = Stack[J][0]; + #declare Stack[I][1] = Stack[J][1]; + #declare Stack[I][2] = Stack[J][2]; + #declare Stack[I][3] = Stack[J][3]; + #declare Stack[J][0] = Src_Row; + #declare Stack[J][1] = Src_Col; + #declare Stack[J][2] = Dst_Row; + #declare Stack[J][3] = Dst_Col; + #end + #end +#end + +#macro Initialise(Visited, North_Walls, East_Walls) + #for (R, 0, Rows-1) + #for (C, 0, Cols-1) + #declare Visited[R][C] = false; + #declare North_Walls[R][C] = true; + #declare East_Walls[R][C] = true; + #end + #end +#end + +#macro Push(Stack, Top, Src_Row, Src_Col, Dst_Row, Dst_Col) + #declare Top = Top + 1; + #declare Stack[Top][0] = Src_Row; + #declare Stack[Top][1] = Src_Col; + #declare Stack[Top][2] = Dst_Row; + #declare Stack[Top][3] = Dst_Col; +#end + +#macro Generate_Maze(Visited, North_Walls, East_Walls) + #local Stack = array[Rows*Cols][4]; // 0: from row, 1: from col, 2: to row, 3: to col + #local Row = floor(rand(Seed)*(Rows-1) + 0.5); // Random start row + #local Col = floor(rand(Seed)*(Cols-1) + 0.5); // Random start column + #local Top = -1; + Push(Stack, Top, Row, Col, Row, Col) + + #while (Top >= 0) + #declare Visited[Row][Col] = true; + #local Start = Top + 1; + + #if (Row < Rows-1) // Add north neighbour + #if (Visited[Row+1][Col] = false) + Push(Stack, Top, Row, Col, Row+1, Col) + #end + #end + + #if (Col < Cols-1) // Add east neighbour + #if (Visited[Row][Col+1] = false) + Push(Stack, Top, Row, Col, Row, Col+1) + #end + #end + + #if (Row > 0) // Add south neighbour + #if (Visited[Row-1][Col] = false) + Push(Stack, Top, Row, Col, Row-1, Col) + #end + #end + + #if (Col > 0) // Add west neighbour + #if (Visited[Row][Col-1] = false) + Push(Stack, Top, Row, Col, Row, Col-1) + #end + #end + + Fisher_Yates_Shuffle(Stack, Start, Top) + + #local Removed_Wall = false; + #while (Top >= 0 & Removed_Wall = false) + #local Src_Row = Stack[Top][0]; + #local Src_Col = Stack[Top][1]; + #local Dst_Row = Stack[Top][2]; + #local Dst_Col = Stack[Top][3]; + #declare Top = Top - 1; + + #if (Visited[Dst_Row][Dst_Col] = false) + #if (Dst_Row = Src_Row+1 & Dst_Col = Src_Col) // North wall + #declare North_Walls[Src_Row][Src_Col] = false; + #elseif (Dst_Row = Src_Row & Dst_Col = Src_Col+1) // East wall + #declare East_Walls[Src_Row][Src_Col] = false; + #elseif (Dst_Row = Src_Row-1 & Dst_Col = Src_Col) // South wall + #declare North_Walls[Dst_Row][Src_Col] = false; + #elseif (Dst_Row = Src_Row & Dst_Col = Src_Col-1) // West wall + #declare East_Walls[Src_Row][Dst_Col] = false; + #else + #error "Unknown wall!\n" + #end + + #declare Row = Dst_Row; + #declare Col = Dst_Col; + #declare Removed_Wall = true; + #end + #end + #end +#end + +#macro Draw_Maze(North_Walls, East_Walls) + merge { + #for (R, 0, Rows-1) + object { Wall translate <1, 0, 0.5> translate <-1, 0, R> } // West edge + #for (C, 0, Cols-1) + #if (R = 0) // South edge + object { Wall rotate y*90 translate <0.5, 0, 1> translate } + #end + #if (North_Walls[R][C]) + object { Wall rotate y*90 translate <0.5, 0, 1> translate } + #end + #if (East_Walls[R][C]) + object { Wall translate <1, 0, 0.5> translate } + #end + #end + #end + translate <-0.5*Cols, 0, 0> // Centre maze on x=0 + } +#end + +camera { + location <0, 13, -2> + right x*image_width/image_height + look_at <0, 2, 5> +} + +light_source { + <-0.1*Cols, Rows, 0.5*Rows>, colour rgb <1, 1, 1> + area_light + x, y, 3, 3 + circular orient +} + +box { + <-0.5*Cols, -0.1, 0>, <0.5*Cols, 0, Rows> + texture { + pigment { + checker colour rgb <0, 0.3, 0> colour rgb <0, 0.4, 0> + scale 0.5 + } + finish { specular 0.5 reflection { 0.1 } } + } +} + +#declare Visited = array[Rows][Cols]; +#declare North_Walls = array[Rows][Cols]; +#declare East_Walls = array[Rows][Cols]; + +Initialise(Visited, North_Walls, East_Walls) +Generate_Maze(Visited, North_Walls, East_Walls) +Draw_Maze(North_Walls, East_Walls) diff --git a/Task/Maze-generation/Uiua/maze-generation.uiua b/Task/Maze-generation/Uiua/maze-generation.uiua index 1138a832b7..79b95d19ee 100644 --- a/Task/Maze-generation/Uiua/maze-generation.uiua +++ b/Task/Maze-generation/Uiua/maze-generation.uiua @@ -1,37 +1,33 @@ -H ← 8 -W ← 18 -Ver ← 0 -Hor ← 1 -Vis ← 2 +# Build and solve a maze. +# Experimental! +W ← 10 +H ← 6 -BreakNS ← ⊂Ver⊂⊃(/↥≡⊡0|⊡0_1) -BreakEW ← ⊂Hor⊂⊃(⊡0_0|/↥≡⊡1) +GetWall ← -:⊡1:÷2/-. # ([here, next], maze) -> (maze') -BreakWall ← ⍜⊡(0◌)⟨BreakNS|BreakEW⟩=°⊟≡⊢. +BreakWall ← ⍜(⊡|⋅@ )GetWall -Neighbours ← +⊙¤[[¯1 0] [1 0] [0 1] [0 ¯1]] # Gives N4 +Nfour ← +⊙¤[¯2_0 2_0 0_2 0_¯2] # Gives N4 Shuffle ← ⊏⍏[⍥⚂]⧻. -IsVisited ← ¬⊡⊂Vis -MarkAsVisited ← ⟜(⍜(⊡|1◌)⊂Vis) -OnlyInBounds ← ▽≡IsVisited ⊙¤,, # (finds the boundary 1's) - +# (pos maze) -> T if it's already a star. +IsVisited ← ≠@.⊡ +MarkAsVisited ← ⟜(⍜⊡⋅@.) +# (pos) -> (bool) +InBounds ← ▽⊸≡(↧⊃(/↧≥1_1|/↧< +1 × 2 H_W)) # (here, maze) -> (maze') Walk ← |2 ( MarkAsVisited # (here, maze) -> ([[here, next] x(up to)4], maze) - ≡⊟¤⟜(Shuffle OnlyInBounds Neighbours) + ≡⊟¤⟜(Shuffle InBounds Nfour) # Update maze for each in turn. For each, if it # still isn't visited, break the wall, recurse into it. - ∧(⟨◌|Walk ⊡1 ⟜BreakWall⟩IsVisited◌°⊟,,) + ∧(⨬(◌|Walk⊡1⟜BreakWall)IsVisited◌°⊟,,) ) -⊂↯H⊂↯W0 1↯+1W1 # vis (added 1's help bounds checks) -⊂↯H⊂↯W1 1↯+1W 0 # ver -↯+1H⊂↯W1 0 # hor -⊂⊟ -# Stack: ([hor, ver, vis]) -Walk [0 0] - -PP! ← ≡/⊂∵^! # Pretty print using switch. -≡(&p$"_\n_")⊃(PP!⟨"+ "|"+--"⟩⊡Ver|PP!⟨" "|"| "⟩⊡Hor) +# Generate a maze. +Maze ← ( + ↘¯1☇1↯(+1H)⊟⊂/⊂↯W"+-" @+⊂/⊂↯W"| " @| # Build a filled maze. + Walk 1_1 # Walk around breaking walls. +) +Maze diff --git a/Task/Maze-solving/Uiua/maze-solving.uiua b/Task/Maze-solving/Uiua/maze-solving.uiua new file mode 100644 index 0000000000..c1336f9e68 --- /dev/null +++ b/Task/Maze-solving/Uiua/maze-solving.uiua @@ -0,0 +1,26 @@ +# You can delete from here to SOLVE THE MAZE +# if you're appending this to the maze generator code. +# Experimental! +["+-+-+-+-+-+-+" + "|. . .|. . .|" + "+-+-+ + + + +" + "|.|. .|.|.|.|" + "+ + +-+-+ + +" + "|.|. . . .|.|" + "+ +-+-+-+-+ +" + "|. . . . . .|" + "+-+-+-+-+-+-+"] +H ← 4 +W ← 6 +Nfour ← +⊙¤[¯2_0 2_0 0_2 0_¯2] # Gives N4 +InBounds ← ▽⊸≡(↧⊃(/↧≥1_1|/↧< +1 × 2 H_W)) +GetWall ← -:⊡1:÷2/-. +# S O L V E T H E M A Z E # +. +Start ← 1_1 +End ← -Start ×2 H_W +Heur ← /+⌵-End # Manhattan distance. +# (pos grid) -> 1-4 next steps, in bounds, without walls in the way. +Ns ← ≡⊡1▽:⟜(≡(=@ ⊡)⊙¤≡GetWall)≡⊟¤:InBounds Nfour. +astar(Ns|Heur|≍End) Start # Solve (costs = 1 => djikstra) +$"_ moves" ⊙⟜(⍜(⊡|+33)):°□⊢ diff --git a/Task/McNuggets-problem/Refal/mcnuggets-problem.refal b/Task/McNuggets-problem/Refal/mcnuggets-problem.refal new file mode 100644 index 0000000000..877827269a --- /dev/null +++ b/Task/McNuggets-problem/Refal/mcnuggets-problem.refal @@ -0,0 +1,37 @@ +$ENTRY Go { + , : e.A + , : e.B + , : e.C + , : e.Nums + , )>: e.Nuggets + , : e.NonNuggets + , e.NonNuggets: e.X s.Last + = ; +}; + +SumPairs { + () (e.Y) = ; + (s.I e.X) (e.Y) = ; +}; + +SumPairs1 { + s.I () = ; + s.I (s.X e.X) = <+ s.I s.X> ; +}; + +Remove { + s.I e.X s.I e.Y = e.X ; + s.I e.X = e.X; +}; + +RemoveAll { + () e.X = e.X; + (s.R e.R) e.X = >; +}; + +Iota { + s.Start s.Step s.End, : { + '+' = ; + s.X = s.Start s.Step s.End>; + }; +}; diff --git a/Task/McNuggets-problem/Uiua/mcnuggets-problem.uiua b/Task/McNuggets-problem/Uiua/mcnuggets-problem.uiua new file mode 100644 index 0000000000..1400394615 --- /dev/null +++ b/Task/McNuggets-problem/Uiua/mcnuggets-problem.uiua @@ -0,0 +1,4 @@ +# Get s/m/l ranges to (100/6, 100/9, 100/20) and multipiy out. +⟜(◴≡/+פ⟜(☇1⇡⌊÷)6_9_20) 100 +# Compare against 0-100 for missing, return highest. +/↥▽:⟜(¬∊)⇡⟜(▽⊸≤) diff --git a/Task/Memory-allocation/PascalABC.NET/memory-allocation.pas b/Task/Memory-allocation/PascalABC.NET/memory-allocation.pas new file mode 100644 index 0000000000..580aad83a1 --- /dev/null +++ b/Task/Memory-allocation/PascalABC.NET/memory-allocation.pas @@ -0,0 +1,16 @@ +procedure ppp; +begin + var i,j: integer; // i,j are allocated automatically on the stack when we call procedure +end; + +begin + ppp; + var p: ^integer; + New(p); // memory is allocated on the heap + p^ := 666; + Dispose(p); // explicit memory deallocation + + var ri := new integer[5]; // memory is allocated on the heap + ri[0] := 555; + ri := nil; // memory is controlled by .NET garbage collector +end. diff --git a/Task/Menu/Langur/menu.langur b/Task/Menu/Langur/menu.langur index 122e18c86d..44a20d9a8e 100644 --- a/Task/Menu/Langur/menu.langur +++ b/Task/Menu/Langur/menu.langur @@ -1,21 +1,21 @@ -val .select = impure fn(.entries) { - if .entries is not list: throw "invalid args" - if len(.entries) == 0: return "" +val choose = impure fn(entries) { + if entries is not list: throw "invalid args" + if not entries: return "" # print the menu - writeln join "\n", map(fn(.e, .i) $"\.i:2;: \.e;", .entries, 1..len .entries) + writeln join("\n", map(fn e, i: "{{i:2}}: {{e}}", entries, 1..len(entries))) - val .idx = number read( + val idx = read( "Select entry #: ", - fn(.x) { - if not .x -> RE/^[0-9]+$/: return false - val .y = number .x - .y > 0 and .y <= len(.entries) + fn(x) { + if not x -> RE/^[0-9]+$/: return false + val y = x -> number + y > 0 and y <= len(entries) }, "invalid selection\n", -1, - ) + ) -> number - .entries[.idx] + entries[idx] } -writeln .select(["fee fie", "eat pi", "huff and puff", "tick tock"]) +writeln choose(["fee fie", "eat pi", "huff and puff", "tick tock"]) diff --git a/Task/Middle-three-digits/Uiua/middle-three-digits.uiua b/Task/Middle-three-digits/Uiua/middle-three-digits.uiua new file mode 100644 index 0000000000..c688251689 --- /dev/null +++ b/Task/Middle-three-digits/Uiua/middle-three-digits.uiua @@ -0,0 +1,9 @@ +[123 12345 1234567 987654321 10001 ¯10001 ¯123 ¯100 100 ¯12345 + 1 2 ¯1 ¯10 2002 ¯2002 0] +Mid ← ( + ⍤("too short")≥3.⧻.°□°⋕⌵ + ⍤("even length")≠0◿2. + ↘¯⟜↘⌊÷2-3 +) +⍉⊟⟜≡⍚⍣(Mid|⊂"Error: "◌) # Convert each +≡(&p$"_\t->\t_"°⊟) # Display diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-1.rexx similarity index 100% rename from Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx rename to Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-1.rexx diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx new file mode 100644 index 0000000000..b7d044c45f --- /dev/null +++ b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx @@ -0,0 +1,167 @@ +parse version version +say version +glob. = '' +numeric digits 1000 +say '25 numbers of the form 2^n-1, mostly Mersenne primes' +say 'Up to about 25 digits deterministic, above probabilistic' +say +mm = '2 3 5 7 11 13 17 19 23 31 61 89 97 107 113 127 131 521 607 1279 2203 2281 2293 3217 3221' +do nn = 1 to 25 + a = Word(mm,nn); b = 2**a-1; l = Length(b) + call time('r'); p = Prime(b); e = time('e') + if l > 25 then + b = Left(b,12)'...'Right(b,13) + select + when p = 0 then + p = 'not' + when l < 26 then + p = 'for sure' + otherwise + p = 'probable' + end + say '2^('a'-1)' '=' b '('l' digits) is' p 'prime' '('format(e,,3) 'seconds)' +end +return + +Prime: +/* Is a number prime? */ +procedure expose glob. +arg x +/* Validity */ +if \ Whole(x) then + return 'X' +if x < 2 then + return 'X' +/* Low primes also used as deterministic witnesses */ +w1 = ' 2 3 5 7 11 13 17 19 23 29 31 37 41 ' +/* Fast values */ +w = x +if Pos(' 'w' ',w1) > 0 then + return 1 +if x//2 = 0 then + return 0 +if x//3 = 0 then + return 0 +if Right(x,1) = 5 then + return 0 +/* Miller-Rabin primality test */ +numeric digits 2*Length(x) +d = x-1; e = d +/* Reduce n-1 by factors of 2 */ +do s = -1 while d//2 = 0 + d = d%2 +end +/* Thresholds deterministic witnesses */ +w2 = ' 2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 0 ', +|| ' 3825123056546413051 0 0 318665857834031151167461 3317044064679887385961981 ' +w = Words(w2) +/* Up to 13 deterministic trials */ +if x < Word(w2,w) then do + do k = 1 to w + if x < Word(w2,k) then + leave + end +end +/* or 3 probabilistic trials */ +else do + w1 = ' ' + do k = 1 to 3 + r = Rand(2,e)/1; w1 = w1||r||' ' + end + k = k-1 +end +/* Algorithm using generated witnesses */ +do k = 1 to k + a = Word(w1,k); y = powermod(a,d,x) + if y = 1 then + iterate + if y = e then + iterate + do s + y = (y*y)//x + if y = 1 then + return 0 + if y = e then + leave + end + if y <> e then + return 0 +end +return 1 + +Floor: +/* Floor */ +procedure expose glob. +arg x +/* Formula */ +if Whole(x) then + return x +else + return Trunc(x)-(x<0) + +Powermod: +/* Power modulus function x^y mod z */ +procedure expose glob. +arg x,y,z +/* Validity */ +if \ Whole(x) then + return 'X' +if \ Whole(x) then + return 'X' +if \ Whole(x) then + return 'X' +if x < 0 then + return 'X' +if y < 0 then + return 'X' +if z < 1 then + return 'X' +/* Special values */ +if z = 1 then + return 0 +/* Binary method */ +numeric digits Max(Length(Format(x,,,0)),Length(Format(y,,,0)),2*Length(Format(z,,,0))) +b = x//z; r = 1 +do while y > 0 + if y//2 then + r = r*x//z + x = x*x//z; y = y%2 +end +return r + +Rand: +/* Random number 12 digits precision */ +procedure expose glob. +arg x,y +/* Validity */ +if x <> '' then do + if \ Whole(x) then + return 'X' + if \ Whole(x) then + return 'X' + if x >= y then + return 'X' +end +/* Fixed precision */ +p = Digits(); numeric digits 30 +/* Get and save first seed from system Date and Time */ +if glob.rand = '' then do + a = Date('s'); b = Time('l') + glob.rand = Substr(b,10,3)||Substr(b,7,2)||Substr(b,4,2)||Substr(b,1,2)||Substr(a,7,2)||Substr(a,5,2)||Substr(a,3,2) +end +/* Calculate next random number method HP calculators */ +glob.rand = Right((glob.rand*2851130928467),15) +/* Uniform deviate [0,1) */ +z = '0.'Left(glob.rand,Length(glob.rand)-3) +numeric digits 12 +if x = '' then + return z/1 +else + return Floor(z*(y+1-x)+x) + +Whole: +/* Is a number integer? */ +procedure expose glob. +arg x +/* Formula */ +return Datatype(x,'w') diff --git a/Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.ada b/Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.ada new file mode 100644 index 0000000000..afc0404d1f --- /dev/null +++ b/Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.ada @@ -0,0 +1,100 @@ +-- Check the "Mind boggling card trick" +-- J. Carter 2024 May +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with Ada.Numerics.Discrete_Random; +with PragmARC.Cards.Decks.US; +with PragmARC.Cards.US; + +procedure Card_Trick is + package Cards renames PragmARC.Cards.US; + package Decks renames PragmARC.Cards.Decks.US; + + function Is_Red (Card : in Cards.Card_Info) return Boolean is + (Card.Suit in Cards.Diamond | Cards.Heart); + + function Correct return Boolean; + -- Performs the trick and returns True if the assertion that 'The number of black cards in the "black" pile equals the number + -- of red cards in the "red" pile' holds; False if it does not + + function Correct return Boolean is + function Num_Red (Deck : in Decks.Deck_52) return Natural; + -- Returns the number of red cards in Deck + + function Num_Black (Deck : in Decks.Deck_52) return Natural; + -- Returns the number of black cards in Deck + + function Num_Red (Deck : in Decks.Deck_52) return Natural is + Result : Natural := 0; + begin -- Num_Red + Count : for I in 1 .. Deck.Size loop + if Is_Red (Deck.Value (I) ) then + Result := Result + 1; + end if; + end loop Count; + + return Result; + end Num_Red; + + function Num_Black (Deck : in Decks.Deck_52) return Natural is + (Deck.Size - Num_Red (Deck) ); + + Hand : Decks.Deck_52; + Red : Decks.Deck_52; + Black : Decks.Deck_52; + Card : Cards.Card_Info; + begin -- Correct + Decks.Standard_Deck (Item => Hand); + Hand.Shuffle; + + All_Cards : loop + exit All_Cards when Hand.Is_Empty; + + Hand.Deal (To => Card); + + if Is_Red (Card) then + Hand.Deal (To => Card); + Red.Add (Item => Card); + else + Hand.Deal (To => Card); + Black.Add (Item => Card); + end if; + end loop All_Cards; + + Swap : declare + Number : constant Natural := Integer'Min (Red.Size, Black.Size) - 1; + + subtype Bunch_Value is Integer range 1 .. Number; + + package Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Bunch_Value); + + Gen : Random.Generator; + Bunch : Bunch_Value; + begin -- Swap + Random.Reset (Gen => Gen); + Bunch := Random.Random (Gen); + + One_Bunch : for I in 1 .. Bunch loop + Red.Deal (To => Card); + Black.Add (Item => Card); + Black.Deal (To => Card); + Red.Add (Item => Card); + end loop One_Bunch; + + return Num_Red (Red) = Num_Black (Black); + end Swap; + end Correct; + + Total : constant := 10_000; + + Good : Natural := 0; +begin -- Card_Trick + Check_All : for I in 1 .. Total loop + if Correct then + Good := Good + 1; + end if; + end loop Check_All; + + Ada.Text_IO.Put_Line (Item => Good'Image & " correct out of" & Total'Image & " tries"); +end Card_Trick; diff --git a/Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq b/Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq new file mode 100644 index 0000000000..4a6717d63f --- /dev/null +++ b/Task/Mind-boggling-card-trick/Jq/mind-boggling-card-trick.jq @@ -0,0 +1,105 @@ +### Generic utilities +def count(s): reduce s as $x (0; . + 1); + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + + +### Pseuo-random numbers + +# Output: a prn in range(0;$n) where $n is `.` +def prn: + if . == 1 then 0 + else . as $n + | ([1, (($n-1)|tostring|length)]|max) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def sample: + if length == 0 # e.g. null or [] + then null + else .[length|prn] + end; + +def knuthShuffle: + length as $n + | if $n <= 1 then . + else {i: $n, a: .} + | until(.i == 0; + .i += -1 + | (.i + 1 | prn) as $j + | .a[.i] as $t + | .a[.i] = .a[$j] + | .a[$j] = $t) + | .a + end; + + +### Cards + +def R: "R"; # 82 ASCII +def B: "B"; # 66 ASCII + +# Create deck, half red, half black and shuffle it. +def deck: + ([range(0;26)|R] + [range(0;26)|B]) | knuthShuffle; + +# Deal from `deck` into three stacks: {black, red, discard} +def deal: + deck as $deck + | reduce range(0; 51; 2) as $i (.; + if $deck[$i] == B + then .black += [$deck[$i+1]] + else .red += [$deck[$i+1]] + end + | .discard += [$deck[$i]] ); + +def proceed: + def p: join(" "); + + (.red|length) as $lr + | (.black|length) as $lb + | (.discard|length) as $ld + + | def displayStacks($discard): + " Red : \($lr|lpad(2)) cards -> \(.red|p)", + " Black : \($lb|lpad(2)) cards -> \(.black|p)", + (select($discard) + | " Discard: \($ld) cards -> \(.discard|p)") ; + + # Input: {red, black} + def swap($n): + . + { rp: ([range(0; $lr)] | knuthShuffle[0:$n] ), + bp: ([range(0; $lb)] | knuthShuffle[0:$n]) } + | reduce range(0;$n) as $i (.; + .red[.rp[$i]] as $t + | .red[.rp[$i]] = .black[.bp[$i]] + | .black[.bp[$i]] = $t); + + def epilog: + # Check that the number of black cards in the black stack equals + # the number of red cards in the red stack: + count(select(.red[] == R)) as $rcount + | count(select(.black[] == B)) as $bcount + | "\nThe number of red cards in the red stack = \($rcount)", + "The number of black cards in the black stack = \($bcount)", + if $rcount == $bcount + then "So the assertion is correct!" + else "So the assertion is incorrect!" + end; + + "After dealing the cards, the stacks are as follows:", + displayStacks(true), + # Swap the same, random, number of cards between the red and black stacks. + ( (if $lr < $lb then $lr else $lb end) as $min + | (($min - 1|prn) + 1) as $n + | swap($n) + | "\n\($n) card(s) are to be swapped.", + "The respective zero-based indices of the cards to be swapped are:", + " Red : \(.rp|map(lpad(3))|p)", + " Black : \(.bp|map(lpad(3))|p)", + "\nAfter swapping, the red and black stacks are as follows:", + displayStacks(false), + epilog ) ; + +deal | proceed diff --git a/Task/Minimal-steps-down-to-1/Jq/minimal-steps-down-to-1.jq b/Task/Minimal-steps-down-to-1/Jq/minimal-steps-down-to-1.jq new file mode 100644 index 0000000000..5163ced4b4 --- /dev/null +++ b/Task/Minimal-steps-down-to-1/Jq/minimal-steps-down-to-1.jq @@ -0,0 +1,82 @@ +### Generic functions + +def array($n): . as $in | [range(0;$n)|$in]; + +def max(stream): reduce stream as $x (-infinite; if $x > . then $x else . end); + +def plural: if . == 1 then " " else "s" end; + +### Minimal Steps +# Input: { divs, subs, limit, mins } +# where .divs and .subs are the arrays of divisors and subtractors respectively, +# and .limit the value specified for task/1; +# .mins should be an array of arrays. +def minsteps($n): + if $n == 1 + then .mins[1] = [] + else .min = .limit + | .p = 0 + | .q = 0 + | .op = "" + | reduce .divs[] as $div (.; + if ($n % $div == 0) + then (($n/$div)|floor) as $d + | (.mins[$d]|length + 1) as $steps + | if $steps < .min + then .min = $steps + | .p = $d + | .q = $div + | .op = "/" + end + end ) + | reduce .subs[] as $sub (.; + ($n - $sub) as $d + | if $d >= 1 + then (.mins[$d]|length + 1) as $steps + | if $steps < .min + then .min = $steps + | .p = $d + | .q = $sub + | .op = "-" + end + end) + | .mins[$n] = ["\(.op)\(.q) -> \(.p)"] + .mins[.p] + end ; + +def task($limit): + range(0;2) as $r + | { divs: [2, 3], + subs: (if $r == 0 then [1] else [2] end), + mins: [], + $limit + } + | "\nWith: Divisors: \(.divs), Subtractors: \(.subs) =>", + " Minimum number of steps to diminish the following numbers down to 1 is:", + ( foreach range(1; 1+$limit) as $i (.; + minsteps($i) # sets .min[$i] + | if ($i <= 10) + then (.mins[$i]|length) as $steps + | .emit = " \($i): \($steps) step\($steps|plural): \(.mins[$i] | join(", "))" + else .emit = null + end; + select(.emit).emit, + + # ... and when all is done: + (select($i==$limit) + | foreach (2000, 20000, $limit) as $lim (.; + .max = max( .mins[0: 1 + $lim][] | length) + | .maxs = [] + | .i = 0 + | reduce .mins[0: 1 + $lim][] as $min (.; + if ($min|length) == .max then .maxs += [.i] end + | .i += 1 ) + | .nums = (.maxs|length) + | (if .nums == 1 then "is" else "are" end) as $are + | (if .nums == 1 then "has" else "have" end) as $have + | .emit = " There \($are) \(.nums) number\(.nums|plural) in the range 1-\($lim)" + | .emit += " that \($have) maximum 'minimal steps' of \(.max):" + | .emit += "\n \(.maxs)"; + .emit) ) ) ) +; + +task(50000) diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Quackery/minimum-multiple-of-m-where-digital-sum-equals-m.quackery b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Quackery/minimum-multiple-of-m-where-digital-sum-equals-m.quackery new file mode 100644 index 0000000000..aee9d4fb1a --- /dev/null +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Quackery/minimum-multiple-of-m-where-digital-sum-equals-m.quackery @@ -0,0 +1,14 @@ + [ 0 swap + [ 10 /mod + rot + swap + dup 0 = until ] + drop ] is digitsum ( n --> n ) + + [] 1 + 40 times + [ 1 from + [ dup dup index * + digitsum = if + [ index swap end ] ] + 1+ dip join ] + drop echo diff --git a/Task/Modified-random-distribution/Jq/modified-random-distribution.jq b/Task/Modified-random-distribution/Jq/modified-random-distribution.jq new file mode 100644 index 0000000000..c095dfdc88 --- /dev/null +++ b/Task/Modified-random-distribution/Jq/modified-random-distribution.jq @@ -0,0 +1,50 @@ +# Output: a PRN (integer) in range(0; .) +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def rgen: + 1000 | prn / 1000; + +# Modified random number generator. +# `modifier` should be a zero-arity filter +def rng(modifier): + {} + | until(.r1 and (.r2 < (.r1|modifier)); + .r1 = rgen + | .r2 = rgen ) + | .r1; + +def modifier: + if (. < 0.5) then 2 * (0.5 - .) + else 2 * (. - 0.5) + end; + +def N:100000; +def NUM_BINS: 20; +def HIST_CHAR: "■"; +def HIST_CHAR_SIZE: 500; +def binSize:1 / NUM_BINS; + +def task: + # tidy decimals + def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p; + def zpad($len): tostring | ($len - length) as $l | . + ("0" * $l); + def r: if . == 0 then "0.00" else round(2) | zpad(4) end; + reduce range(0; N) as $i ([]; + rng(modifier) as $rn + | (($rn / binSize)|floor) as $bn + | .[$bn] += 1) + | {bins: .} + | "Modified random distribution with \(N) samples in range [0, 1):", + " Range Number of samples within that range", + (foreach range(0; NUM_BINS) as $i (.; + (HIST_CHAR * (((.bins[$i] // 0) / HIST_CHAR_SIZE) | round)) as $hist + | .emit = "\(binSize * $i|r) - \($hist) \(.bins[$i] // 0)" ) + | .emit); + +task diff --git a/Task/Monty-Hall-problem/ANSI-BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/ANSI-BASIC/monty-hall-problem.basic new file mode 100644 index 0000000000..53ef155626 --- /dev/null +++ b/Task/Monty-Hall-problem/ANSI-BASIC/monty-hall-problem.basic @@ -0,0 +1,41 @@ +100 PROGRAM MontyHallProblem +110 DEF NGames = 10000 +120 RANDOMIZE +130 LET NWins = 0 +140 FOR Game = 0 TO NGames +150 IF IsGameWon(0) <> 0 THEN LET NWins = NWins + 1 +160 NEXT Game +170 PRINT "NOT switching doors wins car in "; +180 PRINT USING "##.#": NWins / NGames * 100; +190 PRINT "% of games." +200 LET NWins = 0 +210 FOR Game = 0 TO NGames +220 IF IsGameWon(1) <> 0 THEN LET NWins = NWins + 1 +230 NEXT Game +240 PRINT "But switching doors wins car in "; +250 PRINT USING "##.#": NWins / NGames * 100; +260 PRINT "% of games." +270 END +280 REM *** +290 EXTERNAL FUNCTION IsGameWon(Sw) +300 REM Play one game. +310 REM Switching if and only if Sw <> 0. +320 REM Returns 1 if the game is won, 0 otherwise. +330 LET Car = INT(RND * 3) ! Randomly place car behind a door. +340 LET Player0 = INT(RND * 3) ! Player randomly chooses a door. +350 DO +360 LET Monty = INT(RND * 3) ! Monty opens door revealing a goat. +370 LOOP UNTIL (Monty <> Car) AND (Monty <> Player0) +380 IF Sw <> 0 THEN ! Player switches TO remaining door. +390 DO +400 LET Player = INT(RND * 3) +410 LOOP UNTIL (Player <> Player0) AND (Player <> Monty) +420 ELSE +430 LET Player = Player0 ! Player sticks with original door. +440 END IF +450 IF Player = Car THEN +460 LET IsGameWon = 1 +470 ELSE +480 LET IsGameWon = 0 +490 END IF +500 END FUNCTION diff --git a/Task/Monty-Hall-problem/Euphoria/monty-hall-problem.euphoria b/Task/Monty-Hall-problem/Euphoria/monty-hall-problem.euphoria index bf9079eb9b..7a9c8a7886 100644 --- a/Task/Monty-Hall-problem/Euphoria/monty-hall-problem.euphoria +++ b/Task/Monty-Hall-problem/Euphoria/monty-hall-problem.euphoria @@ -16,5 +16,5 @@ for plays = 1 to 10000 do stayWins += choice = winner switchWins += 6-choice-shown = winner end for -printf(1, "Switching wins %d times\n", switchWins) -printf(1, "Staying wins %d times\n", stayWins) +printf(1, "Switching wins %d times.\n", switchWins) +printf(1, "Staying wins %d times.\n", stayWins) diff --git a/Task/Monty-Hall-problem/FutureBasic/monty-hall-problem.basic b/Task/Monty-Hall-problem/FutureBasic/monty-hall-problem.basic new file mode 100644 index 0000000000..2785dc0df4 --- /dev/null +++ b/Task/Monty-Hall-problem/FutureBasic/monty-hall-problem.basic @@ -0,0 +1,60 @@ +// Monty Hall problem +// May 2024 - Rich Love + +local fn IsGameWon(Sw as int) as bool + REM Play one game. + REM Switching if and only if Sw <> 0. + REM Returns 1 if the game is won, 0 otherwise. + + short Car = INT(RND(3)) //Randomly place car behind a door. + short Player0 = INT(RND(3)) // Player randomly chooses a door. + short Monty + short IsGameWon + short Player + + DO + Monty = INT(RND(3)) // Monty opens door revealing a goat. + UNTIL (Monty <> Car) AND (Monty <> Player0) + 380 + + IF Sw <> 0 // Player switches TO remaining door. + + DO + Player = INT(RND(3)) + UNTIL (Player <> Player0) AND (Player <> Monty) + Monty = INT(RND(3)) + + ELSE + Player = Player0 // Player sticks with original door. + END IF + IF Player = Car + IsGameWon = 1 + ELSE + IsGameWon = 0 + END IF +END fn = IsgameWon + + +_NGames = 10000 + +float NWins = 0 +short Game + +FOR Game = 0 TO _NGames + IF fn IsGameWon(0) <> 0 THEN NWins = NWins + 1 +NEXT Game + + +PRINT "NOT switching doors wins car in "; +PRINT USING "##.##" ; NWins / 100 ; +PRINT " % of games." + +NWins = 0 +FOR Game = 0 TO _NGames + IF fn IsGameWon(1) <> 0 THEN NWins = NWins + 1 +NEXT Game +PRINT "But switching doors wins car in "; +PRINT USING "##.##" ; NWins / _NGames * 100; +PRINT " % of games." + +handleevents diff --git a/Task/Monty-Hall-problem/K/monty-hall-problem.k b/Task/Monty-Hall-problem/K/monty-hall-problem.k new file mode 100644 index 0000000000..aee2321694 --- /dev/null +++ b/Task/Monty-Hall-problem/K/monty-hall-problem.k @@ -0,0 +1,3 @@ +montyhall:{t:,/ 1_ x {`prng@`t[];ch:1?3;pr:1?3;sw:1?2;$[sw;a:ch=pr;a:~(ch=pr)];a}\0N;("KEEP %";(+/t)%x;"SWAP %";(+/~t)%x)} + +montyhall 100000 diff --git a/Task/Monty-Hall-problem/Liberty-BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/Liberty-BASIC/monty-hall-problem.basic index 5ea4ac78fc..6c55b34911 100644 --- a/Task/Monty-Hall-problem/Liberty-BASIC/monty-hall-problem.basic +++ b/Task/Monty-Hall-problem/Liberty-BASIC/monty-hall-problem.basic @@ -1,4 +1,3 @@ -'adapted from BASIC solution DIM doors(3) '0 is a goat, 1 is a car total = 10000 'set desired number of iterations diff --git a/Task/Monty-Hall-problem/Minimal-BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/Minimal-BASIC/monty-hall-problem.basic new file mode 100644 index 0000000000..95d94159bb --- /dev/null +++ b/Task/Monty-Hall-problem/Minimal-BASIC/monty-hall-problem.basic @@ -0,0 +1,47 @@ +10 REM Monty Hall problem +20 LET N = 10000 +30 RANDOMIZE +40 LET W = 0 +50 FOR G = 0 TO N +60 LET S = 0 +70 GOSUB 230 +80 IF V = 0 THEN 100 +90 LET W = W+1 +100 NEXT G +110 PRINT "NOT switching doors wins car in"; +120 PRINT W/N*100; "per cent of games." +130 LET W = 0 +140 FOR G = 0 TO N +150 LET S = 1 +160 GOSUB 230 +170 IF V = 0 THEN 190 +180 LET W = W+1 +190 NEXT G +200 PRINT "But switching doors wins car in"; +210 PRINT W/N*100; "per cent of games." +220 END +230 REM ** Is game won? +240 REM Play one game. +250 REM Switching if and only if S <> 0. +260 REM Randomly place car behind a door. +270 LET C = INT(RND*3) +280 REM Player randomly chooses a door. +290 LET P0 = INT(RND*3) +300 REM Monty opens door revealing a goat. +310 LET M = INT(RND*3) +320 IF M = C THEN 310 +330 IF M = P0 THEN 310 +340 IF S = 0 THEN 410 +350 REM Player switches to remaining door. +360 LET P = INT(RND*3) +370 IF P = P0 THEN 360 +380 IF P = M THEN 360 +390 GOTO 430 +400 REM Player sticks with original door. +410 LET P = P0 +420 REM Victory? +430 IF P <> C THEN 460 +440 LET V = 1 +450 RETURN +460 LET V = 0 +470 RETURN diff --git a/Task/Monty-Hall-problem/Modula-2/monty-hall-problem.mod2 b/Task/Monty-Hall-problem/Modula-2/monty-hall-problem.mod2 new file mode 100644 index 0000000000..a251b80c6f --- /dev/null +++ b/Task/Monty-Hall-problem/Modula-2/monty-hall-problem.mod2 @@ -0,0 +1,58 @@ +MODULE MontyHallProblem; + +FROM STextIO IMPORT + WriteLn, WriteString; +FROM RandomNumbers IMPORT + Randomize, Rnd; +FROM SRealIO IMPORT + WriteFixed; + +CONST + NGames = 10000; (* number of games simulated *) +VAR + NWins, Game: CARDINAL; + +PROCEDURE IsGameWon(Sw: BOOLEAN): BOOLEAN; + (* Play one game. *) +VAR + Car, Player, Player0, Monty: CARDINAL; +BEGIN + Car := Rnd(3); (* Randomly place car behind a door. *) + Player0 := Rnd(3); (* Player randomly chooses a door. *) + REPEAT + Monty := Rnd(3); (* Monty opens door revealing a goat. *) + UNTIL (Monty <> Car) AND (Monty <> Player0); + IF Sw THEN + (* Player switches to remaining door. *) + REPEAT + Player := Rnd(3); + UNTIL (Player <> Player0) AND (Player <> Monty) + ELSE + Player := Player0 (* Player sticks with original door. *) + END; + RETURN (Player = Car); +END IsGameWon; + +BEGIN + Randomize(0); + NWins := 0; + FOR Game := 0 TO NGames DO + IF IsGameWon(FALSE) THEN + NWins := NWins + 1 + END + END; + WriteString('NOT switching doors wins car in '); + WriteFixed(FLOAT(NWins) / FLOAT(NGames) * 100.0, 1, 4); + WriteString('% of games.'); + WriteLn; + NWins := 0; + FOR Game := 0 TO NGames DO + IF IsGameWon(TRUE) THEN + NWins := NWins + 1 + END + END; + WriteString('But switching doors wins car in '); + WriteFixed(FLOAT(NWins) / FLOAT(NGames) * 100.0, 1, 4); + WriteString('% of games.'); + WriteLn; +END MontyHallProblem. diff --git a/Task/Monty-Hall-problem/BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/QuickBASIC/monty-hall-problem.basic similarity index 100% rename from Task/Monty-Hall-problem/BASIC/monty-hall-problem.basic rename to Task/Monty-Hall-problem/QuickBASIC/monty-hall-problem.basic diff --git a/Task/Monty-Hall-problem/Run-BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/Run-BASIC/monty-hall-problem.basic index fb0a783b31..d2efed63ce 100644 --- a/Task/Monty-Hall-problem/Run-BASIC/monty-hall-problem.basic +++ b/Task/Monty-Hall-problem/Run-BASIC/monty-hall-problem.basic @@ -1,5 +1,3 @@ -' adapted from BASIC solution - input "Number of tries;";tries ' gimme the number of iterations FOR plays = 1 TO tries winner = INT(RND(1) * 3) + 1 diff --git a/Task/Monty-Hall-problem/SETL/monty-hall-problem.setl b/Task/Monty-Hall-problem/SETL/monty-hall-problem.setl new file mode 100644 index 0000000000..5b124f5c39 --- /dev/null +++ b/Task/Monty-Hall-problem/SETL/monty-hall-problem.setl @@ -0,0 +1,29 @@ +program monty_hall; + setrandom(0); + + n_simulations := 100000; + print('Chance to win:'); + print('When switching doors:', win_chance(true, n_simulations) * 100, '%'); + print('When not switching doors:', win_chance(false, n_simulations) * 100, '%'); + + proc win_chance(switch, n_simulations); + wins := 0; + loop for i in [1..n_simulations] do + wins +:= if simulate(switch) then 1 else 0 end; + end loop; + return wins / n_simulations; + end proc; + + proc simulate(switch); + doors := {1, 2, 3}; + car := random doors; + goats := doors less car; + choice := random doors; + opened := random (goats less choice); + + if switch then + choice := arb (doors less choice less opened); + end if; + return choice = car; + end proc; +end program; diff --git a/Task/Monty-Hall-problem/True-BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/True-BASIC/monty-hall-problem.basic index 579bf8536f..bc77002ccb 100644 --- a/Task/Monty-Hall-problem/True-BASIC/monty-hall-problem.basic +++ b/Task/Monty-Hall-problem/True-BASIC/monty-hall-problem.basic @@ -1,19 +1,21 @@ +OPTION BASE 0 +DIM puertas(3) + LET numTiradas = 1000000 -FOR i = 1 TO numTiradas +FOR i = 0 TO numTiradas LET pta_coche = INT(RND * 3) + 1 + LET puertas(pta_coche) = 1 LET pta_elegida = INT(RND * 3) + 1 - IF pta_coche <> pta_elegida THEN - LET pta_montys = 6 - pta_coche - pta_elegida + DO + LET pta_montys = INT(RND * 3) + 1 + LOOP WHILE puertas(pta_montys) = 1 OR pta_montys = pta_elegida + IF puertas(pta_elegida) = 1 THEN + LET cambia = cambia + 1 ELSE - DO - LET pta_montys = INT(RND * 3) + 1 - LOOP UNTIL pta_montys <> pta_coche + LET permanece = permanece + 1 END IF - ! mantener elección - IF pta_coche = pta_elegida THEN LET permanece = permanece + 1 - ! cambiar elección - IF pta_coche = 6 - pta_montys - pta_elegida THEN LET cambia = cambia + 1 + LET puertas(pta_coche) = 0 NEXT i PRINT "Cambiar gana el"; permanece / numTiradas * 100; "% de las veces." diff --git a/Task/Monty-Hall-problem/XPL0/monty-hall-problem.xpl0 b/Task/Monty-Hall-problem/XPL0/monty-hall-problem.xpl0 index ab854bdcac..df718f59af 100644 --- a/Task/Monty-Hall-problem/XPL0/monty-hall-problem.xpl0 +++ b/Task/Monty-Hall-problem/XPL0/monty-hall-problem.xpl0 @@ -17,17 +17,17 @@ return Player = Car; ]; [Format(2,1); -Text(0, "NOT switching doors wins car in "); NWins:= 0; for Game:= 0 to NGames-1 do if IsGameWon(false) then NWins:= NWins+1; +Text(0, "NOT switching doors wins car in "); RlOut(0, float(NWins)/float(NGames)*100.0); Text(0, "% of games.^M^J"); -Text(0, "But switching doors wins car in "); NWins:= 0; for Game:= 0 to NGames-1 do if IsGameWon(true) then NWins:= NWins+1; +Text(0, "But switching doors wins car in "); RlOut(0, float(NWins)/float(NGames)*100.0); Text(0, "% of games.^M^J"); ] diff --git a/Task/Monty-Hall-problem/Zig/monty-hall-problem.zig b/Task/Monty-Hall-problem/Zig/monty-hall-problem.zig new file mode 100644 index 0000000000..5d00cc875b --- /dev/null +++ b/Task/Monty-Hall-problem/Zig/monty-hall-problem.zig @@ -0,0 +1,29 @@ +const std = @import("std"); + +const number_of_simulations: u32 = 10_000_000; + +pub fn main() !void { + var stick_wins: u32 = 0; + var switch_wins: u32 = 0; + var doors = [3]bool{ true, false, false }; + + var t = std.rand.DefaultPrng.init(42); + const r = t.random(); + + var guess: u8 = undefined; + var door_shown: u8 = undefined; + + for (0..number_of_simulations) |_| { + std.rand.Random.shuffle(r, bool, &doors); + guess = r.intRangeAtMost(u8, 0, 2); + door_shown = r.intRangeAtMost(u8, 0, 2); + while (!doors[door_shown] and door_shown != guess) door_shown = r.intRangeAtMost(u8, 0, 2); + if (doors[guess]) { + stick_wins += 1; + } else { + switch_wins += 1; + } + } + + std.debug.print("After {} simulations:\nStick wins: {}\nSwitch wins: {}\n", .{ number_of_simulations, stick_wins, switch_wins }); +} diff --git a/Task/Motzkin-numbers/Uiua/motzkin-numbers.uiua b/Task/Motzkin-numbers/Uiua/motzkin-numbers.uiua new file mode 100644 index 0000000000..602850f4f5 --- /dev/null +++ b/Task/Motzkin-numbers/Uiua/motzkin-numbers.uiua @@ -0,0 +1,12 @@ +# Uses following formula to generate successive terms: +# m[i] = (m[i-2]*(3*i-3) + m[i-1]*(2*i+1)) / (i + 2) + +# Collect the multiplicands from the above formula. +Multiplicands ← [⊃(-3×3|+1×2|÷:1+2)]⧻ +# Apply formula to generate next Motzkin number. +Mn ← ×⊃(/+↙2|⊢↙¯1)×⊃(⊂:1↙¯2|Multiplicands) +# Generate list of terms to reasonable limit. +⍢(⊂⟜Mn|<36⧻) [1 1] +# Simple (=slow) prime test. +IsPrime ← ⊙◌⟨⟨=1⧻⍢(↘1|≠0◿⊢)⊂:1+2⇡⌊√.|1⟩=2.|0⟩≤1. +⍉⊟⟜∵IsPrime diff --git a/Task/Mouse-position/PascalABC.NET/mouse-position.pas b/Task/Mouse-position/PascalABC.NET/mouse-position.pas new file mode 100644 index 0000000000..0fd6e9634b --- /dev/null +++ b/Task/Mouse-position/PascalABC.NET/mouse-position.pas @@ -0,0 +1,7 @@ +## +uses GraphWPF; +Font.Size := 80; +OnMouseMove := (x,y,mb) -> begin + Window.Clear; + DrawText(Window.ClientRect,$'{x,0:f0}, {y,0:f0}'); +end; diff --git a/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy b/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy new file mode 100644 index 0000000000..9ec20dfb56 --- /dev/null +++ b/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy @@ -0,0 +1,39 @@ +subr init + symt$[] = strchars "abcdefghijklmnopqrstuvwxyz" +. +proc rot k . . + c$ = symt$[k] + for j = k downto 2 + symt$[j] = symt$[j - 1] + . + symt$[1] = c$ +. +func[] encode s$ . + init + for c$ in strchars s$ + k = 1 + while symt$[k] <> c$ + k += 1 + . + res[] &= k - 1 + rot k + . + return res[] +. +func$ decode s[] . + init + for k in s[] + k += 1 + c$ = symt$[k] + res$ &= c$ + rot k + . + return res$ +. +for word$ in [ "broood" "babanaaa" "hiphophiphop" ] + enc[] = encode word$ + print word$ & " -> " & enc[] + if decode enc[] <> word$ + print "error" + . +. diff --git a/Task/Multiple-regression/BASIC256/multiple-regression.basic b/Task/Multiple-regression/BASIC256/multiple-regression.basic new file mode 100644 index 0000000000..cfb6654e95 --- /dev/null +++ b/Task/Multiple-regression/BASIC256/multiple-regression.basic @@ -0,0 +1,70 @@ +arraybase 0 +N = 14: M = 2: Q = 3 # number of points and M.R. polynom degree + +dim X(N+1) # data points +X[0] = 1.47 : X[1] = 1.50 : X[2] = 1.52 +X[3] = 1.55 : X[4] = 1.57 : X[5] = 1.60 +X[6] = 1.63 : X[7] = 1.65 : X[8] = 1.68 +X[9] = 1.70 : X[10] = 1.73 : X[11] = 1.75 +X[12] = 1.78 : X[13] = 1.80 : X[14] = 1.83 +dim Y(N+1) # data points +Y[0] = 52.21 : Y[1] = 53.12 : Y[2] = 54.48 +Y[3] = 55.84 : Y[4] = 57.20 : Y[5] = 58.57 +Y[6] = 59.93 : Y[7] = 61.29 : Y[8] = 63.11 +Y[9] = 64.47 : Y[10] = 66.28 : Y[11] = 68.10 +Y[12] = 69.92 : Y[13] = 72.19 : Y[14] = 74.46 +dim S(N+1): dim T(N+1) # linear system coefficient +dim A(M+1, Q+1) # system to be solved +dim p(M+1, Q+1) + +for k = 0 to 2 * M + S[k] = 0: T[k] = 0 + for i = 0 to N + S[k] = S[k] + X[i] ^ k + if k <= M then T[k] = T[k] + Y[i] * X[i] ^ k + next i +next k + +# build linear system +for fila = 0 to M + for columna = 0 to M + A[fila, columna] = S[fila + columna] + next columna + A[fila, columna] = T[fila] +next fila + +print "Linear system coefficents:" +for i = 0 to M + for j = 0 to M + 1 + print rjust(A[i, j], 14.1); + next j + print +next i + +for j = 0 to M + for i = j to M + if A[i, j] <> 0 then exit for + next i + if i = M + 1 then print: print "SINGULAR MATRIX '" : end + for k = 0 to M + 1 + p[j,k] = A[i,k] : A[i,k] = p[j,k] : A[j,k] = A[i,k] + next k + z = 1 / A[j, j] + for k = 0 to M + 1 + A[j, k] = z * A[j, k] + next k + for i = 0 to M + if i <> j then + z = -A[i, j] + for k = 0 to M + 1 + A[i, k] = A[i, k] + z * A[j, k] + next k + end if + next i +next j + +print: print "Solutions:" +for i = 0 to M + print rjust(A[i, M + 1], 16.7); +next i +end diff --git a/Task/Multiple-regression/Chipmunk-Basic/multiple-regression.basic b/Task/Multiple-regression/Chipmunk-Basic/multiple-regression.basic new file mode 100644 index 0000000000..941fdbe096 --- /dev/null +++ b/Task/Multiple-regression/Chipmunk-Basic/multiple-regression.basic @@ -0,0 +1,68 @@ +100 cls +110 n = 14 : m = 2 : q = 3 ' number of points and M.R. polynom degree +120 dim x(n)' data points +130 data 1.47,1.5,1.52,1.55,1.57,1.6,1.63,1.65,1.68,1.7,1.73,1.75,1.78,1.8,1.83 +140 for c = 0 to n +150 read x(c) +160 next c +170 dim y(n)' data points +180 data 52.21,53.12,54.48,55.84,57.2,58.57,59.93,61.29,63.11,64.47,66.28,68.1,69.92,72.19,74.46 +190 for c = 0 to n +200 read y(c) +210 next c +220 dim s(n) : dim t(n)' linear system coefficient +230 dim a(m,q)' sistem to be solved +240 dim p(m,q) +250 for k = 0 to 2*m +260 s(k) = 0 : t(k) = 0 +270 for i = 0 to n +280 s(k) = s(k)+x(i)^k +290 if k <= m then t(k) = t(k)+y(i)*x(i)^k +300 next i +310 next k +320 ' build linear system +330 for fila = 0 to m +340 for columna = 0 to m +350 a(fila,columna) = s(fila+columna) +360 next columna +370 a(fila,columna) = t(fila) +380 next fila +390 print "Linear system coefficents:" +400 for i = 0 to m +410 for j = 0 to m+1 +420 print using "######.#";a(i,j); +430 next j +440 print +450 next i +460 for j = 0 to m +470 for i = j to m +480 if a(i,j) <> 0 then goto 500 +490 next i +500 if i = m+1 then +510 print : print "SINGULAR MATRIX '" +520 end +530 endif +540 for k = 0 to m+1 +560 p(j,k) = a(i,k) +570 a(i,k) = p(j,k) +580 a(j,k) = a(i,k) +590 next k +600 z = 1/a(j,j) +610 for k = 0 to m+1 +620 a(j,k) = z*a(j,k) +630 next k +640 for i = 0 to m +650 if i <> j then +660 z = -a(i,j) +670 for k = 0 to m+1 +680 a(i,k) = a(i,k)+z*a(j,k) +690 next k +700 endif +710 next i +720 next j +730 print : print "Solutions:" +740 for i = 0 to m +750 print using " #####.#######";a(i,m+1); +760 next i +770 print +780 end diff --git a/Task/Multiple-regression/QB64/multiple-regression.qb64 b/Task/Multiple-regression/QB64/multiple-regression.qb64 new file mode 100644 index 0000000000..5f39849aef --- /dev/null +++ b/Task/Multiple-regression/QB64/multiple-regression.qb64 @@ -0,0 +1,71 @@ +Const N = 14, M = 2, Q = 3 ' number of points and M.R. polynom degree + +Dim X(N) As Double ' data points +Data 1.47,1.50,1.52,1.55,1.57,1.60,1.63,1.65,1.68,1.70,1.73,1.75,1.78,1.80,1.83 +For c = LBound(X) To UBound(X) + Read X(c) +Next c +Dim As Double Y(N) ' data points +Data 52.21,53.12,54.48,55.84,57.20,58.57,59.93,61.29,63.11,64.47,66.28,68.10,69.92,72.19,74.46 +For c = LBound(Y) To UBound(Y) + Read Y(c) +Next c +Dim As Double S(N), T(N) ' linear system coefficient +Dim As Double A(M, Q) ' system to be solved +Dim As Integer i, k, j, fila, columna +Dim As Double z + +For k = 0 To 2 * M + S(k) = 0: T(k) = 0 + For i = 0 To N + S(k) = S(k) + X(i) ^ k + If k <= M Then T(k) = T(k) + Y(i) * X(i) ^ k + Next i +Next k + +' build linear system +For fila = 0 To M + For columna = 0 To M + A(fila, columna) = S(fila + columna) + Next columna + A(fila, columna) = T(fila) +Next fila + +Print "Linear system coefficents:" +For i = 0 To M + For j = 0 To M + 1 + Print Using "######.#"; A(i, j); + Next j + Print +Next i + +For j = 0 To M + For i = j To M + If A(i, j) <> 0 Then Exit For + Next i + If i = M + 1 Then + Print: Print "SINGULAR MATRIX '" + End + End If + For k = 0 To M + 1 + Swap A(j, k), A(i, k) + Next k + z = 1 / A(j, j) + For k = 0 To M + 1 + A(j, k) = z * A(j, k) + Next k + For i = 0 To M + If i <> j Then + z = -A(i, j) + For k = 0 To M + 1 + A(i, k) = A(i, k) + z * A(j, k) + Next k + End If + Next i +Next j + +Print: Print "Solutions:" +For i = 0 To M + Print Using " #####.#######"; A(i, M + 1); +Next i +End diff --git a/Task/Multiple-regression/True-BASIC/multiple-regression.basic b/Task/Multiple-regression/True-BASIC/multiple-regression.basic new file mode 100644 index 0000000000..2b3314a060 --- /dev/null +++ b/Task/Multiple-regression/True-BASIC/multiple-regression.basic @@ -0,0 +1,80 @@ +OPTION BASE 0 +LET n = 14 ! number of points and M.R. polynom degree +LET m = 2 +LET q = 3 +DIM x(0) ! data points +MAT REDIM x(n) +DATA 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83 +FOR c = LBOUND(x) TO UBOUND(x) + READ x(c) +NEXT c +DIM y(0) ! data points +MAT REDIM y(n) +DATA 52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46 +FOR c = LBOUND(y) TO UBOUND(y) + READ y(c) +NEXT c +DIM s(0) ! linear system coefficient +MAT REDIM s(n) +DIM t(0) +MAT REDIM t(n) +DIM a(0,0) ! system to be solved +MAT REDIM a(m, q) +DIM p(0,0) +MAT REDIM p(m, q) + +FOR k = 0 TO 2*m + LET s(k) = 0 + LET t(k) = 0 + FOR i = 0 TO n + LET s(k) = s(k)+x(i)^k + IF k <= m THEN LET t(k) = t(k)+y(i)*x(i)^k + NEXT i +NEXT k +! build linear system +FOR fila = 0 TO m + FOR columna = 0 TO m + LET a(fila, columna) = s(fila+columna) + NEXT columna + LET a(fila, columna) = t(fila) +NEXT fila +PRINT "Linear system coefficents:" +FOR i = 0 TO m + FOR j = 0 TO m+1 + PRINT USING "######.#": a(i, j); + NEXT j + PRINT +NEXT i +FOR j = 0 TO m + FOR i = j TO m + IF a(i, j) <> 0 THEN EXIT FOR + NEXT i + IF i = m+1 THEN + PRINT + PRINT "SINGULAR MATRIX '" + STOP + END IF + FOR k = 0 TO m+1 + LET p(j, k) = a(i, k) + LET a(i, k) = p(j, k) + LET a(j, k) = a(i, k) + NEXT k + LET z = 1/a(j, j) + FOR k = 0 TO m+1 + LET a(j, k) = z*a(j, k) + NEXT k + FOR i = 0 TO m + IF i <> j THEN + LET z = -a(i, j) + FOR k = 0 TO m+1 + LET a(i, k) = a(i, k)+z*a(j, k) + NEXT k + END IF + NEXT i +NEXT j +PRINT +PRINT "Solutions:" +FOR i = 0 TO m + PRINT USING " #####.#######": a(i, m+1); +NEXT i +END diff --git a/Task/Multiple-regression/Yabasic/multiple-regression.basic b/Task/Multiple-regression/Yabasic/multiple-regression.basic new file mode 100644 index 0000000000..2e464e1799 --- /dev/null +++ b/Task/Multiple-regression/Yabasic/multiple-regression.basic @@ -0,0 +1,77 @@ +// number of points and M.R. polynom degree +N = 14 +M = 2 +Q = 3 + +dim X(N) // data points +X(0) = 1.47 : X(1) = 1.50 : X(2) = 1.52 +X(3) = 1.55 : X(4) = 1.57 : X(5) = 1.60 +X(6) = 1.63 : X(7) = 1.65 : X(8) = 1.68 +X(9) = 1.70 : X(10) = 1.73 : X(11) = 1.75 +X(12) = 1.78 : X(13) = 1.80 : X(14) = 1.83 +dim Y(N) // data points +Y(0) = 52.21 : Y(1) = 53.12 : Y(2) = 54.48 +Y(3) = 55.84 : Y(4) = 57.20 : Y(5) = 58.57 +Y(6) = 59.93 : Y(7) = 61.29 : Y(8) = 63.11 +Y(9) = 64.47 : Y(10) = 66.28 : Y(11) = 68.10 +Y(12) = 69.92 : Y(13) = 72.19 : Y(14) = 74.46 + +dim S(N), T(N) // linear system coefficient +dim A(M, Q) // sistem to be solved +dim p(M, Q) + +for k = 0 to 2*M + S(k) = 0 : T(k) = 0 + for i = 0 to N + S(k) = S(k) + X(i) ^ k + if k <= M T(k) = T(k) + Y(i) * X(i) ^ k + next i +next k + +// build linear system +for fila = 0 to M + for columna = 0 to M + A(fila, columna) = S(fila+columna) + next columna + A(fila, columna) = T(fila) +next fila + +print "Linear system coefficents:" +for i = 0 to M + for j = 0 to M+1 + print A(i,j) using "#####.#"; + next j + print +next i + +for j = 0 to M + for i = j to M + if A(i,j) <> 0 break + next i + if i = M+1 then + print "\nSINGULAR MATRIX '" + end + end if + for k = 0 to M+1 + p(j,k) = A(i,k) : A(i,k) = p(j,k) : A(j,k) = A(i,k) + next k + z = 1 / A(j,j) + for k = 0 to M+1 + A(j,k) = z * A(j,k) + next k + for i = 0 to M + if i <> j then + z = -A(i,j) + for k = 0 to M+1 + A(i,k) = A(i,k) + z * A(j,k) + next k + end if + next i +next j + +print "\nSolutions:" +for i = 0 to M + print A(i,M+1) using "#######.#######"; +next i +print +end diff --git a/Task/Multiplicative-order/11l/multiplicative-order.11l b/Task/Multiplicative-order/11l/multiplicative-order.11l index 895e57c750..373554e391 100644 --- a/Task/Multiplicative-order/11l/multiplicative-order.11l +++ b/Task/Multiplicative-order/11l/multiplicative-order.11l @@ -1,9 +1,4 @@ -T PExp - BigInt prime - Int exp - F (prime, exp) - .prime = prime - .exp = exp +T PExp = (BigInt prime, Int exp) F isqrt(self) V b = self diff --git a/Task/Multiplicative-order/Jq/multiplicative-order.jq b/Task/Multiplicative-order/Jq/multiplicative-order.jq new file mode 100644 index 0000000000..207f72ac47 --- /dev/null +++ b/Task/Multiplicative-order/Jq/multiplicative-order.jq @@ -0,0 +1,181 @@ +# Part 1: Library functions + +### Counting and integer arithmetic + +def count(s): reduce s as $x (0; .+1); + +# If $j is 0, then an error condition is raised; +# otherwise, assuming infinite-precision integer arithmetic, +# if the input and $j are integers, then the result will be an integer. +def idivide($j): + (. - (. % $j)) / $j ; + +def idivide($i; $j): + $i | idivide($j); + +# Emit [dividend, mod] +def divmod($j): + (. % $j) as $mod + | [(. - $mod) / $j, $mod] ; + +# input should be a non-negative integer for accuracy +# but may be any non-negative finite number +def isqrt: + def irt: + . as $x + | 1 | until(. > $x; . * 4) as $q + | {$q, $x, r: 0} + | until( .q <= 1; + .q |= idivide(4) + | .t = .x - .r - .q + | .r |= idivide(2) + | if .t >= 0 + then .x = .t + | .r += .q + else . + end) + | .r ; + if type == "number" and (isinfinite|not) and (isnan|not) and . >= 0 + then irt + else "isqrt requires a non-negative integer for accuracy" | error + end ; + +# It is assumed that $n >= 0 +def power($n): + . as $in + | reduce range(0;$n) as $i (1; .* $in); + +# For syntactic convenience +def power($in; $n): $in | power($n); + +def gcd(a; b): + # subfunction expects [a,b] as input + # i.e. a ~ .[0] and b ~ .[1] + def rgcd: if .[1] == 0 then .[0] + else [.[1], .[0] % .[1]] | rgcd + end; + [a,b] | rgcd; + + +### Bit arrays and streams + +def rightshift($n): + reduce range(0;$n) as $i (.; idivide(2)); + +# Convert the input integer to a stream of 0s and 1s, least significant bit first +def bitwise: + recurse( if . >= 2 then idivide(2) else empty end) | . % 2; + +def bitLength: count(bitwise); + +def firstBit: + if . == 0 then empty + else first( foreach bitwise as $b (-1; .+1; if $b == 1 then . else empty end)) + end; + +# Return true if the $i-th least-significant bit is 1, and false otherwise +def testBit($i): + (nth($i; bitwise) // 0) == 1; + +# Part 2: "modulo" functions + +# The multiplicative inverse of . modulo $n +def modInv($n): + . as $in + | { r: $n, + newR: length, # abs + t: 0, + newT: 1 } + | until (.newR != 0.; + idivide(.r; .newR) as $q + | .lastT = .t + | .lastR = .r + | .t = .newT + | .r = .newR + | .newT = .lastT - $q*.newT + | .newR = .lastR - $q*.newR ) + | if .r != 1 + then "\($in) and \($n) are not co-prime." | error + else if (.t < 0) then .t += $n end + | if ($in < 0) then - .t else .t end + end; + +# Return . to the power $exp modulo $mod +def modPow($exp; $mod): + def isOdd: . % 2 == 1; + if $mod == 0 then "Cannot take modPow with modulus 0." | error + else {r: 1, base: (. % $mod), $exp} + | if .exp < 0 + then .exp *= -1 + | .base |= modInv($mod) + end + | until ((.exp == 0) or .emit; + if .base == 0 then .emit = 0 + else if (.exp | isOdd) then .r = (.r * .base) % $mod end + | .exp |= idivide(2) + | .base |= (.*.) % $mod + end ) + | (.emit // .r) + end ; + +# Part 3: Multiplicative order + +def moBachShallit58($a; $n; $pf): + {n1: ($n - 1), + mo: 1 } + | reduce $pf[] as $pe (.; + (.n1 | idivide($pe.prime | power($pe.exp))) as $y + | .o = 0 + | .x = ($a | modPow($y; ($n|length))) + | until (.x <= 1; + .x |= modPow($pe.prime; ($n|length) ) + | .o += 1 ) + | .o1 = .o + | .o1 = power($pe.prime;.o1) + | .o1 = idivide(.o1; gcd(.mo; .o1) ) + | .mo = .mo * .o1 ) + | .mo ; + +def factor($n): + { pf: [], + nn: $n, + e: ($n | firstBit)} + | if .e > 0 + then .e as $e + | .nn |= rightshift($e) + | .pf = [{prime: 2, exp: .e}] + end + | (.nn | isqrt) as $s + | .d = 3 + | until (.nn <= 1; + if .d > $s then .d = .nn end + | .e = 0 + | .done = null + | until( .done; + .d as $d + | (.nn | divmod($d)) as $dm + | if $dm[1] > 0 + then .done = true + else .nn = $dm[0] + | .e += 1 + end ) + | if .e > 0 + then .pf += [{prime: .d, exp: .e}] + |.s = (.nn|isqrt) + end + | .d += 2 + ) + | .pf ; + +# $n should be prime +def moTest($a; $n): + if ($a|bitLength) < 100 then "ord(\($a)) " else "ord([big]) " end + + if ($n|bitLength) < 100 then "mod \($n) " else "mod [big] " end + + "= \(moBachShallit58($a; $n; factor($n - 1)))" ; + +moTest(37; 3343), +moTest(1 + power(10;100); 7919), +moTest(1 + power(10;100); 15485863), +moTest(power(10;10000) - 1; 22801763489), +moTest(1511678068; 7379191741), +moTest(3047753288; 2257683301) diff --git a/Task/Multisplit/EasyLang/multisplit.easy b/Task/Multisplit/EasyLang/multisplit.easy new file mode 100644 index 0000000000..ac60f0d2ff --- /dev/null +++ b/Task/Multisplit/EasyLang/multisplit.easy @@ -0,0 +1,17 @@ +proc multisplit str$ sep$[] . . + repeat + min = 1 / 0 + for sep$ in sep$[] + pos = strpos str$ sep$ + if pos > 0 and pos < min + min = pos + msep$ = sep$ + . + . + until min = 1 / 0 + write substr str$ 1 (min - 1) & "{" & msep$ & "}" + str$ = substr str$ (min + len msep$) 9999 + . + print str$ +. +multisplit "a!===b=!=c" [ "==" "!=" "=" ] diff --git a/Task/Munchausen-numbers/Langur/munchausen-numbers.langur b/Task/Munchausen-numbers/Langur/munchausen-numbers.langur index 745bbd073b..b97ba6c9a9 100644 --- a/Task/Munchausen-numbers/Langur/munchausen-numbers.langur +++ b/Task/Munchausen-numbers/Langur/munchausen-numbers.langur @@ -1,5 +1,5 @@ # sum power of digits -val .spod = fn(.n) fold fn{+}, map(fn(.x) .x^.x, s2n string .n) +val spod = fn n:fold(fn{+}, map(fn x:x^x, n -> string -> s2n)) # Munchausen -writeln "Answers: ", filter fn(.n) .n == .spod(.n), series 0..5000 +writeln "Answers: ", filter(fn n: n == spod(n), series(1..5000)) diff --git a/Task/Munchausen-numbers/Rust/munchausen-numbers.rust b/Task/Munchausen-numbers/Rust/munchausen-numbers-1.rust similarity index 100% rename from Task/Munchausen-numbers/Rust/munchausen-numbers.rust rename to Task/Munchausen-numbers/Rust/munchausen-numbers-1.rust diff --git a/Task/Munchausen-numbers/Rust/munchausen-numbers-2.rust b/Task/Munchausen-numbers/Rust/munchausen-numbers-2.rust new file mode 100644 index 0000000000..3f1f196de9 --- /dev/null +++ b/Task/Munchausen-numbers/Rust/munchausen-numbers-2.rust @@ -0,0 +1,35 @@ +use num_bigint::BigUint; +use num_traits::cast::ToPrimitive; +use rayon::prelude::*; + +fn main() { + // Helper function to compute the Munchausen sum + fn munchausen_sum(num: &BigUint) -> BigUint { + num.to_string() + .chars() + .map(|c| { + let digit = c.to_digit(10).unwrap(); + if digit == 0 { + BigUint::from(0u32) + } else { + BigUint::from(digit).pow(digit) + } + }) + .sum::() + } + + // Loop through the desired range + let start = BigUint::from(0u128); + let end = BigUint::from(1_000_00u128); + let solutions: Vec = (start.to_u128().unwrap()..end.to_u128().unwrap()) + .into_par_iter() + .map(|n| BigUint::from(n)) + .filter(|num| munchausen_sum(num) == *num) + .collect(); + + for solution in &solutions { + println!("Munchausen number found: {:?}", solution); + } + + println!("Munchausen numbers below {:?}: {:?}", end, solutions); +} diff --git a/Task/Musical-scale/Ada/musical-scale.ada b/Task/Musical-scale/Ada/musical-scale.ada new file mode 100644 index 0000000000..ba11498f78 --- /dev/null +++ b/Task/Musical-scale/Ada/musical-scale.ada @@ -0,0 +1,74 @@ +pragma Ada_2022; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Sequential_IO; +with Interfaces; use Interfaces; + +procedure Musical_Scale is + package Byte_IO is new Ada.Sequential_IO (Unsigned_8); use Byte_IO; + + SAMPLE_RATE : constant Unsigned_32 := 44100; + DURATION : constant Unsigned_32 := 8; + DATA_LENGTH : constant Unsigned_32 := SAMPLE_RATE * DURATION; + WAV_HDR_LEN : constant Integer := 44; + FILE_SIZE_8 : constant Unsigned_32 := Unsigned_32 (WAV_HDR_LEN) + DATA_LENGTH + 4; + + type Byte_Arr is array (Positive range <>) of Unsigned_8; + Wav_Header : constant Byte_Arr (1 .. WAV_HDR_LEN) := [ + Character'Pos ('R'), Character'Pos ('I'), Character'Pos ('F'), Character'Pos ('F'), + Unsigned_8 (FILE_SIZE_8 and 16#ff#), + Unsigned_8 (Shift_Right (FILE_SIZE_8, 8) and 16#ff#), + Unsigned_8 (Shift_Right (FILE_SIZE_8, 16) and 16#ff#), + Unsigned_8 (Shift_Right (FILE_SIZE_8, 24) and 16#ff#), + Character'Pos ('W'), Character'Pos ('A'), Character'Pos ('V'), Character'Pos ('E'), + Character'Pos ('f'), Character'Pos ('m'), Character'Pos ('t'), Character'Pos (' '), + 16#10#, 0, 0, 0, 1, 0, 1, 0, 16#44#, 16#ac#, 0, 0, 16#44#, 16#ac#, 0, 0, 1, 0, 8, 0, + Character'Pos ('d'), Character'Pos ('a'), Character'Pos ('t'), Character'Pos ('a'), + Unsigned_8 (DATA_LENGTH and 16#ff#), + Unsigned_8 (Shift_Right (DATA_LENGTH, 8) and 16#ff#), + Unsigned_8 (Shift_Right (DATA_LENGTH, 16) and 16#ff#), + Unsigned_8 (Shift_Right (DATA_LENGTH, 24) and 16#ff#) + ]; + MIDI_Header : constant Byte_Arr (1 .. 22) := [ + Character'Pos ('M'), Character'Pos ('T'), Character'Pos ('h'), Character'Pos ('d'), + 0, 0, 0, 6, 0, 0, 0, 1, 0, 96, -- File header + Character'Pos ('M'), Character'Pos ('T'), Character'Pos ('r'), Character'Pos ('k'), + 0, 0, 0, 8 * 8 + 4 -- Track header + ]; + MIDI_Trailer : constant Byte_Arr := [0, 16#ff#, 16#2f#, 0]; + type Freq_Arr is array (Positive range <>) of Float; + Freqs : constant Freq_Arr := [261.63, 293.67, 329.63, 349.23, 392.0, 440.0, 493.88, 523.25]; + Notes : constant Byte_Arr := [60, 62, 64, 65, 67, 69, 71, 72]; + Note_On_Off : Byte_Arr := [0, 16#90#, 0, 16#40#, 16#60#, 16#80#, 0, 0]; + + Wav_File, MIDI_File : File_Type; + Omega : Float; + + procedure Write_Arr (File : File_Type; Arr : Byte_Arr) is + begin + for B of Arr loop + Write (File, B); + end loop; + end Write_Arr; + +begin + Create (Wav_File, Out_File, "scale.wav"); + Write_Arr (Wav_File, Wav_Header); + for Freq of Freqs loop + Omega := 2.0 * Pi * Freq; + for Tick in 0 .. Integer (DATA_LENGTH) / 8 loop + Write (Wav_File, Unsigned_8 (32.0 * (Sin (Omega * Float (Tick) / Float (SAMPLE_RATE)) + 1.0))); + end loop; + end loop; + Close (Wav_File); + + Create (MIDI_File, Out_File, "scale.mid"); + Write_Arr (MIDI_File, MIDI_Header); + for Note of Notes loop + Note_On_Off (3) := Note; + Note_On_Off (7) := Note; + Write_Arr (MIDI_File, Note_On_Off); + end loop; + Write_Arr (MIDI_File, MIDI_Trailer); + Close (MIDI_File); +end Musical_Scale; diff --git a/Task/Mutual-recursion/EMal/mutual-recursion.emal b/Task/Mutual-recursion/EMal/mutual-recursion.emal new file mode 100644 index 0000000000..4eec1403e0 --- /dev/null +++ b/Task/Mutual-recursion/EMal/mutual-recursion.emal @@ -0,0 +1,8 @@ +fun F ← #include +#include -int count = 0; -void solve(int n, int col, int *hist) -{ - if (col == n) { - printf("\nNo. %d\n-----\n", ++count); - for (int i = 0; i < n; i++, putchar('\n')) - for (int j = 0; j < n; j++) - putchar(j == hist[i] ? 'Q' : ((i + j) & 1) ? ' ' : '.'); +// In column order, print out the given positions in chess notation. +// For example, when N = 8, the first solution printed is: +// "a1 b5 c8 d6 e3 f7 g2 h4" +static void print_positions(int x[], const size_t n) { + static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz"; - return; + // There are only 26 letters in the ASCII alphabet, so + // so don't bother with chess notation above 26. + if (n <= 26) { + for (size_t i = 0; i < n; ++i) + printf("%c%u ", alphabet[i], x[i] + 1); + } else { + for (size_t i = 0; i < n; ++i) + printf("%u ", x[i] + 1); } + putchar('\n'); +} -# define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j) - for (int i = 0, j = 0; i < n; i++) { - for (j = 0; j < col && !attack(i, j); j++); - if (j < col) continue; +// Print all solutions to the N queens problem, holding the results in +// the intermediate array x, and with the auxiliary boolean arrays a, b, and c. +// x and a are both N elements long, while b and c are 2*N-1 elements long. +// It is assumed that these arrays are zeroed before this routine is called. +static void queens(int x[], bool a[], bool b[], bool c[], const size_t n) { + size_t col, row = 0; - hist[col] = i; - solve(n, col + 1, hist); +advance_row: + if (row >= n) { + print_positions(x, n); + goto backtrack; + } + col = 0; +try_column: + if (!a[col] && !b[col+row-1] && !c[col-row+n]) { + a[col] = true; + b[col+row-1] = true; + c[col-row+n] = true; + x[row] = col; + row++; + goto advance_row; + } +try_again: + if (col < n-1) { + col++; + goto try_column; + } +backtrack: + if (row != 0) { + --row; + col = x[row]; + c[col-row+n] = false; + b[col+row-1] = false; + a[col] = false; + goto try_again; } } -int main(int n, char **argv) -{ - if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 8; - int hist[n]; - solve(n, 0, hist); +static void *calloc_wrapper(size_t count, size_t bytesize) { + void *r; + if ((r = calloc(count, bytesize)) == NULL) { + exit(EXIT_FAILURE); + } + return r; +} + +int main(int argc, char **argv) { + bool *a, *b, *c; + int n, *x; + + if (argc != 2 || (n = atoi(argv[1])) <= 0) { + printf("%s: specify a natural number argument\n", argv[0]); + return 1; + } + + x = calloc_wrapper(n, sizeof(x[0])); + a = calloc_wrapper(n, sizeof(a[0])); + b = calloc_wrapper((2 * n - 1), sizeof(b[0])); + c = calloc_wrapper((2 * n - 1), sizeof(c[0])); + + queens(x, a, b, c, n); + + // Don't bother freeing before exiting. + return 0; } diff --git a/Task/N-queens-problem/C/n-queens-problem-2.c b/Task/N-queens-problem/C/n-queens-problem-2.c index dcc46bb728..2dc59e4e1f 100644 --- a/Task/N-queens-problem/C/n-queens-problem-2.c +++ b/Task/N-queens-problem/C/n-queens-problem-2.c @@ -1,38 +1,31 @@ #include #include -#include -typedef uint32_t uint; -uint full, *qs, count = 0, nn; - -void solve(uint d, uint c, uint l, uint r) +int count = 0; +void solve(int n, int col, int *hist) { - uint b, a, *s; - if (!d) { - count++; -#if 0 - printf("\nNo. %d\n===========\n", count); - for (a = 0; a < nn; a++, putchar('\n')) - for (b = 0; b < nn; b++, putchar(' ')) - putchar(" -QQ"[((b == qs[a])<<1)|((a + b)&1)]); -#endif + if (col == n) { + printf("\nNo. %d\n-----\n", ++count); + for (int i = 0; i < n; i++, putchar('\n')) + for (int j = 0; j < n; j++) + putchar(j == hist[i] ? 'Q' : ((i + j) & 1) ? ' ' : '.'); + return; } - a = (c | (l <<= 1) | (r >>= 1)) & full; - if (a != full) - for (*(s = qs + --d) = 0, b = 1; b <= full; (*s)++, b <<= 1) - if (!(b & a)) solve(d, b|c, b|l, b|r); +# define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j) + for (int i = 0, j = 0; i < n; i++) { + for (j = 0; j < col && !attack(i, j); j++); + if (j < col) continue; + + hist[col] = i; + solve(n, col + 1, hist); + } } int main(int n, char **argv) { - if (n <= 1 || (nn = atoi(argv[1])) <= 0) nn = 8; - - qs = calloc(nn, sizeof(int)); - full = (1U << nn) - 1; - - solve(nn, 0, 0, 0); - printf("\nSolutions: %d\n", count); - return 0; + if (n <= 1 || (n = atoi(argv[1])) <= 0) n = 8; + int hist[n]; + solve(n, 0, hist); } diff --git a/Task/N-queens-problem/C/n-queens-problem-3.c b/Task/N-queens-problem/C/n-queens-problem-3.c index 3316ea1a70..dcc46bb728 100644 --- a/Task/N-queens-problem/C/n-queens-problem-3.c +++ b/Task/N-queens-problem/C/n-queens-problem-3.c @@ -1,91 +1,38 @@ #include #include +#include -typedef unsigned int uint; -uint count = 0; +typedef uint32_t uint; +uint full, *qs, count = 0, nn; -#define ulen sizeof(uint) * 8 - -/* could have defined as int solve(...), but void may have less - chance to confuse poor optimizer */ -void solve(int n) +void solve(uint d, uint c, uint l, uint r) { - int cnt = 0; - const uint full = -(int)(1 << (ulen - n)); - register uint bits, pos, *m, d, e; - - uint b0, b1, l[32], r[32], c[32], mm[33] = {0}; - n -= 3; - /* require second queen to be left of the first queen, so - we ever only test half of the possible solutions. This - is why we can't handle n=1 here */ - for (b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) { - for (b1 = b0 << 2; b1; b1 <<= 1) { - d = n; - /* c: columns occupied by previous queens. - l: columns attacked by left diagonals - r: by right diagnoals */ - c[n] = b0 | b1; - l[n] = (b0 << 2) | (b1 << 1); - r[n] = (b0 >> 2) | (b1 >> 1); - - /* availabe columns on current row. m is stack */ - bits = *(m = mm + 1) = full & ~(l[n] | r[n] | c[n]); - - while (bits) { - /* d: depth, aka row. counting backwards - because !d is often faster than d != n */ - while (d) { - /* pos is right most nonzero bit */ - pos = -(int)bits & bits; - - /* mark bit used. only put current bits - on stack if not zero, so backtracking - will skip exhausted rows (because reading - stack variable is sloooow compared to - registers) */ - if ((bits &= ~pos)) - *m++ = bits | d; - - /* faster than l[d+1] = l[d]... */ - e = d--; - l[d] = (l[e] | pos) << 1; - r[d] = (r[e] | pos) >> 1; - c[d] = c[e] | pos; - - bits = full & ~(l[d] | r[d] | c[d]); - - if (!bits) break; - if (!d) { cnt++; break; } - } - /* Bottom of stack m is a zero'd field acting - as sentinel. When saving to stack, left - 27 bits are the available columns, while - right 5 bits is the depth. Hence solution - is limited to size 27 board -- not that it - matters in foreseeable future. */ - d = (bits = *--m) & 31U; - bits &= ~31U; - } - } + uint b, a, *s; + if (!d) { + count++; +#if 0 + printf("\nNo. %d\n===========\n", count); + for (a = 0; a < nn; a++, putchar('\n')) + for (b = 0; b < nn; b++, putchar(' ')) + putchar(" -QQ"[((b == qs[a])<<1)|((a + b)&1)]); +#endif + return; } - count = cnt * 2; + + a = (c | (l <<= 1) | (r >>= 1)) & full; + if (a != full) + for (*(s = qs + --d) = 0, b = 1; b <= full; (*s)++, b <<= 1) + if (!(b & a)) solve(d, b|c, b|l, b|r); } -int main(int c, char **v) +int main(int n, char **argv) { - int nn; - if (c <= 1 || (nn = atoi(v[1])) <= 0) nn = 8; + if (n <= 1 || (nn = atoi(argv[1])) <= 0) nn = 8; - if (nn > 27) { - fprintf(stderr, "Value too large, abort\n"); - exit(1); - } - - /* Can't solve size 1 board; might as well skip 2 and 3 */ - if (nn < 4) count = nn == 1; - else solve(nn); + qs = calloc(nn, sizeof(int)); + full = (1U << nn) - 1; + solve(nn, 0, 0, 0); printf("\nSolutions: %d\n", count); return 0; } diff --git a/Task/N-queens-problem/C/n-queens-problem-4.c b/Task/N-queens-problem/C/n-queens-problem-4.c index 113b40fdcc..3316ea1a70 100644 --- a/Task/N-queens-problem/C/n-queens-problem-4.c +++ b/Task/N-queens-problem/C/n-queens-problem-4.c @@ -1,69 +1,91 @@ #include -#define MAXN 31 +#include -int nqueens(int n) +typedef unsigned int uint; +uint count = 0; + +#define ulen sizeof(uint) * 8 + +/* could have defined as int solve(...), but void may have less + chance to confuse poor optimizer */ +void solve(int n) { - int q0,q1; - int cols[MAXN], diagl[MAXN], diagr[MAXN], posibs[MAXN]; // Our backtracking 'stack' - int num=0; - // - // The top level is two fors, to save one bit of symmetry in the enumeration by forcing second queen to - // be AFTER the first queen. - // - for (q0=0; q0>1 | bit1)>>1; + int cnt = 0; + const uint full = -(int)(1 << (ulen - n)); + register uint bits, pos, *m, d, e; - // The variable posib contains the bitmask of possibilities we still have to try in a given row ... - int posib = ~(cols[0] | diagl[0] | diagr[0]); + uint b0, b1, l[32], r[32], c[32], mm[33] = {0}; + n -= 3; + /* require second queen to be left of the first queen, so + we ever only test half of the possible solutions. This + is why we can't handle n=1 here */ + for (b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) { + for (b1 = b0 << 2; b1; b1 <<= 1) { + d = n; + /* c: columns occupied by previous queens. + l: columns attacked by left diagonals + r: by right diagnoals */ + c[n] = b0 | b1; + l[n] = (b0 << 2) | (b1 << 1); + r[n] = (b0 >> 2) | (b1 >> 1); - while (d >= 0) { - while(posib) { - int bit = posib & -posib; // The standard trick for getting the rightmost bit in the mask - int ncols= cols[d] | bit; - int ndiagl = (diagl[d] | bit) << 1; - int ndiagr = (diagr[d] | bit) >> 1; - int nposib = ~(ncols | ndiagl | ndiagr); - posib^=bit; // Eliminate the tried possibility. + /* availabe columns on current row. m is stack */ + bits = *(m = mm + 1) = full & ~(l[n] | r[n] | c[n]); - // The following is the main additional trick here, as recognizing solution can not be done using stack level (d), - // since we save the depth+backtrack time at the end of the enumeration loop. However by noticing all coloumns are - // filled (comparison to -1) we know a solution was reached ... - // Notice also that avoiding an if on the ncols==-1 comparison is more efficient! - num += ncols==-1; + while (bits) { + /* d: depth, aka row. counting backwards + because !d is often faster than d != n */ + while (d) { + /* pos is right most nonzero bit */ + pos = -(int)bits & bits; - if (nposib) { - if (posib) { // This if saves stack depth + backtrack operations when we passed the last possibility in a row. - posibs[d++] = posib; // Go lower in stack .. - } - cols[d] = ncols; - diagl[d] = ndiagl; - diagr[d] = ndiagr; - posib = nposib; - } - } - posib = posibs[--d]; // backtrack ... - } - } - } - return num*2; + /* mark bit used. only put current bits + on stack if not zero, so backtracking + will skip exhausted rows (because reading + stack variable is sloooow compared to + registers) */ + if ((bits &= ~pos)) + *m++ = bits | d; + + /* faster than l[d+1] = l[d]... */ + e = d--; + l[d] = (l[e] | pos) << 1; + r[d] = (r[e] | pos) >> 1; + c[d] = c[e] | pos; + + bits = full & ~(l[d] | r[d] | c[d]); + + if (!bits) break; + if (!d) { cnt++; break; } + } + /* Bottom of stack m is a zero'd field acting + as sentinel. When saving to stack, left + 27 bits are the available columns, while + right 5 bits is the depth. Hence solution + is limited to size 27 board -- not that it + matters in foreseeable future. */ + d = (bits = *--m) & 31U; + bits &= ~31U; + } + } + } + count = cnt * 2; } - -main(int ac , char **av) +int main(int c, char **v) { - if(ac != 2) { - printf("usage: nq n\n"); - return 1; - } - int n = atoi(av[1]); - if(n<1 || n > MAXN) { - printf("n must be between 2 and 31!\n"); - } - printf("Number of solution for %d is %d\n",n,nqueens(n)); + int nn; + if (c <= 1 || (nn = atoi(v[1])) <= 0) nn = 8; + + if (nn > 27) { + fprintf(stderr, "Value too large, abort\n"); + exit(1); + } + + /* Can't solve size 1 board; might as well skip 2 and 3 */ + if (nn < 4) count = nn == 1; + else solve(nn); + + printf("\nSolutions: %d\n", count); + return 0; } diff --git a/Task/N-queens-problem/C/n-queens-problem-5.c b/Task/N-queens-problem/C/n-queens-problem-5.c new file mode 100644 index 0000000000..113b40fdcc --- /dev/null +++ b/Task/N-queens-problem/C/n-queens-problem-5.c @@ -0,0 +1,69 @@ +#include +#define MAXN 31 + +int nqueens(int n) +{ + int q0,q1; + int cols[MAXN], diagl[MAXN], diagr[MAXN], posibs[MAXN]; // Our backtracking 'stack' + int num=0; + // + // The top level is two fors, to save one bit of symmetry in the enumeration by forcing second queen to + // be AFTER the first queen. + // + for (q0=0; q0>1 | bit1)>>1; + + // The variable posib contains the bitmask of possibilities we still have to try in a given row ... + int posib = ~(cols[0] | diagl[0] | diagr[0]); + + while (d >= 0) { + while(posib) { + int bit = posib & -posib; // The standard trick for getting the rightmost bit in the mask + int ncols= cols[d] | bit; + int ndiagl = (diagl[d] | bit) << 1; + int ndiagr = (diagr[d] | bit) >> 1; + int nposib = ~(ncols | ndiagl | ndiagr); + posib^=bit; // Eliminate the tried possibility. + + // The following is the main additional trick here, as recognizing solution can not be done using stack level (d), + // since we save the depth+backtrack time at the end of the enumeration loop. However by noticing all coloumns are + // filled (comparison to -1) we know a solution was reached ... + // Notice also that avoiding an if on the ncols==-1 comparison is more efficient! + num += ncols==-1; + + if (nposib) { + if (posib) { // This if saves stack depth + backtrack operations when we passed the last possibility in a row. + posibs[d++] = posib; // Go lower in stack .. + } + cols[d] = ncols; + diagl[d] = ndiagl; + diagr[d] = ndiagr; + posib = nposib; + } + } + posib = posibs[--d]; // backtrack ... + } + } + } + return num*2; +} + + +main(int ac , char **av) +{ + if(ac != 2) { + printf("usage: nq n\n"); + return 1; + } + int n = atoi(av[1]); + if(n<1 || n > MAXN) { + printf("n must be between 2 and 31!\n"); + } + printf("Number of solution for %d is %d\n",n,nqueens(n)); +} diff --git a/Task/N-queens-problem/Commodore-BASIC/n-queens-problem.basic b/Task/N-queens-problem/Commodore-BASIC/n-queens-problem.basic new file mode 100644 index 0000000000..9fc67f1733 --- /dev/null +++ b/Task/N-queens-problem/Commodore-BASIC/n-queens-problem.basic @@ -0,0 +1,55 @@ +100 REM N-QUEENS PROBLEM IN CBM BASIC 2 +110 NQ = 8: GOSUB 200: IF A THEN NQ=A +120 PRINT CHR$(147) "SOLVING FOR" NQ "QUEENS" +130 DIM B(NQ), C(NQ), R(NQ):REM BOARD, COLUMN, ROW +140 SP = 0: REM STACK POINTER +150 TI$ = "000000": REM RESET TIMER +160 R(SP) = 0: SP = SP + 1: GOSUB 500: SP = SP - 1:REM PLACE.QUEEN(0) +170 PRINT "FOUND" SC "SOLUTIONS IN" TI / 60 "SECONDS" +180 END +190 REM +200 REM PARSE COMMAND-LINE ARGUMENT +210 P = 512 +220 C = PEEK(P): P = P + 1: IF C <> 0 THEN 220 +230 C = PEEK(P): P = P + 1: IF C = 78 THEN 290 +240 A = 0 +250 IF C = 0 THEN 290 +260 IF C < 48 OR C > 57 THEN PRINT "USAGE: RUN:": END +270 A = A * 10 + C - 48 +280 C = PEEK(P): P = P + 1: GOTO 250 +290 RETURN +295 REM +300 REM COULD.PLACE(ROW, COL): BOOL +310 CP = -1 +320 R = R(SP - 1): IF R = 0 THEN RETURN +330 C = C(SP - 1) +340 FOR I = 0 TO R - 1 +350 : IF B(I) = C OR B(I) - I = C - R OR B(I) + I = C + R THEN CP = 0 +360 : IF CP = 0 THEN I = R - 1 +370 NEXT I +380 RETURN +390 REM +400 REM PRINT.SOLUTION +410 SC = SC + 1: PRINT CHR$(19) CHR$(17) CHR$(17) "FOUND SOLUTION" SC CHR$(13) +420 FOR I=0 TO NQ - 1 +430 : PRINT " "; +440 : IF B(I) THEN N=B(I):CH=46:GOSUB 600 +450 : PRINT "Q"; +460 : IF B(I) < NQ - 1 THEN N=NQ - 1 - B(I):CH=46:GOSUB 600 +470 : PRINT +480 NEXT I +490 PRINT: RETURN +495 REM PLACE.QUEEN(ROW) +500 IF R(SP - 1) = NQ THEN GOSUB 400: RETURN +510 C(SP - 1) = 0 +520 IF C(SP - 1) = NQ THEN 590 +530 GOSUB 300: IF CP = 0 THEN 570 +540 B(R(SP - 1)) = C(SP - 1) +550 R(SP) = R(SP - 1) + 1: SP = SP + 1:GOSUB 500: SP = SP - 1 +560 B(R(SP - 1)) = 0 +570 C(SP - 1) = C(SP - 1) + 1 +580 GOTO 520 +590 RETURN +600 REM PRINT A CHARACTER N TIMES +610 FOR QQ=1 TO N:PRINT CHR$(CH);:NEXT +620 RETURN diff --git a/Task/N-queens-problem/Pascal/n-queens-problem-1.pas b/Task/N-queens-problem/Pascal/n-queens-problem-1.pas index 617a48c86c..698c6fc391 100644 --- a/Task/N-queens-problem/Pascal/n-queens-problem-1.pas +++ b/Task/N-queens-problem/Pascal/n-queens-problem-1.pas @@ -1,81 +1,34 @@ -program queens; +program eightqueens(output); +var i: integer; + a: array [1..8] of boolean; { a[j]: no queen in row j } + b: array [2..16] of boolean; { b[k]: no queen in kth diagonal down-left } + c: array [-7..7] of boolean; { c[k]: no queen in kth diagonal down-right } + x: array [1..8] of integer; { x[i]: position of queen in column i } +procedure print; + var k: integer; +begin + for k := 1 to 8 do write(x[k]: 4); + writeln +end { print } ; -const l=16; - -var i,j,k,m,n,p,q,r,y,z: integer; - a,s: array[1..l] of integer; - u: array[1..4*l-2] of integer; - -label L3,L4,L5,L6,L7,L8,L9,L10; +procedure try(i: integer); + var j: integer; +begin + for j := 1 to 8 do + if a[j] and b[i+j] and c[i-j] then + begin + { place queen } + x[i] := j; + a[j] := false; b[i+j] := false; c[i-j] := false; + if i < 8 then try(i+1) else print; + { remove queen } + a[j] := true; b[i+j] := true; c[i-j] := true + end +end { try } ; begin - for i:=1 to l do a[i]:=i; - for i:=1 to 4*l-2 do u[i]:=0; - for n:=1 to l do - begin - m:=0; - i:=1; - r:=2*n-1; - goto L4; -L3: - s[i]:=j; - u[p]:=1; - u[q+r]:=1; - i:=i+1; -L4: - if i>n then goto L8; - j:=i; -L5: - z:=a[i]; - y:=a[j]; - p:=i-y+n; - q:=i+y-1; - a[i]:=y; - a[j]:=z; - if (u[p]=0) and (u[q+r]=0) then goto L3; -L6: - j:=j+1; - if j<=n then goto L5; -L7: - j:=j-1; - if j=i then goto L9; - z:=a[i]; - a[i]:=a[j]; - a[j]:=z; - goto L7; -L8: - m:=m+1; - { uncomment the following to print solutions } - { write(n,' ',m,':'); - for k:=1 to n do write(' ',a[k]); - writeln; } -L9: - i:=i-1; - if i=0 then goto L10; - p:=i-a[i]+n; - q:=i+a[i]-1; - j:=s[i]; - u[p]:=0; - u[q+r]:=0; - goto L6; -L10: - writeln(n,' ',m); - end; -end. - -{ 1 1 - 2 0 - 3 0 - 4 2 - 5 10 - 6 4 - 7 40 - 8 92 - 9 352 - 10 724 - 11 2680 - 12 14200 - 13 73712 - 14 365596 - 15 2279184 - 16 14772512 } + for i := 1 to 8 do a[i] := true; + for i := 2 to 16 do b[i] := true; + for i := -7 to 7 do c[i] := true; + try(1) +end . diff --git a/Task/N-queens-problem/Pascal/n-queens-problem-2.pas b/Task/N-queens-problem/Pascal/n-queens-problem-2.pas index 92b7279557..617a48c86c 100644 --- a/Task/N-queens-problem/Pascal/n-queens-problem-2.pas +++ b/Task/N-queens-problem/Pascal/n-queens-problem-2.pas @@ -1,112 +1,81 @@ -program NQueens; -{$IFDEF FPC} - {$MODE DELPHI} - {$OPTIMIZATION ON}{$OPTIMIZATION REGVAR}{$OPTIMIZATION PeepHole} - {$OPTIMIZATION CSE}{$OPTIMIZATION ASMCSE} -{$ELSE} - {$Apptype console} -{$ENDIF} +program queens; + +const l=16; + +var i,j,k,m,n,p,q,r,y,z: integer; + a,s: array[1..l] of integer; + u: array[1..4*l-2] of integer; + +label L3,L4,L5,L6,L7,L8,L9,L10; -uses - sysutils;// TDatetime -const - nmax = 17; -type -{$IFNDEF FPC} - NativeInt = longInt; -{$ENDIF} - //ala Nikolaus Wirth A-1 = H - 8 - //diagonal left (A1) to rigth (H8) - tLR_diagonale = array[-nmax-1..nmax-1] of char; - //diagonal right (A8) to left (H1) - tRL_diagonale = array[0..2*nmax-2] of char; - //up to Col are the used Cols, after that the unused - tFreeCol = array[0..nmax-1] of nativeInt; -var - LR_diagonale:tLR_diagonale; - RL_diagonale:tRL_diagonale; - //Using pChar, cause it is implicit an array - //It is always set to - //@LR_diagonale[row] ,@RL_diagonale[row] - pLR,pRL : pChar; - FreeCol : tFreeCol; - i, - n : nativeInt; - gblCount : nativeUInt; - T0,T1 : TdateTime; -procedure Solution; -var - i : NativeInt; begin -// Take's a lot of time under DOS/Win32 - If gblCount AND $FFF = 0 then - write(gblCount:10,#8#8#8#8#8#8#8#8#8#8); - // IF n< 9 then - IF n < 0 then + for i:=1 to l do a[i]:=i; + for i:=1 to 4*l-2 do u[i]:=0; + for n:=1 to l do begin - For i := 1 to n do - write(FreeCol[i]:4); - writeln; + m:=0; + i:=1; + r:=2*n-1; + goto L4; +L3: + s[i]:=j; + u[p]:=1; + u[q+r]:=1; + i:=i+1; +L4: + if i>n then goto L8; + j:=i; +L5: + z:=a[i]; + y:=a[j]; + p:=i-y+n; + q:=i+y-1; + a[i]:=y; + a[j]:=z; + if (u[p]=0) and (u[q+r]=0) then goto L3; +L6: + j:=j+1; + if j<=n then goto L5; +L7: + j:=j-1; + if j=i then goto L9; + z:=a[i]; + a[i]:=a[j]; + a[j]:=z; + goto L7; +L8: + m:=m+1; + { uncomment the following to print solutions } + { write(n,' ',m,':'); + for k:=1 to n do write(' ',a[k]); + writeln; } +L9: + i:=i-1; + if i=0 then goto L10; + p:=i-a[i]+n; + q:=i+a[i]-1; + j:=s[i]; + u[p]:=0; + u[q+r]:=0; + goto L6; +L10: + writeln(n,' ',m); end; -end; - -procedure SetQueen(Row:nativeInt); -var - i,Col : nativeInt; -begin -IF row <= n then - begin - For i := row to n do - begin - Col := FreeCol[i]; - //check diagonals occupied - If (ORD(pLR[-Col]) AND ORD(pRL[Col]))<>0 then - begin - //a "free" position is found - //mark it - pRL[ Col]:=#0; //RL_Diagonale[ Row +Col] := 0; - pLR[-Col]:=#0; //LR_Diagonale[ Row -Col] := 0; - //swap FreeRow[Row<->i] - FreeCol[i] := FreeCol[Row]; - //next row - inc(pRL); - inc(pLR); - FreeCol[Row] := Col; - // check next row - SetQueen(Row+1); - //Undo - dec(pLR); - dec(pRL); - FreeCol[Row] := FreeCol[i]; - FreeCol[i] := Col; - pRL[ Col]:=#1; - pLR[-Col]:=#1; - end; - end; - end -else - begin - //solution ist found - inc(gblCount); - //Solution - end; -end; - -begin - For i := 0 to nmax-1 do - FreeCol[i] := i; - //diagonals filled with True = #1 , something <>0 - fillchar(LR_Diagonale[low(LR_Diagonale)],sizeof(tLR_Diagonale),#1); - fillchar(RL_Diagonale[low(RL_Diagonale)],sizeof(tRL_Diagonale),#1); - For n := 1 to nMax do - begin - t0 := time; - pLR:=@LR_Diagonale[0]; - pRL:=@RL_Diagonale[0]; - gblCount := 0; - SetQueen(1); - t1:= time; - WriteLn(n:6,gblCount:12,FormatDateTime(' NN:SS.ZZZ',T1-t0),' secs'); - end; - WriteLn('Fertig'); end. + +{ 1 1 + 2 0 + 3 0 + 4 2 + 5 10 + 6 4 + 7 40 + 8 92 + 9 352 + 10 724 + 11 2680 + 12 14200 + 13 73712 + 14 365596 + 15 2279184 + 16 14772512 } diff --git a/Task/N-queens-problem/Pascal/n-queens-problem-3.pas b/Task/N-queens-problem/Pascal/n-queens-problem-3.pas new file mode 100644 index 0000000000..92b7279557 --- /dev/null +++ b/Task/N-queens-problem/Pascal/n-queens-problem-3.pas @@ -0,0 +1,112 @@ +program NQueens; +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON}{$OPTIMIZATION REGVAR}{$OPTIMIZATION PeepHole} + {$OPTIMIZATION CSE}{$OPTIMIZATION ASMCSE} +{$ELSE} + {$Apptype console} +{$ENDIF} + +uses + sysutils;// TDatetime +const + nmax = 17; +type +{$IFNDEF FPC} + NativeInt = longInt; +{$ENDIF} + //ala Nikolaus Wirth A-1 = H - 8 + //diagonal left (A1) to rigth (H8) + tLR_diagonale = array[-nmax-1..nmax-1] of char; + //diagonal right (A8) to left (H1) + tRL_diagonale = array[0..2*nmax-2] of char; + //up to Col are the used Cols, after that the unused + tFreeCol = array[0..nmax-1] of nativeInt; +var + LR_diagonale:tLR_diagonale; + RL_diagonale:tRL_diagonale; + //Using pChar, cause it is implicit an array + //It is always set to + //@LR_diagonale[row] ,@RL_diagonale[row] + pLR,pRL : pChar; + FreeCol : tFreeCol; + i, + n : nativeInt; + gblCount : nativeUInt; + T0,T1 : TdateTime; +procedure Solution; +var + i : NativeInt; +begin +// Take's a lot of time under DOS/Win32 + If gblCount AND $FFF = 0 then + write(gblCount:10,#8#8#8#8#8#8#8#8#8#8); + // IF n< 9 then + IF n < 0 then + begin + For i := 1 to n do + write(FreeCol[i]:4); + writeln; + end; +end; + +procedure SetQueen(Row:nativeInt); +var + i,Col : nativeInt; +begin +IF row <= n then + begin + For i := row to n do + begin + Col := FreeCol[i]; + //check diagonals occupied + If (ORD(pLR[-Col]) AND ORD(pRL[Col]))<>0 then + begin + //a "free" position is found + //mark it + pRL[ Col]:=#0; //RL_Diagonale[ Row +Col] := 0; + pLR[-Col]:=#0; //LR_Diagonale[ Row -Col] := 0; + //swap FreeRow[Row<->i] + FreeCol[i] := FreeCol[Row]; + //next row + inc(pRL); + inc(pLR); + FreeCol[Row] := Col; + // check next row + SetQueen(Row+1); + //Undo + dec(pLR); + dec(pRL); + FreeCol[Row] := FreeCol[i]; + FreeCol[i] := Col; + pRL[ Col]:=#1; + pLR[-Col]:=#1; + end; + end; + end +else + begin + //solution ist found + inc(gblCount); + //Solution + end; +end; + +begin + For i := 0 to nmax-1 do + FreeCol[i] := i; + //diagonals filled with True = #1 , something <>0 + fillchar(LR_Diagonale[low(LR_Diagonale)],sizeof(tLR_Diagonale),#1); + fillchar(RL_Diagonale[low(RL_Diagonale)],sizeof(tRL_Diagonale),#1); + For n := 1 to nMax do + begin + t0 := time; + pLR:=@LR_Diagonale[0]; + pRL:=@RL_Diagonale[0]; + gblCount := 0; + SetQueen(1); + t1:= time; + WriteLn(n:6,gblCount:12,FormatDateTime(' NN:SS.ZZZ',T1-t0),' secs'); + end; + WriteLn('Fertig'); +end. diff --git a/Task/N-queens-problem/Python/n-queens-problem-7.py b/Task/N-queens-problem/Python/n-queens-problem-7.py index f7d7633fb1..f404b4c1dc 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-7.py +++ b/Task/N-queens-problem/Python/n-queens-problem-7.py @@ -1,23 +1,23 @@ -def queens(n): - a = list(range(n)) - up = [True]*(2*n - 1) - down = [True]*(2*n - 1) - def sub(i): - if i == n: - yield tuple(a) - else: +def queens(n: int): + + def sub(i: int): + if i < n: for k in range(i, n): j = a[k] - p = i + j - q = i - j + n - 1 - if up[p] and down[q]: - up[p] = down[q] = False + if b[i + j] and c[i - j]: a[i], a[k] = a[k], a[i] + b[i + j] = c[i - j] = False yield from sub(i + 1) - up[p] = down[q] = True + b[i + j] = c[i - j] = True a[i], a[k] = a[k], a[i] + else: + yield a + + a = list(range(n)) + b = [True] * (2 * n - 1) + c = [True] * (2 * n - 1) yield from sub(0) -#Count solutions for n=8: -sum(1 for p in queens(8)) + +sum(1 for p in queens(8)) # count solutions 92 diff --git a/Task/N-queens-problem/Python/n-queens-problem-8.py b/Task/N-queens-problem/Python/n-queens-problem-8.py index bf6b25cd22..3a6b107381 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-8.py +++ b/Task/N-queens-problem/Python/n-queens-problem-8.py @@ -1,31 +1,29 @@ -def queens_lex(n): - a = list(range(n)) - up = [True]*(2*n - 1) - down = [True]*(2*n - 1) - def sub(i): - if i == n: - yield tuple(a) - else: +def queens_lex(n: int): + + def sub(i: int): + if i < n: for k in range(i, n): + j = a[k] a[i], a[k] = a[k], a[i] - j = a[i] - p = i + j - q = i - j + n - 1 - if up[p] and down[q]: - up[p] = down[q] = False + if b[i + j] and c[i - j]: + b[i + j] = c[i - j] = False yield from sub(i + 1) - up[p] = down[q] = True - x = a[i] - for k in range(i + 1, n): - a[k - 1] = a[k] - a[n - 1] = x + b[i + j] = c[i - j] = True + a[i:(n - 1)], a[n - 1] = a[(i + 1):n], a[i] + else: + yield a + + a = list(range(n)) + b = [True] * (2 * n - 1) + c = [True] * (2 * n - 1) yield from sub(0) + next(queens(31)) -(0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20) +[0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20] next(queens_lex(31)) -(0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20) +[0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20] #Compare to A065188 #1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ... diff --git a/Task/N-queens-problem/Uiua/n-queens-problem.uiua b/Task/N-queens-problem/Uiua/n-queens-problem.uiua new file mode 100644 index 0000000000..2aa0c5ea4d --- /dev/null +++ b/Task/N-queens-problem/Uiua/n-queens-problem.uiua @@ -0,0 +1,4 @@ +N ← 8 +Good ← =1⧻◴[⧻◴⟜(∩(⧻◴)⊃+-⇡⧻.)⟜⧻] +⊙◌⍥(⊏⊚≡Good.☇1⊞⊂⇡,),[[]]N +≡(≡(/(⊂⊂)@|/⊂⍜(⊡|@Q◌):↯:@_)⊸⧻) diff --git a/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy b/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy new file mode 100644 index 0000000000..84baeb9cc1 --- /dev/null +++ b/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy @@ -0,0 +1,32 @@ +func$ encode n b . + if n = 0 + return "0" + . + while n <> 0 + r = n mod b + n = n div b + if r < 0 + n += 1 + r -= b + . + out$ = strchar (r + 48) & out$ + . + return out$ +. +func decode n$ b . + if n$ = "0" + return 0 + . + for c$ in strchars n$ + c = strcode c$ - 48 + tot = tot * b + c + . + return tot +. +proc test n b . . + h$ = encode n b + print n & " -> " & h$ & "_" & b & " -> " & decode h$ b +. +test 10 -2 +test 146 -3 +test 15 -10 diff --git a/Task/Nested-function/PL-M/nested-function.plm b/Task/Nested-function/PL-M/nested-function.plm new file mode 100644 index 0000000000..cc83a2961f --- /dev/null +++ b/Task/Nested-function/PL-M/nested-function.plm @@ -0,0 +1,74 @@ +100H: /* USE A NESTED PROCEDURE TO CONSTRUCT A STRING, UPDATING VARIABLES IN */ + /* THE CONTAINING PROCEDURE */ + + /* CP/M BDOS SYSTEM CALL */ + BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5;END; + /* CONSOLE OUTPUT ROUTINES */ + PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; + + /* CONCATENATES ITEM TO THE END OF STR. STR MUST BE LONG ENOUGH TO HOLD */ + /* THE CONCATENATED VALUE */ + CONCAT: PROCEDURE( STR, ITEM ); + DECLARE ( STR, ITEM ) ADDRESS; + + DECLARE STR$S BASED STR ( 0 )BYTE; + DECLARE ITEM$S BASED ITEM ( 0 )BYTE; + DECLARE ( STR$POS, ITEM$POS ) BYTE; + + /* FIND THE CURRENT END OF STR */ + STR$POS = 0; + DO WHILE STR$S( STR$POS ) <> '$'; + STR$POS = STR$POS + 1; + END; + + /* COPY ITEM TO THE END OF STR */ + ITEM$POS = 0; + DO WHILE ITEM$S( ITEM$POS ) <> '$'; + STR$S( STR$POS ) = ITEM$S( ITEM$POS ); + ITEM$POS = ITEM$POS + 1; + STR$POS = STR$POS + 1; + END; + STR$S( STR$POS ) = '$'; + + END CONCAT ; + + /* TASK */ + + /* RETURNS THE ADDRESS OF A STRING CONCATENATED FROM CALLS TO THE NESTED */ + /* MAKE$ITEM PROCEDURE - THE RESULTANT STRING MUST NOT BE MORE */ + /* THAN 64 CHARACTERS IN LENGTH */ + MAKE$LIST: PROCEDURE( SEPARATOR )ADDRESS; + DECLARE SEPARATOR ADDRESS; + + DECLARE LIST$VALUE ( 65 )BYTE; + DECLARE COUNTER BYTE; + + /* RETURNS THE ADDRESS OF A LIST ITEM, THE LENGTH OF THE ITEM MUST'NT */ + /* BE MORE THAN 32 CHARACTERS */ + MAKE$ITEM: PROCEDURE( ITEM )ADDRESS; + DECLARE ITEM ADDRESS; + + DECLARE LIST$ITEM ( 33 )BYTE; + + COUNTER = COUNTER + 1; + LIST$ITEM( 0 ) = '0' + COUNTER; + LIST$ITEM( 1 ) = '$'; + CALL CONCAT( .LIST$ITEM, SEPARATOR ); + CALL CONCAT( .LIST$ITEM, ITEM ); + CALL CONCAT( .LIST$ITEM, .( 0DH, 0AH, '$' ) ); + + RETURN .LIST$ITEM; + END MAKE$ITEM ; + + COUNTER = 0; + LIST$VALUE( 0 ) = '$'; + CALL CONCAT( .LISTVALUE, MAKE$ITEM( .'FIRST$' ) ); + CALL CONCAT( .LISTVALUE, MAKE$ITEM( .'SECOND$' ) ); + CALL CONCAT( .LISTVALUE, MAKE$ITEM( .'THIRD$' ) ); + + RETURN .LIST$VALUE; + END MAKE$LIST ; + + CALL PR$STRING( MAKE$LIST( .'. $' ) ); + +EOF diff --git a/Task/Nested-function/PascalABC.NET/nested-function.pas b/Task/Nested-function/PascalABC.NET/nested-function.pas new file mode 100644 index 0000000000..21f28104f2 --- /dev/null +++ b/Task/Nested-function/PascalABC.NET/nested-function.pas @@ -0,0 +1,21 @@ +procedure MakeList(separator: string); + var counter := 1; + procedure MakeItem; + begin + Write(counter, separator); + case counter of + 1: Writeln('first'); + 2: Writeln('second'); + 3: Writeln('third'); + end; + counter += 1; + end; +begin + MakeItem; + MakeItem; + MakeItem; +end; + +begin + MakeList('. '); +end. diff --git a/Task/Nested-templated-data/BASIC256/nested-templated-data.basic b/Task/Nested-templated-data/BASIC256/nested-templated-data.basic new file mode 100644 index 0000000000..cc817a033c --- /dev/null +++ b/Task/Nested-templated-data/BASIC256/nested-templated-data.basic @@ -0,0 +1,31 @@ +dim p(7) +dim p$(7) +p$[0] = "Payload#0" : p$[1] = "Payload#1" +p$[2] = "Payload#2" : p$[3] = "Payload#3" +p$[4] = "Payload#4" : p$[5] = "Payload#5" +p$[6] = "Payload#6" +dim q(7) fill false +dim t(4, 5) +t[0, 0] = 1: t[0, 1] = 2 +t[1, 0] = 3: t[1, 1] = 4: t[1, 2] = 1 +t[2, 0] = 5 + +for i = 0 to t[?][]-1 + for j = 0 to t[?][]-1 + if t[i, j] <> 0 then + q[t[i, j]] = true + t[i, j] += 1 + end if + next j +next i + +for i = 0 to t[?][]-1 + for j = 0 to t[?][]-1 + if t[i, j] <> 0 then print p$[t[i, j] -1]; " "; + next j + print +next i + +for i = 0 to q[?]-1 + if not q[i] then print p$[i]; " is not used" +next i diff --git a/Task/Nested-templated-data/Chipmunk-Basic/nested-templated-data.basic b/Task/Nested-templated-data/Chipmunk-Basic/nested-templated-data.basic new file mode 100644 index 0000000000..91dfaa29c1 --- /dev/null +++ b/Task/Nested-templated-data/Chipmunk-Basic/nested-templated-data.basic @@ -0,0 +1,30 @@ +100 cls +110 dim i,j,p(6) +120 dim p$(6) +130 p$(0) = "Payload#0" : p$(1) = "Payload#1" +140 p$(2) = "Payload#2" : p$(3) = "Payload#3" +150 p$(4) = "Payload#4" : p$(5) = "Payload#5" +160 p$(6) = "Payload#6" +170 dim q(6) +180 dim t(2,3) +190 t(0,0) = 1 : t(0,1) = 2 +200 t(1,0) = 3 : t(1,1) = 4 : t(1,2) = 1 +210 t(2,0) = 5 +220 for i = 0 to ubound(t) +230 for j = 0 to ubound(t,2) +240 if t(i,j) <> 0 then +250 q(t(i,j)) = true +260 t(i,j) = t(i,j)+1 +270 endif +280 next j +290 next i +300 for i = 0 to ubound(t) +310 for j = 0 to ubound(t,2) +320 if t(i,j) <> 0 then print p$(t(i,j)-1);" "; +330 next j +340 print +350 next i +360 for i = 0 to ubound(q) +370 if not q(i) then print p$(i);" is not used" +380 next i +390 end diff --git a/Task/Nested-templated-data/FreeBASIC/nested-templated-data.basic b/Task/Nested-templated-data/FreeBASIC/nested-templated-data.basic new file mode 100644 index 0000000000..c94e716a0c --- /dev/null +++ b/Task/Nested-templated-data/FreeBASIC/nested-templated-data.basic @@ -0,0 +1,26 @@ +Dim As Integer t(2, 3) = {{1,2},{3,4,1},{5}} +Dim As Integer i, j, p(6) +Dim As String pStr(6) = {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"} +Dim As Boolean q(6) + +For i = Lbound(t) To Ubound(t) + For j = Lbound(t, 2) To Ubound(t, 2) + If t(i, j) <> 0 Then + q(t(i, j)) = True + t(i, j) += 1 + End If + Next j +Next i + +For i = Lbound(t) To Ubound(t) + For j = Lbound(t, 2) To Ubound(t, 2) + If t(i, j) <> 0 Then Print pStr(t(i, j)-1); " "; + Next j + Print +Next i + +For i = Lbound(q) To Ubound(q) + If q(i) = False Then Print pStr(i); " is not used" +Next i + +Sleep diff --git a/Task/Nested-templated-data/GW-BASIC/nested-templated-data.basic b/Task/Nested-templated-data/GW-BASIC/nested-templated-data.basic new file mode 100644 index 0000000000..eb52047593 --- /dev/null +++ b/Task/Nested-templated-data/GW-BASIC/nested-templated-data.basic @@ -0,0 +1,28 @@ +110 TRUE = -1 +120 FALSE = NOT TRUE +130 DIM I,J,P(6) +140 DIM P$(6) +150 P$(0) = "Payload#0" : P$(1) = "Payload#1" +160 P$(2) = "Payload#2" : P$(3) = "Payload#3" +170 P$(4) = "Payload#4" : P$(5) = "Payload#5" +180 P$(6) = "Payload#6" +190 DIM Q(6) +200 DIM T(2,3) +210 T(0,0) = 1 : T(0,1) = 2 +220 T(1,0) = 3 : T(1,1) = 4 : T(1,2) = 1 +230 T(2,0) = 5 +240 FOR I = 0 TO 2 +250 FOR J = 0 TO 3 +260 IF T(I,J) <> 0 THEN Q(T(I,J)) = TRUE : T(I,J) = T(I,J)+1 +270 NEXT J +280 NEXT I +290 FOR I = 0 TO 2 +300 FOR J = 0 TO 3 +310 IF T(I,J) <> 0 THEN PRINT P$(T(I,J)-1);" "; +320 NEXT J +330 PRINT +340 NEXT I +350 FOR I = 0 TO 6 +360 IF Q(I) = FALSE THEN PRINT P$(I);" is not used" +370 NEXT I +380 END diff --git a/Task/Nested-templated-data/QBasic/nested-templated-data.basic b/Task/Nested-templated-data/QBasic/nested-templated-data.basic new file mode 100644 index 0000000000..e83933c6ab --- /dev/null +++ b/Task/Nested-templated-data/QBasic/nested-templated-data.basic @@ -0,0 +1,33 @@ +True = -1: False = NOT True + +DIM p(6) +DIM p$(6) +p$(0) = "Payload#0": p$(1) = "Payload#1" +p$(2) = "Payload#2": p$(3) = "Payload#3" +p$(4) = "Payload#4": p$(5) = "Payload#5" +p$(6) = "Payload#6" +DIM q(6) +DIM t(2, 3) +t(0, 0) = 1: t(0, 1) = 2 +t(1, 0) = 3: t(1, 1) = 4: t(1, 2) = 1 +t(2, 0) = 5 + +FOR i = LBOUND(t) TO UBOUND(t) '0 To 2 + FOR j = LBOUND(t, 2) TO UBOUND(t, 2) '0 To 3 + IF t(i, j) <> 0 THEN + q(t(i, j)) = True + t(i, j) = t(i, j) + 1 + END IF + NEXT j +NEXT i + +FOR i = LBOUND(t) TO UBOUND(t) '0 To 2 + FOR j = LBOUND(t, 2) TO UBOUND(t, 2) '0 To 3 + IF t(i, j) <> 0 THEN PRINT p$(t(i, j) - 1); " "; + NEXT j + PRINT +NEXT i + +FOR i = LBOUND(q) TO UBOUND(q) + IF q(i) = False THEN PRINT p$(i); " is not used" +NEXT i diff --git a/Task/Nested-templated-data/Refal/nested-templated-data.refal b/Task/Nested-templated-data/Refal/nested-templated-data.refal new file mode 100644 index 0000000000..da9645d26d --- /dev/null +++ b/Task/Nested-templated-data/Refal/nested-templated-data.refal @@ -0,0 +1,17 @@ +$ENTRY Go { + , (((1 2) (3 4 1) 5)): e.Template + , "Payload#0" "Payload#1" "Payload#2" "Payload#3" + "Payload#4" "Payload#5" "Payload#6": e.Payload + = >; +}; + +Subst { + (e.P) = ; + (e.P) s.I e.X = ; + (e.P) (e.X) e.Y = () ; +}; + +Item { + 0 t.I e.X = t.I; + s.N t.I e.X = e.X>; +}; diff --git a/Task/Nested-templated-data/Run-BASIC/nested-templated-data.basic b/Task/Nested-templated-data/Run-BASIC/nested-templated-data.basic new file mode 100644 index 0000000000..90a2d37d4c --- /dev/null +++ b/Task/Nested-templated-data/Run-BASIC/nested-templated-data.basic @@ -0,0 +1,31 @@ +DIM p(6) +DIM p$(6) +p$(0) = "Payload#0": p$(1) = "Payload#1" +p$(2) = "Payload#2": p$(3) = "Payload#3" +p$(4) = "Payload#4": p$(5) = "Payload#5" +p$(6) = "Payload#6" +DIM q(6) +DIM t(2, 3) +t(0, 0) = 1: t(0, 1) = 2 +t(1, 0) = 3: t(1, 1) = 4: t(1, 2) = 1 +t(2, 0) = 5 + +FOR i = 0 TO 2 + FOR j = 0 TO 3 + IF t(i, j) <> 0 THEN + q(t(i, j)) = -1 + t(i, j) = t(i, j) + 1 + END IF + NEXT j +NEXT i + +FOR i = 0 TO 2 + FOR j = 0 TO 3 + IF t(i, j) <> 0 THEN PRINT p$(t(i, j) - 1); " "; + NEXT j + PRINT +NEXT i + +FOR i = 0 TO 6 + IF q(i) = 0 THEN PRINT p$(i); " is not used" +NEXT i diff --git a/Task/Nested-templated-data/SETL/nested-templated-data.setl b/Task/Nested-templated-data/SETL/nested-templated-data.setl new file mode 100644 index 0000000000..eded655838 --- /dev/null +++ b/Task/Nested-templated-data/SETL/nested-templated-data.setl @@ -0,0 +1,21 @@ +program substitution; + template := [[[1,2],[3,4,1],5]]; + payload := { + [0,"Payload#0"], [1,"Payload#1"], [2,"Payload#2"], [3,"Payload#3"], + [4,"Payload#4"], [5,"Payload#5"], [6,"Payload#6"] + }; + + print(subst(template, payload)); + + proc subst(template, payload); + if not is_tuple(template) then + return(payload(template)); + end if; + + result := []; + loop for item in template do + result with:= subst(item, payload); + end loop; + return result; + end proc; +end program; diff --git a/Task/Nested-templated-data/Yabasic/nested-templated-data.basic b/Task/Nested-templated-data/Yabasic/nested-templated-data.basic new file mode 100644 index 0000000000..192fdfb647 --- /dev/null +++ b/Task/Nested-templated-data/Yabasic/nested-templated-data.basic @@ -0,0 +1,31 @@ +dim p(6) +dim p$(6) +p$(0) = "Payload#0" : p$(1) = "Payload#1" +p$(2) = "Payload#2" : p$(3) = "Payload#3" +p$(4) = "Payload#4" : p$(5) = "Payload#5" +p$(6) = "Payload#6" +dim q(6) +dim t(2, 3) +t(0, 0) = 1: t(0, 1) = 2 +t(1, 0) = 3: t(1, 1) = 4: t(1, 2) = 1 +t(2, 0) = 5 + +for i = 0 to arraysize(t(), 1) + for j = 0 to arraysize(t(), 2) + if t(i, j) <> 0 then + q(t(i, j)) = True + t(i, j) = t(i, j) + 1 + fi + next j +next i + +for i = 0 to arraysize(t(), 1) + for j = 0 to arraysize(t(), 2) + if t(i, j) <> 0 print p$(t(i, j) -1), " "; + next j + print +next i + +for i = 0 to arraysize(q(), 1) + if not q(i) print p$(i), " is not used" +next i diff --git a/Task/Next-highest-int-from-digits/00-TASK.txt b/Task/Next-highest-int-from-digits/00-TASK.txt index 453d8b629c..0af8f68359 100644 --- a/Task/Next-highest-int-from-digits/00-TASK.txt +++ b/Task/Next-highest-int-from-digits/00-TASK.txt @@ -1,5 +1,4 @@ -Given a zero or positive integer, the task is to generate the next largest -integer using only the given digits*1. +Given a zero or positive integer, the task is to generate the next largest integer with the same digits*1. *   Numbers will not be padded to the left with zeroes. *   Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result). @@ -22,8 +21,8 @@ digits, but should be easy to reason about its correctness. ;Algorithm 2: #   Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it. -#   Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it. -#   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation) +#   Exchange that digit with the smallest digit on the right that is greater than it. +#   Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (that is, so they form the lowest numerical representation) '''E.g.:''' @@ -47,7 +46,7 @@ algorithms for random numbers generated from a range that the first algorithm ca ;Task requirements: -Calculate the next highest int from the digits of the following numbers: +Calculate the next highest integer from the digits of the following numbers: :*   0 :*   9 :*   12 diff --git a/Task/Next-highest-int-from-digits/Ada/next-highest-int-from-digits.ada b/Task/Next-highest-int-from-digits/Ada/next-highest-int-from-digits.ada new file mode 100644 index 0000000000..38a3d3b97f --- /dev/null +++ b/Task/Next-highest-int-from-digits/Ada/next-highest-int-from-digits.ada @@ -0,0 +1,125 @@ +-- Next highest integer with same digits +-- J. Carter 2024 June +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Permutations; +with PragmARC.Sorting.Insertion; + +procedure Next_Highest is + package Permutations is new PragmARC.Permutations (Element => Character); + procedure Sort is new PragmARC.Sorting.Insertion (Element => Character, Index => Positive, Sort_Set => String); + + subtype Digit is Character range '0' .. '9'; + + function Valid (S : in String) return Boolean is + (S'First = 1 and S'Length > 0 and (for all C of S => C in Digit) ); + + function Next_P (Value : in String) return String with + Pre => Valid (Value); + -- Returns the smallest integer > Value that can be produced from Value's decimal digits, using permutations + -- Returns zero if there is no such integer + + function Next_S (Value : in String) return String with + Pre => Valid (Value); + -- Returns the smallest integer > Value that can be produced from Value's decimal digits, using the Scan, Sort, Scan, and Swap + -- (SSSS) algorithm + -- Returns zero if there is no such integer + + function Next_P (Value : in String) return String is + procedure Check (Image : in Permutations.Sequence; Stop : in out Boolean); + -- Checks if Image represents an integer > Value and smaller than Smallest + -- If so, sets Found to True and Smallest to the represented value + + Found : Boolean := False; + Smallest : String := (Value'Range => '9'); + + procedure Check (Image : in Permutations.Sequence; Stop : in out Boolean) is + Number : constant String := String (Image); + begin -- Check + if Number > Value then + Found := True; + Smallest := (if Number < Smallest then Number else Smallest); + end if; + end Check; + begin -- Next_P + if Value'Length < 2 or (Value'Length = 2 and Value < "12") then + return "0"; + end if; + + Permutations.Generate (Initial => Permutations.Sequence (Value), Process => Check'Access); + + return (if Found then Smallest else "0"); + end Next_P; + + function Next_S (Value : in String) return String is + Work : String := Value; + Found : Boolean := False; + Lower : Positive; + Higher : Positive; + begin -- Next_S + Scan_Lower : for I in reverse 1 .. Work'Last - 1 loop + if (for some C of Work (I + 1 .. Work'Last) => Work (I) < C) then + Found := True; + Lower := I; + + exit Scan_Lower; + end if; + end loop Scan_Lower; + + if not Found then + return "0"; + end if; + + Sort (Set => Work (Lower + 1 .. Work'Last) ); + + Scan_Higher : for I in Lower + 1 .. Work'Last loop -- The Found test above ensures that this will always assign to Higher + if Work (I) > Work (Lower) then + Higher := I; + + exit Scan_Higher; + end if; + end loop Scan_Higher; + + Swap : declare + Temp : constant Character := Work (Lower); + begin -- Swap + Work (Lower) := Work (Higher); + Work (Higher) := Temp; + end Swap; + + return Work; + end Next_S; + + Test_1 : constant String := "0"; + Test_2 : constant String := "9"; + Test_3 : constant String := "12"; + Test_4 : constant String := "21"; + Test_5 : constant String := "12453"; + Test_6 : constant String := "738440"; + Test_7 : constant String := "45072010"; + Test_8 : constant String := "95322020"; + Stretch : constant String := "9589776899767587796600"; +begin -- Next_Highest + Ada.Text_IO.Put_Line (Item => "Using permutations"); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_1'Length => ' ') & Test_1 & ' ' & Next_P (Test_1) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_2'Length => ' ') & Test_2 & ' ' & Next_P (Test_2) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_3'Length => ' ') & Test_3 & ' ' & Next_P (Test_3) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_4'Length => ' ') & Test_4 & ' ' & Next_P (Test_4) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_5'Length => ' ') & Test_5 & ' ' & Next_P (Test_5) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_6'Length => ' ') & Test_6 & ' ' & Next_P (Test_6) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_7'Length => ' ') & Test_7 & ' ' & Next_P (Test_7) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_8'Length => ' ') & Test_8 & ' ' & Next_P (Test_8) ); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (Item => "Using SSSS"); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_1'Length => ' ') & Test_1 & ' ' & Next_S (Test_1) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_2'Length => ' ') & Test_2 & ' ' & Next_S (Test_2) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_3'Length => ' ') & Test_3 & ' ' & Next_S (Test_3) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_4'Length => ' ') & Test_4 & ' ' & Next_S (Test_4) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_5'Length => ' ') & Test_5 & ' ' & Next_S (Test_5) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_6'Length => ' ') & Test_6 & ' ' & Next_S (Test_6) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_7'Length => ' ') & Test_7 & ' ' & Next_S (Test_7) ); + Ada.Text_IO.Put_Line (Item => (1 .. 8 - Test_8'Length => ' ') & Test_8 & ' ' & Next_S (Test_8) ); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (Item => Stretch & ' ' & Next_S (Stretch) ); +end Next_Highest; diff --git a/Task/Next-highest-int-from-digits/Phix/next-highest-int-from-digits-1.phix b/Task/Next-highest-int-from-digits/Phix/next-highest-int-from-digits-1.phix index 3d27d9f2ac..9db8b8ed6f 100644 --- a/Task/Next-highest-int-from-digits/Phix/next-highest-int-from-digits-1.phix +++ b/Task/Next-highest-int-from-digits/Phix/next-highest-int-from-digits-1.phix @@ -1,21 +1,19 @@ -(phixonline)--> - function nigh(string n) - sequence p = repeat("",factorial(length(n))) - for i=1 to length(p) do - p[i] = permute(i,n) - end for - p = sort(p) - integer k = rfind(n,p) - return iff(k=length(p)?"0",p[k+1]) - end function +function nigh(string n) + sequence p = repeat("",factorial(length(n))) + for i=1 to length(p) do + p[i] = permute(i,n) + end for + p = sort(p) + integer k = rfind(n,p) + return iff(k=length(p)?"0",p[k+1]) +end function - constant tests = {"0","9","12","21","12453", - "738440","45072010","95322020"} - -- (crashes on) "9589776899767587796600"} - atom t0 = time() - for i=1 to length(tests) do - string t = tests[i] - printf(1,"%22s => %s\n",{t,nigh(t)}) - end for - ?elapsed(time()-t0) - - function nigh(string n) - integer hi = n[$] - for i=length(n)-1 to 1 by -1 do - integer ni = n[i] - if ni<hi then - string sr = sort(n[i..$]) - integer k = rfind(ni,sr)+1 - n[i] = sr[k] - sr[k..k] = "" - n[i+1..$] = sr - return n - end if - hi = max(hi,ni) - end for - return "0" - end function +function nigh(string n) + integer hi = n[$] + for i=length(n)-1 to 1 by -1 do + integer ni = n[i] + if niconstant tests = {"0","9","12","21","12453", - "738440","45072010","95322020", - "9589776899767587796600"} - atom t0 = time() - for i=1 to length(tests) do - string t = tests[i] - printf(1,"%22s => %s\n",{t,nigh(t)}) - end for - ?elapsed(time()-t0) - - -- - -- demo\rosetta\Ormiston_triplets.exw - -- ================================== - -- - -- Uses a segmented sieve, which is about half the speed of get_primes_le(), but uses far less memory. - -- If permited, get_primes_le(1e10) would generate a result of 455,052,511 primes, more than 32 bit - -- can cope with, and use over 6GB of ram, and take about 11mins 44s, that is on this box at least, - -- whereas this processes them on-the-fly, and only uses about 6MB of memory (ie 0.1% of 6GB). - -- - with javascript_semantics +-- +-- demo\rosetta\Ormiston_triplets.exw +-- ================================== +-- +-- Uses a segmented sieve, which is about half the speed of get_primes_le(), but uses far less memory. +-- If permited, get_primes_le(1e10) would generate a result of 455,052,511 primes, more than 32 bit +-- can cope with, and use over 6GB of ram, and take about 11mins 44s, that is on this box at least, +-- whereas this processes them on-the-fly, and only uses about 6MB of memory (ie 0.1% of 6GB). +-- +with javascript_semantics - atom t0 = time() +atom t0 = time() - procedure ormiston_triplets(atom limit) - // Generate primes using the segmented sieve of Eratosthenes. - // credit: https://gist.github.com/kimwalisch/3dc39786fab8d5b34fee - integer segment_size = floor(sqrt(limit)), - count = 0, i = 3, s = 3, triplen = 1 - atom p1 = 2, p2, n = 3, nc = min(1e9,limit), low = 0, t1 = time()+1 +procedure ormiston_triplets(atom limit) + // Generate primes using the segmented sieve of Eratosthenes. + // credit: https://gist.github.com/kimwalisch/3dc39786fab8d5b34fee + integer segment_size = floor(sqrt(limit)), + count = 0, i = 3, s = 3, triplen = 1 + atom p1 = 2, p2, n = 3, nc = min(1e9,limit), low = 0, t1 = time()+1 - sequence isprime = repeat(true,segment_size+1), - primes = {}, - multiples = {}, - orm25 = repeat(0,25) + sequence isprime = repeat(true,segment_size+1), + primes = {}, + multiples = {}, + orm25 = repeat(0,25) - while low<=limit do - sequence sieve = repeat(true,segment_size+1) - if time()>t1 then - progress("Processing %,d/%,d (%3.2f%%)\r",{low,limit,(low/limit)*100}) - t1 = time()+1 - end if + while low<=limit do + sequence sieve = repeat(true,segment_size+1) + if time()>t1 then + progress("Processing %,d/%,d (%3.2f%%)\r",{low,limit,(low/limit)*100}) + t1 = time()+1 + end if - // current segment = [low, high] - atom high = min(low+segment_size,limit) - // generate sieving primes using simple sieve of Eratosthenes - while i*i<=min(high,segment_size) do - if isprime[i+1] then - for j=i*i to segment_size by i do - isprime[j+1] = false - end for - end if - i += 2 - end while + // current segment = [low, high] + atom high = min(low+segment_size,limit) + // generate sieving primes using simple sieve of Eratosthenes + while i*i<=min(high,segment_size) do + if isprime[i+1] then + for j=i*i to segment_size by i do + isprime[j+1] = false + end for + end if + i += 2 + end while - // initialize sieving primes for segmented sieve - while s*s<=high do - if isprime[s+1] then - primes &= s - multiples &= s*s-low - end if - s += 2 - end while + // initialize sieving primes for segmented sieve + while s*s<=high do + if isprime[s+1] then + primes &= s + multiples &= s*s-low + end if + s += 2 + end while - // sieve the current segment - for mi,j in multiples do - integer k = primes[mi]*2 - while j<segment_size do - sieve[j+1] = false - j += k - end while - multiples[mi] = j - segment_size - end for + // sieve the current segment + for mi,j in multiples do + integer k = primes[mi]*2 + while jwhile n<=high do - if sieve[n-low+1] then // n is a prime - if triplen=1 then - if remainder(n-p1,18)=0 - and sort(sprint(p1))=sort(sprint(n)) then - p2 = n - triplen = 2 - else - p1 = n - end if - elsif triplen=2 - and remainder(n-p2,18)=0 - and sort(sprint(p2))=sort(sprint(n)) then - -- triplet found! - if p1>=nc then - string e = elapsed_short(time()-t0) - progress("%,d Ormiston triplets before %,d (%s)\n", {count, nc, e}) - nc *= 10 - end if - count += 1 - if count<=25 then - orm25[count] = sprintf("%d",{p1}) - if count=25 then - printf(1,"Smallest members of first 25 Ormiston triplets:\n%s\n",join_by(orm25,1,5)) - end if - end if - -- overlapping (and leave triplen set to 2): - p1 = p2 - p2 = n - -- (for disjoint-only just set triplen to 0) - else - p1 = n - triplen = 1 - end if - end if - n += 2 - end while - low += segment_size - end while - string e = elapsed_short(time()-t0) - progress("%,d Ormiston triplets before %,d (%s)\n", {count, nc, e}) - end procedure - ormiston_triplets(iff(platform()=JS?1e8:1e9)) - - requires("1.0.3") - requires(WINDOWS) - requires(64,true) - include builtins/primesieve.e - atom t0 = time(), t1 = time()+1, - p = primesieve_next_prime(), - p1 = p, p2, count = 0, nc = 1e9 - sequence orm25 = repeat(0,25) +requires("1.0.3") +requires(WINDOWS) +requires(64,true) +include builtins/primesieve.e +atom t0 = time(), t1 = time()+1, + p = primesieve_next_prime(), + p1 = p, p2, count = 0, nc = 1e9 +sequence orm25 = repeat(0,25) - procedure showt() - if count=25 then - progress("Smallest members of first 25 Ormiston triplets:\n") - progress("%s\n",join_by(orm25,1,5)) - else - string e = elapsed_short(time()-t0) - progress("%,6d Ormiston triplets before %,d (%s)\n",{count,nc,e}) - nc *= 10 - end if - end procedure +procedure showt() + if count=25 then + progress("Smallest members of first 25 Ormiston triplets:\n") + progress("%s\n",join_by(orm25,1,5)) + else + string e = elapsed_short(time()-t0) + progress("%,6d Ormiston triplets before %,d (%s)\n",{count,nc,e}) + nc *= 10 + end if +end procedure - while p<1e10 do - p2 = p1 - p1 = p - p = primesieve_next_prime() - if remainder(p-p1,18)=0 - and remainder(p1-p2,18)=0 then - string s = sort(sprint(p)) - if sort(sprint(p1))=s - and sort(sprint(p2))=s then - if p>=nc then showt() end if - count += 1 - if count<=25 then - orm25[count] = sprintf("%d",{p2}) - if count=25 then showt() end if - end if - end if - elsif time()>t1 then - progress("%,d\r",{p}) - t1 = time()+1 - end if - end while - showt() - [ ) + + [ char a char z range ] constant is lowers ( --> $ ) + + [ char A char Z range ] constant is uppers ( --> $ ) + + [ char 0 char 9 range ] constant is digits ( --> $ ) + + [ $ \!"#$%&'()*+,-./:;<=>?@[]^_{|}~\ ] is others ( --> $ ) + + [ [] ' [ lowers uppers digits others ] + tuck witheach + [ do dup size random peek join ] + [] rot witheach [ do join ] + rot 4 - times + [ dup dup size random peek + rot join swap ] + drop shuffle ] is password ( n --> $ ) + + [ swap times + [ dup password echo$ cr ] drop ] is passwords ( n n --> ) + + [ say "'passwords' generates a specified" cr + say "number of passwords of a specified" cr + say "length. For example," cr + cr + say " 5 10 passwords" cr + cr + say "will generate five ten-character" cr + say "passwords." cr ] is help + + say "Type 'help' for help with passwords." diff --git a/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy new file mode 100644 index 0000000000..cc6ad6edbf --- /dev/null +++ b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy @@ -0,0 +1,51 @@ +numfmt 10 0 +proc task1 . . + print "--- Task 1 pathologic ---" + vpp = 2 + vp = -4 + for i = 3 to 100 + v = 111 - 1130 / vp + 3000 / (vp * vpp) + if i <= 8 or i = 20 or i = 30 or i = 50 or i = 100 + print i & ": " & v + . + vpp = vp + vp = v + . +. +task1 +print "" +# +proc task2 . . + print "--- Task 2 pathologic ---" + e = 2.718281828459045 + bal = e - 1 + for i = 1 to 25 + bal = bal * i - 1 + . + print "Balance after 25 years: $" & bal +. +task2 +print "" +# +proc mul f . bal bal$[] . + for i = len bal$[] downto 1 + dig = number bal$[i] + h = dig * f + c + bal$[i] = h mod 10 + c = h div 10 + . + bal += c +. +proc task2ok . . + print "--- Task 2 OK ---" + e$ = "2.7182818284590452353602874713526624977572470" + bal = number substr e$ 1 1 + bal$[] = strchars substr e$ 3 999 + bal -= 1 + for i = 1 to 25 + mul i bal bal$[] + bal -= 1 + . + print "Balance after 25 years: $" & bal & "." & substr strjoin bal$[] 1 16 +. +task2ok diff --git a/Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq b/Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq new file mode 100644 index 0000000000..0cde59231c --- /dev/null +++ b/Task/Peaceful-chess-queen-armies/Jq/peaceful-chess-queen-armies.jq @@ -0,0 +1,81 @@ +# Is the queen at position . attacking the position $pos ? +def isAttacking($pos): + .x == $pos.x or + .y == $pos.y or + (((.x - $pos.x)|length) == ((.y - $pos.y)|length)); # i.e. abs + +# Place $q black and $q white queens on an $n*$n board, +# where .blackQueens holds the positions of existing black Queens, +# and similarly for .whiteQueens. +# input: {blackQueens, whiteQueens} +# output: updated input on success, otherwise null. +def place($queens; $n): + def place($q): + if $q == 0 then .ok = true + else .placingBlack = true + | first( + foreach range(0; $n) as $i (.; + foreach range(0; $n) as $j (.; + {x:$i, y:$j} as $pos + | .placingBlack as $placingBlack + | if any( .blackQueens[], .whiteQueens[]; + ((.x == $pos.x) and (.y == $pos.y))) + then . # failure + elif .placingBlack + then if any( .whiteQueens[]; isAttacking($pos) ) + then . + else .blackQueens += [$pos] + | .placingBlack = false + end + elif any( .blackQueens[]; isAttacking($pos) ) + then . + else .whiteQueens += [$pos] + | place($q-1) as $place + | if $place then $place # success + else .blackQueens |= .[:-1] + | .whiteQueens |= .[:-1] + | .placingBlack = true + end + end + | if $i == $n-1 and $j == $n-1 then .ok = false end ); + select(.ok) ) + ) // null + end; + {blackQueens: [], whiteQueens: [] } | place($queens); + +# Input {blackQueens, whiteQueens} +def printBoard($n): + [range(0; $n) | 0] as $row + | .board = [range(0; $n) | $row] + | reduce .blackQueens[] as $queen (.; .board[$queen.x][$queen.y] = "B ") + | reduce .whiteQueens[] as $queen (.; .board[$queen.x][$queen.y] = "W ") + | foreach range(0; $n) as $i (.; + reduce range(0; $n) as $j (.row=""; + .board[$i][$j] as $b + | .row += + (if $b != 0 then $b + elif $i%2 == $j%2 + then "• " + else "◦ " + end) ) ) + | .row; + +# Use an object {squares, queens} to record the task: +# $squares is the number of squares on each side of the board, +# and $queens is the number of queens of each color. +def Task($squares; $queens): {$squares, $queens}; + +def tasks: [ + Task(2; 1), Task(3; 1), Task(3; 2), Task(4; 1), Task(4; 2), Task(4; 3), + Task(5; 1), Task(5; 2), Task(5; 3), Task(5; 4), Task(5; 5), + Task(6; 1), Task(6; 2), Task(6; 3), Task(6; 4), Task(6; 5), Task(6; 6), + Task(7; 1), Task(7; 2), Task(7; 3), Task(7; 4), Task(7; 5), Task(7; 6), Task(7; 7) +]; + +tasks[] as $t +| "\($t.queens) black and \($t.queens) white queens on a \($t.squares) x \($t.squares) board:", + ((place($t.queens; $t.squares) + | select(.) + | printBoard($t.squares)) + // "No solution exists."), + "" diff --git a/Task/Pells-equation/Langur/pells-equation.langur b/Task/Pells-equation/Langur/pells-equation.langur index c2e101a25d..ec0697af10 100644 --- a/Task/Pells-equation/Langur/pells-equation.langur +++ b/Task/Pells-equation/Langur/pells-equation.langur @@ -1,31 +1,31 @@ -val .fun = fn(.a, .b, .c) [.b, .b * .c + .a] +val fun = fn a, b, c: [b, b * c + a] -val .solvePell = fn(.n) { - val .x = trunc .n ^/ 2 - var .y, .z, .r = .x, 1, .x * 2 - var .e1, .e2, .f1, .f2 = 1, 0, 0, 1 +val solvePell = fn(n) { + val x = trunc(n ^/ 2) + var y, z, r = x, 1, x * 2 + var e1, e2, f1, f2 = 1, 0, 0, 1 for { - .y = .r * .z - .y - .z = (.n - .y * .y) \ .z - .r = (.x + .y) \ .z - .e1, .e2 = .fun(.e1, .e2, .r) - .f1, .f2 = .fun(.f1, .f2, .r) - val .b, .a = .fun(.e2, .f2, .x) - if .a^2 - .n * .b^2 == 1: return [.a, .b] + y = r * z - y + z = (n - y * y) \ z + r = (x + y) \ z + e1, e2 = fun(e1, e2, r) + f1, f2 = fun(f1, f2, r) + val b, a = fun(e2, f2, x) + if a^2 - n * b^2 == 1: return [a, b] } } -val .C = fn(.x) { +val C = fn(x) { # format number string with commas - var .neg, .s = "", string .x - if .s[1] == '-' { - .neg, .s = "-", rest .s + var neg, s = "", x -> string + if s[1] == '-' { + neg, s = "-", s -> rest } - .neg ~ join ",", split -3, .s + neg ~ join(",", split(-3, s)) } -for .n in [61, 109, 181, 277, 8941] { - val .x, .y = .solvePell(.n) - writeln $"x² - \.n;y² = 1 for:\n\tx = \.x:.C;\n\ty = \.y:.C;\n" +for n in [61, 109, 181, 277, 8941] { + val x, y = solvePell(n) + writeln "x² - {{n}}y² = 1 for:\n\tx = {{x:fn C}}\n\ty = {{y:fn C}}\n" } diff --git a/Task/Penneys-game/Ada/penneys-game.ada b/Task/Penneys-game/Ada/penneys-game.ada new file mode 100644 index 0000000000..ba8ce593b0 --- /dev/null +++ b/Task/Penneys-game/Ada/penneys-game.ada @@ -0,0 +1,102 @@ +-- Penney's game +-- J. Carter 2024 Jun + +with Ada.Characters.Handling; +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; + +procedure Penney_Game is + package Random is new Ada.Numerics.Discrete_Random (Result_Subtype => Boolean); + + type Choice_List is array (1 .. 3) of Boolean; + + procedure Get (List : out Choice_List); + -- Gets the player's choice + + procedure Put (Bool : in Boolean); + -- Puts False => 'T', True => 'H' + + procedure Put (List : in Choice_List); + -- Outputs a choice + + type Optimum_Map is array (Boolean, Boolean, Boolean) of Choice_List; + + Optimum : constant Optimum_Map := + (False => (False => (False => (True, False, False), True => (True, False, False) ), + True => (False => (False, False, True), True => (False, False, True) ) ), + True => (False => (False => (True, True, False), True => (True, True, False) ), + True => (False => (False, True, True), True => (False, True, True) ) ) ); + + procedure Get (List : out Choice_List) is + -- Empty + begin -- Get + All_Tries : loop + Ada.Text_IO.Put (Item => "Enter your sequence as three letters, H or T: "); + + One_Try : declare + Line : constant String := Ada.Characters.Handling.To_Upper (Ada.Text_IO.Get_Line); + begin -- One_Try + if Line'Length = 3 and (for all C of Line => C in 'H' |'T') then + Convert : for I in List'Range loop + List (I) := Line (I) = 'H'; + end loop Convert; + + return; + end if; + end One_Try; + end loop All_Tries; + end Get; + + procedure Put (Bool : in Boolean) is + -- Empty + begin -- Put + Ada.Text_IO.Put (Item => (if Bool then 'H' else 'T') ); + end Put; + + procedure Put (List : in Choice_List) is + -- Empty + begin -- Put + Put_All : for B of List loop + Put (Bool => B); + end loop Put_All; + end Put; + + Gen : Random.Generator; + Play_First : Boolean; + Comp_Choice : Choice_List; + Play_Choice : Choice_List; + Actual : Choice_List; +begin -- Penney_Game + Random.Reset (Gen => Gen); + Play_First := Random.Random (Gen); + + if Play_First then + Get (List => Play_Choice); + Comp_Choice := Optimum (Play_Choice (1), Play_Choice (2), Play_Choice (3) ); + else + Comp_Choice := (others => Random.Random (Gen) ); + end if; + + Ada.Text_IO.Put (Item => "Computer's sequence is "); + Put (List => Comp_Choice); + Ada.Text_IO.New_Line; + + if not Play_First then + Get (List => Play_Choice); + end if; + + Actual := (others => Random.Random (Gen) ); + Put (List => Actual); + + Check : loop + if Actual = Comp_Choice or Actual = Play_Choice then + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (Item => (if Actual = Comp_Choice then "Computer" else "Player") & " wins"); + + return; + end if; + + Actual := Actual (2 .. 3) & Random.Random (Gen); + Put (Bool => Actual (3) ); + end loop Check; +end Penney_Game; diff --git a/Task/Pentomino-tiling/Jq/pentomino-tiling.jq b/Task/Pentomino-tiling/Jq/pentomino-tiling.jq new file mode 100644 index 0000000000..a9d861e9cd --- /dev/null +++ b/Task/Pentomino-tiling/Jq/pentomino-tiling.jq @@ -0,0 +1,178 @@ +# Output: a PRN in range(0; .) +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +### Generic functions + +def array($n): . as $in | [range(0;$n)|$in]; + +def array_swap($i; $j): + if $i < $j then array_swap($j;$i) + elif $i == $j then . + else .[$i] as $t | .[:$j] + [$t] + .[$j:$i] + .[$i + 1:] + end ; + +### Pentominos + +def F: [ + [1, -1, 1, 0, 1, 1, 2, 1], [0, 1, 1, -1, 1, 0, 2, 0], + [1, 0, 1, 1, 1, 2, 2, 1], [1, 0, 1, 1, 2, -1, 2, 0], + [1, -2, 1, -1, 1, 0, 2, -1], [0, 1, 1, 1, 1, 2, 2, 1], + [1, -1, 1, 0, 1, 1, 2, -1], [1, -1, 1, 0, 2, 0, 2, 1] +]; + +def I: [ + [0, 1, 0, 2, 0, 3, 0, 4], [1, 0, 2, 0, 3, 0, 4, 0] +]; + +def L: [ + [1, 0, 1, 1, 1, 2, 1, 3], [1, 0, 2, 0, 3, -1, 3, 0], + [0, 1, 0, 2, 0, 3, 1, 3], [0, 1, 1, 0, 2, 0, 3, 0], + [0, 1, 1, 1, 2, 1, 3, 1], [0, 1, 0, 2, 0, 3, 1, 0], + [1, 0, 2, 0, 3, 0, 3, 1], [1, -3, 1, -2, 1, -1, 1, 0] +]; + +def N: [ + [0, 1, 1, -2, 1, -1, 1, 0], [1, 0, 1, 1, 2, 1, 3, 1], + [0, 1, 0, 2, 1, -1, 1, 0], [1, 0, 2, 0, 2, 1, 3, 1], + [0, 1, 1, 1, 1, 2, 1, 3], [1, 0, 2, -1, 2, 0, 3, -1], + [0, 1, 0, 2, 1, 2, 1, 3], [1, -1, 1, 0, 2, -1, 3, -1] +]; + +def P: [ + [0, 1, 1, 0, 1, 1, 2, 1], [0, 1, 0, 2, 1, 0, 1, 1], + [1, 0, 1, 1, 2, 0, 2, 1], [0, 1, 1, -1, 1, 0, 1, 1], + [0, 1, 1, 0, 1, 1, 1, 2], [1, -1, 1, 0, 2, -1, 2, 0], + [0, 1, 0, 2, 1, 1, 1, 2], [0, 1, 1, 0, 1, 1, 2, 0] +]; + +def T: [ + [0, 1, 0, 2, 1, 1, 2, 1], [1, -2, 1, -1, 1, 0, 2, 0], + [1, 0, 2, -1, 2, 0, 2, 1], [1, 0, 1, 1, 1, 2, 2, 0] +]; + +def U: [ + [0, 1, 0, 2, 1, 0, 1, 2], [0, 1, 1, 1, 2, 0, 2, 1], + [0, 2, 1, 0, 1, 1, 1, 2], [0, 1, 1, 0, 2, 0, 2, 1] +]; + +def V: [ + [1, 0, 2, 0, 2, 1, 2, 2], [0, 1, 0, 2, 1, 0, 2, 0], + [1, 0, 2, -2, 2, -1, 2, 0], [0, 1, 0, 2, 1, 2, 2, 2] +]; + +def W: [ + [1, 0, 1, 1, 2, 1, 2, 2], [1, -1, 1, 0, 2, -2, 2, -1], + [0, 1, 1, 1, 1, 2, 2, 2], [0, 1, 1, -1, 1, 0, 2, -1] +]; + +def X: [[1, -1, 1, 0, 1, 1, 2, 0]]; + +def Y: [ + [1, -2, 1, -1, 1, 0, 1, 1], [1, -1, 1, 0, 2, 0, 3, 0], + [0, 1, 0, 2, 0, 3, 1, 1], [1, 0, 2, 0, 2, 1, 3, 0], + [0, 1, 0, 2, 0, 3, 1, 2], [1, 0, 1, 1, 2, 0, 3, 0], + [1, -1, 1, 0, 1, 1, 1, 2], [1, 0, 2, -1, 2, 0, 3, 0] +]; + +def Z: [ + [0, 1, 1, 0, 2, -1, 2, 0], [1, 0, 1, 1, 1, 2, 2, 2], + [0, 1, 1, 1, 2, 1, 2, 2], [1, -2, 1, -1, 1, 0, 2, -2] +]; + +def shapes: [F, I, L, N, P, T, U, V, W, X, Y, Z]; + +def symbols: "FILNPTUVWXYZ-" | split(""); + +def nRows: 8; +def nCols: 8; +def blank: 12; + +def printResult: + .symbols as $symbols + | .grid[] as $row + | reduce $row[] as $i (""; . + $symbols[$i]); + +# Input: {grid} +def placeOrientation($o; $r; $c; $shapeIndex): + .grid[$r][$c] = $shapeIndex + | reduce range(0; $o|length; 2) as $io (.; + .grid[$r + $o[$io]][$c + $o[$io + 1]] = $shapeIndex); + +# Input and output: {grid} +# If the placement is feasible, call placeOrientation/3 +def tryPlaceOrientation($o; $r; $c; $shapeIndex): + .grid as $grid + | if any( range(0; $o|length; 2); + . as $io + | ($c + $o[$io + 1]) as $x + | ($r + $o[$io] ) as $y + | $x < 0 or $x >= nCols or $y < 0 or $y >= nRows or $grid[$y][$x] != -1 ) + then empty + else placeOrientation($o; $r; $c; $shapeIndex) + end + ; + +# Input: {grid, placed, shapes} +def solve($pos; $numPlaced): + if $numPlaced == (.shapes|length) + then . + else (($pos / nCols)|floor) as $row + | ($pos % nCols ) as $col + | if .grid[$row][$col] != -1 + then solve($pos + 1; $numPlaced) + else .emit = false + | foreach range(0; .shapes|length) as $i (.; + if .placed[$i] then . + else foreach .shapes[$i][] as $orientation (.; + (tryPlaceOrientation($orientation; $row; $col; $i) + | .placed[$i] = true + | solve($pos + 1; $numPlaced + 1) + | .emit = true) + // .) + end ) + | select(.emit) + end + end; + +# input: {shapes, symbols} +def shuffleShapes: + (.shapes|length) as $n + | reduce range(0; $n) as $i (.; + ($n | prn) as $r + | .shapes |= array_swap($r; $i) + | .symbols |= array_swap($r; $i) ) +; + +def task: + def grid: + 0 | array(nCols) | array(nRows); + def placed: + false | array(symbols|length - 1); + + { shapes: shapes, + symbols: symbols, + grid: grid, + placed: placed} + | shuffleShapes + | reduce range(0; nRows) as $r (.; + reduce range(0; .grid[$r]|length) as $c (.; + .grid[$r][$c] = -1)) + | reduce range(0; 4) as $i (.; + .done = false + | until(.done; + .randRow = (nRows | prn) + | .randCol = (nCols | prn) + | .done = (.grid[.randRow][.randCol] != blank) ) + | .grid[.randRow][.randCol] = blank + ) + | first(solve(0; 0)) + | printResult + // "No solution" +; +task diff --git a/Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-3.ada b/Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-3.ada index 41b6d6249b..d280e4185e 100644 --- a/Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-3.ada +++ b/Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-3.ada @@ -1,4 +1,4 @@ function "-" (Left, Right : Pixel) return Count is begin - return (Left.R - Right.R) + (Left.G - Left.G) + (Left.B - Right.B); + return (Left.R - Right.R) + (Left.G - Right.G) + (Left.B - Right.B); end "-"; diff --git a/Task/Percolation-Bond-percolation/11l/percolation-bond-percolation.11l b/Task/Percolation-Bond-percolation/11l/percolation-bond-percolation.11l index 33890bac0c..0bbedbbc8c 100644 --- a/Task/Percolation-Bond-percolation/11l/percolation-bond-percolation.11l +++ b/Task/Percolation-Bond-percolation/11l/percolation-bond-percolation.11l @@ -3,12 +3,7 @@ F nonrandom() :seed = 1664525 * :seed + 1013904223 R Int(:seed >> 16) / Float(FF'FF) -T Grid - [[Int]] cell, hwall, vwall - F (cell, hwall, vwall) - .cell = cell - .hwall = hwall - .vwall = vwall +T Grid = ([[Int]] cell, [[Int]] hwall, [[Int]] vwall) V (M, nn, t) = (10, 10, 100) @@ -37,7 +32,7 @@ F pgrid(grid, percolated) V where = percolated[0] print(‘!) ’(‘ ’ * where)‘ ’f[1]) -F flood_fill(m, n, &cell, hwall, vwall) -> N +F flood_fill(m, n, &cell, hwall, vwall) -> Void cell[n][m] = 1 I n < :nn - 1 & !hwall[n + 1][m] & !cell[n + 1][m] flood_fill(m, n + 1, &cell, hwall, vwall) diff --git a/Task/Percolation-Mean-cluster-density/11l/percolation-mean-cluster-density.11l b/Task/Percolation-Mean-cluster-density/11l/percolation-mean-cluster-density.11l index d36d38f1a0..b8d418dcc8 100644 --- a/Task/Percolation-Mean-cluster-density/11l/percolation-mean-cluster-density.11l +++ b/Task/Percolation-Mean-cluster-density/11l/percolation-mean-cluster-density.11l @@ -13,7 +13,7 @@ V NRange = [4, 64, 256, 1024, 4096] F newGrid(n, p) R (0 .< n).map(i -> (0 .< @n).map(i -> Int(nonrandom() < @@p))) -F walkMaze(&grid, m, n, idx) -> N +F walkMaze(&grid, m, n, idx) -> Void grid[n][m] = idx I n < grid.len - 1 & grid[n + 1][m] == NotClustered walkMaze(&grid, m, n + 1, idx) diff --git a/Task/Percolation-Site-percolation/11l/percolation-site-percolation.11l b/Task/Percolation-Site-percolation/11l/percolation-site-percolation.11l index 3d409734ed..abebe89ea5 100644 --- a/Task/Percolation-Site-percolation/11l/percolation-site-percolation.11l +++ b/Task/Percolation-Site-percolation/11l/percolation-site-percolation.11l @@ -10,7 +10,6 @@ V NOT_VISITED = 1 T PercolatedException (Int, Int) t - F (t) .t = t @@ -24,7 +23,7 @@ F pgrid(cell, percolated) V where = percolated[0] print(‘!) ’(‘ ’ * where)‘’:cell2char[cell[:nn - 1][where]]) -F walk_maze(m, n, &cell, indx) X(PercolatedException) -> N +F walk_maze(m, n, &cell, indx) X(PercolatedException) -> Void cell[n][m] = indx I n < :nn - 1 & cell[n + 1][m] == :NOT_VISITED walk_maze(m, n + 1, &cell, indx) diff --git a/Task/Percolation-Site-percolation/FreeBASIC/percolation-site-percolation.basic b/Task/Percolation-Site-percolation/FreeBASIC/percolation-site-percolation.basic index 88160101f9..1dbf5565b1 100644 --- a/Task/Percolation-Site-percolation/FreeBASIC/percolation-site-percolation.basic +++ b/Task/Percolation-Site-percolation/FreeBASIC/percolation-site-percolation.basic @@ -2,28 +2,28 @@ #define EMPTY " " #define WET "v" -Dim Shared As String grid() +Dim Shared As String grid Dim Shared As Integer last, lastrow, m, n -Sub make_grid(x As Integer, y As Integer, p As Double) - m = x - n = y - Redim Preserve grid(x*(y+1)+1) - last = Len(grid) - Dim As Integer lastrow = last-n +Sub makeGrid(x As Integer, y As Integer, p As Double) Dim As Integer i, j + m = x + n = y + grid = String(x*(y+1)+1, Chr(10)) + last = Len(grid) + lastrow = last - n For i = 0 To x-1 For j = 1 To y - grid(1+i*(y+1)+j) = Iif(Rnd < p, EMPTY, SOLID) + Mid(grid, 1+i*(y+1)+j, 1) = Iif(Rnd < p, EMPTY, SOLID) Next j Next i End Sub -Function ff(i As Integer) As Boolean - If i <= 0 Or i >= last Or grid(i) <> EMPTY Then Return 0 - grid(i) = WET - Return i >= lastrow Or (ff(i+m+1) Or ff(i+1) Or ff(i-1) Or ff(i-m-1)) +Function ff(i As Integer) As Integer + If i <= 0 Or i >= last Or Mid(grid, i, 1) <> EMPTY Then Return 0 + Mid(grid, i, 1) = WET + Return (i >= lastrow) Or ff(i+m+1) Or ff(i+1) Or ff(i-1) Or ff(i-m-1) End Function Function percolate() As Integer @@ -33,24 +33,23 @@ Function percolate() As Integer Return 0 End Function +Randomize Timer +makeGrid(15, 15, 0.55) +percolate() +Print "15x15 grid:"; +Print grid + +Print "running 10,000 tests for each case:" Dim As Double p -Dim As Integer ip, i, cont - -make_grid(15, 15, 0.55) -Print "15x15 grid:" -For i = 1 To Ubound(grid) - Print grid(i); - If i Mod 15 = 0 Then Print -Next i - -Print !"\nrunning 10,000 tests for each case:" -For ip As Ubyte = 0 To 10 +Dim As Integer ip, i, cnt +For ip = 0 To 10 p = ip / 10 - cont = 0 + cnt = 0 For i = 1 To 10000 - make_grid(15, 15, p) - cont += percolate() + makeGrid(15, 15, p) + cnt += (percolate() = 1) Next i - Print Using "p=#.#: #.####"; p; cont/10000 + Print Using "p=#.#: #.####"; p; Abs(cnt / 10000) Next ip + Sleep diff --git a/Task/Perfect-numbers/ALGOL-60/perfect-numbers.alg b/Task/Perfect-numbers/ALGOL-60/perfect-numbers.alg index 5a8f6073f3..57c14c3c9f 100644 --- a/Task/Perfect-numbers/ALGOL-60/perfect-numbers.alg +++ b/Task/Perfect-numbers/ALGOL-60/perfect-numbers.alg @@ -1,10 +1,10 @@ begin -comment - return p mod q; -integer procedure mod(p, q); - value p, q; integer p, q; +comment - return n mod m; +integer procedure mod(n, m); + value n, m; integer n, m; begin - mod := p - q * entier(p / q); + mod := n - m * entier(n / m); end; comment - return true if n is perfect, otherwise false; @@ -38,6 +38,6 @@ for i := 2 step 1 until 10000 do end; outstring(1,"\n"); outinteger(1,found); -outstring(1,"perfect numbers were found"); +outstring(1," were found"); end diff --git a/Task/Perfect-numbers/EasyLang/perfect-numbers.easy b/Task/Perfect-numbers/EasyLang/perfect-numbers.easy index b558cc5ca8..068527c206 100644 --- a/Task/Perfect-numbers/EasyLang/perfect-numbers.easy +++ b/Task/Perfect-numbers/EasyLang/perfect-numbers.easy @@ -1,13 +1,18 @@ -func perf n . - for i = 1 to n - 1 +fastfunc perf n . + i = 1 + while i < n if n mod i = 0 sum += i . + i += 1 . - return if sum = n + if sum = n + return 1 + . + return 0 . for i = 2 to 10000 if perf i = 1 - print i + write i & " " . . diff --git a/Task/Perfect-numbers/S-BASIC/perfect-numbers.basic b/Task/Perfect-numbers/S-BASIC/perfect-numbers.basic index 43d5ffc386..844e69ce17 100644 --- a/Task/Perfect-numbers/S-BASIC/perfect-numbers.basic +++ b/Task/Perfect-numbers/S-BASIC/perfect-numbers.basic @@ -1,8 +1,8 @@ $lines -rem - return p mod q -function mod(p, q = integer) = integer -end = p - q * (p/q) +rem - return n mod m +function mod(n, m = integer) = integer +end = n - m * (n/m) rem - return true if n is perfect, otherwise false function isperfect(n = integer) = integer diff --git a/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy b/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy new file mode 100644 index 0000000000..9b329f16a0 --- /dev/null +++ b/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy @@ -0,0 +1,27 @@ +n = 15 +offs = 0.7 +r = (100 / (3 * n + 1)) +step = 360 * 2 / (n - 1) +# +background 470 +clear +for row = 0 to n - 1 + for col = 0 to n - 1 + x = (3 * col + 2) * r + y = (3 * row + 2) * r + # + h = col * step + row * step + move (x + offs * cos h) (y + offs * sin h) + color 999 + circle r + # + h += 180 + move (x + offs * cos h) (y + offs * sin h) + color 000 + circle r + # + move x y + color 128 + circle r + . +. diff --git a/Task/Perlin-noise/ALGOL-68/perlin-noise.alg b/Task/Perlin-noise/ALGOL-68/perlin-noise.alg new file mode 100644 index 0000000000..8d1e72dc1c --- /dev/null +++ b/Task/Perlin-noise/ALGOL-68/perlin-noise.alg @@ -0,0 +1,77 @@ +BEGIN # perlin noise - translated from the 11l sample # + [ 0 : 511 ]INT p; + p[ 256 : ] := (151,160,137,91,90,15 + ,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23 + ,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33 + ,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166 + ,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244 + ,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196 + ,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123 + ,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42 + ,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9 + ,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228 + ,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107 + ,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254 + ,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 + ); + p[ 0 : 255 ] := p[ 256 : ]; + + OP AND = ( INT a, b )INT: + IF a >= 0 + THEN ABS ( BIN a AND BIN b ) + ELSE ABS ( NOT BIN ( - ( a + 1 ) ) AND BIN b ) + FI # AND # ; + + PROC fade = ( REAL t )REAL: ( t * t * t ) * ( t * ( t * 6 - 15 ) + 10 ); + PROC linerp = ( REAL t, a, b )REAL: a + ( t * ( b - a ) ); + PROC grad = ( INT hash, REAL x, y, z )REAL: + BEGIN + INT h = hash AND 15; + REAL u = IF h < 8 THEN x ELSE y FI; + REAL v = IF h < 4 THEN y ELIF h = 12 OR h = 14 THEN x ELSE z FI; + IF ( h AND 1 ) = 0 THEN u ELSE -u FI + IF ( h AND 2 ) = 0 THEN v ELSE -v FI + END # grad # ; + PROC perlin noise = ( REAL x in, y in, z in )REAL: + BEGIN + REAL x := x in, y := y in, z := z in; + INT xx = ENTIER x AND 255; + INT yy = ENTIER y AND 255; + INT zz = ENTIER z AND 255; + x -:= ENTIER x; + y -:= ENTIER y; + z -:= ENTIER z; + REAL u = fade( x ); + REAL v = fade( y ); + REAL w = fade( z ); + INT a = p[ xx ] + yy; + INT aa = p[ a ] + zz; + INT ab = p[ a + 1 ] + zz; + INT b = p[ xx + 1 ] + yy; + INT ba = p[ b ] + zz; + INT bb = p[ b + 1 ] + zz; + linerp( w + , linerp( v + , linerp( u + , grad( p[ aa ], x, y, z ) + , grad( p[ ba ], x - 1, y, z ) + ) + , linerp( u + , grad( p[ ab ], x, y - 1, z ) + , grad( p[ bb ], x - 1, y - 1, z ) + ) + ) + , linerp( v + , linerp( u + , grad( p[ aa + 1 ], x, y, z - 1 ) + , grad( p[ ba + 1 ], x - 1, y, z - 1 ) + ) + , linerp( u + , grad( p[ ab + 1 ], x, y - 1, z - 1 ) + , grad( p[ bb + 1 ], x - 1, y - 1, z - 1 ) + ) + ) + ) + END # perlin noise # ; + + print( ( fixed( perlin noise( 3.14, 42, 7 ), -18, 15 ) ) ) +END diff --git a/Task/Perlin-noise/Jq/perlin-noise.jq b/Task/Perlin-noise/Jq/perlin-noise.jq new file mode 100644 index 0000000000..9c5cb1c0bc --- /dev/null +++ b/Task/Perlin-noise/Jq/perlin-noise.jq @@ -0,0 +1,99 @@ +### Generic functions +# (-3.2|fraction) #=> -0.2 +def fraction: + if . >= 0 then . - trunc + else - (-. | fraction) + end; + +# For gojq +def div($y): + (. - (. % y)) / $y; + +# Convert the input integer to a stream of 0s and 1s, least significant bit first +def bitwise: + recurse( if . >= 2 then div(2) else empty end) | . % 2; + +# Inverse of bitwise: +def stream_to_integer(stream): + reduce stream as $c ( {power:1 , ans: 0}; + .ans += ($c * .power) | .power *= 2 ) + | .ans; + +# . & 2^($n-1) +def bits($n): + stream_to_integer(limit($n; bitwise)); + +### Perlin Noise +def permutation: [ + 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, + 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, + 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, + 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, + 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, + 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, + 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, + 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, + 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, + 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, + 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, + 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, + 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, + 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, + 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, + 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 +]; + +def grad($hash; $x; $y; $z): + def bit2: nth(1; bitwise); + # Convert low 4 bits of hash code into 12 gradient directions: + ( $hash|bits(4) ) as $h + | (if $h < 8 then $x else $y end) as $u + | (if $h < 4 then $y elif ($h == 12 or $h == 14) then $x else $z end) as $v + | (if ($h % 2 == 0) then $u else -$u end) + + (if (($h | bit2) == 0) then $v else -$v end) ; + +def noise($x; $y; $z): + def p: + permutation as $p + | $p[:256] + [range(256;512) | $p[.-256]]; + + def fade: + . * . * . * (. * (. * 6 - 15) + 10) ; + + def lerp($t; $a; $b): $a + $t * ($b - $a); + + # Find unit cube that contains point + ([$x,$y,$z] | map(floor | bits(8))) as [$xi, $yi, $zi] + + # Find relative x, y, z of point in cube + | ([$x,$y,$z] | map(fraction)) as [$xx, $yy, $zz] + + # Compute fade curves for each of xx, yy, zz + | ([$xx,$yy,$zz] | map(fade)) as [$u, $v, $w] + + | p as $p + # Hash co-ordinates of the 8 cube corners + # and add blended results from 8 corners of cube + | ($p[$xi] + $yi) as $a + | ($p[$a] + $zi) as $aa + | ($p[$a + 1] + $zi) as $ab + | ($p[$xi + 1] + $yi) as $b + | ($p[$b] + $zi) as $ba + | ($p[$b + 1] + $zi) as $bb + | lerp($w; + lerp($v; + lerp($u; + grad($p[$aa]; $xx; $yy; $zz); + grad($p[$ba]; $xx - 1; $yy; $zz)); + lerp($u; + grad($p[$ab]; $xx; $yy - 1; $zz); + grad($p[$bb]; $xx - 1; $yy - 1; $zz))); + lerp($v; + lerp($u; + grad($p[$aa + 1]; $xx; $yy; $zz - 1); + grad($p[$ba + 1]; $xx - 1; $yy; $zz - 1)); + lerp($u; + grad($p[$ab + 1]; $xx; $yy - 1; $zz - 1); + grad($p[$bb + 1]; $xx - 1; $yy - 1; $zz - 1))) ); + +noise(3.14; 42; 7) diff --git a/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy b/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy new file mode 100644 index 0000000000..db99f09c13 --- /dev/null +++ b/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy @@ -0,0 +1,59 @@ +func[] init n . + for i to n + r[] &= i - 1 + . + return r[] +. +func fac n . + f = 1 + for i to n + f *= i + . + return f +. +func[] perm n r . + perm[] = init n + fa = fac n + for i = n downto 1 + fa /= i + d = r div fa + 1 + r = r mod fa + r[] &= perm[d] + for j = d to i - 1 + perm[j] = perm[j + 1] + . + . + return r[] +. +func rank n p[] . + perm[] = init n + fa = fac n + for i = n downto 1 + fa /= i + h = p[n - i + 1] + d = 1 + while perm[d] <> h + d += 1 + . + r += fa * (d - 1) + for j = d to i - 1 + perm[j] = perm[j + 1] + . + . + return r +. +proc show . . + for i = 0 to 5 + h[] = perm 3 i + print i & " -> " & h[] & " -> " & rank 3 h[] + . + print "" + for i to 4 + r = random fac 12 - 1 + write r & " -> " + h[] = perm 12 r + write h[] + print " -> " & rank 12 h[] + . +. +show diff --git a/Task/Permutations-by-swapping/Ada/permutations-by-swapping.ada b/Task/Permutations-by-swapping/Ada/permutations-by-swapping.ada new file mode 100644 index 0000000000..2cd2c9231e --- /dev/null +++ b/Task/Permutations-by-swapping/Ada/permutations-by-swapping.ada @@ -0,0 +1,28 @@ +-- Permutations by swapping +-- J. Carter 2024 Jun +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Permutations; + +procedure Permutations_By_Swapping is + package Permutations is new PragmARC.Permutations (Element => Positive); + + Permutation : Permutations.Sequence_Lists.Vector; +begin -- Permutations_By_Swapping + Permutations.Generate (Initial => (1, 2, 3), Result => Permutation); + + Output : for I in 1 .. Permutation.Last_Index loop + One_Permutation : declare + Sequence : Permutations.Sequence renames Permutation.Element (I); + begin -- One_Permutation + Ada.Text_IO.Put (Item => '('); + + Print : for J in Sequence'Range loop + Ada.Text_IO.Put (Item => (if J > 1 then "," else "") & Sequence (J)'Image); + end loop Print; + + Ada.Text_IO.Put_Line (Item => ") " & (if I rem 2 = 0 then '-' else '+') & '1'); + end One_Permutation; + end loop Output; +end Permutations_By_Swapping; diff --git a/Task/Permutations/Langur/permutations.langur b/Task/Permutations/Langur/permutations.langur index 0dfb1b0d5c..b94494e034 100644 --- a/Task/Permutations/Langur/permutations.langur +++ b/Task/Permutations/Langur/permutations.langur @@ -1,39 +1,39 @@ -val .factorial = fn(.x) if(.x < 2: 1; .x * self(.x - 1)) +val factorial = fn x:if(x < 2: 1; x * fn((x - 1))) -val .permute = fn(.list) { - if .list is not list: throw "expected list" +val permute = fn(plist) { + if plist is not list: throw "expected list" - val .limit = 10 - if len(.list) > .limit: throw $"permutation limit exceeded (currently \.limit;)" + val limit = 10 + if len(plist) > limit: throw "permutation limit exceeded (currently {{limit}})" - var .elements = .list - var .ordinals = pseries len .elements + var elements = plist + var ordinals = pseries(len(elements)) - val .n = len(.ordinals) - var .i, .j + val n = len(ordinals) + var i, j - for[.p=[.list]] of .factorial(len .list)-1 { - .i = .n - 1 - .j = .n - while .ordinals[.i] > .ordinals[.i+1] { - .i -= 1 + for[p=[plist]] of factorial(len(plist))-1 { + i = n - 1 + j = n + while ordinals[i] > ordinals[i+1] { + i -= 1 } - while .ordinals[.j] < .ordinals[.i] { - .j -= 1 + while ordinals[j] < ordinals[i] { + j -= 1 } - .ordinals[.i], .ordinals[.j] = .ordinals[.j], .ordinals[.i] - .elements[.i], .elements[.j] = .elements[.j], .elements[.i] + ordinals[i], ordinals[j] = ordinals[j], ordinals[i] + elements[i], elements[j] = elements[j], elements[i] - .i += 1 - for .j = .n; .i < .j ; .i, .j = .i+1, .j-1 { - .ordinals[.i], .ordinals[.j] = .ordinals[.j], .ordinals[.i] - .elements[.i], .elements[.j] = .elements[.j], .elements[.i] + i += 1 + for j = n; i < j ; i, j = i+1, j-1 { + ordinals[i], ordinals[j] = ordinals[j], ordinals[i] + elements[i], elements[j] = elements[j], elements[i] } - .p = more .p, .elements + p = more(p, elements) } } -for .e in .permute([1, 3.14, 7]) { - writeln .e +for e in permute([1, 3.14, 7]) { + writeln e } diff --git a/Task/Permutations/Uiua/permutations.uiua b/Task/Permutations/Uiua/permutations.uiua new file mode 100644 index 0000000000..ec272f75c7 --- /dev/null +++ b/Task/Permutations/Uiua/permutations.uiua @@ -0,0 +1,6 @@ +# Takes strict range 0..=lwb_digits; i--)); do # work backwards # + ((x=base*digits[i] + digit*i)); + ((digits[i]=x%(2*i-1))); + ((digit=x/(2*i-1))) + done; + ((digits[lwb_digits]=digit % base)); ((digit/=base)); +# nines := # + if((digit == nine)); then + ((nines=nines + 1)) + else + if((digit == base)); then + ((out=predigit+1)); + $yield $out; predigit=0; + for((repeats=1; repeats<=nines; repeats++)); do $yield 0; done + else + if((place != 1)); then $yield $predigit; fi; predigit=$digit; + for((repeats=1; repeats<=nines; repeats++)); do $yield $nine; done + fi; + nines=0 + fi + done; + $yield $predigit +}; + +print_digit(){ + echo -n $1 +} +# feynman_point=762; # feynman_point + 4 is a good test case +# the 33rd decimal place is a shorter tricky test case # +target="3.1415926.......................502"; +((test_decimal_places=${#target}-2)); # upb + +# iterate throught the digits as they are being found # +gen_pi_digits $test_decimal_places print_digit +echo # (new_line) diff --git a/Task/Pick-random-element/PascalABC.NET/pick-random-element.pas b/Task/Pick-random-element/PascalABC.NET/pick-random-element.pas new file mode 100644 index 0000000000..479bc07139 --- /dev/null +++ b/Task/Pick-random-element/PascalABC.NET/pick-random-element.pas @@ -0,0 +1,4 @@ +begin + var a := Arr('cat','dog','wolf','zebra'); + a.RandomElement.Print +end. diff --git a/Task/Pick-random-element/Uiua/pick-random-element.uiua b/Task/Pick-random-element/Uiua/pick-random-element.uiua new file mode 100644 index 0000000000..c3955aa455 --- /dev/null +++ b/Task/Pick-random-element/Uiua/pick-random-element.uiua @@ -0,0 +1 @@ +⊡⌊×⚂⧻."abcdefg" diff --git a/Task/Pierpont-primes/EasyLang/pierpont-primes.easy b/Task/Pierpont-primes/EasyLang/pierpont-primes.easy new file mode 100644 index 0000000000..24256ba706 --- /dev/null +++ b/Task/Pierpont-primes/EasyLang/pierpont-primes.easy @@ -0,0 +1,47 @@ +fastfunc isprim num . + if num mod 2 = 0 + if num = 2 + return 1 + . + return 0 + . + i = 3 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 2 + . + return 1 +. +fastfunc mod2x3x n . + while n mod 2 = 0 + n /= 2 + . + while n mod 3 = 0 + n /= 3 + . + return n +. +i = 2 +cnt = 1 +write 2 & " " +while cnt < 50 + if mod2x3x i = 1 and isprim (i + 1) = 1 + cnt += 1 + write i + 1 & " " + . + i += 2 +. +print "" +print "" +i = 4 +write 2 & " " +cnt = 1 +while cnt < 50 + if mod2x3x i = 1 and isprim (i - 1) = 1 + cnt += 1 + write i - 1 & " " + . + i += 2 +. diff --git a/Task/Pig-the-dice-game-Player/C/pig-the-dice-game-player.c b/Task/Pig-the-dice-game-Player/C/pig-the-dice-game-player.c new file mode 100644 index 0000000000..ffc61ded62 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/C/pig-the-dice-game-player.c @@ -0,0 +1,179 @@ +#include +#include +#include + + +#define MAX_POINTS 100 +#define PLAYER_COUNT 4 + + +//Possible player moves. +typedef enum { + ROLL, + HOLD +} Moves; + +//To allow the player definition to be used in the function definition. +typedef struct Player Player; + +//This function takes the player's current score, returns 1 if the player rolls and 0 if they hold. +typedef Moves (*DeciderFunction) (Player *player); + +struct Player{ + unsigned int score; + unsigned int roundScore; + DeciderFunction dFunction; +}; + +/* + Auxiliary functions +*/ +static int randrange(int min, int max){ + return (rand() % (max - min + 1)) + min; +} + +//Creates a player with the given decider function. +static Player *create_player(DeciderFunction dFunction) { + Player *player = malloc(sizeof(Player)); + player->score = 0; + player->roundScore = 0; + player->dFunction = dFunction; + + return player; +} + +/* + Player functions +*/ +//Randomly decides whether to hold or roll. +static Moves random_player(Player *player) { + if (player->score + player->roundScore >= MAX_POINTS) + return HOLD; + + int num = randrange(0, 9); + + //We do the second check to make sure the player rolls at least once. + if (num < 5 || player->roundScore == 0) + return ROLL; + return HOLD; +} + +//Always tries to score at least a quarter of the difference between their score and "MAX_POINTS". +static Moves quarter_player(Player *player) { + if (player->score + player->roundScore >= MAX_POINTS) + return HOLD; + + unsigned int target = (MAX_POINTS - player->score) / 4; + + if (player->roundScore < target) + return ROLL; + return HOLD; +} + +//Always tries to score at least fifteen points. +static Moves fifteen_player(Player *player) { + if (player->score + player->roundScore >= MAX_POINTS) + return HOLD; + + if (player->roundScore < 15) + return ROLL; + return HOLD; +} + +//Behaves like the fifteen player, except they get nervous when they are close to wining. +static Moves nervous_player(Player *player) { + if (player->score + player->roundScore >= MAX_POINTS) + return HOLD; + + float scorePercent = (float)(1 / MAX_POINTS) * (float)(player->score + player->roundScore); + + //If the player's score is more than 75% of the total score there is a chance they will hold with less points. + if (scorePercent >= 0.75 && player->roundScore > 6) { + int num = randrange(0, 9); + + if (num < 5) + return ROLL; + return HOLD; + } + + if (player->roundScore < 15) + return ROLL; + return HOLD; +} + +/* + Game functions. +*/ +//Given a player it plays as long as the decider function allows it. +static void play(Player *player) { + while (1) { + if (player->dFunction(player) == ROLL) { + int roll = randrange(1, 6); + + if (roll > 1) { + player->roundScore += roll; + fprintf(stdout, "Player rolls a %d - Round score: %d\n", roll, player->roundScore); + } + else { + //If the player rolls a 1 they loose all their points. + player->score = 0; + player->roundScore = 0; + + fprintf(stdout, "Player rolls a 1, they loose all their points\n"); + + break; + } + } + else { + player->score += player->roundScore; + player->roundScore = 0; + + fprintf(stdout, "Player holds\n"); + + break; + } + } + fprintf(stdout, "Current score: %d\n", player->score); +} + +static void game_controller(Player *players[]) { + int playFlag = 1; + while (playFlag) { + for (int i = 0; i < PLAYER_COUNT; i++) { + fprintf(stdout, "\nPlayer %d turn\n", i + 1); + play(players[i]); + + //Check whether the given player has won, if so end the game and display total scores. + if (players[i]->score >= MAX_POINTS) { + fprintf(stdout, "\n\nPlayer %d has won", i + 1); + + puts("\n\nThe overall scores were:"); + for (int j = 0; j < PLAYER_COUNT; j++) + fprintf(stdout, "Player %d: %d points\n", j + 1, players[j]->score); + puts(""); + + playFlag = 0; + break; + } + } + } +} + + +int main () { + //Seed the random number generator with the current system time. + srand(time(0)); + + Player *players[PLAYER_COUNT]; + players[0] = create_player(random_player); + players[1] = create_player(quarter_player); + players[2] = create_player(fifteen_player); + players[3] = create_player(nervous_player); + + game_controller(players); + + for (int i = 0; i < PLAYER_COUNT; i++) + free(players[i]); + + return 0; +} diff --git a/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy b/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy new file mode 100644 index 0000000000..50ccee3074 --- /dev/null +++ b/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy @@ -0,0 +1,10 @@ +for i = 1 to 4 + col = 000 + y = 100 - i * 25 + for x = 0 step i / 4 to 100 - i / 4 + color col + move x y + rect i / 4 25 + col = 999 - col + . +. diff --git a/Task/Pisano-period/APL/pisano-period.apl b/Task/Pisano-period/APL/pisano-period.apl new file mode 100644 index 0000000000..bd5b7a4cd6 --- /dev/null +++ b/Task/Pisano-period/APL/pisano-period.apl @@ -0,0 +1,17 @@ +pisano_period←{ + prime ← 2∘≤∧0∧.≠1↓⍳∘(⌊*∘0.5)|⊢ + select ← {(⍺⍺¨⍵)/⍵} + factors ← {⍺←2 ⋄ ⍺≥⍵×⍵:⍬ ⋄ 0=⍺|⍵:⍺,⍺∇⍵÷⍺ ⋄ (⍺+1)∇⍵} + + pisanoPeriod ← {⊃⍸1 0⍷(⊢,⍵|(+/¯2∘↑))⍣(⍵×⍵),0 1} + pisanoPrime ← {(pisanoPeriod ⍺)×⍺*⍵-1} + pisano ← {∧/{⍺=0:1 ⋄ ⍺ pisanoPrime ≢⍵}⌸factors ⍵} + + showPisanoPrimes ← {+⎕←⍵'pisanoPrime'⍺'→'(⍵ pisanoPrime ⍺)}¨ + _←2 showPisanoPrimes prime select ⍳15 + ⎕←'' + _←1 showPisanoPrimes prime select ⍳180 + ⎕←'' + ⎕←'pisano ⍵ for integers ''⍵'' from 1 to 180 are:' + ⎕←pisano¨12 15⍴⍳180 +} diff --git a/Task/Pisano-period/Jq/pisano-period.jq b/Task/Pisano-period/Jq/pisano-period.jq new file mode 100644 index 0000000000..a4bf4632de --- /dev/null +++ b/Task/Pisano-period/Jq/pisano-period.jq @@ -0,0 +1,114 @@ +### In case gojq is used: +# Require $n > 0 +def _nwise($n): + def _n: if length <= $n then . else .[:$n] , (.[$n:] | _n) end; + if $n <= 0 then "nwise: argument should be non-negative" else _n end; + +### Generic utilities + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def lcm($m; $n): + # The helper function takes advantage of jq's tail-recursion optimization + def _lcm: + # state is [m, n, i] + if (.[2] % .[1]) == 0 then .[2] else (.[0:2] + [.[2] + $m]) | _lcm end; + [$m, $n, $m] | _lcm; + +# Preserve integer accuracy as much as the implementation of jq allows +def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in); + +def is_prime: + . as $n + | if ($n < 2) then false + elif ($n % 2 == 0) then $n == 2 + elif ($n % 3 == 0) then $n == 3 + elif ($n % 5 == 0) then $n == 5 + elif ($n % 7 == 0) then $n == 7 + elif ($n % 11 == 0) then $n == 11 + elif ($n % 13 == 0) then $n == 13 + elif ($n % 17 == 0) then $n == 17 + elif ($n % 19 == 0) then $n == 19 + else sqrt as $s + | 23 + | until( . > $s or ($n % . == 0); . + 2) + | . > $s + end; + +# Emit an array of the prime factors of . in order using a wheel with basis [2, 3, 5] +# e.g. 44 | primeFactors => [2,2,11] +def primeFactors: + def out($i): until (.n % $i != 0; .factors += [$i] | .n = ((.n/$i)|floor) ); + if . < 2 then [] + else [4, 2, 4, 2, 4, 6, 2, 6] as $inc + | { n: ., + factors: [] } + | out(2) + | out(3) + | out(5) + | .k = 7 + | .i = 0 + | until(.k * .k > .n; + if .n % .k == 0 + then .factors += [.k] + | .n = ((.n/.k)|floor) + else .k += $inc[.i] + | .i = ((.i + 1) % 8) + end) + | if .n > 1 then .factors += [ .n ] else . end + | .factors + end; + +# Calculate the Pisano period of . from first principles. +def pisanoPeriod: + . as $m + | {p: 0, c: 1} + | first(foreach range(0; $m*$m) as $i (.; + .p as $t + | .p = .c + | .c = ($t + .c) % $m; + select(.p == 0 and .c == 1) | $i + 1 + )) // 1; + +# Calculate the Pisano period of $p^$k where $p is prime and $k is a positive integer. +def pisanoPrime($p; $k): + $p + | if (is_prime|not) or $k == 0 then 0 # no can do + else ( power($k-1) * pisanoPeriod ) + end; + +# Calculate the Pisano period of . using pisanoPrime/2. +def pisano: + . as $m + | (reduce primeFactors[] as $p ({}; .[$p|tostring] += 1) + | to_entries | map([(.key|tonumber), .value]) ) as $primePowers + | (reduce $primePowers[] as [$p, $n] ([]; + . + [ pisanoPrime($p;$n) ] ) ) as $pps + | ($pps|length) as $ppsl + | if $ppsl == 0 then 1 + elif $ppsl == 1 then $pps[0] + else {f: $pps[0], i: 1} + | until(.i >= $ppsl; + .f = lcm(.f; $pps[.i]) + | .i += 1) + | .f + end; + +def examples: + (range( 2; 15) + | pisanoPrime(.; 2) as $pp + | select($pp > 0) + | "pisanoPrime(\(.); 2) = \($pp)" ), + "", + (range( 2; 180) + | pisanoPrime(.; 1) as $pp + | select($pp > 0) + | "pisanoPrime(\(.);1) = \($pp)" ) +; + +examples, +"\npisano(n) for integers 'n' from 1 to 180 are:", +( [range(1; 181) | pisano ] + | _nwise(15) + | map(lpad(3)) + | join(" ")) diff --git a/Task/Pisano-period/SETL/pisano-period.setl b/Task/Pisano-period/SETL/pisano-period.setl new file mode 100644 index 0000000000..7230dab59c --- /dev/null +++ b/Task/Pisano-period/SETL/pisano-period.setl @@ -0,0 +1,79 @@ +program pisano_period; + loop for p in [2..15] | prime p do + print("pisanoPrime(" + lpad(str p,3) + ", 2) = " + + lpad(str pisanoPrime(p,2), 3)); + end loop; + print; + + loop for p in [2..180] | prime p do + print("pisanoPrime(" + lpad(str p,3) + ", 1) = " + + lpad(str pisanoPrime(p,1), 3)); + end loop; + print; + + print("pisano(n) for integers 'n' from 1 to 180 are:"); + loop for n in [1..180] do + nprint(lpad(str pisano n,4)); + if (col +:= 1) mod 15 = 0 then print; end if; + end loop; + + op gcd(a, b); + return {[0, a]}(b) ? (b gcd (a mod b)); + end op; + + op lcm(a, b); + return a div (a gcd b) * b; + end op; + + op factors(n); + d := 2; + f := {}; + loop while d <= n do + loop while n mod d=0 do + f(d) +:= 1; + n div:= d; + end loop; + d +:= 1; + end loop; + return f; + end op; + + op prime(n); + if n<=4 then return n in {2,3}; end if; + if n mod 2=0 then return n=2; end if; + if n mod 3=0 then return n=3; end if; + d := 5; + loop while d*d <= n do + if n mod d=0 then return false; end if; + d +:= 2; + if n mod d=0 then return false; end if; + d +:= 4; + end loop; + return true; + end op; + + op pisanoPeriod(n); + [p, c, i] := [0, 1, 0]; + loop while i < n*n do + [p, c] := [c, (p+c) mod n]; + i +:= 1; + if p=0 and c=1 then return i; end if; + end loop; + return 1; + end op; + + proc pisanoPrime(p, k); + return if not prime p or k=0 + then om + else p**(k-1) * pisanoPeriod p + end; + end proc; + + op pisano(m); + primePowers := factors m; + pps := [pisanoPrime(p, k) : k = primePowers(p)]; + if #pps = 0 then return 1; end if; + if #pps = 1 then return pps(1); end if; + return lcm/pps; + end op; +end program; diff --git a/Task/Plasma-effect/EasyLang/plasma-effect.easy b/Task/Plasma-effect/EasyLang/plasma-effect.easy new file mode 100644 index 0000000000..42060fa850 --- /dev/null +++ b/Task/Plasma-effect/EasyLang/plasma-effect.easy @@ -0,0 +1,20 @@ +# lodev.org/cgtutor/plasma.html (last example) +func dist a b c d . + d1 = a - c ; d2 = b - d + return 15 * sqrt (d1 * d1 + d2 * d2) +. +on animate + for y = 0 step 0.4 to 100 + for x = 0 step 0.4 to 100 + val = sin dist (x + time) y 50 50 + val += sin dist x y 25 25 + val += sin (dist x (y + time / 7) 75 50 * 1.2) + val += sin dist x y 75 40 + col = (val + 4) / 16 + color3 col col * 2 1 - col + move x y + rect 0.5 0.5 + . + . + time += 1 +. diff --git a/Task/Play-recorded-sounds/Ada/play-recorded-sounds.ada b/Task/Play-recorded-sounds/Ada/play-recorded-sounds.ada new file mode 100644 index 0000000000..8bcfde7d19 --- /dev/null +++ b/Task/Play-recorded-sounds/Ada/play-recorded-sounds.ada @@ -0,0 +1,39 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Sf.Audio.Music; use Sf, Sf.Audio, Sf.Audio.Music; + +procedure Play is + Sound1 : sfMusic_Ptr; + Sound2 : sfMusic_Ptr; +begin + Sound1 := createFromFile ("sound1.ogg"); + Sound2 := createFromFile ("sound2.ogg"); + if Sound1 = null or Sound2 = null then + Put_Line (Standard_Error, "Error: Sound files not found!"); + return; + end if; + + -- Looping for both sounds + setLoop (Sound1, sfTrue); + setLoop (Sound2, sfTrue); + + -- Setting the volume of each sound + setVolume (Sound1, 100.0); + setVolume (Sound2, 75.0); + + Put_Line ("Playing Sound1 individually... "); + play (Sound1); + delay 5.0; + + Put_Line ("Playing Sound1 and Sound2 simultaneously... "); + play (Sound2); + delay 10.0; + + Put_Line ("Stopping Sound1 before the end..."); + stop (Sound1); + + Put_Line ("Playing Sound2 alone for 5 seconds..."); + delay 5.0; + + destroy (Sound1); + destroy (Sound2); +end Play; diff --git a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy index 310c247c68..e6f2741331 100644 --- a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy +++ b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy @@ -17,17 +17,17 @@ for i = 1 to n linewidth 0.1 sty = m div 9 for i range0 10 - move 2 4 + i * 10 - text i * sty move 10 5 + i * 10 line 95 5 + i * 10 + move 2 4 + i * 10 + text i * sty . stx = x[n] div 9 for i range0 10 - move i * 9 + 10 1 - text i * stx move i * 9 + 10 5 line i * 9 + 10 97 + move i * 9 + 10 1 + text i * stx . color 900 linewidth 0.5 diff --git a/Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy b/Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy new file mode 100644 index 0000000000..c3b1d166c3 --- /dev/null +++ b/Task/Pointers-and-references/Ecstasy/pointers-and-references.ecstasy @@ -0,0 +1,18 @@ +module test { + @Inject Console console; + + public class Point(Int x, Int y) { + @Override String toString() = $"({x},{y})"; + } + + void run() { + Point p = new Point(0, 0); + p.x = 7; + p.y = p.x; + console.print($"{p=}"); + + // obtain the reference object itself + Ref r = &p; + console.print($"{r.actualType=}"); + } +} diff --git a/Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas b/Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas new file mode 100644 index 0000000000..8c3a415d0e --- /dev/null +++ b/Task/Pointers-and-references/PascalABC.NET/pointers-and-references.pas @@ -0,0 +1,29 @@ +type MyClass = class +public + x: integer := 555; +end; + +begin + var pi: ^integer; + New(pi); + pi^ := 1023; + var pb: ^byte; + //pb := pi; // compiler error + var p: pointer; + p := pi; + pb := p; + Print(pb^); // byte representation of integer + loop 3 do + begin + pb := pointer(integer(pb)+1); // analog of pb++ + Print(pb^); + end; + Println; + var obj := new MyClass; // obj is a reference to object + // All regferences in .NET are under control of garbage collection + Println(obj); + var obj1 := obj; // another reference to the same object + obj1.x := 666; + Println(obj); + obj := nil; // zero reference +end. diff --git a/Task/Poker-hand-analyser/Ada/poker-hand-analyser.ada b/Task/Poker-hand-analyser/Ada/poker-hand-analyser.ada new file mode 100644 index 0000000000..94bdcc4959 --- /dev/null +++ b/Task/Poker-hand-analyser/Ada/poker-hand-analyser.ada @@ -0,0 +1,162 @@ +pragma Ada_2022; +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Containers.Generic_Constrained_Array_Sort; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Poker is + + type Face_T is (two, three, four, five, six, seven, eight, nine, t, j, q, k, a); + for Face_T use (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14); + type Suit_T is (C, D, H, S); + type Card_T is record + Face : Face_T; + Suit : Suit_T; + end record; + + subtype Hand_Index is Natural range 1 .. 5; + type Hand_T is array (Hand_Index) of Card_T; + type Test_Hand_Arr is array (Positive range <>) of Hand_T; + type Pip_Counter_T is array (Face_T range Face_T'Range) of Natural; + + Pip_Counts : Pip_Counter_T := [others => 0]; + + Test_Hands : Test_Hand_Arr := [ + 1 => [(two, H), (two, D), (two, C), (k, S), (q, D)], + 2 => [(two, H), (five, H), (seven, D), (eight, C), (nine, S)], + 3 => [(a, H), (two, D), (three, C), (four, C), (five, D)], + 4 => [(two, H), (three, H), (two, D), (three, C), (three, D)], + 5 => [(two, H), (seven, H), (two, D), (three, C), (three, D)], + 6 => [(two, H), (seven, H), (seven, D), (seven, C), (seven, S)], + 7 => [(t, H), (j, H), (q, H), (k, H), (a, H)], + 8 => [(four, H), (four, S), (k, S), (five, D), (t, S)], + 9 => [(q, C), (t, C), (seven, C), (six, C), (q, C)] + ]; + + function "<" (L, R : Card_T) return Boolean is + begin + if L.Face = R.Face then + return L.Suit < R.Suit; + else + return L.Face < R.Face; + end if; + end "<"; + + procedure Sort_Hand is new Ada.Containers.Generic_Constrained_Array_Sort (Hand_Index, Card_T, Hand_T); + + procedure Print_Hand (Hand : Hand_T) is + begin + for Card of Hand loop + if Card.Face < j then + Put (Face_T'Enum_Rep (Card.Face)'Image); + else + Put (" " & To_Lower (Card.Face'Img)); + end if; + Put (To_Lower (Card.Suit'Img)); + end loop; + end Print_Hand; + + function Is_Invalid (Hand : Hand_T) return Boolean is + begin + for Ix in 2 .. 5 loop + if Face_T'Pos (Hand (Ix).Face) = Face_T'Pos (Hand (Ix - 1).Face) and then + Hand (Ix).Suit = Hand (Ix - 1).Suit + then + return True; + end if; + end loop; + return False; + end Is_Invalid; + + function Is_Flush (Hand : Hand_T) return Boolean is + begin + for Ix in 2 .. 5 loop + if Hand (Ix).Suit /= Hand (1).Suit then + return False; + end if; + end loop; + return True; + end Is_Flush; + + function Is_Straight (Hand : Hand_T) return Boolean is + begin + -- special case: Ace low + if Hand (5).Face = a and then Hand (1).Face = two and then Hand (2).Face = three and then Hand (3).Face = four then + return True; + end if; + for Ix in 2 .. 5 loop + if Face_T'Pos (Hand (Ix).Face) /= Face_T'Pos (Hand (Ix - 1).Face) + 1 then + return False; + end if; + end loop; + return True; + end Is_Straight; + + function Of_A_Kind (N : Positive) return Boolean is + begin + for Pip in two .. a loop + if Pip_Counts (Pip) = N then + return True; + end if; + end loop; + return False; + end Of_A_Kind; + + function Count_Pairs return Natural is + Pairs : Natural := 0; + begin + for Pip in two .. a loop + if Pip_Counts (Pip) = 2 then + Pairs := Pairs + 1; + end if; + end loop; + return Pairs; + end Count_Pairs; + + Flush, Straight : Boolean; + +begin + + for Hand of Test_Hands loop + Print_Hand (Hand); + Put (":"); + Set_Col (20); + Sort_Hand (Hand); -- Print_Hand (Hand); + if Is_Invalid (Hand) then + Put ("invalid"); + else + Flush := Is_Flush (Hand); + Straight := Is_Straight (Hand); + if Flush and Straight then + Put ("straight-flush"); + else + for Pip in two .. a loop + Pip_Counts (Pip) := 0; + for Card of Hand loop + if Card.Face = Pip then + Pip_Counts (Pip) := Pip_Counts (Pip) + 1; + end if; + end loop; + end loop; + if Of_A_Kind (4) then + Put ("four-of-a-kind"); + elsif Of_A_Kind (3) and then Of_A_Kind (2) then + Put ("full-house"); + elsif Flush then + Put ("flush"); + elsif Straight then + Put ("straight"); + elsif Of_A_Kind (3) then + Put ("three-of-a-kind"); + else + case Count_Pairs is + when 2 => Put ("two-pairs"); + when 1 => Put ("one-pair"); + when others => Put ("high-card"); + end case; + end if; + end if; + end if; + Put_Line (""); + end loop; + +end Poker; diff --git a/Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq b/Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq new file mode 100644 index 0000000000..f6ad9a73e3 --- /dev/null +++ b/Task/Poker-hand-analyser/Jq/poker-hand-analyser.jq @@ -0,0 +1,65 @@ +# A card is represented by a JSON object: +def Card($face; $suit): {$face, $suit}; + +def FACES: "23456789tjqka"; +def SUITS: "shdc"; + +# Input: an array of Card +def isStraight: + sort_by(.face) + | (.[0].face + 4 == .[4].face) + or (.[4].face == 14 and .[0].face == 2 and .[3].face == 5) ; + +def isFlush: + .[0].suit as $suit + | all(.[]; .suit == $suit); + +# Input: a string such as "2h 2d 2c kc qd" +def analyzeHand: + (FACES | split("")) as $FACES + | (SUITS | split("")) as $SUITS + | ascii_downcase + | split(" ") + | unique + | if length != 5 or + any(length != 2 or + (.[0:1] | IN($FACES[]) | not) or + (.[1: ] | IN($SUITS[]) | not) ) + then "invalid" + else [.[] as $s | Card(($FACES|index($s[0:1])) + 2; $s[1:]) ] + | . as $cards + | group_by(.face) + | if length == 2 + then if any(length == 4) then "four-of-a-kind" + else "full-house" + end + elif length == 3 + then if any(length == 3) then "three-of-a-kind" + else "two-pairs" + end + elif length == 4 + then "one-pair" + else ($cards|[isFlush, isStraight]) as [$flush, $straight] + | if $flush and $straight then "straight-flush" + elif $flush then "flush" + elif $straight then "straight" + else "high-card" + end + end + end ; + +def hands: [ + "2h 2d 2c kc qd", + "2h 5h 7d 8c 9s", + "ah 2d 3c 4c 5d", + "2h 3h 2d 3c 3d", + "2h 7h 2d 3c 3d", + "2h 7h 7d 7c 7s", + "th jh qh kh ah", + "4h 4s ks 5d ts", + "qc tc 7c 6c 4c", + "ah ah 7c 6c 4c" +]; + +hands[] +| "\(.): \(analyzeHand)" diff --git a/Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic b/Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic new file mode 100644 index 0000000000..d0798cdfb2 --- /dev/null +++ b/Task/Poker-hand-analyser/Liberty-BASIC/poker-hand-analyser.basic @@ -0,0 +1,371 @@ +NoMainWin +WindowWidth=900 +WindowHeight=720 +BackgroundColor$ = "191 191 255" ' buttonface default +Global Deck, MaxDecks + +StaticText #1.Debug "", 0, 0, 600, 20 +StaticText #1.StaticText "Ten Decks of Poker Hands", 50, 50, 3000, 40 +Button #1.Deal "Deal", [Start], UL, 700, 180, 80, 40 +Button #1.TenThousand "10,000", [TenThousand], UL, 700, 250, 80, 40 +Button #1.Stats "History", ShowStats, UL, 700, 320, 80, 40 +Button #1.Quit "Quit", Quit, UL, 700, 390, 80, 40 +TextEditor #1.TextEditor 50, 100, 600, 500 + +open "POKER HANDS" for dialog as #1 +#1 "TrapClose Quit" +#1 "Font Ariel 12 Bold" +#1.StaticText "!Font Ariel 16 Bold" +#1.TextEditor "!Font Courier_New 14 Bold" +if not(exists("Poker Hands.txt")) then #1.Stats "!Disable" +MaxDecks=10 +wait + +[TenThousand] +TenThousand = 1 +[Start] +if TenThousand then + MaxDecks=10000 + #1.TextEditor "!Hide" + #1.Deal "!Hide" + #1.TenThousand "!Hide" + #1.Stats "!Hide" + #1.Quit "!Hide" + #1.StaticText "Ten Thousand Decks of Poker Hands" +end if +Deck += 1 +if TenThousand then #1.Debug Str$(Deck) +if Deck>MaxDecks then Deck -= 1: call Quit +#1.TextEditor "!cls" +call ShuffleDeck 0 +'call TestDeck +NextCard=1 +for y=1 to 10 + for x=1 to 5 + y$ = A$(NextCard) + B$(x) = ConvertHiCard$(y$) + NextCard += 1 + next x + sort B$(), 1, 5 + for x=NextCard-5 to NextCard-1 + #1.TextEditor A$(x)+" "; + next x + #1.TextEditor " "; + + Values$="" 'determine high value of hand + for x=1 to 5 + Values$ = Values$ + left$(B$(x),1) + next x + HiValue$ = RealValue$(right$(Values$,1)) + + z=0: Flush=0: Straight=0: Royal=0: FourKind=0 + ThreeKind=0: Pair=0: TwoPair=0: FullHouse=0 + if Flush() then Flush=1 + x = Straight() + if x then Straight=1: if x=9 then Royal=1 + z$ = Kind$() + Value$ = RealValue$(right$(z$,1)) + z=val(left$(z$, len(z$)-1)) + if z=41 then FourKind=1 + if z=32 then FullHouse=1 + if z=31 then ThreeKind=1 + if z=22 then TwoPair=1 + if z=21 then Pair=1 + + select case + case Straight and Royal and Flush: #1.TextEditor "Royal Flush": Stats(1) += 1 + case Straight and Flush: #1.TextEditor "Straight Flush, " + HiValue$ + " high": Stats(2) += 1 + case FourKind: #1.TextEditor "Four of a kind, " + Value$ + "s": Stats(3) += 1 + case FullHouse: #1.TextEditor "Full House, " + Value$ + "s high": Stats(4) += 1 + case Flush: #1.TextEditor "Flush, " + HiValue$ + " high": Stats(5) += 1 + case Straight: #1.TextEditor "Straight, " + HiValue$ + " high": Stats(6) += 1 + case ThreeKind: #1.TextEditor "Three of a kind, " + Value$ + "s": Stats(7) += 1 + case TwoPair: #1.TextEditor "Two Pair, " + Value$ + " high": Stats(8) += 1 + case Pair: #1.TextEditor "Pair " + Value$ + "s": Stats(9) += 1 + case else: #1.TextEditor HiValue$ + " high" + end select +next y +#1.TextEditor "" +#1.TextEditor "Deck #" + str$(Deck) +if TenThousand then goto [Start] else wait + +function RealValue$(Value$) + select case Value$ + case "A": RealValue$="T" + case "B": RealValue$="J" + case "C": RealValue$="Q" + case "D": RealValue$="K" + case "E": RealValue$="A" + case else: RealValue$=Value$ + end select +end function + +sub SaveStats Deck + Stats(0) = 10*Deck + if not(exists("Poker Hands.txt")) then + open "Poker Hands.txt" for output as #2 + for x=0 to 9 + print #2 Stats(x) + next + close #2 + #1.Stats "!Enable" + else + open "Poker Hands.txt" for input as #2 + for x=0 to 9 + input #2 History(x) + next + close #2 + for x=0 to 9 + History(x) += Stats(x) + next + open "Poker Hands.txt" for output as #2 + for x=0 to 9 + print #2 History(x) + next + close #2 + end if +end sub + +sub ShowStats + if exists("Poker Hands.txt") then + open "Poker Hands.txt" for input as #2 + for x=0 to 9 + input #2 History(x) + next + close #2 + #1.TextEditor "!cls" + + for x=1 to 9 + Total += History(x) + next x + Nothing = History(0) - Total + + for x=0 to 9 + #1.TextEditor using("###,### ", History(x)); + select case x + case 0: #1.TextEditor "hands " + case 1: #1.TextEditor "royal flush " + using("##.# %", History(x)/History(0)*100) + case 2: #1.TextEditor "straight flush " + using("##.# %", History(x)/History(0)*100) + case 3: #1.TextEditor "four of a kind " + using("##.# %", History(x)/History(0)*100) + case 4: #1.TextEditor "full house " + using("##.# %", History(x)/History(0)*100) + case 5: #1.TextEditor "flush " + using("##.# %", History(x)/History(0)*100) + case 6: #1.TextEditor "straight " + using("##.# %", History(x)/History(0)*100) + case 7: #1.TextEditor "three of a kind " + using("##.# %", History(x)/History(0)*100) + case 8: #1.TextEditor "two pair " + using("##.# %", History(x)/History(0)*100) + case 9: #1.TextEditor "pair " + using("##.# %", History(x)/History(0)*100) + end select + next + #1.TextEditor using("###,### ", Nothing) + "nothing " + using("###.# %", Nothing/History(0)*100) + end if +end sub + +function Kind$() + for x=1 to 5 + C$(x) = left$(B$(x), 1) + next x + if C$(1) = C$(2) then 'check for Lo4 + Lo2=1 + if C$(2) = C$(3) then + Lo2=0: Lo3=1 + if C$(3) = C$(4) then + Lo3=0: Kind$="41" + left$(C$(4),1): exit function + end if + end if + end if + + if C$(5) = C$(4) then 'check for Hi4 + Hi2=1 + if C$(4) = C$(3) then + Hi2=0: Hi3=1 + if C$(3) = C$(2) then + Hi3=0: Kind$="41" + left$(C$(5),1): exit function + end if + end if + end if + + if Lo3 then 'check for Full House and 3Kind + if C$(4) = C$(5) then + Kind$="32" + left$(C$(3),1): exit function + else + Kind$="31" + left$(C$(3),1): exit function + end if + end if + if Hi3 then + if C$(1) = C$(2) then + Kind$="32" + left$(C$(5),1): exit function + else + Kind$="31" + left$(C$(5),1): exit function + end if + end if + if C$(2) = C$(3) and C$(3) = C$(4) then 'Mid3 + Kind$="31" + left$(C$(4),1): exit function + end if + + if Lo2 and Hi2 then 'check for pairs + Kind$="22" + left$(C$(5),1): exit function + end if + if Lo2 and (C$(3)=C$(4)) then + Kind$="22" + left$(C$(4),1): exit function + end if + if Hi2 and (C$(3)=C$(2)) then + Kind$="22" + left$(C$(5),1): exit function + end if + + if Lo2 then Kind$="21" + left$(C$(2),1) + if Hi2 then Kind$="21" + left$(C$(5),1) + if C$(2)=C$(3) then Kind$="21" + left$(C$(3),1) + if C$(3)=C$(4) then Kind$="21" + left$(C$(4),1) +end function + +function Straight() + Order$="23456789ABCDEF" + for x=1 to 5 + Ranks$ = Ranks$ + left$(B$(x), 1) + next x + x = instr(Order$, Ranks$) + if x then Straight=x +end function + +function Flush() + Flush=1 + for x=1 to 5 + Suits$ = Suits$ + right$(B$(x), 1) + next x + for x=2 to 5 + if mid$(Suits$, x, 1) <> left$(Suits$, 1) then Flush=0: exit function + next x +end function + +sub ShuffleDeck Jokers + Jokers = int(abs(Jokers)): if Jokers>4 then Jokers=4 + Size=52 + Jokers + dim CardDeck$(Size+10,1), A$(Size+10) 'Open new card deck +[Start] + for x=1 to Size + CardDeck$(x,0) = "99" + next x + + for x=1 to Size + 1 y=RandomNumber(1,Size) + if CardDeck$(y,0)="99" then CardDeck$(y,0)=str$(x) else goto 1 + next x + + for x=1 to Size 'Examine shuffled deck + if CardDeck$(x,0)=str$(x) then z = 1: exit for + next x + if z then z=0: goto [Start] + for x=1 to Size 'Save shuffled deck + A$(x) = CardFace$(val(CardDeck$(x,0))) + next x + A$(0) = str$(Size) +end sub + +function CardFace$(n) + select case n + case 1: CardFace$="AD" + case 2: CardFace$="2D" + case 3: CardFace$="3D" + case 4: CardFace$="4D" + case 5: CardFace$="5D" + case 6: CardFace$="6D" + case 7: CardFace$="7D" + case 8: CardFace$="8D" + case 9: CardFace$="9D" + case 10: CardFace$="TD" + case 11: CardFace$="JD" + case 12: CardFace$="QD" + case 13: CardFace$="KD" + case 14: CardFace$="AC" + case 15: CardFace$="2C" + case 16: CardFace$="3C" + case 17: CardFace$="4C" + case 18: CardFace$="5C" + case 19: CardFace$="6C" + case 20: CardFace$="7C" + case 21: CardFace$="8C" + case 22: CardFace$="9C" + case 23: CardFace$="TC" + case 24: CardFace$="JC" + case 25: CardFace$="QC" + case 26: CardFace$="KC" + case 27: CardFace$="AH" + case 28: CardFace$="2H" + case 29: CardFace$="3H" + case 30: CardFace$="4H" + case 31: CardFace$="5H" + case 32: CardFace$="6H" + case 33: CardFace$="7H" + case 34: CardFace$="8H" + case 35: CardFace$="9H" + case 36: CardFace$="TH" + case 37: CardFace$="JH" + case 38: CardFace$="QH" + case 39: CardFace$="KH" + case 40: CardFace$="AS" + case 41: CardFace$="2S" + case 42: CardFace$="3S" + case 43: CardFace$="4S" + case 44: CardFace$="5S" + case 45: CardFace$="6S" + case 46: CardFace$="7S" + case 47: CardFace$="8S" + case 48: CardFace$="9S" + case 49: CardFace$="TS" + case 50: CardFace$="JS" + case 51: CardFace$="QS" + case 52: CardFace$="KS" + case 53: CardFace$="X1" + case 54: CardFace$="X2" + case 55: CardFace$="X3" + case 56: CardFace$="X4" + end select +end function + +function RandomNumber(a, b) + smaller = min(a, b) + range = abs(int(a-b))+1 + if range < 1 then exit function + r = int(rnd()*range) + RandomNumber = r + smaller +end function + +function ConvertHiCard$(Card$) + select case left$(Card$,1) + case "T": left$(Card$,1)="A" + case "J": left$(Card$,1)="B" + case "Q": left$(Card$,1)="C" + case "K": left$(Card$,1)="D" + case "A": left$(Card$,1)="E" + case "X": left$(Card$,1)="F" + end select + ConvertHiCard$ = Card$ +end function + +sub TestDeck + data KD, KC, KS, AH, AS ' full house + data 6D, 6C, 6S, 6H, 8H ' four of a kind (io) + data 2D, 4S, 4C, TH, TD ' two pair + data 4H, 5H, 6H, 7H, 8H ' straight flush + data 9S, QD, QC, QH, 3D ' three of a kind + data 6H, 7D, 8C, 9C, TS ' straight + data TH, AH, AS, AC, AD ' four of a kind (hI) + data 3S, 5S, 7S, 9S, JS ' flush + data AD, KD, QD, JD, TD ' royal flush + data 2C, 2D, 3H, 4S, 5C ' one pair + dim A$(50) + for x=1 to 50 + read A$(x) + next x +end sub + +function exists(FileName$) + files "", FileName$, FileDir$() + FileCount$ = FileDir$(0, 0) + exists = val(FileCount$) +end function + +sub Quit + if Deck = MaxDecks then call SaveStats Deck + close #1 + end +end sub diff --git a/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 b/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 new file mode 100644 index 0000000000..95ceb38d34 --- /dev/null +++ b/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 @@ -0,0 +1,86 @@ +string 0; \Use null-terminated strings (vs MSB terminated) +int Count(1+18); \Counts of ranks and suits in a hand + +proc ShowCat; \Show category of poker hand +int I, J; +[for I:= 1 to 14 do + [if Count(I) = 1 then + [for J:= I+1 to I+4 do \are next 4 cards present? + if Count(J) # 1 then J:= 100; + if J <= 100 then + [Text(0, "straight"); + for J:= 15 to 18 do \scan suits + if Count(J) >= 4 then Text(0, "-flush"); + return; + ]; + ]; + ]; +for I:= 15 to 18 do + if Count(I) = 4 then [Text(0, "flush"); return]; +for I:= 1 to 14 do \scan ranks + if Count(I) = 4 then + [Text(0, "four-of-a-kind"); return]; +for I:= 1 to 14 do + [if Count(I) = 3 then + [for J:= 1 to 14 do + if Count(J) = 2 then + [Text(0, "full-house"); return]; + Text(0, "three-of-a-kind"); return; + ]; + ]; +for I:= 1 to 14 do + [if Count(I) = 2 then + [for J:= 1 to 14 do + if J # I and Count(J) = 2 then + [Text(0, "two-pairs"); return]; + Text(0, "one-pair"); return; + ]; + ]; +Text(0, "high-card"); +]; + +int Hands, H, Card, I, Char, N, Invalid, Valid(4), Suit, Rank; +char Str; +[Hands:= [ + "2h 2d 2c kc qd ", + "2h 5h 7d 8c 9s ", + "ah 2d 3c 4c 5d ", + "2h 3h 2d 3c 3d ", + "2h 7h 2d 3c 3d ", + "2h 7h 7d 7c 7s ", + "10h jh qh kh ah ", + "4h 4s ks 5d 10s ", + "qc 10c 7c 6c qc "]; +for H:= 0 to 9-1 do + [for I:= 0 to 18 do Count(I):= 0; + for I:= 0 to 3 do Valid(I):= 0; + Invalid:= false; + Str:= Hands(H); + Card:= 0; I:= 0; + loop [Char:= Str(I); I:= I+1; + case Char of + ^h: N:= 18; + ^d: N:= 17; + ^c: N:= 16; + ^s: N:= 15; + ^a: N:= 14; + ^k: N:= 13; + ^q: N:= 12; + ^j: N:= 11; + ^1: N:= 10; + ^ : [N:= 0; Card:= Card+1; if Card >= 5 then quit] + other N:= Char-^0; + Count(N):= Count(N)+1; + if N = 14 then Count(1):= Count(1)+1; \two-place ace + if N <= 14 then Rank:= N + else [Suit:= N - 15; + if Valid(Suit) and 1<; + lst.Add(new Base(3)); + lst.Add(new Derived(4,5.5)); + lst.Add(new Base(6)); + lst.Add(new Derived(7,8.8)); + lst.Println; + var lst1 := new List; + foreach var obj in lst do + lst1.Add(obj.Clone); + lst1.Println; +end. diff --git a/Task/Polymorphism/PascalABC.NET/polymorphism.pas b/Task/Polymorphism/PascalABC.NET/polymorphism.pas new file mode 100644 index 0000000000..97d78c8985 --- /dev/null +++ b/Task/Polymorphism/PascalABC.NET/polymorphism.pas @@ -0,0 +1,36 @@ +type + Point = class + public + auto property x: real; + auto property y: real; + constructor (x,y: real); + begin + Self.x := x; Self.y := y; + end; + procedure Print; virtual; + begin + PABCSystem.Print(x,y); + end; + end; + Circle = class(Point) + public + auto property r: real; + constructor (x,y,r: real); + begin + inherited Create(x,y); + Self.r := r; + end; + procedure Print; override; + begin + inherited Print; + PABCSystem.Print(r); + end; + end; + +begin + var p: Point := new Point(3,5); + var c: Circle := new Circle(10,8,4); + p.Print; + Println; + c.Print; +end. diff --git a/Task/Polynomial-regression/Jq/polynomial-regression.jq b/Task/Polynomial-regression/Jq/polynomial-regression.jq new file mode 100644 index 0000000000..7023590262 --- /dev/null +++ b/Task/Polynomial-regression/Jq/polynomial-regression.jq @@ -0,0 +1,47 @@ +def mean: add/length; + +def inner_product($y): + . as $x + | reduce range(0; length) as $i (0; . + ($x[$i] * $y[$i])); + +# $x and $y should be arrays of the same length +# Emit { a, b, c, z} +# Attempt to avoid overflow +def polynomialRegression($x; $y): + ($x | length) as $length + | ($length * $length) as $l2 + | ($x | map(./$length)) as $xs + | ($xs | add) as $xm + | ($y | mean) as $ym + | ($xs | map(. * .) | add * $length) as $x2m + | ($x | map( (./$length) * . * .) | add) as $x3m + | ($xs | map(. * . | (.*.) ) | add * $l2 * $length) as $x4m + | ($xs | inner_product($y)) as $xym + | ($xs | map(. * .) | inner_product($y) * $length) as $x2ym + + | ($x2m - $xm * $xm) as $sxx + | ($xym - $xm * $ym) as $sxy + | ($x3m - $xm * $x2m) as $sxx2 + | ($x4m - $x2m * $x2m) as $sx2x2 + | ($x2ym - $x2m * $ym) as $sx2y + | {z: ([$x,$y] | transpose) } + | .b = ($sxy * $sx2x2 - $sx2y * $sxx2) / ($sxx * $sx2x2 - $sxx2 * $sxx2) + | .c = ($sx2y * $sxx - $sxy * $sxx2) / ($sxx * $sx2x2 - $sxx2 * $sxx2) + | .a = $ym - .b * $xm - .c * $x2m ; + +# Input: {a,b,c,z} +def report: + def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + def abc($x): .a + .b * $x + .c * $x * $x; + def print($p): "\($p[0] | lpad(3)) \($p[1] | lpad(4)) \(abc($p[0]) | lpad(5))"; + + "y = \(.a) + \(.b)x + \(.c)x^2\n", + " Input Approximation", + " x y y\u0302", + print(.z[]) ; + +def x: [range(0;11)]; +def y: [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; + +polynomialRegression(x; y) +| report diff --git a/Task/Population-count/ABC/population-count.abc b/Task/Population-count/ABC/population-count.abc new file mode 100644 index 0000000000..9143a24f93 --- /dev/null +++ b/Task/Population-count/ABC/population-count.abc @@ -0,0 +1,25 @@ +HOW TO RETURN popcount n: + IF n=0: RETURN 0 + RETURN (n mod 2) + popcount (floor (n/2)) + +HOW TO REPORT evil n: + REPORT (popcount n) mod 2 = 0 + +HOW TO REPORT odious n: + REPORT (popcount n) mod 2 = 1 + +FOR i IN {0..29}: WRITE popcount (3 ** i) +WRITE / + +PUT {} IN evilnums +PUT {} IN odiousnums + +FOR n IN {0..59}: + SELECT: + evil n: INSERT n IN evilnums + odious n: INSERT n IN odiousnums + +FOR i IN {1..30}: WRITE evilnums item i +WRITE / +FOR i IN {1..30}: WRITE odiousnums item i +WRITE / diff --git a/Task/Population-count/Refal/population-count.refal b/Task/Population-count/Refal/population-count.refal new file mode 100644 index 0000000000..a5bbd78cdf --- /dev/null +++ b/Task/Population-count/Refal/population-count.refal @@ -0,0 +1,41 @@ +$ENTRY Go { + = > + > + >; +}; + +Gen { + 0 s.Fil s.Gen (s.State) = ; + s.N s.Fil s.Gen (s.State), + : (s.Next) s.Item, + : { + T = s.Item s.Fil s.Gen (s.Next)>; + F = ; + }; +}; + +Popcount { + 0 = 0; + s.N, : (s.R) s.B = <+ s.B >; +}; + +Pow3 { + s.N = (<* 3 s.N>) ; +}; + +Evil { + s.N, 2>: { + 0 = T; + 1 = F; + }; +}; + +Odious { + s.N, 2>: { + 0 = F; + 1 = T; + }; +}; + +All { s.X = T; } +Iota { s.N = (<+ 1 s.N>) s.N; } diff --git a/Task/Power-set/PascalABC.NET/power-set.pas b/Task/Power-set/PascalABC.NET/power-set.pas new file mode 100644 index 0000000000..bbbb0950b0 --- /dev/null +++ b/Task/Power-set/PascalABC.NET/power-set.pas @@ -0,0 +1,16 @@ +function AllSubSets(a: array of T; i: integer; lst: List): sequence of List; +begin + if i = a.Length then + begin + yield lst; + exit; + end; + lst.Add(a[i]); + yield sequence AllSubSets(a, i + 1, lst); + lst.RemoveAt(lst.Count-1); + yield sequence AllSubSets(a, i + 1, lst); +end; + +begin + AllSubSets(Arr(1..4),0,new List).Print; +end. diff --git a/Task/Price-fraction/Chipmunk-Basic/price-fraction.basic b/Task/Price-fraction/Chipmunk-Basic/price-fraction.basic new file mode 100644 index 0000000000..c528b1fa2f --- /dev/null +++ b/Task/Price-fraction/Chipmunk-Basic/price-fraction.basic @@ -0,0 +1,22 @@ +100 cls +110 data 10,18,26,32,38,44,50,54,58,62,66,70,74,78,82,86,90,94,98,100 +120 data 6,11,16,21,26,31,36,41,46,51,56,61,66,71,76,81,86,91,96 +130 dim od(21) +140 for i = 1 to 20 +150 read olddec +160 od(i) = olddec +170 next i +180 dim nd(20) +190 for j = 1 to 19 +200 read nuedec +210 nd(j) = nuedec +220 next j +230 for i = 1 to 100 +240 for j = 1 to ubound(nd)-1 +250 if i < nd(j) then exit for +260 next j +270 print using "#.##";(i/100);" -> "; +280 print using "#.##";(od(j)/100);chr$(9); +290 if i mod 5 = 0 then print +300 next i +310 end diff --git a/Task/Price-fraction/Langur/price-fraction-1.langur b/Task/Price-fraction/Langur/price-fraction-1.langur new file mode 100644 index 0000000000..d4550892e7 --- /dev/null +++ b/Task/Price-fraction/Langur/price-fraction-1.langur @@ -0,0 +1,33 @@ +val table = [ + {"low": 0.00, "high": 0.06, "use": 0.10}, + {"low": 0.06, "high": 0.11, "use": 0.18}, + {"low": 0.11, "high": 0.16, "use": 0.26}, + {"low": 0.16, "high": 0.21, "use": 0.32}, + {"low": 0.21, "high": 0.26, "use": 0.38}, + {"low": 0.26, "high": 0.31, "use": 0.44}, + {"low": 0.31, "high": 0.36, "use": 0.50}, + {"low": 0.36, "high": 0.41, "use": 0.54}, + {"low": 0.41, "high": 0.46, "use": 0.58}, + {"low": 0.46, "high": 0.51, "use": 0.62}, + {"low": 0.51, "high": 0.56, "use": 0.66}, + {"low": 0.56, "high": 0.61, "use": 0.70}, + {"low": 0.61, "high": 0.66, "use": 0.74}, + {"low": 0.66, "high": 0.71, "use": 0.78}, + {"low": 0.71, "high": 0.76, "use": 0.82}, + {"low": 0.76, "high": 0.81, "use": 0.86}, + {"low": 0.81, "high": 0.86, "use": 0.90}, + {"low": 0.86, "high": 0.91, "use": 0.94}, + {"low": 0.91, "high": 0.96, "use": 0.98}, + {"low": 0.96, "high": 1.00, "use": 1.00}, + ] + +val pricefrac = fn f: { + if f == 1.00: return 1.00 + for h in table { + if f >= h'low and f < h'high: return h'use + } + throw "no match" +} + +writeln pricefrac(0.17) +writeln pricefrac(0.71) diff --git a/Task/Price-fraction/Langur/price-fraction-2.langur b/Task/Price-fraction/Langur/price-fraction-2.langur new file mode 100644 index 0000000000..88ca5bf89e --- /dev/null +++ b/Task/Price-fraction/Langur/price-fraction-2.langur @@ -0,0 +1,35 @@ +val table = [ + # [low, use] + [0.00, 0.10], + [0.06, 0.18], + [0.11, 0.26], + [0.16, 0.32], + [0.21, 0.38], + [0.26, 0.44], + [0.31, 0.50], + [0.36, 0.54], + [0.41, 0.58], + [0.46, 0.62], + [0.51, 0.66], + [0.56, 0.70], + [0.61, 0.74], + [0.66, 0.78], + [0.71, 0.82], + [0.76, 0.86], + [0.81, 0.90], + [0.86, 0.94], + [0.91, 0.98], + [0.96, 1.00], + ] + +val pricefrac = fn f: { + if f >= table[-1][1] and f <= table[-1][2]: return table[-1][2] + + for t of len(table)-1 { + if f >= table[t][1] and f < table[t+1][1]: return table[t][2] + } + throw "no match" +} + +writeln pricefrac(0.17) +writeln pricefrac(0.71) diff --git a/Task/Price-fraction/Langur/price-fraction.langur b/Task/Price-fraction/Langur/price-fraction.langur deleted file mode 100644 index 6c1ee0d357..0000000000 --- a/Task/Price-fraction/Langur/price-fraction.langur +++ /dev/null @@ -1,26 +0,0 @@ -val .pricefrac = fn(.f) switch[and] .f { - case >= 0.00, < 0.06: 0.10 - case >= 0.06, < 0.11: 0.18 - case >= 0.11, < 0.16: 0.26 - case >= 0.16, < 0.21: 0.32 - case >= 0.21, < 0.26: 0.38 - case >= 0.26, < 0.31: 0.44 - case >= 0.31, < 0.36: 0.50 - case >= 0.36, < 0.41: 0.54 - case >= 0.41, < 0.46: 0.58 - case >= 0.46, < 0.51: 0.62 - case >= 0.51, < 0.56: 0.66 - case >= 0.56, < 0.61: 0.70 - case >= 0.61, < 0.66: 0.74 - case >= 0.66, < 0.71: 0.78 - case >= 0.71, < 0.76: 0.82 - case >= 0.76, < 0.81: 0.86 - case >= 0.81, < 0.86: 0.90 - case >= 0.86, < 0.91: 0.94 - case >= 0.91, < 0.96: 0.98 - case >= 0.96, <= 1.00: 1.00 - default: throw "bad data" -} - -writeln .pricefrac(0.17) -writeln .pricefrac(0.71) diff --git a/Task/Price-fraction/QB64/price-fraction.qb64 b/Task/Price-fraction/QB64/price-fraction.qb64 new file mode 100644 index 0000000000..c8ed1f47cc --- /dev/null +++ b/Task/Price-fraction/QB64/price-fraction.qb64 @@ -0,0 +1,19 @@ +Data 10,18,26,32,38,44,50,54,58,62,66,70,74,78,82,86,90,94,98,100 +Data 6,11,16,21,26,31,36,41,46,51,56,61,66,71,76,81,86,91,96 +Dim od(21) +For i = 1 To 20 + Read olddec + od(i) = olddec +Next i +Dim nd(20) +For j = 1 To 19 + Read nuedec + nd(j) = nuedec +Next j +For i = 1 To 100 + For j = 1 To UBound(nd) - 1 + If i < nd(j) Then Exit For + Next j + Print Using "#.## -> #.##"; (i / 100); (od(j) / 100); + If i Mod 5 = 0 Then Print Else Print Chr$(9); +Next i diff --git a/Task/Primality-by-trial-division/GW-BASIC/primality-by-trial-division.basic b/Task/Primality-by-trial-division/GW-BASIC/primality-by-trial-division.basic new file mode 100644 index 0000000000..e0c4cd0c6a --- /dev/null +++ b/Task/Primality-by-trial-division/GW-BASIC/primality-by-trial-division.basic @@ -0,0 +1,11 @@ +100 FOR I = 1 TO 99 +110 IF I < 2 THEN P = 0 : GOTO 180 +120 IF I = 2 THEN P = 1 : GOTO 180 +130 IF I MOD 2 = 0 THEN P = 0 : GOTO 180 +140 P = 1 +150 FOR J = 3 TO SQR(I) STEP 2 +160 IF I MOD J = 0 THEN P = 0 : GOTO 180 +170 NEXT J +180 IF P <> 0 THEN PRINT I; +190 NEXT I +200 END diff --git a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur index 8f9728d4a2..747b0d4414 100644 --- a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur +++ b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur @@ -1,4 +1,6 @@ -val .isPrime = fn(.i) .i == 2 or .i > 2 and - not any fn(.x) .i div .x, pseries 2 .. .i ^/ 2 +val isPrime = fn(i) { + i == 2 or i > 2 and + not any(fn x:i div x, pseries(2 .. i ^/ 2)) +} -writeln filter .isPrime, series 100 +writeln filter(isPrime, series(100)) diff --git a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur index 30818edf41..678610b891 100644 --- a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur +++ b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur @@ -1,15 +1,15 @@ -val .isPrime = fn(.i) { - val .n = abs(.i) - if .n <= 2: return .n == 2 +val isPrime = fn(i) { + val n = abs(i) + if n <= 2: return n == 2 - val .chkdiv = fn(.n, .i) { - if .i * .i <= .n { - return .n ndiv .i and self(.n, .i+2) + val chkdiv = fn(n, i) { + if i * i <= n { + return n ndiv i and fn((n, i+2)) } return true } - return .n ndiv 2 and .chkdiv(.n, 3) + return n ndiv 2 and chkdiv(n, 3) } -writeln filter .isPrime, series 100 +writeln filter(isPrime, series(100)) diff --git a/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas b/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas new file mode 100644 index 0000000000..fc3525df36 --- /dev/null +++ b/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas @@ -0,0 +1,18 @@ +function IsPrime(N: integer): boolean; +begin + if N = 1 then + Result := False + else Result := True; + for var i:=2 to N.Sqrt.Round do + if N.Divs(i) then + begin + Result := False; + exit + end; +end; + +begin + for var i:=1 to 1000 do + if IsPrime(i) then + Print(i) +end. diff --git a/Task/Prime-decomposition/PascalABC.NET/prime-decomposition.pas b/Task/Prime-decomposition/PascalABC.NET/prime-decomposition.pas new file mode 100644 index 0000000000..fcc3fbc995 --- /dev/null +++ b/Task/Prime-decomposition/PascalABC.NET/prime-decomposition.pas @@ -0,0 +1,19 @@ +function Factors(N: BigInteger): List; +begin + var lst := new List; + if N = 1 then + lst.Add(N); + var i := 2bi; + while i * i <= N do + begin + while N mod i = 0 do + begin + lst.Add(i); + N := N div i; + end; + i += 1; + end; + if N >= 2 then + lst.Add(N); + Result := lst; +end; diff --git a/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx b/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx index e69de29bb2..dcbc1d8c1d 100644 --- a/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx +++ b/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx @@ -0,0 +1,82 @@ +/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ +Numeric Digits 1000 /*handle thousand digits For the powers*/ +Parse Arg bot top step base add /*get optional arguments from the C.L. */ +If bot='?' Then Do + Say 'rexx pfoo bot top step base add' + Exit + End +If bot=='' Then /* no arguments given */ + Parse Value 1 100 With bot top /* set default range .*/ +If top=='' Then top=bot /* process one number */ +If step=='' Then step=1 /* step=2 to process only odd numbers */ +If add =='' Then add=-1 /* for Mersenne tests */ +tell=top>0 /*If TOP is negative, suppress displays*/ +top=abs(top) +w=length(top) /*get maximum width For aligned display*/ +If base\=='' Then + w=length(base**top) /*will be testing powers of two later? */ +tag.=left('', 7) /*some literals: pad; prime (or not).*/ +tag.0='{unity}' +tag.1='[prime]' +Numeric Digits max(9,w+1) /*maybe increase the digits precision. */ +np=0 /*np: is the number of primes found.*/ +Do n=bot To top by step /*process a single number or a range. */ + ?=n + If base\=='' Then /*should we perform a 'Mersenne' test? */ + ?=base**n+add + pf=factr(?) /* get prime factors */ + f=words(pf) /* number of prime factors */ + If f=1 Then /* If the number is prime */ + np=np+1 /* Then bump prime counter */ + If tell Then + Say right(?,w) right('('f')',9) 'prime factors: ' tag.f pf + End /*n*/ +Say '' +ps='prime' +If f>1 Then ps=ps's' /*setup For proper English in sentence.*/ +Say right(np, w+9+1) ps 'found.' /*display the number of primes found. */ +Exit /*stick a fork in it, we're all done. */ +/*---------------------------------------------------------------------------*/ +factr: Procedure + Parse Arg x 1 d,pl /*set X, D to argument 1, pl to null */ + If x==1 Then Return '' /*handle the special case of X=1. */ + primes=2 3 5 7 + Do While primes>'' /* first check the small primes */ + Parse Var primes prime primes + Do While x//prime==0 + pl=pl prime + x=x%prime + End + End + r=isqrt(x) + Do j=11 by 6 To r /*insure that J isn't divisible by 3. */ + Parse var j '' -1 _ /*obtain the last decimal digit of J. */ + If _\==5 Then Do + Do While x//j==0 + pl=pl j + x=x%j + End /*maybe reduce by J. */ + End + If _ ==3 Then Iterate /*If next Y is divisible by 5? Skip. */ + y=j+2 + Do While x//y==0 + pl=pl y + x=x%y + End /*maybe reduce by y. */ + End /*j*/ + + If x==1 Then Return pl /*Is residual=unity? Then don't append.*/ + Return pl x /*return pl with appended residual.*/ + +isqrt: Procedure + Parse Arg x + x=abs(x) + Parse Value 0 x with lo hi + Do While lo<=hi + t=(lo+hi)%2 + If t**2>x Then + hi=t-1 + Else + lo=t+1 + End + Return t diff --git a/Task/Prime-decomposition/REXX/prime-decomposition-3.rexx b/Task/Prime-decomposition/REXX/prime-decomposition-3.rexx new file mode 100644 index 0000000000..86902ca626 --- /dev/null +++ b/Task/Prime-decomposition/REXX/prime-decomposition-3.rexx @@ -0,0 +1,69 @@ +/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ +call time('r') +Numeric Digits 1000 /*handle thousand digits For the powers*/ +Parse Arg bot top step base add /*get optional arguments from the C.L. */ +If bot='?' Then Do + Say 'rexx pfoo bot top step base add' + Exit + End +If bot=='' Then /* no arguments given */ + Parse Value 1 100 With bot top /* set default range .*/ +If top=='' Then top=bot /* process one number */ +If step=='' Then step=1 /* step=2 to process only odd numbers */ +If add =='' Then add=-1 /* for Mersenne tests */ +tell=top>0 /*If TOP is negative, suppress displays*/ +top=abs(top) +w=length(top) /*get maximum width For aligned display*/ +If base\=='' Then + w=length(base**top) /*will be testing powers of two later? */ +tag.=left('', 7) /*some literals: pad; prime (or not).*/ +tag.0='{unity}' +tag.1='[prime]' +Numeric Digits max(9,w+1) /*maybe increase the digits precision. */ +np=0 /*np: is the number of primes found.*/ +Do n=bot To top by step /*process a single number or a range. */ + ?=n + If base\=='' Then /*should we perform a 'Mersenne' test? */ + ?=base**n+add + pf=factr(?) /* get prime factors */ + f=words(pf) /* number of prime factors */ + If f=1 Then /* If the number is prime */ + np=np+1 /* Then bump prime counter */ + If tell Then + Say right(?,w) right('('f')',9) 'prime factors: ' tag.f pf + End /*n*/ +Say '' +ps='prime' +If f>1 Then ps=ps's' /*setup For proper English in sentence.*/ +Say right(np, w+9+1) ps 'found.' /*display the number of primes found. */ +say format(time('e'),,3) 'seconds' +Exit /*stick a fork in it, we're all done. */ +/*---------------------------------------------------------------------------*/ +Factr: +procedure expose glob. +arg x +primes = '2 3 5 7 11 13 17 19 23'; pl = '' +do n = 1 to words(primes) + prime = word(primes,n) + do while x//prime = 0 + pl = pl prime; x = x%prime + end +end +do j = 29 by 6 while j*j <= x + d = right(j,1) + if d <> 5 then do + do while x//j = 0 + pl = pl j; x = x%j + end + end + if d = 3 then + iterate + y = j+2 + do while x//y = 0 + pl = pl y; x = x%y + end +end +if x = 1 then + return pl +else + return pl x diff --git a/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Sidef/prime-numbers-whose-neighboring-pairs-are-tetraprimes.sidef b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Sidef/prime-numbers-whose-neighboring-pairs-are-tetraprimes.sidef new file mode 100644 index 0000000000..bfef71add5 --- /dev/null +++ b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Sidef/prime-numbers-whose-neighboring-pairs-are-tetraprimes.sidef @@ -0,0 +1,34 @@ +func display(arr, p, f, g, type, limit, display_primes) { + + var s = arr.map(f).grep{.is_prime} + print "Found #{s.len.commify} primes under #{limit.commify} whose #{type} neighboring pair are tetraprimes" + + if (display_primes) { + say ':' + s.slices(10).each{.map { "%#{limit.len+1}s" % _ }.join.say } + } + + with (p) {|p| + var c = s.count {|a| is_div(g(a), p) || is_div(g(g(a)), p) } + say "\nof which #{c.commify} have a neighboring pair one of whose factors is #{p}.\n" + } + + var D = s.diffs + + func median(a) { + var l = a.len + var j = l>>1 + l.is_even ? ((a[j-1] + a[j]) >> 1) : a[j] + } + + say("Minimum gap between those #{s.len.commify} primes: ", D.min) + say("Median gap between those #{s.len.commify} primes: ", median(D.sort)) + say("Maximum gap between those #{s.len.commify} primes: ", D.max) + say '' +} + +for limit in (1e5, 1e6, 1e7) { + var arr = 4.squarefree_almost_primes(limit).cons(2).grep_2d{|a,b| b-a == 1 } + display(arr, 7, {.last.inc}, {.dec}, "preceding", limit, limit <= 1e5) + display(arr, 7, {.first.dec}, {.inc}, "following", limit, limit <= 1e5) +} diff --git a/Task/Priority-queue/Zig/priority-queue-1.zig b/Task/Priority-queue/Zig/priority-queue-1.zig index de2bc7ba6c..e92ec4a30d 100644 --- a/Task/Priority-queue/Zig/priority-queue-1.zig +++ b/Task/Priority-queue/Zig/priority-queue-1.zig @@ -24,21 +24,20 @@ const Task = struct { /// /// fn(T, T) bool const Comparator = struct { - fn maxCompare(a: Task, b: Task) bool { - return a.priority > b.priority; + fn maxCompare(_: void, a: Task, b: Task) std.math.Order { + return std.math.order(a.priority, b.priority); } - fn minCompare(a: Task, b: Task) bool { - return a.priority < b.priority; + fn minCompare(_: void, a: Task, b: Task) std.math.Order { + return std.math.order(a.priority, b.priority); } }; test "priority queue (max heap)" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); - var allocator = &arena.allocator; - - var pq = PriorityQueue(Task).init(allocator, Comparator.maxCompare); + const allocator = arena.allocator(); + var pq = PriorityQueue(Task, void, Comparator.maxCompare).init(allocator, {}); defer pq.deinit(); try pq.add(Task.init(3, "Clear drains")); @@ -46,14 +45,14 @@ test "priority queue (max heap)" { try pq.add(Task.init(5, "Make tea")); try pq.add(Task.init(1, "Solve RC tasks")); try pq.add(Task.init(2, "Tax returns")); - testing.expectEqual(pq.count(), 5); + try testing.expectEqual(pq.count(), 5); std.debug.print("\n", .{}); // execute the tasks in decreasing order of priority while (pq.count() != 0) { const task = pq.remove(); - std.debug.print("Executing: {} (priority {})\n", .{ task.name, task.priority }); + std.debug.print("Executing: {s} (priority {d})\n", .{ task.name, task.priority }); } std.debug.print("\n", .{}); } @@ -61,9 +60,8 @@ test "priority queue (max heap)" { test "priority queue (min heap)" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); - var allocator = &arena.allocator; - - var pq = PriorityQueue(Task).init(allocator, Comparator.minCompare); + const allocator = arena.allocator(); + var pq = PriorityQueue(Task, void, Comparator.minCompare).init(allocator, {}); defer pq.deinit(); try pq.add(Task.init(3, "Clear drains")); @@ -71,14 +69,14 @@ test "priority queue (min heap)" { try pq.add(Task.init(5, "Make tea")); try pq.add(Task.init(1, "Solve RC tasks")); try pq.add(Task.init(2, "Tax returns")); - testing.expectEqual(pq.count(), 5); + try testing.expectEqual(pq.count(), 5); std.debug.print("\n", .{}); // execute the tasks in increasing order of priority while (pq.count() != 0) { const task = pq.remove(); - std.debug.print("Executing: {} (priority {})\n", .{ task.name, task.priority }); + std.debug.print("Executing: {s} (priority {d})\n", .{ task.name, task.priority }); } std.debug.print("\n", .{}); } diff --git a/Task/Problem-of-Apollonius/11l/problem-of-apollonius.11l b/Task/Problem-of-Apollonius/11l/problem-of-apollonius.11l index fdec0e8c50..08843a16fe 100644 --- a/Task/Problem-of-Apollonius/11l/problem-of-apollonius.11l +++ b/Task/Problem-of-Apollonius/11l/problem-of-apollonius.11l @@ -1,11 +1,4 @@ -T Circle - Float x, y, r - - F (x, y, r) - .x = x - .y = y - .r = r - +T Circle((Float x, Float y, Float r)) F String() R ‘Circle(x=#., y=#., r=#.)’.format(.x, .y, .r) diff --git a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy index fbde02ed3e..72b2614f28 100644 --- a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy +++ b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy @@ -41,7 +41,7 @@ solve c1[] c2[] c3[] -1 -1 -1 r2[] print r2[] # proc circ x y r . . - linewidth 0.5 + text "" for a = 0 to 360 line x + sin a * r y + cos a * r . diff --git a/Task/Program-name/Ecstasy/program-name.ecstasy b/Task/Program-name/Ecstasy/program-name.ecstasy new file mode 100644 index 0000000000..5934b74a68 --- /dev/null +++ b/Task/Program-name/Ecstasy/program-name.ecstasy @@ -0,0 +1,7 @@ +module WhatIsMyName { + @Inject Console console; + + void run() { + console.print($"program name: {this:module}"); + } +} diff --git a/Task/Program-name/PascalABC.NET/program-name.pas b/Task/Program-name/PascalABC.NET/program-name.pas new file mode 100644 index 0000000000..5e999605d9 --- /dev/null +++ b/Task/Program-name/PascalABC.NET/program-name.pas @@ -0,0 +1,3 @@ +begin + Print(GetEXEFileName); +end. diff --git a/Task/Program-termination/PascalABC.NET/program-termination.pas b/Task/Program-termination/PascalABC.NET/program-termination.pas new file mode 100644 index 0000000000..8b8d6bcdc3 --- /dev/null +++ b/Task/Program-termination/PascalABC.NET/program-termination.pas @@ -0,0 +1,5 @@ +begin + if True then + Halt; + Print(1); +end. diff --git a/Task/Proper-divisors/Chipmunk-Basic/proper-divisors.basic b/Task/Proper-divisors/Chipmunk-Basic/proper-divisors.basic new file mode 100644 index 0000000000..6d789c8e51 --- /dev/null +++ b/Task/Proper-divisors/Chipmunk-Basic/proper-divisors.basic @@ -0,0 +1,35 @@ +100 cls +110 most = 1 +120 maxcount = 0 +130 print "The proper divisors of the following numbers are: ";chr$(10) +140 listproperdivisors(10) +150 for n = 2 to 20000 +160 rem It is extremely slow in this loop +170 count = countproperdivisors(n) +180 if count > maxcount then +190 maxcount = count +200 most = n +210 endif +220 next n +230 print +240 print most;" has the most proper divisors, namely ";maxcount +250 end +260 function countproperdivisors(number) +270 if number < 2 then countproperdivisors = 0 +280 count = 0 +290 for i = 1 to int(number/2) +300 if number mod i = 0 then count = count+1 +310 next i +320 countproperdivisors = count +330 end function +340 sub listproperdivisors(limit) +350 if limit < 1 then exit sub +360 for i = 1 to limit +370 print using "## ->";i; +380 if i = 1 then print " (None)"; +390 for j = 1 to int(i/2) +400 if i mod j = 0 then print " ";j; +410 next j +420 print +430 next i +440 end sub diff --git a/Task/Proper-divisors/EasyLang/proper-divisors.easy b/Task/Proper-divisors/EasyLang/proper-divisors.easy index 3e4ff18fbc..897419fa3e 100644 --- a/Task/Proper-divisors/EasyLang/proper-divisors.easy +++ b/Task/Proper-divisors/EasyLang/proper-divisors.easy @@ -1,7 +1,6 @@ -proc propdivs n . divs[] . - divs[] = [ ] +func[] propdivs n . if n < 2 - return + return [ ] . divs[] &= 1 sqr = sqrt n @@ -13,14 +12,13 @@ proc propdivs n . divs[] . . . . + return divs[] . for i to 10 - propdivs i d[] - write i & ":" - print d[] + print i & ":" & propdivs i . for i to 20000 - propdivs i d[] + d[] = propdivs i if len d[] > max max = len d[] maxi = i diff --git a/Task/Proper-divisors/Gambas/proper-divisors.gambas b/Task/Proper-divisors/Gambas/proper-divisors.gambas new file mode 100644 index 0000000000..7ce4d6643f --- /dev/null +++ b/Task/Proper-divisors/Gambas/proper-divisors.gambas @@ -0,0 +1,47 @@ +Sub ListProperDivisors(limit As Integer) + + If limit < 1 Then Return + For i As Integer = 1 To limit + Print Format$(i, "## ->"); + If i = 1 Then + Print " (None)" + Continue + End If + For j As Integer = 1 To i \ 2 + If i Mod j = 0 Then Print " "; j; + Next + Print + Next + +End Sub + +Function CountProperDivisors(number As Integer) As Integer + + If number < 2 Then Return 0 + Dim count As Integer = 0 + For i As Integer = 1 To number \ 2 + If number Mod i = 0 Then count += 1 + Next + Return count + +End Function + +Public Sub Main() + + Dim n As Integer, count As Integer, most As Integer = 1, maxCount As Integer = 0 + + Print "The proper divisors of the following numbers are: \n" + ListProperDivisors(10) + + For n As Integer = 2 To 20000 + count = CountProperDivisors(n) + If count > maxCount Then + maxCount = count + most = n + End If + Next + + Print + Print most; " has the most proper divisors, namely "; maxCount + +End diff --git a/Task/Proper-divisors/Langur/proper-divisors.langur b/Task/Proper-divisors/Langur/proper-divisors.langur index 18b386c99d..eec521545d 100644 --- a/Task/Proper-divisors/Langur/proper-divisors.langur +++ b/Task/Proper-divisors/Langur/proper-divisors.langur @@ -1,26 +1,26 @@ -val .getproper = fn(.x) for[=[]] .i of .x \ 2 { if .x div .i: _for ~= [.i] } -val .cntproper = fn(.x) for[=0] .i of .x \ 2 { if .x div .i: _for += 1 } +val getproper = fn x: for[=[]] i of x \ 2 { if x div i: _for ~= [i] } +val cntproper = fn x: for[=0] i of x \ 2 { if x div i: _for += 1 } -val .listproper = fn(.x) { - if .x < 1: return null - for[=""] .i of .x { - _for ~= $"\.i:2; -> \.getproper(.i);\n" +val listproper = fn(x) { + if x < 1: return null + for[=""] i of x { + _for ~= "{{i:2}} -> {{getproper(i)}}\n" } } writeln "The proper divisors of the following numbers are :" -writeln .listproper(10) +writeln listproper(10) -var .max = 0 -var .most = [] -for .n in 2 .. 20_000 { - val .cnt = .cntproper(.n) - if .cnt == .max { - .most = more .most, .n - } else if .cnt > .max { - .max, .most = .cnt, [.n] +var mx = 0 +var most = [] +for n in 2 .. 20_000 { + val cnt = cntproper(n) + if cnt == mx { + most = more(most, n) + } else if cnt > mx { + mx, most = cnt, [n] } } -writeln $"The following number(s) <= 20000 have the most proper divisors (\.max;)" -writeln .most +writeln "The following number(s) <= 20000 have the most proper divisors ({{mx}})" +writeln most diff --git a/Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Jq/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.jq b/Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Jq/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.jq new file mode 100644 index 0000000000..cd86b572e2 --- /dev/null +++ b/Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Jq/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.jq @@ -0,0 +1,15 @@ +include "MRG32k3a" {search: "."}; # see above + +def task1: + foreach range(0; 5) as $i (seed(1234567); nextInt ) | .nextInt; + +def task2($n): + seed(987654321) + | reduce range(0; $n) as $i (.counts = [range(0;5)|0]; + nextFloat + | .counts[ (.nextFloat * 5) | floor ] += 1 ) + | "\nThe counts for \($n) repetitions are:", + (range(0;5) as $i | " \($i) : \(.counts[$i] // 0)"); + +task1, +task2(100000) diff --git a/Task/Pseudo-random-numbers-Middle-square-method/ALGOL-W/pseudo-random-numbers-middle-square-method.alg b/Task/Pseudo-random-numbers-Middle-square-method/ALGOL-W/pseudo-random-numbers-middle-square-method.alg new file mode 100644 index 0000000000..95b5c0d56c --- /dev/null +++ b/Task/Pseudo-random-numbers-Middle-square-method/ALGOL-W/pseudo-random-numbers-middle-square-method.alg @@ -0,0 +1,15 @@ +begin % generate random numbers by the middle-square method % + integer seed; + % returns the next middle-square random number % + integer procedure msRandom ; + begin + real realSeed; + realSeed := seed; + realSeed := ( realSeed * realSeed ) / 1000; + seed := entier( realSeed ) rem 1000000; + seed + end msRandom ; + % test the ms random procedure % + seed := 675248; + for i := 1 until 5 do write( msRandom ) +end. diff --git a/Task/Pseudo-random-numbers-PCG32/FreeBASIC/pseudo-random-numbers-pcg32.basic b/Task/Pseudo-random-numbers-PCG32/FreeBASIC/pseudo-random-numbers-pcg32.basic new file mode 100644 index 0000000000..3e3d26807a --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/FreeBASIC/pseudo-random-numbers-pcg32.basic @@ -0,0 +1,49 @@ +#define floor(x) ((x*2.0-0.5) Shr 1) + +Const As Ulongint mask64 = &HFFFFFFFFFFFFFFFF +Const As Ulongint mask32 = &HFFFFFFFF +Const As Ulongint cte = 6364136223846793005 + +Dim Shared As Ulongint state, inc + +Function next_int() As Ulongint + ' return random 32 bit unsigned int + Dim As Ulongint old = state + state = ((old * cte) + inc) And mask64 + Dim As Ulongint xorshifted = (((old Shr 18) Xor old) Shr 27) And mask32 + Dim As Ulongint rot = (old Shr 59) And mask32 + Dim As Ulongint answer = (xorshifted Shr rot) Or (xorshifted Shl ((-rot) And 31)) + answer And= mask32 + Return answer +End Function + +Function next_float() As Double + ' return random float between 0 and 1 + Return next_int() / (2 ^ 32) +End Function + +Sub seed(seed_state As Ulongint, seed_sequence As Ulongint) + state = 0 + inc = ((seed_sequence Shl 1) Or 1) And mask64 + next_int() + state = (state + seed_state) And mask64 + next_int() +End Sub + +Dim As Integer i, hist(4) + +seed(42, 54) +For i = 1 To 5 + Print next_int() +Next i + +Print !"\nThe counts for 100,000 repetitions are:" +seed(987654321, 1) +For i = 1 To 100000 + hist(floor(next_float() * 5)) += 1 +Next i +For i = 0 To 4 + Print Using "hist(#) = #####"; i; hist(i) +Next i + +Sleep diff --git a/Task/Pseudo-random-numbers-PCG32/Jq/pseudo-random-numbers-pcg32.jq b/Task/Pseudo-random-numbers-PCG32/Jq/pseudo-random-numbers-pcg32.jq new file mode 100644 index 0000000000..3273a64d91 --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/Jq/pseudo-random-numbers-pcg32.jq @@ -0,0 +1,50 @@ +include "bitwise" {search: "."}; # see above + +def Const: 6364136223846793005; +def Mask64: 18446744073709551615; # i.e. (1 | leftshift(64)) - 1 +def Mask32: 4294967295; # i.e. (1 | leftshift(32)) - 1 + +# An initialization function if you do not wish to use seed/2 +def rcg32: + {state: 9600629759793949339, # 0x853c49e6748fea9b + inc: 15726070495360670683 # 0xda3e39cb94b95bdb + }; + +# Input: {state, inc} +# Output: {state, inc, nextInt} +def nextInt: + .state as $old + | .state = bitwise_and($old * Const + .inc; Mask64) + | bitwise_and(( bitwise_xor($old | rightshift(18); $old) | rightshift(27)); Mask32) as $xorshifted + | bitwise_and($old|rightshift(59) ; Mask32) as $rot + | .nextInt = bitwise_and( + bitwise_or( + $xorshifted | rightshift($rot) ; + $xorshifted | leftshift( bitwise_and( 32 - $rot; 31) )) ; + Mask32) ; + +def nextFloat: + nextInt + | .nextFloat = .nextInt / pow(2;32); + +def seed($seedState; $seedSequence): + {state: 0, + inc: bitwise_and( bitwise_xor($seedSequence|leftshift(1); 1); Mask64) + } + | nextInt + | .state += $seedState + | nextInt; + +def task1($n): + foreach range(0; $n) as $i (seed(42; 54); nextInt) + | .nextInt; + +def task2($n): + reduce range(0; $n) as $i (seed(987654321; 1); + nextFloat + | .counts[((.nextFloat * 5)|floor)] += 1) + | "\nThe counts for \($n) repetitions are:", + (range(0; 5) as $i | "\($i) : \(.counts[$i])") ; + +task1(5), +task2(100000) diff --git a/Task/Pseudo-random-numbers-Splitmix64/FreeBASIC/pseudo-random-numbers-splitmix64.basic b/Task/Pseudo-random-numbers-Splitmix64/FreeBASIC/pseudo-random-numbers-splitmix64.basic new file mode 100644 index 0000000000..186a379f70 --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/FreeBASIC/pseudo-random-numbers-splitmix64.basic @@ -0,0 +1,44 @@ +#define floor(x) ((x*2.0-0.5) Shr 1) + +Const As Ulongint mask64 = &HFFFFFFFFFFFFFFFF +Const As Ulongint C1 = &H9E3779B97F4A7C15 +Const As Ulongint C2 = &HBF58476D1CE4E5B9 +Const As Ulongint C3 = &H94D049BB133111EB + +Dim Shared As Ulongint state + +Sub seed(num As Ulongint) + state = num And mask64 +End Sub + +Function next_int() As Ulongint + ' return random int between 0 and 2^64 + Dim As Ulongint z = state + state += C1 + z = (z Xor (z Shr 30)) * C2 + z = (z Xor (z Shr 27)) * C3 + Return z Xor (z Shr 31) +End Function + +Function next_float() As Double + ' return random float between 0 and 1 + Return next_int() / (2 ^ 64) +End Function + +Dim As Integer i, hist(4) + +seed(1234567) +For i = 0 To 4 + Print next_int() +Next i + +Print !"\nThe counts for 100,000 repetitions are:" +seed(987654321) +For i = 1 To 100000 + hist(floor(next_float() * 5)) += 1 +Next i +For i = 0 To 4 + Print Using "hist(#) = #####"; i; hist(i) +Next i + +Sleep diff --git a/Task/Pseudo-random-numbers-Splitmix64/Swift/pseudo-random-numbers-splitmix64.swift b/Task/Pseudo-random-numbers-Splitmix64/Swift/pseudo-random-numbers-splitmix64.swift new file mode 100644 index 0000000000..3f208c5ae2 --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/Swift/pseudo-random-numbers-splitmix64.swift @@ -0,0 +1,34 @@ +struct SplitMix64: RandomNumberGenerator { + var state: UInt64 + init(seed: UInt64) { + state = seed + } + mutating func next() -> UInt64 { + state &+= 0x9e3779b97f4a7c15 + var z = state + z = (z ^ (z >> 30)) &* 0xbf58476d1ce4e5b9 + z = (z ^ (z >> 27)) &* 0x94d049bb133111eb + return z ^ (z >> 31) + } + mutating func nextFloat() -> Float64 { + Float64(next() >> 11) * 0x1.0p-53 + } +} + +do { + var split = SplitMix64(seed: 1234567) + print(split) + for _ in 0..<5 { + print(split.next()) + } + split = .init(seed: 987654321) + print("\n\(split)") + var counts = [0, 0, 0, 0, 0] + for _ in 0..<100_000 { + let i = Int(split.nextFloat() * 5.0) + counts[i] += 1 + } + for (i, count) in zip(0..., counts) { + print("\(i): \(count)") + } +} diff --git a/Task/Pseudo-random-numbers-Xorshift-star/FreeBASIC/pseudo-random-numbers-xorshift-star.basic b/Task/Pseudo-random-numbers-Xorshift-star/FreeBASIC/pseudo-random-numbers-xorshift-star.basic new file mode 100644 index 0000000000..ea4bdfa5bf --- /dev/null +++ b/Task/Pseudo-random-numbers-Xorshift-star/FreeBASIC/pseudo-random-numbers-xorshift-star.basic @@ -0,0 +1,43 @@ +#define floor(x) ((x*2.0-0.5) Shr 1) + +Const As Ulongint mask64 = &HFFFFFFFFFFFFFFFF +Const As Ulongint mask32 = &HFFFFFFFF +Const As Ulongint cte = &H2545F4914F6CDD1D + +Dim Shared As Ulongint state + +Sub seed(num As Ulongint) + state = num And mask64 +End Sub + +Function next_int() As Ulongint + Dim As Ulongint x = state + x = (x Xor (x Shr 12)) And mask64 + x = (x Xor (x Shl 25)) And mask64 + x = (x Xor (x Shr 27)) And mask64 + state = x + Dim As Ulongint answer = (((x * cte) And mask64) Shr 32) And mask32 + Return answer +End Function + +Function next_float() As Double + Return next_int() / (2 ^ 32) +End Function + +Dim As Integer i, hist(4) + +seed(1234567) +For i = 1 To 5 + Print next_int() +Next i + +Print !"\nThe counts for 100,000 repetitions are:" +seed(987654321) +For i = 1 To 100000 + hist(floor(next_float() * 5)) += 1 +Next i +For i = 0 To 4 + Print Using "hist(#) = #####"; i; hist(i) +Next i + +Sleep diff --git a/Task/Pseudo-random-numbers-Xorshift-star/Jq/pseudo-random-numbers-xorshift-star.jq b/Task/Pseudo-random-numbers-Xorshift-star/Jq/pseudo-random-numbers-xorshift-star.jq new file mode 100644 index 0000000000..e25bec7dd0 --- /dev/null +++ b/Task/Pseudo-random-numbers-Xorshift-star/Jq/pseudo-random-numbers-xorshift-star.jq @@ -0,0 +1,38 @@ +include "bitwise" {search: "."}; # see above + +def Const: 2685821657736338717; # i.e. 0x2545F4914F6CDD1D +def Mask64: 18446744073709551615; # i.e. (1 | leftshift(64)) - 1 +def Mask32: 4294967295; # i.e. (1 | leftshift(32)) - 1 + +# Emit a suitable {state} object +def seed($num): + {state: bitwise_and($num; Mask64)}; + +# Input: {state} +# Output: {state, nextInt} +def nextInt: + .state |= bitwise_and(bitwise_xor(.; rightshift(12)); Mask64) + | .state |= bitwise_and(bitwise_xor(.; leftshift( 25)); Mask64) + | .state |= bitwise_and(bitwise_xor(.; rightshift(27)); Mask64) + | .nextInt = bitwise_and( bitwise_and(.state * Const; Mask64) | rightshift(32); Mask32) ; + +# Input: {state} +# Output: {state, nextInt, nextFloat} +def nextFloat: + nextInt + | .nextFloat = (.nextInt / (pow(2;32))); + +def task1: + foreach range(0; 5) as $i (seed(1234567); + nextInt; + .nextInt); + +def task2($max): + reduce range(0; $max) as $i (seed(987654321); + nextFloat + | ((.nextFloat * 5)|floor) as $n + | .counts[$n] += 1) + | "\nThe counts for \($max) repetitions are:", + (range(0; 5) as $i | "\($i) : \(.counts[$i])") ; + +task1, "", task2(100000) diff --git a/Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy b/Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy new file mode 100644 index 0000000000..11924ea6f1 --- /dev/null +++ b/Task/Pythagorean-quadruples/EasyLang/pythagorean-quadruples.easy @@ -0,0 +1,28 @@ +n = 2200 +n2 = n * n * 2 +len r[] n +len ab[] n2 +for a = 1 to n + a2 = a * a + for b = a to n + ab[a2 + b * b] = 1 + . +. +s = 3 +for c = 1 to n + s1 = s + s += 2 + s2 = s + for d = c + 1 to n + if ab[s1] = 1 + r[d] = 1 + . + s1 += s2 + s2 += 2 + . +. +for i to n + if r[i] = 0 + write i & " " + . +. diff --git a/Task/Pythagorean-triples/D/pythagorean-triples-1.d b/Task/Pythagorean-triples/D/pythagorean-triples-1.d index 38f73bbc30..3671e42f24 100644 --- a/Task/Pythagorean-triples/D/pythagorean-triples-1.d +++ b/Task/Pythagorean-triples/D/pythagorean-triples-1.d @@ -10,6 +10,6 @@ void main() @safe { .map!(t => tuple(t[0 .. 2].gcd == 1, t[])); auto xs = triples(100); - writeln("Up to 100 there are ", xs.count, " triples, ", - xs.filter!q{ a[0] }.count, " are primitive."); + writefln("\nUp to %d there are %d triples, %d are primitive.", N, xs.count, + xs.filter!q{ a[0] }.count); } diff --git a/Task/Queue-Definition/PascalABC.NET/queue-definition.pas b/Task/Queue-Definition/PascalABC.NET/queue-definition.pas new file mode 100644 index 0000000000..cea9c80af5 --- /dev/null +++ b/Task/Queue-Definition/PascalABC.NET/queue-definition.pas @@ -0,0 +1,39 @@ +type + Node = auto class + data: T; + next: Node; + end; + MyQueue = class + head,tail: Node; + public + procedure Enqueue(x: T); + begin + if tail = nil then + begin + tail := new Node(x,nil); + head := tail; + end + else + begin + tail.next := new Node(x,nil); + tail := tail.next; + end; + end; + function Dequeue(): T; + begin + Result := head.data; + head := head.Next; + if head = nil then + tail := nil; + end; + function IsEmpty: boolean := head = nil; + end; + +begin + var q := new MyQueue; + for var i:=1 to 5 do + q.Enqueue(i); + while not q.IsEmpty do + Print(q.Dequeue); + Print(q.IsEmpty); +end. diff --git a/Task/Queue-Usage/PascalABC.NET/queue-usage.pas b/Task/Queue-Usage/PascalABC.NET/queue-usage.pas new file mode 100644 index 0000000000..47db237571 --- /dev/null +++ b/Task/Queue-Usage/PascalABC.NET/queue-usage.pas @@ -0,0 +1,7 @@ +begin + var q := new Queue; + for var i:=1 to 5 do + q.Enqueue(i); + while q.Count > 0 do + Print(q.Dequeue); +end. diff --git a/Task/Quine/Odin/quine.odin b/Task/Quine/Odin/quine.odin new file mode 100644 index 0000000000..c64cb4fc05 --- /dev/null +++ b/Task/Quine/Odin/quine.odin @@ -0,0 +1,16 @@ +package quine + +import "core:fmt" + +main :: proc() { + q := `package quine + +import "core:fmt" + +main :: proc() {{ + q := %c%s%c + fmt.printf(q, 96, q, 96) +} +` + fmt.printf(q, 96, q, 96) +} diff --git a/Task/Quine/PascalABC.NET/quine.pas b/Task/Quine/PascalABC.NET/quine.pas new file mode 100644 index 0000000000..183c208ff5 --- /dev/null +++ b/Task/Quine/PascalABC.NET/quine.pas @@ -0,0 +1 @@ +## var a:='## var a:='';print(2*a[:12]+2*a[11:])';print(2*a[:12]+2*a[11:]) diff --git a/Task/Quine/Prog8/quine.prog8 b/Task/Quine/Prog8/quine.prog8 new file mode 100644 index 0000000000..e84b6a1c3b --- /dev/null +++ b/Task/Quine/Prog8/quine.prog8 @@ -0,0 +1,9 @@ +%import textio +main { +sub start() { str[] s = [ +"%import textio","main {","sub start() { str[] s = [","]","ubyte i","for i in 0 to 2 { txt.print(s[i]) txt.nl() }","for i in 0 to 8 { txt.chrout(34) txt.print(s[i]) txt.chrout(34) if i<8 txt.chrout(44) }","for i in 3 to 8 { txt.print(s[i]) txt.nl() } }","}"] +ubyte i +for i in 0 to 2 { txt.print(s[i]) txt.nl() } +for i in 0 to 8 { txt.chrout(34) txt.print(s[i]) txt.chrout(34) if i<8 txt.chrout(44) } +for i in 3 to 8 { txt.print(s[i]) txt.nl() } } +} diff --git a/Task/Quine/Uxntal/quine.uxnatl b/Task/Quine/Uxntal/quine.uxnatl new file mode 100644 index 0000000000..ab462458cb --- /dev/null +++ b/Task/Quine/Uxntal/quine.uxnatl @@ -0,0 +1,16 @@ +|100 + ;q DUP2 print quine +BRK + +@quine + LDAk DUP #04 SFT DUP #0a LTH ?{ #27 ADD } #30 ADD #18 DEO + #0f AND DUP #0a LTH ?{ #27 ADD } #30 ADD #18 DEO #2018 DEO + INC2 LDAk ?quine POP2 + #3018 DEO #3018 DEO #0a18 DEO +JMP2r + +@print + LDAk #18 DEO INC2 LDAk ?print POP2 +JMP2r + +@q 7c 31 30 30 0a 09 3b 71 20 44 55 50 32 20 70 72 69 6e 74 20 71 75 69 6e 65 0a 42 52 4b 0a 0a 40 71 75 69 6e 65 0a 09 4c 44 41 6b 20 44 55 50 20 23 30 34 20 53 46 54 20 44 55 50 20 23 30 61 20 4c 54 48 20 3f 7b 20 23 32 37 20 41 44 44 20 7d 20 23 33 30 20 41 44 44 20 23 31 38 20 44 45 4f 0a 09 23 30 66 20 41 4e 44 20 44 55 50 20 23 30 61 20 4c 54 48 20 3f 7b 20 23 32 37 20 41 44 44 20 7d 20 23 33 30 20 41 44 44 20 23 31 38 20 44 45 4f 20 23 32 30 31 38 20 44 45 4f 0a 09 49 4e 43 32 20 4c 44 41 6b 20 3f 71 75 69 6e 65 20 50 4f 50 32 0a 09 23 33 30 31 38 20 44 45 4f 20 23 33 30 31 38 20 44 45 4f 20 23 30 61 31 38 20 44 45 4f 0a 4a 4d 50 32 72 0a 0a 40 70 72 69 6e 74 0a 09 4c 44 41 6b 20 23 31 38 20 44 45 4f 20 49 4e 43 32 20 4c 44 41 6b 20 3f 70 72 69 6e 74 20 50 4f 50 32 0a 4a 4d 50 32 72 0a 0a 40 71 20 00 diff --git a/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-1.pas b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-1.pas new file mode 100644 index 0000000000..84b0e4c1d0 --- /dev/null +++ b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-1.pas @@ -0,0 +1 @@ +var s := 'Hello'; diff --git a/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-2.pas b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-2.pas new file mode 100644 index 0000000000..bd43ef17c8 --- /dev/null +++ b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-2.pas @@ -0,0 +1 @@ +var s := 'd''Artagnan'; // d'Artagnan diff --git a/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-3.pas b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-3.pas new file mode 100644 index 0000000000..1c41e16935 --- /dev/null +++ b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-3.pas @@ -0,0 +1,2 @@ +var (a,b) := (3,5); +var s := $'{a} + {b} = {a + b}'; diff --git a/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-4.pas b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-4.pas new file mode 100644 index 0000000000..3cc41c47bd --- /dev/null +++ b/Task/Quoting-constructs/PascalABC.NET/quoting-constructs-4.pas @@ -0,0 +1,5 @@ +var s := ''' + This is a + multiline + string + '''; diff --git a/Task/RIPEMD-160/Java/ripemd-160-2.java b/Task/RIPEMD-160/Java/ripemd-160-2.java index 5c025e6737..5ffad2ad52 100644 --- a/Task/RIPEMD-160/Java/ripemd-160-2.java +++ b/Task/RIPEMD-160/Java/ripemd-160-2.java @@ -50,7 +50,7 @@ final class RIPEMD160 { } private static byte[] addPadding(String aMessage) { - byte[] bytes = aMessage.getBytes(StandardCharsets.UTF_8); + byte[] bytes = aMessage.getBytes(StandardCharsets.ISO_8859_1); bytes = Arrays.copyOf(bytes, bytes.length + 1); bytes[bytes.length - 1] = (byte) 0x80; diff --git a/Task/RPG-attributes-generator/Uiua/rpg-attributes-generator.uiua b/Task/RPG-attributes-generator/Uiua/rpg-attributes-generator.uiua new file mode 100644 index 0000000000..a7ac39bb69 --- /dev/null +++ b/Task/RPG-attributes-generator/Uiua/rpg-attributes-generator.uiua @@ -0,0 +1,4 @@ +Attr ← (/+↘1⊏⍏.⌈×6∵⋅⚂⊚4) +Attrs ← (∵⋅Attr⊚6) +Valid ← ×⊃(>1/+>14|>75/+) +⍢◌(¬Valid.Attrs) diff --git a/Task/Radical-of-an-integer/PascalABC.NET/radical-of-an-integer.pas b/Task/Radical-of-an-integer/PascalABC.NET/radical-of-an-integer.pas new file mode 100644 index 0000000000..c9dc8df377 --- /dev/null +++ b/Task/Radical-of-an-integer/PascalABC.NET/radical-of-an-integer.pas @@ -0,0 +1,41 @@ +function Factors(N: integer): List; +begin + var lst := new List; + var i := 2; + while i * i <= N do + begin + while N.Divs(i) do + begin + if i not in lst then + lst.Add(i); + N := N div i; + end; + i += 1; + end; + if N >= 2 then + lst.Add(N); + Result := lst; +end; + +function Radical(x: integer) := Factors(x).Product; + +begin + for var i:=1 to 50 do + begin + Write(Radical(i):3); + if i mod 10 = 0 then + Writeln; + end; + Writeln; + + Writeln('Radical(99999) = ',Radical(99999)); + Writeln('Radical(499999) = ',Radical(499999)); + Writeln('Radical(999999) = ',Radical(999999)); + Writeln; + + var a := |0| *8; + for var i:=1 to 1000000 do + a[Factors(i).Count] += 1; + for var i:=0 to 7 do + Writeln($'{i}: {a[i]}'); +end. diff --git a/Task/Radical-of-an-integer/REXX/radical-of-an-integer.rexx b/Task/Radical-of-an-integer/REXX/radical-of-an-integer-1.rexx similarity index 93% rename from Task/Radical-of-an-integer/REXX/radical-of-an-integer.rexx rename to Task/Radical-of-an-integer/REXX/radical-of-an-integer-1.rexx index 446959e900..f1bce2f21a 100644 --- a/Task/Radical-of-an-integer/REXX/radical-of-an-integer.rexx +++ b/Task/Radical-of-an-integer/REXX/radical-of-an-integer-1.rexx @@ -1,4 +1,8 @@ /* REXX */ +parse version version; say version 'Intel i7 5GHz' +say 'Radicals for an integer = product of distinct prime factors' +say 'Version 1: tailor-made procedures' +say call setp Numeric Digits 100 /* 1. Radicals from 1 to 50 */ diff --git a/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx b/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx new file mode 100644 index 0000000000..0e51541db3 --- /dev/null +++ b/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx @@ -0,0 +1,361 @@ +/* REXX */ +arg n +if n = '' then + n = 1000000 +numeric digits 100 +parse version version; say version 'Intel i7 5GHz' +say 'Radicals for an integer = product of distinct prime factors' +say 'Version 2: generic procedures' +say +say 'Radicals for 1..50:' +ol = '' +do i = 1 to 50 + ol = ol||Right(Radical(i),5) + if i//10 = 0 then do + say ol; ol = '' + end +end +say +say 'Radicals for:' +say '99999 =' Radical(99999) +say '499999 =' Radical(499999) +say '999999 =' Radical(999999) +say +s = n/10; r = ISqrt(n); radi. = 0; glob. = '' +say 'Getting distribution list:' +call Time('r') +do i = 1 to n + call Radical(i) + u = glob.ufactor.0 + radi.u = radi.u+1 + if i//s = 0 then + say Right(i,7) Format(Time('e'),,3) 'seconds' +end +say +say 'Distribution for first' n 'radicals over number of factors:' +do i = 0 to 10 + say Right(i,2) Right(radi.i,6) +end +say +say 'Getting primes up to' n':' +call Time('r') +pr = Primes(n) +say 'Took' Format(Time('e'),,3) 'seconds' +say +say 'Getting powers of primes up to' r':' +call Time('r') +pw = 0 +do i = 1 + p1 = glob.prime.i + if p1 > r then + leave + p2 = p1 + do forever + p2 = p2*p1 + if p2 > n then + leave + pw = pw+1 + end +end +say 'Took' Format(Time('e'),,3) 'seconds' +say +say 'Primes' Format(pr,6) +say 'Powers' Format(pw,6) +say ' -----' +say 'Total ' Format(pr+pw,6) +exit + +Radical: +/* Radical function = product of unique prime factors */ +procedure expose glob. +arg x +/* Validity */ +if \ Whole(x) then + return 'X' +if x < 1 then + return 'X' +/* Get unique factors */ +n = Ufactors(x) +/* Calculate product */ +y = 1 +do i = 1 to n + y = y*glob.ufactor.i +end +return y + +Ufactors: +/* Unique factors */ +procedure expose glob. +arg x +/* Validity */ +if \ Datatype(x,'w') then + return 'X' +if x < 1 then + return 'X' +/* Fast values */ +if x = 1 then do + glob.ufactor.0 = 0 + return 0 +end +if x < 4 then do + glob.ufactor.1 = x + glob.ufactor.0 = 1 + return 1 +end +if Prime(x) then do + glob.ufactor.1 = x + glob.ufactor.0 = 1 + return 1 +end +/* Check low factors */ +n = 0; v = 0 +pr = '2 3 5 7 11 13 17 19 23' +do i = 1 to Words(pr) + pn = Word(pr,i) + do while x//pn = 0 + if pn <> v then do + n = n+1; glob.ufactor.n = pn; v = pn + end + x = x%pn + end +end +/* Check higher factors */ +do j = 29 by 6 while j*j <= x + p = Right(j,1) + if p <> 5 then do + do while x//j = 0 + if j <> v then do + n = n+1; glob.ufactor.n = j; v = j + end + x = x%j + end + end + if p = 3 then + iterate + y = j+2 + do while x//y = 0 + if y <> v then do + n = n+1; glob.ufactor.n = y; v = y + end + x = x%y + end +end +/* Last factor */ +if x > 1 then do + if x <> v then do + n = n+1; glob.ufactor.n = x + end +end +glob.ufactor.0 = n +/* Return number of factors */ +return n + +Isqrt: +/* Integer square root Floor(x^(1/2)) function */ +procedure expose glob. +arg x +/* Validity */ +if x < 0 then + return 'X' +/* Fast values */ +if x < 1 then + return 0 +if x < 4 then + return 1 +if x < 9 then + return 2 +/* Uses only integers */ +x = x%1; q = 1 +do until q > x + q = q*4 +end +y = 0 +do while q > 1 + q = q%4; t = x-y-q; y = y%2 + if t >= 0 then do + x = t; y = y+q + end +end +return y + +Powermod: +/* Power modulus x^y mod z function */ +procedure expose glob. +arg x,y,z +/* Validity */ +if \ Whole(x) then + return 'X' +if \ Whole(y) then + return 'X' +if \ Whole(z) then + return 'X' +if x < 0 then + return 'X' +if y < 0 then + return 'X' +if z < 1 then + return 'X' +/* Fast values */ +if z = 1 then + return 0 +/* Binary method */ +numeric digits Max(Length(Format(x,,,0)),Length(Format(y,,,0)),2*Length(Format(z,,,0))) +b = x//z; r = 1 +do while y > 0 + if y//2 then + r = r*x//z + x = x*x//z; y = y%2 +end +return r + +Prime: +/* Is a number prime? function */ +procedure expose glob. +arg x +/* Validity */ +if \ Whole(x) then + return 'X' +if x < 2 then + return 'X' +/* Low primes also used as deterministic witnesses */ +lp = '2 3 5 7 11 13 17 19 23 29 31 37 41' +/* Fast values */ +if x < 42 then do + if Wordpos(x,lp) = 0 then + return 0 + else + return 1 +end +if x//2 = 0 then + return 0 +if x//3 = 0 then + return 0 +if Right(x,1) = 5 then + return 0 +/* Miller-Rabin primality test */ +numeric digits 2*Length(x) +d = x-1; e = d +/* Reduce x-1 by factors of 2 */ +do s = -1 while d//2 = 0 + d = d%2 +end +/* Thresholds deterministic witnesses */ +th = '2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 0 ', +|| '3825123056546413051 0 0 318665857834031151167461 3317044064679887385961981 ' +w = Words(th) +/* Up to 13 deterministic trials */ +if x < Word(th,w) then do + do k = 1 to w + if x < Word(th,k) then + leave + end +end +/* or 3 probabilistic trials */ +else do + lp = '' + do k = 1 to 3 + r = Rand(2,e)/1; lp = lp||r||' ' + end + k = k-1 +end +/* Algorithm using generated witnesses */ +do k = 1 to k + a = Word(lp,k); y = Powermod(a,d,x) + if y = 1 then + iterate + if y = e then + iterate + do s + y = (y*y)//x + if y = 1 then + return 0 + if y = e then + leave + end + if y <> e then + return 0 +end +return 1 + +Rand: +/* Random number 12 digits precision function */ +procedure expose glob. +arg x,y +/* Validity */ +if x <> '' then do + if \ Whole(x) then + return 'X' + if \ Whole(y) then + return 'X' + if x >= y then + return 'X' +end +/* Fixed precision */ +p = Digits(); numeric digits 30 +/* Get and save first seed from system Date and Time */ +if glob.rand = '' then do + a = Date('s'); b = Time('l') + glob.rand = Substr(b,10,3)||Substr(b,7,2)||Substr(b,4,2)||Substr(b,1,2)||Substr(a,7,2)||Substr(a,5,2)||Substr(a,3,2) +end +/* Calculate next random number method HP calculators */ +glob.rand = Right((glob.rand*2851130928467),15) +/* Uniform deviate [0,1) */ +z = '0.'Left(glob.rand,Length(glob.rand)-3) +numeric digits 12 +if x = '' then + return z/1 +else + return Floor(z*(y+1-x)+x) + +Whole: +/* Is a number integer? function */ +procedure expose glob. +arg x +/* Formula */ +return Datatype(x,'w') + +Primes: +/* Prime numbers */ +procedure expose glob. +arg x +/* Validity */ +if Datatype(x,'w') = 0 then + return 'X' +if x < 1 then + return 'X' +/* Fast values */ +if x = 1 then do + glob.prime.0 = 0 + return 0 +end +if x < 101 then do + p = '2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 999' + do n = 1 to Words(p) + w = Word(p,n) + if w > x then do + n = n-1 + leave + end + glob.prime.n = w + end + glob.prime.0 = n + return n +end +/* Wheeled sieve of Eratosthenes */ +z. = 1 +do i = 3 by 2 to x while i*i <= x + if z.i = 1 then do + do j = i*3 by i+i to x + z.j = 0 + end + end +end +/* Save results */ +n = 1; glob.prime.1 = 2 +do i = 3 by 2 to x + if z.i = 1 then do + n = n+1; glob.prime.n = i + end +end +glob.prime.0 = n +return n diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/BASIC256/ramer-douglas-peucker-line-simplification.basic b/Task/Ramer-Douglas-Peucker-line-simplification/BASIC256/ramer-douglas-peucker-line-simplification.basic new file mode 100644 index 0000000000..f12c8cf84f --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/BASIC256/ramer-douglas-peucker-line-simplification.basic @@ -0,0 +1,67 @@ +arraybase 1 +global matriz +dim matriz(10, 3) +matriz[ 1, 1] = 0 : matriz[ 1, 2] = 0 : matriz[ 1, 3] = 0 +matriz[ 2, 1] = 1 : matriz[ 2, 2] = 0.1 : matriz[ 2, 3] = 0 +matriz[ 3, 1] = 2 : matriz[ 3, 2] = -0.1 : matriz[ 3, 3] = 0 +matriz[ 4, 1] = 3 : matriz[ 4, 2] = 5 : matriz[ 4, 3] = 0 +matriz[ 5, 1] = 4 : matriz[ 5, 2] = 6 : matriz[ 5, 3] = 0 +matriz[ 6, 1] = 5 : matriz[ 6, 2] = 7 : matriz[ 6, 3] = 0 +matriz[ 7, 1] = 6 : matriz[ 7, 2] = 8.1 : matriz[ 7, 3] = 0 +matriz[ 8, 1] = 7 : matriz[ 8, 2] = 9 : matriz[ 8, 3] = 0 +matriz[ 9, 1] = 8 : matriz[ 9, 2] = 9 : matriz[ 9, 3] = 0 +matriz[10, 1] = 9 : matriz[10, 2] = 9 : matriz[10, 3] = 0 + +call DRDP(matriz, 1, 10, 1) + +print "Remaining points after simplifying:" +matriz[1, 3] = true +matriz[10, 3] = true +for i = 1 to matriz[?][] + if matriz[i, 3] = true then print "(";matriz[i, 1];", "; matriz[i, 2];") "; +next i +end + +function DistanciaPerpendicular(tabla, i, ini, fin) + dx = tabla[fin, 1] - tabla[ini, 1] + dy = tabla[fin, 2] - tabla[ini, 2] + + #Normalise + mag = (dx^2 + dy^2)^0.5 + if mag > 0 then dx /= mag : dy /= mag + + pvx = tabla[i, 1] - tabla[ini, 1] + pvy = tabla[i, 2] - tabla[ini, 2] + + #Get dot product (project pv onto normalized direction) + pvdot = dx * pvx + dy * pvy + + #Scale line direction vector + dsx = pvdot * dx + dsy = pvdot * dy + + #Subtract this from pv + ax = pvx - dsx + ay = pvy - dsy + return (ax^2 + ay^2)^0.5 +end function + +subroutine DRDP(matriz, ini, fin, epsilon) + dmax = 0 + + # Find the point with the maximum distance + if matriz[?][] < 2 then print "Not enough points to simplify": end + + for i = ini + 1 to fin + d = DistanciaPerpendicular(matriz, i, ini, fin) + if d > dmax then indice = i : dmax = d + next + + # If max distance is greater than epsilon, recursively simplify + if dmax > epsilon then + matriz[indice, 3] = true + # Recursive call + call DRDP(matriz, ini, indice, epsilon) + call DRDP(matriz, indice, fin, epsilon) + end if +end subroutine diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/Jq/ramer-douglas-peucker-line-simplification.jq b/Task/Ramer-Douglas-Peucker-line-simplification/Jq/ramer-douglas-peucker-line-simplification.jq new file mode 100644 index 0000000000..0d819ce0c1 --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/Jq/ramer-douglas-peucker-line-simplification.jq @@ -0,0 +1,29 @@ +def Point($x;$y): {x:$x, y:$y}; # jq and gojq allow: {$x,$y} + +def ppArray: + def pp: "(\(.x), \(.y))"; + "[" + (map(pp) | join(", ")) + "]"; + +def rdp($eps): + . as $l + | {x: 0, + dMax: -1} + | .p1 = $l[0] # first + | .p2 = $l[-1] # last + | (.p2.x - .p1.x) as $x21 + | (.p2.y - .p1.y) as $y21 + | reduce range(1; ($l|length)) as $i (.; + .p = $l[$i] + | ( ($y21*.p.x - $x21*.p.y + .p2.x*.p1.y - .p2.y*.p1.x) | length) as $d # abs ~ length + | if $d > .dMax then .x += 1 | .dMax = $d end ) + | if .dMax > $eps + then ($l[0: 1+.x]|rdp($eps)) + ($l[.x:]|rdp(eps))[1:] + else [$l[0], $l[-1]] + end; + +def points: [ + Point(0; 0), Point(1; 0.1), Point(2; -0.1), Point(3; 5), Point(4; 6), + Point(5; 7), Point(6; 8.1), Point(7; 9), Point(8; 9), Point(9; 9) +]; + +points | rdp(1) | ppArray diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/QBasic/ramer-douglas-peucker-line-simplification.basic b/Task/Ramer-Douglas-Peucker-line-simplification/QBasic/ramer-douglas-peucker-line-simplification.basic new file mode 100644 index 0000000000..eb66842ad5 --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/QBasic/ramer-douglas-peucker-line-simplification.basic @@ -0,0 +1,67 @@ +DECLARE SUB DRDP (ListaDePuntos() AS DOUBLE, ini AS INTEGER, fin AS INTEGER, epsilon AS DOUBLE) +DECLARE FUNCTION DistanciaPerpendicular! (tabla() AS DOUBLE, i AS INTEGER, ini AS INTEGER, fin AS INTEGER) + +CONST True = -1 +DIM matriz(1 TO 10, 1 TO 3) AS DOUBLE +DATA 0,0,1,0.1,2,-0.1,3,5,4,6,5,7,6,8.1,7,9,8,9,9,9 +FOR i = LBOUND(matriz) TO UBOUND(matriz) + READ matriz(i, 1), matriz(i, 2) +NEXT i + +CALL DRDP(matriz(), 1, 10, 1) + +PRINT "Remaining points after simplifying:" +matriz(1, 3) = True: matriz(10, 3) = True +FOR i = LBOUND(matriz) TO UBOUND(matriz) + IF matriz(i, 3) THEN PRINT "("; matriz(i, 1); ", "; matriz(i, 2); ") "; +NEXT i +END + +FUNCTION DistanciaPerpendicular (tabla() AS DOUBLE, i AS INTEGER, ini AS INTEGER, fin AS INTEGER) + DIM dx AS DOUBLE, dy AS DOUBLE, mag AS DOUBLE, pvx AS DOUBLE, pvy AS DOUBLE + DIM pvdot AS DOUBLE, dsx AS DOUBLE, dsy AS DOUBLE, ax AS DOUBLE, ay AS DOUBLE + + dx = tabla(fin, 1) - tabla(ini, 1) + dy = tabla(fin, 2) - tabla(ini, 2) + + 'Normalise + mag = (dx ^ 2 + dy ^ 2) ^ .5 + IF mag > 0 THEN dx = dx / mag: dy = dy / mag + + pvx = tabla(i, 1) - tabla(ini, 1) + pvy = tabla(i, 2) - tabla(ini, 2) + + 'Get dot product (project pv onto normalized direction) + pvdot = dx * pvx + dy * pvy + + 'Scale line direction vector + dsx = pvdot * dx + dsy = pvdot * dy + + 'Subtract this from pv + ax = pvx - dsx + ay = pvy - dsy + + DistanciaPerpendicular = (ax ^ 2 + ay ^ 2) ^ .5 +END FUNCTION + +SUB DRDP (ListaDePuntos() AS DOUBLE, ini AS INTEGER, fin AS INTEGER, epsilon AS DOUBLE) + DIM dmax AS DOUBLE, d AS DOUBLE + DIM indice AS INTEGER, i AS INTEGER + ' Find the point with the maximum distance + + IF UBOUND(ListaDePuntos) < 2 THEN PRINT "Not enough points to simplify": END + + FOR i = ini + 1 TO fin + d = DistanciaPerpendicular(ListaDePuntos(), i, ini, fin) + IF d > dmax THEN indice = i: dmax = d + NEXT + + ' If max distance is greater than epsilon, recursively simplify + IF dmax > epsilon THEN + ListaDePuntos(indice, 3) = True + ' Recursive call + CALL DRDP(ListaDePuntos(), ini, indice, epsilon) + CALL DRDP(ListaDePuntos(), indice, fin, epsilon) + END IF +END SUB diff --git a/Task/Random-numbers/ANSI-BASIC/random-numbers.basic b/Task/Random-numbers/ANSI-BASIC/random-numbers.basic new file mode 100644 index 0000000000..2bb7a7c699 --- /dev/null +++ b/Task/Random-numbers/ANSI-BASIC/random-numbers.basic @@ -0,0 +1,19 @@ +100 REM Random numbers +110 RANDOMIZE +120 DEF RandomNormal = COS(2 * PI * RND) * SQR(-2 * LOG(RND)) +130 DIM R(0 TO 999) +140 LET Sum = 0 +150 FOR I = 0 TO 999 +160 LET R(I) = 1 + RandomNormal / 2 +170 LET Sum = Sum + R(I) +180 NEXT I +190 LET Mean = Sum / 1000 +200 LET Sum = 0 +210 FOR I = 0 TO 999 +220 LET Sum = Sum + (R(I) - Mean) ^ 2 +230 NEXT I +240 LET SD = SQR(Sum / 1000) +250 PRINT "Mean is "; Mean +260 PRINT "Standard Deviation is"; SD +270 PRINT +280 END diff --git a/Task/Random-numbers/QuickBASIC/random-numbers.basic b/Task/Random-numbers/QuickBASIC/random-numbers.basic new file mode 100644 index 0000000000..42387d6e82 --- /dev/null +++ b/Task/Random-numbers/QuickBASIC/random-numbers.basic @@ -0,0 +1,7 @@ +RANDOMIZE TIMER 'seeds random number generator with the system time +pi = 3.141592653589793# +DIM a(1 TO 1000) AS DOUBLE +CLS +FOR i = 1 TO 1000 + a(i) = 1 + SQR(-2 * LOG(RND)) * COS(2 * pi * RND) +NEXT i diff --git a/Task/Random-numbers/Uiua/random-numbers.uiua b/Task/Random-numbers/Uiua/random-numbers.uiua new file mode 100644 index 0000000000..d5343a09dc --- /dev/null +++ b/Task/Random-numbers/Uiua/random-numbers.uiua @@ -0,0 +1,6 @@ +# Generate normal distribution with mean = 1, sd = 0.5 +Gauss ← (×(∿+η××2π⚂) (√ׯ2ₙe⚂)) +[⍥(+1×0.5Gauss)1000] # -> mean = 1, sd = 0.5 +Mean ← ÷⧻⟜/+ +Sd ← √÷⊃(⋅⧻|/+×.-)Mean. +⊸⊃Sd Mean diff --git a/Task/Random-sentence-from-book/Jq/random-sentence-from-book.jq b/Task/Random-sentence-from-book/Jq/random-sentence-from-book.jq new file mode 100644 index 0000000000..1ed3a8cc85 --- /dev/null +++ b/Task/Random-sentence-from-book/Jq/random-sentence-from-book.jq @@ -0,0 +1,107 @@ +include "MRG32k3a" {search: "."}; # see above + +### Generic functions + +def sum(stream): reduce stream as $s (0; . +$s); + +### Random sentences +# puctuation to keep (also keep hyphen and apostrophe but do not count as words) +def ending: ".!?"; +def pausing:" ,:;"; + +# regex for removing puctuation +def removing: "[\"#\\$\\%&\\(\\)\\*\\+/<=>@\\[\\\\]^_`{|}~“”]"; + +# Emit a stream of lines +def text: + foreach inputs as $in (null; + if . then $in + else # skip to start + ($in|index("No one would have believed")) as $ix + | if $ix then $in[$ix:] end + end; + select(.) + | gsub( removing; "" ) # remove extraneous punctuation + | gsub("[\r—]"; " ") # replace \r and EM DASH (unicode 8212) with a space +); + +def pairsAndTriples(stream): + reduce stream as $x ({}; + .pair as $in2 + | .triple as $in3 + | if .pair | length <= 1 then .pair += [$x] end + | if .triple | length <= 2 then .triple += [$x] end + | if .pair | length == 2 + then # .dict2[ .pair | join(" ")] += 1 + .dict[ .pair[0] ][.pair[1]] += 1 + end + | if $in2 | length == 2 + then .pair |= [ last, $x] + end + + | if .triple | length == 3 + then .dict3[.triple[0:2]|join(" ")][ .triple[2]] += 1 + end + | if $in3 | length == 3 + then .triple |= .[1:] + [$x] + end + ) ; + +# split into words +def words: + text + | splits(" +") + | select(length>0) + | (first( foreach (ending, pausing | split("")[]) as $x (.; + if endswith($x) then [.[:-1], .[-1:]] end) + | select(type=="array")) | .[]) + // . +; + +# $randomFloat should be a randomFloat value +# . should be a JSON object with {WORD: count} pairs +def weightedRandomChoice($randomFloat): + to_entries + | . as $entries + | .[0].key as $default + | sum( .[] | .value) as $n + | ($n * $randomFloat | floor) as $r + | first( + { sum: 0 } + | foreach $entries[] as $kv (.; + .key = $kv.key + | .sum += $kv.value ) + | if $r < .sum then .key else empty end) + // $default; + +# build 5 random sentences +def sentences: + pairsAndTriples(words) as $library + | range(1;6) as $u + # First word: + | { prng: (seed((now + $u) % D) | nextFloat)} + | .prng.nextFloat as $nf + | .sentence = ($library.dict["."] | weightedRandomChoice($nf)) + | .lastOne = .sentence + | .lastTwo = ". " + .sentence + | until(.break; + $library.dict3[.lastTwo] as $x + | if $x + then .prng |= nextFloat + | (.prng.nextFloat) as $nf + | ($x | weightedRandomChoice($nf)) as $nextOne + | .sentence += " " + $nextOne + # stop on reaching ending punctuation + | if any(ending|split("")[]; . as $punctuation | $nextOne | index($punctuation)) + then .break = true + else .lastTwo = .lastOne + " " + $nextOne + | .lastOne = $nextOne + end + else debug("unexpected failure") | .break=true + end ) + # tidy up sentence + | .sentence + | reduce (ending + pausing | split("")[]) as $p (.; . |= gsub(" [\($p)]"; "\($p)") ) + | if startswith("“") and (test("”")|not) then .sentence += "”" end ; + +sentences diff --git a/Task/Range-expansion/EasyLang/range-expansion.easy b/Task/Range-expansion/EasyLang/range-expansion.easy new file mode 100644 index 0000000000..c1476c55af --- /dev/null +++ b/Task/Range-expansion/EasyLang/range-expansion.easy @@ -0,0 +1,20 @@ +func[] expand txt$ . + for r$ in strsplit txt$ "," + for i = 2 to len r$ - 1 + if substr r$ i 1 = "-" + a = number substr r$ 1 (i - 1) + b = number substr r$ (i + 1) 999 + break 1 + . + . + if i = len r$ + lst[] &= number r$ + else + for i = a to b + lst[] &= i + . + . + . + return lst[] +. +print expand "-6,-3--1,3-5,7-11,14,15,17-20" diff --git a/Task/Range-extraction/EasyLang/range-extraction.easy b/Task/Range-extraction/EasyLang/range-extraction.easy index 34766517e6..0d3eeb1abe 100644 --- a/Task/Range-extraction/EasyLang/range-extraction.easy +++ b/Task/Range-extraction/EasyLang/range-extraction.easy @@ -1,21 +1,19 @@ -func$ mkrange arr[] . - idx = 1 - idx2 = 1 - while idx <= len arr[] - repeat - idx2 += 1 - until idx2 > len arr[] or arr[idx2] - arr[idx2 - 1] <> 1 +func$ extract l[] . + for i to len l[] + low = l[i] + while i < len l[] and l[i] + 1 = l[i + 1] + i += 1 . - if idx2 - idx > 2 - r$ &= arr[idx] & "-" & arr[idx2 - 1] & "," - idx = idx2 + hi = l[i] + if hi - low >= 2 + r$ &= low & "-" & hi & "," + elif hi - low = 1 + r$ &= low & "," + r$ &= hi & "," else - while idx < idx2 - r$ &= arr[idx] & "," - idx += 1 - . + r$ &= low & "," . . return substr r$ 1 (len r$ - 1) . -print mkrange [ 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 ] +print extract [ 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 ] diff --git a/Task/Rare-numbers/Langur/rare-numbers.langur b/Task/Rare-numbers/Langur/rare-numbers.langur index 7cefd78272..2bec6f3d28 100644 --- a/Task/Rare-numbers/Langur/rare-numbers.langur +++ b/Task/Rare-numbers/Langur/rare-numbers.langur @@ -1,20 +1,29 @@ -val .perfectsquare = fn(.n) (.n ^/ 2) div 1 +val perfectsquare = fn n: (n ^/ 2) div 1 -val .israre = fn(.n) { - val .r = reverse(.n) - if .n == .r: return false - val .sum = .n + .r - val .diff = .n - .r - .diff > 0 and .perfectsquare(.sum) and .perfectsquare(.diff) +val israre = fn(n) { + val r = reverse(n) + if n == r: return false + val sum = n + r + val diff = n - r + diff > 0 and perfectsquare(sum) and perfectsquare(diff) } -val .findfirst = fn(.max) { - for[=[]] .i = 0; len(_for) < .max; .i += 1 { - if .israre(.i) { - _for ~= [.i] +val findfirst = fn(mx) { + for[=[]] i = 0; len(_for) < mx; i += 1 { + if israre(i) { + _for ~= [i] + } + } +} + +val findandprint = impure fn(mx) { + for[cnt=0] i = 0; cnt < mx ; i += 1 { + if israre(i) { + writeln "\n rare ", i, " " + cnt += 1 } } } # if you have the time... -writeln "the first 5 rare numbers: ", .findfirst(5) +writeln "the first 5 rare numbers: ", findfirst(5) diff --git a/Task/Rate-counter/Chipmunk-Basic/rate-counter.basic b/Task/Rate-counter/Chipmunk-Basic/rate-counter.basic new file mode 100644 index 0000000000..9a7e87a49a --- /dev/null +++ b/Task/Rate-counter/Chipmunk-Basic/rate-counter.basic @@ -0,0 +1,17 @@ +100 cls +110 for i = 1 to 3 +120 gosub 170 +130 next i +140 i = 200 +150 gosub 170 +160 end +170 'function timeit +180 iter = 0 +190 starter = timer +200 while true +210 iter = iter+1 +220 if timer >= starter+i then exit while +230 wend +240 print iter;" iteraciones en ";i;" milisegundo"; +250 if i > 1 then print "s" else print "" +260 return diff --git a/Task/Ray-casting-algorithm/11l/ray-casting-algorithm.11l b/Task/Ray-casting-algorithm/11l/ray-casting-algorithm.11l index 9604c7d423..d3bb94d583 100644 --- a/Task/Ray-casting-algorithm/11l/ray-casting-algorithm.11l +++ b/Task/Ray-casting-algorithm/11l/ray-casting-algorithm.11l @@ -1,30 +1,12 @@ -T Pt - Float x, y - - F (x, y) - .x = x - .y = y - +T Pt((Float x, Float y)) F String() R ‘Pt(x=#., y=#.)’.format(.x, .y) -T Edge - Pt a, b - - F (a, b) - .a = a - .b = b - +T Edge((Pt a, Pt b)) F String() R ‘Edge(a=#., b=#.)’.format(.a, .b) -T Poly - String name - [Edge] edges - - F (name, edges) - .name = name - .edges = edges +T Poly = (String name, [Edge] edges) V _eps = 0.00001 V _huge = 1e+100 diff --git a/Task/Read-a-file-character-by-character-UTF8/PascalABC.NET/read-a-file-character-by-character-utf8.pas b/Task/Read-a-file-character-by-character-UTF8/PascalABC.NET/read-a-file-character-by-character-utf8.pas new file mode 100644 index 0000000000..8527400b89 --- /dev/null +++ b/Task/Read-a-file-character-by-character-UTF8/PascalABC.NET/read-a-file-character-by-character-utf8.pas @@ -0,0 +1,6 @@ +begin + var f := OpenRead('a.txt',Encoding.UTF8); + while not f.Eof do + Print(f.ReadChar); + f.Close +end. diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c index b966412e9a..b3d9bd3659 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c @@ -1,29 +1,30 @@ -/* Programa: Número mayor de tres números introducidos (Solución 1) */ - -#include +/* + * Read (and write) the standard input file + * line-by-line. This version is for ASCII + * encoded text files. + */ #include -int main() +/* + * BUFSIZE is a max size of line plus 1. + * + * It would be nice to dynamically allocate bigger buffer for longer lines etc. + * - but this example is as simple as possible. Dynamic buffer allocation from + * the heap may not be a good idea as it seems, because it can cause memory + * segmentation in embeded systems. + */ +#define BUFSIZE 1024 + +int main(void) { - int n1, n2, n3; + static char buffer[BUFSIZE]; - printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); - scanf( "%d", &n1 ); - printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); - scanf( "%d", &n2 ); - printf( "\n Introduzca el tercer n%cmero (entero): ", 163 ); - scanf( "%d", &n3 ); - - if ( n1 >= n2 && n1 >= n3 ) - printf( "\n %d es el mayor.", n1 ); - else - - if ( n2 > n3 ) - printf( "\n %d es el mayor.", n2 ); - else - printf( "\n %d es el mayor.", n3 ); - - getch(); /* Pausa */ + /* + * Never use gets() instead fgets(), because gets() + * is a really unsafe function. + */ + while (fgets(buffer, BUFSIZE, stdin)) + puts(buffer); return 0; } diff --git a/Task/Read-a-file-line-by-line/PascalABC.NET/read-a-file-line-by-line.pas b/Task/Read-a-file-line-by-line/PascalABC.NET/read-a-file-line-by-line.pas new file mode 100644 index 0000000000..1d927c276d --- /dev/null +++ b/Task/Read-a-file-line-by-line/PascalABC.NET/read-a-file-line-by-line.pas @@ -0,0 +1,6 @@ +begin + var f := OpenRead('_a.pas'); + while not f.Eof do + Println(f.ReadString); + f.Close +end. diff --git a/Task/Read-a-specific-line-from-a-file/PascalABC.NET/read-a-specific-line-from-a-file.pas b/Task/Read-a-specific-line-from-a-file/PascalABC.NET/read-a-specific-line-from-a-file.pas new file mode 100644 index 0000000000..cdd0eb4af5 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/PascalABC.NET/read-a-specific-line-from-a-file.pas @@ -0,0 +1,4 @@ +begin + var linenum := 4; + ReadLines('_a.pas').Skip(linenum-1).First.Print; +end. diff --git a/Task/Read-entire-file/PascalABC.NET/read-entire-file.pas b/Task/Read-entire-file/PascalABC.NET/read-entire-file.pas new file mode 100644 index 0000000000..ac863ce103 --- /dev/null +++ b/Task/Read-entire-file/PascalABC.NET/read-entire-file.pas @@ -0,0 +1,3 @@ +## +var text := ReadAllText('_a.pas',Encoding.UTF8); +Print(text); diff --git a/Task/Real-constants-and-functions/ANSI-BASIC/real-constants-and-functions.basic b/Task/Real-constants-and-functions/ANSI-BASIC/real-constants-and-functions.basic new file mode 100644 index 0000000000..ddc92aa3df --- /dev/null +++ b/Task/Real-constants-and-functions/ANSI-BASIC/real-constants-and-functions.basic @@ -0,0 +1,25 @@ +100 REM Real constants and functions +110 DECLARE EXTERNAL FUNCTION Floor +120 PRINT "e = "; EXP(1) ! e not available +130 PRINT "PI = "; PI +140 LET X = 12.345 +150 LET Y = 1.23 +160 PRINT "sqrt = "; SQR(X), X ^ 0.5 ! square root- NB the unusual name +170 PRINT "ln = "; LOG(X) ! natural logarithm base e +180 PRINT "log2 = "; LOG2(X) ! base 2 logarithm +190 PRINT "log10 = "; LOG10(X) ! base 10 logarithm +200 PRINT "log = "; LOG(X) / LOG(Y) ! arbitrary base logarithm +210 PRINT "exp = "; EXP(X) ! exponential +220 PRINT "abs = "; ABS(-1) ! absolute value +230 PRINT "floor = "; Floor(X) ! floor easily implemented as functions +240 PRINT "ceil = "; CEIL(X) ! ceiling +250 PRINT "power = "; X ^ Y ! power +260 END +270 REM ** +280 EXTERNAL FUNCTION Floor(X) +290 IF X > 0 THEN +300 LET Floor = INT(X) +310 ELSE +320 IF X <> INT(X) THEN LET Floor = INT(X) - 1 ELSE LET Floor = INT(X) +330 END IF +340 END FUNCTION diff --git a/Task/Real-constants-and-functions/Liberty-BASIC/real-constants-and-functions.basic b/Task/Real-constants-and-functions/Liberty-BASIC/real-constants-and-functions.basic index f3022653fc..ebfa00b9c3 100644 --- a/Task/Real-constants-and-functions/Liberty-BASIC/real-constants-and-functions.basic +++ b/Task/Real-constants-and-functions/Liberty-BASIC/real-constants-and-functions.basic @@ -1,32 +1,31 @@ -print exp( 1) ' e not available -print 4 *atn( 1) ' pi not available +print exp(1) ' e not available +print 4 *atn(1) ' pi not available x =12.345: y =1.23 -print sqr( x), x^0.5 ' square root- NB the unusual name -print log( x) ' natural logarithm base e -print log( x) /2.303 ' base 10 logarithm -print log( x) /log( y) ' arbitrary base logarithm -print exp( x) ' exponential -print abs( x) ' absolute value -print floor( x) ' floor -print ceiling( x) ' ceiling -print x^y ' power - +print sqr(x), x^0.5 ' square root- NB the unusual name +print log(x) ' natural logarithm base e +print log(x) /2.303 ' base 10 logarithm +print log(x) / log(y) ' arbitrary base logarithm +print exp(x) ' exponential +print abs(x) ' absolute value +print floor(x) ' floor +print ceiling(x) ' ceiling +print x^y ' power end -function floor( x) +function floor(x) if x >0 then - floor =int( x) + floor =int(x) else - if x <>int( x) then floor =int( x) -1 else floor =int( x) + if x <>int(x) then floor =int(x) -1 else floor =int(x) end if end function -function ceiling( x) +function ceiling(x) if x <0 then - ceiling =int( x) + ceiling =int(x) else - ceiling =int( x) +1 + ceiling =int(x) +1 end if end function diff --git a/Task/Real-constants-and-functions/PascalABC.NET/real-constants-and-functions.pas b/Task/Real-constants-and-functions/PascalABC.NET/real-constants-and-functions.pas new file mode 100644 index 0000000000..4c4864b10e --- /dev/null +++ b/Task/Real-constants-and-functions/PascalABC.NET/real-constants-and-functions.pas @@ -0,0 +1,13 @@ +## +Println(E); +Println(Pi); +var x := 2.5; +Println(Sqrt(x)); +Println(Ln(x)); // natural logarithm +Println(LogN(10,x)); // logarithm with base +Println(Exp(x)); +Println(Abs(-x)); +Println(Floor(x)); +Println(Ceil(x)); +var y := 4.1; +Println(x ** y); diff --git a/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic b/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic index 0fa682fa9d..5773a8fa83 100644 --- a/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic +++ b/Task/Real-constants-and-functions/Run-BASIC/real-constants-and-functions.basic @@ -1,5 +1,5 @@ print "exp:";chr$(9); EXP(1) -print "PI:";chr$(9); 22/7 +print "PI:";chr$(9); 4 * ATN(1) print "Sqr2:";chr$(9); SQR(2) print "Log2:";chr$(9); LOG(2) : REM Base 10 print "Exp2:";chr$(9); EXP(2) diff --git a/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml b/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml index 73fdedeed4..497596d5b3 100644 --- a/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml +++ b/Task/Real-constants-and-functions/Standard-ML/real-constants-and-functions.ml @@ -1,10 +1,11 @@ -Math.e; (* e *) -Math.pi; (* pi *) -Math.sqrt x; (* square root *) -Math.ln x; (* natural logarithm--log base 10 also available (Math.log10) *) -Math.exp x; (* exponential *) -abs x; (* absolute value *) -floor x; (* floor *) -ceil x; (* ceiling *) -Math.pow (x, y); (* power *) -~ x; (* negation *) +Math.e (* e *) +Math.pi (* pi *) +(* Math.tau also available in some implementations *) +Math.sqrt x (* square root *) +Math.ln x (* natural logarithm--log base 10 also available (Math.log10) *) +Math.exp ; (* exponential *) +abs x (* absolute value *) +floor x (* floor *) +ceil x (* ceiling *) +Math.pow (x, y) (* power *) +~x (* negation *) diff --git a/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic b/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic index 43fe0011ee..877869db73 100644 --- a/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic +++ b/Task/Real-constants-and-functions/XBasic/real-constants-and-functions.basic @@ -1,4 +1,4 @@ -PROGRAM "progname" +PROGRAM "realcaf" VERSION "0.0000" IMPORT "xma" @@ -9,15 +9,12 @@ DECLARE FUNCTION Floor (x) FUNCTION Entry () DOUBLE e, pi, x, y - e = EXP(1) PRINT "e = "; e ' e not available pi = 4 * ATAN(1) PRINT "pi = "; pi ' pi not available - x = 12.345 y = 1.23 - PRINT "sqrt = "; SQRT (x) ' square root PRINT "ln = "; LOG (x) ' natural logarithm base e PRINT "log10 = "; LOG10 (x) ' base 10 logarithm diff --git a/Task/Record-sound/00-TASK.txt b/Task/Record-sound/00-TASK.txt index 264fe9687d..64d549b885 100644 --- a/Task/Record-sound/00-TASK.txt +++ b/Task/Record-sound/00-TASK.txt @@ -4,3 +4,4 @@ Record a monophonic 16-bit PCM sound into either memory space, a file or array. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs might not record sound in the same format.) + diff --git a/Task/Record-sound/Ada/record-sound.ada b/Task/Record-sound/Ada/record-sound.ada new file mode 100644 index 0000000000..3afa638764 --- /dev/null +++ b/Task/Record-sound/Ada/record-sound.ada @@ -0,0 +1,33 @@ +with Sf.Audio.SoundBufferRecorder; +with Sf.Audio.SoundBuffer; +with Ada.Text_IO; + +procedure Record_Sound is + use Sf, Sf.Audio, Ada.Text_IO; + Sound_Buffer_Recorder : constant sfSoundBufferRecorder_Ptr := SoundBufferRecorder.create; + Sound_Buffer : sfSoundBuffer_Ptr; +begin + + if Sound_Buffer_Recorder = null then + Put_Line (Standard_Error, "Error: sound recorder not available!"); + return; + end if; + + -- By default the recording is in 16-bit mono. Using the + -- setChannelCount method you can change the number of channels + -- used by the audio capture device to record. + if SoundBufferRecorder.start (Sound_Buffer_Recorder, sampleRate => 44_100) /= sfTrue then + Put_Line (Standard_Error, "Error: sound recorder cannot start!"); + return; + end if; + + delay 10.0; + SoundBufferRecorder.stop (Sound_Buffer_Recorder); + + Sound_Buffer := SoundBufferRecorder.getBuffer (Sound_Buffer_Recorder); + if SoundBuffer.saveToFile (Sound_Buffer, filename => "output.ogg") /= sfTrue then + Put_Line (Standard_Error, "Error: recorded sound could not be saved!"); + end if; + + SoundBufferRecorder.destroy (Sound_Buffer_Recorder); +end Record_Sound; diff --git a/Task/Record-sound/FutureBasic/record-sound.basic b/Task/Record-sound/FutureBasic/record-sound.basic new file mode 100644 index 0000000000..c90517e88e --- /dev/null +++ b/Task/Record-sound/FutureBasic/record-sound.basic @@ -0,0 +1,138 @@ +// --------------- +include "NSLog.incl" +include "Tlbx Speech.incl" +include "Tlbx AVFoundation.incl" + +output "RecordToTextDemo" + +#plist CFBundleIdentifier @"com.futurebasic.RecordToTextDemo" +#plist NSSpeechRecognitionUsageDescription @"Enable speech recognition." +#plist NSMicrophoneUsageDescription @"This app requires microphone access." + +#define FILE_URL fn URLByAppendingPathComponent(fn FileManagerURLForApplicationDirectory,@"MyAudioFile.m4a") +#define RECORDER_KEY @"recorder" + + +_window = 1 +begin enum 1 + _recordBtn +end enum + + +void local fn FixViews + dispatchmain + AVAudioRecorderRef recorder = fn AppProperty( RECORDER_KEY ) + if ( recorder ) + button _recordBtn,,, @"Stop Recording",,,, _window + else + button _recordBtn,,, @"Start Recording",,,, _window + end if + dispatchend +end fn + + +void local fn BuildWindow + window _window, @"Record Demo", (0,0,480,270) + button _recordBtn,,, @"Start Recording", (13,13,129,32) +end fn + + +void local fn MyRecognitionTaskHandler( ref as SFSpeechRecognizerRef, result as SFSpeechRecognitionResultRef, err as ErrorRef, userData as ptr ) + SFTranscriptionRef transcription = fn SFSpeechRecognitionResultBestTranscription( result ) + + if ( err ) + NSLog(@"error") + else + if ( fn SFSpeechRecognitionResultIsFinal( result ) ) + NSLog(@"%@",fn SFTranscriptionFormattedString( transcription )) + end if + end if +end fn + + +void local fn MyRequestAuthorization( status as SFSpeechRecognizerAuthorizationStatus, userData as ptr ) + SFSpeechRecognizerRef recognizer + SFSpeechURLRecognitionRequestRef request + + select ( status ) + case SFSpeechRecognizerAuthorizationStatusNotDetermined : NSLog(@"Authorization not determined") + case SFSpeechRecognizerAuthorizationStatusDenied : NSLog(@"Authorization denied") + case SFSpeechRecognizerAuthorizationStatusRestricted : NSLog(@"Authorization restricted") + case SFSpeechRecognizerAuthorizationStatusAuthorized + recognizer = fn SFSpeechRecognizerInit + if ( fn SFSpeechRecognizerIsAvailable( recognizer ) ) + if ( FILE_URL ) + fn SoundPlay( fn SoundWithContentsOfURL( FILE_URL, YES ) ) + request = fn SFSpeechURLRecognitionRequestWithURL( FILE_URL ) + SFSpeechRecognizerSetSupportsOnDeviceRecognition( recognizer, YES ) + fn SFSpeechRecognizerRecognitionTaskWithResultHandler( recognizer, request, @fn MyRecognitionTaskHandler, NULL ) + end if + else + NSLog(@"Speech recognizer not available") + end if + end select +end fn + + +void local fn RecognizeSpeech + SFSpeechRecognizerRequestAuthorization( @fn MyRequestAuthorization, NULL ) +end fn + + +void local fn RecordAudio + CFDictionaryRef settings = @{ + AVFormatIDKey:@(kAudioFormatMPEG4AAC), + AVEncoderAudioQualityKey:@(AVAudioQualityHigh), + AVSampleRateKey:@44100.0, + AVNumberOfChannelsKey:@1, + AVLinearPCMBitDepthKey:@16} + + AVAudioFormatRef format = fn AVAudioFormatWithSettings( settings ) + AVAudioRecorderRef recorder = fn AVAudioRecorderWithFormat( FILE_URL, format, NULL ) + AppSetProperty( RECORDER_KEY, recorder ) + fn FixViews + fn AVAudioRecorderRecord( recorder ) +end fn + + +void local fn MyRequestAccessHandler( granted as BOOL, userData as ptr ) + if ( granted ) then fn RecordAudio +end fn + + +void local fn StartStopRecording + AVAudioRecorderRef recorder = fn AppProperty( RECORDER_KEY ) + AVAuthorizationStatus status + + if ( recorder ) + AVAudioRecorderStop( recorder ) + AppRemoveProperty( RECORDER_KEY ) + fn FixViews + fn RecognizeSpeech + else + status = fn AVCaptureDeviceAuthorizationStatus( AVMediaTypeAudio ) + select ( status ) + case AVAuthorizationStatusDenied : NSLog(@"Denied") + case AVAuthorizationStatusRestricted : NSLog(@"Restricted") + case AVAuthorizationStatusAuthorized : fn RecordAudio + case AVAuthorizationStatusNotDetermined + AVCaptureDeviceRequestAccess( AVMediaTypeAudio, @fn MyRequestAccessHandler, NULL ) + end select + end if +end fn + + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _btnClick + select ( tag ) + case _recordBtn : fn StartStopRecording + end select + end select +end fn + +fn BuildWindow + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy b/Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy new file mode 100644 index 0000000000..1685915756 --- /dev/null +++ b/Task/Reflection-List-methods/Ecstasy/reflection-list-methods.ecstasy @@ -0,0 +1,14 @@ +module test { + void run() { + @Inject Console console; + + String[] names = &this.actualType.multimethods.keys.toArray(); + console.print($"Method/function names on {this}: {names}"); + + Method[] methods = &this.actualType.methods; + console.print($"The methods of {this}: {methods}"); + + Function[] functions = &this.actualType.functions; + console.print($"The functions of {this}: {functions}"); + } +} diff --git a/Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas b/Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas new file mode 100644 index 0000000000..029c568793 --- /dev/null +++ b/Task/Reflection-List-methods/PascalABC.NET/reflection-list-methods.pas @@ -0,0 +1,7 @@ +## +uses System, System.Reflection; + +var flags := BindingFlags.Instance or BindingFlags.Static + or BindingFlags.Public or BindingFlags.DeclaredOnly; + +typeof(integer).GetMethods(flags).PrintLines; diff --git a/Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy b/Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy new file mode 100644 index 0000000000..3c79454fd4 --- /dev/null +++ b/Task/Reflection-List-properties/Ecstasy/reflection-list-properties.ecstasy @@ -0,0 +1,7 @@ +module test { + void run() { + @Inject Console console; + Property[] properties = &this.actualType.properties; + console.print($"The properties of {this}: {properties}"); + } +} diff --git a/Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas b/Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas new file mode 100644 index 0000000000..b614140a49 --- /dev/null +++ b/Task/Reflection-List-properties/PascalABC.NET/reflection-list-properties.pas @@ -0,0 +1,19 @@ +uses System, System.Reflection; + +type + MyClass = class + private + auto property NumberPrivate: integer := 666; + public + auto property Number: integer := 3; + end; + +begin + var flags := BindingFlags.Instance or BindingFlags.Static + or BindingFlags.Public or BindingFlags.NonPublic + or BindingFlags.DeclaredOnly; + + var obj := new MyClass; + + typeof(MyClass).GetProperties(flags).Select(p -> (p.Name,p.GetValue(obj))).PrintLines; +end. diff --git a/Task/Regular-expressions/Langur/regular-expressions-2.langur b/Task/Regular-expressions/Langur/regular-expressions-2.langur index 6d9268d481..bd9de4fe0c 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-2.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-2.langur @@ -1 +1 @@ -if val .x, .y = submatch(re/(abc+).+?(def)/, "somestring") { ... } +if x, y = submatch(re/(abc+).+?(def)/, "somestring") { ... } diff --git a/Task/Regular-expressions/PascalABC.NET/regular-expressions.pas b/Task/Regular-expressions/PascalABC.NET/regular-expressions.pas new file mode 100644 index 0000000000..97899d31e8 --- /dev/null +++ b/Task/Regular-expressions/PascalABC.NET/regular-expressions.pas @@ -0,0 +1,10 @@ +begin + // text in tag (lazy quantification) + var s := 'abc def ghi'; + foreach var m in s.Matches('(?<=)(.*?)(?=)') do + Println(m.Value, m.Index); + + // take words in parentheses + s := 'one two three four five'; + Regex.Replace(s,'\w+','<$0>').Println; +end. diff --git a/Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas b/Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas new file mode 100644 index 0000000000..2b4aaedfa1 --- /dev/null +++ b/Task/Remove-duplicate-elements/PascalABC.NET/remove-duplicate-elements.pas @@ -0,0 +1,17 @@ +begin + // By algorithm + var nums := Arr(1, 1, 2, 3, 4, 4); + var unique := new List; + foreach var x in nums do + if x not in unique then + unique.Add(x); + unique.Println; + + // By method + var unique2 := nums.Distinct; + unique2.Println; + + // Using hash set + var unique3 := HSet(nums); + unique3.Println; +end. diff --git a/Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas b/Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas new file mode 100644 index 0000000000..debe9b6767 --- /dev/null +++ b/Task/Remove-lines-from-a-file/PascalABC.NET/remove-lines-from-a-file.pas @@ -0,0 +1,9 @@ +procedure RemoveLines(fname: string; start: integer; count: integer := 1); +begin + WriteAllLines(fname, + ReadAllLines(fname).Where((s,ind) -> ind not in start - 1 .. start + count - 2).ToArray) +end; + +begin + RemoveLines('a2.pas',3,2); +end. diff --git a/Task/Rename-a-file/PascalABC.NET/rename-a-file.pas b/Task/Rename-a-file/PascalABC.NET/rename-a-file.pas new file mode 100644 index 0000000000..227ef6594b --- /dev/null +++ b/Task/Rename-a-file/PascalABC.NET/rename-a-file.pas @@ -0,0 +1,9 @@ +uses System.IO; + +begin + &File.Move('input.txt','output.txt'); + &File.Move('\input.txt','\output.txt'); + + Directory.Move('docs','mydocs'); + Directory.Move('\docs','\mydocs'); +end. diff --git a/Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas b/Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas new file mode 100644 index 0000000000..21e04fdb9e --- /dev/null +++ b/Task/Repeat-a-string/PascalABC.NET/repeat-a-string.pas @@ -0,0 +1,2 @@ +## +Print('ha' * 5) diff --git a/Task/Repeat/Applesoft-BASIC/repeat.basic b/Task/Repeat/Applesoft-BASIC/repeat.basic new file mode 100644 index 0000000000..865c1b1d9a --- /dev/null +++ b/Task/Repeat/Applesoft-BASIC/repeat.basic @@ -0,0 +1,20 @@ + 100 FOR I = 768 TO 794 + 110 READ B: POKE I,B: NEXT + 120 DATA165,185,72,165,184,72 + 130 DATA165,118,72,165,117,72 + 140 DATA169,176,72,32,123,221 + 150 DATA32,82,231,32,65,217 + 160 DATA76,210,215 + 170 POKE 1014,0: POKE 1015,3 + + 200 LET P = 400:N = 4 + 210 GOSUB 300"REPEAT P N + 220 END + + 300 IF N < = 0 THEN RETURN + 310 LET N = N - 1 + 320 & P + 330 GOTO 300 + + 400 PRINT "EXAMPLE" + 410 RETURN diff --git a/Task/Repeat/Chapel/repeat-1.chapel b/Task/Repeat/Chapel/repeat-1.chapel new file mode 100644 index 0000000000..6ca234b22f --- /dev/null +++ b/Task/Repeat/Chapel/repeat-1.chapel @@ -0,0 +1,13 @@ +config const n = 5; + +proc example() +{ + writeln("example"); +} + +proc repeat(func, n) +{ + for i in 0..#n do func(); +} + +repeat(example, n); diff --git a/Task/Repeat/Chapel/repeat-2.chapel b/Task/Repeat/Chapel/repeat-2.chapel new file mode 100644 index 0000000000..ac4f950092 --- /dev/null +++ b/Task/Repeat/Chapel/repeat-2.chapel @@ -0,0 +1,13 @@ +config const n = 5; + +proc example() +{ + writeln("example"); +} + +proc repeat(func : proc(), n : uint) +{ + for i in 0..#n do func(); +} + +repeat(example, n); diff --git a/Task/Repeat/Chapel/repeat-3.chapel b/Task/Repeat/Chapel/repeat-3.chapel new file mode 100644 index 0000000000..d229a7de7f --- /dev/null +++ b/Task/Repeat/Chapel/repeat-3.chapel @@ -0,0 +1,13 @@ +config const n = 5; + +proc example(x : uint) +{ + writeln("example ", x); +} + +proc repeat(func : proc(x : uint), n : uint) +{ + for i in 0..#n do func(i); +} + +repeat(example, n); diff --git a/Task/Repeat/PascalABC.NET/repeat.pas b/Task/Repeat/PascalABC.NET/repeat.pas new file mode 100644 index 0000000000..28afa11525 --- /dev/null +++ b/Task/Repeat/PascalABC.NET/repeat.pas @@ -0,0 +1,7 @@ +procedure Rep(n: integer; p: procedure) := (p * n); + +procedure p := Print('Hello'); + +begin + Rep(3,p); +end. diff --git a/Task/Repeat/Refal/repeat.refal b/Task/Repeat/Refal/repeat.refal new file mode 100644 index 0000000000..b826dd004c --- /dev/null +++ b/Task/Repeat/Refal/repeat.refal @@ -0,0 +1,12 @@ +$ENTRY Go { + = Eggs And >; +} + +Repeat { + 0 s.F e.X = e.X; + s.N s.F e.X = s.F >; +}; + +Example { + e.X = e.X Spam; +}; diff --git a/Task/Return-multiple-values/PascalABC.NET/return-multiple-values.pas b/Task/Return-multiple-values/PascalABC.NET/return-multiple-values.pas new file mode 100644 index 0000000000..2b6a90767d --- /dev/null +++ b/Task/Return-multiple-values/PascalABC.NET/return-multiple-values.pas @@ -0,0 +1,6 @@ +function AddSub(x,y: real): (real,real) := (x + y, x - y); + +begin + var (a,s) := AddSub(5,3); + Print(a,s); +end. diff --git a/Task/Reverse-a-string/Langur/reverse-a-string.langur b/Task/Reverse-a-string/Langur/reverse-a-string.langur index 43a9ef1478..7758d7657c 100644 --- a/Task/Reverse-a-string/Langur/reverse-a-string.langur +++ b/Task/Reverse-a-string/Langur/reverse-a-string.langur @@ -1 +1 @@ -writeln reverse "don't you know" +writeln reverse("don't you know") diff --git a/Task/Reverse-a-string/PascalABC.NET/reverse-a-string.pas b/Task/Reverse-a-string/PascalABC.NET/reverse-a-string.pas new file mode 100644 index 0000000000..8425b6bdbe --- /dev/null +++ b/Task/Reverse-a-string/PascalABC.NET/reverse-a-string.pas @@ -0,0 +1,3 @@ +## +var s:='asdf';//ReadLnString; +ReverseString(s).Print; diff --git a/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas b/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas new file mode 100644 index 0000000000..d37e9a9155 --- /dev/null +++ b/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas @@ -0,0 +1,3 @@ +## +var s:='Hey you, Bub!'; +s.ToWords.Reverse.Print; diff --git a/Task/Rhonda-numbers/Python/rhonda-numbers.py b/Task/Rhonda-numbers/Python/rhonda-numbers.py new file mode 100644 index 0000000000..4525bd3730 --- /dev/null +++ b/Task/Rhonda-numbers/Python/rhonda-numbers.py @@ -0,0 +1,47 @@ +# rhonda.py by Xing216 +def prime_factors_sum(n): + i = 2 + factors_sum = 0 + while i * i <= n: + if n % i: + i += 1 + else: + n //= i + factors_sum+=i + if n > 1: + factors_sum+=n + return factors_sum +def digits_product(n: int, base: int): + # translated from the nim solution + i = 1 + while n != 0: + i *= n % base + n //= base + return i +def is_rhonda_num(n:int, base: int): + product = digits_product(n, base) + return product == base * prime_factors_sum(n) +def convert_base(num,b): + numerals="0123456789abcdefghijklmnopqrstuvwxyz" + return ((num == 0) and numerals[0]) or (convert_base(num // b, b).lstrip(numerals[0]) + numerals[num % b]) +def is_prime(n): + if n == 1: + return False + i = 2 + while i*i <= n: + if n % i == 0: + return False + i += 1 + return True +for base in range(4,37): + rhonda_nums = [] + if is_prime(base): + continue + i = 1 + while len(rhonda_nums) < 10: + if is_rhonda_num(i,base) : + rhonda_nums.append(i) + i+=1 + else: + i+=1 + print(f"base {base}: {', '.join([convert_base(n, base) for n in rhonda_nums])}") diff --git a/Task/Rock-paper-scissors/EasyLang/rock-paper-scissors.easy b/Task/Rock-paper-scissors/EasyLang/rock-paper-scissors.easy new file mode 100644 index 0000000000..79c8fd06f4 --- /dev/null +++ b/Task/Rock-paper-scissors/EasyLang/rock-paper-scissors.easy @@ -0,0 +1,24 @@ +tool$[] = [ "rock" "paper" "scissors" ] +repeat + write "choose your weapon: " + h$ = input + c = randint 3 + h$ = substr h$ 1 1 + until h$ = "q" + h = strpos "rps" h$ + if h = 0 + print "that's not a valid choice" + else + print tool$[h] + print "computer: " & tool$[c] + if h = c + print "it's a tie!" + elif (h + 1) mod1 3 = c + print "yay you win!" + else + print "the computer beats you... :(" + . + . + print "" + sleep 1 +. diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js index a0ea2acf23..fc1d5ff210 100644 --- a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js +++ b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-8.js @@ -1,6 +1,7 @@ (() => { + "use strict"; - // -------------- ROMAN NUMERALS DECODED --------------- + // ------------- ROMAN NUMERALS DECODED -------------- // Folding from right to left, // lower leftward characters are subtracted, @@ -8,49 +9,34 @@ // fromRoman :: String -> Int const fromRoman = s => - foldr(l => ([r, n]) => [ - l, - l >= r ? ( - n + l - ) : n - l - ])([0, 0])( - [...s].map(charVal) + [...s] + .map(glyphValue) + .reduceRight( + ([r, n], l) => [ + l, + l >= r + ? n + l + : n - l + ], + [0, 0] )[1]; - // charVal :: Char -> Maybe Int - const charVal = k => { - const v = { - I: 1, - V: 5, - X: 10, - L: 50, - C: 100, - D: 500, - M: 1000 - } [k]; - return v !== undefined ? v : 0; - }; - // ----------------------- TEST ------------------------ - const main = () => [ - 'MDCLXVI', 'MCMXC', 'MMVIII', 'MMXVI', 'MMXVII' - ] - .map(fromRoman) - .join('\n'); + // glyphValue :: Char -> Maybe Int + const glyphValue = k => ({ + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000 + }) [k] || 0; - - // ----------------- GENERIC FUNCTIONS ----------------- - - // foldr :: (a -> b -> b) -> b -> [a] -> b - const foldr = f => - // Note that that the Haskell signature of foldr - // differs from that of foldl - the positions of - // accumulator and current value are reversed. - a => xs => [...xs].reduceRight( - (a, x) => f(x)(a), - a - ); - - // MAIN --- - return main(); + // ---------------------- TEST ----------------------- + return [ + "MDCLXVI", "MCMXC", "MMVIII", "MMXVI", "MMXVII" + ] + .map(fromRoman) + .join("\n"); })(); diff --git a/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode.pas b/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode.pas new file mode 100644 index 0000000000..d41482fd30 --- /dev/null +++ b/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode.pas @@ -0,0 +1,39 @@ +function Rim2Arab(S : String) : Integer; +const //римские числа на соответствующие десятичные числа +R : array[1..14] of String[2] = ('M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I',' '); +A : array[1..14] of Integer = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, 0); +begin + var i := 1; + Result := 0; + while S.Length > 0 do + begin + while S.IndexOf(R[i]) = 0 do + begin + S := S.Remove(0, R[i].Length); + Result += A[i] + end; + i += 1; + end; +end; + +const + L = 'IVXLCDM'; +begin + var S := 'MDCLXVI';//'roman numeral:'; + Write(S,': '); + var index := 1; + repeat + if L.IndexOf(S[index]) < 0 then + index += 1 + else + begin + var Rim : String := ''; + repeat + Rim += S[index]; + S := S.Remove(index - 1, 1); + until (S.Length < index) or (L.IndexOf(S[index]) < 0); + S := S.Insert(index - 1, Rim2Arab(Rim).ToString); + end; + until index > S.Length; + WriteLn(S); +end. diff --git a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js index fbd9878304..a7426eb378 100644 --- a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js +++ b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-4.js @@ -7,9 +7,9 @@ const roman = n => mapAccumL(residue => ([k, v]) => second( - q => 0 < q ? ( - k.repeat(q) - ) : "" + q => 0 < q + ? k.repeat(q) + : "" )(remQuot(residue)(v)) )(n)( zip([ @@ -27,11 +27,31 @@ // main :: IO () const main = () => ( [2016, 1990, 2008, 2000, 2020, 1666].map(roman) - ).join("\n"); + ) + .join("\n"); // ---------------- GENERIC FUNCTIONS ---------------- + // Tuple (,) :: a -> b -> (a, b) + const Tuple = a => + // A pair of values, possibly of + // different types. + b => ({ + type: "Tuple", + "0": a, + "1": b, + length: 2, + *[Symbol.iterator]() { + for (const k in this) { + if (!isNaN(k)) { + yield this[k]; + } + } + } + }); + + // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> // [x] -> (acc, [y]) const mapAccumL = f => @@ -39,14 +59,11 @@ // obtained by a combined map and fold, // with accumulation from left to right. acc => xs => [...xs].reduce( - (a, x) => { - const tpl = f(a[0])(x); - - return [ - tpl[0], - a[1].concat(tpl[1]) - ]; - }, + ([a, bs], x) => second( + v => [...bs, v] + )( + f(a)(x) + ), [acc, []] ); @@ -61,7 +78,11 @@ // A function over a simple value lifted // to a function over a tuple. // f (a, b) -> (a, f(b)) - xy => [xy[0], f(xy[1])]; + xy => Tuple( + xy[0] + )( + f(xy[1]) + ); // zip :: [a] -> [b] -> [(a, b)] diff --git a/Task/Roman-numerals-Encode/PascalABC.NET/roman-numerals-encode.pas b/Task/Roman-numerals-Encode/PascalABC.NET/roman-numerals-encode.pas new file mode 100644 index 0000000000..2c842620d2 --- /dev/null +++ b/Task/Roman-numerals-Encode/PascalABC.NET/roman-numerals-encode.pas @@ -0,0 +1,21 @@ +var anums := |1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1|; +var rnums := 'M CM D CD C XC L XL X IX V IV I'.split; + +function ToRoman(x: integer): string; +begin + Result := ''; + foreach var (a,r) in anums.Zip(rnums) do + begin + var n := x div a; + x := x mod a; + Result += r * n; + end; +end; + +begin + var test := |1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30, 40, + 50, 60, 69, 70, 80, 90, 99, 100, 200, 300, 400, 500, 600, 666, 700, 800, 900, 1000, + 1009, 1444, 1666, 1945, 1997, 1999, 2000, 2008, 2010, 2011, 2500, 3000, 3999|; + foreach var x in test do + Println($'{x} - {ToRoman(x)}') +end. diff --git a/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada b/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada index 29d0419cb0..94bc29261f 100644 --- a/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada +++ b/Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada @@ -27,12 +27,12 @@ procedure Count_Examples is A : Attr; Page : Aws.Response.Data; Uri_Xml : constant String := - "http://rosettacode.org/mw/api.php?action=query&list=categorymembers" + "https://rosettacode.org/w/api.php?action=query&list=categorymembers" & "&format=xml&cmlimit=500&cmtitle=Category:"; begin - Page := Client.Get (Uri_Xml & Category); - if Response.Status_Code (Page) not in Messages.Success then + Page := Client.Get (Uri_Xml & Category, Follow_Redirection => True); + if AWS.Response.Status_Code (Page) not in Messages.Success then raise Client.Connection_Error; end if; declare @@ -65,10 +65,11 @@ procedure Count_Examples is begin Page := Client.Get - ("http://rosettacode.org/mw/index.php?title=" & + ("https://rosettacode.org/w/index.php?title=" & Aws.Url.Encode (Title) & - "&action=raw"); - Response.Message_Body (Page, File); + "&action=raw", + Follow_Redirection => True); + AWS.Response.Message_Body (Page, File); while not End_Of_File (File) loop Resources.Get_Line (File, Buffer, Last); Position := diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada b/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada index 402884b167..2d63221a4c 100644 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada @@ -1,19 +1,18 @@ -with Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url; -with Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs; -with Input_Sources.Strings, Unicode, Unicode.Ces.Utf8; +with AWS.Client, AWS.Messages, AWS.Response, AWS.URL; +with DOM.Readers, DOM.Core, DOM.Core.Documents, DOM.Core.Nodes, DOM.Core.Attrs; +with Input_Sources.Strings, Unicode, Unicode.CES.Utf8; with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line; with Ada.Containers.Vectors; -use Aws.Client, Aws.Messages, Aws.Response, Aws.Resources, Aws.Url; -use Dom.Readers, Dom.Core, Dom.Core.Documents, Dom.Core.Nodes, Dom.Core.Attrs; -use Aws, Ada.Strings.Unbounded, Input_Sources.Strings; +use AWS.Client, AWS.Messages, AWS.Response; +use DOM.Readers, DOM.Core, DOM.Core.Documents, DOM.Core.Nodes, DOM.Core.Attrs; +use AWS, Ada.Strings.Unbounded, Input_Sources.Strings; use Ada.Text_IO, Ada.Command_Line; procedure Not_Coded is - package Members_Vectors is new Ada.Containers.Vectors ( - Index_Type => Positive, - Element_Type => Unbounded_String); + package Members_Vectors is new Ada.Containers.Vectors + (Index_Type => Positive, Element_Type => Unbounded_String); use Members_Vectors; All_Tasks, Language_Members : Vector; @@ -24,36 +23,33 @@ procedure Not_Coded is List : Node_List; N : Node; A : Attr; - Page : Aws.Response.Data; + Page : AWS.Response.Data; S : Messages.Status_Code; - -- Query has cmlimit value of 100, so we need 5 calls to - -- retrieve the complete list of Programming_category + -- Query has cmlimit value of 500, so we need 2 calls to + -- retrieve the complete list of Programming_category Uri_Xml : constant String := - "http://rosettacode.org/mw/api.php?action=query&list=categorymembers" - & - "&format=xml&cmlimit=100&cmtitle=Category:"; + "https://rosettacode.org/w/api.php?action=query&list=categorymembers" & + "&format=xml&cmlimit=500&cmtitle=Category:"; Cmcontinue : Unbounded_String := Null_Unbounded_String; begin loop Page := - Aws.Client.Get (Uri_Xml & Category & (To_String (Cmcontinue))); - S := Response.Status_Code (Page); - if S not in Messages.Success then + AWS.Client.Get (Uri_Xml & Category & (To_String (Cmcontinue))); + S := AWS.Response.Status_Code (Page); + if S not in Messages.Success then Put_Line - ("Unable to retrieve data => Status Code :" & - Image (S) & - " Reason :" & - Reason_Phrase (S)); + ("Unable to retrieve data => Status Code :" & Image (S) & + " Reason :" & Reason_Phrase (S)); raise Connection_Error; end if; + declare Xml : constant String := Message_Body (Page); Source : String_Input; begin Open - (Xml'Unrestricted_Access, - Unicode.Ces.Utf8.Utf8_Encoding, + (Xml'Unrestricted_Access, Unicode.CES.Utf8.Utf8_Encoding, Source); Parse (Reader, Source); Close (Source); @@ -64,22 +60,20 @@ procedure Not_Coded is N := Item (List, Index - 1); A := Get_Named_Item (Attributes (N), "title"); Members_Vectors.Append - (Mbr_Vector, - To_Unbounded_String (Value (A))); + (Mbr_Vector, To_Unbounded_String (Value (A))); end loop; Free (List); - List := Get_Elements_By_Tag_Name (Doc, "query-continue"); + List := Get_Elements_By_Tag_Name (Doc, "continue"); if Length (List) = 0 then - -- we are done + -- we are done Free (List); Free (Reader); exit; end if; - N := First_Child (Item (List, 0)); + N := Item (List, 0); A := Get_Named_Item (Attributes (N), "cmcontinue"); Cmcontinue := - To_Unbounded_String - ("&cmcontinue=" & Aws.Url.Encode (Value (A))); + To_Unbounded_String ("&cmcontinue=" & AWS.URL.Encode (Value (A))); Free (List); Free (Reader); end loop; @@ -88,14 +82,14 @@ procedure Not_Coded is procedure Quick_Diff (From : in out Vector; Substract : in Vector) is Beginning, Position : Extended_Index; begin - -- take adavantage that both lists are already sorted + -- take adavantage that both lists are already sorted Beginning := First_Index (From); for I in First_Index (Substract) .. Last_Index (Substract) loop Position := - Find_Index - (Container => From, - Item => Members_Vectors.Element (Substract, I), - Index => Beginning); + Find_Index + (Container => From, + Item => Members_Vectors.Element (Substract, I), + Index => Beginning); if not (Position = No_Index) then Delete (From, Position); Beginning := Position; @@ -108,6 +102,8 @@ begin Put_Line ("Can't process : No language given!"); return; else + Put ("Language given: "); + Put_Line (Argument (1)); Get_Vector (Argument (1), Language_Members); end if; diff --git a/Task/Rosetta-Code-Rank-languages-by-number-of-users/Jq/rosetta-code-rank-languages-by-number-of-users.jq b/Task/Rosetta-Code-Rank-languages-by-number-of-users/Jq/rosetta-code-rank-languages-by-number-of-users.jq new file mode 100644 index 0000000000..2343a99f0b --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-number-of-users/Jq/rosetta-code-rank-languages-by-number-of-users.jq @@ -0,0 +1,14 @@ +def rpad($len): tostring | ($len - length) as $l | . + (" " * $l); + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def cat: sub("Category:";"") | sub(" User$";""); + +"As of \(now | strftime("%A %B %d, %Y %Z %H:%M") ):", +"\n\("Language" | rpad(30)) Users", +"_" * 36, +([.query.pages[] | {title, n: .categoryinfo.size}] + | sort_by(.n) + | reverse[] + | select(.n>100) + | "\(.title | cat | rpad(30)) \(.n|lpad(5))" ) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada b/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada index 470a835d1b..5313630359 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada @@ -1,23 +1,28 @@ +pragma Ada_2022; + with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Ordered_Sets; -with Ada.Strings.Less_Case_Insensitive; +with Ada.Strings.Unbounded.Less_Case_Insensitive; +with Ada.Characters.Handling; use Ada.Characters.Handling; -with AWS.Client; +with AWS.Client; use AWS.Client; +with AWS.Messages; use AWS.Messages; with AWS.Response; -procedure Test is +procedure Rank_Languages_By_Popularity is use Ada.Strings; - function "+" (S : String) return Unbounded_String renames To_Unbounded_String; + function "+" (S : String) return Unbounded_String + renames To_Unbounded_String; type A_Language_Count is record - Count : Integer := 0; + Count : Natural := 0; Language : Unbounded_String; end record; @@ -28,11 +33,12 @@ procedure Test is function "<" (L, R : A_Language_Count) return Boolean is begin - -- Sort by 'Count' and then by Language name + -- Sort by 'Count' and then by Language name return L.Count < R.Count or else (L.Count = R.Count - and then Less_Case_Insensitive (Left => To_String (L.Language), - Right => To_String (R.Language))); + and then Less_Case_Insensitive + (Left => L.Language, + Right => R.Language)); end "<"; package Sets is new Ada.Containers.Ordered_Sets (A_Language_Count); @@ -41,30 +47,140 @@ procedure Test is Counts : Set; procedure Find_Counts (S : String) is - Title_Str : constant String := "title=""Category:"; - End_A_Str : constant String := " ("; - Title_At : constant Natural := Index (S, Title_Str); + function Strip_Character (S : String; C : Character) return String is + S_Copy_Str : String (1 .. S'Length); + S_Copy_Index : Natural := 0; + begin + for I in S'Range loop + if S (I) /= C then + S_Copy_Index := S_Copy_Index + 1; + S_Copy_Str (S_Copy_Index) := S (I); + end if; + end loop; + + return S_Copy_Str (S_Copy_Str'First .. S_Copy_Index); + end Strip_Character; + + function Ignore_Category (L : String) return Boolean is + type Unbounded_String_Array is array (Positive range <>) + of Unbounded_String; + -- This list is quite comprehensive, but not complete + Categories_To_Ignore : Unbounded_String_Array := [ + +"Pages with syntax highlighting errors", + +"Programming", + +"Examples needing attention", + +"Tasks needing attention", + +"Language users", + +"Implementations", + +"Solutions by ", + +"Maintenance/OmitCategoriesCreated", + +"Collection Members", + +"Pages with too many expensive parser function calls", + +"Garbage collection", + +" User", + +"SQL User", + +"Typing", + +"Parameter passing", + +"Execution method", + +"Unimplemented tasks by language", + +"Wolfram Language", + +"/Omit", + +"Wren-", + +"WrenGo", + +"Phix/", + +"PhixClass", + +"Basic language learning", + +"Encyclopedia", + +"RCTemplates", + +"SysUtils", + +"Action! ", + +"Text processing", + +"Image processing", + +"Scala Digital Signal Processing", + +"List processing", + +"Digital signal processing", + +"Processing Python", + +"Classic CS problems and programs", + +"Brainf*** related", + +"Data Structures", + +"Perl modules", + +"Perl/", + +"Perl:LWP", + +"Perl 6 related", + +"Flow control", + +"Excessively difficult task", + +"WikiStubs", + +"Impl needed", + +"Recursion" + ]; + begin + for Category of Categories_To_Ignore loop + declare + Category_At : constant Natural := + Index (+To_Lower (L), + To_Lower (To_String (Category))); + begin + if Category_At /= 0 then + return True; + end if; + end; + end loop; + + return False; + end Ignore_Category; + + Title_Str : constant String := "title=""Category:"; + End_A_Tag_Str : constant String := ""; + Space_Paren_Str : constant String := " ("; + + Title_At : constant Natural := Index (S, Title_Str); begin if Title_At /= 0 then declare - Bracket_At : constant Natural := Index (S (Title_At + Title_Str'Length .. S'Last), ">"); - End_A_At : constant Natural := Index (S (Bracket_At + 1 .. S'Last), End_A_Str); - Space_At : constant Natural := Index (S (End_A_At + End_A_Str'Length .. S'Last), " "); - Count : constant Natural := Natural'Value (S (End_A_At + End_A_Str'Length .. Space_At - 1)); - Language : constant String := S (Title_At + Title_Str'Length .. Bracket_At - 2); + Closing_Bracket_At : constant Natural := + Index (S (Title_At + Title_Str'Length .. S'Last), ">"); + + End_A_Tag_At : constant Natural := + Index (S (Closing_Bracket_At + 1 .. S'Last), End_A_Tag_Str); + + Language : constant String := + S (Closing_Bracket_At + 1 .. End_A_Tag_At - 1); + + Space_Paren_At : constant Natural := + Index (S (End_A_Tag_At + 1 .. S'Last), Space_Paren_Str); + + Space_At : constant Natural := + Index (S (Space_Paren_At + Space_Paren_Str'Length + 1 + .. S'Last), + " "); + + Count : constant Natural := + Natural'Value ( + Strip_Character ( + S (Space_Paren_At + + Space_Paren_Str'Length + .. Space_At - 1), + ',')); begin - if Bracket_At /= 0 and then End_A_At /= 0 and then Space_At /= 0 then + if Closing_Bracket_At /= 0 + and then End_A_Tag_At /= 0 + and then Space_Paren_At /= 0 + and then Space_At /= 0 + then begin - Counts.Insert (New_Item => (Count, +Language)); + if Ignore_Category (Language) = False then + Counts.Insert (New_Item => (Count, +Language)); + end if; exception when Constraint_Error => - Put_Line (Standard_Error, "Warning: repeated language: " & Language); - -- Ignore repeated results. + Put_Line (Standard_Error, "Warning: repeated language: " & + Language); + -- Ignore repeated results. null; end; end if; - -- Recursively parse the string for languages and counts + -- Recursively parse the string for languages and counts Find_Counts (S (Space_At + 1 .. S'Last)); end; end if; @@ -82,8 +198,26 @@ procedure Test is end Display; Http_Source : constant AWS.Response.Data := - AWS.Client.Get ("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"); + AWS.Client.Get ("http://rosettacode.org/w/index.php?" & + "title=Special:Categories&limit=5000", + Follow_Redirection => True); + Status : Status_Code; begin + Put_Line ("Getting website data..."); + + Status := AWS.Response.Status_Code (Http_Source); + if Status not in Success then + Put_Line ("Unable to retrieve data => Status Code :" & + Image (Status) & + " Reason :" & Reason_Phrase (Status)); + raise Connection_Error; + end if; + + Put_Line ("Finding categories..."); Find_Counts (AWS.Response.Message_Body (Http_Source)); + + Put_Line ("Displaying categories..."); Counts.Reverse_Iterate (Display'Access); -end Test; + + Put_Line ("Process complete."); +end Rank_Languages_By_Popularity; diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Java/rosetta-code-rank-languages-by-popularity.java b/Task/Rosetta-Code-Rank-languages-by-popularity/Java/rosetta-code-rank-languages-by-popularity.java index c2b11e7ab7..d58f8f244f 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Java/rosetta-code-rank-languages-by-popularity.java +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Java/rosetta-code-rank-languages-by-popularity.java @@ -1,3 +1,4 @@ +import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.io.*; @@ -45,10 +46,8 @@ public class GetRCLanguages try { - URL url = new URL( path ); + URL url = new URI( path ).toURL(); URLConnection rc = url.openConnection(); - // Rosetta Code objects to the default Java user agant so use a blank one - rc.setRequestProperty( "User-Agent", "" ); BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) ); gcmcontinue[0] = ""; @@ -56,27 +55,27 @@ public class GetRCLanguages String line = bfr.readLine(); while( line != null ) { - line = line.trim(); - if ( line.startsWith( "[title]" ) ) + line = line.trim().replaceAll( "[\",]", "" ); + if ( line.startsWith( "title" ) ) { - // have a programming language - should look like "[title] => Category:languageName" - languageName = after( line, ':' ).trim(); + // have a programming language - should look like "title: Category:languageName" + languageName = after( after( line, ':' ), ':' ).trim(); } - else if( line.startsWith( "[pages]" ) ) + else if( line.startsWith( "pages" ) ) { // number of pages the language has (probably) - String pageCount = after( line, '>' ).trim(); - if( pageCount.compareTo( "Array" ) != 0 ) + String pageCount = after( line, ':' ).trim(); + if( pageCount.compareTo( "{" ) != 0 ) { - // haven't got "[pages] => Array" - must be a number of pages + // haven't got "pages: {" - must be a number of pages languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName ); languageName = "?"; - } // if [pageCount.compareTo( "Array" ) != 0 + } // if [pageCount.compareTo( "{" ) != 0 } - else if( line.startsWith( "[gcmcontinue]" ) ) + else if( line.startsWith( "gcmcontinue" ) ) { // have an indication of wether there is more data or not - gcmcontinue[0] = after( line, '>' ).trim(); + gcmcontinue[0] = after( line, ':' ).trim().replaceAll( "[|]", "%7C" ); } // if various line starts line = bfr.readLine(); } // while line != null @@ -96,13 +95,13 @@ public class GetRCLanguages gcmcontinue[0] = ""; do { - String path = ( "http://www.rosettacode.org/mw/api.php?action=query" + String path = ( "https://www.rosettacode.org/w/api.php?action=query" + "&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" + "&gcmlimit=500" + ( gcmcontinue[0].compareTo( "" ) == 0 ? "" : ( "&gcmcontinue=" + gcmcontinue[0] ) ) + "&prop=categoryinfo" - + "&format=txt" + + "&format=jsonfm" ); parseContent( path, gcmcontinue, languageList ); } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/PascalABC.NET/rosetta-code-rank-languages-by-popularity.pas b/Task/Rosetta-Code-Rank-languages-by-popularity/PascalABC.NET/rosetta-code-rank-languages-by-popularity.pas new file mode 100644 index 0000000000..883b4194c6 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/PascalABC.NET/rosetta-code-rank-languages-by-popularity.pas @@ -0,0 +1,13 @@ +uses System.Net; + +begin + ServicePointManager.SecurityProtocol := SecurityProtocolType(3072); + var wc := new WebClient; + wc.Encoding := Encoding.UTF8; + var s := wc.DownloadString('https://rosettacode.org/wiki/Special:Categories?limit=5000'); + s.Matches('([^><]+).+\(([\d,]+) member') + .Select(x -> KV(x.Groups[1].Value,x.Groups[2].Value.Replace(',','').ToInteger)) + .Where(x -> not x.Key.StartsWith('Pages')) + .OrderByDescending(pair -> pair.Value).Numerate.Take(10) + .PrintLines(x -> $'Rank: {x[0],3} ({x[1].Value} entries) {x[1].Key}') +end. diff --git a/Task/Rot-13/PascalABC.NET/rot-13.pas b/Task/Rot-13/PascalABC.NET/rot-13.pas new file mode 100644 index 0000000000..5f57c13e01 --- /dev/null +++ b/Task/Rot-13/PascalABC.NET/rot-13.pas @@ -0,0 +1,19 @@ +function Rot13(s: string): string; +begin + var sb := new StringBuilder; + foreach var c in s do + begin + var c1 := c; + if c in 'a'..'z' then + c1 := Chr((c.Code - 'a'.Code + 13) mod 26 + 'a'.Code) + else if c in 'A'..'Z' then + c1 := Chr((c.Code - 'A'.Code + 13) mod 26 + 'A'.Code); + sb.Append(c1) + end; + Result := sb.ToString; +end; + +begin + Println(rot13('foo')); + Println(rot13('sbb')) +end. diff --git a/Task/Run-length-encoding/Uiua/run-length-encoding.uiua b/Task/Run-length-encoding/Uiua/run-length-encoding.uiua new file mode 100644 index 0000000000..d2b538adf4 --- /dev/null +++ b/Task/Run-length-encoding/Uiua/run-length-encoding.uiua @@ -0,0 +1,10 @@ +# Run Length Encoding and Decoding + +"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +Split ← ⇌∧(:⊃(⊂□↙)↘)≡/-◫2⊂¯1⊙⊙{} # Use the indexes to cut the string. +Rle ← setinv( + /◇⊂⊜(□⊂⊃(°⋕⧻|⊢))+1⊛. +| ∧(⊂/⊂↯⋕◇⊃↘↙¯1):Split⊚≥@A. +) + +&p⨬("oops"|"good")≍&p.°Rle&p.⊸Rle&p. diff --git a/Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic b/Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic new file mode 100644 index 0000000000..8380944173 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/FreeBASIC/runtime-evaluation-in-an-environment.basic @@ -0,0 +1,10 @@ +#include "solver.bi" + +Dim As String expression = "(x ^ 2 )-7" + +setVar("x",1.2) +Print "one = ";Solver(expression) +setVar("x",3.4) +Print "two = ";Solver(expression) + +Sleep diff --git a/Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy b/Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy new file mode 100644 index 0000000000..f77e6f3c62 --- /dev/null +++ b/Task/Ruth-Aaron-numbers/EasyLang/ruth-aaron-numbers.easy @@ -0,0 +1,40 @@ +func divsum n alldiv . + f = 2 + repeat + q = n / f + if n mod f = 0 + if alldiv = 1 + s1 += f + else + if f <> f0 + s1 += f + f0 = f + . + . + n = q + else + f += 1 + . + until f > n + . + return s1 +. +proc ruth_aaron alldiv . . + n = 2 + repeat + s = divsum n alldiv + if s = s0 + write n - 1 & " " + c += 1 + . + s0 = s + n += 1 + until c >= 30 + . +. +print "first 30 ruth-aaron numbers (factors):" +ruth_aaron 1 +print "" +print "" +print "first 30 ruth-aaron numbers (divisors):" +ruth_aaron 0 diff --git a/Task/SEDOLs/Langur/sedols.langur b/Task/SEDOLs/Langur/sedols.langur index ce5b39d4a1..df0c67a995 100644 --- a/Task/SEDOLs/Langur/sedols.langur +++ b/Task/SEDOLs/Langur/sedols.langur @@ -1,26 +1,26 @@ -val .csd = fn(.code) { - switch len(.code) { +val csd = fn(code) { + switch len(code) { case 0: return "nada, zip, zilch" case != 6: return "invalid length" } - if .code -> re/[^B-DF-HJ-NP-TV-Z0-9]/ { + if code -> re/[^B-DF-HJ-NP-TV-Z0-9]/ { return "invalid character(s)" } - val .weight = [1,3,1,7,3,9] + val weight = [1,3,1,7,3,9] - val .nums = s2n .code - val .sum = for[=0] .i of .nums { - _for += .nums[.i] * .weight[.i] + val nums = s2n(code) + val sum = for[=0] i of nums { + _for += nums[i] * weight[i] } - string 9 - (.sum - 1) rem 10 + string 9 - (sum - 1) rem 10 } -val .h = h{ +val h = { # invalid... "": 0, "123": 0, @@ -45,14 +45,14 @@ val .h = h{ "B00030": 0, } -for .input in sort(keys .h) { - val .d = .csd(.input) - if len(.d) > 1 { - writeln .input, ": ", .d +for input in sort(keys(h)) { + val d = csd(input) + if len(d) > 1 { + writeln input, ": ", d } else { - val .expect = string .h[.input] - write .input, .d - writeln if .expect == .d {""} else { - $" (SEDOL test failed; expected check digit \.expect;)"} + val expect = h[input] -> string + write input, d + writeln if expect == d {""} else { + " (SEDOL test failed; expected check digit {{expect}})"} } } diff --git a/Task/SHA-256/Java/sha-256.java b/Task/SHA-256/Java/sha-256.java index 5331ce7af5..40dfd1b2f9 100644 --- a/Task/SHA-256/Java/sha-256.java +++ b/Task/SHA-256/Java/sha-256.java @@ -49,7 +49,7 @@ final class SHA256 { } private static byte[] addPadding(String message) { - byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + byte[] bytes = message.getBytes(StandardCharsets.ISO_8859_1); bytes = Arrays.copyOf(bytes, bytes.length + 1); bytes[bytes.length - 1] = (byte) 0x80; diff --git a/Task/SHA-256/V-(Vlang)/sha-256.v b/Task/SHA-256/V-(Vlang)/sha-256.v index 2182efdc4c..3ac675f005 100644 --- a/Task/SHA-256/V-(Vlang)/sha-256.v +++ b/Task/SHA-256/V-(Vlang)/sha-256.v @@ -1,9 +1,9 @@ import crypto.sha256 fn main() { - println("${sha256.hexhash('Rosetta code')}") + println('${sha256.hexhash('Rosetta code')}') mut h := sha256.new() - h.write('Rosetta code'.bytes()) ? - println('${h.checksum().map(it.hex()).join('')}') + h.write('Rosetta code'.bytes())! + println('${h.sum([]u8{}).hex()}') } diff --git a/Task/Safe-addition/Langur/safe-addition.langur b/Task/Safe-addition/Langur/safe-addition.langur new file mode 100644 index 0000000000..c21dd4d022 --- /dev/null +++ b/Task/Safe-addition/Langur/safe-addition.langur @@ -0,0 +1 @@ +writeln 1.2 + 0.03 diff --git a/Task/Sailors-coconuts-and-a-monkey-problem/EasyLang/sailors-coconuts-and-a-monkey-problem.easy b/Task/Sailors-coconuts-and-a-monkey-problem/EasyLang/sailors-coconuts-and-a-monkey-problem.easy new file mode 100644 index 0000000000..b8f4a4f96f --- /dev/null +++ b/Task/Sailors-coconuts-and-a-monkey-problem/EasyLang/sailors-coconuts-and-a-monkey-problem.easy @@ -0,0 +1,18 @@ +func valid n nuts . + k = n + while k <> 0 + if nuts mod n <> 1 + return 0 + . + k -= 1 + nuts -= 1 + nuts div n + . + return if nuts <> 0 and nuts mod n = 0 +. +for n = 5 to 6 + x = 0 + while valid n x = 0 + x += 1 + . + print n & ": " & x +. diff --git a/Task/Scope-Function-names-and-labels/EasyLang/scope-function-names-and-labels.easy b/Task/Scope-Function-names-and-labels/EasyLang/scope-function-names-and-labels.easy new file mode 100644 index 0000000000..fd8a09f537 --- /dev/null +++ b/Task/Scope-Function-names-and-labels/EasyLang/scope-function-names-and-labels.easy @@ -0,0 +1,13 @@ +# function names are global, the must be +# implemented or declared before usage +# +func foo1 a . + return a + 1 +. +print foo1 2 +# +funcdecl foo2 a . +print foo2 2 +func foo2 a . + return a + 2 +. diff --git a/Task/Scope-Function-names-and-labels/Wren/scope-function-names-and-labels.wren b/Task/Scope-Function-names-and-labels/Wren/scope-function-names-and-labels.wren index 12e8b689b0..e0b97bb5b2 100644 --- a/Task/Scope-Function-names-and-labels/Wren/scope-function-names-and-labels.wren +++ b/Task/Scope-Function-names-and-labels/Wren/scope-function-names-and-labels.wren @@ -1,4 +1,4 @@ -//func.call() /* invalid, can't call func before its declared */ +// func.call() /* invalid, can't call func before its defined */ var func = Fn.new { System.print("func has been called.") } @@ -7,8 +7,17 @@ func.call() // fine //C.init() /* not OK, as C is null at this point */ class C { - static init() { method() } // fine even though 'method' not yet declared + static init() { method() } // fine even though 'method' not yet defined static method() { System.print("method has been called.") } } C.init() // fine + +/* Although this function is recursive, there is no need for a forward + declaration as it is top-level and begins with a capital letter. */ +var Fib = Fn.new { |n| + if (n < 2) return n + return Fib.call(n-1) + Fib.call(n-2) // Fib already visible here +} + +System.print(Fib.call(8)) // fine diff --git a/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-1.pas b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-1.pas new file mode 100644 index 0000000000..3e18ebf09e --- /dev/null +++ b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-1.pas @@ -0,0 +1 @@ +private diff --git a/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-2.pas b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-2.pas new file mode 100644 index 0000000000..418c98625a --- /dev/null +++ b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-2.pas @@ -0,0 +1 @@ +protected diff --git a/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-3.pas b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-3.pas new file mode 100644 index 0000000000..a48cf0de7a --- /dev/null +++ b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-3.pas @@ -0,0 +1 @@ +public diff --git a/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-4.pas b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-4.pas new file mode 100644 index 0000000000..ce83b25d66 --- /dev/null +++ b/Task/Scope-modifiers/PascalABC.NET/scope-modifiers-4.pas @@ -0,0 +1 @@ +internal diff --git a/Task/Search-a-list/Ecstasy/search-a-list.ecstasy b/Task/Search-a-list/Ecstasy/search-a-list.ecstasy new file mode 100644 index 0000000000..3806d41af5 --- /dev/null +++ b/Task/Search-a-list/Ecstasy/search-a-list.ecstasy @@ -0,0 +1,12 @@ +module test { + @Inject Console console; + + void run() { + String[] haystack = ["this", "needle", "is", "a", "test"]; + if (Int pos := haystack.indexOf("needle")) { + console.print($"Found the needle at {pos=}"); + } else { + console.print("No needle in the haystack"); + } + } +} diff --git a/Task/Search-in-paragraphs-text/Perl/search-in-paragraphs-text.pl b/Task/Search-in-paragraphs-text/Perl/search-in-paragraphs-text.pl new file mode 100644 index 0000000000..020884a4a4 --- /dev/null +++ b/Task/Search-in-paragraphs-text/Perl/search-in-paragraphs-text.pl @@ -0,0 +1,15 @@ +use strict; +use warnings; + +local $/ = ""; # Set the input record separator to an empty string to read paragraph mode +local $\ = "\n----------------\n"; # Set the output record separator + +# Open the file Traceback.txt for reading +open my $fh, '<', 'Traceback.txt' or die "Cannot open Traceback.txt: $!"; + +# Read one paragraph at a time +while (<$fh>) { + if (/Traceback \(most recent call last\):/ && /SystemError/) { + print substr($_, index($_, "Traceback (most recent call last):")); + } +} diff --git a/Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada/selectively-replace-multiple-instances-of-a-character-within-a-string.ada b/Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada/selectively-replace-multiple-instances-of-a-character-within-a-string.ada new file mode 100644 index 0000000000..3e21c4e429 --- /dev/null +++ b/Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada/selectively-replace-multiple-instances-of-a-character-within-a-string.ada @@ -0,0 +1,42 @@ +-- Selectively replace multiple instances of a character within a string +-- J. Carter 2024 Jun + +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Selectively_Replace is + procedure Replace + (Letter : in Character; Occurrence : in Positive; Within : in String; By : in Character; Into : in out String) + with Pre => Into'First = Within'First and Into'Last = Within'Last; + -- Finds the index of the Occurrence-th instance of Letter in Within and sets the character in Into at that index to By + -- If there is no such index, has no effect + -- Before the first call to replace, Within should be = Into + + procedure Replace + (Letter : in Character; Occurrence : in Positive; Within : in String; By : in Character; Into : in out String) + is + Start : Natural := 0; + begin -- Replace + Find : for I in 1 .. Occurrence loop + Start := Ada.Strings.Fixed.Index (Within, Letter & "", Start + 1); + + if Start = 0 then -- Within has fewer than Occurrence instances of Letter + return; + end if; + end loop Find; + + Into (Start) := By; + end Replace; + + Source : constant String := "abracadabra"; + + Result : String := Source; +begin -- Selectively_Replace + Replace (Letter => 'a', Occurrence => 1, Within => Source, By => 'A', Into => Result); + Replace (Letter => 'a', Occurrence => 2, Within => Source, By => 'B', Into => Result); + Replace (Letter => 'a', Occurrence => 4, Within => Source, By => 'C', Into => Result); + Replace (Letter => 'a', Occurrence => 5, Within => Source, By => 'D', Into => Result); + Replace (Letter => 'b', Occurrence => 1, Within => Source, By => 'E', Into => Result); + Replace (Letter => 'r', Occurrence => 2, Within => Source, By => 'F', Into => Result); + Ada.Text_IO.Put_Line (Item => Source & " => " & Result); +end Selectively_Replace; diff --git a/Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/EasyLang/selectively-replace-multiple-instances-of-a-character-within-a-string.easy b/Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/EasyLang/selectively-replace-multiple-instances-of-a-character-within-a-string.easy new file mode 100644 index 0000000000..9fcb0ea68b --- /dev/null +++ b/Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/EasyLang/selectively-replace-multiple-instances-of-a-character-within-a-string.easy @@ -0,0 +1,20 @@ +rs$[] = [ "a" "b" "r" ] +rc[][] = [ [ 1 2 4 5 ] [ 1 ] [ 2 ] ] +rd$[][] = [ [ "A" "B" "C" "D" ] [ "E" ] [ "F" ] ] +s$ = "abracadabra" +# +len cnt[] len rs$[] +for c$ in strchars s$ + for i to len rs$[] + if c$ = rs$[i] + cnt[i] += 1 + for j to len rc[i][] + if rc[i][j] = cnt[i] + c$ = rd$[i][j] + . + . + . + . + r$ &= c$ +. +print r$ diff --git a/Task/Self-numbers/EasyLang/self-numbers.easy b/Task/Self-numbers/EasyLang/self-numbers.easy new file mode 100644 index 0000000000..ceb25d963d --- /dev/null +++ b/Task/Self-numbers/EasyLang/self-numbers.easy @@ -0,0 +1,47 @@ +fastfunc digsum h . + while h > 0 + sum += h mod 10 + h = h div 10 + . + return sum +. +fastfunc isself start i . + j = start + sum = digsum start + while j < i + if j + sum = i + return 0 + . + sum += 1 + j += 1 + if j mod 10 = 0 + sum = digsum j + . + . + return 1 +. +proc main . . + i = 1 + po = 10 + digits = 1 + offs = 9 + repeat + start = higher (i - offs) 0 + if isself start i = 1 + cnt += 1 + if cnt <= 50 + write i & " " + . + . + until cnt = 100000000 + i += 1 + if i mod po = 0 + po *= 10 + digits += 1 + offs = digits * 9 + . + . + print "" + print i +. +main diff --git a/Task/Semiprime/REXX/semiprime-4.rexx b/Task/Semiprime/REXX/semiprime-4.rexx new file mode 100644 index 0000000000..9a4cef25e5 --- /dev/null +++ b/Task/Semiprime/REXX/semiprime-4.rexx @@ -0,0 +1,59 @@ +/*REXX program determines if any integer (or a range of integers) is/are semiprime. */ +numeric digits 100 +call time('r') +parse arg bot top . /*obtain optional arguments from the CL*/ +if bot=='' | bot=="," then bot=random() /*None givenqq User wants us to guess.*/ +if top=='' | top=="," then top=bot /*maybe define a range of numbers. */ +tell= (top>0) /*should results be shown to the termqq */ +w=max(length(bot), length(top)) /*obtain the maximum width of numbers. */ +numeric digits max(9, w) /*ensure there're enough decimal digits*/ +hh=0 /*initialize number of semiprimes found*/ + do n=abs(bot) to abs(top) /*show results for a range of numbers. */ + qq=semiPrime(n); hh=hh+qq /*Is N a semiprimeqq; Maybe bump counter*/ +if tell then say right(n,w) right(word("isn't" 'is', qq+1), 6) 'semiprime.' '('format(time('e'),,3) 'seconds)' +call time('r') + end /*n*/ +say +if bot\==top then say 'found ' hh " semiprimes." +say format(time('e'),,3) ' seconds' +exit /*stick a fork in it, we're all done. */ +/*--------------------------------------------------------------------------------------*/ +Semiprime: +-- Is a number semi prime? function +procedure expose glob. +arg x +-- Validity +if \ whole(x) then + return 'X' +if x < 1 then + return 'X' +if x < 4 then + return 0 +-- Low semiprimes +s = '4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95' +-- Fast values +if x < 101 then do + if wordPos(x,s) = 0 then + return 0 + else + return 1 +end +-- Wheeled scan +do i = 2 for 2 + if x//i = 0 then + if Prime(x%i) then + return 1 + else + return 0 +end +do i = 5 by 6 until i*i > x +-- say 'i' i 'i*i' i*i 'x' x + do j = i by 2 for 2 + if x//j==0 then + if Prime(x%j) then + return 1 + else + return 0 + end +end +return 0 diff --git a/Task/Semordnilap/SuperCollider/semordnilap-1.sc b/Task/Semordnilap/SuperCollider/semordnilap-1.sc deleted file mode 100644 index aa3774f558..0000000000 --- a/Task/Semordnilap/SuperCollider/semordnilap-1.sc +++ /dev/null @@ -1,12 +0,0 @@ -( -var text, words, sdrow, semordnilap, selection; -File.use("unixdict.txt".resolveRelative, "r", { |f| x = text = f.readAllString }); -words = text.split(Char.nl).collect { |each| each.asSymbol }; -sdrow = text.reverse.split(Char.nl).collect { |each| each.asSymbol }; -semordnilap = sect(words, sdrow); // converted to symbols so intersection is possible -semordnilap = semordnilap.collect { |each| each.asString }; -"There are % in unixdict.txt\n".postf(semordnilap.size); -"For example those, with more than 3 characters:".postln; -selection = semordnilap.select { |each| each.size >= 4 }.scramble.keep(4); -selection.do { |each| "% %\n".postf(each, each.reverse); }; -) diff --git a/Task/Semordnilap/SuperCollider/semordnilap-2.sc b/Task/Semordnilap/SuperCollider/semordnilap-2.sc deleted file mode 100644 index c33b0276f6..0000000000 --- a/Task/Semordnilap/SuperCollider/semordnilap-2.sc +++ /dev/null @@ -1,6 +0,0 @@ -There are 405 in unixdict.txt -For example those, with more than 3 characters: -live evil -tram mart -drib bird -eros sore diff --git a/Task/Semordnilap/Uiua/semordnilap.uiua b/Task/Semordnilap/Uiua/semordnilap.uiua index 8c92539883..6905130272 100644 --- a/Task/Semordnilap/Uiua/semordnilap.uiua +++ b/Task/Semordnilap/Uiua/semordnilap.uiua @@ -1 +1,3 @@ -&p &pf "Count: " ⧻.▽≡(×>⇌.⟜∊⇌)⟜¤. ⊜□ ≠@\n. &fras "unixdict.txt" +A ← map:⊚⧻.⊜□≠@\n.&fras"unixdict.txt" +▽:⟜≡(↧⊃(<⇌.|has⇌))⊙◌°map⟜¤A +&p$"Found _ semordnilaps:"⊸⧻ diff --git a/Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy b/Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy new file mode 100644 index 0000000000..b6f5ebf098 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Ecstasy/send-an-unknown-method-call.ecstasy @@ -0,0 +1,21 @@ +module test { + @Inject Console console; + + void run(String[] args) { + String name = args.empty ? "foo" : args[0]; + if (val mm := &this.actualType.multimethods.get(name), + val m := mm.methods.any(m -> m.ParamTypes.size == 0)) { + m.invoke(this, Tuple:()); + } else { + console.print($"No such 0-parameter method: {name.quoted()}"); + } + } + + void foo() { + console.print("this is the foo() method"); + } + + void bar() { + console.print("this is the bar() method"); + } +} diff --git a/Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas b/Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas new file mode 100644 index 0000000000..00019bcb23 --- /dev/null +++ b/Task/Send-an-unknown-method-call/PascalABC.NET/send-an-unknown-method-call.pas @@ -0,0 +1,10 @@ +type MyClass = class +public + procedure Hello := Write('Hello'); +end; + +begin + var obj := new MyClass; + var mi := typeof(MyClass).GetMethod('Hello'); + mi.Invoke(obj,new object[0]) +end. diff --git a/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas b/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas new file mode 100644 index 0000000000..eee758aeaa --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas @@ -0,0 +1,4 @@ +## +function IsPrime(n: integer) := (2..n.Sqrt.Round).All(i -> n.NotDivs(i)); + +(2..100).Where(IsPrime).Println diff --git a/Task/Set-puzzle/Jq/set-puzzle.jq b/Task/Set-puzzle/Jq/set-puzzle.jq new file mode 100644 index 0000000000..fadc9523e6 --- /dev/null +++ b/Task/Set-puzzle/Jq/set-puzzle.jq @@ -0,0 +1,77 @@ +# Source of entropy +include "MRG32k3a" {search: "."}; # see above + +### General utilities + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def array_swap($i; $j): + if $i < $j then array_swap($j;$i) + elif $i == $j then . + else .[$i] as $t + | .[:$j] + [$t] + .[$j:$i] + .[$i + 1:] + end ; + +# input: array of length $n +def shuffle: + length as $n + | ($n | prn($n)) as $prn + # First cut the deck + | .[$prn[0]:] + .[:$prn[0]] + | reduce range(0; $n - 1) as $i (.; + array_swap($prn[$i]; $prn[$i+1]) ) ; + + +### The Set Game + +# For the standard Set game: +def attributes: ["Color", "Symbol", "Number", "Shading"]; +def number_of_values: 3; + +# a single card +def toString: + [attributes, .] | transpose + | map(join(": ")|lpad(7)) + | join(" "); + +# Create a deck for which each attribute defined by `attributes` has $j possible values: +def createDeck($j): + (attributes|length) as $k + | [range(0;$j)] + | [combinations($k)]; + +def isSet: + . as $trio + | all( range(0; attributes|length); + . as $i | $trio | map(.[$i]) | unique | length | IN(1,number_of_values)); + +# For the standard Set game +# For "advanced" play, set $advanced == true +def playGame( $advanced ): + (if $advanced then 12 else 9 end) as $nCards + | (($nCards/2)|floor) as $nSets + | {sets: [], deck: createDeck(number_of_values) } + | label $out + | foreach range(0; infinite) as $_ (.; + .deck |= shuffle + | .sets = [] + | foreach range(0; $nCards-2) as $i (.; + foreach range($i+1; $nCards-1) as $j (.; + foreach range($j+1; $nCards) as $k (.; + [.deck[$i], .deck[$j], .deck[$k]] as $trio + | if $trio | isSet + then .sets += [$trio] + | if (.sets|length) >= $nSets + then .emit = true, break $out + end + end ) ) ) ) + | select(.emit) + | (.deck[0:$nCards] | sort) as $hand + | "DEALT \($nCards) CARDS:", + ($hand[]|toString), + "\nCONTAINING \($nSets) SETS:", + (.sets + | sort[] + | ((.[] | toString),"") ), "" ; + +playGame(false, true) diff --git a/Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq b/Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq new file mode 100644 index 0000000000..e82b0d59fa --- /dev/null +++ b/Task/Set-right-adjacent-bits/Jq/set-right-adjacent-bits.jq @@ -0,0 +1,27 @@ +# Input should be an array of 0s and 1s +def setRightBits($e; $n): + if $e == 0 or $n <= 0 then . + else . as $bits + | reduce range(0; $e - 1) as $i ({bits2: .}; + $bits[$i] as $c + | if $c == 1 + then .j = $i + 1 + | until (.j > ($i + $n) or .j >= $e; + .bits2[.j] = 1 + | .j += 1 ) + end) + | .bits2 + end; + +def b: + "010000000000100000000010000000010000000100000010000010000100010010"; + +def tests: + [["1000", 2], ["0100", 2], ["0010", 2], ["0000", 2], [b, 0], [b, 1], [b, 2], [b, 3]]; + +tests[] as [$bits, $n] +| ($bits|length) as $e +| "n = \($n); Width e = \($e):", + " Input b: \($bits)", + ( ($bits | [explode[] | . - 48]) as $b + | " Result: \($b | setRightBits($e; $n) | join(""))\n" ) diff --git a/Task/Sexy-primes/BASIC256/sexy-primes.basic b/Task/Sexy-primes/BASIC256/sexy-primes.basic new file mode 100644 index 0000000000..83b424fff2 --- /dev/null +++ b/Task/Sexy-primes/BASIC256/sexy-primes.basic @@ -0,0 +1,70 @@ +include "isprime.kbs" + +maxi = 1000035 +cu = 0 +c2 = 0 +c3 = 0 +c4 = 0 +c5 = 0 +#, n, i, +p = 0 +dim unsexy(10) +dim pairs(5) +dim trips(5) +dim quads(5) +dim quins(5) + +for n = maxi to 2 step -1 + if isPrime(n) then + p += 1 + if not isPrime(n-6) and not isPrime(n+6) then + if cu < 10 then unsexy[cu] = n + cu += 1 + end if + if isPrime(n-6) then + if c2 < 5 then pairs[c2] = n + c2 += 1 + if isPrime(n-12) then + if c3 < 5 then trips[c3] = n + c3 += 1 + if isPrime(n-18) then + if c4 < 5 then quads[c4] = n + c4 += 1 + if isPrime(n-24) then + if c5 < 5 then quins[c5] = n + c5 += 1 + end if + end if + end if + end if + end if +next n + +print p; " primes less than "; maxi + +print chr(10); c2; " pairs ending with:" +for i = 4 to 0 step -1 + print " ["; pairs[i]-6; ", "; pairs[i]; "]" +next i + +print chr(10); c3; " triplets ending with:" +for i = 4 to 0 step -1 + print " ["; trips[i]-12; ", "; trips[i]-6; ", "& trips[i]; "]" +next i + +print chr(10); c4; " quadruplets ending with:" +for i = 4 to 0 step -1 + print " ["; quads[i]-18; ", "; quads[i]-12; ", "; quads[i]-6; ", "; quads[i]; "]" +next i + +print chr(10); c5; " quintuplet(s) ending with:" +if c5 > 5 then i = 5 else i = c5 +for i = i-1 to 0 step -1 + print " ["; quins[i]-24; ", "& quins[i]-18; ", "& quins[i]-12; ", "& quins[i]-6; ", "& quins[i]; "]" +next i + +print chr(10); cu; " unsexy primes ending with:" +for i = 9 to 0 step -1 + print unsexy[i]; ","; +next i +end diff --git a/Task/Sexy-primes/FreeBASIC/sexy-primes.basic b/Task/Sexy-primes/FreeBASIC/sexy-primes.basic index 91dfcd7117..1fc2d9420a 100644 --- a/Task/Sexy-primes/FreeBASIC/sexy-primes.basic +++ b/Task/Sexy-primes/FreeBASIC/sexy-primes.basic @@ -1,14 +1,4 @@ -Function isPrime(Byval ValorEval As Uinteger) As Boolean - If ValorEval < 2 Then Return False - If ValorEval Mod 2 = 0 Then Return ValorEval = 2 - If ValorEval Mod 3 = 0 Then Return ValorEval = 3 - Dim d As Integer = 5 - While d * d <= ValorEval - If ValorEval Mod d = 0 Then Return False Else d += 2 - If ValorEval Mod d = 0 Then Return False Else d += 4 - Wend - Return True -End Function +#include "isprime.bas" #define maxi 1000035 Dim As Integer CU = 0, C2 = 0, C3 = 0, C4 = 0, C5 = 0, N, I, P = 0 diff --git a/Task/Sexy-primes/Yabasic/sexy-primes.basic b/Task/Sexy-primes/Yabasic/sexy-primes.basic new file mode 100644 index 0000000000..5873017f2e --- /dev/null +++ b/Task/Sexy-primes/Yabasic/sexy-primes.basic @@ -0,0 +1,66 @@ +import isprime + +maxi = 1000035 +cu = 0 +c2 = 0 +c3 = 0 +c4 = 0 +c5 = 0 +p = 0 +dim unsexy(10), pairs(5), trips(5), quads(5), quins(5) + +for n = maxi to 2 step -1 + if isPrime(n) then + p = p + 1 + if not isPrime(n - 6) and not isPrime(n + 6) then + if cu < 10 unsexy(cu) = n + cu = cu + 1 + fi + if isPrime(n - 6) then + if c2 < 5 pairs(c2) = n + c2 = c2 + 1 + if isPrime(n - 12) then + if c3 < 5 trips(c3) = n + c3 = c3 + 1 + if isPrime(n - 18) then + if c4 < 5 quads(c4) = n + c4 = c4 + 1 + if isPrime(n - 24) then + if c5 < 5 quins(c5) = n + c5 = c5 + 1 + fi + fi + fi + fi + fi +next n + +print p, " primes less than ", maxi + +print chr$(10), c2, " pairs ending with:" +for i = 4 to 0 step -1 + print " [", pairs(i)-6, ", ", pairs(i), "]" +next i + +print chr$(10), c3, " triplets ending with:" +for i = 4 to 0 step -1 + print " [", trips(i)-12, ", ", trips(i)-6, ", ", trips(i), "]" +next i + +print chr$(10), c4, " quadruplets ending with:" +for i = 4 to 0 step -1 + print " [", quads(i)-18, ", ", quads(i)-12, ", ", quads(i)-6, ", ", quads(i), "]" +next i + +print chr$(10), c5, " quintuplet(s) ending with:" +if c5 > 5 then i = 5 else i = c5 : fi +for i = i-1 to 0 step -1 + print " [", quins(i)-24, ", ", quins(i)-18, ", ", quins(i)-12, ", ", quins(i)-6, ", ", quins(i), "]" +next i + +print chr$(10), cu, " unsexy primes ending with:" +for i = 9 to 0 step -1 + print unsexy(i), ","; +next i +print chr$(8)," " +end diff --git a/Task/Show-ASCII-table/Langur/show-ascii-table.langur b/Task/Show-ASCII-table/Langur/show-ascii-table.langur index 54fbcf7601..3659e774e6 100644 --- a/Task/Show-ASCII-table/Langur/show-ascii-table.langur +++ b/Task/Show-ASCII-table/Langur/show-ascii-table.langur @@ -1,7 +1,7 @@ -for .i of 16 { - for .j = 31 + .i ; .j < 128 ; .j += 16 { - val .L = switch(.j; 32: "spc"; 127: "del"; cp2s .j) - write $"\{.j:3} : \{.L:-4}" +for i of 16 { + for j = 31 + i ; j < 128 ; j += 16 { + val L = switch(j; 32: "spc"; 127: "del"; cp2s(j)) + write "{{j:3}} : {{L:-4}}" } writeln() } diff --git a/Task/Show-ASCII-table/SETL/show-ascii-table.setl b/Task/Show-ASCII-table/SETL/show-ascii-table.setl new file mode 100644 index 0000000000..1e1a366e2b --- /dev/null +++ b/Task/Show-ASCII-table/SETL/show-ascii-table.setl @@ -0,0 +1,9 @@ +program ascii_table; + loop for i in [32..47] do + print(+/[lpad(str j, 3) + ' : ' + rpad(ascii j, 6) : j in [i, i+16..127]]); + end loop; + + op ascii(n); + return {[32, 'Spc'], [127, 'Del']}(n) ? (char n); + end op; +end program; diff --git a/Task/Show-the-epoch/EasyLang/show-the-epoch.easy b/Task/Show-the-epoch/EasyLang/show-the-epoch.easy new file mode 100644 index 0000000000..025029e439 --- /dev/null +++ b/Task/Show-the-epoch/EasyLang/show-the-epoch.easy @@ -0,0 +1,2 @@ +# local time zone +print timestr 0 diff --git a/Task/Sierpinski-pentagon/Jq/sierpinski-pentagon.jq b/Task/Sierpinski-pentagon/Jq/sierpinski-pentagon.jq new file mode 100644 index 0000000000..a832f26b1b --- /dev/null +++ b/Task/Sierpinski-pentagon/Jq/sierpinski-pentagon.jq @@ -0,0 +1,59 @@ +### Generic functions + +def addComplex(stream): reduce stream as [$x,$y] ([0,0]; .[0] += $x | .[1] += $y); + +def lpad($len; $x): tostring | ($len - length) as $l | ($x * $l) + .; + +# Input: an array +def multiply($x): map(. * $x); + +# Round to approx $ndec places +def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p; + +def power($a; $b): reduce range(0;$b) as $i (1; . * $a); + +def tau: 8 * atan2(1; 1); + +def tobase($b): + def digit: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[.:.+1]; + def mod: . % $b; + def div: ((. - mod) / $b); + def digits: recurse( select(. > 0) | div) | mod ; + # For jq it would be wise to protect against `infinite` as input, but using `isinfinite` confuses gojq + select( (tostring|test("^[0-9]+$")) and 2 <= $b and $b <= 36) + | if . == 0 then "0" + else [digits | digit] | reverse[1:] | add + end; + +### Sierpinski Pentagons + +def svgHead($width): + ""; + +def svgEnd: ""; + +# SVG height and width will be 2 * dim +def pentagon($dim): + def sides: 5; + def order: 5; + def scale: (3 - (order | sqrt)) / 2; + + def cis: [cos, sin]; + def orders: + [range(0; order) | ((1 - scale) * $dim) * power(scale ; .) ]; + def vertices: + tau as $tau | [range(0; sides) | ( . * $tau / sides | cis)]; + + svgHead(2*$dim), + (orders as $orders + | vertices as $vertices + | range(1; 1 + power(sides; order)) as $i + | [ ($i|tobase(sides) | lpad(order; "0") | split("")[]) | $vertices[tonumber]] as $varr + | addComplex(range(0; $orders|length) as $i | $varr[$i] | multiply($orders[$i])) as $vector + | ($vertices | map( addComplex($vector, multiply($orders[-1] * (1-scale))))) as $vprod + | ($vprod | map( map(round(3)) | "\(.[0]) \(.[1])") | join(" ")) as $points + | ""), + svgEnd ; + +pentagon(250) diff --git a/Task/Sierpinski-square-curve/Ada/sierpinski-square-curve.ada b/Task/Sierpinski-square-curve/Ada/sierpinski-square-curve.ada new file mode 100644 index 0000000000..518a2e97b0 --- /dev/null +++ b/Task/Sierpinski-square-curve/Ada/sierpinski-square-curve.ada @@ -0,0 +1,49 @@ +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +procedure Sierpinski_Square_Curve is + Axiom : constant String := "F+XF+F+XF"; + Rules : constant String := "XF-F+F-XF+F+XF-F+F-X"; + ORDER : constant Positive := 5; + LENGTH : constant Positive := 4; + X : Integer := (600 - LENGTH) / 2; + Y : Integer := LENGTH; + Angle : Integer := 0; + SVG_File : File_Type; + Production : Unbounded_String := To_Unbounded_String (Axiom); + function Rewrite (Str : String) return Unbounded_String is + Prod : Unbounded_String; + begin + for C of Str loop + if C = 'X' then + Prod := Prod & Rules; + else + Prod := Prod & C; + end if; + end loop; + return Prod; + end Rewrite; +begin + Create (SVG_File, Out_File, "sierpinski.svg"); + Put_Line (SVG_File, ""); + Put_Line (SVG_File, ""); + Put (SVG_File, " + X := X + LENGTH * Integer (Cos (Float (Angle), 360.0)); + Y := Y + LENGTH * Integer (Sin (Float (Angle), 360.0)); + Put (SVG_File, " L" & X'Image & "," & Y'Image); + when '+' => Angle := (Angle + 90) mod 360; + when '-' => Angle := (Angle - 90) mod 360; + when others => null; + end case; + end loop; + Put_Line (SVG_File, "'/>\n"); + Close (SVG_File); +end Sierpinski_Square_Curve; diff --git a/Task/Sierpinski-triangle/EasyLang/sierpinski-triangle.easy b/Task/Sierpinski-triangle/EasyLang/sierpinski-triangle.easy new file mode 100644 index 0000000000..51c9ff37bb --- /dev/null +++ b/Task/Sierpinski-triangle/EasyLang/sierpinski-triangle.easy @@ -0,0 +1,14 @@ +size = bitshift 1 4 - 1 +for y = size downto 0 + for i = 0 to y - 1 + write " " + . + for x = 0 to size - y + if bitand x y <> 0 + write " " + else + write "* " + . + . + write "\n" +. diff --git a/Task/Sieve-of-Eratosthenes/EasyLang/sieve-of-eratosthenes.easy b/Task/Sieve-of-Eratosthenes/EasyLang/sieve-of-eratosthenes.easy index 9ce7a9a5c4..ca63c7c0d5 100644 --- a/Task/Sieve-of-Eratosthenes/EasyLang/sieve-of-eratosthenes.easy +++ b/Task/Sieve-of-Eratosthenes/EasyLang/sieve-of-eratosthenes.easy @@ -1,14 +1,16 @@ -len is_divisible[] 100 -max = sqrt len is_divisible[] -for d = 2 to max - if is_divisible[d] = 0 - for i = d * d step d to len is_divisible[] - is_divisible[i] = 1 +len sieve[] 100 +max = sqrt len sieve[] +for i = 2 to max + if sieve[i] = 0 + j = i * i + while j <= len sieve[] + sieve[j] = 1 + j += i . . . -for i = 2 to len is_divisible[] - if is_divisible[i] = 0 +for i = 2 to len sieve[] + if sieve[i] = 0 print i . . diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-6.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-6.erl new file mode 100644 index 0000000000..1c9f4d57a9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-6.erl @@ -0,0 +1,20 @@ +-module(primesieve). +-export([primes/1]). + +mult(N, Limit) -> + case Limit > N * N of + true -> lists:seq(N * N, Limit, N); + false -> [] + end. + +primes(Limit) -> + case Limit > 1 of + true -> sieve(Limit, 3, [2] ++ lists:seq(3, Limit, 2), mult(3, Limit)); + false -> [] + end. + +sieve(Limit, D, S, M) -> + case Limit < D * D of + true -> S; + false -> sieve(Limit, D + 2, S -- M, mult(D + 2, Limit)) + end. diff --git a/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur b/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur index 62cfd57a77..ed2a4bd2b4 100644 --- a/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur +++ b/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur @@ -1,18 +1,18 @@ -val .sieve = fn(.limit) { - if .limit < 2: return [] +val sieve = fn(limit) { + if limit < 2: return [] - var .composite = .limit * [false] - .composite[1] = true + var composite = limit * [false] + composite[1] = true - for .n in 2 .. trunc(.limit ^/ 2) + 1 { - if not .composite[.n] { - for .k = .n^2 ; .k < .limit ; .k += .n { - .composite[.k] = true + for n in 2 .. trunc(limit ^/ 2) + 1 { + if not composite[n] { + for k = n^2 ; k < limit ; k += n { + composite[k] = true } } } - filter fn(.n) not .composite[.n], series .limit-1 + filter fn n:not composite[n], series(limit-1) } -writeln .sieve(100) +writeln sieve(100) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ocaml new file mode 100644 index 0000000000..e8250c81ac --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-7.ocaml @@ -0,0 +1,16 @@ +let sieve limit = + let p = Array.make (limit + 1) true in + let rec sieve_outer d = + if d * d > limit then p + else if p.(d) then + let rec sieve_inner m = + if m > limit then sieve_outer (d + 1) + else ((p.(m) <- false); sieve_inner (m + d)) + in sieve_inner (d * d) + else sieve_outer (d + 1) + in sieve_outer 2 + +let primes limit = + let s = (sieve limit) in + List.init (limit - 1) (fun i -> i + 2) + |> List.filter (fun x -> s.(x)) diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ocaml new file mode 100644 index 0000000000..4748dee4bb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-8.ocaml @@ -0,0 +1,3 @@ +# primes 200;; +- : int list = +[2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47; 53; 59; 61; 67; 71; 73; 79; 83; 89; 97; 101; 103; 107; 109; 113; 127; 131; 137; 139; 149; 151; 157; 163; 167; 173; 179; 181; 191; 193; 197; 199] diff --git a/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas b/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas new file mode 100644 index 0000000000..07aafc9fdb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas @@ -0,0 +1,17 @@ +function Eratosthenes(N: integer): List; +type primetype = (nonprime,prime); +begin + var sieve := |nonprime|*2 + |prime|*(N-1); + for var i:=2 to N.Sqrt.Round do + if sieve[i] = prime then + for var j := i*i to N step i do + sieve[j] := nonprime; + Result := new List; + for var i:=2 to N do + if sieve[i] = prime then + Result.Add(i); +end; + +begin + Eratosthenes(1000).Println +end. diff --git a/Task/Simple-database/11l/simple-database.11l b/Task/Simple-database/11l/simple-database.11l index a6cda0259c..a0e3d6734a 100644 --- a/Task/Simple-database/11l/simple-database.11l +++ b/Task/Simple-database/11l/simple-database.11l @@ -1,11 +1,4 @@ -T Item - String name, date, category - - F (name, date, category) - .name = name - .date = date - .category = category - +T Item((String name, String date, String category)) F String() R .name‘, ’(.date)‘, ’(.category) diff --git a/Task/Simple-database/C++/simple-database.cpp b/Task/Simple-database/C++/simple-database.cpp new file mode 100644 index 0000000000..cf265ce88b --- /dev/null +++ b/Task/Simple-database/C++/simple-database.cpp @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include +#include + +const std::string filename = "Contacts.dat"; + +class Contact { +public: + Contact(const std::string& aName, const std::string& aBirth_Date, const std::string& aState, + const std::string& aRelation, const std::string& aEmail) + : name(aName), birth_date(aBirth_Date), state(aState), relation(aRelation), email(aEmail) { } + + std::string get_relation() const { + return relation; + } + + std::string to_string() const { + return name + ", " + birth_date + ", " + state + ", " + relation + ", " + email; + } + + bool operator<(const Contact& other) const { + return birth_date > other.birth_date; + } + +private: + std::string name, birth_date, state, relation, email; +}; + +std::vector contacts = { }; + +Contact parse(std::string entry) { + std::vector parts; + uint64_t position = 0; + while ( ( position = entry.find(", ") ) != std::string::npos ) { + parts.emplace_back(entry.substr(0, position)); + entry.erase(0, position + 2); + } + return Contact(parts[0], parts[1], parts[2], parts[3], entry); +} + +void write_file(const std::string& new_entry) { + std::fstream database(filename, std::ios::out | std::ios::app); + if ( database.is_open() ) { + database << new_entry; + database.close(); + } else { + std::cerr << "Unable to open database '" << filename << "' for writing" << std::endl; + } +} + +// Open the file if it exists, otherwise create a new empty file. +void read_file() { + std::fstream database(filename, std::ios::in | std::ios::app); + if ( database.is_open() ) { + std::string entry; + while ( std::getline(database, entry) ) { + contacts.emplace_back(parse(entry)); + } + database.close(); + } else { + std::cerr << "Unable to open database '" << filename << "' for reading" << std::endl; + } +} + +void add_new_entry() { + std::cout << "Type the new entry, without inverted commas, in the format:" << std::endl; + std::cout << "Name, Birth_Date, State, Relation, Email" << std::endl; + std::string new_entry; + std::cin.ignore(std::numeric_limits::max(), '\n'); // Clear the keyboard buffer + std::getline(std::cin, new_entry); + Contact contact(parse(new_entry)); + contacts.emplace_back(contact); + write_file(new_entry); + std::cout << "The contact \"" << new_entry << "\" has been added to the database" << std::endl; +} + +void show_latest_entry() { + if ( ! contacts.empty() ) { + std::cout << "The latest entry is: " + contacts.back().to_string() << std::endl; + } else { + std::cout << "There are currently no entries in the database" << std::endl; + } +} + +void show_latest_special_entry(const std::string& search) { + int32_t index = contacts.size() - 1; + while ( index >= 0 && contacts[index].get_relation() != search ) { + index--; + } + + if ( index >= 0 ) { + std::cout << "The latest " << search << " entry is " + contacts[index].to_string() << std::endl; + } else { + std::cout << "There are currently no " << search << " entries" << std::endl; + } +} + +void show_latest_friend_entry() { + show_latest_special_entry("Friend"); +} + +void show_latest_family_entry() { + show_latest_special_entry("Family"); +} + +void list_all_entries_by_age() { + if ( ! contacts.empty() ) { + std::vector copy_contacts = contacts; + std::sort(copy_contacts.begin(), copy_contacts.end()); + for ( const Contact& contact : copy_contacts ) { + std::cout << contact.to_string() << std::endl; + } + } else { + std::cout << "There are currently no entries in the database" << std::endl; + } +} + +int main() { + read_file(); + uint32_t choice = 0; + while ( choice != 6 ) { + std::cout << std::endl; + std::cout << " Menu " << std::endl; + std::cout << " 1: Add a new entry" << std::endl; + std::cout << " 2: Show latest entry" << std::endl; + std::cout << " 3: Show latest Friend entry" << std::endl; + std::cout << " 4: Show latest Family entry" << std::endl; + std::cout << " 5: List all entries by age" << std::endl; + std::cout << " 6: Close the program" << std::endl; + std::cout << std::endl; + + std::cin >> choice; + switch ( choice ) { + case 1 : add_new_entry(); break; + case 2 : show_latest_entry(); break; + case 3 : show_latest_friend_entry(); break; + case 4 : show_latest_family_entry(); break; + case 5 : list_all_entries_by_age(); break; + case 6 : std::cout << "Program closed" << std::endl; break; + default : std::cout << "Please enter a number in the range 1..6" << std::endl; break; + } + } +} diff --git a/Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas b/Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas new file mode 100644 index 0000000000..7767cd8186 --- /dev/null +++ b/Task/Simple-windowed-application/PascalABC.NET/simple-windowed-application.pas @@ -0,0 +1,13 @@ +uses WPF; + +begin + var mainpanel := Panels.StackPanel(200).AsMainContent; + var b := CreateButton('Click me!'); + var lb := CreateLabel('0'); + mainpanel.AddElements(b,lb); + var clicks := 0; + b.Click += (o,e) -> begin + clicks += 1; + lb.Content := clicks; + end; +end. diff --git a/Task/Singleton/Ecstasy/singleton.ecstasy b/Task/Singleton/Ecstasy/singleton.ecstasy new file mode 100644 index 0000000000..4ed6c14010 --- /dev/null +++ b/Task/Singleton/Ecstasy/singleton.ecstasy @@ -0,0 +1,15 @@ +module test { + static service Singleton { + private Int counter; + String fooHasBeenCalled() { + return $"{++counter} times"; + } + } + + void run() { + @Inject Console console; + for (Int i : 1..5) { + console.print($"{Singleton.fooHasBeenCalled()=}"); + } + } +} diff --git a/Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas b/Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas new file mode 100644 index 0000000000..050b35e550 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/PascalABC.NET/singly-linked-list-element-definition.pas @@ -0,0 +1,4 @@ +type Node = auto class + data: T; + next: Node; +end; diff --git a/Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas b/Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas new file mode 100644 index 0000000000..864ad7ddb1 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/PascalABC.NET/singly-linked-list-element-insertion.pas @@ -0,0 +1,33 @@ +type Node = auto class + data: T; + next: Node; +end; + +type + SinglyLinkedList = class + first: Node; + procedure AddFirst(x: T); + begin + first := new Node(x,first); + end; + procedure AddAfter(p: Node; x: T); + begin + p.next := new Node(x,p.next); + end; + procedure PrintList(); + begin + var p := first; + while p<>nil do + begin + Print(p.data); + p := p.next; + end; + end; + end; + +begin + var lst := new SinglyLinkedList; + lst.AddFirst(2); lst.AddFirst(3); + lst.AddAfter(lst.first,555); + lst.PrintList; +end. diff --git a/Task/Sleep/PascalABC.NET/sleep.pas b/Task/Sleep/PascalABC.NET/sleep.pas new file mode 100644 index 0000000000..0fbf64a23c --- /dev/null +++ b/Task/Sleep/PascalABC.NET/sleep.pas @@ -0,0 +1,6 @@ +begin + var ms := ReadInteger; + Print('Sleeping...'); + Sleep(ms); + Print('Awake!'); +end. diff --git a/Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg b/Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg new file mode 100644 index 0000000000..634d6a6fe6 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/ALGOL-68/sleeping-beauty-problem.alg @@ -0,0 +1,19 @@ +BEGIN # sleeping beauty problem - translated from the Wren sample # + PROC sleeping beauty = ( INT reps )REAL: + BEGIN + INT wakings := 0, heads := 0; + FOR i TO reps DO + wakings +:= 1; + IF next random < 0.5 THEN # [0..0.5) = heads, [0.5..1.0) = tails say # + heads +:= 1 + ELSE + wakings +:= 1 + FI + OD; + print( ( "Wakings over ", whole( reps, 0 ), " repetitions = ", whole( wakings, 0 ), newline ) ); + ( heads / wakings ) * 100 + END; # sleeping beauty # + + REAL pc = sleeping beauty( 1 000 000 ); + print( ( "Percentage probability of heads on waking = ", fixed( pc, -10, 6 ), "%", newline ) ) +END diff --git a/Task/Sleeping-Beauty-problem/Fortran/sleeping-beauty-problem.f b/Task/Sleeping-Beauty-problem/Fortran/sleeping-beauty-problem.f new file mode 100644 index 0000000000..f2eccd3d70 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Fortran/sleeping-beauty-problem.f @@ -0,0 +1,43 @@ +program sleepingbeauty + implicit none + + integer :: total_reps + integer :: result_wakings + real :: result_percent + + total_reps = 1e6 + + call sleepingOp(total_reps, result_wakings, result_percent) + + print *, "wakings over", total_reps, "reps: ", result_wakings + print *, "percentage probability of heads on wake:", result_percent + +contains + +subroutine sleepingOp(reps, wakings, percent) + integer, intent(in) :: reps + integer, intent(out) :: wakings + real, intent(out) :: percent + + integer :: heads + integer :: i + real :: coin + + wakings = 0 + heads = 0 + + do i = 0, reps, 1 + call random_number(coin) + wakings = wakings + 1 + if (coin > 0.5) then + heads = heads + 1 + else + wakings = wakings + 1 + end if + end do + + percent = real(heads) / real(wakings) + +end subroutine sleepingOp + +end program sleepingbeauty diff --git a/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic b/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic index bcffedb249..047d660c75 100644 --- a/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic +++ b/Task/Sleeping-Beauty-problem/FutureBasic/sleeping-beauty-problem.basic @@ -1,17 +1,17 @@ _iterations = 1000000 local fn SleepingBeauty -NSUInteger i -CGFloat heads = 0, sleep = 0 + NSUInteger i + CGFloat heads = 0, sleep = 0 -for i = 1 to _iterations -NSInteger coinToss = int( rnd(2) ) -sleep++ -if coinToss = 1 then heads++ else sleep++ -next + for i = 1 to _iterations + NSInteger coinToss = int( rnd(2) ) + sleep++ + if coinToss = 1 then heads++ else sleep++ + next -printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep -printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100 + printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep + printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100 end fn randomize diff --git a/Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq b/Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq new file mode 100644 index 0000000000..f882b5fe3a --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Jq/sleeping-beauty-problem.jq @@ -0,0 +1,25 @@ +# Output: a PRN in range(0; .) +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p; + +# Output: {n, heads, wakings} +def sleepingBeauty: + { n: ., wakings: 0, heads: 0 } + | reduce range(0; .n) as $i (.; + (2|prn) as $coin # heads = 0, tails = 1 say + | .wakings += 1 + | if $coin == 0 then .heads += 1 + else .wakings += 1 + end ); + +1000000 +| sleepingBeauty +| "Wakings over \(.n) repetitions = \(.wakings).", + "Percentage probability of heads on waking = \(100*.heads/.wakings | round(3))%" diff --git a/Task/Smarandache-Wellin-primes/Sidef/smarandache-wellin-primes.sidef b/Task/Smarandache-Wellin-primes/Sidef/smarandache-wellin-primes.sidef new file mode 100644 index 0000000000..966e01c16a --- /dev/null +++ b/Task/Smarandache-Wellin-primes/Sidef/smarandache-wellin-primes.sidef @@ -0,0 +1,32 @@ +say "Smarandache-Wellen primes:" + +for (var (p=2, i=1, n='', nth=1); nth <= 8; (p.next_prime!, ++i)) { + n += Str(p) + if (Num(n).is_prime){ + var t = n + if (t.len > 50) { + t = (t.first(20) + ' ... ' + t.last(20) + " (#{t.len} digits)") + } + printf("%s: Index:%5d Last prime:%6d S-W: %s\n", nth, i, p, t) + ++nth + } +} + +say "\nSmarandache-Wellen derived primes:" + +func derived(String n) -> String { + var freq = n.chars.freq + 0..9 -> map { freq{_} \\ 0 }.join +} + +for (var (p=2, i=1, nth=1, n=''); nth <= 20; (p.next_prime!, ++i)) { + n += Str(p) + var t = derived(n) + if (Num(t).is_prime){ + if (t.len > 50) { + t = (t.first(20) + ' ... ' + t.last(20) + " (#{t.len} digits)") + } + printf("%2s: Index:%5d %s\n", nth, i, t) + ++nth + } +} diff --git a/Task/Smith-numbers/EasyLang/smith-numbers.easy b/Task/Smith-numbers/EasyLang/smith-numbers.easy index fd160e7f16..b50430147f 100644 --- a/Task/Smith-numbers/EasyLang/smith-numbers.easy +++ b/Task/Smith-numbers/EasyLang/smith-numbers.easy @@ -1,15 +1,15 @@ -proc prim_fact x . pf[] . - pf[] = [ ] +func[] primfact x . p = 2 repeat if x mod p = 0 - pf[] &= p + r[] &= p x = x div p else p += 1 . until x = 1 . + return r[] . func digsum x . while x > 0 @@ -19,7 +19,7 @@ func digsum x . return sum . for i = 2 to 9999 - prim_fact i pf[] + pf[] = primfact i if len pf[] >= 2 sum = 0 for e in pf[] diff --git a/Task/Smith-numbers/Uiua/smith-numbers-1.uiua b/Task/Smith-numbers/Uiua/smith-numbers-1.uiua new file mode 100644 index 0000000000..1dc00589f4 --- /dev/null +++ b/Task/Smith-numbers/Uiua/smith-numbers-1.uiua @@ -0,0 +1,7 @@ +N ← 10000 +Primes ← ⇌◌⍢(⊃(▽≠0◿⊢..|⊂⊢)|>0⧻)⊙[]↘2⇡N +Candidates ← ▽¬∊:Primes.↘2⇡ # Exclude primes +SumD ← /+≡⋕°⋕ +PrimeDivisors ← ◌◌⍢(⟜(÷/×)⟜(⊙⊂:)▽:⟜(=0◿)⊙.|⋅(>1))Primes ⊙[] +Smith ← ▽⊸≡(=⊃(SumD|/+≡SumD PrimeDivisors)) +⟜⧻ Smith Candidates N diff --git a/Task/Smith-numbers/Uiua/smith-numbers-2.uiua b/Task/Smith-numbers/Uiua/smith-numbers-2.uiua new file mode 100644 index 0000000000..21cc459008 --- /dev/null +++ b/Task/Smith-numbers/Uiua/smith-numbers-2.uiua @@ -0,0 +1,3 @@ +IsSmith ← =∩(/+≡⋕)⊃°⋕(/◇⊂°⋕°/×) +▽⊸≡IsSmith▽⊸≡(≠1⧻°/×)+1⇡10000 +&p$"Number under 10000: _\nFirst ten: _\nLast ten: _"⊃(⧻|↙10|↙¯10) diff --git a/Task/Snake/Emacs-Lisp/snake.l b/Task/Snake/Emacs-Lisp/snake.l new file mode 100644 index 0000000000..127dbc0b2c --- /dev/null +++ b/Task/Snake/Emacs-Lisp/snake.l @@ -0,0 +1 @@ +M-x snake diff --git a/Task/Snake/Locomotive-Basic/snake.basic b/Task/Snake/Locomotive-Basic/snake.basic index d27ab9f0f4..0b887d5a71 100644 --- a/Task/Snake/Locomotive-Basic/snake.basic +++ b/Task/Snake/Locomotive-Basic/snake.basic @@ -1,30 +1,31 @@ 10 mode 1:randomize time -20 sx=20:sy=5:dx=1:dy=0:ml=20:dim ox(ml),oy(ml):oi=1:ll=4:skill=6 +15 ink 0,0:ink 1,6:ink 2,18:ink 3,11 +20 sx=20:sy=5:dx=1:dy=0:ml=20:dim ox(ml),oy(ml):oi=1:ll=4:skill=8 30 f$=chr$(228):w$=chr$(127):b$=chr$(231) -40 print string$(40,w$); +40 pen 3:print string$(40,w$); 50 for i=2 to 20:print w$;space$(38);w$;:next 60 print string$(40,w$); -70 locate 10, 12:print string$(20,w$); +70 locate 11, 11:print string$(20,w$); 80 gosub 260 -90 frame -100 if inkey(1)>-1 then dx=1:dy=0 -110 if inkey(8)>-1 then dx=-1:dy=0 -120 if inkey(0)>-1 then dx=0:dy=-1 -130 if inkey(2)>-1 then dx=0:dy=1 -140 locate sx,sy:print chr$(224);:ox(oi)=sx:oy(oi)=sy +140 locate sx,sy:pen 2:print chr$(224);:ox(oi)=sx:oy(oi)=sy 150 oi=oi+1:if oi>ml then oi=1 160 nx=sx+dx:ny=sy+dy 170 locate nx,ny:a$=copychr$(#0) 180 if a$=w$ or a$=b$ then sound 2,62500/20,100:locate 13,6:print "You have died!":end -190 if a$=f$ then sound 2,62500/500,10: sound 1,62500/1000,10: sound 4,62500/2000,10:p=p+100:print " ";:gosub 260:if ll-1 then dx=1:dy=0 +212 if inkey(8)>-1 then dx=-1:dy=0 +213 if inkey(0)>-1 then dx=0:dy=-1 +214 if inkey(2)>-1 then dx=0:dy=1 +215 next +220 locate sx,sy:pen 2:print b$; 230 nn=1+((oi+ml-ll) mod ml) 240 if ox(nn)>0 then locate ox(nn),oy(nn):print " "; -250 sx=nx:sy=ny:goto 90 +250 sx=nx:sy=ny:goto 140 260 fx=rnd*39+1:fy=rnd*19+1 270 locate fx,fy:a$=copychr$(#0) 280 if a$<>" " then 260 -290 print f$; +290 pen 1:print f$; 300 return diff --git a/Task/Solve-a-Hidato-puzzle/00-TASK.txt b/Task/Solve-a-Hidato-puzzle/00-TASK.txt index a23202b09c..6705fafb29 100644 --- a/Task/Solve-a-Hidato-puzzle/00-TASK.txt +++ b/Task/Solve-a-Hidato-puzzle/00-TASK.txt @@ -24,7 +24,7 @@ has the following solution, with path marked on it: * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Holy Knight's tour]] -* [[Solve a Knight's tour]] +* [[Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]; diff --git a/Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq b/Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq new file mode 100644 index 0000000000..7b80214b8d --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Jq/solve-a-hidato-puzzle.jq @@ -0,0 +1,74 @@ +### Generic functions + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +### Hidato Puzzle + +# "." ~ -1 (dead cell) +# "_" ~ 0 (to be assigned a number) +def printBoard: + .board[] as $row + | reduce $row[] as $c (""; + if $c == -1 then . + " . " + elif $c > 0 then . + ($c | lpad(3)) + else . + " __" + end); + +# output: { board, given, start} +# "." signifies a dead cell +def setUp($in): + { board:[], given:[], start:[] } + | ($in|length) as $nRows + | [range(0;$nRows) | ($in[.]|split(" "))] as $puzzle + | ($puzzle[0]|length) as $nCols + | .board = [range(0; $nRows+2) | null] + | reduce range(0; .board|length) as $i (. ; .board[$i] = [range(0; $nCols+2) | -1]) + | reduce range(0; $nRows) as $r (.; + $puzzle[$r] as $row + | reduce range(0; $nCols) as $c (.; + $row[$c] as $cell + | if $cell == "_" + then .board[$r + 1][$c + 1] = 0 + elif $cell != "." + then ($cell | tonumber) as $value + | .board[$r + 1][$c + 1] = $value + | .given += [$value] + | if $value == 1 then .start = [$r + 1, $c + 1] end + end )) + | .given |= sort ; + +# Generate all solutions, that is, emit empty on failure. +# $r is a row, $c is a column, $n is the number we're looking for, +# $next is the index in .given of the next given number. +def solve($r; $c; $n; $next): + if $n > .given[-1] then . # all done + else .board[$r][$c] as $back + | if ($back != 0 and $back != $n) then empty + elif $back == 0 and .given[$next] == $n then empty + else + (if $back == $n then (1+$next) else $next end) as $next2 + | if $n != $back then .board[$r][$c] = $n end # avoid unnecessary copying + | ( (-1, 0, 1) as $i + | (-1, 0, 1) as $j + | solve($r + $i; $c + $j; $n + 1; $next2) + ) + end + end; + + +def example: [ + "_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _" +]; + +setUp(example) +| printBoard, + "\nFound:", + ( first( solve(.start[0]; .start[1]; 1; 0) ) + | printBoard) diff --git a/Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua b/Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua new file mode 100644 index 0000000000..dd8f3d793a --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Uiua/solve-a-hidato-puzzle.uiua @@ -0,0 +1,22 @@ +# Experimental! +G ← [[0 33 35 0 0 ¯1 ¯1 ¯1] + [0 0 24 22 0 ¯1 ¯1 ¯1] + [0 0 0 21 0 0 ¯1 ¯1] + [0 26 0 13 40 11 ¯1 ¯1] + [27 0 0 0 9 0 1 ¯1] + [¯1 ¯1 0 0 18 0 0 ¯1] + [¯1 ¯1 ¯1 ¯1 0 7 0 0] + [¯1 ¯1 ¯1 ¯1 ¯1 ¯1 5 0]] +S ← /×△G # Total size. +N ← /+≠¯1♭G +Width ← ⧻⊢G +Dirs ← [¯.1 ⊓∩(+1)∩(-1),,,,¯.Width] # D8 directions. +DiaD ← /↥⌵-∩(⊟⊃(◿|⌊÷)Width) # Diagonal dist. +Ns ← ▽:⟜≡(=0⊡)⊙¤▽⊸≡(↧⊃(≥0| $cnt then . + else first( + range(0;moves|length) as $i + | ($sx + moves[$i][0]) as $x + | ($sy + moves[$i][1]) as $y + | if $x >= 0 and $x < $sz and $y >= 0 and $y < $sz and .pz[$x][$y] == 0 + then .pz[$x][$y] = $idx + | solve($sz; $x; $y; $idx + 1; $cnt) + else empty + end ) + end; + +def printSolution($sz): + range(0; $sz) as $j + | .emit = "" + | reduce range(0; $sz) as $i (.; + if .pz[$i][$j] != -1 + then .emit += (.pz[$i][$j] | lpad(3)) + else .emit += " --" + end ) + | .emit; + +# $b should be a board of size $sz +def findSolution($b; $sz): + [range(0; $sz) | -1] as $minus + | { pz: [range(0;$sz) | $minus], + x: 0, + y: 0, + idx: 0, + cnt: 0 + } + | reduce range(0; $sz) as $j (.; + reduce range(0; $sz) as $i (.; + if $b[.idx: .idx+1] == "x" + then .pz[$i][$j] = 0 + | .cnt += 1 + elif $b[.idx: .idx+1] == "s" + then + .pz[$i][$j] = 1 + | .cnt += 1 + | .x = $i + | .y = $j + end + | .idx += 1 )) + | (solve($sz; .x; .y; 2; .cnt) | printSolution($sz)) + // "Whoops!" ; + +findSolution(board1; 8), +"", +findSolution(board2; 13) diff --git a/Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart b/Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart new file mode 100644 index 0000000000..0178290da7 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Dart/solve-a-numbrix-puzzle.dart @@ -0,0 +1,92 @@ +/// Based on https://rosettacode.org/wiki/Solve_a_Numbrix_puzzle#Kotlin +import 'package:more/more.dart'; +import 'package:sprintf/sprintf.dart'; + +const examples = [ + [ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00" + ], + [ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00" + ] +]; + +const moves = [ + [1, 0], + [0, 1], + [-1, 0], + [0, -1] +]; + +late List board; +late List> grid; +late List clues; +var totalToFill = 0; + +bool solve(int r, int c, int count, int nextClue) { + if (count > totalToFill) return true; + var back = grid[r][c]; + if (back != 0 && back != count) return false; + if (back == 0 && nextClue < clues.length && clues[nextClue] == count) { + return false; + } + + var nextClue2 = nextClue; + if (back == count) nextClue2++; + grid[r][c] = count; + var res = moves.any((m) => solve(r + m[1], c + m[0], count + 1, nextClue2)); + if (!res) grid[r][c] = back; + return res; +} + +void printResult(int n) { + print("Solution for example $n:"); + for (var row in grid) { + print([ + for (var e in row) + if (e != -1) sprintf("%2d ", [e]) + ].join()); + } +} + +main() { + for (var each in examples.indexed()) { + board = each.value; + var nRows = board.length + 2, nCols = board[0].split(",").length + 2; + var startRow = 0, startCol = 0; + grid = List.generate(nRows, (i) => List.filled(nCols, -1)); + totalToFill = (nRows - 2) * (nCols - 2); + var lst = []; + for (var r in 1.to(nRows - 1)) { + var row = board[r - 1].split(","); + for (var c in 1.to(nCols - 1)) { + var value = int.parse(row[c - 1]); + if (value > 0) lst.add(value); + if (value == 1) { + startRow = r; + startCol = c; + } + grid[r][c] = value; + } + } + + clues = (lst..sort()).toList(); + if (solve(startRow, startCol, 1, 0)) printResult(each.index + 1); + } +} diff --git a/Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq b/Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq new file mode 100644 index 0000000000..122070750a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Jq/solve-a-numbrix-puzzle.jq @@ -0,0 +1,80 @@ +def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .; + +def moves: [ [1, 0], [0, 1], [-1, 0], [0, -1] ]; + +# "All solutions" +# Can the puzzle be solved by placing the token $count at row $r, column $c? +# Input: { grid, clues, totalToFill } +def solve($r; $c; $count; $nextClue): + if $count > .totalToFill then . + else .grid[$r][$c] as $back + | if ($back != 0 and $back != $count) + or ($back == 0 and $nextClue < (.clues|length) and .clues[$nextClue] == $count) + then empty + else if $back == $count then .nextClue += 1 end + | .grid[$r][$c] = $count + | moves[] as $m + | solve($r + $m[1]; $c + $m[0]; $count + 1; $nextClue) + end + end ; + +def printResult: + .grid[1:-1][] as $row + | reduce range(1; $row|length -1) as $i (""; + . + (if $i != -1 then $row[$i] else "" end | lpad(3)) ); + +def task($board): + { clues: [] } + | (($board|length) + 2) as $nRows + | ($board[0]|split(",")|length + 2) as $nCols + | .startRow = 0 + | .startCol = 0 + | [range(0; $nCols) | -1] as $m1 + | .grid = [range(0; $nRows) | $m1] + | .totalToFill = ($nRows - 2) * ($nCols - 2) + | reduce range(0; $nRows) as $r (.; + if $r >= 1 and $r < $nRows - 1 + then ($board[$r - 1]|split(",")) as $row + | reduce range(1; $nCols - 1) as $c (.; + ($row[$c - 1] | sub("^0";"") | tonumber) as $value + | if $value > 0 then .clues += [$value] end + | if $value == 1 + then .startRow = $r + | .startCol = $c + end + | .grid[$r][$c] = $value ) + end ) + | .clues |= sort + | .startRow as $startRow + | .startCol as $startCol + | first(solve($startRow; $startCol; 1; 0)) + | printResult ; + +### Examples + +def example1: [ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00" +]; + +def example2: [ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00" +]; + + "Example 1", task(example1), +"\nExample 2", task(example2) diff --git a/Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua b/Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua new file mode 100644 index 0000000000..d637e85420 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Uiua/solve-a-numbrix-puzzle.uiua @@ -0,0 +1,22 @@ +# Experimental! +G ← [[0 0 0 0 0 0 0 0 0] + [0 11 12 15 18 21 62 61 0] + [0 6 0 0 0 0 0 60 0] + [0 33 0 0 0 0 0 57 0] + [0 32 0 0 0 0 0 56 0] + [0 37 0 1 0 0 0 73 0] + [0 38 0 0 0 0 0 72 0] + [0 43 44 47 48 51 76 77 0] + [0 0 0 0 0 0 0 0 0]] +S ← /×△G # Total size. +Width ← ⧻⊢G +Dirs ← [∩(¯.)1Width] # D4 directions. +ManD ← /+⌵-∩(⊟⊃(◿|⌊÷)Width) # Manhattan dist. +Ns ← ▽:⟜≡(=0⊡)⊙¤▽⊸≡(↧⊃(≥0| 0 Then + If Len(s) = 1 Then Return part + Chr(48 + v) + res = solve(Left(s, i - 1) & Mid(s, i + 1), idx + 1, part & Chr(48 + v)) + If Len(res) > 0 Then Return res + End If + Next i + + Return "" +End Function + +Dim As String result = solve("12345678", 1, "") +For i As Integer = 1 To Len(result) + ReplaceString(txt, Chr(64 + i), Mid(result, i, 1)) +Next i +Print txt + +Sleep diff --git a/Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery b/Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery new file mode 100644 index 0000000000..cd0f5ad995 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Quackery/solve-the-no-connection-puzzle.quackery @@ -0,0 +1,24 @@ + [ ' [ [ 0 2 ] [ 0 3 ] [ 0 4 ] + [ 1 3 ] [ 1 4 ] [ 1 5 ] + [ 6 2 ] [ 6 3 ] [ 6 4 ] + [ 7 3 ] [ 7 4 ] [ 7 5 ] + [ 2 3 ] [ 3 4 ] [ 4 5 ] ] ] is connections ( --> [ ) + + [ dip dup do + unrot peek dip peek - abs 1 = ] is invalid ( [ [ --> b ) + + [ true swap + connections witheach + [ dip dup invalid if + [ dip not conclude ] ] + drop ] is allvalid ( [ --> b ) + + say " A B C D E F G H" cr + 8 ! times + [ i^ 8 rank->perm + allvalid if + [ sp + i^ 8 rank->perm + witheach + [ sp 1+ echo ] + cr conclude ] ] diff --git a/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig new file mode 100644 index 0000000000..dec1f5acc4 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-1.zig @@ -0,0 +1,53 @@ +const std = @import("std"); +const print = std.debug.print; + +const PA = 0; +const PB = 1; +const PC = 2; +const PD = 3; +const PE = 4; +const PF = 5; +const PG = 6; +const PH = 7; + +const Pair = struct { u8, u8 }; +const Pairs = [_]Pair{ .{ PA, PC }, .{ PA, PD }, .{ PA, PE }, .{ PB, PD }, .{ PB, PE }, .{ PB, PF }, .{ PC, PG }, .{ PC, PD }, .{ PD, PE }, .{ PD, PG }, .{ PD, PH }, .{ PE, PG }, .{ PE, PH }, .{ PF, PH }, .{ PE, PF } }; +var t: [8]u32 = .{0} ** 8; + +inline fn abs(p: Pair) u32 { + if (t[p.@"0"] < t[p.@"1"]) return t[p.@"1"] - t[p.@"0"]; + return t[p.@"0"] - t[p.@"1"]; +} + +fn check() bool { + var r: bool = true; + for (Pairs) |p| { + r = r and abs(p) > 1; + if (!r) break; + } + + return r; +} + +fn has(a: u32) bool { + for (t) |v| { + if (v == a) return true; + } + return false; +} + +fn solve(lvl: u32) bool { + if (lvl == 8) return check(); + for (1..9) |v| { + if (has(v)) continue; + t[lvl] = v; + if (solve(lvl + 1)) return true; + } + t[lvl] = 0; + return false; +} + +pub fn main() void { + _ = solve(0); + print("{{ A, B, C, D, E, F, G, H }} = {any}", .{t}); +} diff --git a/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig new file mode 100644 index 0000000000..57eea837ff --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Zig/solve-the-no-connection-puzzle-2.zig @@ -0,0 +1,54 @@ +const std = @import("std"); +const print = std.debug.print; + +const PA = 0; +const PB = 1; +const PC = 2; +const PD = 3; +const PE = 4; +const PF = 5; +const PG = 6; +const PH = 7; + +const Pair = struct { u8, u8 }; +const Pairs = [_]Pair{ .{ PA, PC }, .{ PA, PD }, .{ PA, PE }, .{ PB, PD }, .{ PB, PE }, .{ PB, PF }, .{ PC, PG }, .{ PC, PD }, .{ PD, PE }, .{ PD, PG }, .{ PD, PH }, .{ PE, PG }, .{ PE, PH }, .{ PF, PH }, .{ PE, PF } }; +var t: [8]u32 = .{0} ** 8; + +inline fn abs(p: Pair) u32 { + if (t[p.@"0"] < t[p.@"1"]) return t[p.@"1"] - t[p.@"0"]; + return t[p.@"0"] - t[p.@"1"]; +} + +fn check() bool { + var r: bool = true; + for (Pairs) |p| { + r = r and abs(p) > 1; + if (!r) break; + } + + return r; +} + +fn has(a: u32) bool { + for (t) |v| { + if (v == a) return true; + } + return false; +} + +fn solve(lvl: u32) bool { + if (lvl == 8) return check(); + for (1..9) |v| { + if (has(v)) continue; + t[lvl] = v; + if (solve(lvl + 1)) { + print("{{ A, B, C, D, E, F, G, H }} = {any}\n", .{t}); + } + } + t[lvl] = 0; + return false; +} + +pub fn main() void { + _ = solve(0); +} diff --git a/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy b/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy new file mode 100644 index 0000000000..73666aae50 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy @@ -0,0 +1,28 @@ +proc sort . d$[] . + for s$ in d$[] + d[][] &= number strsplit s$ "." + . + n = len d[][] + for i = 1 to n - 1 + for j = i + 1 to n + m = lower len d[i][] len d[j][] + for k to m + if d[i][k] <> d[j][k] + break 1 + . + . + if k > m and len d[i][] > len d[j][] or d[i][k] > d[j][k] + swap d[i][] d[j][] + . + . + . + for i to len d[][] + d$[i] = d[i][1] + for j = 2 to len d[i][] + d$[i] &= "." & d[i][j] + . + . +. +oid$[] = [ "1.3.6.1.4.1.11.2.17.19.3.4.0.10" "1.3.6.1.4.1.11.2.17.5.2.0.79" "1.3.6.1.4.1.11.2.17.19.3.4.0.4" "1.3.6.1.4.1.11150.3.4.0.1" "1.3.6.1.4.1.11.2.17.19.3.4.0.1" "1.3.6.1.4.1.11150.3.4.0" ] +sort oid$[] +print oid$[] diff --git a/Task/Sort-an-array-of-composite-structures/PascalABC.NET/sort-an-array-of-composite-structures.pas b/Task/Sort-an-array-of-composite-structures/PascalABC.NET/sort-an-array-of-composite-structures.pas new file mode 100644 index 0000000000..47855620a1 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PascalABC.NET/sort-an-array-of-composite-structures.pas @@ -0,0 +1,10 @@ +type + Pair = auto class + Name,Value: string; + end; + +begin + var a: array of Pair := (new Pair('ZZZ','333'),new Pair('XXX','222'),new Pair('YYY','111')); + a.OrderBy(p -> p.Name).Println; + a.OrderBy(p -> p.Value).Println; +end. diff --git a/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy b/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy new file mode 100644 index 0000000000..5e57891875 --- /dev/null +++ b/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy @@ -0,0 +1,12 @@ +proc sort . d[] . + for i = 1 to len d[] - 1 + for j = i + 1 to len d[] + if d[j] < d[i] + swap d[j] d[i] + . + . + . +. +a[] = [ 2 4 3 1 2 ] +sort a[] +print a[] diff --git a/Task/Sort-an-integer-array/PascalABC.NET/sort-an-integer-array.pas b/Task/Sort-an-integer-array/PascalABC.NET/sort-an-integer-array.pas new file mode 100644 index 0000000000..748474f4dd --- /dev/null +++ b/Task/Sort-an-integer-array/PascalABC.NET/sort-an-integer-array.pas @@ -0,0 +1,4 @@ +## +var a := Arr(5,1,4,2,3); +Sort(a); +Print(a); diff --git a/Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp b/Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp new file mode 100644 index 0000000000..d58c07152c --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/C++/sort-an-outline-at-every-level.cpp @@ -0,0 +1,258 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +const char DELETE = '\x7f'; + +// Return the number of characters required to print the given string. +uint32_t print_size(const std::string& text) { + uint32_t size = 0; + for ( const char& ch : text ) { + if ( ch == ' ' ) { size += 1; } + if ( ch == '\t' ) { size += 4; } + } + return size; +} + +// Split the given string into a vector of strings separated by the given delimiter. +std::vector split_string(const std::string& text, const char& delimiter) { + std::vector lines; + std::istringstream stream(text); + std::string line; + while ( std::getline(stream, line, delimiter) ) { + lines.emplace_back(line); + } + return lines; +} + +// Return a string consisting of the given string with leading spaces and tabs removed. +std::string trim_left(const std::string& text) { + size_t start = text.find_first_not_of(" \t"); + return ( start == std::string::npos ) ? "" : text.substr(start); +} + +// Return whether the string 'haystack" contains the string 'needle'. +bool contains(const std::string& haystack, const std::string& needle) { + return haystack.find(needle) != std::string::npos; +} + +// Return a string consisting of the given string repeated the given number of times. +std::string repeat(const std::string& text, const uint32_t& multiple) { + std::string result; + result.reserve(multiple * text.size()); + for ( uint32_t i = 0; i < multiple; ++i ) { + result += text; + } + return result; +} + +// Join a vector of strings into a single string separated by the given delimiter. +std::string join(const std::vector& lines, const std::string& delimiter) { + std::stringstream stream; + std::copy(lines.begin(), lines.end(), std::ostream_iterator(stream, delimiter.c_str())); + return stream.str(); +} + +enum Sort { ASCENDING, DESCENDING }; + +// Correct the given outline if necessary and sort it at every level using the given sort. +void sorted_outline(const std::string& outline, const Sort& sort) { + std::vector lines = split_string(outline, '\n'); + // Remove any initial empty lines which typical occur in raw strings. + while ( lines[0].empty() ) { + lines.erase(lines.begin()); + } + + std::string previous_indent = ""; + std::vector messages = {}; + + // Correct formatting errors in each line of the outline. + for ( uint32_t i = 0; i < lines.size(); ++i ) { + std::string line = lines[i]; + if ( line.starts_with(" ") || line.starts_with("\t") ) { + std::string line_trimmed = trim_left(line); + std::string current_indent = line.substr(0, line.size() - line_trimmed.size()); + if ( previous_indent == "" ) { + previous_indent = current_indent; + } else { + bool correction_needed = false; + + if ( ( contains(current_indent, "\t") && ! contains(previous_indent, "\t") ) || + ( ! contains(current_indent, "\t") && contains(previous_indent, "\t") ) ) { + messages.emplace_back("Corrected inconsistent whitespace use at line \"" + line + "\""); + correction_needed = true; + } + + if ( print_size(current_indent) % print_size(previous_indent) != 0 ) { + messages.emplace_back("Corrected inconsistent indent width at line \"" + line + "\""); + correction_needed = true; + } + + if ( correction_needed ) { + const uint32_t multiple = + std::round(static_cast(print_size(current_indent)) / print_size(previous_indent)); + lines[i] = repeat(previous_indent, multiple) + line_trimmed; + } + } + } + } + + // Determine the level of indent for each line of the outline. + std::vector levels(lines.size(), 0); + uint32_t level = 1; + std::string margin = previous_indent; + while ( std::any_of(levels.begin(), levels.end(), [](const uint32_t& i) { return i == 0; }) ) { + for ( uint32_t i = 0; i < lines.size(); ++i ) { + if ( levels[i] == 0 ) { + const std::string line = lines[i]; + if ( line.starts_with(margin) && line[margin.size()] != ' ' && line[margin.size()] != '\t' ) { + levels[i] = level; + } + } + } + margin += previous_indent; + level += 1; + } + + // Prepare the lines of the outline for sorting. + std::vector new_lines(lines.size(), ""); + new_lines[0] = lines[0]; + std::vector nodes = {}; + for ( uint32_t i = 1; i < lines.size(); ++i ) { + if ( levels[i] > levels[i - 1] ) { + nodes.emplace_back(nodes.empty() ? lines[i - 1] : "\n" + lines[i - 1]); + } else if ( levels[i] < levels[i - 1] ) { + for ( uint32_t j = 1; j <= levels[i - 1] - levels[i]; ++j ) { + nodes.pop_back(); + } + } + + if ( ! nodes.empty() ) { + new_lines[i] = join(nodes, "") + "\n" + lines[i]; + } else { + new_lines[i] = lines[i]; + } + } + + // Sort the lines of the outline. + if ( sort == Sort::ASCENDING ) { + std::sort(new_lines.begin(), new_lines.end()); + } else { + // Pad each line of the outline on the right with 'DELETE' characters. + const uint64_t max_size = + std::ranges::max_element(new_lines, std::ranges::less{}, &std::string::size) -> size(); + for ( uint64_t i = 0; i < new_lines.size(); ++i ) { + new_lines[i].insert(new_lines[i].size(), max_size - new_lines[i].size(), DELETE); + } + + std::sort(new_lines.begin(), new_lines.end(), std::greater()); + } + + for ( uint32_t i = 0; i < new_lines.size(); ++i ) { + std::vector sections = split_string(new_lines[i], '\n'); + new_lines[i] = sections.back(); + + if ( sort == Sort::DESCENDING ) { + // Remove the padding of 'DELETE' characters + const int32_t start = new_lines[i].find_first_of(DELETE); + if ( start > 0 ) { + new_lines[i] = new_lines[i].substr(0, start); + } + } + } + + // Display error messages + if ( ! messages.empty() ) { + for ( const std::string& message : messages ) { + std::cout << message << std::endl; + } + } + + // Display corrected and sorted outline + std::cout << join(new_lines, "\n") << std::endl; +} + +int main() { + std::string outline_spaces = R"( + zeta + beta + gamma + lambda + kappa + mu + delta + alpha + theta + iota + epsilon)"; + + std::string outline_tabs = R"( + zeta + beta + gamma + lambda + kappa + mu + delta + alpha + theta + iota + epsilon)"; + + // All spaces except for the line 'kappa' which contains a tab. + std::string outline_faulty_1 = R"( + alpha + epsilon + iota + theta + zeta + beta + delta + gamma + kappa + lambda + mu)"; + + // All spaces with lines 'gamma' and 'kappa' misaligned. + std::string outline_faulty_2 = R"( + zeta + beta + gamma + lambda + kappa + mu + delta + alpha + theta + iota + epsilon)"; + + std::cout << "Four space indented outline, ascending sort:" << std::endl; + sorted_outline(outline_spaces, Sort::ASCENDING); + + std::cout << "Four space indented outline, descending sort:" << std::endl; + sorted_outline(outline_spaces, Sort::DESCENDING); + + std::cout << "Tab indented outline, ascending sort:" << std::endl; + sorted_outline(outline_tabs, Sort::ASCENDING); + + std::cout << "Tab space indented outline, descending sort:" << std::endl; + sorted_outline(outline_tabs, Sort::DESCENDING); + + std::cout << "First faulty outline, ascending sort:" << std::endl; + sorted_outline(outline_faulty_1, Sort::ASCENDING); + + std::cout << "First faulty outline, descending sort:" << std::endl; + sorted_outline(outline_faulty_1, Sort::DESCENDING); + + std::cout << "Second faulty outline, ascending sort:" << std::endl; + sorted_outline(outline_faulty_2, Sort::ASCENDING); + + std::cout << "Second faulty outline, descending sort:" << std::endl; + sorted_outline(outline_faulty_2, Sort::DESCENDING); +} diff --git a/Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq b/Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq new file mode 100644 index 0000000000..f88bb01876 --- /dev/null +++ b/Task/Sort-an-outline-at-every-level/Jq/sort-an-outline-at-every-level.jq @@ -0,0 +1,169 @@ +# Left justify . +def ljust($width; $pad): + tostring as $s + | ($s|length) as $length + | if $width > $length + then $s + $pad * ($width - $length) + else $s + end; + +def sortedOutline($ascending): + + def del: "\u007f"; + def sep: "\u0000"; + + if .[0] | test("^[ \t]") + then " outline structure is unclear" | error + else + reduce range(1; length) as $i ( + { outline: ., + indent: "", + messages: [] }; + .outline[$i] as $line + | ($line|length) as $lc + | if $line | test("^( | \t|\t)") + then ($line | sub("^[ \t]*";"") | length) as $lc2 + | $line[0:$lc-$lc2] as $currIndent + + | if .indent == "" + then .indent = $currIndent + else .correctionNeeded = false + | if (($currIndent|test("\t")) and (.indent|contains("\t") | not)) or + (($currIndent|test("\t")|not) and (.indent|test("\t"))) + then .messages += [.indent + "corrected inconsistent whitespace use at line '\($line)'"] + | .correctionNeeded = true + elif (($currIndent|length) % (.indent|length)) != 0 + then .messages += [.indent + "corrected inconsistent indent width at line '\($line)'"] + | .correctionNeeded = true + end + | if .correctionNeeded + then ((($currIndent|length) / (.indent|length)) |round) as $mult + | .outline[$i] = (.indent * $mult) + $line[$lc-$lc2:] + end + end + end ) + end + | .levels = [range(0; .outline|length) | 0] + | .levels[0] = 1 + | .level = 1 + | .margin = "" + # while any of the levels is 0 ... + | until( all( .levels[]; . > 0); + (.margin|length) as $mc + | reduce range(1; .outline|length) as $i (.; + if .levels[$i] == 0 + then .outline[$i] as $line + | .margin as $margin + | if ($line|startswith($margin)) and + ($line[$mc:$mc+1] | (. != " ") and (. != "\t")) + then .levels[$i] = .level + end + end ) + | .margin += .indent + | .level += 1 ) + | .lines = [range(0; .outline|length) | ""] + | .lines[0] = .outline[0] + | .nodes = [] + | reduce range(1; .outline|length) as $i (.; + if .levels[$i] > .levels[$i-1] + then .nodes += [ if .nodes|length == 0 then .outline[$i-1] else sep + .outline[$i-1] end] + elif .levels[$i] < .levels[$i-1] + then (.levels[$i-1] - .levels[$i] ) as $j + # remove $j elements from the tail + | .nodes |= .[0: length-$j] + end + | if .nodes|length > 0 + then .lines[$i] = (.nodes|join("")) + sep + .outline[$i] + else .lines[$i] = .outline[$i] + end ) + | if $ascending + then .lines |= sort + else (.lines | map(length) | max) as $maxLen + | reduce range(0; .lines|length) as $i (.; + .lines[$i] |= ljust($maxLen; del) ) + | .lines |= (sort|reverse) + end + | reduce range(0; .lines|length) as $i (.; + (.lines[$i]|split(sep) ) as $s + | .lines[$i] = $s[-1] + | if ($ascending|not) + then .lines[$i] |= sub( del + "+$"; "") + end ) + # First print the messages, and then the lines: + | (select((.messages|length) > 0) + | (.messages | join("\n")) + "\n"), + + (.lines|join("\n")) ; + + +### Examples + +def outline: [ + "zeta", + " beta", + " gamma", + " lambda", + " kappa", + " mu", + " delta", + "alpha", + " theta", + " iota", + " epsilon" +]; + +def outline2: + outline | map(gsub(" "; "\t")); + +def outline3: [ + "alpha", + " epsilon", + " iota", + " theta", + "zeta", + " beta", + " delta", + " gamma", + " \t kappa", # same length but \t instead of space + " lambda", + " mu" +]; + +def outline4: [ + "zeta", + " beta", + " gamma", + " lambda", + " kappa", + " mu", + " delta", + "alpha", + " theta", + " iota", + " epsilon" +]; + + +(outline +| "Four space indented outline, ascending sort:", + sortedOutline(true), + "\nFour space indented outline, descending sort:", + sortedOutline(false)), + +(outline2 +| "\nTab indented outline, ascending sort:", + sortedOutline(true), + "\nTab indented outline, descending sort:", + sortedOutline(false) ), + +(outline3 +| "\nFirst unspecified outline, ascending sort:", + sortedOutline(true), + "\nFirst unspecified outline, descending sort:", + sortedOutline(false) ), + +(outline4 +| "\nSecond unspecified outline, ascending sort:", + sortedOutline(true), + "\nSecond unspecified outline, descending sort:", + sortedOutline(false)) diff --git a/Task/Sort-disjoint-sublist/Uiua/sort-disjoint-sublist.uiua b/Task/Sort-disjoint-sublist/Uiua/sort-disjoint-sublist.uiua new file mode 100644 index 0000000000..b279b2229d --- /dev/null +++ b/Task/Sort-disjoint-sublist/Uiua/sort-disjoint-sublist.uiua @@ -0,0 +1 @@ +⍜▽(⊏⍏.)°⊚ 6_1_7 [7 6 5 4 3 2 1 0] diff --git a/Task/Sort-numbers-lexicographically/EasyLang/sort-numbers-lexicographically.easy b/Task/Sort-numbers-lexicographically/EasyLang/sort-numbers-lexicographically.easy new file mode 100644 index 0000000000..737e91b0eb --- /dev/null +++ b/Task/Sort-numbers-lexicographically/EasyLang/sort-numbers-lexicographically.easy @@ -0,0 +1,14 @@ +func[] numlexsort n . + for i to n + d[] &= i + . + for i = 1 to len d[] - 1 + for j = i + 1 to len d[] + if strcmp d[j] d[i] < 0 + swap d[j] d[i] + . + . + . + return d[] +. +print numlexsort 13 diff --git a/Task/Sort-three-variables/PascalABC.NET/sort-three-variables.pas b/Task/Sort-three-variables/PascalABC.NET/sort-three-variables.pas new file mode 100644 index 0000000000..f8ac9fe119 --- /dev/null +++ b/Task/Sort-three-variables/PascalABC.NET/sort-three-variables.pas @@ -0,0 +1,14 @@ +procedure SortThree(var x,y,z: integer); +begin + if x > y then Swap(x, y); + if x > z then Swap(x, z); + if y > z then Swap(y, z); +end; + +begin + var (x,y,z) := Random3(1,10); + Println(x,y,z); + SortThree(x,y,z); + Assert((x <= y) and (y <= z)); + Println(x,y,z); +end. diff --git a/Task/Sort-using-a-custom-comparator/PascalABC.NET/sort-using-a-custom-comparator.pas b/Task/Sort-using-a-custom-comparator/PascalABC.NET/sort-using-a-custom-comparator.pas new file mode 100644 index 0000000000..9a5a826be7 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PascalABC.NET/sort-using-a-custom-comparator.pas @@ -0,0 +1,10 @@ +type + Pair = auto class + Name,Value: string; + end; + +begin + var a: array of Pair := (new Pair('ZZZ','333'),new Pair('XXX','222'),new Pair('YYY','111')); + Sort(a, (p1,p2) -> p1.Name < p2.Name); + Print(a); +end. diff --git a/Task/Sorting-Algorithms-Circle-Sort/ALGOL-68/sorting-algorithms-circle-sort.alg b/Task/Sorting-Algorithms-Circle-Sort/ALGOL-68/sorting-algorithms-circle-sort.alg new file mode 100644 index 0000000000..206cb4b973 --- /dev/null +++ b/Task/Sorting-Algorithms-Circle-Sort/ALGOL-68/sorting-algorithms-circle-sort.alg @@ -0,0 +1,67 @@ +BEGIN # circlesort # + + # swaps a and b # + PRIO =:= = 9; + OP =:= = ( REF INT a, b )VOID: BEGIN INT t = a; a := b; b := t END; + + # sorts data in-place and returns a reference to data # + OP CIRCLESORT = ( REF[]INT data )REF[]INT: + BEGIN + PROC circlesort = ( REF[]INT data, INT low, high, swaps so far )INT: + IF low >= high THEN swaps so far + ELSE + INT swaps := swaps so far; + INT hi := high; + INT lo := low; + INT mid = ( hi - lo ) OVER 2; + WHILE lo < hi DO + IF data[ lo ] > data[ hi ] THEN + data[ lo ] =:= data[ hi ]; + swaps +:= 1 + FI; + lo +:= 1; + hi -:= 1 + OD; + IF lo = hi AND hi < UPB data THEN + IF data[ lo ] > data[ hi + 1 ] THEN + data[ lo ] =:= data[ hi + 1 ]; + swaps +:= 1 + FI + FI; + swaps := circlesort( data, low, low + mid, swaps ); + swaps := circlesort( data, low + mid + 1, high, swaps ) + FI # circlesort # ; + + WHILE circlesort( data, LWB data, UPB data, 0 ) > 0 DO SKIP OD; + data + END # CIRCLESORT # ; + + # prints the elements of an array of integers separated by spaces # + OP SHOW = ( []INT list )VOID: + FOR i FROM LWB list TO UPB list DO + print( ( " ", whole( list[ i ], 0 ) ) ) + OD # SHOW # ; + + # tests the CIRCLESORT operator # + PROC test circle sort = ( []INT unsorted )VOID: + BEGIN + [ LWB unsorted : UPB unsorted ]INT data := unsorted; + print( ( "[" ) ); + SHOW unsorted; + print( ( " ]", newline, " -> [" ) ); + SHOW CIRCLESORT data; + print( ( " ]", newline ) ) + END # test circle sort # ; + + # task test case # + test circle sort( ( 6, 7, 8, 9, 2, 5, 3, 4, 1 ) ); + # test cases from the Action! sample # + test circle sort( ( 1, 4, -1, 0, 3, 7, 4, 8, 20, -6 ) ); + test circle sort( ( 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 ) ); + test circle sort( ( 101, 102, 103, 104, 105, 106, 107, 108 ) ); + test circle sort( ( 1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, -1 ) ); + # additional tests # + test circle sort( ( ) ); + test circle sort( ( 1 ) ) + +END diff --git a/Task/Sorting-Algorithms-Circle-Sort/EasyLang/sorting-algorithms-circle-sort.easy b/Task/Sorting-Algorithms-Circle-Sort/EasyLang/sorting-algorithms-circle-sort.easy new file mode 100644 index 0000000000..1bfad31157 --- /dev/null +++ b/Task/Sorting-Algorithms-Circle-Sort/EasyLang/sorting-algorithms-circle-sort.easy @@ -0,0 +1,31 @@ +global d[] . +func circsort lo hi swaps . + if lo = hi + return swaps + . + high = hi + low = lo + mid = (hi - lo) div 2 + while lo < hi + if d[lo] > d[hi] + swap d[lo] d[hi] + swaps += 1 + . + lo += 1 + hi -= 1 + . + if lo = hi + if d[lo] > d[hi + 1] + swap d[lo] d[hi + 1] + swaps += 1 + . + . + swaps = circsort low (low + mid) swaps + swaps = circsort (low + mid + 1) high swaps + return swaps +. +d[] = [ -4 -1 1 0 5 -7 -2 4 -6 -3 2 6 3 7 -5 ] +while circsort 1 len d[] 0 > 0 + # +. +print d[] diff --git a/Task/Sorting-algorithms-Bogosort/EMal/sorting-algorithms-bogosort.emal b/Task/Sorting-algorithms-Bogosort/EMal/sorting-algorithms-bogosort.emal new file mode 100644 index 0000000000..3966eca2e0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/EMal/sorting-algorithms-bogosort.emal @@ -0,0 +1,19 @@ +type BogoSorter +fun inOrder ← logic by List list + if list.length ≤ 1 do return true end + for int i ← 1; i < list.length; ++i + if list[i] < list[i - 1] do return false end + end + return true +end +fun shuffle ← d[i + 1] + swap d[i] d[i + 1] + h = i + . + . + b = h - 1 + h = b + for i = b downto a + if d[i] > d[i + 1] + swap d[i] d[i + 1] + h = i + . + . + a = h + 1 + . +. +l[] = [ 5 6 1 2 9 14 2 15 6 7 8 97 ] +sort l[] +print l[] diff --git a/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy b/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy new file mode 100644 index 0000000000..78061a2157 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy @@ -0,0 +1,17 @@ +proc combsort . d[] . + gap = len d[] + while gap > 1 or swaps = 1 + gap = higher 1 (gap div 1.25) + swaps = 0 + for i = 1 to len d[] - gap + j = i + gap + if d[i] > d[j] + swap d[i] d[j] + swaps = 1 + . + . + . +. +d[] = [ 88 18 31 44 4 0 8 81 14 78 20 76 84 33 73 75 82 5 62 70 ] +combsort d[] +print d[] diff --git a/Task/Sorting-algorithms-Counting-sort/Langur/sorting-algorithms-counting-sort.langur b/Task/Sorting-algorithms-Counting-sort/Langur/sorting-algorithms-counting-sort.langur index f70238e95f..cc333bc3fa 100644 --- a/Task/Sorting-algorithms-Counting-sort/Langur/sorting-algorithms-counting-sort.langur +++ b/Task/Sorting-algorithms-Counting-sort/Langur/sorting-algorithms-counting-sort.langur @@ -1,11 +1,11 @@ -val .countingSort = fn(.list) { - val .min, .max = minmax(.list) - var .count = [0] * (.max-.min+1) - for .i in .list { .count[.i-.min+1] += 1 } - for .i of .count { _for ~= .count[.i] * [.i+.min-1] } +val countingSort = fn(zlist) { + val mi, ma = minmax(zlist) + var cnt = [0] * (ma-mi+1) + for i in zlist { cnt[i-mi+1] += 1 } + for i of cnt { _for ~= cnt[i] * [i+mi-1] } } -val .data = [7, 234, -234, 9, 43, 123, 14] +val data = [7, 234, -234, 9, 43, 123, 14] -writeln "Original: ", .data -writeln "Sorted : ", .countingSort(.data) +writeln "Original: ", data +writeln "Sorted : ", countingSort(data) diff --git a/Task/Sorting-algorithms-Counting-sort/Yabasic/sorting-algorithms-counting-sort.basic b/Task/Sorting-algorithms-Counting-sort/Yabasic/sorting-algorithms-counting-sort.basic new file mode 100644 index 0000000000..927f87dc47 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Yabasic/sorting-algorithms-counting-sort.basic @@ -0,0 +1,72 @@ +dim array(15) +a = 0 +b = arraysize(array(),1) + +for i = a to b + array(i) = ran(1000) +next i + +print "unsort "; +printArray(array()) +mx = findMax(array()) +mn = findMin(array()) + +countingSort(array(), mn, mx) // ordenar el array + +print " sort "; +printArray(array()) +end + +sub findMax(array()) + local length, i + + length = arraysize(array(),1) - 1 + if length = 0 return 0 + if length = 1 return array(0) + mx = 0 + for i = 1 to arraysize(array(),1) + if array(i) > mx mx = array(i) + next i + return mx +end sub + +sub findMin(array()) + local length, i + + length = arraysize(array(),1) - 1 + if length = 0 return 0 + if length = 1 return array(0) + mn = 0 + for i = 1 to arraysize(array(),1) + if array(i) < mn mn = array(i) + next i + return mn +end sub + +sub countingSort(array(), mn, mx) + local number, z, i, ub + + dim count(mx - mn) + ub = arraysize(array(),1) + + for i = 0 to ub + number = array(i) + count(number - mn) = count(number - mn) + 1 + next + z = 0 + for i = mn to mx + while count(i - mn) > 0 + array(z) = i + z = z + 1 + count(i - mn) = count(i - mn) - 1 + wend + next i +end sub + +sub printArray(array()) + for i = 0 to arraysize(array(),1) + print array(i) using("####"); + if i = b then print ""; else print ", "; : fi + next i + print +end sub diff --git a/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-3.lisp b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-3.lisp new file mode 100644 index 0000000000..fe968b834d --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-3.lisp @@ -0,0 +1,24 @@ +(defgeneric nsrt (sequence predicate)) + +(defmethod nsrt ((sequence sequence) predicate) + (loop :for i :from 1 :below (length sequence) + :do (loop :for j :from i :downto 1 + :do (let ((current (elt sequence j)) + (previous (elt sequence (1- j)))) + (when (funcall predicate current previous) + (rotatef (elt sequence j) + (elt sequence (1- j)))))) + :finally (return sequence))) + +;; (nsrt "adfcghjiklmnoprbtuvqewysxz" #'char<) +;; => "abcdefghijklmnopqrstuvwxyz" +;; +;; (nsrt '(who the hecc do you think i am?) +;; (lambda (x y) +;; (string< (nsrt (format nil "~a" x) #'char<) +;; (nsrt (format nil "~a" y) #'char<)))) +;; => (AM? HECC DO THE THINK WHO I YOU) +;; +;; (nsrt (loop :for i :from 1 :to 1000 :collect (random i)) +;; #'<) +;; => [not printed but works, try it!] diff --git a/Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort.kotlin b/Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort-1.kotlin similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort.kotlin rename to Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort-1.kotlin diff --git a/Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort-2.kotlin b/Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort-2.kotlin new file mode 100644 index 0000000000..a829e8dcc8 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Kotlin/sorting-algorithms-insertion-sort-2.kotlin @@ -0,0 +1,16 @@ +fun > Array.insertionSort() { + for (i in 1..lastIndex) { + val currentElement = this[i] + var low = 0 + var high = i - 1 + while (low <= high) { + val mid = low + (high - low) / 2 + if (this[mid] <= currentElement) + low = mid + 1 + else + high = mid - 1 + } + copyInto(this, low + 1, low, i) + this[low] = currentElement + } +} diff --git a/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml b/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml index f854d7afd7..2b1e424219 100644 --- a/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml +++ b/Task/Sorting-algorithms-Merge-sort/Standard-ML/sorting-algorithms-merge-sort.ml @@ -1,9 +1,10 @@ fun merge cmp ([], ys) = ys | merge cmp (xs, []) = xs | merge cmp (xs as x::xs', ys as y::ys') = - case cmp (x, y) of GREATER => y :: merge cmp (xs, ys') - | _ => x :: merge cmp (xs', ys) -; + case cmp (x, y) of + GREATER => y :: merge cmp (xs, ys') + | _ => x :: merge cmp (xs', ys) + fun merge_sort cmp [] = [] | merge_sort cmp [x] = [x] | merge_sort cmp xs = let @@ -12,5 +13,3 @@ fun merge_sort cmp [] = [] in merge cmp (merge_sort cmp ys, merge_sort cmp zs) end -; -merge_sort Int.compare [8,6,4,2,1,3,5,7,9] diff --git a/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy b/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy new file mode 100644 index 0000000000..24657b1535 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy @@ -0,0 +1,48 @@ +global a[] . +proc flip n . . + for i = 1 to n div 2 + swap a[i] a[n - i + 1] + . + # print "flip (1 .. " & n & ") : " & a[] +. +func[] minmax n . + pmin = 1 + pmax = 1 + for i = 2 to n + if a[i] > a[pmax] + pmax = i + elif a[i] < a[pmin] + pmin = i + . + . + return [ pmin pmax ] +. +proc pcsort n dir . . + if n = 1 + return + . + r[] = minmax n + bestx = r[dir] + altx = r[3 - dir] + flipped = 0 + if bestx = n + n -= 1 + elif bestx = 1 + flip n + n -= 1 + elif altx = n + dir = 3 - dir + n -= 1 + flipped = 1 + else + flip bestx + . + pcsort n dir + if flipped = 1 + flip n + 1 + . +. +a[] = [ 6 7 2 1 8 9 5 3 4 ] +print a[] +pcsort len a[] 2 +print a[] diff --git a/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.ada b/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.ada new file mode 100644 index 0000000000..bb2a8889c7 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.ada @@ -0,0 +1,39 @@ +-- Permutation sort +-- J. Carter 2024 Jun +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Permutations; + +procedure Slow_Sort is + package Char_Perms is new PragmARC.Permutations (Element => Character); + + procedure Put (Item : in Char_Perms.Sequence); + -- Outputs all the Characters in Item to standard output, followed by a line terminator + + procedure Process (Seq : in Char_Perms.Sequence; Stop : in out Boolean); + -- If Seq is sorted, outputs it and sets Stop to True + + procedure Put (Item : in Char_Perms.Sequence) is + -- Empty + begin -- Put + All_Chars : for C of Item loop + Ada.Text_IO.Put (Item => C); + end loop All_Chars; + + Ada.Text_IO.New_Line; + end Put; + + procedure Process (Seq : in Char_Perms.Sequence; Stop : in out Boolean) is + -- Empty + begin -- Process + if (for all J in 1 .. Seq'Last - 1 => Seq (J) <= Seq (J + 1) ) then -- Sorted + Put (Item => Seq); + Stop := True; + end if; + end Process; + + Test : constant Char_Perms.Sequence := "kjihgfedcba"; +begin -- Slow_Sort + Char_Perms.Generate (Initial => Test, Process => Process'Access); +end Slow_Sort; diff --git a/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy b/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy new file mode 100644 index 0000000000..fa9ff44ab4 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy @@ -0,0 +1,49 @@ +global perm[] . +proc nextperm . a[] . + n = len perm[] + k = n - 1 + while k >= 1 and perm[k + 1] <= perm[k] + k -= 1 + . + if k = 0 + a[] = [ ] + return + . + l = n + while perm[l] <= perm[k] + l -= 1 + . + swap perm[l] perm[k] + swap a[l] a[k] + k += 1 + while k < n + swap perm[k] perm[n] + swap a[k] a[n] + k += 1 + n -= 1 + . +. +proc perminit . a[] . + for i to len a[] + perm[] &= i + . +. +proc permsort . a[] . + perminit a[] + repeat + for i = 2 to len a[] + if a[i - 1] > a[i] + break 1 + . + . + until i > len a[] + nextperm a[] + if len a[] = 0 + print "error" + break 1 + . + . +. +arr[] = [ 7 6 5 9 8 4 3 1 2 0 ] +permsort arr[] +print arr[] diff --git a/Task/Sorting-algorithms-Quicksort/11l/sorting-algorithms-quicksort.11l b/Task/Sorting-algorithms-Quicksort/11l/sorting-algorithms-quicksort.11l index d7b0f8efb8..708c053f94 100644 --- a/Task/Sorting-algorithms-Quicksort/11l/sorting-algorithms-quicksort.11l +++ b/Task/Sorting-algorithms-Quicksort/11l/sorting-algorithms-quicksort.11l @@ -1,4 +1,4 @@ -F _quicksort(&array, start, stop) -> N +F _quicksort(&array, start, stop) -> Void I stop - start > 0 V pivot = array[start] V left = start diff --git a/Task/Sorting-algorithms-Quicksort/ANSI-BASIC/sorting-algorithms-quicksort.basic b/Task/Sorting-algorithms-Quicksort/ANSI-BASIC/sorting-algorithms-quicksort.basic new file mode 100644 index 0000000000..3280568cbf --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ANSI-BASIC/sorting-algorithms-quicksort.basic @@ -0,0 +1,51 @@ +100 REM Sorting algorithms/Quicksort +110 DECLARE EXTERNAL SUB QuickSort +120 DIM Arr(0 TO 19) +130 LET A = LBOUND(Arr) +140 LET B = UBOUND(Arr) +150 RANDOMIZE +160 FOR I = A TO B +170 LET Arr(I) = ROUND(INT(RND * 99)) +180 NEXT I +190 PRINT "Unsorted:" +200 FOR I = A TO B +210 PRINT USING "## ": Arr(I); +220 NEXT I +230 PRINT +240 PRINT "Sorted:" +250 CALL QuickSort(Arr, A, B) +260 FOR I = A TO B +270 PRINT USING "## ": Arr(I); +280 NEXT I +290 PRINT +300 END +310 REM ** +320 EXTERNAL SUB QuickSort (Arr(), L, R) +330 LET LIndex = L +340 LET RIndex = R +350 IF R > L THEN +360 LET Pivot = INT((L + R) / 2) +370 DO WHILE (LIndex <= Pivot) AND (RIndex >= Pivot) +380 DO WHILE (Arr(LIndex) < Arr(Pivot)) AND (LIndex <= Pivot) +390 LET LIndex = LIndex + 1 +400 LOOP +410 DO WHILE (Arr(RIndex) > Arr(Pivot)) AND (RIndex >= Pivot) +420 LET RIndex = RIndex - 1 +430 LOOP +440 LET Temp = Arr(LIndex) +450 LET Arr(LIndex) = Arr(RIndex) +460 LET Arr(RIndex) = Temp +470 LET LIndex = LIndex + 1 +480 LET RIndex = RIndex - 1 +490 IF (LIndex - 1) = Pivot THEN +500 LET RIndex = RIndex + 1 +510 LET Pivot = RIndex +520 ELSEIF (RIndex + 1) = Pivot THEN +530 LET LIndex = LIndex - 1 +540 LET Pivot = LIndex +550 END IF +560 LOOP +570 CALL QuickSort (Arr, L, Pivot - 1) +580 CALL QuickSort (Arr, Pivot + 1, R) +590 END IF +600 END SUB diff --git a/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy b/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy index 4838d2105f..7ddf5cf8ad 100644 --- a/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy +++ b/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy @@ -1,24 +1,17 @@ proc qsort left right . d[] . - while left < right - # partition - piv = d[left] - mid = left - for i = left + 1 to right - if d[i] < piv - mid += 1 - swap d[i] d[mid] - . - . - swap d[left] d[mid] - # - if mid < (right + left) / 2 - qsort left mid - 1 d[] - left = mid + 1 - else - qsort mid + 1 right d[] - right = mid - 1 + if left >= right + return + . + mid = left + for i = left + 1 to right + if d[i] < d[left] + mid += 1 + swap d[i] d[mid] . . + swap d[left] d[mid] + qsort left mid - 1 d[] + qsort mid + 1 right d[] . proc sort . d[] . qsort 1 len d[] d[] diff --git a/Task/Sorting-algorithms-Quicksort/PascalABC.NET/sorting-algorithms-quicksort.pas b/Task/Sorting-algorithms-Quicksort/PascalABC.NET/sorting-algorithms-quicksort.pas new file mode 100644 index 0000000000..3ca9ce5b4e --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PascalABC.NET/sorting-algorithms-quicksort.pas @@ -0,0 +1,41 @@ +function Partition(a: array of integer; l,r: integer): integer; +begin + var i := l - 1; + var j := r + 1; + var x := a[l]; + while True do + begin + repeat + i += 1; + until a[i]>=x; + repeat + j -= 1; + until a[j]<=x; + if i=r then exit; + var j := Partition(a,l,r); + QuickSort(a,l,j); + QuickSort(a,j+1,r); +end; + +const n = 20; + +begin + var a := ArrRandom(n); + Println('Before: '); + Println(a); + QuickSort(a,0,a.Length-1); + Println('After sorting: '); + Println(a); +end. diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-8.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-8.py new file mode 100644 index 0000000000..9511b0bdb8 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-8.py @@ -0,0 +1,9 @@ +def quicksort(unsorted_list): + if len(unsorted_list) == 0: + return [] + pivot = unsorted_list[0] + less = list(filter(lambda x: x < pivot, unsorted_list)) + same = list(filter(lambda x: x == pivot, unsorted_list)) + more = list(filter(lambda x: x > pivot, unsorted_list)) + + return quicksort(less) + same + quicksort(more) diff --git a/Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic b/Task/Sorting-algorithms-Quicksort/QuickBASIC/sorting-algorithms-quicksort.basic similarity index 100% rename from Task/Sorting-algorithms-Quicksort/BASIC/sorting-algorithms-quicksort.basic rename to Task/Sorting-algorithms-Quicksort/QuickBASIC/sorting-algorithms-quicksort.basic diff --git a/Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic b/Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic new file mode 100644 index 0000000000..b50bd9c3c1 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/XBasic/sorting-algorithms-quicksort.basic @@ -0,0 +1,75 @@ +' Sorting algorithms/Quicksort +PROGRAM "quicksort" +VERSION "1.0" + +IMPORT "xst" + +DECLARE FUNCTION Entry () +DECLARE FUNCTION QuickSort (@arr%[], l%%, r%%) +' Pseudo-random number generator +' Based on the rand, srand functions from Kernighan & Ritchie's book +' 'The C Programming Language' +DECLARE FUNCTION Rand() +DECLARE FUNCTION SRand(seed%%) + +FUNCTION Entry () + DIM arr%[19] + a%% = 0 + b%% = UBOUND(arr%[]) + XstGetSystemTime (@msec) + SRand(INT(msec) MOD 32768) + FOR i%% = a%% TO b%% + arr%[i%%] = INT(Rand() / 32768.0 * 99.0) + NEXT i%% + PRINT "Unsorted:" + FOR i%% = a%% TO b%% + PRINT FORMAT$("## ", arr%[i%%]); + NEXT i%% + PRINT + PRINT "Sorted:" + QuickSort(@arr%[], a%%, b%%) + FOR i%% = a%% TO b%% + PRINT FORMAT$("## ", arr%[i%%]); + NEXT i%% + PRINT +END FUNCTION + +FUNCTION QuickSort (@arr%[], l%%, r%%) + leftIndex%% = l%% + rightIndex%% = r%% + IF r%% > l%% THEN + pivot%% = (l%% + r%%) \ 2 + DO WHILE (leftIndex%% <= pivot%%) AND (rightIndex%% >= pivot%%) + DO WHILE (arr%[leftIndex%%] < arr%[pivot%%]) AND (leftIndex%% <= pivot%%) + INC leftIndex%% + LOOP + DO WHILE (arr%[rightIndex%%] > arr%[pivot%%]) AND (rightIndex%% >= pivot%%) + DEC rightIndex%% + LOOP + SWAP arr%[leftIndex%%], arr%[rightIndex%%] + INC leftIndex%% + DEC rightIndex%% + SELECT CASE TRUE + CASE leftIndex%% - 1 = pivot%%: + INC rightIndex%% + pivot%% = rightIndex%% + CASE rightIndex%% + 1 = pivot%%: + DEC leftIndex%% + pivot%% = leftIndex%% + END SELECT + LOOP + QuickSort (@arr%[], l%%, pivot%% - 1) + QuickSort (@arr%[], pivot%% + 1, r%%) + END IF +END FUNCTION + +' Return pseudo-random integer on 0..32767 +FUNCTION Rand() + #next&& = #next&& * 1103515245 + 12345 +END FUNCTION USHORT(#next&& / 65536) MOD 32768 + +' Set seed for Rand() +FUNCTION SRand(seed%%) + #next&& = seed%% +END FUNCTION +END PROGRAM diff --git a/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy b/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy new file mode 100644 index 0000000000..81c18775a5 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy @@ -0,0 +1,18 @@ +proc shellsort . a[] . + inc = len a[] div 2 + while inc > 0 + for i = inc to len a[] + tmp = a[i] + j = i + while j > inc and a[j - inc] > tmp + a[j] = a[j - inc] + j = j - inc + . + a[j] = tmp + . + inc = floor (0.5 + inc / 2.2) + . +. +a[] = [ -12 3 0 4 7 4 8 -5 9 ] +shellsort a[] +print a[] diff --git a/Task/Sorting-algorithms-Stooge-sort/11l/sorting-algorithms-stooge-sort.11l b/Task/Sorting-algorithms-Stooge-sort/11l/sorting-algorithms-stooge-sort.11l index 73342017c6..a6ee8c8ca9 100644 --- a/Task/Sorting-algorithms-Stooge-sort/11l/sorting-algorithms-stooge-sort.11l +++ b/Task/Sorting-algorithms-Stooge-sort/11l/sorting-algorithms-stooge-sort.11l @@ -1,4 +1,4 @@ -F stoogesort(&l, i, j) -> N +F stoogesort(&l, i, j) -> Void I l[j] < l[i] swap(&l[i], &l[j]) I j - i > 1 diff --git a/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy b/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy index 9e4fcc91e1..90b23cbadc 100644 --- a/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy +++ b/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy @@ -9,8 +9,6 @@ proc stsort left right . d[] . stsort left right - t d[] . . -for i = 1 to 100 - d[] &= randint 1000 -. +d[] = [ 1 4 5 3 -6 3 7 10 -2 -5 ] stsort 1 len d[] d[] print d[] diff --git a/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic b/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic new file mode 100644 index 0000000000..fb592eb1bf --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic @@ -0,0 +1,38 @@ +dim array(15) +a = 0 +b = arraysize(array(),1) + +for i = a to b + array(i) = ran(1000) +next i + +print "unsort "; +for i = a to b + print array(i) using("####"); + if i = b then print ""; else print ", "; : fi +next i + +stoogeSort(array(), a, b) // ordenar el array + +print "\n sort "; +for i = a to b + print array(i) using("####"); + if i = b then print ""; else print ", "; : fi +next i +print +end + +sub stoogeSort(array(), l, r) + if array(r) < array(l) then + temp = array(r) + array(r) = array(l) + array(l) = temp + fi + + if r - l > 1 then + t = int((r - l +1) / 3) + stoogeSort(array(), l , r - t) + stoogeSort(array(), l + t, r ) + stoogeSort(array(), l , r - t) + fi +end sub diff --git a/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy b/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy new file mode 100644 index 0000000000..484f6e4117 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy @@ -0,0 +1,43 @@ +proc merge . a[] b[] . + a = 1 ; b = 1 + while a <= len a[] and b <= len b[] + if a[a] < b[b] + r[] &= a[a] + a += 1 + else + r[] &= b[b] + b += 1 + . + . + while a <= len a[] + r[] &= a[a] + a += 1 + . + while b <= len b[] + r[] &= b[b] + b += 1 + . + swap a[] r[] +. +proc strand . a[] s[] . + s[] = [ a[1] ] + for i = 2 to len a[] + if a[i] > s[$] + s[] &= a[i] + else + an[] &= a[i] + . + . + swap a[] an[] +. +proc strandsort . a[] . + strand a[] out[] + while len a[] > 0 + strand a[] b[] + merge out[] b[] + . + swap a[] out[] +. +a[] = [ 1 6 3 2 1 7 5 3 ] +strandsort a[] +print a[] diff --git a/Task/Special-variables/PascalABC.NET/special-variables-1.pas b/Task/Special-variables/PascalABC.NET/special-variables-1.pas new file mode 100644 index 0000000000..1fcb3cc601 --- /dev/null +++ b/Task/Special-variables/PascalABC.NET/special-variables-1.pas @@ -0,0 +1,4 @@ +function Add(a,b: integer): integer; +begin + Result := a + b +end; diff --git a/Task/Special-variables/PascalABC.NET/special-variables-2.pas b/Task/Special-variables/PascalABC.NET/special-variables-2.pas new file mode 100644 index 0000000000..e0b87b6a18 --- /dev/null +++ b/Task/Special-variables/PascalABC.NET/special-variables-2.pas @@ -0,0 +1,7 @@ +type A = class + n: integer; + constructor (n: integer); + begin + Self.n := n + end; +end; diff --git a/Task/Special-variables/PascalABC.NET/special-variables-3.pas b/Task/Special-variables/PascalABC.NET/special-variables-3.pas new file mode 100644 index 0000000000..8d09583abe --- /dev/null +++ b/Task/Special-variables/PascalABC.NET/special-variables-3.pas @@ -0,0 +1,4 @@ +type A = class + n: integer; + property pn: integer write n := value; +end; diff --git a/Task/Split-a-character-string-based-on-change-of-character/Refal/split-a-character-string-based-on-change-of-character.refal b/Task/Split-a-character-string-based-on-change-of-character/Refal/split-a-character-string-based-on-change-of-character.refal new file mode 100644 index 0000000000..356936cfb5 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Refal/split-a-character-string-based-on-change-of-character.refal @@ -0,0 +1,16 @@ +$ENTRY Go { + = >>; +}; + +Split { + (e.Cur) = (e.Cur); + (e.Cur s.1) s.1 e.X = ; + (e.Cur) s.1 e.X = (e.Cur) ; + s.1 e.X = ; +}; + +Join { + (e.Joiner) = ; + (e.Joiner) (e.Str) = e.Str; + (e.Joiner) (e.Str) e.Strs = e.Str e.Joiner ; +}; diff --git a/Task/Split-a-character-string-based-on-change-of-character/SETL/split-a-character-string-based-on-change-of-character.setl b/Task/Split-a-character-string-based-on-change-of-character/SETL/split-a-character-string-based-on-change-of-character.setl new file mode 100644 index 0000000000..7c186a705a --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/SETL/split-a-character-string-based-on-change-of-character.setl @@ -0,0 +1,17 @@ +program split_a_character_string_based_on_change_of_character; + s := "gHHH5YY++///\\"; + print(join_strings(", ", split_on_change(s))); + + proc split_on_change(s); + parts := []; + loop while s /= "" do + parts with:= span(s, s(1)); + end loop; + return parts; + end proc; + + proc join_strings(s, parts); + if parts=[] then return ""; end if; + return parts(1) +/ [s + part : part in parts(2..)]; + end proc; +end program; diff --git a/Task/Split-a-character-string-based-on-change-of-character/Uiua/split-a-character-string-based-on-change-of-character.uiua b/Task/Split-a-character-string-based-on-change-of-character/Uiua/split-a-character-string-based-on-change-of-character.uiua new file mode 100644 index 0000000000..2fb89a9b6a --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Uiua/split-a-character-string-based-on-change-of-character.uiua @@ -0,0 +1 @@ +&p/$"_, _"⊜□+1⊸⊛ "gHHH5YY++///\\" diff --git a/Task/Square-but-not-cube/8080-Assembly/square-but-not-cube.8080 b/Task/Square-but-not-cube/8080-Assembly/square-but-not-cube.8080 new file mode 100644 index 0000000000..15af8e54b8 --- /dev/null +++ b/Task/Square-but-not-cube/8080-Assembly/square-but-not-cube.8080 @@ -0,0 +1,91 @@ + org 100h + mvi b,30 ; Counter + push b +loop: lhld curcub ; DE = current cube + xchg + lhld cursqr ; HL = current square + call cdehl + jc advcub ; DE < HL, next cube + jz advsqr ; DE = HL, both square and cube + call prhl ; HL = square but not cube, print it + pop b ; Get counter + dcr b ; Decrease counter + rz ; Stop when zero reached + push b ; Push counter back +advsqr: call nexsqr ; Next square + jmp loop +advcub: call nexcub ; Next cube + jmp loop + + ; compare DE to HL +cdehl: mov a,d + cmp h + rnz + mov a,e + cmp l + ret + + ; Get next square (starting with 1) +nexsqr: lhld sqdiff ; DE = current difference + xchg + lhld cursqr ; HL = current square + dad d ; Add difference to square + inx d ; Increment difference twice + inx d + shld cursqr ; Update current square + xchg + shld sqdiff ; Update current difference + ret +cursqr: dw 0 ; Current square +sqdiff: dw 1 ; Difference to next squre + + ; Get next cube (starting with 1) +nexcub: lhld csumst ; DE = start of current sum + xchg + lxi h,0 ; HL = current cube + lda csumn ; A = amount of numbers to sum +csumlp: dad d ; Add to current cube + inx d ; Next odd number + inx d + dcr a ; Until done summing + jnz csumlp + shld curcub ; Store next sum + xchg + shld csumst ; Store start of next sum + lxi h,csumn ; Increment sum counter + inr m + ret +curcub: dw 0 ; Current cube +csumst: dw 1 ; Start of current sum +csumn: db 1 ; Amount of numbers to sum + + ; Print HL as a decimal value +prhl: push h ; Store registers + push d + push b + lxi b,pnum ; Store pointer to buffer on stack + push b + lxi b,-10 ; Divide by 10 using trial subtraction +prdgt: lxi d,-1 ; D = +prdgtl: inx d + dad b + jc prdgtl + mvi a,'0'+10 ; ASCII digit + 10 + add l ; L = remainder - 10 + pop h ; Get pointer to buffer + dcx h ; Go back one digit + mov m,a ; Store digit + push h ; Store pointer to buffer + xchg ; HL = n/10 + mov a,h ; Zero? + ora l + jnz prdgt ; If not, get more digits + mvi c,9 ; 9 = CP/M print string + pop d ; DE = buffer + call 5 + pop b ; Restore registers + pop d + pop h + ret + db '*****' ; Number placeholder +pnum: db 13,10,'$' diff --git a/Task/Square-but-not-cube/ABC/square-but-not-cube.abc b/Task/Square-but-not-cube/ABC/square-but-not-cube.abc new file mode 100644 index 0000000000..e3035390d2 --- /dev/null +++ b/Task/Square-but-not-cube/ABC/square-but-not-cube.abc @@ -0,0 +1,11 @@ +PUT 1 IN square.root +PUT 1 IN cube.root +PUT 30 IN amount + +WHILE amount > 0: + WHILE square.root ** 2 > cube.root ** 3: + PUT cube.root + 1 IN cube.root + IF square.root ** 2 <> cube.root ** 3: + WRITE square.root ** 2/ + PUT amount - 1 IN amount + PUT square.root + 1 IN square.root diff --git a/Task/Square-but-not-cube/MACRO-11/square-but-not-cube.macro11 b/Task/Square-but-not-cube/MACRO-11/square-but-not-cube.macro11 new file mode 100644 index 0000000000..2211e1072c --- /dev/null +++ b/Task/Square-but-not-cube/MACRO-11/square-but-not-cube.macro11 @@ -0,0 +1,53 @@ + .TITLE SQRCUB + .MCALL .TTYOUT,.EXIT + +SQRCUB::MOV #^D30,R5 + JSR PC,NEXCUB +1$: JSR PC,NEXSQR +2$: CMP R4,R3 + BLT 3$ + BEQ 1$ + MOV R3,R0 + JSR PC,PR0 + SOB R5,1$ + .EXIT +3$: JSR PC,NEXCUB + BR 2$ + + ; PUT SUCCESSIVE SQUARES IN R3 +NEXSQR: MOV 1$,R3 + ADD 2$,R3 + MOV R3,1$ + ADD #2,2$ + RTS PC +1$: .WORD 0 +2$: .WORD 1 + + ; PUT SUCCESSIVE CUBES IN R4 +NEXCUB: CLR R4 + MOV 3$,R1 +1$: ADD 2$,R4 + ADD #2,2$ + SOB R1,1$ + INC 3$ + RTS PC +2$: .WORD 1 +3$: .WORD 1 + + ; PRINT R0 AS DECIMAL WITH NEWLINE +PR0: MOV #4$,R2 +1$: MOV #-1,R1 +2$: INC R1 + SUB #12,R0 + BCC 2$ + ADD #72,R0 + MOVB R0,-(R2) + MOV R1,R0 + BNE 1$ +3$: MOVB (R2)+,R0 + .TTYOUT + BNE 3$ + RTS PC + .BLKB 5 +4$: .BYTE 15,12,0 + .END SQRCUB diff --git a/Task/Square-but-not-cube/Refal/square-but-not-cube.refal b/Task/Square-but-not-cube/Refal/square-but-not-cube.refal new file mode 100644 index 0000000000..0579e28990 --- /dev/null +++ b/Task/Square-but-not-cube/Refal/square-but-not-cube.refal @@ -0,0 +1,21 @@ +$ENTRY Go { + = >; +}; + +SquareCube { + s.Max = ; + 0 s.Sqrt s.Cbrt = ; + + s.Max s.Sqrt s.Cbrt, + : s.Square, + : s.Cube, + : { + '-' = s.Square + <+ 1 s.Sqrt> s.Cbrt>; + '0' = s.Cbrt>; + '+' = >; + }; +}; + +Square { s.N = <* s.N s.N>; }; +Cube { s.N = <* s.N <* s.N s.N>>; }; diff --git a/Task/Square-free-integers/Uiua/square-free-integers.uiua b/Task/Square-free-integers/Uiua/square-free-integers.uiua new file mode 100644 index 0000000000..fdf5d9ec43 --- /dev/null +++ b/Task/Square-free-integers/Uiua/square-free-integers.uiua @@ -0,0 +1,6 @@ +Sqf ← ≠0/↧◿⊸(×.↘2⇡+1⌊√) +⟜⧻▽⊸≡Sqf +1⇡145 +⟜⧻▽⊸≡Sqf +1e12+1⇡145 +# Find all squares and their multiples, and mask them out. +▽:⇡⟜(¬±°⊚/◇⊂≡(□×⇡+1)⌊÷:⟜(.×.↘2⇡√.))1000000 +⊙◌≡(/+<)⇌[⍥(×10.)4 100]¤ diff --git a/Task/Stack-traces/PascalABC.NET/stack-traces.pas b/Task/Stack-traces/PascalABC.NET/stack-traces.pas new file mode 100644 index 0000000000..e43d36da47 --- /dev/null +++ b/Task/Stack-traces/PascalABC.NET/stack-traces.pas @@ -0,0 +1,14 @@ +procedure qqq; +begin + var st := new System.Diagnostics.StackTrace(); + Print(st); +end; + +procedure ppp; +begin + qqq; +end; + +begin + ppp +end. diff --git a/Task/Stack/PascalABC.NET/stack.pas b/Task/Stack/PascalABC.NET/stack.pas new file mode 100644 index 0000000000..d006c63f48 --- /dev/null +++ b/Task/Stack/PascalABC.NET/stack.pas @@ -0,0 +1,11 @@ +begin + var st := new Stack; + var st1 := new Stack; + st.Push(1); + st.Push(2); + st.Push(3); + Println(st1,st); + while st.Count <> 0 do + st1.Push(st.Pop); + Println(st1,st); +end. diff --git a/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy new file mode 100644 index 0000000000..7f6a07a051 --- /dev/null +++ b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy @@ -0,0 +1,15 @@ +func step . + if randint 2 = 2 + print "climbed up" + return 1 + else + print "fell down" + return 0 + . +. +proc step_up . . + while step = 0 + step_up + . +. +step_up diff --git a/Task/Steffensens-method/Phix/steffensens-method.phix b/Task/Steffensens-method/Phix/steffensens-method.phix index f551ce91ba..e328994710 100644 --- a/Task/Steffensens-method/Phix/steffensens-method.phix +++ b/Task/Steffensens-method/Phix/steffensens-method.phix @@ -1,62 +1,60 @@ -(phixonline)--> - with javascript_semantics - function aitken(integer f, atom p0) - atom p1 = f(p0), - p2 = f(p1), - p1m0 = p1 - p0 - return p0 - (p1m0 * p1m0) / (p2 - (2 * p1) + p0) - end function +with javascript_semantics +function aitken(integer f, atom p0) + atom p1 = f(p0), + p2 = f(p1), + p1m0 = p1 - p0 + return p0 - (p1m0 * p1m0) / (p2 - (2 * p1) + p0) +end function - function steffensenAitken(integer f, maxiter, atom pinit, tol) - atom p0 = pinit, p = aitken(f, p0) - integer iter = 1 - while abs(p-p0)>tol and iter<maxiter do - p0 = p - p = aitken(f, p0) - iter += 1 - end while - return iff(abs(p-p0)>tol?"none":p) - end function +function steffensenAitken(integer f, maxiter, atom pinit, tol) + atom p0 = pinit, p = aitken(f, p0) + integer iter = 1 + while abs(p-p0)>tol and itertol?"none":p) +end function - function deCasteljau(atom c0, c1, c2, t) - atom s = 1 - t, - c01 = (s * c0) + (t * c1), - c12 = (s * c1) + (t * c2), - c012 = (s * c01) + (t * c12) - return c012 - end function +function deCasteljau(atom c0, c1, c2, t) + atom s = 1 - t, + c01 = (s * c0) + (t * c1), + c12 = (s * c1) + (t * c2), + c012 = (s * c01) + (t * c12) + return c012 +end function - function xConvexLeftParabola(atom t) - return deCasteljau(2, -8, 2, t) - end function +function xConvexLeftParabola(atom t) + return deCasteljau(2, -8, 2, t) +end function - function yConvexLeftParabola(atom t) - return deCasteljau(1, 2, 3, t) - end function +function yConvexLeftParabola(atom t) + return deCasteljau(1, 2, 3, t) +end function - function implicitEquation(atom x, y) - return (5 * x * x) + y - 5 - end function +function implicitEquation(atom x, y) + return (5 * x * x) + y - 5 +end function - function f(atom t) - atom x = xConvexLeftParabola(t), - y = yConvexLeftParabola(t) - return implicitEquation(x, y) + t - end function +function f(atom t) + atom x = xConvexLeftParabola(t), + y = yConvexLeftParabola(t) + return implicitEquation(x, y) + t +end function - for i=0 to 10 do - printf(1,"t0 = %.1f : ",i/10) - object t = steffensenAitken(f, 1000, i/10, 0.00000001) - if string(t) then - printf(1,"no answer\n") - else - atom x = xConvexLeftParabola(t), - y = yConvexLeftParabola(t) - if abs(implicitEquation(x, y)) <= 0.000001 then - printf(1,"intersection at (%.6f, %.6f)\n",{x,y}) - else - printf(1,"spurious solution\n") - end if - end if - end for - - string size = "little" - string s = sprintf("Mary had a %s lamb.",{size}) - ?s -cell for -? -->cell for -? -->cell for -? - x w s -) - -while=: conjunction def 'u ^: v ^:_' NB. j assumes while is a verb and needs to know while is a conjunction. - -ttt=: outcome@:((display@:move) while undecided)@:display@:prepare - -blindfolded_variant=: outcome@:display@:(move while undecided)@:display@:prepare - -outcome=: {&(>;:'kitty VICTORY')@:won NB. (outcome does not pass along the state) -move=: post locate -undecided=: won nor full -prepare=: , board@:] NB. form the state vector - -Note 'locate' - is a monadic verb. y is the state vector. - returns the character of the chosen cell. - Generally: - locate=: second_strategy`first_strategy@.(first = mark) - Simplified: - locate=: human_locate NB. human versus human -) -locate=: human_locate`computer_locate@.(first = mark) - -display=: show [: (1 1,:5 5)&(];.0)@:": [: <"0 fold - -computer_locate=: [: show@{. board -. marks NB. strategy: first available -computer_locate=: [: show@({~ ?@:#) board -. marks NB. strategy: random - -human_locate=: monad define - state=. y - m=. mark state - b=. board state - cells=. b -. marks state - show '-->cell for ' , m , '?' - whilst. cell -.@:e. cells do. cell =. {. (1!:1]1) , m end. -) - -post=: 2&A.@:(3&{.)@:[ prepare mark@:[`((i.~ board)~)`(board@:[)} - -mark=: {. NB. mark of the current player from state -marks=: 2&{. NB. extract both markers from state -board=: _9&{. NB. extract board from state -first=: 2&{ NB. extract first player from state - -show=: [ smoutput - -full=: 2 = #@:~. -won=: test@:fold -fold=: 3 3 $ board -test=: [: any [: all [: infix_pairs_agree |:@:lines - -lines=: , diagonal , diagonal@:|. , |: -diagonal=: (<0 1)&|: -all=: *./ -any=: +./ -nor=: 8 b. -infix_pairs_agree=: 2&(=/\) + '`turn board open full'=: {.`}.`(0=[{board@])`(0-.@e.board) + '`cpu_move position'=: (?@#{])@([:I.0=board)`(cpu_move`you_move@.(_1 1 i.turn)) + you_move=: $:@echo@'invalid'^:(-.@e.i.@9)@:<:@".@{.@;:@(1!:1@1) + move=: position (][echo@'already taken!')`(-@turn@] , turn@]`[`(board@])})@.open ] + show=: [ [: echo@''@echo (,' '&,)/"1@({&'.XO')@(3 3$board) [ echo@'' + won=: [: +./ (3=[:|+/)"1@(], |:, (<@i.@#|:]),: <@i.@#|:|.)@(3 3$board) + prompt=: echo@:>:@i.@3 3@echo@'enter a move (1–9) each turn; you''re X''s' + outcome=: (echo@'tie')`(' wins'echo@,~{&'.XO'@-@turn)@.won + ttt=: outcome@([F.(show@move[_2:Z:won+.full))@(10{._1)@prompt diff --git a/Task/Tic-tac-toe/Jq/tic-tac-toe.jq b/Task/Tic-tac-toe/Jq/tic-tac-toe.jq new file mode 100644 index 0000000000..b6c396dc78 --- /dev/null +++ b/Task/Tic-tac-toe/Jq/tic-tac-toe.jq @@ -0,0 +1,151 @@ +include "MRG32k3a" {search: "."}; # see comment above + +### Generic functions + +def inform(msg): + . as $in + | msg + "\n" | stderr + | $in; + +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +# Create an m x n matrix with initial values specified by . +def matrix($m; $n): + if $m == 0 then [] + else . as $init + | if $m == 1 then [range(0;$n) | $init] + elif $m > 0 then + matrix(1; $n) as $row + | [range(0; $m) | $row ] + else error("matrix\($m);\($n)) invalid") + end + end; + + +### Tic-Tac-Toe + +# The board is represented by a matrix in which: +# 0 : blank; -1: computer; 1: user +def init: + {b: (0 | matrix(3;3)), + bestI: 0, + bestJ: 0, + prng: seed(now | tostring | sub("^.*[.]";"") | tonumber)}; + +# Output: 0 if undecided, null if game over, otherwise the player id +def checkWinner: + first(range(0; 3) as $i + | if .b[$i][0] != 0 and .b[$i][1] == .b[$i][0] and .b[$i][2] == .b[$i][0] then .b[$i][0] + elif .b[0][$i] != 0 and .b[1][$i] == .b[0][$i] and .b[2][$i] == .b[0][$i] then .b[0][$i] + else empty + end) + // if (.b[1][1] == 0) then 0 + elif (.b[1][1] == .b[0][0] and .b[2][2] == .b[0][0]) then .b[0][0] + elif (.b[1][1] == .b[2][0] and .b[0][2] == .b[1][1]) then .b[1][1] + elif all(.b[][]; . != 0) then null + else 0 + end ; + +def showBoard: + ["X", " ", "O"] as $t + | .b as $b + | range(0;3) as $i + | reduce range(0;3) as $j (""; + . + "\($t[$b[$i][$j] + 1]) " ), # b == -1 => "X"; b == 1 => "O" + "-----"; + +# Examine possible moves of the player identified by $value, avoiding embarrassment +# Set .result, .bestI, .bestJ, etc +def testMove($value; $depth): + checkWinner as $score + | if $score == null then .result = 0 + elif $score != 0 + then .result = (if $score == $value then 1 else -1 end) + else .best = -1 + | .changed = 0 + | reduce range(0;3) as $i (.; + reduce range(0;3) as $j (.; + if .b[$i][$j] == 0 + then .b[$i][$j] = $value + | .changed = $value + | testMove(-$value; $depth + 1) as $test + | (-$test.result) as $score + | .b[$i][$j] = 0 + | if $score > .best + then if $depth == 0 + then .bestI = $i + | .bestJ = $j + end + | .best = $score + end + end ) ) + | .result = if .changed != 0 then .best else 0 end + end; + +# Issue prompts on stderr; +# always allow q for quit +def read($prompt; $regex): + def r: + ($prompt | stderr | empty), + (try ((input + | if . == "q" then halt + else select(test($regex)) + end) // r) + catch if . == "break" then halt else r end ); + r; + +# Input: irrelevant +# $user should be boolean; specify `true` if the user plays first +def game($user): + "Board positions are numbered so:\n1 2 3\n4 5 6\n7 8 9", + "You have O, I have X.\n", + (init + {$user} + | label $out + | foreach range(0;9) as $k (.; + if .user + then .move = null + | until(.move; + (read("Your move: "; "^ *[1-9]") | tonumber - 1) as $move + | ($move/3|floor) as $i + | ($move % 3) as $j + | if .b[$i][$j] == 0 + then .b[$i][$j] = 1 + | .move = $move + end ) + end + | if (.user|not) + then # in the interests of entertainment, randomize if computer opens + if $k == 0 + then .prng |= nextFloat + | .bestI = (.prng.nextFloat * 100 | trunc) % 3 + | .prng |= nextFloat + | .bestJ = (.prng.nextFloat * 100 | trunc) % 3 + else testMove(-1; 0) + end + | .b[.bestI][.bestJ] = -1 + | inform("My move: \(.bestI * 3 + .bestJ + 1)") + end + | .user |= not + ; + # Output: + showBoard, + (checkWinner + | if . == 0 then empty + else (if . == 1 then "You win" + elif . == -1 then "I win" + else "A draw.\n\n" + end), + break $out + end ) )) ; + +# Alternate players +def controller: + def c($user): + game($user), + (read("Play again? [yn]: "; "^[yYnN]") as $in + | if $in|.[0:1]|ascii_downcase == "n" then halt + else c($user|not) + end); + c(true); + +controller diff --git a/Task/Time-a-function/PascalABC.NET/time-a-function.pas b/Task/Time-a-function/PascalABC.NET/time-a-function.pas new file mode 100644 index 0000000000..ebbe256cad --- /dev/null +++ b/Task/Time-a-function/PascalABC.NET/time-a-function.pas @@ -0,0 +1,14 @@ +function LongTimeCalc(n: integer): real; +begin + var sum := 0.0; + for var i:=1 to n do + for var j := 1 to n do + sum += 1/i/j; + Result := sum; +end; + +begin + MillisecondsDelta; + LongTimeCalc(10000).Println; + MillisecondsDelta.Println; +end. diff --git a/Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy b/Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy new file mode 100644 index 0000000000..99f46e1de6 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/EasyLang/tokenize-a-string-with-escaping.easy @@ -0,0 +1,20 @@ +func$[] tokenize src$ sep$ esc$ . + r$[] = [ "" ] + for i = 1 to len src$ + c$ = substr src$ i 1 + if esc = 1 + r$[$] &= c$ + esc = 0 + else + if c$ = sep$ + r$[] &= "" + elif c$ = esc$ + esc = 1 + else + r$[$] &= c$ + . + . + . + return r$[] +. +print tokenize "one^|uno||three^^^^|four^^^|^cuatro|" "|" "^" diff --git a/Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas b/Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas new file mode 100644 index 0000000000..2f40bf497d --- /dev/null +++ b/Task/Tokenize-a-string/PascalABC.NET/tokenize-a-string.pas @@ -0,0 +1,5 @@ +begin + var s := 'Hello,How,Are,You,Today'; + var strings := s.Split(','); + Print(strings.JoinToString('.')); +end. diff --git a/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy b/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy new file mode 100644 index 0000000000..9a39f89571 --- /dev/null +++ b/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy @@ -0,0 +1,58 @@ +global na$[] id$[] sal[] dep$[] n . +# +proc read . . + s$ = input + repeat + s$ = input + until s$ = "" + a$[] = strsplit s$ "," + na$[] &= a$[1] + id$[] &= a$[2] + sal[] &= number a$[3] + dep$[] &= a$[4] + . + n = len na$[] +. +read +# +proc sort . . + for i = 1 to n - 1 + for j = i + 1 to n + h = strcmp dep$[i] dep$[j] + if h > 0 or h = 0 and sal[i] < sal[j] + swap na$[i] na$[j] + swap id$[i] id$[j] + swap sal[i] sal[j] + swap dep$[i] dep$[j] + . + . + . +. +sort +# +for i to n + if i > 1 and dep$[i] <> dep$[i - 1] + cnt = 0 + print "" + . + if cnt < 2 + print dep$[i] & " " & sal[i] & " " & na$[i] + cnt += 1 + . +. +# +input_data +Employee Name,Employee ID,Salary,Department +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190 diff --git a/Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas b/Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas new file mode 100644 index 0000000000..e717892e08 --- /dev/null +++ b/Task/Top-rank-per-group/PascalABC.NET/top-rank-per-group.pas @@ -0,0 +1,25 @@ +begin + var data := |('Tyler Bennett', 'E10297', 32000, 'D101'), + ('John Rappl', 'E21437', 47000, 'D050'), + ('George Woltman', 'E00127', 53500, 'D101'), + ('Adam Smith', 'E63535', 18000, 'D202'), + ('Claire Buckman', 'E39876', 27800, 'D202'), + ('David McClellan', 'E04242', 41500, 'D101'), + ('Rich Holcomb', 'E01234', 49500, 'D202'), + ('Nathan Adams', 'E41298', 21900, 'D050'), + ('Richard Potter', 'E43128', 15900, 'D101'), + ('David Motsinger', 'E27002', 19250, 'D202'), + ('Tim Sampair', 'E03033', 27000, 'D101'), + ('Kim Arlich', 'E10001', 57000, 'D190'), + ('Timothy Grove', 'E16398', 29900, 'D190')|; + + var N := 3; + foreach var group in data.GroupBy(rec -> rec[3]).OrderBy(gr -> gr.Key) do + begin + Println('Department',group.Key); + Println($' Employee Name Employee ID Salary'); + foreach var rec in group.OrderByDescending(x -> x[2]).Take(3) do + Println($' {rec[0],-18} {rec[1],-14} {rec[2]}'); + Println; + end; +end. diff --git a/Task/Topic-variable/Java/topic-variable.java b/Task/Topic-variable/Java/topic-variable.java new file mode 100644 index 0000000000..ddd2465093 --- /dev/null +++ b/Task/Topic-variable/Java/topic-variable.java @@ -0,0 +1,42 @@ +import java.awt.Point; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; + +public final class TopicVariable { + + public static void main(String[] args) { + List numbers = List.of( 1, 2, 3, 4, 5, 6, 7, 8, 9 ); + // Example 1: + // We only want to count the number of elements in a list, + // so a topic variable can be used for the identify of each element of the list. + // An artificial example since we could just use 'total = numbers.size()'. + int total = 0; + for ( Integer _ : numbers ) { // Topic variable + total += 1; + } + System.out.println("The list contains " + total + " numbers"); + + // Example 2: + // A topic variable is suitable for the unused identifier of the NumberFormatException. + String text = "123456:@~"; + int i = 0; + try { + i = Integer.parseInt(text); + } catch(NumberFormatException _) { // Topic variable + System.out.println("Variable i is incorrectly defined with value: " + i); + } + + // Example 3: + // We only require the first two out of every three items in a queue. + // A topic variable can be used for the third unused item. + Queue queue = new ArrayDeque(numbers); + while ( queue.size() >= 3 ) { + int x = queue.poll(); + int y = queue.poll(); + int _ = queue.poll(); // Topic variable + System.out.println( new Point(x, y) ); + } + } + +} diff --git a/Task/Towers-of-Hanoi/11l/towers-of-hanoi.11l b/Task/Towers-of-Hanoi/11l/towers-of-hanoi.11l index b49ca4c909..39a07d4627 100644 --- a/Task/Towers-of-Hanoi/11l/towers-of-hanoi.11l +++ b/Task/Towers-of-Hanoi/11l/towers-of-hanoi.11l @@ -1,4 +1,4 @@ -F hanoi(ndisks, startPeg = 1, endPeg = 3) -> N +F hanoi(ndisks, startPeg = 1, endPeg = 3) -> Void I ndisks hanoi(ndisks - 1, startPeg, 6 - startPeg - endPeg) print(‘Move disk #. from peg #. to peg #.’.format(ndisks, startPeg, endPeg)) diff --git a/Task/Towers-of-Hanoi/Asymptote/towers-of-hanoi.asymptote b/Task/Towers-of-Hanoi/Asymptote/towers-of-hanoi.asymptote new file mode 100644 index 0000000000..b08a7c6dbb --- /dev/null +++ b/Task/Towers-of-Hanoi/Asymptote/towers-of-hanoi.asymptote @@ -0,0 +1,12 @@ +void hanoi(int n, string origen, string auxiliar, string destino) { + if (n == 1) { + write("Move disk 1 from " + origen + " to " + destino); + } else { + hanoi(n - 1, origen, destino, auxiliar); + write("Move disk " + string(n) + " from " + origen + " to " + destino); + hanoi(n - 1, auxiliar, origen, destino); + } +} + +hanoi(3, "pole 1", "pole 2", "pole 3"); +write("Towers of Hanoi puzzle completed!"); diff --git a/Task/Towers-of-Hanoi/Bruijn/towers-of-hanoi.bruijn b/Task/Towers-of-Hanoi/Bruijn/towers-of-hanoi.bruijn new file mode 100644 index 0000000000..afebb12485 --- /dev/null +++ b/Task/Towers-of-Hanoi/Bruijn/towers-of-hanoi.bruijn @@ -0,0 +1,10 @@ +:import std/Combinator . +:import std/Number . +:import std/String . + +hanoi y [[[[=?2 empty go]]]] + go [(4 --3 2 0) ++ str ++ (4 --3 0 1)] ((+6) - 1 - 0) + str "Move " ++ disk ++ " from " ++ source ++ " to " ++ destination ++ "\n" + disk number→string 3 + source number→string 2 + destination number→string 1 diff --git a/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js index 49e482c77c..6ac3a344ab 100644 --- a/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js +++ b/Task/Towers-of-Hanoi/JavaScript/towers-of-hanoi-4.js @@ -9,18 +9,18 @@ (a, b, c) => { const go = hanoi(n - 1); - return Boolean(n) ? [ - ...go(a, c, b), - ...[ - [a, b] - ], - ...go(c, b, a) - ] : []; + return n + ? [ + ...go(a, c, b), + [a, b], + ...go(c, b, a) + ] + : []; }; // ---------------------- TEST ----------------------- return hanoi(3)("left", "right", "mid") - .map(d => `${d[0]} -> ${d[1]}`) - .join("\n"); + .map(d => `${d[0]} -> ${d[1]}`) + .join("\n"); })(); diff --git a/Task/Towers-of-Hanoi/PascalABC.NET/towers-of-hanoi.pas b/Task/Towers-of-Hanoi/PascalABC.NET/towers-of-hanoi.pas new file mode 100644 index 0000000000..b1b19ee5d4 --- /dev/null +++ b/Task/Towers-of-Hanoi/PascalABC.NET/towers-of-hanoi.pas @@ -0,0 +1,9 @@ +## procedure Hanoi(n,rfrom,rto,rwork: integer); +begin + if n = 0 then + exit; + Hanoi(n-1,rfrom,rwork,rto); + Print($'{rfrom}→{rto} '); + Hanoi(n-1,rwork,rto,rfrom); +end; +Hanoi(5,1,3,2); diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PascalABC.NET/trabb-pardo-knuth-algorithm.pas b/Task/Trabb-Pardo-Knuth-algorithm/PascalABC.NET/trabb-pardo-knuth-algorithm.pas new file mode 100644 index 0000000000..de14726133 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PascalABC.NET/trabb-pardo-knuth-algorithm.pas @@ -0,0 +1,10 @@ +function f(x:real) := Sqrt(x) + 5 *x ** 3; + +begin + var seq := ReadArrInteger(11).Reverse; + foreach var x in seq do + begin + var fx := f(x); + Println($'f({x}): {fx > 400 ? ''overflow'' : fx.ToString}'); + end; +end. diff --git a/Task/Trabb-Pardo-Knuth-algorithm/UNIX-Shell/trabb-pardo-knuth-algorithm.sh b/Task/Trabb-Pardo-Knuth-algorithm/UNIX-Shell/trabb-pardo-knuth-algorithm.sh new file mode 100644 index 0000000000..2edba48216 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/UNIX-Shell/trabb-pardo-knuth-algorithm.sh @@ -0,0 +1,18 @@ +fn f { + printf 'scale=3; sqrt(sqrt(%s^2)) + 5.0 * %s ^ 3 \n' $1 $1 | bc +} + +count = 11 +list = () +for (idx in `{seq $count}) { + num = `{read} # get value from stdin + list = ($num $list) # add to list in reverse +} +for (idx in `{seq $count}) { + x = $list($idx) + printf 'f(%s) = ' $x + y = `{f $x} + if (~ `{printf '%s > 400 \n' $y | bc} 1) + echo TOO LARGE! + if not echo $y +} diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/PascalABC.NET/transliterate-english-text-using-the-greek-alphabet.pas b/Task/Transliterate-English-text-using-the-Greek-alphabet/PascalABC.NET/transliterate-english-text-using-the-greek-alphabet.pas new file mode 100644 index 0000000000..b2e05df688 --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/PascalABC.NET/transliterate-english-text-using-the-greek-alphabet.pas @@ -0,0 +1,37 @@ +var repl := Dict( + ('ch', 'χ'), ('th', 'θ'), ('ps', 'ψ'), ('ph', 'f'), ('Ch', 'Χ'), + ('Th', 'Θ'), ('Ps', 'Ψ'), ('Ph', 'F'), ('ee', 'h'), ('ck', 'κ'), ('rh', 'r'), ('kh', 'χ'), + ('Kh', 'Χ'), ('oo', 'w'), + ($'a', 'α'), ($'b', 'β'), ($'c', 'κ'), ($'d', 'δ'), ($'e', 'ε'), + ($'f', 'φ'), ($'g', 'γ'), ($'h', 'η'), ($'i', 'ι'), ($'j', 'ι'), ($'k', 'κ'), ($'l', 'λ'), + ($'m', 'μ'), ($'n', 'ν'), ($'o', 'ο'), ($'p', 'π'), ($'q', 'κ'), ($'r', 'ρ'), ($'s', 'σ'), + ($'t', 'τ'), ($'u', 'υ'), ($'v', 'β'), ($'w', 'ω'), ($'x', 'ξ'), ($'y', 'υ'), ($'z', 'ζ'), + ($'D', 'Δ'), ($'F', 'Φ'), ($'G', 'Γ'), ($'J', 'I'), ($'L', 'Λ'), ($'P', 'Π'), ($'Q', 'Κ'), + ($'R', 'Ρ'), ($'S', 'Σ'), ($'Y', 'U'), ($'W', 'Ω'), ($'X', 'Ξ') +); + +var texts := Arr( + 'The quick brown fox jumped over the lazy dog.', + + ''' + I was looking at some rhododendrons in my back garden, + dressed in my khaki shorts, when the telephone rang. + + As I answered it, I cheerfully glimpsed that the July sun + caused a fragment of black pine wax to ooze on the velvet quilt + laying in my patio. + ''', + + 'sphinx of black quartz, judge my vow.' +); + +begin + foreach var txt in texts do + begin + Println(txt); Println('=>'); + var txt1 := txt; + foreach var pair in repl do + txt1 := txt1.Replace(pair.Key,pair.Value); + Println(txt1 + NewLine); + end; +end. diff --git a/Task/Tree-datastructures/11l/tree-datastructures.11l b/Task/Tree-datastructures/11l/tree-datastructures.11l index 7c2c8d2cff..ef681a86d3 100644 --- a/Task/Tree-datastructures/11l/tree-datastructures.11l +++ b/Task/Tree-datastructures/11l/tree-datastructures.11l @@ -17,16 +17,11 @@ T NNode F String() R .to_str(0) -T INode - String value - Int level - F (value, level) - .value = value - .level = level +T INode = (String value, Int level) F to_indented(node) [INode] result - F add_node(NNode node, Int level) -> N + F add_node(NNode node, Int level) -> Void @result.append(INode(node.value, level)) L(child) node.children @add_node(child, level + 1) diff --git a/Task/Tree-datastructures/PascalABC.NET/tree-datastructures.pas b/Task/Tree-datastructures/PascalABC.NET/tree-datastructures.pas new file mode 100644 index 0000000000..66b73fe890 --- /dev/null +++ b/Task/Tree-datastructures/PascalABC.NET/tree-datastructures.pas @@ -0,0 +1,41 @@ +{$zerobasedstrings} +function NestedToIndented(nested: string): string; +begin + var lst := new List; + foreach var line in Regex.Split(nested,NewLine) do + begin + var ind := Regex.Match(line,'[^\.]').Index; + lst.Add($'{ind div 4} {line[ind:]}'); + end; + Result := lst.JoinToString(NewLine); +end; + +function IndentedToNested(indented: string): string; +begin + var lst := new List; + foreach var line in Regex.Split(indented,NewLine) do + begin + var ind := line.IndexOf(' '); + var level := line[:ind].ToInteger; + lst.Add((level*4) * '.' + line[ind+1:]); + end; + Result := lst.JoinToString(NewLine); +end; + +begin + var initialNested := ''' + Rosetta Code + ....rocks + ........code + ........comparison + ........wiki + ....mocks + ........trolling + '''; + Writeln(initialNested,NewLine); + var indented := NestedToIndented(initialNested); + Writeln(indented,NewLine); + var nested := IndentedToNested(indented); + Writeln(nested,NewLine); + Writeln($'Initial = Restored: {initialNested = nested}'); +end. diff --git a/Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs b/Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs new file mode 100644 index 0000000000..c6e586132d --- /dev/null +++ b/Task/Tree-from-nesting-levels/C-sharp/tree-from-nesting-levels.cs @@ -0,0 +1,70 @@ +public static class TreeFromNestingLevels +{ + public static void Main() + { + List tests = [[], [1,2,4], [3,1,3,1], [1,2,3,1], [3,2,1,3], [3,3,3,1,1,3,3,3]]; + Console.WriteLine($"{"Input",24} -> {"Nested",-32} -> Round-trip"); + foreach (var test in tests) { + var tree = BuildTree(test); + string input = $"[{string.Join(", ", test)}]"; + string roundTrip = $"[{string.Join(", ", tree.ToList())}]"; + Console.WriteLine($"{input,24} -> {tree,-32} -> {roundTrip}"); + } + } + + private static Tree BuildTree(int[] levels) + { + Tree root = new(0); + Tree current = root; + foreach (int level in levels) { + while (current.Level > level) current = current.Parent; + current = current.Parent.Add(level); + } + return root; + } + + private class Tree + { + public int Level { get; } + public Tree Parent { get; } + private readonly List children = []; + + public Tree(int level, Tree? parent = null) + { + Level = level; + Parent = parent ?? this; + } + + public Tree Add(int level) + { + if (Level == level) return this; + Tree tree = new(Level + 1, this); + children.Add(tree); + return tree.Add(level); + } + + public override string ToString() => children.Count == 0 + ? (Level == 0 ? "[]" : $"{Level}") + : $"[{string.Join(", ", children.Select(c => c.ToString()))}]"; + + public List ToList() + { + List list = []; + ToList(this, list); + return list; + } + + private static void ToList(Tree tree, List list) + { + if (tree.children.Count == 0) { + if (tree.Level > 0) list.Add(tree.Level); + } else { + foreach (Tree child in tree.children) { + ToList(child, list); + } + } + } + + } + +} diff --git a/Task/Tree-traversal/11l/tree-traversal.11l b/Task/Tree-traversal/11l/tree-traversal.11l index 2a278b81b8..d4cb66b021 100644 --- a/Task/Tree-traversal/11l/tree-traversal.11l +++ b/Task/Tree-traversal/11l/tree-traversal.11l @@ -8,28 +8,28 @@ T Node .left = left .right = right - F preorder(visitor) -> N + F preorder(visitor) -> Void visitor(.data) I .left != N .left.preorder(visitor) I .right != N .right.preorder(visitor) - F inorder(visitor) -> N + F inorder(visitor) -> Void I .left != N .left.inorder(visitor) visitor(.data) I .right != N .right.inorder(visitor) - F postorder(visitor) -> N + F postorder(visitor) -> Void I .left != N .left.postorder(visitor) I .right != N .right.postorder(visitor) visitor(.data) - F preorder2(&d, level = 0) -> N + F preorder2(&d, level = 0) -> Void d[level].append(.data) I .left != N .left.preorder2(d, level + 1) diff --git a/Task/Tree-traversal/EMal/tree-traversal.emal b/Task/Tree-traversal/EMal/tree-traversal.emal new file mode 100644 index 0000000000..b9445a4632 --- /dev/null +++ b/Task/Tree-traversal/EMal/tree-traversal.emal @@ -0,0 +1,63 @@ +type Node +model + :T value + Node left + Node right + new by generic T, :T ←value do end + fun visit ← <|write(me.value + " ") +end +type Order +enum + int PREORDER, INORDER, POSTORDER, LEVELORDER +end +type Main +fun traverse ← void by Node node, Order order + if node æ null do return end + if order æ Order.PREORDER + node.visit() + traverse(node.left, order) + traverse(node.right, order) + else if order æ Order.INORDER + traverse(node.left, order) + node.visit() + traverse(node.right, order) + else if order æ Order.POSTORDER + traverse(node.left, order) + traverse(node.right, order) + node.visit() + else if order æ Order.LEVELORDER + List queue ← Node[] + queue.insertFirst(node) + while not queue.isEmpty() + Node next ← queue.deleteLast() + next.visit() + if next.left ≠ null do queue.insertFirst(next.left) end + if next.right ≠ null do queue.insertFirst(next.right) end + end + end +end +Node one ← Node(int, 1) +Node two ← Node(int, 2) +Node three ← Node(int, 3) +Node four ← Node(int, 4) +Node five ← Node(int, 5) +Node six ← Node(int, 6) +Node seven ← Node(int, 7) +Node eight ← Node(int, 8) +Node nine ← Node(int, 9) +one.left ← two +one.right ← three +two.left ← four +two.right ← five +three.left ← six +four.left ← seven +six.left ← eight +six.right ← nine +traverse(one, Order.PREORDER) +writeLine() +traverse(one, Order.INORDER) +writeLine() +traverse(one, Order.POSTORDER) +writeLine() +traverse(one, Order.LEVELORDER) +writeLine() diff --git a/Task/Tree-traversal/PascalABC.NET/tree-traversal.pas b/Task/Tree-traversal/PascalABC.NET/tree-traversal.pas new file mode 100644 index 0000000000..caf40fdf02 --- /dev/null +++ b/Task/Tree-traversal/PascalABC.NET/tree-traversal.pas @@ -0,0 +1,61 @@ +type + Node = auto class + data: T; + left,right: Node; + end; + +function ND(data: T; left: Node := nil; right: Node := nil) + := new Node(data,left,right); + +procedure Prefix(r: Node); +begin + if r = nil then + exit; + Print(r.data); + Prefix(r.left); + Prefix(r.right); +end; + +procedure Infix(r: Node); +begin + if r = nil then + exit; + Infix(r.left); + Print(r.data); + Infix(r.right); +end; + +procedure Postfix(r: Node); +begin + if r = nil then + exit; + Postfix(r.left); + Postfix(r.right); + Print(r.data); +end; + +procedure LevelOrder(r: Node); +begin + if r = nil then + exit; + var q := new Queue>; + q.Enqueue(r); + while q.Count > 0 do + begin + var x := q.Dequeue; + Print(x.data); + if x.left <> nil then + q.Enqueue(x.Left); + if x.Right <> nil then + q.Enqueue(x.Right); + end; +end; + +begin + var root := ND(1,ND(2,ND(4,ND(7)),ND(5)),ND(3,ND(6,ND(8),ND(9)))); + Println(root); + Prefix(root); Println; + Infix(root); Println; + Postfix(root); Println; + LevelOrder(root); Println; +end. diff --git a/Task/Tree-traversal/Rust/tree-traversal.rust b/Task/Tree-traversal/Rust/tree-traversal.rust index 3fece25e48..1d40a9504c 100644 --- a/Task/Tree-traversal/Rust/tree-traversal.rust +++ b/Task/Tree-traversal/Rust/tree-traversal.rust @@ -64,38 +64,23 @@ impl TreeNode { res } - // Leftmost to rightmost + // From left to right fn iterative_inorder(&self) -> Vec<&TreeNode> { let mut stack: Vec<&TreeNode> = Vec::new(); let mut res: Vec<&TreeNode> = Vec::new(); - let mut p = self; + let mut opt = Some(self); - loop { - // Stack parents and right children while left-descending - loop { - match p.right { - None => {} - Some(box ref n) => stack.push(n), - } - stack.push(p); - match p.left { - None => break, - Some(box ref n) => p = n, - } - } - // Visit the nodes with no right child - p = stack.pop().unwrap(); - while !stack.is_empty() && p.right.is_none() { - res.push(p); - p = stack.pop().unwrap(); - } - // First node that can potentially have a right child: - res.push(p); - if stack.is_empty() { - break; - } else { - p = stack.pop().unwrap(); + while { + // Descend leftwards + while let Some(tree) = opt { + stack.push(tree); + opt = tree.left.as_deref(); } + !stack.is_empty() + } { + let tree = stack.pop().unwrap(); + res.push(tree); + opt = tree.right.as_deref(); } res } diff --git a/Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas b/Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas new file mode 100644 index 0000000000..83f732fc74 --- /dev/null +++ b/Task/Trigonometric-functions/PascalABC.NET/trigonometric-functions.pas @@ -0,0 +1,20 @@ +begin + var rad := Pi/3; + var deg := RadToDeg(rad); + Println('=== Radians ==='); + var (Si,Co,Ta) := (Sin(rad),Cos(rad),Tan(rad)); + Println($'Sin({rad}) = {Si}'); + Println($'Cos({rad}) = {Co}'); + Println($'Tan({rad}) = {Ta}'); + Println($'ArcSin({Si}) = {ArcSin(Si)}'); + Println($'ArcCos({Co}) = {ArcCos(Co)}'); + Println($'ArcTan({Ta}) = {ArcTan(Ta)}'); + Println('=== Degrees ==='); + var (SiD,CoD,TaD) := (Sin(DegToRad(deg)),Cos(DegToRad(deg)),Tan(DegToRad(deg))); + Println($'Sin({deg}) = {SiD}'); + Println($'Cos({deg}) = {CoD}'); + Println($'Tan({deg}) = {TaD}'); + Println($'ArcSin({SiD}) = {RadToDeg(ArcSin(SiD))}'); + Println($'ArcCos({CoD}) = {RadToDeg(ArcCos(CoD))}'); + Println($'ArcTan({TaD}) = {RadToDeg(ArcTan(TaD))}'); +end. diff --git a/Task/Trigonometric-functions/Phix/trigonometric-functions.phix b/Task/Trigonometric-functions/Phix/trigonometric-functions.phix index 2b71f21c5b..c6b4fb5c91 100644 --- a/Task/Trigonometric-functions/Phix/trigonometric-functions.phix +++ b/Task/Trigonometric-functions/Phix/trigonometric-functions.phix @@ -1,15 +1,13 @@ -(phixonline)--> - with javascript_semantics - ?sin(PI/2) - ?sin(90*PI/180) - ?cos(0) - ?cos(0*PI/180) - ?tan(PI/4) - ?tan(45*PI/180) - ?arcsin(1)*2 - ?arcsin(1)*180/PI - ?arccos(0)*2 - ?arccos(0)*180/PI - ?arctan(1)*4 - ?arctan(1)*180/PI -9 A-->Z */ +Do n=1 To words(z) /* [?] process all specified ISINs.*/ + x=word(z,n) /*obtain an ISIN from the Z list. */ + p=verify(x,valid,'N') + If p>0 Then msg='invalid character in position' p':' substr(x,p,1) + Else Do + dd='' /* [?] construct list of ISIN digits. */ + Do k=1 To length(x) + _=substr(x,k,1) /*the ISIN may contain alphabetic chars*/ + p=pos(_,valid) /*X contains 0-->9 A-->Z */ + dd=dd||p-1 /*convert X string (base 36 --? dec).*/ + End + msg='' + Select + When length(x)\==12 Then msg='not exactly 12 chars' + When \datatype( left(x,2),'U') Then msg='not starting with 2 capital chars' + When \datatype(right(x,1),'W') Then msg='last character is not a digit' + Otherwise + If \luhn(dd) Then msg='does not pass the Luhn test' + End + End + If msg='' Then + Say right(x,15) ' valid' /* display the positive message. */ + Else + Say right(x,15) 'not valid:' msg /* display the problem */ + End /*n*/ +Exit /*stick a fork in it, we're all done */ +/*-----------------------------------------------------------------------------------*/ +luhn: Procedure + Parse Arg x /* get credit card number; */ + dsum=0 /* zero digit sum. */ + y=reverse(left(0,length(x)//2)x) /* add leading zero If needed & reverse */ + Do j=1 To length(y)-1 By 2 + _=2*substr(y,j+1,1) + dsum=dsum+substr(y,j,1)+left(_,1)+substr(_,2,1,0) + End + Return right(dsum,1)==0 /* Return 1 if number passed Luhn test */ diff --git a/Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua b/Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua new file mode 100644 index 0000000000..50c0fb243e --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/Uiua/validate-international-securities-identification-number.uiua @@ -0,0 +1,19 @@ +Base ← "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +Luhn ← =0◿10+⊃(/+⊢|/+∵(⍥(-9)>9.×2)⊡1)⍉⬚0↯∞_2⇌ +Checksum ← Luhn≡⋕/◇⊂≡(□°⋕⊗)⊙(¤Base) +Format ← ××⊃(/×≡(≥@A)↙2|=12⧻|/↧∊:Base) +Valid ← ×⊃(Format|Checksum) + +Tests ← { + "AU0000XVGZA3" + "US0378331005" + "US0373831005" # twiddled + "U50378331005" # 5 rather than S + "US03378331005" # Extra char + "AU0000XVGZA3" + "AU0000VXGZA3" + "FR0000988040" + "F00Ö00988040" # Illegal char +} + +≡◇Valid Tests diff --git a/Task/Van-Eck-sequence/REXX/van-eck-sequence-1.rexx b/Task/Van-Eck-sequence/REXX/van-eck-sequence-1.rexx index edf190ada6..3faa5e1190 100644 --- a/Task/Van-Eck-sequence/REXX/van-eck-sequence-1.rexx +++ b/Task/Van-Eck-sequence/REXX/van-eck-sequence-1.rexx @@ -1,10 +1,24 @@ -/*REXX pgm generates/displays the 'start ──► end' elements of the Van Eck sequence.*/ -parse arg LO HI $ . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 10 /* " " " " " " */ -if $=='' | $=="," then $= 0 /* " " " " " " */ -$$=; z= $ /*$$: old seq: $: initial value of seq*/ - do HI-1; z= wordpos( reverse(z), reverse($$) ); $$= $; $= $ z - end /*HI-1*/ /*REVERSE allows backwards search in $.*/ - /*stick a fork in it, we're all done. */ -say 'terms ' LO " through " HI ' of the Van Eck sequence are: ' subword($,LO,HI-LO+1) +/*REXX pgm generates/displays the 'start --> end' elements of the Van Eck sequence.*/ +Parse Arg lo hi d . /*obtain optional arguments from the CL*/ +If lo=='' | lo==',' Then lo= 1 /*Not specified? Then use the default.*/ +If hi=='' | hi==',' Then hi= 10 /* " " " " " " */ +If d=='' | d==',' Then d= 0 /* " " " " " " */ +dd='' +z=d /*dd: old seq: d: initial value of seq*/ +Do i=1 To hi-1 + za=wordpos(reverse(z),reverse(dd)) + zb=0 + wdd=words(dd) + Do zz=wdd To 1 By -1 + If z=word(dd,zz) Then Do + zb=wdd-zz+1 + Leave + End + End + z=za + dd=d + d=d z + End /*HI-1*/ /*REVERSE allows backwards search in d.*/ +Say 'terms ' lo ' through ' hi ' of the Van Eck sequence are: ' subword(d,lo,hi-lo+1) +Exit + /*stick a fork in it, we're all done. */ diff --git a/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx b/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx index e8cb15b233..533d8971e8 100644 --- a/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx +++ b/Task/Van-Eck-sequence/REXX/van-eck-sequence-2.rexx @@ -1,14 +1,30 @@ -/*REXX pgm generates/displays the 'start ──► end' elements of the Van Eck sequence.*/ -parse arg LO HI sta . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 10 /* " " " " " " */ -if sta=='' | sta=="," then sta= 0 /* " " " " " " */ -$.0= sta; x= sta; @.=. /*$.: the Van Eck sequence as a list.*/ - do #=1 for HI-1 /*X: is the last term being examined. */ - if @.x==. then do; @.x= #; $.#= 0; x= 0; end /*new term.*/ - else do; z= # - @.x; $.#= z; @.x= #; x= z; end /*old term.*/ - end /*#*/ /*Z: the new term being added to list.*/ - LOw= LO - 1; out= $.LOw /*initialize the output value. */ - do j=LO to HI-1; out= out $.j /*build a list for the output display. */ - end /*j*/ /*stick a fork in it, we're all done. */ -say 'terms ' LO " through " HI ' of the Van Eck sequence are: ' out +/*REXX pgm generates/displays the 'start --? end' elements of the Van Eck sequence.*/ +Parse Arg lo hi sta . /*obtain optional arguments from the CL*/ +If lo=='' | lo==',' Then lo= 1 /*Not specified? Then use the default.*/ +If hi=='' | hi==',' Then hi= 10 /* " " " " " " */ +If sta=='' | sta==',' Then sta= 0 /* " " " " " " */ +d.0=sta /*d.: the Van Eck sequence as a list.*/ +x=sta +a.=. +out='0' +Do n=1 For hi-1 /*X: is the last term being examined. */ + If a.x==. Then Do /* new term. */ + a.x=n + d.n=0 + x=0 + End + Else Do /* old term. */ + z=n-a.x + d.n=z + a.x=n + x=z + End + out=out d.n + End /*n*/ /*Z: the new term being added To list.*/ +low=lo-1 +out=d.low /* initialize the output list */ +Do j=lo To hi-1 + out=out d.j /*build a list For the output display. */ + End /*j*/ +Say 'terms ' lo ' through ' hi ' of the Van Eck sequence are: ' out + /*stick a fork in it, we're all done. */ diff --git a/Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs b/Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs new file mode 100644 index 0000000000..8c41a8eebb --- /dev/null +++ b/Task/Variable-declaration-reset/C-sharp/variable-declaration-reset.cs @@ -0,0 +1,37 @@ +internal class Program +{ + private static void Main(string[] args) + { + int[] s = { 1, 2, 2, 3, 4, 4, 5 }; + + // There is no output as 'prev' is created anew each time + // around the loop and set to zero. + for (int i = 0; i < s.Length; ++i) + { + int curr = s[i]; + int prev = 0; + // int prev; // triggers "error: variable prev might not have been initialized" + if (i > 0 && curr == prev) + { + Console.WriteLine(i); + } + + prev = curr; + } + + int gprev = 0; + + // Now 'gprev' is used and reassigned + // each time around the loop producing the desired output. + for (int i = 0; i < s.Length; ++i) + { + int curr = s[i]; + if (i > 0 && curr == gprev) + { + Console.WriteLine(i); + } + + gprev = curr; + } + } +} diff --git a/Task/Variables/PascalABC.NET/variables-1.pas b/Task/Variables/PascalABC.NET/variables-1.pas new file mode 100644 index 0000000000..201530a172 --- /dev/null +++ b/Task/Variables/PascalABC.NET/variables-1.pas @@ -0,0 +1 @@ +var i,j: integer; diff --git a/Task/Variables/PascalABC.NET/variables-2.pas b/Task/Variables/PascalABC.NET/variables-2.pas new file mode 100644 index 0000000000..7ce986bc9e --- /dev/null +++ b/Task/Variables/PascalABC.NET/variables-2.pas @@ -0,0 +1 @@ +var n: integer := 5; diff --git a/Task/Variables/PascalABC.NET/variables-3.pas b/Task/Variables/PascalABC.NET/variables-3.pas new file mode 100644 index 0000000000..6760f159bf --- /dev/null +++ b/Task/Variables/PascalABC.NET/variables-3.pas @@ -0,0 +1 @@ +var n := 5; diff --git a/Task/Variables/PascalABC.NET/variables-4.pas b/Task/Variables/PascalABC.NET/variables-4.pas new file mode 100644 index 0000000000..6ae29d48a4 --- /dev/null +++ b/Task/Variables/PascalABC.NET/variables-4.pas @@ -0,0 +1 @@ +var (m,x) := (5,4.3); diff --git a/Task/Variables/PascalABC.NET/variables-5.pas b/Task/Variables/PascalABC.NET/variables-5.pas new file mode 100644 index 0000000000..9ae9ea9563 --- /dev/null +++ b/Task/Variables/PascalABC.NET/variables-5.pas @@ -0,0 +1,6 @@ +var i: integer; + +procedure p; +begin + var i: integer; +end; diff --git a/Task/Variables/PascalABC.NET/variables-6.pas b/Task/Variables/PascalABC.NET/variables-6.pas new file mode 100644 index 0000000000..c9d7f126b3 --- /dev/null +++ b/Task/Variables/PascalABC.NET/variables-6.pas @@ -0,0 +1,5 @@ +var i: integer; +begin + for var i:=1 to 10 do // Error! + Print(i) +end; diff --git a/Task/Variadic-function/PascalABC.NET/variadic-function.pas b/Task/Variadic-function/PascalABC.NET/variadic-function.pas new file mode 100644 index 0000000000..8edacaec86 --- /dev/null +++ b/Task/Variadic-function/PascalABC.NET/variadic-function.pas @@ -0,0 +1,11 @@ +procedure Output(params arr: array of object); +begin + foreach var obj in arr do + Println(obj); +end; + +begin + Output(1,2.5,'z','PascalABC.NET'); + var a: array of object := (1,2.5,'z','PascalABC.NET'); + Output(a); +end. diff --git a/Task/Vector-products/PascalABC.NET/vector-products.pas b/Task/Vector-products/PascalABC.NET/vector-products.pas new file mode 100644 index 0000000000..8bd220f682 --- /dev/null +++ b/Task/Vector-products/PascalABC.NET/vector-products.pas @@ -0,0 +1,26 @@ +uses System.Numerics; + +function DotProduct(v1,v2: Vector3): real + := v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; + +function CrossProduct(v1,v2: Vector3): Vector3 + := new Vector3(v1.y * v2.z - v1.z * v2.y, + v1.z * v2.x - v1.x * v2.z, + v1.x * v2.y - v1.y * v2.x); + +function ScalarTripleProduct(a,b,c: Vector3): real + := DotProduct(a, CrossProduct(b, c)); + +function VectorTripleProduct(a,b,c: Vector3): Vector3 + := CrossProduct(a, CrossProduct(b, c)); + + +begin + var a := new Vector3(3,4,5); + var b := new Vector3(4,3,5); + var c := new Vector3(-5,-12,-13); + Writeln(DotProduct(a, b)); + Writeln(CrossProduct(a, b)); + Writeln(ScalarTripleProduct(a, b, c)); + Writeln(VectorTripleProduct(a, b, c)); +end. diff --git a/Task/Vector-products/REXX/vector-products.rexx b/Task/Vector-products/REXX/vector-products.rexx index 4f409c7129..facf79ebfb 100644 --- a/Task/Vector-products/REXX/vector-products.rexx +++ b/Task/Vector-products/REXX/vector-products.rexx @@ -1,19 +1,26 @@ -/*REXX program computes the products: dot, cross, scalar triple, and vector triple.*/ - a= 3 4 5 - b= 4 3 5 /*(positive numbers don't need quotes.)*/ - c= "-5 -12 -13" -call tellV 'vector A =', a /*show the A vector, aligned numbers.*/ -call tellV 'vector B =', b /* " " B " " " */ -call tellV 'vector C =', c /* " " C " " " */ - say -call tellV ' dot product [A∙B] =', dot(a, b) -call tellV 'cross product [AxB] =', cross(a, b) -call tellV 'scalar triple product [A∙(BxC)] =', dot(a, cross(b, c) ) -call tellV 'vector triple product [Ax(BxC)] =', cross(a, cross(b, c) ) -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -cross: procedure; arg $1 $2 $3,@1 @2 @3; return $2*@3 -$3*@2 $3*@1 -$1*@3 $1*@2 -$2*@1 -dot: procedure; arg $1 $2 $3,@1 @2 @3; return $1*@1 + $2*@2 + $3*@3 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -tellV: procedure; parse arg name,x y z; w=max(4,length(x),length(y),length(z)) /*max W*/ - say right(name,40) right(x,w) right(y,w) right(z,w); /*show vector.*/ return +/*REXX program computes the products: dot, cross, scalar triple, and vector triple.*/ +a= 3 4 5 +b= 4 3 5 /*(positive numbers don't need quotes.)*/ +c= '-5 -12 -13' +Call tellV 'vector A =', a /*show the A vector, aligned numbers.*/ +Call tellV "vector B =", b /* " " B " " " */ +Call tellV "vector C =", c /* " " C " " " */ +Say '' +Call tellV ' dot product [A·B] =', dot(a,b) +Call tellV 'cross product [AxB] =', cross(a,b) +Call tellV 'scalar triple product [A·(BxC)] =', dot(a,cross(b,c)) +Call tellV 'vector triple product [Ax(BxC)] =', cross(a,cross(b,c)) +Exit /*stick a fork in it, we're all done. */ +/*---------------------------------------------------------------------------*/ +cross: Procedure + Arg a b c, u v w + Return b*w-c*v c*u-a*w a*v-b*u +dot: Procedure + Arg a b c, u v w + Return a*u + b*v + c*w +/*---------------------------------------------------------------------------*/ +tellV: Procedure + Parse Arg name,x y z + w=max(4,length(x),length(y),length(z)) /*max width */ + Say right(name,33) right(x,w) right(y,w) right(z,w) /*show vector. */ + Return diff --git a/Task/Vector/Chipmunk-Basic/vector.basic b/Task/Vector/Chipmunk-Basic/vector.basic new file mode 100644 index 0000000000..bd147fff68 --- /dev/null +++ b/Task/Vector/Chipmunk-Basic/vector.basic @@ -0,0 +1,37 @@ +100 cls +110 dim vect1(2) +120 vect1(1) = 5 : vect1(2) = 7 +130 dim vect2(2) +140 vect2(1) = 2 : vect2(2) = 3 +150 dim vect3(ubound(vect1)) +160 for n = 1 to ubound(vect1) +170 vect3(n) = vect1(n)+vect2(n) +180 next n +190 print "["+str$(vect1(1))+", "+str$(vect1(2))+"] + ["+str$(vect2(1))+", "+str$(vect2(2))+"] = "; +200 showarray(vect3) +210 for n = 1 to ubound(vect1) +220 vect3(n) = vect1(n)-vect2(n) +230 next n +240 print "["+str$(vect1(1))+", "+str$(vect1(2))+"] - ["+str$(vect2(1))+", "+str$(vect2(2))+"] = "; +250 showarray(vect3) +260 for n = 1 to ubound(vect1) +270 vect3(n) = vect1(n)*11 +280 next n +290 print "["+str$(vect1(1))+", "+str$(vect1(2))+"] * 11 = "; +300 showarray(vect3) +310 for n = 1 to ubound(vect1) +320 vect3(n) = vect1(n)/2 +330 next n +340 print "["+str$(vect1(1))+", "+str$(vect1(2))+"] / 2 = "; +350 showarray(vect3) +360 end +370 sub showarray(vect3) +380 print "["; +390 svect$ = "" +400 for n = 1 to ubound(vect3) +410 svect$ = svect$+str$(vect3(n))+", " +420 next n +430 svect$ = left$(svect$,len(svect$)-2) +440 print svect$; +450 print "]" +460 end sub diff --git a/Task/Vector/GW-BASIC/vector.basic b/Task/Vector/GW-BASIC/vector.basic new file mode 100644 index 0000000000..01719a40df --- /dev/null +++ b/Task/Vector/GW-BASIC/vector.basic @@ -0,0 +1,37 @@ +100 CLS : rem 100 HOME for Applesoft BASIC +110 DIM v1(2) +120 v1(1) = 5 : v1(2) = 7 +130 DIM v2(2) +140 v2(1) = 2 : v2(2) = 3 +150 DIM v3(2) +160 FOR n = 1 TO 2 +170 v3(n) = v1(n)+v2(n) +180 NEXT n +190 PRINT "[";v1(1);", ";v1(2);"] + [";v2(1);", ";v2(2);"] = "; +200 GOSUB 370 : rem showarray(vect3) +210 FOR n = 1 TO 2 +220 v3(n) = v1(n)-v2(n) +230 NEXT n +240 PRINT "[";v1(1);", ";v1(2);"] - [";v2(1);", ";v2(2);"] = "; +250 GOSUB 370 : rem showarray(vect3) +260 FOR n = 1 TO 2 +270 v3(n) = v1(n)*11 +280 NEXT n +290 PRINT "[";v1(1);", ";v1(2);"] * ";11;" = "; +300 GOSUB 370 : rem showarray(vect3) +310 FOR n = 1 TO 2 +320 v3(n) = v1(n)/2 +330 NEXT n +340 PRINT "[";v1(1);", ";v1(2);"] / ";2;" = "; +350 GOSUB 370 : rem showarray(vect3) +360 END +370 rem SUB showarray(vect3) +380 PRINT "["; +390 svt$ = "" +400 FOR n = 1 TO 2 +410 svt$ = svt$+STR$(v3(n))+", " +420 NEXT n +430 svt$ = LEFT$(svt$,LEN(svt$)-2) +440 PRINT svt$; +450 PRINT "]" +460 RETURN diff --git a/Task/Vector/PascalABC.NET/vector.pas b/Task/Vector/PascalABC.NET/vector.pas new file mode 100644 index 0000000000..7eac61123f --- /dev/null +++ b/Task/Vector/PascalABC.NET/vector.pas @@ -0,0 +1,31 @@ +type + Vector = class + x,y: real; + public + constructor (xx,yy: real) := (x,y) := (xx,yy); + function ToString: string; override := $'({x},{y})'; + end; + +function operator+(v1,v2: Vector): Vector; extensionmethod + := new Vector(v1.x + v2.x, v1.y + v2.y); + +function operator-(v1,v2: Vector): Vector; extensionmethod + := new Vector(v1.x - v2.x, v1.y - v2.y); + +function operator*(v: Vector; n: real): Vector; extensionmethod + := new Vector(v.x * n, v.y * n); + +function operator*(n: real; v: Vector): Vector; extensionmethod + := v * n; + +function operator/(v: Vector; n: real): Vector; extensionmethod + := new Vector(v.x / n, v.y / n); + +begin + var v1 := new Vector(1,2); + var v2 := new Vector(3,4); + Println(v1 + v2); + Println(v1 - v2); + Println(v1 * 2.5, 2.5 * v1); + Println(v1 / 2); +end. diff --git a/Task/Vector/QBasic/vector.basic b/Task/Vector/QBasic/vector.basic new file mode 100644 index 0000000000..e74c698251 --- /dev/null +++ b/Task/Vector/QBasic/vector.basic @@ -0,0 +1,39 @@ +DECLARE SUB showarray (vect3!()) +CLS +DIM vect1(2) +vect1(1) = 5: vect1(2) = 7 +DIM vect2(2) +vect2(1) = 2: vect2(2) = 3 +DIM vect3(UBOUND(vect1)) +FOR n = 1 TO UBOUND(vect1) + vect3(n) = vect1(n) + vect2(n) +NEXT n +PRINT "["; STR$(vect1(1)); ","; STR$(vect1(2)); " ] + ["; STR$(vect2(1)) + ","; STR$(vect2(2)); " ] = "; +CALL showarray(vect3()) +FOR n = 1 TO UBOUND(vect1) + vect3(n) = vect1(n) - vect2(n) +NEXT n +PRINT "["; STR$(vect1(1)); ","; STR$(vect1(2)); " ] - ["; STR$(vect2(1)) + ","; STR$(vect2(2)); " ] = "; +CALL showarray(vect3()) +FOR n = 1 TO UBOUND(vect1) + vect3(n) = vect1(n) * 11 +NEXT n +PRINT "["; STR$(vect1(1)); ","; STR$(vect1(2)); " ] * 11 = "; +CALL showarray(vect3()) +FOR n = 1 TO UBOUND(vect1) + vect3(n) = vect1(n) / 2 +NEXT n +PRINT "["; STR$(vect1(1)); ","; STR$(vect1(2)); " ] / 2 = "; +CALL showarray(vect3()) +END + +SUB showarray (vect3()) + PRINT "["; + svect$ = "" + FOR n = 1 TO UBOUND(vect3) + svect$ = svect$ + STR$(vect3(n)) + "," + NEXT n + svect$ = LEFT$(svect$, LEN(svect$) - 1) + PRINT svect$; + PRINT " ]" +END SUB diff --git a/Task/Vector/True-BASIC/vector.basic b/Task/Vector/True-BASIC/vector.basic new file mode 100644 index 0000000000..826ab3e64a --- /dev/null +++ b/Task/Vector/True-BASIC/vector.basic @@ -0,0 +1,40 @@ +SUB showarray (vect3()) + PRINT "["; + LET svect$ = "" + FOR n = 1 TO UBOUND(vect3) + LET svect$ = svect$ & STR$(vect3(n)) & ", " + NEXT n + LET svect$ = (svect$)[1:LEN(svect$)-2] + PRINT svect$; + PRINT "]" +END SUB + +DIM vect1(2) +LET vect1(1) = 5 +LET vect1(2) = 7 +DIM vect2(2) +LET vect2(1) = 2 +LET vect2(2) = 3 +DIM vect3(0) +MAT REDIM vect3(UBOUND(vect1)) +FOR n = 1 TO UBOUND(vect1) + LET vect3(n) = vect1(n)+vect2(n) +NEXT n +PRINT "["; STR$(vect1(1)); ", "; STR$(vect1(2)); "] + ["; STR$(vect2(1)) & ", "; STR$(vect2(2)); "] = "; +CALL showarray (vect3()) +FOR n = 1 TO UBOUND(vect1) + LET vect3(n) = vect1(n)-vect2(n) +NEXT n +PRINT "["; STR$(vect1(1)); ", "; STR$(vect1(2)); "] - ["; STR$(vect2(1)) & ", "; STR$(vect2(2)); "] = "; +CALL showarray (vect3()) +FOR n = 1 TO UBOUND(vect1) + LET vect3(n) = vect1(n)*11 +NEXT n +PRINT "["; STR$(vect1(1)); ", "; STR$(vect1(2)); "] * 11 = "; +CALL showarray (vect3()) +FOR n = 1 TO UBOUND(vect1) + LET vect3(n) = vect1(n)/2 +NEXT n +PRINT "["; STR$(vect1(1)); ", "; STR$(vect1(2)); "] / 2 = "; +CALL showarray (vect3()) +END diff --git a/Task/Verify-distribution-uniformity-Naive/EasyLang/verify-distribution-uniformity-naive.easy b/Task/Verify-distribution-uniformity-Naive/EasyLang/verify-distribution-uniformity-naive.easy new file mode 100644 index 0000000000..e3fa0a53fb --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/EasyLang/verify-distribution-uniformity-naive.easy @@ -0,0 +1,47 @@ +func dice5 . + return randint 5 +. +func dice25 . + return (dice5 - 1) * 5 + dice5 +. +func dice7a . + return dice25 mod1 7 +. +func dice7b . + repeat + h = dice25 + until h <= 21 + . + return h mod1 7 +. +numfmt 3 0 +# +proc checkdist dicefunc n delta . . + len dist[] 7 + for i to n + # no function pointers + if dicefunc = 1 + h = dice7a + else + h = dice7b + . + dist[h] += 1 + . + for i to len dist[] + h = dist[i] / n * 7 + if abs (h - 1) > delta + bad = 1 + . + dist[i] = 0 + print h + . + if bad = 1 + print "-> not uniform" + else + print "-> uniform" + . + print "" +. +# +checkdist 1 1000000 0.01 +checkdist 2 1000000 0.01 diff --git a/Task/Wagstaff-primes/Sidef/wagstaff-primes.sidef b/Task/Wagstaff-primes/Sidef/wagstaff-primes.sidef new file mode 100644 index 0000000000..a9d7e1b63a --- /dev/null +++ b/Task/Wagstaff-primes/Sidef/wagstaff-primes.sidef @@ -0,0 +1,20 @@ +var iter = Enumerator({|callback| + var p = 2 + loop { + var t = ((2**p + 1)/3) + callback([p, t]) if t.is_prime + p.next_prime! + } +}) + +var n = 1 +say "Index Exponent Prime" +say "-"*31 + +iter.each {|k| + var (e, p) = k... + p = "(#{p.len} digits)" if (n > 10) + say "#{'%5s'%n} #{'%8s'%e} #{'%16s'%p}" + break if (n == 24) + ++n +} diff --git a/Task/Walk-a-directory-Non-recursively/PascalABC.NET/walk-a-directory-non-recursively.pas b/Task/Walk-a-directory-Non-recursively/PascalABC.NET/walk-a-directory-non-recursively.pas new file mode 100644 index 0000000000..84e2e8c6f4 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PascalABC.NET/walk-a-directory-non-recursively.pas @@ -0,0 +1,4 @@ +begin + var path := 'C:\PABCWork.NET'; + EnumerateFiles(path,'*.pas').PrintLines; +end. diff --git a/Task/Walk-a-directory-Recursively/PascalABC.NET/walk-a-directory-recursively.pas b/Task/Walk-a-directory-Recursively/PascalABC.NET/walk-a-directory-recursively.pas new file mode 100644 index 0000000000..5f9a45edfc --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PascalABC.NET/walk-a-directory-recursively.pas @@ -0,0 +1,4 @@ +begin + var path := 'C:\PABCWork.NET'; + EnumerateAllFiles(path,'*.pas').PrintLines; +end. diff --git a/Task/War-card-game/00-TASK.txt b/Task/War-card-game/00-TASK.txt index b4b80f82e7..a9541f8693 100644 --- a/Task/War-card-game/00-TASK.txt +++ b/Task/War-card-game/00-TASK.txt @@ -15,4 +15,3 @@ Related tasks: * [[Poker hand_analyser]] * [[Go Fish]] - diff --git a/Task/War-card-game/Ada/war-card-game.ada b/Task/War-card-game/Ada/war-card-game.ada new file mode 100644 index 0000000000..ad8c89f727 --- /dev/null +++ b/Task/War-card-game/Ada/war-card-game.ada @@ -0,0 +1,146 @@ +-- Play the card game War +-- J. Carter 2024 Jul +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Ansi_Tty_Control; +with PragmARC.Cards.Decks.US; +with PragmARC.Cards.US; + +procedure War is + package Ansi renames PragmARC.Ansi_Tty_Control; + package Cards renames PragmARC.Cards.US; + package Decks renames PragmARC.Cards.Decks.US; + + use type Cards.Rank_Id; + + procedure Display (Hand1 : in Decks.Deck_52; Hand2 : in Decks.Deck_52); + -- Display the state of the game represented by the 2 hands + + function ">" (Left : in Cards.Card_Info; Right : in Cards.Card_Info) return Boolean is + (if Left.Rank = Cards.Ace then + Right.Rank /= Cards.Ace + elsif Right.Rank = Cards.Ace then + False + else + Left.Rank > Right.Rank); + + procedure Display (Hand1 : in Decks.Deck_52; Hand2 : in Decks.Deck_52) is + function Image (Card : in Cards.Card_Info) return Character is + (Cards.Image (Card) (1) ); + + procedure Display (Hand : in Decks.Deck_52); + -- Puts the ranks of the cards in Hand in a row + + procedure Display (Hand : in Decks.Deck_52) is + -- Empty + begin -- Display + All_Cards : for I in 1 .. Hand.Size loop + Ada.Text_IO.Put (Item => Image (Hand.Value (I) ) ); + end loop All_Cards; + end Display; + begin -- Display + Ada.Text_IO.Put (Item => Ansi.Clear_Screen); + Display (Hand => Hand1); + Ada.Text_IO.Put (Item => Ansi.Position (2, 1) ); + Display (Hand => Hand2); + Ada.Text_IO.Put (Item => Ansi.Position (3, 1) ); + end Display; + + Hand1 : Decks.Deck_52; -- Player 1 + Hand2 : Decks.Deck_52; -- Player 2 + Card1 : Cards.Card_Info; -- Player 1 + Card2 : Cards.Card_Info; -- Player 2 + War1 : Decks.Deck_52; -- Player 1 + War2 : Decks.Deck_52; -- Player 2 +begin -- War + Decks.Standard_Deck (Item => Hand1); + Hand1.Shuffle; + + Deal : for I in 1 .. Hand1.Size / 2 loop -- Each player gets half the deck + Hand1.Deal (To => Card1); + Hand2.Add (Item => Card1); + end loop Deal; + + Play : loop + Display (Hand1 => Hand1, Hand2 => Hand2); + + exit Play when Hand1.Size = 0 or Hand2.Size = 0; + + delay 0.5; + + Hand1.Deal (To => Card1); + Hand2.Deal (To => Card2); + + if Card1.Rank /= Card2.Rank then + if Card1 > Card2 then + Hand1.Add (Item => Card1); + Hand1.Add (Item => Card2); + else + Hand2.Add (Item => Card2); + Hand2.Add (Item => Card1); + end if; + else -- War! + War1.Add (Item => Card1); + War2.Add (Item => Card2); + + All_Tries : loop + Ada.Text_IO.Put (Item => "W^^"); + + delay 0.5; + + Deal1 : for I in 1 .. 2 loop + exit Deal1 when Hand1.Is_Empty; + + Hand1.Deal (To => Card1); + War1.Add (Item => Card1); + end loop Deal1; + + Deal2 : for I in 1 .. 2 loop + exit Deal2 when Hand2.Is_Empty; + + Hand2.Deal (To => Card2); + War2.Add (Item => Card2); + end loop Deal2; + + if War1.Value (War1.Size) > War2.Value (War2.Size) then -- 1 wins + Deal11 : loop + exit Deal11 when War1.Is_Empty; + + War1.Deal (To => Card1); + Hand1.Add (Item => Card1); + end loop Deal11; + + Deal12 : loop + exit Deal12 when War2.Is_Empty; + + War2.Deal (To => Card1); + Hand1.Add (Item => Card1); + end loop Deal12; + + exit All_Tries; + elsif War2.Value (War2.Size) > War1.Value (War1.Size) then -- 2 Wins + Deal22 : loop + exit Deal22 when War2.Is_Empty; + + War2.Deal (To => Card2); + Hand2.Add (Item => Card2); + end loop Deal22; + + Deal21 : loop + exit Deal21 when War1.Is_Empty; + + War1.Deal (To => Card2); + Hand2.Add (Item => Card2); + end loop Deal21; + + exit All_Tries; + else + null; -- The war continues + end if; + end loop All_Tries; + end if; + end loop Play; + + Ada.Text_IO.Put (Item => "Player " & (if Hand1.Size = 0 then '2' else '1') & " wins"); +end War; diff --git a/Task/War-card-game/Jq/war-card-game.jq b/Task/War-card-game/Jq/war-card-game.jq new file mode 100644 index 0000000000..f07aeea78e --- /dev/null +++ b/Task/War-card-game/Jq/war-card-game.jq @@ -0,0 +1,113 @@ +### Generic functions + +# Set .popped to the first item of the specified array, and remove it therefrom +@ Usage example: {a:[1,2]} | pop(.a; .x) +def pop(array; popped): + popped = array[0] + | array |= .[1:]; + +# like while/2 but emit the final term rather than the first one +def whilst(cond; update): + def _whilst: + if cond then update | (., _whilst) else empty end; + _whilst; + +# Output: a prn in range(0;.) +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs)] | join("") | tonumber + | if . < $n then . else ($n | prn) end + end; + +def knuthShuffle: + length as $n + | if $n <= 1 then . + else {i: $n, a: .} + | until(.i == 0; + .i += -1 + | (.i + 1 | prn) as $j + | .a[.i] as $t + | .a[.i] = .a[$j] + | .a[$j] = $t) + | .a + end; + + +### War Card Game +def suits: ["♣", "♦", "♥", "♠"]; +def faces: ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A" ]; + +def cards: [range( 0; 52) | "\(faces[.%13])\(suits[(./13)|floor])"]; +def ranks: [range( 0; 52) | . % 13]; + +def war: + cards as $cards + | ranks as $ranks + | ([range(0; 52)] | knuthShuffle) as $deck + | reduce range(0; 26) as $i ({}; + .hand1 |= [$deck[2*$i]] + . + | .hand2 |= [$deck[2*$i+1]] + .) + | .numPlayed=0 + | whilst( .numPlayed == 0 and + (.hand1|length) > 0 and (.hand2|length) > 0; + + pop(.hand1; .card1) + | pop(.hand2; .card2) + | .played1 = [.card1] + | .played2 = [.card2] + | .numPlayed = 2 + | whilst(.numPlayed > 0 ; + .emit = "\($cards[.card1])\t\($cards[.card2])\t" + | if $ranks[.card1] > $ranks[.card2] + then .hand1 += .played1 + .played2 + | .emit += "Player 1 takes the \(.numPlayed) cards. Now has \(.hand1|length)." + | .numPlayed = 0 + + elif $ranks[.card1] < $ranks[.card2] + then .hand2 += .played2 + .played1 + | .emit += "Player 2 takes the \(.numPlayed) cards. Now has \(.hand2|length)." + | .numPlayed = 0 + + else .emit += "War!\n" + | if (.hand1|length) < 2 + then .emit += "Player 1 has insufficient cards left." + | .hand2 = .hand2 + .played2 + .played1 + .hand1 + | .hand1 = [] + | .numPlayed = 0 + + elif .hand2|length < 2 + then .emit += "Player 2 has insufficient cards left." + | .hand1 = .hand1 + .played1 + .played2 + .hand2 + | .hand2 = [] + | .numPlayed = 0 + + else + pop(.hand1; .card1) # face down card + | .played1 += [.card1] + + | pop(.hand1; .card1) # face up card + | .played1 += [.card1] + + | pop( .hand2; .card2) # face down card 2 + | .played2 += [.card2] + + | pop(.hand2; .card2) # face up card 2 + | .played2 += [.card2] + + | .numPlayed += 4 + | .emit += "? \t?\tFace down cards." + end + end + ) + ) + | .emit, + (if .hand1|length == 52 + then "Player 1 wins the game!" + elif .hand2|length == 52 + then "Player 2 wins the game!" + else empty + end) ; + +war diff --git a/Task/Water-collected-between-towers/PHP/water-collected-between-towers.php b/Task/Water-collected-between-towers/PHP/water-collected-between-towers.php new file mode 100644 index 0000000000..5e62a76be4 --- /dev/null +++ b/Task/Water-collected-between-towers/PHP/water-collected-between-towers.php @@ -0,0 +1,60 @@ + $build[$i][$j]) { + $l = max($l, $build[$i][$k]); + } + } + for ($k = $j + 1; $k < count($build[$i]); $k++) { + if ($build[$i][$k] > $build[$i][$j]) { + $r = max($r, $build[$i][$k]); + } + } + if ($l > 0 && $r > 0) { + $w = min($l, $r) - $build[$i][$j]; + $level[$j] = $w; + } + } + +// Report + echo '
';
+	$max = max($build[$i]);
+	$u = 0;
+	for ($j = $max; $j > 0; $j--) {
+		for ($k = 0; $k < count($build[$i]); $k++) {
+			if ($j - 1 < $build[$i][$k]) {
+				echo $tower;
+			}
+			elseif (!empty($level[$k]) && $level[$k] + $build[$i][$k] >= $j) {
+				echo $water;
+				$u++;
+			}
+			elseif ($build[$i][$k] < $j) {
+				echo $empty;
+			}
+		}
+		echo '
'; + } + echo '
Block ' . $i + 1 . ' will collect ' . $u . ' units of water
'; + echo '
'; +} +?> diff --git a/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua b/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua new file mode 100644 index 0000000000..ecaabaff75 --- /dev/null +++ b/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua @@ -0,0 +1,10 @@ +Area ← /+-:↧⍜⇌\↥⟜\↥. + +{[1 5 3 7 2] + [5 3 7 2 6 4 5 9 1 2] + [2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1] + [5 5 5 5] + [5 6 7 8] + [8 7 7 6] + [6 7 10 7 6]} +∵◇Area diff --git a/Task/Weird-numbers/Ada/weird-numbers-1.ada b/Task/Weird-numbers/Ada/weird-numbers-1.ada new file mode 100644 index 0000000000..906371dcc6 --- /dev/null +++ b/Task/Weird-numbers/Ada/weird-numbers-1.ada @@ -0,0 +1,109 @@ +pragma Ada_2022; + +with Ada.Text_IO; +with Ada.Containers.Vectors; +with Ada.Containers.Ordered_Sets; + +procedure Weird_Numbers is + package IO renames Ada.Text_IO; + -- allows us to type "IO.Put_Line" instead of "Ada.Text_IO.Put_Line" + + package IntVecs is new Ada.Containers.Vectors + (Index_Type => Positive, Element_Type => Natural); + subtype IntVec is IntVecs.Vector; +-- use all type IntVec; + + Factor_Cache : IntVec; + -- used to keep track of the factors on each iteration + + package Intsets is new Ada.Containers.Ordered_Sets + (Element_Type => Positive); + subtype Intset is Intsets.Set; + Semiperfect_Cache : Intset; + Not_Abundant_Cache : Intset; + + function Proper_Divisors (Value : Positive) return IntVec is + Cofactors : IntVec; + begin + Factor_Cache.Clear; + begin + Factor_Cache.Append (1); + for Factor in 2 .. Value / 2 loop + if Value rem Factor = 0 then + Factor_Cache.Append (Factor); + end if; + end loop; + return Factor_Cache; + end; + end Proper_Divisors; + + function Is_Abundant (Value : Positive) return Boolean is + begin + if Not_Abundant_Cache.Contains (Value) + or else Semiperfect_Cache.Contains (Value) + then + return False; + end if; + if Proper_Divisors (Value)'Reduce ("+", 0) > Value then + return True; + end if; + Not_Abundant_Cache.Insert (Value); + return False; + end Is_Abundant; + + function Subset_Of (Factors : IntVec; Ith : Positive) return IntVec is + -- returns the Ith subset of Factors + -- if Factors has N elements, then there are 2**N possibilities + -- this maps Ith to one of these possibilities using its binary representation + Result : IntVec; + Index : Natural := 1; + Ith_Remainder : Natural := Ith; + begin + while Ith_Remainder /= 0 loop + if Ith_Remainder rem 2 = 1 then + Result.Append (Factors (Index)); + Ith_Remainder := @ - 1; + end if; + Ith_Remainder := @ / 2; + Index := @ + 1; + end loop; + return Result; + end Subset_Of; + + function Is_Semiperfect (Value : Positive) return Boolean is + Factors : constant IntVec := Factor_Cache; + Subset : IntVec; + Sum : Natural; + begin + if (for some Previous of Semiperfect_Cache => Value rem Previous = 0) + then + return True; + end if; + for Ith in reverse 1 .. (2**Positive (Factors.Length) - 1) loop + Subset := Subset_Of (Factors, Positive (Ith)); + Sum := Subset'Reduce ("+", 0); + if Sum = Value then + Semiperfect_Cache.Insert (Value); + return True; + end if; + end loop; + return False; + end Is_Semiperfect; + + function Is_Weird (Value : Positive) return Boolean is + (Is_Abundant (Value) and then not Is_Semiperfect (Value)); + + Current : Positive := 2; + Number_Found : Natural := 0; + +begin + IO.Put ("The first 25 weird numbers are"); + while Number_Found < 25 loop + if Is_Weird (Current * 2) then + IO.Put (Integer'Image (Current * 2)); + Number_Found := @ + 1; + end if; + Current := @ + 1; + end loop; + IO.New_Line; +end Weird_Numbers; diff --git a/Task/Weird-numbers/Ada/weird-numbers-2.ada b/Task/Weird-numbers/Ada/weird-numbers-2.ada new file mode 100644 index 0000000000..f1a649cfab --- /dev/null +++ b/Task/Weird-numbers/Ada/weird-numbers-2.ada @@ -0,0 +1,105 @@ +pragma Ada_2022; + +with Ada.Text_IO; +with Ada.Containers.Vectors; +with Ada.Containers.Ordered_Sets; + +procedure Weird_Numbers is + package IO renames Ada.Text_IO; + + package IntVecs is new Ada.Containers.Vectors + (Index_Type => Positive, Element_Type => Positive); + subtype IntVec is IntVecs.Vector; + use all type IntVec; + + Factor_Cache : IntVec; + + package Intsets is new Ada.Containers.Ordered_Sets + (Element_Type => Positive); + subtype Intset is Intsets.Set; + Semiperfect_Cache : Intset; + Not_Abundant_Cache : Intset; + + function Proper_Divisors (Value : Positive) return IntVec is + Cofactors : IntVec; + begin + Factor_Cache.Clear; + begin + Factor_Cache.Append (1); + for Factor in 2 .. Value / 2 loop + if Factor * Factor > Value then + exit; + end if; + if Value rem Factor = 0 then + Factor_Cache.Append (Factor); + if Factor * Factor /= Value then + Cofactors.Append (Value / Factor); + end if; + end if; + end loop; + Factor_Cache.Prepend_Vector (Cofactors); + -- this ordering is REALLY curious + -- for instance, the factors of 12 are ordered as 6, 4, 1, 2, 3 + -- AND THIS MATTERS + -- both strictly ascending and strictly descending orders are much slower + return Factor_Cache; + end; + end Proper_Divisors; + + function Is_Abundant (Value : Positive) return Boolean is + begin + if Not_Abundant_Cache.Contains (Value) + or else Semiperfect_Cache.Contains (Value) + then + return False; + end if; + if Proper_Divisors (Value)'Reduce ("+", 0) > Value then + return True; + end if; + Not_Abundant_Cache.Insert (Value); + return False; + end Is_Abundant; + + function Alternate_Semiperfect (Value : Positive) return Boolean is + function Reroute + (Value : Positive; First : Positive) return Boolean + is + Head : Positive; + begin + if Factor_Cache.Last_Index >= First then + Head := Factor_Cache (First); + if Value < Head then + return Reroute (Value, First + 1); + else + return + Value = Head + or else Reroute (Value - Head, First + 1) + or else Reroute (Value, First + 1); + end if; + else + return False; + end if; + end Reroute; + begin + return + Reroute + (Value, Factor_Cache.First_Index); + end Alternate_Semiperfect; + + function Is_Weird (Value : Positive) return Boolean is + (Is_Abundant (Value) and then not Alternate_Semiperfect (Value)); + + Current : Positive := 2; + Number_Found : Natural := 0; + +begin + IO.Put ("The first 25 weird numbers are"); + while Number_Found < 25 loop + if Is_Weird (Current * 2) then + IO.Put (Integer'Image (Current * 2)); + Number_Found := @ + 1; + end if; + Current := @ + 1; + end loop; + IO.New_Line; +end Weird_Numbers; diff --git a/Task/Weird-numbers/Python/weird-numbers.py b/Task/Weird-numbers/Python/weird-numbers-1.py similarity index 100% rename from Task/Weird-numbers/Python/weird-numbers.py rename to Task/Weird-numbers/Python/weird-numbers-1.py diff --git a/Task/Weird-numbers/Python/weird-numbers-2.py b/Task/Weird-numbers/Python/weird-numbers-2.py new file mode 100644 index 0000000000..8457ac3814 --- /dev/null +++ b/Task/Weird-numbers/Python/weird-numbers-2.py @@ -0,0 +1,51 @@ +# anySum :: Int -> [Int] -> [Int] + +from time import time +start = time() + +primitivesp_nos = set(); primes = [] + +def main(): + x = 2; weird_nos = [] + n = 50 + while n > 0: + if isweird(x) == 1: weird_nos.append(x); n = n - 1 + x = x + 1 + print("First", len(weird_nos), "weird nos:\n", weird_nos) + +def isweird(n): + global primes; global primitivesp_nos; pr_fctrs = []; a = n + for i in primes: + while a % i == 0: pr_fctrs.append(i); a = a//i + if i * i > a: break + if a > 1: pr_fctrs.append(a) + if a == n: primes.append(n); return 0 + sum_fctrs = 1; divisors = set(pr_fctrs) + for i in divisors: sum_fctrs = sum_fctrs*(i**(pr_fctrs.count(i)+1)-1)//(i-1) + difference = sum_fctrs - 2 * n + if difference <= 0: + if difference == 0: primitivesp_nos.add(n) + return 0 + # Next 10 lines from Jerome Richard: stackoverflow.com/questions/6800193 + divisors = [1]; last_prime = 0; fctr = 0; slice_len = 0 + for prime in pr_fctrs: + if last_prime != prime: slice_len = len(divisors); fctr = prime + else: fctr *= prime + for i in range(slice_len): + d = divisors[i] * fctr + if d not in primitivesp_nos: divisors.append(d) + else: return 0 + last_prime = prime + x = 1; divisors = set(i for i in divisors if i <= difference) + ns = n - (difference + n - sum(divisors)) + if ns < 0: return 1 + for d in divisors: x |= x << d + if x >> ns & 1: primitivesp_nos.add(n); return 0 + else: return 1 + +main() + +end = time() +print("Execution time: ", round(end - start, 2), "s") + +-- -> [100,96] diff --git a/Task/Weird-numbers/Uxntal/weird-numbers.uxnatl b/Task/Weird-numbers/Uxntal/weird-numbers.uxnatl new file mode 100644 index 0000000000..9b1ed1016a --- /dev/null +++ b/Task/Weird-numbers/Uxntal/weird-numbers.uxnatl @@ -0,0 +1,85 @@ +( uxncli weird.rom ) + +|10 @Console &vector $2 &read $1 &pad $5 &write $1 &error $1 +%MOD2 { DIV2k MUL2 SUB2 } +|0000 +@c $2 +@n $2 +@i $1 + +|0100 +( init ) +;str ptext #0a .Console/write DEO + +( main ) +#000c +&sieve + #0000 .c STZ2 + DUP2 DUP2 .n STZ2 divisors + abundance ?{ semiperfection } + clear + INC2 .i LDZ #19 LTH ?&sieve + POP2 +BRK + +@pdec ( short* -- ) + #2710 [ LIT2r 00fb ] + &while ( -- ) + DIV2k #000a DIV2k MUL2 SUB2 SWPr EQUk OVR STHkr EQU AND ?{ + DUP [ LIT "0 ] ADD #19 DEO + INCr } + POP2 #000a DIV2 SWPr INCr STHkr ?&while + POP2r POP2 POP2 JMP2r + +@ptext ( str* -- ) + &while + LDAk .Console/write DEO + INC2 LDAk ?&while + POP2 + JMP2r + +@divisors ( short* -- ) + #0000 + &loop + OVR2 OVR2 MOD2 #0000 GTH2 ?{ DUP2 ;divs .c LDZ2 STH2k ADD2 STA2 STH2r INC2 INC2 .c STZ2 } + INC2 GTH2k ?&loop POP2 POP2 + JMP2r + +@abundance ( -- flag ) + #0000 STH2 + ;divs + &while + LDA2k STH2 ADD2r + #0002 ADD2 + LDA2k NIP ?&while + POP2 + STH2r .n LDZ2 GTH2 ?{ #01 JMP2r } #00 ( returns 1 when not abundant to skip semiperfection check in main ) + JMP2r + +@semiperfection ( -- ) + #0001 ;divs .c LDZ2 ADD2 STA2 + #0000 + &for + .n LDZ2 + &loop + OVR2 OVR2 SWP2 #0002 MUL2 ;divs ADD2 LDA2 SUB2 #0002 MUL2 + ;divs .c LDZ2 ADD2 ADD2 LDA2 + #0000 EQU2 ?{ #0001 OVR2 #0002 MUL2 ;divs .c LDZ2 ADD2 ADD2 STA2 } + #0001 SUB2 + OVR2 #0002 MUL2 ;divs ADD2 LDA2 GTH2k STH EQU2k STHr ORA NIP NIP ?&loop POP2 + + INC2 DUP2 .c LDZ2 #0002 DIV2 LTH2 ?&for POP2 + ;divs .c LDZ2 ADD2 .n LDZ2 #0002 MUL2 ADD2 LDA2 NIP ?{ .n LDZ2 pdec #20 #18 DEO .i LDZk INC SWP STZ JMP2r } + JMP2r + +@clear ( -- ) + ;divs + .n LDZ2 .c LDZ2 ADD2 + &while + SWP2 #0000 SWP2 STA2k NIP2 + INC2 INC2 + SWP2 #0001 SUB2 #0000 GTH2k NIP NIP ?&while POP2 POP2 + JMP2r + +@str "The 20 "first 20 "25 20 "weird 20 "numbers: 00 +@divs diff --git a/Task/Window-creation/PascalABC.NET/window-creation.pas b/Task/Window-creation/PascalABC.NET/window-creation.pas new file mode 100644 index 0000000000..6209d1e8d1 --- /dev/null +++ b/Task/Window-creation/PascalABC.NET/window-creation.pas @@ -0,0 +1,5 @@ +uses GraphWPF; + +begin + +end. diff --git a/Task/Wireworld/11l/wireworld.11l b/Task/Wireworld/11l/wireworld.11l index 6ea83c817c..b6191e28d2 100644 --- a/Task/Wireworld/11l/wireworld.11l +++ b/Task/Wireworld/11l/wireworld.11l @@ -11,14 +11,7 @@ V w = . . Ht.. ......’ -T WW - [[Char]] world - Int w - Int h - F (world, w, h) - .world = world - .w = w - .h = h +T WW = ([[Char]] world, Int w, Int h) F readfile(f) V world = f.map(row -> row.rtrim(Array[Char]("\r\n"))) diff --git a/Task/Word-frequency/PascalABC.NET/word-frequency.pas b/Task/Word-frequency/PascalABC.NET/word-frequency.pas new file mode 100644 index 0000000000..759f414c6a --- /dev/null +++ b/Task/Word-frequency/PascalABC.NET/word-frequency.pas @@ -0,0 +1,3 @@ +## +ReadAllText('135-0.txt').ToLower.MatchValues('\w+').EachCount + .OrderByDescending(w -> w.Value).Take(10).PrintLines diff --git a/Task/Word-ladder/APL/word-ladder.apl b/Task/Word-ladder/APL/word-ladder.apl new file mode 100644 index 0000000000..8138277c6e --- /dev/null +++ b/Task/Word-ladder/APL/word-ladder.apl @@ -0,0 +1,23 @@ +wordladder←{ + from to←⍵ + dict←((≢¨⍺)=≢to)/⍺ + + dict{ + match←(⊂to)≡¨⊃∘⌽¨⍵ + ∨/match:⊃match/⍵ + 0∊≢¨⍺⍵:⍬ + word←⊃⌽ladder←⊃⍵ + next←(1=⍺+.≠¨⊂word)/⍺ + (⍺~next)∇(1↓⍵),(⊂ladder),¨⊂¨next + }⊂⊂from +} +task←{ + dict←(~dict∊⎕TC)⊆dict←⊃⎕NGET'unixdict.txt' + pairs←('boy' 'man')('girl' 'lady')('john' 'jane')('child' 'adult') + ⎕←↑↑{ + hdr←⍺,' → ',⍵,': ' + ladder←dict wordladder ⍺ ⍵ + 0=≢ladder:hdr,'impossible' + hdr,1↓∊'→',¨ladder + }/¨pairs +} diff --git a/Task/Word-ladder/Ada/word-ladder.ada b/Task/Word-ladder/Ada/word-ladder.ada new file mode 100644 index 0000000000..1baca530f6 --- /dev/null +++ b/Task/Word-ladder/Ada/word-ladder.ada @@ -0,0 +1,146 @@ +pragma Ada_2022; +with Ada.Containers.Multiway_Trees; +with Ada.Containers.Vectors; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; +procedure Word_Ladder is + + DICT_FILENAME : constant String := "unixdict.txt"; + MAX_DEPTH : constant Positive := 50; + + subtype LC_Chars is Character range 'a' .. 'z'; + + type Word_Node_T is record + Level : Positive; + Word : Unbounded_String; + end record; + + package Word_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + package Dict_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + + package Word_Trees is new Ada.Containers.Multiway_Trees (Word_Node_T); + use Word_Trees; + Word_Tree : Tree; + Solved : Boolean; + Solution : Cursor; + + function Load_Candidate_Words (Dict_Filename : String; Word_Len : Positive) + return Dict_Vectors.Vector is + Dict_File : File_Type; + Read_Word : Unbounded_String; + Cands : Dict_Vectors.Vector; + Valid : Boolean; + C : Character; + begin + Open (File => Dict_File, Mode => In_File, Name => Dict_Filename); + while not End_Of_File (Dict_File) loop + Read_Word := Get_Line (Dict_File); + if Length (Read_Word) = Word_Len then + Valid := True; + for Ix in 1 .. Word_Len loop + C := Element (Read_Word, Ix); + Valid := C in LC_Chars; + exit when not Valid; + end loop; + if Valid then Cands.Append (Read_Word); end if; + end if; + end loop; + Close (Dict_File); + return Cands; + end Load_Candidate_Words; + + function Mutate (Word : Unbounded_String; Dict : in out Dict_Vectors.Vector) + return Word_Vectors.Vector is + Mutations : Word_Vectors.Vector; + Poss_Word : Unbounded_String; + begin + for Ix in 1 .. Length (Word) loop + for Letter in LC_Chars loop + if Letter /= Element (Word, Ix) then + Poss_Word := Word; + Replace_Element (Poss_Word, Ix, Letter); + if Dict.Contains (Poss_Word) then + Mutations.Append (Poss_Word); + Dict.Delete (Dict.Find_Index (Poss_Word)); + end if; + end if; + end loop; + end loop; + return Mutations; + end Mutate; + + procedure Recurse_Tree (Start_Pos : Cursor; + Level : Positive; + Target : Unbounded_String; + Dict : in out Dict_Vectors.Vector) is + Pos : Cursor := Start_Pos; + Mutations : Word_Vectors.Vector; + New_Node : Word_Node_T; + begin + while not Solved and then Pos /= No_Element loop + if Element (Pos).Level = Level then + Mutations := Mutate (Element (Pos).Word, Dict); + if not Word_Vectors.Is_Empty (Mutations) then + for Word of Mutations loop + New_Node.Level := Level + 1; + New_Node.Word := Word; + Append_Child (Word_Tree, Pos, New_Node); + if Word = Target then + Solved := True; + Solution := Pos; + end if; + end loop; + end if; + end if; + if not Solved then + Recurse_Tree (First_Child (Pos), Level, Target, Dict); + end if; + Pos := Next_Sibling (Pos); + end loop; + end Recurse_Tree; + + procedure Ladder (Start_S, Target_S : String) is + Dictionary : Dict_Vectors.Vector; + Level : Positive := 1; + Word_Node : Word_Node_T; + Start, Target : Unbounded_String; + Start_Pos : Cursor; + Output : Unbounded_String; + begin + if Start_S'Length /= Target_S'Length then + Put_Line ("ERROR: Start and Target words must be same length."); + return; + end if; + Dictionary := Load_Candidate_Words (DICT_FILENAME, Start_S'Length); + Start := To_Unbounded_String (Start_S); + Target := To_Unbounded_String (Target_S); + Solved := False; + Word_Node.Level := 1; + Word_Node.Word := Start; + Word_Tree := Empty_Tree; + Word_Tree.Insert_Child (Word_Tree.Root, No_Element, Word_Node); + Start_Pos := Find (Word_Tree, Word_Node); + while Level <= MAX_DEPTH and then not Solved loop + Recurse_Tree (Start_Pos, Level, Target, Dictionary); + Level := @ + 1; + end loop; + if not Solved then + Put_Line (Start & " -> " & Target & " - No solution found at depth" & MAX_DEPTH'Image); + else + while not Is_Root (Solution) loop + Word_Node := Element (Solution); + Output := Word_Node.Word & " -> " & Output; + Solution := Parent (Solution); + end loop; + Put_Line (Output & Target); + end if; + end Ladder; +begin + Ladder ("boy", "man"); + Ladder ("girl", "lady"); + Ladder ("jane", "john"); + Ladder ("child", "adult"); + Ladder ("ada", "god"); + Ladder ("rust", "hell"); +end Word_Ladder; diff --git a/Task/Word-ladder/Refal/word-ladder.refal b/Task/Word-ladder/Refal/word-ladder.refal new file mode 100644 index 0000000000..4da2fac7e6 --- /dev/null +++ b/Task/Word-ladder/Refal/word-ladder.refal @@ -0,0 +1,95 @@ +$ENTRY Go { + , : e.Dict + = + + + ; +}; + +DisplayLadder { + (e.Dict) (e.From) (e.To), + e.From ' -> ' e.To ': ': e.Header, + : { + Impossible = ; + Result e.Words = ') e.Words>>; + }; +}; + +Join { + (e.Join) = ; + (e.Join) (e.Word) = e.Word; + (e.Join) (e.Word) e.Words = e.Word e.Join ; +}; + +ReadFile { + s.Chan e.File = + + ; + (s.Chan), : { + 0 = ; + e.Line = (e.Line) ; + }; +}; + +Filter { + (e.Fn) = ; + (e.Fn) t.Item e.Items, : { + True = t.Item ; + False = ; + }; +}; + +SameLen { + (e.Word1) (e.Word2), + : s.Len e.Word1, + : s.Len e.Word2 = True; + (e.Word1) (e.Word2) = False; +}; + +Diffs { + () () = 0; + (s.X e.Word1) (s.X e.Word2) = ; + (s.X e.Word1) (s.Y e.Word2) = <+ 1 >; +}; + +OneDiff { + t.Word1 t.Word2, : { + 1 = True; + s.Diffs = False; + }; +}; + +Ladder { + (e.Dict) t.From t.To, + : e.Dict2 = + ; +}; + +Ladder2 { + (e.Ladders) (e.Dict) t.To, + e.Ladders: e.X (e.Words t.To) e.Y = Result e.Words t.To; + + (e.Ladders) () t.To = Impossible; + () (e.Dict) t.To = Impossible; + + ((e.Ladder) e.Ladders) (e.Dict) t.To, + e.Ladder: e.1 t.Last, + : e.NextWords, + : e.NextDict, + : e.NextLadders + = ; +}; + +RemoveAll { + (e.Remove) = ; + (e.Remove) t.Word e.Words, e.Remove: { + e.X t.Word e.Y = ; + e.Remove = t.Word ; + }; +}; + +AddAll { + (e.Ladder) = ; + (e.Ladder) t.Word e.Words = + (e.Ladder t.Word) ; +}; diff --git a/Task/Word-ladder/SETL/word-ladder.setl b/Task/Word-ladder/SETL/word-ladder.setl new file mode 100644 index 0000000000..200d0c2766 --- /dev/null +++ b/Task/Word-ladder/SETL/word-ladder.setl @@ -0,0 +1,45 @@ +program word_ladder; + dict := read_dictionary("unixdict.txt"); + testpairs := [['boy', 'man'], ['girl', 'lady'], ['john', 'jane'], ['child', 'adult']]; + + loop for [fromWord, toWord] in testpairs do + l := ladder(dict, fromWord, toWord); + if l = om then + print(fromWord, '->', toWord, 'impossible'); + else + print(fromWord, '->', toWord, l); + end if; + end loop; + + proc ladder(dict, fromWord, toWord); + dict := {word : word in dict | #word = #fromWord}; + ladders := [[fromWord]]; + dict less:= fromWord; + loop while ladders /= [] do + l fromb ladders; + next := {word : word in onediff(dict, l(#l))}; + dict -:= next; + nextls := [l + [word] : word in next]; + if exists l in nextls | l(#l) = toWord then + return l; + end if; + ladders +:= nextls; + end loop; + return om; + end proc; + + proc onediff(rw dict, word); + return {other : other in dict | #other = #word and diffs(word, other) = 1}; + end proc; + + proc diffs(word1, word2); + return +/[if word1(i) = word2(i) then 0 else 1 end : i in [1..#word1]]; + end proc; + + proc read_dictionary(file); + dictfile := open(file, 'r'); + dict := {getline(dictfile) : until eof(dictfile)}; + close(dictfile); + return dict; + end proc; +end program; diff --git a/Task/Word-search/Ada/word-search.ada b/Task/Word-search/Ada/word-search.ada new file mode 100644 index 0000000000..712854b9c1 --- /dev/null +++ b/Task/Word-search/Ada/word-search.ada @@ -0,0 +1,259 @@ +pragma Ada_2022; +with Ada.Containers; use Ada.Containers; +with Ada.Containers.Vectors; +with Ada.Numerics.Discrete_Random; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; + +procedure Word_Search is + + MIN_WORDS : constant Positive := 25; + MIN_WORD_LEN : constant Positive := 3; + MAX_WORD_LEN : constant Positive := 9; + SIDE_LEN : constant Positive := 10; + MESSAGE : constant String := "ROSETTACODE"; + DICT_FILENAME : constant String := "unixdict.txt"; + + type Directions is (N, NE, E, SE, S, SW, W, NW); + type Move is record + DX, DY : Integer; + end record; + type Moves_Arr is array (Directions) of Move; + Moves : constant Moves_Arr := [ + N => (0, -1), NE => (1, -1), E => (1, 0), SE => (1, 1), + S => (0, 1), SW => (-1, 1), W => (-1, 0), NW => (-1, -1) + ]; + subtype Grid_Dimension is Positive range 1 .. SIDE_LEN; + type Matrix is array (Grid_Dimension, Grid_Dimension) of Character; + subtype LC_Chars is Character range 'a' .. 'z'; + subtype Valid_Lengths is Positive range MIN_WORD_LEN .. MAX_WORD_LEN; + + package Word_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + type Dictionary is array (Valid_Lengths) of Word_Vectors.Vector; + Dict : Dictionary; + + type Placement is record + Word : Unbounded_String; + Start : Unbounded_String; + end record; + package Placement_Vectors is new Ada.Containers.Vectors (Positive, Placement); + Placings : Placement_Vectors.Vector; + + subtype Ten_K is Positive range 1 .. 10000; + package Rand_Dimension is new Ada.Numerics.Discrete_Random (Grid_Dimension); + package Rand_Dir is new Ada.Numerics.Discrete_Random (Directions); + package Rand_Len is new Ada.Numerics.Discrete_Random (Valid_Lengths); + package Rand_10k is new Ada.Numerics.Discrete_Random (Ten_K); + Dimension_Gen : Rand_Dimension.Generator; + Dir_Gen : Rand_Dir.Generator; + Len_Gen : Rand_Len.Generator; + Ten_K_Gen : Rand_10k.Generator; + + procedure Load_Dictionary (Filename : String) is + Dict_File : File_Type; + Dict_Word : Unbounded_String; + Dict_Word_Len : Positive; + Word_OK : Boolean; + begin + Open (File => Dict_File, Mode => In_File, Name => Filename); + while not End_Of_File (Dict_File) loop + Dict_Word := Get_Line (Dict_File); + Dict_Word_Len := Length (Dict_Word); + if Dict_Word_Len >= MIN_WORD_LEN and then + Dict_Word_Len <= MAX_WORD_LEN + then + Word_OK := True; + for C of To_String (Dict_Word) loop + if C not in LC_Chars then + Word_OK := False; + exit; + end if; + end loop; + if Word_OK then + Dict (Dict_Word_Len).Append (Dict_Word); + end if; + end if; + end loop; + end Load_Dictionary; + + function Pick_Random_Word return Unbounded_String is + Word_Length : Positive := Rand_Len.Random (Len_Gen); + Rand : constant Natural := Rand_10k.Random (Ten_K_Gen); + Word_Ix : Positive; + begin + Word_Length := Rand_Len.Random (Len_Gen); + if Word_Length > 4 then -- Reduce number of words > 4 chars + Word_Length := Rand_Len.Random (Len_Gen); + end if; + Word_Ix := Positive (Rand) mod (Positive (Dict (Word_Length).Length) - 1) + 1; + return Dict (Word_Length) (Word_Ix); + end Pick_Random_Word; + + function Not_Too_Long (X, Y : Grid_Dimension; Len : Positive; Dir : Directions) return Boolean is + begin + case Dir is + when N => return Y - Len > 0; + when S => return Y + Len <= SIDE_LEN; + when E => return X + Len <= SIDE_LEN; + when W => return X - Len > 0; + when NE => return X + Len <= SIDE_LEN and then Y - Len > 0; + when SW => return Y + Len <= SIDE_LEN and then X - Len > 0; + when SE => return Y + Len <= SIDE_LEN and then X + Len <= SIDE_LEN; + when NW => return Y - Len > 0 and then X - Len > 0; + end case; + end Not_Too_Long; + + function Is_Empty (G : Matrix; Row, Col : Positive) return Boolean is + (G (Row, Col) = ' '); + + function Count_Empties (G : Matrix) return Natural is + Count : Natural := 0; + begin + for Row in Grid_Dimension loop + for Col in Grid_Dimension loop + Count := Count + (if Is_Empty (G, Row, Col) then 1 else 0); + end loop; + end loop; + return Count; + end Count_Empties; + + function Can_Place (G : Matrix; X, Y : Grid_Dimension; Word : Unbounded_String; Dir : Directions) + return Boolean is + GX : Grid_Dimension := X; + GY : Grid_Dimension := Y; + Len : constant Positive := Length (Word); + begin + for C in 1 .. Len loop + if not Is_Empty (G, GX, GY) and then + G (GX, GY) /= Element (Word, C) + then + return False; + else + GX := GX + Moves (Dir).DX; + GY := GY + Moves (Dir).DY; + end if; + end loop; + return True; + end Can_Place; + + procedure Insert_Word (G : in out Matrix; + X, Y : Grid_Dimension; + Dir : Directions; + Word : Unbounded_String) is + -- We assume it fits. You've checked first haven't you! + GX : Grid_Dimension := X; + GY : Grid_Dimension := Y; + begin + for C in 1 .. Length (Word) loop + G (GX, GY) := Element (Word, C); + GX := GX + Moves (Dir).DX; + GY := GY + Moves (Dir).DY; + end loop; + end Insert_Word; + + function Try_To_Place_Word (G : in out Matrix; Word : Unbounded_String; Max_Tries : Positive) + return Boolean is + -- Attempt to place the given word in the grid, return success or failure. + X1, Y1 : Grid_Dimension; + Dir : Directions; + Try : Positive := 1; + Place : Placement; + begin + while Try <= Max_Tries loop + X1 := Rand_Dimension.Random (Dimension_Gen); + Y1 := Rand_Dimension.Random (Dimension_Gen); + Dir := Rand_Dir.Random (Dir_Gen); + if Not_Too_Long (X1, Y1, Length (Word), Dir) and then + Can_Place (G, X1, Y1, Word, Dir) + then + Insert_Word (G, X1, Y1, Dir, Word); + Place.Word := Word; + Place.Start := To_Unbounded_String (X1'Image & LC_Chars'Val (Integer (Y1) + 64)); + Placings.Append (Place); + return True; + end if; + Try := Try + 1; + end loop; + return False; + end Try_To_Place_Word; + + procedure Print_Matrix (M : Matrix) is + begin + Put_Line (" A B C D E F G H I J"); New_Line; + for Row in Grid_Dimension loop + Put (Row'Image); + Set_Col (6); + for Col in Grid_Dimension loop + Put (M (Row, Col) & " "); + end loop; + New_Line; + end loop; + New_Line; + end Print_Matrix; + + function Place_Message (G : in out Matrix; Msg : String) return Boolean is + -- Attempt to put message in grid, return False if unable. + Msg_Posn : Positive := 1; + begin + for Row in Grid_Dimension loop + for Col in Grid_Dimension loop + if Is_Empty (G, Row, Col) then + G (Row, Col) := Msg (Msg_Posn); + if Msg_Posn = Msg'Length then + return True; + else + Msg_Posn := Msg_Posn + 1; + end if; + end if; + end loop; + end loop; + return False; + end Place_Message; + + Grid : Matrix; + Words_Placed : Natural; + Message_Placed : Boolean; + A_Word : Unbounded_String; + Attempt : Positive; + Col : Positive_Count := 1; +begin + Load_Dictionary (DICT_FILENAME); + Rand_Dimension.Reset (Dimension_Gen); + Rand_Dir.Reset (Dir_Gen); + Rand_Len.Reset (Len_Gen); + Rand_10k.Reset (Ten_K_Gen); + loop + Grid := [others => [others => ' ']]; + Words_Placed := 0; Message_Placed := False; Placings.Clear; + Attempt := 1; + Builder : + loop + A_Word := Pick_Random_Word; + if Try_To_Place_Word (Grid, A_Word, 50) then + Words_Placed := @ + 1; + end if; + if Count_Empties (Grid) = MESSAGE'Length then + if Place_Message (Grid, MESSAGE) then + Message_Placed := True; + exit Builder; + end if; + elsif Count_Empties (Grid) < MESSAGE'Length then + -- Put_Line ("No room for message, giving up."); + exit Builder; + elsif Attempt > 1000 then + Put_Line ("Giving up after 1000 tries."); + exit Builder; + end if; + Attempt := Attempt + 1; + end loop Builder; + exit when Words_Placed >= MIN_WORDS and then Message_Placed; + end loop; + Print_Matrix (Grid); + Put_Line ("Words placed:" & Words_Placed'Image); + for P of Placings loop + Set_Col (Col); Put (P.Word); + Set_Col (Col + 9); Put (P.Start); + Col := (if Col < 61 then Col + 20 else 1); + end loop; +end Word_Search; diff --git a/Task/Word-wheel/Ada/word-wheel.ada b/Task/Word-wheel/Ada/word-wheel.ada new file mode 100644 index 0000000000..73db7574e6 --- /dev/null +++ b/Task/Word-wheel/Ada/word-wheel.ada @@ -0,0 +1,56 @@ +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; +procedure Wordwheel is + Compulsory_Ix : constant Positive := 5; + Min_Length : constant Positive := 3; + + function Char_Posn (Str : Unbounded_String; C : Character) return Natural is + begin + for Ix in 1 .. Length (Str) loop + if Element (Str, Ix) = C then + return Ix; + end if; + end loop; + return 0; + end Char_Posn; + + procedure Search (Dict_Filename : String; Wheel : String) is + Dict_File : File_Type; + Allowed : constant String := To_Lower (Wheel); + Required_Char : constant String (1 .. 1) := "" & Allowed (Compulsory_Ix); + Available, Dict_Word : Unbounded_String; + Dict_Word_Len : Positive; + Matched : Boolean; + Posn : Natural; + begin + Open (File => Dict_File, Mode => In_File, Name => Dict_Filename); + while not End_Of_File (Dict_File) loop + Dict_Word := Get_Line (Dict_File); + Dict_Word_Len := Length (Dict_Word); + if Dict_Word_Len >= Min_Length and then + Dict_Word_Len <= Wheel'Length and then + Ada.Strings.Unbounded.Count (Dict_Word, Required_Char) > 0 + then + Available := To_Unbounded_String (Allowed); + Matched := True; + for i in 1 .. Dict_Word_Len loop + Posn := Char_Posn (Available, Element (Dict_Word, i)); + if Posn > 0 then + Delete (Source => Available, From => Posn, Through => Posn); + else + Matched := False; + exit; + end if; + end loop; + if Matched then + Put_Line (Dict_Word); + end if; + end if; + end loop; + Close (Dict_File); + end Search; +begin + Search ("unixdict.txt", "ndeokgelw"); +end Wordwheel; diff --git a/Task/Word-wheel/Lua/word-wheel.lua b/Task/Word-wheel/Lua/word-wheel-1.lua similarity index 100% rename from Task/Word-wheel/Lua/word-wheel.lua rename to Task/Word-wheel/Lua/word-wheel-1.lua diff --git a/Task/Word-wheel/Lua/word-wheel-2.lua b/Task/Word-wheel/Lua/word-wheel-2.lua new file mode 100644 index 0000000000..15ec4ccda0 --- /dev/null +++ b/Task/Word-wheel/Lua/word-wheel-2.lua @@ -0,0 +1,15 @@ +-- Algorithm is from Ruby implementation. +local wheel = arg[1] or 'ndeoKgelw' -- wheel is 1st argument +wheel = wheel:lower() +local middle = wheel:sub(5, 5) +assert(#middle == 1) +for line in io.lines() do -- get dictionary from standard input + local word = line:lower() + if word:find(middle) and #word >= 3 then + for wheel_char in wheel:gmatch('.') do + word = word:gsub(wheel_char, '', 1) + end -- for + if #word == 0 then io.write(line:lower() .. ' ') end + end -- if +end -- for +print '' diff --git a/Task/Word-wrap/PascalABC.NET/word-wrap.pas b/Task/Word-wrap/PascalABC.NET/word-wrap.pas new file mode 100644 index 0000000000..08a58e9720 --- /dev/null +++ b/Task/Word-wrap/PascalABC.NET/word-wrap.pas @@ -0,0 +1,40 @@ +function Wrap(words: sequence of string; lineWidth: integer): sequence of string; +begin + var currentWidth := 0; + foreach var word in words do + begin + if currentWidth <> 0 then + if currentWidth + word.Length < lineWidth then + begin + currentWidth += 1; + yield ' '; + end + else + begin + currentWidth := 0; + yield NewLine; + end; + currentWidth += word.Length; + yield word; + end; +end; + +function Wrap(text: string; lineWidth: integer): string + := Wrap(text.ToWords(' '#13#10),lineWidth).JoinToString(''); + +begin + var text := ''' +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien +vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu +pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus +consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque +penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt +purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel +felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta +tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, +condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed +venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu +nibh. +'''; + Wrap(text,50).Println; +end. diff --git a/Task/Wordiff/Jq/wordiff.jq b/Task/Wordiff/Jq/wordiff.jq new file mode 100644 index 0000000000..c0cec7cb3b --- /dev/null +++ b/Task/Wordiff/Jq/wordiff.jq @@ -0,0 +1,108 @@ +include "MRG32k3a" {search: "."}; # see comment above + +### Generic functions + +# Determine if stream is non-decreasing +def is_sorted(stream): + first(foreach stream as $s ( null; + if . == null or $s >= .[0] then [$s] + else 0 + end; + select(. == 0) ) ) + // 1 + | . == 1; + +# Write to stderr +def inform(msg): + . as $in + | ("\(msg)\n" | stderr) + | $in; + +# q means quit +def read($prompt; $regex): + def r: + ($prompt | stderr | empty), + (try ((input + | if . == "q" then halt + else select(test($regex)) + end) // r) + catch if . == "break" then halt else r end ); + r; + +# Returns levenshteinDistance(s1; $s2) <= $max +# A recursive algorithm is good enough if $max is small +def levenshteinDistance($s1; $s2; $max): + def lev: + . as [$s1, $s2, $max] + | if ($s1|length) == 0 then ($s2|length) <= $max + elif ($s2|length) == 0 then ($s1|length) <= $max + elif $s1[:1] == $s2[:1] + then [$s1[1:], $s2[1:], $max] | lev + else ($s1|length) <= $max + or ($s2|length) <= $max + or ([$s1[1:], $s2, $max-1] | lev) + or ([$s1, $s2[1:], $max-1] | lev) + or ([$s1[1:], $s2[1:], $max-1] | lev) + end ; + [$s1, $s2, $max] | lev; + +##### The Wordiff Game + +# Output: the sorted list of words +# The sort is skipped if we can readily determine the list is already sorted +def words: + [$dict | splits(" *\n *")] + | if is_sorted(.[]) then . + else sort + end; + +def player1: read("Player 1, please enter your name : "; "."); +def player2: read("Player 2, please enter your name : "; "."); + +def round: + .words as $words + | read("\(.player), enter your word: "; ".") as $word + | ($word|length) as $len + | .ok = false + | if $len < 3 + then inform("Words must be at least three letters long.") + elif $word == .prevWord + then inform("You must change the previous word.") + elif .used[$word] + then inform("The word \"\($word)\" has been used before.") + elif # not in dictionary + # if $words is not sorted: ($word | IN($words[]) | not) + # binary search: + ($words | bsearch($word) < 0) + then inform("Not in dictionary.") + + elif levenshteinDistance($word; .prevWord; 1) + #### Good to go + then .ok = true + | .prevLen = ($word|length) + | .prevWord = $word + | .used[$word] = true + | .player = (if .player == .player1 then .player2 else .player1 end) + else inform("Sorry. Only one addition, deletion or alteration is allowed.") + end + | if (.ok|not) then inform("Please retry. The current word is: \(.prevWord)") end + | round ; + +def play: + player1 as $player1 + | { player1: $player1, + player2: ( player2 | if . == $player1 then . + "2" else . end) + } + | inform("Reading and perhaps sorting the list of words takes a few seconds... ") + | inform("Meanwhile note that you can quit by entering q at a prompt.") + | .words = words + # Avoid storing the subset of words needed to make a random selection: + | (.words | map(select(length | IN(3,4))) | .[length | prn(1)[]]) as $firstWord + | .prevLen = ($firstWord|length) + | .prevWord = $firstWord + | .used = {($firstWord): true} # a JSON object for efficiency + | .player = .player1 + | "\nThe first word is: \($firstWord)", + round; + +play diff --git a/Task/Write-entire-file/PascalABC.NET/write-entire-file.pas b/Task/Write-entire-file/PascalABC.NET/write-entire-file.pas new file mode 100644 index 0000000000..7039e6432a --- /dev/null +++ b/Task/Write-entire-file/PascalABC.NET/write-entire-file.pas @@ -0,0 +1,2 @@ +## +WriteAllText('a.txt','string'); diff --git a/Task/Write-to-Windows-event-log/FreeBASIC/write-to-windows-event-log.basic b/Task/Write-to-Windows-event-log/FreeBASIC/write-to-windows-event-log.basic new file mode 100644 index 0000000000..249367b5b2 --- /dev/null +++ b/Task/Write-to-Windows-event-log/FreeBASIC/write-to-windows-event-log.basic @@ -0,0 +1,36 @@ +Dim As String argV(1 To 5) +Dim Shared As String t() + +Sub Split (cadena As String, t() As String, sep As String = " ") + Dim As Integer i, j = 0 + Dim As String word = "" + For i = 1 To Len(cadena) + If Mid(cadena, i, 1) <> sep Then + word &= Mid(cadena, i, 1) + Else + Redim Preserve t(j) + t(j) = word + word = "" + j += 1 + End If + Next i + If word <> "" Then + Redim Preserve t(j) + t(j) = word + End If +End Sub + +Split(Command, t()) + +#ifdef __FB_WIN32__ + If Ubound(t) <> 3 Then + Print "Usage: "; Command(0); " " + Else + For i As Integer = 1 To 4 + argV(i) = t(i-1) + Next i + Shell "EventCreate /t " & argV(1) & " /id " & argV(2) & " /l APPLICATION /so " & argV(3) & " /d """ & argV(4) & """" + End If +#else + Print "Not implemented for *nix, only Windows." +#endif diff --git a/Task/Write-to-Windows-event-log/PascalABC.NET/write-to-windows-event-log.pas b/Task/Write-to-Windows-event-log/PascalABC.NET/write-to-windows-event-log.pas new file mode 100644 index 0000000000..ea94fb0698 --- /dev/null +++ b/Task/Write-to-Windows-event-log/PascalABC.NET/write-to-windows-event-log.pas @@ -0,0 +1,7 @@ +uses System.Diagnostics; + +begin + if not EventLog.SourceExists('MyApp') then + EventLog.CreateEventSource('MyApp', 'Application'); + EventLog.WriteEntry('MyApp', 'Hello from PABC!'); +end. diff --git a/Task/XML-DOM-serialization/PascalABC.NET/xml-dom-serialization.pas b/Task/XML-DOM-serialization/PascalABC.NET/xml-dom-serialization.pas new file mode 100644 index 0000000000..5e75bd8059 --- /dev/null +++ b/Task/XML-DOM-serialization/PascalABC.NET/xml-dom-serialization.pas @@ -0,0 +1,19 @@ +{$reference System.Xml.Serialization.dll} +{$reference System.Xml.dll} +uses System.Xml; +uses System.Xml.Serialization; + +type + [XmlRoot('root')] + ExampleXML = class + public + [XmlElementAttribute('element')] + element := 'My text'; + end; + +begin + var xmlnamespace := new XmlSerializerNamespaces(); + xmlnamespace.Add('', ''); + var writer := XmlWriter.Create('output.xml'); + (new XmlSerializer(typeof(ExampleXML))).Serialize(writer, new ExampleXML(), xmlnamespace); +end. diff --git a/Task/XML-Input/PascalABC.NET/xml-input.pas b/Task/XML-Input/PascalABC.NET/xml-input.pas new file mode 100644 index 0000000000..d1feafbcee --- /dev/null +++ b/Task/XML-Input/PascalABC.NET/xml-input.pas @@ -0,0 +1,20 @@ +{$reference System.Xml.Linq.dll} +{$reference System.Xml.XDocument.dll} +uses System.Xml.Linq; + +begin + var XMLText := ''' + + + + + + + + + + '''; + var xmlDoc := XDocument.Parse(XMLText); + var q := xmlDoc.Descendants('Student').Select(p -> p.Attribute('Name')); + q.PrintLines(item -> item.Value); +end. diff --git a/Task/XML-Input/Vim-Script/xml-input.vim b/Task/XML-Input/Vim-Script/xml-input.vim new file mode 100644 index 0000000000..fff3a4844a --- /dev/null +++ b/Task/XML-Input/Vim-Script/xml-input.vim @@ -0,0 +1,9 @@ +let students_xml = readfile('XML-Input.xml') +call filter(students_xml, 'v:val =~ " substitute(val, s:s_pat, s:s_sub, 'g')}) +let s:s_pat = '\c\v\�*([a-f][[:xdigit:]]|[[:xdigit:]]{3,7});' +let s:s_sub = '\=nr2char(str2nr(submatch(1), 16), 1)' +call map(students_xml, {_, val -> substitute(val, s:s_pat, s:s_sub, 'g')}) +echo students_xml->writefile('XML-input.out.txt') diff --git a/Task/XML-Output/PascalABC.NET/xml-output.pas b/Task/XML-Output/PascalABC.NET/xml-output.pas new file mode 100644 index 0000000000..fb0e205c2e --- /dev/null +++ b/Task/XML-Output/PascalABC.NET/xml-output.pas @@ -0,0 +1,20 @@ +{$reference System.Xml.Linq.dll} +{$reference System.Xml.XDocument.dll} +uses System.Xml.Linq; + +function CreateXML(characterRemarks: Dictionary ): string; +begin + var remarks := characterRemarks.Select(r -> new XElement('Character', r.Value, new XAttribute('Name', r.Key))); + var xml := new XElement('CharacterRemarks', remarks); + Result := xml.ToString; +end; + +begin + var characterRemarks := Dict( + ('April', 'Bubbly: I''m > Tam and <= Emily' ), + ( 'Tam O''Shanter', 'Burns: "When chapman billies leave the street ..."' ), + ( 'Emily', 'Short & shrift' ) + ); + var xml := CreateXML(characterRemarks); + Writeln(xml); +end. diff --git a/Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs b/Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs new file mode 100644 index 0000000000..c5c8c580aa --- /dev/null +++ b/Task/Yellowstone-sequence/C-sharp/yellowstone-sequence.cs @@ -0,0 +1,73 @@ +internal class Program +{ + private static void Main(string[] args) + { + List yellowStoneList = YellowstoneSequence(30); + + Console.WriteLine("Yellowstone 30"); + + foreach (int i in yellowStoneList) + { + Console.Write(i + " "); + } + } + + private static List YellowstoneSequence(int sequenceCount) + { + List yellowstoneList = [1, 2, 3]; + int num = 4; + List notYellowstoneList = new(); + int yellowSize = 3; + + while (yellowSize < sequenceCount) + { + int found = -1; + + for (int index = 0; index < notYellowstoneList.Count; index++) + { + int test = notYellowstoneList[index]; + + if (GCD(yellowstoneList[yellowSize - 2], test) > 1 && GCD(yellowstoneList[yellowSize - 1], test) == 1) + { + found = index; + break; + } + } + + if (found >= 0) + { + yellowstoneList.Add(notYellowstoneList[found]); + notYellowstoneList.RemoveAt(found); + yellowSize++; + } + else + { + while (true) + { + if (GCD(yellowstoneList[yellowSize - 2], num) > 1 && GCD(yellowstoneList[yellowSize - 1], num) == 1) + { + yellowstoneList.Add(num); + yellowSize++; + num++; + break; + } + + notYellowstoneList.Add(num); + num++; + } + } + } + + return yellowstoneList; + } + + private static int GCD(int a, int b) + { + if (b == 0) + { + return a; + } + + return GCD(b, a % b); + } +} diff --git a/Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua b/Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua new file mode 100644 index 0000000000..05925645dc --- /dev/null +++ b/Task/Yellowstone-sequence/Uiua/yellowstone-sequence.uiua @@ -0,0 +1,6 @@ +Gcd ← ⊙◌⍢(⟜◿:|±,) +NextY ← ⍢(+1|⟨¬≍0_1≡(=1Gcd)⊙(↙¯2)|1⟩∊,,)1 # [a0 a1...an] -> an+1 +N ← 200 +⍢(⊂:NextY| - enum Colour, Nationality, Drink, Smoke, Pet - constant Colours = {"red","white","green","yellow","blue"}, - Nationalities = {"English","Swede","Dane","Norwegian","German"}, - Drinks = {"tea","coffee","milk","beer","water"}, - Smokes = {"Pall Mall","Dunhill","Blend","Blue Master","Prince"}, - Pets = {"dog","birds","cats","horse","zebra"}, - Sets = {Colours,Nationalities,Drinks,Smokes,Pets} +--enum colour, nationality, drink, smoke, pet -- (now implicit) +enum red,white,green,yellow,blue +enum English,Swede,Dane,Norwegian,German +enum tea,coffee,milk,beer,water +enum PallMall,Dunhill,Blend,BlueMaster,Prince +enum dog,birds,cats,horse,zebra - constant tagset5 = tagset(5) -- {1,2,3,4,5}, oft-permuted - sequence perm = repeat(tagset5,5) -- perm[1] is Colour of each house, etc +constant colours = {"red","white","green","yellow","blue"}, + nationalities = {"English","Swede","Dane","Norwegian","German"}, + drinks = {"tea","coffee","milk","beer","water"}, + smokes = {"Pall Mall","Dunhill","Blend","Blue Master","Prince"}, + pets = {"dog","birds","cats","horse","zebra"}, + sets = {colours,nationalities,drinks,smokes,pets} - function house(integer i, string name) - return find(find(name,Sets[i]),perm[i]) - end function +constant p5 = permutes(tagset(5)), -- all permutes of {1,2,3,4,5}, + lp = length(p5) -- (== factorial(5), ie 120) - function left_of(integer h1, integer h2) - return (h1-h2)==1 - end function +// In the following, c1,c2 are indexes to p5, for colour..pet, +// and v1,v2 are from their corresponding enums, so eg p5[c1] +// might be {1,4,3,2,5} for the colours of 1..5 and finding +// v1 in that gives us a house number. Checking the specified +// condition, eg [h] == green && [h+1] == white is then easy. - function next_to(integer h1, integer h2) - return abs(h1-h2)==1 - end function +function left_of(integer c1, v1, c2, v2) + integer h = find(v1,p5[c1]) + return h<=4 and p5[c2][h+1]=v2 +end function - procedure print_house(integer i) - printf(1,"%d:%s,%s,%s,%s,%s\n",{i, - Colours[perm[Colour][i]], - Nationalities[perm[Nationality][i]], - Drinks[perm[Drink][i]], - Smokes[perm[Smoke][i]], - Pets[perm[Pet][i]]}) - end procedure +function same_house(integer c1, v1, c2, v2) + integer h = find(v1,p5[c1]) + return p5[c2][h]=v2 +end function - integer solutions = 0 - sequence solperms = {} - atom t0 = time() - constant factorial5 = factorial(5) - for C=1 to factorial5 do - perm[Colour] = permute(C,tagset5) - if left_of(house(Colour,"green"),house(Colour,"white")) then - for N=1 to factorial5 do - perm[Nationality] = permute(N,tagset5) - if house(Nationality,"Norwegian")==1 - and house(Nationality,"English")==house(Colour,"red") - and next_to(house(Nationality,"Norwegian"),house(Colour,"blue")) then - for D=1 to factorial5 do - perm[Drink] = permute(D,tagset5) - if house(Nationality,"Dane")==house(Drink,"tea") - and house(Drink,"coffee")==house(Colour,"green") - and house(Drink,"milk")==3 then - for S=1 to factorial5 do - perm[Smoke] = permute(S,tagset5) - if house(Colour,"yellow")==house(Smoke,"Dunhill") - and house(Nationality,"German")==house(Smoke,"Prince") - and house(Smoke,"Blue Master")==house(Drink,"beer") - and next_to(house(Drink,"water"),house(Smoke,"Blend")) then - for P=1 to factorial5 do - perm[Pet] = permute(P,tagset5) - if house(Nationality,"Swede")==house(Pet,"dog") - and house(Smoke,"Pall Mall")==house(Pet,"birds") - and next_to(house(Smoke,"Blend"),house(Pet,"cats")) - and next_to(house(Pet,"horse"),house(Smoke,"Dunhill")) then - for i=1 to 5 do - print_house(i) - end for - solutions += 1 - solperms = append(solperms,perm) - end if - end for - end if - end for - end if - end for - end if - end for - end if - end for - printf(1,"%d solution%s found (%3.3fs).\n",{solutions,iff(solutions>1,"s",""),time()-t0}) - for i=1 to length(solperms) do - perm = solperms[i] - printf(1,"The %s owns the Zebra\n",{Nationalities[house(Pet,"zebra")]}) - end for - - with javascript_semantics - for i=2 to 99736 by 2 do - if remainder(i*i,1000000)=269696 then ?i exit end if - end for - - with javascript_semantics - procedure solve_babbage_problem() -- (so that return quits 3 loops) - sequence cands = {0}, -- n-digit candidates (n initially 0) - nextc = {} -- n+1-digit candidates, aka next "" - integer p10 = 1, -- power of 10 for adding prefixes - r10 = 10, -- power of 10 for getting remainder - cc = 0 -- count of calculations - for digits=1 to 6 do -- aka 1..length("269696") - for prefix=0 to 9*p10 by p10 do - for cand in sq_add(prefix,cands) do - atom square = cand*cand - cc += 1 - if remainder(square,r10) = remainder(269696,r10) then - if digits=6 then - printf(1,"Solution: %d (%d calcs)\n",{cand,cc}) - return -- leave solve_babbage_problem() - end if - nextc &= cand -- add candidate for next iteration - end if - end for - end for - {cands,nextc} = {nextc,{}} - printf(1,"%d-digit candidates: %v\n",{digits,cands}) - p10 *= 10 - r10 *= 10 - end for - end procedure - solve_babbage_problem() - - -- demo\rosetta\Cheryls_Birthday.exw - with javascript_semantics - sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, - {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} +-- demo\rosetta\Cheryls_Birthday.exw +with javascript_semantics +sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, + {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} - sequence mwud = repeat(false,12) -- months with unique days +sequence mwud = repeat(false,12) -- months with unique days - for step=1 to 4 do - sequence {months,days} = columnize(choices) - bool impossible = false - for i=length(choices) to 1 by -1 do - integer {m,d} = choices[i] - switch step do - case 1: mwud[m] += (sum(sq_eq(days,d))=1) - case 2: impossible = mwud[m] - case 3: impossible = (sum(sq_eq(days,d))!=1) - case 4: impossible = (sum(sq_eq(months,m))!=1) - end switch - if impossible then - choices[i..i] = {} - end if - end for - end for - ?choices - - with javascript_semantics - enum MONTH, DAY +with javascript_semantics +enum MONTH, DAY - function unique_month(sequence si, months) - return sum(sq_eq(months,si[MONTH]))=1 - end function +function unique_month(sequence si, months) + return sum(sq_eq(months,si[MONTH]))=1 +end function - function unique_day(sequence si, days) - return sum(sq_eq(days,si[DAY]))=1 - end function +function unique_day(sequence si, days) + return sum(sq_eq(days,si[DAY]))=1 +end function - function month_without_unique_day(sequence si, months_with_unique_day) - return not find(si[MONTH],months_with_unique_day) - end function +function month_without_unique_day(sequence si, months_with_unique_day) + return not find(si[MONTH],months_with_unique_day) +end function - sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, - {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} +sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, + {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} - -- Albert knows the month but does not know the day. - -- So the month cannot be unique within the choices. - -- However this step would change nothing, hence omit it. - -- (obvs. non_unique_month() would be as above, but !=1) - --choices = filter(choices,non_unique_month,vslice(choices,MONTH)) +-- Albert knows the month but does not know the day. +-- So the month cannot be unique within the choices. +-- However this step would change nothing, hence omit it. +-- (obvs. non_unique_month() would be as above, but !=1) +--choices = filter(choices,non_unique_month,vslice(choices,MONTH)) - -- Albert also knows that Bernard doesn't know the answer. - -- So the month cannot have a unique day. - sequence unique_days = filter(choices,unique_day,vslice(choices,DAY)) - sequence months_with_unique_day = unique(vslice(unique_days,MONTH)) +-- Albert also knows that Bernard doesn't know the answer. +-- So the month cannot have a unique day. +sequence unique_days = filter(choices,unique_day,vslice(choices,DAY)) +sequence months_with_unique_day = unique(vslice(unique_days,MONTH)) - choices = filter(choices,month_without_unique_day,months_with_unique_day) +choices = filter(choices,month_without_unique_day,months_with_unique_day) - -- Bernard now knows the answer. - -- So the day must be unique within the remaining choices. - choices = filter(choices,unique_day,vslice(choices,DAY)) +-- Bernard now knows the answer. +-- So the day must be unique within the remaining choices. +choices = filter(choices,unique_day,vslice(choices,DAY)) - -- Albert now knows the answer too. - -- So the month must be unique within the remaining choices. - choices = filter(choices,unique_month,vslice(choices,MONTH)) +-- Albert now knows the answer too. +-- So the month must be unique within the remaining choices. +choices = filter(choices,unique_month,vslice(choices,MONTH)) - if length(choices)!=1 then crash("Something went wrong!") end if +if length(choices)!=1 then crash("Something went wrong!") end if - include builtins\timedate.e - timedate td = repeat(0,6) - {td[DT_MONTH],td[DT_DAY]} = choices[1] - printf(1,"Cheryl's birthday is %s\n", {format_timedate(td,"Mmmm ddth")}) - - with javascript_semantics - integer count = 0, n = 11*11, - limit = iff(platform()=JS?10:20) - atom t0 = time(), t1 = time() - while count<limit do - if gcd(n,3*5*7)=1 then - sequence f = prime_factors(n,true,-1) - if length(f)>1 then - string s = sprintf("%d",n) - bool valid = true - for i=1 to length(f) do - if (i=1 or f[i]!=f[i-1]) - and not match(sprintf("%d",f[i]),s) then - valid = false - exit - end if - end for - if valid then - count += 1 - string t = join(apply(f,sprint),"x"), - e = elapsed(time()-t1) - printf(1,"%2d: %,10d = %-17s (%s)\n",{count,n,t,e}) - t1 = time() - end if - end if - end if - n += 2 - end while - printf(1,"Total time:%s\n",{elapsed(time()-t0)}) - - with javascript_semantics - integer count = 0, n = 11*11, - limit = iff(platform()=JS?10:20) - atom t0 = time(), t1 = time() - while count<limit do - string s = sprintf("%d",n) - integer l = floor(sqrt(n)), k = n, f = 3 - bool valid = true - while true do - if remainder(k,f)=0 then - if f<10 or not match(sprintf("%d",f),s) then - valid = false - exit - end if - if f=k then exit end if - k /= f - else - f += 2 - if f>l then - if k=n or not match(sprintf("%d",k),s) then - valid = false - end if - exit - end if - end if - end while - if valid then - count += 1; - string t = join(apply(prime_factors(n,true,-1),sprint),"x"), - e = elapsed(time()-t1) - printf(1,"%2d: %,10d = %-17s (%s)\n",{count,n,t,e}) - t1 = time() - end if - n += 2 - end while - printf(1,"Total time:%s\n",{elapsed(time()-t0)}) - - string deBruijn = "" - for n=0 to 99 do - string a = sprintf("%02d",n) - integer a1 = a[1], - a2 = a[2] - if a2>=a1 then - deBruijn &= iff(a1=a2?a1:a) - for m=n+1 to 99 do - string ms = sprintf("%02d",m) - if ms[2]>a1 then - deBruijn &= a&ms - end if - end for - end if - end for - deBruijn &= "000" - printf(1,"de Bruijn sequence length: %d\n\n",length(deBruijn)) - printf(1,"First 130 characters:\n%s\n\n",deBruijn[1..130]) - printf(1,"Last 130 characters:\n%s\n\n",deBruijn[-130..-1]) +string deBruijn = "" +for n=0 to 99 do + string a = sprintf("%02d",n) + integer a1 = a[1], + a2 = a[2] + if a2>=a1 then + deBruijn &= iff(a1=a2?a1:a) + for m=n+1 to 99 do + string ms = sprintf("%02d",m) + if ms[2]>a1 then + deBruijn &= a&ms + end if + end for + end if +end for +deBruijn &= "000" +printf(1,"de Bruijn sequence length: %d\n\n",length(deBruijn)) +printf(1,"First 130 characters:\n%s\n\n",deBruijn[1..130]) +printf(1,"Last 130 characters:\n%s\n\n",deBruijn[-130..-1]) - function check(string text) - sequence res = {} - sequence found = repeat(0,10000) - integer k - for i=1 to length(text)-3 do - k = to_integer(text[i..i+3],-1)+1 - if k!=0 then found[k] += 1 end if - end for - for i=1 to 10000 do - k = found[i] - if k!=1 then - string e = sprintf("Pin number %04d ",i-1) - e &= iff(k=0?"missing":sprintf("occurs %d times",k)) - res = append(res,e) - end if - end for - k = length(res) - if k=0 then - res = "No errors found" - else - string s = iff(k=1?"":"s") - res = sprintf("%d error%s found:\n ",{k,s})&join(res,"\n ") - end if - return res - end function +function check(string text) + sequence res = {} + sequence found = repeat(0,10000) + integer k + for i=1 to length(text)-3 do + k = to_integer(text[i..i+3],-1)+1 + if k!=0 then found[k] += 1 end if + end for + for i=1 to 10000 do + k = found[i] + if k!=1 then + string e = sprintf("Pin number %04d ",i-1) + e &= iff(k=0?"missing":sprintf("occurs %d times",k)) + res = append(res,e) + end if + end for + k = length(res) + if k=0 then + res = "No errors found" + else + string s = iff(k=1?"":"s") + res = sprintf("%d error%s found:\n ",{k,s})&join(res,"\n ") + end if + return res +end function - printf(1,"Missing 4 digit PINs in this sequence: %s\n", check(deBruijn)) - printf(1,"Missing 4 digit PINs in the reversed sequence: %s\n",check(reverse(deBruijn))) - printf(1,"4444th digit in the sequence: %c (setting it to .)\n", deBruijn[4444]) - deBruijn[4444] = '.' - printf(1,"Re-running checks: %s\n",check(deBruijn)) - - function isNumber(string s) - return scanf(s,"%f")!={} - -- Alt: isNumberString(object s) and - -- return string(s) and scanf(s,"%f")!={}, or even - -- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={} - end function +function isNumber(string s) + return scanf(s,"%f")!={} +-- Alt: isNumberString(object s) and +-- return string(s) and scanf(s,"%f")!={}, or even +-- return string(s) and scanf(substitute(trim(s),",",""),"%f")!={} +end function - constant tests = {"#a","#A","0xA","0(16)A","#FF","255","0", - "0.","0.0","000.000","0e0","0e-2000"," ", - ".14",".05","-5.2","0xf","ten","1B","#1B", - " 12 ",trim(" 12 "),"1","0o16","0o18", - "0b10101111_11110000_11110000_00110011", - "1_000","50e","+123","+ 123","-0b10101", - "NaN","+.345","12..34","12e3.4","0-2", - "192.168.0.1","1.2e","1 2","12.34","", - "beef","#beef","1,000,000","Inf","1/2", - "1.5e+27","0x10.5","1."} +constant tests = {"#a","#A","0xA","0(16)A","#FF","255","0", + "0.","0.0","000.000","0e0","0e-2000"," ", + ".14",".05","-5.2","0xf","ten","1B","#1B", + " 12 ",trim(" 12 "),"1","0o16","0o18", + "0b10101111_11110000_11110000_00110011", + "1_000","50e","+123","+ 123","-0b10101", + "NaN","+.345","12..34","12e3.4","0-2", + "192.168.0.1","1.2e","1 2","12.34","", + "beef","#beef","1,000,000","Inf","1/2", + "1.5e+27","0x10.5","1."} - sequence numeric = {}, - notnumb = {} - for i=1 to length(tests) do - string ti = tests[i] - if isNumber(ti) then - numeric = append(numeric,ti) - else - notnumb = append(notnumb,ti) - end if - end for - puts(1,"numeric: ") - pp(numeric,{pp_Indent,9}) - puts(1,"\nnot numeric: ") - pp(notnumb,{pp_Indent,13}) - - procedure StoreVar(integer N, integer NTyp) - -- - -- Store a variable, applying any final operator as needed. - -- If N is zero, PopFactor (ie store in a new temporary variable of - -- the specified type). Otherwise N should be an index to symtab. - -- If storeConst is 1, NTyp is ignored/overridden, otherwise it - -- should usually be the declared or local type of N. - -- - ... - end procedure - - switch {condition1,condition2} do - case {true,true}: - case {true,false}: - case {false,true}: - case {false,false}: - end switch - - function if2(bool c1, bool c2) - return c1*10+c2 - end function +function if2(bool c1, bool c2) + return c1*10+c2 +end function - switch if2(condition1,condition2) do - case 11: - case 10: - case 01: - case 00: - end switch - - enum BOTH = 0b11, FIRST = 0b10, SECOND = 0b01, NEITHER = 0b00 +enum BOTH = 0b11, FIRST = 0b10, SECOND = 0b01, NEITHER = 0b00 - function if2(bool c1, bool c2) - return c1*2+c2 - end function +function if2(bool c1, bool c2) + return c1*2+c2 +end function - integer r = if2(condition1,condition2) - if r=BOTH then - elsif r=FIRST then - elsif r=SECOND then - elsif r=NEITHER then - end if - - global constant T_if2 = 5200 tt_stringF("if2",T_if2) - global constant T_else1 = 5200 tt_stringF("else1",T_else1) - global constant T_else2 = 5200 tt_stringF("else2",T_else2) - - --constant T_endelseelsif = {T_end,T_else,T_elsif,T_case,T_default,T_fallthru,T_fallthrough} - constant T_endelseelsif = {T_end,T_else,T_else1,T_else2,T_elsif,T_case,T_default,T_fallthru,T_fallthrough} - - elsif ttidx=T_if2 then DoIf2() - - for N=10 to 20 do - printf(1,"%d is ",N) - if2 mod(N,2)=0, mod(N,3)=0 then - puts(1,"divisible by both two and three.\n") - else1 - puts(1,"divisible by two, but not by three.\n") - else2 - puts(1,"divisible by three, but not by two.\n") - else - puts(1,"neither divisible by two, nor by three.\n") - end if2 - end for - - with javascript_semantics - function modpow(atom x, atom n, atom m) - atom i = n, - y = 1, - z = x - while i do - if and_bits(i,1) then - y = mod(y*z,m) - end if - z = mod(z*z,m) - i = floor(i/2) - end while - return y - end function +with javascript_semantics +function modpow(atom x, n, m) + atom {i,y,z} = {n,1,x} + while i do + if odd(i) then + y = mod(y*z,m) + end if + z = mod(z*z,m) + i = floor(i/2) + end while + return y +end function - function mersenne_factor(integer p) - if not is_prime(p) then return -1 end if - atom limit = sqrt(power(2,p))-1 - integer k = 1 - while 1 do - atom q = 2*p*k + 1 - if q>=limit then exit end if - if find(mod(q,8),{1,7}) - and is_prime(q) - and modpow(2,p,q)=1 then - return q - end if - k += 1 - end while - return 0 - end function +function mersenne_factor(integer p) + if not is_prime(p) then return -1 end if + atom limit = sqrt(power(2,p))-1 + integer k = 1 + while 1 do + atom q = 2*p*k + 1 + if q>=limit then exit end if + if find(mod(q,8),{1,7}) + and is_prime(q,true) + and modpow(2,p,q)=1 then + return q + end if + k += 1 + end while + return 0 +end function - sequence tests = {11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929, 937} - for i=1 to length(tests) do - integer ti = tests[i] - printf(1,"A factor of M%d is %d\n",{ti,mersenne_factor(ti)}) - end for - - -- - -- demo\rosetta\Functional_coverage_tree.exw - -- ========================================= - -- - with javascript_semantics - constant data = """ - NAME_HIERARCHY | WEIGHT | COVERAGE | - cleaning | | | - house1 |40 | | - bedrooms | |0.25 | - bathrooms | | | - bathroom1 | |0.5 | - bathroom2 | | | - outside_lavatory | |1 | - attic | |0.75 | - kitchen | |0.1 | - living_rooms | | | - lounge | | | - dining_room | | | - conservatory | | | - playroom | |1 | - basement | | | - garage | | | - garden | |0.8 | - house2 |60 | | - upstairs | | | - bedrooms | | | - suite_1 | | | - suite_2 | | | - bedroom_3 | | | - bedroom_4 | | | - bathroom | | | - toilet | | | - attics | |0.6 | - groundfloor | | | - kitchen | | | - living_rooms | | | - lounge | | | - dining_room | | | - conservatory | | | - playroom | | | - wet_room_&_toilet | | | - garage | | | - garden | |0.9 | - hot_tub_suite | |1 | - basement | | | - cellars | |1 | - wine_cellar | |1 | - cinema | |0.75 | - """ - sequence lines = split(data,"\n"), - pi = {}, -- indents (to locate parents) - pdx = {}, -- indexes for "" - children - string desc, weights, covers - integer parent, child - atom weight, coverage, childw = 0 - enum DESC, WEIGHT, COVERAGE, PARENT, CHILDREN, CHILDW - lines[1] &= " SHARE OF RESIDUE" - for i=2 to length(lines) do - -- decode text to useable data, link up parents & children - {desc,weights,covers} = split(lines[i],"|") - -- (nb this assumes /totally/ consistent indenting) - integer indent = length(desc)-length(trim_head(desc)), - k = find(indent,pi) - if k=0 then - pi = append(pi,indent) - pdx = append(pdx,0) - k = length(pi) - end if - pdx[k] = i - parent = 0 - if k>1 then - parent = pdx[k-1] - -- lines[parent][CHILDREN] &= i - lines[parent][CHILDREN] = deep_copy(lines[parent][CHILDREN]) & i - end if - children = {} - weight = to_number(trim(weights),1) - coverage = to_number(trim(covers),0) - lines[i] = {desc, weight, coverage, parent, children, childw} - end for - for i=length(lines) to 2 by -1 do - -- calculate the parent coverages, and save child weight sums - children = lines[i][CHILDREN] - if length(children) then - coverage = 0 - childw = 0 - for c=1 to length(children) do - child = children[c] - atom w = lines[child][WEIGHT] - coverage += lines[child][COVERAGE]*w - childw += w - end for - lines[i][COVERAGE] = coverage/childw - lines[i][CHILDW] = childw -- (save for next loop) - end if - end for - for i=length(lines) to 2 by -1 do - -- calculate the share of residue, and format lines - child = i - {desc, weight, coverage, parent} = lines[i] - atom residue = 1-coverage - while parent do - residue *= lines[child][WEIGHT]/lines[parent][CHILDW] - {child, parent} = {parent, lines[parent][PARENT]} - end while - lines[i] = sprintf("%-32s| %6d | %-8g | %g",{desc,weight,coverage,residue}) - end for - puts(1,join(lines,"\n")&"\n") - {} = wait_key() - - with javascript_semantics - constant A = {{27,"Jonah"}, - {18,"Alan"}, - {28,"Glory"}, - {18,"Popeye"}, - {28,"Alan"}}, - B = {{"Jonah","Whales"}, - {"Jonah","Spiders"}, - {"Alan", "Ghosts"}, - {"Alan", "Zombies"}, - {"Glory","Buffy"}}, - jA = 2, - jB = 1, - MB = new_dict() - sequence C = {} - for i=1 to length(B) do - object key = B[i][jB] - object data = getd(key,MB) - if data=0 then - data = {B[i]} - else - data = append(data,B[i]) - end if - putd(key,data,MB) - end for - for i=1 to length(A) do - object data = getd(A[i][jA],MB) - if sequence(data) then - for j=1 to length(data) do - C = append(C,{A[i],data[j]}) - end for - end if - end for - destroy_dict(MB) - pp(C,{pp_Nest,1}) - - with javascript_semantics - atom t0 = time() - sequence list = {1}, - offset = repeat(0,32) - offset[1..2] = 1 - - function show(integer t, l) - string res = repeat('?',l) - integer level = 0 - for i=l to 1 by -1 do - integer r2 = remainder(t,2) - res[i] = "[}(]{)"[mod(level-r2,6)+1] - level += r2*4-2 - t = floor(t/2) - end for - if level!=0 then ?9/0 end if - return res - end function - - procedure listTrees(integer n) - for i:=offset[n+1]+1 to offset[n+2] do - printf(1,"%s\n",{show(list[i], n*2)}) - end for - end procedure - - procedure assemble(atom t, integer n, sl, pos, rem) - -- - -- assemble tree from subtrees - -- t: assembled parts so far - -- n: length of tree we want to make - -- sl: length of subtree we are looking at - -- pos: offset of subtree we are looking at - -- rem: remaining length to be put together - -- - if rem == 0 then - list = append(list, t*2+1) - else - if sl>rem then -- need smaller sub-trees - sl = rem - pos = offset[sl+1] - elsif pos>=offset[sl+2] then - -- used up sl-trees, try smaller ones - if sl == 1 then return end if - pos = offset[sl] - sl -= 1 - end if - - atom u = or_bits(t*power(2,2*sl),list[pos+1]) - assemble(u, n, sl, pos, rem-sl) - assemble(t, n, sl, pos+1, rem) - end if - end procedure - - procedure mktrees(integer n) - if offset[n+2]=0 then - if n>0 then - mktrees(n - 1) - end if - assemble(0, n, n-1, offset[n], n-1) - offset[n+2] = length(list) - end if - end procedure - - procedure main(integer n) - mktrees(n) - atom nt = offset[n+2]-offset[n+1], - td = time()-t0 - string e = iff(td>0.1?" ("&elapsed(td)&")":"") - printf(1,"Number of %d-trees: %,d%s\n", {n, nt, e}) - if n<=5 then listTrees(n) end if - end procedure - for i=0 to iff(platform()=JS?12:20) do - main(i) - end for - " HI" ", max(50, grp*3), '=') /*title*/ +dd='' /*variable holds output grid of GRP hhs.*/ + do j=LO to HI; dd= dd right( moebius(j), 2) /*process some numbers from LO --> HI.*/ + if words(dd)==grp then do; say substr(dd, 2); dd='' /*show grid if fully populated,*/ + end /* and nullify it for more hhs.*/ end /*j*/ /*for small grids, using wordCnt is OK.*/ -if $\=='' then say substr($, 2) /*handle any residual numbers not shown*/ +if dd\=='' then say substr(dd, 2) /*handle any residual numbers not shown*/ +say format(time('e'),,3) 'seconds' exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -mobius: procedure expose @.; parse arg x /*obtain a integer to be tested for mu.*/ - if x<1 then return '∙' /*special? Then return symbol for null.*/ - #= 0 /*start with a value of zero. */ - do k=1; p= @.k /*get the Kth (pre─generated) prime.*/ +/*--------------------------------------------------------------------------------------*/ +moebius: procedure expose aa.; parse arg x /*obtain a integer to be tested for mu.*/ + if x<1 then return '*' /*special? Then return symbol for null.*/ + hh= 0 /*start with a value of zero. */ + do k=1; p= aa.k /*get the Kth (pre-generated) prime.*/ if p>x then leave /*prime (P) > X? Then we're done. */ - if p*p>x then do; #= #+1; leave /*prime (P**2 > X? Bump # and leave.*/ + if p*p>x then do; hh= hh+1; leave /*prime (P**2 > X? Bump hh and leave.*/ end - if x//p==0 then do; #= #+1 /*X divisible by P? Bump mu number. */ + if x//p==0 then do; hh= hh+1 /*X divisible by P? Bump mu number. */ x= x % p /* Divide by prime. */ if x//p==0 then return 0 /*X÷by P? Then return zero*/ end - end /*k*/ /*# (below) is almost always small, <9*/ - if #//2==0 then return 1 /*Is # even? Then return postive 1 */ + end /*k*/ /*hh (below) is almost always small, <9*/ + if hh//2==0 then return 1 /*Is hh even? Then return postive 1 */ return -1 /* " " odd? " " negative 1. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6= 13; nP=6 /*assign low primes; # primes.*/ +/*--------------------------------------------------------------------------------------*/ +genP: aa.1=2; aa.2=3; aa.3=5; aa.4=7; aa.5=11; aa.6= 13; nP=6 /*assign low primes; hh primes.*/ do lim=nP until lim*lim>=HI /*only keep primes up to the sqrt(HI).*/ end /*lim*/ - do j=@.nP+4 by 2 to HI /*only find odd primes from here on. */ - parse var j '' -1 _;if _==5 then iterate /*Is last digit a "5"? Then not prime*/ + do j=aa.nP+4 by 2 to HI /*only find odd primes from here on. */ + parse var j '' -1 uu;if uu==5 then iterate /*Is last digit a "5"? Then not prime*/ if j// 3==0 then iterate /*is J divisible by 3? " " " */ if j// 7==0 then iterate /* " " " " 7? " " " */ if j//11==0 then iterate /* " " " " 11? " " " */ if j//13==0 then iterate /* " " " " 13? " " " */ do k=7 while k*k<=j /*divide by some generated odd primes. */ - if j // @.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - nP= nP+1; if nP<=HI then @.nP= j /*bump prime count; assign prime to @.*/ + if j // aa.k==0 then iterate j /*Is J divisible by P? Then not prime*/ + end /*k*/ /* [?] a prime (J) has been found. */ + nP= nP+1; if nP<=HI then aa.nP= j /*bump prime count; assign prime to aa.*/ end /*j*/; return diff --git a/Task/M-bius-function/REXX/m-bius-function-2.rexx b/Task/M-bius-function/REXX/m-bius-function-2.rexx new file mode 100644 index 0000000000..90b38b4233 --- /dev/null +++ b/Task/M-bius-function/REXX/m-bius-function-2.rexx @@ -0,0 +1,40 @@ +include Settings + +say version; say 'Moebius sequence'; say +parse arg LO HI grp . /*obtain optional arguments from the CL*/ +numeric digits 100 +if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ +if HI=='' | HI=="," then HI= 199 /* " " " " " " */ +if grp=='' | grp=="," then grp= 20 /* " " " " " " */ + /* ______ */ +say Center(' The Moebius sequence from ' LO " --> " HI" ", Max(50, grp*3), '=') /*title*/ +dd='' /*variable holds output grid of GRP #s.*/ + do j=LO to HI; dd= dd Right( Moebius(j), 2) /*process some numbers from LO --> HI.*/ + if Words(dd)==grp then do; say Substr(dd, 2); dd='' /*show grid if fully populated,*/ + end /* and nullify it for more #s.*/ + end /*j*/ /*for small grids, using wordCnt is OK.*/ +if dd\=='' then say Substr(dd, 2) /*handle any residual numbers not shown*/ +say Format(Time('e'),,3) 'seconds' +exit /*stick a fork in it, we're all done. */ + +Moebius: +/* Moebius sequence */ +procedure expose fact. ufac. +arg x +/* Special value */ +if x = 0 then + return '*' +/* Using # of (unique) prime factors */ +call Factors(x) +call Ufactors(x) +if fact.0 = ufac.0 then + if IsEven(fact.factor.0) then + return 1 + else + return -1 +else + return 0 + +include Functions +include Numbers +include Abend diff --git a/Task/M-bius-function/Rust/m-bius-function.rust b/Task/M-bius-function/Rust/m-bius-function.rs similarity index 100% rename from Task/M-bius-function/Rust/m-bius-function.rust rename to Task/M-bius-function/Rust/m-bius-function.rs diff --git a/Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.delphi b/Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.pas similarity index 100% rename from Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.delphi rename to Task/MAC-vendor-lookup/Delphi/mac-vendor-lookup.pas diff --git a/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.julia b/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.jl similarity index 53% rename from Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.julia rename to Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.jl index 79e31cc0e0..767a6a340b 100644 --- a/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.julia +++ b/Task/MAC-vendor-lookup/Julia/mac-vendor-lookup.jl @@ -1,15 +1,14 @@ -# v0.6.0 - -using Requests +import HTTP: get function getvendor(addr::String) try - get("http://api.macvendors.com/$addr") |> readstring + String(get("http://api.macvendors.com/$addr").body) catch e - nothing + "Vendor not found" end end for addr in ["88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67"] println("$addr -> ", getvendor(addr)) + sleep(0.5) # web site may error if requests are too close together end diff --git a/Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kotlin b/Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kts similarity index 100% rename from Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kotlin rename to Task/MAC-vendor-lookup/Kotlin/mac-vendor-lookup.kts diff --git a/Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ocaml b/Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ml similarity index 100% rename from Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ocaml rename to Task/MAC-vendor-lookup/OCaml/mac-vendor-lookup.ml diff --git a/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rust b/Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rs similarity index 100% rename from Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rust rename to Task/MAC-vendor-lookup/Rust/mac-vendor-lookup.rs diff --git a/Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.ss b/Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.scm similarity index 100% rename from Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.ss rename to Task/MAC-vendor-lookup/Scheme/mac-vendor-lookup.scm diff --git a/Task/MD4/Delphi/md4.delphi b/Task/MD4/Delphi/md4.pas similarity index 100% rename from Task/MD4/Delphi/md4.delphi rename to Task/MD4/Delphi/md4.pas diff --git a/Task/MD4/Julia/md4.julia b/Task/MD4/Julia/md4.jl similarity index 100% rename from Task/MD4/Julia/md4.julia rename to Task/MD4/Julia/md4.jl diff --git a/Task/MD4/Kotlin/md4.kotlin b/Task/MD4/Kotlin/md4.kts similarity index 100% rename from Task/MD4/Kotlin/md4.kotlin rename to Task/MD4/Kotlin/md4.kts diff --git a/Task/MD4/Rust/md4.rust b/Task/MD4/Rust/md4.rs similarity index 100% rename from Task/MD4/Rust/md4.rust rename to Task/MD4/Rust/md4.rs diff --git a/Task/MD5-Implementation/C++/md5-implementation.cpp b/Task/MD5-Implementation/C++/md5-implementation.cpp new file mode 100644 index 0000000000..2d913c1b90 --- /dev/null +++ b/Task/MD5-Implementation/C++/md5-implementation.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include +#include +#include + +const uint32_t INITIAL_A = 0x67452301; +const uint32_t INITIAL_B = static_cast(0xEFCDAB89L); +const uint32_t INITIAL_C = static_cast(0x98BADCFEL); +const uint32_t INITIAL_D = 0x10325476; + +const std::vector SHIFT_AMOUNTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 }; + +const std::vector K = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }; + +std::string to_hex_string(const std::vector& bytes) { + std::string hex_string = ""; + std::stringstream stream; + for ( const int8_t& bb : bytes ) { + stream << std::setfill('0') << std::setw(2) << std::hex << ( bb & 0xff ); + hex_string += stream.str(); + stream.str(""); + } + return hex_string; +} + +std::vector to_byte_vector(const std::string& text) { + std::vector bytes; + bytes.reserve(text.size()); + std::transform(text.begin(), text.end(), + std::back_inserter(bytes), [](char ch){ return static_cast(ch); }); + return bytes; +} + +std::vector computeMD5(const std::vector& message) { + uint64_t message_length_bytes = message.size(); + uint32_t number_blocks = ( ( message_length_bytes + 8 ) >> 6 ) + 1; + uint32_t total_length = number_blocks << 6; + std::vector padding_bytes(total_length - message_length_bytes); + padding_bytes[0] = static_cast(0x80); + uint64_t message_length_bits = message_length_bytes << 3; + for ( uint32_t i = 0; i < 8; ++i ) { + padding_bytes[padding_bytes.size() - 8 + i] = static_cast(message_length_bits); + message_length_bits >>= 8; + } + + uint32_t a = INITIAL_A; + uint32_t b = INITIAL_B; + uint32_t c = INITIAL_C; + uint32_t d = INITIAL_D; + + std::vector buffer(16); + for ( uint32_t i = 0; i < number_blocks; ++i ) { + uint32_t index = i << 6; + for ( uint32_t j = 0; j < 64; index++, ++j ) { + buffer[j >> 2] = ( static_cast( ( index < message_length_bytes ) ? message[index] + : padding_bytes[index - message_length_bytes] ) << 24 ) | ( buffer[j >> 2] >> 8 ); + } + + uint32_t original_A = a; + uint32_t original_B = b; + uint32_t original_C = c; + uint32_t original_D = d; + + for ( uint32_t j = 0; j < 64; ++j ) { + uint32_t div16 = j >> 4; + uint32_t f = 0; + uint32_t buffer_index = j; + switch ( div16 ) { + case 0: f = ( b & c ) | ( ~b & d ); break; + case 1: f = ( b & d ) | ( c & ~d ); buffer_index = ( buffer_index * 5 + 1 ) & 0x0F; break; + case 2: f = b ^ c ^ d; buffer_index = ( buffer_index * 3 + 5 ) & 0x0F; break; + case 3: f = c ^ ( b | ~d ); buffer_index = ( buffer_index * 7 ) & 0x0F; break; + } + uint32_t temp = b + std::rotl( + a + f + buffer[buffer_index] + K[j], SHIFT_AMOUNTS[( div16 << 2 ) | ( j & 3 )]); + + a = d; + d = c; + c = b; + b = temp; + } + + a += original_A; + b += original_B; + c += original_C; + d += original_D; + } + + std::vector md5(16); + uint32_t count = 0; + for ( uint32_t i = 0; i < 4; ++i ) { + uint32_t n = ( i == 0 ) ? a : ( ( i == 1 ) ? b : ( ( i == 2 ) ? c : d ) ); + for ( uint32_t j = 0; j < 4; ++j ) { + md5[count++] = static_cast(n); + n >>= 8; + } + } + return md5; +} + +int main() { + const std::vector tests = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }; + + for ( const std::string& test : tests ) { + std::cout << to_hex_string(computeMD5(to_byte_vector(test))) << " <== \"" + test + "\"" << "\n"; + + } +} diff --git a/Task/MD5-Implementation/Delphi/md5-implementation.delphi b/Task/MD5-Implementation/Delphi/md5-implementation.pas similarity index 100% rename from Task/MD5-Implementation/Delphi/md5-implementation.delphi rename to Task/MD5-Implementation/Delphi/md5-implementation.pas diff --git a/Task/MD5-Implementation/Julia/md5-implementation.julia b/Task/MD5-Implementation/Julia/md5-implementation.jl similarity index 100% rename from Task/MD5-Implementation/Julia/md5-implementation.julia rename to Task/MD5-Implementation/Julia/md5-implementation.jl diff --git a/Task/MD5-Implementation/Kotlin/md5-implementation.kotlin b/Task/MD5-Implementation/Kotlin/md5-implementation.kts similarity index 100% rename from Task/MD5-Implementation/Kotlin/md5-implementation.kotlin rename to Task/MD5-Implementation/Kotlin/md5-implementation.kts diff --git a/Task/MD5-Implementation/Raku/md5-implementation.raku b/Task/MD5-Implementation/Raku/md5-implementation.raku index 96ff90376b..c6dc59e0e0 100644 --- a/Task/MD5-Implementation/Raku/md5-implementation.raku +++ b/Task/MD5-Implementation/Raku/md5-implementation.raku @@ -1,9 +1,8 @@ proto md5($msg) returns Blob is export {*} multi md5(Str $msg) { md5 $msg.encode } multi md5(Blob $msg) { - my buf8 $buf .= new; - $buf.write-uint32: $buf.elems, $_, LittleEndian for - reduce -> Blob $blob, blob32 $X { + [~] map { buf8.new.write-uint32: 0, $_, LittleEndian }, + |reduce -> Blob $blob, blob32 $X { blob32.new: $blob Z+ reduce -> $b, $i { blob32.new: @@ -34,7 +33,6 @@ multi md5(Blob $msg) { $b; }(buf32.new) .rotor(16); - $buf; } CHECK { diff --git a/Task/MD5-Implementation/Rust/md5-implementation.rust b/Task/MD5-Implementation/Rust/md5-implementation.rs similarity index 100% rename from Task/MD5-Implementation/Rust/md5-implementation.rust rename to Task/MD5-Implementation/Rust/md5-implementation.rs diff --git a/Task/MD5/Crystal/md5.crystal b/Task/MD5/Crystal/md5.cr similarity index 100% rename from Task/MD5/Crystal/md5.crystal rename to Task/MD5/Crystal/md5.cr diff --git a/Task/MD5/Delphi/md5.delphi b/Task/MD5/Delphi/md5.pas similarity index 100% rename from Task/MD5/Delphi/md5.delphi rename to Task/MD5/Delphi/md5.pas diff --git a/Task/MD5/Julia/md5.julia b/Task/MD5/Julia/md5.jl similarity index 100% rename from Task/MD5/Julia/md5.julia rename to Task/MD5/Julia/md5.jl diff --git a/Task/MD5/Kotlin/md5.kotlin b/Task/MD5/Kotlin/md5.kts similarity index 100% rename from Task/MD5/Kotlin/md5.kotlin rename to Task/MD5/Kotlin/md5.kts diff --git a/Task/MD5/Nu/md5.nu b/Task/MD5/Nu/md5.nu new file mode 100644 index 0000000000..8e18018790 --- /dev/null +++ b/Task/MD5/Nu/md5.nu @@ -0,0 +1,7 @@ +[ + '' 'a' 'abc' 'message digest' + 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + '12345678901234567890123456789012345678901234567890123456789012345678901234567890' +] +| each { hash md5 } diff --git a/Task/MD5/OCaml/md5.ocaml b/Task/MD5/OCaml/md5.ml similarity index 100% rename from Task/MD5/OCaml/md5.ocaml rename to Task/MD5/OCaml/md5.ml diff --git a/Task/MD5/Rust/md5-1.rust b/Task/MD5/Rust/md5-1.rs similarity index 100% rename from Task/MD5/Rust/md5-1.rust rename to Task/MD5/Rust/md5-1.rs diff --git a/Task/MD5/Rust/md5-2.rust b/Task/MD5/Rust/md5-2.rs similarity index 100% rename from Task/MD5/Rust/md5-2.rust rename to Task/MD5/Rust/md5-2.rs diff --git a/Task/Machine-code/AArch64-Assembly/machine-code.aarch64 b/Task/Machine-code/AArch64-Assembly/machine-code.aarch64 new file mode 100644 index 0000000000..04d63ef750 --- /dev/null +++ b/Task/Machine-code/AArch64-Assembly/machine-code.aarch64 @@ -0,0 +1,94 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program Machine code */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sAreaConv: .skip 24 +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + + mov x0,#5 + mov x1,#10 + bl addition // call function + + ldr x1,qAdrsAreaConv // decimal conversion + bl conversion10 + ldr x0,qAdrsAreaConv // display result + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + adr x2,bCodeArmText // code machine arm address + mov x0,#10 + mov x1,#20 + blr x2 // call code machine + + ldr x1,qAdrsAreaConv // decimal conversion + bl conversion10 + ldr x0,qAdrsAreaConv // display result + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrsAreaConv: .quad sAreaConv + +/******************************************************************/ +/* add two registers */ +/******************************************************************/ +/* x0 contains value 1 */ +/* x1 contains value 2 */ + +addition: + stp x1,lr,[sp,-16]! // TODO: a completer + add x0,x0,x1 +100: + ldp x1,lr,[sp],16 // TODO: a completer + ret + // code machine ARM AARCH 64 bits +bCodeArmText: .byte 0xE1,0x7B,0xBF,0xA9 // stp x1,lr,[sp,-16]! + .byte 0x00,0x00,0x01,0x8B // add x0,x0,x1 + .byte 0xE1,0x7B,0xC1,0xA8 // ldp x1,lr,[sp],16 + .byte 0xC0,0x03,0x5F,0xD6 // ret +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Machine-code/ARM-Assembly/machine-code.arm b/Task/Machine-code/ARM-Assembly/machine-code.arm new file mode 100644 index 0000000000..caa2f7cf72 --- /dev/null +++ b/Task/Machine-code/ARM-Assembly/machine-code.arm @@ -0,0 +1,98 @@ +/* ARM assembly Raspberry PI */ +/* program Machine code */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" + + @ code machine ARM 32 bits +.align 4 +bCodeArm: .byte 0x02,0x40,0x2D,0xE9 @ push {r1,lr} + .byte 0x01,0x00,0x80,0xE0 @ add r0,r1 + .byte 0x02,0x80,0xBD,0xE8 @ pop {r1,pc} +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sAreaConv: .skip 24 +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + + mov r0,#5 + mov r1,#10 + bl addition @ call function + + ldr r1,iAdrsAreaConv @ decimal conversion + bl conversion10 + ldr r0,iAdrsAreaConv @ display result + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r2,iAdrbCodeArm @ code machine arm address + mov r0,#10 + mov r1,#20 + blx r2 @ call code machine + + ldr r1,iAdrsAreaConv @ decimal conversion + bl conversion10 + ldr r0,iAdrsAreaConv @ display result + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrsAreaConv: .int sAreaConv +iAdrbCodeArm: .int bCodeArm + +/******************************************************************/ +/* add two registers */ +/******************************************************************/ +/* r0 contains value 1 */ +/* r1 contains value 2 */ + +addition: + push {r1,lr} @ save registers + add r0,r1 +100: + pop {r1,pc} + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Machine-code/Common-Lisp/machine-code.lisp b/Task/Machine-code/Common-Lisp/machine-code.lisp index f4ee406189..faf7e0ddb8 100644 --- a/Task/Machine-code/Common-Lisp/machine-code.lisp +++ b/Task/Machine-code/Common-Lisp/machine-code.lisp @@ -1,3 +1,49 @@ +;;Update 2024: the previous code is likely not going to work on modern OS, because there is a need to allocate memory with the correct permissions (readable, writable, and executable). We will update with another machine code, equivalent to the function 'ash' in common lisp + +89 f8 mov %edi,%eax +89 f1 mov %esi,%ecx +d3 e8 shr %cl,%eax +c3 ret + +;;sbcl +(require :sb-posix) + +(defconstant +PROT-READ+ 1) +(defconstant +PROT-WRITE+ 2) +(defconstant +PROT-EXEC+ 4) +(defconstant +MAP-PRIVATE+ 2) +(defconstant +MAP-ANONYMOUS+ #x20) + +(defun allocate-executable-memory (size) + (sb-posix:mmap nil + size + (logior +PROT-READ+ +PROT-WRITE+ +PROT-EXEC+) + (logior +MAP-PRIVATE+ +MAP-ANONYMOUS+) + -1 + 0)) + +;; Example usage: +(defparameter *shellcode* #(#x89 #xf8 #x89 #xf1 #xd3 #xe8 #xc3)) +(defparameter *mem-ptr* (allocate-executable-memory (length *shellcode*))) + +;; Copy shellcode to allocated memory +(loop for byte across *shellcode* + for i from 0 + do (setf (sb-sys:sap-ref-8 *mem-ptr* i) byte)) + +;; Create a callable function pointer +(defparameter *func* (sb-alien:sap-alien *mem-ptr* (sb-alien:function sb-alien:unsigned-int sb-alien:unsigned-int sb-alien:unsigned-int))) + +;; Call the function +(sb-alien:alien-funcall *func* 18 1) +;; 9 +;;(ash 18 -1) => 9 + +;; Don't forget to free the memory when done +;;(sb-posix:munmap *mem-ptr* (length *shellcode*)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;old contribution starts here ;;Note that by using the 'CFFI' library, one can apply this procedure portably in any lisp implementation; ;; in this code however I chose to demonstrate only the implementation-dependent programs. diff --git a/Task/Machine-code/Delphi/machine-code.delphi b/Task/Machine-code/Delphi/machine-code.pas similarity index 100% rename from Task/Machine-code/Delphi/machine-code.delphi rename to Task/Machine-code/Delphi/machine-code.pas diff --git a/Task/Machine-code/Julia/machine-code.julia b/Task/Machine-code/Julia/machine-code.jl similarity index 100% rename from Task/Machine-code/Julia/machine-code.julia rename to Task/Machine-code/Julia/machine-code.jl diff --git a/Task/Machine-code/Kotlin/machine-code-1.kotlin b/Task/Machine-code/Kotlin/machine-code-1.kts similarity index 100% rename from Task/Machine-code/Kotlin/machine-code-1.kotlin rename to Task/Machine-code/Kotlin/machine-code-1.kts diff --git a/Task/Machine-code/Kotlin/machine-code-2.kotlin b/Task/Machine-code/Kotlin/machine-code-2.kts similarity index 100% rename from Task/Machine-code/Kotlin/machine-code-2.kotlin rename to Task/Machine-code/Kotlin/machine-code-2.kts diff --git a/Task/Machine-code/Rust/machine-code.rust b/Task/Machine-code/Rust/machine-code.rs similarity index 100% rename from Task/Machine-code/Rust/machine-code.rust rename to Task/Machine-code/Rust/machine-code.rs diff --git a/Task/Machine-code/Scheme/machine-code.ss b/Task/Machine-code/Scheme/machine-code.scm similarity index 100% rename from Task/Machine-code/Scheme/machine-code.ss rename to Task/Machine-code/Scheme/machine-code.scm diff --git a/Task/Mad-Libs/Julia/mad-libs.julia b/Task/Mad-Libs/Julia/mad-libs.jl similarity index 100% rename from Task/Mad-Libs/Julia/mad-libs.julia rename to Task/Mad-Libs/Julia/mad-libs.jl diff --git a/Task/Mad-Libs/Kotlin/mad-libs.kotlin b/Task/Mad-Libs/Kotlin/mad-libs.kts similarity index 100% rename from Task/Mad-Libs/Kotlin/mad-libs.kotlin rename to Task/Mad-Libs/Kotlin/mad-libs.kts diff --git a/Task/Mad-Libs/Rust/mad-libs.rust b/Task/Mad-Libs/Rust/mad-libs.rs similarity index 100% rename from Task/Mad-Libs/Rust/mad-libs.rust rename to Task/Mad-Libs/Rust/mad-libs.rs diff --git a/Task/Magic-8-ball/Delphi/magic-8-ball.delphi b/Task/Magic-8-ball/Delphi/magic-8-ball.pas similarity index 100% rename from Task/Magic-8-ball/Delphi/magic-8-ball.delphi rename to Task/Magic-8-ball/Delphi/magic-8-ball.pas diff --git a/Task/Magic-8-ball/EasyLang/magic-8-ball.easy b/Task/Magic-8-ball/EasyLang/magic-8-ball.easy index 7f793ae08f..3c50eb8113 100644 --- a/Task/Magic-8-ball/EasyLang/magic-8-ball.easy +++ b/Task/Magic-8-ball/EasyLang/magic-8-ball.easy @@ -4,5 +4,5 @@ repeat print "What would you like to know? " q$ = input until q$ = "q" - print answers$[randint len answers$[]] + print answers$[random len answers$[]] . diff --git a/Task/Magic-8-ball/Julia/magic-8-ball.julia b/Task/Magic-8-ball/Julia/magic-8-ball.jl similarity index 100% rename from Task/Magic-8-ball/Julia/magic-8-ball.julia rename to Task/Magic-8-ball/Julia/magic-8-ball.jl diff --git a/Task/Magic-8-ball/Kotlin/magic-8-ball.kotlin b/Task/Magic-8-ball/Kotlin/magic-8-ball.kts similarity index 100% rename from Task/Magic-8-ball/Kotlin/magic-8-ball.kotlin rename to Task/Magic-8-ball/Kotlin/magic-8-ball.kts diff --git a/Task/Magic-8-ball/Rust/magic-8-ball.rust b/Task/Magic-8-ball/Rust/magic-8-ball.rs similarity index 100% rename from Task/Magic-8-ball/Rust/magic-8-ball.rust rename to Task/Magic-8-ball/Rust/magic-8-ball.rs diff --git a/Task/Magic-8-ball/V-(Vlang)/magic-8-ball.v b/Task/Magic-8-ball/V-(Vlang)/magic-8-ball.v new file mode 100644 index 0000000000..8e4e604cae --- /dev/null +++ b/Task/Magic-8-ball/V-(Vlang)/magic-8-ball.v @@ -0,0 +1,26 @@ +import rand +import os + +const answers = ["It is certain", "It is decidedly so", "Without a doubt", + "Yes, definitely", "You may rely on it", "As I see it, yes", + "Most likely", "Outlook good", "Signs point to yes", "Yes", + "Reply hazy, try again", "Ask again later", + "Better not tell you now", "Cannot predict now", + "Concentrate and ask again", "Don't bet on it", + "My reply is no", "My sources say no", "Outlook not so good", + "Very doubtful"] + +fn main() { + mut str :="" + for { + str = os.input_opt("Please enter your question or a blank line to quit? \n") or {panic(err)}.str() + if str =="" { + println("No answer, so exiting!") + break + } + else { + rnum := rand.int_in_range(0, answers.len) or {exit(1)} + println(answers[rnum]) + } + } +} diff --git a/Task/Magic-constant/Delphi/magic-constant.delphi b/Task/Magic-constant/Delphi/magic-constant.pas similarity index 100% rename from Task/Magic-constant/Delphi/magic-constant.delphi rename to Task/Magic-constant/Delphi/magic-constant.pas diff --git a/Task/Magic-constant/Julia/magic-constant.julia b/Task/Magic-constant/Julia/magic-constant.jl similarity index 100% rename from Task/Magic-constant/Julia/magic-constant.julia rename to Task/Magic-constant/Julia/magic-constant.jl diff --git a/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy b/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy new file mode 100644 index 0000000000..c13991f0c6 --- /dev/null +++ b/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy @@ -0,0 +1,56 @@ +func[][] mkarr s . + len q[][] s + for i = 1 to s + len q[i][] s + . + return q[][] +. +func[][] mk_oms s . + q[][] = mkarr s + r = 1 + c = 1 + s div 2 + for p = 1 to s * s + q[r][c] = p + tc = c + 1 + if tc > s + tc = 1 + . + tr = r - 1 + if tr < 1 + tr = s + . + if q[tr][tc] <> 0 + tc = c + tr = r + 1 + . + c = tc + r = tr + . + return q[][] +. +func[][] mk_dems s . + q[][] = mkarr s + tmp[][] = [ [ 1 0 0 1 ] [ 0 1 1 0 ] [ 0 1 1 0 ] [ 1 0 0 1 ] ] + tot = s * s + for r = 1 to s + for c = 1 to s + sx = c mod 4 + if sx < 1 + sx = 4 + . + sy = r mod 4 + if sy < 1 + sy = 4 + . + if tmp[sy][sx] = 1 + q[r][c] = n + 1 + else + q[r][c] = tot - n + . + n += 1 + . + . + return q[][] +. +numfmt 0 2 +print mk_dems 8 diff --git a/Task/Magic-squares-of-doubly-even-order/Elixir/magic-squares-of-doubly-even-order.elixir b/Task/Magic-squares-of-doubly-even-order/Elixir/magic-squares-of-doubly-even-order.ex similarity index 100% rename from Task/Magic-squares-of-doubly-even-order/Elixir/magic-squares-of-doubly-even-order.elixir rename to Task/Magic-squares-of-doubly-even-order/Elixir/magic-squares-of-doubly-even-order.ex diff --git a/Task/Magic-squares-of-doubly-even-order/Julia/magic-squares-of-doubly-even-order.julia b/Task/Magic-squares-of-doubly-even-order/Julia/magic-squares-of-doubly-even-order.jl similarity index 100% rename from Task/Magic-squares-of-doubly-even-order/Julia/magic-squares-of-doubly-even-order.julia rename to Task/Magic-squares-of-doubly-even-order/Julia/magic-squares-of-doubly-even-order.jl diff --git a/Task/Magic-squares-of-doubly-even-order/Kotlin/magic-squares-of-doubly-even-order.kotlin b/Task/Magic-squares-of-doubly-even-order/Kotlin/magic-squares-of-doubly-even-order.kts similarity index 100% rename from Task/Magic-squares-of-doubly-even-order/Kotlin/magic-squares-of-doubly-even-order.kotlin rename to Task/Magic-squares-of-doubly-even-order/Kotlin/magic-squares-of-doubly-even-order.kts diff --git a/Task/Magic-squares-of-doubly-even-order/Rust/magic-squares-of-doubly-even-order.rust b/Task/Magic-squares-of-doubly-even-order/Rust/magic-squares-of-doubly-even-order.rs similarity index 100% rename from Task/Magic-squares-of-doubly-even-order/Rust/magic-squares-of-doubly-even-order.rust rename to Task/Magic-squares-of-doubly-even-order/Rust/magic-squares-of-doubly-even-order.rs diff --git a/Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.elixir b/Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.ex similarity index 100% rename from Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.elixir rename to Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.ex diff --git a/Task/Magic-squares-of-odd-order/Julia/magic-squares-of-odd-order.julia b/Task/Magic-squares-of-odd-order/Julia/magic-squares-of-odd-order.jl similarity index 100% rename from Task/Magic-squares-of-odd-order/Julia/magic-squares-of-odd-order.julia rename to Task/Magic-squares-of-odd-order/Julia/magic-squares-of-odd-order.jl diff --git a/Task/Magic-squares-of-odd-order/Kotlin/magic-squares-of-odd-order.kotlin b/Task/Magic-squares-of-odd-order/Kotlin/magic-squares-of-odd-order.kts similarity index 100% rename from Task/Magic-squares-of-odd-order/Kotlin/magic-squares-of-odd-order.kotlin rename to Task/Magic-squares-of-odd-order/Kotlin/magic-squares-of-odd-order.kts diff --git a/Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rust b/Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rs similarity index 100% rename from Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rust rename to Task/Magic-squares-of-odd-order/Rust/magic-squares-of-odd-order.rs diff --git a/Task/Magic-squares-of-odd-order/V-(Vlang)/magic-squares-of-odd-order.v b/Task/Magic-squares-of-odd-order/V-(Vlang)/magic-squares-of-odd-order.v new file mode 100644 index 0000000000..38a0b1e5a4 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/V-(Vlang)/magic-squares-of-odd-order.v @@ -0,0 +1,12 @@ +fn main() { + mut n, mut x := 9, 0 + println("the square order is : ${n}" + "\n") + for i in 1 .. n + 1 { + for j in 1 .. n + 1 { + x = (i * 2 - j + n - 1) % n * n + (i * 2 + j - 2) % n + 1 + print(" ${x:2} ") + } + println("") + } + println("\n" + "the magic number is : ${n * (n * n+1) / 2}") +} diff --git a/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy b/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy new file mode 100644 index 0000000000..6eaddd19df --- /dev/null +++ b/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy @@ -0,0 +1,63 @@ +func[][] mkarr s . + len q[][] s + for i = 1 to s + len q[i][] s + . + return q[][] +. +func[][] mk_oms s . + q[][] = mkarr s + r = 1 + c = 1 + s div 2 + for p = 1 to s * s + q[r][c] = p + tc = c + 1 + if tc > s + tc = 1 + . + tr = r - 1 + if tr < 1 + tr = s + . + if q[tr][tc] <> 0 + tc = c + tr = r + 1 + . + c = tc + r = tr + . + return q[][] +. +func[][] mk_sems s . + q[][] = mkarr s + sh = s div 2 + q4 = sh * sh + q2 = 2 * q4 + q3 = 3 * q4 + o[][] = mk_oms sh + for r = 1 to sh + for c = 1 to sh + q1 = o[r][c] + q[r][c] = q1 + q[r + sh][c + sh] = q1 + q4 + q[r][c + sh] = q1 + q2 + q[r + sh][c] = q1 + q3 + . + . + lc = sh div 2 + rc = lc - 1 + for r = 1 to sh + for c = 1 to s + if c <= lc or c > s - rc or (c = lc + 1 and r = lc + 1) + if c <> 1 or r <> lc + 1 + t = q[r][c] + q[r][c] = q[r + sh][c] + q[r + sh][c] = t + . + . + . + . + return q[][] +. +numfmt 0 2 +print mk_sems 6 diff --git a/Task/Magic-squares-of-singly-even-order/Elixir/magic-squares-of-singly-even-order.elixir b/Task/Magic-squares-of-singly-even-order/Elixir/magic-squares-of-singly-even-order.ex similarity index 100% rename from Task/Magic-squares-of-singly-even-order/Elixir/magic-squares-of-singly-even-order.elixir rename to Task/Magic-squares-of-singly-even-order/Elixir/magic-squares-of-singly-even-order.ex diff --git a/Task/Magic-squares-of-singly-even-order/Julia/magic-squares-of-singly-even-order.julia b/Task/Magic-squares-of-singly-even-order/Julia/magic-squares-of-singly-even-order.jl similarity index 100% rename from Task/Magic-squares-of-singly-even-order/Julia/magic-squares-of-singly-even-order.julia rename to Task/Magic-squares-of-singly-even-order/Julia/magic-squares-of-singly-even-order.jl diff --git a/Task/Magic-squares-of-singly-even-order/Kotlin/magic-squares-of-singly-even-order.kotlin b/Task/Magic-squares-of-singly-even-order/Kotlin/magic-squares-of-singly-even-order.kts similarity index 100% rename from Task/Magic-squares-of-singly-even-order/Kotlin/magic-squares-of-singly-even-order.kotlin rename to Task/Magic-squares-of-singly-even-order/Kotlin/magic-squares-of-singly-even-order.kts diff --git a/Task/Magic-squares-of-singly-even-order/Rust/magic-squares-of-singly-even-order.rust b/Task/Magic-squares-of-singly-even-order/Rust/magic-squares-of-singly-even-order.rs similarity index 100% rename from Task/Magic-squares-of-singly-even-order/Rust/magic-squares-of-singly-even-order.rust rename to Task/Magic-squares-of-singly-even-order/Rust/magic-squares-of-singly-even-order.rs diff --git a/Task/Magnanimous-numbers/Delphi/magnanimous-numbers.delphi b/Task/Magnanimous-numbers/Delphi/magnanimous-numbers.pas similarity index 100% rename from Task/Magnanimous-numbers/Delphi/magnanimous-numbers.delphi rename to Task/Magnanimous-numbers/Delphi/magnanimous-numbers.pas diff --git a/Task/Magnanimous-numbers/Julia/magnanimous-numbers.julia b/Task/Magnanimous-numbers/Julia/magnanimous-numbers.jl similarity index 100% rename from Task/Magnanimous-numbers/Julia/magnanimous-numbers.julia rename to Task/Magnanimous-numbers/Julia/magnanimous-numbers.jl diff --git a/Task/Magnanimous-numbers/Rust/magnanimous-numbers.rust b/Task/Magnanimous-numbers/Rust/magnanimous-numbers.rs similarity index 100% rename from Task/Magnanimous-numbers/Rust/magnanimous-numbers.rust rename to Task/Magnanimous-numbers/Rust/magnanimous-numbers.rs diff --git a/Task/Main-step-of-GOST-28147-89/Java/main-step-of-gost-28147-89.java b/Task/Main-step-of-GOST-28147-89/Java/main-step-of-gost-28147-89.java index ec768fdf8f..da8920981d 100644 --- a/Task/Main-step-of-GOST-28147-89/Java/main-step-of-gost-28147-89.java +++ b/Task/Main-step-of-GOST-28147-89/Java/main-step-of-gost-28147-89.java @@ -27,7 +27,8 @@ public final class MainStepGOST28147_89 { String encryptedBinary = gost.gostAlgorithm(plainTextBinary, Cryptation.ENCRYPT); // Display the encrypted text bytes and the encrypted text - List encryptedChars = displayBytesFromBinary("The encrypted text bytes are: ", encryptedBinary); + List encryptedChars = + displayBytesFromBinary("The encrypted text bytes are: ", encryptedBinary); String encryptedText = encryptedChars.stream().map(String::valueOf).collect(Collectors.joining()); System.out.println("The encrypted text is: \"" + encryptedText + "\"" + System.lineSeparator()); @@ -35,9 +36,11 @@ public final class MainStepGOST28147_89 { String decryptedBinary = gost.gostAlgorithm(encryptedBinary, Cryptation.DECRYPT); // Display the decrypted text bytes and the decrypted text - List decryptedChars = displayBytesFromBinary("The decrypted text bytes are: ", decryptedBinary); + List decryptedChars = + displayBytesFromBinary("The decrypted text bytes are: ", decryptedBinary); byte[] bytes = new byte[decryptedChars.size()]; - IntStream.range(0, decryptedChars.size()).forEach( i -> bytes[i] = (byte) decryptedChars.get(i).charValue() ); + IntStream.range(0, decryptedChars.size()) + .forEach( i -> bytes[i] = (byte) decryptedChars.get(i).charValue() ); System.out.println("The decrypted text is: \"" + new String(bytes) + "\"" + System.lineSeparator()); } diff --git a/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia b/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.jl similarity index 100% rename from Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia rename to Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.jl diff --git a/Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kotlin b/Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kts similarity index 100% rename from Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kotlin rename to Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kts diff --git a/Task/Main-step-of-GOST-28147-89/Rust/main-step-of-gost-28147-89.rust b/Task/Main-step-of-GOST-28147-89/Rust/main-step-of-gost-28147-89.rs similarity index 100% rename from Task/Main-step-of-GOST-28147-89/Rust/main-step-of-gost-28147-89.rust rename to Task/Main-step-of-GOST-28147-89/Rust/main-step-of-gost-28147-89.rs diff --git a/Task/Make-directory-path/Delphi/make-directory-path.delphi b/Task/Make-directory-path/Delphi/make-directory-path.pas similarity index 100% rename from Task/Make-directory-path/Delphi/make-directory-path.delphi rename to Task/Make-directory-path/Delphi/make-directory-path.pas diff --git a/Task/Make-directory-path/Elixir/make-directory-path.elixir b/Task/Make-directory-path/Elixir/make-directory-path.ex similarity index 100% rename from Task/Make-directory-path/Elixir/make-directory-path.elixir rename to Task/Make-directory-path/Elixir/make-directory-path.ex diff --git a/Task/Make-directory-path/Julia/make-directory-path.julia b/Task/Make-directory-path/Julia/make-directory-path.jl similarity index 100% rename from Task/Make-directory-path/Julia/make-directory-path.julia rename to Task/Make-directory-path/Julia/make-directory-path.jl diff --git a/Task/Make-directory-path/Kotlin/make-directory-path.kotlin b/Task/Make-directory-path/Kotlin/make-directory-path.kts similarity index 100% rename from Task/Make-directory-path/Kotlin/make-directory-path.kotlin rename to Task/Make-directory-path/Kotlin/make-directory-path.kts diff --git a/Task/Make-directory-path/OCaml/make-directory-path.ocaml b/Task/Make-directory-path/OCaml/make-directory-path.ml similarity index 100% rename from Task/Make-directory-path/OCaml/make-directory-path.ocaml rename to Task/Make-directory-path/OCaml/make-directory-path.ml diff --git a/Task/Make-directory-path/Rust/make-directory-path.rust b/Task/Make-directory-path/Rust/make-directory-path.rs similarity index 100% rename from Task/Make-directory-path/Rust/make-directory-path.rust rename to Task/Make-directory-path/Rust/make-directory-path.rs diff --git a/Task/Man-or-boy-test/Crystal/man-or-boy-test.crystal b/Task/Man-or-boy-test/Crystal/man-or-boy-test.cr similarity index 100% rename from Task/Man-or-boy-test/Crystal/man-or-boy-test.crystal rename to Task/Man-or-boy-test/Crystal/man-or-boy-test.cr diff --git a/Task/Man-or-boy-test/Delphi/man-or-boy-test.delphi b/Task/Man-or-boy-test/Delphi/man-or-boy-test.pas similarity index 100% rename from Task/Man-or-boy-test/Delphi/man-or-boy-test.delphi rename to Task/Man-or-boy-test/Delphi/man-or-boy-test.pas diff --git a/Task/Man-or-boy-test/Julia/man-or-boy-test.julia b/Task/Man-or-boy-test/Julia/man-or-boy-test.jl similarity index 100% rename from Task/Man-or-boy-test/Julia/man-or-boy-test.julia rename to Task/Man-or-boy-test/Julia/man-or-boy-test.jl diff --git a/Task/Man-or-boy-test/Kotlin/man-or-boy-test.kotlin b/Task/Man-or-boy-test/Kotlin/man-or-boy-test.kts similarity index 100% rename from Task/Man-or-boy-test/Kotlin/man-or-boy-test.kotlin rename to Task/Man-or-boy-test/Kotlin/man-or-boy-test.kts diff --git a/Task/Man-or-boy-test/OCaml/man-or-boy-test.ocaml b/Task/Man-or-boy-test/OCaml/man-or-boy-test.ml similarity index 100% rename from Task/Man-or-boy-test/OCaml/man-or-boy-test.ocaml rename to Task/Man-or-boy-test/OCaml/man-or-boy-test.ml diff --git a/Task/Man-or-boy-test/Rust/man-or-boy-test-1.rust b/Task/Man-or-boy-test/Rust/man-or-boy-test-1.rs similarity index 100% rename from Task/Man-or-boy-test/Rust/man-or-boy-test-1.rust rename to Task/Man-or-boy-test/Rust/man-or-boy-test-1.rs diff --git a/Task/Man-or-boy-test/Rust/man-or-boy-test-2.rust b/Task/Man-or-boy-test/Rust/man-or-boy-test-2.rs similarity index 100% rename from Task/Man-or-boy-test/Rust/man-or-boy-test-2.rust rename to Task/Man-or-boy-test/Rust/man-or-boy-test-2.rs diff --git a/Task/Man-or-boy-test/Rust/man-or-boy-test-3.rust b/Task/Man-or-boy-test/Rust/man-or-boy-test-3.rs similarity index 100% rename from Task/Man-or-boy-test/Rust/man-or-boy-test-3.rust rename to Task/Man-or-boy-test/Rust/man-or-boy-test-3.rs diff --git a/Task/Man-or-boy-test/Scheme/man-or-boy-test.ss b/Task/Man-or-boy-test/Scheme/man-or-boy-test.scm similarity index 100% rename from Task/Man-or-boy-test/Scheme/man-or-boy-test.ss rename to Task/Man-or-boy-test/Scheme/man-or-boy-test.scm diff --git a/Task/Man-or-boy-test/Ursalang/man-or-boy-test.ursa b/Task/Man-or-boy-test/Ursalang/man-or-boy-test.ursa new file mode 100644 index 0000000000..44c42cf055 --- /dev/null +++ b/Task/Man-or-boy-test/Ursalang/man-or-boy-test.ursa @@ -0,0 +1,14 @@ +let a = fn(k, x1, x2, x3, x4, x5) { + if k <= 0 { + x4() + x5() + } else { + var m = k + let b = fn() { + m := m - 1 + a(m, b, x1, x2, x3, x4) + } + b() + } +} + +print(a(10, fn () {1}, fn () {-1}, fn () {-1}, fn () {1}, fn () {0})) diff --git a/Task/Mandelbrot-set/AArch64-Assembly/mandelbrot-set.aarch64 b/Task/Mandelbrot-set/AArch64-Assembly/mandelbrot-set.aarch64 new file mode 100644 index 0000000000..2ca9c6ab0f --- /dev/null +++ b/Task/Mandelbrot-set/AArch64-Assembly/mandelbrot-set.aarch64 @@ -0,0 +1,134 @@ +#include +.globl main +.section .text + +.macro NEWLINE + mov x0, #10 + stp x9, x10, [sp, #-16]! + bl putchar + ldp x9, x10, [sp], 16 +.endm + +.macro PRINTCHAR p + mov x1, \p + mov x0, #64 + sub x0, x0, x1 + stp x9, x10, [sp, #-16]! + bl putchar + ldp x9, x10, [sp], 16 +.endm + +xsize .req x9 +xsize_w .req w9 +ysize .req x10 +ysize_w .req w10 + +min_imag .req s8 +max_imag .req s9 +min_real .req s10 +max_real .req s9 + +imag .req s11 +real .req s12 + +step_x .req s13 +step_y .req s14 + +zi .req s15 +zr .req s16 + +a .req s17 +b .req s18 + +ftemp_1 .req s19 +ftemp_2 .req s20 + +y .req x19 +y_w .req w19 +x .req x20 +x_w .req w20 +n .req x21 +limit .req x22 + +itemp_1 .req x23 +itemp_1w .req w23 + +/* + redefining register names + for easier implementation +*/ + +main: + stp xzr, lr, [sp, #-16]! + stp d8, d9, [sp, #-16]! + stp d10, d11,[sp, #-16]! + stp d12, d13,[sp, #-16]! + stp d14, d15,[sp, #-16]! + stp x19, x20,[sp, #-16]! + stp x21, x22,[sp, #-16]! + stp x23, x24,[sp, #-16]! + + mov xsize, #108 + mov ysize, #72 + mov limit, #32 + fmov min_imag, #-1.0 + fmov max_imag, #1.0 + fmov min_real, #-2.0 +// fmov max_real #1.0 + + fsub step_x, max_real, min_real + scvtf ftemp_1, xsize_w + fdiv step_x, step_x, ftemp_1 + fsub step_y, max_imag, min_imag + scvtf ftemp_1, ysize_w + fdiv step_y, step_y, ftemp_1 + mov y, #0 + 1: + cmp y, ysize + b.eq 20f + scvtf ftemp_1, y_w + fmadd imag, step_y, ftemp_1, min_imag + mov x, #0 + 2: + cmp x, xsize + b.eq 15f + scvtf ftemp_1, x_w + fmadd real, step_y, ftemp_1, min_real + fmov zr, real + fmov zi, imag + mov n, #0 + 3: + cmp n, limit + b.eq 10f + fmul a, zr, zr + fmul b, zi, zi + fadd ftemp_1, a, b + fmov ftemp_2, #4.0 + fcmp ftemp_1, ftemp_2 + b.gt 10f + fmul zi, zi, zr + fmov ftemp_2, #2.0 + fmadd zi, zi, ftemp_2, imag + fsub zr, a, b + fadd zr, zr, real + add n, n, #1 + b 3b + 10: + add x, x, #1 + PRINTCHAR n + b 2b + 15: + add y, y, #1 + NEWLINE + b 1b + 20: + + ldp x23, x24,[sp], 16 + ldp x21, x22,[sp], 16 + ldp x19, x20,[sp], 16 + ldp d14, d15,[sp], 16 + ldp d12, d13,[sp], 16 + ldp d10, d11,[sp], 16 + ldp d8, d9, [sp], 16 + ldp xzr, lr, [sp], 16 + ret diff --git a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy index d11005b78e..d5e23ca019 100644 --- a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy +++ b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy @@ -1,5 +1,3 @@ -# Mandelbrot -# res = 4 maxiter = 200 # diff --git a/Task/Mandelbrot-set/Elixir/mandelbrot-set.elixir b/Task/Mandelbrot-set/Elixir/mandelbrot-set.ex similarity index 100% rename from Task/Mandelbrot-set/Elixir/mandelbrot-set.elixir rename to Task/Mandelbrot-set/Elixir/mandelbrot-set.ex diff --git a/Task/Mandelbrot-set/J/mandelbrot-set-1.j b/Task/Mandelbrot-set/J/mandelbrot-set-1.j index 18a1ce4df1..f747810a1f 100644 --- a/Task/Mandelbrot-set/J/mandelbrot-set-1.j +++ b/Task/Mandelbrot-set/J/mandelbrot-set-1.j @@ -1 +1 @@ -mcf=. (<: 2:)@|@(] ((*:@] + [)^:((<: 2:)@|@])^:1000) 0:) NB. 1000 iterations test +mcf=. [: (<: 2:)@| ] ((*:@] + [)^:((<: 2:)@|@])^:1000) 0: NB. 1000 iterations test diff --git a/Task/Mandelbrot-set/J/mandelbrot-set-3.j b/Task/Mandelbrot-set/J/mandelbrot-set-3.j index 52740ff704..2ecce89a61 100644 --- a/Task/Mandelbrot-set/J/mandelbrot-set-3.j +++ b/Task/Mandelbrot-set/J/mandelbrot-set-3.j @@ -1 +1 @@ - viewmat mcf "0 @ domain (_2j_1 1j1) ; 0.1 NB. Complex interval and resolution +viewmat mcf "0 @ domain (_2j_1 1j1) ; 0.1 NB. Complex interval and resolution diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-1.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-1.jl similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-1.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-1.jl diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-2.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-2.jl similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-2.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-2.jl diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-3.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-3.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl similarity index 92% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl index 92ddc5c85b..8ca557e392 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl @@ -32,7 +32,8 @@ heatmap(D .^ 1.0, c=:bone_1) savefig("Mandelbrot_normal_map_1.png") N = abs.(Z) .> 2 # advanced normal map effect using higher derivatives (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])) +H, K, L = abs.(Z[N] ./ dZ[N]), abs.(dZ[N] ./ ddZ[N]), log.(abs.(Z[N])) +U = Z[N] ./ dZ[N] .- (H ./ K) .^ 2 .* L ./ (1 .+ L) .* dZ[N] ./ ddZ[N] U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-7.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl similarity index 100% rename from Task/Mandelbrot-set/Julia/mandelbrot-set-7.julia rename to Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl diff --git a/Task/Mandelbrot-set/Kotlin/mandelbrot-set.kotlin b/Task/Mandelbrot-set/Kotlin/mandelbrot-set.kts similarity index 100% rename from Task/Mandelbrot-set/Kotlin/mandelbrot-set.kotlin rename to Task/Mandelbrot-set/Kotlin/mandelbrot-set.kts diff --git a/Task/Mandelbrot-set/OCaml/mandelbrot-set.ocaml b/Task/Mandelbrot-set/OCaml/mandelbrot-set.ml similarity index 100% rename from Task/Mandelbrot-set/OCaml/mandelbrot-set.ocaml rename to Task/Mandelbrot-set/OCaml/mandelbrot-set.ml diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py index 80841dd274..e240ab78e6 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py @@ -22,7 +22,7 @@ plt.imshow(S ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") plt.savefig("Mandelbrot_set_1.png", dpi=200) N = abs(Z) >= r # normalized iteration count -T[N] = T[N] - np.log2(np.log(np.abs(Z[N])) / np.log(r)) +T[N] = T[N] - np.log2(np.log(abs(Z[N])) / np.log(r)) plt.imshow(T ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") plt.savefig("Mandelbrot_set_2.png", dpi=200) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py index 36cd656b0d..8173f62c10 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py @@ -23,7 +23,7 @@ for k in range(n): N = abs(Z) >= r # basic normal map effect and stripe average coloring (potential function) P, Q = S[N] / T[N], (S[N] + np.sin(density * np.angle(Z[N]))) / (T[N] + 1) -U, V = Z[N] / dZ[N], 1 + (np.log2(np.log(np.abs(Z[N])) / np.log(r)) * (P - Q) + Q) * intensity +U, V = Z[N] / dZ[N], 1 + (np.log2(np.log(abs(Z[N])) / np.log(r)) * (P - Q) + Q) * intensity U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and light vector D[N] = np.maximum((U.real * v.real + U.imag * v.imag + V * height) / (1 + height), 0) @@ -31,7 +31,8 @@ plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower") plt.savefig("Mandelbrot_normal_map_1.png", dpi=200) N = abs(Z) > 2 # advanced normal map effect using higher derivatives (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])) +H, K, L = abs(Z[N] / dZ[N]), abs(dZ[N] / ddZ[N]), np.log(abs(Z[N])) +U = Z[N] / dZ[N] - (H / K) ** 2 * L / (1 + L) * dZ[N] / ddZ[N] U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and light vector D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0) diff --git a/Task/Mandelbrot-set/Rust/mandelbrot-set.rust b/Task/Mandelbrot-set/Rust/mandelbrot-set.rs similarity index 100% rename from Task/Mandelbrot-set/Rust/mandelbrot-set.rust rename to Task/Mandelbrot-set/Rust/mandelbrot-set.rs diff --git a/Task/Mandelbrot-set/Scheme/mandelbrot-set-1.ss b/Task/Mandelbrot-set/Scheme/mandelbrot-set-1.scm similarity index 100% rename from Task/Mandelbrot-set/Scheme/mandelbrot-set-1.ss rename to Task/Mandelbrot-set/Scheme/mandelbrot-set-1.scm diff --git a/Task/Mandelbrot-set/Scheme/mandelbrot-set-2.ss b/Task/Mandelbrot-set/Scheme/mandelbrot-set-2.scm similarity index 100% rename from Task/Mandelbrot-set/Scheme/mandelbrot-set-2.ss rename to Task/Mandelbrot-set/Scheme/mandelbrot-set-2.scm diff --git a/Task/Map-range/Elixir/map-range.elixir b/Task/Map-range/Elixir/map-range.ex similarity index 100% rename from Task/Map-range/Elixir/map-range.elixir rename to Task/Map-range/Elixir/map-range.ex diff --git a/Task/Map-range/Euphoria/map-range.euphoria b/Task/Map-range/Euphoria/map-range.ex similarity index 100% rename from Task/Map-range/Euphoria/map-range.euphoria rename to Task/Map-range/Euphoria/map-range.ex diff --git a/Task/Map-range/Julia/map-range.julia b/Task/Map-range/Julia/map-range.jl similarity index 100% rename from Task/Map-range/Julia/map-range.julia rename to Task/Map-range/Julia/map-range.jl diff --git a/Task/Map-range/Kotlin/map-range.kotlin b/Task/Map-range/Kotlin/map-range.kts similarity index 100% rename from Task/Map-range/Kotlin/map-range.kotlin rename to Task/Map-range/Kotlin/map-range.kts diff --git a/Task/Map-range/OCaml/map-range-1.ocaml b/Task/Map-range/OCaml/map-range-1.ml similarity index 100% rename from Task/Map-range/OCaml/map-range-1.ocaml rename to Task/Map-range/OCaml/map-range-1.ml diff --git a/Task/Map-range/OCaml/map-range-2.ocaml b/Task/Map-range/OCaml/map-range-2.ml similarity index 100% rename from Task/Map-range/OCaml/map-range-2.ocaml rename to Task/Map-range/OCaml/map-range-2.ml diff --git a/Task/Map-range/Rust/map-range.rust b/Task/Map-range/Rust/map-range.rs similarity index 100% rename from Task/Map-range/Rust/map-range.rust rename to Task/Map-range/Rust/map-range.rs diff --git a/Task/Mastermind/EasyLang/mastermind.easy b/Task/Mastermind/EasyLang/mastermind.easy index c7155969ca..0ad14ab4a5 100644 --- a/Task/Mastermind/EasyLang/mastermind.easy +++ b/Task/Mastermind/EasyLang/mastermind.easy @@ -1,3 +1,5 @@ +# Mastermind:w90 +# col[] = [ 802 990 171 229 950 808 ] len code[] 4 len guess[] 4 @@ -100,7 +102,7 @@ on timer proc new . . init_vars for i to 4 - code[i] = randint 6 + code[i] = random 6 . color 531 move 10 10 diff --git a/Task/Mastermind/Julia/mastermind.julia b/Task/Mastermind/Julia/mastermind.jl similarity index 100% rename from Task/Mastermind/Julia/mastermind.julia rename to Task/Mastermind/Julia/mastermind.jl diff --git a/Task/Mastermind/Kotlin/mastermind.kotlin b/Task/Mastermind/Kotlin/mastermind.kts similarity index 100% rename from Task/Mastermind/Kotlin/mastermind.kotlin rename to Task/Mastermind/Kotlin/mastermind.kts diff --git a/Task/Mastermind/Rust/mastermind.rust b/Task/Mastermind/Rust/mastermind.rs similarity index 100% rename from Task/Mastermind/Rust/mastermind.rust rename to Task/Mastermind/Rust/mastermind.rs diff --git a/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy b/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy new file mode 100644 index 0000000000..091dd80778 --- /dev/null +++ b/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy @@ -0,0 +1,41 @@ +global m[][] s[][] dims[] . +proc mat_chain_order . . + n = len dims[] - 1 + m[][] = [ ] ; len m[][] n + s[][] = [ ] ; len s[][] n + for i = 1 to n + len m[i][] n + len s[i][] n + . + for lng = 2 to n + for i = 1 to n - lng + 1 + j = i + lng - 1 + m[i][j] = 1 / 0 + for k = i to j - 1 + cost = m[i][k] + m[k + 1][j] + dims[i] * dims[k + 1] * dims[j + 1] + if cost < m[i][j] + m[i][j] = cost + s[i][j] = k + . + . + . + . +. +func$ path a b . + if a = b + return strchar (64 + a) + . + return "(" & path a s[a][b] & path (s[a][b] + 1) b & ")" +. +proc pr_chain_order . . + print "Order : " & path 1 len s[][] +. +dims[][] = [ [ 5 6 3 1 ] [ 1 5 25 30 100 70 2 1 100 250 1 1000 2 ] [ 1000 1 500 12 1 700 2500 3 2 5 14 10 ] ] +for i to len dims[][] + dims[] = dims[i][] + print "Dims : " & dims[] + mat_chain_order + pr_chain_order + print "Cost : " & m[1][len s[][]] + print "" +. diff --git a/Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-1.julia b/Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-1.jl similarity index 100% rename from Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-1.julia rename to Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-1.jl diff --git a/Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-2.julia b/Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-2.jl similarity index 100% rename from Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-2.julia rename to Task/Matrix-chain-multiplication/Julia/matrix-chain-multiplication-2.jl diff --git a/Task/Matrix-chain-multiplication/Kotlin/matrix-chain-multiplication.kotlin b/Task/Matrix-chain-multiplication/Kotlin/matrix-chain-multiplication.kts similarity index 100% rename from Task/Matrix-chain-multiplication/Kotlin/matrix-chain-multiplication.kotlin rename to Task/Matrix-chain-multiplication/Kotlin/matrix-chain-multiplication.kts diff --git a/Task/Matrix-chain-multiplication/Rust/matrix-chain-multiplication.rust b/Task/Matrix-chain-multiplication/Rust/matrix-chain-multiplication.rs similarity index 100% rename from Task/Matrix-chain-multiplication/Rust/matrix-chain-multiplication.rust rename to Task/Matrix-chain-multiplication/Rust/matrix-chain-multiplication.rs diff --git a/Task/Matrix-digital-rain/Julia/matrix-digital-rain.julia b/Task/Matrix-digital-rain/Julia/matrix-digital-rain.jl similarity index 100% rename from Task/Matrix-digital-rain/Julia/matrix-digital-rain.julia rename to Task/Matrix-digital-rain/Julia/matrix-digital-rain.jl diff --git a/Task/Matrix-digital-rain/Rust/matrix-digital-rain-1.rust b/Task/Matrix-digital-rain/Rust/matrix-digital-rain-1.rs similarity index 100% rename from Task/Matrix-digital-rain/Rust/matrix-digital-rain-1.rust rename to Task/Matrix-digital-rain/Rust/matrix-digital-rain-1.rs diff --git a/Task/Matrix-digital-rain/Rust/matrix-digital-rain-2.rust b/Task/Matrix-digital-rain/Rust/matrix-digital-rain-2.rs similarity index 100% rename from Task/Matrix-digital-rain/Rust/matrix-digital-rain-2.rust rename to Task/Matrix-digital-rain/Rust/matrix-digital-rain-2.rs diff --git a/Task/Matrix-exponentiation-operator/Delphi/matrix-exponentiation-operator.delphi b/Task/Matrix-exponentiation-operator/Delphi/matrix-exponentiation-operator.pas similarity index 100% rename from Task/Matrix-exponentiation-operator/Delphi/matrix-exponentiation-operator.delphi rename to Task/Matrix-exponentiation-operator/Delphi/matrix-exponentiation-operator.pas diff --git a/Task/Matrix-exponentiation-operator/EasyLang/matrix-exponentiation-operator.easy b/Task/Matrix-exponentiation-operator/EasyLang/matrix-exponentiation-operator.easy new file mode 100644 index 0000000000..0153f1a8c5 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/EasyLang/matrix-exponentiation-operator.easy @@ -0,0 +1,25 @@ +func[][] mmul m1[][] m2[][] . + for i to len m1[][] + r[][] &= [ ] + for j = 1 to len m2[1][] + r[i][] &= 0 + for k to len m2[][] + r[i][j] += m1[i][k] * m2[k][j] + . + . + . + return r[][] +. +func[][] mexp m[][] e . + n = len m[][] + len r[][] n + for i to n + len r[i][] n + r[i][i] = 1 + . + for i to e + r[][] = mmul r[][] m[][] + . + return r[][] +. +print mexp [ [ 4 3 ] [ 2 1 ] ] 3 diff --git a/Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.julia b/Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.jl similarity index 100% rename from Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.julia rename to Task/Matrix-exponentiation-operator/Julia/matrix-exponentiation-operator.jl diff --git a/Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kotlin b/Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kts similarity index 100% rename from Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kotlin rename to Task/Matrix-exponentiation-operator/Kotlin/matrix-exponentiation-operator.kts diff --git a/Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-1.ocaml b/Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-1.ml similarity index 100% rename from Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-1.ocaml rename to Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-1.ml diff --git a/Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-2.ocaml b/Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-2.ml similarity index 100% rename from Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-2.ocaml rename to Task/Matrix-exponentiation-operator/OCaml/matrix-exponentiation-operator-2.ml diff --git a/Task/Matrix-exponentiation-operator/PascalABC.NET/matrix-exponentiation-operator.pas b/Task/Matrix-exponentiation-operator/PascalABC.NET/matrix-exponentiation-operator.pas new file mode 100644 index 0000000000..483be0fb87 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/PascalABC.NET/matrix-exponentiation-operator.pas @@ -0,0 +1,19 @@ +uses NumLibABC; + +function operator **(m: Matrix; exp: integer): Matrix; +extensionmethod; +begin + Assert(m.ColCount = m.RowCount, 'Matrix must be square.'); + Assert(exp >= 0, 'Negative exponents not supported'); + result := Matrix.Diag(m.RowCount, 1); + loop exp do result := result * m; +end; + +begin + var A := new Matrix(2, 2, 1, 1, 1, 0); + 'Original: '.Println; + A.Println; + A := A ** 10; + 'Raised to the power of 10: '.Println; + A.Println; +end. diff --git a/Task/Matrix-exponentiation-operator/Rust/matrix-exponentiation-operator.rust b/Task/Matrix-exponentiation-operator/Rust/matrix-exponentiation-operator.rs similarity index 100% rename from Task/Matrix-exponentiation-operator/Rust/matrix-exponentiation-operator.rust rename to Task/Matrix-exponentiation-operator/Rust/matrix-exponentiation-operator.rs diff --git a/Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.ss b/Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.scm similarity index 100% rename from Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.ss rename to Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.scm diff --git a/Task/Matrix-multiplication/Delphi/matrix-multiplication.delphi b/Task/Matrix-multiplication/Delphi/matrix-multiplication.pas similarity index 100% rename from Task/Matrix-multiplication/Delphi/matrix-multiplication.delphi rename to Task/Matrix-multiplication/Delphi/matrix-multiplication.pas diff --git a/Task/Matrix-multiplication/Elixir/matrix-multiplication.elixir b/Task/Matrix-multiplication/Elixir/matrix-multiplication.ex similarity index 100% rename from Task/Matrix-multiplication/Elixir/matrix-multiplication.elixir rename to Task/Matrix-multiplication/Elixir/matrix-multiplication.ex diff --git a/Task/Matrix-multiplication/Euphoria/matrix-multiplication.euphoria b/Task/Matrix-multiplication/Euphoria/matrix-multiplication.ex similarity index 100% rename from Task/Matrix-multiplication/Euphoria/matrix-multiplication.euphoria rename to Task/Matrix-multiplication/Euphoria/matrix-multiplication.ex diff --git a/Task/Matrix-multiplication/Julia/matrix-multiplication.julia b/Task/Matrix-multiplication/Julia/matrix-multiplication.jl similarity index 100% rename from Task/Matrix-multiplication/Julia/matrix-multiplication.julia rename to Task/Matrix-multiplication/Julia/matrix-multiplication.jl diff --git a/Task/Matrix-multiplication/Kotlin/matrix-multiplication.kotlin b/Task/Matrix-multiplication/Kotlin/matrix-multiplication.kts similarity index 100% rename from Task/Matrix-multiplication/Kotlin/matrix-multiplication.kotlin rename to Task/Matrix-multiplication/Kotlin/matrix-multiplication.kts diff --git a/Task/Matrix-multiplication/NewLISP/matrix-multiplication-1.l b/Task/Matrix-multiplication/NewLISP/matrix-multiplication-1.l new file mode 100644 index 0000000000..cb2b35e890 --- /dev/null +++ b/Task/Matrix-multiplication/NewLISP/matrix-multiplication-1.l @@ -0,0 +1,6 @@ +(multiply + '((1 2) (3 4)) + '((-3 -8 3) (-2 1 4))) + +((-7 -6 11) + (-17 -20 25)) diff --git a/Task/Matrix-multiplication/NewLISP/matrix-multiplication-2.l b/Task/Matrix-multiplication/NewLISP/matrix-multiplication-2.l new file mode 100644 index 0000000000..cc6a293c2e --- /dev/null +++ b/Task/Matrix-multiplication/NewLISP/matrix-multiplication-2.l @@ -0,0 +1,33 @@ +(multiply + (array 2 2 '(1 2 3 4)) + (array 2 3 '(-3 -8 3 -2 1 4))) + +((-7 -6 11) + (-17 -20 25)) + +(multiply + (array 3 2 '(1 2 3 4 3 6)) + (array 2 3 '(-3 -8 3 -2 1 4))) + +((-7 -6 11) + (-17 -20 25) + (-21 -18 33)) + + +(multiply + (array 3 3 '(1 2 3 4 5 6 7 8 9)) + (array 3 3 '(2 2 2 5 5 5 7 7 7))) + +((33 33 33) + (75 75 75) + (117 117 117)) + + +(multiply + (array 4 2 '(1 2 3 4 5 6 7 8)) + (array 2 3 '(1 2 3 4 5 6))) + +((9 12 15) + (19 26 33) + (29 40 51) + (39 54 69)) diff --git a/Task/Matrix-multiplication/OCaml/matrix-multiplication-1.ocaml b/Task/Matrix-multiplication/OCaml/matrix-multiplication-1.ml similarity index 100% rename from Task/Matrix-multiplication/OCaml/matrix-multiplication-1.ocaml rename to Task/Matrix-multiplication/OCaml/matrix-multiplication-1.ml diff --git a/Task/Matrix-multiplication/OCaml/matrix-multiplication-2.ocaml b/Task/Matrix-multiplication/OCaml/matrix-multiplication-2.ml similarity index 100% rename from Task/Matrix-multiplication/OCaml/matrix-multiplication-2.ocaml rename to Task/Matrix-multiplication/OCaml/matrix-multiplication-2.ml diff --git a/Task/Matrix-multiplication/PascalABC.NET/matrix-multiplication.pas b/Task/Matrix-multiplication/PascalABC.NET/matrix-multiplication.pas new file mode 100644 index 0000000000..cf84afb6d4 --- /dev/null +++ b/Task/Matrix-multiplication/PascalABC.NET/matrix-multiplication.pas @@ -0,0 +1,13 @@ +uses NumLibABC; + +begin + var A := new Matrix(4, 2, 1, 2, 3, 4, 5, 6, 7, 8); + var B := new Matrix(2, 3, 1, 2, 3, 4, 5, 6); + var C := A * B; + 'Matrix A:'.Println; + A.Println(2, 0); + 'Matrix B:'.Println; + B.Println(2, 0); + 'Matrix A * B:'.Println; + C.Println(3, 0); +end. diff --git a/Task/Matrix-multiplication/Rust/matrix-multiplication.rust b/Task/Matrix-multiplication/Rust/matrix-multiplication.rs similarity index 100% rename from Task/Matrix-multiplication/Rust/matrix-multiplication.rust rename to Task/Matrix-multiplication/Rust/matrix-multiplication.rs diff --git a/Task/Matrix-multiplication/Scheme/matrix-multiplication.ss b/Task/Matrix-multiplication/Scheme/matrix-multiplication.scm similarity index 100% rename from Task/Matrix-multiplication/Scheme/matrix-multiplication.ss rename to Task/Matrix-multiplication/Scheme/matrix-multiplication.scm diff --git a/Task/Matrix-transposition/Elixir/matrix-transposition.elixir b/Task/Matrix-transposition/Elixir/matrix-transposition.ex similarity index 100% rename from Task/Matrix-transposition/Elixir/matrix-transposition.elixir rename to Task/Matrix-transposition/Elixir/matrix-transposition.ex diff --git a/Task/Matrix-transposition/Euphoria/matrix-transposition.euphoria b/Task/Matrix-transposition/Euphoria/matrix-transposition.ex similarity index 100% rename from Task/Matrix-transposition/Euphoria/matrix-transposition.euphoria rename to Task/Matrix-transposition/Euphoria/matrix-transposition.ex diff --git a/Task/Matrix-transposition/Julia/matrix-transposition.julia b/Task/Matrix-transposition/Julia/matrix-transposition.jl similarity index 100% rename from Task/Matrix-transposition/Julia/matrix-transposition.julia rename to Task/Matrix-transposition/Julia/matrix-transposition.jl diff --git a/Task/Matrix-transposition/Kotlin/matrix-transposition.kotlin b/Task/Matrix-transposition/Kotlin/matrix-transposition.kts similarity index 100% rename from Task/Matrix-transposition/Kotlin/matrix-transposition.kotlin rename to Task/Matrix-transposition/Kotlin/matrix-transposition.kts diff --git a/Task/Matrix-transposition/Nu/matrix-transposition.nu b/Task/Matrix-transposition/Nu/matrix-transposition.nu new file mode 100644 index 0000000000..02163c2401 --- /dev/null +++ b/Task/Matrix-transposition/Nu/matrix-transposition.nu @@ -0,0 +1,5 @@ +def 'matrix transpose' [] { + each { into record } | values +} + +[[1 5 9] [2 6 10] [3 7 11] [4 8 12]] | matrix transpose | to nuon diff --git a/Task/Matrix-transposition/OCaml/matrix-transposition-1.ocaml b/Task/Matrix-transposition/OCaml/matrix-transposition-1.ml similarity index 100% rename from Task/Matrix-transposition/OCaml/matrix-transposition-1.ocaml rename to Task/Matrix-transposition/OCaml/matrix-transposition-1.ml diff --git a/Task/Matrix-transposition/OCaml/matrix-transposition-2.ocaml b/Task/Matrix-transposition/OCaml/matrix-transposition-2.ml similarity index 100% rename from Task/Matrix-transposition/OCaml/matrix-transposition-2.ocaml rename to Task/Matrix-transposition/OCaml/matrix-transposition-2.ml diff --git a/Task/Matrix-transposition/PascalABC.NET/matrix-transposition.pas b/Task/Matrix-transposition/PascalABC.NET/matrix-transposition.pas new file mode 100644 index 0000000000..63a2b0d315 --- /dev/null +++ b/Task/Matrix-transposition/PascalABC.NET/matrix-transposition.pas @@ -0,0 +1,13 @@ +uses NumLibABC; + +begin + var A := new Matrix(4, 3, + 1, 2, 3, + 4, 5, 6, + 7, 8, 9, + 10, 11, 12); + 'Original:'.Println; + A.Println(3, 0); + 'Transposed:'.Println; + A.Transpose.Println(3, 0); +end. diff --git a/Task/Matrix-transposition/Rust/matrix-transposition-1.rust b/Task/Matrix-transposition/Rust/matrix-transposition-1.rs similarity index 100% rename from Task/Matrix-transposition/Rust/matrix-transposition-1.rust rename to Task/Matrix-transposition/Rust/matrix-transposition-1.rs diff --git a/Task/Matrix-transposition/Rust/matrix-transposition-2.rust b/Task/Matrix-transposition/Rust/matrix-transposition-2.rs similarity index 100% rename from Task/Matrix-transposition/Rust/matrix-transposition-2.rust rename to Task/Matrix-transposition/Rust/matrix-transposition-2.rs diff --git a/Task/Matrix-transposition/SETL/matrix-transposition.setl b/Task/Matrix-transposition/SETL/matrix-transposition.setl new file mode 100644 index 0000000000..b2cee55b9e --- /dev/null +++ b/Task/Matrix-transposition/SETL/matrix-transposition.setl @@ -0,0 +1,10 @@ +program matrix_transposition; + mat := [[1,2,3,4], [5,6,7,8], [9,10,11,12]]; + print(mat); + print(' -> '); + print(transpose(mat)); + + proc transpose(m); + return [[m(y)(x) : y in [1..#m]] : x in [1..#m(1)]]; + end proc; +end program; diff --git a/Task/Matrix-transposition/Scheme/matrix-transposition.ss b/Task/Matrix-transposition/Scheme/matrix-transposition.scm similarity index 100% rename from Task/Matrix-transposition/Scheme/matrix-transposition.ss rename to Task/Matrix-transposition/Scheme/matrix-transposition.scm diff --git a/Task/Matrix-transposition/Tailspin/matrix-transposition.tailspin b/Task/Matrix-transposition/Tailspin/matrix-transposition-1.tailspin similarity index 100% rename from Task/Matrix-transposition/Tailspin/matrix-transposition.tailspin rename to Task/Matrix-transposition/Tailspin/matrix-transposition-1.tailspin diff --git a/Task/Matrix-transposition/Tailspin/matrix-transposition-2.tailspin b/Task/Matrix-transposition/Tailspin/matrix-transposition-2.tailspin new file mode 100644 index 0000000000..f75b08a52f --- /dev/null +++ b/Task/Matrix-transposition/Tailspin/matrix-transposition-2.tailspin @@ -0,0 +1,26 @@ +transpose templates + a is $; + $a(1; .. as j; -> $a(..; $j)) ! +end transpose + +printMatrix templates + formatN templates + @ set []; + $ -> !# + '$@ -> $::length~..2 -> ' ';$@(..:-1)...;' ! + when <|1..> do ..|@ set $ mod 10; $ ~/ 10 -> !# + end formatN + $... -> '|$($::first) -> formatN;$(~..)... -> ', $ -> formatN;';| +' ! +end printMatrix + +m is [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]; +'before: +' ! +$m -> printMatrix ! + +mT is $m -> transpose; +' +transposed: +' ! +$mT -> printMatrix ! diff --git a/Task/Maximum-triangle-path-sum/Elixir/maximum-triangle-path-sum.elixir b/Task/Maximum-triangle-path-sum/Elixir/maximum-triangle-path-sum.ex similarity index 100% rename from Task/Maximum-triangle-path-sum/Elixir/maximum-triangle-path-sum.elixir rename to Task/Maximum-triangle-path-sum/Elixir/maximum-triangle-path-sum.ex diff --git a/Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.julia b/Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.jl similarity index 100% rename from Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.julia rename to Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.jl diff --git a/Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kotlin b/Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kts similarity index 100% rename from Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kotlin rename to Task/Maximum-triangle-path-sum/Kotlin/maximum-triangle-path-sum.kts diff --git a/Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rust b/Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rs similarity index 100% rename from Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rust rename to Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rs diff --git a/Task/Mayan-calendar/Julia/mayan-calendar.julia b/Task/Mayan-calendar/Julia/mayan-calendar.jl similarity index 100% rename from Task/Mayan-calendar/Julia/mayan-calendar.julia rename to Task/Mayan-calendar/Julia/mayan-calendar.jl diff --git a/Task/Mayan-numerals/Julia/mayan-numerals-1.julia b/Task/Mayan-numerals/Julia/mayan-numerals-1.jl similarity index 100% rename from Task/Mayan-numerals/Julia/mayan-numerals-1.julia rename to Task/Mayan-numerals/Julia/mayan-numerals-1.jl diff --git a/Task/Mayan-numerals/Julia/mayan-numerals-2.julia b/Task/Mayan-numerals/Julia/mayan-numerals-2.jl similarity index 100% rename from Task/Mayan-numerals/Julia/mayan-numerals-2.julia rename to Task/Mayan-numerals/Julia/mayan-numerals-2.jl diff --git a/Task/Mayan-numerals/Rust/mayan-numerals.rust b/Task/Mayan-numerals/Rust/mayan-numerals.rs similarity index 100% rename from Task/Mayan-numerals/Rust/mayan-numerals.rust rename to Task/Mayan-numerals/Rust/mayan-numerals.rs diff --git a/Task/Maze-generation/Delphi/maze-generation.delphi b/Task/Maze-generation/Delphi/maze-generation.pas similarity index 100% rename from Task/Maze-generation/Delphi/maze-generation.delphi rename to Task/Maze-generation/Delphi/maze-generation.pas diff --git a/Task/Maze-generation/EasyLang/maze-generation.easy b/Task/Maze-generation/EasyLang/maze-generation.easy index 043b229e65..cc5c352028 100644 --- a/Task/Maze-generation/EasyLang/maze-generation.easy +++ b/Task/Maze-generation/EasyLang/maze-generation.easy @@ -24,7 +24,7 @@ proc m_maze pos . . show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 - d = randint i + d = random i dir = offs[d[d]] d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 @@ -44,7 +44,7 @@ proc make_maze . . m[n * i - n + 1] = 2 m[n * n - n + i] = 2 . - h = 2 * randint 15 - n + n * 2 * randint 15 + h = 2 * random 15 - n + n * 2 * random 15 m_maze h m[endpos] = 0 endpos += n diff --git a/Task/Maze-generation/Elixir/maze-generation.elixir b/Task/Maze-generation/Elixir/maze-generation.ex similarity index 100% rename from Task/Maze-generation/Elixir/maze-generation.elixir rename to Task/Maze-generation/Elixir/maze-generation.ex diff --git a/Task/Maze-generation/FutureBasic/maze-generation.basic b/Task/Maze-generation/FutureBasic/maze-generation.basic index b112b74bdc..4013335896 100644 --- a/Task/Maze-generation/FutureBasic/maze-generation.basic +++ b/Task/Maze-generation/FutureBasic/maze-generation.basic @@ -57,7 +57,7 @@ end fn void local fn DrawMaze long r, c, x = _mgn, y = _mgn, value - pen 2,, NSLineCapStyleRound + pen 2, fn ColorText, NSLineCapStyleRound for r = 0 to _rows - 1 for c = 0 to _cols - 1 diff --git a/Task/Maze-generation/Julia/maze-generation-1.julia b/Task/Maze-generation/Julia/maze-generation-1.jl similarity index 100% rename from Task/Maze-generation/Julia/maze-generation-1.julia rename to Task/Maze-generation/Julia/maze-generation-1.jl diff --git a/Task/Maze-generation/Julia/maze-generation-2.julia b/Task/Maze-generation/Julia/maze-generation-2.jl similarity index 100% rename from Task/Maze-generation/Julia/maze-generation-2.julia rename to Task/Maze-generation/Julia/maze-generation-2.jl diff --git a/Task/Maze-generation/Kotlin/maze-generation.kotlin b/Task/Maze-generation/Kotlin/maze-generation.kts similarity index 100% rename from Task/Maze-generation/Kotlin/maze-generation.kotlin rename to Task/Maze-generation/Kotlin/maze-generation.kts diff --git a/Task/Maze-generation/OCaml/maze-generation.ocaml b/Task/Maze-generation/OCaml/maze-generation.ml similarity index 100% rename from Task/Maze-generation/OCaml/maze-generation.ocaml rename to Task/Maze-generation/OCaml/maze-generation.ml diff --git a/Task/Maze-generation/Rust/maze-generation.rust b/Task/Maze-generation/Rust/maze-generation.rs similarity index 100% rename from Task/Maze-generation/Rust/maze-generation.rust rename to Task/Maze-generation/Rust/maze-generation.rs diff --git a/Task/Maze-solving/Delphi/maze-solving.delphi b/Task/Maze-solving/Delphi/maze-solving.pas similarity index 100% rename from Task/Maze-solving/Delphi/maze-solving.delphi rename to Task/Maze-solving/Delphi/maze-solving.pas diff --git a/Task/Maze-solving/EasyLang/maze-solving.easy b/Task/Maze-solving/EasyLang/maze-solving.easy index 29daa66062..52f27f223c 100644 --- a/Task/Maze-solving/EasyLang/maze-solving.easy +++ b/Task/Maze-solving/EasyLang/maze-solving.easy @@ -23,7 +23,7 @@ proc m_maze pos . . show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 - d = randint i + d = random i dir = offs[d[d]] d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 @@ -43,7 +43,7 @@ proc make_maze . . m[n * i - n + 1] = 2 m[n * n - n + i] = 2 . - h = 2 * randint 15 - n + n * 2 * randint 15 + h = 2 * random 15 - n + n * 2 * random 15 m_maze h m[endpos] = 0 . @@ -68,7 +68,7 @@ proc solve dir0 pos . . found = 1 return . - of = randint 4 - 1 + of = random 4 - 1 for h = 1 to 4 dir = (h + of) mod1 4 posn = pos + offs[dir] diff --git a/Task/Maze-solving/FreeBASIC/maze-solving.basic b/Task/Maze-solving/FreeBASIC/maze-solving.basic new file mode 100644 index 0000000000..9971576799 --- /dev/null +++ b/Task/Maze-solving/FreeBASIC/maze-solving.basic @@ -0,0 +1,95 @@ +Const MazeWidth = 11 +Const MazeHeight = 9 +Const MazeCell = 50 + +Dim Shared dstx As Integer = MazeWidth - 1 +Dim Shared dsty As Integer = 0 + +Screenres MazeWidth * MazeCell, MazeHeight * MazeCell, 32 +Windowtitle "Maze solving" + +Sub Cell(Maze() As Integer, Byval x As Integer, Byval y As Integer, Byval w As Integer, Byval h As Integer, Byval s As Integer) + Dim As Integer i, p, q, r + Maze(x, y) Or= &H40 + r = Rnd * 4 + For i = r To r + 3 + Select Case i Mod 4 + Case 0: p = x - 1 : q = y + Case 1: p = x + 1 : q = y + Case 2: p = x : q = y - 1 + Case 3: p = x : q = y + 1 + End Select + If p >= 0 And p < w And q >= 0 And q < h And Maze(p, q) < &H40 Then + If p > x Then Maze(p, q) Or= 1 : Line (p * s, y * s + 4) - (p * s, (y + 1) * s - 4), Rgb(0, 0, 0) + If q > y Then Maze(p, q) Or= 2 : Line (x * s + 4, q * s) - ((x + 1) * s - 4, q * s), Rgb(0, 0, 0) + If x > p Then Maze(x, y) Or= 1 : Line (x * s, y * s + 4) - (x * s, (y + 1) * s - 4), Rgb(0, 0, 0) + If y > q Then Maze(x, y) Or= 2 : Line (x * s + 4, y * s) - ((x + 1) * s - 4, y * s), Rgb(0, 0, 0) + Cell Maze(), p, q, w, h, s + End If + Next +End Sub + +Sub GenerateMaze(Maze() As Integer, Byval w As Integer, Byval h As Integer, Byval s As Integer) + Dim As Integer x, y + Redim Maze(w, h) + For y = 0 To h - 1 + Line (0, y * s) - (w * s, y * s), Rgb(255, 255, 255) + Next + For x = 0 To w - 1 + Line (x * s, 0) - (x * s, h * s), Rgb(255, 255, 255) + Next + Cell Maze(), Rnd * w, Rnd * h, w, h, s +End Sub + +Sub SolveMaze(Path() As Integer, Maze() As Integer, Byval x As Integer, Byval y As Integer, Byval dstx As Integer, Byval dsty As Integer, Byval s As Integer) + Dim As Integer h, i, n, p, q, w + w = Ubound(Maze, 1) + h = Ubound(Maze, 2) + Redim Path(w * h, 1) + Maze(x, y) Or= &H80 + Do + For i = 0 To 3 + Select Case i + Case 0: p = x - 1 : q = y + Case 1: p = x + 1 : q = y + Case 2: p = x : q = y - 1 + Case 3: p = x : q = y + 1 + End Select + If p >= 0 And p < w And q >= 0 And q < h And Maze(p, q) < &H80 Then + If p > x And Maze(p, q) And 1 Then Exit For + If q > y And Maze(p, q) And 2 Then Exit For + If x > p And Maze(x, y) And 1 Then Exit For + If y > q And Maze(x, y) And 2 Then Exit For + End If + Next + If i < 4 Then + Maze(p, q) Or= &H80 + Path(n, 0) = x + Path(n, 1) = y + Line ((x + 0.5) * s, (y + 0.5) * s) - ((p + 0.5) * s, (q + 0.5) * s), Rgb(255, 0, 0), , &b0001111111111100 + n += 1 + Else + If n > 0 Then + n -= 1 + p = Path(n, 0) + q = Path(n, 1) + Line ((x + 0.5) * s, (y + 0.5) * s) - ((p + 0.5) * s, (q + 0.5) * s), Rgb(0, 0, 0) + End If + End If + x = p + y = q + Sleep 200 + Loop Until x = dstx And y = dsty Or Inkey <> "" + Path(n, 0) = x + Path(n, 1) = y +End Sub + +Dim Maze() As Integer +Dim Path() As Integer + +Randomize Timer +GenerateMaze(Maze(), MazeWidth, MazeHeight, MazeCell) +SolveMaze(Path(), Maze(), 0, MazeHeight - 1, MazeWidth - 1, 0, MazeCell) +Windowtitle "Maze solving ** RESOLVED **" + +Sleep diff --git a/Task/Maze-solving/Julia/maze-solving.julia b/Task/Maze-solving/Julia/maze-solving.jl similarity index 100% rename from Task/Maze-solving/Julia/maze-solving.julia rename to Task/Maze-solving/Julia/maze-solving.jl diff --git a/Task/Maze-solving/Kotlin/maze-solving.kotlin b/Task/Maze-solving/Kotlin/maze-solving.kts similarity index 100% rename from Task/Maze-solving/Kotlin/maze-solving.kotlin rename to Task/Maze-solving/Kotlin/maze-solving.kts diff --git a/Task/Maze-solving/Rust/maze-solving.rust b/Task/Maze-solving/Rust/maze-solving.rs similarity index 100% rename from Task/Maze-solving/Rust/maze-solving.rust rename to Task/Maze-solving/Rust/maze-solving.rs diff --git a/Task/McNuggets-problem/Elixir/mcnuggets-problem.elixir b/Task/McNuggets-problem/Elixir/mcnuggets-problem.ex similarity index 100% rename from Task/McNuggets-problem/Elixir/mcnuggets-problem.elixir rename to Task/McNuggets-problem/Elixir/mcnuggets-problem.ex diff --git a/Task/McNuggets-problem/Julia/mcnuggets-problem.julia b/Task/McNuggets-problem/Julia/mcnuggets-problem.jl similarity index 100% rename from Task/McNuggets-problem/Julia/mcnuggets-problem.julia rename to Task/McNuggets-problem/Julia/mcnuggets-problem.jl diff --git a/Task/McNuggets-problem/Kotlin/mcnuggets-problem.kotlin b/Task/McNuggets-problem/Kotlin/mcnuggets-problem.kts similarity index 100% rename from Task/McNuggets-problem/Kotlin/mcnuggets-problem.kotlin rename to Task/McNuggets-problem/Kotlin/mcnuggets-problem.kts diff --git a/Task/McNuggets-problem/Rust/mcnuggets-problem.rust b/Task/McNuggets-problem/Rust/mcnuggets-problem.rs similarity index 100% rename from Task/McNuggets-problem/Rust/mcnuggets-problem.rust rename to Task/McNuggets-problem/Rust/mcnuggets-problem.rs diff --git a/Task/McNuggets-problem/Tailspin/mcnuggets-problem.tailspin b/Task/McNuggets-problem/Tailspin/mcnuggets-problem-1.tailspin similarity index 100% rename from Task/McNuggets-problem/Tailspin/mcnuggets-problem.tailspin rename to Task/McNuggets-problem/Tailspin/mcnuggets-problem-1.tailspin diff --git a/Task/McNuggets-problem/Tailspin/mcnuggets-problem-2.tailspin b/Task/McNuggets-problem/Tailspin/mcnuggets-problem-2.tailspin new file mode 100644 index 0000000000..5d7ba2b4f9 --- /dev/null +++ b/Task/McNuggets-problem/Tailspin/mcnuggets-problem-2.tailspin @@ -0,0 +1,10 @@ +largestNonMcNuggetNumber templates + @ set { largest: 0, mcNuggetNumbers: [1..$+20 -> 0] }; + @(mcNuggetNumbers:; [6,9,20]) set 1..3 -> 1; + 1..$ -> ! # + $@(largest:) ! + when <|?($@(mcNuggetNumbers:; $) matches <|=0>)> do @(largest:) set $; + otherwise @(mcNuggetNumbers:; [$ + 6, $ + 9, $ + 20]) set 1..3 -> 1; +end largestNonMcNuggetNumber + +100 -> largestNonMcNuggetNumber ! diff --git a/Task/Median-filter/Delphi/median-filter.delphi b/Task/Median-filter/Delphi/median-filter.pas similarity index 100% rename from Task/Median-filter/Delphi/median-filter.delphi rename to Task/Median-filter/Delphi/median-filter.pas diff --git a/Task/Median-filter/Julia/median-filter.julia b/Task/Median-filter/Julia/median-filter.jl similarity index 100% rename from Task/Median-filter/Julia/median-filter.julia rename to Task/Median-filter/Julia/median-filter.jl diff --git a/Task/Median-filter/Kotlin/median-filter.kotlin b/Task/Median-filter/Kotlin/median-filter.kts similarity index 100% rename from Task/Median-filter/Kotlin/median-filter.kotlin rename to Task/Median-filter/Kotlin/median-filter.kts diff --git a/Task/Median-filter/OCaml/median-filter-1.ocaml b/Task/Median-filter/OCaml/median-filter-1.ml similarity index 100% rename from Task/Median-filter/OCaml/median-filter-1.ocaml rename to Task/Median-filter/OCaml/median-filter-1.ml diff --git a/Task/Median-filter/OCaml/median-filter-2.ocaml b/Task/Median-filter/OCaml/median-filter-2.ml similarity index 100% rename from Task/Median-filter/OCaml/median-filter-2.ocaml rename to Task/Median-filter/OCaml/median-filter-2.ml diff --git a/Task/Meissel-Mertens-constant/ALGOL-W/meissel-mertens-constant.alg b/Task/Meissel-Mertens-constant/ALGOL-W/meissel-mertens-constant.alg new file mode 100644 index 0000000000..7b15f0668f --- /dev/null +++ b/Task/Meissel-Mertens-constant/ALGOL-W/meissel-mertens-constant.alg @@ -0,0 +1,54 @@ +begin % compute an approximation to the Meissel-Mertens constant % + integer MAX_PRIME; + MAX_PRIME := 10000000; + begin + logical array primes ( 0 :: MAX_PRIME ); + begin % construct a sieve of odd primes % + integer i, ip; + for i := 1 until MAX_PRIME do primes( i ) := true; + ip := 3; + i := 1; + while i + ip <= MAX_PRIME do begin + if primes( i ) then begin + for s := i + ip step ip until MAX_PRIME do primes( s ) := false + end if_primes__i ; + ip := ip + 2; + i := i + 1 + end while_i_plus_ip_le_MAX_PRIME + end; + begin % sum the reciprocals of the primes % + integer pCount, lastP, p, p10; + long real sum, eulersConstant; + procedure showProgress ; + write( s_w := 0, i_w := 8 + , r_format := "A", r_w := 14, r_d := 12 + , "after ", pCount, " primes, the approximation is: " + , ( sum + eulersConstant ), ", last prime considered: " + , i_w := 1 + , lastP + ); + pCount := 1; + lastP := 0; + sum := longLn( 0.5 ) + 0.5; + p := 1; + p10 := 10; + % Euler's constant from the wikipedia, truncated for long real % + eulersConstant := 0.5772156649015328606 % 0651209008240243104215933593992 %; + for i := 1 until MAX_PRIME do begin + p := p + 2; + if primes( i ) then begin + long real rp; + rp := 1 / long p; + sum := sum + longLn( 1 - rp ) + rp; + pCount := pCount + 1; + lastP := p; + if pCount = p10 then begin + showProgress; + p10 := if p10 < 1000000 THEN p10 * 10 else p10 + 1000000 + end if_pCount_eq_p10 + end if_primes__i + end for_i ; + showProgress + end + end +end. diff --git a/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp b/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp index 4d668b0a41..de0964343f 100644 --- a/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp +++ b/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp @@ -26,8 +26,8 @@ std::vector list_prime_reciprocals(const int32_t& limit) { } int main() { - std::vector prime_reciprocals = list_prime_reciprocals(100'000'000); - const double euler = 0.577'215'664'901'532'861; + std::vector prime_reciprocals = list_prime_reciprocals(100000000); + const double euler = 0.577215664901532861; double sum = 0.0; for ( double reciprocal : prime_reciprocals ) { sum += reciprocal + log(1.0 - reciprocal); diff --git a/Task/Meissel-Mertens-constant/Delphi/meissel-mertens-constant.delphi b/Task/Meissel-Mertens-constant/Delphi/meissel-mertens-constant.pas similarity index 100% rename from Task/Meissel-Mertens-constant/Delphi/meissel-mertens-constant.delphi rename to Task/Meissel-Mertens-constant/Delphi/meissel-mertens-constant.pas diff --git a/Task/Meissel-Mertens-constant/Julia/meissel-mertens-constant.julia b/Task/Meissel-Mertens-constant/Julia/meissel-mertens-constant.jl similarity index 100% rename from Task/Meissel-Mertens-constant/Julia/meissel-mertens-constant.julia rename to Task/Meissel-Mertens-constant/Julia/meissel-mertens-constant.jl diff --git a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx new file mode 100644 index 0000000000..42ff9bd545 --- /dev/null +++ b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx @@ -0,0 +1,66 @@ +include Settings + +say version; say 'Meissel-Mertens constant'; say +arg n +if n = '' then + n = 16 +numeric digits n +fact. = 0 +call Time('r'); a = BruteForce(); e = Format(Time('e'),,3) +say 'BruteForce' a '('e 'seconds)' +call Time('r'); a = UsingSieve(); e = Format(Time('e'),,3) +say 'UsingSieve' a '('e 'seconds)' +call Time('r'); a = Analytic(); e = Format(Time('e'),,3) +say 'Analytic ' a '('e 'seconds)' +call Time('r'); a = TrueValue(); e = Format(Time('e'),,3) +say 'True value' a '('e 'seconds)' +exit + +BruteForce: +procedure expose glob. +numeric digits Digits()+2 +y = 0.5-Ln(2) +do n = 3 by 2 to 1000000 + if IsPrime(n) then do + q = 1/n; t = Ln(1-q)+q; y = y+t + end +end +y = Euler()+y +numeric digits Digits()-2 +return y+0 + +UsingSieve: +procedure expose glob. prim. +numeric digits Digits()+2 +n = Primes(1000000); y = 0 +do i = 1 to n + q = 1/prim.prime.i; t = Ln(1-q)+q; y = y+t +end +y = Euler()+y +numeric digits Digits()-2 +return y+0 + +Analytic: +procedure expose glob. fact. +numeric digits Digits()+2 +y = 0; v = 0 +do n = 2 to 1000 + t = Moebius(n) * Ln(Zeta(n)) / n + if t <> 0 then do + y = y+t + if y = v then + leave + v = y + end +end +y = Euler()+y +numeric digits Digits()-2 +return y+0 + +TrueValue: +procedure +return 0.261497212847642783755426838608695859051566648261199206192064213924924510897368209714142631434246651051617+0 + +include Constants +include Functions +include Numbers diff --git a/Task/Memory-allocation/Julia/memory-allocation.julia b/Task/Memory-allocation/Julia/memory-allocation.jl similarity index 100% rename from Task/Memory-allocation/Julia/memory-allocation.julia rename to Task/Memory-allocation/Julia/memory-allocation.jl diff --git a/Task/Memory-allocation/Kotlin/memory-allocation.kotlin b/Task/Memory-allocation/Kotlin/memory-allocation.kts similarity index 100% rename from Task/Memory-allocation/Kotlin/memory-allocation.kotlin rename to Task/Memory-allocation/Kotlin/memory-allocation.kts diff --git a/Task/Memory-allocation/Rust/memory-allocation.rust b/Task/Memory-allocation/Rust/memory-allocation.rs similarity index 100% rename from Task/Memory-allocation/Rust/memory-allocation.rust rename to Task/Memory-allocation/Rust/memory-allocation.rs diff --git a/Task/Memory-layout-of-a-data-structure/Delphi/memory-layout-of-a-data-structure.delphi b/Task/Memory-layout-of-a-data-structure/Delphi/memory-layout-of-a-data-structure.pas similarity index 100% rename from Task/Memory-layout-of-a-data-structure/Delphi/memory-layout-of-a-data-structure.delphi rename to Task/Memory-layout-of-a-data-structure/Delphi/memory-layout-of-a-data-structure.pas diff --git a/Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.julia b/Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.jl similarity index 100% rename from Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.julia rename to Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.jl diff --git a/Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kotlin b/Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kts similarity index 100% rename from Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kotlin rename to Task/Memory-layout-of-a-data-structure/Kotlin/memory-layout-of-a-data-structure.kts diff --git a/Task/Memory-layout-of-a-data-structure/OCaml/memory-layout-of-a-data-structure.ocaml b/Task/Memory-layout-of-a-data-structure/OCaml/memory-layout-of-a-data-structure.ml similarity index 100% rename from Task/Memory-layout-of-a-data-structure/OCaml/memory-layout-of-a-data-structure.ocaml rename to Task/Memory-layout-of-a-data-structure/OCaml/memory-layout-of-a-data-structure.ml diff --git a/Task/Menu/AArch64-Assembly/menu.aarch64 b/Task/Menu/AArch64-Assembly/menu.aarch64 new file mode 100644 index 0000000000..790529acbc --- /dev/null +++ b/Task/Menu/AArch64-Assembly/menu.aarch64 @@ -0,0 +1,258 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program menu164.s */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +.equ BUFFERSIZE, 2000 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developer debugging + + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "\nError Buffer too small!!!\n" + +szChoose: .asciz "\nMake your choise: " +szMessErrorNum: .asciz "Error : number do not exists!!\n" +szMesschoose: .asciz "\nYou have chosen: " +szLigne1: .asciz "fee fie" +szLigne2: .asciz "huff and puff" +szLigne3: .asciz "mirror mirror" +szLigne4: .asciz "tick tock" + +tabMenu: .quad szLigne1 + .quad szLigne2 + .quad szLigne3 + .quad szLigne4 +.equ NBLIGNES, (. - tabMenu ) / 8 +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +.align 4 +sBuffer: .skip BUFFERSIZE +sBuffex1: .skip BUFFERSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess +1: + ldr x0,qAdrtabMenu // display menu + ldr x1,qAdrsBuffer + bl displayMenu + mov x5,x0 + ldr x0,qAdrszChoose // display string + bl affichageMess + bl keyboardInput + sub x0,x0,#'0' // input control + cmp x0,#0 + ble error + cmp x0,x5 + bge error + sub x4,x0,#1 // compute index choose string + ldr x0,qAdrszMesschoose + bl affichageMess + ldr x1,qAdrtabMenu // menu + ldr x0,[x1,x4,lsl #3] // load line address + bl affichageMess // and display + ldr x0,qAdrszCarriageReturn + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + b 1b // loop +error: + ldr x0,qAdrszMessErrorNum + bl affichageMess + b 1b + + + + ldr x0,qAdrszMessFinOK + bl affichageMess + b 100f +99: + ldr x0,qAdrszMessError // error + bl affichageMess + mov x0, #1 +100: // standard end of the program + mov x0, #0 // return code + mov x8,EXIT + svc 0 // perform system call +qAdrsBuffer: .quad sBuffer +qAdrszChoose: .quad szChoose +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessError: .quad szMessError +qAdrszMessErrorNum: .quad szMessErrorNum +qAdrszMesschoose: .quad szMesschoose +/******************************************************************/ +/* display menu */ +/******************************************************************/ +/* r0 contains menu address */ +/* r1 contains buffer address */ +/* r0 return index max */ +displayMenu: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + mov x8,x0 + mov x9,x1 + bl searchMaxSize // compute max size line + mov x7,x0 // maxi size + mov x5,#0 +1: + ldr x6,[x8,x5,lsl #3] // load line address + mov x2,#0 +2: + mov x0,x6 + mov x1,x9 + bl copyString // copy menu line to buffer + sub x1,x7,x0 // compute maxi len - string length + mov x3,#0 + mov x2,#' ' +3: // loop to add space in buffer + cmp x3,x1 + bge 4f + strb w2,[x9,x0] + add x0,x0,#1 + add x3,x3,#1 + b 3b +4: + strb w2,[x9,x0] // add one space + add x0,x0,#1 + mov x2,#':' + strb w2,[x9,x0] // add : to buffer + add x0,x0,#1 + mov x2,#' ' + strb w2,[x9,x0] // add one space + add x0,x0,#1 + mov x4,x0 + add x0,x5,#1 // index + add x1,x9,x4 + bl conversion10 // decimal conversion + mov x2,' ' + add x1,x0,x4 + strb w2,[x9,x1] // replace zero by space + add x1,x1,#1 + mov x2,#0x0a + strb w2,[x9,x1] // add : to buffer + add x1,x1,#1 + mov x2,#0 + strb w2,[x9,x1] // add 0 final to buffer + + mov x0,x9 // buffer display + bl affichageMess + + add x5,x5,#1 // increment indice + cmp x5,#NBLIGNES // maxi ? + blt 1b + add x0,x5,#1 // index max + +100: + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // restaur registers + ret + +/******************************************************************/ +/* search max size of menu lines */ +/******************************************************************/ +/* r0 contains menu address */ +/* r0 return max lenght */ +searchMaxSize: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + mov x1,#0 + mov x5,#0 // max size +1: + ldr x2,[x0,x1,lsl #3] // load line address + mov x3,#0 // char indice +2: + ldrb w4,[x2,x3] // load char + cmp x4,#0 // end string ? + beq 3f + add x3,x3,#1 + b 2b // loop +3: + + cmp x3,x5 // compare length and size maxi + csel x5,x3,x5,gt + add x1,x1,#1 + cmp x1,#NBLIGNES + blt 1b + mov x0,x5 // return maxi size + +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // restaur registers + ret +qAdrtabMenu: .quad tabMenu +/******************************************************************/ +/* copy strings */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains address buffer +/* r0 return max lenght */ +copyString: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! + mov x2,#0 +1: + ldrb w3,[x0,x2] // load byte + cmp x3,#0 // final zero + beq 2f + strb w3,[x1,x2] // store byte in buffer + add x2,x2,#1 + b 1b +2: + mov x0,x2 // return buffer position +100: + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // restaur registers + ret +/******************************************************************/ +/* string entry */ +/******************************************************************/ +/* r0 return the first character of human entry */ +keyboardInput: + stp x1,lr,[sp,-16]! // save registers + stp x2,x8,[sp,-16]! + mov x0,#STDIN // Linux input console + ldr x1,qAdrsBuffex1 // buffer address + mov x2,#BUFFERSIZE // buffer size + mov x8,#READ // request to read datas + svc 0 // call system + ldr x1,qAdrsBuffex1 // buffer address + ldrb w0,[x1] // load first character +100: + ldp x2,x8,[sp],16 + ldp x1,lr,[sp],16 // restaur registers + ret +qAdrsBuffex1: .quad sBuffex1 +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Menu/ARM-Assembly/menu.arm b/Task/Menu/ARM-Assembly/menu.arm new file mode 100644 index 0000000000..c7571f5766 --- /dev/null +++ b/Task/Menu/ARM-Assembly/menu.arm @@ -0,0 +1,240 @@ +/* ARM assembly Raspberry PI */ +/* program menu1.s */ +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ STDIN, 1 +.equ READ, 3 + +.equ BUFFERSIZE, 2000 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "\nError Buffer too small!!!\n" + +szChoose: .asciz "\nMake your choise: " +szMessErrorNum: .asciz "Error : number do not exists!!\n" +szMesschoose: .asciz "\nYou have chosen: " +szLigne1: .asciz "fee fie" +szLigne2: .asciz "huff and puff" +szLigne3: .asciz "mirror mirror" +szLigne4: .asciz "tick tock" + +tabMenu: .int szLigne1 + .int szLigne2 + .int szLigne3 + .int szLigne4 +.equ NBLIGNES, (. - tabMenu ) / 4 +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +.align 4 +sBuffer: .skip BUFFERSIZE +sBuffer1: .skip BUFFERSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess +1: + ldr r0,iAdrtabMenu @ display menu + ldr r1,iAdrsBuffer + bl displayMenu + mov r5,r0 + ldr r0,iAdrszChoose @ display string + bl affichageMess + bl keyboardInput + //affregtit saisie + sub r0,#'0' @ input control + cmp r0,#0 + ble error + cmp r0,r5 + bge error + sub r4,r0,#1 @ compute index choose string + ldr r0,iAdrszMesschoose + bl affichageMess + ldr r1,iAdrtabMenu @ menu + ldr r0,[r1,r4,lsl #2] @ load line address + bl affichageMess @ and display + ldr r0,iAdrszCarriageReturn + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + b 1b @ loop +error: + ldr r0,iAdrszMessErrorNum + bl affichageMess + b 1b + + + + ldr r0,iAdrszMessFinOK + bl affichageMess + b 100f +99: + ldr r0,iAdrszMessError @ error + bl affichageMess + mov r0, #1 +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrsBuffer: .int sBuffer +iAdrszChoose: .int szChoose +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessError: .int szMessError +iAdrszMessErrorNum: .int szMessErrorNum +iAdrszMesschoose: .int szMesschoose +/******************************************************************/ +/* display menu */ +/******************************************************************/ +/* r0 contains menu address */ +/* r1 contains buffer address */ +/* r0 return index max */ +displayMenu: + push {r1-r9,lr} @ save registers + mov r8,r0 + mov r9,r1 + bl searchMaxSize @ compute max size line + mov r7,r0 @ maxi size + mov r5,#0 +1: + ldr r6,[r8,r5,lsl #2] @ load line address + mov r2,#0 +2: + mov r0,r6 + mov r1,r9 + bl copyString @ copy menu line to buffer + sub r1,r7,r0 @ compute maxi len - string length + mov r3,#0 + mov r2,#' ' +3: @ loop to add space in buffer + cmp r3,r1 + bge 4f + strb r2,[r9,r0] + add r0,r0,#1 + add r3,r3,#1 + b 3b +4: + strb r2,[r9,r0] @ add one space + add r0,r0,#1 + mov r2,#':' + strb r2,[r9,r0] @ add : to buffer + add r0,r0,#1 + mov r2,#' ' + strb r2,[r9,r0] @ add one space + add r0,r0,#1 + mov r4,r0 + add r0,r5,#1 @ index + add r1,r9,r4 + bl conversion10 @ decimal conversion + add r1,r0,r4 + add r1,r1,#1 + mov r2,#0x0a + strb r2,[r9,r1] @ add : to buffer + add r1,r1,#1 + mov r2,#0 + strb r2,[r9,r1] @ add 0 final to buffer + + mov r0,r9 @ buffer display + bl affichageMess + + add r5,r5,#1 @ increment indice + cmp r5,#NBLIGNES @ maxi ? + blt 1b + add r0,r5,#1 @ index max + +100: + pop {r1-r9,pc} @ restaur registers + +/******************************************************************/ +/* search max size of menu lines */ +/******************************************************************/ +/* r0 contains menu address */ +/* r0 return max lenght */ +searchMaxSize: + push {r1-r5,lr} @ save registers + mov r1,#0 + mov r5,#0 @ max size +1: + ldr r2,[r0,r1,lsl #2] @ load line address + mov r3,#0 @ char indice +2: + ldrb r4,[r2,r3] @ load char + cmp r4,#0 @ end string ? + beq 3f + add r3,r3,#1 + b 2b @ loop +3: + cmp r3,r5 @ compare length and size maxi + movgt r5,r3 + add r1,r1,#1 + cmp r1,#NBLIGNES + blt 1b + mov r0,r5 @ return maxi size + +100: + pop {r1-r5,pc} @ restaur registers +iAdrtabMenu: .int tabMenu +/******************************************************************/ +/* copy strings */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains address buffer +/* r0 return max lenght */ +copyString: + push {r1-r3,lr} @ save registers + mov r2,#0 +1: + ldrb r3,[r0,r2] @ load byte + cmp r3,#0 @ final zero + beq 2f + strb r3,[r1,r2] @ store byte in buffer + add r2,r2,#1 + b 1b +2: + mov r0,r2 @ return buffer position +100: + pop {r1-r3,pc} @ restaur registers +/******************************************************************/ +/* string entry */ +/******************************************************************/ +/* r0 return the first character of human entry */ +keyboardInput: + push {r1-r7,lr} @ save registers + mov r0,#STDIN @ Linux input console + ldr r1,iAdrsBuffer1 @ buffer address + mov r2,#BUFFERSIZE @ buffer size + mov r7,#READ @ request to read datas + svc 0 @ call system + ldr r1,iAdrsBuffer1 @ buffer address + ldrb r0,[r1] @ load first character +100: + pop {r1-r7,pc} +iAdrsBuffer1: .int sBuffer1 +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Menu/Delphi/menu.delphi b/Task/Menu/Delphi/menu.pas similarity index 100% rename from Task/Menu/Delphi/menu.delphi rename to Task/Menu/Delphi/menu.pas diff --git a/Task/Menu/Elixir/menu.elixir b/Task/Menu/Elixir/menu.ex similarity index 100% rename from Task/Menu/Elixir/menu.elixir rename to Task/Menu/Elixir/menu.ex diff --git a/Task/Menu/Euphoria/menu.euphoria b/Task/Menu/Euphoria/menu.ex similarity index 100% rename from Task/Menu/Euphoria/menu.euphoria rename to Task/Menu/Euphoria/menu.ex diff --git a/Task/Menu/Julia/menu.julia b/Task/Menu/Julia/menu.jl similarity index 100% rename from Task/Menu/Julia/menu.julia rename to Task/Menu/Julia/menu.jl diff --git a/Task/Menu/Kotlin/menu.kotlin b/Task/Menu/Kotlin/menu.kts similarity index 100% rename from Task/Menu/Kotlin/menu.kotlin rename to Task/Menu/Kotlin/menu.kts diff --git a/Task/Menu/MUMPS/menu.mumps b/Task/Menu/MUMPS/menu.mumps deleted file mode 100644 index d11a659a58..0000000000 --- a/Task/Menu/MUMPS/menu.mumps +++ /dev/null @@ -1,15 +0,0 @@ -MENU(STRINGS,SEP) - ;http://rosettacode.org/wiki/Menu - NEW I,A,MAX - ;I is a loop variable - ;A is the string read in from the user - ;MAX is the number of substrings in the STRINGS list - ;SET STRINGS="fee fie^huff and puff^mirror mirror^tick tock" - SET MAX=$LENGTH(STRINGS,SEP) - QUIT:MAX=0 "" -WRITEMENU - FOR I=1:1:MAX WRITE I,": ",$PIECE(STRINGS,SEP,I),! - READ:30 !,"Choose a string by its index: ",A,! - IF (A<1)!(A>MAX)!(A\1'=A) GOTO WRITEMENU - KILL I,MAX - QUIT $PIECE(STRINGS,SEP,A) diff --git a/Task/Menu/Modula-2/menu.mod2 b/Task/Menu/Modula-2/menu.mod2 index d06c868b4a..f8d92d8f83 100644 --- a/Task/Menu/Modula-2/menu.mod2 +++ b/Task/Menu/Modula-2/menu.mod2 @@ -1,38 +1,60 @@ MODULE Menu; FROM InOut IMPORT WriteString, WriteCard, WriteLn, ReadCard; +FROM STextIO IMPORT ReadChar, SkipLine; +FROM CharClass IMPORT IsNumeric, IsControl, IsWhiteSpace; CONST StringLength = 100; MenuSize = 4; TYPE String = ARRAY[0..StringLength-1] OF CHAR; -VAR menu : ARRAY[0..MenuSize] OF String; - selection, index : CARDINAL; +PROCEDURE MenuF(): String; +VAR + menu : ARRAY[0..MenuSize] OF String; + inp : CHAR; + selection, index : CARDINAL; BEGIN menu[1] := "fee fie"; menu[2] := "huff and puff"; menu[3] := "mirror mirror"; menu[4] := "tick tock"; + selection := 0; + WHILE selection=0 DO + FOR index := 1 TO HIGH(menu) DO + WriteString("["); + WriteCard( index,1); + WriteString( "] "); + WriteString( menu[index]); + WriteLn; + END;(*of FOR*) - FOR index := 1 TO HIGH(menu) DO - WriteString("["); - WriteCard( index,1); - WriteString( "] "); - WriteString( menu[index]); - WriteLn; - END;(*of FOR*) + inp := ''; + WriteString("Choose what you want : "); + ReadChar(inp); + SkipLine; - WriteString("Choose what you want : "); - ReadCard(selection); + IF IsNumeric(inp) THEN + CASE inp OF + '1' : selection := 1 | + '2' : selection := 2 | + '3' : selection := 3 | + '4' : selection := 4 | + ELSE ; + selection := 0; + END; - IF (selection <= HIGH(menu)) AND (selection > 0) THEN - WriteString("You have chosen: "); - WriteString( menu[selection]); - WriteLn; - ELSE - WriteString("Selection is out of range!"); - WriteLn; - END (*of IF*) + IF (selection <= HIGH(menu)) AND (selection > 0) THEN + RETURN menu[selection]; + END (*of IF*) + ELSIF IsWhiteSpace(inp) OR IsControl(inp) THEN + RETURN ""; + END; + END; +END MenuF; + +BEGIN + WriteString(MenuF()); + WriteLn; END Menu. diff --git a/Task/Menu/OCaml/menu-1.ocaml b/Task/Menu/OCaml/menu-1.ml similarity index 100% rename from Task/Menu/OCaml/menu-1.ocaml rename to Task/Menu/OCaml/menu-1.ml diff --git a/Task/Menu/OCaml/menu-2.ocaml b/Task/Menu/OCaml/menu-2.ml similarity index 100% rename from Task/Menu/OCaml/menu-2.ocaml rename to Task/Menu/OCaml/menu-2.ml diff --git a/Task/Menu/Rust/menu.rust b/Task/Menu/Rust/menu.rs similarity index 100% rename from Task/Menu/Rust/menu.rust rename to Task/Menu/Rust/menu.rs diff --git a/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy b/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy new file mode 100644 index 0000000000..51a02cfa7a --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy @@ -0,0 +1,72 @@ +s$ = input +repeat + s$ = input + until s$ = "" + pat$[][] &= strsplit s$ "," + pat$[$][] &= "" +. +proc sort . d$[][] . + for i = len d$[][] - 1 downto 1 + for j = 1 to i + if strcmp d$[j][1] d$[j + 1][1] > 0 + swap d$[j][] d$[j + 1][] + . + . + . +. +sort pat$[][] +n = len pat$[][] +len sum[] n +len cnt[] n +# +s$ = input +repeat + s$ = input + until s$ = "" + vis$[] = strsplit s$ "," + for i to n + if pat$[i][1] = vis$[1] + if strcmp vis$[2] pat$[i][3] > 0 + pat$[i][3] = vis$[2] + . + sum[i] += number vis$[3] + cnt[i] += 1 + . + . +. +func$ f s$ n . + s$ = " " & s$ + while len s$ < n + s$ &= " " + . + return s$ +. +print "PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG" +for i to n + if sum[i] > 0 + sum$ = f sum[i] 11 + cnt$ = f sum[i] / cnt[i] 11 + else + sum$ = f "" 11 + cnt$ = f "" 11 + . + print f pat$[i][1] 11 & "|" & f pat$[i][2] 10 & "|" & f pat$[i][3] 12 & "|" & sum$ & "|" & cnt$ +. +# +input_data +PATIENT_ID,LASTNAME +1001,Hopper +4004,Wirth +3003,Kemeny +2002,Gosling +5005,Kurtz + +PATIENT_ID,VISIT_DATE,SCORE +2002,2020-09-10,6.8 +1001,2020-09-17,5.5 +4004,2020-09-24,8.4 +2002,2020-10-08, +1001,,6.6 +3003,2020-11-12, +4004,2020-11-05,7.0 +1001,2020-11-19,5.3 diff --git a/Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.julia b/Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.jl similarity index 100% rename from Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.julia rename to Task/Merge-and-aggregate-datasets/Julia/merge-and-aggregate-datasets.jl diff --git a/Task/Mertens-function/Delphi/mertens-function.delphi b/Task/Mertens-function/Delphi/mertens-function.pas similarity index 100% rename from Task/Mertens-function/Delphi/mertens-function.delphi rename to Task/Mertens-function/Delphi/mertens-function.pas diff --git a/Task/Mertens-function/Julia/mertens-function.julia b/Task/Mertens-function/Julia/mertens-function.jl similarity index 100% rename from Task/Mertens-function/Julia/mertens-function.julia rename to Task/Mertens-function/Julia/mertens-function.jl diff --git a/Task/Metallic-ratios/Julia/metallic-ratios.julia b/Task/Metallic-ratios/Julia/metallic-ratios.jl similarity index 100% rename from Task/Metallic-ratios/Julia/metallic-ratios.julia rename to Task/Metallic-ratios/Julia/metallic-ratios.jl diff --git a/Task/Metallic-ratios/Kotlin/metallic-ratios.kotlin b/Task/Metallic-ratios/Kotlin/metallic-ratios.kts similarity index 100% rename from Task/Metallic-ratios/Kotlin/metallic-ratios.kotlin rename to Task/Metallic-ratios/Kotlin/metallic-ratios.kts diff --git a/Task/Metaprogramming/ALGOL-68/metaprogramming.alg b/Task/Metaprogramming/ALGOL-68/metaprogramming.alg index a2dc39d932..6f444bb7c3 100644 --- a/Task/Metaprogramming/ALGOL-68/metaprogramming.alg +++ b/Task/Metaprogramming/ALGOL-68/metaprogramming.alg @@ -102,15 +102,10 @@ OP WITH = ( INSPECTTOREPLACE inspected, STRING replace with )REF STRING: OP DISPLAY = ( STRING s )VOID: write( ( s, newline ) ); - PRIO REPLACING = 2, WITH = 1; - - -main: ( - - # test the INSPECT and DISPLAY "verbs" # +BEGIN # test the INSPECT and DISPLAY "verbs" # STRING text := "some text"; DISPLAY text; @@ -125,7 +120,15 @@ main: ( DISPLAY text; INSPECT text REPLACING LEADING "som" WITH "k"; + DISPLAY text; + + text := "another test"; + DISPLAY text; + + INSPECT text REPLACING FIRST "anot" WITH "ABC"; + DISPLAY text; + + INSPECT text REPLACING LEADING "A" WITH "_"; DISPLAY text - -) +END diff --git a/Task/Metaprogramming/Julia/metaprogramming.julia b/Task/Metaprogramming/Julia/metaprogramming.jl similarity index 100% rename from Task/Metaprogramming/Julia/metaprogramming.julia rename to Task/Metaprogramming/Julia/metaprogramming.jl diff --git a/Task/Metaprogramming/Kotlin/metaprogramming.kotlin b/Task/Metaprogramming/Kotlin/metaprogramming.kts similarity index 100% rename from Task/Metaprogramming/Kotlin/metaprogramming.kotlin rename to Task/Metaprogramming/Kotlin/metaprogramming.kts diff --git a/Task/Metaprogramming/Rust/metaprogramming.rust b/Task/Metaprogramming/Rust/metaprogramming.rs similarity index 100% rename from Task/Metaprogramming/Rust/metaprogramming.rust rename to Task/Metaprogramming/Rust/metaprogramming.rs diff --git a/Task/Metered-concurrency/Euphoria/metered-concurrency.euphoria b/Task/Metered-concurrency/Euphoria/metered-concurrency.ex similarity index 100% rename from Task/Metered-concurrency/Euphoria/metered-concurrency.euphoria rename to Task/Metered-concurrency/Euphoria/metered-concurrency.ex diff --git a/Task/Metered-concurrency/Julia/metered-concurrency.julia b/Task/Metered-concurrency/Julia/metered-concurrency.jl similarity index 100% rename from Task/Metered-concurrency/Julia/metered-concurrency.julia rename to Task/Metered-concurrency/Julia/metered-concurrency.jl diff --git a/Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin b/Task/Metered-concurrency/Kotlin/metered-concurrency.kts similarity index 100% rename from Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin rename to Task/Metered-concurrency/Kotlin/metered-concurrency.kts diff --git a/Task/Metered-concurrency/Rust/metered-concurrency.rust b/Task/Metered-concurrency/Rust/metered-concurrency.rs similarity index 100% rename from Task/Metered-concurrency/Rust/metered-concurrency.rust rename to Task/Metered-concurrency/Rust/metered-concurrency.rs diff --git a/Task/Metronome/Delphi/metronome.delphi b/Task/Metronome/Delphi/metronome.pas similarity index 100% rename from Task/Metronome/Delphi/metronome.delphi rename to Task/Metronome/Delphi/metronome.pas diff --git a/Task/Metronome/Julia/metronome.julia b/Task/Metronome/Julia/metronome.jl similarity index 100% rename from Task/Metronome/Julia/metronome.julia rename to Task/Metronome/Julia/metronome.jl diff --git a/Task/Metronome/Kotlin/metronome.kotlin b/Task/Metronome/Kotlin/metronome.kts similarity index 100% rename from Task/Metronome/Kotlin/metronome.kotlin rename to Task/Metronome/Kotlin/metronome.kts diff --git a/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg b/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg index 3274d75fbf..37c3eb9683 100644 --- a/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg +++ b/Task/Mian-Chowla-sequence/ALGOL-68/mian-chowla-sequence.alg @@ -8,7 +8,8 @@ BEGIN [ max mc ]INT mc; INT curr size := 0; # initial size of the array # INT size increment = 10 000; # size to increase the array by # - REF[]BOOL is sum := HEAP[ 1 : 0 ]BOOL; + HEAP[ 1 : 0 ]BOOL empty sum; + REF[]BOOL is sum := empty sum; INT mc count := 1; FOR i WHILE mc count <= max mc DO # assume i will be part of the sequence # diff --git a/Task/Mian-Chowla-sequence/ALGOL-W/mian-chowla-sequence.alg b/Task/Mian-Chowla-sequence/ALGOL-W/mian-chowla-sequence.alg new file mode 100644 index 0000000000..ff9e1077d4 --- /dev/null +++ b/Task/Mian-Chowla-sequence/ALGOL-W/mian-chowla-sequence.alg @@ -0,0 +1,55 @@ +% Find Mian-Chowla numbers: an + where: ai = 1, + and: an = smallest integer such that ai + aj is unique + for all i, j in 1 .. n && i <= j +% +begin + record HashedSum ( integer hSum; reference(HashedSum) hNext ); + integer HASH_MOD, MAX_MC; + HASH_MOD := 10000; + MAX_MC := 100; + begin + % hash table of sums of the sequence elements encountered so far % + reference(HashedSum) array sums ( 0 :: HASH_MOD - 1 ); + % table of the sequence elements encountered so far % + integer array mc ( 1 :: MAX_MC ); + integer mcCount, i; + for i := 0 until HASH_MOD - 1 do sums( i ) := null; + mcCount := 1; + i := 0; + while begin i := i + 1; mcCount <= MAX_MC end do begin + logical isUnique; + integer mcPos; + % assume i will be part of the sequence % + mc( mcCount ) := i; + % check the sums % + isUnique := true; + mcPos := 0; + while begin mcPos := mcPos + 1; mcPos <= mcCount and isUnique end do begin + integer s; + reference(HashedSum) hs; + % attempt to find the sum in the hash table % + s := i + mc( mcPos ); + hs := sums( s rem HASH_MOD ); + while hs not = null and s not = hSum(hs) do hs := hNext(hs); + isUnique := hs = null + end while_isUnique; + if isUnique then begin + % i is a sequence element - store its sums % + for mcPos := 1 until mcCount do begin + integer newSum, sumHash; + newSum := i + mc( mcPos ); + sumHash := newSum rem HASH_MOD; + sums( sumHash ) := HashedSum( newSum, sums( sumHash ) ) + end for_mcPos ; + mcCount := mcCount + 1 + end if_isUnique + end while_mcCount_le_MAX_MC; + + % print parts of the sequence % + write( "Mian Chowla sequence elements 1..30:" );write(); + for i := 1 until 30 do writeon( i_w := 1, s_w := 0, " ", mc( i ) ); + write( "Mian Chowla sequence elements 91..100:" );write(); + for i := 91 until 100 do writeon( i_w := 1, s_w := 0, " ", mc( i ) ) + end +end. diff --git a/Task/Mian-Chowla-sequence/EasyLang/mian-chowla-sequence.easy b/Task/Mian-Chowla-sequence/EasyLang/mian-chowla-sequence.easy new file mode 100644 index 0000000000..ee9400b53e --- /dev/null +++ b/Task/Mian-Chowla-sequence/EasyLang/mian-chowla-sequence.easy @@ -0,0 +1,37 @@ +func[] mian_chowla n . + len mc[] n + mc[1] = 1 + is[] = [ 0 1 ] + for i = 2 to n + j = mc[i - 1] + repeat + j += 1 + mc[i] = j + for k = 1 to i + sum = mc[k] + j + if sum > len is[] + len is[] sum + 10000 + . + if is[sum] = 1 + isnew[] = [ ] + break 1 + . + isnew[] &= sum + . + until len isnew[] > 0 + . + for v in isnew[] + is[v] = 1 + . + . + return mc[] +. +mc[] = mian_chowla 100 +for i to 30 + write mc[i] & " " +. +print "" +print "" +for i = 91 to 100 + write mc[i] & " " +. diff --git a/Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.julia b/Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.jl similarity index 100% rename from Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.julia rename to Task/Mian-Chowla-sequence/Julia/mian-chowla-sequence.jl diff --git a/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kotlin b/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kts similarity index 100% rename from Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kotlin rename to Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-1.kts diff --git a/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kotlin b/Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kts similarity index 100% rename from Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kotlin rename to Task/Mian-Chowla-sequence/Kotlin/mian-chowla-sequence-2.kts diff --git a/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg index 3ee7c8ffdc..44132b4051 100644 --- a/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg +++ b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg @@ -1,38 +1,36 @@ -# we define a UNION MODE so that our middle 3 digits PROC can # -# return either an integer on success or a error message if # -# the middle 3 digits couldn't be extracted # -MODE EINT = UNION( INT # success value #, STRING # error message # ); -# PROC to return the middle 3 digits of an integer. # -# if this is not possible, an error message is returned # -# instead # -PROC middle 3 digits = ( INT number ) EINT: BEGIN - # convert the absolute value of the number to a string with the # - # minumum possible number characters # - STRING digits = whole( ABS number, 0 ); - INT len = UPB digits; - IF len < 3 - THEN - # number has less than 3 digits # - # return an error message # - "number must have at least three digits" - ELIF ( len MOD 2 ) = 0 - THEN - # the number has an even number of digits # - # return an error message # - "number must have an odd number of digits" - ELSE - # the number is suitable for extraction of the middle 3 digits # - INT first digit pos = 1 + ( ( len - 3 ) OVER 2 ); - # the result is the integer value of the three digits # - ( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 ) - + ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 ) - + ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) ) - ) - FI -END; # middle 3 digits # + # we define a UNION MODE so that our middle 3 digits PROC can # + # return either an integer on success or a error message if # + # the middle 3 digits couldn't be extracted # + MODE EINT = UNION( INT # success value #, STRING # error message # ); + # PROC to return the middle 3 digits of an integer. # + # if this is not possible, an error message is returned # + # instead # + PROC middle 3 digits = ( INT number ) EINT: + BEGIN + # convert the absolute value of the number to a string with the # + # minumum possible number characters # + STRING digits = whole( ABS number, 0 ); + INT len = UPB digits; + IF len < 3 + THEN + # number has less than 3 digits return an error message # + "number must have at least three digits" + ELIF len MOD 2 = 0 + THEN + # the number has an even number of digits- return an error message # + "number must have an odd number of digits" + ELSE + # the number is suitable for extraction of the middle 3 digits # + INT first digit pos = 1 + ( ( len - 3 ) OVER 2 ); + # the result is the integer value of the three digits # + ( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 ) + + ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 ) + + ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) ) + ) + FI + END; # middle 3 digits # -main: ( # test the middle 3 digits PROC # []INT test values = ( 123, 12345, 1234567, 987654321 , 10001, -10001, -123, -100 @@ -60,4 +58,4 @@ main: ( ESAC; print( ( newline ) ) OD -) +END diff --git a/Task/Middle-three-digits/Elixir/middle-three-digits.elixir b/Task/Middle-three-digits/Elixir/middle-three-digits.ex similarity index 100% rename from Task/Middle-three-digits/Elixir/middle-three-digits.elixir rename to Task/Middle-three-digits/Elixir/middle-three-digits.ex diff --git a/Task/Middle-three-digits/Julia/middle-three-digits.julia b/Task/Middle-three-digits/Julia/middle-three-digits.jl similarity index 100% rename from Task/Middle-three-digits/Julia/middle-three-digits.julia rename to Task/Middle-three-digits/Julia/middle-three-digits.jl diff --git a/Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin b/Task/Middle-three-digits/Kotlin/middle-three-digits.kts similarity index 100% rename from Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin rename to Task/Middle-three-digits/Kotlin/middle-three-digits.kts diff --git a/Task/Middle-three-digits/OCaml/middle-three-digits.ocaml b/Task/Middle-three-digits/OCaml/middle-three-digits.ml similarity index 100% rename from Task/Middle-three-digits/OCaml/middle-three-digits.ocaml rename to Task/Middle-three-digits/OCaml/middle-three-digits.ml diff --git a/Task/Middle-three-digits/Rust/middle-three-digits.rust b/Task/Middle-three-digits/Rust/middle-three-digits.rs similarity index 100% rename from Task/Middle-three-digits/Rust/middle-three-digits.rust rename to Task/Middle-three-digits/Rust/middle-three-digits.rs diff --git a/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.crystal b/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.cr similarity index 100% rename from Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.crystal rename to Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.cr diff --git a/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.crystal b/Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.cr similarity index 100% rename from Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.crystal rename to Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.cr diff --git a/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.elixir b/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.ex similarity index 100% rename from Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.elixir rename to Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.ex diff --git a/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.elixir b/Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.ex similarity index 100% rename from Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.elixir rename to Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.ex diff --git a/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia b/Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.jl similarity index 100% rename from Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.julia rename to Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.jl diff --git a/Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kotlin b/Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kts similarity index 100% rename from Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kotlin rename to Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kts diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx index b7d044c45f..6d47c35bbb 100644 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx +++ b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx @@ -1,16 +1,17 @@ -parse version version -say version -glob. = '' +include Settings + +say version; say 'Miller-Rabin primality test'; say numeric digits 1000 say '25 numbers of the form 2^n-1, mostly Mersenne primes' say 'Up to about 25 digits deterministic, above probabilistic' say -mm = '2 3 5 7 11 13 17 19 23 31 61 89 97 107 113 127 131 521 607 1279 2203 2281 2293 3217 3221' +mm = '2 3 5 7 11 13 17 19 23 31 61 89 97 107 113 127 131 521 ', +|| '607 1279 2203 2281 2293 3217 3221' do nn = 1 to 25 a = Word(mm,nn); b = 2**a-1; l = Length(b) - call time('r'); p = Prime(b); e = time('e') - if l > 25 then - b = Left(b,12)'...'Right(b,13) + call Time('r'); p = IsPrime(b); e = Time('e') + if l > 20 then + b = Left(b,10)'...'Right(b,10) select when p = 0 then p = 'not' @@ -19,19 +20,14 @@ do nn = 1 to 25 otherwise p = 'probable' end - say '2^('a'-1)' '=' b '('l' digits) is' p 'prime' '('format(e,,3) 'seconds)' + say '2^'a'-1' '=' b '('l' digits) is' p 'prime' '('Format(e,,3) 'seconds)' end return -Prime: +IsPrime: /* Is a number prime? */ procedure expose glob. arg x -/* Validity */ -if \ Whole(x) then - return 'X' -if x < 2 then - return 'X' /* Low primes also used as deterministic witnesses */ w1 = ' 2 3 5 7 11 13 17 19 23 29 31 37 41 ' /* Fast values */ @@ -52,8 +48,8 @@ do s = -1 while d//2 = 0 d = d%2 end /* Thresholds deterministic witnesses */ -w2 = ' 2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 0 ', -|| ' 3825123056546413051 0 0 318665857834031151167461 3317044064679887385961981 ' +w2 = '2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 ', +|| '0 3825123056546413051 0 0 318665857834031151167461 3317044064679887385961981 ' w = Words(w2) /* Up to 13 deterministic trials */ if x < Word(w2,w) then do @@ -72,7 +68,7 @@ else do end /* Algorithm using generated witnesses */ do k = 1 to k - a = Word(w1,k); y = powermod(a,d,x) + a = Word(w1,k); y = Powermod(a,d,x) if y = 1 then iterate if y = e then @@ -89,79 +85,6 @@ do k = 1 to k end return 1 -Floor: -/* Floor */ -procedure expose glob. -arg x -/* Formula */ -if Whole(x) then - return x -else - return Trunc(x)-(x<0) - -Powermod: -/* Power modulus function x^y mod z */ -procedure expose glob. -arg x,y,z -/* Validity */ -if \ Whole(x) then - return 'X' -if \ Whole(x) then - return 'X' -if \ Whole(x) then - return 'X' -if x < 0 then - return 'X' -if y < 0 then - return 'X' -if z < 1 then - return 'X' -/* Special values */ -if z = 1 then - return 0 -/* Binary method */ -numeric digits Max(Length(Format(x,,,0)),Length(Format(y,,,0)),2*Length(Format(z,,,0))) -b = x//z; r = 1 -do while y > 0 - if y//2 then - r = r*x//z - x = x*x//z; y = y%2 -end -return r - -Rand: -/* Random number 12 digits precision */ -procedure expose glob. -arg x,y -/* Validity */ -if x <> '' then do - if \ Whole(x) then - return 'X' - if \ Whole(x) then - return 'X' - if x >= y then - return 'X' -end -/* Fixed precision */ -p = Digits(); numeric digits 30 -/* Get and save first seed from system Date and Time */ -if glob.rand = '' then do - a = Date('s'); b = Time('l') - glob.rand = Substr(b,10,3)||Substr(b,7,2)||Substr(b,4,2)||Substr(b,1,2)||Substr(a,7,2)||Substr(a,5,2)||Substr(a,3,2) -end -/* Calculate next random number method HP calculators */ -glob.rand = Right((glob.rand*2851130928467),15) -/* Uniform deviate [0,1) */ -z = '0.'Left(glob.rand,Length(glob.rand)-3) -numeric digits 12 -if x = '' then - return z/1 -else - return Floor(z*(y+1-x)+x) - -Whole: -/* Is a number integer? */ -procedure expose glob. -arg x -/* Formula */ -return Datatype(x,'w') +include Functions +include Numbers +include Abend diff --git a/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rust b/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rs similarity index 100% rename from Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rust rename to Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rs diff --git a/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rust b/Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rs similarity index 100% rename from Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rust rename to Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rs diff --git a/Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.ss b/Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.scm similarity index 100% rename from Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.ss rename to Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.scm diff --git a/Task/Miller-Rabin-primality-test/X86-64-Assembly/miller-rabin-primality-test.x86-64 b/Task/Miller-Rabin-primality-test/X86-64-Assembly/miller-rabin-primality-test.x86-64 new file mode 100644 index 0000000000..34b09a65ab --- /dev/null +++ b/Task/Miller-Rabin-primality-test/X86-64-Assembly/miller-rabin-primality-test.x86-64 @@ -0,0 +1,383 @@ +; test miller rabin +; assembly X86 window +; download and install visual studio 2022 free site mtcrosoft +; search and open X64 native tools command prompt +; compil and link program with this command : +; ml64 .asm /link /ENTRY:main /SUBSYSTEM:console kernel32.lib user32.lib Shell32.lib +; this program respects the 64-bit calling convention : +; registers arguments : rcx rdx r8 r9 and stack +; registers saved : rbx,rbp,rdi,rsi, r12-r15 +; ATTENTION les registres rax,rcx,rdx,r8-r11 peuvent être +; perdus lors d'un appel de fonction +;********************************* +; constantes +;********************************* +STD_OUTPUT_HANDLE equ -11 + +NBLIGNES equ 5 +BUFFERSIZE equ 200 +NBLOOP equ 5 ; loop number change this if necessary +;********************************* +; MACROS +;********************************* +afficherLib MACRO messa +local mess1,LGMESS1C +.data + mess1 db messa,10,0 + LGMESS1C equ $ - mess1 +.code + push rax + push rcx + push rdx + push r8 + push r9 + push r10 + push r11 + mov rcx, offset mess1 + mov rdx,LGMESS1C + call afficherConsole + pop r11 + pop r10 + pop r9 + pop r8 + pop rdx + pop rcx + pop rax +ENDM + +;********************************* +; user data +;********************************* +.data +sBuffer db BUFFERSIZE dup (' ') +szRetourLigne db 10,0 +sZoneConv db 24 dup (' ') + + +align 8 +qgraine dq 123456789 +qNbDep1 dq 0019660dh +qNbDep2 dq 3c6ef35fh +hConsole dq 0 + +;********************************* +; user code fonction principale +;********************************* +.code +extern WriteFile : proc, GetStdHandle : proc, ExitProcess : proc +extern GetLastError : proc + +main PROC public + afficherLib "Program start." + + ;mov rcx,5107 + ;mov rcx,199 + ;mov rcx, 1707 ; compose + ;mov rcx,-1 ; composé + mov rcx,2305843009213693951 ; prime + mov rdx,NBLOOP + call isPrimeMiller + afficherLib "Resultat =" + mov rcx,rax + mov rdx, offset sZoneConv + call conversion10 + mov rdx,rax ; result length + mov rcx, offset sZoneConv + call afficherConsole + mov rcx, offset szRetourLigne + mov rdx,1 + call afficherConsole + + +finProgramme: + afficherLib "Programm end." + sub rsp,28h ; stack alignement + mov rcx,0 ; return code + call ExitProcess +main ENDP + +;***************************************************/ +;* test miller rabin algorithme wikipedia */ +;* unsigned */ +;***************************************************/ +;* rcx contains number */ +;* rdx contains parameter loop number */ +;* rax return 1 if prime 0 if composite */ +isPrimeMiller: + push rbx + push rdi + push r12 + push r13 + push r14 + push r15 + cmp rcx,0 + je composite + cmp rcx,3 + jbe primeok +prime1: + bt rcx,0 + jc prime2 + afficherLib "pair" + mov rax,0 + jmp finprime +prime2: + afficherLib "impair" + mov rdi,rdx ; loop number maxi + mov r11,rcx ; number + mov r9,rcx + dec r9 ; D + mov r10,0 ; S +prime3: + shr r9,1 ; D/2 + inc r10 + bt r9,0 + jnc prime3 + mov rbx ,0 ; loop counter + mov r12,r11 ; number + sub r12,3 + mov r13,3 +prime4: + mov rcx,r13 + mov rdx,r9 ; exposant = d + mov r8,r11 ; modulo + call moduloPui64 + cmp rax,1 + je prime8 + mov r15,r11 + dec r15 ; N - 1 + cmp r15,rax + je prime8 + mov r15,r10 + dec r15 ; s - 1 +prime5: + mov rdx,0 + mul rax ; compute square + div r11 + cmp rdx,1 ; remainder = 1 ? + je composite + mov r14,r11 + dec r14 + cmp r14,rdx + je prime8 + dec r15 ; S - 1 + jge prime5 + jmp composite + + + +prime8: + add r13,2 + cmp r13,r11 ; pour les petits nombres + je primeok + inc rbx + cmp rbx,rdi ; loop maxi ? + jl prime4 +primeok: + mov rax,1 ; prime + jmp finprime +composite: + mov rax,0 +finprime: + pop r15 + pop r14 + pop r13 + pop r12 + pop rdi + pop rbx + ret + +;********************************************************/ +;* Calcul modulo de b puissance e modulo m */ +;* Exemple 4 puissance 13 modulo 497 = 445 */ +;********************************************************/ +;* rcx nombre */ +;* rdx exposant */ +;* r8 modulo */ +moduloPui64: + push r12 + push r11 + push r10 + push r9 + mov rax,0 + cmp rcx,0 + je finmod + cmp rdx,0 + je finmod + cmp r8,0 + je finmod + mov r10,r8 ; modulo + mov r8,rdx ;exposant + mov rax,rcx ; number + mov r9,1 ; result + mov rdx,0 + div r10 + mov rax,rdx ; remainder + mov r12,rdx +boucleexp: + mov r11,r8 + shr r11,1 + jnc expnonnul + mov rdx,0 + mul r9 ; ltiplie par resultat + div r10 + mov r9,rdx ; resultat = reste + +expnonnul: + mov rax,r12 + mul r12 + div r10 + mov r12,rdx + mov rax,rdx + shr r8,1 + cmp r8,0 + jne boucleexp + mov rax,r9 + +finmod: + pop r9 + pop r10 + pop r11 + pop r12 + ret +;************************************** +; console display +;************************************** +; rcx : string address +; rdx : length string +afficherConsole PROC public + push rbx + push r12 + sub rsp,28h ; 40 bytes on stack (shadow variables) + mov rbx,rcx ; string address + mov r12,rdx ; size string + + cmp QWORD ptr hConsole,0 ; console handle ? + jne @B3 + mov rcx,STD_OUTPUT_HANDLE + call GetStdHandle ; load console handle + mov hConsole, rax ; save in data +@B3: + mov rcx,hconsole ; handle + mov rdx,rbx ; string address + mov r8,r12 ; string length + mov r9,0 ; + + sub rsp,8 ; stack alignement (one push) + push 0 + sub rsp,20h ; stack for shadow variable + call WriteFile ; winapi function + add rsp,20h + add rsp,10h ; 1 push and alignement + add rsp,28h ; stack alignement + pop r12 + pop rbx + ret +afficherConsole ENDP +;*************************************************** +;conversion to unsigned base 10 +;with removal of unnecessary zeros +;and left shift +;**************************************************** +; rcx : value to convert +; rdx : conversion area address length > 22 +LONGUEUR equ 24 +conversion10: + push rbx + push rdi + mov rdi,rdx ; conversion area address + mov BYTE ptr [rdi+LONGUEUR],0 ; 0 final conversion area + mov rax,rcx ; value + mov rcx,LONGUEUR-1 + mov rbx ,10 +CA1: ; loop begin + mov rdx,0 ; division rax by 10 + div rbx + add rdx,'0' ; remainder conversion ascii + mov byte ptr [rdi+rcx],dl + dec rcx + cmp rax,0 ; end ? + jne CA1 + xor rax,rax + inc rcx +CA5: ; copy loop + mov dl,[rdi+rcx] ; load a result character + mov byte ptr [rdi+rax],dl ; and store at conversion area begin + inc rcx + inc rax + cmp rcx,LONGUEUR ; loop if not zero final + jle CA5 + pop rdi + pop rbx + ret +;************************************** +; generate random number +;************************************** +; rcx number limit +randomNumber: + mov rax,0 + cmp rcx,0 + je randfin + mov rax, qGraine ; load seed + mov r8,qNbDep1 + mov rdx,qNbDep2 + mul r8 + add rax,rdx + mov qGraine,rax ; store new seed + inc rcx + mov rdx,0 + div rcx + mov rax,rdx ; result = remainder +randfin: + ret +;*************************************************** +; string concatenation +;************************************************** +; rcx destination area address +; rdx destination area length +; r8 strings number +; r9 0 +; on stack address and length of each string +; in order of insertion +grouperChaines: + enter 0,0 + push rbx + push r12 + push r13 + cmp r8,0 + je fingrp + mov r12,rdx + mov r9,0 ; indice strings + mov r10,0 ; number of characters inserted +bouclezone: + mov r13,r8 + shl r13,1 + mov rbx,[rbp+8+(r13 * 8)] ; string address + mov rax,[rbp+(r13 * 8)] ; sring length + mov r11,0 +bouclecopie: ; loop string copy + mov dl,byte ptr[rbx+r11] + mov byte ptr[rcx+r10],dl + inc r11 + cmp r11,rax + jg finbouclecopie + inc r10 ;number of characters inserted + cmp r10,r12 ; max? + jge erreur + jmp bouclecopie +finbouclecopie: + dec r8 ; other string + jnz bouclezone + + mov rax,r10 ; return size final string + jmp fingrp +erreur: + afficherLib "reception area too small" + mov rax,0 +fingrp: + pop r13 + pop r12 + pop rbx + leave + ret + +end diff --git a/Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.crystal b/Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.cr similarity index 100% rename from Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.crystal rename to Task/Mind-boggling-card-trick/Crystal/mind-boggling-card-trick.cr diff --git a/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy b/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy index f044bb5cb2..9189088f07 100644 --- a/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy +++ b/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy @@ -1,6 +1,6 @@ proc shuffle . a[] . for i = len a[] downto 2 - r = randint i + r = random i swap a[r] a[i] . . @@ -38,7 +38,7 @@ for i to len black[] . shuffle rp[] shuffle bp[] -n = randint lower len red[] len black[] +n = random lower len red[] len black[] len rp[] n len bp[] n # diff --git a/Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.julia b/Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.jl similarity index 100% rename from Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.julia rename to Task/Mind-boggling-card-trick/Julia/mind-boggling-card-trick.jl diff --git a/Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kotlin b/Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kts similarity index 100% rename from Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kotlin rename to Task/Mind-boggling-card-trick/Kotlin/mind-boggling-card-trick.kts diff --git a/Task/Mind-boggling-card-trick/Rust/mind-boggling-card-trick.rust b/Task/Mind-boggling-card-trick/Rust/mind-boggling-card-trick.rs similarity index 100% rename from Task/Mind-boggling-card-trick/Rust/mind-boggling-card-trick.rust rename to Task/Mind-boggling-card-trick/Rust/mind-boggling-card-trick.rs diff --git a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy index 8d1fc663b8..96d2a19eb8 100644 --- a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy +++ b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy @@ -130,8 +130,8 @@ proc start . . . n = 8 while n > 0 - c = randint 8 - 1 - r = randint 7 - 1 + c = random 8 - 1 + r = random 7 - 1 ind = r * 8 + c + 1 if cell[ind] = 0 n -= 1 diff --git a/Task/Minesweeper-game/Julia/minesweeper-game-1.julia b/Task/Minesweeper-game/Julia/minesweeper-game-1.jl similarity index 100% rename from Task/Minesweeper-game/Julia/minesweeper-game-1.julia rename to Task/Minesweeper-game/Julia/minesweeper-game-1.jl diff --git a/Task/Minesweeper-game/Julia/minesweeper-game-2.julia b/Task/Minesweeper-game/Julia/minesweeper-game-2.jl similarity index 100% rename from Task/Minesweeper-game/Julia/minesweeper-game-2.julia rename to Task/Minesweeper-game/Julia/minesweeper-game-2.jl diff --git a/Task/Minesweeper-game/OCaml/minesweeper-game.ocaml b/Task/Minesweeper-game/OCaml/minesweeper-game.ml similarity index 100% rename from Task/Minesweeper-game/OCaml/minesweeper-game.ocaml rename to Task/Minesweeper-game/OCaml/minesweeper-game.ml diff --git a/Task/Minesweeper-game/Rust/minesweeper-game.rust b/Task/Minesweeper-game/Rust/minesweeper-game.rs similarity index 100% rename from Task/Minesweeper-game/Rust/minesweeper-game.rust rename to Task/Minesweeper-game/Rust/minesweeper-game.rs diff --git a/Task/Minimal-steps-down-to-1/Julia/minimal-steps-down-to-1.julia b/Task/Minimal-steps-down-to-1/Julia/minimal-steps-down-to-1.jl similarity index 100% rename from Task/Minimal-steps-down-to-1/Julia/minimal-steps-down-to-1.julia rename to Task/Minimal-steps-down-to-1/Julia/minimal-steps-down-to-1.jl diff --git a/Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kotlin b/Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kts similarity index 100% rename from Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kotlin rename to Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kts diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Delphi/minimum-multiple-of-m-where-digital-sum-equals-m.delphi b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Delphi/minimum-multiple-of-m-where-digital-sum-equals-m.pas similarity index 100% rename from Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Delphi/minimum-multiple-of-m-where-digital-sum-equals-m.delphi rename to Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Delphi/minimum-multiple-of-m-where-digital-sum-equals-m.pas diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Julia/minimum-multiple-of-m-where-digital-sum-equals-m.julia b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Julia/minimum-multiple-of-m-where-digital-sum-equals-m.jl similarity index 100% rename from Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Julia/minimum-multiple-of-m-where-digital-sum-equals-m.julia rename to Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Julia/minimum-multiple-of-m-where-digital-sum-equals-m.jl diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.julia b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.jl similarity index 100% rename from Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.julia rename to Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-1.jl diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.julia b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.jl similarity index 100% rename from Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.julia rename to Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Julia/minimum-positive-multiple-in-base-10-using-only-0-and-1-2.jl diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kotlin b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kts similarity index 100% rename from Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kotlin rename to Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Kotlin/minimum-positive-multiple-in-base-10-using-only-0-and-1.kts diff --git a/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.julia b/Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.jl similarity index 100% rename from Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.julia rename to Task/Minkowski-question-mark-function/Julia/minkowski-question-mark-function.jl diff --git a/Task/Modified-random-distribution/Julia/modified-random-distribution.julia b/Task/Modified-random-distribution/Julia/modified-random-distribution.jl similarity index 100% rename from Task/Modified-random-distribution/Julia/modified-random-distribution.julia rename to Task/Modified-random-distribution/Julia/modified-random-distribution.jl diff --git a/Task/Modified-random-distribution/Rust/modified-random-distribution.rust b/Task/Modified-random-distribution/Rust/modified-random-distribution.rs similarity index 100% rename from Task/Modified-random-distribution/Rust/modified-random-distribution.rust rename to Task/Modified-random-distribution/Rust/modified-random-distribution.rs diff --git a/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg b/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg index 5b4a08cd14..a945eaf881 100644 --- a/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg +++ b/Task/Modular-arithmetic/ALGOL-68/modular-arithmetic.alg @@ -19,4 +19,6 @@ PROC f = ( UNION( LONG LONG INT, MODULARINT ) x )LONG LONG INT: , ( MODULARINT mx ): v OF ( mx**100 + mx + 1 ) ESAC; -print( ( whole( f( MODULARINT( 10, 13 ) ), 0 ), newline ) ) +print( ( whole( f( MODULARINT( 10, 13 ) ), 0 ), newline ) ); +# additional test to avoid a warning that the * operator isn't used... # +print( ( whole( f( MODULARINT( 10, 13 ) * MODULARINT( 10, 13 ) ), 0 ), newline ) ) diff --git a/Task/Modular-arithmetic/Julia/modular-arithmetic.julia b/Task/Modular-arithmetic/Julia/modular-arithmetic.jl similarity index 100% rename from Task/Modular-arithmetic/Julia/modular-arithmetic.julia rename to Task/Modular-arithmetic/Julia/modular-arithmetic.jl diff --git a/Task/Modular-arithmetic/Kotlin/modular-arithmetic.kotlin b/Task/Modular-arithmetic/Kotlin/modular-arithmetic.kts similarity index 100% rename from Task/Modular-arithmetic/Kotlin/modular-arithmetic.kotlin rename to Task/Modular-arithmetic/Kotlin/modular-arithmetic.kts diff --git a/Task/Modular-arithmetic/Scheme/modular-arithmetic.ss b/Task/Modular-arithmetic/Scheme/modular-arithmetic.scm similarity index 100% rename from Task/Modular-arithmetic/Scheme/modular-arithmetic.ss rename to Task/Modular-arithmetic/Scheme/modular-arithmetic.scm diff --git a/Task/Modular-exponentiation/Crystal/modular-exponentiation.crystal b/Task/Modular-exponentiation/Crystal/modular-exponentiation.cr similarity index 100% rename from Task/Modular-exponentiation/Crystal/modular-exponentiation.crystal rename to Task/Modular-exponentiation/Crystal/modular-exponentiation.cr diff --git a/Task/Modular-exponentiation/Delphi/modular-exponentiation.delphi b/Task/Modular-exponentiation/Delphi/modular-exponentiation.pas similarity index 100% rename from Task/Modular-exponentiation/Delphi/modular-exponentiation.delphi rename to Task/Modular-exponentiation/Delphi/modular-exponentiation.pas diff --git a/Task/Modular-exponentiation/Julia/modular-exponentiation.julia b/Task/Modular-exponentiation/Julia/modular-exponentiation.jl similarity index 100% rename from Task/Modular-exponentiation/Julia/modular-exponentiation.julia rename to Task/Modular-exponentiation/Julia/modular-exponentiation.jl diff --git a/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin b/Task/Modular-exponentiation/Kotlin/modular-exponentiation.kts similarity index 100% rename from Task/Modular-exponentiation/Kotlin/modular-exponentiation.kotlin rename to Task/Modular-exponentiation/Kotlin/modular-exponentiation.kts diff --git a/Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml b/Task/Modular-exponentiation/OCaml/modular-exponentiation.ml similarity index 100% rename from Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml rename to Task/Modular-exponentiation/OCaml/modular-exponentiation.ml diff --git a/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation.pas b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation.pas new file mode 100644 index 0000000000..7fdf7bc4c8 --- /dev/null +++ b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation.pas @@ -0,0 +1,16 @@ +// Modular exponentiation. Nigel Galloway:August 22nd., 2024 +type I=System.Numerics.BigInteger; +var bi:string->I:=n->I.Parse(n); +function expMod(a:I;b:I;n:I):I; + function fN(a:I;b:I;c:I):I; + begin + result:=if b=0 then c else fN(a*(a mod n),b/bi('2'),(if (b mod 2)=0 then c else c*a mod n)); + end; +begin + result:=fN(a,b,I.One) +end; +begin + var a := bi('2988348162058574136915891421498819466320163312926952423791023078876139'); + var b := bi('2351399303373464486466122544523690094744975233415544072992656881240319'); + println(expMod(a,b,bi('10')**40).ToString()); +end. diff --git a/Task/Modular-exponentiation/Rust/modular-exponentiation-1.rust b/Task/Modular-exponentiation/Rust/modular-exponentiation-1.rs similarity index 100% rename from Task/Modular-exponentiation/Rust/modular-exponentiation-1.rust rename to Task/Modular-exponentiation/Rust/modular-exponentiation-1.rs diff --git a/Task/Modular-exponentiation/Rust/modular-exponentiation-2.rust b/Task/Modular-exponentiation/Rust/modular-exponentiation-2.rs similarity index 100% rename from Task/Modular-exponentiation/Rust/modular-exponentiation-2.rust rename to Task/Modular-exponentiation/Rust/modular-exponentiation-2.rs diff --git a/Task/Modular-exponentiation/Scheme/modular-exponentiation.ss b/Task/Modular-exponentiation/Scheme/modular-exponentiation.scm similarity index 100% rename from Task/Modular-exponentiation/Scheme/modular-exponentiation.ss rename to Task/Modular-exponentiation/Scheme/modular-exponentiation.scm diff --git a/Task/Modular-inverse/Applesoft-BASIC/modular-inverse.basic b/Task/Modular-inverse/Applesoft-BASIC/modular-inverse.basic new file mode 100644 index 0000000000..3c788f75cc --- /dev/null +++ b/Task/Modular-inverse/Applesoft-BASIC/modular-inverse.basic @@ -0,0 +1,18 @@ + 10 LET E = 42 + 20 LET T = 2017 + 30 GOSUB 500" MODULAR INVERSE + 40 PRINT M; + 50 END + + REM MODULAR INVERSE + 500 LET M = 0 + 510 IF E > = T THEN RETURN + 520 LET C = 1 + 530 FOR B = E TO 1 STEP 0 + 540 LET S = INT ((T - B) / E) + 1 + 550 LET B = B + S * E + 560 LET C = C + S + 570 LET B = B - T + 580 NEXT B + 590 LET M = C + 610 RETURN diff --git a/Task/Modular-inverse/Crystal/modular-inverse.crystal b/Task/Modular-inverse/Crystal/modular-inverse.cr similarity index 100% rename from Task/Modular-inverse/Crystal/modular-inverse.crystal rename to Task/Modular-inverse/Crystal/modular-inverse.cr diff --git a/Task/Modular-inverse/Elixir/modular-inverse.elixir b/Task/Modular-inverse/Elixir/modular-inverse.ex similarity index 100% rename from Task/Modular-inverse/Elixir/modular-inverse.elixir rename to Task/Modular-inverse/Elixir/modular-inverse.ex diff --git a/Task/Modular-inverse/Julia/modular-inverse-1.julia b/Task/Modular-inverse/Julia/modular-inverse-1.jl similarity index 100% rename from Task/Modular-inverse/Julia/modular-inverse-1.julia rename to Task/Modular-inverse/Julia/modular-inverse-1.jl diff --git a/Task/Modular-inverse/Julia/modular-inverse-2.julia b/Task/Modular-inverse/Julia/modular-inverse-2.jl similarity index 100% rename from Task/Modular-inverse/Julia/modular-inverse-2.julia rename to Task/Modular-inverse/Julia/modular-inverse-2.jl diff --git a/Task/Modular-inverse/Kotlin/modular-inverse.kotlin b/Task/Modular-inverse/Kotlin/modular-inverse.kts similarity index 100% rename from Task/Modular-inverse/Kotlin/modular-inverse.kotlin rename to Task/Modular-inverse/Kotlin/modular-inverse.kts diff --git a/Task/Modular-inverse/OCaml/modular-inverse-1.ocaml b/Task/Modular-inverse/OCaml/modular-inverse-1.ml similarity index 100% rename from Task/Modular-inverse/OCaml/modular-inverse-1.ocaml rename to Task/Modular-inverse/OCaml/modular-inverse-1.ml diff --git a/Task/Modular-inverse/OCaml/modular-inverse-2.ocaml b/Task/Modular-inverse/OCaml/modular-inverse-2.ml similarity index 100% rename from Task/Modular-inverse/OCaml/modular-inverse-2.ocaml rename to Task/Modular-inverse/OCaml/modular-inverse-2.ml diff --git a/Task/Modular-inverse/Raku/modular-inverse.raku b/Task/Modular-inverse/Raku/modular-inverse.raku index f544988fbf..fc593866e3 100644 --- a/Task/Modular-inverse/Raku/modular-inverse.raku +++ b/Task/Modular-inverse/Raku/modular-inverse.raku @@ -9,3 +9,7 @@ sub inverse($n, :$modulo) { } say inverse 42, :modulo(2017) + +# or use a built-in routine - https://docs.raku.org/routine/expmod , kudos to trizen++ + +say expmod(42, -1, 2017); diff --git a/Task/Modular-inverse/Rust/modular-inverse-1.rust b/Task/Modular-inverse/Rust/modular-inverse-1.rs similarity index 100% rename from Task/Modular-inverse/Rust/modular-inverse-1.rust rename to Task/Modular-inverse/Rust/modular-inverse-1.rs diff --git a/Task/Modular-inverse/Rust/modular-inverse-2.rust b/Task/Modular-inverse/Rust/modular-inverse-2.rs similarity index 100% rename from Task/Modular-inverse/Rust/modular-inverse-2.rust rename to Task/Modular-inverse/Rust/modular-inverse-2.rs diff --git a/Task/Modular-inverse/Yabasic/modular-inverse.basic b/Task/Modular-inverse/Yabasic/modular-inverse.basic new file mode 100644 index 0000000000..5751ef5b2c --- /dev/null +++ b/Task/Modular-inverse/Yabasic/modular-inverse.basic @@ -0,0 +1,19 @@ +print multInv(42, 2017) +end + +sub multInv(a,b) + x0 = 0 + b0 = b + multInv = 1 + if b = 1 return + while a > 1 + q = a / b + t = b + b = mod (a, b) + a = t + t = x0 + x0 = multInv - q * x0 + multInv = int(t) + wend + if multInv < 0 return multInv + b0 +end sub diff --git a/Task/Monads-List-monad/Delphi/monads-list-monad.delphi b/Task/Monads-List-monad/Delphi/monads-list-monad.pas similarity index 100% rename from Task/Monads-List-monad/Delphi/monads-list-monad.delphi rename to Task/Monads-List-monad/Delphi/monads-list-monad.pas diff --git a/Task/Monads-List-monad/Julia/monads-list-monad.julia b/Task/Monads-List-monad/Julia/monads-list-monad.jl similarity index 100% rename from Task/Monads-List-monad/Julia/monads-list-monad.julia rename to Task/Monads-List-monad/Julia/monads-list-monad.jl diff --git a/Task/Monads-List-monad/Kotlin/monads-list-monad.kotlin b/Task/Monads-List-monad/Kotlin/monads-list-monad.kts similarity index 100% rename from Task/Monads-List-monad/Kotlin/monads-list-monad.kotlin rename to Task/Monads-List-monad/Kotlin/monads-list-monad.kts diff --git a/Task/Monads-List-monad/OCaml/monads-list-monad-1.ocaml b/Task/Monads-List-monad/OCaml/monads-list-monad-1.ml similarity index 100% rename from Task/Monads-List-monad/OCaml/monads-list-monad-1.ocaml rename to Task/Monads-List-monad/OCaml/monads-list-monad-1.ml diff --git a/Task/Monads-List-monad/OCaml/monads-list-monad-2.ocaml b/Task/Monads-List-monad/OCaml/monads-list-monad-2.ml similarity index 100% rename from Task/Monads-List-monad/OCaml/monads-list-monad-2.ocaml rename to Task/Monads-List-monad/OCaml/monads-list-monad-2.ml diff --git a/Task/Monads-List-monad/OCaml/monads-list-monad-3.ocaml b/Task/Monads-List-monad/OCaml/monads-list-monad-3.ml similarity index 100% rename from Task/Monads-List-monad/OCaml/monads-list-monad-3.ocaml rename to Task/Monads-List-monad/OCaml/monads-list-monad-3.ml diff --git a/Task/Monads-List-monad/OCaml/monads-list-monad-4.ocaml b/Task/Monads-List-monad/OCaml/monads-list-monad-4.ml similarity index 100% rename from Task/Monads-List-monad/OCaml/monads-list-monad-4.ocaml rename to Task/Monads-List-monad/OCaml/monads-list-monad-4.ml diff --git a/Task/Monads-Maybe-monad/ALGOL-68/monads-maybe-monad.alg b/Task/Monads-Maybe-monad/ALGOL-68/monads-maybe-monad.alg index 705e49867d..7fd4b9ea6a 100644 --- a/Task/Monads-Maybe-monad/ALGOL-68/monads-maybe-monad.alg +++ b/Task/Monads-Maybe-monad/ALGOL-68/monads-maybe-monad.alg @@ -79,9 +79,9 @@ COMMENT # Using the bind function, we can nest applications of safe functions, # # without the compiler choking on unexpectedly wrapped values returned from # - # other functions of the same kind. # - REAL root one over four = value OF ( MAYBE( TRUE, 4 ) BIND safe reciprocal BIND safe root ); - + # other functions of the same kind. E.g.: # +# REAL root one over four # +# = value OF ( MAYBE( TRUE, 4 ) BIND safe reciprocal BIND safe root ); # # print( ( root one over four, newline ) ); # # -> 0.5 # diff --git a/Task/Monads-Maybe-monad/Delphi/monads-maybe-monad.delphi b/Task/Monads-Maybe-monad/Delphi/monads-maybe-monad.pas similarity index 100% rename from Task/Monads-Maybe-monad/Delphi/monads-maybe-monad.delphi rename to Task/Monads-Maybe-monad/Delphi/monads-maybe-monad.pas diff --git a/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j b/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j new file mode 100644 index 0000000000..6c5b86d50c --- /dev/null +++ b/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j @@ -0,0 +1,3 @@ +'J N'=. s:'Just';'Nothing' +unit =. J,&<] +bind =. {{u@(1{::])^:(N-.@-:])}} diff --git a/Task/Monads-Maybe-monad/J/monads-maybe-monad-2.j b/Task/Monads-Maybe-monad/J/monads-maybe-monad-2.j new file mode 100644 index 0000000000..ba5d7e66a2 --- /dev/null +++ b/Task/Monads-Maybe-monad/J/monads-maybe-monad-2.j @@ -0,0 +1,3 @@ +fail =. {{unit@:u`(N"_)@.v}} NB. if v —> return Nothing, else apply u +show =. [: ": (,' '&,)&":&>/ +comp =. [: > {{y}}/@(,<@unit) NB. multi-compose diff --git a/Task/Monads-Maybe-monad/J/monads-maybe-monad-3.j b/Task/Monads-Maybe-monad/J/monads-maybe-monad-3.j new file mode 100644 index 0000000000..597e8583ba --- /dev/null +++ b/Task/Monads-Maybe-monad/J/monads-maybe-monad-3.j @@ -0,0 +1,14 @@ + ^.%:_2 NB. ln ∘ sqrt; gives complex numbers for inputs < 0 +0.346574j1.5708 + sqrt=. %: fail ([: +./ <&0) NB. return Nothing where result would've been complex + ln =. ^. fail ([: +./ <:&0) NB. same + show ln bind sqrt bind unit 2 3 4 +`Just 0.346574 0.549306 0.693147 + show ln bind sqrt bind unit 2 _3 4 NB. short-circuits on input < 0 +`Nothing + show@(ln bind)@(sqrt bind)@unit&> 2 _3 4 +`Just 0.346574 +`Nothing +`Just 0.693147 + show unit@:*:`ln`sqrt comp 2 3 4 +`Just 0.120113 0.301737 0.480453 diff --git a/Task/Monads-Maybe-monad/J/monads-maybe-monad.j b/Task/Monads-Maybe-monad/J/monads-maybe-monad.j deleted file mode 100644 index 32a0bcce98..0000000000 --- a/Task/Monads-Maybe-monad/J/monads-maybe-monad.j +++ /dev/null @@ -1,27 +0,0 @@ -NB. monad implementation: -unit=: < -bind=: (@>)( :: ]) - -NB. monad utility -safeVersion=: (<@) ( ::((<_.)"_)) -safeCompose=:dyad define - dyad def 'x`:6 bind y'/x,unit y -) - -NB. unsafe functions (fail with infinite arguments) -subtractFromSelf=: -~ -divideBySelf=: %~ - -NB. wrapped functions: -safeSubtractFromSelf=: subtractFromSelf safeVersion -safeDivideBySelf=: divideBySelf safeVersion - -NB. task example: - safeSubtractFromSelf bind safeDivideBySelf 1 -┌─┐ -│0│ -└─┘ - safeSubtractFromSelf bind safeDivideBySelf _ -┌──┐ -│_.│ -└──┘ diff --git a/Task/Monads-Maybe-monad/Julia/monads-maybe-monad.julia b/Task/Monads-Maybe-monad/Julia/monads-maybe-monad.jl similarity index 100% rename from Task/Monads-Maybe-monad/Julia/monads-maybe-monad.julia rename to Task/Monads-Maybe-monad/Julia/monads-maybe-monad.jl diff --git a/Task/Monads-Maybe-monad/K/monads-maybe-monad.k b/Task/Monads-Maybe-monad/K/monads-maybe-monad.k new file mode 100644 index 0000000000..7412f06167 --- /dev/null +++ b/Task/Monads-Maybe-monad/K/monads-maybe-monad.k @@ -0,0 +1,3 @@ +unit:(::) +bind:{[k;a]:[a~`N;a;k a]} +kcomp:{[f;g](bind[g;]@f@)} / (>=>) i.e. kleisli composition diff --git a/Task/Monads-Maybe-monad/Kotlin/monads-maybe-monad.kotlin b/Task/Monads-Maybe-monad/Kotlin/monads-maybe-monad.kts similarity index 100% rename from Task/Monads-Maybe-monad/Kotlin/monads-maybe-monad.kotlin rename to Task/Monads-Maybe-monad/Kotlin/monads-maybe-monad.kts diff --git a/Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-1.ocaml b/Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-1.ml similarity index 100% rename from Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-1.ocaml rename to Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-1.ml diff --git a/Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-2.ocaml b/Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-2.ml similarity index 100% rename from Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-2.ocaml rename to Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-2.ml diff --git a/Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-3.ocaml b/Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-3.ml similarity index 100% rename from Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-3.ocaml rename to Task/Monads-Maybe-monad/OCaml/monads-maybe-monad-3.ml diff --git a/Task/Monads-Maybe-monad/Rust/monads-maybe-monad.rust b/Task/Monads-Maybe-monad/Rust/monads-maybe-monad.rs similarity index 100% rename from Task/Monads-Maybe-monad/Rust/monads-maybe-monad.rust rename to Task/Monads-Maybe-monad/Rust/monads-maybe-monad.rs diff --git a/Task/Monads-Maybe-monad/V-(Vlang)/monads-maybe-monad.v b/Task/Monads-Maybe-monad/V-(Vlang)/monads-maybe-monad.v new file mode 100644 index 0000000000..2a8dbd087e --- /dev/null +++ b/Task/Monads-Maybe-monad/V-(Vlang)/monads-maybe-monad.v @@ -0,0 +1,17 @@ +type Maybe = f64 | string + +fn (m Maybe) div(x f64, y f64) Maybe { + mut result := m{} + result = x / y + if result.str().contains_any_substr(["inf","nan"]) {result = "none"} + return result +} + +fn main() { + mb := Maybe{} + for a in [15, 0, 5] { + for b in [5, 0, 0] { + println(mb.div(a, b)) + } + } +} diff --git a/Task/Monads-Writer-monad/Haskell/monads-writer-monad.hs b/Task/Monads-Writer-monad/Haskell/monads-writer-monad.hs index 3a90946a00..71b1cc0150 100644 --- a/Task/Monads-Writer-monad/Haskell/monads-writer-monad.hs +++ b/Task/Monads-Writer-monad/Haskell/monads-writer-monad.hs @@ -8,6 +8,4 @@ logRoot = loggingVersion sqrt "obtained square root, " logAddOne = loggingVersion (+1) "added 1, " logHalf = loggingVersion (/2) "divided by 2, " -halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf - -main = print $ runWriter (halfOfAddOneOfRoot 5) +main = print . runWriter $ (logRoot >=> logAddOne >=> logHalf) 5 diff --git a/Task/Monads-Writer-monad/J/monads-writer-monad-1.j b/Task/Monads-Writer-monad/J/monads-writer-monad-1.j index fdbc037761..8bde5af717 100644 --- a/Task/Monads-Writer-monad/J/monads-writer-monad-1.j +++ b/Task/Monads-Writer-monad/J/monads-writer-monad-1.j @@ -1,27 +1,4 @@ -root=: %: -incr=: >: -half=: -: - -tostr=: ,@": - -loggingVersion=: conjunction define - n;~u -) - -Lroot=: root loggingVersion 'obtained square root' -Lincr=: incr loggingVersion 'added 1' -Lhalf=: half loggingVersion 'divided by 2' - -loggingUnit=: verb define - y;'Initial value: ',tostr y -) - -loggingBind=: adverb define - r=. u 0{::y - v=. 0{:: r - v;(1{::y),LF,(1{::r),' -> ',tostr v -) - -loggingCompose=: dyad define - ;(dyad def ' Writer c b) +unit=: ;'Initial value: ',,@": +bind=: {{b;w,LF,W,' -> ',,":b['b W'=.u a['a w'=.y}} +comp=: [: > {{y}}/@(,<) NB. multi-compose diff --git a/Task/Monads-Writer-monad/J/monads-writer-monad-2.j b/Task/Monads-Writer-monad/J/monads-writer-monad-2.j index 365dede40a..e35142ea29 100644 --- a/Task/Monads-Writer-monad/J/monads-writer-monad-2.j +++ b/Task/Monads-Writer-monad/J/monads-writer-monad-2.j @@ -1,6 +1,9 @@ - 0{::Lhalf`Lincr`Lroot loggingCompose 5 + wRoot=: %: W 'obtained square root' + wIncr=: >: W 'added 1' + wHalf=: -: W 'divided by 2' + 0{::result=: wHalf`wIncr`wRoot comp unit 5 1.61803 - 1{::Lhalf`Lincr`Lroot loggingCompose 5 + 1{::result Initial value: 5 obtained square root -> 2.23607 added 1 -> 3.23607 diff --git a/Task/Monads-Writer-monad/Julia/monads-writer-monad.julia b/Task/Monads-Writer-monad/Julia/monads-writer-monad.jl similarity index 100% rename from Task/Monads-Writer-monad/Julia/monads-writer-monad.julia rename to Task/Monads-Writer-monad/Julia/monads-writer-monad.jl diff --git a/Task/Monads-Writer-monad/Kotlin/monads-writer-monad.kotlin b/Task/Monads-Writer-monad/Kotlin/monads-writer-monad.kts similarity index 100% rename from Task/Monads-Writer-monad/Kotlin/monads-writer-monad.kotlin rename to Task/Monads-Writer-monad/Kotlin/monads-writer-monad.kts diff --git a/Task/Monads-Writer-monad/Scheme/monads-writer-monad.ss b/Task/Monads-Writer-monad/Scheme/monads-writer-monad.scm similarity index 100% rename from Task/Monads-Writer-monad/Scheme/monads-writer-monad.ss rename to Task/Monads-Writer-monad/Scheme/monads-writer-monad.scm diff --git a/Task/Monte-Carlo-methods/Crystal/monte-carlo-methods.crystal b/Task/Monte-Carlo-methods/Crystal/monte-carlo-methods.cr similarity index 100% rename from Task/Monte-Carlo-methods/Crystal/monte-carlo-methods.crystal rename to Task/Monte-Carlo-methods/Crystal/monte-carlo-methods.cr diff --git a/Task/Monte-Carlo-methods/Delphi/monte-carlo-methods.delphi b/Task/Monte-Carlo-methods/Delphi/monte-carlo-methods.pas similarity index 100% rename from Task/Monte-Carlo-methods/Delphi/monte-carlo-methods.delphi rename to Task/Monte-Carlo-methods/Delphi/monte-carlo-methods.pas diff --git a/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy b/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy index 0fe197b75a..da447ba3db 100644 --- a/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy +++ b/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy @@ -6,7 +6,7 @@ func mc n . hit += 1 . . - return 4.0 * hit / n + return 4 * hit / n . numfmt 4 0 print mc 10000 diff --git a/Task/Monte-Carlo-methods/Elixir/monte-carlo-methods.elixir b/Task/Monte-Carlo-methods/Elixir/monte-carlo-methods.ex similarity index 100% rename from Task/Monte-Carlo-methods/Elixir/monte-carlo-methods.elixir rename to Task/Monte-Carlo-methods/Elixir/monte-carlo-methods.ex diff --git a/Task/Monte-Carlo-methods/Julia/monte-carlo-methods.julia b/Task/Monte-Carlo-methods/Julia/monte-carlo-methods.jl similarity index 100% rename from Task/Monte-Carlo-methods/Julia/monte-carlo-methods.julia rename to Task/Monte-Carlo-methods/Julia/monte-carlo-methods.jl diff --git a/Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kotlin b/Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kts similarity index 100% rename from Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kotlin rename to Task/Monte-Carlo-methods/Kotlin/monte-carlo-methods.kts diff --git a/Task/Monte-Carlo-methods/OCaml/monte-carlo-methods.ocaml b/Task/Monte-Carlo-methods/OCaml/monte-carlo-methods.ml similarity index 100% rename from Task/Monte-Carlo-methods/OCaml/monte-carlo-methods.ocaml rename to Task/Monte-Carlo-methods/OCaml/monte-carlo-methods.ml diff --git a/Task/Monte-Carlo-methods/PascalABC.NET/monte-carlo-methods.pas b/Task/Monte-Carlo-methods/PascalABC.NET/monte-carlo-methods.pas new file mode 100644 index 0000000000..935034ae2d --- /dev/null +++ b/Task/Monte-Carlo-methods/PascalABC.NET/monte-carlo-methods.pas @@ -0,0 +1,9 @@ +## +for var i := 3 to 8 do +begin + var n := integer(10 ** i); + var count := 0; + loop n do + if random.sqr + random.sqr < 1 then count += 1; + Writeln(n:10, 4 * count / n:12:8); +end; diff --git a/Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rust b/Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rs similarity index 100% rename from Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rust rename to Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rs diff --git a/Task/Monty-Hall-problem/Applesoft-BASIC/monty-hall-problem.basic b/Task/Monty-Hall-problem/Applesoft-BASIC/monty-hall-problem.basic new file mode 100644 index 0000000000..fb72fb4b2c --- /dev/null +++ b/Task/Monty-Hall-problem/Applesoft-BASIC/monty-hall-problem.basic @@ -0,0 +1,41 @@ + 100 DATA 1000,ONE,TWO,THREE,GOAT,CAR,2,STICKER,SWITCHER,", YOU HAVE WON A "," HAS WON THE CAR ",","," OR" + 110 READ TIMES,D$(0),D$(1),D$(2),P$(0),P$(1),K,STICKER$,SWITCHER$,CAR$,HAS$,I$(1),I$(2) + 120 LET M$ = CHR$ (13) + 130 DEF FN R(N) = INT ( RND (1) * N) + 140 TEXT + 150 FOR GAME = 1 TO TIMES + 160 IF K = 1 THEN PRINT M$" CONT"; + 170 VTAB 1 + (K = 1) * 22 + 180 HTAB 1 + 190 IF K = 1 THEN END + 200 IF K THEN HOME + 210 LET CAR = FN R(3) + 220 LET GUESS = FN R(3) + 230 FOR LOOP = 0 TO 0 + 240 LET SHOW = FN R(3) + 250 LET LOOP = - (SHOW = GUESS OR SHOW = CAR) + 260 NEXT LOOP + 270 FOR LOOP = 0 TO 0 + 280 LET NG = FN R(3) + 290 LET LOOP = - (NG = GUESS OR NG = SHOW) + 300 NEXT LOOP + 310 LET STICK = STICK + (GUESS = CAR) + 320 LET SWITCH = SWITCH + (NG = CAR) + 330 PRINT "THE MONTY HALL PROBLEM"M$M$" LET'S MAKE A DEAL - GAME # "GAME;M$M$"WHICH DOOR DO YOU THINK THAT THE CAR IS BEHIND?"M$M$"CHOOSE"; + 340 FOR I = 0 TO 2 + 350 PRINT I$((I > 0) + (I = 2))" DOOR NUMBER "D$(I); + 360 NEXT I + 370 PRINT "."M$M$"YOU HAVE CHOSEN DOOR NUMBER "D$(GUESS)"."; + 380 CALL - 868 + 390 PRINT M$M$"THERE IS A GOAT BEHIND DOOR "D$(SHOW)". DO "; + 400 CALL - 868 + 410 PRINT M$"YOU WANT TO SWITCH TO DOOR NUMBER "D$(NG)"?"; + 420 CALL - 868 + 430 PRINT CHR$ (8)M$M$STICKER$CAR$P$(GUESS = CAR)"."; + 440 CALL - 868 + 450 PRINT M$SWITCHER$CAR$P$(NG = CAR)"."; + 460 CALL - 868 + 470 PRINT M$M$STICKER$HAS$STICK" TIMES"M$"AND "SWITCHER$HAS$SWITCH;M$"TIMES OUT OF "GAME"."M$ + 480 LET K = PEEK (49152) > 127 + 490 LET C = PEEK (49200 - K * 32) + 500 NEXT GAME diff --git a/Task/Monty-Hall-problem/Delphi/monty-hall-problem.delphi b/Task/Monty-Hall-problem/Delphi/monty-hall-problem.pas similarity index 100% rename from Task/Monty-Hall-problem/Delphi/monty-hall-problem.delphi rename to Task/Monty-Hall-problem/Delphi/monty-hall-problem.pas diff --git a/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy b/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy index 58f05bec08..1ee159f97e 100644 --- a/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy +++ b/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy @@ -1,12 +1,12 @@ max = 1000000 for i = 1 to max - car_door = randint 3 - chosen_door = randint 3 + car_door = random 3 + chosen_door = random 3 if car_door <> chosen_door montys_door = 6 - car_door - chosen_door else repeat - montys_door = randint 3 + montys_door = random 3 until montys_door <> car_door . . diff --git a/Task/Monty-Hall-problem/Elixir/monty-hall-problem.elixir b/Task/Monty-Hall-problem/Elixir/monty-hall-problem.ex similarity index 100% rename from Task/Monty-Hall-problem/Elixir/monty-hall-problem.elixir rename to Task/Monty-Hall-problem/Elixir/monty-hall-problem.ex diff --git a/Task/Monty-Hall-problem/Euphoria/monty-hall-problem.euphoria b/Task/Monty-Hall-problem/Euphoria/monty-hall-problem.ex similarity index 100% rename from Task/Monty-Hall-problem/Euphoria/monty-hall-problem.euphoria rename to Task/Monty-Hall-problem/Euphoria/monty-hall-problem.ex diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-1.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-1.jl similarity index 100% rename from Task/Monty-Hall-problem/Julia/monty-hall-problem-1.julia rename to Task/Monty-Hall-problem/Julia/monty-hall-problem-1.jl diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-2.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-2.jl similarity index 100% rename from Task/Monty-Hall-problem/Julia/monty-hall-problem-2.julia rename to Task/Monty-Hall-problem/Julia/monty-hall-problem-2.jl diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-3.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-3.jl similarity index 100% rename from Task/Monty-Hall-problem/Julia/monty-hall-problem-3.julia rename to Task/Monty-Hall-problem/Julia/monty-hall-problem-3.jl diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-4.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-4.jl similarity index 100% rename from Task/Monty-Hall-problem/Julia/monty-hall-problem-4.julia rename to Task/Monty-Hall-problem/Julia/monty-hall-problem-4.jl diff --git a/Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kotlin b/Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kts similarity index 100% rename from Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kotlin rename to Task/Monty-Hall-problem/Kotlin/monty-hall-problem.kts diff --git a/Task/Monty-Hall-problem/OCaml/monty-hall-problem.ocaml b/Task/Monty-Hall-problem/OCaml/monty-hall-problem.ml similarity index 100% rename from Task/Monty-Hall-problem/OCaml/monty-hall-problem.ocaml rename to Task/Monty-Hall-problem/OCaml/monty-hall-problem.ml diff --git a/Task/Monty-Hall-problem/Rust/monty-hall-problem.rust b/Task/Monty-Hall-problem/Rust/monty-hall-problem.rs similarity index 100% rename from Task/Monty-Hall-problem/Rust/monty-hall-problem.rust rename to Task/Monty-Hall-problem/Rust/monty-hall-problem.rs diff --git a/Task/Monty-Hall-problem/Scheme/monty-hall-problem.ss b/Task/Monty-Hall-problem/Scheme/monty-hall-problem.scm similarity index 100% rename from Task/Monty-Hall-problem/Scheme/monty-hall-problem.ss rename to Task/Monty-Hall-problem/Scheme/monty-hall-problem.scm diff --git a/Task/Monty-Hall-problem/V-(Vlang)/monty-hall-problem.v b/Task/Monty-Hall-problem/V-(Vlang)/monty-hall-problem.v index 117c631c7d..862760d2f2 100644 --- a/Task/Monty-Hall-problem/V-(Vlang)/monty-hall-problem.v +++ b/Task/Monty-Hall-problem/V-(Vlang)/monty-hall-problem.v @@ -12,7 +12,7 @@ fn main() { } stay_wins += doors[guess] switch_wins += doors[3 - guess - shown] - for clear in 0..3 {if doors[clear] != 0 {doors[clear] = 0}} + for i in 0..3 {doors[i] = 0} } println("Simulating ${games} games:") println("Staying wins ${stay_wins} times at ${(f32(stay_wins) / f32(games) * 100):.2}% of games") diff --git a/Task/Morse-code/Delphi/morse-code.delphi b/Task/Morse-code/Delphi/morse-code.pas similarity index 100% rename from Task/Morse-code/Delphi/morse-code.delphi rename to Task/Morse-code/Delphi/morse-code.pas diff --git a/Task/Morse-code/Ed/morse-code.ed b/Task/Morse-code/Ed/morse-code.ed new file mode 100644 index 0000000000..f9812a17ae --- /dev/null +++ b/Task/Morse-code/Ed/morse-code.ed @@ -0,0 +1,30 @@ +# by Artyom Bologov +H +g/[Aa]/s//.- /g +g/[Bb]/s//-... /g +g/[Cc]/s//-.-. /g +g/[Dd]/s//-.. /g +g/[Ee]/s//. /g +g/[Ff]/s//..-. /g +g/[Gg]/s//--. /g +g/[Hh]/s//.... /g +g/[Ii]/s//.. /g +g/[Jj]/s//.--- /g +g/[Kk]/s//-.- /g +g/[Ll]/s//.-.. /g +g/[Mm]/s//-- /g +g/[Nn]/s//-. /g +g/[Oo]/s//--- /g +g/[Pp]/s//.-- /g +g/[Qq]/s//--.- /g +g/[Rr]/s//.-. /g +g/[Ss]/s//... /g +g/[Tt]/s//- /g +g/[Uu]/s//..- /g +g/[Vv]/s//...- /g +g/[Ww]/s//.-- /g +g/[Xx]/s//-..- /g +g/[Yy]/s//-.-- /g +g/[Zz]/s//--.. /g +,p +Q diff --git a/Task/Morse-code/Elixir/morse-code.elixir b/Task/Morse-code/Elixir/morse-code.ex similarity index 100% rename from Task/Morse-code/Elixir/morse-code.elixir rename to Task/Morse-code/Elixir/morse-code.ex diff --git a/Task/Morse-code/Julia/morse-code.julia b/Task/Morse-code/Julia/morse-code.jl similarity index 100% rename from Task/Morse-code/Julia/morse-code.julia rename to Task/Morse-code/Julia/morse-code.jl diff --git a/Task/Morse-code/Kotlin/morse-code.kotlin b/Task/Morse-code/Kotlin/morse-code.kts similarity index 100% rename from Task/Morse-code/Kotlin/morse-code.kotlin rename to Task/Morse-code/Kotlin/morse-code.kts diff --git a/Task/Morse-code/OCaml/morse-code.ocaml b/Task/Morse-code/OCaml/morse-code.ml similarity index 100% rename from Task/Morse-code/OCaml/morse-code.ocaml rename to Task/Morse-code/OCaml/morse-code.ml diff --git a/Task/Morse-code/Rust/morse-code-1.rust b/Task/Morse-code/Rust/morse-code-1.rs similarity index 100% rename from Task/Morse-code/Rust/morse-code-1.rust rename to Task/Morse-code/Rust/morse-code-1.rs diff --git a/Task/Morse-code/Rust/morse-code-2.rust b/Task/Morse-code/Rust/morse-code-2.rs similarity index 100% rename from Task/Morse-code/Rust/morse-code-2.rust rename to Task/Morse-code/Rust/morse-code-2.rs diff --git a/Task/Morse-code/V-(Vlang)/morse-code.v b/Task/Morse-code/V-(Vlang)/morse-code.v new file mode 100644 index 0000000000..e0e217e756 --- /dev/null +++ b/Task/Morse-code/V-(Vlang)/morse-code.v @@ -0,0 +1,20 @@ +const morse_code = [["a", ".-"], ["b", "-..."], ["c", "-.-."], ["d", "-.."], ["e", "."], + ["f", "..-."], ["g", "--."], ["h", "...."], ["i", ".."], ["j", ".---"], + ["k", "-.-"], ["l", ".-.."], ["m", "--"], ["n", "-."], ["o", "---"], + ["p", ".--."], ["q", "--.-"], ["r", ".-."], ["s", "..."], ["t", "-"], + ["u", "..-"], ["v", "...-"], ["w", ".--"], ["x", "-..-"], ["y", "-.--"], + ["z", "--.."], ["0", "-----"], ["1", ".----"], ["2", "..---"], ["3", "...--"], + ["4", "....-"], ["5", "....."], ["6", "-...."], ["7", "--..."], ["8", "---.."], + ["9", "----."]] + +fn main() { + str := "this is a test text" + mut strmorse := "" + for n, _ in str { + if str[n].ascii_str() ==" " {strmorse += " "} + for m, _ in morse_code { + if morse_code[m][0] == str[n].ascii_str() {strmorse += morse_code[m][1] + "|"} + } + } + println(strmorse.all_before_last("|")) +} diff --git a/Task/Motzkin-numbers/ALGOL-68/motzkin-numbers.alg b/Task/Motzkin-numbers/ALGOL-68/motzkin-numbers.alg index 3bf9ef4acc..b83f368889 100644 --- a/Task/Motzkin-numbers/ALGOL-68/motzkin-numbers.alg +++ b/Task/Motzkin-numbers/ALGOL-68/motzkin-numbers.alg @@ -36,16 +36,17 @@ BEGIN # find some Motzkin numbers # PROC pad left = ( STRING s, INT n )STRING: IF INT len = ( UPB s - LWB s ) + 1; len >= n THEN s ELSE ( ( n - len ) * " " ) + s FI; - # show the Motzkin numbers # - print( ( " n M[n] Prime?", newline ) ); - print( ( "-----------------------------------", newline ) ); - []LONG LONG INT m = MOTZKIN 41; - FOR i FROM LWB m TO UPB m DO - print( ( whole( i, -2 ) - , pad left( commatise( m[ i ] ), 26 ) - , IF is probably prime( m[ i ] ) THEN " prime" ELSE "" FI - , newline - ) - ) - OD + BEGIN # show the Motzkin numbers # + print( ( " n M[n] Prime?", newline ) ); + print( ( "-----------------------------------", newline ) ); + []LONG LONG INT m = MOTZKIN 41; + FOR i FROM LWB m TO UPB m DO + print( ( whole( i, -2 ) + , pad left( commatise( m[ i ] ), 26 ) + , IF is probably prime( m[ i ] ) THEN " prime" ELSE "" FI + , newline + ) + ) + OD + END END diff --git a/Task/Motzkin-numbers/Julia/motzkin-numbers.julia b/Task/Motzkin-numbers/Julia/motzkin-numbers.jl similarity index 100% rename from Task/Motzkin-numbers/Julia/motzkin-numbers.julia rename to Task/Motzkin-numbers/Julia/motzkin-numbers.jl diff --git a/Task/Motzkin-numbers/Rust/motzkin-numbers.rust b/Task/Motzkin-numbers/Rust/motzkin-numbers.rs similarity index 100% rename from Task/Motzkin-numbers/Rust/motzkin-numbers.rust rename to Task/Motzkin-numbers/Rust/motzkin-numbers.rs diff --git a/Task/Mouse-position/Delphi/mouse-position-1.delphi b/Task/Mouse-position/Delphi/mouse-position-1.pas similarity index 100% rename from Task/Mouse-position/Delphi/mouse-position-1.delphi rename to Task/Mouse-position/Delphi/mouse-position-1.pas diff --git a/Task/Mouse-position/Delphi/mouse-position-2.delphi b/Task/Mouse-position/Delphi/mouse-position-2.pas similarity index 100% rename from Task/Mouse-position/Delphi/mouse-position-2.delphi rename to Task/Mouse-position/Delphi/mouse-position-2.pas diff --git a/Task/Mouse-position/Julia/mouse-position.julia b/Task/Mouse-position/Julia/mouse-position.jl similarity index 100% rename from Task/Mouse-position/Julia/mouse-position.julia rename to Task/Mouse-position/Julia/mouse-position.jl diff --git a/Task/Mouse-position/Kotlin/mouse-position.kotlin b/Task/Mouse-position/Kotlin/mouse-position.kts similarity index 100% rename from Task/Mouse-position/Kotlin/mouse-position.kotlin rename to Task/Mouse-position/Kotlin/mouse-position.kts diff --git a/Task/Mouse-position/OCaml/mouse-position.ocaml b/Task/Mouse-position/OCaml/mouse-position.ml similarity index 100% rename from Task/Mouse-position/OCaml/mouse-position.ocaml rename to Task/Mouse-position/OCaml/mouse-position.ml diff --git a/Task/Mouse-position/Rust/mouse-position.rust b/Task/Mouse-position/Rust/mouse-position.rs similarity index 100% rename from Task/Mouse-position/Rust/mouse-position.rust rename to Task/Mouse-position/Rust/mouse-position.rs diff --git a/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg b/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg index c1e61c69e7..0e7c19b92d 100644 --- a/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg +++ b/Task/Move-to-front-algorithm/ALGOL-68/move-to-front-algorithm.alg @@ -7,29 +7,21 @@ PROC move to front = ( STRING text, INT text pos )STRING: text ELSE # the character isn't already at the front - construct the new string # - INT char pos = LWB text + text pos; - ( text[ char pos : char pos ] + text[ : char pos - 1 ] + text[ char pos + 1 : ] ) - FI; - # encode the string "text", using "initial table" as the starting symbol table# PROC encode = ( STRING text, STRING initial table )[]INT: BEGIN - [ 1 : ( UPB text - LWB text ) + 1 ]INT result; - STRING symbol table := initial table; - FOR text pos FROM LWB text TO UPB text DO INT symbol pos := 0; - result[ text pos ] := IF char in string( text[ text pos ], symbol pos, symbol table ) THEN @@ -41,24 +33,17 @@ BEGIN # the character isn't in the symbol table # -1 FI; - # modify the symbol table so the latest character is at the front # symbol table := move to front( symbol table, result[ text pos ] ) - OD; - result END; # encode # - - # decode "encoded", using "initial table" as the starting symbol table # PROC decode = ( []INT encoded, STRING initial table )STRING: BEGIN - STRING result := ""; STRING symbol table := initial table; - FOR text pos FROM LWB encoded TO UPB encoded DO result @@ -70,24 +55,17 @@ BEGIN # the character is in the symbol table # symbol table[ encoded[ text pos ] + LWB symbol table ] FI; - # modify the symbol table so the latest character is at the front # symbol table := move to front( symbol table, encoded[ text pos ] ) - OD; - result END; # decode # - - # routine to test the encode and decode routines # PROC test encode and decode = ( STRING text )VOID: BEGIN - # initial value for the symbol table # []CHAR initial table = "abcdefghijklmnopqrstuvwxyz"; - # procedure to format the encoded value # PROC format encoded value = ( []INT values )STRING: BEGIN @@ -96,13 +74,10 @@ BEGIN DO result +:= ( " " + whole( values[ value pos ], 0 ) ) OD; - result END; # format encoded value # - []INT encoded = encode( text, initial table ); STRING decoded = decode( encoded, initial table ); - print( ( ( text + " encodes to [" + format encoded value( encoded ) @@ -120,18 +95,11 @@ BEGIN , newline ) ) - END; # test encode and decode # - - -main: ( - test encode and decode( "broood" ) ; test encode and decode( "bananaaa" ) ; test encode and decode( "hiphophiphop" ) # ; test encode and decode( "abcdefghijklmnopqrstuvwxyz" ) # # ; test encode and decode( "zyxwvutsrqponmlkjihgfedcba" ) # - -) diff --git a/Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.elixir b/Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.ex similarity index 100% rename from Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.elixir rename to Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.ex diff --git a/Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.julia b/Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.jl similarity index 100% rename from Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.julia rename to Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.jl diff --git a/Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kotlin b/Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kts similarity index 100% rename from Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kotlin rename to Task/Move-to-front-algorithm/Kotlin/move-to-front-algorithm.kts diff --git a/Task/Move-to-front-algorithm/Rust/move-to-front-algorithm.rust b/Task/Move-to-front-algorithm/Rust/move-to-front-algorithm.rs similarity index 100% rename from Task/Move-to-front-algorithm/Rust/move-to-front-algorithm.rust rename to Task/Move-to-front-algorithm/Rust/move-to-front-algorithm.rs diff --git a/Task/Multi-base-primes/Julia/multi-base-primes-1.julia b/Task/Multi-base-primes/Julia/multi-base-primes-1.jl similarity index 100% rename from Task/Multi-base-primes/Julia/multi-base-primes-1.julia rename to Task/Multi-base-primes/Julia/multi-base-primes-1.jl diff --git a/Task/Multi-base-primes/Julia/multi-base-primes-2.julia b/Task/Multi-base-primes/Julia/multi-base-primes-2.jl similarity index 100% rename from Task/Multi-base-primes/Julia/multi-base-primes-2.julia rename to Task/Multi-base-primes/Julia/multi-base-primes-2.jl diff --git a/Task/Multi-base-primes/Rust/multi-base-primes-1.rust b/Task/Multi-base-primes/Rust/multi-base-primes-1.rs similarity index 100% rename from Task/Multi-base-primes/Rust/multi-base-primes-1.rust rename to Task/Multi-base-primes/Rust/multi-base-primes-1.rs diff --git a/Task/Multi-base-primes/Rust/multi-base-primes-2.rust b/Task/Multi-base-primes/Rust/multi-base-primes-2.rs similarity index 100% rename from Task/Multi-base-primes/Rust/multi-base-primes-2.rust rename to Task/Multi-base-primes/Rust/multi-base-primes-2.rs diff --git a/Task/Multi-dimensional-array/Delphi/multi-dimensional-array.delphi b/Task/Multi-dimensional-array/Delphi/multi-dimensional-array.pas similarity index 100% rename from Task/Multi-dimensional-array/Delphi/multi-dimensional-array.delphi rename to Task/Multi-dimensional-array/Delphi/multi-dimensional-array.pas diff --git a/Task/Multi-dimensional-array/Julia/multi-dimensional-array.julia b/Task/Multi-dimensional-array/Julia/multi-dimensional-array.jl similarity index 100% rename from Task/Multi-dimensional-array/Julia/multi-dimensional-array.julia rename to Task/Multi-dimensional-array/Julia/multi-dimensional-array.jl diff --git a/Task/Multi-dimensional-array/Kotlin/multi-dimensional-array.kotlin b/Task/Multi-dimensional-array/Kotlin/multi-dimensional-array.kts similarity index 100% rename from Task/Multi-dimensional-array/Kotlin/multi-dimensional-array.kotlin rename to Task/Multi-dimensional-array/Kotlin/multi-dimensional-array.kts diff --git a/Task/Multifactorial/Crystal/multifactorial.crystal b/Task/Multifactorial/Crystal/multifactorial.cr similarity index 100% rename from Task/Multifactorial/Crystal/multifactorial.crystal rename to Task/Multifactorial/Crystal/multifactorial.cr diff --git a/Task/Multifactorial/Delphi/multifactorial.delphi b/Task/Multifactorial/Delphi/multifactorial.pas similarity index 100% rename from Task/Multifactorial/Delphi/multifactorial.delphi rename to Task/Multifactorial/Delphi/multifactorial.pas diff --git a/Task/Multifactorial/Elixir/multifactorial.elixir b/Task/Multifactorial/Elixir/multifactorial.ex similarity index 100% rename from Task/Multifactorial/Elixir/multifactorial.elixir rename to Task/Multifactorial/Elixir/multifactorial.ex diff --git a/Task/Multifactorial/Julia/multifactorial.julia b/Task/Multifactorial/Julia/multifactorial.jl similarity index 100% rename from Task/Multifactorial/Julia/multifactorial.julia rename to Task/Multifactorial/Julia/multifactorial.jl diff --git a/Task/Multifactorial/Kotlin/multifactorial.kotlin b/Task/Multifactorial/Kotlin/multifactorial.kts similarity index 100% rename from Task/Multifactorial/Kotlin/multifactorial.kotlin rename to Task/Multifactorial/Kotlin/multifactorial.kts diff --git a/Task/Multifactorial/OCaml/multifactorial.ocaml b/Task/Multifactorial/OCaml/multifactorial.ml similarity index 100% rename from Task/Multifactorial/OCaml/multifactorial.ocaml rename to Task/Multifactorial/OCaml/multifactorial.ml diff --git a/Task/Multifactorial/Rust/multifactorial.rust b/Task/Multifactorial/Rust/multifactorial.rs similarity index 100% rename from Task/Multifactorial/Rust/multifactorial.rust rename to Task/Multifactorial/Rust/multifactorial.rs diff --git a/Task/Multifactorial/Scheme/multifactorial.ss b/Task/Multifactorial/Scheme/multifactorial.scm similarity index 100% rename from Task/Multifactorial/Scheme/multifactorial.ss rename to Task/Multifactorial/Scheme/multifactorial.scm diff --git a/Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-1.delphi b/Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-1.pas similarity index 100% rename from Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-1.delphi rename to Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-1.pas diff --git a/Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-2.delphi b/Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-2.pas similarity index 100% rename from Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-2.delphi rename to Task/Multiple-distinct-objects/Delphi/multiple-distinct-objects-2.pas diff --git a/Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.elixir b/Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.ex similarity index 100% rename from Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.elixir rename to Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.ex diff --git a/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.julia b/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.jl similarity index 100% rename from Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.julia rename to Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.jl diff --git a/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.julia b/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.jl similarity index 100% rename from Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.julia rename to Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.jl diff --git a/Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kotlin b/Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kts similarity index 100% rename from Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kotlin rename to Task/Multiple-distinct-objects/Kotlin/multiple-distinct-objects.kts diff --git a/Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-1.ocaml b/Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-1.ml similarity index 100% rename from Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-1.ocaml rename to Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-1.ml diff --git a/Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-2.ocaml b/Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-2.ml similarity index 100% rename from Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-2.ocaml rename to Task/Multiple-distinct-objects/OCaml/multiple-distinct-objects-2.ml diff --git a/Task/Multiple-distinct-objects/Rust/multiple-distinct-objects.rust b/Task/Multiple-distinct-objects/Rust/multiple-distinct-objects.rs similarity index 100% rename from Task/Multiple-distinct-objects/Rust/multiple-distinct-objects.rust rename to Task/Multiple-distinct-objects/Rust/multiple-distinct-objects.rs diff --git a/Task/Multiple-regression/Julia/multiple-regression.julia b/Task/Multiple-regression/Julia/multiple-regression.jl similarity index 100% rename from Task/Multiple-regression/Julia/multiple-regression.julia rename to Task/Multiple-regression/Julia/multiple-regression.jl diff --git a/Task/Multiple-regression/Kotlin/multiple-regression.kotlin b/Task/Multiple-regression/Kotlin/multiple-regression.kts similarity index 100% rename from Task/Multiple-regression/Kotlin/multiple-regression.kotlin rename to Task/Multiple-regression/Kotlin/multiple-regression.kts diff --git a/Task/Multiplication-tables/Delphi/multiplication-tables.delphi b/Task/Multiplication-tables/Delphi/multiplication-tables.pas similarity index 100% rename from Task/Multiplication-tables/Delphi/multiplication-tables.delphi rename to Task/Multiplication-tables/Delphi/multiplication-tables.pas diff --git a/Task/Multiplication-tables/Elixir/multiplication-tables.elixir b/Task/Multiplication-tables/Elixir/multiplication-tables.ex similarity index 100% rename from Task/Multiplication-tables/Elixir/multiplication-tables.elixir rename to Task/Multiplication-tables/Elixir/multiplication-tables.ex diff --git a/Task/Multiplication-tables/Euphoria/multiplication-tables.euphoria b/Task/Multiplication-tables/Euphoria/multiplication-tables.ex similarity index 100% rename from Task/Multiplication-tables/Euphoria/multiplication-tables.euphoria rename to Task/Multiplication-tables/Euphoria/multiplication-tables.ex diff --git a/Task/Multiplication-tables/JavaScript/multiplication-tables-5.js b/Task/Multiplication-tables/JavaScript/multiplication-tables-5.js index 075688f2fb..0005ced912 100644 --- a/Task/Multiplication-tables/JavaScript/multiplication-tables-5.js +++ b/Task/Multiplication-tables/JavaScript/multiplication-tables-5.js @@ -9,15 +9,13 @@ return [ ["x", ...xs], - ...xs.flatMap( - x => [ - [x, ...xs.flatMap( - y => y < x ? ( - [""] - ) : [`${x * y}`] - )] - ] - ) + ...xs.flatMap(x => [ + [x, ...xs.flatMap( + y => y < x + ? [""] + : [`${x * y}`] + )] + ]) ]; }; @@ -32,7 +30,8 @@ "width:33em", "height:33em", "table-layout:fixed" - ].join(";") + ] + .join(";") })( multTable(1)(12) ); @@ -40,10 +39,12 @@ // ---------------- GENERIC FUNCTIONS ---------------- // enumFromTo :: Int -> Int -> [Int] - const enumFromTo = m => n => - n >= m ? Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i) : []; + const enumFromTo = m => + // Enumeration of the integers from m to n. + n => Array.from( + { length: 1 + n - m }, + (_, i) => m + i + ); // ------------------- FORMATTING -------------------- @@ -53,18 +54,21 @@ rows => { const style = ["class", "style"].reduce( - (a, k) => k in opts ? ( - `${a}${k}="${opts[k]}" ` - ) : a, "" + (a, k) => k in opts + ? `${a}${k}="${opts[k]}" ` + : a, + "" ), body = rows.map((row, i) => { const cells = row.map( x => `${x}` || " " - ).join(" || "); + ) + .join(" || "); return `${i ? "|" : "!"} ${cells}`; - }).join("\n|-\n"); + }) + .join("\n|-\n"); return `{| ${style}\n${body}\n|}`; }; diff --git a/Task/Multiplication-tables/Julia/multiplication-tables.julia b/Task/Multiplication-tables/Julia/multiplication-tables.jl similarity index 100% rename from Task/Multiplication-tables/Julia/multiplication-tables.julia rename to Task/Multiplication-tables/Julia/multiplication-tables.jl diff --git a/Task/Multiplication-tables/Kotlin/multiplication-tables-1.kotlin b/Task/Multiplication-tables/Kotlin/multiplication-tables-1.kts similarity index 100% rename from Task/Multiplication-tables/Kotlin/multiplication-tables-1.kotlin rename to Task/Multiplication-tables/Kotlin/multiplication-tables-1.kts diff --git a/Task/Multiplication-tables/Kotlin/multiplication-tables-2.kotlin b/Task/Multiplication-tables/Kotlin/multiplication-tables-2.kts similarity index 100% rename from Task/Multiplication-tables/Kotlin/multiplication-tables-2.kotlin rename to Task/Multiplication-tables/Kotlin/multiplication-tables-2.kts diff --git a/Task/Multiplication-tables/Nu/multiplication-tables.nu b/Task/Multiplication-tables/Nu/multiplication-tables.nu new file mode 100644 index 0000000000..b1cba8fc34 --- /dev/null +++ b/Task/Multiplication-tables/Nu/multiplication-tables.nu @@ -0,0 +1,7 @@ +1..12 | each {|x| + 1..12 | each {|y| + if $x > $y and $y > 1 { '' } else { $x * $y } + } + | fill -a r -w 4 | str join +} +| str join "\n" diff --git a/Task/Multiplication-tables/OCaml/multiplication-tables.ocaml b/Task/Multiplication-tables/OCaml/multiplication-tables.ml similarity index 100% rename from Task/Multiplication-tables/OCaml/multiplication-tables.ocaml rename to Task/Multiplication-tables/OCaml/multiplication-tables.ml diff --git a/Task/Multiplication-tables/PascalABC.NET/multiplication-tables.pas b/Task/Multiplication-tables/PascalABC.NET/multiplication-tables.pas new file mode 100644 index 0000000000..6791ee2e81 --- /dev/null +++ b/Task/Multiplication-tables/PascalABC.NET/multiplication-tables.pas @@ -0,0 +1,10 @@ +## +write(' x|'); +for var i := 1 to 12 do write(i:4); +writeln(#13, '---+', '-' * 48); +for var i := 1 to 12 do +begin + write(i:3, '|', ' ' * (4 * i - 4)); + for var j := i to 12 do write(i * j:4); + writeln; +end; diff --git a/Task/Multiplication-tables/Rust/multiplication-tables-1.rust b/Task/Multiplication-tables/Rust/multiplication-tables-1.rs similarity index 100% rename from Task/Multiplication-tables/Rust/multiplication-tables-1.rust rename to Task/Multiplication-tables/Rust/multiplication-tables-1.rs diff --git a/Task/Multiplication-tables/Rust/multiplication-tables-2.rust b/Task/Multiplication-tables/Rust/multiplication-tables-2.rs similarity index 100% rename from Task/Multiplication-tables/Rust/multiplication-tables-2.rust rename to Task/Multiplication-tables/Rust/multiplication-tables-2.rs diff --git a/Task/Multiplication-tables/Scheme/multiplication-tables.ss b/Task/Multiplication-tables/Scheme/multiplication-tables.scm similarity index 100% rename from Task/Multiplication-tables/Scheme/multiplication-tables.ss rename to Task/Multiplication-tables/Scheme/multiplication-tables.scm diff --git a/Task/Multiplicative-order/Julia/multiplicative-order.julia b/Task/Multiplicative-order/Julia/multiplicative-order.jl similarity index 100% rename from Task/Multiplicative-order/Julia/multiplicative-order.julia rename to Task/Multiplicative-order/Julia/multiplicative-order.jl diff --git a/Task/Multiplicative-order/Kotlin/multiplicative-order.kotlin b/Task/Multiplicative-order/Kotlin/multiplicative-order.kts similarity index 100% rename from Task/Multiplicative-order/Kotlin/multiplicative-order.kotlin rename to Task/Multiplicative-order/Kotlin/multiplicative-order.kts diff --git a/Task/Multisplit/Delphi/multisplit.delphi b/Task/Multisplit/Delphi/multisplit.pas similarity index 100% rename from Task/Multisplit/Delphi/multisplit.delphi rename to Task/Multisplit/Delphi/multisplit.pas diff --git a/Task/Multisplit/Elixir/multisplit.elixir b/Task/Multisplit/Elixir/multisplit.ex similarity index 100% rename from Task/Multisplit/Elixir/multisplit.elixir rename to Task/Multisplit/Elixir/multisplit.ex diff --git a/Task/Multisplit/Julia/multisplit.julia b/Task/Multisplit/Julia/multisplit.jl similarity index 100% rename from Task/Multisplit/Julia/multisplit.julia rename to Task/Multisplit/Julia/multisplit.jl diff --git a/Task/Multisplit/Kotlin/multisplit.kotlin b/Task/Multisplit/Kotlin/multisplit.kts similarity index 100% rename from Task/Multisplit/Kotlin/multisplit.kotlin rename to Task/Multisplit/Kotlin/multisplit.kts diff --git a/Task/Multisplit/NewLISP/multisplit.l b/Task/Multisplit/NewLISP/multisplit.l new file mode 100644 index 0000000000..6c32993b5c --- /dev/null +++ b/Task/Multisplit/NewLISP/multisplit.l @@ -0,0 +1,9 @@ +(define (multi-split str seps) + (let (parsed + (find-all + (string {((.*?)(} (join (map string seps) "|") {))|(.+)$}) + str + (if (= "" $3) (list $4) (list $2 $3)))) + (list parsed (map first parsed)))) + +(multi-split "a!===b=!=c" '(== != =)) diff --git a/Task/Multisplit/PascalABC.NET/multisplit.pas b/Task/Multisplit/PascalABC.NET/multisplit.pas new file mode 100644 index 0000000000..b4c2e1bfba --- /dev/null +++ b/Task/Multisplit/PascalABC.NET/multisplit.pas @@ -0,0 +1,2 @@ +// Multisplit. Nigel Galloway: August 16th., 2024 +## print('a!===b=!=c'.Split(|'==','!=','='|,System.StringSplitOptions.None)) diff --git a/Task/Multisplit/Scheme/multisplit.ss b/Task/Multisplit/Scheme/multisplit.scm similarity index 100% rename from Task/Multisplit/Scheme/multisplit.ss rename to Task/Multisplit/Scheme/multisplit.scm diff --git a/Task/Munchausen-numbers/ALGOL-68/munchausen-numbers-1.alg b/Task/Munchausen-numbers/ALGOL-68/munchausen-numbers-1.alg index b3320f620c..1ef8d89dfd 100644 --- a/Task/Munchausen-numbers/ALGOL-68/munchausen-numbers-1.alg +++ b/Task/Munchausen-numbers/ALGOL-68/munchausen-numbers-1.alg @@ -31,7 +31,7 @@ WHILE d1 < 6 DO d2 := 0; d2 part := 0; d1 +:= 1; - d1 part +:= 1000; + d1 part +:= 1000 FI FI FI diff --git a/Task/Munchausen-numbers/Elixir/munchausen-numbers.elixir b/Task/Munchausen-numbers/Elixir/munchausen-numbers.ex similarity index 100% rename from Task/Munchausen-numbers/Elixir/munchausen-numbers.elixir rename to Task/Munchausen-numbers/Elixir/munchausen-numbers.ex diff --git a/Task/Munchausen-numbers/Julia/munchausen-numbers.julia b/Task/Munchausen-numbers/Julia/munchausen-numbers.jl similarity index 100% rename from Task/Munchausen-numbers/Julia/munchausen-numbers.julia rename to Task/Munchausen-numbers/Julia/munchausen-numbers.jl diff --git a/Task/Munchausen-numbers/Kotlin/munchausen-numbers.kotlin b/Task/Munchausen-numbers/Kotlin/munchausen-numbers.kts similarity index 100% rename from Task/Munchausen-numbers/Kotlin/munchausen-numbers.kotlin rename to Task/Munchausen-numbers/Kotlin/munchausen-numbers.kts diff --git a/Task/Munchausen-numbers/OCaml/munchausen-numbers.ocaml b/Task/Munchausen-numbers/OCaml/munchausen-numbers.ml similarity index 100% rename from Task/Munchausen-numbers/OCaml/munchausen-numbers.ocaml rename to Task/Munchausen-numbers/OCaml/munchausen-numbers.ml diff --git a/Task/Munchausen-numbers/Rust/munchausen-numbers-1.rust b/Task/Munchausen-numbers/Rust/munchausen-numbers-1.rs similarity index 100% rename from Task/Munchausen-numbers/Rust/munchausen-numbers-1.rust rename to Task/Munchausen-numbers/Rust/munchausen-numbers-1.rs diff --git a/Task/Munchausen-numbers/Rust/munchausen-numbers-2.rust b/Task/Munchausen-numbers/Rust/munchausen-numbers-2.rs similarity index 100% rename from Task/Munchausen-numbers/Rust/munchausen-numbers-2.rust rename to Task/Munchausen-numbers/Rust/munchausen-numbers-2.rs diff --git a/Task/Munching-squares/Delphi/munching-squares.delphi b/Task/Munching-squares/Delphi/munching-squares.pas similarity index 100% rename from Task/Munching-squares/Delphi/munching-squares.delphi rename to Task/Munching-squares/Delphi/munching-squares.pas diff --git a/Task/Munching-squares/EasyLang/munching-squares.easy b/Task/Munching-squares/EasyLang/munching-squares.easy index 0a94731bac..b888d2e392 100644 --- a/Task/Munching-squares/EasyLang/munching-squares.easy +++ b/Task/Munching-squares/EasyLang/munching-squares.easy @@ -1,9 +1,8 @@ sc = 100 / 64 for x range0 64 for y range0 64 - h = bitand bitxor x y 63 - c = h / 63 - color3 c c c + h = bitand bitxor x y 63 / 63 + color3 h h h move x * sc y * sc rect sc + 0.1 sc + 0.1 . diff --git a/Task/Munching-squares/Julia/munching-squares.julia b/Task/Munching-squares/Julia/munching-squares.jl similarity index 100% rename from Task/Munching-squares/Julia/munching-squares.julia rename to Task/Munching-squares/Julia/munching-squares.jl diff --git a/Task/Munching-squares/Kotlin/munching-squares.kotlin b/Task/Munching-squares/Kotlin/munching-squares.kts similarity index 100% rename from Task/Munching-squares/Kotlin/munching-squares.kotlin rename to Task/Munching-squares/Kotlin/munching-squares.kts diff --git a/Task/Munching-squares/OCaml/munching-squares.ocaml b/Task/Munching-squares/OCaml/munching-squares.ml similarity index 100% rename from Task/Munching-squares/OCaml/munching-squares.ocaml rename to Task/Munching-squares/OCaml/munching-squares.ml diff --git a/Task/Munching-squares/Rust/munching-squares.rust b/Task/Munching-squares/Rust/munching-squares.rs similarity index 100% rename from Task/Munching-squares/Rust/munching-squares.rust rename to Task/Munching-squares/Rust/munching-squares.rs diff --git a/Task/Musical-scale/Delphi/musical-scale.delphi b/Task/Musical-scale/Delphi/musical-scale.pas similarity index 100% rename from Task/Musical-scale/Delphi/musical-scale.delphi rename to Task/Musical-scale/Delphi/musical-scale.pas diff --git a/Task/Musical-scale/Julia/musical-scale.julia b/Task/Musical-scale/Julia/musical-scale.jl similarity index 100% rename from Task/Musical-scale/Julia/musical-scale.julia rename to Task/Musical-scale/Julia/musical-scale.jl diff --git a/Task/Musical-scale/Kotlin/musical-scale.kotlin b/Task/Musical-scale/Kotlin/musical-scale.kts similarity index 100% rename from Task/Musical-scale/Kotlin/musical-scale.kotlin rename to Task/Musical-scale/Kotlin/musical-scale.kts diff --git a/Task/Mutex/Delphi/mutex.delphi b/Task/Mutex/Delphi/mutex.pas similarity index 100% rename from Task/Mutex/Delphi/mutex.delphi rename to Task/Mutex/Delphi/mutex.pas diff --git a/Task/Mutex/Julia/mutex-1.julia b/Task/Mutex/Julia/mutex-1.jl similarity index 100% rename from Task/Mutex/Julia/mutex-1.julia rename to Task/Mutex/Julia/mutex-1.jl diff --git a/Task/Mutex/Julia/mutex-2.julia b/Task/Mutex/Julia/mutex-2.jl similarity index 100% rename from Task/Mutex/Julia/mutex-2.julia rename to Task/Mutex/Julia/mutex-2.jl diff --git a/Task/Mutex/Julia/mutex-3.julia b/Task/Mutex/Julia/mutex-3.jl similarity index 100% rename from Task/Mutex/Julia/mutex-3.julia rename to Task/Mutex/Julia/mutex-3.jl diff --git a/Task/Mutex/Julia/mutex-4.julia b/Task/Mutex/Julia/mutex-4.jl similarity index 100% rename from Task/Mutex/Julia/mutex-4.julia rename to Task/Mutex/Julia/mutex-4.jl diff --git a/Task/Mutex/Julia/mutex-5.julia b/Task/Mutex/Julia/mutex-5.jl similarity index 100% rename from Task/Mutex/Julia/mutex-5.julia rename to Task/Mutex/Julia/mutex-5.jl diff --git a/Task/Mutex/Julia/mutex-6.julia b/Task/Mutex/Julia/mutex-6.jl similarity index 100% rename from Task/Mutex/Julia/mutex-6.julia rename to Task/Mutex/Julia/mutex-6.jl diff --git a/Task/Mutex/OCaml/mutex.ocaml b/Task/Mutex/OCaml/mutex.ml similarity index 100% rename from Task/Mutex/OCaml/mutex.ocaml rename to Task/Mutex/OCaml/mutex.ml diff --git a/Task/Mutex/Rust/mutex.rust b/Task/Mutex/Rust/mutex.rs similarity index 100% rename from Task/Mutex/Rust/mutex.rust rename to Task/Mutex/Rust/mutex.rs diff --git a/Task/Mutual-recursion/Delphi/mutual-recursion.delphi b/Task/Mutual-recursion/Delphi/mutual-recursion.pas similarity index 100% rename from Task/Mutual-recursion/Delphi/mutual-recursion.delphi rename to Task/Mutual-recursion/Delphi/mutual-recursion.pas diff --git a/Task/Mutual-recursion/Elixir/mutual-recursion.elixir b/Task/Mutual-recursion/Elixir/mutual-recursion.ex similarity index 100% rename from Task/Mutual-recursion/Elixir/mutual-recursion.elixir rename to Task/Mutual-recursion/Elixir/mutual-recursion.ex diff --git a/Task/Mutual-recursion/Euphoria/mutual-recursion.euphoria b/Task/Mutual-recursion/Euphoria/mutual-recursion.ex similarity index 100% rename from Task/Mutual-recursion/Euphoria/mutual-recursion.euphoria rename to Task/Mutual-recursion/Euphoria/mutual-recursion.ex diff --git a/Task/Mutual-recursion/J/mutual-recursion-1.j b/Task/Mutual-recursion/J/mutual-recursion-1.j index 29f97a40e8..c8b6ca40c4 100644 --- a/Task/Mutual-recursion/J/mutual-recursion-1.j +++ b/Task/Mutual-recursion/J/mutual-recursion-1.j @@ -1,2 +1,2 @@ -F =: 1:`(- M @ $: @ <:) @.* M."0 -M =: 0:`(- F @ $: @ <:) @.* M."0 +F =: 1:`(- M@$:@<:)@.* M."0 +M =: 0:`(- F@$:@<:)@.* M."0 diff --git a/Task/Mutual-recursion/Julia/mutual-recursion.julia b/Task/Mutual-recursion/Julia/mutual-recursion.jl similarity index 100% rename from Task/Mutual-recursion/Julia/mutual-recursion.julia rename to Task/Mutual-recursion/Julia/mutual-recursion.jl diff --git a/Task/Mutual-recursion/Kotlin/mutual-recursion.kotlin b/Task/Mutual-recursion/Kotlin/mutual-recursion.kts similarity index 100% rename from Task/Mutual-recursion/Kotlin/mutual-recursion.kotlin rename to Task/Mutual-recursion/Kotlin/mutual-recursion.kts diff --git a/Task/Mutual-recursion/OCaml/mutual-recursion.ocaml b/Task/Mutual-recursion/OCaml/mutual-recursion.ml similarity index 100% rename from Task/Mutual-recursion/OCaml/mutual-recursion.ocaml rename to Task/Mutual-recursion/OCaml/mutual-recursion.ml diff --git a/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas b/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas new file mode 100644 index 0000000000..30c19f3292 --- /dev/null +++ b/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas @@ -0,0 +1,7 @@ +## +function M(n: integer): integer; forward; +function F(n: integer): integer := n < 1 ? 1 : n - M(F(n - 1)); +function M(n: integer): integer := n < 1 ? 0 : n - F(M(n - 1)); + +(0..19).select(x -> F(x)).println; +(0..19).select(x -> M(x)).println; diff --git a/Task/Mutual-recursion/Rust/mutual-recursion.rust b/Task/Mutual-recursion/Rust/mutual-recursion.rs similarity index 100% rename from Task/Mutual-recursion/Rust/mutual-recursion.rust rename to Task/Mutual-recursion/Rust/mutual-recursion.rs diff --git a/Task/Mutual-recursion/Scheme/mutual-recursion-1.ss b/Task/Mutual-recursion/Scheme/mutual-recursion-1.scm similarity index 100% rename from Task/Mutual-recursion/Scheme/mutual-recursion-1.ss rename to Task/Mutual-recursion/Scheme/mutual-recursion-1.scm diff --git a/Task/Mutual-recursion/Scheme/mutual-recursion-2.ss b/Task/Mutual-recursion/Scheme/mutual-recursion-2.scm similarity index 100% rename from Task/Mutual-recursion/Scheme/mutual-recursion-2.ss rename to Task/Mutual-recursion/Scheme/mutual-recursion-2.scm diff --git a/Task/N-queens-problem/Delphi/n-queens-problem.delphi b/Task/N-queens-problem/Delphi/n-queens-problem.pas similarity index 100% rename from Task/N-queens-problem/Delphi/n-queens-problem.delphi rename to Task/N-queens-problem/Delphi/n-queens-problem.pas diff --git a/Task/N-queens-problem/Elixir/n-queens-problem.elixir b/Task/N-queens-problem/Elixir/n-queens-problem.ex similarity index 100% rename from Task/N-queens-problem/Elixir/n-queens-problem.elixir rename to Task/N-queens-problem/Elixir/n-queens-problem.ex diff --git a/Task/N-queens-problem/Julia/n-queens-problem.julia b/Task/N-queens-problem/Julia/n-queens-problem.jl similarity index 100% rename from Task/N-queens-problem/Julia/n-queens-problem.julia rename to Task/N-queens-problem/Julia/n-queens-problem.jl diff --git a/Task/N-queens-problem/Kotlin/n-queens-problem.kotlin b/Task/N-queens-problem/Kotlin/n-queens-problem.kts similarity index 100% rename from Task/N-queens-problem/Kotlin/n-queens-problem.kotlin rename to Task/N-queens-problem/Kotlin/n-queens-problem.kts diff --git a/Task/N-queens-problem/OCaml/n-queens-problem-1.ocaml b/Task/N-queens-problem/OCaml/n-queens-problem-1.ml similarity index 100% rename from Task/N-queens-problem/OCaml/n-queens-problem-1.ocaml rename to Task/N-queens-problem/OCaml/n-queens-problem-1.ml diff --git a/Task/N-queens-problem/OCaml/n-queens-problem-2.ocaml b/Task/N-queens-problem/OCaml/n-queens-problem-2.ml similarity index 100% rename from Task/N-queens-problem/OCaml/n-queens-problem-2.ocaml rename to Task/N-queens-problem/OCaml/n-queens-problem-2.ml diff --git a/Task/N-queens-problem/Rust/n-queens-problem-1.rust b/Task/N-queens-problem/Rust/n-queens-problem-1.rs similarity index 100% rename from Task/N-queens-problem/Rust/n-queens-problem-1.rust rename to Task/N-queens-problem/Rust/n-queens-problem-1.rs diff --git a/Task/N-queens-problem/Rust/n-queens-problem-2.rust b/Task/N-queens-problem/Rust/n-queens-problem-2.rs similarity index 100% rename from Task/N-queens-problem/Rust/n-queens-problem-2.rust rename to Task/N-queens-problem/Rust/n-queens-problem-2.rs diff --git a/Task/N-queens-problem/Rust/n-queens-problem-3.rust b/Task/N-queens-problem/Rust/n-queens-problem-3.rs similarity index 100% rename from Task/N-queens-problem/Rust/n-queens-problem-3.rust rename to Task/N-queens-problem/Rust/n-queens-problem-3.rs diff --git a/Task/N-queens-problem/Scheme/n-queens-problem.ss b/Task/N-queens-problem/Scheme/n-queens-problem.scm similarity index 100% rename from Task/N-queens-problem/Scheme/n-queens-problem.ss rename to Task/N-queens-problem/Scheme/n-queens-problem.scm diff --git a/Task/N-queens-problem/Tailspin/n-queens-problem-2.tailspin b/Task/N-queens-problem/Tailspin/n-queens-problem-2.tailspin index c820a635c1..741791b63f 100644 --- a/Task/N-queens-problem/Tailspin/n-queens-problem-2.tailspin +++ b/Task/N-queens-problem/Tailspin/n-queens-problem-2.tailspin @@ -1,48 +1,31 @@ -templates queens - def n: $; - templates getRowColumn - when )> do 0 ! - when )> do 0 ! - when )> do 0 ! - otherwise 1! - end getRowColumn - - sink setRowColumn - def p: $; - @queens.freeRows($p.r::raw): $p.val::raw; - @queens.freeMaxs($p.c::raw + $p.r::raw): $p.val::raw; - @queens.freeMins($p.c::raw - $p.r::raw + $n): $p.val::raw; - end setRowColumn - - data done <=1> - - templates placeQueen - def c: $; - row´1 -> # - when do 1! - when <=row´($n+1)> do 0 ! - when getRowColumn <=1>)> do - def r: $; - @queens.queenRows($r::raw): $c; - {r: $, c: $c, val: 0} -> !setRowColumn - $c -> \(<=col´$n> done´1! - placeQueen <=1>)> done´1! - <> - {r: $r, c: $c, val: 1} -> !setRowColumn - row´($r::raw + 1) !\) -> # - otherwise row´($::raw + 1) -> # - end placeQueen - - @: { freeRows: [1..$n -> 1], - freeMaxs: [1..$n*2 -> 1], - freeMins: [1..$n*2 -> 1], - queenRows: [1..$n -> -1] }; - col´1 -> placeQueen -> \(<=1> $@queens.queenRows ! <> 'non-existent'!\)! +queens templates + n is $; + addColumn templates + prev is $; + addIfPossible templates + row is $; + minor is $ - $prev::length - 1; + major is $ + $prev::length + 1; + -- If prev is not an array that contains row, send it on... + $prev -> if <~|[<|=$row>]> + -> if <|?($(.. as i; -> $ - $i) matches <~|[<|=$minor>]>)> + -> if <|?($(.. as i; -> $ + $i) matches <~|[<|=$major>]>)> + -> [ $..., $row] ! + end addIfPossible + 1..$n -> addIfPossible ! + end addColumn + 1..$n -> [$] -> # ! + when <|[](=$n)> do $ ! + otherwise $ -> addColumn -> # ! end queens -'A solution to the 8 queens problem is $:8 -> queens; -' -> !OUT::write -'A solution to the 4 queens problem is $:4 -> queens; -' -> !OUT::write -'A solution to the 3 queens problem is $:3 -> queens; -' -> !OUT::write +solutions is [ 8 -> queens ]; +'For 8 queens there are $solutions::length; solutions +' ! + +columns is ['abcdefgh'...]; +'One of them is $solutions(1) -> $(.. as i; -> '$columns($i);$;'); +' ! + +'For 3 queens there are $:[3 -> queens] -> $::length; solutions +' ! diff --git a/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin b/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin new file mode 100644 index 0000000000..c820a635c1 --- /dev/null +++ b/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin @@ -0,0 +1,48 @@ +templates queens + def n: $; + templates getRowColumn + when )> do 0 ! + when )> do 0 ! + when )> do 0 ! + otherwise 1! + end getRowColumn + + sink setRowColumn + def p: $; + @queens.freeRows($p.r::raw): $p.val::raw; + @queens.freeMaxs($p.c::raw + $p.r::raw): $p.val::raw; + @queens.freeMins($p.c::raw - $p.r::raw + $n): $p.val::raw; + end setRowColumn + + data done <=1> + + templates placeQueen + def c: $; + row´1 -> # + when do 1! + when <=row´($n+1)> do 0 ! + when getRowColumn <=1>)> do + def r: $; + @queens.queenRows($r::raw): $c; + {r: $, c: $c, val: 0} -> !setRowColumn + $c -> \(<=col´$n> done´1! + placeQueen <=1>)> done´1! + <> + {r: $r, c: $c, val: 1} -> !setRowColumn + row´($r::raw + 1) !\) -> # + otherwise row´($::raw + 1) -> # + end placeQueen + + @: { freeRows: [1..$n -> 1], + freeMaxs: [1..$n*2 -> 1], + freeMins: [1..$n*2 -> 1], + queenRows: [1..$n -> -1] }; + col´1 -> placeQueen -> \(<=1> $@queens.queenRows ! <> 'non-existent'!\)! +end queens + +'A solution to the 8 queens problem is $:8 -> queens; +' -> !OUT::write +'A solution to the 4 queens problem is $:4 -> queens; +' -> !OUT::write +'A solution to the 3 queens problem is $:3 -> queens; +' -> !OUT::write diff --git a/Task/N-smooth-numbers/Crystal/n-smooth-numbers.crystal b/Task/N-smooth-numbers/Crystal/n-smooth-numbers.cr similarity index 100% rename from Task/N-smooth-numbers/Crystal/n-smooth-numbers.crystal rename to Task/N-smooth-numbers/Crystal/n-smooth-numbers.cr diff --git a/Task/N-smooth-numbers/Delphi/n-smooth-numbers.delphi b/Task/N-smooth-numbers/Delphi/n-smooth-numbers.pas similarity index 100% rename from Task/N-smooth-numbers/Delphi/n-smooth-numbers.delphi rename to Task/N-smooth-numbers/Delphi/n-smooth-numbers.pas diff --git a/Task/N-smooth-numbers/FreeBASIC/n-smooth-numbers.basic b/Task/N-smooth-numbers/FreeBASIC/n-smooth-numbers.basic new file mode 100644 index 0000000000..c1da9627d6 --- /dev/null +++ b/Task/N-smooth-numbers/FreeBASIC/n-smooth-numbers.basic @@ -0,0 +1,131 @@ +Dim Shared primes(9) As Uinteger = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + +Type BigNum + Dim Data(63) As Ubyte +End Type + +Function compareBigNum(a As BigNum, b As BigNum) As Integer + For i As Integer = 63 To 0 Step -1 + If a.data(i) > b.data(i) Then Return 1 + If a.data(i) < b.data(i) Then Return -1 + Next + Exit Function +End Function + +Sub multiplyBigNum(num As BigNum, factor As Uinteger) + Dim As Ulongint carry = 0 + For i As Integer = 0 To 63 + Dim As Ulongint product = Clngint(num.data(i)) * factor + carry + num.data(i) = product And 255 + carry = product Shr 8 + Next +End Sub + +Function NSmooth(n As Uinteger, size As Integer) As BigNum Ptr + Dim As Uinteger i, m, indicies(Ubound(primes)) + Dim As BigNum sgte(Ubound(primes)) + + If n < 2 Or n > 521 Then + Print "Argument 'n' out of range" + Exit Function + End If + If size < 1 Then + Print "Argument 'size' out of range" + Exit Function + End If + + Dim As Boolean ok = False + For i = 0 To Ubound(primes) + If n = primes(i) Then + ok = True + Exit For + End If + Next + If Not ok Then + For i = Ubound(primes) + 1 To 521 + If n = i Then + ok = True + Exit For + End If + Next + End If + If Not ok Then + Print "Must be a prime number: "; n + Exit Function + End If + + Dim As BigNum Ptr ns = Callocate(size, Sizeof(BigNum)) + ns[0].data(0) = 1 + + Dim As Uinteger sgteSize = 0 + For i = 0 To Ubound(primes) + If primes(i) > n Then Exit For + sgte(sgteSize).data(0) = primes(i) + sgteSize += 1 + Next + + For m = 1 To size - 1 + Dim As BigNum minValue = sgte(0) + For i = 0 To sgteSize - 1 + If compareBigNum(sgte(i), minValue) < 0 Then minValue = sgte(i) + Next + ns[m] = minValue + For i = 0 To sgteSize - 1 + If compareBigNum(ns[m], sgte(i)) = 0 Then + indicies(i) += 1 + sgte(i) = ns[indicies(i)] + multiplyBigNum(sgte(i), primes(i)) + End If + Next + Next + + Return ns +End Function + +Function BigNumToString(num As BigNum) As String + Dim As String result = "" + Dim As BigNum quotient, zeroNum, temp = num + Dim As Uinteger divisor = 10 + + Do + Dim As Uinteger remainder = 0 + For i As Integer = 63 To 0 Step -1 + Dim As Ulongint dividend = (Clngint(remainder) Shl 8) Or temp.data(i) + quotient.data(i) = dividend \ divisor + remainder = dividend Mod divisor + Next + result = Chr(remainder + 48) & result + temp = quotient + Loop While compareBigNum(temp, zeroNum) > 0 + + If Len(result) = 0 Then result = "0" + Return result +End Function + +' Main program +Dim As Uinteger i, j, p +Dim As BigNum Ptr ns + +For i = 0 To Ubound(primes) + p = primes(i) + Print !"\nThe first "; p; " -smooth numbers are:" + ns = NSmooth(p, 25) + For j = 0 To 24 + Print BigNumToString(ns[j]); " "; + Next + Print + Deallocate ns +Next + +For i = 1 To Ubound(primes) + p = primes(i) + Print !"\nThe 3000 to 3002 "; p; " -smooth numbers are:" + ns = NSmooth(p, 3002) + For j = 2999 To 3001 + Print BigNumToString(ns[j]); " "; + Next + Print + Deallocate ns +Next + +Sleep diff --git a/Task/N-smooth-numbers/Julia/n-smooth-numbers.julia b/Task/N-smooth-numbers/Julia/n-smooth-numbers.jl similarity index 100% rename from Task/N-smooth-numbers/Julia/n-smooth-numbers.julia rename to Task/N-smooth-numbers/Julia/n-smooth-numbers.jl diff --git a/Task/N-smooth-numbers/Kotlin/n-smooth-numbers.kotlin b/Task/N-smooth-numbers/Kotlin/n-smooth-numbers.kts similarity index 100% rename from Task/N-smooth-numbers/Kotlin/n-smooth-numbers.kotlin rename to Task/N-smooth-numbers/Kotlin/n-smooth-numbers.kts diff --git a/Task/N-smooth-numbers/Rust/n-smooth-numbers.rust b/Task/N-smooth-numbers/Rust/n-smooth-numbers.rs similarity index 100% rename from Task/N-smooth-numbers/Rust/n-smooth-numbers.rust rename to Task/N-smooth-numbers/Rust/n-smooth-numbers.rs diff --git a/Task/Named-parameters/Delphi/named-parameters.delphi b/Task/Named-parameters/Delphi/named-parameters.pas similarity index 100% rename from Task/Named-parameters/Delphi/named-parameters.delphi rename to Task/Named-parameters/Delphi/named-parameters.pas diff --git a/Task/Named-parameters/Elixir/named-parameters.elixir b/Task/Named-parameters/Elixir/named-parameters.ex similarity index 100% rename from Task/Named-parameters/Elixir/named-parameters.elixir rename to Task/Named-parameters/Elixir/named-parameters.ex diff --git a/Task/Named-parameters/Julia/named-parameters.julia b/Task/Named-parameters/Julia/named-parameters.jl similarity index 100% rename from Task/Named-parameters/Julia/named-parameters.julia rename to Task/Named-parameters/Julia/named-parameters.jl diff --git a/Task/Named-parameters/Kotlin/named-parameters.kotlin b/Task/Named-parameters/Kotlin/named-parameters.kts similarity index 100% rename from Task/Named-parameters/Kotlin/named-parameters.kotlin rename to Task/Named-parameters/Kotlin/named-parameters.kts diff --git a/Task/Named-parameters/OCaml/named-parameters.ocaml b/Task/Named-parameters/OCaml/named-parameters.ml similarity index 100% rename from Task/Named-parameters/OCaml/named-parameters.ocaml rename to Task/Named-parameters/OCaml/named-parameters.ml diff --git a/Task/Named-parameters/Scheme/named-parameters-1.ss b/Task/Named-parameters/Scheme/named-parameters-1.scm similarity index 100% rename from Task/Named-parameters/Scheme/named-parameters-1.ss rename to Task/Named-parameters/Scheme/named-parameters-1.scm diff --git a/Task/Named-parameters/Scheme/named-parameters-2.ss b/Task/Named-parameters/Scheme/named-parameters-2.scm similarity index 100% rename from Task/Named-parameters/Scheme/named-parameters-2.ss rename to Task/Named-parameters/Scheme/named-parameters-2.scm diff --git a/Task/Naming-conventions/Kotlin/naming-conventions.kotlin b/Task/Naming-conventions/Kotlin/naming-conventions.kts similarity index 100% rename from Task/Naming-conventions/Kotlin/naming-conventions.kotlin rename to Task/Naming-conventions/Kotlin/naming-conventions.kts diff --git a/Task/Naming-conventions/PascalABC.NET/naming-conventions.pas b/Task/Naming-conventions/PascalABC.NET/naming-conventions.pas new file mode 100644 index 0000000000..d86144aef8 --- /dev/null +++ b/Task/Naming-conventions/PascalABC.NET/naming-conventions.pas @@ -0,0 +1 @@ +Dictionary diff --git a/Task/Narcissist/Julia/narcissist.julia b/Task/Narcissist/Julia/narcissist.jl similarity index 100% rename from Task/Narcissist/Julia/narcissist.julia rename to Task/Narcissist/Julia/narcissist.jl diff --git a/Task/Narcissist/Kotlin/narcissist.kotlin b/Task/Narcissist/Kotlin/narcissist.kts similarity index 100% rename from Task/Narcissist/Kotlin/narcissist.kotlin rename to Task/Narcissist/Kotlin/narcissist.kts diff --git a/Task/Narcissist/Rust/narcissist.rust b/Task/Narcissist/Rust/narcissist.rs similarity index 100% rename from Task/Narcissist/Rust/narcissist.rust rename to Task/Narcissist/Rust/narcissist.rs diff --git a/Task/Narcissistic-decimal-number/Delphi/narcissistic-decimal-number.delphi b/Task/Narcissistic-decimal-number/Delphi/narcissistic-decimal-number.pas similarity index 100% rename from Task/Narcissistic-decimal-number/Delphi/narcissistic-decimal-number.delphi rename to Task/Narcissistic-decimal-number/Delphi/narcissistic-decimal-number.pas diff --git a/Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.elixir b/Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.ex similarity index 100% rename from Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.elixir rename to Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.ex diff --git a/Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.julia b/Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.jl similarity index 100% rename from Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.julia rename to Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.jl diff --git a/Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kotlin b/Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kts similarity index 100% rename from Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kotlin rename to Task/Narcissistic-decimal-number/Kotlin/narcissistic-decimal-number.kts diff --git a/Task/Narcissistic-decimal-number/OCaml/narcissistic-decimal-number.ocaml b/Task/Narcissistic-decimal-number/OCaml/narcissistic-decimal-number.ml similarity index 100% rename from Task/Narcissistic-decimal-number/OCaml/narcissistic-decimal-number.ocaml rename to Task/Narcissistic-decimal-number/OCaml/narcissistic-decimal-number.ml diff --git a/Task/Narcissistic-decimal-number/Refal/narcissistic-decimal-number.refal b/Task/Narcissistic-decimal-number/Refal/narcissistic-decimal-number.refal new file mode 100644 index 0000000000..5a49c62b7a --- /dev/null +++ b/Task/Narcissistic-decimal-number/Refal/narcissistic-decimal-number.refal @@ -0,0 +1,38 @@ +$ENTRY Go { + = >; +}; + +Gen { + s.N s.F = ; + 0 s.F s.C = ; + s.N s.F s.C, : { + True = s.C s.F <+ 1 s.C>>; + False = >; + }; +}; + +Narcissist { + s.N, : e.D, + : s.P e.D, + >: s.N = True; + s.N = False; +}; + +Digits { + s.N = >; +}; + +Each { + (e.F) = ; + (e.F) t.I e.X = ; +}; + +Pow { + 0 s.N = 1; + s.P s.N = s.N>>; +}; + +Sum { + = 0; + s.N e.X = <+ s.N >; +}; diff --git a/Task/Narcissistic-decimal-number/Rust/narcissistic-decimal-number.rust b/Task/Narcissistic-decimal-number/Rust/narcissistic-decimal-number.rs similarity index 100% rename from Task/Narcissistic-decimal-number/Rust/narcissistic-decimal-number.rust rename to Task/Narcissistic-decimal-number/Rust/narcissistic-decimal-number.rs diff --git a/Task/Natural-sorting/C++/natural-sorting.cpp b/Task/Natural-sorting/C++/natural-sorting.cpp new file mode 100644 index 0000000000..9bcd14ad59 --- /dev/null +++ b/Task/Natural-sorting/C++/natural-sorting.cpp @@ -0,0 +1,237 @@ +#include +#include +#include +#include +#include +#include + +// Only covers ISO-8859-1 accented characters plus, for consistency, Ÿ +const std::vector uc_accents = + { "ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ" }; +const std::vector lc_accents = + { "àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ" }; +const std::vector uc_unaccents = { "A", "C", "E", "I", "N", "O", "U", "Y" }; +const std::vector lc_unaccents = { "a", "c", "e", "i", "n", "o", "u", "y" }; + +// Only the more common ligatures +const std::vector uc_ligatures = { "Æ", "IJ", "Œ" }; +const std::vector lc_ligatures = { "æ", "ij", "œ" }; +const std::vector uc_separates = { "AE", "IJ", "OE" }; +const std::vector lc_separates = { "ae", "ij", "oe" }; + +// Miscellaneous replacements +const std::vector misc_letters = { "ß", "ſ", "ʒ" }; +const std::vector misc_replacements = { "ss", "s", "s" }; + +// Remove leading spaces +std::string left_trim(const std::string& text) { + const uint64_t start = text.find_first_not_of(" \n\r\t\f\v"); + return ( start == std::string::npos ) ? "" : text.substr(start); +} + +// Replace multiple spaces with a single space +std::string replace_spaces(std::string text) { + static const std::regex regex_expr("[ ]{2,}"); + text = std::regex_replace(text, regex_expr, " "); + return text; +} + +// Replace whitespace with a single space +std::string replace_whitespace(std::string text) { + static const std::regex regex_expr("\\s+"); + text = std::regex_replace(text, regex_expr, " "); + return text; +} + +// Display strings including whitespace as if the latter were literal characters +std::string to_display_string(std::string text) { + const std::vector whitespace_1 = { "\t", "\n", "\u000b", "\u000c", "\r" }; + const std::vector whitespace_2 = { "\\t", "\\n", "\\u000b", "\\u000c", "\\r" }; + for ( uint64_t i = 0; i < whitespace_1.size(); ++i ) { + std::regex regex_expr(whitespace_1[i]); + text = std::regex_replace(text, regex_expr, whitespace_2[i]); + } + return text; +} + +// Transform the string into lower case +std::string to_lower_case(std::string text) { + std::transform(text.begin(), text.end(), text.begin(), + [](char ch) { return std::tolower(ch); }); + return text; +} + +// Pad each numeric character with leading zeros to a total length of 20 +std::string zero_padding(std::string text) { + const static std::regex digits("-?\\d+"); + const std::vector matches{ + std::sregex_token_iterator{text.begin(), text.end(), digits, 0}, std::sregex_token_iterator{} }; + + std::vector indexes = { }; + for ( const std::string& match : matches ) { + indexes.emplace_back(text.find(match)); + } + + uint32_t extra_index = 0; + for ( uint64_t i = 0; i < matches.size(); ++i ) { + uint64_t start_pos = text.find(matches[i], indexes[i] + extra_index); + text = text.substr(0, start_pos) + std::string(20 - matches[i].size(), '0') + text.substr(start_pos); + extra_index += 20 - matches[i].size(); + } + return text; +} + +std::string remove_title(std::string text) { + return std::regex_replace(text, std::regex("^The\\s+|^An\\s+|^A\\s+"), ""); +} + +// Replace accented letters with their unaccented equivalent +std::string replace_accents(const std::string& text) { + std::string result = ""; + for ( uint64_t i = 0; i < text.length(); ++i ) { + if ( ( text[i] & 0xff ) < 128 ) { + result += text.substr(i, 1); + continue; + } + const uint64_t length = result.length(); + const std::string letter = text.substr(i, 2); + + for ( uint64_t j = 0; j < uc_accents.size(); ++j ) { + if ( uc_accents[j].find(letter) != std::string::npos ) { + result += uc_unaccents[j]; + break; + } + } + + if ( length == result.length() ) { + for ( uint64_t j = 0; j < lc_accents.size(); ++j ) { + if ( lc_accents[j].find(letter) != std::string::npos ) { + result += lc_unaccents[j]; + break; + } + } + } + } + return result; +} + +// Replace ligatures with separated letters +std::string replace_ligatures(std::string text) { + for ( uint64_t i = 0; i < uc_ligatures.size(); ++i ) { + text = std::regex_replace(text, std::regex(uc_ligatures[i]), uc_separates[i]); + } + for ( uint64_t i = 0; i < lc_ligatures.size(); ++i ) { + text = std::regex_replace(text, std::regex(lc_ligatures[i]), lc_separates[i]); + } + return text; +} + +// Replace miscellaneous letters with their equivalent replacements +std::string replace_characters(std::string text) { + for ( uint64_t i = 0; i < misc_letters.size(); ++i ) { + text = std::regex_replace(text, std::regex(misc_letters[i]), misc_replacements[i]); + } + return text; +} + +int main() { + std::cout << "The 9 string lists, sorted 'naturally':" << "\n"; + std::vector s1 = { + "ignore leading spaces: 2-2", + " ignore leading spaces: 2-1", + " ignore leading spaces: 2+0", + " ignore leading spaces: 2+1" + }; + std::cout << "\n";; + std::sort(s1.begin(), s1.end(), + [](std::string lhs, std::string rhs) { return left_trim(lhs) < left_trim(rhs); }); + for ( const std::string& s : s1 ) { std::cout << s << "\n"; } + + std::vector s2 = { + "ignore m.a.s spaces: 2-2", + "ignore m.a.s spaces: 2-1", + "ignore m.a.s spaces: 2+0", + "ignore m.a.s spaces: 2+1" + }; + std::cout << "\n";; + std::sort(s2.begin(), s2.end(), + [](std::string lhs, std::string rhs) { return replace_spaces(lhs) < replace_spaces(rhs); }); + for ( const std::string& s : s2 ) { std::cout << s << "\n"; } + + std::vector s3 = { + "Equiv. spaces: 3-3", + "Equiv.\rspaces: 3-2", + "Equiv.\u000cspaces: 3-1", + "Equiv.\u000bspaces: 3+0", + "Equiv.\nspaces: 3+1", + "Equiv.\tspaces: 3+2" + }; + std::cout << "\n";; + std::sort(s3.begin(), s3.end(), + [](std::string lhs, std::string rhs) { return replace_whitespace(lhs) < replace_whitespace(rhs); }); + for ( const std::string& s : s3 ) { std::cout << to_display_string(s) << "\n"; } + + std::vector s4 = { + "cASE INDEPENENT: 3-2", + "caSE INDEPENENT: 3-1", + "casE INDEPENENT: 3+0", + "case INDEPENENT: 3+1" + }; + std::cout << "\n";; + std::sort(s4.begin(), s4.end(), + [](std::string lhs, std::string rhs) { return to_lower_case(lhs) < to_lower_case(rhs); }); + for ( const std::string& s : s4 ) { std::cout << s << "\n"; } + + std::vector s5 = { + "foo100bar99baz0.txt", + "foo100bar10baz0.txt", + "foo1000bar99baz10.txt", + "foo1000bar99baz9.txt" + }; + std::cout << "\n";; + std::sort(s5.begin(), s5.end(), + [](std::string lhs, std::string rhs) { return zero_padding(lhs) < zero_padding(rhs); }); + for ( const std::string& s : s5 ) { std::cout << s << "\n"; } + + std::vector s6 = { + "The Wind in the Willows", + "The 40th step more", + "The 39 steps", + "Wanda" + }; + std::cout << "\n";; + std::sort(s6.begin(), s6.end(), + [](std::string lhs, std::string rhs) { return remove_title(lhs) < remove_title(rhs); }); + for ( const std::string& s : s6 ) { std::cout << s << "\n"; } + + std::vector s7 = { + "Equiv. ý accents: 2-2", + "Equiv. Ý accents: 2-1", + "Equiv. y accents: 2+0", + "Equiv. Y accents: 2+1" + }; + std::cout << "\n";; + std::sort(s7.begin(), s7.end(), + [](std::string lhs, std::string rhs) { return replace_accents(lhs) < replace_accents(rhs); }); + for ( const std::string& s : s7 ) { std::cout << s << "\n"; } + + std::vector s8 = { + "IJ ligatured ij", + "no ligature" + }; + std::cout << "\n";; + std::sort(s8.begin(), s8.end(), + [](std::string lhs, std::string rhs) { return replace_ligatures(lhs) < replace_ligatures(rhs); }); + for ( const std::string& s : s8 ) { std::cout << s << "\n"; } + + std::vector s9 = { + "Start with an ʒ: 2-2", + "Start with an ſ: 2-1", + "Start with an ß: 2+0", + "Start with an s: 2+1" + }; + std::cout << "\n";; + std::sort(s9.begin(), s9.end(), + [](std::string lhs, std::string rhs) { return replace_characters(lhs) < replace_characters(rhs); }); + for ( const std::string& s : s9 ) { std::cout << s << "\n"; } +} diff --git a/Task/Natural-sorting/Elixir/natural-sorting.elixir b/Task/Natural-sorting/Elixir/natural-sorting.ex similarity index 100% rename from Task/Natural-sorting/Elixir/natural-sorting.elixir rename to Task/Natural-sorting/Elixir/natural-sorting.ex diff --git a/Task/Natural-sorting/Java/natural-sorting.java b/Task/Natural-sorting/Java/natural-sorting.java new file mode 100644 index 0000000000..5a167d7370 --- /dev/null +++ b/Task/Natural-sorting/Java/natural-sorting.java @@ -0,0 +1,227 @@ +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public final class NaturalSorting { + + public static void main(String[] args) { + System.out.println("The 9 string lists, sorted 'naturally':"); + List s1 = Arrays.asList( + "ignore leading spaces: 2-2", + " ignore leading spaces: 2-1", + " ignore leading spaces: 2+0", + " ignore leading spaces: 2+1" + ); + System.out.println(); + s1.sort(comparator1); + s1.forEach(System.out::println); + + List s2 = Arrays.asList( + "ignore m.a.s spaces: 2-2", + "ignore m.a.s spaces: 2-1", + "ignore m.a.s spaces: 2+0", + "ignore m.a.s spaces: 2+1" + ); + System.out.println(); + s2.sort(comparator2); + s2.forEach(System.out::println); + + List s3 = Arrays.asList( + "Equiv. spaces: 3-3", + "Equiv.\rspaces: 3-2", + "Equiv.\u000cspaces: 3-1", + "Equiv.\u000bspaces: 3+0", + "Equiv.\nspaces: 3+1", + "Equiv.\tspaces: 3+2" + ); + System.out.println(); + s3.sort(comparator3); + s3.forEach( s -> System.out.println(toDisplayString(s) )); + + List s4 = Arrays.asList( + "cASE INDEPENENT: 3-2", + "caSE INDEPENENT: 3-1", + "casE INDEPENENT: 3+0", + "case INDEPENENT: 3+1" + ); + System.out.println(); + s4.sort(comparator4); + s4.forEach(System.out::println); + + List s5 = Arrays.asList( + "foo100bar99baz0.txt", + "foo100bar10baz0.txt", + "foo1000bar99baz10.txt", + "foo1000bar99baz9.txt" + ); + System.out.println(); + s5.sort(comparator5); + s5.forEach(System.out::println); + + List s6 = Arrays.asList( + "The Wind in the Willows", + "The 40th step more", + "The 39 steps", + "Wanda" + ); + System.out.println(); + s6.sort(comparator6); + s6.forEach(System.out::println); + + List s7 = Arrays.asList( + "Equiv. ý accents: 2-2", + "Equiv. Ý accents: 2-1", + "Equiv. y accents: 2+0", + "Equiv. Y accents: 2+1" + ); + System.out.println(); + s7.sort(comparator7); + s7.forEach(System.out::println); + + List s8 = Arrays.asList( + "IJ ligatured ij", + "no ligature" + ); + System.out.println(); + s8.sort(comparator8); + s8.forEach(System.out::println); + + List s9 = Arrays.asList( + "Start with an ʒ: 2-2", + "Start with an ſ: 2-1", + "Start with an ß: 2+0", + "Start with an s: 2+1" + ); + System.out.println(); + s9.sort(comparator9); + s9.forEach(System.out::println); + } + + /** Ignoring leading space(s) */ + private static Comparator comparator1 = Comparator.comparing(String::stripLeading); + + /** Ignoring multiple adjacent spaces, that is, condensing to a single space */ + private static Comparator comparator2 = + (s1, s2) -> s1.replaceAll("[ ]{2,}", " ").compareTo(s2.replaceAll("[ ]{2,}", " ")); + + /** Equivalent whitespace characters (all equivalent to a single space) */ + private static Comparator comparator3 = + (s1, s2) -> s1.replaceAll("\\s+", " ").compareTo(s2.replaceAll("\\s+", " ")); + + /** Case independent sort */ + private static Comparator comparator4 = Comparator.comparing(String::toLowerCase); + + /** Numeric fields as numerics (deals with numbers up to 20 digits) */ + private static Comparator comparator5 = Comparator.comparing(NaturalSorting::zeroPadding); + + /** Title sort */ + private static Comparator comparator6 = (s1, s2) -> + s1.replaceFirst("^The\s+|^An\s+|^A\s+", "").compareTo(s2.replaceFirst("^The\s+|^An\s+|^A\s+", "")); + + /** Equivalent accented characters */ + private static Comparator comparator7 = Comparator.comparing(NaturalSorting::replaceAccents); + + /** Separated ligatures */ + private static Comparator comparator8 = Comparator.comparing(NaturalSorting::replaceLigatures); + + /** Character replacements */ + private static Comparator comparator9 = Comparator.comparing(NaturalSorting::replaceCharacters); + + /** Display strings including whitespace as if the latter were literal characters */ + private static String toDisplayString(String text) { + List whitespace1 = List.of( "\t", "\n", "\u000b", "\u000c", "\r" ); + List whitespace2 = List.of( "\\t", "\\n", "\\u000b", "\\u000c", "\\r" ); + for ( int i = 0; i < whitespace1.size(); i++ ) { + text = text.replace(whitespace1.get(i), whitespace2.get(i)); + } + return text; + } + + /** Pad each numeric character with leading zeros to a total length of 20 */ + private static String zeroPadding(String text) { + Pattern pattern = Pattern.compile("-?\\d+"); + Matcher matcher = pattern.matcher(text); + StringBuilder result = new StringBuilder(); + int index = 0; + + while ( matcher.find() ) { + result.append(text.substring(index, matcher.start())); + result.append("0".repeat(20 - ( matcher.end() - matcher.start() ))); + result.append(text.substring(matcher.start(), matcher.end())); + index = matcher.end(); + } + result.append(text.substring(index)); + + return result.toString(); + } + + /** Replace accented letters with their unaccented equivalent */ + private static String replaceAccents(String text) { + StringBuilder stringBuilder = new StringBuilder(); + for ( int i = 0; i < text.length(); i++ ) { + final String letter = text.substring(i, i + 1); + if ( ( text.charAt(i) & 0xff ) < 128 ) { + stringBuilder.append(letter); + continue; + } + final int length = stringBuilder.length(); + + for ( int j = 0; j < ucAccents.size(); j++ ) { + if ( ucAccents.get(j).contains(letter) ) { + stringBuilder.append(ucUnaccents.get(j)); + break; + } + } + + if ( length == stringBuilder.length() ) { + for ( int j = 0; j < lcAccents.size(); j++ ) { + if ( lcAccents.get(j).contains(letter) ) { + stringBuilder.append(lcUnaccents.get(j)); + break; + } + } + } + } + return stringBuilder.toString(); + } + + /** Replace ligatures with separated letters */ + private static String replaceLigatures(String text) { + for ( int i = 0; i < ucLigatures.size(); i++ ) { + text = text.replace(ucLigatures.get(i), ucSeparates.get(i)); + } + for ( int i = 0; i < lcLigatures.size(); i++ ) { + text = text.replace(lcLigatures.get(i), lcSeparates.get(i)); + } + return text; + } + + /** Replace miscellaneous letters with their equivalent replacements */ + private static String replaceCharacters(String text) { + for ( int i = 0; i < miscLetters.size(); i++ ) { + text = text.replace(miscLetters.get(i), miscReplacements.get(i)); + } + return text; + } + + /** Only covers ISO-8859-1 accented characters plus, for consistency, Ÿ */ + private static final List ucAccents = + List.of( "ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ" ); + private static final List lcAccents = + List.of( "àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ" ); + private static final List ucUnaccents = List.of( "A", "C", "E", "I", "N", "O", "U", "Y" ); + private static final List lcUnaccents = List.of( "a", "c", "e", "i", "n", "o", "u", "y" ); + + /** Only the more common ligatures */ + private static final List ucLigatures = List.of( "Æ", "IJ", "Œ" ); + private static final List lcLigatures = List.of( "æ", "ij", "œ" ); + private static final List ucSeparates = List.of( "AE", "IJ", "OE" ); + private static final List lcSeparates = List.of( "ae", "ij", "oe" ); + + /** Miscellaneous replacements */ + private static final List miscLetters = List.of( "ß", "ſ", "ʒ" ); + private static final List miscReplacements = List.of( "ss", "s", "s" ); + +} diff --git a/Task/Natural-sorting/Julia/natural-sorting.julia b/Task/Natural-sorting/Julia/natural-sorting.jl similarity index 100% rename from Task/Natural-sorting/Julia/natural-sorting.julia rename to Task/Natural-sorting/Julia/natural-sorting.jl diff --git a/Task/Natural-sorting/Kotlin/natural-sorting.kotlin b/Task/Natural-sorting/Kotlin/natural-sorting.kts similarity index 100% rename from Task/Natural-sorting/Kotlin/natural-sorting.kotlin rename to Task/Natural-sorting/Kotlin/natural-sorting.kts diff --git a/Task/Natural-sorting/Scheme/natural-sorting.ss b/Task/Natural-sorting/Scheme/natural-sorting.scm similarity index 100% rename from Task/Natural-sorting/Scheme/natural-sorting.ss rename to Task/Natural-sorting/Scheme/natural-sorting.scm diff --git a/Task/Nautical-bell/Julia/nautical-bell.julia b/Task/Nautical-bell/Julia/nautical-bell.jl similarity index 100% rename from Task/Nautical-bell/Julia/nautical-bell.julia rename to Task/Nautical-bell/Julia/nautical-bell.jl diff --git a/Task/Nautical-bell/Kotlin/nautical-bell.kotlin b/Task/Nautical-bell/Kotlin/nautical-bell.kts similarity index 100% rename from Task/Nautical-bell/Kotlin/nautical-bell.kotlin rename to Task/Nautical-bell/Kotlin/nautical-bell.kts diff --git a/Task/Negative-base-numbers/ALGOL-68/negative-base-numbers.alg b/Task/Negative-base-numbers/ALGOL-68/negative-base-numbers.alg index 82b51d2341..3265127f29 100644 --- a/Task/Negative-base-numbers/ALGOL-68/negative-base-numbers.alg +++ b/Task/Negative-base-numbers/ALGOL-68/negative-base-numbers.alg @@ -27,27 +27,28 @@ OP FROMNBASE = ( STRING s, INT b )LONG INT: OD; result END # FROMNBASE # ; + OP FROMNBASE = ( CHAR c, INT b )LONG INT: STRING(c) FROMNBASE b; # returns n encoded as a string in the negative base b # PRIO TONBASE = 9; OP TONBASE = ( LONG INT n, INT b )STRING: - BEGIN - STRING result := ""; - LONG INT v := n; - WHILE - INT d := SHORTEN IF v < 0 THEN - ( ABS v MOD b ) ELSE v MOD b FI; - v OVERAB b; - IF d < 0 - THEN - d -:= b; - v +:= 1 - FI; - base digits[ d ] +=: result; - v /= 0 - DO SKIP OD; - result - END # TONBASE # ; + IF n = 0 + THEN "0" + ELSE STRING result := ""; + LONG INT v := n; + WHILE ABS v /= 0 DO + INT d := SHORTEN IF v < 0 THEN - ( ABS v MOD b ) ELSE v MOD b FI; + v OVERAB b; + IF d < 0 + THEN + d -:= b; + v +:= 1 + FI; + base digits[ d ] +=: result + OD; + result + FI # TONBASE # ; # tests the TONBASE and FROMNBASE operators # PROC test n base = ( LONG INT number, INT base, STRING expected )VOID: @@ -66,4 +67,6 @@ test n base( 146, -3, "21102" ); test n base( 15, -10, "195" ); # The defining document for ALGOL 68 spells the name "Algol 68" on the cover, though inside it is "ALGOL 68" # # at the risk of "judging a language by it's cover", we use "Algol 68" as the name here... # -test n base( - LONG 36492107981104, -63, "Algol 68" ) +test n base( - LONG 36492107981104, -63, "Algol 68" ); +# test the single character decode operator # +print( ( "1 decodes to ", whole( "1" FROMNBASE -2, 0 ), " in base -2", newline ) ) diff --git a/Task/Negative-base-numbers/Julia/negative-base-numbers.julia b/Task/Negative-base-numbers/Julia/negative-base-numbers.jl similarity index 100% rename from Task/Negative-base-numbers/Julia/negative-base-numbers.julia rename to Task/Negative-base-numbers/Julia/negative-base-numbers.jl diff --git a/Task/Negative-base-numbers/Kotlin/negative-base-numbers.kotlin b/Task/Negative-base-numbers/Kotlin/negative-base-numbers.kts similarity index 100% rename from Task/Negative-base-numbers/Kotlin/negative-base-numbers.kotlin rename to Task/Negative-base-numbers/Kotlin/negative-base-numbers.kts diff --git a/Task/Negative-base-numbers/Rust/negative-base-numbers.rust b/Task/Negative-base-numbers/Rust/negative-base-numbers.rs similarity index 100% rename from Task/Negative-base-numbers/Rust/negative-base-numbers.rust rename to Task/Negative-base-numbers/Rust/negative-base-numbers.rs diff --git a/Task/Nested-function/Elixir/nested-function.elixir b/Task/Nested-function/Elixir/nested-function.ex similarity index 100% rename from Task/Nested-function/Elixir/nested-function.elixir rename to Task/Nested-function/Elixir/nested-function.ex diff --git a/Task/Nested-function/Julia/nested-function.julia b/Task/Nested-function/Julia/nested-function.jl similarity index 100% rename from Task/Nested-function/Julia/nested-function.julia rename to Task/Nested-function/Julia/nested-function.jl diff --git a/Task/Nested-function/Kotlin/nested-function.kotlin b/Task/Nested-function/Kotlin/nested-function.kts similarity index 100% rename from Task/Nested-function/Kotlin/nested-function.kotlin rename to Task/Nested-function/Kotlin/nested-function.kts diff --git a/Task/Nested-function/OCaml/nested-function.ocaml b/Task/Nested-function/OCaml/nested-function.ml similarity index 100% rename from Task/Nested-function/OCaml/nested-function.ocaml rename to Task/Nested-function/OCaml/nested-function.ml diff --git a/Task/Nested-function/Rust/nested-function.rust b/Task/Nested-function/Rust/nested-function.rs similarity index 100% rename from Task/Nested-function/Rust/nested-function.rust rename to Task/Nested-function/Rust/nested-function.rs diff --git a/Task/Nested-function/Scheme/nested-function.ss b/Task/Nested-function/Scheme/nested-function.scm similarity index 100% rename from Task/Nested-function/Scheme/nested-function.ss rename to Task/Nested-function/Scheme/nested-function.scm diff --git a/Task/Nested-templated-data/Crystal/nested-templated-data.crystal b/Task/Nested-templated-data/Crystal/nested-templated-data.cr similarity index 100% rename from Task/Nested-templated-data/Crystal/nested-templated-data.crystal rename to Task/Nested-templated-data/Crystal/nested-templated-data.cr diff --git a/Task/Nested-templated-data/Java/nested-templated-data.java b/Task/Nested-templated-data/Java/nested-templated-data.java new file mode 100644 index 0000000000..1faffcf531 --- /dev/null +++ b/Task/Nested-templated-data/Java/nested-templated-data.java @@ -0,0 +1,61 @@ +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.IntStream; + +public final class NestedTemplateData { + + public static void main(String[] args) { + List payloads = IntStream.rangeClosed(0, 6).mapToObj( i -> "Payload#" + i ).toList(); + String template = "[1, [[[1, 6]], [[3, 4, [17], 0], 5], 3], 9, [888], 9]"; + + System.out.println("Level Element"); + processPayloads(template, payloads); + } + + private static void processPayloads(String template, List payloads) { + Set unusedPayloads = new TreeSet(payloads); + Set missingPayloads = new TreeSet(); + int level = 0; + boolean levelChanged = false; + + for ( int i = 0; i < template.length(); i++ ) { + String item = template.substring(i, i + 1); + switch ( item ) { + case "[" -> { level += 1; levelChanged = true; } + case "]" -> { level -= 1; levelChanged = true; } + default -> { + if ( isDigit(item) ) { + while ( isDigit(template.substring(i + 1, i + 2)) ) { + item += template.substring(i + 1, i + 2); + i += 1; + } + if ( levelChanged ) { + System.out.println(); + System.out.print(String.format("%2s%s", level, " ".repeat(level))); + levelChanged = false; + } + String payload = "Payload#" + item; + if ( payloads.contains(payload) ) { + unusedPayloads.remove(payload); + } else { + missingPayloads.add(payload); + payload += " UNDEFINED"; + } + System.out.print(payload + " "); + } + } + } + } + + System.out.println(System.lineSeparator()); + System.out.println(" Unused payloads: " + unusedPayloads); + System.out.println(); + System.out.println(" Missing payloads: " + missingPayloads); + } + + private static boolean isDigit(String item) { + return item.compareTo("0") >= 0 && item.compareTo("9") <= 0; + } + +} diff --git a/Task/Nested-templated-data/Julia/nested-templated-data.julia b/Task/Nested-templated-data/Julia/nested-templated-data.jl similarity index 100% rename from Task/Nested-templated-data/Julia/nested-templated-data.julia rename to Task/Nested-templated-data/Julia/nested-templated-data.jl diff --git a/Task/Next-highest-int-from-digits/Delphi/next-highest-int-from-digits.delphi b/Task/Next-highest-int-from-digits/Delphi/next-highest-int-from-digits.pas similarity index 100% rename from Task/Next-highest-int-from-digits/Delphi/next-highest-int-from-digits.delphi rename to Task/Next-highest-int-from-digits/Delphi/next-highest-int-from-digits.pas diff --git a/Task/Next-highest-int-from-digits/Julia/next-highest-int-from-digits.julia b/Task/Next-highest-int-from-digits/Julia/next-highest-int-from-digits.jl similarity index 100% rename from Task/Next-highest-int-from-digits/Julia/next-highest-int-from-digits.julia rename to Task/Next-highest-int-from-digits/Julia/next-highest-int-from-digits.jl diff --git a/Task/Next-highest-int-from-digits/Kotlin/next-highest-int-from-digits.kotlin b/Task/Next-highest-int-from-digits/Kotlin/next-highest-int-from-digits.kts similarity index 100% rename from Task/Next-highest-int-from-digits/Kotlin/next-highest-int-from-digits.kotlin rename to Task/Next-highest-int-from-digits/Kotlin/next-highest-int-from-digits.kts diff --git a/Task/Next-highest-int-from-digits/Rust/next-highest-int-from-digits.rust b/Task/Next-highest-int-from-digits/Rust/next-highest-int-from-digits.rs similarity index 100% rename from Task/Next-highest-int-from-digits/Rust/next-highest-int-from-digits.rust rename to Task/Next-highest-int-from-digits/Rust/next-highest-int-from-digits.rs diff --git a/Task/Nim-game/Crystal/nim-game.crystal b/Task/Nim-game/Crystal/nim-game.cr similarity index 100% rename from Task/Nim-game/Crystal/nim-game.crystal rename to Task/Nim-game/Crystal/nim-game.cr diff --git a/Task/Nim-game/Julia/nim-game.julia b/Task/Nim-game/Julia/nim-game.jl similarity index 100% rename from Task/Nim-game/Julia/nim-game.julia rename to Task/Nim-game/Julia/nim-game.jl diff --git a/Task/Nim-game/Kotlin/nim-game.kotlin b/Task/Nim-game/Kotlin/nim-game.kts similarity index 100% rename from Task/Nim-game/Kotlin/nim-game.kotlin rename to Task/Nim-game/Kotlin/nim-game.kts diff --git a/Task/Nim-game/OCaml/nim-game.ocaml b/Task/Nim-game/OCaml/nim-game.ml similarity index 100% rename from Task/Nim-game/OCaml/nim-game.ocaml rename to Task/Nim-game/OCaml/nim-game.ml diff --git a/Task/Nim-game/Rust/nim-game.rust b/Task/Nim-game/Rust/nim-game.rs similarity index 100% rename from Task/Nim-game/Rust/nim-game.rust rename to Task/Nim-game/Rust/nim-game.rs diff --git a/Task/Nim-game/Waduzitdo/nim-game.waduzitdo b/Task/Nim-game/Waduzitdo/nim-game.waduzitdo new file mode 100644 index 0000000000..d5c22710e7 --- /dev/null +++ b/Task/Nim-game/Waduzitdo/nim-game.waduzitdo @@ -0,0 +1,52 @@ +T:LET'S PLAY NIM WITH 7 PEBBLES. +T:WE TAKE TURNS TAKING 1,2 OR 3. +T:THE LAST ONE TO TAKE ONE LOSES. +T:THERE ARE 7, HOW MANY ? +A: +M:1 +YJ:1 +M:2 +YJ:2 +M:3 +YJ:6 +T:YOU CAN TAKE ONLY 1,2, OR 3. +J:0 +*T:THAT LEAVES 6, I TAKE 1 LEAVING 5. +T:HOW MANY ? +A: +M:1 +YJ:5 +M:2 +YJ:4 +M:3 +YJ:3 +T:YOU MUST TAKE 1,2 OR 3. +J:0 +*T:THAT LEAVES 5, I TAKE 1 LEAVING 4. +T:HOW MANY ? +A: +M:1 +YJ:3 +M:2 +YJ:2 +M:3 +YJ:1 +T:YOU MUST TAKE 1,2 OR 3 ONLY. +J:0 +*T:THAT LEAVES THE LAST ONE. +T:I TAKE IT ... YOU WIN! +J:5 +*T:THAT LEAVES 2, I TAKE 1 LEAVING 1. +J:3 +*T:THAT LEAVES 3, I TAKE 2 LEAVING 1. +J:2 +*T:THAT LEAVES 4, I TAKE 3 LEAVING 1. +*T:HOW MANY ? +A: +M:1 +NT:YOU HAVE NO CHOICE BUT TO TAKE 1. +NT:HOW MANY ? +NJ:0 +T:YOU JUST TOOK THE LAST ONE ... I WIN. +*T:TO PLAY AGAIN TYPE THE DOLLAR SIGN. +S: diff --git a/Task/Non-continuous-subsequences/Elixir/non-continuous-subsequences.elixir b/Task/Non-continuous-subsequences/Elixir/non-continuous-subsequences.ex similarity index 100% rename from Task/Non-continuous-subsequences/Elixir/non-continuous-subsequences.elixir rename to Task/Non-continuous-subsequences/Elixir/non-continuous-subsequences.ex diff --git a/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.julia b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.jl similarity index 100% rename from Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.julia rename to Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.jl diff --git a/Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kotlin b/Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kts similarity index 100% rename from Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kotlin rename to Task/Non-continuous-subsequences/Kotlin/non-continuous-subsequences.kts diff --git a/Task/Non-continuous-subsequences/OCaml/non-continuous-subsequences.ocaml b/Task/Non-continuous-subsequences/OCaml/non-continuous-subsequences.ml similarity index 100% rename from Task/Non-continuous-subsequences/OCaml/non-continuous-subsequences.ocaml rename to Task/Non-continuous-subsequences/OCaml/non-continuous-subsequences.ml diff --git a/Task/Non-continuous-subsequences/Rust/non-continuous-subsequences.rs b/Task/Non-continuous-subsequences/Rust/non-continuous-subsequences.rs new file mode 100644 index 0000000000..fde9feccac --- /dev/null +++ b/Task/Non-continuous-subsequences/Rust/non-continuous-subsequences.rs @@ -0,0 +1,39 @@ +const M: usize = 0; +const C: usize = 1; +const CM: usize = 2; +const CMC: usize = 3; +static SKIP: [usize; 4] = [M, CM, CM, CMC]; +static INCL: [usize; 4] = [C, C, CMC, CMC]; + +fn ncs(s: &Vec) -> Vec> { + if s.len() < 3 { + return vec![]; + } + let mut v1 = n2([].to_vec(), s[1..].to_vec(), M); + let mut v2 = n2([s[0]].to_vec(), s[1..].to_vec(), C); + v1.append(&mut v2); + return v1; +} + +fn n2(ss: Vec, tail: Vec, seq: usize) -> Vec> { + if tail.len() == 0 { + if seq != CMC as usize { + return vec![]; + } + return [ss].to_vec(); + } + let mut v1 = n2(ss.clone(), tail[1..].to_vec(), SKIP[seq]); + let mut v2 = ss.clone(); + v2.push(tail[0]); + let mut v3 = n2(v2, tail[1..].to_vec(), INCL[seq]); + v1.append(&mut v3); + return v1; +} + +fn main() { + let ss = ncs(&[1, 2, 3, 4].to_vec()); + println!("{} non-continuous subsequences:", ss.len()); + for s in ss { + println!(" {:?}", s); + } +} diff --git a/Task/Non-continuous-subsequences/Scheme/non-continuous-subsequences.ss b/Task/Non-continuous-subsequences/Scheme/non-continuous-subsequences.scm similarity index 100% rename from Task/Non-continuous-subsequences/Scheme/non-continuous-subsequences.ss rename to Task/Non-continuous-subsequences/Scheme/non-continuous-subsequences.scm diff --git a/Task/Non-decimal-radices-Convert/Delphi/non-decimal-radices-convert.delphi b/Task/Non-decimal-radices-Convert/Delphi/non-decimal-radices-convert.pas similarity index 100% rename from Task/Non-decimal-radices-Convert/Delphi/non-decimal-radices-convert.delphi rename to Task/Non-decimal-radices-Convert/Delphi/non-decimal-radices-convert.pas diff --git a/Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.elixir b/Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.ex similarity index 100% rename from Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.elixir rename to Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.ex diff --git a/Task/Non-decimal-radices-Convert/Euphoria/non-decimal-radices-convert.euphoria b/Task/Non-decimal-radices-Convert/Euphoria/non-decimal-radices-convert.ex similarity index 100% rename from Task/Non-decimal-radices-Convert/Euphoria/non-decimal-radices-convert.euphoria rename to Task/Non-decimal-radices-Convert/Euphoria/non-decimal-radices-convert.ex diff --git a/Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.julia b/Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.jl similarity index 100% rename from Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.julia rename to Task/Non-decimal-radices-Convert/Julia/non-decimal-radices-convert.jl diff --git a/Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kotlin b/Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kts similarity index 100% rename from Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kotlin rename to Task/Non-decimal-radices-Convert/Kotlin/non-decimal-radices-convert.kts diff --git a/Task/Non-decimal-radices-Convert/Nu/non-decimal-radices-convert.nu b/Task/Non-decimal-radices-Convert/Nu/non-decimal-radices-convert.nu new file mode 100644 index 0000000000..5a9df38d25 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Nu/non-decimal-radices-convert.nu @@ -0,0 +1,6 @@ +const numerals = ('0123456789abcdefghijklmnopqrstuvwxyz' | split chars) + +def base [r: int]: int -> string { + let c = {|x| if $x < $r { {out: $x} } else {out: ($x mod $r) next: ($x // $r)} } + generate $c $in | reverse | collect {|d| $numerals | get $d.0 ...($d | skip) } | str join +} diff --git a/Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-1.ocaml b/Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-1.ml similarity index 100% rename from Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-1.ocaml rename to Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-1.ml diff --git a/Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-2.ocaml b/Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-2.ml similarity index 100% rename from Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-2.ocaml rename to Task/Non-decimal-radices-Convert/OCaml/non-decimal-radices-convert-2.ml diff --git a/Task/Non-decimal-radices-Convert/Rust/non-decimal-radices-convert.rust b/Task/Non-decimal-radices-Convert/Rust/non-decimal-radices-convert.rs similarity index 100% rename from Task/Non-decimal-radices-Convert/Rust/non-decimal-radices-convert.rust rename to Task/Non-decimal-radices-Convert/Rust/non-decimal-radices-convert.rs diff --git a/Task/Non-decimal-radices-Convert/Scheme/non-decimal-radices-convert.ss b/Task/Non-decimal-radices-Convert/Scheme/non-decimal-radices-convert.scm similarity index 100% rename from Task/Non-decimal-radices-Convert/Scheme/non-decimal-radices-convert.ss rename to Task/Non-decimal-radices-Convert/Scheme/non-decimal-radices-convert.scm diff --git a/Task/Non-decimal-radices-Input/Delphi/non-decimal-radices-input.delphi b/Task/Non-decimal-radices-Input/Delphi/non-decimal-radices-input.pas similarity index 100% rename from Task/Non-decimal-radices-Input/Delphi/non-decimal-radices-input.delphi rename to Task/Non-decimal-radices-Input/Delphi/non-decimal-radices-input.pas diff --git a/Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.elixir b/Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.ex similarity index 100% rename from Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.elixir rename to Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.ex diff --git a/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.julia b/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.jl similarity index 100% rename from Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.julia rename to Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-1.jl diff --git a/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.julia b/Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.jl similarity index 100% rename from Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.julia rename to Task/Non-decimal-radices-Input/Julia/non-decimal-radices-input-2.jl diff --git a/Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kotlin b/Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kts similarity index 100% rename from Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kotlin rename to Task/Non-decimal-radices-Input/Kotlin/non-decimal-radices-input.kts diff --git a/Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-1.ocaml b/Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-1.ml similarity index 100% rename from Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-1.ocaml rename to Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-1.ml diff --git a/Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-2.ocaml b/Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-2.ml similarity index 100% rename from Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-2.ocaml rename to Task/Non-decimal-radices-Input/OCaml/non-decimal-radices-input-2.ml diff --git a/Task/Non-decimal-radices-Input/Rust/non-decimal-radices-input.rust b/Task/Non-decimal-radices-Input/Rust/non-decimal-radices-input.rs similarity index 100% rename from Task/Non-decimal-radices-Input/Rust/non-decimal-radices-input.rust rename to Task/Non-decimal-radices-Input/Rust/non-decimal-radices-input.rs diff --git a/Task/Non-decimal-radices-Input/Scheme/non-decimal-radices-input.ss b/Task/Non-decimal-radices-Input/Scheme/non-decimal-radices-input.scm similarity index 100% rename from Task/Non-decimal-radices-Input/Scheme/non-decimal-radices-input.ss rename to Task/Non-decimal-radices-Input/Scheme/non-decimal-radices-input.scm diff --git a/Task/Non-decimal-radices-Output/Delphi/non-decimal-radices-output.delphi b/Task/Non-decimal-radices-Output/Delphi/non-decimal-radices-output.pas similarity index 100% rename from Task/Non-decimal-radices-Output/Delphi/non-decimal-radices-output.delphi rename to Task/Non-decimal-radices-Output/Delphi/non-decimal-radices-output.pas diff --git a/Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.elixir b/Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.ex similarity index 100% rename from Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.elixir rename to Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.ex diff --git a/Task/Non-decimal-radices-Output/Euphoria/non-decimal-radices-output.euphoria b/Task/Non-decimal-radices-Output/Euphoria/non-decimal-radices-output.ex similarity index 100% rename from Task/Non-decimal-radices-Output/Euphoria/non-decimal-radices-output.euphoria rename to Task/Non-decimal-radices-Output/Euphoria/non-decimal-radices-output.ex diff --git a/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia b/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.jl similarity index 100% rename from Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia rename to Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.jl diff --git a/Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kotlin b/Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kts similarity index 100% rename from Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kotlin rename to Task/Non-decimal-radices-Output/Kotlin/non-decimal-radices-output.kts diff --git a/Task/Non-decimal-radices-Output/OCaml/non-decimal-radices-output.ocaml b/Task/Non-decimal-radices-Output/OCaml/non-decimal-radices-output.ml similarity index 100% rename from Task/Non-decimal-radices-Output/OCaml/non-decimal-radices-output.ocaml rename to Task/Non-decimal-radices-Output/OCaml/non-decimal-radices-output.ml diff --git a/Task/Non-decimal-radices-Output/Rust/non-decimal-radices-output.rust b/Task/Non-decimal-radices-Output/Rust/non-decimal-radices-output.rs similarity index 100% rename from Task/Non-decimal-radices-Output/Rust/non-decimal-radices-output.rust rename to Task/Non-decimal-radices-Output/Rust/non-decimal-radices-output.rs diff --git a/Task/Non-decimal-radices-Output/Scheme/non-decimal-radices-output.ss b/Task/Non-decimal-radices-Output/Scheme/non-decimal-radices-output.scm similarity index 100% rename from Task/Non-decimal-radices-Output/Scheme/non-decimal-radices-output.ss rename to Task/Non-decimal-radices-Output/Scheme/non-decimal-radices-output.scm diff --git a/Task/Non-transitive-dice/C++/non-transitive-dice.cpp b/Task/Non-transitive-dice/C++/non-transitive-dice.cpp new file mode 100644 index 0000000000..059352856c --- /dev/null +++ b/Task/Non-transitive-dice/C++/non-transitive-dice.cpp @@ -0,0 +1,124 @@ +#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() << "]"; +} + +void display_table(const std::vector> table) { + std::cout << "["; + for ( uint64_t i = 0; i < table.size() - 1; ++i ) { + print_vector(table[i]); + std::cout << ", "; + } + print_vector(table.back()); + std::cout << "]" << "\n"; +} + +std::vector> four_face_combinations() { + std::vector> result = { }; + std::set found = { }; + + for ( uint32_t i = 1; i <= 4; ++i ) { + for ( uint32_t j = 1; j <= 4; ++j ) { + for ( uint32_t k = 1; k <= 4; ++k ) { + for ( uint32_t l = 1; l <= 4; ++l ) { + std::vector combo = { i, j, k, l }; + std::sort(combo.begin(), combo.end()); + + const uint32_t key = 64 * combo[0] + 16 * combo[1] + 4 * combo[2] + combo[3]; + if ( found.insert(key).second ) { + result.emplace_back(combo); + } + } + } + } + } + + return result; +} + +bool comparator(const std::vector& one, const std::vector& two) { + uint32_t one_wins = 0; + uint32_t two_wins = 0; + for ( uint32_t i = 0; i < 4; ++i ) { + for ( uint32_t j = 0; j < 4; ++j ) { + if ( one[i] > two[j] ) { + one_wins++; + } else if ( one[i] < two[j] ) { + two_wins++; + } + } + } + return ( one_wins < two_wins ); +} + +std::vector>> find_intransitive_3( + const std::vector>& combos) { + std::vector>> result = { }; + + for ( uint64_t i = 0; i < combos.size(); ++i ) { + for ( uint64_t j = 0; j < combos.size(); ++j ) { + if ( comparator(combos[i], combos[j]) ) { + for ( const std::vector& combo : combos ) { + if ( comparator(combos[j], combo) && comparator(combo, combos[i]) ) { + std::vector> entry = { combos[i], combos[j], combo }; + result.emplace_back(entry); + } + } + } + } + } + + return result; +} + +std::vector>> find_intransitive_4( + const std::vector>& combos) { + std::vector>> result = { }; + + for ( uint64_t i = 0; i < combos.size(); ++i ) { + for ( uint64_t j = 0; j < combos.size(); ++j ) { + if ( comparator(combos[i], combos[j]) ) { + for ( uint64_t k = 0; k < combos.size(); ++k ) { + if ( comparator(combos[j], combos[k]) ) { + for ( const std::vector& combo : combos ) { + if ( comparator(combos[k], combo) && comparator(combo, combos[i]) ) { + std::vector> entry = + { combos[i], combos[j], combos[k], combo }; + result.emplace_back(entry); + } + } + } + } + } + } + } + + return result; +} + +int main() { + std::vector> combinations = four_face_combinations(); + std::cout << "The number of eligible 4-faced dice: " << combinations.size() << "\n\n"; + + std::vector>> intransitive_3 = find_intransitive_3(combinations); + std::cout << intransitive_3.size() << " ordered lists of 3 non-transitive dice found, namely:" << "\n"; + for ( const std::vector>& table : intransitive_3 ) { + display_table(table); + } + std::cout << "\n"; + + std::vector>> intransitive_4 = find_intransitive_4(combinations); + std::cout << intransitive_4.size() << " ordered lists of 4 non-transitive dice found, namely:" << "\n"; + for ( const std::vector>& table : intransitive_4 ) { + display_table(table); + } +} diff --git a/Task/Non-transitive-dice/FreeBASIC/non-transitive-dice.basic b/Task/Non-transitive-dice/FreeBASIC/non-transitive-dice.basic new file mode 100644 index 0000000000..07e663121b --- /dev/null +++ b/Task/Non-transitive-dice/FreeBASIC/non-transitive-dice.basic @@ -0,0 +1,145 @@ +'#include "sort.bas" + +Sub fourFaceCombs(res() As Integer Ptr, found() As Boolean) + Dim As Integer i, j, k, l, m, index, key + + index = 0 + For i = 1 To 4 + For j = 1 To 4 + For k = 1 To 4 + For l = 1 To 4 + Dim As Integer c(3) = {i, j, k, l} + Sort(c()) + + key = 64 * (c(0) - 1) + 16 * (c(1) - 1) + 4 * (c(2) - 1) + (c(3) - 1) + If Not found(key) Then + found(key) = true + Redim Preserve res(index) + res(index) = Callocate(4 * Sizeof(Integer)) + For m = 0 To 3 + res(index)[m] = c(m) + Next + index += 1 + End If + Next + Next + Next + Next +End Sub + +Function cmp(x As Integer Ptr, y As Integer Ptr) As Integer + Dim As Integer i, j, xw, yw + + xw = 0 + yw = 0 + For i = 0 To 3 + For j = 0 To 3 + If x[i] > y[j] Then + xw += 1 + Elseif y[j] > x[i] Then + yw += 1 + End If + Next + Next + + Return Sgn(xw - yw) +End Function + +Sub findIntransitive3(cs() As Integer Ptr, res() As Integer Ptr Ptr) + Dim As Integer i, j, k, c, index + + c = Ubound(cs) + index = 0 + For i = 0 To c + For j = 0 To c + For k = 0 To c + If cmp(cs(i), cs(j)) = -1 Then + If cmp(cs(j), cs(k)) = -1 Then + If cmp(cs(i), cs(k)) = 1 Then + Redim Preserve res(index) + res(index) = Callocate(3 * Sizeof(Integer Ptr)) + res(index)[0] = cs(i) + res(index)[1] = cs(j) + res(index)[2] = cs(k) + index += 1 + End If + End If + End If + Next + Next + Next +End Sub + +Sub findIntransitive4(cs() As Integer Ptr, res() As Integer Ptr Ptr) + Dim As Integer i, j, k, l, c, index + + c = Ubound(cs) + index = 0 + For i = 0 To c + For j = 0 To c + For k = 0 To c + For l = 0 To c + If cmp(cs(i), cs(j)) = -1 Then + If cmp(cs(j), cs(k)) = -1 Then + If cmp(cs(k), cs(l)) = -1 Then + If cmp(cs(i), cs(l)) = 1 Then + Redim Preserve res(index) + res(index) = Callocate(4 * Sizeof(Integer Ptr)) + res(index)[0] = cs(i) + res(index)[1] = cs(j) + res(index)[2] = cs(k) + res(index)[3] = cs(l) + index += 1 + End If + End If + End If + End If + Next + Next + Next + Next +End Sub + +Sub Main() + Dim As Integer i, j, k + Dim As Integer Ptr combs() + Dim As Boolean found(255) + fourFaceCombs(combs(), found()) + Print "Number of eligible 4-faced dice"; Ubound(combs) + 1 + + Dim it3() As Integer Ptr Ptr + findIntransitive3(combs(), it3()) + Print + Print Ubound(it3) + 1; " ordered lists of 3 non-transitive dice found, namely:" + For i = 0 To Ubound(it3) + Print "["; + For j = 0 To 2 + Print "["; + For k = 0 To 3 + Print it3(i)[j][k]; ","; + Next + Print Chr(8); " ], "; + Next + Print Chr(8); Chr(8); "]" + Next + + Dim it4() As Integer Ptr Ptr + findIntransitive4(combs(), it4()) + Print + Print Ubound(it4) + 1; " ordered lists of 4 non-transitive dice found, namely:" + For i = 0 To Ubound(it4) + Print "["; + For j = 0 To 3 + Print "["; + For k = 0 To 3 + Print it4(i)[j][k]; ","; + Next + Print Chr(8); " ], "; + Next + Print Chr(8); Chr(8); "]" + Next +End Sub + +Main() + +Sleep diff --git a/Task/Non-transitive-dice/Julia/non-transitive-dice.julia b/Task/Non-transitive-dice/Julia/non-transitive-dice.jl similarity index 100% rename from Task/Non-transitive-dice/Julia/non-transitive-dice.julia rename to Task/Non-transitive-dice/Julia/non-transitive-dice.jl diff --git a/Task/Non-transitive-dice/Kotlin/non-transitive-dice.kotlin b/Task/Non-transitive-dice/Kotlin/non-transitive-dice.kts similarity index 100% rename from Task/Non-transitive-dice/Kotlin/non-transitive-dice.kotlin rename to Task/Non-transitive-dice/Kotlin/non-transitive-dice.kts diff --git a/Task/Non-transitive-dice/Phix/non-transitive-dice-1.phix b/Task/Non-transitive-dice/Phix/non-transitive-dice-1.phix index 33bc35bc81..a0796ba2dd 100644 --- a/Task/Non-transitive-dice/Phix/non-transitive-dice-1.phix +++ b/Task/Non-transitive-dice/Phix/non-transitive-dice-1.phix @@ -1,221 +1,217 @@ -(phixonline)--> - with javascript_semantics - requires("0.8.2") -- (added sq_cmp() builtin that returns nested -1/0/+1 compare() results, just like the existing sq_eq() does for equal().) +with javascript_semantics +integer mx = 4, -- max number of a die side (later set to 6) + mn = 1 -- min number of a die side (later set to 0) - integer mx = 4, -- max number of a die side (later set to 6) - mn = 1 -- min number of a die side (later set to 0) +function possible_dice(integer sides) + -- + -- construct all non-descending permutes of mn..mx, + -- ie/eg {1,1,1,1}..{4,4,4,4} with (say), amongst + -- others, {1,1,2,4} but not {1,1,4,2}. + -- + sequence die = repeat(mn,sides), -- (main work area) + res = {deep_copy(die)} + while true do + -- find rightmost incrementable side + -- ie/eg {1,2,4,4} -> set rdx to 2 (if 1-based indexing) + integer rdx = rfind(true,sq_lt(die,mx)) + if rdx=0 then exit end if + -- set that and all later to that incremented + -- ie/eg {1,2,4,4} -> {1,3,3,3} + die[rdx..$] = die[rdx]+1 + res = append(res,deep_copy(die)) + end while + printf(1,"There are %d possible %d..%d %d-sided dice\n",{length(res),mn,mx,sides}) + return res +end function - function possible_dice(integer sides) - -- - -- construct all non-descending permutes of mn..mx, - -- ie/eg {1,1,1,1}..{4,4,4,4} with (say), amongst - -- others, {1,1,2,4} but not {1,1,4,2}. - -- - sequence die = repeat(mn,sides), -- (main work area) - res = {deep_copy(die)} - while true do - -- find rightmost incrementable side - -- ie/eg {1,2,4,4} -> set rdx to 2 (if 1-based indexing) - integer rdx = rfind(true,sq_lt(die,mx)) - if rdx=0 then exit end if - -- set that and all later to that incremented - -- ie/eg {1,2,4,4} -> {1,3,3,3} - die[rdx..$] = die[rdx]+1 - res = append(res,deep_copy(die)) - end while - printf(1,"There are %d possible %d..%d %d-sided dice\n",{length(res),mn,mx,sides}) - return res - end function +function Dnn(sequence die) + -- reconstruct the python die numbering (string) + -- essentially just treat it as a base-N number. + integer l = length(die), -- (sides) + N = mx-mn+1, -- (base) + n = 0 -- (result) + for k=1 to l do + n += (die[k]-mn)*power(N,l-k) + end for + return sprintf("D%d",n+1) +end function - function Dnn(sequence die) - -- reconstruct the python die numbering (string) - -- essentially just treat it as a base-N number. - integer l = length(die), -- (sides) - N = mx-mn+1, -- (base) - n = 0 -- (result) - for k=1 to l do - n += (die[k]-mn)*power(N,l-k) - end for - return sprintf("D%d",n+1) - end function +function cmpd(sequence die1, die2) + -- compares two die returning -1, 0, or +1 for <, =, > + integer res = 0 + for i=1 to length(die1) do + res += sum(sq_cmp(die1[i],die2)) + end for + return sign(res) +end function - function cmpd(sequence die1, die2) - -- compares two die returning -1, 0, or +1 for <, =, > - integer res = 0 - for i=1 to length(die1) do - res += sum(sq_cmp(die1[i],die2)) - end for - return sign(res) - end function +function low_rotation(sequence set) + integer k = find(min(set),set) + return set[k..$]&set[1..k-1] +end function - function low_rotation(sequence set) - integer k = find(min(set),set) - return set[k..$]&set[1..k-1] - end function +integer rotations +function find_non_trans(sequence dice, integer n=3) + atom t1 = time()+1 + integer l = length(dice), sk, sk1, c + sequence set = repeat(1,n), -- (indexes to dice) + cache = repeat(repeat(-2,l),l), + res = {} + while true do + bool valid = true + for k=1 to n-1 do + sk = set[k] + sk1 = set[k+1] + c = cache[sk][sk1] + if c=-2 then + c = cmpd(dice[sk],dice[sk1]) + cache[sk][sk1] = c + end if + if c!=-1 then + valid = false + -- force k+1 to be incremented next: + set[k+2..$] = l + exit + end if + end for + if valid then + sk = set[1] + sk1 = set[$] + c = cache[sk][sk1] + if c=-2 then + c = cmpd(dice[sk],dice[sk1]) + cache[sk][sk1] = c + end if + if c=+1 then + res = append(res,low_rotation(set)) + end if + end if + -- find rightmost incrementable die index + -- ie/eg if l is 35 and set is {1,2,35,35} + -- -> set rdx to 2 (if 1-based indexing) + integer rdx = rfind(true,sq_lt(set,l)) + if rdx=0 then exit end if + -- increment that and reset all later + -- ie/eg {1,2,35,35} -> {1,3,1,1} + set[rdx] += 1 + set[rdx+1..$] = 1 + if time()>t1 and platform()!=JS then + progress("working... (%d/%d)\r",{set[1],l}) + t1 = time()+1 + end if + end while + if platform()!=JS then + progress("") + end if + rotations = length(res) + res = unique(res) + rotations -= length(res) + return res +end function - integer rotations - function find_non_trans(sequence dice, integer n=3) - atom t1 = time()+1 - integer l = length(dice), sk, sk1, c - sequence set = repeat(1,n), -- (indexes to dice) - cache = repeat(repeat(-2,l),l), - res = {} - while true do - bool valid = true - for k=1 to n-1 do - sk = set[k] - sk1 = set[k+1] - c = cache[sk][sk1] - if c=-2 then - c = cmpd(dice[sk],dice[sk1]) - cache[sk][sk1] = c - end if - if c!=-1 then - valid = false - -- force k+1 to be incremented next: - set[k+2..$] = l - exit - end if - end for - if valid then - sk = set[1] - sk1 = set[$] - c = cache[sk][sk1] - if c=-2 then - c = cmpd(dice[sk],dice[sk1]) - cache[sk][sk1] = c - end if - if c=+1 then - res = append(res,low_rotation(set)) - end if - end if - -- find rightmost incrementable die index - -- ie/eg if l is 35 and set is {1,2,35,35} - -- -> set rdx to 2 (if 1-based indexing) - integer rdx = rfind(true,sq_lt(set,l)) - if rdx=0 then exit end if - -- increment that and reset all later - -- ie/eg {1,2,35,35} -> {1,3,1,1} - set[rdx] += 1 - set[rdx+1..$] = 1 - if time()>t1 and platform()!=JS then - progress("working... (%d/%d)\r",{set[1],l}) - t1 = time()+1 - end if - end while - if platform()!=JS then - progress("") - end if - rotations = length(res) - res = unique(res) - rotations -= length(res) - return res - end function +function verbose_cmp(sequence die1, die2) + -- compares two die returning their relationship of their names as a string + integer c = cmpd(die1,die2) + string op = {"<","=",">"}[c+2], + n1 = Dnn(die1), + n2 = Dnn(die2) + return sprintf("%s %s %s",{n1,op,n2}) +end function - function verbose_cmp(sequence die1, die2) - -- compares two die returning their relationship of their names as a string - integer c = cmpd(die1,die2) - string op = {"<","=",">"}[c+2], - n1 = Dnn(die1), - n2 = Dnn(die2) - return sprintf("%s %s %s",{n1,op,n2}) - end function +function verbose_dice_cmp(sequence dice, set) + sequence c = {}, d1, d2 + for j=1 to length(set)-1 do + d1 = dice[set[j]] + d2 = dice[set[j+1]] + c = append(c,verbose_cmp(d1,d2)) + end for + d1 = dice[set[1]] + d2 = dice[set[$]] + c = append(c,verbose_cmp(d1,d2)) + return join(c,", ") +end function - function verbose_dice_cmp(sequence dice, set) - sequence c = {}, d1, d2 - for j=1 to length(set)-1 do - d1 = dice[set[j]] - d2 = dice[set[j+1]] - c = append(c,verbose_cmp(d1,d2)) - end for - d1 = dice[set[1]] - d2 = dice[set[$]] - c = append(c,verbose_cmp(d1,d2)) - return join(c,", ") - end function +procedure show_dice(sequence dice, non_trans, integer N) + integer l = length(non_trans), + omissions = 0, + last = 0 + if N then + printf(1,"\n Non_transitive length-%d combinations found: %d\n",{N,l+rotations}) + end if + for i=1 to l do + object ni = non_trans[i] + if sequence(ni) then + if i<5 then + printf(1,"\n") + for j=1 to length(ni) do + sequence d = dice[ni[j]] + printf(1," %s:%v\n",{Dnn(d),d}) + end for + last = i + else + omissions += 1 + end if + end if + end for + if omissions then + printf(1," (%d omitted)\n",omissions) + end if + if rotations then + printf(1," (%d rotations omitted)\n",rotations) + end if + if last then + printf(1,"\n") + if mx<=6 and mn=1 then + printf(1," More verbose comparison of last result:\n") + end if + printf(1," %s\n",{verbose_dice_cmp(dice,non_trans[last])}) + printf(1,"\n ====\n") + end if + printf(1,"\n") +end procedure - procedure show_dice(sequence dice, non_trans, integer N) - integer l = length(non_trans), - omissions = 0, - last = 0 - if N then - printf(1,"\n Non_transitive length-%d combinations found: %d\n",{N,l+rotations}) - end if - for i=1 to l do - object ni = non_trans[i] - if sequence(ni) then - if i<5 then - printf(1,"\n") - for j=1 to length(ni) do - sequence d = dice[ni[j]] - printf(1," %s:%v\n",{Dnn(d),d}) - end for - last = i - else - omissions += 1 - end if - end if - end for - if omissions then - printf(1," (%d omitted)\n",omissions) - end if - if rotations then - printf(1," (%d rotations omitted)\n",rotations) - end if - if last then - printf(1,"\n") - if mx<=6 and mn=1 then - printf(1," More verbose comparison of last result:\n") - end if - printf(1," %s\n",{verbose_dice_cmp(dice,non_trans[last])}) - printf(1,"\n ====\n") - end if - printf(1,"\n") - end procedure +atom t0 = time() +sequence dice = possible_dice(4) +for N=3 to 4 do + show_dice(dice,find_non_trans(dice,N),N) +end for - atom t0 = time() - sequence dice = possible_dice(4) - for N=3 to 4 do - show_dice(dice,find_non_trans(dice,N),N) - end for +-- From the numberphile video (Efron's dice): +mx = 6 +mn = 0 +dice = possible_dice(6) +--show_dice(dice,find_non_trans(dice,4),4) +-- ok, dunno about you but I'm not waiting for power(924,4) permutes... +-- limit to the ones discussed, plus another 4 random ones +-- (hopefully it'll just pick out the right ones...) +printf(1,"\nEfron's dice\n") +dice = {{0,0,4,4,4,4}, + {1,1,1,1,1,1}, -- (rand) + {1,1,1,5,5,5}, + {1,2,3,4,5,6}, -- (rand) + {2,2,2,2,6,6}, + {5,5,5,6,6,6}, -- (rand) + {3,3,3,3,3,3}, + {6,6,6,6,6,6}} -- (rand) - -- From the numberphile video (Efron's dice): - mx = 6 - mn = 0 - dice = possible_dice(6) - --show_dice(dice,find_non_trans(dice,4),4) - -- ok, dunno about you but I'm not waiting for power(924,4) permutes... - -- limit to the ones discussed, plus another 4 random ones - -- (hopefully it'll just pick out the right ones...) - printf(1,"\nEfron's dice\n") - dice = {{0,0,4,4,4,4}, - {1,1,1,1,1,1}, -- (rand) - {1,1,1,5,5,5}, - {1,2,3,4,5,6}, -- (rand) - {2,2,2,2,6,6}, - {5,5,5,6,6,6}, -- (rand) - {3,3,3,3,3,3}, - {6,6,6,6,6,6}} -- (rand) +show_dice(dice,find_non_trans(dice,4),0) - show_dice(dice,find_non_trans(dice,4),0) +-- and from wp: +mx = 9 +mn = 1 +dice = possible_dice(6) +printf(1,"\nFrom wp\n") +dice = {{1,1,6,6,8,8}, + {2,2,4,4,9,9}, + {3,3,5,5,7,7}} - -- and from wp: - mx = 9 - mn = 1 - dice = possible_dice(6) - printf(1,"\nFrom wp\n") - dice = {{1,1,6,6,8,8}, - {2,2,4,4,9,9}, - {3,3,5,5,7,7}} +show_dice(dice,find_non_trans(dice,3),0) - show_dice(dice,find_non_trans(dice,3),0) +-- Miwin's dice +printf(1,"Miwin's dice\n") +dice = {{1,2,5,6,7,9}, + {1,3,4,5,8,9}, + {2,3,4,6,7,8}} - -- Miwin's dice - printf(1,"Miwin's dice\n") - dice = {{1,2,5,6,7,9}, - {1,3,4,5,8,9}, - {2,3,4,6,7,8}} - - show_dice(dice,find_non_trans(dice,3),0) - printf(1,"%s\n\n",elapsed(time()-t0)) - - t0 = time() - mx = 6 - mn = 1 - dice = possible_dice(6) - show_dice(dice,find_non_trans(dice,3),3) - printf(1,"%s\n\n",elapsed(time()-t0)) +t0 = time() +mx = 6 +mn = 1 +dice = possible_dice(6) +show_dice(dice,find_non_trans(dice,3),3) +printf(1,"%s\n\n",elapsed(time()-t0)) - t0 = time() - mx = 6 - mn = 0 - dice = possible_dice(6) - show_dice(dice,find_non_trans(dice,3),3) - printf(1,"%s\n\n",elapsed(time()-t0)) - - with javascript_semantics - function pancake(integer n) - integer gap = 2, sum_gaps = gap, adj = -1 - while sum_gaps<n do - adj += 1 - gap = gap*2-1 - sum_gaps += gap - end while - n += adj - return n - end function - sequence t = tagset(20), - r = columnize({t,apply(t,pancake)}), - p = apply(true,sprintf,{{"p(%2d) = %2d"},r}) - printf(1,"%s\n",join_by(p,1,5)) - - with javascript_semantics - function pancake(integer n) - integer gap = 2, pg = 1, sum_gaps = gap, adj = -1 - while sum_gaps<n do - adj += 1 - {pg,gap} = {gap,gap+pg} - sum_gaps += gap - end while - n += adj - return n - end function - sequence t = tagset(20), - r = columnize({t,apply(t,pancake)}), - p = apply(true,sprintf,{{"p(%2d) = %2d"},r}) - printf(1,"%s\n",join_by(p,1,5)) - - with javascript_semantics - function visitor(sequence stack, integer /*unused*/, sequence stacks) - for pos=2 to length(stack) do - -- for pos=0 to length(stack)-2 do - sequence newstack = reverse(stack[1..pos])&stack[pos+1..$] - -- sequence newstack = stack[1..pos]&reverse(stack[pos+1..$]) - if getd_index(newstack,stacks[1])=NULL then - setd(newstack,0,stacks[$]) -- (next round) - setd(newstack,0,stacks[1]) -- (the master) - end if - end for - return 1 - end function +with javascript_semantics +function visitor(sequence stack, integer /*unused*/, sequence stacks) + for pos=2 to length(stack) do +-- for pos=0 to length(stack)-2 do + sequence newstack = reverse(stack[1..pos])&stack[pos+1..$] +-- sequence newstack = stack[1..pos]&reverse(stack[pos+1..$]) + if getd_index(newstack,stacks[1])=NULL then + setd(newstack,0,stacks[$]) -- (next round) + setd(newstack,0,stacks[1]) -- (the master) + end if + end for + return 1 +end function - function pancake(integer len) - sequence goalstack = tagset(len), - stacks = {new_dict({{goalstack,0}})} - while true do - stacks &= new_dict() - -- add any flips of stacks[$-1] - -- not already in stacks[1] - -- to stacks[$] - traverse_dict(visitor,stacks,stacks[$-1]) - if dict_size(stacks[$])=0 then exit end if - end while - sequence eg = getd_partial_key(0,stacks[$-1],true) - integer sz = dict_size(stacks[$-1]) - papply(stacks,destroy_dict) - return {length(stacks)-2,eg,sz} - end function +function pancake(integer len) + sequence goalstack = tagset(len), + stacks = {new_dict({{goalstack,0}})} + while true do + stacks &= new_dict() + -- add any flips of stacks[$-1] + -- not already in stacks[1] + -- to stacks[$] + traverse_dict(visitor,stacks,stacks[$-1]) + if dict_size(stacks[$])=0 then exit end if + end while + sequence eg = getd_partial_key(0,stacks[$-1],true) + integer sz = dict_size(stacks[$-1]) + papply(stacks,destroy_dict) + return {length(stacks)-2,eg,sz} +end function - atom t0 = time() - for n=1 to 8 do -- (for <2s) - {integer pn, sequence eg, integer sz} = pancake(n) - printf(1,"p(%d) = %d, example: %v (of %,d, %s)\n",{n,pn,eg,sz,elapsed(time()-t0)}) - end for - - integer res -- 1=failure, 0=success - atom rint = 0 -- random 32-bit int +integer res -- 1=failure, 0=success +atom rint = 0 -- random 32-bit int - #ilASM{ - mov eax,1 - cpuid - bt ecx,30 - mov edi,1 -- exit code: failure - jnc :exit +#ilASM{ + mov eax,1 + cpuid + bt ecx,30 + mov edi,1 -- exit code: failure + jnc :exit - -- rdrand sets CF=0 if no random number - -- was available. Intel documentation - -- recommends 10 retries in a tight loop - mov ecx,11 - ::loop1 - sub ecx, 1 - jz :exit -- exit code is set already - rdrand eax - -- (the above generates exception #C000001D if not supported) - -- rdtsc - jnc :loop1 + -- rdrand sets CF=0 if no random number + -- was available. Intel documentation + -- recommends 10 retries in a tight loop + mov ecx,11 + ::loop1 + sub ecx, 1 + jz :exit -- exit code is set already + rdrand eax + -- (the above generates exception #C000001D if not supported) +-- rdtsc + jnc :loop1 - lea edi,[rint] - call :%pStoreMint - xor edi,edi + lea edi,[rint] + call :%pStoreMint + xor edi,edi - ::exit - mov [res],edi - xor ebx,ebx -- important! - } + ::exit + mov [res],edi + xor ebx,ebx -- important! + } - ?{res,rint} +?{res,rint} - if res=0 then -- (success) +if res=0 then -- (success) - -- - -- To convert a signed 32-bit int to an unsigned one: - -- - -- method 1 - -- atom urint1 = rint - -- if urint1<0 then urint1+=#100000000 end if - atom urint1 = rint+iff(rint<0?#100000000:0) + -- + -- To convert a signed 32-bit int to an unsigned one: + -- + -- method 1 +-- atom urint1 = rint +-- if urint1<0 then urint1+=#100000000 end if + atom urint1 = rint+iff(rint<0?#100000000:0) - -- method 2 - atom pMem = allocate(4) - poke4(pMem,rint) - atom urint2 = peek4u(pMem) - free(pMem) + -- method 2 + atom pMem = allocate(4) + poke4(pMem,rint) + atom urint2 = peek4u(pMem) + free(pMem) - -- method 3 - atom urint3 = bytes_to_int(int_to_bytes(rint,4),signed:=false) + -- method 3 + atom urint3 = bytes_to_int(int_to_bytes(rint,4),signed:=false) - ?{urint1,urint2,urint3} + ?{urint1,urint2,urint3} - end if - - integer fn = open("/dev/urandom","rb") - if fn=-1 then - puts(1,"cannot open /dev/urandom\n") - else - sequence s = {} - for i=1 to 4 do - s &= getc(fn) - end for - close(fn) - ?bytes_to_int(s,signed:=false) - end if - ", has_prefix(s, s1)) + + fmt.println( "2. ", s, " contains ", s1, " --> ", contains (s, s1)) + ndx := index(s, s1) + if ndx > -1 { + fmt.println(" 2.1. at location -> ", ndx) + ndx += len(s1) + for ndx < len(s) { + found := index(s[ndx:], s1) + if found > -1 { + fmt.println(" 2.2. at location -> ", found+ndx) + ndx += found+len(s1) + } else { + break + } + } + fmt.println(" 2.2. and that's all.") + } + + fmt.println( "3. ", s, " ends with ", s1, " --> ", has_suffix(s, s1)) +} diff --git a/Task/String-matching/Rust/string-matching-1.rust b/Task/String-matching/Rust/string-matching-1.rs similarity index 100% rename from Task/String-matching/Rust/string-matching-1.rust rename to Task/String-matching/Rust/string-matching-1.rs diff --git a/Task/String-matching/Rust/string-matching-2.rust b/Task/String-matching/Rust/string-matching-2.rs similarity index 100% rename from Task/String-matching/Rust/string-matching-2.rust rename to Task/String-matching/Rust/string-matching-2.rs diff --git a/Task/String-matching/V-(Vlang)/string-matching.v b/Task/String-matching/V-(Vlang)/string-matching.v index fe733095e1..89e0625675 100644 --- a/Task/String-matching/V-(Vlang)/string-matching.v +++ b/Task/String-matching/V-(Vlang)/string-matching.v @@ -4,5 +4,5 @@ fn main() { println(str.ends_with('zn')) // False println(str.contains('bb')) // False println(str.contains('ab')) // True - println(str.index('bc') or {-1}) // 1 // Vlang arrays are 0 based, so first char position is 0 and no result assigned -1 + println(str.index('bc') or {-1}) // 1 // V arrays are 0 based; first char position is 0 } diff --git a/Task/String-prepend/Delphi/string-prepend.delphi b/Task/String-prepend/Delphi/string-prepend.pas similarity index 100% rename from Task/String-prepend/Delphi/string-prepend.delphi rename to Task/String-prepend/Delphi/string-prepend.pas diff --git a/Task/String-prepend/Ed/string-prepend.ed b/Task/String-prepend/Ed/string-prepend.ed new file mode 100644 index 0000000000..feb76b5a86 --- /dev/null +++ b/Task/String-prepend/Ed/string-prepend.ed @@ -0,0 +1 @@ +s/^/String literal/ diff --git a/Task/String-prepend/Elixir/string-prepend.elixir b/Task/String-prepend/Elixir/string-prepend.ex similarity index 100% rename from Task/String-prepend/Elixir/string-prepend.elixir rename to Task/String-prepend/Elixir/string-prepend.ex diff --git a/Task/String-prepend/Julia/string-prepend.julia b/Task/String-prepend/Julia/string-prepend.jl similarity index 100% rename from Task/String-prepend/Julia/string-prepend.julia rename to Task/String-prepend/Julia/string-prepend.jl diff --git a/Task/String-prepend/Kotlin/string-prepend.kotlin b/Task/String-prepend/Kotlin/string-prepend.kts similarity index 100% rename from Task/String-prepend/Kotlin/string-prepend.kotlin rename to Task/String-prepend/Kotlin/string-prepend.kts diff --git a/Task/String-prepend/OCaml/string-prepend.ocaml b/Task/String-prepend/OCaml/string-prepend.ml similarity index 100% rename from Task/String-prepend/OCaml/string-prepend.ocaml rename to Task/String-prepend/OCaml/string-prepend.ml diff --git a/Task/String-prepend/Rust/string-prepend.rust b/Task/String-prepend/Rust/string-prepend.rs similarity index 100% rename from Task/String-prepend/Rust/string-prepend.rust rename to Task/String-prepend/Rust/string-prepend.rs diff --git a/Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.delphi b/Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.pas similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.delphi rename to Task/Strip-a-set-of-characters-from-a-string/Delphi/strip-a-set-of-characters-from-a-string.pas diff --git a/Task/Strip-a-set-of-characters-from-a-string/Ed/strip-a-set-of-characters-from-a-string.ed b/Task/Strip-a-set-of-characters-from-a-string/Ed/strip-a-set-of-characters-from-a-string.ed new file mode 100644 index 0000000000..93a2cdda4b --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Ed/strip-a-set-of-characters-from-a-string.ed @@ -0,0 +1,4 @@ +H +g/.*/s/[aei]//g +,p +Q diff --git a/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.elixir b/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.ex similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.elixir rename to Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.ex diff --git a/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.elixir b/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.ex similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.elixir rename to Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.ex diff --git a/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.euphoria b/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.ex similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.euphoria rename to Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.ex diff --git a/Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.julia b/Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.jl similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.julia rename to Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.jl diff --git a/Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kotlin b/Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kts similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kotlin rename to Task/Strip-a-set-of-characters-from-a-string/Kotlin/strip-a-set-of-characters-from-a-string.kts diff --git a/Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ocaml b/Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ml similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ocaml rename to Task/Strip-a-set-of-characters-from-a-string/OCaml/strip-a-set-of-characters-from-a-string.ml diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rust b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rs similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rust rename to Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rs diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rust b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rs similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rust rename to Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rs diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rust b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rs similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rust rename to Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rs diff --git a/Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.ss b/Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.scm similarity index 100% rename from Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.ss rename to Task/Strip-a-set-of-characters-from-a-string/Scheme/strip-a-set-of-characters-from-a-string.scm diff --git a/Task/Strip-block-comments/AArch64-Assembly/strip-block-comments.aarch64 b/Task/Strip-block-comments/AArch64-Assembly/strip-block-comments.aarch64 new file mode 100644 index 0000000000..3aa9b649f8 --- /dev/null +++ b/Task/Strip-block-comments/AArch64-Assembly/strip-block-comments.aarch64 @@ -0,0 +1,193 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program Strip block comments */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +.equ BUFFERSIZE, 200 + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessBufferError: .asciz "Error : Buffer too small !!\n" + +szStartComm: .asciz "/*" +szEndComm: .asciz "*/" +szString1: .asciz "/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }" + +szString2: .asciz "/* toto */tutu/*truc*/etc" +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + + ldr x0,qAdrszString1 + ldr x1,qAdrszStartComm + ldr x2,qAdrszEndComm + ldr x3,qAdrsBuffer + mov x4,#BUFFERSIZE + bl suppComment + ldr x0,qAdrsBuffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessBufferError: .quad szMessBufferError +qAdrszString1: .quad szString1 +qAdrszString2: .quad szString2 +qAdrszStartComm: .quad szStartComm +qAdrszEndComm: .quad szEndComm +qAdrsBuffer: .quad sBuffer +/******************************************************************/ +/* test execution */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains start comment address */ +/* x2 contains end comment address */ +/* x3 contains buffer address */ +/* x4 contains buffer length */ +suppComment: + stp x5,lr,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + stp x10,x11,[sp,-16]! + mov x5,#0 // indice string + mov x6,#0 // indice start comment + mov x7,#0 // comment + mov x8,#0 // indice write buffer +1: + ldrb w9,[x1,x6] // load first byte of comment start +2: + ldrb w10,[x0,x5] // load byte string + cmp x10,#0 // end string ? + beq 20f + cmp x7,#1 // comment + beq 6f + cmp x10,x9 // compare first byte and byte string + bne 5f +3: + add x6,x6,#1 + ldrb w9,[x1,x6] // load oher byte of comment start + cmp x9,#0 + beq 4f // end comment ? + strb w10,[x3,x8] // store byte in buffer + add x8,x8,#1 + cmp x8,x4 // error size buffer ? + bge 99f + add x5,x5,#1 // load byte string + ldrb w10,[x0,x5] + cmp x10,#0 // end string ? + beq 20f + cmp x10,x9 // compare byte + beq 3b // loop other char start comment + strb w10,[x3,x8] // else store char string + add x8,x8,#1 + cmp x8,x4 // end buffer ? + bge 99f + add x5,x5,#1 // increment indice string + mov x6,#0 // raz indice start comment + b 1b +4: // start comment found + sub x6,x6,#1 + sub x8,x8,x6 // supp write byte buffer + mov x7,#1 // comment + add x5,x5,#1 // increment indice string + b 2b // and loop +5: // bytes inequals + strb w10,[x3,x8] // store char string + add x8,x8,#1 + cmp x8,x4 // end buffer ? + bge 99f + add x5,x5,#1 // increment indice string + b 2b // and loop +6: // is comment + mov x6,#0 +8: + ldrb w9,[x2,x6] // load end comment first char +9: + cmp x10,x9 // equal byte string ? + bne 10f + add x5,x5,#1 + ldrb w10,[x0,x5] // load other byte + cmp x10,#0 // end string + beq 20f + add x6,x6,#1 + ldrb w9,[x2,x6] // load other byte end comment + cmp x9,#0 // end end comment ? + bne 9b // no -> loop + // comment end + mov x7,#0 // raz comment + mov x6,#0 // raz indice start comment + b 1b +10: // comment not end + add x5,x5,#1 + b 2b + +20: + mov x10,#0 // final zero + strb w10,[x3,x8] // store char string + b 100f + +99: // error + ldr x0,qAdrszMessBufferError + bl affichageMess + mov x0,#-1 +100: + ldp x10,x11,[sp],16 + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x5,lr,[sp],16 + ret + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Strip-block-comments/ARM-Assembly/strip-block-comments.arm b/Task/Strip-block-comments/ARM-Assembly/strip-block-comments.arm new file mode 100644 index 0000000000..406449a0e1 --- /dev/null +++ b/Task/Strip-block-comments/ARM-Assembly/strip-block-comments.arm @@ -0,0 +1,189 @@ +/* ARM assembly Raspberry PI */ +/* program Strip block comments */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ BUFFERSIZE, 200 + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessBufferError: .asciz "Error : Buffer too small !!\n" + +szStartComm: .asciz "/*" +szEndComm: .asciz "*/" +szString1: .asciz "/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }" + +szString2: .asciz "/* toto */tutu/*truc*/etc" +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + + ldr r0,iAdrszString1 + ldr r1,iAdrszStartComm + ldr r2,iAdrszEndComm + ldr r3,iAdrsBuffer + mov r4,#BUFFERSIZE + bl suppComment + ldr r0,iAdrsBuffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessBufferError: .int szMessBufferError +iAdrszString1: .int szString1 +iAdrszString2: .int szString2 +iAdrszStartComm: .int szStartComm +iAdrszEndComm: .int szEndComm +iAdrsBuffer: .int sBuffer +/******************************************************************/ +/* test execution */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains start comment address */ +/* r2 contains end comment address */ +/* r3 contains buffer address */ +/* r4 contains buffer length */ +suppComment: + push {r1-r10,lr} @ save registers + mov r5,#0 @ indice string + mov r6,#0 @ indice start comment + mov r7,#0 @ comment + mov r8,#0 @ indice write buffer +1: + ldrb r9,[r1,r6] @ load first byte of comment start +2: + ldrb r10,[r0,r5] @ load byte string + cmp r10,#0 @ end string ? + beq 20f + cmp r7,#1 @ comment + beq 6f + cmp r10,r9 @ compare first byte and byte string + bne 5f +3: + add r6,r6,#1 + ldrb r9,[r1,r6] @ load oher byte of comment start + cmp r9,#0 + beq 4f @ end comment ? + strb r10,[r3,r8] @ store byte in buffer + add r8,r8,#1 + cmp r8,r4 @ error size buffer ? + bge 99f + add r5,r5,#1 @ load byte string + ldrb r10,[r0,r5] + cmp r10,#0 @ end string ? + beq 20f + cmp r10,r9 @ compare byte + beq 3b @ loop other char start comment + strb r10,[r3,r8] @ else store char string + add r8,r8,#1 + cmp r8,r4 @ end buffer ? + bge 99f + add r5,r5,#1 @ increment indice string + mov r6,#0 @ raz indice start comment + b 1b +4: @ start comment found + sub r6,r6,#1 + sub r8,r8,r6 @ supp write byte buffer + mov r7,#1 @ comment + add r5,r5,#1 @ increment indice string + b 2b @ and loop +5: @ bytes inequals + strb r10,[r3,r8] @ store char string + add r8,r8,#1 + cmp r8,r4 @ end buffer ? + bge 99f + add r5,r5,#1 @ increment indice string + b 2b @ and loop +6: @ is comment + mov r6,#0 +8: + ldrb r9,[r2,r6] @ load end comment first char +9: + cmp r10,r9 @ equal byte string ? + bne 10f + add r5,r5,#1 + ldrb r10,[r0,r5] @ load other byte + cmp r10,#0 @ end string + beq 20f + add r6,r6,#1 + ldrb r9,[r2,r6] @ load other byte end comment + cmp r9,#0 @ end end comment ? + bne 9b @ no -> loop + @ comment end + mov r7,#0 @ raz comment + mov r6,#0 @ raz indice start comment + b 1b +10: @ comment not end + add r5,r5,#1 + b 2b + +20: + mov r10,#0 @ final zero + strb r10,[r3,r8] @ store char string + b 100f + +99: @ error + ldr r0,iAdrszMessBufferError + bl affichageMess + mov r0,#-1 +100: + pop {r1-r10,pc} + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Strip-block-comments/Delphi/strip-block-comments.delphi b/Task/Strip-block-comments/Delphi/strip-block-comments.pas similarity index 100% rename from Task/Strip-block-comments/Delphi/strip-block-comments.delphi rename to Task/Strip-block-comments/Delphi/strip-block-comments.pas diff --git a/Task/Strip-block-comments/Ed/strip-block-comments.ed b/Task/Strip-block-comments/Ed/strip-block-comments.ed new file mode 100644 index 0000000000..9392aa8d0f --- /dev/null +++ b/Task/Strip-block-comments/Ed/strip-block-comments.ed @@ -0,0 +1,19 @@ +# by Artyom Bologov +H +,p +# Join all the lines to make multi-line comments searchable +g/./s/$/|/ +,j +# A nice separator +a +---------------------- +. +p +d +# Remove blocks comments +# (faulty heuristic, searches for non-/ chars) +g/./s/\/\*[^/]*\*\///g +g/|/s//\ +/g +,p +Q diff --git a/Task/Strip-block-comments/Julia/strip-block-comments.julia b/Task/Strip-block-comments/Julia/strip-block-comments.jl similarity index 100% rename from Task/Strip-block-comments/Julia/strip-block-comments.julia rename to Task/Strip-block-comments/Julia/strip-block-comments.jl diff --git a/Task/Strip-block-comments/Kotlin/strip-block-comments.kotlin b/Task/Strip-block-comments/Kotlin/strip-block-comments.kts similarity index 100% rename from Task/Strip-block-comments/Kotlin/strip-block-comments.kotlin rename to Task/Strip-block-comments/Kotlin/strip-block-comments.kts diff --git a/Task/Strip-block-comments/Rust/strip-block-comments.rs b/Task/Strip-block-comments/Rust/strip-block-comments.rs new file mode 100644 index 0000000000..44268a21d8 --- /dev/null +++ b/Task/Strip-block-comments/Rust/strip-block-comments.rs @@ -0,0 +1,75 @@ +// Strips first nest of block comments +fn _commentstripper(mut txt: String, deliml: &str, delimr: &str) -> String { + let mut out = String::new(); + if txt.contains(deliml) { + let mut indx = txt.find(deliml).unwrap(); + out += &txt[..indx]; + txt = txt[indx + deliml.len()..].to_string(); + txt = _commentstripper(txt, deliml, delimr); + assert!(txt.contains(delimr), "Missing closing comment delimiter"); + indx = txt.find(delimr).unwrap(); + out += &txt[indx + delimr.len()..]; + } else { + out = txt; + } + return out; +} + +// Strips nests of block comments +fn commentstripper(mut txt: String, deliml: &str, delimr: &str) -> String { + while txt.contains(deliml) { + txt = _commentstripper(txt, deliml, delimr); + } + return txt.to_string(); +} + +fn main() { + let deliml = "/*"; + let delimr = "*/"; + + println!("\nNON-NESTED BLOCK COMMENT EXAMPLE:"); + let mut sample = r#" +/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ +function subroutine() { +a = /* inline comment */ b + c ; +} +/*/ <-- tricky comments */ + +/** +* Another comment. +*/ +function something() { +} +"# + .to_string(); + + println!("{}", commentstripper(sample, deliml, delimr)); + + println!("\nNESTED BLOCK COMMENT EXAMPLE:"); + sample = r#" +/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + *//* +function subroutine() { +a = /* inline comment */ b + c ; +} +/*/ <-- tricky comments */ +*/ +/** +* Another comment. +*/ +function something() { +} +"# + .to_string(); + + println!("{}", commentstripper(sample, deliml, delimr)); +} diff --git a/Task/Strip-block-comments/XPL0/strip-block-comments.xpl0 b/Task/Strip-block-comments/XPL0/strip-block-comments.xpl0 new file mode 100644 index 0000000000..cf9f046cdc --- /dev/null +++ b/Task/Strip-block-comments/XPL0/strip-block-comments.xpl0 @@ -0,0 +1,45 @@ +string 0; +proc Strip(Prog); \Show Prog with comments stripped out +char Prog; +int Ch, Showing; + + func GetCh; + [Ch:= Prog(0); + if Ch = 0 then exit; + Prog:= Prog+1; + ]; + +[Showing:= true; +loop [GetCh; + if Showing then + [if Ch = ^/ then + [GetCh; + if Ch = ^* then Showing:= false + else [ChOut(0, ^/); ChOut(0, Ch)] + ] + else ChOut(0, Ch); + ] + else [if Ch = ^* then + [GetCh; + if Ch =^/ then Showing:= true; + ]; + ]; + ]; +]; + +Strip(" /** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }") diff --git a/Task/Strip-comments-from-a-string/AArch64-Assembly/strip-comments-from-a-string.aarch64 b/Task/Strip-comments-from-a-string/AArch64-Assembly/strip-comments-from-a-string.aarch64 new file mode 100644 index 0000000000..ea410db254 --- /dev/null +++ b/Task/Strip-comments-from-a-string/AArch64-Assembly/strip-comments-from-a-string.aarch64 @@ -0,0 +1,99 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program Strip comments from a string */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" + +szString1: .asciz "apples, pears # and bananas" +szString2: .asciz "apples, pears ; and bananas" +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + + ldr x0,qAdrszString1 + mov x1,#'#' + bl suppComment + ldr x0,qAdrszString1 + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszString2 + mov x1,#';' + bl suppComment + ldr x0,qAdrszString1 + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszString1: .quad szString1 +qAdrszString2: .quad szString2 + +/******************************************************************/ +/* strip comment string */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains comment markers */ +/* x0 returns length of string */ +suppComment: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + mov x2,#0 // indice string +1: + ldrb w3,[x0,x2] + cmp x3,#0 // end string + csel x0,x2,x0,eq + beq 100f + cmp x3,x1 + cinc x2,x2,ne + bne 1b + mov x3,#0 + strb w3,[x0,x2] + mov x0,x2 +100: + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Strip-comments-from-a-string/ARM-Assembly/strip-comments-from-a-string.arm b/Task/Strip-comments-from-a-string/ARM-Assembly/strip-comments-from-a-string.arm new file mode 100644 index 0000000000..ca4975485c --- /dev/null +++ b/Task/Strip-comments-from-a-string/ARM-Assembly/strip-comments-from-a-string.arm @@ -0,0 +1,99 @@ +/* ARM assembly Raspberry PI */ +/* program Strip comments from a string */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" + +szString1: .asciz "apples, pears # and bananas" +szString2: .asciz "apples, pears ; and bananas" +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + + ldr r0,iAdrszString1 + mov r1,#'#' + bl suppComment + ldr r0,iAdrszString1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszString2 + mov r1,#';' + bl suppComment + ldr r0,iAdrszString1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszString1: .int szString1 +iAdrszString2: .int szString2 + +/******************************************************************/ +/* strip comment string */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains comment markers */ +/* r0 returns length of string */ +suppComment: + push {r1-r3,lr} @ save registers + mov r2,#0 @ indice string +1: + ldrb r3,[r0,r2] + cmp r3,#0 @ end string + moveq r0,r2 + beq 100f + cmp r3,r1 + addne r2,r2,#1 + bne 1b + mov r3,#0 + strb r3,[r0,r2] + mov r0,r2 +100: + pop {r1-r3,pc} + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.delphi b/Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.pas similarity index 100% rename from Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.delphi rename to Task/Strip-comments-from-a-string/Delphi/strip-comments-from-a-string.pas diff --git a/Task/Strip-comments-from-a-string/Ed/strip-comments-from-a-string.ed b/Task/Strip-comments-from-a-string/Ed/strip-comments-from-a-string.ed new file mode 100644 index 0000000000..aa090f95cf --- /dev/null +++ b/Task/Strip-comments-from-a-string/Ed/strip-comments-from-a-string.ed @@ -0,0 +1,12 @@ +# by Artyom Bologov +H +,p +# Remove the empty/spaced lines after comments +g/^.[[:space:]]*$/s/// +# Remove comments +g/\(.\)\(.*\)\1.*/s//\2/ +# Strip spaces off +g/^[[:space:]]\{1,\}\(.*\)/s//\1/ +g/\(.*\)[[:space:]]\{1,\}$/s//\1/ +,p +Q diff --git a/Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.julia b/Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.jl similarity index 100% rename from Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.julia rename to Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.jl diff --git a/Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kotlin b/Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kts similarity index 100% rename from Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kotlin rename to Task/Strip-comments-from-a-string/Kotlin/strip-comments-from-a-string.kts diff --git a/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ocaml b/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ml similarity index 100% rename from Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ocaml rename to Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-1.ml diff --git a/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ocaml b/Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ml similarity index 100% rename from Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ocaml rename to Task/Strip-comments-from-a-string/OCaml/strip-comments-from-a-string-2.ml diff --git a/Task/Strip-comments-from-a-string/Rust/strip-comments-from-a-string.rust b/Task/Strip-comments-from-a-string/Rust/strip-comments-from-a-string.rs similarity index 100% rename from Task/Strip-comments-from-a-string/Rust/strip-comments-from-a-string.rust rename to Task/Strip-comments-from-a-string/Rust/strip-comments-from-a-string.rs diff --git a/Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.ss b/Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.scm similarity index 100% rename from Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.ss rename to Task/Strip-comments-from-a-string/Scheme/strip-comments-from-a-string.scm diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Delphi/strip-control-codes-and-extended-characters-from-a-string.delphi b/Task/Strip-control-codes-and-extended-characters-from-a-string/Delphi/strip-control-codes-and-extended-characters-from-a-string.pas similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/Delphi/strip-control-codes-and-extended-characters-from-a-string.delphi rename to Task/Strip-control-codes-and-extended-characters-from-a-string/Delphi/strip-control-codes-and-extended-characters-from-a-string.pas diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Ed/strip-control-codes-and-extended-characters-from-a-string.ed b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ed/strip-control-codes-and-extended-characters-from-a-string.ed new file mode 100644 index 0000000000..c7bb1e0c7f --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ed/strip-control-codes-and-extended-characters-from-a-string.ed @@ -0,0 +1,10 @@ +# by Artyom Bologov +H +,l +,j +s/[[:cntrl:]]//g +y +x +2s/[^[:punct:]a-z0-9A-Z]//g +,p +Q diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.julia b/Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.jl similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.julia rename to Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.jl diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kotlin b/Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kts similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kotlin rename to Task/Strip-control-codes-and-extended-characters-from-a-string/Kotlin/strip-control-codes-and-extended-characters-from-a-string.kts diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/OCaml/strip-control-codes-and-extended-characters-from-a-string.ocaml b/Task/Strip-control-codes-and-extended-characters-from-a-string/OCaml/strip-control-codes-and-extended-characters-from-a-string.ml similarity index 100% rename from Task/Strip-control-codes-and-extended-characters-from-a-string/OCaml/strip-control-codes-and-extended-characters-from-a-string.ocaml rename to Task/Strip-control-codes-and-extended-characters-from-a-string/OCaml/strip-control-codes-and-extended-characters-from-a-string.ml diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/OmniMark/strip-control-codes-and-extended-characters-from-a-string.xom b/Task/Strip-control-codes-and-extended-characters-from-a-string/OmniMark/strip-control-codes-and-extended-characters-from-a-string.xom new file mode 100644 index 0000000000..e393872cb7 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/OmniMark/strip-control-codes-and-extended-characters-from-a-string.xom @@ -0,0 +1,21 @@ +process + local integer i initial {0} + local stream ae + open ae as buffer + repeat + put ae "b" % i when i <= 255 + increment i + exit when i > 255 + again + close ae + output 'Input (all ASCII and extended ASCII characters):%n%g(ae)' + output '%n%nWithout control characters (in ASCII <= 127):%n' + submit ae + output '%n%nWithout control characters and without extended ASCII (128-255):%n' + using group strip-extended-too submit ae + +group strip-extended-too + find (["%16r{80}" to "%16r{FF}"]) + +group #implied + find (["%16r{00}" to "%16r{1F}"] | ["%16r{7F}"]) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs b/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs new file mode 100644 index 0000000000..92f8c4b9dc --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs @@ -0,0 +1,10 @@ +fn stripped(tostrip: &str) -> String { + return tostrip + .chars() + .filter(|c| (*c as u32) < 127 && *c as u32 > 31) + .collect(); +} + +fn main() { + println!("{}", stripped("\x08a\x00b\n\rc\x0cd\u{00c3}")); +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AArch64-Assembly/strip-whitespace-from-a-string-top-and-tail.aarch64 b/Task/Strip-whitespace-from-a-string-Top-and-tail/AArch64-Assembly/strip-whitespace-from-a-string-top-and-tail.aarch64 new file mode 100644 index 0000000000..b42406c87b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/AArch64-Assembly/strip-whitespace-from-a-string-top-and-tail.aarch64 @@ -0,0 +1,237 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program Strip whitespace from a string */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +.equ BUFFERSIZE, 200 + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros64.inc" // for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 64 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessBufferError: .asciz "Error : Buffer too small !!\n" +szEndString: .asciz "<<<<" +szString1: .asciz " apples, pears # and bananas" +szString2: .asciz "apples, pears ; and bananas " +.equ LGSTRING2, . - szString2 +szString3: .asciz " \tapples, pears ; and bananas " +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr x0,qAdrszMessDebutPgm + bl affichageMess // start message + + ldr x0,qAdrszString1 + ldr x1,qAdrsBuffer + mov x2,#BUFFERSIZE + bl stripTail + cmp x0,#-1 + beq 1f + ldr x0,qAdrsBuffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess +1: + ldr x0,qAdrszString2 + mov x1,#LGSTRING2 + ldr x2,qAdrsBuffer + mov x3,#BUFFERSIZE + bl stripTop + cmp x0,#-1 + beq 2f + ldr x0,qAdrsBuffer + bl affichageMess + ldr x0,qAdrszEndString + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess +2: + ldr x0,qAdrszString3 + mov x1,#LGSTRING2 + ldr x2,qAdrsBuffer + mov x3,#BUFFERSIZE + bl stripSpaces + cmp x0,#-1 + beq 100f + ldr x0,qAdrsBuffer + bl affichageMess + ldr x0,qAdrszEndString + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessFinOK + bl affichageMess + +100: + mov x8,EXIT + svc #0 // system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessBufferError: .quad szMessBufferError +qAdrsBuffer: .quad sBuffer +qAdrszEndString: .quad szEndString +qAdrszString1: .quad szString1 +qAdrszString2: .quad szString2 +qAdrszString3: .quad szString3 + +/******************************************************************/ +/* strip leading space */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains buffer address */ +/* x2 contains buffer length maxi */ +/* x0 returns buffer length */ +stripTail: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x3,#0 // indice string + mov x4,#0 // indice buffer write + mov x6,#0 // spaces top +1: + ldrb w5,[x0,x3] + cmp x5,#0 // end string + beq 3f + cmp x6,#1 // end spaces + beq 2f + + cmp x5,#' ' // space ? + cinc x3,x3,eq // increment indice + beq 1b // and loop + cmp x5,#'\t' // tabulation ? + cinc x3,x3,eq // increment indice + beq 1b + mov x6,#1 // end first spaces +2: + strb w5,[x1,x4] // write byte + add x4,x4,#1 + cmp x4,x2 // error ? + bge 99f + add x3,x3,#1 + b 1b // loop +3: + strb w5,[x1,x4] // write byte final zero + add x0,x4,#1 + b 100f +99: // error + ldr x0,qAdrszMessBufferError + bl affichageMess + mov x0,#-1 +100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/******************************************************************/ +/* strip trailing space */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains length string +/* x2 contains buffer address */ +/* x3 contains buffer length maxi */ +/* x0 returns buffer length */ +stripTop: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x4,#0 // indice buffer write + mov x6,#0 // top last spaces + sub x1,x1,#1 // final zero +1: + ldrb w5,[x0,x1] // load last byte + cmp x6,#1 // end spaces? + beq 2f + sub x7,x1,1 + cmp x5,#' ' // space ? + csel x1,x7,x1,eq // decrement indice + beq 1b // and loop + cmp x5,#'\t' + csel x1,x7,x1,eq // decrement indice + beq 1b + mov x6,#0 // final zero + add x4,x1,#1 // increment last position not space + cmp x4,x3 // error ? + bge 99f + strb w6,[x2,x4] // write zero final + mov x7,x4 // save length + mov x6,#1 // end last spaces +2: // not space + mov x4,x1 // last position + strb w5,[x2,x4] // write byte + subs x3,x3,#1 + bgt 1b // and loop +3: + mov x0,x7 + b 100f +99: // error + ldr x0,qAdrszMessBufferError + bl affichageMess + mov x0,#-1 +100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // TODO: a completer + ret +/******************************************************************/ +/* strip leading and trailing spaces */ +/******************************************************************/ +/* x0 contains string address */ +/* x1 contains buffer address */ +/* x2 contains buffer length maxi */ +/* x0 returns buffer length */ +stripSpaces: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + sub sp,sp,x2 // reserve area on stack + mov x4,x1 // save buffer address + mov x5,x2 // save length + mov x1,sp // address temp buffer + mov x2,x5 + bl stripTail // strip leading spaces + cmp x0,#-1 // error ? + beq 100f + mov x1,x0 // new length string + mov x0,sp // temp buffer address + mov x1,x4 // buffer address + mov x2,x5 // maxi length + bl stripTop // stip trailing spaces +100: + add sp,sp,x5 // free area on stack + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // TODO: a completer + ret +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/ARM-Assembly/strip-whitespace-from-a-string-top-and-tail.arm b/Task/Strip-whitespace-from-a-string-Top-and-tail/ARM-Assembly/strip-whitespace-from-a-string-top-and-tail.arm new file mode 100644 index 0000000000..3b04472bbf --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/ARM-Assembly/strip-whitespace-from-a-string-top-and-tail.arm @@ -0,0 +1,221 @@ +/* ARM assembly Raspberry PI */ +/* program Strip whitespace from a string */ + +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ BUFFERSIZE, 200 + +/*******************************************/ +/* macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developper debugging + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessBufferError: .asciz "Error : Buffer too small !!\n" +szEndString: .asciz "<<<<" +szString1: .asciz " apples, pears # and bananas" +szString2: .asciz "apples, pears ; and bananas " +.equ LGSTRING2, . - szString2 +szString3: .asciz " \tapples, pears ; and bananas " +.align 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess @ start message + + ldr r0,iAdrszString1 + ldr r1,iAdrsBuffer + mov r2,#BUFFERSIZE + bl stripTail + cmp r0,#-1 + beq 1f + ldr r0,iAdrsBuffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess +1: + ldr r0,iAdrszString2 + mov r1,#LGSTRING2 + ldr r2,iAdrsBuffer + mov r3,#BUFFERSIZE + bl stripTop + cmp r0,#-1 + beq 2f + ldr r0,iAdrsBuffer + bl affichageMess + ldr r0,iAdrszEndString + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess +2: + ldr r0,iAdrszString3 + mov r1,#LGSTRING2 + ldr r2,iAdrsBuffer + mov r3,#BUFFERSIZE + bl stripSpaces + cmp r0,#-1 + beq 100f + ldr r0,iAdrsBuffer + bl affichageMess + ldr r0,iAdrszEndString + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: + mov r7,#EXIT @ program end + svc #0 @ system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessBufferError: .int szMessBufferError +iAdrsBuffer: .int sBuffer +iAdrszEndString: .int szEndString +iAdrszString1: .int szString1 +iAdrszString2: .int szString2 +iAdrszString3: .int szString3 + +/******************************************************************/ +/* strip leading space */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains buffer address */ +/* r2 contains buffer length maxi */ +/* r0 returns buffer length */ +stripTail: + push {r1-r6,lr} @ save registers + mov r3,#0 @ indice string + mov r4,#0 @ indice buffer write + mov r6,#0 @ spaces top +1: + ldrb r5,[r0,r3] + cmp r5,#0 @ end string + beq 3f + cmp r6,#1 @ end spaces + beq 2f + + cmp r5,#' ' @ space ? + addeq r3,r3,#1 @ increment indice + beq 1b @ and loop + cmp r5,#'\t' @ tabulation ? + addeq r3,r3,#1 + beq 1b + mov r6,#1 @ end first spaces +2: + strb r5,[r1,r4] @ write byte + add r4,r4,#1 + cmp r4,r2 @ error ? + bge 99f + add r3,r3,#1 + b 1b @ loop +3: + strb r5,[r1,r4] @ write byte final zero + add r0,r4,#1 + b 100f +99: @ error + ldr r0,iAdrszMessBufferError + bl affichageMess + mov r0,#-1 +100: + pop {r1-r6,pc} +/******************************************************************/ +/* strip trailing space */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains length string +/* r2 contains buffer address */ +/* r3 contains buffer length maxi */ +/* r0 returns buffer length */ +stripTop: + push {r1-r7,lr} @ save registers + mov r4,#0 @ indice buffer write + mov r6,#0 @ top last spaces + sub r1,r1,#1 @ final zero +1: + ldrb r5,[r0,r1] @ load last byte + cmp r6,#1 @ end spaces? + beq 2f + + cmp r5,#' ' @ space ? + subeq r1,r1,#1 @ decrement indice + beq 1b @ and loop + cmp r5,#'\t' + subeq r1,r1,#1 + beq 1b + mov r6,#0 @ final zero + add r4,r1,#1 @ increment last position not space + cmp r4,r3 @ error ? + bge 99f + strb r6,[r2,r4] @ write zero final + mov r7,r4 @ save length + mov r6,#1 @ end last spaces +2: @ not space + mov r4,r1 @ last position + strb r5,[r2,r4] @ write byte + subs r3,r3,#1 + bgt 1b @ and loop +3: + mov r0,r7 + b 100f +99: @ error + ldr r0,iAdrszMessBufferError + bl affichageMess + mov r0,#-1 +100: + pop {r1-r7,pc} +/******************************************************************/ +/* strip leading and trailing spaces */ +/******************************************************************/ +/* r0 contains string address */ +/* r1 contains buffer address */ +/* r2 contains buffer length maxi */ +/* r0 returns buffer length */ +stripSpaces: + push {r1-r7,lr} @ save registers + sub sp,sp,r2 @ reserve area on stack + mov r4,r1 @ save buffer address + mov r5,r2 @ save length + mov r1,sp @ address temp buffer + mov r2,r5 + bl stripTail @ strip leading spaces + cmp r0,#-1 @ error ? + beq 100f + mov r1,r0 @ new length string + mov r0,sp @ temp buffer address + mov r1,r4 @ buffer address + mov r2,r5 @ maxi length + bl stripTop @ stip trailing spaces +100: + add sp,sp,r5 @ free area on stack + pop {r1-r7,pc} +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.crystal b/Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.cr similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.crystal rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Crystal/strip-whitespace-from-a-string-top-and-tail.cr diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.delphi b/Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.pas similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.delphi rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Delphi/strip-whitespace-from-a-string-top-and-tail.pas diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ed/strip-whitespace-from-a-string-top-and-tail.ed b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ed/strip-whitespace-from-a-string-top-and-tail.ed new file mode 100644 index 0000000000..1bd97062ac --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ed/strip-whitespace-from-a-string-top-and-tail.ed @@ -0,0 +1,10 @@ +H +,p +,j +t0 +t0 +1s/^[[:space:]]*(.*)$/Leading whitespace removed: "\1"/ +2s/^(.*)(.*[^[:space:]])[[:space:]]*$/Trailing whitespace removed: "\1\2"/ +3s/^[[:space:]]*(.*[^[:space:]])[[:space:]]*$/Wrapping whitespace removed: "\1"/ +,p +Q diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir b/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.ex similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.ex diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.euphoria b/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.ex similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.euphoria rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.ex diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia b/Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.jl similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.julia rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Julia/strip-whitespace-from-a-string-top-and-tail.jl diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kotlin b/Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kts similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kotlin rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Kotlin/strip-whitespace-from-a-string-top-and-tail.kts diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Nu/strip-whitespace-from-a-string-top-and-tail.nu b/Task/Strip-whitespace-from-a-string-Top-and-tail/Nu/strip-whitespace-from-a-string-top-and-tail.nu new file mode 100644 index 0000000000..f3e6e8dd03 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Nu/strip-whitespace-from-a-string-top-and-tail.nu @@ -0,0 +1,8 @@ +# leading (left): +$text | str trim -l + +# trailing (right): +$text | str trim -r + +# both: +$text | str trim diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ocaml b/Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ml similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ocaml rename to Task/Strip-whitespace-from-a-string-Top-and-tail/OCaml/strip-whitespace-from-a-string-top-and-tail.ml diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PL-I-80/strip-whitespace-from-a-string-top-and-tail.pli b/Task/Strip-whitespace-from-a-string-Top-and-tail/PL-I-80/strip-whitespace-from-a-string-top-and-tail.pli new file mode 100644 index 0000000000..f799943fd5 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PL-I-80/strip-whitespace-from-a-string-top-and-tail.pli @@ -0,0 +1,43 @@ +trim_test: procedure options (main); + declare + test char(127) varying; + test = ' This is a test string '; + put skip edit ('orginal: |',test,'|') (a); + put skip edit ('ltrim : |',ltrim(test),'|') (a); + put skip edit ('rtrim : |',rtrim(test),'|') (a); + put skip edit ('trim : |',trim(test),'|') (a) ; + stop; + +/* return s with leading white space removed */ +ltrim: procedure (s) returns (char(127) varying); + declare + s char(127) varying, + (slen, i) fixed binary(15); + slen = length(s); + i = 1; + do while (i <= slen & substr(s,i,1) <= ' '); + i = i + 1; + end; + return (substr(s,i,slen)); +end ltrim; + +/* return s with trailing white space removed */ +rtrim: procedure (s) returns (char(127) varying); + declare + s char(127) varying, + (slen, i) fixed binary(15); + slen = length(s); + i = slen; + do while (i >= 1 & substr(s,i,1) <= ' '); + i = i - 1; + end; + return (substr(s,1,i)); +end rtrim; + +/* return s with leading and trailing white space removed */ +trim: procedure (s) returns (char(127) varying); + declare s char(127) varying; + return (ltrim(rtrim(s))); +end trim; + +end trim_test; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rs similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust rename to Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rs diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/S-BASIC/strip-whitespace-from-a-string-top-and-tail.basic b/Task/Strip-whitespace-from-a-string-Top-and-tail/S-BASIC/strip-whitespace-from-a-string-top-and-tail.basic new file mode 100644 index 0000000000..1e6dbe5335 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/S-BASIC/strip-whitespace-from-a-string-top-and-tail.basic @@ -0,0 +1,32 @@ +rem - remove leading white space from s +function ltrim(s = string) = string + var i, slen = integer + i = 1 + slen = len(s) + while i <= slen and mid(s, i, 1) <= " " do + i = i + 1 +end = right(s,i) + +rem - remove trailing white space from s +function rtrim(s = string) = string + var i, slen = integer + slen = len(s) + i = slen + while i > 0 and mid(s, i, 1) <= " " do + i = i - 1 +end = left$(s, i) + +rem - remove leading and trailing white space from s +function trim(s = string) = string +end = ltrim(rtrim(s)) + +rem - exercise the functions + +var test = string +test = " This is the test string " +print "original: |"; test; "|" +print "trim : |"; trim(test); "|" +print "rtrim : |"; rtrim(test); "|" +print "ltrim : |"; ltrim(test); "|" + +end diff --git a/Task/Strong-and-weak-primes/Delphi/strong-and-weak-primes.delphi b/Task/Strong-and-weak-primes/Delphi/strong-and-weak-primes.pas similarity index 100% rename from Task/Strong-and-weak-primes/Delphi/strong-and-weak-primes.delphi rename to Task/Strong-and-weak-primes/Delphi/strong-and-weak-primes.pas diff --git a/Task/Strong-and-weak-primes/Julia/strong-and-weak-primes.julia b/Task/Strong-and-weak-primes/Julia/strong-and-weak-primes.jl similarity index 100% rename from Task/Strong-and-weak-primes/Julia/strong-and-weak-primes.julia rename to Task/Strong-and-weak-primes/Julia/strong-and-weak-primes.jl diff --git a/Task/Strong-and-weak-primes/Kotlin/strong-and-weak-primes.kotlin b/Task/Strong-and-weak-primes/Kotlin/strong-and-weak-primes.kts similarity index 100% rename from Task/Strong-and-weak-primes/Kotlin/strong-and-weak-primes.kotlin rename to Task/Strong-and-weak-primes/Kotlin/strong-and-weak-primes.kts diff --git a/Task/Strong-and-weak-primes/Rust/strong-and-weak-primes.rust b/Task/Strong-and-weak-primes/Rust/strong-and-weak-primes.rs similarity index 100% rename from Task/Strong-and-weak-primes/Rust/strong-and-weak-primes.rust rename to Task/Strong-and-weak-primes/Rust/strong-and-weak-primes.rs diff --git a/Task/Subleq/Delphi/subleq.delphi b/Task/Subleq/Delphi/subleq.pas similarity index 100% rename from Task/Subleq/Delphi/subleq.delphi rename to Task/Subleq/Delphi/subleq.pas diff --git a/Task/Subleq/Julia/subleq-1.julia b/Task/Subleq/Julia/subleq-1.jl similarity index 100% rename from Task/Subleq/Julia/subleq-1.julia rename to Task/Subleq/Julia/subleq-1.jl diff --git a/Task/Subleq/Julia/subleq-2.julia b/Task/Subleq/Julia/subleq-2.jl similarity index 100% rename from Task/Subleq/Julia/subleq-2.julia rename to Task/Subleq/Julia/subleq-2.jl diff --git a/Task/Subleq/Kotlin/subleq.kotlin b/Task/Subleq/Kotlin/subleq.kts similarity index 100% rename from Task/Subleq/Kotlin/subleq.kotlin rename to Task/Subleq/Kotlin/subleq.kts diff --git a/Task/Substitution-cipher/Julia/substitution-cipher-1.julia b/Task/Substitution-cipher/Julia/substitution-cipher-1.jl similarity index 100% rename from Task/Substitution-cipher/Julia/substitution-cipher-1.julia rename to Task/Substitution-cipher/Julia/substitution-cipher-1.jl diff --git a/Task/Substitution-cipher/Julia/substitution-cipher-2.julia b/Task/Substitution-cipher/Julia/substitution-cipher-2.jl similarity index 100% rename from Task/Substitution-cipher/Julia/substitution-cipher-2.julia rename to Task/Substitution-cipher/Julia/substitution-cipher-2.jl diff --git a/Task/Substitution-cipher/Kotlin/substitution-cipher.kotlin b/Task/Substitution-cipher/Kotlin/substitution-cipher.kts similarity index 100% rename from Task/Substitution-cipher/Kotlin/substitution-cipher.kotlin rename to Task/Substitution-cipher/Kotlin/substitution-cipher.kts diff --git a/Task/Substitution-cipher/V-(Vlang)/substitution-cipher.v b/Task/Substitution-cipher/V-(Vlang)/substitution-cipher.v index 7b9210f8e9..fe39456465 100644 --- a/Task/Substitution-cipher/V-(Vlang)/substitution-cipher.v +++ b/Task/Substitution-cipher/V-(Vlang)/substitution-cipher.v @@ -1,5 +1,4 @@ -const -( +const ( key = "]kYV}(!7P\$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ" text = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!" ) diff --git a/Task/Substitution-cipher/XPL0/substitution-cipher.xpl0 b/Task/Substitution-cipher/XPL0/substitution-cipher.xpl0 new file mode 100644 index 0000000000..2d337bad57 --- /dev/null +++ b/Task/Substitution-cipher/XPL0/substitution-cipher.xpl0 @@ -0,0 +1,31 @@ +include xpllib; \for StrLen, Print +char Key; + +func Index(S, C); +char S, C, I; +[for I:= 0 to StrLen(S)-1 do + if S(I) = C then return I; +return -1; +]; + +func Encode(S); +char S, I; +[for I:= 0 to StrLen(S)-1 do + S(I):= Key(S(I)-32); +return S; +]; + +func Decode(S); +char S, I; +[for I:= 0 to StrLen(S)-1 do + S(I):= Index(Key, S(I)) + 32; +return S; +]; + +char S, Enc; +[Key:= "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs^"v*N[#wSl9zq2^^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\C1yxJ"; +S:= "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"; +Enc:= Encode(S); +Print("Encoded: %s\n", Enc); +Print("Decoded: %s\n", Decode(Enc)); +] diff --git a/Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.delphi b/Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.pas similarity index 100% rename from Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.delphi rename to Task/Substring-Top-and-tail/Delphi/substring-top-and-tail.pas diff --git a/Task/Substring-Top-and-tail/Ed/substring-top-and-tail.ed b/Task/Substring-Top-and-tail/Ed/substring-top-and-tail.ed new file mode 100644 index 0000000000..645e4f9dbf --- /dev/null +++ b/Task/Substring-Top-and-tail/Ed/substring-top-and-tail.ed @@ -0,0 +1,9 @@ +# by Artyom Bologov +H +t0 +t0 +1s/.\(.*\)/\1/ +2s/\(.*\)./\1/ +3s/.\(.*\)./\1/ +,p +Q diff --git a/Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.elixir b/Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.ex similarity index 100% rename from Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.elixir rename to Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.ex diff --git a/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.euphoria b/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.ex similarity index 100% rename from Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.euphoria rename to Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.ex diff --git a/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia b/Task/Substring-Top-and-tail/Julia/substring-top-and-tail.jl similarity index 100% rename from Task/Substring-Top-and-tail/Julia/substring-top-and-tail.julia rename to Task/Substring-Top-and-tail/Julia/substring-top-and-tail.jl diff --git a/Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kotlin b/Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kts similarity index 100% rename from Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kotlin rename to Task/Substring-Top-and-tail/Kotlin/substring-top-and-tail.kts diff --git a/Task/Substring-Top-and-tail/Nu/substring-top-and-tail.nu b/Task/Substring-Top-and-tail/Nu/substring-top-and-tail.nu new file mode 100644 index 0000000000..2a26661e51 --- /dev/null +++ b/Task/Substring-Top-and-tail/Nu/substring-top-and-tail.nu @@ -0,0 +1,6 @@ +[ + 1.. + ..-2 + 1..-2 +] +| each {|range| '>test<' | str substring $range } diff --git a/Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ocaml b/Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ml similarity index 100% rename from Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ocaml rename to Task/Substring-Top-and-tail/OCaml/substring-top-and-tail.ml diff --git a/Task/Substring-Top-and-tail/OmniMark/substring-top-and-tail-1.xom b/Task/Substring-Top-and-tail/OmniMark/substring-top-and-tail-1.xom new file mode 100644 index 0000000000..744227f0fd --- /dev/null +++ b/Task/Substring-Top-and-tail/OmniMark/substring-top-and-tail-1.xom @@ -0,0 +1,17 @@ +process + local stream s variable initial {'brooms', 'hit'} + repeat over s + output '---------------------%nWord: %g(s)%n' + do scan s + match any-text any-text+ => firstremoved + output 'First removed: %x(firstremoved)%n' + done + do scan s + match ((lookahead not (any-text value-end)) any)+ => lastremoved + output 'Last removed: %x(lastremoved)%n' + done + do scan s + match any-text ((lookahead not (any-text value-end)) any)+ => bothremoved + output 'Both removed: %x(bothremoved)%n' + done + again diff --git a/Task/Substring-Top-and-tail/OmniMark/substring-top-and-tail-2.xom b/Task/Substring-Top-and-tail/OmniMark/substring-top-and-tail-2.xom new file mode 100644 index 0000000000..c8801a25a5 --- /dev/null +++ b/Task/Substring-Top-and-tail/OmniMark/substring-top-and-tail-2.xom @@ -0,0 +1,35 @@ +include "utf8pat.xin" + +define stream function ucps (value stream chars) as + local integer num + local stream unicodes + open unicodes as buffer + repeat scan chars + match utf8-char => s-char + set num to utf8-char-number(s-char) + put unicodes 'U+%u16r4fzd(num) ' + again + close unicodes + return unicodes + +process + local stream s variable initial {'brooms', '𝓱𝓲𝓽', 'là'} + repeat over s + output '----------------------------------------------------------------%n' + output 'Word: %g(s)%n ' || ucps(s) || '%n' + do scan s + match utf8-char utf8-char+ => firstremoved + output 'First removed: %x(firstremoved)%n ' + output ucps(firstremoved) || '%n' + done + do scan s + match ((lookahead not (utf8-char value-end)) any)+ => lastremoved + output 'Last removed: %x(lastremoved)%n ' + output ucps(lastremoved) || '%n' + done + do scan s + match utf8-char ((lookahead not (utf8-char value-end)) any)+ => bothremoved + output 'Both removed: %x(bothremoved)%n ' + output ucps(bothremoved) || '%n' + done + again diff --git a/Task/Substring-Top-and-tail/Rust/substring-top-and-tail-1.rust b/Task/Substring-Top-and-tail/Rust/substring-top-and-tail-1.rs similarity index 100% rename from Task/Substring-Top-and-tail/Rust/substring-top-and-tail-1.rust rename to Task/Substring-Top-and-tail/Rust/substring-top-and-tail-1.rs diff --git a/Task/Substring-Top-and-tail/Rust/substring-top-and-tail-2.rust b/Task/Substring-Top-and-tail/Rust/substring-top-and-tail-2.rs similarity index 100% rename from Task/Substring-Top-and-tail/Rust/substring-top-and-tail-2.rust rename to Task/Substring-Top-and-tail/Rust/substring-top-and-tail-2.rs diff --git a/Task/Substring-Top-and-tail/Scheme/substring-top-and-tail.ss b/Task/Substring-Top-and-tail/Scheme/substring-top-and-tail.scm similarity index 100% rename from Task/Substring-Top-and-tail/Scheme/substring-top-and-tail.ss rename to Task/Substring-Top-and-tail/Scheme/substring-top-and-tail.scm diff --git a/Task/Substring/Crystal/substring.crystal b/Task/Substring/Crystal/substring.cr similarity index 100% rename from Task/Substring/Crystal/substring.crystal rename to Task/Substring/Crystal/substring.cr diff --git a/Task/Substring/Delphi/substring.delphi b/Task/Substring/Delphi/substring.pas similarity index 100% rename from Task/Substring/Delphi/substring.delphi rename to Task/Substring/Delphi/substring.pas diff --git a/Task/Substring/Ed/substring.ed b/Task/Substring/Ed/substring.ed new file mode 100644 index 0000000000..0d3af2e5ba --- /dev/null +++ b/Task/Substring/Ed/substring.ed @@ -0,0 +1,13 @@ +# by Artyom Bologov +H +t0 +t0 +t0 +t0 +1s/..\(.\{2\}\).*/\1/ +2s/..\(.*\)/\1/ +3s/.$// +4s/.*\(c.\{2\}\).*/\1/ +5s/.*\(cd.\{3\}\).*/\1/ +,p +Q diff --git a/Task/Substring/Elixir/substring.elixir b/Task/Substring/Elixir/substring.ex similarity index 100% rename from Task/Substring/Elixir/substring.elixir rename to Task/Substring/Elixir/substring.ex diff --git a/Task/Substring/Euphoria/substring.euphoria b/Task/Substring/Euphoria/substring.ex similarity index 100% rename from Task/Substring/Euphoria/substring.euphoria rename to Task/Substring/Euphoria/substring.ex diff --git a/Task/Substring/Julia/substring.julia b/Task/Substring/Julia/substring.jl similarity index 100% rename from Task/Substring/Julia/substring.julia rename to Task/Substring/Julia/substring.jl diff --git a/Task/Substring/Kotlin/substring.kotlin b/Task/Substring/Kotlin/substring.kts similarity index 100% rename from Task/Substring/Kotlin/substring.kotlin rename to Task/Substring/Kotlin/substring.kts diff --git a/Task/Substring/OCaml/substring.ocaml b/Task/Substring/OCaml/substring.ml similarity index 100% rename from Task/Substring/OCaml/substring.ocaml rename to Task/Substring/OCaml/substring.ml diff --git a/Task/Substring/OmniMark/substring.xom b/Task/Substring/OmniMark/substring.xom new file mode 100644 index 0000000000..023a077eba --- /dev/null +++ b/Task/Substring/OmniMark/substring.xom @@ -0,0 +1,37 @@ +macro utf8-char is + (["%16r{00}" to "%16r{7F}"] | + ["%16r{C0}" to "%16r{DF}"] ["%16r{80}" to "%16r{BF}"] | + ["%16r{E0}" to "%16r{EF}"] ["%16r{80}" to "%16r{BF}"] {2} | + ["%16r{F0}" to "%16r{F7}"] ["%16r{80}" to "%16r{BF}"] {3}) macro-end + +process + local stream s initial {'This 𝓲𝓼 the 𝓞𝓶𝓷𝓲𝓜𝓪𝓻𝓴 solution.'} + using group StartingFrom_n_CharactersInAndOf_m_Length submit s + using group StartingFrom_n_charactersInUpToTheEndOfTheString submit s + using group WholeStringMinusTheLastCharacter submit s + using group StartingFromKnownCharacterAndOf_m_Length submit s + using group StartingFromKnownSubstringAndOf_m_Length submit s + +group StartingFrom_n_CharactersInAndOf_m_Length + find value-start utf8-char{12} utf8-char{8} => p + output p || '%n' ; outputs characters 13 to 20: 𝓞𝓶𝓷𝓲𝓜𝓪𝓻𝓴 + +group StartingFrom_n_charactersInUpToTheEndOfTheString + find value-start utf8-char{12} utf8-char+ => p + output p || '%n' ; outputs characters 13 to last: 𝓞𝓶𝓷𝓲𝓜𝓪𝓻𝓴 solution. + +group WholeStringMinusTheLastCharacter + find value-start ((lookahead not (utf8-char value-end)) utf8-char)+ => p + output p || '%n' ; outputs characters 1 to (last - 1), so without the . + +group StartingFromKnownCharacterAndOf_m_Length + find 'T' utf8-char{3} => p + output p || '%n' ; outputs his following T + +group StartingFromKnownSubstringAndOf_m_Length + find '𝓞𝓶𝓷𝓲𝓜' utf8-char{3} => p + output p || '%n' ; outputs 𝓪𝓻𝓴 following 𝓞𝓶𝓷𝓲𝓜 + +group #implied + find utf8-char + ; ensures no other characters go to the output diff --git a/Task/Substring/Rust/substring.rust b/Task/Substring/Rust/substring.rs similarity index 100% rename from Task/Substring/Rust/substring.rust rename to Task/Substring/Rust/substring.rs diff --git a/Task/Substring/Scheme/substring.ss b/Task/Substring/Scheme/substring.scm similarity index 100% rename from Task/Substring/Scheme/substring.ss rename to Task/Substring/Scheme/substring.scm diff --git a/Task/Subtractive-generator/Elixir/subtractive-generator.elixir b/Task/Subtractive-generator/Elixir/subtractive-generator.ex similarity index 100% rename from Task/Subtractive-generator/Elixir/subtractive-generator.elixir rename to Task/Subtractive-generator/Elixir/subtractive-generator.ex diff --git a/Task/Subtractive-generator/Julia/subtractive-generator.julia b/Task/Subtractive-generator/Julia/subtractive-generator.jl similarity index 100% rename from Task/Subtractive-generator/Julia/subtractive-generator.julia rename to Task/Subtractive-generator/Julia/subtractive-generator.jl diff --git a/Task/Subtractive-generator/Kotlin/subtractive-generator.kotlin b/Task/Subtractive-generator/Kotlin/subtractive-generator.kts similarity index 100% rename from Task/Subtractive-generator/Kotlin/subtractive-generator.kotlin rename to Task/Subtractive-generator/Kotlin/subtractive-generator.kts diff --git a/Task/Subtractive-generator/OCaml/subtractive-generator.ocaml b/Task/Subtractive-generator/OCaml/subtractive-generator.ml similarity index 100% rename from Task/Subtractive-generator/OCaml/subtractive-generator.ocaml rename to Task/Subtractive-generator/OCaml/subtractive-generator.ml diff --git a/Task/Subtractive-generator/Rust/subtractive-generator.rust b/Task/Subtractive-generator/Rust/subtractive-generator.rs similarity index 100% rename from Task/Subtractive-generator/Rust/subtractive-generator.rust rename to Task/Subtractive-generator/Rust/subtractive-generator.rs diff --git a/Task/Successive-prime-differences/Delphi/successive-prime-differences.delphi b/Task/Successive-prime-differences/Delphi/successive-prime-differences.pas similarity index 100% rename from Task/Successive-prime-differences/Delphi/successive-prime-differences.delphi rename to Task/Successive-prime-differences/Delphi/successive-prime-differences.pas diff --git a/Task/Successive-prime-differences/Julia/successive-prime-differences.julia b/Task/Successive-prime-differences/Julia/successive-prime-differences.jl similarity index 100% rename from Task/Successive-prime-differences/Julia/successive-prime-differences.julia rename to Task/Successive-prime-differences/Julia/successive-prime-differences.jl diff --git a/Task/Successive-prime-differences/Kotlin/successive-prime-differences.kotlin b/Task/Successive-prime-differences/Kotlin/successive-prime-differences.kts similarity index 100% rename from Task/Successive-prime-differences/Kotlin/successive-prime-differences.kotlin rename to Task/Successive-prime-differences/Kotlin/successive-prime-differences.kts diff --git a/Task/Successive-prime-differences/Rust/successive-prime-differences.rust b/Task/Successive-prime-differences/Rust/successive-prime-differences.rs similarity index 100% rename from Task/Successive-prime-differences/Rust/successive-prime-differences.rust rename to Task/Successive-prime-differences/Rust/successive-prime-differences.rs diff --git a/Task/Sudan-function/Asymptote/sudan-function.asymptote b/Task/Sudan-function/Asymptote/sudan-function.asymptote new file mode 100644 index 0000000000..042b9acaa9 --- /dev/null +++ b/Task/Sudan-function/Asymptote/sudan-function.asymptote @@ -0,0 +1,25 @@ +int F(int n, int x, int y) { + if (n == 0) return x + y; + if (y == 0) return x; + return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y); +} + +for (int n = 0; n <= 1; ++n) { + write("Values of F(", n, suffix=none); + write(", x, y ):"); + write("-----------------------------"); + for (int y = 0; y <= 6; ++y) { + write(y, suffix=none); + write(" |", suffix=none); + for (int x = 0; x <= 5; ++x) { + write(" ", F(n, x, y), suffix=none); + } + write(); + } + write(); +} +write("F(0,0,0) = ", F(0, 0, 0)); +write("F(1,3,3) = ", F(1, 3, 3)); +write("F(2,1,1) = ", F(2, 1, 1)); +write("F(3,1,1) = ", F(3, 1, 1)); +write("F(2,2,1) = ", F(2, 2, 1)); diff --git a/Task/Sudan-function/Chipmunk-Basic/sudan-function.basic b/Task/Sudan-function/Chipmunk-Basic/sudan-function.basic new file mode 100644 index 0000000000..33f6fe8a69 --- /dev/null +++ b/Task/Sudan-function/Chipmunk-Basic/sudan-function.basic @@ -0,0 +1,23 @@ +100 sub f(n,x,y) +110 if n = 0 then f = x+y : exit sub +120 if y = 0 then f = x : exit sub +130 f = f(n-1,f(n,x,y-1),f(n,x,y-1)+y) +140 end sub +150 for n = 0 to 1 +160 print using " Values of F(#, x, y ):";n +170 print " y/x 0 1 2 3 4 5" +180 print " -----------------------------" +190 for y = 0 to 6 +200 print y;" |"; +210 for x = 0 to 5 +220 print using "####";f(n,x,y); +230 next x +240 print +250 next y +260 print +270 next n +280 print "F(0,0,0) = ";f(0,0,0) +290 print "F(1,3,3) = ";f(1,3,3) +300 print "F(2,1,1) = ";f(2,1,1) +310 print "F(3,1,1) = ";f(3,1,1) +320 print "F(2,2,1) = ";f(2,2,1) diff --git a/Task/Sudan-function/Delphi/sudan-function.delphi b/Task/Sudan-function/Delphi/sudan-function.pas similarity index 100% rename from Task/Sudan-function/Delphi/sudan-function.delphi rename to Task/Sudan-function/Delphi/sudan-function.pas diff --git a/Task/Sudan-function/Julia/sudan-function.julia b/Task/Sudan-function/Julia/sudan-function.jl similarity index 100% rename from Task/Sudan-function/Julia/sudan-function.julia rename to Task/Sudan-function/Julia/sudan-function.jl diff --git a/Task/Sudan-function/Mathematica/sudan-function.math b/Task/Sudan-function/Mathematica/sudan-function.math new file mode 100644 index 0000000000..36ec4e1a4d --- /dev/null +++ b/Task/Sudan-function/Mathematica/sudan-function.math @@ -0,0 +1,9 @@ +ClearAll[sudan]; + +sudan[0, x_Integer?NonNegative, y_Integer?NonNegative] := x + y; +sudan[n_Integer?NonNegative, y_Integer?NonNegative, 0] := y; +sudan[n_Integer?NonNegative, x_Integer?NonNegative, + y_Integer?NonNegative] := + sudan[n - 1, sudan[n, x, y - 1], sudan[n, x, y - 1] + y]; + +sudan @@@ {{0, 0, 0}, {1, 1, 1}, {1, 3, 3}, {2, 1, 1}, {2, 2, 1}, {3, 1, 1}} diff --git a/Task/Sudan-function/OCaml/sudan-function.ocaml b/Task/Sudan-function/OCaml/sudan-function.ml similarity index 100% rename from Task/Sudan-function/OCaml/sudan-function.ocaml rename to Task/Sudan-function/OCaml/sudan-function.ml diff --git a/Task/Sudan-function/OxygenBasic/sudan-function.basic b/Task/Sudan-function/OxygenBasic/sudan-function.basic new file mode 100644 index 0000000000..1c21cd0124 --- /dev/null +++ b/Task/Sudan-function/OxygenBasic/sudan-function.basic @@ -0,0 +1,37 @@ +uses console +' +function F(int n, x, y) as int + if n = 0 then + function = x + y + exit function + endif + if y = 0 then + function = x + exit function + endif + function = F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y) +end function +' +int n, x, y +for n = 0 to 1 + printl " Values of F(" n ", x, y ):" + printl " y/x 0 1 2 3 4 5" + printl string(52, "-") + for y = 0 to 6 + print " " y " |" tab + for x = 0 to 5 + print F(n, x, y) tab + next x + printl + next y + printl +next n +' +printl "F(0,0,0) = " F(0, 0, 0) +printl "F(1,3,3) = " F(1, 3, 3) +printl "F(2,1,1) = " F(2, 1, 1) +printl "F(3,1,1) = " F(3, 1, 1) +printl "F(2,2,1) = " F(2, 2, 1) + +printl cr "Enter ..." +waitkey diff --git a/Task/Sudoku/Crystal/sudoku.crystal b/Task/Sudoku/Crystal/sudoku.cr similarity index 100% rename from Task/Sudoku/Crystal/sudoku.crystal rename to Task/Sudoku/Crystal/sudoku.cr diff --git a/Task/Sudoku/Delphi/sudoku-1.delphi b/Task/Sudoku/Delphi/sudoku-1.pas similarity index 100% rename from Task/Sudoku/Delphi/sudoku-1.delphi rename to Task/Sudoku/Delphi/sudoku-1.pas diff --git a/Task/Sudoku/Delphi/sudoku-2.delphi b/Task/Sudoku/Delphi/sudoku-2.pas similarity index 100% rename from Task/Sudoku/Delphi/sudoku-2.delphi rename to Task/Sudoku/Delphi/sudoku-2.pas diff --git a/Task/Sudoku/Elixir/sudoku.elixir b/Task/Sudoku/Elixir/sudoku.ex similarity index 100% rename from Task/Sudoku/Elixir/sudoku.elixir rename to Task/Sudoku/Elixir/sudoku.ex diff --git a/Task/Sudoku/Julia/sudoku.julia b/Task/Sudoku/Julia/sudoku.jl similarity index 100% rename from Task/Sudoku/Julia/sudoku.julia rename to Task/Sudoku/Julia/sudoku.jl diff --git a/Task/Sudoku/Kotlin/sudoku.kotlin b/Task/Sudoku/Kotlin/sudoku.kts similarity index 100% rename from Task/Sudoku/Kotlin/sudoku.kotlin rename to Task/Sudoku/Kotlin/sudoku.kts diff --git a/Task/Sudoku/OCaml/sudoku.ocaml b/Task/Sudoku/OCaml/sudoku.ml similarity index 100% rename from Task/Sudoku/OCaml/sudoku.ocaml rename to Task/Sudoku/OCaml/sudoku.ml diff --git a/Task/Sudoku/Rust/sudoku.rust b/Task/Sudoku/Rust/sudoku.rs similarity index 100% rename from Task/Sudoku/Rust/sudoku.rust rename to Task/Sudoku/Rust/sudoku.rs diff --git a/Task/Suffixation-of-decimal-numbers/Julia/suffixation-of-decimal-numbers.julia b/Task/Suffixation-of-decimal-numbers/Julia/suffixation-of-decimal-numbers.jl similarity index 100% rename from Task/Suffixation-of-decimal-numbers/Julia/suffixation-of-decimal-numbers.julia rename to Task/Suffixation-of-decimal-numbers/Julia/suffixation-of-decimal-numbers.jl diff --git a/Task/Suffixation-of-decimal-numbers/Rust/suffixation-of-decimal-numbers.rs b/Task/Suffixation-of-decimal-numbers/Rust/suffixation-of-decimal-numbers.rs new file mode 100644 index 0000000000..03b38b0f73 --- /dev/null +++ b/Task/Suffixation-of-decimal-numbers/Rust/suffixation-of-decimal-numbers.rs @@ -0,0 +1,86 @@ +use astro_float::{BigFloat, Consts, RoundingMode}; +use itertools::Itertools; +use std::cmp::min; +use std::str::FromStr; + +const SUFFIXES: [&str; 14] = [ + "", "K", "M", "G", "T", "P", "E", "Z", "Y", "X", "W", "V", "U", "googol", +]; + +// Do the divisions in BigFloat, then convert the quotients to f64 for formatting +fn suffize(input: &str, digits: usize, base: usize) -> String { + let mut num = input.to_string(); + let numchars = num.chars().collect_vec(); + let exponent_distance = if base == 2 { 10 } else { 3 }; + let magnitude; + let suffix_index; + let mut num_str; + num = num.replace(",", ""); + let num_sign = if "+-".contains(numchars[0]) { + numchars[0].to_string() + } else { + "".to_string() + }; + let mut big_consts = Consts::new().expect("Constants cache initialized"); + let mut fnum = BigFloat::from_str(num.as_str()).unwrap().abs(); + let goog = BigFloat::from_str("1e100").unwrap(); + if base == 10 && fnum >= goog { + suffix_index = 13; + fnum = fnum.div(&goog, 30, RoundingMode::ToEven); + } else if fnum > BigFloat::from(1) { + let temp = format!( + "{}", + fnum.log( + &BigFloat::from(base as i32), + 30, + RoundingMode::ToEven, + &mut big_consts, + ) + .int() + ); + magnitude = f64::from_str(&temp).unwrap().round() as usize; + suffix_index = min(magnitude / exponent_distance, 12); + fnum = fnum.div( + &BigFloat::from(base as i32).powi( + exponent_distance * suffix_index, + 30, + RoundingMode::ToEven, + ), + 30, + RoundingMode::ToEven, + ); + } else { + suffix_index = 0; + } + let fnum64 = f64::from_str(format!("{}", fnum).as_str()).unwrap(); + if digits != 0 { + num_str = format!("{:.*}", digits, fnum64); + } else { + num_str = format!("{:}", fnum64.round()); + let mut s = num_str.strip_suffix("0").unwrap_or(num_str.as_str()); + s = s.strip_suffix(".").unwrap_or(num_str.as_str()); + num_str = s.to_string(); + } + return num_sign + + num_str.as_str() + + SUFFIXES[suffix_index] + + (if base == 2 { "i" } else { "" }); +} + +fn main() { + let tests = [ + ("87,654,321", 3, 10), + ("-998,877,665,544,332,211,000", 3, 10), + ("+112,233", 0, 10), + ("16,777,216", 1, 10), + ("456,789,100,000,000", 2, 10), + ("456,789,100,000,000", 2, 10), + ("456,789,100,000,000", 5, 2), + ("456,789,100,000.000e+00", 0, 10), + ("+16777216", 0, 2), + ("1.2e101", 0, 10), + ]; + for t in tests { + println!("{:>30} {:>2} {:>2} : {}", t.0, t.1, t.2, suffize(t.0, t.1, t.2)) + } +} diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.cr similarity index 100% rename from Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.crystal rename to Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-1.cr diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.cr similarity index 100% rename from Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.crystal rename to Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-2.cr diff --git a/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.crystal b/Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.cr similarity index 100% rename from Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.crystal rename to Task/Sum-and-product-of-an-array/Crystal/sum-and-product-of-an-array-3.cr diff --git a/Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.delphi b/Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.pas similarity index 100% rename from Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.delphi rename to Task/Sum-and-product-of-an-array/Delphi/sum-and-product-of-an-array.pas diff --git a/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.elixir b/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.ex similarity index 100% rename from Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.elixir rename to Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.ex diff --git a/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.elixir b/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.ex similarity index 100% rename from Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.elixir rename to Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.ex diff --git a/Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.euphoria b/Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.ex similarity index 100% rename from Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.euphoria rename to Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.ex diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs index b170853913..b69401289e 100644 --- a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs @@ -1,6 +1,10 @@ -import Data.Array - -values = listArray (1,10) [1..10] - -s = sum . elems $ values -p = product . elems $ values +main :: IO () +main = + mapM_ + print + ( fmap + ($ [1 .. 10]) + [ foldr (+) 0, + foldr (*) 1 + ] + ) diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs index 5bf978fafe..b170853913 100644 --- a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-3.hs @@ -1,4 +1,6 @@ -import Data.Array (listArray, elems) +import Data.Array -main :: IO () -main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]] +values = listArray (1,10) [1..10] + +s = sum . elems $ values +p = product . elems $ values diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-4.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-4.hs new file mode 100644 index 0000000000..5bf978fafe --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-4.hs @@ -0,0 +1,4 @@ +import Data.Array (listArray, elems) + +main :: IO () +main = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]] diff --git a/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.jl similarity index 100% rename from Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia rename to Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.jl diff --git a/Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kotlin b/Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kts similarity index 100% rename from Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kotlin rename to Task/Sum-and-product-of-an-array/Kotlin/sum-and-product-of-an-array.kts diff --git a/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array.l b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-1.l similarity index 100% rename from Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array.l rename to Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-1.l diff --git a/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-2.l b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-2.l new file mode 100644 index 0000000000..f3e4acca77 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-2.l @@ -0,0 +1,3 @@ +(let (a (array 5 (sequence 1 5))) + (println "Sum: " (apply + a)) + (println "Product: " (apply * a))) diff --git a/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-3.l b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-3.l new file mode 100644 index 0000000000..59a4684156 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array-3.l @@ -0,0 +1,9 @@ +;; 2-dimensional array. +(let (ary2d (array 4 5 (sequence 1 9 0.25))) + (dolist (row ary2d) + (print "Row " $idx ": ") + (dolist (x row) (print (format "%6.2f" x))) + (println)) + (println) + (println (apply add (flat (array-list ary2d)))) + (println (apply mul (flat (array-list ary2d))))) diff --git a/Task/Sum-and-product-of-an-array/Nu/sum-and-product-of-an-array.nu b/Task/Sum-and-product-of-an-array/Nu/sum-and-product-of-an-array.nu new file mode 100644 index 0000000000..44da704fad --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Nu/sum-and-product-of-an-array.nu @@ -0,0 +1,3 @@ +const $v = [2 3 4 5 6] +$v | math sum | print +$v | math product | print diff --git a/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ocaml b/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ml similarity index 100% rename from Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ocaml rename to Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-1.ml diff --git a/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ocaml b/Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ml similarity index 100% rename from Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ocaml rename to Task/Sum-and-product-of-an-array/OCaml/sum-and-product-of-an-array-2.ml diff --git a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rs similarity index 100% rename from Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust rename to Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rs diff --git a/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.ss b/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.scm similarity index 100% rename from Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.ss rename to Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-1.scm diff --git a/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.ss b/Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.scm similarity index 100% rename from Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.ss rename to Task/Sum-and-product-of-an-array/Scheme/sum-and-product-of-an-array-2.scm diff --git a/Task/Sum-and-product-puzzle/Elixir/sum-and-product-puzzle.elixir b/Task/Sum-and-product-puzzle/Elixir/sum-and-product-puzzle.ex similarity index 100% rename from Task/Sum-and-product-puzzle/Elixir/sum-and-product-puzzle.elixir rename to Task/Sum-and-product-puzzle/Elixir/sum-and-product-puzzle.ex diff --git a/Task/Sum-and-product-puzzle/Julia/sum-and-product-puzzle.julia b/Task/Sum-and-product-puzzle/Julia/sum-and-product-puzzle.jl similarity index 100% rename from Task/Sum-and-product-puzzle/Julia/sum-and-product-puzzle.julia rename to Task/Sum-and-product-puzzle/Julia/sum-and-product-puzzle.jl diff --git a/Task/Sum-and-product-puzzle/Kotlin/sum-and-product-puzzle.kotlin b/Task/Sum-and-product-puzzle/Kotlin/sum-and-product-puzzle.kts similarity index 100% rename from Task/Sum-and-product-puzzle/Kotlin/sum-and-product-puzzle.kotlin rename to Task/Sum-and-product-puzzle/Kotlin/sum-and-product-puzzle.kts 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.rs similarity index 100% rename from Task/Sum-and-product-puzzle/Rust/sum-and-product-puzzle.rust rename to Task/Sum-and-product-puzzle/Rust/sum-and-product-puzzle.rs diff --git a/Task/Sum-and-product-puzzle/Scheme/sum-and-product-puzzle.ss b/Task/Sum-and-product-puzzle/Scheme/sum-and-product-puzzle.scm similarity index 100% rename from Task/Sum-and-product-puzzle/Scheme/sum-and-product-puzzle.ss rename to Task/Sum-and-product-puzzle/Scheme/sum-and-product-puzzle.scm diff --git a/Task/Sum-digits-of-an-integer/Crystal/sum-digits-of-an-integer.crystal b/Task/Sum-digits-of-an-integer/Crystal/sum-digits-of-an-integer.cr similarity index 100% rename from Task/Sum-digits-of-an-integer/Crystal/sum-digits-of-an-integer.crystal rename to Task/Sum-digits-of-an-integer/Crystal/sum-digits-of-an-integer.cr diff --git a/Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.elixir b/Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.ex similarity index 100% rename from Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.elixir rename to Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.ex diff --git a/Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.julia b/Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.jl similarity index 100% rename from Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.julia rename to Task/Sum-digits-of-an-integer/Julia/sum-digits-of-an-integer.jl diff --git a/Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kotlin b/Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kts similarity index 100% rename from Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kotlin rename to Task/Sum-digits-of-an-integer/Kotlin/sum-digits-of-an-integer.kts diff --git a/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer.nu b/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer.nu new file mode 100644 index 0000000000..fab7bfee7d --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer.nu @@ -0,0 +1,5 @@ +def digits [r: int] { + generate {|n| if $n < $r { {out: $n} } else {out: ($n mod $r) next: ($n // $r)} } $in +} + +[[0 2] [1 10] [1234 10] [0xfe 16] [0xf0e 16]] | each {|p| $p.0 | digits $p.1 | math sum } diff --git a/Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ocaml b/Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ml similarity index 100% rename from Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ocaml rename to Task/Sum-digits-of-an-integer/OCaml/sum-digits-of-an-integer.ml diff --git a/Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rust b/Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rs similarity index 100% rename from Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rust rename to Task/Sum-digits-of-an-integer/Rust/sum-digits-of-an-integer.rs diff --git a/Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.ss b/Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.scm similarity index 100% rename from Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.ss rename to Task/Sum-digits-of-an-integer/Scheme/sum-digits-of-an-integer.scm diff --git a/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-1.crystal b/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-1.cr similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-1.crystal rename to Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-1.cr diff --git a/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-2.crystal b/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-2.cr similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-2.crystal rename to Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-2.cr diff --git a/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-3.crystal b/Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-3.cr similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-3.crystal rename to Task/Sum-multiples-of-3-and-5/Crystal/sum-multiples-of-3-and-5-3.cr diff --git a/Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.delphi b/Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.pas similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.delphi rename to Task/Sum-multiples-of-3-and-5/Delphi/sum-multiples-of-3-and-5.pas diff --git a/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.elixir b/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.ex similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.elixir rename to Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.ex diff --git a/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.elixir b/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.ex similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.elixir rename to Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.ex diff --git a/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.julia b/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.jl similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.julia rename to Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-1.jl diff --git a/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.julia b/Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.jl similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.julia rename to Task/Sum-multiples-of-3-and-5/Julia/sum-multiples-of-3-and-5-2.jl diff --git a/Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kotlin b/Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kts similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kotlin rename to Task/Sum-multiples-of-3-and-5/Kotlin/sum-multiples-of-3-and-5.kts diff --git a/Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-1.ocaml b/Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-1.ml similarity index 100% rename from Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-1.ocaml rename to Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-1.ml diff --git a/Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-2.ocaml b/Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-2.ml similarity index 100% rename from Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-2.ocaml rename to Task/Sum-multiples-of-3-and-5/OCaml/sum-multiples-of-3-and-5-2.ml diff --git a/Task/Sum-multiples-of-3-and-5/Rust/sum-multiples-of-3-and-5.rust b/Task/Sum-multiples-of-3-and-5/Rust/sum-multiples-of-3-and-5.rs similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Rust/sum-multiples-of-3-and-5.rust rename to Task/Sum-multiples-of-3-and-5/Rust/sum-multiples-of-3-and-5.rs diff --git a/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.ss b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.scm similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.ss rename to Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-1.scm diff --git a/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.ss b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.scm similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.ss rename to Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-2.scm diff --git a/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.ss b/Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.scm similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.ss rename to Task/Sum-multiples-of-3-and-5/Scheme/sum-multiples-of-3-and-5-3.scm diff --git a/Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5.v b/Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5-1.v similarity index 100% rename from Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5.v rename to Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5-1.v diff --git a/Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5-2.v b/Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5-2.v new file mode 100644 index 0000000000..c76009df9d --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/V-(Vlang)/sum-multiples-of-3-and-5-2.v @@ -0,0 +1,11 @@ +fn main(){ + println(sum(1000)) +} + +fn sum(num int) int{ + mut n:=0 + for i in 0..num{ + if i%3==0 || i%5==0 {n+=i} + } + return n +} diff --git a/Task/Sum-of-a-series/Amazing-Hopper/sum-of-a-series.hopper b/Task/Sum-of-a-series/Amazing-Hopper/sum-of-a-series.hopper new file mode 100644 index 0000000000..d9c95724b8 --- /dev/null +++ b/Task/Sum-of-a-series/Amazing-Hopper/sum-of-a-series.hopper @@ -0,0 +1,14 @@ +#include + +#define SUMM 0 +#defn gensequence(_X_,_Y_,_Z_) #ATOM#CMPLX;\ + #ATOM#CMPLX;\ + #ATOM#CMPLX;seq(-1) +#define getsummatory stats(SUMM) + +begin + set decimal '15' + "Sum of the Serie = ", gen sequence(1,1,1000), pow by '-2' + get summatory, " (1000 terms)" + "\nAprox. PI^2/6 = ", #( (M_PI)^2/6 ), echo +end diff --git a/Task/Sum-of-a-series/Chipmunk-Basic/sum-of-a-series.basic b/Task/Sum-of-a-series/Chipmunk-Basic/sum-of-a-series.basic new file mode 100644 index 0000000000..d6637d9bd6 --- /dev/null +++ b/Task/Sum-of-a-series/Chipmunk-Basic/sum-of-a-series.basic @@ -0,0 +1,10 @@ +100 sub sumseries(n) +110 if n = 0 then sumseries = 0 +120 sum = 0 +130 for k = 1 to n +140 sum = sum+1/k^2 +150 next k +160 sumseries = sum +170 end sub +180 print "s(1000) = ";sumseries(1000) +190 print "zeta(2) = ";pi*pi/6 diff --git a/Task/Sum-of-a-series/Crystal/sum-of-a-series.crystal b/Task/Sum-of-a-series/Crystal/sum-of-a-series.cr similarity index 100% rename from Task/Sum-of-a-series/Crystal/sum-of-a-series.crystal rename to Task/Sum-of-a-series/Crystal/sum-of-a-series.cr diff --git a/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi b/Task/Sum-of-a-series/Delphi/sum-of-a-series.pas similarity index 100% rename from Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi rename to Task/Sum-of-a-series/Delphi/sum-of-a-series.pas diff --git a/Task/Sum-of-a-series/Elixir/sum-of-a-series.elixir b/Task/Sum-of-a-series/Elixir/sum-of-a-series.ex similarity index 100% rename from Task/Sum-of-a-series/Elixir/sum-of-a-series.elixir rename to Task/Sum-of-a-series/Elixir/sum-of-a-series.ex diff --git a/Task/Sum-of-a-series/Euphoria/sum-of-a-series.euphoria b/Task/Sum-of-a-series/Euphoria/sum-of-a-series.ex similarity index 100% rename from Task/Sum-of-a-series/Euphoria/sum-of-a-series.euphoria rename to Task/Sum-of-a-series/Euphoria/sum-of-a-series.ex diff --git a/Task/Sum-of-a-series/GW-BASIC/sum-of-a-series.basic b/Task/Sum-of-a-series/GW-BASIC/sum-of-a-series.basic new file mode 100644 index 0000000000..7ec986c131 --- /dev/null +++ b/Task/Sum-of-a-series/GW-BASIC/sum-of-a-series.basic @@ -0,0 +1,9 @@ +10 N = 1000 +20 SUM# = 0 +30 FOR K = 1 TO N +40 SUM# = SUM# + 1 / K ^ 2 +50 NEXT K +60 PRINT "s(1000) = "; SUM# +70 PI# = 4 * ATN(1) +80 PRINT "zeta(2) = "; PI# * PI# / 6 +90 END diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series-1.jl similarity index 100% rename from Task/Sum-of-a-series/Julia/sum-of-a-series-1.julia rename to Task/Sum-of-a-series/Julia/sum-of-a-series-1.jl diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series-2.jl similarity index 100% rename from Task/Sum-of-a-series/Julia/sum-of-a-series-2.julia rename to Task/Sum-of-a-series/Julia/sum-of-a-series-2.jl diff --git a/Task/Sum-of-a-series/Kotlin/sum-of-a-series.kotlin b/Task/Sum-of-a-series/Kotlin/sum-of-a-series.kts similarity index 100% rename from Task/Sum-of-a-series/Kotlin/sum-of-a-series.kotlin rename to Task/Sum-of-a-series/Kotlin/sum-of-a-series.kts diff --git a/Task/Sum-of-a-series/Minimal-BASIC/sum-of-a-series.basic b/Task/Sum-of-a-series/Minimal-BASIC/sum-of-a-series.basic new file mode 100644 index 0000000000..f2a363fa85 --- /dev/null +++ b/Task/Sum-of-a-series/Minimal-BASIC/sum-of-a-series.basic @@ -0,0 +1,9 @@ +10 LET N = 1000 +20 LET S = 0 +30 FOR K = 1 TO N +40 LET S = S + 1 / (K * K) +50 NEXT K +60 PRINT "s(1000) = "; S +70 LET P = 4 * ATN(1) +80 PRINT "zeta(2) = "; P * P / 6 +90 END diff --git a/Task/Sum-of-a-series/NewLISP/sum-of-a-series.l b/Task/Sum-of-a-series/NewLISP/sum-of-a-series-1.l similarity index 100% rename from Task/Sum-of-a-series/NewLISP/sum-of-a-series.l rename to Task/Sum-of-a-series/NewLISP/sum-of-a-series-1.l diff --git a/Task/Sum-of-a-series/NewLISP/sum-of-a-series-2.l b/Task/Sum-of-a-series/NewLISP/sum-of-a-series-2.l new file mode 100644 index 0000000000..76c1afae9b --- /dev/null +++ b/Task/Sum-of-a-series/NewLISP/sum-of-a-series-2.l @@ -0,0 +1,6 @@ +(define (sm n (s 0)) + (if (zero? n) s (sm (- n 1) (add s (div 1 n n))))) + +(sm 1000) + +1.64393456668156 diff --git a/Task/Sum-of-a-series/Nu/sum-of-a-series.nu b/Task/Sum-of-a-series/Nu/sum-of-a-series.nu new file mode 100644 index 0000000000..4b17fd40d3 --- /dev/null +++ b/Task/Sum-of-a-series/Nu/sum-of-a-series.nu @@ -0,0 +1 @@ +1..1000 | each { $in ** -2. } | math sum diff --git a/Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ocaml b/Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ml similarity index 100% rename from Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ocaml rename to Task/Sum-of-a-series/OCaml/sum-of-a-series-1.ml diff --git a/Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ocaml b/Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ml similarity index 100% rename from Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ocaml rename to Task/Sum-of-a-series/OCaml/sum-of-a-series-2.ml diff --git a/Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ocaml b/Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ml similarity index 100% rename from Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ocaml rename to Task/Sum-of-a-series/OCaml/sum-of-a-series-3.ml diff --git a/Task/Sum-of-a-series/QB64/sum-of-a-series.qb64 b/Task/Sum-of-a-series/QB64/sum-of-a-series.qb64 new file mode 100644 index 0000000000..debbfd79a0 --- /dev/null +++ b/Task/Sum-of-a-series/QB64/sum-of-a-series.qb64 @@ -0,0 +1,15 @@ +Const pi = 4 * Atn(1) + +Print "s(1000) = "; sumSeries#(1000) +Print "zeta(2) = "; pi * pi / 6 +End + +Function sumSeries# (n) + Dim sum As Double + If n = 0 Then sumSeries# = 0 + sum = 0 + For k = 1 To n + sum = sum + 1.0 / (k * k) + Next + sumSeries# = sum +End Function diff --git a/Task/Sum-of-a-series/QBasic/sum-of-a-series.basic b/Task/Sum-of-a-series/QBasic/sum-of-a-series.basic index 6c5eaab7ea..2bca5e078b 100644 --- a/Task/Sum-of-a-series/QBasic/sum-of-a-series.basic +++ b/Task/Sum-of-a-series/QBasic/sum-of-a-series.basic @@ -1,5 +1,5 @@ FUNCTION sumSeries# (n) - IF n = 0 THEN sunSeries = 0 + IF n = 0 THEN sumSeries# = 0 FOR k = 1 TO n sum# = sum# + 1! / (k * k) NEXT diff --git a/Task/Sum-of-a-series/Rust/sum-of-a-series.rust b/Task/Sum-of-a-series/Rust/sum-of-a-series.rs similarity index 100% rename from Task/Sum-of-a-series/Rust/sum-of-a-series.rust rename to Task/Sum-of-a-series/Rust/sum-of-a-series.rs diff --git a/Task/Sum-of-a-series/Scheme/sum-of-a-series-1.ss b/Task/Sum-of-a-series/Scheme/sum-of-a-series-1.scm similarity index 100% rename from Task/Sum-of-a-series/Scheme/sum-of-a-series-1.ss rename to Task/Sum-of-a-series/Scheme/sum-of-a-series-1.scm diff --git a/Task/Sum-of-a-series/Scheme/sum-of-a-series-2.ss b/Task/Sum-of-a-series/Scheme/sum-of-a-series-2.scm similarity index 100% rename from Task/Sum-of-a-series/Scheme/sum-of-a-series-2.ss rename to Task/Sum-of-a-series/Scheme/sum-of-a-series-2.scm diff --git a/Task/Sum-of-a-series/Yabasic/sum-of-a-series.basic b/Task/Sum-of-a-series/Yabasic/sum-of-a-series.basic index ffc773fcbe..52ba8613b6 100644 --- a/Task/Sum-of-a-series/Yabasic/sum-of-a-series.basic +++ b/Task/Sum-of-a-series/Yabasic/sum-of-a-series.basic @@ -1,12 +1,12 @@ +print "s(1000) = ", sumSeries(1000) +print "zeta(2) = ", pi * pi / 6 +end + sub sumSeries(n) - if n = 0 then return 0 : fi + if n = 0 return 0 sum = 0 for k = 1 to n sum = sum + 1 / k ^ 2 next k return sum end sub - -print "s(1000) = ", sumSeries(1000) -print "zeta(2) = ", pi * pi / 6 -end diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Delphi/sum-of-elements-below-main-diagonal-of-matrix.delphi b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Delphi/sum-of-elements-below-main-diagonal-of-matrix.pas similarity index 100% rename from Task/Sum-of-elements-below-main-diagonal-of-matrix/Delphi/sum-of-elements-below-main-diagonal-of-matrix.delphi rename to Task/Sum-of-elements-below-main-diagonal-of-matrix/Delphi/sum-of-elements-below-main-diagonal-of-matrix.pas diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Julia/sum-of-elements-below-main-diagonal-of-matrix.julia b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Julia/sum-of-elements-below-main-diagonal-of-matrix.jl similarity index 100% rename from Task/Sum-of-elements-below-main-diagonal-of-matrix/Julia/sum-of-elements-below-main-diagonal-of-matrix.julia rename to Task/Sum-of-elements-below-main-diagonal-of-matrix/Julia/sum-of-elements-below-main-diagonal-of-matrix.jl diff --git a/Task/Sum-of-squares/Crystal/sum-of-squares.crystal b/Task/Sum-of-squares/Crystal/sum-of-squares.cr similarity index 100% rename from Task/Sum-of-squares/Crystal/sum-of-squares.crystal rename to Task/Sum-of-squares/Crystal/sum-of-squares.cr diff --git a/Task/Sum-of-squares/Delphi/sum-of-squares.delphi b/Task/Sum-of-squares/Delphi/sum-of-squares.pas similarity index 100% rename from Task/Sum-of-squares/Delphi/sum-of-squares.delphi rename to Task/Sum-of-squares/Delphi/sum-of-squares.pas diff --git a/Task/Sum-of-squares/Elixir/sum-of-squares.elixir b/Task/Sum-of-squares/Elixir/sum-of-squares.ex similarity index 100% rename from Task/Sum-of-squares/Elixir/sum-of-squares.elixir rename to Task/Sum-of-squares/Elixir/sum-of-squares.ex diff --git a/Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria b/Task/Sum-of-squares/Euphoria/sum-of-squares.ex similarity index 100% rename from Task/Sum-of-squares/Euphoria/sum-of-squares.euphoria rename to Task/Sum-of-squares/Euphoria/sum-of-squares.ex diff --git a/Task/Sum-of-squares/FutureBasic/sum-of-squares.basic b/Task/Sum-of-squares/FutureBasic/sum-of-squares.basic new file mode 100644 index 0000000000..e8886f6e58 --- /dev/null +++ b/Task/Sum-of-squares/FutureBasic/sum-of-squares.basic @@ -0,0 +1,14 @@ +void local fn DoIt + NSUinteger i, sum = 0 + CFArrayRef array = @[@3, @1, @4, @1, @5, @9] + + for i = 0 to len(array) -1 + sum = sum + intVal( array[i] ) ^ 2 + next + print "The sum of squares is: ", sum +end fn + + +fn DoIt + +HandleEvents diff --git a/Task/Sum-of-squares/Julia/sum-of-squares.julia b/Task/Sum-of-squares/Julia/sum-of-squares.jl similarity index 100% rename from Task/Sum-of-squares/Julia/sum-of-squares.julia rename to Task/Sum-of-squares/Julia/sum-of-squares.jl diff --git a/Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin b/Task/Sum-of-squares/Kotlin/sum-of-squares.kts similarity index 100% rename from Task/Sum-of-squares/Kotlin/sum-of-squares.kotlin rename to Task/Sum-of-squares/Kotlin/sum-of-squares.kts diff --git a/Task/Sum-of-squares/Nu/sum-of-squares.nu b/Task/Sum-of-squares/Nu/sum-of-squares.nu new file mode 100644 index 0000000000..2032012791 --- /dev/null +++ b/Task/Sum-of-squares/Nu/sum-of-squares.nu @@ -0,0 +1,3 @@ +def sqsum []: { + reduce -f 0 {|x res| $x * $x + $res } +} diff --git a/Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml b/Task/Sum-of-squares/OCaml/sum-of-squares-1.ml similarity index 100% rename from Task/Sum-of-squares/OCaml/sum-of-squares-1.ocaml rename to Task/Sum-of-squares/OCaml/sum-of-squares-1.ml diff --git a/Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml b/Task/Sum-of-squares/OCaml/sum-of-squares-2.ml similarity index 100% rename from Task/Sum-of-squares/OCaml/sum-of-squares-2.ocaml rename to Task/Sum-of-squares/OCaml/sum-of-squares-2.ml diff --git a/Task/Sum-of-squares/Rust/sum-of-squares.rust b/Task/Sum-of-squares/Rust/sum-of-squares.rs similarity index 100% rename from Task/Sum-of-squares/Rust/sum-of-squares.rust rename to Task/Sum-of-squares/Rust/sum-of-squares.rs diff --git a/Task/Sum-of-squares/Scheme/sum-of-squares.ss b/Task/Sum-of-squares/Scheme/sum-of-squares.scm similarity index 100% rename from Task/Sum-of-squares/Scheme/sum-of-squares.ss rename to Task/Sum-of-squares/Scheme/sum-of-squares.scm diff --git a/Task/Sum-of-squares/Tailspin/sum-of-squares.tailspin b/Task/Sum-of-squares/Tailspin/sum-of-squares-1.tailspin similarity index 100% rename from Task/Sum-of-squares/Tailspin/sum-of-squares.tailspin rename to Task/Sum-of-squares/Tailspin/sum-of-squares-1.tailspin diff --git a/Task/Sum-of-squares/Tailspin/sum-of-squares-2.tailspin b/Task/Sum-of-squares/Tailspin/sum-of-squares-2.tailspin new file mode 100644 index 0000000000..13460e2ec8 --- /dev/null +++ b/Task/Sum-of-squares/Tailspin/sum-of-squares-2.tailspin @@ -0,0 +1,8 @@ +ssq templates + @ set 0; + $... -> @ set $@ + $*$; + $@ ! +end ssq + +[] -> ssq ! -- outputs 0 +[1..5] -> ssq ! -- outputs 55 diff --git a/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-1.v b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-1.v new file mode 100644 index 0000000000..4e6c9d08d1 --- /dev/null +++ b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-1.v @@ -0,0 +1,12 @@ +fn main() { + a_list := [1, 2, 3, 4, 5] + println(sum_of_squares(a_list)) +} + +fn sum_of_squares(int_arr []int) int { + mut sum := 0 + for _, elem in int_arr { + sum += elem * elem + } + return sum +} diff --git a/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-2.v b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-2.v new file mode 100644 index 0000000000..c3ffd82536 --- /dev/null +++ b/Task/Sum-of-squares/V-(Vlang)/sum-of-squares-2.v @@ -0,0 +1,6 @@ +import arrays + +fn main() { + a_list := [1, 2, 3, 4, 5] + println(arrays.sum(a_list.map(it * it))!) +} diff --git a/Task/Sum-to-100/Elixir/sum-to-100.elixir b/Task/Sum-to-100/Elixir/sum-to-100.ex similarity index 100% rename from Task/Sum-to-100/Elixir/sum-to-100.elixir rename to Task/Sum-to-100/Elixir/sum-to-100.ex diff --git a/Task/Sum-to-100/Julia/sum-to-100.julia b/Task/Sum-to-100/Julia/sum-to-100.jl similarity index 100% rename from Task/Sum-to-100/Julia/sum-to-100.julia rename to Task/Sum-to-100/Julia/sum-to-100.jl diff --git a/Task/Sum-to-100/Kotlin/sum-to-100.kotlin b/Task/Sum-to-100/Kotlin/sum-to-100.kts similarity index 100% rename from Task/Sum-to-100/Kotlin/sum-to-100.kotlin rename to Task/Sum-to-100/Kotlin/sum-to-100.kts diff --git a/Task/Sum-to-100/Rust/sum-to-100.rust b/Task/Sum-to-100/Rust/sum-to-100.rs similarity index 100% rename from Task/Sum-to-100/Rust/sum-to-100.rust rename to Task/Sum-to-100/Rust/sum-to-100.rs diff --git a/Task/Summarize-and-say-sequence/Julia/summarize-and-say-sequence.julia b/Task/Summarize-and-say-sequence/Julia/summarize-and-say-sequence.jl similarity index 100% rename from Task/Summarize-and-say-sequence/Julia/summarize-and-say-sequence.julia rename to Task/Summarize-and-say-sequence/Julia/summarize-and-say-sequence.jl diff --git a/Task/Summarize-and-say-sequence/Kotlin/summarize-and-say-sequence.kotlin b/Task/Summarize-and-say-sequence/Kotlin/summarize-and-say-sequence.kts similarity index 100% rename from Task/Summarize-and-say-sequence/Kotlin/summarize-and-say-sequence.kotlin rename to Task/Summarize-and-say-sequence/Kotlin/summarize-and-say-sequence.kts diff --git a/Task/Summarize-and-say-sequence/Rust/summarize-and-say-sequence.rs b/Task/Summarize-and-say-sequence/Rust/summarize-and-say-sequence.rs new file mode 100644 index 0000000000..b3d20bc121 --- /dev/null +++ b/Task/Summarize-and-say-sequence/Rust/summarize-and-say-sequence.rs @@ -0,0 +1,128 @@ +use itertools::Itertools; +use std::collections::HashSet; + +fn n_to_v(n: &i32) -> Vec { + return n + .to_string() + .as_bytes() + .iter() + .map(|c| *c as i32 - '0' as i32) + .collect_vec(); +} + +fn v_to_s(v: &Vec) -> String { + return v + .iter() + .map(|i| { + assert!(*i < 10 && *i >= 0); + i.to_string() + }) + .join(""); +} + +fn v_to_n(v: &Vec) -> i32 { + let mut r = v.to_vec(); + r.reverse(); + return r.iter().fold(0, |sum, i| sum * 10 + i); +} + +fn generate_next_term(digits: Vec) -> Vec { + let mut counts = vec![0; 10]; + let mut next: Vec = vec![]; + for i in digits { + assert!(i < 10); + counts[i as usize] += 1; + } + for i in [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] { + if counts[i as usize] > 0 { + for d in n_to_v(&counts[i as usize]) { + next.push(d); + } + next.push(i); + } + } + return next; +} + +fn generate_sequence(seedterm: &Vec) -> (usize, Vec>, usize) { + let mut seen = HashSet::new(); + let mut term_vec = seedterm.clone(); + let mut term_string = v_to_s(&term_vec); + let mut sequence: Vec> = vec![]; + for iterations in 0..1000 { + sequence.push(term_vec.to_vec()); + if !seen.contains(&term_string) { + seen.insert(term_string.clone()); + term_vec = generate_next_term(term_vec); + term_string = v_to_s(&term_vec); + } else { + // found a repeat in the sequence, so find where last one was + let prev = (0..sequence.len()) + .find(|i| sequence[*i] == term_vec) + .unwrap(); + return (iterations, sequence, prev); + } + } + panic!("Could not find a repeat in sequence within 1000 iterations") +} + +// To decrease memory usage, just save the seeds and recalculate sequence later +// To speed up loop, just calculate the numbers with presorted digit sequences +// and then use permutations of results to regenerate the skipped seeds +fn find_max_sequences(start: i32, stop: i32) { + let mut max_length = 1_usize; + let mut max_length_seeds: Vec = vec![]; + for i in start..=stop { + let v = n_to_v(&i); + let mut dup_seq = v.to_vec(); + dup_seq.sort(); + dup_seq.reverse(); + if v != dup_seq { + continue; + } + let (seq_len, _seq, _prev) = generate_sequence(&v); + if seq_len > max_length { + max_length_seeds.clear(); + max_length_seeds.push(i); + max_length = seq_len; + } else if seq_len == max_length { + max_length_seeds.push(i); + } + } + let mut perm_seeds: Vec = vec![]; + for seed in max_length_seeds.clone() { + let v = n_to_v(&seed); + let minresult = 10_i32.pow(v.len() as u32 - 1_u32); + for p in v.iter().permutations(v.len()) { + let perm = p.iter().map(|x| **x).collect_vec(); + let n = v_to_n(&perm); + if n >= minresult { + perm_seeds.push(v_to_n(&perm)); + } + } + } + perm_seeds.sort(); + perm_seeds.dedup(); + println!( + "Seeds: {}", + perm_seeds.iter().map(|n| n.to_string()).join(" ") + ); + println!("\n Iterations: {max_length}\n\nExample sequence:\n"); + let (_len, seq, prev) = generate_sequence(&n_to_v(&max_length_seeds[0])); + for (idx, v) in seq.iter().enumerate() { + println!( + "{:<2}: {}{}", + idx + 1, + v.iter().map(|i| i.to_string()).join(""), + if idx == seq.len() - 1 { + format!(" <-- repeats the sequence from line {}.", prev + 1) + } else { + "".to_string() + }, + ); + } +} + +fn main() { + find_max_sequences(1, 999_999); +} diff --git a/Task/Summarize-primes/Delphi/summarize-primes.delphi b/Task/Summarize-primes/Delphi/summarize-primes.pas similarity index 100% rename from Task/Summarize-primes/Delphi/summarize-primes.delphi rename to Task/Summarize-primes/Delphi/summarize-primes.pas diff --git a/Task/Summarize-primes/Julia/summarize-primes.julia b/Task/Summarize-primes/Julia/summarize-primes.jl similarity index 100% rename from Task/Summarize-primes/Julia/summarize-primes.julia rename to Task/Summarize-primes/Julia/summarize-primes.jl diff --git a/Task/Summarize-primes/Rust/summarize-primes.rust b/Task/Summarize-primes/Rust/summarize-primes.rs similarity index 100% rename from Task/Summarize-primes/Rust/summarize-primes.rust rename to Task/Summarize-primes/Rust/summarize-primes.rs diff --git a/Task/Summarize-primes/Uiua/summarize-primes.uiua b/Task/Summarize-primes/Uiua/summarize-primes.uiua index 2b1143c9d9..cc7907bac6 100644 --- a/Task/Summarize-primes/Uiua/summarize-primes.uiua +++ b/Task/Summarize-primes/Uiua/summarize-primes.uiua @@ -1,4 +1,5 @@ -Primes ← ◌⍢(⊃(▽±◿⊙.⊸⊢|⊂:⊢)|≠0⧻)↘2⇡⊙[]80000 -IsPrime ← ∊:Primes -⊙⊟⊚⊸IsPrime\+.Primes # Raw results -⍉⇌⊂:+1⟜⍜(⊙⍉|⊏) # Formatted +IsPrime ← =1⧻°/× # °/× finds primes factors. +▽⊸≡IsPrime +1⇡1000 # Find primes in the target range. +▽⊙(⍉⊂+1⇡⧻⟜⊟:)⊸≡IsPrime\+. # Scan sums, only keeping prime sums. +&p$"Sequences of primes starting at 2 with prime sums\nLength\tLast\tSum" +≡(&p$"_\t_\t_" °[⊙⊙∘]) diff --git a/Task/Super-d-numbers/Julia/super-d-numbers.julia b/Task/Super-d-numbers/Julia/super-d-numbers.jl similarity index 100% rename from Task/Super-d-numbers/Julia/super-d-numbers.julia rename to Task/Super-d-numbers/Julia/super-d-numbers.jl diff --git a/Task/Super-d-numbers/Kotlin/super-d-numbers.kotlin b/Task/Super-d-numbers/Kotlin/super-d-numbers.kts similarity index 100% rename from Task/Super-d-numbers/Kotlin/super-d-numbers.kotlin rename to Task/Super-d-numbers/Kotlin/super-d-numbers.kts diff --git a/Task/Super-d-numbers/Rust/super-d-numbers.rust b/Task/Super-d-numbers/Rust/super-d-numbers.rs similarity index 100% rename from Task/Super-d-numbers/Rust/super-d-numbers.rust rename to Task/Super-d-numbers/Rust/super-d-numbers.rs diff --git a/Task/Superellipse/Delphi/superellipse.delphi b/Task/Superellipse/Delphi/superellipse.pas similarity index 100% rename from Task/Superellipse/Delphi/superellipse.delphi rename to Task/Superellipse/Delphi/superellipse.pas diff --git a/Task/Superellipse/Julia/superellipse.julia b/Task/Superellipse/Julia/superellipse.jl similarity index 100% rename from Task/Superellipse/Julia/superellipse.julia rename to Task/Superellipse/Julia/superellipse.jl diff --git a/Task/Superellipse/Kotlin/superellipse.kotlin b/Task/Superellipse/Kotlin/superellipse.kts similarity index 100% rename from Task/Superellipse/Kotlin/superellipse.kotlin rename to Task/Superellipse/Kotlin/superellipse.kts diff --git a/Task/Superpermutation-minimisation/Delphi/superpermutation-minimisation.delphi b/Task/Superpermutation-minimisation/Delphi/superpermutation-minimisation.pas similarity index 100% rename from Task/Superpermutation-minimisation/Delphi/superpermutation-minimisation.delphi rename to Task/Superpermutation-minimisation/Delphi/superpermutation-minimisation.pas diff --git a/Task/Superpermutation-minimisation/Elixir/superpermutation-minimisation.elixir b/Task/Superpermutation-minimisation/Elixir/superpermutation-minimisation.ex similarity index 100% rename from Task/Superpermutation-minimisation/Elixir/superpermutation-minimisation.elixir rename to Task/Superpermutation-minimisation/Elixir/superpermutation-minimisation.ex diff --git a/Task/Superpermutation-minimisation/Julia/superpermutation-minimisation.julia b/Task/Superpermutation-minimisation/Julia/superpermutation-minimisation.jl similarity index 100% rename from Task/Superpermutation-minimisation/Julia/superpermutation-minimisation.julia rename to Task/Superpermutation-minimisation/Julia/superpermutation-minimisation.jl diff --git a/Task/Superpermutation-minimisation/Kotlin/superpermutation-minimisation.kotlin b/Task/Superpermutation-minimisation/Kotlin/superpermutation-minimisation.kts similarity index 100% rename from Task/Superpermutation-minimisation/Kotlin/superpermutation-minimisation.kotlin rename to Task/Superpermutation-minimisation/Kotlin/superpermutation-minimisation.kts diff --git a/Task/Superpermutation-minimisation/Rust/superpermutation-minimisation.rs b/Task/Superpermutation-minimisation/Rust/superpermutation-minimisation.rs new file mode 100644 index 0000000000..f3e5c9ba21 --- /dev/null +++ b/Task/Superpermutation-minimisation/Rust/superpermutation-minimisation.rs @@ -0,0 +1,55 @@ +const MAX: usize = 12; + +// 1! + 2! + ... + n! +fn fact_sum(n: usize) -> usize { + let mut sum = 0_usize; + let mut fact = 1_usize; + let mut x = 0_usize; + while x < n { + x += 1; + fact *= x; + sum += fact; + } + return sum; +} + +fn r(n: usize, sup: &mut Vec, pos: &mut usize, cnt: &mut Vec) -> bool { + if n == 0 { + return false; + } + let c = sup[*pos - n]; + cnt[n] -= 1; + if cnt[n] == 0 { + cnt[n] = n; + if !r(n - 1, sup, pos, cnt) { + return false; + } + } + sup[*pos] = c; + *pos += 1; + return true; +} + +fn superperm(n: usize, sup: &mut Vec, pos: &mut usize, cnt: &mut Vec) -> usize { + *pos = n; + let new_len = fact_sum(n); + sup.resize(new_len, 0); + for i in 0..=n { + cnt[i] = i; + } + for i in 1..=n { + sup[i - 1] = (i as u8) + ('0' as u8); + } + + while r(n, sup, pos, cnt) {} + return sup.len(); +} + +fn main() { + let sup: &mut Vec = &mut [0_u8; 0].to_vec(); + let pos: &mut usize = &mut 0_usize; + let cnt: &mut Vec = &mut [0_usize; MAX].to_vec(); + for n in 0..MAX { + println!("superperm of {:<2} has a length of {}", n, superperm(n, sup, pos, cnt)); + } +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Elixir/sutherland-hodgman-polygon-clipping.elixir b/Task/Sutherland-Hodgman-polygon-clipping/Elixir/sutherland-hodgman-polygon-clipping.ex similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/Elixir/sutherland-hodgman-polygon-clipping.elixir rename to Task/Sutherland-Hodgman-polygon-clipping/Elixir/sutherland-hodgman-polygon-clipping.ex diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Julia/sutherland-hodgman-polygon-clipping.julia b/Task/Sutherland-Hodgman-polygon-clipping/Julia/sutherland-hodgman-polygon-clipping.jl similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/Julia/sutherland-hodgman-polygon-clipping.julia rename to Task/Sutherland-Hodgman-polygon-clipping/Julia/sutherland-hodgman-polygon-clipping.jl diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kotlin b/Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kts similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kotlin rename to Task/Sutherland-Hodgman-polygon-clipping/Kotlin/sutherland-hodgman-polygon-clipping.kts diff --git a/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ocaml b/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ml similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ocaml rename to Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-1.ml diff --git a/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ocaml b/Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ml similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ocaml rename to Task/Sutherland-Hodgman-polygon-clipping/OCaml/sutherland-hodgman-polygon-clipping-2.ml diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rust b/Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rs similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rust rename to Task/Sutherland-Hodgman-polygon-clipping/Rust/sutherland-hodgman-polygon-clipping.rs diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Scheme/sutherland-hodgman-polygon-clipping.ss b/Task/Sutherland-Hodgman-polygon-clipping/Scheme/sutherland-hodgman-polygon-clipping.scm similarity index 100% rename from Task/Sutherland-Hodgman-polygon-clipping/Scheme/sutherland-hodgman-polygon-clipping.ss rename to Task/Sutherland-Hodgman-polygon-clipping/Scheme/sutherland-hodgman-polygon-clipping.scm diff --git a/Task/Sylvesters-sequence/Julia/sylvesters-sequence.julia b/Task/Sylvesters-sequence/Julia/sylvesters-sequence.jl similarity index 100% rename from Task/Sylvesters-sequence/Julia/sylvesters-sequence.julia rename to Task/Sylvesters-sequence/Julia/sylvesters-sequence.jl diff --git a/Task/Sylvesters-sequence/Scheme/sylvesters-sequence.ss b/Task/Sylvesters-sequence/Scheme/sylvesters-sequence.scm similarity index 100% rename from Task/Sylvesters-sequence/Scheme/sylvesters-sequence.ss rename to Task/Sylvesters-sequence/Scheme/sylvesters-sequence.scm diff --git a/Task/Symmetric-difference/ALGOL-68/symmetric-difference.alg b/Task/Symmetric-difference/ALGOL-68/symmetric-difference.alg index 249ad03d28..29f1a08ea6 100644 --- a/Task/Symmetric-difference/ALGOL-68/symmetric-difference.alg +++ b/Task/Symmetric-difference/ALGOL-68/symmetric-difference.alg @@ -41,16 +41,19 @@ BEGIN OD; result END # + # ; -# construct the associative arrays for the task # -REF AARRAY a := INIT LOC AARRAY; -REF AARRAY b := INIT LOC AARRAY; -a // []STRING( "John", "Bob", "Mary", "Serena" ); -b // []STRING( "Jim", "Mary", "John", "Bob" ); -# find and show the symetric difference of a and b # -REF AARRAY c := ( a - b ) + ( b - a ); -REF AAELEMENT e := FIRST c; -WHILE e ISNT nil element DO - print( ( " ", key OF e ) ); - e := NEXT c -OD; -print( ( newline ) ) + +BEGIN # task # + # construct the associative arrays for the task # + REF AARRAY a := INIT LOC AARRAY; + REF AARRAY b := INIT LOC AARRAY; + a // []STRING( "John", "Bob", "Mary", "Serena" ); + b // []STRING( "Jim", "Mary", "John", "Bob" ); + # find and show the symetric difference of a and b # + REF AARRAY c := ( a - b ) + ( b - a ); + REF AAELEMENT e := FIRST c; + WHILE e ISNT nil element DO + print( ( " ", key OF e ) ); + e := NEXT c + OD; + print( ( newline ) ) +END diff --git a/Task/Symmetric-difference/Delphi/symmetric-difference-1.delphi b/Task/Symmetric-difference/Delphi/symmetric-difference-1.pas similarity index 100% rename from Task/Symmetric-difference/Delphi/symmetric-difference-1.delphi rename to Task/Symmetric-difference/Delphi/symmetric-difference-1.pas diff --git a/Task/Symmetric-difference/Delphi/symmetric-difference-2.delphi b/Task/Symmetric-difference/Delphi/symmetric-difference-2.pas similarity index 100% rename from Task/Symmetric-difference/Delphi/symmetric-difference-2.delphi rename to Task/Symmetric-difference/Delphi/symmetric-difference-2.pas diff --git a/Task/Symmetric-difference/Elixir/symmetric-difference.elixir b/Task/Symmetric-difference/Elixir/symmetric-difference.ex similarity index 100% rename from Task/Symmetric-difference/Elixir/symmetric-difference.elixir rename to Task/Symmetric-difference/Elixir/symmetric-difference.ex diff --git a/Task/Symmetric-difference/Julia/symmetric-difference.julia b/Task/Symmetric-difference/Julia/symmetric-difference.jl similarity index 100% rename from Task/Symmetric-difference/Julia/symmetric-difference.julia rename to Task/Symmetric-difference/Julia/symmetric-difference.jl diff --git a/Task/Symmetric-difference/Kotlin/symmetric-difference.kotlin b/Task/Symmetric-difference/Kotlin/symmetric-difference.kts similarity index 100% rename from Task/Symmetric-difference/Kotlin/symmetric-difference.kotlin rename to Task/Symmetric-difference/Kotlin/symmetric-difference.kts diff --git a/Task/Symmetric-difference/OCaml/symmetric-difference-1.ocaml b/Task/Symmetric-difference/OCaml/symmetric-difference-1.ml similarity index 100% rename from Task/Symmetric-difference/OCaml/symmetric-difference-1.ocaml rename to Task/Symmetric-difference/OCaml/symmetric-difference-1.ml diff --git a/Task/Symmetric-difference/OCaml/symmetric-difference-2.ocaml b/Task/Symmetric-difference/OCaml/symmetric-difference-2.ml similarity index 100% rename from Task/Symmetric-difference/OCaml/symmetric-difference-2.ocaml rename to Task/Symmetric-difference/OCaml/symmetric-difference-2.ml diff --git a/Task/Symmetric-difference/Rust/symmetric-difference.rust b/Task/Symmetric-difference/Rust/symmetric-difference.rs similarity index 100% rename from Task/Symmetric-difference/Rust/symmetric-difference.rust rename to Task/Symmetric-difference/Rust/symmetric-difference.rs diff --git a/Task/Symmetric-difference/Scheme/symmetric-difference-1.ss b/Task/Symmetric-difference/Scheme/symmetric-difference-1.scm similarity index 100% rename from Task/Symmetric-difference/Scheme/symmetric-difference-1.ss rename to Task/Symmetric-difference/Scheme/symmetric-difference-1.scm diff --git a/Task/Symmetric-difference/Scheme/symmetric-difference-2.ss b/Task/Symmetric-difference/Scheme/symmetric-difference-2.scm similarity index 100% rename from Task/Symmetric-difference/Scheme/symmetric-difference-2.ss rename to Task/Symmetric-difference/Scheme/symmetric-difference-2.scm diff --git a/Task/Synchronous-concurrency/Crystal/synchronous-concurrency.crystal b/Task/Synchronous-concurrency/Crystal/synchronous-concurrency.cr similarity index 100% rename from Task/Synchronous-concurrency/Crystal/synchronous-concurrency.crystal rename to Task/Synchronous-concurrency/Crystal/synchronous-concurrency.cr diff --git a/Task/Synchronous-concurrency/Delphi/synchronous-concurrency.delphi b/Task/Synchronous-concurrency/Delphi/synchronous-concurrency.pas similarity index 100% rename from Task/Synchronous-concurrency/Delphi/synchronous-concurrency.delphi rename to Task/Synchronous-concurrency/Delphi/synchronous-concurrency.pas diff --git a/Task/Synchronous-concurrency/Elixir/synchronous-concurrency.elixir b/Task/Synchronous-concurrency/Elixir/synchronous-concurrency.ex similarity index 100% rename from Task/Synchronous-concurrency/Elixir/synchronous-concurrency.elixir rename to Task/Synchronous-concurrency/Elixir/synchronous-concurrency.ex diff --git a/Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.euphoria b/Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.ex similarity index 100% rename from Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.euphoria rename to Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.ex diff --git a/Task/Synchronous-concurrency/FreeBASIC/synchronous-concurrency.basic b/Task/Synchronous-concurrency/FreeBASIC/synchronous-concurrency.basic new file mode 100644 index 0000000000..c7997ec6fe --- /dev/null +++ b/Task/Synchronous-concurrency/FreeBASIC/synchronous-concurrency.basic @@ -0,0 +1,103 @@ +Const NULL As Any Ptr = 0 + +Type Nodo + As String valor + As Nodo Ptr sgte +End Type + +Type QueueSeguro + As Nodo Ptr head, tail + As Any Ptr mutex + Declare Constructor + Declare Destructor + Declare Function TryDequeue(Byref resultado As String) As Boolean + Declare Sub Enqueue(Byval valor As String) +End Type + +Constructor QueueSeguro + head = NULL + tail = NULL + mutex = Mutexcreate() +End Constructor + +Destructor QueueSeguro + Mutexdestroy(mutex) +End Destructor + +Function QueueSeguro.TryDequeue(Byref resultado As String) As Boolean + Mutexlock(mutex) + If head = NULL Then + Mutexunlock(mutex) + Return False + End If + + resultado = head->valor + Dim temp As Nodo Ptr = head + head = head->sgte + If head = NULL Then tail = NULL + Delete temp + Mutexunlock(mutex) + + Return True +End Function + +Sub QueueSeguro.Enqueue(Byval valor As String) + Dim newNode As Nodo Ptr = New Nodo + newNode->valor = valor + newNode->sgte = NULL + Mutexlock(mutex) + If tail = NULL Then + head = newNode + tail = newNode + Else + tail->sgte = newNode + tail = newNode + End If + Mutexunlock(mutex) +End Sub + +Dim Shared m_EscribirQueue As QueueSeguro +Dim Shared m_LeerQueue As QueueSeguro + +Sub Leer(Byval userdata As Any Ptr) + Dim linea As String + Dim f As Integer = Freefile + Open "input.txt" For Input As #f + While Not Eof(f) + Line Input #f, linea + m_EscribirQueue.Enqueue(linea) + Wend + Close #f + m_EscribirQueue.Enqueue("") + + Dim resultado As String + Do Until m_LeerQueue.TryDequeue(resultado) + Sleep(10) + Loop + + Print resultado +End Sub + +Sub Escribir(Byval userdata As Any Ptr) + Dim cnt As Integer = 0 + Dim linea As String + Do + Do Until m_EscribirQueue.TryDequeue(linea) + Sleep(10) + Loop + If linea <> "" Then + Print linea + cnt += 1 + Else + m_LeerQueue.Enqueue(Str(cnt)) + Exit Do + End If + Loop +End Sub + +Dim t1 As Any Ptr = Threadcreate(@Leer, 0) +Dim t2 As Any Ptr = Threadcreate(@Escribir, 0) +Threadwait(t1) +Threadwait(t2) + +Sleep diff --git a/Task/Synchronous-concurrency/Julia/synchronous-concurrency.julia b/Task/Synchronous-concurrency/Julia/synchronous-concurrency.jl similarity index 100% rename from Task/Synchronous-concurrency/Julia/synchronous-concurrency.julia rename to Task/Synchronous-concurrency/Julia/synchronous-concurrency.jl diff --git a/Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-1.kotlin b/Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-1.kts similarity index 100% rename from Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-1.kotlin rename to Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-1.kts diff --git a/Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-2.kotlin b/Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-2.kts similarity index 100% rename from Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-2.kotlin rename to Task/Synchronous-concurrency/Kotlin/synchronous-concurrency-2.kts diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ml similarity index 100% rename from Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ocaml rename to Task/Synchronous-concurrency/OCaml/synchronous-concurrency-1.ml diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ml similarity index 100% rename from Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ocaml rename to Task/Synchronous-concurrency/OCaml/synchronous-concurrency-2.ml diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ml similarity index 100% rename from Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ocaml rename to Task/Synchronous-concurrency/OCaml/synchronous-concurrency-3.ml diff --git a/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ocaml b/Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ml similarity index 100% rename from Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ocaml rename to Task/Synchronous-concurrency/OCaml/synchronous-concurrency-4.ml diff --git a/Task/Synchronous-concurrency/Rust/synchronous-concurrency.rust b/Task/Synchronous-concurrency/Rust/synchronous-concurrency.rs similarity index 100% rename from Task/Synchronous-concurrency/Rust/synchronous-concurrency.rust rename to Task/Synchronous-concurrency/Rust/synchronous-concurrency.rs diff --git a/Task/System-time/Crystal/system-time.crystal b/Task/System-time/Crystal/system-time.cr similarity index 100% rename from Task/System-time/Crystal/system-time.crystal rename to Task/System-time/Crystal/system-time.cr diff --git a/Task/System-time/Delphi/system-time.delphi b/Task/System-time/Delphi/system-time.pas similarity index 100% rename from Task/System-time/Delphi/system-time.delphi rename to Task/System-time/Delphi/system-time.pas diff --git a/Task/System-time/Elixir/system-time-1.elixir b/Task/System-time/Elixir/system-time-1.ex similarity index 100% rename from Task/System-time/Elixir/system-time-1.elixir rename to Task/System-time/Elixir/system-time-1.ex diff --git a/Task/System-time/Elixir/system-time-2.elixir b/Task/System-time/Elixir/system-time-2.ex similarity index 100% rename from Task/System-time/Elixir/system-time-2.elixir rename to Task/System-time/Elixir/system-time-2.ex diff --git a/Task/System-time/Julia/system-time.julia b/Task/System-time/Julia/system-time.jl similarity index 100% rename from Task/System-time/Julia/system-time.julia rename to Task/System-time/Julia/system-time.jl diff --git a/Task/System-time/Kotlin/system-time.kotlin b/Task/System-time/Kotlin/system-time.kts similarity index 100% rename from Task/System-time/Kotlin/system-time.kotlin rename to Task/System-time/Kotlin/system-time.kts diff --git a/Task/System-time/OCaml/system-time.ocaml b/Task/System-time/OCaml/system-time.ml similarity index 100% rename from Task/System-time/OCaml/system-time.ocaml rename to Task/System-time/OCaml/system-time.ml diff --git a/Task/System-time/Rust/system-time.rust b/Task/System-time/Rust/system-time.rs similarity index 100% rename from Task/System-time/Rust/system-time.rust rename to Task/System-time/Rust/system-time.rs diff --git a/Task/System-time/Scheme/system-time-1.ss b/Task/System-time/Scheme/system-time-1.scm similarity index 100% rename from Task/System-time/Scheme/system-time-1.ss rename to Task/System-time/Scheme/system-time-1.scm diff --git a/Task/System-time/Scheme/system-time-2.ss b/Task/System-time/Scheme/system-time-2.scm similarity index 100% rename from Task/System-time/Scheme/system-time-2.ss rename to Task/System-time/Scheme/system-time-2.scm diff --git a/Task/Table-creation-Postal-addresses/Julia/table-creation-postal-addresses.julia b/Task/Table-creation-Postal-addresses/Julia/table-creation-postal-addresses.jl similarity index 100% rename from Task/Table-creation-Postal-addresses/Julia/table-creation-postal-addresses.julia rename to Task/Table-creation-Postal-addresses/Julia/table-creation-postal-addresses.jl diff --git a/Task/Table-creation-Postal-addresses/Kotlin/table-creation-postal-addresses.kotlin b/Task/Table-creation-Postal-addresses/Kotlin/table-creation-postal-addresses.kts similarity index 100% rename from Task/Table-creation-Postal-addresses/Kotlin/table-creation-postal-addresses.kotlin rename to Task/Table-creation-Postal-addresses/Kotlin/table-creation-postal-addresses.kts diff --git a/Task/Table-creation-Postal-addresses/MariaDB/table-creation-postal-addresses.sql b/Task/Table-creation-Postal-addresses/MariaDB/table-creation-postal-addresses.sql new file mode 100644 index 0000000000..14ae87749d --- /dev/null +++ b/Task/Table-creation-Postal-addresses/MariaDB/table-creation-postal-addresses.sql @@ -0,0 +1,11 @@ +CREATE OR REPLACE TABLE address_usa ( + uuid uuid DEFAULT uuid() PRIMARY KEY + COMMENT 'This is more efficient than a text column', + street varchar(100) NOT NULL, + city varchar(100) NOT NULL, + state varchar(100) CHECK (state > ''), + zip char(5) NOT NULL CHECK (char_length(zip) = 5) +) + ENGINE InnoDB, + COMMENT 'This table is cool' +; diff --git a/Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.ss b/Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.scm similarity index 100% rename from Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.ss rename to Task/Table-creation-Postal-addresses/Scheme/table-creation-postal-addresses.scm diff --git a/Task/Take-notes-on-the-command-line/ALGOL-68/take-notes-on-the-command-line.alg b/Task/Take-notes-on-the-command-line/ALGOL-68/take-notes-on-the-command-line.alg new file mode 100644 index 0000000000..471e51cd04 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/ALGOL-68/take-notes-on-the-command-line.alg @@ -0,0 +1,41 @@ +BEGIN # display or update NOTES.txt depending on the command line options # + + PR read "files.incl.a68" PR # include file utilities # + + # returns a string representation of v with at least two digits and with # + # leading zeros # + OP F = ( INT v )STRING: + BEGIN + INT abs v = ABS v; + STRING result := whole( abs v, 0 ); + IF abs v < 10 AND v >= 0 THEN "0" +=: result FI; + IF v < 0 THEN "-" +=: result FI; + result + END # F # ; + + STRING notes file = "NOTES.txt"; # notes database # + # check for notes on the command line - ALGOL 68G will expect them to # + # follow "--" # + INT notes start := 0; + FOR arg pos FROM 2 TO argc WHILE notes start = 0 DO + IF argv( arg pos ) = "--" THEN notes start := arg pos FI + OD; + IF notes start = 0 OR notes start = argc + THEN # no command line args, show the existing notes # + IF PRINTLINES notes file < 0 + THEN print( ( "Unable to open ", notes file, newline ) ) + FI + ELSE # add a note specified by the command line # + []INT date = local time[ AT 1 ]; + [ 1 : 3 ]STRING new note; + new note[ 1 ] := F date[ 1 ] + "/" + F date[ 2 ] + "/" + F date[ 3 ] + + "."+ F date[ 4 ] + ":" + F date[ 5 ] + ":" + F date[ 6 ]; + new note[ 2 ] := REPR 9 + argv( notes start + 1 ); + FOR arg pos FROM notes start + 2 TO argc DO new note[ 2 ] +:= " " + argv( arg pos ) OD; + new note[ 3 ] := ""; + IF NOT ( notes file APPENDLINES new note ) + THEN print( ( "Unable to append the notes", newline ) ) + FI + FI + +END diff --git a/Task/Take-notes-on-the-command-line/Delphi/take-notes-on-the-command-line.delphi b/Task/Take-notes-on-the-command-line/Delphi/take-notes-on-the-command-line.pas similarity index 100% rename from Task/Take-notes-on-the-command-line/Delphi/take-notes-on-the-command-line.delphi rename to Task/Take-notes-on-the-command-line/Delphi/take-notes-on-the-command-line.pas diff --git a/Task/Take-notes-on-the-command-line/Elixir/take-notes-on-the-command-line.elixir b/Task/Take-notes-on-the-command-line/Elixir/take-notes-on-the-command-line.ex similarity index 100% rename from Task/Take-notes-on-the-command-line/Elixir/take-notes-on-the-command-line.elixir rename to Task/Take-notes-on-the-command-line/Elixir/take-notes-on-the-command-line.ex diff --git a/Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.euphoria b/Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.ex similarity index 100% rename from Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.euphoria rename to Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.ex diff --git a/Task/Take-notes-on-the-command-line/Julia/take-notes-on-the-command-line.julia b/Task/Take-notes-on-the-command-line/Julia/take-notes-on-the-command-line.jl similarity index 100% rename from Task/Take-notes-on-the-command-line/Julia/take-notes-on-the-command-line.julia rename to Task/Take-notes-on-the-command-line/Julia/take-notes-on-the-command-line.jl diff --git a/Task/Take-notes-on-the-command-line/Kotlin/take-notes-on-the-command-line.kotlin b/Task/Take-notes-on-the-command-line/Kotlin/take-notes-on-the-command-line.kts similarity index 100% rename from Task/Take-notes-on-the-command-line/Kotlin/take-notes-on-the-command-line.kotlin rename to Task/Take-notes-on-the-command-line/Kotlin/take-notes-on-the-command-line.kts diff --git a/Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ocaml b/Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ml similarity index 100% rename from Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ocaml rename to Task/Take-notes-on-the-command-line/OCaml/take-notes-on-the-command-line.ml diff --git a/Task/Take-notes-on-the-command-line/Objeck/take-notes-on-the-command-line.objeck b/Task/Take-notes-on-the-command-line/Objeck/take-notes-on-the-command-line.objeck new file mode 100644 index 0000000000..0921d55ae1 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Objeck/take-notes-on-the-command-line.objeck @@ -0,0 +1,32 @@ +class Notes { + function : Main(args : String[]) ~ Nil { + filename := "NOTES.TXT"; + + if(args->Size() > 0) { + buffer := System.Time.Date->New()->ToString() + "\n\t"; + each(arg in args) { + buffer += arg + " "; + }; + buffer += "\n\n"; + + writer := System.IO.Filesystem.FileWriter->New(filename, true); + writer->WriteString(buffer); + writer->Close(); + } + else { + reader := System.IO.Filesystem.FileReader->New(filename); + if(reader->IsOpen()) { + line : String; + do { + line := reader->ReadLine(); + if(line <> Nil) { + line->PrintLine(); + }; + } + while(line <> Nil); + }; + + reader->Close(); + }; + } +} diff --git a/Task/Take-notes-on-the-command-line/Rust/take-notes-on-the-command-line.rust b/Task/Take-notes-on-the-command-line/Rust/take-notes-on-the-command-line.rs similarity index 100% rename from Task/Take-notes-on-the-command-line/Rust/take-notes-on-the-command-line.rust rename to Task/Take-notes-on-the-command-line/Rust/take-notes-on-the-command-line.rs diff --git a/Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.ss b/Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.scm similarity index 100% rename from Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.ss rename to Task/Take-notes-on-the-command-line/Scheme/take-notes-on-the-command-line.scm diff --git a/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh index d39ee57d90..dcaf530ddd 100644 --- a/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh +++ b/Task/Take-notes-on-the-command-line/UNIX-Shell/take-notes-on-the-command-line-1.sh @@ -1,4 +1,4 @@ -# +#!/usr/bin/env bash if declare NOTES=$HOME/notes.txt @@ -6,7 +6,8 @@ if then { date - echo " $*" + echo -e "\t$*" } >> $NOTES -else [[ -r $NOTES ]] && more $NOTES +elif [[ -r $NOTES ]] +then more $NOTES fi diff --git a/Task/Tarjan/Julia/tarjan.julia b/Task/Tarjan/Julia/tarjan.jl similarity index 100% rename from Task/Tarjan/Julia/tarjan.julia rename to Task/Tarjan/Julia/tarjan.jl diff --git a/Task/Tarjan/Kotlin/tarjan.kotlin b/Task/Tarjan/Kotlin/tarjan.kts similarity index 100% rename from Task/Tarjan/Kotlin/tarjan.kotlin rename to Task/Tarjan/Kotlin/tarjan.kts diff --git a/Task/Tarjan/Rust/tarjan.rust b/Task/Tarjan/Rust/tarjan.rs similarity index 100% rename from Task/Tarjan/Rust/tarjan.rust rename to Task/Tarjan/Rust/tarjan.rs diff --git a/Task/Tau-function/Delphi/tau-function.delphi b/Task/Tau-function/Delphi/tau-function.pas similarity index 100% rename from Task/Tau-function/Delphi/tau-function.delphi rename to Task/Tau-function/Delphi/tau-function.pas diff --git a/Task/Tau-function/Julia/tau-function.julia b/Task/Tau-function/Julia/tau-function.jl similarity index 100% rename from Task/Tau-function/Julia/tau-function.julia rename to Task/Tau-function/Julia/tau-function.jl diff --git a/Task/Tau-function/Rust/tau-function.rust b/Task/Tau-function/Rust/tau-function.rs similarity index 100% rename from Task/Tau-function/Rust/tau-function.rust rename to Task/Tau-function/Rust/tau-function.rs diff --git a/Task/Tau-number/Delphi/tau-number.delphi b/Task/Tau-number/Delphi/tau-number.pas similarity index 100% rename from Task/Tau-number/Delphi/tau-number.delphi rename to Task/Tau-number/Delphi/tau-number.pas diff --git a/Task/Tau-number/Julia/tau-number.julia b/Task/Tau-number/Julia/tau-number.jl similarity index 100% rename from Task/Tau-number/Julia/tau-number.julia rename to Task/Tau-number/Julia/tau-number.jl diff --git a/Task/Tau-number/Rust/tau-number.rust b/Task/Tau-number/Rust/tau-number.rs similarity index 100% rename from Task/Tau-number/Rust/tau-number.rust rename to Task/Tau-number/Rust/tau-number.rs diff --git a/Task/Taxicab-numbers/Elixir/taxicab-numbers.elixir b/Task/Taxicab-numbers/Elixir/taxicab-numbers.ex similarity index 100% rename from Task/Taxicab-numbers/Elixir/taxicab-numbers.elixir rename to Task/Taxicab-numbers/Elixir/taxicab-numbers.ex diff --git a/Task/Taxicab-numbers/Julia/taxicab-numbers.julia b/Task/Taxicab-numbers/Julia/taxicab-numbers.jl similarity index 100% rename from Task/Taxicab-numbers/Julia/taxicab-numbers.julia rename to Task/Taxicab-numbers/Julia/taxicab-numbers.jl diff --git a/Task/Taxicab-numbers/Kotlin/taxicab-numbers.kotlin b/Task/Taxicab-numbers/Kotlin/taxicab-numbers.kts similarity index 100% rename from Task/Taxicab-numbers/Kotlin/taxicab-numbers.kotlin rename to Task/Taxicab-numbers/Kotlin/taxicab-numbers.kts diff --git a/Task/Taxicab-numbers/Rust/taxicab-numbers.rust b/Task/Taxicab-numbers/Rust/taxicab-numbers.rs similarity index 100% rename from Task/Taxicab-numbers/Rust/taxicab-numbers.rust rename to Task/Taxicab-numbers/Rust/taxicab-numbers.rs diff --git a/Task/Taxicab-numbers/Scheme/taxicab-numbers.ss b/Task/Taxicab-numbers/Scheme/taxicab-numbers.scm similarity index 100% rename from Task/Taxicab-numbers/Scheme/taxicab-numbers.ss rename to Task/Taxicab-numbers/Scheme/taxicab-numbers.scm diff --git a/Task/Taxicab-numbers/V-(Vlang)/taxicab-numbers.v b/Task/Taxicab-numbers/V-(Vlang)/taxicab-numbers.v new file mode 100644 index 0000000000..d58d085ab5 --- /dev/null +++ b/Task/Taxicab-numbers/V-(Vlang)/taxicab-numbers.v @@ -0,0 +1,26 @@ +import math + +fn main() { + mut num, mut nr := 0, 0 + mut tax := []int{} + for n in 0 .. 500000 { + nr = 0 + tax.clear() + for m in 0 .. 74 { + for p in m + 0 .. 74 { + if n == math.pow(m, 3) + math.pow(p, 3) { + tax << m + tax << p + nr++ + } + } + } + if nr > 1 { + num++ + print(" ${num:2} ${n:6} => ${tax[0]:2}³ + ${tax[1]:2}³, ") + print(" ${tax[2]:2}³ + ${tax[3]:2}³" + "\n") + if num == 25 {exit} + } + } + print("ok" + "\n") +} diff --git a/Task/Teacup-rim-text/EasyLang/teacup-rim-text.easy b/Task/Teacup-rim-text/EasyLang/teacup-rim-text.easy new file mode 100644 index 0000000000..24919028cf --- /dev/null +++ b/Task/Teacup-rim-text/EasyLang/teacup-rim-text.easy @@ -0,0 +1,46 @@ +repeat + s$ = input + until s$ = "" + if len s$ > 2 + w$[] &= s$ + . +. +func search s$ . + max = len w$[] + 1 + while min + 1 < max + mid = min + (max - min) div 2 + h = strcmp w$[mid] s$ + if h = 0 + return 1 + elif h < 0 + min = mid + else + max = mid + . + . + return 0 +. +for w$ in w$[] + w0$ = w$ + out$ = w$ + l = len w$ + for i to l - 1 + w$ = substr w$ 2 (l - 1) & substr w$ 1 1 + if strcmp w$ w0$ <= 0 + break 1 + . + if search w$ <> 1 + break 1 + . + out$ &= " -> " & w$ + . + if i = l + print out$ + . +. +# the content of unixdict.txt +input_data +10th +ate +eat +tea diff --git a/Task/Teacup-rim-text/FreeBASIC/teacup-rim-text.basic b/Task/Teacup-rim-text/FreeBASIC/teacup-rim-text.basic new file mode 100644 index 0000000000..eca3589f4a --- /dev/null +++ b/Task/Teacup-rim-text/FreeBASIC/teacup-rim-text.basic @@ -0,0 +1,67 @@ +Dim As String dict, word, domain, result, uniqueWords, w1, w2, w3 +Dim As Integer i +Dim As String filename = "unixdict.txt" +'Dim As String filename = "mit.10000.words.txt" + +Function REPLACE(original As String, find As String, replaceWith As String) As String + Dim As Integer posic + Dim As String result = original + + Do + posic = Instr(result, find) + If posic = 0 Then Exit Do + result = Left(result, posic - 1) & replaceWith & Mid(result, posic + Len(find)) + Loop + + Return result +End Function + +Function isUnique(word As String) As Boolean + Dim As Integer i, c, chars(255) + + For i = 1 To Len(word) + c = Asc(Mid(word, i, 1)) + If chars(c) Then Return False + chars(c) = 1 + Next + + Return True +End Function + +Function TALLY (Byval s As String, Byval f As String) As Integer + Return (Len(s) - Len(REPLACE(s, f, ""))) / Len(f) +End Function + +Open filename For Input As #1 +dict = Input(Lof(1), #1) +Close #1 + +For i = 1 To Len(dict) + If Mid(dict, i, 1) = Chr(10) Then + If Len(word) = 3 And isUnique(word) Then domain &= word & Chr(10) + word = "" + Else + word &= Mid(dict, i, 1) + End If +Next i + +For i = 1 To Len(domain) + If Mid(domain, i, 1) = Chr(10) Then + w2 = Right(w1, 2) & Left(w1, 1) + w3 = Right(w2, 2) & Left(w2, 1) + If TALLY(domain, w2 & Chr(10)) > 0 _ + And TALLY(domain, w3 & Chr(10)) > 0 _ + And TALLY(uniqueWords, w1 & Chr(10)) = 0 Then + result &= w1 & " " & w2 & " " & w3 & Chr(10) + uniqueWords &= w1 & Chr(10) & w2 & Chr(10) & w3 & Chr(10) + End If + w1 = "" + Else + w1 &= Mid(domain, i, 1) + End If +Next i + +Print result +Print "Total words:"; TALLY(dict, Chr(10)); ", and"; TALLY(result, Chr(10)); " are circular." + +Sleep diff --git a/Task/Teacup-rim-text/Julia/teacup-rim-text.julia b/Task/Teacup-rim-text/Julia/teacup-rim-text.jl similarity index 100% rename from Task/Teacup-rim-text/Julia/teacup-rim-text.julia rename to Task/Teacup-rim-text/Julia/teacup-rim-text.jl diff --git a/Task/Teacup-rim-text/PascalABC.NET/teacup-rim-text-1.pas b/Task/Teacup-rim-text/PascalABC.NET/teacup-rim-text-1.pas new file mode 100644 index 0000000000..5db036d673 --- /dev/null +++ b/Task/Teacup-rim-text/PascalABC.NET/teacup-rim-text-1.pas @@ -0,0 +1,27 @@ +// Teacup rim text. Nigel Galloway: September 26th., 2024 +## +function fG(n:string;g:integer):sequence of string; +begin + yield n; + foreach var i in 1..g-1 do begin + n:=n.Cycle.Take(g+1).Skip(1).JoinIntoString; + yield n; + end; +end; +function fN(g:string):sequence of string; +begin + foreach var n in System.IO.File.ReadLines(g) do if n.Length>2 then yield n; +end; +function fI(n:HashSet;g:integer):sequence of sequence of string; +begin + while n.Count>0 do begin + var c:=fG(n.First,g); + if (c.ElementAt(0)<>c.ElementAt(1)) and c.All(g->n.Contains(g)) then yield c; + n:=n-c.ToHashSet; + end; +end; + +foreach var n in fN('unixdict.txt').GroupBy(n->n.length) do begin + var g:= fI(n.ToHashSet,n.First.Length); + if g.Count>0 then println(g); +end; diff --git a/Task/Teacup-rim-text/PascalABC.NET/teacup-rim-text-2.pas b/Task/Teacup-rim-text/PascalABC.NET/teacup-rim-text-2.pas new file mode 100644 index 0000000000..11d022bc08 --- /dev/null +++ b/Task/Teacup-rim-text/PascalABC.NET/teacup-rim-text-2.pas @@ -0,0 +1,4 @@ +foreach var n in fN('words_alpha.txt').GroupBy(n->n.length) do begin + var g:= fI(n.ToHashSet,n.First.Length); + if g.Count>0 then println(g); +end; diff --git a/Task/Teacup-rim-text/Rust/teacup-rim-text.rust b/Task/Teacup-rim-text/Rust/teacup-rim-text.rs similarity index 100% rename from Task/Teacup-rim-text/Rust/teacup-rim-text.rust rename to Task/Teacup-rim-text/Rust/teacup-rim-text.rs diff --git a/Task/Temperature-conversion/Delphi/temperature-conversion.delphi b/Task/Temperature-conversion/Delphi/temperature-conversion.pas similarity index 100% rename from Task/Temperature-conversion/Delphi/temperature-conversion.delphi rename to Task/Temperature-conversion/Delphi/temperature-conversion.pas diff --git a/Task/Temperature-conversion/Elixir/temperature-conversion.elixir b/Task/Temperature-conversion/Elixir/temperature-conversion.ex similarity index 100% rename from Task/Temperature-conversion/Elixir/temperature-conversion.elixir rename to Task/Temperature-conversion/Elixir/temperature-conversion.ex diff --git a/Task/Temperature-conversion/Euphoria/temperature-conversion.euphoria b/Task/Temperature-conversion/Euphoria/temperature-conversion.ex similarity index 100% rename from Task/Temperature-conversion/Euphoria/temperature-conversion.euphoria rename to Task/Temperature-conversion/Euphoria/temperature-conversion.ex diff --git a/Task/Temperature-conversion/Julia/temperature-conversion.julia b/Task/Temperature-conversion/Julia/temperature-conversion.jl similarity index 100% rename from Task/Temperature-conversion/Julia/temperature-conversion.julia rename to Task/Temperature-conversion/Julia/temperature-conversion.jl diff --git a/Task/Temperature-conversion/Kotlin/temperature-conversion.kotlin b/Task/Temperature-conversion/Kotlin/temperature-conversion.kts similarity index 100% rename from Task/Temperature-conversion/Kotlin/temperature-conversion.kotlin rename to Task/Temperature-conversion/Kotlin/temperature-conversion.kts diff --git a/Task/Temperature-conversion/OCaml/temperature-conversion.ocaml b/Task/Temperature-conversion/OCaml/temperature-conversion.ml similarity index 100% rename from Task/Temperature-conversion/OCaml/temperature-conversion.ocaml rename to Task/Temperature-conversion/OCaml/temperature-conversion.ml diff --git a/Task/Temperature-conversion/Rust/temperature-conversion.rust b/Task/Temperature-conversion/Rust/temperature-conversion.rs similarity index 100% rename from Task/Temperature-conversion/Rust/temperature-conversion.rust rename to Task/Temperature-conversion/Rust/temperature-conversion.rs diff --git a/Task/Temperature-conversion/Scheme/temperature-conversion.ss b/Task/Temperature-conversion/Scheme/temperature-conversion.scm similarity index 100% rename from Task/Temperature-conversion/Scheme/temperature-conversion.ss rename to Task/Temperature-conversion/Scheme/temperature-conversion.scm diff --git a/Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-1.delphi b/Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-1.pas similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-1.delphi rename to Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-1.pas diff --git a/Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-2.delphi b/Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-2.pas similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-2.delphi rename to Task/Terminal-control-Clear-the-screen/Delphi/terminal-control-clear-the-screen-2.pas diff --git a/Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.euphoria b/Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.ex similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.euphoria rename to Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.ex diff --git a/Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.julia b/Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.jl similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.julia rename to Task/Terminal-control-Clear-the-screen/Julia/terminal-control-clear-the-screen.jl diff --git a/Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kotlin b/Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kts similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kotlin rename to Task/Terminal-control-Clear-the-screen/Kotlin/terminal-control-clear-the-screen.kts diff --git a/Task/Terminal-control-Clear-the-screen/Nu/terminal-control-clear-the-screen.nu b/Task/Terminal-control-Clear-the-screen/Nu/terminal-control-clear-the-screen.nu new file mode 100644 index 0000000000..509159dc4a --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Nu/terminal-control-clear-the-screen.nu @@ -0,0 +1 @@ +clear -a diff --git a/Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ocaml b/Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ml similarity index 100% rename from Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ocaml rename to Task/Terminal-control-Clear-the-screen/OCaml/terminal-control-clear-the-screen.ml diff --git a/Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-1.rust b/Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-1.rs similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-1.rust rename to Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-1.rs diff --git a/Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-2.rust b/Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-2.rs similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-2.rust rename to Task/Terminal-control-Clear-the-screen/Rust/terminal-control-clear-the-screen-2.rs diff --git a/Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.julia b/Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.jl similarity index 100% rename from Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.julia rename to Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.jl diff --git a/Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kotlin b/Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kts similarity index 100% rename from Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kotlin rename to Task/Terminal-control-Coloured-text/Kotlin/terminal-control-coloured-text.kts diff --git a/Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ocaml b/Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ml similarity index 100% rename from Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ocaml rename to Task/Terminal-control-Coloured-text/OCaml/terminal-control-coloured-text.ml diff --git a/Task/Terminal-control-Coloured-text/Rust/terminal-control-coloured-text.rust b/Task/Terminal-control-Coloured-text/Rust/terminal-control-coloured-text.rs similarity index 100% rename from Task/Terminal-control-Coloured-text/Rust/terminal-control-coloured-text.rust rename to Task/Terminal-control-Coloured-text/Rust/terminal-control-coloured-text.rs diff --git a/Task/Terminal-control-Cursor-movement/Julia/terminal-control-cursor-movement.julia b/Task/Terminal-control-Cursor-movement/Julia/terminal-control-cursor-movement.jl similarity index 100% rename from Task/Terminal-control-Cursor-movement/Julia/terminal-control-cursor-movement.julia rename to Task/Terminal-control-Cursor-movement/Julia/terminal-control-cursor-movement.jl diff --git a/Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kotlin b/Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kts similarity index 100% rename from Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kotlin rename to Task/Terminal-control-Cursor-movement/Kotlin/terminal-control-cursor-movement.kts diff --git a/Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.euphoria b/Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.ex similarity index 100% rename from Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.euphoria rename to Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.ex diff --git a/Task/Terminal-control-Cursor-positioning/Julia/terminal-control-cursor-positioning.julia b/Task/Terminal-control-Cursor-positioning/Julia/terminal-control-cursor-positioning.jl similarity index 100% rename from Task/Terminal-control-Cursor-positioning/Julia/terminal-control-cursor-positioning.julia rename to Task/Terminal-control-Cursor-positioning/Julia/terminal-control-cursor-positioning.jl diff --git a/Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kotlin b/Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kts similarity index 100% rename from Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kotlin rename to Task/Terminal-control-Cursor-positioning/Kotlin/terminal-control-cursor-positioning.kts diff --git a/Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ocaml b/Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ml similarity index 100% rename from Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ocaml rename to Task/Terminal-control-Cursor-positioning/OCaml/terminal-control-cursor-positioning.ml diff --git a/Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.euphoria b/Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.ex similarity index 100% rename from Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.euphoria rename to Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.ex diff --git a/Task/Terminal-control-Dimensions/Julia/terminal-control-dimensions.julia b/Task/Terminal-control-Dimensions/Julia/terminal-control-dimensions.jl similarity index 100% rename from Task/Terminal-control-Dimensions/Julia/terminal-control-dimensions.julia rename to Task/Terminal-control-Dimensions/Julia/terminal-control-dimensions.jl diff --git a/Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kotlin b/Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kts similarity index 100% rename from Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kotlin rename to Task/Terminal-control-Dimensions/Kotlin/terminal-control-dimensions.kts diff --git a/Task/Terminal-control-Dimensions/Nu/terminal-control-dimensions.nu b/Task/Terminal-control-Dimensions/Nu/terminal-control-dimensions.nu new file mode 100644 index 0000000000..1d5dd6a0a5 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Nu/terminal-control-dimensions.nu @@ -0,0 +1,2 @@ +let x = (term size).columns +let y = (term size).rows diff --git a/Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ocaml b/Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ml similarity index 100% rename from Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ocaml rename to Task/Terminal-control-Dimensions/OCaml/terminal-control-dimensions.ml diff --git a/Task/Terminal-control-Display-an-extended-character/Julia/terminal-control-display-an-extended-character.julia b/Task/Terminal-control-Display-an-extended-character/Julia/terminal-control-display-an-extended-character.jl similarity index 100% rename from Task/Terminal-control-Display-an-extended-character/Julia/terminal-control-display-an-extended-character.julia rename to Task/Terminal-control-Display-an-extended-character/Julia/terminal-control-display-an-extended-character.jl diff --git a/Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kotlin b/Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kts similarity index 100% rename from Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kotlin rename to Task/Terminal-control-Display-an-extended-character/Kotlin/terminal-control-display-an-extended-character.kts diff --git a/Task/Terminal-control-Display-an-extended-character/Nu/terminal-control-display-an-extended-character.nu b/Task/Terminal-control-Display-an-extended-character/Nu/terminal-control-display-an-extended-character.nu new file mode 100644 index 0000000000..63f3253574 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Nu/terminal-control-display-an-extended-character.nu @@ -0,0 +1 @@ +print "\u{A3}" diff --git a/Task/Terminal-control-Hiding-the-cursor/Julia/terminal-control-hiding-the-cursor.julia b/Task/Terminal-control-Hiding-the-cursor/Julia/terminal-control-hiding-the-cursor.jl similarity index 100% rename from Task/Terminal-control-Hiding-the-cursor/Julia/terminal-control-hiding-the-cursor.julia rename to Task/Terminal-control-Hiding-the-cursor/Julia/terminal-control-hiding-the-cursor.jl diff --git a/Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kotlin b/Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kts similarity index 100% rename from Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kotlin rename to Task/Terminal-control-Hiding-the-cursor/Kotlin/terminal-control-hiding-the-cursor.kts diff --git a/Task/Terminal-control-Hiding-the-cursor/Nu/terminal-control-hiding-the-cursor.nu b/Task/Terminal-control-Hiding-the-cursor/Nu/terminal-control-hiding-the-cursor.nu new file mode 100644 index 0000000000..b45e5f0c0a --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Nu/terminal-control-hiding-the-cursor.nu @@ -0,0 +1,3 @@ +print (ansi cursor_off) +sleep 3sec +print (ansi cursor_on) diff --git a/Task/Terminal-control-Inverse-video/Julia/terminal-control-inverse-video.julia b/Task/Terminal-control-Inverse-video/Julia/terminal-control-inverse-video.jl similarity index 100% rename from Task/Terminal-control-Inverse-video/Julia/terminal-control-inverse-video.julia rename to Task/Terminal-control-Inverse-video/Julia/terminal-control-inverse-video.jl diff --git a/Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kotlin b/Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kts similarity index 100% rename from Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kotlin rename to Task/Terminal-control-Inverse-video/Kotlin/terminal-control-inverse-video.kts diff --git a/Task/Terminal-control-Inverse-video/Nu/terminal-control-inverse-video.nu b/Task/Terminal-control-Inverse-video/Nu/terminal-control-inverse-video.nu new file mode 100644 index 0000000000..1224467121 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Nu/terminal-control-inverse-video.nu @@ -0,0 +1 @@ +print $'(ansi default_reverse)reversed(ansi reset) normal' diff --git a/Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ocaml b/Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ml similarity index 100% rename from Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ocaml rename to Task/Terminal-control-Inverse-video/OCaml/terminal-control-inverse-video.ml diff --git a/Task/Terminal-control-Positional-read/Julia/terminal-control-positional-read.julia b/Task/Terminal-control-Positional-read/Julia/terminal-control-positional-read.jl similarity index 100% rename from Task/Terminal-control-Positional-read/Julia/terminal-control-positional-read.julia rename to Task/Terminal-control-Positional-read/Julia/terminal-control-positional-read.jl diff --git a/Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kotlin b/Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kts similarity index 100% rename from Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kotlin rename to Task/Terminal-control-Positional-read/Kotlin/terminal-control-positional-read.kts diff --git a/Task/Terminal-control-Preserve-screen/Julia/terminal-control-preserve-screen.julia b/Task/Terminal-control-Preserve-screen/Julia/terminal-control-preserve-screen.jl similarity index 100% rename from Task/Terminal-control-Preserve-screen/Julia/terminal-control-preserve-screen.julia rename to Task/Terminal-control-Preserve-screen/Julia/terminal-control-preserve-screen.jl diff --git a/Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kotlin b/Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kts similarity index 100% rename from Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kotlin rename to Task/Terminal-control-Preserve-screen/Kotlin/terminal-control-preserve-screen.kts diff --git a/Task/Terminal-control-Preserve-screen/Rust/terminal-control-preserve-screen.rust b/Task/Terminal-control-Preserve-screen/Rust/terminal-control-preserve-screen.rs similarity index 100% rename from Task/Terminal-control-Preserve-screen/Rust/terminal-control-preserve-screen.rust rename to Task/Terminal-control-Preserve-screen/Rust/terminal-control-preserve-screen.rs diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.delphi b/Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.pas similarity index 100% rename from Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.delphi rename to Task/Terminal-control-Ringing-the-terminal-bell/Delphi/terminal-control-ringing-the-terminal-bell.pas diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.julia b/Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.jl similarity index 100% rename from Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.julia rename to Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.jl diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kotlin b/Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kts similarity index 100% rename from Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kotlin rename to Task/Terminal-control-Ringing-the-terminal-bell/Kotlin/terminal-control-ringing-the-terminal-bell.kts diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Nu/terminal-control-ringing-the-terminal-bell-1.nu b/Task/Terminal-control-Ringing-the-terminal-bell/Nu/terminal-control-ringing-the-terminal-bell-1.nu new file mode 100644 index 0000000000..6e197d6c74 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Nu/terminal-control-ringing-the-terminal-bell-1.nu @@ -0,0 +1 @@ +char bel diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Nu/terminal-control-ringing-the-terminal-bell-2.nu b/Task/Terminal-control-Ringing-the-terminal-bell/Nu/terminal-control-ringing-the-terminal-bell-2.nu new file mode 100644 index 0000000000..3fde07b32e --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Nu/terminal-control-ringing-the-terminal-bell-2.nu @@ -0,0 +1 @@ +print "\a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/OCaml/terminal-control-ringing-the-terminal-bell.ocaml b/Task/Terminal-control-Ringing-the-terminal-bell/OCaml/terminal-control-ringing-the-terminal-bell.ml similarity index 100% rename from Task/Terminal-control-Ringing-the-terminal-bell/OCaml/terminal-control-ringing-the-terminal-bell.ocaml rename to Task/Terminal-control-Ringing-the-terminal-bell/OCaml/terminal-control-ringing-the-terminal-bell.ml diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Rust/terminal-control-ringing-the-terminal-bell.rust b/Task/Terminal-control-Ringing-the-terminal-bell/Rust/terminal-control-ringing-the-terminal-bell.rs similarity index 100% rename from Task/Terminal-control-Ringing-the-terminal-bell/Rust/terminal-control-ringing-the-terminal-bell.rust rename to Task/Terminal-control-Ringing-the-terminal-bell/Rust/terminal-control-ringing-the-terminal-bell.rs diff --git a/Task/Terminal-control-Unicode-output/Elixir/terminal-control-unicode-output.elixir b/Task/Terminal-control-Unicode-output/Elixir/terminal-control-unicode-output.ex similarity index 100% rename from Task/Terminal-control-Unicode-output/Elixir/terminal-control-unicode-output.elixir rename to Task/Terminal-control-Unicode-output/Elixir/terminal-control-unicode-output.ex diff --git a/Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.julia b/Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.jl similarity index 100% rename from Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.julia rename to Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.jl diff --git a/Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kotlin b/Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kts similarity index 100% rename from Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kotlin rename to Task/Terminal-control-Unicode-output/Kotlin/terminal-control-unicode-output.kts diff --git a/Task/Ternary-logic/Delphi/ternary-logic-1.delphi b/Task/Ternary-logic/Delphi/ternary-logic-1.pas similarity index 100% rename from Task/Ternary-logic/Delphi/ternary-logic-1.delphi rename to Task/Ternary-logic/Delphi/ternary-logic-1.pas diff --git a/Task/Ternary-logic/Delphi/ternary-logic-2.delphi b/Task/Ternary-logic/Delphi/ternary-logic-2.pas similarity index 100% rename from Task/Ternary-logic/Delphi/ternary-logic-2.delphi rename to Task/Ternary-logic/Delphi/ternary-logic-2.pas diff --git a/Task/Ternary-logic/Delphi/ternary-logic-3.delphi b/Task/Ternary-logic/Delphi/ternary-logic-3.pas similarity index 100% rename from Task/Ternary-logic/Delphi/ternary-logic-3.delphi rename to Task/Ternary-logic/Delphi/ternary-logic-3.pas diff --git a/Task/Ternary-logic/Delphi/ternary-logic-4.delphi b/Task/Ternary-logic/Delphi/ternary-logic-4.pas similarity index 100% rename from Task/Ternary-logic/Delphi/ternary-logic-4.delphi rename to Task/Ternary-logic/Delphi/ternary-logic-4.pas diff --git a/Task/Ternary-logic/Julia/ternary-logic-1.julia b/Task/Ternary-logic/Julia/ternary-logic-1.jl similarity index 100% rename from Task/Ternary-logic/Julia/ternary-logic-1.julia rename to Task/Ternary-logic/Julia/ternary-logic-1.jl diff --git a/Task/Ternary-logic/Julia/ternary-logic-2.julia b/Task/Ternary-logic/Julia/ternary-logic-2.jl similarity index 100% rename from Task/Ternary-logic/Julia/ternary-logic-2.julia rename to Task/Ternary-logic/Julia/ternary-logic-2.jl diff --git a/Task/Ternary-logic/Kotlin/ternary-logic.kotlin b/Task/Ternary-logic/Kotlin/ternary-logic.kts similarity index 100% rename from Task/Ternary-logic/Kotlin/ternary-logic.kotlin rename to Task/Ternary-logic/Kotlin/ternary-logic.kts diff --git a/Task/Ternary-logic/OCaml/ternary-logic-1.ocaml b/Task/Ternary-logic/OCaml/ternary-logic-1.ml similarity index 100% rename from Task/Ternary-logic/OCaml/ternary-logic-1.ocaml rename to Task/Ternary-logic/OCaml/ternary-logic-1.ml diff --git a/Task/Ternary-logic/OCaml/ternary-logic-2.ocaml b/Task/Ternary-logic/OCaml/ternary-logic-2.ml similarity index 100% rename from Task/Ternary-logic/OCaml/ternary-logic-2.ocaml rename to Task/Ternary-logic/OCaml/ternary-logic-2.ml diff --git a/Task/Ternary-logic/Rust/ternary-logic.rust b/Task/Ternary-logic/Rust/ternary-logic.rs similarity index 100% rename from Task/Ternary-logic/Rust/ternary-logic.rust rename to Task/Ternary-logic/Rust/ternary-logic.rs diff --git a/Task/Test-a-function/Crystal/test-a-function.crystal b/Task/Test-a-function/Crystal/test-a-function.cr similarity index 100% rename from Task/Test-a-function/Crystal/test-a-function.crystal rename to Task/Test-a-function/Crystal/test-a-function.cr diff --git a/Task/Test-a-function/Delphi/test-a-function-1.delphi b/Task/Test-a-function/Delphi/test-a-function-1.pas similarity index 100% rename from Task/Test-a-function/Delphi/test-a-function-1.delphi rename to Task/Test-a-function/Delphi/test-a-function-1.pas diff --git a/Task/Test-a-function/Delphi/test-a-function-2.delphi b/Task/Test-a-function/Delphi/test-a-function-2.pas similarity index 100% rename from Task/Test-a-function/Delphi/test-a-function-2.delphi rename to Task/Test-a-function/Delphi/test-a-function-2.pas diff --git a/Task/Test-a-function/Euphoria/test-a-function.euphoria b/Task/Test-a-function/Euphoria/test-a-function.ex similarity index 100% rename from Task/Test-a-function/Euphoria/test-a-function.euphoria rename to Task/Test-a-function/Euphoria/test-a-function.ex diff --git a/Task/Test-a-function/Julia/test-a-function.julia b/Task/Test-a-function/Julia/test-a-function.jl similarity index 100% rename from Task/Test-a-function/Julia/test-a-function.julia rename to Task/Test-a-function/Julia/test-a-function.jl diff --git a/Task/Test-a-function/Kotlin/test-a-function.kotlin b/Task/Test-a-function/Kotlin/test-a-function.kts similarity index 100% rename from Task/Test-a-function/Kotlin/test-a-function.kotlin rename to Task/Test-a-function/Kotlin/test-a-function.kts diff --git a/Task/Test-a-function/OCaml/test-a-function.ocaml b/Task/Test-a-function/OCaml/test-a-function.ml similarity index 100% rename from Task/Test-a-function/OCaml/test-a-function.ocaml rename to Task/Test-a-function/OCaml/test-a-function.ml diff --git a/Task/Test-a-function/Rust/test-a-function.rust b/Task/Test-a-function/Rust/test-a-function.rs similarity index 100% rename from Task/Test-a-function/Rust/test-a-function.rust rename to Task/Test-a-function/Rust/test-a-function.rs diff --git a/Task/Test-a-function/Scheme/test-a-function.ss b/Task/Test-a-function/Scheme/test-a-function.scm similarity index 100% rename from Task/Test-a-function/Scheme/test-a-function.ss rename to Task/Test-a-function/Scheme/test-a-function.scm diff --git a/Task/Test-integerness/ALGOL-68/test-integerness.alg b/Task/Test-integerness/ALGOL-68/test-integerness.alg index 095c4812e2..13ffb0a068 100644 --- a/Task/Test-integerness/ALGOL-68/test-integerness.alg +++ b/Task/Test-integerness/ALGOL-68/test-integerness.alg @@ -1,11 +1,13 @@ # set the required precision of LONG LONG values using # # "PR precision n PR" if required # -PR precision 24 PR +# PR precision 24 PR # # not requied for ALGOL 68 Genie # + # the default precision is > 24 # + # and can't be reduced to 24 # # returns TRUE if v has an integer value, FALSE otherwise # OP ISINT = ( LONG LONG COMPL v )BOOL: IF im OF v /= 0 THEN - # v has an imaginary part # + # v has an imaginarh part # FALSE ELSE # v has a real part only # @@ -15,7 +17,10 @@ OP ISINT = ( LONG LONG COMPL v )BOOL: # test ISINT # PROC test is int = ( LONG LONG COMPLEX v )VOID: - print( ( re OF v, "_", im OF v, IF ISINT v THEN " is " ELSE " is not " FI, "integral", newline ) ); + BEGIN + print( ( float( re OF v, -36, 28, 4 ), "_", float( im OF v, -36, 28, 4 ) ) ); + print( ( IF ISINT v THEN " is " ELSE " is not " FI, "integral", newline ) ) + END # test is int # ; test is int( 1 ); diff --git a/Task/Test-integerness/Delphi/test-integerness.delphi b/Task/Test-integerness/Delphi/test-integerness.pas similarity index 100% rename from Task/Test-integerness/Delphi/test-integerness.delphi rename to Task/Test-integerness/Delphi/test-integerness.pas diff --git a/Task/Test-integerness/Elixir/test-integerness.elixir b/Task/Test-integerness/Elixir/test-integerness.ex similarity index 100% rename from Task/Test-integerness/Elixir/test-integerness.elixir rename to Task/Test-integerness/Elixir/test-integerness.ex diff --git a/Task/Test-integerness/Julia/test-integerness.julia b/Task/Test-integerness/Julia/test-integerness.jl similarity index 100% rename from Task/Test-integerness/Julia/test-integerness.julia rename to Task/Test-integerness/Julia/test-integerness.jl diff --git a/Task/Test-integerness/Kotlin/test-integerness.kotlin b/Task/Test-integerness/Kotlin/test-integerness.kts similarity index 100% rename from Task/Test-integerness/Kotlin/test-integerness.kotlin rename to Task/Test-integerness/Kotlin/test-integerness.kts diff --git a/Task/Text-processing-1/FreeBASIC/text-processing-1.basic b/Task/Text-processing-1/FreeBASIC/text-processing-1.basic new file mode 100644 index 0000000000..9a6b487dcb --- /dev/null +++ b/Task/Text-processing-1/FreeBASIC/text-processing-1.basic @@ -0,0 +1,60 @@ +Dim As String filename = "readings.txt" +Dim As String linea, Part, salida, ErrEnds, rejected_date, Tabu = Chr(9) +Dim As Integer i, posic, startPos, endPos, Errcnt, ErrMax, rejects, +Dim As Integer readings, max_rejected, n_rejected +Dim As Double lsum, tsum, valor + +Open filename For Input As #1 + +Do While Not Eof(1) + Line Input #1, linea + salida = "" + lsum = 0 + rejects = 0 + posic = 1 + For i = 1 To 1 + 2 * 24 + startPos = posic + endPos = Instr(posic, linea, Tabu) + If endPos = 0 Then endPos = Len(linea) + 1 + Part = Mid(linea, startPos, endPos - startPos) + posic = endPos + 1 + + If i = 1 Then ' Date + salida = Part + Elseif i Mod 2 = 0 Then ' Recorded value + valor = Val(Part) + Else ' Status part + If Val(Part) > 0 Then + Errcnt = 0 + readings += 1 + lsum += valor + tsum += valor + Else + rejects += 1 + Errcnt += 1 + If Errcnt > ErrMax Then + ErrMax = Errcnt + ErrEnds = salida + End If + End If + End If + Next i + salida &= " Rejects: " & Str(rejects) + salida &= " Accepts: " & Str(24 - rejects) + salida &= " Line_tot: " & Str(lsum) + If rejects < 24 Then + salida &= " Line_avg: " & Str(lsum / (24 - rejects)) + Else + salida &= " Line_avg: N/A" + End If + Print "Line: " & salida +Loop +Close #1 + +Print !"\nFile = " & filename +Print "Total = " & Str(tsum) +Print "Readings = " & Str(readings) +Print "Average = " & Str(tsum / readings) +Print !"\nMaximum of " & Str(ErrMax) & " consecutive false readings, ends at " & ErrEnds + +Sleep diff --git a/Task/Text-processing-1/Julia/text-processing-1.julia b/Task/Text-processing-1/Julia/text-processing-1.jl similarity index 100% rename from Task/Text-processing-1/Julia/text-processing-1.julia rename to Task/Text-processing-1/Julia/text-processing-1.jl diff --git a/Task/Text-processing-1/Kotlin/text-processing-1.kotlin b/Task/Text-processing-1/Kotlin/text-processing-1.kts similarity index 100% rename from Task/Text-processing-1/Kotlin/text-processing-1.kotlin rename to Task/Text-processing-1/Kotlin/text-processing-1.kts diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-1.l b/Task/Text-processing-1/NewLISP/text-processing-1-1.l new file mode 100644 index 0000000000..4c24a4cd09 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-1.l @@ -0,0 +1,3 @@ +(let (handle (open "readings.txt" "read")) + (setq all-lines (collect (read-line handle))) + (close handle)) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-2.l b/Task/Text-processing-1/NewLISP/text-processing-1-2.l new file mode 100644 index 0000000000..472f20188b --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-2.l @@ -0,0 +1,22 @@ +;; (20.0 "1990-01-01" 1 0) +(define (line->matrix line) + (letn (fields (parse line {\s+} 0) + day (pop fields) + lst) + (for (i 0 (- (length fields) 1) 2) + (push (array 4 (list (float (fields i)) day (int (fields (+ i 1))) 0)) + lst -1)) + lst)) + +(setq all-readings + (array (* 24 (length all-lines)) 4 + '(0.0 "2000-00-00" 0 0)) + _ nil) + +(let (cnt 0) + (dolist (line all-lines) + (setq one-day (line->matrix line)) + (dolist (reading one-day) + (setf (all-readings cnt) reading) + (++ cnt))) + 'ok) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-3.l b/Task/Text-processing-1/NewLISP/text-processing-1-3.l new file mode 100644 index 0000000000..ea178fb586 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-3.l @@ -0,0 +1,7 @@ +(local (prev) + (dotimes (i (length all-readings)) + (unless (= 1 (all-readings i -2)) + (setq prev + (if (zero? i) 0 (all-readings (- i 1) -1))) + (setf (all-readings i -1) (+ 1 prev)))) + 'ok) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-4.l b/Task/Text-processing-1/NewLISP/text-processing-1-4.l new file mode 100644 index 0000000000..057ed0f1c7 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-4.l @@ -0,0 +1,2 @@ +(setq len (apply max (clean zero? (map last all-readings)))) +(println "Longest run of bad readings: " len) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-5.l b/Task/Text-processing-1/NewLISP/text-processing-1-5.l new file mode 100644 index 0000000000..7cfc640564 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-5.l @@ -0,0 +1,4 @@ +(setq days + (map (fn(i) (all-readings i 1)) + (index (curry = len) (map last all-readings)))) +(println "Bad runs with that length ended on these days: " days) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-6.l b/Task/Text-processing-1/NewLISP/text-processing-1-6.l new file mode 100644 index 0000000000..3f1f116190 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-6.l @@ -0,0 +1,3 @@ +(setq grand-total (apply add (map first all-readings))) +(setq grand-count (length (filter zero? (map last all-readings)))) +(println "Total number of bad readings: " (- (length all-readings) grand-count)) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-7.l b/Task/Text-processing-1/NewLISP/text-processing-1-7.l new file mode 100644 index 0000000000..f7822c96e1 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-7.l @@ -0,0 +1,2 @@ +(println (format "Grand total: %.3f Count: %d Average: %.3f" + grand-total grand-count (div grand-total grand-count))) diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-8.l b/Task/Text-processing-1/NewLISP/text-processing-1-8.l new file mode 100644 index 0000000000..40375e3fa9 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-8.l @@ -0,0 +1,4 @@ +(define (get-day day) + (filter (fn(e) (= day (e 1))) (array-list all-readings))) + +(get-day "1993-03-05") diff --git a/Task/Text-processing-1/NewLISP/text-processing-1-9.l b/Task/Text-processing-1/NewLISP/text-processing-1-9.l new file mode 100644 index 0000000000..0bcae6f2f3 --- /dev/null +++ b/Task/Text-processing-1/NewLISP/text-processing-1-9.l @@ -0,0 +1,8 @@ +(define (sum-day day) + (letn (lst (filter (fn(a) (= 1 (a 2))) (get-day day)) + tot (apply add (map first lst))) + (println (format "%s Good readings: %d Total: %.3f Avg.: %.3f" + day (length lst) tot + (div tot (if (zero? (length lst)) 0 (length lst))))))) + +(sum-day "1993-03-05") diff --git a/Task/Text-processing-1/OCaml/text-processing-1.ocaml b/Task/Text-processing-1/OCaml/text-processing-1.ml similarity index 100% rename from Task/Text-processing-1/OCaml/text-processing-1.ocaml rename to Task/Text-processing-1/OCaml/text-processing-1.ml diff --git a/Task/Text-processing-2/Julia/text-processing-2.julia b/Task/Text-processing-2/Julia/text-processing-2.jl similarity index 100% rename from Task/Text-processing-2/Julia/text-processing-2.julia rename to Task/Text-processing-2/Julia/text-processing-2.jl diff --git a/Task/Text-processing-2/Kotlin/text-processing-2.kotlin b/Task/Text-processing-2/Kotlin/text-processing-2.kts similarity index 100% rename from Task/Text-processing-2/Kotlin/text-processing-2.kotlin rename to Task/Text-processing-2/Kotlin/text-processing-2.kts diff --git a/Task/Text-processing-2/OCaml/text-processing-2.ocaml b/Task/Text-processing-2/OCaml/text-processing-2.ml similarity index 100% rename from Task/Text-processing-2/OCaml/text-processing-2.ocaml rename to Task/Text-processing-2/OCaml/text-processing-2.ml diff --git a/Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.euphoria b/Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.ex similarity index 100% rename from Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.euphoria rename to Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.ex diff --git a/Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.julia b/Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.jl similarity index 100% rename from Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.julia rename to Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.jl diff --git a/Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kotlin b/Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kts similarity index 100% rename from Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kotlin rename to Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kts diff --git a/Task/Text-processing-Max-licenses-in-use/NewLISP/text-processing-max-licenses-in-use-1.l b/Task/Text-processing-Max-licenses-in-use/NewLISP/text-processing-max-licenses-in-use-1.l new file mode 100644 index 0000000000..a713a11629 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/NewLISP/text-processing-max-licenses-in-use-1.l @@ -0,0 +1,18 @@ +(define (foo , INOUT Time mxcnt cnt line times tokens a) + (let (handle (open "mlijobs.txt" "read")) + (while (setq line (read-line handle)) + (setq tokens (parse line {[ ]+} 0)) + ;; Match the 7 tokens. + (when (setq a (unify '(_ INOUT _ Time _ _ _) tokens)) + (bind a) ;; Assign to variables INOUT and Time. + (case INOUT + ("OUT" + (when (> (++ cnt) mxcnt) (setq mxcnt cnt) (setq times '())) + (if (= cnt mxcnt) (push Time times))) + ("IN" (-- cnt))))) + (close handle) + (list mxcnt times))) + +(foo) + +(99 ("2008/10/03_08:40:40" "2008/10/03_08:39:34")) diff --git a/Task/Text-processing-Max-licenses-in-use/NewLISP/text-processing-max-licenses-in-use-2.l b/Task/Text-processing-Max-licenses-in-use/NewLISP/text-processing-max-licenses-in-use-2.l new file mode 100644 index 0000000000..00eb819859 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/NewLISP/text-processing-max-licenses-in-use-2.l @@ -0,0 +1,10 @@ +(define (foo , mxcnt cnt times) + (let (handle (open "mlijobs.txt" "read")) + (while (search handle { (IN|OUT) +@ +(\S+)} true 0) + (case $1 + ("OUT" + (when (> (++ cnt) mxcnt) (setq mxcnt cnt) (setq times '())) + (if (= cnt mxcnt) (push $2 times))) + ("IN" (-- cnt)))) + (close handle) + (list mxcnt times))) diff --git a/Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ocaml b/Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ml similarity index 100% rename from Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ocaml rename to Task/Text-processing-Max-licenses-in-use/OCaml/text-processing-max-licenses-in-use.ml diff --git a/Task/Text-processing-Max-licenses-in-use/Rust/text-processing-max-licenses-in-use.rust b/Task/Text-processing-Max-licenses-in-use/Rust/text-processing-max-licenses-in-use.rs similarity index 100% rename from Task/Text-processing-Max-licenses-in-use/Rust/text-processing-max-licenses-in-use.rust rename to Task/Text-processing-Max-licenses-in-use/Rust/text-processing-max-licenses-in-use.rs diff --git a/Task/Textonyms/Delphi/textonyms.delphi b/Task/Textonyms/Delphi/textonyms.pas similarity index 100% rename from Task/Textonyms/Delphi/textonyms.delphi rename to Task/Textonyms/Delphi/textonyms.pas diff --git a/Task/Textonyms/FreeBASIC/textonyms.basic b/Task/Textonyms/FreeBASIC/textonyms.basic new file mode 100644 index 0000000000..3a2e2b609e --- /dev/null +++ b/Task/Textonyms/FreeBASIC/textonyms.basic @@ -0,0 +1,78 @@ +Type KeyValuePair + As String key + As String value +End Type + +' Simulate a dictionary with an array +Dim Shared keyMap(0 To 7) As KeyValuePair +keyMap(0).key = "ABC" : keyMap(0).value = "2" +keyMap(1).key = "DEF" : keyMap(1).value = "3" +keyMap(2).key = "GHI" : keyMap(2).value = "4" +keyMap(3).key = "JKL" : keyMap(3).value = "5" +keyMap(4).key = "MNO" : keyMap(4).value = "6" +keyMap(5).key = "PQRS" : keyMap(5).value = "7" +keyMap(6).key = "TUV" : keyMap(6).value = "8" +keyMap(7).key = "WXYZ" : keyMap(7).value = "9" + +Function GetKeyMapValue(char As String) As String + For i As Integer = Lbound(keyMap) To Ubound(keyMap) + If Instr(keyMap(i).key, Ucase(char)) > 0 Then Return keyMap(i).value + Next + Return "" +End Function + +Function ArrayExists(arr() As String, value As String) As Boolean + For i As Integer = Lbound(arr) To Ubound(arr) + If arr(i) = value Then Return True + Next + Return False +End Function + +Dim As Integer TotalWords = 0 +Dim As Integer UniqueCombinations = 0 +Dim As String uniqueWords(), moreThanOneWord() + +Dim As String inputFile = "unixdict.txt" +Dim As Integer ff = Freefile() +Open inputFile For Input As #ff +If Err <> 0 Then Print "Error: Unable to open file '" & inputFile & "'": End 1 + +Dim As String linea, num, char, digit +Dim As Integer c, i +Do Until Eof(ff) + Line Input #ff, linea + If Len(linea) > 0 Then + num = "" + c = 0 + For i = 1 To Len(linea) + char = Mid(linea, i, 1) + digit = GetKeyMapValue(char) + If digit <> "" Then + num &= digit + c += 1 + End If + Next i + + If c = Len(linea) Then + TotalWords += 1 + If Ubound(uniqueWords) = -1 Orelse Not ArrayExists(uniqueWords(), num) Then + Redim Preserve uniqueWords(0 To Ubound(uniqueWords) + 1) + uniqueWords(Ubound(uniqueWords)) = num + UniqueCombinations += 1 + Else + If Ubound(moreThanOneWord) = -1 Orelse Not ArrayExists(moreThanOneWord(), num) Then + Redim Preserve moreThanOneWord(0 To Ubound(moreThanOneWord) + 1) + moreThanOneWord(Ubound(moreThanOneWord)) = num + End If + End If + End If + End If +Loop + +Close #ff + +Print "There are " & TotalWords & " words in ""unixdict.txt"" which can be represented by the digit key mapping." +Print "They require " & UniqueCombinations & " digit combinations to represent them." +Print Ubound(moreThanOneWord) + 1 & " digit combinations represent Textonyms." + +Sleep diff --git a/Task/Textonyms/Julia/textonyms-1.julia b/Task/Textonyms/Julia/textonyms-1.jl similarity index 100% rename from Task/Textonyms/Julia/textonyms-1.julia rename to Task/Textonyms/Julia/textonyms-1.jl diff --git a/Task/Textonyms/Julia/textonyms-2.julia b/Task/Textonyms/Julia/textonyms-2.jl similarity index 100% rename from Task/Textonyms/Julia/textonyms-2.julia rename to Task/Textonyms/Julia/textonyms-2.jl diff --git a/Task/Textonyms/Kotlin/textonyms.kotlin b/Task/Textonyms/Kotlin/textonyms.kts similarity index 100% rename from Task/Textonyms/Kotlin/textonyms.kotlin rename to Task/Textonyms/Kotlin/textonyms.kts diff --git a/Task/Textonyms/OCaml/textonyms.ocaml b/Task/Textonyms/OCaml/textonyms.ml similarity index 100% rename from Task/Textonyms/OCaml/textonyms.ocaml rename to Task/Textonyms/OCaml/textonyms.ml diff --git a/Task/Textonyms/Rust/textonyms.rust b/Task/Textonyms/Rust/textonyms.rs similarity index 100% rename from Task/Textonyms/Rust/textonyms.rust rename to Task/Textonyms/Rust/textonyms.rs diff --git a/Task/The-Name-Game/COBOL/the-name-game.cobol b/Task/The-Name-Game/COBOL/the-name-game.cobol new file mode 100644 index 0000000000..642968d068 --- /dev/null +++ b/Task/The-Name-Game/COBOL/the-name-game.cobol @@ -0,0 +1,58 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. TheGameName. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 nombre PIC X(20). + 01 x PIC X(20). + 01 x0 PIC X(1). + 01 y PIC X(20). + 01 b PIC X(20). + 01 f PIC X(20). + 01 m PIC X(20). + 01 i PIC 9(2) VALUE 1. + 01 listanombres OCCURS 6 TIMES PIC X(20). + + PROCEDURE DIVISION. + MAIN-PROCEDURE. + MOVE "Gary" TO listanombres(1) + MOVE "EARL" TO listanombres(2) + MOVE "billy" TO listanombres(3) + MOVE "FeLiX" TO listanombres(4) + MOVE "Mary" TO listanombres(5) + MOVE "ShirlEY" TO listanombres(6) + + PERFORM VARYING i FROM 1 BY 1 UNTIL i > 6 + MOVE listanombres(i) TO nombre + PERFORM TheGameName + END-PERFORM + STOP RUN. + + TheGameName. + MOVE FUNCTION LOWER-CASE(nombre) TO x + MOVE FUNCTION UPPER-CASE(x(1:1)) TO x0 + STRING x0 DELIMITED BY SIZE + x(2:) DELIMITED BY SIZE INTO x + + IF x0 = "A" OR x0 = "E" OR x0 = "I" OR x0 = "O" OR x0 = "U" + MOVE FUNCTION LOWER-CASE(x) TO y + ELSE + MOVE x(2:) TO y + END-IF + + STRING "b" y DELIMITED BY SIZE INTO b + STRING "f" y DELIMITED BY SIZE INTO f + STRING "m" y DELIMITED BY SIZE INTO m + + IF x0 = "B" + MOVE y TO b + ELSE IF x0 = "F" + MOVE y TO f + ELSE IF x0 = "M" + MOVE y TO m + END-IF + + DISPLAY x ", " x ", bo-" b + DISPLAY "Banana-fana fo-" f + DISPLAY "Fee-fi-mo-" m + DISPLAY x "!". diff --git a/Task/The-Name-Game/Chipmunk-Basic/the-name-game.basic b/Task/The-Name-Game/Chipmunk-Basic/the-name-game.basic new file mode 100644 index 0000000000..4929548d80 --- /dev/null +++ b/Task/The-Name-Game/Chipmunk-Basic/the-name-game.basic @@ -0,0 +1,39 @@ +100 sub thegamename(nombre$) +110 x$ = lcase$(nombre$) +120 x$ = ucase$(mid$(x$,1,1))+mid$(x$,2,len(x$)-1) +130 x0$ = ucase$(mid$(x$,1,1)) +140 if x0$ = "A" or x0$ = "E" or x0$ = "I" or x0$ = "O" or x0$ = "U" then +150 y$ = lcase$(x$) +160 else +170 y$ = mid$(x$,2) +180 endif +190 b$ = "b"+y$ +200 f$ = "f"+y$ +210 m$ = "m"+y$ +220 if x0$ = "B" then +230 b$ = y$ +240 else +245 if x0$ = "F" then +250 f$ = y$ +260 else +265 if x0$ = "M" then +270 m$ = y$ +275 endif +276 endif +280 endif +290 print x$+", "+x$+", bo-"+b$ +300 print "Banana-fana fo-"+f$ +310 print "Fee-fi-mo-"+m$ +320 print x$+"!"+chr$(10) +330 end sub +340 dim listanombres$(5) +350 listanombres$(0) = "Gary" +360 listanombres$(1) = "EARL" +370 listanombres$(2) = "billy" +380 listanombres$(3) = "FeLiX" +390 listanombres$(4) = "Mary" +400 listanombres$(5) = "ShirlEY" +410 for i = 0 to ubound(listanombres$) +420 thegamename(listanombres$(i)) +430 next i +440 end diff --git a/Task/The-Name-Game/Dart/the-name-game.dart b/Task/The-Name-Game/Dart/the-name-game.dart new file mode 100644 index 0000000000..17e64a51b0 --- /dev/null +++ b/Task/The-Name-Game/Dart/the-name-game.dart @@ -0,0 +1,40 @@ +void theGameName(String nombre) { + String x = nombre.toLowerCase(); + x = x[0].toUpperCase() + x.substring(1); + String x0 = x[0].toUpperCase(); + + String y; + if (x0 == 'A' || x0 == 'E' || x0 == 'I' || x0 == 'O' || x0 == 'U') { + y = x.toLowerCase(); + } else { + y = x.substring(1); + } + + String b = 'b' + y; + String f = 'f' + y; + String m = 'm' + y; + + switch (x0) { + case 'B': + b = y; + break; + case 'F': + f = y; + break; + case 'M': + m = y; + break; + } + + print('$x, $x, bo-$b'); + print('Banana-fana fo-$f'); + print('Fee-fi-mo-$m'); + print('$x!\n'); +} + +void main() { + List listanombres = ['Gary', 'Earl', 'Billy', 'Felix', 'Mary', 'Steve']; + for (String nombre in listanombres) { + theGameName(nombre); + } +} diff --git a/Task/The-Name-Game/Delphi/the-name-game.delphi b/Task/The-Name-Game/Delphi/the-name-game.pas similarity index 100% rename from Task/The-Name-Game/Delphi/the-name-game.delphi rename to Task/The-Name-Game/Delphi/the-name-game.pas diff --git a/Task/The-Name-Game/Gambas/the-name-game.gambas b/Task/The-Name-Game/Gambas/the-name-game.gambas new file mode 100644 index 0000000000..2a49800c1d --- /dev/null +++ b/Task/The-Name-Game/Gambas/the-name-game.gambas @@ -0,0 +1,38 @@ +Public Sub TheGameName(nombre As String) + + Dim x As String = LCase(nombre) + x = UCase(Mid(x, 1, 1)) & Mid(x, 2, Len(x) - 1) + Dim x0 As String = UCase(Mid(x, 1, 1)) + + Dim y As String + y = IIf((x0 = "A" Or x0 = "E" Or x0 = "I" Or x0 = "O" Or x0 = "U"), LCase(x), Mid(x, 2)) + + Dim b As String = "b" & y + Dim f As String = "f" & y + Dim m As String = "m" & y + + Select Case x0 + Case "B" + b = y + Case "F" + f = y + Case "M" + m = y + End Select + + Print x & ", " & x & ", bo-" & b + Print "Banana-fana fo-" & f + Print "Fee-fi-mo-" & m + Print x & "!" & Chr(10) + +End Sub + +Public Sub Main() + + Dim listanombres As String[] = ["Gary", "EARL", "billy", "FeLiX", "Mary", "ShirlEY"] + + For Each nombre As String In listanombres + TheGameName(nombre) + Next + +End diff --git a/Task/The-Name-Game/Julia/the-name-game.julia b/Task/The-Name-Game/Julia/the-name-game.jl similarity index 100% rename from Task/The-Name-Game/Julia/the-name-game.julia rename to Task/The-Name-Game/Julia/the-name-game.jl diff --git a/Task/The-Name-Game/Kotlin/the-name-game.kotlin b/Task/The-Name-Game/Kotlin/the-name-game.kts similarity index 100% rename from Task/The-Name-Game/Kotlin/the-name-game.kotlin rename to Task/The-Name-Game/Kotlin/the-name-game.kts diff --git a/Task/The-Name-Game/PureBasic/the-name-game.basic b/Task/The-Name-Game/PureBasic/the-name-game.basic new file mode 100644 index 0000000000..4f9ee1b30d --- /dev/null +++ b/Task/The-Name-Game/PureBasic/the-name-game.basic @@ -0,0 +1,41 @@ +OpenConsole() +Procedure TheGameName(nombre.s) + x.s = LCase(nombre) + x = UCase(Mid(x, 1, 1)) + Mid(x, 2, Len(x) - 1) + x0.s = UCase(Mid(x, 1, 1)) + + If x0 = "A" Or x0 = "E" Or x0 = "I" Or x0 = "O" Or x0 = "U" + y.s = LCase(x) + Else + y.s = Mid(x, 2, Len(x) - 1) + EndIf + + b.s = "b" + y + f.s = "f" + y + m.s = "m" + y + + Select x0 + Case "B" + b = y + Case "F" + f = y + Case "M" + m = y + EndSelect + + PrintN(x + ", " + x + ", bo-" + b + #CRLF$ + "Banana-fana fo-" + f + #CRLF$ + "Fee-fi-mo-" + m + #CRLF$ + x + "!" + #CRLF$) +EndProcedure + +Dim listanombres.s(5) +listanombres(0) = "Gary" +listanombres(1) = "EARL" +listanombres(2) = "billy" +listanombres(3) = "FeLiX" +listanombres(4) = "Mary" +listanombres(5) = "ShirlEY" + +For i = 0 To 5 + TheGameName(listanombres(i)) +Next i +Input() +CloseConsole() diff --git a/Task/The-Name-Game/QBasic/the-name-game.basic b/Task/The-Name-Game/QBasic/the-name-game.basic new file mode 100644 index 0000000000..3fb536cda1 --- /dev/null +++ b/Task/The-Name-Game/QBasic/the-name-game.basic @@ -0,0 +1,48 @@ +DECLARE SUB TheGameName (nombre AS STRING) + +DIM listanombres(5) AS STRING +listanombres(0) = "Gary" +listanombres(1) = "EARL" +listanombres(2) = "billy" +listanombres(3) = "FeLiX" +listanombres(4) = "Mary" +listanombres(5) = "ShirlEY" + +FOR i = 0 TO UBOUND(listanombres) + TheGameName (listanombres(i)) +NEXT i + +SUB TheGameName (nombre AS STRING) + DIM x AS STRING + x = LCASE$(nombre) + x = UCASE$(MID$(x, 1, 1)) + (MID$(x, 2, LEN(x) - 1)) + DIM x0 AS STRING + x0 = UCASE$(MID$(x, 1, 1)) + + DIM y AS STRING + IF x0 = "A" OR x0 = "E" OR x0 = "I" OR x0 = "O" OR x0 = "U" THEN + y = LCASE$(x) + ELSE + y = MID$(x, 2) + END IF + + DIM b AS STRING + b = "b" + y + DIM f AS STRING + f = "f" + y + DIM m AS STRING + m = "m" + y + + IF x0 = "B" THEN + b = y + ELSEIF x0 = "F" THEN + f = y + ELSEIF x0 = "M" THEN + m = y + END IF + + PRINT x + ", " + x + ", bo-" + b + PRINT "Banana-fana fo-" + f + PRINT "Fee-fi-mo-" + m + PRINT x + "!" + CHR$(10) +END SUB diff --git a/Task/The-Name-Game/Run-BASIC/the-name-game.basic b/Task/The-Name-Game/Run-BASIC/the-name-game.basic new file mode 100644 index 0000000000..badabe9c46 --- /dev/null +++ b/Task/The-Name-Game/Run-BASIC/the-name-game.basic @@ -0,0 +1,36 @@ +dim listanombres$(5) + +for i = 0 to 5 + read listanombres$ + call TheGameName listanombres$ +next i +data "Gary", "EARL", "billy", "FeLiX", "Mary", "ShirleY" +end + +sub TheGameName nombre$ + x$ = lower$(nombre$) + x$ = upper$(mid$(x$, 1, 1)) + mid$(x$, 2, len(x$) - 1) + x0$ = upper$(mid$(x$, 1, 1)) + + if x0$ = "A" or x0$ = "E" or x0$ = "I" or x0$ = "O" or x0$ = "U" then + y$ = lower$(x$) + else + y$ = mid$(x$, 2) + end if + + b$ = "b" + y$ + f$ = "f" + y$ + m$ = "m" + y$ + + select case x0$ + case "B" : b$ = y$ + case "F" : f$ = y$ + case "M" : m$ = y$ + end select + + print x$ + ", " + x$ + ", bo-" + b$ + print "Banana-fana fo-" + f$ + print "Fee-fi-mo-" + m$ + print x$ + "!" + print +end sub diff --git a/Task/The-Name-Game/Rust/the-name-game.rs b/Task/The-Name-Game/Rust/the-name-game.rs new file mode 100644 index 0000000000..102d63d621 --- /dev/null +++ b/Task/The-Name-Game/Rust/the-name-game.rs @@ -0,0 +1,20 @@ +fn verse(name: &str) -> String { + let lower_name = name.to_lowercase(); + let mut x = lower_name.clone(); + x.replace_range(0..1, x[0..1].to_uppercase().as_str()); + let y = if "AEIOU".contains(&x[0..=0]) {lower_name.as_str()} else {&x[1..]}; + let b = if &x[0..1] == "B" {""} else {"b"}; + let f = if &x[0..1] == "F" {""} else {"f"}; + let m = if &x[0..1] == "M"{""} else {"m"}; + return format!(r#" + {x}, {x}, bo-{b}{y} + Banana-fana fo-{f}{y} + Fee-fi-mo-{m}{y} + {x}!"#); +} + +fn main() { + for name in ["gARY", "Earl", "Billy", "Felix", "Mary", "sHIRley"] { + println!("{}", verse(name)); + } +} diff --git a/Task/The-Name-Game/True-BASIC/the-name-game.basic b/Task/The-Name-Game/True-BASIC/the-name-game.basic new file mode 100644 index 0000000000..f09adc2da2 --- /dev/null +++ b/Task/The-Name-Game/True-BASIC/the-name-game.basic @@ -0,0 +1,44 @@ +OPTION BASE 0 + +SUB thegamename (nombre$) + LET x$ = LCASE$(nombre$) + LET x$ = UCASE$((x$)[1:1+1-1]) & ((x$)[2:2+LEN(x$)-1-1]) + LET x0$ = UCASE$((x$)[1:1+1-1]) + + IF x0$ = "A" OR x0$ = "E" OR x0$ = "I" OR x0$ = "O" OR x0$ = "U" THEN + LET y$ = LCASE$(x$) + ELSE + LET y$ = (x$)[2:maxnum] + END IF + + LET b$ = "b" & y$ + LET f$ = "f" & y$ + LET m$ = "m" & y$ + + IF x0$ = "B" THEN + LET b$ = y$ + ELSEIF x0$ = "F" THEN + LET f$ = y$ + ELSEIF x0$ = "M" THEN + LET m$ = y$ + END IF + + PRINT x$ & ", " & x$ & ", bo-" & b$ + PRINT "Banana-fana fo-" & f$ + PRINT "Fee-fi-mo-" & m$ + PRINT x$ & "!" + PRINT +END SUB + +DIM listanombres$(5) +LET listanombres$(0) = "Gary" +LET listanombres$(1) = "EARL" +LET listanombres$(2) = "billy" +LET listanombres$(3) = "FeLiX" +LET listanombres$(4) = "Mary" +LET listanombres$(5) = "ShirlEY" + +FOR i = 0 TO UBOUND(listanombres$) + CALL thegamename(listanombres$(i)) +NEXT i +END diff --git a/Task/The-Name-Game/V-(Vlang)/the-name-game.v b/Task/The-Name-Game/V-(Vlang)/the-name-game.v index 458e587d25..38e71ecfa9 100644 --- a/Task/The-Name-Game/V-(Vlang)/the-name-game.v +++ b/Task/The-Name-Game/V-(Vlang)/the-name-game.v @@ -1,24 +1,24 @@ fn main() { - list := ['Gary', 'Earl', 'Billy', 'Felix', 'Mary'] + list := ["Gary", "Earl", "Billy", "Felix", "Mary"] for name in list {verse(name)} } fn verse(name string) { - mut b, mut f, mut m, mut y :='','','','' + mut b, mut f, mut m, mut y :="","","","" mut x := name.to_lower().title() y = x.substr(1, x.len) - if 'AEIOU'.contains(x[0].ascii_str()) {y = x.to_lower()} - b = 'b' + y - f = 'f' + y - m = 'm' + y + if "AEIOU".contains(x[0].ascii_str()) {y = x.to_lower()} + b = "b" + y + f = "f" + y + m = "m" + y match x[0].ascii_str() { - 'B' {b = y} - 'F' {f = y} - 'M' {m = y} + "B" {b = y} + "F" {f = y} + "M" {m = y} else {} } - println('$x, $x, bo-$b') - println('Banana-fana fo-$f') - println('Fee-fi-mo-$m') - println('$x!\n') + println("${x}, ${x}, bo-${b}") + println("Banana-fana fo-${f}") + println("Fee-fi-mo-${m}") + println("${x}!\n") } diff --git a/Task/The-Name-Game/XBasic/the-name-game.basic b/Task/The-Name-Game/XBasic/the-name-game.basic new file mode 100644 index 0000000000..8feb7bad55 --- /dev/null +++ b/Task/The-Name-Game/XBasic/the-name-game.basic @@ -0,0 +1,53 @@ +PROGRAM "The Name Game" +VERSION "0.0000" + +DECLARE FUNCTION Entry () +DECLARE FUNCTION TheGameName (nombre$) + +FUNCTION Entry () + DIM listanombres$[5] + listanombres$[0] = "Gary" + listanombres$[1] = "EARL" + listanombres$[2] = "billy" + listanombres$[3] = "FeLiX" + listanombres$[4] = "Mary" + listanombres$[5] = "ShirlEY" + + FOR i = 0 TO 5 + TheGameName(listanombres$[i]) + NEXT i +END FUNCTION + +FUNCTION TheGameName (nombre$) + x$ = LCASE$(nombre$) + x$ = UCASE$(MID$(x$, 1, 1)) + MID$(x$, 2, LEN(x$) - 1) + x0$ = UCASE$(MID$(x$, 1, 1)) + + IF (x0$ = "A") OR (x0$ = "E") OR (x0$ = "I") OR (x0$ = "O") OR (x0$ = "U") THEN + y$ = LCASE$(x$) + ELSE + y$ = MID$(x$, 2, LEN(x$) - 1) + END IF + + b$ = "b" + y$ + f$ = "f" + y$ + m$ = "m" + y$ + + IF x0$ = "B" THEN + b$ = y$ + ELSE + IF x0$ = "F" THEN + f$ = y$ + ELSE + IF x0$ = "M" THEN + m$ = y$ + END IF + END IF + END IF + + PRINT x$ + ", " + x$ + ", bo-" + b$ + PRINT "Banana-fana fo-" + f$ + PRINT "Fee-fi-mo-" + m$ + PRINT x$ + "!" + CHR$(10) +END FUNCTION +END PROGRAM diff --git a/Task/The-Name-Game/Yabasic/the-name-game.basic b/Task/The-Name-Game/Yabasic/the-name-game.basic new file mode 100644 index 0000000000..1677912eea --- /dev/null +++ b/Task/The-Name-Game/Yabasic/the-name-game.basic @@ -0,0 +1,40 @@ +dim listanombres$(5) +listanombres$(0) = "Gary" +listanombres$(1) = "EARL" +listanombres$(2) = "billy" +listanombres$(3) = "FeLiX" +listanombres$(4) = "Mary" +listanombres$(5) = "ShirlEY" + +for i = 0 to arraysize(listanombres$(), 1) + TheGameName(listanombres$(i)) +next i +end + +sub TheGameName(nombre$) + local x$, x0$, y$, b$, f$, m$ + x$ = lower$(nombre$) + x$ = upper$(mid$(x$, 1, 1)) + mid$(x$, 2, len(x$) - 1) + x0$ = upper$(mid$(x$, 1, 1)) + + if x0$ = "A" or x0$ = "E" or x0$ = "I" or x0$ = "O" or x0$ = "U" then + y$ = lower$(x$) + else + y$ = mid$(x$, 2) + end if + + b$ = "b" + y$ + f$ = "f" + y$ + m$ = "m" + y$ + + switch x0$ + case "B" : b$ = y$ + case "F" : f$ = y$ + case "M" : m$ = y$ + end switch + + print x$ + ", " + x$ + ", bo-" + b$ + print "Banana-fana fo-" + f$ + print "Fee-fi-mo-" + m$ + print x$ + "!" + chr$(10) +end sub diff --git a/Task/The-Twelve-Days-of-Christmas/Crystal/the-twelve-days-of-christmas.crystal b/Task/The-Twelve-Days-of-Christmas/Crystal/the-twelve-days-of-christmas.cr similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Crystal/the-twelve-days-of-christmas.crystal rename to Task/The-Twelve-Days-of-Christmas/Crystal/the-twelve-days-of-christmas.cr diff --git a/Task/The-Twelve-Days-of-Christmas/Delphi/the-twelve-days-of-christmas.delphi b/Task/The-Twelve-Days-of-Christmas/Delphi/the-twelve-days-of-christmas.pas similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Delphi/the-twelve-days-of-christmas.delphi rename to Task/The-Twelve-Days-of-Christmas/Delphi/the-twelve-days-of-christmas.pas diff --git a/Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.elixir b/Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.ex similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.elixir rename to Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.ex diff --git a/Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.julia b/Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.jl similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.julia rename to Task/The-Twelve-Days-of-Christmas/Julia/the-twelve-days-of-christmas.jl diff --git a/Task/The-Twelve-Days-of-Christmas/Kotlin/the-twelve-days-of-christmas.kotlin b/Task/The-Twelve-Days-of-Christmas/Kotlin/the-twelve-days-of-christmas.kts similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Kotlin/the-twelve-days-of-christmas.kotlin rename to Task/The-Twelve-Days-of-Christmas/Kotlin/the-twelve-days-of-christmas.kts diff --git a/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust b/Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rs similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rust rename to Task/The-Twelve-Days-of-Christmas/Rust/the-twelve-days-of-christmas.rs diff --git a/Task/The-Twelve-Days-of-Christmas/Scheme/the-twelve-days-of-christmas.ss b/Task/The-Twelve-Days-of-Christmas/Scheme/the-twelve-days-of-christmas.scm similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Scheme/the-twelve-days-of-christmas.ss rename to Task/The-Twelve-Days-of-Christmas/Scheme/the-twelve-days-of-christmas.scm diff --git a/Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas.tailspin b/Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas-1.tailspin similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas.tailspin rename to Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas-1.tailspin diff --git a/Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas-2.tailspin b/Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas-2.tailspin new file mode 100644 index 0000000000..92111b6f5d --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Tailspin/the-twelve-days-of-christmas-2.tailspin @@ -0,0 +1,31 @@ +ordinal is ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth']; +gift is [ + 'a partridge in a pear tree', + 'two turtle-doves', + 'three French hens', + 'four calling birds', + 'five golden rings', + 'six geese a-laying', + 'seven swans a-swimming', + 'eight maids a-milking', + 'nine ladies dancing', + 'ten lords a-leaping', + 'eleven pipers piping', + 'twelve drummers drumming' +]; +punctuation templates + when <|=1> do '.' ! + when <|=2> do ' and' ! + when <|=5> do ';' ! + otherwise ',' ! +end punctuation + +'$: 1..12 -> templates + 'On the $ordinal($); day of Christmas, +my true love gave to me: +' ! + $..1:-1 -> '$gift($);$->punctuation; +' ! +' +' ! +end;' ! diff --git a/Task/The-sieve-of-Sundaram/Julia/the-sieve-of-sundaram.julia b/Task/The-sieve-of-Sundaram/Julia/the-sieve-of-sundaram.jl similarity index 100% rename from Task/The-sieve-of-Sundaram/Julia/the-sieve-of-sundaram.julia rename to Task/The-sieve-of-Sundaram/Julia/the-sieve-of-sundaram.jl diff --git a/Task/Thieles-interpolation-formula/FreeBASIC/thieles-interpolation-formula.basic b/Task/Thieles-interpolation-formula/FreeBASIC/thieles-interpolation-formula.basic index c204e37408..c985f58b5b 100644 --- a/Task/Thieles-interpolation-formula/FreeBASIC/thieles-interpolation-formula.basic +++ b/Task/Thieles-interpolation-formula/FreeBASIC/thieles-interpolation-formula.basic @@ -12,7 +12,12 @@ For i As Integer = 1 To n1 tTan(i) = Tan(xVal(i)) Next i -Dim As Integer rSin, rCos, rTan, rTrig +Enum + rSin + rCos + rTan + rTrig +End Enum Dim Shared rhot(rTrig, n2) As Double For i As Integer = 0 To rTrig @@ -42,7 +47,7 @@ Function thieleInterpolator(x() As Double, y() As Double, _ + (xin-x(n+1)) / thieleInterpolator(x(), y(), rdx, xin, n+1) End Function -Print " PI : 3.141592653589793" +Print " PI : "; 4 * Atn(1) Print " 6*arcsin(0.5) : "; 6 * Asin(0.5) Print " 3*arccos(0.5) : "; 3 * Acos(0.5) Print " 4*arctan(1.0) : "; 4 * Atn(1.0) diff --git a/Task/Thieles-interpolation-formula/Julia/thieles-interpolation-formula.julia b/Task/Thieles-interpolation-formula/Julia/thieles-interpolation-formula.jl similarity index 100% rename from Task/Thieles-interpolation-formula/Julia/thieles-interpolation-formula.julia rename to Task/Thieles-interpolation-formula/Julia/thieles-interpolation-formula.jl diff --git a/Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kotlin b/Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kts similarity index 100% rename from Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kotlin rename to Task/Thieles-interpolation-formula/Kotlin/thieles-interpolation-formula.kts diff --git a/Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ocaml b/Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ml similarity index 100% rename from Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ocaml rename to Task/Thieles-interpolation-formula/OCaml/thieles-interpolation-formula.ml diff --git a/Task/Thieles-interpolation-formula/Rust/thieles-interpolation-formula.rust b/Task/Thieles-interpolation-formula/Rust/thieles-interpolation-formula.rs similarity index 100% rename from Task/Thieles-interpolation-formula/Rust/thieles-interpolation-formula.rust rename to Task/Thieles-interpolation-formula/Rust/thieles-interpolation-formula.rs diff --git a/Task/Thue-Morse/Crystal/thue-morse.crystal b/Task/Thue-Morse/Crystal/thue-morse.cr similarity index 100% rename from Task/Thue-Morse/Crystal/thue-morse.crystal rename to Task/Thue-Morse/Crystal/thue-morse.cr diff --git a/Task/Thue-Morse/Elixir/thue-morse.elixir b/Task/Thue-Morse/Elixir/thue-morse.ex similarity index 100% rename from Task/Thue-Morse/Elixir/thue-morse.elixir rename to Task/Thue-Morse/Elixir/thue-morse.ex diff --git a/Task/Thue-Morse/Julia/thue-morse.julia b/Task/Thue-Morse/Julia/thue-morse.jl similarity index 100% rename from Task/Thue-Morse/Julia/thue-morse.julia rename to Task/Thue-Morse/Julia/thue-morse.jl diff --git a/Task/Thue-Morse/Kotlin/thue-morse-1.kotlin b/Task/Thue-Morse/Kotlin/thue-morse-1.kts similarity index 100% rename from Task/Thue-Morse/Kotlin/thue-morse-1.kotlin rename to Task/Thue-Morse/Kotlin/thue-morse-1.kts diff --git a/Task/Thue-Morse/Kotlin/thue-morse-2.kotlin b/Task/Thue-Morse/Kotlin/thue-morse-2.kts similarity index 100% rename from Task/Thue-Morse/Kotlin/thue-morse-2.kotlin rename to Task/Thue-Morse/Kotlin/thue-morse-2.kts diff --git a/Task/Thue-Morse/OCaml/thue-morse-1.ocaml b/Task/Thue-Morse/OCaml/thue-morse-1.ml similarity index 100% rename from Task/Thue-Morse/OCaml/thue-morse-1.ocaml rename to Task/Thue-Morse/OCaml/thue-morse-1.ml diff --git a/Task/Thue-Morse/OCaml/thue-morse-2.ocaml b/Task/Thue-Morse/OCaml/thue-morse-2.ml similarity index 100% rename from Task/Thue-Morse/OCaml/thue-morse-2.ocaml rename to Task/Thue-Morse/OCaml/thue-morse-2.ml diff --git a/Task/Thue-Morse/Rust/thue-morse.rust b/Task/Thue-Morse/Rust/thue-morse.rs similarity index 100% rename from Task/Thue-Morse/Rust/thue-morse.rust rename to Task/Thue-Morse/Rust/thue-morse.rs diff --git a/Task/Tic-tac-toe/Delphi/tic-tac-toe.delphi b/Task/Tic-tac-toe/Delphi/tic-tac-toe.pas similarity index 100% rename from Task/Tic-tac-toe/Delphi/tic-tac-toe.delphi rename to Task/Tic-tac-toe/Delphi/tic-tac-toe.pas diff --git a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy index 222a3071a8..fffa6c4109 100644 --- a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy +++ b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy @@ -82,7 +82,7 @@ proc minmax player alpha beta . rval rmov . . else rval = alpha - start = randint 9 + start = random 9 mov = start repeat if f[mov] = 0 diff --git a/Task/Tic-tac-toe/Euphoria/tic-tac-toe.euphoria b/Task/Tic-tac-toe/Euphoria/tic-tac-toe.ex similarity index 100% rename from Task/Tic-tac-toe/Euphoria/tic-tac-toe.euphoria rename to Task/Tic-tac-toe/Euphoria/tic-tac-toe.ex diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-1.j b/Task/Tic-tac-toe/J/tic-tac-toe-1.j new file mode 100644 index 0000000000..69a658b77c --- /dev/null +++ b/Task/Tic-tac-toe/J/tic-tac-toe-1.j @@ -0,0 +1,8 @@ +'`turn board open full'=. {.`}.`(0=[{board@])`(0-.@e.board) +'`cpu pos'=. (?@#{])@([:I.0=board)`(cpu`you@.(_1 1 i.turn)) +you=. $:@echo@'no'^:(-.@e.i.@9)@:<:@".@(1!:1)@1@echo@'enter a move (1–9):' +move=. pos ($:@][echo@'no')`(-@turn@], turn@]`[`(board@])})@.open ] +outcome=. 'tie'"_`(' wins',~ {&'.XO'@-@turn)@.won +show=. [ ''echo@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$board) +won=. [: +./ 3 = [: | +/"1@(],|:,(<@0 1|:]),:<@0 1|:|.)@(3 3$board) +ttt=: [: outcome [: [F.(show@move[_2:Z:won+.full) 10&{.@_1 diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-2.j b/Task/Tic-tac-toe/J/tic-tac-toe-2.j new file mode 100644 index 0000000000..325f65948e --- /dev/null +++ b/Task/Tic-tac-toe/J/tic-tac-toe-2.j @@ -0,0 +1 @@ +Until=. {{[F.(u[_2:Z:v)}} NB. apply u until condition v is true diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-3.j b/Task/Tic-tac-toe/J/tic-tac-toe-3.j new file mode 100644 index 0000000000..5d221db368 --- /dev/null +++ b/Task/Tic-tac-toe/J/tic-tac-toe-3.j @@ -0,0 +1 @@ +ttt=: [: outcome [: show@move Until (won+.full) 10&{.@_1 diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-4.j b/Task/Tic-tac-toe/J/tic-tac-toe-4.j new file mode 100644 index 0000000000..dc3238ad10 --- /dev/null +++ b/Task/Tic-tac-toe/J/tic-tac-toe-4.j @@ -0,0 +1 @@ +{{u^:(-.@:v)^:_}} diff --git a/Task/Tic-tac-toe/J/tic-tac-toe.j b/Task/Tic-tac-toe/J/tic-tac-toe.j deleted file mode 100644 index 0c95ee3316..0000000000 --- a/Task/Tic-tac-toe/J/tic-tac-toe.j +++ /dev/null @@ -1,9 +0,0 @@ - '`turn board open full'=: {.`}.`(0=[{board@])`(0-.@e.board) - '`cpu_move position'=: (?@#{])@([:I.0=board)`(cpu_move`you_move@.(_1 1 i.turn)) - you_move=: $:@echo@'invalid'^:(-.@e.i.@9)@:<:@".@{.@;:@(1!:1@1) - move=: position (][echo@'already taken!')`(-@turn@] , turn@]`[`(board@])})@.open ] - show=: [ [: echo@''@echo (,' '&,)/"1@({&'.XO')@(3 3$board) [ echo@'' - won=: [: +./ (3=[:|+/)"1@(], |:, (<@i.@#|:]),: <@i.@#|:|.)@(3 3$board) - prompt=: echo@:>:@i.@3 3@echo@'enter a move (1–9) each turn; you''re X''s' - outcome=: (echo@'tie')`(' wins'echo@,~{&'.XO'@-@turn)@.won - ttt=: outcome@([F.(show@move[_2:Z:won+.full))@(10{._1)@prompt diff --git a/Task/Tic-tac-toe/Julia/tic-tac-toe.julia b/Task/Tic-tac-toe/Julia/tic-tac-toe.jl similarity index 100% rename from Task/Tic-tac-toe/Julia/tic-tac-toe.julia rename to Task/Tic-tac-toe/Julia/tic-tac-toe.jl diff --git a/Task/Tic-tac-toe/K/tic-tac-toe.k b/Task/Tic-tac-toe/K/tic-tac-toe.k new file mode 100644 index 0000000000..fc73404088 --- /dev/null +++ b/Task/Tic-tac-toe/K/tic-tac-toe.k @@ -0,0 +1,8 @@ +b::2 9#0 / the board +WINMASKS::((9#2)\)'7 56 448 73 146 292 273 84 / winning trios +fin:{`0:x," won";`exit 0} +{1}{({`1:"MOVE: ";$[(|/b)m:(`I$-1_1:`)-1;o`0:"NO";b[0;m]::1]} / your move + {b[1;(|/b)?0]::1})[x;0] / cpu's move + x{`0:" "/'`c$3 3#|/"XO*"*b,,~|/b}/0 / show board after cpu moves + $[+/3=0^WINMASKS(+/&)\:b x;fin "XO*" x;511=2/|/b;fin"the cat"] / test win + ~x}/1 / now it's other player's turn diff --git a/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin b/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kts similarity index 100% rename from Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin rename to Task/Tic-tac-toe/Kotlin/tic-tac-toe.kts diff --git a/Task/Tic-tac-toe/Rust/tic-tac-toe.rust b/Task/Tic-tac-toe/Rust/tic-tac-toe.rs similarity index 100% rename from Task/Tic-tac-toe/Rust/tic-tac-toe.rust rename to Task/Tic-tac-toe/Rust/tic-tac-toe.rs diff --git a/Task/Time-a-function/Delphi/time-a-function.delphi b/Task/Time-a-function/Delphi/time-a-function.pas similarity index 100% rename from Task/Time-a-function/Delphi/time-a-function.delphi rename to Task/Time-a-function/Delphi/time-a-function.pas diff --git a/Task/Time-a-function/EasyLang/time-a-function.easy b/Task/Time-a-function/EasyLang/time-a-function.easy index e5f6214948..a24f8c8a9b 100644 --- a/Task/Time-a-function/EasyLang/time-a-function.easy +++ b/Task/Time-a-function/EasyLang/time-a-function.easy @@ -1,4 +1,4 @@ -func fua lim . +func sumrange lim . # this is interpreted i = 1 while i <= lim @@ -8,10 +8,10 @@ func fua lim . return sum . start = systime -print fua 1e8 +print sumrange 1e8 print systime - start # -fastfunc fub lim . +fastfunc sumrangef lim . # this is compiled to wasm i = 1 while i <= lim @@ -21,5 +21,5 @@ fastfunc fub lim . return sum . start = systime -print fub 1e8 +print sumrangef 1e8 print systime - start diff --git a/Task/Time-a-function/Elixir/time-a-function-1.elixir b/Task/Time-a-function/Elixir/time-a-function-1.ex similarity index 100% rename from Task/Time-a-function/Elixir/time-a-function-1.elixir rename to Task/Time-a-function/Elixir/time-a-function-1.ex diff --git a/Task/Time-a-function/Elixir/time-a-function-2.elixir b/Task/Time-a-function/Elixir/time-a-function-2.ex similarity index 100% rename from Task/Time-a-function/Elixir/time-a-function-2.elixir rename to Task/Time-a-function/Elixir/time-a-function-2.ex diff --git a/Task/Time-a-function/Elixir/time-a-function-3.elixir b/Task/Time-a-function/Elixir/time-a-function-3.ex similarity index 100% rename from Task/Time-a-function/Elixir/time-a-function-3.elixir rename to Task/Time-a-function/Elixir/time-a-function-3.ex diff --git a/Task/Time-a-function/Euphoria/time-a-function.euphoria b/Task/Time-a-function/Euphoria/time-a-function.ex similarity index 100% rename from Task/Time-a-function/Euphoria/time-a-function.euphoria rename to Task/Time-a-function/Euphoria/time-a-function.ex diff --git a/Task/Time-a-function/FutureBasic/time-a-function.basic b/Task/Time-a-function/FutureBasic/time-a-function.basic new file mode 100644 index 0000000000..8924c2338a --- /dev/null +++ b/Task/Time-a-function/FutureBasic/time-a-function.basic @@ -0,0 +1,62 @@ +begin enum 1 + _numLabel + _numInput + _textField + _computeTime +end enum + +void local fn BuildMacInterface + window 1, @"Prime factors", ( 0, 0, 560, 120 ), NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + textlabel _numLabel, @"Number to factor:", ( 155, 86, 148, 24 ) + textfield _numInput, Yes, @"", ( 280, 88, 160, 24 ) + TextFieldSetTextColor ( _numLabel, fn ColorGray ) + ControlSetAlignment ( _numInput, NSTextAlignmentCenter ) + ControlSetFormat ( _numInput, @"0123456789-", YES, 15, _formatCaseInsensitive ) + ControlSetFont ( _numInput, fn FontSystemFontOfSize( 13 ) ) + textfield _textField, YES, , ( 20, 46, 520, 26 ) + ControlSetFontWithName ( _textField, @"Menlo", 12 ) + ControlSetAlignment( _textField, NSTextAlignmentCenter ) + TextFieldSetBordered( _textField, YES ) + textlabel _computeTime,,( 350, 16, 188, 22 ) + ControlSetAlignment( _computeTime, NSTextAlignmentRight ) + filemenu 1 : menu 1, , No + editmenu 2 : menu 2, , Yes + WindowMakeFirstResponder ( 1, _numInput ) +end fn + + +void local fn factor + SInt64 i, count = 0, num = fn ControlIntegerValue( _numInput ), n = num + if n < 0 then n = -n + while ( n mod 2 == 0 ) + mda(count) = 2 : count++ : n = n/2 + wend + for i = 3 to sqr(n) + 1 step 2 + while ( n mod i == 0 ) + mda(count) = i : count++ : n = n/i + wend + next + if (n > 2) then mda(count) = n + if num < 0 then mda(0) = -mda_integer(0) + CFStringRef s = fn StringByReplacingOccurrencesOfString( mda_text, @"\n", @" * " ) : mda_kill + s = fn StringByTrimmingCharactersInSet( s, fn CharacterSetWithCharactersInString( @" * " ) ) + ControlSetStringValue( _textField, fn StringWithFormat( @"%@ = %lld", s, num ) ) +end fn + + +void local fn DoDialog( ev as Long ) + select ev + case _controlTextDidEndEditing + CFTimeInterval t = fn CACurrentMediaTime + fn Factor + ControlSetStringValue( _computeTime, fn StringWithFormat( @"Compute time: %.3f ms", (fn CACurrentMediaTime-t)*1000 ) ) + WindowMakeFirstResponder( _textField, _numInput ) + case _windowWillClose : end + end select +end fn + +fn BuildMacInterface + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Time-a-function/Julia/time-a-function.julia b/Task/Time-a-function/Julia/time-a-function.jl similarity index 100% rename from Task/Time-a-function/Julia/time-a-function.julia rename to Task/Time-a-function/Julia/time-a-function.jl diff --git a/Task/Time-a-function/Kotlin/time-a-function.kotlin b/Task/Time-a-function/Kotlin/time-a-function.kts similarity index 100% rename from Task/Time-a-function/Kotlin/time-a-function.kotlin rename to Task/Time-a-function/Kotlin/time-a-function.kts diff --git a/Task/Time-a-function/Nu/time-a-function.nu b/Task/Time-a-function/Nu/time-a-function.nu new file mode 100644 index 0000000000..069519aa2b --- /dev/null +++ b/Task/Time-a-function/Nu/time-a-function.nu @@ -0,0 +1 @@ +timeit { sleep 1ms } diff --git a/Task/Time-a-function/OCaml/time-a-function.ocaml b/Task/Time-a-function/OCaml/time-a-function.ml similarity index 100% rename from Task/Time-a-function/OCaml/time-a-function.ocaml rename to Task/Time-a-function/OCaml/time-a-function.ml diff --git a/Task/Time-a-function/REXX/time-a-function-1.rexx b/Task/Time-a-function/REXX/time-a-function-1.rexx index 0e752fd011..9afaf04611 100644 --- a/Task/Time-a-function/REXX/time-a-function-1.rexx +++ b/Task/Time-a-function/REXX/time-a-function-1.rexx @@ -1,27 +1,5 @@ -/*REXX program displays the elapsed time for a REXX function (or subroutine). */ -arg reps . /*obtain an optional argument from C.L.*/ -if reps=='' then reps=100000 /*Not specified? No, then use default.*/ -call time 'Reset' /*only the 1st character is examined. */ -junk = silly(reps) /*invoke the SILLY function (below). */ - /*───► CALL SILLY REPS also works.*/ - - /* The E is for elapsed time.*/ - /* │ ─ */ - /* ┌────◄───┘ */ - /* │ */ - /* ↓ */ -say 'function SILLY took' format(time("E"),,2) 'seconds for' reps "iterations." - /* ↑ */ - /* │ */ - /* ┌────────►───────┘ */ - /* │ */ - /* The above 2 for the FORMAT function displays the time with*/ - /* two decimal digits (rounded) past the decimal point). Using */ - /* a 0 (zero) would round the time to whole seconds. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -silly: procedure /*chew up some CPU time doing some silly stuff.*/ - do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */ - @.j=random() date() time() digits() fuzz() form() xrange() queued() - end /*j*/ - return j-1 +do x = 1 to 40 + say time('l') time('e') + do y = 1 to 10000 + end +end diff --git a/Task/Time-a-function/REXX/time-a-function-2.rexx b/Task/Time-a-function/REXX/time-a-function-2.rexx index 4d8817660a..0e752fd011 100644 --- a/Task/Time-a-function/REXX/time-a-function-2.rexx +++ b/Task/Time-a-function/REXX/time-a-function-2.rexx @@ -5,12 +5,12 @@ call time 'Reset' /*only the 1st character is examined. */ junk = silly(reps) /*invoke the SILLY function (below). */ /*───► CALL SILLY REPS also works.*/ - /* The J is for the CPU time used */ - /* │ by the REXX program since */ - /* ┌───────┘ since the time was RESET. */ - /* │ This is a Regina extension.*/ + /* The E is for elapsed time.*/ + /* │ ─ */ + /* ┌────◄───┘ */ + /* │ */ /* ↓ */ -say 'function SILLY took' format(time("J"),,2) 'seconds for' reps "iterations." +say 'function SILLY took' format(time("E"),,2) 'seconds for' reps "iterations." /* ↑ */ /* │ */ /* ┌────────►───────┘ */ diff --git a/Task/Time-a-function/REXX/time-a-function-3.rexx b/Task/Time-a-function/REXX/time-a-function-3.rexx new file mode 100644 index 0000000000..4d8817660a --- /dev/null +++ b/Task/Time-a-function/REXX/time-a-function-3.rexx @@ -0,0 +1,27 @@ +/*REXX program displays the elapsed time for a REXX function (or subroutine). */ +arg reps . /*obtain an optional argument from C.L.*/ +if reps=='' then reps=100000 /*Not specified? No, then use default.*/ +call time 'Reset' /*only the 1st character is examined. */ +junk = silly(reps) /*invoke the SILLY function (below). */ + /*───► CALL SILLY REPS also works.*/ + + /* The J is for the CPU time used */ + /* │ by the REXX program since */ + /* ┌───────┘ since the time was RESET. */ + /* │ This is a Regina extension.*/ + /* ↓ */ +say 'function SILLY took' format(time("J"),,2) 'seconds for' reps "iterations." + /* ↑ */ + /* │ */ + /* ┌────────►───────┘ */ + /* │ */ + /* The above 2 for the FORMAT function displays the time with*/ + /* two decimal digits (rounded) past the decimal point). Using */ + /* a 0 (zero) would round the time to whole seconds. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +silly: procedure /*chew up some CPU time doing some silly stuff.*/ + do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */ + @.j=random() date() time() digits() fuzz() form() xrange() queued() + end /*j*/ + return j-1 diff --git a/Task/Time-a-function/REXX/time-a-function-4.rexx b/Task/Time-a-function/REXX/time-a-function-4.rexx new file mode 100644 index 0000000000..d4b24082bd --- /dev/null +++ b/Task/Time-a-function/REXX/time-a-function-4.rexx @@ -0,0 +1,485 @@ +Main: +call Parameters +call DoToLoops +call DoForLoops +call Tarra +call IntegerAssign +call IntegerAdd +call IntegerSubtract +call IntegerMultiply +call IntegerDivide1 +call IntegerDivide2 +call IntegerRemainder +call IntegerPower +call FloatingAssign +call FloatingAdd +call FloatingSubtract +call FloatingMultiply +call FloatingDivide1 +call FloatingDivide2 +call FloatingRemainder +call FloatingPower +call Formula +call StringFunctions +call NumericFunctions +call FixedParseVar +call DynamicParseVar +call NoOperation +call IfThen +call SelectWhen +call IfElseIf +call CallProc +call CallProcParms +call CallRout +call CallRoutParms +call DateTime +call PushPullQueued +call Interpreting +call Output +call Input +call StemProcessing +return + +Parameters: +arg count digit +if count = '' then + count = 1e6 +if digit = '' then + digit = 9 +numeric digits digit +parse version version +say 'Version' version +say 'Using loop counter' count/1e6 'million and' digits() 'digits' +say +tarra = 0 +call time('r') +return + +DoToLoops: +call time('r') +do x = 1 to count*10 +end +call Measure 'Do ... to ...',10 +return + +DoForLoops: +call time('r') +do x = 1 for count*10 +end +call Measure 'Do ... for ...',10 +return + +Tarra: +call time('r') +do x = 1 to count*10 +end +tarra = time('e')/10 +return + +IntegerAssign: +call time('r') +do x = 1 to count*10 + a = 123 +end +call Measure 'Integer assign',10 +return + +IntegerAdd: +call time('r') +do x = 1 to count*10 + a = x+123 +end +call Measure 'Integer +',10 +return + +IntegerSubtract: +call time('r') +do x = 1 to count*10 + a = x-123 +end +call Measure 'Integer -',10 +return + +IntegerMultiply: +call time('r') +do x = 1 to count*10 + a = x*123 +end +call Measure 'Integer *',10 +return + +IntegerDivide1: +call time('r') +do x = 1 to count*10 + a = 123/3 +end +call Measure 'Integer /',10 +return + +IntegerDivide2: +call time('r') +do x = 1 to count*10 + a = x//123 +end +call Measure 'Integer //',10 +return + +IntegerRemainder: +call time('r') +do x = 1 to count*10 + a = x%123 +end +call Measure 'Integer %',10 +return + +IntegerPower: +call time('r') +do x = 1 to count*10 + a = 123**2 +end +call Measure 'Integer **',10 +return + +FloatingAssign: +call time('r') +do x = 1 to count*10 + a = 1.23 +end +call Measure 'Floating assign',10 +return + +FloatingAdd: +call time('r') +do x = 1 to count*10 + a = x+1.23 +end +call Measure 'Floating +',10 +return + +FloatingSubtract: +call time('r') +do x = 1 to count*10 + a = x-1.23 +end +call Measure 'Floating -',10 +return + +FloatingMultiply: +call time('r') +do x = 1 to count*10 + a = x*1.23 +end +call Measure 'Floating *',10 +return + +FloatingDivide1: +call time('r') +do x = 1 to count*10 + a = x/1.23 +end +call Measure 'Floating /',10 +return + +FloatingDivide2: +call time('r') +do x = 1 to count*10 + a = x//1.23 +end +call Measure 'Floating //',10 +return + +FloatingRemainder: +call time('r') +do x = 1 to count*10 + a = x%1.23 +end +call Measure 'Floating %',10 +return + +FloatingPower: +call time('r') +do x = 1 to count*10 + a = 1.23**2 +end +call Measure 'Floating **',10 +return + +Formula: +call time('r') +do x = 1 to count + a = ( (x+1.23) * (x-1.23) ) / ( (x*1.23) * (x/1.23) ) +end +call Measure 'Formula',1 +return + +StringFunctions: +a = 'this is the first text'; b = 'this is the second text'; c = 1.23 +call time('r') +do x = 1 to count + t = a||b + t = abbrev('text',a) + t = center(a,100) + t = compare(a,b) + t = copies(a,3) + t = delstr(a,5,10) + t = delword(a,2,3) + t = format(c,1,2) + t = insert(a,b,10) + t = lastpos('text',a) + t = left(a,10) + t = length(a) + t = overlay('paul',a,4) + t = pos('text',a) + t = reverse(a) + t = right(a,10) + t = space(a) + t = strip(a) + t = substr(a,5,10) + t = subword(a,2,2) + t = translate(a,'one','the') + t = verify(a,'the') + t = word(a,3) + t = wordindex(a,3) + t = wordlength(a,3) + t = wordpos('is the',a) + t = words(a) + t = xrange('a','z') +end +call Measure 'String functions',28 +return + +NumericFunctions: +a = -1.23; b = 1.23 +call time('r') +do x = 1 to count + t = abs(a) + t = max(a,b) + t = min(a,b) + t = random() + t = sign(a) + t = trunc(b) + t = digits() +end +call Measure 'Numeric functions',7 +return + +FixedParseVar: +t = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20' +call time('r') +do x = 1 to count + parse var t rec1 ',' rec2 ',' rec3 ',' rec4 ',' rec5 ',' rec6 ',' rec7 ',' rec8 ',' rec9 ',' rec10 ',', + rec11 ',' rec12 ',' rec13 ',' rec14 ',' rec15 ',' rec16 ',' rec17 ',' rec18 ',' rec19 ',' rec20 ',' +end +call Measure 'Fixed parse var',1 +return + +DynamicParseVar: +t = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20' +call time('r') +do x = 1 to count + do y = 1 to 20 + parse var t rec.y ',' t + end +end +call Measure 'Dynamic parse var',1 +return + +NoOperation: +call time('r') +do x = 1 to count*10 + nop +end +call Measure 'No operation',10 +return + +IfThen: +a = 1 +call time('r') +do x = 1 to count + if a = 1 then nop + if a = 2 then nop + if a <> 1 then nop + if a <> 2 then nop + if a < 0 then nop + if a < 2 then nop + if a > 0 then nop + if a > 2 then nop +end +call Measure 'If ...then ...',8 +return + +SelectWhen: +a = 2 +call time('r') +do x = 1 to count + select + when a = 1 then nop + when a = 2 then nop + when a = 3 then nop + end + select + when a <> 2 then nop + when a <> 1 then nop + when a <> 0 then nop + end + select + when a > 2 then nop + when a > 1 then nop + when a > 0 then nop + end + select + when a < 2 then nop + when a < 3 then nop + when a < 4 then nop + end +end +call Measure 'Select ... when ...',8 +return + +IfElseIf: +a = 2 +call time('r') +do x = 1 to count + if a = 1 then nop + else if a = 2 then nop + else if a = 3 then nop + if a <> 2 then nop + else if a <> 1 then nop + else if a <> 0 then nop + if a > 2 then nop + else if a > 1 then nop + else if a > 0 then nop + if a < 2 then nop + else if a < 3 then nop + else if a < 4 then nop +end +call Measure 'If ... else if ...',8 +return + +CallProc: +call time('r') +do x = 1 to count + call Proc1 +end +call Measure 'Call procedure',1 +return + +CallProcParms: +call time('r') +do x = 1 to count + call Proc2 1,2,3 +end +call Measure 'Call procedure with parms',1 +return + +CallRout: +call time('r') +do x = 1 to count + call Rout1 +end +call Measure 'Call routine',1 +return + +CallRoutParms: +call time('r') +do x = 1 to count + call Rout2 1,2,3 +end +call Measure 'Call routine with parms',1 +return + +Proc1: +procedure +return + +Proc2: +procedure +arg a,b,c +return + +Rout1: +return + +Rout2: +arg a,b,c +return + +DateTime: +call time('r') +do x = 1 to count + t = date('b') + t = date('d') + t = date('e') + t = date('m') + t = date('n') + t = date('o') + t = date('s') + t = date('u') + t = date('w') + t = time('c') + t = time('e') + t = time('h') + t = time('l') + t = time('m') + t = time('n') + t = time('s') +end +call Measure 'Date and time',16 +return + +PushPullQueued: +a = 123.45 +call time('r') +do x = 1 to count + push a + b = queued() + pull a +end +call Measure 'Push, pull and queued',3 +return + +Interpreting: +a = 'nop' +call time('r') +do x = 1 to count + interpret a +end +call Measure 'Interpret',1 +return + +Output: +file = '\temp\perf.txt' +call lineout file,,1 +call time('r') +do x = 1 to count + call lineout file,'sequence number of this record is' x +end +call Measure 'Output',1 +return + +Input: +file = '\temp\perf.txt' +call time('r') +do x = 1 to count + t = linein(file) +end +call Measure 'Input',1 +return + +StemProcessing: +call time('r') +do x = 1 to count + stem.x.x.x = 1.23 +end +call Measure 'Stem processing',1 +return + +Measure: +parse arg measure,clauses +elaps = time('e')-tarra +if elaps > 0 then do + say left(measure,25) format((count*clauses)/(1e6*elaps) ,3,1) 'million clauses/sec' +end +else + say left(measure,25) 'loop counter too low, cannot perform measure' +return diff --git a/Task/Time-a-function/Rust/time-a-function.rust b/Task/Time-a-function/Rust/time-a-function.rs similarity index 100% rename from Task/Time-a-function/Rust/time-a-function.rust rename to Task/Time-a-function/Rust/time-a-function.rs diff --git a/Task/Time-a-function/Scheme/time-a-function.ss b/Task/Time-a-function/Scheme/time-a-function.scm similarity index 100% rename from Task/Time-a-function/Scheme/time-a-function.ss rename to Task/Time-a-function/Scheme/time-a-function.scm diff --git a/Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.julia b/Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.jl similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.julia rename to Task/Tokenize-a-string-with-escaping/Julia/tokenize-a-string-with-escaping.jl diff --git a/Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kotlin b/Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kts similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kotlin rename to Task/Tokenize-a-string-with-escaping/Kotlin/tokenize-a-string-with-escaping.kts diff --git a/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ocaml b/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ml similarity index 100% rename from Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ocaml rename to Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-1.ml diff --git a/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ocaml b/Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ml similarity index 100% rename from Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ocaml rename to Task/Tokenize-a-string-with-escaping/OCaml/tokenize-a-string-with-escaping-2.ml diff --git a/Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rust b/Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rs similarity index 100% rename from Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rust rename to Task/Tokenize-a-string-with-escaping/Rust/tokenize-a-string-with-escaping.rs diff --git a/Task/Tokenize-a-string/Crystal/tokenize-a-string.crystal b/Task/Tokenize-a-string/Crystal/tokenize-a-string.cr similarity index 100% rename from Task/Tokenize-a-string/Crystal/tokenize-a-string.crystal rename to Task/Tokenize-a-string/Crystal/tokenize-a-string.cr diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-1.pas similarity index 100% rename from Task/Tokenize-a-string/Delphi/tokenize-a-string-1.delphi rename to Task/Tokenize-a-string/Delphi/tokenize-a-string-1.pas diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-2.pas similarity index 100% rename from Task/Tokenize-a-string/Delphi/tokenize-a-string-2.delphi rename to Task/Tokenize-a-string/Delphi/tokenize-a-string-2.pas diff --git a/Task/Tokenize-a-string/Delphi/tokenize-a-string-3.delphi b/Task/Tokenize-a-string/Delphi/tokenize-a-string-3.pas similarity index 100% rename from Task/Tokenize-a-string/Delphi/tokenize-a-string-3.delphi rename to Task/Tokenize-a-string/Delphi/tokenize-a-string-3.pas diff --git a/Task/Tokenize-a-string/Ed/tokenize-a-string.ed b/Task/Tokenize-a-string/Ed/tokenize-a-string.ed new file mode 100644 index 0000000000..cd1e1968bf --- /dev/null +++ b/Task/Tokenize-a-string/Ed/tokenize-a-string.ed @@ -0,0 +1,6 @@ +# by Artyom Bologov +H +,p +s/,/./g +,p +Q diff --git a/Task/Tokenize-a-string/Elixir/tokenize-a-string.elixir b/Task/Tokenize-a-string/Elixir/tokenize-a-string.ex similarity index 100% rename from Task/Tokenize-a-string/Elixir/tokenize-a-string.elixir rename to Task/Tokenize-a-string/Elixir/tokenize-a-string.ex diff --git a/Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria b/Task/Tokenize-a-string/Euphoria/tokenize-a-string.ex similarity index 100% rename from Task/Tokenize-a-string/Euphoria/tokenize-a-string.euphoria rename to Task/Tokenize-a-string/Euphoria/tokenize-a-string.ex diff --git a/Task/Tokenize-a-string/Julia/tokenize-a-string.julia b/Task/Tokenize-a-string/Julia/tokenize-a-string.jl similarity index 100% rename from Task/Tokenize-a-string/Julia/tokenize-a-string.julia rename to Task/Tokenize-a-string/Julia/tokenize-a-string.jl diff --git a/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin b/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kts similarity index 100% rename from Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin rename to Task/Tokenize-a-string/Kotlin/tokenize-a-string.kts diff --git a/Task/Tokenize-a-string/Nu/tokenize-a-string.nu b/Task/Tokenize-a-string/Nu/tokenize-a-string.nu new file mode 100644 index 0000000000..83ce8ca024 --- /dev/null +++ b/Task/Tokenize-a-string/Nu/tokenize-a-string.nu @@ -0,0 +1 @@ +'Hello,How,Are,You,Today' | split row ',' | str join '.' diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ml similarity index 100% rename from Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ocaml rename to Task/Tokenize-a-string/OCaml/tokenize-a-string-1.ml diff --git a/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml b/Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ml similarity index 100% rename from Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ocaml rename to Task/Tokenize-a-string/OCaml/tokenize-a-string-2.ml diff --git a/Task/Tokenize-a-string/Rust/tokenize-a-string.rust b/Task/Tokenize-a-string/Rust/tokenize-a-string.rs similarity index 100% rename from Task/Tokenize-a-string/Rust/tokenize-a-string.rust rename to Task/Tokenize-a-string/Rust/tokenize-a-string.rs diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-1.scm similarity index 100% rename from Task/Tokenize-a-string/Scheme/tokenize-a-string-1.ss rename to Task/Tokenize-a-string/Scheme/tokenize-a-string-1.scm diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-2.scm similarity index 100% rename from Task/Tokenize-a-string/Scheme/tokenize-a-string-2.ss rename to Task/Tokenize-a-string/Scheme/tokenize-a-string-2.scm diff --git a/Task/Tokenize-a-string/Scheme/tokenize-a-string-3.ss b/Task/Tokenize-a-string/Scheme/tokenize-a-string-3.scm similarity index 100% rename from Task/Tokenize-a-string/Scheme/tokenize-a-string-3.ss rename to Task/Tokenize-a-string/Scheme/tokenize-a-string-3.scm diff --git a/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.julia b/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.jl similarity index 100% rename from Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.julia rename to Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-1.jl diff --git a/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.julia b/Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.jl similarity index 100% rename from Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.julia rename to Task/Tonelli-Shanks-algorithm/Julia/tonelli-shanks-algorithm-2.jl diff --git a/Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kotlin b/Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kts similarity index 100% rename from Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kotlin rename to Task/Tonelli-Shanks-algorithm/Kotlin/tonelli-shanks-algorithm.kts diff --git a/Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ocaml b/Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ml similarity index 100% rename from Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ocaml rename to Task/Tonelli-Shanks-algorithm/OCaml/tonelli-shanks-algorithm.ml diff --git a/Task/Top-rank-per-group/Delphi/top-rank-per-group.delphi b/Task/Top-rank-per-group/Delphi/top-rank-per-group.pas similarity index 100% rename from Task/Top-rank-per-group/Delphi/top-rank-per-group.delphi rename to Task/Top-rank-per-group/Delphi/top-rank-per-group.pas diff --git a/Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir b/Task/Top-rank-per-group/Elixir/top-rank-per-group.ex similarity index 100% rename from Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir rename to Task/Top-rank-per-group/Elixir/top-rank-per-group.ex diff --git a/Task/Top-rank-per-group/Julia/top-rank-per-group.julia b/Task/Top-rank-per-group/Julia/top-rank-per-group.jl similarity index 100% rename from Task/Top-rank-per-group/Julia/top-rank-per-group.julia rename to Task/Top-rank-per-group/Julia/top-rank-per-group.jl diff --git a/Task/Top-rank-per-group/Kotlin/top-rank-per-group.kotlin b/Task/Top-rank-per-group/Kotlin/top-rank-per-group.kts similarity index 100% rename from Task/Top-rank-per-group/Kotlin/top-rank-per-group.kotlin rename to Task/Top-rank-per-group/Kotlin/top-rank-per-group.kts diff --git a/Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml b/Task/Top-rank-per-group/OCaml/top-rank-per-group.ml similarity index 100% rename from Task/Top-rank-per-group/OCaml/top-rank-per-group.ocaml rename to Task/Top-rank-per-group/OCaml/top-rank-per-group.ml diff --git a/Task/Top-rank-per-group/Rust/top-rank-per-group.rust b/Task/Top-rank-per-group/Rust/top-rank-per-group.rs similarity index 100% rename from Task/Top-rank-per-group/Rust/top-rank-per-group.rust rename to Task/Top-rank-per-group/Rust/top-rank-per-group.rs diff --git a/Task/Top-rank-per-group/Scheme/top-rank-per-group.ss b/Task/Top-rank-per-group/Scheme/top-rank-per-group-1.scm similarity index 100% rename from Task/Top-rank-per-group/Scheme/top-rank-per-group.ss rename to Task/Top-rank-per-group/Scheme/top-rank-per-group-1.scm diff --git a/Task/Top-rank-per-group/Scheme/top-rank-per-group-2.scm b/Task/Top-rank-per-group/Scheme/top-rank-per-group-2.scm new file mode 100644 index 0000000000..a0bcc4a366 --- /dev/null +++ b/Task/Top-rank-per-group/Scheme/top-rank-per-group-2.scm @@ -0,0 +1,72 @@ +(use srfi-197) ;; chain +(use gauche.collection) + +(define .salary (cut list-ref <> 2)) +(define .dept last) + +(define employee-data + (chain '(("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190)) + (group-collection _ :key .dept) + (map (^d (sort d > .salary)) _))) + +(define (foo n) + (dolist (dept employee-data) + (print (.dept (car dept))) + (for-each + (^e (apply format #t " ~15a ~a ~a\n" (take e 3))) + (take* dept n)) + (print))) + +(foo 2) + +D101 + George Woltman E00127 53500 + David McClellan E04242 41500 + +D050 + John Rappl E21437 47000 + Nathan Adams E41298 21900 + +D202 + Rich Holcomb E01234 49500 + Claire Buckman E39876 27800 + +D190 + Kim Arlich E10001 57000 + Timothy Grove E16398 29900 + + +(foo 8000) + +D101 + George Woltman E00127 53500 + David McClellan E04242 41500 + Tyler Bennett E10297 32000 + Tim Sampair E03033 27000 + Richard Potter E43128 15900 + +D050 + John Rappl E21437 47000 + Nathan Adams E41298 21900 + +D202 + Rich Holcomb E01234 49500 + Claire Buckman E39876 27800 + David Motsinger E27002 19250 + Adam Smith E63535 18000 + +D190 + Kim Arlich E10001 57000 + Timothy Grove E16398 29900 diff --git a/Task/Top-rank-per-group/Scheme/top-rank-per-group-3.scm b/Task/Top-rank-per-group/Scheme/top-rank-per-group-3.scm new file mode 100644 index 0000000000..004f707cee --- /dev/null +++ b/Task/Top-rank-per-group/Scheme/top-rank-per-group-3.scm @@ -0,0 +1,64 @@ +(define-syntax ainc! + (syntax-rules () + [(_ alist key val func default) + (let ((pair (assoc key alist))) + (if pair + (set-cdr! pair (func val (cdr pair))) + (set! alist (cons (cons key (func val default)) alist))))] + [(_ alist key val func) + (ainc! alist key val func 0)] + [(_ alist key val) + (ainc! alist key val +)] + [(_ alist key) + (ainc! alist key 1)])) + +(define .salary (cut list-ref <> 2)) +(define .dept last) + +(define employee-data + '(("Tyler Bennett" E10297 32000 D101) + ("John Rappl" E21437 47000 D050) + ("George Woltman" E00127 53500 D101) + ("Adam Smith" E63535 18000 D202) + ("Claire Buckman" E39876 27800 D202) + ("David McClellan" E04242 41500 D101) + ("Rich Holcomb" E01234 49500 D202) + ("Nathan Adams" E41298 21900 D050) + ("Richard Potter" E43128 15900 D101) + ("David Motsinger" E27002 19250 D202) + ("Tim Sampair" E03033 27000 D101) + ("Kim Arlich" E10001 57000 D190) + ("Timothy Grove" E16398 29900 D190))) + +(define (top-salaries n) + (let ((table '())) + (dolist (e employee-data) + (ainc! table + (.dept e) + (list e) + (lambda(new old) (merge new old > .salary)) + '())) + (dolist (dept table) + (print (car dept)) + (for-each + (^e (apply format #t " ~15a ~a ~a\n" (take e 3))) + (take* (cdr dept) n)) + (print)))) + +(top-salaries 2) + +D190 + Kim Arlich E10001 57000 + Timothy Grove E16398 29900 + +D202 + Rich Holcomb E01234 49500 + Claire Buckman E39876 27800 + +D050 + John Rappl E21437 47000 + Nathan Adams E41298 21900 + +D101 + George Woltman E00127 53500 + David McClellan E04242 41500 diff --git a/Task/Topic-variable/Julia/topic-variable.julia b/Task/Topic-variable/Julia/topic-variable.jl similarity index 100% rename from Task/Topic-variable/Julia/topic-variable.julia rename to Task/Topic-variable/Julia/topic-variable.jl diff --git a/Task/Topic-variable/Kotlin/topic-variable.kotlin b/Task/Topic-variable/Kotlin/topic-variable.kts similarity index 100% rename from Task/Topic-variable/Kotlin/topic-variable.kotlin rename to Task/Topic-variable/Kotlin/topic-variable.kts diff --git a/Task/Topic-variable/V-(Vlang)/topic-variable-1.v b/Task/Topic-variable/V-(Vlang)/topic-variable-1.v new file mode 100644 index 0000000000..a8e2d8dfd3 --- /dev/null +++ b/Task/Topic-variable/V-(Vlang)/topic-variable-1.v @@ -0,0 +1,9 @@ +// function that returns multiple values +fn foo() (int, int) { + return 2, 3 +} + +mut a, mut b := foo() +println("${a} and ${b}") +a, _ = foo() // to ignore particular returned values, the `_` is used +println(a) diff --git a/Task/Topic-variable/V-(Vlang)/topic-variable-2.v b/Task/Topic-variable/V-(Vlang)/topic-variable-2.v new file mode 100644 index 0000000000..491c68cbcf --- /dev/null +++ b/Task/Topic-variable/V-(Vlang)/topic-variable-2.v @@ -0,0 +1,9 @@ +// ignore values, while iterating over keys +m := { + 'one': 1 + 'two': 2 +} + +for key, _ in m { + println(key) +} diff --git a/Task/Topic-variable/V-(Vlang)/topic-variable-3.v b/Task/Topic-variable/V-(Vlang)/topic-variable-3.v new file mode 100644 index 0000000000..4dd7ac90f9 --- /dev/null +++ b/Task/Topic-variable/V-(Vlang)/topic-variable-3.v @@ -0,0 +1,4 @@ +// "it", used in filter and map +words := ['hello', 'world'] +upper := words.map(it.to_upper()) +println(upper) diff --git a/Task/Topological-sort/Crystal/topological-sort.crystal b/Task/Topological-sort/Crystal/topological-sort.cr similarity index 100% rename from Task/Topological-sort/Crystal/topological-sort.crystal rename to Task/Topological-sort/Crystal/topological-sort.cr diff --git a/Task/Topological-sort/Elixir/topological-sort.elixir b/Task/Topological-sort/Elixir/topological-sort.ex similarity index 100% rename from Task/Topological-sort/Elixir/topological-sort.elixir rename to Task/Topological-sort/Elixir/topological-sort.ex diff --git a/Task/Topological-sort/Julia/topological-sort.julia b/Task/Topological-sort/Julia/topological-sort.jl similarity index 100% rename from Task/Topological-sort/Julia/topological-sort.julia rename to Task/Topological-sort/Julia/topological-sort.jl diff --git a/Task/Topological-sort/Kotlin/topological-sort-1.kotlin b/Task/Topological-sort/Kotlin/topological-sort-1.kts similarity index 100% rename from Task/Topological-sort/Kotlin/topological-sort-1.kotlin rename to Task/Topological-sort/Kotlin/topological-sort-1.kts diff --git a/Task/Topological-sort/Kotlin/topological-sort-2.kotlin b/Task/Topological-sort/Kotlin/topological-sort-2.kts similarity index 100% rename from Task/Topological-sort/Kotlin/topological-sort-2.kotlin rename to Task/Topological-sort/Kotlin/topological-sort-2.kts diff --git a/Task/Topological-sort/OCaml/topological-sort.ocaml b/Task/Topological-sort/OCaml/topological-sort.ml similarity index 100% rename from Task/Topological-sort/OCaml/topological-sort.ocaml rename to Task/Topological-sort/OCaml/topological-sort.ml diff --git a/Task/Topological-sort/Rust/topological-sort.rust b/Task/Topological-sort/Rust/topological-sort.rs similarity index 100% rename from Task/Topological-sort/Rust/topological-sort.rust rename to Task/Topological-sort/Rust/topological-sort.rs diff --git a/Task/Topological-sort/Scheme/topological-sort.ss b/Task/Topological-sort/Scheme/topological-sort.scm similarity index 100% rename from Task/Topological-sort/Scheme/topological-sort.ss rename to Task/Topological-sort/Scheme/topological-sort.scm diff --git a/Task/Topswops/Elixir/topswops.elixir b/Task/Topswops/Elixir/topswops.ex similarity index 100% rename from Task/Topswops/Elixir/topswops.elixir rename to Task/Topswops/Elixir/topswops.ex diff --git a/Task/Topswops/Julia/topswops.julia b/Task/Topswops/Julia/topswops.jl similarity index 100% rename from Task/Topswops/Julia/topswops.julia rename to Task/Topswops/Julia/topswops.jl diff --git a/Task/Topswops/Kotlin/topswops.kotlin b/Task/Topswops/Kotlin/topswops.kts similarity index 100% rename from Task/Topswops/Kotlin/topswops.kotlin rename to Task/Topswops/Kotlin/topswops.kts diff --git a/Task/Topswops/Rust/topswops.rust b/Task/Topswops/Rust/topswops.rs similarity index 100% rename from Task/Topswops/Rust/topswops.rust rename to Task/Topswops/Rust/topswops.rs diff --git a/Task/Total-circles-area/Delphi/total-circles-area.delphi b/Task/Total-circles-area/Delphi/total-circles-area.pas similarity index 100% rename from Task/Total-circles-area/Delphi/total-circles-area.delphi rename to Task/Total-circles-area/Delphi/total-circles-area.pas diff --git a/Task/Total-circles-area/Julia/total-circles-area.julia b/Task/Total-circles-area/Julia/total-circles-area.jl similarity index 100% rename from Task/Total-circles-area/Julia/total-circles-area.julia rename to Task/Total-circles-area/Julia/total-circles-area.jl diff --git a/Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin b/Task/Total-circles-area/Kotlin/total-circles-area-1.kts similarity index 100% rename from Task/Total-circles-area/Kotlin/total-circles-area-1.kotlin rename to Task/Total-circles-area/Kotlin/total-circles-area-1.kts diff --git a/Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin b/Task/Total-circles-area/Kotlin/total-circles-area-2.kts similarity index 100% rename from Task/Total-circles-area/Kotlin/total-circles-area-2.kotlin rename to Task/Total-circles-area/Kotlin/total-circles-area-2.kts diff --git a/Task/Total-circles-area/Uiua/total-circles-area.uiua b/Task/Total-circles-area/Uiua/total-circles-area.uiua index 7d661b1bd2..fadba6ddda 100644 --- a/Task/Total-circles-area/Uiua/total-circles-area.uiua +++ b/Task/Total-circles-area/Uiua/total-circles-area.uiua @@ -1,45 +1,43 @@ -Cs ← [[1.6417233788 1.6121789534 0.0848270516] - [¯1.4944608174 1.2077959613 1.1039549836] - [0.6110294452 ¯0.6907087527 0.9089162485] - [0.3844862411 0.2923344616 0.2375743054] - [¯0.249589295 ¯0.3832854473 1.0845181219] - [1.7813504266 1.6178237031 0.8162655711] - [¯0.1985249206 ¯0.8343333301 0.0538864941] - [¯1.7011985145 ¯0.1263820964 0.4776976918] - [¯0.4319462812 1.4104420482 0.7886291537] - [0.2178372997 ¯0.9499557344 0.0357871187] - [¯0.6294854565 ¯1.3078893852 0.7653357688] - [1.7952608455 0.6281269104 0.2727652452] - [1.4168575317 1.0683357171 1.1016025378] - [1.4637371396 0.9463877418 1.1846214562] - [¯0.5263668798 1.7315156631 1.4428514068] - [¯1.2197352481 0.9144146579 1.0727263474] - [¯0.1389358881 0.109280578 0.7350208828] - [1.5293954595 0.0030278255 1.2472867347] - [¯0.5258728625 1.3782633069 1.3495508831] - [¯0.1403562064 0.2437382535 1.3804956588] - [0.8055826339 ¯0.0482092025 0.3327165165] - [¯0.6311979224 0.7184578971 0.2491045282] - [1.4685857879 ¯0.8347049536 1.3670667538] - [¯0.6855727502 1.6465021616 1.0593087096] - [0.0152957411 0.0638919221 0.9771215985]] +Cs ← [ + [1.6417233788 1.6121789534 0.0848270516] + [¯1.4944608174 1.2077959613 1.1039549836] + [0.6110294452 ¯0.6907087527 0.9089162485] + [0.3844862411 0.2923344616 0.2375743054] + [¯0.249589295 ¯0.3832854473 1.0845181219] + [1.7813504266 1.6178237031 0.8162655711] + [¯0.1985249206 ¯0.8343333301 0.0538864941] + [¯1.7011985145 ¯0.1263820964 0.4776976918] + [¯0.4319462812 1.4104420482 0.7886291537] + [0.2178372997 ¯0.9499557344 0.0357871187] + [¯0.6294854565 ¯1.3078893852 0.7653357688] + [1.7952608455 0.6281269104 0.2727652452] + [1.4168575317 1.0683357171 1.1016025378] + [1.4637371396 0.9463877418 1.1846214562] + [¯0.5263668798 1.7315156631 1.4428514068] + [¯1.2197352481 0.9144146579 1.0727263474] + [¯0.1389358881 0.109280578 0.7350208828] + [1.5293954595 0.0030278255 1.2472867347] + [¯0.5258728625 1.3782633069 1.3495508831] + [¯0.1403562064 0.2437382535 1.3804956588] + [0.8055826339 ¯0.0482092025 0.3327165165] + [¯0.6311979224 0.7184578971 0.2491045282] + [1.4685857879 ¯0.8347049536 1.3670667538] + [¯0.6855727502 1.6465021616 1.0593087096] + [0.0152957411 0.0638919221 0.9771215985]] -# Scale total range to (0-Dim,0-Dim), save MaxXorY for later. -Dim ← 500 -MinXY ← /↧≡(-⊃(⊢|↘1)↻¯1) Cs -Zcs ← ≡(⬚0-MinXY) Cs -MaxXorY ← /↥/↥≡(+⊃(⊢|↘1)↻¯1) Zcs -Scs ← ⁅×Dim÷ MaxXorY Zcs +# Translate so that minimal X-R, Y-R values are both 0. +Tcs ← -¤⊂:0/↧⍜⍉(+¤¯°⊂↻¯1).Cs +Dim ← 1000 +# Calculate scale factor to fit (0-Dim,0-Dim), save for later. +Scale ← ÷Dim/↥♭+≡(⊃(⊢|↘1)↻¯1) Tcs # For each r generate a 2r.2r grid and set cells that are within circle. -InCircle ← <ⁿ2⟜(⊞(/+≡ⁿ2⊟).+⇡⊃(×2|¯)) -# Fade this circle out, then add to accumulator, offset appropriately. -Filler ← ⍜(↻|⬚0+)⊙: ⊃(+¯|×0.1InCircle) ⊃(⊢|↘1) ↻¯1 -# Fold over all circles, accumulating into a blank grid. -⍜now(∧Filler Scs ↯Dim_Dim 0) +InCircle ← <ⁿ2⟜(⊞(/+ⁿ2⊟).+⇡⊃(×2|¯)) +# Offset that grid down/right, and fade it out, then add to accum. +Filler ← ⍜(↻|⬚0+)⊙: ⊃(+¯|×0.1InCircle) °⊂ ↻¯1 +# Fold over all scaled circles, accumulating into a blank grid. +&p ⍜now(∧Filler (⁅÷ Scale Tcs) ↯Dim_Dim 0) -&p &pf "Runtime (s): " -×ⁿ2 ÷Dim MaxXorY (⧻⊚≠0) ♭. -&p &pf "*Very* approximate area: " +&p $"Very approximate area: _" × ⁿ2 Scale (⧻⊚≠0) ♭. # Uncomment to save image. # &ime "png" diff --git a/Task/Totient-function/Ada/totient-function.ada b/Task/Totient-function/Ada/totient-function.ada index 90288642e9..8b42e4f17a 100644 --- a/Task/Totient-function/Ada/totient-function.ada +++ b/Task/Totient-function/Ada/totient-function.ada @@ -1,72 +1,76 @@ -with Ada.Text_IO; -with Ada.Integer_Text_IO; +with Ada.Text_IO; with Ada.Integer_Text_IO; +with Ada.Strings.Fixed; procedure Totient is - function Totient (N : in Integer) return Integer is - Tot : Integer := N; - I : Integer; - N2 : Integer := N; - begin - I := 2; - while I * I <= N2 loop - if N2 mod I = 0 then - while N2 mod I = 0 loop - N2 := N2 / I; - end loop; - Tot := Tot - Tot / I; - end if; + function Totient (N : in Integer) return Integer is + Tot : Integer := N; + I : Integer; + N2 : Integer := N; + begin + I := 2; + while I * I <= N2 loop + if N2 mod I = 0 then + while N2 mod I = 0 loop + N2 := N2 / I; + end loop; + Tot := Tot - Tot / I; + end if; - if I = 2 then - I := 1; - end if; - I := I + 2; - end loop; + if I = 2 then + I := 1; + end if; + I := I + 2; + end loop; - if N2 > 1 then - Tot := Tot - Tot / N2; - end if; + if N2 > 1 then + Tot := Tot - Tot / N2; + end if; - return Tot; - end Totient; + return Tot; + end Totient; - Count : Integer := 0; - Tot : Integer; - Placeholder : String := " n Phi Is_Prime"; - Image_N : String renames Placeholder ( 1 .. 3); - Image_Phi : String renames Placeholder ( 6 .. 8); - Image_Prime : String renames Placeholder (11 .. 17); - use Ada.Text_IO; - use Ada.Integer_Text_IO; + Count : Integer := 0; + Tot : Integer; + Placeholder : String := " n Phi Is_Prime"; + Image_N : String renames Placeholder ( 1 .. 3); + Image_Phi : String renames Placeholder ( 6 .. 8); + Image_Prime : String renames Placeholder (11 .. Placeholder'Last); + use Ada.Text_IO; + use Ada.Integer_Text_IO; + + Last : constant := 25; begin - Put_Line (Placeholder); + Put_Line (Placeholder); - for N in 1 .. 25 loop - Tot := Totient (N); + for N in 1 .. Last loop + Tot := Totient (N); - if N - 1 = Tot then - Count := Count + 1; - end if; - Put (Image_N, N); - Put (Image_Phi, Tot); - Image_Prime := (if N - 1 = Tot then " True" else " False"); - Put_Line (Placeholder); - end loop; - New_Line; + if N - 1 = Tot then + Count := Count + 1; + end if; + Put (Image_N, N); + Put (Image_Phi, Tot); + Image_Prime := Ada.Strings.Fixed.Tail + (Source => (if N - 1 = Tot then True'Image else False'Image), + Count => Image_Prime'Length); + Put_Line (Placeholder); + end loop; + New_Line; - Put_Line ("Number of primes up to " & Integer'(25)'Image &" =" & Count'Image); + Put_Line ("Number of primes up to " & Last'Image &" =" & Count'Image); - for N in 26 .. 100_000 loop - Tot := Totient (N); + for N in Last + 1 .. 100_000 loop + Tot := Totient (N); - if Tot = N - 1 then - Count := Count + 1; - end if; + if Tot = N - 1 then + Count := Count + 1; + end if; - if N = 100 or N = 1_000 or N mod 10_000 = 0 then - Put_Line ("Number of primes up to " & N'Image & " =" & Count'Image); - end if; - end loop; + if N = 100 or N = 1_000 or N mod 10_000 = 0 then + Put_Line ("Number of primes up to " & N'Image & " =" & Count'Image); + end if; + end loop; end Totient; diff --git a/Task/Totient-function/Julia/totient-function.julia b/Task/Totient-function/Julia/totient-function.jl similarity index 100% rename from Task/Totient-function/Julia/totient-function.julia rename to Task/Totient-function/Julia/totient-function.jl diff --git a/Task/Totient-function/Kotlin/totient-function.kotlin b/Task/Totient-function/Kotlin/totient-function.kts similarity index 100% rename from Task/Totient-function/Kotlin/totient-function.kotlin rename to Task/Totient-function/Kotlin/totient-function.kts diff --git a/Task/Totient-function/Phix/totient-function-1.phix b/Task/Totient-function/Phix/totient-function-1.phix new file mode 100644 index 0000000000..6f0a76a595 --- /dev/null +++ b/Task/Totient-function/Phix/totient-function-1.phix @@ -0,0 +1,37 @@ +with javascript_semantics +atom t0 = time() +function totient(integer n) + integer tot = n, i = 2 + while i*i<=n do + if mod(n,i)=0 then + while true do + n /= i + if mod(n,i)!=0 then exit end if + end while + tot -= tot/i + end if + i += iff(i=2?1:2) + end while + if n>1 then + tot -= tot/n + end if + return tot +end function + +printf(1," n phi prime\n") +printf(1," --------------\n") +for n=1 to 25 do + integer tot = totient(n) + bool prime = (n-1=tot) + printf(1,"%2d %2d %t\n",{n,tot,prime}) +end for +printf(1,"\n") +integer count = 0 +for n=1 to 1e6 do +-- count += (totient(n)=n-1) + count += (phi(n)=n-1) + if find(n,{25,1e2,1e3,1e4,1e5,1e6,1e7}) then + printf(1,"Number of primes up to %d = %d\n",{n,count}) + end if +end for +?elapsed(time()-t0) diff --git a/Task/Totient-function/Phix/totient-function-2.phix b/Task/Totient-function/Phix/totient-function-2.phix new file mode 100644 index 0000000000..5a1af0025d --- /dev/null +++ b/Task/Totient-function/Phix/totient-function-2.phix @@ -0,0 +1,38 @@ +with javascript_semantics +atom t0 = time() +constant maxphi = 1e7 +sequence s_phi +procedure computePhi() + s_phi = tagset(maxphi) + for i=2 to maxphi do + if s_phi[i]=i then + for j=i to maxphi by i do + s_phi[j] -= s_phi[j] / i; + end for + end if + end for +end procedure + +function countPrimes(int lo, hi) + int count = 0; + for i=lo to hi do + if s_phi[i] == i-1 then + count += 1 + end if + end for + return count; +end function + +computePhi() +printf(1," n phi prime\n") +printf(1," --------------\n") +for n=1 to 25 do + integer tot = s_phi[n] + bool prime = (n-1=tot) + printf(1,"%2d %2d %t\n",{n,tot,prime}) +end for +printf(1,"\n") +for n in {25,1e2,1e3,1e4,1e5,1e6,1e7} do + printf(1,"Number of primes up to %d = %d\n",{n,countPrimes(1,n)}) +end for +?elapsed(time()-t0) diff --git a/Task/Totient-function/Phix/totient-function.phix b/Task/Totient-function/Phix/totient-function.phix deleted file mode 100644 index 15df95ea82..0000000000 --- a/Task/Totient-function/Phix/totient-function.phix +++ /dev/null @@ -1,37 +0,0 @@ -(phixonline)--> - function totient(integer n) - integer tot = n, i = 2 - while i*i<=n do - if mod(n,i)=0 then - while true do - n /= i - if mod(n,i)!=0 then exit end if - end while - tot -= tot/i - end if - i += iff(i=2?1:2) - end while - if n>1 then - tot -= tot/n - end if - return tot - end function - - printf(1," n phi prime\n") - printf(1," --------------\n") - integer count = 0 - for n=1 to 25 do - integer tot = totient(n), - prime = (n-1=tot) - count += prime - string isp = iff(prime?"true":"false") - printf(1,"%2d %2d %s\n",{n,tot,isp}) - end for - printf(1,"\nNumber of primes up to 25 = %d\n",count) - for n=26 to 100000 do - count += (totient(n)=n-1) - if find(n,{100,1000,10000,100000}) then - printf(1,"Number of primes up to %-6d = %d\n",{n,count}) - end if - end for - - without js -- (peek/poke, call_back) - constant Here_am_I = "Here am I" - function Query(atom pData, pLength) - integer len = peekNS(pLength,machine_word(),0) - if poke_string(pData,len,Here_am_I) then - return 0 - end if - pokeN(pLength,length(Here_am_I)+1,machine_word()) - return 1 - end function - constant Query_cb = call_back(Query) - 1] + [32] AD S94#@ [acc := h{i} - (current maximum)] + G39@ [skip if h{i} < max] + A94#@ [restore acc after test] + T94#@ [update value of maximum] + A32@ T93@ [update A order for maximum] + [39] T4F [clear acc] + A32@ S65@ [have we just done h{n-1}?] + G28@ [loop back if not] +[Fill troughs from the left. Here with acc = 0.] + [43] AD [(planted) read h{0}] + T94#@ [initialize level to h{0}] + A49@ [acc := A order for h{1}] + S93@ [subtract A order for maximum] + E64@ [skip if maximum is at h{0} or h{1}] + [Start of loop] + [48] T4F [clear acc] + [49] AD [read h{i}; initially i = 1] + S94#@ [subtract current level] + G55@ [skip if h{i} < level] + A94#@ [restore acc after test] + T94#@ [update level] + E59@ [join common code] + [55] T4D [temp store h{i} - h_max, which is < 0] + AD [acc := result so far] + S4D [add h_max - h{i} to result] + TD [update result] + [59] A49@ A92@ U49@ [make A order for h{i+1}] + S93@ [have we reached the highest tower yet?] + G48@ [if not, loop back] +[Fill troughs from the right. + Similar to filling from the left, so given in condensed form to save space.] + [64] T4F + [65] AF T94#@ A93@ S71@ E87@ + [70] T4F + [71] AF S94#@ G77@ A94#@ T94#@ E81@ + [77] T4D AD S4D TD + [81] A71@ S92@ T71@ A93@ S71@ G70@ +[Exit from suubroutine] + [87] T4F [clear acc on exit, as usual] + [88] ZF [(planted) jump back to caller] +[Constants] + [89] U3F + [90] U1F [subtract to convert E order to A order] + [91] AD + [92] P2F [2 in address field] +[Variables: Swap if necessary to get 35-bit variable at even address] + [93] AF [order to read h_max] + [94] PF PF [current maximum height] +[-----------------------------------------------------------------------] +[Main routine: must be at even address] + E25K TM GK + [0] PF PF [store for 35-bit height] + [2] PF [data count] + [3] P2F [to change address by 2] + [4] #F [figure shift] + [5] K2048F [letter shift] + [6] DF[7] IF[8] YF + [9] NF [comma (in figures mode)] + [10] @F [carriage return] + [11] &F [line feed] + [12] !F [space] + [13] K4096F [teleprinter null] +[Entry] + [14] O4@ [set figures] +[Loop over datasets] + [15] A15@ GH [call library subroutine R4, sets 0D := data count N] + SD E63@ [exit if N = 0] + T4F [clear acc] + A23@ T40@ [initialize T order to store data] + AD [load data count, 35-bit but with high half = 0] + [23] T#& [store at start of data] + [24] S& [acc := 17-bit negative count of data] + [25] LD [shift to address field *** or use k1 to inc ?? ***] + G28@ [don't print comma before first height] +[Loop over heights in current dataset] + [27] O9@ [print comma] + [28] T2@ [update negative loop counter] + A40@ A3@ T40@ [inc address for next 35-bit height] + A32@ GH [read next height to 0D (clears acc)] + AD T#@ [acc := height, save locally] + A36@ GN !1F [print height, min width = 1] + A#@ [retrieve height] + [40] TD [(planted) store height in array] + A2@ A2F [inc negative loop counter] + G27@ [if not yet 0, loop back] + A44@ GL P& [call subroutine returns amount of water in 0D] + [Print ' YIELDS ' (requires temporary change to letters shift)] + O5@ O12@ O8@ O7@ O62@ + O25@ O6@ O24@ O12@ O4@ + A57@ GN !1F [print result, min width = 1; leaves acc = 0] + O10@ O11@ [print CR, LF] + [62] E15@ [loop back for next data set (also letter E)] +[Jump to here if data count = 0, means end of data] + [63] O13@ [print null to flush teleprinter buffer] + ZF [stop the machine] +[------------------------------------------------------------------------------- + Library subroutine R4. + Input of one signed integer, returned in 0D.] + E25K TH + GK A3F T21@ T4D H6@ E11@ P5D JF T6F VD L4F A4D TD I4F A4F S5@ G7@ S5@ G20@ SD TD T6F EF +[------------------------------------------------------------------------------- + Modification of library subroutine P7; prints integer N in range 0 <= N < 10^10. + Prints 0 correctly, and allows caller to specify a minimum width. + Input : 0D = integer (not preserved) + 17-bit print control word follows subroutine call, + e.g. !5F means minimum width 5, pad on left with space. + 49 locations; even address; workspace: 0F, 1F, 4D, 6F, 7F] + E25K TN + GK A48@ U4@ A27@ T35@ AF U4@ L256F S45@ T7F H46#@ ND YF LD T4D S45@ T1F H21@ S21@ A45@ G21@ U4@ TF V4D A1F G36@ S1F LD U1F O1F F1F S1F L4F T4D AF G18@ ZF S1F L8F T4D AF A7F G43@ O4@ T6F E33@ T46#Z PF T45Z P1024F P610D @524D P2F +[--------------------------------------------------------------------------------] +[M parameter (main routine) again] + E25K TM GK + E14Z [define entry point] + PF [acc = 0 on entry] +[--------------------------------------------------------------------------------] +[Counts and data values to be read by library subroutine R4. + Note sign comes _after_ value.] +5+ 1+5+3+7+2+ +10+ 5+3+7+2+6+4+5+9+1+2+ +16+ 2+6+3+5+2+8+1+4+2+2+5+3+5+7+4+1+ +4+ 5+5+5+5+ +4+ 5+6+7+8+ +4+ 8+7+7+6+ +5+ 6+7+10+7+6+ +0+ diff --git a/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy b/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy index f46f7dcf15..71937aa4de 100644 --- a/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy +++ b/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy @@ -1,4 +1,4 @@ -proc water h[] . . +func water h[] . n = len h[] len left[] n len right[] n @@ -12,14 +12,14 @@ proc water h[] . . right[i] = max . for i = 1 to n - sum += (lower left[i] right[i]) - h[i] + sum += lower left[i] right[i] - h[i] . - print sum + return sum . repeat s$ = input until s$ = "" - water number strsplit s$ " " + print water number strsplit s$ " " . # input_data diff --git a/Task/Water-collected-between-towers/Julia/water-collected-between-towers.julia b/Task/Water-collected-between-towers/Julia/water-collected-between-towers.jl similarity index 100% rename from Task/Water-collected-between-towers/Julia/water-collected-between-towers.julia rename to Task/Water-collected-between-towers/Julia/water-collected-between-towers.jl diff --git a/Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kotlin b/Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kts similarity index 100% rename from Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kotlin rename to Task/Water-collected-between-towers/Kotlin/water-collected-between-towers.kts diff --git a/Task/Water-collected-between-towers/Rust/water-collected-between-towers.rust b/Task/Water-collected-between-towers/Rust/water-collected-between-towers.rs similarity index 100% rename from Task/Water-collected-between-towers/Rust/water-collected-between-towers.rust rename to Task/Water-collected-between-towers/Rust/water-collected-between-towers.rs diff --git a/Task/Water-collected-between-towers/Scheme/water-collected-between-towers.ss b/Task/Water-collected-between-towers/Scheme/water-collected-between-towers.scm similarity index 100% rename from Task/Water-collected-between-towers/Scheme/water-collected-between-towers.ss rename to Task/Water-collected-between-towers/Scheme/water-collected-between-towers.scm diff --git a/Task/Water-collected-between-towers/Tailspin/water-collected-between-towers.tailspin b/Task/Water-collected-between-towers/Tailspin/water-collected-between-towers-1.tailspin similarity index 100% rename from Task/Water-collected-between-towers/Tailspin/water-collected-between-towers.tailspin rename to Task/Water-collected-between-towers/Tailspin/water-collected-between-towers-1.tailspin diff --git a/Task/Water-collected-between-towers/Tailspin/water-collected-between-towers-2.tailspin b/Task/Water-collected-between-towers/Tailspin/water-collected-between-towers-2.tailspin new file mode 100644 index 0000000000..0702da9743 --- /dev/null +++ b/Task/Water-collected-between-towers/Tailspin/water-collected-between-towers-2.tailspin @@ -0,0 +1,24 @@ +histogramWater templates + $ -> templates + @ set 0"1"; + [$... -> ($)"1"-> { leftMax: $ -> #, value: ($)"1" } ] ! + when <|$@..> do @ set $; $ ! + otherwise $@ ! + end -> templates + @ set { rightMax: 0"1", sum: 0"1" }; + $(..:-1)... -> !# + $@(sum:) ! + when <|{ value: <|$@(rightMax:)..> }> do @(rightMax:) set $(value:); + when <|{ value: <|$(leftMax:)..> }> do VOID + when <|{ leftMax: <|..$@(rightMax:)>}> do @(sum:) set $@(sum:) + $(leftMax:) - $(value:); + otherwise @(sum:) set $@(sum:) + $@(rightMax:) - $(value:); + end ! +end histogramWater + +[[1, 5, 3, 7, 2], + [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], + [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], + [5, 5, 5, 5], + [5, 6, 7, 8], + [8, 7, 7, 6], + [6, 7, 10, 7, 6]]... -> '$ -> histogramWater; water in $;$#10;' ! diff --git a/Task/Web-scraping/Delphi/web-scraping-1.delphi b/Task/Web-scraping/Delphi/web-scraping-1.pas similarity index 100% rename from Task/Web-scraping/Delphi/web-scraping-1.delphi rename to Task/Web-scraping/Delphi/web-scraping-1.pas diff --git a/Task/Web-scraping/Delphi/web-scraping-2.delphi b/Task/Web-scraping/Delphi/web-scraping-2.pas similarity index 100% rename from Task/Web-scraping/Delphi/web-scraping-2.delphi rename to Task/Web-scraping/Delphi/web-scraping-2.pas diff --git a/Task/Web-scraping/Julia/web-scraping-1.julia b/Task/Web-scraping/Julia/web-scraping-1.jl similarity index 100% rename from Task/Web-scraping/Julia/web-scraping-1.julia rename to Task/Web-scraping/Julia/web-scraping-1.jl diff --git a/Task/Web-scraping/Julia/web-scraping-2.julia b/Task/Web-scraping/Julia/web-scraping-2.jl similarity index 100% rename from Task/Web-scraping/Julia/web-scraping-2.julia rename to Task/Web-scraping/Julia/web-scraping-2.jl diff --git a/Task/Web-scraping/Kotlin/web-scraping.kotlin b/Task/Web-scraping/Kotlin/web-scraping.kts similarity index 100% rename from Task/Web-scraping/Kotlin/web-scraping.kotlin rename to Task/Web-scraping/Kotlin/web-scraping.kts diff --git a/Task/Web-scraping/OCaml/web-scraping.ocaml b/Task/Web-scraping/OCaml/web-scraping.ml similarity index 100% rename from Task/Web-scraping/OCaml/web-scraping.ocaml rename to Task/Web-scraping/OCaml/web-scraping.ml diff --git a/Task/Web-scraping/Rust/web-scraping.rust b/Task/Web-scraping/Rust/web-scraping.rs similarity index 100% rename from Task/Web-scraping/Rust/web-scraping.rust rename to Task/Web-scraping/Rust/web-scraping.rs diff --git a/Task/Web-scraping/Scheme/web-scraping.ss b/Task/Web-scraping/Scheme/web-scraping.scm similarity index 100% rename from Task/Web-scraping/Scheme/web-scraping.ss rename to Task/Web-scraping/Scheme/web-scraping.scm diff --git a/Task/Weird-numbers/Crystal/weird-numbers.crystal b/Task/Weird-numbers/Crystal/weird-numbers.cr similarity index 100% rename from Task/Weird-numbers/Crystal/weird-numbers.crystal rename to Task/Weird-numbers/Crystal/weird-numbers.cr diff --git a/Task/Weird-numbers/EasyLang/weird-numbers.easy b/Task/Weird-numbers/EasyLang/weird-numbers.easy new file mode 100644 index 0000000000..e23175307b --- /dev/null +++ b/Task/Weird-numbers/EasyLang/weird-numbers.easy @@ -0,0 +1,68 @@ +func[] divisors n . + divs[] &= 1 + for i = 2 to sqrt n + if n mod i = 0 + j = n / i + divs[] &= i + if i <> j + divs2[] &= j + . + . + . + for i = len divs2[] downto 1 + divs[] &= divs2[i] + . + return divs[] +. +func sum divs[] . + for e in divs[] + s += e + . + return s +. +func semiperf n divs[] . + if len divs[] = 0 + return 0 + . + h = divs[$] + len divs[] -1 + if n = h + return 1 + . + if n > h + if semiperf (n - h) divs[] = 1 + return 1 + . + . + return semiperf n divs[] +. +proc sieve limit . wierd[] . + len wierd[] limit + for j = 1 to limit + if j mod 6 <> 0 + wierd[j] = 1 + . + . + for i = 2 step 2 to limit + if wierd[i] = 1 + divs[] = divisors i + if i > sum divs[] + wierd[i] = 0 + elif semiperf i divs[] = 1 + for j = i step i to limit + wierd[j] = 0 + . + . + . + . +. +sieve 20000 wierd[] +i = 2 +repeat + if wierd[i] = 1 + cnt += 1 + write i & " " + . + until cnt = 25 + i += 2 +. diff --git a/Task/Weird-numbers/Julia/weird-numbers.julia b/Task/Weird-numbers/Julia/weird-numbers.jl similarity index 100% rename from Task/Weird-numbers/Julia/weird-numbers.julia rename to Task/Weird-numbers/Julia/weird-numbers.jl diff --git a/Task/Weird-numbers/Kotlin/weird-numbers.kotlin b/Task/Weird-numbers/Kotlin/weird-numbers.kts similarity index 100% rename from Task/Weird-numbers/Kotlin/weird-numbers.kotlin rename to Task/Weird-numbers/Kotlin/weird-numbers.kts diff --git a/Task/Weird-numbers/YAMLScript/weird-numbers.ys b/Task/Weird-numbers/YAMLScript/weird-numbers.ys new file mode 100644 index 0000000000..2bf68a1df2 --- /dev/null +++ b/Task/Weird-numbers/YAMLScript/weird-numbers.ys @@ -0,0 +1,48 @@ +!yamlscript/v0 + +defn main(max=16500): + weird =: sieve(max) + numbers =: + filter \(nth weird _): range(2 max 2) + say: | + The first $(numbers.#) weird numbers: + $(numbers:joins) + +defn sieve(limit): + weirds =: into([] repeat(limit true)) + loop i 2, weirds weirds: + if i < limit: + recur (i + 2): + or _ weirds: + when weirds.$i: + divs =: divisors(i) + if abundant(i divs): + when semiperfect(i divs): + loop j i, weirds weirds: + if j < limit: + recur (j + i): + weirds.assoc(j false) + else: weirds + weirds: .assoc(i false) + else: weirds + +defn divisors(number): + divisors =: + mapcat _ range(1 sqrt(number)): + fn(n): + when 0 == (number % n): + V: n (number / n) + divisors: .distinct().sort(gt _):rest + +defn abundant(n divs): + sum(divs) > n + +defn semiperfect(n divs): + when divs.# > 0: + div *divs =: divs + if n < div: + semiperfect: n divs + or: + n ==: div + semiperfect: (n - div) divs + semiperfect: n divs diff --git a/Task/Wieferich-primes/Julia/wieferich-primes.julia b/Task/Wieferich-primes/Julia/wieferich-primes.jl similarity index 100% rename from Task/Wieferich-primes/Julia/wieferich-primes.julia rename to Task/Wieferich-primes/Julia/wieferich-primes.jl diff --git a/Task/Wieferich-primes/REXX/wieferich-primes.rexx b/Task/Wieferich-primes/REXX/wieferich-primes.rexx index e7689645db..262532c37f 100644 --- a/Task/Wieferich-primes/REXX/wieferich-primes.rexx +++ b/Task/Wieferich-primes/REXX/wieferich-primes.rexx @@ -1,34 +1,61 @@ /*REXX program finds and displays Wieferich primes which are under a specified limit N*/ -parse arg n . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 5000 /*Not specified? Then use the default.*/ -numeric digits 3000 /*bump # of dec. digs for calculation. */ -numeric digits max(9, length(2**n) ) /*calculate # of decimal digits needed.*/ +Parse arg n . /*obtain optional argument from the CL.*/ +If n=='' | n=="," Then n=5000 /*Not specified? Then use the default.*/ +Numeric Digits 5000 +Numeric Digits max(9,length(2**n)) /*calculate nr of decimal digits needed*/ call genP /*build array of semaphores for primes.*/ - title= ' Wieferich primes that are < ' commas(n) /*title for the output.*/ -w= length(title) + 2 /*width of field for the primes listed.*/ -say ' index │'center(title, w) /*display the title for the output. */ -say '───────┼'center("" , w, '─') /* " a sep " " " */ -found= 0 /*initialize number of Wieferich primes*/ - do j=1 to #; p= @.j /*search for Wieferich primes in range.*/ - if (2**(p-1)-1)//p**2\==0 then iterate /*P**2 not evenly divide 2**(P-1) - 1?*/ /* ◄■■■■■■■ the filter.*/ - found= found + 1 /*bump the counter of Wieferich primes.*/ - say center(found, 7)'│' center(commas(p), w) /*display the Wieferich prime.*/ - end /*j*/ +/**************** +Do i=1 To nn + Say i pr.i sq.i + End +****************/ +title=' Wieferich primes that are < 'commas(n) /*title for the output. */ +w=length(title)+2 /*width of field for the primes listed.*/ +Say ' index |'center(title,w) /*display the title for the output. */ +Say '-------+'center('',w,'-') /* " a sep " " " */ +found=0 /*initialize number of Wieferich primes*/ +Do j=1 To nn + p=pr.j /*search for Wieferich primes in range.*/ + If (2**(p-1)-1)//p**2=0 Then Do /* P**2 evenly divides 2**(P-1)-1 */ + found=found+1 /*bump the counter of Wieferich primes.*/ + Say center(found,7)'|' center(commas(p),w) /*display the Wieferich prime.*/ + End + End -say '───────┴'center("" , w, '─'); say /*display a foot sep for the output. */ -say 'Found ' commas(found) title /* " " summary " " " */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes (index-1). */ - !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* " " " " (semaphores).*/ - #= 5; sq.#= @.# ** 2 /*number of primes so far; prime². */ - do j=@.#+2 by 2 to n-1; parse var j '' -1 _ /*get right decimal digit of J.*/ - if _==5 then iterate /*J ÷ by 5? Yes, skip.*/ - if j//3==0 then iterate; if j//7==0 then iterate /*" " " 3? J ÷ by 7? */ - do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ - if j//@.k==0 then iterate j /*Is J ÷ a P? Then not prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # Ps; assign next P; P sqare; P.*/ - end /*j*/; return +Say '--------'center("" , w, '-') /*display a foot sep for the output. */ +Say 'Found ' commas(found) title /* " " summary " " " */ +Exit 0 /*stick a fork in it, we're all done. */ +/*--------------------------------------------------------------------------------------*/ +commas: Parse arg ?; Do jc=length(?)-3 To 1 by -3; ?=insert(',', ?, jc); End; Return ? +/*--------------------------------------------------------------------------------------*/ +genP: +/***************************************************************************************** +* Compute all primes less than n+1 +* Output: nn - the number of primes found +* pr.i The i-th prime +* sq.i the square of pr.i +*****************************************************************************************/ + primes='2 3 5 7 11' + nn=0 + Do while primes>'' /* for efficiency note a few primes */ + Parse Var primes w primes + Call store w + End + Do j=pr.nn+2 by 2 To n /* look at odd numbers up to n */ + If right(j,1)<>5 Then /* number does not end in 5 */ + If j//3<>0 Then /* " is not a multiple of 3 */ + If j//7<>0 Then Do /* " is not a multiple of 7 */ + Do k=5 while sq.k<=j /* check all primes up to sqrt(j) */ + If j//pr.k==0 Then iterate j /* if this is a divisor: j is not prime*/ + End + Call store j /* j is a prime number. store it */ + End + End + Return + +store: + Parse Arg w + nn=nn+1 + pr.nn=w + sq.nn=w**2 + Return diff --git a/Task/Wieferich-primes/Rust/wieferich-primes.rust b/Task/Wieferich-primes/Rust/wieferich-primes.rs similarity index 100% rename from Task/Wieferich-primes/Rust/wieferich-primes.rust rename to Task/Wieferich-primes/Rust/wieferich-primes.rs diff --git a/Task/Wilson-primes-of-order-n/Julia/wilson-primes-of-order-n.julia b/Task/Wilson-primes-of-order-n/Julia/wilson-primes-of-order-n.jl similarity index 100% rename from Task/Wilson-primes-of-order-n/Julia/wilson-primes-of-order-n.julia rename to Task/Wilson-primes-of-order-n/Julia/wilson-primes-of-order-n.jl diff --git a/Task/Wilson-primes-of-order-n/Rust/wilson-primes-of-order-n.rust b/Task/Wilson-primes-of-order-n/Rust/wilson-primes-of-order-n.rs similarity index 100% rename from Task/Wilson-primes-of-order-n/Rust/wilson-primes-of-order-n.rust rename to Task/Wilson-primes-of-order-n/Rust/wilson-primes-of-order-n.rs diff --git a/Task/Window-creation-X11/Julia/window-creation-x11.julia b/Task/Window-creation-X11/Julia/window-creation-x11.jl similarity index 100% rename from Task/Window-creation-X11/Julia/window-creation-x11.julia rename to Task/Window-creation-X11/Julia/window-creation-x11.jl diff --git a/Task/Window-creation-X11/Kotlin/window-creation-x11.kotlin b/Task/Window-creation-X11/Kotlin/window-creation-x11.kts similarity index 100% rename from Task/Window-creation-X11/Kotlin/window-creation-x11.kotlin rename to Task/Window-creation-X11/Kotlin/window-creation-x11.kts diff --git a/Task/Window-creation-X11/OCaml/window-creation-x11.ocaml b/Task/Window-creation-X11/OCaml/window-creation-x11.ml similarity index 100% rename from Task/Window-creation-X11/OCaml/window-creation-x11.ocaml rename to Task/Window-creation-X11/OCaml/window-creation-x11.ml diff --git a/Task/Window-creation/Delphi/window-creation-1.delphi b/Task/Window-creation/Delphi/window-creation-1.pas similarity index 100% rename from Task/Window-creation/Delphi/window-creation-1.delphi rename to Task/Window-creation/Delphi/window-creation-1.pas diff --git a/Task/Window-creation/Delphi/window-creation-2.delphi b/Task/Window-creation/Delphi/window-creation-2.pas similarity index 100% rename from Task/Window-creation/Delphi/window-creation-2.delphi rename to Task/Window-creation/Delphi/window-creation-2.pas diff --git a/Task/Window-creation/Euphoria/window-creation-1.euphoria b/Task/Window-creation/Euphoria/window-creation-1.ex similarity index 100% rename from Task/Window-creation/Euphoria/window-creation-1.euphoria rename to Task/Window-creation/Euphoria/window-creation-1.ex diff --git a/Task/Window-creation/Euphoria/window-creation-2.euphoria b/Task/Window-creation/Euphoria/window-creation-2.ex similarity index 100% rename from Task/Window-creation/Euphoria/window-creation-2.euphoria rename to Task/Window-creation/Euphoria/window-creation-2.ex diff --git a/Task/Window-creation/Euphoria/window-creation-3.euphoria b/Task/Window-creation/Euphoria/window-creation-3.ex similarity index 100% rename from Task/Window-creation/Euphoria/window-creation-3.euphoria rename to Task/Window-creation/Euphoria/window-creation-3.ex diff --git a/Task/Window-creation/Euphoria/window-creation-4.euphoria b/Task/Window-creation/Euphoria/window-creation-4.ex similarity index 100% rename from Task/Window-creation/Euphoria/window-creation-4.euphoria rename to Task/Window-creation/Euphoria/window-creation-4.ex diff --git a/Task/Window-creation/Euphoria/window-creation-5.euphoria b/Task/Window-creation/Euphoria/window-creation-5.ex similarity index 100% rename from Task/Window-creation/Euphoria/window-creation-5.euphoria rename to Task/Window-creation/Euphoria/window-creation-5.ex diff --git a/Task/Window-creation/Julia/window-creation.julia b/Task/Window-creation/Julia/window-creation.jl similarity index 100% rename from Task/Window-creation/Julia/window-creation.julia rename to Task/Window-creation/Julia/window-creation.jl diff --git a/Task/Window-creation/Kotlin/window-creation.kotlin b/Task/Window-creation/Kotlin/window-creation.kts similarity index 100% rename from Task/Window-creation/Kotlin/window-creation.kotlin rename to Task/Window-creation/Kotlin/window-creation.kts diff --git a/Task/Window-creation/OCaml/window-creation-1.ocaml b/Task/Window-creation/OCaml/window-creation-1.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-1.ocaml rename to Task/Window-creation/OCaml/window-creation-1.ml diff --git a/Task/Window-creation/OCaml/window-creation-2.ocaml b/Task/Window-creation/OCaml/window-creation-2.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-2.ocaml rename to Task/Window-creation/OCaml/window-creation-2.ml diff --git a/Task/Window-creation/OCaml/window-creation-3.ocaml b/Task/Window-creation/OCaml/window-creation-3.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-3.ocaml rename to Task/Window-creation/OCaml/window-creation-3.ml diff --git a/Task/Window-creation/OCaml/window-creation-4.ocaml b/Task/Window-creation/OCaml/window-creation-4.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-4.ocaml rename to Task/Window-creation/OCaml/window-creation-4.ml diff --git a/Task/Window-creation/OCaml/window-creation-5.ocaml b/Task/Window-creation/OCaml/window-creation-5.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-5.ocaml rename to Task/Window-creation/OCaml/window-creation-5.ml diff --git a/Task/Window-creation/OCaml/window-creation-6.ocaml b/Task/Window-creation/OCaml/window-creation-6.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-6.ocaml rename to Task/Window-creation/OCaml/window-creation-6.ml diff --git a/Task/Window-creation/OCaml/window-creation-7.ocaml b/Task/Window-creation/OCaml/window-creation-7.ml similarity index 100% rename from Task/Window-creation/OCaml/window-creation-7.ocaml rename to Task/Window-creation/OCaml/window-creation-7.ml diff --git a/Task/Window-creation/Rust/window-creation.rust b/Task/Window-creation/Rust/window-creation.rs similarity index 100% rename from Task/Window-creation/Rust/window-creation.rust rename to Task/Window-creation/Rust/window-creation.rs diff --git a/Task/Window-creation/Scheme/window-creation.ss b/Task/Window-creation/Scheme/window-creation.scm similarity index 100% rename from Task/Window-creation/Scheme/window-creation.ss rename to Task/Window-creation/Scheme/window-creation.scm diff --git a/Task/Window-creation/XPL0/window-creation.xpl0 b/Task/Window-creation/XPL0/window-creation.xpl0 new file mode 100644 index 0000000000..00479559c2 --- /dev/null +++ b/Task/Window-creation/XPL0/window-creation.xpl0 @@ -0,0 +1,43 @@ +\12345678901234567890123456789012345 +\Window creation............... X . + +def X0=20, Y0=10; \upper-left corner of window's position (chars) +int Mouse, Button, C; + +func GetButton; \Return soft button number at mouse pointer +int X, Y; +[Mouse:= GetMouse; +X:= Mouse(0)/8 - X0; \convert pixels to char cells +Y:= Mouse(1)/16 - Y0; +if X>=32 & X<=34 & Y=0 then return 0; \exit [X] +return -1; \mouse not on any soft button +]; + +[SetVid($12); \640x480 graphics +TrapC(true); \disable Ctrl+C +Attrib($70); \black on gray +SetWind(0+X0, 0+Y0, 35+X0, 8+Y0, 0, \fill\true); +Cursor(33+X0, 0+Y0); Text(6, "X"); + +Attrib($1F); \bright white on blue, for title +Cursor(0+X0, 0+Y0); Text(6, " Window creation "); + +ShowMouse(true); +loop [MoveMouse; \make pointer track mouse movements + Mouse:= GetMouse; + if Mouse(2) then \a left or right mouse button is down + [Button:= GetButton; \get soft button at mouse pointer + while Mouse(2) do \wait for mouse button's release + [MoveMouse; + Mouse:= GetMouse; + ]; + if Button = GetButton then \if down Button = release button + if Button = 0 then quit; + ]; + if KeyHit then + [C:= ChIn(1); \get character from non-echoed keyboard + if C = \Esc\$1B then quit; + ]; + ]; +SetVid(3); \restore normal text mode immediately +] diff --git a/Task/Window-management/FreeBASIC/window-management.basic b/Task/Window-management/FreeBASIC/window-management.basic new file mode 100644 index 0000000000..ff95d5b107 --- /dev/null +++ b/Task/Window-management/FreeBASIC/window-management.basic @@ -0,0 +1,85 @@ +#include "windows.bi" + +Function WindowProc(Byval hWnd As HWND, Byval uMsg As UINT, Byval wParam As WPARAM, Byval lParam As LPARAM) As LRESULT + Select Case uMsg + Case WM_DESTROY + PostQuitMessage(0) + Return 0 + Case Else + Return DefWindowProc(hWnd, uMsg, wParam, lParam) + End Select +End Function + +Function CreateSimpleWindow(titulo As String, ancho As Integer, alto As Integer) As HWND + Dim As HWND hWnd + Dim As WNDCLASS wc + + wc.style = CS_HREDRAW Or CS_VREDRAW + wc.lpfnWndProc = @WindowProc + wc.cbClsExtra = 0 + wc.cbWndExtra = 0 + wc.hInstance = GetModuleHandle(NULL) + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION) + wc.hCursor = LoadCursor(NULL, IDC_ARROW) + wc.hbrBackground = GetStockObject(WHITE_BRUSH) + wc.lpszMenuName = NULL + wc.lpszClassName = @"SimpleWindowClass" + + RegisterClass(@wc) + + hWnd = CreateWindowEx(0, @"SimpleWindowClass", titulo, WS_OVERLAPPEDWINDOW, _ + CW_USEDEFAULT, CW_USEDEFAULT, ancho, alto, NULL, NULL, _ + GetModuleHandle(NULL), NULL) + + ShowWindow(hWnd, SW_SHOW) + UpdateWindow(hWnd) + + Return hWnd +End Function + +Dim As HWND hWnd = CreateSimpleWindow("Rosetta code", 400, 300) + +If hWnd = 0 Then + Print "Error: Could not create window.." +Else + Print "Let's go... " + + Print "Show window" + ShowWindow(hWnd, SW_SHOW) + Sleep 1000 + + Print "Hide window" + ShowWindow(hWnd, SW_HIDE) + Sleep 1000 + + Print "Minimize window" + ShowWindow(hWnd, SW_MINIMIZE) + Sleep 1000 + + Print "Maximize window" + ShowWindow(hWnd, SW_MAXIMIZE) + Sleep 1000 + + Print "Restore window" + ShowWindow(hWnd, SW_RESTORE) + Sleep 1000 + + Print "Move window" + MoveWindow(hWnd, 100, 100, 800, 600, True) + Sleep 1000 + + Print "Resize the window" + MoveWindow(hWnd, 100, 100, 400, 300, True) + Sleep 1000 + + Print "Close window" + PostMessage(hWnd, WM_CLOSE, 0, 0) +End If + +Dim uMsg As MSG +While GetMessage(@uMsg, NULL, NULL, NULL) + TranslateMessage(@uMsg) + DispatchMessage(@uMsg) +Wend + +Print "That's all folks!" diff --git a/Task/Window-management/Julia/window-management.julia b/Task/Window-management/Julia/window-management.jl similarity index 100% rename from Task/Window-management/Julia/window-management.julia rename to Task/Window-management/Julia/window-management.jl diff --git a/Task/Wireworld/Delphi/wireworld.delphi b/Task/Wireworld/Delphi/wireworld.pas similarity index 100% rename from Task/Wireworld/Delphi/wireworld.delphi rename to Task/Wireworld/Delphi/wireworld.pas diff --git a/Task/Wireworld/EasyLang/wireworld.easy b/Task/Wireworld/EasyLang/wireworld.easy index d40d68f310..1408594f2e 100644 --- a/Task/Wireworld/EasyLang/wireworld.easy +++ b/Task/Wireworld/EasyLang/wireworld.easy @@ -1,4 +1,4 @@ -sys topleft +sysconf topleft global m[] nc . background 777 # diff --git a/Task/Wireworld/Elixir/wireworld.elixir b/Task/Wireworld/Elixir/wireworld.ex similarity index 100% rename from Task/Wireworld/Elixir/wireworld.elixir rename to Task/Wireworld/Elixir/wireworld.ex diff --git a/Task/Wireworld/Julia/wireworld.julia b/Task/Wireworld/Julia/wireworld.jl similarity index 100% rename from Task/Wireworld/Julia/wireworld.julia rename to Task/Wireworld/Julia/wireworld.jl diff --git a/Task/Wireworld/OCaml/wireworld.ocaml b/Task/Wireworld/OCaml/wireworld.ml similarity index 100% rename from Task/Wireworld/OCaml/wireworld.ocaml rename to Task/Wireworld/OCaml/wireworld.ml diff --git a/Task/Wireworld/Rust/wireworld-1.rust b/Task/Wireworld/Rust/wireworld-1.rs similarity index 100% rename from Task/Wireworld/Rust/wireworld-1.rust rename to Task/Wireworld/Rust/wireworld-1.rs diff --git a/Task/Wireworld/Rust/wireworld-2.rust b/Task/Wireworld/Rust/wireworld-2.rs similarity index 100% rename from Task/Wireworld/Rust/wireworld-2.rust rename to Task/Wireworld/Rust/wireworld-2.rs diff --git a/Task/Word-frequency/Crystal/word-frequency.crystal b/Task/Word-frequency/Crystal/word-frequency.cr similarity index 100% rename from Task/Word-frequency/Crystal/word-frequency.crystal rename to Task/Word-frequency/Crystal/word-frequency.cr diff --git a/Task/Word-frequency/Delphi/word-frequency.delphi b/Task/Word-frequency/Delphi/word-frequency.pas similarity index 100% rename from Task/Word-frequency/Delphi/word-frequency.delphi rename to Task/Word-frequency/Delphi/word-frequency.pas diff --git a/Task/Word-frequency/Julia/word-frequency.julia b/Task/Word-frequency/Julia/word-frequency.jl similarity index 100% rename from Task/Word-frequency/Julia/word-frequency.julia rename to Task/Word-frequency/Julia/word-frequency.jl diff --git a/Task/Word-frequency/Kotlin/word-frequency.kotlin b/Task/Word-frequency/Kotlin/word-frequency.kts similarity index 100% rename from Task/Word-frequency/Kotlin/word-frequency.kotlin rename to Task/Word-frequency/Kotlin/word-frequency.kts diff --git a/Task/Word-frequency/OCaml/word-frequency.ocaml b/Task/Word-frequency/OCaml/word-frequency.ml similarity index 100% rename from Task/Word-frequency/OCaml/word-frequency.ocaml rename to Task/Word-frequency/OCaml/word-frequency.ml diff --git a/Task/Word-frequency/Rust/word-frequency.rust b/Task/Word-frequency/Rust/word-frequency.rs similarity index 100% rename from Task/Word-frequency/Rust/word-frequency.rust rename to Task/Word-frequency/Rust/word-frequency.rs diff --git a/Task/Word-frequency/Scheme/word-frequency.scm b/Task/Word-frequency/Scheme/word-frequency.scm new file mode 100644 index 0000000000..933477c452 --- /dev/null +++ b/Task/Word-frequency/Scheme/word-frequency.scm @@ -0,0 +1,40 @@ +(use srfi-13) ;; string functions +(use srfi-14) ;; character sets +(use file.util) + +;; Increment a value in an association list. +(define-syntax ainc! + (syntax-rules () + [(_ alist key val func default) + (let ((pair (assoc key alist))) + (if pair + (set-cdr! pair (func val (cdr pair))) + (set! alist (cons (cons key (func val default)) alist))))] + [(_ alist key val func) + (ainc! alist key val func 0)] + [(_ alist key val) + (ainc! alist key val +)] + [(_ alist key) + (ainc! alist key 1)])) + +(define *table* '()) + +(define (process-line line) + (dolist (word + (string-tokenize (string-upcase line) char-set:letter)) + (ainc! *table* word))) + +(define (foo filename) + (set! *table* '()) + (dolist (line (file->string-list filename)) + (process-line line))) + +(time (foo "Alice.txt")) +; user 3.219 [seconds] + +(define *result* (sort *table* > cdr)) + +(take *result* 10) + +(("THE" . 1818) ("AND" . 940) ("TO" . 809) ("A" . 690) ("OF" . 631) + ("IT" . 610) ("SHE" . 553) ("I" . 545) ("YOU" . 481) ("SAID" . 462)) diff --git a/Task/Word-ladder/EasyLang/word-ladder.easy b/Task/Word-ladder/EasyLang/word-ladder.easy new file mode 100644 index 0000000000..3426bb8316 --- /dev/null +++ b/Task/Word-ladder/EasyLang/word-ladder.easy @@ -0,0 +1,80 @@ +repeat + s$ = input + until s$ = "" + words$[] &= s$ +. +func hammingdist w1$ w2$ . + for i to len w1$ + if substr w1$ i 1 <> substr w2$ i 1 + cnt += 1 + if cnt = 2 + break 1 + . + . + . + return cnt +. +proc ladder a$ b$ . . + # BFS + h = len a$ + for w$ in words$[] + if len w$ = h + w$[] &= w$ + if w$ = a$ + a = len w$[] + elif w$ = b$ + b = len w$[] + . + . + . + if a = 0 or b = 0 + print "Words are not in dictionary" + return + . + n = len w$[] + len prev[] n + todo[] = [ a ] + while len todo[] > 0 + for cur in todo[] + if cur = b + break 2 + . + for i to n + if prev[i] = 0 and hammingdist w$[cur] w$[i] = 1 + todon[] &= i + prev[i] = cur + . + . + . + swap todon[] todo[] + todon[] = [ ] + . + if cur = b + while cur <> a + seq$ = " -> " & w$[cur] & seq$ + cur = prev[cur] + . + seq$ = w$[cur] & seq$ + print seq$ + else + print "No path" + . +. +ladder "boy" "man" +ladder "girl" "lady" +ladder "jane" "john" +ladder "child" "adult" +ladder "ada" "god" +ladder "rust" "hell" +# +# the content of unixdict.txt +input_data +10th +. +ada +bay +ban +boy +god +man +. diff --git a/Task/Word-ladder/Julia/word-ladder.julia b/Task/Word-ladder/Julia/word-ladder.jl similarity index 100% rename from Task/Word-ladder/Julia/word-ladder.julia rename to Task/Word-ladder/Julia/word-ladder.jl diff --git a/Task/Word-ladder/Rust/word-ladder.rs b/Task/Word-ladder/Rust/word-ladder.rs new file mode 100644 index 0000000000..9ca4f84e2b --- /dev/null +++ b/Task/Word-ladder/Rust/word-ladder.rs @@ -0,0 +1,51 @@ +use std::collections::HashSet; +use std::fs; + +fn targeted_mutations(word: &str, targ: &str, hs: &HashSet<&str>) -> Vec> { + let mut working = [[word.to_string()].to_vec()].to_vec(); + let mut tried = HashSet::new(); + while working.iter().all(|a| a.last().unwrap() != &targ) { + let mut new_working: Vec> = vec![]; + for arr in working { + let s = arr.last().unwrap(); + tried.insert(s.to_owned()); + for j in 0..s.len() { + for c in 'a'..='z' { + let w = String::new() + &s[..j] + &c.to_string() + &s[j + 1..]; + if hs.contains(w.as_str()) && !tried.contains(&w) { + let mut a = arr.iter().map(|st| st.to_string()).collect::>(); + a.push(w); + new_working.push(a); + } + } + } + } + if new_working.is_empty() { + return [["This cannot be done.".to_string()].to_vec()].to_vec(); + } + working = new_working; + } + return working + .iter() + .filter(|a| !a.is_empty() && a.last().unwrap() == targ) + .map(|x| x.to_owned()) + .collect::>>(); +} + +fn main() { + let wordsfile = fs::read_to_string("unixdict.txt").unwrap().to_lowercase(); + let dict: HashSet<&str> = wordsfile.split_whitespace().into_iter().collect(); + println!("boy to man: {:?}", targeted_mutations("boy", "man", &dict)); + println!( + "girl to lady: {:?}", + targeted_mutations("girl", "lady", &dict) + ); + println!( + "john to jane: {:?}", + targeted_mutations("john", "jane", &dict) + ); + println!( + "child to adult: {:?}", + targeted_mutations("child", "adult", &dict) + ); +} diff --git a/Task/Word-search/Julia/word-search.julia b/Task/Word-search/Julia/word-search.jl similarity index 100% rename from Task/Word-search/Julia/word-search.julia rename to Task/Word-search/Julia/word-search.jl diff --git a/Task/Word-search/Kotlin/word-search.kotlin b/Task/Word-search/Kotlin/word-search.kts similarity index 100% rename from Task/Word-search/Kotlin/word-search.kotlin rename to Task/Word-search/Kotlin/word-search.kts diff --git a/Task/Word-search/Rust/word-search.rs b/Task/Word-search/Rust/word-search.rs new file mode 100644 index 0000000000..ff2bbb98fc --- /dev/null +++ b/Task/Word-search/Rust/word-search.rs @@ -0,0 +1,186 @@ +use once_cell::sync::Lazy; +use rand::rngs::ThreadRng; +use rand::seq::SliceRandom; +use regex::Regex; +use std::fs; + +const DIRS: [[i32; 2]; 8] = [ + [1, 0], + [0, 1], + [1, 1], + [1, -1], + [-1, 0], + [0, -1], + [-1, -1], + [-1, 1], +]; +const NROWS: usize = 10; +const NCOLS: usize = NROWS; +const GRIDSIZE: usize = NROWS * NCOLS; +const MINWORDS: usize = 25; + +struct Grid { + num_attempts: usize, + cells: Vec>, + solutions: Vec, +} + +fn new_grid() -> Grid { + return Grid { + num_attempts: 0, + cells: vec![vec![0_u8; NCOLS]; NROWS], + solutions: vec![String::new(); 0], + }; +} + +fn read_words(file_name: &str) -> Vec { + let re = Regex::new(r"^[a-z]{3,10}$").unwrap(); + let wordsfile = fs::read_to_string(file_name).unwrap().to_lowercase(); + return wordsfile + .split_whitespace() + .filter(|w| re.is_match(w)) + .map(|x| x.to_owned()) + .collect::>(); +} + +fn create_word_search(mut words: Vec) -> Grid { + let mut rng = rand::thread_rng(); + let mut gr = new_grid(); + 'outer: for i in 1..100 { + // up to 100 tries + gr = new_grid(); + let message_len = place_message(&mut gr, "Rosetta Code", &mut rng); + let target = GRIDSIZE - message_len; + let mut cells_filled = 0_usize; + words.shuffle(&mut rng); + for word in &words { + cells_filled += try_place_word(&mut gr, &word, &mut rng); + if cells_filled == target { + if gr.solutions.len() >= MINWORDS { + gr.num_attempts = i; + break 'outer; // outer for + } else { + break; // inner for + } + } + } + } + return gr; +} + +fn place_message(gr: &mut Grid, msg: &str, rng: &mut ThreadRng) -> usize { + static RE: Lazy = Lazy::new(|| Regex::new(r"[^A-Z]").unwrap()); + let mut smsg = msg.to_uppercase(); + smsg = RE.replace(&&smsg, "").to_string(); + let message_len = smsg.len(); + if message_len > 0 && message_len < GRIDSIZE { + let gap_size = GRIDSIZE / message_len; + for i in 0..message_len { + let rpos = i * gap_size + (0..gap_size).collect::>().choose(rng).unwrap(); + gr.cells[rpos / NCOLS][rpos % NCOLS] = smsg.as_bytes()[i]; + } + return message_len; + } + return 0; +} + +fn try_place_word(gr: &mut Grid, word: &str, rng: &mut ThreadRng) -> usize { + let binding = (0..DIRS.len()).collect::>(); + let rand_dir = binding.choose(rng).unwrap(); + let bindingp = (0..GRIDSIZE).collect::>(); + let rand_pos = bindingp.choose(rng).unwrap(); + for dir in 0..DIRS.len() { + let rdir = (dir + rand_dir) % DIRS.len(); + for pos in 0..GRIDSIZE { + let rpos = (pos + rand_pos) % GRIDSIZE; + let letters_placed = try_location(gr, word, rdir, rpos); + if letters_placed > 0 { + return letters_placed; + } + } + } + return 0; +} + +fn try_location(gr: &mut Grid, word: &str, dir: usize, pos: usize) -> usize { + let r = pos / NCOLS; + let c = pos % NCOLS; + let le = word.len(); + + // check bounds + if (DIRS[dir][0] == 1 && (le + c) > NCOLS) + || (DIRS[dir][0] == -1 && (le - 1) > c) + || (DIRS[dir][1] == 1 && (le + r) > NROWS) + || (DIRS[dir][1] == -1 && (le - 1) > r) + { + return 0; + } + let mut overlaps = 0; + + // check cells + let mut rr: i32 = r.try_into().unwrap(); + let mut cc: i32 = c.try_into().unwrap(); + for i in 0..le { + if gr.cells[rr as usize][cc as usize] != 0 + && gr.cells[rr as usize][cc as usize] != word.as_bytes()[i] + { + return 0; + } + cc += DIRS[dir][0]; + rr += DIRS[dir][1]; + } + + // place + rr = r.try_into().unwrap(); + cc = c.try_into().unwrap(); + for i in 0..le { + if gr.cells[rr as usize][cc as usize] == word.as_bytes()[i] { + overlaps += 1; + } else { + gr.cells[rr as usize][cc as usize] = word.as_bytes()[i]; + } + if i < le - 1 { + cc += DIRS[dir][0]; + rr += DIRS[dir][1]; + } + } + + let letters_placed = le - overlaps; + if letters_placed > 0 { + let sol = format!("{:>10} ({},{})({},{})", word, c, r, cc, rr); + gr.solutions.push(sol); + } + return letters_placed; +} + +fn print_result(gr: Grid) { + if gr.num_attempts == 0 { + println!("\nWord search puzzle: No grid to display\n"); + return; + } + let size = gr.solutions.len(); + println!( + "Word search puzzle solution:\n Attempts: {}", + gr.num_attempts + ); + println!(" Number of words: {}", size); + println!("\n 0 1 2 3 4 5 6 7 8 9"); + for r in 0..NROWS { + print!("\n{} ", r); + for c in 0..NCOLS { + print!(" {} ", gr.cells[r][c] as char); + } + } + println!("\n"); + for i in (0..size - 1).step_by(2) { + println!("{} {}", gr.solutions[i], gr.solutions[i + 1]); + } + if size % 2 == 1 { + println!("{}", gr.solutions[size - 1]); + } +} + +fn main() { + let dict_path = "unixdict.txt"; + print_result(create_word_search(read_words(dict_path))); +} diff --git a/Task/Word-wheel/Delphi/word-wheel.delphi b/Task/Word-wheel/Delphi/word-wheel.pas similarity index 100% rename from Task/Word-wheel/Delphi/word-wheel.delphi rename to Task/Word-wheel/Delphi/word-wheel.pas diff --git a/Task/Word-wheel/EasyLang/word-wheel.easy b/Task/Word-wheel/EasyLang/word-wheel.easy new file mode 100644 index 0000000000..656b753a41 --- /dev/null +++ b/Task/Word-wheel/EasyLang/word-wheel.easy @@ -0,0 +1,40 @@ +letters$ = "ndeokgelw" +mid$ = substr letters$ 5 1 +# +func count word$ c$ . + for h$ in strchars word$ + cnt += if h$ = c$ + . + return cnt +. +repeat + word$ = input + until word$ = "" + if len word$ >= 3 and len word$ <= 9 and strpos word$ mid$ <> 0 + hits = 0 + for c$ in strchars word$ + if strpos letters$ c$ <> 0 + hits += 1 + . + . + if len word$ = hits and hits >= 3 + c$ = "" + for c$ in strchars word$ + if count word$ c$ > count letters$ c$ + break 1 + . + . + if c$ = "" + write word$ & " " + . + . + . +. +# +# the content of unixdict.txt +input_data +10th +eke +keg +kong +week diff --git a/Task/Word-wheel/Julia/word-wheel-1.julia b/Task/Word-wheel/Julia/word-wheel-1.jl similarity index 100% rename from Task/Word-wheel/Julia/word-wheel-1.julia rename to Task/Word-wheel/Julia/word-wheel-1.jl diff --git a/Task/Word-wheel/Julia/word-wheel-2.julia b/Task/Word-wheel/Julia/word-wheel-2.jl similarity index 100% rename from Task/Word-wheel/Julia/word-wheel-2.julia rename to Task/Word-wheel/Julia/word-wheel-2.jl diff --git a/Task/Word-wheel/Rust/word-wheel.rs b/Task/Word-wheel/Rust/word-wheel.rs new file mode 100644 index 0000000000..58c3874745 --- /dev/null +++ b/Task/Word-wheel/Rust/word-wheel.rs @@ -0,0 +1,20 @@ +fn main() { + let wordsfile = fs::read_to_string("unixdict.txt").unwrap().to_lowercase(); + let wheel = "ndeokgelw".to_string(); + let middle = &wheel[4..=4]; + + for dictword in wordsfile.split_whitespace() { + let mut word = dictword.to_string(); + if word.len() > 2 && word.len() <= wheel.len() && word.contains(middle) { + for c in wheel.chars() { + if word.contains(c) { + let j = word.find(c).unwrap(); + word.replace_range(j..=j, " "); + } + } + if word.chars().filter(|c| c == &' ').count() == word.len() { + println!("{}", dictword); + } + } + } +} diff --git a/Task/Word-wrap/Delphi/word-wrap.delphi b/Task/Word-wrap/Delphi/word-wrap.pas similarity index 100% rename from Task/Word-wrap/Delphi/word-wrap.delphi rename to Task/Word-wrap/Delphi/word-wrap.pas diff --git a/Task/Word-wrap/Ed/word-wrap.ed b/Task/Word-wrap/Ed/word-wrap.ed new file mode 100644 index 0000000000..81f674c311 --- /dev/null +++ b/Task/Word-wrap/Ed/word-wrap.ed @@ -0,0 +1,5 @@ +H +g/.*/s/(.{0,79})([ ]|$)/\1\ +/g +,p +Q diff --git a/Task/Word-wrap/Elixir/word-wrap.elixir b/Task/Word-wrap/Elixir/word-wrap.ex similarity index 100% rename from Task/Word-wrap/Elixir/word-wrap.elixir rename to Task/Word-wrap/Elixir/word-wrap.ex diff --git a/Task/Word-wrap/Julia/word-wrap.julia b/Task/Word-wrap/Julia/word-wrap.jl similarity index 100% rename from Task/Word-wrap/Julia/word-wrap.julia rename to Task/Word-wrap/Julia/word-wrap.jl diff --git a/Task/Word-wrap/Kotlin/word-wrap.kotlin b/Task/Word-wrap/Kotlin/word-wrap.kts similarity index 100% rename from Task/Word-wrap/Kotlin/word-wrap.kotlin rename to Task/Word-wrap/Kotlin/word-wrap.kts diff --git a/Task/Word-wrap/OCaml/word-wrap.ocaml b/Task/Word-wrap/OCaml/word-wrap.ml similarity index 100% rename from Task/Word-wrap/OCaml/word-wrap.ocaml rename to Task/Word-wrap/OCaml/word-wrap.ml diff --git a/Task/Word-wrap/Rust/word-wrap.rust b/Task/Word-wrap/Rust/word-wrap.rs similarity index 100% rename from Task/Word-wrap/Rust/word-wrap.rust rename to Task/Word-wrap/Rust/word-wrap.rs diff --git a/Task/Word-wrap/Scheme/word-wrap.ss b/Task/Word-wrap/Scheme/word-wrap.scm similarity index 100% rename from Task/Word-wrap/Scheme/word-wrap.ss rename to Task/Word-wrap/Scheme/word-wrap.scm diff --git a/Task/Wordiff/Julia/wordiff.julia b/Task/Wordiff/Julia/wordiff.jl similarity index 100% rename from Task/Wordiff/Julia/wordiff.julia rename to Task/Wordiff/Julia/wordiff.jl diff --git a/Task/Wordiff/Rust/wordiff.rs b/Task/Wordiff/Rust/wordiff.rs new file mode 100644 index 0000000000..44e1b289f1 --- /dev/null +++ b/Task/Wordiff/Rust/wordiff.rs @@ -0,0 +1,100 @@ +use rand::seq::SliceRandom; +use std::collections::HashSet; +use std::fs; +use std::io::Write; + +fn request_player_names(wanted: i32) -> Vec { + let mut player_names = vec![]; + for i in 0..wanted { + let mut buf = String::new(); + print!("\nPlease enter the player's name for player {}: ", i + 1); + let _ = std::io::stdout().flush(); + let _ = std::io::stdin().read_line(&mut buf); + player_names.push(buf.trim_end().to_owned()); + } + return player_names; +} + +fn is_letter_removed(previous_word: &str, current_word: &str) -> bool { + for i in 0..previous_word.len() { + if current_word == previous_word[..i].to_owned() + &previous_word[i + 1..] { + return true; + } + } + return false; +} + +fn is_letter_added(previous_word: &str, current_word: &str) -> bool { + return is_letter_removed(current_word, previous_word); +} + +fn is_letter_changed(previous_word: &str, current_word: &str) -> bool { + if previous_word.len() != current_word.len() { + return false; + } + + let mut difference_count = 0; + for i in 0..current_word.len() { + difference_count += (current_word[i..=i] != previous_word[i..=i]) as usize; + } + return difference_count == 1; +} + +fn is_wordiff(current_word: &str, words_used: &Vec, dictionary: &HashSet<&str>) -> bool { + if !dictionary.contains(current_word) || words_used.contains(¤t_word.to_string()) { + return false; + } + let previous_word = words_used.last().unwrap(); + return is_letter_changed(previous_word, current_word) + || is_letter_removed(previous_word, current_word) + || is_letter_added(previous_word, current_word); +} + +fn could_have_entered(words_used: &Vec, dictionary: &HashSet<&str>) -> Vec { + let mut result: Vec = vec![]; + for word in dictionary { + if is_wordiff(word, words_used, dictionary) { + result.push(word.to_string()); + } + } + return result; +} + +fn main() { + let mut rng = rand::thread_rng(); + let wordsfile = fs::read_to_string("unixdict.txt").unwrap().to_lowercase(); + let words = wordsfile.split_whitespace().collect::>(); + let dictionary: &HashSet<&str> = &words.iter().cloned().collect(); + let mut starters = words + .clone() + .into_iter() + .filter(|w| w.len() == 3 || w.len() == 4) + .collect::>(); + starters.shuffle(&mut rng); + let mut words_used = vec![starters[0].to_string(); 1]; + + let player_names = request_player_names(2); + let mut playing = true; + let mut player_index = 0_usize; + let mut current_word = words_used.last().unwrap().to_string(); + println!("\nThe first word is: {}", current_word); + let _ = std::io::stdout().flush(); + + while playing { + print!("{}, enter your word: ", player_names[player_index]); + let _ = std::io::stdout().flush(); + current_word.clear(); + let _ = std::io::stdin().read_line(&mut current_word); + current_word = current_word.trim_end().to_owned(); + println!("You entered {}.", current_word); + if is_wordiff(¤t_word, &words_used, dictionary) { + words_used.push(current_word.clone()); + player_index = (player_index + 1) % player_names.len(); + } else { + println!("You have lost the game, {}.", player_names[player_index]); + let missed_words = could_have_entered(&words_used, dictionary); + println!("You could have entered: {:?}", missed_words); + playing = false; + } + } +} diff --git a/Task/Wordiff/V-(Vlang)/wordiff.v b/Task/Wordiff/V-(Vlang)/wordiff.v index 23ab172d42..134d1f4e69 100644 --- a/Task/Wordiff/V-(Vlang)/wordiff.v +++ b/Task/Wordiff/V-(Vlang)/wordiff.v @@ -5,11 +5,11 @@ import arrays fn is_wordiff(guesses []string, word string, dict []string) bool { if word !in dict { - println('That word is not in the dictionary') + println("That word is not in the dictionary") return false } if word in guesses { - println('That word has already been used') + println("That word has already been used") return false } if word.len < guesses[guesses.len-1].len { @@ -25,16 +25,16 @@ fn is_wordiff_removal(new_word string, last_word string) bool { return true } } - println('Word is not derived from previous by removal of one letter') + println("Word is not derived from previous by removal of one letter") return false } fn is_wordiff_insertion(new_word string, last_word string) bool { if new_word.len > last_word.len+1 { - println('More than one character insertion difference') + println("More than one character insertion difference") return false } - mut a := new_word.split('') - b := last_word.split('') + mut a := new_word.split("") + b := last_word.split("") for c in b { idx := a.index(c) if idx >=0 { @@ -42,7 +42,7 @@ fn is_wordiff_insertion(new_word string, last_word string) bool { } } if a.len >1 { - println('Word is not derived from previous by insertion of one letter') + println("Word is not derived from previous by insertion of one letter") return false } return true @@ -55,16 +55,16 @@ fn is_wordiff_change(new_word string, last_word string) bool { } } if diff != 1 { - println('More or less than exactly one character changed') + println("More or less than exactly one character changed") return false } return true } fn main() { - words := os.read_lines('unixdict.txt')? - time_limit := os.input('Time limit (sec) or 0 for none: ').int() - players := os.input('Please enter player names, separated by commas: ').split(',') + words := os.read_lines("unixdict.txt")? + time_limit := os.input("Time limit (sec) or 0 for none: ").int() + players := os.input("Please enter player names, separated by commas: ").split(",") dic_3_4 := words.filter(it.len in [3,4]) mut wordiffs := rand.choose(dic_3_4,1)? @@ -73,25 +73,25 @@ fn main() { mut turn_count := 0 for { turn_start := time.now() - word := os.input('${players[turn_count%players.len]}: Input a wordiff from ${wordiffs[wordiffs.len-1]}: ') + word := os.input("${players[turn_count%players.len]}: Input a wordiff from ${wordiffs[wordiffs.len-1]}: ") if time_limit != 0.0 && time.since(start).seconds()>time_limit{ - println('TIMES UP ${players[turn_count%players.len]}') + println("TIMES UP ${players[turn_count%players.len]}") break } else { if is_wordiff(wordiffs, word, words) { wordiffs<(p) or {0} - println(' ${players[i]}: ${sum/p.len:10.3 f} seconds average') + println(" ${players[i]}: ${sum/p.len:10.3 f} seconds average") } } diff --git a/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir b/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.ex similarity index 100% rename from Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir rename to Task/World-Cup-group-stage/Elixir/world-cup-group-stage.ex diff --git a/Task/World-Cup-group-stage/FreeBASIC/world-cup-group-stage.basic b/Task/World-Cup-group-stage/FreeBASIC/world-cup-group-stage.basic new file mode 100644 index 0000000000..e6ed99287b --- /dev/null +++ b/Task/World-Cup-group-stage/FreeBASIC/world-cup-group-stage.basic @@ -0,0 +1,96 @@ +Dim Shared As Integer points(3, 9) +Dim Shared As String*2 games(5) = {"12", "13", "14", "23", "24", "34"} +Dim Shared As String result +result = "000000" + +Sub SortArray(arr() As Integer) + Dim As Integer i, j + + For i = 0 To Ubound(arr) - 1 + For j = i + 1 To Ubound(arr) + If arr(i) > arr(j) Then Swap arr(i), arr(j) + Next + Next +End Sub + +Function ParseInt(number As String, base_ As Integer) As Integer + Dim As Integer i, x = 0, pot = 0 + + For i = Len(number) To 1 Step -1 + x += base_ ^ pot * Val(Mid(number, i, 1)) + pot += 1 + Next + + Return x +End Function + +Function Formato(decimal As Integer, base_ As Integer) As String + Dim As Integer cociente + Dim As String conv = "" + + Do + cociente = decimal \ base_ + conv = Str(decimal Mod base_) + conv + decimal = cociente + Loop Until cociente = 0 + + Return conv +End Function + +Function NextResult() As Boolean + If result = "222222" Then Return False + + Dim As Integer res = ParseInt(result, 3) + result = Formato(res + 1, 3) + While Len(result) < 6 + result = "0" & result + Wend + Return True +End Function + +Function Compute() As Boolean + 'Dim records(3) As Integer + Dim As Integer records(3), i, t + + For i = 0 To 5 + Select Case Mid(result, i + 1, 1) + Case "2" + t = Val(Mid(games(i), 1, 1)) - 1 + records(t) += 3 + Case "1" + t = Val(Mid(games(i), 1, 1)) - 1 + records(t) += 1 + t = Val(Mid(games(i), 2, 1)) - 1 + records(t) += 1 + Case "0" + t = Val(Mid(games(i), 2, 1)) - 1 + records(t) += 3 + End Select + Next + + SortArray(records()) + + For i = 0 To 3 + points(i, records(i)) += 1 + Next + + Return Iif(NextResult(), True, False) +End Function + +Do While Compute() +Loop + +Print "POINTS 0 1 2 3 4 5 6 7 8 9" +Print String (61, "-") +Dim As Integer i, j +Dim As String places(3) = {"1st", "2nd", "3rd", "4th"} + +For i = 0 To 3 + Print places(i); " place "; + For j = 0 To 9 + Print Using "#####"; points(3 - i, j); + Next + Print +Next + +Sleep diff --git a/Task/World-Cup-group-stage/Julia/world-cup-group-stage.julia b/Task/World-Cup-group-stage/Julia/world-cup-group-stage.jl similarity index 100% rename from Task/World-Cup-group-stage/Julia/world-cup-group-stage.julia rename to Task/World-Cup-group-stage/Julia/world-cup-group-stage.jl diff --git a/Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kotlin b/Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kts similarity index 100% rename from Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kotlin rename to Task/World-Cup-group-stage/Kotlin/world-cup-group-stage.kts diff --git a/Task/Write-entire-file/Delphi/write-entire-file.delphi b/Task/Write-entire-file/Delphi/write-entire-file.pas similarity index 100% rename from Task/Write-entire-file/Delphi/write-entire-file.delphi rename to Task/Write-entire-file/Delphi/write-entire-file.pas diff --git a/Task/Write-entire-file/Elixir/write-entire-file.elixir b/Task/Write-entire-file/Elixir/write-entire-file.ex similarity index 100% rename from Task/Write-entire-file/Elixir/write-entire-file.elixir rename to Task/Write-entire-file/Elixir/write-entire-file.ex diff --git a/Task/Write-entire-file/Julia/write-entire-file.julia b/Task/Write-entire-file/Julia/write-entire-file.jl similarity index 100% rename from Task/Write-entire-file/Julia/write-entire-file.julia rename to Task/Write-entire-file/Julia/write-entire-file.jl diff --git a/Task/Write-entire-file/Kotlin/write-entire-file.kotlin b/Task/Write-entire-file/Kotlin/write-entire-file.kts similarity index 100% rename from Task/Write-entire-file/Kotlin/write-entire-file.kotlin rename to Task/Write-entire-file/Kotlin/write-entire-file.kts diff --git a/Task/Write-entire-file/OCaml/write-entire-file.ocaml b/Task/Write-entire-file/OCaml/write-entire-file.ml similarity index 100% rename from Task/Write-entire-file/OCaml/write-entire-file.ocaml rename to Task/Write-entire-file/OCaml/write-entire-file.ml diff --git a/Task/Write-entire-file/Rust/write-entire-file.rust b/Task/Write-entire-file/Rust/write-entire-file.rs similarity index 100% rename from Task/Write-entire-file/Rust/write-entire-file.rust rename to Task/Write-entire-file/Rust/write-entire-file.rs diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.delphi b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.pas similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.delphi rename to Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.pas diff --git a/Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.elixir b/Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.ex similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.elixir rename to Task/Write-float-arrays-to-a-text-file/Elixir/write-float-arrays-to-a-text-file.ex diff --git a/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria b/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.ex similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.euphoria rename to Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.ex diff --git a/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic b/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic index 0ec9072912..a7966953a2 100644 --- a/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic +++ b/Task/Write-float-arrays-to-a-text-file/FutureBasic/write-float-arrays-to-a-text-file.basic @@ -27,4 +27,4 @@ end fn fn DoIt -HandleEven +HandleEvents diff --git a/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia b/Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.jl similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.julia rename to Task/Write-float-arrays-to-a-text-file/Julia/write-float-arrays-to-a-text-file.jl diff --git a/Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kotlin b/Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kts similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kotlin rename to Task/Write-float-arrays-to-a-text-file/Kotlin/write-float-arrays-to-a-text-file.kts diff --git a/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml b/Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ml similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ocaml rename to Task/Write-float-arrays-to-a-text-file/OCaml/write-float-arrays-to-a-text-file.ml diff --git a/Task/Write-language-name-in-3D-ASCII/Delphi/write-language-name-in-3d-ascii.delphi b/Task/Write-language-name-in-3D-ASCII/Delphi/write-language-name-in-3d-ascii.pas similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Delphi/write-language-name-in-3d-ascii.delphi rename to Task/Write-language-name-in-3D-ASCII/Delphi/write-language-name-in-3d-ascii.pas diff --git a/Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.elixir b/Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.ex similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.elixir rename to Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.ex diff --git a/Task/Write-language-name-in-3D-ASCII/Julia/write-language-name-in-3d-ascii.julia b/Task/Write-language-name-in-3D-ASCII/Julia/write-language-name-in-3d-ascii.jl similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Julia/write-language-name-in-3d-ascii.julia rename to Task/Write-language-name-in-3D-ASCII/Julia/write-language-name-in-3d-ascii.jl diff --git a/Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kotlin b/Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kts similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kotlin rename to Task/Write-language-name-in-3D-ASCII/Kotlin/write-language-name-in-3d-ascii.kts diff --git a/Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ocaml b/Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ml similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ocaml rename to Task/Write-language-name-in-3D-ASCII/OCaml/write-language-name-in-3d-ascii.ml diff --git a/Task/Write-language-name-in-3D-ASCII/Rust/write-language-name-in-3d-ascii.rust b/Task/Write-language-name-in-3D-ASCII/Rust/write-language-name-in-3d-ascii.rs similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Rust/write-language-name-in-3d-ascii.rust rename to Task/Write-language-name-in-3D-ASCII/Rust/write-language-name-in-3d-ascii.rs diff --git a/Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.delphi b/Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.pas similarity index 100% rename from Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.delphi rename to Task/Write-to-Windows-event-log/Delphi/write-to-windows-event-log.pas diff --git a/Task/Write-to-Windows-event-log/Julia/write-to-windows-event-log.julia b/Task/Write-to-Windows-event-log/Julia/write-to-windows-event-log.jl similarity index 100% rename from Task/Write-to-Windows-event-log/Julia/write-to-windows-event-log.julia rename to Task/Write-to-Windows-event-log/Julia/write-to-windows-event-log.jl diff --git a/Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kotlin b/Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kts similarity index 100% rename from Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kotlin rename to Task/Write-to-Windows-event-log/Kotlin/write-to-windows-event-log.kts diff --git a/Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-1.rust b/Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-1.rs similarity index 100% rename from Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-1.rust rename to Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-1.rs diff --git a/Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-2.rust b/Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-2.rs similarity index 100% rename from Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-2.rust rename to Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-2.rs diff --git a/Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-3.rust b/Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-3.rs similarity index 100% rename from Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-3.rust rename to Task/Write-to-Windows-event-log/Rust/write-to-windows-event-log-3.rs diff --git a/Task/XML-DOM-serialization/Julia/xml-dom-serialization.julia b/Task/XML-DOM-serialization/Julia/xml-dom-serialization.jl similarity index 100% rename from Task/XML-DOM-serialization/Julia/xml-dom-serialization.julia rename to Task/XML-DOM-serialization/Julia/xml-dom-serialization.jl diff --git a/Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kotlin b/Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kts similarity index 100% rename from Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kotlin rename to Task/XML-DOM-serialization/Kotlin/xml-dom-serialization.kts diff --git a/Task/XML-Input/Delphi/xml-input.delphi b/Task/XML-Input/Delphi/xml-input.pas similarity index 100% rename from Task/XML-Input/Delphi/xml-input.delphi rename to Task/XML-Input/Delphi/xml-input.pas diff --git a/Task/XML-Input/Julia/xml-input.julia b/Task/XML-Input/Julia/xml-input.jl similarity index 100% rename from Task/XML-Input/Julia/xml-input.julia rename to Task/XML-Input/Julia/xml-input.jl diff --git a/Task/XML-Input/Kotlin/xml-input.kotlin b/Task/XML-Input/Kotlin/xml-input.kts similarity index 100% rename from Task/XML-Input/Kotlin/xml-input.kotlin rename to Task/XML-Input/Kotlin/xml-input.kts diff --git a/Task/XML-Input/OCaml/xml-input-1.ocaml b/Task/XML-Input/OCaml/xml-input-1.ml similarity index 100% rename from Task/XML-Input/OCaml/xml-input-1.ocaml rename to Task/XML-Input/OCaml/xml-input-1.ml diff --git a/Task/XML-Input/OCaml/xml-input-2.ocaml b/Task/XML-Input/OCaml/xml-input-2.ml similarity index 100% rename from Task/XML-Input/OCaml/xml-input-2.ocaml rename to Task/XML-Input/OCaml/xml-input-2.ml diff --git a/Task/XML-Input/OCaml/xml-input-3.ocaml b/Task/XML-Input/OCaml/xml-input-3.ml similarity index 100% rename from Task/XML-Input/OCaml/xml-input-3.ocaml rename to Task/XML-Input/OCaml/xml-input-3.ml diff --git a/Task/XML-Input/OmniMark/xml-input-1.xom b/Task/XML-Input/OmniMark/xml-input-1.xom new file mode 100644 index 0000000000..02a0e02645 --- /dev/null +++ b/Task/XML-Input/OmniMark/xml-input-1.xom @@ -0,0 +1,16 @@ + + + + + + + + +]> diff --git a/Task/XML-Input/OmniMark/xml-input-2.xom b/Task/XML-Input/OmniMark/xml-input-2.xom new file mode 100644 index 0000000000..05c2b1629f --- /dev/null +++ b/Task/XML-Input/OmniMark/xml-input-2.xom @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/Task/XML-Input/OmniMark/xml-input-3.xom b/Task/XML-Input/OmniMark/xml-input-3.xom new file mode 100644 index 0000000000..b3c47ba866 --- /dev/null +++ b/Task/XML-Input/OmniMark/xml-input-3.xom @@ -0,0 +1,16 @@ +process + local stream students-dtd initial {file 'XML-input.dtd'} + local stream students-xml initial {file 'XML-input.xml'} + + do xml-parse document + scan students-dtd || students-xml + output "%c" + done + + element Student + output "%v(Name)%n" + suppress + + element #implied ; all other elements can be suppressed, except + output '%c' when element is Students + suppress when element isnt Students diff --git a/Task/XML-Input/Rust/xml-input-1.rust b/Task/XML-Input/Rust/xml-input-1.rs similarity index 100% rename from Task/XML-Input/Rust/xml-input-1.rust rename to Task/XML-Input/Rust/xml-input-1.rs diff --git a/Task/XML-Input/Rust/xml-input-2.rust b/Task/XML-Input/Rust/xml-input-2.rs similarity index 100% rename from Task/XML-Input/Rust/xml-input-2.rust rename to Task/XML-Input/Rust/xml-input-2.rs diff --git a/Task/XML-Output/Delphi/xml-output.delphi b/Task/XML-Output/Delphi/xml-output.pas similarity index 100% rename from Task/XML-Output/Delphi/xml-output.delphi rename to Task/XML-Output/Delphi/xml-output.pas diff --git a/Task/XML-Output/Euphoria/xml-output.euphoria b/Task/XML-Output/Euphoria/xml-output.ex similarity index 100% rename from Task/XML-Output/Euphoria/xml-output.euphoria rename to Task/XML-Output/Euphoria/xml-output.ex diff --git a/Task/XML-Output/Julia/xml-output.julia b/Task/XML-Output/Julia/xml-output.jl similarity index 100% rename from Task/XML-Output/Julia/xml-output.julia rename to Task/XML-Output/Julia/xml-output.jl diff --git a/Task/XML-Output/Kotlin/xml-output-1.kotlin b/Task/XML-Output/Kotlin/xml-output-1.kts similarity index 100% rename from Task/XML-Output/Kotlin/xml-output-1.kotlin rename to Task/XML-Output/Kotlin/xml-output-1.kts diff --git a/Task/XML-Output/Kotlin/xml-output-2.kotlin b/Task/XML-Output/Kotlin/xml-output-2.kts similarity index 100% rename from Task/XML-Output/Kotlin/xml-output-2.kotlin rename to Task/XML-Output/Kotlin/xml-output-2.kts diff --git a/Task/XML-Output/OCaml/xml-output-1.ocaml b/Task/XML-Output/OCaml/xml-output-1.ml similarity index 100% rename from Task/XML-Output/OCaml/xml-output-1.ocaml rename to Task/XML-Output/OCaml/xml-output-1.ml diff --git a/Task/XML-Output/OCaml/xml-output-2.ocaml b/Task/XML-Output/OCaml/xml-output-2.ml similarity index 100% rename from Task/XML-Output/OCaml/xml-output-2.ocaml rename to Task/XML-Output/OCaml/xml-output-2.ml diff --git a/Task/XML-Output/Rust/xml-output.rust b/Task/XML-Output/Rust/xml-output.rs similarity index 100% rename from Task/XML-Output/Rust/xml-output.rust rename to Task/XML-Output/Rust/xml-output.rs diff --git a/Task/XML-XPath/Delphi/xml-xpath-1.delphi b/Task/XML-XPath/Delphi/xml-xpath-1.pas similarity index 100% rename from Task/XML-XPath/Delphi/xml-xpath-1.delphi rename to Task/XML-XPath/Delphi/xml-xpath-1.pas diff --git a/Task/XML-XPath/Delphi/xml-xpath-2.delphi b/Task/XML-XPath/Delphi/xml-xpath-2.pas similarity index 100% rename from Task/XML-XPath/Delphi/xml-xpath-2.delphi rename to Task/XML-XPath/Delphi/xml-xpath-2.pas diff --git a/Task/XML-XPath/Julia/xml-xpath.julia b/Task/XML-XPath/Julia/xml-xpath.jl similarity index 100% rename from Task/XML-XPath/Julia/xml-xpath.julia rename to Task/XML-XPath/Julia/xml-xpath.jl diff --git a/Task/XML-XPath/Kotlin/xml-xpath.kotlin b/Task/XML-XPath/Kotlin/xml-xpath.kts similarity index 100% rename from Task/XML-XPath/Kotlin/xml-xpath.kotlin rename to Task/XML-XPath/Kotlin/xml-xpath.kts diff --git a/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia b/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.jl similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia rename to Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.jl diff --git a/Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kotlin b/Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kts similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kotlin rename to Task/Xiaolin-Wus-line-algorithm/Kotlin/xiaolin-wus-line-algorithm.kts diff --git a/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.ss b/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.scm similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.ss rename to Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-1.scm diff --git a/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.ss b/Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.scm similarity index 100% rename from Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.ss rename to Task/Xiaolin-Wus-line-algorithm/Scheme/xiaolin-wus-line-algorithm-2.scm diff --git a/Task/Y-combinator/Crystal/y-combinator-1.crystal b/Task/Y-combinator/Crystal/y-combinator-1.cr similarity index 100% rename from Task/Y-combinator/Crystal/y-combinator-1.crystal rename to Task/Y-combinator/Crystal/y-combinator-1.cr diff --git a/Task/Y-combinator/Crystal/y-combinator-2.crystal b/Task/Y-combinator/Crystal/y-combinator-2.cr similarity index 100% rename from Task/Y-combinator/Crystal/y-combinator-2.crystal rename to Task/Y-combinator/Crystal/y-combinator-2.cr diff --git a/Task/Y-combinator/Crystal/y-combinator-3.crystal b/Task/Y-combinator/Crystal/y-combinator-3.cr similarity index 100% rename from Task/Y-combinator/Crystal/y-combinator-3.crystal rename to Task/Y-combinator/Crystal/y-combinator-3.cr diff --git a/Task/Y-combinator/Delphi/y-combinator.delphi b/Task/Y-combinator/Delphi/y-combinator.pas similarity index 100% rename from Task/Y-combinator/Delphi/y-combinator.delphi rename to Task/Y-combinator/Delphi/y-combinator.pas diff --git a/Task/Y-combinator/Elixir/y-combinator.elixir b/Task/Y-combinator/Elixir/y-combinator.ex similarity index 100% rename from Task/Y-combinator/Elixir/y-combinator.elixir rename to Task/Y-combinator/Elixir/y-combinator.ex diff --git a/Task/Y-combinator/J/y-combinator-1.j b/Task/Y-combinator/J/y-combinator-1.j index b597d336eb..e6cd6b8f33 100644 --- a/Task/Y-combinator/J/y-combinator-1.j +++ b/Task/Y-combinator/J/y-combinator-1.j @@ -1,3 +1,3 @@ -Y=. '('':''<@;(1;~":0)<@;<@((":0)&;))'(2 : 0 '') - (1 : (m,'u'))(1 : (m,'''u u`:6('',(5!:5<''u''),'')`:6 y'''))(1 :'u u`:6') -) + Y=. {{x&(x`:6)`'' u y}} {{u`''&u}} + fac=. 1:`{{(* x`:6@<:)y}}@.(0 < ]) + fib=. {{(-&1 +&(x`:6) -&2)y}}^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-10.j b/Task/Y-combinator/J/y-combinator-10.j index c2fa4be554..479e547b25 100644 --- a/Task/Y-combinator/J/y-combinator-10.j +++ b/Task/Y-combinator/J/y-combinator-10.j @@ -1,6 +1 @@ - sr=. [ apply f.,&< NB. Self referring - lv=. (((^:_1)b.)(`(<'0';_1)))(`:6) NB. Linear representation of a verb argument - Y=. (&>)/lv(&sr) NB. Y with embedded states - Y=. 'Y'f. NB. Fixing it... - Y NB. ... To make it stateless (i.e., a combinator) -((((&>)/)((((^:_1)b.)(`_1))(`:6)))(&([ 128!:2 ,&<))) +XY=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')(1 :'('':''<@;(1;~":0)<@;<@((":0)&;))((''u u`:6('',(5!:5<''u''),'')`:6 y''),(10{a.),'':'',(10{a.),''x(u u`:6('',(5!:5<''u''),'')`:6)y'')')(1 :'u u`:6') diff --git a/Task/Y-combinator/J/y-combinator-11.j b/Task/Y-combinator/J/y-combinator-11.j index 55910b1599..9a26fa7d3b 100644 --- a/Task/Y-combinator/J/y-combinator-11.j +++ b/Task/Y-combinator/J/y-combinator-11.j @@ -1,20 +1,14 @@ -Y=:1 :0 - f=. u Defer - (5!:1<'f') f y -) - -Defer=: 1 :0 -: - g=. x&(x`:6) - (5!:1<'g') u y -) - -almost_factorial=: 4 :0 - if. 0 >: y do. 1 - else. y * x`:6 y-1 end. -) - -almost_fibonacci=: 4 :0 - if. 2 > y do. y - else. (x`:6 y-1) + x`:6 y-2 end. -) + 1 2 3 '([:`(>:@:])`(<:@:[ u 1:)`(<:@[ u [ u <:@:])@.(#.@,&*))'XY"0/ 1 2 3 4 5 NB. Ackermann function... + 3 4 5 6 7 + 5 7 9 11 13 +13 29 61 125 253 + '1:`(<: u <:)@.* : (+ + 2 * u@:])'XY"0/~ i.7 NB. Ambivalent recursion... +2 5 14 35 80 173 362 +3 6 15 36 81 174 363 +4 7 16 37 82 175 364 +5 8 17 38 83 176 365 +6 9 18 39 84 177 366 +7 10 19 40 85 178 367 +8 11 20 41 86 179 368 + NB. OEIS A097813 - main diagonal + NB. OEIS A050488 = A097813 - 1 - adyacent upper off-diagonal diff --git a/Task/Y-combinator/J/y-combinator-12.j b/Task/Y-combinator/J/y-combinator-12.j index baa222544a..758788c8b7 100644 --- a/Task/Y-combinator/J/y-combinator-12.j +++ b/Task/Y-combinator/J/y-combinator-12.j @@ -1,6 +1 @@ - almost_factorial Y 9 -362880 - almost_fibonacci Y 9 -34 - almost_fibonacci Y"0 i. 10 -0 1 1 2 3 5 8 13 21 34 +YX=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')($:`)(`:6) diff --git a/Task/Y-combinator/J/y-combinator-13.j b/Task/Y-combinator/J/y-combinator-13.j deleted file mode 100644 index 01995e50b7..0000000000 --- a/Task/Y-combinator/J/y-combinator-13.j +++ /dev/null @@ -1,9 +0,0 @@ -Y=:2 :0(0 :0) -NB. this block will be n in the second part -: - g=. x&(x`:6) - (5!:1<'g') u y -) - f=. u (1 :n) - (5!:1<'f') f y -) diff --git a/Task/Y-combinator/J/y-combinator-14.j b/Task/Y-combinator/J/y-combinator-14.j deleted file mode 100644 index 972cd7dc2f..0000000000 --- a/Task/Y-combinator/J/y-combinator-14.j +++ /dev/null @@ -1,2 +0,0 @@ - almost_factorial f. Y 10 -3628800 diff --git a/Task/Y-combinator/J/y-combinator-2.j b/Task/Y-combinator/J/y-combinator-2.j index a242963298..1a2e4cd6be 100644 --- a/Task/Y-combinator/J/y-combinator-2.j +++ b/Task/Y-combinator/J/y-combinator-2.j @@ -1,4 +1,4 @@ - 'if. * y do. y * u <: y else. 1 end.' Y 10 NB. Factorial -3628800 - '(u@:<:@:<: + u@:<:)^:(1 < ])' Y 10 NB. Fibonacci -55 + fac Y 9 +362880 + fib Y 9 +34 diff --git a/Task/Y-combinator/J/y-combinator-3.j b/Task/Y-combinator/J/y-combinator-3.j index 6ed01b419a..43c4ff31b2 100644 --- a/Task/Y-combinator/J/y-combinator-3.j +++ b/Task/Y-combinator/J/y-combinator-3.j @@ -1,7 +1,4 @@ - arb=. ':'<@;(1;~":0)<@;<@((":0)&;) NB. AR of an explicit adverb from its body - - ara=. 1 :'arb u' NB. The verb arb as an adverb - srt=. 1 :'arb ''u u`:6('' , (5!:5<''u'') , '')`:6 y''' NB. AR of the self-replication and transformation adverb - gab=. 1 :'u u`:6' NB. The AR of the adverb and the adverb itself as a train - - Y=. ara srt gab NB. Train of adverbs + Y=. ]:&>/]:^:_1 b.]:`(<'0';_1)`:6&([ 128!:2 ,&<) + sr=. [ apply f. ,&< NB. Self referring + fac=. 1:`(] * [ sr ] - 1:)@.(0 < ]) + fib=. (([ sr ] - 2:) + [ sr ] - 1:)^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-4.j b/Task/Y-combinator/J/y-combinator-4.j index 479e547b25..6bb711db53 100644 --- a/Task/Y-combinator/J/y-combinator-4.j +++ b/Task/Y-combinator/J/y-combinator-4.j @@ -1 +1,4 @@ -XY=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')(1 :'('':''<@;(1;~":0)<@;<@((":0)&;))((''u u`:6('',(5!:5<''u''),'')`:6 y''),(10{a.),'':'',(10{a.),''x(u u`:6('',(5!:5<''u''),'')`:6)y'')')(1 :'u u`:6') + fac f. Y 10 +3628800 + fib f. Y 10 +55 diff --git a/Task/Y-combinator/J/y-combinator-5.j b/Task/Y-combinator/J/y-combinator-5.j index 9a26fa7d3b..e5fcf900d8 100644 --- a/Task/Y-combinator/J/y-combinator-5.j +++ b/Task/Y-combinator/J/y-combinator-5.j @@ -1,14 +1,11 @@ - 1 2 3 '([:`(>:@:])`(<:@:[ u 1:)`(<:@[ u [ u <:@:])@.(#.@,&*))'XY"0/ 1 2 3 4 5 NB. Ackermann function... - 3 4 5 6 7 - 5 7 9 11 13 -13 29 61 125 253 - '1:`(<: u <:)@.* : (+ + 2 * u@:])'XY"0/~ i.7 NB. Ambivalent recursion... -2 5 14 35 80 173 362 -3 6 15 36 81 174 363 -4 7 16 37 82 175 364 -5 8 17 38 83 176 365 -6 9 18 39 84 177 366 -7 10 19 40 85 178 367 -8 11 20 41 86 179 368 - NB. OEIS A097813 - main diagonal - NB. OEIS A050488 = A097813 - 1 - adyacent upper off-diagonal + fac f. Y NB. Factorial... +'1:`(] * (([ 128!:2 ,&<) <:))@.(0 < ])&>/'&([ 128!:2 ,&<) + + fac f. NB. Factorial step... +1:`(] * (([ 128!:2 ,&<) <:))@.(0 < ]) + + fib f. Y NB. Fibonacci... +'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ])&>/'&([ 128!:2 ,&<) + + fib f. NB. Fibonacci step... +(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-6.j b/Task/Y-combinator/J/y-combinator-6.j index 758788c8b7..bcbaa5edea 100644 --- a/Task/Y-combinator/J/y-combinator-6.j +++ b/Task/Y-combinator/J/y-combinator-6.j @@ -1 +1,6 @@ -YX=. (1 :'('':''<@;(1;~":0)<@;<@((":0)&;))u')($:`)(`:6) + sr=. [ apply f. ,&< NB. Self referring + lv=. ]:^:_1 b.]:`(<'0';_1)`:6 NB. Linear representation of a verb operand + Y=. ]:&>/lv&sr NB. Y with embedded states + Y=. 'Y' f. NB. Fixing it... + Y NB. ... To make it stateless (i.e., a combinator) +((]: & >) / ((((]: ^: (_1)) b. ]:) ` (<'0';_1)) `: 6)) & ([ 128!:2 ,&<) diff --git a/Task/Y-combinator/J/y-combinator-7.j b/Task/Y-combinator/J/y-combinator-7.j index c88bb44baf..b597d336eb 100644 --- a/Task/Y-combinator/J/y-combinator-7.j +++ b/Task/Y-combinator/J/y-combinator-7.j @@ -1 +1,3 @@ -Y=. ((((&>)/)((((^:_1)b.)(`(<'0';_1)))(`:6)))(&([ 128!:2 ,&<))) +Y=. '('':''<@;(1;~":0)<@;<@((":0)&;))'(2 : 0 '') + (1 : (m,'u'))(1 : (m,'''u u`:6('',(5!:5<''u''),'')`:6 y'''))(1 :'u u`:6') +) diff --git a/Task/Y-combinator/J/y-combinator-8.j b/Task/Y-combinator/J/y-combinator-8.j index c700edddd5..a242963298 100644 --- a/Task/Y-combinator/J/y-combinator-8.j +++ b/Task/Y-combinator/J/y-combinator-8.j @@ -1,11 +1,4 @@ - u=. [ NB. Function (left) - n=. ] NB. Argument (right) - sr=. [ apply f. ,&< NB. Self referring - - fac=. (1:`(n * u sr n - 1:)) @. (0 < n) - fac f. Y 10 + 'if. * y do. y * u <: y else. 1 end.' Y 10 NB. Factorial 3628800 - - Fib=. ((u sr n - 2:) + u sr n - 1:) ^: (1 < n) - Fib f. Y 10 + '(u@:<:@:<: + u@:<:)^:(1 < ])' Y 10 NB. Fibonacci 55 diff --git a/Task/Y-combinator/J/y-combinator-9.j b/Task/Y-combinator/J/y-combinator-9.j index 7061a73639..6ed01b419a 100644 --- a/Task/Y-combinator/J/y-combinator-9.j +++ b/Task/Y-combinator/J/y-combinator-9.j @@ -1,12 +1,7 @@ - fac f. Y NB. Factorial... -'1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0 < ])&>/'&([ 128!:2 ,&<) + arb=. ':'<@;(1;~":0)<@;<@((":0)&;) NB. AR of an explicit adverb from its body - fac f. NB. Factorial step... -1:`(] * [ ([ 128!:2 ,&<) ] - 1:)@.(0 < ]) + ara=. 1 :'arb u' NB. The verb arb as an adverb + srt=. 1 :'arb ''u u`:6('' , (5!:5<''u'') , '')`:6 y''' NB. AR of the self-replication and transformation adverb + gab=. 1 :'u u`:6' NB. The AR of the adverb and the adverb itself as a train - - Fib f. Y NB. Fibonacci... -'(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ])&>/'&([ 128!:2 ,&<) - - Fib f. NB. Fibonacci step... -(([ ([ 128!:2 ,&<) ] - 2:) + [ ([ 128!:2 ,&<) ] - 1:)^:(1 < ]) + Y=. ara srt gab NB. Train of adverbs diff --git a/Task/Y-combinator/Julia/y-combinator-1.julia b/Task/Y-combinator/Julia/y-combinator-1.jl similarity index 100% rename from Task/Y-combinator/Julia/y-combinator-1.julia rename to Task/Y-combinator/Julia/y-combinator-1.jl diff --git a/Task/Y-combinator/Julia/y-combinator-2.julia b/Task/Y-combinator/Julia/y-combinator-2.jl similarity index 100% rename from Task/Y-combinator/Julia/y-combinator-2.julia rename to Task/Y-combinator/Julia/y-combinator-2.jl diff --git a/Task/Y-combinator/Kotlin/y-combinator.kotlin b/Task/Y-combinator/Kotlin/y-combinator.kts similarity index 100% rename from Task/Y-combinator/Kotlin/y-combinator.kotlin rename to Task/Y-combinator/Kotlin/y-combinator.kts diff --git a/Task/Y-combinator/Nu/y-combinator.nu b/Task/Y-combinator/Nu/y-combinator.nu new file mode 100644 index 0000000000..acfd0621ab --- /dev/null +++ b/Task/Y-combinator/Nu/y-combinator.nu @@ -0,0 +1,14 @@ +def Y [f] { + {|x| do $f {|y| do (do $x $x) $y } } | do $in $in +} + +let factorial = Y {|rec| + {|n| if $n < 2 { 1 } else { (do $rec ($n - 1)) * $n } } +} + +let fibonacci = Y {|rec| + {|n| if $n < 2 { $n } else { (do $rec ($n - 1)) + (do $rec ($n - 2)) } } +} + + +..9 | each { {fac: (do $factorial $in) fib: (do $fibonacci $in)} } diff --git a/Task/Y-combinator/OCaml/y-combinator-1.ocaml b/Task/Y-combinator/OCaml/y-combinator-1.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-1.ocaml rename to Task/Y-combinator/OCaml/y-combinator-1.ml diff --git a/Task/Y-combinator/OCaml/y-combinator-2.ocaml b/Task/Y-combinator/OCaml/y-combinator-2.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-2.ocaml rename to Task/Y-combinator/OCaml/y-combinator-2.ml diff --git a/Task/Y-combinator/OCaml/y-combinator-3.ocaml b/Task/Y-combinator/OCaml/y-combinator-3.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-3.ocaml rename to Task/Y-combinator/OCaml/y-combinator-3.ml diff --git a/Task/Y-combinator/OCaml/y-combinator-4.ocaml b/Task/Y-combinator/OCaml/y-combinator-4.ml similarity index 100% rename from Task/Y-combinator/OCaml/y-combinator-4.ocaml rename to Task/Y-combinator/OCaml/y-combinator-4.ml diff --git a/Task/Y-combinator/Q/y-combinator.q b/Task/Y-combinator/Q/y-combinator.q index 10e057588a..765814b515 100644 --- a/Task/Y-combinator/Q/y-combinator.q +++ b/Task/Y-combinator/Q/y-combinator.q @@ -2,6 +2,6 @@ > fac: {{$[y<2; 1; y*x y-1]} x} > (Y fac) 6 720j -> fib: {{$[y<2; 1; (x y-1) + (x y-2)]} x} +> fib: {{$[y<2; y; (x y-1) + (x y-2)]} x} > (Y fib) each til 20 -1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 +0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 diff --git a/Task/Y-combinator/Rust/y-combinator.rust b/Task/Y-combinator/Rust/y-combinator.rs similarity index 100% rename from Task/Y-combinator/Rust/y-combinator.rust rename to Task/Y-combinator/Rust/y-combinator.rs diff --git a/Task/Y-combinator/Scheme/y-combinator-1.ss b/Task/Y-combinator/Scheme/y-combinator-1.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-1.ss rename to Task/Y-combinator/Scheme/y-combinator-1.scm diff --git a/Task/Y-combinator/Scheme/y-combinator-2.ss b/Task/Y-combinator/Scheme/y-combinator-2.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-2.ss rename to Task/Y-combinator/Scheme/y-combinator-2.scm diff --git a/Task/Y-combinator/Scheme/y-combinator-3.ss b/Task/Y-combinator/Scheme/y-combinator-3.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-3.ss rename to Task/Y-combinator/Scheme/y-combinator-3.scm diff --git a/Task/Y-combinator/Scheme/y-combinator-4.ss b/Task/Y-combinator/Scheme/y-combinator-4.scm similarity index 100% rename from Task/Y-combinator/Scheme/y-combinator-4.ss rename to Task/Y-combinator/Scheme/y-combinator-4.scm diff --git a/Task/Yahoo-search-interface/Julia/yahoo-search-interface.julia b/Task/Yahoo-search-interface/Julia/yahoo-search-interface.jl similarity index 100% rename from Task/Yahoo-search-interface/Julia/yahoo-search-interface.julia rename to Task/Yahoo-search-interface/Julia/yahoo-search-interface.jl diff --git a/Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kotlin b/Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kts similarity index 100% rename from Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kotlin rename to Task/Yahoo-search-interface/Kotlin/yahoo-search-interface.kts diff --git a/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg b/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg index 79b28d08b0..f7655de3a9 100644 --- a/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg +++ b/Task/Yellowstone-sequence/ALGOL-68/yellowstone-sequence.alg @@ -24,7 +24,8 @@ BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # IF n > 2 THEN result[ 3 ] := 3; # guess the maximum element will be n, if it is larger, used will be enlarged # - REF[]BOOL used := HEAP[ 1 : n ]BOOL; + HEAP[ 1 : n ]BOOL initial used; + REF[]BOOL used := initial used; used[ 1 ] := used[ 2 ] := used[ 3 ] := TRUE; FOR i FROM 4 TO UPB used DO used[ i ] := FALSE OD; FOR i FROM 4 TO UPB result DO @@ -34,7 +35,7 @@ BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # FOR j WHILE NOT found DO IF j > UPB used THEN # not enough elements in used - enlarge it # - REF[]BOOL new used := HEAP[ 1 : 2 * UPB used ]BOOL; + HEAP[ 1 : 2 * UPB used ]BOOL new used; new used[ 1 : UPB used ] := used; FOR k FROM UPB used + 1 TO UPB new used DO new used[ k ] := FALSE OD; used := new used @@ -56,5 +57,6 @@ BEGIN # find members of the yellowstone sequence: starting from 1, 2, 3 the # []INT ys = YELLOWSTONE 30; FOR i TO UPB ys DO print( ( " ", whole( ys[ i ], 0 ) ) ) - OD + OD; + print( ( newline ) ) END diff --git a/Task/Yellowstone-sequence/Delphi/yellowstone-sequence.delphi b/Task/Yellowstone-sequence/Delphi/yellowstone-sequence.pas similarity index 100% rename from Task/Yellowstone-sequence/Delphi/yellowstone-sequence.delphi rename to Task/Yellowstone-sequence/Delphi/yellowstone-sequence.pas diff --git a/Task/Yellowstone-sequence/Julia/yellowstone-sequence.julia b/Task/Yellowstone-sequence/Julia/yellowstone-sequence.jl similarity index 100% rename from Task/Yellowstone-sequence/Julia/yellowstone-sequence.julia rename to Task/Yellowstone-sequence/Julia/yellowstone-sequence.jl diff --git a/Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kotlin b/Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kts similarity index 100% rename from Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kotlin rename to Task/Yellowstone-sequence/Kotlin/yellowstone-sequence.kts diff --git a/Task/Yellowstone-sequence/Rust/yellowstone-sequence.rust b/Task/Yellowstone-sequence/Rust/yellowstone-sequence.rs similarity index 100% rename from Task/Yellowstone-sequence/Rust/yellowstone-sequence.rust rename to Task/Yellowstone-sequence/Rust/yellowstone-sequence.rs diff --git a/Task/Yin-and-yang/Delphi/yin-and-yang.delphi b/Task/Yin-and-yang/Delphi/yin-and-yang.pas similarity index 100% rename from Task/Yin-and-yang/Delphi/yin-and-yang.delphi rename to Task/Yin-and-yang/Delphi/yin-and-yang.pas diff --git a/Task/Yin-and-yang/Julia/yin-and-yang.julia b/Task/Yin-and-yang/Julia/yin-and-yang.jl similarity index 100% rename from Task/Yin-and-yang/Julia/yin-and-yang.julia rename to Task/Yin-and-yang/Julia/yin-and-yang.jl diff --git a/Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin b/Task/Yin-and-yang/Kotlin/yin-and-yang.kts similarity index 100% rename from Task/Yin-and-yang/Kotlin/yin-and-yang.kotlin rename to Task/Yin-and-yang/Kotlin/yin-and-yang.kts diff --git a/Task/Yin-and-yang/OCaml/yin-and-yang.ocaml b/Task/Yin-and-yang/OCaml/yin-and-yang.ml similarity index 100% rename from Task/Yin-and-yang/OCaml/yin-and-yang.ocaml rename to Task/Yin-and-yang/OCaml/yin-and-yang.ml diff --git a/Task/Yin-and-yang/Rust/yin-and-yang.rust b/Task/Yin-and-yang/Rust/yin-and-yang.rs similarity index 100% rename from Task/Yin-and-yang/Rust/yin-and-yang.rust rename to Task/Yin-and-yang/Rust/yin-and-yang.rs diff --git a/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg b/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg index 4222092053..57c13b77a4 100644 --- a/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg +++ b/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg @@ -22,20 +22,21 @@ BEGIN AND can set( smoke OF h, smoke OF s ) ) # XOR # ; # sets a field in a house to value if it is unknown # - PROC set = ( REF INT field, INT value )VOID: IF field = unknown AND value /= same THEN field := value FI; + PROC setf = ( REF INT field, INT value )VOID: + IF field = unknown AND value /= same THEN field := value FI; # sets the unknown fields in house h to the non-same fields of suggestion s # OP +:= = ( REF HOUSE h, HOUSE s )VOID: - ( set( nationality OF h, nationality OF s ); set( animal OF h, animal OF s ) - ; set( colour OF h, colour OF s ); set( drink OF h, drink OF s ) - ; set( smoke OF h, smoke OF s ) + ( setf( nationality OF h, nationality OF s ); setf( animal OF h, animal OF s ) + ; setf( colour OF h, colour OF s ); setf( drink OF h, drink OF s ) + ; setf( smoke OF h, smoke OF s ) ) # +:= # ; # sets a field in a house to unknown if the value is not same # - PROC reset = ( REF INT field, INT value )VOID: IF value /= same THEN field := unknown FI; + PROC resetf = ( REF INT field, INT value )VOID: IF value /= same THEN field := unknown FI; # sets fields in house h to unknown if the suggestion s is not same # OP -:= = ( REF HOUSE h, HOUSE s )VOID: - ( reset( nationality OF h, nationality OF s ); reset( animal OF h, animal OF s ) - ; reset( colour OF h, colour OF s ); reset( drink OF h, drink OF s ) - ; reset( smoke OF h, smoke OF s ) + ( resetf( nationality OF h, nationality OF s ); resetf( animal OF h, animal OF s ) + ; resetf( colour OF h, colour OF s ); resetf( drink OF h, drink OF s ) + ; resetf( smoke OF h, smoke OF s ) ) # -:= # ; # attempts a partial solution for the house at pos # PROC try = ( INT pos, HOUSE suggestion, PROC VOID continue )VOID: diff --git a/Task/Zebra-puzzle/Crystal/zebra-puzzle.crystal b/Task/Zebra-puzzle/Crystal/zebra-puzzle.cr similarity index 100% rename from Task/Zebra-puzzle/Crystal/zebra-puzzle.crystal rename to Task/Zebra-puzzle/Crystal/zebra-puzzle.cr diff --git a/Task/Zebra-puzzle/Elixir/zebra-puzzle.elixir b/Task/Zebra-puzzle/Elixir/zebra-puzzle.ex similarity index 100% rename from Task/Zebra-puzzle/Elixir/zebra-puzzle.elixir rename to Task/Zebra-puzzle/Elixir/zebra-puzzle.ex diff --git a/Task/Zebra-puzzle/FreeBASIC/zebra-puzzle.basic b/Task/Zebra-puzzle/FreeBASIC/zebra-puzzle.basic new file mode 100644 index 0000000000..dd4499cd39 --- /dev/null +++ b/Task/Zebra-puzzle/FreeBASIC/zebra-puzzle.basic @@ -0,0 +1,185 @@ +Enum attr + Colour = 1 + Nationality + Beverage + Smoke + Pet +End Enum + +Enum Drinks_ + Beer = 1 + Coffee + Milk + Tea + Water +End Enum + +Enum nations + Danish = 1 + English + German + Norwegian + Swedish +End Enum + +Enum colors + Blue = 1 + Green + Red + White + Yellow +End Enum + +Enum tobaccos + Blend = 1 + BlueMaster + Dunhill + PallMall + Prince +End Enum + +Enum animals + Bird = 1 + Cat + Dog + Horse + Zebra +End Enum + +Const factorial5 = 120 +Dim Shared As String permutation(120), perm(5) +Dim Shared As String Colours(5), Nationalities(5), Drinks(5), Smokes(5), Pets(5) +Dim Shared As Integer index + +Sub generate(n As Integer, A() As Integer) + Dim As Integer i + If n = 1 Then + Dim tmp As String = "" + For i = 1 To 5 + tmp &= Str(A(i)) & " " + Next i + permutation(index) = tmp + index += 1 + Else + For i = 1 To n + generate(n - 1, A()) + If n Mod 2 = 0 Then + Swap A(i), A(n) + Else + Swap A(1), A(n) + End If + Next i + End If +End Sub + +Function house(i As Integer, nombre As Integer) As Integer + For x As Integer = 1 To 5 + If Val(Mid(perm(i), x * 2 - 1, 1)) = nombre Then Return x + Next x + Return 0 +End Function + +Function left_of(h1 As Integer, h2 As Integer) As Boolean + Return (h1 - h2) = -1 +End Function + +Function next_to(h1 As Integer, h2 As Integer) As Boolean + Return Abs(h1 - h2) = 1 +End Function + +Sub print_house(i As Integer) + Print Using "####: "; i; + Print Using "\ \ \ \ \ \ \ \ \ \"; _ + Colours(Val(Mid(perm(Colour), i * 2 - 1, 1))); _ + Nationalities(Val(Mid(perm(Nationality), i * 2 - 1, 1))); _ + Drinks(Val(Mid(perm(Beverage), i * 2 - 1, 1))); _ + Smokes(Val(Mid(perm(Smoke), i * 2 - 1, 1))); _ + Pets(Val(Mid(perm(Pet), i * 2 - 1, 1))) +End Sub + +Sub Zebra_puzzle() + Colours(1) = "blue": Colours(2) = "green": Colours(3) = "red": Colours(4) = "white": Colours(5) = "yellow" + Nationalities(1) = "Dane": Nationalities(2) = "English": Nationalities(3) = "German": Nationalities(4) = "Norwegian": Nationalities(5) = "Swede" + Drinks(1) = "beer": Drinks(2) = "coffee": Drinks(3) = "milk": Drinks(4) = "tea": Drinks(5) = "water" + Smokes(1) = "Blend": Smokes(2) = "Blue Master": Smokes(3) = "Dunhill": Smokes(4) = "Pall Mall": Smokes(5) = "Prince" + Pets(1) = "birds": Pets(2) = "cats": Pets(3) = "dog": Pets(4) = "horse": Pets(5) = "zebra" + + Dim As String solperms(120, 5) + Dim As Integer solutions, i, c, n, d, s, p, j + Dim As Integer b(5) + For i = 1 To 5: b(i) = i: Next + 'There are five houses. + index = 0 + generate(5, b()) + For c = 0 To factorial5 - 1 + perm(Colour) = permutation(c) + 'The green house is immediately to the left of the white house. + If left_of(house(Colour, Green), house(Colour, White)) Then + For n = 0 To factorial5 - 1 + perm(Nationality) = permutation(n) + 'The Norwegian lives in the first house. + 'The English man lives in the red house. + 'The Norwegian lives next to the blue house. + If house(Nationality, Norwegian) = 1 _ + And house(Nationality, English) = house(Colour, Red) _ + And next_to(house(Nationality, Norwegian), house(Colour, Blue)) Then + For d = 0 To factorial5 - 1 + perm(Beverage) = permutation(d) + 'The Dane drinks tea. + 'They drink coffee in the green house. + 'In the middle house they drink milk. + If house(Nationality, Danish) = house(Beverage, Tea) _ + And house(Beverage, Coffee) = house(Colour, Green) _ + And house(Beverage, Milk) = 3 Then + For s = 0 To factorial5 - 1 + perm(Smoke) = permutation(s) + 'In the yellow house they smoke Dunhill. + 'The German smokes Prince. + 'The man who smokes Blue Master drinks beer. + 'They Drink water in a house next to the house where they smoke Blend. + If house(Colour, Yellow) = house(Smoke, Dunhill) _ + And house(Nationality, German) = house(Smoke, Prince) _ + And house(Smoke, BlueMaster) = house(Beverage, Beer) _ + And next_to(house(Beverage, Water), house(Smoke, Blend)) Then + For p = 0 To factorial5 - 1 + perm(Pet) = permutation(p) + 'The Swede has a dog. + 'The man who smokes Pall Mall has birds. + 'The man who smokes Blend lives in the house next to the house with cats. + 'In a house next to the house where they have a horse, they smoke Dunhill. + If house(Nationality, Swedish) = house(Pet, Dog) _ + And house(Smoke, PallMall) = house(Pet, Bird) _ + And next_to(house(Smoke, Blend), house(Pet, Cat)) _ + And next_to(house(Pet, Horse), house(Smoke, Dunhill)) Then + For i = 1 To 5 + print_house(i) + Next i + Print + solutions += 1 + For j = 1 To 5 + solperms(solutions - 1, j - 1) = perm(j) + Next j + End If + Next p + End If + Next s + End If + Next d + End If + Next n + End If + Next c + + Print solutions & " solution" & Iif(solutions > 1, "s", "") & " found" + For i As Integer = 0 To solutions - 1 + For j As Integer = 1 To 5 + perm(j) = solperms(i, j - 1) + Next j + Print "The " & Nationalities(Val(Mid(perm(Nationality), house(Pet, Zebra) * 2 - 1, 1))) & " owns the Zebra" + Next i +End Sub +Print "House Colour Nation Drink Smoke Animal" + +Zebra_puzzle() + +Sleep diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-1.j b/Task/Zebra-puzzle/J/zebra-puzzle-1.j index 3a97c1da26..cfff37de00 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-1.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-1.j @@ -1,13 +1,14 @@ -ehs=: 5$a: - -cr=: (('English';'red') 0 3} ehs);<('Dane';'tea') 0 2}ehs -cr=: cr, (('German';'Prince') 0 4}ehs);<('Swede';'dog') 0 1 }ehs - -cs=: <('PallMall';'birds') 4 1}ehs -cs=: cs, (('yellow';'Dunhill') 3 4}ehs);<('BlueMaster';'beer') 4 2}ehs - -lof=: (('coffee';'green')2 3}ehs);<(<'white')3}ehs - -next=: <((<'Blend') 4 }ehs);<(<'water')2}ehs -next=: next,<((<'Blend') 4 }ehs);<(<'cats')1}ehs -next=: next,<((<'Dunhill') 4}ehs);<(<'horse')1}ehs +in=: {{n&{ i. m"_}} NB. index of m in row n of matrix +F =: {{u"_1 # ]}} NB. filter by function of items +'Col Nat Pet Drink Cig'=: i.5 NB. refer to rows by name +'col nat pet drink cig'=: (A.~i.@!@#)&>;:'BGRWY DEGNS BCDHZ BCMTW BbDpP' NB. perm matrices +P=: ('W' in Col (= >:) 'G' in Col)F ,/col,:"1/nat NB. join first two mats and add 1st constraint +P=: ,/pet,"2 1/~ (('E' in Nat = 'R' in Col)*.(0 = 'N' in Nat))F P NB. and so on... +P=: ,/drink,"2 1/~ (('D' in Pet = 'S' in Nat)*.('N' in Nat (1=|@:-) 'B' in Col))F P +P=: (('C' in Drink = 'G' in Col)*.(2 = 'M' in Drink))F P +P=: (('T' in Drink = 'D' in Nat)*.('p' in Cig = 'B' in Pet))F ,/P,"2 1/cig +P=: (('D' in Cig = 'Y' in Col)*.('b' in Cig = 'B' in Drink))F P +P=: (('P' in Cig = 'G' in Nat)*.('B' in Cig (1=|@:-) 'C' in Pet))F P +P=: (('D' in Cig (1=|@:-) 'H' in Pet)*.('B' in Cig (1=|@:-) 'W' in Drink))F P +echo 'Solutions found: ',(":#P),LF,LF,~' owns the Z',~('Z' in Pet { Nat&{){.P +echo 'Col Nat Pet Drink Cig', ([,(6#' '),])/"1|:{.P diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-10.j b/Task/Zebra-puzzle/J/zebra-puzzle-10.j index eea43ac714..ce52506cf3 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-10.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-10.j @@ -1,12 +1,8 @@ - houses solve3 constraints, [: compose&.>~/y&, +z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x +> (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z +) diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-11.j b/Task/Zebra-puzzle/J/zebra-puzzle-11.j new file mode 100644 index 0000000000..eea43ac714 --- /dev/null +++ b/Task/Zebra-puzzle/J/zebra-puzzle-11.j @@ -0,0 +1,12 @@ + houses solve3 constraints, next + lof +┌─────────────────┬───────────┐ +│┌┬┬──────┬─────┬┐│┌┬┬┬─────┬┐│ +││││coffee│green│││││││white│││ +│└┴┴──────┴─────┴┘│└┴┴┴─────┴┘│ +└─────────────────┴───────────┘ diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-4.j b/Task/Zebra-puzzle/J/zebra-puzzle-4.j index 55bcd68d29..1ad98a0b60 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-4.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-4.j @@ -1 +1,4 @@ -houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs; next diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-5.j b/Task/Zebra-puzzle/J/zebra-puzzle-5.j index 79452d510f..55bcd68d29 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-5.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-5.j @@ -1,6 +1 @@ - houses -┌───────────────┬──────────┬──────────┬──────┬──────┐ -│┌─────────┬┬┬┬┐│┌┬┬┬────┬┐│┌┬┬────┬┬┐│┌┬┬┬┬┐│┌┬┬┬┬┐│ -││Norwegian││││││││││blue││││││milk││││││││││││││││││ -│└─────────┴┴┴┴┘│└┴┴┴────┴┘│└┴┴────┴┴┘│└┴┴┴┴┘│└┴┴┴┴┘│ -└───────────────┴──────────┴──────────┴──────┴──────┘ +houses=: ((<'Norwegian') 0}ehs);((<'blue') 3 }ehs);((<'milk') 2}ehs);ehs;#S:0)"1 -compose=: [: filter f. [: ,/ select f. L:0"1"1 _ - -solve=: 4 :0 -h=. ,:x -whilst. 0=# z do. - for_e. y do. h=. h compose > e end. - z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h -end. -) +constraints=: hcr;hcs;hlof;"0 houses solve constraints -┌─────────┬─────┬──────┬──────┬──────────┐ -│Norwegian│cats │water │yellow│Dunhill │ -├─────────┼─────┼──────┼──────┼──────────┤ -│Dane │horse│tea │blue │Blend │ -├─────────┼─────┼──────┼──────┼──────────┤ -│English │birds│milk │red │PallMall │ -├─────────┼─────┼──────┼──────┼──────────┤ -│German │ │coffee│green │Prince │ -├─────────┼─────┼──────┼──────┼──────────┤ -│Swede │dog │beer │white │BlueMaster│ -└─────────┴─────┴──────┴──────┴──────────┘ +Select=: [: ~. ,: #~ ,&(0~:#) +Filter=: #~ *./@:(2>#S:0)"1 +Compose=: [: Filter [: ,/ Select L:0"1"1 _ + +solve=: 4 :0 +h=. ,:x +whilst. 0=# z do. + for_e. y do. h=. h Compose > e end. + z=.(#~1=[:+/"1 (0=#)S:0"1) h=.~. h +end. +) diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-9.j b/Task/Zebra-puzzle/J/zebra-puzzle-9.j index 4ca962c4d5..ac84dd931f 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-9.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-9.j @@ -1,8 +1,12 @@ -zebra=: (-i.5)|."0 1 (<(<'zebra') 1}ehs),4$ [: compose&.>~/y&, f. -z=. f^:(3>[:#(#~p"1)&>)^:_ <,:x ->"0 (#~([:*./[:;[:<@({.~:}.)\.;)"1)(#~p"1); z -) + > houses solve constraints +┌─────────┬─────┬──────┬──────┬──────────┐ +│Norwegian│cats │water │yellow│Dunhill │ +├─────────┼─────┼──────┼──────┼──────────┤ +│Dane │horse│tea │blue │Blend │ +├─────────┼─────┼──────┼──────┼──────────┤ +│English │birds│milk │red │PallMall │ +├─────────┼─────┼──────┼──────┼──────────┤ +│German │ │coffee│green │Prince │ +├─────────┼─────┼──────┼──────┼──────────┤ +│Swede │dog │beer │white │BlueMaster│ +└─────────┴─────┴──────┴──────┴──────────┘ diff --git a/Task/Zebra-puzzle/Julia/zebra-puzzle-1.julia b/Task/Zebra-puzzle/Julia/zebra-puzzle-1.jl similarity index 90% rename from Task/Zebra-puzzle/Julia/zebra-puzzle-1.julia rename to Task/Zebra-puzzle/Julia/zebra-puzzle-1.jl index 6549440ab4..50aa43a79c 100644 --- a/Task/Zebra-puzzle/Julia/zebra-puzzle-1.julia +++ b/Task/Zebra-puzzle/Julia/zebra-puzzle-1.jl @@ -1,6 +1,5 @@ -# Julia 1.0 using Combinatorics -function make(str, test ) +function make(str, test = (s) -> true) filter(test, collect( permutations(split(str))) ) end @@ -9,7 +8,6 @@ men = make("danish english german norwegian swedish", drinks = make("beer coffee milk tea water", x -> "milk" == x[3]) -#Julia 1.0 compatible colors = make("blue green red white yellow", x -> 1 == findfirst(c -> c == "white", x) - findfirst(c -> c == "green",x)) @@ -18,11 +16,11 @@ pets = make("birds cats dog horse zebra") smokes = make("blend blue-master dunhill pall-mall prince") function eq(x, xs, y, ys) - findfirst(xs, x) == findfirst(ys, y) + findfirst(s -> s == x, xs) == findfirst(s -> s == y, ys) end function adj(x, xs, y, ys) - 1 == abs(findfirst(xs, x) - findfirst(ys, y)) + 1 == abs(findfirst(z -> z == x, xs) - findfirst(z -> z == y, ys)) end function print_houses(n, pet, nationality, colors, drink, smokes) diff --git a/Task/Zebra-puzzle/Julia/zebra-puzzle-2.julia b/Task/Zebra-puzzle/Julia/zebra-puzzle-2.jl similarity index 100% rename from Task/Zebra-puzzle/Julia/zebra-puzzle-2.julia rename to Task/Zebra-puzzle/Julia/zebra-puzzle-2.jl diff --git a/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin b/Task/Zebra-puzzle/Kotlin/zebra-puzzle.kts similarity index 100% rename from Task/Zebra-puzzle/Kotlin/zebra-puzzle.kotlin rename to Task/Zebra-puzzle/Kotlin/zebra-puzzle.kts diff --git a/Task/Zebra-puzzle/Rust/zebra-puzzle.rs b/Task/Zebra-puzzle/Rust/zebra-puzzle.rs new file mode 100644 index 0000000000..1fb799e738 --- /dev/null +++ b/Task/Zebra-puzzle/Rust/zebra-puzzle.rs @@ -0,0 +1,338 @@ +#[derive(Clone)] +enum Attrib { + Color, + Man, + Drink, + Animal, + Smoke, +} +enum Colors { + Red, + Green, + White, + Yellow, + Blue, +} +enum Humans { + English, + Swede, + Dane, + German, + Norwegian, +} +enum Drinks { + Tea, + Coffee, + Milk, + Beer, + Water, +} +#[allow(unused)] +enum Animals { + Dog, + Birds, + Cats, + Horse, + Zebra, +} +enum Smokes { + PallMall, + Dunhill, + Blend, + BlueMaster, + Prince, +} + +struct HouseNoRule { + houseno: usize, + a: Attrib, + v: i32, +} + +struct AttrPairRule { + a1: Attrib, + v1: i32, + a2: Attrib, + v2: i32, +} +impl AttrPairRule { + fn invalid(&self, ha: &Vec>, i: usize) -> bool { + let (j, k) = (self.a1.clone() as usize, self.a2.clone() as usize); + return (ha[i][j] >= 0 && ha[i][k] >= 0) + && ((ha[i][j] == self.v1 && ha[i][k] != self.v2) + || (ha[i][j] != self.v1 && ha[i][k] == self.v2)); + } +} + +struct NextToRule { + a1: Attrib, + v1: i32, + a2: Attrib, + v2: i32, +} +impl NextToRule { + fn invalid(&self, ha: &Vec>, i: usize) -> bool { + let (j, k) = (self.a1.clone() as usize, self.a2.clone() as usize); + return (ha[i][j] == self.v1) + && ((i == 0 && ha[i + 1][k] >= 0 && ha[i + 1][k] != self.v2) + || (i == ha.len() - 1 && ha[i - 1][k] != self.v2) + || (ha[i + 1][k] >= 0 && ha[i + 1][k] != self.v2 && ha[i - 1][k] != self.v2)); + } +} + +struct LeftOfRule { + a1: Attrib, + v1: i32, + a2: Attrib, + v2: i32, +} +impl LeftOfRule { + fn invalid_circ(&self, ha: &Vec>) -> bool { + let end = ha.len() - 1; + let (j, k) = (self.a1.clone() as usize, self.a2.clone() as usize); + return (ha[0][k] == self.v2) || (ha[end][j] == self.v1); + } + fn invalid(&self, ha: &Vec>, i: usize) -> bool { + let (j, k) = (self.a1.clone() as usize, self.a2.clone() as usize); + return i > 0 + && (ha[i][j] >= 0 && ha[i - 1][j] == self.v1 && ha[i][k] != self.v2 + || ha[i - 1][j] != self.v1 && ha[i][k] == self.v2); + } +} + +struct Rules<'a> { + pairs: &'a [AttrPairRule], + nexttos: &'a [NextToRule], + leftofs: &'a [LeftOfRule], +} +impl<'a> Rules<'a> { + fn invalid(&self, ha: &Vec>) -> bool { + for rule in self.leftofs { + if rule.invalid_circ(ha) { + return true; + } + } + for i in 0..ha.len() { + for rule in self.pairs { + if rule.invalid(ha, i) { + return true; + } + } + for rule in self.nexttos { + if rule.invalid(ha, i) { + return true; + } + } + for rule in self.leftofs { + if rule.invalid(ha, i) { + return true; + } + } + } + return false; + } + fn search( + &self, + used: &mut Vec>, + ha: &mut Vec>, + hno: usize, + attr: usize, + attribs: &Vec<&str>, + attr_names: &Vec>, + ) { + let end = ha.len() - 1; + let (nexthno, nextattr); + if attr < end { + nextattr = attr + 1; + nexthno = hno; + } else { + nextattr = 0; + nexthno = hno + 1; + } + if ha[hno][attr] != -1 { + self.search(used, ha, nexthno, nextattr, attribs, attr_names); + } else { + for i in 0..ha.len() { + if used[attr][i] { + continue; + } + used[attr][i] = true; + ha[hno][attr] = i as i32; + if !self.invalid(ha) { + if hno == end && attr == end { + print_houses(ha, attribs, attr_names); + } else { + self.search(used, ha, nexthno, nextattr, attribs, attr_names); + } + } + used[attr][i] = false; + } + ha[hno][attr] = -1; + } + } +} + +fn zebra_problem() { + let attribs: Vec<&str> = "Color, Man, Drink, Animal, Smoke" + .split(", ") + .into_iter() + .collect(); + let colors: Vec<&str> = "Red, Green, White, Yellow, Blue" + .split(", ") + .into_iter() + .collect(); + let humans: Vec<&str> = "English, Swede, Dane, German, Norwegian" + .split(", ") + .into_iter() + .collect(); + let drinks: Vec<&str> = "Tea, Coffee, Milk, Beer, Water" + .split(", ") + .into_iter() + .collect(); + let animals: Vec<&str> = "Dog, Birds, Cats, Horse, Zebra" + .split(", ") + .into_iter() + .collect(); + let smokes: Vec<&str> = "PallMall, Dunhill, Blend, BlueMaster, Prince" + .split(", ") + .into_iter() + .collect(); + let attr_names = vec![colors, humans, drinks, animals, smokes]; + + let housenos = [ + HouseNoRule { + houseno: 2, + a: Attrib::Drink, + v: Drinks::Milk as i32, + }, // Cond 9: In the middle house they drink milk. + HouseNoRule { + houseno: 0, + a: Attrib::Man, + v: Humans::Norwegian as i32, + }, // Cond 10: The Norwegian lives in the first house. + ]; + let ps = [ + AttrPairRule { + a1: Attrib::Man, + v1: Humans::English as i32, + a2: Attrib::Color, + v2: Colors::Red as i32, + }, // Cond 2: The English man lives in the red house. + AttrPairRule { + a1: Attrib::Man, + v1: Humans::Swede as i32, + a2: Attrib::Animal, + v2: Animals::Dog as i32, + }, // Cond 3: The Swede has a dog. + AttrPairRule { + a1: Attrib::Man, + v1: Humans::Dane as i32, + a2: Attrib::Drink, + v2: Drinks::Tea as i32, + }, // Cond 4: The Dane drinks tea. + AttrPairRule { + a1: Attrib::Color, + v1: Colors::Green as i32, + a2: Attrib::Drink, + v2: Drinks::Coffee as i32, + }, // Cond 6: drink coffee in the green house. + AttrPairRule { + a1: Attrib::Smoke, + v1: Smokes::PallMall as i32, + a2: Attrib::Animal, + v2: Animals::Birds as i32, + }, // Cond 7: The man who smokes Pall Mall has birds. + AttrPairRule { + a1: Attrib::Smoke, + v1: Smokes::Dunhill as i32, + a2: Attrib::Color, + v2: Colors::Yellow as i32, + }, // Cond 8: In the yellow house they smoke Dunhill. + AttrPairRule { + a1: Attrib::Smoke, + v1: Smokes::BlueMaster as i32, + a2: Attrib::Drink, + v2: Drinks::Beer as i32, + }, // Cond 13: The man who smokes Blue Master drinks beer. + AttrPairRule { + a1: Attrib::Man, + v1: Humans::German as i32, + a2: Attrib::Smoke, + v2: Smokes::Prince as i32, + }, // Cond 14: The German smokes Prince + ]; + let ns = [ + NextToRule { + a1: Attrib::Smoke, + v1: Smokes::Blend as i32, + a2: Attrib::Animal, + v2: Animals::Cats as i32, + }, // Cond 11: The man who smokes Blend lives in the house next to the house with cats. + NextToRule { + a1: Attrib::Smoke, + v1: Smokes::Dunhill as i32, + a2: Attrib::Animal, + v2: Animals::Horse as i32, + }, // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill. + NextToRule { + a1: Attrib::Man, + v1: Humans::Norwegian as i32, + a2: Attrib::Color, + v2: Colors::Blue as i32, + }, // Cond 15: The Norwegian lives next to the blue house. + NextToRule { + a1: Attrib::Smoke, + v1: Smokes::Blend as i32, + a2: Attrib::Drink, + v2: Drinks::Water as i32, + }, // Cond 16: They drink water in a house next to the house where they smoke Blend. + ]; + let ls = [ + LeftOfRule { + a1: Attrib::Color, + v1: Colors::Green as i32, + a2: Attrib::Color, + v2: Colors::White as i32, + }, // Cond 5: The green house is immediately to the left of the white house. + ]; + let rules = Rules { + pairs: &ps[..], + nexttos: &ns[..], + leftofs: &ls[..], + }; + + let mut used = vec![vec![false; 5]; 5]; + let mut ha = vec![vec![-1_i32; 5]; 5]; + for rule in housenos { + let (a, v) = (rule.a as usize, rule.v as usize); + ha[rule.houseno][a] = rule.v; + used[a][v] = true; + } + rules.search(&mut used, &mut ha, 0, 0, &attribs, &attr_names); +} + +fn print_houses(ha: &Vec>, attribs: &Vec<&str>, attr_names: &Vec>) { + print!("{:<10}", "House"); + for s in attribs { + print!("{:<10}", s); + } + println!(); + for i in 0..ha.len() { + print!("{:<10}", i); + for j in 0..attr_names.len() { + print!( + "{:<10}", + if ha[i][j] >= 0 { + attr_names[j][ha[i][j] as usize] + } else { + " " + } + ); + } + println!(); + } +} + +fn main() { + zebra_problem(); +} diff --git a/Task/Zebra-puzzle/Tailspin/zebra-puzzle-3.tailspin b/Task/Zebra-puzzle/Tailspin/zebra-puzzle-3.tailspin new file mode 100644 index 0000000000..d79f0793ae --- /dev/null +++ b/Task/Zebra-puzzle/Tailspin/zebra-puzzle-3.tailspin @@ -0,0 +1,103 @@ +operator (candidate overlap clue) + ({| $candidate... -> {field: $}|} matching {| $clue... -> {field: $}|}) ! +end overlap + +test 'overlap' + assert ({nationality: 'English', colour: 'red'} overlap {nationality: 'English', colour: 'red'}) -> $::count <=2> 'identity' + assert ({nationality: 'English'} overlap {nationality: 'English', colour: 'red'}) -> $::count <=1> 'partial' + assert ({} overlap {nationality: 'English', colour: 'red'}) -> $::count <=0> 'none' + assert ({nationality: 'German'} overlap {nationality: 'English', colour: 'red'}) -> $::count <=0> 'contradict' +end 'overlap' + +templates has&{house:} + def street: $; + $ -> # + // when one element already fits + when <[ $::count <=2>)>]> do $ ! + // when two different elements contain the facts required to be together + when <[ $::count <=1>)>=2]> do !VOID + // when one element contains one fact together with a contradictory fact for the other property + when <[ $::count <=1>)?(({|$|} notMatching {|$house|}) -> $::count <=1>)>]> do !VOID + // when one element can be augmented + when <[ $::count <=1>)>]> do + $ -> \[i](when $::count <=1>)> do [$street(first..~$i)..., {$, $house}, $street($i~..last)...] ! \)... ! + // otherwise create new solution for each possible element that can contain these facts + otherwise $ -> \[i](({|$|} matching {|$house|})... -> [$street(first..~$i)..., {$, $house}, $street($i~..last)...] ! \)... ! +end has + +templates follows&{left:, right:} + data + is-left $::count <=1>)>, + is-right $::count <=1>)>, + can-be-right $::count <=1>)>, + can-be-left $::count <=1>)> + local + def street: $; + $ -> # + // when the right element already follows the left + when <[(:)]> do $ ! + // when both elements exist (but implicitly not following as required) + when <[,]> do !VOID + // when the left element is followed by one that could be augmented with the right fact + when <[(:)]> do + $ -> \[i](($ overlap $left)... -> [$street(first..$i)..., {$street($i+1), $right}, $street($i+1~..last)...] ! \)... ! + // when an element that can contain the left fact is followed by an element containing the right fact + when <[(:)]> do + $ -> \[i](($ overlap $right)... -> [$street(first..~$i-1)..., {$street($i-1), $left}, $street($i..last)...] ! \)... ! + // when there is an element with either fact (and implicitly cannot be made to match the requirement) + when <[]> do !VOID + // otherwise add these facts in all possible configurations + otherwise + $street::first..~$street::last -> \( + def i: $; + ({|$street($i)|} matching {|$left|})... + -> ({|$street($i+1)|} matching {|$right|})... + -> [$street(first..~$i)..., {$street($i), $left}, {$street($i+1), $right}, $street($i+1~..last)...] ! + \) ! +end follows + +templates next-to&{a:, b:} + $ -> follows&{left: $a, right: $b} ! + $ -> follows&{left: $b, right: $a} ! +end next-to + +// There are five houses. +[1..5 -> {number: $}] +// The English man lives in the red house. +-> has&{house: {nationality: 'English', colour: 'red'}} +// The Swede has a dog. +-> has&{house: {nationality: 'Swede', pet: 'dog'}} +// The Dane drinks tea. +-> has&{house: {nationality: 'Dane', drink: 'tea'}} +// The green house is immediately to the left of the white house. +-> follows&{left: {colour: 'green'}, right: {colour: 'white'}} +// They drink coffee in the green house. +-> has&{house: {colour: 'green', drink: 'coffee'}} +// The man who smokes Pall Mall has a bird. +-> has&{house: {smoke: 'Pall Mall', pet: 'bird'}} +// In the yellow house they smoke Dunhill. +-> has&{house: {colour: 'yellow', smoke: 'Dunhill'}} +// In the middle house they drink milk. +-> has&{house: {number: 3, drink: 'milk'}} +// The Norwegian lives in the first house. +-> has&{house: {number: 1, nationality: 'Norwegian'}} +// The Blend-smoker lives in the house next to the house with a cat. +-> next-to&{a: {smoke: 'Blend'}, b: {pet: 'cat'}} +// In a house next to the house with a horse, they smoke Dunhill. +-> next-to&{a: {pet: 'horse'}, b: {smoke: 'Dunhill'}} +// The man who smokes Blue Master drinks beer. +-> has&{house: {smoke: 'Blue Master', drink: 'beer'}} +// The German smokes Prince. +-> has&{house: {nationality: 'German', smoke: 'Prince'}} +// The Norwegian lives next to the blue house. +-> next-to&{a: {nationality: 'Norwegian'}, b: {colour: 'blue'}} +// They drink water in a house next to the house where they smoke Blend. +-> next-to&{a: {drink: 'water'}, b: {smoke: 'Blend'}} +-> \( + $... -> # + $-> \[i]('$i;: $;' !\)... -> '$;$#10;' -> !OUT::write + '$#10;' -> !OUT::write + + when <{pet: VOID}> do 'The $.nationality; owns the zebra.$#10;' -> !OUT::write + \) +-> !VOID diff --git a/Task/Zeckendorf-arithmetic/FreeBASIC/zeckendorf-arithmetic.basic b/Task/Zeckendorf-arithmetic/FreeBASIC/zeckendorf-arithmetic.basic new file mode 100644 index 0000000000..5d382f1f7c --- /dev/null +++ b/Task/Zeckendorf-arithmetic/FreeBASIC/zeckendorf-arithmetic.basic @@ -0,0 +1,174 @@ +Type Zeckendorf + As Integer dLen + As Ulongint dVal + + Declare Constructor() + Declare Constructor(x As String) + Declare Sub a(n As Integer) + Declare Sub b(Pos As Integer) + Declare Sub c(Pos As Integer) + Declare Sub inc() + Declare Function suma(rhs As Zeckendorf) As Zeckendorf + Declare Function resta(rhs As Zeckendorf) As Zeckendorf + Declare Function producto(rhs As Zeckendorf) As Zeckendorf + Declare Function toString() As String +End Type + +Constructor Zeckendorf() + This.dLen = 0 + This.dVal = 0 +End Constructor + +Constructor Zeckendorf(x As String) + Dim As Ulongint q = 1 + Dim As Integer i = Len(x) - 1 + This.dLen = Int(i / 2) + This.dVal = 0 + While i >= 0 + This.dVal += (Asc(Mid(x, i+1, 1)) - Asc("0")) * q + q *= 2 + i -= 1 + Wend +End Constructor + +Sub Zeckendorf.a(n As Integer) + Dim As Integer i = n + Do + If This.dLen < i Then This.dLen = i + Dim As Integer j = (This.dVal Shr (i * 2)) And 3 + If j = 0 Or j = 1 Then Exit Sub + If j = 2 Then + If ((This.dVal Shr ((i + 1) * 2)) And 1) <> 1 Then Exit Sub + This.dVal += 1ULL Shl (i * 2 + 1) + Exit Sub + End If + If j = 3 Then + Dim As Ulongint temp = 3ULL Shl (i * 2) + temp Xor= &HFFFFFFFFFFFFFFFFULL + This.dVal And= temp + This.b((i + 1) * 2) + End If + i += 1 + Loop +End Sub + +Sub Zeckendorf.b(posic As Integer) + If posic = 0 Then + This.inc() + Exit Sub + End If + If ((This.dVal Shr posic) And 1) = 0 Then + This.dVal += 1ULL Shl posic + This.a(Int(posic / 2)) + If posic > 1 Then This.a(Int(posic / 2) - 1) + Else + Dim As Ulongint temp = 1ULL Shl posic + temp Xor= &HFFFFFFFFFFFFFFFFULL + This.dVal And= temp + This.b(posic + 1) + This.b(posic - Iif(posic > 1, 2, 1)) + End If +End Sub + +Sub Zeckendorf.c(posic As Integer) + If ((This.dVal Shr posic) And 1) = 1 Then + Dim As Ulongint temp = 1ULL Shl posic + temp Xor= &HFFFFFFFFFFFFFFFFULL + This.dVal And= temp + Exit Sub + End If + This.c(posic + 1) + If posic > 0 Then + This.b(posic - 1) + Else + This.inc() + End If +End Sub + +Sub Zeckendorf.inc() + This.dVal += 1 + This.a(0) +End Sub + +Function Zeckendorf.suma(rhs As Zeckendorf) As Zeckendorf + Dim As Zeckendorf copy = This + Dim As Ulongint rhs_dVal = rhs.dVal + Dim As Integer limit = (rhs.dLen + 1) * 2 + For gn As Integer = 0 To limit - 1 + If ((rhs_dVal Shr gn) And 1) = 1 Then copy.b(gn) + Next + Return copy +End Function + +Function Zeckendorf.resta(rhs As Zeckendorf) As Zeckendorf + Dim As Zeckendorf copy = This + Dim As Ulongint rhs_dVal = rhs.dVal + Dim As Integer limit = (rhs.dLen + 1) * 2 + For gn As Integer = 0 To limit - 1 + If ((rhs_dVal Shr gn) And 1) = 1 Then copy.c(gn) + Next + While (((copy.dVal Shr ((copy.dLen * 2) And 31)) And 3) = 0) Or (copy.dLen = 0) + copy.dLen -= 1 + Wend + Return copy +End Function + +Function Zeckendorf.producto(rhs As Zeckendorf) As Zeckendorf + Dim As Zeckendorf na = rhs, nb = rhs, nr + Dim As Ulongint dVal = This.dVal + For i As Integer = 0 To (This.dLen + 1) * 2 - 1 + If ((dVal Shr i) And 1) > 0 Then nr = nr.suma(nb) + Dim As Zeckendorf nt = nb + nb = nb.suma(na) + na = nt + Next + Return nr +End Function + +Function Zeckendorf.toString() As String + Dim As String dig(2) = {"00", "01", "10"} + Dim As String dig1(2) = {"", "1", "10"} + + If This.dVal = 0 Then Return "0" + Dim As Integer idx = (This.dVal Shr ((This.dLen * 2) And 31)) And 3 + Dim As String sb = dig1(idx) + For i As Integer = This.dLen - 1 To 0 Step -1 + idx = (This.dVal Shr (i * 2)) And 3 + sb &= dig(idx) + Next + Return sb +End Function + +' Main +Print "Addition:" +Dim As Zeckendorf g = Zeckendorf("10") +g = g.suma(Zeckendorf("10")) +Print g.toString() +g = g.suma(Zeckendorf("10")) +Print g.toString() +g = g.suma(Zeckendorf("1001")) +Print g.toString() +g = g.suma(Zeckendorf("1000")) +Print g.toString() +g = g.suma(Zeckendorf("10101")) +Print g.toString() +Print + +Print "Subtraction:" +g = Zeckendorf("1000") +g = g.resta(Zeckendorf("101")) +Print g.toString() +g = Zeckendorf("10101010") +g = g.resta(Zeckendorf("1010101")) +Print g.toString() +Print + +Print "Multiplication:" +g = Zeckendorf("1001") +g = g.producto(Zeckendorf("101")) +Print g.toString() +g = Zeckendorf("101010") +g = g.suma(Zeckendorf("101")) +Print g.toString() + +Sleep diff --git a/Task/Zeckendorf-arithmetic/Julia/zeckendorf-arithmetic.julia b/Task/Zeckendorf-arithmetic/Julia/zeckendorf-arithmetic.jl similarity index 100% rename from Task/Zeckendorf-arithmetic/Julia/zeckendorf-arithmetic.julia rename to Task/Zeckendorf-arithmetic/Julia/zeckendorf-arithmetic.jl diff --git a/Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kotlin b/Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kts similarity index 100% rename from Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kotlin rename to Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kts diff --git a/Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rust b/Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rs similarity index 100% rename from Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rust rename to Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rs diff --git a/Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-1.crystal b/Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-1.cr similarity index 100% rename from Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-1.crystal rename to Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-1.cr diff --git a/Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-2.crystal b/Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-2.cr similarity index 100% rename from Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-2.crystal rename to Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-2.cr diff --git a/Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-3.crystal b/Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-3.cr similarity index 100% rename from Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-3.crystal rename to Task/Zeckendorf-number-representation/Crystal/zeckendorf-number-representation-3.cr diff --git a/Task/Zeckendorf-number-representation/Delphi/zeckendorf-number-representation.delphi b/Task/Zeckendorf-number-representation/Delphi/zeckendorf-number-representation.pas similarity index 100% rename from Task/Zeckendorf-number-representation/Delphi/zeckendorf-number-representation.delphi rename to Task/Zeckendorf-number-representation/Delphi/zeckendorf-number-representation.pas diff --git a/Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-1.elixir b/Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-1.ex similarity index 100% rename from Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-1.elixir rename to Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-1.ex diff --git a/Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-2.elixir b/Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-2.ex similarity index 100% rename from Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-2.elixir rename to Task/Zeckendorf-number-representation/Elixir/zeckendorf-number-representation-2.ex diff --git a/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia b/Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.jl similarity index 100% rename from Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.julia rename to Task/Zeckendorf-number-representation/Julia/zeckendorf-number-representation.jl diff --git a/Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kotlin b/Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kts similarity index 100% rename from Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kotlin rename to Task/Zeckendorf-number-representation/Kotlin/zeckendorf-number-representation.kts diff --git a/Task/Zeckendorf-number-representation/OCaml/zeckendorf-number-representation.ocaml b/Task/Zeckendorf-number-representation/OCaml/zeckendorf-number-representation.ml similarity index 100% rename from Task/Zeckendorf-number-representation/OCaml/zeckendorf-number-representation.ocaml rename to Task/Zeckendorf-number-representation/OCaml/zeckendorf-number-representation.ml diff --git a/Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rust b/Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rs similarity index 100% rename from Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rust rename to Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rs diff --git a/Task/Zeckendorf-number-representation/Scheme/zeckendorf-number-representation.ss b/Task/Zeckendorf-number-representation/Scheme/zeckendorf-number-representation.scm similarity index 100% rename from Task/Zeckendorf-number-representation/Scheme/zeckendorf-number-representation.ss rename to Task/Zeckendorf-number-representation/Scheme/zeckendorf-number-representation.scm diff --git a/Task/Zero-to-the-zero-power/Crystal/zero-to-the-zero-power.crystal b/Task/Zero-to-the-zero-power/Crystal/zero-to-the-zero-power.cr similarity index 100% rename from Task/Zero-to-the-zero-power/Crystal/zero-to-the-zero-power.crystal rename to Task/Zero-to-the-zero-power/Crystal/zero-to-the-zero-power.cr diff --git a/Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.elixir b/Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.ex similarity index 100% rename from Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.elixir rename to Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.ex diff --git a/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia b/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.jl similarity index 100% rename from Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia rename to Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.jl diff --git a/Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kotlin b/Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kts similarity index 100% rename from Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kotlin rename to Task/Zero-to-the-zero-power/Kotlin/zero-to-the-zero-power.kts diff --git a/Task/Zero-to-the-zero-power/Nu/zero-to-the-zero-power.nu b/Task/Zero-to-the-zero-power/Nu/zero-to-the-zero-power.nu new file mode 100644 index 0000000000..f0fef5f5bd --- /dev/null +++ b/Task/Zero-to-the-zero-power/Nu/zero-to-the-zero-power.nu @@ -0,0 +1 @@ +0 ** 0 | print diff --git a/Task/Zero-to-the-zero-power/Pyret/zero-to-the-zero-power.pyret b/Task/Zero-to-the-zero-power/Pyret/zero-to-the-zero-power.arr similarity index 100% rename from Task/Zero-to-the-zero-power/Pyret/zero-to-the-zero-power.pyret rename to Task/Zero-to-the-zero-power/Pyret/zero-to-the-zero-power.arr diff --git a/Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rust b/Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rs similarity index 100% rename from Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rust rename to Task/Zero-to-the-zero-power/Rust/zero-to-the-zero-power.rs diff --git a/Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.ss b/Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.scm similarity index 100% rename from Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.ss rename to Task/Zero-to-the-zero-power/Scheme/zero-to-the-zero-power.scm diff --git a/Task/Zhang-Suen-thinning-algorithm/Elixir/zhang-suen-thinning-algorithm.elixir b/Task/Zhang-Suen-thinning-algorithm/Elixir/zhang-suen-thinning-algorithm.ex similarity index 100% rename from Task/Zhang-Suen-thinning-algorithm/Elixir/zhang-suen-thinning-algorithm.elixir rename to Task/Zhang-Suen-thinning-algorithm/Elixir/zhang-suen-thinning-algorithm.ex diff --git a/Task/Zhang-Suen-thinning-algorithm/Julia/zhang-suen-thinning-algorithm.julia b/Task/Zhang-Suen-thinning-algorithm/Julia/zhang-suen-thinning-algorithm.jl similarity index 100% rename from Task/Zhang-Suen-thinning-algorithm/Julia/zhang-suen-thinning-algorithm.julia rename to Task/Zhang-Suen-thinning-algorithm/Julia/zhang-suen-thinning-algorithm.jl diff --git a/Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kotlin b/Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kts similarity index 100% rename from Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kotlin rename to Task/Zhang-Suen-thinning-algorithm/Kotlin/zhang-suen-thinning-algorithm.kts diff --git a/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal b/Task/Zig-zag-matrix/Crystal/zig-zag-matrix.cr similarity index 100% rename from Task/Zig-zag-matrix/Crystal/zig-zag-matrix.crystal rename to Task/Zig-zag-matrix/Crystal/zig-zag-matrix.cr diff --git a/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi b/Task/Zig-zag-matrix/Delphi/zig-zag-matrix.pas similarity index 100% rename from Task/Zig-zag-matrix/Delphi/zig-zag-matrix.delphi rename to Task/Zig-zag-matrix/Delphi/zig-zag-matrix.pas diff --git a/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir b/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.ex similarity index 100% rename from Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir rename to Task/Zig-zag-matrix/Elixir/zig-zag-matrix.ex diff --git a/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria b/Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.ex similarity index 100% rename from Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.euphoria rename to Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.ex diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.jl diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.jl diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.jl diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.jl similarity index 100% rename from Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.julia rename to Task/Zig-zag-matrix/Julia/zig-zag-matrix-4.jl diff --git a/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin b/Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kts similarity index 100% rename from Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kotlin rename to Task/Zig-zag-matrix/Kotlin/zig-zag-matrix.kts diff --git a/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml b/Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ml similarity index 100% rename from Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ocaml rename to Task/Zig-zag-matrix/OCaml/zig-zag-matrix.ml diff --git a/Task/Zig-zag-matrix/Rust/zig-zag-matrix.rust b/Task/Zig-zag-matrix/Rust/zig-zag-matrix.rs similarity index 100% rename from Task/Zig-zag-matrix/Rust/zig-zag-matrix.rust rename to Task/Zig-zag-matrix/Rust/zig-zag-matrix.rs diff --git a/Task/Zumkeller-numbers/FreeBASIC/zumkeller-numbers.basic b/Task/Zumkeller-numbers/FreeBASIC/zumkeller-numbers.basic new file mode 100644 index 0000000000..86bd18ebfb --- /dev/null +++ b/Task/Zumkeller-numbers/FreeBASIC/zumkeller-numbers.basic @@ -0,0 +1,96 @@ +' Function to get divisors of a number +Sub getDivisors(n As Integer, divs() As Integer) + Redim divs(1) + divs(0) = 1 + divs(1) = n + Dim As Integer i = 2, j + While i * i <= n + If n Mod i = 0 Then + j = n \ i + Redim Preserve divs(Ubound(divs) + 1) + divs(Ubound(divs)) = i + If i <> j Then + Redim Preserve divs(Ubound(divs) + 1) + divs(Ubound(divs)) = j + End If + End If + i += 1 + Wend +End Sub + +' Function to check if a sum can be formed by a subset of divisors +Function isPartSum(divs() As Integer, sum As Integer) As Boolean + If sum = 0 Then Return True + + Dim le As Integer = Ubound(divs) + 1 + If le = 0 Then Return False + + Dim last As Integer = divs(le - 1) + Dim newDivs(le - 2) As Integer + For i As Integer = 0 To le - 2 + newDivs(i) = divs(i) + Next + If last > sum Then Return isPartSum(newDivs(), sum) + + Return isPartSum(newDivs(), sum) Orelse isPartSum(newDivs(), sum - last) +End Function + +' Function to check if a number is a Zumkeller number +Function isZumkeller(n As Integer) As Boolean + Dim divs() As Integer + getDivisors(n, divs()) + Dim sum As Integer = 0 + For i As Integer = 0 To Ubound(divs) + sum += divs(i) + Next + ' if sum is odd can't be split into two partitions with equal sums + If sum Mod 2 = 1 Then Return False + ' if n is odd use 'abundant odd number' optimization + If n Mod 2 = 1 Then + Dim abundance As Integer = sum - 2 * n + Return abundance > 0 Andalso abundance Mod 2 = 0 + End If + ' if n and sum are both even check if there's a partition which totals sum / 2 + Return isPartSum(divs(), sum \ 2) +End Function + +Sub main() + Print "The first 220 Zumkeller numbers are:" + Dim As Integer i = 2 + Dim As Integer cnt = 0 + While cnt < 220 + If isZumkeller(i) Then + Print Using "### "; i; + cnt += 1 + If cnt Mod 20 = 0 Then Print + End If + i += 1 + Wend + + Print !"\nThe first 40 odd Zumkeller numbers are:" + i = 3 + cnt = 0 + While cnt < 40 + If isZumkeller(i) Then + Print Using "##### "; i; + cnt += 1 + If cnt Mod 10 = 0 Then Print + End If + i += 2 + Wend + + Print !"\nThe first 40 odd Zumkeller numbers which don't end in 5 are:" + i = 3 + cnt = 0 + While cnt < 40 + If i Mod 10 <> 5 Andalso isZumkeller(i) Then + Print Using "####### "; i; + cnt += 1 + If cnt Mod 8 = 0 Then Print + End If + i += 2 + Wend +End Sub + +main() +Sleep diff --git a/Task/Zumkeller-numbers/Julia/zumkeller-numbers.julia b/Task/Zumkeller-numbers/Julia/zumkeller-numbers.jl similarity index 100% rename from Task/Zumkeller-numbers/Julia/zumkeller-numbers.julia rename to Task/Zumkeller-numbers/Julia/zumkeller-numbers.jl diff --git a/Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kotlin b/Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kts similarity index 100% rename from Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kotlin rename to Task/Zumkeller-numbers/Kotlin/zumkeller-numbers.kts diff --git a/Task/Zumkeller-numbers/Rust/zumkeller-numbers.rust b/Task/Zumkeller-numbers/Rust/zumkeller-numbers.rs similarity index 100% rename from Task/Zumkeller-numbers/Rust/zumkeller-numbers.rust rename to Task/Zumkeller-numbers/Rust/zumkeller-numbers.rs From 157b70a8103c3631677d57858f84b0146faeceb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Mon, 4 Nov 2024 20:28:54 -0800 Subject: [PATCH 04/12] Data update --- Lang/AArch64-Assembly/Conways-Game-of-Life | 1 + Lang/ALGOL-68/Biorhythms | 1 + ...bers-indexing-permutations-of-a-collection | 1 + Lang/ALGOL-68/LU-decomposition | 1 + Lang/ALGOL-68/Mayan-numerals | 1 + Lang/ALGOL-68/Subtractive-generator | 1 + Lang/ALGOL-68/Vogels-approximation-method | 1 + Lang/AWK/Vampire-number | 1 + Lang/Ada/Babylonian-spiral | 1 + Lang/BQN/Dutch-national-flag-problem | 1 + Lang/EasyLang/Mayan-numerals | 1 + Lang/EasyLang/Vogels-approximation-method | 1 + Lang/Fish/00-LANG.txt | 3 +- Lang/FreeBASIC/15-puzzle-solver | 1 + Lang/FreeBASIC/Brace-expansion | 1 + Lang/FreeBASIC/Chat-server | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + .../Display-an-outline-as-a-nested-table | 1 + Lang/FreeBASIC/Echo-server | 1 + ...bers-indexing-permutations-of-a-collection | 1 + Lang/FreeBASIC/Hello-world-Web-server | 1 + Lang/FreeBASIC/History-variables | 1 + Lang/FreeBASIC/Intersecting-number-wheels | 1 + Lang/FreeBASIC/Jaro-Winkler-distance | 1 + Lang/FreeBASIC/K-d-tree | 1 + Lang/FreeBASIC/LU-decomposition | 1 + Lang/FreeBASIC/Mayan-calendar | 1 + Lang/FreeBASIC/P-value-correction | 1 + Lang/FreeBASIC/Parse-an-IP-Address | 1 + .../FreeBASIC/Parsing-RPN-to-infix-conversion | 1 + .../FreeBASIC/Parsing-Shunting-yard-algorithm | 1 + Lang/FreeBASIC/QR-decomposition | 1 + .../Rosetta-Code-Find-bare-lang-tags | 1 + Lang/FreeBASIC/SOAP | 1 + Lang/FreeBASIC/Stable-marriage-problem | 1 + Lang/FreeBASIC/State-name-puzzle | 1 + Lang/FreeBASIC/Strassens-algorithm | 1 + Lang/FreeBASIC/Summarize-and-say-sequence | 1 + Lang/FreeBASIC/Tarjan | 1 + Lang/FreeBASIC/Universal-Turing-machine | 1 + ...y-distribution-uniformity-Chi-squared-test | 1 + Lang/FreeBASIC/Vogels-approximation-method | 1 + .../Wasteful-equidigital-and-frugal-numbers | 1 + Lang/FutureBasic/15-puzzle-solver | 1 + Lang/FutureBasic/Amb | 1 + Lang/FutureBasic/Anonymous-recursion | 1 + Lang/FutureBasic/Arithmetic-geometric-mean | 1 + Lang/FutureBasic/Averages-Mean-angle | 1 + Lang/FutureBasic/Averages-Root-mean-square | 1 + Lang/FutureBasic/Barnsley-fern | 1 + Lang/FutureBasic/Binary-search | 1 + Lang/FutureBasic/Bitmap-B-zier-curves-Cubic | 1 + Lang/FutureBasic/Blum-integer | 1 + Lang/FutureBasic/Box-the-compass | 1 + Lang/FutureBasic/Caesar-cipher | 1 + Lang/FutureBasic/Catamorphism | 1 + Lang/FutureBasic/Chinese-zodiac | 1 + Lang/FutureBasic/Compile-time-calculation | 1 + ...tors-whose-factors-are-all-substrings-of-k | 1 + .../FutureBasic/Cumulative-standard-deviation | 1 + ...ne-if-a-string-has-all-the-same-characters | 1 + Lang/FutureBasic/Dutch-national-flag-problem | 1 + Lang/FutureBasic/Equilibrium-index | 1 + .../Evaluate-binomial-coefficients | 1 + Lang/FutureBasic/Exceptions | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/FutureBasic/Flow-control-structures | 1 + Lang/FutureBasic/Forward-difference | 1 + Lang/FutureBasic/Function-composition | 1 + Lang/FutureBasic/Fusc-sequence | 1 + Lang/FutureBasic/Host-introspection | 1 + Lang/FutureBasic/ISBN13-check-digit | 1 + Lang/FutureBasic/JortSort | 1 + Lang/FutureBasic/Josephus-problem | 1 + Lang/FutureBasic/Last-Friday-of-each-month | 1 + Lang/FutureBasic/Least-common-multiple | 1 + .../Long-literals-with-continuations | 1 + Lang/FutureBasic/Long-year | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + ...m-multiple-of-m-where-digital-sum-equals-m | 1 + Lang/FutureBasic/Munching-squares | 1 + Lang/FutureBasic/Nim-game | 1 + Lang/FutureBasic/Nth | 1 + Lang/FutureBasic/Own-digits-power-sum | 1 + Lang/FutureBasic/Palindrome-dates | 1 + Lang/FutureBasic/Pascals-triangle-Puzzle | 1 + Lang/FutureBasic/Pinstripe-Display | 1 + Lang/FutureBasic/Playing-cards | 1 + Lang/FutureBasic/Regular-expressions | 1 + Lang/FutureBasic/Search-a-list-of-records | 1 + Lang/FutureBasic/Sierpinski-triangle | 1 + .../Sort-an-array-of-composite-structures | 1 + .../Sort-numbers-lexicographically | 1 + Lang/FutureBasic/Spinning-rod-animation-Text | 1 + Lang/FutureBasic/Square-but-not-cube | 1 + Lang/FutureBasic/Stack | 1 + Lang/FutureBasic/Sudan-function | 1 + Lang/FutureBasic/Sum-digits-of-an-integer | 1 + Lang/FutureBasic/Temperature-conversion | 1 + .../Terminal-control-Clear-the-screen | 1 + Lang/FutureBasic/The-Name-Game | 1 + Lang/FutureBasic/User-input-Text | 1 + Lang/GW-BASIC/Colour-pinstripe-Display | 1 + Lang/GW-BASIC/Pinstripe-Display | 1 + Lang/Isabelle/Bernoulli-numbers | 1 + Lang/Isabelle/Catalan-numbers | 1 + Lang/Jq/Strassens-algorithm | 1 + Lang/LSL/00-LANG.txt | 33 +- Lang/LSL/Binary-digits | 1 + Lang/M2000-Interpreter/00-LANG.txt | 34 +- .../Associative-array-Merging | 1 + Lang/M2000-Interpreter/Averages-Mean-angle | 1 + Lang/M2000-Interpreter/Babylonian-spiral | 1 + Lang/M2000-Interpreter/Bernoulli-numbers | 1 + Lang/M2000-Interpreter/Chinese-zodiac | 1 + .../Factors-of-a-Mersenne-number | 1 + .../Find-the-last-Sunday-of-each-month | 1 + Lang/M2000-Interpreter/K-d-tree | 1 + .../Old-lady-swallowed-a-fly | 1 + Lang/M2000-Interpreter/Password-generator | 1 + Lang/M2000-Interpreter/Problem-of-Apollonius | 1 + .../M2000-Interpreter/Stable-marriage-problem | 1 + Lang/M2000-Interpreter/Statistics-Basic | 1 + .../Statistics-Normal-distribution | 1 + Lang/MSX-Basic/Colour-pinstripe-Display | 1 + Lang/MSX-Basic/Pinstripe-Display | 1 + ...rs-whose-neighboring-pairs-are-tetraprimes | 1 + Lang/Miranda/Fractran | 1 + Lang/OxygenBasic/Loops-Continue | 1 + Lang/PascalABC.NET/Emirp-primes | 1 + Lang/PascalABC.NET/Evolutionary-algorithm | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/PascalABC.NET/Execute-a-system-command | 1 + Lang/PascalABC.NET/Exponentiation-order | 1 + ...nfix-operators-in-or-operating-on-the-base | 1 + Lang/PascalABC.NET/Extend-your-language | 1 + Lang/PascalABC.NET/Extensible-prime-generator | 1 + Lang/PascalABC.NET/Factorial-primes | 1 + Lang/PascalABC.NET/Factorions | 1 + .../Factors-of-a-Mersenne-number | 1 + .../Fairshare-between-two-and-more | 1 + Lang/PascalABC.NET/Farey-sequence | 1 + .../Feigenbaum-constant-calculation | 1 + Lang/PascalABC.NET/Fermat-numbers | 1 + Lang/PascalABC.NET/Fibonacci-word | 1 + Lang/PascalABC.NET/Fibonacci-word-fractal | 1 + Lang/PascalABC.NET/Five-weekends | 1 + Lang/Pike/Execute-Brain- | 1 + Lang/Plain-English/00-LANG.txt | 56 +-- Lang/QB64/Averages-Mean-angle | 1 + Lang/QB64/Intersecting-number-wheels | 1 + Lang/QB64/Mayan-calendar | 1 + Lang/QBasic/Averages-Mean-angle | 1 + Lang/QBasic/Loops-Continue | 1 + Lang/QBasic/Pinstripe-Display | 1 + Lang/REXX/Goldbachs-comet | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/Refal/Fractran | 1 + Lang/Refal/Sierpinski-triangle | 1 + Lang/Rust/Almkvist-Giullera-formula-for-pi | 1 + Lang/Rust/Biorhythms | 1 + Lang/Rust/Stern-Brocot-sequence | 1 + Lang/Rust/Subleq | 1 + Lang/Rust/Tropical-algebra-overloading | 1 + Lang/Rust/Vogels-approximation-method | 1 + ...mine-if-a-string-has-all-unique-characters | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/SETL/Fractran | 1 + Lang/SETL/Mayan-numerals | 1 + Lang/SETL/Range-consolidation | 1 + Lang/Standard-ML/Averages-Mean-angle | 1 + .../Averages-Simple-moving-average | 1 + Lang/V-(Vlang)/00-LANG.txt | 54 +-- .../Find-the-last-Sunday-of-each-month | 1 + Lang/V-(Vlang)/Monads-List-monad | 1 + Lang/V-(Vlang)/Pascals-triangle | 1 + Lang/V-(Vlang)/Probabilistic-choice | 1 + ...rate-English-text-using-the-Greek-alphabet | 1 + Lang/V-(Vlang)/Word-frequency | 1 + Lang/Visual-Basic-.NET/Execute-Brain- | 1 + Lang/XPL0/Count-the-coins | 1 + Lang/XPL0/Currency | 1 + Lang/XPL0/Gaussian-elimination | 1 + Lang/XPL0/IBAN | 1 + Lang/XPL0/Left-factorials | 1 + Lang/XPL0/Long-primes | 1 + Lang/XPL0/Modified-random-distribution | 1 + Lang/XPL0/Sierpinski-square-curve | 1 + Lang/XPL0/Subtractive-generator | 1 + Lang/XPL0/Thieles-interpolation-formula | 1 + Lang/XPL0/World-Cup-group-stage | 1 + Lang/Yabasic/Averages-Mean-angle | 1 + Task/100-doors/00-TASK.txt | 5 + Task/100-doors/Plain-English/100-doors.plain | 1 + Task/100-doors/YAMLScript/100-doors.ys | 25 +- .../FreeBASIC/15-puzzle-solver.basic | 288 ++++++++++++++ .../FutureBasic/15-puzzle-solver.basic | 165 ++++++++ Task/24-game/ALGOL-68/24-game.alg | 10 +- .../YAMLScript/99-bottles-of-beer-1.ys | 1 - Task/ABC-problem/ALGOL-68/abc-problem.alg | 47 +-- .../Phix/aks-test-for-primes-1.phix | 78 ++++ .../Phix/aks-test-for-primes-2.phix | 27 ++ .../Phix/aks-test-for-primes-3.phix | 24 ++ .../Phix/aks-test-for-primes.phix | 82 ---- .../REXX/aks-test-for-primes-3.rexx | 85 ++-- .../V-(Vlang)/aks-test-for-primes.v | 29 +- .../accumulator-factory.m2000 | 63 +-- .../REXX/additive-primes-2.rexx | 13 +- .../almkvist-giullera-formula-for-pi.alg | 14 +- .../Rust/almkvist-giullera-formula-for-pi.rs | 89 +++++ Task/Almost-prime/REXX/almost-prime-3.rexx | 1 + Task/Amb/FutureBasic/amb.basic | 26 ++ Task/Anagrams/V-(Vlang)/anagrams.v | 18 +- .../FutureBasic/anonymous-recursion.basic | 11 + .../Jq/anonymous-recursion-2.jq | 12 +- .../Jq/anonymous-recursion-3.jq | 8 + .../anonymous-recursion-1.m2000 | 6 - .../anonymous-recursion-2.m2000 | 11 - .../anonymous-recursion-3.m2000 | 23 -- .../anonymous-recursion-4.m2000 | 24 -- .../anonymous-recursion.m2000 | 4 + Task/Anti-primes/ALGOL-68/anti-primes.alg | 3 +- Task/Anti-primes/REXX/anti-primes-3.rexx | 1 + ...ital-filter-direct-form-ii-transposed-.alg | 35 +- ...tal-filter-direct-form-ii-transposed-.phix | 38 +- ...bitrary-precision-integers-included-.refal | 17 + ...rbitrary-precision-integers-included-.setl | 8 + .../Standard-ML/arithmetic-complex.ml | 27 +- .../arithmetic-geometric-mean.basic | 12 + ...numbers.rexx => arithmetic-numbers-1.rexx} | 2 +- .../REXX/arithmetic-numbers-2.rexx | 76 ++++ Task/Arrays/FutureBasic/arrays.basic | 42 +- .../associative-array-creation.basic | 8 +- .../associative-array-merging.m2000 | 33 ++ .../FutureBasic/averages-mean-angle.basic | 14 + .../averages-mean-angle.m2000 | 52 +++ .../QB64/averages-mean-angle.qb64 | 34 ++ .../QBasic/averages-mean-angle.basic | 55 +++ .../Standard-ML/averages-mean-angle.ml | 34 ++ .../Yabasic/averages-mean-angle.basic | 30 ++ .../averages-root-mean-square.basic | 19 + .../averages-simple-moving-average.ml | 32 ++ .../Ada/babylonian-spiral.ada | 136 +++++++ .../M2000-Interpreter/babylonian-spiral.m2000 | 80 ++++ .../FutureBasic/barnsley-fern.basic | 34 ++ .../Isabelle/bernoulli-numbers-1.isabelle | 373 ++++++++++++++++++ .../Isabelle/bernoulli-numbers-2.isabelle | 45 +++ .../M2000-Interpreter/bernoulli-numbers.m2000 | 96 +++++ Task/Binary-digits/LSL/binary-digits.lsl | 75 ++++ .../FutureBasic/binary-search-1.basic | 27 ++ .../FutureBasic/binary-search-2.basic | 28 ++ .../ALGOL-68/bioinformatics-base-count.alg | 112 +++--- Task/Biorhythms/ALGOL-68/biorhythms.alg | 76 ++++ Task/Biorhythms/FutureBasic/biorhythms.basic | 2 +- .../M2000-Interpreter/biorhythms.m2000 | 2 +- Task/Biorhythms/Rust/biorhythms.rs | 63 +++ .../bitmap-b-zier-curves-cubic.basic | 31 ++ .../FutureBasic/blum-integer.basic | 47 +++ .../FutureBasic/box-the-compass.basic | 32 ++ .../FreeBASIC/brace-expansion.basic | 134 +++++++ Task/CSV-data-manipulation/00-TASK.txt | 4 +- .../FutureBasic/caesar-cipher.basic | 42 ++ ...f-e.rs => calculating-the-value-of-e-1.rs} | 0 .../Rust/calculating-the-value-of-e-2.rs | 36 ++ .../ALGOL-68/calkin-wilf-sequence.alg | 14 +- .../ALGOL-68/camel-case-and-snake-case.alg | 4 +- .../carmichael-3-strong-pseudoprimes-2.rexx | 6 +- .../Isabelle/catalan-numbers-1.isabelle | 125 ++++++ .../Isabelle/catalan-numbers-2.isabelle | 6 + .../FutureBasic/catamorphism.basic | 25 ++ Task/Chat-server/FreeBASIC/chat-server.basic | 122 ++++++ .../FutureBasic/chinese-zodiac.basic | 21 + .../M2000-Interpreter/chinese-zodiac.m2000 | 17 + .../ALGOL-68/circular-primes.alg | 4 +- .../REXX/circular-primes-2.rexx | 9 +- .../ALGOL-68/cistercian-numerals.alg | 29 +- .../ALGOL-68/colorful-numbers.alg | 2 +- .../GW-BASIC/colour-pinstripe-display.basic | 16 + .../MSX-Basic/colour-pinstripe-display.basic | 15 + .../QBasic/colour-pinstripe-display.basic | 2 +- .../compare-length-of-two-strings.alg | 8 +- .../compile-time-calculation.basic | 3 + ...hose-factors-are-all-substrings-of-k.basic | 68 ++++ ...ascending-or-descending-differences-2.rexx | 48 +-- ...thmetic-construct-from-rational-number.alg | 24 +- ...ic-g-matrix-ng-continued-fraction-n-.basic | 126 ++++++ .../conways-game-of-life.aarch64 | 262 ++++++++++++ .../REXX/count-in-factors-3.rexx | 1 + .../count-occurrences-of-a-substring.alg | 6 +- Task/Count-the-coins/Jq/count-the-coins.jq | 6 +- .../Count-the-coins/XPL0/count-the-coins.xpl0 | 15 + Task/Cuban-primes/REXX/cuban-primes-2.rexx | 2 +- .../Cumulative-standard-deviation/00-TASK.txt | 2 +- .../cumulative-standard-deviation-1.alg | 6 +- .../cumulative-standard-deviation-2.alg | 31 +- .../cumulative-standard-deviation.basic | 19 + Task/Currency/XPL0/currency.xpl0 | 44 +++ .../ALGOL-68/curzon-numbers.alg | 10 +- .../REXX/cyclops-numbers-2.rexx | 8 +- ...a-string-has-all-the-same-characters.basic | 30 ++ ...f-a-string-has-all-unique-characters.basic | 50 +++ .../ALGOL-68/discordian-date.alg | 8 +- ...display-an-outline-as-a-nested-table.basic | 166 ++++++++ .../BQN/dutch-national-flag-problem.bqn | 5 + .../dutch-national-flag-problem.basic | 43 ++ .../ALGOL-68/dynamic-variable-names.alg | 11 +- Task/Echo-server/FreeBASIC/echo-server.basic | 80 ++++ .../elementary-cellular-automaton.alg | 9 +- .../PascalABC.NET/emirp-primes.pas | 57 +++ Task/Emirp-primes/REXX/emirp-primes-3.rexx | 22 +- .../equal-prime-and-composite-sums.alg | 50 +-- .../FutureBasic/equilibrium-index.basic | 27 ++ .../ALGOL-68/esthetic-numbers.alg | 56 +-- .../evaluate-binomial-coefficients.basic | 16 + .../PascalABC.NET/evolutionary-algorithm.pas | 24 ++ ...an-exception-thrown-in-a-nested-call.basic | 33 ++ ...h-an-exception-thrown-in-a-nested-call.pas | 26 ++ .../Exceptions/FutureBasic/exceptions-1.basic | 29 ++ .../Exceptions/FutureBasic/exceptions-2.basic | 15 + .../ALGOL-68/execute-brain--1.alg | 9 +- Task/Execute-Brain-/Pike/execute-brain-.pike | 39 ++ .../Visual-Basic-.NET/execute-brain-.vb | 70 ++++ .../execute-a-system-command.pas | 2 + .../PascalABC.NET/exponentiation-order.pas | 4 + ...-operators-in-or-operating-on-the-base.pas | 6 + .../extend-your-language.m2000 | 2 +- .../PascalABC.NET/extend-your-language.pas | 24 ++ .../extensible-prime-generator.pas | 42 ++ Task/FASTA-format/ALGOL-68/fasta-format.alg | 13 +- ...-indexing-permutations-of-a-collection.alg | 130 ++++++ ...ndexing-permutations-of-a-collection.basic | 167 ++++++++ .../PascalABC.NET/factorial-primes.pas | 42 ++ Task/Factorions/Jq/factorions.jq | 2 +- Task/Factorions/PascalABC.NET/factorions.pas | 22 ++ .../factors-of-a-mersenne-number.m2000 | 41 ++ .../factors-of-a-mersenne-number.pas | 36 ++ .../REXX/factors-of-a-mersenne-number-2.rexx | 14 +- .../fairshare-between-two-and-more.pas | 22 ++ .../ALGOL-68/farey-sequence.alg | 2 +- .../PascalABC.NET/farey-sequence.pas | 20 + .../feigenbaum-constant-calculation.pas | 27 ++ .../ALGOL-68/fermat-numbers.alg | 2 +- .../PascalABC.NET/fermat-numbers.pas | 35 ++ .../PascalABC.NET/fibonacci-word-fractal.pas | 32 ++ .../ALGOL-68/fibonacci-word.alg | 38 +- .../PascalABC.NET/fibonacci-word.pas | 37 ++ .../FutureBasic/file-input-output.basic | 2 - .../find-the-last-sunday-of-each-month.alg | 27 +- .../find-the-last-sunday-of-each-month.m2000 | 23 ++ .../find-the-last-sunday-of-each-month.v | 24 ++ ...-square-in-base-n-with-n-unique-digits.alg | 4 +- Task/Five-weekends/Jq/five-weekends-1.jq | 2 +- .../PascalABC.NET/five-weekends.pas | 27 ++ Task/FizzBuzz/YAMLScript/fizzbuzz.ys | 42 +- .../FutureBasic/flow-control-structures.basic | 21 + .../ALGOL-68/floyd-warshall-algorithm.alg | 28 +- .../YAMLScript/floyds-triangle.ys | 2 +- .../REXX/fortunate-numbers-2.rexx | 3 +- .../FutureBasic/forward-difference.basic | 26 ++ Task/Fractran/ALGOL-68/fractran.alg | 53 +-- Task/Fractran/Miranda/fractran.miranda | 80 ++++ Task/Fractran/REXX/fractran-3.rexx | 4 +- Task/Fractran/Refal/fractran.refal | 78 ++++ Task/Fractran/SETL/fractran.setl | 52 +++ .../FutureBasic/function-composition.basic | 14 + ...tion.basic => function-definition-1.basic} | 0 .../FutureBasic/function-definition-2.basic | 8 + .../FutureBasic/function-prototype.basic | 1 + .../FutureBasic/fusc-sequence.basic | 40 ++ .../Gamma-function/REXX/gamma-function-3.rexx | 6 +- .../ALGOL-68/gapful-numbers.alg | 4 +- .../gauss-jordan-matrix-inversion.alg | 25 +- .../XPL0/gaussian-elimination.xpl0 | 43 ++ .../ALGOL-68/general-fizzbuzz.alg | 20 +- Task/Generic-swap/Jq/generic-swap-1.jq | 2 +- Task/Generic-swap/Jq/generic-swap-4.jq | 1 + .../M2000-Interpreter/generic-swap-3.m2000 | 19 + .../Goldbachs-comet/REXX/goldbachs-comet.rexx | 57 +++ ...reedy-algorithm-for-egyptian-fractions.alg | 10 +- .../Scheme/hailstone-sequence.scm | 24 +- .../REXX/hamming-numbers-4.rexx | 73 ++++ .../ALGOL-68/harmonic-series.alg | 8 +- .../CBASIC/harmonic-series.basic | 2 +- Task/Hello-world-Text/C/hello-world-text-1.c | 9 +- Task/Hello-world-Text/C/hello-world-text-2.c | 8 +- Task/Hello-world-Text/C/hello-world-text-3.c | 9 +- Task/Hello-world-Text/C/hello-world-text-4.c | 8 +- .../FreeBASIC/hello-world-web-server.basic | 76 ++++ .../FreeBASIC/history-variables.basic | 60 +++ .../Phix/history-variables-1.phix | 24 +- .../Phix/history-variables-2.phix | 32 +- .../Phix/history-variables-3.phix | 15 +- .../{home-primes.rexx => home-primes-1.rexx} | 0 Task/Home-primes/REXX/home-primes-2.rexx | 40 ++ .../FutureBasic/host-introspection.basic | 32 ++ ...ble-numbers.rexx => humble-numbers-1.rexx} | 0 .../Humble-numbers/REXX/humble-numbers-2.rexx | 86 ++++ Task/IBAN/XPL0/iban.xpl0 | 60 +++ .../FutureBasic/isbn13-check-digit.basic | 21 + .../Jq/integer-comparison-1.jq | 2 +- .../intersecting-number-wheels.basic | 103 +++++ .../QB64/intersecting-number-wheels.qb64 | 108 +++++ Task/JSON/Standard-ML/json-1.ml | 148 ++----- Task/JSON/Standard-ML/json-2.ml | 147 +++++-- Task/JSON/Standard-ML/json-3.ml | 29 ++ .../FreeBASIC/jaro-winkler-distance.basic | 128 ++++++ Task/JortSort/FutureBasic/jortsort.basic | 8 + .../FutureBasic/josephus-problem.basic | 13 + .../Phix/josephus-problem-1.phix | 16 - .../Phix/josephus-problem-2.phix | 17 - .../Phix/josephus-problem-3.phix | 11 - .../Phix/josephus-problem-4.phix | 25 -- .../Phix/josephus-problem-5.phix | 13 - .../Phix/josephus-problem-6.phix | 5 - .../Phix/josephus-problem-7.phix | 9 - .../Phix/josephus-problem-8.phix | 13 - .../Phix/josephus-problem-9.phix | 69 ---- .../Phix/josephus-problem.phix | 201 ++++++++++ Task/K-d-tree/FreeBASIC/k-d-tree.basic | 194 +++++++++ .../K-d-tree/M2000-Interpreter/k-d-tree.m2000 | 166 ++++++++ .../kernighans-large-earthquake-problem.alg | 2 +- .../ALGOL-68/knuth-shuffle-2.alg | 6 - ...{knuth-shuffle-1.alg => knuth-shuffle.alg} | 6 + .../ALGOL-68/lu-decomposition.alg | 112 ++++++ .../FreeBASIC/lu-decomposition.basic | 100 +++++ .../ALGOL-68/last-friday-of-each-month.alg | 27 +- .../last-friday-of-each-month.basic | 41 ++ .../last-friday-of-each-month.m2000 | 41 +- .../V-(Vlang)/last-friday-of-each-month.v | 26 +- .../FutureBasic/least-common-multiple.basic | 9 + Task/Left-factorials/Jq/left-factorials-1.jq | 15 + .../Left-factorials/XPL0/left-factorials.xpl0 | 45 +++ .../V-(Vlang)/letter-frequency.v | 5 +- .../M2000-Interpreter/literals-integer.m2000 | 13 +- .../long-literals-with-continuations.basic | 31 ++ Task/Long-primes/ALGOL-68/long-primes.alg | 2 +- Task/Long-primes/XPL0/long-primes.xpl0 | 64 +++ Task/Long-year/FutureBasic/long-year.basic | 11 + .../V-(Vlang)/longest-common-substring.v | 7 +- .../OxygenBasic/loops-continue.basic | 15 + .../QBasic/loops-continue.basic | 6 + .../{loops-for.basic => loops-for-1.basic} | 0 Task/Loops-For/FutureBasic/loops-for-2.basic | 10 + .../Plain-English/loops-foreach.plain | 46 +-- ...ncrement-loop-index-within-loop-body.basic | 23 ++ .../ALGOL-68/loops-wrong-ranges.alg | 10 +- .../REXX/m-bius-function-2.rexx | 1 + .../V-(Vlang)/mac-vendor-lookup.v | 12 +- .../ALGOL-68/magnanimous-numbers.alg | 33 +- .../FreeBASIC/mayan-calendar.basic | 99 +++++ Task/Mayan-calendar/QB64/mayan-calendar.qb64 | 113 ++++++ .../ALGOL-68/mayan-numerals.alg | 68 ++++ .../EasyLang/mayan-numerals.easy | 68 ++++ Task/Mayan-numerals/SETL/mayan-numerals.setl | 38 ++ .../REXX/meissel-mertens-constant.rexx | 2 +- .../ALGOL-68/mertens-function.alg | 6 +- ...iple-of-m-where-digital-sum-equals-m.basic | 30 ++ .../ALGOL-68/modified-random-distribution.alg | 6 +- .../XPL0/modified-random-distribution.xpl0 | 39 ++ .../V-(Vlang)/monads-list-monad.v | 27 ++ .../ALGOL-68/multiple-regression.alg | 44 +-- .../FutureBasic/munching-squares.basic | 53 +++ .../ALGOL-68/n-queens-problem.alg | 31 +- .../Tailspin/n-queens-problem-3.tailspin | 4 +- .../Tailspin/n-queens-problem-4.tailspin | 52 +++ Task/Nim-game/FutureBasic/nim-game.basic | 30 ++ Task/Nth/ALGOL-68/nth.alg | 19 +- Task/Nth/FutureBasic/nth.basic | 28 ++ .../old-lady-swallowed-a-fly.m2000 | 33 ++ .../FutureBasic/own-digits-power-sum.basic | 20 + .../FreeBASIC/p-value-correction.basic | 301 ++++++++++++++ .../padovan-n-step-number-sequences.alg | 6 +- .../FutureBasic/palindrome-dates.basic | 30 ++ .../BASIC/palindrome-detection.basic | 2 +- Task/Pancake-numbers/00-TASK.txt | 2 +- ...ancake-numbers.rs => pancake-numbers-1.rs} | 0 .../Pancake-numbers/Rust/pancake-numbers-2.rs | 45 +++ .../FreeBASIC/parse-an-ip-address.basic | 175 ++++++++ .../parsing-rpn-calculator-algorithm.alg | 16 +- .../parsing-rpn-to-infix-conversion.basic | 117 ++++++ .../parsing-rpn-to-infix-conversion.m2000 | 1 - .../parsing-shunting-yard-algorithm.basic | 121 ++++++ .../partition-an-integer-x-into-n-primes.alg | 10 +- .../FutureBasic/pascals-triangle-puzzle.basic | 29 ++ .../Haskell/pascals-triangle-10.hs | 5 + .../Haskell/pascals-triangle-11.hs | 11 + .../Haskell/pascals-triangle-6.hs | 5 +- .../Haskell/pascals-triangle-7.hs | 3 +- .../Haskell/pascals-triangle-8.hs | 9 +- .../Haskell/pascals-triangle-9.hs | 13 +- .../Phix/pascals-triangle.phix | 81 +++- .../V-(Vlang)/pascals-triangle.v | 16 + .../password-generator-1.m2000 | 71 ++++ .../password-generator-2.m2000 | 72 ++++ ...generator.pas => password-generator-1.pas} | 0 .../Pascal/password-generator-2.pas | 143 +++++++ .../ALGOL-68/percolation-mean-run-density.alg | 2 +- .../ALGOL-68/periodic-table.alg | 2 +- .../Jq/permutations-derangements-3.jq | 1 - .../ALGOL-68/pierpont-primes.alg | 40 +- .../FutureBasic/pinstripe-display.basic | 12 + .../GW-BASIC/pinstripe-display.basic | 17 + .../MSX-Basic/pinstripe-display.basic | 16 + .../QBasic/pinstripe-display.basic | 14 + .../FutureBasic/playing-cards.basic | 58 +++ .../ALGOL-68/polynomial-long-division.alg | 18 +- .../REXX/prime-decomposition-4.rexx | 45 ++- ...hose-neighboring-pairs-are-tetraprimes.alg | 6 +- ...ose-neighboring-pairs-are-tetraprimes.math | 54 +++ .../REXX/primorial-numbers-2.rexx | 1 + .../V-(Vlang)/probabilistic-choice.v | 26 ++ .../ALGOL-68/problem-of-apollonius.alg | 23 +- .../problem-of-apollonius.m2000 | 65 +++ ...do-random-numbers-middle-square-method.alg | 8 +- .../FreeBASIC/qr-decomposition.basic | 206 ++++++++++ .../Java/qr-decomposition-5.java | 3 +- .../ALGOL-68/quickselect-algorithm.alg | 28 +- .../ALGOL-68/rpg-attributes-generator.alg | 41 +- .../REXX/radical-of-an-integer-2.rexx | 19 +- .../ALGOL-68/random-latin-squares.alg | 5 +- .../ALGOL-68/range-consolidation.alg | 9 +- .../SETL/range-consolidation.setl | 43 ++ .../ALGOL-68/ranking-methods.alg | 1 - Task/Rare-numbers/ALGOL-68/rare-numbers.alg | 10 +- .../FutureBasic/regular-expressions.basic | 20 + .../regular-expressions.m2000 | 2 +- Task/Repeat/ALGOL-68/repeat.alg | 24 +- .../rosetta-code-find-bare-lang-tags.basic | 166 ++++++++ Task/SOAP/FreeBASIC/soap.basic | 88 +++++ .../search-a-list-of-records.basic | 50 +++ Task/Semiprime/REXX/semiprime-4.rexx | 23 +- .../XPL0/sierpinski-arrowhead-curve.xpl0 | 2 +- .../XPL0/sierpinski-square-curve.xpl0 | 28 ++ ...triangle.awk => sierpinski-triangle-1.awk} | 0 .../AWK/sierpinski-triangle-2.awk | 9 + .../FutureBasic/sierpinski-triangle.basic | 21 + .../Refal/sierpinski-triangle.refal | 43 ++ .../CBASIC/sieve-of-eratosthenes.basic | 5 +- .../ALGOL-68/sisyphus-sequence.alg | 9 +- .../ALGOL-68/sleeping-beauty-problem.alg | 2 +- ...2^m-is-composite-for-all-m-less-than-k.alg | 2 +- Task/Sockets/FreeBASIC/sockets.basic | 111 +++--- ...ort-an-array-of-composite-structures.basic | 23 ++ ...ort-an-array-of-composite-structures.m2000 | 125 +++--- .../sort-numbers-lexicographically.basic | 10 + .../Phix/sort-using-a-custom-comparator.phix | 21 +- .../sorting-algorithms-circle-sort.alg | 6 +- .../ALGOL-68/spelling-of-ordinal-numbers.alg | 2 + .../ALGOL-68/spinning-rod-animation-text.alg | 2 +- .../spinning-rod-animation-text.basic | 12 + .../FutureBasic/square-but-not-cube.basic | 23 ++ .../ALGOL-68/square-form-factorization.alg | 6 +- .../FreeBASIC/stable-marriage-problem.basic | 84 ++++ .../stable-marriage-problem.m2000 | 95 +++++ Task/Stack/FutureBasic/stack.basic | 29 ++ .../FreeBASIC/state-name-puzzle.basic | 108 +++++ .../ALGOL-68/statistics-basic.alg | 1 - .../M2000-Interpreter/statistics-basic.m2000 | 38 ++ .../statistics-normal-distribution.m2000 | 51 +++ .../Rust/stern-brocot-sequence.rs | 38 ++ .../FreeBASIC/strassens-algorithm.basic | 204 ++++++++++ .../Jq/strassens-algorithm.jq | 113 ++++++ ...matching.m2000 => string-matching-1.m2000} | 0 .../M2000-Interpreter/string-matching-2.m2000 | 15 + ...hitespace-from-a-string-top-and-tail-1.alg | 11 +- ...hitespace-from-a-string-top-and-tail-2.alg | 2 +- Task/Subleq/Phix/subleq.phix | 42 +- Task/Subleq/Rust/subleq.rs | 46 +++ .../ALGOL-68/substitution-cipher.alg | 2 +- .../ALGOL-68/subtractive-generator.alg | 37 ++ .../XPL0/subtractive-generator.xpl0 | 41 ++ .../FutureBasic/sudan-function.basic | 8 + .../ALGOL-68/sum-digits-of-an-integer-1.alg | 6 +- .../sum-digits-of-an-integer.basic | 14 + .../ALGOL-68/sum-of-a-series.alg | 11 +- .../summarize-and-say-sequence.basic | 90 +++++ Task/Tarjan/FreeBASIC/tarjan.basic | 131 ++++++ .../FutureBasic/temperature-conversion.basic | 42 ++ .../terminal-control-clear-the-screen.basic | 1 + .../FutureBasic/the-name-game.basic | 36 ++ .../XPL0/thieles-interpolation-formula.xpl0 | 56 +++ .../REXX/totient-function-3.rexx | 1 + ...te-english-text-using-the-greek-alphabet.v | 34 ++ .../ALGOL-68/tropical-algebra-overloading.alg | 10 +- .../Rust/tropical-algebra-overloading.rs | 57 +++ Task/Twin-primes/Ada/twin-primes.ada | 258 ++++++------ Task/UPC/ALGOL-68/upc.alg | 10 +- Task/URL-decoding/V-(Vlang)/url-decoding.v | 2 +- Task/URL-encoding/Julia/url-encoding.jl | 3 +- .../ALGOL-68/ulam-spiral-for-primes-.alg | 12 +- .../FreeBASIC/universal-turing-machine.basic | 154 ++++++++ Task/User-input-Text/00-TASK.txt | 5 + .../FutureBasic/user-input-text.basic | 14 + Task/Vampire-number/AWK/vampire-number.awk | 19 + .../M2000-Interpreter/vector-products.m2000 | 132 +++---- ...ribution-uniformity-chi-squared-test.basic | 99 +++++ .../ALGOL-68/vogels-approximation-method.alg | 100 +++++ .../EasyLang/vogels-approximation-method.easy | 103 +++++ .../vogels-approximation-method.basic | 127 ++++++ .../Rust/vogels-approximation-method.rs | 117 ++++++ ...teful-equidigital-and-frugal-numbers.basic | 104 +++++ .../Word-frequency/V-(Vlang)/word-frequency.v | 25 ++ .../XPL0/world-cup-group-stage.xpl0 | 77 ++++ Task/Y-combinator/Elm/y-combinator.elm | 10 +- 604 files changed, 14253 insertions(+), 2100 deletions(-) create mode 120000 Lang/AArch64-Assembly/Conways-Game-of-Life create mode 120000 Lang/ALGOL-68/Biorhythms create mode 120000 Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection create mode 120000 Lang/ALGOL-68/LU-decomposition create mode 120000 Lang/ALGOL-68/Mayan-numerals create mode 120000 Lang/ALGOL-68/Subtractive-generator create mode 120000 Lang/ALGOL-68/Vogels-approximation-method create mode 120000 Lang/AWK/Vampire-number create mode 120000 Lang/Ada/Babylonian-spiral create mode 120000 Lang/BQN/Dutch-national-flag-problem create mode 120000 Lang/EasyLang/Mayan-numerals create mode 120000 Lang/EasyLang/Vogels-approximation-method create mode 120000 Lang/FreeBASIC/15-puzzle-solver create mode 120000 Lang/FreeBASIC/Brace-expansion create mode 120000 Lang/FreeBASIC/Chat-server create mode 120000 Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/FreeBASIC/Display-an-outline-as-a-nested-table create mode 120000 Lang/FreeBASIC/Echo-server create mode 120000 Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection create mode 120000 Lang/FreeBASIC/Hello-world-Web-server create mode 120000 Lang/FreeBASIC/History-variables create mode 120000 Lang/FreeBASIC/Intersecting-number-wheels create mode 120000 Lang/FreeBASIC/Jaro-Winkler-distance create mode 120000 Lang/FreeBASIC/K-d-tree create mode 120000 Lang/FreeBASIC/LU-decomposition create mode 120000 Lang/FreeBASIC/Mayan-calendar create mode 120000 Lang/FreeBASIC/P-value-correction create mode 120000 Lang/FreeBASIC/Parse-an-IP-Address create mode 120000 Lang/FreeBASIC/Parsing-RPN-to-infix-conversion create mode 120000 Lang/FreeBASIC/Parsing-Shunting-yard-algorithm create mode 120000 Lang/FreeBASIC/QR-decomposition create mode 120000 Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags create mode 120000 Lang/FreeBASIC/SOAP create mode 120000 Lang/FreeBASIC/Stable-marriage-problem create mode 120000 Lang/FreeBASIC/State-name-puzzle create mode 120000 Lang/FreeBASIC/Strassens-algorithm create mode 120000 Lang/FreeBASIC/Summarize-and-say-sequence create mode 120000 Lang/FreeBASIC/Tarjan create mode 120000 Lang/FreeBASIC/Universal-Turing-machine create mode 120000 Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test create mode 120000 Lang/FreeBASIC/Vogels-approximation-method create mode 120000 Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers create mode 120000 Lang/FutureBasic/15-puzzle-solver create mode 120000 Lang/FutureBasic/Amb create mode 120000 Lang/FutureBasic/Anonymous-recursion create mode 120000 Lang/FutureBasic/Arithmetic-geometric-mean create mode 120000 Lang/FutureBasic/Averages-Mean-angle create mode 120000 Lang/FutureBasic/Averages-Root-mean-square create mode 120000 Lang/FutureBasic/Barnsley-fern create mode 120000 Lang/FutureBasic/Binary-search create mode 120000 Lang/FutureBasic/Bitmap-B-zier-curves-Cubic create mode 120000 Lang/FutureBasic/Blum-integer create mode 120000 Lang/FutureBasic/Box-the-compass create mode 120000 Lang/FutureBasic/Caesar-cipher create mode 120000 Lang/FutureBasic/Catamorphism create mode 120000 Lang/FutureBasic/Chinese-zodiac create mode 120000 Lang/FutureBasic/Compile-time-calculation create mode 120000 Lang/FutureBasic/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k create mode 120000 Lang/FutureBasic/Cumulative-standard-deviation create mode 120000 Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters create mode 120000 Lang/FutureBasic/Dutch-national-flag-problem create mode 120000 Lang/FutureBasic/Equilibrium-index create mode 120000 Lang/FutureBasic/Evaluate-binomial-coefficients create mode 120000 Lang/FutureBasic/Exceptions create mode 120000 Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/FutureBasic/Flow-control-structures create mode 120000 Lang/FutureBasic/Forward-difference create mode 120000 Lang/FutureBasic/Function-composition create mode 120000 Lang/FutureBasic/Fusc-sequence create mode 120000 Lang/FutureBasic/Host-introspection create mode 120000 Lang/FutureBasic/ISBN13-check-digit create mode 120000 Lang/FutureBasic/JortSort create mode 120000 Lang/FutureBasic/Josephus-problem create mode 120000 Lang/FutureBasic/Last-Friday-of-each-month create mode 120000 Lang/FutureBasic/Least-common-multiple create mode 120000 Lang/FutureBasic/Long-literals-with-continuations create mode 120000 Lang/FutureBasic/Long-year create mode 120000 Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m create mode 120000 Lang/FutureBasic/Munching-squares create mode 120000 Lang/FutureBasic/Nim-game create mode 120000 Lang/FutureBasic/Nth create mode 120000 Lang/FutureBasic/Own-digits-power-sum create mode 120000 Lang/FutureBasic/Palindrome-dates create mode 120000 Lang/FutureBasic/Pascals-triangle-Puzzle create mode 120000 Lang/FutureBasic/Pinstripe-Display create mode 120000 Lang/FutureBasic/Playing-cards create mode 120000 Lang/FutureBasic/Regular-expressions create mode 120000 Lang/FutureBasic/Search-a-list-of-records create mode 120000 Lang/FutureBasic/Sierpinski-triangle create mode 120000 Lang/FutureBasic/Sort-an-array-of-composite-structures create mode 120000 Lang/FutureBasic/Sort-numbers-lexicographically create mode 120000 Lang/FutureBasic/Spinning-rod-animation-Text create mode 120000 Lang/FutureBasic/Square-but-not-cube create mode 120000 Lang/FutureBasic/Stack create mode 120000 Lang/FutureBasic/Sudan-function create mode 120000 Lang/FutureBasic/Sum-digits-of-an-integer create mode 120000 Lang/FutureBasic/Temperature-conversion create mode 120000 Lang/FutureBasic/Terminal-control-Clear-the-screen create mode 120000 Lang/FutureBasic/The-Name-Game create mode 120000 Lang/FutureBasic/User-input-Text create mode 120000 Lang/GW-BASIC/Colour-pinstripe-Display create mode 120000 Lang/GW-BASIC/Pinstripe-Display create mode 120000 Lang/Isabelle/Bernoulli-numbers create mode 120000 Lang/Isabelle/Catalan-numbers create mode 120000 Lang/Jq/Strassens-algorithm create mode 120000 Lang/LSL/Binary-digits create mode 120000 Lang/M2000-Interpreter/Associative-array-Merging create mode 120000 Lang/M2000-Interpreter/Averages-Mean-angle create mode 120000 Lang/M2000-Interpreter/Babylonian-spiral create mode 120000 Lang/M2000-Interpreter/Bernoulli-numbers create mode 120000 Lang/M2000-Interpreter/Chinese-zodiac create mode 120000 Lang/M2000-Interpreter/Factors-of-a-Mersenne-number create mode 120000 Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month create mode 120000 Lang/M2000-Interpreter/K-d-tree create mode 120000 Lang/M2000-Interpreter/Old-lady-swallowed-a-fly create mode 120000 Lang/M2000-Interpreter/Password-generator create mode 120000 Lang/M2000-Interpreter/Problem-of-Apollonius create mode 120000 Lang/M2000-Interpreter/Stable-marriage-problem create mode 120000 Lang/M2000-Interpreter/Statistics-Basic create mode 120000 Lang/M2000-Interpreter/Statistics-Normal-distribution create mode 120000 Lang/MSX-Basic/Colour-pinstripe-Display create mode 120000 Lang/MSX-Basic/Pinstripe-Display create mode 120000 Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes create mode 120000 Lang/Miranda/Fractran create mode 120000 Lang/OxygenBasic/Loops-Continue create mode 120000 Lang/PascalABC.NET/Emirp-primes create mode 120000 Lang/PascalABC.NET/Evolutionary-algorithm create mode 120000 Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/PascalABC.NET/Execute-a-system-command create mode 120000 Lang/PascalABC.NET/Exponentiation-order create mode 120000 Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base create mode 120000 Lang/PascalABC.NET/Extend-your-language create mode 120000 Lang/PascalABC.NET/Extensible-prime-generator create mode 120000 Lang/PascalABC.NET/Factorial-primes create mode 120000 Lang/PascalABC.NET/Factorions create mode 120000 Lang/PascalABC.NET/Factors-of-a-Mersenne-number create mode 120000 Lang/PascalABC.NET/Fairshare-between-two-and-more create mode 120000 Lang/PascalABC.NET/Farey-sequence create mode 120000 Lang/PascalABC.NET/Feigenbaum-constant-calculation create mode 120000 Lang/PascalABC.NET/Fermat-numbers create mode 120000 Lang/PascalABC.NET/Fibonacci-word create mode 120000 Lang/PascalABC.NET/Fibonacci-word-fractal create mode 120000 Lang/PascalABC.NET/Five-weekends create mode 120000 Lang/Pike/Execute-Brain- create mode 120000 Lang/QB64/Averages-Mean-angle create mode 120000 Lang/QB64/Intersecting-number-wheels create mode 120000 Lang/QB64/Mayan-calendar create mode 120000 Lang/QBasic/Averages-Mean-angle create mode 120000 Lang/QBasic/Loops-Continue create mode 120000 Lang/QBasic/Pinstripe-Display create mode 120000 Lang/REXX/Goldbachs-comet create mode 120000 Lang/Refal/Arbitrary-precision-integers-included- create mode 120000 Lang/Refal/Fractran create mode 120000 Lang/Refal/Sierpinski-triangle create mode 120000 Lang/Rust/Almkvist-Giullera-formula-for-pi create mode 120000 Lang/Rust/Biorhythms create mode 120000 Lang/Rust/Stern-Brocot-sequence create mode 120000 Lang/Rust/Subleq create mode 120000 Lang/Rust/Tropical-algebra-overloading create mode 120000 Lang/Rust/Vogels-approximation-method create mode 120000 Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters create mode 120000 Lang/SETL/Arbitrary-precision-integers-included- create mode 120000 Lang/SETL/Fractran create mode 120000 Lang/SETL/Mayan-numerals create mode 120000 Lang/SETL/Range-consolidation create mode 120000 Lang/Standard-ML/Averages-Mean-angle create mode 120000 Lang/Standard-ML/Averages-Simple-moving-average create mode 120000 Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month create mode 120000 Lang/V-(Vlang)/Monads-List-monad create mode 120000 Lang/V-(Vlang)/Pascals-triangle create mode 120000 Lang/V-(Vlang)/Probabilistic-choice create mode 120000 Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet create mode 120000 Lang/V-(Vlang)/Word-frequency create mode 120000 Lang/Visual-Basic-.NET/Execute-Brain- create mode 120000 Lang/XPL0/Count-the-coins create mode 120000 Lang/XPL0/Currency create mode 120000 Lang/XPL0/Gaussian-elimination create mode 120000 Lang/XPL0/IBAN create mode 120000 Lang/XPL0/Left-factorials create mode 120000 Lang/XPL0/Long-primes create mode 120000 Lang/XPL0/Modified-random-distribution create mode 120000 Lang/XPL0/Sierpinski-square-curve create mode 120000 Lang/XPL0/Subtractive-generator create mode 120000 Lang/XPL0/Thieles-interpolation-formula create mode 120000 Lang/XPL0/World-Cup-group-stage create mode 120000 Lang/Yabasic/Averages-Mean-angle create mode 100644 Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic create mode 100644 Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic create mode 100644 Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix create mode 100644 Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix create mode 100644 Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix delete mode 100644 Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix create mode 100644 Task/Almkvist-Giullera-formula-for-pi/Rust/almkvist-giullera-formula-for-pi.rs create mode 100644 Task/Amb/FutureBasic/amb.basic create mode 100644 Task/Anonymous-recursion/FutureBasic/anonymous-recursion.basic create mode 100644 Task/Anonymous-recursion/Jq/anonymous-recursion-3.jq delete mode 100644 Task/Anonymous-recursion/M2000-Interpreter/anonymous-recursion-1.m2000 delete mode 100644 Task/Anonymous-recursion/M2000-Interpreter/anonymous-recursion-2.m2000 delete mode 100644 Task/Anonymous-recursion/M2000-Interpreter/anonymous-recursion-3.m2000 delete mode 100644 Task/Anonymous-recursion/M2000-Interpreter/anonymous-recursion-4.m2000 create mode 100644 Task/Anonymous-recursion/M2000-Interpreter/anonymous-recursion.m2000 create mode 100644 Task/Arbitrary-precision-integers-included-/Refal/arbitrary-precision-integers-included-.refal create mode 100644 Task/Arbitrary-precision-integers-included-/SETL/arbitrary-precision-integers-included-.setl create mode 100644 Task/Arithmetic-geometric-mean/FutureBasic/arithmetic-geometric-mean.basic rename Task/Arithmetic-numbers/REXX/{arithmetic-numbers.rexx => arithmetic-numbers-1.rexx} (97%) create mode 100644 Task/Arithmetic-numbers/REXX/arithmetic-numbers-2.rexx create mode 100644 Task/Associative-array-Merging/M2000-Interpreter/associative-array-merging.m2000 create mode 100644 Task/Averages-Mean-angle/FutureBasic/averages-mean-angle.basic create mode 100644 Task/Averages-Mean-angle/M2000-Interpreter/averages-mean-angle.m2000 create mode 100644 Task/Averages-Mean-angle/QB64/averages-mean-angle.qb64 create mode 100644 Task/Averages-Mean-angle/QBasic/averages-mean-angle.basic create mode 100644 Task/Averages-Mean-angle/Standard-ML/averages-mean-angle.ml create mode 100644 Task/Averages-Mean-angle/Yabasic/averages-mean-angle.basic create mode 100644 Task/Averages-Root-mean-square/FutureBasic/averages-root-mean-square.basic create mode 100644 Task/Averages-Simple-moving-average/Standard-ML/averages-simple-moving-average.ml create mode 100644 Task/Babylonian-spiral/Ada/babylonian-spiral.ada create mode 100644 Task/Babylonian-spiral/M2000-Interpreter/babylonian-spiral.m2000 create mode 100644 Task/Barnsley-fern/FutureBasic/barnsley-fern.basic create mode 100644 Task/Bernoulli-numbers/Isabelle/bernoulli-numbers-1.isabelle create mode 100644 Task/Bernoulli-numbers/Isabelle/bernoulli-numbers-2.isabelle create mode 100644 Task/Bernoulli-numbers/M2000-Interpreter/bernoulli-numbers.m2000 create mode 100644 Task/Binary-digits/LSL/binary-digits.lsl create mode 100644 Task/Binary-search/FutureBasic/binary-search-1.basic create mode 100644 Task/Binary-search/FutureBasic/binary-search-2.basic create mode 100644 Task/Biorhythms/ALGOL-68/biorhythms.alg create mode 100644 Task/Biorhythms/Rust/biorhythms.rs create mode 100644 Task/Bitmap-B-zier-curves-Cubic/FutureBasic/bitmap-b-zier-curves-cubic.basic create mode 100644 Task/Blum-integer/FutureBasic/blum-integer.basic create mode 100644 Task/Box-the-compass/FutureBasic/box-the-compass.basic create mode 100644 Task/Brace-expansion/FreeBASIC/brace-expansion.basic create mode 100644 Task/Caesar-cipher/FutureBasic/caesar-cipher.basic rename Task/Calculating-the-value-of-e/Rust/{calculating-the-value-of-e.rs => calculating-the-value-of-e-1.rs} (100%) create mode 100644 Task/Calculating-the-value-of-e/Rust/calculating-the-value-of-e-2.rs create mode 100644 Task/Catalan-numbers/Isabelle/catalan-numbers-1.isabelle create mode 100644 Task/Catalan-numbers/Isabelle/catalan-numbers-2.isabelle create mode 100644 Task/Catamorphism/FutureBasic/catamorphism.basic create mode 100644 Task/Chat-server/FreeBASIC/chat-server.basic create mode 100644 Task/Chinese-zodiac/FutureBasic/chinese-zodiac.basic create mode 100644 Task/Chinese-zodiac/M2000-Interpreter/chinese-zodiac.m2000 create mode 100644 Task/Colour-pinstripe-Display/GW-BASIC/colour-pinstripe-display.basic create mode 100644 Task/Colour-pinstripe-Display/MSX-Basic/colour-pinstripe-display.basic create mode 100644 Task/Compile-time-calculation/FutureBasic/compile-time-calculation.basic create mode 100644 Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/FutureBasic/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.basic create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/FreeBASIC/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.basic create mode 100644 Task/Conways-Game-of-Life/AArch64-Assembly/conways-game-of-life.aarch64 create mode 100644 Task/Count-the-coins/XPL0/count-the-coins.xpl0 create mode 100644 Task/Cumulative-standard-deviation/FutureBasic/cumulative-standard-deviation.basic create mode 100644 Task/Currency/XPL0/currency.xpl0 create mode 100644 Task/Determine-if-a-string-has-all-the-same-characters/FutureBasic/determine-if-a-string-has-all-the-same-characters.basic create mode 100644 Task/Determine-if-a-string-has-all-unique-characters/S-BASIC/determine-if-a-string-has-all-unique-characters.basic create mode 100644 Task/Display-an-outline-as-a-nested-table/FreeBASIC/display-an-outline-as-a-nested-table.basic create mode 100644 Task/Dutch-national-flag-problem/BQN/dutch-national-flag-problem.bqn create mode 100644 Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic create mode 100644 Task/Echo-server/FreeBASIC/echo-server.basic create mode 100644 Task/Emirp-primes/PascalABC.NET/emirp-primes.pas create mode 100644 Task/Equilibrium-index/FutureBasic/equilibrium-index.basic create mode 100644 Task/Evaluate-binomial-coefficients/FutureBasic/evaluate-binomial-coefficients.basic create mode 100644 Task/Evolutionary-algorithm/PascalABC.NET/evolutionary-algorithm.pas create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/FutureBasic/exceptions-catch-an-exception-thrown-in-a-nested-call.basic create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/PascalABC.NET/exceptions-catch-an-exception-thrown-in-a-nested-call.pas create mode 100644 Task/Exceptions/FutureBasic/exceptions-1.basic create mode 100644 Task/Exceptions/FutureBasic/exceptions-2.basic create mode 100644 Task/Execute-Brain-/Pike/execute-brain-.pike create mode 100644 Task/Execute-Brain-/Visual-Basic-.NET/execute-brain-.vb create mode 100644 Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas create mode 100644 Task/Exponentiation-order/PascalABC.NET/exponentiation-order.pas create mode 100644 Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/PascalABC.NET/exponentiation-with-infix-operators-in-or-operating-on-the-base.pas create mode 100644 Task/Extend-your-language/PascalABC.NET/extend-your-language.pas create mode 100644 Task/Extensible-prime-generator/PascalABC.NET/extensible-prime-generator.pas create mode 100644 Task/Factorial-base-numbers-indexing-permutations-of-a-collection/ALGOL-68/factorial-base-numbers-indexing-permutations-of-a-collection.alg create mode 100644 Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic create mode 100644 Task/Factorial-primes/PascalABC.NET/factorial-primes.pas create mode 100644 Task/Factorions/PascalABC.NET/factorions.pas create mode 100644 Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 create mode 100644 Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas create mode 100644 Task/Fairshare-between-two-and-more/PascalABC.NET/fairshare-between-two-and-more.pas create mode 100644 Task/Farey-sequence/PascalABC.NET/farey-sequence.pas create mode 100644 Task/Feigenbaum-constant-calculation/PascalABC.NET/feigenbaum-constant-calculation.pas create mode 100644 Task/Fermat-numbers/PascalABC.NET/fermat-numbers.pas create mode 100644 Task/Fibonacci-word-fractal/PascalABC.NET/fibonacci-word-fractal.pas create mode 100644 Task/Fibonacci-word/PascalABC.NET/fibonacci-word.pas create mode 100644 Task/Find-the-last-Sunday-of-each-month/M2000-Interpreter/find-the-last-sunday-of-each-month.m2000 create mode 100644 Task/Find-the-last-Sunday-of-each-month/V-(Vlang)/find-the-last-sunday-of-each-month.v create mode 100644 Task/Five-weekends/PascalABC.NET/five-weekends.pas create mode 100644 Task/Flow-control-structures/FutureBasic/flow-control-structures.basic create mode 100644 Task/Forward-difference/FutureBasic/forward-difference.basic create mode 100644 Task/Fractran/Miranda/fractran.miranda create mode 100644 Task/Fractran/Refal/fractran.refal create mode 100644 Task/Fractran/SETL/fractran.setl create mode 100644 Task/Function-composition/FutureBasic/function-composition.basic rename Task/Function-definition/FutureBasic/{function-definition.basic => function-definition-1.basic} (100%) create mode 100644 Task/Function-definition/FutureBasic/function-definition-2.basic create mode 100644 Task/Fusc-sequence/FutureBasic/fusc-sequence.basic create mode 100644 Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 create mode 100644 Task/Generic-swap/Jq/generic-swap-4.jq create mode 100644 Task/Generic-swap/M2000-Interpreter/generic-swap-3.m2000 create mode 100644 Task/Goldbachs-comet/REXX/goldbachs-comet.rexx create mode 100644 Task/Hamming-numbers/REXX/hamming-numbers-4.rexx create mode 100644 Task/Hello-world-Web-server/FreeBASIC/hello-world-web-server.basic create mode 100644 Task/History-variables/FreeBASIC/history-variables.basic rename Task/Home-primes/REXX/{home-primes.rexx => home-primes-1.rexx} (100%) create mode 100644 Task/Home-primes/REXX/home-primes-2.rexx create mode 100644 Task/Host-introspection/FutureBasic/host-introspection.basic rename Task/Humble-numbers/REXX/{humble-numbers.rexx => humble-numbers-1.rexx} (100%) create mode 100644 Task/Humble-numbers/REXX/humble-numbers-2.rexx create mode 100644 Task/IBAN/XPL0/iban.xpl0 create mode 100644 Task/ISBN13-check-digit/FutureBasic/isbn13-check-digit.basic create mode 100644 Task/Intersecting-number-wheels/FreeBASIC/intersecting-number-wheels.basic create mode 100644 Task/Intersecting-number-wheels/QB64/intersecting-number-wheels.qb64 create mode 100644 Task/JSON/Standard-ML/json-3.ml create mode 100644 Task/Jaro-Winkler-distance/FreeBASIC/jaro-winkler-distance.basic create mode 100644 Task/JortSort/FutureBasic/jortsort.basic create mode 100644 Task/Josephus-problem/FutureBasic/josephus-problem.basic delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-1.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-2.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-3.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-4.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-5.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-6.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-7.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-8.phix delete mode 100644 Task/Josephus-problem/Phix/josephus-problem-9.phix create mode 100644 Task/Josephus-problem/Phix/josephus-problem.phix create mode 100644 Task/K-d-tree/FreeBASIC/k-d-tree.basic create mode 100644 Task/K-d-tree/M2000-Interpreter/k-d-tree.m2000 delete mode 100644 Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-2.alg rename Task/Knuth-shuffle/ALGOL-68/{knuth-shuffle-1.alg => knuth-shuffle.alg} (69%) create mode 100644 Task/LU-decomposition/ALGOL-68/lu-decomposition.alg create mode 100644 Task/LU-decomposition/FreeBASIC/lu-decomposition.basic create mode 100644 Task/Last-Friday-of-each-month/FutureBasic/last-friday-of-each-month.basic create mode 100644 Task/Least-common-multiple/FutureBasic/least-common-multiple.basic create mode 100644 Task/Left-factorials/XPL0/left-factorials.xpl0 create mode 100644 Task/Long-literals-with-continuations/FutureBasic/long-literals-with-continuations.basic create mode 100644 Task/Long-primes/XPL0/long-primes.xpl0 create mode 100644 Task/Long-year/FutureBasic/long-year.basic create mode 100644 Task/Loops-Continue/OxygenBasic/loops-continue.basic create mode 100644 Task/Loops-Continue/QBasic/loops-continue.basic rename Task/Loops-For/FutureBasic/{loops-for.basic => loops-for-1.basic} (100%) create mode 100644 Task/Loops-For/FutureBasic/loops-for-2.basic create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/FutureBasic/loops-increment-loop-index-within-loop-body.basic create mode 100644 Task/Mayan-calendar/FreeBASIC/mayan-calendar.basic create mode 100644 Task/Mayan-calendar/QB64/mayan-calendar.qb64 create mode 100644 Task/Mayan-numerals/ALGOL-68/mayan-numerals.alg create mode 100644 Task/Mayan-numerals/EasyLang/mayan-numerals.easy create mode 100644 Task/Mayan-numerals/SETL/mayan-numerals.setl create mode 100644 Task/Minimum-multiple-of-m-where-digital-sum-equals-m/FutureBasic/minimum-multiple-of-m-where-digital-sum-equals-m.basic create mode 100644 Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 create mode 100644 Task/Monads-List-monad/V-(Vlang)/monads-list-monad.v create mode 100644 Task/Munching-squares/FutureBasic/munching-squares.basic create mode 100644 Task/N-queens-problem/Tailspin/n-queens-problem-4.tailspin create mode 100644 Task/Nim-game/FutureBasic/nim-game.basic create mode 100644 Task/Nth/FutureBasic/nth.basic create mode 100644 Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 create mode 100644 Task/Own-digits-power-sum/FutureBasic/own-digits-power-sum.basic create mode 100644 Task/P-value-correction/FreeBASIC/p-value-correction.basic create mode 100644 Task/Palindrome-dates/FutureBasic/palindrome-dates.basic rename Task/Pancake-numbers/Rust/{pancake-numbers.rs => pancake-numbers-1.rs} (100%) create mode 100644 Task/Pancake-numbers/Rust/pancake-numbers-2.rs create mode 100644 Task/Parse-an-IP-Address/FreeBASIC/parse-an-ip-address.basic create mode 100644 Task/Parsing-RPN-to-infix-conversion/FreeBASIC/parsing-rpn-to-infix-conversion.basic create mode 100644 Task/Parsing-Shunting-yard-algorithm/FreeBASIC/parsing-shunting-yard-algorithm.basic create mode 100644 Task/Pascals-triangle-Puzzle/FutureBasic/pascals-triangle-puzzle.basic create mode 100644 Task/Pascals-triangle/Haskell/pascals-triangle-10.hs create mode 100644 Task/Pascals-triangle/Haskell/pascals-triangle-11.hs create mode 100644 Task/Pascals-triangle/V-(Vlang)/pascals-triangle.v create mode 100644 Task/Password-generator/M2000-Interpreter/password-generator-1.m2000 create mode 100644 Task/Password-generator/M2000-Interpreter/password-generator-2.m2000 rename Task/Password-generator/Pascal/{password-generator.pas => password-generator-1.pas} (100%) create mode 100644 Task/Password-generator/Pascal/password-generator-2.pas create mode 100644 Task/Pinstripe-Display/FutureBasic/pinstripe-display.basic create mode 100644 Task/Pinstripe-Display/GW-BASIC/pinstripe-display.basic create mode 100644 Task/Pinstripe-Display/MSX-Basic/pinstripe-display.basic create mode 100644 Task/Pinstripe-Display/QBasic/pinstripe-display.basic create mode 100644 Task/Playing-cards/FutureBasic/playing-cards.basic create mode 100644 Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Mathematica/prime-numbers-whose-neighboring-pairs-are-tetraprimes.math create mode 100644 Task/Probabilistic-choice/V-(Vlang)/probabilistic-choice.v create mode 100644 Task/Problem-of-Apollonius/M2000-Interpreter/problem-of-apollonius.m2000 create mode 100644 Task/QR-decomposition/FreeBASIC/qr-decomposition.basic create mode 100644 Task/Range-consolidation/SETL/range-consolidation.setl create mode 100644 Task/Regular-expressions/FutureBasic/regular-expressions.basic create mode 100644 Task/Rosetta-Code-Find-bare-lang-tags/FreeBASIC/rosetta-code-find-bare-lang-tags.basic create mode 100644 Task/SOAP/FreeBASIC/soap.basic create mode 100644 Task/Search-a-list-of-records/FutureBasic/search-a-list-of-records.basic create mode 100644 Task/Sierpinski-square-curve/XPL0/sierpinski-square-curve.xpl0 rename Task/Sierpinski-triangle/AWK/{sierpinski-triangle.awk => sierpinski-triangle-1.awk} (100%) create mode 100644 Task/Sierpinski-triangle/AWK/sierpinski-triangle-2.awk create mode 100644 Task/Sierpinski-triangle/FutureBasic/sierpinski-triangle.basic create mode 100644 Task/Sierpinski-triangle/Refal/sierpinski-triangle.refal create mode 100644 Task/Sort-an-array-of-composite-structures/FutureBasic/sort-an-array-of-composite-structures.basic create mode 100644 Task/Sort-numbers-lexicographically/FutureBasic/sort-numbers-lexicographically.basic create mode 100644 Task/Spinning-rod-animation-Text/FutureBasic/spinning-rod-animation-text.basic create mode 100644 Task/Square-but-not-cube/FutureBasic/square-but-not-cube.basic create mode 100644 Task/Stable-marriage-problem/FreeBASIC/stable-marriage-problem.basic create mode 100644 Task/Stable-marriage-problem/M2000-Interpreter/stable-marriage-problem.m2000 create mode 100644 Task/Stack/FutureBasic/stack.basic create mode 100644 Task/State-name-puzzle/FreeBASIC/state-name-puzzle.basic create mode 100644 Task/Statistics-Basic/M2000-Interpreter/statistics-basic.m2000 create mode 100644 Task/Statistics-Normal-distribution/M2000-Interpreter/statistics-normal-distribution.m2000 create mode 100644 Task/Stern-Brocot-sequence/Rust/stern-brocot-sequence.rs create mode 100644 Task/Strassens-algorithm/FreeBASIC/strassens-algorithm.basic create mode 100644 Task/Strassens-algorithm/Jq/strassens-algorithm.jq rename Task/String-matching/M2000-Interpreter/{string-matching.m2000 => string-matching-1.m2000} (100%) create mode 100644 Task/String-matching/M2000-Interpreter/string-matching-2.m2000 create mode 100644 Task/Subleq/Rust/subleq.rs create mode 100644 Task/Subtractive-generator/ALGOL-68/subtractive-generator.alg create mode 100644 Task/Subtractive-generator/XPL0/subtractive-generator.xpl0 create mode 100644 Task/Sudan-function/FutureBasic/sudan-function.basic create mode 100644 Task/Sum-digits-of-an-integer/FutureBasic/sum-digits-of-an-integer.basic create mode 100644 Task/Summarize-and-say-sequence/FreeBASIC/summarize-and-say-sequence.basic create mode 100644 Task/Tarjan/FreeBASIC/tarjan.basic create mode 100644 Task/Temperature-conversion/FutureBasic/temperature-conversion.basic create mode 100644 Task/Terminal-control-Clear-the-screen/FutureBasic/terminal-control-clear-the-screen.basic create mode 100644 Task/The-Name-Game/FutureBasic/the-name-game.basic create mode 100644 Task/Thieles-interpolation-formula/XPL0/thieles-interpolation-formula.xpl0 create mode 100644 Task/Transliterate-English-text-using-the-Greek-alphabet/V-(Vlang)/transliterate-english-text-using-the-greek-alphabet.v create mode 100644 Task/Tropical-algebra-overloading/Rust/tropical-algebra-overloading.rs create mode 100644 Task/Universal-Turing-machine/FreeBASIC/universal-turing-machine.basic create mode 100644 Task/User-input-Text/FutureBasic/user-input-text.basic create mode 100644 Task/Vampire-number/AWK/vampire-number.awk create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/FreeBASIC/verify-distribution-uniformity-chi-squared-test.basic create mode 100644 Task/Vogels-approximation-method/ALGOL-68/vogels-approximation-method.alg create mode 100644 Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy create mode 100644 Task/Vogels-approximation-method/FreeBASIC/vogels-approximation-method.basic create mode 100644 Task/Vogels-approximation-method/Rust/vogels-approximation-method.rs create mode 100644 Task/Wasteful-equidigital-and-frugal-numbers/FreeBASIC/wasteful-equidigital-and-frugal-numbers.basic create mode 100644 Task/Word-frequency/V-(Vlang)/word-frequency.v create mode 100644 Task/World-Cup-group-stage/XPL0/world-cup-group-stage.xpl0 diff --git a/Lang/AArch64-Assembly/Conways-Game-of-Life b/Lang/AArch64-Assembly/Conways-Game-of-Life new file mode 120000 index 0000000000..048d5e56cd --- /dev/null +++ b/Lang/AArch64-Assembly/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/AArch64-Assembly \ No newline at end of file diff --git a/Lang/ALGOL-68/Biorhythms b/Lang/ALGOL-68/Biorhythms new file mode 120000 index 0000000000..b15056dfc9 --- /dev/null +++ b/Lang/ALGOL-68/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection new file mode 120000 index 0000000000..ab36c72f12 --- /dev/null +++ b/Lang/ALGOL-68/Factorial-base-numbers-indexing-permutations-of-a-collection @@ -0,0 +1 @@ +../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/LU-decomposition b/Lang/ALGOL-68/LU-decomposition new file mode 120000 index 0000000000..3453e9548a --- /dev/null +++ b/Lang/ALGOL-68/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Mayan-numerals b/Lang/ALGOL-68/Mayan-numerals new file mode 120000 index 0000000000..901b0eac41 --- /dev/null +++ b/Lang/ALGOL-68/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Subtractive-generator b/Lang/ALGOL-68/Subtractive-generator new file mode 120000 index 0000000000..f90071e31a --- /dev/null +++ b/Lang/ALGOL-68/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Vogels-approximation-method b/Lang/ALGOL-68/Vogels-approximation-method new file mode 120000 index 0000000000..9c09f3c2a5 --- /dev/null +++ b/Lang/ALGOL-68/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/ALGOL-68 \ No newline at end of file diff --git a/Lang/AWK/Vampire-number b/Lang/AWK/Vampire-number new file mode 120000 index 0000000000..3b7709e53a --- /dev/null +++ b/Lang/AWK/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/AWK \ No newline at end of file diff --git a/Lang/Ada/Babylonian-spiral b/Lang/Ada/Babylonian-spiral new file mode 120000 index 0000000000..fd4ac4c6ad --- /dev/null +++ b/Lang/Ada/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/Ada \ No newline at end of file diff --git a/Lang/BQN/Dutch-national-flag-problem b/Lang/BQN/Dutch-national-flag-problem new file mode 120000 index 0000000000..c24e10da06 --- /dev/null +++ b/Lang/BQN/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/BQN \ No newline at end of file diff --git a/Lang/EasyLang/Mayan-numerals b/Lang/EasyLang/Mayan-numerals new file mode 120000 index 0000000000..101692428a --- /dev/null +++ b/Lang/EasyLang/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Vogels-approximation-method b/Lang/EasyLang/Vogels-approximation-method new file mode 120000 index 0000000000..576b7c1373 --- /dev/null +++ b/Lang/EasyLang/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/EasyLang \ No newline at end of file diff --git a/Lang/Fish/00-LANG.txt b/Lang/Fish/00-LANG.txt index ae84e9d381..3479165e5a 100644 --- a/Lang/Fish/00-LANG.txt +++ b/Lang/Fish/00-LANG.txt @@ -1,4 +1,3 @@ -{{language}}Fish is an Funge-like esoteric language, consisting of the traditional Funge one-character commands. -A complete specification with a list of implementations can be found at [[eso:Fish|esolangs]]. +{{language}}Fish (properly spelled "><>") is a Funge-like esoteric language, consisting of the traditional Funge one-character commands arranged in a two-dimensional code space. A complete specification with a list of implementations can be found at [[eso:Fish|esolangs]]. [[Category:Esoteric_Languages]] \ No newline at end of file diff --git a/Lang/FreeBASIC/15-puzzle-solver b/Lang/FreeBASIC/15-puzzle-solver new file mode 120000 index 0000000000..aac40387ff --- /dev/null +++ b/Lang/FreeBASIC/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Brace-expansion b/Lang/FreeBASIC/Brace-expansion new file mode 120000 index 0000000000..b08a413ab2 --- /dev/null +++ b/Lang/FreeBASIC/Brace-expansion @@ -0,0 +1 @@ +../../Task/Brace-expansion/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Chat-server b/Lang/FreeBASIC/Chat-server new file mode 120000 index 0000000000..59f06de348 --- /dev/null +++ b/Lang/FreeBASIC/Chat-server @@ -0,0 +1 @@ +../../Task/Chat-server/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..e2defb3109 --- /dev/null +++ b/Lang/FreeBASIC/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Display-an-outline-as-a-nested-table b/Lang/FreeBASIC/Display-an-outline-as-a-nested-table new file mode 120000 index 0000000000..e1fe23aa03 --- /dev/null +++ b/Lang/FreeBASIC/Display-an-outline-as-a-nested-table @@ -0,0 +1 @@ +../../Task/Display-an-outline-as-a-nested-table/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Echo-server b/Lang/FreeBASIC/Echo-server new file mode 120000 index 0000000000..af11371400 --- /dev/null +++ b/Lang/FreeBASIC/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection b/Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection new file mode 120000 index 0000000000..1f2b24105a --- /dev/null +++ b/Lang/FreeBASIC/Factorial-base-numbers-indexing-permutations-of-a-collection @@ -0,0 +1 @@ +../../Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Hello-world-Web-server b/Lang/FreeBASIC/Hello-world-Web-server new file mode 120000 index 0000000000..25d52ccee6 --- /dev/null +++ b/Lang/FreeBASIC/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/History-variables b/Lang/FreeBASIC/History-variables new file mode 120000 index 0000000000..68f4bcd858 --- /dev/null +++ b/Lang/FreeBASIC/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Intersecting-number-wheels b/Lang/FreeBASIC/Intersecting-number-wheels new file mode 120000 index 0000000000..42313ae624 --- /dev/null +++ b/Lang/FreeBASIC/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Jaro-Winkler-distance b/Lang/FreeBASIC/Jaro-Winkler-distance new file mode 120000 index 0000000000..567e61dfba --- /dev/null +++ b/Lang/FreeBASIC/Jaro-Winkler-distance @@ -0,0 +1 @@ +../../Task/Jaro-Winkler-distance/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/K-d-tree b/Lang/FreeBASIC/K-d-tree new file mode 120000 index 0000000000..f6319abaa1 --- /dev/null +++ b/Lang/FreeBASIC/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/LU-decomposition b/Lang/FreeBASIC/LU-decomposition new file mode 120000 index 0000000000..a239ac6c87 --- /dev/null +++ b/Lang/FreeBASIC/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Mayan-calendar b/Lang/FreeBASIC/Mayan-calendar new file mode 120000 index 0000000000..4de11e93f6 --- /dev/null +++ b/Lang/FreeBASIC/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/P-value-correction b/Lang/FreeBASIC/P-value-correction new file mode 120000 index 0000000000..a2f7c2e1e2 --- /dev/null +++ b/Lang/FreeBASIC/P-value-correction @@ -0,0 +1 @@ +../../Task/P-value-correction/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parse-an-IP-Address b/Lang/FreeBASIC/Parse-an-IP-Address new file mode 120000 index 0000000000..4b51728d74 --- /dev/null +++ b/Lang/FreeBASIC/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parsing-RPN-to-infix-conversion b/Lang/FreeBASIC/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..d524880dde --- /dev/null +++ b/Lang/FreeBASIC/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parsing-Shunting-yard-algorithm b/Lang/FreeBASIC/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..c598b75c18 --- /dev/null +++ b/Lang/FreeBASIC/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/QR-decomposition b/Lang/FreeBASIC/QR-decomposition new file mode 120000 index 0000000000..b4e25e341a --- /dev/null +++ b/Lang/FreeBASIC/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags b/Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags new file mode 120000 index 0000000000..c9a2ddc646 --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Find-bare-lang-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-bare-lang-tags/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/SOAP b/Lang/FreeBASIC/SOAP new file mode 120000 index 0000000000..927bc2295a --- /dev/null +++ b/Lang/FreeBASIC/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Stable-marriage-problem b/Lang/FreeBASIC/Stable-marriage-problem new file mode 120000 index 0000000000..e54d2883a7 --- /dev/null +++ b/Lang/FreeBASIC/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/State-name-puzzle b/Lang/FreeBASIC/State-name-puzzle new file mode 120000 index 0000000000..31d5af215a --- /dev/null +++ b/Lang/FreeBASIC/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Strassens-algorithm b/Lang/FreeBASIC/Strassens-algorithm new file mode 120000 index 0000000000..a5c6e9ef78 --- /dev/null +++ b/Lang/FreeBASIC/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Summarize-and-say-sequence b/Lang/FreeBASIC/Summarize-and-say-sequence new file mode 120000 index 0000000000..c59e649aca --- /dev/null +++ b/Lang/FreeBASIC/Summarize-and-say-sequence @@ -0,0 +1 @@ +../../Task/Summarize-and-say-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Tarjan b/Lang/FreeBASIC/Tarjan new file mode 120000 index 0000000000..2088963b57 --- /dev/null +++ b/Lang/FreeBASIC/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Universal-Turing-machine b/Lang/FreeBASIC/Universal-Turing-machine new file mode 120000 index 0000000000..a29b2e6201 --- /dev/null +++ b/Lang/FreeBASIC/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test b/Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..8088ed160e --- /dev/null +++ b/Lang/FreeBASIC/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Vogels-approximation-method b/Lang/FreeBASIC/Vogels-approximation-method new file mode 120000 index 0000000000..e685ba3d8d --- /dev/null +++ b/Lang/FreeBASIC/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers b/Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..7889ec2570 --- /dev/null +++ b/Lang/FreeBASIC/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FutureBasic/15-puzzle-solver b/Lang/FutureBasic/15-puzzle-solver new file mode 120000 index 0000000000..db2f936a7e --- /dev/null +++ b/Lang/FutureBasic/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Amb b/Lang/FutureBasic/Amb new file mode 120000 index 0000000000..399b8a70d5 --- /dev/null +++ b/Lang/FutureBasic/Amb @@ -0,0 +1 @@ +../../Task/Amb/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Anonymous-recursion b/Lang/FutureBasic/Anonymous-recursion new file mode 120000 index 0000000000..d52f4bbda0 --- /dev/null +++ b/Lang/FutureBasic/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-geometric-mean b/Lang/FutureBasic/Arithmetic-geometric-mean new file mode 120000 index 0000000000..2894f4733f --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Mean-angle b/Lang/FutureBasic/Averages-Mean-angle new file mode 120000 index 0000000000..45c7d861f6 --- /dev/null +++ b/Lang/FutureBasic/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Root-mean-square b/Lang/FutureBasic/Averages-Root-mean-square new file mode 120000 index 0000000000..f04b81a3b0 --- /dev/null +++ b/Lang/FutureBasic/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Barnsley-fern b/Lang/FutureBasic/Barnsley-fern new file mode 120000 index 0000000000..a6da4c722a --- /dev/null +++ b/Lang/FutureBasic/Barnsley-fern @@ -0,0 +1 @@ +../../Task/Barnsley-fern/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Binary-search b/Lang/FutureBasic/Binary-search new file mode 120000 index 0000000000..55e96bcbd8 --- /dev/null +++ b/Lang/FutureBasic/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bitmap-B-zier-curves-Cubic b/Lang/FutureBasic/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..743bf83068 --- /dev/null +++ b/Lang/FutureBasic/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Blum-integer b/Lang/FutureBasic/Blum-integer new file mode 120000 index 0000000000..0ccbf69775 --- /dev/null +++ b/Lang/FutureBasic/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Box-the-compass b/Lang/FutureBasic/Box-the-compass new file mode 120000 index 0000000000..7b89a8413c --- /dev/null +++ b/Lang/FutureBasic/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Caesar-cipher b/Lang/FutureBasic/Caesar-cipher new file mode 120000 index 0000000000..c0196256fa --- /dev/null +++ b/Lang/FutureBasic/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Catamorphism b/Lang/FutureBasic/Catamorphism new file mode 120000 index 0000000000..25e6699616 --- /dev/null +++ b/Lang/FutureBasic/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Chinese-zodiac b/Lang/FutureBasic/Chinese-zodiac new file mode 120000 index 0000000000..df6e098031 --- /dev/null +++ b/Lang/FutureBasic/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Compile-time-calculation b/Lang/FutureBasic/Compile-time-calculation new file mode 120000 index 0000000000..ef10ff644e --- /dev/null +++ b/Lang/FutureBasic/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/FutureBasic/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..2fbac26654 --- /dev/null +++ b/Lang/FutureBasic/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/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Cumulative-standard-deviation b/Lang/FutureBasic/Cumulative-standard-deviation new file mode 120000 index 0000000000..e51653c2b1 --- /dev/null +++ b/Lang/FutureBasic/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters b/Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..94f004e3ea --- /dev/null +++ b/Lang/FutureBasic/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Dutch-national-flag-problem b/Lang/FutureBasic/Dutch-national-flag-problem new file mode 120000 index 0000000000..a769d7e0d9 --- /dev/null +++ b/Lang/FutureBasic/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Equilibrium-index b/Lang/FutureBasic/Equilibrium-index new file mode 120000 index 0000000000..92d577887f --- /dev/null +++ b/Lang/FutureBasic/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Evaluate-binomial-coefficients b/Lang/FutureBasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..59e49028f9 --- /dev/null +++ b/Lang/FutureBasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Exceptions b/Lang/FutureBasic/Exceptions new file mode 120000 index 0000000000..0e25a15f85 --- /dev/null +++ b/Lang/FutureBasic/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..fd7f3bd9e7 --- /dev/null +++ b/Lang/FutureBasic/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Flow-control-structures b/Lang/FutureBasic/Flow-control-structures new file mode 120000 index 0000000000..47305c16bf --- /dev/null +++ b/Lang/FutureBasic/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Forward-difference b/Lang/FutureBasic/Forward-difference new file mode 120000 index 0000000000..8669b1c1f5 --- /dev/null +++ b/Lang/FutureBasic/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Function-composition b/Lang/FutureBasic/Function-composition new file mode 120000 index 0000000000..363444c694 --- /dev/null +++ b/Lang/FutureBasic/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Fusc-sequence b/Lang/FutureBasic/Fusc-sequence new file mode 120000 index 0000000000..603bccf327 --- /dev/null +++ b/Lang/FutureBasic/Fusc-sequence @@ -0,0 +1 @@ +../../Task/Fusc-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Host-introspection b/Lang/FutureBasic/Host-introspection new file mode 120000 index 0000000000..c342a7333a --- /dev/null +++ b/Lang/FutureBasic/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/ISBN13-check-digit b/Lang/FutureBasic/ISBN13-check-digit new file mode 120000 index 0000000000..ad5e4cffb4 --- /dev/null +++ b/Lang/FutureBasic/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/JortSort b/Lang/FutureBasic/JortSort new file mode 120000 index 0000000000..a21b94121b --- /dev/null +++ b/Lang/FutureBasic/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Josephus-problem b/Lang/FutureBasic/Josephus-problem new file mode 120000 index 0000000000..d84fa33d5d --- /dev/null +++ b/Lang/FutureBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Last-Friday-of-each-month b/Lang/FutureBasic/Last-Friday-of-each-month new file mode 120000 index 0000000000..a3476e0672 --- /dev/null +++ b/Lang/FutureBasic/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Least-common-multiple b/Lang/FutureBasic/Least-common-multiple new file mode 120000 index 0000000000..23b8dbfe57 --- /dev/null +++ b/Lang/FutureBasic/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Long-literals-with-continuations b/Lang/FutureBasic/Long-literals-with-continuations new file mode 120000 index 0000000000..09dff817df --- /dev/null +++ b/Lang/FutureBasic/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Long-year b/Lang/FutureBasic/Long-year new file mode 120000 index 0000000000..ae89f1d742 --- /dev/null +++ b/Lang/FutureBasic/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body b/Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..ff81b810cd --- /dev/null +++ b/Lang/FutureBasic/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..088e4f56af --- /dev/null +++ b/Lang/FutureBasic/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Munching-squares b/Lang/FutureBasic/Munching-squares new file mode 120000 index 0000000000..3fb288f688 --- /dev/null +++ b/Lang/FutureBasic/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Nim-game b/Lang/FutureBasic/Nim-game new file mode 120000 index 0000000000..edc10ed0c5 --- /dev/null +++ b/Lang/FutureBasic/Nim-game @@ -0,0 +1 @@ +../../Task/Nim-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Nth b/Lang/FutureBasic/Nth new file mode 120000 index 0000000000..10c058fbd2 --- /dev/null +++ b/Lang/FutureBasic/Nth @@ -0,0 +1 @@ +../../Task/Nth/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Own-digits-power-sum b/Lang/FutureBasic/Own-digits-power-sum new file mode 120000 index 0000000000..5cd998b558 --- /dev/null +++ b/Lang/FutureBasic/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Palindrome-dates b/Lang/FutureBasic/Palindrome-dates new file mode 120000 index 0000000000..2b72c0230b --- /dev/null +++ b/Lang/FutureBasic/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pascals-triangle-Puzzle b/Lang/FutureBasic/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..142f796d16 --- /dev/null +++ b/Lang/FutureBasic/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Pinstripe-Display b/Lang/FutureBasic/Pinstripe-Display new file mode 120000 index 0000000000..da5d8bc2b0 --- /dev/null +++ b/Lang/FutureBasic/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Playing-cards b/Lang/FutureBasic/Playing-cards new file mode 120000 index 0000000000..965405f346 --- /dev/null +++ b/Lang/FutureBasic/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Regular-expressions b/Lang/FutureBasic/Regular-expressions new file mode 120000 index 0000000000..cd49461444 --- /dev/null +++ b/Lang/FutureBasic/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Search-a-list-of-records b/Lang/FutureBasic/Search-a-list-of-records new file mode 120000 index 0000000000..3fefc25b7b --- /dev/null +++ b/Lang/FutureBasic/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-triangle b/Lang/FutureBasic/Sierpinski-triangle new file mode 120000 index 0000000000..300049c10c --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sort-an-array-of-composite-structures b/Lang/FutureBasic/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..ffd97b8a5e --- /dev/null +++ b/Lang/FutureBasic/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sort-numbers-lexicographically b/Lang/FutureBasic/Sort-numbers-lexicographically new file mode 120000 index 0000000000..b8d6f91892 --- /dev/null +++ b/Lang/FutureBasic/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Spinning-rod-animation-Text b/Lang/FutureBasic/Spinning-rod-animation-Text new file mode 120000 index 0000000000..a0c68e7478 --- /dev/null +++ b/Lang/FutureBasic/Spinning-rod-animation-Text @@ -0,0 +1 @@ +../../Task/Spinning-rod-animation-Text/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Square-but-not-cube b/Lang/FutureBasic/Square-but-not-cube new file mode 120000 index 0000000000..a8c6d02eba --- /dev/null +++ b/Lang/FutureBasic/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Stack b/Lang/FutureBasic/Stack new file mode 120000 index 0000000000..638a183bbc --- /dev/null +++ b/Lang/FutureBasic/Stack @@ -0,0 +1 @@ +../../Task/Stack/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sudan-function b/Lang/FutureBasic/Sudan-function new file mode 120000 index 0000000000..1f582a9d0d --- /dev/null +++ b/Lang/FutureBasic/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-digits-of-an-integer b/Lang/FutureBasic/Sum-digits-of-an-integer new file mode 120000 index 0000000000..cf8ab32c2c --- /dev/null +++ b/Lang/FutureBasic/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Temperature-conversion b/Lang/FutureBasic/Temperature-conversion new file mode 120000 index 0000000000..b60c2baf77 --- /dev/null +++ b/Lang/FutureBasic/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Terminal-control-Clear-the-screen b/Lang/FutureBasic/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..878687a038 --- /dev/null +++ b/Lang/FutureBasic/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/The-Name-Game b/Lang/FutureBasic/The-Name-Game new file mode 120000 index 0000000000..2e6c9ef1a6 --- /dev/null +++ b/Lang/FutureBasic/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/User-input-Text b/Lang/FutureBasic/User-input-Text new file mode 120000 index 0000000000..3d0e3bd7f1 --- /dev/null +++ b/Lang/FutureBasic/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/FutureBasic \ No newline at end of file diff --git a/Lang/GW-BASIC/Colour-pinstripe-Display b/Lang/GW-BASIC/Colour-pinstripe-Display new file mode 120000 index 0000000000..383619acfb --- /dev/null +++ b/Lang/GW-BASIC/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Pinstripe-Display b/Lang/GW-BASIC/Pinstripe-Display new file mode 120000 index 0000000000..282b987dfa --- /dev/null +++ b/Lang/GW-BASIC/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/GW-BASIC \ No newline at end of file diff --git a/Lang/Isabelle/Bernoulli-numbers b/Lang/Isabelle/Bernoulli-numbers new file mode 120000 index 0000000000..73728f3564 --- /dev/null +++ b/Lang/Isabelle/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Isabelle \ No newline at end of file diff --git a/Lang/Isabelle/Catalan-numbers b/Lang/Isabelle/Catalan-numbers new file mode 120000 index 0000000000..b2ce7b3a40 --- /dev/null +++ b/Lang/Isabelle/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Isabelle \ No newline at end of file diff --git a/Lang/Jq/Strassens-algorithm b/Lang/Jq/Strassens-algorithm new file mode 120000 index 0000000000..d6ccda4254 --- /dev/null +++ b/Lang/Jq/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Jq \ No newline at end of file diff --git a/Lang/LSL/00-LANG.txt b/Lang/LSL/00-LANG.txt index bdb68f1bc2..3025477b27 100644 --- a/Lang/LSL/00-LANG.txt +++ b/Lang/LSL/00-LANG.txt @@ -1,25 +1,42 @@ {{language |hopl=no }} -The [[wp:Linden_Scripting_Language|'''Linden Scripting Language''']], usually just called '''LSL''' for short, is a language developed by [http://en.wikipedia.org/wiki/Linden_Lab Linden Labs] for their [[wp:Second_Life|Second Life]] virtual world. LSL allows Second Life objects to sense, respond to events, and interact with the (virtual) world around them, and the Avatars in that world. +'''LSL''' ([[wp:Linden_Scripting_Language|'''Linden Scripting Language''']]) is the scripting language developed by [http://en.wikipedia.org/wiki/Linden_Lab Linden Labs] for their virtual sandbox world [[wp:Second_Life|Second Life]]. Also [[wp:OpenSimulator|OpenSimulator]] along with other [https://omrg.org Open Metaverse] proprietors run a largely compatible superset version of LSL. LSL scripts allow objects rezzed in-world(in-game) to interact with and manipulate the virtual world around them, but also the internet in limited fashion. LSL has many built-in functions, and the ability for inter script messaging, http POST and GET requests, gui dialog boxes, chat channel messaging, java & C like semantics, is turning complete, etc. + +==In Depth: Syntax Structure== +LSL is C-like with scoping of local varaibles and global; strict typing with type-recasting possible; use of {} to encapsulate function blocks, and ; to denote an execution block, and () to encapsulate parameters, and equivalency from right to left and for assignment myint=1-2, variables can be formed as procedures that return a value. Oprands are the same, but there are no pointers nor triple oprands such as +++. +LSL is not like C in many ways, there are only 3 basic types, and 4 special types of data structures: integer (unsigned 32bit), float (unsigned 32bit), string (max string length varies), key ( a 32bit base16 UUID often treated as a string),vectors (set of three floats, aka a tuple <0.0,0.0,0.0> ); quaternions or rot ( set of four floats <0.0,0.0,0.0,0.0> ); lists (1D array that can contain any of or a mix of types of data), There is no void as a type! Nor is there any keyword for functions. Simply outside of a script's default loop function called a state, one forms a function with it's name(type prams){;} and can be called anywhere else. Over-loading is not valid, nor is under-loading when calling a function or variable-function that returns a value. + +==In Depth: Where & when LSL scripts can run== +Rezzing is dragging and dropping from the user's inventory into to the virtual world space, or being worn as attachments to one's avatar (including HUDs). These aforementioned objects take the form of built-in 3d models of basic shapes commonly known as primitives or just prims, sculpted prims, and user uploaded 3D models. Each object has in-turn it's own inventory where the scripts run. In truth one can link many objects into a meta-object known as a link-set, each linked object retains it's own inventory instance, and running scripts. When an object is derezzed, that is brought back into the user's inventory, or an attached object derezzes when the user logs off the scripts' current status is paused and saved. + +==In Depth: LSL basic script structure== +Each script must contain a default script state, this is very similar to the default loop found with in Arduino Clike programming. It is possible to switch the currently running state of a script to a knew one, and back again, thus ignoring/clearing any callback functions called "events". (However the timer does not get cleared upon state changes). +Each state in LSL scripts can have built in call-back functions known as "event types" which are triggered with interrupt like behavior from a cue that is filled by the current simulator or sim (a sim is world instance, generally a 256x256meter block, although some communication with adjacent sims maybe possible) the script is residing in. Most events are repeatable, but there are logically single fire events such as state_entry, on_rez, on_attach, on_deattach. Aforementioned user functions, variables, + +==Back-ends of LSL with in Second-Life== +In Second-life, one can save & run scripts optionally for the two current back-ends that actually run the code over a server, each with their own pros and cons. +[https://wiki.secondlife.com/wiki/LSO LSO] exists for backward compatibility. LSO saved scripts are interpreted at runtime by the server. LSO scripts take less initial script memory, they are limited to less available memory as well. In rare circumstances LSO may run faster than MONO. However LSO suffers from memory fragmentation slow downs with list connotation (there are some work around). LSO handles the jump to @location in unexpected ways. +Mono saved scripts are compiled under [[wp:Mono_(software)|Mono]] (the most recent) to byte-code ran by the server. + Most scripts will benefit from being set to MONO compilation for greater speed and more available memory, at the cost of higher initial memory used. ==Flavors of LSL== -There are currently three flavors of the LSL language -# LSL compiled under [[wp:Mono_(software)|Mono]] (the most recent) -# The original interpreted version (no longer being developed and only exists for backward compatibility) -# A largely compatible version of LSL that can run in the [[wp:OpenSimulator|OpenSimulator]] virtual world. +# A largely compatible version of LSL that can run in the [[http://opensimulator.org/wiki/OSSL_Script_Library|OpenSimulator]] virtual world. ==Documentation== There are two popular web sites documenting LSL # Second Life's own [http://wiki.secondlife.com/wiki/LSL_Portal LSL Portal] # a user supported [http://lslwiki.net/lslwiki/wakka.php LSL Wiki] -==Libraries== +==Libraries of Scripts== There exists several open source libraries where users share code +* [https://outworldz.com/cgi/freescripts.plx Free LSL Scripts] * [http://community.secondlife.com/t5/LSL-Scripting-Library/bd-p/LSLScriptingLibrary LSL Scripting Library] * [http://wiki.secondlife.com/wiki/Category:LSL_Examples LSL Examples] -* [http://www.free-lsl-scripts.com/cgi/freescripts.plx Free LSL Scripts] * [http://community.secondlife.com/t5/LSL-Scripting/bd-p/LSLScripting LSL Scripting] ==External Editors== -There are also many [http://wiki.secondlife.com/wiki/LSL_Alternate_Editors external editors] for LSL allowing you to write, syntax check, and (to a limited extent) execute LSL outside of the Second Life environment. You will need to sign up at [http://secondlife.com Second Life] and have a Second Life account to execute LSL in the virtual world. Your scripts can exist by themselves in a folder of your inventory, or in an Object in your inventory, but need to be in an Object that is in-world to execute (if an Object containing scripts is taken in to your inventory, the scripts will be suspended and will resume when brought out in to the world again.) \ No newline at end of file +There are also many [http://wiki.secondlife.com/wiki/LSL_Alternate_Editors external editors] for LSL allowing you to write with highlighting, [https://github.com/Feay/LSL-for-Scite api tool-tips], [https://github.com/Makopo/lslint syntax check], and (to a limited extent) +[https://github.com/Sei-Lisa/LSL-compiler compile and execute LSL] outside of the Second Life environment. + +You will need to sign up at [http://secondlife.com Second Life] and have a Second Life account to execute LSL in the virtual world. Your scripts can exist by themselves in a folder of your inventory, or in an Object in your inventory, but need to be in an Object that is in-world to execute (if an Object containing scripts is taken in to your inventory, the scripts will be suspended and will resume when brought out in to the world again.) \ No newline at end of file diff --git a/Lang/LSL/Binary-digits b/Lang/LSL/Binary-digits new file mode 120000 index 0000000000..54627407f6 --- /dev/null +++ b/Lang/LSL/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/LSL \ No newline at end of file diff --git a/Lang/M2000-Interpreter/00-LANG.txt b/Lang/M2000-Interpreter/00-LANG.txt index ed77df4b81..feda8eeb04 100644 --- a/Lang/M2000-Interpreter/00-LANG.txt +++ b/Lang/M2000-Interpreter/00-LANG.txt @@ -26,7 +26,7 @@ Module's may be Global, or local to other modules. We can define global modules We can change a inner module at the calling of a module, see the example: We call inner Beta in two stages. At the second stage we change inner Theta with Theta2. This is the decoration of Beta with Theta as Theta2. This is a temporary decoration because Beta after execution erase any new identifier including Theta. So each time we call Beta, statement Module Theta make this module unless a decoration stop it. ====English Vocabulary==== -Module Beta { +Module Beta { Module Theta (x){ Print "This is Theta, we get x=";x } @@ -38,8 +38,9 @@ Module Theta2 (x) { } Beta ; Theta as Theta2 + ====Greek Vocabulary==== -Τμήμα Βήτα { +Τμήμα Βήτα { Τμήμα Θήτα (χ){ Τύπωσε "Αυτό είναι το Θήτα, θα πάρουμε το χ=";χ } @@ -54,7 +55,7 @@ Beta ; Theta as Theta2 As we can see from code, some statements are like BASIC, except the use of curly brackets {}. Check the code below. We have a Module (as a Procedure), where we define some functions and some variables, as entities. These entities defined in every call to CheckIt, and erased when execution return from CheckIt. By default every parameter in M2000 pass by value. We define two functions, Alfa() where we set type for parameter x and ExpType$() where we not set type for x, and we wish to return the name of type when we make a call. -Module CheckIt { +Module CheckIt { \\ We can't call something out of this module Function Alfa(X as double) { =X**2 @@ -92,7 +93,7 @@ A statement Input Alfa$ can input characters for a string or for object typed gr Types are strong for values with a name (variables, constants), but weak for items in containers. In a container (Array, Inventory and Stack) we can place anything including other containers. We can bypass the "strong" capability but this isn't a practice for good programming. Internal or variables are of type of Variant, so we can make a reference of A to A$ and we can save a string "1212" and read from A the number 1212. - + Module AKindOfMess { a=10@ Print Type$(a)="Decimal" @@ -131,7 +132,7 @@ Print Error$="" So check this for proper use of types. -Module CheckInt { +Module CheckInt { A%=1212212.12@ Print A% ' 1212212 A%=1212212.52@ @@ -149,18 +150,19 @@ So check this for proper use of types. } CheckInt -So we say about Integer Variables, and no Integer Numeric Type. Like in Basic, M2000 is not case sensitive (except for labels), so A% and a% is the same. We may have A, A$ and A% as three variables, or A(), A%(), A$() as arrays or and functions. We can use name(@ ) to call function and not array if we have each with same name. +So we say about Integer Variables, and no Integer Numeric Type. Like in Basic, M2000 is not case sensitive (except for labels), so A% and a% is the same. We may have A, A$ and A% as three variables, or A(), A%(), A$() as arrays or and functions. We can use name(* ) to call function and not array if we have each with same name. -Dim A(10)=1 +Dim A(10)=1 Def A(x)=x**2 -Print A(3), A(@ 4) +Print A(3), A(* 4) ' change @ to * from later versions + By default all variables are local. M2000 uses heap to store local variables, not stack. We can use global variables, but a local definition hide a global one. We can make global variables for temporary use (at return from module which we define a global, this global erased). A global definition in an already defined global variable with same name, hide for temporary use the old global variable. It is easy to make modules, with modules, functions, variables, arrays. We can use subroutines when we want code in a module or a function to used more than once. We can use local variables inside subroutines. In subroutines we can use module's variables, functions, subroutines. Until here we see something like BASIC, except that variables are local to modules and functions, but can be used by subroutines. Also we have see that we can replace a module in a module when we call it. With this replacement we can use a predefined logic with some "terminals", modules that get parameters and do final things. We can make global modules and functions in local modules and functions, but these exist until creator module or function exit. -M2000 can be used for more advanced programming. Modules and functions can be members of Groups. Groups are values. So a function can return a Group. +M2000 can be used for more advanced programming. Modules and functions can be members of Groups. Groups are values. So a function can return a Group. ===Stack of Values=== Modules and functions get parameters in a stack. Modules get the parent stack with parameters, and functions get a new stack with parameters. Modules return from call and are responsible to clear as needed the stack. Functions drop the stack after the call from an expression. A module can return entities in stack, if we want to do that. We can call a module and pass parameters, and that module can call other module leaving parameters in stack to be read in last module. @@ -170,7 +172,7 @@ In the example below (y) is a Read y for module definition. Early versions of la As we see alfa has no read statement, because before get the first number need to make two modules, and then pop one number and call a module passing current stack, so if choose beta, then the second value feed y from a read y statement. - + module alfa { module beta (y) { print y**3 @@ -195,15 +197,13 @@ function sumall { print sumall(1,2,3,4,5,6,7)=28 - - ===OOP=== Groups are objects for M2000. We can use them as values, and if we want we can use pointers for groups (but we can make a lot of programs without using pointers to groups). Without using pointer, a Group may be local with a name in a Module or can be in a container like array, inventory (a type of map) and stack objects, without name. Groups may have private and public members, may have properties as read only, may get value and return value, and may have operators. Members of Groups can be anything, including other groups. Groups may have events too. We can make groups by using CLASS statement or by using own function which return a Group or a pointer to Group. A special object is the lambda object, which may have a number of closures, and have to faces, a variable and a function: -Module Delta { +Module Delta { \\ Make a group like a lambda \\ A Class make a Global Function \\ (in a group a Class definition make a group member, not a global function) @@ -244,7 +244,7 @@ We can place a lambda function as closure in a lambda function, and we can build a class define a type too. We can make a class from other classes too. We can make inner classes too. - + Form 80,50 \\ counters supposed we provide them from a file global LastCustomerId=100, ReportId=80 @@ -342,7 +342,7 @@ While M { Until now we see modules/functions/subs for procedural programming, Groups for OOP, Groups as lambda functions and lambda functions for functional programming. We can use events for groups and for COM objects, including GUI objects. -Module Beta { +Module Beta { Group WithEvents Alpha { Event "One" Module DoIt (x) { @@ -380,7 +380,7 @@ Until now we see that programming with events can be used in M2000. There is an Modules may have Threads, part of modules that can be executed in intervals, can be halted, or can be released, and can be erased. Each thread has own stack and may have own static variables (Modules and Functions also may have static variables), but can use modules variables and functions/modules/subs. Threads can run concurrent (thread return to task manager after execution of a statement or a block of statements) or sequential (a thread has to exit from interval to start other thread) -Module Zeta { +Module Zeta { k=10 Thread { k++ @@ -399,7 +399,7 @@ Zeta M2000 Interpreter can work with Structures and Buffers. Buffer is a memory block and Structure can define types of memory, and a buffer can hold arrays of structures. Each structure can be made from other structures or arrays of structures, and may have unions. We can use buffers for code execution (writing machine code), using standard buffers (not executable), for data holder. Also we can use Buffers calling external dll and passing by address. -Module Kappa { +Module Kappa { Function Theta(x) { Structure Points_single { x as single diff --git a/Lang/M2000-Interpreter/Associative-array-Merging b/Lang/M2000-Interpreter/Associative-array-Merging new file mode 120000 index 0000000000..e54ba7cbfd --- /dev/null +++ b/Lang/M2000-Interpreter/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Averages-Mean-angle b/Lang/M2000-Interpreter/Averages-Mean-angle new file mode 120000 index 0000000000..5bcc89482d --- /dev/null +++ b/Lang/M2000-Interpreter/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Babylonian-spiral b/Lang/M2000-Interpreter/Babylonian-spiral new file mode 120000 index 0000000000..70eeaaf834 --- /dev/null +++ b/Lang/M2000-Interpreter/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bernoulli-numbers b/Lang/M2000-Interpreter/Bernoulli-numbers new file mode 120000 index 0000000000..91c31cbe94 --- /dev/null +++ b/Lang/M2000-Interpreter/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Chinese-zodiac b/Lang/M2000-Interpreter/Chinese-zodiac new file mode 120000 index 0000000000..ba20540cb2 --- /dev/null +++ b/Lang/M2000-Interpreter/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Factors-of-a-Mersenne-number b/Lang/M2000-Interpreter/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..dcb49d5579 --- /dev/null +++ b/Lang/M2000-Interpreter/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month b/Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..14e77f2ff4 --- /dev/null +++ b/Lang/M2000-Interpreter/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/K-d-tree b/Lang/M2000-Interpreter/K-d-tree new file mode 120000 index 0000000000..5f1e9bff31 --- /dev/null +++ b/Lang/M2000-Interpreter/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Old-lady-swallowed-a-fly b/Lang/M2000-Interpreter/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..f9fe169db2 --- /dev/null +++ b/Lang/M2000-Interpreter/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Password-generator b/Lang/M2000-Interpreter/Password-generator new file mode 120000 index 0000000000..0b48ccbf39 --- /dev/null +++ b/Lang/M2000-Interpreter/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Problem-of-Apollonius b/Lang/M2000-Interpreter/Problem-of-Apollonius new file mode 120000 index 0000000000..3c1d7459c0 --- /dev/null +++ b/Lang/M2000-Interpreter/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Stable-marriage-problem b/Lang/M2000-Interpreter/Stable-marriage-problem new file mode 120000 index 0000000000..1148451e3c --- /dev/null +++ b/Lang/M2000-Interpreter/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Statistics-Basic b/Lang/M2000-Interpreter/Statistics-Basic new file mode 120000 index 0000000000..9d5dab6ba7 --- /dev/null +++ b/Lang/M2000-Interpreter/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Statistics-Normal-distribution b/Lang/M2000-Interpreter/Statistics-Normal-distribution new file mode 120000 index 0000000000..6018d24b87 --- /dev/null +++ b/Lang/M2000-Interpreter/Statistics-Normal-distribution @@ -0,0 +1 @@ +../../Task/Statistics-Normal-distribution/M2000-Interpreter \ No newline at end of file diff --git a/Lang/MSX-Basic/Colour-pinstripe-Display b/Lang/MSX-Basic/Colour-pinstripe-Display new file mode 120000 index 0000000000..f0497934ea --- /dev/null +++ b/Lang/MSX-Basic/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Pinstripe-Display b/Lang/MSX-Basic/Pinstripe-Display new file mode 120000 index 0000000000..b37582657e --- /dev/null +++ b/Lang/MSX-Basic/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/MSX-Basic \ No newline at end of file diff --git a/Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..e8da31b0d4 --- /dev/null +++ b/Lang/Mathematica/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Mathematica \ No newline at end of file diff --git a/Lang/Miranda/Fractran b/Lang/Miranda/Fractran new file mode 120000 index 0000000000..528ab3ee2e --- /dev/null +++ b/Lang/Miranda/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Miranda \ No newline at end of file diff --git a/Lang/OxygenBasic/Loops-Continue b/Lang/OxygenBasic/Loops-Continue new file mode 120000 index 0000000000..df4c4e529e --- /dev/null +++ b/Lang/OxygenBasic/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/OxygenBasic \ No newline at end of file diff --git a/Lang/PascalABC.NET/Emirp-primes b/Lang/PascalABC.NET/Emirp-primes new file mode 120000 index 0000000000..69e5f4d7f7 --- /dev/null +++ b/Lang/PascalABC.NET/Emirp-primes @@ -0,0 +1 @@ +../../Task/Emirp-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Evolutionary-algorithm b/Lang/PascalABC.NET/Evolutionary-algorithm new file mode 120000 index 0000000000..bc9856dbc0 --- /dev/null +++ b/Lang/PascalABC.NET/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..7cf9286a5e --- /dev/null +++ b/Lang/PascalABC.NET/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Execute-a-system-command b/Lang/PascalABC.NET/Execute-a-system-command new file mode 120000 index 0000000000..7b3f5b40fe --- /dev/null +++ b/Lang/PascalABC.NET/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exponentiation-order b/Lang/PascalABC.NET/Exponentiation-order new file mode 120000 index 0000000000..7066d9dd6b --- /dev/null +++ b/Lang/PascalABC.NET/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base b/Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base new file mode 120000 index 0000000000..cc33366128 --- /dev/null +++ b/Lang/PascalABC.NET/Exponentiation-with-infix-operators-in-or-operating-on-the-base @@ -0,0 +1 @@ +../../Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Extend-your-language b/Lang/PascalABC.NET/Extend-your-language new file mode 120000 index 0000000000..ee51376fd1 --- /dev/null +++ b/Lang/PascalABC.NET/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Extensible-prime-generator b/Lang/PascalABC.NET/Extensible-prime-generator new file mode 120000 index 0000000000..c255987252 --- /dev/null +++ b/Lang/PascalABC.NET/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factorial-primes b/Lang/PascalABC.NET/Factorial-primes new file mode 120000 index 0000000000..5b7eb12507 --- /dev/null +++ b/Lang/PascalABC.NET/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factorions b/Lang/PascalABC.NET/Factorions new file mode 120000 index 0000000000..8d771f5a56 --- /dev/null +++ b/Lang/PascalABC.NET/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Factors-of-a-Mersenne-number b/Lang/PascalABC.NET/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..3160230a03 --- /dev/null +++ b/Lang/PascalABC.NET/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fairshare-between-two-and-more b/Lang/PascalABC.NET/Fairshare-between-two-and-more new file mode 120000 index 0000000000..c21d1ab427 --- /dev/null +++ b/Lang/PascalABC.NET/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Farey-sequence b/Lang/PascalABC.NET/Farey-sequence new file mode 120000 index 0000000000..cd060f6fa5 --- /dev/null +++ b/Lang/PascalABC.NET/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Feigenbaum-constant-calculation b/Lang/PascalABC.NET/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..df0fd85992 --- /dev/null +++ b/Lang/PascalABC.NET/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fermat-numbers b/Lang/PascalABC.NET/Fermat-numbers new file mode 120000 index 0000000000..87303a8419 --- /dev/null +++ b/Lang/PascalABC.NET/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fibonacci-word b/Lang/PascalABC.NET/Fibonacci-word new file mode 120000 index 0000000000..6accc7df5c --- /dev/null +++ b/Lang/PascalABC.NET/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Fibonacci-word-fractal b/Lang/PascalABC.NET/Fibonacci-word-fractal new file mode 120000 index 0000000000..32647433c7 --- /dev/null +++ b/Lang/PascalABC.NET/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Five-weekends b/Lang/PascalABC.NET/Five-weekends new file mode 120000 index 0000000000..868fa3eedb --- /dev/null +++ b/Lang/PascalABC.NET/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/PascalABC.NET \ No newline at end of file diff --git a/Lang/Pike/Execute-Brain- b/Lang/Pike/Execute-Brain- new file mode 120000 index 0000000000..dd7ee4c73b --- /dev/null +++ b/Lang/Pike/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Pike \ No newline at end of file diff --git a/Lang/Plain-English/00-LANG.txt b/Lang/Plain-English/00-LANG.txt index ff86a2a8e2..d3044419f6 100644 --- a/Lang/Plain-English/00-LANG.txt +++ b/Lang/Plain-English/00-LANG.txt @@ -43,21 +43,25 @@ and it can do a few other things. To run: -Start up. -Clear the screen. -Use medium letters. Use the fat pen. -Pick a really dark color. -Loop. -Start in the center of the screen. -Turn left 1/32 of the way. -Turn right. Move 2 inches. Turn left. -Write "HELLO WORLD". -Refresh the screen. -Lighten the current color about 20 percent. -Add 1 to a count. If the count is 32, break. -Repeat. -Wait for the escape key. -Shut down. + Start up. + Clear the screen. + Use medium letters. + Use the fat pen. + Pick a really dark color. + Loop. + Start in the center of the screen. + Turn left 1/32 of the way. + Turn right. + Move 2 inches. + Turn left. + Write "HELLO WORLD". + Refresh the screen. + Lighten the current color about 20 percent. + Add 1 to a count. + If the count is 32, break. + Repeat. + Wait for the escape key. + Shut down. Note that standard English punctuation, word types, and sentence structure are all used. @@ -172,8 +176,8 @@ Type reductions proceed, recursively, from left to right, until a match is found To decide if a number is greater than another number: -If the first number is greater than the second number, say yes. -Say no. + If the first number is greater than the second number, say yes. + Say no. '''Function:''' A routine that extracts, calculates, or otherwise derives a value from a passed parameter. Function headers take this form: @@ -187,14 +191,14 @@ Unlike procedures (which are called via imperative sentences) and deciders (whic '''Statements''' From the instruction manual (see link below): -(1) I really only understand five kinds of sentences: -(a) type definitions, which always start with A, AN, or SOME; -(b) global variable definitions, which always start with THE; -(c) routine headers, which always start with TO, which can contain: -(d) conditional statements, which always start with IF; and -(e) imperative statements, which start with anything else. +(1) The compiler really only understand five kinds of sentences: +(a) Type definitions, which always start with A, AN, or SOME; +(b) Global variable definitions, which always start with THE; +(c) Routine headers, which always start with TO, which can contain: +(d) Conditional statements, which always start with IF; and +(e) Imperative statements, which start with anything else. -(2) I treat as a name anything after A, AN, ANOTHER, SOME, or THE, up to: +(2) I treat as a name (that is, a variable, argument, parameter or a type) anything after A, AN, ANOTHER, SOME, or THE, up to: (a) any simple verb, like IS, ARE, CAN, or DO, or (b) any conjunction, like AND or OR, or @@ -211,7 +215,9 @@ From the instruction manual (see link below): The noodle built into Plain English is simply not useful enough by itself, and therefore libraries were created to assist in writing Rosetta Code tasks in Plain English. See also: -https://github.com/Folds/english A work in progress to normalize Plain English into a more standard compiler. For documentation on the language in general, see the instructions.pdf file in the documentation folder. The author objects (see the issues) +https://github.com/Folds/english A work in progress to normalize Plain English into a more standard compiler. +For documentation on the language in general, see the instructions.pdf file in the documentation folder. +The author objects (see the issues) https://forums.parallax.com/discussion/163792/plain-english-programming a long rambling and unproductive (but educational, so productive in that sense) discussion of Plain English with it's author and proponents of a bare metal processor. {| class="wikitable" diff --git a/Lang/QB64/Averages-Mean-angle b/Lang/QB64/Averages-Mean-angle new file mode 120000 index 0000000000..aab53ced3a --- /dev/null +++ b/Lang/QB64/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/QB64 \ No newline at end of file diff --git a/Lang/QB64/Intersecting-number-wheels b/Lang/QB64/Intersecting-number-wheels new file mode 120000 index 0000000000..226a608551 --- /dev/null +++ b/Lang/QB64/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/QB64 \ No newline at end of file diff --git a/Lang/QB64/Mayan-calendar b/Lang/QB64/Mayan-calendar new file mode 120000 index 0000000000..13deaa3e8a --- /dev/null +++ b/Lang/QB64/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/QB64 \ No newline at end of file diff --git a/Lang/QBasic/Averages-Mean-angle b/Lang/QBasic/Averages-Mean-angle new file mode 120000 index 0000000000..499df28583 --- /dev/null +++ b/Lang/QBasic/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Loops-Continue b/Lang/QBasic/Loops-Continue new file mode 120000 index 0000000000..eeea4ac585 --- /dev/null +++ b/Lang/QBasic/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Pinstripe-Display b/Lang/QBasic/Pinstripe-Display new file mode 120000 index 0000000000..f245a0ccf2 --- /dev/null +++ b/Lang/QBasic/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/QBasic \ No newline at end of file diff --git a/Lang/REXX/Goldbachs-comet b/Lang/REXX/Goldbachs-comet new file mode 120000 index 0000000000..ddf76b927f --- /dev/null +++ b/Lang/REXX/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/REXX \ No newline at end of file diff --git a/Lang/Refal/Arbitrary-precision-integers-included- b/Lang/Refal/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..f00d324a4e --- /dev/null +++ b/Lang/Refal/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Refal \ No newline at end of file diff --git a/Lang/Refal/Fractran b/Lang/Refal/Fractran new file mode 120000 index 0000000000..30b9e7a511 --- /dev/null +++ b/Lang/Refal/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Refal \ No newline at end of file diff --git a/Lang/Refal/Sierpinski-triangle b/Lang/Refal/Sierpinski-triangle new file mode 120000 index 0000000000..078d645de8 --- /dev/null +++ b/Lang/Refal/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Refal \ No newline at end of file diff --git a/Lang/Rust/Almkvist-Giullera-formula-for-pi b/Lang/Rust/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..495c52095c --- /dev/null +++ b/Lang/Rust/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/Rust \ No newline at end of file diff --git a/Lang/Rust/Biorhythms b/Lang/Rust/Biorhythms new file mode 120000 index 0000000000..8d5ffa21d8 --- /dev/null +++ b/Lang/Rust/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Rust \ No newline at end of file diff --git a/Lang/Rust/Stern-Brocot-sequence b/Lang/Rust/Stern-Brocot-sequence new file mode 120000 index 0000000000..72080b645a --- /dev/null +++ b/Lang/Rust/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Subleq b/Lang/Rust/Subleq new file mode 120000 index 0000000000..cc28544f34 --- /dev/null +++ b/Lang/Rust/Subleq @@ -0,0 +1 @@ +../../Task/Subleq/Rust \ No newline at end of file diff --git a/Lang/Rust/Tropical-algebra-overloading b/Lang/Rust/Tropical-algebra-overloading new file mode 120000 index 0000000000..271296f0b3 --- /dev/null +++ b/Lang/Rust/Tropical-algebra-overloading @@ -0,0 +1 @@ +../../Task/Tropical-algebra-overloading/Rust \ No newline at end of file diff --git a/Lang/Rust/Vogels-approximation-method b/Lang/Rust/Vogels-approximation-method new file mode 120000 index 0000000000..377b0aef0a --- /dev/null +++ b/Lang/Rust/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Rust \ No newline at end of file diff --git a/Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters b/Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..f2a5cead6b --- /dev/null +++ b/Lang/S-BASIC/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/S-BASIC \ No newline at end of file diff --git a/Lang/SETL/Arbitrary-precision-integers-included- b/Lang/SETL/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..36386fe719 --- /dev/null +++ b/Lang/SETL/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/SETL \ No newline at end of file diff --git a/Lang/SETL/Fractran b/Lang/SETL/Fractran new file mode 120000 index 0000000000..20f759abeb --- /dev/null +++ b/Lang/SETL/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/SETL \ No newline at end of file diff --git a/Lang/SETL/Mayan-numerals b/Lang/SETL/Mayan-numerals new file mode 120000 index 0000000000..fd50100876 --- /dev/null +++ b/Lang/SETL/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/SETL \ No newline at end of file diff --git a/Lang/SETL/Range-consolidation b/Lang/SETL/Range-consolidation new file mode 120000 index 0000000000..b24d504011 --- /dev/null +++ b/Lang/SETL/Range-consolidation @@ -0,0 +1 @@ +../../Task/Range-consolidation/SETL \ No newline at end of file diff --git a/Lang/Standard-ML/Averages-Mean-angle b/Lang/Standard-ML/Averages-Mean-angle new file mode 120000 index 0000000000..38ef0bd393 --- /dev/null +++ b/Lang/Standard-ML/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Averages-Simple-moving-average b/Lang/Standard-ML/Averages-Simple-moving-average new file mode 120000 index 0000000000..6dd59a5e2f --- /dev/null +++ b/Lang/Standard-ML/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Standard-ML \ No newline at end of file diff --git a/Lang/V-(Vlang)/00-LANG.txt b/Lang/V-(Vlang)/00-LANG.txt index dfc23e4e27..d8ee4e2c69 100644 --- a/Lang/V-(Vlang)/00-LANG.txt +++ b/Lang/V-(Vlang)/00-LANG.txt @@ -13,7 +13,7 @@ ''Simple, fast, safe, compiled. For developing maintainable software.''

-'''Note: V is also known as Vlang. There was a language naming collision, so V (Vlang) was chosen.''' +'''Note: V (or Vlang). There was a language naming collision, so V (Vlang) was chosen.''' V (Vlang) is used here on Rosetta Code to disambiguate from the other language called [[:Category:V|V]]. @@ -38,55 +38,41 @@ V language review and documentation are [https://github.com/vlang/v/blob/master/ * More info on the below can be found at [https://modules.vlang.io/ modules used by V] {| class="wikitable" -! No. !! Module name !! !! No. !! Module name +! No. !! Module name !! !! No. !! Module name !! !! No. !! Module name |- -| 1 || [https://rosettacode.org/wiki/Category:Vlang-arrays arrays] || || 2 || [https://rosettacode.org/wiki/Category:Vlang-benchmark benchmark] +| 1 || [https://modules.vlang.io/arrays.html arrays] || || 2 || [https://modules.vlang.io/benchmark.html benchmark] || || 3 || [https://modules.vlang.io/bitfield.html bifield] |- -| 3 || [https://rosettacode.org/wiki/Category:Vlang-bifield bifield] || || 4 || [https://rosettacode.org/wiki/Category:Vlang-cli cli] +| 4 || [https://modules.vlang.io/cli.html cli] || || 5 || [https://modules.vlang.io/clipboard.html clipboard] || || 6 || [https://modules.vlang.io/compress.html compress] |- -| 5 || [https://rosettacode.org/wiki/Category:Vlang-clipboard clipboard] || || 6 || [https://rosettacode.org/wiki/Category:Vlang-compress compress] +| 7 || [https://modules.vlang.io/context.html context] || || 8 || [https://modules.vlang.io/crypto.html crypto] || || 9 || [https://modules.vlang.io/net.websocket.html websocket] |- -| 7 || [https://rosettacode.org/wiki/Category:Vlang-context context] || || 8 || [https://rosettacode.org/wiki/Category:Vlang-crypto crypto] +| 10 || [https://modules.vlang.io/datatypes.html datatypes] || || 11 || [https://modules.vlang.io/main.html main] || || 12 || [https://modules.vlang.io/dl.html dl] |- -| 9 || [https://rosettacode.org/wiki/Category:Vlang-darwin darwin] || || 10 || [https://rosettacode.org/wiki/Category:Vlang-datatypes datatypes] +| 13 || [https://modules.vlang.io/dlmalloc.html dlmalloc] || || 14 || [https://modules.vlang.io/encoding.html encoding] || || 15 || [https://modules.vlang.io/eventbus.html eventbus] |- -| 11 || [https://rosettacode.org/wiki/Category:Vlang-main main] || || 12 || [https://rosettacode.org/wiki/Category:Vlang-dl dl] +| 16 || [https://modules.vlang.io/flag.html flag] || || 17 || [https://modules.vlang.io/fontstash.html fontstash] || || 18 || [https://modules.vlang.io/gg.html gg] |- -| 13 || [https://rosettacode.org/wiki/Category:Vlang-dlmalloc dlmalloc] || || 14 || [https://rosettacode.org/wiki/Category:Vlang-encoding encoding] +| 19 || [https://modules.vlang.io/gx.html gx] || || 20 || [https://modules.vlang.io/hash.html hash] || || 21 || [https://modules.vlang.io/io.html io] |- -| 15 || [https://rosettacode.org/wiki/Category:Vlang-eventbus eventbus] || || 16 || [https://rosettacode.org/wiki/Category:Vlang-flag flag] +| 22 || [https://modules.vlang.io/json.html json] || || 23 || [https://modules.vlang.io/log.html log] || || 24 || [https://modules.vlang.io/math.html math] |- -| 17 || [https://rosettacode.org/wiki/Category:Vlang-fontstash fontstash] || || 18 || [https://rosettacode.org/wiki/Category:Vlang-gg gg] +| 25 || [https://modules.vlang.io/db.mssql.html mssql] || || 26 || [https://modules.vlang.io/db.mysql.html mysql] || || 27 || [https://modules.vlang.io/net.html net] |- -| 19 || [https://rosettacode.org/wiki/Category:Vlang-gx gx] || || 20 || [https://rosettacode.org/wiki/Category:Vlang-crypto hash] +| 28 || [https://modules.vlang.io/orm.html orm] || || 29 || [https://modules.vlang.io/os.html os] || || 30 || [https://modules.vlang.io/pg.html pg] |- -| 21 || [https://rosettacode.org/wiki/Category:Vlang-io io] || || 22 || [https://rosettacode.org/wiki/Category:Vlang-json json] +| 31 || [https://modules.vlang.io/picoev.html picoev] || || 32 || [https://modules.vlang.io/veb.html veb] || || 33 || [https://modules.vlang.io/picohttpparser.html picohttpparser] |- -| 23 || [https://rosettacode.org/wiki/Category:Vlang-log log] || || 24 || [https://rosettacode.org/wiki/Category:Vlang-math math] +| 34 || [https://modules.vlang.io/rand.html rand]|| || 35 || [https://modules.vlang.io/readline.html readline] || || 36 || [https://modules.vlang.io/regex.html regex] |- -| 25 || [https://rosettacode.org/wiki/Category:Vlang-mssql mssql] || || 26 || [https://rosettacode.org/wiki/Category:Vlang-mysql mysql] +| 37 || [https://modules.vlang.io/runtime.html runtime] || || 38 || [https://modules.vlang.io/semver.html semver] || || 39 || [https://modules.vlang.io/sokol.sapp.html sokol.sapp] |- -| 27 || [https://rosettacode.org/wiki/Category:Vlang-net net] || || 28 || [https://rosettacode.org/wiki/Category:Vlang-orm orm] +| 40 || [https://modules.vlang.io/db.sqlite.html sqlite] || || 41 || [https://modules.vlang.io/stbi.html stbi] || || 42 || [https://modules.vlang.io/strconv.html strconv] |- -| 29 || [https://rosettacode.org/wiki/Category:Vlang-os os] || || 30 || [https://rosettacode.org/wiki/Category:Vlang-pg pg] +| 43 || [https://modules.vlang.io/strings.html strings] || || 44 || [https://modules.vlang.io/sync.html sync] || || 45 || [https://modules.vlang.io/szip.html szip] |- -| 31 || [https://rosettacode.org/wiki/Category:Vlang-picoev picoev] || || 32 || [https://rosettacode.org/wiki/Category:Vlang-veb veb] +| 46 || [https://modules.vlang.io/term.html term] || || 47 || [https://modules.vlang.io/time.html time] || || 48 || [https://modules.vlang.io/toml.html toml] |- -| 33 || [https://rosettacode.org/wiki/Category:Vlang-picohttpparser picohttpparser] || || 34 || [https://rosettacode.org/wiki/Category:Vlang-rand rand] +| 49 || [https://modules.vlang.io/vweb.html vweb] || || 50 || [https://modules.vlang.io/wasm.html wasm] || || 51 || [https://modules.vlang.io/maps.html maps] |- -| 35 || [https://rosettacode.org/wiki/Category:Vlang-readline readline] || || 36 || [https://rosettacode.org/wiki/Category:Vlang-regex regex] -|- -| 37 || [https://rosettacode.org/wiki/Category:Vlang-runtime runtime] || || 38 || [https://rosettacode.org/wiki/Category:Vlang-semver semver] -|- -| 39 || [https://rosettacode.org/wiki/Category:Vlang-sokol sokol] || || 40 || [https://rosettacode.org/wiki/Category:Vlang-sqlite sqlite] -|- -| 41 || [https://rosettacode.org/wiki/Category:Vlang-stbi stbi] || || 42 || [https://rosettacode.org/wiki/Category:Vlang-strconv strconv] -|- -| 43 || [https://rosettacode.org/wiki/Category:Vlang-strings strings] || || 44 || [https://rosettacode.org/wiki/Category:Vlang-sync sync] -|- -| 45 || [https://rosettacode.org/wiki/Category:Vlang-szip szip] || || 46 || [https://rosettacode.org/wiki/Category:Vlang-term term] -|- -| 47 || [https://rosettacode.org/wiki/Category:Vlang-time time] || || 48 || [https://rosettacode.org/wiki/Category:Vlang-toml toml] -|- -| 49 || [https://rosettacode.org/wiki/Category:Vlang-vweb vweb] || || 50 || [https://rosettacode.org/wiki/Category:Vlang-wasm wasm] +| 52 || [https://modules.vlang.io/sokol.audio.html sokol.audio] || || 53 || [https://modules.vlang.io/x.ttf.html ttf] || || 54 || [https://modules.vlang.io/x.json2.html json2] |} \ No newline at end of file diff --git a/Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month b/Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..8c3dbc9a79 --- /dev/null +++ b/Lang/V-(Vlang)/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Monads-List-monad b/Lang/V-(Vlang)/Monads-List-monad new file mode 120000 index 0000000000..60c249323a --- /dev/null +++ b/Lang/V-(Vlang)/Monads-List-monad @@ -0,0 +1 @@ +../../Task/Monads-List-monad/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Pascals-triangle b/Lang/V-(Vlang)/Pascals-triangle new file mode 120000 index 0000000000..91982b11d4 --- /dev/null +++ b/Lang/V-(Vlang)/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Probabilistic-choice b/Lang/V-(Vlang)/Probabilistic-choice new file mode 120000 index 0000000000..5f44e37240 --- /dev/null +++ b/Lang/V-(Vlang)/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet b/Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..9c6f1c38d1 --- /dev/null +++ b/Lang/V-(Vlang)/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Word-frequency b/Lang/V-(Vlang)/Word-frequency new file mode 120000 index 0000000000..7472df9d00 --- /dev/null +++ b/Lang/V-(Vlang)/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/V-(Vlang) \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Execute-Brain- b/Lang/Visual-Basic-.NET/Execute-Brain- new file mode 120000 index 0000000000..40c465e5ff --- /dev/null +++ b/Lang/Visual-Basic-.NET/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/XPL0/Count-the-coins b/Lang/XPL0/Count-the-coins new file mode 120000 index 0000000000..7a91396756 --- /dev/null +++ b/Lang/XPL0/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Currency b/Lang/XPL0/Currency new file mode 120000 index 0000000000..05aee1c3b1 --- /dev/null +++ b/Lang/XPL0/Currency @@ -0,0 +1 @@ +../../Task/Currency/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Gaussian-elimination b/Lang/XPL0/Gaussian-elimination new file mode 120000 index 0000000000..6a178b8f16 --- /dev/null +++ b/Lang/XPL0/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/IBAN b/Lang/XPL0/IBAN new file mode 120000 index 0000000000..ce771b5589 --- /dev/null +++ b/Lang/XPL0/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Left-factorials b/Lang/XPL0/Left-factorials new file mode 120000 index 0000000000..c9ff64d1b6 --- /dev/null +++ b/Lang/XPL0/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Long-primes b/Lang/XPL0/Long-primes new file mode 120000 index 0000000000..4b515cb676 --- /dev/null +++ b/Lang/XPL0/Long-primes @@ -0,0 +1 @@ +../../Task/Long-primes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Modified-random-distribution b/Lang/XPL0/Modified-random-distribution new file mode 120000 index 0000000000..dfbceea492 --- /dev/null +++ b/Lang/XPL0/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sierpinski-square-curve b/Lang/XPL0/Sierpinski-square-curve new file mode 120000 index 0000000000..f8060a7322 --- /dev/null +++ b/Lang/XPL0/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Subtractive-generator b/Lang/XPL0/Subtractive-generator new file mode 120000 index 0000000000..e69b094ce6 --- /dev/null +++ b/Lang/XPL0/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Thieles-interpolation-formula b/Lang/XPL0/Thieles-interpolation-formula new file mode 120000 index 0000000000..fcd209a547 --- /dev/null +++ b/Lang/XPL0/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/World-Cup-group-stage b/Lang/XPL0/World-Cup-group-stage new file mode 120000 index 0000000000..4312a43d55 --- /dev/null +++ b/Lang/XPL0/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/XPL0 \ No newline at end of file diff --git a/Lang/Yabasic/Averages-Mean-angle b/Lang/Yabasic/Averages-Mean-angle new file mode 120000 index 0000000000..ee2478f1ef --- /dev/null +++ b/Lang/Yabasic/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Yabasic \ No newline at end of file diff --git a/Task/100-doors/00-TASK.txt b/Task/100-doors/00-TASK.txt index fd7471448b..f3737c40a0 100644 --- a/Task/100-doors/00-TASK.txt +++ b/Task/100-doors/00-TASK.txt @@ -20,3 +20,8 @@ Opening only those doors is an   [[task feature::Rosetta Code:optimization| however, as should be obvious, this defeats the intent of comparing implementations across programming languages.

+;Why doesn't syntax highlighting work on this page ?: +Currently, there is a limit on how many <syntaxhighlight> tags can appear on a page, so only the first few languages get highlighting, the rest are shown in monochrome.
+You could try "manual highlighting", possibly using one of the highlighters on [[Syntax highlighting using Mediawiki formatting]] or something similar. + + diff --git a/Task/100-doors/Plain-English/100-doors.plain b/Task/100-doors/Plain-English/100-doors.plain index f6ee5c1b2e..809fe08e73 100644 --- a/Task/100-doors/Plain-English/100-doors.plain +++ b/Task/100-doors/Plain-English/100-doors.plain @@ -6,6 +6,7 @@ Clear the door's flag. Append the door to the doors. Repeat. +A flag thing is a thing with a flag. A door is a flag thing. To go through some doors given a number and some passes: diff --git a/Task/100-doors/YAMLScript/100-doors.ys b/Task/100-doors/YAMLScript/100-doors.ys index 918b5e5f0a..23c45269c2 100644 --- a/Task/100-doors/YAMLScript/100-doors.ys +++ b/Task/100-doors/YAMLScript/100-doors.ys @@ -1,17 +1,14 @@ !yamlscript/v0 defn main(): - say: |- - Open doors after 100 passes: - $(open-doors().join(', ')) - -defn open-doors(): - ? for [d n] map(vector doors() range().drop(1)) - :when d - : n - -defn doors(): - reduce: - fn(doors idx): doors.assoc(idx true) - into []: repeat(100 false) - map \(sqr(_).--): 1 .. 10 + open =: + reduce _ vec([true] * 100) (1 .. 100): + fn(doors i): + loop j i, doors doors: + if j < 100: + recur (j + i).++: + update-in doors [j]: \(doors.$j.!) + else: doors + say: -"Open doors after 100 passes:\ " + + (1 .. 100).map(\(_.--:open && _)) + .filter(a).join(', ') diff --git a/Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic b/Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic new file mode 100644 index 0000000000..4dcdf807c9 --- /dev/null +++ b/Task/15-puzzle-solver/FreeBASIC/15-puzzle-solver.basic @@ -0,0 +1,288 @@ +Randomize Timer + +Dim Shared As Integer Nr(15) = {3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3} +Dim Shared As Integer Nc(15) = {3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2} +Dim Shared As Integer n, nn +Dim Shared As Integer N0(99), N3(100), N4(99) +Dim Shared As Ulongint N2(99) + +Enum + Ki = 1 + Kg = 8 + Ke = 2 + Kl = 4 +End Enum + +Dim Shared As Integer l = 108, r = 114, u = 117, d = 100 + +Declare Function fY() As Boolean +Declare Function fZ(w As Integer) As Boolean +Declare Function fN() As Boolean + +Sub fI() + Dim As Integer g = (11 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) + 4 + N2(n + 1) = N2(n) - a + (a Shl 16) + N3(n + 1) = d + N4(n + 1) = N4(n) + If Not(Nr((a Shr g)) <= N0(n)\4) Then N4(n + 1) += 1 + n += 1 +End Sub + +Sub fG() + Dim As Integer g = (19 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) - 4 + N2(n + 1) = N2(n) - a + (a Shr 16) + N3(n + 1) = u + N4(n + 1) = N4(n) + If Not(Nr((a Shr g)) >= N0(n)\4) Then N4(n + 1) += 1 + n += 1 +End Sub + +Sub fE() + Dim As Integer g = (14 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) + 1 + N2(n + 1) = N2(n) - a + (a Shl 4) + N3(n + 1) = r + N4(n + 1) = N4(n) + If Not(Nc((a Shr g)) <= (N0(n) Mod 4)) Then N4(n + 1) += 1 + n += 1 +End Sub + +Sub fL() + Dim As Integer g = (16 - N0(n)) * 4 + Dim As Ulongint a = (N2(n) And (15ULL Shl g)) + N0(n + 1) = N0(n) - 1 + N2(n + 1) = N2(n) - a + (a Shr 4) + N3(n + 1) = l + N4(n + 1) = N4(n) + If Not(Nc((a Shr g)) >= (N0(n) Mod 4)) Then N4(n + 1) += 1 + n += 1 +End Sub + +Function fY() As Boolean + If N2(n) = &h123456789abcdef0ULL Then Return True + If N4(n) <= nn Then Return fN() + Return False +End Function + +Function fZ(w As Integer) As Boolean + If (w And Ki) > 0 Then + fI() + If fY() Then Return True + n -= 1 + End If + If (w And Kg) > 0 Then + fG() + If fY() Then Return True + n -= 1 + End If + If (w And Ke) > 0 Then + fE() + If fY() Then Return True + n -= 1 + End If + If (w And Kl) > 0 Then + fL() + If fY() Then Return True + n -= 1 + End If + Return False +End Function + +Function fN() As Boolean + Select Case N0(n) + Case 0 + Select Case N3(n) + Case l: Return fZ(Ki) + Case u: Return fZ(Ke) + Case Else: Return fZ(Ki Or Ke) + End Select + Case 3 + Select Case N3(n) + Case r: Return fZ(Ki) + Case u: Return fZ(Kl) + Case Else: Return fZ(Ki Or Kl) + End Select + Case 1, 2 + Select Case N3(n) + Case l: Return fZ(Ki Or Kl) + Case r: Return fZ(Ki Or Ke) + Case u: Return fZ(Ke Or Kl) + Case Else: Return fZ(Kl Or Ke Or Ki) + End Select + Case 12 + Select Case N3(n) + Case l: Return fZ(Kg) + Case d: Return fZ(Ke) + Case Else: Return fZ(Ke Or Kg) + End Select + Case 15 + Select Case N3(n) + Case r: Return fZ(Kg) + Case d: Return fZ(Kl) + Case Else: Return fZ(Kg Or Kl) + End Select + Case 13, 14 + Select Case N3(n) + Case l: Return fZ(Kg Or Kl) + Case r: Return fZ(Ke Or Kg) + Case d: Return fZ(Ke Or Kl) + Case Else: Return fZ(Kg Or Ke Or Kl) + End Select + Case 4, 8 + Select Case N3(n) + Case l: Return fZ(Ki Or Kg) + Case u: Return fZ(Kg Or Ke) + Case d: Return fZ(Ki Or Ke) + Case Else: Return fZ(Ki Or Kg Or Ke) + End Select + Case 7, 11 + Select Case N3(n) + Case d: Return fZ(Ki Or Kl) + Case u: Return fZ(Kg Or Kl) + Case r: Return fZ(Ki Or Kg) + Case Else: Return fZ(Ki Or Kg Or Kl) + End Select + Case Else + Select Case N3(n) + Case d: Return fZ(Ki Or Ke Or Kl) + Case l: Return fZ(Ki Or Kg Or Kl) + Case r: Return fZ(Ki Or Kg Or Ke) + Case u: Return fZ(Kg Or Ke Or Kl) + Case Else: Return fZ(Ki Or Kg Or Ke Or Kl) + End Select + End Select +End Function + +Sub solve() + If fN() Then + Exit Sub + Else + n = 0 + nn += 1 + solve() + End If +End Sub + +Function createPuzzle(Byval j As Integer) As Ulongint + Dim As Ulongint q = &h123456789abcdef0ULL + Dim As String h = Hex(q, 16) + Dim As Integer z, d, r, u = 0 + While j > 0 ' number of moves to do + Do + d = Int(Rnd * 4) + 1 + Loop While d = u + u = -d + r = Int(Rnd * 3) + 1 + While r > 0 + z = Instr(h, "0") + Select Case d + Case 1 ' -1 + If (z Mod 4) <> 1 Then + Mid(h, z, 1) = Mid(h, z - 1, 1) + Mid(h, z - 1, 1) = "0" + j -= 1 + End If + Case 2 ' +1 + If (z Mod 4) <> 0 Then + Mid(h, z, 1) = Mid(h, z + 1, 1) + Mid(h, z + 1, 1) = "0" + j -= 1 + End If + Case 3 ' -4 + If z >= 5 Then + Mid(h, z, 1) = Mid(h, z - 4, 1) + Mid(h, z - 4, 1) = "0" + j -= 1 + End If + Case 4 ' +4 + If z <= 12 Then + Mid(h, z, 1) = Mid(h, z + 4, 1) + Mid(h, z + 4, 1) = "0" + j -= 1 + End If + End Select + r -= 1 + Wend + Wend + Return Valulng("&h" + h) +End Function + +Sub ShowConfiguration(Byval h As String, i As Integer) + Dim As Integer r, c + Dim x As String + Color 14 + For r = 1 To 4 + For c = 1 To 4 + x = Mid(h, r * 4 - 4 + c, 1) + If x = "0" Then x = " " + Locate r + i, c + c - 1: Print x; + Next + Next + Color 7 +End Sub + +Sub shoWMoves(Byval h As String, Byval s As String, Byval m As Integer, Byval p As Integer) + Dim As Integer j, z, d + ShowConfiguration(h, 12) + For j = 1 To m + d = Asc(Mid(s, j, 1)) + z = Instr(h, "0") + Select Case d + Case l + If (z Mod 4) <> 1 Then + Mid(h, z, 1) = Mid(h, z - 1, 1) + Mid(h, z - 1, 1) = "0" + End If + Case r + If (z Mod 4) <> 0 Then + Mid(h, z, 1) = Mid(h, z + 1, 1) + Mid(h, z + 1, 1) = "0" + End If + Case u + If z >= 5 Then + Mid(h, z, 1) = Mid(h, z - 4, 1) + Mid(h, z - 4, 1) = "0" + End If + Case d + If z <= 12 Then + Mid(h, z, 1) = Mid(h, z + 4, 1) + Mid(h, z + 4, 1) = "0" + End If + End Select + ShowConfiguration(h, 12) + Sleep p + Next + Print +End Sub + +Sub fifteenSolver(Byval g As Ulongint, Byval p As Integer) + Dim As String h, s + Dim As Integer j + Dim As Double t0 = Timer + n = 0 + nn = 0 + h = Hex(g, 16) + Cls + Print "Puzzle: "; Lcase(h) + ShowConfiguration(h, 2) + Print Chr(10) + N0(0) = Instr(h, "0") - 1 + N2(0) = g + solve() + Print Using "Solution found in & moves: "; n; + For j = 1 To n + s &= Chr(N3(j)) + Next + Print s + Print Using !"\nTook ###.######## seconds on i5 @ 3.20 GHz"; Timer - t0 + If p Then showMoves(h, s, n, p) +End Sub + +fifteenSolver(&hfe169b4c0a73d852ULL, 1000) + +Sleep diff --git a/Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic b/Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic new file mode 100644 index 0000000000..16a309133a --- /dev/null +++ b/Task/15-puzzle-solver/FutureBasic/15-puzzle-solver.basic @@ -0,0 +1,165 @@ +// 15 Puzzle Solver +//https://rosettacode.org/wiki/15_puzzle_solver +// Requires FutureBasic 7.0.30 or later + +begin globals + int Nr(15), Nc(15), n, un, N0(99), N3(99), N4(99) + UInt64 N2(99) +end globals + +def fn fY as BOOL +void def fn fI +void def fn fG +void def fn fE +void def fn fL + +local fn fN1 as BOOL + if ( N3(n) != _"u" && N0(n) / 4 < 3 ) + fn fI + n++ + if ( fn fY ) then return YES + n-- + end if + + if ( N3(n) != _"d" && N0(n) / 4 > 0 ) + fn fG + n++ + if ( fn fY ) then return YES + n-- + end if + + if ( N3(n) != _"l" && N0(n) % 4 < 3 ) + fn fE + n++ + if ( fn fY ) then return YES + n-- + end if + + if ( N3(n) != _"r" && N0(n) %4 > 0 ) + fn fL + n++ + if ( fn fY ) then return YES + n-- + end if +end fn = NO + +void local fn fI + int g = ( 11 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) + 4 + N2(n + 1) = N2(n) - a + (a << 16) + N3(n + 1) = _"d" + if ( Nr(a >> g) <= N0(n) / 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +void local fn fG + int g = (19 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) - 4 + N2(n + 1) = N2(n) - a + (a >> 16) + N3(n + 1) = _"u" + if ( Nr(a >> g) >= N0(n) / 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +void local fn fE + int g = (14 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) + 1 + N2(n + 1) = N2(n) - a + (a << 4) + N3(n + 1) = _"r" + if ( Nc(a >> g) <= N0(n) % 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +void local fn fL + int g = (16 - N0(n)) * 4 + UInt64 a = N2(n) & ((UInt64)15 << g) + N0(n + 1) = N0(n) - 1 + N2(n + 1) = N2(n) - a + (a >> 4) + N3(n + 1) = _"l" + if ( Nc(a >> g) >= N0(n) % 4 ) + N4(n + 1) = N4(n) + else + N4(n + 1) = N4(n) + 1 + end if +end fn + +local fn fY as BOOL + if ( N4(n) < un ) then return fn fN1 + if ( N2(n) == 0x123456789abcdef0 ) + printf @"Solution found in %d moves:",n + for int g = 1 to n + printf @"%c\b",N3(g) + next + print + return YES + end if + if ( N4(n) == un ) then return fn fN1 +end fn = NO + +void local fn Solve( initN as int, initG as UInt64 ) + int tempNr(15) = {3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3} + int tempNc(15) = {3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2} + + fn memcpy(@Nr(0),@tempNr(0),sizeof(int)*16) + fn memcpy(@Nc(0),@tempNc(0),sizeof(int)*16) + + n = 0 + un = 0 + + N0(0) = initN + N2(0) = initG + + while ( !fn fY ) + un++ + wend +end fn + + +window 1, @"15 Puzzle Solver" +windowcenter(1) +WindowSetBackgroundColor(1,fn ColorBlack) + +text ,14,fn colorWhite +Print "Puzzle: "; "fe169b4c0a73d852" + +text ,14,fn colorYellow +print +print @"15 14 1 6" +print @" 9 11 4 12" +print @" 0 10 7 3" +print @"13 8 5 2" +print +text ,14,fn colorWhite + +CFStringRef ComputerChip = unix @"sysctl -n machdep.cpu.brand_string" + +CFTimeInterval t : t = fn CACurrentMediaTime +fn Solve( 8, 0xfe169b4c0a73d852 ) +CFTimeInterval CurrentTime = fn CACurrentMediaTime-t + +print +text ,14,fn colorYellow +print +print @" 1 2 3 4" +print @" 5 6 7 8" +print @" 9 10 11 12" +print @"13 14 15 0" +print +text ,14,fn colorWhite + +print : printf @"Compute time: %.3f seconds",(CurrentTime) +print ComputerChip + +HandleEvents diff --git a/Task/24-game/ALGOL-68/24-game.alg b/Task/24-game/ALGOL-68/24-game.alg index 3ba4ed6a03..b74144035a 100644 --- a/Task/24-game/ALGOL-68/24-game.alg +++ b/Task/24-game/ALGOL-68/24-game.alg @@ -40,7 +40,7 @@ BEGIN # play the 24 game - present the user with 4 digits and invite them to # error( "Unexpected """ + curr ch + """" ); 0 FI # factor # ; - PROC term = REAL: + PROC expr term = REAL: BEGIN REAL result := factor; WHILE curr ch = "*" OR curr ch = "/" DO @@ -49,14 +49,14 @@ BEGIN # play the 24 game - present the user with 4 digits and invite them to # IF op = "*" THEN result *:= factor ELSE result /:= factor FI OD; result - END # term # ; + END # expr term # ; PROC expression = REAL: BEGIN - REAL result := term; + REAL result := expr term; WHILE curr ch = "+" OR curr ch = "-" DO CHAR op = curr ch; next ch; - IF op = "+" THEN result +:= term ELSE result -:= term FI + IF op = "+" THEN result +:= expr term ELSE result -:= expr term FI OD; result END # expression # ; @@ -80,7 +80,7 @@ BEGIN # play the 24 game - present the user with 4 digits and invite them to # puzzle digits[ i ] := 0 OD; print( ( "Enter an expression using these digits:" ) ); - FOR i TO 4 DO # pick 4 random digits # + TO 4 DO # pick 4 random digits # INT digit := 1 + ENTIER ( next random * 9 ); IF digit > 9 THEN digit := 9 FI; puzzle digits[ digit ] +:= 1; diff --git a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys index d951447c6d..2ad5b109ca 100644 --- a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys +++ b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys @@ -1,7 +1,6 @@ !yamlscript/v0 defn main(number=99): - :: Print the verses to "99 Bottles of Beer" each num (number .. 1): say: | $bottles(num) of beer on the wall, diff --git a/Task/ABC-problem/ALGOL-68/abc-problem.alg b/Task/ABC-problem/ALGOL-68/abc-problem.alg index 524af00c33..11c3a41ade 100644 --- a/Task/ABC-problem/ALGOL-68/abc-problem.alg +++ b/Task/ABC-problem/ALGOL-68/abc-problem.alg @@ -1,21 +1,14 @@ +# ABC problem: # # determine whether we can spell words with a set of blocks # -# construct the list of blocks # -[][]STRING blocks = ( ( "B", "O" ), ( "X", "K" ), ( "D", "Q" ), ( "C", "P" ) - , ( "N", "A" ), ( "G", "T" ), ( "R", "E" ), ( "T", "G" ) - , ( "Q", "D" ), ( "F", "S" ), ( "J", "W" ), ( "H", "U" ) - , ( "V", "I" ), ( "A", "N" ), ( "O", "B" ), ( "E", "R" ) - , ( "F", "S" ), ( "L", "Y" ), ( "P", "C" ), ( "Z", "M" ) - ); - # Returns TRUE if we can spell the word using the blocks, FALSE otherwise # # Returns TRUE for an empty string # -PROC can spell = ( STRING word, [][]STRING blocks )BOOL: +PROC can spell = ( STRING word, [][]STRING block set )BOOL: BEGIN # construct a set of flags to indicate whether the blocks are used # # or not # - [ 1 LWB blocks : 1 UPB blocks ]BOOL used; + [ 1 LWB block set : 1 UPB block set ]BOOL used; FOR block pos FROM LWB used TO UPB used DO used[ block pos ] := FALSE @@ -34,11 +27,11 @@ PROC can spell = ( STRING word, [][]STRING blocks )BOOL: # look through the unused blocks for the current letter # BOOL found := FALSE; - FOR block pos FROM 1 LWB blocks TO 1 UPB blocks + FOR block pos FROM 1 LWB block set TO 1 UPB block set WHILE NOT found DO - IF ( c = blocks[ block pos ][ 1 ][ 1 ] - OR c = blocks[ block pos ][ 2 ][ 1 ] + IF ( c = block set[ block pos ][ 1 ][ 1 ] + OR c = block set[ block pos ][ 2 ][ 1 ] ) AND NOT used[ block pos ] THEN @@ -56,25 +49,33 @@ PROC can spell = ( STRING word, [][]STRING blocks )BOOL: END; # can spell # -main: ( +# main # ( + + [][]STRING abc blocks # construct the list of blocks # + = ( ( "B", "O" ), ( "X", "K" ), ( "D", "Q" ), ( "C", "P" ) + , ( "N", "A" ), ( "G", "T" ), ( "R", "E" ), ( "T", "G" ) + , ( "Q", "D" ), ( "F", "S" ), ( "J", "W" ), ( "H", "U" ) + , ( "V", "I" ), ( "A", "N" ), ( "O", "B" ), ( "E", "R" ) + , ( "F", "S" ), ( "L", "Y" ), ( "P", "C" ), ( "Z", "M" ) + ); # test the can spell procedure # - PROC test can spell = ( STRING word, [][]STRING blocks )VOID: + PROC test can spell = ( STRING word, [][]STRING block set )VOID: write( ( ( "can spell: """ + word + """ -> " - + IF can spell( word, blocks ) THEN "yes" ELSE "no" FI + + IF can spell( word, block set ) THEN "yes" ELSE "no" FI ) , newline ) ); - test can spell( "A", blocks ); - test can spell( "BaRK", blocks ); - test can spell( "BOOK", blocks ); - test can spell( "TREAT", blocks ); - test can spell( "COMMON", blocks ); - test can spell( "SQUAD", blocks ); - test can spell( "CONFUSE", blocks ) + test can spell( "A", abc blocks ); + test can spell( "BaRK", abc blocks ); + test can spell( "BOOK", abc blocks ); + test can spell( "TREAT", abc blocks ); + test can spell( "COMMON", abc blocks ); + test can spell( "SQUAD", abc blocks ); + test can spell( "CONFUSE", abc blocks ) ) diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix new file mode 100644 index 0000000000..da1bc84810 --- /dev/null +++ b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-1.phix @@ -0,0 +1,78 @@ +-- demo/rosetta/AKSprimes.exw +-- Does not work for primes above 67 (56 on 32bit), which is actually beyond the original task anyway. +-- Translated from the C version (with all out-by-1 stuff now eradicated). +with javascript_semantics +constant limit = iff(machine_bits()=32?56:67) +sequence c = repeat(0,limit+1) + +procedure coef(integer n) + c[n+1] = 1 + for i=n to 2 by -1 do + c[i] += c[i-1] + end for +end procedure + +function is_aks_prime(integer n) + coef(n) + for i=2 to n-1 do + if remainder(c[i],n)!=0 then + return false + end if + end for + return true +end function + +procedure show(integer n) + for i=n+1 to 1 by -1 do + object ci = c[i] + if ci=1 then + if remainder(n-i+1,2)=0 then + if i=1 then + if n=0 then + ci = "1" + else + ci = "+1" + end if + else + ci = "" + end if + else + ci = "-1" + end if + else + if remainder(n-i+1,2)=0 then + ci = sprintf("+%d",ci) + else + ci = sprintf("-%d",ci) + end if + end if + if i=1 then -- ie ^0 + printf(1,"%s",{ci}) + elsif i=2 then -- ie ^1 + printf(1,"%sx",{ci}) + else + printf(1,"%sx^%d",{ci,i-1}) + end if + end for +end procedure + +procedure main() + for n=0 to 9 do + coef(n); + printf(1,"(x-1)^%d = ", n); + show(n); + puts(1,'\n'); + end for + + printf(1,"\nprimes (<=%d):",limit); +-- coef(1); -- (needed to reset c, if we want to avoid saying 1 is prime...) + c[2] = 1 -- (this manages "", which is all that call did anyway...) + for n=2 to limit do + if is_aks_prime(n) then + printf(1," %d", n); + end if + end for + puts(1,'\n'); + wait_key() +end procedure +main() diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix new file mode 100644 index 0000000000..f8bd4ad4ab --- /dev/null +++ b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-2.phix @@ -0,0 +1,27 @@ +include mpfr.e +mpz z = mpz_init() +atom t0 = time(), t1 = t0+1 +sequence p = {} +integer maxn = 0 +for n=2 to 10000 do -- (more than we can manage in 10s) + bool nprime = true + for k=1 to n-1 do + mpz_bin_uiui(z,n,k) + if not mpz_divisible_ui_p(z,n) then + nprime = false + exit + end if + end for + if nprime then + p &= n + end if + maxn = n + if time()>t1 then + if time()>t0+10 then progress("") exit end if + progress("checking %d",{n}) + t1 = time()+1 + end if +end for +sequence q = get_primes_le(maxn) +printf(1,"%d primes < %d found, correctly:%t, in %s\n",{length(p),maxn,p=q,elapsed(time()-t0)}) +wait_key() diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix new file mode 100644 index 0000000000..bfa4d0b3d9 --- /dev/null +++ b/Task/AKS-test-for-primes/Phix/aks-test-for-primes-3.phix @@ -0,0 +1,24 @@ +atom t0 = time(), t1 = t0+1 +sequence p = {} +integer maxn = 0 +for n=2 to 10000 do -- (more than we can manage in 10s) + sequence r = {1} + for k=1 to n do + r &= 1 + for l=k to 2 by -1 do + r[l] = remainder(r[l]+r[l-1],n) + end for + end for + if sum(r)=2 then -- ie {1,<==all 0s==>,1} + p &= n + end if + maxn = n + if time()>t1 then + if time()>t0+10 then progress("") exit end if + progress("checking %d",{n}) + t1 = time()+1 + end if +end for +sequence q = get_primes_le(maxn) +printf(1,"%d primes < %d found, correctly:%t, in %s\n",{length(p),maxn,p=q,elapsed(time()-t0)}) +wait_key() diff --git a/Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix b/Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix deleted file mode 100644 index 384e622777..0000000000 --- a/Task/AKS-test-for-primes/Phix/aks-test-for-primes.phix +++ /dev/null @@ -1,82 +0,0 @@ ---> - -- demo/rosetta/AKSprimes.exw - -- Does not work for primes above 53, which is actually beyond the original task anyway. - -- Translated from the C version, just about everything is (working) out-by-1, what fun. - - sequence c = repeat(0,100) - - procedure coef(integer n) - -- out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 etc. - c[n] = 1 - for i=n-1 to 2 by -1 do - c[i] = c[i]+c[i-1] - end for - end procedure - - function is_aks_prime(integer n) - coef(n+1); -- (I said it was out-by-1) - for i=2 to n-1 do -- (technically "to n" is more correct) - if remainder(c[i],n)!=0 then - return 0 - end if - end for - return 1 - end function - - procedure show(integer n) - -- (As per coef, this is (working) out-by-1) - object ci - for i=n to 1 by -1 do - ci = c[i] - if ci=1 then - if remainder(n-i,2)=0 then - if i=1 then - if n=1 then - ci = "1" - else - ci = "+1" - end if - else - ci = "" - end if - else - ci = "-1" - end if - else - if remainder(n-i,2)=0 then - ci = sprintf("+%d",ci) - else - ci = sprintf("-%d",ci) - end if - end if - if i=1 then -- ie ^0 - printf(1,"%s",{ci}) - elsif i=2 then -- ie ^1 - printf(1,"%sx",{ci}) - else - printf(1,"%sx^%d",{ci,i-1}) - end if - end for - end procedure - - procedure main() - for n=1 to 10 do -- (0 to 9 really) - coef(n); - printf(1,"(x-1)^%d = ", n-1); - show(n); - puts(1,'\n'); - end for - - puts(1,"\nprimes (<=53):"); - -- coef(2); -- (needed to reset c, if we want to avoid saying 1 is prime...) - c[2] = 1 -- (this manages "", which is all that call did anyway...) - for n = 2 to 53 do - if is_aks_prime(n) then - printf(1," %d", n); - end if - end for - puts(1,'\n'); - if getc(0) then end if - end procedure - main() - - with javascript_semantics - function direct_form_II_transposed_filter(sequence a, b, signal) - sequence result = repeat(0,length(signal)) - for i=1 to length(signal) do - atom tmp = 0 - for j=1 to min(i,length(b)) do tmp += b[j]*signal[i-j+1] end for - for j=2 to min(i,length(a)) do tmp -= a[j]*result[i-j+1] end for - result[i] = tmp/a[1] - end for - return result - end function +with javascript_semantics +function direct_form_II_transposed_filter(sequence a, b, signal) + sequence result = repeat(0,length(signal)) + for i=1 to length(signal) do + atom tmp = 0 + for j=1 to min(i,length(b)) do tmp += b[j]*signal[i-j+1] end for + for j=2 to min(i,length(a)) do tmp -= a[j]*result[i-j+1] end for + result[i] = tmp/a[1] + end for + return result +end function - constant acoef = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}, - bcoef = {0.16666667, 0.5, 0.5, 0.16666667}, - signal = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973, - -1.00700480494,-0.404707073677,0.800482325044,0.743500089861,1.01090520172, - 0.741527555207,0.277841675195,0.400833448236,-0.2085993586,-0.172842103641, - -0.134316096293,0.0259303398477,0.490105989562,0.549391221511,0.9047198589} +constant acoef = {1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}, + bcoef = {0.16666667, 0.5, 0.5, 0.16666667}, + signal = {-0.917843918645,0.141984778794,1.20536903482,0.190286794412,-0.662370894973, + -1.00700480494,-0.404707073677,0.800482325044,0.743500089861,1.01090520172, + 0.741527555207,0.277841675195,0.400833448236,-0.2085993586,-0.172842103641, + -0.134316096293,0.0259303398477,0.490105989562,0.549391221511,0.9047198589} - pp(direct_form_II_transposed_filter(acoef, bcoef, signal),{pp_FltFmt,"%9.6f",pp_Maxlen,110}) - + print obj + print @"no exception" + end try + + catch ( e ) // handle exception + print : print @"" + print e + end catch + + finally // finally is always executed + print : print @"" + + // ... cleanup + + end finally +end fn + +fn DoSomething + +HandleEvents diff --git a/Task/Exceptions/FutureBasic/exceptions-2.basic b/Task/Exceptions/FutureBasic/exceptions-2.basic new file mode 100644 index 0000000000..203d2eb6c3 --- /dev/null +++ b/Task/Exceptions/FutureBasic/exceptions-2.basic @@ -0,0 +1,15 @@ +void local fn ThrowException + ExceptionRef e = fn ExceptionWithName( @"Oops!", @"Something went wrong", NULL ) + + try + throw e + end try + + catch (e) + print fn ExceptionName( e ), fn ExceptionReason( e ) + end catch +end fn + +fn ThrowException + +HandleEvents diff --git a/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg b/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg index c74c21fd7b..6f36b9cea2 100644 --- a/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg +++ b/Task/Execute-Brain-/ALGOL-68/execute-brain--1.alg @@ -86,11 +86,10 @@ BEGIN # Brain**** -> Algol 68 transpiler # # get the code to transpile and output it as a comment at the start # # of the code # print( ( "CO BF> " ) ); - STRING code list; - read( ( code list, newline ) ); - print( ( newline, code list, newline, "CO", newline ) ); + STRING bf code; + read( ( bf code, newline ) ); + print( ( newline, bf code, newline, "CO", newline ) ); # transpile the code # - generate( code list ) - + generate( bf code ) END diff --git a/Task/Execute-Brain-/Pike/execute-brain-.pike b/Task/Execute-Brain-/Pike/execute-brain-.pike new file mode 100644 index 0000000000..d4cc02b12c --- /dev/null +++ b/Task/Execute-Brain-/Pike/execute-brain-.pike @@ -0,0 +1,39 @@ +string prog = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; + +void main() { + array tape = allocate(30000); + int p; + int l = strlen(prog); + for (int i = 0; i < l; i++) { + switch (prog[i]) { + case '>': + p++; + break; + case '<': + p--; + break; + case '+': + tape[p]++; + break; + case '-': + tape[p]--; + break; + case '.': + write(sprintf("%c", tape[p])); // ascii only + break; + case ',': + tape[p] = Stdio.stdin.getchar(); + break; + case '[': + if (!tape[p]) + for (int nest = 1; nest;) + prog[--i] == ']' ? nest-- : prog[i] == '[' ? nest++ : 0; + break; + case ']': + if (tape[p]) + for (int nest = 1; nest;) + prog[--i] == '[' ? nest-- : prog[i] == ']' ? nest++ : 0; + break; + } + } +} diff --git a/Task/Execute-Brain-/Visual-Basic-.NET/execute-brain-.vb b/Task/Execute-Brain-/Visual-Basic-.NET/execute-brain-.vb new file mode 100644 index 0000000000..b258dd7b25 --- /dev/null +++ b/Task/Execute-Brain-/Visual-Basic-.NET/execute-brain-.vb @@ -0,0 +1,70 @@ +Imports System + +Module Program + Sub Main(args As String()) + Brainfug("++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.") + End Sub + + Sub Brainfug(code As String, Optional input As String = Nothing) + Dim inp As Integer = 1 ' input pointer if we use an input string + Dim tape(29999) As Integer ' yes, 29999 makes an array of 30000 + Dim p As Integer + For i = 1 To code.Length + Dim c As Char = Mid(code, i, 1) + Select c + Case ">" + p += 1 + Case "<" + p -= 1 + Case "+" + tape(p) += 1 + Case "-" + tape(p) -= 1 + Case "." + Try + Console.Write(Chr(tape(p))) + Catch ex As NotSupportedException + Console.Write(".") + End Try + Case "," + If input Is Nothing then + tape(p) = Console.Read() + Else + Try + tape(p) = AscW(Mid(input, inp, 1)) + Catch ex As ArgumentException + Console.WriteLine("Panic: Out of input!") + Environment.Exit(1) + End Try + inp += 1 + End If + Case "[" + If tape(p) = 0 + Dim nest = 1 + While nest + i += 1 + Select Mid(code, i, 1) + Case "]" + nest -= 1 + Case "[" + nest += 1 + End Select + End While + End If + Case "]" + If tape(p) <> 0 + Dim nest = 1 + While nest + i -= 1 + Select Mid(code, i, 1) + Case "[" + nest -= 1 + Case "]" + nest += 1 + End Select + End While + End If + End Select + Next + End Sub +End Module diff --git a/Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas b/Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas new file mode 100644 index 0000000000..ab758487a0 --- /dev/null +++ b/Task/Execute-a-system-command/PascalABC.NET/execute-a-system-command.pas @@ -0,0 +1,2 @@ +## +exec('cmd.exe','/c dir /p'); diff --git a/Task/Exponentiation-order/PascalABC.NET/exponentiation-order.pas b/Task/Exponentiation-order/PascalABC.NET/exponentiation-order.pas new file mode 100644 index 0000000000..d38b6a0302 --- /dev/null +++ b/Task/Exponentiation-order/PascalABC.NET/exponentiation-order.pas @@ -0,0 +1,4 @@ +## +println('5**3**2 =',5**3**2); +println('(5**3)**2 =',(5**3)**2); +println('5**(3**2) =',5**(3**2)); diff --git a/Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/PascalABC.NET/exponentiation-with-infix-operators-in-or-operating-on-the-base.pas b/Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/PascalABC.NET/exponentiation-with-infix-operators-in-or-operating-on-the-base.pas new file mode 100644 index 0000000000..5a551f50f0 --- /dev/null +++ b/Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/PascalABC.NET/exponentiation-with-infix-operators-in-or-operating-on-the-base.pas @@ -0,0 +1,6 @@ +## +foreach var x in |-5, 5| do + foreach var p in |2, 3| do + writeln('x is ', x:2, ', p is ', p:1, ', ', + '-x**p is ', -x ** p:4, ', -(x)**p is ', -(x) ** p:4, ', ', + '(-x)**p is ', (-x) ** p:4, ', ', '-(x**p) is ', -(x ** p):4); diff --git a/Task/Extend-your-language/M2000-Interpreter/extend-your-language.m2000 b/Task/Extend-your-language/M2000-Interpreter/extend-your-language.m2000 index d3b25c299f..fb9dc63d17 100644 --- a/Task/Extend-your-language/M2000-Interpreter/extend-your-language.m2000 +++ b/Task/Extend-your-language/M2000-Interpreter/extend-your-language.m2000 @@ -21,7 +21,7 @@ ctrl=true for a=1 to 2 for b=1 to 2 Print "a=";a, "b=";b - if2 a=1, b=2, &ctrl : Part { + if2 a=1, b=1, &ctrl : Part { print "both", a, b } as ctrl ifelse1 : Part { diff --git a/Task/Extend-your-language/PascalABC.NET/extend-your-language.pas b/Task/Extend-your-language/PascalABC.NET/extend-your-language.pas new file mode 100644 index 0000000000..4c4c00b38e --- /dev/null +++ b/Task/Extend-your-language/PascalABC.NET/extend-your-language.pas @@ -0,0 +1,24 @@ +const + ifboth = 0; + else1 = 1; + else2 = 2; + else3 = 3; + +function operator **(x, y: boolean): integer; extensionmethod; +begin + if x and y then result := ifboth + else + if x then result := else1 + else + if y then result := else2 + else result := else3 +end; + +begin + case (2 > 1) ** (3 < 2) of + ifboth: 'both are true'.println; + else1: 'the first is true'.println; + else2: 'the second is true'.println; + else3: 'both are false'.println; + end; +end. diff --git a/Task/Extensible-prime-generator/PascalABC.NET/extensible-prime-generator.pas b/Task/Extensible-prime-generator/PascalABC.NET/extensible-prime-generator.pas new file mode 100644 index 0000000000..9c0e34d213 --- /dev/null +++ b/Task/Extensible-prime-generator/PascalABC.NET/extensible-prime-generator.pas @@ -0,0 +1,42 @@ +const + maxi = maxint.Sqrt.Floor; + +function gen_primes: sequence of integer; +begin + yield 2; + var D := new Dictionary; + var q := 3; + while True do + begin + if q not in D then + begin + if q < maxi then // prevent overflow + D[q * q] := q; + yield q; + end + else + begin + var p := D[q]; + D -= q; + var x := q + p + p; + while x in D do x += p + p; + D[x] := p; + end; + q += 2; + end; +end; + +begin + print('The first 20 primes are:'); + gen_primes.Take(20).println; + print('The primes between 100 and 150 are:'); + gen_primes.SkipWhile(x -> x < 100).TakeWhile(x -> x < 150).Println; + print('The number of primes between 7700 and 8000 is:'); + gen_primes.SkipWhile(x -> x < 7700).TakeWhile(x -> x < 8000).count.Println; + print('The 10,000th prime is:'); + gen_primes.Skip(10_000 - 1).First.Println; + print('The 100,000,000th prime is:'); + gen_primes.Skip(100_000_000 - 1).First.Println; + print('The sum of the primes to two million is:'); + gen_primes.Takewhile(x -> x < 2_000_000).select(x -> int64(x)).Sum.Println; +end. diff --git a/Task/FASTA-format/ALGOL-68/fasta-format.alg b/Task/FASTA-format/ALGOL-68/fasta-format.alg index 0af6a2dd55..5324552978 100644 --- a/Task/FASTA-format/ALGOL-68/fasta-format.alg +++ b/Task/FASTA-format/ALGOL-68/fasta-format.alg @@ -8,15 +8,16 @@ BEGIN # read FASTA format data from standard input and write the results to # 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 line /= "" THEN # non-empty line # + INT start pos := LWB line; + BOOL is heading = line[ start pos ] = ">"; # check for heading line # IF is heading THEN print( ( newline ) ); - start +:= 1 + start pos +:= 1 FI; - print( ( line[ start : ] ) ); + print( ( line[ start pos : ] ) ); IF is heading THEN print( ( ": " ) ) FI FI - OD + OD; + print( ( newline ) ) END diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/ALGOL-68/factorial-base-numbers-indexing-permutations-of-a-collection.alg b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/ALGOL-68/factorial-base-numbers-indexing-permutations-of-a-collection.alg new file mode 100644 index 0000000000..49ec974119 --- /dev/null +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/ALGOL-68/factorial-base-numbers-indexing-permutations-of-a-collection.alg @@ -0,0 +1,130 @@ +BEGIN # factorial base numbers indexing permutations of a collection # + # - translated from the Phix/FreeBASIC samples # + + PROC print sequence = ( []INT s )VOID: + BEGIN + print( ( " " ) ); + IF UPB s >= LWB s THEN + FOR j FROM LWB s TO UPB s DO + print( ( whole( s[ j ], 0 ) ) ) + OD + FI; + print( ( newline ) ) + END # print sequence # ; + + PROC factorial = ( INT n )LONG INT: IF n <= 1 THEN 1 ELSE n * factorial( n - 1 ) FI; + + PROC tagset = ( INT n )[]INT: + BEGIN + [ 1 : n ]INT result; + FOR i TO n DO result[ i ] := i OD; + result + END # tagset # ; + + PROC show cards = ( []INT s )VOID: + BEGIN + STRING cards = "AKQJT98765432", suits = "SHDC"; + FOR i FROM LWB s TO UPB s DO + INT c = s[ i ] - 1; + STRING card = cards[ ( c MOD 13 ) + 1 ] + suits[ ( c OVER 13 ) + 1 ]; + print( ( card, IF i MOD 13 = 0 OR i = UPB s THEN newline ELSE space FI ) ) + OD; + print( ( newline ) ) + END # show cards # ; + + PROC fperm = ( []INT fbn, omega )[]INT: + BEGIN + INT m := 0; + [ LWB omega : UPB omega ]INT result := omega; + FOR i FROM LWB fbn TO UPB fbn DO + INT g = fbn[ i ]; + IF g > 0 THEN + INT tmp = result[ m + g + 1 ]; + FOR j FROM m + g + 1 BY -1 TO m + 2 DO + result[ j ] := result[ j - 1 ] + OD; + result[ m + 1 ] := tmp + FI; + m +:= 1 + OD; + result + END # fperm # ; + + PROC factorial base numbers = ( INT size, BOOL count only )[]INT: + BEGIN + [ 1 : size ]INT res; FOR i TO size DO res[ i ] := 0 OD; + # count the number of results # + INT count := 0; + FOR n FROM 0 WHILE INT radix := 2; + INT k := n; + WHILE k > 0 DO + k OVERAB radix; + radix +:= 1 + OD; + radix <= size + 2 + DO count +:= 1 + OD; + [ 1 : IF count only THEN 0 ELSE count * size FI ]INT results; + FOR i TO UPB results DO results[ i ] := 0 OD; + INT results pos := - size; + IF NOT count only THEN + # want the results, not just a count # + FOR n FROM 0 WHILE INT radix := 2; + INT k := n; + WHILE k > 0 DO + IF NOT count only AND radix <= size + 1 THEN + res[ size - radix + 2 ] := k MOD radix + FI; + k OVERAB radix; + radix +:= 1 + OD; + radix <= size + 2 + DO count +:= 1; + results pos +:= size; + results[ results pos + 1 : results pos + size ] := res + OD + FI; + IF count only THEN count ELSE results FI + END # factorial base numbers # ; + + # Generate random factorial base number sequence # + PROC randfbn51 = []INT: + BEGIN + [ 1 : 51 ]INT fbn51; + FOR i TO 51 DO fbn51[ i ] := ENTIER ( next random * ( 52 - i ) ) + 1 OD; + fbn51 + END # randfbn51 # ; + + BEGIN + INT size = 3; + []INT fbns = factorial base numbers( size, FALSE ); + []INT omega = ( 0, 1, 2, 3 ); + FOR i TO UPB fbns OVER size DO + FOR j TO size DO + print( ( whole( fbns[ ( i - 1 ) * size + j ], 0 ), IF j = size THEN "" ELSE "." FI ) ) + OD; + print( ( " ->" ) ); + [ 1 : size ]INT tmp; + FOR j TO size DO tmp[ j ] := fbns[ ( i - 1 ) * size + j ] OD; + []INT result = fperm( tmp, omega ); + print sequence( result ) + OD; + print( ( newline ) ); + []INT count = factorial base numbers( 10, TRUE ); + print( ( "Permutations generated = ", whole( ( count )[ 1 ], 0 ), newline ) ); + print( ( " compared to 11! which = ", whole( factorial( 11 ), 0 ), newline ) ); + print( ( newline ) ); + [][]INT fbn51s = ( ( 39, 49, 7, 47, 29, 30, 2, 12, 10, 3, 29, 37, 33, 17, 12, 31, 29 + , 34, 17, 25, 2, 4, 25, 4, 1, 14, 20, 6, 21, 18, 1, 1, 1, 4 + , 0, 5, 15, 12, 4, 3, 10, 10, 9, 1, 6, 5, 5, 3, 0, 0, 0 + ) + , ( 51, 48, 16, 22, 3, 0, 19, 34, 29, 1, 36, 30, 12, 32, 12, 29, 30 + , 26, 14, 21, 8, 12, 1, 3, 10, 4, 7, 17, 6, 21, 8, 12, 15, 15 + , 13, 15, 7, 3, 12, 11, 9, 5, 5, 6, 6, 3, 4, 0, 3, 2, 1 + ) + , rand fbn51 + ); + # Show all card arrangements # + FOR i FROM LWB fbn51s TO UPB fbn51s DO show cards( fperm( fbn51s[ i ], tagset( 52 ) ) ) OD + END +END diff --git a/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic new file mode 100644 index 0000000000..abd85c0b29 --- /dev/null +++ b/Task/Factorial-base-numbers-indexing-permutations-of-a-collection/FreeBASIC/factorial-base-numbers-indexing-permutations-of-a-collection.basic @@ -0,0 +1,167 @@ +Type Sequence + longi As Integer + dato(1000) As Integer +End Type + +Sub printSequence(s As Sequence) + Print " "; + For i As Integer = 1 To s.longi + Print Chr(8) & s.dato(i); + If i < s.longi Then Print "."; + Next i + Print +End Sub + +Function factorial(n As Integer) As Longint + If n <= 1 Then Return 1 + Return n * factorial(n - 1) +End Function + +Function tagset(n As Integer) As Sequence + Dim As Sequence result + result.longi = n + For i As Integer = 1 To n + result.dato(i) = i + Next i + Return result +End Function + +Sub showCards(s As Sequence) + Const cards = "AKQJT98765432" + Const suits = "SHDC" + + For i As Integer = 1 To s.longi + Dim As Integer c = s.dato(i) - 1 + Dim As String card = Mid(cards, (c Mod 13) + 1, 1) + Mid(suits, (c \ 13) + 1, 1) + Print card; Iif(((i Mod 13) = 0 Or i = s.longi), Chr(10), " "); + Next i + Print +End Sub + +Function fperm(fbn As Sequence, omega As Sequence) As Sequence + Dim As Integer i, g, tmp, j, m = 0 + Dim As Sequence result = omega + + For i = 1 To fbn.longi + g = fbn.dato(i) + If g > 0 Then + tmp = result.dato(m + g + 1) + For j = m + g + 1 To m + 2 Step -1 + result.dato(j) = result.dato(j - 1) + Next j + result.dato(m + 1) = tmp + End If + m += 1 + Next i + + result.longi = omega.longi + Return result +End Function + +Function factorialBaseNumbers(size As Integer, cntOnly As Integer) As Sequence + Dim As Sequence results + Dim As Integer res(1000) + Dim As Integer cnt, n, radix, k, i + + results.longi = 0 + cnt = 0 + n = 0 + Do + radix = 2 + k = n + For i = 1 To size + res(i) = 0 + Next i + + While k > 0 + If cntOnly = 0 Andalso radix <= size + 1 Then + res(size - radix + 2) = k Mod radix + End If + k \= radix + radix += 1 + Wend + + If radix > size + 2 Then Exit Do + + cnt += 1 + If cntOnly = 0 Then + results.longi += 1 + For i = 1 To size + results.dato((results.longi - 1) * size + i) = res(i) + Next i + End If + n += 1 + Loop + + If cntOnly Then + results.longi = 1 + results.dato(1) = cnt + End If + + Return results +End Function + +' Generate random factorial base number sequence +Function randFBN51() As Sequence + Dim As Sequence fbn51 + fbn51.longi = 51 + For i As Integer = 1 To 51 + fbn51.dato(i) = Int(Rnd * (52 - i)) + 1 + Next i + Return fbn51 +End Function + +' Main program +Randomize Timer +Dim As Integer i, j + +Dim As Sequence fbns = factorialBaseNumbers(3, 0) +Dim As Sequence omega +omega.longi = 4 +For i = 0 To 3 + omega.dato(i + 1) = i +Next i + +For i = 1 To fbns.longi + For j = 1 To 3 + Print fbns.dato((i-1)*3 + j) & "."; + Next j + Print Chr(8) & " ->"; + + Dim As Sequence tmp + tmp.longi = 3 + For j = 1 To 3 + tmp.dato(j) = fbns.dato((i-1)*3 + j) + Next j + + Dim As Sequence result = fperm(tmp, omega) + printSequence(result) +Next i + +Print +Dim As Sequence cnt = factorialBaseNumbers(10, 1) +Print "Permutations generated ="; cnt.dato(1) +Print " compared to 11! which ="; factorial(11) + +Print +Dim As Sequence fbn51s(3) + +' First predefined sequence +fbn51s(1).longi = 51 +Data 39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0 +For i = 1 To 51: Read fbn51s(1).dato(i): Next + +' Second predefined sequence +fbn51s(2).longi = 51 +Data 51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1 +For i = 1 To 51: Read fbn51s(2).dato(i): Next + +' Third random sequence +fbn51s(3) = randFBN51() + +' Show all card arrangements +For i = 1 To 3 + showCards(fperm(fbn51s(i), tagset(52))) +Next i + +Sleep diff --git a/Task/Factorial-primes/PascalABC.NET/factorial-primes.pas b/Task/Factorial-primes/PascalABC.NET/factorial-primes.pas new file mode 100644 index 0000000000..817ecf3506 --- /dev/null +++ b/Task/Factorial-primes/PascalABC.NET/factorial-primes.pas @@ -0,0 +1,42 @@ +function IsPrime(n: int64): boolean; +begin + if (n = 2) or (n = 3) then Result := true + else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result := false + else + begin + var i := 5; + Result := False; + while i <= trunc(sqrt(n)) do + begin + if ((n mod i) = 0) or ((n mod (i + 2)) = 0) then exit; + i += 6; + end; + Result := True; + end; +end; + +function Factorial(n: integer): int64; +begin + Result := 1; + for var i := 2 to n do Result *= i; +end; + +begin + var found := 0; + var i := 1; + while found < 10 do + begin + var fact := Factorial(i); + if IsPrime(fact - 1) then + begin + writeln(i:2, '! - 1 = ', fact - 1); + found += 1; + end; + if IsPrime(fact + 1) then + begin + writeln(i:2, '! + 1 = ', fact + 1); + found += 1; + end; + i += 1; + end; +end. diff --git a/Task/Factorions/Jq/factorions.jq b/Task/Factorions/Jq/factorions.jq index 84891c0781..012ec312ee 100644 --- a/Task/Factorions/Jq/factorions.jq +++ b/Task/Factorions/Jq/factorions.jq @@ -29,7 +29,7 @@ def sufficient: .digits += 1 | .value *= $base ) ; -# Show the factorions for all based from 2 through 12: +# Show the factorions for all bases from 2 through 12: (range(2;10) | . as $base | sufficient.value as $max diff --git a/Task/Factorions/PascalABC.NET/factorions.pas b/Task/Factorions/PascalABC.NET/factorions.pas new file mode 100644 index 0000000000..ac69d82c56 --- /dev/null +++ b/Task/Factorions/PascalABC.NET/factorions.pas @@ -0,0 +1,22 @@ +## +var fact := |1| * 12; +for var i := 1 to 11 do fact[i] := i * fact[i - 1]; + +for var b := 9 to 12 do +begin + write('The factorions for base ', b:2, ' are: '); + for var i := 1 to 1_500_000 do + begin + var fact_sum := 0; + var j := i; + while j > 0 do + begin + var d := j mod b; + fact_sum += fact[d]; + j := j div b; + end; + if fact_sum = i then + print(i) + end; + println; +end; diff --git a/Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 b/Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 new file mode 100644 index 0000000000..d9f148a243 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/M2000-Interpreter/factors-of-a-mersenne-number.m2000 @@ -0,0 +1,41 @@ +Module Factors_of_a_Mersenne_number{ + Dim q(1 To 10) + q(1)= 11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929 + For k = 1 To 10 + If @isPrime(q(k)) Then + long p, r, d, r=q(k) + long long i + d = 2*q(k)+1 + while r>0: r=sint(binary.add(r,r)): end while + Do + i=1 + p=r + While p<>0 + i = i**2@ Mod d + If p<0 Then i*=2 + If i>d Then i-=d + p=sint(binary.add(p,p)) + End While + If i=1 Then Exit + d+=2*q(k) + Always + Print "2^"; q(k); @(6); " - 1 = 0 (mod"; d; ")" + Else + Print q(k); " is not prime" + End If + Next + + Function isPrime(n As long) + If n Mod 2 = 0 Then = n=2 : Exit Function + If n Mod 3 = 0 Then = n=3 : Exit Function + Local d As long = 5 + While d * d <= n + If n Mod d = 0 Then =False: exit function + d += 2 + If n Mod d = 0 Then = False: exit function + d += 4 + End While + =True + End Function +} +Factors_of_a_Mersenne_number diff --git a/Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas b/Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas new file mode 100644 index 0000000000..32d45238dc --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/PascalABC.NET/factors-of-a-mersenne-number.pas @@ -0,0 +1,36 @@ +const + q = 929; + +function isPrime(a: integer): boolean; +begin + if a = 2 then + begin result := true; exit end; + if (a < 2) or (a mod 2 = 0) then + begin result := false; exit end; + for var i := 3 to sqrt(a).Floor step 2 do + if a mod i = 0 then + begin result := false; exit end; + result := true; +end; + +begin + if not isPrime(q) then exit; + var r := q; + while r > 0 do r := r shl 1; + var d := 2 * q + 1; + while true do + begin + var i := 1; + var p := r; + while p <> 0 do + begin + i := (i * i) mod d; + if p < 0 then i *= 2; + if i > d then i -= d; + p := p shl 1; + end; + if i <> 1 then d += 2 * q + else break + end; + write('2^', q, ' - 1 = 0 (mod ', d, ')'); +end. diff --git a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx index 6b25dba13c..0c9b756a9b 100644 --- a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx +++ b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx @@ -1,10 +1,11 @@ -say 'Factor of a Mersenne number - Using REXX libraries' +include Settings +say 'Factor of a Mersenne Number - Using REXX libraries' parse version version; say version; say call Time('r') numeric digits 300 n = Primes(1000) do i = 1 to n - x = prim.prime.i + x = prim.Prime.i select when (x >= 2 & x <= 83) then call Task x @@ -21,7 +22,7 @@ Task: procedure arg x a = x; a = 'M'a; m = 2**x -do k = 1 by 2*x to ISqrt(m) +do k = 1 by 2*x to Isqrt(m) if Right(k,1) = 5 then iterate k b = k//8 @@ -32,14 +33,15 @@ do k = 1 by 2*x to ISqrt(m) iterate k c = m//k if c = 1 then do - say a 'is composite =' k 'x ...' + say a 'is Composite =' k 'x ...' leave k end end end if c <> 1 then - say a 'is prime' + say a 'is Prime' return include Functions -include Numbers +include Sequences +Include Abend diff --git a/Task/Fairshare-between-two-and-more/PascalABC.NET/fairshare-between-two-and-more.pas b/Task/Fairshare-between-two-and-more/PascalABC.NET/fairshare-between-two-and-more.pas new file mode 100644 index 0000000000..d3d73e75cf --- /dev/null +++ b/Task/Fairshare-between-two-and-more/PascalABC.NET/fairshare-between-two-and-more.pas @@ -0,0 +1,22 @@ +function ThueMorseSequence(terms, baseValue: integer): list; +begin + result := new List; + for var i := 0 to terms - 1 do + begin + var sum := 0; + var n := i; + while (n > 0) do + begin + // Compute the digit sum + sum += n mod baseValue; + n := n div baseValue; + end; + // Compute the digit sum modulo baseValue. + result.Add(sum mod baseValue); + end; +end; + +begin + foreach var baseValue in |2, 3, 5, 11| do + println('Base', baseValue, '=', ThueMorseSequence(25, baseValue)); +end. diff --git a/Task/Farey-sequence/ALGOL-68/farey-sequence.alg b/Task/Farey-sequence/ALGOL-68/farey-sequence.alg index c0e20f9828..8a2e0ac9da 100644 --- a/Task/Farey-sequence/ALGOL-68/farey-sequence.alg +++ b/Task/Farey-sequence/ALGOL-68/farey-sequence.alg @@ -27,7 +27,7 @@ BEGIN # construct some Farey Sequences and calculate their lengths # length FI # farey sequence length # ; # task # - FOR i TO 11 DO farey sequence length( i, TRUE ) OD; + FOR i TO 11 DO VOID( farey sequence length( i, TRUE ) ) OD; FOR n FROM 100 BY 100 TO 1 000 DO print( ( "Farey Sequence of order ", whole( n, -4 ) , " has length: ", whole( farey sequence length( n, FALSE ), -6 ) diff --git a/Task/Farey-sequence/PascalABC.NET/farey-sequence.pas b/Task/Farey-sequence/PascalABC.NET/farey-sequence.pas new file mode 100644 index 0000000000..779923fc7c --- /dev/null +++ b/Task/Farey-sequence/PascalABC.NET/farey-sequence.pas @@ -0,0 +1,20 @@ +function Generate(n: integer): list<(integer, integer)>; +begin + var fractions := new list<(integer, integer)>; + result := new list<(integer, integer)>; + for var den := 1 to n do + for var num := 0 to den do fractions.Add((num, den)); + fractions := fractions.OrderBy(f -> f[0] / f[1]).ToList; + + result.Add(fractions[0]); + for var i := 0 to fractions.Count - 2 do + if fractions[i][0] * fractions[i + 1][1] <> fractions[i][1] * fractions[i + 1][0] then + result.add(fractions[i + 1]); +end; + +begin + for var i := 1 to 11 do + writeln('F', i, ': ', Generate(i).Select(f -> f[0].ToString + '/' + f[1].tostring)); + for var i := 100 to 1000 step 100 do + writeln('F', i, ' has ', Generate(i).Count, ' terms.'); +end. diff --git a/Task/Feigenbaum-constant-calculation/PascalABC.NET/feigenbaum-constant-calculation.pas b/Task/Feigenbaum-constant-calculation/PascalABC.NET/feigenbaum-constant-calculation.pas new file mode 100644 index 0000000000..9d7dc4d382 --- /dev/null +++ b/Task/Feigenbaum-constant-calculation/PascalABC.NET/feigenbaum-constant-calculation.pas @@ -0,0 +1,27 @@ +## +var maxIt := 13; +var maxItJ := 10; +var a1 := 1.0; +var a2 := 0.0; +var d1 := 3.2; +println(' i d'); +for var i := 2 to maxIt do +begin + var a := a1 + (a1 - a2) / d1; + for var j := 1 To maxItJ do + begin + var x := 0.0; + var y := 0.0; + for var k := 1 To 1 shl i do + begin + y := 1.0 - 2.0 * y * x; + x := a - x * x; + end; + a -= x / y; + end; + var d := (a1 - a2) / (a - a1); + writeln(i:2, d:14:10); + d1 := d; + a2 := a1; + a1 := a; +end; diff --git a/Task/Fermat-numbers/ALGOL-68/fermat-numbers.alg b/Task/Fermat-numbers/ALGOL-68/fermat-numbers.alg index 798b42a9a8..42ea37a082 100644 --- a/Task/Fermat-numbers/ALGOL-68/fermat-numbers.alg +++ b/Task/Fermat-numbers/ALGOL-68/fermat-numbers.alg @@ -19,7 +19,7 @@ BEGIN # find and factorise some Fermat numbers: F(n) = 2^(2^n) + 1 # IF is probably prime( n ) THEN n ELIF LONG LONG INT x := 2, y := 2, d := 1; - PROC g = ( LONG LONG INT x )LONG LONG INT: ( ( x * x ) + 1 ) MOD n; + PROC g = ( LONG LONG INT gx )LONG LONG INT: ( ( gx * gx ) + 1 ) MOD n; WHILE d = 1 DO x := g( x ); y := g( g( y ) ); diff --git a/Task/Fermat-numbers/PascalABC.NET/fermat-numbers.pas b/Task/Fermat-numbers/PascalABC.NET/fermat-numbers.pas new file mode 100644 index 0000000000..6d4086960e --- /dev/null +++ b/Task/Fermat-numbers/PascalABC.NET/fermat-numbers.pas @@ -0,0 +1,35 @@ +## +function IsPrime(n: biginteger): boolean; +begin + if (n = 2) or (n = 3) then Result := true + else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result := false + else + begin + var i := 5bi; + Result := False; + while i * i < n do + begin + if (n mod i) = 0 then + begin + println(i, n div i); + exit; + end + else if (n mod (i + 2)) = 0 then + begin + println(i + 2, n div (i + 2)); + exit; + end; + i += 6; + end; + Result := True; + end; +end; + +function fermat(n: integer) := power(2bi, int64(power(2, n))) + 1; + +for var n := 0 to 9 do writeln('F', n, ' = ', fermat(n)); +for var n := 0 to 6 do +begin + write('F', n, ' = '); + if isprime(fermat(n)) then println(fermat(n)); +end; diff --git a/Task/Fibonacci-word-fractal/PascalABC.NET/fibonacci-word-fractal.pas b/Task/Fibonacci-word-fractal/PascalABC.NET/fibonacci-word-fractal.pas new file mode 100644 index 0000000000..704bd809f7 --- /dev/null +++ b/Task/Fibonacci-word-fractal/PascalABC.NET/fibonacci-word-fractal.pas @@ -0,0 +1,32 @@ +uses Turtle; + +function fibword(n: integer): string; +begin + var a := '1'.ToString; + result := '0'; + loop n - 2 do + begin + a := result + a; + swap(a, result); + end; +end; + +procedure draw_fractal(w: string; step: real); +begin + foreach var c in w index i do + begin + Forw(step); + if c = '0' then + if i mod 2 = 0 then TurnLeft(90) + else TurnRight(90) + end; +end; + +begin + var w := fibword(20); + var step := 1; + SetWidth(2); + Down; + TurnRight(90); + draw_fractal(w, step); +end. diff --git a/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg b/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg index cdeda9d346..abb856955b 100644 --- a/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg +++ b/Task/Fibonacci-word/ALGOL-68/fibonacci-word.alg @@ -22,7 +22,6 @@ PROC print fibonacci word stats = ( INT max number )VOID: BEGIN - # prints some statistics for a fibonacci word: # # the word number, its length and its entropy # PROC print one words stats = ( INT word @@ -30,75 +29,51 @@ BEGIN , INT ones )VOID: BEGIN - REAL probability := 0; REAL entropy := 0; INT word length = zeros + ones; - IF zeros > 0 THEN # the word contains some zeros # probability := zeros / word length; entropy -:= probability * log( probability ) FI; - IF ones > 0 THEN # the word contains some ones # probability := ones / word length; entropy -:= probability * log( probability ) FI; - # we want entropy in bits so convert to log base 2 # entropy /:= log( 2 ); - - print( ( ( whole( word, -5 ) - + " " - + whole( word length, -12 ) - + " " - + fixed( entropy, -8, 4 ) - ) - , newline - ) - ) - - + print( ( whole( word, -5 ), " ", whole( word length, -12 ) ) ); + print( ( " ", fixed( entropy, -8, 4 ), newline ) ) END; # print one words stats # - INT zeros one = 0; # number of zeros in word 1 # INT ones one = 1; # number of ones in word 1 # INT zeros two = 1; # number of zeros in word 2 # INT ones two = 0; # number of ones in word 2 # - print( ( " word length entropy", newline ) ); - IF max number > 0 THEN # we want at least one number's statistics # print one words stats( 1, zeros one, ones one ); - IF max number > 1 THEN # we want at least 2 number's statistics # print one words stats( 2, zeros two, ones two ); - IF max number > 2 THEN # we want more statistics # - INT zeros n minus 1 := zeros two; INT ones n minus 1 := ones two; INT zeros n minus 2 := zeros one; INT ones n minus 2 := ones one; - FOR word FROM 3 TO max number DO - INT zeros n := zeros n minus 1 + zeros n minus 2; INT ones n := ones n minus 1 + ones n minus 2; - print one words stats( word, zeros n, ones n ); - zeros n minus 2 := zeros n minus 1; ones n minus 2 := ones n minus 1; zeros n minus 1 := zeros n; @@ -107,12 +82,7 @@ BEGIN FI FI FI - END; # print fibonacci word stats # - -main: -( - # print the statistics for the first 37 fibonacci words # - print fibonacci word stats( 37 ) -) +# print the statistics for the first 37 fibonacci words # +print fibonacci word stats( 37 ) diff --git a/Task/Fibonacci-word/PascalABC.NET/fibonacci-word.pas b/Task/Fibonacci-word/PascalABC.NET/fibonacci-word.pas new file mode 100644 index 0000000000..eee6fcebff --- /dev/null +++ b/Task/Fibonacci-word/PascalABC.NET/fibonacci-word.pas @@ -0,0 +1,37 @@ +function entropy(str: string): real; +begin + // ## return the entropy of a fibword string. + if str.length <= 1 then begin result := 0.0; exit end; + var strlen := str.length; + var count0 := str.where(c -> c = '0').count; + var count1 := strlen - count0; + result := -(count0 / strlen * log2(count0 / strlen) + count1 / strlen * log2(count1 / strlen)) +end; + +function fibword(): sequence of string; +begin + // ## Yield the successive fibwords. + var a := '1'.ToString; + var b := '0'.ToString; + yield a; + yield b; + while true do + begin + a := b + a; + swap(a, b); + yield b + end; +end; + +begin + println(' n length entropy'); + println('————————————————————————————————'); + var n := 0; + foreach var str in fibword do + begin + n += 1; + write(n:2, str.length:10, entropy(str):18:14); + if n < 10 then writeln(' ', str) else writeln; + if n = 37 then break + end; +end. diff --git a/Task/File-input-output/FutureBasic/file-input-output.basic b/Task/File-input-output/FutureBasic/file-input-output.basic index 6fc45a678d..f66dbb9cb5 100644 --- a/Task/File-input-output/FutureBasic/file-input-output.basic +++ b/Task/File-input-output/FutureBasic/file-input-output.basic @@ -50,8 +50,6 @@ fn doIt end select end fn - on AppEvent fn DoAppEvent - handleevents diff --git a/Task/Find-the-last-Sunday-of-each-month/ALGOL-68/find-the-last-sunday-of-each-month.alg b/Task/Find-the-last-Sunday-of-each-month/ALGOL-68/find-the-last-sunday-of-each-month.alg index 98c92a6a9c..9fcb7f60bd 100644 --- a/Task/Find-the-last-Sunday-of-each-month/ALGOL-68/find-the-last-sunday-of-each-month.alg +++ b/Task/Find-the-last-Sunday-of-each-month/ALGOL-68/find-the-last-sunday-of-each-month.alg @@ -33,17 +33,18 @@ BEGIN # find the last Sunday in each month of a year # OD; last END # last sundays # ; - # test the last sundays procedure # - INT year = 2021; - []INT last = last sundays( year ); - FOR m pos TO 12 DO - print( ( whole( year, 0 ) - , IF m pos < 10 THEN "-0" ELSE "-1" FI - , whole( m pos MOD 10, 0 ) - , "-" - , whole( last[ m pos ], 0 ) - , newline - ) - ) - OD + BEGIN # test the last sundays procedure # + INT year = 2021; + []INT last = last sundays( year ); + FOR m pos TO 12 DO + print( ( whole( year, 0 ) + , IF m pos < 10 THEN "-0" ELSE "-1" FI + , whole( m pos MOD 10, 0 ) + , "-" + , whole( last[ m pos ], 0 ) + , newline + ) + ) + OD + END END diff --git a/Task/Find-the-last-Sunday-of-each-month/M2000-Interpreter/find-the-last-sunday-of-each-month.m2000 b/Task/Find-the-last-Sunday-of-each-month/M2000-Interpreter/find-the-last-sunday-of-each-month.m2000 new file mode 100644 index 0000000000..8ee65ae040 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/M2000-Interpreter/find-the-last-sunday-of-each-month.m2000 @@ -0,0 +1,23 @@ +module LastSunday (year as integer=0) { + REM LOCALE 1032 ' Greek + LOCALE 1033 ' US - English + DEF firstdayYear(y)=cdate(0, y-1900,0,2) + DEF lastdayYear(y)=cdate(0, y-1900,12,1) + IF year=0 THEN INPUT "Year (e.g. 2024 or 24):", year + year=ABS(year) + IF year<100 THEN year+=2000 + DATE a=firstdayYear(year), Sunday=1 + DATE a1=lastdayYear(year) + DATE i=a+7-(a-Sunday) mod 7 + DOCUMENT result$="Last Sunday per month for year " + year + {: + } + FOR i=i+7 TO a1 STEP 7 + IF VAL(DATE$(i, LOCALE, "M")) <>VAL(DATE$(i+7, LOCALE, "M")) THEN + result$=FORMAT$("{0:12} {1:-14}",DATE$(i, LOCALE, "MMMM"),DATE$(i, LOCALE, "d")) + { + } + END IF + NEXT + PRINT #-2, result$ + CLIPBOARD result$ +} +LastSunday 2025 diff --git a/Task/Find-the-last-Sunday-of-each-month/V-(Vlang)/find-the-last-sunday-of-each-month.v b/Task/Find-the-last-Sunday-of-each-month/V-(Vlang)/find-the-last-sunday-of-each-month.v new file mode 100644 index 0000000000..109e638118 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/V-(Vlang)/find-the-last-sunday-of-each-month.v @@ -0,0 +1,24 @@ +import time +import os + +fn main() { + mut year := "" + mut now, mut mdx := time.now(), time.month_days[0] + for year.len != 4 || !year.split("").any(it.is_int()) { + year = os.input("What year to calculate (yyyy): ") + } + println("Last Sunday for each month of ${year}") + println("==================================") + for idx in 1..13 { + mdx = time.month_days[idx - 1] + if idx == 2 && time.is_leap_year(year.int()) {mdx = 29} + for { + now = time.parse("$year-${idx:02}-${mdx} 12:30:00")! + if now.weekday_str() == "Sun" { + println("${time.long_months[idx -1 ]}: ${mdx}") + break + } + mdx-- + } + } +} diff --git a/Task/First-perfect-square-in-base-n-with-n-unique-digits/ALGOL-68/first-perfect-square-in-base-n-with-n-unique-digits.alg b/Task/First-perfect-square-in-base-n-with-n-unique-digits/ALGOL-68/first-perfect-square-in-base-n-with-n-unique-digits.alg index 4cd590746e..540e9b67d6 100644 --- a/Task/First-perfect-square-in-base-n-with-n-unique-digits/ALGOL-68/first-perfect-square-in-base-n-with-n-unique-digits.alg +++ b/Task/First-perfect-square-in-base-n-with-n-unique-digits/ALGOL-68/first-perfect-square-in-base-n-with-n-unique-digits.alg @@ -25,9 +25,7 @@ BEGIN # find the first perfect square in base n with n unique digits n=1..16 # FOR b FROM 2 TO 16 DO all digits := all digits OR dmask[ b - 1 ]; LONG INT root := 1; - FOR i TO b - 1 DO - root *:= b - OD; + TO b - 1 DO root *:= b OD; root := ENTIER long sqrt( root ); BOOL found := FALSE; WHILE NOT found DO diff --git a/Task/Five-weekends/Jq/five-weekends-1.jq b/Task/Five-weekends/Jq/five-weekends-1.jq index 9b9ce0a660..89cc7a31bd 100644 --- a/Task/Five-weekends/Jq/five-weekends-1.jq +++ b/Task/Five-weekends/Jq/five-weekends-1.jq @@ -1,4 +1,4 @@ - Use Zeller's Congruence to determine the day of the week, given +# Use Zeller's Congruence to determine the day of the week, given # year, month and day as integers in the conventional way. # Emit 0 for Saturday, 1 for Sunday, etc. # diff --git a/Task/Five-weekends/PascalABC.NET/five-weekends.pas b/Task/Five-weekends/PascalABC.NET/five-weekends.pas new file mode 100644 index 0000000000..98a7e8d4bd --- /dev/null +++ b/Task/Five-weekends/PascalABC.NET/five-weekends.pas @@ -0,0 +1,27 @@ +uses system; + +const + startYear = 1900; + endYear = 2100; + +begin + var query := new List; + foreach var year in (startyear..endyear) do + foreach var month in (1..12) do + if DateTime.DaysInMonth(year, month) = 31 then + query.Add(new DateTime(year, month, 1)); + query := query.where(d -> d.dayofweek = dayofweek.Friday).ToList; + + println('Count:', query.Count); + println; + println('First five:'); + foreach var date in query.Take(5) do + writeln(date.Year, '-', date.Month); + println; + Println('Last five:'); + foreach var date in query.Skip(query.Count - 5) do + writeln(date.Year, '-', date.Month); + println; + println('Years without 5 weekends:'); + (startyear..endyear).except(query.Select(d -> d.year)).Println +end. diff --git a/Task/FizzBuzz/YAMLScript/fizzbuzz.ys b/Task/FizzBuzz/YAMLScript/fizzbuzz.ys index b328c65d02..7dbb165768 100644 --- a/Task/FizzBuzz/YAMLScript/fizzbuzz.ys +++ b/Task/FizzBuzz/YAMLScript/fizzbuzz.ys @@ -1,39 +1,7 @@ !yamlscript/v0 -defn main(count=100 impl=1): - :: | - Invoke one of the FizzBuzz implementations below. - - usage: ys fizzbuzz.ys [ []] - - fizzbuzz =: "fizzbuzz-$impl" - say: "Running function '$fizzbuzz' with count=$count" - mapv say: - call fizzbuzz: count - -defn fizzbuzz-1(n): - :: Implementation 1 - with 'map' - map _ (1 .. n): - fn(x): - cond: - zero?(x % 15) : 'FizzBuzz' - zero?(x % 5) : 'Buzz' - zero?(x % 3) : 'Fizz' - else : x - -defn fizzbuzz-2(n): - :: Implementation 2 - with 'loop' - loop i 1, l []: - if i <= n: - recur i.++: - conj l: - condp eq 0: - i % 15 :: FizzBuzz - i % 5 :: Buzz - i % 3 :: Fizz - else : i - else: l - -defn fizzbuzz-3(n): - :: Implementation 3 - with 'for' - for x (1 .. n): str(((x % 3).! &&& 'Fizz') ((x % 5).! &&& 'Buzz')) ||| x +defn main(n=100): + each x (1 .. n): !:say + or? _ x: + str ((x % 3).! &&& 'Fizz'): + ((x % 5).! &&& 'Buzz') diff --git a/Task/Flow-control-structures/FutureBasic/flow-control-structures.basic b/Task/Flow-control-structures/FutureBasic/flow-control-structures.basic new file mode 100644 index 0000000000..e1bdbc5e11 --- /dev/null +++ b/Task/Flow-control-structures/FutureBasic/flow-control-structures.basic @@ -0,0 +1,21 @@ +override _allowSubroutines = _true +#build Optimization _buildOptimizationNone + +print "First line." +gosub "sub1" +print "Fifth line." + +HandleEvents + +"sub1" +print "Second line." +gosub "sub2" +print "Fourth line." +goto "skip" +print "we don't get here" +"skip" +return + +"sub2" +print "Third line." +return diff --git a/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg b/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg index 1b23cfac2f..68ed0e7149 100644 --- a/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg +++ b/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg @@ -22,7 +22,7 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # ) ); WHILE u := nxt[ u - 1, v - 1 ]; - print( ( " -> " +whole( u, 0 ) ) ); + print( ( " -> " + whole( u, 0 ) ) ); u /= v DO SKIP OD; print( ( newline ) ) @@ -34,12 +34,12 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # PROC floyd warshall = ( [,]INT weights, INT num vertices )VOID: BEGIN - REAL infinity = max real; + REAL infinite = max real; [ 0 : num vertices - 1, 0 : num vertices - 1 ]REAL dist; FOR i FROM LWB dist TO 1 UPB dist DO FOR j FROM 2 LWB dist TO 2 UPB dist DO - dist[ i, j ] := infinity + dist[ i, j ] := infinite OD OD; @@ -59,7 +59,7 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # FOR k FROM 2 LWB dist TO 2 UPB dist DO FOR i FROM 1 LWB dist TO 1 UPB dist DO FOR j FROM 2 LWB dist TO 2 UPB dist DO - IF dist[ i, k ] /= infinity AND dist[ k, j ] /= infinity THEN + IF dist[ i, k ] /= infinite AND dist[ k, j ] /= infinite THEN IF dist[ i, k ] + dist[ k, j ] < dist[ i, j ] THEN dist[ i, j ] := dist[ i, k ] + dist[ k, j ]; nxt[ i, j ] := nxt[ i, k ] @@ -71,14 +71,14 @@ BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # print result( dist, nxt ) END # floyd warshall # ; - - [,]INT weights = ( ( 1, 3, -2 ) - , ( 2, 1, 4 ) - , ( 2, 3, 3 ) - , ( 3, 4, 2 ) - , ( 4, 2, -1 ) - ); - INT num vertices = 4; - floyd warshall( weights, num vertices ) - + BEGIN + [,]INT weights = ( ( 1, 3, -2 ) + , ( 2, 1, 4 ) + , ( 2, 3, 3 ) + , ( 3, 4, 2 ) + , ( 4, 2, -1 ) + ); + INT num vertices = 4; + floyd warshall( weights, num vertices ) + END END diff --git a/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys b/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys index 94df2abdee..d1619de731 100644 --- a/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys +++ b/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys @@ -9,5 +9,5 @@ defn main(n): conj(rows nums.take(row-n)) else: rows width =: rows:last:last:len - fmt =: \((' ' * (width - len(_))) + _) + fmt =: \((' ' * (width - _:len)) + _) each row rows: say(row.map(fmt):joins) diff --git a/Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx b/Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx index 3735dfc520..5d4aa0d250 100644 --- a/Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx +++ b/Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx @@ -24,7 +24,7 @@ do i = 1 to x p = prmo.primorial.i do j = 3 by 2 m = m+1 - if IsPrime(p+j) then + if Prime(p+j) then leave j end if work.j = 0 then do @@ -55,6 +55,7 @@ say Format(Time('e'),,3) 'seconds'; say return include Numbers +include Sequences include Functions include Constants include Abend diff --git a/Task/Forward-difference/FutureBasic/forward-difference.basic b/Task/Forward-difference/FutureBasic/forward-difference.basic new file mode 100644 index 0000000000..b9277f5984 --- /dev/null +++ b/Task/Forward-difference/FutureBasic/forward-difference.basic @@ -0,0 +1,26 @@ +include "NSLog.incl" + +CFArrayRef local fn ForwardDifference( arr as CFArrayRef ) + CFMutableArrayRef result = fn MutableArrayNew + for NSUInteger i = 1 to len(arr) - 1 + CFNumberRef diff = @(dblval(arr[i]) - dblval(arr[i-1])) + MutableArrayAddObject( result, diff ) + next +end fn = result + +CFArrayRef local fn NthForwardDifference( arr as CFArrayRef, n as NSInteger ) + if ( len(arr) == 0 ) then return @[] + if ( n == 0 ) then return arr +end fn = fn NthForwardDifference( fn ForwardDifference( arr ), n - 1 ) + +void local fn DoIt + CFArrayRef initialArray = @[@90, @47, @58, @29, @22, @32, @55, @5, @55, @73] + for NSInteger i = 0 to 9 + CFArrayRef diff = fn NthForwardDifference( initialArray, i ) + NSLog(@"[%@]", fn ArrayComponentsJoinedByString( diff, @", " )) + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Fractran/ALGOL-68/fractran.alg b/Task/Fractran/ALGOL-68/fractran.alg index c1d894374e..2908205a60 100644 --- a/Task/Fractran/ALGOL-68/fractran.alg +++ b/Task/Fractran/ALGOL-68/fractran.alg @@ -1,6 +1,6 @@ # as the numbers required for finding the first 20 primes are quite large, # -# we use Algol 68G's LONG LONG INT with a precision of 100 digits # -PR precision 100 PR +# we use Algol 68G's LONG LONG INT with a precision of 200 digits # +PR precision 200 PR # mode to hold fractions # MODE FRACTION = STRUCT( INT numerator, INT denominator ); @@ -9,16 +9,16 @@ MODE FRACTION = STRUCT( INT numerator, INT denominator ); OP / = ( INT a, b )FRACTION: ( a, b ); # mode to define a FRACTRAN progam # -MODE FRACTRAN = STRUCT( FLEX[0]FRACTION data +MODE FRACTRAN = STRUCT( [0]FRACTION data , LONG LONG INT n , BOOL halted ); # prepares a FRACTRAN program for use - sets the initial value of n and halted to FALSE # PRIO STARTAT = 1; -OP STARTAT = ( REF FRACTRAN f, INT start )REF FRACTRAN: +OP STARTAT = ( REF FRACTRAN f, INT start p )REF FRACTRAN: BEGIN halted OF f := FALSE; - n OF f := start; + n OF f := start p; f END; @@ -39,36 +39,39 @@ OP NEXT = ( REF FRACTRAN f )LONG LONG INT: FI ; # generate and print the sequence of numbers from a FRACTRAN pogram # -PROC print fractran sequence = ( REF FRACTRAN f, INT start, INT limit )VOID: +PROC print fractran sequence = ( REF FRACTRAN f, INT start p, INT limit )VOID: BEGIN - VOID( f STARTAT start ); - print( ( "0: ", whole( start, 0 ) ) ); + VOID( f STARTAT start p ); + print( ( "0: ", whole( start p, 0 ) ) ); FOR i TO limit WHILE VOID( NEXT f ); NOT halted OF f DO - print( ( " " + whole( i, 0 ) + ": " + whole( n OF f, 0 ) ) ) + print( ( " ", whole( i, 0 ), ":", whole( n OF f, 0 ) ) ) OD; print( ( newline ) ) END ; # print the first 16 elements from the primes FRACTRAN program # -FRACTRAN pf := ( ( 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 ), 0, FALSE ); +FRACTRAN pf := ( ( 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 ), 0, FALSE ); print fractran sequence( pf, 2, 15 ); # find some primes using the pf FRACTRAN progam - n is prime for the members in the sequence that are 2^n # -INT primes found := 0; -VOID( pf STARTAT 2 ); -INT pos := 0; -print( ( "seq position prime sequence value", newline ) ); -WHILE primes found < 20 AND NOT halted OF pf DO - LONG LONG INT value := NEXT pf; - INT power of 2 := 0; - pos +:= 1; - WHILE value MOD 2 = 0 AND value > 0 DO power of 2 PLUSAB 1; value OVERAB 2 OD; - IF value = 1 THEN - # found a prime # - primes found +:= 1; - print( ( whole( pos, -12 ) + " " + whole( power of 2, -6 ) + " (" + whole( n OF pf, 0 ) + ")", newline ) ) - FI -OD +BEGIN + INT primes found := 0; + VOID( pf STARTAT 2 ); + INT pos := 0; + print( ( "seq position prime sequence value", newline ) ); + WHILE primes found < 20 AND NOT halted OF pf DO + LONG LONG INT value := NEXT pf; + INT power of 2 := 0; + pos +:= 1; + WHILE value MOD 2 = 0 AND value > 0 DO power of 2 PLUSAB 1; value OVERAB 2 OD; + IF value = 1 THEN + primes found +:= 1; + print( ( whole( pos, -12 ), " ", whole( power of 2, -6 ) ) ); + print( ( " (" + whole( n OF pf, 0 ), ")", newline ) ) + FI + OD +END diff --git a/Task/Fractran/Miranda/fractran.miranda b/Task/Fractran/Miranda/fractran.miranda new file mode 100644 index 0000000000..c1f844d524 --- /dev/null +++ b/Task/Fractran/Miranda/fractran.miranda @@ -0,0 +1,80 @@ +main :: [sys_message] +main = [Stdout (lay [show (take 15 (run 2 primeprog)), + show (take 20 fracprimes)])] + +primeprog :: [(num,num)] +primeprog = fromjust (prog ("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")) + +fracprimes :: [num] +fracprimes = [fromjust k | k<-map fracprime (run 2 primeprog); isjust k] + +fracprime :: num->maybe num +fracprime = f 0 + where f 1 1 = Nothing + f n 1 = Just n + f n x = Nothing, if x mod 2 ~= 0 + f n x = f (n+1) (x div 2), otherwise + +run :: num->[(num,num)]->[num] +run n prog = [n], if ~isjust n' + = n : run (fromjust n') prog, otherwise + where n' = step n prog + +step :: num->[(num,num)]->maybe num +step x [] = Nothing +step x ((n,d):xs) = Just (x*n div d), if x*n mod d = 0 + = step x xs, otherwise + +maybe * ::= Nothing | Just * + +isjust :: maybe *->bool +isjust (Just x) = True +isjust Nothing = False + +fromjust :: maybe *->* +fromjust (Just x) = x + +prog :: [char]->maybe [(num, num)] +prog xs = Just [], if trim xs = [] + = Nothing, if ~isjust fp \/ ~isjust rp + = Just (fr : fromjust rp), otherwise + where fp = frac xs + Just (fr, xs') = fp + rp = prog xs' + +frac :: [char]->maybe ((num,num), [char]) +frac xs = Nothing, if ~isjust np \/ ~isjust sl \/ ~isjust dp + = Just ((n, d), xs'''), otherwise + where np = numb xs + Just (n, xs') = np + sl = match '/' (trim xs') + Just xs'' = sl + dp = numb xs'' + Just (d, xs''') = dp + +numb :: [char]->maybe (num, [char]) +numb xs = Nothing, if n=[] + = Just (numval n, r), otherwise + where (n, r) = span "0123456789" (trim xs) + +match :: *->[*]->maybe [*] +match m [] = Nothing +match m (m:xs) = Just xs +match m (x:xs) = Nothing + +span :: [*]->[*]->([*],[*]) +span match [] = ([], []) +span match (x:xs) = ([], x:xs), if ~(x $in match) + = (x:r, xs'), otherwise + where (r, xs') = span match xs + +in :: *->[*]->bool +in x [] = False +in x (x:xs) = True +in x (y:xs) = x $in xs + +trim :: [char]->[char] +trim [] = [] +trim (c:xs) = trim xs, if c='\t' \/ c='\n' \/ c=' ' +trim (c:xs) = c:xs diff --git a/Task/Fractran/REXX/fractran-3.rexx b/Task/Fractran/REXX/fractran-3.rexx index 7981a9941e..1614a50f5c 100644 --- a/Task/Fractran/REXX/fractran-3.rexx +++ b/Task/Fractran/REXX/fractran-3.rexx @@ -29,7 +29,7 @@ call Time('r') say 'First' t 'terms of the sequence:' do i = 2 to t do j = 1 to w - if \ IsWhole(n/d.j) then + if \ Whole(n/d.j) then iterate call CharOut ,Right(n,9) if i//10 = 0 then @@ -57,7 +57,7 @@ say 'Prime numbers:' n = 2; p = 0 do i = 2 to 1300000 do j = 1 to w - if \ IsWhole(n/d.j) then + if \ Whole(n/d.j) then iterate j if p.n then do p = p+1 diff --git a/Task/Fractran/Refal/fractran.refal b/Task/Fractran/Refal/fractran.refal new file mode 100644 index 0000000000..e66c789961 --- /dev/null +++ b/Task/Fractran/Refal/fractran.refal @@ -0,0 +1,78 @@ +$ENTRY Go { + , >: e.Prog + = > + >; +}; + +PrimeProgram { + = '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'; +}; + +FracPrimes { + 0 e.X = ; + s.I (e.N) e.P, + : Next e.N2, + : { + T s.N = s.N (e.N2) e.P>; + F = ; + }; +}; + +FracPrime { + (1) 1 = F; + (s.N) 1 = T s.N; + (s.N) e.X, : { + (e.X2) 0 = ) e.X2>; + e.Z = F; + }; + e.X = ; +}; + +FracRun { + 0 e.X = ; + s.I (e.N) e.P, : { + Halt = e.N; + Next e.N2 = e.N (e.N2) e.P>; + }; +}; + +FracStep { + (e.N) = Halt; + (e.N) ((e.Num) e.Denom) e.P, + ) e.Denom>: { + (e.N2) 0 = Next e.N2; + e.X = ; + }; +}; + +Prog { + e.X, : T (e.F) e.R = (e.F) ; + e.X = ; +}; + +Frac { + e.X, : T (e.N) e.X2, + : '/' e.X3, + : T (e.D) e.X4 = + T ((e.N) e.D) e.X4; + e.X = F e.X; +}; + +Num { + e.X, >: { + () e.R = F e.R; + (e.N) e.R = T () e.R; + }; +}; + +Span { + (e.M) (e.S) s.C e.X, e.S: e.1 s.C e.2 = ; + (e.M) (e.S) e.X = (e.M) e.X; + (e.S) e.X = ; +}; + +SkipWs { + s.C e.X, ' \n\t': e.1 s.C e.2 = ; + e.X = e.X; +}; diff --git a/Task/Fractran/SETL/fractran.setl b/Task/Fractran/SETL/fractran.setl new file mode 100644 index 0000000000..05f2b18236 --- /dev/null +++ b/Task/Fractran/SETL/fractran.setl @@ -0,0 +1,52 @@ +program fractran; + p := parse_fractran( + "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" + ); + + print(frac_run_steps(p, 2, 15)); + print(frac_primes(p, 2, 20)); + + proc frac_primes(p, n, nprimes); + primes := []; + loop for i in [1..nprimes] do + loop until n bit_and (n-1) = 0 do + n := frac_step(p, n); + end loop; + primes with:= log n/log 2; + end loop; + return primes; + end proc; + + proc frac_run_steps(p, n, steps); + return [n] + [n := frac_step(p, n) : i in [2..steps]]; + end proc; + + proc frac_step(p, n); + if exists [num, denom] in p | n * num mod denom = 0 then + return n * num div denom; + end if; + return om; + end proc; + + proc rdws(rw s); + span(s, " \t\n"); + end proc; + + proc rdnum(rw s); + rdws(s); + return val span(s, "0123456789"); + end proc; + + proc rdfrac(rw s); + if (num := rdnum(s)) = om then return om; end if; + rdws(s); + if match(s, "/") = "" then return om; end if; + if (denom := rdnum(s)) = om then return om; end if; + return [num, denom]; + end proc; + + proc parse_fractran(s); + return [f := rdfrac(s) : until f=om]; + end proc; +end program; diff --git a/Task/Function-composition/FutureBasic/function-composition.basic b/Task/Function-composition/FutureBasic/function-composition.basic new file mode 100644 index 0000000000..8df8fe887d --- /dev/null +++ b/Task/Function-composition/FutureBasic/function-composition.basic @@ -0,0 +1,14 @@ +double local fn FunctionF( x as double ) +end fn = x + 1.5 + +double local fn FunctionG( x as double ) +end fn = x * x + +double local fn Compose( f as ptr, g as ptr ) + double def fn ff(x1 as double) using f + double def fn fg(x2 as double) using g +end fn = fn ff(fn fg(2.5)) + +print fn Compose( @fn FunctionF, @fn FunctionG ) + +HandleEvents diff --git a/Task/Function-definition/FutureBasic/function-definition.basic b/Task/Function-definition/FutureBasic/function-definition-1.basic similarity index 100% rename from Task/Function-definition/FutureBasic/function-definition.basic rename to Task/Function-definition/FutureBasic/function-definition-1.basic diff --git a/Task/Function-definition/FutureBasic/function-definition-2.basic b/Task/Function-definition/FutureBasic/function-definition-2.basic new file mode 100644 index 0000000000..c6c813c61b --- /dev/null +++ b/Task/Function-definition/FutureBasic/function-definition-2.basic @@ -0,0 +1,8 @@ +window 1 + +long local fn multiply( a as long, b as long ) +end fn = a * b + +print fn multiply( 3, 9 ) + +HandleEvents diff --git a/Task/Function-prototype/FutureBasic/function-prototype.basic b/Task/Function-prototype/FutureBasic/function-prototype.basic index 547ce06eff..9a96932ecb 100644 --- a/Task/Function-prototype/FutureBasic/function-prototype.basic +++ b/Task/Function-prototype/FutureBasic/function-prototype.basic @@ -1,3 +1,4 @@ def fn NoArgs def fn TwoArgs( a as long, b as long ) def fn VarArgs( n as long, ... ) +long def fn Multiply( a as long, b as long ) // function returns a value diff --git a/Task/Fusc-sequence/FutureBasic/fusc-sequence.basic b/Task/Fusc-sequence/FutureBasic/fusc-sequence.basic new file mode 100644 index 0000000000..4f848b700e --- /dev/null +++ b/Task/Fusc-sequence/FutureBasic/fusc-sequence.basic @@ -0,0 +1,40 @@ +_max = 20000000 + +begin globals +NSUInteger f(_max) +end globals + +void local fn Fusc + f(0) = 0 : f(1) = 1 + for NSUInteger n = 2 to _max + if ( n & 1 ) + f(n) = f((n - 1) / 2) + f((n + 1) / 2) + else + f(n) = f(n / 2) + end if + next +end fn + +void local fn DoIt + NSUInteger i, d = 0 + + fn Fusc + + for i = 0 to 60 + print f(i);" "; + if ( i == 32 ) then print + next + + print : print : print @" index\t\t value" + for i = 0 to _max + if ( f(i) >= d ) + printf @"%11lu\t\t%6lu",i,f(i) + if ( d == 0 ) then d = 1 + d *= 10 + end if + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Gamma-function/REXX/gamma-function-3.rexx b/Task/Gamma-function/REXX/gamma-function-3.rexx index 0e72ca6abf..37ad3facc1 100644 --- a/Task/Gamma-function/REXX/gamma-function-3.rexx +++ b/Task/Gamma-function/REXX/gamma-function-3.rexx @@ -49,7 +49,7 @@ procedure expose glob. fact. arg x /* Formulas for negative and positive (half)integers */ if x < 0 then do - if IsHalf(x) then do + if Half(x) then do numeric digits Digits()+2 i = Abs(Floor(x)); y = (-1)**i*2**(2*i)*Fact(i)*Sqrt(Pi())/Fact(2*i) numeric digits Digits()-2 @@ -57,9 +57,9 @@ if x < 0 then do end end if x > 0 then do - if IsWhole(x) then + if Whole(x) then return Fact(x-1) - if IsHalf(x) then do + if Half(x) then do numeric digits Digits()+2 i = Floor(x); y = Fact(2*i)*Sqrt(Pi())/(2**(2*i)*Fact(i)) numeric digits Digits()-2 diff --git a/Task/Gapful-numbers/ALGOL-68/gapful-numbers.alg b/Task/Gapful-numbers/ALGOL-68/gapful-numbers.alg index e9f1e423de..55c4cf9bb7 100644 --- a/Task/Gapful-numbers/ALGOL-68/gapful-numbers.alg +++ b/Task/Gapful-numbers/ALGOL-68/gapful-numbers.alg @@ -23,10 +23,10 @@ BEGIN # find some gapful numbers - numbers divisible by f*10 + b # result END; # GAPFUL # # prints a sequence of gapful numbers # - PROC print gapful = ( []INT seq, INT start )VOID: + PROC print gapful = ( []INT seq, INT nstart )VOID: BEGIN print( ( "First ", whole( ( UPB seq + 1 ) - LWB seq, 0 ) - , " gapful numbers starting from ", whole( start, 0 ) + , " gapful numbers starting from ", whole( nstart, 0 ) , ":", newline ) ); diff --git a/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg b/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg index 2b79d01805..14b3603189 100644 --- a/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg +++ b/Task/Gauss-Jordan-matrix-inversion/ALGOL-68/gauss-jordan-matrix-inversion.alg @@ -43,16 +43,17 @@ BEGIN # Gauss-Jordan matrix inversion # OD END # show #; - INT n = 4; - [ 1 : n, 1 : n ]REAL a, b, c; - a := [,]REAL( ( 2, 1, 1, 4 ) - , ( 0, -1, 0, -1 ) - , ( 1, 0, -2, 4 ) - , ( 4, 1, 2, 2 ) - ); - show( "a", a ); - b := inverse( a ); - show( "b", b ); - c := inverse( b ); - show( "c", c ) + BEGIN # test # + [ 1 : 4, 1 : 4 ]REAL a, b, c; + a := [,]REAL( ( 2, 1, 1, 4 ) + , ( 0, -1, 0, -1 ) + , ( 1, 0, -2, 4 ) + , ( 4, 1, 2, 2 ) + ); + show( "a", a ); + b := inverse( a ); + show( "b", b ); + c := inverse( b ); + show( "c", c ) + END END diff --git a/Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 b/Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 new file mode 100644 index 0000000000..d3f43119aa --- /dev/null +++ b/Task/Gaussian-elimination/XPL0/gaussian-elimination.xpl0 @@ -0,0 +1,43 @@ +proc Gauss(A, B, X, N); \Gaussian elimination returns [X] for [A]*[X] = [B] +real A, B, X; int N; \matrix, vector, output vector, number of rows +int Diag, MaxRow, Row, Col, I; +real Max, Temp; +[for Diag:= 0 to N-1 do \partial pivoting uses largest magnitude coefficient + [MaxRow:= Diag; \ to improve numerical stability + Max:= A(Diag, Diag); + for Row:= Diag+1 to N-1 do + [Temp:= abs(A(Row, Diag)); + if Temp > Max then + [MaxRow:= Row; Max:= Temp]; + ]; + Temp:= A(Diag); A(Diag):= A(MaxRow); A(MaxRow):= Temp; \swap rows + Temp:= B(Diag); B(Diag):= B(MaxRow); B(MaxRow):= Temp; + for Row:= Diag+1 to N-1 do + [Temp:= A(Row, Diag) / A(Diag, Diag); \divide by pivot element + for Col:= Diag+1 to N-1 do + A(Row, Col):= A(Row, Col) - Temp*A(Diag, Col); + A(Row, Diag):= 0.; + B(Row):= B(Row) - Temp*B(Diag); + ]; + ]; \reduced row echelon form +for Row:= N-1 downto 0 do \back substitution makes [X] + [Temp:= B(Row); + for I:= N-1 downto Row+1 do + Temp:= Temp - X(I)*A(Row, I); + X(Row):= Temp / A(Row, Row); + ]; +]; + +real A, B, X(6); +int I; +[A:= [ [1.00, 0.00, 0.00, 0.00, 0.00, 0.00], + [1.00, 0.63, 0.39, 0.25, 0.16, 0.10], + [1.00, 1.26, 1.58, 1.98, 2.49, 3.13], + [1.00, 1.88, 3.55, 6.70, 12.62, 23.80], + [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], + [1.00, 3.14, 9.87, 31.01, 97.41, 306.02] ]; +B:= [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02]; +Gauss(A, B, X, 6); +for I:= 0 to 6-1 do + [RlOut(0, X(I)); CrLf(0)]; +] diff --git a/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg b/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg index 301d6ba2ca..046fa5220b 100644 --- a/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg +++ b/Task/General-FizzBuzz/ALGOL-68/general-fizzbuzz.alg @@ -1,25 +1,25 @@ BEGIN # generalised FizzBuzz # # prompts for an integer, reads it and returns it # - PROC read integer = ( STRING prompt )INT: + PROC read an integer = ( STRING prompt )INT: BEGIN print( ( prompt ) ); INT result; read( ( result, newline ) ); result - END; # read integer # + END; # read an integer # # prompts for a string, reads it and returns it # - PROC read string = ( STRING prompt )STRING: + PROC read a string = ( STRING prompt )STRING: BEGIN print( ( prompt ) ); STRING result; read( ( result, newline ) ); result - END; # read string # + END; # read a string # # mode to hold a factor and associated text # MODE FBFACTOR = STRUCT( INT factor, STRING text ); #===============================================================# - # quicksort routine for the factors, from the Algol 68 uicksort # - # task sample # + # quicksort routine for the factors # + # - from the Algol 68 task sample # #---------------------------------------------------------------# #--- Swap function ---# PROC swap = (REF[]FBFACTOR array, INT first, INT second) VOID: @@ -51,14 +51,14 @@ BEGIN # generalised FizzBuzz # OP > = ( FBFACTOR a, b )BOOL: factor OF a > factor OF b; #===============================================================# # get the maximum number to consider # - INT max number = read integer( "Numbers reuired: " ); - # number of factors reuired # + INT max number = read an integer( "Numbers required: " ); + # number of factors required # INT max factor = 3; # get the factors and associated words # [ max factor ]FBFACTOR factors; FOR i TO max factor DO - factor OF factors[ i ] := read integer( "Factor " + whole( i, 0 ) + ": " ); - text OF factors [ i ] := read string( "Text for " + whole( factor OF factors[ i ], 0 ) + ": " ) + factor OF factors[ i ] := read an integer( "Factor " + whole( i, 0 ) + ": " ); + text OF factors [ i ] := read a string( "Text for " + whole( factor OF factors[ i ], 0 ) + ": " ) OD; # sort the factors into order # quick( factors, 1, UPB factors ); diff --git a/Task/Generic-swap/Jq/generic-swap-1.jq b/Task/Generic-swap/Jq/generic-swap-1.jq index caf53e505b..102f51f565 100644 --- a/Task/Generic-swap/Jq/generic-swap-1.jq +++ b/Task/Generic-swap/Jq/generic-swap-1.jq @@ -1 +1 @@ -jq -n '1 as $a | 2 as $b | $a as $tmp | $b as $a | $tmp as $b | [$a,$b]' +{a: 1, b: 2} | {a: .b, b: a.} diff --git a/Task/Generic-swap/Jq/generic-swap-4.jq b/Task/Generic-swap/Jq/generic-swap-4.jq new file mode 100644 index 0000000000..caf53e505b --- /dev/null +++ b/Task/Generic-swap/Jq/generic-swap-4.jq @@ -0,0 +1 @@ +jq -n '1 as $a | 2 as $b | $a as $tmp | $b as $a | $tmp as $b | [$a,$b]' diff --git a/Task/Generic-swap/M2000-Interpreter/generic-swap-3.m2000 b/Task/Generic-swap/M2000-Interpreter/generic-swap-3.m2000 new file mode 100644 index 0000000000..0c066ce00a --- /dev/null +++ b/Task/Generic-swap/M2000-Interpreter/generic-swap-3.m2000 @@ -0,0 +1,19 @@ +dim a(10) as byte +a(3)=2 +a(4)=100 +Print a() +swap a(3), a(4) +Print a() +try ok { + a(0)=-1 +} +if not ok then print error$ =" Overflow Byte" +try ok { + a(0)=256 +} +if not ok then print error$ =" Overflow Byte" +a()=a()#rev() +Print a() +Print type$(a(3)) +Print a(10-3-1)=100 +Print a(10-4-1)=2 diff --git a/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx b/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx new file mode 100644 index 0000000000..db599de5d4 --- /dev/null +++ b/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx @@ -0,0 +1,57 @@ +include Settings + +say version; say 'Goldbach''s comet'; say +numeric digits 7 +call GetPrimes +call ShowFirst100 +call ShowMillion +exit + +GetPrimes: +procedure expose prim. +call Time('r') +say 'Collect Primes up to 1000000...' +call Primes(1e6) +say Time('e')/1 'seconds' +say +return + +ShowFirst100: +procedure expose prim. +call Time('r') +say 'First 100 values...' +do i = 4 by 2 to 202 + call Charout ,Right(Goldbach(i),3) + if i//20 = 2 then + say +end +say Time('e')/1 'seconds' +say +return + +ShowMillion: +procedure expose prim. +call Time('r') +say 'G(1000000)...' +say Goldbach(1e6) +say Time('e')/1 'seconds' +say +return + +Goldbach: +procedure expose prim. +arg x +y = 0 +do i = 2 to x%2 + if prim.flag.i then do + j = x-i + if prim.flag.j then do + y = y+1 + end + end +end +return y/1 + +include Abend +include Functions +include Sequences diff --git a/Task/Greedy-algorithm-for-Egyptian-fractions/ALGOL-68/greedy-algorithm-for-egyptian-fractions.alg b/Task/Greedy-algorithm-for-Egyptian-fractions/ALGOL-68/greedy-algorithm-for-egyptian-fractions.alg index 653de829fb..0d7c9e866c 100644 --- a/Task/Greedy-algorithm-for-Egyptian-fractions/ALGOL-68/greedy-algorithm-for-egyptian-fractions.alg +++ b/Task/Greedy-algorithm-for-Egyptian-fractions/ALGOL-68/greedy-algorithm-for-egyptian-fractions.alg @@ -1,4 +1,4 @@ -BEGIN # compute some Egytian fractions # +BEGIN # compute some Egyptian fractions # PR precision 2000 PR # set the number of digits for LONG LONG INT # PROC gcd = ( LONG LONG INT a, b )LONG LONG INT: IF b = 0 THEN @@ -14,7 +14,7 @@ BEGIN # compute some Egytian fractions # MODE LISTOFRATIONAL = STRUCT( RATIONAL element, REF LISTOFRATIONAL next ); REF LISTOFRATIONAL nil list of rational = NIL; OP TOSTRING = ( INT a )STRING: whole( a, 0 ); - OP TOSTRING = ( LONG INT a )STRING: whole( a, 0 ); +CO OP TOSTRING = ( LONG INT a )STRING: whole( a, 0 ); # not needed for the task # CO OP TOSTRING = ( LONG LONG INT a )STRING: whole( a, 0 ); OP TOSTRING = ( RATIONAL a )STRING: IF den OF a = 1 @@ -49,12 +49,12 @@ BEGIN # compute some Egytian fractions # ELSE REF LISTOFRATIONAL result := nil list of rational; REF LISTOFRATIONAL end result := nil list of rational; - PROC add = ( RATIONAL r )VOID: + PROC add = ( RATIONAL rn )VOID: IF end result IS nil list of rational THEN - result := HEAP LISTOFRATIONAL := ( r, nil list of rational ); + result := HEAP LISTOFRATIONAL := ( rn, nil list of rational ); end result := result ELSE - next OF end result := HEAP LISTOFRATIONAL := ( r, nil list of rational ); + next OF end result := HEAP LISTOFRATIONAL := ( rn, nil list of rational ); end result := next OF end result FI ; # add # IF num OF r > den OF r THEN diff --git a/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm b/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm index b0311a38ee..5219a0c4e9 100644 --- a/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm +++ b/Task/Hailstone-sequence/Scheme/hailstone-sequence.scm @@ -1,16 +1,24 @@ (define (collatz n) -(if (= n 1) '(1) -(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n))))))) + (if (= n 1) + (list 1) + (cons n + (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n))))))) (define (collatz-length n) -(let aux ((n n) (r 1)) (if (= n 1) r -(aux (if (even? n) (/ n 2) (+ 1 (* 3 n))) (+ r 1))))) + (let aux ((n n) (r 1)) + (if (= n 1) + r + (aux (if (even? n) (/ n 2) (+ 1 (* 3 n))) + (+ r 1))))) (define (collatz-max a b) -(let aux ((i a) (j 0) (k 0)) -(if (> i b) (list j k) -(let ((h (collatz-length i))) -(if (> h k) (aux (+ i 1) i h) (aux (+ i 1) j k)))))) + (let aux ((i a) (j 0) (k 0)) + (if (> i b) + (list j k) + (let ((h (collatz-length i))) + (if (> h k) + (aux (+ i 1) i h) + (aux (+ i 1) j k)))))) (collatz 27) ; (27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-4.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-4.rexx new file mode 100644 index 0000000000..3d590eb3a0 --- /dev/null +++ b/Task/Hamming-numbers/REXX/hamming-numbers-4.rexx @@ -0,0 +1,73 @@ +include Settings + +say version; say 'Hamming numbers'; say +call Hammings 1e6 +call ShowFirstN 20 +call ShowNth 1691 +call ShowNth 1e6 +call Hammings 1e7 +call ShowNth 1e7 +exit + +Hammings: +procedure expose hamm. +arg xx +call Time('r') +xx = xx/1 +say 'Collect Hamming numbers up to the' xx'th' +/* Ensure enough digits */ +numeric digits 2**(Length(xx)+1) +/* Dijkstra */ +hamm.hamming.1 = 1 +x2 = 2; x3 = 3; x5 = 5; i2 = 1; i3 = 1; i5 = 1 +do yy = 2 + h = x2 + if x3 < h then + h = x3 + if x5 < h then + h = x5 + hamm.hamming.yy = h + if yy = xx then + leave + if x2 = h then do + i2 = i2+1; x2 = hamm.hamming.i2+hamm.hamming.i2 + end + if x3 = h then do + i3 = i3+1; x3 = hamm.hamming.i3+hamm.hamming.i3+hamm.hamming.i3 + end + if x5 = h then do + i5 = i5+1; x5 = hamm.hamming.i5*5 + end +end +hamm.0 = yy +say Time('e')/1 'seconds' +say +return + +ShowFirstN: +procedure expose hamm. +arg xx +call Time('r') +xx = xx/1 +say 'First' xx 'Hamming numbers are' +do i = 1 to xx + call Charout ,Right(hamm.hamming.i,5) + if i//10 = 0 then + say +end +say Time('e')/1 'seconds' +say +return + +ShowNth: +procedure expose hamm. +arg xx +xx = xx/1 +call Time('r') +say xx'th Hamming Number is' +say hamm.hamming.xx '('Length(hamm.hamming.xx) 'digits)' +say Time('e')/1 'seconds' +say +return + +include Abend diff --git a/Task/Harmonic-series/ALGOL-68/harmonic-series.alg b/Task/Harmonic-series/ALGOL-68/harmonic-series.alg index 1746c38513..a050da661d 100644 --- a/Task/Harmonic-series/ALGOL-68/harmonic-series.alg +++ b/Task/Harmonic-series/ALGOL-68/harmonic-series.alg @@ -2,12 +2,12 @@ BEGIN # find some harmonic numbers, Hn is the sum of the reciprocals of 1..n # # returns the first n Harmonic numbers # OP HARMONIC = ( INT n )[]REAL: BEGIN - [ 1 : n ]REAL h; - h[ 1 ] := 1; + [ 1 : n ]REAL hs; + hs[ 1 ] := 1; FOR i FROM 2 TO n DO - h[ i ] := h[ i - 1 ] + ( 1 / i ) + hs[ i ] := hs[ i - 1 ] + ( 1 / i ) OD; - h + hs END # HARMONIC # ; # find the first 20 000 harmonic numbers # []REAL h = HARMONIC 20 000; diff --git a/Task/Harmonic-series/CBASIC/harmonic-series.basic b/Task/Harmonic-series/CBASIC/harmonic-series.basic index a98d0afede..35bb0c4f57 100644 --- a/Task/Harmonic-series/CBASIC/harmonic-series.basic +++ b/Task/Harmonic-series/CBASIC/harmonic-series.basic @@ -1,7 +1,7 @@ limit = 20 h = 0 print "First";limit;"numbers in the harmonic series" -for i = 1 to 20 +for i = 1 to limit h = h + 1 / i print using "## #.#####"; i; h next i diff --git a/Task/Hello-world-Text/C/hello-world-text-1.c b/Task/Hello-world-Text/C/hello-world-text-1.c index 25b7d304c2..172c037a05 100644 --- a/Task/Hello-world-Text/C/hello-world-text-1.c +++ b/Task/Hello-world-Text/C/hello-world-text-1.c @@ -1,8 +1,7 @@ -#include -#include +#include -int main(void) +int main() { - printf("Hello world!\n"); - return EXIT_SUCCESS; + printf("\nHello world!"); + return 0; } diff --git a/Task/Hello-world-Text/C/hello-world-text-2.c b/Task/Hello-world-Text/C/hello-world-text-2.c index ccbb562e43..1ad413c047 100644 --- a/Task/Hello-world-Text/C/hello-world-text-2.c +++ b/Task/Hello-world-Text/C/hello-world-text-2.c @@ -1,8 +1,6 @@ -#include -#include +#include -int main(void) +int main() { - puts("Hello world!"); - return EXIT_SUCCESS; + return printf("\nHello World!"); } diff --git a/Task/Hello-world-Text/C/hello-world-text-3.c b/Task/Hello-world-Text/C/hello-world-text-3.c index 172c037a05..25b7d304c2 100644 --- a/Task/Hello-world-Text/C/hello-world-text-3.c +++ b/Task/Hello-world-Text/C/hello-world-text-3.c @@ -1,7 +1,8 @@ -#include +#include +#include -int main() +int main(void) { - printf("\nHello world!"); - return 0; + printf("Hello world!\n"); + return EXIT_SUCCESS; } diff --git a/Task/Hello-world-Text/C/hello-world-text-4.c b/Task/Hello-world-Text/C/hello-world-text-4.c index 1ad413c047..ccbb562e43 100644 --- a/Task/Hello-world-Text/C/hello-world-text-4.c +++ b/Task/Hello-world-Text/C/hello-world-text-4.c @@ -1,6 +1,8 @@ -#include +#include +#include -int main() +int main(void) { - return printf("\nHello World!"); + puts("Hello world!"); + return EXIT_SUCCESS; } diff --git a/Task/Hello-world-Web-server/FreeBASIC/hello-world-web-server.basic b/Task/Hello-world-Web-server/FreeBASIC/hello-world-web-server.basic new file mode 100644 index 0000000000..cde1d9cf39 --- /dev/null +++ b/Task/Hello-world-Web-server/FreeBASIC/hello-world-web-server.basic @@ -0,0 +1,76 @@ +#include once "windows.bi" +#include once "win/winsock2.bi" + +Type SOCKET As Ulongint + +' Define the response text +Const RESPONSE_TEXT = "Goodbye, World!" +Const CRLF = Chr(13) & Chr(10) + +' Initialize Winsock +Dim As WSADATA wsaData +If WSAStartup(&h0202, @wsaData) Then + Print "Error initializing Winsock" + End 1 +End If + +' Create a socket +Dim As SOCKET serverSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0) +If serverSocket = INVALID_SOCKET Then + Print "Error creating socket" + WSACleanup() + End 1 +End If + +' Bind the socket to the port +Dim As sockaddr_in serverAddr +With serverAddr + .sin_family = AF_INET + .sin_addr.s_addr = INADDR_ANY + .sin_port = htons(8080) +End With + +' Bind the socket to the port +If bind(serverSocket, Cast(sockaddr Ptr, @serverAddr), Sizeof(sockaddr_in)) = SOCKET_ERROR Then + Print "Error binding socket" + closesocket(serverSocket) + WSACleanup() + End 1 +End If + +' Listen for incoming connections +If listen(serverSocket, SOMAXCONN) = SOCKET_ERROR Then + Print "Error listening on socket" + closesocket(serverSocket) + WSACleanup() + End 1 +End If + +Print "Server is running on http://localhost:8080/" + +' Main server loop +Do + Dim As sockaddr_in clientAddr + Dim As Long clientAddrLen = Sizeof(sockaddr_in) + + Dim As SOCKET clientSocket = accept(serverSocket, Cast(sockaddr Ptr, @clientAddr), @clientAddrLen) + If clientSocket = INVALID_SOCKET Then + Print "Error accepting connection" + Continue Do + End If + + ' Build and send the HTTP response + Dim As String httpResponse = _ + "HTTP/1.1 200 OK" & CRLF & _ + "Content-Length: " & Len(RESPONSE_TEXT) & CRLF & _ + "Content-Type: text/plain" & CRLF & _ + CRLF & _ + RESPONSE_TEXT + + send(clientSocket, Strptr(httpResponse), Len(httpResponse), 0) + closesocket(clientSocket) +Loop + +' Final cleaning +closesocket(serverSocket) +WSACleanup() diff --git a/Task/History-variables/FreeBASIC/history-variables.basic b/Task/History-variables/FreeBASIC/history-variables.basic new file mode 100644 index 0000000000..2c61e3f4d2 --- /dev/null +++ b/Task/History-variables/FreeBASIC/history-variables.basic @@ -0,0 +1,60 @@ +REM integer history variable + +Type HistoryInt + As Integer Ptr values + As Integer cnt + As Integer capacity +End Type + +Function InitHistory() As HistoryInt Ptr + Dim As HistoryInt Ptr hist = Allocate(Sizeof(HistoryInt)) + hist->capacity = 10 + hist->values = Allocate(hist->capacity * Sizeof(Integer)) + hist->cnt = 0 + Return hist +End Function + +Sub SetInt(hist As HistoryInt Ptr, value As Integer) + If hist->cnt >= hist->capacity Then + hist->capacity *= 2 + hist->values = Reallocate(hist->values, hist->capacity * Sizeof(Integer)) + End If + + If hist->cnt = 0 Then + hist->values[hist->cnt] = 0 + hist->cnt += 1 + End If + + hist->values[hist->cnt] = value + hist->cnt += 1 +End Sub + +Sub ShowHistory(hist As HistoryInt Ptr) + For i As Integer = 0 To hist->cnt - 1 + Print hist->values[i] + Next +End Sub + +Function UndoInt(hist As HistoryInt Ptr) As Integer + If hist->cnt <= 1 Then Return hist->values[0] + hist->cnt -= 1 + Return hist->values[hist->cnt - 1] +End Function + +' Main program +Randomize Timer +Dim As HistoryInt Ptr x = InitHistory() + +For i As Integer = 0 To 3 + SetInt(x, Int(Rnd * 50) + 100) +Next + +Print "x history:" +ShowHistory(x) +Print + +For i As Integer = 0 To 3 + Print "undo, x ="; UndoInt(x) +Next + +Sleep diff --git a/Task/History-variables/Phix/history-variables-1.phix b/Task/History-variables/Phix/history-variables-1.phix index 0d84745f09..8270fe1bbe 100644 --- a/Task/History-variables/Phix/history-variables-1.phix +++ b/Task/History-variables/Phix/history-variables-1.phix @@ -1,15 +1,13 @@ ---> - without js -- (desktop/Phix only) - sequence history = {} +without js -- (desktop/Phix only) +sequence history = {} - type hvt(object o) - history = append(history,o) - return true - end type +type hv(object o) + history = append(history,o) + return true +end type - hvt test = 1 - test = 2 - test = 3 - ?{"current",test} - ?{"history",history} - - -- history.e - sequence histories = {} +-- history.e +sequence histories = {} - global function new_history_id(object v) - histories = append(histories,{v}) - return length(histories) - end function +global function new_history_id(object v) + histories = append(histories,{v}) + return length(histories) +end function - global procedure set_hv(integer hv, object v) - histories[hv] = append(histories[hv],v) - end procedure +global procedure set_hv(integer hv, object v) + histories[hv] = append(histories[hv],v) +end procedure - global function get_hv(integer hv) - return histories[hv][$] - end function +global function get_hv(integer hv) + return histories[hv][$] +end function - global function get_hv_full_history(integer hv) - return histories[hv] - end function - - include history.e +with javascript_semantics +include history.e - constant test2 = new_history_id(1) - set_hv(test2, 2) - set_hv(test2, 3) - ?{"current",get_hv(test2)} - ?{"history",get_hv_full_history(test2)} - - function skipping(sequence prisoners, integer step, survivors=1) - integer n = length(prisoners), nn = n, p = 0 - while n>survivors do - integer found = 0 - while found<step do - p = iff(p=nn?1:p+1) - found += prisoners[p]!=-1 - end while - prisoners[p] = -1 - n -= 1 - end while - return remove_all(-1,prisoners) - end function - --?skipping({"Joe","Jack","William","John","James"},2,1) --> {"William"} - - function linked_list(sequence prisoners, integer step, survivors) - integer n = length(prisoners) - sequence links = tagset(n,2)&1 - integer p = n, prvp - while n>survivors do - for i=1 to step do - prvp = p - p = links[p] - end for - prisoners[p] = -1 - links[prvp] = links[p] - n -= 1 - end while - return remove_all(-1,prisoners) - end function - - function sliding_queue(sequence prisoners, integer step, survivors) - integer n = length(prisoners) - while n>survivors do - integer k = remainder(step-1,n)+1 -- (mostly k==step) - prisoners = prisoners[k+1..$]&prisoners[1..k-1] -- rotate, dropping one. - n -= 1 - end while - return prisoners - end function - - function contractacycle(integer n, integer k, s) - sequence living = tagset(n) - integer startPosition = k, i, lasti - while n!=s do -- Keep going round the circle until only s prisoners remain. - integer circleSize = n - if (n < k) then - i = mod(startPosition-1,circleSize) + 1 - living = living[1..i-1]&living[i+1..$] - n -= 1 - lasti = i - else - for i=startPosition to circleSize by k do - living[i] = -1 - n -= 1 - if (n = s) then exit end if -- Not Groovy, see note - lasti = i - end for - living = remove_all(-1,living) - end if - startPosition = lasti + k - circleSize - end while - return living - end function - - function contractalot(integer n, integer k, s) - sequence list = tagset(n) - integer i = 1 - while n>s do - i += k - 1 - if (i > n) then i := mod(i-1, n)+1 end if - list [i..i] = {} - n -= 1 - end while - return list - end function - - function recursive(integer n, k) - return iff(n=1?1:1+mod(k-1+(recursive(n-1, k)),n)) - end function - - function iterative(integer n, k, m=0) - -- Return m-th on the reversed kill list; m=0 is final survivor. - for a = m+1 to n do - m = mod(m+k, a) - end for - return m + 1 -- (make result 1-based) - end function - - function iterative2(integer n,k,s) - integer a = k*(n-s) + 1, - olda = a - atom q = k/(k-1), - nk = n*k - while a <= nk do - olda = a - a = ceil(a*q) - end while - return nk - olda + 1 -- (make result 1-based) - end function - - --demo/rosetta/Josephus.exw - constant show_all = true, - show_slow = false, - show_skipping = false, - show_linkedlist = false, - show_sliding_queue = false, - show_contractacycle = false, - show_contractalot = false, - show_recursive = false, - show_iterative = false, - show_iterative2 = true - - constant TAGSET = #01, - ITER = #02, - ITER2 = #04, - SLOW = #08, - ONES = #10 - - constant tests = {{41,3,1,false}, - {41,3,3,false}, - {5,2,1,false}, - {5,4,1,false}, - {50,2,1,false}, - {60,3,1,false}, - {23482,3343,3,true}, - {23482,3343,1,true}, - {41,3,6,false}} - - procedure test(string name, integer flags) - atom t0 = time() - integer rid = routine_id(name) - for i=1 to length(tests) do - integer {prisoners, step, survivors, slow} = tests[i] - if (not and_bits(flags,ONES) or survivors=1) - and (not slow or show_slow or not and_bits(flags,SLOW)) then - sequence res - if and_bits(flags,ONES) then - -- (recursive does not take a 3rd param) - res = {rid(prisoners,step)} - elsif and_bits(flags,TAGSET) then - res = rid(tagset(prisoners),step,survivors) - elsif and_bits(flags,ITER) then - res = {} - for s=0 to survivors-1 do - res &= rid(prisoners,step,s) - end for - elsif and_bits(flags,ITER2) then - res = {} - for s=prisoners-survivors+1 to prisoners do - res &= rid(prisoners,step,s) - end for - else - res = rid(prisoners,step,survivors) - end if - printf(1,"%s(%d,%d,%d) = %v\n",{name,prisoners,step,survivors,res}) - end if - end for - ?elapsed(time()-t0) - end procedure - if show_all or show_skipping then test("skipping",TAGSET+SLOW) end if - if show_all or show_linkedlist then test("linked_list",TAGSET+SLOW) end if - if show_all or show_sliding_queue then test("sliding_queue",TAGSET+SLOW) end if - if show_all or show_contractacycle then test("contractacycle",SLOW) end if - if show_all or show_contractalot then test("contractalot",NULL) end if - if show_all or show_recursive then test("recursive",ONES) end if - if show_all or show_iterative then test("iterative",ITER) end if - if show_all or show_iterative2 then test("iterative2",ITER2) end if - {"William"} + +-- linked list - used by Arch64 Assembly, Ada, ARM Assembly, Common Lisp[2, probably], Fortran, +-- JavaScript[1] (albeit dbl-lnk), Python[3]. +-- Method: like skipping, all prisoners stay where they are, but +-- the executioner uses the links to speed things up a bit. +function linked_list(sequence prisoners, integer step, survivors) + integer n = length(prisoners) + sequence links = tagset(n,2)&1 + integer p = n, prvp + while n>survivors do + for i=1 to step do + prvp = p + p = links[p] + end for + prisoners[p] = -1 + links[prvp] = links[p] + n -= 1 + end while + return remove_all(-1,prisoners) +end function + +-- sliding queue - used by Clojure, Crystal, D (both), Eiffel, Elixir, Erlang, friendly interactive shell, Go, jq, +-- Perl, PowerShell, PureBasic (albeit one at a time), Quackery, Raku, REBOL, Ruby, Scala, +-- Sidef[1], Tcl, Vlang. +-- Method: all skipped prisoners rejoin the end of the queue which sidles left, +-- executioner stays put until the queue gets too short. +function sliding_queue(sequence prisoners, integer step, survivors) + integer n = length(prisoners) + while n>survivors do + integer k = remainder(step-1,n)+1 -- (mostly k==step) + prisoners = prisoners[k+1..$]&prisoners[1..k-1] -- rotate, dropping one. + n -= 1 + end while + return prisoners +end function + +-- contractacycle - used by AppleScript[2], Groovy +-- Method: executioner walks along killing every k'th prisoner; while he walks back the queue contracts to remove gaps. +-- (once the queue gets too small it obviously reverts to one at a time, a bit more like contractalot below) +function contractacycle(integer n, integer k, s) + sequence living = tagset(n) + integer startPosition = k, i, lasti + while n!=s do -- Keep going round the circle until only s prisoners remain. + integer circleSize = n + if (n < k) then + i = mod(startPosition-1,circleSize) + 1 + living = living[1..i-1]&living[i+1..$] + n -= 1 + lasti = i + else + for i=startPosition to circleSize by k do + living[i] = -1 + n -= 1 + if (n = s) then exit end if -- Not Groovy, see note + lasti = i + end for + living = remove_all(-1,living) + end if + startPosition = lasti + k - circleSize + end while + return living +end function +-- Groovy does not have a n=s test, it probably is entirely unnecessary. The Groovy code is also somewhat neater, +-- always using a loop and remove_all() - while not probihitively expensive, it may check lots of things for -1 +-- that the slicing won't. + +-- contractalot - used by 11L, Arturo, AutoHotkey, C#, C++, Delphi, Frink, Formulae, Java (both), JavaScript[2], +-- Julia[2], Kotlin, Lua, NanoQuery, Nim, Objeck, Oforth, Processing, Python[1], R[2], +-- Rust, Seed7, Swift, VBScript, Vedit, VisualBasic.NET, XPL0, zkl. +-- Method: executioner walks round and round, queue contracts after every kill. +-- Often implemented as execute all prisoners then release last one killed. +function contractalot(integer n, integer k, s) + sequence list = tagset(n) + integer i = 1 + while n>s do + i += k - 1 + if (i > n) then i := mod(i-1, n)+1 end if + list [i..i] = {} + n -= 1 + end while + return list +end function + +-- recursive - used by Emacs Lisp, Icon, Julia[1], PARI/GP, PicoLisp (less the optms.n), Sidef[2] +-- Method: recursive mod maths madness - only handles the lone survivor case. +function recursive(integer n, k) + return iff(n=1?1:1+mod(k-1+(recursive(n-1, k)),n)) +end function + +-- iterative - used by ALGOL 68, ANSI Standard BASIC, AppleScript[1,3(!!)], BASIC(*11), Batch File, C (but not ULL), +-- Common Lisp[1], Craft Basic, Easylang, EDSAC (allegedly), Factor, Forth, FreeBASIC, FTCBASIC, +-- FutureBasic, Modula-2, Python[2], R, Racket, Ring, SequenceL, ZX Spectrum Basic +-- Method: iterative mod maths madness - but hey, it will be extremely fast. +-- Unlike recursive, it can also deliver >1 survivor, one at a time. +function iterative(integer n, k, m=0) + -- Return m-th on the reversed kill list; m=0 is final survivor. + for a = m+1 to n do + m = mod(m+k, a) + end for + return m + 1 -- (make result 1-based) +end function + +-- iterative2 - used by Icon[2] +-- Method: more iterative maths madness +function iterative2(integer n,k,s) + integer a = k*(n-s) + 1, + olda = a + atom q = k/(k-1), + nk = n*k + while a <= nk do + olda = a + a = ceil(a*q) + end while + return nk - olda + 1 -- (make result 1-based) +end function + +-- test driver +--demo/rosetta/Josephus.exw +constant show_all = true, + show_slow = false, + show_skipping = false, + show_linkedlist = false, + show_sliding_queue = false, + show_contractacycle = false, + show_contractalot = false, + show_recursive = false, + show_iterative = false, + show_iterative2 = true + +constant TAGSET = #01, + ITER = #02, + ITER2 = #04, + SLOW = #08, + ONES = #10 + +constant tests = {{41,3,1,false}, + {41,3,3,false}, + {5,2,1,false}, + {5,4,1,false}, + {50,2,1,false}, + {60,3,1,false}, + {23482,3343,3,true}, + {23482,3343,1,true}, + {41,3,6,false}} + +procedure test(string name, integer flags) + atom t0 = time() + integer rid = routine_id(name) + for i=1 to length(tests) do + integer {prisoners, step, survivors, slow} = tests[i] + if (not and_bits(flags,ONES) or survivors=1) + and (not slow or show_slow or not and_bits(flags,SLOW)) then + sequence res + if and_bits(flags,ONES) then + -- (recursive does not take a 3rd param) + res = {rid(prisoners,step)} + elsif and_bits(flags,TAGSET) then + res = rid(tagset(prisoners),step,survivors) + elsif and_bits(flags,ITER) then + res = {} + for s=0 to survivors-1 do + res &= rid(prisoners,step,s) + end for + elsif and_bits(flags,ITER2) then + res = {} + for s=prisoners-survivors+1 to prisoners do + res &= rid(prisoners,step,s) + end for + else + res = rid(prisoners,step,survivors) + end if + printf(1,"%s(%d,%d,%d) = %v\n",{name,prisoners,step,survivors,res}) + end if + end for + ?elapsed(time()-t0) +end procedure +if show_all or show_skipping then test("skipping",TAGSET+SLOW) end if +if show_all or show_linkedlist then test("linked_list",TAGSET+SLOW) end if +if show_all or show_sliding_queue then test("sliding_queue",TAGSET+SLOW) end if +if show_all or show_contractacycle then test("contractacycle",SLOW) end if +if show_all or show_contractalot then test("contractalot",NULL) end if +if show_all or show_recursive then test("recursive",ONES) end if +if show_all or show_iterative then test("iterative",ITER) end if +if show_all or show_iterative2 then test("iterative2",ITER2) end if diff --git a/Task/K-d-tree/FreeBASIC/k-d-tree.basic b/Task/K-d-tree/FreeBASIC/k-d-tree.basic new file mode 100644 index 0000000000..ed87b0222b --- /dev/null +++ b/Task/K-d-tree/FreeBASIC/k-d-tree.basic @@ -0,0 +1,194 @@ +Const NULL As Any Ptr = 0 + +Type Point + coords(2) As Single '3D points +End Type + +Type KdNode + punto As Point + izda As KdNode Ptr + dcha As KdNode Ptr +End Type + +Type KdTree + root As KdNode Ptr + bestNode As KdNode Ptr + bestDist As Single + visited As Integer + dimensions As Integer +End Type + +Function Point_Distance(This As Point, pt As Point) As Single + Dim dist As Single = 0 + For i As Integer = 0 To 2 + Dim d As Single = this.coords(i) - pt.coords(i) + dist += d * d + Next + Return dist +End Function + +Function CreateNode(p As Point) As KdNode Ptr + Dim node As KdNode Ptr = New KdNode + node->punto = p + node->izda = NULL + node->dcha = NULL + Return node +End Function + +Function MakeTree(nodes() As KdNode Ptr, startIdx As Integer, endIdx As Integer, depth As Integer, dimensions As Integer) As KdNode Ptr + If endIdx <= startIdx Then Return NULL + + Dim As Integer midIdx = startIdx + (endIdx - startIdx) \ 2 + Dim As Integer axis = depth Mod dimensions + + For i As Integer = startIdx To endIdx - 1 + For j As Integer = i + 1 To endIdx + If nodes(i)->punto.coords(axis) > nodes(j)->punto.coords(axis) Then + Swap nodes(i), nodes(j) + End If + Next + Next + + nodes(midIdx)->izda = MakeTree(nodes(), startIdx, midIdx, depth + 1, dimensions) + nodes(midIdx)->dcha = MakeTree(nodes(), midIdx + 1, endIdx, depth + 1, dimensions) + + Return nodes(midIdx) +End Function + +Sub SearchNearest(node As KdNode Ptr, punto As Point, depth As Integer, tree As KdTree Ptr) + If node = NULL Then Exit Sub + + tree->visited += 1 + Dim As Single dist = Point_Distance(node->punto, punto) + + If tree->bestNode = NULL Orelse dist < tree->bestDist Then + tree->bestDist = dist + tree->bestNode = node + End If + + If tree->bestDist = 0 Then Exit Sub + + Dim As Integer axis = depth Mod tree->dimensions + Dim As Single dx = node->punto.coords(axis) - punto.coords(axis) + + If dx > 0 Then + SearchNearest(node->izda, punto, depth + 1, tree) + If dx * dx >= tree->bestDist Then Exit Sub + SearchNearest(node->dcha, punto, depth + 1, tree) + Else + SearchNearest(node->dcha, punto, depth + 1, tree) + If dx * dx >= tree->bestDist Then Exit Sub + SearchNearest(node->izda, punto, depth + 1, tree) + End If +End Sub + +Function BuildKdTree(points() As Point, dimensions As Integer) As KdTree Ptr + Dim As KdTree Ptr tree = New KdTree + If tree = NULL Then Return NULL + + tree->dimensions = dimensions + tree->bestDist = 0 + tree->visited = 0 + tree->root = NULL + tree->bestNode = NULL + + Dim nodes(Ubound(points)) As KdNode Ptr + For i As Integer = 0 To Ubound(points) + nodes(i) = CreateNode(points(i)) + If nodes(i) = NULL Then Return NULL + Next + + tree->root = MakeTree(nodes(), 0, Ubound(nodes), 0, dimensions) + Return tree +End Function + +Function FindNearest(tree As KdTree Ptr, punto As Point) As Point + Dim As Point result + + If tree = NULL Orelse tree->root = NULL Then Return result + + tree->bestNode = NULL + tree->visited = 0 + tree->bestDist = 0 + + SearchNearest(tree->root, punto, 0, tree) + + If tree->bestNode <> NULL Then result = tree->bestNode->punto + + Return result +End Function + +Sub TestWikipedia() + Print "Wikipedia example data:" + + Dim As Point points(5) + points(0).coords(0) = 2: points(0).coords(1) = 3 + points(1).coords(0) = 5: points(1).coords(1) = 4 + points(2).coords(0) = 9: points(2).coords(1) = 6 + points(3).coords(0) = 4: points(3).coords(1) = 7 + points(4).coords(0) = 8: points(4).coords(1) = 1 + points(5).coords(0) = 7: points(5).coords(1) = 2 + + Dim As KdTree Ptr tree = BuildKdTree(points(), 2) + If tree = NULL Then + Print "Error creating tree" + End 1 + End If + + Dim As Point searchPoint + searchPoint.coords(0) = 9 + searchPoint.coords(1) = 2 + + Dim As Point nearest = FindNearest(tree, searchPoint) + + Print "Nearest point: (" & nearest.coords(0) & ", " & nearest.coords(1) & ")" + Print "Distance: " & Sqr(tree->bestDist) + Print "Nodes visited: " & tree->visited + + Delete tree +End Sub + +Function RandomDouble(min As Single, max As Single) As Single + Return min + (max - min) * Rnd() +End Function + +Function CreateRandomPoint() As Point + Dim As Point p + p.coords(0) = RandomDouble(0, 1) + p.coords(1) = RandomDouble(0, 1) + p.coords(2) = RandomDouble(0, 1) + Return p +End Function + +Sub TestRandom(count As Integer) + Print "Random data (" & count & " points):" + + Dim As Point points(count-1) + For i As Integer = 0 To count-1 + points(i) = CreateRandomPoint() + Next + + Dim As KdTree Ptr tree = BuildKdTree(points(), 3) + + Dim As Point searchPoint = CreateRandomPoint() + Dim As Point nearest = FindNearest(tree, searchPoint) + + Print "Search point : (" & searchPoint.coords(0) & ", " & searchPoint.coords(1) & ", " & searchPoint.coords(2) & ")" + Print "Nearest point: (" & nearest.coords(0) & ", " & nearest.coords(1) & ", " & nearest.coords(2) & ")" + Print "Distance: " & Sqr(tree->bestDist) + Print "Nodes visited: " & tree->visited + + Delete tree +End Sub + +'Main program +' Original Wikipedia example +TestWikipedia() +Print +' Random tests +Randomize Timer +TestRandom(1000) +Print +TestRandom(10000) + +Sleep diff --git a/Task/K-d-tree/M2000-Interpreter/k-d-tree.m2000 b/Task/K-d-tree/M2000-Interpreter/k-d-tree.m2000 new file mode 100644 index 0000000000..7cb0d366b4 --- /dev/null +++ b/Task/K-d-tree/M2000-Interpreter/k-d-tree.m2000 @@ -0,0 +1,166 @@ +Module k_d { + push random(!381210&): drop + class point { + dim coords(0 to 2) As Single '3D points + remove { + REM ? "Deleted Point("+.coords()#str$(", ")+")" + } + class: + Module Point (a=0, b=0, c=0) { + .coords(0):=a,b,c + } + } + + class KdNode { + punto=pointer() + izda=pointer() + dcha=pointer() + class: + Module KdNode { + .punto<=pointer(point(![])) + } + } + class KdTree { + root=pointer() ' As KdNode Ptr + bestNode=pointer() ' As KdNode Ptr + Single bestDist + Integer visited, dimensions + remove { + .root<=pointer() + REM print "tree deleted" + } + class: + Module KdTree (&nodes(), dimensions As Integer) { + .dimensions<=dimensions + .root<= @MakeTree(0, len(nodes())-1, 0) + Function MakeTree(startIdx As Integer, endIdx As Integer, depth As Integer) + If endIdx <= startIdx Then =pointer(): exit function + local Integer midIdx = startIdx + (endIdx - startIdx) div 2, axis = depth Mod dimensions, i, j + Data startIdx, endIdx-1 + do If Stackitem()>=Stackitem(2) Then Drop 2:if empty then exit else continue + over 2,2 + Read p, r : i = p-1 + For nodes(r) { + x=.punto=>coords(axis) + For j=p to r-1 { + For nodes(j) {If ..punto=>coords(axis)> x Then i++: swap .punto, ..punto + }}:For nodes(i+1){swap .punto, ..punto}:Push i+2, i:shift 3 + } + Always + nodes(midIdx).izda = @MakeTree(startIdx, midIdx, depth + 1) + nodes(midIdx).dcha = @MakeTree(midIdx+1 , endIdx, depth + 1) + ->nodes(midIdx) + End Function + } + } + Function Global FindNearest(tree As *KdTree, punto As *Point) { + Function Point_Distance(Th As *Point, pt As *Point) { + Single dist, d : Integer i + For i = 0 To 2 + d= th=>coords(i) - pt=>coords(i) + dist += d * d + Next + =dist + } + result->point() + + If tree is type null then =result: exit + if tree=>root is type null Then =result: exit + + tree=>bestNode = Pointer() + tree=>visited = 0 + tree=>bestDist = 0 + + SearchNearest(tree=>root, 0, tree) + + If not tree=>bestNode is type null Then result = tree=>bestNode=>punto + + =result + + Sub SearchNearest(node as pointer, depth As Integer, tree As *KdTree) + If node is type null Then Exit Sub + tree=>visited ++ + + local Single dist = Point_Distance(node=>punto, punto) + If tree=>bestNode is type null or dist < tree=>bestDist Then + tree=>bestDist = dist + tree=>bestNode = node + End if + If tree=>bestDist = 0 Then Exit Sub + + Local Integer axis = depth Mod tree=>dimensions + Local Single dx= node=>punto=>coords(axis) - punto=>coords(axis) + If dx > 0 Then + SearchNearest(node=>izda, depth + 1, tree) + If dx * dx >= tree=>bestDist Then Exit Sub + SearchNearest(node=>dcha, depth + 1, tree) + Else + SearchNearest(node=>dcha, depth + 1, tree) + If dx * dx >= tree=>bestDist Then Exit Sub + SearchNearest(node=>izda, depth + 1, tree) + End If + End Sub + } + Module TestWikipedia { + Doc$ <= "Wikipedia example data:"+{ + } + searchPoint->Point(9, 2) + + k=stack:=2,3,5,4,9,6,4,7,8,1,7,2 + 'k=stack:=7, 2, 8, 1, 4, 7, 9, 6, 5, 4, 2, 3 + Feed=Lambda k -> { + if len(k)=0 then =point(): exit + stack k {->KdNode(number, number)} + } + + Dim points(0 to 5)<KdTree(&points(), 2) + nearest=FindNearest(tree, searchPoint) + Doc$ <= "Search point: (" + (searchPoint=>coords(0) )+ ", " + (searchPoint=>coords(1)) + ")"+{ + } + Doc$ <= "Nearest point: (" + (nearest=>coords(0) )+ ", " + (nearest=>coords(1)) + ")"+{ + } + Doc$ <= "Distance: " + (Sqrt(tree=>bestDist))+{ + } + Doc$ <= "Nodes visited: " + (tree=>visited)+{ + } + tree=pointer() + + } + Module TestRandom (count As Integer) { + doc$ <="Random data (" + count + " points):"+{ + } + integer i + searchPoint->Point(rnd, rnd, rnd) + feed =lambda ->{ + ->KdNode(rnd, rnd, rnd) + } + Dim points(count)<KdTree(&points(), 3) + nearest=FindNearest(tree, searchPoint) + Doc$ <= "Search point: (" +searchPoint=>coords()#str$(", ") + ")"+{ + } + Doc$ <= "Nearest point: (" +nearest=>coords()#str$(", ") + ")"+{ + } + Doc$ <= "Distance: " + (Sqrt(tree=>bestDist))+{ + } + Doc$ <= "Nodes visited: " + (tree=>visited)+{ + } + tree=pointer() + } + Global Doc$ + Document Doc$ + TestWikipedia + profiler + TestRandom 1000 + Print timecount + profiler + TestRandom 10000 + Print timecount + Report Doc$ + try{ + clipboard doc$ + } + Save.Doc doc$, "out.txt" +} +k_d diff --git a/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg b/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg index 27cc2b61e9..49f65a5e24 100644 --- a/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg +++ b/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg @@ -45,7 +45,7 @@ ELSE FILE real value; associate( real value, f ); on value error( real value - , ( REF FILE f )BOOL: + , ( REF FILE ef )BOOL: BEGIN # "handle" invalid data # result := 0; diff --git a/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-2.alg b/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-2.alg deleted file mode 100644 index 25bc6d8afa..0000000000 --- a/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-2.alg +++ /dev/null @@ -1,6 +0,0 @@ -main:( - [20]INT a; - FOR i FROM 1 TO 20 DO a[i] := i OD; - knuth shuffle(a); - print(a) -) diff --git a/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-1.alg b/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle.alg similarity index 69% rename from Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-1.alg rename to Task/Knuth-shuffle/ALGOL-68/knuth-shuffle.alg index f5202e6668..3a977799d1 100644 --- a/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle-1.alg +++ b/Task/Knuth-shuffle/ALGOL-68/knuth-shuffle.alg @@ -12,3 +12,9 @@ PROC knuth shuffle = (REF[]INT a)VOID: a[j] := t OD ); +# main # ( + [20]INT a; + FOR i FROM 1 TO 20 DO a[i] := i OD; + knuth shuffle(a); + print((a, newline)) +) diff --git a/Task/LU-decomposition/ALGOL-68/lu-decomposition.alg b/Task/LU-decomposition/ALGOL-68/lu-decomposition.alg new file mode 100644 index 0000000000..0b4f280798 --- /dev/null +++ b/Task/LU-decomposition/ALGOL-68/lu-decomposition.alg @@ -0,0 +1,112 @@ +BEGIN # LU decomposition - translation of the Kotlin sample # + + OP * = ( [,]REAL this, other )[,]REAL: + IF 1 LWB this /= 2 LWB other OR 1 UPB this /= 2 UPB other + THEN print( ( "Cannot multiply matrices: " ) ); + print( ( "[", whole( 1 LWB this, 0 ), ":", whole( 1 UPB this, 0 ) ) ); + print( ( ",", whole( 2 LWB this, 0 ), ":", whole( 2 UPB this, 0 ), "]" ) ); + print( ( " X " ) ); + print( ( "[", whole( 1 LWB other, 0 ), ":", whole( 1 UPB other, 0 ) ) ); + print( ( ",", whole( 2 LWB other, 0 ), ":", whole( 2 UPB other, 0 ), "]" ) ); + print( ( newline ) ); + stop + ELSE [ 1 LWB this : 1 UPB this, 2 LWB other : 2 UPB other ]REAL result; + FOR i FROM 1 LWB this TO 1 UPB this DO + FOR j FROM 2 LWB other TO 2 UPB other DO + result[ i, j ] := 0; + FOR k FROM 1 LWB other TO 1 UPB other DO + result[ i, j ] +:= this[ i, k ] * other[ k, j ] + OD + OD + OD; + result + FI # * # ; + + OP PIVOTISE = ( [,]REAL m in )[,]REAL: + BEGIN + [,]REAL m = m in[ AT 1, AT 1 ]; + INT n = ( 1 UPB m - 1 LWB m ) + 1; + [ 1 : n, 1 : n ]REAL im; + FOR i TO n DO + FOR j TO n DO im[ i, j ] := 0 OD; + im[ i, i ] := 1 + OD; + FOR i TO n DO + REAL max := ABS m[ i, i ]; + INT row := i; + FOR j FROM i TO n DO + IF ABS m[ j, i ] > max THEN + max := ABS m[ j, i ]; + row := j + FI + OD; + IF i /= row THEN + []REAL t = im[ i, : ]; + im[ i, : ] := im[ row, : ]; + im[ row, : ] := t + FI + OD; + im + END # PIVOTISE # ; + + MODE DECOMPOSITION = STRUCT( [ 1 : 1, 1 : 1 ]REAL l, u, p ); + + OP LU = ( [,]REAL a in )DECOMPOSITION: + BEGIN + [,]REAL a = a in[ AT 1, AT 1 ]; + INT n = ( 1 UPB a in - 1 LWB a in ) + 1; + [ 1 : n, 1 : n ]REAL l, u; + [,]REAL p = PIVOTISE a; + [,]REAL a2 = p * a; + FOR i TO n DO FOR j TO n DO l[ i, j ] := u[ i, j ] := 0 OD OD; + FOR j TO n DO + l[ j, j ] := 1; + FOR i TO j DO + REAL sum := 0; + FOR k TO i DO sum +:= u[ k, j ] * l[ i, k ] OD; + u[ i, j ] := a2[ i, j ] - sum + OD; + FOR i FROM j + 1 TO n DO + REAL sum := 0; + FOR k TO j DO sum +:= u[ k, j ] * l[ i, k ] OD; + l[ i, j ] := ( a2[ i, j ] - sum ) / u[ j, j ] + OD + OD; + DECOMPOSITION( l, u, p ) + END # LU # ; + + PROC show matrix = ( STRING title, [,]REAL m, INT fw, fdp )VOID: + BEGIN + print( ( " ", title, newline ) ); + FOR i FROM 1 LWB m TO 1 UPB m DO + print( ( " " ) ); + FOR j FROM 2 LWB m TO 2 UPB m DO print( ( fixed( m[ i, j ], -fw, fdp ), " " ) ) OD; + print( ( newline ) ) + OD + END # show matrix # ; + + BEGIN # test the LU decomposition operator # + [,]REAL a1 = ( ( 1.0, 3.0, 5.0 ) + , ( 2.0, 4.0, 7.0 ) + , ( 1.0, 1.0, 0.0 ) + ); + DECOMPOSITION d1 = LU a1; + print( ( "EXAMPLE 1:-", newline ) ); + show matrix( "A:", a1, 1, 0 ); + show matrix( "L:", l OF d1, 8, 5 ); + show matrix( "U:", u OF d1, 8, 5 ); + show matrix( "P:", p OF d1, 1, 0 ); + print( ( newline ) ); + [,]REAL a2 = ( ( 11.0, 9.0, 24.0, 2.0 ) + , ( 1.0, 5.0, 2.0, 6.0 ) + , ( 3.0, 17.0, 18.0, 1.0 ) + , ( 2.0, 5.0, 7.0, 1.0 ) + ); + DECOMPOSITION d2 = LU a2; + print( ( "EXAMPLE 2:-", newline ) ); + show matrix( "A:", a2, 2, 0 ); + show matrix( "L:", l OF d2, 8, 5 ); + show matrix( "U:", u OF d2, 8, 5 ); + show matrix( "P:", p OF d2, 1, 0 ) + END +END diff --git a/Task/LU-decomposition/FreeBASIC/lu-decomposition.basic b/Task/LU-decomposition/FreeBASIC/lu-decomposition.basic new file mode 100644 index 0000000000..b36a182334 --- /dev/null +++ b/Task/LU-decomposition/FreeBASIC/lu-decomposition.basic @@ -0,0 +1,100 @@ +Sub pivotize(m() As Double, im() As Double) + Dim As Integer n, i, j + n = Ubound(m) + Redim im(n, n) + + For i = 0 To n + For j = 0 To n + im(i, j) = 0 + Next j + im(i, i) = 1 + Next i + + For i = 0 To n + Dim As Double mx + Dim As Integer fila + mx = Abs(m(i, i)) + fila = i + For j = i To n + If Abs(m(j, i)) > mx Then + mx = Abs(m(j, i)) + fila = j + End If + Next j + If i <> fila Then + For j = 0 To n + Swap im(i, j), im(fila, j) + Next j + End If + Next i +End Sub + +Sub LUdecomposition(a() As Double,l() As Double, u() As Double, p() As Double) + Dim As Integer i, j, k, n + Dim As Double s + n = Ubound(a) + Redim l(n, n), u(n, n), p(n, n) + Dim As Double b(n, n) + pivotize(a(), p()) + + For i = 0 To n + For j = 0 To n + b(i, j) = 0 + For k = 0 To n + b(i, j) += p(i, k) * a(k, j) + Next k + Next j + Next i + + For j = 0 To n + l(j, j) = 1 + For i = 0 To j + s = 0 + For k = 0 To i - 1 + s += u(k, j) * l(i, k) + Next k + u(i, j) = b(i, j) - s + Next i + For i = j + 1 To n + s = 0 + For k = 0 To j - 1 + s += u(k, j) * l(i, k) + Next k + l(i, j) = (b(i, j) - s) / u(j, j) + Next i + Next j +End Sub + +Sub showMatrix(a() As Double) + Dim As Integer i, j + Dim As String As1 + For i = 0 To Ubound(a, 1) + For j = 0 To Ubound(a, 2) + Print Using "###.##### "; a(i, j); + Next j + Print + Next i + Print +End Sub + +Dim As Double A1(2, 2) => {{1, 3, 5}, {2, 4, 7}, {1, 1, 0}} +Dim As Double L1(), U1(), P1() +LUdecomposition(A1(), L1(), U1(), P1()) +Print "L1:" +showMatrix(L1()) +Print "U1:" +showMatrix(U1()) +Print "P1:" +showMatrix(P1()) + +Dim As Double A2(3, 3) => {{11, 9, 24, 2}, {1, 5, 2, 6}, {3, 17, 18, 1}, {2, 5, 7, 1}} +Dim As Double L2(), U2(), P2() +LUdecomposition(A2(), L2(), U2(), P2()) +Print "L2:" +showMatrix(L2()) +Print "U2:" +showMatrix(U2()) +Print "P2:" +showMatrix(P2()) + +Sleep diff --git a/Task/Last-Friday-of-each-month/ALGOL-68/last-friday-of-each-month.alg b/Task/Last-Friday-of-each-month/ALGOL-68/last-friday-of-each-month.alg index e83dd0c9aa..435d911993 100644 --- a/Task/Last-Friday-of-each-month/ALGOL-68/last-friday-of-each-month.alg +++ b/Task/Last-Friday-of-each-month/ALGOL-68/last-friday-of-each-month.alg @@ -35,17 +35,18 @@ BEGIN # find the last Friday in each month of a year # OD; last END # last fridays # ; - # test the last fridays procedure # - INT year = 2021; - []INT last = last fridays( year ); - FOR m pos TO 12 DO - print( ( whole( year, 0 ) - , IF m pos < 10 THEN "-0" ELSE "-1" FI - , whole( m pos MOD 10, 0 ) - , "-" - , whole( last[ m pos ], 0 ) - , newline - ) - ) - OD + BEGIN # test the last fridays procedure # + INT year = 2021; + []INT last = last fridays( year ); + FOR m pos TO 12 DO + print( ( whole( year, 0 ) + , IF m pos < 10 THEN "-0" ELSE "-1" FI + , whole( m pos MOD 10, 0 ) + , "-" + , whole( last[ m pos ], 0 ) + , newline + ) + ) + OD + END END diff --git a/Task/Last-Friday-of-each-month/FutureBasic/last-friday-of-each-month.basic b/Task/Last-Friday-of-each-month/FutureBasic/last-friday-of-each-month.basic new file mode 100644 index 0000000000..05c38e7385 --- /dev/null +++ b/Task/Last-Friday-of-each-month/FutureBasic/last-friday-of-each-month.basic @@ -0,0 +1,41 @@ +include "NSLog.incl" + +void local fn LastFridayOfEachMonthInYear( year as NSInteger ) + CFCalendarRef calendar = fn CalendarCurrent + + for NSInteger month = 1 to 12 + DateComponentsRef components = fn DateComponentsInit + DateComponentsSetMonth( components, month ) + DateComponentsSetYear( components, year ) + DateComponentsSetDay( components, 1 ) + + CFDateRef firstDayOfMonth = fn CalendarDateFromComponents( calendar, components ) + CFRange dayRange = fn CalendarRangeOfUnitInUnit( calendar, NSCalendarUnitDay, NSCalendarUnitMonth, firstDayOfMonth ) + NSInteger numberOfDaysInMonth = dayRange.length + + DateComponentsRef lastDayComponents = fn DateComponentsInit + DateComponentsSetMonth( lastDayComponents, month ) + DateComponentsSetYear( lastDayComponents, year ) + DateComponentsSetDay( lastDayComponents, numberOfDaysInMonth ) + + CFDateRef lastDayOfMonth = fn CalendarDateFromComponents( calendar, lastDayComponents ) + DateComponentsRef lastFridayComponents = fn CalendarComponentsFromDate( calendar, NSCalendarUnitYear + NSCalendarUnitMonth + NSCalendarUnitDay, lastDayOfMonth ) + while ( fn DateComponentsDay( lastFridayComponents ) > 0 ) + DateComponentsSetDay( lastFridayComponents, fn DateComponentsDay( lastFridayComponents ) -1 ) + CFDateRef lastPotentialFriday = fn CalendarDateFromComponents( calendar, lastFridayComponents ) + DateComponentsRef weekdayComponents = fn CalendarComponentsFromDate( calendar, NSCalendarUnitWeekday, lastPotentialFriday ) + if ( fn DateComponentsWeekday( weekdayComponents ) == 6 ) + DateFormatterRef formatter = fn DateFormatterInit + DateFormatterSetDateStyle( formatter, NSDateFormatterMediumStyle ) + NSLog( @"Last Friday: %@", fn DateFormatterStringFromDate( formatter, lastPotentialFriday ) ) + break + end if + wend + next + NSLog( @"\n" ) +end fn + +fn LastFridayOfEachMonthInYear( 2012 ) +fn LastFridayOfEachMonthInYear( 2025 ) + +HandleEvents 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 index fefc73a49c..6ab9e78f67 100644 --- 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 @@ -1,24 +1,23 @@ -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 + {: +module Lastfriday (year as integer=0) { + REM LOCALE 1032 ' Greek + LOCALE 1033 ' US - English + DEF firstdayYear(y)=cdate(0, y-1900,0,2) + DEF lastdayYear(y)=cdate(0, y-1900,12,1) + IF year=0 THEN INPUT "Year (e.g. 2024 or 24):", year + year=ABS(year) + IF year<100 THEN year+=2000 + DATE a=firstdayYear(year), friday=6 'firstdayYear(1900)+4 + DATE a1=lastdayYear(year) + DATE i=a+7-(a-friday) mod 7 + 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") + { + FOR i=i+7 TO a1 STEP 7 + IF VAL(DATE$(i, LOCALE, "M")) <>VAL(DATE$(i+7, LOCALE, "M")) THEN + result$=FORMAT$("{0:12} {1:-14}",DATE$(i, LOCALE, "MMMM"),DATE$(i, LOCALE, "d")) + { } - end if - next - report result$ - clipboard result$ + END IF + NEXT + PRINT #-2, result$ + CLIPBOARD result$ } -lastfriday +Lastfriday 2025 diff --git a/Task/Last-Friday-of-each-month/V-(Vlang)/last-friday-of-each-month.v b/Task/Last-Friday-of-each-month/V-(Vlang)/last-friday-of-each-month.v index b7a9a81554..98f77abecf 100644 --- a/Task/Last-Friday-of-each-month/V-(Vlang)/last-friday-of-each-month.v +++ b/Task/Last-Friday-of-each-month/V-(Vlang)/last-friday-of-each-month.v @@ -2,23 +2,23 @@ import time import os fn main() { - mut year := 0 - mut t := time.now() - year = os.input("Please select a year: ").int() - println("Last Fridays of each month of $year") + mut year := "" + mut now, mut mdx := time.now(), time.month_days[0] + for year.len != 4 || !year.split("").any(it.is_int()) { + year = os.input("What year to calculate (yyyy): ") + } + println("Last Friday for each month of $year") println("==================================") - for i in 1..13 { - mut j := time.month_days[i-1] - if i == 2 { - if time.is_leap_year(year) {j = 29} - } + for idx in 1..13 { + mdx = time.month_days[idx - 1] + if idx == 2 && time.is_leap_year(year.int()) {mdx = 29} for { - t = time.parse('$year-${i:02}-$j 12:30:00')! - if t.weekday_str() == 'Fri' { - println("${time.long_months[i-1]}: $j") + now = time.parse("$year-${idx:02}-${mdx} 12:30:00")! + if now.weekday_str() == "Fri" { + println("${time.long_months[idx - 1]}: ${mdx}") break } - j-- + mdx-- } } } diff --git a/Task/Least-common-multiple/FutureBasic/least-common-multiple.basic b/Task/Least-common-multiple/FutureBasic/least-common-multiple.basic new file mode 100644 index 0000000000..48cf54d10b --- /dev/null +++ b/Task/Least-common-multiple/FutureBasic/least-common-multiple.basic @@ -0,0 +1,9 @@ +int local fn gcd_rec( a as int, b as int ) + if ( b == 0 ) then return a +end fn = fn gcd_rec(b, a % b) + +int def fn lcm( a as int, b as int ) = abs(a * b) / fn gcd_rec(a, b) + +print fn lcm(12,18) + +HandleEvents diff --git a/Task/Left-factorials/Jq/left-factorials-1.jq b/Task/Left-factorials/Jq/left-factorials-1.jq index dfa8c03390..309bb9648b 100644 --- a/Task/Left-factorials/Jq/left-factorials-1.jq +++ b/Task/Left-factorials/Jq/left-factorials-1.jq @@ -3,3 +3,18 @@ def left_factorial: # state: [i!, !i] ([1,0]; .[1] += .[0] | .[0] *= $i) | .[1]; + +# input and gap should be integers +def left_factorial_lengths(gap): + reduce range(1; .+1) as $i + # state: [i!, !i, gap] + ([1, 0, []]; + .[1] = (.[0] + .[1]) + | .[0] = (.[0] * $i) + | (.[1] | tostring | length) as $lf + | if $i % gap == 0 then .[2] += [[$i, $lf]] else . end) + | .[2]; + +((range(0;11), (range(2; 12) * 10)) | "\(.): \(left_factorial)"), + +(10000 | left_factorial_lengths(1000) | .[] | "\(.[0]): length is \(.[1])") diff --git a/Task/Left-factorials/XPL0/left-factorials.xpl0 b/Task/Left-factorials/XPL0/left-factorials.xpl0 new file mode 100644 index 0000000000..5780a1ae7c --- /dev/null +++ b/Task/Left-factorials/XPL0/left-factorials.xpl0 @@ -0,0 +1,45 @@ +include xpllib; \for Big ops +def Size = 36000; + +func BigSize(Num); \Return number of digits in a big number +char Num; +int I; +[for I:= 0 to Size-1 do + if Num(I) # ^0 then return Size-I; +return Size; +]; + +char LFact(Size+1), Sum(Size+1), BigI(Size+1); +int I; +[Int2Big(1, LFact, Size); \LFact:= 1 +Int2Big(0, Sum, Size); \Sum:= 0 +BigOut(0, Sum); CrLf(0); +for I:= 1 to 10 do + [BigAdd(Sum, LFact); \Sum:= Sum + LFact + BigOut(0, Sum); CrLf(0); + Int2Big(I, BigI, Size); + BigMul(LFact, BigI); \LFact:= LFact*I + ]; +CrLf(0); +Int2Big(1, LFact, Size); \LFact:= 1 +Int2Big(0, Sum, Size); \Sum:= 0 +for I:= 1 to 110 do + [BigAdd(Sum, LFact); \Sum:= Sum + LFact + if I >= 20 and rem(I/10) = 0 then + [ChOut(0, ^!); IntOut(0, I); Text(0, " = "); + BigOut(0, Sum); CrLf(0)]; + Int2Big(I, BigI, Size); + BigMul(LFact, BigI); \LFact:= LFact*I + ]; +CrLf(0); +Int2Big(1, LFact, Size); \LFact:= 1 +Int2Big(0, Sum, Size); \Sum:= 0 +for I:= 1 to 10_000 do + [BigAdd(Sum, LFact); \Sum:= Sum + LFact + if I >= 1000 and rem(I/1000) = 0 then + [ChOut(0, ^!); IntOut(0, I); Text(0, " -> "); + IntOut(0, BigSize(Sum)); CrLf(0)]; + Int2Big(I, BigI, Size); + BigMul(LFact, BigI); \LFact:= LFact*I + ]; +] diff --git a/Task/Letter-frequency/V-(Vlang)/letter-frequency.v b/Task/Letter-frequency/V-(Vlang)/letter-frequency.v index 9f98c0c4bf..fcc785524e 100644 --- a/Task/Letter-frequency/V-(Vlang)/letter-frequency.v +++ b/Task/Letter-frequency/V-(Vlang)/letter-frequency.v @@ -1,11 +1,12 @@ import os + struct LetterFreq { rune int freq int } fn main(){ - file := os.read_file('unixdict.txt')? + file := os.read_file('unixdict.txt')! mut freq := map[rune]int{} for c in file { freq[c]++ @@ -24,6 +25,6 @@ fn main(){ return 0 }) for f in lf { - println('${u8(f.rune).ascii_str()} ${f.rune} $f.freq') + println('${u8(f.rune).ascii_str()} ${f.rune} ${f.freq}') } } diff --git a/Task/Literals-Integer/M2000-Interpreter/literals-integer.m2000 b/Task/Literals-Integer/M2000-Interpreter/literals-integer.m2000 index f73c7b9f5b..01d7a091ac 100644 --- a/Task/Literals-Integer/M2000-Interpreter/literals-integer.m2000 +++ b/Task/Literals-Integer/M2000-Interpreter/literals-integer.m2000 @@ -1,7 +1,14 @@ Def ExpType$(x)=Type$(x) Print ExpType$(12345678912345#)="Currency", 12345678912345# Print ExpType$(123456789123456789123456@)="Decimal", 123456789123456789123456@ -Print ExpType$(12&)="Long", 12&, 0xFFFFFFFF&=-1 +Print ExpType$(12&)="Long", 12&, 0xFFFF_FFFF&=-1 Print ExpType$(12%)="Integer", 12%, 0xFFFF%=-1 -\\ used for unsigned integers (but it is double) -Print ExpType$(0xFFFFFFFF)="Double", 0xFFFFFFFF=4294967295 +Print ExpType$(12&&)="Long Long", 12&&, 0xFFFFFFFF_FFFFFFFF&&=-1 + +\\ used for unsigned 32 bit integers (but it is Currency) +Print ExpType$(0xFFFF)="Currency", 0xFFFF=65535 +Print ExpType$(0xFFFFFFFF)="Currency", 0xFFFFFFFF=4294967295 +\\ used for unsigned 64 bit integers (but it is Decimal) +Print ExpType$(0xFFFFFFFF_FFFFFFFF)="Decimal", 0xFFFFFFFF_FFFFFFFF=18446744073709551615@ +Print ExpType$(12ub)="Byte", ExpType$(255ub)="Byte" +Print ExpType$(42000ud)="Date", "27/12/2014"=""+42000ud, date$(42000ud+1)="28/12/2014" diff --git a/Task/Long-literals-with-continuations/FutureBasic/long-literals-with-continuations.basic b/Task/Long-literals-with-continuations/FutureBasic/long-literals-with-continuations.basic new file mode 100644 index 0000000000..5a73de2a15 --- /dev/null +++ b/Task/Long-literals-with-continuations/FutureBasic/long-literals-with-continuations.basic @@ -0,0 +1,31 @@ +void local fn DoIt + CFStringRef elements = @"hydrogen helium lithium beryllium boron carbon nitrogen ¬ + oxygen fluorine neon sodium magnesium aluminum silicon ¬ + phosphorous sulfur chlorine argon potassium calcium ¬ + scandium titanium vanadium chromium manganese iron cobalt ¬ + nickel copper zinc gallium germanium arsenic selenium ¬ + bromine krypton rubidium strontium yttrium zirconium ¬ + niobium molybdenum technetium ruthenium rhodium palladium ¬ + silver cadmium indium tin antimony tellurium iodine ¬ + xenon cesium barium lanthanum cerium praseodymium ¬ + neodymium promethium samarium europium gadolinium terbium ¬ + dysprosium holmium erbium thulium ytterbium lutetium ¬ + hafnium tantalum tungsten rhenium osmium iridium platinum ¬ + gold mercury thallium lead bismuth polonium astatine ¬ + radon francium radium actinium thorium protactinium ¬ + uranium neptunium plutonium americium curium berkelium ¬ + californium einsteinium fermium mendelevium nobelium ¬ + lawrencium rutherfordium dubnium seaborgium bohrium hassium ¬ + meitnerium darmstadtium roentgenium copernicium nihonium ¬ + flerovium moscovium livermorium tennessine oganesson" + + CFArrayRef array = fn StringComponentsSeparatedByString( elements, @" " ) + + print @"Last revision: 20230217" + print @"Elements: ";len(array) + print @"Last element: ";array[len(array)-1] +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Long-primes/ALGOL-68/long-primes.alg b/Task/Long-primes/ALGOL-68/long-primes.alg index 5a56ad4552..8d6d540b9d 100644 --- a/Task/Long-primes/ALGOL-68/long-primes.alg +++ b/Task/Long-primes/ALGOL-68/long-primes.alg @@ -13,7 +13,7 @@ BEGIN # find some long primes - primes whose reciprocol have a period of p-1 # OP PERIOD = ( INT n )INT: # returns the period of the reciprocal of n # BEGIN INT r := 1; - FOR i TO n + 1 DO + TO n + 1 DO r *:= 10 MODAB n OD; INT rr = r; diff --git a/Task/Long-primes/XPL0/long-primes.xpl0 b/Task/Long-primes/XPL0/long-primes.xpl0 new file mode 100644 index 0000000000..dc5820cb46 --- /dev/null +++ b/Task/Long-primes/XPL0/long-primes.xpl0 @@ -0,0 +1,64 @@ +include xpllib; \for Print + +func Sieve(Limit, Primes); \Return Primes array and its size +int Limit, Primes; +char C; +int I, P, P2, N; +[C:= Reserve(Limit+1); +for I:= 0 to Limit do C(I):= false; +P:= 3; \no need to process even numbers +P2:= P*P; +while P2 <= Limit do + [I:= P2; + while I <= Limit do + [C(I):= true; I:= I + 2*P]; + repeat P:= P+2 until C(P) = false; + P2:= P*P; + ]; +N:= 0; +for I:= 3 to Limit do + [if C(I) = false then [Primes(N):= I; N:= N+1]; + I:= I+1; + ]; +return N; +]; + +func FindPeriod(N); \Return the period of the reciprocal of N +int N; +int I, R, RR, Period; +[R:= 1; +for I:= 1 to N+1 do + R:= rem((10*R) / N); +RR:= R; +Period:= 0; +repeat R:= rem((10*R) / N); + Period:= Period+1; +until R = RR; +return Period; +]; + +int I, Prime, Count, Index, PrimeCount, LongCount; +int Primes(6500), LongPrimes, Totals(8), Numbers; +[Numbers:= [500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]; +PrimeCount:= Sieve(64000, Primes); +LongPrimes:= Reserve(PrimeCount*IntSize); +LongCount:= 0; +for I:= 0 to PrimeCount-1 do \surely LongCount < PrimeCount + [Prime:= Primes(I); + if FindPeriod(Prime) = Prime-1 then + [LongPrimes(LongCount):= Prime; LongCount:= LongCount+1]; + ]; +Count:= 0; Index:= 0; +for I:= 0 to LongCount-1 do + [if LongPrimes(I) > Numbers(Index) then + [Totals(Index):= Count; Index:= Index+1]; + Count:= Count+1; + ]; +Totals(8-1):= Count; +Print("The long primes up to %d are:\n", Numbers(0)); +for I:= 0 to Totals(0)-1 do + Print("%d ", LongPrimes(I)); +Print("\n\nThe number of long primes up to:\n"); +for I:= 0 to 8-1 do + Print(" %5d is %d\n", Numbers(I), Totals(I)); +] diff --git a/Task/Long-year/FutureBasic/long-year.basic b/Task/Long-year/FutureBasic/long-year.basic new file mode 100644 index 0000000000..d0baa0bff8 --- /dev/null +++ b/Task/Long-year/FutureBasic/long-year.basic @@ -0,0 +1,11 @@ +BOOL local fn IsLongYear( year as int ) + int year1 = year - 1 + int p = (year + (year / 4) - (year / 100) + (year / 400)) % 7 + int p1 = (year1 + (year1 / 4) - (year1 / 100) + (year1 / 400)) % 7 +end fn = p == 4 || p1 == 3 + +for int y = 2000 to 2100 + if ( fn IsLongYear( y ) ) then print y +next + +HandleEvents diff --git a/Task/Longest-common-substring/V-(Vlang)/longest-common-substring.v b/Task/Longest-common-substring/V-(Vlang)/longest-common-substring.v index b307430ce5..98ff6e1c63 100644 --- a/Task/Longest-common-substring/V-(Vlang)/longest-common-substring.v +++ b/Task/Longest-common-substring/V-(Vlang)/longest-common-substring.v @@ -1,5 +1,4 @@ -fn main() -{ +fn main() { println(lcs("thisisatest", "testing123testing")) } @@ -7,11 +6,11 @@ fn lcs(a string, b string) string { mut lengths := map[int]int{} mut output :='' mut greatest_length := 0 - for i, x in a { for j, y in b { if x == y { - if i == 0 || j == 0 {lengths[i * b.len + j] = 1} else {lengths[i * b.len + j] = lengths[(i-1) * b.len + j-1] + 1} + if i == 0 || j == 0 {lengths[i * b.len + j] = 1} + else {lengths[i * b.len + j] = lengths[(i-1) * b.len + j-1] + 1} if lengths[i * b.len + j] > greatest_length { greatest_length = lengths[i * b.len + j] output += x.ascii_str() diff --git a/Task/Loops-Continue/OxygenBasic/loops-continue.basic b/Task/Loops-Continue/OxygenBasic/loops-continue.basic new file mode 100644 index 0000000000..6c921191fc --- /dev/null +++ b/Task/Loops-Continue/OxygenBasic/loops-continue.basic @@ -0,0 +1,15 @@ +uses console + +int i + +for i = 1 to 10 + print str(i); + if i mod 5 = 0 then + printl + continue for + end if + print ", "; +next + +printl cr "Enter ..." +waitkey diff --git a/Task/Loops-Continue/QBasic/loops-continue.basic b/Task/Loops-Continue/QBasic/loops-continue.basic new file mode 100644 index 0000000000..6746bd9eee --- /dev/null +++ b/Task/Loops-Continue/QBasic/loops-continue.basic @@ -0,0 +1,6 @@ +FOR i = 1 TO 10 + PRINT STR$(i); + IF (i MOD 5) THEN PRINT ", "; ELSE PRINT +NEXT i +PRINT +END diff --git a/Task/Loops-For/FutureBasic/loops-for.basic b/Task/Loops-For/FutureBasic/loops-for-1.basic similarity index 100% rename from Task/Loops-For/FutureBasic/loops-for.basic rename to Task/Loops-For/FutureBasic/loops-for-1.basic diff --git a/Task/Loops-For/FutureBasic/loops-for-2.basic b/Task/Loops-For/FutureBasic/loops-for-2.basic new file mode 100644 index 0000000000..c4508d9315 --- /dev/null +++ b/Task/Loops-For/FutureBasic/loops-for-2.basic @@ -0,0 +1,10 @@ +window 1 + +for long i = 1 to 5 + for long j = 1 to i + print @"*"; + next + print +next + +HandleEvents diff --git a/Task/Loops-Foreach/Plain-English/loops-foreach.plain b/Task/Loops-Foreach/Plain-English/loops-foreach.plain index 2c79ec293e..6e6c6fa78b 100644 --- a/Task/Loops-Foreach/Plain-English/loops-foreach.plain +++ b/Task/Loops-Foreach/Plain-English/loops-foreach.plain @@ -1,36 +1,36 @@ To run: -Start up. -Create a list. -Write each entry in the list to the console. -Destroy the list. -Wait for the escape key. -Shut down. + Start up. + Create a list. + Write each entry in the list to the console. + Destroy the list. + Wait for the escape key. + Shut down. An entry is a thing with a number. A list is some entries. To add a number to a list: -Allocate memory for an entry. -Put the number into the entry's number. -Append the entry to the list. + Allocate memory for an entry. + Put the number into the entry's number. + Append the entry to the list. To create a list: -Add 1 to the list. -Add 2 to the list. -Add 3 to the list. -Add 6 to the list. -Add 7 to the list. -Add 9 to the list. + Add 1 to the list. + Add 2 to the list. + Add 3 to the list. + Add 6 to the list. + Add 7 to the list. + Add 9 to the list. To write an entry to the console: -Convert the entry's number to a string. -Write the string to the console. + Convert the entry's number to a string. + Write the string to the console. To write each entry in a list to the console: -Get an entry from the list. -Loop. -If the entry is nil, exit. -Write the entry to the console. -Put the entry's next into the entry. -Repeat. + Get an entry from the list. + Loop. + If the entry is nil, exit. + Write the entry to the console. + Put the entry's next into the entry. + Repeat. diff --git a/Task/Loops-Increment-loop-index-within-loop-body/FutureBasic/loops-increment-loop-index-within-loop-body.basic b/Task/Loops-Increment-loop-index-within-loop-body/FutureBasic/loops-increment-loop-index-within-loop-body.basic new file mode 100644 index 0000000000..83e485b31a --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/FutureBasic/loops-increment-loop-index-within-loop-body.basic @@ -0,0 +1,23 @@ +BOOL local fn IsPrime( n as long ) + if ( n == 2 ) then return YES + if ( n < 2 || n % 2 == 0 ) then return NO + for long i = 3 to sqr(n) step 2 + if ( ( n % i ) == 0 ) then return NO + next i +end fn = YES + +void local fn DoIt + long count = 0 + for long i = 42 to LONG_MAX + if ( fn IsPrime( i ) ) + count++ + print count,i + if ( count == 42 ) then break + i += i + end if + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Loops-Wrong-ranges/ALGOL-68/loops-wrong-ranges.alg b/Task/Loops-Wrong-ranges/ALGOL-68/loops-wrong-ranges.alg index bd6c637e96..6ec86ff09d 100644 --- a/Task/Loops-Wrong-ranges/ALGOL-68/loops-wrong-ranges.alg +++ b/Task/Loops-Wrong-ranges/ALGOL-68/loops-wrong-ranges.alg @@ -1,20 +1,20 @@ BEGIN - # returns the first n elements of the sequences of values specified by start, stop and increment # - PROC sequence = ( INT n, start, stop, increment )[]INT: + # returns the first n elements of the sequences of values specified by s sstart, s stop and increment # + PROC sequence = ( INT n, s start, s stop, increment )[]INT: BEGIN [ 1 : n ]INT s; FOR j FROM LWB s TO UPB s DO s[ j ] := 0 OD; INT s pos := LWB s - 1; - FOR j FROM start BY increment TO stop WHILE s pos < n DO + FOR j FROM s start BY increment TO s stop WHILE s pos < n DO s[ s pos +:= 1 ] := j OD; s[ LWB s : s pos ] END # sequence # ; # tests the sequence procedure # - PROC test sequence = ( INT start, stop, increment, STRING legend )VOID: + PROC test sequence = ( INT s start, s stop, increment, STRING legend )VOID: BEGIN - []INT s = sequence( 10, start, stop, increment ); + []INT s = sequence( 10, s start, s stop, increment ); print( ( legend, ": " ) ); FOR i FROM LWB s TO UPB s DO print( ( " ", whole( s[ i ], -4 ) ) ) OD; print( ( newline ) ) diff --git a/Task/M-bius-function/REXX/m-bius-function-2.rexx b/Task/M-bius-function/REXX/m-bius-function-2.rexx index 90b38b4233..65f32f2d38 100644 --- a/Task/M-bius-function/REXX/m-bius-function-2.rexx +++ b/Task/M-bius-function/REXX/m-bius-function-2.rexx @@ -37,4 +37,5 @@ else include Functions include Numbers +include Sequences include Abend diff --git a/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v b/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v index b0e0dc190d..55037b2dbc 100644 --- a/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v +++ b/Task/MAC-vendor-lookup/V-(Vlang)/mac-vendor-lookup.v @@ -1,16 +1,16 @@ import net.http import time -const macs = -(' +const macs = (" FC-A1-3E FC:FB:FB:01:FA:21 +xx:12:5 D4:F4:6F:C9:EF:8D -') +") fn main() { - for line in macs.split('\n') { - if line !='' { + for line in macs.split_into_lines() { + if !line.is_blank() { println(mac_lookup(line)) time.sleep(2 * time.second) // considerate delay between attempts } @@ -18,6 +18,6 @@ fn main() { } fn mac_lookup(mac string) string { - resp := http.get("http://api.macvendors.com/" + mac) or {return 'No data from server'} + resp := http.get("http://api.macvendors.com/" + mac) or {return "No data from server"} return resp.body.str() } diff --git a/Task/Magnanimous-numbers/ALGOL-68/magnanimous-numbers.alg b/Task/Magnanimous-numbers/ALGOL-68/magnanimous-numbers.alg index d68e75ba4f..273507c2eb 100644 --- a/Task/Magnanimous-numbers/ALGOL-68/magnanimous-numbers.alg +++ b/Task/Magnanimous-numbers/ALGOL-68/magnanimous-numbers.alg @@ -1,5 +1,6 @@ BEGIN # find some magnanimous numbers - numbers where inserting a + between any # - # digits ab=nd evaluatinf the sum results in a prime in all cases # + # digits ab=nd evaluating the sum results in a prime in all cases # + PR read "primes.incl.a68" PR # include prime utilities # # returns the first n magnanimous numbers # # uses global sieve prime which must include 0 and be large enough # # for all possible sub-sequences of digits # @@ -8,21 +9,23 @@ BEGIN # find some magnanimous numbers - numbers where inserting a + between any [ 1 : n ]INT result; INT m count := 0; FOR i FROM 0 WHILE m count < n DO - # split the number into pairs of digit seuences and check the sums of the pairs are all prime # - INT divisor := 1; + # split the number into pairs of digit sequences # + # and check the sums of the pairs are all prime # + INT divisor := 10; BOOL all prime := TRUE; - WHILE divisor *:= 10; - IF INT front = i OVER divisor; + WHILE IF INT front = i OVER divisor; front = 0 THEN FALSE ELSE all prime := prime[ front + ( i MOD divisor ) ] FI - DO SKIP OD; + DO + divisor *:= 10 + OD; IF all prime THEN result[ m count +:= 1 ] := i FI OD; result END; # MAGNANIMPUS # - # prints part of a seuence of magnanimous numbers # + # prints part of a sequence of magnanimous numbers # PROC print magnanimous = ( []INT m, INT first, INT last, STRING legend )VOID: BEGIN print( ( legend, ":", newline ) ); @@ -31,16 +34,10 @@ BEGIN # find some magnanimous numbers - numbers where inserting a + between any END ; # print magnanimous # # we assume the first 400 magnanimous numbers will be in 0 .. 1 000 000 # # so we will need a sieve of 0 up to 99 999 + 9 # - [ 0 : 99 999 + 9 ]BOOL prime; - prime[ 0 ] := prime[ 1 ] := FALSE; prime[ 2 ] := TRUE; - FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE OD; - FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD; - FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO - IF prime[ i ] THEN FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD FI - OD; + []BOOL prime = PRIMESIEVE ( 99 999 + 9 ); # construct the sequence of magnanimous numbers # - []INT m = MAGNANIMOUS 400; - print magnanimous( m, 1, 45, "First 45 magnanimous numbers" ); - print magnanimous( m, 241, 250, "Magnanimous numbers 241-250" ); - print magnanimous( m, 391, 400, "Magnanimous numbers 391-400" ) + []INT mns = MAGNANIMOUS 400; + print magnanimous( mns, 1, 45, "First 45 magnanimous numbers" ); + print magnanimous( mns, 241, 250, "Magnanimous numbers 241-250" ); + print magnanimous( mns, 391, 400, "Magnanimous numbers 391-400" ) END diff --git a/Task/Mayan-calendar/FreeBASIC/mayan-calendar.basic b/Task/Mayan-calendar/FreeBASIC/mayan-calendar.basic new file mode 100644 index 0000000000..b3cac2800c --- /dev/null +++ b/Task/Mayan-calendar/FreeBASIC/mayan-calendar.basic @@ -0,0 +1,99 @@ +#include "datetime.bi" + +Type DateResult + As String long_date + As String round_date +End Type + +Function IntToStr(num As Integer, ancho As Integer = 2) As String + Return Right("00" & Str(num), ancho) +End Function + +Function JulianDate(y As Integer, m As Integer, d As Integer) As Long + Dim As Long a = (14 - m) \ 12 + y += 4800 - a + m += 12 * a - 3 + Return d + ((153 * m + 2) \ 5) + 365 * y + (y \ 4) - (y \ 100) + (y \ 400) - 32045 +End Function + +Function g2m(dateStr As String, gtm_correlation As Boolean = True) As DateResult + Dim As DateResult result + + ' Constants and arrays + Dim As Long correlation = Iif(gtm_correlation, 584283, 584285) + + Dim As Long long_count_days(4) = {144000, 7200, 360, 20, 1} + + Dim As String tzolkin_months(19) = { _ + "Imix'", "Ik'", "Ak'bal", "K'an", "Chikchan", "Kimi", "Manik'", "Lamat", _ + "Muluk", "Ok", "Chuwen", "Eb", "Ben", "Hix", "Men", "K'ib'", "Kaban", _ + "Etz'nab'", "Kawak", "Ajaw" } + + Dim As String haad_months(18) = { _ + "Pop", "Wo'", "Sip", "Sotz'", "Sek", "Xul", "Yaxk'in", "Mol", "Ch'en", _ + "Yax", "Sak'", "Keh", "Mak", "K'ank'in", "Muwan", "Pax", "K'ayab", _ + "Kumk'u", "Wayeb'" } + + ' Parse date string (YYYY-MM-DD) + Dim As Integer y = Valint(Mid(dateStr, 1, 4)) + Dim As Integer m = Valint(Mid(dateStr, 6, 2)) + Dim As Integer d = Valint(Mid(dateStr, 9, 2)) + + ' Calculate Julian days + Dim As Long julian_days = JulianDate(y, m, d) + + ' Calculate long count date + Dim As Long remainder = julian_days - correlation + Dim As Integer long_parts(4) + + For i As Integer = 0 To 4 + long_parts(i) = remainder \ long_count_days(i) + remainder Mod= long_count_days(i) + Next + + ' Format long date + result.long_date = "" + For i As Integer = 0 To 4 + If i > 0 Then result.long_date &= "." + result.long_date &= IntToStr(long_parts(i)) + Next + + ' Calculate round calendar date + Dim As Integer tzolkin_month = (julian_days + 16) Mod 20 + Dim As Integer tzolkin_day = ((julian_days + 5) Mod 13) + 1 + + Dim As Integer haab_month = ((julian_days + 65) Mod 365) \ 20 + Dim As String haab_day + Dim As Integer haab_day_num = ((julian_days + 65) Mod 365) Mod 20 + haab_day = Iif(haab_day_num = 0, "Chum", Str(haab_day_num)) + + Dim As Integer lord_number = (julian_days - correlation) Mod 9 + If lord_number = 0 Then lord_number = 9 + + ' Format round date + result.round_date = Trim(Str(tzolkin_day)) & " " & _ + Left(tzolkin_months(tzolkin_month) & Space(10), 10) & _ + Right(Space(4) & Trim(haab_day), 4) & " " & _ + Left(haad_months(haab_month) & Space(8), 8) & _ + Space(7) & "G" & Trim(Str(lord_number)) + + Return result +End Function + +' Main program +Print " Gregorian Long Tzolk'in Haab' Lord of" +Print " Date Count # Name Day Month the Night" +Print "---------- -------------- -------- ------------- ---------" + +Dim As String dates(9) = { _ +"1961-10-06", "1963-11-21", "2004-06-19", "2012-12-18", "2012-12-21", _ +"2019-01-19", "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16" } + +Dim As DateResult result + +For i As Integer = 0 To 9 + result = g2m(dates(i)) + Print dates(i); " "; result.long_date; " "; result.round_date +Next + +Sleep diff --git a/Task/Mayan-calendar/QB64/mayan-calendar.qb64 b/Task/Mayan-calendar/QB64/mayan-calendar.qb64 new file mode 100644 index 0000000000..951a4c96c6 --- /dev/null +++ b/Task/Mayan-calendar/QB64/mayan-calendar.qb64 @@ -0,0 +1,113 @@ +DECLARE FUNCTION IntToStr$ (num AS LONG, ancho AS INTEGER) +DECLARE FUNCTION JulianDate# (y AS LONG, m AS LONG, d AS LONG) +DECLARE FUNCTION g2m$ (dateStr AS STRING) + +Dim dates(6) As String +dates(0) = "2004-06-19": dates(1) = "2012-12-18": dates(2) = "2012-12-21" +dates(3) = "2019-01-19": dates(4) = "2019-03-27": dates(5) = "2020-02-29" +dates(6) = "2020-03-01" + +Dim i As Integer +For i = 0 To 6 + Print dates(i); " "; g2m$(dates(i)) +Next i +'sleep +End + +Function IntToStr$ (num As Long, ancho As Integer) + IntToStr$ = Right$("00" + LTrim$(Str$(num)), ancho) +End Function + +Function JulianDate# (y As Long, m As Long, d As Long) + Dim a As Long + a = (14 - m) \ 12 + y = y + 4800 - a + m = m + 12 * a - 3 + JulianDate# = d + ((153 * m + 2) \ 5) + 365 * y + (y \ 4) - (y \ 100) + (y \ 400) - 32045 +End Function + +Function g2m$ (dateStr As String) + Dim longDate As String + Dim roundDate As String + Dim correlation As Double + correlation = 584283 'GTM correlation + + Dim longCountDays(4) As Double + longCountDays(0) = 144000: longCountDays(1) = 7200 + longCountDays(2) = 360: longCountDays(3) = 20: longCountDays(4) = 1 + + Dim tzolkinMonths(19) As String + tzolkinMonths(0) = "Imix'": tzolkinMonths(1) = "Ik'" + tzolkinMonths(2) = "Ak'bal": tzolkinMonths(3) = "K'an" + tzolkinMonths(4) = "Chikchan": tzolkinMonths(5) = "Kimi" + tzolkinMonths(6) = "Manik'": tzolkinMonths(7) = "Lamat" + tzolkinMonths(8) = "Muluk": tzolkinMonths(9) = "Ok" + tzolkinMonths(10) = "Chuwen": tzolkinMonths(11) = "Eb" + tzolkinMonths(12) = "Ben": tzolkinMonths(13) = "Hix" + tzolkinMonths(14) = "Men": tzolkinMonths(15) = "K'ib'" + tzolkinMonths(16) = "Kaban": tzolkinMonths(17) = "Etz'nab'" + tzolkinMonths(18) = "Kawak": tzolkinMonths(19) = "Ajaw" + + Dim haadMonths(18) As String + haadMonths(0) = "Pop": haadMonths(1) = "Wo'" + haadMonths(2) = "Sip": haadMonths(3) = "Sotz'" + haadMonths(4) = "Sek": haadMonths(5) = "Xul" + haadMonths(6) = "Yaxk'in": haadMonths(7) = "Mol" + haadMonths(8) = "Ch'en": haadMonths(9) = "Yax" + haadMonths(10) = "Sak'": haadMonths(11) = "Keh" + haadMonths(12) = "Mak": haadMonths(13) = "K'ank'in" + haadMonths(14) = "Muwan": haadMonths(15) = "Pax" + haadMonths(16) = "K'ayab": haadMonths(17) = "Kumk'u" + haadMonths(18) = "Wayeb'" + + Dim y As Long, m As Long, d As Long + y = Val(Mid$(dateStr, 1, 4)) + m = Val(Mid$(dateStr, 6, 2)) + d = Val(Mid$(dateStr, 9, 2)) + + Dim julianDays As Double + julianDays = JulianDate#(y, m, d) + + Dim remainder As Double + remainder = julianDays - correlation + Dim longParts(4) As Long + + For i = 0 To 4 + longParts(i) = Int(remainder / longCountDays(i)) + remainder = remainder - (longParts(i) * longCountDays(i)) + Next i + + longDate = "" + For i = 0 To 4 + If i > 0 Then longDate = longDate + "." + longDate = longDate + IntToStr$(longParts(i), 2) + Next i + + Dim tzolkinMonth As Long, tzolkinDay As Long + Dim haabMonth As Long, haabDayNum As Long + Dim lordNumber As Long + + tzolkinMonth = Int((julianDays + 16) Mod 20) + tzolkinDay = Int(((julianDays + 5) Mod 13)) + 1 + + haabMonth = Int(((julianDays + 65) Mod 365) / 20) + haabDayNum = Int(((julianDays + 65) Mod 365) Mod 20) + + Dim haabDay As String + If haabDayNum = 0 Then + haabDay = "Chum" + Else + haabDay = LTrim$(Str$(haabDayNum)) + End If + + lordNumber = Int((julianDays - correlation) Mod 9) + If lordNumber = 0 Then lordNumber = 9 + + roundDate = LTRIM$(STR$(tzolkinDay)) + " " + _ + tzolkinMonths(tzolkinMonth) + " " + _ + haabDay + " " + _ + haadMonths(haabMonth) + " G" + _ + LTRIM$(STR$(lordNumber)) + + g2m$ = longDate + " " + roundDate +End Function diff --git a/Task/Mayan-numerals/ALGOL-68/mayan-numerals.alg b/Task/Mayan-numerals/ALGOL-68/mayan-numerals.alg new file mode 100644 index 0000000000..3c803d5187 --- /dev/null +++ b/Task/Mayan-numerals/ALGOL-68/mayan-numerals.alg @@ -0,0 +1,68 @@ +BEGIN + # print Mayan numerals # + # Mayan numerals are base-20 positional numbers, each digit consists of # + # four four character lines in a box # + + # converts n to a mayan representation # + OP TOMAYAN = ( INT n )[]STRING: + BEGIN + # cartouche boarders, etc. # + CHAR top left = REPR 201; CHAR top middle = REPR 203; CHAR top right = REPR 187; + CHAR bottom left = REPR 200; CHAR bottom middle = REPR 202; CHAR bottom right = REPR 188; + CHAR vertical = REPR 186; CHAR horizontal = REPR 205; CHAR turtle = "@"; + STRING horizontal edge = horizontal + horizontal + horizontal + horizontal; + # representations of 1, 2, 3 etc. # + []STRING fragment = ( " . ", " .. ", "... ", "....", "----" ); + STRING blanks = " "; STRING zero = " " + turtle + " "; + # build the cartouche # + INT final line = 6; + [ 1 : final line ]STRING result; + IF n < 0 THEN # negative numbers not supported # + FOR i TO final line DO result[ i ] := "?" OD + ELSE # 0 or negative # + FOR i TO final line DO result[ i ] := "" OD; + top right +=: result[ 1 ]; # right edge of the cartouche # + FOR i FROM 2 TO final line - 1 DO vertical +=: result[ i ] OD; + bottom right +=: result[ final line ]; + INT rest := n; # number body # + WHILE + INT digit := rest MOD 20; rest OVERAB 20; + INT f := digit; + horizontal edge +=: result[ 1 ]; + FOR i FROM final line - 1 BY -1 TO 2 DO + IF f >= 5 THEN + fragment[ 5 ] +=: result[ i ] + ELIF f = 0 THEN + IF i = final line - 1 THEN zero ELSE blanks FI +=: result[ i ] + ELSE + fragment[ digit MOD 5 ] +=: result[ i ] + FI; + IF f > 5 THEN f -:= 5 ELSE f := 0 FI + OD; + horizontal edge +=: result[ final line ]; + rest > 0 + DO + # add a separator # + top middle +=:result[ 1 ]; + FOR i FROM 2 TO UPB result - 1 DO vertical +=: result[ i ] OD; + bottom middle +=: result[ final line ] + OD; + top left +=: result[ 1 ]; # left edge of the cartouche # + FOR i FROM 2 TO final line - 1 DO vertical +=: result[ i ] OD; + bottom left +=: result[ final line ] + FI; + result + END # TOMAYAN # ; + # print n as a mayan number # + PROC print mayan = ( INT n )VOID: + BEGIN + []STRING cartouche = TOMAYAN n; + FOR i TO UPB cartouche DO print( ( cartouche[ i ], newline ) ) OD + END # print mayan # ; + + []INT test cases = ( 4 005, 8 017, 326 205, 886 205, 68, 1303 ); + FOR n FROM LWB test cases TO UPB test cases DO + print( ( "Mayan representation of ", whole( test cases[ n ], 0 ), newline ) ); + print mayan( test cases[ n ] ) + OD +END diff --git a/Task/Mayan-numerals/EasyLang/mayan-numerals.easy b/Task/Mayan-numerals/EasyLang/mayan-numerals.easy new file mode 100644 index 0000000000..55ec0fd97a --- /dev/null +++ b/Task/Mayan-numerals/EasyLang/mayan-numerals.easy @@ -0,0 +1,68 @@ +func[] base20 n . + if n < 20 + return [ n ] + . + r[] = base20 (n div 20) + r[] &= n mod 20 + return r[] +. +mayan$[] = [ " " " ∙ " " ∙∙ " "∙∙∙ " "∙∙∙∙" ] +func$[] mayan d . + r$[] = [ mayan$[1] mayan$[1] mayan$[1] mayan$[1] ] + if d = 0 + r$[4] = " Θ " + return r$[] + . + for i = 4 downto 1 + if d >= 5 + r$[i] = "────" + d -= 5 + else + r$[i] = mayan$[d + 1] + break 1 + . + . + return r$[] +. +proc drawma . mayans$[][] . + idx = len mayans$[][] + write "╔" + for i to idx + for j to 4 + write "═" + . + if i < idx + write "╦" + else + print "╗" + . + . + for i to 4 + write "║" + for j to idx + write mayans$[j][i] & "║" + . + print "" + . + write "╚" + for i to idx + for j to 4 + write "═" + . + if i < idx + write "╩" + else + print "╝" + . + . +. +for n in [ 4005 8017 326205 886205 1081439556 ] + print n + digs[] = base20 n + mayans$[][] = [ ] + for d in digs[] + mayans$[][] &= mayan d + . + drawma mayans$[][] + print "" +. diff --git a/Task/Mayan-numerals/SETL/mayan-numerals.setl b/Task/Mayan-numerals/SETL/mayan-numerals.setl new file mode 100644 index 0000000000..74e36127e4 --- /dev/null +++ b/Task/Mayan-numerals/SETL/mayan-numerals.setl @@ -0,0 +1,38 @@ +program mayan_numerals; + loop for n in [4005, 8017, 326205, 886205, 18380658207197784] do + print(str n + ":"); + print(mayan(n)); + end loop; + + proc mayan(n); + carts := [cartouche(d) : d in to_base20(n)]; + topbtm := '+----' * #carts + '+\n'; + lines := [+/['|' + c(l) : c in carts] + '|\n' : l in [1..4]]; + return topbtm +/ lines + topbtm; + end proc; + + proc cartouche(n); + parts := { + [0, ' '], + [1, ' . '], + [2, ' .. '], + [3, '... '], + [4, '....'], + [5, '----'] + }; + + cart := [parts((n-m) min 5 max 0) : m in [15,10,5,0]]; + if n=0 then cart(4) := ' @ '; end if; + return cart; + end proc; + + proc to_base20(n); + if n=0 then return [0]; end if; + ds := []; + loop while n>0 do + ds := [n mod 20] + ds; + n div:= 20; + end loop; + return ds; + end proc; +end program; diff --git a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx index 42ff9bd545..55681c59ee 100644 --- a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx +++ b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx @@ -21,7 +21,7 @@ procedure expose glob. numeric digits Digits()+2 y = 0.5-Ln(2) do n = 3 by 2 to 1000000 - if IsPrime(n) then do + if Prime(n) then do q = 1/n; t = Ln(1-q)+q; y = y+t end end diff --git a/Task/Mertens-function/ALGOL-68/mertens-function.alg b/Task/Mertens-function/ALGOL-68/mertens-function.alg index 479a042e38..cfeea7bcfe 100644 --- a/Task/Mertens-function/ALGOL-68/mertens-function.alg +++ b/Task/Mertens-function/ALGOL-68/mertens-function.alg @@ -9,11 +9,11 @@ BEGIN # compute values of the Mertens function # # Print table # print( ( "The first 99 Mertens numbers are:", newline ) ); print( ( " " ) ); - INT k := 9; + INT left := 9; FOR n TO 99 DO print( ( whole( m[ n ], -3 ) ) ); - IF ( k -:= 1 ) = 0 THEN - k := 10; + IF ( left -:= 1 ) = 0 THEN + left := 10; print( ( newline ) ) FI OD; diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/FutureBasic/minimum-multiple-of-m-where-digital-sum-equals-m.basic b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/FutureBasic/minimum-multiple-of-m-where-digital-sum-equals-m.basic new file mode 100644 index 0000000000..e837dbf2e1 --- /dev/null +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/FutureBasic/minimum-multiple-of-m-where-digital-sum-equals-m.basic @@ -0,0 +1,30 @@ +int local fn DigitSum( num as int ) + int sum = 0, n = num + while ( n > 0 ) + sum += n % 10 + n /= 10 + wend +end fn = sum + +void local fn DoIt + for int n = 1 to 70 + int m = 1 + while ( 1 ) + if ( fn DigitSum( m * n ) == n ) + printf @"%8d\b",m + if ( n % 10 == 0 ) + print + else + print @" "; + end if + break + end if + m++ + wend + next +end fn + +window 1, @"Minimum multiple of m where digital sum equals m", (0,0,670,200) +fn DoIt + +HandleEvents diff --git a/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg b/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg index f87bdbb776..9fd0fc9832 100644 --- a/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg +++ b/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg @@ -2,13 +2,13 @@ BEGIN # Modified random distribution - translation of the Wren sample # next random; # initialise the random number generator # - PROC rng = ( PROC(REAL)REAL modifier )REAL: + PROC rng = ( PROC(REAL)REAL modifier fn )REAL: BEGIN REAL r1, r2; WHILE r1 := random; r2 := random; - r2 >= modifier( r1 ) + r2 >= modifier fn( r1 ) DO SKIP OD; r1 END # rng # ; @@ -21,7 +21,7 @@ BEGIN # Modified random distribution - translation of the Wren sample # CHAR hist char = "#"; INT hist char size = 125; [ 0 : num bins - 1 ]INT bins ; FOR i FROM LWB bins TO UPB bins DO bins[ i ] := 0 OD; - FOR i FROM 0 TO n DO + FROM 0 TO n DO bins[ ENTIER ( rng( modifier ) / bin size ) ] +:= 1 OD; diff --git a/Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 b/Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 new file mode 100644 index 0000000000..e6bcbd4ba3 --- /dev/null +++ b/Task/Modified-random-distribution/XPL0/modified-random-distribution.xpl0 @@ -0,0 +1,39 @@ +include xpllib; \for Print + +func real Modifier(X); +real X; +return if X < 0.5 then 2.*(0.5-X) else 2.*(X-0.5); + +func real RGen; +return float(Ran(1_000_000)) / 1e6; + +func real RNG; +real R1, R2; +[loop [R1:= RGen; + R2:= RGen; + if R2 < Modifier(R1) then + return R1; + ]; +]; + +def N = 100_000; +def NUM_BINS = 20; +def HIST_CHAR = ^#; +def HIST_CHAR_SIZE = 125; +def BinSize = 1. / float(NUM_BINS); +int Bins(NUM_BINS), BN, I, J, Hist; +real RN; +[for I:= 0 to N-1 do + [RN:= RNG; + BN:= fix(Floor(RN/BinSize)); + Bins(BN):= Bins(BN)+1; + ]; +Print("Modified random distribution with %,d samples in range [0, 1):\n", N); +Print(" Range Number of samples within that range\n"); +for I:= 0 to NUM_BINS-1 do + [Hist:= Bins(I) / HIST_CHAR_SIZE; + Print("%1.2f ..< %1.2f ", BinSize*float(I), BinSize*float(I+1)); + for J:= 1 to Hist do Print("%c", HIST_CHAR); + Print(" %,d\n", Bins(I)); + ]; +] diff --git a/Task/Monads-List-monad/V-(Vlang)/monads-list-monad.v b/Task/Monads-List-monad/V-(Vlang)/monads-list-monad.v new file mode 100644 index 0000000000..38bf250e8a --- /dev/null +++ b/Task/Monads-List-monad/V-(Vlang)/monads-list-monad.v @@ -0,0 +1,27 @@ +struct Mlist {value []int} + +fn (m Mlist) bind(f fn (lst []int) Mlist) Mlist {return f(m.value)} + +fn unit(lst []int) Mlist {return Mlist{lst}} + +fn increment(lst []int) Mlist { + mut lst2 := lst.clone() + for i, v in lst { + lst2[i] = v + 1 + } + return unit(lst2) +} + +fn double(lst []int) Mlist { + mut lst2 := lst.clone() + for i, v in lst { + lst2[i] = 2 * v + } + return unit(lst2) +} + +fn main() { + ml1 := unit([3, 4, 5]) + ml2 := ml1.bind(increment).bind(double) + println("${ml1.value} -> ${ml2.value}") +} diff --git a/Task/Multiple-regression/ALGOL-68/multiple-regression.alg b/Task/Multiple-regression/ALGOL-68/multiple-regression.alg index 587b22a4f8..2891016c6e 100644 --- a/Task/Multiple-regression/ALGOL-68/multiple-regression.alg +++ b/Task/Multiple-regression/ALGOL-68/multiple-regression.alg @@ -13,28 +13,28 @@ BEGIN # Multiple Regression - trnslation of the VB.NET sample but using the # ); PRIO NEWMATRIX = 1; - OP NEWMATRIX = ( INT rows, INT cols )MATRIX: + OP NEWMATRIX = ( INT m rows, INT m cols )MATRIX: BEGIN MATRIX result; - require( rows > 0, "Need at least one row" ); - row count OF result := rows; - require( cols > 0, "Need at least one column" ); - col count OF result := cols; - data OF result := HEAP[ 1 : rows, 1 : cols ]REAL; - FOR r TO rows DO FOR c TO cols DO ( data OF result )[ r, c ] := 0 OD OD; + require( m rows > 0, "Need at least one row" ); + row count OF result := m rows; + require( m cols > 0, "Need at least one column" ); + col count OF result := m cols; + data OF result := HEAP[ 1 : m rows, 1 : m cols ]REAL; + FOR r TO m rows DO FOR c TO m cols DO ( data OF result )[ r, c ] := 0 OD OD; result END # NEWMATRIX # ; OP NEWMATRIX = ( [,]REAL source )MATRIX: BEGIN MATRIX result; - INT rows = 1 + ( 1 UPB source - 1 LWB source ); - require( rows > 0, "Need at least one row" ); - row count OF result := rows; - INT cols = 1 + ( 2 UPB source - 2 LWB source ); - require( cols > 0, "Need at least one column" ); - col count OF result := cols; - data OF result := HEAP[ 1 : rows, 1 : cols ]REAL := source[ AT 1, AT 1 ]; + INT m rows = 1 + ( 1 UPB source - 1 LWB source ); + require( m rows > 0, "Need at least one row" ); + row count OF result := m rows; + INT m cols = 1 + ( 2 UPB source - 2 LWB source ); + require( m cols > 0, "Need at least one column" ); + col count OF result := m cols; + data OF result := HEAP[ 1 : m rows, 1 : m cols ]REAL := source[ AT 1, AT 1 ]; result END # NEWMATRIX # ; @@ -101,16 +101,16 @@ BEGIN # Multiple Regression - trnslation of the VB.NET sample but using the # m[this row,lead col:] := m[other row,lead col:]; m[other row,lead col:] := swap FI; - FIELD scale = 1/m[this row,lead col]; - IF scale /= 1 THEN + FIELD scalef = 1/m[this row,lead col]; + IF scalef /= 1 THEN m[this row,lead col] := 1; - FOR col FROM lead col+1 TO 2 UPB m DO m[this row,col] *:= scale OD + FOR col FROM lead col+1 TO 2 UPB m DO m[this row,col] *:= scalef OD FI; - FOR other row FROM LWB m TO UPB m DO - IF this row /= other row THEN - REAL scale = m[other row,lead col]; - m[other row,lead col]:=0; - FOR col FROM lead col+1 TO 2 UPB m DO m[other row,col] -:= scale*m[this row,col] OD + FOR other row pos FROM LWB m TO UPB m DO + IF this row /= other row pos THEN + REAL o scale = m[other row pos,lead col]; + m[other row pos,lead col]:=0; + FOR col FROM lead col+1 TO 2 UPB m DO m[other row pos,col] -:= o scale*m[this row,col] OD FI OD; lead col +:= 1 diff --git a/Task/Munching-squares/FutureBasic/munching-squares.basic b/Task/Munching-squares/FutureBasic/munching-squares.basic new file mode 100644 index 0000000000..122f54b73e --- /dev/null +++ b/Task/Munching-squares/FutureBasic/munching-squares.basic @@ -0,0 +1,53 @@ +void local fn HueToRGB( hue as double, sat as double, buffer as ptr ) + double x + int c = 255 * sat + hue /= 60.0 + x = (1 - abs((hue % 2) - 1)) * 255 + + xref p(1) as unsigned char + p = buffer + + select ( fix(hue) ) + case 0 : p(0) = c : p(1) = x : p(2) = 0 + case 1 : p(0) = x : p(1) = c : p(2) = 0 + case 2 : p(0) = 0 : p(1) = c : p(2) = x + case 3 : p(0) = 0 : p(1) = x : p(2) = c + case 4 : p(0) = x : p(1) = 0 : p(2) = c + case 5 : p(0) = c : p(1) = 0 : p(2) = x + end select +end fn + +ImageRef local fn CreateImage + int size = 512, i, j + ptr colors = fn malloc( size * 3 ) + ptr pix = fn malloc( size * size * 3 ) + + for i = 0 to size - 1 + fn HueToRGB( i * 240.0 / size, i * 1.0 / size, (ptr)(colors + 3 * i) ) + next + + for i = 0 to size - 1 + for j = 0 to size - 1 + fn memcpy( pix + ( ( i * size + j ) * 3 ), colors + ( ( i ^^ j ) * 3 ), 3 ) + next + next + + BitmapImageRepRef bitmap = fn BitmapImageRepWithBitmapDataPlanes( @pix, size, size, 8, 3, NO, NO, NSCalibratedRGBColorSpace, 3 * size, 24 ) + ImageRef image = fn ImageWithSize( fn CGSizeMake(size,size) ) + ImageAddRepresentation( image, bitmap ) + + free( colors ) + free( pix ) +end fn = image + +void local fn DoIt + window 1, @"Munching squares", (0,0,512,512) + imageview 1,,, (0,0,512,512) + ViewSetAutoresizingMask( 1, NSViewWidthSizable | NSViewHeightSizable ) + ImageRef image = fn CreateImage + imageview 1,, image +end fn + +fn DoIt + +HandleEvents diff --git a/Task/N-queens-problem/ALGOL-68/n-queens-problem.alg b/Task/N-queens-problem/ALGOL-68/n-queens-problem.alg index 4b35b32487..288ff44b1f 100644 --- a/Task/N-queens-problem/ALGOL-68/n-queens-problem.alg +++ b/Task/N-queens-problem/ALGOL-68/n-queens-problem.alg @@ -1,26 +1,24 @@ +# N-queens problem # INT ofs = 1, # Algol68 normally uses array offset of 1 # dim = 8; # dim X dim chess board # [ofs:dim+ofs-1]INT b; PROC unsafe = (INT y)BOOL:( - INT i, t, x; - x := b[y]; - FOR i TO y - LWB b DO - t := b[y - i]; - IF t = x THEN break true - ELIF t = x - i THEN break true - ELIF t = x + i THEN break true + INT x = b[y]; + BOOL safe := TRUE; + FOR i TO y - LWB b WHILE safe DO + INT t = b[y - i]; + IF t = x THEN safe := FALSE + ELIF t = x - i THEN safe := FALSE + ELIF t = x + i THEN safe := FALSE FI OD; - FALSE EXIT -break true: - TRUE + NOT safe ); INT s := 0; PROC print board = VOID:( - INT x, y; print((new line, "Solution # ", s+:=1, new line)); FOR y FROM LWB b TO UPB b DO FOR x FROM LWB b TO UPB b DO @@ -30,15 +28,12 @@ PROC print board = VOID:( OD ); -main: ( +# main # ( INT y := LWB b; b[LWB b] := LWB b - 1; - FOR i WHILE y >= LWB b DO - WHILE - b[y]+:=1; - # BREAK # IF b[y] <= UPB b THEN unsafe(y) ELSE FALSE FI - DO SKIP OD; - IF b[y] <= UPB b THEN + WHILE y >= LWB b DO + WHILE IF (b[y]+:=1) <= UPB b THEN unsafe(y) ELSE FALSE FI DO SKIP OD; + IF b[y] <= UPB b THEN IF y < UPB b THEN b[y+:=1] := LWB b - 1 ELSE diff --git a/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin b/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin index c820a635c1..968f6bbe2e 100644 --- a/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin +++ b/Task/N-queens-problem/Tailspin/n-queens-problem-3.tailspin @@ -1,4 +1,6 @@ templates queens + data done <=1> local + def n: $; templates getRowColumn when )> do 0 ! @@ -14,8 +16,6 @@ templates queens @queens.freeMins($p.c::raw - $p.r::raw + $n): $p.val::raw; end setRowColumn - data done <=1> - templates placeQueen def c: $; row´1 -> # diff --git a/Task/N-queens-problem/Tailspin/n-queens-problem-4.tailspin b/Task/N-queens-problem/Tailspin/n-queens-problem-4.tailspin new file mode 100644 index 0000000000..f4cdba96da --- /dev/null +++ b/Task/N-queens-problem/Tailspin/n-queens-problem-4.tailspin @@ -0,0 +1,52 @@ +queens templates + done requires <|=1> + failed requires <|=0> + n is $; + getRowColumn templates + when <|?($@queens(freeRows:; $(r:)::raw) matches <|=0>)> do 0 ! + when <|?($@queens(freeMaxs:; $(r:)::raw + $(c:)::raw) matches <|=0>)> do 0 ! + when <|?($@queens(freeMins:; $(c:)::raw - $(r:)::raw + $n) matches <|=0>)> do 0 ! + otherwise 1! + end getRowColumn + + setRowColumn sink + p is $; + @queens(freeRows:; $p(r:)::raw) set $p(val:)::raw; + @queens(freeMaxs:; $p(c:)::raw + $p(r:)::raw) set $p(val:)::raw; + @queens(freeMins:; $p(c:)::raw - $p(r:)::raw + $n) set $p(val:)::raw; + end setRowColumn + + placeQueen templates + {c: $, r: 1} -> # ! + when <|done> do done´1! + when <|{c: <|$n + 1..>}> do done´1! + when <|{r: <|$n + 1..>}> do failed´0 ! + when <|?($ -> getRowColumn matches <|=1>)> do + current is $; + @queens(queenRows:; $(r:)::raw) set $(c:); + {$, val: 0} -> !setRowColumn + {c: $(c:)::raw + 1, r: 1} -> # -> templates + when <|done> do done´1! + otherwise + {$current, val: 1} -> !setRowColumn + {c: $current(c:), r: $current(r:)::raw + 1} ! + end -> # ! + otherwise {c: $(c:), r: $(r:)::raw + 1} -> # ! + end placeQueen + + @ set { freeRows: [1..$n -> 1], + freeMaxs: [1..$n*2 -> 1], + freeMins: [1..$n*2 -> 1], + queenRows: [1..$n -> -1] }; + 1 -> placeQueen -> templates + when <|done> do $@queens(queenRows:) ! + otherwise 'non-existent'! + end! +end queens + +'A solution to the 8 queens problem is $:8 -> queens; +' ! +'A solution to the 4 queens problem is $:4 -> queens; +' ! +'A solution to the 3 queens problem is $:3 -> queens; +' ! diff --git a/Task/Nim-game/FutureBasic/nim-game.basic b/Task/Nim-game/FutureBasic/nim-game.basic new file mode 100644 index 0000000000..75134082cf --- /dev/null +++ b/Task/Nim-game/FutureBasic/nim-game.basic @@ -0,0 +1,30 @@ +void local fn NimGame + window 1, @"Nim game" + + int tokens = 12 + while ( tokens != 0 ) + print @"Tokens remaining: ";tokens + CFStringRef num = inkey @"Take 1 to 3 tokens", @"123" + if ( !num ) then end + + int n = intval(num) + + print @"You took ";n; @" token"; + if ( n > 1 ) then print @"s" else print + tokens -= n + + int c = 4-n + + print @"I took ";c;@" token"; + if ( c > 1 ) then print @"s" else print + + tokens -= c + print + wend + + print @"I win!" +end fn + +fn NimGame + +HandleEvents diff --git a/Task/Nth/ALGOL-68/nth.alg b/Task/Nth/ALGOL-68/nth.alg index c468135b15..7127b891e0 100644 --- a/Task/Nth/ALGOL-68/nth.alg +++ b/Task/Nth/ALGOL-68/nth.alg @@ -1,9 +1,7 @@ # PROC to suffix a number with st, nd, rd or th as appropriate # PROC nth = ( INT number )STRING: BEGIN - INT number mod 100 = number MOD 100; - # RESULT # whole( number, 0 ) + IF number mod 100 >= 10 AND number mod 100 <= 20 @@ -29,21 +27,20 @@ BEGIN FOR test value FROM from TO to DO STRING test result = nth( test value ); - print( ( " "[ 1 : 8 - UPB test result ], nth( test value ) ) ); + print( ( " "[ 1 : 8 - UPB test result ], test result ) ); test count +:= 1; IF test count MOD 8 = 0 THEN print( ( newline ) ) FI OD; + IF test count MOD 8 /= 0 + THEN + print( ( newline ) ) + FI; print( ( newline ) ) END; # test nth # - -main: ( - - test nth( 0, 25 ); - test nth( 250, 265 ); - test nth( 1000, 1025 ) - -) +test nth( 0, 25 ); +test nth( 250, 265 ); +test nth( 1000, 1025 ) diff --git a/Task/Nth/FutureBasic/nth.basic b/Task/Nth/FutureBasic/nth.basic new file mode 100644 index 0000000000..f53b3a13ab --- /dev/null +++ b/Task/Nth/FutureBasic/nth.basic @@ -0,0 +1,28 @@ +CFStringRef local fn Suffix( n as int ) + if ( n % 100 / 10 == 1 ) then exit fn + select ( n % 10 ) + case 1 : return @"st" + case 2 : return @"nd" + case 3 : return @"rd" + end select +end fn = @"th" + +void local fn DoIt + int i + + for i = 0 to 25 + print i;fn Suffix(i);@" "; + next + print + for i = 250 to 265 + print i;fn Suffix(i);@" "; + next + print + for i = 1000 to 1025 + print i;fn Suffix(i);@" "; + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 b/Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 new file mode 100644 index 0000000000..26de64aba9 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/M2000-Interpreter/old-lady-swallowed-a-fly.m2000 @@ -0,0 +1,33 @@ +MODULE LikeBasic { + 010 M$="" + 020 NAME$="" : REM "out.txt" + 030 DIM A$(8), E$(8) + 040 GOSUB 220 + 050 OPEN NAME$ FOR OUTPUT AS #F + 070 FOR N = 0 TO 7: READ A$(N), E$(N): NEXT N : N-- + 080 FOR C = 1 TO N + 090 PRINT #F, "THERE WAS AN OLD LADY WHO SWALLOWED A "+A$(C) + 100 IF C > 1 THEN + 110 PRINT #F, E$(C) + 120 IF C < N THEN + 130 FOR B = C TO 2 + 140 PRINT #F, A$(0);A$(B);" TO CATCH THE ";A$(B-1);MID$(",;",1 - (B = 2),1) + 150 NEXT B + 160 END IF + 170 END IF + 180 IF C < N THEN PRINT #F, E$(1);E$(0) + 190 PRINT #F,"",,"" + 170 NEXT C + 200 CLOSE #F + 210 END + 220 DATA" SHE SWALLOWED A "," - PERHAPS SHE'LL DIE!" + 230 DATA"FLY","I DON'T KNOW WHY SHE SWALLOWED A FLY" + 240 DATA"SPIDER","THAT WRIGGLED AND JIGGLED AND TICKLED INSIDE HER;" + 250 DATA"BIRD","HOW ABSURD TO SWALLOW A BIRD." + 260 DATA"CAT","FANCY THAT TO SWALLOW A CAT!" + 270 DATA"DOG","WHAT A HOG, TO SWALLOW A DOG;" + 280 DATA"COW","I DON'T KNOW HOW SHE SWALLOWED A COW," + 290 DATA"HORSE","SHE'S DEAD, OF COURSE!" + 300 RETURN +} +LikeBasic diff --git a/Task/Own-digits-power-sum/FutureBasic/own-digits-power-sum.basic b/Task/Own-digits-power-sum/FutureBasic/own-digits-power-sum.basic new file mode 100644 index 0000000000..cab98ffd2e --- /dev/null +++ b/Task/Own-digits-power-sum/FutureBasic/own-digits-power-sum.basic @@ -0,0 +1,20 @@ +void local fn DoIt + for long N = 3 to 9 + print N;@" digits:"; + for long curr = 10^(N-1) to 10^N-1 + long sum = 0 + long temp = curr + do + long dig = temp % 10 + temp = temp / 10 + sum += dig ^ N + until temp == 0 + if ( sum == curr ) then printf @"%12ld\b",curr + next + print + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/P-value-correction/FreeBASIC/p-value-correction.basic b/Task/P-value-correction/FreeBASIC/p-value-correction.basic new file mode 100644 index 0000000000..e74e7775f8 --- /dev/null +++ b/Task/P-value-correction/FreeBASIC/p-value-correction.basic @@ -0,0 +1,301 @@ +#include "string.bi" + +#define MIN(a, b) iif((a) < (b), (a), (b)) + +Enum Direction + UP + DOWN +End Enum + +Type Sequence + As Integer length + As Double values(Any) +End Type + +' Constants for correction types +Dim As String correctionTypes(7) = { _ +"Benjamini-Hochberg", "Benjamini-Yekutieli", "Bonferroni", "Hochberg", _ +"Holm", "Hommel", "Sidak", "Unknown" } + +' Test p-values +Dim Shared As Double test_values(49) = { _ +4.533744e-01, 7.296024e-01, 9.936026e-02, 9.079658e-02, 1.801962e-01, _ +8.752257e-01, 2.922222e-01, 9.115421e-01, 4.355806e-01, 5.324867e-01, _ +4.926798e-01, 5.802978e-01, 3.485442e-01, 7.883130e-01, 2.729308e-01, _ +8.502518e-01, 4.268138e-01, 6.442008e-01, 3.030266e-01, 5.001555e-02, _ +3.194810e-01, 7.892933e-01, 9.991834e-01, 1.745691e-01, 9.037516e-01, _ +1.198578e-01, 3.966083e-01, 1.403837e-02, 7.328671e-01, 6.793476e-02, _ +4.040730e-03, 3.033349e-04, 1.125147e-02, 2.375072e-02, 5.818542e-04, _ +3.075482e-04, 8.251272e-03, 1.356534e-03, 1.360696e-02, 3.764588e-04, _ +1.801145e-05, 2.504456e-07, 3.310253e-02, 9.427839e-03, 8.791153e-04, _ +2.177831e-04, 9.693054e-04, 6.610250e-05, 2.900813e-02, 5.735490e-03 } + +Function minimum(p As Sequence) As Double + Dim m As Double = p.values(0) + For i As Integer = 1 To p.length - 1 + If p.values(i) < m Then m = p.values(i) + Next + Return m +End Function + +Function maximum(p As Sequence) As Double + Dim m As Double = p.values(0) + For i As Integer = 1 To p.length - 1 + If p.values(i) > m Then m = p.values(i) + Next + Return m +End Function + +Sub ratchet(p As Sequence, direcc As Integer) + Dim m As Double = p.values(0) + Dim i As Integer + + If direcc = UP Then + For i = 1 To p.length - 1 + ' Corrected logic: only update if greater than minimum + If p.values(i) > m Then p.values(i) = m + m = p.values(i) + Next + Else + For i = 1 To p.length - 1 + If p.values(i) < m Then p.values(i) = m + m = p.values(i) + Next + End If + + ' Cap at 1.0 + For i = 0 To p.length - 1 + If p.values(i) > 1.0 Then p.values(i) = 1.0 + Next +End Sub + +Function schwartzian(p As Sequence, mult As Sequence, direcc As Integer) As Sequence + Dim As Sequence result + result.length = p.length + Redim result.values(p.length-1) + Dim As Integer i, j + + ' Sort with indices + Dim As Integer indices(p.length-1) + For i = 0 To p.length-1 + indices(i) = i + Next + + ' Sort based on direccection + For i = 0 To p.length-2 + For j = 0 To p.length-2-i + Dim As Boolean cond + If direcc = UP Then + cond = p.values(indices(j)) < p.values(indices(j+1)) + Else + cond = p.values(indices(j)) > p.values(indices(j+1)) + End If + If cond Then Swap indices(j), indices(j+1) + Next + Next + + ' Apply multipliers + For i = 0 To p.length-1 + result.values(i) = p.values(indices(i)) * mult.values(i) + Next + + ratchet(result, direcc) + + ' Restore original order + Dim As Sequence final + final.length = p.length + Redim final.values(p.length-1) + + For i = 0 To p.length-1 + final.values(indices(i)) = result.values(i) + Next + + Return final +End Function + +Function adjust(p As Sequence, method As String) As Sequence + Dim As Sequence result + result.length = p.length + Redim result.values(p.length-1) + + Dim As Sequence mult + mult.length = p.length + Redim mult.values(p.length-1) + + Dim As Integer i + Dim As Double tmp + + Select Case method + Case "Benjamini-Hochberg" + For i = 0 To p.length-1 + mult.values(i) = p.length / (p.length - i) + Next + Return schwartzian(p, mult, UP) + + Case "Benjamini-Yekutieli" + tmp = 0 + For i = 1 To p.length + tmp += 1.0 / i + Next + + For i = 0 To p.length-1 + mult.values(i) = tmp * p.length / (p.length - i) + Next + Return schwartzian(p, mult, UP) + + Case "Bonferroni" + For i = 0 To p.length-1 + result.values(i) = Min(p.values(i) * p.length, 1.0) + Next + Return result + + Case "Hochberg" + For i = 0 To p.length-1 + mult.values(i) = i + 1 + Next + Return schwartzian(p, mult, UP) + + Case "Holm" + For i = 0 To p.length-1 + mult.values(i) = p.length - i + Next + Return schwartzian(p, mult, DOWN) + + Case "Hommel" + Dim As Integer order(p.length-1), j + Dim As Double s(p.length-1) + + ' Sort and get order + For i = 0 To p.length-1 + order(i) = i + Next + For i = 0 To p.length-2 + For j = 0 To p.length-2-i + If p.values(order(j)) > p.values(order(j+1)) Then Swap order(j), order(j+1) + Next + Next + + ' Get sorted values + For i = 0 To p.length-1 + s(i) = p.values(order(i)) + Next + + ' Calculate initial minimum + Dim As Double m(p.length-1) + For i = 0 To p.length-1 + m(i) = s(i) * p.length / (i + 1) + Next + + Dim As Double min_val = m(0) + For i = 1 To p.length-1 + If m(i) < min_val Then min_val = m(i) + Next + + Dim As Double pa(p.length-1), q(p.length-1) + For i = 0 To p.length-1 + pa(i) = min_val + q(i) = min_val + Next + + ' Hommel algorithm + For j = p.length-1 To 2 Step -1 + Dim As Integer lower_count = p.length - j + 1 + Dim As Integer upper_count = j - 1 + + ' Initialize qmin with first upper value + Dim As Double qmin = j * s(p.length - j + 1) / 2.0 + + ' Check remaining upper values + For i = 1 To upper_count-1 + Dim As Double tmp = s(p.length - j + 1 + i) * j / (2.0 + i) + qmin = MIN(qmin, tmp) + Next + + ' Update lower values + For i = 0 To lower_count-1 + q(i) = MIN(s(i) * j, qmin) + Next + + ' Update upper values + For i = lower_count To p.length-1 + q(i) = q(p.length - j) + Next + + ' Update pa with maximum between current and new values + For i = 0 To p.length-1 + If q(i) > pa(i) Then pa(i) = q(i) + Next + Next + + ' Map back to original order + For i = 0 To p.length-1 + result.values(order(i)) = MIN(pa(i), 1.0) + Next + Return result + + Case "Šidák", "Sidak" + For i = 0 To p.length-1 + result.values(i) = 1.0 - (1.0 - p.values(i)) ^ p.length + Next + Return result + + Case Else + result.length = 0 + End Select + + Return result +End Function + +Function formatOutput(values As Sequence) As String + Dim As String result = "" + Dim As Integer i, j + + For i = 0 To values.length -1 Step 5 + result &= "[" & Format(i, "00") & "] " + For j = 0 To 4 + If i + j < values.length Then + result &= Format(values.values(i+j), "0.0000000000") & " " + End If + Next + result &= !"\n" + Next + Return result +End Function + +'Main program +Dim As Sequence p +p.length = 50 +Redim p.values(49) +Dim As Integer i + +' Initialize p-values +For i = 0 To 49 + p.values(i) = test_values(i) +Next + +' Check p-values +If p.length = 0 Orelse minimum(p) < 0 Orelse maximum(p) > 1 Then + Print "p-values must be in range 0.0 to 1.0" + End +End If + +' Apply each correction method +For i = 0 To 7 + Dim As String method = correctionTypes(i) + + Print method + + Dim As Sequence result = adjust(p, method) + + If result.length > 0 Then + Print formatOutput(result) + Else + Print "Sorry, do not know how to do '" & method & "' correction." + Print "Perhaps you want one of these?:" + For j As Integer = 0 To 6 + Print " " & correctionTypes(j) + Next + End If +Next + +Sleep diff --git a/Task/Padovan-n-step-number-sequences/ALGOL-68/padovan-n-step-number-sequences.alg b/Task/Padovan-n-step-number-sequences/ALGOL-68/padovan-n-step-number-sequences.alg index 38f518a27a..d7feced12a 100644 --- a/Task/Padovan-n-step-number-sequences/ALGOL-68/padovan-n-step-number-sequences.alg +++ b/Task/Padovan-n-step-number-sequences/ALGOL-68/padovan-n-step-number-sequences.alg @@ -21,11 +21,11 @@ BEGIN # show some valuies of the Padovan n-step number sequences # r END # padovan sequences # ; # calculate and show the sequences # - [,]INT r = padovan sequences( 8, 15 ); + [,]INT ps = padovan sequences( 8, 15 ); print( ( "Padovan n-step sequences:", newline ) ); - FOR n FROM 1 LWB r TO 1 UPB r DO + FOR n FROM 1 LWB ps TO 1 UPB ps DO print( ( whole( n, 0 ), " |" ) ); - FOR x FROM 2 LWB r TO 2 UPB r DO print( ( " ", whole( r[ n, x ], -3 ) ) ) OD; + FOR x FROM 2 LWB ps TO 2 UPB ps DO print( ( " ", whole( ps[ n, x ], -3 ) ) ) OD; print( ( newline ) ) OD END diff --git a/Task/Palindrome-dates/FutureBasic/palindrome-dates.basic b/Task/Palindrome-dates/FutureBasic/palindrome-dates.basic new file mode 100644 index 0000000000..109cff9e12 --- /dev/null +++ b/Task/Palindrome-dates/FutureBasic/palindrome-dates.basic @@ -0,0 +1,30 @@ +BOOL local fn IsPalindrome( string as CFStringRef ) + CFMutableStringRef tempString = fn MutableStringNew + for long i = len(string) - 1 to 0 step -1 + MutableStringAppendString( tempString, mid(string,i,1) ) + next +end fn = fn StringIsEqual( string, tempString ) + +void local fn DoIt + DateFormatterRef format = fn DateFormatterInit + DateFormatterSetDateFormat( format, @"yyyyMMdd" ) + + DateFormatterRef outputFormat = fn DateFormatterInit + DateFormatterSetDateFormat( outputFormat, @"yyyy-MM-dd" ) + + long count = 0, limit = 15 + CFCalendarRef calendar = fn CalendarCurrent + CFDateRef dt = fn DateInit + + while ( count < limit ) + if ( fn IsPalindrome( fn DateFormatterStringFromDate( format, dt ) ) ) + print fn DateFormatterStringFromDate( outputFormat, dt ) + count ++ + end if + dt = fn CalendarDateByAddingUnit( calendar, NSCalendarUnitDay, 1, dt, 0 ) + wend +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Palindrome-detection/BASIC/palindrome-detection.basic b/Task/Palindrome-detection/BASIC/palindrome-detection.basic index e14e4f498a..c3d6779af0 100644 --- a/Task/Palindrome-detection/BASIC/palindrome-detection.basic +++ b/Task/Palindrome-detection/BASIC/palindrome-detection.basic @@ -68,7 +68,7 @@ END FUNCTION FUNCTION RvrsText$ (WhichText$) ' Var - DIM i%, c$, NewText$, j% + DIM i%, NewText$, j% j% = LEN(WhichText$) FOR i% = 1 TO j% diff --git a/Task/Pancake-numbers/00-TASK.txt b/Task/Pancake-numbers/00-TASK.txt index cd1b078632..37e1a1ab7c 100644 --- a/Task/Pancake-numbers/00-TASK.txt +++ b/Task/Pancake-numbers/00-TASK.txt @@ -10,7 +10,7 @@ Few people know p(20), generously I shall award an extra credit for anyone doing : Note that the original "cheeky partial answer" of [[Pancake_numbers#Phix|Phix]] has since been updated (5/12/2020), and/but just that, with no examples as asked for, ''will'' get your entry marked as incomplete. ;References -# [https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem Bill Gates and the pancake problem] +# [https://web.archive.org/web/20240525075316/https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem/ Bill Gates and the pancake problem] # [https://oeis.org/A058986 A058986]

diff --git a/Task/Pancake-numbers/Rust/pancake-numbers.rs b/Task/Pancake-numbers/Rust/pancake-numbers-1.rs similarity index 100% rename from Task/Pancake-numbers/Rust/pancake-numbers.rs rename to Task/Pancake-numbers/Rust/pancake-numbers-1.rs diff --git a/Task/Pancake-numbers/Rust/pancake-numbers-2.rs b/Task/Pancake-numbers/Rust/pancake-numbers-2.rs new file mode 100644 index 0000000000..09908f59b0 --- /dev/null +++ b/Task/Pancake-numbers/Rust/pancake-numbers-2.rs @@ -0,0 +1,45 @@ +use std::collections::HashMap; + +fn pancake_flips(len: usize) -> Option<(Vec, i32)> { + if len < 1 { + return None; + } + let goal_stack: Vec = (1..len as i32 + 1).collect(); + let mut stacks: HashMap, i32> = HashMap::new(); + stacks.insert(goal_stack.clone(), 0); + let mut num_stacks = 1; + let mut new_stacks = stacks.clone(); + for i in 1..1001 { + let mut next_stacks: HashMap, i32> = HashMap::new(); + for (arr, _steps) in &new_stacks { + for pos in 1_usize..(len + 1) { + let mut new_stack = arr[0..pos].to_vec(); + new_stack.reverse(); + new_stack.extend_from_slice(&arr[pos..arr.len()]); + if !stacks.contains_key(&new_stack) { + next_stacks.insert(new_stack.clone(), i); + } + } + } + new_stacks = next_stacks; + stacks.extend(new_stacks.clone().into_iter()); + let perms = stacks.len(); + if perms == num_stacks { + match stacks.into_iter().max_by_key(|p| p.1) { + Some(pair) => return Some(pair), + None => break, + } + } + num_stacks = perms; + } + None +} + +fn main() { + for i in 1..=10 { + match pancake_flips(i) { + Some(p) => println!("pancake({:>2}) = {:<5} example: {:?}", i, p.1, p.0), + None => println!("Error: cannot flip stack with size {i}"), + } + } +} diff --git a/Task/Parse-an-IP-Address/FreeBASIC/parse-an-ip-address.basic b/Task/Parse-an-IP-Address/FreeBASIC/parse-an-ip-address.basic new file mode 100644 index 0000000000..51c30cad3a --- /dev/null +++ b/Task/Parse-an-IP-Address/FreeBASIC/parse-an-ip-address.basic @@ -0,0 +1,175 @@ +Function isNumericString(s As String) As Boolean + For i As Integer = 1 To Len(s) + Dim c As String = Mid(s, i, 1) + If c < "0" Or c > "9" Then Return False + Next + Return True +End Function + +Function isHexString(s As String) As Boolean + For i As Integer = 1 To Len(s) + Dim c As String = Mid(s, i, 1) + If Not ((c >= "0" And c <= "9") Or (c >= "a" And c <= "f") Or (c >= "A" And c <= "F")) Then Return False + Next + Return True +End Function + +Function Split(text As String, delimiter As String, arr() As String) As Integer + If Len(text) = 0 Then Return 0 + + Dim As Integer cnt = 0, posic = 0, lastPos = 0 + Redim arr(8) ' Pre-allocate array with sufficient size + + Do + posic = Instr(lastPos + 1, text, delimiter) + If posic = 0 Then + If lastPos < Len(text) Then + arr(cnt) = Mid(text, lastPos + 1) + cnt += 1 + End If + Exit Do + End If + + arr(cnt) = Mid(text, lastPos + 1, posic - lastPos - 1) + cnt += 1 + lastPos = posic + Loop + + Return cnt +End Function + +Function parseIP(addr As String) As String + Dim As String result = "IP address : " & addr & !"\n" + Dim As String parts(8), ipParts(8) + Dim As Integer cnt, i + Dim As String port = "not specified" + + ' Check if it's an IPv4 address + cnt = Split(addr, ":", parts()) + + ' IPv4 processing + cnt = Split(parts(0), ".", ipParts()) + If cnt = 4 Then + Dim As String hexa = "" + Dim As Boolean valid = True + + For i = 0 To 3 + Dim As Integer value = Valint(ipParts(i)) + If value >= 0 Andalso value <= 255 Then + hexa &= Right("0" & Hex(value), 2) + Else + valid = False + Exit For + End If + Next + + If valid Then + result &= "Address : " & hexa & !"\n" + result &= "Address Space: IPv4" & !"\n" + If Len(parts(1)) > 0 Then + Dim As Integer portVal = Valint(parts(1)) + If portVal >= 0 Andalso portVal <= 65535 Then + result &= "Port : " & parts(1) & !"\n" + End If + Else + result &= "Port : not specified" & !"\n" + End If + Return result + End If + End If + + ' Check if it's an IPv6 address + If Instr(addr, ":") > 0 Then + Dim As String ipv6Addr = addr + + If Left(addr, 1) = "[" Then + Dim As Integer endBracket = Instr(addr, "]") + If endBracket > 0 Then + ipv6Addr = Mid(addr, 2, endBracket - 2) + If endBracket < Len(addr) Then + port = Mid(addr, endBracket + 2) + End If + End If + End If + + ' Special handling for IPv4-mapped IPv6 addresses + If Instr(ipv6Addr, "::ffff:") > 0 Then + Dim As String ipv4Part = Mid(ipv6Addr, Instr(ipv6Addr, "::ffff:") + 7) + cnt = Split(ipv4Part, ".", ipParts()) + + If cnt = 4 Then + Dim As String hexa = "FFFF" + Dim As Boolean valid = True + + For i = 0 To 3 + Dim As Integer value = Valint(ipParts(i)) + If value >= 0 Andalso value <= 255 Then + hexa &= Right("0" & Hex(value), 2) + Else + valid = False + Exit For + End If + Next + + If valid Then + result &= "Address : " & hexa & !"\n" + result &= "Address Space: IPv6" & !"\n" + result &= "Port : " & port & !"\n" + Return result + End If + End If + ' If IPv4 part is invalid, return invalid address + Return result & "Address : Invalid Address" & !"\n" + End If + + cnt = Split(ipv6Addr, ":", ipParts()) + If cnt > 0 Then + Dim As String hexa = "" + Dim As Integer emptyIndex = -1 + + ' Find :: position + For i = 0 To cnt - 1 + If Len(ipParts(i)) = 0 Then + emptyIndex = i + Exit For + End If + Next + + ' Process parts before :: + For i = 0 To emptyIndex - 1 + hexa &= Right("0000" & ipParts(i), 4) + Next + + ' Fill middle with zeros + If emptyIndex >= 0 Then + Dim As Integer zerosNeeded = 8 - (cnt - 1) + hexa &= String(zerosNeeded * 4, "0") + End If + + ' Process parts after :: + For i = emptyIndex + 1 To cnt - 1 + hexa &= Right("0000" & ipParts(i), 4) + Next + + result &= "Address : " & hexa & !"\n" + result &= "Address Space: IPv6" & !"\n" + result &= "Port : " & port & !"\n" + Return result + End If + End If + + Return result & "Address : Invalid Address" & !"\n" +End Function + +' Test cases +Dim As String ipAddresses(0 To ...) = { _ +"127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", _ +"[2605:2700:0:3::4713:93e3]:80", "::ffff:192.168.173.22", _ +"[::ffff:192.168.173.22]:80", _ +"1::", "::", "256.0.0.0", "::ffff:127.0.0.0.1", "RosettaCode" } + +For i As Byte = 0 To Ubound(ipAddresses) + Print parseIP(ipAddresses(i)) +Next + +Sleep diff --git a/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg b/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg index 099cffc8ab..115936b675 100644 --- a/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg +++ b/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg @@ -5,7 +5,7 @@ CHAR end of expression character = REPR 12; # evaluates the specified rpn expression # -PROC evaluate = ( STRING rpn expression )VOID: +PROC evaluate rpn = ( STRING rpn expression )VOID: BEGIN [ 256 ]REAL stack; @@ -123,21 +123,15 @@ BEGIN print( ( "Result is: ", fixed( stack[ stack pos ], 12, 8 ), newline ) ) -END; # evaluate # - -main: ( +END; # evaluate rpn # +BEGIN # get the RPN expresson from the user # - STRING rpn expression; - print( ( "Enter expression: " ) ); read( ( rpn expression, newline ) ); - # add a space to terminate the final token and an expression terminator # rpn expression +:= " " + end of expression character; - # execute the expression # - evaluate( rpn expression ) - -) + evaluate rpn( rpn expression ) +END diff --git a/Task/Parsing-RPN-to-infix-conversion/FreeBASIC/parsing-rpn-to-infix-conversion.basic b/Task/Parsing-RPN-to-infix-conversion/FreeBASIC/parsing-rpn-to-infix-conversion.basic new file mode 100644 index 0000000000..28a2f72fdd --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/FreeBASIC/parsing-rpn-to-infix-conversion.basic @@ -0,0 +1,117 @@ +Dim Shared As Boolean showWorkings = True +Dim Shared As String*1 operators(4) = {"^","*","/","+","-"} +Dim Shared As Integer precedence(4) = { 4, 3, 3, 2, 2 } +Dim Shared As Integer rassoc(4) = {Asc("r"), 0 , Asc("l"), 0 , Asc("l")} + +Sub parseRPN(expr As String, expected As String) + Dim As String stack(), ops() + Dim As String lhs, rhs, token, op, res + Dim As Integer lprec, rprec, posic + Dim As Integer i, j, k + + ' Convert expr to ops array without using SPLIT + posic = 1 + While posic <= Len(expr) + token = "" + While posic <= Len(expr) And Mid(expr, posic, 1) <> " " + token &= Mid(expr, posic, 1) + posic += 1 + Wend + If token <> "" Then + Redim Preserve ops(Ubound(ops) + 1) + ops(Ubound(ops)) = token + End If + posic += 1 + Wend + + Print "Postfix input: "; + Print Using ("\ \"); expr; + Print Iif(showWorkings, Chr(10), " "); + + If Ubound(ops) = -1 Then + Print "error" + Exit Sub + End If + + For i = 0 To Ubound(ops) + op = ops(i) + k = -1 + For j = 0 To Ubound(operators) + If op = operators(j) Then + k = j + Exit For + End If + Next + + If k = -1 Then + Redim Preserve stack(Ubound(stack) + 1) + stack(Ubound(stack)) = "9 " & op + Else + If Ubound(stack) < 1 Then + Print "error" + Exit Sub + End If + Dim As String rprec_rhs = stack(Ubound(stack)) + stack(Ubound(stack)) = "" + Redim Preserve stack(Ubound(stack) - 1) + Dim As String lprec_lhs = stack(Ubound(stack)) + lprec = Val(Left(lprec_lhs, 1)) + lhs = Mid(lprec_lhs, 3) + rprec = Val(Left(rprec_rhs, 1)) + rhs = Mid(rprec_rhs, 3) + Dim As Integer prec = precedence(k) + Dim As Integer assoc = rassoc(k) + If lprec < prec Or (lprec = prec And assoc = Asc("r")) Then lhs = "(" & lhs & ")" + If rprec < prec Or (rprec = prec And assoc = Asc("l")) Then rhs = "(" & rhs & ")" + stack(Ubound(stack)) = prec & " " & lhs & " " & op & " " & rhs + End If + + If showWorkings Then + ?"["; + 'Print op; " "; Join(stack, ", ") + Print op; ", [["; stack(0); + For j = 1 To Ubound(stack) + Print "], ["; stack(j); + Next + Print "]]]" + End If + Next + + res = Mid(stack(0), 3) + Print "Infix result: "; res; + Print " ["; Iif(res = expected, "ok", "**ERROR**"); "]" +End Sub + +parseRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +", "3 + 4 * 2 / (1 - 5) ^ 2 ^ 3") +showWorkings = False +parseRPN("1 2 + 3 4 + ^ 5 6 + ^", "((1 + 2) ^ (3 + 4)) ^ (5 + 6)") +parseRPN("1 2 + 3 4 + 5 6 + ^ ^", "(1 + 2) ^ (3 + 4) ^ (5 + 6)") +parseRPN("moon stars mud + * fire soup * ^", "(moon * (stars + mud)) ^ (fire * soup)") +parseRPN("3 4 ^ 2 9 ^ ^ 2 5 ^ ^", "((3 ^ 4) ^ 2 ^ 9) ^ 2 ^ 5") +parseRPN("5 6 * * + +", "error") +parseRPN("", "error") +parseRPN("1 4 + 5 3 + 2 3 * * *", "(1 + 4) * (5 + 3) * 2 * 3") +parseRPN("1 2 * 3 4 * *", "1 * 2 * 3 * 4") +parseRPN("1 2 + 3 4 + +", "1 + 2 + 3 + 4") +parseRPN("1 2 + 3 4 + ^", "(1 + 2) ^ (3 + 4)") +parseRPN("5 6 ^ 7 ^", "(5 ^ 6) ^ 7") +parseRPN("5 4 3 2 ^ ^ ^", "5 ^ 4 ^ 3 ^ 2") +parseRPN("1 2 3 + +", "1 + 2 + 3") +parseRPN("1 2 + 3 +", "1 + 2 + 3") +parseRPN("1 2 3 ^ ^", "1 ^ 2 ^ 3") +parseRPN("1 2 ^ 3 ^", "(1 ^ 2) ^ 3") +parseRPN("1 1 - 3 +", "1 - 1 + 3") +parseRPN("3 1 1 - +", "3 + 1 - 1") +parseRPN("1 2 3 + -", "1 - (2 + 3)") +parseRPN("4 3 2 + +", "4 + 3 + 2") +parseRPN("5 4 3 2 + + +", "5 + 4 + 3 + 2") +parseRPN("5 4 3 2 * * *", "5 * 4 * 3 * 2") +parseRPN("5 4 3 2 + - +", "5 + 4 - (3 + 2)") +parseRPN("3 4 5 * -", "3 - 4 * 5") +parseRPN("3 4 5 - *", "3 * (4 - 5)") +parseRPN("3 4 - 5 *", "(3 - 4) * 5") +parseRPN("4 2 * 1 5 - +", "4 * 2 + 1 - 5") +parseRPN("4 2 * 1 5 - 2 ^ /", "4 * 2 / (1 - 5) ^ 2") +parseRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +", "3 + 4 * 2 / (1 - 5) ^ 2 ^ 3") + +Sleep diff --git a/Task/Parsing-RPN-to-infix-conversion/M2000-Interpreter/parsing-rpn-to-infix-conversion.m2000 b/Task/Parsing-RPN-to-infix-conversion/M2000-Interpreter/parsing-rpn-to-infix-conversion.m2000 index 1dcd80a5b4..44a63690c9 100644 --- a/Task/Parsing-RPN-to-infix-conversion/M2000-Interpreter/parsing-rpn-to-infix-conversion.m2000 +++ b/Task/Parsing-RPN-to-infix-conversion/M2000-Interpreter/parsing-rpn-to-infix-conversion.m2000 @@ -51,6 +51,5 @@ Module Rpn_2_Infix { Print example1, example2, example3 Rem Print #-2, Export$ ClipBoard Export$ - } Rpn_2_Infix diff --git a/Task/Parsing-Shunting-yard-algorithm/FreeBASIC/parsing-shunting-yard-algorithm.basic b/Task/Parsing-Shunting-yard-algorithm/FreeBASIC/parsing-shunting-yard-algorithm.basic new file mode 100644 index 0000000000..ab3e646d63 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/FreeBASIC/parsing-shunting-yard-algorithm.basic @@ -0,0 +1,121 @@ +Dim Shared As String stack, queue, token +stack = "" +queue = "" +token = "#" + +Function word_(s As String, n As Integer, sep As String = " ") As String + Dim As Integer pio, cnt, posic, i + + pio = 1 : cnt = 0 : posic = 0 + For i = 1 To Len(s) + If Mid(s, i, Len(sep)) = sep Then + cnt += 1 + If cnt = n - 1 Then pio = i + Len(sep) + If cnt = n Then posic = i: Exit For + End If + Next + + If cnt < n Then Return "" + If posic = 0 Then posic = Len(s) + 1 + + Return Mid(s, pio, posic - pio) +End Function + +Sub stackPush(s As String) + stack = s & "|" & stack +End Sub + +Sub queuePush(s As String) + queue = queue & s & "|" +End Sub + +Function queuePop() As String + Dim As String result = word_(queue, 1, "|") + queue = Mid(queue, Instr(queue, "|") + 1) + Return result +End Function + +Function isOperator(op As String) As Boolean + Return Instr("+-*/^", op) <> 0 And Len(op) = 1 +End Function + +Function precedence(op As String) As Integer + If isOperator(op) Then + Return 1 + (Instr("+-*/^", op) <> 0) + (Instr("*/^", op) <> 0) + (Instr("^", op) <> 0) + End If +End Function + +Function stackPop() As String + Dim As String result = word_(stack, 1, "|") + stack = Mid(stack, Instr(stack, "|") + 1) + Return result +End Function + +Function stackPeek() As String + Return word_(stack, 1, "|") +End Function + +Function reverse(s As String) As String + Dim As String result = "" + Dim As String token = "#" + Dim As Integer i = 0 + + While token <> "" + i += 1 + token = word_(s, i, "|") + result = token & " " & result + Wend + + Return result +End Function + +Dim As String test = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" +Print !"Input:\n"; test; !"\nNo", "token", "stack", "queue" + +Dim As Integer i = 0 +Do + i += 1 + token = word_(test, i) + If token = "" Then Exit Do + Print i, token, reverse(stack), queue + + Select Case token + Case "(" + stackPush(token) + + Case ")" + While stackPeek() <> "(" + If stack = "" Then Print "Error: no matching '(' for token "; i: Sleep: End + queuePush(stackPop()) + Wend + Dim As String discard = stackPop() 'discard "(" + + Case Else + If isOperator(token) Then + Dim As String op1 = token + While isOperator(stackPeek()) + Dim As String op2 = stackPeek() + If op2 <> "^" And precedence(op1) = precedence(op2) Then + queuePush(stackPop()) + Else + Exit While + End If + Wend + stackPush(op1) + Else 'number + queuePush(token) + End If + End Select +Loop + +While stack <> "" + If stackPeek() = "(" Then Print "no matching ')'": Sleep:End + queuePush(stackPop()) +Wend + +Print !"\nOutput:" +While queue <> "" + Print queuePop(); " "; +Wend + +Sleep diff --git a/Task/Partition-an-integer-x-into-n-primes/ALGOL-68/partition-an-integer-x-into-n-primes.alg b/Task/Partition-an-integer-x-into-n-primes/ALGOL-68/partition-an-integer-x-into-n-primes.alg index fa836bfa0f..570e8de5e0 100644 --- a/Task/Partition-an-integer-x-into-n-primes/ALGOL-68/partition-an-integer-x-into-n-primes.alg +++ b/Task/Partition-an-integer-x-into-n-primes/ALGOL-68/partition-an-integer-x-into-n-primes.alg @@ -14,9 +14,9 @@ BEGIN # find the lowest n distinct primes that sum to an integer x # [ 1 : 0 ]INT no partition; # empty array - used if can't partition # # returns n partitioned into p primes or an empty array if n can't be # - # partitioned into p primes, the first prime to try is in start # - PROC partition from = ( INT n, p, start )[]INT: - IF p < 1 OR n < 2 OR start < 2 THEN # invalid parameters # + # partitioned into p primes, the first prime to try is in pstart # + PROC partition from = ( INT n, p, pstart )[]INT: + IF p < 1 OR n < 2 OR pstart < 2 THEN # invalid parameters # no partition ELIF p = 1 THEN # partition into 1 prime - n must be prime # IF NOT prime[ n ] THEN no partition ELSE n FI @@ -24,7 +24,7 @@ BEGIN # find the lowest n distinct primes that sum to an integer x # INT half n = n OVER 2; INT p1 := 0, p2 := 0; BOOL found := FALSE; - FOR p pos FROM start TO UPB prime WHILE NOT found AND p pos < half n DO + FOR p pos FROM pstart TO UPB prime WHILE NOT found AND p pos < half n DO IF prime[ p pos ] THEN p1 := p pos; p2 := n - p pos; @@ -37,7 +37,7 @@ BEGIN # find the lowest n distinct primes that sum to an integer x # INT half n = n OVER 2; INT p1 := 0; BOOL found := FALSE; - FOR p pos FROM start TO UPB prime WHILE NOT found AND p pos < half n DO + FOR p pos FROM pstart TO UPB prime WHILE NOT found AND p pos < half n DO IF prime[ p pos ] THEN p1 := p pos; []INT sub partition = partition from( n - p1, p - 1, p pos + 1 ); diff --git a/Task/Pascals-triangle-Puzzle/FutureBasic/pascals-triangle-puzzle.basic b/Task/Pascals-triangle-Puzzle/FutureBasic/pascals-triangle-puzzle.basic new file mode 100644 index 0000000000..cba9ae9ba4 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/FutureBasic/pascals-triangle-puzzle.basic @@ -0,0 +1,29 @@ +void local fn DoIt + long a, b, c, d, e, f, g, h, x = 0, y, z + do + x++ + e = x + 11 + f = 40 - e + y = f - 11 + g = y + 4 + c = f + g + a = c + 40 + b = 151 - a + d = b - c + h = d - g + z = h - 4 + until ( y == (x + z) ) + + text ,,,, NSTextAlignmentCenter + print + print 151 + print a, b + print 40, c, d + print e, f, g, h + print x, 11, y, 4, z +end fn + +window 1, @"Pascal triangle/Puzzle", (0,0,250,100), NSWindowStyleMaskTitled +fn DoIt + +HandleEvents diff --git a/Task/Pascals-triangle/Haskell/pascals-triangle-10.hs b/Task/Pascals-triangle/Haskell/pascals-triangle-10.hs new file mode 100644 index 0000000000..f67559679c --- /dev/null +++ b/Task/Pascals-triangle/Haskell/pascals-triangle-10.hs @@ -0,0 +1,5 @@ +fac = product . enumFromTo 1 + +binCoef n k = fac n `div` (fac k * fac (n - k)) + +pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred diff --git a/Task/Pascals-triangle/Haskell/pascals-triangle-11.hs b/Task/Pascals-triangle/Haskell/pascals-triangle-11.hs new file mode 100644 index 0000000000..ad74065521 --- /dev/null +++ b/Task/Pascals-triangle/Haskell/pascals-triangle-11.hs @@ -0,0 +1,11 @@ +*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10 +1 +1 1 +1 2 1 +1 3 3 1 +1 4 6 4 1 +1 5 10 10 5 1 +1 6 15 20 15 6 1 +1 7 21 35 35 21 7 1 +1 8 28 56 70 56 28 8 1 +1 9 36 84 126 126 84 36 9 1 diff --git a/Task/Pascals-triangle/Haskell/pascals-triangle-6.hs b/Task/Pascals-triangle/Haskell/pascals-triangle-6.hs index 06c3f90de0..1c4db70c8d 100644 --- a/Task/Pascals-triangle/Haskell/pascals-triangle-6.hs +++ b/Task/Pascals-triangle/Haskell/pascals-triangle-6.hs @@ -1,4 +1 @@ -pascal :: [[Integer]] -pascal = - (1 : [ 0 | _ <- head pascal]) - : [zipWith (+) (0:row) row | row <- pascal] +nextRow = (zipWith (+) . (0 :)) <*> (<> [0]) diff --git a/Task/Pascals-triangle/Haskell/pascals-triangle-7.hs b/Task/Pascals-triangle/Haskell/pascals-triangle-7.hs index 15e32d7013..988644f933 100644 --- a/Task/Pascals-triangle/Haskell/pascals-triangle-7.hs +++ b/Task/Pascals-triangle/Haskell/pascals-triangle-7.hs @@ -1,2 +1 @@ -*Pascal> take 5 <$> (take 5 $ triangle) -[[1,0,0,0,0],[1,1,0,0,0],[1,2,1,0,0],[1,3,3,1,0],[1,4,6,4,1]] +nextRow = (zipWith (+) <*> reverse) . (0 :) diff --git a/Task/Pascals-triangle/Haskell/pascals-triangle-8.hs b/Task/Pascals-triangle/Haskell/pascals-triangle-8.hs index f67559679c..06c3f90de0 100644 --- a/Task/Pascals-triangle/Haskell/pascals-triangle-8.hs +++ b/Task/Pascals-triangle/Haskell/pascals-triangle-8.hs @@ -1,5 +1,4 @@ -fac = product . enumFromTo 1 - -binCoef n k = fac n `div` (fac k * fac (n - k)) - -pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred +pascal :: [[Integer]] +pascal = + (1 : [ 0 | _ <- head pascal]) + : [zipWith (+) (0:row) row | row <- pascal] diff --git a/Task/Pascals-triangle/Haskell/pascals-triangle-9.hs b/Task/Pascals-triangle/Haskell/pascals-triangle-9.hs index ad74065521..15e32d7013 100644 --- a/Task/Pascals-triangle/Haskell/pascals-triangle-9.hs +++ b/Task/Pascals-triangle/Haskell/pascals-triangle-9.hs @@ -1,11 +1,2 @@ -*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10 -1 -1 1 -1 2 1 -1 3 3 1 -1 4 6 4 1 -1 5 10 10 5 1 -1 6 15 20 15 6 1 -1 7 21 35 35 21 7 1 -1 8 28 56 70 56 28 8 1 -1 9 36 84 126 126 84 36 9 1 +*Pascal> take 5 <$> (take 5 $ triangle) +[[1,0,0,0,0],[1,1,0,0,0],[1,2,1,0,0],[1,3,3,1,0],[1,4,6,4,1]] diff --git a/Task/Pascals-triangle/Phix/pascals-triangle.phix b/Task/Pascals-triangle/Phix/pascals-triangle.phix index c41da206dd..44105b99b3 100644 --- a/Task/Pascals-triangle/Phix/pascals-triangle.phix +++ b/Task/Pascals-triangle/Phix/pascals-triangle.phix @@ -1,14 +1,75 @@ (phixonline)--> - sequence row = {} - for m = 1 to 13 do - row = row & 1 - for n=length(row)-1 to 2 by -1 do - row[n] += row[n-1] + with javascript_semantics + sequence row, rows = {} + + function check(integer i, string name) -- helper routine + string s = join(row,fmt:="%d") + if s!=rows[i+1] then + printf(1,"%s: goes wrong on line %d\n",{name,i+1}) + return false + end if + return true + end function + + procedure sum_prior() -- First method + row = {} -- (using just one row) + for i=0 to 119 do + row &= 1 + for n=length(row)-1 to 2 by -1 do + row[n] += row[n-1] + end for + if not check(i,"sum_prior") then exit end if end for - printf(1,repeat(' ',(13-m)*2)) - for i=1 to length(row) do - printf(1," %3d",row[i]) + end procedure + + procedure algebraic() -- Second method + for i=0 to 119 do + atom c = 1 + row = {1} + for j=0 to i-1 do + -- c *= (i-j)/(j+1) -- NO: precedence differs, and eg 5*(1/5) inexact + c = c*(i-j)/(j+1) -- ..whereas (5*1)/5 is exact + row &= c + end for + if not check(i,"algebraic") then exit end if end for - puts(1,'\n') - end for + end procedure + -- Aside: error with c was self-evident and more relevant when it was an integer, + --- but I made it an atom to get past the 33/63 limits that imposed. + + procedure builtin() -- Third method + for i=0 to 119 do + row = {} + for j=0 to i do + row &= choose(i,j) + end for + if not check(i,"builtin") then exit end if + end for + end procedure + + include mpfr.e + procedure arbitrary_precision() -- Fourth method, but run first + -- perfectly accurate until you + -- run out of memory or patience. + mpz z = mpz_init() + for i=0 to 119 do + row = {} + for j=0 to i do + mpz_bin_uiui(z,i,j) + row = append(row,mpz_get_str(z)) + end for + string s = join(row) + if i<=19 then + printf(1,"%=96s\n",s) + end if + -- to check the others against: + rows = append(rows,s) + end for + printf(1,"\n") + end procedure + + arbitrary_precision() + sum_prior() + algebraic() + builtin() - function my_compare(sequence a, b) - integer c = -compare(length(a),length(b)) -- descending length - if c=0 then - c = compare(lower(a),lower(b)) -- ascending lexical within same length - end if - return c - end function - ?custom_sort(my_compare,{"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}) - - procedure subleq(sequence code) - integer ip := 0 - while ip>=0 do - integer {a,b,c} = code[ip+1..ip+3] - ip += 3 - if a=-1 then - code[b+1] = iff(platform()=JS?'?':getc(0)) - elsif b=-1 then - puts(1,code[a+1]) - else - code[b+1] -= code[a+1] - if code[b+1]<=0 then - ip := c - end if - end if - end while - end procedure +procedure subleq(sequence code) + integer ip := 0 + while ip>=0 do + integer {a,b,c} = code[ip+1..ip+3] + ip += 3 + if a=-1 then + code[b+1] = iff(platform()=JS?'?':getc(0)) + elsif b=-1 then + puts(1,code[a+1]) + else + code[b+1] -= code[a+1] + if code[b+1]<=0 then + ip := c + end if + end if + end while +end procedure - subleq({15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, - 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, - 119, 111, 114, 108, 100, 33, 10, 0}) - [ ) + + [ 0 swap witheach + ] is sum ( [ --> n ) + + [ slice sum join ] is square ( [ [ n n --> [ ) + + [ true swap + behead swap witheach + [ over = not if + [ dip not conclude ] ] + drop ] is same ( [ --> b ) + + [ [] temp put + over - 1+ times + [ dup i^ + temp gather ] + drop + temp take ] is low->high ( n n --> [ ) + + [ [] temp put + witheach + [ [] + over 0 1 square + over 1 3 square + over 3 5 square + over 5 6 square + same iff + [ nested temp gather ] + else drop ] + temp take ] is task ( [ n --> [ ) + + 1 7 low->high permutations task + witheach [ echo cr ] cr + 3 9 low->high permutations task + witheach [ echo cr ] cr + 0 9 low->high 7 arrangements task size echo diff --git a/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart b/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart index 3251bd7375..07a966aa75 100644 --- a/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart +++ b/Task/99-bottles-of-beer/Dart/99-bottles-of-beer.dart @@ -57,5 +57,3 @@ class BeerSong extends Song { return theLyrics; } } - -} diff --git a/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer.ex b/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-1.ex similarity index 100% rename from Task/99-bottles-of-beer/Elixir/99-bottles-of-beer.ex rename to Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-1.ex diff --git a/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-2.ex b/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-2.ex new file mode 100644 index 0000000000..21f101524c --- /dev/null +++ b/Task/99-bottles-of-beer/Elixir/99-bottles-of-beer-2.ex @@ -0,0 +1,36 @@ +last = [ + """ + 2 bottles of beer on the wall + 2 bottles of beer + Take one down, pass it around + 1 bottle of beer on the wall + """, + """ + 1 bottle of beer on the wall + 1 bottle of beer + Take one down, pass it around + No bottles of beer on the wall + """, + """ + No more bottles of beer on the wall + No more bottles of beer + Go to the store and buy some more + 99 bottles of beer on the wall + """ +] + +skeleton = fn n -> + """ + #{n} bottles of beer on the wall + #{n} bottles of beer + Take one down, pass it around + #{n - 1} bottles of beer on the wall + """ +end + +99..3 +|> Stream.map(skeleton) +|> Stream.concat(last) +|> Enum.intersperse("\n") +|> IO.iodata_to_binary() +|> IO.puts() diff --git a/Task/99-bottles-of-beer/Java/99-bottles-of-beer-5.java b/Task/99-bottles-of-beer/Java/99-bottles-of-beer-5.java new file mode 100644 index 0000000000..394eb68af8 --- /dev/null +++ b/Task/99-bottles-of-beer/Java/99-bottles-of-beer-5.java @@ -0,0 +1,76 @@ +import java.util.Scanner; + +public class NineNineBottles { + static int bottlesOfBeer = 99; + static boolean hasBeer = true; + static Scanner keyboard = new Scanner(System.in); + + public static void main(String[] args) { + beerCheck(); + keyboard.close(); + } + + private static void beerCheck() { + if(hasBeer) { + party(bottlesOfBeer); + } + + if(!hasBeer) { + System.out.println("Your ran out of beer. Would you like to go to the store?: "); + String blurryVision, fallingOver, youAreDrunk; + youAreDrunk = keyboard.nextLine(); + fallingOver = "RUHFO" + youAreDrunk.toLowerCase() + "RUHFOISafhur"; + blurryVision = fallingOver.split("[a-zA-Z]", 2).toString(); + if(blurryVision.contains("y")) + blurryVision = blurryVision.substring(0, 1).toUpperCase(); + System.out.println("You entered: " + blurryVision.toString() + fallingOver); + System.out.println("Did you mean yes?: "); + blurryVision = keyboard.nextLine(); + if(blurryVision.contains("y") || blurryVision.contains("Y") || blurryVision.contains("8") + || blurryVision.contains("2") || blurryVision.equalsIgnoreCase(youAreDrunk)) + {String beRECcheeck = blurryVision.toLowerCase(); + if(beRECcheeck.equals("y")) { + goToStore(); + beerCheck(); + } + } + } + } + + private static void party(int bottlesOfBeer) { + while(bottlesOfBeer > 1) { + putOnWall(bottlesOfBeer); + bottlesOfBeer = takeOneDown(bottlesOfBeer); + } + putLastOnWall(bottlesOfBeer); + } + + private static void putOnWall(int bottlesOfBeer) { + System.out.printf("%d bottles of beer on the wall%n", bottlesOfBeer); + + } + + private static int takeOneDown(int bottlesOfBeer) { + System.out.printf("%d bottles of beer%n", bottlesOfBeer); + System.out.println("Take one down, pass it around"); + bottlesOfBeer--; + putOnWall(bottlesOfBeer); + System.out.println(); + return bottlesOfBeer; + + } + + private static void putLastOnWall(int bottleOfBeer) { + System.out.printf("%d bottle of beer on the wall%n", bottleOfBeer); + System.out.printf("%d bottle of beer%n", bottleOfBeer); + System.out.println("Take it down, pass it around"); + bottleOfBeer--; + System.out.println("No more bottles of beer on the wall."); + hasBeer = false; + } + + private static void goToStore() { + bottlesOfBeer = 99; + hasBeer = true; + } +} diff --git a/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt b/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt index ccd2ec6780..fcac676e27 100644 --- a/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt +++ b/Task/99-bottles-of-beer/Nutt/99-bottles-of-beer.nutt @@ -1,8 +1,8 @@ -module main imports native.io.output.say +module main +import $native 'io' : output#sayn -for i|->{1,2..99;<|>) do - say(""+i+" bottles of beer on the wall, "+i+" bottles of beer") - say("Take one down and pass it around, "+(i-1)+" bottles of beer on the wall.") -done - -end +funct main () : () = + [1, 2; 99]#reverse#each { + sayn "\(it) bottles of beer on the wall, \(it) bottles of beer"; + sayn "Take one down and pass it around, \(it# - 1) bottles of beer on the wall." + } diff --git a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys index 2ad5b109ca..5dc37d24c9 100644 --- a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys +++ b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer-1.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(number=99): each num (number .. 1): diff --git a/Task/A+B/Guile/a+b.guile b/Task/A+B/Guile/a+b.guile new file mode 100644 index 0000000000..d3ef4f223d --- /dev/null +++ b/Task/A+B/Guile/a+b.guile @@ -0,0 +1,3 @@ +;;;Actually, the solution is same as that of many other Lisp dialects here +(+ (read) (read)) +;;Yes, it is neat but not strong, error prone actually. Other than this walkaround, if you dislike fetching a line in string format then parse the chars one by one by hand or byte by byte from stdin, you can use one read and do the work, with the price of typing (1 2) instead of 1 2 at the prompt since read would treat the input as a symbolic expression. So.,.there is sadly no easy way like scanf and %d %d in c unless one is willing to type ()s! diff --git a/Task/A+B/LOLCODE/a+b.lol b/Task/A+B/LOLCODE/a+b.lol new file mode 100644 index 0000000000..711b24849b --- /dev/null +++ b/Task/A+B/LOLCODE/a+b.lol @@ -0,0 +1,9 @@ +HAI 1.2 + I HAS A VAR1 ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE + I HAS A VAR2 ITZ A YARN BTW DECLARE A VARIABLE FOR LATER USE + VISIBLE "NUMBAH 1?" + GIMMEH VAR1 BTW GET INPUT (NUMBER) INTO VARIABLE + VISIBLE "NUMBAH 2?" + GIMMEH VAR2 BTW GET INPUT (NUMBER) INTO VARIABLE + VISIBLE SUM OF VAR1 AN VAR2 +KTHXBYE diff --git a/Task/A+B/Nutt/a+b.nutt b/Task/A+B/Nutt/a+b.nutt index 50a609c5d5..5b0625667e 100644 --- a/Task/A+B/Nutt/a+b.nutt +++ b/Task/A+B/Nutt/a+b.nutt @@ -1,7 +1,8 @@ module main -imports native.io{input.hear,output.say} +import $native 'io' [input#hear output#sayn] -vals a=hear(Int),b=hear(Int) -say(a+b) - -end +funct main () : () = + val read_int = {(hear ())#to_int#fold {0} {it}}; + val a = read_int (); + val b = read_int (); + sayn (a# + b) diff --git a/Task/A+B/Plain-English/a+b.plain b/Task/A+B/Plain-English/a+b.plain index 01ffffe01a..4187b423eb 100644 --- a/Task/A+B/Plain-English/a+b.plain +++ b/Task/A+B/Plain-English/a+b.plain @@ -1,21 +1,42 @@ To run: Start up. - Read a number from the console. - Read another number from the console. - Output the sum of the number and the other number. - Wait for the escape key. + Set up the console. + Write "Type the first number: " to Stdout. + Read a buffer from stdin. + Trim the buffer. + If the buffer is not any integer, + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; + Shut down; + Exit. + Write "Type the second number: " to Stdout. + Read a second buffer from stdin. + Trim the second buffer. + If the second buffer is not any integer, + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; + Shut down; + Exit. + Convert the buffer to a number. + Convert the second buffer to a second number. + Output the sum of the number and the second number. Shut down. To output the sum of a number and another number: If the number is not valid, - Write "Invalid input" to the console; + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; Exit. If the other number is not valid, - Write "Invalid input" to the console; + Write "Invalid input. Aborting Operation." + then the CRLF string to StdOut; Exit. - Write the number plus the other number then " is the sum." to the console. + Add the other number to the number. + Convert the number to a string called result. + Write "The sum is " then the result + then the CRLF string to StdOut. To decide if a number is valid: - If the number is not greater than or equal to -1000, say no. - If the number is not less than or equal to 1000, say no. + If the number is less than -1000, say no. + If the number is greater than 1000, say no. Say yes. diff --git a/Task/A+B/ZED/a+b.zed b/Task/A+B/ZED/a+b.zed index 6c28d79b86..b3605ef199 100644 --- a/Task/A+B/ZED/a+b.zed +++ b/Task/A+B/ZED/a+b.zed @@ -1,14 +1,14 @@ (A+B) -comment: +READ AND ADD #true (+) (read) (read) (+) one two -comment: +========= #true (003) "+" one two (read) -comment: +========= #true (001) "read" diff --git a/Task/A+B/Zig/a+b.zig b/Task/A+B/Zig/a+b.zig index fc0d17b9f6..378622f54f 100644 --- a/Task/A+B/Zig/a+b.zig +++ b/Task/A+B/Zig/a+b.zig @@ -1,25 +1,18 @@ const std = @import("std"); -const stdout = std.io.getStdOut().writer(); - -const Input = enum { a, b }; pub fn main() !void { var buf: [1024]u8 = undefined; const reader = std.io.getStdIn().reader(); + const stdout = std.io.getStdOut().writer(); + try stdout.writeAll("Enter two integers separated by a space: "); const input = try reader.readUntilDelimiter(&buf, '\n'); - const values = std.mem.trim(u8, input, "\x20"); + const text = std.mem.trimRight(u8, input, "\r\n"); - var count: usize = 0; - var split: usize = 0; - for (values, 0..) |c, i| { - if (!std.ascii.isDigit(c)) { - count += 1; - if (count == 1) split = i; - } - } + var it = std.mem.tokenizeScalar(u8, text, ' '); + + const a = try std.fmt.parseInt(i64, it.next().?, 10); + const b = try std.fmt.parseInt(i64, it.next().?, 10); - const a = try std.fmt.parseInt(u64, values[0..split], 10); - const b = try std.fmt.parseInt(u64, values[split + count ..], 10); try stdout.print("{d}\n", .{a + b}); } diff --git a/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic b/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic new file mode 100644 index 0000000000..c94e8f7494 --- /dev/null +++ b/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic @@ -0,0 +1,102 @@ +// AKS Test for Primes task +// https://rosettacode.org/wiki/AKS_test_for_primes +// Translated from Yabasic to FutureBASIC + + +#build ShowMoreWarnings NO + +begin globals + sInt64 c(100) + //double n +end globals + +local fn coef(nx as short) + // out-by-1, ie coef(1)==^0, coef(2)==^1, coef(3)==^2 etc. + c(nx) = 1 + short i + for i = nx-1 to 2 step -1 + c(i) = c(i) + c(i-1) + next +end fn + +local fn is_prime(nx as short) as boolean + short i + bool result = _false + fn coef(nx+1) // (I said it was out-by-1) + for i = 2 to nx-1 // (technically "to n" is more correct) + if int(c(i)/nx) <> c(i)/nx + return _false + end if + next + + result = _true +end fn = result + +local fn show(nx as short) + // (As per coef, this is (working) out-by-1) + + double ci + str255 cix + short i + + for i = nx to 1 step -1 + ci = c(i) + if ci = 1 + if (nx-i) mod 2 = 0 + if i = 1 + if nx = 1 + cix = " 1" + else + cix = "+1" + end if + else + cix = "" + end if + else + cix = "-1" + end if + else + if (nx-i) mod 2 = 0 + cix = "+" + str$(ci) + else + cix = "-" + str$(ci) + end if + end if + + if i = 1 // ie ^0 + print cix; + else + if i = 2 then print cix, "x"; // ie ^1 + if i <> 2 then print cix, "x^", i-1; + end if + + next i +end fn + +local fn AKS_test_for_primes + short nx + + for nx = 1 to 10 // (0 to 9 really) + fn coef(nx) + print "(x-1)^" + str$(nx-1) + " = "; + fn show(nx) + print + next + + print + print "primes (<=53): "; + short n + c(2) = 1 // (this manages "", which is all that call did anyway...) + for n = 2 to 53 + if fn is_prime(n) + print " ", n; + end if + next + print +end fn + +window 1,@"AKS test for Primes",fn CGRectMake(0, 0, 850, 200) + +fn AKS_test_for_primes + +handleevents diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx index 79dc451c4e..77862e7896 100644 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx @@ -1,12 +1,14 @@ -parse version version; say version -say 'AKS-test for Primes'; say +include Settings + +say version +say 'AKS-test for primes'; say arg p if p = '' then p = 10 numeric digits Max(10,Abs(p)%3) call Combis p call Polynomials p -call ShowPrimes p +call Showprimes p exit Combis: @@ -17,7 +19,7 @@ if p > 0 then say 'Combinations up to' p'...' else say 'Combinations for' Abs(p)'...' -say Combinations(p) 'Combinations generated' +say Combinations(p) 'combinations generated' say Format(Time('e'),,3) 'seconds' say return @@ -33,9 +35,9 @@ else b = 0 p = Abs(p); prim. = 0; n = 0 do i = b to p - a = Ppower('1 -1',i) + a = Ppow('1 -1',i) if i < 11 then - say '(x-1)^'i '=' Parray2formula() + say '(x-1)^'i '=' Plst2form(Parr2lst()) s = 1 do j = 2 to poly.0-1 a = poly.coef.j @@ -56,7 +58,7 @@ say Format(Time('e'),,3) 'seconds' say return -ShowPrimes: +Showprimes: procedure expose prim. arg p call Time('r') @@ -64,9 +66,9 @@ say 'Primes...' if p < 0 then do p = Abs(p) if prim.0 > 0 then - say p 'is Prime' + say p 'is prime' else - say p 'is not Prime' + say p 'is not prime' end else do do i = 1 to prim.0 @@ -80,124 +82,8 @@ say Format(Time('e'),,3) 'seconds' say return -Combinations: -/* Combinations */ -procedure expose comb. -arg xx -/* Validate */ -if \ Whole(xx) then say abend -/* Recurring definition */ -comb. = 1 -if xx < 0 then do - xx = -xx; m = xx%2; a = 1 - do i = 1 to m - a = a*(xx-i+1)/i; comb.xx.i = a - end - do i = m+1 to xx-1 - j = xx-i; comb.xx.i = comb.xx.j - end - return xx+1 -end -else do - do i = 1 to xx - i1 = i-1 - do j = 1 to i1 - j1 = j-1; comb.i.j = comb.i1.j1+comb.i1.j - end - end - return (xx*xx+3*xx+2)/2 -end - -Ppower: -/* Exponentiation */ -procedure expose poly. comb. work. -arg x,y -/* Validate */ -if x = '' then say abend -if \ Whole(y) then say abend -if y < 0 then say abend -/* Exponentiate */ -numeric digits Digits()+2 -wx = Words(x); wm = wx*y-y+1 -poly. = 0; poly.0 = wm -select - when wx = 1 then -/* Power of a number */ - poly.coef.1 = x**y - when wx = 2 then do -/* Newton's binomial */ - a = Word(x,1); b = Word(x,2) - do i = 1 to wm - j = y-i+1; k = i-1 - poly.coef.i = comb.y.k*a**j*b**k - end - end - otherwise do -/* Repeated multiplication */ - do i = 1 to wx - poly.coef.1.i = Word(x,i) - poly.coef.2.i = poly.coef.1.i - end - wy = wx - do i = 2 to y - work. = 0 - do j = 1 to wx - do k = 1 to wy - l = j+k-1; work.coef.l = work.coef.l+poly.coef.1.j*poly.coef.2.k - end - end - if i = y then - leave i - wx = wx+wy-1 - do j = 1 to wx - poly.coef.1.j = work.coef.j - end - end - do i = 1 to wm - poly.coef.i = work.coef.i - end - end -end -numeric digits Digits()-2 -/* Normalize coefs */ -call Pnormalize -return wm - -Parray2formula: -/* Array -> Formula */ -procedure expose poly. -/* Generate formula */ -y = ''; wm = poly.0 -do i = 1 to wm - a = poly.coef.i - if a <> 0 then do - select - when a < 0 then - s = '-' - when i > 1 then - s = '+' - otherwise - s = '' - end - a = Abs(a); e = wm-i - if a = 1 & e > 0 then - a = '' - select - when e > 1 then - b = 'x^'e - when e = 1 then - b = 'x' - otherwise - b = '' - end - y = y||s||a||b - end -end -if y = '' then - y = 0 -return Strip(y) - include Functions include Numbers include Polynomial include Sequences +include Abend diff --git a/Task/ASCII-art-diagram-converter/Chipmunk-Basic/ascii-art-diagram-converter.basic b/Task/ASCII-art-diagram-converter/Chipmunk-Basic/ascii-art-diagram-converter.basic new file mode 100644 index 0000000000..54092c2681 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/Chipmunk-Basic/ascii-art-diagram-converter.basic @@ -0,0 +1,84 @@ +100 cls +110 type tableentry +120 nombre as string *8 +130 bits as integer +140 startpos as integer +150 length as integer +160 end type +170 dim hexmap$(15) +180 hexmap$(0) = "0000" : hexmap$(1) = "0001" : hexmap$(2) = "0010" : hexmap$(3) = "0011" +190 hexmap$(4) = "0100" : hexmap$(5) = "0101" : hexmap$(6) = "0110" : hexmap$(7) = "0111" +200 hexmap$(8) = "1000" : hexmap$(9) = "1001" : hexmap$(10) = "1010" : hexmap$(11) = "1011" +210 hexmap$(12) = "1100" : hexmap$(13) = "1101" : hexmap$(14) = "1110" : hexmap$(15) = "1111" +220 dim fields(12) as tableentry +230 header$ = " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"+chr$(10) +240 header$ = header$+" | ID |"+chr$(10) +250 header$ = header$+" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"+chr$(10) +260 header$ = header$+" |QR| Opcode |AA|TC|RD|RA| Z | RCODE |"+chr$(10) +270 header$ = header$+" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"+chr$(10) +280 header$ = header$+" | QDCOUNT |"+chr$(10) +290 header$ = header$+" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"+chr$(10) +300 header$ = header$+" | ANCOUNT |"+chr$(10) +310 header$ = header$+" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"+chr$(10) +320 header$ = header$+" | NSCOUNT |"+chr$(10) +330 header$ = header$+" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"+chr$(10) +340 header$ = header$+" | ARCOUNT |"+chr$(10) +350 header$ = header$+" +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" +360 fields(0).nombre = " ID " : fields(0).bits = 16 : fields(0).startpos = 0 : fields(0).length = 16 +370 fields(1).nombre = " QR " : fields(1).bits = 1 : fields(1).startpos = 16 : fields(1).length = 1 +380 fields(2).nombre = " Opcode " : fields(2).bits = 4 : fields(2).startpos = 17 : fields(2).length = 4 +390 fields(3).nombre = " AA " : fields(3).bits = 1 : fields(3).startpos = 21 : fields(3).length = 1 +400 fields(4).nombre = " TC " : fields(4).bits = 1 : fields(4).startpos = 22 : fields(4).length = 1 +410 fields(5).nombre = " RD " : fields(5).bits = 1 : fields(5).startpos = 23 : fields(5).length = 1 +420 fields(6).nombre = " RA " : fields(6).bits = 1 : fields(6).startpos = 24 : fields(6).length = 1 +430 fields(7).nombre = " Z " : fields(7).bits = 3 : fields(7).startpos = 25 : fields(7).length = 3 +440 fields(8).nombre = " RCODE " : fields(8).bits = 4 : fields(8).startpos = 28 : fields(8).length = 4 +450 fields(9).nombre = "QDCOUNT " : fields(9).bits = 16 : fields(9).startpos = 32 : fields(9).length = 16 +460 fields(10).nombre = "ANCOUNT " : fields(10).bits = 16 : fields(10).startpos = 48 : fields(10).length = 16 +470 fields(11).nombre = "NSCOUNT " : fields(11).bits = 16 : fields(11).startpos = 64 : fields(11).length = 16 +480 fields(12).nombre = "ARCOUNT " : fields(12).bits = 16 : fields(12).startpos = 80 : fields(12).length = 16 +490 hexstr$ = "78477bbf5496e12e1bf169a4" +500 binstr$ = hextobinary$(hexstr$) +510 print "RFC 1035 message diagram header:" +520 print header$ +530 print +540 print " Decoded:" +550 print " Name Bits Start End" +560 print " ======= ==== ===== ===" +570 for i = 0 to 12 +580 print " ";fields(i).nombre;" "; +581 print using "####";fields(i).bits;" "; +600 print using "#####";fields(i).startpos;" "; +601 print using "###";fields(i).startpos+fields(i).length-1 +610 next i +620 print +630 print " Test string in hex:" +640 print " ";hexstr$ +650 print +660 print " Test string in binary:" +670 print " ";binstr$ +680 print +690 print " Unpacked:" +700 print " Name Size Bit Pattern" +710 print " ======= ==== ================" +720 for i = 0 to 12 +730 bitpattern$ = mid$(binstr$,fields(i).startpos+1,fields(i).length) +740 bitpattern$ = left$(bitpattern$+" ",16) +760 print " ";fields(i).nombre;" "; +770 print using "####";fields(i).bits;" "; +780 print bitpattern$ +790 next i +800 end +810 sub hextobinary$(hexstring$) +820 result$ = "" +830 for i = 1 to len(hexstring$) +840 hexdigit$ = ucase$(mid$(hexstring$,i,1)) +850 if hexdigit$ >= "0" and hexdigit$ <= "9" then +860 idx = val(hexdigit$) +870 else +880 idx = asc(hexdigit$)-asc("A")+10 +890 endif +900 if idx >= 0 and idx <= 15 then result$ = result$+hexmap$(idx) +910 next i +920 hextobinary$ = result$ +930 end sub diff --git a/Task/ASCII-art-diagram-converter/FreeBASIC/ascii-art-diagram-converter.basic b/Task/ASCII-art-diagram-converter/FreeBASIC/ascii-art-diagram-converter.basic new file mode 100644 index 0000000000..6501672dfa --- /dev/null +++ b/Task/ASCII-art-diagram-converter/FreeBASIC/ascii-art-diagram-converter.basic @@ -0,0 +1,92 @@ +Type TableEntry + nombre As String * 8 + bits As Integer + startPos As Integer + length As Integer +End Type + +Function HexToBinary(hexString As String) As String + Dim As Integer i, idx + Dim As String hexDigit, result = "" + + ' Create hex to binary mapping + Dim As String hexMap(15) = { _ + "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", _ + "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" } + + For i = 0 To Len(hexString) - 1 + hexDigit = Ucase(Mid(hexString, i + 1, 1)) + ' Convert hex digit to index + idx = Iif(hexDigit >= "0" And hexDigit <= "9", Val(hexDigit), Asc(hexDigit) - Asc("A") + 10) + If idx >= 0 And idx <= 15 Then result &= hexMap(idx) + Next + Return result +End Function + +Sub ParseASCIIArt() + Dim As String header = _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" & Chr(10) & _ + " | ID |" & Chr(10) & _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" & Chr(10) & _ + " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |" & Chr(10) & _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" & Chr(10) & _ + " | QDCOUNT |" & Chr(10) & _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" & Chr(10) & _ + " | ANCOUNT |" & Chr(10) & _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" & Chr(10) & _ + " | NSCOUNT |" & Chr(10) & _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" & Chr(10) & _ + " | ARCOUNT |" & Chr(10) & _ + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + + Dim As TableEntry fields(12) = { _ + (" ID ", 16, 0, 16), _ + (" QR ", 1, 16, 1), _ + (" Opcode ", 4, 17, 4), _ + (" AA ", 1, 21, 1), _ + (" TC ", 1, 22, 1), _ + (" RD ", 1, 23, 1), _ + (" RA ", 1, 24, 1), _ + (" Z ", 3, 25, 3), _ + (" RCODE ", 4, 28, 4), _ + ("QDCOUNT ", 16, 32, 16), _ + ("ANCOUNT ", 16, 48, 16), _ + ("NSCOUNT ", 16, 64, 16), _ + ("ARCOUNT ", 16, 80, 16) } + + Dim As String hexStr = "78477bbf5496e12e1bf169a4" + Dim As String binStr = HexToBinary(hexStr) + Dim As Integer i + + ' Print header + Print "RFC 1035 message diagram header:" + Print header + + ' Print decoded fields + Print !"\n Decoded:" + Print !" Name Bits Start End\n ======= ==== ===== ===" + + For i = 0 To 12 + Print Using " \ \ #### ##### ###"; _ + fields(i).nombre; _ + fields(i).bits; _ + fields(i).startPos; _ + fields(i).startPos + fields(i).length - 1 + Next + + Print !"\n Test string in hex:\n " & hexStr + Print !"\n Test string in binary:\n " & binStr + Print !"\n Unpacked:" + Print !" Name Size Bit Pattern\n ======= ==== ===============" + + For i = 0 To 12 + Print Using " \ \ #### \ \"; _ + fields(i).nombre; _ + fields(i).bits; _ + Left(Mid(binStr, fields(i).startPos + 1, fields(i).length) + Space(16), 16) + Next +End Sub + +ParseASCIIArt() + +Sleep diff --git a/Task/ASCII-art-diagram-converter/PureBasic/ascii-art-diagram-converter.basic b/Task/ASCII-art-diagram-converter/PureBasic/ascii-art-diagram-converter.basic new file mode 100644 index 0000000000..b682c629b1 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/PureBasic/ascii-art-diagram-converter.basic @@ -0,0 +1,94 @@ +Structure TableEntry + nombre.s + bits.i + startPos.i + length.i +EndStructure + +Procedure.s HexToBinary(hexString.s) + Dim hexMap.s(15) + hexMap(0) = "0000" : hexMap(1) = "0001" : hexMap(2) = "0010" : hexMap(3) = "0011" + hexMap(4) = "0100" : hexMap(5) = "0101" : hexMap(6) = "0110" : hexMap(7) = "0111" + hexMap(8) = "1000" : hexMap(9) = "1001" : hexMap(10) = "1010" : hexMap(11) = "1011" + hexMap(12) = "1100" : hexMap(13) = "1101" : hexMap(14) = "1110" : hexMap(15) = "1111" + + Protected.s result = "", hexDigit + Protected.i idx + + For i = 0 To Len(hexString) - 1 + hexDigit = UCase(Mid(hexString, i + 1, 1)) + If hexDigit >= "0" And hexDigit <= "9" + idx = Val(hexDigit) + Else + idx = Asc(hexDigit) - Asc("A") + 10 + EndIf + If idx >= 0 And idx <= 15 + result + hexMap(idx) + EndIf + Next + + ProcedureReturn result +EndProcedure + +Procedure ParseASCIIArt() + Protected header.s = " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + #CRLF$ + + " | ID |" + #CRLF$ + + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + #CRLF$ + + " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |" + #CRLF$ + + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + #CRLF$ + + " | QDCOUNT |" + #CRLF$ + + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + #CRLF$ + + " | ANCOUNT |" + #CRLF$ + + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + #CRLF$ + + " | NSCOUNT |" + #CRLF$ + + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + #CRLF$ + + " | ARCOUNT |" + #CRLF$ + + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + + Dim fields.TableEntry(12) + fields(0)\nombre = " ID " : fields(0)\bits = 16 : fields(0)\startPos = 0 : fields(0)\length = 16 + fields(1)\nombre = " QR " : fields(1)\bits = 1 : fields(1)\startPos = 16 : fields(1)\length = 1 + fields(2)\nombre = " Opcode " : fields(2)\bits = 4 : fields(2)\startPos = 17 : fields(2)\length = 4 + fields(3)\nombre = " AA " : fields(3)\bits = 1 : fields(3)\startPos = 21 : fields(3)\length = 1 + fields(4)\nombre = " TC " : fields(4)\bits = 1 : fields(4)\startPos = 22 : fields(4)\length = 1 + fields(5)\nombre = " RD " : fields(5)\bits = 1 : fields(5)\startPos = 23 : fields(5)\length = 1 + fields(6)\nombre = " RA " : fields(6)\bits = 1 : fields(6)\startPos = 24 : fields(6)\length = 1 + fields(7)\nombre = " Z " : fields(7)\bits = 3 : fields(7)\startPos = 25 : fields(7)\length = 3 + fields(8)\nombre = " RCODE " : fields(8)\bits = 4 : fields(8)\startPos = 28 : fields(8)\length = 4 + fields(9)\nombre = "QDCOUNT " : fields(9)\bits = 16 : fields(9)\startPos = 32 : fields(9)\length = 16 + fields(10)\nombre = "ANCOUNT " : fields(10)\bits = 16 : fields(10)\startPos = 48 : fields(10)\length = 16 + fields(11)\nombre = "NSCOUNT " : fields(11)\bits = 16 : fields(11)\startPos = 64 : fields(11)\length = 16 + fields(12)\nombre = "ARCOUNT " : fields(12)\bits = 16 : fields(12)\startPos = 80 : fields(12)\length = 16 + + Protected hexStr.s = "78477bbf5496e12e1bf169a4" + Protected binStr.s = HexToBinary(hexStr) + + PrintN("RFC 1035 message diagram header:") + PrintN(header) + PrintN(#CRLF$ + " Decoded:") + PrintN(" Name Bits Start End" + #CRLF$ + " ======= ==== ===== ===") + + For i = 0 To 12 + PrintN(RSet(fields(i)\nombre, 9) + " " + RSet(Str(fields(i)\bits), 4) + " " + + RSet(Str(fields(i)\startPos), 6) + " " + RSet(Str(fields(i)\startPos + fields(i)\length - 1), 4)) + Next + + PrintN(#CRLF$ + " Test string in hex:") + PrintN(" " + hexStr) + PrintN(#CRLF$ + " Test string in binary:") + PrintN(" " + binStr) + PrintN(#CRLF$ + " Unpacked:") + PrintN(" Name Size Bit Pattern" + #CRLF$ + " ======= ==== ================") + + For i = 0 To 12 + bitPattern.s = Mid(binStr, fields(i)\startPos + 1, fields(i)\length) + bitPattern = Left(bitPattern + Space(16), 16) + PrintN(RSet(fields(i)\nombre, 9) + " " + RSet(Str(fields(i)\bits), 4) + " " + bitPattern) + Next +EndProcedure + +OpenConsole() + +ParseASCIIArt() +PrintN(#CRLF$ + "Press ENTER to exit"): Input() +CloseConsole() diff --git a/Task/ASCII-art-diagram-converter/QBasic/ascii-art-diagram-converter.basic b/Task/ASCII-art-diagram-converter/QBasic/ascii-art-diagram-converter.basic new file mode 100644 index 0000000000..a5c32ea3b5 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/QBasic/ascii-art-diagram-converter.basic @@ -0,0 +1,95 @@ +DECLARE SUB ParseASCIIArt () +DECLARE FUNCTION HexToBinary$ (hexString AS STRING) + +TYPE TableEntry + nombre AS STRING * 8 + bits AS INTEGER + startPos AS INTEGER + length AS INTEGER +END TYPE + +ParseASCIIArt +END + +FUNCTION HexToBinary$ (hexString AS STRING) + DIM hexMap(15) AS STRING + hexMap(0) = "0000": hexMap(1) = "0001": hexMap(2) = "0010": hexMap(3) = "0011" + hexMap(4) = "0100": hexMap(5) = "0101": hexMap(6) = "0110": hexMap(7) = "0111" + hexMap(8) = "1000": hexMap(9) = "1001": hexMap(10) = "1010": hexMap(11) = "1011" + hexMap(12) = "1100": hexMap(13) = "1101": hexMap(14) = "1110": hexMap(15) = "1111" + + result$ = "" + FOR i = 0 TO LEN(hexString) - 1 + hexDigit$ = UCASE$(MID$(hexString, i + 1, 1)) + IF hexDigit$ >= "0" AND hexDigit$ <= "9" THEN + idx = VAL(hexDigit$) + ELSE + idx = ASC(hexDigit$) - ASC("A") + 10 + END IF + IF idx >= 0 AND idx <= 15 THEN result$ = result$ + hexMap(idx) + NEXT + HexToBinary$ = result$ +END FUNCTION + +SUB ParseASCIIArt + DIM header AS STRING + header = " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + CHR$(10) + header = header + " | ID |" + CHR$(10) + header = header + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + CHR$(10) + header = header + " |QR| Opcode |AA|TC|RD|RA| Z | RCODE |" + CHR$(10) + header = header + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + CHR$(10) + header = header + " | QDCOUNT |" + CHR$(10) + header = header + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + CHR$(10) + header = header + " | ANCOUNT |" + CHR$(10) + header = header + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + CHR$(10) + header = header + " | NSCOUNT |" + CHR$(10) + header = header + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + CHR$(10) + header = header + " | ARCOUNT |" + CHR$(10) + header = header + " +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" + + DIM fields(12) AS TableEntry + fields(0).nombre = " ID ": fields(0).bits = 16: fields(0).startPos = 0: fields(0).length = 16 + fields(1).nombre = " QR ": fields(1).bits = 1: fields(1).startPos = 16: fields(1).length = 1 + fields(2).nombre = " Opcode ": fields(2).bits = 4: fields(2).startPos = 17: fields(2).length = 4 + fields(3).nombre = " AA ": fields(3).bits = 1: fields(3).startPos = 21: fields(3).length = 1 + fields(4).nombre = " TC ": fields(4).bits = 1: fields(4).startPos = 22: fields(4).length = 1 + fields(5).nombre = " RD ": fields(5).bits = 1: fields(5).startPos = 23: fields(5).length = 1 + fields(6).nombre = " RA ": fields(6).bits = 1: fields(6).startPos = 24: fields(6).length = 1 + fields(7).nombre = " Z ": fields(7).bits = 3: fields(7).startPos = 25: fields(7).length = 3 + fields(8).nombre = " RCODE ": fields(8).bits = 4: fields(8).startPos = 28: fields(8).length = 4 + fields(9).nombre = "QDCOUNT ": fields(9).bits = 16: fields(9).startPos = 32: fields(9).length = 16 + fields(10).nombre = "ANCOUNT ": fields(10).bits = 16: fields(10).startPos = 48: fields(10).length = 16 + fields(11).nombre = "NSCOUNT ": fields(11).bits = 16: fields(11).startPos = 64: fields(11).length = 16 + fields(12).nombre = "ARCOUNT ": fields(12).bits = 16: fields(12).startPos = 80: fields(12).length = 16 + + hexStr$ = "78477bbf5496e12e1bf169a4" + binStr$ = HexToBinary$(hexStr$) + + PRINT "RFC 1035 message diagram header:" + PRINT header + PRINT + PRINT " Decoded:" + PRINT " Name Bits Start End" + PRINT " ======= ==== ===== ===" + + FOR i = 0 TO 12 + PRINT USING " \ \ #### ##### ###"; fields(i).nombre; fields(i).bits; fields(i).startPos; fields(i).startPos + fields(i).length - 1 + NEXT + + PRINT + PRINT " Test string in hex:" + PRINT " "; hexStr$ + PRINT + PRINT " Test string in binary:" + PRINT " "; binStr$ + PRINT + PRINT " Unpacked:" + PRINT " Name Size Bit Pattern" + PRINT " ======= ==== ===============" + + FOR i = 0 TO 12 + bitPattern$ = MID$(binStr$, fields(i).startPos + 1, fields(i).length) + bitPattern$ = LEFT$(bitPattern$ + SPACE$(16), 16) + PRINT USING " \ \ #### \ \"; fields(i).nombre; fields(i).bits; bitPattern$ + NEXT +END SUB diff --git a/Task/Abbreviations-automatic/Crystal/abbreviations-automatic.cr b/Task/Abbreviations-automatic/Crystal/abbreviations-automatic.cr new file mode 100644 index 0000000000..fb78aea856 --- /dev/null +++ b/Task/Abbreviations-automatic/Crystal/abbreviations-automatic.cr @@ -0,0 +1,12 @@ +def auto_abbreviate (string) + words = string.split + return nil unless words.present? + (1..words.max_of(&.size)).each do |n| + return n if words.map(&.[0, n]).to_set.size == words.size + end + "∞" +end + +File.read_lines("weekdays.txt").each_with_index do |line, i| + puts "#{i+1}) #{auto_abbreviate(line)} #{line}" +end diff --git a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000 b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000 new file mode 100644 index 0000000000..e710dbc3c6 --- /dev/null +++ b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000 @@ -0,0 +1,71 @@ +Module Abbreviations_simple { + commands=list + a$="add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + a$+="compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + a$+="3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + a$+="forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + a$+="locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + a$+="msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + a$+="refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + a$+="2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1" + gosub cleanspaces + gosub makelist + if not empty then gosub processstack + a$="riG rePEAT copies put mo rest types fup. 6 poweRin" + Print a$ + gosub cleanspaces + gosub findresult + a$="riG macro copies macr" + Print a$ + gosub cleanspaces + gosub findresult + End +processstack: + Read many, word$ + if many>0 and many"" then data 0, ucase$(w$):w$="" + end if + next + return +findresult: + dim a$() + a$()=piece$(ucase$(a$), " ") + flush + for i=0 to len(a$())-1 + if exist(commands, a$(i)) then + Data eval$(commands) + else + Data "*error*" + end if + next + Print Array([])#str$(" ") + Return +} +Abbreviations_simple diff --git a/Task/Abbreviations-simple/NewLISP/abbreviations-simple.l b/Task/Abbreviations-simple/NewLISP/abbreviations-simple.l index 2f137ce9e2..67b0ad7999 100644 --- a/Task/Abbreviations-simple/NewLISP/abbreviations-simple.l +++ b/Task/Abbreviations-simple/NewLISP/abbreviations-simple.l @@ -32,6 +32,6 @@ (push (or found? "*error*") result -1)) (join result " ")))) -(foo +(println (foo "riG rePEAT copies put mo rest types fup. 6 poweRin" -) +)) diff --git a/Task/Abstract-type/Arturo/abstract-type.arturo b/Task/Abstract-type/Arturo/abstract-type.arturo new file mode 100644 index 0000000000..ffff513cd7 --- /dev/null +++ b/Task/Abstract-type/Arturo/abstract-type.arturo @@ -0,0 +1,35 @@ +define :queue [ + init: method [][ + \items: [] + ] + + enqueue: method [item][ + panic "enqueue must be implemented by concrete type" + ] + + dequeue: method [][ + panic "dequeue must be implemented by concrete type" + ] +] + +define :simpleQueue is :queue [ + enqueue: method [item][ + \items: \items ++ item + ] + + dequeue: method [][ + if empty? \items -> return null + ret: first \items + \items: drop \items + return ret + ] +] + +q: to :simpleQueue []! + +q\enqueue "first" +q\enqueue "second" + +print q\dequeue +print q\dequeue +print q\dequeue diff --git a/Task/Achilles-numbers/FutureBasic/achilles-numbers.basic b/Task/Achilles-numbers/FutureBasic/achilles-numbers.basic new file mode 100644 index 0000000000..194d6b3e21 --- /dev/null +++ b/Task/Achilles-numbers/FutureBasic/achilles-numbers.basic @@ -0,0 +1,90 @@ +NSInteger local fn GCD( n as NSInteger, d as NSInteger ) + if ( d == 0 ) then return n else return fn GCD( d, n % d ) +end fn = 0 + +NSInteger local fn Totient( n as NSInteger ) + NSInteger tot = 0 + for NSInteger m = 1 to n + if fn GCD( m, n ) = 1 then tot++ + next + return tot +end fn = 0 + +BOOL local fn IsPowerful( m as NSInteger ) + int n = m + int f = 2 + double l = sqr(m) + + if m <= 1 then return NO + while ( YES ) + NSInteger q = n / f + if ( n % f ) == 0 + if ( m % (f * f) ) then return NO + n = q + if f > n then exit while + else + f++ + if ( f > l ) + if ( m % (n * n) ) then return NO + exit while + end if + end if + wend +end fn = YES + +BOOL local fn IsAchilles( n as NSInteger ) + if fn IsPowerful(n) == NO then return NO + NSInteger m = 2 + NSInteger a = m * m + do + do + if a == n then return NO + a *= m + until ( a > n ) + m++ + a = m * m + until ( a > n ) +end fn = YES + +local fn AchillesNumbers + print "First 50 Achilles numbers:" + NSInteger num = 0 + NSInteger n = 1 + + CFTimeInterval t : t = fn CACurrentMediaTime + do + if fn IsAchilles( n ) + printf @"%4d \b", n + num++ + if ( num % 10 ) != 0 then printf @" \b" else print + end if + n++ + until ( num >= 50 ) + + printf @"\n\nFirst 20 strong Achilles numbers:" + num = 0 + n = 1 + do + if fn IsAchilles(n) && fn IsAchilles( fn Totient(n) ) + printf @"%5d \b", n + num++ + if ( num % 5 ) != 0 then printf @" \b" else print + end if + n++ + until ( num >= 20 ) + + printf @"\n" + for NSInteger i = 2 to 6 + NSInteger inicio = fix( 10.0 ^ (i-1) ) + num = 0 + for n = inicio to inicio * 10 -1 + if fn IsAchilles(n) then num++ + next + printf @"Achilles numbers with %d digits: %d", i, num + next + printf @"\nCompute time: %.3f ms", (fn CACurrentMediaTime - t ) * 1000 +end fn + +fn AchillesNumbers + +HandleEvents diff --git a/Task/Achilles-numbers/PARI-GP/achilles-numbers.parigp b/Task/Achilles-numbers/PARI-GP/achilles-numbers.parigp new file mode 100644 index 0000000000..44391a9b19 --- /dev/null +++ b/Task/Achilles-numbers/PARI-GP/achilles-numbers.parigp @@ -0,0 +1,8 @@ +is(n,f=factor(n))=gcd(f[,2])==1 && vecmin(f[,2])>1 +first(n)=my(v=List()); forfactored(k=1,10^9, if(is(k[1],k[2]), listput(v,k[1]); if(#v==n, return(Vec(v))))) +firstStrong(n)=my(v=List()); forfactored(k=1,10^9, if(is(k[1],k[2]) && is(eulerphi(k)), listput(v,k[1]); if(#v==n, return(Vec(v))))) +countBetween(a,b)=my(s); forfactored(k=a,b, if(is(k[1],k[2]), s++)); s +countDigits(n)=countBetween(10^(n-1),10^n-1) +first(50) +firstStrong(20) +apply(countDigits, [2..5]) diff --git a/Task/Ackermann-function/ZED/ackermann-function.zed b/Task/Ackermann-function/ZED/ackermann-function.zed index a16fe385ad..af5d1c0f49 100644 --- a/Task/Ackermann-function/ZED/ackermann-function.zed +++ b/Task/Ackermann-function/ZED/ackermann-function.zed @@ -1,29 +1,29 @@ -(A) m n -comment: +(a) m n +M ZERO (=) m 0 (add1) n -(A) m n -comment: +(a) m n +N ZERO (=) n 0 -(A) (sub1) m 1 +(a) (sub1) m 1 -(A) m n -comment: +(a) m n +DEFAULT #true -(A) (sub1) m (A) m (sub1) n +(a) (sub1) m (a) m (sub1) n (add1) n -comment: +========= #true (003) "+" n 1 (sub1) n -comment: +========= #true (003) "-" n 1 (=) n1 n2 -comment: +========= #true (003) "=" n1 n2 diff --git a/Task/Additive-primes/Fortran/additive-primes.f b/Task/Additive-primes/Fortran/additive-primes.f new file mode 100644 index 0000000000..fe0cf1cf05 --- /dev/null +++ b/Task/Additive-primes/Fortran/additive-primes.f @@ -0,0 +1,66 @@ +program AdditivePrimes + implicit none + + integer :: i, j, digit_sum, count + logical :: is_prime + + ! Arrays to track prime numbers and additive primes + logical, dimension(500) :: prime_check + logical, dimension(500) :: additive_prime_check + + ! Initialize arrays + prime_check = .true. + prime_check(1) = .false. + additive_prime_check = .false. + + ! Sieve of Eratosthenes to find primes + do i = 2, int(sqrt(real(500))) + if (prime_check(i)) then + do j = i*i, 500, i + prime_check(j) = .false. + end do + end if + end do + + ! Find additive primes + count = 0 + do i = 2, 500 + if (prime_check(i)) then + ! Calculate digit sum + digit_sum = sum_digits(i) + + ! Check if digit sum is also prime + if (prime_check(digit_sum)) then + additive_prime_check(i) = .true. + count = count + 1 + end if + end if + end do + + ! Print results + print *, "Additive Primes less than 500:" + do i = 2, 500 + if (additive_prime_check(i)) then + print *, i + end if + end do + + print *, "Total number of additive primes:", count + + contains + + ! Function to calculate sum of digits + function sum_digits(num) result(total) + integer, intent(in) :: num + integer :: total, temp_num + + total = 0 + temp_num = num + + do while (temp_num > 0) + total = total + mod(temp_num, 10) + temp_num = temp_num / 10 + end do + end function sum_digits + + end program AdditivePrimes diff --git a/Task/Additive-primes/Langur/additive-primes.langur b/Task/Additive-primes/Langur/additive-primes.langur index 19042c8a58..70cff53c32 100644 --- a/Task/Additive-primes/Langur/additive-primes.langur +++ b/Task/Additive-primes/Langur/additive-primes.langur @@ -1,15 +1,15 @@ val isPrime = fn(i) { i == 2 or i > 2 and - not any(fn x: i div x, pseries(2 .. i ^/ 2)) + not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x) } -val sumDigits = fn i: fold(fn{+}, s2n(string(i))) +val sumDigits = fn i: fold(s2n(string(i)), by=fn{+}) writeln "Additive primes less than 500:" var cnt = 0 -for i in [2] ~ series(3..500, 2) { +for i in [2] ~ series(3..500, inc=2) { if isPrime(i) and isPrime(sumDigits(i)) { write "{{i:3}} " cnt += 1 diff --git a/Task/Additive-primes/Scala/additive-primes.scala b/Task/Additive-primes/Scala/additive-primes.scala new file mode 100644 index 0000000000..447bb9eabb --- /dev/null +++ b/Task/Additive-primes/Scala/additive-primes.scala @@ -0,0 +1,26 @@ +def isPrime(n: Int): Boolean = { + @annotation.tailrec + def checkDivisor(d: Int): Boolean = { + if (d * d > n) true + else if (n % d == 0) false + else checkDivisor(d + 2) + } + + if (n < 2) false + else if (n == 2 || n == 3) true + else if (n % 2 == 0 || n % 3 == 0) false + else checkDivisor(5) +} + +private def digitSum(n: Int): Int = n.toString.map(_ - '0').sum + +private def additivePrime(n: Int): Boolean = isPrime(n) && isPrime(digitSum(n)) + +private def testAdditivePrime(max: Int): Unit = { + val result = (2 to max).filter(additivePrime) + println(result.mkString(", ")) + println(s"Found ${result.length} additive primes less than 500.") +} + +@main def main(): Unit = + testAdditivePrime(500) diff --git a/Task/Address-of-a-variable/Zig/address-of-a-variable.zig b/Task/Address-of-a-variable/Zig/address-of-a-variable.zig index 88fd6ff5ee..9012f0e79e 100644 --- a/Task/Address-of-a-variable/Zig/address-of-a-variable.zig +++ b/Task/Address-of-a-variable/Zig/address-of-a-variable.zig @@ -2,8 +2,9 @@ const std = @import("std"); pub fn main() !void { const stdout = std.io.getStdOut().writer(); - var i: i32 = undefined; - var address_of_i: *i32 = &i; - - try stdout.print("{x}\n", .{@intFromPtr(address_of_i)}); + const i: i32 = 76; + try stdout.print("{x} {*}\n", .{ + @intFromPtr(&i), + &i + }); } diff --git a/Task/Align-columns/8080-Assembly/align-columns.8080 b/Task/Align-columns/8080-Assembly/align-columns.8080 new file mode 100644 index 0000000000..2156a3485e --- /dev/null +++ b/Task/Align-columns/8080-Assembly/align-columns.8080 @@ -0,0 +1,212 @@ +putc equ 2 +puts equ 9 +fopen equ 15 +fclose equ 16 +fread equ 20 +FCB1 equ 5Ch +FCB2 equ 6Ch +DTA equ 80h +COLSEP equ '$' + org 100h + + ;;; Check arguments + lxi d,argmsg + lda FCB1+1 ; Check file argument + cpi ' ' + jz prmsg + lda FCB2+1 ; Check alignment argument + cpi 'L' + jz setal + cpi 'R' + jz setar + cpi 'C' + jnz prmsg + lxi h,center ; Set alignment function to run + jmp setfn +setal: lxi h,left + jmp setfn +setar: lxi h,right +setfn: shld alnfn+1 + + ;;; Initialize column lengths to 0 + xra a + lxi h,colw +inicol: mov m,a + inr l + jnz inicol + + ;;; Open file + lxi d,FCB1 + mvi c,fopen + call 5 + inr a + jz efile ; FF = error + + ;;; Process file + lxi h,maxw ; Find maximum widths + call rdlins + lxi h,alnlin ; Read lines and align columns + call rdlins + + ;;; Close file + lxi d,FCB1 + mvi c,fclose + jmp 5 + + ;;; Update maximum widths of columns, given line +maxw: lxi h,colw ; Column widths + lxi d,linbuf +mcol: mvi b,0FFh ; B = column width +mscan: inr b + ldax d ; Get current item + inx d ; Next item + call colend ; End of column? + jc mscan + push psw ; Keep column comparison + mov a,m ; Current width + cmp b ; Compare to new width + jnc mnxcol + mov m,b ; New one is bigger +mnxcol: inr l ; Next column + pop psw ; Restore column comparison + jz mcol ; Keep going if not end of line + ret + + ;;; Align and print columns of line +alnlin: lxi h,colw + lxi b,linbuf +alncol: lxi d,colbuf-1 +alnscn: inx d ; Copy current column to buffer + ldax b + stax d + inx b + call colend + jc alnscn + push psw + push h + push b +alncal: xra a ; Zero-terminate the buffer + stax d + mov a,m ; Current max column length + sub e ; Minus length of this column + mov b,a ; Set B = current padding needed +alnfn: call 0 ; Call selected alignment + pop b + pop h + inr l + pop psw + jz alncol ; Next column, if any + lxi d,newlin ; End line + mvi c,puts + jmp 5 + + ;;; Align column left and print +left: push b ; Save padding needed + lxi h,colbuf ; Print column + call print0 + pop b ; Restore padding + inr b ; Plus one, for separator between columns + + ;;; Print B spaces as padding +pad: xra a + ora b + rz ; No padding +padl: push b + mvi e,' ' + mvi c,putc + call 5 + pop b + dcr b + jnz padl + ret + + ;;; Align column right and print +right: call pad ; Padding first + lxi h,colbuf + call print0 ; Then column + mvi b,1 + jmp pad ; Separator space + + ;;; Align column in the center and print +center: mov a,b ; Split padding in half + rar + mov b,a + aci 0 + mov c,a + push b ; Keep both parts + call pad ; Left padding + lxi h,colbuf ; Print column + call print0 + pop b ; Restore padding + mov b,c ; Right padding + inr b ; Plus one for the separator + jmp pad + + ;;; Print 0-terminated string at HL +print0: mov a,m + ana a + rz + push h + mov e,m + mvi c,putc + call 5 + pop h + inx h + jmp print0 + + ;;; Does character in A end a column? + ;;; C clear if so. Z clear if also end of line. +colend: cpi 32 ; End of line? + cmc + rnc + cpi COLSEP ; Separator? + rz + stc ; If neither, set carry and return + ret + + ;;; Process file in FCB1 line by line + ;;; HL = line callback +rdlins: shld linecb+1 ; Set callback + xra a ; Start at beginning of file + sta FCB1+0Ch ; EX + sta FCB1+0Eh ; S2 + sta FCB1+0Fh ; RC + sta FCB1+20h ; AL + lxi d,linbuf ; Start write pointer at line buffer +rdrec: push d ; Keep write pointer + lxi d,FCB1 ; Read next record + mvi c,fread + call 5 + pop d ; Restore write pointer + dcr a ; 1 = EOF + rz + inr a + jnz efile ; Otherwise, <>0 = error + lxi h,DTA ; Reset read pointer to DTA +cpydat: mov a,m ; Copy byte to line buffer + stax d + inx d + cpi 26 ; EOF -> done + rz + cpi 10 ; (\r)\n -> EOL + jnz cnexb + push h ; Keep record pointer +linecb: call 0 ; Call callback routine + pop h ; Restore record pointer + lxi d,linbuf ; Reset line pointer +cnexb: inr l ; Next byte + jz rdrec ; Next record + jmp cpydat +efile: lxi d,filerr +prmsg: mvi c,puts + jmp 5 + + ;;; Messages +argmsg: db 'ALIGN FILE.TXT L/R/C$' +filerr: db 'FILE ERROR$' +newlin: db 13,10,'$' + + ;;; Variables +colw equ ($/256+1)*256 ; Column widths (page-aligned) +colbuf equ colw+256 ; Column buffer +linbuf equ colbuf+256 ; Line buffer diff --git a/Task/Align-columns/Cowgol/align-columns.cowgol b/Task/Align-columns/Cowgol/align-columns.cowgol new file mode 100644 index 0000000000..67428f2a4f --- /dev/null +++ b/Task/Align-columns/Cowgol/align-columns.cowgol @@ -0,0 +1,134 @@ +include "cowgol.coh"; +include "strings.coh"; +include "file.coh"; +include "argv.coh"; + +interface ColumnCb(colnum: uint8, col: [uint8], isLast: uint8); +sub ForEachColumn(fcb: [FCB], colfn: ColumnCb, colsep: uint8) is + var linebuf: uint8[256]; + var bufptr := &linebuf[0]; + + sub HandleColumns() is + var colbuf: uint8[256]; + var col: uint8 := 0; + var lineptr := &linebuf[0]; + var colptr := &colbuf[0]; + + while [lineptr] != 0 loop + if [lineptr] == colsep or [lineptr] == '\n' then + [colptr] := 0; + colptr := &colbuf[0]; + if [lineptr] == '\n' then + colfn(col, colptr, 1); + else + colfn(col, colptr, 0); + end if; + col := col + 1; + else + [colptr] := [lineptr]; + colptr := @next colptr; + end if; + lineptr := @next lineptr; + end loop; + end sub; + + var len := FCBExt(fcb); + FCBSeek(fcb, 0); + + while len > 0 loop + var ch := FCBGetChar(fcb); + [bufptr] := ch; + bufptr := @next bufptr; + len := len - 1; + + if ch == '\n' then + [bufptr] := 0; + HandleColumns(); + bufptr := &linebuf[0]; + end if; + end loop; +end sub; + +var columnWidths: uint8[256]; +sub FindColumnMaxWidths(fcb: [FCB], colsep: uint8) is + sub FindColumnMaxWidth implements ColumnCb is + var len := StrLen(col) as uint8; + if columnWidths[colnum] < len then + columnWidths[colnum] := len; + end if; + end sub; + + ForEachColumn(fcb, FindColumnMaxWidth, colsep); +end sub; + +sub Pad(padding: uint8) is + while padding > 0 loop + print_char(' '); + padding := padding - 1; + end loop; +end sub; + +interface Alignment(padding: uint8, string: [uint8]); +sub Left implements Alignment is + print(string); + Pad(padding); +end sub; + +sub Right implements Alignment is + Pad(padding); + print(string); +end sub; + +sub Center implements Alignment is + Pad(padding >> 1); + print(string); + Pad((padding >> 1) + (padding & 1)); +end sub; + +sub PrintColumnsAligned(fcb: [FCB], colsep: uint8, alignment: Alignment) is + sub PrintColumnAligned implements ColumnCb is + var len := StrLen(col) as uint8; + var padding := columnWidths[colnum] - len; + alignment(padding, col); + if isLast != 0 then + print_nl(); + else + print_char(' '); + end if; + end sub; + + ForEachColumn(fcb, PrintColumnAligned, colsep); +end sub; + +ArgvInit(); +var filename := ArgvNext(); +if filename == 0 as [uint8] then + print("No filename given\n"); + ExitWithError(); +end if; + +var align := ArgvNext(); +if align == 0 as [uint8] then + print("No alignment given\n"); + ExitWithError(); +end if; + +var alignment: Alignment; +case [align] & ~32 is + when 'L': alignment := Left; + when 'R': alignment := Right; + when 'C': alignment := Center; + when else: + print("Alignment must be L(eft), R(ight), or C(enter)\n"); + ExitWithError(); +end case; + +var file: FCB; +if FCBOpenIn(&file, filename) != 0 then + print("Cannot open file\n"); + ExitWithError(); +end if; + +const separator := '$'; +FindColumnMaxWidths(&file, separator); +PrintColumnsAligned(&file, separator, alignment); diff --git a/Task/Align-columns/Draco/align-columns.draco b/Task/Align-columns/Draco/align-columns.draco new file mode 100644 index 0000000000..3c5cfe9a9a --- /dev/null +++ b/Task/Align-columns/Draco/align-columns.draco @@ -0,0 +1,93 @@ +\util.g +char separator = '$'; + +type + colHandler = proc(byte n; *char col; bool last)void, + alignment = proc(byte padding; *char col)void; + +[256]byte ColWidths; +alignment Alignment; + +proc find_max_col_width(byte n; *char col; bool last) void: + if ColWidths[n] < CharsLen(col) then + ColWidths[n] := CharsLen(col) + fi +corp + +proc write_col_aligned(byte n; *char col; bool last) void: + byte padding; + padding := ColWidths[n] - CharsLen(col); + Alignment(padding, col); + if last then writeln() else write(' ') fi +corp + +proc pad(byte padding) void: + while padding>0 do write(' '); padding := padding-1 od +corp + +proc align_left(byte padding; *char col) void: write(col); pad(padding) corp +proc align_right(byte padding; *char col) void: pad(padding); write(col) corp +proc align_center(byte padding; *char col) void: + pad(padding>>1); + write(col); + pad((padding>>1) + (padding&1)) +corp + +proc do_line(*char line; colHandler handler) void: + byte col; + bool last; + char ch; + *char colstart; + col := 0; + colstart := line; + + while + ch := line*; + last := ch = '\e'; + if last or ch = separator then + line* := '\e'; + handler(col, colstart, last); + colstart := line+1; + col := col+1 + fi; + not last + do + line := line+1 + od +corp + +proc do_columns(*char filename; colHandler handler) void: + [256]char linebuf; + *char line; + channel input text in; + file(1024) infile; + + open(in, infile, filename); + line := &linebuf[0]; + while readln(in; line) do do_line(line, handler) od; + close(in); +corp + +proc ucase(char c) char: pretend(pretend(c, byte) & ~32, char) corp + +proc main() void: + *char filename, align; + word i; + for i from 0 upto 255 do ColWidths[i] := 0 od; + + filename := GetPar(); + if filename = nil then writeln("No filename given"); exit(1) fi; + + align := GetPar(); + if align = nil then writeln("No alignment given"); exit(1) fi; + + case ucase(align*) + incase 'L': Alignment := align_left + incase 'R': Alignment := align_right + incase 'C': Alignment := align_center + default: writeln("Alignment must be L/R/C"); exit(1) + esac; + + do_columns(filename, find_max_col_width); + do_columns(filename, write_col_aligned) +corp diff --git a/Task/Align-columns/Emacs-Lisp/align-columns.l b/Task/Align-columns/Emacs-Lisp/align-columns.l new file mode 100644 index 0000000000..a073ab13c1 --- /dev/null +++ b/Task/Align-columns/Emacs-Lisp/align-columns.l @@ -0,0 +1,251 @@ +(defun rob-even-p (integer) + "Test if INTEGER is even." + (= (% integer 2) 0)) + +(defun rob-odd-p (integer) + "Test if INTEGER is odd." + (not (rob-even-p integer))) + +(defun both-odd-or-both-even-p (x y) + "Test if X and Y are both even or both odd." + (or (and (rob-even-p x) (rob-even-p y)) + (and (rob-odd-p x) (rob-odd-p y)))) + +(defun word-lengths (words) + "Convert WORDS into list of lengths of each word." + (mapcar 'length words)) + +(defun get-one-row (row-number rows-columns-words) + "Get ROW-NUMBER row from ROWS-COLUMNS-WORDS. +ROWS-COLUMNS-WORDS is list of lists in form of row, column, word." + (seq-filter + (lambda (element) + (= row-number (car element))) + rows-columns-words)) + +(defun get-one-word (row-number column-number rows-columns-words) + "Get one word from ROWS-COLUMNS-WORDS at ROW-NUMBER and COLUMN-NUMBER. +ROWS-COLUMNS-WORDS is list of lists in form of row, column, word." + (delq nil + (mapcar + (lambda (element) + (when (= column-number (nth 1 element)) + (nth 2 element))) + (get-one-row row-number rows-columns-words)))) + +(defun get-last-row (rows-columns-words) + "Get the number of the last row of ROWS-COLUMNS-WORDS. +ROWS-COLUMNS-WORDS is a list of lists, each list in the form of +row, column, word." + (apply 'max (mapcar 'car rows-columns-words))) + +(defun list-nth-column (column rows-columns-words) + "List the words in column COLUMN of ROWS-COLUMNS-WORDS. +ROWS-COLUMNS-WORDS is a list of lists, each list in the form of row, column, +word." + (let ((row 1) + (column-word) + (last-row (get-last-row rows-columns-words )) + (matches nil)) + (while (and (<= row last-row) + (<= column (get-last-column rows-columns-words))) + (setq column-word (get-one-word row column rows-columns-words)) + (when (null column-word) + (setq column-word "")) + (push column-word matches) + (setq row (1+ row))) + (flatten-tree (nreverse matches)))) + +(defun get-widest-in-column (column) + "Get the widest word in COLUMN, which is a list of words." + (apply #'max (word-lengths column))) + +(defun get-column-width (column) + "Calculate the width of COLUMN, which is a list of words." + (+ (get-widest-in-column column) 2)) + +(defun get-column-widths (rows-columns-words) + "Make a list of the column widths in ROWS-COLUMNS-WORDS. +ROWS-COLUMNS-WORDS is list of lists, with each list in the form of row, column, +word." + (let ((last-column (get-last-column rows-columns-words)) + (column 1) + (columns)) + (while (<= column last-column) + (push (get-column-width (list-nth-column column rows-columns-words)) columns) + (setq column (1+ column))) + (reverse columns))) + +(defun add-column-widths (widths rows-columns-words) + "Add WIDTHS to ROWS-COLUMNS-WORDS. +ROWS-COLUMNS-WORDS is a list of lists, with each list in the form of row, +column, word. WIDTHS are the widths of each column. Output is a +list of lists, with each list in the form of column-width, row, +column, word." + (let ((new-data) + (new-database) + (column) + (width)) + (dolist (data rows-columns-words) + (setq column (cadr data)) + (setq width (nth (- column 1) widths)) + (setq new-data (push width data)) + (push new-data new-database)) + (nreverse new-database))) + +(defun get-last-column (rows-columns-words) + "Get the number of the last column in ROWS-COLUMNS-WORDS." + (apply 'max (mapcar 'cadr rows-columns-words))) + +(defun create-rows-columns-words () + "Put text from column-data.txt file in lists. +Each list consists of a row number, a column number, and a word." + (let ((lines) + (line-number 0) + (word-number) + (words)) + (with-temp-buffer + (insert-file-contents "~/Documents/Elisp/column_data.txt") + (beginning-of-buffer) + (dolist (line (split-string (buffer-string) "[\r\n]" :no-nulls)) + (push line lines)) + (setq lines (nreverse lines))) + (dolist (line lines) + (setq line-number (1+ line-number)) + (setq word-number 0) + (dolist (word (split-string line "\\$" :no-nulls)) + (setq word-number (1+ word-number)) + (push (list line-number word-number word) words))) + (setq words (nreverse words)))) + +(defun pad-for-center-align (column-width text) + "Pad TEXT to center in space of COLUMN-WIDTH." + (let* ((text-width (length text)) + (total-padding-length (- column-width text-width)) + (pre-padding-length) + (post-padding-length) + (pre-padding) + (post-padding)) + (if (both-odd-or-both-even-p text-width column-width) + (progn + (setq pre-padding-length (/ total-padding-length 2)) + (setq post-padding-length pre-padding-length)) + (setq pre-padding-length (+ (/ total-padding-length 2) 1)) + (setq post-padding-length (- pre-padding-length 1))) + (setq pre-padding (make-string pre-padding-length ? )) + (setq post-padding (make-string post-padding-length ? )) + (format "%s%s%s" pre-padding text post-padding))) + +(defun create-a-center-aligned-line (widths-1row-columns-words) + "Create a centered line based on WIDTHS-1ROW-COLUMNS-WORDS. +WIDTHS-1ROW-COLUMNS-WORDS is a list of lists. Each list consists +of the column-width, the row number, the column number, and the +word. The row number is the same in all lists." + (let ((full-line "") + (next-section)) + (insert "\n") + (dolist (word-data widths-1row-columns-words) + ;; below, nth 0 is the column width, nth 3 is the word + (setq next-section (pad-for-center-align (nth 0 word-data) (nth 3 word-data))) + (setq full-line (concat full-line next-section))) + (insert full-line))) + +(defun pad-for-left-align (column-width text) + "Pad TEXT to left-align in space of COLUMN-WIDTH." + (let* ((text-width (length text)) + (post-padding-length (- column-width text-width))) + (setq post-padding (make-string post-padding-length ? )) + (format "%s%s" text post-padding))) + +(defun create-a-left-aligned-line (widths-1row-columns-words) + "Create a left-aligned line based on WIDTHS-1ROW-COLUMNS-WORDS. +Each element of WIDTHS-1ROW-COLUMNS-WORDS consists of the column +width, the row number, the column number, and the word. The row +number is the same in every case." + (let ((full-line "") + (next-section)) + (insert "\n") + (dolist (one-item widths-1row-columns-words) + (setq next-section (pad-for-left-align (nth 0 one-item) (nth 3 one-item))) + (setq full-line (concat full-line next-section))) + (insert full-line))) + +(defun pad-for-right-align (column-width text) + "Pad TEXT to right-align in space of COLUMN-WIDTH." + (let* ((text-width (length text)) + (pre-padding-length (- column-width text-width))) + (setq pre-padding (make-string pre-padding-length ? )) + (format "%s%s" pre-padding text))) + +(defun create-a-right-aligned-line (widths-1row-columns-words) + "Create a right-aligned line based on WIDTHS-1ROW-COLUMNS-WORDS. +Each element of WIDTHS-1ROW-COLUMNS-WORDS consists of the column +width, the row number, the column number, and the word. The row +number is the same in every case." + (let ((full-line "") + (next-section)) + (insert "\n") + (dolist (one-item widths-1row-columns-words) + (setq next-section (pad-for-right-align (nth 0 one-item) (nth 3 one-item))) + (setq full-line (concat full-line next-section))) + (insert full-line))) + +(defun left-align-lines (rows-columns-words) + "Write ROWS-COLUMNS-WORDS in left-aligned columns. +ROWS-COLUMNS-WORDS is a list of lists. Each list consists of the +row number, the column number, and the word." + (let* ((row-number 1) + (column-widths (get-column-widths rows-columns-words)) + (last-row (get-last-row rows-columns-words)) + (one-row) + (width-place 0)) + (while (<= row-number last-row) + (setq one-row (get-one-row row-number rows-columns-words)) + (setq one-row (add-column-widths column-widths one-row)) + (create-a-left-aligned-line one-row) + (setq row-number (1+ row-number)) + (setq width-place (1+ width-place))))) + +(defun right-align-lines (rows-columns-words) + "Write ROWS-COLUMNS-WORDS in right-aligned columns. +ROWS-COLUMNS-WORDS is a list of lists. Each list consists of the +row number, the column number, and the word." + (let* ((row-number 1) + (column-widths (get-column-widths rows-columns-words)) + (last-row (get-last-row rows-columns-words)) + (one-row) + (width-place 0)) + (while (<= row-number last-row) + (setq one-row (get-one-row row-number rows-columns-words)) + (setq one-row (add-column-widths column-widths one-row)) + (create-a-right-aligned-line one-row) + (setq row-number (1+ row-number)) + (setq width-place (1+ width-place))))) + +(defun center-align-lines (rows-columns-words) + "Write ROWS-COLUMNS-WORDS in center-aligned columns. +ROWS-COLUMNS-WORDS is a list of lists. Each list consists of the +row number, the column number, and the word." + (let* ((row-number 1) + (column-widths (get-column-widths rows-columns-words)) + (last-row (get-last-row rows-columns-words)) + (one-row) + (width-place 0)) + (while (<= row-number last-row) + (setq one-row (get-one-row row-number rows-columns-words)) + (setq one-row (add-column-widths column-widths one-row)) + (create-a-center-aligned-line one-row) + (setq row-number (1+ row-number)) + (setq width-place (1+ width-place))))) + +(defun align-lines (alignment rows-columns-words) + "Write ROWS-COLUMNS-WIDTHS with given ALIGNMENT. +ROWS-COLUMNS-WIDTHS consists of a list of lists. Each internal list contains width of column, row number, column number, and a word." + (let ((align-function (pcase alignment + ('left 'left-align-lines) + ("left" 'left-align-lines) + ('center 'center-align-lines) + ("center" 'center-align-lines) + ('right 'right-align-lines) + ("right" 'right-align-lines)))) + (funcall align-function rows-columns-words))) diff --git a/Task/Align-columns/Miranda/align-columns.miranda b/Task/Align-columns/Miranda/align-columns.miranda new file mode 100644 index 0000000000..f39cb05be0 --- /dev/null +++ b/Task/Align-columns/Miranda/align-columns.miranda @@ -0,0 +1,34 @@ +#! /usr/bin/mira -exec +main :: [sys_message] +main = [Stdout (align (alignment algm) '$' (read file))] + where [cmd, file, algm] = $* + +alignment :: [char]->num->[char]->[char] +alignment "left" = ljustify +alignment "center" = cjustify +alignment "right" = rjustify +alignment x = error "Alignment must be left, center, or right" + +align :: (num->[char]->[char])->char->[char]->[char] +align just sep text = (lay . map (alignline just sep cols) . lines) text + where cols = colwidths sep text + +split :: *->[*]->[[*]] +split sep = s [] + where s acc [] = [acc] + s acc (a:as) = acc:s [] as, if a==sep + = s (acc++[a]) as, otherwise + +colwidths :: char->[char]->[num] +colwidths sep text = (map max . transpose . map (extend maxwidth 0)) widths + where widths = map (map (#) . split sep) (lines text) + maxwidth = max (map (#) widths) + +alignline :: (num->[char]->[char])->char->[num]->[char]->[char] +alignline just sep cols = concat . map (++" ") . zipwith just cols . split sep + +zipwith :: (*->**->***)->[*]->[**]->[***] +zipwith f xs ys = map f' (zip2 xs ys) where f' (x,y) = f x y + +extend :: num->*->[*]->[*] +extend n k ls = ls ++ take (n-#ls) (repeat k) diff --git a/Task/Align-columns/Refal/align-columns.refal b/Task/Align-columns/Refal/align-columns.refal new file mode 100644 index 0000000000..19662f46b2 --- /dev/null +++ b/Task/Align-columns/Refal/align-columns.refal @@ -0,0 +1,71 @@ +$ENTRY Go { + , : e.File + , : e.Alignment + , : e.Lines + , : e.Parts + , >: e.Cols + = ; +}; + +ReadFile { + s.Chan e.File = + ; + (s.Chan), : { + 0 = ; + e.Line = (e.Line) ; + }; +}; + +Split { + (e.Sep) e.Part e.Sep e.Rest = (e.Part) ; + (e.Sep) e.Part = (e.Part); +}; + +Each { + (e.F) = ; + (e.F) (e.X) e.Xs = () ; +}; + +MaxWidth { + (Acc s.W) = s.W; + (Acc s.W) (e.P) e.X, : s.L, : { + '+' = ; + s.C = ; + }; + e.X = ; +}; + +Transpose { + e.X, : e.L, : { + True = ; + False = (e.L) >; + }; +}; + +ZipWith { + (e.F) () e.Ys = ; + (e.F) e.Xs () = ; + (e.F) (t.X e.Xs) (t.Y e.Ys) = ; +}; + +AlignCell { + ('left') (e.Cell) (s.Width), + : s.L = e.Cell ' '> ' '; + ('right') (e.Cell) (s.Width), + : s.L = ' '> e.Cell ' '; + ('center') (e.Cell) (s.Width), + > 2>: (s.P) s.V, + : e.LP, + ' '>: e.RP = e.LP e.Cell e.RP ' '; +}; + +AlignLine { + (e.Alignment) (e.Cols) e.Line = + >; +}; + +Rep { 0 s.C = ; s.N s.C = s.C s.C>; }; +Empty { = True; () e.X = ; e.X = False; }; +Len { e.X, : s.L e.X = s.L; }; +Head { = ; (e.X) e.Xs = e.X; }; +Tail { = ; (e.X) e.Xs = e.Xs; }; diff --git a/Task/Aliquot-sequence-classifications/FutureBasic/aliquot-sequence-classifications.basic b/Task/Aliquot-sequence-classifications/FutureBasic/aliquot-sequence-classifications.basic new file mode 100644 index 0000000000..663c14ccfa --- /dev/null +++ b/Task/Aliquot-sequence-classifications/FutureBasic/aliquot-sequence-classifications.basic @@ -0,0 +1,95 @@ +begin globals + short n + long arr(17) + bool gStop = _False +end globals + +local fn sumFactors(nx as long) as long + long i, sumFactor + sumFactor = 0 + for i = 1 to fix(nx / 2) + if (nx) mod i = 0 then sumFactor = sumFactor + i + next +end fn = sumFactor + +void local fn printSeries(arrx as short, size as short, type as str255) + short i = 0 + print + print "Integer" + str$(arrx) + ", Type: " + type + ", Series: "; + for i=0 to size - 2 + print str$(arr(i)) + " "; + next i +end fn + +local fn Aliquot(nx as long) + + short i, j + str255 type + + type = "Sociable" + arr(0) = nx + + for i = 1 to 15 + + arr(i) = fn sumFactors(arr(i-1)) + if (arr(i)=0 || arr(i)=nx || (arr(i) = arr(i-1)) && arr(i)<>nx) + if arr(i) = 0 + type = "Terminating" + else + if arr(i) = nx && i = 1 + type = "Perfect" + else + if arr(i) = nx && i = 2 + type = "Amicable" + else + if arr(i) = arr(i-1) && arr(i)<>nx + type = "Aspiring" + end if + end if + end if + end if + + fn printSeries(arr(0),i+1,type) + if type = "Terminating" + print " 0" + else + print + end if + + exit fn + end if + + + for j = 1 to i-1 + if arr(j) = arr(i) + fn printSeries(arr(0),i+1,"Cyclic") + print + exit fn + end if + next j + next i + fn printSeries(arr(i),i+1,"Non-Terminating") + print + +end fn + + +local fn DoAliquot + // declare and assign c-type array + long dataArray(30) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184,¬ + 12496, 1264460, 790, 909, 562, 1064, 1488, 0} + + short i + for i = 0 to 24 + if dataArray(i) = 0 then gStop = _True:exit fn + fn Aliquot(dataArray(i)) + next i + +end fn = gStop + +window 1,@"Aliquot sequence classifications",fn CGRectMake(0, 0, 1150, 700) +windowcenter(1) + +fn AppSetTimer( .000001, @Fn DoAliquot, _true ) + +handleevents diff --git a/Task/Almkvist-Giullera-formula-for-pi/PARI-GP/almkvist-giullera-formula-for-pi.parigp b/Task/Almkvist-Giullera-formula-for-pi/PARI-GP/almkvist-giullera-formula-for-pi.parigp new file mode 100644 index 0000000000..9761b3ae9b --- /dev/null +++ b/Task/Almkvist-Giullera-formula-for-pi/PARI-GP/almkvist-giullera-formula-for-pi.parigp @@ -0,0 +1,2 @@ +\p77 +sqrt(375/4/suminf(n=0,(6*n)!*(532*n^2+126*n+9.)/(n!*10^n)^6)) diff --git a/Task/Amb/Langur/amb.langur b/Task/Amb/Langur/amb.langur index 3adeaad38f..7f047193bb 100644 --- a/Task/Amb/Langur/amb.langur +++ b/Task/Amb/Langur/amb.langur @@ -10,6 +10,6 @@ val alljoin = fn words: for[=true] i of len(words)-1 { } # amb expects 2 or more arguments -val amb = fn ...[2..] words: if alljoin(words) { join " ", words } +val amb = fn ...[2..] words: if alljoin(words) { join words, by=" " } -writeln join("\n", filter(mapX(amb, wordsets...))) +writeln join(mapX(wordsets..., by=amb) -> filter, by="\n") diff --git a/Task/Amb/Scheme/amb-1.scm b/Task/Amb/Scheme/amb-1.scm index 951db6f220..825f13342c 100644 --- a/Task/Amb/Scheme/amb-1.scm +++ b/Task/Amb/Scheme/amb-1.scm @@ -13,7 +13,7 @@ (LAMBDA (K-SUCCESS) ; which we return possibles. (CALL-WITH-CURRENT-CONTINUATION (LAMBDA (K-FAILURE) ; K-FAILURE will try the next - (SET! FAIL K-FAILURE) ; possible expression. + (SET! FAIL (LAMBDA () (K-FAILURE 'anything-is-fine-here))) ; possible expression. (K-SUCCESS ; Note that the expression is (LAMBDA () ; evaluated in tail position expression)))) ; with respect to AMB. diff --git a/Task/Angle-difference-between-two-bearings/ANSI-BASIC/angle-difference-between-two-bearings.basic b/Task/Angle-difference-between-two-bearings/ANSI-BASIC/angle-difference-between-two-bearings.basic new file mode 100644 index 0000000000..9a7c6b0d99 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/ANSI-BASIC/angle-difference-between-two-bearings.basic @@ -0,0 +1,33 @@ +100 REM Angle difference between two bearings +110 DECLARE EXTERNAL FUNCTION GetDiff +120 REM +130 SUB PrintRow(B1, B2) +140 PRINT USING "#######.###### #######.###### #######.######": B1, B2, GetDiff(B1, B2) +150 END SUB +160 REM +170 print "Input in -180 to +180 range" +180 PRINT " Bearing 1 Bearing 2 Difference" +190 CALL PrintRow(20.0, 45.0) +200 CALL PrintRow(-45.0, 45.0) +210 CALL PrintRow(-85.0, 90.0) +220 CALL PrintRow(-95.0, 90.0) +230 CALL PrintRow(-45.0, 125.0) +240 CALL PrintRow(-45.0, 145.0) +250 CALL PrintRow(-45.0, 125.0) +260 CALL PrintRow(-45.0, 145.0) +270 CALL PrintRow(29.4803, -88.6381) +280 CALL PrintRow(-78.3251, -159.036) +290 PRINT +300 PRINT "Input in wider range" +310 PRINT " Bearing 1 Bearing 2 Difference" +320 CALL PrintRow(-70099.74233810938, 29840.67437876723) +330 CALL PrintRow(-165313.6666297357, 33693.9894517456) +340 CALL PrintRow(1174.8380510598456, -154146.66490124757) +350 CALL PrintRow(60175.77306795546, 42213.07192354373) +360 END +370 REM +380 EXTERNAL FUNCTION GetDiff (B1, B2) +390 LET R = MOD(B2 - B1, 360.0) +400 IF R >= 180.0 THEN LET R = R - 360.0 +410 LET GetDiff = R +420 END FUNCTION diff --git a/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp b/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp index af35a7815c..92cb3f68b7 100644 --- a/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp +++ b/Task/Angle-difference-between-two-bearings/C++/angle-difference-between-two-bearings.cpp @@ -2,34 +2,40 @@ #include using namespace std; -double getDifference(double b1, double b2) { - double r = fmod(b2 - b1, 360.0); - if (r < -180.0) - r += 360.0; - if (r >= 180.0) - r -= 360.0; - return r; +double getDifference(double b1, double b2) +{ + double r = fmod(b2 - b1, 360.0); + if (r < -180.0) + r += 360.0; + if (r >= 180.0) + r -= 360.0; + return r; +} + +inline void printRow(double b1, double b2) +{ + cout << getDifference(b1, b2) << endl; } int main() { - cout << "Input in -180 to +180 range" << endl; - cout << getDifference(20.0, 45.0) << endl; - cout << getDifference(-45.0, 45.0) << endl; - cout << getDifference(-85.0, 90.0) << endl; - cout << getDifference(-95.0, 90.0) << endl; - cout << getDifference(-45.0, 125.0) << endl; - cout << getDifference(-45.0, 145.0) << endl; - cout << getDifference(-45.0, 125.0) << endl; - cout << getDifference(-45.0, 145.0) << endl; - cout << getDifference(29.4803, -88.6381) << endl; - cout << getDifference(-78.3251, -159.036) << endl; - - cout << "Input in wider range" << endl; - cout << getDifference(-70099.74233810938, 29840.67437876723) << endl; - cout << getDifference(-165313.6666297357, 33693.9894517456) << endl; - cout << getDifference(1174.8380510598456, -154146.66490124757) << endl; - cout << getDifference(60175.77306795546, 42213.07192354373) << endl; + cout << "Input in -180 to +180 range" << endl; + printRow(20.0, 45.0); + printRow(-45.0, 45.0); + printRow(-85.0, 90.0); + printRow(-95.0, 90.0); + printRow(-45.0, 125.0); + printRow(-45.0, 145.0); + printRow(-45.0, 125.0); + printRow(-45.0, 145.0); + printRow(29.4803, -88.6381); + printRow(-78.3251, -159.036); - return 0; + cout << endl << "Input in wider range" << endl; + printRow(-70099.74233810938, 29840.67437876723); + printRow(-165313.6666297357, 33693.9894517456); + printRow(1174.8380510598456, -154146.66490124757); + printRow(60175.77306795546, 42213.07192354373); + + return 0; } diff --git a/Task/Angle-difference-between-two-bearings/PHP/angle-difference-between-two-bearings.php b/Task/Angle-difference-between-two-bearings/PHP/angle-difference-between-two-bearings.php new file mode 100644 index 0000000000..0cec699805 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/PHP/angle-difference-between-two-bearings.php @@ -0,0 +1,38 @@ + 180.0) + $r -= 360.0; + if ($r < -180.0) + $r += 360.0; + return $r; + } + + function echo_row($b1, $b2) { + echo str_pad(number_format($b1, 6, ".", ""), 14, " ", STR_PAD_LEFT).' '; + echo str_pad(number_format($b2, 6, ".", ""), 14, " ", STR_PAD_LEFT).' '; + echo str_pad(number_format(get_diff($b1, $b2), 6), 14, " ", STR_PAD_LEFT); + echo "\n"; + } + + echo "Input in -180 to +180 range\n"; + echo " Bearing 1 Bearing 2 Difference\n"; + echo_row(20.0, 45.0); + echo_row(-45.0, 45.0); + echo_row(-85.0, 90.0); + echo_row(-95.0, 90.0); + echo_row(-45.0, 125.0); + echo_row(-45.0, 145.0); + echo_row(-45.0, 125.0); + echo_row(-45.0, 145.0); + echo_row(29.4803, -88.6381); + echo_row(-78.3251, -159.036); + echo "\nInput in wider range\n"; + echo " Bearing 1 Bearing 2 Difference\n"; + echo_row(-70099.74233810938, 29840.67437876723); + echo_row(-165313.6666297357, 33693.9894517456); + echo_row(1174.8380510598456, -154146.66490124757); + echo_row(60175.77306795546, 42213.07192354373); +?> diff --git a/Task/Angles-geometric-normalization-and-conversion/FutureBasic/angles-geometric-normalization-and-conversion.basic b/Task/Angles-geometric-normalization-and-conversion/FutureBasic/angles-geometric-normalization-and-conversion.basic new file mode 100644 index 0000000000..df05b07e41 --- /dev/null +++ b/Task/Angles-geometric-normalization-and-conversion/FutureBasic/angles-geometric-normalization-and-conversion.basic @@ -0,0 +1,100 @@ +include "NSLog.incl" + +double local fn Normalize( f as double, n as double ) + double a = f + while ( a < -n ) : a += n : wend + while ( a >= n ) : a -= n : wend +end fn = a + +double local fn NormalizeToDegrees( f as double ) return fn Normalize( f, 360 ) end fn = 0.0 +double local fn NormalizeToGradians( f as double ) return fn Normalize( f, 400 ) end fn = 0.0 +double local fn NormalizeToMils( f as double ) return fn Normalize( f, 6400 ) end fn = 0.0 +double local fn NormalizeToRadians( f as double ) return fn Normalize( f, 2 * M_PI ) end fn = 0.0 + +double local fn d2g( f as double ) return f * 10 / 9 end fn = 0.0 +double local fn d2m( f as double ) return f * 160 / 9 end fn = 0.0 +double local fn d2r( f as double ) return f * M_PI / 180 end fn = 0.0 + +double local fn g2d( f as double ) return f * 9 / 10 end fn = 0.0 +double local fn g2m( f as double ) return f * 16 end fn = 0.0 +double local fn g2r( f as double ) return f * M_PI / 200 end fn = 0.0 + +double local fn m2d( f as double ) return f * 9 / 160 end fn = 0.0 +double local fn m2g( f as double ) return f / 16 end fn = 0.0 +double local fn m2r( f as double ) return f * M_PI / 3200 end fn = 0.0 + +double local fn r2d( f as double ) return f * 180 / M_PI end fn = 0.0 +double local fn r2g( f as double ) return f * 200 / M_PI end fn = 0.0 +double local fn r2m( f as double ) return f * 3200 / M_PI end fn = 0.0 + +local fn CalculateDegrees + CFArrayRef angles = @[@-2, @-1, @0, @1, @2, @6.2831853, @16, @57.2957795, @359, @6399, @1000000] + double angle, degrees, gradians, mils, radians + NSUInteger i + CFStringRef unit + CFStringRef dashpad = fn StringByPaddingToLength( @"", 73, @"-", 0 ) + + ptr anglePtr = fn StringUTF8String( @"Angle" ) + ptr unitPtr = fn StringUTF8String( @"Unit" ) + ptr normalPtr = fn StringUTF8String( @"Normalized" ) + ptr gradiansPtr = fn StringUTF8String( @"Gradians" ) + ptr milsPtr = fn StringUTF8String( @"Mils" ) + ptr radiansPtr = fn StringUTF8String( @"Radians" ) + + // Header + NSLog( @"\n%@", dashpad ) + NSLog( @"%13s %5s %15s %10s %7s %15s", anglePtr, unitPtr, normalPtr, gradiansPtr, milsPtr, radiansPtr ) + NSLog( @"%@", dashpad ) + + // Degrees + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Degrees" + degrees = fn NormalizeToDegrees( angle ) + gradians = fn NormalizeToGradians( fn d2g( degrees ) ) + mils = fn NormalizeToMils( fn d2m( degrees ) ) + radians = fn NormalizeToRadians( fn d2r( degrees ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"" ) + + // Gradians + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Gradians" + gradians = fn NormalizeToGradians( angle ) + degrees = fn NormalizeToDegrees( fn g2d( gradians ) ) + mils = fn NormalizeToMils( fn g2m( gradians ) ) + radians = fn NormalizeToRadians( fn g2r( gradians ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"" ) + + // Mils + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Mils" + mils = fn NormalizeToMils( angle ) + degrees = fn NormalizeToDegrees( fn m2d( mils ) ) + gradians = fn NormalizeToGradians( fn m2g( mils ) ) + radians = fn NormalizeToRadians( fn m2r( mils ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"" ) + + // Radians + for i = 0 to fn ArrayCount( angles ) - 1 + angle = dblval( angles[i] ) + unit = @"Radians" + radians = fn NormalizeToRadians( angle ) + degrees = fn NormalizeToDegrees( fn r2d( radians ) ) + gradians = fn NormalizeToGradians( fn r2g( radians ) ) + mils = fn NormalizeToMils( fn r2m( radians ) ) + NSLog( @"%13.4f %-10s % -12.4f % -11.4f % -12.4f % -13.4f", angle, fn StringUTF8String( unit ), degrees, gradians, mils, radians ) + next + NSLog( @"%@", dashpad ) +end fn + +fn CalculateDegrees + +HandleEvents diff --git a/Task/Animate-a-pendulum/Locomotive-Basic/animate-a-pendulum.basic b/Task/Animate-a-pendulum/Locomotive-Basic/animate-a-pendulum.basic new file mode 100644 index 0000000000..151efccb41 --- /dev/null +++ b/Task/Animate-a-pendulum/Locomotive-Basic/animate-a-pendulum.basic @@ -0,0 +1,16 @@ +10 mode 1 +20 theta=pi/2 +30 g=9.81 +40 l=1 +50 sp=0 : px=320 : py=300 : bx=px : by=py +100 move bx-4,by+4:graphics pen 0:tag:print chr$(231);:tagoff +110 move px,py:draw bx,by +120 bx=px+l*250*sin(theta) +130 by=py+l*250*cos(theta) +140 move bx-4,by+4:graphics pen 1:tag:print chr$(231);:tagoff +150 move px,py:draw bx,by +160 accel=g*sin(theta)/l/100 +170 sp=sp+accel/100 +180 theta=theta+sp +190 frame +200 goto 100 diff --git a/Task/Animate-a-pendulum/Nim/animate-a-pendulum-2.nim b/Task/Animate-a-pendulum/Nim/animate-a-pendulum-2.nim index 106527b8c9..d21ca79c40 100644 --- a/Task/Animate-a-pendulum/Nim/animate-a-pendulum-2.nim +++ b/Task/Animate-a-pendulum/Nim/animate-a-pendulum-2.nim @@ -3,82 +3,74 @@ import math import times -import gintro/[gobject, gdk, gtk, gio, cairo] -import gintro/glib except Pi +import gtk2 except update +import gdk2, glib2, cairo type # Description of the simulation. - Simulation = ref object - area: DrawingArea # Drawing area. + Simulation = object + area: PDrawingArea # Drawing area. length: float # Pendulum length. g: float # Gravity (should be positive). time: Time # Current time. theta0: float # initial angle. - theta: float # Current angle. + theta: float # Current drawangle. omega: float # Angular velocity = derivative of theta. accel: float # Angular acceleration = derivative of omega. e: float # Total energy. -#--------------------------------------------------------------------------------------------------- -proc newSimulation(area: DrawingArea; length, g, theta0: float): Simulation {.noInit.} = - ## Allocate and initialize the simulation object. +proc initSimulation(area: PDrawingArea; length, g, theta0: float): Simulation {.noInit.} = + ## Initialize a simulation object. - new(result) - result.area = area - result.length = length - result.g = g - result.time = getTime() - result.theta0 = theta0 - result.theta = theta0 - result.omega = 0 - result.accel = -g / length * sin(theta0) - result.e = g * length * (1 - cos(theta0)) # Total energy = potential energy when starting. + result = Simulation( + area: area, length: length, g: g, time: getTime(), + theta0: theta0, theta: theta0, omega: 0, + accel: -g / length * sin(theta0), + e: g * length * (1 - cos(theta0))) # Total energy = potential energy when starting. -#--------------------------------------------------------------------------------------------------- template toFloat(dt: Duration): float = dt.inNanoseconds.float / 1e9 -#--------------------------------------------------------------------------------------------------- const Origin = (x: 320.0, y: 100.0) # Pivot coordinates. const Scale = 300 # Coordinates scaling constant. -proc draw(sim: Simulation; context: cairo.Context) = + +proc draw(sim: var Simulation; context: ptr Context) = ## Draw the pendulum. - # Compute coordinates in drawing area. + # Compute coordinates in drawing draw. let x = Origin.x + sin(sim.theta) * Scale let y = Origin.y + cos(sim.theta) * Scale - # Clear the region. + # Clear the region.draw context.moveTo(0, 0) - context.setSource(0.0, 0.0, 0.0) + context.setSourceRgb(0.0, 0.0, 0.0) context.paint() # Draw pendulum. context.moveTo(Origin.x, Origin.y) - context.setSource(0.3, 1.0, 0.3) + context.setSourceRgb(0.3, 1.0, 0.3) context.lineTo(x, y) context.stroke() # Draw pivot. - context.setSource(0.3, 0.3, 1.0) + context.setSourceRgb(0.3, 0.3, 1.0) context.arc(Origin.x, Origin.y, 8, 0, 2 * Pi) context.fill() # Draw mass. - context.setSource(1.0, 0.3, 0.3) + context.setSourceRgb(1.0, 0.3, 0.3) context.arc(x, y, 8, 0, 2 * Pi) context.fill() -#--------------------------------------------------------------------------------------------------- -proc update(sim: Simulation): gboolean = +proc update(sim: var Simulation): gboolean = ## Update the simulation state. - # compute time interval. + # Compute time interval. let nextTime = getTime() let dt = (nextTime - sim.time).toFloat sim.time = nextTime @@ -100,26 +92,25 @@ proc update(sim: Simulation): gboolean = sim.draw(sim.area.window.cairoCreate()) -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Quit the application. + mainQuit() - let window = app.newApplicationWindow() - window.setSizeRequest(640, 480) - window.setTitle("Pendulum simulation") - let area = newDrawingArea() - window.add(area) +nimInit() - let sim = newSimulation(area, length = 5, g = 9.81, theta0 = PI / 3) +let window = windowNew(WINDOW_TOPLEVEL) +window.setSizeRequest(640, 480) +window.setTitle("Pendulum simulation") - timeoutAdd(10, update, sim) +let area = drawingAreaNew() +window.add area +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - window.showAll() +var sim = initSimulation(area, length = 5, g = 9.81, theta0 = PI / 3) -#——————————————————————————————————————————————————————————————————————————————————————————————————— +discard timeoutAdd(10, cast[gtk2.TFunction](update), sim.addr) -let app = newApplication(Application, "Rosetta.pendulum") -discard app.connect("activate", activate) -discard app.run() +window.showAll() +main() diff --git a/Task/Animation/EasyLang/animation.easy b/Task/Animation/EasyLang/animation.easy index 93d6d938cc..82c5470808 100644 --- a/Task/Animation/EasyLang/animation.easy +++ b/Task/Animation/EasyLang/animation.easy @@ -1,5 +1,5 @@ s$ = "Hello world! " -textsize 16 +textsize 14 lg = len s$ on timer color 333 @@ -7,13 +7,13 @@ on timer rect 80 20 color 999 move 12 24 - text s$ - if forw = 0 + text substr s$ 1 9 + if forw = 1 s$ = substr s$ lg 1 & substr s$ 1 (lg - 1) else s$ = substr s$ 2 (lg - 1) & substr s$ 1 1 . - timer 0.2 + timer 0.4 . on mouse_down if mouse_x > 10 and mouse_x < 90 diff --git a/Task/Animation/Nim/animation.nim b/Task/Animation/Nim/animation.nim index bb2821a478..bbb4e4ecce 100644 --- a/Task/Animation/Nim/animation.nim +++ b/Task/Animation/Nim/animation.nim @@ -1,4 +1,4 @@ -import gintro/[glib, gobject, gdk, gtk, gio] +import gtk2, gdk2, glib2 type @@ -6,56 +6,56 @@ type ScrollDirection = enum toLeft, toRight # Data transmitted to update callback. - UpdateData = ref object - label: Label + UpdateData = object + label: PLabel scrollDir: ScrollDirection -#--------------------------------------------------------------------------------------------------- -proc update(data: UpdateData): gboolean = +proc update(data: var UpdateData): gboolean {.cdecl.} = ## Update the text, scrolling to the right or to the left according to "data.scrollDir". - - data.label.setText(if data.scrollDir == toRight: data.label.text[^1] & data.label.text[0..^2] - else: data.label.text[1..^1] & data.label.text[0]) + let text = $data.label.text # Get text as a Nim string. + let newText = if data.scrollDir == toRight: text[^1] & text[0..^2] + else: text[1..^1] & text[0] + data.label.setText(newText.cstring) result = gboolean(1) -#--------------------------------------------------------------------------------------------------- -proc changeScrollingDir(evtBox: EventBox; event: EventButton; data: UpdateData): bool = +proc changeScrollingDir(evtBox: PEventBox; event: PEventButton; data: ptr UpdateData): bool = ## Change scrolling direction. - data.scrollDir = ScrollDirection(1 - ord(data.scrollDir)) -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: Pgpointer): gboolean {.cdecl.} = + ## Process the "destroy" event. + main_quit() - let window = app.newApplicationWindow() - window.setSizeRequest(150, 50) - window.setTitle("Animation") - # Create an event box to catch the button press event. - let evtBox = newEventBox() - window.add(evtBox) - # Create the label and add it to the event box. - let label = newLabel("Hello World! ") - evtBox.add(label) +nim_init() - # Create the update data. - let data = UpdateData(label: label, scrollDir: toRight) +let window = window_new(WINDOW_TOPLEVEL) +window.set_size_request(150, 50) +window.set_title("Animation") - # Connect the "button-press-event" to the callback to change scrolling direction. - discard evtBox.connect("button-press-event", changeScrollingDir, data) +# Create an event box to catch the button press event. +let evtBox = event_box_new() +window.add evtBox - # Create a timer to update the label and simulate scrolling. - timeoutAdd(200, update, data) +# Create the label and add it to the event box. +let label = label_new("Hello World! ") +evtBox.add label - window.showAll() +# Create the update data. +var data = UpdateData(label: label, scrollDir: toRight) -#——————————————————————————————————————————————————————————————————————————————————————————————————— +# Connect the "button-press-event" to the callback to change the scrolling direction. +discard evtBox.signal_connect("button-press-event", SIGNAL_FUNC(changeScrollingDir), data.addr) -let app = newApplication(Application, "Rosetta.animation") -discard app.connect("activate", activate) -discard app.run() +# Quit the application if the window is closed. +discard window.signal_connect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) + +# Create a timer to update the label and simulate scrolling. +discard timeout_add(200, cast[gtk2.TFunction](animation.update), data.addr) + +window.showAll() +main() diff --git a/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur b/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur index 67108b6065..61d90f3fb8 100644 --- a/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur +++ b/Task/Apply-a-callback-to-an-array/Langur/apply-a-callback-to-an-array.langur @@ -1 +1 @@ -writeln map(fn{^2}, 1..10) +writeln map(1..10, by=fn{^2}) diff --git a/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur b/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur index ac88ad929c..b7a153403f 100644 --- a/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur +++ b/Task/Arbitrary-precision-integers-included-/Langur/arbitrary-precision-integers-included-.langur @@ -2,8 +2,8 @@ val xs = string(5 ^ 4 ^ 3 ^ 2) writeln len(xs), " digits" -if len(xs) > 39 and s2s(xs, 1..20) == "62060698786608744707" and - s2s(xs, -20 .. -1) == "92256259918212890625" { +if len(xs) > 39 and s2s(xs, of=1..20) == "62060698786608744707" and + s2s(xs, of=-20 .. -1) == "92256259918212890625" { writeln "SUCCESS" } diff --git a/Task/Arbitrary-precision-integers-included-/M2000-Interpreter/arbitrary-precision-integers-included-.m2000 b/Task/Arbitrary-precision-integers-included-/M2000-Interpreter/arbitrary-precision-integers-included-.m2000 new file mode 100644 index 0000000000..5869a47e0f --- /dev/null +++ b/Task/Arbitrary-precision-integers-included-/M2000-Interpreter/arbitrary-precision-integers-included-.m2000 @@ -0,0 +1,17 @@ +module checkit { + z=4^(3^2) + z1=z/1024-1 + m=Biginteger("5") + with m, "ToString" as m.ToString + p=Biginteger("1024") + method m, "intpower", p as m1 + m=m1 + for i=1 to z1 + method m1, "multiply", m as m + ? len(m.tostring), i + refresh + next + a=m.tostring + Print left$(a, 20)+"..."+Right$(a,20) +} +checkit diff --git a/Task/Archimedean-spiral/Ada/archimedean-spiral.ada b/Task/Archimedean-spiral/Ada/archimedean-spiral.ada index 0cdfaae32f..e949fa2f1f 100644 --- a/Task/Archimedean-spiral/Ada/archimedean-spiral.ada +++ b/Task/Archimedean-spiral/Ada/archimedean-spiral.ada @@ -1,17 +1,18 @@ with Ada.Numerics.Elementary_Functions; with SDL.Video.Windows.Makers; +with SDL.Video.Rectangles; with SDL.Video.Renderers.Makers; with SDL.Events.Events; procedure Archimedean_Spiral is - Width : constant := 800; - Height : constant := 800; - A : constant := 4.2; - B : constant := 3.2; - T_First : constant := 4.0; - T_Last : constant := 100.0; + Width : constant := 800; + Height : constant := 800; + A : constant := 4.2; + B : constant := 3.2; + T_First : constant := 4.0; + T_Last : constant := 100.0; Window : SDL.Video.Windows.Window; Renderer : SDL.Video.Renderers.Renderer; @@ -29,8 +30,10 @@ procedure Archimedean_Spiral is loop R := A + B * T; Renderer.Draw - (Point => (X => Width / 2 + SDL.C.int (R * Cos (T, 2.0 * Pi)), - Y => Height / 2 - SDL.C.int (R * Sin (T, 2.0 * Pi)))); + (Point => + SDL.Video.Rectangles.Point' + (X => Width / 2 + SDL.C.int (R * Cos (T, 2.0 * Pi)), + Y => Height / 2 - SDL.C.int (R * Sin (T, 2.0 * Pi)))); exit when T >= T_Last; T := T + Step; end loop; @@ -53,14 +56,16 @@ begin return; end if; - SDL.Video.Windows.Makers.Create (Win => Window, - Title => "Archimedean spiral", - Position => SDL.Natural_Coordinates'(X => 10, Y => 10), - Size => SDL.Positive_Sizes'(Width, Height), - Flags => 0); + SDL.Video.Windows.Makers.Create + (Win => Window, + Title => "Archimedean spiral", + Position => SDL.Natural_Coordinates'(X => 10, Y => 10), + Size => SDL.Positive_Sizes'(Width, Height), + Flags => 0); SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); Renderer.Set_Draw_Colour ((0, 0, 0, 255)); - Renderer.Fill (Rectangle => (0, 0, Width, Height)); + Renderer.Fill + (Rectangle => SDL.Video.Rectangles.Rectangle'(0, 0, Width, Height)); Renderer.Set_Draw_Colour ((0, 220, 0, 255)); Draw_Archimedean_Spiral; diff --git a/Task/Archimedean-spiral/Aquarius-BASIC/archimedean-spiral.basic b/Task/Archimedean-spiral/Aquarius-BASIC/archimedean-spiral.basic new file mode 100644 index 0000000000..fc325caa2a --- /dev/null +++ b/Task/Archimedean-spiral/Aquarius-BASIC/archimedean-spiral.basic @@ -0,0 +1,8 @@ +10 PRINT CHR$(11); +20 PI=3.141593 +30 FOR I=0 TO 1080 +40 R=I/42+2 +50 X=R*SIN(I*PI/180) +60 Y=R*COS(I*PI/180)*1.4 +70 PSET(39+X,33+Y) +80 NEXT diff --git a/Task/Archimedean-spiral/Atari-BASIC/archimedean-spiral.basic b/Task/Archimedean-spiral/Atari-BASIC/archimedean-spiral.basic new file mode 100644 index 0000000000..ff20bc9dcf --- /dev/null +++ b/Task/Archimedean-spiral/Atari-BASIC/archimedean-spiral.basic @@ -0,0 +1,9 @@ +10 GRAPHICS 8:COLOR 0:DEG +20 N=5.4 +30 FOR I=0 TO N*360 STEP 10 +40 R=I/24+4 +50 X=R*SIN(I) +60 Y=R*COS(I) +70 DRAWTO 160+X,80+Y +80 COLOR 1 +90 NEXT I diff --git a/Task/Archimedean-spiral/Crystal/archimedean-spiral.cr b/Task/Archimedean-spiral/Crystal/archimedean-spiral.cr new file mode 100644 index 0000000000..8644de1114 --- /dev/null +++ b/Task/Archimedean-spiral/Crystal/archimedean-spiral.cr @@ -0,0 +1,42 @@ +# output utilities -- solution starts after them +def print_line (line) + (0..line[0].size-1).step(2) do |i| + char = ((line[0][i] | line[1][i] << 1 | line[2][i] << 2 | + line[0][i+1] << 3 | line[1][i+1] << 4 | line[2][i+1] << 5 | + line[3][i] << 6 | line[3][i+1] << 7) + 0x2800).chr + print char + end + puts +end + +def print_dots (coords, screen_width) + coords = coords.sort_by {|x, y| y} + left, right = coords.map(&.first).minmax + if screen_width.odd? + screen_width -= 1 + end + factor = screen_width / (right - left + 1) + line = (0..3).map { Array(UInt32).new(screen_width, 0) } + row = (coords[0].last * factor).to_i + coords.map {|x, y| {((x - left) * factor).to_i, (y * factor).to_i} }.each do |x, y| + while y > row+3 + print_line line + line.each do |stripe| stripe.fill(0) end + row += 4 + end + line[y - row][x] = 1 + end + print_line line +end + +# actual solution starts here: + +def spiral (a, b, step_resolution, step_count) + start, stop = 0.0, step_count * step_resolution + (start..stop).step(step_resolution).map { |theta| + r = a + b * theta + { r * Math.cos(theta), r * Math.sin(theta) } + }.to_a +end + +print_dots(spiral(10, 10, 0.01, 4000), 60) diff --git a/Task/Archimedean-spiral/M2000-Interpreter/archimedean-spiral.m2000 b/Task/Archimedean-spiral/M2000-Interpreter/archimedean-spiral.m2000 index 5f9e9e7555..49b7017044 100644 --- a/Task/Archimedean-spiral/M2000-Interpreter/archimedean-spiral.m2000 +++ b/Task/Archimedean-spiral/M2000-Interpreter/archimedean-spiral.m2000 @@ -5,7 +5,7 @@ module Archimedean_spiral { pen #FFFF00 refresh 5000 every 1000 { - \\ redifine window (console width and height) and place it to center (symbol ;) + \\ redefine window (console width and height) and place it to center (symbol ;) Window 12, random(10, 18)*1000, random(8, 12)*1000; move scale.x/2, scale.y/2 let N=2, k1=pi/120, k=k1, op=5, op1=1 diff --git a/Task/Archimedean-spiral/Nim/archimedean-spiral.nim b/Task/Archimedean-spiral/Nim/archimedean-spiral.nim index 004dbe69f8..fec5dd2a2b 100644 --- a/Task/Archimedean-spiral/Nim/archimedean-spiral.nim +++ b/Task/Archimedean-spiral/Nim/archimedean-spiral.nim @@ -1,38 +1,38 @@ -import math - -import gintro/[glib, gobject, gtk, gio, cairo] +import std/math +import cairo const - Width = 601 - Height = 601 + Width = 400 + Height = 400 Limit = 12 * math.PI Origin = (x: float(Width div 2), y: float(Height div 2)) B = floor((Width div 2) / Limit) -#--------------------------------------------------------------------------------------------------- -proc draw(area: DrawingArea; context: Context) = +proc drawSpiral(surface: ptr Surface) = ## Draw the spiral. + let context = create(surface) + var theta = 0.0 var delta = 0.01 var (prevx, prevy) = Origin # Clear the region. context.moveTo(0, 0) - context.setSource(0.0, 0.0, 0.0) + context.setSourceRgb(0.0, 0.0, 0.0) context.paint() # Draw the spiral. - context.setSource(1.0, 1.0, 0.0) + context.setSourceRgb(1.0, 1.0, 0.0) context.moveTo(Origin.x, Origin.y) while theta < Limit: let r = B * theta - let x = Origin.x + r * cos(theta) # X-coordinate on drawing area. - let y = Origin.y + r * sin(theta) # Y-coordinate on drawing area. + let x = Origin.x + r * cos(theta) + let y = Origin.y + r * sin(theta) context.lineTo(x, y) context.stroke() # Set data for next round. @@ -41,34 +41,11 @@ proc draw(area: DrawingArea; context: Context) = prevy = y theta += delta -#--------------------------------------------------------------------------------------------------- + context.destroy() -proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = - ## Callback to draw/redraw the drawing area contents. - area.draw(context) - result = true - -#--------------------------------------------------------------------------------------------------- - -proc activate(app: Application) = - ## Activate the application. - - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Archimedean spiral") - - # Create the drawing area. - let area = newDrawingArea() - window.add(area) - - # Connect the "draw" event to the callback to draw the spiral. - discard area.connect("draw", ondraw, pointer(nil)) - - window.showAll() - -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.spiral") -discard app.connect("activate", activate) -discard app.run() +let surface = imageSurfaceCreate(FormatRgb24, Width, Height) +surface.drawSpiral() +if surface.writeToPng("archimedean_spiral.png") != StatusSuccess: + quit "Error while saving file.", QuitFailure +surface.destroy() diff --git a/Task/Arithmetic-Complex/Langur/arithmetic-complex.langur b/Task/Arithmetic-Complex/Langur/arithmetic-complex.langur new file mode 100644 index 0000000000..07c6898485 --- /dev/null +++ b/Task/Arithmetic-Complex/Langur/arithmetic-complex.langur @@ -0,0 +1,22 @@ +val conjugate = fn(c) { + if c is not complex: throw "expected complex number" + return complex(c[1], -c[2]) +} + +val examples = { + "-(1+1i)": -(1+1i), + "abs(1+1i)": abs(1+1i), + "(2+2i) + (5+13.2i)": (2+2i) + (5+13.2i), + "5 + (2+2i)": 5 + (2+2i), + "5i + (2+2i)": 5i + (2+2i), + "5i - (2+2i)": 5i - (2+2i), + "(1+1i) * (3.141592653589793+1.2i)": (1+1i) * (3.141592653589793+1.2i), + "(5+3i) / (4-3i)": (5+3i) / (4-3i), + "1 / (4-3i)": 1 / (4-3i), + "(4-3i) ^ 3": (4-3i) ^ 3, + "conjugate(7+21.0i)": conjugate(7+21.0i), +} + +for e of examples { + writeln "{{e : 20}}: ", examples[e] +} diff --git a/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex.m2000 b/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex.m2000 new file mode 100644 index 0000000000..4d894f3c26 --- /dev/null +++ b/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex.m2000 @@ -0,0 +1,152 @@ +Class Complex { +private: + double vr, vi +public: + property real { + value {link parent vr to vr : value=vr} + } + property imaginary { + value {link parent vi to vi : value=vi} + } + property toString { + value { + clear + ' so default variable VALUE deleted and again defined it as string + link parent vr, vi to vr, vi + if vi then + if vr then + if vi>0 then + if vi==1 then + value="("+vr+"+i)" + else + value="("+vr+"+"+vi+"i)" + end if + else + if vi==-1 then + value="("+vr+"-i)" + else + value="("+vr+""+vi+"i)" + end if + end if + else + if vi=1 then + value="(i)" + else.if vi=-1 then + value="(-i)" + else + value="("+vi+"i)" + end if + end if + else + value="("+vr+")" + end if + } + } + function final Arg { + declare m math + Method m, "Atan2", .vi, .vr as ret + =ret + } + function final exp(rr=10) { + double exp = 2.71828182845905^.vr + c=this + th=.vi/1.74532925199433E-02 + c.vr<=round(exp * cos(th), rr) + c.vi<=round(exp * sin(th),rr) + =c + } + function final cabs { + if abs(.vr)=infinity or abs(.vi)=infinity then + =1.7976931348623157E+308 : break + end if + double c=abs(.vr), d=abs(.vi) + if c>d then + r=d/c : =c*sqrt(1+r*r) + else.if d==0 then + =c + else + r=c/d : =d*sqrt(1+r*r) + end if + } + function final clog { + c=this + c.vr<=ln(.cabs()) + c.vi<=.Arg() + =c + } + function final pow { + if match("G") then + read p as Complex + else + read p1 as double + p=this:p.vr=p1:p.vi=0 + end if + Read ? rr=10 + exp=.clog()*p + c=exp.exp(rr) + c.vr=round(c.vr, rr) + c.vi=round(c.vi, rr) + =c + } + function final inv { + if .vr==0 and .vi==0 then error "zero complex num" + acb=this.conj() + c=this*acb + c.vi <= acb.vi/c.vr + c.vr <= acb.vr/c.vr + =c + } + function final conj { + c=this : c.vi-! : =c + } + function final absc { + c=this*.conj() : =sqrt(c.vr) + } + operator final "+" { + read k as Complex : .vr+= k.vr : .vi+= k.vi + } + operator final "-" { + read k as Complex : .vr-= k.vr : .vi-= k.vi + } + operator final high "*" { + read k as Complex + double ivr = .vr*k.vr-.vi*k.vi + .vi <= .vi*k.vr+.vr*k.vi + .vr <= ivr + } + operator final high "/" { + read k as Complex + k1=k*k.conj() + acb = this*k.conj() + .vr <= acb.vr/k1.vr + .vi <= acb.vi/k1.vr + } + operator final unary { + .vr-! + .vi-! + } + +class: + module Complex (.vr, .vi) {} +} +Module Check (filename as string="") { + def f(x)=x.toString + a=Complex(8,-3) + b=a.inv() + open filename for wide output as #f + Print #f, "A="+a.toString + Print #f, " r=";a.cabs();" θ=";a.Arg();" rad" + Print #f, "B="+b.toString+" as 1/A" + Print #f, " r=";b.cabs();" θ=";b.Arg();" rad" + Print #f, a.toString+"*"+b.toString+"="+f(a*b) + Print #f, Complex(1).toString+"/"+b.toString+"="+f(Complex(1)/b) + Print #f, a.toString+"/"+a.toString+"="+f(a/a) + Print #f, a.toString+"+"+a.toString+"="+f(a+a) + Print #f, a.toString+"-"+a.toString+"="+f(a-a) + Print #f, "-"+a.toString+"="+f(-a) + Print #f, "e^(πi)+1="+f(Complex(2.71828182845905).pow(Complex(0,pi))+Complex(1)) + close #f + if filename<>"" then if exist(filename) then win "notepad", dir$+filename +} +Check "out.txt" +Check ' just show here diff --git a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx index e58b2f326c..fd21689cfc 100644 --- a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx +++ b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx @@ -1,23 +1,38 @@ -/*REXX program demonstrates how to support some math functions for complex numbers. */ -x = '(5,3i)' /*define X ─── can use I i J or j */ -y = "( .5, 6j)" /*define Y " " " " " " " */ +include Settings -say ' addition: ' x " + " y ' = ' Cadd(x, y) -say ' subtraction: ' x " - " y ' = ' Csub(x, y) -say 'multiplication: ' x " * " y ' = ' Cmul(x, y) -say ' division: ' x " ÷ " y ' = ' Cdiv(x, y) -say ' inverse: ' x " = " Cinv(x, y) -say ' conjugate of: ' x " = " Conj(x, y) -say ' negation of: ' x " = " Cneg(x, y) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Conj: procedure; parse arg a ',' b,c ',' d; call C#; return C$( a , -b ) -Cadd: procedure; parse arg a ',' b,c ',' d; call C#; return C$( a+c , b+d ) -Csub: procedure; parse arg a ',' b,c ',' d; call C#; return C$( a-c , b-d ) -Cmul: procedure; parse arg a ',' b,c ',' d; call C#; return C$( ac-bd , bc+ad) -Cdiv: procedure; parse arg a ',' b,c ',' d; call C#; return C$((ac+bd)/s, (bc-ad)/s) -Cinv: return Cdiv(1, arg(1)) -Cneg: return Cmul(arg(1), -1) -C_: return word(translate(arg(1), , '{[(JjIi)]}') 0, 1) /*get # or 0*/ -C#: a=C_(a); b=C_(b); c=C_(c); d=C_(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d;s=c*c+d*d; return -C$: parse arg r,c; _='['r; if c\=0 then _=_","c'j'; return _"]" /*uses j */ +say version; say 'Arithmetic numbers'; say +numeric digits 9 +divi. = 0; a = 0; c = 0 +do i = 1 +/* Is the number arithmetic? */ + if Arithmetic(i) then do + a = a+1 +/* Is the number composite? */ + if divi.0 > 2 then + c = c+1 +/* Output control */ + if a <= 100 then do + if a = 1 then + say 'First 100 arithmetic numbers are' + call Charout ,Right(i,4) + if a//10 = 0 then + say + if a = 100 then + say + end + if a = 100 | a = 1000 | a = 10000 | a = 100000 | a = 1000000 then do + say 'The' a'th arithmetic number is' i + say 'Of the first' a 'numbers' c 'are composite' + say + end +/* Max 1m, higher takes too long */ + if a = 1000000 then + leave + end +end +say Format(Time('e'),,3) 'seconds' +exit + +include Numbers +include Functions +include Abend diff --git a/Task/Arithmetic-Complex/Uiua/arithmetic-complex.uiua b/Task/Arithmetic-Complex/Uiua/arithmetic-complex.uiua new file mode 100644 index 0000000000..411190a2d5 --- /dev/null +++ b/Task/Arithmetic-Complex/Uiua/arithmetic-complex.uiua @@ -0,0 +1,11 @@ +Za ← ℂ 3 1.5 # 1.5+3i +Zb ← ℂ 1.5 1.5 # 1.5+1.5i ++ Zb Za +- Zb Za +× Zb Za +÷ Zb Za +¯Za +ℂ¯ °ℂ Za +⌵ Za +ⁿ Zb Za +°ℂZa diff --git a/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig b/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig new file mode 100644 index 0000000000..564d8cc2b4 --- /dev/null +++ b/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig @@ -0,0 +1,23 @@ +const std = @import("std"); + +pub fn main() !void { + var buf: [1024]u8 = undefined; + const reader = std.io.getStdIn().reader(); + const stdout = std.io.getStdOut().writer(); + try stdout.writeAll("Enter two integers separated by a space: "); + const input = try reader.readUntilDelimiter(&buf, '\n'); + const text = std.mem.trimRight(u8, input, "\r\n"); + + var it = std.mem.tokenizeScalar(u8, text, ' '); + + const a = try std.fmt.parseInt(i64, it.next().?, 10); + const b = try std.fmt.parseInt(i64, it.next().?, 10); + + try stdout.print("Values: a {d} b {d}\n", .{a, b}); + try stdout.print("Sum: a + b = {d}\n", .{a + b}); + try stdout.print("Difference: a - b = {d}\n", .{a - b}); + try stdout.print("Product: a * b = {d}\n", .{a * b}); + try stdout.print("Integer quotient: a / b = {d}\n", .{@divTrunc(a, b)}); //truncates towards 0 + try stdout.print("Remainder: a % b = {d}\n", .{@rem(a, b)}); // same sign as first operand + try stdout.print("Exponentiation: math.pow = {d}\n", .{std.math.pow(i64, a, b)}); //no exponentiation operator +} diff --git a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx index 4d17ceb166..16e57b5dcc 100644 --- a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx +++ b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx @@ -1,87 +1,62 @@ -/*REXX program implements a reasonably complete rational arithmetic (using fractions).*/ -L=length(2**19 - 1) /*saves time by checking even numbers. */ - do j=2 by 2 to 2**19 - 1; s=0 /*ignore unity (which can't be perfect)*/ - mostDivs=eDivs(j); @= /*obtain divisors>1; zero sum; null @. */ - do k=1 for words(mostDivs) /*unity isn't return from eDivs here.*/ - r='1/'word(mostDivs, k); @=@ r; s=$fun(r, , s) - end /*k*/ - if s\==1 then iterate /*Is sum not equal to unity? Skip it.*/ - say 'perfect number:' right(j, L) " fractions:" @ - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -$div: procedure; parse arg x; x=space(x,0); f= 'fractional division' - parse var x n '/' d; d=p(d 1) - if d=0 then call err 'division by zero:' x - if \datatype(n,'N') then call err 'a non─numeric numerator:' x - if \datatype(d,'N') then call err 'a non─numeric denominator:' x - return n/d -/*──────────────────────────────────────────────────────────────────────────────────────*/ -$fun: procedure; parse arg z.1,,z.2 1 zz.2; arg ,op; op=p(op '+') -F= 'fractionalFunction'; do j=1 for 2; z.j=translate(z.j, '/', "_"); end /*j*/ -if abbrev('ADD' , op) then op= "+" -if abbrev('DIVIDE' , op) then op= "/" -if abbrev('INTDIVIDE', op, 4) then op= "÷" -if abbrev('MODULUS' , op, 3) | abbrev('MODULO', op, 3) then op= "//" -if abbrev('MULTIPLY' , op) then op= "*" -if abbrev('POWER' , op) then op= "^" -if abbrev('SUBTRACT' , op) then op= "-" -if z.1=='' then z.1= (op\=="+" & op\=='-') -if z.2=='' then z.2= (op\=="+" & op\=='-') -z_=z.2 - /* [↑] verification of both fractions.*/ - do j=1 for 2 - if pos('/', z.j)==0 then z.j=z.j"/1"; parse var z.j n.j '/' d.j - if \datatype(n.j,'N') then call err 'a non─numeric numerator:' n.j - if \datatype(d.j,'N') then call err 'a non─numeric denominator:' d.j - if d.j=0 then call err 'a denominator of zero:' d.j - n.j=n.j/1; d.j=d.j/1 - do while \datatype(n.j,'W'); n.j=(n.j*10)/1; d.j=(d.j*10)/1 - end /*while*/ /* [↑] {xxx/1} normalizes a number. */ - g=gcd(n.j, d.j); if g=0 then iterate; n.j=n.j/g; d.j=d.j/g - end /*j*/ +include Settings - select - when op=='+' | op=='-' then do; l=lcm(d.1,d.2); do j=1 for 2; n.j=l*n.j/d.j; d.j=l - end /*j*/ - if op=='-' then n.2= -n.2; t=n.1 + n.2; u=l - end - when op=='**' | op=='↑' |, - op=='^' then do; if \datatype(z_,'W') then call err 'a non─integer power:' z_ - t=1; u=1; do j=1 for abs(z_); t=t*n.1; u=u*d.1 - end /*j*/ - if z_<0 then parse value t u with u t /*swap U and T */ - end - when op=='/' then do; if n.2=0 then call err 'a zero divisor:' zz.2 - t=n.1*d.2; u=n.2*d.1 - end - when op=='÷' then do; if n.2=0 then call err 'a zero divisor:' zz.2 - t=trunc($div(n.1 '/' d.1)); u=1 - end /* [↑] this is integer division. */ - when op=='//' then do; if n.2=0 then call err 'a zero divisor:' zz.2 - _=trunc($div(n.1 '/' d.1)); t=_ - trunc(_) * d.1; u=1 - end /* [↑] modulus division. */ - when op=='ABS' then do; t=abs(n.1); u=abs(d.1); end - when op=='*' then do; t=n.1 * n.2; u=d.1 * d.2; end - when op=='EQ' | op=='=' then return $div(n.1 '/' d.1) = fDiv(n.2 '/' d.2) - when op=='NE' | op=='\=' | op=='╪' | , - op=='¬=' then return $div(n.1 '/' d.1) \= fDiv(n.2 '/' d.2) - when op=='GT' | op=='>' then return $div(n.1 '/' d.1) > fDiv(n.2 '/' d.2) - when op=='LT' | op=='<' then return $div(n.1 '/' d.1) < fDiv(n.2 '/' d.2) - when op=='GE' | op=='≥' | op=='>=' then return $div(n.1 '/' d.1) >= fDiv(n.2 '/' d.2) - when op=='LE' | op=='≤' | op=='<=' then return $div(n.1 '/' d.1) <= fDiv(n.2 '/' d.2) - otherwise call err 'an illegal function:' op - end /*select*/ +say version; say 'Rational arithmetic'; say +a = '1 2'; b = '-3 4'; c = '5 -6'; d = '-7 -8'; e = 3; f = 1.666666666 +say 'VALUES' +say 'a =' Rlst2form(a) +say 'b =' Rlst2form(b) +say 'c =' Rlst2form(c) +say 'd =' Rlst2form(d) +say 'e =' e +say 'f =' f +say +say 'BASICS' +say 'a+b =' Rlst2form(Radd(a,b)) +say 'a+b+c+d =' Rlst2form(Radd(a,b,c,d)) +say 'a-b =' Rlst2form(Rsub(a,b)) +say 'a-b-c-d =' Rlst2form(Rsub(a,b,c,d)) +say 'a*b =' Rlst2form(Rmul(a,b)) +say 'a*b*c*d =' Rlst2form(Rmul(a,b,c,d)) +say 'a/b =' Rlst2form(Rdiv(a,b)) +say 'a/b/c/d =' Rlst2form(Rdiv(a,b,c,d)) +say '-a =' Rlst2form(Rneg(a)) +say '1/a =' Rlst2form(Rinv(a)) +say +say 'COMPARE' +say 'a=b =' Rge(a,b) +say 'a>b =' Rgt(a,b) +say 'a<>b =' Rne(a,b) +say +say 'BONUS' +say 'Abs(c) =' Rlst2form(Rabs(c)) +say 'Float(b) =' Rfloat(b) +say 'Neg(d) =' Rlst2form(Rneg(d)) +say 'Power(a,e) =' Rlst2form(Rpow(a,e)) +say 'Rational(f) =' Rlst2form(Rrat(f)) +say +say 'FORMULA' +say 'a^2-2ab+3c-4ad^4+5 = ', +Rlst2form(Radd(Rpow(a,2),Rmul(-2,a,b),Rmul(3,c),Rmul(-4,a,Rpow(d,4)),5)) +say +say 'PERFECT NUMBERS' +call time('r') +numeric digits 20 +do c = 6 to 2**19 + s = 1 c; m = Isqrt(c) + do f = 2 to m + if c//f = 0 then do + s = Radd(s,1 f,1 c/f) + end + end + if Req(s,1) then + say c 'is a perfect number' +end +say time('e')/1's' +exit -if t==0 then return 0; g=gcd(t, u); t=t/g; u=u/g -if u==1 then return t - return t'/'u -/*──────────────────────────────────────────────────────────────────────────────────────*/ -eDivs: procedure; parse arg x 1 b,a - do j=2 while j*j>6 + PUT col+1 IN col + IF col mod 10 = 0: WRITE/ + +FOR m IN {1..20}: + WRITE "D(10^`m>>2`) = `(lagarias (10**m))/7`"/ diff --git a/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative.alg b/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative-1.alg similarity index 100% rename from Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative.alg rename to Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative-1.alg diff --git a/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative-2.alg b/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative-2.alg new file mode 100644 index 0000000000..777a307ffd --- /dev/null +++ b/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative-2.alg @@ -0,0 +1,12 @@ +FOR n FROM -99 TO 100 DO + INT l := 0, f := 3, z := ABS n; + WHILE z >= 2 DO + WHILE z MOD 2 = 0 DO l +:= n OVER 2; z OVERAB 2 OD; + IF f <= z THEN + WHILE z MOD f = 0 DO l +:= n OVER f; z OVERAB f OD; + f +:= 2 + FI + OD; + print( ( whole( l, -8 ) ) ); + IF ( n + 100 ) MOD 10 = 0 THEN print( ( newline ) ) FI +OD diff --git a/Task/Arithmetic-derivative/APL/arithmetic-derivative.apl b/Task/Arithmetic-derivative/APL/arithmetic-derivative.apl new file mode 100644 index 0000000000..1c399278d7 --- /dev/null +++ b/Task/Arithmetic-derivative/APL/arithmetic-derivative.apl @@ -0,0 +1,7 @@ +lagarias←{ + ⍵<0:-∇-⍵ + ⍵∊0 1:0 + 0=d←⊃1+⍸0=(1↓⍳⌊⍵*÷2)|⍵:1 + (n×∇d)+d×∇n←⍵÷d +} +lagarias¨ 20 10⍴¯100+⍳200 diff --git a/Task/Arithmetic-derivative/Action-/arithmetic-derivative.action b/Task/Arithmetic-derivative/Action-/arithmetic-derivative.action new file mode 100644 index 0000000000..11a719733d --- /dev/null +++ b/Task/Arithmetic-derivative/Action-/arithmetic-derivative.action @@ -0,0 +1,15 @@ +PROC Main() + INT n, f, l, z + FOR n = -99 TO 100 DO + l = 0 f = 3 IF n < 0 THEN z = - n ELSE z = n FI + WHILE z >= 2 DO + WHILE z MOD 2 = 0 DO l ==+ n / 2 z ==/ 2 OD + IF f <= z THEN + WHILE z MOD f = 0 DO l ==+ n / f z ==/ f OD + f ==+ 2 + FI + OD + PrintF( "%8I", l ) + IF ( n + 100 ) MOD 10 = 0 THEN PutE() FI + OD +RETURN diff --git a/Task/Arithmetic-derivative/Ada/arithmetic-derivative.ada b/Task/Arithmetic-derivative/Ada/arithmetic-derivative.ada new file mode 100644 index 0000000000..9e3a37edda --- /dev/null +++ b/Task/Arithmetic-derivative/Ada/arithmetic-derivative.ada @@ -0,0 +1,55 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; + +procedure Arithmetic_Derivative is + + function D (N : Big_Integer) return Big_Integer is + Inc : Constant array (1 .. 8) of Big_Integer := (4, 2, 4, 2, 4, 6, 2, 6); + I : Integer := 1; + Num : Big_Integer := N; + P : Big_Integer := 2; + PCount : Big_Integer; + Result : Big_Integer := 0; + begin + if N < 0 then return -D(-N); end if; + if N = 0 or N = 1 then return 0; end if; + + while P <= N / 2 loop + if Num mod P = 0 then + PCount := 0; + while Num mod P = 0 loop + Num := Num / P; + PCount := PCount + 1; + end loop; + Result := Result + (PCount * N) / P; + end if; + if Num = 1 then exit; end if; + if P >= 7 then + P := P + Inc(I); + I := (I mod 8) + 1; + end if; + if P = 3 or P = 5 then P := P + 2; end if; + if P = 2 then P := P + 1; end if; + end loop; + + if Num > 1 then return 1; end if; + + return result; + end D; + + P : Big_Integer; + +begin + for I in Integer range -99 .. 100 loop + P := To_Big_Integer(I); + Put(To_String(Arg => D(P), Width => 5)); + if I mod 10 = 0 then New_Line; end if; + end loop; + + for I in Integer range 1 .. 20 loop + P := 10 ** I; + Put("D(10^"); Put(Item => I, Width => 2); Put(") / 7 = "); + Put(Big_Integer'Image(D(P) / 7)); New_Line; + end loop; +end Arithmetic_Derivative; diff --git a/Task/Arithmetic-derivative/BASIC/arithmetic-derivative.basic b/Task/Arithmetic-derivative/BASIC/arithmetic-derivative.basic new file mode 100644 index 0000000000..1c7a401d8e --- /dev/null +++ b/Task/Arithmetic-derivative/BASIC/arithmetic-derivative.basic @@ -0,0 +1,12 @@ +10 DEFINT A-Z +20 FOR N=-99 TO 100 +30 GOSUB 100: PRINT USING "########";L; +40 NEXT +50 END +100 L=0: F=3: Z=ABS(N) +110 IF Z<2 THEN RETURN +120 IF Z MOD 2=0 THEN L=L+N\2: Z=Z\2: GOTO 120 +130 IF F>Z THEN RETURN +140 IF Z MOD F=0 THEN L=L+N\F: Z=Z\F: GOTO 140 +150 F=F+2 +160 GOTO 130 diff --git a/Task/Arithmetic-derivative/CLU/arithmetic-derivative.clu b/Task/Arithmetic-derivative/CLU/arithmetic-derivative.clu new file mode 100644 index 0000000000..15fbee5766 --- /dev/null +++ b/Task/Arithmetic-derivative/CLU/arithmetic-derivative.clu @@ -0,0 +1,44 @@ +factors = iter (n: bigint) yields (bigint) + own zero: bigint := bigint$i2bi(0) + own two: bigint := bigint$i2bi(2) + own three: bigint := bigint$i2bi(3) + + while n>zero cand n//two = zero do yield(two) n := n/two end + + fac: bigint := three + while fac<=n do + while n//fac = zero do yield(fac) n := n/fac end + fac := fac + two + end +end factors + +lagarias = proc (n: bigint) returns (bigint) + own zero: bigint := bigint$i2bi(0) + if n < zero then return(-lagarias(-n)) end + + sum: bigint := zero + for fac: bigint in factors(n) do + sum := sum + n / fac + end + return(sum) +end lagarias + +start_up = proc () + own po: stream := stream$primary_output() + own seven: bigint := bigint$i2bi(7) + own ten: bigint := bigint$i2bi(10) + + for n: int in int$from_to(-99, 100) do + stream$putright(po, bigint$unparse(lagarias(bigint$i2bi(n))), 7) + if (n + 100)//10 = 0 then stream$putl(po, "") end + end + + for m: int in int$from_to(1, 20) do + d: bigint := lagarias(ten ** bigint$i2bi(m)) / seven + stream$puts(po, "D(10^") + stream$putright(po, int$unparse(m), 2) + stream$puts(po, ") / 7 = ") + stream$putright(po, bigint$unparse(d), 25) + stream$putl(po, "") + end +end start_up diff --git a/Task/Arithmetic-derivative/Cowgol/arithmetic-derivative.cowgol b/Task/Arithmetic-derivative/Cowgol/arithmetic-derivative.cowgol new file mode 100644 index 0000000000..5a640ee1c3 --- /dev/null +++ b/Task/Arithmetic-derivative/Cowgol/arithmetic-derivative.cowgol @@ -0,0 +1,43 @@ +include "cowgol.coh"; + +sub abs(n: int32): (r: uint32) is + if n<0 then + r := (-n) as uint32; + else + r := n as uint32; + end if; +end sub; + +sub printcol(n: int32, s: uint8) is + var buf: uint8[12]; + var ptr := IToA(n, 10, &buf[0]); + s := s - (ptr - &buf[0]) as uint8; + while s>0 loop + print_char(' '); + s := s-1; + end loop; + print(&buf[0]); +end sub; + +sub lagarias(n: int32): (r: int32) is + var nn := abs(n); + r := 0; + if nn<2 then return; end if; + var f: uint32 := 2; + while f<=nn loop + while nn%f == 0 loop + r := r + n/f as int32; + nn := nn/f; + end loop; + f := f+1; + end loop; +end sub; + +var i: int32 := -99; +var c: uint8 := 0; +while i <= 100 loop + printcol(lagarias(i), 7); + i := i+1; + c := c+1; + if c%10 == 0 then print_nl(); end if; +end loop; diff --git a/Task/Arithmetic-derivative/Draco/arithmetic-derivative.draco b/Task/Arithmetic-derivative/Draco/arithmetic-derivative.draco new file mode 100644 index 0000000000..ae8d034c8c --- /dev/null +++ b/Task/Arithmetic-derivative/Draco/arithmetic-derivative.draco @@ -0,0 +1,32 @@ +proc lagarias(int n) int: + int f, r, s; + if n<0 then + -lagarias(-n) + elif n<2 then + 0 + else + s := 0; + r := n; + while r % 2 = 0 do + r := r / 2; + s := s + n / 2 + od; + f := 3; + while f <= r do + while r % f = 0 do + r := r / f; + s := s + n / f + od; + f := f + 2 + od; + s + fi +corp + +proc main() void: + int n; + for n from -99 upto 100 do + write(lagarias(n):7); + if (n+100) % 10=0 then writeln() fi + od +corp diff --git a/Task/Arithmetic-derivative/FreeBASIC/arithmetic-derivative.basic b/Task/Arithmetic-derivative/FreeBASIC/arithmetic-derivative.basic new file mode 100644 index 0000000000..5fa7e2e419 --- /dev/null +++ b/Task/Arithmetic-derivative/FreeBASIC/arithmetic-derivative.basic @@ -0,0 +1,46 @@ +Function aDerivative(Byval n As Longint) As Longint + If n < 0 Then Return -aDerivative(-n) + If n = 0 Or n = 1 Then Return 0 + If n = 2 Then Return 1 + + Dim As Longint q, d = 2 + Dim As Longint result = 1 + + While d * d <= n + If n Mod d = 0 Then + q = n \ d + result = q * aDerivative(d) + d * aDerivative(q) + Exit While + End If + d += 1 + Wend + + Return result +End Function + +'Main program +Print "Arithmetic derivatives for -99 through 100:" + +Dim As Integer col, n +col = 0 +For n = -99 To 100 + col += 1 + Print Using "####"; aDerivative(n); + If col = 10 Then + Print + col = 0 + Else + Print " "; + End If +Next + +'Stretch task +Print !"\n\nPowers of 10 derivatives divided by 7:" +Dim As Double m = 1 +For n = 1 To 18 ' LongInt limit in FreeBASIC + m *= 10 + Dim As Longint a = aDerivative(Clngint(m)) + Print Using "D(10^&) / 7 = &"; n; a \ 7 +Next + +Sleep diff --git a/Task/Arithmetic-derivative/FutureBasic/arithmetic-derivative.basic b/Task/Arithmetic-derivative/FutureBasic/arithmetic-derivative.basic new file mode 100644 index 0000000000..b54e9393bb --- /dev/null +++ b/Task/Arithmetic-derivative/FutureBasic/arithmetic-derivative.basic @@ -0,0 +1,30 @@ +// Arithmetic Derivative +// https://rosettacode.org/wiki/Arithmetic_derivative# + +local fn DoIt( N as short) as short + short L,F,Z + L = 0: F = 3: Z = ABS(N) + IF Z<2 THEN exit fn + + 1 IF Z MOD 2 = 0 THEN L=L+N\2: Z=Z\2: GOTO 1 + 2 IF F>Z THEN exit fn + 3 IF Z MOD F = 0 THEN L=L+N\F: Z=Z\F: GOTO 2 + + F=F+2 + goto 1 + +end fn = L + +_Window = 1 + +window _Window,@"Arithmetic Derivative",fn cgrectmake(0,0,640,400) +windowcenter(_Window) + +short N,L,LineCount +FOR N = -99 TO 100 +L = fn DoIt(N): PRINT USING "########";L; +LineCount ++ +if LineCount = 10 then print : LineCount = 0 +NEXT + +handleevents diff --git a/Task/Arithmetic-derivative/MAD/arithmetic-derivative.mad b/Task/Arithmetic-derivative/MAD/arithmetic-derivative.mad new file mode 100644 index 0000000000..dd608891dc --- /dev/null +++ b/Task/Arithmetic-derivative/MAD/arithmetic-derivative.mad @@ -0,0 +1,42 @@ + NORMAL MODE IS INTEGER + + INTERNAL FUNCTION(X,Y) + ENTRY TO REM. + FUNCTION RETURN X-(X/Y)*Y + END OF FUNCTION + + INTERNAL FUNCTION(N) + ENTRY TO DERIV. + R = N + WHENEVER R.L.0, R = -R + WHENEVER R.L.2, FUNCTION RETURN 0 + S = 0 +FAC2 WHENEVER REM.(R,2).E.0 + S = S + N/2 + R = R/2 + TRANSFER TO FAC2 + END OF CONDITIONAL + THROUGH FAC, FOR F=3, 2, F.G.R +FACF WHENEVER REM.(R,F).E.0 + S = S + N/F + R = R/F + TRANSFER TO FACF + END OF CONDITIONAL +FAC CONTINUE + FUNCTION RETURN S + END OF FUNCTION + + VECTOR VALUES LINEF = $10(I6)*$ + DIMENSION LINE(10) + C = 0 + THROUGH ITEM, FOR I=-99, 1, I.G.100 + LINE(C) = DERIV.(I) + C = C+1 + WHENEVER C.E.10 + PRINT FORMAT LINEF, + 0 LINE(0),LINE(1),LINE(2),LINE(3),LINE(4), + 1 LINE(5),LINE(6),LINE(7),LINE(8),LINE(9) + C = 0 + END OF CONDITIONAL +ITEM CONTINUE + END OF PROGRAM diff --git a/Task/Arithmetic-derivative/MiniScript/arithmetic-derivative.mini b/Task/Arithmetic-derivative/MiniScript/arithmetic-derivative.mini index 1c297bd18d..91af00f19b 100644 --- a/Task/Arithmetic-derivative/MiniScript/arithmetic-derivative.mini +++ b/Task/Arithmetic-derivative/MiniScript/arithmetic-derivative.mini @@ -37,7 +37,7 @@ for n in range( -99, 100 ) end if end for print() -for n in range( 1, 17 ) // 18, 19 and 20 would overflow ????? TODO: check +for n in range( 1, 17 ) m = 10 ^ n print( "D(" + str(m) + ") / 7 = " + str( floor (lagarias (m) / 7) ) ) end for diff --git a/Task/Arithmetic-derivative/Miranda/arithmetic-derivative.miranda b/Task/Arithmetic-derivative/Miranda/arithmetic-derivative.miranda new file mode 100644 index 0000000000..c4ecee4682 --- /dev/null +++ b/Task/Arithmetic-derivative/Miranda/arithmetic-derivative.miranda @@ -0,0 +1,24 @@ +main :: [sys_message] +main = [Stdout (table 10 7 (map (show . lagarias) [-99..100])), + Stdout (lay (map ten_pow_m_div_7 [1..20]))] + +ten_pow_m_div_7 :: num->[char] +ten_pow_m_div_7 m = "D(10^" ++ rjustify 2 (show m) ++ ") / 7 = " ++ + show (lagarias (10^m) div 7) + +table :: num->num->[[char]]->[char] +table w cw ls = lay [concat (map (rjustify cw) l) | l <- group w ls] + +group :: num->[*]->[[*]] +group n [] = [] +group n ls = take n ls : group n (drop n ls) + +lagarias :: num->num +lagarias n = -lagarias (-n), if n<0 + = sum [n div f | f <- factors n], otherwise + +factors :: num->[num] +factors n = f n 2 + where f n d = [], if d > n + = d : f (n div d) d, if n mod d = 0 + = f n (d+1), otherwise diff --git a/Task/Arithmetic-derivative/PL-I/arithmetic-derivative.pli b/Task/Arithmetic-derivative/PL-I/arithmetic-derivative.pli new file mode 100644 index 0000000000..179acc3c0a --- /dev/null +++ b/Task/Arithmetic-derivative/PL-I/arithmetic-derivative.pli @@ -0,0 +1,27 @@ +arithmeticDerivative: procedure options(main); + lagarias: procedure(n) returns(fixed); + declare (n, res, fac, rem) fixed; + rem = abs(n); + if rem<2 then return(0); + + res = 0; + do while(mod(rem,2) = 0); + res = res + n/2; + rem = rem/2; + end; + + do fac=3 repeat(fac+2) while(fac<=rem); + do while(mod(rem,fac) = 0); + res = res + n/fac; + rem = rem/fac; + end; + end; + return(res); + end lagarias; + + declare n fixed; + do n=-99 to 100; + put edit(lagarias(n)) (F(7)); + if mod(n+100, 10)=0 then put skip; + end; +end arithmeticDerivative; diff --git a/Task/Arithmetic-derivative/PL-M/arithmetic-derivative.plm b/Task/Arithmetic-derivative/PL-M/arithmetic-derivative.plm new file mode 100644 index 0000000000..d2e0a6eb98 --- /dev/null +++ b/Task/Arithmetic-derivative/PL-M/arithmetic-derivative.plm @@ -0,0 +1,66 @@ +100H: /* ARITHMETIC DERIVATIVE - BASED ON THE BASIC SAMPLE */ + + /* RETURNS TRUE IF A < B, FALSE OTHERWISE WITH A AND B TREATED AS SIGNED */ + SIGNED$LT: PROCEDURE( A, B )BYTE; + DECLARE ( A, B ) ADDRESS; + IF ( A + 32768 ) < ( B + 32768 ) THEN RETURN 0FFH; ELSE RETURN 0; + END SIGNED$LT ; + + /* RETURNS A / B WITH A AND B TREATED AS SIGNED */ + SIGNED$DIV: PROCEDURE( AIN, BIN )ADDRESS; + DECLARE ( AIN, BIN )ADDRESS; + DECLARE ( A, B, SIGN )ADDRESS; + SIGN = 1; + A = AIN; + B = BIN; + IF SIGNED$LT( A, 0 ) THEN DO; + SIGN = - SIGN; + A = - A; + END; + IF SIGNED$LT( B, 0 ) THEN DO; + SIGN = - SIGN; + B = - B; + END; + RETURN ( A / B ) * SIGN; + END SIGNED$DIV ; + + /* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */ + BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; + PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; + PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; + PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END; + + PR$SIGNED$NUMBER: PROCEDURE( N ); /* PRINTS A SIGNED NUMBER */ + DECLARE N ADDRESS; + DECLARE V ADDRESS, N$STR ( 9 )BYTE, W BYTE; + IF SIGNED$LT( N, 0 ) THEN V = - N; ELSE V = N; + DO W = 0 TO LAST( N$STR ); N$STR( W ) = ' '; END; + W = LAST( N$STR ); + N$STR( W ) = '$'; + N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); + DO WHILE( ( V := V / 10 ) > 0 ); + N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); + END; + IF SIGNED$LT( N, 0 ) THEN N$STR( W := W - 1 ) = '-'; + CALL PR$STRING( .N$STR ); + END PR$SIGNED$NUMBER; + + /* TASK */ + + DECLARE ( C, N, L, F, Z ) ADDRESS; + + DO C = 1 TO 200; + N = C - 100; + L = 0; F = 3; IF SIGNED$LT( N, 0 ) THEN Z = - N; ELSE Z = N; + DO WHILE Z >= 2; + DO WHILE Z MOD 2 = 0; L = L + SIGNED$DIV( N, 2 ); Z = Z / 2; END; + IF F <= Z THEN DO; + DO WHILE Z MOD F = 0; L = L + SIGNED$DIV( N, F ); Z = Z / F; END; + F = F + 2; + END; + END; + CALL PR$SIGNED$NUMBER( L ); + IF C MOD 10 = 0 THEN CALL PR$NL; + END; + +EOF diff --git a/Task/Arithmetic-derivative/Refal/arithmetic-derivative.refal b/Task/Arithmetic-derivative/Refal/arithmetic-derivative.refal new file mode 100644 index 0000000000..d124d001a8 --- /dev/null +++ b/Task/Arithmetic-derivative/Refal/arithmetic-derivative.refal @@ -0,0 +1,32 @@ +$ENTRY Go { + = >> +}; + +Lagarias { + '-' e.N = '-' ; + 0 = 0; + 1 = 0; + e.N, : { + e.N = 1; + e.F,
: e.R = + > + >>; + }; +}; + +Fac { + (e.F) e.N, : e.N2, + : '+' = e.N; + (e.F) e.N, : 0 = e.F; + (e.F) e.N = ) e.N>; + e.N = ; +}; + +Table { s.C s.W e.L = >>; }; +Line { s.W e.X = >; }; +Fmt { s.W e.X, >: (e.Z) e.C = e.C; }; +Rep { 0 s.C = ; s.N s.C = s.C s.C>; }; +Join { = ; (e.X) e.Y = e.X ; }; +Group { s.N = ; s.N e.X, : (e.G) e.R = (e.G) ; }; +Each { (e.F) = ; (e.F) (e.X) e.XS = () ; }; +Iota { (e.E) e.E = (e.E); (e.S) e.E = (e.S) ) e.E>; }; diff --git a/Task/Arithmetic-derivative/SETL/arithmetic-derivative.setl b/Task/Arithmetic-derivative/SETL/arithmetic-derivative.setl new file mode 100644 index 0000000000..e48e921bf7 --- /dev/null +++ b/Task/Arithmetic-derivative/SETL/arithmetic-derivative.setl @@ -0,0 +1,25 @@ +program arithmetic_derivative; + loop for n in [-99..100] do + nprint(lpad(str lagarias(n), 6)); + if (col +:= 1) mod 10 = 0 then + print; + end if; + end loop; + + loop for m in [1..20] do + nprint("D(10^" + lpad(str m, 2) + ") / 7 = "); + print(lagarias(10**m) div 7); + end loop; + + proc lagarias(n); + return if n<0 then + -lagarias(-n) + elseif n in {0,1} then + 0 + elseif forall d in {2..floor sqrt n} | n mod d /= 0 then + 1 + else + (n div d)*lagarias(d) + d*lagarias(n div d) + end; + end proc; +end program; diff --git a/Task/Arithmetic-derivative/Sidef/arithmetic-derivative-1.sidef b/Task/Arithmetic-derivative/Sidef/arithmetic-derivative-1.sidef new file mode 100644 index 0000000000..171928e84f --- /dev/null +++ b/Task/Arithmetic-derivative/Sidef/arithmetic-derivative-1.sidef @@ -0,0 +1,9 @@ +say "Arithmetic derivative for n in range [-99, 100]:" +-99 .. 100 -> map { .arithmetic_derivative }.each_slice(10, {|*a| + a.map { '%4s' % _ }.join(' ').say +}) + +say "\nArithmetic derivative D(10^n)/7 for n in range [1, 20]:" +for n in (1..20) { + say "D(10^#{n})/7 = #{arithmetic_derivative(10**n) / 7}" +} diff --git a/Task/Arithmetic-derivative/Sidef/arithmetic-derivative-2.sidef b/Task/Arithmetic-derivative/Sidef/arithmetic-derivative-2.sidef new file mode 100644 index 0000000000..d9d62d3285 --- /dev/null +++ b/Task/Arithmetic-derivative/Sidef/arithmetic-derivative-2.sidef @@ -0,0 +1,26 @@ +subset Integer < Number { .is_int } +subset Positive < Integer { .is_pos } +subset Negative < Integer { .is_neg } +subset Prime < Positive { .is_prime } + +func arithmetic_derivative((0)) { 0 } +func arithmetic_derivative((1)) { 0 } + +func arithmetic_derivative(Prime _) { 1 } + +func arithmetic_derivative(Negative n) { + -arithmetic_derivative(-n) +} + +func arithmetic_derivative(Positive n) is cached { + + var a = n.factor.rand + var b = n/a + + arithmetic_derivative(a)*b + a*arithmetic_derivative(b) +} + +func arithmetic_derivative(Number n) { + var (a, b) = n.nude + (arithmetic_derivative(a)*b - arithmetic_derivative(b)*a) / b**2 +} diff --git a/Task/Arithmetic-numbers/REXX/arithmetic-numbers-2.rexx b/Task/Arithmetic-numbers/REXX/arithmetic-numbers-2.rexx deleted file mode 100644 index cb506d1077..0000000000 --- a/Task/Arithmetic-numbers/REXX/arithmetic-numbers-2.rexx +++ /dev/null @@ -1,76 +0,0 @@ -parse Version version -say version; say 'Arithmetic numbers'; say -Call time 'R' -numeric digits 9 -a = 0; c = 0 -do i = 1 -/* Is the number arithmetic? */ - if Arithmetic(i) then do - a = a+1 -/* Is the number composite? */ - if divi.0 > 2 then - c = c+1 -/* Output control */ - if a <= 100 then do - if a = 1 then - say 'First 100 arithmetic numbers are' - call Charout ,Right(i,4) - if a//10 = 0 then - say - if a = 100 then - say - end - if a = 100 | a = 1000 | a = 10000 | a = 100000 | a = 1000000 then do - say 'The' a'th arithmetic number is' i - say 'Of the first' a 'numbers' c 'are composite' - say - end -/* Max 1m, higher takes too long */ - if a = 1000000 then - leave - end -end -say Format(Time('e'),,3) 'seconds' -exit - -Arithmetic: -/* Is a number arithmetic? function */ -procedure expose divi. -arg x -/* Cf definition */ -s = Sigma(x) -if Whole(s/divi.0) then - return 1 -else - return 0 - -Sigma: -/* Sigma = Sum of all divisors of x including 1 and x */ -procedure expose divi. -arg xx -/* Fast values */ -if xx = 1 then do - divi.0 = 1 - return 1 -end -/* Euclid's method */ -m = xx//2; yy = 1+xx; n = 2 -do j = 2+m by 1+m while j*j < xx - if xx//j = 0 then do - yy = yy+j+xx%j; n = n+2 - end -end -if j*j = xx then do - yy = yy+j; n = n+1 -end -/* Store number of divisors */ -divi.0 = n -/* Return sum */ -return yy - -Whole: -/* Is a number integer? */ -procedure -arg xx -/* Formula */ -return Datatype(xx,'w') diff --git a/Task/Arithmetic-numbers/REXX/arithmetic-numbers-1.rexx b/Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx similarity index 82% rename from Task/Arithmetic-numbers/REXX/arithmetic-numbers-1.rexx rename to Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx index 6094ba7514..fd21689cfc 100644 --- a/Task/Arithmetic-numbers/REXX/arithmetic-numbers-1.rexx +++ b/Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx @@ -2,7 +2,7 @@ include Settings say version; say 'Arithmetic numbers'; say numeric digits 9 -a = 0; c = 0 +divi. = 0; a = 0; c = 0 do i = 1 /* Is the number arithmetic? */ if Arithmetic(i) then do @@ -33,17 +33,6 @@ end say Format(Time('e'),,3) 'seconds' exit -Arithmetic: -/* Is a number arithmetic? function */ -procedure expose divi. -arg x -/* Cf definition */ -s = Sigma(x) -if Whole(s/divi.0) then - return 1 -else - return 0 - include Numbers include Functions include Abend diff --git a/Task/Arithmetic-numbers/Sidef/arithmetic-numbers.sidef b/Task/Arithmetic-numbers/Sidef/arithmetic-numbers.sidef new file mode 100644 index 0000000000..0530ed1c31 --- /dev/null +++ b/Task/Arithmetic-numbers/Sidef/arithmetic-numbers.sidef @@ -0,0 +1,14 @@ +func is_arithmetic(n) { + n.tau `divides` n.sigma +} + +say "The first one hundred arithmetic numbers:" +100.by(is_arithmetic).each_slice(10, {|*a| + a.map { '%3s' % _ }.join(' ').say +}) + +for x in (1e3, 1e4, 1e5, 1e6) { + var arr = x.by(is_arithmetic) + say "\n#{x}th arithmetic number is #{arr.last}." + say "There are #{arr.count{.is_composite}} composite arithmetic numbers <= #{arr.last}." +} diff --git a/Task/Assertions/FutureBasic/assertions.basic b/Task/Assertions/FutureBasic/assertions.basic new file mode 100644 index 0000000000..0572a113ad --- /dev/null +++ b/Task/Assertions/FutureBasic/assertions.basic @@ -0,0 +1 @@ +cln NSAssert(a == 42, @"Error message"); diff --git a/Task/Assertions/Uiua/assertions.uiua b/Task/Assertions/Uiua/assertions.uiua new file mode 100644 index 0000000000..582a84d525 --- /dev/null +++ b/Task/Assertions/Uiua/assertions.uiua @@ -0,0 +1,2 @@ +r ← 41 +⍤"r doesn't equal 42!" =42 r diff --git a/Task/Associative-array-Creation/Uiua/associative-array-creation.uiua b/Task/Associative-array-Creation/Uiua/associative-array-creation.uiua new file mode 100644 index 0000000000..eb353f2a2b --- /dev/null +++ b/Task/Associative-array-Creation/Uiua/associative-array-creation.uiua @@ -0,0 +1 @@ +map [1 2] {"foo" "bar"} diff --git a/Task/Associative-array-Iteration/Uiua/associative-array-iteration.uiua b/Task/Associative-array-Iteration/Uiua/associative-array-iteration.uiua new file mode 100644 index 0000000000..e93ccc48ba --- /dev/null +++ b/Task/Associative-array-Iteration/Uiua/associative-array-iteration.uiua @@ -0,0 +1,5 @@ +x ← .map [3 9 7] {"foo" "bar" "hey"} # Using the example from the 'Creation' page +.⊟°map x # Decouple the hashmap and put a copy of it on the stack +&p.⊢ # Get the keys as a new array and print them +&p⊣: # Get the values as a new array and print them +&p⧅◌ # Get keys mapped to values diff --git a/Task/Associative-array-Merging/Uiua/associative-array-merging.uiua b/Task/Associative-array-Merging/Uiua/associative-array-merging.uiua new file mode 100644 index 0000000000..a9f9bb2ba1 --- /dev/null +++ b/Task/Associative-array-Merging/Uiua/associative-array-merging.uiua @@ -0,0 +1,19 @@ +Base ← map {"name" "price" "color"} {"Rocket Skates" 12.75 "yellow"} +Update ← map {"price" "color" "year"} {15.25 "red" 1974} +&pBase +&pUpdate +UnmapAndPop ← ◌: °map +GetAndMap ← ˜map˜get + +°⊂ UnmapAndPop Base UnmapAndPop Update +Base. +GetAndMap +.:◌: +Update +GetAndMap +&p"\n" +&p⊂ +&p"\n" + +&pBase +&pUpdate diff --git a/Task/Average-loop-length/YAMLScript/average-loop-length.ys b/Task/Average-loop-length/YAMLScript/average-loop-length.ys index afb2ab3f81..4b3bde0c68 100644 --- a/Task/Average-loop-length/YAMLScript/average-loop-length.ys +++ b/Task/Average-loop-length/YAMLScript/average-loop-length.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 # Use *' (vs. *) to allow arbitrary length arithmetic: mul =: value("*'") diff --git a/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur b/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur index f313eb66b4..ad6e0ac086 100644 --- a/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur +++ b/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur @@ -1,4 +1,4 @@ -val umean = fn x:fold(fn{+}, x) / len(x) +val umean = fn x:fold(x, by=fn{+}) / len(x) writeln " custom: ", umean([7, 3, 12]) writeln "built-in: ", mean([7, 3, 12]) diff --git a/Task/Averages-Arithmetic-mean/Ursalang/averages-arithmetic-mean.ursa b/Task/Averages-Arithmetic-mean/Ursalang/averages-arithmetic-mean.ursa new file mode 100644 index 0000000000..f678c19151 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Ursalang/averages-arithmetic-mean.ursa @@ -0,0 +1,8 @@ +let mean = fn(l) { + var tot = 0 + for i in l.iter() { + tot := tot + i + } + return tot/l.len() +} +print(mean([10, 30, 50, 5, 5])) diff --git a/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.jl b/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.jl index cefb410d21..9bd21ffb79 100644 --- a/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.jl +++ b/Task/Averages-Mean-angle/Julia/averages-mean-angle-2.jl @@ -1,8 +1,8 @@ julia> meandegrees([350, 10]) 0.0 -julia> meandegrees([90, 180, 270, 360]]) +julia> meandegrees([90, 180, 270, 360]) 0.0 -julia> meandegrees([10, 20, 30]]) +julia> meandegrees([10, 20, 30]) 19.999999999999996 diff --git a/Task/Averages-Mode/Ursalang/averages-mode.ursa b/Task/Averages-Mode/Ursalang/averages-mode.ursa new file mode 100644 index 0000000000..4201bfb04e --- /dev/null +++ b/Task/Averages-Mode/Ursalang/averages-mode.ursa @@ -0,0 +1,20 @@ +let mode = fn(l) { + let m = {} + for i in l.iter() { + let old = m.get(i) + let new = if old == null {1} else {old + 1} + m.set(i, new) + } + var max = 0 + var mode = null + for i in m.iter() { + if i.get(1) > max { + max := i.get(1) + mode := i.get(0) + } + } + return mode +} + +print(mode([4, 6, 66, 66, 9, 22, 9, 9, 23, 43, 2, 43])) +print(mode(["abc", "def", "ghi", "abc"])) diff --git a/Task/Averages-Root-mean-square/Raku/averages-root-mean-square-2.raku b/Task/Averages-Root-mean-square/Raku/averages-root-mean-square-2.raku index e813d829a8..2bb7f6aecd 100644 --- a/Task/Averages-Root-mean-square/Raku/averages-root-mean-square-2.raku +++ b/Task/Averages-Root-mean-square/Raku/averages-root-mean-square-2.raku @@ -1 +1 @@ -sub rms { sqrt @_ R/ [+] @_ X** 2 } +sub rms { sqrt @_ R/ [+] @_».² } diff --git a/Task/Averages-Root-mean-square/Ursalang/averages-root-mean-square.ursa b/Task/Averages-Root-mean-square/Ursalang/averages-root-mean-square.ursa new file mode 100644 index 0000000000..cd5c2e381a --- /dev/null +++ b/Task/Averages-Root-mean-square/Ursalang/averages-root-mean-square.ursa @@ -0,0 +1,5 @@ +var tot = 0 +for i in range(10) { + tot := tot + (i + 1) ** 2 +} +print(sqrt(tot/10)) diff --git a/Task/Averages-Simple-moving-average/M2000-Interpreter/averages-simple-moving-average-1.m2000 b/Task/Averages-Simple-moving-average/M2000-Interpreter/averages-simple-moving-average-1.m2000 new file mode 100644 index 0000000000..3e70598a48 --- /dev/null +++ b/Task/Averages-Simple-moving-average/M2000-Interpreter/averages-simple-moving-average-1.m2000 @@ -0,0 +1,28 @@ +module Simple_moving_average { + smaMAKER=lambda (m) -> { + s=stack + =lambda m, s (N) -> { + stack s { + if len(s)=m then drop + data N + } + = array(stack(s))#sum()/len(s) + } + } + Print "Period = 3" + ma=smaMaker(3) + test(0, 9) + Print "Period = 5" + ma=smaMaker(5) + test(9, 0) + end + sub test(A, B) + local i + Print + for i=A to B + Print "Add ";i;" => moving average ";ma(i) + next + Print + end sub +} +Simple_moving_average diff --git a/Task/Averages-Simple-moving-average/M2000-Interpreter/averages-simple-moving-average-2.m2000 b/Task/Averages-Simple-moving-average/M2000-Interpreter/averages-simple-moving-average-2.m2000 new file mode 100644 index 0000000000..6ebf41e00a --- /dev/null +++ b/Task/Averages-Simple-moving-average/M2000-Interpreter/averages-simple-moving-average-2.m2000 @@ -0,0 +1,37 @@ +module Simple_moving_average { + class smaMaker { + private: + s=stack + m + public: + set { + read this + } + value (N) { + stack .s { + if len(.s)=.m then drop + data N + } + = array(stack(.s))#sum()/len(.s) + } + class: + module smaMaker (.m) { + } + } + Print "Period = 3" + ma=smaMaker(3) + test(0, 9) + Print "Period = 5" + ma=smaMaker(5) + test(9, 0) + end + sub test(A, B) + local i + Print + for i=A to B + Print "Add ";i;" => moving average ";ma(i) + next + Print + end sub +} +Simple_moving_average diff --git a/Task/Babbage-problem/EDSAC-order-code/babbage-problem.edsac b/Task/Babbage-problem/EDSAC-order-code/babbage-problem.edsac index 3189034b85..1240f20d03 100644 --- a/Task/Babbage-problem/EDSAC-order-code/babbage-problem.edsac +++ b/Task/Babbage-problem/EDSAC-order-code/babbage-problem.edsac @@ -26,12 +26,13 @@ Here, the last character sets the teleprinter to figures.] [4] PF PF [1st difference for n^2] [Constants] +[2024-12-25 Load time: clear each 35-bit constant, including sandwich bit] + T6#ZPF T8#ZPF T10#ZPF T12#ZPF +[Then resume normal loading at first 35-bit constant] + T6Z [6] P64F PF [2nd difference for n^2, i.e. 128] [8] P4F PF [1st difference for n, i.e. 8] - T10#Z PF T10Z [clears sandwich digit between 10 and 11; - cf. Wilkes, Wheeler & Gill, 1951, pp 110, 141-2] [10] #1760F V2046F [-1000000] - T12#Z PF T12Z [clears sandwich digit between 12 and 13] [12] Q1728F PD [269696] [14] &F [line feed] [15] @F [carriage return] diff --git a/Task/Babbage-problem/M2000-Interpreter/babbage-problem.m2000 b/Task/Babbage-problem/M2000-Interpreter/babbage-problem.m2000 index 1dcd8795e0..db574a7240 100644 --- a/Task/Babbage-problem/M2000-Interpreter/babbage-problem.m2000 +++ b/Task/Babbage-problem/M2000-Interpreter/babbage-problem.m2000 @@ -1,6 +1,14 @@ -Def Long k=1000000, T=269696, n +long long k=1000000, T=269696, n +boolean first=true +Document doc$ n=Sqrt(269696) For n=n to k { - If n^2 mod k = T Then Exit + If n^2&& mod k = T Then + doc$=format$("The "+if$(first->"smallest", "next")+" number whose square ends in {0} is {1}, Its square is {2}", T, n, n**2&&)+{ + } + first=false + refresh + end if } -Report format$("The smallest number whose square ends in {0} is {1}, Its square is {2}", T, n, n**2) +clipboard doc$ +report doc$ diff --git a/Task/Babbage-problem/PascalABC.NET/babbage-problem.pas b/Task/Babbage-problem/PascalABC.NET/babbage-problem.pas new file mode 100644 index 0000000000..e8c2ecff0e --- /dev/null +++ b/Task/Babbage-problem/PascalABC.NET/babbage-problem.pas @@ -0,0 +1,9 @@ +//the smallest positive integer whose square ends in the digits 269,696 +## var k:=269696; +var n:=trunc(sqrt(k));(* Start with n *) +if n mod 2<>0 then n-=1;(* n:=n-1 *) + repeat + n += 2 (* Increase n by 2. n:=n+2 *) + until (n * n) mod 1000000 = 269696; +$'The smallest positive integer is {n} whose square ends in {k}'.println; +$'{n}² = {n*n}'.println; diff --git a/Task/Bell-numbers/BQN/bell-numbers.bqn b/Task/Bell-numbers/BQN/bell-numbers.bqn new file mode 100644 index 0000000000..918f1357ad --- /dev/null +++ b/Task/Bell-numbers/BQN/bell-numbers.bqn @@ -0,0 +1,8 @@ +Bell ← {(+`⊢´⊸∾)⍟(↕𝕩)⋈1} + +•Out "First 15 Bell numbers:" +•Show ⊑¨ Bell 15 + +•Out "" +•Out "First 10 rows of the Bell triangle:" +•Show¨ Bell 10 diff --git a/Task/Bell-numbers/Forth/bell-numbers.fth b/Task/Bell-numbers/Forth/bell-numbers.fth new file mode 100644 index 0000000000..6b7c8259fa --- /dev/null +++ b/Task/Bell-numbers/Forth/bell-numbers.fth @@ -0,0 +1,51 @@ +: triangle-allocate ( u -- addr ) + dup 1+ * 2/ cells dup + allocate abort" out of memory" + tuck swap erase ; + +: triangle-deallocate ( addr -- ) + free abort" memory deallocation error" ; + +: triangle-row-address ( addr u -- addr ) + dup 1+ * 2/ cells + ; + +: bell-triangle-row ( addr u -- ) + tuck 1- triangle-row-address + 2dup swap cells + + dup 1 cells - @ over ! + rot 0 ?do + dup @ >r over @ r> + >r + cell+ r> over ! + swap cell+ swap + loop 2drop ; + +: bell-triangle ( u -- addr ) + dup triangle-allocate + dup 1 swap ! + swap 1 ?do + dup i bell-triangle-row + loop ; + +: print-bell-numbers ( addr u -- ) + 0 ?do + dup i triangle-row-address @ . cr + loop drop ; + +: print-bell-row ( addr u -- ) + tuck triangle-row-address swap + 1+ 0 ?do + dup @ . cell+ + loop drop cr ; + +: main ( -- ) + 15 bell-triangle + ." First 15 Bell numbers:" cr + dup 15 print-bell-numbers cr + ." First 10 rows of the Bell triangle:" cr + 10 0 do + dup i print-bell-row + loop + triangle-deallocate ; + +main +bye diff --git a/Task/Bell-numbers/Haskell/bell-numbers-5.hs b/Task/Bell-numbers/Haskell/bell-numbers-5.hs new file mode 100644 index 0000000000..2574f2daa3 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-5.hs @@ -0,0 +1,17 @@ +import Data.Ratio ((%), numerator) + +infixl 7 *. +(*.) :: Num a => a -> [a] -> [a] +x *. (p:ps) = x*p : x*.ps + +instance Num a => Num [a] where + negate = map negate + (+) = zipWith (+) + (*) (p:ps) (q:qs) = p*q : ((p*.qs) + ps*(q:qs)) + fromInteger n = fromInteger n:repeat 0 + +instance (Eq a, Fractional a) => Fractional [a] where + (/) (0:ps) (0:qs) = ps/qs + (/) (p:ps) (q:qs) = let r=p/q in r : (ps - r*.qs)/(q:qs) + + fromRational q = fromRational q:repeat 0 diff --git a/Task/Bell-numbers/Haskell/bell-numbers-6.hs b/Task/Bell-numbers/Haskell/bell-numbers-6.hs new file mode 100644 index 0000000000..1cccede973 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-6.hs @@ -0,0 +1,2 @@ +expseq :: [Rational] -> [Rational] +expseq ps = zipWith (\p q -> p*fromInteger q) ps (scanl (*) 1 [1..]) diff --git a/Task/Bell-numbers/Haskell/bell-numbers-7.hs b/Task/Bell-numbers/Haskell/bell-numbers-7.hs new file mode 100644 index 0000000000..e6c2d50d9c --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-7.hs @@ -0,0 +1,3 @@ +infixr 9 |> +(|>) :: (Eq a, Num a) => [a] -> [a] -> [a] +(p:ps) |> (0:qs) = p : qs*(ps |> (0:qs)) diff --git a/Task/Bell-numbers/Haskell/bell-numbers-8.hs b/Task/Bell-numbers/Haskell/bell-numbers-8.hs new file mode 100644 index 0000000000..9cc115db88 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-8.hs @@ -0,0 +1,11 @@ +exp1 :: [Rational] +exp1 = 0 : map (1%) factorials + where + factorials = scanl (*) 1 [2..] + +exps :: [Rational] +exps = 1 : zipWith (*) exps [ 1%n | n <- [1..] ] + +bell :: [Integer] +bell = map numerator + (expseq (exps |> exp1)) diff --git a/Task/Bell-numbers/Haskell/bell-numbers-9.hs b/Task/Bell-numbers/Haskell/bell-numbers-9.hs new file mode 100644 index 0000000000..11d50b5761 --- /dev/null +++ b/Task/Bell-numbers/Haskell/bell-numbers-9.hs @@ -0,0 +1,4 @@ +ghci> take 15 bell +[1,1,2,5,15,52,203,877,4140,21147,115975,678570,4213597,27644437,190899322] +ghci> bell !! 49 +10726137154573358400342215518590002633917247281 diff --git a/Task/Bell-numbers/Miranda/bell-numbers.miranda b/Task/Bell-numbers/Miranda/bell-numbers.miranda new file mode 100644 index 0000000000..67a573f599 --- /dev/null +++ b/Task/Bell-numbers/Miranda/bell-numbers.miranda @@ -0,0 +1,16 @@ +main :: [sys_message] +main = [Stdout "First 15 and 50th Bell numbers:\n", + Stdout (lay [(rjustify 2 (show i)) ++ ": " ++ show (bell_numbers ! i) + | i <- [1..15] ++ [50]]), + Stdout "\nFirst 10 rows of the Bell triangle:\n", + Stdout (lay [concat [rjustify 7 (show n) | n <- row] + | row <- take 10 bell_triangle]) + ] + + +bell_numbers :: [num] +bell_numbers = map last bell_triangle + +bell_triangle :: [[num]] +bell_triangle = iterate bell_step [1] + where bell_step row = scan (+) (last row) row diff --git a/Task/Bell-numbers/PARI-GP/bell-numbers.parigp b/Task/Bell-numbers/PARI-GP/bell-numbers.parigp new file mode 100644 index 0000000000..f62bf25259 --- /dev/null +++ b/Task/Bell-numbers/PARI-GP/bell-numbers.parigp @@ -0,0 +1,4 @@ +genit(maxx=50)={bell=List(); +for(n=0,maxx,q=sum(k=0,n,stirling(n,k,2)); +listput(bell,q));bell} +END diff --git a/Task/Bell-numbers/Refal/bell-numbers.refal b/Task/Bell-numbers/Refal/bell-numbers.refal new file mode 100644 index 0000000000..f65c59ce11 --- /dev/null +++ b/Task/Bell-numbers/Refal/bell-numbers.refal @@ -0,0 +1,41 @@ +$ENTRY Go { + , : e.Bell (e.B50) + , : (e.F15) e.Rest + = + + >; +} + +Show { + (e.X) = >; +}; + +BellNumbers { + s.N, : e.Rows = ; +}; + +BellTriangle { + s.N = ((1))>; + 0 e.T = e.T; + s.N e.Rs (e.R) = e.Rs (e.R) ()>; +}; + +BellStep { + e.Row, e.Row: e.X (e.Last) = ; +}; + +Rsum { + (Acc e.Acc) = ; + (Acc e.Acc) (e.N) e.Ns, : e.N2 = + (e.N2) ; + e.Ns = ; +}; + +Each { + (e.F) = ; + (e.F) (e.X) e.Xs = () ; +}; + +Head { + t.X e.Y = t.X; +}; diff --git a/Task/Bell-numbers/SETL/bell-numbers.setl b/Task/Bell-numbers/SETL/bell-numbers.setl new file mode 100644 index 0000000000..83c7ca45d4 --- /dev/null +++ b/Task/Bell-numbers/SETL/bell-numbers.setl @@ -0,0 +1,31 @@ +program bell_numbers; + print("First 15 and 50th Bell numbers:"); + b := bell_nums(50); + loop for i in [1..15] with 50 do + print(lpad(str i, 2) + ": " + str b(i)); + end loop; + + print; + print("First 10 rows of the Bell triangle:"); + loop for row in bell_triangle(10) do + print(+/[lpad(str n, 7) : n in row]); + end loop; + + proc bell_nums(n); + tri := bell_triangle(n); + return [row(#row) : row in tri]; + end proc; + + proc bell_triangle(rows); + tri := [[1]]; + loop for i in [2..rows] do + row := tri(#tri); + nextrow := [row(#row)]; + loop for n in row do + nextrow with:= nextrow(#nextrow) + n; + end loop; + tri with:= nextrow; + end loop; + return tri; + end proc; +end program; diff --git a/Task/Benfords-law/Quackery/benfords-law.quackery b/Task/Benfords-law/Quackery/benfords-law.quackery new file mode 100644 index 0000000000..c18ea50a99 --- /dev/null +++ b/Task/Benfords-law/Quackery/benfords-law.quackery @@ -0,0 +1,36 @@ + [ $ "bigrat.qky" loadfile ] now! + + [ ' [ 1 1 ] + swap 2 - times + [ dup -1 peek + over -2 peek + + join ] ] is fibonacci ( n --> [ ) + + [ 0 swap witheach + ] is sum ( [ --> n ) + + [ [ 10 /mod over while + drop again ] nip ] is msd ( n --> n ) + + [ 2dup peek 1+ unrot poke ] is tallydigit ( [ n --> [ ) + + [ 0 10 of swap + witheach + [ msd tallydigit ] ] is msdcount ( [ --> [ ) + + [ [ table + $ "0.30103" $ "0.17609" + $ "0.12494" $ "0.09691" + $ "0.07918" $ "0.06695" + $ "0.05799" $ "0.05115" + $ "0.04576" ] do echo$ ] is expected ( --> ) + + say "n expected counted" cr + 1000 fibonacci msdcount + behead drop + dup sum swap + witheach + [ i^ 1+ echo sp sp + i^ expected sp sp + over reduce + 5 point$ echo$ cr ] + drop diff --git a/Task/Bifid-cipher/Go/bifid-cipher.go b/Task/Bifid-cipher/Go/bifid-cipher.go new file mode 100644 index 0000000000..c8a6cfa6fe --- /dev/null +++ b/Task/Bifid-cipher/Go/bifid-cipher.go @@ -0,0 +1,180 @@ +/* + Only use ASCII letters between A and Z or the Characters in square... . If the row with 'J' is removed from the squares, + then the square is a 'Polybios square' and you must use removeSpaceI(text) to encrypt and decrypt +*/ +package main + +import ( + "fmt" + "strings" +) + +var ( + squareRosetta [][]byte = [][]byte{ //rosettacode + {'A', 'B', 'C', 'D', 'E'}, + {'F', 'G', 'H', 'I', 'K'}, + {'L', 'M', 'N', 'O', 'P'}, + {'Q', 'R', 'S', 'T', 'U'}, + {'V', 'W', 'X', 'Y', 'Z'}, + {'J', '1', '2', '3', '4'}, + } + + squareWikipedia [][]byte = [][]byte{ // wikipedia + + {'B', 'G', 'W', 'K', 'Z'}, + {'Q', 'P', 'N', 'D', 'S'}, + {'I', 'O', 'A', 'X', 'E'}, + {'F', 'C', 'L', 'U', 'M'}, + {'T', 'H', 'Y', 'V', 'R'}, + {'J', '1', '2', '3', '4'}, + } + + textRosetta string = "0ATTACKATDAWN" + textRosettaEncoded string = "DQBDAXDQPDQH" // only for test + textWikipedia string = "FLEEATONCE" + textWikipediaEncoded string = "UAEOLWRINS" // only for test + textTest string = "The invasion will start on the first of January" + textTextEncoded string = "RASOAQXFIOORXESXADETSWLTNIAZQOISBRGBALY" // only for test +) + +type koord struct { + X byte + Y byte +} + +func (k *koord) LessThen(other *koord) bool { + if k.Y > other.Y { + return false + } + if k.Y < other.Y { + return true + } + if k.X < other.X { + return true + } + return false +} + +func (k *koord) EqualTo(other koord) bool { + if k.X == other.X && k.Y == other.Y { + return true + } + return false +} + +var encryptMap map[byte]koord +var decryptMap map[koord]byte + +func squareToMaps(square [][]byte) (map[byte]koord, map[koord]byte) { + eMap := make(map[byte]koord) + dMap := make(map[koord]byte) + for x, col := range square { + for y, v := range col { + eMap[v] = koord{byte(x), byte(y)} + dMap[koord{byte(x), byte(y)}] = v + + } + } + return eMap, dMap +} + +func removeSpaceI(text string) string { + var n string + s := strings.ToUpper(text) + for _, b := range []byte(s) { + //use only ASCII Characters from A to Z + if b < 'A' || b > 'Z' { + continue + } + if b == 'J' { + b = 'I' + } + n = n + string(b) + } + return n +} + +func removeSpace(text string, square map[byte]koord) string { + var n string + //to UpperCase and then remove all Spaces an Characters witch are not in square + s := strings.ReplaceAll(strings.ToUpper(text), " ", "") + for _, b := range []byte(s) { + _, ok := square[b] + if ok { + n = n + string(b) + } + } + return n +} + +func encrypt(text string, emap map[byte]koord, dmap map[koord]byte) string { + text = removeSpace(text, emap) + var row0, row1 []byte + for _, b := range []byte(text) { + xy := emap[b] + row0 = append(row0, xy.X) + row1 = append(row1, xy.Y) + } + row0 = append(row0, row1...) + + var s string + for i := 0; i < len(row0); i += 2 { + s = s + string(dmap[koord{row0[i], row0[i+1]}]) + } + return s +} + +func decrypt(text string, emap map[byte]koord, dmap map[koord]byte) string { + text = removeSpace(text, emap) + k := make([]koord, len(text)) + + for i, b := range []byte(text) { + k[i] = emap[b] + } + + kl := make([]byte, len(k)*2) + i := int(0) + for _, ki := range k { + kl[i] = ki.X + kl[i+1] = ki.Y + i += 2 + } + l := len(kl) / 2 + k1 := kl[:l] + k2 := kl[l:] + var s string + + for i := 0; i < l; i++ { + s = s + string(dmap[koord{k1[i], k2[i]}]) + } + return s +} + +func main() { + + encryptMap, decryptMap = squareToMaps(squareRosetta) + fmt.Println("from Rosettacode") + fmt.Println("original:\t", textRosetta) + s := encrypt(textRosetta, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) + + fmt.Println("from Wikipedia") + encryptMap, decryptMap = squareToMaps(squareWikipedia) + fmt.Println("original:\t", textWikipedia) + s = encrypt(textWikipedia, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) + + encryptMap, decryptMap = squareToMaps(squareWikipedia) + fmt.Println("from Rosettacode long part") + fmt.Println("original:\t", textTest) + s = encrypt(textTest, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + // Wenn der Text eine ungerade Anzahl Buchstaben hat, funktioniert der Algorithmus nicht!!! + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) + +} diff --git a/Task/Bifid-cipher/Haskell/bifid-cipher.hs b/Task/Bifid-cipher/Haskell/bifid-cipher.hs new file mode 100644 index 0000000000..9964f7aa9d --- /dev/null +++ b/Task/Bifid-cipher/Haskell/bifid-cipher.hs @@ -0,0 +1,60 @@ +import Data.List +import Data.Char + +-- Defining all the grids I'll be using in one go. + +rcBifid = [ + 'A','B','C','D','E', + 'F','G','H','I','K', + 'L','M','N','O','P', + 'Q','R','S','T','U', + 'V','W','X','Y','Z' + ] -- We will use strings here onwards. This was just a demonstration. + +wikiBifid = "POLYBIUSCHERADFGKMNQTVWXZ" +cmiBifid = "CMIHASKELQWRTYUOPDFGZXVBN" + +-- Convert a character to its grid coordinates (1-based index) +chr2pair square x = if x == 'J' then chr2pair square 'I' else case elemIndex x square of + Nothing -> error "char is not in cipher grid" + Just a -> (\(x,y) -> (x+1,y+1)) (divMod a 5) -- Convert flat index to (row, col) + +pair2chr square (x,y) = square !! ((x-1)*5+y-1) + +-- Pairs up elements from a list, used in Bifid encoding process +pairUp :: [a] -> [(a,a)] +pairUp [] = [] +pairUp [a] = error "Odd number of elements" +pairUp (x:y:ys) = (x,y):(pairUp ys) + +encrypt square message = map (pair2chr square) (pairUp (l ++ r)) where + (l,r) = unzip $ map (chr2pair square) message + +decrypt square message = map (pair2chr square) (zip u d) where + (u,d) = splitAt (length message) $ concatMap (\(x,y) -> [x,y]) $ map (chr2pair square) message + +main = do + let + message1 = "ATTACKATDAWN" + message2 = "FLEEATONCE" + encrypt1 = encrypt rcBifid message1 + encrypt2 = encrypt wikiBifid message2 + encrypt3 = encrypt wikiBifid message1 + myMessage = "The invasion will start on the first of January" + encrypt4 = encrypt cmiBifid $ map toUpper $ filter (/= ' ') myMessage -- Remove spaces, uppercase + + putStrLn $ "Message 1: " ++ message1 + putStrLn $ "Encryption wrt RC's square: " ++ encrypt1 + putStrLn $ "Decrypt: " ++ show (decrypt rcBifid encrypt1) + + putStrLn $ "Message 2: " ++ message2 + putStrLn $ "Encryption wrt Wiki's square: " ++ encrypt2 + putStrLn $ "Decrypt: " ++ show (decrypt wikiBifid encrypt2) + + putStrLn $ "Message 3: " ++ message1 + putStrLn $ "Encryption wrt Wiki's square: " ++ encrypt3 + putStrLn $ "Decrypt: " ++ show (decrypt wikiBifid encrypt3) + + putStrLn $ "Message 4: " ++ myMessage + putStrLn $ "Encryption wrt CMI square: " ++ encrypt4 + putStrLn $ "Decrypt: " ++ show (decrypt cmiBifid encrypt4) diff --git a/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 b/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 new file mode 100644 index 0000000000..67d507af7a --- /dev/null +++ b/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 @@ -0,0 +1,68 @@ +module Bifid_cipher (f, code$) { + n=sqrt(len(code$)) + print #f," "; + for i=1 to n + print #f, i+" "; + next + print #f + for i=0 to n-1 + Print #f, (i+1)+" "+STR$(mid$(code$,1+i*n, n),STRING$("@ ", 5)) + next + tables=lambda (a$)->{ + n=sqrt(len(a$)) + a=list + for i=1 to len(a$) + append a, mid$(a$,i, 1):=((i-1) mod n+1, (i-1) div n+1 ) + next + b=list + m=each(a) + while m + z=eval(m) + append b, z#val$(1)+z#val$(0):=eval$(m!) + end while + =a, b + }(code$) + encode= lambda (a, b)->{ + =lambda a,b (mess as string) -> { + document code$ + for n=1 to 0 + for i=1 to len(mess) + q=mid$(mess, i,1) + if not exist(a, q) then + if q="J" then q="I" else q="A" + end if + code$=a(q)#val$(n) + next + next + document final$ + for i=1 to len(code$) step 2 + final$=b$(mid$(code$, i, 2)) + next + = final$ + } + }(!tables) + decode= lambda (a, b)->{ + =lambda a,b (final as string) -> { + document code$, mess$ + for i=1 to len(final) + q=a(mid$(final, i, 1)) + code$=q#val$(1)+q#val$(0) + next + offset=len(code$) div 2 + for i=1 to offset + mess$=b$(mid$(code$,i,1)+mid$(code$,i+offset,1)) + next + = mess$ + } + }(!tables) + Print #f, encode("ATTACKATDAWN") + Print #f, decode(encode("ATTACKATDAWN"))="ATTACKATDAWN" + Print #f, encode(ucase$(filter$("The invasion will start on the first of January", " "))) + Print #f, decode(encode(ucase$(filter$("The invasion will start on the first of January", " ")))) +} +open "out.txt" for output as #a +Bifid_cipher a, "ABCDEFGHIKLMNOPQRSTUVWXYZ" +Bifid_cipher a, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +Bifid_cipher a, "BGWKZQPNDSIOAXEFCLUMTHYVR" +close #a +win "out.txt" diff --git a/Task/Binary-digits/Zig/binary-digits.zig b/Task/Binary-digits/Zig/binary-digits.zig new file mode 100644 index 0000000000..8b207ca0b0 --- /dev/null +++ b/Task/Binary-digits/Zig/binary-digits.zig @@ -0,0 +1,7 @@ +const std = @import("std"); + +pub fn main() void { + for(0..10) |i| { + std.debug.print("{b}\n", .{i}); + } +} diff --git a/Task/Binary-strings/Free-Pascal-Lazarus/binary-strings.pas b/Task/Binary-strings/Free-Pascal-Lazarus/binary-strings.pas new file mode 100644 index 0000000000..7a8bb08035 --- /dev/null +++ b/Task/Binary-strings/Free-Pascal-Lazarus/binary-strings.pas @@ -0,0 +1,31 @@ +uses sysutils; +var + { declaration is creation } + a,b:string; + { creation with default value } + c:string = 'this is a string'; +begin + { assignment } + a := 'test'; + b := 'test'; + writeln(a:6, b:6); + { comparison } + writeln('equal? ', a = b ); + { empty string } + writeln('empty? ', a = ''); + { cloning, copying } + a := c; + writeln('copy c to a, a is now: ', a); + { append } + b := b +'W'; + writeln('append W to b: ',b); + { extract substring } + b := copy(a,6,2); + writeln('this should be is": ',b); + { replace } + a := stringreplace(a,'i','I',[rfReplaceAll]); + writeln('replace i with I: ',a); + { join } + a:= concat(b,c); + writeln('join b and c; ',a); +end. diff --git a/Task/Binary-strings/M2000-Interpreter/binary-strings.m2000 b/Task/Binary-strings/M2000-Interpreter/binary-strings.m2000 new file mode 100644 index 0000000000..02751bf64b --- /dev/null +++ b/Task/Binary-strings/M2000-Interpreter/binary-strings.m2000 @@ -0,0 +1,51 @@ +' String assignment +a$="alfa" +string a="beta" +b="beta too" +all=a$+a+b +Print All +' String comparison +Print a$=a, a=b, a+A+" too"+a$=a+b+a$ ' false false true +b$=a$ +// compare return 0 for equal (-1,0, 1), +//same as <=> but compare work with variables only (without coping values) +print "using compare", compare(a$, b$), a$<=>b$ ' 0 0 +' String cloning and copying +a2$=a$ ' copy +' Check if a string is empty +print a2$="", len(a$)=0 +' Append a byte to a string +c$=Str$("ABCDE") ' utf16le "ABCDE" convert to ANSI (one byte per code) +Print len(c$)=2.5 ' measure 16bit, so we get 2.5x2=5 bytes +c$+=Str$("Z") +Print Len(c$)=3 +Print chr$(c$)="ABCDEZ" ' convert to UTF16LE and then compare +' Extract a substring from a string +Print chr$(mid$(c$,2, 2 as byte))="BC" +Print mid$("ABCDEZ",2,2) ="BC" +' Replace every occurrence of a byte (or a string) in a string with another string +Print Replace$("BC", "?", "ABCDEZBC")="A?DEZ?" +Print Replace$("BC", "?", CHR$(c$))="A?DEZ" +' String creation and destruction (using buffers. Memory Blocks) +' (when needed and if there's no garbage collection or similar mechanism) +'Join strings (IN A BUFFRT) +buffer clear K as byte*10 ' using clear to erase the buffer with 0 +Return K, 0:=c$ +Print eval(k, 2)=asc("C"), eval(k, 3)=asc("D") +Return k, 2:=str$("KL") +Print chr$(eval$(k, 0, 6))="ABKLEZ" +' rotate one byte +M= eval(K,0) +return k, 0:=eval$(k, 1, 5), 5:=m ' we can place strings or bytes at specific index - from 0. +Print chr$(eval$(k, 0, 6))="BKLEZA" ' true +// change length of buffer +buffer K as byte*6 +// now we get the full string (with the length of 6 bytes) +Print chr$(eval$(k))="BKLEZA" ' true +buffer K1 as byte*6 +// buffers are special objects, so we have strings refering by object pointer. +// we can pass the buffer pointer or return it from a function, also we can swap variables for buffers +swap K, k1 +Print chr$(eval$(k1))="BKLEZA" ' true +// we can get the address of string: +Print k1(0) ' return the absolute address of byte at offset 0 on k1 buffer diff --git a/Task/Binary-strings/Sidef/binary-strings.sidef b/Task/Binary-strings/Sidef/binary-strings.sidef new file mode 100644 index 0000000000..9f9f66c290 --- /dev/null +++ b/Task/Binary-strings/Sidef/binary-strings.sidef @@ -0,0 +1,48 @@ +# string creation +var x = "hello world" + +# string destruction +x = nil + +# string assignment with a null byte +x = "a\0b" +say x.length # ==> 3 + +# string comparison +if (x == "hello") { + say "equal" +} else { + say "not equal" +} + +var y = 'bc' +if (x < y) { + say "#{x} is lexicographically less than #{y}" +} + +# string cloning +var xx = x.clone +say (x == xx) # true, same length and content +say (x.refaddr == xx.refaddr) # false, different objects + +# check if empty +if (x.is_empty) { + say "is empty" +} + +# append a byte +x += "\07" +say x.dump #=> "a\0b\a" + +# substring +say x.substr(0, -1).dump #=> "a\0b" + +# replace bytes +say "hello world".tr("l", "L") + +# join strings +var a = "hel" +var b = "lo w" +var c = "orld" +var d = (a + b + c) +say d diff --git a/Task/Bioinformatics-base-count/C/bioinformatics-base-count-1.c b/Task/Bioinformatics-base-count/C/bioinformatics-base-count-1.c deleted file mode 100644 index 40a842e9b5..0000000000 --- a/Task/Bioinformatics-base-count/C/bioinformatics-base-count-1.c +++ /dev/null @@ -1,115 +0,0 @@ -#include -#include -#include - -typedef struct genome{ - char* strand; - int length; - struct genome* next; -}genome; - -genome* genomeData; -int totalLength = 0, Adenine = 0, Cytosine = 0, Guanine = 0, Thymine = 0; - -int numDigits(int num){ - int len = 1; - - while(num>10){ - num = num/10; - len++; - } - - return len; -} - -void buildGenome(char str[100]){ - int len = strlen(str),i; - genome *genomeIterator, *newGenome; - - totalLength += len; - - for(i=0;istrand = (char*)malloc(len*sizeof(char)); - strcpy(genomeData->strand,str); - genomeData->length = len; - - genomeData->next = NULL; - } - - else{ - genomeIterator = genomeData; - - while(genomeIterator->next!=NULL) - genomeIterator = genomeIterator->next; - - newGenome = (genome*)malloc(sizeof(genome)); - - newGenome->strand = (char*)malloc(len*sizeof(char)); - strcpy(newGenome->strand,str); - newGenome->length = len; - - newGenome->next = NULL; - genomeIterator->next = newGenome; - } -} - -void printGenome(){ - genome* genomeIterator = genomeData; - - int width = numDigits(totalLength), len = 0; - - printf("Sequence:\n"); - - while(genomeIterator!=NULL){ - printf("\n%*d%3s%3s",width+1,len,":",genomeIterator->strand); - len += genomeIterator->length; - - genomeIterator = genomeIterator->next; - } - - printf("\n\nBase Count\n----------\n\n"); - - printf("%3c%3s%*d\n",'A',":",width+1,Adenine); - printf("%3c%3s%*d\n",'T',":",width+1,Thymine); - printf("%3c%3s%*d\n",'C',":",width+1,Cytosine); - printf("%3c%3s%*d\n",'G',":",width+1,Guanine); - printf("\n%3s%*d\n","Total:",width+1,Adenine + Thymine + Cytosine + Guanine); - - free(genomeData); -} - -int main(int argc,char** argv) -{ - char str[100]; - int counter = 0, len; - - if(argc!=2){ - printf("Usage : %s \n",argv[0]); - return 0; - } - - FILE *fp = fopen(argv[1],"r"); - - while(fscanf(fp,"%s",str)!=EOF) - buildGenome(str); - fclose(fp); - - printGenome(); - - return 0; -} diff --git a/Task/Bioinformatics-base-count/C/bioinformatics-base-count-2.c b/Task/Bioinformatics-base-count/C/bioinformatics-base-count.c similarity index 100% rename from Task/Bioinformatics-base-count/C/bioinformatics-base-count-2.c rename to Task/Bioinformatics-base-count/C/bioinformatics-base-count.c diff --git a/Task/Bioinformatics-base-count/M2000-Interpreter/bioinformatics-base-count.m2000 b/Task/Bioinformatics-base-count/M2000-Interpreter/bioinformatics-base-count.m2000 new file mode 100644 index 0000000000..ad0dda3e8e --- /dev/null +++ b/Task/Bioinformatics-base-count/M2000-Interpreter/bioinformatics-base-count.m2000 @@ -0,0 +1,39 @@ +Module Bioinformatics_base_count (f){ + a$={ + CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG + CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG + AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT + GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT + CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG + TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA + TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT + CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG + TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC + GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT + } + Data "A", "C","G","T" + a$=filter$(a$," "+chr$(13)+chr$(10)+chr$(9)) + tot=len(a$) + k=1 + print #f, "SEQUENCE:" + for i=50 to len(a$) step 50 + Print #f, str$(k,"000: ");mid$(a$, k, 50) + k=i + next + Print #f, "BASECOUNT:" + while not empty + read t$ + b$=filter$(a$, t$) + Print #f, " "+t$+": ";len(a$)-len(b$) + swap a$, b$ + end while + Print #f, "Tot:";tot +} + +open "" for wide output as #f +Bioinformatics_base_count f +close #f +open "outtext.txt" for wide output as #f +Bioinformatics_base_count f +close #f +win "outtext.txt" diff --git a/Task/Biorhythms/C/biorhythms-2.c b/Task/Biorhythms/C/biorhythms-2.c index 3e2d9d0f69..ddd8256686 100644 --- a/Task/Biorhythms/C/biorhythms-2.c +++ b/Task/Biorhythms/C/biorhythms-2.c @@ -3,3 +3,4 @@ gcc -o cbio cbio.c -lm Age: 10717 days Physical cycle: -27% Emotional cycle: -100% +Intellectual cycle: -100% diff --git a/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 b/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 index 8b4a33c778..732e4e600f 100644 --- a/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 +++ b/Task/Biorhythms/M2000-Interpreter/biorhythms.m2000 @@ -1,24 +1,21 @@ -Module Biorhythms { - form 80 - enum bio {Physical=23, Emotional=28,Mental=33} - quadrants=(("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")) - date birth="1943-03-09" - date bioDay="1972-07-11", transition - for k=1 to 1 +Module Biorhythms (birth, bioDay, N as long = 1) { + date birth, bioDay, transition + enum bio {Physical=23, Emotional=28, Mental=33} + dim quadrants(4) + quadrants(0):=("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition") + if N<1 then N=1 + for k=1 to N long Days=bioDay-birth - Print "Day "+(bioDay)+":" - + Print "Day "+bioDay+" | Age in days: "+Days string frm="{0:-20} : {1}", pword, dfmt="YYYY-MM-DD" - long position, percentage, length, targetday + long position, percentage, length k=each(bio) while k - length=eval(k) - + length=eval(k) position=days mod length quadrant=int(4*position/length) - targetday=bioDay // get the long value of day from date type percentage=100*sin(360*position/length) - transition=bioDay+floor((quadrant+1)/4*23)-position + transition=bioDay+floor((quadrant+1)/4*length)-position select case percentage case >95 pword="peak" @@ -27,14 +24,15 @@ Module Biorhythms { case -5 to 5 pword="critical " case else - { - pword=percentage+"% ("+quadrants#val(quadrant)#val$(0)+", next " - pword+=quadrants#val(quadrant)#val$(1)+" "+str$(transition,dfmt)+")" - } + { + pword=percentage+"% ("+quadrants(quadrant)#val$(0)+", next " + pword+=quadrants(quadrant)#val$(1)+" "+str$(transition, dfmt)+")" + } end select print format$(frm, eval$(k)+" day "+(days mod length), pword) End while bioDay++ next k } -Biorhythms +form 80 +Biorhythms "1943-03-09", "1972-07-11" diff --git a/Task/Biorhythms/Scala/biorhythms.scala b/Task/Biorhythms/Scala/biorhythms-1.scala similarity index 100% rename from Task/Biorhythms/Scala/biorhythms.scala rename to Task/Biorhythms/Scala/biorhythms-1.scala diff --git a/Task/Biorhythms/Scala/biorhythms-2.scala b/Task/Biorhythms/Scala/biorhythms-2.scala new file mode 100644 index 0000000000..347b8ef0ba --- /dev/null +++ b/Task/Biorhythms/Scala/biorhythms-2.scala @@ -0,0 +1,94 @@ +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import scala.jdk.CollectionConverters._ + +object Biorhythms extends App { + + private val datePairs = List( + ("1943-03-09", "1972-07-11"), + ("1809-01-12", "1863-11-19"), + ("1809-02-12", "1863-11-19") + ) + + datePairs.foreach(calculateBiorhythms) + + private def calculateBiorhythms(dates: (String, String)): Unit = { + val formatter = DateTimeFormatter.ISO_LOCAL_DATE + val birthDate = LocalDate.parse(dates._1, formatter) + val targetDate = LocalDate.parse(dates._2, formatter) + val daysBetween = ChronoUnit.DAYS.between(birthDate, targetDate).toInt + + println(s"Birth Date: $birthDate, Target Date: $targetDate") + println(s"Days Between: $daysBetween") + + Cycle.values.foreach(processCycle(daysBetween, targetDate, _)) + + println() + } + + private def processCycle(daysBetween: Int, targetDate: LocalDate, cycle: Cycle): Unit = { + val position = daysBetween % cycle.length + val angle = 2 * Math.PI * position / cycle.length + val percentage = Math.round(100 * Math.sin(angle)).toInt + + val description = percentage match { + case p if p > 95 => "peak" + case p if p < -95 => "valley" + case p if Math.abs(p) < 5 => "critical transition" + case _ => + val quadrant = Quadrant.fromPosition(position, cycle.length) + val daysToTransition = quadrant.daysToTransition(position, cycle.length) + val transitionDate = targetDate.plusDays(daysToTransition) + val (trend, nextTransition) = quadrant.getDescriptions + s"$percentage% ($trend, $nextTransition on $transitionDate)" + } + + println(s"${cycle} day $position: $description") + } + + private enum Cycle(val length: Int) { + private case PHYSICAL extends Cycle(23) + private case EMOTIONAL extends Cycle(28) + private case MENTAL extends Cycle(33) + + override def toString: String = this match { + case PHYSICAL => "Physical" + case EMOTIONAL => "Emotional" + case MENTAL => "Mental" + } + } + + enum Quadrant { + case UpAndRising + case UpButFalling + case DownAndFalling + case DownButRising + + def getDescriptions: (String, String) = this match { + case UpAndRising => ("up and rising", "next peak") + case UpButFalling => ("up but falling", "next transition") + case DownAndFalling => ("down and falling", "next valley") + case DownButRising => ("down but rising", "next transition") + } + + def daysToTransition(position: Int, cycleLength: Int): Int = { + val quarter = cycleLength / 4 + val positionInQuadrant = position % quarter + quarter - positionInQuadrant + } + } + + private object Quadrant { + def fromPosition(position: Int, cycleLength: Int): Quadrant = { + val relativePosition = position.toDouble / cycleLength + relativePosition match { + case p if p >= 0.0 && p < 0.25 => Quadrant.UpAndRising + case p if p >= 0.25 && p < 0.5 => Quadrant.UpButFalling + case p if p >= 0.5 && p < 0.75 => Quadrant.DownAndFalling + case p if p >= 0.75 && p < 1.0 => Quadrant.DownButRising + case _ => throw new IllegalArgumentException("Position out of bounds") + } + } + } +} diff --git a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg index e19cad1f9b..64efe22d15 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg +++ b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic-2.alg @@ -1,12 +1,12 @@ #!/usr/bin/a68g --script # # -*- coding: utf-8 -*- # -PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # -PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; # c.f. [[rc:Bitmap/Bresenhams_line_algorithm]] # +PR READ "prelude/Bitmap.a68" PR; +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; PR READ "prelude/Bitmap/Bezier_curves/Cubic.a68" PR; -# The following test # -test:( +### test program ### +( REF IMAGE x = INIT LOC[16,16]PIXEL; (fill OF class image)(x, (white OF class image)); (cubic bezier OF class image)(x, (16, 1), (1, 4), (3, 16), (15, 11), (black OF class image), EMPTY); diff --git a/Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68/bitmap-b-zier-curves-quadratic.alg b/Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68/bitmap-b-zier-curves-quadratic.alg new file mode 100644 index 0000000000..c06ba96d7a --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/ALGOL-68/bitmap-b-zier-curves-quadratic.alg @@ -0,0 +1,41 @@ +BEGIN # draw a quadratic curve using Bresenham's line algoritm # + + PR READ "prelude/Bitmap.a68" PR; + PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; + + PROC quadratic bezier = ( REF IMAGE bm, INT x1, y1, x2, y2, x3, y3, nseg, REAL scale )VOID: + BEGIN + INT prevx := 0, prevy := 0; + FOR i FROM 0 TO nseg DO + REAL t = i / nseg; + REAL t1 = 1 - t; + REAL a = t1 * t1; + REAL b = 2 * t * t1; + REAL c = t * t; + INT currx = ENTIER ( scale * ( a * x1 + b * x2 + c * x3 + 0.5 ) ); + INT curry = ENTIER ( scale * ( a * y1 + b * y2 + c * y3 + 0.5 ) ); + IF i > 0 THEN + ( line OF class image )( bm + , ( prevx, prevy ) + , ( currx, curry ) + , black OF class image + ) + FI; + prevx := currx; + prevy := curry + OD + END # quadratic bezier # ; + + BEGIN + REF IMAGE bm = INIT LOC[ 1 : 60, 1 : 40 ]PIXEL; + ( fill OF class image )( bm, white OF class image ); + quadratic bezier( bm, 10, 100, 250, 270, 150, 20, 20, 70 / 300 ); + # print in monochrome # + FOR y FROM 2 UPB bm BY -1 TO 2 LWB bm DO + FOR x FROM 1 LWB bm TO 1 UPB bm DO + print( ( IF PIXEL( bm[ x, y ] ) /= white OF class image THEN "##" ELSE " " FI ) ) + OD; + print( ( newline ) ) + OD + END +END diff --git a/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy new file mode 100644 index 0000000000..2edb8d1510 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy @@ -0,0 +1,19 @@ +proc quadraticbezier x1 y1 x2 y2 x3 y3 nseg . . + for i = 0 to nseg + t = i / nseg + t1 = 1 - t + a = t1 * t1 + b = 2 * t * t1 + c = t * t + currx = a * x1 + b * x2 + c * x3 + 0.5 + curry = a * y1 + b * y2 + c * y3 + 0.5 + if i = 0 + move currx curry + else + line currx curry + . + . +. +linewidth 0.5 +clear +quadraticbezier 1 1 30 37 59 1 100 diff --git a/Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter/bitmap-b-zier-curves-quadratic.m2000 b/Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter/bitmap-b-zier-curves-quadratic.m2000 new file mode 100644 index 0000000000..a5b02611cc --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/M2000-Interpreter/bitmap-b-zier-curves-quadratic.m2000 @@ -0,0 +1,191 @@ +module bezier { + Function Bitmap { + def x as long, y as long, Import as boolean + If match("NN") then + Read x, y + else.if Match("N") Then + \\ is a file? + Read f as long + byte whitespace[0] + if not Eof(f) then + get #f, whitespace :P6$=chr$(whitespace[0]) + get #f, whitespace : P6$+=chr$(whitespace[0]) + boolean getW=true, getH=true, getV=true + long v + If p6$="P6" Then + do + get #f, whitespace + select case whitespace[0] + case 35 + {do get #f, whitespace + until whitespace[0]=10 + } + case 32, 9, 13, 10 + { if getW and x<>0 then + getW=false + else.if getH and y<>0 then + getH=false + else.if getV and v<>0 then + getV=false + end if + } + case 48 to 57 + {if getW then + x*=10 + x+=whitespace[0]-48 + else.if getH then + y*=10 + y+=whitespace[0]-48 + else.if getV then + v*=10 + v+=whitespace[0]-48 + end if + } + End Select + iF eof(f) then Error "Not a ppm file" + until getV=false + else + Error "Not a P6 ppm" + end if + Import=True + end if + else + Error "No proper arguments" + end if + if x<1 or y<1 then Error "Wrong dimensions" + structure rgb { + red as byte + green as byte + blue as byte + } + m=len(rgb)*x mod 4 + if m>0 then m=4-m ' add some bytes to raster line + m+=len(rgb) *x + Structure rasterline { + { + pad as byte*m + } + hline as rgb*x + } + Structure Raster { + magic as integer*4 + w as integer*4 + h as integer*4 + { + linesB as byte*len(rasterline)*y + } + lines as rasterline*y + } + Buffer Clear Image1 as Raster + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + if not Import then Return Image1, 0!lines:=String$(chrcode$(0xffff), Len(rasterline)*y div 2) + Buffer Clear Pad as Byte*4 + SetPixel=Lambda Image1, Pad, aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + where=alines+3*x+blines*y + if c>0 then c=color(c) + c-! + Return Pad, 0:=c as long + Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + } + GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ + where=alines+3*x+blines*y + =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + } + StrDib$=Lambda$ Image1, Raster -> { + =Eval$(Image1, 0, Len(Raster)) + } + CopyImage=Lambda Image1 (image$) -> { + if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { + Return Image1, 0:=Image$ + } Else Error "Can't Copy Image" + } + Export2File=Lambda Image1, x, y (f) -> { + Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 + x0=x*3 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad as rgbP6*x*y + For y1=y-1 to 0 { + Return pad, x*y1:=eval$(image1, 0!linesB!where, x0) + where+=x0 + m=where mod 4 : if m<>0 then where+=4-m + } + For x1=0 to x*y-1 { + Push Eval(pad, x1!b) : Return pad, x1!b:=Eval(pad, x1!r), x1!r:=Number + } + Put #f, pad + } + if Import then { + x0=x-1 : where=0 + structure rgbP6 { + r as byte, g as byte, b as byte + } + buffer Pad1 as rgbP6*x*y + Get #f, Pad1 + For x1=0 to x*y-1 { + Push Eval(pad1, x1!b) : Return pad1, x1!b:=Eval(pad1, x1!r), x1!r:=Number + } + x1=x*3 + For y1=y-1 to 0 { + Return Image1, 0!linesB!where:=Eval$(Pad1, y1*x, x1) + where+=3*(x0+1) + m=where mod 4 : if m<>0 then where+=4-m + } + } + Group Bitmap { + type:Bitmap + SetPixel=SetPixel + GetPixel=GetPixel + Image$=StrDib$ + Copy=CopyImage + ToFile=Export2File + } + =Bitmap + } + module bezier (&ppm as Bitmap, x1, y1, x2, y2, x3, y3, n, col=0){ + Group point_ { + long x,y + } + Long i + Double t, t1, a, b, c, d + Dim p(n+1)=point_ + For i = 0 To n + t = i / n + t1 = 1 - t + a = t1 ^ 2 + b = t * t1 * 2 + c = t ^ 2 + p(i).x = Int(a * x1 + b * x2 + c * x3 + .5) + p(i).y = Int(a * y1 + b * y2 + c * y3 + .5) + Next + + For i = 0 To n -1 + Br_line(p(i).x, p(i).y, p(i +1).x, p(i +1).y, col) + Next + sub Br_line(x0 As Long, y0 As Long, x1 As Long, y1 As Long, Col=0) + Local Long dx = Abs(x1 - x0), dy = Abs(y1 - y0) + Local Long sx = If(x0 < x1-> 1, -1) + Local Long sy = If(y0 < y1-> 1, -1) + Local Long er = If(dx > dy-> dx, -dy) div 2, e2 + Do + Call ppm.SetPixel(x0, y0, Col) + If x0=x1 And y0=y1 Then Exit + e2 = er + If e2 > -dx Then Er -= dy : x0 += sx + If e2 < dy Then Er += dx : y0 += sy + Always + end sub + } + A=Bitmap(250, 250) + bezier &A, 10, 100, 220, 310, 150, 20, 20 + move 3000,3000 : image A.Image$() + Open "curve.ppm" for output as #f + Call A.tofile(f) + close #f +} +bezier diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg deleted file mode 100644 index 71ca3c026d..0000000000 --- a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-1.alg +++ /dev/null @@ -1,42 +0,0 @@ -# -*- coding: utf-8 -*- # - -line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID: -BEGIN - REAL dx = ABS (x OF stop - x OF start), - dy = ABS (y OF stop - y OF start); - REAL err; - POINT here := start, - step := (1, 1); - IF x OF start > x OF stop THEN - x OF step := -1 - FI; - IF y OF start > y OF stop THEN - y OF step := -1 - FI; - IF dx > dy THEN - err := dx / 2; - WHILE x OF here /= x OF stop DO - picture[x OF here, y OF here] := color; - err -:= dy; - IF err < 0 THEN - y OF here +:= y OF step; - err +:= dx - FI; - x OF here +:= x OF step - OD - ELSE - err := dy / 2; - WHILE y OF here /= y OF stop DO - picture[x OF here, y OF here] := color; - err -:= dx; - IF err < 0 THEN - x OF here +:= x OF step; - err +:= dy - FI; - y OF here +:= y OF step - OD - FI; - picture[x OF here, y OF here] := color # ensure dots to be drawn # -END # line #; - -SKIP diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg similarity index 89% rename from Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg rename to Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg index d1ba6015a9..223c635fd0 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm-2.alg +++ b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg @@ -1,11 +1,11 @@ #!/usr/bin/a68g --script # # -*- coding: utf-8 -*- # -PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # +PR READ "prelude/Bitmap.a68" PR; PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; ### The test program: ### -test:( +( REF IMAGE x = INIT LOC[1:16, 1:16]PIXEL; (fill OF class image)(x, white OF class image); (line OF class image)(x, ( 1, 8), ( 8,16), black OF class image); diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Arturo/bitmap-bresenhams-line-algorithm.arturo b/Task/Bitmap-Bresenhams-line-algorithm/Arturo/bitmap-bresenhams-line-algorithm.arturo new file mode 100644 index 0000000000..874b30a87e --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Arturo/bitmap-bresenhams-line-algorithm.arturo @@ -0,0 +1,67 @@ +; Bitmap object definition +define :bitmap [ + init: method [width :integer height :integer][ + \width: width + \height: height + \grid: array.of:@[width height] false + ] + + setOn: method [x :integer y :integer][ + \grid\[y]\[x]: true + ] + + line: method [x0 :integer y0 :integer x1 :integer y1 :integer][ + [dx,dy]: @[abs x1 - x0, abs y1 - y0] + [x,y]: @[x0, y0] + sx: (x0 > x1) ? -> neg 1 -> 1 + sy: (y0 > y1) ? -> neg 1 -> 1 + + switch dx > dy [ + err: dx // 2 + while [x <> x1][ + \setOn x y + if negative? err: <= err - dy -> + [y, err]: @[y + sy, err + dx] + + x: x + sx + ] + ][ + err: dy // 2 + while [y <> y1][ + \setOn x y + if negative? err: <= err - dx -> + [x, err]: @[x + sx, err + dy] + y: y + sy + ] + ] + \setOn x y + ] + + string: method [][ + join.with:"\n" @[ + "+" ++ (repeat "-" \width) ++ "+" + join.with:"\n" map 0..dec \height 'y [ + "|" ++ (join.with:"" map 0..dec \width 'x -> + \grid\[dec \height-y]\[x] ? -> "@" -> " " + ) ++ "|" + ] + "+" ++ (repeat "-" \width) ++ "+" + ] + ] +] + +; Create bitmap +bitmap: to :bitmap @[17 17]! + +; and... draw a diamond shape +points: @[ + [1 8 8 16] + [8 16 16 8] + [16 8 8 1] + [8 1 1 8] +] + +loop points 'p -> + bitmap\line p\0 p\1 p\2 p\3 + +print bitmap diff --git a/Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter/bitmap-bresenhams-line-algorithm.m2000 b/Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter/bitmap-bresenhams-line-algorithm.m2000 new file mode 100644 index 0000000000..5ed0c0f987 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/M2000-Interpreter/bitmap-bresenhams-line-algorithm.m2000 @@ -0,0 +1,20 @@ +' using Twips +' twipsX is 15 twips. So for 96 dpi, we have 1440/96=15 twips/pixel +Module Bresenham_s_line_algorithm { + Module Br_line(x0 As Long, y0 As Long, x1 As Long, y1 As Long, Col=15) { + Long dx = Abs(x1 - x0), dy = Abs(y1 - y0) + Long sx = If(x0 < x1-> TWIPSX, -TWIPSX) + Long sy = If(y0 < y1-> TWIPSY, -TWIPSY) + Long er = If(dx > dy-> dx, -dy) div 2, e2 + Do + PSet col, x0, y0 + If abs(x0-x1)<=TWIPSX And abs(y0-y1)<=TWIPSY Then Exit + e2 = er + If e2 > -dx Then Er -= dy : x0 += sx + If e2 < dy Then Er += dx : y0 += sy + Always + } + cls ,0 + Br_line scale.x*.2, scale.y*.2, scale.x*.8, scale.y*.8 , #FFbb77 +} +Bresenham_s_line_algorithm diff --git a/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg index e3b8b12235..f48de65ee9 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg +++ b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm-2.alg @@ -1,13 +1,12 @@ #!/usr/bin/a68g --script # # -*- coding: utf-8 -*- # -PR READ "prelude/Bitmap.a68" PR; # c.f. [[rc:Bitmap]] # -PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; # c.f. [[rc:Bitmap/Bresenhams_line_algorithm]] # +PR READ "prelude/Bitmap.a68" PR; +PR READ "prelude/Bitmap/Bresenhams_line_algorithm.a68" PR; PR READ "prelude/Bitmap/Midpoint_circle_algorithm.a68" PR; # The following illustrates use: # - -test:( +( REF IMAGE x = INIT LOC [1:16, 1:16] PIXEL; (fill OF class image)(x, (white OF class image)); (circle OF class image)(x, (8, 8), 5, (black OF class image)); diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC/bitmap-ppm-conversion-through-a-pipe.basic b/Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC/bitmap-ppm-conversion-through-a-pipe.basic new file mode 100644 index 0000000000..5633823dd7 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/FreeBASIC/bitmap-ppm-conversion-through-a-pipe.basic @@ -0,0 +1,64 @@ +Const ancho = 400 +Const alto = 300 +Dim As Integer i, x, y +Dim As Ulong kolor + +' Set up graphics +Screenres ancho, alto, 32 +Windowtitle "Pattern Generator" + +' A little extravagant, this draws a design of dots and lines +' Fill background with color Rgb(&h40, &h80, &hc0) +Line (0, 0)-(ancho-1, alto-1), Rgb(64, 128, 192), BF + +' Draw random dots Rgb(&h20, &h40, &h80) +For i = 1 To 2000 + Pset (Rnd * (ancho-1), Rnd * (alto-1)), Rgb(32, 64, 128) +Next + +' Draw horizontal lines +For x = 0 To ancho-1 + For y = 240 To 244 + Pset (x, y), Rgb(32, 64, 128) + Next + For y = 260 To 264 + Pset (x, y), Rgb(32, 64, 128) + Next +Next + +' Draw vertical lines +For y = 0 To alto-1 + For x = 80 To 84 + Pset (x, y), Rgb(32, 64, 128) + Next + For x = 95 To 99 + Pset (x, y), Rgb(32, 64, 128) + Next +Next + +' Open PPM file to write +Dim As Integer ff = Freefile +Open "noutput.ppm" For Binary As #ff +If Err > 0 Then Print "Error opening output file": End + +' Write PPM header +Put #ff, , "P6" & Chr(10) +Put #ff, , Str(ancho) & " " & Str(alto) & Chr(10) +Put #ff, , "255" & Chr(10) + +' Write pixel data +For y = 0 To alto - 1 + For x = 0 To ancho - 1 + kolor = Point(x, y) + Put #ff, , Cbyte(kolor Shr 16) ' Blue + Put #ff, , Cbyte(kolor Shr 8) ' Green + Put #ff, , Cbyte(kolor) ' Red + Next +Next + +Close #ff + +' Convert to JPG using ImageMagick (pipe logic) +Shell "magick.exe noutput.ppm noutput.jpg" + +Sleep diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC/bitmap-read-an-image-through-a-pipe.basic b/Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC/bitmap-read-an-image-through-a-pipe.basic new file mode 100644 index 0000000000..532b629312 --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/FreeBASIC/bitmap-read-an-image-through-a-pipe.basic @@ -0,0 +1,65 @@ +Type IMAGE + w As Integer + h As Integer + bpp As Integer + dato(Any) As Ubyte +End Type + +Function readImageFile(filename As String, img As IMAGE) As Boolean + ' First convert image to PPM using temp file + Dim As String cmd = "magick.exe " & filename & " temp.ppm" + Shell(cmd) + + Dim As Integer ff = Freefile + Open "temp.ppm" For Binary As #ff + + ' Read PPM header + Dim As String linea + Line Input #ff, linea ' P6 + If Left(linea, 2) <> "P6" Then Return True + + ' Skip comments + Do + Line Input #ff, linea + If Left(linea, 1) <> "#" Then Exit Do + Loop + + img.w = Val(Left(linea, Instr(linea, " "))) + img.h = Val(Mid(linea, Instr(linea, " "))) + + ' Allocate memory for image data + Redim img.dato(img.w * img.h * 3 - 1) + + ' Read binary pixel data + Get #ff, , img.dato() + + Close #ff + Kill("temp.ppm") ' Clean up temp file + Return False +End Function + +Function writePPM(filename As String, img As IMAGE) As Boolean + Dim As Integer ff = Freefile + Open filename For Binary As #ff + + ' Write PPM header + Put #ff, , "P6" & Chr(10) + Put #ff, , Str(img.w) & " " & Str(img.h) & Chr(10) + Put #ff, , "255" & Chr(10) + + ' Write image data + For i As Integer = 0 To (img.w * img.h * 3 - 1) Step 3 + Put #ff, , img.dato(i + 1) ' Green + Put #ff, , img.dato(i + 2) ' Blue + Put #ff, , img.dato(i) ' Red + Next + + Close #ff + Return False +End Function + +' Main program +Dim As IMAGE img + +If readImageFile("example.png", img) Then Print "Error reading input file" +If writePPM("output.ppm", img) Then Print "i:\Error writing PPM file" diff --git a/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic b/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic index a955daa425..d658dc3b0d 100644 --- a/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic +++ b/Task/Bitmap-Write-a-PPM-file/FreeBASIC/bitmap-write-a-ppm-file.basic @@ -1,7 +1,8 @@ -Dim As Integer ancho = 150, alto = 200 +Dim As Integer ancho, alto +ancho = 150: alto = 200 Dim As Integer x, y ' width, height -Dim As Ubyte kolor -Screenres ancho,alto,32 +Dim As Ulong kolor +Screenres ancho, alto, 32 ' Draw circles Screenlock @@ -10,24 +11,26 @@ Circle (75, 100), 35, Rgb(0, 255, 0),,,, F Circle (75, 100), 20, Rgb(0, 0, 255),,,, F Screenunlock -' Create PPM file header -Dim encabezado As String -encabezado = "P6" & Chr(10) & Str(ancho) & " " & Str(alto) & Chr(10) & "255" & Chr(10) - ' Open PPM file to write Dim As Integer ff = Freefile -Open "i:\example.PPM" For Binary As #ff -Put #ff, , encabezado +Open "example.ppm" For Binary As #ff +If Err > 0 Then Print "Error opening output file": End + +' Create PPM file header +Print #ff, "P6" +Print #ff, "# Created using FreeBASIC" +Print #ff, ancho & " " & alto +Print #ff, "255" ' Write image data to PPM file For y = 0 To alto - 1 For x = 0 To ancho - 1 kolor = Point(x, y) - Put #ff, , Chr( kolor And &HFF) ' Red - Put #ff, , Chr((kolor Shr 8) And &HFF) ' Green - Put #ff, , Chr((kolor Shr 16) And &HFF) ' Blue - Next x -Next y + Put #ff, , Cbyte(kolor Shr 8) ' Green + Put #ff, , Cbyte(kolor) ' Blue + Put #ff, , Cbyte(kolor Shr 16) ' Red + Next +Next Close #ff diff --git a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 index c2892cc958..b3c4b9607b 100644 --- a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 +++ b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-1.m2000 @@ -50,26 +50,28 @@ Module Checkit { Return Image1, 0:=Image$ } Else Error "Can't Copy Image" } - Export2File=Lambda Image1, x, y (f) -> { + Export2File=Lambda Image1, x, y, r=len(rasterline) (f) -> { \\ use this between open and close Print #f, "P3" Print #f,"# Created using M2000 Interpreter" Print #f, x;" ";y Print #f, 255 x2=x-1 - where=24 - For y1= 0 to y-1 { + For y1= y-1 to 0 { a$="" - For x1=0 to x2 { - Print #f, a$;Eval(Image1, where +2 as byte);" "; + where=24+r*y1 + x1=0 + Print #f, Eval(Image1, where +2 as byte);" "; + Print #f, Eval(Image1, where+1 as byte);" "; + Print #f, Eval(Image1, where as byte); + where+=3 + For x1=1 to x2 { + Print #f, " ";Eval(Image1, where +2 as byte);" "; Print #f, Eval(Image1, where+1 as byte);" "; Print #f, Eval(Image1, where as byte); where+=3 - a$=" " } Print #f - m=where mod 4 - if m<>0 then where+=4-m } } Group Bitmap { @@ -81,31 +83,10 @@ Module Checkit { } =Bitmap } - A=Bitmap(10, 10) Call A.SetPixel(5,5, color(128,0,255)) Open "A2.PPM" for Output as #F Call A.ToFile(F) Close #f - ' is the same as this one - Try { - Open "A.PPM" for Output as #F - Print #f, "P3" - Print #f,"# Created using M2000 Interpreter" - Print #f, 10;" ";10 - Print #f, 255 - For y=10-1 to 0 { - a$="" - For x=0 to 10-1 { - rgb=-A.GetPixel(x, y) - Print #f, a$;Binary.And(rgb, 0xFF); " "; - Print #f, Binary.And(Binary.Shift(rgb, -8), 0xFF); " "; - Print #f, Binary.Shift(rgb, -16); - a$=" " - } - Print #f - } - Close #f - } } Checkit diff --git a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 index f65d2af1b7..0cc430b1ff 100644 --- a/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 +++ b/Task/Bitmap-Write-a-PPM-file/M2000-Interpreter/bitmap-write-a-ppm-file-2.m2000 @@ -1,177 +1,180 @@ -Module PPMbinaryP6 { - If Version<9.4 then 1000 - If Version=9.4 Then if Revision<19 then 1000 - Module Checkit { - Function Bitmap { - def x as long, y as long - If match("NN") then { - Read x, y - } else.if Match("N") Then { - E$="Not a ppm file" - Read f as long - buffer whitespace as byte - if not Eof(f) then { - get #f, whitespace : iF eof(f) then Error E$ - P6$=eval$(whitespace) - get #f, whitespace : iF eof(f) then Error E$ - P6$+=eval$(whitespace) - def boolean getW=true, getH=true, getV=true - def long v - \\ str$("P6") has 2 bytes. "P6" has 4 bytes - If p6$=str$("P6") Then { - do { - get #f, whitespace - if Eval$(whitespace)=str$("#") then { - do { - iF eof(f) then Error E$ - get #f, whitespace - } until eval(whitespace)=10 - } else { - select case eval(whitespace) - case 32, 9, 13, 10 - { - if getW and x<>0 then { - getW=false - } else.if getH and y<>0 then { - getH=false - } else.if getV and v<>0 then { - getV=false - } - } - case 48 to 57 - { - if getW then { - x*=10 - x+=eval(whitespace, 0)-48 - } else.if getH then { - y*=10 - y+=eval(whitespace, 0)-48 - } else.if getV then { - v*=10 - v+=eval(whitespace, 0)-48 - } - } - End Select - } - iF eof(f) then Error E$ - } until getV=false - } else Error "Not a P6 ppm" - } - } else Error "No proper arguments" - if x<1 or y<1 then Error "Wrong dimensions" - structure rgb { - red as byte - green as byte - blue as byte - } - m=len(rgb)*x mod 4 - if m>0 then m=4-m ' add some bytes to raster line - m+=len(rgb) *x - Structure rasterline { - { - pad as byte*m - } - \\ union pad+hline - hline as rgb*x - } - \\ we use union linesB and lines - \\ so we can address linesb as bytes - Structure Raster { - magic as integer*4 - w as integer*4 - h as integer*4 - { - linesB as byte*len(rasterline)*y - } - lines as rasterline*y - } - Buffer Clear Image1 as Raster - \\ 24 chars as header to be used from bitmap render build in functions - Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) - \\ fill white (all 255) - \\ Str$(string) convert to ascii, so we get all characters from words width to byte width - if not valid(f) then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) - Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ - where=alines+3*x+blines*y - if c>0 then c=color(c) - c-! - Return Pad, 0:=c as long - Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte - } - GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) - } - StrDib$=Lambda$ Image1, Raster -> { - =Eval$(Image1, 0, Len(Raster)) - } - CopyImage=Lambda Image1 (image$) -> { - if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { - Return Image1, 0:=Image$ - } Else Error "Can't Copy Image" - } - Export2File=Lambda Image1, x, y (f) -> { - \\ use this between open and close - Print #f, "P6";chr$(10); - Print #f,"# Created using M2000 Interpreter";chr$(10); - Print #f, x;" ";y;" 255";chr$(10); - x2=x-1 - where=0 - Buffer pad as byte*3 - For y1= 0 to y-1 { - For x1=0 to x2 { - \\ use linesB which is array of bytes - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Push Eval(pad, 2) - Return pad, 2:=Eval(pad, 0), 0:=Number - Put #f, pad - where+=3 - } - m=where mod 4 - if m<>0 then where+=4-m - } - } - if valid(F) then { - x0=x-1 - where=0 - Buffer Pad1 as byte*3 - For y1=y-1 to 0 { - For x1=0 to x0 { - Get #f, Pad1 ' Read binary - \\ reverse rgb - Push Eval(pad1, 2) - Return pad1, 2:=Eval(pad1, 0), 0:=Number - Return Image1, 0!linesB!where:=Eval$(Pad1) - where+=3 +Module P6 { + Function Bitmap { + def x as long, y as long, Import as boolean + If match("NN") then + Read x, y + else.if Match("N") Then + \\ is a file? + Read f as long + byte whitespace[0] + if not Eof(f) then + get #f, whitespace :P6$=chr$(whitespace[0]) + get #f, whitespace : P6$+=chr$(whitespace[0]) + boolean getW=true, getH=true, getV=true + long v + If p6$="P6" Then + do + get #f, whitespace + select case whitespace[0] + case 35 + {do get #f, whitespace + until whitespace[0]=10 } - m=where mod 4 - if m<>0 then where+=4-m - } - } - Group Bitmap { - SetPixel=SetPixel - GetPixel=GetPixel - Image$=StrDib$ - Copy=CopyImage - ToFile=Export2File - } - =Bitmap + case 32, 9, 13, 10 + { if getW and x<>0 then + getW=false + else.if getH and y<>0 then + getH=false + else.if getV and v<>0 then + getV=false + end if + } + case 48 to 57 + {if getW then + x*=10 + x+=whitespace[0]-48 + else.if getH then + y*=10 + y+=whitespace[0]-48 + else.if getV then + v*=10 + v+=whitespace[0]-48 + end if + } + End Select + iF eof(f) then Error "Not a ppm file" + until getV=false + else + Error "Not a P6 ppm" + end if + Import=True + end if + else + Error "No proper arguments" + end if + if x<1 or y<1 then Error "Wrong dimensions" + structure rgb { + red as byte + green as byte + blue as byte } - A=Bitmap(10, 10) - Call A.SetPixel(5,5, color(128,0,255)) - Open "A.PPM" for Output as #F - Call A.ToFile(F) - Close #f - - Print "Saved" - Open "A.PPM" for Input as #F - C=Bitmap(f) - Copy 400*twipsx,200*twipsy use C.Image$() - Close #f - } - Checkit - End - 1000 Error "Need Version 9.4, Revision 19 or higher" + m=len(rgb)*x mod 4 + if m>0 then m=4-m ' add some bytes to raster line + m+=len(rgb) *x + Structure rasterline { + { + pad as byte*m + } + hline as rgb*x + } + Structure Raster { + magic as integer*4 + w as integer*4 + h as integer*4 + { + linesB as byte*len(rasterline)*y + } + lines as rasterline*y + } + Buffer Clear Image1 as Raster + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + if not Import then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) + Buffer Clear Pad as Byte*4 + SetPixel=Lambda Image1, Pad, aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + where=alines+3*x+blines*y + if c>0 then c=color(c) + c-! + Return Pad, 0:=c as long + Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + } + GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ + where=alines+3*x+blines*y + =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + } + StrDib$=Lambda$ Image1, Raster -> { + =Eval$(Image1, 0, Len(Raster)) + } + CopyImage=Lambda Image1 (image$) -> { + if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { + Return Image1, 0:=Image$ + } Else Error "Can't Copy Image" + } + Export2File=Lambda Image1, x, y (f) -> { + Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 + x0=x*3 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad as rgbP6*x*y + For y1=y-1 to 0 { + Return pad, x*y1:=eval$(image1, 0!linesB!where, x0) + where+=x0 + m=where mod 4 : if m<>0 then where+=4-m + } + For x1=0 to x*y-1 { + Push Eval(pad, x1!b) : Return pad, x1!b:=Eval(pad, x1!r), x1!r:=Number + } + Put #f, pad + } + if Import then { + x0=x-1 : where=0 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad1 as rgbP6*x*y + Get #f, Pad1 + For x1=0 to x*y-1 { + Push Eval(pad1, x1!b) : Return pad1, x1!b:=Eval(pad1, x1!r), x1!r:=Number + } + x1=x*3 + For y1=y-1 to 0 { + Return Image1, 0!linesB!where:=Eval$(Pad1, y1*x, x1) + where+=3*(x0+1) + m=where mod 4 : if m<>0 then where+=4-m + } + } + Group Bitmap { + SetPixel=SetPixel + GetPixel=GetPixel + Image$=StrDib$ + Copy=CopyImage + ToFile=Export2File + } + =Bitmap + } + A=Bitmap(150,100) + For i=0 to 98 { + Call A.SetPixel(i, i, 0) + Call A.SetPixel(99, i, 0) + } + Call A.SetPixel(i,i,0) + Copy 200*twipsx, 100*twipsy use A.Image$() + Profiler + Open "a.ppm" for output as #F + Call A.tofile(f) + Close #f + Print Filelen("a.ppm") + Print Timecount/1000;"sec" + Profiler + exit + Image A.Image$() Export "a.jpg", 100 ' per cent quality + Print Filelen("a.jpg") + Image A.Image$() Export "a1.jpg", 10 ' per cent quality + Print Filelen("a1.jpg") + Image A.Image$() Export "a.bmp" + Print Filelen("a.bmp") ' no compression + Print Timecount/1000;"sec" + Move 5000,5000 ' twips + Image "a.jpg" + Move 5000,8000 + Image "a1.jpg" + Move 8000, 5000 + Image "a.bmp" } -PPMbinaryP6 +p6 diff --git a/Task/Bitmap/ALGOL-68/bitmap-1.alg b/Task/Bitmap/ALGOL-68/bitmap-1.alg deleted file mode 100644 index 896165161a..0000000000 --- a/Task/Bitmap/ALGOL-68/bitmap-1.alg +++ /dev/null @@ -1,48 +0,0 @@ -# -*- coding: utf-8 -*- # - -MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue); -MODE POINT = STRUCT(INT x,y); - -MODE IMAGE = [0,0]PIXEL; # instance attributes # - -MODE CLASSIMAGE = STRUCT ( # class attributes # - PIXEL black, red, green, blue, white, - PROC (REF IMAGE)REF IMAGE init, - PROC (REF IMAGE, PIXEL)VOID fill, - PROC (REF IMAGE)VOID print, -# virtual: # - REF PROC (REF IMAGE, POINT, POINT, PIXEL)VOID line, - REF PROC (REF IMAGE, POINT, INT, PIXEL)VOID circle, - REF PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID cubic bezier -); - -CLASSIMAGE class image = ( - # black = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16r00), - # red = # (#SHORTEN# 16rff, #SHORTEN# 16r00, #SHORTEN# 16r00), - # green = # (#SHORTEN# 16r00, #SHORTEN# 16rff, #SHORTEN# 16r00), - # blue = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16rff), - # white = # (#SHORTEN# 16rff, #SHORTEN# 16rff, #SHORTEN# 16rff), - # PROC init = # (REF IMAGE self)REF IMAGE: - BEGIN - (fill OF class image)(self, black OF class image); - self - END, - - # PROC fill = # (REF IMAGE self, PIXEL color)VOID: - FOR x FROM 1 LWB self TO 1 UPB self DO - FOR y FROM 2 LWB self TO 2 UPB self DO - self[x,y] := color - OD - OD, - # PROC print = # (REF IMAGE self)VOID: - printf(($n(UPB self)(3(16r2d))l$, self)), -# virtual: # - # REF PROC line = # LOC PROC (REF IMAGE, POINT, POINT, PIXEL)VOID, - # REF PROC circle = # LOC PROC (REF IMAGE, POINT, INT, PIXEL)VOID, - # REF PROC cubic bezier = # LOC PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID -); - -OP CLASSOF = (IMAGE image)CLASSIMAGE: class image; -OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image); - -SKIP diff --git a/Task/Bitmap/ALGOL-68/bitmap-2.alg b/Task/Bitmap/ALGOL-68/bitmap.alg similarity index 100% rename from Task/Bitmap/ALGOL-68/bitmap-2.alg rename to Task/Bitmap/ALGOL-68/bitmap.alg diff --git a/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 b/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 index 905292d6cb..ebd64b552a 100644 --- a/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 +++ b/Task/Bitmap/M2000-Interpreter/bitmap-1.m2000 @@ -1,72 +1,102 @@ -\ Bitmap width in pixels, height in pixels -\ Return a group object with some lambda as members: SetPixel, GetPixel, Image$ -\ copyimage -\ using Copy x, y Use Image$ we can display image$ to x, y as twips -\ we can use x*twipsx, y*twipsy for x,y as pixels -Function Bitmap (x as long, y as long) { - if x<1 or y<1 then Error "Wrong dimensions" - structure rgb { - red as byte - green as byte - blue as byte - } - m=len(rgb)*x mod 4 - if m>0 then m=4-m ' add some bytes to raster line - m+=len(rgb) *x - Structure rasterline { - { - pad as byte*m +Module Checkit { + Function Bitmap (x as long, y as long) { + if x<1 or y<1 then Error "Wrong dimensions" + structure rgb { + red as byte + green as byte + blue as byte + } + m=len(rgb)*x mod 4 + if m>0 then m=4-m ' add some bytes to raster line + m+=len(rgb) *x + Structure rasterline { + { + pad as byte*m + } + \\ union pad+hline + hline as rgb*x } - \\ union pad+hline - hline as rgb*x - } - Structure Raster { - magic as integer*4 - w as integer*4 - h as integer*4 - lines as rasterline*y - } - Buffer Clear Image1 as Raster - \\ 24 chars as header to be used from bitmap render build in functions - Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) - \\ fill white (all 255) - \\ Str$(string) convert to ascii, so we get all characters from words width to byte width - Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) - Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ - where=alines+3*x+blines*y - if c>0 then c=color(c) - c-! - Return Pad, 0:=c as long - Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + Structure Raster { + magic as integer*4 + w as integer*4 + h as integer*4 + lines as rasterline*y + } + Buffer Clear Image1 as Raster + \\ 24 chars as header to be used from bitmap render build in functions + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + \\ fill white (all 255) + \\ Str$(string) convert to ascii, so we get all characters from words width to byte width + Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) + Buffer Clear Pad as Byte*4 + SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + where=alines+3*x+blines*y + if c>0 then c=color(c) + c-! + Return Pad, 0:=c as long + Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte + } + GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ + where=alines+3*x+blines*y + =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + } + StrDib$=Lambda$ Image1, Raster -> { + =Eval$(Image1, 0, Len(Raster)) + } + CopyImage=Lambda Image1 (image$) -> { + if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { + Return Image1, 0:=Image$ + } Else Error "Can't Copy Image" + } + Export2File=Lambda Image1, x, y, r=len(rasterline) (f) -> { + \\ use this between open and close + Print #f, "P3" + Print #f,"# Created using M2000 Interpreter" + Print #f, x;" ";y + Print #f, 255 + x2=x-1 + For y1= y-1 to 0 { + a$="" + where=24+r*y1 + x1=0 + Print #f, Eval(Image1, where +2 as byte);" "; + Print #f, Eval(Image1, where+1 as byte);" "; + Print #f, Eval(Image1, where as byte); + where+=3 + For x1=1 to x2 { + Print #f, " ";Eval(Image1, where +2 as byte);" "; + Print #f, Eval(Image1, where+1 as byte);" "; + Print #f, Eval(Image1, where as byte); + where+=3 + } + Print #f + } + } + Group Bitmap { + SetPixel=SetPixel + GetPixel=GetPixel + Image$=StrDib$ + Copy=CopyImage + ToFile=Export2File + } + =Bitmap } - GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) + A=Bitmap(150,100) + For i=0 to 98 { + Call A.SetPixel(i, i, 5) + Call A.SetPixel(99, i, color(128,0,255)) } - StrDib$=Lambda$ Image1, Raster -> { - =Eval$(Image1, 0, Len(Raster)) - } - CopyImage=Lambda Image1 (image$) -> { - if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { - Return Image1, 0:=Image$ - } Else Error "Can't Copy Image" - } - Group Bitmap { - SetPixel=SetPixel - GetPixel=GetPixel - Image$=StrDib$ - Copy=CopyImage - } - =Bitmap + Call A.SetPixel(i,i,0) + Call A.SetPixel(30,50, color(128,0,255)) + Print A.GetPixel(30,50)=color(128,0,255) + move 3000, 3000 + Image A.image$() + profiler + Open "A2.PPM" for Output as #F + Call A.ToFile(F) + Close #f + print timecount } -A=Bitmap(100,100) -Call A.SetPixel(50,50, color(128,0,255)) -Print A.GetPixel(50,50)=color(128,0,255) -\\ display image to screen at 100, 50 pixel -copy 100*twipsx,50*twipsy use A.Image$() -A1=Bitmap(100,100) -Call A1.copy(A.Image$()) -copy 500*twipsx,50*twipsy use A1.Image$() +Checkit diff --git a/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 b/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 index 562ea41c5b..bae307643e 100644 --- a/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 +++ b/Task/Bitmap/M2000-Interpreter/bitmap-2.m2000 @@ -1,55 +1,57 @@ Module P6 { Function Bitmap { def x as long, y as long, Import as boolean - - If match("NN") then { + If match("NN") then Read x, y - } else.if Match("N") Then { + else.if Match("N") Then \\ is a file? Read f as long - buffer whitespace as byte - if not Eof(f) then { - get #f, whitespace :P6$=eval$(whitespace) - get #f, whitespace : P6$+=eval$(whitespace) - def boolean getW=true, getH=true, getV=true - def long v - \\ str$("P6") has 2 bytes. "P6" has 4 bytes - If p6$=str$("P6") Then { - do { + byte whitespace[0] + if not Eof(f) then + get #f, whitespace :P6$=chr$(whitespace[0]) + get #f, whitespace : P6$+=chr$(whitespace[0]) + boolean getW=true, getH=true, getV=true + long v + If p6$="P6" Then + do get #f, whitespace - if Eval$(whitespace)=str$("#") then { - do {get #f, whitespace} until eval(whitespace)=10 - } else { - select case eval(whitespace) - case 32, 9, 13, 10 - { if getW and x<>0 then { - getW=false - } else.if getH and y<>0 then { - getH=false - } else.if getV and v<>0 then { - getV=false - } - } - case 48 to 57 - {if getW then { - x*=10 - x+=eval(whitespace, 0)-48 - } else.if getH then { - y*=10 - y+=eval(whitespace, 0)-48 - } else.if getV then { - v*=10 - v+=eval(whitespace, 0)-48 - } - } - End Select + select case whitespace[0] + case 35 + {do get #f, whitespace + until whitespace[0]=10 } + case 32, 9, 13, 10 + { if getW and x<>0 then + getW=false + else.if getH and y<>0 then + getH=false + else.if getV and v<>0 then + getV=false + end if + } + case 48 to 57 + {if getW then + x*=10 + x+=whitespace[0]-48 + else.if getH then + y*=10 + y+=whitespace[0]-48 + else.if getV then + v*=10 + v+=whitespace[0]-48 + end if + } + End Select iF eof(f) then Error "Not a ppm file" - } until getV=false - } else Error "Not a P6 ppm" + until getV=false + else + Error "Not a P6 ppm" + end if Import=True - } - } else Error "No proper arguments" + end if + else + Error "No proper arguments" + end if if x<1 or y<1 then Error "Wrong dimensions" structure rgb { red as byte @@ -78,7 +80,7 @@ Module P6 { Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) if not Import then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ + SetPixel=Lambda Image1, Pad, aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ where=alines+3*x+blines*y if c>0 then c=color(c) c-! @@ -101,23 +103,41 @@ Module P6 { Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); Print #f, x;" ";y;" 255";chr$(10); x2=x-1 : where=0 - Buffer pad as byte*3 - For y1= 0 to y-1 { - For x1=0 to x2 { - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Push Eval(pad, 2) : Return pad, 2:=Eval(pad, 0), 0:=Number - Put #f, pad : where+=3 - } + x0=x*3 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad as rgbP6*x*y + For y1=y-1 to 0 { + Return pad, x*y1:=eval$(image1, 0!linesB!where, x0) + where+=x0 m=where mod 4 : if m<>0 then where+=4-m } + For x1=0 to x*y-1 { + Push Eval(pad, x1!b) : Return pad, x1!b:=Eval(pad, x1!r), x1!r:=Number + } + Put #f, pad } if Import then { - x0=x-1 : where=0 - Buffer Pad1 as byte*3 - For y1=y-1 to 0 { - For x1=0 to x0 {Get #f, Pad1 : Push Eval(pad1, 2) : Return pad1, 2:=Eval(pad1, 0), 0:=Number - Return Image1, 0!linesB!where:=Eval$(Pad1) : where+=3} - m=where mod 4 : if m<>0 then where+=4-m} + x0=x-1 : where=0 + structure rgbP6 { + r as byte + g as byte + b as byte + } + buffer Pad1 as rgbP6*x*y + Get #f, Pad1 + For x1=0 to x*y-1 { + Push Eval(pad1, x1!b) : Return pad1, x1!b:=Eval(pad1, x1!r), x1!r:=Number + } + x1=x*3 + For y1=y-1 to 0 { + Return Image1, 0!linesB!where:=Eval$(Pad1, y1*x, x1) + where+=3*(x0+1) + m=where mod 4 : if m<>0 then where+=4-m + } } Group Bitmap { SetPixel=SetPixel diff --git a/Task/Bitwise-IO/Seed7/bitwise-io.seed7 b/Task/Bitwise-IO/Seed7/bitwise-io.seed7 index a5764cfc78..413c230ed9 100644 --- a/Task/Bitwise-IO/Seed7/bitwise-io.seed7 +++ b/Task/Bitwise-IO/Seed7/bitwise-io.seed7 @@ -1,14 +1,7 @@ $ include "seed7_05.s7i"; include "bitdata.s7i"; - include "strifile.s7i"; -const proc: initWriteAscii (inout file: outFile, inout integer: bitPos) is func - begin - outFile.bufferChar := '\0;'; - bitPos := 0; - end func; - -const proc: writeAscii (inout file: outFile, inout integer: bitPos, in string: ascii) is func +const proc: writeAscii (inout msbOutBitStream: outStream, in string: ascii) is func local var char: ch is ' '; begin @@ -16,42 +9,38 @@ const proc: writeAscii (inout file: outFile, inout integer: bitPos, in string: a if ch > '\127;' then raise RANGE_ERROR; else - putBitsMsb(outFile, bitPos, ord(ch), 7); + putBits(outStream, ord(ch), 7); end if; end for; end func; -const proc: finishWriteAscii (inout file: outFile, inout integer: bitPos) is func +const proc: finishWriteAscii (inout msbOutBitStream: outStream) is func begin - putBitsMsb(outFile, bitPos, 0, 7); # Write a terminating NUL char. - write(outFile, chr(ord(outFile.bufferChar))); + putBits(outStream, 0, 7); # Write a terminating NUL char. + flush(outStream); end func; -const func string: readAscii (inout msbBitStream: aBitStream) is func +const func string: readAscii (inout msbInBitStream: inStream) is func result var string: stri is ""; local var char: ch is ' '; begin - while ch <> '\0;' do - ch := chr(getBits(aBitStream, 7)); + repeat + ch := chr(getBits(inStream, 7)); if ch <> '\0;' then stri &:= ch; end if; - end while; + until ch = '\0;'; end func; const proc: main is func local - var file: aFile is STD_NULL; - var integer: bitPos is 0; - var msbBitStream: aBitStream is msbBitStream.value; + var msbOutBitStream: outStream is msbOutBitStream.value; + var msbInBitStream: inStream is msbInBitStream.value; begin - aFile := openStriFile; - initWriteAscii(aFile, bitPos); - writeAscii(aFile, bitPos, "Hello, Rosetta Code!"); - finishWriteAscii(aFile, bitPos); - seek(aFile, 1); - aBitStream := openMsbBitStream(aFile); - writeln(literal(readAscii(aBitStream))); + writeAscii(outStream, "Hello, Rosetta Code!"); + finishWriteAscii(outStream); + inStream := openMsbInBitStream(getBytes(outStream)); + writeln(literal(readAscii(inStream))); end func; diff --git a/Task/Bitwise-operations/EasyLang/bitwise-operations.easy b/Task/Bitwise-operations/EasyLang/bitwise-operations.easy index 433a6625bb..800e7fa354 100644 --- a/Task/Bitwise-operations/EasyLang/bitwise-operations.easy +++ b/Task/Bitwise-operations/EasyLang/bitwise-operations.easy @@ -1,9 +1,10 @@ -# numbers are doubles, bit operations use 32 bits and are unsigned -x = 11 -y = 2 -print bitnot x -print bitand x y -print bitor x y -print bitxor x y -print bitshift x y -print bitshift x -y +# numbers are doubles, bit operations are unsigned, truncate +# the fractional part and use 53 integer bits +a = 14 +b = 3 +print bitand a b +print bitor a b +print bitxor a b +print bitshift a b +print bitshift a -b +print bitand a bitnot b diff --git a/Task/Bitwise-operations/M2000-Interpreter/bitwise-operations.m2000 b/Task/Bitwise-operations/M2000-Interpreter/bitwise-operations.m2000 new file mode 100644 index 0000000000..7185314544 --- /dev/null +++ b/Task/Bitwise-operations/M2000-Interpreter/bitwise-operations.m2000 @@ -0,0 +1,43 @@ +module binary_ops{ + select case random(1, 6) + case 1 + Double x=10, y=2 + case 2 + Decimal x=10, y=2 + case 3 + Integer x=10, y=2 + case 4 + Long x=10, y=2 + case 5 ' byte from 0 to 255 (unsigned) + Byte x=10, y=2 + case else + Long Long x=10, y=2 + end select + print type$(x) + //x & y values from 0 to 4294967295 + print binary.not(x)=4294967285, sint(binary.not(x))=-11 + print binary.and(x, y)=2 + print binary.or(x, y)=10 + // y values -31 to 31 + print binary.xor(x, y)=8 + print binary.shift(x, y)=40 + print binary.shift(x, -y)=2 + print binary.rotate(x, y)=40 + print binary.rotate(x, -y)=2147483650, sint(binary.rotate(x, -y))=-2147483646 + // Binary.Neg return Unsigned from signed values: -2147483648 (0x8000_0000&) to 2147483647 (0x7FFF_FFFF&) + // values>2147483647 return 2147483648 + // values <-2147483648 return 2147483647 + // 0xFFFF_ABCD& (signed value), 0xFFFF_ABCD unsinged value same bits + print 0xFFFF_ABCD&=-21555, 0xFFFF_ABCD=4294945741, sint(0xFFFF_ABCD)=-21555 + print Binary.Neg(0xFFFF_ABCD&)=21554, Binary.Not(0xFFFF_ABCD)=21554 + print sint(Binary.Neg(0xFFFF_ABCD&)+ uint(0xFFFF_ABCD&))=sint(Binary.Neg(0)) + // signed 0xFFFF_ABCD& has same bits as unsigned 0xFFFF_ABCD, + // but have different value as used in calculations + print Binary.Neg(0xFFFF_ABCD&)=Binary.Not(0xFFFF_ABCD), 0xFFFF_ABCD&<>0xFFFF_ABCD + print Binary.Neg(0x0FFF_ABCD&)=Binary.Not(0x0FFF_ABCD), 0xFFFF_ABCD&<>0xFFFF_ABCD + // Add (modulo 32), x unsigned and add a negate signed (converted to unsigned) + print binary.add(x, binary.neg(y), 1)=8 ' 10 - 2 =12 + print binary.add(x, binary.neg(-y), 1)=12 ' 10 - - 2 = 12 + print sint(binary.neg(x))=-11, binary.neg(x)=binary.not(x) +} +binary_ops diff --git a/Task/Bitwise-operations/Nim/bitwise-operations.nim b/Task/Bitwise-operations/Nim/bitwise-operations.nim index 6932b12574..d831e18c5f 100644 --- a/Task/Bitwise-operations/Nim/bitwise-operations.nim +++ b/Task/Bitwise-operations/Nim/bitwise-operations.nim @@ -1,4 +1,4 @@ -proc bitwise(a, b) = +proc bitwise[T: SomeInteger](a, b: T) = echo "a and b: " , a and b echo "a or b: ", a or b echo "a xor b: ", a xor b diff --git a/Task/Bitwise-operations/Raku/bitwise-operations.raku b/Task/Bitwise-operations/Raku/bitwise-operations.raku index a7596faadb..7cbeacac55 100644 --- a/Task/Bitwise-operations/Raku/bitwise-operations.raku +++ b/Task/Bitwise-operations/Raku/bitwise-operations.raku @@ -9,7 +9,8 @@ sub int-bits (Int $a, Int $b) { say ''; say_bit "$a", $a; say ''; - say_bit "2's complement $a", +^$a; + say_bit "1's complement (not) $a", +^$a; + say_bit "2's complement $a", +^$a + 1; say_bit "$a and $b", $a +& $b; say_bit "$a or $b", $a +| $b; say_bit "$a xor $b", $a +^ $b; diff --git a/Task/Blum-integer/Ada/blum-integer.ada b/Task/Blum-integer/Ada/blum-integer.ada new file mode 100644 index 0000000000..5c8e2c59ca --- /dev/null +++ b/Task/Blum-integer/Ada/blum-integer.ada @@ -0,0 +1,89 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; + +procedure Blum is + + Inc : Constant array (1 .. 8) of Integer := (4, 2, 4, 2, 4, 6, 2, 6); + + function Is_Prime (N : Integer) return Boolean is + D : Integer := 5; + begin + if N < 2 then return False; end if; + if N mod 2 = 0 then return N = 2; end if; + if N mod 3 = 0 then return N = 3; end if; + + while D * D <= N loop + if N mod D = 0 then return False; end if; + D := D + 2; + if N mod D = 0 then return False; end if; + D := D + 4; + end loop; + + return True; + end Is_Prime; + + function First_Prime_Factor (N : Integer) return Integer is + D : Integer := 7; + I : Integer := 1; + begin + if N = 1 then return 1; end if; + if N mod 3 = 0 then return 3; end if; + if N mod 5 = 0 then return 5; end if; + + while D * D <= N loop + if N mod D = 0 then + return D; + end if; + D := D + Inc(I); + I := (I mod 8) + 1; + end loop; + + return N; + end First_Prime_Factor; + + I, Blum_Count : Integer := 1; + J, P, Q : Integer; + Blums : Array (1 .. 50) of Integer; + Counts : Array (1 .. 4) of Integer := (others => 0); + Final_Digits : Array (1 .. 4) of Integer := (1, 3, 7, 9); + +begin + loop + P := First_Prime_Factor(I); + if P mod 4 = 3 then + Q := I / P; + if Q /= P and Q mod 4 = 3 and Is_Prime(Q) then + if Blum_Count < 51 then Blums(Blum_Count) := I; end if; + Counts(((I mod 10) / 3) + 1) := Counts(((I mod 10) / 3) + 1) + 1; + Blum_Count := Blum_Count + 1; + if Blum_Count = 51 then + Put("First 50 Blum Integers:"); New_Line; + for J in Integer range 1 .. 50 loop + Put(Item => Blums(J), Width => 3); Put(" "); + if J mod 10 = 0 then New_Line; end if; + end loop; + New_Line; + elsif Blum_Count = 26829 or Blum_Count mod 100000 = 1 then + Put("The "); Put(Item => Blum_Count, Width => 7); + Put("th Blum Integer is: "); Put(Item => I, Width => 9); + New_Line; + if Blum_Count = 400001 then + New_Line; Put("% Distribution of the First 400,000 Blum Integers:"); New_Line; + for J in Integer range 1 .. 4 loop + Put(" "); Put(Item => Float(Counts(J)) / 4000.0, Fore => 2, Aft => 3, Exp => 0); + Put("% end in "); Put(Item => Final_Digits(J), Width => 1); + New_Line; + end loop; + exit; + end if; + end if; + end if; + end if; + if I mod 5 = 3 then + I := I + 4; + else + I := I + 2; + end if; + end loop; +end Blum; diff --git a/Task/Blum-integer/Fortran/blum-integer.f b/Task/Blum-integer/Fortran/blum-integer.f new file mode 100644 index 0000000000..1108cc2fbe --- /dev/null +++ b/Task/Blum-integer/Fortran/blum-integer.f @@ -0,0 +1,158 @@ +program BlumInteger + use, intrinsic :: iso_fortran_env, only: int32, int64 + implicit none + + integer(int32), parameter :: LIMIT = 10*1000*1000 + integer(int32), allocatable :: BlumPrimes(:) + integer(int32), allocatable :: BlumPrimes2(:) + logical :: BlumField(0:LIMIT) + integer(int32) :: EndDigit(0:9) + integer(int64) :: k + integer(int32) :: n, idx, j, P4n3Cnt,xx,yy + call system_clock(count=xx) + call Sieve4n_3_Primes(LIMIT, BlumPrimes2) +! allocate(blumprimes(0:size(BlumPrimes2)-1)) +! The blumprimes2 array is allocated in the subroutine as a zero based array +! but, the main program doesn't know that and assumes it's 1 based so we allocate +! a zero based array then use move_alloc to correctly resize it a transfer the data + allocate(blumprimes(0:1)) + call move_alloc(blumprimes2,blumprimes) + P4n3Cnt = size(BlumPrimes) -1 + print *, 'There are ', CommaUint(int(P4n3Cnt, int64)), ' needed primes 4*n+3 to Limit ', CommaUint(int(LIMIT, int64)) + P4n3Cnt = P4n3Cnt - 1 + print * + + ! Generate Blum-Integers + BlumField = .false. + do idx = 0, P4n3Cnt + n = BlumPrimes(idx) + do j = idx+1, P4n3Cnt + k = int(n, int64) * int(BlumPrimes(j), int64) + if (k > LIMIT) exit + BlumField(k) = .true. + end do + end do + call system_clock(count=yy) + print *, 'First 50 Blum-Integers ' + idx = 0 + j = 0 + do + do while (idx < LIMIT .and. .not. BlumField(idx)) + idx = idx + 1 + end do + if (idx == LIMIT) exit + if (mod(j, 10) == 0 .and. j /= 0) print * + write(*, '(I5)', advance='no') idx + j = j + 1 + idx = idx + 1 + if (j >= 50) exit + end do + print '(//)' + + print *, ' relative occurence of digit' + print *, ' n.th |BlumInteger|Digit: 1 3 7 9' + idx = 0 + j = 0 + n = 0 + k = 26828 + EndDigit = 0 + do + do while (idx < LIMIT .and. .not. BlumField(idx)) + idx = idx + 1 + end do + if (idx == LIMIT) exit + ! Count last decimal digit + EndDigit(mod(idx, 10)) = EndDigit(mod(idx, 10)) + 1 + j = j + 1 + if (j == k) then + write(*, '(A10,A1,A11,A1)', advance='no') CommaUint(int(j, int64)), '|', CommaUint(int(idx, int64)), '|' + write(*, '(F7.3,A4)', advance='no') real(EndDigit(1))/j*100, '% |' + write(*, '(F7.3,A4)', advance='no') real(EndDigit(3))/j*100, '% |' + write(*, '(F7.3,A4)', advance='no') real(EndDigit(7))/j*100, '% |' + write(*, '(F7.3,A2)') real(EndDigit(9))/j*100, '%' + if (k < 100000) then + k = 100000 + else + k = k + 100000 + end if + end if + idx = idx + 1 + if (j >= 400000) exit + end do + print '(/,a,f8.6,1x,a)', 'Elapsed time = ',(yy-xx)/1000.0,'seconds' +contains + + subroutine Sieve4n_3_Primes(Limit, P4n3) + use iso_fortran_env + integer(int32), intent(in) :: Limit + integer(int32), allocatable, intent(out) :: P4n3(:) + integer(kind=1), allocatable :: sieve(:) + integer(int32) :: BlPrCnt, idx, n, j, sieve_size + + sieve_size = (Limit / 3 - 3) / 4 + 1 + allocate(sieve(0:sieve_size-1)) + allocate(P4n3(0:sieve_size-1)) + + sieve = 0 + BlPrCnt = 0 + idx = 0 + do + if (sieve(idx) == 0) then + n = idx*4 + 3 + P4n3(BlPrCnt) = n + BlPrCnt = BlPrCnt + 1 + j = idx + n + if (j > ubound(sieve, 1)) exit + do while (j <= ubound(sieve, 1)) + sieve(j) = 1 + j = j + n + end do + end if + idx = idx + 1 + if (idx > ubound(sieve, 1)) exit + end do + ! Collect the rest + do idx = idx, ubound(sieve, 1) + if (sieve(idx) == 0) then + P4n3(BlPrCnt) = idx*4 + 3 + BlPrCnt = BlPrCnt + 1 + end if + end do + P4n3 = P4n3(0:BlPrCnt-1) + end subroutine Sieve4n_3_Primes + + function CommaUint(n) result(res) + integer, parameter :: sizer = 30 + integer(int64), intent(in) :: n + character(:), allocatable :: res + character(len=sizer) :: temp + integer :: fromIdx, toIdx, i + character :: pRes(sizer) + + write(temp, '(I0)') n + fromIdx = len_trim(temp) + toIdx = fromIdx - 1 + if (toIdx < 3) then + res = temp(1:fromIdx) + return + end if + allocate(res, mold=repeat(' ',sizer)) + toIdx = 4*(toIdx / 3) + mod(toIdx, 3) + 1 + pRes = ' ' + + do i = 1, fromIdx + pRes(toIdx) = temp(fromIdx-i+1:fromIdx-i+1) + toIdx = toIdx - 1 + if (mod(i, 3) == 0 .and. i /= fromIdx) then + pRes(toIdx) = ',' + toIdx = toIdx - 1 + end if + end do + do i = 1,sizer ! Go from character array to string + res(I:I) = pRes(i) + end do +! + res = trim(adjustl(Res)) + end function CommaUint + +end program BlumInteger diff --git a/Task/Blum-integer/FreeBASIC/blum-integer.basic b/Task/Blum-integer/FreeBASIC/blum-integer.basic index 8b1bdd7df5..4f8b7da16f 100644 --- a/Task/Blum-integer/FreeBASIC/blum-integer.basic +++ b/Task/Blum-integer/FreeBASIC/blum-integer.basic @@ -1,39 +1,76 @@ -Dim Shared As Uinteger Prime1 -Dim As Uinteger n = 3, c = 0, Prime2 +#include "isprime.bas" -Function isSemiprime(n As Uinteger) As Boolean - Dim As Uinteger d = 3, c = 0 - While d*d <= n - While n Mod d = 0 - If c = 2 Then Return False - n /= d - c += 1 - Wend - d += 2 - Wend - Prime1 = n - Return c = 1 +Type PrimeHelper + inc(7) As Integer + idx As Integer +End Type + +Function initPrimeHelper() As PrimeHelper + Dim helper As PrimeHelper + helper.inc(0) = 4 : helper.inc(1) = 2 : helper.inc(2) = 4 + helper.inc(3) = 2 : helper.inc(4) = 4 : helper.inc(5) = 6 + helper.inc(6) = 2 : helper.inc(7) = 6 + helper.idx = 0 + Return helper End Function -Print "The first 50 Blum integers:" -Do - If isSemiprime(n) Then - If Prime1 Mod 4 = 3 Then - Prime2 = n / Prime1 - If (Prime2 <> Prime1) And (Prime2 Mod 4 = 3) Then - c += 1 - If c <= 50 Then - Print Using "####"; n; - If c Mod 10 = 0 Then Print - End If - If c >= 26828 Then - Print !"\nThe 26828th Blum integer is: " ; n - Exit Do +Function firstPrimeFactor(n As Integer) As Integer + If n = 1 Then Return 1 + If n Mod 3 = 0 Then Return 3 + If n Mod 5 = 0 Then Return 5 + + Dim helper As PrimeHelper = initPrimeHelper() + Dim k As Integer = 7 + + While k * k <= n + If n Mod k = 0 Then Return k + k += helper.inc(helper.idx) + helper.idx = (helper.idx + 1) Mod 8 + Wend + + Return n +End Function + +Sub main() + Dim As Integer blum(49), counts(9) + Dim As Integer bc = 0, i = 1, p, q + Dim As Integer j + + Dim As Double t0 = Timer + Do + p = firstPrimeFactor(i) + If p Mod 4 = 3 Then + q = i \ p + If q <> p Andalso q Mod 4 = 3 Andalso isPrime(q) Then + If bc < 50 Then blum(bc) = i + counts(i Mod 10) += 1 + bc += 1 + + If bc = 50 Then + Print "First 50 Blum integers:" + For j = 0 To 49 + Print Using "####"; blum(j); + If (j + 1) Mod 10 = 0 Then Print + Next + Print + Elseif bc = 26828 Orelse bc Mod 100000 = 0 Then + Print Using "The ###,###th Blum integer is: #,###,###"; bc; i + + If bc = 400000 Then + Print !"\n% distribution of the first 400,000 Blum integers:" + For j = 1 To 9 Step 2 + If j <> 5 Then Print Using " ##.###% end in #"; (counts(j)/4000); j + Next + Exit Do + End If End If End If End If - End If - n += 2 -Loop + i += Iif(i Mod 5 = 3, 4, 2) + Loop + Print Chr(10); Timer - t0; " sec." +End Sub + +main() Sleep diff --git a/Task/Blum-integer/Gambas/blum-integer.gambas b/Task/Blum-integer/Gambas/blum-integer.gambas index 027cc6a610..ce94e9d661 100644 --- a/Task/Blum-integer/Gambas/blum-integer.gambas +++ b/Task/Blum-integer/Gambas/blum-integer.gambas @@ -1,44 +1,67 @@ -Public Prime1 As Integer +Use "isprime.bas" -Public Sub Main() +Private inc As Integer[] = [4, 2, 4, 2, 4, 6, 2, 6] - Dim n As Integer = 3, c As Integer = 0, Prime2 As Integer +Private Function FirstPrimeFactor(n As Long) As Long - Print "The first 50 Blum integers:" - Do - If isSemiprime(n) Then - If Prime1 Mod 4 = 3 Then - Prime2 = n / Prime1 - If (Prime2 <> Prime1) And (Prime2 Mod 4 = 3) Then - c += 1 - If c <= 50 Then - Print Format$(n, "####"); - If c Mod 10 = 0 Then Print - End If - If c >= 26828 Then - Print "\nThe 26828th Blum integer is: "; n - Break - End If - End If - End If - End If - n += 2 - Loop + If n = 1 Then Return 1 + If n Mod 3 = 0 Then Return 3 + If n Mod 5 = 0 Then Return 5 + + Dim k As Long = 7 + Dim i As Integer = 0 + + While k * k <= n + If n Mod k = 0 Then Return k + k += inc[i] + i = (i + 1) Mod 8 + Wend + + Return n End -Function isSemiprime(n As Integer) As Boolean +Public Sub Main() - Dim d As Integer = 3, c As Integer = 0 - While d * d <= n - While n Mod d = 0 - If c = 2 Then Return False - n /= d - c += 1 - Wend - d += 2 + Dim blum As New Long[50] + Dim counts As New Collection + + counts[1] = 0 + counts[3] = 0 + counts[7] = 0 + counts[9] = 0 + + Dim bc As Long = 0, i As Long = 1 + + While True + Dim p As Long = FirstPrimeFactor(i) + If p Mod 4 = 3 Then + Dim q As Long = i \ p + If q <> p And q Mod 4 = 3 And IsPrime(q) Then + If bc < 50 Then blum[bc] = i + counts[i Mod 10] += 1 + bc += 1 + + If bc = 50 Then + Print "First 50 Blum integers:" + For j As Integer = 0 To 49 + Print Format(blum[j], "####"); " "; + If (j + 1) Mod 10 = 0 Then Print + Next + Print + Else If bc = 26828 Or bc Mod 100000 = 0 Then + Print "The "; Format(bc, " ###,###"); "th Blum integer is: "; Format(i, " #,###,###") + If bc = 400000 Then + Print Chr(10); "% distribution of the first 400,000 Blum integers:" + For Each j As Integer In [1, 3, 7, 9] + Print Format(counts[j] / 4000, " ##.###"); "% end in "; j + Next + Return + Endif + Endif + Endif + Endif + i += If(i Mod 5 = 3, 4, 2) Wend - Prime1 = n - Return c = 1 -End Function +End diff --git a/Task/Blum-integer/OxygenBasic/blum-integer.basic b/Task/Blum-integer/OxygenBasic/blum-integer.basic new file mode 100644 index 0000000000..50ba04d0a0 --- /dev/null +++ b/Task/Blum-integer/OxygenBasic/blum-integer.basic @@ -0,0 +1,78 @@ +#include "isprime.bas" +uses console + +dim inc(7) as integer +inc(0) = 4: inc(1) = 2: inc(2) = 4 +inc(3) = 2: inc(4) = 4: inc(5) = 6 +inc(6) = 2: inc(7) = 6 + +function firstPrimeFactor(n as long) as long + if n = 1 then return 1 + if n mod 3 = 0 then return 3 + if n mod 5 = 0 then return 5 + + long k = 7 + int idx = 0 + + while k * k <= n + if mod(n, k) = 0 then return k + k += inc(idx) + idx = mod((idx + 1), 8) + wend + return n +end function + +sub main() + dim as long blum(49), counts(9) + long bc = 0, i = 1, pct, p, q + int j + string s, t + + do + p = firstPrimeFactor(i) + if p mod 4 = 3 then + q = i \ p + if q <> p and q mod 4 = 3 and isPrime(q) then + if bc < 50 then blum(bc) = i + counts(i mod 10) = counts(i mod 10) + 1 + bc += 1 + + if bc = 50 then + printl "First 50 Blum integers:" + for j = 0 to 49 + s = str(blum(j)) + while len(s) < 4: s = " " + s: wend + print s; + if mod((j + 1), 10) = 0 then printl + next + printl + elseif bc = 26828 or bc mod 100000 = 0 then + s = str(bc) + while len(s) < 6: s = " " + s: wend + t = str(i) + while len(t) < 7: t = " " + t: wend + printl "The " + s + "th Blum integer is: " + t + if bc = 400000 then + printl cr "% distribution of the first 400,000 Blum integers:" + + for j = 1 to 9 step 2 + if j <> 5 then + pct = counts(j)/4000 + s = str(pct) + while len(s) < 5: s = " " + s: wend + printl s + "% end in " + str(j) + end if + next + end + end if + end if + end if + end if + if mod(i, 5) = 3 then i += 4 else i += 2 + end do +end sub + +main() + +printl cr "Enter ..." +waitkey diff --git a/Task/Blum-integer/PureBasic/blum-integer.basic b/Task/Blum-integer/PureBasic/blum-integer.basic new file mode 100644 index 0000000000..191ab6d065 --- /dev/null +++ b/Task/Blum-integer/PureBasic/blum-integer.basic @@ -0,0 +1,69 @@ +XIncludeFile "isprime.pb" + +Structure PrimeHelper + inc.i[8] + index.i +EndStructure + +Procedure.i firstPrimeFactor(n.q) + If n = 1 : ProcedureReturn 1 : EndIf + If n % 3 = 0 : ProcedureReturn 3 : EndIf + If n % 5 = 0 : ProcedureReturn 5 : EndIf + + Define helper.PrimeHelper + helper\inc[0] = 4 : helper\inc[1] = 2 : helper\inc[2] = 4 + helper\inc[3] = 2 : helper\inc[4] = 4 : helper\inc[5] = 6 + helper\inc[6] = 2 : helper\inc[7] = 6 + + Define k.q = 7 + While k * k <= n + If n % k = 0 : ProcedureReturn k : EndIf + k + helper\inc[helper\index] + helper\index = (helper\index + 1) % 8 + Wend + ProcedureReturn n +EndProcedure + +OpenConsole() +Define Dim blum.q(49) +Define.q bc = 0, i = 1 +Define Dim counts.q(9) + +Repeat + Define p.q = firstPrimeFactor(i) + If p % 4 = 3 + Define q.q = i / p + If q <> p And q % 4 = 3 And isPrime(q) + If bc < 50 : blum(bc) = i : EndIf + counts(i % 10) + 1 + bc + 1 + + If bc = 50 + PrintN("First 50 Blum integers:") + For j = 0 To 49 + Print(" " + RSet(Str(blum(j)), 3)) + If (j + 1) % 10 = 0 : PrintN("") : EndIf + Next + PrintN("") + ElseIf bc = 26828 Or bc % 100000 = 0 + PrintN("The " + RSet(Str(bc), 6) + "th Blum integer is: " + RSet(Str(i), 7)) + If bc = 400000 + PrintN(#CRLF$ + "% distribution of the first 400,000 Blum integers:") + For j = 1 To 9 Step 2 + If j <> 5 + PrintN(RSet(StrF(counts(j)/4000, 3), 5) + "% end in " + Str(j)) + EndIf + Next + Break + EndIf + EndIf + EndIf + EndIf + If i % 5 = 3 + i + 4 + Else + i + 2 + EndIf +ForEver + +PrintN(#CRLF$ + "Press ENTER to exit"): Input() diff --git a/Task/Blum-integer/QB64/blum-integer.qb64 b/Task/Blum-integer/QB64/blum-integer.qb64 new file mode 100644 index 0000000000..9b3a0be158 --- /dev/null +++ b/Task/Blum-integer/QB64/blum-integer.qb64 @@ -0,0 +1,73 @@ +Dim Shared inc(7) As Integer +inc(0) = 4: inc(1) = 2: inc(2) = 4 +inc(3) = 2: inc(4) = 4: inc(5) = 6 +inc(6) = 2: inc(7) = 6 + +Dim blum(49) As Long +Dim counts(9) As Long +Dim bc As Long, i As Long, p As Long, q As Long, j As Integer +i = 1 + +Do + p = firstPrimeFactor(i) + If p Mod 4 = 3 Then + q = i \ p + If q <> p And q Mod 4 = 3 And isPrime(q) Then + If bc < 50 Then blum(bc) = i + counts(i Mod 10) = counts(i Mod 10) + 1 + bc = bc + 1 + + If bc = 50 Then + Print "First 50 Blum integers:" + For j = 0 To 49 + Print Using "####"; blum(j); + If (j + 1) Mod 10 = 0 Then Print + Next + Print + ElseIf bc = 26828 Or bc Mod 100000 = 0 Then + Print Using "The ###,###th Blum integer is: #,###,###"; bc; i + If bc = 400000 Then + Print Chr$(10); "% distribution of the first 400,000 Blum integers:" + For j = 1 To 9 Step 2 + If j <> 5 Then + Print Using " ##.###% end in #"; (counts(j%) / 4000); j% + End If + Next + End + End If + End If + End If + End If + If i Mod 5 = 3 Then i = i + 4 Else i = i + 2 +Loop +End + +Function firstPrimeFactor& (n As Long) + Dim k As Long, idx As Integer + If n = 1 Then firstPrimeFactor& = 1: Exit Function + If n Mod 3 = 0 Then firstPrimeFactor& = 3: Exit Function + If n Mod 5 = 0 Then firstPrimeFactor& = 5: Exit Function + k = 7: idx = 0 + Do While k * k <= n + If n Mod k = 0 Then + firstPrimeFactor& = k + Exit Function + End If + k = k + inc(idx) + idx = (idx + 1) Mod 8 + Loop + firstPrimeFactor& = n +End Function + +Function isPrime% (n As Long) + Dim i As Long + If n <= 1 Then Exit Function + If n <= 3 Then isPrime% = 1: Exit Function + If n Mod 2 = 0 Or n Mod 3 = 0 Then Exit Function + i = 5 + While i * i <= n + If n Mod i = 0 Or n Mod (i + 2) = 0 Then Exit Function + i = i + 6 + Wend + isPrime% = 1 +End Function diff --git a/Task/Boyer-Moore-string-search/Free-Pascal-Lazarus/boyer-moore-string-search.pas b/Task/Boyer-Moore-string-search/Free-Pascal-Lazarus/boyer-moore-string-search.pas new file mode 100644 index 0000000000..2a2772d84a --- /dev/null +++ b/Task/Boyer-Moore-string-search/Free-Pascal-Lazarus/boyer-moore-string-search.pas @@ -0,0 +1,62 @@ +{$mode objfpc}{$H+} +uses strutils, classes; +const s:string = 'GCTAGCTCTACGAGTCTA'+ LineEnding + + 'GGCTATAATGCGTA'+ LineEnding + + 'there would have been a time for such a word'+ LineEnding + + 'needle need noodle needle'+ LineEnding + + 'DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages'+ LineEnding + + 'Nearby farms grew an acre of alfalfa on the dairy''s behalf, with bales of that alfalfa exchanged for milk.'; + +var + List:TStringlist; + matches:SizeIntArray; + i:SizeInt; +begin + List := TStringlist.Create; + try + List.Text := s; + if FindMatchesBoyerMooreCaseSensitive(List[0],'TCTA',matches,true) then + begin + write('TCTA found at index: '); + for i in matches do write(i:4); + writeln; + end else writeln('no matches found'); + + if FindMatchesBoyerMooreCaseSensitive(List[1],'TAATAAA',matches,true) then + begin + write('TAATAAA found at index: '); + for i in matches do write(i:4); + writeln; + end else writeln('no matches found for TAATAAA'); + + if FindMatchesBoyerMooreCaseSensitive(List[2],'word',matches,true) then + begin + write('word found at index: '); + for i in matches do write(i:4); + writeln; + end else writeln('no matches found for word'); + + if FindMatchesBoyerMooreCaseSensitive(List[3],'needle',matches,true) then + begin + write('needle found at index: '); + for i in matches do write(i:4); + writeln; + end else writeln('no matches found for needle'); + + if FindMatchesBoyerMooreCaseSensitive(List[4],'and',matches,true) then + begin + write('and found at index: '); + for i in matches do write(i:4); + writeln; + end else writeln('no matches found for and'); + + if FindMatchesBoyerMooreCaseSensitive(List[5],'alfalfa',matches,true) then + begin + write('alfalfa found at index: '); + for i in matches do write(i:4); + writeln; + end else writeln('no matches found for alfalfa'); + finally + List.Free; + end; +end. diff --git a/Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search-1.pas b/Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search-1.pas new file mode 100644 index 0000000000..dfbfd37b6c --- /dev/null +++ b/Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search-1.pas @@ -0,0 +1,2 @@ +FindMatchesBoyerMooreCaseInSensitive; +FindMatchesBoyerMooreCaseSensitive; diff --git a/Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search.pas b/Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search-2.pas similarity index 100% rename from Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search.pas rename to Task/Boyer-Moore-string-search/Pascal/boyer-moore-string-search-2.pas diff --git a/Task/Brilliant-numbers/00-TASK.txt b/Task/Brilliant-numbers/00-TASK.txt index e17610886b..24c4103983 100644 --- a/Task/Brilliant-numbers/00-TASK.txt +++ b/Task/Brilliant-numbers/00-TASK.txt @@ -23,4 +23,5 @@ ;See also ;* [https://www.numbersaplenty.com/set/brilliant_number Numbers Aplenty - Brilliant numbers] +;* [https://www.alpertron.com.ar/BRILLIANT.HTM - Like the task upper Limit 1E201] ;* [[oeis:A078972|OEIS:A078972 - Brilliant numbers: semiprimes whose prime factors have the same number of decimal digits]] diff --git a/Task/Brilliant-numbers/Free-Pascal-Lazarus/brilliant-numbers.pas b/Task/Brilliant-numbers/Free-Pascal-Lazarus/brilliant-numbers.pas index c38497d189..d85407517a 100644 --- a/Task/Brilliant-numbers/Free-Pascal-Lazarus/brilliant-numbers.pas +++ b/Task/Brilliant-numbers/Free-Pascal-Lazarus/brilliant-numbers.pas @@ -2,227 +2,259 @@ program BrilliantNumbers; {$IFDEF FPC} {$MODE Delphi} {$Optimization ON,All} + {$codealign proc=32,loop=1} {$ENDIF} {$IFDEF WINDOWS} {$APPTYPE CONSOLE} {$ENDIF} - uses - SysUtils,classes; + SysUtils,primSieve,classes; const - MaxRoot = 100*1000*1000+2310;//+2310 to get next prime beyond limit + MaxRoot =1000*1000*1000; type - tPrimeDelta = array of Uint8; + tPrime = array of Uint32; + tpPrime = pUint32; tBrilliant = record - pMin, // start for dgtcnt - pMid, // start for dgtcnt+1 - pMax, // end for dgtcnt+1 + Count_dgt : Uint64; MinIdx, MidIdx, MaxIdx : Uint32; end; var - BrilliantPos :array [0..8] of TBrilliant; - OddPowP : Uint32; +{$ALIGN 32} + BrilliantPos :array [0..10] of TBrilliant; - function BuildWheel(var primes: tPrimeDelta): longint; - //pre-sieve with small primes,returns the last used prime + function commatize(n:NativeUint):string; var - //wheelprimes = 2,3,5,7,11. ;wheelsize = product[i= 0..wpno-1]wheelprimes[i] > Uint64|i> 13 - wheelprimes: array[0..15] of byte; - wheelSize, wpno, pr, pw, i, k: longword; + l,i : NativeUint; begin - pr := 1; - primes[1] := 1; - WheelSize := 1; - wpno := 0; - repeat - Inc(pr); - pw := pr; - if pw > wheelsize then - Dec(pw, wheelsize); - if Primes[pw]<>0 then - begin - k := WheelSize + 1; - for i := 1 to pr - 1 do - begin - Inc(k, WheelSize); - if k < High(primes) then - move(primes[1], primes[k - WheelSize], WheelSize) - else - begin - move(primes[1], primes[k - WheelSize], High(primes) - WheelSize * i); - break; - end; - end; - Dec(k); - if k > High(primes) then - k := High(primes); - wheelPrimes[wpno] := pr; - primes[pr] := 0; - - i := sqr(pr); - while i <= k do - begin - primes[i] := 0; - Inc(i, pr); - end; - - Inc(wpno); - WheelSize := k; - end; - until WheelSize >= High(primes); - while wpno > 0 do - begin - Dec(wpno); - primes[wheelPrimes[wpno]] := 1; + str(n,result); + l := length(result); + if l < 4 then + exit; + i := l+ (l-1) DIV 3; + setlength(result,i); + While i <> l do + Begin + result[i]:= result[l]; + result[i-1]:= result[l-1]; + result[i-2]:= result[l-2]; + result[i-3]:= ','; + dec(i,4); + dec(l,3); end; - Result := pr; end; - procedure Sieve(var primes: tPrimeDelta); + procedure Sieve(var pr: tPrime;n:UInt32); + //get primes plus one beyond limit var - pPrime: pUint8; - sieveprime, delFact: longword; + pPr : pUInt32; + i,p : Int32; begin - sieveprime := BuildWheel(primes); - pPrime := @primes[0]; + If n> 60184 then + //Pierre Dusart proved in 2010 + setlength(pr,trunc(n/(ln(n)-1.1))) + else + setlength(pr,6542); + i := 0; + pPr := @pr[0]; repeat - repeat - Inc(sieveprime); - until pPrime[sieveprime]<>0; - delFact := High(primes) div sieveprime; - if delFact < sieveprime then - BREAK; - inc(delFact); - repeat - repeat - Dec(delFact); - until pPrime[delFact]<>0; - pPrime[sieveprime * delFact] := 0; - until delFact < sieveprime; - until False; - primes[1] := 0; + p := NextPrime; + pPr[i] := p; + i +=1; + until p > n; + setlength(pr,i); + writeln('Primes [',pPr[0],'..',commatize(pPr[i-2]),'] +',commatize(pPr[i-1])); end; - procedure GetPrimeDelta(var prD:tPrimeDelta;size: int32); - var - pPD : pUint8; - idx,LastP,p : Uint32; - Begin - setlength(prD, 0); - setlength(prD, size + 1); - Sieve(prD); - pPD := @prD[0]; - idx := 0; - LastP := 0; - p := 0; - repeat - if pPD[p] <> 0 then - begin - pPD[idx] := p-LastP; - LastP := p; - inc(idx); - end; - inc(p); - until p> Size; - Setlength(prD,idx); - end; - - function Cnt_First_DgtCnt(pPD:pUint8;lmt:UInt64;dgtCnt: Int32):nativeUint; - //counting products of prime factors smaller than limit + function InsRes(p : tpPrime;Val,MaxIdx,cnt: Int32):int32; var - pLo,pHi,iLo,iHi : UInt64; + i : Int32; begin - with BrilliantPos[dgtCnt] do + if cnt = maxIdx then begin - pLo := pMin; - iLO := MinIdx; - pHi := pMid; - iHi := MidIdx; + while (maxIdx >=0) AND (val < p[maxIdx]) do + Begin + p[maxIdx+1] := p[maxIdx]; + dec(maxIdx); + end; + p[maxIdx+1] := val; + EXIT(cnt); + end + else + Begin + i := MaxIDx; + if val > p[i] then + begin + p[i+1] := val; + end + else + begin + while (i >=0) AND (val < p[i]) do + Begin + p[i+1] := p[i]; + dec(i); + end; + p[i+1] := val; + end; end; - result := iHi-iLo+1; - repeat - iLo+=1; - pLO := pLo+pPD[iLo]; - if pLo = pHi then - begin - if sqr(pLo) < Lmt then - pLO := pLo+pPD[iLo+1]; - OddPowP := pLo; - EXIT(result+1); - end; - while (pHi >= pLo) AND (pHi*pLo > lmt) do - begin - pHi := pHi-pPD[iHi]; - iHi-=1; - end; - result += iHi-iLo+1; - until (pHi < pLo); - OddPowP := pLo; + result := MaxIdx+1; + if result > cnt then + result := cnt; end; - procedure GetLimitPos(pPD:pUint8;MaxPrIdx:NativeUint); + procedure Get_N_Brilliant(pPr:tpPrime;cnt:Int32); var - lmt, p,pmin,idx1,dgtCnt : nativeuint; - DeltaMax,DeltaMin,TotCnt: Uint64; - begin + p_p : array of Int32; + lmt,p1,p2,i1,i2,maxIdx : Int32; + Begin + setlength(p_p,cnt+2); + MaxIdx := 0; + p_p[MaxIdx] := maxint; + i1 := 1; + p1 := pPr[0]; lmt := 10; - p := 0; - idx1 := 0; - dgtCnt := 0; - TotCnt := 0; - p += pPD[idx1]; repeat - BrilliantPos[dgtCnt].pMin:= p; - BrilliantPos[dgtCnt].MinIdx := idx1; - write('10^',2*dgtCnt+1:2,':',p:10); - pMin := p; - while (pMin*p < lmt) and (idx1 < MaxPrIdx) do - begin - idx1 += 1; - p += pPD[idx1]; - end; - pMin := p-pPD[idx1]; - BrilliantPos[dgtCnt].pMid := pMin; - BrilliantPos[dgtCnt].MidIdx := idx1-1; - DeltaMin := Cnt_First_DgtCnt(pPD,lmt,dgtCnt); - writeln(DeltaMin:20,TotCnt+DeltaMin:20); + repeat + p2 := p1; + if MaxIdx = cnt then + if p1*p1 > p_p[MaxIdx] then + break; + i2 := i1; + repeat + MaxIdx := InsRes(@p_p[0],p1*p2,MaxIdx,cnt); + p2 := pPr[i2]; + i2+=1; + if MaxIdx = cnt then + if p1*p2 > p_p[MaxIdx] then + break; + until p2>lmt; + p1 := pPr[i1]; + i1 +=1; + until p1>lmt; lmt *=10; - while (p*p <= lmt) AND (idx1 < MaxPrIdx) do - begin - idx1 += 1; - p += pPD[idx1]; - end; - pMin := p-pPD[idx1]; - BrilliantPos[dgtCnt].pMax := pMin; - BrilliantPos[dgtCnt].MaxIdx := idx1-1; + until (MaxIdx = cnt)AND (p1*p1 > p_p[MaxIdx]); - //for both decimals just summation formula - deltaMax := idx1-BrilliantPos[dgtCnt].MinIdx; - deltaMax := (deltaMax*(deltaMax+1) DIV 2); - TotCnt += deltaMax; - write('10^',2*dgtCnt+2:2,':',OddPowP:10); - writeln(DeltaMax-DeltaMin:20,TotCnt:20); - dgtCnt += 1; - lmt*=10; - until (idx1 >= MaxPrIdx) or(lmt>sqr(MaxRoot)); - writeln(p:16); - end; + Writeln('The first ',cnt,' brilliant numbers '); + For i1 := 1 to cnt do + Begin + write(commatize(p_p[i1-1]):6); + if i1 MOD 10 = 0 then + write(#13#10); + end; + writeln; + end; + + function BinSearch(pPr:tpPrime;maxIdx,p:NativeUint):NativeInt; + // binary search for idx , so, that primes[idx-1] < p < primes[idx] + var + tmp : double; + i1,i2,m : nativeUInt; + begin + //assumption, where to find the right prime + tmp := ln(p)-1; + i1 := trunc(p/tmp); + i2 := trunc(p/(tmp-0.1)); + IF i2 > MaxIdx then + i2 := MaxIdx; + repeat + m := (i1+i2) shr 1; + if pPr[m]

MaxIdx then + i2 := MaxIdx; + while pPr[i2] < p do + inc(i2); + result := i2; + end; + + function Cnt_First_DgtCnt(pPr:tpPrime;lmt:UInt64;dgtCnt: Int32):nativeInt; + //counting products of prime factors below limit + //and memorize the smallest brilliant number above limit + var + pLo,tmp,res : UInt64; + iLo,iHi : Int64; + begin + with BrilliantPos[dgtCnt] do + begin + iLO := MinIdx; + iHi := MidIdx; + end; + result := iHi-iLo; + res := pPr[iLo]*pPr[iHi+1]; + repeat + iLo +=1; + pLo := pPr[iLo]; + while (iHi >= iLo) AND (pPr[iHi]*pLo > Lmt) do + iHi-=1; + tmp := pPr[iHi+1]*pLo; + if (tmp>lmt)AND (res>tmp) then + res := tmp; + result += iHi-iLo+1; + until (iHi < iLo); + BrilliantPos[dgtCnt].Count_dgt := res; + end; + + procedure GetLimitPos(pPr:tpPrime;MaxPrIdx:NativeUint); + var + lmt, p,idx1,dgtCnt : nativeuint; + DeltaMax,DeltaMin,First,TotCnt: Uint64; + begin + lmt := 10; + p := 0; + idx1 := 0; + dgtCnt := 0; + TotCnt := 0; + p := pPr[idx1]; + repeat + BrilliantPos[dgtCnt].MinIdx := idx1; + write(2*dgtCnt+1:3,':'); + First := p*p; + p := Lmt DIV p; + if p> 60000 then + idx1:= BinSearch(pPr,MaxPrIdx,p) + else + while (p>pPr[idx1]) and (idx1 < MaxPrIdx) do + idx1 += 1; + BrilliantPos[dgtCnt].MidIdx := idx1; + DeltaMin := Cnt_First_DgtCnt(pPr,lmt,dgtCnt); + writeln(commatize(TotCnt+DeltaMin):23,commatize(First):24); + lmt *=10; + repeat + idx1 +=1; + until (sqr(pPr[idx1]) >= lmt)OR (idx1>=MaxPrIdx); + p := pPr[idx1]; + BrilliantPos[dgtCnt].MaxIdx := idx1-1; + //for both decimals just summation formula + deltaMax := idx1-BrilliantPos[dgtCnt].MinIdx; + deltaMax := (deltaMax*(deltaMax+1) DIV 2); + TotCnt += deltaMax; + First := BrilliantPos[dgtCnt].Count_dgt; + write(2*dgtCnt+2:3,':'); + writeln(commatize(TotCnt):23,commatize(First):24); + dgtCnt += 1; + lmt*=10; + until (idx1 >= MaxPrIdx) or(lmt>sqr(MaxRoot)); + end; var - primeDelta :TprimeDelta; + primes :tPrime; + pPr : tpPrime; T : INt64; - pPD : pUint8; begin T := GetTickCount64; - GetPrimeDelta(primeDelta,MaxRoot); + Sieve(primes,MaxRoot); Writeln('Sieving in ',GetTickCount64-T,' ms'); T := GetTickCount64; - pPD := @primeDelta[0]; -// 10^ 1: 2 3 3 - writeln('Limit first prime deltaCount Total Count'); - GetLimitPos(pPD,High(primeDelta)); + + pPr := @primes[0]; + Get_N_Brilliant(pPr,100); + writeln('Digits total count first brilliant'); + GetLimitPos(pPr,High(primes)); + writeln(' ',Commatize(sqr(primes[High(primes)])):26); Writeln('Counting in ',GetTickCount64-T,' ms'); {$IFDEF WINDOWS} readln; diff --git a/Task/Brownian-tree/FutureBasic/brownian-tree.basic b/Task/Brownian-tree/FutureBasic/brownian-tree.basic new file mode 100644 index 0000000000..a394c348c4 --- /dev/null +++ b/Task/Brownian-tree/FutureBasic/brownian-tree.basic @@ -0,0 +1,153 @@ +// Brownian tree +//https://rosettacode.org/wiki/Brownian_tree + +/* +A Brownian tree is built with these steps: +first, a "seed" is placed somewhere on the screen. +Then, a particle is placed in a random position of the screen, +and moved randomly until it bumps against the seed. +The particle is left there, and another particle is placed in a random position +and moved until it bumps against the seed or any previous particle, and so on. + +*/ + + +begin globals + + _w = 400 // window size + short w = _w + bool pixelUsed(_w ,_w ) + short x, y , Oldx, Oldy + cgRect TheRect + short Edge + long SpeckleCount + short MainColor,SpeckleColor + bool GreenGreen,WhiteWhite,WhiteIndigo,WhiteMagenta,GreenIndigo,CyanBlue + bool SeedPlanted + long count + + + // Color Options + GreenGreen = 0 + GreenIndigo = 0 + WhiteIndigo = 1 + WhiteWhite = 0 + WhiteMagenta = 0 + CyanBlue = 0 + + if GreenGreen then MainColor = _ZGreen : SpeckleColor = _ZGreen + if WhiteWhite then MainColor = _ZWhite : SpeckleColor = _ZWhite + if WhiteIndigo then MainColor = _ZWhite : SpeckleColor = _zSystemIndigo + if WhiteMagenta then MainColor = _ZWhite : SpeckleColor = _zMagenta + if GreenIndigo then MainColor = _ZGreen : SpeckleColor = _zSystemIndigo + if CyanBlue then MainColor = _zCyan : SpeckleColor = _zBlue + +end globals + +_Window = 1 +window _Window, @"", ( 0, 0, _w, _w ), NSWindowStyleMaskTitled + NSWindowStyleMaskMiniaturizable + +windowcenter(_Window) +WindowSetBackgroundColor(_Window,fn ColorBlack) + +local fn ClearPixelArray + cls + + short row,col + for row = 1 to 400 + for col = 1 to 400 + pixelUsed(row,col) = NO + next + next + + + SpeckleCount = 0 + + Edge = _w + /// place seed in the middle + pen -1 + oval fill (w/2,w/2,5,5), MainColor + x = w/2 + y = w/2 + pixelUsed(x,y) = YES + + Oldx = x + Oldy = y + count = 0 + SeedPlanted = _true + +end fn + + +local fn DrawPixels + + // Set New Random particle location + if SeedPlanted = _false + do + x = rnd(Edge) + y = rnd(Edge) + until pixelUsed(x,y) = NO + end if + + SeedPlanted = _false + short xBack, yBack + xBack = x + yBack = x + + + // Find a location for the new particle + do + + Oldx = x + Oldy = y + + // set x and y within plus or minus 15 pixels of x or y + x += RND(3) - 2 + y += RND(3) - 2 + + // prevent results that are not within 15 pixels of Oldx and Oldy + if x <= 0 then x = xBack : y = yBack + if y <= 0 then y = xBack : y = yBack + if x > Edge then x = xBack : y = yBack + if y > Edge then y = xBack : y = yBack + + until pixelUsed(x,y) = YES + + + // Draw the new particle but protect the margin on the edge + + if Oldx > 15 && Oldx < Edge - 15 && Oldy > 15 && Oldy < Edge - 15 + SpeckleCount ++ + + pen -1 + if SpeckleCount < 200 + oval fill (Oldx,Oldy,1,1), MainColor + else + oval fill (Oldx,Oldy,2,2), SpeckleColor + SpeckleCount = 0 + end if + + pixelUsed(Oldx,Oldy) = YES + xBack = x + yBack = y + count ++ + end if + + + if count > 10000 + CFStringRef ReturnedKey + ReturnedKey = Inkey %(90,1),@"Any key for another one. Q to quit" + if fn StringContainsString(ReturnedKey, @"q") then end + if fn StringContainsString(ReturnedKey, @"Q") then end + fn ClearPixelArray + end if + + +end fn + + +fn ClearPixelArray + +fn AppSetTimer( .000001, @Fn DrawPixels, _true ) + +handleevents diff --git a/Task/Bulls-and-cows/J/bulls-and-cows-2.j b/Task/Bulls-and-cows/J/bulls-and-cows-2.j index 0fb16de9c6..9795e742c7 100644 --- a/Task/Bulls-and-cows/J/bulls-and-cows-2.j +++ b/Task/Bulls-and-cows/J/bulls-and-cows-2.j @@ -1,4 +1,4 @@ -U =. {{]F.(u[_2:Z:v)}} NB. apply u until v is true +U =. {{u^:(-.@:v)^:_.}} NB. apply u until v is true input =. 1!:1@1@echo@'Guess: ' output =. [ ('Bulls: ',:'Cows: ')echo@,.":@,. isdigits=. *./@e.&'0123456789' diff --git a/Task/Burrows-Wheeler-transform/ALGOL-68/burrows-wheeler-transform.alg b/Task/Burrows-Wheeler-transform/ALGOL-68/burrows-wheeler-transform.alg new file mode 100644 index 0000000000..a401340fef --- /dev/null +++ b/Task/Burrows-Wheeler-transform/ALGOL-68/burrows-wheeler-transform.alg @@ -0,0 +1,63 @@ +BEGIN # Burrows-Wheeler transform - translated from the EasyLang sample # + PR read "sort.incl.a68" PR # include sort utilities # + CHAR stx = REPR 2, etx = REPR 3; + OP BWT = ( STRING s )STRING: + BEGIN + [ LWB s : UPB s + 2 ]STRING tbl; + STRING ss = stx + s + etx; + FOR i FROM LWB ss TO UPB ss DO + STRING a = ss[ LWB ss : i ]; + STRING b = IF i >= UPB ss THEN "" ELSE ss[ i + 1 : ] FI; + tbl[ i ] := b + a + OD; + QUICKSORT tbl; + STRING r := ""; + FOR s pos FROM LWB tbl TO UPB tbl DO + r +:= tbl[ s pos ][ UPB tbl[ s pos ] ] + OD; + r + END # BWT # ; + OP IBWT = ( STRING r )STRING: + BEGIN + [ LWB r : UPB r ]STRING tbl; + FOR j FROM LWB r TO UPB r DO tbl[ j ] := "" OD; + FROM LWB r TO UPB r DO + FOR k FROM LWB r TO UPB r DO + r[ k ] +=: tbl[ k ] + OD; + QUICKSORT tbl + OD; + STRING result := ""; + FOR r pos FROM LWB tbl TO UPB tbl WHILE result = "" DO + STRING row = tbl[ r pos ]; + IF row[ UPB row ] = etx THEN result := row[ LWB row + 1 : UPB row - 1 ] FI + OD; + result + END # IBWT # ; + + BEGIN + OP XTX = ( STRING s )STRING: # make stx and etx visible # + BEGIN + STRING result := ""; + FOR s pos FROM LWB s TO UPB s DO + CHAR c = s[ s pos ]; + result +:= IF c = stx THEN "" + ELIF c = etx THEN "" + ELSE c + FI + OD; + result + END # XTX # ; + []STRING tests = ( "banana", "appellee", "dogwood" + , "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" + , "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" + ); + FOR t pos FROM LWB tests TO UPB tests DO + STRING s = tests[ t pos ]; + print( ( s, newline ) ); + STRING h = BWT s; + print( ( " -> ", XTX h, newline ) ); + print( ( IBWT h, newline, newline ) ) + OD + END +END diff --git a/Task/Burrows-Wheeler-transform/Fortran/burrows-wheeler-transform.f b/Task/Burrows-Wheeler-transform/Fortran/burrows-wheeler-transform.f new file mode 100644 index 0000000000..8fcb501e51 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Fortran/burrows-wheeler-transform.f @@ -0,0 +1,163 @@ +program BurrowsWheeler + implicit none + + ! Main program + call Test("BANANA") + call Test("CANAAN") + call Test("CANCAN") + call Test("appellee") + call Test("dogwood") + call Test("TO BE OR NOT TO BE OR WANT TO BE OR NOT?") + call Test("SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES") + call Test("Four score and 7 years ago, our forefathers set forth on this continent to establish a new nation "//& + "conceived in liberty and dedicated to he proposition that all men were created equal") + contains + ! Function to compare rotations + integer function CompareRotations(input, n, a, b) + character(len=*), intent(in) :: input + integer, intent(in) :: n, a, b + integer :: p, q, nrNotTested + integer :: i ,k + + CompareRotations = 0 + p = a + q = b + nrNotTested = n + do + p = p + 1 + if (p == n) p = 0 + q = q + 1 + if (q == n) q = 0 + i = p + 1 + k = q + 1 + if (input(i:i) == input(k:k)) then + nrNotTested = nrNotTested - 1 + else if (input(i:i) > input(k:k)) then + CompareRotations = 1 + exit + else + CompareRotations = -1 + exit + end if + if (nrNotTested == 0) exit + end do + end function CompareRotations + + ! Subroutine to encode the input string + subroutine Encode(input, encoded, index) + character(len=*), intent(in) :: input + character(len=*), intent(out) :: encoded + integer, intent(out) :: index + integer :: n, i, j, k, incr, v + integer, allocatable :: perm(:) + + n = len(input) + allocate(perm(0:n-1)) + do j = 0, n - 1 + perm(j) = j + end do + + ! Shell sort + incr = 1 + do + incr = 3 * incr + 1 + if (incr >= n) exit + end do + do + incr = incr / 3 + do i = incr, n - 1 + v = perm(i) + j = i + do while (j >= incr) + if(CompareRotations(input, n, perm(j - incr), v) /= 1)exit + perm(j) = perm(j - incr) + j = j - incr + end do + perm(j) = v + end do + if (incr == 1) exit + end do + + ! Create the output + do j = 0, n - 1 + k = perm(j) + encoded(j + 1:j + 1) = input(k + 1:k + 1) + if (k == n - 1) index = j + end do + + deallocate(perm) + end subroutine Encode + + ! Function to decode the encoded string + function Decode(encoded, index) result(decoded) + character(len=*), intent(in) :: encoded + integer, intent(in) :: index + character(len=:), allocatable :: decoded + integer :: charInfo(0:255) + integer, allocatable :: perm(:) + integer :: n, j, k, total, prev + character :: c + + n = len(encoded) + if (n == 0) then + decoded = "" + return + end if + + charInfo = 0 + do j = 0, n - 1 + c = encoded(j + 1:j + 1) + charInfo(ichar(c)) = charInfo(ichar(c)) + 1 + end do + + total = 0 + prev = 0 + do k = 0, 255 + total = total + prev + prev = charInfo(k) + charInfo(k) = total + end do + + allocate(perm(0:n-1)) + do j = 0, n - 1 + c = encoded(j + 1:j + 1) + k = charInfo(ichar(c)) + perm(k) = j + charInfo(ichar(c)) = charInfo(ichar(c)) + 1 + end do + + allocate(character(len=n) :: decoded) + k = 0 + j = index + do + j = perm(j) + decoded(k + 1:k + 1) = encoded(j + 1:j + 1) + k = k + 1 + if (j == index) exit + end do + + if (k < n) then + do j = k, n - 1 + decoded(j + 1:j + 1) = decoded(j - k + 1:j - k + 1) + end do + end if + end function Decode + + ! Subroutine to test the encoding and decoding + subroutine Test(s) + character(len=*), intent(in) :: s + character(len=:), allocatable :: encoded, decoded + integer :: index + + print *, "" + print *, " ", s + allocate(character(len=len(s)) :: encoded) + call Encode(s, encoded, index) + print *, "---> ", encoded + print *, " index = ", index + decoded = Decode(encoded, index) + print *, "---> ", decoded + deallocate(encoded) + end subroutine Test + +end program BurrowsWheeler diff --git a/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 b/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 index 52eb55078b..c6073ef05e 100644 --- a/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 +++ b/Task/CRC-32/M2000-Interpreter/crc-32-1.m2000 @@ -1,25 +1,30 @@ -Module CheckIt { - Function PrepareTable { - Dim Base 0, table(256) - For i = 0 To 255 { - k = i - For j = 0 To 7 { - If binary.and(k,1)=1 Then { - k =binary.Xor(binary.shift(k, -1) , 0xEDB88320) - } Else k=binary.shift(k, -1) - } - table(i) = k - } - =table() - } - crctable=PrepareTable() - crc32= lambda crctable (buf$) -> { - crc =0xFFFFFFFF - For i = 0 To Len(buf$) -1 - crc = binary.xor(binary.shift(crc, -8), array(crctable, binary.xor(binary.and(crc, 0xff), asc(mid$(buf$, i+1, 1))))) - Next i - =0xFFFFFFFF-crc - } - Print crc32("The quick brown fox jumps over the lazy dog")=0x414fa339 +odule CheckIt { + crc32 = lambda ->{ + Function PrepareTable { + buffer t as long * 256 + For i = 0 To 255 + k = i + For j = 0 To 7 + If binary.and(k,1)=1 Then + k =binary.Xor(binary.shift(k, -1) , 0xEDB88320) + Else + k=binary.shift(k, -1) + End If + Next + Return t, i:=k + Next + =t + } + = lambda crctable=PrepareTable() (c, buf$) -> { + crc=0xFFFFFFFF-c + For i = 1 To Len(buf$) + crc = binary.xor(binary.shift(crc, -8), eval(crctable, binary.xor(binary.and(crc, 0xff), asc(mid$(buf$, i, 1))))) + Next i + =0xFFFFFFFF-crc + } + }() ' execute now + Print crc32(0, "The quick brown fox jumps over the lazy dog")=0x414fa339& + Print crc32(crc32(0, "The quick brown fox jumps"), " over the lazy dog")=0x414fa339& + Print crc32(crc32(crc32(0, "The qu"), "ick brown"), " fox jumps over the lazy dog")=0x414fa339& } CheckIt diff --git a/Task/CRC-32/Zig/crc-32.zig b/Task/CRC-32/Zig/crc-32.zig index 10a6bf31c1..629dbde918 100644 --- a/Task/CRC-32/Zig/crc-32.zig +++ b/Task/CRC-32/Zig/crc-32.zig @@ -2,6 +2,6 @@ const std = @import("std"); const Crc32Ieee = std.hash.Crc32; pub fn main() !void { - var res: u32 = Crc32Ieee.hash("The quick brown fox jumps over the lazy dog"); + const res: u32 = Crc32Ieee.hash("The quick brown fox jumps over the lazy dog"); std.debug.print("{x}\n", .{res}); } diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation-1.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-1.lua new file mode 100644 index 0000000000..38f23efa69 --- /dev/null +++ b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-1.lua @@ -0,0 +1,13 @@ +-- Lua has no built in methods to handle csv files. +-- it does have string.gmatch, which we use to global.match whatever isn't a comma + +print(io.read"l" .. ",SUM") +for line in io.lines() do + local fields, sum = {}, 0 + for field in line:gmatch"[^,]+" do + table.insert(fields, field) + sum = sum + field + end + table.insert(fields, sum) + print(table.concat(fields,",")) +end diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation-2.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-2.lua new file mode 100644 index 0000000000..0469930ba1 --- /dev/null +++ b/Task/CSV-data-manipulation/Lua/csv-data-manipulation-2.lua @@ -0,0 +1,26 @@ +local csv={} + +-- read csv file, save records and fields into table +for line in io.lines('file.csv') do + local fields = {} + for field in line:gmatch"[^,]+" do + table.insert(fields, tonumber(field) or field) + end + table.insert(csv, fields) +end + +-- change csv values +table.insert(csv[1], 'SUM') +for i=2,#csv do + local sum=0 + for _, val in ipairs(csv[i]) do + sum = sum + val + end + table.insert(csv[i], sum) +end + +-- Save +local fileHandler = io.open('file.csv', 'w') +for NR, fields in ipairs(csv) do + fileHandler:write(table.concat(fields,","), "\n") +end diff --git a/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua b/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua deleted file mode 100644 index 26ddaeabc9..0000000000 --- a/Task/CSV-data-manipulation/Lua/csv-data-manipulation.lua +++ /dev/null @@ -1,31 +0,0 @@ -local csv={} -for line in io.lines('file.csv') do - table.insert(csv, {}) - local i=1 - for j=1,#line do - if line:sub(j,j) == ',' then - table.insert(csv[#csv], line:sub(i,j-1)) - i=j+1 - end - end - table.insert(csv[#csv], line:sub(i,j)) -end - -table.insert(csv[1], 'SUM') -for i=2,#csv do - local sum=0 - for j=1,#csv[i] do - sum=sum + tonumber(csv[i][j]) - end - if sum>0 then - table.insert(csv[i], sum) - end -end - -local newFileData = '' -for i=1,#csv do - newFileData=newFileData .. table.concat(csv[i], ',') .. '\n' -end - -local file=io.open('file.csv', 'w') -file:write(newFileData) diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-4.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-4.js new file mode 100644 index 0000000000..1124a5e5d1 --- /dev/null +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-4.js @@ -0,0 +1,40 @@ +function csvToHtml(input) { + if (!input || typeof input !== 'string') { + throw new Error('Invalid input!'); + } + + function _createTableCell(cellContents, index) { + if (!cellContents || typeof cellContents !== 'string') { + throw new Error('Invalid data!'); + } + + const tableCell = document.createElement( + (index === 0) ? 'th' : 'td' + ); + + tableCell.textContent = cellContents.trim(); + return tableCell; + } + + const rows = input.split('\n'); + const table = document.createElement('table'); + + rows.forEach((row, index) => { + const tableRow = document.createElement('tr'); + const tableCells = row.split(','); + + tableCells.forEach((cell) => { + try { + tableRow.appendChild( + _createTableCell(cell, index), + ); + } catch (error) { + console.error(error); + } + }); + + table.appendChild(tableRow); + }); + + return table; +} diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-5.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-5.js new file mode 100644 index 0000000000..986924331b --- /dev/null +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-5.js @@ -0,0 +1,14 @@ +const inputData = `Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!`; + +try { + document.body.append( + csvToHtml(inputData), + ); +} catch (error) { + console.error(error) +} diff --git a/Task/CUSIP/Langur/cusip-1.langur b/Task/CUSIP/Langur/cusip-1.langur index 544bb91265..df07bf5a9d 100644 --- a/Task/CUSIP/Langur/cusip-1.langur +++ b/Task/CUSIP/Langur/cusip-1.langur @@ -6,7 +6,7 @@ val isCusip = fn(s) { val basechars = '0'..'9' ~ 'A'..'Z' ~ "*@#" val sum = for[=0] i of 8 { - var v = index(s2s(s, i), basechars) + var v = index(basechars, by=s2s(s, of=i)) if not v: return false v = v[1]-1 if i div 2: v *= 2 diff --git a/Task/Caesar-cipher/Langur/caesar-cipher.langur b/Task/Caesar-cipher/Langur/caesar-cipher.langur index 3161281621..7b3a36cc20 100644 --- a/Task/Caesar-cipher/Langur/caesar-cipher.langur +++ b/Task/Caesar-cipher/Langur/caesar-cipher.langur @@ -1,5 +1,5 @@ val rot = fn(s, key) { - cp2s map(fn(c) { rotate(rotate(c, key, 'a'..'z'), key, 'A'..'Z') }, s2cp(s)) + cp2s map(s2cp(s), by=fn(c) { rotate(rotate(c, distance=key, range='a'..'z'), distance=key, range='A'..'Z') }) } val s = "A quick brown fox jumped over something, you know." diff --git a/Task/Calculating-the-value-of-e/ALGOL-W/calculating-the-value-of-e.alg b/Task/Calculating-the-value-of-e/ALGOL-W/calculating-the-value-of-e.alg new file mode 100644 index 0000000000..2e559bfec8 --- /dev/null +++ b/Task/Calculating-the-value-of-e/ALGOL-W/calculating-the-value-of-e.alg @@ -0,0 +1,16 @@ +begin % calculate an approximation to e % + long real epsilon; + long real e0, e, f; + integer n; + epsilon := 1'-14; f := 1; e := n := 2; + while begin + e0 := e; + f := f * n; + n := n + 1; + e := e + 1.0 / f; + abs ( e - e0 ) >= epsilon + end do begin end; + write( I_w := 1, s_w := 0, r_format := "A", r_w := 16, r_d := 14 % <-- sets output formatting % + , "e = ", e, " after ", n - 1, " iterations" + ) +end. diff --git a/Task/Calculating-the-value-of-e/EDSAC-order-code/calculating-the-value-of-e-1.edsac b/Task/Calculating-the-value-of-e/EDSAC-order-code/calculating-the-value-of-e-1.edsac index 84c31ea9eb..d51b3a4a5e 100644 --- a/Task/Calculating-the-value-of-e/EDSAC-order-code/calculating-the-value-of-e-1.edsac +++ b/Task/Calculating-the-value-of-e/EDSAC-order-code/calculating-the-value-of-e-1.edsac @@ -1,5 +1,6 @@ [Calculate e] [EDSAC program, Initial Orders 2] + [2024-12-25 Bug fix: ensure sandwich bit in 35-bit constant is 0] [Library subroutine M3. Prints header and is then overwritten] [Here, last character sets teleprinter to figures] @@ -29,6 +30,8 @@ GK [set @ (theta) for relative addresses] [0] PF PF [build sum 4*(1/3! + 1/4! + 1/5! + ...)] [2] PF PF [term in sum] + T4#ZPF [load time: clear whole of #4, including sandwich bit] + T4Z [load time: resume normal loading] [4] PD PF [2^-34, stop when term < this] [6] PF [divisor] [7] IF [1/2] diff --git a/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-1.hs b/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-1.hs index e7ff6b2acd..d43cad0693 100644 --- a/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-1.hs +++ b/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-1.hs @@ -1,8 +1,7 @@ ------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ---- eApprox :: Int -> Double -eApprox n = - (sum . take n) $ (1 /) <$> scanl (*) 1 [1 ..] +eApprox n = sum . map (1 /) $ scanl (*) 1 [1..n] --------------------------- TEST ------------------------- main :: IO () diff --git a/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-3.hs b/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-3.hs index 3b9b856f95..a13155388a 100644 --- a/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-3.hs +++ b/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-3.hs @@ -1,16 +1,4 @@ -{-# LANGUAGE TupleSections #-} - -------------------- APPROXIMATIONS TO E ------------------ - -approximatEs :: [Double] -approximatEs = - fst - <$> iterate - ( \(e, (i, n)) -> - (,) . (e +) . (1 /) <*> (succ i,) $ i * n - ) - (1, (1, 1)) - ---------------------------- TEST ------------------------- -main :: IO () -main = print $ approximatEs !! 17 +eApprox n = snd $ foldr f (1, 1) [n, pred n .. 1] + where + f x (fl, e) = + let y = fl * x in (y, e + 1 / y) diff --git a/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-4.hs b/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-4.hs new file mode 100644 index 0000000000..3b9b856f95 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Haskell/calculating-the-value-of-e-4.hs @@ -0,0 +1,16 @@ +{-# LANGUAGE TupleSections #-} + +------------------- APPROXIMATIONS TO E ------------------ + +approximatEs :: [Double] +approximatEs = + fst + <$> iterate + ( \(e, (i, n)) -> + (,) . (e +) . (1 /) <*> (succ i,) $ i * n + ) + (1, (1, 1)) + +--------------------------- TEST ------------------------- +main :: IO () +main = print $ approximatEs !! 17 diff --git a/Task/Calendar/EasyLang/calendar.easy b/Task/Calendar/EasyLang/calendar.easy index 72c2661b82..b785fed23d 100644 --- a/Task/Calendar/EasyLang/calendar.easy +++ b/Task/Calendar/EasyLang/calendar.easy @@ -1,4 +1,5 @@ year = 1969 +# year = number substr timestr systime 1 4 # wkdays$ = "Su Mo Tu We Th Fr Sa" pagewide = 80 diff --git a/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-1.c b/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-1.c deleted file mode 100644 index c37f86a156..0000000000 --- a/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-1.c +++ /dev/null @@ -1,24 +0,0 @@ -#include -#include - -int main(int argc,char** argv) { - - int arg1 = atoi(argv[1]), arg2 = atoi(argv[2]), sum, diff, product, quotient, remainder ; - - __asm__ ( "addl %%ebx, %%eax;" : "=a" (sum) : "a" (arg1) , "b" (arg2) ); - __asm__ ( "subl %%ebx, %%eax;" : "=a" (diff) : "a" (arg1) , "b" (arg2) ); - __asm__ ( "imull %%ebx, %%eax;" : "=a" (product) : "a" (arg1) , "b" (arg2) ); - - __asm__ ( "movl $0x0, %%edx;" - "movl %2, %%eax;" - "movl %3, %%ebx;" - "idivl %%ebx;" : "=a" (quotient), "=d" (remainder) : "g" (arg1), "g" (arg2) ); - - printf( "%d + %d = %d\n", arg1, arg2, sum ); - printf( "%d - %d = %d\n", arg1, arg2, diff ); - printf( "%d * %d = %d\n", arg1, arg2, product ); - printf( "%d / %d = %d\n", arg1, arg2, quotient ); - printf( "%d %% %d = %d\n", arg1, arg2, remainder ); - - return 0 ; -} diff --git a/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-2.c b/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-2.c deleted file mode 100644 index f6729d9aa6..0000000000 --- a/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-2.c +++ /dev/null @@ -1,16 +0,0 @@ -#include - -int main() -{ - Py_Initialize(); - PyRun_SimpleString("a = [3*x for x in range(1,11)]"); - - PyRun_SimpleString("print 'First 10 multiples of 3 : ' + str(a)"); - - PyRun_SimpleString("print 'Last 5 multiples of 3 : ' + str(a[5:])"); - - PyRun_SimpleString("print 'First 10 multiples of 3 in reverse order : ' + str(a[::-1])"); - - Py_Finalize(); - return 0; -} diff --git a/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function.c b/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function.c new file mode 100644 index 0000000000..4e0643695b --- /dev/null +++ b/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function.c @@ -0,0 +1,35 @@ +#include +#include +#include + +#include +#include + +const char * const lua_code = "print('tau = ' .. 8*math.atan(1))"; + +int +main(void) +{ + lua_State* L; + + /* initialize lua */ + L = luaL_newstate(); + luaL_openlibs(L); /* allows use of lua's standard libraries e.g. math */ + + /* load and run the code */ + if (luaL_loadstring(L, lua_code) != LUA_OK) { + fprintf(stderr, "Error loading lua code\n"); + return EXIT_FAILURE; + } + + if (lua_pcall(L, 0, 0, 0) != LUA_OK) { + fprintf(stderr, "Error running lua code\n"); + return EXIT_FAILURE; + } + + /* tidy up */ + lua_pop(L, lua_gettop(L)); + lua_close(L); + + return 0; +} diff --git a/Task/Call-a-foreign-language-function/M2000-Interpreter/call-a-foreign-language-function-5.m2000 b/Task/Call-a-foreign-language-function/M2000-Interpreter/call-a-foreign-language-function-5.m2000 index 7a98009d84..a8f20f1814 100644 --- a/Task/Call-a-foreign-language-function/M2000-Interpreter/call-a-foreign-language-function-5.m2000 +++ b/Task/Call-a-foreign-language-function/M2000-Interpreter/call-a-foreign-language-function-5.m2000 @@ -1,14 +1,14 @@ Module checkit { Static DisplayOnce=0 - N=100000 + N=1000000 Read ? N Form 60 Pen 14 Background { Cls 5} Cls 5 - \\ use f1 do unload lib - because only New statemend unload it + ' use f1 do unload lib - because only New statemend unload it FKEY 1,"save ctst1:new:load ctst1" - \\ We use a function as string container, because c code can easy color decorated in M2000. + ' We use a function as string container, because c code can easy color decorated in M2000. Function ccode { long primes(long a[], long b) { @@ -52,53 +52,54 @@ Module checkit { return 0; } } - \\ extract code. &functionname() is a string with the code inside "{ }" - \\ a reference to function actual is code of function in m2000 - \\ using Document object we have an easy way to drop paragraphs + ' extract code. &functionname() is a string with the code inside "{ }" + ' a reference to function actual is code of function in m2000 + ' using Document object we have an easy way to drop paragraphs document code$=Mid$(&ccode(), 2, len(&ccode())-2) - \\ remove 1st line two times \\ one line for an edit information from interpreter - \\ paragraph$(code$, 1) export paragraph 1st,using third parameter -1 means delete after export. + ' remove 1st line two times ' one line for an edit information from interpreter + ' paragraph$(code$, 1) export paragraph 1st,using third parameter -1 means delete after export. drop$=paragraph$(code$,1,-1)+paragraph$(code$,1,-1) If DisplayOnce Else { + If exist(temporary$+"MyName.dll") then dos "del "+temporary$+"MyName.*", 200; Report 2, "c code for primes" - Report code$ \\ report stop after 3/4 of screen lines use. Press spacebar or mouse button to continue + Report code$ ' report stop after 3/4 of screen lines use. Press spacebar or mouse button to continue DisplayOnce++ } - \\ dos "del c:\MyName.*", 200; - If not exist("c:\MyName.dll") then { + + If not exist(temporary$+"MyName.dll") then { Report 2, "Now we have to make a dll" - Rem : Load Make \\ we can use a Make.gsb in current folder - this is the user folder for now + Rem : Load Make ' we can use a Make.gsb in current folder - this is the user folder for now Module MAKE ( fname$, code$, timeout ) { if timeout<1000 then timeout=1000 If left$(fname$,2)="My" Else Error "Not proper name - use 'My' as first two letters" Print "Delete old files" - try { remove "c:\MyName" } - Dos "del c:\"+fname$+".*", timeout; + try { remove temporary$+"MyName" } + Dos "del "+temporary$+fname$+".*", timeout; Print "Save c file" - Open "c:\"+fname$+".c" for output as F \\ use of non unicode output + Open temporary$+fname$+".c" for output as F ' use of non unicode output Print #F, code$ Close #F - \\ use these two lines for opening dos console and return to M2000 command line - rem : Dos "cd c:\ && gcc -c -DBUILD_DLL "+fname$+".c" + ' use these two lines for opening dos console and return to M2000 command line + rem : Dos "cd " +temporary$+" && gcc -c -DBUILD_DLL "+fname$+".c" rem : Error "Check for errors" - \\ by default we give a time to process dos command and then continue + ' by default we give a time to process dos command and then continue Print "make object file" - dos "cd c:\ && gcc -c -DBUILD_DLL "+fname$+".c" , timeout; - if exist("c:\"+fname$+".o") then { + dos "cd " +temporary$+" && gcc -c -DBUILD_DLL "+fname$+".c" , timeout; + if exist(temporary$+fname$+".o") then { Print "make dll" - dos "cd c:\ && gcc -shared -o "+fname$+".dll "+fname$+".o -Wl,--out-implib,libmessage.a", timeout; + dos "cd " +temporary$+" && gcc -shared -o "+fname$+".dll "+fname$+".o -Wl,--out-implib,libmessage.a", timeout; } else Error "No object file - Error" - if not exist("c:\"+fname$+".dll") then Error "No dll - Error" + if not exist(temporary$+fname$+".dll") then Error "No dll - Error" } Make "MyName", code$, 1000 } - Declare primes lib c "c:\MyName.primes" {long c, long d} \\ c after lib mean CDecl call - \\ So now we can check error - \\ make a Buffer (add two more longs for any purpose) - Buffer Clear A as Long*(N+2) \\ so A(0) is base address, of an array of 100002 long (unsign for M2000). - \\ profiler enable a timecount + Declare primes lib c temporary$+"MyName.primes" {long c, long d} ' c after lib mean CDecl call + ' So now we can check error + ' make a Buffer (add two more longs for any purpose) + Buffer Clear A as Long*(N+2) ' so A(0) is base address, of an array of 100002 long (unsign for M2000). + ' profiler enable a timecount profiler Call primes(A(0), N) m=timecount @@ -118,7 +119,8 @@ Module checkit { Print } Print format$("Compute {0} primes in range 1 to {1}, in msec:{2:3}", total, N, m) - \\ unload dll, we have to use exactly the same name, as we use it in declare except for last chars ".dll" - remove "c:\MyName" + ' unload dll, we have to use exactly the same name, as we use it in declare except for last chars ".dll" + remove temporary$+"MyName" } +' use clear statement to clear static variables before run this, to make new dll checkit diff --git a/Task/Call-a-function/Langur/call-a-function-6.langur b/Task/Call-a-function/Langur/call-a-function-6.langur index 1efc364d84..846df84db9 100644 --- a/Task/Call-a-function/Langur/call-a-function-6.langur +++ b/Task/Call-a-function/Langur/call-a-function-6.langur @@ -1 +1 @@ -mapX(amb, wordsets...) +testfn(a, b, wordsets...) diff --git a/Task/Call-an-object-method/BQN/call-an-object-method.bqn b/Task/Call-an-object-method/BQN/call-an-object-method.bqn new file mode 100644 index 0000000000..eb5f410f28 --- /dev/null +++ b/Task/Call-an-object-method/BQN/call-an-object-method.bqn @@ -0,0 +1,7 @@ +foo ← { + Spam ⇐ {𝕊: "Wonderful Spam!!!"} + Eggs ⇐ {𝕨+𝕩} +} + +•Show 1 foo.Eggs 2 + foo.Spam@ diff --git a/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy b/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy index 64d7aae038..7c1c9054e8 100644 --- a/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy +++ b/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy @@ -1,23 +1,15 @@ func$ can_cidr s$ . - n[] = number strsplit s$ "./" - if len n[] <> 5 - return "" - . + n[] = number strtok s$ "./" + if len n[] <> 5 : return "" for i to 4 - if n[i] < 0 or n[i] > 255 - return "" - . + if n[i] < 0 or n[i] > 255 : return "" ad = ad * 256 + n[i] . - if n[5] > 31 or n[5] < 1 - return "" - . + if n[5] > 31 or n[5] < 1 : return "" mask = bitnot (bitshift 1 (32 - n[5]) - 1) ad = bitand ad mask for i to 4 - if r$ <> "" - r$ = "." & r$ - . + if r$ <> "" : r$ = "." & r$ r$ = ad mod 256 & r$ ad = ad div 256 . diff --git a/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic b/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic index 97b62bc879..bd4af5e919 100644 --- a/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic +++ b/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic @@ -1,54 +1,99 @@ -#lang "qb" +Const MAX_OCTET = 255 +Const MIN_NETWORK = 1 +Const MAX_NETWORK = 32 +Const OCTET_BITS = 8 -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 +Type IPAddress + octets(3) As Integer +End Type + +Function isDigit(Byval ch As String) As Boolean + Return (Asc(ch) >= Asc("0")) And (Asc(ch) <= Asc("9")) +End Function + +Function ParseIPAddress(cidr As String, Byref networkWidth As Integer) As IPAddress + Dim As IPAddress ip + Dim As Integer slashPos = Instr(cidr, "/") + Dim As String ipPart = Left(cidr, slashPos - 1) + + networkWidth = Val(Mid(cidr, slashPos + 1)) + + Dim As Integer i, currentOctet = 0, octetValue = 0 + For i = 1 To Len(ipPart) + If Mid(ipPart, i, 1) = "." Then + ip.octets(currentOctet) = octetValue + currentOctet += 1 + octetValue = 0 + Elseif IsDigit(Mid(ipPart, i, 1)) Then + octetValue = octetValue * 10 + Val(Mid(ipPart, i, 1)) 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" + Next + ip.octets(currentOctet) = octetValue + + Return ip +End Function + +Function ApplyNetworkMask(ip As IPAddress, networkWidth As Integer) As IPAddress + Dim As IPAddress result = ip + Dim As Integer completeOctets = networkWidth \ OCTET_BITS + Dim As Integer remainingBits = networkWidth And 7 + + ' Apply mask to partial octet + If completeOctets < 4 Then + result.octets(completeOctets) And= (MAX_OCTET - 2^(OCTET_BITS-remainingBits) + 1) + ' Zero remaining octets + For i As Integer = completeOctets + 1 To 3 + result.octets(i) = 0 + Next + End If + + Return result +End Function + +Function ValidateInput(ip As IPAddress, networkWidth As Integer, cidr As String) As Boolean + If Instr(cidr, "/") = 0 Then + Print "INVALID CIDR STRING: '"; cidr; "'" + Return False + End If + + If networkWidth < MIN_NETWORK Or networkWidth > MAX_NETWORK Then + Print "INVALID NETWORK WIDTH:"; networkWidth + Return False + End If + + For i As Integer = 0 To 3 + If ip.octets(i) > MAX_OCTET Then + Print "INVALID OCTET VALUE:"; ip.octets(i) + Return False + End If + Next + + Return True +End Function + +Sub ProcessCIDR(cidr As String) + Dim As Integer networkWidth + Dim As IPAddress ip = ParseIPAddress(cidr, networkWidth) + + If Not ValidateInput(ip, networkWidth, cidr) Then Exit Sub + + ip = ApplyNetworkMask(ip, networkWidth) + + Dim As String result = Str(ip.octets(0)) + For i As Integer = 1 To 3 + result &= "." & Str(ip.octets(i)) + Next + Print result & "/" & networkWidth +End Sub + +' Main program +Dim As String cidr(9) = { _ +"87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", _ +"67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18", _ +"127.0.0.1", "123.45.67.89/0", "98.76.54.32/100", "123.456.789.0/12" } + +For i As Integer = 0 To 9 + ProcessCIDR(cidr(i)) +Next Sleep diff --git a/Task/Cantor-set/V-(Vlang)/cantor-set.v b/Task/Cantor-set/V-(Vlang)/cantor-set.v index 42d284fa1b..4da07c3172 100644 --- a/Task/Cantor-set/V-(Vlang)/cantor-set.v +++ b/Task/Cantor-set/V-(Vlang)/cantor-set.v @@ -5,12 +5,10 @@ const ( fn cantor(mut lines [][]u8, start int, len int, index int) { seg := len / 3 - if seg == 0 { - return - } + if seg == 0 {return} for i in index.. height { for j in start + seg..start + 2 * seg { - lines[i][j] = ' '[0] + lines[i][j] = " " [0] } } cantor(mut lines, start, seg, index + 1) diff --git a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur index 88328fabe6..41c5649210 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur +++ b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur @@ -1,16 +1,16 @@ val X = fn ...x:x -writeln mapX(X, [1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]] -writeln mapX(X, [3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]] -writeln mapX(X, [1, 2], []) == [] -writeln mapX(X, [], [1, 2]) == [] +writeln mapX([1, 2], [3, 4], by=X) == [[1, 3], [1, 4], [2, 3], [2, 4]] +writeln mapX([3, 4], [1, 2], by=X) == [[3, 1], [3, 2], [4, 1], [4, 2]] +writeln mapX([1, 2], [], by=X) == [] +writeln mapX([], [1, 2], by=X) == [] writeln() -writeln mapX(X, [1776, 1789], [7, 12], [4, 14, 23], [0, 1]) +writeln mapX([1776, 1789], [7, 12], [4, 14, 23], [0, 1], by=X) writeln() -writeln mapX(X, [1, 2, 3], [30], [500, 100]) +writeln mapX([1, 2, 3], [30], [500, 100], by=X) writeln() -writeln mapX(X, [1, 2, 3], [], [500, 100]) +writeln mapX([1, 2, 3], [], [500, 100], by=X) writeln() diff --git a/Task/Cartesian-product-of-two-or-more-lists/Quackery/cartesian-product-of-two-or-more-lists.quackery b/Task/Cartesian-product-of-two-or-more-lists/Quackery/cartesian-product-of-two-or-more-lists.quackery index f5d68fb2af..f4e6d266e1 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Quackery/cartesian-product-of-two-or-more-lists.quackery +++ b/Task/Cartesian-product-of-two-or-more-lists/Quackery/cartesian-product-of-two-or-more-lists.quackery @@ -1,13 +1,26 @@ - [ [] unrot + [ [] temp put swap witheach - [ over witheach - [ over nested - swap nested join - nested dip rot join - unrot ] - drop ] drop ] is cartprod ( [ [ --> [ ) + [ [] temp put + over witheach + [ dip dup join + nested temp gather ] + drop temp take + temp gather ] + drop temp take ] is cart ( [ [ --> [ ) - ' [ 1 2 ] ' [ 3 4 ] cartprod echo cr - ' [ 3 4 ] ' [ 1 2 ] cartprod echo cr - ' [ 1 2 ] ' [ ] cartprod echo cr - ' [ ] ' [ 1 2 ] cartprod echo cr + [ behead swap witheach cart ] is n-cart ( [ --> [ ) + + ' [ 1 2 ] ' [ 3 4 ] cart echo cr cr + ' [ 1 2 ] ' [ ] cart echo cr cr + ' [ ] ' [ 1 2 ] cart echo cr cr + + ' [ [ 1776 1789 ] [ 7 12 ] [ 4 14 23 ] [ 0 1 ] ] n-cart + say "[ " + witheach + [ i^ 0 != if [ say " " ] + echo + i 0 = if [ say " ]" ] cr ] + cr + + ' [ [ 1 2 3 ] [ 30 ] [ 500 100 ] ] n-cart echo cr cr + ' [ [ 1 2 3 ] [ ] [ 500 100 ] ] n-cart echo cr cr diff --git a/Task/Case-sensitivity-of-identifiers/GW-BASIC/case-sensitivity-of-identifiers.basic b/Task/Case-sensitivity-of-identifiers/GW-BASIC/case-sensitivity-of-identifiers.basic deleted file mode 100644 index 33a43f9953..0000000000 --- a/Task/Case-sensitivity-of-identifiers/GW-BASIC/case-sensitivity-of-identifiers.basic +++ /dev/null @@ -1,5 +0,0 @@ -10 dog$ = "Benjamin" -20 dog$ = "Smokey" -30 dog$ = "Samba" -40 dog$ = "Bernie" -50 print "There is just one dog, named ";dog$ diff --git a/Task/Case-sensitivity-of-identifiers/Joy/case-sensitivity-of-identifiers.joy b/Task/Case-sensitivity-of-identifiers/Joy/case-sensitivity-of-identifiers.joy new file mode 100644 index 0000000000..5e074a15e6 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Joy/case-sensitivity-of-identifiers.joy @@ -0,0 +1,17 @@ +DEFINE dog == "Benjamin". +DEFINE Dog == "Samba". +DEFINE DOG == "Bernie". +"The three dogs are named" +"." DOG "and" Dog "," dog "The three dogs are named" +. +"The three dogs are named" +. +"Benjamin" +. +"," +. +"Samba" +. +"and" +. +"Bernie" diff --git a/Task/Catalan-numbers-Pascals-triangle/FutureBasic/catalan-numbers-pascals-triangle.basic b/Task/Catalan-numbers-Pascals-triangle/FutureBasic/catalan-numbers-pascals-triangle.basic new file mode 100644 index 0000000000..f8d7a51702 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/FutureBasic/catalan-numbers-pascals-triangle.basic @@ -0,0 +1,20 @@ + local fn CatalanNumbers( levels as int ) + int k, n + double num, den, cat + + printf @"1" + + for n = 2 to levels + num = 1 : den = 1 + for k = 2 to n + num *= ( n + k ) + den *= k + cat = num / den + next + printf @"%.f", cat + next +end fn + +fn CatalanNumbers( 30 ) + +HandleEvents diff --git a/Task/Catalan-numbers-Pascals-triangle/PascalABC.NET/catalan-numbers-pascals-triangle.pas b/Task/Catalan-numbers-Pascals-triangle/PascalABC.NET/catalan-numbers-pascals-triangle.pas new file mode 100644 index 0000000000..f031c01feb --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/PascalABC.NET/catalan-numbers-pascals-triangle.pas @@ -0,0 +1,14 @@ +const + n = 15; + +begin + var t: array[0..n + 1] of integer; + t[1] := 1; + for var i := 1 to n do + begin + for var j := i downto 1 do t[j] += t[j - 1]; + t[i + 1] := t[i]; + for var j := i + 1 downto 1 do t[j] += t[j - 1]; + print(t[i + 1] - t[i]); + end; +end. diff --git a/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac b/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac index 2c170a456d..4a49996986 100644 --- a/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac +++ b/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac @@ -12,9 +12,9 @@ Must be loaded at an even address. Input: Number is at 0D.] T 56 K - GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF - H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@ - A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@ + GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TFH17@ + S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@A1FA43@ + G20@XFT44#ZPFT43ZP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@ [Main routine] T 120 K [load at 120] diff --git a/Task/Catalan-numbers/Haskell/catalan-numbers-1.hs b/Task/Catalan-numbers/Haskell/catalan-numbers-1.hs new file mode 100644 index 0000000000..54c01db03f --- /dev/null +++ b/Task/Catalan-numbers/Haskell/catalan-numbers-1.hs @@ -0,0 +1,9 @@ +infixl 7 *. +(*.) :: Num a => a -> [a] -> [a] +x *. (p:ps) = x*p : x*.ps + +instance Num a => Num [a] where + negate = map negate + (+) = zipWith (+) + (*) (p:ps) (q:qs) = p*q : ((p*.qs) + ps*(q:qs)) + fromInteger n = fromInteger n:repeat 0 diff --git a/Task/Catalan-numbers/Haskell/catalan-numbers-2.hs b/Task/Catalan-numbers/Haskell/catalan-numbers-2.hs new file mode 100644 index 0000000000..59351ad478 --- /dev/null +++ b/Task/Catalan-numbers/Haskell/catalan-numbers-2.hs @@ -0,0 +1,2 @@ +catalan :: [Integer] +catalan = 1 : catalan^2 diff --git a/Task/Catalan-numbers/Haskell/catalan-numbers-3.hs b/Task/Catalan-numbers/Haskell/catalan-numbers-3.hs new file mode 100644 index 0000000000..ef200970ea --- /dev/null +++ b/Task/Catalan-numbers/Haskell/catalan-numbers-3.hs @@ -0,0 +1,2 @@ +ghci> take 15 catalan +[1,1,2,5,14,42,132,429,1430,4862,16796,58786,208012,742900,2674440] diff --git a/Task/Catalan-numbers/Haskell/catalan-numbers.hs b/Task/Catalan-numbers/Haskell/catalan-numbers-4.hs similarity index 100% rename from Task/Catalan-numbers/Haskell/catalan-numbers.hs rename to Task/Catalan-numbers/Haskell/catalan-numbers-4.hs diff --git a/Task/Catalan-numbers/Langur/catalan-numbers.langur b/Task/Catalan-numbers/Langur/catalan-numbers.langur index 81d8b2e82f..51ff6b65a4 100644 --- a/Task/Catalan-numbers/Langur/catalan-numbers.langur +++ b/Task/Catalan-numbers/Langur/catalan-numbers.langur @@ -1,4 +1,4 @@ -val factorial = fn x:if(x < 2: 1; x * self(x - 1)) +val factorial = fn x:if(x < 2: 1; x * fn((x - 1))) val catalan = fn n:factorial(2 * n) / factorial(n+1) / factorial(n) diff --git a/Task/Catamorphism/Lua/catamorphism.lua b/Task/Catamorphism/Lua/catamorphism-1.lua similarity index 100% rename from Task/Catamorphism/Lua/catamorphism.lua rename to Task/Catamorphism/Lua/catamorphism-1.lua diff --git a/Task/Catamorphism/Lua/catamorphism-2.lua b/Task/Catamorphism/Lua/catamorphism-2.lua new file mode 100644 index 0000000000..29a7baf0fa --- /dev/null +++ b/Task/Catamorphism/Lua/catamorphism-2.lua @@ -0,0 +1,19 @@ +function foldl(func, init, array) + assert(type(func) == "function", "type(fn) == " .. type(func)) + assert(type(array) == "table", "type(array) == " .. type(array)) + local result = init + for v in ipairs(array) do + result = func(result, v) + end + return result +end + +function add(x, y) return x + y end +mul = function(x, y) return x * y end + +nums = {1,2,3,4,5,6,7,8,9} +print("add 1 to 9 ", foldl(add, 0, nums)) +print("multiply", foldl(mul, 1, nums)) +-- uses anonymous function +print("concatenate", + foldl(function(x,y) return x .. y end, "", nums)) diff --git a/Task/Catamorphism/Pascal/catamorphism.pas b/Task/Catamorphism/Pascal/catamorphism.pas index ad363522b6..e17cca17ba 100644 --- a/Task/Catamorphism/Pascal/catamorphism.pas +++ b/Task/Catamorphism/Pascal/catamorphism.pas @@ -1,53 +1,38 @@ program reduceApp; +{$modeswitch classicProcVars+} + +{Works in many modes with Free Pascal Compiler: +fpc, objfpc, delphi, macpas, iso, extendedpascal} + type -// tmyArray = array of LongInt; - tmyArray = array[-5..5] of LongInt; - tmyFunc = function (a,b:LongInt):LongInt; + Num = LongInt; // this can be changed to Real if desired + BinaryFunc = function(a, b: Num): Num; -function add(x,y:LongInt):LongInt; -begin - add := x+y; -end; +function add(x, y: Num): Num; begin add := x + y; end; +function sub(x, y: Num): Num; begin sub := x - y; end; +function mul(x, y: Num): Num; begin mul := x * y; end; -function sub(k,l:LongInt):LongInt; -begin - sub := k-l; -end; - -function mul(r,t:LongInt):LongInt; -begin - mul := r*t; -end; - -function reduce(myFunc:tmyFunc;a:tmyArray):LongInt; +function reduce(func: BinaryFunc; a: array of Num): Num; var - i,res : LongInt; + i: Integer; + answer: Num; begin - res := a[low(a)]; - For i := low(a)+1 to high(a) do - res := myFunc(res,a[i]); - reduce := res; + answer := a[low(a)]; + for i := low(a)+1 to high(a) do + answer := func(answer, a[i]); + reduce := answer; // return answer end; -procedure InitMyArray(var a:tmyArray); -var - i: LongInt; -begin - For i := low(a) to high(a) do - begin - //no a[i] = 0 - a[i] := i + ord(i=0); - write(a[i],','); - end; - writeln(#8#32); -end; - -var - ma : tmyArray; +VAR + // dynamic array + ma: array of Num; + // static arrays + mb: array[1..9] of Num = (1,2,3,4,5,6,7,8,9); + mc: array[0..8] of Num = (1,2,3,4,5,6,7,8,9); BEGIN - InitMyArray(ma); - writeln(reduce(@add,ma)); - writeln(reduce(@sub,ma)); - writeln(reduce(@mul,ma)); + ma := [1,2,3,4,5,6,7,8,9]; + writeln(reduce(add, ma)); + writeln(reduce(sub, mb)); + writeln(reduce(mul, mc)); END. diff --git a/Task/Chaocipher/EasyLang/chaocipher.easy b/Task/Chaocipher/EasyLang/chaocipher.easy index f748565f29..3d9af716be 100644 --- a/Task/Chaocipher/EasyLang/chaocipher.easy +++ b/Task/Chaocipher/EasyLang/chaocipher.easy @@ -1,8 +1,6 @@ proc index c$ . a$[] ind . for ind = 1 to len a$[] - if a$[ind] = c$ - return - . + if a$[ind] = c$ : return . ind = 0 . @@ -14,12 +12,9 @@ func$ chao txt$ mode . right$[] = strchars right$ len tmp$[] 26 for c$ in strchars txt$ - # print strjoin left$[] & " " & strjoin right$[] if mode = 1 index c$ right$[] ind - if ind = 0 - return "" - . + if ind = 0 : return "" r$ &= left$[ind] else index c$ left$[] ind diff --git a/Task/Chaocipher/Fortran/chaocipher.f b/Task/Chaocipher/Fortran/chaocipher.f new file mode 100644 index 0000000000..ef2f081da9 --- /dev/null +++ b/Task/Chaocipher/Fortran/chaocipher.f @@ -0,0 +1,190 @@ +! +!This program implements the **Chaocipher encryption algorithm** in FORTRAN, extended to handle all printable ASCII characters (32-127). +! The Chaocipher is a polyalphabetic cipher invented by John F. Byrne in 1918, which dynamically permutes two alphabets after +! processing each character, making it highly secure and resistant to cryptanalysis. +! +!#### Key Features: +!1. **Initialization**: +! - Two alphabets (`left` and `right`) are initialized with shuffled ASCII characters (32-127). +! - The `plaintext` is set to "WELLDONEISBETTERTHANWELLSAID". +! +!2. **Enciphering**: +! - For each character in the plaintext: +! - Locate the character in the `right` alphabet. +! - Find the corresponding ciphertext character in the `left` alphabet. +! - Permute both alphabets based on the Chaocipher rules: +! - The `left` alphabet is rotated to bring the ciphertext character to the top, and a specific character is moved to a new position. +! - The `right` alphabet is similarly rotated, with an additional rotation step. +! +!3. **Deciphering**: +! - The ciphertext is decrypted back into plaintext using the reverse process: +! - Locate the ciphertext character in the `left` alphabet. +! - Find the corresponding plaintext character in the `right` alphabet. +! - Permute both alphabets identically as in enciphering. +! +!4. **Verification**: +! - After enciphering and deciphering, the program compares the original plaintext with the decrypted text to ensure correctness. +! +!#### Output: +!The program prints: +!- Initial left and right alphabets. +!- Enciphered ciphertext. +!- Deciphered plaintext. +!- A success message if decryption matches the original plaintext. +! +!#### Example Execution: +!For input plaintext "WELLDONEISBETTERTHANWELLSAID", the program outputs: +!- Ciphertext: `OAHQHCNYNXTSZJRRHJBYHQKSOUJY` +!- Decrypted Text: `WELLDONEISBETTERTHANWELLSAID` +!- Verification: "Decryption successful: plaintext matches decrypted text." +! +!This implementation demonstrates both encryption and decryption processes while adhering to Chaocipher's dynamic permutation rules, +!extended for modern ASCII characters. +! +! +PROGRAM Chaocipher + IMPLICIT NONE + CHARACTER(LEN=96) :: left, right, left_orig, right_orig + CHARACTER(LEN=1000) :: plaintext, ciphertext, decrypted + INTEGER :: i, len, ascii_start + LOGICAL :: trace + + ! Initialize alphabets and input + CALL initialize_alphabets(left, right) + left_orig = left + right_orig = right + plaintext = 'Well, when I was in Egypt, I had a conversation with the Sphinx! She taught me how to sew.' + ciphertext = '' + decrypted = '' + trace = .FALSE. + ascii_start = 32 ! ASCII start at space character + + len = LEN_TRIM(plaintext) + + PRINT *, 'Initial Left: ', left + PRINT *, 'Initial Right:', right + PRINT *, 'Plaintext: ', TRIM(plaintext) + + ! Encipher + DO i = 1, len + CALL encipher(plaintext(i:i), ciphertext(i:i), left, right, ascii_start) + IF (trace) THEN + PRINT *, 'Step ', i + PRINT *, 'Left: ', left + PRINT *, 'Right: ', right + END IF + END DO + + PRINT *, 'Ciphertext: ', TRIM(ciphertext) + + ! Reset alphabets for deciphering + left = left_orig + right = right_orig + + ! Decipher + DO i = 1, len + CALL decipher(ciphertext(i:i), decrypted(i:i), left, right, ascii_start) + END DO + + PRINT *, 'Decrypted: ', TRIM(decrypted) + + ! Check for correctness + IF (plaintext == decrypted) THEN + PRINT *, 'Decryption successful: plaintext matches decrypted text' + ELSE + PRINT *, 'Decryption failed: plaintext does not match decrypted text' + END IF + +CONTAINS + + SUBROUTINE initialize_alphabets(left, right) + CHARACTER(LEN=96), INTENT(OUT) :: left, right + INTEGER :: i, j + CHARACTER :: temp + REAL :: r + + ! Initialize alphabets with ASCII characters 32-127 + DO i = 1, 96 + left(i:i) = CHAR(i + 31) + right(i:i) = CHAR(i + 31) + END DO + + ! Fisher-Yates shuffle for left alphabet + DO i = 96, 2, -1 + CALL RANDOM_NUMBER(r) + j = 1 + FLOOR(i * r) + temp = left(i:i) + left(i:i) = left(j:j) + left(j:j) = temp + END DO + + ! Fisher-Yates shuffle for right alphabet + DO i = 96, 2, -1 + CALL RANDOM_NUMBER(r) + j = 1 + FLOOR(i * r) + temp = right(i:i) + right(i:i) = right(j:j) + right(j:j) = temp + END DO +END SUBROUTINE initialize_alphabets + + SUBROUTINE encipher(p, c, left, right, ascii_start) + CHARACTER(LEN=1), INTENT(IN) :: p + CHARACTER(LEN=1), INTENT(OUT) :: c + CHARACTER(LEN=96), INTENT(INOUT) :: left, right + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + + pos = INDEX(right, p) + c = left(pos:pos) + + CALL permute_left(left, c, ascii_start) + CALL permute_right(right, p, ascii_start) + END SUBROUTINE encipher + + SUBROUTINE decipher(c, p, left, right, ascii_start) + CHARACTER(LEN=1), INTENT(IN) :: c + CHARACTER(LEN=1), INTENT(OUT) :: p + CHARACTER(LEN=96), INTENT(INOUT) :: left, right + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + + pos = INDEX(left, c) + p = right(pos:pos) + + CALL permute_left(left, c, ascii_start) + CALL permute_right(right, p, ascii_start) + END SUBROUTINE decipher + + SUBROUTINE permute_left(alphabet, pivot, ascii_start) + CHARACTER(LEN=96), INTENT(INOUT) :: alphabet + CHARACTER(LEN=1), INTENT(IN) :: pivot + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + CHARACTER(LEN=1) :: temp + + pos = INDEX(alphabet, pivot) + alphabet = alphabet(pos:) // alphabet(:pos-1) + + temp = alphabet(2:2) + alphabet(2:49) = alphabet(3:50) + alphabet(50:50) = temp + END SUBROUTINE permute_left + + SUBROUTINE permute_right(alphabet, pivot, ascii_start) + CHARACTER(LEN=96), INTENT(INOUT) :: alphabet + CHARACTER(LEN=1), INTENT(IN) :: pivot + INTEGER, INTENT(IN) :: ascii_start + INTEGER :: pos + CHARACTER(LEN=1) :: temp + + pos = INDEX(alphabet, pivot) + alphabet = alphabet(pos:) // alphabet(:pos-1) + alphabet = alphabet(2:) // alphabet(1:1) + + temp = alphabet(3:3) + alphabet(3:49) = alphabet(4:50) + alphabet(50:50) = temp + END SUBROUTINE permute_right + +END PROGRAM Chaocipher diff --git a/Task/Chaos-game/Ada/chaos-game.ada b/Task/Chaos-game/Ada/chaos-game.ada new file mode 100644 index 0000000000..fe213c85fc --- /dev/null +++ b/Task/Chaos-game/Ada/chaos-game.ada @@ -0,0 +1,45 @@ +pragma Ada_2022; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Discrete_Random; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Easy_Graphics; use Easy_Graphics; + +procedure Chaos_Game is + Img : Easy_Image := New_Image ((1, 1), (512, 512), WHITE); + + procedure Chaos (Image : in out Easy_Image; + Vertex_Count : Positive; + Radius : Float; + Iters : Positive) is + type Vertex_Array is array (1 .. Vertex_Count) of Point; + Vertices : Vertex_Array; + subtype Vertex_Range is Integer range 1 .. Vertex_Count; + package Rand_V is new Ada.Numerics.Discrete_Random (Vertex_Range); + use Rand_V; + Gen : Generator; + Half_X : constant Integer := X_Last (Image) / 2; + Half_Y : constant Integer := Y_Last (Image) / 2; + Half_Pi : constant Float := Float (Pi) / 2.0; + Two_Pi : constant Float := Float (Pi) * 2.0; + V : Integer; + X : Integer := Half_X; + Y : Integer := Half_Y; + begin + for V in 1 .. Vertex_Count loop + Vertices (V).X := Half_X + Integer (Float (Half_X) * + Cos (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count))); + Vertices (V).Y := Half_Y - Integer (Float (Half_Y) * + Sin (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count))); + end loop; + for I in 1 .. Iters loop + V := Random (Gen); + X := X + Integer (Radius * Float (Vertices (V).X - X)); + Y := Y + Integer (Radius * Float (Vertices (V).Y - Y)); + Plot (Image, (X, Y), BLACK); + end loop; + end Chaos; + +begin + Chaos (Img, 3, 0.5, 250_000); + Write_GIF (Img, "chaos_game.gif"); +end Chaos_Game; diff --git a/Task/Chaos-game/AmigaBASIC/chaos-game.basic b/Task/Chaos-game/AmigaBASIC/chaos-game.basic new file mode 100644 index 0000000000..637e89a1da --- /dev/null +++ b/Task/Chaos-game/AmigaBASIC/chaos-game.basic @@ -0,0 +1,28 @@ +DEFINT a-z +w=600:h=180:w2=300 +x=w*RND:y=h*RND + +FOR i=1 TO 32000 + v=2*RND+1 + ON v GOTO One, Two, Three + +One: + x=x/2 + y=y/2 + GOTO Draw + +Two: + x=w2+(w2-x)/2 + y=h-(h-y)/2 + GOTO Draw + +Three: + x=w-(w-x)/2 + y=y/2 + +Draw: + PSET (x,y),v +NEXT + +loop: + GOTO loop diff --git a/Task/Chaos-game/Atari-BASIC/chaos-game.basic b/Task/Chaos-game/Atari-BASIC/chaos-game.basic new file mode 100644 index 0000000000..b612f7a348 --- /dev/null +++ b/Task/Chaos-game/Atari-BASIC/chaos-game.basic @@ -0,0 +1,18 @@ +10 GRAPHICS 7+16 +20 W=159:H=95:W2=79 +30 X=INT(W*RND(0)) +40 Y=INT(H*RND(0)) +50 FOR I=1 TO 5000 +60 V=INT(3*RND(0))+1 +70 GOTO 100*V +100 X=X/2:Y=Y/2 +110 GOTO 500 +200 X=W2+(W2-X)/2 +210 Y=H-(H-Y)/2 +220 GOTO 500 +300 X=W-(W-X)/2 +310 Y=Y/2 +500 COLOR V +510 PLOT X,Y +520 NEXT I +530 GOTO 530 diff --git a/Task/Character-codes/Dart/character-codes.dart b/Task/Character-codes/Dart/character-codes.dart new file mode 100644 index 0000000000..b1b602f4bd --- /dev/null +++ b/Task/Character-codes/Dart/character-codes.dart @@ -0,0 +1,6 @@ +void main() { + const string = 'D'; + print(string.runes.first); + var out = String.fromCharCode(67); + print(out); +} diff --git a/Task/Character-codes/Langur/character-codes.langur b/Task/Character-codes/Langur/character-codes.langur index e24d7430fe..053f7ab322 100644 --- a/Task/Character-codes/Langur/character-codes.langur +++ b/Task/Character-codes/Langur/character-codes.langur @@ -1,11 +1,11 @@ val a1 = 'a' val a2 = 97 val a3 = "a"[1] -val a4 = s2cp("a", 1) +val a4 = s2cp("a", of=1) val a5 = [a1, a2, a3, a4] writeln a1 == a2 writeln a2 == a3 writeln a3 == a4 -writeln "numbers: ", join(", ", map(string, [a1, a2, a3, a4, a5])) -writeln "letters: ", join(", ", map(cp2s, [a1, a2, a3, a4, a5])) +writeln "numbers: ", join(map([a1, a2, a3, a4, a5], by=string), by=", ") +writeln "letters: ", join(map([a1, a2, a3, a4, a5], by=cp2s), by=", ") diff --git a/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal-1.wren b/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal-1.wren deleted file mode 100644 index 34bcd3db89..0000000000 --- a/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal-1.wren +++ /dev/null @@ -1,7 +0,0 @@ -/* Check_output_device_is_a_terminal.wren */ - -class C { - foreign static isOutputDeviceTerminal -} - -System.print("Output device is a terminal = %(C.isOutputDeviceTerminal)") diff --git a/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal-2.wren b/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal-2.wren deleted file mode 100644 index a1e31b0511..0000000000 --- a/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal-2.wren +++ /dev/null @@ -1,82 +0,0 @@ -#include -#include -#include -#include -#include "wren.h" - -void C_isOutputDeviceTerminal(WrenVM* vm) { - bool isTerminal = (bool)isatty(fileno(stdout)); - wrenSetSlotBool(vm, 0, isTerminal); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "isOutputDeviceTerminal") == 0) { - return C_isOutputDeviceTerminal; - } - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main() { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Check_output_device_is_a_terminal.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal.wren b/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal.wren new file mode 100644 index 0000000000..e8da13ba3c --- /dev/null +++ b/Task/Check-output-device-is-a-terminal/Wren/check-output-device-is-a-terminal.wren @@ -0,0 +1,5 @@ +import "io" for Stdout, Stderr + +System.print("Is output device a terminal?") +System.print(" stdout: %(Stdout.isTerminal)") +System.print(" stderr: %(Stderr.isTerminal)") diff --git a/Task/Check-that-file-exists/Langur/check-that-file-exists.langur b/Task/Check-that-file-exists/Langur/check-that-file-exists.langur index a275544023..b6ce97188b 100644 --- a/Task/Check-that-file-exists/Langur/check-that-file-exists.langur +++ b/Task/Check-that-file-exists/Langur/check-that-file-exists.langur @@ -1,4 +1,4 @@ -val printresult = impure fn(file) { +val printresult = fn*(file) { write file, ": " if val p = prop(file) { if p'isdir { diff --git a/Task/Chernicks-Carmichael-numbers/ALGOL-68/chernicks-carmichael-numbers.alg b/Task/Chernicks-Carmichael-numbers/ALGOL-68/chernicks-carmichael-numbers.alg new file mode 100644 index 0000000000..df8b4ad05f --- /dev/null +++ b/Task/Chernicks-Carmichael-numbers/ALGOL-68/chernicks-carmichael-numbers.alg @@ -0,0 +1,51 @@ +BEGIN # find some of Chernick's Carmichael numbers - translation of Go # + + PR precision 80 PR # set the precision of LONG LONG INT # + PR read "primes.incl.a68" PR # include prime utilities # + + # integer mode large enough to hold a Chernick's Carmichael number # + MODE CHERNICKINTEGER = LONG LONG INT; + # integer mode large to hold a factor of a Chernick's Carmichael number # + MODE CHERNICKFACTOR = LONG INT; + + # returns the value of the Chernick's Carmichaal number U( n, m ) # + # or 0 if n and m are not a Chernicj's Carmichael number # + PROC possible chernick = ( INT n, m )CHERNICKINTEGER: + IF CHERNICKINTEGER prod := 6 * m + 1; + NOT is probably prime( prod ) + THEN 0 + ELIF CHERNICKFACTOR f := 12 * m + 1; + NOT is probably prime( f ) + THEN 0 + ELSE CHERNICKFACTOR t := 9 * m; + prod *:= f; + f := t; + BOOL result := TRUE; + CHERNICKINTEGER ii := 1; + WHILE IF ii > n - 2 + THEN FALSE + ELSE f := ( t +:= t ) + 1; + result := is probably prime( f ) + FI + DO ii +:= 1; + prod *:= f + OD; + IF result THEN prod ELSE 0 FI + FI # possible chernick # ; + + BEGIN + FOR n FROM 3 TO 9 DO + INT m := IF n > 4 THEN 2 ^ ( n - 4 ) ELSE 1 FI; + WHILE IF CHERNICKINTEGER cn = possible chernick( n, m ); + cn > 0 + THEN print( ( "U( ", whole( n, 0 ) ) ); + print( ( ", " , whole( m, -8 ) ) ); + print( ( " ): ", whole( cn, 0 ), newline ) ); + FALSE + ELSE m +:= IF n <= 4 THEN 1 ELSE 2 ^ ( n - 4 ) FI; + TRUE + FI + DO SKIP OD + OD + END +END diff --git a/Task/Chinese-zodiac/00-TASK.txt b/Task/Chinese-zodiac/00-TASK.txt index 5fa4f581b8..04d125ed61 100644 --- a/Task/Chinese-zodiac/00-TASK.txt +++ b/Task/Chinese-zodiac/00-TASK.txt @@ -4,11 +4,11 @@ In the Chinese calendar, years are identified using two lists of labels, one of Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. However, since both lists are of even length, only like-parity pairs occur (A1, A3, A5, but not A2, A4, A6), so only half of the 120 possible pairs are included in the sequence. The result is a repeating 60-year pattern within which each name pair occurs only once. -Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Saturday, February 10, 2024 CE (in the common Gregorian calendar) began the lunisolar Year of the Dragon. +Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Wednesday, January 29, 2025 CE (in the common Gregorian calendar) begins the lunisolar Year of the Snake. The stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the traditional wǔxíng elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang. -Thus, the Chinese year beginning in 2024 CE is also the yang year of Wood. Since 12 is an even number, the association between animals and yin/yang aspect doesn't change; consecutive Years of the Dragon will cycle through the five elements, but will always be yang. +Thus, the Chinese year beginning in 2025 CE is also the yin year of Wood. Since 12 is an even number, the association between animals and yin/yang aspect doesn't change; consecutive Years of the Snake will cycle through the five elements, but will always be yin. ;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. @@ -20,10 +20,10 @@ You may optionally provide more information in the form of the year's numerical * Each element gets two consecutive years; a yang followed by a yin. * The first year (Wood Rat, yang) of the current 60-year cycle began in 1984 CE. -The lunisolar year beginning in 2024 CE - which, as already noted, is the year of the Wood Dragon (yang) - is the 41st of the current cycle. +The lunisolar year beginning in 2025 CE - which, as already noted, is the year of the Wood Snake (yin) - is the 42nd of the current cycle. ;Information for optional task: * The ten celestial stems are '''甲''' ''jiă'', '''乙''' ''yĭ'', '''丙''' ''bĭng'', '''丁''' ''dīng'', '''戊''' ''wù'', '''己''' ''jĭ'', '''庚''' ''gēng'', '''辛''' ''xīn'', '''壬''' ''rén'', and '''癸''' ''gŭi''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". * The twelve terrestrial branches are '''子''' ''zĭ'', '''丑''' ''chŏu'', '''寅''' ''yín'', '''卯''' ''măo'', '''辰''' ''chén'', '''巳''' ''sì'', '''午''' ''wŭ'', '''未''' ''wèi'', '''申''' ''shēn'', '''酉''' ''yŏu'', '''戌''' ''xū'', '''亥''' ''hài''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". -Therefore 1984 was '''甲子''' (''jiă-zĭ'', or jia3-zi3), while 2024 is '''甲辰''' (''jĭa-chén'' or jia3-chen2). +Therefore 1984 was '''甲子''' (''jiă-zĭ'', or jia3-zi3), while 2025 is '''乙巳''' (''yĭ-sì'' or yi3-si4). diff --git a/Task/Chowla-numbers/Quackery/chowla-numbers.quackery b/Task/Chowla-numbers/Quackery/chowla-numbers.quackery new file mode 100644 index 0000000000..6fc47e0c39 --- /dev/null +++ b/Task/Chowla-numbers/Quackery/chowla-numbers.quackery @@ -0,0 +1,31 @@ + [ 2 max + dup sqrt+ + iff 0 else [ dup negate ] + unrot + times + [ dup i^ 1+ /mod + 0 = iff + [ i^ 1+ + + swap dip + ] + else drop ] + 1+ - ] is chowla ( n --> n ) + + 37 times + [ say "chowla(" + i^ 1+ dup echo + say ")= " + chowla echo cr ] + cr + ' [ 100 1000 10000 100000 1000000 10000000 ] + witheach + [ 0 over 2 - times + [ i^ 2 + chowla 0 = + ] + say "There are " echo + say " primes less than " + echo cr ] + cr + 35000000 2 - times + [ i^ 2 + dup chowla 1+ = if + [ i^ 2 + echo + say " is perfect" + cr ] ] diff --git a/Task/Closures-Value-capture/Kotlin/closures-value-capture.kts b/Task/Closures-Value-capture/Kotlin/closures-value-capture-1.kts similarity index 100% rename from Task/Closures-Value-capture/Kotlin/closures-value-capture.kts rename to Task/Closures-Value-capture/Kotlin/closures-value-capture-1.kts diff --git a/Task/Closures-Value-capture/Kotlin/closures-value-capture-2.kts b/Task/Closures-Value-capture/Kotlin/closures-value-capture-2.kts new file mode 100644 index 0000000000..03fcbea1ef --- /dev/null +++ b/Task/Closures-Value-capture/Kotlin/closures-value-capture-2.kts @@ -0,0 +1,5 @@ +val results = mutableListOf<() -> Int>() +for (i in 0..9) { + results.add { i * i } +} +println(results[3]()) // prints "9" diff --git a/Task/Closures-Value-capture/Kotlin/closures-value-capture-3.kts b/Task/Closures-Value-capture/Kotlin/closures-value-capture-3.kts new file mode 100644 index 0000000000..88988eb563 --- /dev/null +++ b/Task/Closures-Value-capture/Kotlin/closures-value-capture-3.kts @@ -0,0 +1,2 @@ +val results = (0..9).map { { it * it } } +println(results[3]()) // prints "9" diff --git a/Task/Color-of-a-screen-pixel/Atari-BASIC/color-of-a-screen-pixel.basic b/Task/Color-of-a-screen-pixel/Atari-BASIC/color-of-a-screen-pixel.basic new file mode 100644 index 0000000000..d28e199feb --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Atari-BASIC/color-of-a-screen-pixel.basic @@ -0,0 +1 @@ +LOCATE X,Y,Q diff --git a/Task/Colorful-numbers/Haskell/colorful-numbers.hs b/Task/Colorful-numbers/Haskell/colorful-numbers.hs index 097645267c..bdecdbc569 100644 --- a/Task/Colorful-numbers/Haskell/colorful-numbers.hs +++ b/Task/Colorful-numbers/Haskell/colorful-numbers.hs @@ -1,23 +1,21 @@ -import Data.List ( nub ) -import Data.List.Split ( divvy ) -import Data.Char ( digitToInt ) +import Data.Char (digitToInt) +isColorful :: Int -> Bool +isColorful n + | n < 0 = error "Only non-negative integers are allowed" + | n == 0 || n == 1 = True + | 0 `elem` digits = False + | 1 `elem` digits = False + | not (distinct digits) = False + | not (distinct subpros) = False + | otherwise = True + where + digits = map digitToInt (show n) + subpros = [(prods !! i) `div` (prods !! j) |j <- [0..length(digits)], i <- [(j+1)..length(digits)]] + prods = scanl (*) 1 digits -isColourful :: Integer -> Bool -isColourful n - |n >= 0 && n <= 10 = True - |n > 10 && n < 100 = ((length s) == (length $ nub s)) && - (not $ any (\c -> elem c "01") s) - |n >= 100 = ((length s) == (length $ nub s)) && (not $ any (\c -> elem c "01") s) - && ((length products) == (length $ nub products)) - where - s :: String - s = show n - products :: [Int] - products = map (\p -> (digitToInt $ head p) * (digitToInt $ last p)) - $ divvy 2 1 s +distinct :: Eq a => [a] -> Bool +distinct [] = True +distinct [a] = True +distinct (x:xs) = distinct xs && (x `notElem` xs) -solution1 :: [Integer] -solution1 = filter isColourful [0 .. 100] - -solution2 :: Integer -solution2 = head $ filter isColourful [98765432, 98765431 ..] +-- Note, for s2, I started at 98762543 as it is the largest number that doesn't 'obviously' violate the colourful condition. Everything else either has 2*3 = 6; 2*4 = 8; 1 or 0 or a repeat digit. This was a rather random optimisation. diff --git a/Task/Colour-bars-Display/Aquarius-BASIC/colour-bars-display.basic b/Task/Colour-bars-Display/Aquarius-BASIC/colour-bars-display.basic new file mode 100644 index 0000000000..d21d2bb53c --- /dev/null +++ b/Task/Colour-bars-Display/Aquarius-BASIC/colour-bars-display.basic @@ -0,0 +1,8 @@ +10 PRINT CHR$(11) +20 CS=12328+1024 +30 FOR Y=0 TO 23 +40 FOR X=0 TO 15 +50 POKE CS+40*Y+X+16,X +60 NEXT +70 NEXT +80 GOTO 80 diff --git a/Task/Colour-bars-Display/Atari-BASIC/colour-bars-display.basic b/Task/Colour-bars-Display/Atari-BASIC/colour-bars-display.basic new file mode 100644 index 0000000000..a8eeba3831 --- /dev/null +++ b/Task/Colour-bars-Display/Atari-BASIC/colour-bars-display.basic @@ -0,0 +1,10 @@ +10 GRAPHICS 11:X=0 +20 FOR C=0 TO 15:COLOR C +30 FOR DX=0 TO 4 +40 PLOT X+DX,0 +50 DRAWTO X+DX,191 +60 NEXT DX +70 X=X+5 +80 NEXT C +90 REM WAIT FOR JOYSTICK FIRE BUTTON PRESS +100 IF STRIG(0)=1 THEN 100 diff --git a/Task/Colour-bars-Display/Crystal/colour-bars-display.cr b/Task/Colour-bars-Display/Crystal/colour-bars-display.cr new file mode 100644 index 0000000000..f2ca7972d4 --- /dev/null +++ b/Task/Colour-bars-Display/Crystal/colour-bars-display.cr @@ -0,0 +1,9 @@ +require "colorize" + +10.times do + [:black, :red, :green, :blue, :magenta, :cyan, :yellow, :white].each do |colour| + print ("█" * 8).colorize colour + end + Colorize.reset + puts +end diff --git a/Task/Colour-bars-Display/Nim/colour-bars-display.nim b/Task/Colour-bars-Display/Nim/colour-bars-display.nim index 77cebe5d54..17e18f999f 100644 --- a/Task/Colour-bars-Display/Nim/colour-bars-display.nim +++ b/Task/Colour-bars-Display/Nim/colour-bars-display.nim @@ -1,58 +1,41 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import cairo const - Width = 400 - Height = 300 + Width = 600 + Height = 400 -#--------------------------------------------------------------------------------------------------- -proc draw(area: DrawingArea; context: Context) = +proc drawBars(surface: ptr Surface) = ## Draw the color bars. - const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0], - [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], - [255.0, 0.0, 255.0], [0.0, 255.0, 255.0], - [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]] + const Colors = [(0.0, 0.0, 0.0), # Black. + (1.0, 0.0, 0.0), # Red. + (0.0, 1.0, 0.0), # Green. + (0.0, 0.0, 1.0), # Blue. + (1.0, 0.0, 1.0), # Magenta. + (0.0, 1.0, 1.0), # Cyan. + (1.0, 1.0, 0.0), # Yellow. + (1.0, 1.0, 1.0) # White. + ] const RectWidth = float(Width div Colors.len) RectHeight = float(Height) + let context = create(surface) + var x = 0.0 - for color in Colors: + for (r, g, b) in Colors: context.rectangle(x, 0, RectWidth, RectHeight) - context.setSource(color) + context.setSourceRgb(r, g, b) context.fill() x += RectWidth -#--------------------------------------------------------------------------------------------------- + context.destroy() -proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = - ## Callback to draw/redraw the drawing area contents. - area.draw(context) - result = true - -#--------------------------------------------------------------------------------------------------- - -proc activate(app: Application) = - ## Activate the application. - - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Color bars") - - # Create the drawing area. - let area = newDrawingArea() - window.add(area) - - # Connect the "draw" event to the callback to draw the spiral. - discard area.connect("draw", ondraw, pointer(nil)) - - window.showAll() - -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.ColorBars") -discard app.connect("activate", activate) -discard app.run() +let surface = imageSurfaceCreate(FormatRgb24, 600, 400) +surface.drawBars() +if surface.writeToPng("color_bars.png") != StatusSuccess: + quit "Error while writing file.", QuitFailure +surface.destroy() diff --git a/Task/Colour-pinstripe-Display/Nim/colour-pinstripe-display.nim b/Task/Colour-pinstripe-Display/Nim/colour-pinstripe-display.nim index d560f6940c..8be6b5c802 100644 --- a/Task/Colour-pinstripe-Display/Nim/colour-pinstripe-display.nim +++ b/Task/Colour-pinstripe-Display/Nim/colour-pinstripe-display.nim @@ -1,63 +1,55 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import gtk2, gdk2, glib2, cairo const Width = 420 Height = 420 -const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0], - [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], - [255.0, 0.0, 255.0], [0.0, 255.0, 255.0], - [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]] +const Colors = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), + (1.0, 0.0, 1.0), (0.0, 1.0, 1.0), + (1.0, 1.0, 0.0), (1.0, 1.0, 1.0)] -#--------------------------------------------------------------------------------------------------- -proc draw(area: DrawingArea; context: Context) = +proc onExposeEvent(widget: PWidget; event: PEventExpose; data: Pgpointer): gboolean {.cdecl.} = ## Draw the color bars. const lineHeight = Height div 4 + let cr = cairo_create(widget.window) + var y = 0.0 for lineWidth in [1.0, 2.0, 3.0, 4.0]: - context.setLineWidth(lineWidth) + cr.setLineWidth(lineWidth) var x = 0.0 var colorIndex = 0 while x < Width: - context.setSource(Colors[colorIndex]) - context.moveTo(x, y) - context.lineTo(x, y + lineHeight) - context.stroke() + let (r, g, b) = Colors[colorIndex] + cr.setSourceRgb(r, g, b) + cr.moveTo(x, y) + cr.lineTo(x, y + lineHeight) + cr.stroke() colorIndex = (colorIndex + 1) mod Colors.len x += lineWidth y += lineHeight -#--------------------------------------------------------------------------------------------------- + cr.destroy() -proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = - ## Callback to draw/redraw the drawing area contents. - area.draw(context) - result = true +proc onDestroyEvent(widget: PWidget; data: Pgpointer): gboolean {.cdecl.} = + ## Quit the application. + main_quit() -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +nim_init() +let window = window_new(gtk2.WINDOW_TOPLEVEL) +window.set_title("Color pinstripe") - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Color pinstripe") +let drawingArea = drawing_area_new() +window.add drawingArea +drawingArea.set_size_request(Width, Height) - # Create the drawing area. - let area = newDrawingArea() - window.add(area) +discard drawingArea.signal_connect("expose-event", SIGNAL_FUNC(onExposeEvent), nil) +discard window.signal_connect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - # Connect the "draw" event to the callback to draw the color bars. - discard area.connect("draw", ondraw, pointer(nil)) - - window.showAll() - -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.ColorPinstripe") -discard app.connect("activate", activate) -discard app.run() +window.show_all() +main() diff --git a/Task/Colour-pinstripe-Printer/Nim/colour-pinstripe-printer.nim b/Task/Colour-pinstripe-Printer/Nim/colour-pinstripe-printer.nim index fedb55ffff..18f983f387 100644 --- a/Task/Colour-pinstripe-Printer/Nim/colour-pinstripe-printer.nim +++ b/Task/Colour-pinstripe-Printer/Nim/colour-pinstripe-printer.nim @@ -1,22 +1,66 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import gtk2, glib2, cairo -const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0], - [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], - [255.0, 0.0, 255.0], [0.0, 255.0, 255.0], - [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]] +############################################################################### +# Missing declarations needed for print operations. -#--------------------------------------------------------------------------------------------------- +when defined(win32): + const lib = "libgtk-win32-2.0-0.dll" +elif defined(macosx): + const lib = "(libgtk-quartz-2.0.0.dylib|libgtk-x11-2.0.dylib)" +else: + const lib = "libgtk-x11-2.0.so(|.0)" -proc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) = - ## Process signal "begin_print", that is set the number of pages to print. - op.setNPages(1) +# Missing type definitions. +type + PrintOperation = PObject + PrintContext = PObject + PrintOperationAction = enum + PRINT_OPERATION_ACTION_PRINT_DIALOG + PRINT_OPERATION_ACTION_PRINT + PRINT_OPERATION_ACTION_PREVIEW + PRINT_OPERATION_ACTION_EXPORT + PrintOperationResult = enum + PRINT_OPERATION_RESULT_ERROR + PRINT_OPERATION_RESULT_APPLY + PRINT_OPERATION_RESULT_CANCEL + PRINT_OPERATION_RESULT_IN_PROGRESS -#--------------------------------------------------------------------------------------------------- +# Missing external procedures. +proc print_operation_new(): PrintOperation {.cdecl, + importc: "gtk_print_operation_new", dynlib: lib.} +proc print_operation_run(op: PrintOperation; action: PrintOperationAction; + parent: PWindow; error: pointer): PrintOperationResult {.cdecl, + importc: "gtk_print_operation_run", dynlib: lib.} +proc set_n_pages(op: PrintOperation; n: gint) {.cdecl, + importc: "gtk_print_operation_set_n_pages", dynlib: lib.} +proc get_cairo_context(printContext: PrintContext): ptr Context {.cdecl, + importc: "gtk_print_context_get_cairo_context", dynlib: lib.} +proc width(printContext: PrintContext): cdouble {.cdecl, + importc: "gtk_print_context_get_width", dynlib: lib.} +proc height(printContext: PrintContext): cdouble {.cdecl, + importc: "gtk_print_context_get_height", dynlib: lib.} -proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) = - ## Draw a page. - let context = printContext.getCairoContext() +############################################################################### + +const Colors = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), + (1.0, 0.0, 1.0), (0.0, 1.0, 1.0), + (1.0, 1.0, 0.0), (1.0, 1.0, 1.0)] + + +proc beginPrint(op: PrintOperation; printContext: PrintContext; + data: Pgpointer): gboolean {.cdecl.} = + ## Process "begin_print" signal. + op.setNPages(1) # Print one page. + result = true + + +proc drawPage(op: PrintOperation; printContext: PrintContext; + pageNum: int; data: Pgpointer): gboolean {.cdecl.} = + ## Process "draw_page" signal. + + let context = printContext.get_cairo_context() let lineHeight = printContext.height / 4 var y = 0.0 @@ -25,7 +69,8 @@ proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data var x = 0.0 var colorIndex = 0 while x < printContext.width: - context.setSource(Colors[colorIndex]) + let (r, g, b) = Colors[colorIndex] + context.setSourceRgb(r, g, b) context.moveTo(x, y) context.lineTo(x, y + lineHeight) context.stroke() @@ -33,21 +78,13 @@ proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data x += lineWidth y += lineHeight -#--------------------------------------------------------------------------------------------------- + result = true/* {{header|Nim}} */ -proc activate(app: Application) = - ## Activate the application. - # Launch a print operation. - let op = newPrintOperation() - op.connect("begin_print", beginPrint, pointer(nil)) - op.connect("draw_page", drawPage, pointer(nil)) +nim_init() - # Run the print dialog. - discard op.run(printDialog) - -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.ColorPinstripe") -discard app.connect("activate", activate) -discard app.run() +# Print the pinstripe. +let op = print_operation_new() +discard op.g_signal_connect("begin_print", G_CALLBACK(begin_print), nil) +discard op.g_signal_connect("draw_page", G_CALLBACK(draw_page), nil) +discard op.print_operation_run(PRINT_OPERATION_ACTION_PRINT_DIALOG, nil, nil) diff --git a/Task/Combinations-and-permutations/Quackery/combinations-and-permutations.quackery b/Task/Combinations-and-permutations/Quackery/combinations-and-permutations.quackery new file mode 100644 index 0000000000..68b70aa74c --- /dev/null +++ b/Task/Combinations-and-permutations/Quackery/combinations-and-permutations.quackery @@ -0,0 +1,21 @@ + [ 1 swap times [ i^ 1+ * ] ] is ! ( n --> n ) + + [ dip dup - ! dip ! / ] is p ( n n --> n ) + + [ tuck p swap ! / ] is c ( n n --> n ) + + ' [ [ 1 0 ] [ 12 4 ] [ 60 20 ] [ 105 103 ] [ 15000 333 ] ] + witheach + [ unpack 2dup + say " P(" + swap echo say "," echo + say ") = " + p shorten echo$ cr ] + cr + ' [ [ 10 5 ] [ 60 30 ] [ 50 48 ] [ 900 675 ] [ 970 730 ] ] + witheach + [ unpack 2dup + say " C(" + swap echo say "," echo + say ") = " + c shorten echo$ cr ] diff --git a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq index 3972206ac5..bb25c96913 100644 --- a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq +++ b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-1.jq @@ -6,3 +6,5 @@ def pick(n): else ([.[m]] + pick(n-1; m)), pick(n; m+1) end; pick(n;0) ; + +def count(s): reduce s as $_ (0; .+1); diff --git a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq index 6c2692b448..50f06bd1e4 100644 --- a/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq +++ b/Task/Combinations-with-repetitions/Jq/combinations-with-repetitions-2.jq @@ -1,4 +1,4 @@ - "Pick 2:", +"Pick 2:", (["iced", "jam", "plain"] | pick(2)), - ([[range(0;10)] | pick(3)] | length) as $n - | "There are \($n) ways to pick 3 objects with replacement from 10." + (count( [range(0;10)] | pick(3)) as $n + | "There are \($n) ways to pick 3 objects with replacement from 10.") diff --git a/Task/Combinations/M2000-Interpreter/combinations-1.m2000 b/Task/Combinations/M2000-Interpreter/combinations-1.m2000 index a5f1f5bb7e..47e46a34ce 100644 --- a/Task/Combinations/M2000-Interpreter/combinations-1.m2000 +++ b/Task/Combinations/M2000-Interpreter/combinations-1.m2000 @@ -1,41 +1,32 @@ Module Checkit { - Global a$ - Document a$ - Module Combinations (m as long, n as long){ + Function Combinations (m as long, n as long){ + Global a$ + Document a$ Module Level (n, s, h) { - If n=1 then { - while Len(s) { - Print h, car(s) - ToClipBoard() + If n=1 then + while Len(s) + a$<=h#str$("-")+"-"+car(s)#str$()+{ + } s=cdr(s) - } - } Else { - While len(s) { + End While + Else + While len(s) call Level n-1, cdr(s), cons(h, car(s)) s=cdr(s) - } - } - Sub ToClipBoard() - local m=each(h) - Local b$="" - While m { - b$+=If$(Len(b$)<>0->" ","")+Format$("{0::-10}",Array(m)) - } - b$+=If$(Len(b$)<>0->" ","")+Format$("{0::-10}",Array(s,0))+{ - } - a$<=b$ ' assign to global need <= - End Sub + End While + End if } If m<1 or n<1 then Error s=(,) - for i=0 to n-1 { - s=cons(s, (i,)) - } + for i=0 to n-1 + Append s, (i,) + next + s=s#sort() Head=(,) Call Level m, s, Head + =a$ } - Clear a$ - Combinations 3, 5 - ClipBoard a$ + ClipBoard Combinations( 3, 5) + report clipboard$ } Checkit diff --git a/Task/Combinations/M2000-Interpreter/combinations-2.m2000 b/Task/Combinations/M2000-Interpreter/combinations-2.m2000 index 96566c892d..9d851f853b 100644 --- a/Task/Combinations/M2000-Interpreter/combinations-2.m2000 +++ b/Task/Combinations/M2000-Interpreter/combinations-2.m2000 @@ -1,45 +1,55 @@ Module StepByStep { - Function CombinationsStep (a, nn) { - c1=lambda (&f, &a) ->{ - =car(a) : a=cdr(a) : f=len(a)=0 - } - m=len(a) + Function CombinationsStep (a, nn) { + c1=lambda (&f, &a) ->{ + =car(a) : a=cdr(a) : f=len(a)=0 + } + m=len(a) + c=c1 + n=m-nn+1 + p=2 + While m>n + c1=lambda c2=c,n=p, z=(,) (&f, &m) ->{ + if len(z)=0 then z=cdr(m) + =cons(car(m),c2(&f, &z)) + if f then z=(,) : m=cdr(m) : f=len(m)+len(z)n { - c1=lambda c2=c,n=p, z=(,) (&f, &m) ->{ - if len(z)=0 then z=cdr(m) - =cons(car(m),c2(&f, &z)) - if f then z=(,) : m=cdr(m) : f=len(m)+len(z) { + =c(&f, &a) } - =lambda c, a (&f) -> { - =c(&f, &a) - } - } - k=false - StepA=CombinationsStep((1, 2, 3, 4,5), 3) - while not k { - Print StepA(&k) - } - k=false - StepA=CombinationsStep((0, 1, 2, 3, 4), 3) - while not k { - Print StepA(&k) - } - k=false - StepA=CombinationsStep(("A", "B", "C", "D","E"), 3) - while not k { - Print StepA(&k) - } - k=false - StepA=CombinationsStep(("CAT", "DOG", "BAT"), 2) - while not k { - Print StepA(&k) - } + } + enum out {screen="", file="out.txt"} + m=each(out) + while m + open eval(m) for output as #f + k=false + StepA=CombinationsStep((1, 2, 3, 4,5), 3) + While not k + Print #f, StepA(&k)#str$() + End While + Print #f + k=false + StepA=CombinationsStep((0, 1, 2, 3, 4), 3) + While not k + Print #f, StepA(&k)#str$() + End While + Print #f + k=false + StepA=CombinationsStep(("A", "B", "C", "D","E"), 3) + While not k + Print #f, StepA(&k)#str$("-") + End While + Print #f + k=false + StepA=CombinationsStep(("CAT", "DOG", "BAT"), 2) + While not k + Print #f, StepA(&k)#str$("-") + End While + close #f + end while + win "notepad", dir$+file } StepByStep diff --git a/Task/Combinations/Quackery/combinations-1.quackery b/Task/Combinations/Quackery/combinations-1.quackery index 697808559d..ccf881afbe 100644 --- a/Task/Combinations/Quackery/combinations-1.quackery +++ b/Task/Combinations/Quackery/combinations-1.quackery @@ -1,48 +1,21 @@ - [ 0 swap - [ dup 0 != while - dup 1 & if - [ dip 1+ ] - 1 >> again ] - drop ] is bits ( n --> n ) - - [ [] unrot - bit times - [ i bits - over = if - [ dip - [ i join ] ] ] - drop ] is combnums ( n n --> [ ) - - [ [] 0 rot - [ dup 0 != while - dup 1 & if - [ dip - [ dup dip join ] ] - dip 1+ - 1 >> - again ] - 2drop ] is makecomb ( n --> [ ) - [ over 0 = iff - [ 2drop [] ] done - combnums - [] swap witheach - [ makecomb - nested join ] ] is comb ( n n --> [ ) + [ 2drop ' [ [ ] ] ] + done + dup [] = iff nip done + 1 split rot tuck + 1 - over recurse + dip [ rot [] ] + witheach + [ dip over join + nested join ] + nip unrot recurse join ] is comb ( n [ --> [ ) - [ behead swap witheach max ] is largest ( [ --> n ) + [ [] swap times + [ i^ join ] + comb + witheach + [ witheach + [ echo sp ] + cr ] ] is task ( n n --> ) - [ 0 rot witheach - [ [ dip [ over * ] ] + ] - nip ] is comborder ( [ n --> n ) - - [ dup [] != while - sortwith - [ 2dup join - largest 1+ dup dip - [ comborder swap ] - comborder < ] ] is sortcombs ( [ --> [ ) - - 3 5 comb - sortcombs - witheach [ witheach [ echo sp ] cr ] + 3 5 task diff --git a/Task/Combinations/Quackery/combinations-2.quackery b/Task/Combinations/Quackery/combinations-2.quackery index 5626470d75..697808559d 100644 --- a/Task/Combinations/Quackery/combinations-2.quackery +++ b/Task/Combinations/Quackery/combinations-2.quackery @@ -1,31 +1,48 @@ - [ stack ] is comb.stack - [ stack ] is comb.items - [ stack ] is comb.required - [ stack ] is comb.result + [ 0 swap + [ dup 0 != while + dup 1 & if + [ dip 1+ ] + 1 >> again ] + drop ] is bits ( n --> n ) - [ 1 - comb.items put - 1+ comb.required put - 0 comb.stack put - [] comb.result put - [ comb.required share - comb.stack size = if - [ comb.result take - comb.stack behead - drop nested join - comb.result put ] - comb.stack take - dup comb.items share - = iff - [ drop - comb.stack size 1 > iff - [ 1 comb.stack tally ] ] - else - [ dup comb.stack put - 1+ comb.stack put ] - comb.stack size 1 = until ] - comb.items release - comb.required release - comb.result take ] is comb ( n n --> ) + [ [] unrot + bit times + [ i bits + over = if + [ dip + [ i join ] ] ] + drop ] is combnums ( n n --> [ ) + + [ [] 0 rot + [ dup 0 != while + dup 1 & if + [ dip + [ dup dip join ] ] + dip 1+ + 1 >> + again ] + 2drop ] is makecomb ( n --> [ ) + + [ over 0 = iff + [ 2drop [] ] done + combnums + [] swap witheach + [ makecomb + nested join ] ] is comb ( n n --> [ ) + + [ behead swap witheach max ] is largest ( [ --> n ) + + [ 0 rot witheach + [ [ dip [ over * ] ] + ] + nip ] is comborder ( [ n --> n ) + + [ dup [] != while + sortwith + [ 2dup join + largest 1+ dup dip + [ comborder swap ] + comborder < ] ] is sortcombs ( [ --> [ ) 3 5 comb + sortcombs witheach [ witheach [ echo sp ] cr ] diff --git a/Task/Combinations/Quackery/combinations-3.quackery b/Task/Combinations/Quackery/combinations-3.quackery index 721a651555..5626470d75 100644 --- a/Task/Combinations/Quackery/combinations-3.quackery +++ b/Task/Combinations/Quackery/combinations-3.quackery @@ -1,16 +1,31 @@ - [ dup size dip - [ witheach - [ over swap peek swap ] ] - nip pack ] is arrange ( [ [ --> [ ) + [ stack ] is comb.stack + [ stack ] is comb.items + [ stack ] is comb.required + [ stack ] is comb.result + + [ 1 - comb.items put + 1+ comb.required put + 0 comb.stack put + [] comb.result put + [ comb.required share + comb.stack size = if + [ comb.result take + comb.stack behead + drop nested join + comb.result put ] + comb.stack take + dup comb.items share + = iff + [ drop + comb.stack size 1 > iff + [ 1 comb.stack tally ] ] + else + [ dup comb.stack put + 1+ comb.stack put ] + comb.stack size 1 = until ] + comb.items release + comb.required release + comb.result take ] is comb ( n n --> ) - ' [ 10 20 30 40 50 ] 3 5 comb - witheach - [ dip dup arrange - witheach [ echo sp ] - cr ] - drop - cr - $ "zero one two three four" nest$ - ' [ 4 3 1 0 1 4 3 ] arrange - witheach [ echo$ sp ] + witheach [ witheach [ echo sp ] cr ] diff --git a/Task/Combinations/Quackery/combinations-4.quackery b/Task/Combinations/Quackery/combinations-4.quackery new file mode 100644 index 0000000000..721a651555 --- /dev/null +++ b/Task/Combinations/Quackery/combinations-4.quackery @@ -0,0 +1,16 @@ + [ dup size dip + [ witheach + [ over swap peek swap ] ] + nip pack ] is arrange ( [ [ --> [ ) + + ' [ 10 20 30 40 50 ] + 3 5 comb + witheach + [ dip dup arrange + witheach [ echo sp ] + cr ] + drop + cr + $ "zero one two three four" nest$ + ' [ 4 3 1 0 1 4 3 ] arrange + witheach [ echo$ sp ] diff --git a/Task/Command-line-arguments/FutureBasic/command-line-arguments.basic b/Task/Command-line-arguments/FutureBasic/command-line-arguments.basic new file mode 100644 index 0000000000..ed30014088 --- /dev/null +++ b/Task/Command-line-arguments/FutureBasic/command-line-arguments.basic @@ -0,0 +1,14 @@ +include "NSLog.incl" + +void local fn DoCommandLineArguments + CFArrayRef args = fn ProcessInfoArguments + NSLog(@"This program is named %@.",args[0]) + NSLog(@"There are %d arguments.",len(args)-1) + for long i = 1 to len(args)-1 + NSLog(@"the argument #%d is %@", i, args[i]) + next +end fn + +fn DoCommandLineArguments + +HandleEvents diff --git a/Task/Command-line-arguments/LDPL/command-line-arguments-1.ldpl b/Task/Command-line-arguments/LDPL/command-line-arguments-1.ldpl new file mode 100644 index 0000000000..26aa218485 --- /dev/null +++ b/Task/Command-line-arguments/LDPL/command-line-arguments-1.ldpl @@ -0,0 +1,10 @@ +DATA: + argument_count IS NUMBER + +PROCEDURE: + GET LENGTH OF argv IN argument_count + IF argument_count IS EQUAL TO 0 THEN + DISPLAY "No arguments!" CRLF + ELSE + DISPLAY argv:0 CRLF + END IF diff --git a/Task/Command-line-arguments/LDPL/command-line-arguments-2.ldpl b/Task/Command-line-arguments/LDPL/command-line-arguments-2.ldpl new file mode 100644 index 0000000000..6cc4b9df78 --- /dev/null +++ b/Task/Command-line-arguments/LDPL/command-line-arguments-2.ldpl @@ -0,0 +1,6 @@ +$ ldpl argv.ldpl +* Loading argv.ldpl +* Compiling argv.ldpl +* Building argv-bin +* Saved as argv-bin +* File(s) compiled successfully. diff --git a/Task/Command-line-arguments/LDPL/command-line-arguments-3.ldpl b/Task/Command-line-arguments/LDPL/command-line-arguments-3.ldpl new file mode 100644 index 0000000000..ff51e1fe0c --- /dev/null +++ b/Task/Command-line-arguments/LDPL/command-line-arguments-3.ldpl @@ -0,0 +1,4 @@ +$ ./argv-bin test +test +$ ./argv-bin +No arguments! diff --git a/Task/Command-line-arguments/Tcl/command-line-arguments-1.tcl b/Task/Command-line-arguments/Tcl/command-line-arguments-1.tcl new file mode 100644 index 0000000000..3e39085837 --- /dev/null +++ b/Task/Command-line-arguments/Tcl/command-line-arguments-1.tcl @@ -0,0 +1,3 @@ +if { $argc >= 1 } { + puts [lindex $argv 0] +} diff --git a/Task/Command-line-arguments/Tcl/command-line-arguments-2.tcl b/Task/Command-line-arguments/Tcl/command-line-arguments-2.tcl new file mode 100644 index 0000000000..8db1f98495 --- /dev/null +++ b/Task/Command-line-arguments/Tcl/command-line-arguments-2.tcl @@ -0,0 +1,2 @@ +$ tclsh file.tcl test +test diff --git a/Task/Command-line-arguments/Tcl/command-line-arguments.tcl b/Task/Command-line-arguments/Tcl/command-line-arguments.tcl deleted file mode 100644 index 0827817f9e..0000000000 --- a/Task/Command-line-arguments/Tcl/command-line-arguments.tcl +++ /dev/null @@ -1,3 +0,0 @@ -if { $argc > 1 } { - puts [lindex $argv 1] -} diff --git a/Task/Command-line-arguments/Zig/command-line-arguments.zig b/Task/Command-line-arguments/Zig/command-line-arguments.zig new file mode 100644 index 0000000000..5b35ff255c --- /dev/null +++ b/Task/Command-line-arguments/Zig/command-line-arguments.zig @@ -0,0 +1,13 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + const args = try std.process.argsAlloc(allocator); + + try stdout.print("{s}\n", .{args}); +} diff --git a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn index 513bc811cf..a840cab418 100644 --- a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn +++ b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-1.bqn @@ -1,8 +1 @@ -AllEq ← ⍋≡⍒ -Asc ← ¬∘AllEq∧∧≡⊢ - -•Show AllEq ⟨"AA", "AA", "AA", "AA"⟩ -•Show Asc ⟨"AA", "AA", "AA", "AA"⟩ - -•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩ -•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩ +⊣` diff --git a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn index 680eb502aa..51394587b4 100644 --- a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn +++ b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-2.bqn @@ -1,4 +1,8 @@ -1 -0 -0 -1 +AllEq ← ⍋≡⍒ # or ⊣`⊸≡ +Asc ← ⍷∘∧⊸≡ + +•Show AllEq ⟨"AA", "AA", "AA", "AA"⟩ +•Show Asc ⟨"AA", "AA", "AA", "AA"⟩ + +•Show AllEq ⟨"AA", "ACB", "BB", "CC"⟩ +•Show Asc ⟨"AA", "ACB", "BB", "CC"⟩ diff --git a/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-3.bqn b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-3.bqn new file mode 100644 index 0000000000..680eb502aa --- /dev/null +++ b/Task/Compare-a-list-of-strings/BQN/compare-a-list-of-strings-3.bqn @@ -0,0 +1,4 @@ +1 +0 +0 +1 diff --git a/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq b/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq index 9d9694486b..9a73ae5c6f 100644 --- a/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq +++ b/Task/Compare-a-list-of-strings/Jq/compare-a-list-of-strings-1.jq @@ -1,11 +1,11 @@ # Are the strings all equal? def lexically_equal: - . as $in - | reduce range(0;length-1) as $i - (true; if . then $in[$i] == $in[$i + 1] else false end); + if length <= 1 then true + else . as $in + | all( range(0;length-1); $in[0] == $in[. + 1]) + end; -# Are the strings in strictly ascending order? +# Are the elements in strictly ascending order? def lexically_ascending: . as $in - | reduce range(0;length-1) as $i - (true; if . then $in[$i] < $in[$i + 1] else false end); + | all( range(0;length-1); $in[.] < $in[. + 1]); diff --git a/Task/Compare-a-list-of-strings/K/compare-a-list-of-strings.k b/Task/Compare-a-list-of-strings/K/compare-a-list-of-strings.k new file mode 100644 index 0000000000..94f07991ed --- /dev/null +++ b/Task/Compare-a-list-of-strings/K/compare-a-list-of-strings.k @@ -0,0 +1,2 @@ +alleq:&/1_~': +asc:&/(*<,)':,:' diff --git a/Task/Compile-time-calculation/Python/compile-time-calculation.py b/Task/Compile-time-calculation/Python/compile-time-calculation.py new file mode 100644 index 0000000000..2aa67ebc19 --- /dev/null +++ b/Task/Compile-time-calculation/Python/compile-time-calculation.py @@ -0,0 +1 @@ +fc = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 diff --git a/Task/Compound-data-type/M2000-Interpreter/compound-data-type.m2000 b/Task/Compound-data-type/M2000-Interpreter/compound-data-type.m2000 new file mode 100644 index 0000000000..3b9796e35b --- /dev/null +++ b/Task/Compound-data-type/M2000-Interpreter/compound-data-type.m2000 @@ -0,0 +1,27 @@ +class point { + single x, y +class: + module point (.x, .y) {} +} +function global add2(k as point) { + k.x+=2 + =k +} +module check { + a=point(2.343, 4.556) + print a.x, a.y + alfa(@add1(a)) + a=add2(a) + alfa(a) + print a is type point = true + + sub alfa(k as point) + print k.x + end sub + + function add1(k as point) + k.x+=1 + =k + end function +} +check diff --git a/Task/Concurrent-computing/M2000-Interpreter/concurrent-computing.m2000 b/Task/Concurrent-computing/M2000-Interpreter/concurrent-computing.m2000 index f6093e4fcb..06efefcb69 100644 --- a/Task/Concurrent-computing/M2000-Interpreter/concurrent-computing.m2000 +++ b/Task/Concurrent-computing/M2000-Interpreter/concurrent-computing.m2000 @@ -1,6 +1,6 @@ Thread.Plan Concurrent Module CheckIt { - Flush \\ empty stack of values + Flush ' empty stack of values Data "Enjoy", "Rosetta", "Code" For i=1 to 3 { Thread { @@ -13,21 +13,21 @@ Module CheckIt { Threads } Rem : Wait 3000 ' we can use just a wait loop, or the main.task loop - \\ main.task exit if all threads erased + ' main.task exit if all threads erased Main.Task 30 { } -\\ when module exit all threads from this module get a signal to stop. -\\ we can use Threads Erase to erase all threads. -\\ Also if we press Esc we do the same +' when module exit all threads from this module get a signal to stop. +' we can use Threads Erase to erase all threads. +' Also if we press Esc we do the same } CheckIt -\\ we can define again the module, and now we get three time each name, but not every time three same names. -\\ if we change to Threads.Plan Sequential we get always the three same names -\\ Also in concurrent plan we can use a block to ensure that statements run without other thread executed in parallel. +' we can define again the module, and now we get three time each name, but not every time three same names. +' if we change to Threads.Plan Sequential we get always the three same names +' Also in concurrent plan we can use a block to ensure that statements run without other thread executed in parallel. Module CheckIt { - Flush \\ empty stack of values + Flush ' empty stack of values Data "Enjoy", "Rosetta", "Code" For i=1 to 3 { Thread { @@ -42,11 +42,11 @@ Module CheckIt { Threads } Rem : Wait 3000 ' we can use just a wait loop, or the main.task loop - \\ main.task exit if all threads erased + ' main.task exit if all threads erased Main.Task 30 { } -\\ when module exit all threads from this module get a signal to stop. -\\ we can use Threads Erase to erase all threads. -\\ Also if we press Esc we do the same +' when module exit all threads from this module get a signal to stop. +' we can use Threads Erase to erase all threads. +' Also if we press Esc we do the same } CheckIt diff --git a/Task/Consecutive-primes-with-ascending-or-descending-differences/ALGOL-68/consecutive-primes-with-ascending-or-descending-differences.alg b/Task/Consecutive-primes-with-ascending-or-descending-differences/ALGOL-68/consecutive-primes-with-ascending-or-descending-differences.alg index 7b1613f55e..d6d1a27772 100644 --- a/Task/Consecutive-primes-with-ascending-or-descending-differences/ALGOL-68/consecutive-primes-with-ascending-or-descending-differences.alg +++ b/Task/Consecutive-primes-with-ascending-or-descending-differences/ALGOL-68/consecutive-primes-with-ascending-or-descending-differences.alg @@ -17,7 +17,7 @@ BEGIN # find sequences of primes where the gaps between the elements # FOR i TO n DO IF p[ i ] = yes THEN p[ p pos +:= 1 ] := i FI OD; p[ 1 : p pos ] END # prime list # ; - # shos the results of a search # + # shows the results of a search # PROC show sequence = ( []INT primes, STRING seq name, INT seq start, seq length )VOID: BEGIN print( ( " The longest sequence of primes with " diff --git a/Task/Constrained-genericity/Python/constrained-genericity.py b/Task/Constrained-genericity/Python/constrained-genericity.py new file mode 100644 index 0000000000..1cb6717482 --- /dev/null +++ b/Task/Constrained-genericity/Python/constrained-genericity.py @@ -0,0 +1,42 @@ +"""Constrained genericity. Requires Python >= 3.9.""" + +from typing import Generic +from typing import Protocol +from typing import TypeVar +from typing import runtime_checkable + +T = TypeVar("T", covariant=True) + + +@runtime_checkable +class Edible(Protocol[T]): + def eat(self) -> T: ... + + +class FoodBox(Generic[T]): + def __init__(self, *food: Edible[T]): + # Runtime type checking + for item in food: + if not isinstance(item, Edible): + raise TypeError(f"expected food, found {item.__class__.__name__}") + + self.contents = food + + +class Cheese: + def eat(self) -> None: + print("eating cheese") + + +class Shoe: + def wear(self) -> None: + print("wearing shoe") + + +if __name__ == "__main__": + box = FoodBox[None](Cheese()) + for food in box.contents: + food.eat() + + # This fails static type checking. + box = FoodBox[None](Cheese(), Shoe()) diff --git a/Task/Constrained-random-points-on-a-circle/FutureBasic/constrained-random-points-on-a-circle.basic b/Task/Constrained-random-points-on-a-circle/FutureBasic/constrained-random-points-on-a-circle.basic new file mode 100644 index 0000000000..11e9b8959d --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/FutureBasic/constrained-random-points-on-a-circle.basic @@ -0,0 +1,20 @@ +//Constrained random points on a circle +//https://rosettacode.org/wiki/Constrained_random_points_on_a_circle +// Translated from Yabasic to FutureBASIC + +short i,x,y,r +window 1,@"Circle",fn CGRectMake(0, 0, 100, 100),NSWindowStyleMaskTitled +windowcenter(1) +WindowSetBackgroundColor(1,fn ColorBlack) +for i = 1 to 100 + do + x = rnd(30)-15 + y = rnd(30)-15 + r = fn sqrt(x*x + y*y) + until 10 <= r and r <= 15 + + oval fill (x+50, y+50,1,1) +next i + + +handleevents diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code/continued-fraction-arithmetic-construct-from-rational-number.edsac b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code/continued-fraction-arithmetic-construct-from-rational-number.edsac index 859cc85936..a9bbf460bf 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code/continued-fraction-arithmetic-construct-from-rational-number.edsac +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code/continued-fraction-arithmetic-construct-from-rational-number.edsac @@ -28,13 +28,14 @@ [---------------------------------------------------------------------- Modification of library subroutine P7. Prints signed integer up to 10 digits, left-justified. - 54 storage locations; working position 4D. + 52 storage locations; working position 4D. Must be loaded at an even address. Input: Number is at 0D.] - T 56 K - GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF - H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@ - T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@ + [2024-12-25 Fixed bug in print subroutine. Did not affect Rosetta Code output.] + T 56 K + GKA3FT42@A47@T31@ADE10@T31@A46@T31@SDTDH44#@NDYFLDT4DS43@ + TFH17@S17@A43@G23@UFS43@T1FV4DAFG48@SFLDUFXFOFFFSFL4FT4DA47@ + T31@A1FA43@G20@XFT44#ZPFT43ZP1024FP610D@524DO26@XFSFL8FT4DE39@ [---------------------------------------------------------------------- Division subroutine for long positive integers. diff --git a/Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational.fth b/Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational-1.fth similarity index 100% rename from Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational.fth rename to Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational-1.fth diff --git a/Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational-2.fth b/Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational-2.fth new file mode 100644 index 0000000000..dbfe173a7b --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Forth/convert-decimal-number-to-rational-2.fth @@ -0,0 +1,13 @@ +: RealToRational ( f n1 -- n2 n3) + 0 dup rot max-n s>f fswap fdup f0< >r + fabs fdup ftrunc f>s 1+ swap ( den num lim real R: neg F: best real) + \ helps set integer bounds around target + 1+ 1 ?do \ search through possible denominators + dup i * over 1- i * ?do \ search within integer limits bounding the real + fover fover i s>f j s>f f/ f- fabs fdup frot f< + if nip nip j i rot fswap frot then fdrop + loop \ e.g. for 3.1419e search only between 3 and 4 + loop + + fdrop fdrop drop r> if negate then swap +; diff --git a/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur b/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur index baca41f3e5..4c77456e8b 100644 --- a/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur +++ b/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur @@ -11,7 +11,7 @@ val d = fn(var sec) { for seconds in [7259, 86400, 6000000] { val dur = d(seconds) write "{{seconds:7}} sec = " - writeln join(", ", for[=[]] k of dur[1] { + writeln join(for[=[]] k of dur[1] { if dur[2][k] != 0: _for ~= ["{{dur[2][k]}} {{dur[1][k]}}"] - }) + }, by=", ") } diff --git a/Task/Conways-Game-of-Life/Zig/conways-game-of-life.zig b/Task/Conways-Game-of-Life/Zig/conways-game-of-life.zig new file mode 100644 index 0000000000..524afe1ece --- /dev/null +++ b/Task/Conways-Game-of-Life/Zig/conways-game-of-life.zig @@ -0,0 +1,85 @@ +const std = @import("std"); +const mem = std.mem; + +pub fn main() !void { + // ---------------------------- pseudo random number generator + var prng = std.Random.DefaultPrng.init(blk: { + var seed: u64 = undefined; + std.posix.getrandom(mem.asBytes(&seed)) catch unreachable; + break :blk seed; + }); + const random = prng.random(); + // ---------------------------------------------------------- + const stdout = std.io.getStdOut(); + var bw = std.io.bufferedWriter(stdout.writer()); + const writer = bw.writer(); + // ---------------------------------------------------------- + var life = Life(80, 15).init(random); + for (0..300) |_| { + life.step(); + try writer.writeByte('\x0c'); + try writer.print("{}", .{life}); + try bw.flush(); + std.time.sleep(comptime (1_000_000_000 / 30)); // 1/30th second + } +} +fn Life(comptime w: usize, comptime h: usize) type { + return struct { + const Self = @This(); + a: Field(w, h), + b: Field(w, h), + + fn init(random: std.Random) Self { + var life = Self{ + .a = Field(w, h).init(), + .b = Field(w, h).init(), + }; + for (0..w * h / 2) |_| { + const x = random.uintLessThan(usize, w); + const y = random.uintLessThan(usize, h); + life.a.set(x, y, true); + } + return life; + } + fn step(self: *Self) void { + for (0..h) |y| + for (0..w) |x| + self.b.set(x, y, self.a.next(x, y)); + mem.swap(Field(w, h), &self.a, &self.b); + } + pub fn format(self: *const Self, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { + for (0..h) |y| { + for (0..w) |x| + try writer.writeByte(if (self.a.state(x, y)) '*' else ' '); + try writer.writeByte('\n'); + } + } + }; +} +fn Field(comptime w: usize, comptime h: usize) type { + return struct { + const Self = @This(); + s: std.StaticBitSet(w * h), + + fn init() Self { + return .{ .s = std.StaticBitSet(w * h).initEmpty() }; + } + fn set(self: *Self, x: usize, y: usize, b: bool) void { + self.s.setValue(y * w + x, b); + } + fn next(self: *const Self, x_: usize, y_: usize) bool { + var on: usize = 0; + // Use wraparound arithmetic, i.e. -% + inline for ([3]usize{ x_ -% 1, x_, x_ + 1 }) |x| + inline for ([3]usize{ y_ -% 1, y_, y_ + 1 }) |y| + if (self.state(x, y)) { + on += 1; + }; + return on == 3 or on == 2 and self.state(x_, y_); + } + fn state(self: *const Self, x: usize, y: usize) bool { + if (x >= w or y >= h) return false; + return self.s.isSet(y * w + x); + } + }; +} diff --git a/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 b/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 index 7f91645c39..10041191cb 100644 --- a/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 +++ b/Task/Copy-a-string/68000-Assembly/copy-a-string-2.68000 @@ -7,10 +7,7 @@ LEA myString,A3 LEA StringRam,A4 CopyString: -MOVE.B (A3)+,D0 -MOVE.B D0,(A4)+ ;we could have used "MOVE.B (A3)+,(A4)+" but this makes it easier to check for the terminator. -BEQ Terminated -BRA CopyString +MOVE.B (A3)+,(A4)+ ;Copy one byte. +BNE CopyString ;Not zero, do more bytes. -Terminated: ;the null terminator is already stored along with the string itself, so we are done. ;program ends here. diff --git a/Task/Count-in-octal/Go/count-in-octal-4.go b/Task/Count-in-octal/Go/count-in-octal-4.go index 6f7d6a6ce6..a38069db73 100644 --- a/Task/Count-in-octal/Go/count-in-octal-4.go +++ b/Task/Count-in-octal/Go/count-in-octal-4.go @@ -1,5 +1,6 @@ +package main import ( - "big" + "math/big" "fmt" ) diff --git a/Task/Count-in-octal/Zig/count-in-octal.zig b/Task/Count-in-octal/Zig/count-in-octal.zig index 59ece70ab3..ea4057cc52 100644 --- a/Task/Count-in-octal/Zig/count-in-octal.zig +++ b/Task/Count-in-octal/Zig/count-in-octal.zig @@ -1,13 +1,7 @@ const std = @import("std"); -const fmt = std.fmt; -const warn = std.debug.warn; pub fn main() void { - var i: u8 = 0; - var buf: [3]u8 = undefined; - - while (i < 255) : (i += 1) { - _ = fmt.formatIntBuf(buf[0..], i, 8, false, 0); // buffer, value, base, uppercase, width - warn("{}\n", buf); + for(0..255) |i| { + std.debug.print("{o}\n", .{i}); } } diff --git a/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur b/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur index 868b9d305f..8ce8e87c0b 100644 --- a/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur +++ b/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur @@ -1,2 +1,2 @@ -writeln len(indices("th", "the three truths")) -writeln len(indices("abab", "ababababab")) +writeln len(indices("the three truths", by="th")) +writeln len(indices("ababababab", by="abab")) diff --git a/Task/Count-occurrences-of-a-substring/M2000-Interpreter/count-occurrences-of-a-substring.m2000 b/Task/Count-occurrences-of-a-substring/M2000-Interpreter/count-occurrences-of-a-substring.m2000 new file mode 100644 index 0000000000..e95415b220 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/M2000-Interpreter/count-occurrences-of-a-substring.m2000 @@ -0,0 +1,15 @@ +module Count_occurrences_of_a_substring { + print @countSubstring("the three truths","th") '3 + print @countSubstring("ababababab","abab") '2 + function countSubstring(a$, b$) + local k=1, count + do + k=instr(a$, b$, k) + if k<1 then exit + count++ + k+=len(b$) + always + =count + end function +} +Count_occurrences_of_a_substring diff --git a/Task/Count-occurrences-of-a-substring/Zig/count-occurrences-of-a-substring.zig b/Task/Count-occurrences-of-a-substring/Zig/count-occurrences-of-a-substring.zig new file mode 100644 index 0000000000..103eb1c190 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Zig/count-occurrences-of-a-substring.zig @@ -0,0 +1,7 @@ +const std = @import("std"); + +pub fn main() void { + std.debug.print("{d}\n", .{ + std.mem.count(u8, "the three truths", "th") + }); +} diff --git a/Task/Cuban-primes/Quackery/cuban-primes.quackery b/Task/Cuban-primes/Quackery/cuban-primes.quackery new file mode 100644 index 0000000000..953bc53225 --- /dev/null +++ b/Task/Cuban-primes/Quackery/cuban-primes.quackery @@ -0,0 +1,24 @@ + say "The first 200 cuban primes:" + [] [] 1 + 0 temp put + [ 6 temp tally + temp share + + dup prime if + [ dup dip join ] + over size 200 = until ] + drop + witheach + [ number$ +commas nested join ] + 72 wrap$ + temp release + cr cr + say "The 100,000th cuban prime is " + 0 1 + 0 temp put + [ 6 temp tally + temp share + dup prime if + [ dip 1+ ] + over 100000 = until ] + nip number$ +commas echo$ + char . emit + temp release diff --git a/Task/Currying/M2000-Interpreter/currying-1.m2000 b/Task/Currying/M2000-Interpreter/currying-1.m2000 deleted file mode 100644 index fa7e6533d1..0000000000 --- a/Task/Currying/M2000-Interpreter/currying-1.m2000 +++ /dev/null @@ -1,42 +0,0 @@ -Module LikeGroovy { - divide=lambda (x, y)->x/y - partsof120=lambda divide ->divide(120, ![]) - Print "half of 120 is ";partsof120(2) - Print "a third is ";partsof120(3) - Print "and a quarter is ";partsof120(4) -} -LikeGroovy - -Module Joke { - \\ we can call F1(), with any number of arguments, and always read one and then - \\ call itself passing the remain arguments - \\ ![] take stack of values and place it in the next call. - F1=lambda -> { - if empty then exit - Read x - =x+lambda(![]) - } - - Print F1(F1(2),2,F1(-4))=0 - Print F1(-4,F1(2),2)=0 - Print F1(2, F1(F1(2),2))=F1(F1(F1(2),2),2) - Print F1(F1(F1(2),2),2)=6 - Print F1(2, F1(2, F1(2),2))=F1(F1(F1(2),2, F1(2)),2) - Print F1(F1(F1(2),2, F1(2)),2)=8 - Print F1(2, F1(10, F1(2, F1(2),2)))=F1(F1(F1(2),2, F1(2)),2, 10) - Print F1(F1(F1(2),2, F1(2)),2, 10)=18 - Print F1(2,2,2,2,10)=18 - Print F1()=0 - - Group F2 { - Sum=0 - Function Add (x){ - .Sum+=x - =x - } - } - Link F2.Add() to F2() - Print F1(F1(F1(F2(2)),F2(2), F1(F2(2))),F2(2))=8 - Print F2.Sum=8 -} -Joke diff --git a/Task/Currying/M2000-Interpreter/currying-2.m2000 b/Task/Currying/M2000-Interpreter/currying-2.m2000 deleted file mode 100644 index b8aaf91170..0000000000 --- a/Task/Currying/M2000-Interpreter/currying-2.m2000 +++ /dev/null @@ -1,26 +0,0 @@ -Module Puzzle { - Global Group F2 { - Sum=0 - Sum2=0 - Function Add (x){ - .Sum+=x - =x - } - } - F1=lambda -> { - if empty then exit - Read x - Print ">>>", F2.Sum - F2.Sum2++ ' add one each time we read x - =x+lambda(![]) - } - Link F2.Add() to F2() - P=F1(F1(F1(F2(2)),F2(2), F1(F2(2))),F2(2))=8 - Print F2.Sum=8 - Print F2.Sum2=7 - \\ We read 7 times x, but we get 8, 2+2+2+2 - \\ So 3 times x was zero, or not? - \\ but where we pass zero? - \\ zero return from F1 if no argument pass, so how x get zero?? -} -Puzzle diff --git a/Task/Currying/M2000-Interpreter/currying.m2000 b/Task/Currying/M2000-Interpreter/currying.m2000 new file mode 100644 index 0000000000..11e0feb542 --- /dev/null +++ b/Task/Currying/M2000-Interpreter/currying.m2000 @@ -0,0 +1,59 @@ +Module LikeGroovy { + divide=lambda (x, y)->x/y + Curry=lambda (f as lambda, k)->(lambda f, k ->(f(k,![]))) + partsof120=Curry(divide, 120) + Print "half of 120 is ";partsof120(2) + Print "a third is ";partsof120(3) + Print "and a quarter is ";partsof120(4) + + joinTwoWordsWithSymbol=lambda (s, a, b)->a+s+b + Assert joinTwoWordsWithSymbol("#","Hello", "World")="Hello#World" + concatWords =Curry(joinTwoWordsWithSymbol, " ") + Assert concatWords("Hello", "World")="Hello World" + prependHello =Curry(concatWords, "Hello") + Assert prependHello("World")="Hello World" + Print "done" +} +LikeGroovy +Module M2000way { + class curry{ + private: + p=stack ' stack of values + func$ ' field for the weak reference + public: + property counter {value } ' readonly + class: + module curry(.func$) { + .p<=[] + class value { + value () { + ' symbol ! used for feeding stack of values from arrays or stacks. + ' [] is the current stack (leave emtpy stack as current stack) + ' Stack(.p) make a copy of .p (which have a stack object) + =function(.func$, !stack(.p), ![]) + .[counter]++ + } + } + this=value() ' make this as a property + } + } + ' using a general function + Function Divide(a, b) { + =a/b + } + Print "Divide(10, 6) is ";Divide(10, 5) + partsof120=Curry(&Divide(), 120) + Print "half of 120 is ";partsof120(2) + Print "a third is ";partsof120(3) + Print "and a quarter is ";partsof120(4) + Print "Use of partsof120 so far: "; partsof120.counter; " times" + ' using a lambda function + joinTwoWordsWithSymbol=lambda (s, a, b)->a+s+b + Assert joinTwoWordsWithSymbol("#","Hello", "World")="Hello#World" + concatWords =Curry(&joinTwoWordsWithSymbol, " ") + Assert concatWords("Hello", "World")="Hello World" + prependHello =Curry(&concatWords, "Hello") + Assert prependHello("World")="Hello World" + Print "done" +} +M2000way diff --git a/Task/Cyclops-numbers/REXX/cyclops-numbers-1.rexx b/Task/Cyclops-numbers/REXX/cyclops-numbers-1.rexx deleted file mode 100644 index bc1ab73571..0000000000 --- a/Task/Cyclops-numbers/REXX/cyclops-numbers-1.rexx +++ /dev/null @@ -1,55 +0,0 @@ -/*REXX pgm finds 1st N cyclops (Θ) #s, Θ primes, blind Θ primes, palindromic Θ primes*/ -parse arg n cols . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ -if cols=='' | cols=="," then cols= 10 /* " " " " " " */ -call genP /*build array of semaphores for primes.*/ -w= max(10, length( commas(@.#) ) ) /*max width of a number in any column. */ -pri?= 0; bli?= 0; pal?= 0; call 0 ' first ' commas(n) " cyclops numbers" -pri?= 1; bli?= 0; pal?= 0; call 0 ' first ' commas(n) " prime cyclops numbers" -pri?= 1; bli?= 1; pal?= 0; call 0 ' first ' commas(n) " blind prime cyclops numbers" -pri?= 1; bli?= 0; pal?= 1; call 0 ' first ' commas(n) " palindromic prime cyclops numbers" -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -/*──────────────────────────────────────────────────────────────────────────────────────*/ -0: parse arg title; idx= 1 /*get the title of this output section.*/ - say ' index │'center(title, 1 + cols*(w+1) ) /*display the output title. */ - say '───────┼'center("" , 1 + cols*(w+1), '─') /* " " " separator*/ - finds= 0; $= /*the number of finds (so far); $ list.*/ - do j=0 until finds== n; L= length(j) /*find N cyclops numbers, start at 101.*/ - if L//2==0 then do; j= left(1, L+1, 0) /*Is J an even # of digits? Yes, bump J*/ - iterate /*use a new J that has odd # of digits.*/ - end - z= pos(0, j); if z\==(L+1)%2 then iterate /* " " " " (zero in mid)? " */ - if pos(0, j, z+1)>0 then iterate /* " " " " (has two 0's)? " */ - if pri? then if \!.j then iterate /*Need a cyclops prime? Then skip.*/ - if bli? then do; ?= space(translate(j, , 0), 0) /*Need a blind cyclops prime ?*/ - if \!.? then iterate /*Not a blind cyclops prime? Then skip.*/ - end - if pal? then do; r= reverse(j) /*Need a palindromic cyclops prime? */ - if r\==j then iterate /*Cyclops number not palindromic? Skip.*/ - if \!.r then iterate /* " palindrome not prime? " */ - end - finds= finds + 1 /*bump the number of palindromic primes*/ - $= $ right( commas(j), w) /*add a palindromic prime ──► $ list.*/ - if finds//cols\==0 then iterate /*have we populated a line of output? */ - say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */ - idx= idx + cols /*bump the index count for the output*/ - end /*j*/ - if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible show residual output.*/ - say '───────┴'center("" , 1 + cols*(w+1), '─'); say - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: !.= 0; hip= 7890987 - 1 /*placeholders for primes (semaphores).*/ - @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*define some low primes. */ - !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1 /* " " " " flags. */ - #= 6; sq.#= @.# ** 2 /*number of primes so far; prime square*/ - do j=@.#+2 by 2 for max(0, hip%2-@.#%2-1) /*find odd primes from here on. */ - parse var j '' -1 _ /*get the last dec. digit of J.*/ - if _==5 then iterate; if j// 3==0 then iterate /*÷ by 5? ÷ by 3? Skip.*/ - if j// 7==0 then iterate; if j//11==0 then iterate /*÷ " 7? ÷ by 11? " */ - do k=6 while sq.k<=j /* [↓] divide by the known odd primes.*/ - if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # Ps; assign next P; P sq; P# */ - end /*j*/; return diff --git a/Task/Cyclops-numbers/REXX/cyclops-numbers-2.rexx b/Task/Cyclops-numbers/REXX/cyclops-numbers.rexx similarity index 100% rename from Task/Cyclops-numbers/REXX/cyclops-numbers-2.rexx rename to Task/Cyclops-numbers/REXX/cyclops-numbers.rexx diff --git a/Task/Cyclotomic-polynomial/FreeBASIC/cyclotomic-polynomial.basic b/Task/Cyclotomic-polynomial/FreeBASIC/cyclotomic-polynomial.basic new file mode 100644 index 0000000000..9c96e1eb57 --- /dev/null +++ b/Task/Cyclotomic-polynomial/FreeBASIC/cyclotomic-polynomial.basic @@ -0,0 +1,137 @@ +#include "isprime.bas" + +Type IntArray + Dim values(Any) As Integer + Dim length As Integer +End Type + +Function distinctPrimeFactors(n As Integer) As IntArray + Dim result As IntArray + Redim result.values(0) + result.length = 0 + + For i As Integer = 2 To n + If n Mod i = 0 Andalso isPrime(i) Then + result.length += 1 + Redim Preserve result.values(result.length - 1) + result.values(result.length - 1) = i + While n Mod i = 0 + n \= i + Wend + End If + Next + Return result +End Function + +Function substituteExponent(polynomial As IntArray, exponent As Integer) As IntArray + Dim result As IntArray + result.length = exponent * (polynomial.length - 1) + 1 + Redim result.values(result.length - 1) + + For i As Integer = polynomial.length - 1 To 0 Step -1 + result.values(i * exponent) = polynomial.values(i) + Next + + Return result +End Function + +Function exactDivision(dividend As IntArray, divisor As IntArray) As IntArray + Dim As Integer i, j + Dim result As IntArray + result.length = dividend.length - divisor.length + 1 + Redim result.values(result.length - 1) + + Dim temp(dividend.length - 1) As Integer + For i = 0 To dividend.length - 1 + temp(i) = dividend.values(i) + Next + + For i = 0 To dividend.length - divisor.length + result.values(i) = temp(i) + If temp(i) <> 0 Then + For j = 1 To divisor.length - 1 + temp(i + j) -= divisor.values(j) * temp(i) + Next + End If + Next + + Return result +End Function + +Function cycloPoly(cpIndex As Integer) As IntArray + Dim i As Integer + Dim polynomial As IntArray + polynomial.length = 2 + Redim polynomial.values(1) + polynomial.values(0) = 1 + polynomial.values(1) = -1 + + If cpIndex = 1 Then Return polynomial + + If isPrime(cpIndex) Then + Dim result As IntArray + result.length = cpIndex + Redim result.values(cpIndex - 1) + For i = 0 To cpIndex - 1 + result.values(i) = 1 + Next + Return result + End If + + Dim primes As IntArray = distinctPrimeFactors(cpIndex) + Dim product As Integer = 1 + + For i = 0 To primes.length - 1 + Dim numerator As IntArray = substituteExponent(polynomial, primes.values(i)) + polynomial = exactDivision(numerator, polynomial) + product *= primes.values(i) + Next + + Return substituteExponent(polynomial, cpIndex \ product) +End Function + +Function hasHeight(polynomial As IntArray, coefficient As Integer) As Boolean + For i As Integer = 0 To (polynomial.length + 1) \ 2 - 1 + If Abs(polynomial.values(i)) = coefficient Then Return True + Next + Return False +End Function + +' Main program +Print "Task 1: Cyclotomic polynomials for n <= 30:" +Print "CP( 1) = x - 1" + +For cpIndex As Integer = 2 To 30 + Print Using "CP(##) = "; cpIndex; + Dim poly As IntArray = cycloPoly(cpIndex) + + Dim first As Boolean = True + For i As Integer = poly.length - 1 To 0 Step -1 + If poly.values(i) <> 0 Then + If Not first Then Print Iif(poly.values(i) > 0, " + ", " "); + If poly.values(i) <> 1 Or i = 0 Then + Print Iif(poly.values(i) = -1 And i > 0, "- ", Str(poly.values(i))); + End If + + If i > 0 Then + Print "x"; + If i > 1 Then Print "^" & i; + End If + first = False + End If + Next + Print +Next + +Print !"\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:" +Print "CP( 1) has a coefficient with magnitude 1" + +Dim cpIndex As Integer = 2 +For coeff As Integer = 2 To 10 + While isPrime(cpIndex) Or Not hasHeight(cycloPoly(cpIndex), coeff) + cpIndex += 1 + Wend + Print Using "CP(#####) has a coefficient with magnitude &"; cpIndex; coeff +Next + +Sleep diff --git a/Task/DNS-query/Wren/dns-query-1.wren b/Task/DNS-query/Wren/dns-query-1.wren deleted file mode 100644 index 728593ed2b..0000000000 --- a/Task/DNS-query/Wren/dns-query-1.wren +++ /dev/null @@ -1,9 +0,0 @@ -/* DNS_query.wren */ - -class Net { - foreign static lookupHost(host) -} - -var host = "orange.kame.net" -var addrs = Net.lookupHost(host).split(", ") -System.print(addrs.join("\n")) diff --git a/Task/DNS-query/Wren/dns-query-2.wren b/Task/DNS-query/Wren/dns-query-2.wren deleted file mode 100644 index 266b61a3c3..0000000000 --- a/Task/DNS-query/Wren/dns-query-2.wren +++ /dev/null @@ -1,31 +0,0 @@ -/* go run DNS_query.go */ - -package main - -import( - wren "github.com/crazyinfin8/WrenGo" - "net" - "strings" -) - -type any = interface{} - -func lookupHost(vm *wren.VM, parameters []any) (any, error) { - host := parameters[1].(string) - addrs, err := net.LookupHost(host) - if err != nil { - return nil, nil - } - return strings.Join(addrs, ", "), nil -} - -func main() { - vm := wren.NewVM() - fileName := "DNS_query.wren" - methodMap := wren.MethodMap{"static lookupHost(_)": lookupHost} - classMap := wren.ClassMap{"Net": wren.NewClass(nil, nil, methodMap)} - module := wren.NewModule(classMap) - vm.SetModule(fileName, module) - vm.InterpretFile(fileName) - vm.Free() -} diff --git a/Task/DNS-query/Wren/dns-query.wren b/Task/DNS-query/Wren/dns-query.wren new file mode 100644 index 0000000000..e2ce79fd16 --- /dev/null +++ b/Task/DNS-query/Wren/dns-query.wren @@ -0,0 +1,18 @@ +import "os" for Process + +var domainName = "www.kame.net" +System.print(domainName) +var ipvs = ["IPv4", "IPv6"] +var args = ["A", "AAAA"] +for (i in 0..1) { + var cmd = "nslookup -querytype=%(args[i]) %(domainName)" + var lines = Process.read(cmd).split("\n") + var addresses = [] + for (line in lines.skip(3)) { + if (line.startsWith("Address:")) { + var address = line[8..-1].trim() + addresses.add(address) + } + } + for (address in addresses) System.print("%(ipvs[i]): %(address)") +} diff --git a/Task/Date-format/Langur/date-format-1.langur b/Task/Date-format/Langur/date-format-1.langur index 9375725f6a..48c2cf95d3 100644 --- a/Task/Date-format/Langur/date-format-1.langur +++ b/Task/Date-format/Langur/date-format-1.langur @@ -1,2 +1,2 @@ -writeln string(dt//, "2006-01-02") -writeln string(dt//, "Monday, January 2, 2006") +writeln string(dt//, fmt="2006-01-02") +writeln string(dt//, fmt="Monday, January 2, 2006") diff --git a/Task/Date-manipulation/Langur/date-manipulation.langur b/Task/Date-manipulation/Langur/date-manipulation.langur index d25c9c940e..674403c0ae 100644 --- a/Task/Date-manipulation/Langur/date-manipulation.langur +++ b/Task/Date-manipulation/Langur/date-manipulation.langur @@ -2,13 +2,13 @@ val input = "March 7 2009 7:30pm -05:00" val iformat = "January 2 2006 3:04pm -07:00" val oformat = "January 2 2006 3:04pm MST" -val d1 = datetime(input, iformat) +val d1 = datetime(input, fmt=iformat) val d2 = d1 + dr/T12h/ -val d3 = datetime(d2, "US/Arizona") -val d4 = datetime(d2, zls) -val d5 = datetime(d2, "Z") -val d6 = datetime(d2, "+02:30") -val d7 = datetime(d2, "EST") +val d3 = datetime(d2, fmt="US/Arizona") +val d4 = datetime(d2, fmt=zls) +val d5 = datetime(d2, fmt="Z") +val d6 = datetime(d2, fmt="+02:30") +val d7 = datetime(d2, fmt="EST") writeln "input string: ", input writeln "input format string: ", iformat diff --git a/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 b/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 new file mode 100644 index 0000000000..6c81a3e2b7 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 @@ -0,0 +1,45 @@ +Module FreeCellDeal { + deal = lambda ->{ + ms_lcg = lambda ms_state=0# (seed As currency = -1) ->{ + If seed <> -1 Then + ms_state = seed Mod 2 ^ 31 + Else + ms_state = (214013 * ms_state + 2531011) Mod 2 ^ 31 + End If + = binary.shift(ms_state, -16) + } + fillbytes = lambda n=0ud ->{=n:n++} + dim cards(52) as byte< { + call void ms_lcg(game) + dim ncards() + ncards()=cards() + for i = 51 to 0 + c = ms_lcg() Mod (i +1) + Swap ncards(i), ncards(c) + next + =ncards() + } + }() ' execute now + dim dealcards() + string suit = "CDHS", value = "A23456789TJQK" + aList=(1, 617) + nList=each(alist) + while nList + Print "Game:"+array(nList) + dealcards() = deal(array(nlist)) + CardDis$ = lambda$ dealcards(), suit, value (c)-> { + s = dealcards(51 - c) Mod 4 + 1 + v = dealcards(51 - c) div 4 + 1 + =Mid$(value,v, 1)+Mid$(suit,s, 1) + } + c=0 + Do + Print CardDis$(c); + if c mod 8 < 7 then ? " "; Else ? + c++ + until c>51 + ? : ? + end while +} +FreeCellDeal diff --git a/Task/Death-Star/FreeBASIC/death-star.basic b/Task/Death-Star/FreeBASIC/death-star-1.basic similarity index 100% rename from Task/Death-Star/FreeBASIC/death-star.basic rename to Task/Death-Star/FreeBASIC/death-star-1.basic diff --git a/Task/Death-Star/FreeBASIC/death-star-2.basic b/Task/Death-Star/FreeBASIC/death-star-2.basic new file mode 100644 index 0000000000..008d4ea2d0 --- /dev/null +++ b/Task/Death-Star/FreeBASIC/death-star-2.basic @@ -0,0 +1,100 @@ +Type vector + v(2) As Double +End Type + +Type sphere + cx As Integer + cy As Integer + cz As Integer + r As Integer +End Type + +Function dot(x As vector, y As vector) As Double + Return x.v(0)*y.v(0) + x.v(1)*y.v(1) + x.v(2)*y.v(2) +End Function + +Sub normalizeVector(v As vector) + Dim invLen As Double = 1.0 / Sqr(dot(v, v)) + v.v(0) *= invLen + v.v(1) *= invLen + v.v(2) *= invLen +End Sub + +Function hitSphere(s As sphere, x As Integer, y As Integer, z1 As Double Ptr, z2 As Double Ptr) As Boolean + Dim xx As Integer = x - s.cx + Dim yy As Integer = y - s.cy + Dim zsq As Integer = s.r*s.r - (xx*xx + yy*yy) + + If zsq >= 0 Then + Dim zsqrt As Double = Sqr(zsq) + *z1 = s.cz - zsqrt + *z2 = s.cz + zsqrt + Return True + End If + Return False +End Function + +Function createDeathStar(posic As sphere, neg As sphere, k As Double, amb As Double, direc As vector) As Any Ptr + Dim As Integer w = posic.r * 4 + Dim As Integer h = posic.r * 3 + + Dim As Any Ptr img = Imagecreate(w, h, Rgb(0,0,0)) + + Dim vec As vector + Dim As Double z1, z2, zs1, zs2 + + For y As Integer = posic.cy - posic.r To posic.cy + posic.r + For x As Integer = posic.cx - posic.r To posic.cx + posic.r + If hitSphere(posic, x, y, @z1, @z2) Then + Dim hit As Boolean = hitSphere(neg, x, y, @zs1, @zs2) + + If hit Then + If zs1 > z1 Then hit = False + If zs2 > z2 Then Continue For + End If + + If hit Then + vec.v(0) = neg.cx - x + vec.v(1) = neg.cy - y + vec.v(2) = neg.cz - zs2 + Else + vec.v(0) = x - posic.cx + vec.v(1) = y - posic.cy + vec.v(2) = z1 - posic.cz + End If + + normalizeVector(vec) + Dim s As Double = dot(direc, vec) + If s < 0 Then s = 0 + + Dim lum As Double = 255 * (s^k + amb) / (1 + amb) + If lum < 0 Then lum = 0 + If lum > 255 Then lum = 255 + + Dim shade As Integer = lum + Pset img, (x + w\2, y + h\2), Rgb(shade, shade, shade) + End If + Next x + Next y + + Return img +End Function + +' Main program +Screenres 500, 400, 32 +Windowtitle "Death Star FreeBASIC" + +Dim direct As vector +direct.v(0) = 20 +direct.v(1) = -40 +direct.v(2) = -10 +normalizeVector(direct) + +Dim posic As sphere = Type(0, 0, 0, 120) +Dim neg As sphere = Type(-50, -50, -30, 75) + +Dim img As Any Ptr = createDeathStar(posic, neg, 1.5, 0.2, direct) +Put (0, 0), img +Imagedestroy(img) + +Sleep diff --git a/Task/Death-Star/FutureBasic/death-star-1.basic b/Task/Death-Star/FutureBasic/death-star-1.basic new file mode 100644 index 0000000000..b46ca64359 --- /dev/null +++ b/Task/Death-Star/FutureBasic/death-star-1.basic @@ -0,0 +1,86 @@ +_window = 1 +begin enum 1 + _circularView + _OvalView +end enum + +void local fn BuildWindow + CGRect r = fn CGRectMake( 0, 0, 400, 400 ) + window _window, @"Rosetta Code Death Star", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable + WindowSetBackgroundColor( _window, fn ColorBlack ) + + r = fn CGRectMake( 20, 20, 360, 360 ) + subclass view _circularView, r, _window + + r = fn CGRectMake( 50, 170, 200, 180 ) + subclass view _OvalView,r, _circularView +end fn + +local fn OvalView( tag as NSInteger ) + CGRect r = fn ViewBounds( tag ) + ViewSetWantsLayer( tag, YES ) + CFArrayRef cols = @[fn ColorWithRGB(0.125,0.125,0.125,1),fn ColorWithRGB(0.425,0.425,0.4425,1),fn ColorWithRGB(0.725,0.725,0.725,1),fn ColorWithRGB(0.925,0.925,0.925,1),fn ColorWhite,fn ColorWhite ] + + CALayerRef layer = fn CALayerInit + ViewSetLayer( tag, layer ) + CALayerSetCornerRadius( layer, r.size.height / 2.0 ) + CALayerSetMasksToBounds( layer, YES ) + CALayerSetBorderWidth( layer, 0.25 ) + CALayerSetBorderColor( layer, fn ColorBlue ) + + CAGradientLayerRef gradLayer = fn CAGradientLayerInit + CAGradientLayerSetColors( gradLayer, cols ) + CALayerSetCornerRadius( gradLayer, r.size.Height / 2.0 ) + CAGradientLayerSetStartPoint( gradLayer, fn CGPointMake(1,0) ) + CAGradientLayerSetEndPoint( gradLayer, fn CGPointMake(0,1) ) + CALayerSetShadowOffset( gradLayer, fn CGSizeMake( 10, -10 ) ) + CALayerSetShadowRadius( gradLayer, 3.0 ) + CALayerSetShadowOpacity( gradLayer, 0.4 ) + CALayerSetFrame( gradLayer, fn CGRectMake(0,0,200,200) ) + + CALayerAddSublayer( layer, gradLayer ) +end fn + +local fn CircularView( tag as NSinteger ) + CGRect r = fn ViewBounds( tag ) + ViewSetWantsLayer( tag, YES ) + CFArrayRef cols = @[fn ColorWithRGB(0.125,0.125,0.125,1),fn ColorWithRGB(0.425,0.425,0.4425,1),fn ColorWithRGB(0.725,0.725,0.725,1),fn ColorWithRGB(0.925,0.925,0.925,1),fn ColorWhite,fn ColorWhite ] + CALayerRef layer = fn CALayerInit + + ViewSetLayer( tag, layer ) + CALayerSetCornerRadius( layer, r.size.width / 2.0 ) + CALayerSetMasksToBounds( layer, YES ) + CALayerSetBorderWidth( layer, 0.25 ) + CALayerSetBorderColor( layer, fn ColorBlack ) + + CAGradientLayerRef gradLayer = fn CAGradientLayerInit + CALayerSetCornerRadius( gradLayer, r.size.width / 2.0 ) + CAGradientLayerSetColors( gradLayer, cols ) + CAGradientLayerSetStartPoint( gradLayer, fn CGPointMake( 0,0.2 ) ) + CAGradientLayerSetEndPoint( gradLayer, fn CGPointMake( 1,1 ) ) + CALayerSetShadowOffset( gradLayer, fn CGSizeMake( 10, -10 ) ) + CALayerSetShadowRadius( gradLayer, 3.0 ) + CALayerSetShadowOpacity( gradLayer, 0.4 ) + CALayerSetFrame( gradLayer, fn CGRectMake(0,0,360,360) ) + CALayerAddSublayer( layer, gradLayer ) +end fn + + +void local fn DoDialog( ev as long, tag as long, wnd as long ) + select ( ev ) + case _viewDrawRect + select ( tag ) + case _circularView : fn CircularView( tag ) + + case _OvalView : fn OvalView( tag) + + end select + case _windowWillClose : end + end select +end fn + +on dialog fn DoDialog + +fn BuildWindow + +HandleEvents diff --git a/Task/Death-Star/FutureBasic/death-star-2.basic b/Task/Death-Star/FutureBasic/death-star-2.basic new file mode 100644 index 0000000000..18d86f6adf --- /dev/null +++ b/Task/Death-Star/FutureBasic/death-star-2.basic @@ -0,0 +1,60 @@ +_window = 1 +begin enum 1 + _circularView + _ovalView +end enum + +void local fn BuildWindow + CGRect r = fn CGRectMake( 0, 0, 400, 400 ) + + window _window, @"Death Star", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable + WindowSetBackgroundColor( _window, fn ColorBlack ) + + r = fn CGRectMake( 20, 20, 360, 360 ) + subclass view _circularView, r + + r = fn CGRectMake( 0, 120, 200, 200 ) + subclass view _ovalView, r +end fn + +local fn OvalView( tag as NSInteger ) + CGRect r = fn ViewBounds( tag ) + r.size.height *= 0.5 + CFArrayRef cols = @[fn ColorWithWhite(0.8,1),fn ColorBlack] + BezierPathRef path = fn BezierPathWithOvalInRect( r ) + GradientRef grad = fn GradientWithColors( cols ) + GraphicsContextSaveGraphicsState + AffineTransformRef tx = fn AffineTransformInit + NSPoint center = fn CGPointMake( fn CGRectGetMidX(r), fn CGRectGetMidY(r)) + center.x -= 25 + AffineTransformTranslate( tx, center.x, center.y ) + AffineTransformRotateByDegrees( tx, 52 ) + AffineTransformConcat( tx ) + GradientDrawInBezierPath( grad, path, 0.0 ) + GraphicsContextRestoreGraphicsState +end fn + +local fn CircularView( tag as NSinteger ) + CGRect r = fn ViewBounds( tag ) + CFArrayRef cols = @[fn ColorWithWhite(0.1,1),fn ColorWhite] + BezierPathRef path = fn BezierPathWithOvalInRect( r ) + GradientRef grad = fn GradientWithColors( cols ) + GradientDrawInBezierPath( grad, path, 0.0 ) +end fn + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _viewDrawRect + select ( tag ) + case _circularView : fn CircularView( tag ) + case _ovalView : fn OvalView( tag) + end select + case _windowWillClose : end + end select +end fn + +on dialog fn DoDialog + +fn BuildWindow + +HandleEvents diff --git a/Task/Deceptive-numbers/Forth/deceptive-numbers.fth b/Task/Deceptive-numbers/Forth/deceptive-numbers.fth new file mode 100644 index 0000000000..a3289a799e --- /dev/null +++ b/Task/Deceptive-numbers/Forth/deceptive-numbers.fth @@ -0,0 +1,44 @@ +: modpow { c b a -- a^b mod c } + c 1 = if 0 exit then + 1 + a c mod to a + begin + b 0> + while + b 1 and 1 = if + a * c mod + then + a a * c mod to a + b 2/ to b + repeat ; + +: deceptive? ( n -- ? ) + dup 2 mod 0= if drop false exit then + dup 3 mod 0= if drop false exit then + dup 5 mod 0= if drop false exit then + dup dup 1- 10 modpow 1 <> if drop false exit then + 7 begin + 2dup dup * > + while + 2dup mod 0= if 2drop true exit then + 4 + + 2dup mod 0= if 2drop true exit then + 2 + + repeat + 2drop false ; + +: main ( -- ) + 0 7 begin + over 100 < + while + dup deceptive? if + dup 6 .r + swap 1+ swap + over 10 mod 0= if cr else space then + then + 1+ + repeat + 2drop ; + +main +bye diff --git a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur index acba2f2f8c..615ec14669 100644 --- a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur +++ b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur @@ -1,6 +1,6 @@ val isPrime = fn(i) { i == 2 or i > 2 and - not any(fn x: i div x, pseries(2 .. i ^/ 2)) + not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x) } var nums = [] diff --git a/Task/Deconvolution-2D+/C++/deconvolution-2d+.cpp b/Task/Deconvolution-2D+/C++/deconvolution-2d+.cpp index 50449ee68e..04e6133754 100644 --- a/Task/Deconvolution-2D+/C++/deconvolution-2d+.cpp +++ b/Task/Deconvolution-2D+/C++/deconvolution-2d+.cpp @@ -6,30 +6,6 @@ #include #include -std::complex add(const std::complex& c1, const std::complex& c2) { - return std::complex(c1.real() + c2.real(), c1.imag() + c2.imag()); -} - -std::complex subtract(const std::complex& c1, const std::complex& c2) { - return std::complex(c1.real() - c2.real(), c1.imag() - c2.imag()); -} - -std::complex multiply(const std::complex& c1, const std::complex& c2) { - return std::complex(c1.real() * c2.real() - c1.imag() * c2.imag(), - c1.imag() * c2.real() + c1.real() * c2.imag()); -} - -std::complex divide(const std::complex& complex, const int32_t& n) { - return std::complex(complex.real() / n, complex.imag() / n); -} - -std::complex divide(const std::complex& c1, const std::complex& c2) { - const double rr = c1.real() * c2.real() + c1.imag() * c2.imag(); - const double ii = c1.imag() * c2.real() - c1.real() * c2.imag(); - const double norm = c2.real() *c2.real() + c2.imag() * c2.imag(); - return std::complex(rr / norm, ii / norm); -} - struct Return_Value { int32_t power_of_two; std::vector> list; @@ -62,7 +38,7 @@ void print_3D_vector(const std::vector>>& lists) { print_2D_vector(lists.back()); std::cout << "]" << std::endl; } -Return_Value padAndComplexify(const std::vector& list, const int32_t& power_of_two) { +Return_Value pad_and_complexify(const std::vector& list, const int32_t& power_of_two) { const int32_t padded_vector_size = ( power_of_two == 0 ) ? 1 << static_cast(std::ceil(std::log(list.size()) / std::log(2))) : power_of_two; std::vector> padded_vector(padded_vector_size, std::complex(0.0, 0.0)); @@ -134,10 +110,9 @@ void fft(std::vector>& deconvolution1D, std::vector t = multiply( - std::complex(std::cos(theta), std::sin(theta)), result[j + step + start]); - deconvolution1D[( j / 2 ) + start] = add(result[j + start], t); - deconvolution1D[( ( j + power_of_two ) / 2 ) + start] = subtract(result[j + start], t); + std::complex t = std::complex(std::cos(theta), std::sin(theta)) * result[j + step + start]; + deconvolution1D[( j / 2 ) + start] = result[j + start] + t; + deconvolution1D[( ( j + power_of_two ) / 2 ) + start] = result[j + start] - t; } } } @@ -155,9 +130,9 @@ std::vector deconvolution(const std::vector& convolved, const const int32_t& convolved_row_size, const int32_t& remain_size) { int32_t power_of_two = 0; - Return_Value convoluted_result = padAndComplexify(convolved, power_of_two); + Return_Value convoluted_result = pad_and_complexify(convolved, power_of_two); std::vector> convoluted_padded = convoluted_result.list; - Return_Value remove_result = padAndComplexify(remove, convoluted_result.power_of_two); + Return_Value remove_result = pad_and_complexify(remove, convoluted_result.power_of_two); std::vector> remove_padded = remove_result.list; power_of_two = remove_result.power_of_two; @@ -165,7 +140,7 @@ std::vector deconvolution(const std::vector& convolved, const fft(remove_padded, power_of_two); std::vector> quotient(power_of_two, std::complex(0.0, 0.0)); for ( int32_t i = 0; i < power_of_two; ++i ) { - quotient[i] = divide(convoluted_padded[i], remove_padded[i]); + quotient[i] = convoluted_padded[i] / remove_padded[i]; } fft(quotient, power_of_two); @@ -178,8 +153,8 @@ std::vector deconvolution(const std::vector& convolved, const std::vector remain_vector(remain_size, 0); int32_t i = 0; while ( i > remove_size - convolved_size - convolved_row_size ) { - remain_vector[-i] = std::lround( - divide(quotient[( i + power_of_two ) % power_of_two], 32.0).real()); + remain_vector[-i] = std::lround(( + quotient[( i + power_of_two ) % power_of_two] / std::complex(32.0, 0.0)).real()); i -= 1; } return remain_vector; diff --git a/Task/Delegates/EMal/delegates.emal b/Task/Delegates/EMal/delegates.emal new file mode 100644 index 0000000000..fbe738a0a4 --- /dev/null +++ b/Task/Delegates/EMal/delegates.emal @@ -0,0 +1,25 @@ +type Thingable +interface + fun thing ← text by block do end +end +type Delegate implements Thingable +model + fun thing ← text by block + return "delegate implementation" + end +end +type Delegator +model + Thingable delegate + fun operation ← <|when(me.delegate æ null, "default implementation", me.delegate.thing()) +end +fun byDelegate ← Delegator by Thingable delegate + var delegator ← Delegator() + delegator.delegate ← delegate + return delegator +end +type Main +Delegator a ← Delegator() +writeLine(a.operation()) +Delegator b ← Delegator.byDelegate(Delegate()) +writeLine(b.operation()) diff --git a/Task/Descending-primes/Scala/descending-primes.scala b/Task/Descending-primes/Scala/descending-primes.scala new file mode 100644 index 0000000000..cad06bbd50 --- /dev/null +++ b/Task/Descending-primes/Scala/descending-primes.scala @@ -0,0 +1,42 @@ +def isPrime(n: Long): Boolean = { + @annotation.tailrec + def hasDivisor(f: Long): Boolean = + if (f * f > n) false + else if (n % f == 0 || n % (f + 2) == 0) true + else hasDivisor(f + 6) + + if (n < 2) false + else if (n == 2 || n == 3) true + else if (n % 2 == 0 || n % 3 == 0) false + else { + !hasDivisor(5) + } +} + +def descendingPrimes(): Seq[Int] = { + val digits = Seq(9, 8, 7, 6, 5, 4, 3, 2, 1) + + val (_, primes) = digits.foldLeft((Seq(0), Seq.empty[Int])) { case ((candidates, primes), digit) => + val newCandidates = candidates.map(_ * 10 + digit) + val newPrimes = primes ++ newCandidates.filter(isPrime) + (candidates ++ newCandidates, newPrimes) + } + + primes.sorted +} + +@main def main(): Unit = { + def test(): Unit = { + val primes = descendingPrimes() + + val maxDigits = primes.map(_.toString.length).max + val columnsPerLine = 8 + val groupedPrimes = primes.grouped(columnsPerLine) + groupedPrimes.foreach { group => + val formattedGroup = group.map(p => String.format(s"%${maxDigits}d", Int.box(p))).mkString(" ") + println(formattedGroup) + } + } + + test() +} diff --git a/Task/Determinant-and-permanent/00-TASK.txt b/Task/Determinant-and-permanent/00-TASK.txt index 7359865431..cce4a54788 100644 --- a/Task/Determinant-and-permanent/00-TASK.txt +++ b/Task/Determinant-and-permanent/00-TASK.txt @@ -8,7 +8,6 @@ In both cases the sum is over the permutations \sigma of the permut More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. - ;Related task: * [[Permutations by swapping]]

diff --git a/Task/Determinant-and-permanent/ALGOL-68/determinant-and-permanent.alg b/Task/Determinant-and-permanent/ALGOL-68/determinant-and-permanent.alg new file mode 100644 index 0000000000..c25b5c3420 --- /dev/null +++ b/Task/Determinant-and-permanent/ALGOL-68/determinant-and-permanent.alg @@ -0,0 +1,84 @@ +BEGIN # matrix determinant and permanent # + # - translated from the Phix sample, via EasyLang # + + MODE NUMBER = REAL; # type of matrix elements to be handled # + # adjust to suit, if necessary # + + PROC minor = ( [,]NUMBER a, INT x, y )[,]NUMBER: + BEGIN + [ 1 LWB a : 1 UPB a - 1, 2 LWB a : 2 UPB a - 1 ]NUMBER r; + FOR i FROM 1 LWB a TO 1 UPB a - 1 DO + FOR j FROM 2 LWB a TO 2 UPB a - 1 DO + r[ i, j ] := a[ i + ABS ( i >= x ), j + ABS ( j >= y ) ] + OD + OD; + r + END # minor # ; + + PROC det = ( [,]NUMBER a )NUMBER: + IF 1 UPB a = 1 LWB a THEN # only one NUMBER # + a[ 1 LWB a, 2 LWB a ] + ELSE + INT sgn := 1; + NUMBER res := 0; + FOR i FROM 2 LWB a TO 2 UPB a DO + res +:= sgn * a[ 1 LWB a, i ] * det( minor( a, 1 LWB a, i ) ); + sgn := - sgn + OD; + res + FI # det # ; + + PROC perm = ( [,]NUMBER a )NUMBER: + IF 1 UPB a = 1 LWB a THEN # only one NUMBER # + a[ 1 LWB a, 2 LWB a ] + ELSE + NUMBER res := 0; + FOR i FROM 2 LWB a TO 2 UPB a DO + res +:= a[ 1 LWB a, i ] * perm( minor( a, 1 LWB a, i ) ) + OD; + res + FI # perm # ; + + BEGIN # test cases # + PROC test det and perm = ( [,]NUMBER a )VOID: + print( ( whole( det( a ), -8 ), " ", whole( perm( a ), -8 ), newline ) ); + + test det and perm( ( ( 1, 2 ) + , ( 3, 4 ) + ) + ); + test det and perm( ( ( 2, 9, 4 ) + , ( 7, 5, 3 ) + , ( 6, 1, 8 ) + ) ); + test det and perm( ( ( -2, 2, -3 ) + , ( -1, 1, 3 ) + , ( 2, 0, -1 ) + ) + ); + test det and perm( ( ( 1, 2, 3, 4 ) + , ( 4, 5, 6, 7 ) + , ( 7, 8, 9, 10 ) + , ( 10, 11, 12, 13 ) + ) + ); + test det and perm( ( ( 0, 1, 2, 3, 4 ) + , ( 5, 6, 7, 8, 9 ) + , ( 10, 11, 12, 13, 14 ) + , ( 15, 16, 17, 18, 19 ) + , ( 20, 21, 22, 23, 24 ) + ) + ); + test det and perm( ( ( 5 ) ) ); + test det and perm( ( ( 1, 0, 0 ) + , ( 0, 1, 0 ) + , ( 0, 0, 1 ) + ) + ); + test det and perm( ( ( 0, 0, 1 ) + , ( 0, 1, 0 ) + , ( 1, 0, 0 ) + ) + ) + END +END diff --git a/Task/Determinant-and-permanent/XPL0/determinant-and-permanent.xpl0 b/Task/Determinant-and-permanent/XPL0/determinant-and-permanent.xpl0 new file mode 100644 index 0000000000..74c60b83ae --- /dev/null +++ b/Task/Determinant-and-permanent/XPL0/determinant-and-permanent.xpl0 @@ -0,0 +1,48 @@ +func DetPerm(Det, A, N); \Return value of determinant or permanent of A, order N +int Det, A, N; +int B Sum, Term; +int I, K, L; +[if N = 1 then return A(0, 0); +B:= Reserve((N-1)*4); +Sum:= 0; +for I:= 0 to N-1 do + [L:= 0; + for K:= 0 to N-1 do + if K # I then + [B(L):= @A(K, 1); L:= L+1]; + Term:= A(I, 0) * DetPerm(Det, B, N-1); + if Det & I&1 then Term:= -Term; + Sum:= Sum + Term; + ]; +return Sum; +]; + +int Arrays, I; +[Arrays:= [ + [ [1, 2], + [3, 4] ], + + [ [-2, 2, -3], + [-1, 1, 3], + [ 2, 0, -1] ], + + [ [ 1, 2, 3, 4], + [ 4, 5, 6, 7], + [ 7, 8, 9, 10], + [10, 11, 12, 13] ], + + [ [ 0, 1, 2, 3, 4], + [ 5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19], + [20, 21, 22, 23, 24] ] + ]; +for I:= 0 to 3 do + [Text(0, "Determinant: "); + IntOut(0, DetPerm(true, Arrays(I), I+2)); + CrLf(0); + Text(0, "Permanent : "); + IntOut(0, DetPerm(false, Arrays(I), I+2)); + CrLf(0); CrLf(0); + ]; +] diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/C/determine-if-a-string-has-all-the-same-characters-1.c b/Task/Determine-if-a-string-has-all-the-same-characters/C/determine-if-a-string-has-all-the-same-characters-1.c deleted file mode 100644 index 19fdbf57c8..0000000000 --- a/Task/Determine-if-a-string-has-all-the-same-characters/C/determine-if-a-string-has-all-the-same-characters-1.c +++ /dev/null @@ -1,33 +0,0 @@ -#include -#include - -int main(int argc,char** argv) -{ - int i,len; - char reference; - - if(argc>2){ - printf("Usage : %s \n",argv[0]); - return 0; - } - - if(argc==1||strlen(argv[1])==1){ - printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1])); - return 0; - } - - reference = argv[1][0]; - len = strlen(argv[1]); - - for(i=1;i -#include -#include - -/* - * The wide character version of the program is compiled if WIDE_CHAR is defined - */ -#define WIDE_CHAR - -#ifdef WIDE_CHAR -#define CHAR wchar_t -#else -#define CHAR char -#endif - -/** - * Find a character different from the preceding characters in the given string. - * - * @param s the given string, NULL terminated. - * - * @return the pointer to the occurence of the different character - * or a pointer to NULL if all characters in the string - * are exactly the same. - * - * @notice This function return a pointer to NULL also for empty strings. - * Returning NULL-or-CHAR would not enable to compute the position - * of the non-matching character. - * - * @warning This function compare characters (single-bytes, unicode etc.). - * Therefore this is not designed to compare bytes. The NULL character - * is always treated as the end-of-string marker, thus this function - * cannot be used to scan strings with NULL character inside string, - * for an example "aaa\0aaa\0\0". - */ -const CHAR* find_different_char(const CHAR* s) -{ - /* The code just below is almost the same regardles - char or wchar_t is used. */ - - const CHAR c = *s; - while (*s && c == *s) - { - s++; - } - return s; -} - -/** - * Apply find_different_char function to a given string and output the raport. - * - * @param s the given NULL terminated string. - */ -void report_different_char(const CHAR* s) -{ -#ifdef WIDE_CHAR - wprintf(L"\n"); - wprintf(L"string: \"%s\"\n", s); - wprintf(L"length: %d\n", wcslen(s)); - const CHAR* d = find_different_char(s); - if (d) - { - /* - * We have got the famous pointers arithmetics and we can compute - * difference of pointers pointing to the same array. - */ - wprintf(L"character '%wc' (%#x) at %d\n", *d, *d, (int)(d - s)); - } - else - { - wprintf(L"all characters are the same\n"); - } - wprintf(L"\n"); -#else - putchar('\n'); - printf("string: \"%s\"\n", s); - printf("length: %d\n", strlen(s)); - const CHAR* d = find_different_char(s); - if (d) - { - /* - * We have got the famous pointers arithmetics and we can compute - * difference of pointers pointing to the same array. - */ - printf("character '%c' (%#x) at %d\n", *d, *d, (int)(d - s)); - } - else - { - printf("all characters are the same\n"); - } - putchar('\n'); -#endif -} - -/* There is a wmain function as an entry point when argv[] points to wchar_t */ - -#ifdef WIDE_CHAR -int wmain(int argc, wchar_t* argv[]) -#else -int main(int argc, char* argv[]) -#endif -{ - if (argc < 2) - { - report_different_char(L""); - report_different_char(L" "); - report_different_char(L"2"); - report_different_char(L"333"); - report_different_char(L".55"); - report_different_char(L"tttTTT"); - report_different_char(L"4444 444k"); - } - else - { - report_different_char(argv[1]); - } - - return EXIT_SUCCESS; -} diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/C/determine-if-a-string-has-all-the-same-characters.c b/Task/Determine-if-a-string-has-all-the-same-characters/C/determine-if-a-string-has-all-the-same-characters.c new file mode 100644 index 0000000000..5517b124d6 --- /dev/null +++ b/Task/Determine-if-a-string-has-all-the-same-characters/C/determine-if-a-string-has-all-the-same-characters.c @@ -0,0 +1,37 @@ +#include +#include +#include + +void +allCharsSame(const char *s) +{ + const char *p; + ptrdiff_t offs; + + printf("Input: \"%s\", length = %ld\n", s, strlen(s)); + + for (p = s; *p; p++) { + if (p[1] && p[0] != p[1]) { + offs = &p[1] - s; + /* +8 to skip past 'Input: "' */ + printf("%-*s^\n", (int)offs+8, ""); + printf("Difference at position %ld: '%c' (%#02x) != '%c' (%#02x)\n", + offs, p[0], p[0], p[1], p[1]); + return; + } + } + printf("All characters are identical\n"); +} + +int +main(void) +{ + allCharsSame(""); + allCharsSame(" "); + allCharsSame("2"); + allCharsSame("333"); + allCharsSame(".55"); + allCharsSame("tttTTT"); + allCharsSame("4444 444k"); + return 0; +} diff --git a/Task/Determine-if-a-string-has-all-unique-characters/C/determine-if-a-string-has-all-unique-characters.c b/Task/Determine-if-a-string-has-all-unique-characters/C/determine-if-a-string-has-all-unique-characters.c index 31f2fa664f..51b8cdd0b7 100644 --- a/Task/Determine-if-a-string-has-all-unique-characters/C/determine-if-a-string-has-all-unique-characters.c +++ b/Task/Determine-if-a-string-has-all-unique-characters/C/determine-if-a-string-has-all-unique-characters.c @@ -1,128 +1,40 @@ -#include -#include -#include -#include +#include +#include +#include -typedef struct positionList{ - int position; - struct positionList *next; -}positionList; - -typedef struct letterList{ - char letter; - int repititions; - positionList* positions; - struct letterList *next; -}letterList; - -letterList* letterSet; -bool duplicatesFound = false; - -void checkAndUpdateLetterList(char c,int pos){ - bool letterOccurs = false; - letterList *letterIterator,*newLetter; - positionList *positionIterator,*newPosition; - - if(letterSet==NULL){ - letterSet = (letterList*)malloc(sizeof(letterList)); - letterSet->letter = c; - letterSet->repititions = 0; - - letterSet->positions = (positionList*)malloc(sizeof(positionList)); - letterSet->positions->position = pos; - letterSet->positions->next = NULL; - - letterSet->next = NULL; - } - - else{ - letterIterator = letterSet; - - while(letterIterator!=NULL){ - if(letterIterator->letter==c){ - letterOccurs = true; - duplicatesFound = true; - - letterIterator->repititions++; - positionIterator = letterIterator->positions; - - while(positionIterator->next!=NULL) - positionIterator = positionIterator->next; - - newPosition = (positionList*)malloc(sizeof(positionList)); - newPosition->position = pos; - newPosition->next = NULL; - - positionIterator->next = newPosition; - } - if(letterOccurs==false && letterIterator->next==NULL) - break; - else - letterIterator = letterIterator->next; - } - - if(letterOccurs==false){ - newLetter = (letterList*)malloc(sizeof(letterList)); - newLetter->letter = c; - - newLetter->repititions = 0; - - newLetter->positions = (positionList*)malloc(sizeof(positionList)); - newLetter->positions->position = pos; - newLetter->positions->next = NULL; - - newLetter->next = NULL; - - letterIterator->next = newLetter; - } - } +/* +* return -1 if s has no repeated characters, otherwise the array +* index where a duplicated character first reappears +*/ +int uniquechars(char *s) { + int i, j, slen; + slen = strlen(s); + if (slen < 2) return -1; + for (i = 0; i < (slen - 1); i++) + for (j = i + 1; j < slen; j++) + if (s[i] == s[j]) return j; + return -1; } -void printLetterList(){ - positionList* positionIterator; - letterList* letterIterator = letterSet; - - while(letterIterator!=NULL){ - if(letterIterator->repititions>0){ - printf("\n'%c' (0x%x) at positions :",letterIterator->letter,letterIterator->letter); - - positionIterator = letterIterator->positions; - - while(positionIterator!=NULL){ - printf("%3d",positionIterator->position + 1); - positionIterator = positionIterator->next; - } - } - - letterIterator = letterIterator->next; - } - printf("\n"); +void report(char *s) { + int pos, first; + pos = uniquechars(s); + if (pos == -1) + printf("\"%s\" (length = %d) has no duplicate characters\n", s, strlen(s)); + else { + printf("\"%s\" (length = %d) has duplicate characters:\n", s, strlen(s)); + /* find first instance of duplicated ch in s */ + first = (int) (strchr(s, s[pos]) - s); + printf(" '%c' (= %2Xh) appears at positions %d and %d\n", + s[pos], s[pos], first+1, pos+1); + } } -int main(int argc,char** argv) -{ - int i,len; - - if(argc>2){ - printf("Usage : %s \n",argv[0]); - return 0; - } - - if(argc==1||strlen(argv[1])==1){ - printf("\"%s\" - Length %d - Contains only unique characters.\n",argc==1?"":argv[1],argc==1?0:1); - return 0; - } - - len = strlen(argv[1]); - - for(i=0;i 0 + dr = dr + n mod(10) + n = int(n / 10) + wend + + ap = ap + 1 + n = dr + until dr < 10 + +end fn = dr + + +long a(2) +a(0) = 627615 : a(1) = 39390 : a(2) = 588225 +short i +for i = 0 to 2 + dr = fn digitalRoot(a(i)) + print a(i), "Additive persistence = ", ap, "Digital root = ", dr +next i + +handleevents diff --git a/Task/Dijkstras-algorithm/FreeBASIC/dijkstras-algorithm.basic b/Task/Dijkstras-algorithm/FreeBASIC/dijkstras-algorithm.basic new file mode 100644 index 0000000000..41e56c1e89 --- /dev/null +++ b/Task/Dijkstras-algorithm/FreeBASIC/dijkstras-algorithm.basic @@ -0,0 +1,140 @@ +Const INFINITY As Integer = &h7FFFFFFF + +Type Edge + src As String * 1 + dst As String * 1 + cost As Integer +End Type + +Type Vertex + nom As String * 1 + dist As Integer + prev As String * 1 +End Type + +Type Graph + edges(100) As Edge + edgeCount As Integer + verts(100) As Vertex + vertCount As Integer +End Type + +Function createGraph(edges() As Edge, cnt As Integer) As Graph + Dim As Graph g + Dim As String names(100) + Dim As Integer i, j, nCount = 0 + + g.edgeCount = cnt + + ' Copy edges and collect unique vertices + For i = 0 To cnt - 1 + g.edges(i) = edges(i) + + ' Check source vertex + Dim As Boolean found = False + For j = 0 To nCount - 1 + If names(j) = edges(i).src Then + found = True + Exit For + End If + Next + If Not found Then + names(nCount) = edges(i).src + nCount += 1 + End If + + ' Check destination vertex + found = False + For j = 0 To nCount - 1 + If names(j) = edges(i).dst Then + found = True + Exit For + End If + Next + If Not found Then + names(nCount) = edges(i).dst + nCount += 1 + End If + Next + + ' Initialize vertices + g.vertCount = nCount + For i = 0 To nCount - 1 + With g.verts(i) + .nom = names(i) + .dist = INFINITY + .prev = names(i) + End With + Next + + Return g +End Function + +Function findVertex(g As Graph, nombre As String) As Integer + For i As Integer = 0 To g.vertCount - 1 + If g.verts(i).nom = nombre Then Return i + Next + Return -1 +End Function + +Function dijkstraPath(g As Graph, source As String, dest As String) As Integer + Dim As Integer changed, i, srcIdx, dstIdx, newDist, destIdx + srcIdx = findVertex(g, source) + If srcIdx >= 0 Then g.verts(srcIdx).dist = 0 + + Do + changed = 0 + For i = 0 To g.edgeCount - 1 + With g.edges(i) + srcIdx = findVertex(g, .src) + dstIdx = findVertex(g, .dst) + + If srcIdx >= 0 Andalso g.verts(srcIdx).dist <> INFINITY Then + newDist = g.verts(srcIdx).dist + .cost + If newDist < g.verts(dstIdx).dist Then + g.verts(dstIdx).dist = newDist + g.verts(dstIdx).prev = .src + changed = 1 + End If + End If + End With + Next + Loop While changed + + destIdx = findVertex(g, dest) + Return Iif(destIdx >= 0, g.verts(destIdx).dist, INFINITY) +End Function + +Function getPath(g As Graph, source As String, dest As String) As String + Dim As String path = "", current = dest + Dim As Integer idx, destIdx, cost + + ' Build path backwards + While current <> source + idx = findVertex(g, current) + If idx >= 0 Then + path = " -> " & current & path + current = g.verts(idx).prev + End If + Wend + + ' Get final cost + destIdx = findVertex(g, dest) + cost = Iif(destIdx >= 0, g.verts(destIdx).dist, INFINITY) + + Return source & " " & dest & " : " & source & path & " cost : " & cost +End Function + +' Test program +Dim As Edge testGraph(8) => {_ +("a", "b", 7), ("a", "c", 9), ("a", "f", 14), _ +("b", "c", 10), ("b", "d", 15), ("c", "d", 11), _ +("c", "f", 2), ("d", "e", 6), ("e", "f", 9)} + +Dim As Graph g = createGraph(testGraph(), 9) +Dim As String source = "a", dest = "e" + +dijkstraPath(g, source, dest) +Print getPath(g, source, dest) + +Sleep diff --git a/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm.m2000 b/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm-1.m2000 similarity index 92% rename from Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm.m2000 rename to Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm-1.m2000 index f04844c45f..b76ecc771a 100644 --- a/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm.m2000 +++ b/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm-1.m2000 @@ -4,18 +4,25 @@ Module Dijkstra`s_algorithm { dim d(n)=val =d() } + FillList=lambda (n) -> { + m=list + for i=1 to n: append m, i: next + =m + } + // tree term=("",0) Edges=(("a", ("b",7),("c",9),("f",14)),("b",("c",10),("d",15)),("c",("d",11),("f",2)),("d",("e",6)),("e",("f", 9)),("f",term)) + // Document Doc$="Graph:"+{ } ShowGraph() Doc$="Paths"+{ } Print "Paths" - For from_here=0 to 5 + For from_here=0 to Len(Edges)-1 pa=GetArr(len(Edges), -1) d=GetArr(len(Edges), max_number) - Inventory S=1,2,3,4,5,6 + S=FillList(len(Edges)) return d, from_here:=0 RemoveMin=Lambda S, d, max_number-> { ss=each(S) diff --git a/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm-2.m2000 b/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm-2.m2000 new file mode 100644 index 0000000000..918a104194 --- /dev/null +++ b/Task/Dijkstras-algorithm/M2000-Interpreter/dijkstras-algorithm-2.m2000 @@ -0,0 +1,132 @@ +Module Dijkstra`s_algorithm { + const max_number=1.E+306 + GetArr=lambda (n, val)->{ + dim d(n)=val + =d() + } + FillList=lambda (n) -> { + m=list + for i=1 to n : append m, i :next + =m + } + // tree + class node { + name$, val as long + remove { + created-- + print "Node removed, left: "+created + } + class: + module node (.name$, .val) { + created++ + print "New node, total: "+created + } + } + global long created + pNode = lambda ->{ + ->node(![]) + } + Class EdgeList { + object Node[0] + name$ + class: + module EdgeList (.name$) { + n=0 + while not empty + read .Node[n] + n++ + end while + } + } + Node_A=EdgeList("a", pNode("b",7), pNode("c", 9), pNode("f",14) ) + Node_B=EdgeList("b",pNode("c",10),pNode("d",15)) + Node_C=EdgeList("c",pNode("d",11),pNode("f",2)) + Node_D=EdgeList("d",pNode("e",6)) + Node_E=EdgeList("e",pNode("f", 9)) + Node_F=EdgeList("f",pNode()) + Dim Edges(6) + Edges(0)=Node_A, Node_B, Node_C, Node_D, Node_E, Node_F + Document Doc$="Graph:"+{ + } + ShowGraph() + Doc$="Paths"+{ + } + Print "Paths" + For from_here=0 to Len(Edges())-1 + pa=GetArr(len(Edges()), -1) + d=GetArr(len(Edges()), max_number) + S=FillList(len(Edges())) + return d, from_here:=0 + RemoveMin=Lambda S, d, max_number-> { + ss=each(S) + min=max_number + p=0 + while ss + val=d#val(eval(S,ss^)-1) + if min>val then let min=val : p=ss^ + end while + =s(p!) ' use p as index not key + Delete S, eval(s,p) + } + Show_Distance_and_Path$=lambda$ d, pa, from_here, max_number (n) -> { + ret1$=chr$(from_here+asc("a"))+" to "+chr$(n+asc("a")) + if d#val(n) =max_number then =ret1$+ " No Path" :exit + let ret$="", mm=n, m=n + repeat + n=m + ret$+=chr$(asc("a")+n) + m=pa#val(n) + until from_here=n + =ret1$+format$("{0::-4} {1}",d#val(mm),strrev$(ret$)) + } + while len(s)>0 + u=RemoveMin() + rem Print u, chr$(u-1+asc("a")) + Relaxed() + end while + For i=0 to len(d)-1 + line$=Show_Distance_and_Path$(i) + Print line$ + doc$=line$+{ + } + next + next + Clipboard Doc$ + End + Sub Relaxed() + local vertex=Edges(u-1).node, i + local e=Len(vertex)-1, val + for i=0 to e + for vertex[i] { + if .name$<>"" then + val=Asc(.name$)-Asc("a") + if d#val(val)>.val+d#val(u-1) then return d, val:=.val+d#val(u-1) : Return Pa, val:=u-1 + end if + } + next + end sub + Sub ShowGraph() + Print "Graph" + local i + for i=1 to len(Edges()) + show_edges(i) + next + end sub + Sub show_edges(n) + n-- + local line$, j + for Edges(n) { + for j=0 to len(.node)-1 + Print .name$; + for .node[j] { + if ..name$>"" then + print "->"+..name$+" "+format$(" {0::-2}",..val) + else + print + end if + } + next + } + end sub +} +Dijkstra`s_algorithm diff --git a/Task/Dijkstras-algorithm/PascalABC.NET/dijkstras-algorithm.pas b/Task/Dijkstras-algorithm/PascalABC.NET/dijkstras-algorithm.pas new file mode 100644 index 0000000000..c77947a2fe --- /dev/null +++ b/Task/Dijkstras-algorithm/PascalABC.NET/dijkstras-algorithm.pas @@ -0,0 +1,78 @@ +type + Edge = auto class + start, &end: char; + cost: real; + end; + + Graph = auto class + edges: array of Edge; + vertices: HashSet; + + constructor(params edges: array of (char, char, real)); + begin + Self.edges := edges.Select(e -> new Edge(e[0], e[1], e[2])).ToArray; + Self.vertices := new HashSet( + Self.edges.Select(e -> e.start) + Self.edges.Select(e -> e.end) + ); + end; + + function Dijkstra(source, dest: char): sequence of char; + begin + assert(vertices.Contains(source)); + + var inf := real.MaxValue; + var dist := Dict(vertices.Select(v -> (v, inf))); + var previous := Dict(vertices.Select(v -> (v, ' '))); + dist[source] := 0; + + var q := vertices.ToHashSet; + var neighbours := Dict(vertices.Select(v -> (v, new HashSet<(char, real)>))); + + foreach var edge in edges do + begin + neighbours[edge.start].Add((edge.end, edge.cost)); + neighbours[edge.end].Add((edge.start, edge.cost)); + end; + + while q.Count > 0 do + begin + var u := q.MinBy(v -> dist[v]); + q.Remove(u); + + if (dist[u] = inf) or (u = dest) then + break; + + foreach var (v, cost) in neighbours[u] do + begin + var alt := dist[u] + cost; + if alt < dist[v] then + begin + dist[v] := alt; + previous[v] := u; + end; + end; + end; + + var s := new List; + var u := dest; + + while previous[u] <> ' ' do + begin + s.Insert(0, u); + u := previous[u]; + end; + + s.Insert(0, u); + Result := s; + end; + end; + +begin + var gr := new Graph( + ('a', 'b', 7.0), ('a', 'c', 9.0), ('a', 'f', 14.0), + ('b', 'c', 10.0), ('b', 'd', 15.0), ('c', 'd', 11.0), + ('c', 'f', 2.0), ('d', 'e', 6.0), ('e', 'f', 9.0) + ); + + gr.Dijkstra('a', 'e').Println; +end. diff --git a/Task/Dinesmans-multiple-dwelling-problem/FutureBasic/dinesmans-multiple-dwelling-problem.basic b/Task/Dinesmans-multiple-dwelling-problem/FutureBasic/dinesmans-multiple-dwelling-problem.basic new file mode 100644 index 0000000000..55f4064fdc --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/FutureBasic/dinesmans-multiple-dwelling-problem.basic @@ -0,0 +1,37 @@ +// Dinesmans multiple-dwelling problem +//https://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem + + +short Baker,Cooper,Fletcher,Miller,Smith +short LoopCount + +FOR Baker = 0 TO 4 + FOR Cooper = 0 TO 4 + FOR Fletcher = 0 TO 4 + FOR Miller = 0 TO 4 + FOR Smith = 0 TO 4 + IF Baker <> 4 && Cooper <> 0 && Miller <> Cooper + IF Fletcher <> 0 && Fletcher <> 4 && ABS(Smith-Fletcher)<>1 && ABS(Fletcher-Cooper)<>1 + IF Baker<>Cooper and Baker<>Fletcher && Baker<>Miller and ¬ + Baker<>Smith and Cooper<>Fletcher and Cooper<>Miller and ¬ + Cooper<>Smith and Fletcher<>Miller and Fletcher<>Smith and ¬ + Miller<>Smith + + LoopCount ++ + if LoopCount = 4 + PRINT "Baker lives on floor " ; Baker + 1 + PRINT "Cooper lives on floor " ; Cooper + 1 + PRINT "Fletcher lives on floor " ; Fletcher + 1 + PRINT "Miller lives on floor " ; Miller + 1 + PRINT "Smith lives on floor " ; Smith + 1 + end if + END IF + END IF + END IF + NEXT Smith + NEXT Miller + NEXT Fletcher + NEXT Cooper +NEXT Baker + +handleevents diff --git a/Task/Dining-philosophers/FreeBASIC/dining-philosophers.basic b/Task/Dining-philosophers/FreeBASIC/dining-philosophers.basic new file mode 100644 index 0000000000..4909077304 --- /dev/null +++ b/Task/Dining-philosophers/FreeBASIC/dining-philosophers.basic @@ -0,0 +1,108 @@ +Const NUM_PHILOSOPHERS = 5 +Const HUNGER = 3 +Const THINK_TIME = 1000 +Const EAT_TIME = 1000 + +Type Fork + mutex As Any Ptr + available As Boolean +End Type + +Type Philosopher + nombre As String + leftFork As Fork Ptr + rightFork As Fork Ptr + hunger As Integer +End Type + +Dim Shared As Philosopher philosophers(NUM_PHILOSOPHERS-1) +Dim Shared As Fork forks(NUM_PHILOSOPHERS-1) +Dim Shared As Any Ptr printMutex + +Function threadSafePrint(text As String) As Integer + Mutexlock(printMutex) + Print text + Mutexunlock(printMutex) + Return 0 +End Function + +Sub delay(ms As Integer) + Dim As Double t = Timer + While (Timer - t) * 1000 < ms + Sleep 1, 1 + Wend +End Sub + +Function philosopherThread(param As Any Ptr) As Any Ptr + Dim As Philosopher Ptr phil = param + + threadSafePrint(phil->nombre + " seated") + + While phil->hunger > 0 + threadSafePrint(phil->nombre + " hungry") + + Mutexlock(phil->leftFork->mutex) + Mutexlock(phil->rightFork->mutex) + + threadSafePrint(phil->nombre + " eating") + delay(EAT_TIME) + + Mutexunlock(phil->leftFork->mutex) + Mutexunlock(phil->rightFork->mutex) + + threadSafePrint(phil->nombre + " thinking") + delay(THINK_TIME) + + phil->hunger -= 1 + Wend + + threadSafePrint(phil->nombre + " satisfied") + threadSafePrint(phil->nombre + " left the table") + + Return 0 +End Function + +' Main program +Dim As Integer i +Dim As String names(NUM_PHILOSOPHERS-1) = {"Aristotle", "Kant", "Spinoza", "Marx", "Russell"} +Print "Table empty" + +printMutex = Mutexcreate() + +' Initialize forks +For i = 0 To NUM_PHILOSOPHERS-1 + forks(i).mutex = Mutexcreate() + forks(i).available = True +Next + +' Initialize philosophers +For i = 0 To NUM_PHILOSOPHERS-1 + philosophers(i).nombre = names(i) + philosophers(i).hunger = HUNGER + philosophers(i).leftFork = @forks(i) + philosophers(i).rightFork = @forks((i + 1) Mod NUM_PHILOSOPHERS) +Next + +' Make last philosopher left-handed +Swap philosophers(NUM_PHILOSOPHERS-1).leftFork, philosophers(NUM_PHILOSOPHERS-1).rightFork + +' Create threads +Dim As Any Ptr threads(NUM_PHILOSOPHERS-1) +For i = 0 To NUM_PHILOSOPHERS-1 + threads(i) = Threadcreate(Cast(Sub(As Any Ptr), @philosopherThread), @philosophers(i)) +Next + +' Wait for all threads +For i = 0 To NUM_PHILOSOPHERS-1 + Threadwait(threads(i)) +Next + +' Cleanup +For i = 0 To NUM_PHILOSOPHERS-1 + Mutexdestroy(forks(i).mutex) +Next + +Mutexdestroy(printMutex) +Print "Table empty" + +Sleep diff --git a/Task/Display-a-linear-combination/XPL0/display-a-linear-combination.xpl0 b/Task/Display-a-linear-combination/XPL0/display-a-linear-combination.xpl0 new file mode 100644 index 0000000000..2186fb9b51 --- /dev/null +++ b/Task/Display-a-linear-combination/XPL0/display-a-linear-combination.xpl0 @@ -0,0 +1,37 @@ +func LinearCombo(Combo, Len); \Display linear combination of Combo +int Combo, Len; +int Zero, N, I; +[Zero:= true; +for I:= 0 to Len-1 do + [N:= Combo(I); + if N # 0 then + [ if N < 0 and Zero then Text(0, "-") + else if N < 0 then Text(0, " - ") + else if not Zero then Text(0, " + "); + if abs(N) # 1 then + [IntOut(0, abs(N)); Text(0, "*")]; + Text(0, "e("); IntOut(0, I+1); Text(0, ")"); + Zero:= false; + ]; + ]; +if Zero then Text(0, "0"); +CrLf(0); +]; + +int Combos, C; +[Combos:= [ + [1, 2, 3], + [0, 1, 2, 3], + [1, 0, 3, 4], + [1, 2, 0], + [0, 0, 0], + [0], + [1, 1, 1], + [-1, -1, -1], + [-1, -2, 0, -3], + [-1], + [0] \sentinel provides length of last item (=1) + ]; +for C:= 0 to 10-1 do + LinearCombo( Combos(C), (Combos(C+1)-Combos(C))/4 ); \4 = SizeOfInt +] diff --git a/Task/Display-an-outline-as-a-nested-table/ALGOL-68/display-an-outline-as-a-nested-table-1.alg b/Task/Display-an-outline-as-a-nested-table/ALGOL-68/display-an-outline-as-a-nested-table-1.alg new file mode 100644 index 0000000000..4ac32f3482 --- /dev/null +++ b/Task/Display-an-outline-as-a-nested-table/ALGOL-68/display-an-outline-as-a-nested-table-1.alg @@ -0,0 +1,141 @@ +BEGIN # Show an outline as a wiki or HTML table # + MODE ONODE = STRUCT( STRING text, INT indent, REF ONODE next, child ); + REF ONODE nil node = NIL; + OP LTRIM = ( STRING s )STRING: # returns s without leading spaces # + BEGIN + INT s pos := LWB s; + WHILE IF s pos > UPB s THEN FALSE ELSE s[ s pos ] = " " FI DO s pos +:= 1 OD; + IF s pos > UPB s THEN "" ELSE s[ s pos : ] FI + END # LTRIM # ; + OP INDENTOF = ( STRING s )INT: # returns count of leading spaces of s # + BEGIN + INT s pos := LWB s; + WHILE IF s pos > UPB s THEN FALSE ELSE s[ s pos ] = " " FI DO s pos +:= 1 OD; + s pos - LWB s + END # INDENTOF # ; + + # count the total number of columns in tree # + OP COUNTCOLUMNS = ( REF ONODE tree )INT: + IF child OF tree IS nil node + THEN 1 + ELSE INT count := 0; + REF ONODE next := child OF tree; + WHILE next ISNT nil node DO + count +:= COUNTCOLUMNS next; + next := next OF next + OD; + count + FI # COUNTCOLUMNS # ; + + OP TOONODE = ( []STRING s )REF ONODE: + IF HEAP ONODE result; + LWB s > UPB s + THEN result := ( "", 0, nil node, nil node ) + ELSE result := ( s[ LWB s ], INDENTOF s[ LWB s ], nil node, nil node ); + [ 1 : ( UPB s - LWB s ) + 1 ]REF ONODE tstack; + FOR i TO UPB tstack DO tstack[ i ] := nil node OD; + INT s pos := LWB tstack; + tstack[ s pos ] := result; + FOR pos FROM LWB s + 1 TO UPB s DO + INT indent = INDENTOF s[ pos ]; + WHILE indent < indent OF tstack[ s pos ] DO s pos -:= 1 OD; + HEAP ONODE next := ( s[ pos ], indent, nil node, nil node ); + IF indent > indent OF tstack[ s pos ] + THEN child OF tstack[ s pos ] := next; + tstack[ s pos +:= 1 ] := next + ELSE IF next OF tstack[ s pos ] IS nil node + THEN next OF tstack[ s pos ] := next + FI; + tstack[ s pos ] := next + FI + OD; + result + FI # TOONODE # ; + + PROC print tree table body = ( REF ONODE tree, STRING tr, rt, open td, close td, dt, empty td )VOID: + BEGIN + INT td max := 0; # find the maximum elements the rows # + REF ONODE next := tree; + WHILE next ISNT nil node DO + td max +:= COUNTCOLUMNS next; + next := next OF next + OD; + [ 1 : td max ]REF ONODE td; # get the elements of the first row # + td max := 0; + next := tree; + WHILE next ISNT nil node DO + td[ td max +:= 1 ] := next; + next := next OF next + OD; + BOOL more rows := TRUE; # generate the rows # + WHILE more rows DO + print( ( tr, newline ) ); # output the current row # + FOR td pos TO td max DO + REF ONODE element = td[ td pos ]; + IF element IS nil node + THEN print( ( empty td ) ) + ELSE INT span = COUNTCOLUMNS element; + print( ( open td ) ); + IF span > 1 THEN print( ( " colspan=""", whole( span, 0 ), """" ) ) FI; + print( ( close td, LTRIM text OF element ) ); + IF dt /= "" THEN print( ( "" ) ) FI; + print( ( newline ) ) + FI + OD; + IF rt /= "" THEN print( ( rt, newline ) ) FI; + []REF ONODE prev = td[ 1 : td max ]; # replace td with the # + INT new max := 0; # ... child elements of the current row # + more rows := FALSE; + FOR td pos TO td max DO + next := IF prev[ td pos ] IS nil node + THEN nil node + ELSE child OF prev[ td pos ] + FI; + td[ new max +:= 1 ] := next; + IF next ISNT nil node THEN + more rows := TRUE; + WHILE ( next := next OF next ) ISNT nil node DO + td[ new max +:= 1 ] := next + OD + FI + OD; + td max := new max + OD + END # print tree table body # ; + + # prints tree as an HTML table # + PROC print tree as html table = ( REF ONODE tree )VOID: + BEGIN + print( ( "

", newline ) ); + print tree table body( tree, "", "", "", "", "
" ); + print( ( "
", newline ) ) + END # print tree as html table # ; + + # prints tree as a wiki table b # + PROC print tree as wiki table = ( REF ONODE tree )VOID: + BEGIN + print( ( "{| class=""wikitable"" style=""text-align: center;""", newline ) ); + print tree table body( tree, "|-", "", "| ", " | ", "", "| |" + REPR 10 ); + print( ( "|}", newline ) ) + END # print tree as wiki table # ; + + BEGIN + REF ONODE ex tree + = TOONODE []STRING( "Display an outline as a nested table." + , " Parse the outline to a tree," + , " measuring the indent of each line," + , " translating the indentation to a nested structure," + , " and padding the tree to even depth." + , " (happens during the output in this version)" + , " count the leaves descending from each node," + , " defining the width of a leaf as 1," + , " and the width of a parent node as a sum." + , " (The sum of the widths of its children)" + , " and write out a table with 'colspan' values" + , " either as a wiki table," + , " or as HTML." + ); + print tree as html table( ex tree ); + print tree as wiki table( ex tree ) + END +END diff --git a/Task/Display-an-outline-as-a-nested-table/ALGOL-68/display-an-outline-as-a-nested-table-2.alg b/Task/Display-an-outline-as-a-nested-table/ALGOL-68/display-an-outline-as-a-nested-table-2.alg new file mode 100644 index 0000000000..6ff0caa928 --- /dev/null +++ b/Task/Display-an-outline-as-a-nested-table/ALGOL-68/display-an-outline-as-a-nested-table-2.alg @@ -0,0 +1,47 @@ + # make all columns of tree have the same number of rows # + # tree is modified and also returned as the result # + OP STANDARDISE = ( REF ONODE tree )REF ONODE: + BEGIN + INT td max := 0; # find the maximum elements the rows # + REF ONODE next := tree; + WHILE next ISNT nil node DO + td max +:= COUNTCOLUMNS next; + next := next OF next + OD; + [ 1 : td max ]REF ONODE td; # get the elements of the first row # + td max := 0; + next := tree; + WHILE next ISNT nil node DO + td[ td max +:= 1 ] := next; + next := next OF next + OD; + WHILE BOOL more rows := FALSE; # balance the tree # + FOR td pos TO td max DO + REF ONODE element = td[ td pos ]; + IF child OF element ISNT nil node + THEN more rows := TRUE + FI + OD; + more rows + DO FOR td pos TO td max DO # add "missing" child elements # + REF ONODE element = td[ td pos ]; + IF child OF element IS nil node + THEN HEAP ONODE new child := ( "", 0, nil node, nil node ); + child OF element := new child + FI + OD; + []REF ONODE prev = td[ 1 : td max ]; # replace td with the # + INT new max := 0; # ... child elements of the current row # + FOR td pos TO td max DO + next := child OF prev[ td pos ]; + td[ new max +:= 1 ] := next; + IF next ISNT nil node THEN + WHILE ( next := next OF next ) ISNT nil node DO + td[ new max +:= 1 ] := next + OD + FI + OD; + td max := new max + OD; + tree + END # STANDARDISE # ; diff --git a/Task/Distance-and-Bearing/FreeBASIC/distance-and-bearing.basic b/Task/Distance-and-Bearing/FreeBASIC/distance-and-bearing.basic new file mode 100644 index 0000000000..701127456b --- /dev/null +++ b/Task/Distance-and-Bearing/FreeBASIC/distance-and-bearing.basic @@ -0,0 +1,148 @@ +Type Airport + nombre As String + location As String + ICAO As String + dist As Double + bearing As Integer +End Type + +#define MAX_AIRPORTS 21 +#define PI 3.1415926535897932 + +Dim Shared db(MAX_AIRPORTS) As Airport +Dim Shared DME As Double, TOHDG As Double + +Function DegToRad(degrees As Double) As Double + Return degrees * PI / 180 +End Function + +Function RoundIt(theNum As Double, theDec As Integer) As Double + Return Fix(theNum * (10 ^ theDec) + 0.5) / (10 ^ theDec) +End Function + +Function DistanceGC(lat1 As Double, lon1 As Double, lat2 As Double, lon2 As Double) As Double + Dim As Double Dm, ER, dLat, dLon, a, c + + ER = 6371.0 'Earth's mean radius in km + dLat = DegToRad(lat2) - DegToRad(lat1) + dLon = DegToRad(lon2) - DegToRad(lon1) + a = Sin(dLat / 2) * Sin(dLat / 2) + Cos(DegToRad(lat1)) * Cos(DegToRad(lat2)) * Sin(dLon / 2) * Sin(dLon / 2) + c = 2 * Atan2(Sqr(a), Sqr(1 - a)) + Dm = ER * c / 1.852 + + Return Dm +End Function + +Function Bearing(lat1 As Double, lon1 As Double, lat2 As Double, lon2 As Double) As Double + Dim As Double lat1Rad = DegToRad(lat1) + Dim As Double lat2Rad = DegToRad(lat2) + Dim As Double dLon = DegToRad(lon2 - lon1) + Dim As Double y = Sin(dLon) * Cos(lat2Rad) + Dim As Double x = Cos(lat1Rad) * Sin(lat2Rad) - Sin(lat1Rad) * Cos(lat2Rad) * Cos(dLon) + + Return (Atan2(y, x) * 180/PI + 360) Mod 360 +End Function + +Sub Insert(ap As Airport) + Dim n As Integer = MAX_AIRPORTS - 1 + If ap.dist >= db(n).dist Then Exit Sub + While ap.dist < db(n).dist Andalso n > 0 + db(n + 1) = db(n) + n -= 1 + Wend + db(n + 1) = ap +End Sub + +Sub Test(lat2 As Double, lon2 As Double) + Static As Double lat1 = 51.514669, lon1 = 2.198581 'Rosetta coordinates + DME = DistanceGC(lat1, lon1, lat2, lon2) + DME = RoundIt(DME, 1) + TOHDG = Bearing(lat1, lon1, lat2, lon2) + TOHDG = RoundIt(TOHDG, 0) +End Sub + +Function IsValidNumber(s As String) As Integer + Return (Val(s) <> 0 Or s = "0") +End Function + +Function ReadAirportFile() As Integer + Dim As String linea, campo, c + Dim As Airport ap + Dim As Integer i, j, inQuotes + + Open "Airport-data.csv" For Input As #1 + If Err Then Print "Error opening file": Return 0 + + While Not Eof(1) + Line Input #1, linea + If Len(linea) = 0 Then Continue While + + Dim fields(15) As String + i = 0 + campo = "" + inQuotes = 0 + + For j = 1 To Len(linea) + c = Mid(linea, j, 1) + Select Case c + Case """" + inQuotes = Not inQuotes + Case "," + If Not inQuotes Then + If i < Ubound(fields) Then + fields(i) = campo + i += 1 + campo = "" + End If + Else + campo &= c + End If + Case Else + If c <> """" Then campo &= c + End Select + Next + + If i <= Ubound(fields) Then fields(i) = campo + + If i >= 7 Then + If IsValidNumber(fields(6)) And IsValidNumber(fields(7)) Then + 'Process the fields + Test(Val(fields(6)), Val(fields(7))) + ap.nombre = Trim(fields(1)) + ap.location = Trim(fields(2)) & ", " & Trim(fields(3)) + ap.ICAO = Trim(fields(5)) + ap.dist = DME + ap.bearing = TOHDG + Insert(ap) + End If + End If + Wend + + Close #1 + Return 1 +End Function + +'Main program +Dim i As Integer + +'Initialize distances +For i = 0 To MAX_AIRPORTS + db(i).dist = 99999 +Next + +If ReadAirportFile() Then + Print "AIRPORT/COUNTRY"; Tab(39); "ICAO"; Tab(46); "DISTANCE BEARING" + Print String(62, "-") + + For i = 1 To MAX_AIRPORTS - 1 + With db(i) + Print Left(.nombre & Space(38), 38) + Print Left(.location & Space(38), 38); + Print Left(.ICAO & Space(5), 5); Spc(6); + Print Using "##.# ###"; .dist; .bearing; + Print Chr(248); Chr(10) + End With + Next +End If + +Sleep diff --git a/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas b/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas index cc2c4a9fd3..972e2e8c39 100644 --- a/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas +++ b/Task/Diversity-prediction-theorem/PascalABC.NET/diversity-prediction-theorem.pas @@ -10,5 +10,5 @@ begin WriteLn('diversity: ', AverageSquareDiff(average, predictions)); end; -DiversityTheorem(49.0, |48.0, 47.0, 51.0|); -DiversityTheorem(49.0, |48.0, 47.0, 51.0, 42.0|) +DiversityTheorem(49.0, [48.0, 47.0, 51.0]); +DiversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0]) diff --git a/Task/Dominoes/Raku/dominoes.raku b/Task/Dominoes/Raku/dominoes.raku new file mode 100644 index 0000000000..09e6b0f0e7 --- /dev/null +++ b/Task/Dominoes/Raku/dominoes.raku @@ -0,0 +1,85 @@ +sub domino (Str $s) { $s.comb.sort.join } + +sub solve ( UInt $rows, UInt $cols, @tab ) { + die unless @tab.elems == $rows*$cols; + die unless @tab.elems %% 2; + + my @orientations = 'A' xx @tab.elems; # [A]vailable,[R]ight,[D]own,[L]eft,[U]p + + my SetHash $hand .= new: map &domino, [X~] @tab.unique xx 2; + + return gather { + my sub place_domino_at_first_available_after ( UInt $pos_last = 0 ) { + my $p1 = $pos_last + @orientations.skip($pos_last).first(:k, 'A'); + + for (False, $p1+1 , ), + (True , $p1+$cols, ) -> ($is_down, $p2, @two_letters) { + + next if $p2 > @tab.end or (!$is_down && $p2 %% $cols); # Board boundaries. + + my @two_cells := @orientations[$p1, $p2]; # Bind to candidate location + + next if @two_cells !eqv ; # Both cells must be available for placement. + + my $dom = domino( @tab[$p1, $p2].join ); + + $hand{$dom}-- or next; # Take domino from hand, iff present + @two_cells = @two_letters; # Assign placement + + # Either the solution is complete, or we must recurse. + if !$hand { take @orientations.clone } + else { place_domino_at_first_available_after($p1) } + + @two_cells = ; # Unassign placement + $hand{$dom}++; # Restore domino into hand + } + } + place_domino_at_first_available_after(); + } +} +sub bonus ( UInt $rows, UInt $cols ) { + die "Both are odd, so no tiling possible" if $rows !%% 2 and $cols !%% 2; + + my $half = $rows * $cols div 2; + + my sub T ($N) { map { ( pi * $_/($N+1) ).cos² * 4 }, 1..($N/2).ceiling } + + my $arrangements = [*] T($rows) X+ T($cols); + my $flips = 2 ** $half; + my $permutations = [*] 1 .. $half; + my $product = [*] ($arrangements, $flips, $permutations); + return :$arrangements, :$flips, :$permutations, :$product; +} +my @tests = + (7, 8, '05132231055052464303662006235126113002452143346664515414'), + (7, 8, '64220650162341432102355113505610426040114420536366525334'), + (3, 4, '001102221201'), +; +sub solution_works ( UInt $rows, UInt $cols, @tab, @sol --> Bool ) { + die unless @sol.all eq .any; + my BagHash $b .= new; + for @sol.keys -> $p1 { + given @sol[$p1] { + when 'L' { my $p2 = $p1+1; die unless @sol[$p2] eq 'R'; $b{ domino( @tab[$p1,$p2].join ) }++; } + when 'D' { my $p2 = $p1+$cols; die unless @sol[$p2] eq 'U'; $b{ domino( @tab[$p1,$p2].join ) }++; } + } + } + die unless $b.values.max == 1 and $b.elems == $rows * $cols / 2; + return True; +} +for @tests -> ( $rows, $cols, $flat_table ) { + my @solutions = solve($rows, $cols, $flat_table.comb); + say 'Solutions found: ', +@solutions; + + # Confirm that every solution is valid. + solution_works($rows, $cols, $flat_table.comb, $_) or die for @solutions; + + # Print first solution + say .join.trans( [] => [<╼ ╾ ╽ ╿>]) for @solutions[0].batch($cols); + + if ++$ == 1 { + say 'Bonus:'; + say .value.fmt("%45d "), .key.tclc for bonus($rows, $cols); + say ''; + } +} diff --git a/Task/Doomsday-rule/Draco/doomsday-rule.draco b/Task/Doomsday-rule/Draco/doomsday-rule.draco new file mode 100644 index 0000000000..73e8211a33 --- /dev/null +++ b/Task/Doomsday-rule/Draco/doomsday-rule.draco @@ -0,0 +1,50 @@ +type Date = struct { + word year; + byte month; + byte day; +}; + +proc leap_year(word y) bool: + y%4 = 0 and (y%100 /= 0 or y % 400 = 0) +corp + +proc weekday(Date date) *char: + [12]byte leapdoom = (4,1,7,4,2,6,4,1,5,3,7,5); + [12]byte normdoom = (3,7,7,4,2,6,4,1,5,3,7,5); + word c, r, s, t, c_anchor, doom, anchor; + + c := date.year / 100; + r := date.year % 100; + s := r / 12; + t := r % 12; + + c_anchor := (5 * (c % 4) + 2) % 7; + doom := (s + t + (t/4) + c_anchor) % 7; + anchor := if leap_year(date.year) + then leapdoom[date.month-1] + else normdoom[date.month-1] + fi; + + case (doom+date.day-anchor+7)%7 + incase 0: "Sunday" + incase 1: "Monday" + incase 2: "Tuesday" + incase 3: "Wednesday" + incase 4: "Thursday" + incase 5: "Friday" + incase 6: "Saturday" + esac +corp + +proc main() void: + [7]Date dates = ( + (1800,1,6), (1875,3,29), (1915,12,7), (1970,12,23), (2043,5,14), + (2077,2,12), (2101,4,2) + ); + + word d; + for d from 0 upto 6 do + writeln(dates[d].month:2, '/', dates[d].day:2, '/', dates[d].year:4, + ": ", weekday(dates[d])) + od +corp diff --git a/Task/Doomsday-rule/M2000-Interpreter/doomsday-rule.m2000 b/Task/Doomsday-rule/M2000-Interpreter/doomsday-rule.m2000 new file mode 100644 index 0000000000..bc2bab76ac --- /dev/null +++ b/Task/Doomsday-rule/M2000-Interpreter/doomsday-rule.m2000 @@ -0,0 +1,60 @@ +' MAKE USING("FORMAT STRING", PAR1, PAR2, ...PARN) +' WE USE READ V TO READ MORE PARAMETERS. +FUNCTION USING(A$) { + VARIANT V : LONG D, S, E, I=1: S$="" + WHILE I<=LEN(A$) + IF S THEN + IF MID$(A$,I,1)<>"#" THEN + IF MID$(A$,I,1)="." THEN D=I ELSE E=I + END IF + ELSE + IF MID$(A$,I,1)="#" THEN S=I + END IF + IF S AND E THEN + IF S>1 THEN S$+=LEFT$(A$, S-1) + A$=MID$(A$, E) + G() + S=0:E=0:D=0 + I=1 + END IF + I++ + END WHILE + IF S THEN + IF S>1 THEN S$+=LEFT$(A$, S-1):E=I-S+1: S=1 ELSE E=I + G() + =S$ + ELSE + =S$+A$ + END IF + SUB G() + IF ISNUM THEN + READ V + IF D>0 THEN + S$+=STR$(V, STRING$("#",E-D-1)+"0."+STRING$("0",D-S+1)) + ELSE + S$+=STR$(V, STRING$("0",E-S-1)+"0") + END IF + ELSE + V="" + READ V + S$+=LEFT$(V+STRING$(" ", E-S), E-S) + END IF + END SUB +} +05 FLUSH : GOSUB 110 +10 DIM D$(1 TO 7): FOR I=1 TO 7: READ D$(I): NEXT I +20 DIM D(1 TO 12, 0 TO 1): FOR I=0 TO 1: FOR J=1 TO 12: READ D(J, I): NEXT J : NEXT I +30 READ Y: IF Y=0 THEN BREAK ELSE READ M,D +40 PRINT USING("##/##/#### ", M, D, Y); +50 C=Y DIV 100: R=Y MOD 100 +60 S=R DIV 12: T=R MOD 12 +70 A=(5*BINARY.AND(C, 3)+2) MOD 7 +80 B=(S+T+(T DIV 4)+A) MOD 7 +90 PRINT D$((B+D-D(M,-(Y MOD 4=0 AND (Y MOD 100<>0 OR Y MOD 400=0)))+7) MOD 7+1) +100 GOTO 30 +110 DATA "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" +120 DATA 3,7,7,4,2,6,4,1,5,3,7,5 +130 DATA 4,1,7,4,2,6,4,1,5,3,7,5 +140 DATA 1800,1,6,1875,3,29,1915,12,7,1970,12,23 +150 DATA 2043,5,14,2077,2,12,2101,4,2,0 +160 RETURN diff --git a/Task/Doomsday-rule/Miranda/doomsday-rule.miranda b/Task/Doomsday-rule/Miranda/doomsday-rule.miranda new file mode 100644 index 0000000000..de3b570449 --- /dev/null +++ b/Task/Doomsday-rule/Miranda/doomsday-rule.miranda @@ -0,0 +1,29 @@ +main :: [sys_message] +main = [Stdout (lay [showdate d ++ ": " ++ weekday d | d<-tests])] + +date ::= Date (num,num,num) + +showdate :: date->[char] +showdate (Date (y,m,d)) = show m ++ "/" ++ show d ++ "/" ++ show y + +tests :: [date] +tests = map Date [ + (1800,1,6), (1875,3,29), (1915,12,7), (1970,12,23), (2043,5,14), + (2077,2,12), (2101,4,2)] + +weekday :: date->[char] +weekday (Date (year,month,day)) + = weekdays ! daynum + where weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday", + "Friday","Saturday"] + doomtab = leapdoom, if leapyear + = normdoom, otherwise + leapdoom = [4,1,7,2,4,6,4,1,5,3,7,5] + normdoom = [3,7,7,4,2,6,4,1,5,3,7,5] + leapyear = year mod 4=0 & (year mod 100~=0 \/ year mod 400=0) + (c, r) = (year div 100, year mod 100) + (s, t) = (r div 12, r mod 12) + c_anchor = (5 * (c mod 4) + 2) mod 7 + doom = (s + t + t div 4 + c_anchor) mod 7 + anchor = doomtab ! (month - 1) + daynum = (doom + day - anchor + 7) mod 7 diff --git a/Task/Doomsday-rule/Quackery/doomsday-rule.quackery b/Task/Doomsday-rule/Quackery/doomsday-rule.quackery new file mode 100644 index 0000000000..5dfa5b0e1d --- /dev/null +++ b/Task/Doomsday-rule/Quackery/doomsday-rule.quackery @@ -0,0 +1,26 @@ + [ dup 400 mod 0 = iff [ drop true ] done + dup 100 mod 0 = iff [ drop false ] done + 4 mod 0 = ] is leap ( y --> b ) + + [ dup 4 mod 5 * + over 100 mod 4 * + + swap 400 mod 6 * + 2 + 7 mod ] is doomsday ( y --> n ) + + [ leap iff [ ' [ table 0 4 1 ] ] + else [ ' [ table 0 3 7 ] ] + ' [ 7 4 2 6 4 1 5 3 7 5 ] join do ] is close ( m y --> n ) + + [ dup doomsday unrot close - + 7 mod ] is weekday ( d m y --> n ) + + [ [ table $ "Sunday" $ "Monday" + $ "Tuesday" $ "Wednesday" $ "Thursday" + $ "Friday" $ "Saturday" ] do echo$ ] is echoday ( d --> ) + + ' [ [ 6 1 1800 ] + [ 29 3 1875 ] + [ 7 12 1915 ] + [ 23 12 1970 ] + [ 14 5 2043 ] + [ 12 2 2077 ] + [ 2 4 2101 ] ] + witheach [ unpack weekday echoday cr ] diff --git a/Task/Doomsday-rule/Refal/doomsday-rule.refal b/Task/Doomsday-rule/Refal/doomsday-rule.refal new file mode 100644 index 0000000000..611e530466 --- /dev/null +++ b/Task/Doomsday-rule/Refal/doomsday-rule.refal @@ -0,0 +1,43 @@ +$ENTRY Go { + , (1800 1 6) (1875 3 29) (1915 12 7) (1970 12 23) + (2043 5 14) (2077 2 12) (2101 4 2): e.Tests + = ; +}; + +Test { + e.Test = >; +}; + +LeapYear { + s.Year = > + > + >>>; +}; + +Weekday { + s.Year s.Month s.Day, + 4 1 7 4 2 6 4 1 5 3 7 5: e.LeapDoom, + 3 7 7 4 2 6 4 1 5 3 7 5: e.NormDoom, + Sunday Monday Tuesday Wednesday Thursday Friday Saturday: e.Days, + : (s.C) s.R, + : (s.S) s.T, + >> 7>: s.CAn, + >>> 7>: s.Doom, + (e.LeapDoom) (e.NormDoom)>: (e.DoomTab), + e.DoomTab>: e.Anchor, + e.Anchor>> 7>: s.Weekday + = ; +}; + +Item { + 0 s.X e.XS = s.X; + s.N s.X e.XS = e.XS>; +}; + +If { True t.T t.F = t.T; False t.T t.F = t.F; }; +Eq { t.X t.X = True; t.X t.Y = False; }; +Or { True s.Y = True; False s.Y = s.Y; }; +And { False s.Y = False; True s.Y = s.Y; }; +Not { True = False; False = True; }; +Neq { t.X t.Y = >; }; +Each { (e.F) = ; (e.F) (e.X) e.XS = ; }; diff --git a/Task/Doomsday-rule/SETL/doomsday-rule.setl b/Task/Doomsday-rule/SETL/doomsday-rule.setl new file mode 100644 index 0000000000..cf225f497f --- /dev/null +++ b/Task/Doomsday-rule/SETL/doomsday-rule.setl @@ -0,0 +1,29 @@ +program doomsday; + tests := [[1800,1,6], [1875,3,29], [1915,12,7], [1970,12,23], + [2043,5,14], [2077,2,12], [2101,4,2]]; + + loop for [year, month, day] in tests do + print(str day + "/" + str month + "/" + str year + ": " + + weekday(year, month, day)); + end loop; + + proc leap(y); + return y mod 4 = 0 and (y mod 100 /= 0 or y mod 400 = 0); + end proc; + + proc weekday(year, month, day); + leapdoom := [4,1,7,4,2,6,4,1,5,3,7,5]; + normdoom := [3,7,7,4,2,6,4,1,5,3,7,5]; + weekdays := ["Sunday","Monday","Tuesday","Wednesday","Thursday", + "Friday","Saturday"]; + + c := year div 100; + r := year mod 100; + s := r div 12; + t := r mod 12; + c_anchor := (5 * (c mod 4) + 2) mod 7; + doom := (s + t + (t div 4) + c_anchor) mod 7; + anchor := if leap(year) then leapdoom else normdoom end(month); + return weekdays((doom+day-anchor+7) mod 7+1); + end proc; +end program; diff --git a/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh b/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh index 10334c8be4..891530b914 100644 --- a/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh +++ b/Task/Doomsday-rule/UNIX-Shell/doomsday-rule.sh @@ -5,14 +5,14 @@ day-of-the-week() then local -ra names=({Sun,Mon,Tues,Wednes,Thurs,Fri,Satur}day) doomsday=({37,41}7426415375) local -i i c s t a b - local -i {year,month,day}=${BASH_REMATCH[++i]} + local -i {y,m,d}=${BASH_REMATCH[++i]} echo ${names[ - c=year/100, - s=(year%100)/12, - t=(year % 100) % 12, + c=y/100, + s=(y%100)/12, + t=(y % 100) % 12, a=(5*(c%4)+2) % 7, b=(s + t + (t / 4) + a ) % 7, - (b + day - ${doomsday[(year%4 == 0) && ((year%100) || (year%400 == 0))]:month-1:1} + 7) % 7 + (b + d - ${doomsday[(y%4 == 0) && ((y%100) || (y%400 == 0))]:m-1:1} + 7) % 7 ]} else return 1 fi diff --git a/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v b/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v index bc6194f84e..002a8b84fc 100644 --- a/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v +++ b/Task/Doomsday-rule/V-(Vlang)/doomsday-rule.v @@ -1,5 +1,4 @@ -const -( +const ( days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] first_days_common = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] first_days_leap = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] @@ -24,15 +23,11 @@ fn main() { d = date[8..10].int() a = anchor_day(y) f = first_days_common[m] - if is_leap_year(y) { - f = first_days_leap[m] - } + if is_leap_year(y) {f = first_days_leap[m]} w = d - f - if w < 0 { - w = 7 + w - } + if w < 0 {w = 7 + w} dow = (a + w) % 7 - println('$date -> ${days[dow]}') + println("$date -> ${days[dow]}") } } diff --git a/Task/Dot-product/Zig/dot-product.zig b/Task/Dot-product/Zig/dot-product.zig index 82ecb11802..1118520c95 100644 --- a/Task/Dot-product/Zig/dot-product.zig +++ b/Task/Dot-product/Zig/dot-product.zig @@ -1,10 +1,9 @@ const std = @import("std"); -const Vector = std.meta.Vector; pub fn main() !void { - const a: Vector(3, i32) = [_]i32{1, 3, -5}; - const b: Vector(3, i32) = [_]i32{4, -2, -1}; - var dot: i32 = @reduce(.Add, a*b); + const a = @Vector(3, i32){ 1, 3, -5 }; + const b = @Vector(3, i32){ 4, -2, -1 }; + const dot: i32 = @reduce(.Add, a * b); try std.io.getStdOut().writer().print("{d}\n", .{dot}); } diff --git a/Task/Doubly-linked-list-Definition/FutureBasic/doubly-linked-list-definition.basic b/Task/Doubly-linked-list-Definition/FutureBasic/doubly-linked-list-definition.basic new file mode 100644 index 0000000000..32155d51d0 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/FutureBasic/doubly-linked-list-definition.basic @@ -0,0 +1,67 @@ +begin globals + str255 List(8) //create a new list of strings (List(0) not used +end globals + + +local fn ShowList(title As str255) + //display all elements from list of string + short j + Print title; + For j = 1 to 7 + Print List(j); " "; + Next j + Print "" +End fn + + +/////////// MAIN PROGRAM //////////// + +Dim As str255 item //items to add to the list +Dim As short i,j, c = 0 + +//the list of data that will be added to the list +data: +Data "One", "Two", "Three", "Four", "Five", "Six", "EndOfData" + +Restore +c = 0 +Do + Read item + If item <> "EndOfData" Then List(c) = item + c ++ +Until item = "EndOfData" + +str255 ListTMP(7) + +For j = 1 To 7 + ListTMP(7-j) = List(j) +Next j +For j = 1 To 7 + Swap List(j), ListTMP(j) +Next j +fn ShowList("Insertion at Head: ") + +for i = 1 to 7 : List(i) = "" : next i // clear list +Restore +c = 0 +Do + Read item //: c += 1 + If item <> "EndOfData" Then List(c) = item + c ++ +Until item = "EndOfData" +fn ShowList("Insertion at Tail: ") + +for i = 1 to 7 : List(i) = "" : next i // clear list +Restore +c = 0 +Do + Read item //: c += 1 + If item <> "EndOfData" Then List(c) = item + c ++ +Until item = "EndOfData" + +Swap List(3), List(6) +fn ShowList("Insertion in Middle: ") + + +handleevents diff --git a/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg b/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg index 55d2235f9e..4d180563f7 100644 --- a/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg +++ b/Task/Dragon-curve/ALGOL-68/dragon-curve-4.alg @@ -53,7 +53,7 @@ BEGIN # Dragon Curve in SVG # put( svg file, ( "'/>", newline, "", newline ) ); close( svg file ) - FI # sierpinski square # ; + FI # dragon curve # ; dragon curve( "dragon.svg", 1200, 5, 12, 400, 200 ) diff --git a/Task/Dragon-curve/ASIC/dragon-curve.asic b/Task/Dragon-curve/ASIC/dragon-curve.asic new file mode 100644 index 0000000000..5697f69b99 --- /dev/null +++ b/Task/Dragon-curve/ASIC/dragon-curve.asic @@ -0,0 +1,130 @@ +REM Dragon curve +DIM S@(7) +DIM C@(7) +DIM R(27) +REM SIN, COS in arrays for PI/4 multipl. +DATA 0@, 0.70711@, 1@, 0.70711@, 0@, -0.70711@, -1@, -0.70711@ +DATA 1@, 0.70711@, 0@, -0.70711@, -1@, -0.70711@, 0@, 0.70711@ +Sqrt2@ = 1.41421@ +FOR I = 0 TO 7 + READ S@(I) +NEXT I +FOR I = 0 TO 7 + READ C@(I) +NEXT I +Level = 17 +Insize@ = 256 +REM Insize@ = 2^WHOLE_NUM looks fine +X@ = 224 +Y@ = 124 +RotQPi = 0 +RQ = 1 +SCREEN 9 +GOSUB Dragon: +LOCATE 20, 1 +PRINT "Press any key to exit." +Loop: + X$=INKEY$ + IF X$="" THEN Loop: +SCREEN 0 +END + +Dragon: +RotQPi = RotQPi MOD 8 +WHILE RotQPi < 0 + RotQPi = RotQPi + 8 +WEND +IF Level <= 1 THEN + YN@ = S@(RotQPi) * Insize@ + YN@ = YN@ + Y@ + XN@ = C@(RotQPi) * Insize@ + XN@ = XN@ + X@ + GOSUB DrawLine: + X@ = XN@ + Y@ = YN@ +ELSE + Insize@ = Insize@ * Sqrt2@ + Insize@ = Insize@ / 2@ + RotQPi = RotQPi + RQ + RotQPi = RotQPi MOD 8 + WHILE RotQPi < 0 + RotQPi = RotQPi + 8 + WEND + Level = Level - 1 + R(Level) = RQ + RQ = 1 + GOSUB Dragon: + RLevelM2 = R(Level) * 2 + RotQPi = RotQPi - RLevelM2 + RotQPi = RotQPi MOD 8 + WHILE RotQPi < 0 + RotQPi = RotQPi + 8 + WEND + RQ = -1 + GOSUB Dragon: + RQ = R(Level) + RotQPi = RotQPi + RQ + RotQPi = RotQPi MOD 8 + WHILE RotQPi < 0 + RotQPi = RotQPi + 8 + WEND + Level = Level + 1 + Insize@ = Insize@ * Sqrt2@ +ENDIF +RETURN + +DrawLine: +REM Draw a line from (X@, Y@) to (XN@, YN@) +REM Coordinates decimal, but converted in PSET. +DX@ = XN@ - X@ +DY@ = YN@ - Y@ +AbsDX@ = ABS(DX@) +AbsDY@ = ABS(DY@) +IF AbsDX@ <= AbsDY@ THEN + REM More vertical line + IF AbsDY@ <= 1@ THEN + REM The same pixel or neighboring ones, because AbsDX@ <= AbsDY@ <= 1. + PSET (Y@, X@), 10 + PSET (YN@, XN@), 10 + ELSE + REM There are pixels in between. + A@ = DX@ / DY@ + IF YN@ >= Y@ THEN + D@ = 1@ + ELSE + D@ = -1@ + ENDIF + CoordY@ = Y@ + WHILE CoordY@ <= YN@ + CoordX@ = CoordY@ - Y@ + CoordX@ = A@ * CoordX@ + CoordX@ = X@ + CoordX@ + PSET (CoordY@, CoordX@), 10 + CoordY@ = CoordY@ + D@ + WEND + ENDIF +ELSE + REM More horizontal line + IF AbsDX@ <= 1@ THEN + REM The same pixel or neighboring ones, because AbsDY@ < AbsDX@ <= 1. + PSET (Y@, X@), 10 + PSET (YN@, XN@), 10 + ELSE + REM There are pixels in between. + A@ = DY@ / DX@ + IF XN@ >= X@ THEN + D@ = 1@ + ELSE + D@ = -1@ + ENDIF + CoordX@ = X@ + WHILE CoordX@ <= XN@ + CoordY@ = CoordX@ - X@ + CoordY@ = A@ * CoordY@ + CoordY@ = Y@ + CoordY@ + PSET (CoordY@, CoordX@), 10 + CoordX@ = CoordX@ + D@ + WEND + ENDIF +ENDIF +RETURN diff --git a/Task/Dragon-curve/Applesoft-BASIC/dragon-curve.basic b/Task/Dragon-curve/Applesoft-BASIC/dragon-curve.basic new file mode 100644 index 0000000000..b9f8bff709 --- /dev/null +++ b/Task/Dragon-curve/Applesoft-BASIC/dragon-curve.basic @@ -0,0 +1,37 @@ +10 REM Dragon curve +20 DEF FN MOD(M) = M - INT(M / 8) * 8 +30 REM SIN, COS in arrays for PI/4 multipl. +40 DIM S(7), C(7) +50 QPI = ATN(1): SQ = SQR(2) +60 FOR I = 0 TO 7 +70 S(I) = SIN(I * QPI): C(I) = COS(I * QPI) +80 NEXT I +90 LEVEL = 15 +100 INSIZE = 128: REM 2^WHOLE_NUM (looks better) +110 X = 98: Y = 68 +120 ROTQPI = 0: RQ = 1 +130 DIM R(LEVEL) +140 HGR2: HCOLOR = 1 +150 GOSUB 170 +160 END +170 REM ** Dragon +180 ROTQPI = FN MOD8(ROTQPI) +190 IF LEVEL > 1 THEN GOTO 250 +200 YN = S(ROTQPI) * INSIZE + Y +210 XN = C(ROTQPI) * INSIZE + X +220 HPLOT X, Y TO XN, YN +230 X = XN: Y = YN +240 RETURN +250 INSIZE = INSIZE * SQ / 2 +260 ROTQPI = FN MOD8(ROTQPI + RQ) +270 LEVEL = LEVEL - 1 +280 R(LEVEL) = RQ: RQ = 1 +290 GOSUB 170 +300 ROTQPI = FN MOD8(ROTQPI - R(LEVEL) * 2) +310 RQ = -1 +320 GOSUB 170 +330 RQ = R(LEVEL) +340 ROTQPI = FN MOD8(ROTQPI + RQ) +350 LEVEL = LEVEL + 1 +360 INSIZE = INSIZE * SQ +370 RETURN diff --git a/Task/Dragon-curve/Nascom-BASIC/dragon-curve.basic b/Task/Dragon-curve/Nascom-BASIC/dragon-curve.basic new file mode 100644 index 0000000000..2f42679f86 --- /dev/null +++ b/Task/Dragon-curve/Nascom-BASIC/dragon-curve.basic @@ -0,0 +1,54 @@ +10 REM Dragon curve +20 REM SIN, COS in arrays for PI/4 multipl. +30 DIM S(7), C(7) +40 QPI=ATN(1):SQ=SQR(2) +50 FOR I=0 TO 7 +60 S(I)=SIN(I*QPI):C(I)=COS(I*QPI) +70 NEXT I +80 LEVEL=15 +90 INSIZE=32:REM 2^WHOLE_NUM (looks better) +100 X=34:Y=16 +110 ROTQPI=0:RQ=1 +120 DIM R(LEVEL) +130 CLS +140 GOSUB 160 +150 END +160 REM ** Dragon +170 ROTQPI=ROTQPI AND 7 +180 IF LEVEL>1 THEN GOTO 240 +190 YN=S(ROTQPI)*INSIZE+Y +200 XN=C(ROTQPI)*INSIZE+X +210 GOSUB 370 +220 X=XN:Y=YN +230 RETURN +240 INSIZE=INSIZE*SQ/2 +250 ROTQPI=(ROTQPI+RQ)AND 7 +260 LEVEL=LEVEL-1 +270 R(LEVEL)=RQ:RQ=1 +280 GOSUB 160 +290 ROTQPI=(ROTQPI-R(LEVEL)*2)AND 7 +300 RQ=-1 +310 GOSUB 160 +320 RQ=R(LEVEL) +330 ROTQPI=(ROTQPI+RQ)AND 7 +340 LEVEL=LEVEL+1 +350 INSIZE=INSIZE*SQ +360 RETURN +370 REM ** Draw a line from (X, Y) to (XN, YN) +380 IF ABS(XN-X)>1 OR ABS(YN-Y)>1 THEN 400 +390 SET(X,Y):SET(XN,YN):RETURN +400 IF ABS(XN-X)>ABS(YN-Y) THEN 480 +410 REM More vertical line +420 A=(XN-X)/(YN-Y) +430 IF YN>Y THEN D=1 ELSE D=-1 +440 FOR YC=Y TO YN STEP D +450 SET(X+A*(YC-Y),YC) +460 NEXT YC +470 RETURN +480 REM More horizontal line +490 A=(YN-Y)/(XN-X) +500 IF XN>X THEN D=1 ELSE D=-1 +510 FOR XC=X TO XN STEP D +520 SET(XC,Y+A*(XC-X)) +530 NEXT XC +540 RETURN diff --git a/Task/Draw-a-clock/Atari-BASIC/draw-a-clock.basic b/Task/Draw-a-clock/Atari-BASIC/draw-a-clock.basic new file mode 100644 index 0000000000..ef54e7f437 --- /dev/null +++ b/Task/Draw-a-clock/Atari-BASIC/draw-a-clock.basic @@ -0,0 +1,45 @@ +10 GRAPHICS 7:DEG +20 PRINT "Please enter current time (HH,MM):" +30 INPUT HH,MM:GRAPHICS 7+16 +40 FPS=60:REM SYSTEM CAN BE EITHER NTSC OR PAL +50 IF PEEK(53268)=1 THEN FPS=50 +60 MINUTE=60*FPS +70 XC=80:YC=40:R=35:RF=38 +80 GOSUB 800 +90 SETCOLOR 0,3,10:SETCOLOR 4,8,2:SETCOLOR 2,13,14 +100 POKE 19,0:POKE 20,0:SS=0:REM RESET FOR NEXT MINUTE +200 COLOR 0:IF SS>0 THEN 230 +210 PLOT XC,YC:DRAWTO HX,HY +220 PLOT XC,YC:DRAWTO MX,MY +230 PLOT XC,YC:DRAWTO SX,SY +240 GOSUB 500 +250 COLOR 2 +260 PLOT XC,YC:DRAWTO HX,HY +270 PLOT XC,YC:DRAWTO MX,MY +280 COLOR 1 +290 PLOT XC,YC:DRAWTO SX,SY +300 JIFFIES=256*PEEK(19)+PEEK(20) +310 NSEC=INT(JIFFIES/FPS):IF NSEC=60 THEN GOSUB 400:GOTO 100 +320 IF NSEC>SS THEN SS=NSEC:GOTO 2OO +330 GOTO 300 +400 REM INCREASE MINUTE AND HOUR +410 MM=MM+1 +420 IF MM=60 THEN MM=0:HH=HH+1 +430 IF HH=24 THEN HH=0 +440 REM DISABLE SCREEN SAVER/ATTRACT MODE +450 POKE 77,0 +460 RETURN +500 IF SS>0 THEN 550:REM CALCULATE X AND Y POSITIONS OF HANDS +510 HX=XC+R*SIN(30*HH+MM/2)*0.5 +520 HY=YC-R*COS(30*HH+MM/2)*0.5 +530 MX=XC+R*SIN(6*MM) +540 MY=YC-R*COS(6*MM) +550 SX=XC+R*SIN(6*SS) +560 SY=YC-R*COS(6*SS) +570 RETURN +800 REM DRAW CLOCK FACE +810 COLOR 3 +820 FOR I=30 TO 360 STEP 30 +830 PLOT XC+RF*SIN(I),YC-RF*COS(I) +840 NEXT I +850 RETURN diff --git a/Task/Draw-a-clock/EasyLang/draw-a-clock.easy b/Task/Draw-a-clock/EasyLang/draw-a-clock.easy index 7d2dc2ddee..6befc2a8d8 100644 --- a/Task/Draw-a-clock/EasyLang/draw-a-clock.easy +++ b/Task/Draw-a-clock/EasyLang/draw-a-clock.easy @@ -1,5 +1,4 @@ proc draw hour min sec . . - # dial color 333 move 50 50 circle 45 @@ -16,18 +15,15 @@ proc draw hour min sec . . move 50 + sin a * 40 50 + cos a * 40 circle 1 . - # hour linewidth 2 color 000 a = (hour * 60 + min) / 2 move 50 50 line 50 + sin a * 32 50 + cos a * 32 - # min linewidth 1.5 a = (sec + min * 60) / 10 move 50 50 line 50 + sin a * 40 50 + cos a * 40 - # sec linewidth 1 color 700 a = sec * 6 @@ -41,11 +37,9 @@ on timer sec = number substr h$ 18 2 min = number substr h$ 15 2 hour = number substr h$ 12 2 - if hour > 12 - hour -= 12 - . + if hour > 12 : hour -= 12 draw hour min sec . - timer 0.1 + timer 0.05 . timer 0 diff --git a/Task/Duffinian-numbers/Forth/duffinian-numbers.fth b/Task/Duffinian-numbers/Forth/duffinian-numbers.fth new file mode 100644 index 0000000000..264737eeb8 --- /dev/null +++ b/Task/Duffinian-numbers/Forth/duffinian-numbers.fth @@ -0,0 +1,61 @@ +: gcd ( u1 u2 -- u3 ) + dup 0= if drop exit then + tuck mod recurse ; + +: duffinian? ( u -- ? ) + dup 2 = if drop false exit then + 1 >r dup 2 + begin + over 2 mod 0= + while + dup r> + >r 2* swap 2/ swap + repeat + drop 3 + begin + 2dup dup * >= + while + dup 1 >r + begin + 2 pick 2 pick mod 0= + while + dup r> + >r over * >r tuck / swap r> + repeat + 2r> * >r drop 2 + + repeat + drop + 2dup = if 2drop rdrop false exit then + dup 1 > if 1+ r> * else drop r> then + gcd 1 = ; + +: main + ." First 50 Duffinian numbers:" cr + 0 1 + begin + over 50 < + while + dup duffinian? if + dup 3 .r + swap 1+ swap + over 10 mod 0= if cr else space then + then + 1+ + repeat + 2drop + cr ." First 30 Duffinian triplets:" cr + 0 >r 0 1 + begin + r@ 30 < + while + dup duffinian? if swap 1+ swap else nip 0 swap then + over 3 = if + r> 1+ >r + dup 2 - 5 .r space + dup 1- 5 .r space + dup 5 .r cr + then + 1+ + repeat + rdrop 2drop ; + +main +bye diff --git a/Task/Duffinian-numbers/Lua/duffinian-numbers.lua b/Task/Duffinian-numbers/Lua/duffinian-numbers.lua new file mode 100644 index 0000000000..a8422b4049 --- /dev/null +++ b/Task/Duffinian-numbers/Lua/duffinian-numbers.lua @@ -0,0 +1,58 @@ +function gcd(a, b) + while b ~= 0 do + a, b = b, a % b + end + return a +end + +function duffinian(n) + if n == 2 then return false end + local total = 1 + local power = 2 + local m = n + while (n & 1) == 0 do + total = total + power + power = power << 1 + n = n >> 1 + end + local p = 3 + while p * p <= n do + local sum = 1 + local power = p + while n % p == 0 do + sum = sum + power + power = power * p + n = n / p + end + total = total * sum + p = p + 2 + end + if m == n then return false end + if n > 1 then total = total * (n + 1) end + return gcd(total, m) == 1 +end + +print("First 50 Duffinian numbers:") +count = 0 +n = 1 +while count < 50 do + if duffinian(n) then + count = count + 1 + if count % 10 == 0 then space = 10 else space = 32 end + io.write(string.format('%3d%c', n, space)) + end + n = n + 1 +end + +print("\nFirst 30 Duffinian triplets:") +n = 1 +m = 0 +count = 0 +while count < 30 do + if duffinian(n) then m = m + 1 else m = 0 end + if m == 3 then + count = count + 1 + print(string.format('%d, %d, %d', n - 2, n - 1, n)) + end + n = n + 1 +end diff --git a/Task/Duffinian-numbers/Refal/duffinian-numbers.refal b/Task/Duffinian-numbers/Refal/duffinian-numbers.refal new file mode 100644 index 0000000000..576fa3f49d --- /dev/null +++ b/Task/Duffinian-numbers/Refal/duffinian-numbers.refal @@ -0,0 +1,76 @@ +$ENTRY Go { + = + >> + + + >; +}; + +ShowTriple { + s.N = >; +}; + +Each { + s.F = ; + s.F t.I e.X = ; +}; + +Group { + s.N = ; + s.N e.X, : (e.1) e.2 = (e.1) ; +}; + +Gen { + s.N s.F = ; + 0 s.F s.I = ; + s.N s.F s.I, : { + True = s.I s.F >; + False = >; + }; +}; + +DuffinianTriple { + s.N, + > + >: True True True = True; + s.N = False; +}; + +Duffinian { + s.N, : s.S, + : s.P, + s.S : { + s.P s.1 = False; + s.Q 1 = True; + s.1 s.2 = False; + }; +}; + +Gcd { + s.A 0 = s.A; + s.A s.B = >; +}; + +SigmaSum { + s.N = 2 >; + s.N s.Sum s.D s.Max, : '+' = s.Sum; + s.N s.Sum s.D s.Max, : s.N = ; + s.N s.Sum s.D s.Max, : 0 = + >> + s.Max>; + s.N s.Sum s.D s.Max = s.Max>; +}; + +Sqrt { + 0 = 1; + 1 = 1; + s.N = >; + s.N s.X0, +
> 2>: s.X1, + : { + '+' = ; + s.C = s.X0; + }; +}; diff --git a/Task/Duffinian-numbers/SETL/duffinian-numbers.setl b/Task/Duffinian-numbers/SETL/duffinian-numbers.setl new file mode 100644 index 0000000000..792e5adddc --- /dev/null +++ b/Task/Duffinian-numbers/SETL/duffinian-numbers.setl @@ -0,0 +1,48 @@ +program duffinian_numbers; + init sigma := divisor_sum_table(20000); + + print("First 50 Duffinian numbers:"); + loop for n in first(50, routine is_duffinian) do + nprint(lpad(str n, 6)); + if (col +:= 1) mod 10 = 0 then print; end if; + end loop; + + print; + print("First 15 Duffinian triplets:"); + loop for n in first(15, routine is_duffinian_triplet) do + print(+/[lpad(str i, 6) : i in [n,n+1,n+2]]); + end loop; + + proc first(num, pred); + ls := []; + loop while #ls < num do + loop until call(pred, n) do + n +:= 1; + end loop; + ls with:= n; + end loop; + return ls; + end proc; + + proc is_duffinian_triplet(n); + return and/[is_duffinian(i) : i in [n,n+1,n+2]]; + end proc; + + proc is_duffinian(n); + return sigma(n) > n+1 and gcd(n, sigma(n)) = 1; + end proc; + + proc gcd(a,b); + return if b=0 then a else gcd(b, a mod b) end; + end proc; + + proc divisor_sum_table(sz); + ds := [0] * sz; + loop for i in [1..sz] do + loop for j in [i,i+i..sz] do + ds(j) +:= i; + end loop; + end loop; + return ds; + end proc; +end program; diff --git a/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic b/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic index 59c514fbfe..f7c621a282 100644 --- a/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic +++ b/Task/Dutch-national-flag-problem/FutureBasic/dutch-national-flag-problem.basic @@ -1,39 +1,39 @@ void local fn DrawBalls( y as long, balls as CFArrayRef, sort as BOOL ) -long col, prevCol = 0, x = 10 -CFArrayRef cols = @[fn ColorWithSRGB(.78,.06,.18,1.0),fn ColorWhite,fn ColorWithSRGB(0,.24,.65,1.0)] -if ( sort ) then balls = fn ArraySortedArrayUsingSelector( balls, @"compare:" ) + long col, prevCol = 0, x = 10 + CFArrayRef cols = @[fn ColorWithSRGB(.78,.06,.18,1.0),fn ColorWhite,fn ColorWithSRGB(0,.24,.65,1.0)] + if ( sort ) then balls = fn ArraySortedArrayUsingSelector( balls, @"compare:" ) -pen -1 -for long i = 0 to len(balls) - 1 -col = intval(balls[i]) -if ( sort == YES ) -if ( col != prevCol ) then y += 30 : x = 10 -else -if ( i > 0 && i % 15 == 0 ) then y += 30 : x = 10 -end if -oval fill (x,y,30,30), cols[col] -x += 30 -prevCol = col -next + pen -1 + for long i = 0 to len(balls) - 1 + col = intval(balls[i]) + if ( sort == YES ) + if ( col != prevCol ) then y += 30 : x = 10 + else + if ( i > 0 && i % 15 == 0 ) then y += 30 : x = 10 + end if + oval fill (x,y,30,30), cols[col] + x += 30 + prevCol = col + next end fn void local fn DutchNationalFlagProblem -window 1, @"Dutch national flag problem", (0,0,470,230) -WindowSetBackgroundColor( 1, fn ColorWithSRGB(1.0,.61,0,1.0) ) + window 1, @"Dutch national flag problem", (0,0,470,230) + WindowSetBackgroundColor( 1, fn ColorWithSRGB(1.0,.61,0,1.0) ) -CFMutableArrayRef balls = fn MutableArrayNew + CFMutableArrayRef balls = fn MutableArrayNew -text @"Menlo-Bold",, fn ColorWhite + text @"Menlo-Bold",, fn ColorWhite -for long i = 0 to 29 -balls[i] = @(rnd(3)-1) -next + for long i = 0 to 29 + balls[i] = @(rnd(3)-1) + next -print @"Unsorted:" -fn DrawBalls( 20, balls, NO ) + print @"Unsorted:" + fn DrawBalls( 20, balls, NO ) -print %(3,100)@"Sorted:" -fn DrawBalls( 120, balls, YES ) + print %(3,100)@"Sorted:" + fn DrawBalls( 120, balls, YES ) end fn random diff --git a/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-1.m2000 b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-1.m2000 new file mode 100644 index 0000000000..12e0137b20 --- /dev/null +++ b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-1.m2000 @@ -0,0 +1,23 @@ + SortElse=lambda white (a(), &swaps, &compares)->{ + long mid=white + long i, j, k=len(a())-1 + while j<=k + + if a(j)mid then + compares+=2 + swap a(j), a(k) + swaps++ + k-- + else + compares+=2 + j++ + end if + end while + =a() + } diff --git a/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-2.m2000 b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-2.m2000 new file mode 100644 index 0000000000..acaf408117 --- /dev/null +++ b/Task/Dutch-national-flag-problem/M2000-Interpreter/dutch-national-flag-problem-2.m2000 @@ -0,0 +1,88 @@ +function Dutch_national_flag_problem { + enum bands {red=1, white, blue} + s=red + check_in_order=lambda s, (a as array) ->{ + boolean true=@true, false + k=each(a) + m=s + Z=S + =true + while k + z=array(k) + if m=z else + if m=blue then + =false + break + else + m++ + if m=z else =false : break + end if + end if + end while + } + SortElse=lambda (m(), &swaps, &compares)->{ + long t=len(m()) + dim c(1 to 3)=t + c=1 + for i=0 to len(m())-1 + rem ? "pos:";i;" "; + w=m(i) + if w0 + if c(k)=t then k-- : continue + if m(j)c(k) then c(m(j))=c(k) + rem ? "swap:";m(j);" at pos "+j;" with ";m(c(k)); " at pos ";c(k) + swap m(j), m(c(k)) + rem ? "just swapped array :", m()#str$() + rem ? "c()", c()#str$() + swaps++ + j=c(k) + c(k)++ + end if + k-- + rem ? "k=";k, c(k) + end while + else.if w>c then + c=w + if i-c(c)>1 else c(c)=i + end if + next + =m() + } + random_band=lambda->random(1, 3) + n=random(10, 20) + if n<3 then exit ' need at least 3 colors for the flag - although n now didn't get value 3 we place it to remember it later + do + do + dim balls(n)< { - if size<1 then size=1 - randomitem=lambda a->a#val(random(0,2)) - dim a(size)<{ - Document r$=eval$(array(s)) - if len(s)>1 then - For i=1 to len(s)-1 { - r$=", "+eval$(array(s,i)) - } - end if - =r$ -} -TestSort$=lambda$ (s as array)-> { - ="unsorted: " - x=array(s) - for i=1 to len(s)-1 { - k=array(s,i) - if x>k then break - swap x, k - } - ="sorted: " -} -Positions=lambda mid=White (a as array) ->{ - m=len(a) - dim Base 0, b(m)=-1 - low=-1 - high=m - m-- - i=0 - medpos=stack - link a to a() - for i=m to 0 { - if a(i)<=mid then exit - high-- - b(high)=high - } - for i=0 to m { - if a(i)>=mid then exit - low++ - b(low)=low - } - if high-low>1 then - for i=low+1 to high-1 { - select case a(i)<=>Mid - case -1 - low++ : b(low)=i - case 1 - { - high-- :b(high)=i - if High0 then - dim c() - c()=array(medpos) - stock c(0) keep len(c()), b(low+1) - for i=low+1 to high-1 - if b(i)>low and b(i)i then swap b(b(i)), b(i) - next i - end if - if low>0 then - for i=0 to low - if b(i)<=low and b(i)<>i then swap b(b(i)), b(i) - next - end if - if High=High and b(i)<>i then swap b(b(i)), b(i) - next - end if - =b() -} -InPlace=Lambda (&p(), &Final()) ->{ - def i=0, j=-1, k=-1, many=0 - for i=0 to len(p())-1 - if p(i)<>i then - j=i - z=final(j) - do - final(j)=final(p(j)) - k=j - j=p(j) - p(k)=k - many++ - until j=i - final(k)=z - end if - next - =many -} - - -Dim final(), p(), second(), p1() -Rem final()=(White,Red,Blue,White,Red, Red, Blue) -Rem final()=(white, blue, red, blue, white) - -final()=fillarray(30) -Print "Items: ";len(final()) -Report TestSort$(final())+Display$(final()) -\\ backup for final() for second example -second()=final() -p()=positions(final()) -\\ backup p() to p1() for second example -p1()=p() - - -Report Center, "InPlace" -rem Print p() ' show array items -many=InPlace(&p(), &final()) -rem print p() ' show array items -Report TestSort$(final())+Display$(final()) -print "changes: "; many - - -Report Center, "Using another array to make the changes" -final()=second() -\\ using a second array to place only the changes -item=each(p1()) -many=0 -While item { - if item^=array(item) else final(item^)=second(array(item)) : many++ -} -Report TestSort$(final())+Display$(final()) -print "changes: "; many -Module three_way_partition (A as array, mid as balls, &swaps) { - Def i, j, k - k=Len(A) - Link A to A() - While j < k - if A(j) < mid Then - Swap A(i), A(j) - swaps++ - i++ - j++ - Else.if A(j) > mid Then - k-- - Swap A(j), A(k) - swaps++ - Else - j++ - End if - End While -} -Many=0 -Z=second() -Print -Report center, {Three Way Partition -} -Report TestSort$(Z)+Display$(Z) -three_way_partition Z, White, &many -Print -Report TestSort$(Z)+Display$(Z) -Print "changes: "; many diff --git a/Task/Eban-numbers/FutureBasic/eban-numbers.basic b/Task/Eban-numbers/FutureBasic/eban-numbers.basic new file mode 100644 index 0000000000..e1246b9d9b --- /dev/null +++ b/Task/Eban-numbers/FutureBasic/eban-numbers.basic @@ -0,0 +1,50 @@ +void local fn Eban( start as NSUInteger, finish as NSUInteger, printable as BOOL ) + NSUInteger i, b, r, m, t, count + + if ( start = 2 ) + printf @"eban numbers up to and including %lu", finish + else + printf @"eban numbers between %lu and %lu:", start, finish + end if + + count = 0 + for i = start to finish step 2 + b = int(i / 100000000) + r = i % 100000000 + m = int(r / 1000000) + r = i % 1000000 + t = int(r / 1000) + r = r % 1000 + if m >= 30 && m <= 66 then m = (m % 10) + if t >= 30 && t <= 66 then t = (t % 10) + if r >= 30 && r <= 66 then r = (r % 10) + if b = 0 || b = 2 || b = 4 || b = 6 + if m = 0 || m = 2 || m = 4 || m = 6 + if t = 0 || t = 2 || t = 4 || t = 6 + if r = 0 || r = 2 || r = 4 || r = 6 + if printable == YES then printf @"%lu \b", i + count++ + end if + end if + end if + end if + next + if printable == YES then print + printf @"%lu eban numbers found\n", count +end fn + +void local fn EbanNumbers + CFTimeInterval t = fn CACurrentMediaTime + fn Eban( 2, 1000, YES ) + fn Eban( 1000, 4000, YES ) + fn Eban( 2, 10000, NO ) + fn Eban( 2, 100000, NO ) + fn Eban( 2, 1000000, NO ) + fn Eban( 2, 10000000, NO ) + fn Eban( 2, 100000000, NO ) + printf @"Compute time: %.3f sec\n", fn CACurrentMediaTime - t +end fn + +fn EbanNumbers + +HandleEvents diff --git a/Task/Eban-numbers/OxygenBasic/eban-numbers.basic b/Task/Eban-numbers/OxygenBasic/eban-numbers.basic new file mode 100644 index 0000000000..ba5f4082c8 --- /dev/null +++ b/Task/Eban-numbers/OxygenBasic/eban-numbers.basic @@ -0,0 +1,54 @@ +uses console + +! GetTickCount lib "kernel32.dll" +double t1, t2 + +sub eban (start as int, ended as int, printable as int) + int contar + long i, b, r, m, t + + contar = 0 + if start = 2 then + printl "eban numbers up to and including " ended ":" + else + printl "eban numbers between " start " and " ended " (inclusive):" + end if + + for i = start to ended step 2 + b = (i \ 1000000000) + r = mod(i, 1000000000) + m = (r \ 1000000) + r = mod(i, 1000000) + t = (r \ 1000) + r = mod(r, 1000) + if m >= 30 and m <= 66 then m = mod(m, 10) + if t >= 30 and t <= 66 then t = mod(t, 10) + if r >= 30 and r <= 66 then r = mod(r, 10) + if b = 0 or b = 2 or b = 4 or b = 6 then + if m = 0 or m = 2 or m = 4 or m = 6 then + if t = 0 or t = 2 or t = 4 or t = 6 then + if r = 0 or r = 2 or r = 4 or r = 6 then + if printable then print i " "; + contar += 1 + end if + end if + end if + end if + next i + if printable then print cr + printl "count = " contar cr +end sub + +t1 = GetTickCount +call eban (2, 1000, 1) +call eban (1000, 4000, 1) +call eban (2, 10000, 0) +call eban (2, 100000, 0) +call eban (2, 1000000, 0) +call eban (2, 10000000, 0) +call eban (2, 100000000, 0) +t2 = GetTickCount +printl "Run time: " (t2-t1)/1000 " seconds." + +printl cr "Enter ..." +waitkey diff --git a/Task/Echo-server/FutureBasic/echo-server.basic b/Task/Echo-server/FutureBasic/echo-server.basic new file mode 100644 index 0000000000..f0a415f3d2 --- /dev/null +++ b/Task/Echo-server/FutureBasic/echo-server.basic @@ -0,0 +1,16 @@ +// Echo Server +// https://rosettacode.org/wiki/Echo_server# + +#plist NSAppleEventsUsageDescription @"Access to Apple Events is needed for this task." + +str255 theMessage +theMessage = "tell application " + CHR$(34) + "Terminal" + CHR$(34) + CHR$(10) + "activate" + CHR$(10)¬ ++ "do script " + CHR$(34) + "ssh ::1" + CHR$(34) + CHR$(10) + "end tell" + CHR$(10) + +AppleScriptRef script +script = fn AppleScriptWithSource( fn stringwithpascalstring (theMessage) ) +fn AppleScriptExecute( script, null ) + +// Sends ssh ::1 as a terminal command to open a connection to the local host +// You need to enable Sharing - Remote Login in System Settings for a succesful login. +// Otherwise you will get a Connection Refused message from the terminal. diff --git a/Task/Egyptian-division/FutureBasic/egyptian-division.basic b/Task/Egyptian-division/FutureBasic/egyptian-division.basic new file mode 100644 index 0000000000..44246587ac --- /dev/null +++ b/Task/Egyptian-division/FutureBasic/egyptian-division.basic @@ -0,0 +1,32 @@ +void local fn EgyptianDivision + int table(32, 2) + int i = 1, dividend = 580, divisor = 34 + int answer, accumulator + + table(i, 1) = 1 + table(i, 2) = divisor + + while ( table( i, 2 ) < dividend ) + i++ + table(i, 1) = table(i - 1, 1) * 2 + table(i, 2) = table(i - 1, 2) * 2 + wend + i-- + answer = table(i, 1) + accumulator = table(i, 2) + + while ( i > 1 ) + i-- + if table(i, 2) + accumulator <= dividend + answer += table(i, 1) + accumulator += table(i, 2) + end if + wend + + printf @"Using Egyptian Division %d / %d = %d remainder %d", dividend, divisor, answer, dividend - accumulator +end fn + + +fn EgyptianDivision + +HandleEvents diff --git a/Task/Egyptian-division/M2000-Interpreter/egyptian-division.m2000 b/Task/Egyptian-division/M2000-Interpreter/egyptian-division.m2000 new file mode 100644 index 0000000000..608f59ab55 --- /dev/null +++ b/Task/Egyptian-division/M2000-Interpreter/egyptian-division.m2000 @@ -0,0 +1,32 @@ +MODULE LIKEBASIC { + 100 REM Egyptian division + 110 DIM Table(0 TO 31, 0 TO 1) + 120 LET Dividend = 580 + 130 LET Divisor = 34 + 140 REM ** Division + 150 LET I = 0 + 160 LET Table(I, 0) = 1 + 170 LET Table(I, 1) = Divisor + 180 WHILE Table(I, 1) < Dividend + 190 LET I = I + 1 + 200 LET Table(I, 0) = Table(I - 1, 0) * 2 + 210 LET Table(I, 1) = Table(I - 1, 1) * 2 + 220 END WHILE + 230 LET I = I - 1 + 240 LET Answer = Table(I, 0) + 250 LET Accumulator = Table(I, 1) + 260 WHILE I > 0 + 270 LET I = I - 1 + 280 IF Table(I, 1) + Accumulator <= Dividend THEN + 290 LET Answer = Answer + Table(I, 0) + 300 LET Accumulator = Accumulator + Table(I, 1) + 310 END IF + 320 END WHILE + 330 REM ** Results + 340 PRINT Dividend; " divided by "; Divisor; " using Egytian division"; + 350 PRINT " returns "; Answer; " remainder "; Dividend - Accumulator + 360 END +} +' Change DO WHILE ...LOOP -> WHILE ...END WHILE +' Adding some space for string literals +LIKEBASIC diff --git a/Task/Elementary-cellular-automaton-Random-number-generator/ALGOL-68/elementary-cellular-automaton-random-number-generator.alg b/Task/Elementary-cellular-automaton-Random-number-generator/ALGOL-68/elementary-cellular-automaton-random-number-generator.alg new file mode 100644 index 0000000000..a495116d55 --- /dev/null +++ b/Task/Elementary-cellular-automaton-Random-number-generator/ALGOL-68/elementary-cellular-automaton-random-number-generator.alg @@ -0,0 +1,48 @@ +BEGIN # elementary cellular automaton - random number generation # + COMMENT returns the next state from state using rule s must be at least 2 characters long + and consist of # and - only + COMMENT + PROC next state = ( STRING state, INT rule )STRING: + BEGIN + COMMENT returns 1 or 0 depending on whether c = # or not COMMENT + OP TOINT = ( CHAR c )INT: IF c = "#" THEN 1 ELSE 0 FI; + # construct the state with additional extra elements to allow wrap-around # + STRING s = state[ UPB state ] + state + state[ LWB state : LWB state + 1 ]; + COMMENT convert rule to a string of # or - depending on whether the bits of r are on or off + COMMENT + STRING r := ""; + INT v := rule; + TO 8 DO + r +:= IF ODD v THEN "#" ELSE "-" FI; + v OVERAB 2 + OD; + STRING new state := ""; + FOR i FROM LWB s TO UPB s - 3 DO + CHAR c1 = s[ i ]; + CHAR c2 = s[ i + 1 ]; + CHAR c3 = s[ i + 2 ]; + INT pos := ( ( ( TOINT c1 * 2 ) + TOINT c2 ) * 2 ) + TOINT c3; + new state +:= r[ pos + 1 ] + OD; + new state + END # next state # ; + # get a pseudo-random byte from by evolving the state # + PROC get byte = ( REF STRING state, INT rule, element )INT: + BEGIN + BITS b := 16r0; + TO 8 DO + state := next state( state, rule ); + b := b SHL 1; + IF state[ element ] = "#" THEN b := b OR 16r1 FI + OD; + ABS b + END # get byte # ; + + BEGIN # test # + STRING rg state := "###############################################################-"; + TO 10 DO + print( ( " ", whole( get byte( rg state, 30, 1 ), 0 ) ) ) + OD; + print( ( newline ) ) + END +END diff --git a/Task/Empty-string/EMal/empty-string.emal b/Task/Empty-string/EMal/empty-string.emal index 4dd34da9b1..d6165ca73b 100644 --- a/Task/Empty-string/EMal/empty-string.emal +++ b/Task/Empty-string/EMal/empty-string.emal @@ -1,9 +1,9 @@ # Demonstrate how to assign an empty string to a variable. -text sampleA = Text.EMPTY -text sampleB = "hello world" -text sampleC = "" -List samples = text[sampleA, sampleB, sampleC] +text sampleA ← Text.EMPTY +text sampleB ← "hello world" +text sampleC ← "" +List samples ← text[sampleA, sampleB, sampleC] for each text sample in samples # Demonstrate how to check that a string is empty. - writeLine("Is '" + sample + "' empty? " + when(sample.isEmpty(), "Yes", "No") + ".") + writeLine("Is '", sample, "' empty? ", when(sample.isEmpty(), "Yes", "No"), ".") end diff --git a/Task/Entropy/FutureBasic/entropy.basic b/Task/Entropy/FutureBasic/entropy.basic new file mode 100644 index 0000000000..9ef9433d59 --- /dev/null +++ b/Task/Entropy/FutureBasic/entropy.basic @@ -0,0 +1,34 @@ +include "NSLog.incl" + +double local fn Entropy( array as CFArrayRef ) + CFMutableDictionaryRef count = fn MutableDictionaryNew + + for CFStringRef element in array + if ( count[element] ) + count[element] = @(fn NumberIntegerValue( count[element] ) + 1) + else + count[element] = @(1) + end if + next + + double entropy = 0.0 + NSUInteger total = fn ArrayCount( array ) + CFArrayRef valuesArr = fn DictionaryAllValues( count ) + + for CFNumberRef value in valuesArr + double p = fn NumberDoubleValue( value ) / total + entropy -= p * log(p) + next + return entropy / log(2) +end fn = 0.0 + +void local fn DoIt + CFStringRef string = @"1,2,2,3,3,3,4,4,4,4" + CFArrayRef characters = fn StringComponentsSeparatedByString( string, @"," ) + double result = fn Entropy( characters ) + NSLog( @"Entrophy of \"%@\": %.15f", fn StringByReplacingOccurrencesOfString( string, @",", @"" ), result ) +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Enumerations/Crystal/enumerations.cr b/Task/Enumerations/Crystal/enumerations.cr new file mode 100644 index 0000000000..7774d59b5e --- /dev/null +++ b/Task/Enumerations/Crystal/enumerations.cr @@ -0,0 +1,78 @@ +# An enum is a set of integer values, where each value has an associated name. +# For example: + +enum Color + Red # 0 + Green # 1 + Blue # 2 +end + +# Values start with the value 0 and are incremented by one, +# but can be overwritten. + +# To get the underlying value you invoke value on it: + +Color::Green.value # => 1 + +# Each constant (member) in the enum has the type of the enum: + +typeof(Color::Red) # => Color + +# An enum can be marked with the @[Flags] annotation. +# This changes the default values: + +@[Flags] +enum IOMode + Read # 1 + Write # 2 + Async # 4 +end + +# Additionally, some methods change their behaviour. + +# An enum can be created from an integer: + +Color.new(1).to_s # => "Green" + +# Values that don't correspond to enum's constants are allowed: +# the value will still be of type Color, but when printed you will get +# the underlying value: + +Color.new(10).to_s # => "10" + +# This method is mainly intended to convert integers from C to enums in Crystal. + +# An enum automatically defines question methods for each member, +# using String#underscore for the method name. +# * In the case of regular enums, this compares by equality (#==). +# * In the case of flags enums, this invokes #includes?. +# For example: + +color = Color::Blue +color.red? # => false +color.blue? # => true + +mode = IOMode::Read | IOMode::Async +mode.read? # => true +mode.write? # => false +mode.async? # => true + +# This is very convenient in case expressions: + +case color +when .red? + puts "Got red" +when .blue? + puts "Got blue" +end + +# The type of the underlying enum value is Int32 by default, +# but it can be changed to any type in Int::Primitive. + +enum Color : UInt8 + Red + Green + Blue +end + +Color::Red.value # : UInt8 diff --git a/Task/Enumerations/EMal/enumerations.emal b/Task/Enumerations/EMal/enumerations.emal index 60c6220bd6..5ceb8bdebe 100644 --- a/Task/Enumerations/EMal/enumerations.emal +++ b/Task/Enumerations/EMal/enumerations.emal @@ -5,13 +5,13 @@ enum end type ExplicitFruits enum - int APPLE = 10 - int BANANA = 20 - int CHERRY = 1 + 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("[", Generic.name(enumeration), "]") writeLine("getting an object with value = 1:") writeLine(:enumeration.byValue(1)) writeLine("iterating over the items:") diff --git a/Task/Enumerations/M2000-Interpreter/enumerations.m2000 b/Task/Enumerations/M2000-Interpreter/enumerations.m2000 index 7d9cc5e6e1..3d20ecd98d 100644 --- a/Task/Enumerations/M2000-Interpreter/enumerations.m2000 +++ b/Task/Enumerations/M2000-Interpreter/enumerations.m2000 @@ -1,7 +1,29 @@ Module Checkit { - \\ need revision 15, version 9.4 - Enum Fruit {apple, banana, cherry} - Enum Fruit2 {apple2=10, banana2=20, cherry2=30} + Enum Fruit { + apple, banana, cherry + } + Enum Fruit2 { + apple2=10, + banana2=20.5, + cherry2=30 + } + Enum StrType { + alfa="Άλφα", + beta="Βήτα", + gamma="Γάμμα", + delta="Δέλτα" + } + Print alfa, beta + z=alfa + z++ + Print z=beta, eval$(z)="beta", z="Βήτα" + z="Γάμμα" ' change to 3rd by searching value from the list + CheckByReference2(&z) + z1=Each(StrType, -1, 1) ' from last to first + while z1 + CheckByValue2(z1) + end while + Print apple, banana, cherry Print apple2, banana2, cherry2 Print Len(apple)=0 @@ -47,10 +69,16 @@ Module Checkit { Sub CheckByValue(z as Fruit2) Print Eval$(z), z End Sub - + Sub CheckByValue2(z as StrType) + Print Eval$(z), z + End Sub Sub CheckByReference(&z as Fruit2) z++ Print Eval$(z), z End Sub + Sub CheckByReference2(&z as StrType) + z++ + Print Eval$(z), z + End Sub } Checkit diff --git a/Task/Environment-variables/EMal/environment-variables.emal b/Task/Environment-variables/EMal/environment-variables.emal index 1052e86a8f..c7cd2af565 100644 --- a/Task/Environment-variables/EMal/environment-variables.emal +++ b/Task/Environment-variables/EMal/environment-variables.emal @@ -1,6 +1,6 @@ -fun showVariable = n: + break + while n % p == 0: + factors.append(p) + n = n // p + if n > 1 and n in primes_set: + factors.append(n) + return factors + + +def compute_categories(primes): + primes_set = set(primes) + category = {p: 0 for p in primes} + for p in primes: + m = p + 1 + factors = factor(m, primes, primes_set) + if all(f in {2, 3} for f in factors): + category[p] = 1 + else: + max_cat = 0 + for q in factors: + q_cat = category.get(q, 0) + if q_cat > max_cat: + max_cat = q_cat + category[p] = max_cat + 1 + return category + + +def print_first_200(primes, category): + print("First 200 primes sorted by category:") + print("-" * 34) + + # Create list of (category, prime, original_position) + sorted_primes = sorted( + [(category[p], p, i + 1) for i, p in enumerate(primes[:200])], + key=lambda x: (x[0], x[1]) + ) + # Group by category for better visualization + current_category = None + for cat, p, orig_pos in sorted_primes: + if cat != current_category: + print(f"\nCategory {cat}:") + current_category = cat + print(f"{p}", end=" ") + + +def process_million_primes(): + n = 10 ** 6 + primes = generate_primes_sieve(n) + primes = primes[:n] + category = compute_categories(primes) + + stats = defaultdict(lambda: {'count': 0, 'min': None, 'max': None}) + for p in primes: + cat = category[p] + stats[cat]['count'] += 1 + if stats[cat]['min'] is None or p < stats[cat]['min']: + stats[cat]['min'] = p + if stats[cat]['max'] is None or p > stats[cat]['max']: + stats[cat]['max'] = p + + print("\n\nCategory statistics for first 1,000,000 primes:") + print(f"{'Category':<8} {'Count':>12} {'Smallest':>12} {'Largest':>12}") + print("-" * 48) + for cat in sorted(stats.keys()): + s = stats[cat] + print(f"{cat:<8} {s['count']:>12,} {s['min']:>12,} {s['max']:>12,}") + + +# First part: Display first 200 primes sorted by category +primes_200 = generate_primes_sieve(200) +primes_200 = primes_200[:200] +category_200 = compute_categories(primes_200) +print_first_200(primes_200, category_200) + +# Second part: Process first million primes and display statistics +process_million_primes() diff --git a/Task/Ethiopian-multiplication/EMal/ethiopian-multiplication.emal b/Task/Ethiopian-multiplication/EMal/ethiopian-multiplication.emal index 4f8456efb4..1247805063 100644 --- a/Task/Ethiopian-multiplication/EMal/ethiopian-multiplication.emal +++ b/Task/Ethiopian-multiplication/EMal/ethiopian-multiplication.emal @@ -1,13 +1,14 @@ -fun halve = int by int value do return value / 2 end -fun double = int by int value do return value * 2 end -fun isEven = logic by int value do return value % 2 == 0 end -fun ethiopian = int by int multiplicand, int multiplier +fun halve ← = 1 - if not isEven(multiplicand) do product += multiplier end - multiplicand = halve(multiplicand) - multiplier = double(multiplier) + while multiplicand ≥ 1 + if not isEven(multiplicand) do product +← multiplier end + multiplicand ← halve(multiplicand) + multiplier ← double(multiplier) end return product end -writeLine(ethiopian(17, 34)) +writeLine(17, " x ", 34, " = ", ethiopian(17, 34)) +writeLine(99, " x ", 99, " = ", ethiopian(99, 99)) diff --git a/Task/Ethiopian-multiplication/M2000-Interpreter/ethiopian-multiplication.m2000 b/Task/Ethiopian-multiplication/M2000-Interpreter/ethiopian-multiplication.m2000 index 7b36107578..23beab8bf1 100644 --- a/Task/Ethiopian-multiplication/M2000-Interpreter/ethiopian-multiplication.m2000 +++ b/Task/Ethiopian-multiplication/M2000-Interpreter/ethiopian-multiplication.m2000 @@ -1,33 +1,23 @@ -Module EthiopianMultiplication{ - Form 60, 25 - Const Center=2, ColumnWith=12 - Report Center,"Ethiopian Method of Multiplication" - // using decimals as unsigned integers - Def Decimal leftval, rightval, sum - (leftval, rightval)=(random(1, 65535), random(1, 65536)) - Print $( , ColumnWith), "Target:", leftval*rightval, - Hex leftval*rightval - sum=0 - if @IsEven(leftval) Else sum+=rightval - Print leftval, rightval, - Hex leftval, rightval - while leftval>1 - leftval=@halveInt(leftval) - rightval=@DoubleInt(rightval) - Print leftval, rightval, - Hex leftval, rightval - if @IsEven(leftval) Else sum+=rightval - End while - Print "", sum - Hex "", sum - Function HalveInt(i) - =Binary.Shift(i,-1) - End Function - Function DoubleInt(i) - =Binary.Shift(i,1) - End Function - Function IsEven(i) - =Binary.And(i, 1)=0 - End Function +Function ethiopian(mr as long long, md as long long) { + def even()=number mod 2&& + def div2()=number div 2&& + def mul2()=number * 2&& + result=0&& + while mr>=1 + if even(mr) then result+=md + mr=div2(mr) + md=mul2(md) + end while + =result } -EthiopianMultiplication +Print ethiopian(17, 34)=578 +Function ethiopian(mr as long long, md as long long) { + result=0&& + while mr>=1 + if mr mod 2 then result+=md + mr|div 2& + md*=2& + end while + =result +} +Print ethiopian(17, 34)=578 diff --git a/Task/Eulers-identity/M2000-Interpreter/eulers-identity.m2000 b/Task/Eulers-identity/M2000-Interpreter/eulers-identity.m2000 new file mode 100644 index 0000000000..ba35d26c68 --- /dev/null +++ b/Task/Eulers-identity/M2000-Interpreter/eulers-identity.m2000 @@ -0,0 +1,105 @@ +Class Complex { +private: + double vr, vi + final pidivby180=pi/180 + final e=2.71828182845905 +public: + property real { + value {link parent vr to vr : value=vr} + } + property imaginary { + value {link parent vi to vi : value=vi} + } + property toString { + value { clear 'so a new clear as string created after + link parent vr, vi to vr, vi + if vi then + if vr then + if vi>0 then + value="("+vr+"+"+vi+"i)" + else + value="("+vr+""+vi+"i)" + end if + else + value="("+vi+"i)" + end if + else + value="("+vr+")" + end if + } + } + function exp { + double exp = .e^.vr + c=this + c.vr<=exp * cos(.vi/.pidivby180) + c.vi<=exp * sin(.vi/.pidivby180) + =c + } + function conj { + c=this : c.vi-! : =c + } + function absc { + c=this*.conj() : =sqrt(c.vr) + } + operator "+" { + read k as Complex : .vr+= k.vr : .vi+= k.vi + } + operator "-" { + read k as Complex : .vr-= k.vr : .vi-= k.vi + } + operator "*" { + read k as Complex + double ivr = .vr*k.vr-.vi*k.vi + .vi <= .vi*k.vr+.vr*k.vi + .vr <= ivr + } + operator "/" { + read k as Complex + k1=k*k.conj() + acb = this*k.conj() + .vr <= acb.vr/k1.vr + .vi <= acb.vi/k1.vr + } +class: + module Complex (.vr, .vi) {} +} +module Check (filename$="") { + const MAXITER=12& + long i, k = 2 + pii=Complex(0, pi) + pii2 = pii*pii + B0 = Complex(2) + A0 = Complex(2) + B1 = Complex(2) - pii + A1 = B0*B1 + Complex(2)*pii + open filename$ for output as #f + printc(A0/B0) + print #f, " Absolute error = ";@absc(A0/B0) + printc(A1/B1) + print #f, " Absolute error = ";@absc(A1/B1) + for i = 1 to MAXITER + k += 4 + A2 = Complex(k)*A1 + pii2*A0 + B2 = Complex(k)*B1 + pii2*B0 + try ok {curr = A2/B2} + if not ok then exit for + A0 = A1 + A1 = A2 + B0 = B1 + B1 = B2 + printc(curr) + print #f, " Absolute error = "; curr.absc() + next i + r=pii.exp()+Complex(1) + Print #f, "e^(πi)+1 = ";r.toString + close#f + if f<>-2 and exist(dir$+filename$) then win "notepad", dir$+filename$ + end + sub printc(c as Complex) + Print #f, c.toString + end sub + function absc(c as complex) + =c.absc() + end function +} +Check ' use Check "out.txt" diff --git a/Task/Evaluate-binomial-coefficients/PascalABC.NET/evaluate-binomial-coefficients.pas b/Task/Evaluate-binomial-coefficients/PascalABC.NET/evaluate-binomial-coefficients.pas index 2abbe607cb..e211b2dd47 100644 --- a/Task/Evaluate-binomial-coefficients/PascalABC.NET/evaluate-binomial-coefficients.pas +++ b/Task/Evaluate-binomial-coefficients/PascalABC.NET/evaluate-binomial-coefficients.pas @@ -3,7 +3,7 @@ function binomial(n, k: integer): biginteger; begin result := 1bi; for var i := 1 to k do - result *= (n - i + 1) div i; + result = result * (n - i + 1) div i; end; Println(binomial(5, 3)) diff --git a/Task/Evaluate-binomial-coefficients/Quackery/evaluate-binomial-coefficients.quackery b/Task/Evaluate-binomial-coefficients/Quackery/evaluate-binomial-coefficients.quackery index 84ddfed0ec..067fbe1414 100644 --- a/Task/Evaluate-binomial-coefficients/Quackery/evaluate-binomial-coefficients.quackery +++ b/Task/Evaluate-binomial-coefficients/Quackery/evaluate-binomial-coefficients.quackery @@ -2,6 +2,6 @@ 1 swap times [ over i + 1+ * ] nip swap times - [ i 1+ / ] ] is binomial ( n n --> ) + [ i 1+ / ] ] is binomial ( n n --> n ) 5 3 binomial echo diff --git a/Task/Even-or-odd/ALGOL-60/even-or-odd.alg b/Task/Even-or-odd/ALGOL-60/even-or-odd.alg new file mode 100644 index 0000000000..314105fd32 --- /dev/null +++ b/Task/Even-or-odd/ALGOL-60/even-or-odd.alg @@ -0,0 +1,21 @@ +begin + +integer i; + +boolean procedure even(n); + value n; integer n; +begin + even := (n = entier(n/2) * 2); +end; + +comment - exercise the function; +for i := 1 step 3 until 12 do + begin + outinteger(1,i); + if even(i) then + outstring(1,"is even\n") + else + outstring(1,"is odd\n"); + end; + +end diff --git a/Task/Even-or-odd/EMal/even-or-odd.emal b/Task/Even-or-odd/EMal/even-or-odd.emal index 0292abacd4..ee2b7e1cd8 100644 --- a/Task/Even-or-odd/EMal/even-or-odd.emal +++ b/Task/Even-or-odd/EMal/even-or-odd.emal @@ -1,20 +1,16 @@ -List evenCheckers = fun[ - logic by int i do return i % 2 == 0 end, - logic by int i do return i & 1 == 0 end] -List oddCheckers = fun[ - logic by int i do return i % 2 != 0 end, - logic by int i do return i & 1 == 1 end] -writeLine("integer".padStart(10, " ") + "|is_even" + "|is_odd |") +List evenCheckers ← fun[ + candidate_fitness + candidate, candidate_fitness = child, child_fitness + end + end + candidate +end + +parent = TARGET.map { ALPHABET.sample } + +(1..).each do |gen| + printf "%4d %s\n", gen, parent.join + break if parent == TARGET + parent = next_parent(parent, TARGET, C, RATE) +end diff --git a/Task/Evolutionary-algorithm/FutureBasic/evolutionary-algorithm.basic b/Task/Evolutionary-algorithm/FutureBasic/evolutionary-algorithm.basic new file mode 100644 index 0000000000..36c9824034 --- /dev/null +++ b/Task/Evolutionary-algorithm/FutureBasic/evolutionary-algorithm.basic @@ -0,0 +1,80 @@ +include "NSLog.incl" + +begin globals + CFStringRef target + CFStringRef alphabet + NSInteger c + CGFloat p +end globals + +target = @"METHINKS IT IS LIKE A WEASEL" +alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ " +c = 100 +p = 0.06 + +toolbox fn arc4random_uniform( UInt32 upperbound ) = UInt32 + +local fn Fitness( s as CFStringRef ) as NSInteger + NSInteger score = len(target) + for NSInteger i = 0 to len(target) -1 + if ( ucc(s,i) == ucc(target,i) ) then score-- + next +end fn = score + +local fn Mutate( s as CFStringRef, rate as CGFloat ) as CFStringRef + CFMutableStringRef result = fn MutableStringWithString( @"" ) + for NSInteger i = 0 to len(s) -1 + if ( ( fn arc4random_uniform(100) / 100.0) < rate ) + NSInteger idx = fn arc4random_uniform( (UInt32)len(alphabet) ) + MutableStringAppendFormat( result, @"%C", ucc( alphabet, idx ) ) + else + MutableStringAppendFormat( result, @"%C", ucc( s, i ) ) + end if + next +end fn = result + +local fn RandomString( length as NSInteger ) as CFStringRef + CFMutableStringRef result = fn MutableStringWithString( @"" ) + for NSInteger i = 0 to length -1 + NSInteger idx = fn arc4random_uniform( (UInt32)len(alphabet) ) + MutableStringAppendFormat( result, @"%C", ucc( alphabet, idx ) ) + next +end fn = result + +void local fn PrintStep( stepNum as NSInteger, s as CFStringRef, fit as NSInteger, result as CFMutableStringRef ) + MutableStringAppendFormat( result, @"%3ld: %@ Distance: %ld\n", (long)stepNum, s, (long)fit ) +end fn + +local fn EvolveString as CFStringRef + CFMutableStringRef result = fn MutableStringNew + CFStringRef parent = fn RandomString( len(target) ) + fn PrintStep( 0, parent, fn Fitness(parent), result ) + + NSInteger stepNum = 0 + while ( fn StringIsEqual( parent, target ) == NO ) + NSInteger bestFitness = len(target) + 1 + CFStringRef bestChild = @"" + CFStringRef child + NSInteger fit + + for NSInteger i = 0 to c -1 + child = fn Mutate( parent, p ) + fit = fn Fitness( child ) + if ( fit < bestFitness ) + bestFitness = fit + bestChild = child + end if + next + parent = bestChild + stepNum++ + fn PrintStep( stepNum, parent, bestFitness, result ) + wend +end fn = result + +CFTimeInterval t : t = fn CACurrentMediaTime +CFStringRef result : result = fn EvolveString +NSLog( @"\nCompute time: %.3f ms\n",(fn CACurrentMediaTime-t)*1000 ) +NSLog( @"%@", result ) +NSLogScrollToTop + +HandleEvents diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur index e376e53714..13d7a22492 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Langur/exceptions-catch-an-exception-thrown-in-a-nested-call.langur @@ -4,7 +4,7 @@ val U1 = {"msg": "U1"} val baz = fn i: throw if(i==0: U0; U1) val bar = fn i: baz(i) -val foo = impure fn() { +val foo = fn*() { for i in [0, 1] { bar(i) catch { diff --git a/Task/Execute-Computer-Zero/M2000-Interpreter/execute-computer-zero.m2000 b/Task/Execute-Computer-Zero/M2000-Interpreter/execute-computer-zero.m2000 new file mode 100644 index 0000000000..90e8e54763 --- /dev/null +++ b/Task/Execute-Computer-Zero/M2000-Interpreter/execute-computer-zero.m2000 @@ -0,0 +1,155 @@ +module Execute_Computer_Zero{ + global byte MEM[31]=0XFF, PC=0 + module ZERO (program$, f=-2, showrun, skipreadcode){ + Enum Commands { + NOP=0X0, LDA=0X20, STA=0X40, ADD=0X60, SUB=0X80, BRZ=0XA0, JMP=0XC0, STP=0XE0 + } + if skipreadcode then goto cont1 + PC<=0 + dim code$() + var crlf=chr$(13)+chr$(10) ' CRLF + var prname$="Program #1" + program$=replace$(chr$(9)," ", program$) + program$=replace$(",",crlf, program$) + program$=ucase$(filter$(program$, "().")) + code$()=piece$(program$, crlf) + document source$ + for I=0 to len(code$())-1 + tok$=trim$(LeftPart$(trim$(code$(I))+" ", " ")) + part$=trim$(RightPart$(trim$(code$(I))+" 0", " ")) + val=val(part$) MOD 32 + ch$=left$(tok$,1) + c=0 + if ch$="#" then + prname$=mid$(trim$(code$(I)), 2) + continue + end if + tok$=filter$(tok$, "+-_x!@#$%^&*/|><") + if ch$>="0" and ch$<="9" then + val=int(val(tok$)) mod 256 + source$ =" "+hex$(PC, 1)+" "+hex$(val,1)+crlf + else.if tok$="" then + continue + else.if valid(eval(tok$)) then + c=eval(tok$) + source$ =" "+hex$(PC, 1)+" "+tok$+" "+hex$(val,1)+crlf + end if + MEM[PC]<=c+VAL + PC++ + next + Print #f, "Program Name:";prname$ + Print #f, source$; + Print #f, "Program Length ";PC;"bytes" + PC<=0 +cont1: + byte A=0, ADDR=0 + structure Accumulator { + { A as Byte, Overflow as Byte + } + R as Integer + } + Accumulator AC + CM=STP + if showrun then Print #f, "PC MEM COM ADDR AC" + do + if inkey$=" " then Print "Break": exit + A=MEM[PC] + ADDR=A MOD 32 + CM=A-ADDR + if showrun then Print #f, Hex$(PC,1);" ";hex$(A,1);" ";EVAL$(CM);" ";hex$(ADDR, 1);" ";Hex$(AC|A, 1) + select case CM + case NOP + PC++ : PC|MOD 32 + case LDA + AC|R=MEM[ADDR]:PC++ : PC|MOD 32 + case STA + MEM[ADDR]<=AC|A : PC++ : PC|MOD 32 + case ADD + AC|R=AC|R+MEM[ADDR]:PC++ : PC|MOD 32 + case SUB + AC|R=uint(AC|R-MEM[ADDR]): PC++ : PC|MOD 32 + case BRZ + { + if AC|A then + PC++ : PC|MOD 32 + if showrun then Print #f, "NON ZERO - CONTINUE" + else + PC<=A MOD 32 + if showrun then Print #f, "BRANCH TO ";PC + end if + } + case JMP + PC<=A MOD 32:if showrun then Print #f, "JUMP TO ";PC + case STP + exit + end select + always + if skipreadcode else + Print #f, "STOP AT ";hex$(PC,1) + Print #f, "RESULT:";AC|A;"|0x";hex$(AC|A, 1) + Print #f, "NEGATIVE:"; IF$(AC|A>126->"1","0") + Print #f, "OVERFLOW:"; IF$(AC|Overflow>0->"1","0") + Print #f + end if + } + Flush + Data { + #add 2 + LDA 3, ADD 4, STP 0, 2, 2 + } + Data {#fibonacci + LDA 14, STA 15, ADD 13, STA 14, + LDA 15, STA 13, LDA 16, SUB 17, + BRZ 11, STA 16, JMP 0, LDA 14, + STP 0, 1, 1, 0 , 8, 1 + } + Data {#8*7 + LDA 12, ADD 10, STA 12, LDA 11, SUB 13, + STA 11, BRZ 8, JMP 0, LDA 12, STP 0, + 8, 7, 0, 1 + } + Data {#linkedList + LDA 13, ADD 15, STA 5, ADD 16, STA 7, NOP 0, STA 14, NOP 0 + , BRZ 11, STA 15, JMP 0, LDA 14, STP 0, LDA 0, 0, 28 + , 1, 0, 0, 0, 6, 0, 2, 26 + , 5, 20, 3, 30, 1, 22, 4, 24 + } + Data { #0-255 + LDA 3, SUB 4, STP 0, 0, 255 + } + Data {#0-1 + LDA 3, SUB 4, STP 0, 0, 1 + } + Data {#1+255 + LDA 3, ADD 4, STP 0, 1, 255 + } + filename="run01.txt" + open filename for wide output as #d + while not empty + Zero letter$, d, false, false + end while + Zero { #prisoner + NOP 0, NOP 0, STP 0, 0, LDA 3, SUB 29, BRZ 18, LDA 3 + , STA 29, BRZ 14, LDA 1, ADD 31, STA 1, JMP 2, LDA 0, ADD 31 + , STA 0, JMP 2, LDA 3, STA 29, LDA 1, ADD 30, ADD 3, STA 1 + , LDA 0, ADD 30, ADD 3, STA 0, JMP 2, 0, 1, 3 + }, d, false, false + + Enum Action {cooperate=0UB, defect} + byte AcA + PM=defect + for i=1 to 5 + Print #d, "Round ";i;" ";field$(eval$(PM), 10); + PC++ + mem[PC]<=pm + IF PM=cooperate THEN PM++ ELSE PM-- + PC++ + Zero {}, d, false, true + Read AcA + Print #d, "Player:";mem[0], " Computer:";mem[1] + next + close #d + if filename<>"" then win dir$+filename + +} +Execute_Computer_Zero diff --git a/Task/Execute-Computer-Zero/Quackery/execute-computer-zero.quackery b/Task/Execute-Computer-Zero/Quackery/execute-computer-zero.quackery new file mode 100644 index 0000000000..27224d387f --- /dev/null +++ b/Task/Execute-Computer-Zero/Quackery/execute-computer-zero.quackery @@ -0,0 +1,175 @@ + [ 0 ] is NOP ( --> n ) + [ 1 ] is LDA ( --> n ) + [ 2 ] is STA ( --> n ) + [ 3 ] is ADD ( --> n ) + [ 4 ] is SUB ( --> n ) + [ 5 ] is BRZ ( --> n ) + [ 6 ] is JMP ( --> n ) + [ 7 ] is STP ( --> n ) + + [ 0 ] is DATA ( --> n ) + [ 0 ] is -- ( --> n ) + + [ stack 0 ] is acc ( --> s ) + [ stack 0 ] is ip ( --> s ) + [ stack false ] is flag ( --> n ) + + [ 0 ip replace 0 32 of ] is computer/zero ( --> [ ) + + [ 255 & swap 5 << | + swap ip share poke + 1 ip tally ] is , ( [ --> [ ) + + [ drop ] is nop ( [ n --> [ ) + + [ dip dup peek acc replace ] is lda ( [ n --> [ ) + + [ acc share unrot poke ] is sta ( [ n --> [ ) + + [ dip dup peek + acc take + 255 & acc put ] is add ( [ n --> [ ) + + [ dip dup peek negate + acc take + 255 & acc put ] is sub ( [ n --> [ ) + + [ acc share iff drop done + ip replace ] is brz ( [ n --> [ ) + + [ ip replace ] is jmp ( [ n --> [ ) + + [ drop true flag replace ] is stp ( [ n --> [ ) + + [ false flag replace + 0 acc replace + 0 ip replace + [ dup ip share peek + 1 ip tally + dup 31 & swap 5 >> + [ table + nop lda sta add + sub brz jmp stp ] do + flag share until ] + drop + acc share + say "acc = " dup echo + dup 128 & iff + [ say " or " + 127 ~ | echo ] + else drop cr ] is execute ( [ --> ) + + cr say " 2+2: " + computer/zero + ( 00 ) LDA 03 , + ( 01 ) ADD 04 , + ( 02 ) STP -- , + ( 03 ) DATA 2 , + ( 04 ) DATA 2 , + execute + cr say " 7*8: " + computer/zero + ( 00 ) LDA 12 , + ( 01 ) ADD 10 , + ( 02 ) STA 12 , + ( 03 ) LDA 11 , + ( 04 ) SUB 13 , + ( 05 ) STA 11 , + ( 06 ) BRZ 08 , + ( 07 ) JMP 00 , + ( 08 ) LDA 12 , + ( 09 ) STP -- , + ( 10 ) DATA 8 , + ( 11 ) DATA 7 , + ( 12 ) DATA 0 , + ( 13 ) DATA 1 , + execute + cr say " Fibonacci: " + computer/zero + ( 00 ) LDA 14 , + ( 01 ) STA 15 , + ( 02 ) ADD 13 , + ( 03 ) STA 14 , + ( 04 ) LDA 15 , + ( 05 ) STA 13 , + ( 06 ) LDA 16 , + ( 07 ) SUB 17 , + ( 08 ) BRZ 11 , + ( 09 ) STA 16 , + ( 10 ) JMP 00 , + ( 11 ) LDA 14 , + ( 12 ) STP -- , + ( 13 ) DATA 1 , + ( 14 ) DATA 1 , + ( 15 ) DATA 0 , + ( 16 ) DATA 8 , + ( 17 ) DATA 1 , + execute + cr say "linked list: " + computer/zero + ( 00 ) LDA 13 , + ( 01 ) ADD 15 , + ( 02 ) STA 05 , + ( 03 ) ADD 16 , + ( 04 ) STA 07 , + ( 05 ) NOP -- , + ( 06 ) STA 14 , + ( 07 ) NOP -- , + ( 08 ) BRZ 11 , + ( 09 ) STA 15 , + ( 10 ) JMP 00 , + ( 11 ) LDA 14 , + ( 12 ) STP -- , + ( 13 ) LDA 00 , + ( 14 ) DATA 0 , + ( 15 ) DATA 28 , + ( 16 ) DATA 1 , + ( 17 ) DATA 0 , + ( 18 ) DATA 0 , + ( 19 ) DATA 0 , + ( 20 ) DATA 6 , + ( 21 ) DATA 0 , + ( 22 ) DATA 2 , + ( 23 ) DATA 26 , + ( 24 ) DATA 5 , + ( 25 ) DATA 20 , + ( 26 ) DATA 3 , + ( 27 ) DATA 30 , + ( 28 ) DATA 1 , + ( 29 ) DATA 22 , + ( 30 ) DATA 4 , + ( 31 ) DATA 24 , + execute + cr say " prisoner: " + computer/zero + ( 00 ) NOP -- , + ( 01 ) NOP -- , + ( 02 ) STP -- , + ( 03 ) NOP -- , + ( 04 ) LDA 03 , + ( 05 ) SUB 29 , + ( 06 ) BRZ 18 , + ( 07 ) LDA 03 , + ( 08 ) STA 29 , + ( 09 ) BRZ 14 , + ( 10 ) LDA 01 , + ( 11 ) ADD 31 , + ( 12 ) STA 01 , + ( 13 ) JMP 02 , + ( 14 ) LDA 00 , + ( 15 ) ADD 31 , + ( 16 ) STA 00 , + ( 17 ) JMP 02 , + ( 18 ) LDA 03 , + ( 19 ) STA 29 , + ( 20 ) LDA 01 , + ( 21 ) ADD 30 , + ( 22 ) ADD 03 , + ( 23 ) STA 01 , + ( 24 ) LDA 00 , + ( 25 ) ADD 30 , + ( 26 ) ADD 03 , + ( 27 ) STA 01 , + ( 28 ) JMP 02 , + ( 29 ) DATA 0 , + ( 30 ) DATA 1 , + ( 31 ) DATA 3 , + execute diff --git a/Task/Execute-a-system-command/Wren/execute-a-system-command-1.wren b/Task/Execute-a-system-command/Wren/execute-a-system-command-1.wren deleted file mode 100644 index c638a0983e..0000000000 --- a/Task/Execute-a-system-command/Wren/execute-a-system-command-1.wren +++ /dev/null @@ -1,8 +0,0 @@ -/* Execute_a_system_command.wren */ -class Command { - foreign static exec(name, param) // the code for this is provided by Go -} - -Command.exec("ls", "-lt") -System.print() -Command.exec("dir", "") diff --git a/Task/Execute-a-system-command/Wren/execute-a-system-command-2.wren b/Task/Execute-a-system-command/Wren/execute-a-system-command-2.wren deleted file mode 100644 index 2e0ffb7e03..0000000000 --- a/Task/Execute-a-system-command/Wren/execute-a-system-command-2.wren +++ /dev/null @@ -1,39 +0,0 @@ -/* Execute_a_system_command.go*/ -package main - -import ( - wren "github.com/crazyinfin8/WrenGo" - "log" - "os" - "os/exec" -) - -type any = interface{} - -func execCommand(vm *wren.VM, parameters []any) (any, error) { - name := parameters[1].(string) - param := parameters[2].(string) - var cmd *exec.Cmd - if param != "" { - cmd = exec.Command(name, param) - } else { - cmd = exec.Command(name) - } - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - log.Fatal(err) - } - return nil, nil -} - -func main() { - vm := wren.NewVM() - fileName := "Execute_a_system_command.wren" - methodMap := wren.MethodMap{"static exec(_,_)": execCommand} - classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)} - module := wren.NewModule(classMap) - vm.SetModule(fileName, module) - vm.InterpretFile(fileName) - vm.Free() -} diff --git a/Task/Execute-a-system-command/Wren/execute-a-system-command.wren b/Task/Execute-a-system-command/Wren/execute-a-system-command.wren new file mode 100644 index 0000000000..1d97b0a9de --- /dev/null +++ b/Task/Execute-a-system-command/Wren/execute-a-system-command.wren @@ -0,0 +1,5 @@ +import "os" for Process + +Process.exec("ls", ["-lt"]) +System.print() +Process.exec("dir") diff --git a/Task/Extreme-floating-point-values/Uiua/extreme-floating-point-values.uiua b/Task/Extreme-floating-point-values/Uiua/extreme-floating-point-values.uiua new file mode 100644 index 0000000000..d9ae4f444f --- /dev/null +++ b/Task/Extreme-floating-point-values/Uiua/extreme-floating-point-values.uiua @@ -0,0 +1,4 @@ +&p∞ +&p¯∞ +&p¯0 # Distinct value from "0". +&pNaN # IEEE 754-2008's NaN diff --git a/Task/Factorial/Haskell/factorial-10.hs b/Task/Factorial/Haskell/factorial-10.hs new file mode 100644 index 0000000000..d7507d16b3 --- /dev/null +++ b/Task/Factorial/Haskell/factorial-10.hs @@ -0,0 +1,8 @@ +-- product of [a,a+1..b] +productFromTo a b = + if a>b then 1 + else if a == b then a + else productFromTo a c * productFromTo (c+1) b + where c = (a+b) `div` 2 + +factorial = productFromTo 1 diff --git a/Task/Factorial/Haskell/factorial-5.hs b/Task/Factorial/Haskell/factorial-5.hs index 6b76b69b6e..f036c73a77 100644 --- a/Task/Factorial/Haskell/factorial-5.hs +++ b/Task/Factorial/Haskell/factorial-5.hs @@ -1,3 +1 @@ -factorial :: Integral -> Integral -factorial 0 = 1 -factorial n = n * factorial (n-1) +factorials = 1 : zipWith (*) factorials [1..] diff --git a/Task/Factorial/Haskell/factorial-6.hs b/Task/Factorial/Haskell/factorial-6.hs index baef906bf8..655c366a44 100644 --- a/Task/Factorial/Haskell/factorial-6.hs +++ b/Task/Factorial/Haskell/factorial-6.hs @@ -1,5 +1,2 @@ -fac n - | n >= 0 = go 1 n - | otherwise = error "Negative factorial!" - where go acc 0 = acc - go acc n = go (acc * n) (n - 1) +factorials = go 1 1 where + go n fac = f : go (n+1) (n*fac) diff --git a/Task/Factorial/Haskell/factorial-7.hs b/Task/Factorial/Haskell/factorial-7.hs index 77d34e9b2e..6b76b69b6e 100644 --- a/Task/Factorial/Haskell/factorial-7.hs +++ b/Task/Factorial/Haskell/factorial-7.hs @@ -1,10 +1,3 @@ -{-# LANGUAGE PostfixOperators #-} - -(!) :: Integer -> Integer -(!) 0 = 1 -(!) n = n * (pred n !) - -main :: IO () -main = do - print (5 !) - print ((4 !) !) +factorial :: Integral -> Integral +factorial 0 = 1 +factorial n = n * factorial (n-1) diff --git a/Task/Factorial/Haskell/factorial-8.hs b/Task/Factorial/Haskell/factorial-8.hs index d7507d16b3..baef906bf8 100644 --- a/Task/Factorial/Haskell/factorial-8.hs +++ b/Task/Factorial/Haskell/factorial-8.hs @@ -1,8 +1,5 @@ --- product of [a,a+1..b] -productFromTo a b = - if a>b then 1 - else if a == b then a - else productFromTo a c * productFromTo (c+1) b - where c = (a+b) `div` 2 - -factorial = productFromTo 1 +fac n + | n >= 0 = go 1 n + | otherwise = error "Negative factorial!" + where go acc 0 = acc + go acc n = go (acc * n) (n - 1) diff --git a/Task/Factorial/Haskell/factorial-9.hs b/Task/Factorial/Haskell/factorial-9.hs new file mode 100644 index 0000000000..77d34e9b2e --- /dev/null +++ b/Task/Factorial/Haskell/factorial-9.hs @@ -0,0 +1,10 @@ +{-# LANGUAGE PostfixOperators #-} + +(!) :: Integer -> Integer +(!) 0 = 1 +(!) n = n * (pred n !) + +main :: IO () +main = do + print (5 !) + print ((4 !) !) diff --git a/Task/Factorial/Langur/factorial-1.langur b/Task/Factorial/Langur/factorial-1.langur index 607783ad36..8f10a78690 100644 --- a/Task/Factorial/Langur/factorial-1.langur +++ b/Task/Factorial/Langur/factorial-1.langur @@ -1,2 +1,2 @@ -val factorial = fn n: fold(fn{*}, 2 .. n) +val factorial = fn n: fold(2 .. n, by=fn{*}) writeln factorial(7) diff --git a/Task/Factorial/M2000-Interpreter/factorial.m2000 b/Task/Factorial/M2000-Interpreter/factorial-1.m2000 similarity index 100% rename from Task/Factorial/M2000-Interpreter/factorial.m2000 rename to Task/Factorial/M2000-Interpreter/factorial-1.m2000 diff --git a/Task/Factorial/M2000-Interpreter/factorial-2.m2000 b/Task/Factorial/M2000-Interpreter/factorial-2.m2000 new file mode 100644 index 0000000000..dc7940cef8 --- /dev/null +++ b/Task/Factorial/M2000-Interpreter/factorial-2.m2000 @@ -0,0 +1,27 @@ +Cls , 0 ' 0 for non split display, eg 3 means we preserve the 3 top lines from scrolling/cla +Report { + Factorial Task + Definitions + • The factorial of 0 (zero) is defined as being 1 (unity). + • The Factorial Function of a positive integer, n, is defined as the product of the sequence: + n, n-1, n-2, ... 1 + +} +Cls, row ' now we preserve some lines (as row number return here) +Module CheckIt { + m=bigInteger("1") + with m, "tostring" as m.toString + k=width-tab + For i=1 to 1000 + if pos>tab then print + Print @(0), format$("{0::-4} :", i) ; + method m,"multiply", biginteger(i+"") as m + Report m.toString, k + ' Report stop at 2/3 of display lines, and wait mouse button or spacebar + ' we can flush the keyboard buffer and press space, so we get non stop display + ' Report didn't stop if we use the printer's layer. + while inkey$<>"": wait 1:end while + keyboard " " + Next i +} +Checkit diff --git a/Task/Factorial/Retro/factorial.retro b/Task/Factorial/Retro/factorial.retro index fb56673ef4..11cf76e297 100644 --- a/Task/Factorial/Retro/factorial.retro +++ b/Task/Factorial/Retro/factorial.retro @@ -1,2 +1,8 @@ -: dup 1 = if; dup 1- * ; -: factorial dup 0 = [ 1+ ] [ ] if ; +: + dup #1 -eq? 0; drop + dup n:dec * ; + +:factorial + dup n:zero? + [ n:inc ] + [ ] choose ; diff --git a/Task/Factorial/YAMLScript/factorial.ys b/Task/Factorial/YAMLScript/factorial.ys index b823037a90..06c6ba6aef 100644 --- a/Task/Factorial/YAMLScript/factorial.ys +++ b/Task/Factorial/YAMLScript/factorial.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(n=10): say: "$n! -> $factorial(n)" diff --git a/Task/Factors-of-an-integer/EDSAC-order-code/factors-of-an-integer.edsac b/Task/Factors-of-an-integer/EDSAC-order-code/factors-of-an-integer.edsac index cdf4742401..75f73ed6fb 100644 --- a/Task/Factors-of-an-integer/EDSAC-order-code/factors-of-an-integer.edsac +++ b/Task/Factors-of-an-integer/EDSAC-order-code/factors-of-an-integer.edsac @@ -1,153 +1,151 @@ - [Factors of an integer, from Rosetta Code website.] - [EDSAC program, Initial Orders 2.] +[Factors of an integer, from Rosetta Code website.] +[EDSAC program, Initial Orders 2.] +[2024-12-25 (1) Fixed bug in print subroutine + (2) Added factors of more integers. [The numbers to be factorized are read in by library subroutine R2 (Wilkes, Wheeler and Gill, 1951 edition, pp.96-97, 148).] [The address of the integers is placed in location 46, so they can be referred to by the N parameter (or we could have used 45 and H, etc.)] - T 46 K - P 600 F [address of integers] + T46K + P600F [address of integers] [Subroutine R2] GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z - T #N [pass address of integers to R2] + T#N [pass address of integers to R2] +[Integers, separated by 'F' and terminated by '#TZ', as R2 requires.] +420F42000F420000F99999F999999F0# + TZ [resume normal loading] -[List of integers to be factorized; edit ad lib. R2 requires 'F' after - each integer except the last, and '#' (pi) after the last. - This program uses 0 to mark the end of the list.] - 42000F999999F0# - T Z [resume normal loading] + [Modified library subroutine P7. + Prints signed integer; up to 10 digits, left-justified. + Input: 0D = integer + 52 locations. Load at even address. Workspace 4D.] + T56K +GKA3FT42@A47@T31@ADE10@T31@A46@T31@SDTDH44#@NDYFLDT4DS43@TF +H17@S17@A43@G23@UFS43@T1FV4DAFG48@SFLDUFXFOFFFSFL4FT4DA47@ +T31@A1FA43@G20@XFT44#ZPFT43ZP1024FP610D@524DO26@XFSFL8FT4DE39@ - [Modified library subroutine P7.] - [Prints signed integer; up to 10 digits, left-justified.] - [Input: 0D = integer,] - [54 locations. Load at even address. Workspace 4D.] - T 56 K -GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@ -TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@ -T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@ - - [Division subroutine for positive long integers. - 35-bit dividend and divisor (max 2^34 - 1) - returning quotient and remainder. - Input: dividend at 4D, divisor at 6D - Output: remainder at 4D, quotient at 6D. - 37 locations; working locations 0D, 8D.] - T 110 K + [Division subroutine for positive long integers. + 35-bit dividend and divisor (max 2^34 - 1) + returning quotient and remainder. + Input: dividend at 4D, divisor at 6D + Output: remainder at 4D, quotient at 6D. + 37 locations; working locations 0D, 8D.] + T110K GKA3FT35@A6DU8DTDA4DRDSDG13@T36@ADLDE4@T36@T6DA4DSDG23@ T4DA6DYFYFT6DT36@A8DSDE35@T36@ADRDTDA6DLDT6DE15@EFPF [********************** ROSETTA CODE TASK **********************] - [Subroutine to find and print factors of a positive integer. - Input: 0D = integer, maximum 10 decimal digits. - Load at even address.] - T 148 K - G K - A 3 F [form and plant link for return] - T 55 @ - A D [load integer whose factors are to be found] - T 56#@ [store] - A 62#@ [load 1] - T 58#@ [possible factor := 1] - S 65 @ [negative count of items per line] - T 64 @ [initialize count] + [Subroutine to find and print factors of a positive integer. + Input: 0D = integer, maximum 10 decimal digits. + Load at even address.] + T148K + GK + A3F [form and plant link for return] + T55@ + AD [load integer whose factors are to be found] + T56#@ [store] + A62#@ [load 1] + T58#@ [possible factor := 1] + S65@ [negative count of items per line] + T64@ [initialize count] [Start of loop round possible factors] - [8] T F [clear acc] - A 56#@ [load integer] - T 4 D [to 4F for division] - A 58#@ [load possible factor] - T 6 D [to 6F for division] - A 13 @ [for return from next] - G 110 F [do division; clears acc] - A 6 D [save quotient (6F may be changed below)] - T 60#@ - S 4 D [load negative of remainder] - G 44 @ [skip if remainder > 0] + [8] TF [clear acc] + A56#@ [load integer] + T4D [to 4D for division] + A58#@ [load possible factor] + T6D [to 6D for division] + A13@ [for return from next] + G110F [do division; clears acc] + A6D [save quotient (6D may be changed below)] + T60#@ + S4D [load negative of remainder] + G44@ [skip if remainder > 0] [Here if m is a factor of n.] [Print m and the quotient together] - T F [clear acc] - A 64 @ [test count of items per line] - G 26 @ [skip if not start of line] - S 65 @ [start of line, reset count] - T 64 @ - O 70 @ [and print CR, LF] - O 71 @ - [26] T F [clear acc] - O 67 @ [print '('] - A 58#@ [load factor] - T D [to 0D for printing] - A 30 @ [for return from next] - G 56 F [print factor; clears acc] - O 69 @ [print comma] - A 60#@ [load quotient] - T D [to 0D for printing] - A 35 @ [for return from next] - G 56 F [print quotient; clears acc] - O 68 @ [print ')'] - A 64 @ [negative counter for items per line] - A 2 F [inc] - E 43 @ [skip if end of line] - O 66 @ [not end of line, print 2 spaces] - O 66 @ - [43] T 64 @ [update counter] + TF [clear acc] + A64@ [test count of items per line] + G26@ [skip if not start of line] + S65@ [start of line, reset count] + T64@ + O70@ [and print CR, LF] + O71@ + [26] TF [clear acc] + O67@ [print '('] + A58#@ [load factor] + TD [to 0D for printing] + A30@ [for return from next] + G56F [print factor; clears acc] + O69@ [print comma] + A60#@ [load quotient] + TD [to 0D for printing] + A35@ [for return from next] + G56F [print quotient; clears acc] + O68@ [print ')'] + A64@ [negative counter for items per line] + A2F [inc] + E43@ [skip if end of line] + O66@ [not end of line, print 2 spaces] + O66@ + [43] T64@ [update counter] [Common code after testing possible factor] - [44] T F [clear acc] - A 58#@ [load possible factor] - A 62#@ [inc by 1] - U 58#@ [store back] - S 60#@ [compare with quotient] - G 8 @ [loop if (new factor) < (old quotient)] + [44] TF [clear acc] + A58#@ [load possible factor] + A62#@ [inc by 1] + U58#@ [store back] + S60#@ [compare with quotient] + G8@ [loop if (new factor) < (old quotient)] [Here when found all factors] - O 70 @ [print CR, LF twice] - O 71 @ - O 70 @ - O 71 @ - T F [exit with acc = 0] - [55] E F [return] - [--------] - [56] PF PF [number whose factors are to be found] - [58] PF PF [possible factor] - [60] PF PF [integer part of (number/factor)] - T62#Z PF [clear sandwich digit in 35-bit constant 1] - T 62 Z [resume normal loading] - [62] PD PF [35-bit constant 1] - [64] P F [negative counter for items per line] - [65] P 4 F [items per line, in address field] - [66] ! F [space] - [67] K F [left parenthesis (in figures mode)] - [68] L F [right parenthesis (in figures mode)] - [69] N F [comma (in figures mode)] - [70] @ F [carriage return] - [71] & F [line feed] + O70@ [print CR, LF twice] + O71@ + O70@ + O71@ + TF [exit with acc = 0] + [55] EF [(planted) return to caller] + [--------------] + [56] PF PF [number whose factors are to be found] + [58] PF PF [possible factor] + [60] PF PF [integer part of (number/factor)] + T62#Z [clear whole of 35-bit constant, including sandwich bit] + PF + T62Z [resume normal loading] + [62] PD PF [35-bit constant 1] + [64] PF [negative counter for items per line] + [65] P4F [items per line, in address field] + [66] !F [space] + [67] KF + [68] LF + [69] NF [comma, in figure shift] + [70] @F [carriage return] + [71] &F [line feed] [Main routine for demonstrating subroutine.] - T 400 K - G K - [0] # F [set figures mode] - [1] K 4096 F [null char] - [2] S #N [order to load negative of first number] - [3] P 2 F [to inc address by 2 for next number] + T400K + GK + [0] #F [figure shift] + [1] K4096F [null char] + [2] S#N [order to load negative first number] + [3] P2F [to inc address by 2 for next number] [Enter with acc = 0] - [4] O @ [set teleprinter to figures] - A 2 @ [load order for first integer] - [6] T 7 @ [plant in next order] - [7] S D [load negative of 35-bit integer] - E 17 @ [exit if number is 0] - T D [negative to 0D] - S D [convert to positive] - T D [pass to subroutine] - A 12 @ [call subroutine to find and print factors] - G 148 F - A 7 @ [modify order above, for next integer] - A 3 @ - E 6 @ [always jump, since S = 12 > 0] - [--------] - [17] O 1 @ [done, print null to flush printer buffer] - Z F [stop] - - E 4 Z [define entry point] - P F [acc = 0 on entry] + [4] O@ [set teleprinter to figures] + A2@ [load order for first integer] + [6] T7@ [plant in next order] + [7] SD [load negative of 35-bit integer] + E17@ [exit if number is 0] + TD + SD [convert to positive] + TD [pass to subroutine] + A12@ [call subroutine to find and print factors] + G148F + A7@ [modify order above, for next integer] + A3@ + E6@ [always jump, since S = 12 > 0] + [17] O1@ [done, print null to flush printer buffer] + ZF [stop] + E4Z [define entry point] + PF [acc = 0 on entry diff --git a/Task/Factors-of-an-integer/FutureBasic/factors-of-an-integer.basic b/Task/Factors-of-an-integer/FutureBasic/factors-of-an-integer.basic index d8d5b31d8b..5ceb9204b8 100644 --- a/Task/Factors-of-an-integer/FutureBasic/factors-of-an-integer.basic +++ b/Task/Factors-of-an-integer/FutureBasic/factors-of-an-integer.basic @@ -1,50 +1,23 @@ -window 1, @"Factors of an Integer", (0,0,1000,270) +local fn Factors( n as int ) as CFArrayRef + CFMutableArrayRef mutArray = fn MutableArrayNew -clear local mode -local fn IntegerFactors( f as long ) as CFStringRef - long i, s, l(100), c = 0 - CFStringRef factorStr = @"" - - for i = 1 to sqr(f) - if ( f mod i == 0 ) - l(c) = i - c++ - if ( f != i ^ 2 ) - l(c) = ( f / i ) - c++ + for int factor = 1 to sqr(n) + if ( n mod factor == 0 ) + MutableArrayAddObject( mutArray, @(factor) ) + if ( n/factor != factor ) + MutableArrayAddObject( mutArray, @(n/factor) ) end if end if - next i - - s = 1 - while ( s = 1 ) - s = 0 - for i = 0 to c-1 - if l(i) > l(i+1) and l(i+1) != 0 - swap l(i), l(i+1) - s = 1 - end if - next i - wend - - for i = 0 to c - 1 - if ( i < c - 1 ) - factorStr = fn StringWithFormat( @"%@ %ld, ", factorStr, l(i) ) - else - factorStr = fn StringWithFormat( @"%@ %ld", factorStr, l(i) ) - end if next -end fn = factorStr + CFArrayRef result = fn ArraySortedArrayUsingSelector( mutArray, @"compare:" ) +end fn = result -print @"Factors of 25 are:"; fn IntegerFactors( 25 ) -print @"Factors of 45 are:"; fn IntegerFactors( 45 ) -print @"Factors of 103 are:"; fn IntegerFactors( 103 ) -print @"Factors of 760 are:"; fn IntegerFactors( 760 ) -print @"Factors of 12345 are:"; fn IntegerFactors( 12345 ) -print @"Factors of 32766 are:"; fn IntegerFactors( 32766 ) -print @"Factors of 32767 are:"; fn IntegerFactors( 32767 ) -print @"Factors of 57097 are:"; fn IntegerFactors( 57097 ) -print @"Factors of 12345678 are:"; fn IntegerFactors( 12345678 ) -print @"Factors of 32434243 are:"; fn IntegerFactors( 32434243 ) +mda (0) = {1,2,3,4,5,6,7,8,9,10,20,40,60,80,100,200,300,400,512,677,768,966,1000,1024,2048,4096} + +int i, n +for i = 0 to mda_count -1 + n = mda_integer(i) + print fn StringWithFormat( @"Factors of %4d: [%@]", n, fn ArrayComponentsJoinedByString( fn Factors( n ), @", " ) ) +next HandleEvents diff --git a/Task/Factors-of-an-integer/Raku/factors-of-an-integer.raku b/Task/Factors-of-an-integer/Raku/factors-of-an-integer-1.raku similarity index 100% rename from Task/Factors-of-an-integer/Raku/factors-of-an-integer.raku rename to Task/Factors-of-an-integer/Raku/factors-of-an-integer-1.raku diff --git a/Task/Factors-of-an-integer/Raku/factors-of-an-integer-2.raku b/Task/Factors-of-an-integer/Raku/factors-of-an-integer-2.raku new file mode 100644 index 0000000000..ae8b49d375 --- /dev/null +++ b/Task/Factors-of-an-integer/Raku/factors-of-an-integer-2.raku @@ -0,0 +1,5 @@ +use Prime::Factor; + +put divisors :s, 2⁹⁹ + 1; + +say (now - INIT now).round(.001) ~' seconds'; diff --git a/Task/Farey-sequence/Langur/farey-sequence.langur b/Task/Farey-sequence/Langur/farey-sequence.langur index 2743d7c155..2aa36b46f1 100644 --- a/Task/Farey-sequence/Langur/farey-sequence.langur +++ b/Task/Farey-sequence/Langur/farey-sequence.langur @@ -10,7 +10,7 @@ val farey = fn(n) { val testFarey = fn*() { writeln "Farey sequence for orders 1 through 11" for i of 11 { - writeln "{{i:2}}: ", join(" ", map(fn f: "{{f[1]}}/{{f[2]}}", farey(i))) + writeln "{{i:2}}: ", join(map(farey(i), by=fn f: "{{f[1]}}/{{f[2]}}"), by=" ") } } diff --git a/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-1.m2000 b/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-1.m2000 new file mode 100644 index 0000000000..45d054c7f9 --- /dev/null +++ b/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-1.m2000 @@ -0,0 +1,51 @@ +module CreateLibComplexPack { + prototype { + class ComplexPack { + function final complexPolar(a, b) { + method .m, "cxPolar", a, b as ret + =ret + } + function final complex(a, b) { + method .m, "cxNew", a, b as ret + =ret + } + function final mul(a, b) { + method .m, "cxMul", a, b as ret + =ret + } + function final add(a, b) { + method .m, "cxAdd", a, b as ret + =ret + } + function final sub(a, b) { + method .m, "cxSub", a, b as ret + =ret + } + Module final FFT(buf, out, begin as Long, stp as Long, N as Long) { + If stp < N Then + call .FFT, out, buf, begin, 2 * stp, N + call .FFT, out, buf, begin + stp, 2 * stp, N + var i as long, t as variant + for i=0 to N-1 step 2*stp + t= .mul(.complexPolar(1, -pi* i / N), out[begin + i + stp]) + buf[begin + i div 2]= .add(out[begin + i], t) + buf[begin + (i + N) div 2]= .sub(out[begin + i], t) + next + End If + } + private: + declare m math2 + public: + property zero {value} + class: + module ComplexPack{ + method .m,"cxzero" as z + .[zero]<=z + } + } + } as ComplexPack + const UTF8=2& + document Export$=ComplexPack + Save.Doc Export$, "ComplexPack.gsb", UTF8 +} +CreateLibComplexPack diff --git a/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 b/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 new file mode 100644 index 0000000000..aeb97fb834 --- /dev/null +++ b/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 @@ -0,0 +1,19 @@ +module FFT { + load "ComplexPack" + cp=ComplexPack() + variant buf[7]=cp.zero, out[7]=cp.zero + buf[0]|r = 1: buf[1]|r = 1: buf[2]|r = 1: buf[3]|r = 1 + showArr(buf, "Input") + cp.FFT out, buf, 0, 1, 8 + ShowArr(out, "Output") + + Sub ShowArr(m, mes as string) + local n, mx=len(m) + Print mes;": (real+imag)" + while n") + concat("<",vstr(2, Comp,", ",0,-1),"j> ") #end #macro CdebugArr(data) #for(i,0, dimension_size(data, 1)-1) - #debug concat(Cstr(data[i]), "\n") + #debug concat(Cstr(data[i]), " ", str(Abs(data[i]),-1,-1),"\n") #end #end #macro R2C(Real) #end -#macro CmultC(C1, C2) #end +#macro CmultC(C1, C2) #end #macro Conjugate(Comp) #end @@ -26,6 +26,8 @@ global_settings{ assumed_gamma 1.0 } bitwise_and((X > 0), (bitwise_and(X, (X - 1)) = 0)) #end +#macro Abs(C) sqrt(C.x * C.x + C.y * C.y) #end + #macro _FFT0(X, Y, N, Stride, EO) #local M = div(N, 2); #local Theta = 2 * pi / N; diff --git a/Task/Fast-Fourier-transform/PascalABC.NET/fast-fourier-transform.pas b/Task/Fast-Fourier-transform/PascalABC.NET/fast-fourier-transform.pas new file mode 100644 index 0000000000..f6b42e2fa0 --- /dev/null +++ b/Task/Fast-Fourier-transform/PascalABC.NET/fast-fourier-transform.pas @@ -0,0 +1,32 @@ +function fft(x: array of complex): array of complex; +begin + var n := x.length; + if n = 0 then exit; + + setlength(result, n); + + if n = 1 then + begin + result[0] := x[0]; + exit; + end; + + var evens := x.Where((x, i) -> i mod 2 = 0).ToArray; + var odds := x.Where((x, i) -> i mod 2 = 1).ToArray; + var (even, odd) := (fft(evens), fft(odds)); + + var halfn := n div 2; + + for var k := 0 to halfn - 1 do + begin + var a := exp(new Complex(0.0, -2 * Pi * k / n)) * odd[k]; + result[k] := even[k] + a; + result[k + halfn] := even[k] - a; + end; +end; + +begin + var test := |1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0|; + foreach var x in fft(test.select(x -> new Complex(x, 0)).ToArray) do + println(x) +end. diff --git a/Task/Fast-Fourier-transform/Swift/fast-fourier-transform.swift b/Task/Fast-Fourier-transform/Swift/fast-fourier-transform.swift index ff86082f2b..aba4575660 100644 --- a/Task/Fast-Fourier-transform/Swift/fast-fourier-transform.swift +++ b/Task/Fast-Fourier-transform/Swift/fast-fourier-transform.swift @@ -5,7 +5,7 @@ typealias Complex = Numerics.Complex extension Complex { var exp: Complex { - Complex(cos(imaginary), sin(imaginary)) * Complex(cosh(real), sinh(real)) + Complex(cos(imaginary), sin(imaginary)) * Complex(cosh(real) + sinh(real), 0) } var pretty: String { diff --git a/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-3.py b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-3.py index fb273a2545..bc445d27d1 100644 --- a/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-3.py +++ b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-3.py @@ -1,19 +1,19 @@ from itertools import islice, cycle -def fiblike(tail): - for x in tail: - yield x - for i in cycle(xrange(len(tail))): +def fiblike(init_values=(0, 1)): + tail = list(init_values) + yield from tail + for i in cycle(range(len(tail))): tail[i] = x = sum(tail) yield x -fibo = fiblike([1, 1]) -print list(islice(fibo, 10)) +print([*islice(fiblike(), 10)]) lucas = fiblike([2, 1]) -print list(islice(lucas, 10)) +print([*islice(lucas, 10)]) -suffixes = "fibo tribo tetra penta hexa hepta octo nona deca" -for n, name in zip(xrange(2, 11), suffixes.split()): - fib = fiblike([1] + [2 ** i for i in xrange(n - 1)]) +suffixes = dict(enumerate('fibo tribo tetra penta hexa hepta octo nona deca'.split(), start=2)) + +for name, n in suffixes.items(): + fib = fiblike([1] + [2 ** i for i in range(n-1)]) items = list(islice(fib, 15)) - print "n=%2i, %5snacci -> %s ..." % (n, name, items) + print(f'n={n:>2}, {name:>5}nacci -> {items} ...') diff --git a/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-5.py b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-5.py new file mode 100644 index 0000000000..d95bd55348 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-5.py @@ -0,0 +1,34 @@ +from itertools import chain + +def A000032(): + '''Non finite sequence of Lucas numbers. + ''' + return unfoldr(recurrence, [0, 1]) + +def n_step_fibonacci(n): + '''Non-finite series of N-step Fibonacci numbers, + defined by a recurrence relation. + ''' + return unfoldr( + recurrence, + chain( + (0,), + (2 ** i for i in range(0, n-1)))) + +def recurrence(xs): + '''Recurrence relation in Fibonacci and related series. + ''' + h, *t = xs + return h, t + [sum(xs)] + +def unfoldr(f, residue): + '''Generic anamorphism. + A lazy (generator) list unfolded from a seed value by + repeated application of f until no residue remains. + Dual to fold/reduce. + f returns either None, or just (value, residue). + For a strict output value, wrap in list(). + ''' + while residue is not None: + value, residue = f(residue) + yield value diff --git a/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-6.py b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-6.py new file mode 100644 index 0000000000..0de67431c2 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-6.py @@ -0,0 +1,46 @@ +from itertools import chain + +def f_rec_tailfail(values=[0, 1], combine=sum): + """ + This fails with `RecursionError: maximum recursion depth exceeded` + when the number of consumed elements surpasses maximum stack size + (by default 1000 call frames -- `sys.getrecursionlimit()`), + due to the fact that Python does not have tail call optimization. + """ + yield values[0] + yield from f_rec_tailfail(values[1:] + [combine(values)], combine) + + +def f_rec_gen_func(values=[0, 1], combine=sum): + """ + This function does not suffer from `RecursionError` per se, but stack overflow + nevertheless does happen in the underlying C code when too many elements are + consumed from the generator. + + One possible reason for this is because `chain` is implemented in C, + and the chain consists of another `chain` object, which in turn contains + another `chain` object, etc. The effect of this is that all the recursive + calls happen on the C call stack (where recursion depth is not checked + against the limit), not on the Python call stack. As a result, it is possible + to achieve much greater recursion depth -- over 40,000 recursive calls + instead of mere 1000. When a stack overflow eventually happens, the Python + interpreter crashes quietly without any error message (CPython 3.11.3 AMD64). + """ + def generate_values(): + yield [values[0]] + yield f_rec_gen_func(values[1:] + [combine(values)], combine) + return chain.from_iterable(generate_values()) + + +def f_rec_gen_lambdas(values=[0, 1], combine=sum): + """ + Similar to `f_rec_gen_func`; also does not suffer from `RecursionError` + but crashes when many values are consumed. + """ + return chain.from_iterable( + f() + for f in ( + lambda: [values[0]], + lambda: f_rec_gen_lambdas(values[1:] + [combine(values)], combine), + ) + ) diff --git a/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-7.py b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-7.py new file mode 100644 index 0000000000..7889a4ed7b --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Python/fibonacci-n-step-number-sequences-7.py @@ -0,0 +1,35 @@ +from dataclasses import dataclass, field +from functools import wraps +from typing import Callable, Generator + +GeneratorFunc = Callable[..., Generator] + +@dataclass +class RecursiveCall: + args: tuple = () + kwargs: dict = field(default_factory=dict) + +def tail_recursive_generator(fun: GeneratorFunc) -> GeneratorFunc: + @wraps(fun) + def decorated(*args, **kwargs): + while True: + it = fun(*args, **kwargs) + try: + while True: + yield next(it) + except StopIteration as e: + if not isinstance(res := e.value, RecursiveCall): + return res + args, kwargs = res.args, res.kwargs + + return decorated + +@tail_recursive_generator +def f_rec_tail(values=(0, 1), combine=sum): + """ + Does not crash or throw RecursionError! Yay! + """ + yield values[0] + # determining why we cannot call `f_rec_tail` directly + # is left as an exercise for the reader... + return RecursiveCall(args=(values[1:] + (combine(values),), combine)) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs index 593d8551aa..a2360de226 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs @@ -1,35 +1,17 @@ -import Control.Arrow ((&&&)) +import Data.Ratio (numerator) -fibstep :: (Integer, Integer) -> (Integer, Integer) -fibstep (a, b) = (b, a + b) +infixl 7 *. +(*.) :: Num a => a -> [a] -> [a] +x *. (p:ps) = x*p : x*.ps -fibnums :: [Integer] -fibnums = map fst $ iterate fibstep (0, 1) +instance Num a => Num [a] where + negate = map negate + (+) = zipWith (+) + (*) (p:ps) (q:qs) = p*q : ((p*.qs) + ps*(q:qs)) + fromInteger n = fromInteger n:repeat 0 -fibN2 :: Integer -> (Integer, Integer) -fibN2 m - | m < 10 = iterate fibstep (0, 1) !! fromIntegral m -fibN2 m = fibN2_next (n, r) (fibN2 n) - where - (n, r) = quotRem m 3 +instance (Eq a, Fractional a) => Fractional [a] where + (/) (0:ps) (0:qs) = ps/qs + (/) (p:ps) (q:qs) = let r=p/q in r : (ps - r*.qs)/(q:qs) -fibN2_next (n, r) (f, g) - | r == 0 = (a, b) -- 3n ,3n+1 - | r == 1 = (b, c) -- 3n+1,3n+2 - | r == 2 = (c, d) -- 3n+2,3n+3 (*) - where - a = - 5 * f ^ 3 + - if even n - then 3 * f - else (-3 * f) -- 3n - b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 - c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 - d = - 5 * g ^ 3 + - if even n - then (-3 * g) - else 3 * g -- 3(n+1) (*) - -main :: IO () -main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) + fromRational q = fromRational q:repeat 0 diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs index c69d736bc9..4c4bac3a5c 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs @@ -1,2 +1,3 @@ - *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) -(208988,"19532821287077577316") +fibs :: [Integer] +fibs = map numerator + (1/(1 : (-1) : (-1) : repeat 0)) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs index 7f0a39dbc2..b41a6a08fd 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-19.hs @@ -1 +1,2 @@ -f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth +ghci> take 15 fibs +[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610] diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs index dd052ec7a3..ef2e13f1a0 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-20.hs @@ -1 +1,8 @@ -g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth +import Data.Functor.Identity (Identity (..)) + +fibs :: [Integer] +fibs = runIdentity (hsequence (repeat f)) + where f [] = Identity 1 + f [_] = Identity 1 + f xs = Identity ((xs !! (i-1)) + (xs !! i)) + where i = length xs-1 diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-21.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-21.hs new file mode 100644 index 0000000000..3152e83315 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-21.hs @@ -0,0 +1,6 @@ +hsequence :: Monad m => [[x] -> m x] -> m [x] +hsequence [] = pure [] +hsequence (r:rs) = do + x <- r [] + xs <- hsequence [ \ys -> g (x:ys) | g <- rs ] + pure (x:xs) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-22.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-22.hs new file mode 100644 index 0000000000..8340df8cb9 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-22.hs @@ -0,0 +1,2 @@ +ghci> take 17 fibs +[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597] diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-23.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-23.hs new file mode 100644 index 0000000000..593d8551aa --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-23.hs @@ -0,0 +1,35 @@ +import Control.Arrow ((&&&)) + +fibstep :: (Integer, Integer) -> (Integer, Integer) +fibstep (a, b) = (b, a + b) + +fibnums :: [Integer] +fibnums = map fst $ iterate fibstep (0, 1) + +fibN2 :: Integer -> (Integer, Integer) +fibN2 m + | m < 10 = iterate fibstep (0, 1) !! fromIntegral m +fibN2 m = fibN2_next (n, r) (fibN2 n) + where + (n, r) = quotRem m 3 + +fibN2_next (n, r) (f, g) + | r == 0 = (a, b) -- 3n ,3n+1 + | r == 1 = (b, c) -- 3n+1,3n+2 + | r == 2 = (c, d) -- 3n+2,3n+3 (*) + where + a = + 5 * f ^ 3 + + if even n + then 3 * f + else (-3 * f) -- 3n + b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 + c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 + d = + 5 * g ^ 3 + + if even n + then (-3 * g) + else 3 * g -- 3(n+1) (*) + +main :: IO () +main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-24.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-24.hs new file mode 100644 index 0000000000..c69d736bc9 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-24.hs @@ -0,0 +1,2 @@ + *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) +(208988,"19532821287077577316") diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-25.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-25.hs new file mode 100644 index 0000000000..7f0a39dbc2 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-25.hs @@ -0,0 +1 @@ +f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-26.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-26.hs new file mode 100644 index 0000000000..dd052ec7a3 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-26.hs @@ -0,0 +1 @@ +g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth diff --git a/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur b/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur index 1eaa61b5f6..9db6f35cd7 100644 --- a/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur +++ b/Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur @@ -1,3 +1,3 @@ val fibonacci = fn x:if(x < 2: x ; fn((x - 1)) + fn((x - 2))) -writeln map(fibonacci, series(2..20)) +writeln map(series(2..20), by=fibonacci) diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-14.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-14.py index 5e6109260b..9ef20e2594 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-14.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-14.py @@ -1,8 +1,6 @@ '''Fibonacci accumulation''' -from itertools import accumulate, chain -from operator import add - +from itertools import accumulate # fibs :: Integer :: [Integer] def fibs(n): @@ -10,22 +8,16 @@ def fibs(n): the Fibonacci series. The accumulator is a pair of the two preceding numbers. ''' - def go(ab, _): - return ab[1], add(*ab) - - return [xy[1] for xy in accumulate( - chain( - [(0, 1)], - range(1, n) - ), - go - )] + return [ + a + for a, b in accumulate( + range(1, n), # we don't actually use these numbers + lambda acc, _: (acc[1], sum(acc)), + initial = (0, 1) + ) + ] # MAIN --- if __name__ == '__main__': - print( - 'First twenty: ' + repr( - fibs(20) - ) - ) + print(f'First twenty: {fibs(20)}') diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-15.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-15.py index 9da8f6a398..7cd4d0fa62 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-15.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-15.py @@ -1,21 +1,18 @@ '''Nth Fibonacci term (by folding)''' from functools import reduce -from operator import add - # nthFib :: Integer -> Integer def nthFib(n): '''Nth integer in the Fibonacci series.''' - def go(ab, _): - return ab[1], add(*ab) - return reduce(go, range(1, n), (0, 1))[1] + return reduce( + lambda acc, _: (acc[1], sum(acc)), + range(1, n), + (0, 1) + )[0] # MAIN --- if __name__ == '__main__': - print( - '1000th term: ' + repr( - nthFib(1000) - ) - ) + n = 1000 + print(f'{n}th term: {nthFib(n)}') diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-18.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-18.py deleted file mode 100644 index 4f15e0818e..0000000000 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-18.py +++ /dev/null @@ -1,7 +0,0 @@ -fi1=fi2=fi3=1 # FIB Russia rextester.com/FEEJ49204 -for da in range(1, 88): # Danilin - print("."*(20-len(str(fi3))), end=' ') - print(fi3) - fi3 = fi2+fi1 - fi1 = fi2 - fi2 = fi3 diff --git a/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys b/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys index d15ba93346..c3c49b69b6 100644 --- a/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys +++ b/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(n=10): loop a 0, b 1, i 1: diff --git a/Task/Fibonacci-word/Forth/fibonacci-word.fth b/Task/Fibonacci-word/Forth/fibonacci-word.fth new file mode 100644 index 0000000000..b5cf419abc --- /dev/null +++ b/Task/Fibonacci-word/Forth/fibonacci-word.fth @@ -0,0 +1,36 @@ +: .fibword ( n -- ) + dup case + 0 of drop ." 1" endof + 1 of drop ." 0" endof + dup 1- recurse + 2 - recurse + endcase ; + +fvariable ilog2 +1e 2e fln f/ ilog2 f! + +: flog2 ( r -- r ) + fdup f0<> if + fln ilog2 f@ f* + then ; + +: entropy ( n1 n2 -- r ) + 2dup + s>f s>f fover f/ fswap s>f fswap f/ + fdup flog2 f* fswap fdup flog2 f* f+ + fnegate ; + +: main + ." N Length Entropy Word" cr + 1 0 + 37 0 do + i 1+ 2 .r + 2dup + 10 .r space + 2dup entropy 17 15 1 f.rdp space + i 9 < if i .fibword else ." ..." then + cr + tuck + + loop + 2drop ; + +main +bye diff --git a/Task/Fibonacci-word/FutureBasic/fibonacci-word.basic b/Task/Fibonacci-word/FutureBasic/fibonacci-word.basic new file mode 100644 index 0000000000..c54549850e --- /dev/null +++ b/Task/Fibonacci-word/FutureBasic/fibonacci-word.basic @@ -0,0 +1,69 @@ +include "NSLog.incl" + +begin globals + CFStringRef cur, nex +end globals + + +CFStringRef local fn Increment + CFStringRef ret = cur + cur = nex + nex = fn StringWithFormat( @"%@%@", ret, nex ) +end fn = ret + +double local fn GetEntropy( s as CFArrayRef ) + double entropy = 0.0 + double hist(256) + NSUInteger i + + for i = 0 to 255 + hist(i)= 0 + next + + for CFNumberRef num in s + hist( fn NumberIntegerValue(num) ) += 1 + next + + for i = 0 to 255 + if ( hist(i) > 0 ) + double rat = hist(i) / fn ArrayCount( s ) + entropy -= rat * log2(rat) + end if + next + return entropy +end fn = 0.0 + +CFStringRef local fn ReverseString( string as CFStringRef ) + CFMutableStringRef reversedStr = fn MutableStringNew + for NSInteger i = len(string) - 1 to 0 step -1 + MutableStringAppendString( reversedStr, fn StringWithFormat( @"%c", fn StringCharacterAtIndex( string, i ) ) ) + next +end fn = reversedStr + +local fn DoIt + cur = @"1" + nex = @"0" + + NSLog( @"%5s %10s %11s %33s", "No.", "Length", "Entrophy", "Binary Fibonacci Word" ) + CFTimeInterval t = fn CACurrentMediaTime + for int i = 0 to 36 + CFStringRef string = fn Increment + CFMutableArrayRef asciiValues = fn MutableArrayNew + for NSUInteger j = 0 to len(string) - 1 + unichar character = fn StringCharacterAtIndex( string, j ) + MutableArrayAddObject( asciiValues, @(character) ) + next + double ent = fn GetEntropy( asciiValues ) + + if ( i <= 10 ) + NSLog( @"%3d. %9lu %19.15f %@", i+1, (unsigned long)len(string), ent, fn ReverseString( string ) ) + else + NSLog( @"%3d. %9lu %19.15f [length exceeds task limits]", i+1, (unsigned long)len(string), ent ) + end if + next + NSLog( @"\nCompute time: %.3f ms",(fn CACurrentMediaTime-t) * 1000 ) +end fn + +fn DoIt + +HandleEvents diff --git a/Task/File-input-output/Zig/file-input-output.zig b/Task/File-input-output/Zig/file-input-output.zig index 877fcc1dfb..8dac331546 100644 --- a/Task/File-input-output/Zig/file-input-output.zig +++ b/Task/File-input-output/Zig/file-input-output.zig @@ -1,20 +1,19 @@ const std = @import("std"); -pub fn main() (error{OutOfMemory} || std.fs.File.OpenError || std.fs.File.ReadError || std.fs.File.WriteError)!void { +pub fn main() !void { var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const cwd = std.fs.cwd(); - var input_file = try cwd.openFile("input.txt", .{ .mode = .read_only }); + var input_file = try cwd.openFile("input.txt", .{}); defer input_file.close(); var output_file = try cwd.createFile("output.txt", .{}); defer output_file.close(); - // Restrict input_file's size to "up to 10 MiB". - var input_file_content = try input_file.readToEndAlloc(allocator, 10 * 1024 * 1024); + const input_file_content = try input_file.readToEndAlloc(allocator, (try input_file.stat()).size); defer allocator.free(input_file_content); try output_file.writeAll(input_file_content); diff --git a/Task/Filter/Langur/filter.langur b/Task/Filter/Langur/filter.langur index 330dbc2ec2..de22c6a4a2 100644 --- a/Task/Filter/Langur/filter.langur +++ b/Task/Filter/Langur/filter.langur @@ -1,4 +1,4 @@ val zlist = series(7) writeln " list: ", zlist -writeln "filtered: ", filter(fn{div 2}, zlist) +writeln "filtered: ", filter(zlist, by=fn{div 2}) diff --git a/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy b/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy index da4b66fced..f57bc5c2a7 100644 --- a/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy +++ b/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy @@ -1,3 +1,10 @@ +ax = 10 +ay = 20 +bx = 90 +by = 30 +cx = 50 +cy = 80 +# func sgn px py ax ay bx by . return sign ((px - bx) * (ay - by) - (ax - bx) * (py - by)) . @@ -7,10 +14,6 @@ func isin px py ax ay bx by cx cy . z3 = sgn px py cx cy ax ay return if abs (z1 + z2 + z3) = 3 . -ax = 10 ; ay = 20 -bx = 90 ; by = 30 -cx = 50 ; cy = 80 -# move 5 90 textsize 4 text "Move mouse into the triangle" diff --git a/Task/Find-the-missing-permutation/FutureBasic/find-the-missing-permutation.basic b/Task/Find-the-missing-permutation/FutureBasic/find-the-missing-permutation.basic new file mode 100644 index 0000000000..a5bb1361ab --- /dev/null +++ b/Task/Find-the-missing-permutation/FutureBasic/find-the-missing-permutation.basic @@ -0,0 +1,31 @@ +void local fn Permute( string as CFStringRef, result as CFMutableArrayRef, current as CFStringRef ) + if ( len(string) == 0 ) then MutableArrayAddObject( result, current ) : return + for NSUInteger i = 0 to len(string) - 1 + unichar c = fn StringCharacterAtIndex( string, i ) + CFMutableStringRef remainingStr = fn MutableStringWithString( string ) + MutableStringDeleteCharacters( remainingStr, fn RangeMake( i, 1 ) ) + CFStringRef newCurrent = fn StringByAppendingFormat( current, @"%C", c ) + fn Permute( remainingStr, result, newCurrent ) + next +end fn + +local fn DoPermutations as CFStringRef + CFStringRef inputString = @"ABCD" + CFMutableArrayRef array1 = fn MutableArrayNew + fn Permute( inputString, array1, @"" ) + + CFArrayRef array2 = @[ + @"ABCD", @"CABD", @"ACDB", @"DACB", @"BCDA", @"ACBD", + @"ADCB", @"CDAB", @"DABC", @"BCAD", @"CADB", @"CDBA", + @"CBAD", @"ABDC", @"ADBC", @"BDCA", @"DCBA", @"BACD", + @"BADC", @"BDAC", @"CBDA", @"DBCA", @"DCAB"] + + CFMutableSetRef set1 = fn MutableSetWithArray( array1 ) + CFSetRef set2 = fn SetWithArray( array2 ) + MutableSetMinusSet( set1, set2 ) + return fn SetAnyObject( set1 ) +end fn = NULL + +printf @"%@", fn DoPermutations + +HandleEvents diff --git a/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java b/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java index 7b381dee6e..69c063ad4d 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java +++ b/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java @@ -2,7 +2,7 @@ import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; -public class FirstClassFunctionsUseNumbersAnalogously { +public final class FirstClassFunctionsUseNumbersAnalogously { public static void main(String[] args) { final double x = 2.0, xi = 0.5, diff --git a/Task/First-class-functions-Use-numbers-analogously/Quackery/first-class-functions-use-numbers-analogously.quackery b/Task/First-class-functions-Use-numbers-analogously/Quackery/first-class-functions-use-numbers-analogously.quackery new file mode 100644 index 0000000000..e477a97f20 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Quackery/first-class-functions-use-numbers-analogously.quackery @@ -0,0 +1,14 @@ + [ $ "bigrat.qky" loadfile ] now! + + [ 2 1 ] is x ( --> n/d ) + [ 1 2 ] is xi ( --> n/d ) + [ 4 1 ] is y ( --> n/d ) + [ 1 4 ] is yi ( --> n/d ) + [ x y v+ ] is z ( n/d n/d --> n/d ) + [ x y v+ 1/v ] is zi ( n/d n/d --> n/d ) + + [ ' [ v* v* ] join join ] is multiplier ( x n/d --> [ ) + +' xi ' [ 1 2 ] multiplier dup echo x rot do say " applied to x gives: " vulgar$ echo$ cr +' yi ' [ 1 2 ] multiplier dup echo y rot do say " applied to y gives: " vulgar$ echo$ cr +' zi ' [ 1 2 ] multiplier dup echo z rot do say " applied to z gives: " vulgar$ echo$ cr diff --git a/Task/Fivenum/EMal/fivenum.emal b/Task/Fivenum/EMal/fivenum.emal index bacb48ca7f..44415e8e61 100644 --- a/Task/Fivenum/EMal/fivenum.emal +++ b/Task/Fivenum/EMal/fivenum.emal @@ -2,7 +2,7 @@ type Fivenum int ILLEGAL_ARGUMENT = 0 fun median = real by List x, int start, int endInclusive int size = endInclusive - start + 1 - if size <= 0 do Event.error(ILLEGAL_ARGUMENT, "Array slice cannot be empty").raise() end + if size <= 0 do error(ILLEGAL_ARGUMENT, "Array slice cannot be empty") end int m = start + size / 2 return when(size % 2 == 1, x[m], (x[m - 1] + x[m]) / 2.0) end diff --git a/Task/Fixed-length-records/Jq/fixed-length-records.jq b/Task/Fixed-length-records/Jq/fixed-length-records.jq index 8f27c59448..aa773fce7d 100644 --- a/Task/Fixed-length-records/Jq/fixed-length-records.jq +++ b/Task/Fixed-length-records/Jq/fixed-length-records.jq @@ -1,4 +1,3 @@ -def cut($n): def nwise($n): def n: if length <= $n then . else .[0:$n] , (.[$n:] | n) end; n; diff --git a/Task/FizzBuzz/Nu/fizzbuzz-1.nu b/Task/FizzBuzz/Nu/fizzbuzz-1.nu new file mode 100644 index 0000000000..2ce6276c9d --- /dev/null +++ b/Task/FizzBuzz/Nu/fizzbuzz-1.nu @@ -0,0 +1,9 @@ +1..100 | each { + { x: $in, mod3: ($in mod 3), mod5: ($in mod 5), } + | match $in { + { mod3: 0, mod5: 0, } => 'FizzBuz', + { mod3: 0, mod5: _, } => 'Fizz', + { mod3: _, mod5: 0, } => 'Buzz', + _ => $in.x + } +} | str join "\n" diff --git a/Task/FizzBuzz/Nu/fizzbuzz-2.nu b/Task/FizzBuzz/Nu/fizzbuzz-2.nu new file mode 100644 index 0000000000..857bc7cdcb --- /dev/null +++ b/Task/FizzBuzz/Nu/fizzbuzz-2.nu @@ -0,0 +1,3 @@ +1..100 | each { + if $in mod 15 == 0 {'FizzBuzz'} else if $in mod 3 == 0 {'Fizz'} else if $in mod 5 == 0 {'Buzz'} else {$in} +} | str join "\n" diff --git a/Task/FizzBuzz/Nu/fizzbuzz-3.nu b/Task/FizzBuzz/Nu/fizzbuzz-3.nu new file mode 100644 index 0000000000..00f958a9c6 --- /dev/null +++ b/Task/FizzBuzz/Nu/fizzbuzz-3.nu @@ -0,0 +1,6 @@ +1..100 | each {( + if $in mod 15 == 0 {'FizzBuzz'} + else if $in mod 3 == 0 {'Fizz'} + else if $in mod 5 == 0 {'Buzz'} + else {$in} +)} | str join "\n" diff --git a/Task/FizzBuzz/Nu/fizzbuzz.nu b/Task/FizzBuzz/Nu/fizzbuzz-4.nu similarity index 100% rename from Task/FizzBuzz/Nu/fizzbuzz.nu rename to Task/FizzBuzz/Nu/fizzbuzz-4.nu diff --git a/Task/FizzBuzz/Retro/fizzbuzz-1.retro b/Task/FizzBuzz/Retro/fizzbuzz-1.retro deleted file mode 100644 index beb6d646a4..0000000000 --- a/Task/FizzBuzz/Retro/fizzbuzz-1.retro +++ /dev/null @@ -1,8 +0,0 @@ -: fizz? ( s-f ) 3 mod 0 = ; -: buzz? ( s-f ) 5 mod 0 = ; -: num? ( s-f ) dup fizz? swap buzz? or 0 = ; -: ?fizz ( s- ) fizz? [ "Fizz" puts ] ifTrue ; -: ?buzz ( s- ) buzz? [ "Buzz" puts ] ifTrue ; -: ?num ( s- ) num? &putn &drop if ; -: fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ; -: all ( - ) 100 [ 1+ fizzbuzz ] iter ; diff --git a/Task/FizzBuzz/Retro/fizzbuzz-2.retro b/Task/FizzBuzz/Retro/fizzbuzz-2.retro deleted file mode 100644 index 5912fde82c..0000000000 --- a/Task/FizzBuzz/Retro/fizzbuzz-2.retro +++ /dev/null @@ -1,6 +0,0 @@ -needs math' -: - [ 15 ^math'divisor? ] [ drop "FizzBuzz" puts ] when - [ 3 ^math'divisor? ] [ drop "Fizz" puts ] when - [ 5 ^math'divisor? ] [ drop "Buzz" puts ] when putn ; -: fizzbuzz cr 100 [ 1+ space ] iter ; diff --git a/Task/FizzBuzz/Retro/fizzbuzz.retro b/Task/FizzBuzz/Retro/fizzbuzz.retro new file mode 100644 index 0000000000..0d0a9928be --- /dev/null +++ b/Task/FizzBuzz/Retro/fizzbuzz.retro @@ -0,0 +1,26 @@ +( empty string result to display result ) +~~~ + +'result var +' s:format !result + +'number var +#1 !number + +~~~ +( checks for empty string if result empty print number ) +( else append fizz for divisible by 3 and prepend buzz for divisible by 5) +( if; exists the word fizzbuzz immediately ) +~~~ + +:fizzbuzz (-) + @number #3 mod #0 eq? [ 'fizz @result s:append !result ] if + @number #5 mod #0 eq? [ 'buzz @result s:prepend !result ] if + ' @result s:eq? [ @number n:put nl ] if; + ' @result s:eq? not [ @result s:put nl ] if; + ; + +[ fizzbuzz 'result var + ' s:format !result @number #1 + !number @number #100 lteq? ] while + +~~~ diff --git a/Task/FizzBuzz/YAMLScript/fizzbuzz.ys b/Task/FizzBuzz/YAMLScript/fizzbuzz.ys index 7dbb165768..1021f2a5f0 100644 --- a/Task/FizzBuzz/YAMLScript/fizzbuzz.ys +++ b/Task/FizzBuzz/YAMLScript/fizzbuzz.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(n=100): each x (1 .. n): !:say diff --git a/Task/FizzBuzz/Zig/fizzbuzz.zig b/Task/FizzBuzz/Zig/fizzbuzz.zig index 6630d76864..d69633205d 100644 --- a/Task/FizzBuzz/Zig/fizzbuzz.zig +++ b/Task/FizzBuzz/Zig/fizzbuzz.zig @@ -1,7 +1,7 @@ const print = @import("std").debug.print; pub fn main() void { - var i: usize = 1; - while (i <= 100) : (i += 1) { + + for(1..101) |i| { if (i % 3 == 0 and i % 5 == 0) { print("FizzBuzz\n", .{}); } else if (i % 3 == 0) { diff --git a/Task/Flipping-bits-game/FutureBasic/flipping-bits-game.basic b/Task/Flipping-bits-game/FutureBasic/flipping-bits-game.basic new file mode 100644 index 0000000000..16581081a8 --- /dev/null +++ b/Task/Flipping-bits-game/FutureBasic/flipping-bits-game.basic @@ -0,0 +1,99 @@ +uint16 board( 9 ), goal( 9 ) +int size, count, mask +colorref hue( 1 ) +CFStringRef key +bool win + +local fn show + int x = 20, y = 20, row, col, v, t = size * 20 + 63 + text @"Courier", 17, fn ColorGray, fn colorClear + cls + printf@"\n GOAL" + print @( size * 2 + 8, 1 )"BOARD" + for row = 0 to size -1 + y = row * 20 + 40 + for col = 0 to size - 1 + v = ( goal( row ) & bit( col ) ) > 0 + x = col * 20 + 20 + rect fill ( x, y, 19, 19 ), hue( v ) + print %( x + 5, y - 2 ) v + x += t + v = ( board( row ) & bit( col ) ) > 0 + rect fill ( x, y, 19, 19 ), hue( v ) + print %( x + 5, y - 2 ) v + next + print %( x + 25, y - 2 ) mid( key, size + row, 1 ) + next + //print %( t + 15, y + 17 ) left( @" A B C D E F G H I J", size * 2 ) //Alternate + print %( t + 15, y + 17 ) left( @" Q W E R T Y U I O P", size * 2 ) + print %( size * 20 + 26, size * 10 + 20 )@"MOVES" + print %( t - 18, size * 10 + 40 )count +end fn + +local fn match as bool + for int r = 0 to size -1 + if board( r ) <> goal( r ) then return no + next +end fn = yes + +local fn move( k as int ) + select k + case >= size : board( k - size) ^^= mask //row + case >= 0 //column + for int r = 0 to size -1 + board( r ) ^^= bit( k ) + next + case else : exit fn + end select + DialogEventSetBool(YES) // we handled the event + count ++ + fn show +end fn + +local fn newGame + int r + for r = 0 to size -1 + board( r ) = rnd( mask ) -1 + next + fn memmove( @goal( 0 ), @board( 0 ), 20 ) + do + for r = 0 to size + fn move( rnd( size * 2 ) -1) + next + until !fn match + count = 0 + fn show +end fn + +local fn init( sz as int ) + if sz < 3 | sz > 10 then stop "Size param must be 3-10" : end + size = sz//:stop + mask = bit( size ) - 1 + hue( 0 ) = fn colorYellow + hue( 1 ) = fn colorcyan//Green + subclass window 1, @"Flipping bits puzzle", ( 0, 0, sz * 40 + 123, sz * 20 + 80 )¬ + , NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + //key = fn StringWithFormat( @"Q%@%@", left( @"ABCDEFGHIJ", sz ), left( @"1234567890", sz ) ) //Alternate + key = fn StringWithFormat( @"%@%@", LEFT( @"QWERTYUIOP", sz ), left( @"1234567890", sz ) ) + fn newGame +end fn + +local fn doDialog( evt as long ) + select ( evt ) + case _windowKeyDown + if win then win = no : fn newGame : exit fn + fn move( instr( 0, key, fn EventCharacters, NSCaseInsensitiveSearch ) ) + if fn match + text ,,_zRed + print @(size*2 + 1, 0)"SOLVED!" + print %(20,size*20+50)"Any key for new game." + win = yes : beep + end if + case _windowWillClose : end + end select +end fn + +on dialog fn DoDialog +fn init( 3 ) +fn newGame +handleevents diff --git a/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys b/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys index d1619de731..b633b847da 100644 --- a/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys +++ b/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(n): nums =: range().map(inc).map(str) diff --git a/Task/Forest-fire/Locomotive-Basic/forest-fire-1.basic b/Task/Forest-fire/Locomotive-Basic/forest-fire-1.basic new file mode 100644 index 0000000000..0762b99f10 --- /dev/null +++ b/Task/Forest-fire/Locomotive-Basic/forest-fire-1.basic @@ -0,0 +1,33 @@ +10 randomize time:mode 1:ink 0,0:ink 1,9:ink 2,15:defint a-o,r-z +20 pfire=0.00002:ptree=0.002 +30 dimx=90:dimy=90 +40 dim forest(dimx,dimy), forest2(dimx,dimy) +50 for y=1 to dimy-1:for x=1 to dimx-1 +60 if rnd<.5 then forest(x,y)=1 +70 next:next +80 gosub 1000 +100 for y=1 to dimy-1 +110 for x=1 to dimx-1 +120 on forest(x,y)+1 gosub 500,600,700 +130 next:next +140 for y=1 to dimy-1 +150 for x=1 to dimx-1 +160 forest(x,y)=forest2(x,y) +170 next:next +180 gosub 1000 +190 goto 100 +500 if rnd 0 THEN + component +:= " " + power suffix[ power pos ] + FI; + IF result /= "" THEN component +:= " " FI; + component +=: result + FI; + power pos +:= 1; + v OVERAB 1000 + OD; + result + FI # NAME # ; + # returns the "x is y, y is z, ... four is magic" sequence derived from n # + OP MAGIC = ( NUMBER n )STRING: + BEGIN + NUMBER v := n; + STRING result := ""; + WHILE v /= 4 DO + IF result /= "" THEN result +:= ", " FI; + STRING v name = NAME v; + v := ( UPB v name - LWB v name ) + 1; + result +:= v name + " is " + NAME v + OD; + IF result /= "" THEN result +:= ", " FI; + result + "four is magic" + END # MAGIC # ; + # test cases # + []NUMBER t = ( 0, 1, 2, 3, 4, 5, 100, 101, 272, 1701, 1968, 4077, 90 210 + , - 100 001, 987 654, - NUMBER( 8 007 006 005 004 003 ) + ); + FOR n FROM LWB t TO UPB t DO + print( ( whole( t[ n ], -18 ), ": ", MAGIC t[ n ], newline ) ) + OD +END diff --git a/Task/Four-is-magic/Common-Lisp/four-is-magic.lisp b/Task/Four-is-magic/Common-Lisp/four-is-magic.lisp index d8fa958084..4f8ab2f47b 100644 --- a/Task/Four-is-magic/Common-Lisp/four-is-magic.lisp +++ b/Task/Four-is-magic/Common-Lisp/four-is-magic.lisp @@ -5,3 +5,6 @@ while (/= n 4) do (format out "~A is ~R, " c (length c)) finally (format out "four is magic."))))) +(loop for n + in '( -1 0 1 2 3 4 5 6 7 8 9 11 21 1995 1000000 1234567890 1100100100100 ) + do (print (integer-to-text n))) diff --git a/Task/Four-is-magic/M2000-Interpreter/four-is-magic.m2000 b/Task/Four-is-magic/M2000-Interpreter/four-is-magic.m2000 new file mode 100644 index 0000000000..08efda8634 --- /dev/null +++ b/Task/Four-is-magic/M2000-Interpreter/four-is-magic.m2000 @@ -0,0 +1,67 @@ +module Four_is_magic { + numname=lambda ->{ + flush + data "", "one", "two", "three", "four" + data "five", "six", "seven", "eight", "nine", "ten" + data "eleven", "twelve", "thirteen", "fourteen", "fifteen" + data "sixteen", "seventeen","eighteen", "nineteen" + dim lows(), tens(), lev() + lows()=array([]) + data "", "", "twenty", "thirty", "forty","fifty", "sixty" + data "seventy", "eighty", "ninety" + tens()=array([]) + lev()=("", "thousand", "million", "billion") + =lambda lows(), tens(), lev() (n as long) -> { + if n=0 then ="zero": exit + long i, tr : boolean t : string ret, prefix + if n < 0 then prefix= "negative ": n-! else prefix="" + while n>0 {push n mod 1000: n|div 1000} + t=stack.size>1 + while not empty { + tripn="" : read tr : if tr=0 then continue + lt= tr mod 100 : h= tr div 100 + if lt<20 then + tripn+=lows(lt) + else + tripn=tens(lt div 10)+if$(lt mod 10 >0 ->"-"+lows(lt mod 10),"") + end if + if h>0 then tripn = lows(h)+" hundred " + tripn + if empty then if t and h = 0 then tripn = " and " + tripn + ret+=tripn+" "+lev(stack.size)+" " + } + =prefix+trim$(ret) + } + }() + TitleStr=lambda (s as string) ->{ + =ucase$(left$(s,1))+mid$(s, 2) + } + magic=lambda numname, TitleStr (n as integer)-> { + first$=numname(n) + count$=numname(len(first$)) + while first$<>"four" + data first$+" is "+count$ + swap first$, count$ + count$=numname(len(first$)) + end while + data "four is magic." + =TitleStr(array([])#str$(", ")) + } + document doc$ + for i=0 to 9 + doc$ = magic(i)+{ + } + next + doc$ = magic(23)+{ + } + doc$ = magic(130)+{ + } + doc$ = magic(151)+{ + } + doc$ = magic(-7)+{ + } + doc$ = magic(20140)+{ + } + report doc$ + clipboard doc$ +} +Four_is_magic diff --git a/Task/Four-is-the-number-of-letters-in-the-.../FreeBASIC/four-is-the-number-of-letters-in-the-....basic b/Task/Four-is-the-number-of-letters-in-the-.../FreeBASIC/four-is-the-number-of-letters-in-the-....basic new file mode 100644 index 0000000000..4ed3cc24f9 --- /dev/null +++ b/Task/Four-is-the-number-of-letters-in-the-.../FreeBASIC/four-is-the-number-of-letters-in-the-....basic @@ -0,0 +1,173 @@ +#include "string.bi" + +Type NumberNames + cardinal As ZString Ptr + ordinal As ZString Ptr +End Type + +Type NamedNumber + cardinal As ZString Ptr + ordinal As ZString Ptr + number As Ulongint +End Type + +' Arrays of number names +Dim Shared small(0 To 19) As NumberNames = { _ +(@"zero", @"zeroth"), (@"one", @"first"), (@"two", @"second"), _ +(@"three", @"third"), (@"four", @"fourth"), (@"five", @"fifth"), _ +(@"six", @"sixth"), (@"seven", @"seventh"), (@"eight", @"eighth"), _ +(@"nine", @"ninth"), (@"ten", @"tenth"), (@"eleven", @"eleventh"), _ +(@"twelve", @"twelfth"), (@"thirteen", @"thirteenth"), _ +(@"fourteen", @"fourteenth"), (@"fifteen", @"fifteenth"), _ +(@"sixteen", @"sixteenth"), (@"seventeen", @"seventeenth"), _ +(@"eighteen", @"eighteenth"), (@"nineteen", @"nineteenth") } + +Dim Shared tens(0 To 7) As NumberNames = { _ +(@"twenty", @"twentieth"), (@"thirty", @"thirtieth"), _ +(@"forty", @"fortieth"), (@"fifty", @"fiftieth"), _ +(@"sixty", @"sixtieth"), (@"seventy", @"seventieth"), _ +(@"eighty", @"eightieth"), (@"ninety", @"ninetieth") } + +Dim Shared namedNumbers(0 To 6) As NamedNumber = { _ +(@"hundred", @"hundredth", 100ULL), _ +(@"thousand", @"thousandth", 1000ULL), _ +(@"million", @"millionth", 1000000ULL), _ +(@"billion", @"billionth", 1000000000ULL), _ +(@"trillion", @"trillionth", 1000000000000ULL), _ +(@"quadrillion", @"quadrillionth", 1000000000000000ULL), _ +(@"quintillion", @"quintillionth", 1000000000000000000ULL) } + +Function getName(n As NumberNames, ordinal As Boolean) As String + Return *Iif(ordinal, n.ordinal, n.cardinal) +End Function + +Function getNamedName(n As NamedNumber, ordinal As Boolean) As String + Return *Iif(ordinal, n.ordinal, n.cardinal) +End Function + +Function getNamedNumber(n As Ulongint) As NamedNumber + For i As Integer = 0 To 5 + If n < namedNumbers(i + 1).number Then Return namedNumbers(i) + Next + Return namedNumbers(6) +End Function + +Function isLetter(c As Integer) As Boolean + Return ((c >= 65 And c <= 90) Or (c >= 97 And c <= 122)) +End Function + +Function countLetters(s As String) As Integer + Dim cnt As Integer = 0 + For i As Integer = 1 To Len(s) + If isLetter(Asc(Mid(s, i, 1))) Then cnt += 1 + Next + Return cnt +End Function + +Sub appendNumberName(result As String Ptr, n As Ulongint, ordinal As Boolean, Byref resultCount As Integer) + Static As String tempStr + + If n < 20 Then + result[resultCount] = getName(small(n), ordinal) + resultCount += 1 + Elseif n < 100 Then + If (n Mod 10) = 0 Then + result[resultCount] = getName(tens(n\10 - 2), ordinal) + Else + tempStr = getName(tens(n\10 - 2), False) + tempStr &= "-" + tempStr &= getName(small(n Mod 10), ordinal) + result[resultCount] = tempStr + End If + resultCount += 1 + Else + Dim As NamedNumber num = getNamedNumber(n) + Dim As Ulongint p = num.number + appendNumberName(result, n\p, False, resultCount) + + If (n Mod p) = 0 Then + result[resultCount] = getNamedName(num, ordinal) + resultCount += 1 + Else + result[resultCount] = getNamedName(num, False) + resultCount += 1 + appendNumberName(result, n Mod p, ordinal, resultCount) + End If + End If +End Sub + +Function makeSentence(cnt As Integer, Byref resultSize As Integer) As String Ptr + Dim As Const String opening(0 To 12) = { _ + "Four", "is", "the", "number", "of", "letters", "in", "the", _ + "first", "word", "of", "this", "sentence," } + + Dim As String Ptr result = Callocate((cnt + 1) * Sizeof(String)) + resultSize = 0 + + ' Add opening words more efficiently + For i As Integer = 0 To 12 + If i = cnt Then Exit For + result[i] = opening(i) + Next + resultSize = Iif(cnt < 13, cnt, 13) + + ' Generate remaining words + Dim As Integer i = 1 + While resultSize < cnt + appendNumberName(result, countLetters(result[i]), False, resultSize) + If resultSize >= cnt Then Exit While + + result[resultSize] = "in" + result[resultSize + 1] = "the" + resultSize += 2 + If resultSize >= cnt Then Exit While + + appendNumberName(result, i + 1, True, resultSize) + result[resultSize - 1] += "," + i += 1 + Wend + + Return result +End Function + +' Main program +Dim As Integer n = 201 +Dim As Integer i, wordCount, totalLength +Dim As String Ptr words = makeSentence(n, wordCount) + +Print "The lengths of the first"; n; !" words are:\n" + +For i = 0 To n - 1 + If i Mod 25 = 0 Then Print Using "###: "; i + 1; + Print Using " ##"; countLetters(words[i]); + If (i + 1) Mod 25 = 0 Then Print +Next + +' Calculate sentence length more efficiently +totalLength = -1 ' Account for last space +For i = 0 To n - 1 + totalLength += Len(words[i]) + 1 ' Include space +Next + +Print !"\n\nLength of sentence = "; Format(totalLength, "#,###") +Deallocate(words) + +' Process larger numbers +n = 1000 +While n <= 10000000 + words = makeSentence(n, wordCount) + + ' Calculate sentence length + totalLength = -1 ' Start at -1 to account for last space + For i = 0 To n - 1 + totalLength += Len(words[i]) + 1 ' Add length plus space + Next + + Print !"\nThe length of word "; Format(n, "#,###"); " ["; words[n-1]; "] is "; countLetters(words[n-1]) + Print "Length of sentence = "; Format(totalLength, "#,###") + + Deallocate(words) + n *= 10 +Wend + +Sleep diff --git a/Task/Fractal-tree/Free-Pascal-Lazarus/fractal-tree.pas b/Task/Fractal-tree/Free-Pascal-Lazarus/fractal-tree.pas new file mode 100644 index 0000000000..ee20b18f8f --- /dev/null +++ b/Task/Fractal-tree/Free-Pascal-Lazarus/fractal-tree.pas @@ -0,0 +1,53 @@ +program FractalTree; + +uses + cthreads, // Required for multithreading on supported platforms + Math, PtcCrt, PtcGraph, SysUtils; + +const + TreeDepth = 17; // Maximum depth of the tree + +procedure DrawTree(X1, Y1: Integer; Angle: Double; Depth: Integer); +var + X2, Y2, Thickness: Integer; +begin + if Depth = 0 then + Exit; + + // Calculate the next point + X2 := Trunc(X1 + Cos(DegToRad(Angle)) * Depth * 6); + Y2 := Trunc(Y1 + Sin(DegToRad(Angle)) * Depth * 6); + + // Set the color based on depth + SetColor(986895 * Depth); + + // Dynamically calculate thickness (thicker at smaller depths) + Thickness := Max(1, Depth div 5); // Ensure thickness is at least 1 + SetLineStyle(0, 0, Thickness); + + // Draw the branch + Line(X1, Y1, X2, Y2); + + // Recursively draw the left and right branches + DrawTree(X2, Y2, Angle - 15, Depth - 1); + DrawTree(X2, Y2, Angle + 15, Depth - 1); +end; + +var + ModeInfo: PModeInfo; +begin + // Query and set the graphics mode for 1600x900 resolution with 24-bit color + ModeInfo := QueryAdapterInfo; + repeat + ModeInfo := ModeInfo^.Next; + until (ModeInfo^.MaxX = 1599) and (ModeInfo^.MaxY = 899) and (ModeInfo^.MaxColor = 16777216); + + InitGraph(ModeInfo^.DriverNumber, ModeInfo^.ModeNumber, ''); + + // Draw the fractal tree + DrawTree(ModeInfo^.MaxX div 2, ModeInfo^.MaxY, -90, TreeDepth); + + // Wait for user input before closing + ReadKey; + CloseGraph; +end. diff --git a/Task/Fractran/EasyLang/fractran.easy b/Task/Fractran/EasyLang/fractran.easy new file mode 100644 index 0000000000..5ee0b75bf6 --- /dev/null +++ b/Task/Fractran/EasyLang/fractran.easy @@ -0,0 +1,38 @@ +proc fractran prog$ val limit . r[] . + for s$ in strsplit prog$ " " : n[][] &= number strsplit s$ "/" + for n to limit + r[] &= val + for i to len n[][] + if val mod n[i][2] = 0 : break 1 + . + if i > len n[][] : break 1 + val = val / n[i][2] * n[i][1] + . +. +p$ = "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" +fractran p$ 2 15 r[] +print r[] +# +proc sort . d[] . + for i = 1 to len d[] - 1 + for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] + . + . +. +fractran p$ 2 1000 r[] +sort r[] +i = 1 +prim = 2 +po = 4 +repeat + repeat + if i > len r[] : break 2 + until i > len r[] or r[i] >= po + i += 1 + . + until i > len r[] + if r[i] = po : write prim & " " + prim += 1 + po *= 2 +. diff --git a/Task/Fractran/Julia/fractran.jl b/Task/Fractran/Julia/fractran.jl index a590a05890..7bd1303fe5 100644 --- a/Task/Fractran/Julia/fractran.jl +++ b/Task/Fractran/Julia/fractran.jl @@ -1,41 +1,29 @@ -# FRACTRAN interpreter implemented as an iterable struct +using Base.Iterators: filter, map, take +using Dates: now, seconds -using .Iterators: filter, map, take - -struct Fractran - rs::Vector{Rational{BigInt}} - i₀::BigInt - limit::Int +struct FRACTRAN + P::Vector{Rational{BigInt}} + i::BigInt end -Base.iterate(f::Fractran, i = f.i₀) = - for r in f.rs - if iszero(i % r.den) - i = i ÷ r.den * r.num - return i, i +# a new method for the builtin function 'iterate' to make the Fractran program run +Base.iterate(ft::FRACTRAN, n = ft.i) = + for f in ft.P + if iszero(n % f.den) + n = n ÷ f.den * f.num + return n, n end end -interpret(f::Fractran) = - take( - map(trailing_zeros, - filter(ispow2, f)) - f.limit) +"lazy generation of Fractran output sequence" +out(ft::FRACTRAN) = map(trailing_zeros, filter(ispow2, ft)) -Base.show(io::IO, f::Fractran) = - join(io, interpret(f), ' ') +"convenient Fractran scripting" +macro P_str(s) eval(Meta.parse(replace("[$s]", "/" => "//"))) end -macro code_str(s) - [eval(Meta.parse(replace(t, "/" => "//"))) for t ∈ split(s)] -end +primes = FRACTRAN(P"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 ", - join(take(primes, 25), ' ')) - -println("\nWatch the first 30 primes dropping out within seconds:") - -primes +println("2, ", join(take(primes, 20), ", "), "...") +t = now() +join(stdout, take(out(primes), 25), ", ") +println("...\n25 primes in $(seconds(now() - t)) seconds") diff --git a/Task/Fractran/REXX/fractran-1.rexx b/Task/Fractran/REXX/fractran-1.rexx deleted file mode 100644 index 8572c8bd0b..0000000000 --- a/Task/Fractran/REXX/fractran-1.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */ -numeric digits 2000 /*be able to handle larger numbers. */ -parse arg N terms fracs /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 2 /*Not specified? Then use the default.*/ -if terms=='' | terms=="," then terms= 100 /* " " " " " " */ -if fracs='' then fracs= "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' - /* [↑] The default for the fractions. */ -f= space(fracs, 0) /*remove all blanks from the FRACS list*/ - do #=1 while f\==''; parse var f n.# "/" d.# ',' f - end /*#*/ /* [↑] parse all the fractions in list*/ -#= # - 1 /*the number of fractions just found. */ -say # 'fractions:' fracs /*display number and actual fractions. */ -say 'N is starting at ' N /*display the starting number N. */ -say terms ' terms are being shown:' /*display a kind of header/title. */ - - do j=1 for terms /*perform the DO loop for each term. */ - do k=1 for # /* " " " " " " fraction*/ - if N // d.k \== 0 then iterate /*Not an integer? Then ignore it. */ - cN= commas(N); L= length(cN) /*maybe insert commas into N; get len.*/ - say right('term' commas(j), 44) "──► " right(cN, max(15, L)) /*show Nth term & N*/ - N= N % d.k * n.k /*calculate next term (use %≡integer ÷)*/ - leave /*go start calculating the next term. */ - end /*k*/ /* [↑] if an integer, we found a new N*/ - end /*j*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? diff --git a/Task/Fractran/REXX/fractran-2.rexx b/Task/Fractran/REXX/fractran-2.rexx deleted file mode 100644 index a201c8471b..0000000000 --- a/Task/Fractran/REXX/fractran-2.rexx +++ /dev/null @@ -1,39 +0,0 @@ -/*REXX program runs FRACTRAN for a given set of fractions and from a specified N. */ -numeric digits 999; d= digits(); w= length(d) /*be able to handle gihugeic numbers. */ -parse arg N terms fracs /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 2 /*Not specified? Then use the default.*/ -if terms=='' | terms=="," then terms= 100 /* " " " " " " */ -if fracs='' then fracs= "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' - /* [↑] The default for the fractions. */ -f= space(fracs, 0) /*remove all blanks from the FRACS list*/ - do #=1 while f\==''; parse var f n.# "/" d.# ',' f - end /*#*/ /* [↑] parse all the fractions in list*/ -#= # - 1 /*adjust the number of fractions found.*/ -tell= terms>0 /*flag: show number or a power of 2.*/ -!.= 0; _= 1 /*the default value for powers of 2. */ -if \tell then do p=1 until length(_)>d; _= _ + _; !._= 1 - if p==1 then @._= left('', w + 9) "2**"left(p, w) ' ' - else @._= '(prime' right(p, w)") 2**"left(p, w) ' ' - end /*p*/ /* [↑] build powers of 2 tables. */ -L= length(N) /*length in decimal digits of integer N*/ -say # 'fractions:' fracs /*display number and actual fractions. */ -say 'N is starting at ' N /*display the starting number N. */ -if tell then say terms ' terms are being shown:' /*display header.*/ - else say 'only powers of two are being shown:' /* " " */ -@a= '(max digits used:' /*a literal used in the SAY below. */ - - do j=1 for abs(terms) /*perform DO loop once for each term. */ - do k=1 for # /* " " " " " " fraction*/ - if N // d.k \== 0 then iterate /*Not an integer? Then ignore it. */ - cN= commas(N); cj=commas(j) /*maybe insert commas into N. */ - if tell then say right('term' cj, 44) "──► " cN /*display Nth term and N.*/ - else if !.N then say right('term' cj,15) "──►" @.N @a right(L,w)") " cN - N= N % d.k * n.k /*calculate next term (use %≡integer ÷)*/ - L= max(L, length(N) ) /*the maximum number of decimal digits.*/ - leave /*go start calculating the next term. */ - end /*k*/ /* [↑] if an integer, we found a new N*/ - end /*j*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? diff --git a/Task/Fractran/REXX/fractran-3.rexx b/Task/Fractran/REXX/fractran.rexx similarity index 95% rename from Task/Fractran/REXX/fractran-3.rexx rename to Task/Fractran/REXX/fractran.rexx index 1614a50f5c..43e2b0fd23 100644 --- a/Task/Fractran/REXX/fractran-3.rexx +++ b/Task/Fractran/REXX/fractran.rexx @@ -29,7 +29,7 @@ call Time('r') say 'First' t 'terms of the sequence:' do i = 2 to t do j = 1 to w - if \ Whole(n/d.j) then + if \ Integer(n/d.j) then iterate call CharOut ,Right(n,9) if i//10 = 0 then @@ -57,7 +57,7 @@ say 'Prime numbers:' n = 2; p = 0 do i = 2 to 1300000 do j = 1 to w - if \ Whole(n/d.j) then + if \ Integer(n/d.j) then iterate j if p.n then do p = p+1 diff --git a/Task/Function-definition/YAMLScript/function-definition.ys b/Task/Function-definition/YAMLScript/function-definition.ys index 4024b595ec..7bab26ba31 100644 --- a/Task/Function-definition/YAMLScript/function-definition.ys +++ b/Task/Function-definition/YAMLScript/function-definition.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 # Main function definition with variable arguments: defn main(*args): diff --git a/Task/Function-definition/Zig/function-definition.zig b/Task/Function-definition/Zig/function-definition.zig index f67148e5cd..38dab3141a 100644 --- a/Task/Function-definition/Zig/function-definition.zig +++ b/Task/Function-definition/Zig/function-definition.zig @@ -1,4 +1,4 @@ -fun multiply(x: i64, y: i64) i64 { +fn multiply(x: i64, y: i64) i64 { return x * y; } diff --git a/Task/GUI-component-interaction/Forth/gui-component-interaction.fth b/Task/GUI-component-interaction/Forth/gui-component-interaction.fth new file mode 100644 index 0000000000..b25d56f2fa --- /dev/null +++ b/Task/GUI-component-interaction/Forth/gui-component-interaction.fth @@ -0,0 +1,91 @@ +\ The following is Forth code using iMops v2.23 +\ Tested on all MacOS from High Sierra to Sonoma +\ using Intel based systems. +\ This code can be used to create a stand-alone application + +: isdigit? ( char -- flag ) \ true if 0 thru 9, false otherwise + 48 58 within? ; + +: >uinteger { addr len \ dec accum -- n t | f } + len NIF exit THEN + 1 -> dec 0 -> accum + len 1+ 1 ?DO + addr len + i - c@ dup isdigit? + IF ( it's a digit 0 thru 9 ) + 48 - dec * accum + -> accum + dec 10 * -> dec + ELSE 2drop false unloop exit + THEN drop + LOOP accum true ; + +SYSCALL rand { -- int } + +:class TextView' super{ TextView } +:m put: ( addr len -- ) + 0 #ofChars: self SetSelect: self + insert: self ;m +;class + +Window+ w + View wview + Button incButton + 100 30 90 20 ( x0 y0 wid hi ) setFrame: incButton + Button randButton + 190 30 70 20 ( x0 y0 wid hi ) setFrame: randButton + TextView' val + 180 100 100 15 setFrame: val + FixedText valLabel + 110 98 80 18 setframe: valLabel + +Window+ okW + view okView + Button yesButton + 100 20 80 18 setframe: yesButton + Button cancelButton + 10 20 80 18 setframe: cancelButton + FixedText okText + 5 40 200 18 setframe: okText + +:noname + getText: val >uinteger + IF 1+ deciNumstr + ELSE " 0" + THEN put: val ; setAction: incButton + +:noname + show: okW ; setAction: randButton + +:noname + rand deciNumstr put: val + show: w ; setAction: yesButton + +:noname + getText: val >uinteger + NIF " 0" put: val + THEN show: w ; setAction: cancelButton + +: main + incButton addview: wview + randButton addview: wview + val addview: wview + valLabel addview: wview + " value:" SetText: valLabel + 300 30 430 230 put: frameRect + frameRect " GUI component interaction" docWindow + wview new: w show: w + " 0" put: val \ must be done after window is new: + " increment" setTitle: incButton + " random" setTitle: randButton + + yesButton addview: okView + cancelButton addview: okView + okText addview: okView + " Set value to random number?" SetText: okText + 310 40 200 60 put: frameRect + frameRect " " noCloseStyle + okView new: okW + " yes" setTitle: yesButton + " cancel" setTitle: cancelButton + ; + +main \ if creating installed app, startup word must be commented out diff --git a/Task/GUI-component-interaction/XPL0/gui-component-interaction.xpl0 b/Task/GUI-component-interaction/XPL0/gui-component-interaction.xpl0 new file mode 100644 index 0000000000..86292ba117 --- /dev/null +++ b/Task/GUI-component-interaction/XPL0/gui-component-interaction.xpl0 @@ -0,0 +1,147 @@ +\0123456789012345678901234567 template for display layout +\ Component interaction. X . main window +\ Value: 123456789_ . +\ [Increment] [Random] . +\ Confirm............... X . dialog pop-up +\ Set to a random value? +\ [ Yes ] [ No ] + +include xpllib; \for Ctrl key names, AtoI, ItoA and StrLen +def X0=22, Y0=10; \upper-left corner of main window's position +def X1=X0+21, Y1=Y0+5; \position of dialog pop-up (character cells) +int Mouse, Button, X, Y, Ch, I; \all variables are global for simplicity +def StrMax = 10; \max chars in String including underline +char String(StrMax); \Value string array +int StrInx; \index for character to be added to String + +proc ShowString; \Show Value String +[Attrib($F0); \set black on bright white +Cursor(13+X0, 2+Y0); \move to Value field position +for I:= 0 to StrInx-1 do ChOut(6, String(I)); +ChOut(6, ^_); \show cursor underline at end of String +for I:= StrInx+1 to StrMax-1 do ChOut(6, ^ ); \blank rest of line +]; + +func GetButton; \Return soft button number at mouse pointer +[Mouse:= GetMouse; +X:= Mouse(0)/8 - X0; \convert pixels to 8x16-pixel character cells +Y:= Mouse(1)/16 - Y0; +if X>=24 & X<=26 & Y=0 then return 0; \exit [X] +if X>= 3 & X<=13 & Y=4 then return 1; \Increment +if X>=17 & X<=24 & Y=4 then return 2; \Random +X:= Mouse(0)/8 - X1; \convert pixels to character cells for dialog +Y:= Mouse(1)/16 - Y1; +if X>=24 & X<=26 & Y=0 then return 3; \exit [X] +if X>= 3 & X<=11 & Y=4 then return 4; \Yes +if X>=16 & X<=24 & Y=4 then return 5; \No +return -1; \mouse is not on any soft button +]; + +proc DoDialog; \Do pop-up dialog for further information +[Attrib($70); \set black-on-gray color attribute +SetWind(0+X1, 0+Y1, 27+X1, 5+Y1, 0, \fill\true); \draw gray rectangle +Cursor(25+X1, 0+Y1); ChOut(6, ^X); \draw exit button +Cursor( 3+X1, 2+Y1); Text(6, "Set to a random value?"); +Attrib($80); \set black on dark gray for buttons +Cursor( 3+X1, 4+Y1); Text(6, " Yes "); +Cursor(16+X1, 4+Y1); Text(6, " No "); +Attrib($9F); \set bright white on light blue, for title bar +Cursor(0+X1, 0+Y1); Text(6, " Confirm "); +ShowMouse(true); \turn on mouse pointer +loop [MoveMouse; \make pointer track mouse movements + Mouse:= GetMouse; + if Mouse(2) then \a left or right mouse button is down + [Button:= GetButton; \get soft button at mouse pointer + while Mouse(2) do \wait for mouse button to be released + [MoveMouse; + Mouse:= GetMouse; + ]; + if Button = GetButton then \if down Button = release button + [if Button = 3 then InsertKey(Esc); \insert into keyboard buffer + if Button = 4 then InsertKey(^y); + if Button = 5 then InsertKey(^n); + ]; + ]; + if KeyHit then \key is hit or was inserted in KB buffer + [Ch:= ChIn(1); \get character from non-echoed keyboard + if Ch=^y or Ch=^Y then \set Value to random number + [I:= Ran(1_000_000_000); + ItoA(I, String); + StrInx:= StrLen(String); + quit; + ] + else if Ch=^n or Ch=^N or Ch=Esc then quit; + ]; + ]; \loop +]; + +proc DoMain; \Do main window interaction +[ShowMouse(true); \turn on mouse pointer +loop [MoveMouse; \make pointer track mouse movements + Mouse:= GetMouse; + if Mouse(2) then \a left or right mouse button is down + [Button:= GetButton; \get soft button at mouse pointer + while Mouse(2) do \wait for mouse button to be released + [MoveMouse; + Mouse:= GetMouse; + ]; + if Button = GetButton then \if down Button = release button + [if Button = 0 then InsertKey(Esc); \insert into keyboard buffer + if Button = 1 then InsertKey(^i); + if Button = 2 then InsertKey(^r); + ]; + ]; + if KeyHit then \key is hit or was inserted in KB buffer + [ShowMouse(false); \don't draw on top of mouse pointer + Ch:= ChIn(1); \get character from non-echoed keyboard + if Ch>=$30 & Ch<=$39 then \only allow numeric digits for Value + [if StrInx < StrMax-1 then \limit number of digits added + [String(StrInx):= Ch; + StrInx:= StrInx+1; + \handle leading zeros - convert number to its canonical form + String(StrInx):= 0; \append string terminator for AtoI + I:= AtoI(String); \convert numeric String to an integer + ItoA(I, String); \convert binary integer back to String + StrInx:= StrLen(String); \String could have gotten shorter + ]; + ] + else if Ch = BS then \(backspace) delete back a character + [if StrInx > 0 then StrInx:= StrInx-1] + else if Ch=^i or Ch=^I then \increment Value + [String(StrInx):= 0; \append terminator for AtoI + I:= AtoI(String); + ItoA(I+1, String); + StrInx:= StrLen(String); \String could have gotten longer + if StrInx > StrMax-1 then \roll all 9's to zero + [String(0):= ^0; StrInx:= 1]; + ] + else if Ch=^r or Ch=^R then \random Value - go do dialog pop-up + quit + else if Ch = Esc then + [SetVid(3); exit]; \restore normal text mode before exiting + ShowString; + ShowMouse(true); + ]; + ]; \loop +]; + +[SetVid($12); \set 640x480 graphics mode display +TrapC(true); \prevent Ctrl+C from aborting the program +String(0):= ^0; \initialize Value String to zero +StrInx:= 1; +loop [Attrib($70); \set black-on-gray color attribute + SetWind(0+X0, 0+Y0, 27+X0, 5+Y0, 0, \fill\true); \draw gray rectangle + Cursor(25+X0, 0+Y0); ChOut(6, ^X); \draw exit button + Cursor( 4+X0, 2+Y0); Text(6, "Value:"); + Attrib($80); \set black on dark gray for buttons + Cursor( 3+X0, 4+Y0); Text(6, " Increment "); + Cursor(17+X0, 4+Y0); Text(6, " Random "); + Attrib($9F); \set bright white on light blue for title bar + Cursor(0+X0, 0+Y0); Text(6, " Component interaction "); + ShowString; + DoMain; + DoDialog; + ShowMouse(false); \don't overwrite mouse pointer (with Clear) + Clear; \remove pop-up dialog + ]; \loop back to redraw main window +] diff --git a/Task/Gamma-function/EMal/gamma-function.emal b/Task/Gamma-function/EMal/gamma-function.emal new file mode 100644 index 0000000000..b97e5e94c7 --- /dev/null +++ b/Task/Gamma-function/EMal/gamma-function.emal @@ -0,0 +1,19 @@ +fun stirling ← 9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return g/1 diff --git a/Task/Gamma-function/REXX/gamma-function-3.rexx b/Task/Gamma-function/REXX/gamma-function-3.rexx deleted file mode 100644 index 37ad3facc1..0000000000 --- a/Task/Gamma-function/REXX/gamma-function-3.rexx +++ /dev/null @@ -1,175 +0,0 @@ -include Settings - -say version; say 'Gamma'; say -arg n; if n = '' then n = 100; numeric digits n -say '(Half)integers formulas' -w = '-99.5 -10.5 -5.5 -2.5 -1.5 -0.5 0.5 1 1.5 2 2.5 5 5.5 10 10.5 99 99.5' -numeric digits n -do i = 1 to Words(w) - x = Word(w,i); call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) - say 'Formulas' Format(x,4,1) r '('e 'seconds)' -end -say -say 'Lanczos (max 60 decimals) vs Spouge (no limit) vs Stirling (no limit) approximation' -w = '-12.8 -6.4 -3.2 -1.6 -0.8 -0.4 -0.2 -0.1 0.1 0.2 0.4 0.8 1.6 3.2 6.4 12.8' -do i = 1 to Words(w) - x = Word(w,i) - numeric digits Min(60,n) - call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) - say 'Lanczos ' Format(x,4,1) r '('e 'seconds)' - numeric digits n - call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) - say 'Spouge ' Format(x,4,1) r '('e 'seconds)' - if x > 0 then do - call Time('r'); r = Stirling(x); e = Format(Time('e'),,3) - say 'Stirling' Format(x,4,1) r '('e 'seconds)' - end -end -say -say 'Same for a bigger number' -w = '-99.9 99.9' -do i = 1 to Words(w) - x = Word(w,i) - numeric digits Min(60,n) - call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) - say 'Lanczos ' Format(x,4,1) r '('e 'seconds)' - numeric digits n - call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) - say 'Spouge ' Format(x,4,1) r '('e 'seconds)' - if x > 0 then do - call Time('r'); r = Stirling(x); e = Format(Time('e'),,3) - say 'Stirling' Format(x,4,1) r '('e 'seconds)' - end -end -exit - -Gamma: -/* Gamma */ -procedure expose glob. fact. -arg x -/* Formulas for negative and positive (half)integers */ -if x < 0 then do - if Half(x) then do - numeric digits Digits()+2 - i = Abs(Floor(x)); y = (-1)**i*2**(2*i)*Fact(i)*Sqrt(Pi())/Fact(2*i) - numeric digits Digits()-2 - return y+0 - end -end -if x > 0 then do - if Whole(x) then - return Fact(x-1) - if Half(x) then do - numeric digits Digits()+2 - i = Floor(x); y = Fact(2*i)*Sqrt(Pi())/(2**(2*i)*Fact(i)) - numeric digits Digits()-2 - return y+0 - end -end -p = Digits() -if p < 61 then do -/* Lanczos with predefined coefficients */ -/* Map negative x to positive x */ - if x < 0 then - return Pi()/(Gamma(1-x)*Sin(Pi()*x)) -/* Argument reduction to interval (0.5,1.5) */ - numeric digits p+2 - c = Trunc(x); x = x-c - if x < 0.5 then do - x = x+1; c = c-1 - end -/* Series coefficients 1/Gamma(x) in 80 digits Fransen & Wrigge */ - c.1 = 1.00000000000000000000000000000000000000000000000000000000000000000000000000000000 - c.2 = 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 - c.3 = -0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 - c.4 = -0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 - c.5 = 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 - c.6 = -0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 - c.7 = -0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 - c.8 = 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 - c.9 = -0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 - c.10 = -0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 - c.11 = 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 - c.12 = -0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 - c.13 = -0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 - c.14 = 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 - c.15 = -0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 - c.16 = 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 - c.17 = 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 - c.18 = -0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 - c.19 = 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 - c.20 = 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 - c.21 = -0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 - c.22 = 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 - c.23 = -0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 - c.24 = -0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 - c.25 = 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 - c.26 = -0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 - c.27 = 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 - c.28 = 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 - c.29 = -0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 - c.30 = 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 - c.31 = 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 - c.32 = -0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 - c.33 = 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 - c.34 = -0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 - c.35 = -0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 - c.36 = 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 - c.37 = -0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 - c.38 = 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 - c.39 = 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 - c.40 = -0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 - c.41 = 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 - c.42 = -0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 - c.43 = 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 - c.44 = 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 - c.45 = -0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 - c.46 = 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 - c.47 = -0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 - c.48 = -0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 - c.49 = 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 - c.50 = -0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 - c.51 = 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 - c.52 = 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 -/* Series expansion */ - x = x-1; s = 0 - do k = 52 by -1 to 1 - s = s*x+c.k - end - y = 1/s -/* Undo reduction */ - if c = -1 then - y = y/x - else do - do i = 1 to c - y = (x+i)*y - end - end -end -else do - x = x-1 -/* Spouge */ -/* Estimate digits and iterations */ - q = Floor(p*1.5); a = Floor(p*1.3) - numeric digits q -/* Series */ - s = 0 - do k = 1 to a-1 - s = s+((-1)**(k-1)*Power(a-k,k-0.5)*Exp(a-k))/(Fact(k-1)*(x+k)) - end - s = s+Sqrt(2*Pi()); y = Power(x+a,x+0.5)*Exp(-a-x)*s -end -/* Normalize */ -numeric digits p -return y+0 - -Stirling: -/* Sterling */ -procedure expose glob. fact. -arg x -return Sqrt(2*Pi()/x) * Power(x/e(),x) - -include Constants -include Functions -include Numbers -include Abend diff --git a/Task/Gamma-function/REXX/gamma-function.rexx b/Task/Gamma-function/REXX/gamma-function.rexx new file mode 100644 index 0000000000..9b91fe493d --- /dev/null +++ b/Task/Gamma-function/REXX/gamma-function.rexx @@ -0,0 +1,55 @@ +include Settings + +say version; say 'Gamma'; say +arg n; if n = '' then n = 100; numeric digits n +say '(Half)integers formulas' +w = '-99.5 -10.5 -5.5 -2.5 -1.5 -0.5 0.5 1 1.5 2 2.5 5 5.5 10 10.5 99 99.5' +numeric digits n +do i = 1 to Words(w) + x = Word(w,i); call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + say 'Formulas' Format(x,4,1) r '('e 'seconds)' +end +say +say 'Lanczos (max 60 decimals) vs Spouge (no limit) vs Stirling (no limit) approximation' +w = '-12.8 -6.4 -3.2 -1.6 -0.8 -0.4 -0.2 -0.1 0.1 0.2 0.4 0.8 1.6 3.2 6.4 12.8' +do i = 1 to Words(w) + x = Word(w,i) + numeric digits Min(60,n) + call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + say 'Lanczos ' Format(x,4,1) r '('e 'seconds)' + numeric digits n + call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + say 'Spouge ' Format(x,4,1) r '('e 'seconds)' + if x > 0 then do + call Time('r'); r = Stirling(x); e = Format(Time('e'),,3) + say 'Stirling' Format(x,4,1) r '('e 'seconds)' + end +end +say +say 'Same for a bigger number' +w = '-99.9 99.9' +do i = 1 to Words(w) + x = Word(w,i) + numeric digits Min(60,n) + call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + say 'Lanczos ' Format(x,4,1) r '('e 'seconds)' + numeric digits n + call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + say 'Spouge ' Format(x,4,1) r '('e 'seconds)' + if x > 0 then do + call Time('r'); r = Stirling(x); e = Format(Time('e'),,3) + say 'Stirling' Format(x,4,1) r '('e 'seconds)' + end +end +exit + +Stirling: +/* Sterling */ +procedure expose glob. fact. +arg x +return Sqrt(2*Pi()/x) * Power(x/e(),x) + +include Constants +include Functions +include Numbers +include Abend diff --git a/Task/Gaussian-elimination/PascalABC.NET/gaussian-elimination.pas b/Task/Gaussian-elimination/PascalABC.NET/gaussian-elimination.pas new file mode 100644 index 0000000000..e6f257930e --- /dev/null +++ b/Task/Gaussian-elimination/PascalABC.NET/gaussian-elimination.pas @@ -0,0 +1,16 @@ +uses NumLibABC; + +begin + var A := new real[6, 6] ((1.00, 0.00, 0.00, 0.00, 0.00, 0.00), + (1.00, 0.63, 0.39, 0.25, 0.16, 0.10), + (1.00, 1.26, 1.58, 1.98, 2.49, 3.13), + (1.00, 1.88, 3.55, 6.70, 12.62, 23.80), + (1.00, 2.51, 6.32, 15.88, 39.90, 100.28), + (1.00, 3.14, 9.87, 31.01, 97.41, 306.02)); + + var b := new real[6] (-0.01, 0.61, 0.91, 0.99, 0.60, 0.02); + + var oL := new Decomp(A); + oL.Solve(b); + b.Println; +end. diff --git a/Task/Generate-Chess960-starting-position/Chipmunk-Basic/generate-chess960-starting-position.basic b/Task/Generate-Chess960-starting-position/Chipmunk-Basic/generate-chess960-starting-position.basic new file mode 100644 index 0000000000..35d08c975c --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Chipmunk-Basic/generate-chess960-starting-position.basic @@ -0,0 +1,15 @@ +100 randomize timer +110 for i = 1 to 10 +120 inicio$ = "RKR" +130 pieza$ = "QNN" +140 for n = 1 to len(pieza$) +150 posic = int(rnd(len(inicio$)+1))+1 +160 inicio$ = left$(inicio$,posic-1)+mid$(pieza$,n,1)+right$(inicio$,len(inicio$)-posic+1) +170 next n +180 posic = int(rnd(len(inicio$)+1))+1 +190 inicio$ = left$(inicio$,posic-1)+"B"+right$(inicio$,len(inicio$)-posic+1) +200 posic = posic+1+2*int(int(rnd(len(inicio$)-posic))/2) +210 inicio$ = left$(inicio$,posic-1)+"B"+right$(inicio$,len(inicio$)-posic+1) +220 print inicio$ +230 next i +240 end diff --git a/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy b/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy index 2c6c527052..80dca8ffad 100644 --- a/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy +++ b/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy @@ -18,4 +18,4 @@ repeat randins "Q" 1 8 b1 randins "N" 1 8 b1 randins "N" 1 8 b1 -print strjoin t$[] +print strjoin t$[] "" diff --git a/Task/Generate-Chess960-starting-position/FreeBASIC/generate-chess960-starting-position.basic b/Task/Generate-Chess960-starting-position/FreeBASIC/generate-chess960-starting-position.basic index 4121b4fe91..ec27d49e50 100644 --- a/Task/Generate-Chess960-starting-position/FreeBASIC/generate-chess960-starting-position.basic +++ b/Task/Generate-Chess960-starting-position/FreeBASIC/generate-chess960-starting-position.basic @@ -9,9 +9,12 @@ For i As Byte = 1 To 10 Mid(pieza, n, 1) +_ Right(inicio, Len(inicio) - posic + 1) Next n + posic = Int(Rnd*(Len(inicio) + 1)) + 1 inicio = Left(inicio, posic-1) + "B" + Right(inicio, Len(inicio) - posic + 1) - posic = posic + 1 + 2 * Int(Int(Rnd*(Len(inicio) - posic)) / 2) + + posic += 1 + 2 * (Int(Rnd*(Len(inicio) - posic)) \ 2) inicio = Left(inicio, posic-1) + "B" + Right(inicio, Len(inicio) - posic + 1) + Print inicio Next i diff --git a/Task/Generate-Chess960-starting-position/Gambas/generate-chess960-starting-position.gambas b/Task/Generate-Chess960-starting-position/Gambas/generate-chess960-starting-position.gambas new file mode 100644 index 0000000000..bd592b61f9 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Gambas/generate-chess960-starting-position.gambas @@ -0,0 +1,21 @@ +Public Sub Main() + + Randomize + + For i As Integer = 1 To 10 + Dim inicio As String = "RKR" + Dim pieza As String = "QNN" + Dim posic As Integer + + For n As Integer = 1 To Len(pieza) + posic = Int(Rnd * (Len(inicio) + 1)) + 1 + inicio = Left(inicio, posic - 1) & Mid(pieza, n, 1) & Right(inicio, Len(inicio) - posic + 1) + Next + posic = Int(Rnd * (Len(inicio) + 1)) + 1 + inicio = Left(inicio, posic - 1) & "B" & Right(inicio, Len(inicio) - posic + 1) + posic += 1 + 2 * Int(Int(Rnd * (Len(inicio) - posic)) / 2) + inicio = Left(inicio, posic - 1) & "B" & Right(inicio, Len(inicio) - posic + 1) + Print inicio + Next + +End diff --git a/Task/Generate-Chess960-starting-position/PascalABC.NET/generate-chess960-starting-position.pas b/Task/Generate-Chess960-starting-position/PascalABC.NET/generate-chess960-starting-position.pas new file mode 100644 index 0000000000..b45cbcaded --- /dev/null +++ b/Task/Generate-Chess960-starting-position/PascalABC.NET/generate-chess960-starting-position.pas @@ -0,0 +1,15 @@ +## +function random960: string; +begin + var start := 'RKR'; + + foreach var piece in 'QNN' do + Insert(piece, start, Random(start.length + 1) + 1); + + var bishpos := Random(start.length + 1) + 1; + Insert('B', start, bishpos); + Insert('B', start, Range(bishpos + 1, start.Length + 1, 2).ToArray.RandomElement); + result := start; +end; + +random960.Println; diff --git a/Task/Generate-Chess960-starting-position/PureBasic/generate-chess960-starting-position.basic b/Task/Generate-Chess960-starting-position/PureBasic/generate-chess960-starting-position.basic new file mode 100644 index 0000000000..3a41d96d22 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/PureBasic/generate-chess960-starting-position.basic @@ -0,0 +1,21 @@ +OpenConsole() +RandomSeed(Date()) +For i = 1 To 10 + inicio.s = "RKR" + pieza.s = "QNN" + + For n = 1 To Len(pieza) + posic = Random(Len(inicio)) + 1 + inicio = Left(inicio, posic - 1) + Mid(pieza, n, 1) + Right(inicio, Len(inicio) - posic + 1) + Next n + + posic = Random(Len(inicio)) + 1 + inicio = Left(inicio, posic - 1) + "B" + Right(inicio, Len(inicio) - posic + 1) + posic + 1 + 2 * Int(Random(Len(inicio) - posic) / 2) + inicio = Left(inicio, posic - 1) + "B" + Right(inicio, Len(inicio) - posic + 1) + + PrintN(inicio) +Next i + +PrintN(#CRLF$ + "Press ENTER to exit"): Input() +CloseConsole() diff --git a/Task/Generate-Chess960-starting-position/QBasic/generate-chess960-starting-position.basic b/Task/Generate-Chess960-starting-position/QBasic/generate-chess960-starting-position.basic index 004f9491ad..aa667deeb1 100644 --- a/Task/Generate-Chess960-starting-position/QBasic/generate-chess960-starting-position.basic +++ b/Task/Generate-Chess960-starting-position/QBasic/generate-chess960-starting-position.basic @@ -1,9 +1,8 @@ -RANDOMIZE TIMER +RANDOMIZE TIMER ' DELETE for Run BASIC, Just Basic & Liberty BASIC FOR i = 1 TO 10 inicio$ = "RKR" pieza$ = "QNN" - 'Dim posic FOR n = 1 TO LEN(pieza$) posic = INT(RND * (LEN(inicio$) + 1)) + 1 diff --git a/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-4.ada b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-4.ada new file mode 100644 index 0000000000..49649e5209 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-4.ada @@ -0,0 +1,34 @@ +-- Here is the fleshed-out code using the snippets from above +-- Note that I could have enhanced the output by not displaying the last comma +-- December 2024, R. B. E. + +with Ada.Text_IO; + +procedure Generate_Lower_Case_ASCII_Alphabet is + +-- We start with a strong type definition: A character range that can only hold lower-case letters: + + type Lower_Case is new Character range 'a' .. 'z'; + +-- Now we define an array type and initialize the Array A of that type with the 26 letters: + + type Arr_Type is array (Integer range <>) of Lower_Case; + A : Arr_Type (1 .. 26) := "abcdefghijklmnopqrstuvwxyz"; + +-- Strong typing would catch two errors: (1) any upper-case letters or +-- other symbols in the string assigned to A, and (2) too many or too +-- few letters assigned to A. However, a letter might still appear +-- twice (or more) in A, at the cost of one or more other +-- letters. Array B is safe even against such errors: + + B : Arr_Type (1 .. 26); +begin + B(B'First) := 'a'; + for I in B'First .. B'Last-1 loop + B(I+1) := Lower_Case'Succ(B(I)); + end loop; -- now all the B(I) are different + for I in B'First .. B'Last loop + Ada.Text_IO.Put (B(I)'Image & ", "); + end loop; + Ada.Text_IO.New_Line; +end Generate_Lower_Case_ASCII_Alphabet; diff --git a/Task/Generate-lower-case-ASCII-alphabet/M2000-Interpreter/generate-lower-case-ascii-alphabet.m2000 b/Task/Generate-lower-case-ASCII-alphabet/M2000-Interpreter/generate-lower-case-ascii-alphabet.m2000 index fe1a6ae9a8..d1934f96d8 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/M2000-Interpreter/generate-lower-case-ascii-alphabet.m2000 +++ b/Task/Generate-lower-case-ASCII-alphabet/M2000-Interpreter/generate-lower-case-ascii-alphabet.m2000 @@ -1,9 +1,19 @@ \\ old style Basic, including a Binary.Or() function Module OldStyle { 10 LET A$="" - 20 FOR I=ASC("A") TO ASC("Z") - 30 LET A$=A$+CHR$(BINARY.OR(I, 32)) - 40 NEXT I - 50 PRINT A$ + 20 DEF FNUP$(I)=""""+CHR$(BINARY.OR(I, 32))+"""" + 30 FOR I=ASC("A") TO ASC("Y") + 40 LET A$= A$ + FNUP$(I, 32)+", " + 50 NEXT I + 60 LET A$ = A$+ FNUP$(I, 32) + 70 PRINT A$ } CALL OldStyle + +Module new_style { + a=("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z") + map1= lambda ->{push binary.or(asc(letter$), 32)} + map2= lambda ->{push chr$(number)} + Print """"+a#map(map1, map2)#str$({", "})+"""" +} +new_style diff --git a/Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet.x86-64 b/Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet-1.x86-64 similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet.x86-64 rename to Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet-1.x86-64 diff --git a/Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet-2.x86-64 b/Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet-2.x86-64 new file mode 100644 index 0000000000..fd17eea75d --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/X86-64-Assembly/generate-lower-case-ascii-alphabet-2.x86-64 @@ -0,0 +1,26 @@ +format ELF64 executable 3 +entry begin + +segment executable readable +begin: + mov rcx, 26 + mov rdi, alphabet + mov rax, 'a' + .loop0: + stosb + inc rax + loop .loop0 + mov byte[alphabet + 26], 0x0a + .print0: + mov rax, 1 + mov rdi, 1 + mov rsi, alphabet + mov rdx, 27 + syscall + .end: + mov rax, 60 + xor rdi, rdi + syscall + +segment readable writeable +alphabet: rb 27 diff --git a/Task/Get-system-command-output/Wren/get-system-command-output-1.wren b/Task/Get-system-command-output/Wren/get-system-command-output-1.wren deleted file mode 100644 index 4695b3d104..0000000000 --- a/Task/Get-system-command-output/Wren/get-system-command-output-1.wren +++ /dev/null @@ -1,6 +0,0 @@ -/* Get_system_command_output.wren */ -class Command { - foreign static output(name, param) // the code for this is provided by Go -} - -System.print(Command.output("ls", "-ls")) diff --git a/Task/Get-system-command-output/Wren/get-system-command-output-2.wren b/Task/Get-system-command-output/Wren/get-system-command-output-2.wren deleted file mode 100644 index 0bc8713e26..0000000000 --- a/Task/Get-system-command-output/Wren/get-system-command-output-2.wren +++ /dev/null @@ -1,39 +0,0 @@ -/* Get_system_command_output.go */ -package main - -import ( - wren "github.com/crazyinfin8/WrenGo" - "log" - "os" - "os/exec" -) - -type any = interface{} - -func getCommandOutput(vm *wren.VM, parameters []any) (any, error) { - name := parameters[1].(string) - param := parameters[2].(string) - var cmd *exec.Cmd - if param != "" { - cmd = exec.Command(name, param) - } else { - cmd = exec.Command(name) - } - cmd.Stderr = os.Stderr - bytes, err := cmd.Output() - if err != nil { - log.Fatal(err) - } - return string(bytes), nil -} - -func main() { - vm := wren.NewVM() - fileName := "Get_system_command_output.wren" - methodMap := wren.MethodMap{"static output(_,_)": getCommandOutput} - classMap := wren.ClassMap{"Command": wren.NewClass(nil, nil, methodMap)} - module := wren.NewModule(classMap) - vm.SetModule(fileName, module) - vm.InterpretFile(fileName) - vm.Free() -} diff --git a/Task/Get-system-command-output/Wren/get-system-command-output.wren b/Task/Get-system-command-output/Wren/get-system-command-output.wren new file mode 100644 index 0000000000..411638195b --- /dev/null +++ b/Task/Get-system-command-output/Wren/get-system-command-output.wren @@ -0,0 +1,3 @@ +import "os" for Process + +System.print(Process.read("ls", ["-ls"])) diff --git a/Task/Goldbachs-comet/PascalABC.NET/goldbachs-comet.pas b/Task/Goldbachs-comet/PascalABC.NET/goldbachs-comet.pas new file mode 100644 index 0000000000..234717b9bc --- /dev/null +++ b/Task/Goldbachs-comet/PascalABC.NET/goldbachs-comet.pas @@ -0,0 +1,36 @@ +uses GraphWPF; + +const colpick = (Colors.Red, Colors.Green, Colors.Blue); + +function IsPrime(x: longword): boolean; +begin + var i := 2; + while (i * i <= x) and (x mod i <> 0) do + i += 1; + Result := i * i > x; +end; + +function g(n: integer): integer; +begin + assert((n > 2) and (n mod 2 = 0), '“n” must be even and greater than 2.'); + for var i := 2 to (n div 2) do + if isPrime(i) and isPrime(n - i) then + result += 1; +end; + +begin + println('First 100 G numbers:'); + foreach var n in (2..101) index i do + begin + write(g( 2 * n):3); + if (i + 1) mod 10 = 0 then writeln; + end; + println; + println('G(1_000_000) =', g(1_000_000)); + + setMathematicCoords(0, 4000, 0, false); + foreach var x in range(4, 4002, 2) do + begin + fillcircle(x, g(x)*15, 10, colpick[(x div 2) mod 3]); + end; +end. diff --git a/Task/Golden-ratio-Convergence/Quackery/golden-ratio-convergence.quackery b/Task/Golden-ratio-Convergence/Quackery/golden-ratio-convergence.quackery new file mode 100644 index 0000000000..1f4c606229 --- /dev/null +++ b/Task/Golden-ratio-Convergence/Quackery/golden-ratio-convergence.quackery @@ -0,0 +1,23 @@ + [ $ "bigrat.qky" loadfile ] now! + + 0 temp put + 1 n->v + [ 1 temp tally + 2dup 1/v 1 n->v v+ + 2over 2over + 5 approx= not while ( i.e. to five digits after the decimal point ) + 2swap 2drop again ] + say " After " + temp take echo + say " iterations: " + 63 point$ echo$ cr + say "As a vulgar fraction: " + 2dup vulgar$ echo$ cr + 2dup + [ 2dup 1/v 1 n->v v+ ( Continue to 63 digits after the decimal point ) + 2over 2over ( to find the approximate error to same accuracy ) + 63 approx= not while ( as Wolfram Alpha. ) + 2swap 2drop again ] + 2drop 2swap v- + say " Approximate error: " + 63 point$ echo$ cr diff --git a/Task/Gotchas/C/gotchas-1.c b/Task/Gotchas/C/gotchas-1.c index f46446548f..5d12d22ba7 100644 --- a/Task/Gotchas/C/gotchas-1.c +++ b/Task/Gotchas/C/gotchas-1.c @@ -1,3 +1,3 @@ -if(a=b){} //assigns to "a" the value of "b". Then, if "a" is nonzero, the code in the curly braces is run. - -if(a==b){} //runs the code in the curly braces if and only if the value of "a" equals the value of "b". +if (a=b) { + ...; /* this is run if b is non-zero */ +} diff --git a/Task/Gotchas/C/gotchas-10.c b/Task/Gotchas/C/gotchas-10.c index d0512d7776..f1d321c444 100644 --- a/Task/Gotchas/C/gotchas-10.c +++ b/Task/Gotchas/C/gotchas-10.c @@ -1,7 +1,2 @@ -int main() -{ -int x = 3; -int y = 5; -int z = 7; -printf("%d %d %d %x %x",x,y,z); //on an Intel cpu the first %x reveals %%ebp and the second reveals the return address.) -} +myArray[40]; +int x = gotcha(&myArray[0]); diff --git a/Task/Gotchas/C/gotchas-11.c b/Task/Gotchas/C/gotchas-11.c index 8bd998e6a1..f4cdf00887 100644 --- a/Task/Gotchas/C/gotchas-11.c +++ b/Task/Gotchas/C/gotchas-11.c @@ -1,3 +1,7 @@ -(let numbers [1 2 3 4] - maximum (max numbers)) ;should be (... max numbers) -(+ maximum 5) +int foo(char buf[],int length){} + +int main() +{ +char myArray[30]; +int j = foo(myArray,sizeof(myArray)); //passes 30 as the length parameter. +} diff --git a/Task/Gotchas/C/gotchas-12.c b/Task/Gotchas/C/gotchas-12.c index f43e241d84..08a2b7c6c0 100644 --- a/Task/Gotchas/C/gotchas-12.c +++ b/Task/Gotchas/C/gotchas-12.c @@ -1,2 +1,4 @@ -(mock + (fn a b ((unmocked +) a b 1))) -(+ 2 3) +int x = 3; +int y = 5; +printf("%d %d %x\n",x,y); /* this may crash or print undefined values after 3 5 */ +printf("testing %n\n"); /* this writes the int value 8 to an undefined location */ diff --git a/Task/Gotchas/C/gotchas-13.c b/Task/Gotchas/C/gotchas-13.c new file mode 100644 index 0000000000..30ecde47fc --- /dev/null +++ b/Task/Gotchas/C/gotchas-13.c @@ -0,0 +1,7 @@ +void +say_hello(const char *name) /* assume name is something the user entered */ +{ + printf("hello "); + printf(name); /* the name entered could be "%s" or "%n" or something */ + printf("\n"); +} diff --git a/Task/Gotchas/C/gotchas-2.c b/Task/Gotchas/C/gotchas-2.c index fd9a19497b..d5c6ab4190 100644 --- a/Task/Gotchas/C/gotchas-2.c +++ b/Task/Gotchas/C/gotchas-2.c @@ -1 +1,3 @@ -int foo[4] = {4,8,12,16}; +if (a==b) { + ...; /* this is run if a and b are equal */ +} diff --git a/Task/Gotchas/C/gotchas-3.c b/Task/Gotchas/C/gotchas-3.c index bf983982ce..035755e086 100644 --- a/Task/Gotchas/C/gotchas-3.c +++ b/Task/Gotchas/C/gotchas-3.c @@ -1,4 +1,3 @@ -int foo[4] = {4,8,12,16}; -int x = foo[0]; //x = 4 -int y = foo[3]; //y = 16 -int z = foo[4]; //z = ????????? +if ( (a=b) ) { /* this shows that an assignment was intended */ + ...; +} diff --git a/Task/Gotchas/C/gotchas-4.c b/Task/Gotchas/C/gotchas-4.c index 6bbd139b94..33537501dd 100644 --- a/Task/Gotchas/C/gotchas-4.c +++ b/Task/Gotchas/C/gotchas-4.c @@ -1,5 +1 @@ -int foo() -{ -char bar[20]; -return sizeof(bar); -} +int foo[4] = { 4, 8, 12, 16 }; diff --git a/Task/Gotchas/C/gotchas-5.c b/Task/Gotchas/C/gotchas-5.c index 1783b1cadd..7a03a2d3b7 100644 --- a/Task/Gotchas/C/gotchas-5.c +++ b/Task/Gotchas/C/gotchas-5.c @@ -1,7 +1,4 @@ -int foo() -{ -#define size_of_bar 20 //the sizeof operator is the same as doing this essentially. - -char bar[size_of_bar]; -return size_of_bar; -} +int foo[4] = { 4, 8, 12, 16 }; +int x = foo[0]; /* x = 4 */ +int y = foo[3]; /* y = 16 */ +int z = foo[4]; /* z contains whatever was after foo[3] in memory */ diff --git a/Task/Gotchas/C/gotchas-6.c b/Task/Gotchas/C/gotchas-6.c index 604364d864..5934e16574 100644 --- a/Task/Gotchas/C/gotchas-6.c +++ b/Task/Gotchas/C/gotchas-6.c @@ -1,4 +1,5 @@ -int gotcha(char bar[]) -{ -return sizeof(bar); +int i; +int squarenums[10]; +for (i=0; i<=10; i++) { + squarenums[i] = i * i; } diff --git a/Task/Gotchas/C/gotchas-7.c b/Task/Gotchas/C/gotchas-7.c index adfaa38c5d..d91e167014 100644 --- a/Task/Gotchas/C/gotchas-7.c +++ b/Task/Gotchas/C/gotchas-7.c @@ -1,2 +1,5 @@ -myArray[40]; -int x = gotcha(myArray); +int foo() +{ + char bar[20]; + return sizeof(bar); /* returns 20 as expected */ +} diff --git a/Task/Gotchas/C/gotchas-8.c b/Task/Gotchas/C/gotchas-8.c index f1d321c444..c5c984bbcd 100644 --- a/Task/Gotchas/C/gotchas-8.c +++ b/Task/Gotchas/C/gotchas-8.c @@ -1,2 +1,4 @@ -myArray[40]; -int x = gotcha(&myArray[0]); +int gotcha(char bar[]) /* could have been: int gotcha(char *bar) */ +{ + return sizeof(bar); /* returns the size of a pointer to char, probably 4 on 32-bit systems and 8 on 64-bit systems */ +} diff --git a/Task/Gotchas/C/gotchas-9.c b/Task/Gotchas/C/gotchas-9.c index f4cdf00887..1e79626483 100644 --- a/Task/Gotchas/C/gotchas-9.c +++ b/Task/Gotchas/C/gotchas-9.c @@ -1,7 +1,2 @@ -int foo(char buf[],int length){} - -int main() -{ -char myArray[30]; -int j = foo(myArray,sizeof(myArray)); //passes 30 as the length parameter. -} +char myArray[40]; +int x = gotcha(myArray); diff --git a/Task/Gotchas/X86-Assembly/gotchas.x86 b/Task/Gotchas/X86-Assembly/gotchas.x86 index 3026998ad2..ab771d3e0b 100644 --- a/Task/Gotchas/X86-Assembly/gotchas.x86 +++ b/Task/Gotchas/X86-Assembly/gotchas.x86 @@ -1,4 +1,15 @@ +; this takes two bytes, it is slower on some processors but faster or the same on others label: -;loop body goes here -DEC ECX -JNZ label + loop label + +; this takes three bytes but is slower on some processors +label: + dec ecx + jnz label + +; this is takes five bytes and is potentially faster than the above +label: + sub ecx,1 + jnz label + +; there is also a two-byte jecxz instruction but no jecxnz diff --git a/Task/Gray-code/FutureBasic/gray-code.basic b/Task/Gray-code/FutureBasic/gray-code.basic new file mode 100644 index 0000000000..9bb50c362a --- /dev/null +++ b/Task/Gray-code/FutureBasic/gray-code.basic @@ -0,0 +1,31 @@ +// Gray Code +//https://rosettacode.org/wiki/Gray_code + +local fn gray2bin(g As uint32) As uint32 + uint32 b = g + While g + g = g >> 1 + b = b Xor g + Wend + Return b +End fn = b + +local fn bin2gray(b As uint32) As uint32 +End fn = b Xor (b >> 1) + +// ------=< MAIN >=------ + +uint32 i +Print " DEC Binary Gray GrayToBinary" + +For i = 0 To 31 + print str$(i) + " "; + if i < 10 then print " "; + print " " + right$(bin$(i),5); + print " -->"; + print " " + right$(bin$(fn bin2gray(i)),5); + print " -->"; + print " " + right$(bin$(fn gray2bin(fn bin2gray(i))),5) +Next + +handleevents diff --git a/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys b/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys index 75ae864e19..b77cb8bd55 100644 --- a/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys +++ b/Task/Greatest-common-divisor/YAMLScript/greatest-common-divisor.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(a=42 b=63): say: "gcd($a $b) -> $gcd(a b)" diff --git a/Task/Greyscale-bars-Display/Nim/greyscale-bars-display.nim b/Task/Greyscale-bars-Display/Nim/greyscale-bars-display.nim index 405fc25cb1..0a0338495a 100644 --- a/Task/Greyscale-bars-Display/Nim/greyscale-bars-display.nim +++ b/Task/Greyscale-bars-Display/Nim/greyscale-bars-display.nim @@ -1,12 +1,11 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import gtk2, gdk2, cairo const Width = 640 Height = 480 -#--------------------------------------------------------------------------------------------------- -proc draw(area: DrawingArea; context: Context) = +proc draw(area: PDrawingArea; cr: ptr Context) = ## Draw the greyscale bars. const @@ -25,43 +24,39 @@ proc draw(area: DrawingArea; context: Context) = # Draw rectangles. for _ in 1..nrect: - context.rectangle(x, y, rectWidth, rectHeight) - context.setSource([grey, grey, grey]) - context.fill() + cr.rectangle(x, y, rectWidth, rectHeight) + cr.setSourceRgb(grey, grey, grey) + cr.fill() x += rectWidth grey += incr y += rectHeight nrect *= 2 -#--------------------------------------------------------------------------------------------------- -proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = +proc onExposeEvent(area: PDrawingArea; event: PEventExpose; data: pointer): bool = ## Callback to draw/redraw the drawing area contents. - - area.draw(context) + let cr = cairoCreate(area.window) + area.draw(cr) result = true -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): bool = + mainQuit() - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Greyscale bars") - # Create the drawing area. - let area = newDrawingArea() - window.add(area) +nimInit() +let window = windowNew(WINDOW_TOPLEVEL) +window.setSizeRequest(Width, Height) +window.setTitle("Greyscale bars") +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - # Connect the "draw" event to the callback to draw the spiral. - discard area.connect("draw", ondraw, pointer(nil)) +# Create the drawing area. +let area = drawingAreaNew() +window.add area - window.showAll() +# Connect the "expose" event to the callback to draw the bars. +discard area.signalConnect("expose-event", SIGNAL_FUNC(onExposeEvent), nil) -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.GreyscaleBars") -discard app.connect("activate", activate) -discard app.run() +window.showAll() +main() diff --git a/Task/Guess-the-number/EMal/guess-the-number.emal b/Task/Guess-the-number/EMal/guess-the-number.emal new file mode 100644 index 0000000000..ddc2333cad --- /dev/null +++ b/Task/Guess-the-number/EMal/guess-the-number.emal @@ -0,0 +1,6 @@ +int number ← random(1, 10 + 1) +int guess ← when(Runtime.args.length æ 1, number, -1) +while number ≠ guess + guess ← ask(int, "Guess the number between 1 and 10 inclusive: ") +end +writeLine("Well guessed!") diff --git a/Task/Guess-the-number/Langur/guess-the-number.langur b/Task/Guess-the-number/Langur/guess-the-number.langur index fe84301d0f..650b318cd4 100644 --- a/Task/Guess-the-number/Langur/guess-the-number.langur +++ b/Task/Guess-the-number/Langur/guess-the-number.langur @@ -2,7 +2,11 @@ writeln "Guess a number from 1 to 10" val n = string(random(10)) for { - val guess = read(">> ", RE/^0*(?:[1-9]|10)(?:\.0+)?$/, "bad data\n", 7, "") + val guess = read( + prompt=">> ", + validation=RE/^0*(?:[1-9]|10)(?:\.0+)?$/, + errmsg="bad data\n", maxattempts=7, alt=zls) + if guess == "" { writeln "too much bad data" break diff --git a/Task/HTTP/Visual-Basic-.NET/http.vb b/Task/HTTP/Visual-Basic-.NET/http.vb index 1f09d1f81e..4fdf9c2351 100644 --- a/Task/HTTP/Visual-Basic-.NET/http.vb +++ b/Task/HTTP/Visual-Basic-.NET/http.vb @@ -1,5 +1,11 @@ Imports System.Net -Dim client As WebClient = New WebClient() -Dim content As String = client.DownloadString("http://www.google.com") -Console.WriteLine(content) +Module RCHttp + + Public Sub Main(args As String()) + Dim client As New WebClient() + Dim content As String = client.DownloadString("http://www.google.com") + Console.WriteLine(content) + End Sub + +End Module diff --git a/Task/HTTP/Wren/http-1.wren b/Task/HTTP/Wren/http-1.wren deleted file mode 100644 index 68b4d13a8d..0000000000 --- a/Task/HTTP/Wren/http-1.wren +++ /dev/null @@ -1,31 +0,0 @@ -/* HTTP.wren */ - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_ERRORBUFFER = 10010 - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() -if (curl == 0) { - System.print("Error initializing cURL.") - return -} -curl.easySetOpt(CURLOPT_URL, "http://www.rosettacode.org/") -curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) -curl.easySetOpt(CURLOPT_ERRORBUFFER, 0) // buffer to be supplied by C - -var status = curl.easyPerform() -if (status != 0) { - System.print("Failed to perform task.") - return -} -curl.easyCleanup() diff --git a/Task/HTTP/Wren/http-2.wren b/Task/HTTP/Wren/http-2.wren deleted file mode 100644 index f352990519..0000000000 --- a/Task/HTTP/Wren/http-2.wren +++ /dev/null @@ -1,127 +0,0 @@ -/* gcc HTTP.c -o HTTP -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -/* C <=> Wren interface functions */ - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLcode cc = curl_easy_perform(curl); - wrenSetSlotDouble(vm, 0, (double)cc); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else { - if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } else if (opt == CURLOPT_ERRORBUFFER) { - char buffer[CURL_ERROR_SIZE]; - curl_easy_setopt(curl, opt, buffer); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "HTTP.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/HTTP/Wren/http.wren b/Task/HTTP/Wren/http.wren new file mode 100644 index 0000000000..082cf7690c --- /dev/null +++ b/Task/HTTP/Wren/http.wren @@ -0,0 +1,3 @@ +import "os" for Process + +Process.exec("curl -s -L http://www.rosettacode.org/") diff --git a/Task/HTTPS-Authenticated/FutureBasic/https-authenticated.basic b/Task/HTTPS-Authenticated/FutureBasic/https-authenticated.basic new file mode 100644 index 0000000000..d9eb17ef39 --- /dev/null +++ b/Task/HTTPS-Authenticated/FutureBasic/https-authenticated.basic @@ -0,0 +1,11 @@ +// HTTPS/Authenticated task +// https://rosettacode.org/wiki/HTTPS/Authenticated# + +CFStringRef response +CFDataRef dta +response = unix @"curl -u admin:admin https://httpbin.org/basic-auth/admin/admin" +dta = fn StringData( response, NSUTF8StringEncoding ) + +print fn StringWithData( dta, NSUTF8StringEncoding ) + +handleevents diff --git a/Task/HTTPS-Authenticated/Wren/https-authenticated-1.wren b/Task/HTTPS-Authenticated/Wren/https-authenticated-1.wren deleted file mode 100644 index 57f5ccf7af..0000000000 --- a/Task/HTTPS-Authenticated/Wren/https-authenticated-1.wren +++ /dev/null @@ -1,31 +0,0 @@ -/* HTTPS_Authenticated.wren */ - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_ERRORBUFFER = 10010 - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() -if (curl == 0) { - System.print("Error initializing cURL.") - return -} -curl.easySetOpt(CURLOPT_URL, "https://user:password@secure.example.com/") -curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) -curl.easySetOpt(CURLOPT_ERRORBUFFER, 0) // buffer to be supplied by C - -var status = curl.easyPerform() -if (status != 0) { - System.print("Failed to perform task.") - return -} -curl.easyCleanup() diff --git a/Task/HTTPS-Authenticated/Wren/https-authenticated-2.wren b/Task/HTTPS-Authenticated/Wren/https-authenticated-2.wren deleted file mode 100644 index f57b8f7e7d..0000000000 --- a/Task/HTTPS-Authenticated/Wren/https-authenticated-2.wren +++ /dev/null @@ -1,127 +0,0 @@ -/* gcc HTTPS_Authenticated.c -o HTTPS_Authenticated -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -/* C <=> Wren interface functions */ - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLcode cc = curl_easy_perform(curl); - wrenSetSlotDouble(vm, 0, (double)cc); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else { - if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } else if (opt == CURLOPT_ERRORBUFFER) { - char buffer[CURL_ERROR_SIZE]; - curl_easy_setopt(curl, opt, buffer); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "HTTPS_Authenticated.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/HTTPS-Authenticated/Wren/https-authenticated.wren b/Task/HTTPS-Authenticated/Wren/https-authenticated.wren new file mode 100644 index 0000000000..1fd4bcd5f1 --- /dev/null +++ b/Task/HTTPS-Authenticated/Wren/https-authenticated.wren @@ -0,0 +1,5 @@ +import "os" for Process + +var userPwd = "admin:admin" +var url = "https://httpbin.org/basic-auth/admin/admin" +Process.exec("curl", ["-u", userPwd, url]) diff --git a/Task/HTTPS-Client-authenticated/FreeBASIC/https-client-authenticated.basic b/Task/HTTPS-Client-authenticated/FreeBASIC/https-client-authenticated.basic new file mode 100644 index 0000000000..3d6a030dce --- /dev/null +++ b/Task/HTTPS-Client-authenticated/FreeBASIC/https-client-authenticated.basic @@ -0,0 +1,64 @@ +#ifdef __FB_WIN32__ + #include once "win/winsock2.bi" + Declare Function fbsocket Alias "socket" (af As Long, Type As Long, protocol As Long) As SOCKET +#else + #include once "sys/socket.bi" + #include once "netinet/in.bi" + #include once "arpa/inet.bi" + #include once "netdb.bi" + Declare Function fbsocket Alias "socket" (af As Long, Type As Long, protocol As Long) As Long +#endif + +Function main() As Integer + #ifdef __fb_win32__ + Dim As WSADATA wsaData + WSAStartup(MAKEWORD(2, 2), @wsaData) + #endif + + ' Create socket + Dim As Long sock = fbsocket(AF_INET, SOCK_STREAM, 0) + + ' Get host info + Dim As hostent Ptr host = gethostbyname("www.example.com") + + ' Set up address structure + Dim As sockaddr_in addr + addr.sin_family = AF_INET + addr.sin_port = htons(443) + addr.sin_addr = *Cast(in_addr Ptr, host->h_addr) + + ' Connect + connect(sock, Cast(sockaddr Ptr, @addr), Sizeof(sockaddr_in)) + + ' Send request + Dim As String request = "GET / HTTP/1.1" & Chr(13, 10) & _ + "Host: www.example.com" & Chr(13, 10) & _ + Chr(13, 10) + send(sock, request, Len(request), 0) + + ' Receive response + Dim As String response + Dim As String buffer = Space(4096) + Dim As Integer bytes + + Do + bytes = recv(sock, buffer, 4096, 0) + If bytes > 0 Then response &= Left(buffer, bytes) + Loop While bytes > 0 + + Print response + + ' Cleanup + #ifdef __fb_win32__ + closesocket(sock) + WSACleanup() + #Else + Close(sock) + #endif + + Return 0 +End Function + +main() + +Sleep diff --git a/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated-1.wren b/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated-1.wren deleted file mode 100644 index 9bd8870f49..0000000000 --- a/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated-1.wren +++ /dev/null @@ -1,34 +0,0 @@ -/* HTTPS_Client-authenticated.wren */ - -var CURLOPT_URL = 10002 -var CURLOPT_SSLCERT = 10025 -var CURLOPT_SSLKEY = 10087 -var CURLOPT_KEYPASSWD = 10258 - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() -if (curl == 0) { - System.print("Error initializing cURL.") - return -} - -curl.easySetOpt(CURLOPT_URL, "https://example.com/") -curl.easySetOpt(CURLOPT_SSLCERT, "cert.pem") -curl.easySetOpt(CURLOPT_SSLKEY, "key.pem") -curl.easySetOpt(CURLOPT_KEYPASSWD, "s3cret") - -var status = curl.easyPerform() -if (status != 0) { - System.print("Failed to perform task.") - return -} -curl.easyCleanup() diff --git a/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated-2.wren b/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated-2.wren deleted file mode 100644 index 6cb74e498d..0000000000 --- a/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated-2.wren +++ /dev/null @@ -1,117 +0,0 @@ -/* gcc HTTPS_Client-authenticated.c -o HTTPS_Client-authenticated -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -/* C <=> Wren interface functions */ - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLcode cc = curl_easy_perform(curl); - wrenSetSlotDouble(vm, 0, (double)cc); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - const char *arg = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, arg); -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "HTTPS_Client-authenticated.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated.wren b/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated.wren new file mode 100644 index 0000000000..dcf8f261a0 --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Wren/https-client-authenticated.wren @@ -0,0 +1,7 @@ +import "os" for Process + +var certFile = "myCert.pem" +var keyFile = "myKey.pem" +var url = "www.example.com" + +Process.exec("curl", ["--cert", certFile, "--key", keyFile, url]) diff --git a/Task/HTTPS/Wren/https-1.wren b/Task/HTTPS/Wren/https-1.wren deleted file mode 100644 index c26b4bd296..0000000000 --- a/Task/HTTPS/Wren/https-1.wren +++ /dev/null @@ -1,31 +0,0 @@ -/* HTTPS.wren */ - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_ERRORBUFFER = 10010 - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() -if (curl == 0) { - System.print("Error initializing cURL.") - return -} -curl.easySetOpt(CURLOPT_URL, "https://www.w3.org/") -curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) -curl.easySetOpt(CURLOPT_ERRORBUFFER, 0) // buffer to be supplied by C - -var status = curl.easyPerform() -if (status != 0) { - System.print("Failed to perform task.") - return -} -curl.easyCleanup() diff --git a/Task/HTTPS/Wren/https-2.wren b/Task/HTTPS/Wren/https-2.wren deleted file mode 100644 index dc70c2b81b..0000000000 --- a/Task/HTTPS/Wren/https-2.wren +++ /dev/null @@ -1,127 +0,0 @@ -/* gcc HTTPS.c -o HTTPS -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -/* C <=> Wren interface functions */ - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLcode cc = curl_easy_perform(curl); - wrenSetSlotDouble(vm, 0, (double)cc); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else { - if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } else if (opt == CURLOPT_ERRORBUFFER) { - char buffer[CURL_ERROR_SIZE]; - curl_easy_setopt(curl, opt, buffer); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "HTTPS.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/HTTPS/Wren/https.wren b/Task/HTTPS/Wren/https.wren new file mode 100644 index 0000000000..1d35125f6e --- /dev/null +++ b/Task/HTTPS/Wren/https.wren @@ -0,0 +1,3 @@ +import "os" for Process + +Process.exec("curl -s -L https://www.w3.org/") diff --git a/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq b/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq index c6b0fe55d9..06fd8b01e9 100644 --- a/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq +++ b/Task/Hailstone-sequence/Jq/hailstone-sequence-2.jq @@ -3,5 +3,5 @@ "The first four numbers: \($h[0:4])", "The last four numbers: \($h|.[length-4:length])", "", - max_hailstone(100000) as $m - | "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))" + (max_hailstone(100000) as $m + | "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))") diff --git a/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 b/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 index 36d886dcb9..6cdcbfba59 100644 --- a/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 +++ b/Task/Hailstone-sequence/M2000-Interpreter/hailstone-sequence.m2000 @@ -7,7 +7,7 @@ Module hailstone.Task { n*=3 : n++: val=n } } - Count=Lambda (n) ->{ + count=Lambda (n as long) ->{ m=lambda n ->{ if n=1 then =false: exit =true :if n mod 2=0 then n/=2 :exit diff --git a/Task/Halt-and-catch-fire/FutureBasic/halt-and-catch-fire.basic b/Task/Halt-and-catch-fire/FutureBasic/halt-and-catch-fire.basic new file mode 100644 index 0000000000..858825d80b --- /dev/null +++ b/Task/Halt-and-catch-fire/FutureBasic/halt-and-catch-fire.basic @@ -0,0 +1 @@ +~ 0,0 diff --git a/Task/Halt-and-catch-fire/Uiua/halt-and-catch-fire.uiua b/Task/Halt-and-catch-fire/Uiua/halt-and-catch-fire.uiua new file mode 100644 index 0000000000..414ff2f8ec --- /dev/null +++ b/Task/Halt-and-catch-fire/Uiua/halt-and-catch-fire.uiua @@ -0,0 +1 @@ +⍤@a 0 diff --git a/Task/Halt-and-catch-fire/Zig/halt-and-catch-fire.zig b/Task/Halt-and-catch-fire/Zig/halt-and-catch-fire.zig new file mode 100644 index 0000000000..d8b5049869 --- /dev/null +++ b/Task/Halt-and-catch-fire/Zig/halt-and-catch-fire.zig @@ -0,0 +1,3 @@ +pub fn main() void { + unreachable; +} diff --git a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v index 509ec16025..bd63012c8d 100644 --- a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v +++ b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-1.v @@ -1,9 +1,7 @@ import math.big fn min(a big.Integer, b big.Integer) big.Integer { - if a < b { - return a - } + if a < b {return a} return b } diff --git a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v index 3f7755a80b..4fa74da146 100644 --- a/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v +++ b/Task/Hamming-numbers/V-(Vlang)/hamming-numbers-2.v @@ -63,7 +63,7 @@ fn (lr LogRep) str() string { } struct HammingsLog { - mut: + mut: // automatically initialized with LogRep = one (defult)... s2 []LogRep = []LogRep { len: 1024, cap: 1024 } s3 []LogRep = []LogRep { len: 1024, cap: 1024 } diff --git a/Task/Harmonic-series/ALGOL-60/harmonic-series.alg b/Task/Harmonic-series/ALGOL-60/harmonic-series.alg new file mode 100644 index 0000000000..7b5f62d6ba --- /dev/null +++ b/Task/Harmonic-series/ALGOL-60/harmonic-series.alg @@ -0,0 +1,32 @@ +begin + +real i, h, n, limit; + +limit := 20; +h := 0; +outstring(1,"First"); +outreal(1,limit); +outstring(1,"numbers in the harmonic series\n"); +for i := 1, i + 1 while i <= limit do + begin + h := h + 1 / i; + outreal(1,i); + outreal(1,h); + outstring(1,"\n"); + end; + +for i := 1, i + 1 while i <= 5 do + begin + h := 1; + for n := 2, n + 1 while h <= i do + begin + h := h + 1 / n; + end; + outstring(1,"First harmonic number >"); + outreal(1,i); + outstring(1,"is at position"); + outreal(1,n-1); + outstring(1,"\n"); + end; + +end diff --git a/Task/Hash-from-two-arrays/Emacs-Lisp/hash-from-two-arrays.l b/Task/Hash-from-two-arrays/Emacs-Lisp/hash-from-two-arrays.l index da8a189a6d..7967d72d53 100644 --- a/Task/Hash-from-two-arrays/Emacs-Lisp/hash-from-two-arrays.l +++ b/Task/Hash-from-two-arrays/Emacs-Lisp/hash-from-two-arrays.l @@ -1,3 +1,11 @@ -(let ((keys ["a" "b" "c"]) - (values [1 2 3])) - (apply 'vector (cl-loop for i across keys for j across values collect (vector i j)))) +(defun hash-from-two-arrays (seq1 seq2) + (let ((hash (make-hash-table :test 'equal)) + (list1 (if (listp seq1) seq1 (append seq1 nil))) + (list2 (if (listp seq2) seq2 (append seq2 nil)))) + (while (and list1 list2) + (puthash (car list1) (car list2) hash) + (setq list1 (cdr list1) + list2 (cdr list2))) + hash)) + +(hash-from-two-arrays (list 'a 'b 'c) [1 2 3]) diff --git a/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur b/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur index 02fa5dea1e..8b6190318f 100644 --- a/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur +++ b/Task/Hash-from-two-arrays/Langur/hash-from-two-arrays-2.langur @@ -1,5 +1,7 @@ -val new = foldfrom( - fn h, key, value:more(h, {key: value}), - {:}, fw/a b c d/, [1, 2, 3, 4], +val new = fold( + fw/a b c d/, [1, 2, 3, 4], + by=fn(h, key, value) { more h, {key: value} }, + init={:}, ) + writeln new diff --git a/Task/Hash-from-two-arrays/Uiua/hash-from-two-arrays.uiua b/Task/Hash-from-two-arrays/Uiua/hash-from-two-arrays.uiua new file mode 100644 index 0000000000..0b37a63ba3 --- /dev/null +++ b/Task/Hash-from-two-arrays/Uiua/hash-from-two-arrays.uiua @@ -0,0 +1,3 @@ +A ← {"carl" "randy" "sam"} +B ← {"robinson" "michaels" "wooley"} +map A B diff --git a/Task/Haversine-formula/PascalABC.NET/haversine-formula.pas b/Task/Haversine-formula/PascalABC.NET/haversine-formula.pas new file mode 100644 index 0000000000..8eafc78a1a --- /dev/null +++ b/Task/Haversine-formula/PascalABC.NET/haversine-formula.pas @@ -0,0 +1,19 @@ +const + r = 6372.8; + +function haversine(lat1, lon1, lat2, lon2: real): real; +begin + var dLat := degToRad(lat2 - lat1); + var dLon := degToRad(lon2 - lon1); + lat1 := degToRad(lat1); + lat2 := degToRad(lat2); + + var a := sin(dLat / 2) * sin(dLat / 2) + cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2); + var c := 2 * arcsin(sqrt(a)); + + result := r * c; +end; + +begin + haversine(36.12, -86.67, 33.94, -118.40).Println; +end. diff --git a/Task/Hello-world-Graphical/AutoHotKey-V2/hello-world-graphical.ahk b/Task/Hello-world-Graphical/Autohotkey-V2/hello-world-graphical.ahk similarity index 100% rename from Task/Hello-world-Graphical/AutoHotKey-V2/hello-world-graphical.ahk rename to Task/Hello-world-Graphical/Autohotkey-V2/hello-world-graphical.ahk diff --git a/Task/Hello-world-Line-printer/Lua/hello-world-line-printer.lua b/Task/Hello-world-Line-printer/Lua/hello-world-line-printer.lua new file mode 100644 index 0000000000..ad8cf4ea5f --- /dev/null +++ b/Task/Hello-world-Line-printer/Lua/hello-world-line-printer.lua @@ -0,0 +1,7 @@ +require "io" + +lp = io.open("/dev/lp0", 'w') + +io.output(lp) +io.write("Hello World\n") +io.close(lp) diff --git a/Task/Hello-world-Line-printer/Wren/hello-world-line-printer-1.wren b/Task/Hello-world-Line-printer/Wren/hello-world-line-printer-1.wren deleted file mode 100644 index 93d982231b..0000000000 --- a/Task/Hello-world-Line-printer/Wren/hello-world-line-printer-1.wren +++ /dev/null @@ -1,7 +0,0 @@ -/* Hello_world_Line_printer.wren */ - -class C { - foreign static lprint(s) -} - -C.lprint("Hello World!") diff --git a/Task/Hello-world-Line-printer/Wren/hello-world-line-printer-2.wren b/Task/Hello-world-Line-printer/Wren/hello-world-line-printer-2.wren deleted file mode 100644 index 3c40e19b85..0000000000 --- a/Task/Hello-world-Line-printer/Wren/hello-world-line-printer-2.wren +++ /dev/null @@ -1,62 +0,0 @@ -/* gcc Hello_world_Line_printer.c -o Hello_world_Line_printer -lwren -lm */ - -#include -#include -#include -#include "wren.h" - -/* C <=> Wren interface functions */ - -void C_lprint(WrenVM* vm) { - const char *arg = wrenGetSlotString(vm, 1); - char command[strlen(arg) + 13]; - strcpy(command, "echo \""); - strcat(command, arg); - strcat(command, "\" | lp"); - system(command); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "lprint(_)") == 0) return C_lprint; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Hello_world_Line_printer.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Hello-world-Line-printer/Wren/hello-world-line-printer.wren b/Task/Hello-world-Line-printer/Wren/hello-world-line-printer.wren new file mode 100644 index 0000000000..0b54029108 --- /dev/null +++ b/Task/Hello-world-Line-printer/Wren/hello-world-line-printer.wren @@ -0,0 +1,3 @@ +import "os" for Process + +Process.exec("echo \"Hello World!\" | lpr") diff --git a/Task/Hello-world-Standard-error/FutureBasic/hello-world-standard-error.basic b/Task/Hello-world-Standard-error/FutureBasic/hello-world-standard-error.basic new file mode 100644 index 0000000000..d481f57192 --- /dev/null +++ b/Task/Hello-world-Standard-error/FutureBasic/hello-world-standard-error.basic @@ -0,0 +1 @@ +alert 1,NSAlertStyleCritical,@"ERROR",@"",@"Goodbye World!" diff --git a/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur b/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur index 3e78e993c5..b8c0747ee1 100644 --- a/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur +++ b/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur @@ -1 +1 @@ -writelnErr "Goodbye, world." +writelnErr "Houston, we have a problem." diff --git a/Task/Hello-world-Standard-error/Wren/hello-world-standard-error.wren b/Task/Hello-world-Standard-error/Wren/hello-world-standard-error.wren index 6a71f0c607..fd53c2ca9d 100644 --- a/Task/Hello-world-Standard-error/Wren/hello-world-standard-error.wren +++ b/Task/Hello-world-Standard-error/Wren/hello-world-standard-error.wren @@ -1 +1,3 @@ -Fiber.abort("Goodbye, World!") +import "io" for Stderr + +Stderr.print("Goodbye, World!") diff --git a/Task/Hello-world-Text/LLVM/hello-world-text.llvm b/Task/Hello-world-Text/LLVM/hello-world-text.llvm index ceedc75fe4..c9ac842688 100644 --- a/Task/Hello-world-Text/LLVM/hello-world-text.llvm +++ b/Task/Hello-world-Text/LLVM/hello-world-text.llvm @@ -1,11 +1,11 @@ ; const char str[14] = "Hello World!\00" -@.str = private unnamed_addr constant [14 x i8] c"Hello, world!\00" +@str = private unnamed_addr constant [14 x i8] c"Hello, world!\00" ; declare extern `puts` method declare i32 @puts(i8*) nounwind define i32 @main() { - call i32 @puts( i8* getelementptr ([14 x i8]* @str, i32 0,i32 0)) + call i32 @puts( i8* getelementptr ([14 x i8], [14 x i8]* @str, i32 0,i32 0)) ret i32 0 } diff --git a/Task/Hello-world-Text/M2000-Interpreter/hello-world-text.m2000 b/Task/Hello-world-Text/M2000-Interpreter/hello-world-text.m2000 index 344c7f6491..095ca03aef 100644 --- a/Task/Hello-world-Text/M2000-Interpreter/hello-world-text.m2000 +++ b/Task/Hello-world-Text/M2000-Interpreter/hello-world-text.m2000 @@ -1,3 +1,4 @@ -Print "Hello World!" \\ printing on columns, in various ways defined by last $() for specific layer -Print $(4),"Hello World!" \\ proportional printing using columns, expanded to a number of columns as the length of string indicates. -Report "Hello World!" \\ proportional printing with word wrap, for text, can apply justification and rendering a range of text lines +module HelloWorld { + print "Hello World!" +} +HelloWorld diff --git a/Task/Hello-world-Text/Retro/hello-world-text.retro b/Task/Hello-world-Text/Retro/hello-world-text.retro index bea2713ce6..6ba876ba35 100644 --- a/Task/Hello-world-Text/Retro/hello-world-text.retro +++ b/Task/Hello-world-Text/Retro/hello-world-text.retro @@ -1 +1 @@ -'Hello_world! s:put +'Hello_world! s:put nl diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text.ys index 0432ff6961..11f7569ea9 100644 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text.ys +++ b/Task/Hello-world-Text/YAMLScript/hello-world-text.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 say: "Hello, world!" diff --git a/Task/Hello-world-Text/Zig/hello-world-text.zig b/Task/Hello-world-Text/Zig/hello-world-text.zig index 6090c0bd6c..bde0254043 100644 --- a/Task/Hello-world-Text/Zig/hello-world-text.zig +++ b/Task/Hello-world-Text/Zig/hello-world-text.zig @@ -1,6 +1,6 @@ const std = @import("std"); -pub fn main() std.fs.File.WriteError!void { +pub fn main() !void { const stdout = std.io.getStdOut(); try stdout.writeAll("Hello world!\n"); diff --git a/Task/Here-document/EasyLang/here-document.easy b/Task/Here-document/EasyLang/here-document.easy index 9ad6f150d5..eb9d1a19cd 100644 --- a/Task/Here-document/EasyLang/here-document.easy +++ b/Task/Here-document/EasyLang/here-document.easy @@ -11,4 +11,4 @@ This is a 'raw' string with the following properties: - interpolation such as %(a) is also interpreted literally. - """ is also interpreted literally. -`Have fun!` +Have fun! diff --git a/Task/Here-document/FutureBasic/here-document.basic b/Task/Here-document/FutureBasic/here-document.basic new file mode 100644 index 0000000000..f673e6d968 --- /dev/null +++ b/Task/Here-document/FutureBasic/here-document.basic @@ -0,0 +1,5 @@ +text @"Monaco" // Mono spaced font +print @"Here" +print @" Doc" + +handleevents diff --git a/Task/Heronian-triangles/PascalABC.NET/heronian-triangles.pas b/Task/Heronian-triangles/PascalABC.NET/heronian-triangles.pas new file mode 100644 index 0000000000..7a00c8ae30 --- /dev/null +++ b/Task/Heronian-triangles/PascalABC.NET/heronian-triangles.pas @@ -0,0 +1,42 @@ +uses school; + +function hero(a, b, c: integer): real; +begin + var s := (a + b + c) / 2; + var a2 := s * (s - a) * (s - b) * (s - c); + result := if a2 > 0 then a2.sqrt else 0; +end; + +function is_heronian(a, b, c: integer): boolean; +begin + var h := hero(a, b, c); + result := (h > 0) and (h = h.Ceil); +end; + +function gcd3(x, y, z: integer) := gcd(gcd(x, y), z); + +function heronians(n: integer): sequence of (integer, integer, integer); +begin + for var x := 1 to n do + for var y := x to n do + for var z := y to n do + if (x + y > z) and (gcd3(x, y, z) = 1) and is_heronian(x, y, z) then + yield (x, y, z); +end; + +begin + var n := 200; + var hsorted := heronians(n).OrderBy(t -> hero(t[0], t[1], t[2])) + .ThenBy(t -> t[0] + t[1] + t[2]) + .ThenBy(t -> t[2]); + + writeln('Primitive Heronian triangles with sides up to ', n, ': ', hsorted.count); + writeln; + writeln('First ten when ordered by increasing area, then perimeter, then maximum sides:'); + foreach var h in hsorted.Take(10) do + writeln(h:12, ' perim: ', h[0] + h[1] + h[2]:3, ' area: ', hero(h[0], h[1], h[2]):3); + writeln; + writeln('All with area 210 subject to the previous ordering:'); + foreach var h in hsorted.Where(t -> hero(t[0], t[1], t[2]) = 210) do + writeln(h:12, ' perim: ', h[0] + h[1] + h[2]:3, ' area: ', hero(h[0], h[1], h[2]):3); +end. diff --git a/Task/Hex-words/PascalABC.NET/hex-words.pas b/Task/Hex-words/PascalABC.NET/hex-words.pas new file mode 100644 index 0000000000..82c258f36c --- /dev/null +++ b/Task/Hex-words/PascalABC.NET/hex-words.pas @@ -0,0 +1,38 @@ +uses System.Net, system.Globalization; + +function digroot(n: integer): integer; +begin + while n > 9 do + n := n.ToString.Select(x -> x.ToDigit).Sum; + result := n; +end; + +begin + var client := new WebClient(); + var text := client.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); + var words: sequence of string := text.ToWords(|#10, #13|); + words := words.Where(w -> w.length >= 4) + .Where(w -> w.All(c -> c in 'abcdef')); + + var results := new List<(string, integer, integer)>; + foreach var w in words do + begin + var wnum := integer.Parse(w, NumberStyles.HexNumber); + results.Add((w, wnum, digroot(wnum))); + end; + + println('Hex words in unixdict.txt:'); + println('Root Word Base 10'); + println('-' * 23); + foreach var a in results.OrderBy(t -> t[2]) do + writeln(a[2], a[0]:10, a[1]:11); + println('Total count of these words:', results.Count); + println; + println('Hex words with > 3 distinct letters:'); + println('Root Word Base 10'); + println('-' * 23); + results := results.Where(a -> (hset(a[0].ToCharArray).Count >= 4)).ToList; + foreach var a in results.OrderByDescending(t -> t[1]) do + writeln(a[2], a[0]:10, a[1]:11); + println('Total count of those words:', results.Count) +end. diff --git a/Task/Hickerson-series-of-almost-integers/Free-Pascal-Lazarus/hickerson-series-of-almost-integers.pas b/Task/Hickerson-series-of-almost-integers/Free-Pascal-Lazarus/hickerson-series-of-almost-integers.pas new file mode 100644 index 0000000000..f127845ab8 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Free-Pascal-Lazarus/hickerson-series-of-almost-integers.pas @@ -0,0 +1,35 @@ +{$mode ObjFPC} {$H+} + +Uses sysutils,math; + +Function fact(n : integer): qword; +Begin + If n <= 1 Then + result := 1 + Else + result := n * fact(n-1); +End; + +Function hickerson(n : integer): extended; +Begin + result := fact(n) / (2*power(ln(2),n+1)); +End; + +Function AlmostInteger(n : extended): boolean; + +Var firstdec : integer; +Begin + firstdec := trunc(n * 10) Mod 10; + result := (firstdec = 0) Or (firstdec = 9); +End; + +Var i : integer; + hick : extended; + +Begin + For i := 1 To 17 Do + Begin + hick := hickerson(i); + writeln('H(',i:2,') = ',hick:25:4,almostinteger(hick): 7); + End; +End. diff --git a/Task/Hickerson-series-of-almost-integers/PascalABC.NET/hickerson-series-of-almost-integers.pas b/Task/Hickerson-series-of-almost-integers/PascalABC.NET/hickerson-series-of-almost-integers.pas new file mode 100644 index 0000000000..0147f61abc --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/PascalABC.NET/hickerson-series-of-almost-integers.pas @@ -0,0 +1,12 @@ +## +var ln2: decimal := decimal.Parse('0.693147180559945309417232121458'); +var h := decimal(0.5) / ln2; + +for var i := 1 to 17 do +begin + h := h * i / ln2; + var w := BigInteger(h); + var d := (h - decimal(w)).ToString.Substring(2, 1); + + Writeln('n: ', i:2, ' h: ', h, ' Nearly integer: ', (d = '0') or (d = '9')); +end; diff --git a/Task/Higher-order-functions/REXX/higher-order-functions-1.rexx b/Task/Higher-order-functions/REXX/higher-order-functions-1.rexx new file mode 100644 index 0000000000..11f07018d9 --- /dev/null +++ b/Task/Higher-order-functions/REXX/higher-order-functions-1.rexx @@ -0,0 +1,27 @@ +include Settings + +Main: +say version; say 'Higher-order functions'; say +call Calculate '1/x',6 +call Calculate 'Sqrt(x)',2 +call Calculate 'Sin(x)',1 +call Calculate 'Cos(x)',2 +call Calculate 'Tan(x)',3 +call Calculate 'Sin(x)/Cos(x)-Tan(x)',1 +call Calculate 'x**2-3*x+Arcsin(x)-Sinh(x)/x-Pi()+E()',1/3 +exit + +Calculate: +procedure +parse arg ff,xx +say ff 'for x='xx 'makes' Evaluate(ff,xx)+0 +return + +Evaluate: +procedure +parse arg f,x +interpret 'return' f + +include Functions +include Constants +include Abend diff --git a/Task/Higher-order-functions/REXX/higher-order-functions.rexx b/Task/Higher-order-functions/REXX/higher-order-functions-2.rexx similarity index 100% rename from Task/Higher-order-functions/REXX/higher-order-functions.rexx rename to Task/Higher-order-functions/REXX/higher-order-functions-2.rexx diff --git a/Task/Hofstadter-Conway-$10-000-sequence/ALGOL-68/hofstadter-conway-$10-000-sequence.alg b/Task/Hofstadter-Conway-$10-000-sequence/ALGOL-68/hofstadter-conway-$10-000-sequence.alg index f73c6d20c7..562efb8774 100644 --- a/Task/Hofstadter-Conway-$10-000-sequence/ALGOL-68/hofstadter-conway-$10-000-sequence.alg +++ b/Task/Hofstadter-Conway-$10-000-sequence/ALGOL-68/hofstadter-conway-$10-000-sequence.alg @@ -3,8 +3,8 @@ BEGIN [max]INT a list; INT k1 := 2, lg2 := 1, - v := a list[1] := a list[2] := 1; # Concurrent declaration and assignment in declarations are allowed # - + v := a list[1] := a list[2] := 1; # Concurrent declaration and assignment # + # in declarations are allowed # INT nmax; LONG REAL amax := 0.0; @@ -13,15 +13,16 @@ BEGIN FOR n FROM 3 TO max DO v := a list[n] := a list[v] + a list[n-v]; - ( amax < v/n | amax := v/n; nmax := n ); # When given a Boolean as the 1st expression, ( | ) is the short form of IF...THEN...FI # - - IF v/n >= 0.55 THEN # This is the equivalent full form of the above construct # + ( amax < v/n | amax := v/n; nmax := n ); # When given a Boolean as the 1st expression, # + # ( | ) is the short form of IF...THEN...FI # + IF v/n >= 0.55 THEN # This is the equivalent full form of the above construct # mallows number := n FI; IF ABS(BIN k1 AND BIN n) = 0 THEN # 'BIN' converts an INT type to a BITS type; In this context, 'ABS' reverses that operation # - printf(($"Maximum between 2^"g(0)" and 2^"g(0)" is about "g(-10,8)" at "g(0)l$, lg2,lg2+1, amax, nmax)); + print(("Maximum between 2^",whole(lg2,0)," and 2^",whole(lg2+1,0)," is about ",fixed(amax,-10,8))); + print((" at ",whole(nmax,0),newline)); amax := 0; lg2 PLUSAB 1 # 'PLUSAB' (plus-and-becomes) has the short form +:= # FI; @@ -30,7 +31,4 @@ BEGIN mallows number # the result of the last expression evaluated is returned as the result of the PROC # END; -INT mallows number = do sqnc(2**20); # This definition of 'mallows number' does not clash with the variable - of the same name inside PROC do sqnc - they are in different scopes# - -printf(($"You too might have won $1000 with an answer of n = "g(0)$, mallows number)) +print(("You too might have won $1000 with an answer of n = ", whole(do sqnc(2**20),0))) diff --git a/Task/Hofstadter-Conway-$10-000-sequence/PascalABC.NET/hofstadter-conway-$10-000-sequence.pas b/Task/Hofstadter-Conway-$10-000-sequence/PascalABC.NET/hofstadter-conway-$10-000-sequence.pas new file mode 100644 index 0000000000..2cae58c01e --- /dev/null +++ b/Task/Hofstadter-Conway-$10-000-sequence/PascalABC.NET/hofstadter-conway-$10-000-sequence.pas @@ -0,0 +1,22 @@ +[cache] +function hof(n: integer): integer; +begin + if n < 3 then result := 1 + else result := hof(hof(n - 1)) + hof(n - hof(n - 1)) +end; + +begin + for var nmax := 1 to 19 do + begin + var amax := 0.0; + for var n := 1 shl nmax to 1 shl (nmax + 1) do + amax := max(amax, hof(n) / n); + writeln('Maximum between 2^', nmax, ' and 2^', nmax + 1, ' was ', amax); + end; + + var prize := 1 shl 20; + repeat + prize -= 1; + until (hof(prize) / prize >= 0.55); + println('Mallows'' number =', prize); +end. diff --git a/Task/Hofstadter-Figure-Figure-sequences/PascalABC.NET/hofstadter-figure-figure-sequences.pas b/Task/Hofstadter-Figure-Figure-sequences/PascalABC.NET/hofstadter-figure-figure-sequences.pas new file mode 100644 index 0000000000..12cfa59ae1 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/PascalABC.NET/hofstadter-figure-figure-sequences.pas @@ -0,0 +1,31 @@ +function ffs: sequence of integer; forward; + +function ffr: sequence of integer; +begin + var n := 1; + yield n; + foreach var s in ffs do + begin + n += s; + yield n; + end; +end; + +function ffs: sequence of integer; +begin + yield 2; + yield 4; + var u := 5; + foreach var r in ffr do + begin + if r <= u then continue; + foreach var x in (u..r - 1) do yield x; + u := r + 1; + end; +end; + +begin + ffr.Take(10).Println; + var a := ffr.Take(40) + ffs.Take(960); + (1..1000).SequenceEqual(a.Sorted).Println; +end. diff --git a/Task/Hofstadter-Q-sequence/ALGOL-68/hofstadter-q-sequence.alg b/Task/Hofstadter-Q-sequence/ALGOL-68/hofstadter-q-sequence.alg index 071be33dcf..02d0922aa4 100644 --- a/Task/Hofstadter-Q-sequence/ALGOL-68/hofstadter-q-sequence.alg +++ b/Task/Hofstadter-Q-sequence/ALGOL-68/hofstadter-q-sequence.alg @@ -1,24 +1,16 @@ -#!/usr/local/bin/a68g --script # - -INT n = 100000; -main: -( - INT flip; - [n]INT q; +BEGIN + [100000]INT q; + INT flips := 0; q[1] := q[2] := 1; - - FOR i FROM 3 TO n DO - q[i] := q[i - q[i - 1]] + q[i - q[i - 2]] OD; + FOR i FROM 3 TO UPB q DO + q[i] := q[i - q[i - 1]] + q[i - q[i - 2]]; + IF q[i] < q[i - 1] THEN flips +:= 1 FI + OD; FOR i TO 10 DO - printf(($g(0)$, q[i], $b(l,x)$, i = 10)) OD; + print((whole(q[i],0), IF i = 10 THEN newline ELSE space FI)) OD; - printf(($g(0)l$, q[1000])); - - flip := 0; - FOR i TO n-1 DO - flip +:= ABS (q[i] > q[i + 1]) OD; - - printf(($"flips: "g(0)l$, flip)) -) + print((whole(q[1000],0), newline)); + print(("flips: ", whole(flips,0), newline)) +END diff --git a/Task/Hofstadter-Q-sequence/FutureBasic/hofstadter-q-sequence.basic b/Task/Hofstadter-Q-sequence/FutureBasic/hofstadter-q-sequence.basic new file mode 100644 index 0000000000..c9f3691860 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/FutureBasic/hofstadter-q-sequence.basic @@ -0,0 +1,19 @@ +_limit = 100000 + +Long Q(_limit), i, count = 0 + +Q(1) = 1 +Q(2) = 1 +For i = 3 To _limit + Q(i) = Q(i-Q(i-1)) + Q(i-Q(i-2)) + If Q(i) < Q(i-1) Then count += 1 +Next i + +Print "First 10 elements:"; +For i = 1 To 10 + Print str$(Q(i)) + " "; +Next i +Print +Print "Q(1000) is "; Q(1000) +Print "There were" + str$(count) + " inversions" +handleevents diff --git a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-2.hs b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-2.hs index 37c7f28e2d..3a361b185b 100644 --- a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-2.hs +++ b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-2.hs @@ -1,21 +1,13 @@ -import Data.Array +douglasHofstadter :: Int -> [Int] +douglasHofstadter m = reverse (dSeqEffect [1,1] 2 m) + where + dSeqEffect xs n m | n > m = xs + | otherwise = dSeqEffect (((xs !! (xs !! (n - 1))) + (xs !! (n - (xs !! (n - 1)))) ) : xs) (n + 1) m -qSequence n = arr - where - arr = listArray (1,n) $ 1:1: map g [3..n] - g i = arr!(i - arr!(i-1)) + - arr!(i - arr!(i-2)) +-- main +getIntArg :: IO Int +getIntArg = fmap (read . head) getArgs -gradualth m k arr -- gradually precalculate m-th item - | m <= v = pre `seq` arr!m -- in steps of k - where -- to prevent STACK OVERFLOW - pre = foldl1 (\a b-> a `seq` arr!b) [u,u+k..m] - (u,v) = bounds arr - -qSeqTest m n = let arr = qSequence $ max m n in - ( take 10 . elems $ arr -- 10 first items - , gradualth m 10000 $ arr -- m-th item - , length . filter (> 0) -- reversals in n items - . _S (zipWith (-)) tail . take n . elems $ arr ) - -_S f g x = f x (g x) +main = do + args <- getIntArg + print (douglasHofstadter args) diff --git a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-3.hs b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-3.hs index 162d5cee47..37c7f28e2d 100644 --- a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-3.hs +++ b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-3.hs @@ -1,7 +1,21 @@ -Prelude Main> qSeqTest 1000 100000 -- reversals in 100,000 -([1,1,2,3,3,4,5,5,6,6],502,49798) -(0.09 secs, 18879708 bytes) +import Data.Array -Prelude Main> qSeqTest 1000000 100000 -- 1,000,000-th item -([1,1,2,3,3,4,5,5,6,6],512066,49798) -(2.80 secs, 87559640 bytes) +qSequence n = arr + where + arr = listArray (1,n) $ 1:1: map g [3..n] + g i = arr!(i - arr!(i-1)) + + arr!(i - arr!(i-2)) + +gradualth m k arr -- gradually precalculate m-th item + | m <= v = pre `seq` arr!m -- in steps of k + where -- to prevent STACK OVERFLOW + pre = foldl1 (\a b-> a `seq` arr!b) [u,u+k..m] + (u,v) = bounds arr + +qSeqTest m n = let arr = qSequence $ max m n in + ( take 10 . elems $ arr -- 10 first items + , gradualth m 10000 $ arr -- m-th item + , length . filter (> 0) -- reversals in n items + . _S (zipWith (-)) tail . take n . elems $ arr ) + +_S f g x = f x (g x) diff --git a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-4.hs b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-4.hs index 40d00cdae6..162d5cee47 100644 --- a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-4.hs +++ b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-4.hs @@ -1,16 +1,7 @@ -q = qq (listArray (1,2) [1,1]) 1 where - qq ar n = (arr!n) : qq arr (n+1) where - l = snd (bounds ar) - step n =arr!(n - (fromIntegral (arr!(n - 1)))) + - arr!(n - (fromIntegral (arr!(n - 2)))) - arr :: Array Int Integer - arr | n <= l = ar - | otherwise = listArray (1, l*2)$ - ([ar!i | i <- [1..l]] ++ - [step i | i <- [l+1..l*2]]) +Prelude Main> qSeqTest 1000 100000 -- reversals in 100,000 +([1,1,2,3,3,4,5,5,6,6],502,49798) +(0.09 secs, 18879708 bytes) -main = do - putStr("first 10: "); print (take 10 q) - putStr("1000-th: "); print (q !! 999) - putStr("flips: ") - print $ length $ filter id $ take 100000 (zipWith (>) q (tail q)) +Prelude Main> qSeqTest 1000000 100000 -- 1,000,000-th item +([1,1,2,3,3,4,5,5,6,6],512066,49798) +(2.80 secs, 87559640 bytes) diff --git a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-5.hs b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-5.hs index d7722cbb4d..40d00cdae6 100644 --- a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-5.hs +++ b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-5.hs @@ -1,21 +1,16 @@ -import Data.Array -import Data.Int (Int64) +q = qq (listArray (1,2) [1,1]) 1 where + qq ar n = (arr!n) : qq arr (n+1) where + l = snd (bounds ar) + step n =arr!(n - (fromIntegral (arr!(n - 1)))) + + arr!(n - (fromIntegral (arr!(n - 2)))) + arr :: Array Int Integer + arr | n <= l = ar + | otherwise = listArray (1, l*2)$ + ([ar!i | i <- [1..l]] ++ + [step i | i <- [l+1..l*2]]) -q = qq [listArray (1,2) [1,1]] 1 where - qq a n = seek aa n : qq aa (1 + n) where - aa | n <= l = a - | otherwise = listArray (l+1,l*2) (take l $ drop 2 lst):a - where - l = snd (bounds $ head a) - lst = seek a (l-1):seek a l:(ext lst (l+1)) - ext (q1:q2:qs) i = (g (i-q2) + g (i-q1)):ext (q2:qs) (1+i) - g = seek aa - seek (ar:ars) n - | n >= fst (bounds ar) = ar ! n - | otherwise = seek ars n - --- Only a perf test. Task can be done exactly the same as above -main = print $ sum qqq - where - qqq :: [Int64] - qqq = map fromIntegral $ take 3000000 q +main = do + putStr("first 10: "); print (take 10 q) + putStr("1000-th: "); print (q !! 999) + putStr("flips: ") + print $ length $ filter id $ take 100000 (zipWith (>) q (tail q)) diff --git a/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-6.hs b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-6.hs new file mode 100644 index 0000000000..d7722cbb4d --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Haskell/hofstadter-q-sequence-6.hs @@ -0,0 +1,21 @@ +import Data.Array +import Data.Int (Int64) + +q = qq [listArray (1,2) [1,1]] 1 where + qq a n = seek aa n : qq aa (1 + n) where + aa | n <= l = a + | otherwise = listArray (l+1,l*2) (take l $ drop 2 lst):a + where + l = snd (bounds $ head a) + lst = seek a (l-1):seek a l:(ext lst (l+1)) + ext (q1:q2:qs) i = (g (i-q2) + g (i-q1)):ext (q2:qs) (1+i) + g = seek aa + seek (ar:ars) n + | n >= fst (bounds ar) = ar ! n + | otherwise = seek ars n + +-- Only a perf test. Task can be done exactly the same as above +main = print $ sum qqq + where + qqq :: [Int64] + qqq = map fromIntegral $ take 3000000 q diff --git a/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence.kts b/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence-1.kts similarity index 100% rename from Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence.kts rename to Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence-1.kts diff --git a/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence-2.kts b/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence-2.kts new file mode 100644 index 0000000000..ac07d6cc8e --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Kotlin/hofstadter-q-sequence-2.kts @@ -0,0 +1,24 @@ +fun Q(n: Int): List { + val mem = mutableMapOf().also { + it[1] = 1 + it[2] = 1 + } + q(n, mem) + return mem.values.toList() +} + +private fun q(n: Int, mem: MutableMap): Int { + if (!mem.containsKey(n)) { + mem[n] = + q(n - q(n - 1, mem), mem) + q(n - q(n - 2, mem), mem) + } + return mem[n]!! +} + +fun main() { + val n = 1000 + Q(n).also { qList -> + println("Q[1..10] = ${qList.take(10)}") + println("Q($n) = ${qList[1000 - 1]}") // 502 + } +} diff --git a/Task/Hofstadter-Q-sequence/PascalABC.NET/hofstadter-q-sequence.pas b/Task/Hofstadter-Q-sequence/PascalABC.NET/hofstadter-q-sequence.pas new file mode 100644 index 0000000000..6c1be48d54 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/PascalABC.NET/hofstadter-q-sequence.pas @@ -0,0 +1,16 @@ +## +var q := |1, 1|.ToList; +for var n := 2 to 100_000 do + q.add(q[n - q[n - 1]] + q[n - q[n - 2]]); + +q.take(10).println; +assert(q.Take(10).SequenceEqual(|1, 1, 2, 3, 3, 4, 5, 5, 6, 6|)); + +q[999].println; +assert(q[999] = 502); + +var lessCount := 0; +for var n := 1 to 100_000 do + if q[n] < q[n - 1] then + lessCount += 1; +lessCount.Println; diff --git a/Task/Honeycombs/Nim/honeycombs.nim b/Task/Honeycombs/Nim/honeycombs.nim index 0069221f0f..8a8f5cbdab 100644 --- a/Task/Honeycombs/Nim/honeycombs.nim +++ b/Task/Honeycombs/Nim/honeycombs.nim @@ -1,7 +1,23 @@ -import lenientops, math, random, sequtils, strutils, tables +import std/[lenientops, math, random, sequtils, strutils, tables] -import gintro/[gobject, gdk, gtk, gio, cairo] -import gintro/glib except PI +import gtk2, gdk2, glib2, cairo + + +############################################################################### +# Missing gtk2 definition. + +when defined(win32): + const lib = "libgtk-win32-2.0-0.dll" +elif defined(macosx): + const lib = "(libgtk-quartz-2.0.0.dylib|libgtk-x11-2.0.dylib)" +else: + const lib = "libgtk-x11-2.0.so(|.0)" + +proc setCanFocus(widget: PWidget; canFocus: bool) {.cdecl, + importc: "gtk_widget_set_can_focus", dynlib: lib.} + + +############################################################################### const Size = 308 # Size of drawing area. @@ -12,44 +28,36 @@ const type - Letter = range['A'..'Z'] - # Description of a hexagon. Hexagon = object cx, cy: float - letter: Letter + letter: char selected: bool # Description of the honeycomb. - HoneyComb = ref object + HoneyComb = object hexagons: array[NHexagons, Hexagon] # List of hexagons. - indexes: tables.Table[char, int] # Mapping letter -> index of hexagon. - archive: seq[Letter] # List of selected letters. - label: Label # Label displaying the selected letters. + indexes: Table[char, int] # Mapping letter -> index of hexagon. + archive: seq[char] # List of selected letters. + label: PLabel # Label displaying the selected letters. -#--------------------------------------------------------------------------------------------------- -proc newHoneyComb(): HoneyComb = +proc initHoneyComb(): HoneyComb = ## Create a honeycomb. - - new(result) var letters = toSeq('A'..'Z') letters.shuffle() - for i in 0.. "; -30 INPUT LAT -40 PRINT "Enter longitude => "; -50 INPUT LNG -60 PRINT "Enter legal meridian => "; -70 INPUT REF -80 PRINT -90 LET PI = 4 * ATN(1) -100 LET SLAT = SIN(LAT * PI / 180) -110 PRINT " sine of latitude: "; USING "#.##^^^^"; SLAT -120 PRINT " diff longitude: "; USING "####.###"; LNG - REF -130 PRINT -140 PRINT "Hour, sun hour angle, dial hour line angle from 6am to 6pm" -150 FOR H% = -6 TO 6 -160 LET HRA = 15 * H% -170 LET HRA = HRA - (LNG - REF): ' correct for longitude difference -180 LET HLA = ATN(SLAT * TAN(HRA * PI / 180)) * 180 / PI -190 PRINT "HR="; USING "+##"; H%; -200 PRINT "; HRA="; USING "+###.###"; HRA; -210 PRINT "; HLA="; USING "+###.###"; HLA -220 NEXT H% -230 END +10 ' Horizontal sundial calculations +20 INPUT "Enter latitude => "; LAT +30 INPUT "Enter longitude => "; LNG +40 INPUT "Enter legal meridian => "; REF +50 PRINT +60 LET PI = 4 * ATN(1) +70 LET SLAT = SIN(LAT * PI / 180) +80 PRINT " sine of latitude: "; USING "#.##^^^^"; SLAT +90 PRINT " diff longitude: "; USING "####.###"; LNG - REF +100 PRINT +110 PRINT "Hour, sun hour angle, dial hour line angle from 6am to 6pm" +120 FOR H% = -6 TO 6 +130 LET HRA = 15 * H% +140 LET HRA = HRA - (LNG - REF) ' correct for longitude difference +150 LET HLA = ATN(SLAT * TAN(HRA * PI / 180)) * 180 / PI +160 PRINT "HR="; USING "+##"; H%; +170 PRINT "; HRA="; USING "+###.###"; HRA; +180 PRINT "; HLA="; USING "+###.###"; HLA +190 NEXT H% +200 END diff --git a/Task/Horizontal-sundial-calculations/JavaScript/horizontal-sundial-calculations-1.js b/Task/Horizontal-sundial-calculations/JavaScript/horizontal-sundial-calculations-1.js new file mode 100644 index 0000000000..bf19679c98 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/JavaScript/horizontal-sundial-calculations-1.js @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Task/Horizontal-sundial-calculations/JavaScript/horizontal-sundial-calculations-2.js b/Task/Horizontal-sundial-calculations/JavaScript/horizontal-sundial-calculations-2.js new file mode 100644 index 0000000000..364a0571bc --- /dev/null +++ b/Task/Horizontal-sundial-calculations/JavaScript/horizontal-sundial-calculations-2.js @@ -0,0 +1,41 @@ +// Horizontal sundial calculations + +function deg2rad(d) { + return d * Math.PI / 180; +} + +function rad2deg(r) { + return r / Math.PI * 180; +} + +document.write(""); +lat = prompt("Enter latitude"); +document.write("

Latitude: ", lat); +lng = prompt("Enter longitude"); +document.write("
Longitude: ", lng); +ref = prompt("Enter legal meridian"); +document.write("
Legal meridian: ", ref); +document.write("

"); +sLat = Math.sin(deg2rad(lat)); +document.write("

Sine of latitude: ", sLat.toFixed(5)); +document.write("
Diff longitude: ", (lng - ref).toFixed(5)); +document.write("

"); +document.write(""); +document.write(""); +document.write(""); +document.write(""); +document.write(""); +document.write("", + ""); +for (hour = -6; hour <= 6; hour++) { + hourAngle = 15 * hour - (lng - ref); + hourLineAngle = rad2deg(Math.atan(sLat * Math.tan(deg2rad(hourAngle)))); + document.write(""); + document.write(""); + document.write(""); + document.write(""); +} +document.write("
TimeSun hour angleDial hour line angle
", (hour + 12).toFixed(), ":00", hourAngle.toFixed(5), + "", hourLineAngle.toFixed(5), + "
"); +document.write("
"); diff --git a/Task/Horizontal-sundial-calculations/PHP/horizontal-sundial-calculations.php b/Task/Horizontal-sundial-calculations/PHP/horizontal-sundial-calculations.php new file mode 100644 index 0000000000..d474be2cb0 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/PHP/horizontal-sundial-calculations.php @@ -0,0 +1,28 @@ + '); +$lng = (float)readline('Enter longitude => '); +$ref = (float)readline('Enter legal meridian => '); +echo PHP_EOL; +$s_lat = sin(deg2rad($lat)); +echo ' sine of latitude: '.$s_lat.PHP_EOL; +echo ' diff longitude: '.($lng - $ref).PHP_EOL; +echo PHP_EOL; +echo 'Hour, sun hour angle, dial hour line angle from 6am to 6pm'.PHP_EOL; +for ($hour = -6; $hour <= 6; $hour++) { + $hour_angle = 15 * $hour; + $hour_angle = $hour_angle - ($lng - $ref); // correct for longitude difference + $hour_line_angle = rad2deg(atan($s_lat * tan(deg2rad($hour_angle)))); + echo 'HR='.dec_format($hour, 3, 0); + echo '; HRA='.dec_format($hour_angle, 8, 3); + echo '; HLA='.dec_format($hour_line_angle, 8, 3).PHP_EOL; +} +?> diff --git a/Task/Horizontal-sundial-calculations/PascalABC.NET/horizontal-sundial-calculations.pas b/Task/Horizontal-sundial-calculations/PascalABC.NET/horizontal-sundial-calculations.pas new file mode 100644 index 0000000000..8d18e7e8fa --- /dev/null +++ b/Task/Horizontal-sundial-calculations/PascalABC.NET/horizontal-sundial-calculations.pas @@ -0,0 +1,18 @@ +## +var lat := readlnreal('Enter latitude => '); +var lng := readlnreal('Enter longitude => '); +var med := readlnreal('Enter legal meridian => '); +println; + +var slat := sin(degToRad(lat)); +writeln(' sine of latitude: ', slat:5:3); +writeln(' diff longitude: ', lng - med:5:3); +println; +println('Hour, sun hour angle, dial hour line angle from 6am to 6pm'); + +for var h := -6 to 6 do +begin + var hra := 15 * h - lng + med; + var hla := radtodeg(arctan(slat * tan(degToRad(hra)))); + writeln('HR=', h:2, '; HRA=', hra:8:3, '; HLA=', hla:8:3); +end; diff --git a/Task/Horizontal-sundial-calculations/QBasic/horizontal-sundial-calculations.basic b/Task/Horizontal-sundial-calculations/QBasic/horizontal-sundial-calculations.basic new file mode 100644 index 0000000000..4822cf3a5c --- /dev/null +++ b/Task/Horizontal-sundial-calculations/QBasic/horizontal-sundial-calculations.basic @@ -0,0 +1,20 @@ +' Horizontal sundial calculations +INPUT "Enter latitude => "; Lat +INPUT "Enter longitude => "; Lng +INPUT "Enter legal meridian => "; Ref +PRINT +PI = 4 * ATN(1) +SLat = SIN(Lat * PI / 180) +PRINT " sine of latitude: "; USING "#.##^^^^"; SLat +PRINT " diff longitude: "; USING "####.###"; Lng - Ref +PRINT +PRINT "Hour, sun hour angle, dial hour line angle from 6am to 6pm" +FOR Hour% = -6 TO 6 + HourAngle = 15 * Hour% + HourAngle = HourAngle - (Lng - Ref): ' correct for longitude difference + HourLineAngle = ATN(SLat * TAN(HourAngle * PI / 180)) * 180 / PI + PRINT "HR="; USING "+##"; Hour%; + PRINT "; HRA="; USING "+###.###"; HourAngle; + PRINT "; HLA="; USING "+###.###"; HourLineAngle +NEXT Hour% +END diff --git a/Task/Horners-rule-for-polynomial-evaluation/Draco/horners-rule-for-polynomial-evaluation.draco b/Task/Horners-rule-for-polynomial-evaluation/Draco/horners-rule-for-polynomial-evaluation.draco new file mode 100644 index 0000000000..80ba616670 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Draco/horners-rule-for-polynomial-evaluation.draco @@ -0,0 +1,14 @@ +proc horner([*]int coeff; int x) int: + int acc; + word i; + acc := 0; + for i from dim(coeff,1)-1 downto 0 do + acc := acc * x + coeff[i] + od; + acc +corp + +proc main() void: + [4]int coeff = (-19, 7, -4, 6); + writeln(horner(coeff, 3)) +corp diff --git a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx index aa5cab3ea2..e565529a4c 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx +++ b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx @@ -1,19 +1,45 @@ -/*REXX program demonstrates using Horner's rule for polynomial evaluation. */ -numeric digits 30 /*use extra numeric precision. */ -parse arg x poly /*get value of X and the coefficients. */ -$= /*start with a clean slate equation. */ - do deg=0 until poly=='' /*get the equation's coefficients. */ - parse var poly c.deg poly; c.deg=c.deg/1 /*get equation coefficient & normalize.*/ - if c.deg>=0 then c.deg= '+'c.deg /*if ¬ negative, then prefix with a + */ - $=$ c.deg /*concatenate it to the equation. */ - if deg\==0 & c.deg\=0 then $=$'∙x^'deg /*¬1st coefficient & ¬0? Append X pow.*/ - $=$ ' ' /*insert some blanks, make it look nice*/ - end /*deg*/ -say ' x = ' x -say ' degree = ' deg -say ' equation = ' $ -a=c.deg /*A: is the accumulator (or answer). */ - do j=deg-1 by -1 for deg; a=a*x+c.j /*apply Horner's rule to the equations.*/ - end /*j*/ -say /*display a blank line for readability.*/ -say ' answer = ' a /*stick a fork in it, we're all done. */ +/* REXX --------------------------------------------------------------- +* 27.07.2012 Walter Pachl +* coefficients reversed to descending order of power +* I'm used to x**2+x-3 +* equation formatting prettified (coefficients 1 and 0) +*--------------------------------------------------------------------*/ + Numeric Digits 30 /* use extra numeric precision. */ + Parse Arg x poly /* get value of x and coefficients*/ + rpoly='' + Do p=0 To words(poly)-1 + rpoly=rpoly word(poly,words(poly)-p) + End + poly=rpoly + equ='' /* start with equation clean slate*/ + deg=words(poly)-1 + pdeg=deg + Do Until deg<0 /* get the equation's coefficients*/ + Parse Var poly c.deg poly /* in descending order of powers */ + c.deg=c.deg+0 /* normalize it */ + If c.deg>0 & deg0 Then /* build up the equation */ + equ=equ||prefix||term + deg=deg-1 + End + a=c.pdeg + Do p=pdeg To 1 By -1 /* apply Horner's rule. */ + pm1=p-1 + a=a*x+c.pm1 + End + Say ' x = ' x + Say ' degree = ' pdeg + Say ' equation = ' equ + Say ' ' + Say ' result = ' a diff --git a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx index e565529a4c..b74d9bd5cb 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx +++ b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx @@ -1,45 +1,18 @@ -/* REXX --------------------------------------------------------------- -* 27.07.2012 Walter Pachl -* coefficients reversed to descending order of power -* I'm used to x**2+x-3 -* equation formatting prettified (coefficients 1 and 0) -*--------------------------------------------------------------------*/ - Numeric Digits 30 /* use extra numeric precision. */ - Parse Arg x poly /* get value of x and coefficients*/ - rpoly='' - Do p=0 To words(poly)-1 - rpoly=rpoly word(poly,words(poly)-p) - End - poly=rpoly - equ='' /* start with equation clean slate*/ - deg=words(poly)-1 - pdeg=deg - Do Until deg<0 /* get the equation's coefficients*/ - Parse Var poly c.deg poly /* in descending order of powers */ - c.deg=c.deg+0 /* normalize it */ - If c.deg>0 & deg0 Then /* build up the equation */ - equ=equ||prefix||term - deg=deg-1 - End - a=c.pdeg - Do p=pdeg To 1 By -1 /* apply Horner's rule. */ - pm1=p-1 - a=a*x+c.pm1 - End - Say ' x = ' x - Say ' degree = ' pdeg - Say ' equation = ' equ - Say ' ' - Say ' result = ' a +include Settings +say version; say 'Polynomial Horner''s rule'; say +call Evaluate '6 -4 7 -19',3 +call Evaluate '2',4 +call Evaluate '2 3',0 +call Evaluate '2 0 -3 0 4',5 +call Evaluate '1 2 3',Pi()+0 +exit + +Evaluate: +arg x,y +say Plst2form(x) '| x='y '=' Peval(x,y)+0 +return + +include Polynomial +include Functions +include Constants +include Abend diff --git a/Task/Horners-rule-for-polynomial-evaluation/Raku/horners-rule-for-polynomial-evaluation-2.raku b/Task/Horners-rule-for-polynomial-evaluation/Raku/horners-rule-for-polynomial-evaluation-2.raku index 17455ac1da..127c4def49 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Raku/horners-rule-for-polynomial-evaluation-2.raku +++ b/Task/Horners-rule-for-polynomial-evaluation/Raku/horners-rule-for-polynomial-evaluation-2.raku @@ -1,6 +1,5 @@ -multi horner(Numeric $c, $) { $c } -multi horner(Pair $c, $x) { - $c.key + $x * horner( $c.value, $x ) +multi horner(@c, $x) { + @c > 1 ?? @c.head + $x * samewith(@c.tail(*-1), $x) !! @c.pick } -say horner( [=>](-19, 7, -4, 6 ), 3 ); +say horner( [-19, 7, -4, 6 ], 3 ); diff --git a/Task/Horners-rule-for-polynomial-evaluation/Refal/horners-rule-for-polynomial-evaluation.refal b/Task/Horners-rule-for-polynomial-evaluation/Refal/horners-rule-for-polynomial-evaluation.refal new file mode 100644 index 0000000000..ca072c16c4 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Refal/horners-rule-for-polynomial-evaluation.refal @@ -0,0 +1,8 @@ +$ENTRY Go { + = >; +}; + +Horner { + (e.X) = 0; + (e.X) (e.C) e.Cs = >>; +}; diff --git a/Task/Horners-rule-for-polynomial-evaluation/SETL/horners-rule-for-polynomial-evaluation.setl b/Task/Horners-rule-for-polynomial-evaluation/SETL/horners-rule-for-polynomial-evaluation.setl new file mode 100644 index 0000000000..abfc1e59e0 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/SETL/horners-rule-for-polynomial-evaluation.setl @@ -0,0 +1,11 @@ +program horners_rule; + print(horner([-19, 7, -4, 6], 3)); + + proc horner(coeff, x); + acc := 0; + loop for i in [#coeff, #coeff-1 .. 1] do + acc := acc * x + coeff(i); + end loop; + return acc; + end proc; +end program; diff --git a/Task/Horners-rule-for-polynomial-evaluation/UNIX-Shell/horners-rule-for-polynomial-evaluation.sh b/Task/Horners-rule-for-polynomial-evaluation/UNIX-Shell/horners-rule-for-polynomial-evaluation.sh new file mode 100644 index 0000000000..6650b786a9 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/UNIX-Shell/horners-rule-for-polynomial-evaluation.sh @@ -0,0 +1,13 @@ +horner() + if + local -i x=$1 + shift + (($#)) + then + local -i y=$1 + shift + echo $((y + x*$( horner $x "$@") )) + else echo 0 + fi + +horner 3 -19 7 -4 6 diff --git a/Task/Host-introspection/Wren/host-introspection-3.wren b/Task/Host-introspection/Wren/host-introspection-3.wren new file mode 100644 index 0000000000..4ee1fae58c --- /dev/null +++ b/Task/Host-introspection/Wren/host-introspection-3.wren @@ -0,0 +1,6 @@ +import "os" for Process + +var wordSize = Process.read("getconf LONG_BIT") +var endianness = Process.read("lscpu | grep \"Byte Order\"").split(":")[1].trimStart() +System.print("word size = %(wordSize) bits") +System.print("endianness = %(endianness)") diff --git a/Task/Hostname/Wren/hostname-1.wren b/Task/Hostname/Wren/hostname-1.wren deleted file mode 100644 index ef379c81bb..0000000000 --- a/Task/Hostname/Wren/hostname-1.wren +++ /dev/null @@ -1,6 +0,0 @@ -/* Hostname.wren */ -class Host { - foreign static name() // the code for this is provided by Go -} - -System.print(Host.name()) diff --git a/Task/Hostname/Wren/hostname-2.wren b/Task/Hostname/Wren/hostname-2.wren deleted file mode 100644 index 4227ab6330..0000000000 --- a/Task/Hostname/Wren/hostname-2.wren +++ /dev/null @@ -1,25 +0,0 @@ -/* Hostname.go */ -package main - -import ( - wren "github.com/crazyinfin8/WrenGo" - "os" -) - -type any = interface{} - -func hostname(vm *wren.VM, parameters []any) (any, error) { - name, _ := os.Hostname() - return name, nil -} - -func main() { - vm := wren.NewVM() - fileName := "Hostname.wren" - methodMap := wren.MethodMap{"static name()": hostname} - classMap := wren.ClassMap{"Host": wren.NewClass(nil, nil, methodMap)} - module := wren.NewModule(classMap) - vm.SetModule(fileName, module) - vm.InterpretFile(fileName) - vm.Free() -} diff --git a/Task/Hostname/Wren/hostname.wren b/Task/Hostname/Wren/hostname.wren new file mode 100644 index 0000000000..6a4cad7d44 --- /dev/null +++ b/Task/Hostname/Wren/hostname.wren @@ -0,0 +1,3 @@ +import "os" for Platform + +System.print(Platform.hostName) diff --git a/Task/Humble-numbers/PascalABC.NET/humble-numbers.pas b/Task/Humble-numbers/PascalABC.NET/humble-numbers.pas new file mode 100644 index 0000000000..4ea1f2542b --- /dev/null +++ b/Task/Humble-numbers/PascalABC.NET/humble-numbers.pas @@ -0,0 +1,25 @@ +## +function humbles: sequence of uint64; +begin + var s := hset(uint64(1)); + while True do + begin + var m := s.min; + yield m; + s -= m; + foreach var k in |2, 3, 5, 7| do s += k * m; + end; +end; + +println('The first 50 humble numbers are:'); +foreach var n in humbles.Take(50) index i do + write(n:4, if i mod 10 = 9 then #10 else ''); + +println; +println('Digits Count'); +for var dig := 1 to 18 do +begin + var count := humbles.SkipWhile(x -> x < 10 ** (dig - 1)) + .TakeWhile(x -> x < 10 ** dig).Count; + writeln(dig:2, count:10); +end; diff --git a/Task/Hunt-the-Wumpus/FutureBasic/hunt-the-wumpus.basic b/Task/Hunt-the-Wumpus/FutureBasic/hunt-the-wumpus.basic new file mode 100644 index 0000000000..714df4ab49 --- /dev/null +++ b/Task/Hunt-the-Wumpus/FutureBasic/hunt-the-wumpus.basic @@ -0,0 +1,229 @@ +// Hunt the Wumpus +// https://rosettacode.org/wiki/Hunt_the_Wumpus# + + +_w = 640 // window size width and height +_h = 400 +_window = 1 + +local fn BuildWindow + + CGRect r = fn cgrectmake(0,0,_w,_h) + window _Window, @"Hunt the Wumpus", r, NSWindowStyleMaskTitled + NSWindowStyleMaskMiniaturizable + windowcenter(_Window) + WindowSetBackgroundColor(_Window,fn ColorBlack) + WindowPrintViewSetTextInset( _window, 20) + + text ,14,fn colorWhite + +end fn + + +fn BuildWindow + + +//////////// Main Program ////////////// + +"Start" + +cls:restore + +data 7,13,19,12,18,20,16,17,19,11,14,18,13,15,18,9,14,16,1,15,17,10,16,20,6,11,19,8,12,17 +data 4,9,13,2,10,15,1,5,11,4,6,20,5,7,12,3,6,8,3,7,10,2,4,5,1,3,9,2,8,14 +data 1,2,3,1,3,2,2,1,3,2,3,1,3,1,2,3,2,1 + +uint32 i, j,tunnel(21,4),lost(7,4),targ,wump,player,bat1, bat2, pit1, pit2, d6, epi +player = int(rnd(20)) +uint32 arrows = 5 +CFStringRef choice + +for i = 1 to 20 //set up rooms + for j = 1 to 3 + read tunnel(i,j) + next j +next i + +for i = 1 to 6 //set up list of permuatations of 1-2-3 + for j = 1 to 3 + read lost(i,j) + next j +next i + + +//place wumpus, bats, and pits +do + wump = int(rnd(20)) +until wump <> player +do + pit1 = int(rnd(20)) +until pit1 <> player +do + pit2 = int(rnd(20)) +until pit2 <> player && pit2 <> pit1 +do + bat1 = int(rnd(20)) +until bat1 <> player && bat1 <> pit1 && bat1 <> pit2 +do + bat2 = int(rnd(20)) +until bat2 <> player && bat2 <> pit1 && bat2 <> pit2 && bat2 <> bat1 + +do + if player = wump + text ,,fn colorRed + print "You have been eaten by the Wumpus!" + Print: WindowPrintViewScrollToBottom( _window ) + goto "defeat" + end if + if player = pit1 || player = pit2 + text ,,fn colorRed + print "Aaaaaaaaaaa! You have fallen into a bottomless pit." + Print: WindowPrintViewScrollToBottom( _window ) + goto "defeat" + end if + if player = bat1 || player = bat2 + text ,,fn colorOrange + print "A bat has carried you into another empty room." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + do + player = (rnd(20)) + until player <> wump && player <> pit1 && player <> pit2 && player <> bat1 && player <> bat2 + end if + + print + text ,,fn colorGreen + print "You are in room number" + str$(player) + ". There are tunnels to rooms"¬ + + str$(tunnel(player,1)) + "," str$(tunnel(player,2)) + " and" +str$(tunnel(player,3)) + if (tunnel(player,1)) + (tunnel(player,2)) + (tunnel(player,3)) = 0 then arrows = 5 : goto "Start" + text ,,fn colorYellow + print "You have" + str$(arrows) + " arrows left." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + + d6 = int(rnd(6)) + for i = 1 to 3 + epi = tunnel(player,lost(d6,i)) + if epi = wump + text ,,fn colorRed + print "You smell something terrible nearby." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end if + if epi = bat1 || epi = bat2 + text ,,fn colorRed + print "You hear a rustling." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end if + if epi = pit1 || epi = pit2 + print "You feel a cold wind blowing from a nearby cavern." + Print: WindowPrintViewScrollToBottom( _window ) + end if + next i + "choices" + print + print "What would you like to do?" + Print: WindowPrintViewScrollToBottom( _window ) + + choice = input %(_w/2 - 260 , _h + 20),@"Type A to shoot an arrow, or a number to move to another room. ( or Q to quit )" + + select case left(choice,1) + + case @"q", @"Q" , @"x" , @"X" + end + + case @"a", @"A" + + CFStringRef targString + targString = input %(_w/2 - 140 , _h + 20), @"Which room would you like to shoot into? " + targ = fn StringIntegerValue(targString) + + print "You shot an arrow into room " + str$(targ) + + if targ = player + text ,,fn colorRed + print "You shot yourself. Why would you want to do such a thing?" + Print: WindowPrintViewScrollToBottom( _window ) + goto "defeat" + end if + + text ,,fn colorGreen + if targ = wump then goto "victory" + + if targ = tunnel(player,1) || targ = tunnel(player,2) || targ = tunnel(player,3) + text ,,fn colorYellow + print "The Wumpus awakes!" + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + if rnd(100) <= 75 + print "He moves to a nearby cavern." + Print: WindowPrintViewScrollToBottom( _window ) + short wumpRnd + wumpRnd = Int(Rnd(3)) + wump = Tunnel(wump,wumpRnd) + else + print "He goes back to sleep." + Print: WindowPrintViewScrollToBottom( _window ) + end if + else + text ,,fn colorRed + print "You can't shoot that room from here." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + goto "choices" + end if + arrows -= 1 + + case @"0", @"1" ,@"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9" + + targ = fn StringIntegerValue(choice) + if targ = player then print "You are already there." + + if targ = tunnel(player,1) || targ = tunnel(player,2) || targ = tunnel(player,3) + print using "You walk to room ##"; targ + player = targ + else + text ,,fn colorOrange + print "You can't get there from here." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end if + case else + text ,,fn colorRed + print "You are making no sense." + text ,,fn colorWhite + Print: WindowPrintViewScrollToBottom( _window ) + end select +until arrows = 0 +text ,,fn colorRed +print "You have run out of arrows!" +Print: WindowPrintViewScrollToBottom( _window ) +"defeat" +text ,,fn colorRed +print "You lose! Better luck next time." +Print: WindowPrintViewScrollToBottom( _window ) + +goto "End" + +"victory" +text ,20,fn colorGreen +print "You have slain the Wumpus!" +print "You won!" +Print: WindowPrintViewScrollToBottom( _window ) + +"End" + +text ,14,fn colorWhite +choice = input %(_w/2 -140 , _h + 20),@"Hit Return for another. ( or Q to quit )" + +select case left(choice,1) + + case @"q", @"Q" , @"x" , @"X" + end + + case else arrows = 5: goto "Start" + +end select + + +handleevents diff --git a/Task/I-before-E-except-after-C/BQN/i-before-e-except-after-c.bqn b/Task/I-before-E-except-after-C/BQN/i-before-e-except-after-c.bqn new file mode 100644 index 0000000000..dbbec600b8 --- /dev/null +++ b/Task/I-before-E-except-after-C/BQN/i-before-e-except-after-c.bqn @@ -0,0 +1,15 @@ +Func ← { + Filter ← {+´(∨´∘(𝕨⊸⍷))¨𝕩} + nei ← "ei" Filter 𝕩 + cei ← "cei" Filter 𝕩 + nie ← "ie" Filter 𝕩 + cie ← "cie" Filter 𝕩 + •Show (nie < 2×cie)◶⟨ + "I before E when not preceded by C is plausible" + "I before E when not preceded by C is not plausible" + ⟩@ + (nei > 2×cei)◶⟨ + "E before I when preceded by C is plausible" + "E before I when preceded by C is not plausible" + ⟩@ +} diff --git a/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur b/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur index 5b64809d01..4b8c215e68 100644 --- a/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur +++ b/Task/I-before-E-except-after-C/Langur/i-before-e-except-after-c.langur @@ -1,4 +1,4 @@ -val words = split("\n", readfile("./data/unixdict.txt")) -> rest +val words = less(split(readfile("./data/unixdict.txt"), by="\n"), of=1) val print = fn*(support, against) { val ratio = support / against diff --git a/Task/IBAN/ALGOL-68/iban.alg b/Task/IBAN/ALGOL-68/iban.alg new file mode 100644 index 0000000000..93dc56bbc2 --- /dev/null +++ b/Task/IBAN/ALGOL-68/iban.alg @@ -0,0 +1,104 @@ +BEGIN # validate IBAN numbers # + + # country code and expected bank account length for IBAN codes # + MODE IBANCOUNTRY = STRUCT( [ 1 : 2 ]CHAR code, INT length ); + + []IBANCOUNTRY country info = + ( ("AL",28), ("AD",24), ("AT",20), ("AZ",28), ("BE",16), ("BH",22), ("BA",20), ("BR",29) + , ("BG",22), ("CR",21), ("HR",21), ("CY",28), ("CZ",24), ("DK",18), ("DO",28), ("EE",20) + , ("FO",18), ("FI",18), ("FR",27), ("GE",22), ("DE",22), ("GI",23), ("GR",27), ("GL",18) + , ("GT",28), ("HU",28), ("IS",26), ("IE",22), ("IL",23), ("IT",27), ("KZ",20), ("KW",30) + , ("LV",21), ("LB",28), ("LI",21), ("LT",20), ("LU",20), ("MK",19), ("MT",31), ("MR",27) + , ("MU",30), ("MC",27), ("MD",24), ("ME",22), ("NL",18), ("NO",15), ("PK",24), ("PS",29) + , ("PL",28), ("PT",25), ("RO",24), ("SM",27), ("SA",24), ("RS",22), ("SK",24), ("SI",19) + , ("ES",24), ("SE",24), ("CH",21), ("TN",24), ("TR",26), ("AE",23), ("GB",22), ("VG",24) + ); + + # returns "" if s could be a valid IBAN, an error message otherwise # + OP POSSIBLEIBAN = ( STRING s )STRING: + BEGIN + BOOL is valid := TRUE; + STRING result := ""; + # remove spaces and check we only have digits and spaces # + STRING iban := ""; + FOR s pos FROM LWB s TO UPB s WHILE is valid DO + CHAR c = s[ s pos ]; + IF c /= " " THEN + IF NOT ( is valid := ( c >= "A" AND c <= "Z" ) OR ( c >= "0" AND c <= "9" ) ) + THEN result := "Invalid character: " + c + FI; + iban +:= c + FI + OD; + IF is valid THEN + # OK so far - check the length matches the country code # + INT supplied length = ( UPB iban - LWB iban ) + 1; + is valid := FALSE; + IF supplied length <= 4 + THEN result := "Code is too short" + ELSE # enough characters for a country code and a check sum # + INT expected length := -1; + STRING supplied country = iban[ LWB iban : LWB iban + 1 ]; + FOR c pos FROM LWB country info TO UPB country info WHILE NOT is valid DO + IF is valid := code OF country info[ c pos ] = supplied country THEN + expected length := length OF country info[ c pos ] + FI + OD; + IF NOT is valid + THEN result := "Not a known IBAN country: " + supplied country + ELIF NOT ( is valid := expected length = supplied length ) + THEN result := "Expected code length: " + whole( expected length, 0 ) + + " but actual length is: " + whole( supplied length, 0 ) + ELSE # OK so far - check the checksum # + STRING rearranged iban = iban[ LWB iban + 4 : ] + iban[ LWB iban : LWB iban + 3 ]; + LONG LONG INT numeric iban := 0; + FOR c pos FROM LWB rearranged iban TO UPB rearranged iban DO + CHAR c = rearranged iban[ c pos ]; + IF c >= "0" AND c <= "9" THEN + numeric iban *:= 10 +:= ( ABS c - ABS "0" ) + ELSE + numeric iban *:= 100 +:= ( ABS c - ABS "A" ) + 10 + FI + OD; + IF NOT ( is valid := numeric iban MOD 97 = 1 ) + THEN result := "Incorrect checksum" + FI + FI + FI + FI; + IF is valid THEN "" ELIF result = "" THEN "Unknown error" ELSE result FI + END # POSSIBLEIBAN # ; + + BEGIN # tests # + []STRING valid codes = ( "GB82 WEST 1234 5698 7654 32", "GB82WEST12345698765432" + , "GR16 0110 1250 0000 0001 2300 695", "GB29 NWBK 6016 1331 9268 19" + , "SA03 8000 0000 6080 1016 7519", "CH93 0076 2011 6238 5295 7" + , "IL62 0108 0000 0009 9999 999" + ); + []STRING invalid codes = ( "gb82 west 1234 5698 7654 32" # invalid characters # + , "GB82 TEST 1234 5698 7654 32" # invalid check digits # + , "IL62-0108-0000-0009-9999-999" # invalid characters # + , "US12 3456 7890 0987 6543 210" # invalid country code # + , "GR16 0110 1250 0000 0001 2300 695X" # invalid code length # + , "" # code is too short # + , "G2" # code is too short # + , "GB271" # invalid code length # + ); + FOR t pos FROM LWB valid codes TO UPB valid codes DO + STRING code = valid codes[ t pos ]; + STRING message = POSSIBLEIBAN code; + IF message = "" + THEN print( ( "Possible IBAN: ", code, newline ) ) + ELSE print( ( "INVALID IBAN: ", code, ": UNEXPECTED ERROR: ", message, newline ) ) + FI + OD; + FOR t pos FROM LWB invalid codes TO UPB invalid codes DO + STRING code = invalid codes[ t pos ]; + STRING message = POSSIBLEIBAN code; + IF message = "" + THEN print( ( "POSSIBLE IBAN: ", code, " BUT EXPECTED AN ERROR MESSAGE", newline ) ) + ELSE print( ( "Invalid IBAN: ", code, ": ", message, newline ) ) + FI + OD + END +END diff --git a/Task/IBAN/PascalABC.NET/iban.pas b/Task/IBAN/PascalABC.NET/iban.pas new file mode 100644 index 0000000000..ad59a4e740 --- /dev/null +++ b/Task/IBAN/PascalABC.NET/iban.pas @@ -0,0 +1,33 @@ +var + countryLen := Dict( + ('AL', 28), ('AD', 24), ('AT', 20), ('AZ', 28), ('BE', 16), ('BH', 22), ('BA', 20), ('BR', 29), + ('BG', 22), ('CR', 21), ('HR', 21), ('CY', 28), ('CZ', 24), ('DK', 18), ('DO', 28), ('EE', 20), + ('FO', 18), ('FI', 18), ('FR', 27), ('GE', 22), ('DE', 22), ('GI', 23), ('GR', 27), ('GL', 18), + ('GT', 28), ('HU', 28), ('IS', 26), ('IE', 22), ('IL', 23), ('IT', 27), ('KZ', 20), ('KW', 30), + ('LV', 21), ('LB', 28), ('LI', 21), ('LT', 20), ('LU', 20), ('MK', 19), ('MT', 31), ('MR', 27), + ('MU', 30), ('MC', 27), ('MD', 24), ('ME', 22), ('NL', 18), ('NO', 15), ('PK', 24), ('PS', 29), + ('PL', 28), ('PT', 25), ('RO', 24), ('SM', 27), ('SA', 24), ('RS', 22), ('SK', 24), ('SI', 19), + ('ES', 24), ('SE', 24), ('CH', 21), ('TN', 24), ('TR', 26), ('AE', 23), ('GB', 22), ('VG', 24)); + +function validIban(iban: string): boolean; +begin + result := False; + iban := iban.Replace(' ', '').Replace(#9, ''); + if not iban.All(c -> c.isupper or c.isdigit) then exit; + + if iban.Length <> countryLen.Get(iban[1:3]) then exit; + + iban := iban[5:iban.Length + 1] + iban[1:5]; + var digits: string := ''; + foreach var ch in iban do + case ch of + '0'..'9': digits += ch; + 'A'..'Z': digits += (Ord(ch) - Ord('A') + 10).ToString; + end; + result := digits.ToBigInteger mod 97 = 1; +end; + +begin + foreach var account in |'GB82 WEST 1234 5698 7654 32', 'GB82 TEST 1234 5698 7654 32'| do + Println(account, 'validation is:', validIban(account)); +end. diff --git a/Task/ISBN13-check-digit/JavaScript/isbn13-check-digit.js b/Task/ISBN13-check-digit/JavaScript/isbn13-check-digit.js new file mode 100644 index 0000000000..0d39e85b78 --- /dev/null +++ b/Task/ISBN13-check-digit/JavaScript/isbn13-check-digit.js @@ -0,0 +1,25 @@ +/** + * Validate that the given string of digits is an ISBN13 number + * If we allow 8, 12, 13, and 14-digit numbers, this becomes a GTIN validator. + * See: https://ref.gs1.org/standards/genspecs/ + * @param {string} s + * @returns {boolean} True if the given string is a GS1 GTIN number + */ +const check = s => { + const _multiply = (e, i) => i % 2 ? e * 1 : e * 3; + const _sum = (p, c) => p + c; + const arr = [...s.replaceAll('-', '') + .replaceAll(' ', '')]; + if ([13].includes(arr.length)) { + const [last, ...rest] = [...arr].reverse(); + const result = rest.map(_multiply).reduce(_sum, last * 1); + return result % 10 === 0; + } + return false; +} + +[ + "978-0596528126", + "978-0596528120", + "978-1788399081", + "978-1788399083"].map(check) diff --git a/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur b/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur index d8bb48c1ff..2a6e6518dc 100644 --- a/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur +++ b/Task/ISBN13-check-digit/Langur/isbn13-check-digit.langur @@ -1,7 +1,7 @@ val isbn13checkdigit = fn(var s) { - s = replace(s, RE/[\- ]/) + s = replace(s, by=RE/[\- ]/) s -> re/^[0-9]{13}$/ and - fold(fn{+}, map([_, fn{*3}], s2n(s))) div 10 + fold(map(s2n(s), by=[_, fn{*3}]), by=fn{+}) div 10 } val tests = { diff --git a/Task/ISBN13-check-digit/M2000-Interpreter/isbn13-check-digit.m2000 b/Task/ISBN13-check-digit/M2000-Interpreter/isbn13-check-digit.m2000 new file mode 100644 index 0000000000..119a762eea --- /dev/null +++ b/Task/ISBN13-check-digit/M2000-Interpreter/isbn13-check-digit.m2000 @@ -0,0 +1,37 @@ +Module CheckISBN (filename as string, feed as array) { + if len(feed)=0 then exit + link feed to isbn() ' just change interface + open filename for output as #f ' use "" for output to screen (f=-2) + for n = 0 to len(feed)-1 + long sum = 0, k = 0 + string isbnStr = filter$(isbn(n), "- ") + if len(isbnStr)=0 then continue + for m = 1 to len(isbnStr) + if m mod 2 = 0 then + num = 3 * val(mid$(isbnStr, m, 1)) + else + num = val(mid$(isbnStr, m, 1)) + end if + sum += num + k++ + next m + + print #f, isbn(n); + if k<>13 then + print #f, ": not an ISBN 13" + else.if sum mod 10 = 0 then + print #f, ": good" + else + print #f, ": bad (last digit should be:"+((10-(sum-num) mod 10) mod 10)+")" + end if + next n + close #f +} +Flush +Data "978-0596528126", "978-0596528120", "978-1788399081" +Data "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5" +Data "978 1 86197 876 9", "9603313440" +a=array([]) ' get current stack (leave an empty one) then return an array +CheckISBN "isbn.txt", a +win file.app$("txt"), dir$+"isbn.txt" +CheckISBN "", a diff --git a/Task/ISBN13-check-digit/PascalABC.NET/isbn13-check-digit.pas b/Task/ISBN13-check-digit/PascalABC.NET/isbn13-check-digit.pas new file mode 100644 index 0000000000..4d9b209fe5 --- /dev/null +++ b/Task/ISBN13-check-digit/PascalABC.NET/isbn13-check-digit.pas @@ -0,0 +1,18 @@ +## +function CheckISBN13(code: string): boolean; +begin + result := false; + code := code.Replace('-', '').Replace(' ', ''); + if (code.Length <> 13) then exit; + var sum := 0; + foreach var digit in code index i do + if digit.isdigit then + sum += digit.ToDigit * (if i mod 2 = 0 then 1 else 3) + else exit; + result := sum mod 10 = 0; +end; + +CheckISBN13('978-0596528126').Println; +CheckISBN13('978-0596528120').Println; +CheckISBN13('978-1788399081').Println; +CheckISBN13('978-1788399083').Println; diff --git a/Task/ISBN13-check-digit/Scala/isbn13-check-digit.scala b/Task/ISBN13-check-digit/Scala/isbn13-check-digit.scala new file mode 100644 index 0000000000..910add1d43 --- /dev/null +++ b/Task/ISBN13-check-digit/Scala/isbn13-check-digit.scala @@ -0,0 +1,26 @@ +object ISBNValidator: + private def checkChecksum(isbn: String): Boolean = + val digits = isbn.map(_.asDigit) + val checksum = digits.zipWithIndex.map { + case (digit, idx) => + if idx % 2 == 0 then digit + else digit * 3 + }.sum + checksum % 10 == 0 + + def isValidISBN13(isbn: String): Boolean = + val cleaned = isbn.filter(_.isDigit) + cleaned.length == 13 && checkChecksum(cleaned) + +@main def main(): Unit = + def test(isbn: String): Unit = + val result = ISBNValidator.isValidISBN13(isbn) + println(s"$isbn: $result") + + List( + "978-0596528126", + "978-0596528120", + "978-1788399081", + "978-1788399083" + ) + .foreach(test) diff --git a/Task/Include-a-file/Uiua/include-a-file.uiua b/Task/Include-a-file/Uiua/include-a-file.uiua new file mode 100644 index 0000000000..1f81fb39a5 --- /dev/null +++ b/Task/Include-a-file/Uiua/include-a-file.uiua @@ -0,0 +1 @@ +~ "example.ua" diff --git a/Task/Increasing-gaps-between-consecutive-Niven-numbers/PascalABC.NET/increasing-gaps-between-consecutive-niven-numbers.pas b/Task/Increasing-gaps-between-consecutive-Niven-numbers/PascalABC.NET/increasing-gaps-between-consecutive-niven-numbers.pas new file mode 100644 index 0000000000..67152f2e87 --- /dev/null +++ b/Task/Increasing-gaps-between-consecutive-Niven-numbers/PascalABC.NET/increasing-gaps-between-consecutive-niven-numbers.pas @@ -0,0 +1,37 @@ +function digitsSum(n, sum: int64): int64; +begin + result := sum + 1; + while (n > 0) and (n mod 10 = 0) do + begin + result -= 9; + n := n div 10; + end; +end; + +begin + var niven: int64 := 0; + var gap: int64 := 0; + var sum: int64 := 0; + var nivenIndex: int64 := 0; + var previous: int64 := 1; + var gapIndex: int64 := 1; + + println('Gap index Gap Niven index Niven number'); + + while gapIndex <= 32 do + begin + niven += 1; + sum := digitsSum(niven, sum); + if niven mod sum = 0 then + begin + if niven > previous + gap then + begin + gap := niven - previous; + writeln(gapIndex:9, gap:5, nivenIndex:13, previous:14); + gapIndex += 1; + end; + previous := niven; + nivenIndex += 1; + end; + end; +end. diff --git a/Task/Infinity/Uiua/infinity.uiua b/Task/Infinity/Uiua/infinity.uiua new file mode 100644 index 0000000000..f82e41ab43 --- /dev/null +++ b/Task/Infinity/Uiua/infinity.uiua @@ -0,0 +1 @@ +&p∞ diff --git a/Task/Inheritance-Single/Arturo/inheritance-single.arturo b/Task/Inheritance-Single/Arturo/inheritance-single.arturo new file mode 100644 index 0000000000..9f1606abe4 --- /dev/null +++ b/Task/Inheritance-Single/Arturo/inheritance-single.arturo @@ -0,0 +1,24 @@ +; Base Animal type +define :animal [ + init: constructor [name :string] +] + +; Dog type inheriting from Animal +define :dog is :animal [ + ; ... +] + +; Cat type inheriting from Animal +define :cat is :animal [ + ; ... +] + +; Lab type inheriting from Dog +define :lab is :dog [ + ; ... +] + +; Collie type inheriting from Dog +define :collie is :dog [ + ; ... +] diff --git a/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic b/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic index af3e54154a..342b708226 100644 --- a/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic +++ b/Task/Integer-overflow/Applesoft-BASIC/integer-overflow-5.basic @@ -1 +1 @@ -A% = -32767 : POKE PEEK(131) + PEEK(132) * 256, 0 : ? A% +A% = -32767 : POKE PEEK(131) + PEEK(132) * 256 + 1, 0 : ? A% diff --git a/Task/Integer-overflow/FutureBasic/integer-overflow.basic b/Task/Integer-overflow/FutureBasic/integer-overflow.basic new file mode 100644 index 0000000000..722195a19e --- /dev/null +++ b/Task/Integer-overflow/FutureBasic/integer-overflow.basic @@ -0,0 +1,17 @@ +include "NSLog.incl" + +NSLog( @"FB Integer ranges:\n" ) + +NSLog( @"UInt64: 0 to %llu", ULLONG_MAX ) +NSLog( @"SInt64: %lld to %lld\n", LLONG_MIN, LLONG_MAX ) + +NSLog( @"UInt32: 0 to %u", UINT_MAX ) +NSLog( @"SInt32: %ld to %ld\n", INT_MIN, INT_MAX ) + +NSLog( @"UInt16: 0 to %hu", USHRT_MAX ) +NSLog( @"SInt16: %hd to %hd\n", SHRT_MIN, SHRT_MAX ) + +NSLog( @"UInt8: 0 to %u", UCHAR_MAX ) +NSLog( @"SInt8: %d to %d", CHAR_MIN, CHAR_MAX ) + +HandleEvents diff --git a/Task/Intersecting-number-wheels/PascalABC.NET/intersecting-number-wheels.pas b/Task/Intersecting-number-wheels/PascalABC.NET/intersecting-number-wheels.pas new file mode 100644 index 0000000000..f4cc88a641 --- /dev/null +++ b/Task/Intersecting-number-wheels/PascalABC.NET/intersecting-number-wheels.pas @@ -0,0 +1,39 @@ +function WheelCreator(wheel: string): () -> char; +begin + var index := 1; + + result := function(): char -> + begin + result := wheel[index]; + index := if index >= wheel.Length then 1 else index + 1; + end; +end; + +function TurnWheels(primary: char; wheels: dictionary char>): sequence of char; +begin + while true do + begin + var turn := wheels.Get(primary)(); + while not turn.IsDigit do + turn := wheels.Get(turn); + yield turn; + end; +end; + +begin + var allwheels := + ||('A', '123')|, + |('A', '1B2'), ('B', '34')|, + |('A', '1DD'), ('D', '678')|, + |('A', '1BC'), ('B', '34'), ('C', '5B')||; + + foreach var wheels in allwheels do + begin + foreach var w in wheels do + writeln(w[0], ': ', w[1]); + println('Generates:'); + var t := TurnWheels(wheels[0][0], wheels.ToDictionary(x -> x[0], x -> WheelCreator(x[1]))); + println(t.Take(20)); + println; + end; +end. diff --git a/Task/Introspection/Zig/introspection-1.zig b/Task/Introspection/Zig/introspection-1.zig index 7473a0ec4c..0a1d9a3921 100644 --- a/Task/Introspection/Zig/introspection-1.zig +++ b/Task/Introspection/Zig/introspection-1.zig @@ -8,7 +8,7 @@ pub fn abs(a: i32) i32 { } pub fn main() error{NotSupported}!void { - if (builtin.zig_version.order(.{ .major = 0, .minor = 11, .patch = 0 }) == .lt) { + if (builtin.zig_version.order(.{ .major = 0, .minor = 12, .patch = 1 }) == .lt) { std.debug.print("Version {any} is less than 0.11.0, not suitable, exiting!\n", .{builtin.zig_version}); return error.NotSupported; } else { diff --git a/Task/Introspection/Zig/introspection-2.zig b/Task/Introspection/Zig/introspection-2.zig index 5c15d3b78b..801c1e7015 100644 --- a/Task/Introspection/Zig/introspection-2.zig +++ b/Task/Introspection/Zig/introspection-2.zig @@ -1,4 +1,5 @@ const std = @import("std"); +const builtin = @import("builtin"); pub const first_integer_constant: i32 = 5; pub const second_integer_constant: i32 = 3; @@ -10,7 +11,18 @@ pub const another_non_integer_constant: bool = false; pub fn main() void { comptime var cnt: comptime_int = 0; comptime var sum: comptime_int = 0; - inline for (@typeInfo(@This()).Struct.decls) |decl_info| { + if (comptime builtin.zig_version.order(.{ .major = 0, .minor = 13, .patch = 0 }) == .gt) { + inline for (@typeInfo(@This()).@"struct".decls) |decl_info| { + const decl = @field(@This(), decl_info.name); + switch (@typeInfo(@TypeOf(decl))) { + .int, .comptime_int => { + sum += decl; + cnt += 1; + }, + else => continue, + } + } + } else inline for (@typeInfo(@This()).Struct.decls) |decl_info| { const decl = @field(@This(), decl_info.name); switch (@typeInfo(@TypeOf(decl))) { .Int, .ComptimeInt => { diff --git a/Task/Inverted-index/FreeBASIC/inverted-index.basic b/Task/Inverted-index/FreeBASIC/inverted-index.basic new file mode 100644 index 0000000000..4e7d383e4c --- /dev/null +++ b/Task/Inverted-index/FreeBASIC/inverted-index.basic @@ -0,0 +1,115 @@ +Const NULL As Any Ptr = 0 + +Type WordCant + arch As String + cant As Integer + sgte As WordCant Ptr +End Type + +Type WordEntry + word As String + cnts As WordCant Ptr + sgte As WordEntry Ptr +End Type + +Function addWord(root As WordEntry Ptr, word As String, arch As String) As WordEntry Ptr + Dim As WordEntry Ptr actual = root + Dim As WordCant Ptr newCant + + ' Search existing word + While actual <> NULL + If actual->word = word Then + ' Word exists, update cant for file + Dim As WordCant Ptr cant = actual->cnts + While cant <> NULL + If cant->arch = arch Then + cant->cant += 1 + Return root + End If + cant = cant->sgte + Wend + ' Add new file cant + newCant = New WordCant + newCant->arch = arch + newCant->cant = 1 + newCant->sgte = actual->cnts + actual->cnts = newCant + Return root + End If + actual = actual->sgte + Wend + + ' Add new word + Dim As WordEntry Ptr newEntry = New WordEntry + newCant = New WordCant + newCant->arch = arch + newCant->cant = 1 + newCant->sgte = NULL + + newEntry->word = word + newEntry->cnts = newCant + newEntry->sgte = root + Return newEntry +End Function + +Function makeDoubleIndex(files() As String) As WordEntry Ptr + Dim As WordEntry Ptr index = NULL + + For i As Integer = Lbound(files) To Ubound(files) + Dim As Integer ff = Freefile + Open files(i) For Input As #ff + + Dim As String linea, word + While Not Eof(ff) + Line Input #ff, linea + linea = Lcase(linea) + + Dim As Integer start = 1, posic + Do + posic = Instr(start, linea, Any " ,.;:!?()[]{}""'") + word = Mid(linea, start, Iif(posic = 0, Len(linea) - start + 1, posic - start)) + + word = Trim(word) + If Len(word) > 0 Then index = addWord(index, word, files(i)) + + start = posic + 1 + Loop Until posic = 0 + Wend + Close #ff + Next + + Return index +End Function + +Sub wordSearch(index As WordEntry Ptr, searchTerms() As String) + For i As Integer = Lbound(searchTerms) To Ubound(searchTerms) + Dim As String word = Lcase(searchTerms(i)) + Dim As WordEntry Ptr entry = index + + While entry <> NULL + If entry->word = word Then + Print Chr(34); word; Chr(34); " found in "; + Dim As WordCant Ptr cant = entry->cnts + While cant <> NULL + Print cant->arch; + If cant->sgte <> NULL Then Print ", "; + cant = cant->sgte + Wend + Print + Exit While + End If + entry = entry->sgte + Wend + + If entry = NULL Then Print Chr(34); word; """ not found." + Next +End Sub + +' Main program +Dim As String files(3) = {"file1.txt", "file2.txt", "file3.txt", "file4.txt"} +Dim As String searchTerms(4) = {"forehead", "of", "hand", "a", "foot"} + +Dim As WordEntry Ptr index = makeDoubleIndex(files()) +wordSearch(index, searchTerms()) + +Sleep diff --git a/Task/Isograms-and-heterograms/PascalABC.NET/isograms-and-heterograms.pas b/Task/Isograms-and-heterograms/PascalABC.NET/isograms-and-heterograms.pas new file mode 100644 index 0000000000..d4b5949986 --- /dev/null +++ b/Task/Isograms-and-heterograms/PascalABC.NET/isograms-and-heterograms.pas @@ -0,0 +1,28 @@ +uses System.Net; + +function isogram(word: string): integer; +begin + result := 0; + var letters := new Dictionary; + foreach var c in word do + letters[c] := letters.Get(c) + 1; + var counts: set of integer; + foreach var letter in letters do + counts += [letter.value]; + if counts.Count = 1 then + result := letters.Get(word[1]); +end; + +begin + var client := new WebClient(); + var text := client.DownloadString('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'); + var words: sequence of string := text.ToWords(|#10, #13|); + words.Where(w -> isogram(w) > 1) + .OrderByDescending(w -> isogram(w)) + .ThenByDescending(w -> w.Length) + .ThenBy(w -> w).println; + println; + words.where(w -> (isogram(w) = 1) and (w.Length > 10)) + .OrderByDescending(w -> w.Length) + .ThenBy(w -> w).println; +end. diff --git a/Task/Isograms-and-heterograms/Python/isograms-and-heterograms.py b/Task/Isograms-and-heterograms/Python/isograms-and-heterograms.py new file mode 100644 index 0000000000..8adf7d3a1d --- /dev/null +++ b/Task/Isograms-and-heterograms/Python/isograms-and-heterograms.py @@ -0,0 +1,32 @@ +from collections import Counter + +def find_n_isograms(wordlist): + n_isograms = [] + for word in wordlist: + word_lower = word.lower() + freq = Counter(word_lower) + frequencies = freq.values() + if len(set(frequencies)) == 1 and next(iter(frequencies)) > 1: + n = next(iter(frequencies)) + n_isograms.append((-n, -len(word), word)) + n_isograms.sort() + return [word for _, _, word in n_isograms] + +def find_heterograms(wordlist): + heterograms = [] + for word in wordlist: + if len(word) > 10: + word_lower = word.lower() + if len(set(word_lower)) == len(word_lower): + heterograms.append((-len(word), word)) + heterograms.sort() + return [word for _, word in heterograms] + +with open('unidict.txt', 'r') as file: + wordlist = [line.strip() for line in file] + +n_isograms_result = find_n_isograms(wordlist) +heterograms_result = find_heterograms(wordlist) + +print("n-isograms (n > 1):", n_isograms_result) +print("Heterograms with more than 10 characters:", heterograms_result) diff --git a/Task/Isqrt-integer-square-root-of-X/Miranda/isqrt-integer-square-root-of-x.miranda b/Task/Isqrt-integer-square-root-of-X/Miranda/isqrt-integer-square-root-of-x.miranda new file mode 100644 index 0000000000..1036ac98b4 --- /dev/null +++ b/Task/Isqrt-integer-square-root-of-X/Miranda/isqrt-integer-square-root-of-x.miranda @@ -0,0 +1,36 @@ +main :: [sys_message] +main = [Stdout "isqrt of 0..65:\n", + Stdout (table 2 11 [show (isqrt x) | x <- [0..65]]), + Stdout "\nisqrt of 7^1 .. 7^73:\n", + Stdout (lay (map isqrtp7 [1,3..73]))] + +isqrtp7 :: num->[char] +isqrtp7 x = "isqrt(7^" ++ rjustify 2 (show x) ++ ") = " ++ + rjustify 41 (commatize (isqrt (7^x))) + +table :: num->num->[[char]]->[char] +table cw rw xs = lay [concat (map (rjustify cw) r) | r<-split rw xs] + +split :: num->[*]->[[*]] +split n [] = [] +split n xs = take n xs:split n (drop n xs) + +isqrt :: num->num +isqrt x = step qf x 0 + where qf = (hd . dropwhile (<= x) . iterate (*4)) 1 + step 1 z r = r + step q z r = step q' z' r'', otherwise + where q' = q div 4 + t = z - r - q' + r' = r div 2 + z' = t, if t>=0 + = z, otherwise + r'' = r' + q', if t>=0 + = r', otherwise + +commatize :: num->[char] +commatize n = show n, if n<1000 + = commatize (n div 1000) ++ ',':part (n mod 1000), otherwise + where part n = show n, if n>=100 + = '0':show n, if n>=10 + = '0':'0':show n, otherwise diff --git a/Task/Isqrt-integer-square-root-of-X/PascalABC.NET/isqrt-integer-square-root-of-x.pas b/Task/Isqrt-integer-square-root-of-X/PascalABC.NET/isqrt-integer-square-root-of-x.pas new file mode 100644 index 0000000000..70f2e379d2 --- /dev/null +++ b/Task/Isqrt-integer-square-root-of-X/PascalABC.NET/isqrt-integer-square-root-of-x.pas @@ -0,0 +1,30 @@ +function isqrt(x: biginteger): biginteger; +begin + var q := 1bi; + result := 0bi; + while q <= x do + q := q shl 2; + while q > 1 do + begin + q := q shr 2; + var t := x - result - q; + result := result shr 1; + if t >= 0 Then + begin + x := t; + result += q; + end; + end; +end; + +begin + for var n := 0 to 65 do + write(isqrt(n):2); + println(#10); + var n := 7bi; + for var i := 1 to 73 step 2 do + begin + writeln('isqrt(7^', i, ') = ', isqrt(n).ToString('N0')); + n *= 49; + end; +end. diff --git a/Task/Isqrt-integer-square-root-of-X/Refal/isqrt-integer-square-root-of-x.refal b/Task/Isqrt-integer-square-root-of-X/Refal/isqrt-integer-square-root-of-x.refal new file mode 100644 index 0000000000..861ed6e80d --- /dev/null +++ b/Task/Isqrt-integer-square-root-of-X/Refal/isqrt-integer-square-root-of-x.refal @@ -0,0 +1,64 @@ +$ENTRY Go { + = + + ; +}; + +Isqrt0To65 { + = + >>>; +}; + +IsqrtOddPow7 { + , >>: e.Pows + = ; +}; + +IsqrtPow7 { + s.Pow, : e.Pow7, + : e.Sqrt = + ') = ' >; +}; + +Isqrt { + e.X, : e.Q = ; +}; + +Isqrt1 { + (e.Q) e.X, : '+' = e.Q; + (e.Q) e.X = ) e.X>; + e.X = ; +}; + +Isqrt2 { + (1) (e.Z) (e.R) = e.R; + (e.Q) (e.Z) (e.R), +
: e.Q2, + ) e.Q2>: e.T, +
: e.R2, + e.T: { + '-' e.T2 = ; + e.T = )>; + }; +}; + +Pow { + (e.N) 0 = 1; + (e.N) e.P, : { + (e.P2) 0, : e.X = ; + (e.P2) 1, : e.X = >; + }; +}; + +Commatize { + e.N = >; +}; + +Commatize1 { + e.X s.F s.1 s.2 s.3 = ',' s.1 s.2 s.3; + e.X = e.X; +} + +Iota { s.E s.E = s.E; s.S s.E = s.S s.E>; }; +Each { (e.F) = ; (e.F) t.X e.XS = ; }; +Split { s.G = ; s.G e.X, : (e.F) e.R = (e.F) ; }; diff --git a/Task/Iterated-digits-squaring/PascalABC.NET/iterated-digits-squaring.pas b/Task/Iterated-digits-squaring/PascalABC.NET/iterated-digits-squaring.pas new file mode 100644 index 0000000000..adfa61198b --- /dev/null +++ b/Task/Iterated-digits-squaring/PascalABC.NET/iterated-digits-squaring.pas @@ -0,0 +1,48 @@ +function digits(n: integer): sequence of integer; +begin + result := new List; + repeat + result := result + n mod 10; + n := n div 10; + until n = 0; +end; + +function gen(n: integer): integer; +begin + result := n; + while (result <> 1) and (result <> 89) do + begin + var s := 0; + foreach var d in digits(result) do s += d * d; + result := s; + end; +end; + +function chainsEndingWith89(ndigits: integer): int64; +begin + var prevcount := new Dictionary; + var currcount := new Dictionary; + for var i := 0 to 9 do prevcount[i * i] := 1; + + loop ndigits - 1 do + begin + currcount.Clear; + foreach var prev in prevcount do + for var newdigit := 0 to 9 do + begin + var nextgen := newdigit * newdigit + prev.key; + currcount[nextgen] := currcount.get(nextgen) + prev.value; + end; + prevcount := new Dictionary(currcount); + end; + + foreach var curr in currcount do + if (curr.key <> 0) and (gen(curr.key) = 89) then + result += curr.value; +end; + +begin + println('For 8 digits: ', chainsEndingWith89(8)); + println('For 18 digits: ', chainsEndingWith89(18)); + println(milliseconds, 'ms'); +end. diff --git a/Task/Jacobi-symbol/PascalABC.NET/jacobi-symbol.pas b/Task/Jacobi-symbol/PascalABC.NET/jacobi-symbol.pas new file mode 100644 index 0000000000..7c26f92003 --- /dev/null +++ b/Task/Jacobi-symbol/PascalABC.NET/jacobi-symbol.pas @@ -0,0 +1,34 @@ +function jacobi(n, k: integer): integer; +begin + assert((k > 0) and (k mod 2 = 1)); + n := n mod k; + result := 1; + while n <> 0 do + begin + while n mod 2 = 0 do + begin + n := n shr 1; + if (k and 7) in [3, 5] then + result := -result; + end; + swap(n, k); + if ((n and 3) = 3) and ((k and 3) = 3) then + result := -result; + n := n mod k; + end; + if k <> 1 then result := 0; +end; + +begin + write('n/k|'); + for var n := 1 to 20 do write(n:3); + writeln(#10, '—' * 64); + + for var k := 1 to 21 step 2 do + begin + write(k:2, ' |'); + for var n := 1 to 20 do + write(jacobi(n, k):3); + writeln; + end; +end. diff --git a/Task/Jacobsthal-numbers/PascalABC.NET/jacobsthal-numbers.pas b/Task/Jacobsthal-numbers/PascalABC.NET/jacobsthal-numbers.pas new file mode 100644 index 0000000000..f3a1bac47a --- /dev/null +++ b/Task/Jacobsthal-numbers/PascalABC.NET/jacobsthal-numbers.pas @@ -0,0 +1,54 @@ +function IsPrime(n: integer): boolean; +begin + result := false; + if n < 2 then exit; + for var i: integer := 2 to round(sqrt(n)) do + if n mod i = 0 then exit; + result := true; +end; + +function jacobsthalSequence(prev, curr: int64): sequence of int64; +begin + yield prev; + yield curr; + while true do + begin + swap(prev, curr); + curr += curr + prev; + yield curr; + end; +end; + +function jacobsthalOblong(): sequence of int64; +begin + var prev := -1; + foreach var n in jacobsthalSequence(0, 1) do + begin + if prev >= 0 then yield prev * n; + prev := n; + end; +end; + +function jacobsthalPrimes(): sequence of int64; +begin + foreach var n in jacobsthalSequence(0, 1) do + if isPrime(n) then yield n +end; + +begin + writeln('First 30 Jacobsthal numbers:'); + foreach var n in jacobsthalSequence(0, 1).Take(30) index i do + write(n:11, if i mod 6 = 5 then #10 else ''); + + writeln(#10, 'First 30 Jacobsthal-Lucas numbers:'); + foreach var n in jacobsthalSequence(2, 1).Take(30) index i do + write(n:11, if i mod 6 = 5 then #10 else ''); + + writeln(#10, 'First 20 Jacobsthal oblong numbers:'); + foreach var n in jacobsthalOblong().Take(20) index i do + write(n:13, if i mod 5 = 4 then #10 else ''); + + writeln(#10, 'First 10 Jacobsthal prime numbers:'); + foreach var n in jacobsthalPrimes().Take(10) index i do + write(n:11, if i mod 5 = 4 then #10 else ''); +end. diff --git a/Task/Jaro-similarity/ALGOL-68/jaro-similarity.alg b/Task/Jaro-similarity/ALGOL-68/jaro-similarity.alg new file mode 100644 index 0000000000..5337666bb1 --- /dev/null +++ b/Task/Jaro-similarity/ALGOL-68/jaro-similarity.alg @@ -0,0 +1,29 @@ +BEGIN # Jaro distance - translated from the EasyLang sample # + PROC jaro distance = ( STRING s1, s2 )REAL: BEGIN + INT len s1 = ( UPB s1 - LWB s1 ) + 1; + INT len s2 = ( UPB s2 - LWB s2 ) + 1; + INT matchstd = IF len s1 > len s2 THEN len s1 ELSE len s2 FI OVER 2 - 1; + INT m := 0, p := 0; + FOR i1 FROM LWB s1 TO UPB s1 DO + FOR i2 FROM LWB s2 TO UPB s2 DO + IF s1[ i1 ] = s2[ i2 ] THEN + IF ABS ( i2 - i1 ) <= matchstd THEN + m +:= 1; + IF i2 = i1 THEN + p +:= 1 + FI + FI + FI + OD + OD; + INT t = ( m - p ) OVER 2; + 1 / 3 * ( m / len s1 + m / len s2 + ( m - t ) / m ) + END ; + PROC print jaro distance = ( STRING s1, s2 )VOID: + print( ( s1, " :: ", s2, " -> ", fixed( jaro distance( s1, s2 ), -6, 2 ), newline ) ); + + print jaro distance( "MARTHA", "MARHTA" ); + print jaro distance( "DIXON", "DICKSONX" ); + print jaro distance( "JELLYFISH", "SMELLYFISH" ) + +END diff --git a/Task/Jensens-Device/PascalABC.NET/jensens-device.pas b/Task/Jensens-Device/PascalABC.NET/jensens-device.pas new file mode 100644 index 0000000000..5220f30d17 --- /dev/null +++ b/Task/Jensens-Device/PascalABC.NET/jensens-device.pas @@ -0,0 +1,14 @@ +function Sum(var i: integer; lo, hi: integer; term: ()-> real): real; +begin + i := lo; + while i <= hi do + begin + result += term(); + i += 1; + end; +end; + +begin + var i := 0; + Writeln(Sum(i, 1, 100, () -> 1.0 / i)); +end. diff --git a/Task/Jordan-P-lya-numbers/Sidef/jordan-p-lya-numbers.sidef b/Task/Jordan-P-lya-numbers/Sidef/jordan-p-lya-numbers.sidef new file mode 100644 index 0000000000..4b6ef5a8c0 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Sidef/jordan-p-lya-numbers.sidef @@ -0,0 +1,60 @@ +func jordan_pólya_numbers(n, k, F, callback) { + + var factors = F.sort.uniq + var factors_end = factors.end + + if (k == 0) { + callback(1) + return nil + } + + func (m, k, i=0) { + + if (k == 1) { + + var L = idiv(n,m) + + for j in (i..factors_end) { + with (factors[j]) {|q| + q > L && break + callback(m*q) + } + } + + return nil + } + + var L = idiv(n,m).iroot(k) + + for j in (i..factors_end) { + with (factors[j]) { |q| + q > L && break + __FUNC__(m*q, k-1, j) + } + } + }(1, k) + + return nil +} + +func inverse_factorial_W(n) { + var l = (log(n) - log(Num.tau)/2) + l / lambert_w(l / Num.e) - 1/2 +} + +var limit = 100e6 +var factors = (2..inverse_factorial_W(limit).int -> map { .factorial }) +var terms = Set() + +for k in (0 .. limit.ilog2) { + jordan_pólya_numbers(limit, k, factors, {|v| terms << v }) +} + +terms.sort! + +say "The first 50 Jordan-Pólya numbers:" +terms.first(50).each_slice(10, {|*a| + a.map { '%5s' % _ }.join(' ').say +}) + +say "\nThere are #{terms.len} Jordan-Pólya numbers <= #{limit.commify}, where largest is #{terms.last}." diff --git a/Task/JortSort/PascalABC.NET/jortsort.pas b/Task/JortSort/PascalABC.NET/jortsort.pas new file mode 100644 index 0000000000..9acf98045a --- /dev/null +++ b/Task/JortSort/PascalABC.NET/jortsort.pas @@ -0,0 +1,10 @@ +## +function jortsort(Self: sequence of T): boolean; +extensionmethod; +begin + result := Self.SequenceEqual(Self.sorted); +end; + +(1..10).jortsort.println; +[1,2,3].jortsort.println; +'abcdefgc'.jortsort.Println; diff --git a/Task/Josephus-problem/PascalABC.NET/josephus-problem.pas b/Task/Josephus-problem/PascalABC.NET/josephus-problem.pas new file mode 100644 index 0000000000..90949fd051 --- /dev/null +++ b/Task/Josephus-problem/PascalABC.NET/josephus-problem.pas @@ -0,0 +1,21 @@ +procedure j(n, k: integer); +begin + var p := (0..n - 1).ToList; + var i := 0; + var s := new List; + + while p.Count > 0 do + begin + i := (i + k - 1) mod p.Count; + s.Add(p[i]); + p.RemoveAt(i); + end; + + println('Prisoner killing order:', s.SkipLast); + println('Survivor:', s.Last); +end; + +begin + j(5, 2); + j(41, 3); +end. diff --git a/Task/Joystick-position/XPL0/joystick-position.xpl0 b/Task/Joystick-position/XPL0/joystick-position.xpl0 new file mode 100644 index 0000000000..3b80fbdc16 --- /dev/null +++ b/Task/Joystick-position/XPL0/joystick-position.xpl0 @@ -0,0 +1,19 @@ +def X0=20, Y0=12; \center position (character cells) +def XL=X0-5, XR=X0+5; \left, right +def YD=Y0+5, YU=Y0-5; \down, up +int TblX, TblY, Key, KeyOld; +[SetVid($13); \set 320x200 graphics +\ 0 1 2 3 4 5 6 7 8 9 A B C D E F +TblX:= [X0, XR, X0, XR, XL, X0, XL, X0, X0, XR, X0, XR, XL, X0, XL, X0]; +TblY:= [Y0, Y0, YD, YD, Y0, Y0, YD, YD, YU, YU, Y0, Y0, YU, YU, Y0, Y0]; +KeyOld:= 0; +Cursor(TblX(KeyOld), TblY(KeyOld)); ChOut(6, ^+); \draw + in center +loop [repeat Key:= GetShiftKeys; + if Key < 0 then quit; \Esc = MSb + Key:= Key>>8 & $0F; + until Key # KeyOld; + Cursor(TblX(KeyOld), TblY(KeyOld)); ChOut(6, ^ ); \erase + at old loc + Cursor(TblX(Key), TblY(Key)); ChOut(6, ^+); \draw + at new loc + KeyOld:= Key; + ]; +] diff --git a/Task/Juggler-sequence/PascalABC.NET/juggler-sequence.pas b/Task/Juggler-sequence/PascalABC.NET/juggler-sequence.pas new file mode 100644 index 0000000000..c544ab9f82 --- /dev/null +++ b/Task/Juggler-sequence/PascalABC.NET/juggler-sequence.pas @@ -0,0 +1,46 @@ +function isqrt(x: biginteger): biginteger; +begin + var q := 1bi; + result := 0bi; + while q <= x do + q := q shl 2; + while q > 1 do + begin + q := q shr 2; + var t := x - result - q; + result := result shr 1; + if t >= 0 Then + begin + x := t; + result += q; + end; + end; +end; + +procedure juggler(k: biginteger; countdig: boolean := True); +begin + var m := k; + var maxj := k; + var maxjpos := 0; + for var i := 1 to 1000 do + begin + m := if m mod 2 = 0 then isqrt(m) else isqrt(m * m * m); + if m >= maxj then + (maxj, maxjpos) := (m, i); + if m = 1 then + begin + writeln(k:9, i:6, maxjpos:6, ' ', (if countdig then maxj.ToString.Length else maxj):20 + , if countdig then ' digits, ' + milliseconds.ToString + ' ms' else ''); + exit; + end; + end; +end; + +begin + writeln(' n l(n) i(n) h(n) or d(n)'); + for var k := 20 to 39 do + juggler(k, False); + + foreach var k in [113, 173, 193, 2183, 11229, 15065, 15845, 30817] do + juggler(k) +end. diff --git a/Task/Julia-set/PascalABC.NET/julia-set.pas b/Task/Julia-set/PascalABC.NET/julia-set.pas new file mode 100644 index 0000000000..479d731956 --- /dev/null +++ b/Task/Julia-set/PascalABC.NET/julia-set.pas @@ -0,0 +1,35 @@ +uses GraphWPF; + +const + W = 800; + H = 600; + Zoom = 1; + MaxIter = 255; + MoveX = 0; + MoveY = 0; + Cx = -0.7; + Cy = 0.27015; + +begin + var colors: array [0..255] of color; + for var n := 0 to 255 do + colors[n] := RGB(n shr 5 * 36, (n shr 3 and 7) * 36, (n and 3) * 85); + + Window.Title := 'Julia set'; + var image := new Color[W, H]; + + for var x := 0 to W - 1 do + for var y := 0 to H - 1 do + begin + var zx := 1.5 * (x - W / 2) / (0.5 * Zoom * W) + MoveX; + var zy := 1.0 * (y - H / 2) / (0.5 * Zoom * H) + MoveY; + var i := MaxIter; + while (zx * zx + zy * zy < 4) and (i > 1) do + begin + (zy, zx) := (2.0 * zx * zy + Cy, zx * zx - zy * zy + Cx); + i -= 1; + end; + image[x, y] := colors[i]; + end; + DrawPixels(0,0,image); +end. diff --git a/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg b/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg index 49f65a5e24..c1f9ddbb06 100644 --- a/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg +++ b/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg @@ -1,71 +1,57 @@ -IF FILE input file; - STRING file name = "data.txt"; - open( input file, file name, stand in channel ) /= 0 -THEN - # failed to open the file # - print( ( "Unable to open """ + file name + """", newline ) ) -ELSE - # file opened OK # - BOOL at eof := FALSE; - # set the EOF handler for the file # - on logical file end( input file, ( REF FILE f )BOOL: - BEGIN - # note that we reached EOF on the latest read # - at eof := TRUE; - # return TRUE so processing can continue # - TRUE - END - ); - # return the real value of the specified field on the line # +BEGIN # Kernighan's large earthquake problem - show lines from data.txt that # + # record earthquakes greater than magnitude 6 # + + PR read "files.incl.a68" PR # include file utilities: EACHLINE, etc. # + + # return the real value of the specified field on the line # PROC real field = ( STRING line, INT field )REAL: BEGIN REAL result := 0; INT c pos := LWB line; - INT max pos := UPB line; + INT max pos = UPB line; STRING f := ""; - FOR f ield number TO field WHILE c pos <= max pos DO + FOR f ield number TO field WHILE c pos <= max pos AND f = "" DO # skip leading spaces # WHILE IF c pos > max pos THEN FALSE ELSE line[ c pos ] = " " FI DO c pos +:= 1 OD; - IF c pos <= max pos THEN - # have a field # + IF c pos <= max pos THEN # have a field # INT start pos = c pos; WHILE IF c pos > max pos THEN FALSE ELSE line[ c pos ] /= " " FI DO c pos +:= 1 OD; - IF field number = field THEN - # have the required field # + IF field number = field THEN # have the required field # f := line[ start pos : c pos - 1 ] FI FI OD; IF f /= "" THEN - # have the field - assume it a real value and convert it # + # have the field - assume it a real value and convert it # FILE real value; associate( real value, f ); - on value error( real value - , ( REF FILE ef )BOOL: - BEGIN - # "handle" invalid data # - result := 0; - # return TRUE so processing can continue # + on value error + ( real value + , ( REF FILE ef )BOOL: # "handles" ibvalid datq and # + BEGIN # returns TRUE so processing # + result := 0; # can continue # TRUE END - ); + ); get( real value, ( result ) ) FI; result END # real field # ; - # show the lines where the third field is > 6 # - WHILE NOT at eof - DO - STRING line; - get( input file, ( line, newline ) ); - IF real field( line, 3 ) > 6 THEN - print( ( line, newline ) ) - FI - OD; - # close the file # - close( input file ) -FI + # shows line if its third field is > 6, returns TRUE if it is # + PROC show large earthquake = ( STRING line, INT count so far )BOOL: + IF real field( line, 3 ) > 6 THEN + print( ( line, newline ) ); + TRUE + ELSE + FALSE + FI # show large earthquake # ; + + IF "data.txt" EACHLINE show large earthquake < 0 + THEN print( ( "Unable to open data.txt", newline ) ) + FI + +END diff --git a/Task/Kernighans-large-earthquake-problem/M2000-Interpreter/kernighans-large-earthquake-problem.m2000 b/Task/Kernighans-large-earthquake-problem/M2000-Interpreter/kernighans-large-earthquake-problem.m2000 index aa15495991..1b7668076e 100644 --- a/Task/Kernighans-large-earthquake-problem/M2000-Interpreter/kernighans-large-earthquake-problem.m2000 +++ b/Task/Kernighans-large-earthquake-problem/M2000-Interpreter/kernighans-large-earthquake-problem.m2000 @@ -18,3 +18,23 @@ Module Find_Magnitude { Close #F } Find_Magnitude +Module Find_MagnitudeUsingComma { + data$={8/27/1883 Krakatoa 8,8 + 5/18/1980 MountStHelens 7,6 + 3/13/2009 CostaRica 5,1 + 1/23/4567 EdgeCase1 6 + 1/24/4567 EdgeCase2 6,0 + 1/25/4567 EdgeCase3 6,1 + } + Open "data.txt" for output as F + Print #F, data$; + Close #F + Open "data.txt" for input as F + While not eof(#F) + Line Input #f, part$ + REM if val(mid$(part$,30), ",")>6 then print part$ + if val(mid$(part$,rinstr(rtrim$(part$)," ")),",")>6 then print part$ + End While + Close #F +} +Find_MagnitudeUsingComma diff --git a/Task/Kernighans-large-earthquake-problem/PascalABC.NET/kernighans-large-earthquake-problem.pas b/Task/Kernighans-large-earthquake-problem/PascalABC.NET/kernighans-large-earthquake-problem.pas new file mode 100644 index 0000000000..e9a71a4e27 --- /dev/null +++ b/Task/Kernighans-large-earthquake-problem/PascalABC.NET/kernighans-large-earthquake-problem.pas @@ -0,0 +1,4 @@ +## +foreach var s in ReadLines('data.txt') do + if StrToFloat(s.ToWords(' ')[2]) > 6 then + s.Println; diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Nim/keyboard-input-obtain-a-y-or-n-response.nim b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Nim/keyboard-input-obtain-a-y-or-n-response.nim index 0d670069b5..96191d8fce 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Nim/keyboard-input-obtain-a-y-or-n-response.nim +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Nim/keyboard-input-obtain-a-y-or-n-response.nim @@ -1,41 +1,39 @@ -import strformat -import gintro/[glib, gobject, gtk, gio] -import gintro/gdk except Window +import std/strformat +import gtk2, glib2 +import gdk2 except PWindow -#--------------------------------------------------------------------------------------------------- -proc onKeyPress(window: ApplicationWindow; event: Event; label: Label): bool = - var keyval: int - if not event.getKeyval(keyval): return false +proc onKeyPress(window: PWindow; event: PEventKey; label: PLabel): bool = + let keyval = event.keyval.int if keyval in [ord('n'), ord('y')]: - label.setText(&"You pressed key '{chr(keyval)}'") + let text = &"You pressed key '{chr(keyval)}'" + label.setText(text.cstring) result = true -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Quit the application. + mainQuit() - let window = app.newApplicationWindow() - window.setTitle("Y/N response") - let hbox = newBox(Orientation.horizontal, 0) - window.add(hbox) - let vbox = newBox(Orientation.vertical, 10) - hbox.packStart(vbox, true, true, 20) +nimInit() +let window = windowNew(WINDOW_TOPLEVEL) +window.setSizeRequest(400, 200) +window.setTitle("Y/N response") - let label1 = newLabel(" Press 'y' or 'n' key ") - vbox.packStart(label1, true, true, 5) +let hbox = hboxNew(false, 0) +window.add hbox +let vbox = vboxNew(false, 10) +hbox.packStart(vbox, true, true, 20) - let label2 = newLabel() - vbox.packStart(label2, true, true, 5) +let label1 = labelNew(" Press 'y' or 'n' key ") +vbox.packStart(label1, true, true, 5) - discard window.connect("key-press-event", onKeyPress, label2) +let label2 = labelNew("") +vbox.packStart(label2, true, true, 5) - window.showAll() +discard window.signalConnect("key-press-event", SIGNAL_FUNC(onKeyPress), label2) +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.YNResponse") -discard app.connect("activate", activate) -discard app.run() +window.showAll() +main() diff --git a/Task/Keyboard-macros/Nim/keyboard-macros.nim b/Task/Keyboard-macros/Nim/keyboard-macros.nim index d0581a54ea..6c6907507e 100644 --- a/Task/Keyboard-macros/Nim/keyboard-macros.nim +++ b/Task/Keyboard-macros/Nim/keyboard-macros.nim @@ -1,75 +1,73 @@ import tables -import gintro/[glib, gobject, gio] -import gintro/gtk except Table -import gintro/gdk except Window +import gtk2, glib2 +import gdk2 except PWindow type - MacroProc = proc(app: App) + MacroProc = proc(app: var App) MacroTable = Table[int, MacroProc] # Mapping key values -> procedures. - App = ref object of Application + App = object dispatchTable: MacroTable - label: Label + label: PLabel -#--------------------------------------------------------------------------------------------------- -proc addMacro(app: App; ch: char; macroProc: MacroProc) = +proc addMacro(app: var App; ch: char; macroProc: MacroProc) = ## Assign a procedure to a key. ## If the key is already assigned, nothing is done. let keyval = ord(ch) if keyval notin app.dispatchTable: app.dispatchTable[keyval] = macroProc -#--------------------------------------------------------------------------------------------------- + # Macro procedures. -proc proc1(app: App) = +proc proc1(app: var App) = app.label.setText("You called macro 1") -proc proc2(app: App) = +proc proc2(app: var App) = app.label.setText("You called macro 2") -proc proc3(app: App) = +proc proc3(app: var App) = app.label.setText("You called macro 3") -#--------------------------------------------------------------------------------------------------- -proc onKeyPress(window: ApplicationWindow; event: Event; app: App): bool = - var keyval: int - if not event.getKeyval(keyval): return false +proc onKeyPress(window: PWindow; event: PEventKey; app: var App): bool = + let keyval = event.keyval.int if keyval in app.dispatchTable: app.dispatchTable[keyval](app) result = true -#--------------------------------------------------------------------------------------------------- -proc activate(app: App) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Quit the application. + mainQuit() - app.addMacro('1', proc1) - app.addMacro('2', proc2) - app.addMacro('3', proc3) - let window = app.newApplicationWindow() - window.setTitle("Keyboard macros") +var app: App - let hbox = newBox(Orientation.horizontal, 10) - window.add(hbox) - let vbox = newBox(Orientation.vertical, 10) - hbox.packStart(vbox, true, true, 10) +nimInit() - app.label = newLabel() - app.label.setWidthChars(18) - vbox.packStart(app.label, true, true, 5) +app.addMacro('1', proc1) +app.addMacro('2', proc2) +app.addMacro('3', proc3) - discard window.connect("key-press-event", onKeyPress, app) +let window = windowNew(WINDOW_TOPLEVEL) +window.setTitle("Keyboard macros") +window.setSizeRequest(300, 50) +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - window.showAll() +let hbox = hboxNew(false, 10) +window.add hbox +let vbox = vboxNew(false, 10) +hbox.packStart(vbox, true, true, 10) -#——————————————————————————————————————————————————————————————————————————————————————————————————— +app.label = labelNew(nil) +app.label.setWidthChars(18) +vbox.packStart(app.label, true, true, 5) -let app = newApplication(App, "Rosetta.KeyboardMacros") -discard app.connect("activate", activate) -discard app.run() +discard window.signalConnect("key-press-event", SIGNAL_FUNC(onKeyPress), app.addr) + +window.showAll() +main() diff --git a/Task/Knapsack-problem-0-1/Crystal/knapsack-problem-0-1.cr b/Task/Knapsack-problem-0-1/Crystal/knapsack-problem-0-1.cr index 2b6cdc7483..1fe589ff2b 100644 --- a/Task/Knapsack-problem-0-1/Crystal/knapsack-problem-0-1.cr +++ b/Task/Knapsack-problem-0-1/Crystal/knapsack-problem-0-1.cr @@ -26,7 +26,7 @@ class Knapsack candidate = items[candidate_index] # candidate is a best of available items, so if we fill remaining value with it # and still don't reach the threshold, the branch is wrong - return nil if taken.total_value + 1.0 * candidate.value / candidate.weight * remaining_weight < @threshold_value + return nil if taken.total_value + 1.0 * candidate.value / candidate.weight * remaining_weight <= @threshold_value # now recursively check both variants mask = taken.mask.clone mask[candidate_index] = true diff --git a/Task/Knapsack-problem-0-1/PascalABC.NET/knapsack-problem-0-1.pas b/Task/Knapsack-problem-0-1/PascalABC.NET/knapsack-problem-0-1.pas new file mode 100644 index 0000000000..bba4801d23 --- /dev/null +++ b/Task/Knapsack-problem-0-1/PascalABC.NET/knapsack-problem-0-1.pas @@ -0,0 +1,59 @@ +type + item = (string, integer, integer); + +const + wants: array of item = + |('map', 9, 150), + ('compass', 13, 35), + ('water', 153, 200), + ('sandwich', 50, 160), + ('glucose', 15, 60), + ('tin', 68, 45), + ('banana', 27, 60), + ('apple', 39, 40), + ('cheese', 23, 30), + ('beer', 52, 10), + ('suntan cream', 11, 70), + ('camera', 32, 30), + ('T-shirt', 24, 15), + ('trousers', 48, 10), + ('umbrella', 73, 40), + ('waterproof trousers', 42, 70), + ('waterproof overclothes', 43, 75), + ('note-case', 22, 80), + ('sunglasses', 7, 20), + ('towel', 18, 12), + ('socks', 4, 50), + ('book', 30, 10)|; + maxweight = 400; + +function m(i, w: integer): (List, integer, integer); +begin + var chosen := new List; + if (i < 0) or (w = 0) then + result := (chosen, 0, 0) + else if (wants[i].Item2 > w) then + result := m(i - 1, w) + else + begin + var (l0, w0, v0) := m(i - 1, w); + var (l1, w1, v1) := m(i - 1, w - wants[i].Item2); + v1 += wants[i].Item3; + if (v1 > v0) then + begin + l1.Add(wants[i]); + result := (l1, w1 + wants[i].Item2, v1); + end + else result := (l0, w0, v0); + end; +end; + +begin + var (chosenItems, totalWeight, totalValue) := m(wants.Count - 1, maxweight); + println('Knapsack Item Chosen Weight Value'); + println('---------------------- ------ -----'); + foreach var it in chosenItems do + writeln(it.Item1.PadRight(22), it.Item2:7, it.Item3:6); + println('---------------------- ------ -----'); + writeln('Total ', chosenItems.Count, ' Items Chosen', totalWeight:8, totalValue:6); +end. diff --git a/Task/Knights-tour/FutureBasic/knights-tour.basic b/Task/Knights-tour/FutureBasic/knights-tour.basic new file mode 100644 index 0000000000..40584f720b --- /dev/null +++ b/Task/Knights-tour/FutureBasic/knights-tour.basic @@ -0,0 +1,270 @@ +include "NSLog.incl" +output @"Knight's Move" + +_window = 1 +_layerView = 10 + +begin record moved + CGPoint offset + Int SquareMove +end record + +begin globals +dim move(8) as moved +int Squares(64) +CFMutableArrayRef gFinalArray +end globals + +gFinalArray = fn MutableArrayWithCapacity(0) + +local fn PointOffset( pt as CGPoint,offset as CGPoint) as CGPoint + pt.x += offset.x + pt.y += offset.y +end fn = pt + +local fn FindLocation( x as int ) as CGPoint + float a,b + float y = x/8 + float z = frac(y) + CGPoint pts + + If z == 0 + a = 8 + b = 8 - fix(y) + else + a = z*8 + b = 8 - fix(y) - 1 + end if + + pts.x = a*50 - 25 + pts.y = b*50 + 25 + +end fn = pts + +local fn SetRecord + for int x = 1 to 64 + Squares(x) = 0 + next + //8 possible moves for a Knight + move.offset.x(1) = -50 + move.offset.y(1) = -100 + move.SquareMove(1) = 15 + move.offset.x(2) = 50 + move.offset.y(2) = -100 + move.SquareMove(2) = 17 + move.offset.x(3) = -50 + move.offset.y(3) = 100 + move.SquareMove(3) = -17 + move.offset.x(4) = 50 + move.offset.y(4) = 100 + move.SquareMove(4) = -15 + move.offset.x(5) = 100 + move.offset.y(5) = 50 + move.SquareMove(5) = -6 + move.offset.x(6) = -100 + move.offset.y(6) = 50 + move.SquareMove(6) = -10 + move.offset.x(7) = 100 + move.offset.y(7) = -50 + move.SquareMove(7) = 10 + move.offset.x(8) = -100 + move.offset.y(8) = -50 + move.SquareMove(8) = 6 + +end fn + +local fn Check(y as int, x as int ) as bool + bool ans = NO + + select y + case 1 + select x + case > 48 + ans = No + case 1,9,17,25,33,41,49,57 + ans = NO + case else + ans = YES + end select + case 2 + select x + case > 48 + ans = NO + case 8,16,24,32,40,48,56,64 + ans = NO + case else + ans = YES + end select + case 3 + select x + case < 16 + ans = NO + case 1,9,17,25,33,41,49,57 + ans = NO + case else + ans = YES + end select + case 4 + select x + case < 16 + ans = NO + case 8,16,24,32,40,48,56,64 + ans = NO + case else + ans = YES + end select + case 5 + select x + case < 9 + ans = NO + case 7,8,15,16,23,24,31,32,39,40,47,48,55,56,63,64 + ans = NO + case else + ans = YES + end select + case 6 + select x + case < 9 + ans = NO + case 1,2,9,10,17,18,25,26,33,34,41,42,49,50,57,58 + ans = NO + case else + ans = YES + end select + case 7 + select x + case > 56 + ans = NO + case 7,8,15,16,23,24,31,32,39,40,47,48,55,56,63,64 + ans = NO + case else + ans = YES + end select + case 8 + select x + case > 56 + ans = NO + case 1,2,9,10,17,18,25,26,33,34,41,42,49,50,57,58 + ans = NO + case else + ans = YES + end select + end select +end fn = ans + +local fn DrawKnightsPassage( tag as long, array as CFArrayRef) as int + CALayerRef layer + CAShapeLayerRef shapeLayer + BezierPathRef path = fn BezierPathInit + int x,count = fn ArrayCount(array) + int square = fn StringIntValue(fn ArrayObjectAtIndex( array, 0)) + + layer = fn ViewLayer( tag ) + CALayerSetBackgroundColor( layer, fn ColorClear ) + CALayerSetBorderWidth( layer, 2 ) + shapeLayer = fn CAShapeLayerInit + CGPoint pt = fn FindLocation( square) + Squares(square) = 1 + BezierPathMoveToPoint( path, pt) + for x = 1 to count - 2 + square = fn StringIntValue(fn ArrayObjectAtIndex( array, x)) + pt = fn FindLocation( square) + BezierPathLineToPoint( path, pt) + next + + CAShapeLayerSetPath( shapeLayer, path ) + CAShapeLayerSetLineWidth( shapeLayer, 2 ) + CAShapeLayerSetLineCap( shapeLayer, kCALineCapRound ) + CAShapeLayerSetStrokeColor( shapeLayer, fn ColorBlue ) + CAShapeLayerSetFillColor( shapeLayer, fn ColorClear ) + CALayerAddSublayer( layer, shapeLayer ) + +end fn = x + +local fn KnightsTour as int + int x,j,y + int square = rnd(64)//58 //Starting square 58= White left Knight this is random start + CFMutableStringRef array = fn MutableStringWithCapacity(0) + CGPoint pt = fn FindLocation( square) + for x = 1 to 64 + Squares(x) = 0 + next + Squares(square) = 1 + MutableStringAppendString( array, fn StringWithFormat( @"%d:", square )) + + for x = 1 to 63 + j = 1 + do + y = rnd(8) + j++ + until (square > 0 && square < 65 && (fn Check(y,square)) && square + move.SquareMove(y) > 0 && Squares(square + move.SquareMove(y)) == 0) || j == 35 + if j == 35 then exit next + square += move.SquareMove(y) + MutableStringAppendString( array, fn StringWithFormat( @"%d:", square )) + + pt = fn PointOffset( pt, move.offset(y)) + Squares(square) = 1 + next + MutableArrayAddObject( gFinalArray, (CFTypeRef) array ) + +end fn = x + +void local fn BuildWnd + CGRect r + int x,y,j,Item(100000),max + ColorRef hue(1) // Thanks Jay + CALayerRef layer + bool i + CFTypeRef ans + CFArrayRef array + + window _window, @"Chess Board", ( 0,0,450,450) + view _layerView, (20,20,400,400) + WindowCenter(_window) + WindowSubclassContentView(_window) + ViewSetFlipped( _windowContentViewTag, YES ) + ViewSetNeedsDisplay( _windowContentViewTag ) + ViewSetWantsLayer( _layerView, YES ) + layer = fn ViewLayer( _layerview ) + ViewSetFlipped( _layerview, YES ) + CALayerSetBackgroundColor( layer, fn ColorClear ) + CALayerSetBorderWidth( layer, 2 ) + + r = fn CGREctMake( 20,20,50,50 ) + hue(NO) = fn colorLightGray + hue(YES) = fn ColorClear + i = YES + j = 1 + for x = 1 to 8 + for y = 1 to 8 + rect fill r, hue(i) + print %(r.origin.x,r.origin.y) j + r = fn CGRectOffset( r, 50,0) + j++ + if i == YES then i = NO else i = YES + next + if i == YES then i = NO else i = YES + r = fn CGRectOffset( r , - 400, 50 ) + next + for x = 1 to 100000 + item(x) = fn KnightsTour + next + max = 1 + y = 1 + for x = 1 to 99999 + if item(x) > max then max = item(x):y = x + next + + ans = fn ArrayObjectAtIndex(gFinalArray, y-1 ) + array = fn StringComponentsSeparatedByString(ans, @":" ) + + fn DrawKnightsPassage( _layerview, array) + NSLog(@"Starts at %@",fn ArrayObjectAtIndex( array, 0)) + NSLog(@"max= %d Item= %d try= %d", max, item(y), y ) + +end fn + +fn SetRecord +fn BuildWnd + +HandleEvents diff --git a/Task/Knuth-shuffle/Standard-ML/knuth-shuffle.ml b/Task/Knuth-shuffle/Standard-ML/knuth-shuffle.ml new file mode 100644 index 0000000000..5ee802311d --- /dev/null +++ b/Task/Knuth-shuffle/Standard-ML/knuth-shuffle.ml @@ -0,0 +1,23 @@ +val rng = ref (SplitMix64.init NONE) + +fun getRandInt max = + let + val (rng', next) = SplitMix64.nextRange (0, max) + val () = rng := rng' + in + Word64.toInt next + end + +fun knuthShuffle a = + let + val i = ref ((Array.length a) - 1) + in + while !i > 0 do + let + val a_i = Array.sub (a, !i) + val j = getRandInt !i + val a_j = Array.sub (a, j) + in + (Array.update (a, !i, a_j); Array.update (a, j, a_i); i := (!i - 1)) + end + end diff --git a/Task/Knuths-algorithm-S/PascalABC.NET/knuths-algorithm-s.pas b/Task/Knuths-algorithm-S/PascalABC.NET/knuths-algorithm-s.pas new file mode 100644 index 0000000000..e6116c92ff --- /dev/null +++ b/Task/Knuths-algorithm-S/PascalABC.NET/knuths-algorithm-s.pas @@ -0,0 +1,32 @@ +function s_of_n_creator(n: integer): T-> list; +begin + var sample := new List; + var i := 0; + + result := function(item: T): list -> + begin + i += 1; + if i <= n then + sample.add(item) + else if random(i) < n then + sample[random(n)] := item; + result := sample; + end; +end; + +begin + println('Digits counts for 100_000 runs:'); + var hist: array [0..9] of integer; + var sample := new List; + loop 100_000 do + begin + var s_of_n := s_of_n_creator&(3); + for var i := 0 to 9 do + sample := s_of_n(i); + foreach var val in sample do + hist[val] += 1; + end; + + foreach var count in hist index n do + writeln(n, ': ', count); +end. diff --git a/Task/Knuths-power-tree/PascalABC.NET/knuths-power-tree.pas b/Task/Knuths-power-tree/PascalABC.NET/knuths-power-tree.pas new file mode 100644 index 0000000000..c7321cb788 --- /dev/null +++ b/Task/Knuths-power-tree/PascalABC.NET/knuths-power-tree.pas @@ -0,0 +1,56 @@ +uses NumLibABC; + +var + p := Dict((1, 0)); + lvl := Lst(Lst(word(1))); + +function tofraction(s: string): fraction; +begin + var period := s.IndexOf('.'); + if period = -1 then result := Frc(s.ToBigInteger) + else result := Frc(s.Remove(period, 1).ToBigInteger, Power(10bi, s.Length - period - 1)); +end; + +function path(n: word): List; +begin + result := new List; + if n = 0 then exit; + while not p.ContainsKey(n) do + begin + var q := new List; + foreach var x in lvl[0] do + foreach var y in path(x) do + begin + if (x + y) in p then break; + p[x + y] := x; + q.add(x + y); + end; + lvl[0] := q; + end; + result := path(p[n]) + Lst(n); +end; + +function treePow(x: real; n: word): Fraction; +begin + var frac := tofraction(FloatToStr(x)); + var r := Dict((0, Frc(1)), (1, frac)); + var p := 0; + foreach var i in path(n) do + begin + r[i] := r[i - p] * r[p]; + p := i; + end; + result := r[n]; +end; + +procedure showPow(x: real; n: word); +begin + writeln(n, ': ', path(n)); + writeln(x, '^', n, ' = ', treePow(x, n), #10); +end; + +begin + for var n := 0 to 17 do showPow(2, n); + showPow(1.1, 81); + showPow(3, 191); +end. diff --git a/Task/Koch-curve/ALGOL-68/koch-curve.alg b/Task/Koch-curve/ALGOL-68/koch-curve.alg index bc36c46f10..2ecf137680 100644 --- a/Task/Koch-curve/ALGOL-68/koch-curve.alg +++ b/Task/Koch-curve/ALGOL-68/koch-curve.alg @@ -52,7 +52,7 @@ BEGIN # Koch Curve in SVG # put( svg file, ( "'/>", newline, "", newline ) ); close( svg file ) - FI # sierpinski square # ; + FI # koch curve # ; koch curve( "koch.svg", 600, 5, 4, 150, 150 ) diff --git a/Task/Kolakoski-sequence/PascalABC.NET/kolakoski-sequence.pas b/Task/Kolakoski-sequence/PascalABC.NET/kolakoski-sequence.pas new file mode 100644 index 0000000000..b22af518c0 --- /dev/null +++ b/Task/Kolakoski-sequence/PascalABC.NET/kolakoski-sequence.pas @@ -0,0 +1,59 @@ +function nextInCycle(a: array of integer; index: word) := a[index mod a.Length]; + +function kolakoski(a: array of integer; length: word): array of integer; +begin + SetLength(result, length); + var i := 0; + var k := 0; + + while true do + begin + result[i] := nextInCycle(a, k); + if result[k] > 1 then + for var j := 1 to result[k] - 1 do + begin + i += 1; + if i = length then exit; + result[i] := result[i - 1]; + end; + i += 1; + if i = length then exit; + k += 1; + end; +end; + +function possibleKolakoski(a: array of integer): boolean; +begin + var rle := new List; + var prev := a[0]; + var count := 1; + result := true; + + for var i := 1 to a.Count - 1 do + if a[i] = prev then + count += 1 + else + begin + rle.Add(count); + count := 1; + prev := a[i]; + end; + + foreach var val in rle index i do + if val <> a[i] then result := false; +end; + + +begin + var Ias := |[1, 2], [2, 1], [1, 3, 1, 2], [1, 3, 2, 1]|; + var Lengths := [20, 20, 30, 30]; + + foreach var (length, ia) in Zip(Lengths, Ias) do + begin + var kol := kolakoski(ia, length); + writeln('First ', length, ' members of the sequence generated by ', ia, ':'); + writeln(kol); + var s := if possibleKolakoski(kol) then 'Yes' else 'No'; + writeln('Possible Kolakoski sequence? ', s, #10); + end; +end. diff --git a/Task/Kosaraju/PascalABC.NET/kosaraju.pas b/Task/Kosaraju/PascalABC.NET/kosaraju.pas new file mode 100644 index 0000000000..157f2ee389 --- /dev/null +++ b/Task/Kosaraju/PascalABC.NET/kosaraju.pas @@ -0,0 +1,46 @@ +function kosaraju(g: List): array of integer; +var + size := g.Count; + vis: array of boolean := new boolean[size]; + l: array of integer := new integer[size]; + c: array of integer := new integer[size]; + x := size; + t: array of List := new List[size]; + + procedure visit(u: integer); + begin + if not vis[u] then + begin + vis[u] := true; + foreach var v in g[u] do + begin + visit(v); + t[v].Add(u); + end; + dec(x); + l[x] := u; + end; + end; + + procedure assign(u, root: integer); + begin + if vis[u] then + begin + vis[u] := false; + c[u] := root; + foreach var v in t[u] do assign(v, root); + end; + end; + +begin + for var i := 0 to t.Count - 1 do t[i] := new List; + + foreach var u in [0..size - 1] do visit(u); + foreach var u in l do assign(u, u); + result := c; +end; + +begin + var g := Lst(|1|, |2|, |0|, |1, 2, 4|, |3, 5|, |2, 6|, |5|, |4, 6, 7|); + println(kosaraju(g)); +end. diff --git a/Task/Kronecker-product-based-fractals/PascalABC.NET/kronecker-product-based-fractals.pas b/Task/Kronecker-product-based-fractals/PascalABC.NET/kronecker-product-based-fractals.pas new file mode 100644 index 0000000000..64856ba1fa --- /dev/null +++ b/Task/Kronecker-product-based-fractals/PascalABC.NET/kronecker-product-based-fractals.pas @@ -0,0 +1,39 @@ +type + Matrix = array [,] of integer; + +function kronecker(a, b: Matrix): Matrix; +begin + SetLength(result, a.RowCount * b.RowCount, a.ColCount * b.ColCount); + for var i := 0 to a.RowCount - 1 do + for var j := 0 to a.ColCount - 1 do + for var k := 0 to b.RowCount - 1 do + for var l := 0 to b.ColCount - 1 do + result[b.RowCount * i + k, b.ColCount * j + l] := a[i, j] * b[k, l]; +end; + +function kroneckerPower(m: Matrix; n: integer): Matrix; +begin + result := Copy(m); + foreach var i in 2..n do + result := kronecker(result, m) +end; + +procedure printMatrix(text: String; m: Matrix); +begin + println(text, 'fractal :'); + for var i := 0 to m.RowCount - 1 do + begin + for var j := 0 to m.ColCount - 1 do + write(if (m[i, j] = 1) then '*' else ' '); + println(); + end; + println(); +end; + +begin + var a: Matrix := ((0, 1, 0), (1, 1, 1), (0, 1, 0)); + printMatrix('Vicsek', kroneckerPower(a, 4)); + + var b: Matrix := ((1, 1, 1), (1, 0, 1), (1, 1, 1)); + printMatrix('Sierpinski carpet', kroneckerPower(b, 4)) +end. diff --git a/Task/Kronecker-product/PascalABC.NET/kronecker-product.pas b/Task/Kronecker-product/PascalABC.NET/kronecker-product.pas new file mode 100644 index 0000000000..6e0fb920fb --- /dev/null +++ b/Task/Kronecker-product/PascalABC.NET/kronecker-product.pas @@ -0,0 +1,22 @@ +type + Matrix = array [,] of integer; + +function kronecker(a, b: Matrix): Matrix; +begin + SetLength(result, a.RowCount * b.RowCount, a.ColCount * b.ColCount); + for var i := 0 to a.RowCount - 1 do + for var j := 0 to a.ColCount - 1 do + for var k := 0 to b.RowCount - 1 do + for var l := 0 to b.ColCount - 1 do + result[b.RowCount * i + k, b.ColCount * j + l] := a[i, j] * b[k, l]; +end; + +begin + var a1: Matrix := ((1, 2), (3, 4)); + var b1: Matrix := ((0, 5), (6, 7)); + kronecker(a1, b1).Println; + println; + var a2: Matrix := ((0, 1, 0), (1, 1, 1), (0, 1, 0)); + var b2: Matrix := ((1, 1, 1, 1), (1, 0, 0, 1), (1, 1, 1, 1)); + kronecker(a2, b2).Println; +end. diff --git a/Task/LZW-compression/PascalABC.NET/lzw-compression.pas b/Task/LZW-compression/PascalABC.NET/lzw-compression.pas new file mode 100644 index 0000000000..a21d45daa7 --- /dev/null +++ b/Task/LZW-compression/PascalABC.NET/lzw-compression.pas @@ -0,0 +1,63 @@ +function Compress(uncompressed: string): list; +begin + // build the dictionary + var dictionary := new Dictionary; + for var i := 0 to 255 do + dictionary[Chr(i).ToString] := i; + + var w := ''; + var compressed := new List; + + foreach var c in uncompressed do + begin + var wc := w + c; + if wc in dictionary then w := wc + else begin + // write w to output + compressed.Add(dictionary[w]); + // wc is a new sequence; add it to the dictionary + dictionary[wc] := dictionary.Count; + w := c.ToString; + end; + end; + + // write remaining output if necessary + if w <> '' then compressed.Add(dictionary[w]); + result := compressed; +end; + +function Decompress(compressed: list): string; +begin + // build the dictionary + var dictionary := new Dictionary; + for var i := 0 to 255 do + dictionary[i] := Chr(i).ToString; + + var w := dictionary[compressed[0]]; + compressed.RemoveAt(0); + var decompressed := new StringBuilder(w); + + foreach var k in compressed do + begin + var entry := ''; + if k in dictionary then entry := dictionary[k] + else + if k = dictionary.Count then entry := w + w[0]; + + decompressed.Append(entry); + + // new sequence; add it to the dictionary + dictionary[dictionary.Count] := w + entry[1]; + + w := entry; + end; + + result := decompressed.ToString; +end; + +begin + var compressed := Compress('TOBEORNOTTOBEORTOBEORNOT'); + Writeln(compressed); + var decompressed := Decompress(compressed); + Writeln(decompressed); +end. diff --git a/Task/Lah-numbers/Ada/lah-numbers.ada b/Task/Lah-numbers/Ada/lah-numbers.ada new file mode 100644 index 0000000000..67e6a3b0c0 --- /dev/null +++ b/Task/Lah-numbers/Ada/lah-numbers.ada @@ -0,0 +1,70 @@ +-- Rosetta Code Task written in Ada +-- Lah numbers +-- https://rosettacode.org/wiki/Lah_numbers +-- (Mostly) translated from the AWK example +-- Proper formatting of the Big Integers would be nice. +-- Not important here, but in general, the factorials should be cached for greater performance. +-- Could use alternate libraries for large integers... +-- January 2025, R. B. E. +-- Using GNAT Big Integers, GNAT version 14.2, MacOS 15.3, M1 chip + +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; + +procedure Lah_Numbers is + + function Factorial (F : Natural) return Big_Positive is + Prod : Big_Positive := To_Big_Integer (1); + begin + for I in reverse 2..F loop + Prod := Prod * To_Big_Integer (I); + end loop; + return Prod; + end Factorial; + + function Lah (N, K : Natural) return Big_Natural is + begin + if (K = 1) then + return Factorial (N); + end if; + if (K = N) then + return (To_Big_Integer (1)); + end if; + if (K > N) then + return (To_Big_Integer (0)); + end if; + if ((K < 1) or (N < 1)) then + return (To_Big_Integer (0)); + end if; + return (Factorial (N) * Factorial (N-1)) / (Factorial (K) * Factorial (K-1)) / Factorial (N-K); + end Lah; + + Biggest_Lah_Number_in_Row_100 : Big_Natural := To_Big_Integer (0); + Candidate_Biggest_Lah_Number_in_Row_100 : Big_Positive; + +begin + Put_Line ("unsigned Lah numbers: L(n,k)"); + Put ("n/k"); + for I in 0..12 loop + Put (I, 3); + end loop; + New_Line; + for Row in 0..12 loop + Put (Row, 2); + for Col in 0..Row loop + Put (To_String (Lah (Row, Col))); + end loop; + New_Line; + end loop; + New_Line; + for Col in 0..12 loop + Candidate_Biggest_Lah_Number_in_Row_100 := Lah (100, Col); + if Biggest_Lah_Number_in_Row_100 < Candidate_Biggest_Lah_Number_in_Row_100 then + Biggest_Lah_Number_in_Row_100 := Candidate_Biggest_Lah_Number_in_Row_100; + end if; + end loop; + Put_Line ("Maximum value of L(n,k) where n = 100:"); + Put_Line (To_String (Biggest_Lah_Number_in_Row_100)); +end Lah_Numbers; diff --git a/Task/Lah-numbers/Forth/lah-numbers.fth b/Task/Lah-numbers/Forth/lah-numbers.fth new file mode 100644 index 0000000000..4236464c90 --- /dev/null +++ b/Task/Lah-numbers/Forth/lah-numbers.fth @@ -0,0 +1,34 @@ +: factorial ( u -- u ) + 1 swap + begin + dup 0> + while + tuck * swap 1- + repeat + drop ; + +: lah ( n k -- u ) + dup 1 = if drop factorial exit then + dup 1 < if 2drop 0 exit then + over 1 < if 2drop 0 exit then + 2dup = if 2drop 1 exit then + 2dup < if 2drop 0 exit then + dup factorial over 1- factorial * >r + swap dup factorial over 1- factorial * + r> / >r swap - factorial r> swap / ; + +: main ( -- ) + ." Unsigned Lah numbers L(n, k):" cr + ." n/k" + 13 1 do + i 11 .r + loop cr + 13 1 do + i 3 .r + i 1+ 1 do + j i lah 11 .r + loop cr + loop ; + +main +bye diff --git a/Task/Lah-numbers/PascalABC.NET/lah-numbers.pas b/Task/Lah-numbers/PascalABC.NET/lah-numbers.pas new file mode 100644 index 0000000000..6ee08fcda3 --- /dev/null +++ b/Task/Lah-numbers/PascalABC.NET/lah-numbers.pas @@ -0,0 +1,38 @@ +function binomial(n, k: integer): biginteger; +begin + result := 1bi; + for var i := 1 to k do + result := result * (n - i + 1) div i; +end; + +function factorial(n: integer): biginteger; +begin + result := 1bi; + for var i := 2 to n do + result *= i; +end; + +function lah(n, k: integer; signed: boolean := false): biginteger; +begin + if (n = 0) or (k = 0) or (k > n) then result := 0bi + else + if n = k then result := 1bi + else + if k = 1 then result := factorial(n) + else + begin + result := binomial(n, k) * binomial(n - 1, k - 1) * factorial(n - k); + if signed and ((n and 1) <> 0) then result := -result; + end; +end; + +begin + for var n := 0 to 12 do + begin + for var k := 0 to n do + print(lah(n, k)); + println; + end; + println; + (1..100).Select(k -> lah(100, k)).Max.Println; +end. diff --git a/Task/Lah-numbers/Refal/lah-numbers.refal b/Task/Lah-numbers/Refal/lah-numbers.refal new file mode 100644 index 0000000000..3f7d3df290 --- /dev/null +++ b/Task/Lah-numbers/Refal/lah-numbers.refal @@ -0,0 +1,60 @@ +$ENTRY Go { + = > + + + >>; +}; + +Fac { + 0 = 1; + e.N = >>; +}; + +Lah { + (e.N) e.N = 1; + (0) e.K = 0; + (e.N) 0 = 0; + (e.N) 1 = ; + (e.N) e.K, + ) >>: e.1, + ) >>: e.2, + >: e.3 = +
) e.3>; +}; + +FindMax { + = ; + (e.M) 101 = e.M; + (e.M) s.I, : e.C = + ) >; +}; + +Max { + (e.1) e.2, : { + '+' = e.1; + s.C = e.2; + }; +}; + +Rpt { + 0 s.C = ; + s.N s.C = s.C s.C>; +}; + +Fmt { + s.W e.N, >: (e.1) e.2 = e.2; +}; + +Row { + s.N = >>>; +}; + +Iota { + s.E s.E = s.E; + s.S s.E = s.S s.E>; +}; + +Each { + (e.F) = ; + (e.F) t.X e.Xs = ; +}; diff --git a/Task/Langtons-ant/PascalABC.NET/langtons-ant.pas b/Task/Langtons-ant/PascalABC.NET/langtons-ant.pas new file mode 100644 index 0000000000..22be724089 --- /dev/null +++ b/Task/Langtons-ant/PascalABC.NET/langtons-ant.pas @@ -0,0 +1,35 @@ +type + Direction = (up, right, down, left); + Color = (white, black); + +const + width = 75; + height = 52; + maxSteps = 12_000; + +begin + var m: array [1..height] of array [1..width] of color; + var dir := up; + var x := width div 2; + var y := height div 2; + + var i := 0; + while (i < maxSteps) and (x in (1..width )) and (y in (1..height )) do + begin + var turn := m[y][x] = black; + m[y][x] := if m[y][x] = black then white else black; + + dir := Direction((4 + integer(dir) + (if turn then 1 else -1)) mod 4); + case dir of + up: dec(y); + right: dec(x); + down: inc(y); + left: inc(x); + end; + + inc(i); + end; + + for var row := 1 to height do + m[row].select(x -> (if x = white then '.' else '#')).println; +end. diff --git a/Task/Largest-int-from-concatenated-ints/ALGOL-68/largest-int-from-concatenated-ints.alg b/Task/Largest-int-from-concatenated-ints/ALGOL-68/largest-int-from-concatenated-ints.alg index 6c96705df9..828bd7f5e9 100644 --- a/Task/Largest-int-from-concatenated-ints/ALGOL-68/largest-int-from-concatenated-ints.alg +++ b/Task/Largest-int-from-concatenated-ints/ALGOL-68/largest-int-from-concatenated-ints.alg @@ -1,5 +1,4 @@ BEGIN - # returns the integer value of s # OP TOINT = ( STRING s)INT: BEGIN INT result := 0; @@ -8,38 +7,21 @@ BEGIN OD; result END # TOINT # ; - # returns the first digit of n # - OP FIRSTDIGIT = ( INT n )INT: - BEGIN - INT result := ABS n; - WHILE result > 9 DO result OVERAB 10 OD; - result - END # FIRSTDIGIT # ; - # returns a string representaton of n # OP TOSTRING = ( INT n )STRING: whole( n, 0 ); - # returns an array containing the values of a sorted such that concatenating the values would result in the largest value # + OP PRINT = ( []INT a )VOID: + FOR a pos FROM LWB a TO UPB a DO + print( ( TOSTRING a[ a pos ] ) ) + OD # PRINT # ; + + # returns an array containing the values of a sorted such that # + # concatenating the values would result in the largest value # OP CONCATSORT = ( []INT a )[]INT: - IF LWB a >= UPB a THEN - # 0 or 1 element(s) # + IF LWB a >= UPB a THEN # 0 or 1 element(s) # a - ELSE - # 2 or more elements # + ELSE # 2 or more elements # [ 1 : ( UPB a - LWB a ) + 1 ]INT result := a[ AT 1 ]; - # sort the numbers into reverse first digit order # - FOR o pos FROM UPB result - 1 BY -1 TO 1 - WHILE BOOL swapped := FALSE; - FOR i pos TO o pos DO - IF FIRSTDIGIT result[ i pos ] < FIRSTDIGIT result[ i pos + 1 ] THEN - INT t = result[ i pos + 1 ]; - result[ i pos + 1 ] := result[ i pos ]; - result[ i pos ] := t; - swapped := TRUE - FI - OD; - swapped - DO SKIP OD; - # now re-order adjacent numbers so they have the highest concatenated value # - WHILE BOOL swapped := FALSE; + # re-order adjacent numbers so they have the highest concatenated # + WHILE BOOL swapped := FALSE; # value # FOR i pos TO UPB result - 1 DO STRING l := TOSTRING result[ i pos ]; STRING r := TOSTRING result[ i pos + 1 ]; @@ -54,11 +36,6 @@ BEGIN DO SKIP OD; result FI # CONCATSORT # ; - # prints the array a # - OP PRINT = ( []INT a )VOID: - FOR a pos FROM LWB a TO UPB a DO - print( ( TOSTRING a[ a pos ] ) ) - OD # PRINT # ; # task test cases # PRINT CONCATSORT []INT( 1, 34, 3, 98, 9, 76, 45, 4 ); diff --git a/Task/Largest-int-from-concatenated-ints/PascalABC.NET/largest-int-from-concatenated-ints.pas b/Task/Largest-int-from-concatenated-ints/PascalABC.NET/largest-int-from-concatenated-ints.pas new file mode 100644 index 0000000000..65036d600b --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/PascalABC.NET/largest-int-from-concatenated-ints.pas @@ -0,0 +1,10 @@ +## +function maxNum(x: array of integer): string; +begin + var s := x.select(n -> n.tostring).ToList; + sort(s, (x, y) -> (x > y)); + result := s.Aggregate((p, x) -> p + x); +end; + +maxNum([1, 34, 3, 98, 9, 76, 45, 4]).println; +maxNum([54, 546, 548, 60]).println; diff --git a/Task/Largest-number-divisible-by-its-digits/PascalABC.NET/largest-number-divisible-by-its-digits.pas b/Task/Largest-number-divisible-by-its-digits/PascalABC.NET/largest-number-divisible-by-its-digits.pas new file mode 100644 index 0000000000..cec834c71c --- /dev/null +++ b/Task/Largest-number-divisible-by-its-digits/PascalABC.NET/largest-number-divisible-by-its-digits.pas @@ -0,0 +1,37 @@ +function digits(n: int64; base: byte): List; +begin + result := new List; + repeat + result.Add(byte(n mod base)); + n := n div base; + until n = 0; +end; + +function isLynchBell(num: int64; base: byte) := digits(num, base).All(x -> num mod x = 0); + +begin + for var n := 9876432 downto 1 do + begin + var dignum := digits(n, 10); + if (dignum.Count = dignum.ToSet.Count) and (not dignum.Contains(0)) then + if islynchbell(n, 10) then + begin + Println('Largest decimal number is:', n); + break; + end; + end; + + var magic := 15 * 14 * 13 * 12 * 11; + var n := $fedcba987654321 div magic * magic; + while n > 0 do + begin + var dignum := digits(n, 16); + if (dignum.Count = dignum.ToSet.Count) and (not dignum.Contains(0)) then + if islynchbell(n, 16) then + begin + Println('Largest hex number is:', n.ToString('x')); + break; + end; + n -= magic; + end; +end. diff --git a/Task/Largest-proper-divisor-of-n/PascalABC.NET/largest-proper-divisor-of-n.pas b/Task/Largest-proper-divisor-of-n/PascalABC.NET/largest-proper-divisor-of-n.pas new file mode 100644 index 0000000000..647abc0431 --- /dev/null +++ b/Task/Largest-proper-divisor-of-n/PascalABC.NET/largest-proper-divisor-of-n.pas @@ -0,0 +1,5 @@ +## +function lpd(n: integer) := range((n / 2).Ceil, 1, -1).First(x -> n mod x = 0); + +for var n := 1 to 100 do + write(lpd(n):3, if n mod 10 = 0 then #10 else ''); diff --git a/Task/Last-Friday-of-each-month/PascalABC.NET/last-friday-of-each-month.pas b/Task/Last-Friday-of-each-month/PascalABC.NET/last-friday-of-each-month.pas new file mode 100644 index 0000000000..47e447bda8 --- /dev/null +++ b/Task/Last-Friday-of-each-month/PascalABC.NET/last-friday-of-each-month.pas @@ -0,0 +1,16 @@ +## +uses System; + +var year := ReadlnInteger('Enter year:'); +var date := new DateTime(year, 12, 31); + +var lastfridays := + (0..360) + .Select(x -> date.AddDays(-x)) + .where(x -> x.DayOfWeek = DayOfWeek.friday) + .GroupBy(x -> x.Month) + .Select(g -> g.First) + .Reverse; + +foreach var d in lastfridays do + writeln(d.Year, '-', d.Month, '-', d.Day); diff --git a/Task/Last-letter-first-letter/PascalABC.NET/last-letter-first-letter.pas b/Task/Last-letter-first-letter/PascalABC.NET/last-letter-first-letter.pas new file mode 100644 index 0000000000..f5a1935ff4 --- /dev/null +++ b/Task/Last-letter-first-letter/PascalABC.NET/last-letter-first-letter.pas @@ -0,0 +1,57 @@ +var + names: array of string := ( + 'audino', 'bagon', 'baltoy', 'banette', 'bidoof', + 'braviary', 'bronzor', 'carracosta', 'charmeleon', 'cresselia', + 'croagunk', 'darmanitan', 'deino', 'emboar', 'emolga', + 'exeggcute', 'gabite', 'girafarig', 'gulpin', 'haxorus', + 'heatmor', 'heatran', 'ivysaur', 'jellicent', 'jumpluff', + 'kangaskhan', 'kricketune', 'landorus', 'ledyba', 'loudred', + 'lumineon', 'lunatone', 'machamp', 'magnezone', 'mamoswine', + 'nosepass', 'petilil', 'pidgeotto', 'pikachu', 'pinsir', + 'poliwrath', 'poochyena', 'porygon2', 'porygonz', 'registeel', + 'relicanth', 'remoraid', 'rufflet', 'sableye', 'scolipede', + 'scrafty', 'seaking', 'sealeo', 'silcoon', 'simisear', + 'snivy', 'snorlax', 'spoink', 'starly', 'tirtouga', + 'trapinch', 'treecko', 'tyrogue', 'vigoroth', 'vulpix', + 'wailord', 'wartortle', 'whismur', 'wingull', 'yamask'); + +var + maxPathLength := 0; + maxPathLengthCount := 0; + maxPathExample := ''; + +procedure search(part: array of string; offset: integer); +begin + if (offset > maxPathLength) then + begin + maxPathLength := offset; + maxPathLengthCount := 1; + end + else if (offset = maxPathLength) then + begin + maxPathLengthCount += 1; + maxPathExample := ''; + foreach var i in (0..offset - 1) do + maxPathExample := maxpathexample + (if (i mod 5 = 0) then #10 else ' ') + part[i]; + end; + var lastChar := part[offset - 1].last; + foreach var i in (offset..part.Length - 1) do + if (part[i][1] = lastChar) then + begin + Swap(names[offset], names[i]); + search(names, offset + 1); + Swap(names[offset], names[i]); + end; +end; + +begin + foreach var i in (0..names.Length - 1) do + begin + Swap(names[0], names[i]); + search(names, 1); + Swap(names[0], names[i]); + end; + println('Maximum path length : ', maxPathLength); + println('Paths of that length : ', maxPathLengthCount); + println('Example path of that length : ', maxPathExample); +end. diff --git a/Task/Law-of-cosines---triples/PascalABC.NET/law-of-cosines---triples.pas b/Task/Law-of-cosines---triples/PascalABC.NET/law-of-cosines---triples.pas new file mode 100644 index 0000000000..8c73a2086b --- /dev/null +++ b/Task/Law-of-cosines---triples/PascalABC.NET/law-of-cosines---triples.pas @@ -0,0 +1,23 @@ +## +function issqr(n: integer) := n.Sqrt.Floor.sqr = n; + +var alltriples := (1..13).Cartesian(3).Where(x -> (x[0] <= x[1]) and (x[1] <= x[2])); + +var tri90 := alltriples.where(x -> x[0].sqr + x[1].sqr = x[2].sqr); +println('For an angle of 90 there are', tri90.count, 'solutions:'); +tri90.println; + +var tri60 := alltriples.Where(x -> (x[0].sqr + x[1].sqr - x[0] * x[1] = x[2].sqr) or + (x[0].sqr + x[2].sqr - x[0] * x[2] = x[1].sqr)); +println(#10, 'For an angle of 60 there are', tri60.count, 'solutions:'); +tri60.println; + +var tri120 := alltriples.Where(x -> x[0].sqr + x[1].sqr + x[0] * x[1] = x[2].sqr); +println(#10, 'For an angle of 120 there are', tri120.count, 'solutions:'); +tri120.println; + +var tri60notsame := (1..10_000) + .Combinations(2) + .Where(x -> issqr(x[0].sqr + x[1].sqr - x[0] * x[1])) + .Count; +println(#10, '60 degree triangle where sides are not equal, there are', tri60notsame, 'solutions'); diff --git a/Task/Leap-year/Uiua/leap-year.uiua b/Task/Leap-year/Uiua/leap-year.uiua new file mode 100644 index 0000000000..d2fba7928d --- /dev/null +++ b/Task/Leap-year/Uiua/leap-year.uiua @@ -0,0 +1 @@ +Leap ← ◿2/+=0◿100_400_4 diff --git a/Task/Leap-year/YAMLScript/leap-year.ys b/Task/Leap-year/YAMLScript/leap-year.ys index ef0b841aca..d26e73d558 100644 --- a/Task/Leap-year/YAMLScript/leap-year.ys +++ b/Task/Leap-year/YAMLScript/leap-year.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(year=2024): say: "$year is $when-not( diff --git a/Task/Left-factorials/Ada/left-factorials.ada b/Task/Left-factorials/Ada/left-factorials.ada new file mode 100644 index 0000000000..238684691c --- /dev/null +++ b/Task/Left-factorials/Ada/left-factorials.ada @@ -0,0 +1,76 @@ +-- Rosetta Code Task written in Ada +-- Left factorials +-- https://rosettacode.org/wiki/Left_factorials +-- (Mostly) translated from the AWK example +-- February 2025, R. B. E. +-- Using PragmARC.Unbounded_Numbers, GNAT version 14.2.0-3, MacOS 15.3, M1 chip + +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with PragmARC.Unbounded_Numbers.Integers; use PragmARC.Unbounded_Numbers.Integers; + +procedure Left_Factorials is + + function Left_Fact (F : Natural) return Unbounded_Integer is + Result : Unbounded_Integer := To_Unbounded_Integer (0); + Adder : Unbounded_Integer := To_Unbounded_Integer (1); + begin + if F = 0 then + return Result; + end if; + for K in 1..F loop + Result := Result + Adder; + Adder := Adder * To_Unbounded_Integer (K); + end loop; + return Result; + end Left_Fact; + + function Brute_Force_Digit_String_Length (N : in Unbounded_Integer) return Natural is + Big_Zero : constant Unbounded_Integer := To_Unbounded_Integer (0); + Big_Ten : constant Unbounded_Integer := To_Unbounded_Integer (10); + Local_N : Unbounded_Integer := N; + String_Length : Natural := 0; + begin + loop + exit when Local_N = Big_Zero; + Local_N := Local_N / Big_Ten; + String_Length := String_Length + 1; + end loop; + return String_Length; + end Brute_Force_Digit_String_Length; + +begin + for I in 0..10 loop + Put ("!"); + Put (I, 0); + Put (" = "); + Put (Image (Value => Left_Fact (I))); + New_Line; + end loop; + New_Line; + for I in 20..110 loop + if (I mod 10) = 0 then + Put ("!"); + Put (I, 0); + Put (" ="); + if I < 70 then + Put (" "); + else + New_Line; + end if; + Put (Image (Value => Left_Fact (I))); + New_Line; + end if; + end loop; + New_Line; + for I in 1_000..10_000 loop + if (I mod 1_000) = 0 then + Put ("!"); + Put (I, 0); + Put (" has "); + Put (Brute_Force_Digit_String_Length (Left_Fact (I)), 0); + Put_Line (" digits."); + end if; + end loop; + New_Line; +end Left_Factorials; diff --git a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx new file mode 100644 index 0000000000..7dde8a8542 --- /dev/null +++ b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx @@ -0,0 +1,32 @@ +Main: +include Settings +say version; say 'Legendre Prime counter (no memoization)'; say +numeric digits 10 +do n = 0 to 9 + call Time('r') + a = 10**n; p = pi(a) + say '10^'n Right(p,9) Format(Time('e'),3,3)'s' +end +exit + +Pi: +procedure expose prim. +arg xx +if xx < 3 then + return 0+(xx=2) +n = Primes(Isqrt(xx)) +return Phi(xx,n)+n-1 + +Phi: +procedure expose prim. +arg xx,yy +if yy < 2 then + return xx-(xx%2)*(yy=1) +p = prim.prime.yy +if xx <= p then + return 1 +return Phi(xx,yy-1)-Phi(xx%p,yy-1) + +include Abend +include Functions +include Sequences diff --git a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx new file mode 100644 index 0000000000..3ca9b25734 --- /dev/null +++ b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx @@ -0,0 +1,36 @@ +Main: +include Settings +say version; say 'Legendre Prime counter (with memoization)'; say +numeric digits 10 +do n = 0 to 9 + call Time('r') + a = 10**n; p = Pi(a) + say '10^'n Right(p,9) Format(Time('e'),3,3)'s' +end +exit + +Pi: +procedure expose prim. work. +arg xx +if xx < 3 then + return 0+(xx=2) +n = Primes(Isqrt(xx)) +work. = 0 +return Phi(xx,n)+n-1 + +Phi: +procedure expose prim. work. +arg xx,yy +if yy < 2 then + return xx-(xx%2)*(yy=1) +p = prim.prime.yy +if xx <= p then + return 1 +if work.xx.yy > 0 then + return work.xx.yy +work.xx.yy = Phi(xx,yy-1)-Phi(xx%p,yy-1) +return work.xx.yy + +include Abend +include Functions +include Sequences diff --git a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx new file mode 100644 index 0000000000..44c20aa6e8 --- /dev/null +++ b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx @@ -0,0 +1,14 @@ +Main: +include Settings +say version; say 'Legendre Prime counter (sieving)'; say +numeric digits 10 +do n = 0 to 8 + call Time('r') + a = 10**n; p = Primes(a) + say '10^'n Right(p,9) Format(Time('e'),3,3)'s' +end +exit + +include Abend +include Functions +include Sequences diff --git a/Task/Leonardo-numbers/ANSI-BASIC/leonardo-numbers.basic b/Task/Leonardo-numbers/ANSI-BASIC/leonardo-numbers.basic new file mode 100644 index 0000000000..1ea42efc8e --- /dev/null +++ b/Task/Leonardo-numbers/ANSI-BASIC/leonardo-numbers.basic @@ -0,0 +1,18 @@ +100 REM Leonardo numbers +110 DECLARE EXTERNAL SUB PrintLeonardoNums +120 CALL PrintLeonardoNums(1, 1, 1, 25, "Leonardo numbers") +130 CALL PrintLeonardoNums(0, 1, 0, 25, "Fibonacci numbers") +140 END +150 REM ** +160 EXTERNAL SUB PrintLeonardoNums(L0, L1, Sum, Lmt, What$) +170 PRINT What$; " ("; L0; ","; L1; ","; Sum; "):" +180 IF Lmt >= 1 THEN PRINT L0; +190 IF Lmt >= 2 THEN PRINT L1; +200 FOR I = 3 TO Lmt +210 PRINT L0 + L1 + Sum; +220 LET Tmp = L0 +230 LET L0 = L1 +240 LET L1 = Tmp + L1 + Sum +250 NEXT I +260 PRINT +270 END SUB diff --git a/Task/Leonardo-numbers/Forth/leonardo-numbers.fth b/Task/Leonardo-numbers/Forth/leonardo-numbers.fth new file mode 100644 index 0000000000..cd123f5fa7 --- /dev/null +++ b/Task/Leonardo-numbers/Forth/leonardo-numbers.fth @@ -0,0 +1,18 @@ +: leonardo-next ( n1 n2 n3 -- n1 n1+n2+n3 n2 ) + swap dup >r + over + r> ; + +: leonardo-print ( n1 n2 n3 u -- ) + 0 do + dup . + leonardo-next + loop + drop 2drop ; + +: main ( -- ) + ." First 25 Leonardo numbers:" cr + 1 1 1 25 leonardo-print cr + ." First 25 Fibonacci numbers:" cr + 0 1 0 25 leonardo-print cr ; + +main +bye diff --git a/Task/Leonardo-numbers/Free-Pascal-Lazarus/leonardo-numbers.pas b/Task/Leonardo-numbers/Free-Pascal-Lazarus/leonardo-numbers.pas new file mode 100644 index 0000000000..2e6ff3a2e9 --- /dev/null +++ b/Task/Leonardo-numbers/Free-Pascal-Lazarus/leonardo-numbers.pas @@ -0,0 +1,28 @@ +program LeonardoNumbers; + + procedure WriteLeonardoNums(L0, L1: longint; Sum: integer; + Lmt: integer; What: string); + var + I: integer; + Tmp: longint; + begin + WriteLn(What, ' (', L0, ', ', L1, ', ', Sum, '):'); + if Lmt >= 1 then + Write(L0, ' '); + if Lmt >= 2 then + Write(L1, ' '); + for I := 3 to Lmt do + begin + Write(L0 + L1 + Sum, ' '); + Tmp := L0; + L0 := L1; + L1 := Tmp + L1 + Sum; + end; + WriteLn; + end; + +begin + WriteLeonardoNums(1, 1, 1, 25, 'Leonardo numbers'); + WriteLeonardoNums(0, 1, 0, 25, 'Fibonacci numbers'); + ReadLn; +end. diff --git a/Task/Leonardo-numbers/GW-BASIC/leonardo-numbers.basic b/Task/Leonardo-numbers/GW-BASIC/leonardo-numbers.basic new file mode 100644 index 0000000000..8ba8a56228 --- /dev/null +++ b/Task/Leonardo-numbers/GW-BASIC/leonardo-numbers.basic @@ -0,0 +1,17 @@ +10 REM Leonardo numbers +20 LIMIT = 25 +30 L0 = 1: L1 = 1: SUMA = 1 +40 PRINT "Numeros de Leonardo (";L0;",";L1;",";SUMA;"):" +50 GOSUB 100 +60 L0 = 0: L1 = 1: SUMA = 0 +70 PRINT "Numeros de Fibonacci (";L0;",";L1;",";SUMA;"):" +80 GOSUB 100 +90 END +100 IF LIMIT >= 1 THEN PRINT L0; +110 IF LIMIT >= 2 THEN PRINT L1; +120 FOR I = 3 TO LIMIT +130 PRINT L0 + L1 + SUMA; +140 TMP = L0: L0 = L1: L1 = TMP + L1 + SUMA +150 NEXT I +160 PRINT +170 RETURN diff --git a/Task/Leonardo-numbers/Julia/leonardo-numbers.jl b/Task/Leonardo-numbers/Julia/leonardo-numbers.jl index 6e51c6ec38..0960ca32bc 100644 --- a/Task/Leonardo-numbers/Julia/leonardo-numbers.jl +++ b/Task/Leonardo-numbers/Julia/leonardo-numbers.jl @@ -1,18 +1,12 @@ -function L(n, add::Int=1, firsts::Vector=[1, 1]) - l = max(maximum(n) .+ 1, length(firsts)) - r = Vector{Int}(l) - r[1:length(firsts)] = firsts - for i in 3:l - r[i] = r[i - 1] + r[i - 2] + add +function leonardo(first::Int, second::Int, add::Int, amount::Int) + nums = [first, second] + for i in 3:amount + append!(nums, nums[i-1] + nums[i-2] + add) end - return r[n .+ 1] + return nums end -# Task 1 -println("First 25 Leonardo numbers: ", join(L(0:24), ", ")) - -# Task 2 -@show L(0) L(1) - -# Task 4 -println("First 25 Leonardo numbers starting with [0, 1]: ", join(L(0:24, 0, [0, 1]), ", ")) +println("First 25 Leonardo numbers with L1 = 1 L2 = 1 and add number = 1 :") +println(leonardo(1,1,1,25)) +println("First 25 Leonardo numbers with L1 = 0 L2 = 1 and add number = 0 :") +println(leonardo(1,1,0,25)) diff --git a/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-1.m2000 b/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-1.m2000 new file mode 100644 index 0000000000..15c7e89c68 --- /dev/null +++ b/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-1.m2000 @@ -0,0 +1,28 @@ +Module Leonardo_Task { + base1=lambda (l0 as decimal,l1 as decimal,add as decimal)->{ + a=list:=0:=l0,1:=l1 + =lambda a, add (i as decimal) ->{ + i=int(i)-1 + if i<0 then =a(0) exit + if not exist(a, i) then + do + j=len(a) + Append a, j:=a(j-1)+a(j-2)+add + j++ + until j>i + end if + =a(i) + } + } + leonardo=base1(1,1,1) + for i=1 to 25 + ? leonardo(i)+" "; + next + print + fibonacci=base1(0,1,0) + for i=1 to 25 + ? fibonacci(i)+" "; + next + print +} +Leonardo_Task diff --git a/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-2.m2000 b/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-2.m2000 new file mode 100644 index 0000000000..4cab1f216d --- /dev/null +++ b/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-2.m2000 @@ -0,0 +1,20 @@ +base1=lambda (l0 as decimal=1, l1 as decimal=1, add as decimal=1)-> { + ret=stack:=l0, l1 + = lambda l0, l1, add, ret (x as long)->{ + z=x + x-=len(ret) + stack ret { + while x>0 + push l1: l1+=l0+add:read l0 + data l1 ' at the end + x-- + end while + } + ' stack up ret, z Return z members from ret + =array(stack up ret, z) + } +} +Leonardo=base1() +Print Leonardo(25)#str$(" ") +fibonacci=base1(0,1,0) +Print fibonacci(25)#str$(" ") diff --git a/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-3.m2000 b/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-3.m2000 new file mode 100644 index 0000000000..210650ff91 --- /dev/null +++ b/Task/Leonardo-numbers/M2000-Interpreter/leonardo-numbers-3.m2000 @@ -0,0 +1,74 @@ +class Leonardo { + events "export", "exportdone" + decimal l0=1, l1=1, add=1 + ret=stack + module take (x as long){ + while x>0 + if len(.ret)=0 then + push .l1: .l1+=.l0+.add:read .l0 + callevent(&.l1) + else + stack .ret { + read a + callevent(&a) + } + end if + x-- + end while + sub callevent(&v) + if x>1 then + call event "export", v + else + call event "exportdone", v + end if + end sub + } +class: + module Leonardo (.l0, .l1, .add) { + stack .ret {data .l0, .l1} + } +} +Module Solution1 { + group withevents Leonardo=Leonardo() + group withevents Fibonacci=Leonardo(0,1,0) + function leonardo_export { + Print number+" "; + } + function leonardo_exportdone { + Print number + } + function fibonacci_export { + Print number+" "; + } + function fibonacci_exportdone { + Print number + } + Leonardo.take 25 + Fibonacci.take 25 +} +Solution1 +Module Solution2 { + group withevents Leonardo=Leonardo() + group withevents Fibonacci=Leonardo(0,1,0) + ret=stack + function leonardo_export { + read new Value + stack ret {data value} + } + function leonardo_exportdone { + call local leonardo_export() + Print array(ret)#str$(" ") + } + function fibonacci_export { + call local leonardo_export() + } + function fibonacci_exportdone { + call local leonardo_exportdone() + } + module dosomething(&ThatObject as Leonardo){ + ThatObject.take 25 + } + dosomething &Leonardo + dosomething &Fibonacci +} +Solution2 diff --git a/Task/Leonardo-numbers/MSX-Basic/leonardo-numbers.basic b/Task/Leonardo-numbers/MSX-Basic/leonardo-numbers.basic index f5644d9dc6..b259dec2bf 100644 --- a/Task/Leonardo-numbers/MSX-Basic/leonardo-numbers.basic +++ b/Task/Leonardo-numbers/MSX-Basic/leonardo-numbers.basic @@ -1,17 +1,18 @@ -100 LIMIT = 25 -110 L0 = 1 -120 L1 = 1 -130 SUMA = 1 -140 PRINT "Numeros de Leonardo (";L0;",";L1;",";SUMA;"):" -150 GOSUB 220 -160 LET L0 = 0 -170 LET L1 = 1 -180 LET SUMA = 0 -190 PRINT "Numeros de Fibonacci (";L0;",";L1;",";SUMA;"):" -200 GOSUB 220 -210 END -220 FOR I = 1 TO LIMIT -230 IF I = 1 THEN PRINT L0; : ELSE IF I = 2 THEN PRINT L1; : ELSE PRINT L0+L1+SUMA; : TMP = L0 : L0 = L1 : L1 = TMP+L1+SUMA -240 NEXT I -250 PRINT CHR$(10) -260 RETURN +10 REM Leonardo numbers +20 LIMIT = 25 +30 L0 = 1: L1 = 1: SUMA = 1 +40 PRINT "Numeros de Leonardo (";L0;",";L1;",";SUMA;"):" +50 GOSUB 100 +60 L0 = 0: L1 = 1: SUMA = 0 +70 PRINT "Numeros de Fibonacci (";L0;",";L1;",";SUMA;"):" +80 GOSUB 100 +90 END +100 IF LIMIT >= 1 THEN PRINT L0; +110 IF LIMIT >= 2 THEN PRINT L1; +120 IF LIMIT < 3 THEN 170: REM In MSX, FOR works like REPEAT +130 FOR I = 3 TO LIMIT +140 PRINT L0 + L1 + SUMA; +150 TMP = L0: L0 = L1: L1 = TMP + L1 + SUMA +160 NEXT I +170 PRINT +180 RETURN diff --git a/Task/Leonardo-numbers/Miranda/leonardo-numbers.miranda b/Task/Leonardo-numbers/Miranda/leonardo-numbers.miranda new file mode 100644 index 0000000000..bb34711b03 --- /dev/null +++ b/Task/Leonardo-numbers/Miranda/leonardo-numbers.miranda @@ -0,0 +1,18 @@ +main :: [sys_message] +main = [Stdout "First 25 Leonardo numbers:\n", + Stdout (tab 5 10 (take 25 (leo 1 1 1))), + Stdout "\nFirst 25 Fibonacci numbers:\n", + Stdout (tab 5 10 (take 25 (leo 0 1 0)))] + +tab :: num->num->[num]->[char] +tab w cw = lay . map (concat . map (rjustify cw . shownum)) . group w + +group :: num->[*]->[[*]] +group n [] = [] +group n ls = take n ls:group n (drop n ls) + +leo :: num->num->num->[num] +leo s0 s1 add + = ks + where ks = s0 : s1 : map step (zip2 ks (tl ks)) + step (a,b) = a + b + add diff --git a/Task/Leonardo-numbers/PHP/leonardo-numbers.php b/Task/Leonardo-numbers/PHP/leonardo-numbers.php new file mode 100644 index 0000000000..8355af37a0 --- /dev/null +++ b/Task/Leonardo-numbers/PHP/leonardo-numbers.php @@ -0,0 +1,21 @@ += 1) + echo($l0.' '); + if ($lmt >= 2) + echo($l1.' '); + for ($i = 3; $i <= $lmt; $i++) { + echo(($l0 + $l1 + $sum).' '); + $tmp = $l0; + $l0 = $l1; + $l1 = $tmp + $l1 + $sum; + } + echo(PHP_EOL); +} + +echo_Leonardo_nums(1, 1, 1, 25, 'Leonardo numbers'); +echo_Leonardo_nums(0, 1, 0, 25, 'Fibonacci numbers'); +?> diff --git a/Task/Leonardo-numbers/PascalABC.NET/leonardo-numbers.pas b/Task/Leonardo-numbers/PascalABC.NET/leonardo-numbers.pas new file mode 100644 index 0000000000..f7a472e7bf --- /dev/null +++ b/Task/Leonardo-numbers/PascalABC.NET/leonardo-numbers.pas @@ -0,0 +1,12 @@ +## +function Leonardo(L0: integer; L1: integer; add: integer): sequence of integer; +begin + while (true) do + begin + yield L0; + (L0, L1) := (L1, L0 + L1 + add); + end; +end; + +Leonardo(1, 1, 1).Take(25).println; +Leonardo(0, 1, 0).Take(25).println; diff --git a/Task/Leonardo-numbers/QBasic/leonardo-numbers.basic b/Task/Leonardo-numbers/QBasic/leonardo-numbers.basic index 7fa50be328..b6daa7ccfc 100644 --- a/Task/Leonardo-numbers/QBasic/leonardo-numbers.basic +++ b/Task/Leonardo-numbers/QBasic/leonardo-numbers.basic @@ -1,25 +1,20 @@ +REM Leonardo numbers DECLARE SUB leonardo (L0!, L1!, suma!, texto$) CONST limit = 25 -CALL leonardo(1, 1, 1, "Leonardo") -CALL leonardo(0, 1, 0, "Fibonacci") +CALL leonardo(1, 1, 1, "Numeros de Leonardo") +CALL leonardo(0, 1, 0, "Numeros de Fibonacci") END SUB leonardo (L0, L1, suma, texto$) - PRINT "Numeros de "; texto$; " ("; L0; ","; L1; ","; suma; "):" - FOR i = 1 TO limit - IF i = 1 THEN - PRINT L0; - ELSE - IF i = 2 THEN - PRINT L1; - ELSE - PRINT L0 + L1 + suma; - LET tmp = L0 - LET L0 = L1 - LET L1 = tmp + L1 + suma - END IF - END IF + PRINT texto$; " ("; L0; ","; L1; ","; suma; "):" + IF limit >= 1 THEN PRINT L0; + IF limit >= 2 THEN PRINT L1; + FOR i = 3 TO limit + PRINT L0 + L1 + suma; + LET tmp = L0 + LET L0 = L1 + LET L1 = tmp + L1 + suma NEXT i - PRINT CHR$(10) + PRINT END SUB diff --git a/Task/Leonardo-numbers/Tiny-BASIC/leonardo-numbers.basic b/Task/Leonardo-numbers/Tiny-BASIC/leonardo-numbers.basic new file mode 100644 index 0000000000..5b7e034c1b --- /dev/null +++ b/Task/Leonardo-numbers/Tiny-BASIC/leonardo-numbers.basic @@ -0,0 +1,27 @@ +10 REM Leonardo numbers +20 N=21 +30 K=1 +40 L=1 +50 S=1 +60 PRINT "Leonardo numbers (";K;", ";L;", ";S;"):" +70 GOSUB 140 +80 K=0 +90 L=1 +100 S=0 +110 PRINT "Fibonacci numbers (";K;", ";L;", ";S;"):" +120 GOSUB 140 +130 END +140 IF N<1 GOTO 260 +150 PRINT K;" "; +160 IF N<2 GOTO 260 +170 PRINT L;" "; +180 I=3 +190 IF I>N GOTO 260 +200 PRINT K+L+S;" "; +210 T=K +220 K=L +230 L=T+L+S +240 I=I+1 +250 GOTO 190 +260 PRINT +270 RETURN diff --git a/Task/Leonardo-numbers/True-BASIC/leonardo-numbers.basic b/Task/Leonardo-numbers/True-BASIC/leonardo-numbers.basic index f5c382a85a..b3de9ef13d 100644 --- a/Task/Leonardo-numbers/True-BASIC/leonardo-numbers.basic +++ b/Task/Leonardo-numbers/True-BASIC/leonardo-numbers.basic @@ -1,23 +1,17 @@ SUB leonardo (L0, L1, suma, texto$) - PRINT "Numeros de "; texto$; " ("; L0; ","; L1; ","; suma; "):" - FOR i = 1 TO limit - IF i = 1 THEN - PRINT L0; - ELSE - IF i = 2 THEN - PRINT L1; - ELSE - PRINT L0 + L1 + suma; - LET tmp = L0 - LET L0 = L1 - LET L1 = tmp + L1 + suma - END IF - END IF + PRINT texto$; " ("; L0; ","; L1; ","; suma; "):" + IF limit >= 1 THEN PRINT L0; + IF limit >= 2 THEN PRINT L1; + FOR i = 3 TO LIMIT + PRINT L0 + L1 + suma; + LET tmp = L0 + LET L0 = L1 + LET L1 = tmp + L1 + suma NEXT i - PRINT CHR$(10) + PRINT END SUB LET limit = 25 -CALL leonardo(1, 1, 1, "Leonardo") -CALL leonardo(0, 1, 0, "Fibonacci") +CALL leonardo(1, 1, 1, "Numeros de Leonardo") +CALL leonardo(0, 1, 0, "Numeros de Fibonacci") END diff --git a/Task/Leonardo-numbers/TypeScript/leonardo-numbers.ts b/Task/Leonardo-numbers/TypeScript/leonardo-numbers.ts new file mode 100644 index 0000000000..f427eabcad --- /dev/null +++ b/Task/Leonardo-numbers/TypeScript/leonardo-numbers.ts @@ -0,0 +1,15 @@ +function leoNums( + n: number, + L0: number = 1, + L1: number = 1, + add: number = 1 +): number[] { + const lNums: number[] = [L0, L1]; + while (lNums.length < n) { + lNums.push(lNums[lNums.length - 1] + lNums[lNums.length - 2] + add); + } + return lNums +} + +console.log(leoNums(25)) +console.log(leoNums(25, 0, 1, 0)) diff --git a/Task/Letter-frequency/Crystal/letter-frequency.cr b/Task/Letter-frequency/Crystal/letter-frequency.cr new file mode 100644 index 0000000000..85fa5f979d --- /dev/null +++ b/Task/Letter-frequency/Crystal/letter-frequency.cr @@ -0,0 +1,3 @@ +File.open("les_miserables.txt") do |f| + pp f.each_char.select(&.letter?).tally.to_a.sort_by {|k,v| -v} +end diff --git a/Task/Letter-frequency/Langur/letter-frequency.langur b/Task/Letter-frequency/Langur/letter-frequency.langur index c21156b15c..c33f892e23 100644 --- a/Task/Letter-frequency/Langur/letter-frequency.langur +++ b/Task/Letter-frequency/Langur/letter-frequency.langur @@ -1,8 +1,8 @@ val countLetters = fn(s) { - for[={:}] s2 in split(replace(s, RE/\P{L}/)) { + for[={:}] s2 in split(replace(s, by=RE/\P{L}/)) { _for[s2; 0] += 1 } } val counts = countLetters(readfile("./fuzz.txt")) -writeln join("\n", map(fn(k) { "{{k}}: {{counts[k]}}" }, keys(counts))) +writeln join(map(keys(counts), by=fn(k) { "{{k}}: {{counts[k]}}" }), by="\n") diff --git a/Task/Levenshtein-distance/PascalABC.NET/levenshtein-distance.pas b/Task/Levenshtein-distance/PascalABC.NET/levenshtein-distance.pas new file mode 100644 index 0000000000..7a638fe782 --- /dev/null +++ b/Task/Levenshtein-distance/PascalABC.NET/levenshtein-distance.pas @@ -0,0 +1,23 @@ +## +function levenshteinDistance(s1, s2: string): integer; +begin + if s1.Length > s2.Length then swap(s1, s2); + + var distances := Range(0, s1.Length).ToList; + + foreach var c2 in s2 index i2 do + begin + var newDistances := Lst(i2 + 1); + foreach var c1 in s1 index i1 do + if c1 = c2 then + newDistances.Add(distances[i1]) + else + newDistances.Add(1 + Min(distances[i1], distances[i1 + 1], newDistances[^1])); + + distances := newDistances; + end; + result := distances[^1]; +end; + +levenshteinDistance('kitten', 'sitting').println; +levenshteinDistance('rosettacode', 'raisethysword').println; diff --git a/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac b/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac index f905a3c8bf..7677c8f4b3 100644 --- a/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac +++ b/Task/Linear-congruential-generator/EDSAC-order-code/linear-congruential-generator.edsac @@ -12,12 +12,13 @@ 55 locations, load at even address. Set up to be called with 'G N', so that caller needn't know its address. See Wilkes, Wheeler & Gill, 1951 edition, page 18.] + [2024-12-22 Fixed bug in print subroutine. Did not affect Rosetta Code output.] T 46 K [location corresponding to N parameter] P 72 F [load subroutine at 72] E 25 K TN - GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF - H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@ - A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@ + GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TFH17@ + S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@A1FA43@ + G20@XFT44#ZPFT43ZP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@ [BSD linear congruential generator. Call with 'G B' to initialize, passing seed in 0D. diff --git a/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas b/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas index ca4342fc87..050110505e 100644 --- a/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas +++ b/Task/Linear-congruential-generator/PascalABC.NET/linear-congruential-generator-2.pas @@ -18,22 +18,12 @@ end; begin 'BSD with seed = 1'.println; - var count := 0; var iter1 := bsdRand(1); - foreach var val in iter1 do - begin + foreach var val in iter1.Take(10) do println(val); - count += 1; - if count = 10 then break; - end; println; 'Microsoft with seed = 0'.Println; - count := 0; var iter2 := msvcrtRand(0); - foreach var val in iter2 do - begin + foreach var val in iter2.Take(10) do println(val); - count += 1; - if count = 10 then break; - end; end. diff --git a/Task/Literals-Floating-point/68000-Assembly/literals-floating-point.68000 b/Task/Literals-Floating-point/68000-Assembly/literals-floating-point.68000 index 646ae7abc4..05c33c6daf 100644 --- a/Task/Literals-Floating-point/68000-Assembly/literals-floating-point.68000 +++ b/Task/Literals-Floating-point/68000-Assembly/literals-floating-point.68000 @@ -1,2 +1,11 @@ -Pi: -DC.L $40490FDB + fmovecr.x #0,fp0 ; now fp0 contains pi + fmovecr.x #$0c,fp1 ; now fp1 contains e + + ; you can also define constants in several formats +extended: dc.x 2.0 ; extended precision, 80-bits in the FPU but stored as 96-bits in memory +doublep: dc.d 2.0 ; 64-bit double precision +singlep: dc.s 2.0 ; 32-bit single precision +packedbcd: dc.p 2.0 ; a 96-bit packed BCD format + + ; they can be loaded with the corresponding instructions, e.g. + fmove.p packedbcd,fp2 diff --git a/Task/Literals-Floating-point/Uiua/literals-floating-point.uiua b/Task/Literals-Floating-point/Uiua/literals-floating-point.uiua new file mode 100644 index 0000000000..236d7824cb --- /dev/null +++ b/Task/Literals-Floating-point/Uiua/literals-floating-point.uiua @@ -0,0 +1,5 @@ +2.3 # Standard floating-point literal +0.3e34 # Short floating-point +1/3 # Uiua can work with repeating decimals +1/24 # Another example of the above +2 # Uiua only has 4 types - all non-complex numbers are floats diff --git a/Task/Literals-Integer/PascalABC.NET/literals-integer.pas b/Task/Literals-Integer/PascalABC.NET/literals-integer.pas new file mode 100644 index 0000000000..6bc28e8439 --- /dev/null +++ b/Task/Literals-Integer/PascalABC.NET/literals-integer.pas @@ -0,0 +1,5 @@ +const + dec = 16; + hex = $ff; + sep = 1_000_000; + big = 123456789bi; // big integer, unrestricted diff --git a/Task/Logical-operations/Langur/logical-operations.langur b/Task/Logical-operations/Langur/logical-operations.langur index ef567db8c9..3d876cab21 100644 --- a/Task/Logical-operations/Langur/logical-operations.langur +++ b/Task/Logical-operations/Langur/logical-operations.langur @@ -1,5 +1,5 @@ val test = fn(a, b) { - join("\n", [ + join([ "not {{a}}: {{not a}}", "{{a}} and {{b}}: {{a and b}}", "{{a}} nand {{b}}: {{a nand b}}", @@ -17,7 +17,8 @@ val test = fn(a, b) { "{{a}} xor? {{b}}: {{a xor? b}}", "{{a}} nxor? {{b}}: {{a nxor? b}}", "\n", - ]) + ], + by="\n") } val tests = [ diff --git a/Task/Logistic-curve-fitting-in-epidemiology/PascalABC.NET/logistic-curve-fitting-in-epidemiology.pas b/Task/Logistic-curve-fitting-in-epidemiology/PascalABC.NET/logistic-curve-fitting-in-epidemiology.pas new file mode 100644 index 0000000000..45552e0964 --- /dev/null +++ b/Task/Logistic-curve-fitting-in-epidemiology/PascalABC.NET/logistic-curve-fitting-in-epidemiology.pas @@ -0,0 +1,63 @@ +const + K = 7.8e9; + N0 = 27; + Actual = + |27.0, 27.0, 27.0, 44.0, 44.0, 59.0, 59.0, + 59.0, 59.0, 59.0, 59.0, 59.0, 59.0, 60.0, + 60.0, 61.0, 61.0, 66.0, 83.0, 219.0, 239.0, + 392.0, 534.0, 631.0, 897.0, 1350.0, 2023.0, 2820.0, + 4587.0, 6067.0, 7823.0, 9826.0, 11946.0, 14554.0, 17372.0, + 20615.0, 24522.0, 28273.0, 31491.0, 34933.0, 37552.0, 40540.0, + 43105.0, 45177.0, 60328.0, 64543.0, 67103.0, 69265.0, 71332.0, + 73327.0, 75191.0, 75723.0, 76719.0, 77804.0, 78812.0, 79339.0, + 80132.0, 80995.0, 82101.0, 83365.0, 85203.0, 87024.0, 89068.0, + 90664.0, 93077.0, 95316.0, 98172.0, 102133.0, 105824.0, 109695.0, + 114232.0, 118610.0, 125497.0, 133852.0, 143227.0, 151367.0, 167418.0, + 180096.0, 194836.0, 213150.0, 242364.0, 271106.0, 305117.0, 338133.0, + 377918.0, 416845.0, 468049.0, 527767.0, 591704.0, 656866.0, 715353.0, + 777796.0, 851308.0, 928436.0, 1000249.0, 1082054.0, 1174652.0|; + +function f(r: real): real; +begin + foreach var i in (0..Actual.length - 1) do + begin + var eri := exp(r * i); + var guess := (N0 * eri) / (1 + N0 * (eri - 1) / K); + var diff := guess - Actual[i]; + result += diff * diff; + end; +end; + +function solve(fn: (real) -> real; guess: real := 0.5; epsilon: real := 0.0): real; +begin + result := guess; + var delta := if result <> 0 then result else 1.0; + var f0 := fn(result); + var factor := 2.0; + + while (delta > epsilon) and (result <> result - delta) do + begin + var nf := fn(result - delta); + if nf < f0 then + begin + f0 := nf; + result -= delta; + end + else + nf := fn(result + delta); + if nf < f0 then + begin + f0 := nf; + result += delta; + end + else + factor := 0.5; + delta *= factor; + end; +end; + +begin + var r := solve(f); + var r0 := exp(12 * r); + writeln('r = ', r, ', R0 = ', r0); +end. diff --git a/Task/Long-literals-with-continuations/PascalABC.NET/long-literals-with-continuations.pas b/Task/Long-literals-with-continuations/PascalABC.NET/long-literals-with-continuations.pas new file mode 100644 index 0000000000..399260f878 --- /dev/null +++ b/Task/Long-literals-with-continuations/PascalABC.NET/long-literals-with-continuations.pas @@ -0,0 +1,33 @@ +const + RevDate = '2024-12-28'; + + elementStr = ''' + hydrogen helium lithium beryllium boron carbon + nitrogen oxygen fluorine neon sodium magnesium + aluminum silicon phosphorous sulfur chlorine argon + potassium calcium scandium titanium vanadium chromium + manganese iron cobalt nickel copper zinc + gallium germanium arsenic selenium bromine krypton + rubidium strontium yttrium zirconium niobium molybdenum + technetium ruthenium rhodium palladium silver cadmium + indium tin antimony tellurium iodine xenon + cesium barium lanthanum cerium praseodymium neodymium + promethium samarium europium gadolinium terbium dysprosium + holmium erbium thulium ytterbium lutetium hafnium + tantalum tungsten rhenium osmium iridium platinum + gold mercury thallium lead bismuth polonium + astatine radon francium radium actinium thorium + protactinium uranium neptunium plutonium americium curium + berkelium californium einsteinium fermium mendelevium nobelium + lawrencium rutherfordium dubnium seaborgium bohrium hassium + meitnerium darmstadtium roentgenium copernicium nihonium flerovium + moscovium livermorium tennessine oganesson +'''; + + elements = elementstr.towords(|#10, #13, ' '|); + +begin + println('Last revision date: ', RevDate); + println('Number of elements: ', Elements.count); + println('Last element in list: ', Elements[^1]); +end. diff --git a/Task/Long-multiplication/M2000-Interpreter/long-multiplication.m2000 b/Task/Long-multiplication/M2000-Interpreter/long-multiplication.m2000 new file mode 100644 index 0000000000..d2a0f992bd --- /dev/null +++ b/Task/Long-multiplication/M2000-Interpreter/long-multiplication.m2000 @@ -0,0 +1,18 @@ +function placecoma(a as string) { + if len(a)<4 then =a :exit + k=StrRev$(a) + a="" + for i=4 to len(k) step 3 + a+=mid$(k,i-3, 3)+"," + next + a+=mid$(k, i-3) + a=strrev$(a) + if left$(a,1)="," then =mid$(a,2) else =a +} + +a=bigInteger("2") +'method a, "intpower", biginteger("128") as a +method a, "intpower", biginteger("64") as a +method a, "multiply", a as a +with a,"tostring" as a.tostring +Print placecoma(a.tostring) diff --git a/Task/Long-multiplication/PascalABC.NET/long-multiplication.pas b/Task/Long-multiplication/PascalABC.NET/long-multiplication.pas new file mode 100644 index 0000000000..2356f7c57f --- /dev/null +++ b/Task/Long-multiplication/PascalABC.NET/long-multiplication.pas @@ -0,0 +1,56 @@ +function longmulti(a, b: string): string; +begin + var i := 0; + var j := 0; + var k := false; + + // either is zero, return "0" + if (a = '0') or (b = '0') then + begin + result := '0'; + exit; + end; + + // see if either a or b is negative + if a[1] = '-' then + begin + i := 2; + k := not k; + end; + if b[1] = '-' then + begin + j := 2; + k := not k; + end; + + // if yes, prepend minus sign if needed and skip the sign + if (i > 1) or (j > 1) then + begin + result := if k then '-' else ''; + result += longmulti(a[i:a.Length + 1], b[j:b.Length + 1]); + exit; + end; + + result := '0' * (a.length + b.length); + + for var ii := a.length downto 1 do + begin + var carry := 0; + var kk := ii + b.length; + for var jj := b.length downto 1 do + begin + var n := a[ii].todigit * b[jj].todigit + result[kk].todigit + carry; + carry := n div 10; + result[kk] := chr(n mod 10 + ord('0')); + dec(kk); + end; + result[kk] := chr(ord(result[kk]) + carry); + end; + + if result[1] = '0' then + result[1:result.length] := result[2:result.length + 1]; +end; + +begin + longmulti('-18446744073709551616', '-18446744073709551616').println; +end. diff --git a/Task/Long-primes/PascalABC.NET/long-primes.pas b/Task/Long-primes/PascalABC.NET/long-primes.pas new file mode 100644 index 0000000000..53de556a3d --- /dev/null +++ b/Task/Long-primes/PascalABC.NET/long-primes.pas @@ -0,0 +1,34 @@ +function gen_primes_upto(n: integer): sequence of integer; +begin + if n < 3 then exit; + var table := |True| * n; + var sqrtn := n.sqrt.Floor; + for var i := 2 to sqrtn do + if table[i] then + for var j := i * i to n - 1 step i do + table[j] := False; + + yield 2; + for var i := 3 to n step 2 do + if table[i] then yield i +end; + +function period(n: integer): integer; +begin + var r := 1; + repeat + r := r * 10 mod n; + result += 1; + until r <= 1; +end; + +begin + writeln('The long primes up to 500 are:'); + var primes := Gen_primes_upto(64000).Skip(1); + primes.Where(x -> (x < 500) and (period(x) = x - 1)).Println; + writeln; + + writeln('The number of long primes up to:'); + foreach var n in |500, 1000, 2000, 4000, 8000, 16000, 32000, 64000| do + writeln(n:6, ' is ', primes.Where(x -> (x < n) and (period(x) = x - 1)).Count); +end. diff --git a/Task/Long-year/PascalABC.NET/long-year.pas b/Task/Long-year/PascalABC.NET/long-year.pas new file mode 100644 index 0000000000..58d177492f --- /dev/null +++ b/Task/Long-year/PascalABC.NET/long-year.pas @@ -0,0 +1,11 @@ +## +uses System; + +function islongyear(year: integer): boolean; +begin + var startdate := new DateTime(year, 1, 1); + var enddate := new DateTime(year, 12, 31); + result := (startdate.DayOfWeek = DayOfWeek.Thursday) or (enddate.DayOfWeek = DayOfWeek.Thursday) +end; + +(2000..2100).Where(y -> islongyear(y)).Println; diff --git a/Task/Longest-common-subsequence/Jq/longest-common-subsequence-4.jq b/Task/Longest-common-subsequence/Jq/longest-common-subsequence-4.jq new file mode 100644 index 0000000000..39f6e8f6d9 --- /dev/null +++ b/Task/Longest-common-subsequence/Jq/longest-common-subsequence-4.jq @@ -0,0 +1,42 @@ +# Create an m x n matrix +def matrix(m; n; init): + if m == 0 then [] + elif m == 1 + then [[range(0;n) | init]] + elif m > 0 + then [range(0;n) | init] as $row + | [range(0;m) | $row ] + else error("matrix\(m);_;_) invalid") + end; + +def lcs($a; $b): + {lengths: matrix(1+($a|length); 1+($b|length); 0)} + # row 0 and column 0 are initialized to 0 already + | reduce range(0; $a|length) as $i (.; + $a[$i:$i+1] as $x + | reduce range(0; $b|length) as $j (.; + $b[$j:$j+1] as $y + | if $x == $y + then .lengths[$i+1][$j+1] = .lengths[$i][$j] + 1 + else .lengths[$i+1][$j+1] = ([.lengths[$i+1][$j], .lengths[$i][$j+1]] | max) + end )) + # read out the substring from the matrix + |.result = "" + | .x = ($a|length) + | .y = ($b|length) + | until( .x <= 0 or .y <= 0; + if .lengths[.x][.y] == .lengths[.x-1][.y] + then .x -= 1 + elif .lengths[.x][.y] == .lengths[.x][.y-1] + then .y -= 1 + else + # debug(".x is \(.x) => \($a[.x-1:.x])") + .result = $a[.x-1:.x] + .result + | .x -= 1 + | .y -= 1 + end ) + | .result ; + +lcs("1234"; "1224533324"), +lcs("thisisatest"; "testing123testing"), +lcs("thisisatest" * 4; "testing123testing" * 4) diff --git a/Task/Longest-common-substring/Langur/longest-common-substring.langur b/Task/Longest-common-substring/Langur/longest-common-substring.langur index 951978e86f..368bb54b25 100644 --- a/Task/Longest-common-substring/Langur/longest-common-substring.langur +++ b/Task/Longest-common-substring/Langur/longest-common-substring.langur @@ -2,7 +2,7 @@ val lcs = fn(s1, s2) { var l, r, sublen = 1, 0, 0 for i of s1 { for j in i .. len(s1) { - if not matching(s2s(s1, i .. j), s2): break + if not matching(s2, by=s2s(s1, of=i .. j)): break if sublen <= j - i { l, r = i, j sublen = j - i @@ -10,7 +10,7 @@ val lcs = fn(s1, s2) { } } if r == 0: return "" - s2s s1, l .. r + s2s s1, of=l .. r } writeln lcs("thisisatest", "testing123testing") diff --git a/Task/Longest-common-substring/PascalABC.NET/longest-common-substring.pas b/Task/Longest-common-substring/PascalABC.NET/longest-common-substring.pas new file mode 100644 index 0000000000..44f677a397 --- /dev/null +++ b/Task/Longest-common-substring/PascalABC.NET/longest-common-substring.pas @@ -0,0 +1,21 @@ +## +function lcs(s1, s2: string): String; +begin + var l := 1; + var r := 0; + var sub_len := 0; + for var i := 1 to s1.length do + foreach var j in (i..s1.length) do + begin + if s2.contains(s1[i:j + 1]) then + if sub_len <= j - i then + begin + (l, r) := (i, j); + sub_len := j - i; + end + else break + end; + result := s1[l:r + 1]; +end; + +lcs('thisisatest', 'testing123testing').println; diff --git a/Task/Longest-increasing-subsequence/ALGOL-68/longest-increasing-subsequence.alg b/Task/Longest-increasing-subsequence/ALGOL-68/longest-increasing-subsequence.alg new file mode 100644 index 0000000000..625db03760 --- /dev/null +++ b/Task/Longest-increasing-subsequence/ALGOL-68/longest-increasing-subsequence.alg @@ -0,0 +1,47 @@ +BEGIN # find the longest increasing subsequence of a list # + # - translated from the Kotlin sample # + + PR read "rows.incl.a68" PR # include array utilities including SHOW # + + PROC longest increasing subsequence = ( []INT x in )[]INT: + IF []INT x = x in[ AT 0 ]; # normalise array bounds to 0 : n - 1 # + INT n = ( UPB x - LWB x ) + 1; + n = 0 + THEN []INT() # empty list # + ELIF n = 1 + THEN x # one element # + ELSE [ 0 : n - 1 ]INT p; + [ 0 : n ]INT m; FOR i FROM LWB m TO UPB m DO m[ i ] := 0 OD; + INT len := 0; + FOR i FROM 0 TO n - 1 DO + INT lo := 1; + INT hi := len; + WHILE lo <= hi DO + REAL midr = ( lo + hi ) / 2; + INT midi = ENTIER midr; + INT mid = IF midi = midr THEN midi ELSE midi + 1 FI; + IF x[ m[ mid ] ] < x[ i ] THEN lo := mid + 1 ELSE hi := mid - 1 FI + OD; + INT new len = lo; + p[ i ] := m[ new len - 1 ]; + m[ new len ] := i; + IF new len > len THEN len := new len FI + OD; + [ 0 : len - 1 ]INT s; + INT k := m[ len ]; + FOR i FROM len - 1 BY -1 TO 0 DO + s[ i ] := x[ k ]; + k := p[ k ] + OD; + s + FI # longest increasing subsequence # ; + + PROC show longest increasing subsequence = ( []INT x )VOID: + BEGIN + print( ( "[" ) ); SHOW longest increasing subsequence( x ); print( ( " ]", newline ) ) + END # show longest increasing subsequence # ; + + show longest increasing subsequence( ( 3, 2, 6, 4, 5, 1 ) ); + show longest increasing subsequence( ( 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 ) ) + +END diff --git a/Task/Longest-increasing-subsequence/PascalABC.NET/longest-increasing-subsequence.pas b/Task/Longest-increasing-subsequence/PascalABC.NET/longest-increasing-subsequence.pas new file mode 100644 index 0000000000..8af2191ff2 --- /dev/null +++ b/Task/Longest-increasing-subsequence/PascalABC.NET/longest-increasing-subsequence.pas @@ -0,0 +1,30 @@ +function lis(list: array of integer): sequence of array of integer; +begin + for var len := list.Count downto 1 do + begin + var res := new integer[len]; + foreach var sub in (0..list.Count - 1).Combinations(len) do + begin + var temp := list[sub[0]]; + for var ind := 1 to len - 1 do + if list[sub[ind]] > temp then + begin + temp := list[sub[ind]]; + if ind = len - 1 then + begin + foreach var n in sub index i do + res[i] := (list[n]); + yield res; + end; + end + else break; + end; + end; +end; + +begin +var a := |3, 2, 6, 4, 5, 1|; +lis(a).First.Println; +a := |0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15|; +lis(a).First.Println; +end. diff --git a/Task/Look-and-say-sequence/PascalABC.NET/look-and-say-sequence.pas b/Task/Look-and-say-sequence/PascalABC.NET/look-and-say-sequence.pas new file mode 100644 index 0000000000..ddfac7124c --- /dev/null +++ b/Task/Look-and-say-sequence/PascalABC.NET/look-and-say-sequence.pas @@ -0,0 +1,26 @@ +## +function lookAndSay(): sequence of string; +begin + var current: string := '1'; + yield current; + + while true do + begin + var ch := current[1]; + var count := 1; + var next := ''; + foreach var i in 2..current.Length do + if current[i] = ch then + inc(count) + else begin + next += count.ToString + ch; + ch := current[i]; + count := 1; + end; + current := next + count.ToString + ch; + yield current; + end; +end; + +foreach var s in lookandsay.Take(12) do + s.Println; diff --git a/Task/Loops-Do-while/Nim/loops-do-while-2.nim b/Task/Loops-Do-while/Nim/loops-do-while-2.nim index 4cdcc90d5d..57db76fb79 100644 --- a/Task/Loops-Do-while/Nim/loops-do-while-2.nim +++ b/Task/Loops-Do-while/Nim/loops-do-while-2.nim @@ -1,9 +1,3 @@ -template doWhile(a, b: untyped): untyped = - b - while a: - b - var val = 0 -doWhile val mod 6 != 0: - inc val - echo val +while (inc val; echo val; val mod 6 != 0): + discard diff --git a/Task/Loops-Do-while/Nim/loops-do-while-3.nim b/Task/Loops-Do-while/Nim/loops-do-while-3.nim new file mode 100644 index 0000000000..4cdcc90d5d --- /dev/null +++ b/Task/Loops-Do-while/Nim/loops-do-while-3.nim @@ -0,0 +1,9 @@ +template doWhile(a, b: untyped): untyped = + b + while a: + b + +var val = 0 +doWhile val mod 6 != 0: + inc val + echo val diff --git a/Task/Loops-For/Dart/loops-for.dart b/Task/Loops-For/Dart/loops-for.dart index bf5831ccbd..4bdf131750 100644 --- a/Task/Loops-For/Dart/loops-for.dart +++ b/Task/Loops-For/Dart/loops-for.dart @@ -1,6 +1,8 @@ +import 'dart:io'; main() { - for (var i = 0; i < 5; i++) + for (var i = 0; i < 5; i++) { for (var j = 0; j < i + 1; j++) - print("*"); - print("\n"); + stdout.write("*"); + print(""); + } } diff --git a/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas b/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas index 754dbfc90b..58dc9f1308 100644 --- a/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas +++ b/Task/Loops-Foreach/PascalABC.NET/loops-foreach.pas @@ -1,3 +1,3 @@ ## -foreach var s in |'Pascal','ABC','.NET'| do +foreach var s in ['Pascal','ABC','.NET'] do Print(s); diff --git a/Task/Loops-While/Dart/loops-while-1.dart b/Task/Loops-While/Dart/loops-while-1.dart index 1f512078a9..ff9fb8dcc1 100644 --- a/Task/Loops-While/Dart/loops-while-1.dart +++ b/Task/Loops-While/Dart/loops-while-1.dart @@ -2,6 +2,6 @@ void main() { var val = 1024; while (val > 0) { print(val); - val >>= 2; + val >>= 1; } } diff --git a/Task/Loops-While/Dart/loops-while-2.dart b/Task/Loops-While/Dart/loops-while-2.dart index d345f90995..bd057fc674 100644 --- a/Task/Loops-While/Dart/loops-while-2.dart +++ b/Task/Loops-While/Dart/loops-while-2.dart @@ -1,7 +1,7 @@ void main() { - num val = 1024; + var val = 1024; while (val > 0) { print(val); - val /= 2; + val ~/= 2; } } diff --git a/Task/Loops-While/J/loops-while-2.j b/Task/Loops-While/J/loops-while-2.j index d9e2d1ee8f..bd00c5eedb 100644 --- a/Task/Loops-While/J/loops-while-2.j +++ b/Task/Loops-While/J/loops-while-2.j @@ -1,7 +1 @@ -monad define 1024 - while. 0 < y do. - smoutput y - y =. <. -: y - end. - i.0 0 -) +0 0$([ echo)@<.@-:^:*^:_. ]1024 diff --git a/Task/Loops-While/J/loops-while-3.j b/Task/Loops-While/J/loops-while-3.j new file mode 100644 index 0000000000..c4a37b6181 --- /dev/null +++ b/Task/Loops-While/J/loops-while-3.j @@ -0,0 +1,7 @@ +monad define 1024 + while. 0 < y do. + echo y + y =. <. -: y + end. + i.0 0 +) diff --git a/Task/Loops-While/M2000-Interpreter/loops-while-1.m2000 b/Task/Loops-While/M2000-Interpreter/loops-while-1.m2000 deleted file mode 100644 index d0a72a45e0..0000000000 --- a/Task/Loops-While/M2000-Interpreter/loops-while-1.m2000 +++ /dev/null @@ -1,8 +0,0 @@ -Module Checkit { - Def long A=1024 - While A>0 { - Print A - A/=2 - } -} -Checkit diff --git a/Task/Loops-While/M2000-Interpreter/loops-while-2.m2000 b/Task/Loops-While/M2000-Interpreter/loops-while-2.m2000 deleted file mode 100644 index 0ebb2d8d4d..0000000000 --- a/Task/Loops-While/M2000-Interpreter/loops-while-2.m2000 +++ /dev/null @@ -1 +0,0 @@ -Module Online { A=1024&: While A>0 {Print A: A/=2}} : OnLine diff --git a/Task/Loops-While/M2000-Interpreter/loops-while.m2000 b/Task/Loops-While/M2000-Interpreter/loops-while.m2000 new file mode 100644 index 0000000000..bdb4621b6d --- /dev/null +++ b/Task/Loops-While/M2000-Interpreter/loops-while.m2000 @@ -0,0 +1,31 @@ +Module Checkit { + Long A=1024 + While A>0 { + Print A + A/=2 + if a<500 then goto alfa + } + Print "not that" +alfa: + Print "ok" +} +Checkit +Module Checkit2 { + Long A=1024 + While A>0 + Print A + A/=2 + if a<500 then 10 + End While + Print "not that" +10 Print "ok" +} +Checkit2 +Module Checkit3 { + A=(1,2,3,4,5) + B=Each(A, -1, 1) + While B + Print Array(B), B^ + End While +} +Checkit3 diff --git a/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur b/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur index 211984fe9b..a5e20e4e49 100644 --- a/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur +++ b/Task/Loops-Wrong-ranges/Langur/loops-wrong-ranges.langur @@ -13,16 +13,16 @@ END # Process data string into table. # We could have just started with a list of lists, of course. -var table = submatches(RE/([^ ]+) +([^ ]+) +([^ ]+) +(.+)\n?/, data) +var table = submatches(data, by=RE/([^ ]+) +([^ ]+) +([^ ]+) +(.+)\n?/) for i in 2..len(table) { - table[i] = map([number, number, number, _], table[i]) + table[i] = map(table[i], by=[number, number, number, _]) } -for test in rest(table) { +for test in less(table, of=1) { val start, stop, inc, comment = test { - val s = series(start .. stop, inc) + val s = series(start .. stop, inc=inc) catch { writeln "{{comment}}\nERROR: {{_err'msg:L200(...)}}\n" } else { diff --git a/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur b/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur index f7a86123a0..d23abfe4c5 100644 --- a/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur +++ b/Task/Lucas-Lehmer-test/Langur/lucas-lehmer-test.langur @@ -1,6 +1,6 @@ val isPrime = fn(i) { i == 2 or i > 2 and - not any(fn x:i div x, pseries(2 .. i ^/ 2)) + not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x) } val isMersennePrime = fn(p) { @@ -13,4 +13,4 @@ val isMersennePrime = fn(p) { } == 0 } -writeln join(" ", map(fn x:"M{{x}}", filter(isMersennePrime, series(2300)))) +writeln join(map(filter(series(2300), by=isMersennePrime), by=fn x:"M{{x}}"), by=" ") diff --git a/Task/Lucas-Lehmer-test/PascalABC.NET/lucas-lehmer-test.pas b/Task/Lucas-Lehmer-test/PascalABC.NET/lucas-lehmer-test.pas new file mode 100644 index 0000000000..61401fd11e --- /dev/null +++ b/Task/Lucas-Lehmer-test/PascalABC.NET/lucas-lehmer-test.pas @@ -0,0 +1,33 @@ +function isMersennePrime(p: integer): boolean; +begin + if (p mod 2 = 0) then result := p = 2 + else begin + for var i := 3 to p.Sqrt.Floor step 2 do + if (p mod i = 0) then + begin + result := false; //not prime + exit + end; + var m_p := Power(2bi, p) - 1bi; + var s := 4bi; + for var i := 3 to p do + s := (s * s - 2bi) mod m_p; + result := s = 0bi; + end; +end; + +function GetMersennePrimeNumbers(upTo: integer): sequence of integer; +begin + var response := new List; + {$omp parallel for} + for var i := 2 to upTo do + if isMersennePrime(i) then response.Add(i); + response.Sort; + result := response; +end; + +begin + foreach var mp in GetMersennePrimeNumbers(11213) do + Write('M', mp, ' '); + println(#10, milliseconds / 1000, 's'); +end. diff --git a/Task/Ludic-numbers/PascalABC.NET/ludic-numbers.pas b/Task/Ludic-numbers/PascalABC.NET/ludic-numbers.pas new file mode 100644 index 0000000000..d33d9fd017 --- /dev/null +++ b/Task/Ludic-numbers/PascalABC.NET/ludic-numbers.pas @@ -0,0 +1,38 @@ +function ludic(): sequence of integer; +begin + yield 1; + var ludics := new List; + while True do + begin + var k := 0; + foreach var j in ludics[::-1] do + k := (k * j) div (j - 1) + 1; + ludics.Add(k + 2); + yield k + 2 + end; +end; + +function triplets(): sequence of (integer, integer, integer); +begin + var (a, b, c, d) := (0, 0, 0, 0); + foreach var k in ludic do + begin + if (k - 4 in [b, c, d]) and (k - 6 in [a, b, c]) then + yield (k - 6, k - 4, k); + (a, b, c, d) := (b, c, d, k); + end; +end; + +begin + writeln('First 25 ludic numbers:'); + ludic.Take(25).Println; + + write(#10, 'Ludic numbers below 1000: '); + ludic.TakeWhile(x -> x <= 1000).Count.Println; + + writeln(#10, 'Ludic numbers 2000 to 2005: '); + ludic.Skip(2000 - 1).Take(6).Println; + + writeln(#10, 'all triplets of ludic numbers < 250: '); + triplets.TakeWhile(x -> x[2] < 250).Println; +end. diff --git a/Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC/luhn-test-of-credit-card-numbers.basic new file mode 100644 index 0000000000..a361c757fe --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/ANSI-BASIC/luhn-test-of-credit-card-numbers.basic @@ -0,0 +1,22 @@ +100 REM Luhn test of credit card numbers +110 DATA "49927398716", "49927398717", "1234567812345678", "1234567812345670" +120 DECLARE EXTERNAL FUNCTION LuhnTest +130 FOR J = 1 TO 4 +140 READ C$ +150 PRINT C$; +160 IF LuhnTest(C$) = 1 THEN PRINT " is valid." ELSE PRINT " is invalid." +170 NEXT J +180 END +190 REM +200 EXTERNAL FUNCTION LuhnTest(C$) +210 LET S = 0 +220 FOR I = LEN(C$) TO 1 STEP -2 +230 LET S = S + VAL(C$(I:I)) +240 NEXT I +250 FOR I = LEN(C$) - 1 TO 1 STEP -2 +260 LET B = VAL(C$(I:I)) * 2 +270 IF B >= 10 THEN LET B = B - 9 +280 LET S = S + B +290 NEXT I +300 IF MOD(S, 10) = 0 THEN LET LuhnTest = 1 ELSE LET LuhnTest = 0 +310 END FUNCTION diff --git a/Task/Luhn-test-of-credit-card-numbers/ASIC/luhn-test-of-credit-card-numbers.asic b/Task/Luhn-test-of-credit-card-numbers/ASIC/luhn-test-of-credit-card-numbers.asic new file mode 100644 index 0000000000..5416e3933f --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/ASIC/luhn-test-of-credit-card-numbers.asic @@ -0,0 +1,42 @@ +REM Luhn test of credit card numbers +DATA "49927398716", "49927398717", "1234567812345678", "1234567812345670" +FOR J = 1 TO 4 + READ C$ + GOSUB DoLuhnTest: + PRINT C$; + IF RetVal = 1 THEN + PRINT " is valid." + ELSE + PRINT " is invalid." + ENDIF +NEXT J +END + +DoLuhnTest: +LenC = LEN(C$) +S = 0 +I = LenC +WHILE I >= 1 + CI$ = MID$(C$, I, 1) + Num = VAL(CI$) + S = S + Num + I = I - 2 +WEND +I = LenC - 1 +WHILE I >= 1 + CI$ = MID$(C$, I, 1) + Num = VAL(CI$) + B = Num * 2 + IF B >= 10 THEN + B = B - 9 + ENDIF + S = S + B + I = I - 2 +WEND +SMod10 = S MOD 10 +IF SMod10 = 0 THEN + RetVal = 1 +ELSE + RetVal = 0 +ENDIF +RETURN diff --git a/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic index 577e9f7824..8453461734 100644 --- a/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic +++ b/Task/Luhn-test-of-credit-card-numbers/FutureBasic/luhn-test-of-credit-card-numbers.basic @@ -1,43 +1,18 @@ include "NSLog.incl" -local fn LuhnCheck( cardStr as CFStringRef ) as BOOL - NSInteger i, j, count, s1 = 0, s2 = 0 - BOOL result = NO +local fn luhn( n as long ) + int r = 0, nx2(9) = {0,2,4,6,8,1,3,5,7,9} + nslog(@"%20ld \b", n) + while n + r += n % 10 + nx2(n / 10 % 10) + n /= 100 + wend + if r % 10 then nslog( @"fail") else nslog( @"pass") +end fn - // Build array of individual numbers in credit card string - NSUInteger strLength = len(cardStr) - CFMUtableArrayRef mutArr = fn MutableArrayWithCapacity(strLength) - for i = 0 to strLength - 1 - CFStringRef tempStr = fn StringWithFormat( @"%C", fn StringCharacterAtIndex( cardStr, i ) ) - MutableArrayInsertObjectAtIndex( mutArr, tempStr, i ) - next +fn luhn(49927398716) +fn luhn(49927398717) +fn luhn(1234567812345678) +fn luhn(1234567812345670) - // Reverse the number array - CFArrayRef reversedArray = fn EnumeratorAllObjects( fn ArrayReverseObjectEnumerator( mutArr ) ) - - // Get number of array elements - count = len(reversedArray) - - // Handle odd numbers - for i = 0 to count - 1 step 2 - s1 = s1 + fn StringIntegerValue( reversedArray[i] ) - next - - // Hnadle even numbers - for i = 1 to count - 1 step 2 - j = fn StringIntegerValue( reversedArray[i] ) - j = j * 2 - if j > 9 then j = j mod 10 + 1 - s2 = s2 + j - next - - if (s1 + s2) mod 10 = 0 then result = YES else result = NO -end fn = result - -NSLogClear -if fn LuhnCheck( @"49927398716" ) then NSLog (@"%@ is valid.", @"49927398716" ) else NSLog (@"%@ is not valid.", @"49927398716" ) -if fn LuhnCheck( @"49927398717" ) then NSLog (@"%@ is valid.", @"49927398717" ) else NSLog (@"%@ is not valid.", @"49927398717" ) -if fn LuhnCheck( @"1234567812345678" ) then NSLog (@"%@ is valid.", @"1234567812345678" ) else NSLog (@"%@ is not valid.", @"1234567812345678" ) -if fn LuhnCheck( @"1234567812345670" ) then NSLog (@"%@ is valid.", @"1234567812345670" ) else NSLog (@"%@ is not valid.", @"1234567812345670" ) - -HandleEvents +handleevents diff --git a/Task/Luhn-test-of-credit-card-numbers/GW-BASIC/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/GW-BASIC/luhn-test-of-credit-card-numbers.basic new file mode 100644 index 0000000000..4e5104142d --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/GW-BASIC/luhn-test-of-credit-card-numbers.basic @@ -0,0 +1,20 @@ +10 REM Luhn test of credit card numbers +20 DATA "49927398716", "49927398717", "1234567812345678", "1234567812345670" +30 FOR J = 1 TO 4 +40 READ C$: GOSUB 1000 +50 PRINT C$; +60 IF RETVAL THEN PRINT " is valid." ELSE PRINT " is invalid." +70 NEXT J +80 END +1000 REM ** Luhn test +1010 S = 0 +1020 FOR I = LEN(C$) TO 1 STEP -2 +1030 S = S + VAL(MID$(C$, I, 1)) +1040 NEXT I +1050 FOR I = LEN(C$) - 1 TO 1 STEP -2 +1060 B = VAL(MID$(C$, I, 1)) * 2 +1070 IF B >= 10 THEN B = B - 9 +1080 S = S + B +1090 NEXT I +1100 RETVAL = (S MOD 10 = 0) +1110 RETURN diff --git a/Task/Luhn-test-of-credit-card-numbers/Modula-2/luhn-test-of-credit-card-numbers.mod2 b/Task/Luhn-test-of-credit-card-numbers/Modula-2/luhn-test-of-credit-card-numbers.mod2 new file mode 100644 index 0000000000..6ff97b5f25 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Modula-2/luhn-test-of-credit-card-numbers.mod2 @@ -0,0 +1,49 @@ +MODULE LuhnTestCreditCard; +(* Luhn test of credit card numbers *) + +FROM STextIO IMPORT + WriteString, WriteLn; + +CONST + MaxLen = 16; + +TYPE + TCardNum = ARRAY[0 .. MaxLen] OF CHAR; + TCards = ARRAY[0 .. 3] OF TCardNum; + +CONST + Cards = TCards{"49927398716", "49927398717", + "1234567812345678", "1234567812345670"}; +VAR + J: CARDINAL; + +PROCEDURE LuhnTest(C: ARRAY OF CHAR): BOOLEAN; +VAR + S, I, B, LastIndex: CARDINAL; +BEGIN + S := 0; + LastIndex := LENGTH(C) - 1; + FOR I := LastIndex TO 0 BY -2 DO + S := S + (ORD(C[I]) - ORD("0")) + END; + FOR I := LastIndex - 1 TO 0 BY -2 DO + B := (ORD(C[I]) - ORD("0")) * 2; + IF B >= 10 THEN + B := B - 9 + END; + S := S + B + END; + RETURN S MOD 10 = 0 +END LuhnTest; + +BEGIN + FOR J := 0 TO 3 DO + WriteString(Cards[J]); + IF LuhnTest(Cards[J]) THEN + WriteString(" is valid.") + ELSE + WriteString(" is invalid.") + END; + WriteLn; + END; +END LuhnTestCreditCard. diff --git a/Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC/luhn-test-of-credit-card-numbers.basic new file mode 100644 index 0000000000..12f480a536 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Nascom-BASIC/luhn-test-of-credit-card-numbers.basic @@ -0,0 +1,22 @@ +10 REM Luhn test of credit card numbers +20 DATA "49927398716","49927398717" +30 DATA "1234567812345678","1234567812345670" +40 FOR J=1 TO 4 +50 READ C$:GOSUB 1000 +60 PRINT C$; +70 IF RV THEN PRINT " is valid.":GOTO 90 +80 PRINT " is invalid." +90 NEXT J +100 END +1000 REM ** Luhn test +1010 S=0 +1020 FOR I=LEN(C$) TO 1 STEP -2 +1030 S=S+VAL(MID$(C$,I,1)) +1040 NEXT I +1050 FOR I=LEN(C$)-1 TO 1 STEP -2 +1060 B=VAL(MID$(C$,I,1))*2 +1070 IF B>=10 THEN B=B-9 +1080 S=S+B +1090 NEXT I +1100 RV=(INT(S/10)*10=S) +1110 RETURN diff --git a/Task/Luhn-test-of-credit-card-numbers/PascalABC.NET/luhn-test-of-credit-card-numbers.pas b/Task/Luhn-test-of-credit-card-numbers/PascalABC.NET/luhn-test-of-credit-card-numbers.pas new file mode 100644 index 0000000000..2a8fbbf6ae --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/PascalABC.NET/luhn-test-of-credit-card-numbers.pas @@ -0,0 +1,18 @@ +function doubleDigit(n: integer) := (n * 2).ToString.Select(c -> c.ToDigit).Sum; + +function LuhnCheck(creditCardNumber: string): boolean; +begin + var checkSum := creditCardNumber + .Select(c -> c.ToDigit) + .Reverse + .Select((digit, index) -> (if odd(index + 1) then digit else doubleDigit(digit))) + .Sum; + + result := checkSum mod 10 = 0; +end; + +begin + var testNumbers := |49927398716, 49927398717, 1234567812345678, 1234567812345670|; + foreach var testNumber in testNumbers do + Writeln(testnumber, ' is ', if LuhnCheck(testNumber.ToString) then '' else 'not ', 'valid'); +end. diff --git a/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic b/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic index 25e7b7cf33..eb9d93f266 100644 --- a/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic +++ b/Task/Luhn-test-of-credit-card-numbers/QBasic/luhn-test-of-credit-card-numbers.basic @@ -19,7 +19,7 @@ FOR test = 1 TO 4 IF num <= 9 THEN sum = sum + num ELSE - sum = sum + VAL(LEFT$(STR$(num), 1)) + VAL(RIGHT$(STR$(num), 1)) + sum = sum + num - 9 END IF odd = True END IF diff --git a/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v b/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v index b9a29520f7..c95eec833e 100644 --- a/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v +++ b/Task/Luhn-test-of-credit-card-numbers/V-(Vlang)/luhn-test-of-credit-card-numbers.v @@ -1,8 +1,9 @@ const ( - input = '49927398716 -49927398717 -1234567812345678 -1234567812345670' + input = " + 49927398716 + 49927398717 + 1234567812345678 + 1234567812345670" t = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9] ) @@ -10,21 +11,16 @@ const ( fn luhn(s string) bool { odd := s.len & 1 mut sum := 0 - for i, c in s.split('') { - if c < '0' || c > '9' { - return false - } - if i&1 == odd { - sum += t[c.int()-'0'.int()] - } else { - sum += c.int() - '0'.int() - } + for i, c in s.split("") { + if c < '0' || c > '9' {return false} + if i&1 == odd {sum += t[c.int()-'0'.int()]} + else {sum += c.int() - '0'.int()} } - return sum%10 == 0 + return sum % 10 == 0 } fn main() { - for s in input.split("\n") { - println('$s ${luhn(s)}') + for s in input.trim_indent().split_into_lines() { + println("${s} ${luhn(s)}") } } diff --git a/Task/Lychrel-numbers/PascalABC.NET/lychrel-numbers.pas b/Task/Lychrel-numbers/PascalABC.NET/lychrel-numbers.pas new file mode 100644 index 0000000000..dfacb06e29 --- /dev/null +++ b/Task/Lychrel-numbers/PascalABC.NET/lychrel-numbers.pas @@ -0,0 +1,55 @@ +const + iterations = 1000; + limit = 10_000; + +var + cache := new Dictionary; + +function rev(n: biginteger) := n.ToString[::-1].ToBigInteger; + +function lychrel(n: biginteger): (boolean, biginteger); +begin + if n in cache then result := cache[n] + else begin + var r := rev(n); + var res := (True, n); + var seen := new List; + loop iterations do + begin + n += r; + r := rev(n); + if n = r then + begin + res := (False, 0bi); + break + end; + if n in cache then + begin + res := cache[n]; + break + end; + seen.Add(n) + end; + + foreach var x in seen do cache[x] := res; + result := res; + end; +end; + +begin + var seeds := new List; + var related := new List; + var palin := new List; + + foreach var i in (1..limit) do + begin + var (tf, s) := lychrel(i); + if not tf then continue; + if i = s then seeds.Add(i) else related.Add(i); + if i = rev(i) then palin.Add(i); + end; + + println('There are', seeds.count, 'Lychrel seeds, namely:', seeds); + println('Lychrel related numbers:', related.count); + println('There are', palin.count, 'Lychrel palindromes, namely:', palin); +end. diff --git a/Task/Lychrel-numbers/Wren/lychrel-numbers.wren b/Task/Lychrel-numbers/Wren/lychrel-numbers.wren index c3a10d72e0..1b6eb6b704 100644 --- a/Task/Lychrel-numbers/Wren/lychrel-numbers.wren +++ b/Task/Lychrel-numbers/Wren/lychrel-numbers.wren @@ -1,5 +1,5 @@ import "./big" for BigInt -import "./set" for Set +import "./hash" for HashSet var iterations = 500 var limit = 10000 @@ -8,7 +8,7 @@ var bigLimit = BigInt.new(limit) // In the sieve, 0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel var lychrelSieve = List.filled(limit + 1, 0) var seedLychrels = [] -var relatedLychrels = Set.new() +var relatedLychrels = HashSet.new() var isPalindrome = Fn.new { |bi| var s = bi.toString @@ -32,12 +32,12 @@ var lychrelTest = Fn.new { |i, seq| } var sizeBefore = relatedLychrels.count // if all of these can be added 'i' must be a seed Lychrel - relatedLychrels.addAll(seq.map { |i| i.toString }) // can't add BigInts directly to a Set + relatedLychrels.addAll(seq) if (relatedLychrels.count - sizeBefore == seq.count) { seedLychrels.add(i) lychrelSieve[i] = 1 } else { - relatedLychrels.add(i.toString) + relatedLychrels.add(i) lychrelSieve[i] = 2 } } diff --git a/Task/M-bius-function/Forth/m-bius-function.fth b/Task/M-bius-function/Forth/m-bius-function.fth new file mode 100644 index 0000000000..16d5292cfb --- /dev/null +++ b/Task/M-bius-function/Forth/m-bius-function.fth @@ -0,0 +1,36 @@ +\ Moebius function +: mu ( u -- n ) + \ multiple of 4 so return 0 + dup 3 and 0= if drop 0 exit then + \ even numbers have 2 as a prime factor + dup 1 and 0= if 2/ 1 else 0 then >r + \ look for odd prime factors up to the square root + 3 begin + 2dup dup * >= + while + 2dup mod 0= if + tuck / swap + 2dup mod 0= if + \ repeated prime factor so return 0 + 2drop rdrop 0 exit + then + \ we have another prime factor + r> 1+ >r + then + 2 + + repeat + drop + \ prime factor > square root? + r> swap 1 > if 1+ then + 1 and 0= if 1 else -1 then ; + +: main ( -- ) + ." The first 199 Moebius numbers are:" cr + ." " + 200 1 do + i mu 3 .r + i 1+ 20 mod 0= if cr else then + loop ; + +main +bye diff --git a/Task/M-bius-function/PascalABC.NET/m-bius-function.pas b/Task/M-bius-function/PascalABC.NET/m-bius-function.pas new file mode 100644 index 0000000000..4760b377f0 --- /dev/null +++ b/Task/M-bius-function/PascalABC.NET/m-bius-function.pas @@ -0,0 +1,15 @@ +uses school; + +function mobius(n: integer): integer; +begin + var factors := n.Factorize; + if factors.Count = factors.ToSet.Count then + result := if factors.Count.IsEven then 1 else -1 + else result := 0 +end; + +begin + println('Mobius numbers from 1..99:'); + for var n := 1 to 99 do + write(mobius(n):3, if n mod 20 = 0 then #10 else ''); +end. diff --git a/Task/M-bius-function/Swift/m-bius-function.swift b/Task/M-bius-function/Swift/m-bius-function.swift new file mode 100644 index 0000000000..5cdbe1c56e --- /dev/null +++ b/Task/M-bius-function/Swift/m-bius-function.swift @@ -0,0 +1,36 @@ +import Foundation + +// Moebius function +func mu(number: Int) -> Int { + var n = number + if n % 4 == 0 { + return 0 + } + var primeFactors = 0 + if n % 2 == 0 { + primeFactors += 1 + n /= 2 + } + var p = 3 + while p * p <= n { + if n % p == 0 { + n /= p + if n % p == 0 { + return 0 + } + primeFactors += 1 + } + p += 2 + } + if (n > 1) { + primeFactors += 1 + } + return primeFactors % 2 == 0 ? 1 : -1 +} + +print("The first 199 Moebius numbers are:") +print(" ", terminator: "") +for i in 1..<200 { + print(String(format: "%3d", mu(number: i)), + terminator: (i + 1) % 20 == 0 ? "\n" : "") +} diff --git a/Task/MAC-vendor-lookup/FutureBasic/mac-vendor-lookup.basic b/Task/MAC-vendor-lookup/FutureBasic/mac-vendor-lookup.basic new file mode 100644 index 0000000000..b8cd701fb1 --- /dev/null +++ b/Task/MAC-vendor-lookup/FutureBasic/mac-vendor-lookup.basic @@ -0,0 +1,15 @@ +local fn MACVendorLookup( vendor as CFStringRef ) as CFStringRef +CFStringRef cmd = fn StringWithFormat( @"curl -s \"https://api.macvendors.com/%@\" && echo", vendor ) +return unix cmd +end fn = NULL + +CFStringRef MACaddr +CFArrayRef vendors +vendors = @[@"88:53:2E:67:07:BE", @"D4:F4:6F:C9:EF:8D", @"FC:FB:FB:01:FA:21", @"4c:72:b9:56:fe:bc", @"00-14-22-01-23-45"] + +for MACaddr in vendors +print fn StringByReplacingOccurrencesOfString( fn MACVendorLookup( MACaddr ), @"\n", @"" ) +delay 1000 // Delay a second between each request to prevent api.macvendors.com server from rejecting query +next + +HandleEvents diff --git a/Task/MAC-vendor-lookup/PascalABC.NET/mac-vendor-lookup.pas b/Task/MAC-vendor-lookup/PascalABC.NET/mac-vendor-lookup.pas new file mode 100644 index 0000000000..49fece1ba1 --- /dev/null +++ b/Task/MAC-vendor-lookup/PascalABC.NET/mac-vendor-lookup.pas @@ -0,0 +1,11 @@ +## +uses System.Net; + +ServicePointManager.SecurityProtocol := SecurityProtocolType(3072); +var wc := new WebClient; + +foreach var mac in |'FC-A1-3E', 'FC:FB:FB:01:FA:21', 'BC:5F:F4'| do +begin + println(mac, wc.DownloadString('https://api.macvendors.com/' + mac)); + Sleep(1500); +end; diff --git a/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-3.wren b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-3.wren new file mode 100644 index 0000000000..238c3622b3 --- /dev/null +++ b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-3.wren @@ -0,0 +1,10 @@ +import "os" for Process +import "timer" for Timer + +var macs = ["88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D", "23:45:67"] +for (mac in macs) { + var vendor = Process.read("curl -s " + "https://api.macvendors.com/" + mac) + if (vendor.contains("errors")) vendor = "Vendor not found" + System.print("%(mac) %(vendor)") + Timer.wait(2000) +} diff --git a/Task/MD5-Implementation/Guile/md5-implementation.guile b/Task/MD5-Implementation/Guile/md5-implementation.guile new file mode 100644 index 0000000000..fd52628d4f --- /dev/null +++ b/Task/MD5-Implementation/Guile/md5-implementation.guile @@ -0,0 +1,196 @@ +;;;This is intended to be run by Guile +;;;If you want to try it elsewhere, I think you might need to replace some module importing lines + +;;module-required (rnrs bytevectors) +;;usage -> {bytevector-u8-list bytevector-length bytevector->uint-list bytevector-u8-set! bytevector-copy! bytevector-u32-set!} {pad listify} +;; +(use-modules (rnrs bytevectors)) + +;;module-required (ice-9 receive) (ice-9 exceptions) +;;usage -> {receive make-exception-with-message} {md5sum test-suite} +;; +(use-modules (ice-9 receive)) +(use-modules (ice-9 exceptions)) + +;;syntax-name F +;;match -> (<$:self:F> B C D) +;; +(define-syntax F + (syntax-rules () + [(_ B C D) + (logior (logand B C) (logand (lognot B) D))])) + +;;syntax-name G +;;match -> (<$:self:G> B C D) +;; +(define-syntax G + (syntax-rules () + [(_ B C D) + (logior (logand B D) (logand C (lognot D)))])) + +;;syntax-name H +;;match -> (<$:self:H> B C D) +;; +(define-syntax H + (syntax-rules () + [(_ B C D) + (logxor B C D)])) + +;;syntax-name I +;;match -> (<$:self:I> B C D) +;; +(define-syntax I + (syntax-rules () + [(_ B C D) + (logxor C (logior B (lognot D)))])) + +;;syntax-name leftrotate +;;match -> (<$:self:leftrotate> num s) +;; +(define-syntax leftrotate + (syntax-rules () + [(_ num s) + (let ([num (logand num #xFFFFFFFF)]) + (logior (ash num (- s 32)) (ash num s)))])) + +;;procedure-name pad +;;input -> bv (bytevector) +;;output -> output-bv (bytevector) [(zero? (floor-remainder (bytevector-length output-bv) 64)) => #t] +;; +(define pad + (lambda (bv) + (let* ([bv-length (bytevector-length bv)] + [original-length (* 8 bv-length)] + + [remainder (floor-remainder bv-length 64)] + [pad-total (if (>= remainder 56) (- 128 remainder) (- 64 remainder))] + [total-length (+ bv-length pad-total)] + [output-bv (make-bytevector total-length 0)] + + [original-length-cooked (logand original-length #xFFFFFFFFFFFFFFFF)] + [original-length-bv (uint-list->bytevector (list original-length-cooked) (endianness little) 8)]) + + (bytevector-copy! bv 0 output-bv 0 bv-length) + (bytevector-u8-set! output-bv bv-length #x80) + (bytevector-copy! original-length-bv 0 output-bv (- total-length 8) 8) + + output-bv))) + +;;procedure-name listify +;;input -> bv (bytevector) [(zero? (floor-remainder (bytevector-length output-bv) 64)) => #t] +;;output -> _ (list:list:u32[16]) +;; +(define listify + (lambda (bv) + (let ([bv-as-u32-list (bytevector->uint-list bv (endianness little) 4)]) + (let ([total-num (/ (length bv-as-u32-list) 16)]) + (let loop ([n 0] [lst bv-as-u32-list]) + (if (>= n (- total-num 1)) + (list lst) + (cons (list-head lst 16) (loop (+ 1 n) (list-tail lst 16))))))))) + +;;procedure-name process-512bits +;;input -> X (list;u32[16]) A B C D K s +;;output -> _ (u32[4]) +;;note -> "This function is intended to do the real 64 rounds calculation and return the A B C D in the end but it doesn't need to loop at all" +;; +(define process-512bits + (lambda (X A B C D K s) + (let ([AA A][BB B][CC C][DD D]) + (let ([F1 #f][g #f][i 0]) + (while (<= i 63) + (when (and (>= i 0) (<= i 15)) + (set! F1 (F BB CC DD)) + (set! g i)) + (when (and (>= i 16) (<= i 31)) + (set! F1 (G BB CC DD)) + (set! g (modulo (1+ (* 5 i)) 16))) + (when (and (>= i 32) (<= i 47)) + (set! F1 (H BB CC DD)) + (set! g (modulo (+ 5 (* 3 i)) 16))) + (when (and (>= i 48) (<= i 63)) + (set! F1 (I BB CC DD)) + (set! g (modulo (* 7 i) 16))) + + (set! F1 (modulo (+ F1 AA (list-ref K i) (list-ref X g)) (expt 2 32))) + (set! AA DD) + (set! DD CC) + (set! CC BB) + (set! BB (modulo (+ BB (leftrotate F1 (list-ref s i))) (expt 2 32))) + + (set! i (1+ i))) + + (values (modulo (+ A AA) (expt 2 32)) + (modulo (+ B BB) (expt 2 32)) + (modulo (+ C CC) (expt 2 32)) + (modulo (+ D DD) (expt 2 32))))))) + +#! uncomment this block if guile complains about the unbound variable: format +;;module-required (ice-9 format) +;;usage -> format (procedure) md5sum (procedure) +;; +(use-modules (ice-9 format)) +!# + +;;procedure-name md5sum +;;input -> bv (bytevector) +;;output -> _ (string) +;; +(define md5sum + (lambda (bv) + (let ([A #x67452301] + [B #xEFCDAB89] + [C #x98BADCFE] + [D #x10325476] + [K '(#xd76aa478 #xe8c7b756 #x242070db #xc1bdceee #xf57c0faf #x4787c62a #xa8304613 #xfd469501 #x698098d8 #x8b44f7af #xffff5bb1 #x895cd7be #x6b901122 #xfd987193 #xa679438e #x49b40821 #xf61e2562 #xc040b340 #x265e5a51 #xe9b6c7aa #xd62f105d #x02441453 #xd8a1e681 #xe7d3fbc8 #x21e1cde6 #xc33707d6 #xf4d50d87 #x455a14ed #xa9e3e905 #xfcefa3f8 #x676f02d9 #x8d2a4c8a #xfffa3942 #x8771f681 #x6d9d6122 #xfde5380c #xa4beea44 #x4bdecfa9 #xf6bb4b60 #xbebfbc70 #x289b7ec6 #xeaa127fa #xd4ef3085 #x04881d05 #xd9d4d039 #xe6db99e5 #x1fa27cf8 #xc4ac5665 #xf4292244 #x432aff97 #xab9423a7 #xfc93a039 #x655b59c3 #x8f0ccc92 #xffeff47d #x85845dd1 #x6fa87e4f #xfe2ce6e0 #xa3014314 #x4e0811a1 #xf7537e82 #xbd3af235 #x2ad7d2bb #xeb86d391)] + [s '(7 12 17 22 7 12 17 22 7 12 17 22 7 12 17 22 5 9 14 20 5 9 14 20 5 9 14 20 5 9 14 20 4 11 16 23 4 11 16 23 4 11 16 23 4 11 16 23 6 10 15 21 6 10 15 21 6 10 15 21 6 10 15 21)]) + (let* ([padded-bv (pad bv)] + [512bits-word-lists (listify padded-bv)] + [words-list-length (length 512bits-word-lists)]) + + (do ((index 0 (1+ index))) + ((>= index words-list-length)) + + (receive (A1 B1 C1 D1) (process-512bits (list-ref 512bits-word-lists index) A B C D K s) + (set! A A1) + (set! B B1) + (set! C C1) + (set! D D1))) + + (let ([bvA (uint-list->bytevector (list A) (endianness little) 4)] + [bvB (uint-list->bytevector (list B) (endianness little) 4)] + [bvC (uint-list->bytevector (list C) (endianness little) 4)] + [bvD (uint-list->bytevector (list D) (endianness little) 4)]) + (set! A (car (bytevector->uint-list bvA (endianness big) 4))) + (set! B (car (bytevector->uint-list bvB (endianness big) 4))) + (set! C (car (bytevector->uint-list bvC (endianness big) 4))) + (set! D (car (bytevector->uint-list bvD (endianness big) 4)))) + + (format #f "~8,'0x~8,'0x~8,'0x~8,'0x" A B C D))))) + +;;procedure-name test-suite +;;input -> <$:nil> +;;output -> _ (string) +;;note -> "this is the test function for the overall output" +;; +(define test-suite + (lambda () + (let ([standard '(("" . "d41d8cd98f00b204e9800998ecf8427e") + ("a" . "0cc175b9c0f1b6a831c399e269772661") + ("abc" . "900150983cd24fb0d6963f7d28e17f72") + ("message digest" . "f96b697d7cb7938d525a2f31aaf161d0") + ("abcdefghijklmnopqrstuvwxyz" . "c3fcd3d76192e4007dfb496cca67e13b") + ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" . "d174ab98d277d9f5a5611c2c9f419d9f") + ("12345678901234567890123456789012345678901234567890123456789012345678901234567890" . "57edf4a22be3c955ac49da2e2107b67a"))]) + (for-each (lambda (some-pair) + (display "Now checking: ") + (write some-pair) + (newline) + (let ([my-ans (md5sum (string->utf8 (car some-pair)))]) + (display "my answer is: ") + (display my-ans) + (newline) + (if (string=? my-ans (cdr some-pair)) + (begin (display "Pass! Next!") (newline)) + (raise-exception (make-exception-with-message "Failed!"))))) + standard)))) diff --git a/Task/MD5/PascalABC.NET/md5.pas b/Task/MD5/PascalABC.NET/md5.pas new file mode 100644 index 0000000000..97d933d8b3 --- /dev/null +++ b/Task/MD5/PascalABC.NET/md5.pas @@ -0,0 +1,6 @@ +## +uses System.Security.Cryptography; + +var data := Encoding.ASCII.GetBytes('The quick brown fox jumped over the lazy dog''s back'); +foreach var h in MD5.Create().ComputeHash(data) do + h.ToString('X2').print; diff --git a/Task/Magic-constant/PascalABC.NET/magic-constant.pas b/Task/Magic-constant/PascalABC.NET/magic-constant.pas new file mode 100644 index 0000000000..6e33247fbb --- /dev/null +++ b/Task/Magic-constant/PascalABC.NET/magic-constant.pas @@ -0,0 +1,17 @@ +## +function magic(n: biginteger) := n * (n * n + 1) div 2; + +println('The first 20 magic constants:'); +(1 + 2..22).Select(x -> magic(x)).Println; +println; + +println('The 1,000th magic constant:',magic(1000 + 2),#10); + +for var n := 1 to 20 do +begin + write('10^', n, ': '); + (1..maxint).Select(x -> biginteger(x)) + .SkipWhile(x -> magic(x) < power(10bi, n)) + .First + .Println; +end; diff --git a/Task/Magic-squares-of-doubly-even-order/PascalABC.NET/magic-squares-of-doubly-even-order.pas b/Task/Magic-squares-of-doubly-even-order/PascalABC.NET/magic-squares-of-doubly-even-order.pas new file mode 100644 index 0000000000..8a599e6027 --- /dev/null +++ b/Task/Magic-squares-of-doubly-even-order/PascalABC.NET/magic-squares-of-doubly-even-order.pas @@ -0,0 +1,29 @@ +const + n = 8; + +function MagicSquareDoublyEven(n: integer): array [,] of integer; +begin + assert((n >= 4) and (n mod 4 = 0), 'base must be a positive multiple of 4'); + + // pattern of count-up vs count-down zones + var bits := Convert.ToInt32('1001011001101001', 2); + var size := n * n; + var mult := n div 4; // how many multiples of 4 + + result := new integer[n, n]; + + var i := 0; + for var r := 0 to n - 1 do + for var c := 0 to n - 1 do + begin + var bitPos := c div mult + (r div mult) * 4; + result[r, c] := if (bits and (1 shl bitPos)) <> 0 then i + 1 else size - i; + i += 1; + end; +end; + +begin + MagicSquareDoublyEven(n).Println; + + Writeln(#10, 'Magic constant: ', (n * n + 1) * n div 2); +end. diff --git a/Task/Magic-squares-of-doubly-even-order/XPL0/magic-squares-of-doubly-even-order.xpl0 b/Task/Magic-squares-of-doubly-even-order/XPL0/magic-squares-of-doubly-even-order.xpl0 new file mode 100644 index 0000000000..faeeb5bfbc --- /dev/null +++ b/Task/Magic-squares-of-doubly-even-order/XPL0/magic-squares-of-doubly-even-order.xpl0 @@ -0,0 +1,26 @@ + \Magic squares of doubly even order - 11/30/2024; + integer Pattern(1+4,1+4); + integer N, R, C, S, M, I, B, T; +begin + N:=8; + for R:=1 to 4 do + for C:=1 to 4 do + Pattern(R,C):=if + ((C=1 or C=4) and (R=1 or R=4)) or + ((C=2 or C=3) and (R=2 or R=3)) then 1 else 0; + S:=N*N; M:=N/4; + Text(1,"magic square -- n = "); IntOut(1,N); Text(1,"^m^j"); + I:=0; + for R:=1 to N do begin + for C:=1 to N do begin + B:=Pattern((R-1)/M+1, (C-1)/M+1); + if B=1 then T:=I+1 else T:=S-I; + if T < 10 then Text(1," "); + Text(1," "); + IntOut(1,T); + I:=I+1 + end; + Text(1,"^m^j") + end; + Text(1,"magic constant = "); IntOut(1,(S+1)*N/2) +end diff --git a/Task/Magnanimous-numbers/PascalABC.NET/magnanimous-numbers.pas b/Task/Magnanimous-numbers/PascalABC.NET/magnanimous-numbers.pas new file mode 100644 index 0000000000..de6dee7581 --- /dev/null +++ b/Task/Magnanimous-numbers/PascalABC.NET/magnanimous-numbers.pas @@ -0,0 +1,50 @@ +function IsPrime(n: int64): boolean; +begin + if (n = 2) or (n = 3) then Result := true + else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result := false + else + begin + var i := 5; + Result := False; + while i <= trunc(sqrt(n)) do + begin + if ((n mod i) = 0) or ((n mod (i + 2)) = 0) then exit; + i += 6; + end; + Result := True; + end; +end; + +function isMagnanimous(n: int64): boolean; +begin + var p := 10; + result := True; + while True do + begin + var a := n div p; + var b := n mod p; + if a = 0 then exit; + if not isPrime(a + b) then break; + p *= 10; + end; + result := false; +end; + +function magnanimous(): sequence of int64; +begin + var n: int64 := 0; + while true do + begin + if isMagnanimous(n) then yield n; + n += 1; + end; +end; + +begin + writeln('First 45 magnanimous numbers:'); + magnanimous.Take(45).Println; + writeln(#10, '241st through 250th magnanimous numbers:'); + magnanimous.Skip(240).Take(10).Println; + writeln(#10, '391st through 400th magnanimous numbers:'); + magnanimous.Skip(390).Take(10).Println; +end. diff --git a/Task/Mandelbrot-set/Aquarius-BASIC/mandelbrot-set-1.basic b/Task/Mandelbrot-set/Aquarius-BASIC/mandelbrot-set-1.basic new file mode 100644 index 0000000000..fbe45621fe --- /dev/null +++ b/Task/Mandelbrot-set/Aquarius-BASIC/mandelbrot-set-1.basic @@ -0,0 +1,19 @@ +10 PRINT CHR$(11); +20 CS=12288+1024 +30 FOR Y=0 TO 24 +40 FOR X=0 TO 39 +50 GOSUB 100:POKE CS,COL +60 CS=CS+1 +70 NEXT +80 NEXT +90 END +100 XP=X/39*2.7-2 +110 YP=Y/24*2-1 +120 IT=0:XX=0:YY=0 +130 XTEMP=XX*XX - YY*YY + XP +140 YY=2*XX*YY + YP +150 XX=XTEMP +160 IT=IT+1 +170 IF XX*XX+YY*YY<4 AND IT<20 THEN 130 +180 COL=IT AND 15:IF IT=20 THEN COL=0 +190 RETURN diff --git a/Task/Mandelbrot-set/Aquarius-BASIC/mandelbrot-set-2.basic b/Task/Mandelbrot-set/Aquarius-BASIC/mandelbrot-set-2.basic new file mode 100644 index 0000000000..a185c3d6a6 --- /dev/null +++ b/Task/Mandelbrot-set/Aquarius-BASIC/mandelbrot-set-2.basic @@ -0,0 +1,15 @@ +10 PRINT CHR$(11); +20 FOR Y=0 TO 71 +30 FOR X=0 TO 79 +40 GOSUB 100 +50 NEXT:NEXT:END +100 XP=X/79*2.7-2 +110 YP=Y/71*2-1 +120 IT=0:XX=0:YY=0 +130 XTEMP=XX*XX - YY*YY + XP +140 YY=2*XX*YY + YP +150 XX=XTEMP +160 IT=IT+1 +170 IF XX*XX+YY*YY<4 AND IT<20 THEN 130 +180 IF IT=20 THEN PSET(X,Y) +190 RETURN diff --git a/Task/Mandelbrot-set/Atari-BASIC/mandelbrot-set.basic b/Task/Mandelbrot-set/Atari-BASIC/mandelbrot-set.basic new file mode 100644 index 0000000000..f2b1fc6ac0 --- /dev/null +++ b/Task/Mandelbrot-set/Atari-BASIC/mandelbrot-set.basic @@ -0,0 +1,18 @@ +10 GRAPHICS 7+16 +20 FOR Y=0 TO 95 +30 FOR X=0 TO 159 +40 GOSUB 100 +50 NEXT X +60 NEXT Y +70 GOTO 70 +100 XP=X/159*2.7-2 +110 YP=Y/95*2-1 +120 IT=0:XX=0:YY=0 +130 XTEMP=XX*XX-YY*YY+XP +140 YY=2*XX*YY+YP +150 XX=XTEMP +160 IT=IT+1 +170 IF XX*XX+YY*YY<4 AND IT<20 THEN 130 +180 COLOR 1:IF IT=20 THEN COLOR 3 +190 PLOT X,Y +200 RETURN diff --git a/Task/Mandelbrot-set/FreeBASIC/mandelbrot-set.basic b/Task/Mandelbrot-set/FreeBASIC/mandelbrot-set.basic index 9abceba9b2..8dd4df4dd8 100644 --- a/Task/Mandelbrot-set/FreeBASIC/mandelbrot-set.basic +++ b/Task/Mandelbrot-set/FreeBASIC/mandelbrot-set.basic @@ -51,6 +51,8 @@ for x=0 to 639 next y next x +bsave "mandel.bmp",0 + while inkey="" wend end diff --git a/Task/Map-range/PascalABC.NET/map-range.pas b/Task/Map-range/PascalABC.NET/map-range.pas new file mode 100644 index 0000000000..1c7eb439af --- /dev/null +++ b/Task/Map-range/PascalABC.NET/map-range.pas @@ -0,0 +1,5 @@ +## +function maprange(a, b: (real, real); s: real) := b[0] + (s - a[0]) * (b[1] - b[0]) / (a[1] - a[0]); + +for var i := 0 to 10 do + Writeln(i, ' maps to ', maprange((0, 10), (-1, 0), i)); diff --git a/Task/Mastermind/FutureBasic/mastermind.basic b/Task/Mastermind/FutureBasic/mastermind.basic new file mode 100644 index 0000000000..f7a202c696 --- /dev/null +++ b/Task/Mastermind/FutureBasic/mastermind.basic @@ -0,0 +1,452 @@ +_window = 1 +_Check = 250 +_NewGame = 251 + +_view = 2000 + +_PrefWnd = 2 +begin enum 1 + _NoOfColours + _Label + _CodeLgth + _Label1 + _Guesses + _Repeats + _Label2 + _Exit + _info +end enum + +begin enum 1000 + _blue + _Red + _Yellow + _Magenta + _Orange + _Green + _Brown + _Cyan + _Purple + _DarkGray +end enum + +_mApplication = 0 +begin enum 0 + _iAbout + _iSeparator + _PreferencesItem + _iSeparator1 + _iHide +end enum + +_EditMenu = 1 + +begin enum + _iUndo + _iRedo + _ + _iCut + _iCopy + _iPaste + _iDelete + _iSelectAll +end enum + + +begin globals +CFStringRef gColours, gCodeLgth, gGuesses +BOOL gRepeats = NO, gWon = NO +ColorRef gNewColour +int gNextFld = 1, gRestriction = 1 +CFMutableArrayRef gArray +CFMutableArrayRef gTargetArray +CFMutableArrayRef gTargetColours +CFMutableArrayRef gGuessArray +int gLine = 1, gLastGuess, gLength +int gColor(12) +CFMutableArrayRef gRestrict +end globals + +// Colours 2 - 12 +// Code Lgth 4 - 10 +// Guesses 7 - 20 total fields 10*20 = 200 + +gArray = fn MutableArrayWithCapacity(0) +gTargetArray = fn MutableArrayWithCapacity(0) +gGuessArray = fn MutableArrayWithCapacity(0) +gRestrict = fn MutableArrayWithCapacity(0) +gTargetColours = fn MutableArrayWithCapacity(0) + +// Master Mind game + +void local fn SetBackgroundColor( col as ColorRef ) + TextFieldRef fld = fn ViewWithTag(gNextFld) + UndoManagerRef um = fn ResponderUndoManager( fld ) + UndoManagerRegisterUndo( um, @fn SetBackgroundColor, fn TextFieldBackgroundColor(fld)) + UndoManagerSetActionName( um, @"Set Background Color" ) + TextFieldSetBackgroundColor( fld, col ) +end fn + +LOCAL FN Max(Big as int,Little AS int) as int + int MaxNo + IF Big > Little THEN MaxNo = Big ELSE MaxNo = Little +END FN = MaxNo + +void local fn SetColor + for int x = 0 to 11 + gColor(x) = x + next +end fn + +local fn RandomChoice( count as int) as int + int x,i + Bool check = NO + DO + x = rnd( count + 1 ) - 1 + if gColor(x) > -1 + i = gColor(x ) + if gColor(x) == 0 + gColor(x) = -1 + else + gColor(x) = -gColor(x) + end if + check = YES + end if + until check == YES +end fn = i + +void local fn Winning + alert -1,, @"Message", @"You Won This Game", @"OK;Continue", YES + AlertButtonSetKeyEquivalent( 1, 1, @"\e" ) + alert 1 + gWon = YES +end fn + +void local fn SetTarget + int count = fn StringIntValue( gColours ) + int x, y + CFStringRef key + ColorRef col + MutableArrayRemoveAllObjects( gTargetArray ) + MutableArrayRemoveAllObjects( gTargetColours ) + + for x = 0 to count - 1 + if gRepeats == NO + y = fn RandomChoice( count ) + else + y = rnd( count + 1 ) - 1 + end if + key = fn StringWithFormat( @"%d", y) + col = fn ArrayObjectAtIndex( gArray, y ) + MutableArrayInsertObjectAtIndex( gTargetColours,col, x ) + MutableArrayInsertObjectAtIndex( gTargetArray,key, x ) + next +end fn + +void local fn SetFields + Int x,y,z = 1,xx,yy,zz = 299 + int CodeLgth = fn StringIntValue( gCodeLgth ) + int Guesses = fn StringIntValue( gGuesses ) + CGRect r, lr + gLastGuess = Guesses + xx = 20:yy = 40 + r = fn CGRectMake( xx, yy, 25, 25 ) + lr = fn CGRectMake( xx+CodeLgth*25 + 50, yy + 6, 12,12 ) + for x = 1 to Guesses + for y = 1 to CodeLgth + textfield z,,@"", r + ControlSetFontWithName(z,@"Times",12) + ControlSetAlignment( z, NSTextAlignmentCenter ) + TextFieldSetBackgroundColor( z, fn ColorWhite ) + r = fn CGRectOffset( r, 25, 0) + textfield z+zz,,@"",lr + TextFieldSetBackgroundColor( z+zz, fn ColorLightGray ) + z++ + lr = fn CGRectOffset( lr, 12,0) + next + lr = fn CGRectOffset( lr, -12*CodeLgth, 25 ) + r = fn CGRectOffset( r,-CodeLgth*25, 25) + next +end fn + +local fn FindColourAtPixel( tag as long ) as ColorRef +End Fn = fn ViewColorAtPoint( tag, fn EventLocationInView( tag )) + +local fn ClearTarget + int x, z = 3000 + int CodeLgth = fn StringIntValue( gCodeLgth ) + + for x = 0 to CodeLgth-1 + TextFieldSetBackgroundColor( z, fn ColorClear ) + z++ + next + textlabel 3100, @"" +end fn + +local fn ShowTarget + int x, z = 3000 + int CodeLgth = fn StringIntValue( gCodeLgth ) + int Guesses = fn StringIntValue( gGuesses ) + CGRect rr = fn CGRectMake( 20, Guesses*30 + 30, 25,25 ) + + for x = 0 to CodeLgth-1 + textfield z,,, rr + TextFieldSetBackgroundColor( z, fn ArrayObjectAtIndex( gTargetColours, x ) ) + rr = fn CGRectOffset( rr, 25, 0 ) + z++ + next + textlabel 3100, @"Target Array", ( 20, Guesses*30 + 60, 100, 26 ) +end fn + +void local fn BuildWnd + ColorRef col + Int x,z = 1,offset = 200 + CGRect r, rr + int lgth, wide + int CodeLgth = fn StringIntValue( gCodeLgth ) + int Guesses = fn StringIntValue( gGuesses ) + int Colour = fn StringIntValue( gColours ) + if Colour <= CodeLgth + select CodeLgth + case 4,5,6,7 + Colour += 3 + case 8,9,10 + Colour = 12 + end select + end if + if Guesses < 9 && Colour > 9 then offset += (Colour-Guesses) * 25 + CFArrayRef array = @[fn ColorBlue,fn ColorRed,fn ColorYellow,fn ColorMagenta,fn ColorOrange,fn ColorGreen,fn ColorBrown,fn ColorCyan,fn ColorPurple,fn ColorDarkGray,fn ColorSystemPink,fn ColorSystemTeal] + MutableArrayAddObjectsFromArray( gArray, array ) + wide = CodeLgth*37 + 180 + lgth = fn Max(Guesses*27 + offset, Colour*30 + 50 ) + gLength = lgth + window _window, @"Master Mind", ( 210,310,wide, lgth ) + ViewSetFlipped(_windowContentViewTag, YES) + fn SetFields + subclass view _view, ( wide - 65, 20,50, lgth - 60) + ViewSetFlipped( _view, YES ) + rr = fn CGRectMake( wide - 65, 20,50, lgth - 60) + rect rr,,8 + r = fn CGRectMake( 15, 15, 25,25) + z = 1000 + for x = 0 to Colour - 1 + col = fn ArrayObjectAtIndex( array, x) + subclass view z, r + ViewSetWantsLayer( z, YES ) + CALayerSetBackgroundColor( fn ViewLayer(z), col ) + ViewInitTrackingArea( z ) + ViewAddSubView( _view, z ) + r = fn CGRectOffset( r,0,30 ) + z++ + next + + button _Check, , , @"Check", ( 30, lgth - 65, 100, 26) + button _NewGame, , ,@"New Game", (150, lgth - 65, 100, 26 ) + +end fn + +void local fn Capture( wnd as long ) + int y, z + CFStringRef txt = @"" + + select Wnd + case _PrefWnd + gColours = fn PopUpButtonTitleOfSelectedItem(_NoOfColours) + gCodeLgth = fn PopUpButtonTitleOfSelectedItem(_CodeLgth) + gGuesses = fn PopUpButtonTitleOfSelectedItem(_Guesses) + if fn ButtonState( _Repeats ) == NSControlStateValueOn then gRepeats = YES else gRepeats = NO + fn SetColor + case _window + //if fn ButtonState( _Repeats ) == NSControlStateValueOn then gRepeats = YES else gRepeats = NO + z = fn StringIntValue( gCodeLgth ) + y = gLine*z - z + 1 + MutableArrayRemoveAllObjects( gGuessArray ) + for int x = y to (y + z - 1) + txt = fn ControlStringValue( x) + MutableArrayAddObject(gGuessArray, txt ) + next + gLine++ + if gLine > gLastGuess + fn ShowTarget + alert -1,, @"Message", @"You Fail to win this Game", @"OK;Continue", YES + AlertButtonSetKeyEquivalent( 1, 1, @"\e" ) + alert 1 + gWon = NO + end if + end select +end fn + +void local fn Compare + int x,y,count = fn StringIntValue( gCodeLgth ) + CFTypeRef target,guess,target1 + bool won = YES + + fn Capture( _window ) + gRestriction = 1 + //Check for location and colour + for x = 0 to count - 1 + target = fn ArrayObjectAtIndex( gTargetArray, x) + guess = fn ArrayObjectAtIndex( gGuessArray, x) + if target == guess + TextFieldSetBackgroundColor( (gLine-2)*count + 300 + x, fn ColorBlack ) + else + for y = 0 to count - 1 + won = NO + target1 = fn ArrayObjectAtIndex( gTargetArray, y) + if target1 == guess + TextFieldSetBackgroundColor( (gLine-2)*count + 300 + x, fn ColorWhite ) + end if + next + end if + next + ControlSetEnabled( _Check, NO ) + MutableArrayRemoveAllObjects( gRestrict ) + if won == YES then fn Winning +end fn + +void local fn NewGame + fn SetColor + fn SetFields + if gWon == NO + fn ClearTarget + end if + fn SetTarget + gLine = 1 + gNextFld = 1 +end fn + +void local fn Preferences + CGRect rr, lr + window _PrefWnd, @"Preferences", ( 0,0,250,350) + + rr = fn CGRectMake( 20,220,160,26) + lr = fn CGRectMake( 20,200, 60, 26 ) + textlabel _label, @"No Of Colours", rr + popupbutton _NoOfColours,,19, @"2;3;4;5;6;7;8;9;10;11;12", lr + rr = fn CGRectOffset( rr, 0, -50) + lr = fn CGRectOffset( lr, 0, -50) + textlabel _label1, @"No Of Items", rr + popupbutton _CodeLgth,,7,@"4;5;6;7;8;9;10", lr + rr = fn CGRectOffset( rr, 0, -50) + lr = fn CGRectOffset( lr, 0, -50) + textlabel _label2, @"No Of Guesses", rr + popupbutton _Guesses,,14,@"4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20", lr + rr = fn CGRectMake( 100,150,100,26) + button _Exit,,,@"Begin Game", rr + checkbox _Repeats,,,@"Repeats Allowed", ( 20, 70 , 160, 26 ) + rr = fn CGRectMake( 10,250, 230, 100) + textfield _info,,@"Move mouse over coloured square to choose\nThen move away from window\nRepeat for all fields\nThen click Check",rr + gNextFld = 1 + gRestriction = 1 + UserDefaultsRestoreWindowViewValues( _PrefWnd, NULL ) +end fn + +void Local Fn BuildMenu //build menu & get handle + menu _mApplication, _iAbout + menu _mApplication, _iSeparator + menu _mApplication, _PreferencesItem,, @"Settings…", @"," + menu _mApplication, _iSeparator1 + menu _mApplication, _iHide,, @"Hide Master Mind", @"h" + MenuItemSetAction( _mApplication, _iHide, @"hide:") + + EditMenu _EditMenu + /* + menu _EditMenu,_iUndo,YES + MenuItemSetActionCallBack( _EditMenu, _iUndo, @fn SetBackGroundColor, NULL ) + menu _EditMenu,_iRedo + + menu _EditMenu,_iCut + menu _EditMenu,_iCopy + menu _EditMenu,_iPaste + menu _EditMenu,_iDelete + menu _EditMenu,_iSelectAll + */ +end fn + +void local fn doMenu(act as long, ref as long ) + select act + case _mApplication + select ref + case _PreferencesItem + windowClose( _window) + fn Preferences + case else + end select + case _EditMenu + /* + select ref + case _iUndo + gNextFld-- + case _iRedo + gNextFld++ + case _iCut + case _iCopy + case _iPaste + case _iDelete + case _iSelectAll + end select + */ + end select +end fn + +void local fn doDialog( act as long, ref as long, wnd as long) + select Wnd + case _window + select act + case _BtnClick + select ref + case _Check : fn Compare + case _NewGame : fn NewGame + + end select + case _viewMouseEntered,_viewMouseDown + select ref + if gRepeats == NO && fn ArrayDoesContain( gRestrict, (ObjectRef)fn StringWithFormat( @"%d", ref )) == YES + else + if gRestriction < fn StringIntValue( gCodeLgth) + 1 + gNewColour = fn FindColourAtPixel( ref ) + ControlSetStringValue( gNextFld, fn StringWithFormat(@"%d",ref-1000)) + fn SetBackgroundColor( gNewColour ) + if gRepeats == NO + MutableArrayAddObject( gRestrict,fn StringWithFormat( @"%d", ref )) + end if + gNextFld++ + gRestriction++ + else + ControlSetEnabled( _Check, YES ) + end if + end if + end select + end select + case _PrefWnd + select act + case _btnClick + select ref + case _NoOfColours + gColours = fn PopUpButtonTitleOfSelectedItem(ref) + case _CodeLgth + gCodeLgth = fn PopUpButtonTitleOfSelectedItem(ref) + case _Guesses + gGuesses = fn PopUpButtonTitleOfSelectedItem(ref) + Case _Repeats + if fn ButtonState( _Repeats ) == NSControlStateValueOn then gRepeats = YES else gRepeats = NO + case _Exit + UserDefaultsStoreWindowViewValues( wnd, NULL ) + fn Capture (wnd ) + WindowClose( wnd) + fn BuildWnd + fn SetTarget + end select + end select + end select +end fn + + +fn Preferences +fn BuildMenu + + +on Dialog fn doDialog +on Menu fn doMenu + +HandleEvents diff --git a/Task/Mastermind/M2000-Interpreter/mastermind.m2000 b/Task/Mastermind/M2000-Interpreter/mastermind.m2000 new file mode 100644 index 0000000000..d5146cf1d7 --- /dev/null +++ b/Task/Mastermind/M2000-Interpreter/mastermind.m2000 @@ -0,0 +1,88 @@ +Module MasterMind { + cls #225522, 0 + GetInput=lambda (s as string, min as integer, max as integer) -> { + do + print s+"("+min+" - "+max+")"; + Input ":",v% + until v%>=min and v%<=max + =v% + } + GetInputGuess=lambda (moves as integer, length as integer, max as integer, once as boolean) -> { + string k, s + integer j, oldi + boolean check[max]=false + pen 15 {print str$(moves,"00")+". ";} + for i=1 to length + do + do + if oldi=i then beep + k=ucase$(key$) + j = asc(k)-64 + oldi=i + when j<1 or j>max + when once and check[j] + pen #99ffbb {print k;} + if once then check[j]=true + s+=k + next + =s + } + DisplayFinal=lambda (a) -> { + string s + for i=1 to len(a)-1 + s+=chr$(64+a[i]) + next + =s + } + pen 15 + integer C=GetInput("number of colors", 2, 20) + integer CL=GetInput("code length", 4, 10) + integer mn=GetInput("maximum number of guesses", 7, 20) + if c>=CL then + boolean rc=GetInput("colors may be repeated in the code", 0, 1) + else + boolean rc=true + end if + pen #00ff00 + Cls ,0 + integer acc[CL], i + do + if rc then + for i=1 to cl: acc[i]=random(1, C): next + else + boolean color[C] + for i=1 to cl + do + acc[i]=random(1, C) + when color[acc[i]] + color[acc[i]]=true + next + end if + string target=DisplayFinal(acc), z, mark + integer moves=1 + pen 15 {Print "Guess", @(20),"Mark"} + for i=1 to mn + z=GetInputGuess(i, CL, C, Not RC) + if target=z then exit for + mark="" + for j=1 to CL + if acc[j]=asc(mid$(z, j, 1))-64 then + mark+="X" + else.if instr(target, mid$(z, j, 1))>0 then + mark+="O" + else + mark+="-" + end if + next + Print @(20), mark + next + print + if target=z then + pen 15 {print "Guess Done"} + else + print "You loose, secret code was:"+target + end if + print "Play again ? (Y - N)" + Until ucase$(key$)<>"Y" +} +MasterMind diff --git a/Task/Matrix-digital-rain/Aquarius-BASIC/matrix-digital-rain.basic b/Task/Matrix-digital-rain/Aquarius-BASIC/matrix-digital-rain.basic new file mode 100644 index 0000000000..f9c961c005 --- /dev/null +++ b/Task/Matrix-digital-rain/Aquarius-BASIC/matrix-digital-rain.basic @@ -0,0 +1,22 @@ +10 DIM P(40),ACT(40),S(40) +20 FOR I=0 TO 1000:POKE 13312+I,0:NEXT + +100 CA=0 +110 FOR X=0 TO 39:IF ACT(X)=0 THEN 180 +120 CA=CA+1 +130 IF S(X)=0 THEN Y=P(X)-1:COL=0:GOSUB 1000:GOTO 160 +140 Y=P(X):COL=112:IF Y<24 THEN GOSUB 1000 +150 Y=P(X)-1:COL=32:GOSUB 1000 +160 P(X)=P(X)+1 +170 IF P(X)=25 THEN ACT(X)=0 +180 NEXT X +190 IF CA<6 AND RND(1)<.1 THEN GOSUB 2000 +200 GOTO 100 + +1000 POKE 13312+40*Y+X,COL +1010 POKE 12288+40*Y+X,INT(255*RND(1)) +1020 RETURN + +2000 NX=38*RND(1)+1:ACT(NX)=1:P(NX)=1:OLD=S(NX) +2010 S(NX)=0:IF OLD=0 THEN S(NX)=1 +2020 RETURN diff --git a/Task/Matrix-digital-rain/M2000-Interpreter/matrix-digital-rain.m2000 b/Task/Matrix-digital-rain/M2000-Interpreter/matrix-digital-rain.m2000 new file mode 100644 index 0000000000..c471dde51f --- /dev/null +++ b/Task/Matrix-digital-rain/M2000-Interpreter/matrix-digital-rain.m2000 @@ -0,0 +1,56 @@ +module MatrixRain { + a$="寿司历史可追溯至2000年前日本开始发展水稻种植的时期。寿司的雏形出现于弥生时代,当时的人发明了将食用鱼加盐在米饭中发酵的做法,即今日的熟寿司,此时米饭为发酵所用材料,并不食用。到了室町时代,其中发酵过的米饭变得也可以食用。在江户时代,醋逐渐取代了发酵米饭的地位。而到了近现代,寿司则成为了一种与日本文化紧密相关的快餐食品。" + r=random(!4324234) + + p3=pi*3/2 + double m[120] + single x[120], y[120] + long t[120], k[120], s[120], z[120], q[120], p[120] + hide + background { + for i=1 to 120 + t[i]=random(1, 10) + x[i]=random(0, scale.x) + y[i]=random(-1000, scale.y/2) + k[i]=random(20, 50) + s[i]=random(30, 60) + z[i]=random(8, 22) + q[i]=random(1, len(a$)-20) + p[i]=10 + m[i]=1+rnd/100 + next + refresh 1000 + do + pen 0, 50 + gradient 0, #002200 + for i=1 to 120 + if k[i]<20 then + y[i]+=twipsY*s[i] + move @f(x[i]), y[i] :m[i]*=1.006 + pen #00aa00, t[i]*(22-p[i])/20+20 + legend mid$(a$, q[i],p[i]), fontname$, z[i], p3 + if p[i]>2 then q[i]++:p[i]-- + end if + k[i]-- + if k[i]=0 then + q[i]=random(1, len(a$)-20):p[i]=10 + y[i]=random(-1000, scAle.y/4): k[i]=random(15, 30):z[i]=random(8, 22) + m[i]=1+rnd/100:s[i]=random(30, 60) + end if + next + refresh 1000 + if inkey$=" " then exit + pen 14, 255 + always + } + background {cls} + show + function f(x) + if x0 then print #f, ", "; + print #f, "("; + if dimension(a(),2,1)>1 then + for j=0 to dimension(a(),2,1)-1 + print #f, a(i, j)+", "; + next + print #f, a(i, j)+")"; + else + print #f, a(i, 0)+",)"; + end if + next + if z then print #f, ",)" else print #f, ")" + end sub + sub showarray2(title$, a as *Long) + ' handle with one or zero sub arrays + print #f, title$+": ["; + for i=0 to len(a)-1 + if i>0 then print #f, ", "; + if valid(len(a[i])) then + print #f, "["; + if len(a[i])>1 then + for j=0 to len(a[i])-2 + print #f, a[i][j]+", "; + next + else + j=0 + end if + print #f, a[i][j]+"]"; + else + print #f, a[i]; + end if + next + print #f, "]" + end sub + function transposeLong(a as *long) + Local long R=Len(a)-1 ' upper bound dim 1 + Local long L=len(a[0])-1 ' upper bound dim 2 + local long b[L][R] + for i=0 to L + for j=0 to R + b[i][j]=a[j][i] + next + next + =b + End Function + function transposeAny(a) + if not valid(a[0][0]) then Error "Wrong Type" + Local long R=Len(a)-1 ' upper bound dim 1 + Local long L=len(a[0])-1 ' upper bound dim 2 + local Variant b[L][R] + for i=0 to L + for j=0 to R + b[i][j]=a[j][i] + next + next + =b + End Function + function transpose(a as array) + // we use a as pointer to array + // if we use transpose(a()) we get a copy on a() + // so we make one copy only + // copy a to a() + Local a() + a()=a + push &a + Read new &b() + Local long R=dimension(a(),1,1) ' upper bound dim 1 + Local long L=dimension(a(),2,1) ' upper bound dim 2 + ' this is a redim, and preserve the array type also + Dim a(L+1,R+1) + for i=0 to L + for j=0 to R + a(i,j)=b(j, i) + next + next + =a() + End Function +} +Matrix_Transpose diff --git a/Task/Maximum-triangle-path-sum/PascalABC.NET/maximum-triangle-path-sum.pas b/Task/Maximum-triangle-path-sum/PascalABC.NET/maximum-triangle-path-sum.pas new file mode 100644 index 0000000000..b17568558e --- /dev/null +++ b/Task/Maximum-triangle-path-sum/PascalABC.NET/maximum-triangle-path-sum.pas @@ -0,0 +1,35 @@ +var + data := arr( + |55|, + |94, 48|, + |95, 30, 96|, + |77, 71, 26, 67|, + |97, 13, 76, 38, 45|, + |07, 36, 79, 16, 37, 68|, + |48, 07, 09, 18, 70, 26, 06|, + |18, 72, 79, 46, 59, 79, 29, 90|, + |20, 76, 87, 11, 32, 07, 07, 49, 18|, + |27, 83, 58, 35, 71, 11, 25, 57, 29, 85|, + |14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55|, + |02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23|, + |92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42|, + |56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72|, + |44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36|, + |85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52|, + |06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15|, + |27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93|); + +function solve(triangle: array of array of integer): integer; +begin + var rows := triangle.Count; + var sumrow := triangle[rows - 1]; + for var row := rows - 1 downto 1 do + sumrow := sumrow.Pairwise((x, y) -> Max(x, y)) + .Zip(triangle[row - 1], (x, y) -> x + y).ToArray; + + result := sumrow[0]; +end; + +begin + solve(data).Println; +end. diff --git a/Task/Mayan-calendar/FutureBasic/mayan-calendar.basic b/Task/Mayan-calendar/FutureBasic/mayan-calendar.basic new file mode 100644 index 0000000000..46e164ebff --- /dev/null +++ b/Task/Mayan-calendar/FutureBasic/mayan-calendar.basic @@ -0,0 +1,107 @@ +//================================================================= +// Convert Gregorian to real Julian Date (not JDE) +// on entry Gregorian M = month, D = day, Y = YYYY +// on exit Long JD = Julian Date +//================================================================= + +local fn Greg2Julian (M as Int, D as Int, Y as Int) as Long + Long JD + JD= D-32075+1461*(Y+4800+(M-14)/12)/4+367*(M-2-(M-14)/12*12)/12-3*((Y+4900+(M-14)/12)/100)/4 +End fn = JD + +//================================================================== +// Convert Gregorian to Mayan Calendar +// on entry Gregorian M = month, D = day, Y = YYYY +// On exit CFStringRef of Mayan calendar +//================================================================== +local fn Greg2Mayan (M as Int, D as Int, Y as Int) as CFStringRef + + CFStringRef tM(19),hM(18) //Tzolkin and Haad Months + CFStringRef result + Long longParts(5) + Double remainder + Double JulianDays //Julian Date + Double LCD(4) //long count days + Double correlation //Day of creation GTM + correlation = 584283 //Julian date of Monday 3114 B.C. September 6, @noon + CFStringRef longDate, roundDate, HaabDay, tmp + Long tzolkinMonth, tzolkinDay + Long haabMonth, haabDayNum + Long lordNumber // Lord of the Nights, nine Deity, God 1 through God 9 (G1 - G9) + Int i + + // Sacred Tzolk'in Months, 20 days + + tM(0) = @"Imix'": tM(1) = @"Ik'": tM(2) = @"Ak'bal": tM(3) = @"K'an" + tM(4) = @"Chikchan": tM(5) = @"Kimi": tM(6) = @"Manik'": tM(7) = @"Lamat" + tM(8) = @"Muluk": tM(9) = @"Ok": tM(10) = @"Chuwen": tM(11) = @"Eb" + tM(12) = @"Ben": tM(13) = @"Hix": tM(14) = @"Men": tM(15) = @"K'ib'" + tM(16) = @"Kaban": tM(17) = @"Etz'nab'": tM(18) = @"Kawak": tM(19) = @"Ajaw" + + // Civil Haab Months 20 days + + hM(0) = @"Pop": hM(1) = @"Wo'": hM(2) = @"Sip": hM(3) = @"Sotz'" + hM(4) = @"Sek": hM(5) = @"Xul": hM(6) = @"Yaxk'in": hM(7) = @"Mol" + hM(8) = @"Ch'en": hM(9) = @"Yax": hM(10) = @"Sak'": hM(11) = @"Keh" + hM(12) = @"Mak": hM(13) = @"K'ank'in": hM(14) = @"Muwan": hM(15) = @"Pax" + hM(16) = @"K'ayab": hM(17) = @"Kumk'u": hM(18) = @"Wayeb'" + + // Long count days + + LCD(0) = 144000: LCD(1) = 7200: LCD(2) = 360: LCD(3) = 20: LCD(4) = 1 + + JulianDays = fn Greg2Julian (M, D, Y) + remainder = JulianDays - correlation + For i = 0 To 4 + longParts(i) = Fix(remainder / LCD(i)) + remainder = remainder - (longParts(i) * LCD(i)) + Next i + + longDate = @"" + For i = 0 To 4 + If i > 0 Then longDate = concat (longDate,@".") + tmp = mid(str(longParts(i)),1) + if len(tmp) < 2 then tmp = concat(@"0",tmp) + longDate = concat(longDate, tmp) + Next i + + tzolkinMonth = fix((julianDays + 16) Mod 20) + tzolkinDay = fix(((julianDays + 5) Mod 13)) + 1 + + haabMonth = fix(((julianDays + 65) Mod 365) / 20) + haabDayNum = fix(((julianDays + 65) Mod 365) Mod 20) + + If haabDayNum = 0 + haabDay = @"Chum" + Else + haabDay = mid(Str(haabDayNum),1) + End If + + lordNumber = Fix((julianDays - correlation) Mod 9) + If lordNumber = 0 Then lordNumber = 9 + + roundDate = @"" + roundDate = concat(roundDate, @" ", mid(str(tzolkinDay),1), @"\t", tM(tzolkinMonth), @" ", haabDay, @" ", hM(haabMonth), @" G", mid(str(lordNumber),1)) + result = concat(longDate, @" ", roundDate) +end fn = result + +Window 1 + +CFStringRef mayanDate, GregDate +CFArrayRef comps +Int i,mm,dd,yy +CFStringRef testDate(7) +testDate(1) = @"2004-06-19": testDate(2) = @"2012-12-18": testDate(3) = @"2012-12-21": testDate(4) = @"2019-01-19" +testDate(5) = @"2019-03-27": testDate(6) = @"2020-02-29": testDate(7) = @"2020-03-01" + +for i = 1 to 7 + GregDate = testDate(i) + comps = fn StringComponentsSeparatedByString(GregDate, @"-" ) + dd = IntVal(comps[2]) + mm = IntVal(comps[1]) + yy = IntVal(comps[0]) + mayanDate = fn Greg2Mayan (mm,dd,yy) + print GregDate;" - ";mayanDate +next i + +handleEvents diff --git a/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 b/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 index f0fd0485e1..b73c42a4b5 100644 --- a/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 +++ b/Task/Maze-generation/M2000-Interpreter/maze-generation-1.m2000 @@ -1,56 +1,52 @@ -Module Maze { - width% = 40 - height% = 20 - \\ we can use DIM maze$(0 to width%,0 to height%)="#" - \\ so we can delete the two For loops - DIM maze$(0 to width%,0 to height%) - FOR x% = 0 TO width% - FOR y% = 0 TO height% - maze$(x%, y%) = "#" - NEXT y% - NEXT x% +MODULE Maze { + INTEGER W = 40, H = 20, X, Y, CX, CY, OX, OY, I + BOOLEAN DONE + DIM MAZE(0 TO W, 0 TO H) AS STRING + FOR X = 0 TO W + FOR Y = 0 TO H + MAZE(X, Y) = "#" + NEXT Y + NEXT X - currentx% = INT(RND * (width% - 1)) - currenty% = INT(RND * (height% - 1)) + CX = RND * (W - 1) + CY = RND * (H - 1) - IF currentx% MOD 2 = 0 THEN currentx%++ - IF currenty% MOD 2 = 0 THEN currenty%++ - maze$(currentx%, currenty%) = " " + IF CX MOD 2 = 0 THEN CX++ + IF CY MOD 2 = 0 THEN CY++ + MAZE(CX, CY) = " " - done% = 0 - WHILE done% = 0 { - FOR i% = 0 TO 99 - oldx% = currentx% - oldy% = currenty% - SELECT CASE INT(RND * 4) + WHILE NOT DONE + FOR I = 0 TO 99 + OX = CX + OY = CY + SELECT CASE RANDOM(0, 3) CASE 0 - IF currentx% + 2 < width% THEN currentx%+=2 + IF CX + 2 < W THEN CX+=2 CASE 1 - IF currenty% + 2 < height% THEN currenty%+=2 + IF CY + 2 < H THEN CY+=2 CASE 2 - IF currentx% - 2 > 0 THEN currentx%-=2 + IF CX - 2 > 0 THEN CX-=2 CASE 3 - IF currenty% - 2 > 0 THEN currenty%-=2 + IF CY - 2 > 0 THEN CY-=2 END SELECT - IF maze$(currentx%, currenty%) = "#" Then { - maze$(currentx%, currenty%) = " " - maze$(INT((currentx% + oldx%) / 2), ((currenty% + oldy%) / 2)) = " " - } - NEXT i% - done% = 1 - FOR x% = 1 TO width% - 1 STEP 2 - FOR y% = 1 TO height% - 1 STEP 2 - IF maze$(x%, y%) = "#" THEN done% = 0 - NEXT y% - NEXT x% - } + IF MAZE(CX, CY) = "#" THEN + MAZE(CX, CY) = " " + MAZE((CX + OX) DIV 2, (CY + OY) DIV 2) = " " + END IF + NEXT I + DONE = TRUE + FOR X = 1 TO W - 1 STEP 2 + FOR Y = 1 TO H - 1 STEP 2 + IF MAZE(X, Y) = "#" THEN DONE = FALSE + NEXT Y + NEXT X + END WHILE - - FOR y% = 0 TO height% - FOR x% = 0 TO width% - PRINT maze$(x%, y%); - NEXT x% + FOR Y = 0 TO H + FOR X = 0 TO W + PRINT MAZE(X, Y); + NEXT X PRINT - NEXT y% + NEXT Y } Maze diff --git a/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 b/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 index 9f5c8762a4..1e0759ec34 100644 --- a/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 +++ b/Task/Maze-generation/M2000-Interpreter/maze-generation-2.m2000 @@ -1,43 +1,67 @@ Module Maze2 { \\ depth-first search - Profiler + While Inkey$<>"" {} ' drop keys + Const View as boolean=True + Double tcc + Form 80,50 - let w=60, h=40 +again: + Gradient 5,6 + Cursor 0,0 + let w=random(2,6)*10, h=random(1,4)*10, slice=w*h div 30 + let slice=if(slice=0->1, slice) : counter =1 Double \\center proportional text double size Report 2, Format$("Maze {0}x{1}",w,h) Normal + Hold Refresh Set Fast ! - Dim maze$(1 to w+1, 1 to h+1)="#" - Include=Lambda w,h (a,b) ->a>=1 and a<=w and b>=1 and b<=h - Flush ' empty stack - if random(1,2)=1 then { - entry=(if(random(1,2)=1->2, w),Random(1, h/2)*2) - } else { - entry=(random(1,w/2)*2,If(Random(1,2)=1->2,h)) + stack new { + Profiler + Dim maze$(1 to w+1, 1 to h+1)="#" + Include=Lambda w,h (a,b) ->a>=1 and a<=w and b>=1 and b<=h + Flush ' empty stack + if random(1,2)=1 then + entry=(if(random(1,2)=1->2, w),Random(1, h/2)*2) + else + entry=(random(1,w/2)*2,If(Random(1,2)=1->2,h)) + end if + maze$(entry#val(0), entry#val(1))=" " + forchoose=(,) + Push Entry + do + do + NewForChoose(!entry) + status=len(forchoose) + if status>0 then + status-- + forchoose=forchoose#val(random(0,status)) + Push forchoose + OpenDoor(!Entry, !forchoose) + if view then counter=if(counter=0->slice, counter-1) : if counter=0 then ShowMaze() + else + exit + end if + entry=forchoose + Always + if empty then exit + Read entry + Always + tc= timecount/1000 } - maze$(entry#val(0), entry#val(1))=" " - forchoose=(,) - Push Entry - do { - do { - NewForChoose(!entry) - status=len(forchoose) - if status>0 then { - status-- - forchoose=forchoose#val(random(0,status)) - Push forchoose - OpenDoor(!Entry, !forchoose) - Rem : ShowMaze() - } else exit - entry=forchoose - } Always - if empty then exit - Read entry - } Always ShowMaze() - Print timecount/1000 + Cursor 0,Height-1 + Print Part $(6,width), ~(15,0,0),"Press a key or mouse button after any drawing of the maze to exit - "+format$("{0:3}",tc) + Refresh + counter=10 + every 200 { + counter-- + if inkey$<>"" or mouse<>0 then counter=-1 : exit + if counter<1 then exit + } + if counter=0 then Release : goto again + End Sub NewForChoose(x,y) Local x1=x-2, x2=x+2, y1=y-2, y2=y+2, arr=(,) Stack New { @@ -50,19 +74,21 @@ Module Maze2 { End Sub Sub OpenDoor(x1,y1, x2,y2) Local i - if x1=x2 then { + if x1=x2 then y1+=y2<=>y1 - for i=y1 to y2 {maze$(x1, i)=" " } - } Else { + for i=y1 to y2 step sgn(y2-y1) {maze$(x1, i)=" " } + Else x1+=x2<=>x1 - for i=x1 to x2 {maze$(i, y1)=" "} - } + for i=x1 to x2 step sgn(x2-x1) {maze$(i, y1)=" "} + End if End Sub Sub ShowMaze() Refresh 5000 - cls ,4 ' split screen - preserve lines form 0 to 3 - Local i, j - For j=1 to h+1 { Print @(10) : for i=1 to w+1 {Print maze$(i,j);}:Print} +Rem cls ,4 ' split screen - preserve lines form 0 to 3 + Release + cursor 0,(height-h) div 2 + Local i, j, t=40-w div 2 + For j=1 to h+1 { Print @(t) : for i=1 to w+1 {Print maze$(i,j);}:Print} Print Refresh 100 End Sub diff --git a/Task/Maze-generation/PascalABC.NET/maze-generation.pas b/Task/Maze-generation/PascalABC.NET/maze-generation.pas new file mode 100644 index 0000000000..5291470844 --- /dev/null +++ b/Task/Maze-generation/PascalABC.NET/maze-generation.pas @@ -0,0 +1,29 @@ +const + w = 14; + h = 10; + +var + vis := (0..h - 1).Select(x -> [false] * w).ToArray; + hor := (0..h).select(x -> ['+---'] * w + [string('+')]).ToArray; + ver := (0..h - 1).select(x -> ['| '] * w + [string('|')]).ToArray; + +procedure walk(x, y: integer); +begin + vis[y][x] := true; + foreach var p in ||x - 1, y|, |x, y + 1|, |x + 1, y|, |x, y - 1||.Shuffle do + begin + if (p[0] not in (0..w - 1)) or (p[1] not in (0..h - 1)) or vis[p[1]][p[0]] then continue; + if p[0] = x then hor[max(y, p[1])][x] := '+ '; + if p[1] = y then ver[y][max(x, p[0])] := ' '; + walk(p[0], p[1]); + end; +end; + +begin + walk(random(w), random(h)); + foreach var (a, b) in hor.zip(ver + [''], (x, y) -> (x, y)) do + begin + a.println(''); + b.println(''); + end; +end. diff --git a/Task/McNuggets-problem/ALGOL-W/mcnuggets-problem.alg b/Task/McNuggets-problem/ALGOL-W/mcnuggets-problem.alg new file mode 100644 index 0000000000..0db3731f01 --- /dev/null +++ b/Task/McNuggets-problem/ALGOL-W/mcnuggets-problem.alg @@ -0,0 +1,25 @@ +begin % Solve the McNuggets problem: find the largest n <= 100 for which there % + % are no non-negative integers x, y, z such that 6x + 9y + 20z = n % + integer maxNuggets; + maxNuggets := 100; + begin + logical array isSum ( 0 :: maxNuggets ); + integer largest; + % find the numbers that can be formed % + for x := 0 step 6 until maxNuggets do begin + for y := x step 9 until maxNuggets do begin + for z := y step 20 until maxNuggets do isSum( z ) := true + end for_y + end for_x ; + % show the highest number that cannot be formed % + largest := -1; + for i := maxNuggets step -1 until 0 do begin + if not isSum( i ) then begin + largest := i; + goto foundLargest + end if_not_isSum_i + end for_i; +foundLargest: + write( i_w := 1, s_w := 0, "The largest non-McNugget number is: ", largest ) + end +end. diff --git a/Task/McNuggets-problem/PascalABC.NET/mcnuggets-problem.pas b/Task/McNuggets-problem/PascalABC.NET/mcnuggets-problem.pas new file mode 100644 index 0000000000..649f9066ea --- /dev/null +++ b/Task/McNuggets-problem/PascalABC.NET/mcnuggets-problem.pas @@ -0,0 +1,6 @@ +## +var nuggets := [0..100]; +foreach var (x, y, z) in Cartesian(Range(0, 100 div 6), Range(0, 100 div 9), Range(0, 100 div 20)) do + Exclude(nuggets, 6 * x + 9 * y + 20 * z); + +nuggets.Max.println; diff --git a/Task/Median-filter/FreeBASIC/median-filter.basic b/Task/Median-filter/FreeBASIC/median-filter.basic new file mode 100644 index 0000000000..1e23743325 --- /dev/null +++ b/Task/Median-filter/FreeBASIC/median-filter.basic @@ -0,0 +1,64 @@ +' Set up dimensions +Const ancho = 400 +Const alto = 400 + +' Create arrays +Dim As Integer salida(ancho-1, alto-1) +Dim As Integer pix(24) +Dim As Integer x, y, p, i, j, col + +' Set up graphics +Screenres ancho, alto, 32 +Windowtitle "Median Filter" + +' Create image buffer +'Dim imagen As Any Ptr = Imagecreate(ancho, alto, Rgb(0,0,0)) +Dim imagen As Any Ptr = Imagecreate(ancho, alto) +' Load image +Bload "i:\plasma.bmp", imagen +Put (0, 0), imagen, Pset + +' Create buffer for filtered image +Dim imagenFiltrada As Any Ptr = Imagecreate(ancho, alto) + +' Median filtering +For y = 2 To alto-3 + For x = 2 To ancho-3 + p = 0 + For i = -2 To 2 + For j = -2 To 2 + ' Get pixel value from source image + pix(p) = Point(((x+i)), ((y+j))) And &hFF + p += 1 + Next j + Next i + + ' Sort the pixels (bubble sort) + For i = 0 To 23 + For j = 0 To 23-i + If pix(j) > pix(j+1) Then Swap pix(j), pix(j+1) + Next j + Next i + + ' Store median value + salida(x, y) = pix(12) + Next x +Next y + +' Display filtered result and store in buffer +For y = 0 To alto-1 + For x = 0 To ancho-1 + col = salida(x, y) + Pset(x, y), Rgb(col, col, col) + Pset imagenFiltrada, (x, y), Rgb(col, col, col) + Next x +Next y + +' Save filtered image +Bsave "i:\plasmamedian.bmp", imagenFiltrada + +' Free image memory +Imagedestroy imagen +Imagedestroy imagenFiltrada + +Sleep diff --git a/Task/Meissel-Mertens-constant/PascalABC.NET/meissel-mertens-constant.pas b/Task/Meissel-Mertens-constant/PascalABC.NET/meissel-mertens-constant.pas new file mode 100644 index 0000000000..7391f06912 --- /dev/null +++ b/Task/Meissel-Mertens-constant/PascalABC.NET/meissel-mertens-constant.pas @@ -0,0 +1,27 @@ +function gen_primes_upto(n: integer): sequence of integer; +begin + if n < 3 then exit; + var table := |True| * n; + var sqrtn := n.sqrt.Floor; + for var i := 2 to sqrtn do + if table[i] then + for var j := i * i to n - 1 step i do + table[j] := False; + + yield 2; + for var i := 3 to n step 2 do + if table[i] then yield i +end; + +begin + var γ := 0.57721566490153286; + var sum := 0.0; + foreach var p in gen_primes_upto(10_000_000_000) index i do + begin + var rp := 1 / p; + sum += ln(1 - rp) + rp; + // inc count + if (i+1) mod 10_000_000 = 0 then + writeln(i+1, sum + γ:20); + end; +end. diff --git a/Task/Memory-allocation/68000-Assembly/memory-allocation-1.68000 b/Task/Memory-allocation/68000-Assembly/memory-allocation-1.68000 index 4e3854c474..26705bfaec 100644 --- a/Task/Memory-allocation/68000-Assembly/memory-allocation-1.68000 +++ b/Task/Memory-allocation/68000-Assembly/memory-allocation-1.68000 @@ -1,5 +1,5 @@ MyFunction: -LINK A6,#-16 ;create a stack frame of 16 bytes. Now you can safely write to (SP+0) thru (SP+15). +LINK A6,#-16 ;create a stack frame of 16 bytes. Now you can safely write to anywhere from (SP+0) to (SP+15) inclusive. ;;;; your code goes here. diff --git a/Task/Menu/AArch64-Assembly/menu.aarch64 b/Task/Menu/AArch64-Assembly/menu.aarch64 index 790529acbc..acfe5994fc 100644 --- a/Task/Menu/AArch64-Assembly/menu.aarch64 +++ b/Task/Menu/AArch64-Assembly/menu.aarch64 @@ -23,7 +23,7 @@ szCarriageReturn: .asciz "\n" szMessFinOK: .asciz "Program normal end. \n" szMessError: .asciz "\nError Buffer too small!!!\n" -szChoose: .asciz "\nMake your choise: " +szChoose: .asciz "\nMake your choice: " szMessErrorNum: .asciz "Error : number do not exists!!\n" szMesschoose: .asciz "\nYou have chosen: " szLigne1: .asciz "fee fie" diff --git a/Task/Menu/ARM-Assembly/menu.arm b/Task/Menu/ARM-Assembly/menu.arm index c7571f5766..79834fbae1 100644 --- a/Task/Menu/ARM-Assembly/menu.arm +++ b/Task/Menu/ARM-Assembly/menu.arm @@ -28,7 +28,7 @@ szCarriageReturn: .asciz "\n" szMessFinOK: .asciz "Program normal end. \n" szMessError: .asciz "\nError Buffer too small!!!\n" -szChoose: .asciz "\nMake your choise: " +szChoose: .asciz "\nMake your choice: " szMessErrorNum: .asciz "Error : number do not exists!!\n" szMesschoose: .asciz "\nYou have chosen: " szLigne1: .asciz "fee fie" diff --git a/Task/Menu/Action-/menu.action b/Task/Menu/Action-/menu.action index 49a3b9c616..6ebf118abd 100644 --- a/Task/Menu/Action-/menu.action +++ b/Task/Menu/Action-/menu.action @@ -21,7 +21,7 @@ BYTE FUNC GetMenuItem(PTR ARRAY items BYTE count) DO ShowMenu(items,count) PutE() - Print("Make your choise: ") + Print("Make your choice: ") res=InputB() UNTIL res>=1 AND res<=count OD diff --git a/Task/Menu/Langur/menu.langur b/Task/Menu/Langur/menu.langur index 44a20d9a8e..fd8a49e707 100644 --- a/Task/Menu/Langur/menu.langur +++ b/Task/Menu/Langur/menu.langur @@ -1,18 +1,19 @@ -val choose = impure fn(entries) { +val choose = fn*(entries) { if entries is not list: throw "invalid args" if not entries: return "" # print the menu - writeln join("\n", map(fn e, i: "{{i:2}}: {{e}}", entries, 1..len(entries))) + writeln join(map(entries, 1..len(entries), by=fn e, i:"{{i:2}}: {{e}}"), by="\n") val idx = read( - "Select entry #: ", - fn(x) { + prompt="Select entry #: ", + validation=fn(x) { if not x -> RE/^[0-9]+$/: return false val y = x -> number y > 0 and y <= len(entries) }, - "invalid selection\n", -1, + errmsg="invalid selection\n", + maxattempts=-1, ) -> number entries[idx] diff --git a/Task/Menu/Quackery/menu.quackery b/Task/Menu/Quackery/menu.quackery new file mode 100644 index 0000000000..d43ff51b32 --- /dev/null +++ b/Task/Menu/Quackery/menu.quackery @@ -0,0 +1,17 @@ + [ swap dup [] = iff nip done + [ dup witheach + [ i^ 1+ echo say ") " + echo$ cr ] + over input + $->n not iff drop again + dup 1 < iff drop again + over size + over < iff drop again ] + rot drop 1 - peek ] is menu ( [ $ --> $ ) + + ' [ $ "fee fie" $ "huff and puff" + $ "mirror mirror" $ "tick tock" ] + [] swap witheach [ do nested join ] + + $ "What does a clock say? " menu + say "Your answer: " echo$ diff --git a/Task/Mertens-function/PascalABC.NET/mertens-function.pas b/Task/Mertens-function/PascalABC.NET/mertens-function.pas new file mode 100644 index 0000000000..0f6b50e7d3 --- /dev/null +++ b/Task/Mertens-function/PascalABC.NET/mertens-function.pas @@ -0,0 +1,21 @@ +function mertens(max: integer): list; +begin + result := (0..max).select( x -> 1).ToList; + foreach var n in 2..max do + foreach var k in 2..n do + result[n] -= result[n div k]; +end; + +begin + println('The first 99 Mertens numbers are:'); + foreach var m in mertens(99) index i do + if i = 0 then write(' ') + else write(m:3, if i mod 10 = 9 then #10 else ''); + + var zeroes := mertens(1000).Where(x -> x = 0).Count; + println('M(N) equals zero', zeroes, 'times.'); + + var crosses := mertens(1000).Zip(mertens(1000).Skip(1), (x, y) -> (x <> 0) and (y = 0)) + .Where(x -> x).Count; + println('M(N) crosses zero', crosses, 'times.'); +end. diff --git a/Task/Metallic-ratios/PascalABC.NET/metallic-ratios.pas b/Task/Metallic-ratios/PascalABC.NET/metallic-ratios.pas new file mode 100644 index 0000000000..e320bdb1ed --- /dev/null +++ b/Task/Metallic-ratios/PascalABC.NET/metallic-ratios.pas @@ -0,0 +1,63 @@ +type + Metal = (platinum, golden, silver, bronze, copper, nickel, aluminium, iron, tin, lead); + +function seq(b: integer): sequence of biginteger; +begin + // Yield the successive terms if a “Lucas” sequence. + // The first two terms are ignored. + var x := 1bi; + var y := 1bi; + while true do + begin + x += b * y; + Swap(x, y); + yield y; + end; +end; + +function plural(n: integer) := if n >= 2 then 's' else ''; + +procedure computeRatio(b: integer; digits: integer); +begin + // Compute the ratio for the given "n" with the required number of digits. + + var M := Power(10bi, digits); + + var niter := 0; // Number of iterations. + var prevN := 1bi; // Previous value of "n". + var ratio := M ; // Current value of ratio. + + foreach var n in seq(b) do + begin + inc(niter); + var nextRatio := n * M div prevN; + if nextRatio = ratio then break; + prevN := n; + ratio := nextRatio; + end; + + var str := ratio.ToString; + insert('.', str, 2); + Writeln('Value to ', digits, ' decimal places after ', niter, ' iteration', plural(niter), ': ',str); +end; + +begin + foreach var b in 0..9 do + begin + Writeln('“Lucas” sequence for ', Metal(b), ' ratio where b = ', b, ':'); + Write('First 15 elements: 1 1 '); + var count := 2; + foreach var n in seq(b) do + begin + Write(' ', n); + Inc(count); + if count = 15 then break + end; + println; + computeRatio(b, 32); + Println; + end; + + Println('Golden ratio where b = 1:'); + computeRatio(1, 256); +end. diff --git a/Task/Metered-concurrency/PascalABC.NET/metered-concurrency.pas b/Task/Metered-concurrency/PascalABC.NET/metered-concurrency.pas new file mode 100644 index 0000000000..28eea66021 --- /dev/null +++ b/Task/Metered-concurrency/PascalABC.NET/metered-concurrency.pas @@ -0,0 +1,20 @@ +uses System, System.Threading, System.Threading.Tasks; + +procedure Worker(arg: SemaphoreSlim; id: integer); +begin + var sem: SemaphoreSlim := arg; + sem.Wait(); + Writeln('Thread ', id, ' has a semaphore & is now working.'); + Thread.Sleep(2 * 1000); + Writeln('#', id, 'done.'); + sem.Release(); +end; + +begin + var semaphore := new SemaphoreSlim(Environment.ProcessorCount * 2, MaxInt); + + Writeln('You have ', Environment.ProcessorCount, ' processors availiabe'); + Writeln('This program will use ', semaphore.CurrentCount, ' semaphores.'); + + Parallel.For(0, Environment.ProcessorCount * 3, y -> Worker(semaphore, y)); +end. diff --git a/Task/Mian-Chowla-sequence/PascalABC.NET/mian-chowla-sequence.pas b/Task/Mian-Chowla-sequence/PascalABC.NET/mian-chowla-sequence.pas new file mode 100644 index 0000000000..6d9a76aa64 --- /dev/null +++ b/Task/Mian-Chowla-sequence/PascalABC.NET/mian-chowla-sequence.pas @@ -0,0 +1,29 @@ +function mian_chowla(): sequence of integer; +label 1; +begin + var mc := Lst(1); + yield 1; + var psums: set of integer := [2]; + var newsums: set of integer := []; + foreach var trial in 2.Step do + begin + foreach var n in (mc + [trial]) do + begin + var sum := n + trial; + if sum in psums then goto 1; + newsums.add(sum) + end; + psums += newsums; + mc.add(trial); + yield trial; + 1: newsums := []; + end; +end; + +begin + println('The first 30 terms of the Mian-Chowla sequence are:'); + mian_chowla.Take(30).Println; + println; + println('Terms 91 to 100 of the Mian-Chowla sequence are:'); + mian_chowla.Skip(90).Take(10).Println; +end. diff --git a/Task/Middle-three-digits/PascalABC.NET/middle-three-digits.pas b/Task/Middle-three-digits/PascalABC.NET/middle-three-digits.pas new file mode 100644 index 0000000000..4763087818 --- /dev/null +++ b/Task/Middle-three-digits/PascalABC.NET/middle-three-digits.pas @@ -0,0 +1,28 @@ +type + ErrOdd = class (Exception) end; + ErrLen = class (Exception) end; + +function middle_three_digits(i: integer): string; +begin + var s := abs(i).ToString; + if s.Length < 3 then raise new ErrLen; + if s.Length mod 2 = 0 then raise new ErrOdd; + var mid := s.Length div 2; + result := s[mid:mid + 3]; +end; + +begin + var passing := |123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345|; + var failing := |1, 2, -1, -10, 2002, -2002, 0|; + + foreach var x in passing + failing do + try + var answer := middle_three_digits(x); + writeln(x:10, ' -> ', answer); + except + on ErrOdd do + writeln(x:10, ' -> must have an odd number of digits'); + on ErrLen do + writeln(x:10, ' -> must have 3 digits or more'); + end; +end. diff --git a/Task/Miller-Rabin-primality-test/M2000-Interpreter/miller-rabin-primality-test.m2000 b/Task/Miller-Rabin-primality-test/M2000-Interpreter/miller-rabin-primality-test.m2000 new file mode 100644 index 0000000000..8e7350d03b --- /dev/null +++ b/Task/Miller-Rabin-primality-test/M2000-Interpreter/miller-rabin-primality-test.m2000 @@ -0,0 +1,59 @@ +function isProbablyPrime(n as *BigInteger, k as long) { + boolean T=true, F=false + =F + Zero=BigInteger("0") + One=BigInteger("1") + Two=BigInteger("2") + Method n, "compare", Two as c1 + Method n, "modulus", Two as m2 + method m2,"compare", zero as C2 + if c1=0 or c2=0 then exit + with n, "toString" as ns$ + s=0 + Method n, "subtract", one as nn + d=nn + + with d, "tostring" as dstr$ + do + method d,"modulus", two as m2 + method m2,"compare", zero as C + if c else exit + s++ + method d, "divide", two as d + Always + z=len(ns$) + a=one + with a, "toString" as astr$ + x=a + =T + for i=1 to k { + do + zs="" + for j=1 to len(ns$) + zs+=chr$(47+random(1,10)) + next + a=bigInteger(zs) + method nn,"compare", a as C + method a,"compare", one as c1 + until c=1 and c1>-1 + method a, "modpow", d, n as x + method x,"compare", one as c1 + if c1 else continue + method x,"compare", nn as c1 + if c1 else continue + for r=1 to s { + method x, "modpow", two, n as x + method x,"compare", one as c1 + if c1 else =F : break + method x,"compare", nn as c1 + if c1 else exit + } + if c1 then =F: break + } +} +profiler +Print isProbablyPrime(BigInteger("5400349"), 5)=True +print timecount +profiler +a=BigInteger("5400349"): Method a, "isProbablyPrime", 5 as ret:Print ret +print timecount diff --git a/Task/Miller-Rabin-primality-test/PascalABC.NET/miller-rabin-primality-test.pas b/Task/Miller-Rabin-primality-test/PascalABC.NET/miller-rabin-primality-test.pas new file mode 100644 index 0000000000..5f8a56581b --- /dev/null +++ b/Task/Miller-Rabin-primality-test/PascalABC.NET/miller-rabin-primality-test.pas @@ -0,0 +1,57 @@ +uses System.Security.Cryptography; + +function IsProbablePrime(source: biginteger; certainty: integer): boolean; +begin + if (source = 2) or (source = 3) then + begin result := true; exit end; + + if (source < 2) or (source mod 2 = 0) then + begin result := false; exit end; + + var d := source - 1; + var s := 0; + + while d mod 2 = 0 do + begin + d := d div 2; + s += 1; + end; + + var rng := RandomNumberGenerator.Create(); + var bytes := new byte[source.ToByteArray.LongLength]; + var a: biginteger; + loop certainty do + begin + repeat + rng.GetBytes(bytes); + a := new BigInteger(bytes); + until (a >= 2) and (a < source - 2); + + var x := BigInteger.ModPow(a, d, source); + if (x = 1) or (x = source - 1) then continue; + + for var r := 1 to s - 1 do + begin + x := BigInteger.ModPow(x, 2, source); + if x = 1 then + begin result := false; exit end; + if x = source - 1 then break; + end; + + if x <> source - 1 then + begin result := false; exit end; + end; + + result := true; +end; + +begin + var data := |'4547337172376300111955330758342147474062293202868155909489', + '4547337172376300111955330758342147474062293202868155909393'|; + + foreach var candidate in data do + isprobableprime(candidate.tobiginteger, 10).Println; + + foreach var x in (900..1000) do + if isprobableprime(x, 10) then print(x); +end. diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-1.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-1.rexx deleted file mode 100644 index 0c977f54e7..0000000000 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-1.rexx +++ /dev/null @@ -1,48 +0,0 @@ -/*REXX program puts the Miller─Rabin primality test through its paces. */ -parse arg limit times seed . /*obtain optional arguments from the CL*/ -if limit=='' | limit=="," then limit= 1000 /*Not specified? Then use the default.*/ -if times=='' | times=="," then times= 10 /* " " " " " " */ -if datatype(seed, 'W') then call random ,,seed /*If seed specified, use it for RANDOM.*/ -numeric digits max(200, 2*limit) /*we're dealing with some ginormous #s.*/ -tell= times<0 /*display primes only if times is neg.*/ -times= abs(times); w= length(times) /*use absolute value of TIMES; get len.*/ -call genP limit /*suspenders now, use a belt later ··· */ -@MR= 'Miller─Rabin primality test' /*define a character literal for SAY. */ -say "There are" # 'primes ≤' limit /*might as well display some stuff. */ -say /* [↓] (skipping unity); show sep line*/ - do a=2 to times; say copies('─', 89) /*(skipping unity) do range of TIMEs.*/ - p= 0 /*the counter of primes for this pass. */ - do z=1 for limit /*now, let's get busy and crank primes.*/ - if \M_Rt(z, a) then iterate /*Not prime? Then try another number.*/ - p= p + 1 /*well, we found another one, by gum! */ - if tell then say z 'is prime according to' @MR "with K="a - if !.z then iterate - say '[K='a"] " z "isn't prime !" /*oopsy─doopsy and/or whoopsy─daisy !*/ - end /*z*/ - say ' for 1──►'limit", K="right(a,w)',' @MR "found" p 'primes {out of' #"}." - end /*a*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: parse arg high; @.=0; @.1=2; @.2=3; !.=@.; !.2=1; !.3=1; #=2 - do j=@.#+2 by 2 to high /*just examine odd integers from here. */ - do k=2 while k*k<=j; if j//@.k==0 then iterate j; end /*k*/ - #= # + 1; @.#= j; !.j= 1 /*bump prime counter; add prime to the */ - end /*j*/; return /*@. array; define a prime in !. array.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -M_Rt: procedure; parse arg n,k; d= n-1; nL=d /*Miller─Rabin: A.K.A. Rabin─Miller.*/ - if n==2 then return 1 /*special case of (the) even prime. */ - if n<2 | n//2==0 then return 0 /*check for too low, or an even number.*/ - - do s=-1 while d//2==0; d= d % 2 /*keep halving until a zero remainder.*/ - end /*while*/ - - do k; ?= random(2, nL) /* [↓] perform the DO loop K times.*/ - x= ?**d // n /*X can get real gihugeic really fast.*/ - if x==1 | x==nL then iterate /*First or penultimate? Try another pow*/ - do s; x= x**2 // n /*compute new X ≡ X² modulus N. */ - if x==1 then return 0 /*if unity, it's definitely not prime.*/ - if x==nL then leave /*if N-1, then it could be prime. */ - end /*r*/ /* [↑] // is REXX's division remainder*/ - if x\==nL then return 0 /*nope, it ain't prime nohows, noway. */ - end /*k*/ /*maybe it's prime, maybe it ain't ··· */ - return 1 /*coulda/woulda/shoulda be prime; yup.*/ diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx deleted file mode 100644 index 6d47c35bbb..0000000000 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test-2.rexx +++ /dev/null @@ -1,90 +0,0 @@ -include Settings - -say version; say 'Miller-Rabin primality test'; say -numeric digits 1000 -say '25 numbers of the form 2^n-1, mostly Mersenne primes' -say 'Up to about 25 digits deterministic, above probabilistic' -say -mm = '2 3 5 7 11 13 17 19 23 31 61 89 97 107 113 127 131 521 ', -|| '607 1279 2203 2281 2293 3217 3221' -do nn = 1 to 25 - a = Word(mm,nn); b = 2**a-1; l = Length(b) - call Time('r'); p = IsPrime(b); e = Time('e') - if l > 20 then - b = Left(b,10)'...'Right(b,10) - select - when p = 0 then - p = 'not' - when l < 26 then - p = 'for sure' - otherwise - p = 'probable' - end - say '2^'a'-1' '=' b '('l' digits) is' p 'prime' '('Format(e,,3) 'seconds)' -end -return - -IsPrime: -/* Is a number prime? */ -procedure expose glob. -arg x -/* Low primes also used as deterministic witnesses */ -w1 = ' 2 3 5 7 11 13 17 19 23 29 31 37 41 ' -/* Fast values */ -w = x -if Pos(' 'w' ',w1) > 0 then - return 1 -if x//2 = 0 then - return 0 -if x//3 = 0 then - return 0 -if Right(x,1) = 5 then - return 0 -/* Miller-Rabin primality test */ -numeric digits 2*Length(x) -d = x-1; e = d -/* Reduce n-1 by factors of 2 */ -do s = -1 while d//2 = 0 - d = d%2 -end -/* Thresholds deterministic witnesses */ -w2 = '2047 1373653 25326001 3215031751 2152302898747 3474749660383 341550071728321 ', -|| '0 3825123056546413051 0 0 318665857834031151167461 3317044064679887385961981 ' -w = Words(w2) -/* Up to 13 deterministic trials */ -if x < Word(w2,w) then do - do k = 1 to w - if x < Word(w2,k) then - leave - end -end -/* or 3 probabilistic trials */ -else do - w1 = ' ' - do k = 1 to 3 - r = Rand(2,e)/1; w1 = w1||r||' ' - end - k = k-1 -end -/* Algorithm using generated witnesses */ -do k = 1 to k - a = Word(w1,k); y = Powermod(a,d,x) - if y = 1 then - iterate - if y = e then - iterate - do s - y = (y*y)//x - if y = 1 then - return 0 - if y = e then - leave - end - if y <> e then - return 0 -end -return 1 - -include Functions -include Numbers -include Abend diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx new file mode 100644 index 0000000000..30799c4f3d --- /dev/null +++ b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx @@ -0,0 +1,29 @@ +include Settings + +say version; say 'Miller-Rabin primality test'; say +numeric digits 1000 +say '25 numbers of the form 2^n-1, mostly Mersenne primes' +say 'Up to about 25 digits deterministic, above probabilistic' +say +mm = '2 3 5 7 11 13 17 19 23 31 61 89 97 107 113 127 131 521 ', +|| '607 1279 2203 2281 2293 3217 3221' +do nn = 1 to 25 + a = Word(mm,nn); b = 2**a-1; l = Length(b) + call Time('r'); p = Prime(b); e = Time('e') + if l > 20 then + b = Left(b,10)'...'Right(b,10) + select + when p = 0 then + p = 'not' + when l < 26 then + p = 'for sure' + otherwise + p = 'probable' + end + say '2^'a'-1' '=' b '('l' digits) is' p 'prime' '('Format(e,,3) 'seconds)' +end +return + +include Functions +include Numbers +include Abend diff --git a/Task/Minesweeper-game/FutureBasic/minesweeper-game.basic b/Task/Minesweeper-game/FutureBasic/minesweeper-game.basic new file mode 100644 index 0000000000..9c9c3bce2f --- /dev/null +++ b/Task/Minesweeper-game/FutureBasic/minesweeper-game.basic @@ -0,0 +1,148 @@ +_sizeX = 6 // SET BOARD WIDTH HERE +_sizey = 4 // SET BOARD HEIGHT HERE +_minePct = 20 // SET MINES PERCENT HERE + +begin enum + _mine = 0x10 + _flag = 0x20 + //miss < _safe + _safe = 0x30 + _show = 0x40 + //nums < 0x50 + //mine = 0x50 + //miss < 0x60 + _boom = 0x80 + + _mines = _sizeX * _sizeY * _minePct / 100 + _quit = 1001 // NSAlertSecondButtonReturn + _cmdOpt = 1572864 // NSEventModifierFlagOption+NSEventModifierFlagCommand +end enum + +begin globals + uint8 flags, count, miss, board( _sizeX+1, _sizeY+1 ) + bool start = YES +end globals + +void local fn show + int x, y, cell + cls + text @"Helvetica",15,_zGray + print @"\t Click to Clear\r \U00002318-Click to flag" + text @"Menlo bold",14,,_zClear + for y = 20 to _sizeY * 20 step 20 : for x = 20 to _sizeX * 20 step 20 + cell = board( x/20, y/20 ) + rect fill (x, y+20, 19, 19),(cell & _show) ? _zGray : _zLightGray + select cell + case < _flag //ignore + case <= _safe : print %(x+6, y+17)@"\U0001F6A9" // 🚩︎ + case < _show+_mine : text,,(cell & 15) + print %(x+5, y+18) mid(@" 12345678", (cell & 15), 1)// num + case _show+_mine :rect fill (x,y+20,19,19),_zRed + print %(x-1, y+19)@"\U0001F4A3" // 💣 + case < _show+_safe : print %(x+1, y+19)@"\U0000274C" // ❌ + case _show+_boom : text ,24 + print %(x-5, y+10)@"\U0001F4A5" : text ,14 // 💥 + //case else : stop hex$(cell) + end select + next : next + text ,15,_zBlack,_zRed + printf %(20,_sizeY * 20 + 50)@" MINES: %d ",_mines - flags + text ,,,fn ColorClear +end fn + +void local fn newBoard // make edge cells inaccessible + fn blockfill(@board(0, 0), (_sizeX + 2) * (_sizey + 2), _show) + for int y = 1 to _sizeY : for int x = 1 to _sizeX + board(x, y) = 0 // set all clickable cells to 0 + next : next + count = _sizeX * _sizeY + flags = 0 : miss = 0 + fn show +end fn + +void local fn endGame + int x, y + for y = 1 to _sizeY : for x = 1 to _sizeX + select board(x, y) & _safe + case _safe : + case _mine : board(x, y) |= (miss) ? _show : _flag + case else : board(x, y) |= _show + end select + next : next + if !miss then flags = _mines + + fn show + + if miss + x = alert 1,,@"Yikes! Bad move!\nNew assignment, or R&R?",,@"New (again);R&R (quit)" + else + x = alert 1,,@"WHEW! SAFE!\nNew assignment, or R&R?",,@"New (again);R&R (quit)" + end if + if x == _quit then end + fn newBoard + start = YES +end fn + +void local fn click( x as int, y as int, cmd as bool ) + if (x < 1 || y < 1 || x > _sizeX || y > _sizeY) then exit fn + int c, r + if start + int m = _mines, xx, yy + start = NO + fn newBoard + while m + c = rnd(_sizeX) : r = rnd(_sizeY) + // REM NEXT LINE TO ALLOW MINE OR NUMBER UNDER FIRST CLICK + if abs( x-c ) < 2 & abs( y-r ) < 2 then continue //start on empty cell + if board(c,r) == _mine then continue + board(c,r) = _mine : m-- // place mine + for xx = c-1 to c+1 : for yy = r-1 to r+1 // mark proximity + if board(xx, yy) <> _mine then board(xx, yy)++ + next : next + wend + end if + + ^uint8 cell = @board(x, y) + select + case *cell & _show // ignore + case cmd + if *cell & _flag + flags-- : if *cell < _safe then miss-- + else + flags++ : if *cell < _mine then miss++ + end if + *cell ^^= _flag // toggle flag + case *cell & _mine : *cell = _boom // hit mine + miss ++ : fn endGame + case *cell < 9 : *cell |= _show : count-- // open cell + if *cell == _show // if no adjacent flags, + for c = x-1 to x+1 : for r = y-1 to y+1 // click adjacent cells + if board(c, r) < 9 then fn click(c, r, NO) + next : next + end if + end select +end fn + +void local fn MINESWEEPER + subclass window 1, @"Minesweeper", (0,0,_sizeX * 20 + 40, _sizeY * 20 + 80) + WindowMakeFirstResponder( 1, _WindowContentViewTag) + fn newBoard +end fn + +void local fn doDialog( evt as long ) + select evt + case _windowMouseUp + CGPoint pt = fn EventLocationInView( _WindowContentViewTag ) + bool cmd = sgn( fn EventModifierFlags & _cmdOpt ) + fn click( pt.x / 20, _sizeY -(pt.y / 20 ) +3, cmd ) + fn show //: NSLog(@"%d, %d, %d",flags, _mines, count ) + if flags == _mines || count == _mines then fn endgame + case _windowWillClose : end + end select + +end fn + +on dialog fn doDialog +fn MINESWEEPER + +handleevents diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PascalABC.NET/minimum-multiple-of-m-where-digital-sum-equals-m.pas b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PascalABC.NET/minimum-multiple-of-m-where-digital-sum-equals-m.pas new file mode 100644 index 0000000000..d60b5241bb --- /dev/null +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PascalABC.NET/minimum-multiple-of-m-where-digital-sum-equals-m.pas @@ -0,0 +1,16 @@ +function digitsum(n: integer) := n.ToString.Select(c -> c.ToDigit).Sum; + +function a131382(): sequence of integer; +begin + foreach var n in 1.step do + begin + var m := 1; + while digitsum(m * n) <> n do m += 1; + yield m; + end; +end; + +begin + foreach var n in a131382.take(70) index i do + write(n:9, if i mod 10 = 9 then #10 else ''); +end. diff --git a/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy b/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy new file mode 100644 index 0000000000..1e16044bef --- /dev/null +++ b/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy @@ -0,0 +1,32 @@ +func$ rep c$ n . + for i to n : r$ &= c$ + return r$ +. +func modifier x . + if x < 0.5 : return 2 * (0.5 - x) + return 2 * (x - 0.5) +. +func rand . + repeat + r1 = randomf + r2 = randomf + until r2 < modifier r1 + . + return r1 +. +n = 100000 +nbins = 20 +histsz = 200 +binsz = 1 / nbins +len bins[] nbins +arrbase bins[] 0 +# +for i to n + rn = rand + bn = floor (rn / binsz) + bins[bn] += 1 +. +numfmt 0 4 +for i range0 nbins + print bins[i] & " " & rep "*" (bins[i] / histsz) +. diff --git a/Task/Modified-random-distribution/M2000-Interpreter/modified-random-distribution.m2000 b/Task/Modified-random-distribution/M2000-Interpreter/modified-random-distribution.m2000 new file mode 100644 index 0000000000..1867306e6a --- /dev/null +++ b/Task/Modified-random-distribution/M2000-Interpreter/modified-random-distribution.m2000 @@ -0,0 +1,34 @@ +module Modified_random_distribution (f, m, bins){ + form 60, 32 + Cls 1, 0 + Report "Modified Random Distribution" + Cls 0, 1 + Cursor 0, 5 + T$="Range Istogram" + Print #f, T$ + Print T$ + double a[bins] + def modifier(x) = if(x < 0.5-> 1-2*x, 2*x -1) + for i=1 to m + while True: + random1 = rnd + random2 = rnd + if random2 < modifier(random1) then + answer = int(random1*bins) + a[answer]++ + exit + end if + end while + next + b=100 / bins + + for i=0 to bins-1 + L$=format$("{0:1:-4} - {1:1:-4} {2} {3}% ",i*b,(i+1)*b-.1, string$("*",a[i]/(m/bins)*20), round(a[i]/m*100,2)) + Print #f, L$ + Print L$ + next + } + // Ansi file / use for wide output for UTF16LE +Open "ModRandomDistr.txt" for output as #f +Modified_random_distribution f, 10000, 21 +close #f diff --git a/Task/Modified-random-distribution/PascalABC.NET/modified-random-distribution.pas b/Task/Modified-random-distribution/PascalABC.NET/modified-random-distribution.pas new file mode 100644 index 0000000000..b6242e5a36 --- /dev/null +++ b/Task/Modified-random-distribution/PascalABC.NET/modified-random-distribution.pas @@ -0,0 +1,21 @@ +function modifier(x: real) := if x < 0.5 then 2 * (0.5 - x) else 2 * (x - 0.5); + +function modrand(modifier: real-> real): sequence of real; +begin + repeat + var r := Random; + if Random < modifier(r) then yield r; + until false; +end; + +begin + var data := modrand(modifier).Take(100_000); + var bins := data.Select(x -> (20 * x).Floor) + .Sorted + .GroupBy(n -> n) + .Select(g -> g.Count); + + writeln('Bin Counts Histogram'); + foreach var counts in bins index i do + writeln(i / 20:2:2, counts:6, ': ', '■' * (counts div 125)); +end. diff --git a/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation.m2000 b/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation.m2000 new file mode 100644 index 0000000000..4ded66199d --- /dev/null +++ b/Task/Modular-exponentiation/M2000-Interpreter/modular-exponentiation.m2000 @@ -0,0 +1,15 @@ +function ToString(x as *BigInteger) { + with x,"toString" as ret + =ret +} +Function PowerTen(x as integer) { + a=Biginteger("10") + method a, "intPower", biginteger(str$(x,"")) as a + =a +} +a=bigInteger("2988348162058574136915891421498819466320163312926952423791023078876139") +b=biginteger("2351399303373464486466122544523690094744975233415544072992656881240319") +profiler + method a, "modpow", b, PowerTen(40) as result +print timecount +Print ToString(result) diff --git a/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-1.pas b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-1.pas new file mode 100644 index 0000000000..2f85905dae --- /dev/null +++ b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-1.pas @@ -0,0 +1,5 @@ +## +var a := '2988348162058574136915891421498819466320163312926952423791023078876139'.ToBigInteger; +var b := '2351399303373464486466122544523690094744975233415544072992656881240319'.ToBigInteger; +var m := Power(10bi, 40); +Writeln(BigInteger.ModPow(a, b, m)); diff --git a/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation.pas b/Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-2.pas similarity index 100% rename from Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation.pas rename to Task/Modular-exponentiation/PascalABC.NET/modular-exponentiation-2.pas diff --git a/Task/Modular-inverse/PascalABC.NET/modular-inverse.pas b/Task/Modular-inverse/PascalABC.NET/modular-inverse.pas new file mode 100644 index 0000000000..4f66c5bd88 --- /dev/null +++ b/Task/Modular-inverse/PascalABC.NET/modular-inverse.pas @@ -0,0 +1,18 @@ +function ModInverse(a, m: integer): integer; +begin + result := 1; + if m = 1 then exit; + var m0 := m; + var (x, y) := (1, 0); + while a > 1 do + begin + var q := a div m; + (a, m) := (m, a mod m); + (x, y) := (y, x - q * y); + end; + result := if x < 0 then x + m0 else x; +end; + +begin + ModInverse(42, 2017).Println; +end. diff --git a/Task/Monty-Hall-problem/PascalABC.NET/monty-hall-problem.pas b/Task/Monty-Hall-problem/PascalABC.NET/monty-hall-problem.pas new file mode 100644 index 0000000000..5f882e336d --- /dev/null +++ b/Task/Monty-Hall-problem/PascalABC.NET/monty-hall-problem.pas @@ -0,0 +1,37 @@ +function games(n: integer): (integer, integer); +begin + var stay := 0; + var switch := 0; + loop n do + begin + var lst := lst(1, 0, 0); // one car and two goats + lst.shuffle; // shuffles the list randomly + var ran := Random(3); // gets a random number for the random guess + var user := lst[ran]; // storing the random guess + lst.RemoveAt(ran); // deleting the random guess + + var huh := 0; + foreach var i in lst do + begin // getting a value 0 and deleting it + if i = 0 then + begin + lst.RemoveAt(huh); // deletes a goat when it finds it + break + end; + huh += 1; + end; + + if user = 1 then // if the original choice is 1 then stay adds 1 + stay += 1; + + if lst[0] = 1 then // if the switched value is 1 then switch adds 1 + switch += 1; + end; + result := (stay, switch); +end; + +begin + var (stay, switch) := games(1000); + println('Stay = ', stay); + println('Switch = ', switch); +end. diff --git a/Task/Morse-code/M2000-Interpreter/morse-code.m2000 b/Task/Morse-code/M2000-Interpreter/morse-code.m2000 new file mode 100644 index 0000000000..81a8c04401 --- /dev/null +++ b/Task/Morse-code/M2000-Interpreter/morse-code.m2000 @@ -0,0 +1,58 @@ +Module Morse_code { + declare Json JsonObject + json$={{ + "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", + "(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--", + "-": "-....-", ".": ".-.-.-", "/": "-..-.", + "0": "-----", "1": ".----", "2": "..---", "3": "...--", + "4": "....-", "5": ".....", "6": "-....", "7": "--...", + "8": "---..", "9": "----.", + ":": "---...", ";": "-.-.-.", "=": "-...-", "?": "..--..", + "@": ".--.-.", + "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", + "E": ".", "F": "..-.", "G": "--.", "H": "....", + "I": "..", "J": ".---", "K": "-.-", "L": ".-..", + "M": "--", "N": "-.", "O": "---", "P": ".--.", + "Q": "--.-", "R": ".-.", "S": "...", "T": "-", + "U": "..-", "V": "...-", "W": ".--", "X": "-..-", + "Y": "-.--", "Z": "--..", + "[": "-.--.", "]": "-.--.-", "_": "..--.-", + }} + e = 50 ' Element time in ms. one dit is on for e then off for e + f = 1280 ' Tone freq. in hertz + chargap = 1*e ' Time between characters of a word + wordgap = 7*e ' Time between words + + method json, "parser", json$ as json + with json, "itempath" as json.path$() + + + Input "Send Message:";a$ + a$=trim$(a$) + if len(a$)=0 then exit + a$=ucase$(a$) + + for i=1 to len(a$) + L$=mid$(a$, i, 1) + Print L$; + Send(json.path$(L$)) + next + + sub Send(a$) + if len(a$)=0 then wait wordgap : exit sub + local i + for i=1 to len(a$) + select case mid$(a$, i, 1) + case "." + tone e, f + case "-" + tone 3*e, f + case else + tone 3*e, f mod 2 + end select + wait chargap + next + end sub +} +Keyboard "This is Morse_code", 13 +Morse_code diff --git a/Task/Morse-code/PascalABC.NET/morse-code.pas b/Task/Morse-code/PascalABC.NET/morse-code.pas new file mode 100644 index 0000000000..f1718d8cd5 --- /dev/null +++ b/Task/Morse-code/PascalABC.NET/morse-code.pas @@ -0,0 +1,27 @@ +const + Morse = dict(('A', '.-'), ('B', '-...'), ('C', '-.-.'), ('D', '-..'), ('E', string('.')), + ('F', '..-.'), ('G', '--.'), ('H', '....'), ('I', '..'), ('J', '.---'), + ('K', '-.-'), ('L', '.-..'), ('M', '--'), ('N', '-.'), ('O', '---'), + ('P', '.--.'), ('Q', '--.-'), ('R', '.-.'), ('S', '...'), ('T', string('-')), + ('U', '..-'), ('V', '...-'), ('W', '.--'), ('X', '-..-'), ('Y', '-.--'), + ('Z', '--..'), ('0', '-----'), ('1', '.----'), ('2', '..---'), ('3', '...--'), + ('4', '....-'), ('5', '.....'), ('6', '-....'), ('7', '--...'), ('8', '---..'), + ('9', '----.'), ('.', '.-.-.-'), (',', '--..--'), ('?', '..--..'), ('\', '.----.'), + ('!', '-.-.--'), ('/', '-..-.'), ('(', '-.--.'), (')', '-.--.-'), ('&', '.-...'), + (':', '---...'), (';', '-.-.-.'), ('=', '-...-'), ('+', '.-.-.'), ('-', '-....-'), + ('_', '..--.-'), ('''', '.-..-.'), ('$', '...-..-'), ('@', '.--.-.')); + +procedure SayMorse(s: string); +begin + foreach var c in s do + begin + foreach var c2 in Morse.get(c.ToUpper, '') do + if c2 = '.' then console.Beep(1000, 250) + else console.Beep(1000, 750); + sleep(1000); + end; +end; + +begin + SayMorse('SOS'); +end. diff --git a/Task/Motzkin-numbers/EMal/motzkin-numbers.emal b/Task/Motzkin-numbers/EMal/motzkin-numbers.emal index 93f3d08a50..416df0338f 100644 --- a/Task/Motzkin-numbers/EMal/motzkin-numbers.emal +++ b/Task/Motzkin-numbers/EMal/motzkin-numbers.emal @@ -1,6 +1,6 @@ fun isPrime = logic by int n if n <= 1 do return false end - for int i = 2; i <= int!sqrt(n); ++i + for int i = 2; i <= int!√n; ++i if n % i == 0 do return false end end return true diff --git a/Task/Motzkin-numbers/PascalABC.NET/motzkin-numbers.pas b/Task/Motzkin-numbers/PascalABC.NET/motzkin-numbers.pas new file mode 100644 index 0000000000..3d630274f4 --- /dev/null +++ b/Task/Motzkin-numbers/PascalABC.NET/motzkin-numbers.pas @@ -0,0 +1,31 @@ +function IsPrime(n: int64): boolean; +begin + if (n = 2) or (n = 3) then Result := true + else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result := false + else + begin + var i := 5; + Result := False; + while i <= trunc(sqrt(n)) do + begin + if ((n mod i) = 0) or ((n mod (i + 2)) = 0) then exit; + i += 6; + end; + Result := True; + end; +end; + +function mot(): sequence of biginteger; +begin + var (a, b, n) := (0bi, 1bi, 1bi); + repeat + yield b div n; + n += 1; + (a, b) := (b, (3 * (n - 1) * n * a + (2 * n - 1) * n * b) div ((n + 1) * (n - 1))) + until false; +end; + +begin + foreach var val in mot.Take(42) index i do + writeln(i:2, val:20, if isprime(int64(val)) then ' is prime' else ''); +end. diff --git a/Task/Mouse-position/Nim/mouse-position.nim b/Task/Mouse-position/Nim/mouse-position.nim index 1957662497..4e78571df3 100644 --- a/Task/Mouse-position/Nim/mouse-position.nim +++ b/Task/Mouse-position/Nim/mouse-position.nim @@ -1,27 +1,25 @@ -import gintro/[glib, gobject, gtk, gio] -import gintro/gdk except Window +import gtk2, glib2 +import gdk2 except PWindow -#--------------------------------------------------------------------------------------------------- -proc onButtonPress(window: ApplicationWindow; event: Event; data: pointer): bool = - echo event.getCoords() - result = true +proc onButtonPress(window: pointer; event: PEventButton; data: pointer): gboolean {.cdecl.} = + echo event.x, " ", event.y + result = false -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Quit the application. + mainQuit() - let window = app.newApplicationWindow() - window.setTitle("Mouse position") - window.setSizeRequest(640, 480) - discard window.connect("button-press-event", onButtonPress, pointer(nil)) +nimInit() - window.showAll() +let window = windowNew(WINDOW_TOPLEVEL) +window.setTitle("Mouse position") +window.setSizeRequest(640, 480) +window.setEvents(BUTTON_PRESS_MASK) +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) +discard window.signalConnect("button-press-event", SIGNAL_FUNC(onButtonPress), nil) +window.showAll() -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.MousePosition") -discard app.connect("activate", activate) -discard app.run() +main() diff --git a/Task/Move-to-front-algorithm/PascalABC.NET/move-to-front-algorithm.pas b/Task/Move-to-front-algorithm/PascalABC.NET/move-to-front-algorithm.pas new file mode 100644 index 0000000000..bdc7f3445e --- /dev/null +++ b/Task/Move-to-front-algorithm/PascalABC.NET/move-to-front-algorithm.pas @@ -0,0 +1,37 @@ +const + SymbolTable = Lst('a'..'z'); + +function encode(s: string): list; +begin + result := new List; + var symtable := SymbolTable; + foreach var c in s do + begin + var idx := symtable.IndexOf(c); + result.add(idx); + symtable.RemoveAt(idx); + symtable.Insert(0, c); + end; +end; + +function decode(s: list): string; +begin + var symtable := SymbolTable; + foreach var idx in s do + begin + var c := symtable[idx]; + result += c; + symtable.RemoveAt(idx); + symtable.Insert(0, c); + end; +end; + +begin + foreach var word in ['broood', 'babanaaa', 'hiphophiphop'] do + begin + var encoded := encode(word); + var decoded := decode(encoded); + var status := if decoded = word then 'correctly' else 'incorrectly'; + println(word, 'encodes to', encoded, 'which', status, 'decodes to', decoded); + end; +end. diff --git a/Task/Multi-base-primes/Python/multi-base-primes.py b/Task/Multi-base-primes/Python/multi-base-primes.py new file mode 100644 index 0000000000..37fcfcfa1c --- /dev/null +++ b/Task/Multi-base-primes/Python/multi-base-primes.py @@ -0,0 +1,78 @@ +import timeit +from collections import deque + +from sympy import isprime + + +def digits(num: int): + digits = deque() + + while num > 0: + digits.appendleft(num % 10) + num //= 10 + + return digits + + +def all_digits_are_less(dig: list[int], b: int): + for d in dig: + if d >= b: + return False + + return True + + +def eval_poly(coeffs: list[int], x: int): + y = 0 + + for pv in coeffs: + y = y * x + pv + + return y + + +def max_prime_bases(ndig: int, maxbase: int): + maxprimebases = [[]] + nwithbases = [0] + maxprime = 10 ** (ndig) - 1 + + for p in range(int((maxprime + 1) / 10), maxprime + 1): + dig = digits(p) + bases = [ + b + for b in range(2, maxbase + 1) + if isprime(eval_poly(dig, b)) and all_digits_are_less(dig, b) + ] + + if len(bases) > len(maxprimebases[0]): + maxprimebases = [bases] + nwithbases = [p] + + elif len(bases) == len(maxprimebases[0]): + maxprimebases.append(bases) + nwithbases.append(p) + + alen, vlen = len(maxprimebases[0]), len(maxprimebases) + + print( + "\nThe maximum number of prime valued bases for base 10 numeric strings of length", + ndig, + "is", + f"{alen}.", + "The base 10 value list of", + "these" if vlen > 1 else "this", + "is: ", + ) + + for i in range(len(maxprimebases)): + print(nwithbases[i], "=>", maxprimebases[i]) + + +def main(): + for n in range(1, 7): + max_prime_bases(n, 36) + + +if __name__ == "__main__": + execution_time = timeit.timeit(main, number=1) + print(f"Execution time: {execution_time:.6f} seconds") diff --git a/Task/Multi-dimensional-array/C/multi-dimensional-array-1.c b/Task/Multi-dimensional-array/C/multi-dimensional-array-1.c deleted file mode 100644 index 7fcedea181..0000000000 --- a/Task/Multi-dimensional-array/C/multi-dimensional-array-1.c +++ /dev/null @@ -1,37 +0,0 @@ -/*Single dimensional array of integers*/ -int a[10]; - -/*2-dimensional array, also called matrix of floating point numbers. -This matrix has 3 rows and 2 columns.*/ - -float b[3][2]; - -/*3-dimensional array ( Cube ? Cuboid ? Lattice ?) of characters*/ - -char c[4][5][6]; - -/*4-dimensional array (Hypercube ?) of doubles*/ - -double d[6][7][8][9]; - -/*Note that the right most number in the [] is required, all the others may be omitted. -Thus this is ok : */ - -int e[][3]; - -/*But this is not*/ - -float f[5][4][]; - -/*But why bother with all those numbers ? You can also write :*/ -int *g; - -/*And for a matrix*/ -float **h; - -/*or if you want to show off*/ -double **i[]; - -/*you get the idea*/ - -char **j[][5]; diff --git a/Task/Multi-dimensional-array/C/multi-dimensional-array-2.c b/Task/Multi-dimensional-array/C/multi-dimensional-array-2.c deleted file mode 100644 index f1ea68cb31..0000000000 --- a/Task/Multi-dimensional-array/C/multi-dimensional-array-2.c +++ /dev/null @@ -1,27 +0,0 @@ -#include - -int main() -{ - int hyperCube[5][4][3][2]; - - /*An element is set*/ - - hyperCube[4][3][2][1] = 1; - - /*IMPORTANT : C ( and hence C++ and Java and everyone of the family ) arrays are zero based. - The above element is thus actually the last element of the hypercube.*/ - - /*Now we print out that element*/ - - printf("\n%d",hyperCube[4][3][2][1]); - - /*But that's not the only way to get at that element*/ - printf("\n%d",*(*(*(*(hyperCube + 4) + 3) + 2) + 1)); - - /*Yes, I know, it's beautiful*/ - *(*(*(*(hyperCube+3)+2)+1)) = 3; - - printf("\n%d",hyperCube[3][2][1][0]); - - return 0; -} diff --git a/Task/Multi-dimensional-array/C/multi-dimensional-array-3.c b/Task/Multi-dimensional-array/C/multi-dimensional-array-3.c deleted file mode 100644 index 8f3043efee..0000000000 --- a/Task/Multi-dimensional-array/C/multi-dimensional-array-3.c +++ /dev/null @@ -1,66 +0,0 @@ -#include -#include - -/*The stdlib header file is required for the malloc and free functions*/ - -int main() -{ - /*Declaring a four fold integer pointer, also called - a pointer to a pointer to a pointer to an integer pointer*/ - - int**** hyperCube, i,j,k; - - /*We will need i,j,k for the memory allocation*/ - - /*First the five lines*/ - - hyperCube = (int****)malloc(5*sizeof(int***)); - - /*Now the four planes*/ - - for(i=0;i<5;i++){ - hyperCube[i] = (int***)malloc(4*sizeof(int**)); - - /*Now the 3 cubes*/ - - for(j=0;j<4;j++){ - hyperCube[i][j] = (int**)malloc(3*sizeof(int*)); - - /*Now the 2 hypercubes (?)*/ - - for(k=0;k<3;k++){ - hyperCube[i][j][k] = (int*)malloc(2*sizeof(int)); - } - } - } - - /*All that looping and function calls may seem futile now, - but imagine real applications when the dimensions of the dataset are - not known beforehand*/ - - /*Yes, I just copied the rest from the first program*/ - - hyperCube[4][3][2][1] = 1; - - /*IMPORTANT : C ( and hence C++ and Java and everyone of the family ) arrays are zero based. - The above element is thus actually the last element of the hypercube.*/ - - /*Now we print out that element*/ - - printf("\n%d",hyperCube[4][3][2][1]); - - /*But that's not the only way to get at that element*/ - printf("\n%d",*(*(*(*(hyperCube + 4) + 3) + 2) + 1)); - - /*Yes, I know, it's beautiful*/ - *(*(*(*(hyperCube+3)+2)+1)) = 3; - - printf("\n%d",hyperCube[3][2][1][0]); - - /*Always nice to clean up after you, yes memory is cheap, but C is 45+ years old, - and anyways, imagine you are dealing with terabytes of data, or more...*/ - - free(hyperCube); - - return 0; -} diff --git a/Task/Multi-dimensional-array/C/multi-dimensional-array.c b/Task/Multi-dimensional-array/C/multi-dimensional-array.c new file mode 100644 index 0000000000..3b8edae5f7 --- /dev/null +++ b/Task/Multi-dimensional-array/C/multi-dimensional-array.c @@ -0,0 +1,31 @@ +/* an array of ten ints */ +int a[10]; + +/* a 2D-array of floats with three rows and two columns */ +float b[3][2]; +/* + these would be ordered in memory as + b[0][0] b[0][1] b[1][0] b[1][1] b[2][0] b[2][1] + + for example: +*/ +b[0][0] = 1.0; +b[0][1] = 2.0; +b[1][0] = 3.0; +b[1][1] = 4.0; +b[2][0] = 5.0; +b[2][1] = 6.0; +/* +now these would be stored in memory as: + ++----+----+----+----+----+----+ +| 1.0| 2.0| 3.0| 4.0| 5.0| 6.0| ++----+----+----+----+----+----+ + +*/ + + +/* a 3D-array of chars */ +char c[4][5][6]; + +/* etc. */ diff --git a/Task/Multi-dimensional-array/M2000-Interpreter/multi-dimensional-array.m2000 b/Task/Multi-dimensional-array/M2000-Interpreter/multi-dimensional-array.m2000 new file mode 100644 index 0000000000..ba3688a140 --- /dev/null +++ b/Task/Multi-dimensional-array/M2000-Interpreter/multi-dimensional-array.m2000 @@ -0,0 +1,100 @@ +// supports multi-dimensional arrays +// support row-major and column major order - we can use both on different arrays. +// this is variant type +Dim A(0 to 4, 0 to 3, 1 to 2, -1 to 1) = 1 +A(0,0,1,-1)++ +Print A(0,0,1,-1)=2 +// Arrays are values also +// here we pass a tuple (one dimension array 9 based) +A(4,3,2,1)=(1,2,3,4,5) +Print A(4,3,2,1)(2)=3 +Dim Z(10) +Z(3)=A() +Print Z(3)(4,3,2,1)(2)=3 + +// We can define type: BigInteger, Complex, Decimal, Currency, Double, Single, Long Long, Long, Byte, Date, Boolean, Object +Dim B(0 to 4, 0 to 3, 1 to 2, -1 to 1) as byte = 255 +B(0,0,1,-1)-- +Print B(0,0,1,-1)=254 +// redim - by default is row-major +Dim B(0 to 5, 0 to 3, 1 to 2, -1 to 1) +Print B(0,0,1,-1)=254 +// OLE type are column major +Dim OLE B(0 to 4, 0 to 3, 1 to 2, -1 to 1) as byte = 255 +B(0,0,1,-1)-- +// redim the last dimension only +Dim B(0 to 4, 0 to 3, 1 to 2, -1 to 5) +Print B(0,0,1,-1)=254 +B(4,3,2,5)=253 +Print Dimension(B())=4, Dimension(B(),4,1)=5 +Print B()#pos(253)=279 ' Zero position (trait like one dimension) +// we can redim free, but the items change positions.. +k=len(B()) +' one dimension +DIM B(K) +Print B(279)=253, type$(B(279))="Byte" +// we can get the actual address +Print Varptr(B(279))-Varptr(B(278))=1 +// another type of arrays +// there is no dim, we set index and we get resize +Byte z[10]=255 +d=lambda->{ + object d[number] + = d +} +object P[2]=d(0) +p[2]=d(10) +p[1]=d(3) +P[2][1]=z // we get the pointer +P[2][2]=z[] // we get the copy +P[1][1]=z // we get the pointer +P[1][2]=z[] // we get the copy +p[2][2][2]-=10 +? p[2][2][2]=245 +? p[1][2][2]=255 +DEF TypeVal(x)=type$(x) +// these are the Seven arrays (two of them are z): +Print len(p[0])=1, type$(p, 0)="RefArray" +Print len(p[1])=4, type$(p, 1)="RefArray" +Print len(p[2])=11, type$(p, 2)="RefArray" +Print TypeVal(p[1][1])="RefArray" +Print p[1][1] is z +Print TypeVal(p[1][2])="RefArray" +Print len(p[1][2])=11, TypeVal(p[1][2][0])="Byte" +Print TypeVal(p[2][1])="RefArray" +Print p[2][1] is z +Print p[1][1] is p[2][1] +Print TypeVal(p[2][2])="RefArray" +Print not p[1][1] is p[2][2] +z[6]-=100 +Print p[1][1][6]=z[6], p[2][1][6]=z[6] +Print len(p[2][2])=11, TypeVal(p[2][2][0])="Byte" +byte k[0] +// shallow copy +k=p[] +Print k[2][1] is z +// copy +k[2][1]=k[2][] +// so now array at k[2][1] is a copy, different pointer from z +Print not k[2][1] is z + +// Sparse Matrix using a list (has a hash table) +g=list:= 1:=100, 10:=300, 500:=40 +if exist(g, 10) then print eval(g)=300 +Print g(1)=100, g(10)=300, g(500)=40 +Print valid(g(20)) = false +Print valid(g(10)) = true +Append g, 400:=1000 +// this is a quicksort +Sort ascending g as number +// Sparse Matrix using a Queue (a list taking same keys) +t=queue:=2,3,4,4,5,10:="A",10:="C",10:="B", 3 +// this is a stable sort +sort t as number +// Access same keys using the hash table +if exist(t, 10) then +many=exist(t, 10, 0) +for i=1 to many + if exist(t, 10, i) then print eval$(t), eval(t!) ' value and position +next +end if diff --git a/Task/Multifactorial/PascalABC.NET/multifactorial.pas b/Task/Multifactorial/PascalABC.NET/multifactorial.pas new file mode 100644 index 0000000000..7592c4e50a --- /dev/null +++ b/Task/Multifactorial/PascalABC.NET/multifactorial.pas @@ -0,0 +1,11 @@ +## +function mfac(n, m: integer) := range(n, 1, -m).aggregate(1, (p, x) -> p * x); + +function mfac2(n, m: integer): integer := if n <= (m + 1) then n else n * mfac2(n - m, m); + +foreach var m in (1..5) do +begin + write(#10, m, ': '); + foreach var n in (1..10) do + mfac2(n, m).Print; +end; diff --git a/Task/Multiple-regression/M2000-Interpreter/multiple-regression.m2000 b/Task/Multiple-regression/M2000-Interpreter/multiple-regression.m2000 new file mode 100644 index 0000000000..2f3759c549 --- /dev/null +++ b/Task/Multiple-regression/M2000-Interpreter/multiple-regression.m2000 @@ -0,0 +1,67 @@ +Module Task_Multiple_regression{ + Function Multiple_regression(X(), Y()){ + Form 14*5, 32 + Print $(0, 14) + integer M=2, Q=3, n=len(x())-1 + Dim s(0 to 2*M), t(0 to 2*M) + For k = 0 To 2*M + S(k) = 0 : T(k) = 0 + For i = 0 To N + S(k) += X(i) ^ k + If k <= M Then T(k) += Y(i) * X(i) ^ k + Next i + Next k + dim a(0 to M, 0 to Q) + For r = 0 To M + For c = 0 To M + A(r, c) = S(r+c) + Next c + A(r, c) = T(r) + Next r + Print "Linear system coefficents:" + Print $("0.0") + For i = 0 To M + For j = 0 To M+1 + Print A(i,j), + Next j + Print + Next i + Print $(0) + For j = 0 To M + For i = j To M + If A(i,j) <> 0 Then Exit For + Next i + If i = M+1 Then + Print "SINGULAR MATRIX" + break + End If + For k = 0 To M+1 + Swap A(j,k), A(i,k) + Next k + z = 1 / A(j,j) + For k = 0 To M+1 + A(j,k) = z * A(j,k) + Next k + For i = 0 To M + If i <> j Then + z = -A(i,j) + For k = 0 To M+1 + A(i,k) += z * A(j,k) + Next k + End If + Next i + Next j + Flush + For i = 0 To M + data A(i,M+1) + Next i + =array([]) + } + Dim Solution() + DataX=(1.47,1.50,1.52,1.55,1.57, 1.60,1.63,1.65,1.68, 1.70,1.73,1.75,1.78,1.80,1.83) + DataY=(52.21,53.12,54.48,55.84,57.20,58.57,59.93,61.29,63.11,64.47, 66.28,68.10,69.92,72.19,74.46) + Solution()=Multiple_regression(DataX, DataY) + Print "Solutions:" + Print $("0.0000000"), Solution() +} +Task_Multiple_regression diff --git a/Task/Multiple-regression/PascalABC.NET/multiple-regression.pas b/Task/Multiple-regression/PascalABC.NET/multiple-regression.pas new file mode 100644 index 0000000000..a1fac0343c --- /dev/null +++ b/Task/Multiple-regression/PascalABC.NET/multiple-regression.pas @@ -0,0 +1,26 @@ +uses NumLibABC; + +function multipleRegression(y, x: Matrix): Matrix; +begin + var cy := y.Transpose; + var cx := x.Transpose; + result := ((x * cx).Inv * x * cy).Transpose; +end; + +begin + var y := new Matrix(1, 5, 1, 2, 3, 4, 5); + var x := new Matrix(1, 5, 2, 1, 3, 4, 5); + multipleRegression(y, x).println(18, 15); + + y := new Matrix(1, 3, 3, 4, 5); + x := new Matrix(2, 3, 1, 2, 1, 1, 1, 2); + multipleRegression(y, x).Println(4, 1); + + y := new Matrix(1, 15, 52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, + 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46); + var a := |1.47, 1.5, 1.52, 1.55, 1.57, 1.6, 1.63, 1.65, 1.68, 1.7, 1.73, 1.75, 1.78, 1.8, 1.83|; + var aa := a.Select(x -> x.Sqr).ToArray; + var c := |1.0| * a.Length + a + aa; + x := new Matrix(3, a.Length, c); + multipleRegression(y, x).Println(18, 12); +end. diff --git a/Task/Multiplicative-order/FreeBASIC/multiplicative-order.basic b/Task/Multiplicative-order/FreeBASIC/multiplicative-order.basic new file mode 100644 index 0000000000..5b66e8738d --- /dev/null +++ b/Task/Multiplicative-order/FreeBASIC/multiplicative-order.basic @@ -0,0 +1,177 @@ +#include "windows.bi" + +Type prime_factor + p As Ulong + e As Ulong +End Type + +' Arrays and their counters +Dim Shared primes(1 Shl 15) As Ulong +Dim Shared primeCount As Integer = 0 + +Function get_prime_factors(n As Ulong, factors() As prime_factor) As Integer + Static As Ulong e, p, i + Dim factorCount As Integer = 0 + + ' Handle even numbers specially + If (n And 1) = 0 Then + e = 0 + While (n And 1) = 0 + e += 1 + n Shr= 1 + Wend + factors(factorCount).p = 2 + factors(factorCount).e = e + factorCount += 1 + End If + + ' Now we only need to check odd numbers + For i = 1 To primeCount - 1 + p = primes(i) + If p * p > n Then Exit For + + If (n Mod p) = 0 Then + e = 0 + Do + e += 1 + n \= p + Loop While (n Mod p) = 0 + + factors(factorCount).p = p + factors(factorCount).e = e + factorCount += 1 + End If + Next + + If n > 1 Then + factors(factorCount).p = n + factors(factorCount).e = 1 + factorCount += 1 + End If + + Return factorCount +End Function + +Function get_factors(n As Ulong, factors() As Ulong) As Integer + Dim As Ulong i, k + Dim As Integer p, j, prevLen + Dim As prime_factor prime_factors(100) + Dim As Integer factorCount = get_prime_factors(n, prime_factors()) + + factors(0) = 1 + Dim As Integer len2 = 1 + Dim As Integer totalFactors = 1 + + For i = 0 To factorCount - 1 + p = prime_factors(i).p + prevLen = totalFactors + + For j = 0 To prime_factors(i).e - 1 + For k = 0 To prevLen - 1 + factors(totalFactors) = factors(k) * p + totalFactors += 1 + Next + p *= prime_factors(i).p + Next + Next + + ' Sort the factors + For i = 0 To totalFactors - 2 + For p = i + 1 To totalFactors - 1 + If factors(i) > factors(p) Then Swap factors(i), factors(p) + Next + Next + + Return totalFactors +End Function + +Function mpow(a As Ulongint, p As Ulongint, m As Ulongint) As Ulongint + Dim r As Ulongint = 1 + While p > 0 + If (p And 1) Then r = (r * a) Mod m + a = (a * a) Mod m + p Shr= 1 + Wend + Return r +End Function + +Function ipow(a As Ulongint, p As Ulongint) As Ulongint + Dim r As Ulongint = 1 + While p > 0 + If (p And 1) Then r *= a + a *= a + p Shr= 1 + Wend + Return r +End Function + +Function GCD(n As Ulongint, d As Ulongint) As Ulongint + Return Iif(d = 0, n, GCD(d, n Mod d)) +End Function + +Function lcm(r As Ulongint, s As Ulongint) As Ulongint + Return (r * s) / GCD(r, s) +End Function + +Function multi_order_p(a As Ulong, p As Ulong, e As Ulong) As Ulong + Dim As Ulong m = ipow(p, e) + Dim As Ulong t = (m \ p) * (p - 1) + Dim As Ulong fac(1000) + Dim As Integer facCount = get_factors(t, fac()) + + For i As Integer = 0 To facCount - 1 + If mpow(a, fac(i), m) = 1 Then Return fac(i) + Next + + Return 0 +End Function + +Function multi_order(a As Ulong, m As Ulong) As Ulong + Dim pf(100) As prime_factor + Dim pfCount As Integer = get_prime_factors(m, pf()) + Dim res As Ulong = 1 + + For i As Integer = 0 To pfCount - 1 + res = lcm(res, multi_order_p(a, pf(i).p, pf(i).e)) + Next + + Return res +End Function + +Sub sieve() + Dim As Integer i, j + Const SIZE = 1 Shl 15 + Static bits(0 To SIZE-1) As Boolean + + ' Fill with True's (faster than loop) + FillMemory(@bits(0), SIZE, True) + + bits(0) = False + bits(1) = False + + ' Only need to check up to sqrt(SIZE) + For i = 2 To Int(Sqr(SIZE)) + If bits(i) Then + For j = i * i To SIZE-1 Step i + bits(j) = False + Next + End If + Next + + ' Store primes in array + For i = 2 To SIZE-1 + If bits(i) Then + primes(primeCount) = i + primeCount += 1 + End If + Next +End Sub + +' Main program +sieve() +Print multi_order(37, 1000) ' Prints 100 +Print multi_order(37, 3343) ' Prints 1114 +Print multi_order(54, 100001) ' Prints 9090 +Print multi_order(3047753288, 2257683301) ' Prints 62713425 + +Sleep diff --git a/Task/Munchausen-numbers/Langur/munchausen-numbers.langur b/Task/Munchausen-numbers/Langur/munchausen-numbers.langur index b97ba6c9a9..244ff69d79 100644 --- a/Task/Munchausen-numbers/Langur/munchausen-numbers.langur +++ b/Task/Munchausen-numbers/Langur/munchausen-numbers.langur @@ -1,5 +1,5 @@ # sum power of digits -val spod = fn n:fold(fn{+}, map(fn x:x^x, n -> string -> s2n)) +val spod = fn n:fold(map(n -> string -> s2n, by=fn x:x^x), by=fn{+}) # Munchausen -writeln "Answers: ", filter(fn n: n == spod(n), series(1..5000)) +writeln "Answers: ", filter(series(5000), by=fn n:n == spod(n)) diff --git a/Task/Munchausen-numbers/PascalABC.NET/munchausen-numbers.pas b/Task/Munchausen-numbers/PascalABC.NET/munchausen-numbers.pas new file mode 100644 index 0000000000..c1e948ce26 --- /dev/null +++ b/Task/Munchausen-numbers/PascalABC.NET/munchausen-numbers.pas @@ -0,0 +1,2 @@ +## +(1..5000).Where(x -> x = x.ToString.Select(c -> (if c = '0' then 0 else c.ToDigit ** c.ToDigit)).Sum).Println; diff --git a/Task/Musical-scale/68000-Assembly/musical-scale.68000 b/Task/Musical-scale/68000-Assembly/musical-scale.68000 new file mode 100644 index 0000000000..70dc735408 --- /dev/null +++ b/Task/Musical-scale/68000-Assembly/musical-scale.68000 @@ -0,0 +1,25 @@ + lea sample(pc),a0 + move.l a0,$dff0a0 ; AUD0LCH and AUD0LCL + move.w #32,$dff0a4 ; AUD0LEN = number of sample words + move.w #48,$dff0a8 ; AUD0VOL + moveq #9,d2 ; number of notes -1 + lea notes(pc),a0 + move.w #$8203,$dff096 ; enable DMA for AUD0 +loop: move.w (a0)+,$dff0a6 + moveq #50,d1 ; delay 50 frames +waitv1: tst.b $dff006 ; VPOSHR + bne waitv1 +waitv2: tst.b $dff006 + beq waitv2 + dbf d1,waitv1 + dbf d2,loop + move.w #1,$dff096 ; turn DMA off again + rts + +notes: dc.w 212,189,168,159,141,126,112,106,106,106 + +; a simple triangular waveform +sample: dc.b 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96, 104, 112, 120 + dc.b 128, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8 + dc.b 0,-8,-16,-24,-32,-40,-48,-56,-64,-72,-80,-88,-96,-104,-112,-120 + dc.b -127,-120,-112,-140,-96,-88,-80,-72,-64,-56,-48,-40,-32,-24,-16,-8 diff --git a/Task/Musical-scale/Aquarius-BASIC/musical-scale.basic b/Task/Musical-scale/Aquarius-BASIC/musical-scale.basic new file mode 100644 index 0000000000..fef6565b5c --- /dev/null +++ b/Task/Musical-scale/Aquarius-BASIC/musical-scale.basic @@ -0,0 +1,6 @@ +10 FOR I=1 TO 8 +20 READ F +30 P=285*200/F +40 SOUND(F,P) +50 NEXT +60 DATA 262, 294, 330, 349, 392, 440, 494, 523 diff --git a/Task/Musical-scale/Atari-BASIC/musical-scale.basic b/Task/Musical-scale/Atari-BASIC/musical-scale.basic new file mode 100644 index 0000000000..d87d4a698d --- /dev/null +++ b/Task/Musical-scale/Atari-BASIC/musical-scale.basic @@ -0,0 +1,9 @@ +10 Q=31960.4:REM NTSC +20 IF PEEK(53268)=1 THEN Q=31668.7:REM PAL +30 FOR I=1 TO 8 +40 READ F +50 P=INT(Q/F-0.5) +60 SOUND 1,P,10,15 +70 FOR T=0 TO 800:NEXT T +80 NEXT I +90 DATA 262,294,330,349,392,440,494,523 diff --git a/Task/Musical-scale/PascalABC.NET/musical-scale.pas b/Task/Musical-scale/PascalABC.NET/musical-scale.pas new file mode 100644 index 0000000000..8dc903320b --- /dev/null +++ b/Task/Musical-scale/PascalABC.NET/musical-scale.pas @@ -0,0 +1,3 @@ +## +foreach var note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25] do + Console.Beep(note.Round, 500) diff --git a/Task/Mutual-recursion/Miranda/mutual-recursion.miranda b/Task/Mutual-recursion/Miranda/mutual-recursion.miranda new file mode 100644 index 0000000000..ebe291b2c3 --- /dev/null +++ b/Task/Mutual-recursion/Miranda/mutual-recursion.miranda @@ -0,0 +1,11 @@ +main :: [sys_message] +main = [Stdout ("F: " ++ show (map f [0..20]) ++ "\n"), + Stdout ("M: " ++ show (map m [0..20]) ++ "\n")] + +f :: num->num +f 0 = 1 +f n = n - m (f (n-1)) + +m :: num->num +m 0 = 0 +m n = n - f (m (n-1)) diff --git a/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas b/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas index 30c19f3292..b8ff897ee9 100644 --- a/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas +++ b/Task/Mutual-recursion/PascalABC.NET/mutual-recursion.pas @@ -1,7 +1,7 @@ ## function M(n: integer): integer; forward; -function F(n: integer): integer := n < 1 ? 1 : n - M(F(n - 1)); -function M(n: integer): integer := n < 1 ? 0 : n - F(M(n - 1)); +function F(n: integer): integer := if n < 1 then 1 else n - M(F(n - 1)); +function M(n: integer): integer := if n < 1 then 0 else n - F(M(n - 1)); (0..19).select(x -> F(x)).println; (0..19).select(x -> M(x)).println; diff --git a/Task/Mutual-recursion/Zig/mutual-recursion.zig b/Task/Mutual-recursion/Zig/mutual-recursion.zig new file mode 100644 index 0000000000..eab66631c0 --- /dev/null +++ b/Task/Mutual-recursion/Zig/mutual-recursion.zig @@ -0,0 +1,15 @@ +fn f(n: u64) u64 { + return if (n == 0) 1 else n-m(f(n-1)); +} + +fn m(n: u64) u64 { + return if (n == 0) 0 else n-f(m(n-1)); +} + +pub fn main() !void { + const stdout = @import("std").io.getStdOut().writer(); + try stdout.writeAll(" n F M\n"); + for (0..20) |n| { + try stdout.print("{d: >2}: {d: >2} {d: >2}\n", .{n, f(n), m(n)}); + } +} diff --git a/Task/N-queens-problem/PascalABC.NET/n-queens-problem.pas b/Task/N-queens-problem/PascalABC.NET/n-queens-problem.pas new file mode 100644 index 0000000000..ccef0ba98e --- /dev/null +++ b/Task/N-queens-problem/PascalABC.NET/n-queens-problem.pas @@ -0,0 +1,17 @@ +const + N = 8; + +begin + var cols := (1..N); + var solutions := 0; + foreach var vec in cols.Permutations do + if (N = cols.Select(n -> vec[n - 1] + n).ToSet.Count) and + (N = cols.Select(n -> vec[n - 1] - n).ToSet.Count) then + begin + solutions += 1; +// foreach var col in ('a'..'h') index i do +// write(col, vec[i], ' '); +// write(if solutions mod 4 = 0 then #10 else ' '); + end; + writeln('Solutions: ', solutions); +end. diff --git a/Task/Named-parameters/PascalABC.NET/named-parameters.pas b/Task/Named-parameters/PascalABC.NET/named-parameters.pas new file mode 100644 index 0000000000..12fdc0f1d9 --- /dev/null +++ b/Task/Named-parameters/PascalABC.NET/named-parameters.pas @@ -0,0 +1,8 @@ +## +procedure test(first: integer; second: integer := 2; third: integer := 3); +begin +end; + +test(5); +test(5, 5); +test(5, third := 5, second := 5); diff --git a/Task/Narcissistic-decimal-number/PascalABC.NET/narcissistic-decimal-number.pas b/Task/Narcissistic-decimal-number/PascalABC.NET/narcissistic-decimal-number.pas new file mode 100644 index 0000000000..8b3416a0b8 --- /dev/null +++ b/Task/Narcissistic-decimal-number/PascalABC.NET/narcissistic-decimal-number.pas @@ -0,0 +1,26 @@ +function narc(): sequence of integer; +begin + var power := |0, 1, 2, 3, 4, 5, 6, 7, 8, 9|; + var limit := 10; + var x := 0; + repeat + if x >= limit then + begin + foreach var i in (0..9) do power[i] := power[i] * i; + limit := limit * 10; + end; + var sum := 0; + var xx := x; + while (xx > 0) do + begin + sum := sum + power[xx mod 10]; + xx := (xx / 10).floor; + end; + if sum = x then yield x; + x += 1; + until false; +end; + +begin + narc.Take(25).println; +end. diff --git a/Task/Next-highest-int-from-digits/PascalABC.NET/next-highest-int-from-digits.pas b/Task/Next-highest-int-from-digits/PascalABC.NET/next-highest-int-from-digits.pas new file mode 100644 index 0000000000..32e794561b --- /dev/null +++ b/Task/Next-highest-int-from-digits/PascalABC.NET/next-highest-int-from-digits.pas @@ -0,0 +1,53 @@ +function digits(n: biginteger): list; +begin + // Return the list of digits of "n" in reverse order. + result := new list; + if n = 0 then result.add(0); + while n <> 0 do + begin + result.add(byte(n mod 10)); + n := n div 10; + end; +end; + +function nextHighest(n: biginteger): biginteger; +begin + // Find the next highest integer of "n". + // If none is found, "n" is returned. + var d := digits(n); // Warning: in reverse order. + var m := d[0]; + foreach var i in 1..d.Count - 1 do + if d[i] < m then + begin + // Find the digit greater then d[i] and closest to it. + var delta := m - d[i] + 1; + var best: integer; + foreach var j in 0..i - 1 do + begin + var diff := d[j] - d[i]; + if (diff > 0) and (diff < delta) then + begin + // Greater and closest. + delta := diff; + best := j; + end; + end; + // Exchange digits. + (d[i], d[best]) := (d[best], d[i]); + // Sort previous digits. + var (d1, d2) := d.SplitAt(i); + d := d1.SortedDescending.ToList + d2.ToList; + break; + end + else m := d[i]; + // Compute the value from the digits. + foreach var val in d[::-1] do + result := 10 * result + val; +end; + +begin + foreach var n in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020] do + println(n, ' → ', nextHighest(n)); + var n := '9589776899767587796600'.ToBigInteger; + println(n, '→', nextHighest(n)); +end. diff --git a/Task/Nim-game/PascalABC.NET/nim-game.pas b/Task/Nim-game/PascalABC.NET/nim-game.pas new file mode 100644 index 0000000000..a65c62b67a --- /dev/null +++ b/Task/Nim-game/PascalABC.NET/nim-game.pas @@ -0,0 +1,24 @@ +## +writeln('There are twelve tokens.'); +writeln('You can take 1, 2, or 3 on your turn.'); +writeln('Whoever takes the last token wins.'); + +var tokens := 12; + +while (tokens > 0) do +begin + writeln('There are ' + tokens + ' remaining.'); + writeln('How many do you take?'); + var playertake := ReadInteger; + + if (playertake < 1) or (playertake > 3) then + writeln('1, 2 or 3 only.') + else + begin + tokens -= playertake; + writeln('I take ' + (4 - playertake) + '.'); + tokens -= (4 - playertake); + end; +end; + +writeln('I win again.'); diff --git a/Task/Non-continuous-subsequences/PascalABC.NET/non-continuous-subsequences.pas b/Task/Non-continuous-subsequences/PascalABC.NET/non-continuous-subsequences.pas new file mode 100644 index 0000000000..3cc439b320 --- /dev/null +++ b/Task/Non-continuous-subsequences/PascalABC.NET/non-continuous-subsequences.pas @@ -0,0 +1,29 @@ +function AllSubSets(a: List; i: integer; lst: List): sequence of List; +begin + if i = a.Count then yield lst + else + begin + lst.Add(a[i]); + yield sequence AllSubSets(a, i + 1, lst); + lst.RemoveAt(lst.Count - 1); + yield sequence AllSubSets(a, i + 1, lst); + end; +end; + +function IsContinuous(lst: List) := +if lst.Count > 0 then lst[^1] - lst[0] + 1 = lst.Count else true; + +function ncsub(seq: list) := +Allsubsets(Lst(1..seq.Count), 0, new List) + .Where(s -> not iscontinuous(s)) + .Select(s -> s.Select(i -> seq[i - 1]).ToList); + +begin + var seq := |'C', 'D', 'A', 'E', 'B'|.ToList; + println('Non-continuous subsequences for', seq, ':'); + ncsub(seq).Println; + println; + println('Non-continuous subsequences:'); + for var n := 1 to 20 do + println([1..n], '=', ncsub([1..n].ToList).Count); +end. diff --git a/Task/Nonoblock/PascalABC.NET/nonoblock.pas b/Task/Nonoblock/PascalABC.NET/nonoblock.pas new file mode 100644 index 0000000000..ccd63c9919 --- /dev/null +++ b/Task/Nonoblock/PascalABC.NET/nonoblock.pas @@ -0,0 +1,37 @@ +function genSequence(ones: list; numZeros: integer): list; +begin + result := new list; + if ones.Count = 0 then result := Lst('0' * (numZeros +1)) + else + foreach var x in 1..(numZeros - ones.Count + 2) do + begin + var skipOne := ones.Skip(1).ToList; + foreach var tail in genSequence(skipOne, numZeros - x) do + result.add(('0' * x) + ones[0] + tail); + end; +end; + +procedure printBlock(data: string; length: integer); +begin + var a := data.select(c -> ord(c) - ord('0')).ToList; + var sumBytes := a.sum; + + writeln(#10, 'blocks ', a, ' cells ', length); + if length - sumBytes <= 0 then + println('No solution') + else + begin + var prep := a.Select(n -> '1' * n).ToList; + + foreach var r in genSequence(prep, length - sumBytes) do + r[2:].println; + end; +end; + +begin + printBlock('21', 5); + printBlock('', 5); + printBlock('8', 10); + printBlock('2323', 15); + printBlock('23', 5); +end. diff --git a/Task/Nth-root/ALGOL-60/nth-root-1.alg b/Task/Nth-root/ALGOL-60/nth-root-1.alg new file mode 100644 index 0000000000..54eecfc751 --- /dev/null +++ b/Task/Nth-root/ALGOL-60/nth-root-1.alg @@ -0,0 +1,21 @@ +begin + +comment - return the nth root of x to stated precision; +real procedure nthroot(x, n, precision); + value x, n, precision; real x, n, precision; +begin + real x0, x1; + x0 := x; + x1 := x / n; + for x0 := x0 while abs(x1 - x0) > precision do + begin + x0 := x1; + x1 := ((n-1)*x1 + x / x1 ** (n-1)) / n; + end; + nthroot := x1; +end; + +outstring(1,"Cube root of 81 ="); +outreal(1,nthroot(81, 3, 0.0000001)); + +end diff --git a/Task/Nth-root/ALGOL-60/nth-root-2.alg b/Task/Nth-root/ALGOL-60/nth-root-2.alg new file mode 100644 index 0000000000..fd6187db55 --- /dev/null +++ b/Task/Nth-root/ALGOL-60/nth-root-2.alg @@ -0,0 +1,5 @@ +real procedure nthroot(x, n); + value x, n; real x, n; +begin + nthroot := exp(ln(x) / n); +end; diff --git a/Task/Nth-root/ALGOL-60/nth-root-3.alg b/Task/Nth-root/ALGOL-60/nth-root-3.alg new file mode 100644 index 0000000000..5f133379b8 --- /dev/null +++ b/Task/Nth-root/ALGOL-60/nth-root-3.alg @@ -0,0 +1,5 @@ +real procedure nthroot(x, n); + value x, n; real x, n; +begin + nthroot := x ** (1/n); +end; diff --git a/Task/Nth-root/ANSI-BASIC/nth-root.basic b/Task/Nth-root/ANSI-BASIC/nth-root.basic new file mode 100644 index 0000000000..74e50776b8 --- /dev/null +++ b/Task/Nth-root/ANSI-BASIC/nth-root.basic @@ -0,0 +1,23 @@ +100 REM Nth root +110 DECLARE EXTERNAL FUNCTION NthRoot +120 LET X = 144 +130 PRINT "Finding the nth root of"; X; "to 6 decimal places" +140 PRINT " x n root x ^ (1 / n)" +150 PRINT "--------------------------------------" +160 FOR I = 1 TO 8 +170 PRINT USING "### ": X; +180 PRINT USING "#### ": I; +190 PRINT USING "###.######": NthRoot(I, X, 1.000000E-07); +200 PRINT USING " ###.######": X ^ (1 / I) +210 NEXT I +220 END +230 EXTERNAL FUNCTION NthRoot(N, X, Precision) +240 REM Returns the Nth root of value X to stated Precision +250 LET X0 = X +260 LET X1 = X / N ! initial guess +270 DO WHILE ABS(X1 - X0) > Precision +280 LET X0 = X1 +290 LET X1 = ((N - 1) * X1 + X / X1 ^ (N - 1)) / N +300 LOOP +310 LET NthRoot = X1 +320 END FUNCTION diff --git a/Task/Nth-root/AWK/nth-root.awk b/Task/Nth-root/AWK/nth-root-1.awk similarity index 100% rename from Task/Nth-root/AWK/nth-root.awk rename to Task/Nth-root/AWK/nth-root-1.awk diff --git a/Task/Nth-root/AWK/nth-root-2.awk b/Task/Nth-root/AWK/nth-root-2.awk new file mode 100644 index 0000000000..149c314327 --- /dev/null +++ b/Task/Nth-root/AWK/nth-root-2.awk @@ -0,0 +1,24 @@ +#!/usr/bin/awk -f +BEGIN { + # test + print nthroot(8,3) + print nthroot(16,2) + print nthroot(16,4) + print nthroot(125,3) + print nthroot(3,3) + print nthroot(3,2) +} + +function nthroot(a, n, x, y, a_n, n1_n) { + # no need for eps, the values are monotonically decreasing + # until the root is found (if the initial value is above the root) + x = 1 + a / n # starting value above the root + a_n = a/n # precompute loop invariants + n1_n = (n - 1) / n + do { + y = x + x = n1_n * x + a_n / x^(n-1) + } while (x < y) + # no harm to use average if x = y + return (x + y) / 2 +} diff --git a/Task/Nth-root/AWK/nth-root-3.awk b/Task/Nth-root/AWK/nth-root-3.awk new file mode 100644 index 0000000000..a408ea3387 --- /dev/null +++ b/Task/Nth-root/AWK/nth-root-3.awk @@ -0,0 +1,8 @@ +{ + x = $0 + do { + y = x + x = (x + $0/x)/2 + } while (x < y) + print "sqrt(" a ")=" x +} diff --git a/Task/Nth-root/BASIC/nth-root-3.basic b/Task/Nth-root/BASIC/nth-root-3.basic deleted file mode 100644 index 077503d9b9..0000000000 --- a/Task/Nth-root/BASIC/nth-root-3.basic +++ /dev/null @@ -1 +0,0 @@ -PRINT "The "; e; "th root of "; b; " is "; RootX(b, e, .000001) diff --git a/Task/Nth-root/GW-BASIC/nth-root.basic b/Task/Nth-root/GW-BASIC/nth-root.basic new file mode 100644 index 0000000000..222b294249 --- /dev/null +++ b/Task/Nth-root/GW-BASIC/nth-root.basic @@ -0,0 +1,23 @@ +100 REM Nth root +110 X# = 144 +120 PRINT "Finding the nth root of"; X#; "to 6 decimal places" +130 PRINT " x n root x ^ (1 / n)" +140 PRINT "--------------------------------------" +150 FOR I% = 1 TO 8 +160 PRINT USING "### "; X#; +170 PRINT USING "#### "; I%; +180 N% = I%: PREC# = .0000001#: GOSUB 1000 +190 PRINT USING "###.######"; NTH.ROOT#; +200 PRINT USING " ###.######"; X# ^ (1 / I%) +210 NEXT I% +220 END +1000 REM Calculate the N%th root of value X# to stated precision PREC# +1010 REM Result: NTH.ROOT# +1020 X0# = X# +1030 X1# = X# / N% ' initial guess +1040 WHILE ABS(X1# - X0#) > PREC# +1050 X0# = X1# +1060 X1# = ((N% - 1) * X1# + X# / X1# ^ (N% - 1)) / N% +1070 WEND +1080 NTH.ROOT# = X1# +1090 RETURN diff --git a/Task/Nth-root/Modula-2/nth-root.mod2 b/Task/Nth-root/Modula-2/nth-root.mod2 new file mode 100644 index 0000000000..fc8d4f18ec --- /dev/null +++ b/Task/Nth-root/Modula-2/nth-root.mod2 @@ -0,0 +1,47 @@ +MODULE NthRoot; +FROM LongMath IMPORT + power; +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SLongIO IMPORT + WriteFixed; +FROM SWholeIO IMPORT + WriteInt; + +VAR + X: LONGREAL; + I: CARDINAL; + +PROCEDURE Root(X: LONGREAL; N: CARDINAL; Precision: LONGREAL): LONGREAL; +(* Returns the Nth root of value X to stated Precision *) +VAR + X0, X1, NR: LONGREAL; +BEGIN + NR := FLOAT(N); + X0 := X; + X1 := X / NR; (* initial guess *) + WHILE ABS(X1 - X0) > Precision DO + X0 := X1; + X1 := ((NR - 1.0) * X1 + X / power(X1, NR - 1.0)) / NR + END; + RETURN X1 +END Root; + +BEGIN + X := 144.0; + WriteString("Finding the nth root of "); + WriteFixed(X, 1, 5); + WriteString(" to 6 decimal places"); + WriteLn; + WriteString(" x n root x ^ (1 / n)"); + WriteLn; + WriteString("----------------------------------------"); + WriteLn; + FOR I := 1 TO 8 DO + WriteFixed(X, 1, 5); + WriteInt(I, 7); + WriteFixed(Root(X, I, 1.0E-07), 6, 14); + WriteFixed(power(X, 1. / FLOAT(I)), 6, 14); + WriteLn + END +END NthRoot. diff --git a/Task/Nth-root/OoRexx/nth-root.rexx b/Task/Nth-root/OoRexx/nth-root.rexx new file mode 100644 index 0000000000..ef8aae872c --- /dev/null +++ b/Task/Nth-root/OoRexx/nth-root.rexx @@ -0,0 +1,31 @@ +/* REXX */ +Numeric Digits 70 +Call test 2,2 +Call test 10,3 +Call test 625,-4 +Call test 100.666,47 +Call test -256,8 +Call test 12345678900098765432100.00987654321000123456789e333,19 +Exit +test: +Parse Arg x,n +xa=abs(x) +na=abs(n) +lnx=rxmlog(xa,70) +rt=rxmexp(lnx/na,70) +Numeric Digits 65 +result=rt+0 +If pos('.',result)>0 Then Do -- get rid of zeroes in decimals + Parse Var result int '.' dec + If dec=0 Then + result=int + End +If sign(n)=-1 Then result=1/result +If sign(x)=-1 Then result=result'j' +Say ' x = ' x +Say ' root = ' n +Say ' digits = ' 65 +Say ' answer = ' result +Say '' +Return +::REQUIRES rxm.cls diff --git a/Task/Nth-root/QuickBASIC/nth-root.basic b/Task/Nth-root/QuickBASIC/nth-root.basic new file mode 100644 index 0000000000..0f351df4f8 --- /dev/null +++ b/Task/Nth-root/QuickBASIC/nth-root.basic @@ -0,0 +1,24 @@ +' Nth root +DECLARE FUNCTION NthRoot# (N%, X#, Precision#) +X# = 144 +PRINT "Finding the nth root of"; X#; "to 6 decimal places" +PRINT " x n root x ^ (1 / n)" +PRINT "--------------------------------------" +FOR I% = 1 TO 8 + PRINT USING "### "; X#; + PRINT USING "#### "; I%; + PRINT USING "###.######"; NthRoot#(I%, X#, .0000001); + PRINT USING " ###.######"; X# ^ (1 / I%) +NEXT I% +END + +FUNCTION NthRoot# (N%, X#, Precision#) + ' Returns the Nth root of value X to stated Precision + X0# = X# + X1# = X# / N% ' initial guess + DO WHILE ABS(X1# - X0#) > Precision# + X0# = X1# + X1# = ((N% - 1) * X1# + X# / X1# ^ (N% - 1)) / N% + LOOP + NthRoot# = X1# +END FUNCTION diff --git a/Task/Nth-root/REXX/nth-root-1.rexx b/Task/Nth-root/REXX/nth-root-1.rexx deleted file mode 100644 index 0cb70d985e..0000000000 --- a/Task/Nth-root/REXX/nth-root-1.rexx +++ /dev/null @@ -1,38 +0,0 @@ -/*REXX program calculates the Nth root of X, with DIGS (decimal digits) accuracy. */ -parse arg x root digs . /*obtain optional arguments from the CL*/ -if x=='' | x=="," then x= 2 /*Not specified? Then use the default.*/ -if root=='' | root=="," then root= 2 /* " " " " " " */ -if digs=='' | digs=="," then digs=65 /* " " " " " " */ -numeric digits digs /*set the decimal digits to DIGS. */ -say ' x = ' x /*echo the value of X. */ -say ' root = ' root /* " " " " ROOT. */ -say ' digits = ' digs /* " " " " DIGS. */ -say ' answer = ' root(x, root) /*show the value of ANSWER. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -root: procedure; parse arg x 1 Ox, r 1 Or /*arg1 ──► x & Ox, 2nd ──► r & Or*/ - if r=='' then r=2 /*Was root specified? Assume √. */ - if r=0 then return '[n/a]' /*oops-ay! Can't do zeroth root.*/ - complex= x<0 & R//2==0 /*will the result be complex? */ - oDigs=digits() /*get the current number of digs.*/ - if x=0 | r=1 then return x/1 /*handle couple of special cases.*/ - dm=oDigs+5 /*we need a little guard room. */ - r=abs(r); x=abs(x) /*the absolute values of R and X.*/ - rm=r-1 /*just a fast version of ROOT -1*/ - numeric form /*take a good guess at the root─┐*/ - parse value format(x,2,1,,0) 'E0' with ? 'E' _ . /* ◄────────────────────────────┘*/ - g= (? / r'E'_ % r) + (x>1) /*kinda uses a crude "logarithm".*/ - d=5 /*start with five decimal digits.*/ - do until d==dm; d=min(d+d,dm) /*each time, precision doubles. */ - numeric digits d /*tell REXX to use D digits. */ - old=-1 /*assume some kind of old guess. */ - do until old=g; old=g /*where da rubber meets da road─┐*/ - g=format((rm*g**r+x)/r/g**rm,, d-2) /* ◄────── the root computation─┘*/ - end /*until old=g*/ /*maybe until the cows come home.*/ - end /*until d==dm*/ /*and wait for more cows to come.*/ - - if g=0 then return 0 /*in case the jillionth root = 0.*/ - if Or<0 then g=1/g /*root < 0 ? Reciprocal it is! */ - if \complex then g=g*sign(Ox) /*adjust the sign (maybe). */ - numeric digits oDigs /*reinstate the original digits. */ - return (g/1) || left('j', complex) /*normalize # to digs, append j ?*/ diff --git a/Task/Nth-root/REXX/nth-root-2.rexx b/Task/Nth-root/REXX/nth-root-2.rexx deleted file mode 100644 index 7f4dbc34e6..0000000000 --- a/Task/Nth-root/REXX/nth-root-2.rexx +++ /dev/null @@ -1,4 +0,0 @@ -do until old=g; old=g /*where da rubber meets da road-+*/
-g=format((rm*g**r+x)/r/g**rm,, d-2) /* ?------ the root computation-+*/
-'''say 'g' g 'old' old'''
-end /*until old=g*/ /*maybe until the cows come home.*/
diff --git a/Task/Nth-root/REXX/nth-root-3.rexx b/Task/Nth-root/REXX/nth-root.rexx similarity index 56% rename from Task/Nth-root/REXX/nth-root-3.rexx rename to Task/Nth-root/REXX/nth-root.rexx index 3f0c57e41e..d319e533a9 100644 --- a/Task/Nth-root/REXX/nth-root-3.rexx +++ b/Task/Nth-root/REXX/nth-root.rexx @@ -10,49 +10,8 @@ numeric digits digs /*set the decimal digits to say ' x = ' x /*echo the value of X. */ say ' root = ' root /* " " " " ROOT. */ say ' digits = ' digs /* " " " " DIGS. */ -say ' answer = ' nroot(x, root) /*show the value of ANSWER. */ +say ' answer = ' Nroot(x, root) /*show the value of ANSWER. */ exit /*stick a fork in it, we're all done. */ -/*--------------------------------------------------------------------------------------*/ -Nroot: -/* Nth root function = x^(1/n) */ -procedure expose glob. -arg x,n -/* Fast values */ -if x = 0 then - return 0 -if x = 1 then - return 1 -/* Formulas using faster methods */ -if n = 2 then - return Sqrt(x) -if n = 3 then - return Cbrt(x) -if n = 4 then - return Qtrt(x) -/* Calculate */ -sx = Sign(x); x = Abs(x) -p1 = Digits(); p2 = p1+2 -numeric digits 3 -/* First guess low accuracy */ -y = 1/Exp(Ln(x)/n) -numeric digits p2 -/* Dynamic precision */ -d = p2 -do k = 1 while d > 4 - d.k = d; d = d%2+1 -end -d.k = 4 -/* Halley */ -a = 1/n; b = n+1 -do j = k to 1 by -1 - numeric digits d.j - y = y*a*(b-x*y**n) -end -y = 1/y -if sx < 0 then - y = -y -numeric digits p1 -return y+0 include Numbers include Functions diff --git a/Task/Nth-root/RapidQ/nth-root.rapidq b/Task/Nth-root/RapidQ/nth-root.rapidq new file mode 100644 index 0000000000..2aa6bd3b8a --- /dev/null +++ b/Task/Nth-root/RapidQ/nth-root.rapidq @@ -0,0 +1,25 @@ +' Nth root +DECLARE FUNCTION NthRoot (N%, X#, Precision#) AS DOUBLE +X# = 144 +PRINT "Finding the nth root of ";X#;" to 6 decimal places" +PRINT " x n root x ^ (1 / n)" +PRINT "--------------------------------------" +FOR I% = 1 TO 8 + PRINT FORMAT$("%3d ", X#); + PRINT FORMAT$("%4d ", I%); + PRINT FORMAT$("%10.6f", NthRoot(I%, X#, .0000001)); + PRINT FORMAT$(" %10.6f", X# ^ (1 / I%)) +NEXT I% +input X# +END + +FUNCTION NthRoot (N%, X#, Precision#) AS DOUBLE + ' Returns the Nth root of value X to stated Precision + X0# = X# + X1# = X# / N% ' initial guess + WHILE ABS(X1# - X0#) > Precision# + X0# = X1# + X1# = ((N% - 1) * X1# + X# / X1# ^ (N% - 1)) / N% + WEND + NthRoot = X1# +END FUNCTION diff --git a/Task/Nth-root/S-BASIC/nth-root-1.basic b/Task/Nth-root/S-BASIC/nth-root-1.basic index a38e90743c..9a2373df01 100644 --- a/Task/Nth-root/S-BASIC/nth-root-1.basic +++ b/Task/Nth-root/S-BASIC/nth-root-1.basic @@ -4,12 +4,14 @@ end = exp((1.0 / n) * log(x)) rem - exercise the routine by finding successive roots of 144 var i = integer +var x = real -print "Finding the nth root of x" +x = 144 +print "Finding the nth root of"; x print " x n root" print "-----------------------" for i = 1 to 8 - print using "### #### ###.####"; 144; i; nthroot(144, i) + print using "### #### ###.####"; x; i; nthroot(x, i) next i end diff --git a/Task/Nth-root/S-BASIC/nth-root-2.basic b/Task/Nth-root/S-BASIC/nth-root-2.basic index 7a8c2ac639..7d03be3618 100644 --- a/Task/Nth-root/S-BASIC/nth-root-2.basic +++ b/Task/Nth-root/S-BASIC/nth-root-2.basic @@ -1,8 +1,8 @@ -rem - return the nth root of real.double value x to stated precision +rem - return the nth root of x to stated precision function nthroot(n, x, precision = real.double) = real.double var x0, x1 = real.double x0 = x - x1 = x / n rem - initial guess + x1 = x / n rem - initial guess while abs(x1 - x0) > precision do begin x0 = x1 @@ -13,11 +13,14 @@ end = x1 rem -- exercise the routine var i = integer -print "Finding the nth root of 144 to 6 decimal places" +var x = real.double + +x = 144 +print "Finding the nth root of"; x; " to 8 decimal places" print " x n root" print "------------------------" -for i = 1 to 8 - print using "### #### ###.######"; 144; i; nthroot(i, 144.0, 1E-7) +for i = 2 to 8 + print using "### #### ###.########"; x; i; nthroot(i, x, 1E-9) next i end diff --git a/Task/Nth-root/XPL0/nth-root.xpl0 b/Task/Nth-root/XPL0/nth-root.xpl0 index c29d27d80a..c3184fb7e8 100644 --- a/Task/Nth-root/XPL0/nth-root.xpl0 +++ b/Task/Nth-root/XPL0/nth-root.xpl0 @@ -1,21 +1,24 @@ include c:\cxpl\stdlib; -func real NRoot(A, N); \Return the Nth root of A -real A, N; -real X, X0, Y; +func real NRoot(A, N, Prec); \Return the Nth root of A with precision Prec +real A; +int N; +real Prec; +real X, X0, Y, NF; int I; -[X:= 1.0; \initial guess +[NF:= float(N); +X:= 1.0; \initial guess repeat X0:= X; Y:= 1.0; - for I:= 1 to fix(N)-1 do Y:= Y*X0; - X:= ((N-1.0)*X0 + A/Y) / N; -until abs(X-X0) < 1.0E-15; \(until X=X0 doesn't always work) + for I:= 1 to N-1 do Y:= Y*X0; + X:= ((NF-1.0)*X0 + A/Y) / NF; +until abs(X-X0) < Prec; \(until X=X0 doesn't always work) return X; ]; [Format(5, 15); -RlOut(0, NRoot( 2., 2.)); CrLf(0); +RlOut(0, NRoot( 2., 2, 1.0E-15)); CrLf(0); RlOut(0, Power( 2., 0.5)); CrLf(0); \for comparison -RlOut(0, NRoot(27., 3.)); CrLf(0); -RlOut(0, NRoot(1024.,10.)); CrLf(0); +RlOut(0, NRoot(27., 3, 1.0E-15)); CrLf(0); +RlOut(0, NRoot(1024., 10, 1.0E-15)); CrLf(0); ] diff --git a/Task/Number-names/Arturo/number-names.arturo b/Task/Number-names/Arturo/number-names.arturo new file mode 100644 index 0000000000..99358afb21 --- /dev/null +++ b/Task/Number-names/Arturo/number-names.arturo @@ -0,0 +1,60 @@ +small: [ + "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" + "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" + "eighteen" "nineteen" +] + +tens: [ + "wrong" "wrong" "twenty" "thirty" "forty" + "fifty" "sixty" "seventy" "eighty" "ninety" +] + +prefixes: ["m" "b" "tr" "quadr" "quint" "sext" "sept" "oct" "non" "dec"] +big: ["" "thousand"] ++ map prefixes 'p -> p ++ "illion" + +wordify: function [number :integer][ + if number < 0 -> + return "negative " ++ wordify neg number + + if number < 20 -> + return small\[number] + + if number < 100 [ + [d m]: divmod number 10 + return tens\[d] ++ (zero? m)? -> "" -> "-" ++ wordify m + ] + + if number < 1000 [ + [d m]: divmod number 100 + return (~{|small\[d]| hundred}) ++ (zero? m)? -> "" -> " and " ++ wordify m + ] + + chunks: [] + n: number + while [not? zero? n][ + [n remainder]: divmod n 1000 + 'chunks ++ remainder + ] + + if (size chunks) > size big -> + return "integer value too large" + + words: [] + loop.with:'i chunks 'ch [ + scale: big\[i] + unless zero? ch [ + chunkStr: wordify ch + 'words ++ (empty? scale)? -> chunkStr + -> ~"|chunkStr| |scale|" + ] + ] + + return join.with:", " reverse words +] + +loop @[ + 0,1,4,5,10,15,18,25,83,140,300,678,1024, + 45039,123456,91740274651983, + neg 83125311200, neg 12, neg 7 +] 'num -> + print [pad to :string num 15, join.with: "\n"++ (repeat " " 16) split.lines wordwrap.at: 40 wordify num diff --git a/Task/Number-names/M2000-Interpreter/number-names.m2000 b/Task/Number-names/M2000-Interpreter/number-names.m2000 new file mode 100644 index 0000000000..b47caeb010 --- /dev/null +++ b/Task/Number-names/M2000-Interpreter/number-names.m2000 @@ -0,0 +1,62 @@ +module Number_names { + numname=lambda ->{ + flush + data "", "one", "two", "three", "four" + data "five", "six", "seven", "eight", "nine", "ten" + data "eleven", "twelve", "thirteen", "fourteen", "fifteen" + data "sixteen", "seventeen","eighteen", "nineteen" + dim lows(), tens(), lev() + lows()=array([]) + data "", "", "twenty", "thirty", "forty","fifty", "sixty" + data "seventy", "eighty", "ninety" + tens()=array([]) + lev()=("", "thousand", "million", "billion") + numname_int=lambda lows(), tens(), lev() (n as long) -> { + if n=0 then ="zero": exit + long tr[0], t=-1, i + string ret, prefix + if n < 0 then prefix= "negative ": n-! else prefix="" + while n>0 + t++ + tr[t]= n mod 1000 + n|div 1000 + end while + for i=t to 0 + tripn="" + if tr[i]=0 then continue for + lt= tr[i] mod 100 + h= tr[i] div 100 + if lt<20 then + tripn+=lows(lt) + else + tripn=tens(lt div 10)+if$(lt mod 10 >0 ->"-"+lows(lt mod 10),"") + end if + if h>0 then + if lt>0 then tripn = " and " + tripn + tripn = lows(h)+" hundred" + tripn + end if + if i=0 and t>0 and h = 0 then tripn = "and " + tripn + ret += tripn+" "+lev(i)+" " + next i + =prefix+trim$(ret) + } + =lambda numname_int (n as currency) ->{ + if int(n)=n then =numname_int(n): exit + string prefix= numname_int(int(abs(n)))+" point " + string decdig = str$(abs(n)-int(abs(n))), ret + if n<0 then prefix="negative "+prefix + ret=prefix + for i = 3 to len(decdig) + ret+=lambda(val(mid$(decdig, i, 1)))+" " + next i + =trim$(ret) + } + }() 'execute here so we get the inner lambda + report numname(0) + report numname(1.0) + report numname(-1.7) + report numname(910000) + report numname(987654) + report numname(100000017) +} +Number_names diff --git a/Task/Number-names/Quackery/number-names.quackery b/Task/Number-names/Quackery/number-names.quackery index 65f25e5730..086bc21982 100644 --- a/Task/Number-names/Quackery/number-names.quackery +++ b/Task/Number-names/Quackery/number-names.quackery @@ -10,7 +10,7 @@ [ [ table $ "nonety" $ "tenty" $ "twenty" - $ "thirty" $ "fourty" $ "fifty" + $ "thirty" $ "forty" $ "fifty" $ "sixty" $ "seventy" $ "eighty" $ "ninety" ] do ] is tens ( n --> $ ) diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET/numbers-which-are-not-the-sum-of-distinct-squares.pas b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET/numbers-which-are-not-the-sum-of-distinct-squares.pas new file mode 100644 index 0000000000..7841c5478c --- /dev/null +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/PascalABC.NET/numbers-which-are-not-the-sum-of-distinct-squares.pas @@ -0,0 +1,37 @@ +function soms(n: integer; f: list): boolean; +begin + if (n <= 0) then result := false + else + if n in f then result := true + else + case n.CompareTo(f.Sum) of + 1: result := false; + 0: result := true; + else + var rf := f[::-1].Skip(1).ToList; + result := soms(n - f.Last, rf) or soms(n, rf); + end; +end; + +begin + var i := 1; + var g := 1; + var s := new List; + var a := new List; + + repeat + if i.Sqrt.Floor.Sqr = i then s.Add(i); + if not soms(i, s) then + begin + g := i; + a.Add(g) + end; + i += 1; + until g < (i shr 1); + + println('Numbers which are not the sum of distinct squares:'); + a.println; + println; + println('Stopped checking after finding', i - g, 'sequential non-gaps after the final gap of', g); + println('Found', a.count, 'total.'); +end. diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Python/numbers-which-are-not-the-sum-of-distinct-squares.py b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Python/numbers-which-are-not-the-sum-of-distinct-squares.py new file mode 100644 index 0000000000..3802f1df42 --- /dev/null +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/Python/numbers-which-are-not-the-sum-of-distinct-squares.py @@ -0,0 +1,58 @@ +import math + + +def soms(n: int, f: list[int]): + if n <= 0: + return False + + if n in f: + return True + + sumation = sum(f) + + if n > sumation: + return False + + if n == sumation: + return True + + rf = f.copy() + i, j = 0, len(rf) - 1 + + while i < j: + rf[i], rf[j] = rf[j], rf[i] + i += 1 + j -= 1 + + rf = rf[1:] + return soms(n - f[len(f) - 1], rf) or soms(n, rf) + + +def main(): + s = [] + a = [] + + sf = "\nStopped checking after finding %d sequential non-gaps after the final gap of %d\n" + + i, g = 1, 1 + + while g >= (i >> 1): + r = int(math.sqrt(i)) + + if r * r == i: + s.append(i) + + if not soms(i, s): + g = i + a.append(g) + + i += 1 + + print("Numbers which are not the sum of distinct squares:") + print(a) + print(sf % (i - g, g), end="") + print("Found %d in total" % len(a)) + + +if __name__ == "__main__": + main() diff --git a/Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/PascalABC.NET/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.pas b/Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/PascalABC.NET/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.pas new file mode 100644 index 0000000000..6ae05f2f00 --- /dev/null +++ b/Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/PascalABC.NET/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.pas @@ -0,0 +1,28 @@ +function ProperDivisorsProduct(n: int64): int64; +begin + result := 1; + var d := 2; + repeat + if n mod d = 0 then + begin + result *= d; + var q := n div d; + if q <> d then result *= q; + end; + d += 1; + until d * d > n; +end; + +function a111398(): sequence of int64; +begin + foreach var n: int64 in 1.step do + if n * n * n = ProperDivisorsProduct(n) then yield n; +end; + +begin + foreach var n in a111398.Take(50) index i do + write(n:4, if (i + 1) mod 10 = 0 then #10 else ''); + writeln; + foreach var n in |500, 5000, 50000| do + writeln(n:5, ' ', a111398.ElementAt(n - 1)); +end. diff --git a/Task/Numbers-with-equal-rises-and-falls/PascalABC.NET/numbers-with-equal-rises-and-falls.pas b/Task/Numbers-with-equal-rises-and-falls/PascalABC.NET/numbers-with-equal-rises-and-falls.pas new file mode 100644 index 0000000000..ee7120586d --- /dev/null +++ b/Task/Numbers-with-equal-rises-and-falls/PascalABC.NET/numbers-with-equal-rises-and-falls.pas @@ -0,0 +1,17 @@ +function a296712(): sequence of integer; +begin + foreach var n in 1.step do + if n.ToString + .Pairwise((x, y) -> (if x > y then 1 else if x < y then -1 else 0)) + .Sum = 0 then + yield n; +end; + +begin + println('The first 200 numbers are:'); + a296712.Take(200).Print; + println; + println; + println('The 10,000,000th number is:'); + a296712.ElementAt(10_000_000 - 1).Println; +end. diff --git a/Task/Numeric-error-propagation/PascalABC.NET/numeric-error-propagation.pas b/Task/Numeric-error-propagation/PascalABC.NET/numeric-error-propagation.pas new file mode 100644 index 0000000000..60bc6aba5e --- /dev/null +++ b/Task/Numeric-error-propagation/PascalABC.NET/numeric-error-propagation.pas @@ -0,0 +1,64 @@ +type + Approx = record + private + value, sigma: real; + public + constructor(v, s: real); + begin + value := v; + sigma := s; + end; + + class function operator-(a: Approx) := new Approx(-a.value, a.sigma); + class function operator+(a: Approx) := a; + + class function operator+(a, b: Approx) := new Approx(a.value + b.value, (a.sigma.Sqr + b.sigma.Sqr).Sqrt); + class function operator+(a: Approx; b: real) := new Approx(a.value + b, a.sigma); + class function operator+(b: real; a: Approx) := a + b; + + class function operator-(a, b: Approx) := a + (-b); + class function operator-(a: Approx; b: real) := a + (-b); + class function operator-(b: real; a: Approx) := (-a) + b; + + class function operator*(a, b: Approx): Approx; + begin + var v := a.value * b.value; + Result := new Approx(v, v * ((a.sigma / a.value).Sqr + (b.sigma / b.value).Sqr).Sqrt) + end; + + class function operator*(a: Approx; b: real) := new Approx(a.value * b, abs(a.sigma * b)); + class function operator*(b: real; a: Approx) := a * b; + + class function operator/(a, b: Approx): Approx; + begin + var v := a.value / b.value; + Result := new Approx(v, v * ((a.sigma / a.value).Sqr + (b.sigma / b.value).Sqr).Sqrt); + end; + + class function operator/(a: Approx; b: real) := new Approx(a.value / b, abs(a.sigma * b)); + class function operator/(b: real; a: Approx) := a / b; + + class function operator**(a: Approx; b: real): Approx; + begin + var v := power(a.value, b); + Result := new Approx(v, abs(v * b * a.sigma / a.value)); + end; + + function ToString: string; override; + begin + Result := Format('{0} ± {1}', value, sigma); + end; + end; + +function Sqrt(Self: Approx): Approx; extensionmethod; +begin + result := Self ** 0.5; +end; + +begin + var x1 := new Approx(100, 1.1); + var y1 := new Approx(50, 1.2); + var x2 := new Approx(200, 2.2); + var y2 := new Approx(100, 2.3); + println(((x1 - x2) ** 2 + (y1 - y2) ** 2).Sqrt); +end. diff --git a/Task/Numerical-integration/PascalABC.NET/numerical-integration.pas b/Task/Numerical-integration/PascalABC.NET/numerical-integration.pas new file mode 100644 index 0000000000..2537966410 --- /dev/null +++ b/Task/Numerical-integration/PascalABC.NET/numerical-integration.pas @@ -0,0 +1,25 @@ +function integrate(a, b: real; n: integer; f: real-> real): real; +begin + var h := (b - a) / n; + var sum: array [0..4] of real; + for var i := 0 to n - 1 do + begin + var x := a + i * h; + sum[0] += f(x); + sum[1] += f(x + h / 2.0); + sum[2] += f(x + h); + sum[3] += (f(x) + f(x + h)) / 2.0; + sum[4] += (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0; + end; + var methods := |'LeftRect ', 'MidRect ', 'RightRect', 'Trapezium', 'Simpson '|.tolist; + for var i := 0 to 4 do + println(methods[i], ' = ', sum[i] * h); + println; +end; + +begin + integrate(0.0, 1.0, 100, x -> x * x * x); + integrate(1.0, 100.0, 1_000, x -> 1 / x); + integrate(0.0, 5000.0, 5_000_000, x -> x); + integrate(0.0, 6000.0, 6_000_000, x -> x); +end. diff --git a/Task/Odd-word-problem/PascalABC.NET/odd-word-problem.pas b/Task/Odd-word-problem/PascalABC.NET/odd-word-problem.pas new file mode 100644 index 0000000000..ff11f731ed --- /dev/null +++ b/Task/Odd-word-problem/PascalABC.NET/odd-word-problem.pas @@ -0,0 +1,33 @@ +var + alpha := ('a'..'z') + ('A'..'Z'); + +procedure reverseWord(var ch: char); +begin + var nextch := readChar(); + if nextch in alpha then reverseWord(nextch); + write(ch); + ch := nextch; +end; + +procedure normalWord(var ch: char); +begin + write(ch); + ch := readChar(); + if ch in alpha then normalWord(ch); +end; + +begin + var ch := readChar(); + + while ch <> '.' do + begin + normalWord(ch); + if ch <> '.' then + begin + write(ch); + ch := readChar(); + reverseWord(ch); + end; + end; + write(ch) +end. diff --git a/Task/Old-lady-swallowed-a-fly/Quackery/old-lady-swallowed-a-fly.quackery b/Task/Old-lady-swallowed-a-fly/Quackery/old-lady-swallowed-a-fly.quackery new file mode 100644 index 0000000000..241ec851f9 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Quackery/old-lady-swallowed-a-fly.quackery @@ -0,0 +1,32 @@ + [ [ table + [ say "fly" ] + [ say "spider" ] + [ say "bird" ] + [ say "cat" ] + [ say "dog" ] + [ say "goat" ] + [ say "cow" ] ] do ] is beast ( n --> ) + + [ [ table + [ say "I don't know why she swallowed a fly." ] + [ say "That wiggled and jiggled and tickled inside her." ] + [ say "How absurd to swallow a bird." ] + [ say "Imagine that, she swallowed a cat!" ] + [ say "What a hog to swallow a dog." ] + [ say "She just opened her throat and swallowed that goat." ] + [ say "I don't know how she swallowed a cow." ] ] do ] is observation ( n --> ) + + [ say "There was an old lady who swallowed a " dup beast + dup if [ cr dup observation ] + times + [ cr say "She swallowed the " i 1+ beast + say " to catch the " i beast ] + cr 0 observation + cr say "Perhaps she'll die." ] is verse ( n --> ) + + [ say "There was an old lady who swallowed a horse." + cr say "She's dead, of course." ] is coda ( --> ) + + [ 7 times [ i^ verse cr cr ] coda ] is song ( --> ) + + song diff --git a/Task/Old-lady-swallowed-a-fly/SETL/old-lady-swallowed-a-fly.setl b/Task/Old-lady-swallowed-a-fly/SETL/old-lady-swallowed-a-fly.setl new file mode 100644 index 0000000000..c98b271fea --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/SETL/old-lady-swallowed-a-fly.setl @@ -0,0 +1,26 @@ +program old_lady; + animals := ["fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"]; + verses := [ + "I don't know why she swallowed that fly.\nPerhaps she'll die.\n", + "That wiggled and jiggled and tickled inside her!", + "How absurd to swallow a bird", + "Imagine that, she swallowed a cat", + "What a hog to swallow a dog", + "She just opened her throat and swallowed that goat", + "I don't know how she swallowed that cow", + "She's dead, of course." + ]; + + loop for i in [1..8] do + print("There was an old lady who swallowed a " + animals(i)); + print(verses(i)); + if i=8 then quit; end if; + loop for j in [i, i-1..2] do + print("She swallowed the " + animals(j) + + " to catch the " + animals(j-1)); + if j < 4 then + print(verses(j-1)); + end if; + end loop; + end loop; +end program; diff --git a/Task/One-dimensional-cellular-automata/PascalABC.NET/one-dimensional-cellular-automata.pas b/Task/One-dimensional-cellular-automata/PascalABC.NET/one-dimensional-cellular-automata.pas new file mode 100644 index 0000000000..2559c48baf --- /dev/null +++ b/Task/One-dimensional-cellular-automata/PascalABC.NET/one-dimensional-cellular-automata.pas @@ -0,0 +1,8 @@ +## +var gen := '_###_##_#_#_#_#__#__'.Select(ch -> (if ch = '#' then 1 else 0)).ToList; +loop 10 do +begin + gen.Select(n -> (if n = 1 then '#' else '_')).println; + gen := (0 + gen + 0).ToList; + gen := (1..gen.Count - 2).Select(m -> (if gen[m - 1:m + 2].Sum = 2 then 1 else 0)).ToList; +end; diff --git a/Task/One-of-n-lines-in-a-file/PascalABC.NET/one-of-n-lines-in-a-file.pas b/Task/One-of-n-lines-in-a-file/PascalABC.NET/one-of-n-lines-in-a-file.pas new file mode 100644 index 0000000000..c0ca6221be --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/PascalABC.NET/one-of-n-lines-in-a-file.pas @@ -0,0 +1,18 @@ +## +function oneOfN(n: integer): integer; +begin + result := 0; + for var x := 0 to n-1 do + if random(x+1) = 0 then + result := x; +end; + +function oneOfNTest(n: integer := 10; trials: integer := 1_000_000): array of integer; +begin + result := new integer[n]; + if n >= 0 then + foreach var i in 1..trials do + result[oneOfN(n)] += 1; +end; + +oneOfNTest.println; diff --git a/Task/OpenWebNet-password/PascalABC.NET/openwebnet-password.pas b/Task/OpenWebNet-password/PascalABC.NET/openwebnet-password.pas new file mode 100644 index 0000000000..c851d1aa63 --- /dev/null +++ b/Task/OpenWebNet-password/PascalABC.NET/openwebnet-password.pas @@ -0,0 +1,47 @@ +const + INT_BITS = 32; + +function rotateLeft(n, d: longword) := (n shl d) or (n shr (INT_BITS - d)); + +function rotateRight(n, d: longword) := (n shr d) or (n shl (INT_BITS - d)); + +function ownCalcPass(password, nonce: string): longword; +begin + var start := true; + + foreach var c in nonce do + begin + if (c <> '0') and start then + begin + result := password.tointeger; + start := false; + end; + case c of + '0': ; + '1': result := rotateRight(result, 7); + '2': result := rotateRight(result, 4); + '3': result := rotateRight(result, 3); + '4': result := rotateLeft(result, 1); + '5': result := rotateLeft(result, 5); + '6': result := rotateLeft(result, 12); + '7': result := (result and $0000FF00) or result shl 24 + or (result and $00FF0000) shr 16 or (result and $FF000000) shr 8; + '8': result := result shl 16 or result shr 24 or (result and $00FF0000) shr 8; + '9': result := not result; + else raise new Exception('non-digit in nonce.'); + end; + end; +end; + +procedure testPasswordCalc(password, nonce: string; expected: longword); +begin + var res := ownCalcPass(password, nonce); + print(if res = expected then 'PASS ' else 'FAIL '); + println(password, nonce, res, expected); +end; + +begin + testPasswordCalc('12345', '603356072', 25280520); + testPasswordCalc('12345', '410501656', 119537670); + testPasswordCalc('12345', '630292165', 4269684735); +end. diff --git a/Task/Operator-precedence/PascalABC.NET/operator-precedence.pas b/Task/Operator-precedence/PascalABC.NET/operator-precedence.pas new file mode 100644 index 0000000000..a06d8ffd7a --- /dev/null +++ b/Task/Operator-precedence/PascalABC.NET/operator-precedence.pas @@ -0,0 +1,11 @@ +Table of operations priorities: + +** 1 (highest) +@, not, L , +, - (unary), new 2 +*, /, div, mod, and, shl, shr, as, is 3 ++, - (binary), or, xor 4 +.. 5 += , <> , < , > , <=, >=, in 6 +?: 7 (lowest) + +Brackets are used to change the order of operations in expressions. diff --git a/Task/Order-two-numerical-lists/PascalABC.NET/order-two-numerical-lists.pas b/Task/Order-two-numerical-lists/PascalABC.NET/order-two-numerical-lists.pas new file mode 100644 index 0000000000..2edd125b7d --- /dev/null +++ b/Task/Order-two-numerical-lists/PascalABC.NET/order-two-numerical-lists.pas @@ -0,0 +1,15 @@ +## +function operator <(a, b: List): boolean; +extensionmethod; where T: IComparable; +begin + foreach var (x, y) in Zip(a, b) do + begin + if x = y then continue; + result := x.CompareTo(y) < 0; + exit; + end; + result := a.Count < b.Count; +end; + +println(Lst(1, 2, 1, 3, 2) < Lst(1, 2, 0, 4, 4, 0, 0, 0)); +println(Lst(1, 2, 0, 4, 4, 0, 0, 0) < Lst(1, 2, 1, 3, 2)); diff --git a/Task/Ordered-words/Free-Pascal-Lazarus/ordered-words.pas b/Task/Ordered-words/Free-Pascal-Lazarus/ordered-words.pas new file mode 100644 index 0000000000..776e952f6c --- /dev/null +++ b/Task/Ordered-words/Free-Pascal-Lazarus/ordered-words.pas @@ -0,0 +1,54 @@ +Program Ordered_Words; +{$mode ObjFPC}{$H+} + +Uses +Classes; + +Const + FILENAME = 'unixdict.txt'; + +Function IsOrdered(Const S: String): boolean; + +Var + I, Len: integer; +Begin + Len := Length(S); + If Len < 2 Then + Exit(True); + For I := 2 To Len Do + If S[I] < S[I - 1] Then + Exit(False); + Result := True; +End; + +Var + WordList, OrderedWords: TStringList; + CurrentWord: string; + CurrentLength, LongestLength: integer; + +Begin + LongestLength := 0; + WordList := TStringList.Create; + OrderedWords := TStringList.Create; + + WordList.LoadFromFile(FILENAME); + For CurrentWord In WordList Do + Begin + CurrentLength := Length(CurrentWord); + If CurrentLength >= LongestLength Then + If IsOrdered(CurrentWord) Then + If CurrentLength > LongestLength Then + Begin + LongestLength := CurrentLength; + OrderedWords.Clear; + OrderedWords.Add(CurrentWord); + End + Else If CurrentLength = LongestLength Then + OrderedWords.Add(CurrentWord); + End; + For CurrentWord In OrderedWords Do + WriteLn(CurrentWord); + + WordList.Free; + OrderedWords.Free; +End. diff --git a/Task/Ordered-words/M2000-Interpreter/ordered-words.m2000 b/Task/Ordered-words/M2000-Interpreter/ordered-words.m2000 new file mode 100644 index 0000000000..a44766a0af --- /dev/null +++ b/Task/Ordered-words/M2000-Interpreter/ordered-words.m2000 @@ -0,0 +1,38 @@ +module Ordered_Words { + orderword=lambda ->{ + buffer a as integer*30 + =lambda a (s as string) -> { + if len(s)*2>len(a) then buffer a as integer*len(s) + return a, 0:=s + if len(s)=1 then =true: exit + for i=1 to len(s)-1 + if a[i-1]>a[i] then break + next i + =true + } + }() + max=2 + res=stack + document a$ + load.doc a$, "unixdict.txt" + k=doc.par(a$) + i=0 + m=Paragraph(a$, 0) + if forward(a$, m) then + while m + i++ + if i mod 20=1 then Print Over round(i/k*100,2);"%" : refresh + word=paragraph$(a$, (m)) + if orderword(word) then + if max; +begin + assert(k >= 2); + result := if n = 2 then Lst(1, 1, 1) else rn(n - 1, n + 1); + while result.Count <> k do + result.Add(result[^(n + 1):^1].Sum); +end; + +for var n := 2 to 8 do + println(n, ': ', rn(n, 15)); diff --git a/Task/Padovan-sequence/PascalABC.NET/padovan-sequence.pas b/Task/Padovan-sequence/PascalABC.NET/padovan-sequence.pas new file mode 100644 index 0000000000..41650536d6 --- /dev/null +++ b/Task/Padovan-sequence/PascalABC.NET/padovan-sequence.pas @@ -0,0 +1,71 @@ +const + PP = 1.324717957244746025960908854; + S = 1.0453567932525329623; + +var + Rules := dict(('A', string('B')), ('B', string('C')), ('C', 'AB')); + +function padovan1(n: integer): sequence of integer; +begin + // ## Yield the first 'n' Padovan values using recurrence relation. + loop min(n, 3) do yield 1; + var (a, b, c) := (1, 1, 1); + var count := 3; + while count < n do + begin + (a, b, c) := (b, c, a + b); + yield c; + count += 1; + end; +end; + +function padovan2(n: integer): sequence of integer; +begin + // ## Yield the first 'n' Padovan values using formula. + if n > 1 then yield 1; + var p := 1.0; + var count := 1; + while count < n do + begin + yield (p / S).Round; + p *= PP; + count += 1; + end; +end; + +function padovan3(n: integer): sequence of string; +begin + // ## Yield the strings produced by the L-system. + var s: string := 'A'; + var count := 0; + while count < n do + begin + yield s; + var next := string(''); + foreach var ch in s do + next += Rules[ch]; + s := next; + count += 1; + end; +end; + +begin + println('First 20 terms of the Padovan sequence:'); + println(padovan1(20)); + + var list1 := padovan1(64).ToList; + var list2 := padovan2(64).ToList; + println('The first 64 iterative and calculated values', + if list1.SequenceEqual(list2) then 'are the same.' else 'differ.'); + + println; + println('First 10 L-system strings:'); + println(padovan3(10)); + println; + println('Lengths of the 32 first L-system strings:'); + var list3 := padovan3(32).select(it -> it.Length).ToList; + list3.println; + writeln('These lengths are ', + if list3.SequenceEqual(list1[0:32]) then '' else 'not ', + 'the 32 first terms of the Padovan sequence.'); +end. diff --git a/Task/Palindrome-dates/PascalABC.NET/palindrome-dates.pas b/Task/Palindrome-dates/PascalABC.NET/palindrome-dates.pas new file mode 100644 index 0000000000..85480628cb --- /dev/null +++ b/Task/Palindrome-dates/PascalABC.NET/palindrome-dates.pas @@ -0,0 +1,23 @@ +uses system; + +function Reverse(x: integer) := x mod 10 * 10 + x div 10; + +function IsValidDate(y, m, d: integer; var date: datetime) := + DateTime.TryParse(y.tostring + '-' + m.tostring + '-' + d.tostring, date); + +function PalindromicDates(startYear: integer): sequence of datetime; +begin + var y := startyear; + repeat + var m := Reverse(y mod 100); + var d := Reverse(y div 100); + var date: datetime; + if (IsValidDate(y, m, d, date)) then yield date; + y += 1; + until false; +end; + +begin + foreach var date in PalindromicDates(2021).Take(15) do + Writeln(date.ToString('yyyy-MM-dd')); +end. diff --git a/Task/Palindrome-detection/EasyLang/palindrome-detection.easy b/Task/Palindrome-detection/EasyLang/palindrome-detection.easy index 5a80f5f29d..fa6af77dde 100644 --- a/Task/Palindrome-detection/EasyLang/palindrome-detection.easy +++ b/Task/Palindrome-detection/EasyLang/palindrome-detection.easy @@ -3,7 +3,7 @@ func$ reverse s$ . for i = 1 to len a$[] div 2 swap a$[i] a$[len a$[] - i + 1] . - return strjoin a$[] + return strjoin a$[] "" . func palin s$ . if s$ = reverse s$ diff --git a/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf b/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf index 64bf7cf402..58cdea2875 100644 --- a/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf +++ b/Task/Palindrome-detection/Golfscript/palindrome-detection-2.golf @@ -1,4 +1,3 @@ -"ABBA" pal -"a" pal -"13231+464+989=989+464+13231" pal -"123 456 789 897 654 321" pal +["ABBA" "a" +"13231+464+989=989+464+13231" +"123 456 789 897 654 321"]{pal puts}/ diff --git a/Task/Palindrome-detection/Idris/palindrome-detection-1.idris b/Task/Palindrome-detection/Idris/palindrome-detection-1.idris new file mode 100644 index 0000000000..3dbcc99256 --- /dev/null +++ b/Task/Palindrome-detection/Idris/palindrome-detection-1.idris @@ -0,0 +1,30 @@ +module Palindromes + +import Data.Primitives.Views +import Data.List +import Data.List.Views +import Data.Nat + +isPalindromeReverse : String -> Bool +isPalindromeReverse str = let cs = unpack str in cs == reverse cs + +isPalindromeReverseHalf : String -> Bool +isPalindromeReverseHalf str = + let cs = (unpack str) + n = (length str) `div` 2 + in take n cs == (take n $ reverse cs) + +isPalindromeSplit : String -> Bool +isPalindromeSplit str = + let cs = unpack str + n = length cs `div` 2 + (left, right) = bimap id reverse $ splitAt n cs + in all (uncurry (==)) $ zip left right + +isPalindromeSnoc : String -> Bool +isPalindromeSnoc str = + let cs = unpack str in go cs + where go : Eq a => List a -> Bool + go xs with (snocList xs) + go (x :: ys ++ [z]) | Snoc z (x::ys) _ = x == z && go ys + go _ | _ = True diff --git a/Task/Palindrome-detection/Idris/palindrome-detection-2.idris b/Task/Palindrome-detection/Idris/palindrome-detection-2.idris new file mode 100644 index 0000000000..734cb00569 --- /dev/null +++ b/Task/Palindrome-detection/Idris/palindrome-detection-2.idris @@ -0,0 +1,58 @@ +module PalindromesTypeLevel + +import Data.List +import Data.List.Views + + +isPalindromeDirect : (str : String) -> (str = reverse str) => Bool +isPalindromeDirect _ = True + +ipd = isPalindromeDirect "AABBAA" + +failing + ipdf = isPalindromeDirect "ABCCBB" + + +||| Proof that the list is constructed of consecutive pairs of equal elements. +||| Last element can be unpaired. +data EqualPairsInList : List a -> Type where + Nil : EqualPairsInList [] + Single : EqualPairsInList [x] + EqualPair : EqualPairsInList xs -> EqualPairsInList (x :: x :: xs) + +||| Reorders the list so that the first half is interleaved with a reversed second half. +interleaveOwnHalfReverse : List a -> List a +interleaveOwnHalfReverse [] = [] +interleaveOwnHalfReverse [x] = [x] +interleaveOwnHalfReverse (x :: y :: ys) = let (z, zs) = splitLast (y::ys) in x :: z :: interleaveOwnHalfReverse zs + where splitLast : (xs : List a) -> NonEmpty xs => (a, List a) + splitLast [x] = (x, []) + splitLast (x :: y :: ys) = let (z, zs) = splitLast (y::ys) in (z, x::zs) + +||| Precondition for checking if a list is a palindrome. +IsPalindrome : List a -> Type +IsPalindrome = EqualPairsInList . interleaveOwnHalfReverse + +||| Function for testing palindromes. Typechecks only when applied to a palindrome list. +isPalindrome : (xs : List a) -> IsPalindrome xs => Bool +isPalindrome _ = True + +||| Palindrome precondition specialized for strings. +IsPalindromeStr : String -> Type +IsPalindromeStr = IsPalindrome . unpack + +||| Function for testing string palindromes. Typechecks only when applied to a palindrome list. +isPalindromeStr : (str : String) -> IsPalindromeStr str => Bool +isPalindromeStr _ = True + + +-- Tests + +ip = isPalindrome [1, 4, 3, 1, 1, 3, 4, 1] +ips = isPalindromeStr "ABCDCBA" + +failing + ipf = isPalindrome [2, 2, 2, 3, 2, 2] + +failing + ipsf = isPalindromeStr "RBCDCBA" diff --git a/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys b/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys index dbf1adef7e..5faba4be6b 100644 --- a/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys +++ b/Task/Palindrome-detection/YAMLScript/palindrome-detection.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(n=31337): not =: when((n:S != n:S:reverse) ' not') diff --git a/Task/Palindromic-gapful-numbers/PascalABC.NET/palindromic-gapful-numbers.pas b/Task/Palindromic-gapful-numbers/PascalABC.NET/palindromic-gapful-numbers.pas new file mode 100644 index 0000000000..b172609d71 --- /dev/null +++ b/Task/Palindromic-gapful-numbers/PascalABC.NET/palindromic-gapful-numbers.pas @@ -0,0 +1,30 @@ +function pal_gen(): sequence of BigInteger; +begin + var o := 10; + var e := 10; + repeat + var fwd_o := o.ToString; + var fwd_e := e.ToString; + var rev_o := fwd_o[^2:0:-1]; + var rev_e := fwd_e[::-1]; + var pal := Min((fwd_o + rev_o).ToBigInteger, (fwd_e + rev_e).ToBigInteger); + yield pal; + if pal.ToString.Length.IsEven then e += 1 else o += 1; + until false; +end; + +function is_gapful(n: BigInteger) := n mod (n.ToString[1].ToDigit * 10 + (n mod 10)) = 0; + +begin + writeln('palindromic gapful numbers from 1 to 20:'); + for var i := 1 to 9 do + writeln(i, ': ', pal_gen.Where(n -> is_gapful(n)).Where(n -> n mod 10 = i).Take(20)); + writeln; + writeln('palindromic gapful numbers from 86 to 100:'); + for var i := 1 to 9 do + writeln(i, ': ', pal_gen.Where(n -> is_gapful(n)).Where(n -> n mod 10 = i).Skip(85).Take(15)); + writeln; + writeln('palindromic gapful numbers from 991 to 1000:'); + for var i := 1 to 9 do + writeln(i, ': ', pal_gen.Where(n -> is_gapful(n)).Where(n -> n mod 10 = i).Skip(990).Take(10)); +end. diff --git a/Task/Pancake-numbers/00-TASK.txt b/Task/Pancake-numbers/00-TASK.txt index 37e1a1ab7c..c1308a4030 100644 --- a/Task/Pancake-numbers/00-TASK.txt +++ b/Task/Pancake-numbers/00-TASK.txt @@ -13,4 +13,3 @@ Few people know p(20), generously I shall award an extra credit for anyone doing # [https://web.archive.org/web/20240525075316/https://www.bbvaopenmind.com/en/science/mathematics/bill-gates-and-the-pancake-problem/ Bill Gates and the pancake problem] # [https://oeis.org/A058986 A058986]

- diff --git a/Task/Pancake-numbers/ARM-Assembly/pancake-numbers.arm b/Task/Pancake-numbers/ARM-Assembly/pancake-numbers.arm new file mode 100644 index 0000000000..c05f240a1e --- /dev/null +++ b/Task/Pancake-numbers/ARM-Assembly/pancake-numbers.arm @@ -0,0 +1,393 @@ +/* ARM assembly Raspberry PI */ +/* program pancake number */ +/* */ + + /* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ +/* for constantes see task include a file in arm assembly */ +/************************************/ +/* Constantes */ +/************************************/ +.include "../constantes.inc" +.equ NBPANCAKEMAX, 30 +.equ NBQUEUEITEM, 5000000 +.equ NBVALUEMAX, 15 +.equ NUMPAN, 10 + +/************************************/ +/* Macros */ +/************************************/ +//.include "../../ficmacros32.inc" @ use for developper debugging + +/*******************************************/ +/* Structures */ +/********************************************/ + +/* structure pancake flip*/ + .struct 0 +Pan_left: @ next element left + .struct Pan_left + 4 +Pan_right: @ next element right + .struct Pan_right + 4 +Pan_value: @ + .struct Pan_value + NBVALUEMAX +Pan_flips: + .struct Pan_flips + 1 @ flips counter +Pan_end: +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessStart: .asciz "Program 32 bits start.\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessError: .asciz "ERROR array flips too small.\n" +szMessErrnotFind: .asciz "Address not find in area.\n" + +szCarriageReturn: .asciz "\n" +szMessResHead: .asciz "Pancake : @ " +szMessResLib: .asciz "Flips : @ example : " +sMessResult: .asciz " @," + +.align 4 + +QueuePancake: .skip 4 * NBQUEUEITEM +EndQueuePancake: +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sZoneConv: .skip 24 +iCptMax: .skip 4 +iAdddressMax: .skip 4 +Pancakes: .skip 4 * NBPANCAKEMAX +arrayFlips: .skip Pan_end * NBQUEUEITEM + +iQueueStart: .skip 4 @ queue start pointer +iQueueEnd: .skip 4 @ queue end pointer +areaFlipTemp: .skip 4+NBVALUEMAX + + +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + mov r4,#2 @ pancake number +1: + mov r0,r4 + bl pancakesNum + add r4,r4,#1 + cmp r4,#NUMPAN + ble 1b + + ldr r0,iAdrszMessFinOK + bl affichageMess +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 +iAdrsMessResult: .int sMessResult +iAdrszMessStart: .int szMessStart +iAdrszMessFinOK: .int szMessFinOK +/******************************************************************/ +/* pancake Number */ +/******************************************************************/ +/* r0 contains pancake number */ +pancakesNum: @ INFO: pancakesNum + push {r2-r4,lr} + mov r4,r0 + mov r1,#1 + ldr r2,iAdriCptMax + str r1,[r2] + mov r10,#1 @ max flips counter + ldr r0,iAdrQueuePancake + ldr r1,iAdriQueueStart + str r0,[r1] + ldr r1,iAdriQueueEnd + str r0,[r1] + ldr r11,iAdrarrayFlips @ flips array item 0 + ldr r0,iAdriAdddressMax + str r11,[r0] @ init with flips array item 0 + mov r3,#0 @ init pointer + str r3,[r11,#Pan_left] + str r3,[r11,#Pan_right] + strb r3,[r11,#Pan_flips] @ init counter flips + add r6,r11,#Pan_value + mov r1,#1 +1: @ init flips area with first combinaison + str r1,[r6,r3] + add r3,r3,#1 + add r1,r1,#1 + cmp r1,r4 + ble 1b + @ init queue + ldr r0,iAdrQueuePancake + str r11,[r0] @ init with first item + add r0,r0,#4 + ldr r1,iAdriQueueEnd + str r0,[r1] + mov r12,#1 @ indice flip area + +2: + ldr r1,iAdriQueueEnd + ldr r1,[r1] @ load end queue pointer + ldr r2,iAdriQueueStart + ldr r0,[r2] @ load start queue pointer + cmp r1,r0 @ end queue ? + beq 20f + ldr r5,[r0] @ load value to start pointer + add r0,r0,#4 @ new start queue pointer + str r0,[r2] @ and store + + + add r0,r5,#Pan_flips + ldrb r9,[r0] + add r9,r9,#1 @ flip + 1 + mov r8,#1 @ poste 1 +5: @ start loop + mov r0,r5 @ address pancake area + + mov r1,#0 + mov r2,r4 + mov r3,r8 + bl flip + cmp r0,#-1 + beq 99f + mov r7,r0 @ flipped + + mov r1,r11 @ area pancake address + mov r2,r4 + mov r3,r12 + bl searchArea + cmp r0,#-1 + beq 10f @ find -> next loop + mov r3,#Pan_end + mul r6,r3,r12 + add r6,r6,r11 + cmp r0,#0 + streq r6,[r1,#Pan_left] + strne r6,[r1,#Pan_right] + strb r9,[r6,#Pan_flips] + + add r3,r6,#Pan_value + ldr r2,iAdrareaFlipTemp + add r2,r2,#Pan_value + mov r0,#0 + str r0,[r6,#Pan_left] + str r0,[r6,#Pan_right] + 6: + ldrb r1,[r2,r0] + strb r1,[r3,r0] + add r0,r0,#1 + cmp r0,r4 + blt 6b + + add r12,r12,#1 @ + ldr r0,iMaxItem + cmp r12,r0 + bge 99f + ldr r0,iAdriQueueEnd + ldr r1,[r0] @ load end queue pointer + str r6,[r1] @ add fliped in queue + add r1,r1,#4 + ldr r2,iAdrEndQueuePancake + ldr r2,[r2] + cmp r1,r2 @ maxi ? + bge 99f + + str r1,[r0] @ store next end queue pointer + cmp r9,r10 + ble 10f + mov r10,r9 + ldr r0,iAdriAdddressMax + str r7,[r0] +10: @ loops + + add r8,r8,#1 + cmp r8,r4 + blt 5b + b 2b +20: + mov r0,r4 + ldr r1,iAdrsZoneConv + bl conversion10 @ décimal conversion + add r1,r1,r0 + mov r0,#0 + strb r0,[r1] + ldr r0,iAdrszMessResHead + ldr r1,iAdrsZoneConv @ insert conversion + bl strInsertAtCharInc + bl affichageMess + mov r0,r10 + ldr r1,iAdrsZoneConv + bl conversion10 @ décimal conversion + add r1,r1,r0 + mov r0,#0 + strb r0,[r1] + ldr r0,iAdrszMessResLib + ldr r1,iAdrsZoneConv @ insert conversion + bl strInsertAtCharInc + bl affichageMess + + ldr r1,iAdriAdddressMax + ldr r0,[r1] + mov r1,r4 + bl displayTable + b 100f +98: + affregtit erreur + ldr r0,iAdrszMessErrnotFind + bl affichageMess + mov r0,#-1 +99: + ldr r0,iAdrszMessError + bl affichageMess + mov r0,#-1 +100: + pop {r2-r4,pc} +iAdrPancakes: .int Pancakes +iAdrQueuePancake: .int QueuePancake +iAdriQueueStart: .int iQueueStart +iAdriQueueEnd: .int iQueueEnd +iAdrEndQueuePancake: .int EndQueuePancake +iAdrarrayFlips: .int arrayFlips + +iAdrszMessError: .int szMessError +iAdriCptMax: .int iCptMax +iAdriAdddressMax: .int iAdddressMax +iAdrszMessErrnotFind: .int szMessErrnotFind +iAdrszMessResHead: .int szMessResHead +iAdrszMessResLib: .int szMessResLib +iMaxItem: .int NBQUEUEITEM +/******************************************************************/ +/* flip */ +/******************************************************************/ +/* r0 contains the address of table */ +/* r1 contains first start index +/* r2 contains the number of elements */ +/* r3 contains the position of flip */ +flip: @ INFO: flip + push {r1-r8,lr} @ save registers + mov r5,r0 + ldr r8,iAdrareaFlipTemp + mov r4,#Pan_value + mov r0,#0 + add r7,r8,#Pan_value + add r4,r4,r5 +1: @ copy area loop + + ldrb r6,[r4,r0] + strb r6,[r7,r0] + add r0,r0,#1 + cmp r0,r2 + blt 1b @ loop + + mov r0,r7 + cmp r3,r2 + subge r3,r2,#1 @ last index if position >= size +2: + cmp r1,r3 + bge 3f + ldrb r5,[r0,r1] @ load value first index + ldrb r6,[r0,r3] @ load value position index + strb r6,[r0,r1] @ inversion + strb r5,[r0,r3] @ + sub r3,r3,#1 + add r1,r1,#1 + b 2b +3: + mov r0,r8 @ return flip area temp +100: + pop {r1-r8,pc} +iAdrareaFlipTemp: .int areaFlipTemp +/******************************************************************/ +/* search area in table area */ +/******************************************************************/ +/* r0 contains the address area to search */ +/* r1 contains address area address +/* r2 nombre elements */ +/* r3 nombre address area */ +/* r0 return -1 if find, 0 if pointer left, 1 if pointer right */ +/* r1 return address item */ +searchArea : + push {r4-r11,lr} @ save registers + mov r7,#0 + mov r9,#Pan_end + add r10,r0,#Pan_value + mov r6,r1 +1: @ loop begin + mov r8,#0 @ indice value array + add r5,r6,#Pan_value @ load value address +2: + ldrb r4,[r10,r8] @ load one value to search + ldrb r11,[r5,r8] @ load one value to tree + add r8,r8,#1 + cmp r4,r11 @ compare value + blt 3f @ smaller + bgt 4f @ highter + cmp r8,r2 @ end value ? + blt 2b @ no -> loop + mov r0,#-1 @ equal return -1 + b 100f +3: @ smaller + ldr r4,[r6,#Pan_left] @ load left pointer + cmp r4,#0 @ end ? + movne r6,r4 + bne 1b @ loop + mov r1,r6 @ last pointer address + mov r0,#0 @ not find pointer left + b 100f +4: @ highter + ldr r4,[r6,#Pan_right] @ load right pointer + cmp r4,#0 + movne r6,r4 + bne 1b + mov r1,r6 @ last pointer address + mov r0,#1 @ not find pointer right +100: + pop {r4-r11,pc} + + +/******************************************************************/ +/* Display table elements */ +/******************************************************************/ +/* r0 contains the address of table */ +/* r1 contains elements number */ +displayTable: @ INFO: displayTable + push {r0-r3,lr} @ save registers + mov r4,r1 + add r2,r0,#Pan_value + mov r3,#0 +1: @ loop display table + ldrb r0,[r2,r3] + ldr r1,iAdrsZoneConv + bl conversion10 @ décimal conversion + add r1,r1,r0 + mov r0,#0 + strb r0,[r1] + ldr r0,iAdrsMessResult + ldr r1,iAdrsZoneConv @ insert conversion + bl strInsertAtCharInc + bl affichageMess @ display message + add r3,#1 + cmp r3,r4 + blt 1b + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r0,r2 +100: + pop {r0-r3,lr} + bx lr +iAdrsZoneConv: .int sZoneConv + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Pancake-numbers/C++/pancake-numbers.cpp b/Task/Pancake-numbers/C++/pancake-numbers.cpp index 70a3d06253..e7c8202a2e 100644 --- a/Task/Pancake-numbers/C++/pancake-numbers.cpp +++ b/Task/Pancake-numbers/C++/pancake-numbers.cpp @@ -1,52 +1,49 @@ -#include -#include #include -#include -#include -#include +#include #include +#include +#include +#include +#include +#include -std::vector flip_stack(std::vector& stack, const int32_t index) { - reverse(stack.begin(), stack.begin() + index); +std::vector flip_stack(std::vector stack, const uint32_t& index) { + std::reverse(stack.begin(), stack.begin() + index); return stack; } -std::pair, int32_t> pancake(const int32_t number) { - std::vector initial_stack(number); +std::pair, uint32_t> pancake(const uint32_t& number) { + std::vector initial_stack(number); std::iota(initial_stack.begin(), initial_stack.end(), 1); - std::map, int32_t> stack_flips = { std::make_pair(initial_stack, 1) }; - std::queue> queue; + std::map, uint32_t> stack_flips = { std::make_pair(initial_stack, 0) }; + std::queue> queue; queue.push(initial_stack); while ( ! queue.empty() ) { - std::vector stack = queue.front(); + std::vector stack = queue.front(); queue.pop(); - const int32_t flips = stack_flips[stack] + 1; - for ( int i = 2; i <= number; ++i ) { - std::vector flipped = flip_stack(stack, i); - if ( stack_flips.find(flipped) == stack_flips.end() ) { + const uint32_t flips = stack_flips[stack] + 1; + for ( uint32_t i = 2; i <= number; ++i ) { + std::vector flipped = flip_stack(stack, i); + if ( ! stack_flips.contains(flipped) ) { stack_flips[flipped] = flips; queue.push(flipped); } } } - auto ptr = std::max_element( - stack_flips.begin(), stack_flips.end(), - [] ( const auto & pair1, const auto & pair2 ) { - return pair1.second < pair2.second; - } - ); + const auto ptr = std::max_element(stack_flips.begin(), stack_flips.end(), + [](const auto& pair1, const auto& pair2){ return pair1.second < pair2.second; }); return std::make_pair(ptr->first, ptr->second); } int main() { - for ( int32_t n = 1; n <= 9; ++n ) { - std::pair, int32_t> result = pancake(n); + for ( uint32_t n = 1; n <= 9; ++n ) { + std::pair, uint32_t> result = pancake(n); std::cout << "pancake(" << n << ") = " << std::setw(2) << result.second << ". Example ["; - for ( uint64_t i = 0; i < result.first.size() - 1; ++i ) { + for ( uint32_t i = 0; i < result.first.size() - 1; ++i ) { std::cout << result.first[i] << ", "; } std::cout << result.first.back() << "]" << std::endl; diff --git a/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic b/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic index fccbd46483..7b45c49976 100644 --- a/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic +++ b/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic @@ -1,23 +1,37 @@ -Dim As Integer num_pancakes = 20 -Dim As Integer i, j, c = 0, n - Function pancake(n As Integer) As Integer - Dim As Integer gap = 2, sum = 2, adj = -1 - While sum < n + Dim As Integer gap, pg, gapsum, adj, temp + + gap = 2 + pg = 1 + gapsum = gap + adj = -1 + While gapsum < n adj += 1 - gap = (gap * 2) - 1 - sum += gap + temp = gap + gap += pg + pg = temp + gapsum += gap Wend + Return n + adj End Function -For i = 0 To 3 - For j = 1 To 5 - n = (i * 5) + j - c += 1 - Print Using "p(##) = ## "; n; pancake(n); - If c Mod 5 = 0 Then Print - Next j +' Main program +Dim As Integer numbers(1 To 20), results(1 To 20) +Dim As Integer i, row, col, idx + +' Generate sequence 1 to 20 +For i = 1 To 20 + numbers(i) = i + results(i) = pancake(i) Next i +For row = 0 To 3 + For col = 1 To 5 + idx = row * 5 + col + Print Using "p(##) = ## "; numbers(idx); results(idx); + Next col + Print +Next row + Sleep diff --git a/Task/Pancake-numbers/Gambas/pancake-numbers.gambas b/Task/Pancake-numbers/Gambas/pancake-numbers.gambas index 5056e83a0c..042c109d2d 100644 --- a/Task/Pancake-numbers/Gambas/pancake-numbers.gambas +++ b/Task/Pancake-numbers/Gambas/pancake-numbers.gambas @@ -1,27 +1,43 @@ +Public numbers[20] As Integer +Public results[20] As Integer + Public Sub Main() - Dim i As Integer, j As Integer, c As Integer = 0, n As Integer + Dim i As Integer, row As Integer, col As Integer, idx As Integer - For i = 0 To 3 - For j = 1 To 5 - n = (i * 5) + j - c += 1 - Print "p("; Format$(n, "##"); ") = "; Format$(pancake(n), "##"); " "; - If c Mod 5 = 0 Then Print + ' Generate sequence 1 to 20 + For i = 0 To 19 + numbers[i] = i + 1 + results[i] = pancake(i + 1) + Next + + For row = 0 To 3 + For col = 0 To + idx = row * 5 + col + Print "p("; Format$(numbers[idx], "##"); ") = "; Format$(results[idx], "##"); " "; Next + Print Next End Function pancake(n As Integer) As Integer - Dim gap As Integer = 2, sum As Integer = 2, adj As Integer = -1 + Dim gap As Integer, pg As Integer, gapsum As Integer, adj As Integer, tmp As Integer - While sum < n + gap = 2 + pg = 1 + gapsum = gap + adj = -1 + + While gapsum < n adj += 1 - gap = (gap * 2) - 1 - sum += gap + tmp = gap + gap += pg + pg = tmp + gapsum += gap Wend + Return n + adj End Function diff --git a/Task/Pancake-numbers/Java/pancake-numbers-1.java b/Task/Pancake-numbers/Java/pancake-numbers-1.java index 126c595da8..a061523e2b 100644 --- a/Task/Pancake-numbers/Java/pancake-numbers-1.java +++ b/Task/Pancake-numbers/Java/pancake-numbers-1.java @@ -1,23 +1,31 @@ -public class Pancake { - private static int pancake(int n) { - int gap = 2; - int sum = 2; - int adj = -1; - while (sum < n) { - adj++; - gap = 2 * gap - 1; - sum += gap; - } - return n + adj; - } - - public static void main(String[] args) { - for (int i = 0; i < 4; i++) { - for (int j = 1; j < 6; j++) { - int n = 5 * i + j; - System.out.printf("p(%2d) = %2d ", n, pancake(n)); +public final class PancakeNumbersApproximation { + + public static void main(String[] args) { + for ( int i = 0; i < 4; i++ ) { + for ( int j = 1; j < 6; j++ ) { + final int n = 5 * i + j; + System.out.print(String.format("%s%2d%s%d%s", "p(", n, ") = ", pancake(n), "\t")); } System.out.println(); } } + + private static int pancake(int number) { + int gap = 2; + int previousGap = 1; + int sumGaps = gap; + int adjustment = -1; + + while ( sumGaps < number ) { + adjustment += 1; + final int previousGapCopy = previousGap; + previousGap = gap; + gap += previousGapCopy; + sumGaps += gap; + } + + number += adjustment; + return number; + } + } diff --git a/Task/Pancake-numbers/Java/pancake-numbers-2.java b/Task/Pancake-numbers/Java/pancake-numbers-2.java index 7c5fc884aa..87518ae864 100644 --- a/Task/Pancake-numbers/Java/pancake-numbers-2.java +++ b/Task/Pancake-numbers/Java/pancake-numbers-2.java @@ -1,47 +1,53 @@ -import static java.util.Comparator.comparing; -import static java.util.stream.Collectors.toList; - import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; +import java.util.stream.Collectors; import java.util.stream.IntStream; +public final class PancakeNumbers { -public class Pancake { + public static void main(String[] args) { + for ( int n = 1; n <= 9; n++ ) { + PancakeInfo result = pancake(n); + System.out.println(String.format("%s%2d%s", "Pancake(", result.index, "). Example " + result.pancake)); + } + } + + private static PancakeInfo pancake(int number) { + List initialStack = IntStream.rangeClosed(1, number).boxed().collect(Collectors.toList()); + Map, Integer> stackFlips = new HashMap, Integer>(); + stackFlips.put(initialStack, 0); + Queue> queue = new ArrayDeque>(); + queue.add(initialStack); + + while ( ! queue.isEmpty() ) { + List stack = queue.remove(); - private static List flipStack(List stack, int spatula) { - List copy = new ArrayList<>(stack); - Collections.reverse(copy.subList(0, spatula)); + final int flipCount = stackFlips.get(stack) + 1; + for ( int i = 2; i <= number; i++ ) { + List flipped = flipStack(stack, i); + if ( stackFlips.putIfAbsent(flipped, flipCount) == null ) { + queue.add(flipped); + } + } + } + + Map.Entry, Integer> entry = + stackFlips.entrySet().stream().max(Comparator.comparing( e -> e.getValue() )).get(); + return new PancakeInfo(entry.getKey(), entry.getValue()); + } + + private static List flipStack(List stack, int index) { + List copy = new ArrayList(stack); + Collections.reverse(copy.subList(0, index)); return copy; } + + private static record PancakeInfo(List pancake, int index) {} - private static Map.Entry, Integer> pancake(int n) { - List initialStack = IntStream.rangeClosed(1, n).boxed().collect(toList()); - Map, Integer> stackFlips = new HashMap<>(); - stackFlips.put(initialStack, 1); - Queue> queue = new ArrayDeque<>(); - queue.add(initialStack); - while (!queue.isEmpty()) { - List stack = queue.remove(); - int flips = stackFlips.get(stack) + 1; - for (int i = 2; i <= n; ++i) { - List flipped = flipStack(stack, i); - if (stackFlips.putIfAbsent(flipped, flips) == null) { - queue.add(flipped); - } - } - } - return stackFlips.entrySet().stream().max(comparing(e -> e.getValue())).get(); - } - - public static void main(String[] args) { - for (int i = 1; i <= 10; ++i) { - Map.Entry, Integer> result = pancake(i); - System.out.printf("pancake(%s) = %s. Example: %s\n", i, result.getValue(), result.getKey()); - } - } } diff --git a/Task/Pancake-numbers/Scala/pancake-numbers.scala b/Task/Pancake-numbers/Scala/pancake-numbers-1.scala similarity index 100% rename from Task/Pancake-numbers/Scala/pancake-numbers.scala rename to Task/Pancake-numbers/Scala/pancake-numbers-1.scala diff --git a/Task/Pancake-numbers/Scala/pancake-numbers-2.scala b/Task/Pancake-numbers/Scala/pancake-numbers-2.scala new file mode 100644 index 0000000000..349ada38f3 --- /dev/null +++ b/Task/Pancake-numbers/Scala/pancake-numbers-2.scala @@ -0,0 +1,29 @@ +object PancakeNumbers extends App: + + private def pancake(n: Int): Int = + var gap = 2 + var sum = 2 + var adj = -1 + + while (sum < n) { + adj += 1 + gap = gap * 2 - 1 + sum += gap + } + + n + adj + + private def formatPancakeNumbers(maxN: Int, perRow: Int): List[String] = + (1 to maxN).toList + .grouped(perRow) + .map { group => + group.map(n => f"p($n%2d) = ${pancake(n)}%2d").mkString(" ") + } + .toList + + private def runPancakeNumbers(): Unit = + val maxN = 20 + val formattedOutput = formatPancakeNumbers(maxN, perRow = 5) + formattedOutput.foreach(println) + + runPancakeNumbers() diff --git a/Task/Parallel-calculations/Scala/parallel-calculations.scala b/Task/Parallel-calculations/Scala/parallel-calculations.scala new file mode 100644 index 0000000000..45f3446d7b --- /dev/null +++ b/Task/Parallel-calculations/Scala/parallel-calculations.scala @@ -0,0 +1,56 @@ +import scala.collection.parallel.CollectionConverters._ + +case class PrimeFactorInfo( + number: Int, + smallestPrimeFactor: Int, + primeFactors: List[Int] + ) + +def isPrime(n: Int): Boolean = { + @annotation.tailrec + def checkDivisor(d: Int): Boolean = { + if (d * d > n) true + else if (n % d == 0) false + else checkDivisor(d + 2) + } + + if (n < 2) false + else if (n == 2 || n == 3) true + else if (n % 2 == 0 || n % 3 == 0) false + else checkDivisor(5) +} + +def primeFactorInfo(n: Int): PrimeFactorInfo = { + require(n > 1, "Number must be more than one") + + @annotation.tailrec + def factorize(num: Int, currentFactor: Int = 2, factors: List[Int] = Nil): List[Int] = { + if (num == 1) factors.reverse + else if (isPrime(num)) (num :: factors).reverse + else if (num % currentFactor == 0) factorize(num / currentFactor, currentFactor, currentFactor :: factors) + else { + val nextFactor = if (currentFactor == 2) 3 else currentFactor + 2 + factorize(num, nextFactor, factors) + } + } + + val factors = if (isPrime(n)) List(n) + else factorize(n).sorted + + PrimeFactorInfo(n, factors.min, factors) +} + +object ParallelCalculations extends App { + + private val numbers: List[Int] = List( + 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 + ) + private val info: List[PrimeFactorInfo] = numbers.par.map(primeFactorInfo).toList + private val maxFactor: Int = info.map(_.smallestPrimeFactor).max + private val results: List[PrimeFactorInfo] = info.filter(_.smallestPrimeFactor == maxFactor) + + println(s"The following number(s) have the largest minimal prime factor of $maxFactor:") + results.foreach { result => + println(s" ${result.number} whose prime factors are ${result.primeFactors.mkString(", ")}") + } +} diff --git a/Task/Parametric-polymorphism/Python/parametric-polymorphism-1.py b/Task/Parametric-polymorphism/Python/parametric-polymorphism-1.py new file mode 100644 index 0000000000..a99472d43d --- /dev/null +++ b/Task/Parametric-polymorphism/Python/parametric-polymorphism-1.py @@ -0,0 +1,38 @@ +"""Parametric polymorphism. Requires Python >= 3.9.""" + +from typing import Callable +from typing import Generic +from typing import Iterable +from typing import TypeVar +from typing import Union + +T = TypeVar("T") + + +class Tree(Generic[T]): + def __init__(self, value: T): + self.value = value + self.left: Union[Tree[T], None] = None + self.right: Union[Tree[T], None] = None + + def map(self, func: Callable[[T], T]) -> Iterable[T]: + yield func(self.value) + if self.left is not None: + yield from self.left.map(func) + if self.right is not None: + yield from self.right.map(func) + + +if __name__ == "__main__": + tree = Tree(7) + tree.left = Tree(42) + tree.right = Tree(101) + tree.right.left = Tree(1) + + # Fails static type checking as "foo" is not an int. + # tree.left.left = Tree[int]("foo") + + # Fails static type checking as Tree[str] is not Tree[int] + # tree.left.left = Tree("bar") + + print(list(tree.map(lambda v: v + 1))) # [8, 43, 102, 2] diff --git a/Task/Parametric-polymorphism/Python/parametric-polymorphism-2.py b/Task/Parametric-polymorphism/Python/parametric-polymorphism-2.py new file mode 100644 index 0000000000..25762e97ef --- /dev/null +++ b/Task/Parametric-polymorphism/Python/parametric-polymorphism-2.py @@ -0,0 +1,33 @@ +"""Parametric polymorphism. Requires Python >= 3.12.""" + +from typing import Callable +from typing import Iterable + + +class Tree[T]: + def __init__(self, value: T): + self.value = value + self.left: Tree[T] | None = None + self.right: Tree[T] | None = None + + def map(self, func: Callable[[T], T]) -> Iterable[T]: + yield func(self.value) + if self.left is not None: + yield from self.left.map(func) + if self.right is not None: + yield from self.right.map(func) + + +if __name__ == "__main__": + tree = Tree(7) + tree.left = Tree(42) + tree.right = Tree(101) + tree.right.left = Tree(1) + + # Fails static type checking as "foo" is not an int. + # tree.left.left = Tree[int]("foo") + + # Fails static type checking as Tree[str] is not Tree[int] + # tree.left.left = Tree("bar") + + print(list(tree.map(lambda v: v + 1))) # [8, 43, 102, 2] diff --git a/Task/Parametric-polymorphism/Zig/parametric-polymorphism.zig b/Task/Parametric-polymorphism/Zig/parametric-polymorphism.zig new file mode 100644 index 0000000000..92e3d00840 --- /dev/null +++ b/Task/Parametric-polymorphism/Zig/parametric-polymorphism.zig @@ -0,0 +1,33 @@ +const std = @import("std"); + +pub fn main() void { + var tree = Tree(u8).init(10); + std.debug.print("Before: {}\n", .{tree.value}); + tree.replace_all(65); + std.debug.print("After: {}\n", .{tree.value}); + +} + +pub fn Tree(T: type) type { + + return struct { + const Self = @This(); + value: T, + left: ?*Self, + right: ?*Self, + + pub fn init(value: T) Self { + return Self{ + .value = value, + .left = null, + .right = null, + }; + } + + pub fn replace_all(self: *Self, value: T) void { + self.value = value; + if (self.left) |_| self.left.?.replace_all(value); + if (self.right) |_| self.right.?.replace_all(value); + } + }; +} diff --git a/Task/Parsing-RPN-calculator-algorithm/Lua/parsing-rpn-calculator-algorithm.lua b/Task/Parsing-RPN-calculator-algorithm/Lua/parsing-rpn-calculator-algorithm.lua deleted file mode 100644 index fe4c77654b..0000000000 --- a/Task/Parsing-RPN-calculator-algorithm/Lua/parsing-rpn-calculator-algorithm.lua +++ /dev/null @@ -1,52 +0,0 @@ -local stack = {} -function push( a ) table.insert( stack, 1, a ) end -function pop() - if #stack == 0 then return nil end - return table.remove( stack, 1 ) -end -function writeStack() - for i = #stack, 1, -1 do - io.write( stack[i], " " ) - end - print() -end -function operate( a ) - local s - if a == "+" then - push( pop() + pop() ) - io.write( a .. "\tadd\t" ); writeStack() - elseif a == "-" then - s = pop(); push( pop() - s ) - io.write( a .. "\tsub\t" ); writeStack() - elseif a == "*" then - push( pop() * pop() ) - io.write( a .. "\tmul\t" ); writeStack() - elseif a == "/" then - s = pop(); push( pop() / s ) - io.write( a .. "\tdiv\t" ); writeStack() - elseif a == "^" then - s = pop(); push( pop() ^ s ) - io.write( a .. "\tpow\t" ); writeStack() - elseif a == "%" then - s = pop(); push( pop() % s ) - io.write( a .. "\tmod\t" ); writeStack() - else - push( tonumber( a ) ) - io.write( a .. "\tpush\t" ); writeStack() - end -end -function calc( s ) - local t, a = "", "" - print( "\nINPUT", "OP", "STACK" ) - for i = 1, #s do - a = s:sub( i, i ) - if a == " " then operate( t ); t = "" - else t = t .. a - end - end - if a ~= "" then operate( a ) end - print( string.format( "\nresult: %.13f", pop() ) ) -end ---[[ entry point ]]-- -calc( "3 4 2 * 1 5 - 2 3 ^ ^ / +" ) -calc( "22 11 *" ) diff --git a/Task/Partition-function-P/ALGOL-68/partition-function-p.alg b/Task/Partition-function-P/ALGOL-68/partition-function-p.alg new file mode 100644 index 0000000000..fccba86274 --- /dev/null +++ b/Task/Partition-function-P/ALGOL-68/partition-function-p.alg @@ -0,0 +1,46 @@ +BEGIN # calculate the partition function of some integers # + # translated from the FreeBASIC sample # + PR precision 128 PR # set the number of digits for LONG LONG INT # + MODE PARTINT = LONG LONG INT; + PROC partitions p = ( INT n )PARTINT: + BEGIN + [ 0 : n ]PARTINT p; FOR i FROM LWB p TO UPB p DO p[ i ] := 0 OD; + p[ 0 ] := 1; + FOR i TO n DO + INT k := 0; + WHILE k +:= 1; + INT j := ( k * ( 3 * k - 1 ) ) OVER 2; + IF j > i + THEN FALSE # exit the loop # + ELSE IF ODD k THEN + p[ i ] +:= p[ i - j ] + ELSE + p[ i ] -:= p[ i - j ] + FI; + j +:= k; + IF j > i + THEN FALSE # exit the loop # + ELSE IF ODD k THEN + p[ i ] +:= p[ i - j ] + ELSE + p[ i ] -:= p[ i - j ] + FI; + TRUE # continue to loop # + FI + FI + DO SKIP OD + OD; + p[ n ] + END # partitions p # ; + + BEGIN + print( ( "P(0..12):" ) ); + FOR x FROM 0 TO 12 DO + print( ( " ", whole( partitions p( x ), 0 ) ) ) + OD; + print( ( newline, "P(127): ", whole( partitions p( 127 ), 0 ) ) ); + print( ( newline, "P(255): ", whole( partitions p( 255 ), 0 ) ) ); + print( ( newline, "P(6666): ", whole( partitions p( 6666 ), 0 ) ) ); + print( ( newline ) ) + END +END diff --git a/Task/Partition-function-P/Haskell/partition-function-p.hs b/Task/Partition-function-P/Haskell/partition-function-p-1.hs similarity index 100% rename from Task/Partition-function-P/Haskell/partition-function-p.hs rename to Task/Partition-function-P/Haskell/partition-function-p-1.hs diff --git a/Task/Partition-function-P/Haskell/partition-function-p-2.hs b/Task/Partition-function-P/Haskell/partition-function-p-2.hs new file mode 100644 index 0000000000..7990f93ed9 --- /dev/null +++ b/Task/Partition-function-P/Haskell/partition-function-p-2.hs @@ -0,0 +1,2 @@ +part = 1 : b 1 + where b n = p where p = zipWith (+) (1 : b (n + 1)) (replicate n 0 ++ p) diff --git a/Task/Partition-function-P/Haskell/partition-function-p-3.hs b/Task/Partition-function-P/Haskell/partition-function-p-3.hs new file mode 100644 index 0000000000..763b5b3f73 --- /dev/null +++ b/Task/Partition-function-P/Haskell/partition-function-p-3.hs @@ -0,0 +1,6 @@ +ghci> take 30 part +[1,1,2,3,5,7,11,15,22,30,42,56,77,101,135,176,231,297,385,490,627,792,1002,1255,1575,1958,2436,3010,3718,4565] +ghci> :set +s +ghci> part !! 6666 +193655306161707661080005073394486091998480950338405932486880600467114423441282418165863 +(4.89 secs, 5,214,048,336 bytes) diff --git a/Task/Partition-function-P/J/partition-function-p.j b/Task/Partition-function-P/J/partition-function-p-1.j similarity index 100% rename from Task/Partition-function-P/J/partition-function-p.j rename to Task/Partition-function-P/J/partition-function-p-1.j diff --git a/Task/Partition-function-P/J/partition-function-p-2.j b/Task/Partition-function-P/J/partition-function-p-2.j new file mode 100644 index 0000000000..e2219223e7 --- /dev/null +++ b/Task/Partition-function-P/J/partition-function-p-2.j @@ -0,0 +1 @@ +{{ {: (y{. +//.@(*/) )/ (0=}.|/])@i. @ >:y}} diff --git a/Task/Partition-function-P/J/partition-function-p-3.j b/Task/Partition-function-P/J/partition-function-p-3.j new file mode 100644 index 0000000000..955870d33f --- /dev/null +++ b/Task/Partition-function-P/J/partition-function-p-3.j @@ -0,0 +1,2 @@ + {{ {: (y{. +//.@(*/) )/ (x:(0=}.|/])@i. @ >:y)}} 666 +11393868451739000294452939 diff --git a/Task/Partition-function-P/SETL/partition-function-p.setl b/Task/Partition-function-P/SETL/partition-function-p.setl new file mode 100644 index 0000000000..faa0dd6601 --- /dev/null +++ b/Task/Partition-function-P/SETL/partition-function-p.setl @@ -0,0 +1,36 @@ +program partition_function; + loop for n in [666, 6666] do + show_partition_with_time(n); + end loop; + + proc show_partition_with_time(n); + s := clock; + p := partition(n); + d := (clock - s) / 1000; + print("p(" + str n + ") = " + str p + " (" + str d + "s)"); + end proc; + + proc partition(n); + pn := [1,1]; + loop for i in [3..n+2] do + pn(i) := 0; + loop init k := 1; step k +:= 1; do + penta := k * (3 * k-1) div 2; + if penta >= i-1 then quit; end if; + if k mod 2 = 1 then + pn(i) +:= pn(i-penta); + else + pn(i) -:= pn(i-penta); + end if; + penta +:= k; + if penta >= i-1 then quit; end if; + if k mod 2 = 1 then + pn(i) +:= pn(i-penta); + else + pn(i) -:= pn(i-penta); + end if; + end loop; + end loop; + return pn(n+2); + end proc; +end program; diff --git a/Task/Pascals-triangle/FutureBasic/pascals-triangle.basic b/Task/Pascals-triangle/FutureBasic/pascals-triangle.basic new file mode 100644 index 0000000000..5f71055f27 --- /dev/null +++ b/Task/Pascals-triangle/FutureBasic/pascals-triangle.basic @@ -0,0 +1,20 @@ +include "NSLog.incl" +NSLogSetTitle( @"Pascal's Triangle" ) +NSLogSetTextAlignment( NSTextAlignmentCenter ) + +clear local fn pyramid( n as int ) + int v( 20, 20 ) + v( 0, 1 ) = 1 + nslog( @"\n 1 " ) + for int y = 1 to n -1 + for int x = 1 to y + 1 + v( y, x ) = v( y - 1, x - 1 ) + v( y - 1, x ) + nslog( @"%4d \b", v( y, x ) ) + next + nslog( @"" ) + next +end fn + +fn pyramid( 15 ) + +handleevents diff --git a/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy index cc6ad6edbf..efa8b72473 100644 --- a/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy +++ b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy @@ -46,6 +46,6 @@ proc task2ok . . mul i bal bal$[] bal -= 1 . - print "Balance after 25 years: $" & bal & "." & substr strjoin bal$[] 1 16 + print "Balance after 25 years: $" & bal & "." & substr strjoin bal$[] "" 1 16 . task2ok diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq index eea1e73398..7bfc030148 100644 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq +++ b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-1.jq @@ -1,17 +1,9 @@ -# Input: the value at which to compute v +# A (naive) limitless generator def v: - # Input: cache - # Output: updated cache - def v_(n): - (n|tostring) as $s - | . as $cache - | if ($cache | has($s)) then . - else if n == 1 then $cache["1"] = 2 - elif n == 2 then $cache["2"] = -4 - else ($cache | v_(n-1) | v_(n - 2)) as $new - | $new[(n-1)|tostring] as $x - | $new[(n-2)|tostring] as $y - | $new + {($s): ((111 - (1130 / $x) + (3000 / ($x * $y)))) } - end - end; - . as $m | {} | v_($m) | .[($m|tostring)] ; + [2, -4] + | recurse( [.[1], 111 - (1130 / .[1]) + 3000 / (.[0] * .[1])] ) + | .[0]; + +[limit(100; v)] +| (3, 4, 5, 6, 7, 8, 20, 30, 50, 100) as $i +| [$i, .[$i - 1]] diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq index 64e4ca8c42..c25a7af901 100644 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq +++ b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-2.jq @@ -1 +1,11 @@ -(3,4,5,6,7,8,20,30,50,100) | v +# Given the balance in the prior year, compute the new balance in year n. +# Input: { e: m, c: n } representing m*e + n +def new_balance(n): + if n == 0 then {e: 1, c: -1} + else {e: (.e * n), c: (.c * n - 1) } + end; + +def balance(n): + def e: 1|exp; + reduce range(0;n) as $i ({}; new_balance($i) ) + | (.e * e) + .c; diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq index c25a7af901..45c0ab4f6c 100644 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq +++ b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-3.jq @@ -1,11 +1 @@ -# Given the balance in the prior year, compute the new balance in year n. -# Input: { e: m, c: n } representing m*e + n -def new_balance(n): - if n == 0 then {e: 1, c: -1} - else {e: (.e * n), c: (.c * n - 1) } - end; - -def balance(n): - def e: 1|exp; - reduce range(0;n) as $i ({}; new_balance($i) ) - | (.e * e) + .c; +balance(25) diff --git a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-4.jq b/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-4.jq deleted file mode 100644 index 45c0ab4f6c..0000000000 --- a/Task/Pathological-floating-point-problems/Jq/pathological-floating-point-problems-4.jq +++ /dev/null @@ -1 +0,0 @@ -balance(25) diff --git a/Task/Peano-curve/ALGOL-68/peano-curve.alg b/Task/Peano-curve/ALGOL-68/peano-curve.alg index bc5d4c2bbb..2f62d20b9a 100644 --- a/Task/Peano-curve/ALGOL-68/peano-curve.alg +++ b/Task/Peano-curve/ALGOL-68/peano-curve.alg @@ -53,7 +53,7 @@ BEGIN # Peano Curve in SVG # put( svg file, ( "'/>", newline, "", newline ) ); close( svg file ) - FI # sierpinski square # ; + FI # peano curve # ; peano curve( "peano.svg", 1200, 12, 3, 50, 50 ) diff --git a/Task/Peano-curve/C/peano-curve.c b/Task/Peano-curve/C/peano-curve.c index 7d70c91302..50e63f94c6 100644 --- a/Task/Peano-curve/C/peano-curve.c +++ b/Task/Peano-curve/C/peano-curve.c @@ -1,35 +1,82 @@ -/*Abhishek Ghosh, 14th September 2018*/ +#include -#include -#include +#include +#include -void Peano(int x, int y, int lg, int i1, int i2) { +/* should be a power of 3 e.g. 1, 3, 9, 27, 81, 243, 729 */ +const int peano_width = 81; +/* the window is a square */ +const int window_side_len = 800; + +void +peano(sfVertexArray *verts, int x, int y, int lg, int i1, int i2) +{ + /* initial x, initial y, curve width (3^m), initial i1, initial i2 */ if (lg == 1) { - lineto(3*x,3*y); + sfVertex v; + v.position.x = 12.0 * x; /* multiply by 12 to scale-up the curve */ + v.position.y = 12.0 * y; + v.color = sfWhite; + sfVertexArray_append(verts, v); return; } - lg = lg/3; - Peano(x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); - Peano(x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); - Peano(x+lg, y+lg, lg, i1, 1-i2); - Peano(x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); - Peano(x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); - Peano(x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); - Peano(x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); - Peano(x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); - Peano(x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); + + peano(verts, x+(2*i1*lg), y+(2*i1*lg), lg, i1, i2); + peano(verts, x+((i1-i2+1)*lg), y+((i1+i2)*lg), lg, i1, 1-i2); + peano(verts, x+lg, y+lg, lg, i1, 1-i2); + peano(verts, x+((i1+i2)*lg), y+((i1-i2+1)*lg), lg, 1-i1, 1-i2); + peano(verts, x+(2*i2*lg), y+(2*(1-i2)*lg), lg, i1, i2); + peano(verts, x+((1+i2-i1)*lg), y+((2-i1-i2)*lg), lg, i1, i2); + peano(verts, x+(2*(1-i1)*lg), y+(2*(1-i1)*lg), lg, i1, i2); + peano(verts, x+((2-i1-i2)*lg), y+((1+i2-i1)*lg), lg, 1-i1, i2); + peano(verts, x+(2*(1-i2)*lg), y+(2*i2*lg), lg, 1-i1, i2); } -int main(void) { +int +main(void) +{ + sfVideoMode mode = {window_side_len, window_side_len, 32}; + sfRenderWindow* window; + sfEvent event; + sfVideoMode vidmode; + sfVector2i winpos; + sfVertexArray *verts; - initwindow(1000,1000,"Peano, Peano"); + /* this will end up holding peano_width^2 vertices */ + verts = sfVertexArray_create(); + sfVertexArray_setPrimitiveType(verts, sfLineStrip); - Peano(0, 0, 1000, 0, 0); /* Start Peano recursion. */ - - getch(); - cleardevice(); - - return 0; + /* Create the main window */ + window = sfRenderWindow_create(mode, "Peano Curve", sfResize | sfClose, NULL); + if (!window) + return EXIT_FAILURE; + + /* Centre the window */ + vidmode = sfVideoMode_getDesktopMode(); + winpos.x = vidmode.width/2 - window_side_len/2; + winpos.y = vidmode.height/2 - window_side_len/2; + sfRenderWindow_setPosition(window, winpos); + + /* Generate the vertices */ + peano(verts, 0, 0, peano_width, 0, 0); + + /* Start the event loop */ + while (sfRenderWindow_isOpen(window)) { + /* Process events */ + while (sfRenderWindow_pollEvent(window, &event)) { + /* Close window : exit */ + if (event.type == sfEvtClosed) + sfRenderWindow_close(window); + } + + sfRenderWindow_clear(window, sfBlack); + /* Render the line */ + sfRenderWindow_drawVertexArray(window, verts, NULL); + sfRenderWindow_display(window); + } + sfRenderWindow_destroy(window); + + return EXIT_SUCCESS; } diff --git a/Task/Pell-numbers/Sidef/pell-numbers.sidef b/Task/Pell-numbers/Sidef/pell-numbers.sidef new file mode 100644 index 0000000000..592a4136e6 --- /dev/null +++ b/Task/Pell-numbers/Sidef/pell-numbers.sidef @@ -0,0 +1,31 @@ +func pell_number(n) { + lucasU(2, -1, n) +} + +func pell_lucas_number(n) { + lucasV(2, -1, n) +} + +say ("The first 10 Pell numbers: ", 10.of(pell_number).join(", ")) +say ("The first 10 Pell-Lucas numbers: ", 10.of(pell_lucas_number).join(", ")) + +say "\nFirst 10 rational approximations to √2:" +{|n| pell_lucas_number(n) / 2 / pell_number(n) }.map(1..10).each {|r| + say "#{'%10s' % r.as_frac} =~ #{r.as_float}" +} + +var pell_prime_indices = 10.by {|n| pell_number(n).is_prime } +say "\nThe first 10 Pell primes: " +pell_prime_indices.each {|n| + say "Pell(#{'%2s' % n}) = #{pell_number(n)}" +} + +say ("\nThe first 10 Newman-Shank-Williams numbers: ", + 10.of{|n| pell_number(2*n) + pell_number(2*n + 1) }.join(', ')) + +say "\nThe first 10 Pythagorean triples corresponding to near isosceles right triangles:" +10.of{|n| pell_number(2*n + 1) }.map {|h| + var t = isqrt(h**2 >> 1) + assert_eq(t**2 + (t+1)**2, h**2) + [t, t+1, h] +}.each{.say} diff --git a/Task/Pells-equation/Langur/pells-equation.langur b/Task/Pells-equation/Langur/pells-equation.langur index ec0697af10..0458436259 100644 --- a/Task/Pells-equation/Langur/pells-equation.langur +++ b/Task/Pells-equation/Langur/pells-equation.langur @@ -1,5 +1,3 @@ -val fun = fn a, b, c: [b, b * c + a] - val solvePell = fn(n) { val x = trunc(n ^/ 2) var y, z, r = x, 1, x * 2 @@ -20,9 +18,9 @@ val C = fn(x) { # format number string with commas var neg, s = "", x -> string if s[1] == '-' { - neg, s = "-", s -> rest + neg, s = "-", less(s, of=1) } - neg ~ join(",", split(-3, s)) + neg ~ join(split(s, by=-3), by=",") } for n in [61, 109, 181, 277, 8941] { diff --git a/Task/Pells-equation/Zig/pells-equation-1.zig b/Task/Pells-equation/Zig/pells-equation-1.zig new file mode 100644 index 0000000000..3ef8f0923d --- /dev/null +++ b/Task/Pells-equation/Zig/pells-equation-1.zig @@ -0,0 +1 @@ +@subWithOverflow() diff --git a/Task/Pells-equation/Zig/pells-equation-2.zig b/Task/Pells-equation/Zig/pells-equation-2.zig new file mode 100644 index 0000000000..95733d5b96 --- /dev/null +++ b/Task/Pells-equation/Zig/pells-equation-2.zig @@ -0,0 +1 @@ +u256 diff --git a/Task/Pells-equation/Zig/pells-equation-3.zig b/Task/Pells-equation/Zig/pells-equation-3.zig new file mode 100644 index 0000000000..58b298fc2f --- /dev/null +++ b/Task/Pells-equation/Zig/pells-equation-3.zig @@ -0,0 +1,60 @@ +const std = @import("std"); + +pub fn main() !void { + const writer = std.io.getStdOut().writer(); + + try printSolvedPell(61, writer); + try printSolvedPell(109, writer); + try printSolvedPell(181, writer); + try printSolvedPell(277, writer); +} + +const Pair = struct { + v1: u256, + v2: u256, + + fn init(a: u256, b: u256) Pair { + return Pair{ + .v1 = a, + .v2 = b, + }; + } +}; + +fn solvePell(n: u256) Pair { + const x: u256 = std.math.sqrt(n); + + // n is a perfect square - no solution other than 1,0 + if (x * x == n) + return Pair.init(1, 0); + + // there are non-trivial solutions + var y = x; + var z: u256 = 1; + var r = 2 * x; + var e = Pair.init(1, 0); + var f = Pair.init(0, 1); + var a: u256 = 0; + var b: u256 = 0; + + while (true) { + y = r * z - y; + z = (n - y * y) / z; + r = (x + y) / z; + e = Pair.init(e.v2, r * e.v2 + e.v1); + f = Pair.init(f.v2, r * f.v2 + f.v1); + a = e.v2 + x * f.v2; + b = f.v2; + const ov = @subWithOverflow(a * a, n * b * b); + if (ov[1] != 0) + continue; + if (ov[0] == 1) // a * a, n * b * b == 1 + break; + } + return Pair.init(a, b); +} + +fn printSolvedPell(n: u256, writer: anytype) !void { + const r = solvePell(n); + try writer.print("x^2 - {d:3} * y^2 = 1 for x = {d:21} and y = {d:19}\n", .{ n, r.v1, r.v2 }); +} diff --git a/Task/Pentagram/ALGOL-68/pentagram.alg b/Task/Pentagram/ALGOL-68/pentagram.alg new file mode 100644 index 0000000000..789e0c9999 --- /dev/null +++ b/Task/Pentagram/ALGOL-68/pentagram.alg @@ -0,0 +1,42 @@ +BEGIN # draw a pentagram, using SVG # + + OP SIND = ( REAL x )REAL: sin( x * pi / 180 ); + OP COSD = ( REAL x )REAL: cos( x * pi / 180 ); + PRIO FMT = 9; + OP FMT = ( REAL v, INT dp )STRING: + BEGIN + STRING result = IF ENTIER v = v + THEN whole( v, - dp * 16 ) + ELSE fixed( v, - dp * 16, ABS dp ) + FI; + INT v pos := LWB result; + WHILE result[ v pos ] = " " DO v pos +:= 1 OD; + result[ v pos : ] + END # FMT # ; + PROC point = ( REAL x, y )STRING: x FMT 2 + " " + y FMT 2; + + PROC draw gram = ( INT width, height, vertices, REAL side, start x, start y, line width )VOID: + BEGIN + REAL angle = 360 / vertices; + print( ( "", newline + ) + ); + REAL x := start x, y := start y; + print( ( " ", newline ) ); + print( ( "", newline ) ) + END # draw gram #; + + draw gram( 500, 300, 5, 240, 150, 50, 3 ) + +END diff --git a/Task/Pentagram/FutureBasic/pentagram.basic b/Task/Pentagram/FutureBasic/pentagram.basic new file mode 100644 index 0000000000..d42c9cbd30 --- /dev/null +++ b/Task/Pentagram/FutureBasic/pentagram.basic @@ -0,0 +1,51 @@ +_window = 1 + +void local fn DrawInView + CFMutableArrayRef points = fn MutableArrayWithCapacity( 0 ) + CGPoint ptA,ptB,ptC,ptD,ptE + float xo,yo, z, x,y, twoPi = 0.0174533 + + xo = 225 + yo = 20 + z = 340 + + ptA = fn CGPointMake( xo,yo) + x = xo - z*sin(18*TwoPi) + y = yo + z*cos(18*TwoPi) + ptB = fn CGPointMake( x,y) + ptE = fn CGPointMake( xo + z*sin(18*TwoPi),y) + x = ptB.x + z*cos(36*TwoPi) + y = ptB.y - z*sin(36*TwoPi) + ptC = fn CGPointMake( x,y) + x -= z + ptD = fn CGPointMake(x,y) + + MutableArrayAddObject( points, fn ValueWithPoint( ptA ) ) + MutableArrayAddObject( points, fn ValueWithPoint( ptB ) ) + MutableArrayAddObject( points, fn ValueWithPoint( ptC ) ) + MutableArrayAddObject( points, fn ValueWithPoint( ptD ) ) + MutableArrayAddObject( points, fn ValueWithPoint( ptE ) ) + MutableArrayAddObject( points, fn ValueWithPoint( ptA ) ) + BezierPathStrokeFillPolygon( points, 2, fn ColorBlack, fn ColorSystemBlue ) + +end fn + +void local fn BuildWindow + window _window, @"Pentagram", ( 0,0,450,400 ) + WindowCenter(_window) + WindowSubclassContentView(_window) + ViewSetFlipped( _windowContentViewTag, YES ) + ViewSetNeedsDisplay( _windowContentViewTag ) +end fn + +void local fn DoDialog( ev as long) + select ( ev ) + case _viewDrawRect : fn DrawInView + end select +end fn + +fn BuildWindow + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Percolation-Bond-percolation/FreeBASIC/percolation-bond-percolation.basic b/Task/Percolation-Bond-percolation/FreeBASIC/percolation-bond-percolation.basic new file mode 100644 index 0000000000..6e5cc21dc0 --- /dev/null +++ b/Task/Percolation-Bond-percolation/FreeBASIC/percolation-bond-percolation.basic @@ -0,0 +1,98 @@ +Randomize Timer + +Const RAND_MAX = 32767 +Const FILL = 1 +Const RWALL = 2 +Const BWALL = 4 + +Dim Shared As Integer x = 10, y = 10 +Dim Shared As Integer grid(x * (y + 2)) +Dim Shared As Integer m, n +Dim Shared As Integer cells, endPos + +Sub makeGrid(p As Double) + Dim As Integer i, j, thresh, r1, r2, r3 + + thresh = Int(p * RAND_MAX) + m = x + n = y + + For i = 0 To Ubound(grid) : grid(i) = 0 : Next + + For i = 0 To m-1: grid(i) = BWALL Or RWALL : Next + + cells = m + endPos = m + + For i = 0 To y-1 + For j = x-1 To 1 Step -1 + r1 = Int(Rnd * (RAND_MAX + 1)) + r2 = Int(Rnd * (RAND_MAX + 1)) + grid(endPos) = Iif(r1 < thresh, BWALL, 0) Or Iif(r2 < thresh, RWALL, 0) + endPos += 1 + Next + r3 = Int(Rnd * (RAND_MAX + 1)) + grid(endPos) = RWALL Or Iif(r3 < thresh, BWALL, 0) + endPos += 1 + Next +End Sub + +Sub showGrid() + Dim As Integer i, j + + For j = 0 To m-1 + Print "+--"; + Next + Print "+" + + For i = 0 To n + Print Iif(i = n, " ", "|"); + For j = 0 To m-1 + Print Iif((grid(i * m + j + cells) And FILL) <> 0, "[]", " "); + Print Iif((grid(i * m + j + cells) And RWALL) <> 0, "|", " "); + Next + Print + If i = n Then Exit Sub + For j = 0 To m-1 + Print Iif((grid(i * m + j + cells) And BWALL) <> 0, "+--", "+ "); + Next + Print "+" + Next +End Sub + +Function filled(p As Integer) As Boolean + If (grid(p) And FILL) <> 0 Then Return False + grid(p) = grid(p) Or FILL + If p >= endPos Then Return True + + Return ((grid(p + 0) And BWALL) = 0 Andalso filled(p + m)) Orelse _ + ((grid(p + 0) And RWALL) = 0 Andalso filled(p + 1)) Orelse _ + ((grid(p - 1) And RWALL) = 0 Andalso filled(p - 1)) Orelse _ + ((grid(p - m) And BWALL) = 0 Andalso filled(p - m)) +End Function + +Function percolate() As Boolean + Dim i As Integer = 0 + While i < m Andalso Not filled(cells + i) + i += 1 + Wend + Return i < m +End Function + +' Main program +makeGrid(0.5) +percolate() +showGrid() + +Print !"\nRunning " & x & " x " & y & " grids 10,000 times for each p:" +For p As Integer = 1 To 9 + Dim As Integer cnt = 0 + Dim As Double pp = p / 10 + For i As Integer = 0 To 9999 + makeGrid(pp) + If percolate() Then cnt += 1 + Next + Print Using "p = #.# : #.####"; pp; cnt / 10000 +Next + +Sleep diff --git a/Task/Perfect-numbers/Zig/perfect-numbers.zig b/Task/Perfect-numbers/Zig/perfect-numbers.zig index fc7e187815..6546be0c9b 100644 --- a/Task/Perfect-numbers/Zig/perfect-numbers.zig +++ b/Task/Perfect-numbers/Zig/perfect-numbers.zig @@ -1,8 +1,8 @@ const std = @import("std"); const expect = std.testing.expect; -const stdout = std.io.getStdOut().outStream(); pub fn main() !void { + const stdout = std.io.getStdOut().writer(); var i: u32 = 2; try stdout.print("The first few perfect numbers are: ", .{}); while (i <= 10_000) : (i += 2) if (propersum(i) == i) @@ -23,7 +23,7 @@ fn propersum(n: u32) u32 { } test "Proper divisors" { - expect(propersum(28) == 28); - expect(propersum(71) == 1); - expect(propersum(30) == 42); + try expect(propersum(28) == 28); + try expect(propersum(71) == 1); + try expect(propersum(30) == 42); } diff --git a/Task/Periodic-table/C-sharp/periodic-table.cs b/Task/Periodic-table/C-sharp/periodic-table.cs new file mode 100644 index 0000000000..68540b31df --- /dev/null +++ b/Task/Periodic-table/C-sharp/periodic-table.cs @@ -0,0 +1,35 @@ +// Periodic table +using System; + +class PeriodicTable +{ + private static readonly int[] aArray = {1, 2, 5, 13, 57, 72, 89, 104}; + private static readonly int[] bArray = {-1, 15, 25, 35, 72, 21, 58, 7}; + + public void RowAndColumn(int n, out int r, out int c) + { + int i = 7; + while (aArray[i] > n) + i--; + int m = n + bArray[i]; + r = m / 18 + 1; + c = m % 18 + 1; + } +} + +class Program +{ + public static void Main() + { + PeriodicTable pt = new PeriodicTable(); + // Example elements (atomic numbers). + int[] nums = new int[]{1, 2, 29, 42, 57, 58, 72, 89, 90, 103}; + foreach (var n in nums) + { + int r, c; + pt.RowAndColumn(n, out r, out c); + Console.Write(String.Format("{0,3:###} ->", n)); + Console.WriteLine(String.Format("{0,2:##}{1,3:###}", r, c)); + } + } +} diff --git a/Task/Periodic-table/JavaScript/periodic-table.js b/Task/Periodic-table/JavaScript/periodic-table.js new file mode 100644 index 0000000000..241c432974 --- /dev/null +++ b/Task/Periodic-table/JavaScript/periodic-table.js @@ -0,0 +1,24 @@ +// Periodic table + +class PeriodicTable { + constructor() { + this.aArray = [1, 2, 5, 13, 57, 72, 89, 104]; + this.bArray = [-1, 15, 25, 35, 72, 21, 58, 7]; + } + + rowAndColumn(n) { + var i = 7; + while (this.aArray[i] > n) + i--; + var m = n + this.bArray[i]; + return [Math.floor(m / 18) + 1, m % 18 + 1]; + } +} + +pt = new PeriodicTable(); +// Example elements (atomic numbers). +for (var n of [1, 2, 29, 42, 57, 58, 72, 89, 90, 103]) { + [r, c] = pt.rowAndColumn(n); + console.log(n.toString().padStart(3, ' ') + " ->" + + r.toString().padStart(2, ' ') + c.toString().padStart(3, ' ')); +} diff --git a/Task/Periodic-table/M2000-Interpreter/periodic-table.m2000 b/Task/Periodic-table/M2000-Interpreter/periodic-table.m2000 new file mode 100644 index 0000000000..87137341b8 --- /dev/null +++ b/Task/Periodic-table/M2000-Interpreter/periodic-table.m2000 @@ -0,0 +1,22 @@ +module Periodic_table { + Dim Element() As Integer + Element()= (1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113) + For I = 0 To len(Element())-1 + MostarPos(Element(I)) + Next I + Sub MostarPos(N As Integer) + Local Integer M, I, R, C + Local A() as integer, B() as integer + A() = (1, 2, 5, 13, 57, 72, 89, 104) + B() = (-1, 15, 25, 35, 72, 21, 58, 7) + I = 7 + While A(I) > N + I -= 1 + End While + M = N + B(I) + R = (M Div 18) +1 + C = (M Mod 18) +1 + Print format$("Atomic number {0:-3} -> {1}, {2}", N, R, C) + End Sub +} +Periodic_table diff --git a/Task/Periodic-table/Modula-2/periodic-table.mod2 b/Task/Periodic-table/Modula-2/periodic-table.mod2 new file mode 100644 index 0000000000..349a80a4db --- /dev/null +++ b/Task/Periodic-table/Modula-2/periodic-table.mod2 @@ -0,0 +1,39 @@ +MODULE PeriodicTable; +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; +TYPE + TAB = ARRAY [0 .. 7] OF INTEGER; + TANum = ARRAY [0 .. 9] OF INTEGER; +CONST + A = TAB{1, 2, 5, 13, 57, 72, 89, 104}; + B = TAB{-1, 15, 25, 35, 72, 21, 58, 7}; + +PROCEDURE ShowRowAndColumn(ANum: INTEGER); +VAR + I, M, R, C: CARDINAL; +BEGIN + I := 7; + WHILE A[I] > ANum DO + I := I - 1 + END; + M := ANum + B[I]; + R := M DIV 18 + 1; + C := M MOD 18 + 1; + WriteInt(ANum, 3); + WriteString(" ->"); + WriteInt(R, 2); + WriteInt(C, 3); + WriteLn; +END ShowRowAndColumn; + +VAR + J : CARDINAL; + ANum: TANum; (* Example elements (atomic numbers) *) +BEGIN + ANum := TANum{1, 2, 29, 42, 57, 58, 72, 89, 90, 103}; + FOR J := 0 TO 9 DO + ShowRowAndColumn(ANum[J]) + END +END PeriodicTable. diff --git a/Task/Peripheral-drift-illusion/Nim/peripheral-drift-illusion.nim b/Task/Peripheral-drift-illusion/Nim/peripheral-drift-illusion.nim index 7a44691a15..bbd3d9b653 100644 --- a/Task/Peripheral-drift-illusion/Nim/peripheral-drift-illusion.nim +++ b/Task/Peripheral-drift-illusion/Nim/peripheral-drift-illusion.nim @@ -1,11 +1,11 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import gtk2, glib2, gdk2, cairo const Width = 600 Height = 460 type - Color = array[3, float] + Color = (float, float, float) Edge {.pure.} = enum LT, TR, RB, BL const @@ -23,20 +23,23 @@ const [TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT, BL], [TR, TR, LT, LT, BL, BL, RB, RB, TR, TR, LT, LT]] - Black: Color = [0.0, 0.0, 0.0] - Blue: Color = [0.2, 0.3, 1.0] - White: Color = [1.0, 1.0, 1.0] - Yellow: Color = [0.8, 0.8, 0.0] + Black: Color = (0.0, 0.0, 0.0) + Blue: Color = (0.2, 0.3, 1.0) + White: Color = (1.0, 1.0, 1.0) + Yellow: Color = (0.8, 0.8, 0.0) Colors: array[Edge, array[4, Color]] = [[White, Black, Black, White], [White, White, Black, Black], [Black, White, White, Black], [Black, Black, White, White]] -#--------------------------------------------------------------------------------------------------- -proc draw(area: DrawingArea; context: Context) = - ## Draw the pattern in the area. +template setSource(ctx: ptr Context; color: Color) = + ctx.setSourceRgb(color[0], color[1], color[2]) + + +proc draw(context: ptr Context) = + ## Draw the pattern. func line(x1, y1, x2, y2: float; color: Color) = context.setSource(color) @@ -62,34 +65,33 @@ proc draw(area: DrawingArea; context: Context) = line(px + 23, py + 23, px, py + 23, carray[2]) line(px, py + 23, px, py, carray[3]) -#--------------------------------------------------------------------------------------------------- -proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = +proc onExposeEvent(area: PDrawingArea; event: PEventExpose; data: pointer): gboolean {.cdecl.} = ## Callback to draw/redraw the drawing area contents. - - area.draw(context) + let context = cairoCreate(area.window) + context.draw() result = true -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Process the "destroy" event. + mainQuit() - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Peripheral drift illusion") - # Create the drawing area. - let area = newDrawingArea() - window.add(area) +nimInit() +let window = windowNew(WINDOW_TOPLEVEL) +window.setSizeRequest(Width, Height) +window.setTitle("Peripheral drift illusion") - # Connect the "draw" event to the callback to draw the pattern. - discard area.connect("draw", ondraw, pointer(nil)) +# Create the drawing area. +let area = drawingAreaNew() +window.add area - window.showAll() +# Connect the "expose" event to the callback to draw the pattern. +discard area.signalConnect("expose-event", SIGNAL_FUNC(onExposeEvent), nil) -#——————————————————————————————————————————————————————————————————————————————————————————————————— +# Quit the application if the window is closed. +discard window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) -let app = newApplication(Application, "Rosetta.Illusion") -discard app.connect("activate", activate) -discard app.run() +window.showAll() +main() diff --git a/Task/Peripheral-drift-illusion/Octave/peripheral-drift-illusion.octave b/Task/Peripheral-drift-illusion/Octave/peripheral-drift-illusion.octave new file mode 100644 index 0000000000..b581cbab55 --- /dev/null +++ b/Task/Peripheral-drift-illusion/Octave/peripheral-drift-illusion.octave @@ -0,0 +1,69 @@ +function pdi_circle(cell_size = 50, numrows = 15, numcols = 15, radius = 15, offset = 5, rotx = 2, roty = 2, color1 = [0, 0, 255], color2 = [0, 255, 0]) +% creates peripheral drift illusion using circles +% pdi_circle(cell_size, numrows, numcols, radius, offset, rotx, roty, color1, color2) +% pdi_circle(50, 15, 15, 15, 5, 2, 2, [0, 0, 255], [0, 255, 0]) + +% color dimension +colorB = uint8([0, 0, 0]); +colorW = uint8([255, 255, 255]); +color1 = uint8(color1); +color2 = uint8(color2); + +% pixels per cell +centerC = cell_size * [1 1] / 2; +[cellX, cellY] = ndgrid(1:cell_size, 1:cell_size); +cell_ones = ones(cell_size, cell_size, "uint8"); + +% total image size +img_size = [numrows, numcols] * cell_size +final_image = zeros(img_size(1), img_size(2), 3, "uint8"); + +% offset steps +stepx = 2 * pi * rotx / numrows; +stepy = 2 * pi * roty / numcols; + +% loop over cells +for nr = 1:numrows, for nc = 1:numcols + + % find offset centers + step_phase = (nr-1) * stepx + (nc-1) * stepy; + offsetC = offset * [cos(step_phase), sin(step_phase)]; + centerB = centerC + offsetC; + centerW = centerC - offsetC; + + % fill background + image1 = cell_ones * color2(1); + image2 = cell_ones * color2(2); + image3 = cell_ones * color2(3); + + % fill white + insideW = sqrt((cellX - centerW(1)).^2 + (cellY - centerW(2)).^2) <= radius; + image1(insideW) = colorW(1); + image2(insideW) = colorW(2); + image3(insideW) = colorW(3); + + % fill black + insideB = sqrt((cellX - centerB(1)).^2 + (cellY - centerB(2)).^2) <= radius; + image1(insideB) = colorB(1); + image2(insideB) = colorB(2); + image3(insideB) = colorB(3); + + % fill foreground + insideC = sqrt((cellX - centerC(1)).^2 + (cellY - centerC(2)).^2) <= radius; + image1(insideC) = color1(1); + image2(insideC) = color1(2); + image3(insideC) = color1(3); + + % generate image + offset_image = cat(3, image1, image2, image3); + final_rows = (nr-1) * cell_size + [1:cell_size]; + final_cols = (nc-1) * cell_size + [1:cell_size]; + final_image(final_rows, final_cols, :) = offset_image; + +endfor, endfor + +% show and save image +imshow(final_image) +imwrite(final_image, "PeripheralDriftOctave.png") + +endfunction diff --git a/Task/Peripheral-drift-illusion/Python/peripheral-drift-illusion.py b/Task/Peripheral-drift-illusion/Python/peripheral-drift-illusion.py new file mode 100644 index 0000000000..c784e1f9ea --- /dev/null +++ b/Task/Peripheral-drift-illusion/Python/peripheral-drift-illusion.py @@ -0,0 +1,56 @@ +import pygame + +width, height = 750, 700 + +RADIUS = width // 15 + +width += RADIUS +height += RADIUS + +def calculate_angle_pos( + start: tuple[int | float, int | float], radius: int | float, angle: int | float +): + vec = pygame.math.Vector2(0, -radius).rotate((angle) % 360) + return start[0] + vec.x, start[1] + vec.y + +def main(): + pygame.init() + pygame.display.set_caption('Drift Illusion') + + screen = pygame.display.set_mode((width, height)) + + running = True + + while running: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + + screen.fill((0, 125, 0)) + + step = 360 / 15 + angle = step + + for y in range(RADIUS, height, RADIUS): + for x in range(RADIUS, width, RADIUS): + rad = RADIUS // 3 + + comp_angle = (angle + 180) % 361 + + x1, y1 = calculate_angle_pos((x, y), (1/2.5) * rad, angle) + x2, y2 = calculate_angle_pos((x, y), (1/2.5) * rad, comp_angle) + + pygame.draw.circle(screen, (255, 255, 255), (x1, y1), rad) + pygame.draw.circle(screen, (0, 0, 0), (x2, y2), rad) + pygame.draw.circle(screen, (0, 0, 255), (x, y), rad) + + angle = (angle - step) % 361 + + angle = (angle - step) % 361 + + pygame.display.flip() + + pygame.quit() + +if __name__ == '__main__': + main() diff --git a/Task/Permutations-Derangements/Haskell/permutations-derangements-3.hs b/Task/Permutations-Derangements/Haskell/permutations-derangements-3.hs new file mode 100644 index 0000000000..1b03d6b0ef --- /dev/null +++ b/Task/Permutations-Derangements/Haskell/permutations-derangements-3.hs @@ -0,0 +1,14 @@ +import Data.Ratio ((%), numerator) + +infixl 7 *. +(*.) :: Num a => a -> [a] -> [a] +x *. (p:ps) = x*p : x*.ps + +instance Num a => Num [a] where + negate = map negate + (+) = zipWith (+) + (*) (p:ps) (q:qs) = p*q : ((p*.qs) + ps*(q:qs)) + fromInteger n = fromInteger n:repeat 0 + +expseq :: [Rational] -> [Rational] +expseq ps = zipWith (\p q -> p*fromInteger q) ps (scanl (*) 1 [1..]) diff --git a/Task/Permutations-Derangements/Haskell/permutations-derangements-4.hs b/Task/Permutations-Derangements/Haskell/permutations-derangements-4.hs new file mode 100644 index 0000000000..d485297c1f --- /dev/null +++ b/Task/Permutations-Derangements/Haskell/permutations-derangements-4.hs @@ -0,0 +1,8 @@ +derangements :: [Integer] +derangements = map numerator + (expseq (invexp/(1:(-1):repeat 0))) + +invexp :: [Rational] +invexp = zipWith (%) (cycle [1,-1]) factorials + where + factorials = scanl (*) 1 [1..] diff --git a/Task/Permutations-Derangements/Haskell/permutations-derangements-5.hs b/Task/Permutations-Derangements/Haskell/permutations-derangements-5.hs new file mode 100644 index 0000000000..e86433cce4 --- /dev/null +++ b/Task/Permutations-Derangements/Haskell/permutations-derangements-5.hs @@ -0,0 +1,4 @@ +ghci> take 10 derangements +[1,0,1,2,9,44,265,1854,14833,133496] +ghci> derangements !! 20 +895014631192902121 diff --git a/Task/Permutations-Derangements/PascalABC.NET/permutations-derangements.pas b/Task/Permutations-Derangements/PascalABC.NET/permutations-derangements.pas new file mode 100644 index 0000000000..41ec4b72c6 --- /dev/null +++ b/Task/Permutations-Derangements/PascalABC.NET/permutations-derangements.pas @@ -0,0 +1,23 @@ +function derangements(a: array of T) := + a.Permutations.where(p -> p.where((x, i) -> x = a[i]).Count = 0); + +function subFactorial(n: integer): int64; +begin + if n <= 1 then result := 1 - n + else result := (n - 1) * (subfactorial(n - 1) + subfactorial(n - 2)); +end; + +begin + println('Derangements of 1 2 3 4:'); + foreach var d in derangements(|1, 2, 3, 4|) do + d.println; + + println(#10, 'Number of derangements:'); + println('n counted calculated'); + println('- ------- ----------'); + for var n := 1 to 10 do + writeln(n:2, derangements(range(1, n).ToArray).count:9, subfactorial(n):10); + + println; + println('!20 = ', subfactorial(20)); +end. diff --git a/Task/Permutations/AWK/permutations.awk b/Task/Permutations/AWK/permutations-1.awk similarity index 100% rename from Task/Permutations/AWK/permutations.awk rename to Task/Permutations/AWK/permutations-1.awk diff --git a/Task/Permutations/AWK/permutations-2.awk b/Task/Permutations/AWK/permutations-2.awk new file mode 100644 index 0000000000..8a202c697c --- /dev/null +++ b/Task/Permutations/AWK/permutations-2.awk @@ -0,0 +1,33 @@ +# determine and print all permutations of numbers 1..n + +# General variant: simple, single array, recursive, not in lexical order +# +# An array with n places is used, marked by 0 as free. +# The current element l replaces the free places one by one, +# and the next element l+1 is probed recursively with the array. +# +function permute1(l, n, r, i) { + if ( l <= n) { + for (i=1; i<=n; ++i) { + if (r[i] == 0) { + r[i] = l + permute1(l+1, n, r) + r[i] = 0 + } + } + return + } + # print result; consumes ca. 50% of CPU time + s = "" + for (i=1; i <= length(r); ++i) # ensure order + s = s r[i] " " + print s +} + +# command line parameter is number of elements. +BEGIN { + n = 3 # default + if (ARGC > 1) n = ARGV[1] # number may be given as parameter + for (i=1; i <=n; ++i) r[i] = 0 # fill with zeroes + permute1(1, n, r) +} diff --git a/Task/Permutations/AWK/permutations-3.awk b/Task/Permutations/AWK/permutations-3.awk new file mode 100644 index 0000000000..f8a31c3005 --- /dev/null +++ b/Task/Permutations/AWK/permutations-3.awk @@ -0,0 +1,23 @@ +function permute(l, k, i, s) { + if (k == length(l)) { + show(s) + return + } + for (i=k; i <= length(l); ++i) { + swap(l, i, k) + permute(l, k+1) + swap(l, k, i) + } +} +function swap(l, i, k, t) { + t = l[i] + l[i] = l[k] + l[k] = t +} +BEGIN { + n = 3 # default + if (ARGC > 1) n = ARGV[1] # number may be given as parameter + for (i=1; i <=n; ++i) + l[i] = i + permute(l, 1) + } diff --git a/Task/Permutations/Langur/permutations.langur b/Task/Permutations/Langur/permutations.langur index b94494e034..2a97227c73 100644 --- a/Task/Permutations/Langur/permutations.langur +++ b/Task/Permutations/Langur/permutations.langur @@ -7,7 +7,7 @@ val permute = fn(plist) { if len(plist) > limit: throw "permutation limit exceeded (currently {{limit}})" var elements = plist - var ordinals = pseries(len(elements)) + var ordinals = series(len(elements)) val n = len(ordinals) var i, j diff --git a/Task/Permutations/M2000-Interpreter/permutations-2.m2000 b/Task/Permutations/M2000-Interpreter/permutations-2.m2000 index c2613878b0..8889cf5d07 100644 --- a/Task/Permutations/M2000-Interpreter/permutations-2.m2000 +++ b/Task/Permutations/M2000-Interpreter/permutations-2.m2000 @@ -1,43 +1,42 @@ Module StepByStep { - Function PermutationStep (a) { - c1=lambda (&f, a) ->{ - =car(a) - f=true - } - m=len(a) - c=c1 - while m>1 { - c1=lambda c2=c,p, m=(,) (&f, a) ->{ - if len(m)=0 then m=a - =cons(car(m),c2(&f, cdr(m))) - if f then f=false:p++: m=cons(cdr(m), car(m)) : if p=len(m) then p=0 : m=(,):: f=true - } - c=c1 - m-- - } - =lambda c, a (&f) -> { - =c(&f, a) - } - } - k=false - StepA=PermutationStep((1,2,3,4)) - while not k { - Print StepA(&k) - } - k=false - StepA=PermutationStep((100,200,300)) - while not k { - Print StepA(&k) - } - k=false - StepA=PermutationStep(("A", "B", "C", "D")) - while not k { - Print StepA(&k) - } - k=false - StepA=PermutationStep(("DOG", "CAT", "BAT")) - while not k { - Print StepA(&k) - } + Function PermutationStep { + a=array([]) + c1=lambda (&f, a) ->{ + =car(a) + f=true + } + m=len(a) + c=c1 + while m>1 + c1=lambda c2=c, p, m=(,) (&f, a) ->{ + if len(m)=0 then m=a + =cons(car(m),c2(&f, cdr(m))) + if f then + f=false + p++ + m=cons(cdr(m), car(m)) + if p=len(m) then + p=0 + m=(,) + f=true + end if + end if + } + c=c1 + m-- + end while + =lambda c, a (&f) -> { + =c(&f, a) + } + } + display(PermutationStep(1,2,3,4)) + display(PermutationStep(100,200,300)) + display(PermutationStep("A", "B", "C", "D")) + display(PermutationStep("DOG", "CAT", "BAT")) + + sub display(S as lambda) + k=false + while not k : Print S(&k)#str$(): end while + end sub } StepByStep diff --git a/Task/Phrase-reversals/EasyLang/phrase-reversals.easy b/Task/Phrase-reversals/EasyLang/phrase-reversals.easy index 6d593561d0..6c28250eda 100644 --- a/Task/Phrase-reversals/EasyLang/phrase-reversals.easy +++ b/Task/Phrase-reversals/EasyLang/phrase-reversals.easy @@ -5,10 +5,10 @@ func$[] rev a$[] . return a$[] . lin$ = "rosetta code phrase reversal" -print strjoin rev strchars lin$ +print strjoin rev strchars lin$ "" words$[] = strsplit lin$ " " for w$ in words$[] - write strjoin rev strchars w$ + write strjoin rev strchars w$ "" write " " . print "" diff --git a/Task/Pick-random-element/V-(Vlang)/pick-random-element.v b/Task/Pick-random-element/V-(Vlang)/pick-random-element.v index 2b166baed8..c8f880e892 100644 --- a/Task/Pick-random-element/V-(Vlang)/pick-random-element.v +++ b/Task/Pick-random-element/V-(Vlang)/pick-random-element.v @@ -2,5 +2,7 @@ import rand fn main() { list := ["friends", "peace", "people", "happiness", "hello", "world"] - for index in 1..list.len + 1 {println(index.str() + ': ' + list[rand.intn(list.len) or {}])} + for index in 1..list.len + 1 { + println(index.str() + ": " + list[rand.intn(list.len) or {}]) + } } diff --git a/Task/Pinstripe-Display/Nim/pinstripe-display.nim b/Task/Pinstripe-Display/Nim/pinstripe-display.nim index db98319f49..f00d71c49a 100644 --- a/Task/Pinstripe-Display/Nim/pinstripe-display.nim +++ b/Task/Pinstripe-Display/Nim/pinstripe-display.nim @@ -1,60 +1,52 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import gtk2, glib2, gdk2, cairo const Width = 420 Height = 420 -const Colors = [[255.0, 255.0, 255.0], [0.0, 0.0, 0.0]] +const Colors = [(1.0, 1.0, 1.0), (0.0, 0.0, 0.0)] -#--------------------------------------------------------------------------------------------------- -proc draw(area: DrawingArea; context: Context) = +proc onExposeEvent(widget: PWidget; event: PEventExpose; data: Pgpointer): gboolean {.cdecl.} = ## Draw the bars. const lineHeight = Height div 4 + let cr = cairo_create(widget.window) + var y = 0.0 for lineWidth in [1.0, 2.0, 3.0, 4.0]: - context.setLineWidth(lineWidth) + cr.setLineWidth(lineWidth) var x = 0.0 var colorIndex = 0 while x < Width: - context.setSource(Colors[colorIndex]) - context.moveTo(x, y) - context.lineTo(x, y + lineHeight) - context.stroke() + let (r, g, b) = Colors[colorIndex] + cr.setSourceRgb(r, g, b) + cr.moveTo(x, y) + cr.lineTo(x, y + lineHeight) + cr.stroke() colorIndex = 1 - colorIndex x += lineWidth y += lineHeight -#--------------------------------------------------------------------------------------------------- + cr.destroy() -proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = - ## Callback to draw/redraw the drawing area contents. - area.draw(context) - result = true +proc onDestroyEvent(widget: PWidget; data: Pgpointer): gboolean {.cdecl.} = + ## Quit the application. + main_quit() -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +nim_init() +let window = window_new(gtk2.WINDOW_TOPLEVEL) +window.set_title("Pinstripe") - let window = app.newApplicationWindow() - window.setSizeRequest(Width, Height) - window.setTitle("Color pinstripe") +let drawingArea = drawing_area_new() +window.add drawingArea +drawingArea.set_size_request(Width, Height) - # Create the drawing area. - let area = newDrawingArea() - window.add(area) +discard drawingArea.signal_connect("expose-event", SIGNAL_FUNC(onExposeEvent), nil) +discard window.signal_connect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - # Connect the "draw" event to the callback to draw the bars. - discard area.connect("draw", ondraw, pointer(nil)) - - window.showAll() - -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.Pinstripe") -discard app.connect("activate", activate) -discard app.run() +window.show_all() +main() diff --git a/Task/Pinstripe-Printer/Nim/pinstripe-printer.nim b/Task/Pinstripe-Printer/Nim/pinstripe-printer.nim index ac1d287c15..9bd328695e 100644 --- a/Task/Pinstripe-Printer/Nim/pinstripe-printer.nim +++ b/Task/Pinstripe-Printer/Nim/pinstripe-printer.nim @@ -1,19 +1,63 @@ -import gintro/[glib, gobject, gtk, gio, cairo] +import gtk2, glib2, cairo -const Colors = [[255.0, 255.0, 255.0], [0.0, 0.0, 0.0]] +############################################################################### +# Missing declarations needed for print operations. -#--------------------------------------------------------------------------------------------------- +when defined(win32): + const lib = "libgtk-win32-2.0-0.dll" +elif defined(macosx): + const lib = "(libgtk-quartz-2.0.0.dylib|libgtk-x11-2.0.dylib)" +else: + const lib = "libgtk-x11-2.0.so(|.0)" -proc beginPrint(op: PrintOperation; printContext: PrintContext; data: pointer) = - ## Process signal "begin_print", that is set the number of pages to print. - op.setNPages(1) +# Missing type definitions. +type + PrintOperation = PObject + PrintContext = PObject + PrintOperationAction = enum + PRINT_OPERATION_ACTION_PRINT_DIALOG + PRINT_OPERATION_ACTION_PRINT + PRINT_OPERATION_ACTION_PREVIEW + PRINT_OPERATION_ACTION_EXPORT + PrintOperationResult = enum + PRINT_OPERATION_RESULT_ERROR + PRINT_OPERATION_RESULT_APPLY + PRINT_OPERATION_RESULT_CANCEL + PRINT_OPERATION_RESULT_IN_PROGRESS -#--------------------------------------------------------------------------------------------------- +# Missing external procedures. +proc print_operation_new(): PrintOperation {.cdecl, + importc: "gtk_print_operation_new", dynlib: lib.} +proc print_operation_run(op: PrintOperation; action: PrintOperationAction; + parent: PWindow; error: pointer): PrintOperationResult {.cdecl, + importc: "gtk_print_operation_run", dynlib: lib.} +proc set_n_pages(op: PrintOperation; n: gint) {.cdecl, + importc: "gtk_print_operation_set_n_pages", dynlib: lib.} +proc get_cairo_context(printContext: PrintContext): ptr Context {.cdecl, + importc: "gtk_print_context_get_cairo_context", dynlib: lib.} +proc width(printContext: PrintContext): cdouble {.cdecl, + importc: "gtk_print_context_get_width", dynlib: lib.} +proc height(printContext: PrintContext): cdouble {.cdecl, + importc: "gtk_print_context_get_height", dynlib: lib.} -proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data: pointer) = - ## Draw a page. - let context = printContext.getCairoContext() +############################################################################### + +const Colors = [(1.0, 1.0, 1.0), (0.0, 0.0, 0.0)] + + +proc beginPrint(op: PrintOperation; printContext: PrintContext; + data: Pgpointer): gboolean {.cdecl.} = + ## Process "begin_print" signal. + op.setNPages(1) # Print one page. + result = true + + +proc drawPage(op: PrintOperation; printContext: PrintContext; + pageNum: int; data: Pgpointer): gboolean {.cdecl.} = + ## Process "draw_page" signal. + + let context = printContext.get_cairo_context() let lineHeight = printContext.height / 4 var y = 0.0 @@ -22,7 +66,8 @@ proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data var x = 0.0 var colorIndex = 0 while x < printContext.width: - context.setSource(Colors[colorIndex]) + let (r, g, b) = Colors[colorIndex] + context.setSourceRgb(r, g, b) context.moveTo(x, y) context.lineTo(x, y + lineHeight) context.stroke() @@ -30,21 +75,13 @@ proc drawPage(op: PrintOperation; printContext: PrintContext; pageNum: int; data x += lineWidth y += lineHeight -#--------------------------------------------------------------------------------------------------- + result = true -proc activate(app: Application) = - ## Activate the application. - # Launch a print operation. - let op = newPrintOperation() - op.connect("begin_print", beginPrint, pointer(nil)) - op.connect("draw_page", drawPage, pointer(nil)) +nim_init() - # Run the print dialog. - discard op.run(printDialog) - -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.Pinstripe") -discard app.connect("activate", activate) -discard app.run() +# Print the pinstripe. +let op = print_operation_new() +discard op.g_signal_connect("begin_print", G_CALLBACK(begin_print), nil) +discard op.g_signal_connect("draw_page", G_CALLBACK(draw_page), nil) +discard op.print_operation_run(PRINT_OPERATION_ACTION_PRINT_DIALOG, nil, nil) diff --git a/Task/Poker-hand-analyser/FutureBasic/poker-hand-analyser.basic b/Task/Poker-hand-analyser/FutureBasic/poker-hand-analyser.basic new file mode 100644 index 0000000000..1b24f05b77 --- /dev/null +++ b/Task/Poker-hand-analyser/FutureBasic/poker-hand-analyser.basic @@ -0,0 +1,349 @@ +include "Tlbx GameplayKit.incl" + +_window = 1 + +_Deal = 100 +_Four = 101 +_Full = 102 +_flush = 103 +_straight = 104 +_SFlush = 105 +_NewDeck = 106 + +begin globals +int gOmit(52) +int gCount = 1 +int gDeck(4,13) +CFStringRef gSpecial(5) +bool gInsert = NO +bool gNewDeck = NO +end globals + +local fn Set + for int x = 1 to 52):gOmit(x) = x:next +end fn + +//Ken's code +local fn MyImageDrawingHandler( r as CGRect, userData as ptr ) + AttributedStringDrawAtPoint( userData, fn CGPointMake(0,0) ) +end fn = YES + +local fn StringToImage( string as CFStringRef, font as FontRef, color as ColorRef ) as ImageRef + CFDictionaryRef attributes = @{NSFontAttributeName:font,NSForegroundColorAttributeName:color} + CFMutableAttributedStringRef aString = fn MutableAttributedStringWithAttributes( string, attributes ) +end fn = fn ImageWithDrawingHandler( fn AttributedStringSize( aString ), NO, @fn MyImageDrawingHandler, aString ) + +local fn ConvertValueToEmoji( value as long ) as CFStringRef + UInt32 unicodeInt + ScannerRef scanner = fn ScannerWithString( fn StringWithFormat( @"0x%X", value ) ) + fn ScannerScanHexInt( scanner, @unicodeInt ) +end fn = fn StringWithBytes( @unicodeInt, 4, NSUTF32LittleEndianStringEncoding ) + +void local fn BuildWnd + int height = 800 + CGrect rr = fn CGRectMake( 0,0,500,height) + + window _window, @"Assess Poker Hands" , rr + + rr = fn CGRectMake( 10, 60, 90, 26 ) + button _Four,,,@"4 of kind", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _Full,,,@"Full House", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _Flush,,,@"Flush", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _straight,,,@"Straight", rr + rr = fn CGRectOffset( rr, 90, 0 ) + button _sFlush,,,@"S Flush", rr + rr = fn CGRectMake( 120, 20, 100, 26) + button _Deal,,,@"Deal Hand", rr + rr = fn CGRectMake( 240, 20, 200, 26) + checkbox _NewDeck,,,@"New deck each time", rr + textlabel 2,@"Row of buttons to prove the rare hands assess correctly", ( 40, 90, 380, 26 ) + +end fn + +void local fn SetDeck + int x,y + for x = 1 to 13 + for y = 0 to 3 + gDeck(y,x) = (y*13 + 1) + x - 1 + next + next +end fn + +local fn SetCards + NSUInteger i, index, c, j = 1 + CFMutableArrayRef NumbArr = fn MutableArrayNew + + index = 0 : c = 0 + for i = 127137 to 127199 + if ( c == 11 ) + c++ + else + MutableArrayInsertObjectAtIndex( NumbArr, fn StringWithFormat(@"%ld;%d", i, j), index ) + index++ + c++ + j++ + end if + if c mod 14 == 0 && i != 127198 then c = 0 : i += 2 + next + + AppSetProperty( @"Numbers",fn ArrayWithArray( NumbArr ) ) + CFArrayRef Numbers = fn AppProperty( @"Numbers" ) + AppSetProperty( @"NoShuffled",fn ArrayShuffledArray( Numbers )) + +end fn + +local fn GetRandomNo as int + int j,item + Bool check = NO + + do + j = rnd( 52 ) + if gOmit(j) > -1 + item = j + gOmit(j) = -gOmit(j) + check = YES + end if + until check == YES + +end fn = item + +clear local fn AssessHand( cNo(5) as int) as CFStringRef + CFStringRef answer = @"High Card" + int x,y,check + int w,b,col,row,ans(5) + bool checked + + //Sort cards lowest to highest + for x = 1 to 5 + for y = x+1 to 5 + if cNo(y) < cNo(x) then Swap cNo(x), cNo(y) + next + next + + b = 20 + for w = 1 to 5 + for x = 5 to 1 step -1 + for col = 13 to 1 step -1 + for row = 3 to 0 step -1 + if cNo(x) == gDeck(row,col) + if col < b + ans(x) = col + b = 20 + else + end if + end if + next + next + next + next + for x = 1 to 5 + for y = x+1 to 5 + if ans(y) < ans(x) then Swap ans(x), ans(y) + next + next + + //Check for pair, two pair, three of a kind, Four of a kind + if ans(1) == ans(2) && ans(2) == ans(3) && ans(3) == ans(4) then answer = @"Four of a Kind":Exit fn = answer + if ans(2) == ans(3) && ans(3) == ans(4) && ans(4) == ans(5) then answer = @"Four of a Kind":Exit fn = answer + if ans(1) == ans(2) && ans(2) == ans(3) && ans(4) == ans(5) then answer = @"Full House":Exit fn = answer + if ans(1) == ans(2) && ans(3) == ans(4) && ans(4) == ans(5) then answer = @"Full House":Exit fn = answer + if ans(1) == ans(2) && ans(2) == ans(3) then answer = @"three of a kind":Exit fn = answer + if ans(2) == ans(3) && ans(3) == ans(4) then answer = @"three of a kind":Exit fn = answer + if ans(3) == ans(4) && ans(4) == ans(5) then answer = @"three of a kind":Exit fn = answer + if ans(1) == ans(2) && ans(3) == ans(4) then answer = @"two pair":Exit fn = answer + if ans(1) == ans(2) && ans(4) == ans(5) then answer = @"two pair":Exit fn = answer + if ans(1) == ans(2)|| ans(3) == ans(2)|| ans(3) == ans(4) || ans(4) == ans(5) then answer = @"Pair":Exit fn = answer + + + //Check for Straight Flush + if (cNo(1) < 10 && cNo(1) > 0 ) || (cNo(1) < 23 && cNo(1) > 13) || (cNo(1) < 36 && cNo(1) > 26)|| (cNo(1) < 49 && cNo(1) > 39) + if cNo(2) != cNo(1) + 1 + else + if cNo(3) != cNo(2) + 1 + else + if cNo(4) != cNo(3) + 1 + else + if cNo(5) != cNo(4) + 1 + else + answer = @"Straight Flush" + exit fn = answer + end if + end if + end if + end if + end if + + //Check for flush + if (cNo(1) < 10 && cNo(1) > 0 ) || (cNo(1) < 23 && cNo(1) > 13) || (cNo(1) < 36 && cNo(1) > 26)|| (cNo(1) < 49 && cNo(1) > 39) + check = 1 + if (cNo(1) < 10 && cNo(1) > 0 )//Spades + for x = 2 to 5 + if cNo(x) < 13 && cNo(x) > 0 + check++ + end if + next + if check == 5 then answer = @"Flush of Spades" : Exit fn = answer + end if + if (cNo(1) < 23 && cNo(1) > 13 )//Hearts + for x = 2 to 5 + if cNo(x) < 27 && cNo(x) > 13 + check++ + end if + next + if check == 5 then answer = @"Flush of Hearts" : Exit fn = answer + end if + if (cNo(1) < 36 && cNo(1) > 26)//Diamonds + for x = 2 to 5 + if cNo(x) < 40 && cNo(x) > 26 + check++ + end if + next + if check == 5 then answer = @"Flush of Diamonds" : Exit fn = answer + end if + if (cNo(1) < 49 && cNo(1) > 39)//Clubs + for x = 2 to 5 + if cNo(x) < 53 && cNo(x) > 39 + check++ + end if + next + if check == 5 then answer = @"Flush of Clubs" : Exit fn = answer + end if + end if + + //Check for Straight + //Find lowest card ignoring suit + + for x = 5 to 2 step -1 + if (ans(x) - ans(x-1)) == 1 + checked = YES + else + checked = NO + exit next + end if + next + if checked == YES + answer = @"straight" + end if + +end fn = answer + +clear local fn DealHand + CFArrayRef Numb = fn AppProperty( @"NoShuffled" ) + CFStringRef Ans,card,Number + int x, item, CardNo(5), y + CFRange range + + text @"Menlo", 72, fn ColorText + + for x = 1 to 5 + do + if gInsert = YES + ans = gSpecial(x) + else + item = fn GetRandomNo + Ans = Numb[ item] + end if + range = fn StringRangeOfString( Ans, @";" ) + card = fn StringSubstringToIndex( Ans, range.location ) + Number = fn StringSubStringFromIndex( Ans, range.location + 1) + cardNo(x) = fn StringIntValue( Number ) + y = fn StringIntValue( card) + until y != 127199 + if y > 127152 && y < 127185 then text,, fn ColorRed else text,,fn ColorBlack + printf @"%@\b", fn ConvertValueToEmoji( y ) + next + if gNewDeck == YES then fn Set + text @"Times",24, fn ColorMagenta + printf fn AssessHand( cardNo(0)) + printf @"" + text @"Menlo", 72, fn ColorText + gInsert = NO +end fn + +local fn Flush + gSpecial(1) = @"127155;16" + gSpecial(2) = @"127160;21" + gSpecial(3) = @"127153;14" + gSpecial(4) = @"127158;19" + gSpecial(5) = @"127163;24" +end fn + +local fn Four + gSpecial(1) = @"127137;1" + gSpecial(2) = @"127169;27" + gSpecial(3) = @"127153;14" + gSpecial(4) = @"127158;19" + gSpecial(5) = @"127185;40" +end fn + +local fn Full + gSpecial(1) = @"127140;4" + gSpecial(2) = @"127159;20" + gSpecial(3) = @"127175;33" + gSpecial(4) = @"127156;17" + gSpecial(5) = @"127188;43" +end fn + +local fn Straight + gSpecial(1) = @"127158;19" + gSpecial(2) = @"127145;9" + gSpecial(3) = @"127191;46" + gSpecial(4) = @"127178;36" + gSpecial(5) = @"127176;34" +end fn + +local fn SFlush + gSpecial(1) = @"127156;17" + gSpecial(2) = @"127158;19" + gSpecial(3) = @"127160;21" + gSpecial(4) = @"127157;18" + gSpecial(5) = @"127159;20" +end fn + +void local fn doDialog(act as long, ref as long, wnd as long ) + select act + case _btnClick + select ref + case _Newdeck + if fn ButtonState( _NewDeck ) == NSControlStateValueOn then gNewDeck = YES else gNewDeck = NO + case _Deal + if gCount < 11 + fn DealHand + gCount++ + else + cls + fn Set + fn SetDeck + fn SetCards + gCount = 1 + end if + case _Flush + gInsert = YES + fn Flush + case _Four + gInsert = YES + fn Four + case _Full + gInsert = YES + fn Full + case _Straight + gInsert = YES + fn Straight + case _SFlush + gInsert = YES + fn SFlush + end select + end select + +end fn +fn SetDeck +fn SetCards +fn BuildWnd + + +on dialog fn doDialog + +HandleEvents diff --git a/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 b/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 index 95ceb38d34..7e4aed6322 100644 --- a/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 +++ b/Task/Poker-hand-analyser/XPL0/poker-hand-analyser.xpl0 @@ -3,36 +3,36 @@ int Count(1+18); \Counts of ranks and suits in a hand proc ShowCat; \Show category of poker hand int I, J; -[for I:= 1 to 14 do +[for I:= 1 to 10 do [if Count(I) = 1 then [for J:= I+1 to I+4 do \are next 4 cards present? if Count(J) # 1 then J:= 100; if J <= 100 then [Text(0, "straight"); for J:= 15 to 18 do \scan suits - if Count(J) >= 4 then Text(0, "-flush"); + if Count(J) = 5 then Text(0, "-flush"); return; ]; ]; ]; for I:= 15 to 18 do - if Count(I) = 4 then [Text(0, "flush"); return]; -for I:= 1 to 14 do \scan ranks + if Count(I) = 5 then [Text(0, "flush"); return]; +for I:= 2 to 14 do \scan ranks if Count(I) = 4 then [Text(0, "four-of-a-kind"); return]; -for I:= 1 to 14 do +for I:= 2 to 14 do [if Count(I) = 3 then - [for J:= 1 to 14 do + [for J:= 2 to 14 do if Count(J) = 2 then [Text(0, "full-house"); return]; Text(0, "three-of-a-kind"); return; ]; ]; -for I:= 1 to 14 do +for I:= 2 to 14 do [if Count(I) = 2 then - [for J:= 1 to 14 do + [for J:= 2 to 14 do if J # I and Count(J) = 2 then - [Text(0, "two-pairs"); return]; + [Text(0, "two-pair"); return]; Text(0, "one-pair"); return; ]; ]; @@ -71,7 +71,7 @@ for H:= 0 to 9-1 do ^ : [N:= 0; Card:= Card+1; if Card >= 5 then quit] other N:= Char-^0; Count(N):= Count(N)+1; - if N = 14 then Count(1):= Count(1)+1; \two-place ace + if N = 14 then Count(1):= Count(1)+1; \ace in two places if N <= 14 then Rank:= N else [Suit:= N - 15; if Valid(Suit) and 1<= 3 && isodd(n) && all(i -> n % i != 0, 3:2:isqrt(n))) end n = 100 -a = filter(isprime_trialdivision, [1:n]) +a = filter(isprime_trialdivision, 1:n) + +import Primes.primes # for check, use existing library function if all(a .== primes(n)) println("The primes <= ", n, " are:\n ", a) diff --git a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur index 747b0d4414..a0304f5019 100644 --- a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur +++ b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-1.langur @@ -1,6 +1,6 @@ val isPrime = fn(i) { i == 2 or i > 2 and - not any(fn x:i div x, pseries(2 .. i ^/ 2)) + not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x) } -writeln filter(isPrime, series(100)) +writeln filter(series(100), by=isPrime) diff --git a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur index 678610b891..5e876b0618 100644 --- a/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur +++ b/Task/Primality-by-trial-division/Langur/primality-by-trial-division-2.langur @@ -12,4 +12,4 @@ val isPrime = fn(i) { return n ndiv 2 and chkdiv(n, 3) } -writeln filter(isPrime, series(100)) +writeln filter(series(100), by=isPrime) diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/FreeBASIC/primes---allocate-descendants-to-their-ancestors.basic b/Task/Primes---allocate-descendants-to-their-ancestors/FreeBASIC/primes---allocate-descendants-to-their-ancestors.basic new file mode 100644 index 0000000000..12fa00a865 --- /dev/null +++ b/Task/Primes---allocate-descendants-to-their-ancestors/FreeBASIC/primes---allocate-descendants-to-their-ancestors.basic @@ -0,0 +1,107 @@ +Type NumberList + As Integer count + As Ulongint values(50000) +End Type + +Sub AddToList(Byref list As NumberList, value As Ulongint) + list.values(list.count) = value + list.count += 1 +End Sub + +Function GetPrimes(max As Integer) As NumberList + Dim primes As NumberList + + If max < 2 Then Return primes + + AddToList(primes, 2) + Dim As Integer i, j + For j = 3 To max Step 2 + Dim As Boolean isPrime = True + For i = 0 To primes.count - 1 + If j Mod primes.values(i) = 0 Then + isPrime = False + Exit For + End If + Next + If isPrime Then AddToList(primes, j) + Next + Return primes +End Function + +Sub SortList(Byref list As NumberList) + Dim As Integer i, j + For i = 0 To list.count - 2 + For j = i + 1 To list.count - 1 + If list.values(i) > list.values(j) Then + Swap list.values(i), list.values(j) + End If + Next + Next +End Sub + +Const maxSum = 99 +Dim Shared As NumberList descendants(maxSum), ancestors(maxSum) +Dim primes As NumberList = GetPrimes(maxSum) +Dim As Integer p, s, d + +' Calculate descendants +For p = 0 To primes.count - 1 + Dim As Ulongint prime = primes.values(p) + AddToList(descendants(prime), prime) + + For s = 1 To maxSum - prime + For d = 0 To descendants(s).count - 1 + Dim As Ulongint newDesc = prime * descendants(s).values(d) + AddToList(descendants(s + prime), newDesc) + Next + Next +Next + +' Remove last element from prime descendants and 4 +For s = 0 To primes.count - 1 + p = primes.values(s) + If descendants(p).count > 0 Then descendants(p).count -= 1 +Next +If descendants(4).count > 0 Then descendants(4).count -= 1 + +' Calculate totals and print results +Dim As Integer total = 0 +For s = 1 To maxSum + SortList(descendants(s)) + total += descendants(s).count + + ' Calculate ancestors for current s + For d = 0 To descendants(s).count - 1 + If descendants(s).values(d) <= maxSum Then + ' Add all ancestors from previous calculations + For p = 0 To ancestors(s).count - 1 + AddToList(ancestors(descendants(s).values(d)), ancestors(s).values(p)) + Next + ' Add current value as ancestor + AddToList(ancestors(descendants(s).values(d)), s) + End If + Next + + If s < 21 Or s = 46 Or s = 74 Or s = maxSum Then + Print Using "##: "; s; + Print ancestors(s).count; " Ancestors[s]: ["; + For p = 0 To ancestors(s).count - 1 + Print ancestors(s).values(p); + If p < ancestors(s).count - 1 Then Print ", "; + Next + Print "] " & Iif(s = 46 Or s = 74, !"\t", !"\t\t"); + + Print Using "#####"; descendants(s).count; + Print " Descendants[s]: ["; + For p = 0 To Iif(descendants(s).count > 10, 9, descendants(s).count - 1) + Print descendants(s).values(p); + If p < Iif(descendants(s).count > 10, 9, descendants(s).count - 1) Then Print ", "; + Next + If descendants(s).count > 10 Then Print ", ..."; + Print "]" + End If +Next + +Print !"\nTotal descendants "; total + +Sleep diff --git a/Task/Primorial-numbers/REXX/primorial-numbers-1.rexx b/Task/Primorial-numbers/REXX/primorial-numbers-1.rexx deleted file mode 100644 index 78b99be865..0000000000 --- a/Task/Primorial-numbers/REXX/primorial-numbers-1.rexx +++ /dev/null @@ -1,43 +0,0 @@ -/*REXX program computes some primorial numbers for low numbers, and for various 10^n.*/ -parse arg N H . /*get optional arguments: N, L, H */ -if N=='' | N==',' then N= 10 /*Not specified? Then use the default.*/ -if H=='' | H==',' then H= 100000 /* " " " " " " */ -numeric digits 600000 /*be able to handle gihugic numbers. */ -w= length( commas( digits() ) ) /*W: width of the largest commatized #*/ -@.=.; @.0= 1; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13 /*some low primes.*/ - s.1= 4; s.2= 9; s.3= 25; s.4= 49; s.5= 121; s.6= 169 /*squared primes. */ -#= 6 /*number of primes*/ - do j=0 for N /*calculate the first N primorial #s.*/ - say right(j, length(N))th(j) " primorial is: " right(commas(primorial(j) ), N+2) - end /*j*/ -say -iw= length( commas(H) ) + 2 /*IW: width of largest commatized index*/ -p= 1 /*initialize the first multiplier for P*/ - do k=1 for H /*process a large range of numbers. */ - p= p * prime(k) /*calculate the next primorial number. */ - parse var k L 2 '' -1 R /*get the left and rightmost dec digits*/ - if R\==0 then iterate /*if right─most decimal digit\==0, skip*/ - if L\==1 then iterate /* " left─most " " \==1, " */ - if strip(k, , 0)\==1 then iterate /*Not a power of 10? Then skip this K.*/ - say right( commas(k), iw)th(k) ' primorial number length in decimal digits is:' , - right( commas( length(p) ), w) - end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ -th: parse arg th; return word('th st nd rd', 1+ (th//10)*(th//100%10\==1)*(th//10<4)) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -primorial: procedure expose @. s. #; parse arg y; != 1 /*obtain the arg Y. */ - do p=0 to y; != ! * prime(p) /*calculate product. */ - end /*p*/; return ! /*return with the #. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -prime: procedure expose @. s. #; parse arg n; if @.n\==. then return @.n - numeric digits 9 /*limit digs to min.*/ - do j=@.#+2 by 2 /*start looking at #*/ - if j//2==0 then iterate; if j//3==0 then iterate /*divisible by 2│3 ?*/ - parse var j '' -1 _; if _==5 then iterate /*right─most dig≡5? */ - if j//7==0 then iterate; if j//11==0 then iterate /*divisible by 7│11?*/ - do k=6 while s.k<=j; if j//@.k==0 then iterate j /*divide by primes. */ - end /*k*/ - #= # + 1; @.#= j; s.#= j * j; return j /*next prime; return*/ - end /*j*/ diff --git a/Task/Primorial-numbers/REXX/primorial-numbers-2.rexx b/Task/Primorial-numbers/REXX/primorial-numbers.rexx similarity index 98% rename from Task/Primorial-numbers/REXX/primorial-numbers-2.rexx rename to Task/Primorial-numbers/REXX/primorial-numbers.rexx index a6a829a8bd..9d9a7fbf57 100644 --- a/Task/Primorial-numbers/REXX/primorial-numbers-2.rexx +++ b/Task/Primorial-numbers/REXX/primorial-numbers.rexx @@ -57,7 +57,7 @@ say 'Number of digits by summing log10:' numeric digits 10 a = 0; e = 0 do i = 1 to x - a = a+Log(prim.prime.i) + a = a+Log10(prim.prime.i) f = Xpon(i) if f <> e then do say 'Primorial(10^'f') has' Trunc(a)+1 'digits' diff --git a/Task/Primorial-numbers/XPL0/primorial-numbers.xpl0 b/Task/Primorial-numbers/XPL0/primorial-numbers.xpl0 new file mode 100644 index 0000000000..feab78830a --- /dev/null +++ b/Task/Primorial-numbers/XPL0/primorial-numbers.xpl0 @@ -0,0 +1,41 @@ +func IsPrime(N); \Return 'true' if N >= 3 is prime +int N, D; +[if rem(N/3) = 0 then return N = 3; +D:= 5; +while D*D <= N do + [if rem(N/D) = 0 then return false; + D:= D+2; + if rem(N/D) = 0 then return false; + D:= D+4; + ]; +return true; +]; + +int Prod, Num, Count, Limit; +real Sum; +[IntOut(0, 1); ChOut(0, ^ ); + IntOut(0, 2); ChOut(0, ^ ); +Prod:= 2; Num:= 3; Count:= 1; +loop [if IsPrime(Num) then + [Prod:= Prod*Num; + IntOut(0, Prod); ChOut(0, ^ ); + Count:= Count+1; + if Count >= 9 then quit; + ]; + Num:= Num+2; + ]; +CrLf(0); +Num:= 3; Count:= 1; Sum:= Log(2.); Limit:= 10; +loop [if IsPrime(Num) then + [Sum:= Sum + Log(float(Num)); + Count:= Count+1; + if Count = Limit then + [IntOut(0, fix(Sum-0.5)+1); ChOut(0, ^ ); + if Limit >= 1_000_000 then quit; + Limit:= Limit*10; + ]; + ]; + Num:= Num+2; + ]; +CrLf(0); +] diff --git a/Task/Probabilistic-choice/F-Sharp/probabilistic-choice.fs b/Task/Probabilistic-choice/F-Sharp/probabilistic-choice.fs new file mode 100644 index 0000000000..509ef1ee9a --- /dev/null +++ b/Task/Probabilistic-choice/F-Sharp/probabilistic-choice.fs @@ -0,0 +1,20 @@ +// Probabilistic choice. Nigel Galloway: November 15th., 2024 +type items=Aleph|Beth|Gimel|Daleth|He|Waw|Zayin|Heth +let item=function n when n<5544 ->Aleph + |n when n<10164->Beth + |n when n<14124->Gimel + |n when n<17589->Daleth + |n when n<20669->He + |n when n<23441->Waw + |n when n<25961->Zayin + |_->Heth +let R=System.Random() +let expected=function Aleph ->1000000/5 + |Beth ->1000000/6 + |Gimel ->1000000/7 + |Daleth->1000000/8 + |He ->1000000/9 + |Waw ->1000000/10 + |Zayin ->1000000/11 + |Heth ->(1000000*1759)/27720 +Seq.init 1000000 (fun _->R.Next(0,27720))|>Seq.countBy item|>Seq.iter(fun(n,g)->printfn $"item={n} count={g} expected={expected n}") diff --git a/Task/Probabilistic-choice/Free-Pascal-Lazarus/probabilistic-choice.pas b/Task/Probabilistic-choice/Free-Pascal-Lazarus/probabilistic-choice.pas new file mode 100644 index 0000000000..5b5bceaf43 --- /dev/null +++ b/Task/Probabilistic-choice/Free-Pascal-Lazarus/probabilistic-choice.pas @@ -0,0 +1,61 @@ +program Probablistic; +const + rounds = 1000*1000; + names : array[0..7] of string =('aleph','beth','gimel','daleth','he','waw','zayin','heth'); + quotient = 5*6*7*8*9*10*11; + RezValues: array[0..7] of integer=(5,6,7,8,9,10,11,0); +//remaining heth = 27720/1759 + +function GCD(a, b: Int64): Int64; +var + temp: Int64; +begin + while b <> 0 do + begin + temp := b; + b := a mod b; + a := temp + end; + Exit(a); +end; + +var + cnt : array of Uint32; + i ,z,n,tmp,idx,lmt : NativeInt; + sumTot : NativeUint; +begin + randomize; + z := 0; + n := 1; + For i := 0 to 6 do + begin + z := z*RezValues[i]+n; + n := n*RezValues[i]; + tmp := GCD(z,n); + z := z div tmp; + n := n div tmp; + end; + + //create the values + setlength(cnt,n+1); + For i := 1 to rounds do + inc(cnt[trunc(random()*n)]); + //count occurences in range + writeln('Item':9,'expected':10,'actual':10); + sumTot := 0; + idx := 0; + lmt := 0; + For i := 0 to 6 do + begin + lmt += n DIV RezValues[i]; + tmp := 0; + repeat + inc(tmp,cnt[idx]); + inc(idx); + until idx >= lmt; + sumTot += tmp; + writeln(names[i]:9,1/RezValues[i]:10:6,tmp/rounds:10:6); + end; + //the remaining for heth + writeln(names[7]:9,(n-z)/n:10:6,1-sumTot/rounds:10:6); +end. diff --git a/Task/Program-name/Langur/program-name.langur b/Task/Program-name/Langur/program-name.langur deleted file mode 100644 index b6e3033cd4..0000000000 --- a/Task/Program-name/Langur/program-name.langur +++ /dev/null @@ -1,2 +0,0 @@ -writeln "script: ", _script -writeln "script args: ", _args diff --git a/Task/Proper-divisors/Langur/proper-divisors.langur b/Task/Proper-divisors/Langur/proper-divisors.langur index eec521545d..60bddb48d4 100644 --- a/Task/Proper-divisors/Langur/proper-divisors.langur +++ b/Task/Proper-divisors/Langur/proper-divisors.langur @@ -11,6 +11,8 @@ val listproper = fn(x) { writeln "The proper divisors of the following numbers are :" writeln listproper(10) +exit 0 + var mx = 0 var most = [] for n in 2 .. 20_000 { @@ -22,5 +24,5 @@ for n in 2 .. 20_000 { } } -writeln "The following number(s) <= 20000 have the most proper divisors ({{mx}})" +writeln "The following number(s) <= 20000 have the most proper divisors ({{max}})" writeln most diff --git a/Task/Pseudo-random-numbers-Middle-square-method/M2000-Interpreter/pseudo-random-numbers-middle-square-method.m2000 b/Task/Pseudo-random-numbers-Middle-square-method/M2000-Interpreter/pseudo-random-numbers-middle-square-method.m2000 new file mode 100644 index 0000000000..23210c3717 --- /dev/null +++ b/Task/Pseudo-random-numbers-Middle-square-method/M2000-Interpreter/pseudo-random-numbers-middle-square-method.m2000 @@ -0,0 +1,25 @@ +Module Pseudo_random_numbers { + random = lambda seed = 675248 -> { + string s = str$(seed * seed,"") + while not len(s) = 12 + s = "0" + s + end while + seed = val(mid$(s, 4, 6)) + =seed + } + for i=1 to 5 + print random() + next +} +Pseudo_random_numbers +' same without using strings (we use long long numbers - bit) +Module Pseudo_random_numbers { + random = lambda seed = 675248&& -> { + seed = seed^2 div 1000&& mod 1000000&& + =seed + } + for i=1 to 5 + print random() + next +} +Pseudo_random_numbers diff --git a/Task/Pseudo-random-numbers-Middle-square-method/X86-64-Assembly/pseudo-random-numbers-middle-square-method.x86-64 b/Task/Pseudo-random-numbers-Middle-square-method/X86-64-Assembly/pseudo-random-numbers-middle-square-method.x86-64 new file mode 100644 index 0000000000..00d2569868 --- /dev/null +++ b/Task/Pseudo-random-numbers-Middle-square-method/X86-64-Assembly/pseudo-random-numbers-middle-square-method.x86-64 @@ -0,0 +1,64 @@ +format ELF64 executable 3 +entry begin + +define seed 675248 +define iterations 5 + +segment executable readable +begin: + mov rax, seed + mov rsi, iterations + .loop0: + mul rax + xor rdx, rdx + mov rdi, 1000000000 + div rdi + mov rax, rdx + xor rdx, rdx + mov rdi, 1000 + div rdi + mov rdi, rax + call printq + dec rsi + jnz .loop0 + .end: + mov rax, 60 + xor rdi, rdi + syscall +printq: + push rax + push rsi + sub rsp, 24 + mov byte[rsp + 23], 0x0a + mov r8, 22 + mov rsi, 10 + mov rax, rdi + or rax, rax + jns .loop0 + neg rax + .loop0: + xor rdx, rdx + div rsi + add rdx, '0' + mov byte[rsp + r8], dl + or rax, rax + jz .check + dec r8 + jmp .loop0 + .check: + or rdi, rdi + jns .out0 + dec r8 + mov byte[rsp + r8], '-' + .out0: + mov rax, 1 + mov rdi, 1 + mov rsi, rsp + add rsi, r8 + mov rdx, 24 + sub rdx, r8 + syscall + add rsp, 24 + pop rsi + pop rax + ret diff --git a/Task/Pseudo-random-numbers-Splitmix64/Standard-ML/pseudo-random-numbers-splitmix64.ml b/Task/Pseudo-random-numbers-Splitmix64/Standard-ML/pseudo-random-numbers-splitmix64.ml new file mode 100644 index 0000000000..e92140d2b9 --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/Standard-ML/pseudo-random-numbers-splitmix64.ml @@ -0,0 +1,98 @@ +structure SplitMix64 = +struct + structure W64 = Word64 + + val randmax = (0wxFFFFFFFFFFFFFFFF : W64.word) + + (* if NONE is passed, seed using the current time *) + fun init NONE = + W64.fromLargeInt (Time.toNanoseconds (Time.now ())) + | init (SOME x) = x + (* takes the state and returns a tuple of the + * new state and the random number *) + fun next instate = + let + val newstate = instate + 0wx9e3779b97f4a7c15 + val z1 = W64.xorb (newstate, W64.>> (newstate, 0w30)) + val z2 = z1 * 0wxbf58476d1ce4e5b9 + val z3 = W64.xorb (z2, W64.>> (z2, 0w27)) + val z4 = z3 * 0wx94d049bb133111eb + in + (newstate, W64.xorb (z4, W64.>> (z4, 0w31))) + end + (* need to use LargeInt to fit the values *) + fun nextInt instate = + let + val (newstate, res) = next instate + val intres = W64.toLargeInt res + in + (newstate, intres) + end + fun nextReal instate = + let + val (newstate, res) = next instate + val realres = Real.fromLargeInt (W64.toLargeInt (res)) + in + (* divide by 2^64 *) + (newstate, realres * (1.0 / 18446744073709551616.0)) + end + (* gets the next number in the range min <= x < max without bias *) + fun nextRange instate (min, max) = + let + val minword = W64.fromInt min + val maxword = W64.fromInt max + val maxfromzero = maxword - minword + val ignored_range = randmax - randmax mod maxword + val (newstate, res) = next instate + in + if res >= ignored_range then nextRange newstate (min, max) + else (newstate, (res mod maxword) + minword) + end +end + +(* produce a list of n random ints using given seed *) +fun getRandIntList (seed, n) = + let + val init = SplitMix64.init seed + fun aux (0, acc, _) = rev acc + | aux (n, acc, state) = + let val (newstate, res) = SplitMix64.nextInt state + in aux (n - 1, res :: acc, newstate) + end + in + aux (n, [], init) + end + +fun testNextReal (seed, n) = + let + val hist = Array.array (n, 0) + val nreal = Real.fromInt n + fun loopFn 0 _ = () + | loopFn n state = + let + val (newstate, res) = SplitMix64.nextReal state + val idx = Real.floor (res * nreal) + val old_count = Array.sub (hist, idx) + in + (Array.update (hist, idx, old_count + 1); loopFn (n - 1) newstate) + end + val () = loopFn 100000 (SplitMix64.init seed) + in + Array.foldri + (fn (i, x, l) => + (String.concat [Int.toString i, ": ", Int.toString x]) :: l) [] hist + end + +fun main () = + let + val five_ints = getRandIntList (0w1234567, 5) + val () = app (print o (fn s => s ^ "\n") o LargeInt.toString) five_ints + val () = print "\n" + val hist_list = testNextReal (0w987654321, 5) + val () = print (String.concatWith ", " hist_list) + val () = print "\n" + in + () + end + +val () = main () diff --git a/Task/Pseudo-random-numbers-Xorshift-star/M2000-Interpreter/pseudo-random-numbers-xorshift-star.m2000 b/Task/Pseudo-random-numbers-Xorshift-star/M2000-Interpreter/pseudo-random-numbers-xorshift-star.m2000 new file mode 100644 index 0000000000..e756842fbc --- /dev/null +++ b/Task/Pseudo-random-numbers-Xorshift-star/M2000-Interpreter/pseudo-random-numbers-xorshift-star.m2000 @@ -0,0 +1,86 @@ +module Pseudo_random_numbers{ + class Xorshift_star{ + private: + Decimal state=int(rnd*0x2000_0000_0000_0000) ' Must be seeded to non-zero initial value + final MAGIC=0x2545F4914F6CDD1D + function xorU64(x, y) { + const dec1=0x1_0000_0000 + x_u=x div dec1 + x_d=x mod dec1 + y_u=y div dec1 + y_d=y mod dec1 + =binary.xor(x_u, y_u)*dec1+binary.xor(x_d, y_d) + } + function ShiftRightU64(x, y) { + boolean skip + const dec1=0x1_0000_0000 + if y>31 then y=y-32:skip=true + y=-abs(y) + x_u=x div dec1 + if skip then + = binary.shift(x_u, y) + else + x_d=x mod dec1 + f1= binary.not(binary.shift(0xFFFF_FFFF, y)) + f2= binary.and(binary.rotate(x_u, y), f1) + = binary.shift(x_u, y)*dec1+binary.shift(x_d, y)+f2 + end if + } + function ShiftLeftU64(x, y) { + boolean skip + y=abs(y) + const dec1=0x1_0000_0000 + if y>31 then y=y-32:skip=true + x_d=x mod dec1 + if skip then + =binary.shift(x_d, y)*dec1 + else + f1= binary.not(binary.shift(0xFFFF_FFFF, y)) + f2= binary.and(binary.rotate(x_d, y), f1)*dec1 + x_u=x div dec1 + = binary.shift(x_u, y)*dec1+binary.shift(x_d, y)+f2 + end if + } + function mul64to32(x, y) { + const dd=0x1_0000_0000 + long long a=x mod dd, b=x div dd + long long a1=y mod dd, b1=y div dd + decimal mm=0 + p1=a*a1 + mm+=p1 + p1=(b*a1+a*b1) mod dd + mm+=p1*dd + =(mm div dd) mod dd + } + public: + module seed(num as decimal) { + .state <= int(abs(num)) + } + function next_int() { + x =.state + x = .xorU64(x, .ShiftRightU64(x, 12)) + x = .xorU64(x, .ShiftLeftU64(x, 25)) + x = .xorU64(x, .ShiftRightU64(x, 27)) + .state <= x + =.mul64to32(x, .MAGIC) + } + function next_float() { + = .next_int() /0x1_0000_0000 + } + } + k=Xorshift_star() + k.seed 1234567 + Print k.next_int() + Print k.next_int() + Print k.next_int() + Print k.next_int() + Print k.next_int() + k.seed 987654321 + dim hist(5) + for i=1 to 100_000:hist(floor(k.next_float()*5))++:next + z=each(hist()) + while z + print z^;": "; array(z) + end while +} +Pseudo_random_numbers diff --git a/Task/Pseudo-random-numbers-Xorshift-star/Quackery/pseudo-random-numbers-xorshift-star.quackery b/Task/Pseudo-random-numbers-Xorshift-star/Quackery/pseudo-random-numbers-xorshift-star.quackery new file mode 100644 index 0000000000..27f15ca184 --- /dev/null +++ b/Task/Pseudo-random-numbers-Xorshift-star/Quackery/pseudo-random-numbers-xorshift-star.quackery @@ -0,0 +1,25 @@ + [ $ "bigrat.qky" loadfile ] now! + + [ ' [ stack ] swap join nested + ' [ dup share + dup 12 >> ^ + dup 25 << 64bits ^ + dup 27 >> ^ + dup rot replace + hex 2545F4914F6CDD1D + * 64bits 32 >> ] join ] is makerand ( --> [ ) + + [ ]'[ 0 peek replace ] is reseed ( x --> ) + + [ [ 32 bit ] constant reduce ] is vrand ( n --> n/d ) + + [ 1234567 makerand ] maker is rand1 ( --> n ) + + 5 times [ rand1 echo cr ] + cr + 987654321 reseed rand1 + 0 5 of + 100000 times + [ rand1 vrand 5 1 v* / + 2dup peek 1+ unrot poke ] + echo diff --git a/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js b/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js index d523e5bf33..8e9c4abb97 100644 --- a/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js +++ b/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js @@ -1,14 +1,10 @@ -let base = [[{ x: -200, y: 0 }, { x: 200, y: 0 }]]; -const doc = [...Array(12)].reduce((doc_a, _, lvl) => { - const rg = step => `0${(80 + (lvl - 2) * step).toString(16)}`.slice(-2); - return doc_a + base.splice(0).reduce((ga, [a, b]) => { - const w = (kx, ky) => (kx * (b.x - a.x) + ky * (b.y - a.y)) / 2; - const [c, e, d] = [2, 3, 2].map((j, i) => ({ x: a.x + w(i, j), y: a.y + w(-j, i) })); +const base = [[[-200, 0], [200, 0]],]; +document.documentElement.innerHTML = [...Array(12)].reduce((svg_a, _, lvl) => { + const rg = step => (80 + (lvl - 2) * step) & 255; + return svg_a + base.splice(0).reduce((g_a, [a, b]) => { + const w = (k0, k1) => (k0 * (b[0] - a[0]) + k1 * (b[1] - a[1])) / 2; + const [c, e, d] = [2, 3, 2].map((j, i) => [a[0] + w(i, j), a[1] + w(-j, i)]); base.push([c, e], [e, d]); - return ga + `\n`; - }, `\n`) + '\n'; -}, '\n') + ''; - -const { x, y } = base.flat().reduce((a, p) => ({ x: Math.min(a.x, p.x), y: Math.min(a.y, p.y) })); -const svg = doc.replace('`; + }, ``) + ''; +}, '') + '', ""; diff --git a/Task/Quickselect-algorithm/R/quickselect-algorithm.r b/Task/Quickselect-algorithm/R/quickselect-algorithm.r new file mode 100644 index 0000000000..3080e241a5 --- /dev/null +++ b/Task/Quickselect-algorithm/R/quickselect-algorithm.r @@ -0,0 +1,21 @@ +quickselect <- function(vec, k) { + stopifnot(k > 0, k <= length(vec)) + repeat { + pivot_index <- sample.int(length(vec), 1) + pivot_value <- vec[[pivot_index]] + left <- vec[vec < pivot_value] + right <- vec[vec > pivot_value] + pivot_index <- length(left) + 1 + if (k == pivot_index) { + return(pivot_value) + } else if (k < pivot_index) { + vec <- left + } else { + k <- k - pivot_index + vec <- right + } + } +} + +vec <- c(9, 8, 7, 6, 5, 0, 1, 2, 3, 4) +print(sapply(1:10, quickselect, vec = vec)) diff --git a/Task/Radical-of-an-integer/Arturo/radical-of-an-integer.arturo b/Task/Radical-of-an-integer/Arturo/radical-of-an-integer.arturo new file mode 100644 index 0000000000..34f235ef96 --- /dev/null +++ b/Task/Radical-of-an-integer/Arturo/radical-of-an-integer.arturo @@ -0,0 +1,15 @@ +radical: $[n]-> product unique factors.prime n + +(1..50) | map => radical + | split.every:10 + | map => [join map & 'r -> pad to :string r 4] + | print.lines + +print "" +loop [99999, 499999, 999999] 'r -> + print ["Radical of" r "->" radical r] +print "" + +(1..1000000) | map => [size unique factors.prime &] + | tally + | loop [k,v] -> print [k ":" v] diff --git a/Task/Radical-of-an-integer/Kotlin/radical-of-an-integer.kts b/Task/Radical-of-an-integer/Kotlin/radical-of-an-integer.kts new file mode 100644 index 0000000000..3869cef59d --- /dev/null +++ b/Task/Radical-of-an-integer/Kotlin/radical-of-an-integer.kts @@ -0,0 +1,64 @@ +import java.util.BitSet +import java.util.TreeMap +import kotlin.math.sqrt + +class Radicals(val limit: Int) { + val primes: List + val radicals: IntArray // valid indices: 1..limit + val distinctPrimeFactorCounts: IntArray // valid indices: 2..limit + val distinctPrimeFactorCountDistribution: Map + + init { + // Sieve + val composites = BitSet() + for (i in 2..sqrt(limit.toDouble()).toInt()) { + if (!composites[i]) { + for (j in i * i..limit step i) composites.set(j) + } + } + primes = (2..limit).filterNot(composites::get) + + // Calculate radicals and distinct prime factor counts + distinctPrimeFactorCounts = IntArray(limit + 1) { 0 } + radicals = IntArray(limit + 1) { 1 } + for (p in primes) { + for (i in p..limit step p) { + distinctPrimeFactorCounts[i]++ + radicals[i] *= p + } + } + + distinctPrimeFactorCountDistribution = + distinctPrimeFactorCounts.asList() + .subList(2, distinctPrimeFactorCounts.size) + .groupingBy { it } + .eachCountTo(TreeMap()) + } +} + +fun main() { + with(Radicals(limit = 1_000_000)) { + println("Radicals of first 50 positive integers:") + for (i in 1..41 step 10) { + println((i..i + 9).joinToString(separator = " ") { "%2d".format(radicals[it]) }) + } + println() + + for (n in listOf(99_999, 499_999, 999_999)) { + println("Radical for %6d: %6d".format(n, radicals[n])) + } + println() + + println("Distribution of the first $limit positive integers by numbers of distinct prime factors:") + for ((i, count) in distinctPrimeFactorCountDistribution) { + println("%d: %6d".format(i, count)) + } + println() + + println("Number of primes and powers of primes less than or equal to $limit:") + val count = primes.sumOf { prime -> + generateSequence(limit) { it / prime }.takeWhile { it >= prime }.count() + } + println(count) + } +} diff --git a/Task/Ramanujan-primes-twins/Python/ramanujan-primes-twins.py b/Task/Ramanujan-primes-twins/Python/ramanujan-primes-twins.py new file mode 100644 index 0000000000..31e760dcef --- /dev/null +++ b/Task/Ramanujan-primes-twins/Python/ramanujan-primes-twins.py @@ -0,0 +1,105 @@ +import math + +def ramanujan_maximum(number: int): + return math.ceil(4 * number * math.log(4 * number)) + +def initialise_prime_pi(limit: int): + result = [1] * limit + result[0] = 0 + result[1] = 0 + + for i in range(4, limit, 2): + result[i] = 0 + + p = 3 + square = 9 + + while square < limit: + if result[p] != 0: + q = square + + while q < limit: + result[q] = 0 + q += p << 1 + + square += (p + 1) << 2 + p += 2 + + for i in range(1, len(result)): + result[i] += result[i - 1] + + return result + +def ramanujan_prime(prime_pi: list[int], number: int): + maximum = ramanujan_maximum(number) + + if maximum & 1 == 1: + maximum -= 1 + + index = maximum + + while prime_pi[index] - prime_pi[index // 2] >= number: + index -= 1 + + return index + 1 + +def list_primes_less_than(limit: int): + composite = [False] * limit + n = 3 + n_squared = 9 + + while n_squared <= limit: + if not composite[n]: + k = n_squared + + while k < limit: + composite[k] = True + k += 2 * n + + n_squared += (n + 1) << 2 + n += 2 + + result = [2] + + for i in range(3, limit, 2): + if not composite[i]: + result.append(i) + + return result + +def main(): + limit = 1_000_000 + prime_pi = initialise_prime_pi(ramanujan_maximum(limit) + 1) + millionth_ramanujan_prime = ramanujan_prime(prime_pi, limit) + print("The 1_000_000th Ramanujan prime is", millionth_ramanujan_prime) + + primes = list_primes_less_than(millionth_ramanujan_prime) + ramanujan_prime_indexes = [0] * len(primes) + + for i in range(len(ramanujan_prime_indexes)): + ramanujan_prime_indexes[i] = prime_pi[primes[i]] - prime_pi[primes[i] // 2] + + lower_limit = ramanujan_prime_indexes[len(ramanujan_prime_indexes) - 1] + + for i in range(len(ramanujan_prime_indexes) - 2, -1, -1): + if ramanujan_prime_indexes[i] < lower_limit: + lower_limit = ramanujan_prime_indexes[i] + else: + ramanujan_prime_indexes[i] = 0 + + ramanujan_primes = [] + + for i in range(len(ramanujan_prime_indexes)): + if ramanujan_prime_indexes[i] != 0: + ramanujan_primes.append(primes[i]) + + twins_count = 0 + + for i in range(len(ramanujan_primes) - 1): + if ramanujan_primes[i] + 2 == ramanujan_primes[i + 1]: + twins_count += 1 + + print("There are", twins_count, "twins in the first", limit, "Ramanujan primes.") + +if __name__ == '__main__': + main() diff --git a/Task/Random-number-generator-device-/Atari-BASIC/random-number-generator-device-.basic b/Task/Random-number-generator-device-/Atari-BASIC/random-number-generator-device-.basic new file mode 100644 index 0000000000..5b062d820f --- /dev/null +++ b/Task/Random-number-generator-device-/Atari-BASIC/random-number-generator-device-.basic @@ -0,0 +1,5 @@ +10 X=0 +20 FOR I=0 TO 3 +30 X=X+PEEK(53770)*(256^I) +40 NEXT I +50 PRINT X diff --git a/Task/Random-number-generator-device-/Commodore-BASIC/random-number-generator-device-.basic b/Task/Random-number-generator-device-/Commodore-BASIC/random-number-generator-device-.basic new file mode 100644 index 0000000000..1b70494db1 --- /dev/null +++ b/Task/Random-number-generator-device-/Commodore-BASIC/random-number-generator-device-.basic @@ -0,0 +1,8 @@ +10 POKE 54286,255 +20 POKE 54287,255 +30 POKE 54290,128 +40 X=0 +50 FOR I=0 TO 3 +60 X=X+PEEK(54299)*(256^I) +70 NEXT +80 PRINT X diff --git a/Task/Range-expansion/FutureBasic/range-expansion.basic b/Task/Range-expansion/FutureBasic/range-expansion.basic new file mode 100644 index 0000000000..193ed1191f --- /dev/null +++ b/Task/Range-expansion/FutureBasic/range-expansion.basic @@ -0,0 +1,26 @@ +CFStringRef local fn ExpandRanges( string as CFStringRef ) + CFArrayRef ranges = fn StringComponentsSeparatedByString( string, @"," ) + CFStringRef expanded = @"" + for CFStringRef s in ranges + ScannerRef scanner = fn ScannerWithString( s ) + long first, last + if ( fn ScannerScanInteger( scanner, @first ) ) + if ( len(expanded) ) then expanded = concat(expanded,@", ") + expanded = concat(expanded,@(first)) + end if + if ( !fn ScannerIsAtEnd( scanner ) ) + if ( fn ScannerScanString( scanner, @"-", NULL ) ) + if ( fn ScannerScanInteger( scanner, @last ) ) + for long i = first + 1 to last + if ( len(expanded) ) then expanded = concat(expanded,@", ") + expanded = concat(expanded,@(i)) + next + end if + end if + end if + next +end fn = expanded + +print fn ExpandRanges( @"-6,-3--1,3-5,7-11,14,15,17-20" ) + +HandleEvents diff --git a/Task/Range-extraction/FutureBasic/range-extraction.basic b/Task/Range-extraction/FutureBasic/range-extraction.basic new file mode 100644 index 0000000000..0c69b04582 --- /dev/null +++ b/Task/Range-extraction/FutureBasic/range-extraction.basic @@ -0,0 +1,46 @@ +void local fn DoRangeExtraction + CFArrayRef nums = @[ + @0 , @1 , @2 , @4 , @6 , @7 , @8 , @11, @12, @14, + @15, @16, @17, @18, @19, @20, @21, @22, @23, @24, + @25, @27, @28, @29, @30, @31, @32, @33, @35, @36, + @37, @38, @39] + + CFMutableArrayRef array = fn MutableArrayNew + CFRange range + long prevNum = NSNotFound + + for CFNumberRef num in nums + if ( prevNum == NSNotFound ) + range = fn CFRangeMake(intval(num),1) + else + if ( intval(num) == prevNum + 1 ) + range.length++ + else + MutableArrayAddObject( array, @(range) ) + range = fn CFRangeMake(intval(num),1) + end if + end if + prevNum = intval(num) + next + MutableArrayAddObject( array, @(range) ) + + CFMutableStringRef ranges = fn MutableStringNew + for ValueRef value in array + range = fn ValueRange( value ) + if ( range.length > 2 ) + if ( len(ranges) ) then MutableStringAppendString(ranges,@", ") + MutableStringAppendFormat( ranges, @"%ld-%ld", range.location, range.location + range.length - 1 ) + else + for long i = range.location to range.location + range.length - 1 + if ( len(ranges) ) then MutableStringAppendString(ranges,@", ") + MutableStringAppendFormat( ranges, @"%ld", i ) + next + end if + next + + print ranges +end fn + +fn DoRangeExtraction + +HandleEvents diff --git a/Task/Ranking-methods/Fortran/ranking-methods.f b/Task/Ranking-methods/Fortran/ranking-methods.f new file mode 100644 index 0000000000..99d63bdd8e --- /dev/null +++ b/Task/Ranking-methods/Fortran/ranking-methods.f @@ -0,0 +1,145 @@ +module ranking_methods + implicit none + private + public :: standard_ranking, modified_ranking, dense_ranking, ordinal_ranking, fractional_ranking + +contains + + subroutine standard_ranking(scores, names, ranks) + implicit none + real, intent(in) :: scores(:) + character(len=*), intent(in) :: names(:) + real, allocatable, intent(out) :: ranks(:) + integer :: i, n + + n = size(scores) + allocate(ranks(n)) + ranks(1) = 1.0 + do i = 2, n + ranks(i) = MERGE(ranks(i-1), REAL(i), scores(i) == scores(i-1)) + end do + end subroutine standard_ranking + + subroutine modified_ranking(scores, names, ranks) + implicit none + real, intent(in) :: scores(:) + character(len=*), intent(in) :: names(:) + real, allocatable, intent(out) :: ranks(:) + integer :: i, j, n + + n = size(scores) + allocate(ranks(n)) + do i = 1, n + ranks(i) = real(i) + do j = i+1, n + if (scores(j) == scores(i)) then + ranks(j) = ranks(i) + end if + end do + end do + end subroutine modified_ranking + + subroutine dense_ranking(scores, names, ranks) + implicit none + real, intent(in) :: scores(:) + character(len=*), intent(in) :: names(:) + real, allocatable, intent(out) :: ranks(:) + integer :: i, n + real :: current_rank + + n = size(scores) + allocate(ranks(n)) + current_rank = 1.0 + ranks(1) = current_rank + do i = 2, n + if (scores(i) /= scores(i-1)) then + current_rank = current_rank + 1 + end if + ranks(i) = current_rank + end do + end subroutine dense_ranking + + + subroutine ordinal_ranking(scores, names, ranks) + real, intent(in) :: scores(:) + character(len=*), intent(in) :: names(:) + real, allocatable, intent(out) :: ranks(:) + integer :: i, n + + n = size(scores) + allocate(ranks(n)) + do i = 1, n + ranks(i) = real(i) + end do + end subroutine ordinal_ranking + +subroutine fractional_ranking(scores, names, ranks) + implicit none + real, intent(in) :: scores(:) + character(len=*), intent(in) :: names(:) + real, allocatable, intent(out) :: ranks(:) + integer :: i, j, n + real :: sum_rank + + n = size(scores) + allocate(ranks(n)) + + i = 1 + do while (i <= n) + sum_rank = real(i) + j = i + 1 + do while (j <= n .and. scores(j) == scores(i)) + sum_rank = sum_rank + real(j) + j = j + 1 + end do + ranks(i:j-1) = sum_rank / (j - i) + i = j + end do +end subroutine fractional_ranking + + +program main + use ranking_methods + implicit none + + real, dimension(7) :: scores = [44.0, 42.0, 42.0, 41.0, 41.0, 41.0, 39.0] + character(len=10), dimension(7) :: names = ["Solomon ", "Jason ", "Errol ", & + "Garry ", "Bernard ", "Barry ", "Stephen "] + real, allocatable :: ranks(:) + integer :: i + + print *, "Standard Ranking:" + call standard_ranking(scores, names, ranks) + call print_results(scores, names, ranks) + + print *, "Modified Ranking:" + call modified_ranking(scores, names, ranks) + call print_results(scores, names, ranks) + + print *, "Dense Ranking:" + call dense_ranking(scores, names, ranks) + call print_results(scores, names, ranks) + + print *, "Ordinal Ranking:" + call ordinal_ranking(scores, names, ranks) + call print_results(scores, names, ranks) + + print *, "Fractional Ranking:" + call fractional_ranking(scores, names, ranks) + call print_results(scores, names, ranks) + +contains + + subroutine print_results(scores, names, ranks) + real, intent(in) :: scores(:), ranks(:) + character(len=*), intent(in) :: names(:) + integer :: i + + do i = 1, size(scores) + print '(F5.1, 2X, A10, 2X, F5.1)', scores(i), names(i), ranks(i) + end do + print * + end subroutine print_results + +end program main +end module ranking_methods diff --git a/Task/Read-a-file-line-by-line/Joy/read-a-file-line-by-line.joy b/Task/Read-a-file-line-by-line/Joy/read-a-file-line-by-line.joy new file mode 100644 index 0000000000..7f5196961d --- /dev/null +++ b/Task/Read-a-file-line-by-line/Joy/read-a-file-line-by-line.joy @@ -0,0 +1,9 @@ +(* Reads file input.txt and puts the lines as char in a list *) + +"input.txt" "r" fopen +(* while not end get char and swap the end to get the stream object for fgets *) +[ feof not ] [ fgets swap ] while +(*pop the stream object *) +pop +stack +. diff --git a/Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line.scm b/Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line-1.scm similarity index 100% rename from Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line.scm rename to Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line-1.scm diff --git a/Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line-2.scm b/Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line-2.scm new file mode 100644 index 0000000000..a44d775675 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Scheme/read-a-file-line-by-line-2.scm @@ -0,0 +1,5 @@ +; For R6RS Scheme i.e. Chez Scheme +(define file (open-input-file path)) +(do ((line (get-line file) (get-line file))) ((eof-object? line)) + (display line) + (newline)) diff --git a/Task/Read-a-file-line-by-line/Standard-ML/read-a-file-line-by-line.ml b/Task/Read-a-file-line-by-line/Standard-ML/read-a-file-line-by-line.ml index 87d2f47de3..08fe006787 100644 --- a/Task/Read-a-file-line-by-line/Standard-ML/read-a-file-line-by-line.ml +++ b/Task/Read-a-file-line-by-line/Standard-ML/read-a-file-line-by-line.ml @@ -1,13 +1,10 @@ fun readLines string = let val strm = TextIO.openIn path - fun chomp str = - let - val xstr = String.explode str - val slen = List.length xstr - in - String.implode(List.take(xstr, (slen-1))) - end + (* this would remove all trailing whitespace *) + (* fun chomp str = Substring.string (Substring.dropr Char.isSpace (Substring.full str)) *) + (* but TextIO.inputLine guarantees that the line is newline terminated so this works equally well *) + fun chomp str = Substring.string (Substring.trimr 1 (Substring.full str)) fun collectLines ls s = case TextIO.inputLine s of SOME(l) => collectLines (chomp l::ls) s diff --git a/Task/Read-a-specific-line-from-a-file/M2000-Interpreter/read-a-specific-line-from-a-file.m2000 b/Task/Read-a-specific-line-from-a-file/M2000-Interpreter/read-a-specific-line-from-a-file.m2000 new file mode 100644 index 0000000000..14c9dc7368 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/M2000-Interpreter/read-a-specific-line-from-a-file.m2000 @@ -0,0 +1,58 @@ +Module Read_a_specific_line_from_a_file { + select case rnd + case <0.4 + document ExportThis$=format$("1.\n2.\n3.\n4.\n5.\n6.\n\n8.") + case <0.8 + document ExportThis$=format$("1.\n2.\n3.\n4.\n5.\n6.\n7. la cédille (cedilla) – ç\n8.") + case else + document ExportThis$=format$("1.\n2.\n3.\n4.\n5.\n6.") + end select + ' Print len(ExportThis$)=55 + If Doc.par(ExportThis$)>6 then + If len(Paragraph$(ExportThis$, 7))=0 then + print "Empty 7th Line" + else + Print Paragraph$(ExportThis$, 7) + end if + else + Print "There is no 7th line" + end if + ' expot with varius encoding, BOM included/excluded, line seperators. + ' We use here Ansi codepage 1033 + Save.Doc ExportThis$, "Input.txt", 1033 + ' set locale - used from open to convert to UTF16LE (default intenal type) + locale 1033 + ' open used for binary/text ansi/utf16le + open "input.txt" for input as #f + integer m=1 + boolean ok + while not eof(#f) and not ok + line input #f, L$ + if m=7 then + ok=true + if L$="" then + print "Empty 7th Line" + else + Print L$ + end if + end if + m++ + end while + if not ok then Print "There is no 7th line" + close #f + ' Print filelen("Input.txt")=55 + Document ImportDoc$ + Load.Doc ImportDoc$, "Input.txt", 1033 + ' Print len(ImportDoc$)=55 + If Doc.par(ImportDoc$)>6 then + If len(Paragraph$(ImportDoc$, 7))=0 then + print "Empty 7th Line" + else + Print Paragraph$(ImportDoc$, 7) + end if + else + Print "There is no 7th line" + end if +} + +Read_a_specific_line_from_a_file diff --git a/Task/Read-entire-file/Forth/read-entire-file.fth b/Task/Read-entire-file/Forth/read-entire-file-1.fth similarity index 100% rename from Task/Read-entire-file/Forth/read-entire-file.fth rename to Task/Read-entire-file/Forth/read-entire-file-1.fth diff --git a/Task/Read-entire-file/Forth/read-entire-file-2.fth b/Task/Read-entire-file/Forth/read-entire-file-2.fth new file mode 100644 index 0000000000..0b45f69f33 --- /dev/null +++ b/Task/Read-entire-file/Forth/read-entire-file-2.fth @@ -0,0 +1,2 @@ +: read-file "foo.txt" GET-FILE TYPE ; +read-file diff --git a/Task/Read-entire-file/Racket/read-entire-file.rkt b/Task/Read-entire-file/Racket/read-entire-file.rkt index 19b556e463..18a197bb6e 100644 --- a/Task/Read-entire-file/Racket/read-entire-file.rkt +++ b/Task/Read-entire-file/Racket/read-entire-file.rkt @@ -1 +1,2 @@ +(require racket/file) (file->string "foo.txt") diff --git a/Task/Read-entire-file/Zig/read-entire-file-1.zig b/Task/Read-entire-file/Zig/read-entire-file-1.zig index 77aca01305..6ae327f52f 100644 --- a/Task/Read-entire-file/Zig/read-entire-file-1.zig +++ b/Task/Read-entire-file/Zig/read-entire-file-1.zig @@ -1,18 +1,14 @@ const std = @import("std"); -const File = std.fs.File; - -pub fn main() (error{OutOfMemory} || File.OpenError || File.ReadError)!void { +pub fn main() !void { var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); - const cwd = std.fs.cwd(); - - var file = try cwd.openFile("input_file.txt", .{ .mode = .read_only }); + var file = try std.fs.cwd().openFile("input_file.txt", .{}); defer file.close(); - const file_content = try file.readToEndAlloc(allocator, comptime std.math.maxInt(usize)); + const file_content = try file.readToEndAlloc(allocator, (try file.stat()).size); defer allocator.free(file_content); std.debug.print("Read {d} octets. File content:\n", .{file_content.len}); diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx new file mode 100644 index 0000000000..7fc4460e78 --- /dev/null +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx @@ -0,0 +1,19 @@ +include Settings + +say version; say 'Real constants and functions'; say +numeric digits 16 +say 'e =' e()+0 +say 'pi =' pi()+0 +say 'square root 7 =' sqrt(7)+0 +say 'log 7 base e =' log(7)+0 +say 'log 7 base 10 =' log10(7)+0 +say 'log 7 base 2 =' logxy(7,2)+0 +say 'exponential 7 =' exp(7)+0 +say '1/2^3/4 =' power(1/2,3/4)+0 +say 'floor 4/3 =' floor(4/3) +say 'ceiling 4/3 =' ceil(4/3) +exit + +include Functions +include Constants +include Abend diff --git a/Task/Real-constants-and-functions/Uiua/real-constants-and-functions.uiua b/Task/Real-constants-and-functions/Uiua/real-constants-and-functions.uiua new file mode 100644 index 0000000000..e910174315 --- /dev/null +++ b/Task/Real-constants-and-functions/Uiua/real-constants-and-functions.uiua @@ -0,0 +1,9 @@ +π # pi +√x # sqrt +e # e +ₙe x # natural logarithm +ₙy x # logarithm - x is the number ot take the logarithm of and y is the power to take the log with respect to. +⁅x # absolute value, called "round" in uiua +⌊x # floor +⌈x # ceiling +ⁿy x # power - x is the base and y is the power diff --git a/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs b/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs index b7263ccd28..b1e6f2c5bc 100644 --- a/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs +++ b/Task/Recamans-sequence/Haskell/recamans-sequence-2.hs @@ -1,42 +1,8 @@ -import Data.Set (Set, fromList, insert, isSubsetOf, member, size) -import Data.Bool (bool) - -firstNRecamans :: Int -> [Int] -firstNRecamans n = reverse $ recamanUpto (\(_, i, _) -> n == i) - -firstDuplicateR :: Int -firstDuplicateR = head $ recamanUpto (\(rs, _, set) -> size set /= length rs) - -recamanSuperset :: Set Int -> [Int] -recamanSuperset setInts = - tail $ recamanUpto (\(_, _, setR) -> isSubsetOf setInts setR) - -recamanUpto :: (([Int], Int, Set Int) -> Bool) -> [Int] -recamanUpto p = rs - where - (rs, _, _) = - until - p - (\(rs@(r:_), i, seen) -> - let n = nextR seen i r - in (n : rs, succ i, insert n seen)) - ([0], 1, fromList [0]) - -nextR :: Set Int -> Int -> Int -> Int -nextR seen i r = - let back = r - i - in bool back (r + i) (0 > back || member back seen) - --- TEST --------------------------------------------------------------- -main :: IO () -main = - (putStrLn . unlines) - [ "First 15 Recamans:" - , show $ firstNRecamans 15 - , [] - , "First duplicated Recaman:" - , show firstDuplicateR - , [] - , "Length of Recaman series required to include [0..1000]:" - , (show . length . recamanSuperset) $ fromList [0 .. 1000] - ] +recaman :: Integer -> [Integer] +recaman n = reverse (go 0 0 []) + where + go i a_n xs | i > n = xs + | (am > 0) && (not (any (am ==) xs)) = go (i + 1) am (am : xs) + | otherwise = go (i + 1) ap (ap : xs) + where am = a_n - (i + 1) + ap = a_n + (i + 1) diff --git a/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs b/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs index 01113e4b84..b7263ccd28 100644 --- a/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs +++ b/Task/Recamans-sequence/Haskell/recamans-sequence-3.hs @@ -1,47 +1,42 @@ -import Data.List (find, findIndex, nub) -import Data.Maybe (fromJust) -import Data.Set (Set, fromList, insert, isSubsetOf, member) +import Data.Set (Set, fromList, insert, isSubsetOf, member, size) +import Data.Bool (bool) ---- INFINITE STREAM OF RECAMAN SERIES OF GROWING LENGTH -- -rSeries :: [[Int]] -rSeries = - scanl - ( \rs@(r : _) i -> - let back = r - i - nxt - | 0 > back || elem back rs = r + i - | otherwise = back - in nxt : rs - ) - [0] - [1 ..] +firstNRecamans :: Int -> [Int] +firstNRecamans n = reverse $ recamanUpto (\(_, i, _) -> n == i) ------------ INFINITE STREAM OF RECAMAN-GENERATED --------- ---------------- INTEGER SETS OF GROWING SIZE ------------- -rSets :: [(Set Int, Int)] -rSets = - scanl - ( \(seen, r) i -> - let back = r - i - nxt - | 0 > back || member back seen = r + i - | otherwise = back - in (insert nxt seen, nxt) - ) - (fromList [0], 0) - [1 ..] +firstDuplicateR :: Int +firstDuplicateR = head $ recamanUpto (\(rs, _, set) -> size set /= length rs) ---------------------------- TEST ------------------------- +recamanSuperset :: Set Int -> [Int] +recamanSuperset setInts = + tail $ recamanUpto (\(_, _, setR) -> isSubsetOf setInts setR) + +recamanUpto :: (([Int], Int, Set Int) -> Bool) -> [Int] +recamanUpto p = rs + where + (rs, _, _) = + until + p + (\(rs@(r:_), i, seen) -> + let n = nextR seen i r + in (n : rs, succ i, insert n seen)) + ([0], 1, fromList [0]) + +nextR :: Set Int -> Int -> Int -> Int +nextR seen i r = + let back = r - i + in bool back (r + i) (0 > back || member back seen) + +-- TEST --------------------------------------------------------------- main :: IO () -main = do - let setK = fromList [0 .. 1000] +main = (putStrLn . unlines) - [ "First 15 Recamans:", - show . reverse . fromJust $ find ((15 ==) . length) rSeries, - [], - "First duplicated Recaman:", - show . head . fromJust $ find ((/=) <$> length <*> (length . nub)) rSeries, - [], - "Length of Recaman series required to include [0..1000]:", - show . fromJust $ findIndex (\(setR, _) -> isSubsetOf setK setR) rSets + [ "First 15 Recamans:" + , show $ firstNRecamans 15 + , [] + , "First duplicated Recaman:" + , show firstDuplicateR + , [] + , "Length of Recaman series required to include [0..1000]:" + , (show . length . recamanSuperset) $ fromList [0 .. 1000] ] diff --git a/Task/Recamans-sequence/Haskell/recamans-sequence-4.hs b/Task/Recamans-sequence/Haskell/recamans-sequence-4.hs new file mode 100644 index 0000000000..01113e4b84 --- /dev/null +++ b/Task/Recamans-sequence/Haskell/recamans-sequence-4.hs @@ -0,0 +1,47 @@ +import Data.List (find, findIndex, nub) +import Data.Maybe (fromJust) +import Data.Set (Set, fromList, insert, isSubsetOf, member) + +--- INFINITE STREAM OF RECAMAN SERIES OF GROWING LENGTH -- +rSeries :: [[Int]] +rSeries = + scanl + ( \rs@(r : _) i -> + let back = r - i + nxt + | 0 > back || elem back rs = r + i + | otherwise = back + in nxt : rs + ) + [0] + [1 ..] + +----------- INFINITE STREAM OF RECAMAN-GENERATED --------- +--------------- INTEGER SETS OF GROWING SIZE ------------- +rSets :: [(Set Int, Int)] +rSets = + scanl + ( \(seen, r) i -> + let back = r - i + nxt + | 0 > back || member back seen = r + i + | otherwise = back + in (insert nxt seen, nxt) + ) + (fromList [0], 0) + [1 ..] + +--------------------------- TEST ------------------------- +main :: IO () +main = do + let setK = fromList [0 .. 1000] + (putStrLn . unlines) + [ "First 15 Recamans:", + show . reverse . fromJust $ find ((15 ==) . length) rSeries, + [], + "First duplicated Recaman:", + show . head . fromJust $ find ((/=) <$> length <*> (length . nub)) rSeries, + [], + "Length of Recaman series required to include [0..1000]:", + show . fromJust $ findIndex (\(setR, _) -> isSubsetOf setK setR) rSets + ] diff --git a/Task/Record-sound/Wren/record-sound-1.wren b/Task/Record-sound/Wren/record-sound-1.wren deleted file mode 100644 index 8922c706f5..0000000000 --- a/Task/Record-sound/Wren/record-sound-1.wren +++ /dev/null @@ -1,39 +0,0 @@ -/* Record_sound.wren */ - -class C { - foreign static getInput(maxSize) - - foreign static arecord(args) - - foreign static aplay(name) -} - -var name = "" -while (name == "") { - System.write("Enter output file name (without extension) : ") - name = C.getInput(80) -} -name = name + ".wav" - -var rate = 0 -while (!rate || !rate.isInteger || rate < 2000 || rate > 192000) { - System.write("Enter sampling rate in Hz (2000 to 192000) : ") - rate = Num.fromString(C.getInput(6)) -} -var rateS = rate.toString - -var dur = 0 -while (!dur || dur < 5 || dur > 30) { - System.write("Enter duration in seconds (5 to 30) : ") - dur = Num.fromString(C.getInput(5)) -} -var durS = dur.toString - -System.print("\nOK, start speaking now...") -// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported. -var args = ["-r", rateS, "-f", "S16_LE", "-d", durS, name] -C.arecord(args.join(" ")) - -System.print("\n'%(name)' created on disk and will now be played back...") -C.aplay(name) -System.print("\nPlay-back completed.") diff --git a/Task/Record-sound/Wren/record-sound-2.wren b/Task/Record-sound/Wren/record-sound-2.wren deleted file mode 100644 index 0ad3196c0d..0000000000 --- a/Task/Record-sound/Wren/record-sound-2.wren +++ /dev/null @@ -1,102 +0,0 @@ -#include -#include -#include -#include -#include "wren.h" - -void C_getInput(WrenVM* vm) { - int maxSize = (int)wrenGetSlotDouble(vm, 1) + 2; - char input[maxSize]; - fgets(input, maxSize, stdin); - __fpurge(stdin); - input[strcspn(input, "\n")] = 0; - wrenSetSlotString(vm, 0, (const char*)input); -} - -void C_arecord(WrenVM* vm) { - const char *args = wrenGetSlotString(vm, 1); - char command[strlen(args) + 8]; - strcpy(command, "arecord "); - strcat(command, args); - system(command); -} - -void C_aplay(WrenVM* vm) { - const char *name = wrenGetSlotString(vm, 1); - char command[strlen(name) + 6]; - strcpy(command, "aplay "); - strcat(command, name); - system(command); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "getInput(_)") == 0) return C_getInput; - if (isStatic && strcmp(signature, "arecord(_)") == 0) return C_arecord; - if (isStatic && strcmp(signature, "aplay(_)") == 0) return C_aplay; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Record_sound.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Record-sound/Wren/record-sound.wren b/Task/Record-sound/Wren/record-sound.wren new file mode 100644 index 0000000000..f7437f90a3 --- /dev/null +++ b/Task/Record-sound/Wren/record-sound.wren @@ -0,0 +1,20 @@ +import "os" for Process +import "./ioutil" for Input + +var name = Input.text("Enter output file name (without extension) : ", 1, 80) +name = name + ".wav" + +var rate = Input.integer("Enter sampling rate in Hz (2000 to 192000) : ", 2000, 192000) +var rateS = rate.toString + +var dur = Input.number("Enter duration in seconds (5 to 30) : ", 5, 30) +var durS = dur.toString + +System.print("\nOK, start speaking now...") +// Default arguments: -c 1, -t wav. Note only signed 16 bit format supported. +var args = ["-r", rateS, "-f", "S16_LE", "-d", durS, name] +Process.exec("arecord", args) + +System.print("\n'%(name)' created on disk and will now be played back...") +Process.exec("aplay %(name)") +System.print("\nPlay-back completed.") diff --git a/Task/Reflection-List-methods/Arturo/reflection-list-methods.arturo b/Task/Reflection-List-methods/Arturo/reflection-list-methods.arturo new file mode 100644 index 0000000000..fe5abc95f4 --- /dev/null +++ b/Task/Reflection-List-methods/Arturo/reflection-list-methods.arturo @@ -0,0 +1,10 @@ +define :person [ + init: constructor [name surname] + + sayHello: method [][ + print ["Hello" \name "!"] + ] +] + +p: to :person ["John" "Doe"]! +print.lines methods p diff --git a/Task/Regular-expressions/Langur/regular-expressions-2.langur b/Task/Regular-expressions/Langur/regular-expressions-2.langur index bd9de4fe0c..9be6f90975 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-2.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-2.langur @@ -1 +1 @@ -if x, y = submatch(re/(abc+).+?(def)/, "somestring") { ... } +if x, y = submatch("somestring", by=re/(abc+).+?(def)/) { ... } diff --git a/Task/Regular-expressions/Langur/regular-expressions-5.langur b/Task/Regular-expressions/Langur/regular-expressions-5.langur index dd3a7ba9f8..01569b08a3 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-5.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-5.langur @@ -1,2 +1,2 @@ -replace("abcdef", re/abc/, "Y") +replace("abcdef", by=re/abc/, with="Y") # result: "Ydef" diff --git a/Task/Resistor-mesh/FutureBasic/resistor-mesh.basic b/Task/Resistor-mesh/FutureBasic/resistor-mesh.basic new file mode 100644 index 0000000000..be6a215e48 --- /dev/null +++ b/Task/Resistor-mesh/FutureBasic/resistor-mesh.basic @@ -0,0 +1,94 @@ +// Rosetta Code Resistor Mesh task +//https://rosettacode.org/wiki/Resistor_mesh +// Translation of Yabasic to FutureBasic + + +window 1,@"Resistor Mesh Task" + +#build ShowMoreWarnings NO +short N=10 +short NN=100 +double A(100,101) + +short NODE=0 +short ROW,COL + +FOR ROW=1 TO N + FOR COL=1 TO N + NODE=NODE+1 + IF ROW>1 + A(NODE,NODE)=A(NODE,NODE)+1 + A(NODE,NODE-N)=-1 + END IF + IF ROW1 + A(NODE,NODE)=A(NODE,NODE)+1 + A(NODE,NODE-1)=-1 + END IF + IF COL0 then break + NEXT + IF I=R+1 + PRINT "No solution!" + END + END IF + FOR K=1 TO R+1 + T = A(J,K) + A(J,K) = A(I,K) + A(I,K) = T + NEXT + Y= (1 / A(J,J)) + FOR K=1 TO R+1 + A(J,K) = Y * A(J,K) + NEXT + FOR I=1 TO R + IF I<>J + Y=-A(I,J) + FOR K=1 TO R+1 + A(I,K)=A(I,K)+ Y*A(J,K) + NEXT + END IF + NEXT +NEXT + +double Resistance + +Resistance = A(ANode,101)-A(BNode,101) + +PRINT +PRINT "Resistance between Nodes" str$(ANode) + " and" + str$(BNode) + " is" + str$(abs(Resistance)) + " Ohms" + + +handleevents diff --git a/Task/Reverse-a-string/Atari-BASIC/reverse-a-string.basic b/Task/Reverse-a-string/Atari-BASIC/reverse-a-string.basic new file mode 100644 index 0000000000..72e3a9129e --- /dev/null +++ b/Task/Reverse-a-string/Atari-BASIC/reverse-a-string.basic @@ -0,0 +1,11 @@ +10 DIM S$(4) +20 S$="asdf" +30 GOSUB 100 +40 PRINT S$,REV$ +50 END +100 X=LEN(S$) +110 DIM REV$(X) +120 FOR I=1 TO X +130 REV$(I)=S$(X-I+1) +140 NEXT I +150 RETURN diff --git a/Task/Reverse-a-string/EasyLang/reverse-a-string.easy b/Task/Reverse-a-string/EasyLang/reverse-a-string.easy index 749257002d..8687375d09 100644 --- a/Task/Reverse-a-string/EasyLang/reverse-a-string.easy +++ b/Task/Reverse-a-string/EasyLang/reverse-a-string.easy @@ -3,6 +3,6 @@ func$ reverse s$ . for i = 1 to len a$[] div 2 swap a$[i] a$[len a$[] - i + 1] . - return strjoin a$[] + return strjoin a$[] "" . print reverse "hello" diff --git a/Task/Roman-numerals-Decode/Wren/roman-numerals-decode.wren b/Task/Roman-numerals-Decode/Wren/roman-numerals-decode-1.wren similarity index 100% rename from Task/Roman-numerals-Decode/Wren/roman-numerals-decode.wren rename to Task/Roman-numerals-Decode/Wren/roman-numerals-decode-1.wren diff --git a/Task/Roman-numerals-Decode/Wren/roman-numerals-decode-2.wren b/Task/Roman-numerals-Decode/Wren/roman-numerals-decode-2.wren new file mode 100644 index 0000000000..c5c7b2b99d --- /dev/null +++ b/Task/Roman-numerals-Decode/Wren/roman-numerals-decode-2.wren @@ -0,0 +1,7 @@ +import "./roman" for Roman +import "./fmt" for Fmt + +var romans = ["I", "III", "IV", "VIII", "XLIX", "CCII", "CDXXXIII", "MCMXC", "MMVIII", "MDCLXVI"] +for (r in romans) { + Fmt.print("$-10s = $d", r, Roman.new(r).toInt) +} diff --git a/Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode.basic b/Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode-1.basic similarity index 100% rename from Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode.basic rename to Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode-1.basic diff --git a/Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode-2.basic b/Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode-2.basic new file mode 100644 index 0000000000..af2e10bad9 --- /dev/null +++ b/Task/Roman-numerals-Encode/BBC-BASIC/roman-numerals-encode-2.basic @@ -0,0 +1,22 @@ + PRINT 1999;" ";FNint_ToRoman(1999) + PRINT 2012;" ";FNint_ToRoman(2012) + PRINT 1666;" ";FNint_ToRoman(1666) + PRINT 3888;" ";FNint_ToRoman(3888) + END + DEFFNint_ToRoman(A%) + IF A%<0:="MINIMUS" + IF A%=0:="NULLA" + IF A%>3999:="MAXIMUS" + A$=STRING$(A% DIV 1000,"M"):A%=A% MOD 1000 + IF A%>899:A$=A$+"CM":A%=A%-900 + IF A%>499:A$=A$+"D" :A%=A%-500 + IF A%>399:A$=A$+"CD":A%=A%-400 + A$=A$+STRING$(A% DIV 100,"C"):A%=A% MOD 100 + IF A%>89:A$=A$+"XC":A%=A%-90 + IF A%>49:A$=A$+"L" :A%=A%-50 + IF A%>39:A$=A$+"XL":A%=A%-40 + A$=A$+STRING$(A% DIV 10,"X"):A%=A% MOD 10 + IF A%>8:A$=A$+"IX":A%=A%-9 + IF A%>4:A$=A$+"V" :A%=A%-5 + IF A%>3:A$=A$+"IV":A%=A%-4 + =A$+STRING$(A%,"I") diff --git a/Task/Roman-numerals-Encode/Draco/roman-numerals-encode.draco b/Task/Roman-numerals-Encode/Draco/roman-numerals-encode.draco new file mode 100644 index 0000000000..59411b5e18 --- /dev/null +++ b/Task/Roman-numerals-Encode/Draco/roman-numerals-encode.draco @@ -0,0 +1,30 @@ +proc toroman(word n; *char buf) *char: + *char parts = "M\e\eCM\eD\e\eCD\eC\e\eXC\eL\e\eXL\eX\e\eIX\eV\e\eIV\eI"; + [13]word sizes = (1000,900,500,400,100,90,50,40,10,9,5,4,1); + channel output text roman; + word part; + + open(roman, buf); + while n > 0 do + part := 0; + while sizes[part]>n do part := part+1 od; + write(roman; parts + 3*part); + n := n - sizes[part] + od; + close(roman); + buf +corp + +proc test(word n) void: + [32]char buf; + writeln(n, ": ", toroman(n, &buf[0])) +corp + +proc main() void: + test(1666); + test(2008); + test(1001); + test(1999); + test(3888); + test(2025) +corp diff --git a/Task/Roman-numerals-Encode/Refal/roman-numerals-encode.refal b/Task/Roman-numerals-Encode/Refal/roman-numerals-encode.refal new file mode 100644 index 0000000000..983c5af98a --- /dev/null +++ b/Task/Roman-numerals-Encode/Refal/roman-numerals-encode.refal @@ -0,0 +1,31 @@ +$ENTRY Go { + = + + + + + ; +}; + +Show { + s.N = ' = ' >; +}; + +Roman { + 0 = ; + s.N, : s.Next e.Part = e.Part ; +}; + +RomanStep { + s.N = >; + s.N (s.Size e.Part) e.Parts, >: '+' = + e.Part; + s.N t.Part e.Parts = ; +}; + +RomanDigits { + = (1000 'M') + ( 900 'CM') ( 500 'D') ( 400 'CD') ( 100 'C') + ( 90 'XC') ( 50 'L') ( 40 'XL') ( 10 'X') + ( 9 'IX') ( 5 'V') ( 4 'IV') ( 1 'I'); +}; diff --git a/Task/Roman-numerals-Encode/Wren/roman-numerals-encode.wren b/Task/Roman-numerals-Encode/Wren/roman-numerals-encode-1.wren similarity index 100% rename from Task/Roman-numerals-Encode/Wren/roman-numerals-encode.wren rename to Task/Roman-numerals-Encode/Wren/roman-numerals-encode-1.wren diff --git a/Task/Roman-numerals-Encode/Wren/roman-numerals-encode-2.wren b/Task/Roman-numerals-Encode/Wren/roman-numerals-encode-2.wren new file mode 100644 index 0000000000..39cf04cf1a --- /dev/null +++ b/Task/Roman-numerals-Encode/Wren/roman-numerals-encode-2.wren @@ -0,0 +1,3 @@ +import "./roman" for Roman + +for (n in [1990, 1666, 2008, 2020]) System.print(Roman.new(n)) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj index 972ea34d90..cf894bf095 100644 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-1.clj @@ -3,7 +3,7 @@ Returns any of nil, a float, or a vector." [a b c] (let [sq-d (Math/sqrt (- (* b b) (* 4 a c))) - f #(/ (% b sq-d) (* 2 a))] + f #(/ (% (- b) sq-d) (* 2 a))] (cond (neg? sq-d) nil (zero? sq-d) (f +) diff --git a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj index 8ff7eb4a0b..3d2eff5cdc 100644 --- a/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj +++ b/Task/Roots-of-a-quadratic-function/Clojure/roots-of-a-quadratic-function-2.clj @@ -1,6 +1,6 @@ user=> (quadratic 1.0 1.0 1.0) nil user=> (quadratic 1.0 2.0 1.0) -1.0 +-1.0 user=> (quadratic 1.0 3.0 1.0) -[2.618033988749895 0.3819660112501051] +[-0.3819660112501051 -2.618033988749895] diff --git a/Task/Roots-of-a-quadratic-function/M2000-Interpreter/roots-of-a-quadratic-function.m2000 b/Task/Roots-of-a-quadratic-function/M2000-Interpreter/roots-of-a-quadratic-function.m2000 new file mode 100644 index 0000000000..bedd98f24f --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/M2000-Interpreter/roots-of-a-quadratic-function.m2000 @@ -0,0 +1,69 @@ +Module Roots_of_Quadratic_Function { + declare global m math2 + function global complex(a as double, b as double=0) { + method m, "cxNew", a, b as ret: =ret + } + function quadroots(a as double, b as double, c as double) { + var d = b*b - 4*a*c, a2 = a + a + if d<0 then + var r=-b/a2 + var i=sqrt(-d)/a2 + ="complex", complex(r, i), complex(r, -i), 5 + else.if d==0 then + ="single root", -b/2/a, -b/2/a, 8 + else + var r =if(b<0 -> (-b + sqrt(d)) / a2, (-b - sqrt(d)) / a2) + ="real", r, c/(a*r), 5 + end if + } + flush + data "" , "outputRoots.txt" + while not empty + read filename + open filename for wide output as #f + Disp(quadroots(3, 4, 4/3)) + Disp(quadroots(3, 2, -1)) + Disp(quadroots(3, 2, 1)) + Disp(quadroots(1, -1e9, 1)) + Disp(quadroots(1, -1e70, 1)) + Disp(quadroots(1, -1e100, 1)) + Disp(quadroots(1, -1e200, 1)) + Disp(quadroots(1, -1e300, 1)) + Disp(quadroots(1, 0, 1)) + Disp(quadroots(2, -1, -6)) + Disp(quadroots(3, 4, 5)) + Disp(quadroots(0.5, sqrt(2), 1)) + Disp(quadroots(1, 2, 2)) + close #f + if filename<>"" then win dir$+filename + end while + sub disp(arg as array) + (s, a, b, n)=arg + Print #f, field$(s, 12); + if type$(a)="cxComplex" then disp1(a) else disp2(a) + if type$(b)="cxComplex" then disp1(b) else disp2(b) + Print #f + end sub + sub disp1(a) + local aa="", bb=if$(a|i<0->"-","+") + if a|i<>0 then + if abs(a|i)<>1 then bb+=""+(abs(round(a|i, n))) + bb+="i" + else + bb="" + end if + if a|r=0 then + if a|i=0 then aa="0" + else + aa=""+(round(a|r, n)) + end if + Print #f, " (";aa;bb;")"; + end sub + sub disp2(b) + local boolean k=b<>0 and (abs(b)<1e-6 or abs(b)>1e6) + local res=if$(k-> str$(b,"Scientific"), ""+(round(b, n))) + if instr(res, "INF") then res="inf" + Print #f, " ";res; + end sub +} +Roots_of_Quadratic_Function diff --git a/Task/Roots-of-unity/PascalABC.NET/roots-of-unity.pas b/Task/Roots-of-unity/PascalABC.NET/roots-of-unity.pas new file mode 100644 index 0000000000..5fd98de9cc --- /dev/null +++ b/Task/Roots-of-unity/PascalABC.NET/roots-of-unity.pas @@ -0,0 +1,6 @@ +function RootsOfUnity(n: integer) + := (0..n-1).Select(x -> Complex.FromPolarCoordinates(1, 2 * PI * x / n)); + +begin + RootsOfUnity(3).PrintLines +end. diff --git a/Task/Rosetta-Code-Count-examples/00-TASK.txt b/Task/Rosetta-Code-Count-examples/00-TASK.txt index 688e2be18b..813ffce72e 100644 --- a/Task/Rosetta-Code-Count-examples/00-TASK.txt +++ b/Task/Rosetta-Code-Count-examples/00-TASK.txt @@ -12,5 +12,5 @@ Total: X examples. For a full output, updated periodically, see [[Rosetta Code/Count examples/Full list]]. -You'll need to use the Media Wiki API, which you can find out about locally, [http://rosettacode.org/mw/api.php here], or in Media Wiki's API documentation at, [http://www.mediawiki.org/wiki/API_Query API:Query] +You'll need to use the Media Wiki API, which you can find out about locally, [https://rosettacode.org/w/api.php here], or in Media Wiki's API documentation at, [http://www.mediawiki.org/wiki/API_Query API:Query] diff --git a/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples-1.py b/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples-1.py index ff8f072a6b..72f90b4a08 100644 --- a/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples-1.py +++ b/Task/Rosetta-Code-Count-examples/Python/rosetta-code-count-examples-1.py @@ -2,17 +2,20 @@ from urllib.request import urlopen, Request import xml.dom.minidom r = Request( - 'https://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml', - headers={'User-Agent': 'Mozilla/5.0'}) + "https://rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml", + headers={"User-Agent": "Mozilla/5.0"}, +) x = urlopen(r) tasks = [] -for i in xml.dom.minidom.parseString(x.read()).getElementsByTagName('cm'): - t = i.getAttribute('title').replace(' ', '_') - r = Request(f'https://www.rosettacode.org/mw/index.php?title={t}&action=raw', - headers={'User-Agent': 'Mozilla/5.0'}) +for i in xml.dom.minidom.parseString(x.read()).getElementsByTagName("cm"): + t = i.getAttribute("title").replace(" ", "_").replace("+", "%2B") + r = Request( + f"https://rosettacode.org/w/index.php?title={t}&action=raw", + headers={"User-Agent": "Mozilla/5.0"}, + ) y = urlopen(r) - tasks.append( y.read().lower().count(b'{{header|') ) - print(t.replace('_', ' ') + f': {tasks[-1]} examples.') + tasks.append(y.read().lower().count(b"{{header|")) + print(t.replace("_", " ") + f": {tasks[-1]} examples.") -print(f'\nTotal: {sum(tasks)} examples.') +print(f"\nTotal: {sum(tasks)} examples.") diff --git a/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples-1.wren b/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples-1.wren deleted file mode 100644 index 3f98f47135..0000000000 --- a/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples-1.wren +++ /dev/null @@ -1,52 +0,0 @@ -/* Rosetta_Code_Count_examples.wren */ - -import "./pattern" for Pattern - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_WRITEFUNCTION = 20011 -var CURLOPT_WRITEDATA = 10001 - -foreign class Buffer { - construct new() {} // C will allocate buffer of a suitable size - - foreign value // returns buffer contents as a string -} - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() - -var getContent = Fn.new { |url| - var buffer = Buffer.new() - curl.easySetOpt(CURLOPT_URL, url) - curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) - curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C - curl.easySetOpt(CURLOPT_WRITEDATA, buffer) - curl.easyPerform() - return buffer.value -} - -var url = "https://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" -var content = getContent.call(url) -var p = Pattern.new("title/=\"[+1^\"]\"") -var matches = p.findAll(content) -for (m in matches) { - var title = m.capsText[0].replace("'", "'").replace(""", "\"") - var title2 = title.replace(" ", "_").replace("+", "\%252B") - var taskUrl = "https://www.rosettacode.org/w/index.php?title=%(title2)&action=raw" - var taskContent = getContent.call(taskUrl) - var lines = taskContent.split("\n") - var count = lines.count { |line| line.trim().startsWith("=={{header|") } - System.print("%(title) : %(count) examples") -} - -curl.easyCleanup() diff --git a/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples-2.wren b/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples-2.wren deleted file mode 100644 index 59d2fda281..0000000000 --- a/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples-2.wren +++ /dev/null @@ -1,191 +0,0 @@ -/* gcc Rosetta_Code_Count_examples.c -o Rosetta_Code_Count_examples -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -struct MemoryStruct { - char *memory; - size_t size; -}; - -/* C <=> Wren interface functions */ - -static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { - size_t realsize = size * nmemb; - struct MemoryStruct *mem = (struct MemoryStruct *)userp; - - char *ptr = realloc(mem->memory, mem->size + realsize + 1); - if(!ptr) { - /* out of memory! */ - printf("not enough memory (realloc returned NULL)\n"); - return 0; - } - - mem->memory = ptr; - memcpy(&(mem->memory[mem->size]), contents, realsize); - mem->size += realsize; - mem->memory[mem->size] = 0; - return realsize; -} - -void C_bufferAllocate(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); - ms->memory = malloc(1); - ms->size = 0; -} - -void C_bufferFinalize(void* data) { - struct MemoryStruct *ms = (struct MemoryStruct *)data; - free(ms->memory); -} - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_value(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); - wrenSetSlotString(vm, 0, ms->memory); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_perform(curl); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else if (opt < 20000) { - if (opt == CURLOPT_WRITEDATA) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); - curl_easy_setopt(curl, opt, (void *)ms); - } else if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } - } else if (opt < 30000) { - if (opt == CURLOPT_WRITEFUNCTION) { - curl_easy_setopt(curl, opt, &WriteMemoryCallback); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - methods.allocate = C_bufferAllocate; - methods.finalize = C_bufferFinalize; - } else if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - if (!isStatic && strcmp(signature, "value") == 0) return C_value; - } else if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { - if( result.source) free((void*)result.source); -} - -WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { - WrenLoadModuleResult result = {0}; - if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { - result.onComplete = loadModuleComplete; - char fullName[strlen(name) + 6]; - strcpy(fullName, name); - strcat(fullName, ".wren"); - result.source = readFile(fullName); - } - return result; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - config.loadModuleFn = &loadModule; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Rosetta_Code_Count_examples.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples.wren b/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples.wren new file mode 100644 index 0000000000..b984773fdc --- /dev/null +++ b/Task/Rosetta-Code-Count-examples/Wren/rosetta-code-count-examples.wren @@ -0,0 +1,16 @@ +import "os" for Process +import "./pattern" for Pattern + +var url = "https://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" +var content = Process.read("curl -s -L \"%(url)\"") // url needs quotes as it contains '&' +var p = Pattern.new("title/=\"[+1^\"]\"") +var matches = p.findAll(content) +for (m in matches.take(25)) { // limit to first 25 + var title = m.capsText[0].replace("'", "'").replace(""", "\"") + var title2 = title.replace(" ", "_").replace("+", "\%2B") + var taskUrl = "https://www.rosettacode.org/w/index.php?title=%(title2)&action=raw" + var taskContent = Process.read("curl -s -L \"%(taskUrl)\"") + var lines = taskContent.split("\n") + var count = lines.count { |line| line.trim().startsWith("=={{header|") } + System.print("%(title) : %(count) examples") +} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Arturo/rosetta-code-find-unimplemented-tasks.arturo b/Task/Rosetta-Code-Find-unimplemented-tasks/Arturo/rosetta-code-find-unimplemented-tasks.arturo new file mode 100644 index 0000000000..59a3c92dd4 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Arturo/rosetta-code-find-unimplemented-tasks.arturo @@ -0,0 +1,72 @@ +;------------------------------------------ +; Configuration +;------------------------------------------ + +API_URL: "https://rosettacode.org/w/api.php" + +;------------------------------------------ +; Helper Functions +;------------------------------------------ + +fetchCategory: function [category][ + results: [] + continue: "" + + while ø [ + ; build query parameters + params: #[ + action: "query" + list: "categorymembers" + cmtitle: ~"Category:|category|" + cmlimit: "500" + format: "json" + ] + + ; add continue parameter if we have one + unless empty? continue -> + params\cmcontinue: continue + + ; perform API request + response: request API_URL params + body: read.json response\body + + ; extract page titles and add to results + 'results ++ map body\query\categorymembers 'page -> + page\title + + ; check if we need to continue + switch key? body 'continue + -> continue: body\continue\cmcontinue + -> break + ] + + return results +] + +getUnimplementedTasks: function [language][ + print "Fetching all programming tasks..." + allTasks: fetchCategory "Programming_Tasks" + + print ~"Fetching tasks implemented in |language|..." + languageTasks: fetchCategory language + + print "Finding unimplemented tasks..." + return difference allTasks languageTasks +] + +;------------------------------------------ +; Main Program +;------------------------------------------ + +if standalone? [ + if empty? arg -> + panic "Usage: rosetta-tasks " + + language: capitalize arg\0 + tasks: getUnimplementedTasks language + + print ~"\nFound |size tasks| unimplemented tasks for |language|:\n" + + print.lines sort map tasks 'task -> + "• " ++ task +] diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Python/rosetta-code-find-unimplemented-tasks-5.py b/Task/Rosetta-Code-Find-unimplemented-tasks/Python/rosetta-code-find-unimplemented-tasks-5.py index 9263fce0b2..e3d2f26664 100644 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Python/rosetta-code-find-unimplemented-tasks-5.py +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Python/rosetta-code-find-unimplemented-tasks-5.py @@ -60,6 +60,10 @@ def category_members(category: str, url: str = URL) -> Iterable[PageInfo]: response.raise_for_status() data = response.json() + if not data.get("query"): + # Empty category + return + for page in data["query"]["pages"]: yield PageInfo(**{k: v for k, v in page.items() if k in PageInfo._fields}) @@ -87,28 +91,37 @@ def omitted_tasks(language: str) -> Set[PageInfo]: return set(category_members(f"Category:{language}/Omit")) -def unimplemented_tasks(lang_tasks: Set[PageInfo], omitted: Set[PageInfo]) -> Set[str]: +def unimplemented_tasks( + lang_tasks: Set[PageInfo], omitted: Set[PageInfo] +) -> Set[PageInfo]: tasks = set(category_members("Category:Programming Tasks")) return tasks.difference(lang_tasks).difference(omitted) def unimplemented_draft_tasks( lang_tasks: Set[PageInfo], omitted: Set[PageInfo] -) -> Set[str]: +) -> Set[PageInfo]: tasks = set(category_members("Category:Draft Programming Tasks")) return tasks.difference(lang_tasks).difference(omitted) def display(title: str, pages: Iterable[PageInfo]) -> None: print(title) - for page in pages: + for page in sorted(pages, key=lambda p: p.title): print(" ", page.title, page.canonicalurl) print("") if __name__ == "__main__": - lang = lang_tasks("Python") - omitted = omitted_tasks("Python") - display("Programming Tasks", unimplemented_tasks(lang, omitted)) - display("Draft Programming Tasks", unimplemented_draft_tasks(lang, omitted)) + import sys + + if len(sys.argv) > 1: + language = sys.argv[1] + else: + language = "Python" + + tasks = lang_tasks(language) + omitted = omitted_tasks(language) + display("Programming Tasks", unimplemented_tasks(tasks, omitted)) + display("Draft Programming Tasks", unimplemented_draft_tasks(tasks, omitted)) display("Omitted Tasks", omitted) diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Red/rosetta-code-find-unimplemented-tasks.red b/Task/Rosetta-Code-Find-unimplemented-tasks/Red/rosetta-code-find-unimplemented-tasks.red new file mode 100644 index 0000000000..0e4c1056fd --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Red/rosetta-code-find-unimplemented-tasks.red @@ -0,0 +1,35 @@ +Red [] + +arg: system/script/args + +if arg = "" [ + print "Missing command line argument for language" + quit/return 1 +] + +lang: trim/with arg #"'" + +getall: func[category [string!] /local titles cmcontinue page][ + titles: make block! 500 + cmcontinue: none + forever [ + page: load-json read rejoin [ + http://rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category: + enhex category + "&format=json&cmlimit=500" + either cmcontinue = none [""] [rejoin ["&cmcontinue=" enhex cmcontinue]] + ] + foreach member page/query/categorymembers [ + append titles member/title + ] + if page/continue = none [break/return titles] + cmcontinue: page/continue/cmcontinue + ] +] + +lang-tasks: getall lang +programming-tasks: getall "Programming_Tasks" + +foreach task sort exclude programming-tasks lang-tasks [ + print task +] diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks-1.wren b/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks-1.wren deleted file mode 100644 index b8cb29c1a0..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks-1.wren +++ /dev/null @@ -1,70 +0,0 @@ -/* Rosetta_Code_Find_unimplemented_tasks.wren */ - -import "./pattern" for Pattern - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_WRITEFUNCTION = 20011 -var CURLOPT_WRITEDATA = 10001 - -foreign class Buffer { - construct new() {} // C will allocate buffer of a suitable size - - foreign value // returns buffer contents as a string -} - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() - -var getContent = Fn.new { |url| - var buffer = Buffer.new() - curl.easySetOpt(CURLOPT_URL, url) - curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) - curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C - curl.easySetOpt(CURLOPT_WRITEDATA, buffer) - curl.easyPerform() - return buffer.value -} - -var p1 = Pattern.new("title/=\"[+1^\"]\"") -var p2 = Pattern.new("cmcontinue/=\"[+1^\"]\"") - -var findTasks = Fn.new { |category| - var url = "https://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:%(category)&cmlimit=500&format=xml" - var cmcontinue = "" - var tasks = [] - while (true) { - var content = getContent.call(url + cmcontinue) - var matches1 = p1.findAll(content) - for (m in matches1) { - var title = m.capsText[0].replace("'", "'").replace(""", "\"") - tasks.add(title) - } - var m2 = p2.find(content) - if (m2) cmcontinue = "&cmcontinue=%(m2.capsText[0])" else break - } - return tasks -} - -var tasks1 = findTasks.call("Programming_Tasks") // 'full' tasks only -var tasks2 = findTasks.call("Draft_Programming_Tasks") -var lang = "Wren" -var langTasks = findTasks.call(lang) // includes draft tasks -curl.easyCleanup() -System.print("Unimplemented 'full' tasks in %(lang):") -for (task in tasks1) { - if (!langTasks.contains(task)) System.print(" " + task) -} -System.print("\nUnimplemented 'draft' tasks in %(lang):") -for (task in tasks2) { - if (!langTasks.contains(task)) System.print(" " + task) -} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks-2.wren b/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks-2.wren deleted file mode 100644 index eb9df26983..0000000000 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks-2.wren +++ /dev/null @@ -1,191 +0,0 @@ -/* gcc Rosetta_Code_Find_unimplemented_tasks.c -o Rosetta_Code_Find_unimplemented_tasks -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -struct MemoryStruct { - char *memory; - size_t size; -}; - -/* C <=> Wren interface functions */ - -static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { - size_t realsize = size * nmemb; - struct MemoryStruct *mem = (struct MemoryStruct *)userp; - - char *ptr = realloc(mem->memory, mem->size + realsize + 1); - if(!ptr) { - /* out of memory! */ - printf("not enough memory (realloc returned NULL)\n"); - return 0; - } - - mem->memory = ptr; - memcpy(&(mem->memory[mem->size]), contents, realsize); - mem->size += realsize; - mem->memory[mem->size] = 0; - return realsize; -} - -void C_bufferAllocate(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); - ms->memory = malloc(1); - ms->size = 0; -} - -void C_bufferFinalize(void* data) { - struct MemoryStruct *ms = (struct MemoryStruct *)data; - free(ms->memory); -} - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_value(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); - wrenSetSlotString(vm, 0, ms->memory); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_perform(curl); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else if (opt < 20000) { - if (opt == CURLOPT_WRITEDATA) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); - curl_easy_setopt(curl, opt, (void *)ms); - } else if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } - } else if (opt < 30000) { - if (opt == CURLOPT_WRITEFUNCTION) { - curl_easy_setopt(curl, opt, &WriteMemoryCallback); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - methods.allocate = C_bufferAllocate; - methods.finalize = C_bufferFinalize; - } else if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - if (!isStatic && strcmp(signature, "value") == 0) return C_value; - } else if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { - if( result.source) free((void*)result.source); -} - -WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { - WrenLoadModuleResult result = {0}; - if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { - result.onComplete = loadModuleComplete; - char fullName[strlen(name) + 6]; - strcpy(fullName, name); - strcat(fullName, ".wren"); - result.source = readFile(fullName); - } - return result; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - config.loadModuleFn = &loadModule; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Rosetta_Code_Find_unimplemented_tasks.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks.wren b/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks.wren new file mode 100644 index 0000000000..7c630edd56 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Wren/rosetta-code-find-unimplemented-tasks.wren @@ -0,0 +1,48 @@ +import "os" for Process +import "timer" for Now +import "./pattern" for Pattern +import "./ioutil" for Input + +var p1 = Pattern.new("title/=\"[+1^\"]\"") +var p2 = Pattern.new("cmcontinue/=\"[+1^\"]\"") + +var findTasks = Fn.new { |category| + var url = "https://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:%(category)&cmlimit=500&format=xml" + var cmcontinue = "" + var tasks = [] + while (true) { + var content = Process.read("curl -s -L \"%(url)%(cmcontinue)\"") + var matches1 = p1.findAll(content) + for (m in matches1) { + var title = m.capsText[0].replace("'", "'").replace(""", "\"") + tasks.add(title) + } + var m2 = p2.find(content) + if (m2) cmcontinue = "&cmcontinue=%(m2.capsText[0])" else break + } + return tasks +} + +var tasks1 = findTasks.call("Programming_Tasks") // 'full' tasks only +var tasks2 = findTasks.call("Draft_Programming_Tasks") +var lang = Input.text("Enter the category name of your language: ", 1) +var langTasks = findTasks.call(lang) // includes draft tasks +System.print("\nResults for %(lang) as at %(Now.date):") +System.print("\nUnimplemented 'full' tasks:") +var count = 0 +for (task in tasks1) { + if (!langTasks.contains(task)) { + System.print(" " + task) + count = count + 1 + } +} +System.print(" Total = %(count)") +count = 0 +System.print("\nUnimplemented 'draft' tasks:") +for (task in tasks2) { + if (!langTasks.contains(task)) { + System.print(" " + task) + count = count + 1 + } +} +System.print(" Total = %(count)") diff --git a/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users-1.wren b/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users-1.wren deleted file mode 100644 index 58de572231..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users-1.wren +++ /dev/null @@ -1,68 +0,0 @@ -/* Rosetta_Code_Rank_languages_by_number_of_users.wren */ - -import "./pattern" for Pattern -import "./fmt" for Fmt - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_WRITEFUNCTION = 20011 -var CURLOPT_WRITEDATA = 10001 - -foreign class Buffer { - construct new() {} // C will allocate buffer of a suitable size - - foreign value // returns buffer contents as a string -} - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() - -var getContent = Fn.new { |url| - var buffer = Buffer.new() - curl.easySetOpt(CURLOPT_URL, url) - curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) - curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C - curl.easySetOpt(CURLOPT_WRITEDATA, buffer) - curl.easyPerform() - return buffer.value -} - -var p = Pattern.new(" User\">[+1^<]\u200f\u200e ([#13/d] member~s)") -var url = "https://rosettacode.org/w/index.php?title=Special:Categories&limit=5000" -var content = getContent.call(url) -var matches = p.findAll(content) -var over100s = [] -for (m in matches) { - var numUsers = Num.fromString(m.capsText[1]) - if (numUsers >= 100) { - var language = m.capsText[0][0..-6] - over100s.add([language, numUsers]) - } -} -over100s.sort { |a, b| a[1] > b[1] } -System.print("Languages with at least 100 users as at 3 February, 2024:") -var rank = 0 -var lastScore = 0 -var lastRank = 0 -for (i in 0...over100s.count) { - var pair = over100s[i] - var eq = " " - rank = i + 1 - if (lastScore == pair[1]) { - eq = "=" - rank = lastRank - } else { - lastScore = pair[1] - lastRank = rank - } - Fmt.print("$-2d$s $-11s $d", rank, eq, pair[0], pair[1]) -} diff --git a/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users-2.wren b/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users-2.wren deleted file mode 100644 index 07d8913360..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users-2.wren +++ /dev/null @@ -1,191 +0,0 @@ -/* gcc Rosetta_Code_Rank_languages_by_number_of_users.c -o Rosetta_Code_Rank_languages_by_number_of_users -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -struct MemoryStruct { - char *memory; - size_t size; -}; - -/* C <=> Wren interface functions */ - -static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { - size_t realsize = size * nmemb; - struct MemoryStruct *mem = (struct MemoryStruct *)userp; - - char *ptr = realloc(mem->memory, mem->size + realsize + 1); - if(!ptr) { - /* out of memory! */ - printf("not enough memory (realloc returned NULL)\n"); - return 0; - } - - mem->memory = ptr; - memcpy(&(mem->memory[mem->size]), contents, realsize); - mem->size += realsize; - mem->memory[mem->size] = 0; - return realsize; -} - -void C_bufferAllocate(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); - ms->memory = malloc(1); - ms->size = 0; -} - -void C_bufferFinalize(void* data) { - struct MemoryStruct *ms = (struct MemoryStruct *)data; - free(ms->memory); -} - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_value(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); - wrenSetSlotString(vm, 0, ms->memory); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_perform(curl); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else if (opt < 20000) { - if (opt == CURLOPT_WRITEDATA) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); - curl_easy_setopt(curl, opt, (void *)ms); - } else if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } - } else if (opt < 30000) { - if (opt == CURLOPT_WRITEFUNCTION) { - curl_easy_setopt(curl, opt, &WriteMemoryCallback); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - methods.allocate = C_bufferAllocate; - methods.finalize = C_bufferFinalize; - } else if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - if (!isStatic && strcmp(signature, "value") == 0) return C_value; - } else if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { - if( result.source) free((void*)result.source); -} - -WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { - WrenLoadModuleResult result = {0}; - if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { - result.onComplete = loadModuleComplete; - char fullName[strlen(name) + 6]; - strcpy(fullName, name); - strcat(fullName, ".wren"); - result.source = readFile(fullName); - } - return result; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - config.loadModuleFn = &loadModule; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Rosetta_Code_Rank_languages_by_number_of_users.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users.wren b/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users.wren new file mode 100644 index 0000000000..37250acd07 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-number-of-users/Wren/rosetta-code-rank-languages-by-number-of-users.wren @@ -0,0 +1,47 @@ +import "os" for Process +import "timer" for Now +import "./xsequence" for XDocument +import "./fmt" for Fmt + +var urlBase = "https://rosettacode.org/w/api.php?action=query&format=xml&generator=categorymembers&gcmtitle=Category:Language\%20users&gcmlimit=500&prop=categoryinfo" + +var over100s = [] +var url = urlBase +while (true) { + var content = Process.read("curl -s -L \"%(url)\"") + var doc = XDocument.parse(content) + for (p in doc.root.element("query").element("pages").elements("page")) { + if (p.attributeValue("ns") == "14") { + var ci = p.element("categoryinfo") + var numUsers = ci.attributeValue("pages", Num, 0) + if (numUsers >= 100) { + var language = p.attributeValue("title")[9..-6] + over100s.add([language, numUsers]) + } + } + } + var cel = doc.root.element("continue") + if (!cel) break + var gcmcont = "&gcmcontinue=%(cel.attribute("gcmcontinue").value)" + var cont = "&continue=%(cel.attribute("continue").value)" + url = urlBase + gcmcont + cont +} +over100s.sort { |a, b| a[1] > b[1] } +var date = "%(Now.day) %(Now.monthName), %(Now.year)" +System.print("Languages with at least 100 users as at %(date):\n") +var rank = 0 +var lastScore = 0 +var lastRank = 0 +for (i in 0...over100s.count) { + var pair = over100s[i] + var eq = " " + rank = i + 1 + if (lastScore == pair[1]) { + eq = "=" + rank = lastRank + } else { + lastScore = pair[1] + lastRank = rank + } + Fmt.print("$-2d$s $-11s $d", rank, eq, pair[0], pair[1]) +} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb b/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb index 31a07c8a36..56f947b6e8 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb @@ -39,12 +39,22 @@ Module RankLanguagesByPopularity Dim nextPageEx = New RegEx("
([^<]+?)[^<]*([^<]+?) * "" Dim wc As New WebClient() - Dim page As String = wc.DownloadString(nextPage) + ' Ensure the WebClient has a User-Agent. + Dim hasAgent As Boolean = False + for hPos As Integer = 0 To wc.Headers.Count - 1 + Dim headerKey As String = wc.Headers.GetKey(hPos) + hasAgent = hasAgent Or headerKey = "User-Agent" + Next hPos + If not hasAgent Then + wc.Headers.Add("User-Agent", "RC_Tasks_Agent") + End If + + Dim page As String = wc.DownloadString(nextPage) nextPage = "" For Each link In nextPageEx.Matches(page) nextPage = basePage & link.Groups(1).Value @@ -60,6 +70,12 @@ Module RankLanguagesByPopularity languages.Add(New LanguageStat(lName, lCount)) End If Next language + + If nextPage <> "" Then + ' Sleep for a while to avoid looking like a DOS attack... + System.Threading.Thread.Sleep(500) + End If + Loop languages.Sort(AddressOf CompareLanguages) diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity-1.wren b/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity-1.wren deleted file mode 100644 index 6185dba031..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity-1.wren +++ /dev/null @@ -1,78 +0,0 @@ -/* Rosetta_Code_Rank_languages_by_popularity.wren */ - -import "./pattern" for Pattern -import "./fmt" for Fmt - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_WRITEFUNCTION = 20011 -var CURLOPT_WRITEDATA = 10001 - -foreign class Buffer { - construct new() {} // C will allocate buffer of a suitable size - - foreign value // returns buffer contents as a string -} - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var curl = Curl.easyInit() - -var getContent = Fn.new { |url| - var buffer = Buffer.new() - curl.easySetOpt(CURLOPT_URL, url) - curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) - curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C - curl.easySetOpt(CURLOPT_WRITEDATA, buffer) - curl.easyPerform() - return buffer.value -} - -var p1 = Pattern.new("> +1^,, [+1^ ] page") -var p2 = Pattern.new("subcatfrom/=[+1^#/#mw-subcategories]\"") - -var findLangs = Fn.new { - var url = "https://rosettacode.org/w/index.php?title=Category:Programming_Languages" - var subcatfrom = "" - var langs = [] - while (true) { - var content = getContent.call(url + subcatfrom) - var matches1 = p1.findAll(content) - for (m in matches1) { - var name = m.capsText[0] - var tasks = Num.fromString(m.capsText[1].replace(",", "")) - langs.add([name, tasks]) - } - var m2 = p2.find(content) - if (m2) subcatfrom = "&subcatfrom=%(m2.capsText[0])" else break - } - return langs -} - -var langs = findLangs.call() -langs.sort { |a, b| a[1] > b[1] } -System.print("Languages with most examples as at 3 February, 2024:") -var rank = 0 -var lastScore = 0 -var lastRank = 0 -for (i in 0...langs.count) { - var pair = langs[i] - var eq = " " - rank = i + 1 - if (lastScore == pair[1]) { - eq = "=" - rank = lastRank - } else { - lastScore = pair[1] - lastRank = rank - } - Fmt.print("$-3d$s $-20s $,5d", rank, eq, pair[0], pair[1]) -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity-2.wren b/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity-2.wren deleted file mode 100644 index f71329e680..0000000000 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity-2.wren +++ /dev/null @@ -1,191 +0,0 @@ -/* gcc Rosetta_Code_Rank_languages_by_popularity.c -o Rosetta_Code_Rank_languages_by_popularity -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -struct MemoryStruct { - char *memory; - size_t size; -}; - -/* C <=> Wren interface functions */ - -static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { - size_t realsize = size * nmemb; - struct MemoryStruct *mem = (struct MemoryStruct *)userp; - - char *ptr = realloc(mem->memory, mem->size + realsize + 1); - if(!ptr) { - /* out of memory! */ - printf("not enough memory (realloc returned NULL)\n"); - return 0; - } - - mem->memory = ptr; - memcpy(&(mem->memory[mem->size]), contents, realsize); - mem->size += realsize; - mem->memory[mem->size] = 0; - return realsize; -} - -void C_bufferAllocate(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct MemoryStruct)); - ms->memory = malloc(1); - ms->size = 0; -} - -void C_bufferFinalize(void* data) { - struct MemoryStruct *ms = (struct MemoryStruct *)data; - free(ms->memory); -} - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_value(WrenVM* vm) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 0); - wrenSetSlotString(vm, 0, ms->memory); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_perform(curl); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else if (opt < 20000) { - if (opt == CURLOPT_WRITEDATA) { - struct MemoryStruct *ms = (struct MemoryStruct *)wrenGetSlotForeign(vm, 2); - curl_easy_setopt(curl, opt, (void *)ms); - } else if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } - } else if (opt < 30000) { - if (opt == CURLOPT_WRITEFUNCTION) { - curl_easy_setopt(curl, opt, &WriteMemoryCallback); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - methods.allocate = C_bufferAllocate; - methods.finalize = C_bufferFinalize; - } else if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - if (!isStatic && strcmp(signature, "value") == 0) return C_value; - } else if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { - if( result.source) free((void*)result.source); -} - -WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { - WrenLoadModuleResult result = {0}; - if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { - result.onComplete = loadModuleComplete; - char fullName[strlen(name) + 6]; - strcpy(fullName, name); - strcat(fullName, ".wren"); - result.source = readFile(fullName); - } - return result; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - config.loadModuleFn = &loadModule; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Rosetta_Code_Rank_languages_by_popularity.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity.wren b/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity.wren new file mode 100644 index 0000000000..075d0a8de7 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Wren/rosetta-code-rank-languages-by-popularity.wren @@ -0,0 +1,45 @@ +import "os" for Process +import "timer" for Now +import "./xsequence" for XDocument +import "./fmt" for Fmt + +var urlBase = "https://rosettacode.org/w/api.php?action=query&format=xml&generator=categorymembers&gcmtitle=Category:Programming\%20Languages&gcmlimit=500&prop=categoryinfo" + +var results = [] +var url = urlBase +while (true) { + var content = Process.read("curl -s -L \"%(url)\"") + var doc = XDocument.parse(content) + for (p in doc.root.element("query").element("pages").elements("page")) { + if (p.attributeValue("ns") == "14") { + var ci = p.element("categoryinfo") + var numTasks = ci.attributeValue("pages", Num, 0) + var language = p.attributeValue("title")[9..-1] + results.add([language, numTasks]) + } + } + var cel = doc.root.element("continue") + if (!cel) break + var gcmcont = "&gcmcontinue=%(cel.attribute("gcmcontinue").value)" + var cont = "&continue=%(cel.attribute("continue").value)" + url = urlBase + gcmcont + cont +} +results.sort { |a, b| a[1] > b[1] } +var date = "%(Now.day) %(Now.monthName), %(Now.year)" +System.print("Languages with most tasks completed as at %(date):\n") +var rank = 0 +var lastScore = 0 +var lastRank = 0 +for (i in 0..29) { // just show top 30 + var pair = results[i] + var eq = " " + rank = i + 1 + if (lastScore == pair[1]) { + eq = "=" + rank = lastRank + } else { + lastScore = pair[1] + lastRank = rank + } + Fmt.print("$-2d$s $-11s $4d", rank, eq, pair[0], pair[1]) +} diff --git a/Task/Rot-13/YAMLScript/rot-13.ys b/Task/Rot-13/YAMLScript/rot-13.ys index d67c6052fb..96b5bcf73e 100644 --- a/Task/Rot-13/YAMLScript/rot-13.ys +++ b/Task/Rot-13/YAMLScript/rot-13.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(input='Hello, World!'): s =: set(\\A .. \\Z) + (\\a .. \\z) diff --git a/Task/S-expressions/FreeBASIC/s-expressions.basic b/Task/S-expressions/FreeBASIC/s-expressions.basic new file mode 100644 index 0000000000..693f6544f2 --- /dev/null +++ b/Task/S-expressions/FreeBASIC/s-expressions.basic @@ -0,0 +1,132 @@ +Type Token + tokenType As Integer '1=lbr, 2=rbr, 3=string, 4=number, 5=symbol + value As String + numValue As Double +End Type + +Type TokenList + tokens(1000) As Token + cnt As Integer +End Type + +Function isNumber(word As String) As Boolean + For i As Integer = 1 To Len(word) + If (Mid(word, i, 1) < "0" Or Mid(word, i, 1) > "9") And Mid(word, i, 1) <> "." Then Return False + Next + Return True +End Function + +Function ParseSExpr(cad As String) As TokenList + Dim As TokenList tlist + Dim As Integer state = 1 '1=token_start, 2=read_quoted_string, 3=read_string_or_number + Dim As String word = "" + + For i As Integer = 1 To Len(cad) + Select Case state + Case 1 'token_start + Select Case Mid(cad, i, 1) + Case "(" + tlist.tokens(tlist.cnt).tokenType = 1 + tlist.cnt += 1 + Case ")" + tlist.tokens(tlist.cnt).tokenType = 2 + tlist.cnt += 1 + Case " ", Chr(9), Chr(10), Chr(13) + Case """" + state = 2 : word = "" + Case Else + state = 3 : word = Mid(cad, i, 1) + End Select + + Case 2 'read_quoted_string + If Mid(cad, i, 1) = """" Then + tlist.tokens(tlist.cnt).tokenType = 3 + tlist.tokens(tlist.cnt).value = word + tlist.cnt += 1 + state = 1 + Else + word &= Mid(cad, i, 1) + End If + + Case 3 'read_string_or_number + If Instr(" " & Chr(9) & Chr(10) & Chr(13) & ")", Mid(cad, i, 1)) Then + tlist.tokens(tlist.cnt).tokenType = Iif(isNumber(word), 4, 5) + If isNumber(word) Then + tlist.tokens(tlist.cnt).numValue = Val(word) + Else + tlist.tokens(tlist.cnt).value = word + End If + tlist.cnt += 1 + If Mid(cad, i, 1) = ")" Then + tlist.tokens(tlist.cnt).tokenType = 2 + tlist.cnt += 1 + End If + state = 1 + Else + word &= Mid(cad, i, 1) + End If + End Select + Next + Return tlist +End Function + +Function ArrayToString(tlist As TokenList, startIdx As Integer, Byref endIdx As Integer) As String + Dim As String result = "" + Dim As Integer i = startIdx + + If startIdx = 0 Then result = "[" + + While i < tlist.cnt + Select Case tlist.tokens(i).tokenType + Case 1 'lbr + result &= "[" + i += 1 + result &= ArrayToString(tlist, i, i) + Case 2 'rbr + endIdx = i + Return result & "]" + Case 3 'string + result &= """" & tlist.tokens(i).value & """" + Case 4 'number + result &= Rtrim(Str(tlist.tokens(i).numValue)) + Case 5 'symbol + result &= ":" & tlist.tokens(i).value + End Select + If i < tlist.cnt - 1 Andalso tlist.tokens(i+1).tokenType <> 2 Then result &= ", " + i += 1 + Wend + Return result +End Function + +Function ToSExpr(tlist As TokenList) As String + Dim As String result = "" + For i As Integer = 0 To tlist.cnt - 1 + Select Case tlist.tokens(i).tokenType + Case 1: result &= "(" + Case 2: result &= ")" + Case 3: result &= """" & tlist.tokens(i).value & """" + Case 4: result &= Rtrim(Str(tlist.tokens(i).numValue)) + Case 5: result &= tlist.tokens(i).value + End Select + If i < tlist.cnt - 1 Andalso tlist.tokens(i+1).tokenType <> 2 Andalso tlist.tokens(i).tokenType <> 1 Then result &= " " + Next + Return result +End Function + +' Main program +Dim As String inputString = _ +"((data ""quoted data"" 123 4.5)" & Chr(10) & _ +" (data (!@# (4.5) ""(more"" ""data)"")))" + +Print "Original S-Expression:" +Print inputString +Dim As TokenList tokens = ParseSExpr(inputString) + +Print !"\nNative Structure:" +Dim As Integer dummy +Print ArrayToString(tokens, 0, dummy) + +Print !"\nand back to S-Expression:" +Print ToSExpr(tokens) + +Sleep diff --git a/Task/SHA-256/FutureBasic/sha-256.basic b/Task/SHA-256/FutureBasic/sha-256.basic new file mode 100644 index 0000000000..d63eade7d7 --- /dev/null +++ b/Task/SHA-256/FutureBasic/sha-256.basic @@ -0,0 +1,19 @@ +include "NSLog.incl" +include "CommonCrypto/CommonCrypto.incl" + +void local fn DoIt + CFStringRef msg = @"Rosetta code" + ptr rc = fn StringUTF8String( msg ) + unsigned char buf(32) + fn CC_SHA256( rc, fn strlen(rc), @buf(0) ) + CFMutableStringRef res = fn MutableStringWithCapacity(CC_SHA256_DIGEST_LENGTH) + for int i = 0 to CC_SHA256_DIGEST_LENGTH - 1 + MutableStringAppendFormat( res, @"%02x", buf(i) ) + next + NSLog(@"Input:\n%@\n",msg) + NSLog(@"Output:\n%@", res) +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Safe-addition/Wren/safe-addition-2.wren b/Task/Safe-addition/Wren/safe-addition-2.wren deleted file mode 100644 index 56460cb85a..0000000000 --- a/Task/Safe-addition/Wren/safe-addition-2.wren +++ /dev/null @@ -1,85 +0,0 @@ -/* gcc Safe_addition.c -o Safe_addition -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -void Interval_nextAfter(WrenVM* vm) { - double x = wrenGetSlotDouble(vm, 1); - double y = wrenGetSlotDouble(vm, 2); - wrenSetSlotDouble(vm, 0, nextafter(x, y)); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Interval") == 0) { - if (isStatic && strcmp(signature, "nextAfter_(_,_)") == 0) { - return Interval_nextAfter; - } - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main() { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Safe_addition.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Safe-addition/Wren/safe-addition-1.wren b/Task/Safe-addition/Wren/safe-addition.wren similarity index 59% rename from Task/Safe-addition/Wren/safe-addition-1.wren rename to Task/Safe-addition/Wren/safe-addition.wren index 70ab7e5f1e..e6b21f84db 100644 --- a/Task/Safe-addition/Wren/safe-addition-1.wren +++ b/Task/Safe-addition/Wren/safe-addition.wren @@ -1,4 +1,6 @@ -/* Safe_addition.wren */ +import "numeric" for Float +import "io" for Stdfmt + class Interval { construct new(lower, upper) { if (lower.type != Num || upper.type != Num) { @@ -11,13 +13,15 @@ class Interval { lower { _lower } upper { _upper } - static stepAway(x) { new(nextAfter_(x, -1/0), nextAfter_(x, 1/0)) } + static stepAway(x) { new(Float.prev(x), Float.next(x)) } static safeAdd(x, y) { stepAway(x + y) } - foreign static nextAfter_(x, y) // the code for this is written in C - - toString { "[%(_lower), %(_upper)]" } + toString { + var ls = Stdfmt.writef("$f", _lower, null, 0, 16) + var us = Stdfmt.writef("$f", _upper, null, 0, 16) + return "[%(ls), %(us)]" + } } var a = 1.2 diff --git a/Task/Semordnilap/AWK/semordnilap.awk b/Task/Semordnilap/AWK/semordnilap-1.awk similarity index 100% rename from Task/Semordnilap/AWK/semordnilap.awk rename to Task/Semordnilap/AWK/semordnilap-1.awk diff --git a/Task/Semordnilap/AWK/semordnilap-2.awk b/Task/Semordnilap/AWK/semordnilap-2.awk new file mode 100644 index 0000000000..96f14162e1 --- /dev/null +++ b/Task/Semordnilap/AWK/semordnilap-2.awk @@ -0,0 +1,15 @@ +{ wrd = $0 + rwrd = "" + for (i=length(wrd); i>0; --i) + rwrd = rwrd substr(wrd,i,1) + if (rwrd == wrd) + palindromes += 1 + else if ( seen[rwrd] ) { + if (++pairs < 7) + print wrd " " rwrd + } else + seen[wrd] = wrd +} +END { + print pairs " pairs, " palindromes " palindromes." +} diff --git a/Task/Semordnilap/Crystal/semordnilap.cr b/Task/Semordnilap/Crystal/semordnilap.cr index 512ed6150b..7271233a72 100644 --- a/Task/Semordnilap/Crystal/semordnilap.cr +++ b/Task/Semordnilap/Crystal/semordnilap.cr @@ -1,17 +1,8 @@ -require "set" - -UNIXDICT = File.read("unixdict.txt").lines - -def word?(word : String) - UNIXDICT.includes?(word) -end - -# is it a word and is it a word backwards? -semordnilap = UNIXDICT.select { |word| word?(word) && word?(word.reverse) } - -# consolidate pairs like [bad, dab] == [dab, bad] -final_results = semordnilap.map { |word| [word, word.reverse].to_set }.uniq - -# sets of N=1 mean the word is identical backwards -# print out the size, and 5 random pairs -puts final_results.size, final_results.sample(5) +words = File.read("unixdict.txt").each_line.to_set +semordnilap = words.compact_map {|word| + reversed = word.reverse + if word < reversed && words.includes? reversed + { word, reversed } + end +} +p semordnilap.size, semordnilap.sample(5) diff --git a/Task/Semordnilap/EasyLang/semordnilap.easy b/Task/Semordnilap/EasyLang/semordnilap.easy index 9b1e0b0489..0409c84756 100644 --- a/Task/Semordnilap/EasyLang/semordnilap.easy +++ b/Task/Semordnilap/EasyLang/semordnilap.easy @@ -8,7 +8,7 @@ func$ reverse s$ . for i = 1 to len a$[] div 2 swap a$[i] a$[len a$[] - i + 1] . - return strjoin a$[] + return strjoin a$[] "" . func search s$ . max = len w$[] + 1 diff --git a/Task/Semordnilap/FutureBasic/semordnilap.basic b/Task/Semordnilap/FutureBasic/semordnilap.basic new file mode 100644 index 0000000000..a074dfbc8c --- /dev/null +++ b/Task/Semordnilap/FutureBasic/semordnilap.basic @@ -0,0 +1,38 @@ +#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES} + +local fn Dictionary as CFArrayRef + CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ) + CFStringRef string = fn StringWithContentsOfURL( url, NSASCIIStringEncoding, NULL ) +end fn = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet ) + +local fn ReverseString( inString as CFStringRef ) as CFStringRef + CFMutableStringRef outString = fn MutableStringNew + for long index = len(inString) - 1 to 0 step -1 + MutableStringAppendString( outString, mid(inString,index,1) ) + next +end fn = outString + +void local fn Doit + CFMutableArrayRef pairs = fn MutableArrayNew + CFArrayRef words = fn Dictionary + NSUInteger count = len(words), i, index + for i = 0 to count - 2 + CFStringRef wd1 = words[i] + CFStringRef wd2 = fn ReverseString( wd1 ) + index = fn ArrayIndexOfObjectInRange( words, wd2, fn CFRangeMake( i+1, count-(i+1) ) ) + if ( index != NSNotFound ) then MutableArrayAddObject( pairs, @{@"wd1":wd1,@"wd2":wd2} ) + next + + text ,,,,, 60 + for i = 1 to 5 + count = len(pairs) + index = rnd(count)-1 + CFDictionaryRef dict = pairs[index] + print dict[@"wd1"],dict[@"wd2"] + MutableArrayRemoveObjectAtIndex( pairs, index ) + next +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac b/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac index ff3d80b08f..804567152c 100644 --- a/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac +++ b/Task/Sequence-of-primes-by-trial-division/EDSAC-order-code/sequence-of-primes-by-trial-division.edsac @@ -2,8 +2,9 @@ [EDSAC program, Initial Orders 2.] [Division is done implicitly by the use of wheels. One wheel for each possible prime divisor, up to an editable limit.] +[2024-12-25 Fixed bug in print subroutine (did not affect RC output)] - T51K [G parameter: print subroutine, 54 locations.] + T51K [G parameter: print subroutine, 52 locations.] P56F [must be even address] T47K [M parameter: main routine.] P110F [must be even address] @@ -149,11 +150,11 @@ [Modified library subroutine P7.] [Prints signed integer; up to 10 digits, left-justified.] [Input: 0D = integer,] -[54 locations. Load at even address. Workspace 4D.] +[52 locations. Load at even address. Workspace 4D.] E25KTG - GKA3FT42@A49@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@ - TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4D - A49@T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFSFL8FT4DE39@ + GKA3FT42@A47@T31@ADE10@T31@A46@T31@SDTDH44#@NDYFLDT4DS43@TF + H17@S17@A43@G23@UFS43@T1FV4DAFG48@SFLDUFXFOFFFSFL4FT4DA47@ + T31@A1FA43@G20@XFT44#ZPFT43ZP1024FP610D@524DO26@XFSFL8FT4DE39@ [========================= M parameter again ===============================] E25KTM diff --git a/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy b/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy index 5cf6eead30..92b6e3a8ac 100644 --- a/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy +++ b/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy @@ -10,7 +10,7 @@ proc adjacent txt$ n . . . . . - res$ = strjoin res$[] + res$ = strjoin res$[] "" print "result: " & res$ print "" . diff --git a/Task/Shoelace-formula-for-polygonal-area/00-TASK.txt b/Task/Shoelace-formula-for-polygonal-area/00-TASK.txt index 397e6728c7..04bc4791ee 100644 --- a/Task/Shoelace-formula-for-polygonal-area/00-TASK.txt +++ b/Task/Shoelace-formula-for-polygonal-area/00-TASK.txt @@ -1,3 +1,4 @@ + {{task}} Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:
 abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
diff --git a/Task/Shoelace-formula-for-polygonal-area/EDSAC-order-code/shoelace-formula-for-polygonal-area.edsac b/Task/Shoelace-formula-for-polygonal-area/EDSAC-order-code/shoelace-formula-for-polygonal-area.edsac
new file mode 100644
index 0000000000..0905deae5e
--- /dev/null
+++ b/Task/Shoelace-formula-for-polygonal-area/EDSAC-order-code/shoelace-formula-for-polygonal-area.edsac
@@ -0,0 +1,98 @@
+[Shoelace formula for Rosetta Code website.
+EDSAC program, Initial Orders 2]
+[Arrange the storage]
+          T45K P150F      [H, library subroutine R4 to read signed integer]
+          T46K P56F       [N, library subroutiine P7 to print positive integer]
+          T47K P200F      [M, main routine]
+[--------------------------------------------------------------------------
+ Library subroutine M3, prints header at load time and is then overwritten.
+ This header is 'AREA = ' and leaves the teleprinter in figures mode.]
+      PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
+      *AREA!#V!..PZ
+[--------------------------------------------------------------------------
+ Main routine]
+          E25K TM GK
+    [0]   PF PF     [sum, then shifted absolute sum]
+    [2]   PF        [x{0}]
+    [3]   PF        [y{0}]
+    [4]   PF        [x_curr, current x-coordinate]
+    [5]   PF        [x_prev, previous x-coordinate]
+    [6]   PF        [y-coordinate, gets copied to multiplier register]
+    [7]   PF        [positive count of vertices, then negative loop counter]
+    [8]   PD        [17-bit constant 1]
+    [9]   MF        [decimal point (in figures mode)]
+   [10]   @F        [carriage return]
+   [11]   &F        [line feed]
+   [12]   K4096F    [null]
+
+[In this program, it's assumed that input values are 17-bit signed integers,
+   so that the value from library subroutine R4 is returned in 0F.
+ Note that R4 changes the multiplier register.
+ Enter here with acc = 0]
+   [13]   A13@ GH         [0F := count of vertices, right justified]
+          AF LD T7@       [store count, shifted to address field]
+        [First vertex is read outside the loop]
+   [18]   A18@ GH         [0F := x{0}]
+          AF U2@ T5@      [store in x{0} and x_prev]
+   [23]   A23@ GH         [0F := y{0}]
+          AF U3@ T6@      [store in y{0} and y_mr]
+          T#@             [initialize sum to 0]
+          S7@             [acc := negative count of vertices]
+          A2F             [allow for first vertex being outside the loop]
+        [Head of loop]
+   [31]   T7@             [update negative count of vertices]
+   [32]   A32@ GH         [0F := x coordinate]
+          AF T4@          [store in x_curr]
+          H6@             [y coordinate to multiplier register]
+          A#@ N4@ T#@     [sum := sum - x_curr*y_mr]
+   [40]   A40@ GH         [0F := y-coordinate]
+          AF T6@ H6@      [store in y_mr and multiplier register]
+          A#@ V5@ T#@     [sum := sum + x_prev*y_mr]
+          A4@ T5@         [x_prev := x_curr]
+          A7@ A2F         [inc negative count of vertices]
+          G31@            [if still < 0, loop back]
+       [All vertices have been read, finish off. Here acc = 0.]
+          A#@ N2@         [acc := sum - x{0}*y{n}]
+          H3@ V5@         [acc := acc + x{n}*y{0}]
+          E60@ TD SD      [if acc < 0 then negate it]
+   [60]
+       [Here acc = abs(final sum). Since coordinates are scaled by 2^-16,
+        the sum is scaled by 2^-32. Shift 2 right to scale by 2^-34,
+        the scaling for a 35-bit integer. Finally shift 1 more right
+        to get the area, which is half an integer.]
+          R1F U#@         [shift 2 right, save result (= 2*area)]
+          RD TD           [0D := floor(area) for print routine]
+   [64]   A64@ GN O9@     [print floor(area) and decimal point]
+          H8@             [mult. reg. := 17-bit 1]
+          C@ S8@          [test 2*area for even or odd]
+          G73@            [if even, jump to print '0']
+          O31@ E74@       [else print '5' and skip next]
+   [73]   O8@             [print '0']
+   [74]   O10@ O11@       [print carriage return, line feed]
+          O12@            [print null to flush printer buffer]
+          ZF              [halt the machine]
+[================== H parameter: Library subroutine R4 ==================]
+[Input of one signed integer, returned in 0D.]
+[22 locations.]
+          E25K TH GK
+    GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF
+[================== N parameter: Library subroutine P7 ==================]
+[Prints long strictly positive integer;]
+[10 characters, right justified, padded left with spaces.]
+[Even address; 35 storage locations; working position 4D.]
+          E25K TN GK
+    GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
+    T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
+[======================= M parameter again =============================]
+          E25K TM GK
+          E13Z            [define entry address]
+          PF              [acc = 0 on entry]
+[-----------------------------------------------------------------------
+ Signed integers to be read by subroutine R4 (sign comes _after_ value).
+ Values are: count, x{0}, y{0}, x{1}, y{1}, ...
+ The data could be on a separate tape, so that the program could be used to
+   find the area of many polygons. Cf. Wilkes, Wheeler & Gill, 1951, p. 47.]
+5+3+4+5+11+12+8+9+5+5+6+ [area = 30.0]
+[5+60003-60004-60005-60011-60012-60008-60009-60005-60005-60006-] [30.0]
+[5+15000+20000+25000+55000+60000+40000+45000+25000+25000+30000+] [750000000.0]
+[3+10+20+11+20+10+21+] [.5]
diff --git a/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area.jl b/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area.jl
index 20e2d29adf..a0e02ebe27 100644
--- a/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area.jl
+++ b/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area.jl
@@ -2,8 +2,8 @@
 Assumes x,y points go around the polygon in one direction.
 """
 shoelacearea(x, y) =
-    abs(sum(i * j for (i, j) in zip(x, append!(y[2:end], y[1]))) -
-        sum(i * j for (i, j) in zip(append!(x[2:end], x[1]), y))) / 2
+			abs(sum([i * j for (i, j) in zip(x, append!(y[2:end], y[1]))]) -
+				sum([i * j for (i, j) in zip(append!(x[2:end], x[1]), y)])) / 2
 
 x, y = [3, 5, 12, 9, 5], [4, 11, 8, 5, 6]
 @show x y shoelacearea(x, y)
diff --git a/Task/Show-ASCII-table/Zig/show-ascii-table.zig b/Task/Show-ASCII-table/Zig/show-ascii-table.zig
index 58b0f9a085..76ded1aed0 100644
--- a/Task/Show-ASCII-table/Zig/show-ascii-table.zig
+++ b/Task/Show-ASCII-table/Zig/show-ascii-table.zig
@@ -1,9 +1,10 @@
-const print = @import("std").debug.print;
+const std = @import("std");
+const print = std.debug.print;
 pub fn main() void {
-  var i: u8 = 33;
-  print(" 32: Spc", .{});
-  while (i < 127) : (i += 1) {
-    print("{:03}: {c}  ", .{ i, i });
+
+  print("032: Spc ", .{});
+  for(33..127) |i| {
+    print("{:03}: {c:<4}", .{ i, std.math.cast(u8, i).? });
     if (@mod(i, 6) == 1) {
       print("\n", .{});
     }
diff --git a/Task/Sierpinski-arrowhead-curve/ALGOL-68/sierpinski-arrowhead-curve.alg b/Task/Sierpinski-arrowhead-curve/ALGOL-68/sierpinski-arrowhead-curve.alg
index d71e509742..7cb9b9e3a0 100644
--- a/Task/Sierpinski-arrowhead-curve/ALGOL-68/sierpinski-arrowhead-curve.alg
+++ b/Task/Sierpinski-arrowhead-curve/ALGOL-68/sierpinski-arrowhead-curve.alg
@@ -53,7 +53,7 @@ BEGIN # Sierpinski Arrowhead Curve in SVG                                    #
 
             put( svg file, ( "'/>", newline, "", newline ) );
             close( svg file )
-         FI # sierpinski square # ;
+         FI # sierpinski arrowhead curve # ;
 
     sierpinski arrowhead curve( "sierpinski_arrowhead.svg", 1200, 12, 6, 200, 700 )
 
diff --git a/Task/Sierpinski-carpet/FutureBasic/sierpinski-carpet.basic b/Task/Sierpinski-carpet/FutureBasic/sierpinski-carpet.basic
new file mode 100644
index 0000000000..df454464ab
--- /dev/null
+++ b/Task/Sierpinski-carpet/FutureBasic/sierpinski-carpet.basic
@@ -0,0 +1,25 @@
+local fn IsInCarpet( x as NSUInteger, y as NSUInteger ) as BOOL
+  while ( x != 0 && y != 0 )
+    if ( x % 3 == 1 && y % 3 == 1 ) then return NO
+    y /= 3 : x /= 3
+  wend
+end fn = YES
+
+void local fn SierpinskiCarpet( n as NSUInteger )
+  NSUInteger i, j, k = fn pow(3,n) - 1
+  pen -1
+  for i = 0 to k
+    for j = 0 to k
+      ColorRef col = fn ColorOrange
+      if ( fn IsInCarpet(i,j) )
+        col = fn ColorRed
+      end if
+      rect fill (i * 10, j * 10, 10, 10 ), col
+    next
+  next
+end fn
+
+window 1, @"Sierpinski Carpet", (0,0,270,270), NSWindowStyleMaskTitled
+fn SierpinskiCarpet(3)
+
+HandleEvents
diff --git a/Task/Sierpinski-pentagon/Ada/sierpinski-pentagon.ada b/Task/Sierpinski-pentagon/Ada/sierpinski-pentagon.ada
new file mode 100644
index 0000000000..29b48ba909
--- /dev/null
+++ b/Task/Sierpinski-pentagon/Ada/sierpinski-pentagon.ada
@@ -0,0 +1,45 @@
+pragma Ada_2022;
+with Ada.Numerics;  use Ada.Numerics;
+with Ada.Numerics.Discrete_Random;
+with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
+with Easy_Graphics; use Easy_Graphics;
+
+procedure Sierpinski_Pentagon is
+   Img : Easy_Image := New_Image ((1, 1), (512, 512), WHITE);
+
+   procedure Chaos_Game (Image        : in out Easy_Image;
+                         Vertex_Count : Positive;
+                         Radius       : Float;
+                         Iters        : Positive) is
+      type Vertex_Array is array (1 .. Vertex_Count) of Point;
+      Vertices : Vertex_Array;
+      subtype Vertex_Range is Integer range 1 .. Vertex_Count;
+      package Rand_V is new Ada.Numerics.Discrete_Random (Vertex_Range);
+      use Rand_V;
+      Gen : Generator;
+      Half_X  : constant Integer := X_Last (Image) / 2;
+      Half_Y  : constant Integer := Y_Last (Image) / 2;
+      Half_Pi : constant Float   := Float (Pi) / 2.0;
+      Two_Pi  : constant Float   := Float (Pi) * 2.0;
+      V       : Integer;
+      X       : Integer := Half_X;
+      Y       : Integer := Half_Y;
+   begin
+      for V in 1 .. Vertex_Count loop
+         Vertices (V).X := Half_X + Integer (Float (Half_X) *
+                           Cos (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count)));
+         Vertices (V).Y := Half_Y - Integer (Float (Half_Y) *
+                           Sin (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count)));
+      end loop;
+      for I in 1 .. Iters loop
+         V := Random (Gen);
+         X := X + Integer (Radius * Float (Vertices (V).X - X));
+         Y := Y + Integer (Radius * Float (Vertices (V).Y - Y));
+         Plot (Image, (X, Y), BLACK);
+      end loop;
+   end Chaos_Game;
+
+begin
+   Chaos_Game (Img, 5, 1.0 / ((1.0 + Sqrt (5.0)) / 2.0), 1_000_000);
+   Write_GIF (Img, "sierpinski_pentagon.gif");
+end Sierpinski_Pentagon;
diff --git a/Task/Sierpinski-pentagon/D/sierpinski-pentagon.d b/Task/Sierpinski-pentagon/D/sierpinski-pentagon.d
index dee83b683a..c5d2d0877c 100644
--- a/Task/Sierpinski-pentagon/D/sierpinski-pentagon.d
+++ b/Task/Sierpinski-pentagon/D/sierpinski-pentagon.d
@@ -89,7 +89,7 @@ struct Point {
     }
 }
 
-/// Mock turtle implementation sufficiant to handle "drawing" the pentagons
+/// Mock turtle implementation sufficient to handle "drawing" the pentagons
 class Turtle {
     /////////////////////////////////
     private:
diff --git a/Task/Sierpinski-square-curve/ALGOL-68/sierpinski-square-curve.alg b/Task/Sierpinski-square-curve/ALGOL-68/sierpinski-square-curve.alg
index 685c1f0d6c..c7ecec5bdc 100644
--- a/Task/Sierpinski-square-curve/ALGOL-68/sierpinski-square-curve.alg
+++ b/Task/Sierpinski-square-curve/ALGOL-68/sierpinski-square-curve.alg
@@ -53,7 +53,7 @@ BEGIN # Sierpinski Square Curve in SVG - SVG generation translated from the  #
 
             put( svg file, ( "'/>", newline, "", newline ) );
             close( svg file )
-         FI # sierpinski square # ;
+         FI # sierpinski square curve # ;
 
     sierpinski square curve( "sierpinski_square.svg", 635, 5, 5 )
 
diff --git a/Task/Sierpinski-triangle-Graphical/ALGOL-68/sierpinski-triangle-graphical.alg b/Task/Sierpinski-triangle-Graphical/ALGOL-68/sierpinski-triangle-graphical.alg
index 329a8843ce..b81d938f63 100644
--- a/Task/Sierpinski-triangle-Graphical/ALGOL-68/sierpinski-triangle-graphical.alg
+++ b/Task/Sierpinski-triangle-Graphical/ALGOL-68/sierpinski-triangle-graphical.alg
@@ -53,7 +53,7 @@ BEGIN # Sierpinski Triangle Curve in SVG                                     #
 
             put( svg file, ( "'/>", newline, "", newline ) );
             close( svg file )
-         FI # sierpinski square # ;
+         FI # sierpinski triangle curve # ;
 
     sierpinski triangle curve( "sierpinski_triangle.svg", 1200, 12, 5, 200, 400 )
 
diff --git a/Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes.k b/Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes.k
new file mode 100644
index 0000000000..3735a28d9a
--- /dev/null
+++ b/Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes.k
@@ -0,0 +1,10 @@
+n:100
+limit: _%n+1 // until square root +1
+iter:(2_!limit),limit  // to be iterated over inclusive limit
+numbers: (!n),n // array with numbers until n (inclusive)
+sieve: {2_((&0=x!)numbers)} // sieve function first two omitted
+dummy: { {yy:x; $[ ( (yy!x) ~ 0 ); numbers[x]:0 ;]}'sieve x}'|iter // iter must be reversed
+// this sets multiples in the array numbers to zero, if the modulus is zero
+// each x in iter is checked with '
+dummy: dummy   // to supress output
+1_(0<)#numbers // filter out bigger than zero
diff --git a/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur b/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur
index ed2a4bd2b4..18ed97992a 100644
--- a/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur
+++ b/Task/Sieve-of-Eratosthenes/Langur/sieve-of-eratosthenes.langur
@@ -12,7 +12,7 @@ val sieve = fn(limit) {
         }
     }
 
-    filter fn n:not composite[n], series(limit-1)
+    filter series(limit-1), by=fn n:not composite[n]
 }
 
 writeln sieve(100)
diff --git a/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin b/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin
new file mode 100644
index 0000000000..e3834b9432
--- /dev/null
+++ b/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin
@@ -0,0 +1,36 @@
+package main
+
+import "core:fmt"
+import "core:math"
+
+
+main :: proc() {
+
+    n :: 120
+    // outer loop with square root as limit
+    limit := i32(math.round_f16(math.sqrt_f16(n)))
+
+    array : [n]i32
+    // fill array with values
+    for i:=1;iA is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{−1}AX.
+A is any m by n matrix, square or rectangular. Its rank is r. We will diagonalize this A, but not by X^{-1} A X.
 The eigenvectors in X have three big problems: They are usually not orthogonal, there
-are not always enough eigenvectors, and Ax = λx requires A to be a square matrix. The
+are not always enough eigenvectors, and Ax = \lambda x requires A to be a square matrix. The
 singular vectors of A solve all those problems in a perfect way.   
 
 [https://math.mit.edu/classes/18.095/2016IAP/lec2/SVD_Notes.pdf The Singular Value Decomposition (SVD)]   
 
-According to the web page above, for any rectangular matrix A, we can decomposite it as A=UΣV^T
+According to the web page above, for any rectangular matrix A, we can decomposite it as A=U\Sigma V^T
 
 ''' Task Description'''   
 
@@ -13,7 +13,7 @@ Firstly, input two numbers "m" and "n".
 
 Then, input a square/rectangular matrix A^{m\times n}.   
 
-Finally, output U,Σ,V with respect to A.
+Finally, output U,~\Sigma,\ V with respect to A.
 
 ''' Example '''   
 
diff --git a/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic b/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic
index 51cc7b262a..81928efde4 100644
--- a/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic
+++ b/Task/Singular-value-decomposition/FreeBASIC/singular-value-decomposition.basic
@@ -1,4 +1,4 @@
-#include once "g:\FreeBASIC\inc\gsl\gsl_linalg.bi"
+#include once "inc\gsl\gsl_linalg.bi"
 
 Sub MatrixPrint(r As Integer, c As Integer, m() As Double)
     For i As Integer = 0 To r - 1
diff --git a/Task/Sisyphus-sequence/FreeBASIC/sisyphus-sequence.basic b/Task/Sisyphus-sequence/FreeBASIC/sisyphus-sequence.basic
new file mode 100644
index 0000000000..d8d2253733
--- /dev/null
+++ b/Task/Sisyphus-sequence/FreeBASIC/sisyphus-sequence.basic
@@ -0,0 +1,83 @@
+'#include "isprime.bas"
+
+Function getNthPrime(n As Integer) As Longint
+    If n <= 0 Then Return 0
+
+    Dim As Integer cnt = 0
+    Dim As Longint num = 1
+
+    While cnt < n
+        num += 1
+        If isPrime(num) Then cnt += 1
+    Wend
+
+    Return num
+End Function
+
+Function findMax(arr() As Integer) As Integer
+    Dim As Integer maxVal = arr(0)
+    For i As Integer = 1 To Ubound(arr)
+        If arr(i) > maxVal Then maxVal = arr(i)
+    Next
+    Return maxVal
+End Function
+
+' Main program
+Const As Longint limit = 1e6
+Dim As Double sisyphus(100)
+Dim As Integer under250(250)
+Dim As Integer i, m, np = 0
+Dim As Longint specific = 1000
+Dim As Longint cnt = 1
+Dim As Double nextVal = 1
+
+sisyphus(0) = 1
+under250(1) = 1
+
+Do
+    If (nextVal Mod 2) = 0 Then
+        nextVal /= 2
+    Else
+        np += 1
+        nextVal += getNthPrime(np)
+    End If
+
+    If nextVal <= 250 Then under250(nextVal) += 1
+
+    cnt += 1
+    If cnt <= 100 Then
+        sisyphus(cnt-1) = nextVal
+        If cnt = 100 Then
+            Print "The first 100 members of the Sisyphus sequence are:"
+            For i = 0 To 99
+                Print Using "####"; sisyphus(i);
+                If (i + 1) Mod 10 = 0 Then Print
+            Next
+            Print
+        End If
+    Elseif cnt = specific Then
+        Print Using "###,###,###,###"; cnt;
+        Print "th member is: ";
+        Print Using "###,###,###,###"; nextVal;
+        Print " and highest prime needed: ";
+        Print Using "###,###,###"; getNthPrime(np)
+
+        If cnt = limit Then
+            m = findMax(under250())
+            Print !"\nNumbers under 250 that do not occur in first "; cnt; " terms:"
+            For i = 1 To 250
+                If under250(i) = 0 Then Print i; " ";
+            Next
+            Print
+            Print !"\nNumbers under 250 that occur the most in first "; cnt; " terms:"
+            For i = 1 To 250
+                If under250(i) = m Then Print i; " ";
+            Next
+            Print " all occur "; m; " times."
+            Exit Do
+        End If
+        specific *= 10
+    End If
+Loop
+
+Sleep
diff --git a/Task/Sisyphus-sequence/Zig/sisyphus-sequence.zig b/Task/Sisyphus-sequence/Zig/sisyphus-sequence.zig
new file mode 100644
index 0000000000..0b7db13562
--- /dev/null
+++ b/Task/Sisyphus-sequence/Zig/sisyphus-sequence.zig
@@ -0,0 +1,162 @@
+const primesieve = @cImport({
+    @cInclude("primesieve.h");
+});
+const std = @import("std");
+const mem = std.mem;
+
+pub fn main() !void {
+    var t0 = try std.time.Timer.start();
+    // ------------------------------------------------------- stdout
+    const stdout = std.io.getStdOut().writer();
+    // ---------------------------------------------------- allocator
+    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
+    defer arena.deinit();
+    const allocator = arena.allocator();
+    // --------------------------------------------------------------
+    var counter = try Counter.init(allocator);
+    defer counter.deinit();
+
+    var sisyphus = try SisyphusSequenceGenerator.init();
+    defer sisyphus.deinit();
+
+    var number: u64 = undefined;
+    for (0..10) |_| {
+        for (0..10) |_| {
+            number = try sisyphus.next();
+            try counter.add(number);
+            try stdout.print(" {d:3}", .{number});
+        }
+        try stdout.writeByte('\n');
+    }
+    try stdout.writeByte('\n');
+
+    for ([_]usize{ 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000 }) |n| {
+        while (counter.count != n) {
+            number = try sisyphus.next();
+            try counter.add(number);
+        }
+        try stdout.print(
+            "{d:10}th member is {d:10} and highest prime needed is {d:9}\n",
+            .{ n, number, sisyphus.prime },
+        );
+    }
+    {
+        try stdout.writeAll("\nThese numbers under 250 do not occur in the first 100,000,000 terms:\n");
+        const missing = try counter.getMissing(allocator);
+        defer allocator.free(missing);
+
+        var sep: []const u8 = "";
+        for (missing) |n| {
+            try stdout.print("{s}{d}", .{ sep, n });
+            sep = ", ";
+        }
+        try stdout.writeByte('\n');
+    }
+    {
+        try stdout.writeAll("\nThese numbers under 250 occur the most in the first 100,000,000 terms:\n");
+        const most = try counter.getMost(allocator);
+        defer allocator.free(most.numbers);
+
+        var sep: []const u8 = "";
+        for (most.numbers) |n| {
+            try stdout.print("{s}{d}", .{ sep, n });
+            sep = ", ";
+        }
+        try stdout.print(" all occur {d} times.\n", .{most.max});
+    }
+    var count = counter.count; // Only need the count, not the found hashmap. Ditch counter.
+    while (true) {
+        number = try sisyphus.next();
+        count += 1;
+        if (number == 36) {
+            try stdout.print(
+                "\nMember {d} is {d} and highest prime needed is {d}\n",
+                .{ count, number, sisyphus.prime },
+            );
+            break;
+        }
+    }
+    try stdout.print("\nProcessed in {}\n", .{std.fmt.fmtDuration(t0.read())});
+}
+
+const SisyphusSequenceGeneratorError = error{
+    PrimeSieveError,
+};
+
+const SisyphusSequenceGenerator = struct {
+    it: primesieve.primesieve_iterator = undefined,
+    next_: u64 = 1,
+    prime: u64 = 0,
+
+    fn init() !SisyphusSequenceGenerator {
+        var si = SisyphusSequenceGenerator{};
+        primesieve.primesieve_init(&si.it);
+        return si;
+    }
+    fn deinit(self: *SisyphusSequenceGenerator) void {
+        primesieve.primesieve_free_iterator(&self.it);
+    }
+    fn next(self: *SisyphusSequenceGenerator) SisyphusSequenceGeneratorError!u64 {
+        const n = self.next_;
+        if (self.next_ % 2 == 0) {
+            self.next_ /= 2;
+        } else {
+            self.prime = primesieve.primesieve_next_prime(&self.it);
+            if (self.it.is_error != 0 or self.prime == primesieve.PRIMESIEVE_ERROR)
+                return SisyphusSequenceGeneratorError.PrimeSieveError;
+            self.next_ += self.prime;
+        }
+        return n;
+    }
+};
+
+const Counter = struct {
+    found: std.AutoHashMap(u64, usize),
+    count: usize = 0,
+
+    fn init(allocator: mem.Allocator) !Counter {
+        var found = std.AutoHashMap(u64, usize).init(allocator);
+        try found.ensureTotalCapacity(250);
+        for (1..250) |n|
+            try found.put(@as(u64, n), 0);
+        return Counter{ .found = found };
+    }
+    fn deinit(self: *Counter) void {
+        self.found.deinit();
+    }
+    fn add(self: *Counter, n: u64) !void {
+        self.count += 1;
+        if (n < 250)
+            self.found.getEntry(n).?.value_ptr.* += 1;
+    }
+    /// Caller owns returned slice memory.
+    fn getMissing(self: *const Counter, allocator: mem.Allocator) ![]u64 {
+        var missing_array = std.ArrayList(u64).init(allocator);
+        var it = self.found.iterator();
+        while (it.next()) |entry| {
+            if (entry.value_ptr.* == 0)
+                try missing_array.append(entry.key_ptr.*);
+        }
+        const missing = try missing_array.toOwnedSlice();
+        mem.sort(u64, missing, {}, std.sort.asc(u64));
+        return missing;
+    }
+    /// Caller owns returned 'numbers' slice memory.
+    fn getMost(self: *const Counter, allocator: mem.Allocator) !struct { numbers: []u64, max: usize } {
+        // Find the maximum count (there may be more than one at this value)
+        var value_it = self.found.valueIterator();
+        var max: usize = 0;
+        while (value_it.next()) |count|
+            max = @max(max, count.*);
+
+        var most_array = std.ArrayList(u64).init(allocator);
+        var it = self.found.iterator();
+        while (it.next()) |entry| {
+            if (entry.value_ptr.* == max)
+                try most_array.append(entry.key_ptr.*);
+        }
+        const most = try most_array.toOwnedSlice();
+        mem.sort(u64, most, {}, std.sort.asc(u64));
+        return .{ .numbers = most, .max = max };
+    }
+};
diff --git a/Task/Sleep/Quackery/sleep.quackery b/Task/Sleep/Quackery/sleep.quackery
new file mode 100644
index 0000000000..63bbf56a18
--- /dev/null
+++ b/Task/Sleep/Quackery/sleep.quackery
@@ -0,0 +1,7 @@
+  [ $ \import time
+time.sleep(from_stack())\
+    python ]              is sleep ( seconds --> )
+
+  say "Sleeping..."
+  10 sleep
+  say "Awake!"
diff --git a/Task/Sleep/Standard-ML/sleep-1.ml b/Task/Sleep/Standard-ML/sleep-1.ml
new file mode 100644
index 0000000000..ad62f83d2b
--- /dev/null
+++ b/Task/Sleep/Standard-ML/sleep-1.ml
@@ -0,0 +1,12 @@
+fun doSleep () =
+  let
+    val maybeline = TextIO.inputLine TextIO.stdIn
+    val line = if isSome maybeline then valOf maybeline else raise Fail "Enter a number of seconds"
+    val maybesecs = Real.fromString line
+    val secs = if isSome maybesecs then valOf maybesecs else raise Fail "Bad number entered"
+    val () = print "Sleeping...\n"
+    val () = OS.Process.sleep (Time.fromReal secs)
+    val () = print "Awake!\n"
+  in
+    ()
+  end
diff --git a/Task/Sleep/Standard-ML/sleep-2.ml b/Task/Sleep/Standard-ML/sleep-2.ml
new file mode 100644
index 0000000000..b535620c46
--- /dev/null
+++ b/Task/Sleep/Standard-ML/sleep-2.ml
@@ -0,0 +1,2 @@
+(* load the above function in the REPL and then: *)
+PolyML.export("doSleep.o", doSleep);
diff --git a/Task/Sleep/Standard-ML/sleep.ml b/Task/Sleep/Standard-ML/sleep.ml
deleted file mode 100644
index dc947357b6..0000000000
--- a/Task/Sleep/Standard-ML/sleep.ml
+++ /dev/null
@@ -1,8 +0,0 @@
-(TextIO.print "input a number of seconds please: ";
-let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
-  TextIO.print "Sleeping...\n";
-  OS.Process.sleep (Time.fromReal seconds);  (* it takes a Time.time data structure as arg,
-                                               but in my implementation it seems to round down to the nearest second.
-                                               I dunno why; it doesn't say anything about this in the documentation *)
-  TextIO.print "Awake!\n"
-end)
diff --git a/Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Ada/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.ada b/Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Ada/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.ada
new file mode 100644
index 0000000000..691e6d45dd
--- /dev/null
+++ b/Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Ada/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.ada
@@ -0,0 +1,40 @@
+-- Rosetta Code Task written in Ada
+-- Smallest number k such that k+2^m is composite for all m less than k
+-- https://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
+-- loosely translated from the Python solution
+-- uses Unbounded_Unsigneds from Simple Components
+-- January 2025, R. B. E. (with significant support from the author of the Simple Components Ada Package)
+
+with Ada.Text_IO;                 use Ada.Text_IO;
+with Unbounded_Unsigneds;         use Unbounded_Unsigneds;
+with Unbounded_Unsigneds.Primes;  use Unbounded_Unsigneds.Primes;
+
+procedure Smallest_k is
+
+   function Is_A033919 (K : Bit_Count) return Boolean is
+      N : Unbounded_Unsigned;
+   begin
+      for M in 1..K loop
+         Power_Of_Two (M, N);
+         Add (N, Half_Word (K));
+         if Is_Prime (N, 15) /= Composite then
+            return False;
+         end if;
+      end loop;
+      return True;
+   end Is_A033919;
+
+   Numbers_Found : Natural := 0;
+   Max_Numbers_to_Calculate : constant Positive := 5;
+   I : Bit_Count := 3;
+begin
+   loop
+      if Is_A033919 (I) then
+         Numbers_Found := Numbers_Found + 1;
+         Put (Bit_Count'Image (I));
+      end if;
+      exit when Numbers_Found = Max_Numbers_to_Calculate;
+      I := I + 2;
+   end loop;
+   New_Line;
+end Smallest_k;
diff --git a/Task/Sort-a-list-of-object-identifiers/FreeBASIC/sort-a-list-of-object-identifiers.basic b/Task/Sort-a-list-of-object-identifiers/FreeBASIC/sort-a-list-of-object-identifiers.basic
new file mode 100644
index 0000000000..e21c5c205a
--- /dev/null
+++ b/Task/Sort-a-list-of-object-identifiers/FreeBASIC/sort-a-list-of-object-identifiers.basic
@@ -0,0 +1,64 @@
+Function formatOID(oid As String) As String
+    Dim As String result = ""
+    Dim As String segment = ""
+    Dim As Integer i = 1, lenOID = Len(oid)
+
+	While i <= lenOID
+        If Mid(oid, i, 1) = "." Then
+            result &= Space(5 - Len(segment)) & segment & "."
+            segment = ""
+        Else
+            segment &= Mid(oid, i, 1)
+        End If
+        i += 1
+    Wend
+    result &= Space(5 - Len(segment)) & segment
+    Return result
+End Function
+
+Sub quickSort(arr() As String, first As Integer, last As Integer)
+    If first >= last Then Exit Sub
+
+    Dim As Integer i = first, j = last
+    Dim As String pivot = arr((first + last) \ 2)
+
+    Do
+        While arr(i) < pivot: i += 1: Wend
+        While arr(j) > pivot: j -= 1: Wend
+
+        If i <= j Then
+            Swap arr(i), arr(j)
+            i += 1
+            j -= 1
+        End If
+    Loop Until i > j
+
+    If first < j Then quickSort(arr(), first, j)
+    If i < last Then quickSort(arr(), i, last)
+End Sub
+
+' Main program
+Dim As Integer i, j
+Dim As String oids(5) = { _
+"1.3.6.1.4.1.11.2.17.19.3.4.0.10", _
+"1.3.6.1.4.1.11.2.17.5.2.0.79", _
+"1.3.6.1.4.1.11.2.17.19.3.4.0.4", _
+"1.3.6.1.4.1.11150.3.4.0.1", _
+"1.3.6.1.4.1.11.2.17.19.3.4.0.1", _
+"1.3.6.1.4.1.11150.3.4.0" }
+
+For i = 0 To Ubound(oids)
+    oids(i) = formatOID(oids(i))
+Next
+
+quickSort(oids(), 0, Ubound(oids))
+
+For i = 0 To Ubound(oids)
+    Dim As String tmp = ""
+    For j = 1 To Len(oids(i))
+        If Mid(oids(i), j, 1) <> " " Then tmp &= Mid(oids(i), j, 1)
+    Next
+    Print tmp
+Next
+
+Sleep
diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx
index 35e8662e81..0df1385350 100644
--- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx
+++ b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx
@@ -1,6 +1,7 @@
+-- Module Quicksort21.inc - Build 30 Jan 2025
+-- Fast stem sort
+
 default [label]=Quicksort21 [table]=table. [key1]=key1. [key2]=key2. [data1]=data1. [lt]=< [eq]== [gt]=>
--- Sorting procedure - Build 7 Sep 2024
--- (C) Paul van den Eertwegh 2024
 
 [label]:
 -- Sort a stem on 2 key columns, syncing 1 data column
diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx
index 6d56931334..b12abc5667 100644
--- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx
+++ b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx
@@ -1,23 +1,24 @@
+-- Module Quicksort.inc - Build 30 Jan 2025
+-- Generic stem sort
+
 default [label]=Quicksort [lt]=< [eq]== [gt]=>
--- Sorting procedure - Build 7 Sep 2024
--- (C) Paul van den Eertwegh 2024
 
 [label]:
 -- Sort a stem on 1 or more key columns, syncing 0 or more data columns
 procedure expose (table)
 arg table,keys,data
 -- Collect keys
-kn = words(keys)
+kn = Words(keys)
 do x = 1 to kn
-   key.x = word(keys,x)
+   key.x = Word(keys,x)
 end
 -- Collect data
-dn = words(data)
+dn = Words(data)
 do x = 1 to dn
-   data.x = word(data,x)
+   data.x = Word(data,x)
 end
 -- Sort
-n = value(table||0); s = 1; sl.1 = 1; sr.1 = n
+n = Value(table||0); s = 1; sl.1 = 1; sr.1 = n
 do until s = 0
    l = sl.s; r = sr.s; s = s-1
    do until l >= r
@@ -25,14 +26,14 @@ do until s = 0
       if r-l < 20 then do
          do i = l+1 to r
             do x = 1 to kn
-               k.x = value(table||key.x||i)
+               k.x = Value(table||key.x||i)
             end
             do x = 1 to dn
-               d.x = value(table||data.x||i)
+               d.x = Value(table||data.x||i)
             end
             do j=i-1 to l by -1
                do x = 1 to kn
-                  a = value(table||key.x||j)
+                  a = Value(table||key.x||j)
                   if a [gt] k.x then
                      leave x
                   if a [eq] k.x then
@@ -42,11 +43,11 @@ do until s = 0
                end
                k = j+1
                do x = 1 to kn
-                  t = value(table||key.x||j)
+                  t = Value(table||key.x||j)
                   call value table||key.x||k,t
                end
                do x = 1 to dn
-                  t = value(table||data.x||j)
+                  t = Value(table||data.x||j)
                   call value table||data.x||k,t
                end
             end
@@ -66,14 +67,14 @@ do until s = 0
 -- Find optimized pivot
          m = (l+r)%2
          do x = 1 to kn
-            a = value(table||key.x||l); b = value(table||key.x||m)
+            a = Value(table||key.x||l); b = Value(table||key.x||m)
             if a [gt] b then do
                do y = 1 to kn
-                  t = value(table||key.y||l); u = value(table||key.y||m)
+                  t = Value(table||key.y||l); u = Value(table||key.y||m)
                   call value table||key.y||l,u; call value table||key.y||m,t
                end
                do y = 1 to dn
-                  t = value(table||data.y||l); u = value(table||data.y||m)
+                  t = Value(table||data.y||l); u = Value(table||data.y||m)
                   call value table||data.y||l,u; call value table||data.y||m,t
                end
                leave
@@ -82,14 +83,14 @@ do until s = 0
                leave
          end
          do x = 1 to kn
-            a = value(table||key.x||l); b = value(table||key.x||r)
+            a = Value(table||key.x||l); b = Value(table||key.x||r)
             if a [gt] b then do
                do y = 1 to kn
-                  t = value(table||key.y||l); u = value(table||key.y||r)
+                  t = Value(table||key.y||l); u = Value(table||key.y||r)
                   call value table||key.y||l,u; call value table||key.y||r,t
                end
                do y = 1 to dn
-                  t = value(table||data.y||l); u = value(table||data.y||r)
+                  t = Value(table||data.y||l); u = Value(table||data.y||r)
                   call value table||data.y||l,u; call value table||data.y||r,t
                end
                leave
@@ -98,14 +99,14 @@ do until s = 0
                leave
          end
          do x = 1 to kn
-            a = value(table||key.x||m); b = value(table||key.x||r)
+            a = Value(table||key.x||m); b = Value(table||key.x||r)
             if a [gt] b then do
                do y = 1 to kn
-                  t = value(table||key.y||m); u = value(table||key.y||r)
+                  t = Value(table||key.y||m); u = Value(table||key.y||r)
                   call value table||key.y||m,u; call value table||key.y||r,t
                end
                do y = 1 to dn
-                  t = value(table||data.y||m); u = value(table||data.y||r)
+                  t = Value(table||data.y||m); u = Value(table||data.y||r)
                   call value table||data.y||m,u; call value table||data.y||r,t
                end
                leave
@@ -116,12 +117,12 @@ do until s = 0
 -- Rearrange rows in partition
          i = l; j = r
          do x = 1 to kn
-            p.x = value(table||key.x||m)
+            p.x = Value(table||key.x||m)
          end
          do until i > j
             do i = i
                do x = 1 to kn
-                  a = value(table||key.x||i)
+                  a = Value(table||key.x||i)
                   if a [lt] p.x then
                      leave x
                   if a [eq] p.x then
@@ -132,7 +133,7 @@ do until s = 0
             end
             do j = j by -1
                do x = 1 to kn
-                  a = value(table||key.x||j)
+                  a = Value(table||key.x||j)
                   if a [gt] p.x then
                      leave x
                   if a [eq] p.x then
@@ -143,11 +144,11 @@ do until s = 0
             end
             if i <= j then do
                do x = 1 to kn
-                  t = value(table||key.x||i); u = value(table||key.x||j)
+                  t = Value(table||key.x||i); u = Value(table||key.x||j)
                   call value table||key.x||i,u; call value table||key.x||j,t
                end
                do x = 1 to dn
-                  t = value(table||data.x||i); u = value(table||data.x||j)
+                  t = Value(table||data.x||i); u = Value(table||data.x||j)
                   call value table||data.x||i,u; call value table||data.x||j,t
                end
                i = i+1; j = j-1
diff --git a/Task/Sort-an-integer-array/Joy/sort-an-integer-array.joy b/Task/Sort-an-integer-array/Joy/sort-an-integer-array.joy
new file mode 100644
index 0000000000..e9e6912162
--- /dev/null
+++ b/Task/Sort-an-integer-array/Joy/sort-an-integer-array.joy
@@ -0,0 +1,5 @@
+    1 3 2 4
+   stack dup.
+   [4 2 3 1]
+   qsort.
+   [1 2 3 4]
diff --git a/Task/Sort-an-integer-array/M2000-Interpreter/sort-an-integer-array.m2000 b/Task/Sort-an-integer-array/M2000-Interpreter/sort-an-integer-array.m2000
new file mode 100644
index 0000000000..8a4cd71eca
--- /dev/null
+++ b/Task/Sort-an-integer-array/M2000-Interpreter/sort-an-integer-array.m2000
@@ -0,0 +1,21 @@
+module Sort_an_integer_array{
+	const n=10
+	// s() for feeding array
+	s=lambda n=1 (x)->{=x-n:n++}
+	dim a(1 to n) as long long< len inp$[]
+      linpos = -1
+      return
+   .
+   lin$ = inp$[linpos]
+   linind = 0
+   for c$ in strchars lin$
+      if istab = -1
+         if c$ = " "
+            istab = 0
+         elif c$ = "\t"
+            stdind = 1
+            istab = 1
+         .
+      .
+      if c$ <> " " and c$ <> "\t"
+         if stdind = -1 and linind > 0 : stdind = linind
+         break 1
+      .
+      if istab = 0 and c$ = " " or istab = 1 and c$ = "\t"
+         linind += 1
+      else
+         print "mix of tab and space - line " & linpos
+         linpos = -1
+         return
+      .
+   .
+.
+func$[] outline .
+   curind = linind
+   repeat
+      #
+      until linpos = -1 or linind < curind
+      if linind = curind
+         r$[][] &= [ lin$ ]
+      elif linind = curind + stdind
+         h$[] = outline
+         for h$ in h$[] : r$[$][] &= h$
+      else
+         if linpos <> -1 : print "indentation error - line " & linpos
+         linpos = -1
+      .
+      nextline
+   .
+   sort r$[][]
+   for i to len r$[][]
+      for r$ in r$[i][] : r$[] &= r$
+   .
+   if linpos <> -1 : linpos -= 1
+   return r$[]
+.
+proc run dir . .
+   sortdir = dir
+   call init
+   nextline
+   for s$ in outline : print s$
+   print ""
+.
+run 1
+run -1
+#
+input_data
+zeta
+    beta
+    gamma
+        lambda
+        kappa
+        mu
+    delta
+alpha
+    theta
+    iota
+    epsilon
diff --git a/Task/Sort-an-outline-at-every-level/FreeBASIC/sort-an-outline-at-every-level.basic b/Task/Sort-an-outline-at-every-level/FreeBASIC/sort-an-outline-at-every-level.basic
new file mode 100644
index 0000000000..be7503a61b
--- /dev/null
+++ b/Task/Sort-an-outline-at-every-level/FreeBASIC/sort-an-outline-at-every-level.basic
@@ -0,0 +1,293 @@
+Type StringArray
+    Dim elements(Any) As String
+    Dim cnt As Integer
+
+    Declare Sub annadir(value As String)
+    Declare Function join(delimiter As String) As String
+End Type
+
+Sub StringArray.annadir(value As String)
+    this.cnt += 1
+    Redim Preserve this.elements(this.cnt - 1)
+    this.elements(this.cnt - 1) = value
+End Sub
+
+Function StringArray.join(delimiter As String) As String
+    Dim result As String = ""
+    For i As Integer = 0 To this.cnt - 1
+        If i > 0 Then result &= delimiter
+        result &= this.elements(i)
+    Next
+    Return result
+End Function
+
+Function Replace(text As String, find As String, replaceWith As String) As String
+    Dim result As String = text
+    Dim posic As Integer = Instr(result, find)
+
+    While posic > 0
+        result = Left(result, posic - 1) & replaceWith & Mid(result, posic + Len(find))
+        posic = Instr(posic + Len(replaceWith), result, find)
+    Wend
+
+    Return result
+End Function
+
+Function trimLeft(text As String, chars As String) As String
+    Dim i As Integer = 1
+    While i <= Len(text) Andalso Instr(chars, Mid(text, i, 1)) > 0
+        i += 1
+    Wend
+    Return Mid(text, i)
+End Function
+
+Function trimRight(text As String, chars As String) As String
+    Dim i As Integer = Len(text)
+    While i > 0 Andalso Instr(chars, Mid(text, i, 1)) > 0
+        i -= 1
+    Wend
+    Return Left(text, i)
+End Function
+
+Sub sortedOutline(originalOutline() As String, ascending As Boolean)
+    Dim As String indent = "", del = Chr(127), sep = Chr(0)
+    Dim As Integer outlineCount = Ubound(originalOutline) + 1
+    Dim As StringArray messages, nodes
+    Dim As Integer i, j
+
+    Dim As String outline(outlineCount - 1)
+    ' Copy original array
+    For i = 0 To outlineCount - 1
+        outline(i) = originalOutline(i)
+    Next
+
+    ' Check first line indentation
+    If trimLeft(outline(0), " " + Chr(9)) <> outline(0) Then
+        Print "    outline structure is unclear"
+        Exit Sub
+    End If
+
+    ' Process indentation
+    For i = 1 To outlineCount - 1
+        Dim As String linea = outline(i)
+        Dim As Integer lc = Len(linea)
+
+        If Left(linea, 2) = "  " Orelse Left(linea, 1) = Chr(9) Then
+            Dim As String trimmedLine = trimLeft(linea, " " + Chr(9))
+            Dim As String currIndent = Left(linea, lc - Len(trimmedLine))
+
+            If indent = "" Then
+                indent = currIndent
+            Else
+                Dim As Boolean correctionNeeded = False
+
+                If (Instr(currIndent, Chr(9)) > 0 Andalso Instr(indent, Chr(9)) = 0) Orelse _
+                    (Instr(currIndent, Chr(9)) = 0 Andalso Instr(indent, Chr(9)) > 0) Then
+                    messages.annadir(indent + "corrected inconsistent whitespace use at line '" + linea + "'")
+                    correctionNeeded = True
+                Elseif (Len(currIndent) Mod Len(indent)) <> 0 Then
+                    messages.annadir(indent + "corrected inconsistent indent width at line '" + linea + "'")
+                    correctionNeeded = True
+                End If
+
+                If correctionNeeded Then
+                    Dim As Integer mult = Int((Len(currIndent) + Len(indent)/2) / Len(indent))
+                    Dim As String newIndent = ""
+                    For j = 1 To mult
+                        newIndent &= indent
+                    Next
+                    outline(i) = newIndent & trimmedLine
+                End If
+            End If
+        End If
+    Next
+
+    ' Create levels array
+    Dim As Integer levels(outlineCount - 1)
+    levels(0) = 1
+    Dim As Integer level = 1
+    Dim As String margin = ""
+
+    Do
+        Dim As Boolean allProcessed = True
+        For i = 0 To outlineCount - 1
+            If levels(i) = 0 Then
+                allProcessed = False
+                Exit For
+            End If
+        Next
+        If allProcessed Then Exit Do
+
+        Dim As Integer mc = Len(margin)
+        For i = 1 To outlineCount - 1
+            If levels(i) = 0 Then
+                If Left(outline(i), mc) = margin Andalso _
+                    Mid(outline(i), mc + 1, 1) <> " " Andalso _
+                    Mid(outline(i), mc + 1, 1) <> Chr(9) Then
+                    levels(i) = level
+                End If
+            End If
+        Next
+        margin += indent
+        level += 1
+    Loop
+
+    ' Sort the outline
+    Dim As String lines(outlineCount - 1)
+    lines(0) = outline(0)
+
+    For i = 1 To outlineCount - 1
+        If levels(i) > levels(i-1) Then
+            If nodes.cnt = 0 Then
+                nodes.annadir(outline(i-1))
+            Else
+                nodes.annadir(sep + outline(i-1))
+            End If
+        Elseif levels(i) < levels(i-1) Then
+            j = levels(i-1) - levels(i)
+            nodes.cnt -= j
+            Redim Preserve nodes.elements(nodes.cnt - 1)
+        End If
+
+        If nodes.cnt > 0 Then
+            lines(i) = nodes.join("") & sep & outline(i)
+        Else
+            lines(i) = outline(i)
+        End If
+    Next
+
+    ' Sort lines
+    If ascending Then
+        For i = 0 To outlineCount - 2
+            For j = i + 1 To outlineCount - 1
+                If lines(i) > lines(j) Then Swap lines(i), lines(j)
+            Next
+        Next
+    Else
+        Dim As Integer maxLen = Len(lines(0))
+        For i = 1 To outlineCount - 1
+            If Len(lines(i)) > maxLen Then maxLen = Len(lines(i))
+        Next
+
+        For i = 0 To outlineCount - 1
+            lines(i) = lines(i) & String(maxLen - Len(lines(i)), del)
+        Next
+
+        For i = 0 To outlineCount - 2
+            For j = i + 1 To outlineCount - 1
+                If lines(i) < lines(j) Then Swap lines(i), lines(j)
+            Next
+        Next
+    End If
+
+    ' Process final lines
+    For i = 0 To outlineCount - 1
+        Dim As String parts()
+        Dim As Integer partCount = 0
+        Dim As String tmp = lines(i)
+
+        ' Split by separator
+        Do
+            Dim As Integer posic = Instr(tmp, sep)
+            If posic = 0 Then
+                partCount += 1
+                Redim Preserve parts(partCount - 1)
+                parts(partCount - 1) = tmp
+                Exit Do
+            End If
+            partCount += 1
+            Redim Preserve parts(partCount - 1)
+            parts(partCount - 1) = Left(tmp, posic - 1)
+            tmp = Mid(tmp, posic + 1)
+        Loop
+
+        lines(i) = parts(partCount - 1)
+        If Not ascending Then lines(i) = trimRight(lines(i), del)
+    Next
+
+    ' Print messages if any
+    If messages.cnt > 0 Then
+        Print messages.join(!"\n")
+        Print
+    End If
+
+    ' Print result
+    For i = 0 To outlineCount - 1
+        Print lines(i)
+    Next
+End Sub
+
+' Main program with test cases
+Dim outline(10) As String
+outline(0) = "zeta"
+outline(1) = "    beta"
+outline(2) = "    gamma"
+outline(3) = "        lambda"
+outline(4) = "        kappa"
+outline(5) = "        mu"
+outline(6) = "    delta"
+outline(7) = "alpha"
+outline(8) = "    theta"
+outline(9) = "    iota"
+outline(10) = "    epsilon"
+
+Print "Four space indented outline, ascending sort:"
+sortedOutline(outline(), True)
+
+Print !"\nFour space indented outline, descending sort:"
+sortedOutline(outline(), False)
+
+' Create outline2 (tab version)
+Dim outline2(10) As String
+For i As Integer = 0 To 10
+    outline2(i) = Replace(outline(i), "    ", Chr(9))
+Next
+
+' Create outline3
+Dim outline3(10) As String
+outline3(0) = "alpha"
+outline3(1) = "    epsilon"
+outline3(2) = "        iota"
+outline3(3) = "    theta"
+outline3(4) = "zeta"
+outline3(5) = "    beta"
+outline3(6) = "    delta"
+outline3(7) = "    gamma"
+outline3(8) = "    " + Chr(9) + "   kappa"
+outline3(9) = "        lambda"
+outline3(10) = "        mu"
+
+' Create outline4
+Dim outline4(10) As String
+outline4(0) = "zeta"
+outline4(1) = "    beta"
+outline4(2) = "   gamma"
+outline4(3) = "        lambda"
+outline4(4) = "         kappa"
+outline4(5) = "        mu"
+outline4(6) = "    delta"
+outline4(7) = "alpha"
+outline4(8) = "    theta"
+outline4(9) = "    iota"
+outline4(10) = "    epsilon"
+
+' Add these test cases after the first two Print calls
+Print !"\nTab indented outline, ascending sort:"
+sortedOutline(outline2(), True)
+
+Print !"\nTab indented outline, descending sort:"
+sortedOutline(outline2(), False)
+
+Print !"\nFirst unspecified outline, ascending sort:"
+sortedOutline(outline3(), True)
+
+Print !"\nFirst unspecified outline, descending sort:"
+sortedOutline(outline3(), False)
+
+Print !"\nSecond unspecified outline, ascending sort:"
+sortedOutline(outline4(), True)
+
+Print !"\nSecond unspecified outline, descending sort:"
+sortedOutline(outline4(), False)
+
+Sleep
diff --git a/Task/Sort-an-outline-at-every-level/M2000-Interpreter/sort-an-outline-at-every-level.m2000 b/Task/Sort-an-outline-at-every-level/M2000-Interpreter/sort-an-outline-at-every-level.m2000
new file mode 100644
index 0000000000..0b95477083
--- /dev/null
+++ b/Task/Sort-an-outline-at-every-level/M2000-Interpreter/sort-an-outline-at-every-level.m2000
@@ -0,0 +1,137 @@
+MODULE Sort_an_outline_at_every_level {
+	CLASS PACK {
+		PAD$
+		HEAD=QUEUE
+	CLASS:
+		MODULE PACK (.PAD$) {
+		}
+	}
+	FUNCTION CREATETREE(A$){
+		CONST I$=CHR$(9)+CHR$(32)
+		L=1
+		PR=PACK()
+		A=QUEUE
+		F=QUEUE
+		LN=0
+		DIM LINE$()
+		LINE$()=PIECE$(A$, CHR$(13)+CHR$(10))
+		MAX=LEN(LINE$())
+		INTEGER NORM[0]=1
+		FOR I=0 TO MAX-2
+			FOR M=1 TO LEN(LINE$(I))
+				IF INSTR(I$, MID$(LINE$(I),M, 1))=0 THEN EXIT FOR
+			NEXT
+			IF L=M THEN
+				IF NOT EMPTY THEN READ PREV$, PR: APPEND A, PREV$:=PR
+				PUSH PACK(LEFT$(LINE$(I), M-1)), MID$(LINE$(I), M)
+			ELSE.IF L{
+		}
+		TRAVERSAL(A)
+		PRINT "ASCENDING ORDER"
+		JOB=LAMBDA (Z)->{SORT ASCENDING Z}
+		TRAVERSAL(A)
+		PRINT "DESCENDING ORDER"
+		JOB=LAMBDA (Z)->{SORT DESCENDING Z}
+		TRAVERSAL(A)
+		PRINT "PRESS ANY KEY"
+		PUSH KEY$
+		DROP
+	END SUB
+	SUB TRAVERSAL(A)
+		CALL JOB(A)
+		LOCAL W=EACH(A)
+		LOCAL M=PACK()
+		WHILE W
+			M=EVAL(W)
+			// USING -2 TO PROCESS TABS.
+			PRINT #-2, M.PAD$+EVAL$(W!)
+			TRAVERSAL(M.HEAD)
+		END WHILE
+	END SUB
+}
+Sort_an_outline_at_every_level
diff --git a/Task/Sort-disjoint-sublist/FutureBasic/sort-disjoint-sublist.basic b/Task/Sort-disjoint-sublist/FutureBasic/sort-disjoint-sublist.basic
new file mode 100644
index 0000000000..52f4831947
--- /dev/null
+++ b/Task/Sort-disjoint-sublist/FutureBasic/sort-disjoint-sublist.basic
@@ -0,0 +1,21 @@
+void local fn DoIt
+  int i, values(7) = {7,6,5,4,3,2,1,0}, indices(2) = {6,1,7}
+
+  print @"Before sort:"
+  for i = 0 to 7
+    print values(i);@" ";
+  next
+
+  for i = 0 to 1
+    if ( values(indices(i)) > values(indices(i+1)) ) then swap values(indices(i)),values(indices(i+1))
+  next
+
+  print @"\n\nAfter sort:"
+  for i = 0 to 7
+    print values(i);@" ";
+  next
+end fn
+
+fn DoIt
+
+HandleEvents
diff --git a/Task/Sort-three-variables/EDSAC-order-code/sort-three-variables.edsac b/Task/Sort-three-variables/EDSAC-order-code/sort-three-variables.edsac
index d5c531fc63..293eac726c 100644
--- a/Task/Sort-three-variables/EDSAC-order-code/sort-three-variables.edsac
+++ b/Task/Sort-three-variables/EDSAC-order-code/sort-three-variables.edsac
@@ -1,47 +1,81 @@
 [Sort three variables, for Rosetta Code.
- EDSAC, Initial Orders 2]
-[---------------------------------------------------------------------------
- Sorts three 35-bit variables x, y, x, stored at 0#V, 2#V, 4#V respectively.
+ EDSAC, Initial Orders 2.
+--------------------------------------------------------------------------------
+ Sorts three variables x, y, x, stored in consecutive 35-bit locations.
  Uses the algortihm:
     if x > z then swap( x,z)
     if y > z then swap( y,z)
     if x > y then swap( x,y)
  At most two swaps are carried out in any particular case.
- ----------------------------------------------------------------------------]
+ On EDSAC, whether a variable is an integer or a fixed-point real is a matter
+   of interpretation. The integer N has the same bit-pattern as the fixed-point
+   real N*(2^-34). In this program, variables are regarded as integers.
+ NB Integers are here compared by subtraction and noting the sign of the result.
+   It's assumed that the subtraction doesn't overflow the accumulator.
+   This will be OK if the absolute values of the integers are less than 2^33.
+ ------------------------------------------------------------------------------]
 [Arrange the storage]
-            T47K P96F  [M parameter: main routine]
-            T55K P128F [V parameter: variables to be sorted]
+          T55K P56F       [V parameter: variables to be sorted]
+          T46K P62F       [N parameter: print subroutine]
+          T47K P120F      [M parameter: main routine]
 
 [Compressed form of library subroutine R2.
  Reads integers at load time and is then overwritten.]
-            GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z
-            T#V     [tell R2 where to store integers]
-[EDIT: List of 35-bit integers separated by 'F', list terminated by '#TZ'.]
-987654321F500000000F123456789#TZ
+          E25K TN  [will be overwritten by the following print subroutine]
+          GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z
+          T#V      [tell R2 where to store integers]
+[List of 35-bit integers separated by 'F', list terminated by '#TZ'.
+-12 is entered as -12 + 2^35. Uncomment the desired starting order.]
+ [34359738356F0F77444#TZ]
+ [34359738356F77444F0#TZ]
+ [0F34359738356F77444#TZ]
+ [0F77444F34359738356#TZ]
+  77444F34359738356F0#TZ
+ [77444F0F34359738356#TZ]
+
+[Modified version of library subroutine P7.
+ Prints signed integer left-justified. Integer is passed in 0D.]
+  GKA3FT42@A47@T31@ADE10@T31@A46@T31@SDTDH44#@NDYFLDT4DS43@
+  TFH17@S17@A43@G23@UFS43@T1FV4DAFG48@SFLDUFXFOFFFSFL4FT4DA47@
+  T31@A1FA43@G20@XFT44#ZPFT43ZP1024FP610D@524DO26@XFSFL8FT4DE39@
 
 [Main routine]
-            E25K TM GK
-      [0]   A4#V S#V  [accumulator := z - x]
-            E8@       [skip the swap if x <= z]
-            TD        [0D := z - x]
-            A#V U4#V  [z := x]
-            AD        [acc := old z]
-            T#V       [x := old z]
-      [8]   TF        [clear acc]
-            A4#V S2#V [acc := z - y]
-            E17@      [skip the swap if y <= z]
-            TD        [0D := z - y]
-            A2#V U4#V [z := y]
-            AD        [acc := old z]
-            T2#V      [y := old z]
-     [17]   TF        [clear acc]
-            A2#V S#V  [acc := y - x]
-            E26@      [skip the swap if x <= y]
-            TD        [0D := y - x]
-            A#V U2#V  [y := x]
-            AD        [acc := old y]
-            T#V       [x := old y]
-     [26]   ZF        [halt the machine]
-            EZ        [define entry point]
-            PF        [acc = 0 on entry]
+          E25K TM GK
+    [0]   #F              [figures shift]
+    [1]   NF              [comma (in figures mode)]
+    [2]   !F              [space]
+    [3]   @F              [carriage return]
+    [4]   &F              [line feed]
+    [5]   K4096F          [null]
+       [Enter here with accumulator = 0]
+    [6]   A4#V S#V        [acc := z - x]
+          E14@            [skip the swap if x <= z]
+          TD              [0D := z - x]
+          A#V U4#V        [z := x]
+          AD              [acc := old z]
+          T#V             [x := old z]
+   [14]   TF              [clear acc]
+          A4#V S2#V       [acc := z - y]
+          E23@            [skip the swap if y <= z]
+          TD              [0D := z - y]
+          A2#V U4#V       [z := y]
+          AD              [acc := old z]
+          T2#V            [y := old z]
+   [23]   TF              [clear acc]
+          A2#V S#V        [acc := y - x]
+          E32@            [skip the swap if x <= y]
+          TD              [0D := y - x]
+          A#V U2#V        [y := x]
+          AD              [acc := old y]
+          T#V             [x := old y]
+   [32]   TF              [clear acc]
+       [Print variables after sorting]
+          O@              [set teleprinter to figures mode]
+          A#V TD A36@ GN O1@ O2@  [print 1st variable plus comma, space]
+          A2#V TD A42@ GN O1@ O2@ [print 2nd variable plus comma, space]
+          A4#V TD A48@ GN O3@ O4@ [print 3rd variable plus CR, LF]
+          O5@             [print null to flush teleprinter buffer]
+          ZF              [halt the machine]
+          E6Z             [define entry point]
+          PF              [accumulator = 0 on entry]
 [end]
diff --git a/Task/Sorting-algorithms-Merge-sort/OoRexx/sorting-algorithms-merge-sort.rexx b/Task/Sorting-algorithms-Merge-sort/OoRexx/sorting-algorithms-merge-sort.rexx
new file mode 100644
index 0000000000..1d53ca4fa2
--- /dev/null
+++ b/Task/Sorting-algorithms-Merge-sort/OoRexx/sorting-algorithms-merge-sort.rexx
@@ -0,0 +1,56 @@
+/******************************************************************
+* Translated from REXX Version 1a
+* with a little help from a friend:-)
+******************************************************************/
+Call Init
+Call show 'Array:'
+arr=mergeSort(arr)
+Say ''
+Call show 'Sorted:'
+Exit
+mergesort: Procedure
+  Use Arg a
+  If a~items=1 Then Return a
+  mid=a~items%2+1
+  l1=a~section(1,mid-1)
+  l2=a~section(mid)
+  l1 = mergesort( l1 )
+  l2 = mergesort( l2 )
+  Return merge( l1, l2 )
+
+merge: Procedure
+  Use Arg a,b
+  c=.array~new
+  Do while a~items>0 & b~items>0
+    if  a[1] > b[1] Then Do
+       c~append(b[1])
+       b=b~section(2)
+       End
+    Else Do
+       c~append(a[1])
+       a=a~section(2)
+       End
+   end
+   c~appendAll(a)
+   c~appendAll(b)
+   Return c
+
+init:
+  arr=.array~new
+  arr~append('---The seven deadly sins---')
+  arr~append('===========================')
+  arr~append('pride')
+  arr~append('avarice')
+  arr~append('wrath')
+  arr~append('envy')
+  arr~append('gluttony')
+  arr~append('sloth')
+  arr~append('lust')
+  Return
+
+show:
+  Say arg(1)
+  Do elem over arr
+    Say elem
+    End
+  Return
diff --git a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-1.rexx b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-1.rexx
index 266d49875a..3b65c4ed6f 100644
--- a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-1.rexx
+++ b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-1.rexx
@@ -1,40 +1,48 @@
-/*REXX pgm sorts a stemmed array (numbers and/or chars) using the  merge─sort algorithm.*/
-call init                                        /*sinfully initialize the   @   array. */
-call show      'before sort'                     /*show the   "before"  array elements. */
-                            say copies('▒', 75)  /*display a separator line to the term.*/
-call merge          #                            /*invoke the  merge sort  for the array*/
-call show      ' after sort'                     /*show the    "after"  array elements. */
-exit 0                                           /*stick a fork in it,  we're all done. */
-/*──────────────────────────────────────────────────────────────────────────────────────*/
-init: @.=;    @.1= '---The seven deadly sins---'  ;    @.4= "avarice"  ;   @.7= 'gluttony'
-              @.2= '==========================='  ;    @.5= "wrath"    ;   @.8= 'sloth'
-              @.3= 'pride'                        ;    @.6= "envy"     ;   @.9= 'lust'
-      do #=1  until @.#==''; end;   #= #-1;   return      /*#:  # of entries in @ array.*/
-/*──────────────────────────────────────────────────────────────────────────────────────*/
-show: do j=1  for #; say right('element',20) right(j,length(#)) arg(1)":" @.j; end; return
-/*──────────────────────────────────────────────────────────────────────────────────────*/
-merge: procedure expose @. !.;   parse arg n, L;   if L==''  then do;  !.=;  L= 1;  end
-          if n==1  then return;     h= L + 1
-          if n==2  then do; if @.L>@.h  then do; _=@.h; @.h=@.L; @.L=_; end; return;  end
-          m= n % 2                                     /* [↑]  handle case of two items.*/
-          call merge  n-m, L+m                         /*divide items  to the left   ···*/
-          call merger m,   L,   1                      /*   "     "     "  "  right  ···*/
-          i= 1;                     j= L + m
-                     do k=L  while k word(b,1) Then Do  -- numeric or mixed ascending
+* if  word(a,1) >> word(b,1) Then Do -- string ascending
+* if  word(a,1) < word(b,1) Then Do  -- numeric or mixed descending
+* if  word(a,1) << word(b,1) Then Do -- string descending
+* you may perform the usual sorts.
+***********************************************************************/
+Parse Arg list
+If list='' Then
+  unsortedList ='890 481 272 628 353 513 654 138 474 531'
+Else
+  unsortedList = list
+sortedList = mergeSort(unsortedList)
+say 'list  ='unsortedList
+say 'sorted='space(sortedList)
+Exit
+mergesort: Procedure
+  Parse Arg a
+   if words(a)=1 Then return a
+   mid=words(a)%2+1
+   l1=subword(a,1,mid-1)
+   l2=subword(a,mid)
+      l1 = mergesort( l1 )
+      l2 = mergesort( l2 )
+      return merge( l1, l2 )
+merge: Procedure
+  Parse Arg a,b
+  c=''
+  Do while words(a)>0 & words(b)>0
+    if  word(a,1) > word(b,1) Then Do
+       c=c word(b,1)
+       b=subword(b,2)
+       End
+    Else Do
+       c=c word(a,1)
+       a=subword(a,2)
+       End
+   end
+   c=c a
+   c=c b
+   return c
diff --git a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-2.rexx b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-2.rexx
index 954c469b17..1b3594903e 100644
--- a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-2.rexx
+++ b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-2.rexx
@@ -1,67 +1,70 @@
-Main:
-call Generate
-call Show
-call Mergesort 1,n
-call Show
-exit
-
-Generate:
-call Random,,12345
-n = 10
-do i = 1 to n
-   stem.i = Random()
-end
-stem.0 = n
-return
-
-Show:
-do i = 1 to n
-   say right(i,2) right(stem.i,3)
-end
-say
-return
-
-Mergesort:
-procedure expose stem. work.
-arg b,e
-if e-b < 1 then
-   return
-if e-b = 1 then do
-   if stem.b > stem.e then do
-      t = stem.b; stem.b = stem.e; stem.e = t
+/***********************************************************************
+* Translating blanks in the array's elements lets me use Version 1
+***********************************************************************/
+Call Init
+unsortedList=''
+Do i=1 To arr.0
+  If pos('00'x,arr.i)>0 Then Do
+    'Sorry, array elements must not contain ''00''x characters'
+    Exit
+    End
+  unsortedList=unsortedList translate(arr.i,'00'x,' ')
+  End
+say 'Array :'
+Call show
+sortedList = mergeSort(unsortedList)
+Do i=1 To arr.0
+  arr.i=translate(word(sortedList,i),' ','00'x)
+  End
+Say ''
+Say 'Sorted:'
+Call show
+Exit
+show:
+  Do i=1 To arr.0
+    Say 'arr.'i'='arr.i
+    End
+  Return
+mergesort: Procedure
+  Parse Arg a
+  If words(a)=1 Then Return a
+  mid=words(a)%2+1
+  l1=subword(a,1,mid-1)
+  l2=subword(a,mid)
+  l1 = mergesort( l1 )
+  l2 = mergesort( l2 )
+  Return merge( l1, l2 )
+merge: Procedure
+  Parse Arg a,b
+  c=''
+  Do while words(a)>0 & words(b)>0
+    If  word(a,1) > word(b,1) Then Do
+       c=c word(b,1)
+       b=subword(b,2)
+       End
+    Else Do
+       c=c word(a,1)
+       a=subword(a,2)
+       End
    end
-   return
-end
-m = (b+e)%2
-call Mergesort b,m
-call Mergesort m+1,e
-call Merger b,m,e
-return
+   c=c a
+   c=c b
+   Return c
 
-Merger:
-procedure expose stem. work.
-arg b,m,e
-i = b; j = m+1; k = b
-do while i <= m | j <= e
-   select
-      when i <= m & j <= e then do
-         if stem.i <= stem.j then do
-            work.k = stem.i; i = i+1
-         end
-         else do
-            work.k = stem.j; j = j+1
-         end
-         k = k+1
-      end
-      when i<=m then do
-         work.k = stem.i; i = i+1; k = k+1
-      end
-      otherwise do
-         work.k = stem.j; j = j+1; k = k+1
-      end
-   end
-end
-do i = b to e
-   stem.i = work.i
-end
-return
+init:
+  arr.=0
+  Call store '---The seven deadly sins---'
+  Call store '==========================='
+  Call store 'pride'
+  Call store 'avarice'
+  Call store 'wrath'
+  Call store 'envy'
+  Call store 'gluttony'
+  Call store 'sloth'
+  Call store 'lust'
+  Return
+store:
+  z=arr.0+1
+  arr.z=arg(1)
+  arr.0=z
+  Return
diff --git a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx
new file mode 100644
index 0000000000..954c469b17
--- /dev/null
+++ b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx
@@ -0,0 +1,67 @@
+Main:
+call Generate
+call Show
+call Mergesort 1,n
+call Show
+exit
+
+Generate:
+call Random,,12345
+n = 10
+do i = 1 to n
+   stem.i = Random()
+end
+stem.0 = n
+return
+
+Show:
+do i = 1 to n
+   say right(i,2) right(stem.i,3)
+end
+say
+return
+
+Mergesort:
+procedure expose stem. work.
+arg b,e
+if e-b < 1 then
+   return
+if e-b = 1 then do
+   if stem.b > stem.e then do
+      t = stem.b; stem.b = stem.e; stem.e = t
+   end
+   return
+end
+m = (b+e)%2
+call Mergesort b,m
+call Mergesort m+1,e
+call Merger b,m,e
+return
+
+Merger:
+procedure expose stem. work.
+arg b,m,e
+i = b; j = m+1; k = b
+do while i <= m | j <= e
+   select
+      when i <= m & j <= e then do
+         if stem.i <= stem.j then do
+            work.k = stem.i; i = i+1
+         end
+         else do
+            work.k = stem.j; j = j+1
+         end
+         k = k+1
+      end
+      when i<=m then do
+         work.k = stem.i; i = i+1; k = k+1
+      end
+      otherwise do
+         work.k = stem.j; j = j+1; k = k+1
+      end
+   end
+end
+do i = b to e
+   stem.i = work.i
+end
+return
diff --git a/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed b/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed
index ef24e8c56b..a4dd852c14 100644
--- a/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed
+++ b/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed
@@ -1,86 +1,107 @@
 (append) list1 list2
-comment:
+=========
 #true
 (003) "append" list1 list2
 
 (car) pair
-comment:
+=========
 #true
 (002) "car" pair
 
+(cadr) pair
+=========
+#true
+(002) "cadr" pair
+
 (cdr) pair
-comment:
+=========
 #true
 (002) "cdr" pair
 
+(cddr) pair
+=========
+#true
+(002) "cddr" pair
+
 (cons) one two
-comment:
+=========
 #true
 (003) "cons" one two
 
+(list1a) item
+=========
+#true
+(002) "list" item
+
 (map) function list
-comment:
+=========
 #true
 (003) "map" function list
 
 (merge) comparator list1 list2
-comment:
+CONTINUE WITH COLLECT ARGUMENT
 #true
-(merge1) comparator list1 list2 nil
+(merge01) comparator list1 list2 nil
 
-(merge1) comparator list1 list2 collect
-comment:
+(merge01) comparator list1 list2 collect
+LIST2 EXHAUSTED -> MERGED
 (null?) list2
 (append) (reverse) collect list1
 
-(merge1) comparator list1 list2 collect
-comment:
+(merge01) comparator list1 list2 collect
+LIST1 EXHAUSTED -> MERGED
 (null?) list1
 (append) (reverse) collect list2
 
-(merge1) comparator list1 list2 collect
-comment:
+(merge01) comparator list1 list2 collect
+TAKE FROM LIST2 (HANDLES ONE CASE)
 (003) comparator (car) list2 (car) list1
-(merge1) comparator list1 (cdr) list2 (cons) (car) list2 collect
+(merge01) comparator
+  list1
+  (cdr) list2
+  (cons) (car) list2 collect
 
-(merge1) comparator list1 list2 collect
-comment:
+(merge01) comparator list1 list2 collect
+TAKE FROM LIST1 (HANDLES TWO CASES)
 #true
-(merge1) comparator (cdr) list1 list2 (cons) (car) list1 collect
+(merge01) comparator
+  (cdr) list1
+  list2
+  (cons) (car) list1 collect
 
 (null?) value
-comment:
+=========
 #true
 (002) "null?" value
 
 (reverse) list
-comment:
+=========
 #true
 (002) "reverse" list
 
 (sort) comparator jumble
-comment:
+PREPARE JUMBLE AND PERFORM MERGE PASSES -> EXTRACT
 #true
-(car) (sort11) comparator (sort1) jumble
+(car) (sort02) comparator (sort01) jumble
 
-(sort1) jumble
-comment:
+(sort01) jumble
+PREPARED JUMBLE
 #true
-(map) "list" jumble
+(map) list1a jumble
 
-(sort11) comparator jumble
-comment:
+(sort02) comparator jumble
+WHEN ZERO LISTS THEN NIL
 (null?) jumble
 nil
 
-(sort11) comparator jumble
-comment:
+(sort02) comparator jumble
+WHEN ONE LIST THEN ALREADY SORTED
 (null?) (cdr) jumble
 jumble
 
-(sort11) comparator jumble
-comment:
+(sort02) comparator jumble
+REPEATEDLY MERGE ALONG LENGTH
 #true
-(sort11) comparator
-         (cons) (merge) comparator (car) jumble (002) "cadr" jumble
-                (sort11) comparator (002) "cddr" jumble
+(sort02) comparator
+  (cons) (merge) comparator (car) jumble (cadr) jumble
+    (sort02) comparator (cddr) jumble
diff --git a/Task/Sorting-algorithms-Pancake-sort/Forth/sorting-algorithms-pancake-sort.fth b/Task/Sorting-algorithms-Pancake-sort/Forth/sorting-algorithms-pancake-sort.fth
new file mode 100644
index 0000000000..35ab48a346
--- /dev/null
+++ b/Task/Sorting-algorithms-Pancake-sort/Forth/sorting-algorithms-pancake-sort.fth
@@ -0,0 +1,56 @@
+\ swap the values stored at two memory locations
+: exchange ( addr1 addr2 -- )
+  2dup @ >r @ swap ! r> swap ! ;
+
+\ reverse an array of cells in place
+: reverse ( addr u -- )
+  1- cells over +
+  begin
+    2dup <
+  while
+    2dup exchange
+    swap cell+ swap
+    1 cells -
+  repeat 2drop ;
+
+\ index of the largest value in an array of cells
+: max-index ( addr u -- u )
+  0 -rot 0 ?do
+    2dup swap cells + @
+    over i cells + @
+    < if nip i swap then
+  loop drop ;
+
+\ sorts an array of cells in place
+: pancake-sort ( addr u -- )
+  begin
+    dup 1 >
+  while
+    2dup max-index 1+
+    2dup <> if
+      dup 1 > if
+        >r over r> reverse
+      else
+        drop
+      then
+      2dup reverse
+    else
+      drop
+    then
+    1-
+  repeat 2drop ;
+
+\ print an array of cells
+: print-array ( addr u -- )
+  ." [" 0 ?do
+    i 0> if ." , " then
+    dup i cells + @ 1 .r
+  loop drop ." ]" ;
+
+create test-array 6 , 7 , 2 , 1 , 8 , 9 , 5 , 3 , 4 ,
+." Before sorting: "
+test-array 9 print-array cr
+test-array 9 pancake-sort
+." After sorting: "
+test-array 9 print-array cr
+bye
diff --git a/Task/Sorting-algorithms-Quicksort/Quackery/sorting-algorithms-quicksort.quackery b/Task/Sorting-algorithms-Quicksort/Quackery/sorting-algorithms-quicksort.quackery
index 4155c0f3c8..20e2c83133 100644
--- a/Task/Sorting-algorithms-Quicksort/Quackery/sorting-algorithms-quicksort.quackery
+++ b/Task/Sorting-algorithms-Quicksort/Quackery/sorting-algorithms-quicksort.quackery
@@ -6,8 +6,6 @@
 
 [ - -1 1 clamp 1+ ]            is <=>       ( n n --> n )
 
-[ tuck take join swap put ]    is append    ( x s -->   )
-
 [ dup size 2 < if done
   [] less put
   [] same put
@@ -15,8 +13,8 @@
   behead swap witheach
     [ 2dup swap <=>
       [ table less same more ]
-      append ]
-  same append
+      gather ]
+  same gather
   less take recurse
   same take join
   more take recurse join ]     is quicksort (   [ --> [ )
diff --git a/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f b/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f
index 85bdd73c2b..1cf519a11e 100644
--- a/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f
+++ b/Task/Sorting-algorithms-Radix-sort/Fortran/sorting-algorithms-radix-sort.f
@@ -294,161 +294,115 @@
 !***************************************************************************
 !                            End of Superfast LSD sort
 !***************************************************************************
-*=======================================================================
-* RSORT - sort a list of integers by the Radix Sort algorithm
-* Public domain.  This program may be used by any person for any purpose.
-* Origin:  Herman Hollerith, 1887
-*
-*___Name____Type______In/Out____Description_____________________________
-*   IX(N)   Integer   Both      Array to be sorted in increasing order
-*   IW(N)   Integer   Neither   Workspace
-*   N       Integer   In        Length of array
-*
-* ASSUMPTIONS:  Bits in an INTEGER is an even number.
-*               Integers are represented by twos complement.
-*
-* NOTE THAT:  Radix sorting has an advantage when the input is known
-*             to be less than some value, so that only a few bits need
-*             to be compared.  This routine looks at all the bits,
-*             and is thus slower than Quicksort.
-*=======================================================================
-      SUBROUTINE RSORT (IX, IW, N)
-       IMPLICIT NONE
-       INTEGER IX, IW, N
-       DIMENSION IX(N), IW(N)
+!
+! Performs a MSD radi sort using bits.
+! It sorts only using the bit size of the largest and smallest numbers
+! So, on small numbers < 128, it's faster than a Quicksort for very large numbers > 20 bits
+! It's slower.
+! Author: Peter Kelly
+! No claim is made on the code and no warranty implied.
+module msd_bit_sort_module
+    implicit none
+    private
+    public :: msd_bit_sort
 
-       INTEGER I,                        ! count bits
-     $         ILIM,                     ! bits in an integer
-     $         J,                        ! count array elements
-     $         P1OLD, P0OLD, P1, P0,     ! indices to ones and zeros
-     $         SWAP
-       LOGICAL ODD                       ! even or odd bit position
+contains
+    ! Transform signed integer to make it comparable
+    PURE FUNCTION transform_for_sort(x) RESULT(transformed)
+        INTEGER, INTENT(IN) :: x
+        INTEGER :: transformed
 
-*      IF (N < 2) RETURN      ! validate
-*
-        ILIM = Bit_size(i)    !Get the fixed number of bits
-*=======================================================================
-* Alternate between putting data into IW and into IX
-*=======================================================================
-       P1 = N+1
-       P0 = N                ! read from 1, N on first pass thru
-       ODD = .FALSE.
-       DO I = 0, ILIM-2
-         P1OLD = P1
-         P0OLD = P0         ! save the value from previous bit
-         P1 = N+1
-         P0 = 0                 ! start a fresh count for next bit
-
-         IF (ODD) THEN
-           DO J = 1, P0OLD, +1             ! copy data from the zeros
-             IF ( BTEST(IW(J), I) ) THEN
-               P1 = P1 - 1
-               IX(P1) = IW(J)
-             ELSE
-               P0 = P0 + 1
-               IX(P0) = IW(J)
-             END IF
-           END DO
-           DO J = N, P1OLD, -1             ! copy data from the ones
-             IF ( BTEST(IW(J), I) ) THEN
-               P1 = P1 - 1
-               IX(P1) = IW(J)
-             ELSE
-               P0 = P0 + 1
-              IX(P0) = IW(J)
-             END IF
-           END DO
-
-         ELSE
-           DO J = 1, P0OLD, +1             ! copy data from the zeros
-             IF ( BTEST(IX(J), I) ) THEN
-               P1 = P1 - 1
-               IW(P1) = IX(J)
-              ELSE
-               P0 = P0 + 1
-               IW(P0) = IX(J)
-             END IF
-           END DO
-           DO J = N, P1OLD, -1            ! copy data from the ones
-             IF ( BTEST(IX(J), I) ) THEN
-               P1 = P1 - 1
-               IW(P1) = IX(J)
-             ELSE
-               P0 = P0 + 1
-               IW(P0) = IX(J)
-             END IF
-          END DO
-         END IF  ! even or odd i
-
-         ODD = .NOT. ODD
-       END DO  ! next i
-
-*=======================================================================
-*        the sign bit
-*=======================================================================
-       P1OLD = P1
-       P0OLD = P0
-       P1 = N+1
-       P0 = 0
-
-*          if sign bit is set, send to the zero end
-       DO J = 1, P0OLD, +1
-         IF ( BTEST(IW(J), ILIM-1) ) THEN
-           P0 = P0 + 1
-           IX(P0) = IW(J)
-         ELSE
-           P1 = P1 - 1
-           IX(P1) = IW(J)
-         END IF
-       END DO
-       DO J = N, P1OLD, -1
-         IF ( BTEST(IW(J), ILIM-1) ) THEN
-           P0 = P0 + 1
-           IX(P0) = IW(J)
-         ELSE
-           P1 = P1 - 1
-           IX(P1) = IW(J)
-         END IF
-       END DO
-
-*=======================================================================
-*       Reverse the order of the greater value partition
-*=======================================================================
-       P1OLD = P1
-       DO J = N, (P1OLD+N)/2+1, -1
-         SWAP = IX(J)
-         IX(J) = IX(P1)
-         IX(P1) = SWAP
-         P1 = P1 + 1
-       END DO
-       RETURN
-      END ! of RSORT
+        ! XOR with sign bit to make negative numbers sortable
+        ! This inverts the bit representation for negative numbers
+        transformed = IEOR(x, ISHFT(-1, BIT_SIZE(x)-1))
+    END FUNCTION transform_for_sort
 
 
-***********************************************************************
-*         test program
-***********************************************************************
-      PROGRAM t_sort
-       IMPLICIT NONE
-       INTEGER I, N
-       PARAMETER (N = 11)
-       INTEGER IX(N), IW(N)
-       LOGICAL OK
+    RECURSIVE SUBROUTINE msd_bit_sort_internal(arr, left, right, bit)
+        INTEGER, INTENT(INOUT) :: arr(:)
+        INTEGER, INTENT(IN) :: left, right, bit
+        INTEGER :: i, j, temp
+        INTEGER :: transformed_i, transformed_j
 
-       DATA IX / 2, 24, 45, 0, 66, 75, 170, -802, -90, 1066, 666 /
+        ! Base case
+        IF (left >= right .OR. bit < 0) RETURN
 
-       PRINT *, 'before: ', IX
-       CALL RSORT (IX, IW, N)
-       PRINT *, 'after: ', IX
+        i = left
+        j = right
 
-*              compare
-       OK = .TRUE.
-       DO I = 1, N-1
-         IF (IX(I) > IX(I+1)) OK = .FALSE.
-       END DO
-       IF (OK) THEN
-         PRINT *, 't_sort: successful test'
-       ELSE
-         PRINT *, 't_sort: failure!'
-       END IF
-      END ! of test program
+        DO WHILE (i <= j)
+            ! Find elements to swap
+            DO WHILE (i <= j)
+                transformed_i = transform_for_sort(arr(i))
+                transformed_j = transform_for_sort(arr(j))
+
+                ! Partition based on transformed values
+                IF (BTEST(transformed_i, bit) .AND. .NOT. BTEST(transformed_j, bit)) THEN
+                    ! Swap needed
+                    temp = arr(i)
+                    arr(i) = arr(j)
+                    arr(j) = temp
+                    EXIT
+                END IF
+
+                ! Move pointers
+                IF (.NOT. BTEST(transformed_i, bit)) i = i + 1
+                IF (BTEST(transformed_j, bit)) j = j - 1
+            END DO
+
+            ! Adjust pointers
+            IF (i < j) THEN
+                i = i + 1
+                j = j - 1
+            END IF
+        END DO
+
+        ! Recursively sort sub-arrays
+        IF (left < j) THEN
+            CALL msd_bit_sort_internal(arr, left, j, bit-1)
+        END IF
+        IF (i < right) THEN
+            CALL msd_bit_sort_internal(arr, i, right, bit-1)
+        END IF
+    END SUBROUTINE msd_bit_sort_internal
+
+    SUBROUTINE msd_bit_sort(arr)
+        INTEGER, INTENT(INOUT) :: arr(:)
+        INTEGER :: max_bit, n, mini, maxi
+
+        n = SIZE(arr)
+        IF (n < 2) RETURN
+
+        ! Find most significant bit
+        mini = MINVAL(arr)
+        maxi = MAXVAL(arr)
+        max_bit = MAX(BIT_SIZE(arr(1)) - LEADZ(IEOR(mini, maxi)) - 1, 0)
+
+        ! Perform the recursive bit sort
+        CALL msd_bit_sort_internal(arr, 1, n, max_bit)
+    END SUBROUTINE msd_bit_sort
+    end module msd_bit_sort_module
+!
+    program bit_sort_test_harness
+    use msd_bit_sort_module
+    implicit none
+
+    INTEGER, PARAMETER :: ARRAY_SIZE = 2**23
+    INTEGER :: test_array(ARRAY_SIZE)
+    real :: holder(ARRAY_SIZE)
+    INTEGER :: xx,yy,rate
+    call random_number(holder)
+    holder = holder -0.33333
+    test_array = int(holder*1000000.0)
+    ! Initialize with some test values
+
+    PRINT *, "Original Array:"
+    PRINT *, test_array(1:10)
+    call system_clock(count=xx,count_rate=rate)
+    CALL msd_bit_sort(test_array)
+    call system_clock(count=yy)
+    print*,'sort time = ',(real(yy-xx)/rate)
+    PRINT *, "Sorted Array:"
+    PRINT *, test_array(1:5),test_array(array_size-5:)
+
+end program bit_sort_test_harness
diff --git a/Task/Sorting-algorithms-Radix-sort/FreeBASIC/sorting-algorithms-radix-sort.basic b/Task/Sorting-algorithms-Radix-sort/FreeBASIC/sorting-algorithms-radix-sort.basic
new file mode 100644
index 0000000000..5757cb4bb4
--- /dev/null
+++ b/Task/Sorting-algorithms-Radix-sort/FreeBASIC/sorting-algorithms-radix-sort.basic
@@ -0,0 +1,93 @@
+Sub countSort(rs() As Long, expo As Long)
+    Dim As Long lb = Lbound(rs), ub = Ubound(rs)
+    Dim As Long i, t
+    Dim As Long salida(lb To ub), conteo(0 To 9)
+
+    For i = lb To ub
+        t = (rs(i) \ expo) Mod 10
+        conteo(t) += 1
+    Next
+
+    For i = 1 To 9
+        conteo(i) += conteo(i-1)
+    Next
+
+    For i = ub To lb Step -1
+        t = (rs(i) \ expo) Mod 10
+        salida(lb + conteo(t) - 1) = rs(i)
+        conteo(t) -= 1
+    Next
+
+    For i = lb To ub
+        rs(i) = salida(i)
+    Next
+End Sub
+
+Sub radixSort(rs() As Long)
+    Dim As Long lb = Lbound(rs), ub = Ubound(rs)
+
+    ' Find minimum value
+    Dim As Long i, minVal = rs(lb)
+    For i = lb + 1 To ub
+        If rs(i) < minVal Then minVal = rs(i)
+    Next
+
+    ' If negative numbers exist, shift array to positive
+    If minVal < 0 Then
+        For i = lb To ub
+            rs(i) -= minVal
+        Next
+    End If
+
+    ' Find maximum value
+    Dim As Long maxVal = rs(lb)
+    For i = lb + 1 To ub
+        If rs(i) > maxVal Then maxVal = rs(i)
+    Next
+
+    ' Do counting sort for every digit
+    Dim As Long expo = 1
+    While (maxVal \ expo) > 0
+        countSort(rs(), expo)
+        expo *= 10
+    Wend
+
+    ' If we shifted for negatives, shift back
+    If minVal < 0 Then
+        For i = lb To ub
+            rs(i) += minVal
+        Next
+    End If
+End Sub
+
+Sub printArray(rs() As Long)
+    Dim As Long lb = Lbound(rs), ub = Ubound(rs)
+    Print "[ ";
+    For i As Long = lb To ub
+        Print rs(i);
+        If i < ub Then Print ", ";
+    Next
+    Print " ]"
+End Sub
+
+'--- Main Program ---
+Dim As Long i, array(-7 To 7)
+Dim As Long a = Lbound(array), b = Ubound(array)
+
+Randomize Timer
+For i = a To b : array(i) = i : Next i
+
+For i = a To b ' little shuffle
+    Swap array(i), array(Int(Rnd * (b - a + 1)) + a)
+Next i
+
+Print "unsort ";
+For i = a To b : Print Using "####"; array(i); : Next i
+
+radixSort(array())  ' sort the array
+
+Print !"\n  sort ";
+For i = a To b : Print Using "####"; array(i); : Next i
+Print
+
+Sleep
diff --git a/Task/Sorting-algorithms-Shell-sort/Free-Pascal-Lazarus/sorting-algorithms-shell-sort.pas b/Task/Sorting-algorithms-Shell-sort/Free-Pascal-Lazarus/sorting-algorithms-shell-sort.pas
new file mode 100644
index 0000000000..3508fc9b27
--- /dev/null
+++ b/Task/Sorting-algorithms-Shell-sort/Free-Pascal-Lazarus/sorting-algorithms-shell-sort.pas
@@ -0,0 +1,25 @@
+procedure ShellSort(var a: array of extended);
+var
+  i, j, h, n: integer;
+  v: extended;
+begin
+  n := length(a);
+  h := 1;
+  repeat
+    h := 3 * h + 1
+  until h > n;
+  repeat
+    h := h div 3;
+    for i := h to n - 1 do
+    begin
+      v := a[i];
+      j := i;
+      while (j >= h) and (a[j - h] > v) do
+      begin
+        a[j] := a[j - h];
+        j := j - h;
+      end;
+      a[j] := v;
+    end
+  until h = 1;
+end;
diff --git a/Task/Sorting-algorithms-Shell-sort/Object-Pascal/sorting-algorithms-shell-sort.pas b/Task/Sorting-algorithms-Shell-sort/Object-Pascal/sorting-algorithms-shell-sort.pas
new file mode 100644
index 0000000000..6e675ed5f2
--- /dev/null
+++ b/Task/Sorting-algorithms-Shell-sort/Object-Pascal/sorting-algorithms-shell-sort.pas
@@ -0,0 +1,29 @@
+procedure ShellSort(var a: array of extended);
+  { Sorts a vector of arbitrary length }
+  { Requirement: Support for open arrays by Object Pascal compiler }
+  { otherwise please use the algorithm for Pascal, which is less flexible, }
+  { but also supported by Object Pascal }
+var
+  i, j, h, n: integer;
+  v: extended;
+begin
+  n := length(a);
+  h := 1;
+  repeat
+    h := 3 * h + 1
+  until h > n;
+  repeat
+    h := h div 3;
+    for i := h to n - 1 do
+    begin
+      v := a[i];
+      j := i;
+      while (j >= h) and (a[j - h] > v) do
+      begin
+        a[j] := a[j - h];
+        j := j - h;
+      end;
+      a[j] := v;
+    end
+  until h = 1;
+end;
diff --git a/Task/Special-characters/Ring/special-characters.ring b/Task/Special-characters/Ring/special-characters.ring
new file mode 100644
index 0000000000..ed87b635df
--- /dev/null
+++ b/Task/Special-characters/Ring/special-characters.ring
@@ -0,0 +1,9 @@
+load "stdlib.ring"
+
+see "Special characters in Ring:" + nl
+for n = 1 to 255
+    ch = char(n)
+    if isSpecial(ch)
+       see ch + nl
+    ok
+next
diff --git a/Task/Spelling-of-ordinal-numbers/Arturo/spelling-of-ordinal-numbers.arturo b/Task/Spelling-of-ordinal-numbers/Arturo/spelling-of-ordinal-numbers.arturo
new file mode 100644
index 0000000000..d04f2259d6
--- /dev/null
+++ b/Task/Spelling-of-ordinal-numbers/Arturo/spelling-of-ordinal-numbers.arturo
@@ -0,0 +1,71 @@
+small: [
+    "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten"
+    "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen"
+    "eighteen" "nineteen"
+]
+
+tens: [
+    "wrong" "wrong" "twenty" "thirty" "forty"
+    "fifty" "sixty" "seventy" "eighty" "ninety"
+]
+
+prefixes: ["m" "b" "tr" "quadr" "quint" "sext" "sept" "oct" "non" "dec"]
+big: ["" "thousand"] ++ map prefixes 'p -> p ++ "illion"
+
+getOrdinal: function [numstr][
+    return when.has:numstr [
+        [|suffix? "one"] -> replace numstr {/one$/} {first}
+        [|suffix? "two"] -> replace numstr {/two$/} {second}
+        [|suffix? "three"] -> replace numstr {/three$/} {third}
+        [|suffix? "four"] -> replace numstr {/four$/} {forth}
+        [|suffix? "five"] -> replace numstr {/five$/} {fifth}
+        [|suffix? "y"] -> replace numstr {/y$/} {ieth}
+        true -> numstr ++ "th"
+    ]
+]
+
+wordify: function [number :integer][
+    if number < 0 ->
+        return "negative " ++ neg number
+
+    if number < 20 ->
+        return small\[number]
+
+    if number < 100 [
+        [d m]: divmod number 10
+        return tens\[d] ++ (zero? m)? -> "" -> "-" ++ wordify m
+    ]
+
+    if number < 1000 [
+        [d m]: divmod number 100
+        return (~{|small\[d]| hundred}) ++ (zero? m)? -> "" -> " and " ++ wordify m
+    ]
+
+    chunks: []
+    n: number
+    while [not? zero? n][
+        [n remainder]: divmod n 1000
+        'chunks ++ remainder
+    ]
+
+    if (size chunks) > size big ->
+        return "integer value too large"
+
+    words: []
+    loop.with:'i chunks 'ch [
+        scale: big\[i]
+        unless zero? ch [
+            chunkStr: wordify ch
+            'words ++ (empty? scale)? -> chunkStr
+                                      -> ~"|chunkStr| |scale|"
+        ]
+    ]
+
+    return join.with:", " reverse words
+]
+
+loop @[
+    0,1,4,5,10,15,18,25,83,140,300,678,1024,
+    45039,123456,91740274651983
+] 'num ->
+    print [pad to :string num 15, join.with: "\n"++ (repeat " " 16) split.lines wordwrap.at: 40 getOrdinal wordify num]
diff --git a/Task/Spiral-matrix/FutureBasic/spiral-matrix.basic b/Task/Spiral-matrix/FutureBasic/spiral-matrix.basic
new file mode 100644
index 0000000000..db594ba86b
--- /dev/null
+++ b/Task/Spiral-matrix/FutureBasic/spiral-matrix.basic
@@ -0,0 +1,41 @@
+void local fn SpiralMatrix( size as int )
+  int t = 0, b = size - 1, l = 0, r = size - 1
+  int value = 0, i, j
+
+  while ( t <= b && l <= r) {
+    for i = l to r
+      mda(t,i) = value++
+    next
+    t++
+
+    for i = t to b
+      mda(i,r) = value++
+    next
+    r--
+
+    if ( t <= b )
+      for i = r to l step -1
+        mda(b,i) = value++
+      next
+      b--
+    end if
+
+    if ( l <= r )
+      for i = b to t step -1
+        mda(i,l) = value++
+      next
+      l++
+    end if
+  wend
+
+  for i = 0 to size -1
+    for j = 0 to size - 1
+      printf @"%2d \b",mda_integer(i,j)
+    next
+    print
+  next
+end fn
+
+fn SpiralMatrix( 5 )
+
+HandleEvents
diff --git a/Task/Square-free-integers/ALGOL-60/square-free-integers.alg b/Task/Square-free-integers/ALGOL-60/square-free-integers.alg
new file mode 100644
index 0000000000..ff8477f7ca
--- /dev/null
+++ b/Task/Square-free-integers/ALGOL-60/square-free-integers.alg
@@ -0,0 +1,60 @@
+begin
+
+comment - return n mod m;
+integer procedure mod(n, m);
+   value n, m; integer n, m;
+begin
+  mod := n - entier(n/m) * m;
+end;
+
+comment - return true if n has no square divisors other than 1;
+boolean procedure sqfree(n);
+  value n; integer n;
+begin
+  integer i, sq;
+  boolean sqf;
+  comment - quick exit for most common square;
+  if mod(n,4) = 0 then sqf := false else sqf := true;
+  i := 3;
+  for sq := i * i while (sq <= n) and sqf do
+    begin
+      if mod(n, sq) = 0 then sqf := false;
+      i := i + 2;
+    end;
+  sqfree := sqf;
+end;
+
+comment - report number of square-free integers up to limit;
+procedure report(limit);
+  value limit; integer limit;
+begin
+  integer i, count;;
+  outstring(1,"Square-free integers up to");
+  outinteger(1,limit);
+  outstring(1,": ");
+  count := 0;
+  for i := 1 step 1 until limit do
+    if sqfree(i) then count := count + 1;
+  outinteger(1,count);
+  outstring(1,"\n");
+end;
+
+integer i, count;
+count := 0;
+outstring(1,"Square free integers up to 145:\n");
+for i := 1 step 1 until 145 do
+  if sqfree(i) then
+    begin
+      outinteger(1,i);
+      count := count + 1;
+      if mod(count, 10) = 0 then outstring(1,"\n");
+    end;
+outinteger(1,count);
+outstring(1," were found\n");
+
+report(100);
+report(1000);
+report(10000);
+report(100000);
+
+end
diff --git a/Task/Square-free-integers/ALGOL-W/square-free-integers.alg b/Task/Square-free-integers/ALGOL-W/square-free-integers.alg
new file mode 100644
index 0000000000..692a734ade
--- /dev/null
+++ b/Task/Square-free-integers/ALGOL-W/square-free-integers.alg
@@ -0,0 +1,117 @@
+begin
+    % count/show some square free numbers                                           %
+    % a number is square free if not divisible by any square and so not divisible   %
+    % by any squared prime                                                          %
+    % to satisfy the task we need to know the primes up to root 1 000 000 000 145   %
+    % and the square free numbers up to 1 000 000                                   %
+    long real oneTrillion;
+    integer   primeMax, sfMax;
+    oneTrillion := 1'6 * 1'6;
+    primeMax    := entier( longsqrt( oneTrillion + 145 ) ) + 1;
+    sfMax       := 1000000;
+    begin
+        logical array prime     ( 1 :: primeMax );
+        logical array squareFree( 1 :: sfMax    );
+
+        % returns true if n is square free, false otherwise                         %
+        %         n is long real to allow for values up to 2^53                     %
+        %         the values of n must be non-negative integers <= 2^53             %
+        logical procedure isSquareFree ( long real value n ) ;
+                if n <= sfMax then squareFree( entier( n ) )
+                else begin % n is larger than the sieve - use trial division        %
+                    integer maxFactor, f;
+                    logical isSF;
+                    maxFactor := entier( longsqrt( n ) ) + 1;
+                    isSF      := true;
+                    f         := 1;
+                    while begin f := f + 1;
+                                f <= maxFactor and isSF
+                          end
+                    do    begin
+                              if prime( f ) then begin
+                                  long real nOverFF, n10, p10;
+                                  nOverFF := n / ( f * f );
+                                  % as we are using long real to handle integers    %
+                                  % larger than 2^32, we can't use rem              %
+                                  % instead we subtract powers of ten from nOverFF  %
+                                  % until nOverFF is < 1, if it is 0 then f * f     %
+                                  % exactly divides n...                            %
+                                  p10 :=  1;
+                                  n10 := 10;
+                                  while n10 < nOverFF do begin
+                                      p10 := n10;
+                                      n10 := n10 * 10
+                                  end while_n10_lt_nOverFF ;
+                                  while p10 >= 1 do begin
+                                      while nOverFF >= p10 do nOverFF := nOverFF - p10;
+                                      p10 := p10 / 10
+                                  end while_p10_ge_1 ;
+                                  isSF    := nOverFF not = 0
+                              end if_isPrime__f
+                    end while_isSf ;
+                    isSF
+                end isSquareFree ;
+        % returns the count of squareFree numbers between m and n (inclusive)      %
+        integer procedure countSquareFree ( integer value m, n ) ;
+                begin
+                    integer count;
+                    count := 0;
+                    for i := m until n do if squareFree( i ) then count := count + 1;
+                    count
+                end countSquareFree ;
+
+        % sieve the primes                                                          %
+        for i := 1 until primeMax do prime( i ) := true;
+        for i := 1 until sfMax    do squareFree( i ) := true;
+        for s := 2 until entier( sqrt( primeMax ) ) do begin
+            if prime( s ) then begin
+                for p := s * s step s until primeMax do prime( p ) := false
+            end if_prime__s
+        end for_s ;
+        % sieve the square free integers                                            %
+        for s := 2 until entier( sqrt( sfMax ) ) do begin
+            if prime( s ) then begin
+                integer q;
+                q := s * s;
+                for p := q step q until sfMax do squareFree( p ) := false
+            end if_prime__s
+        end for_s ;
+
+        begin % task requirements                                                   %
+            integer count, sf100, sf1000, sf10000, sf100000, sf1000000;
+            % show square free numbers from 1 -> 145                                %
+            write( "Square free numbers from 1 to 145:" );write();
+            count := 0;
+            for i := 1 until 145 do begin
+                if isSquareFree( i ) then begin
+                    writeon( i_w := 4, s_w := 0, i );
+                    count := count + 1;
+                    if count rem 20 = 0 then write()
+                end if_isSquareFree__i
+            end for_i ;
+            write();
+            % show square free numbers from 1 trillion -> one trillion + 145        %
+            write( "Square free numbers from 1 000 000 000 000 to 1 000 000 000 145:" );write();
+            count := 0;
+            for i := 0 until 145 do begin
+                if isSquareFree( oneTrillion + i ) then begin
+                    writeon( r_format := "A", r_w := 14, r_d := 0, oneTrillion + i );
+                    count := count + 1;
+                    if count rem 5 = 0 then write()
+                end if_isSquareFree__oneTrillion_plus_i
+            end for_i ;
+            write();
+            % show counts of square free numbers                                    %
+            sf100     :=            countSquareFree(      1,     100 );
+            sf1000    := sf100    + countSquareFree(    101,    1000 );
+            sf10000   := sf1000   + countSquareFree(   1001,   10000 );
+            sf100000  := sf10000  + countSquareFree(  10001,  100000 );
+            sf1000000 := sf100000 + countSquareFree( 100001, 1000000 );
+            write( i_w := 6, s_w := 0, "square free numbers between 1 and     100: ", sf100     );
+            write( i_w := 6, s_w := 0, "square free numbers between 1 and    1000: ", sf1000    );
+            write( i_w := 6, s_w := 0, "square free numbers between 1 and   10000: ", sf10000   );
+            write( i_w := 6, s_w := 0, "square free numbers between 1 and  100000: ", sf100000  );
+            write( i_w := 6, s_w := 0, "square free numbers between 1 and 1000000: ", sf1000000 )
+        end
+    end
+end.
diff --git a/Task/Square-free-integers/EasyLang/square-free-integers.easy b/Task/Square-free-integers/EasyLang/square-free-integers.easy
new file mode 100644
index 0000000000..72647835ea
--- /dev/null
+++ b/Task/Square-free-integers/EasyLang/square-free-integers.easy
@@ -0,0 +1,27 @@
+fastfunc square_free n .
+   root = 2
+   while root <= sqrt n
+      if n mod (root * root) = 0 : return 0
+      root += 1
+   .
+   return 1
+.
+proc run lo hi show . .
+   print "From " & lo & " to " & hi & ":"
+   for i = lo to hi
+      if square_free i = 1
+         cnt += 1
+         if show = 1 : write i & " "
+      .
+   .
+   if show = 0 : write cnt & " numbers"
+   print ""
+   print ""
+.
+run 1 145 1
+run 1000000000000 1000000000145 1
+run 1 100 0
+run 1 1000 0
+run 1 10000 0
+run 1 100000 0
+run 1 1000000 0
diff --git a/Task/Square-free-integers/Forth/square-free-integers.fth b/Task/Square-free-integers/Forth/square-free-integers.fth
index dc42a00c9c..4c52193f05 100644
--- a/Task/Square-free-integers/Forth/square-free-integers.fth
+++ b/Task/Square-free-integers/Forth/square-free-integers.fth
@@ -4,17 +4,12 @@
   begin
     2dup dup * >=
   while
-    0 >r
-    begin
-      2dup mod 0=
-    while
-      r> 1+ dup 1 > if
-        2drop drop false exit
-      then
-      >r
+    2dup mod 0= if
       tuck / swap
-    repeat
-    rdrop
+      2dup mod 0= if
+        2drop false exit
+      then
+    then
     2 +
   repeat
   2drop true ;
diff --git a/Task/Square-free-integers/PL-I-80/square-free-integers.pli b/Task/Square-free-integers/PL-I-80/square-free-integers.pli
new file mode 100644
index 0000000000..d58642d4b3
--- /dev/null
+++ b/Task/Square-free-integers/PL-I-80/square-free-integers.pli
@@ -0,0 +1,53 @@
+SquareFreeDemo: proc options (main);
+
+    %replace
+       false by '0'b,
+       true by '1'b;
+
+    dcl (i, found) fixed bin;
+
+    put skip list ('Square-free integers from 1 to 145');
+    put skip;
+    found = 0;
+    do i = 1 to 145;
+        if (square_free(i)) then
+            do;
+                put edit (i) (f(4));
+                found = found + 1;
+		if (mod(found, 16) = 0) then put skip;
+            end;
+    end;
+    put skip edit (found, ' were found') (f(3), a);
+
+    call report_number_found(100);
+    call report_number_found(1000);
+    call report_number_found(10000);
+
+    stop;
+
+/* report number of square-free integers from 1 to limit */
+report_number_found: proc(limit);
+   dcl (limit, i, found);
+   put skip edit ('Number of square-free integers from 1 to',
+      limit, ':') (a, f(6), a);
+   found = 0;
+   do i = 1 to limit;
+      if (square_free(i)) then found = found + 1;
+   end;
+   put edit (found) (f(5));
+end report_number_found;
+
+/* return true if n has no square divisors other than 1 */
+square_free: proc (n) returns (bit(1));
+    dcl (n, i, sq) fixed bin;
+    i = 2;
+    sq = i * i;
+    do while (sq <= n);
+	if (mod(n, sq) = 0) then return (false);
+        i = i + 1;
+        sq = i * i;
+    end;
+    return (true);
+end square_free;
+
+end SquareFreeDemo;
diff --git a/Task/Square-free-integers/Quackery/square-free-integers.quackery b/Task/Square-free-integers/Quackery/square-free-integers.quackery
new file mode 100644
index 0000000000..b083b1c081
--- /dev/null
+++ b/Task/Square-free-integers/Quackery/square-free-integers.quackery
@@ -0,0 +1,38 @@
+  [ stack ]                      is primesquares (   --> s )
+
+  []
+  1000000000145 sqrt
+  dup eratosthenes
+  times
+    [ i^ isprime if
+      [ i^ dup * join ] ]
+  primesquares put
+
+  [ true swap
+    primesquares share witheach
+      [ 2dup < iff
+          [ drop conclude ]
+          done
+        dip dup mod 0 = if
+          [ dip not conclude ] ]
+    drop ]                       is squarefree   ( n --> b )
+
+  say "square-free numbers from 1 to 145"
+  [] 145 times
+    [ i^ 1+ squarefree if
+        [ i^ 1+ number$ nested join ] ]
+  80 wrap$
+  cr cr
+  say "square-free numbers from 1000000000000 to 1000000000145"
+  [] 146 times
+  [ i^ 1000000000000 + squarefree if
+      [ i^ 1000000000000 + number$ nested join ] ]
+  80 wrap$
+  cr cr
+  ' [ 100 1000 10000 100000 1000000 ]
+  witheach
+    [  say "square-free numbers from 1 to "
+       dup echo say ": "
+      0 swap times
+        [ i^ 1+ squarefree + ]
+      echo cr ]
diff --git a/Task/Square-free-integers/S-BASIC/square-free-integers.basic b/Task/Square-free-integers/S-BASIC/square-free-integers.basic
new file mode 100644
index 0000000000..fdf66e8206
--- /dev/null
+++ b/Task/Square-free-integers/S-BASIC/square-free-integers.basic
@@ -0,0 +1,54 @@
+$lines
+
+$constant true = 0FFFFH
+$constant false = 0
+
+rem - return true if n is square-free
+function SquareFree(n = integer) = integer
+   var i, count, result = integer
+   i = 2
+   result = true
+   rem - decompose n into its prime factors
+   while (i*i) <= n and result <> false do
+      begin
+         count = 0
+         while n - (n / i) * i = 0 do
+            begin
+               count = count + 1
+               n = n / i
+            end
+         rem - not square-free if a divisor was repeated
+         if count > 1 then result = false
+         i = i + 1
+      end
+end = result
+
+rem - demonstrate the function
+
+var i, found = integer
+
+print "Showing square-free numbers between 1 and 145"
+for i = 1 to 145
+  if SquareFree(i) then print using "### ";i;
+next i
+print
+
+found = 0
+for i = 1 to 100
+  if SquareFree(i) then found = found + 1
+next i
+print "Square-free numbers between 1 and 100 ="; found
+
+found = 0
+for i = 1 to 1000
+  if SquareFree(i) then found = found + 1
+next i
+print "Square-free numbers between 1 and 1,000 ="; found
+
+found = 0
+for i = 1 to 10000
+  if SquareFree(i) then found = found + 1
+next i
+print "Square-free numbers between 1 and 10,000 ="; found
+
+end
diff --git a/Task/Square-free-integers/SETL/square-free-integers.setl b/Task/Square-free-integers/SETL/square-free-integers.setl
new file mode 100644
index 0000000000..ef1231063e
--- /dev/null
+++ b/Task/Square-free-integers/SETL/square-free-integers.setl
@@ -0,0 +1,45 @@
+program square_free_integers;
+    show_square_frees([1..145]);
+    show_square_frees([1000000000000..1000000000145]);
+    count_square_frees();
+
+    proc count_square_frees();
+        loop init
+            limit := 100;
+            count := 0;
+            n := 1;
+        while limit <= 1000000 do
+            if n = limit then
+                print(str count + " square free numbers <= " + str limit);
+                limit *:= 10;
+            end if;
+            if square_free(n) then
+                count +:= 1;
+            end if;
+            n +:= 1;
+        end loop;
+    end proc;
+
+    proc show_square_frees(nums);
+        loop for n in nums do
+            if square_free(n) then
+                nprint(lpad(str n, 15));
+                if (col +:= 1) mod 5 = 0 then
+                    print;
+                end if;
+            end if;
+        end loop;
+        print;
+    end proc;
+
+    proc square_free(n);
+        loop init r := 2;
+        while r*r <= n do
+            if n mod (r*r) = 0 then
+                return False;
+            end if;
+            r +:= 1;
+        end loop;
+        return True;
+    end proc;
+end program;
diff --git a/Task/Square-free-integers/XPL0/square-free-integers.xpl0 b/Task/Square-free-integers/XPL0/square-free-integers.xpl0
new file mode 100644
index 0000000000..9f0aee1391
--- /dev/null
+++ b/Task/Square-free-integers/XPL0/square-free-integers.xpl0
@@ -0,0 +1,47 @@
+func SqFree(N);                 \Return 'true' if N is square-free
+real N, D2;
+int  D;
+[for D:= 2 to 1000 do           \sqrt one million
+    [D2:= float(D*D);
+    if fix(Mod(N, D2)) = 0 then return false;
+    if D > 2 then D:= D+1;      \(doubles speed to 19.5 sec)
+    ];
+return true;
+];
+
+int  Num, Count, Limit;
+real T;
+[Format(3, 0);
+Count:= 0;
+for Num:= 1 to 145 do
+    [if SqFree(float(Num)) then
+        [Count:= Count+1;
+        RlOut(0, float(Num));
+        if rem(Count/20) then ChOut(0, ^ ) else CrLf(0);
+        ];
+    ];
+CrLf(0);  CrLf(0);
+
+Count:= 0;
+for Num:= 0 to 145 do
+    [T:= float(Num) + 1e12;
+    if SqFree(T) then
+        [RlOut(0, T);
+        Count:= Count+1;
+        if rem(Count/5) then ChOut(0, ^ ) else CrLf(0);
+        ];
+    ];
+CrLf(0);  CrLf(0);
+
+Limit:= 100;
+loop    [Count:= 0;
+        for Num:= 1 to Limit do
+            [T:= float(Num);
+            if SqFree(T) then Count:= Count+1;
+            ];
+        Text(0, "Square-free integers up to ");  IntOut(0, Limit);
+        Text(0, ": ");  IntOut(0, Count);  CrLf(0);
+        if Limit = 1_000_000 then quit;
+        Limit:= Limit * 10;
+        ];
+]
diff --git a/Task/Stem-and-leaf-plot/Crystal/stem-and-leaf-plot.cr b/Task/Stem-and-leaf-plot/Crystal/stem-and-leaf-plot.cr
new file mode 100644
index 0000000000..07d6e34c9e
--- /dev/null
+++ b/Task/Stem-and-leaf-plot/Crystal/stem-and-leaf-plot.cr
@@ -0,0 +1,20 @@
+data = [12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124,
+        37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104,
+        123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44,
+        105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113,
+        121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13,
+        27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52,
+        71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47,
+        105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48,
+        125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146]
+
+hist = Hash(Int32, Array(Int32)).new
+
+data.each do |n|
+  stem = n // 10
+  hist[stem] = (hist[stem]? || [] of Int32) << n % 10
+end
+
+Range.new(*hist.keys.minmax).each do |stem|
+  printf "%4d|%s\n", stem, (hist[stem]? || [] of Int32).sort.map(&.to_s).join
+end
diff --git a/Task/Stirling-numbers-of-the-first-kind/Forth/stirling-numbers-of-the-first-kind.fth b/Task/Stirling-numbers-of-the-first-kind/Forth/stirling-numbers-of-the-first-kind.fth
new file mode 100644
index 0000000000..59e9154b80
--- /dev/null
+++ b/Task/Stirling-numbers-of-the-first-kind/Forth/stirling-numbers-of-the-first-kind.fth
@@ -0,0 +1,25 @@
+: s1 ( n k -- u )
+  dup 0= if
+    drop 0> if 0 else 1 then exit
+  then
+  2dup < if 2drop 0 exit then
+  swap 1- swap
+  2dup 1- recurse >r
+  over swap recurse
+  * r> + ;
+
+: main ( -- )
+  ." Unsigned Stirling numbers of the first kind:" cr
+  ." n/k"
+  13 1 do
+    i 10 .r
+  loop cr
+  13 1 do
+    i 3 .r
+    i 1+ 1 do
+      j i s1 10 .r
+    loop cr
+  loop ;
+
+main
+bye
diff --git a/Task/Stirling-numbers-of-the-second-kind/Forth/stirling-numbers-of-the-second-kind.fth b/Task/Stirling-numbers-of-the-second-kind/Forth/stirling-numbers-of-the-second-kind.fth
new file mode 100644
index 0000000000..f5526fccd0
--- /dev/null
+++ b/Task/Stirling-numbers-of-the-second-kind/Forth/stirling-numbers-of-the-second-kind.fth
@@ -0,0 +1,23 @@
+: s2 ( n k -- u )
+  dup 0= if 2drop 0 exit then
+  over 0= if 2drop 0 exit then
+  2dup = if 2drop 1 exit then
+  swap 1- swap
+  2dup 1- recurse >r
+  tuck recurse * r> + ;
+
+: main ( -- )
+  ." Stirling numbers of the second kind:" cr
+  ." n/k"
+  13 1 do
+    i 8 .r
+  loop cr
+  13 1 do
+    i 3 .r
+    i 1+ 1 do
+      j i s2 8 .r
+    loop cr
+  loop ;
+
+main
+bye
diff --git a/Task/String-append/Retro/string-append.retro b/Task/String-append/Retro/string-append.retro
new file mode 100644
index 0000000000..1aadba0845
--- /dev/null
+++ b/Task/String-append/Retro/string-append.retro
@@ -0,0 +1,3 @@
+'Hello  '_World
+s:append s:put nl
+Hello World
diff --git a/Task/String-case/Zig/string-case.zig b/Task/String-case/Zig/string-case.zig
index 1110070e42..85c281716e 100644
--- a/Task/String-case/Zig/string-case.zig
+++ b/Task/String-case/Zig/string-case.zig
@@ -5,9 +5,9 @@ pub fn main() !void {
     const string = "alphaBETA";
     var lower: [string.len]u8 = undefined;
     var upper: [string.len]u8 = undefined;
-    for (string) |char, i| {
-        lower[i] = std.ascii.toLower(char);
-        upper[i] = std.ascii.toUpper(char);
+    for (string, &lower, &upper) |char, *lo, *up| {
+        lo.* = std.ascii.toLower(char);
+        up.* = std.ascii.toUpper(char);
     }
     try stdout_wr.print("lower: {s}\n", .{lower});
     try stdout_wr.print("upper: {s}\n", .{upper});
diff --git a/Task/String-interpolation-included-/S-BASIC/string-interpolation-included-.basic b/Task/String-interpolation-included-/S-BASIC/string-interpolation-included-.basic
new file mode 100644
index 0000000000..958f7e486b
--- /dev/null
+++ b/Task/String-interpolation-included-/S-BASIC/string-interpolation-included-.basic
@@ -0,0 +1,4 @@
+var template = string
+template = "Mary had a & lamb."
+print using template; "little"
+end
diff --git a/Task/Strip-block-comments/FutureBasic/strip-block-comments.basic b/Task/Strip-block-comments/FutureBasic/strip-block-comments.basic
new file mode 100644
index 0000000000..142075ef51
--- /dev/null
+++ b/Task/Strip-block-comments/FutureBasic/strip-block-comments.basic
@@ -0,0 +1,39 @@
+include "NSLog.incl"
+
+local fn StripBlockComments( string as CFStringRef, openStr as CFStringRef, closeStr as CFStringRef ) as CFStringRef
+  if ( len( openStr ) == 0 || len( closeStr ) == 0 ) then return string
+
+  CFMutableStringRef ret = fn MutableStringWithString( string )
+  CFRange range
+  while ( YES )
+    range = fn StringRangeOfString( ret, openStr )
+    if ( range.location == NSNotFound ) then exit while
+    CFRange endRange = fn StringRangeOfStringWithOptionsInRange( ret, closeStr, NULL, fn CFRangeMake( range.location + range.length, len(ret) - (range.location + range.length ) ) )
+    if ( endRange.location == NSNotFound )
+      break
+    end if
+    CFRange fullRange = fn CFRangeMake( range.location, endRange.location + endRange.length - range.location )
+    MutableStringDeleteCharacters( ret, fullRange )
+  wend
+end fn = ret
+
+CFStringRef test = @"/**\n¬
+* Some comments\n¬
+* longer comments here that we can parse.\n¬
+*\n¬
+* Rahoo \n¬
+*/\n¬
+local fn Subroutine( b as int, c as int ) as int\n¬
+  int a = /* inline comment */ b + c \n¬
+end fn = a\n¬
+/*/ <-- tricky comments */\n¬
+\n¬
+/**\n¬
+* Another comment.\n¬
+*/\n¬
+local fn DoSomething\n¬
+end fn\n¬
+  "
+NSLog( @"%@", fn StripBlockComments( test, @"/*", @"*/" ) )
+
+HandleEvents
diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/FutureBasic/strip-control-codes-and-extended-characters-from-a-string.basic b/Task/Strip-control-codes-and-extended-characters-from-a-string/FutureBasic/strip-control-codes-and-extended-characters-from-a-string.basic
new file mode 100644
index 0000000000..7d7a8e7859
--- /dev/null
+++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/FutureBasic/strip-control-codes-and-extended-characters-from-a-string.basic
@@ -0,0 +1,47 @@
+include "NSLog.incl"
+
+local fn StringStripControlCodes( string as CFStringRef ) as CFStringRef
+  CFMutableCharacterSetRef set = fn MutableCharacterSetNew
+  MutableCharacterSetAddCharactersInRange( set, fn CFRangeMake( 0, 32 ) )
+  MutableCharacterSetAddCharactersInRange( set, fn CFRangeMake( 127, 1 ) )
+end fn = fn ArrayComponentsJoinedByString( fn StringComponentsSeparatedByCharactersInSet( string, set ), @"" )
+
+local fn StringStripExtendedCharacters( string as CFStringRef ) as CFStringRef
+  CFCharacterSetRef set = fn CharacterSetWithRange( fn CFRangeMake( 128, 128 ) )
+end fn = fn ArrayComponentsJoinedByString( fn StringComponentsSeparatedByCharactersInSet( string, set ), @"" )
+
+void local fn DoIt
+  CFStringRef s1 = @"Welcome "
+  CFStringRef s2 = @"to "
+  CFStringRef s3 = @"FutureBasic"
+
+  CFMutableStringRef string = fn MutableStringWithString( s1 )
+
+  int i
+  for i = 0 to 31
+    MutableStringAppendString( string, ucs(i) )
+  next
+
+  MutableStringAppendString( string, ucs(127) )
+  MutableStringAppendString( string, s2 )
+  for i = 128 to 255
+    MutableStringAppendString( string, ucs(i) )
+  next
+  MutableStringAppendString( string, s3 )
+
+  NSLog(@"-- String --\n%@",string)
+
+  CFStringRef string1 = fn StringStripControlCodes( string )
+  NSLog(@"\n\n-- Control codes stripped --\n%@",string1)
+
+  CFStringRef string2 = fn StringStripExtendedCharacters( string )
+  NSLog(@"\n\n-- Extended characters stripped --\n%@",string2)
+
+  CFStringRef string3 = fn StringStripControlCodes( string )
+  string3 = fn StringStripExtendedCharacters( string3 )
+  NSLog(@"\n\n-- Control codes and extended characters stripped --\n%@",string3)
+end fn
+
+fn DoIt
+
+HandleEvents
diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Langur/strip-control-codes-and-extended-characters-from-a-string.langur b/Task/Strip-control-codes-and-extended-characters-from-a-string/Langur/strip-control-codes-and-extended-characters-from-a-string.langur
index 51299ba2b1..4e27dccc91 100644
--- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Langur/strip-control-codes-and-extended-characters-from-a-string.langur
+++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Langur/strip-control-codes-and-extended-characters-from-a-string.langur
@@ -1,5 +1,5 @@
 val str = "()\x15abcd\uFFFF123\uBBBB!@#$%^&*\x01"
 
 writeln "original          : ", str
-writeln "without ctrl chars: ", replace(str, RE/\p{Cc}/, "")
-writeln "print ASCII only  : ", replace(str, re/[^ -~]/, "")
+writeln "without ctrl chars: ", replace(str, by=RE/\p{Cc}/)
+writeln "print ASCII only  : ", replace(str, by=re/[^ -~]/)
diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Fortran/strip-whitespace-from-a-string-top-and-tail.f b/Task/Strip-whitespace-from-a-string-Top-and-tail/Fortran/strip-whitespace-from-a-string-top-and-tail.f
new file mode 100644
index 0000000000..05aa9e6a36
--- /dev/null
+++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Fortran/strip-whitespace-from-a-string-top-and-tail.f
@@ -0,0 +1,28 @@
+! Tested with GNU Fortran (GCC) 14.2.0
+! Standard: Fortran 90+
+
+program strip_demo
+    implicit none
+    character(21) :: str = "     Jabberwocky     "
+
+    ! Show original string with delimiters
+    write(*, '(A)') "Original:      '" // str // "'"
+
+    ! Remove leading spaces (using adjustl)
+    write(*, '(A)') "Remove left:   '" // adjustl(str) // "'"
+
+    ! Remove trailing spaces (using trim)
+    write(*, '(A)') "Remove right:  '" // trim(str) // "'"
+
+    ! Remove both (using trim and adjustl)
+    write(*, '(A)') "Remove both:   '" // trim(adjustl(str)) // "'"
+end program strip_demo
+
+
+Output:
+
+Original:      '     Jabberwocky     '
+Remove left:   'Jabberwocky          '
+Remove right:  '     Jabberwocky'
+Remove both:   'Jabberwocky'
+
diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET/strip-whitespace-from-a-string-top-and-tail.pas b/Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET/strip-whitespace-from-a-string-top-and-tail.pas index 50398e4465..d41dba0f0c 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET/strip-whitespace-from-a-string-top-and-tail.pas +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PascalABC.NET/strip-whitespace-from-a-string-top-and-tail.pas @@ -1,6 +1,6 @@ begin - var s := #9' abc '#9; - Writeln(s.TrimStart,'|'); - Writeln(s.TrimEnd,'|'); - Writeln(s.Trim,'|'); + var s := #9' abc '#9; // #9 = TAB + Writeln('|', s.TrimStart,'|'); + Writeln('|', s.TrimEnd,'|'); + Writeln('|', s.Trim,'|'); end. diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail-1.basic b/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail-1.basic new file mode 100644 index 0000000000..03c3cba201 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail-1.basic @@ -0,0 +1,3 @@ + Debug "|" + LTrim(" Top ") + "|" + Debug "|" + RTrim(" Tail ") + "|" + Debug "|" + Trim(" Both ") + "|" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail.basic b/Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail-2.basic similarity index 100% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail.basic rename to Task/Strip-whitespace-from-a-string-Top-and-tail/PureBasic/strip-whitespace-from-a-string-top-and-tail-2.basic diff --git a/Task/Sudan-function/Crystal/sudan-function.cr b/Task/Sudan-function/Crystal/sudan-function.cr new file mode 100644 index 0000000000..439aaa56e5 --- /dev/null +++ b/Task/Sudan-function/Crystal/sudan-function.cr @@ -0,0 +1,14 @@ +def sudan (n, x : UInt64, y : UInt64) + if n == 0 + x + y + elsif y == 0 + x + else + s = sudan(n, x, y-1) + sudan(n-1, s, s + y) + end +end + +[{0, 0, 0}, {1, 1, 1}, {2, 1, 1}, {2, 2, 1}, {2, 2, 2}, {3, 1, 1}].each do |n, x, y| + puts "sudan #{n} (#{x}, #{y}) = #{sudan(n, x.to_u64, y.to_u64)}" +end diff --git a/Task/Sudan-function/EMal/sudan-function.emal b/Task/Sudan-function/EMal/sudan-function.emal new file mode 100644 index 0000000000..22b7195ccd --- /dev/null +++ b/Task/Sudan-function/EMal/sudan-function.emal @@ -0,0 +1,12 @@ +fun F ← int by int n, int x, int y + if n æ 0 + return x + y + else if y æ 0 + return x + end + return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y) +end +writeLine("F(1, 3, 3) ← ", F(1, 3, 3)) +writeLine("F(2, 1, 1) ← ", F(2, 1, 1)) +writeLine("F(3, 1, 1) ← ", F(3, 1, 1)) +writeLine("F(2, 2, 1) ← ", F(2, 2, 1)) diff --git a/Task/Sudoku/Python/sudoku-2.py b/Task/Sudoku/Python/sudoku-2.py index 6687c9d173..61d34ca0d3 100644 --- a/Task/Sudoku/Python/sudoku-2.py +++ b/Task/Sudoku/Python/sudoku-2.py @@ -1,56 +1,86 @@ -sudoku = [ - # cell value # cell number - 0, 0, 4, 0, 5, 0, 0, 0, 0, # 0, 1, 2, 3, 4, 5, 6, 7, 8, - 9, 0, 0, 7, 3, 4, 6, 0, 0, # 9, 10, 11, 12, 13, 14, 15, 16, 17, - 0, 0, 3, 0, 2, 1, 0, 4, 9, # 18, 19, 20, 21, 22, 23, 24, 25, 26, - 0, 3, 5, 0, 9, 0, 4, 8, 0, # 27, 28, 29, 30, 31, 32, 33, 34, 35, - 0, 9, 0, 0, 0, 0, 0, 3, 0, # 36, 37, 38, 39, 40, 41, 42, 43, 44, - 0, 7, 6, 0, 1, 0, 9, 2, 0, # 45, 46, 47, 48, 49, 50, 51, 52, 53, - 3, 1, 0, 9, 7, 0, 2, 0, 0, # 54, 55, 56, 57, 58, 59, 60, 61, 62, - 0, 0, 9, 1, 8, 2, 0, 0, 3, # 63, 64, 65, 66, 67, 68, 69, 70, 71, - 0, 0, 0, 0, 6, 0, 1, 0, 0, # 72, 73, 74, 75, 76, 77, 78, 79, 80 - # zero = empty. -] +# Sudoku Solver +# Recursive backtracking algorithm +# Usage: python3 sudoku.py [puzzle.txt] -numbers = {1,2,3,4,5,6,7,8,9} +import sys -def options(cell,sudoku): - """ determines the degree of freedom for a cell. """ - column = {v for ix, v in enumerate(sudoku) if ix % 9 == cell % 9} - row = {v for ix, v in enumerate(sudoku) if ix // 9 == cell // 9} - box = {v for ix, v in enumerate(sudoku) if (ix // (9 * 3) == cell // (9 * 3)) and ((ix % 9) // 3 == (cell % 9) // 3)} - return numbers - (box | row | column) +grid0 = [[0,0,8,0,0,0,0,1,6], # Data type for sudoku puzzles: + [5,0,0,0,9,2,0,0,8], # a list of 9 lists, each of 9 digits. + [0,0,0,1,0,0,0,0,0], + [9,0,0,3,0,0,8,2,0], # grid0 is a global variable used by readFile() + [0,2,0,0,0,0,0,7,0], + [0,8,4,0,0,6,0,0,5], # This sudoku is solved when there is no + [0,0,0,0,0,3,0,0,0], # filename argument on the command line. + [4,0,0,9,6,0,0,0,2], + [1,6,0,0,0,0,7,0,0]] -initial_state = sudoku[:] # the sudoku is our initial state. +def readFile(): + '''Parses a textfile containing a sudoku puzzle; + returns this puzzle as 'grid', a list of 9 lists of 9 digits. + Returns grid0 if no filename is given on the command line. + ''' + if len(sys.argv) == 1: # No command line argument + return grid0 + else: + name = sys.argv[1] # A filename or path/filename of a sudoku textfile + file = open(name) + grid = [] + while True: + txt = file.readline() + if txt == "": break + row = [] + for ch in txt: # In the sudoku textfile: + if ch == "#": break # a '#' can be used for comments, + if ch == ".": row.append(0) # '.' or '0' stand for empty cells + if ch == "_": row.append(0) # '_' or '-' + if ch == "-": row.append(0) # could also be used for this. + if ch.isdigit(): row.append(int(ch)) + if row != []: # all lines without digits or empty cell characters give [] + if len(row) != 9: + print("Sudoku file configuration error: not 9 columns"); + file.close; exit() # Halt the program + grid.append(row) + file.close() + if len(grid) != 9: + print("Sudoku file configuration error: not 9 rows"); exit() + else: + return grid -job_queue = [initial_state] # we need the jobqueue in case of ambiguity of choice. +def printGrid (grid): + for i in range(0, 9): + if i > 0 and i % 3 == 0: + print("------+-------+------", end="") + print() + for j in range(0, 9): + if j > 0 and j % 3 == 0: print("| ", end="") + n = grid[i][j] + c = "." if n == 0 else str(n) + print(c, end=" ") + print() -while job_queue: - state = job_queue.pop(0) - if not any(i==0 for i in state): # no missing values means that the sudoku is solved. - break +def valid (row, col, n): + res = True + for i in range(0, 9): + for j in range(0, 9): + if ( i == row or j == col or + i // 3 == row // 3 and j // 3 == col // 3 ): # square + if grid[i][j] == n: res = False + return res - # determine the degrees of freedom for each cell. - degrees_of_freedom = [0 if v!=0 else len(options(ix,state)) for ix,v in enumerate(state)] - # find cell with least freedom. - least_freedom = min(v for v in degrees_of_freedom if v > 0) - cell = degrees_of_freedom.index(least_freedom) +def solve(): + for row in range(0, 9): + for col in range(0, 9): + if grid[row][col] == 0: + for n in (range(1, 10)): + if valid(row, col, n): + grid[row][col] = n + solve() # recursive call + grid[row][col] = 0 # backtracking step + return + printGrid(grid) # The solved sudoku + input("\nPress enter to check for more solutions\n") - for option in options(cell, state): # for each option we add the new state to the queue. - new_state = state[:] - new_state[cell] = option - job_queue.append(new_state) - -# finally - print out the solution -for i in range(9): - print(state[i*9:i*9+9]) - -# [2, 6, 4, 8, 5, 9, 3, 1, 7] -# [9, 8, 1, 7, 3, 4, 6, 5, 2] -# [7, 5, 3, 6, 2, 1, 8, 4, 9] -# [1, 3, 5, 2, 9, 7, 4, 8, 6] -# [8, 9, 2, 5, 4, 6, 7, 3, 1] -# [4, 7, 6, 3, 1, 8, 9, 2, 5] -# [3, 1, 8, 9, 7, 5, 2, 6, 4] -# [6, 4, 9, 1, 8, 2, 5, 7, 3] -# [5, 2, 7, 4, 6, 3, 1, 9, 8] +grid = readFile() # valid() and solve() use this global variable +printGrid(grid) # The unsolved sudoku +print() +solve() diff --git a/Task/Sudoku/Python/sudoku-3.py b/Task/Sudoku/Python/sudoku-3.py new file mode 100644 index 0000000000..6687c9d173 --- /dev/null +++ b/Task/Sudoku/Python/sudoku-3.py @@ -0,0 +1,56 @@ +sudoku = [ + # cell value # cell number + 0, 0, 4, 0, 5, 0, 0, 0, 0, # 0, 1, 2, 3, 4, 5, 6, 7, 8, + 9, 0, 0, 7, 3, 4, 6, 0, 0, # 9, 10, 11, 12, 13, 14, 15, 16, 17, + 0, 0, 3, 0, 2, 1, 0, 4, 9, # 18, 19, 20, 21, 22, 23, 24, 25, 26, + 0, 3, 5, 0, 9, 0, 4, 8, 0, # 27, 28, 29, 30, 31, 32, 33, 34, 35, + 0, 9, 0, 0, 0, 0, 0, 3, 0, # 36, 37, 38, 39, 40, 41, 42, 43, 44, + 0, 7, 6, 0, 1, 0, 9, 2, 0, # 45, 46, 47, 48, 49, 50, 51, 52, 53, + 3, 1, 0, 9, 7, 0, 2, 0, 0, # 54, 55, 56, 57, 58, 59, 60, 61, 62, + 0, 0, 9, 1, 8, 2, 0, 0, 3, # 63, 64, 65, 66, 67, 68, 69, 70, 71, + 0, 0, 0, 0, 6, 0, 1, 0, 0, # 72, 73, 74, 75, 76, 77, 78, 79, 80 + # zero = empty. +] + +numbers = {1,2,3,4,5,6,7,8,9} + +def options(cell,sudoku): + """ determines the degree of freedom for a cell. """ + column = {v for ix, v in enumerate(sudoku) if ix % 9 == cell % 9} + row = {v for ix, v in enumerate(sudoku) if ix // 9 == cell // 9} + box = {v for ix, v in enumerate(sudoku) if (ix // (9 * 3) == cell // (9 * 3)) and ((ix % 9) // 3 == (cell % 9) // 3)} + return numbers - (box | row | column) + +initial_state = sudoku[:] # the sudoku is our initial state. + +job_queue = [initial_state] # we need the jobqueue in case of ambiguity of choice. + +while job_queue: + state = job_queue.pop(0) + if not any(i==0 for i in state): # no missing values means that the sudoku is solved. + break + + # determine the degrees of freedom for each cell. + degrees_of_freedom = [0 if v!=0 else len(options(ix,state)) for ix,v in enumerate(state)] + # find cell with least freedom. + least_freedom = min(v for v in degrees_of_freedom if v > 0) + cell = degrees_of_freedom.index(least_freedom) + + for option in options(cell, state): # for each option we add the new state to the queue. + new_state = state[:] + new_state[cell] = option + job_queue.append(new_state) + +# finally - print out the solution +for i in range(9): + print(state[i*9:i*9+9]) + +# [2, 6, 4, 8, 5, 9, 3, 1, 7] +# [9, 8, 1, 7, 3, 4, 6, 5, 2] +# [7, 5, 3, 6, 2, 1, 8, 4, 9] +# [1, 3, 5, 2, 9, 7, 4, 8, 6] +# [8, 9, 2, 5, 4, 6, 7, 3, 1] +# [4, 7, 6, 3, 1, 8, 9, 2, 5] +# [3, 1, 8, 9, 7, 5, 2, 6, 4] +# [6, 4, 9, 1, 8, 2, 5, 7, 3] +# [5, 2, 7, 4, 6, 3, 1, 9, 8] diff --git a/Task/Sum-and-product-of-an-array/Langur/sum-and-product-of-an-array.langur b/Task/Sum-and-product-of-an-array/Langur/sum-and-product-of-an-array.langur index 3d2548363d..2b938f77a6 100644 --- a/Task/Sum-and-product-of-an-array/Langur/sum-and-product-of-an-array.langur +++ b/Task/Sum-and-product-of-an-array/Langur/sum-and-product-of-an-array.langur @@ -1,4 +1,4 @@ val alist = series(19) writeln " list: ", alist -writeln " sum: ", fold(fn{+}, alist) -writeln "product: ", fold(fn{*}, alist) +writeln " sum: ", fold(alist, by=fn{+}) +writeln "product: ", fold(alist, by=fn{*}) diff --git a/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-1.jq b/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-1.jq deleted file mode 100644 index 4dc4101f8c..0000000000 --- a/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-1.jq +++ /dev/null @@ -1,7 +0,0 @@ -def sum_multiples(d): - ((./d) | floor) | (d * . * (.+1))/2 ; - -# Sum of multiples of a or b that are less than . (the input) -def task(a;b): - . - 1 - | sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b); diff --git a/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-2.jq b/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-2.jq deleted file mode 100644 index 6583a547b0..0000000000 --- a/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5-2.jq +++ /dev/null @@ -1,3 +0,0 @@ -1000 | task(3;5) # => 233168 - -10e20 | task(3;5) # => 2.333333333333333e+41 diff --git a/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5.jq b/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5.jq new file mode 100644 index 0000000000..7a73096e2d --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Jq/sum-multiples-of-3-and-5.jq @@ -0,0 +1,20 @@ +def idivide($j): + (. % $j) as $mod + | (. - $mod) / $j ; + +def sum_multiples(d): + idivide(d) | (d * . * (.+1)) | idivide(2) ; + +# Sum of multiples of a or b that are less than . (the input) +def task(a;b): + . - 1 + | sum_multiples(a) + sum_multiples(b) - sum_multiples(a*b); + +# Examples: +(1000 | task(3;5)), # => 233168 + +(10e20 | task(3;5)), # => 2.333333333333333e+41 + +(1000000000000000000000 | task(3;5)) +# gojq => 233333333333333333333166666666666666666668 +# jq and jaq => 2.333333333333333e41 diff --git a/Task/Sum-multiples-of-3-and-5/K/sum-multiples-of-3-and-5.k b/Task/Sum-multiples-of-3-and-5/K/sum-multiples-of-3-and-5.k new file mode 100644 index 0000000000..8b6cd3f022 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/K/sum-multiples-of-3-and-5.k @@ -0,0 +1,2 @@ +limit: 1000 ++/(!limit)[&{(*/{ (3!x), (5!x)}'x)=0}'!limit] diff --git a/Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5-1.quackery b/Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5-1.quackery new file mode 100644 index 0000000000..6ae00005e0 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5-1.quackery @@ -0,0 +1,5 @@ + 0 1000 times + [ i 3 mod + i 5 mod * + 0 = if [ i + ] ] + echo diff --git a/Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5.quackery b/Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5-2.quackery similarity index 100% rename from Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5.quackery rename to Task/Sum-multiples-of-3-and-5/Quackery/sum-multiples-of-3-and-5-2.quackery diff --git a/Task/Sum-multiples-of-3-and-5/Retro/sum-multiples-of-3-and-5.retro b/Task/Sum-multiples-of-3-and-5/Retro/sum-multiples-of-3-and-5.retro new file mode 100644 index 0000000000..ac4a0593a5 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Retro/sum-multiples-of-3-and-5.retro @@ -0,0 +1,17 @@ +:sum checks if number is divisible by 5 or 3 +adds then to result +output with n:put nl; +works only with integers, no big int support +~~~ +'number var +#1 !number + +'result var +#0 !number + +:sum (n-) #3 mod #0 eq? @number #5 mod #0 eq? or [ @result @number + !result ] if ; + +#1000 [ @number sum &number v:inc ] times +@result n:put nl + +~~~ diff --git a/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg new file mode 100644 index 0000000000..55260b26a2 --- /dev/null +++ b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg @@ -0,0 +1,18 @@ +begin + +comment - return sum from a to b of the series 1 / k^2; + +real procedure suminvsq(a, b); + value a, b; real a, b; +begin + real k, sum; + sum := 0; + for k := a step 1 until b do + sum := sum + 1 / (k * k); + suminvsq := sum; +end; + +comment - show result for 1..1000 +outreal(1,suminvsq(1,1000)); + +end diff --git a/Task/Sum-of-a-series/Langur/sum-of-a-series-1.langur b/Task/Sum-of-a-series/Langur/sum-of-a-series-1.langur index d8fa25f5d9..a088cbe369 100644 --- a/Task/Sum-of-a-series/Langur/sum-of-a-series-1.langur +++ b/Task/Sum-of-a-series/Langur/sum-of-a-series-1.langur @@ -1,4 +1,4 @@ val pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214 -writeln "calc.: ", fold(fn{+}, map(fn x:1/x^2, 1..1000)) +writeln "calc.: ", fold(map(1..1000, by=fn x:1/x^2), by=fn{+}) writeln "known: ", pi^2/6 diff --git a/Task/Sum-of-a-series/Langur/sum-of-a-series-2.langur b/Task/Sum-of-a-series/Langur/sum-of-a-series-2.langur index 616b81088c..58018db702 100644 --- a/Task/Sum-of-a-series/Langur/sum-of-a-series-2.langur +++ b/Task/Sum-of-a-series/Langur/sum-of-a-series-2.langur @@ -2,5 +2,5 @@ val pi = 3.141592653589793238462643383279502884197169399375105820974944592307816 mode divMaxScale = 100 -writeln "calc.: ", fold(fn{+}, map(fn x:1/x^2, 1..1000)) +writeln "calc.: ", fold(map(1..1000, by=fn x:1/x^2), by=fn{+}) writeln "known: ", pi^2/6 diff --git a/Task/Summarize-primes/Lua/summarize-primes.lua b/Task/Summarize-primes/Lua/summarize-primes.lua new file mode 100644 index 0000000000..4a5db5ee08 --- /dev/null +++ b/Task/Summarize-primes/Lua/summarize-primes.lua @@ -0,0 +1,28 @@ +require "math" + +function isprime(n) + for i=2, math.sqrt(n) do + if math.mod(n, i) == 0 then + return false + end + end + return true +end + +index = 1 + +for i=2, 1000 do + sum = 0 + if isprime(i) then + for j=2,i do + if isprime(j) then + sum = sum + j + end + end + + if isprime(sum) then + print(index, i, sum) + end + index = index + 1 + end +end diff --git a/Task/Sylvesters-sequence/Java/sylvesters-sequence.java b/Task/Sylvesters-sequence/Java/sylvesters-sequence.java new file mode 100644 index 0000000000..416de8d0d9 --- /dev/null +++ b/Task/Sylvesters-sequence/Java/sylvesters-sequence.java @@ -0,0 +1,60 @@ +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.MathContext; +import java.math.RoundingMode; + +public final class SylvestersSequence { + + public static void main(String[] args) { + System.out.println("The first 10 terms in Sylvester's sequence are:"); + BigInteger term = BigInteger.TWO; + BigRational sum = BigRational.ZERO; + for ( int i = 1; i <= 10; i++ ) { + System.out.println(term); + sum = sum.add( new BigRational(BigInteger.ONE, term) ); + term = term.multiply(term).subtract(term).add(BigInteger.ONE); + } + System.out.println(); + + System.out.println("The sum of their reciprocals as a rational number is:"); + System.out.println(sum + System.lineSeparator()); + + System.out.println("The sum of their reciprocals as a decimal number, to 235 decimal places, is:"); + System.out.println(sum.toDecimal(235)); + } + +} + +final class BigRational { + + public BigRational(BigInteger aNumerator, BigInteger aDenominator) { + numerator = aNumerator; + denominator = aDenominator; + + BigInteger gcd = numerator.gcd(denominator); + numerator = numerator.divide(gcd); + denominator = denominator.divide(gcd); + } + + public BigRational add(BigRational other) { + BigInteger numer = numerator.multiply(other.denominator).add(denominator.multiply(other.numerator)); + BigInteger denom = denominator.multiply(other.denominator); + return new BigRational(numer, denom); + } + + public String toDecimal(int decimalPlaces) { + BigDecimal numer = new BigDecimal(numerator); + BigDecimal denom = new BigDecimal(denominator); + return numer.divide(denom, new MathContext(decimalPlaces + 1, RoundingMode.HALF_UP)).toString(); + } + + public String toString() { + return numerator.toString() + " / " + denominator.toString(); + } + + public static final BigRational ZERO = new BigRational(BigInteger.ZERO, BigInteger.ONE); + + private BigInteger numerator; + private BigInteger denominator; + +} diff --git a/Task/Symmetric-difference/Wren/symmetric-difference.wren b/Task/Symmetric-difference/Wren/symmetric-difference.wren index 9bb7ad6ab9..30eaa25574 100644 --- a/Task/Symmetric-difference/Wren/symmetric-difference.wren +++ b/Task/Symmetric-difference/Wren/symmetric-difference.wren @@ -1,11 +1,9 @@ import "./set" for Set -var symmetricDifference = Fn.new { |a, b| a.except(b).union(b.except(a)) } - var a = Set.new(["John", "Bob", "Mary", "Serena"]) var b = Set.new(["Jim", "Mary", "John", "Bob"]) System.print("A = %(a)") System.print("B = %(b)") System.print("A - B = %(a.except(b))") System.print("B - A = %(b.except(a))") -System.print("A △ B = %(symmetricDifference.call(a, b))") +System.print("A △ B = %(a.symDiff(b))") diff --git a/Task/System-time/Atari-BASIC/system-time.basic b/Task/System-time/Atari-BASIC/system-time.basic new file mode 100644 index 0000000000..21f7dbafab --- /dev/null +++ b/Task/System-time/Atari-BASIC/system-time.basic @@ -0,0 +1,4 @@ +10 REM DETECT NTSC OR PAL SYSTEM +20 FPS=60:IF PEEK(53268)=1 THEN FPS=50 +30 JIFFIES=65536*PEEK(18)+256*PEEK(19)+PEEK(20) +40 PRINT JIFFIES/FPS;" SECONDS SINCE LAST RESET" diff --git a/Task/System-time/Python/system-time.py b/Task/System-time/Python/system-time.py index 513d9a94ab..38b94f8a27 100644 --- a/Task/System-time/Python/system-time.py +++ b/Task/System-time/Python/system-time.py @@ -1,2 +1,2 @@ import time -print time.ctime() +print(time.ctime()) diff --git a/Task/System-time/Wren/system-time.wren b/Task/System-time/Wren/system-time.wren index ba4e07fc5e..9b37978c91 100644 --- a/Task/System-time/Wren/system-time.wren +++ b/Task/System-time/Wren/system-time.wren @@ -1,10 +1,3 @@ -import "os" for Process -import "./date" for Date +import "timer" for Now -var args = Process.arguments -if (args.count != 1) Fiber.abort("Please pass the current time in hh:mm:ss format.") -var startTime = Date.parse(args[0], Date.isoTime) -for (i in 0..1e8) {} // do something which takes a bit of time -var now = startTime.addMillisecs((System.clock * 1000).round) -Date.default = Date.isoTime + "|.|ttt" -System.print("Time now is %(now)") +System.print(Now.time) diff --git a/Task/Taxicab-numbers/Arturo/taxicab-numbers.arturo b/Task/Taxicab-numbers/Arturo/taxicab-numbers.arturo new file mode 100644 index 0000000000..11422e07d2 --- /dev/null +++ b/Task/Taxicab-numbers/Arturo/taxicab-numbers.arturo @@ -0,0 +1,18 @@ +taxicabs: [0] ++ (@1..1200) | combine.repeated.by:2 + | gather 'pair -> (pair\0^3) + pair\1^3 + | select [k,pair] -> (size pair) > 1 + | arrange [k,v] -> to :integer k + +cubed: function [n]-> pad (to :string n)++"³" 4 + +loop append @1..25 @2000..2007 'rank [ + [num,p]: taxicabs\[rank] + print [ + pad to :string rank 5 ":" + pad num 10 "=" + cubed p\0\0 "+" + cubed p\0\1 "=" + cubed p\1\0 "+" + cubed p\1\1 + ] +] diff --git a/Task/Taxicab-numbers/M2000-Interpreter/taxicab-numbers.m2000 b/Task/Taxicab-numbers/M2000-Interpreter/taxicab-numbers.m2000 new file mode 100644 index 0000000000..b6fb31d9db --- /dev/null +++ b/Task/Taxicab-numbers/M2000-Interpreter/taxicab-numbers.m2000 @@ -0,0 +1,47 @@ +module TaxiCab (f as long){ + cls,0 + Print Part "Taxicab numbers" + Print Under + profiler + var Cubes=list, Sums=list, Ret=list + var st=0, en=1200 + st=@Proc(0, en) + sort ret as number + Display(1, 25) + Display(2000, 2006) + Print timecount + print "done" + end + sub Display(from, to) + local k=each(ret, from,to), s="" + while k + s= format$("{0:-6} {1:-12}",K^+1, val(eval$(k!)+"&&"))+eval$(k) + Print s : if f>-1 then print #f, s + end while + end sub + function Proc(ia, ib) + local i, cube as long long, s as long long + for i=ia to ib + if i mod 10=1 then print over $("#0.00"), "Working..";(i-ia)/ib*100;"%" + cube=i^3 + Append Cubes, cube + k=each(cubes) + while k + s=cube+eval(k) + if not exist(Sums, s) then + append Sums,s:=(i)+"^3 + "+(k^)+"^3" + else.if not exist(Ret, s) then + append Ret, s:=" = "+(i)+"^3 + "+(k^)+"^3 = "+eval$(Sums) + end if + end while + next + print over $("#0.00"), "Working..";100;"%" + print + =i + end function +} +file2export="TaxiCabNumbers.txt" +open file2export for wide output as #f +TaxiCab f +close #f +win dir$+"TaxiCabNumbers.txt" diff --git a/Task/Temperature-conversion/ANSI-BASIC/temperature-conversion.basic b/Task/Temperature-conversion/ANSI-BASIC/temperature-conversion.basic new file mode 100644 index 0000000000..439ee88a59 --- /dev/null +++ b/Task/Temperature-conversion/ANSI-BASIC/temperature-conversion.basic @@ -0,0 +1,13 @@ +100 REM Temperature conversion +110 DO +120 INPUT PROMPT "Kelvin degrees ":K +130 IF K < 0 THEN EXIT DO +140 LET C = K - 273.15 +150 LET F = K * 1.8 - 459.67 +160 LET R = K * 1.8 +170 PRINT K; "Kelvin is equivalent to" +180 PRINT C; "degrees Celsius," +190 PRINT F; "degrees Fahrenheit," +200 PRINT R; "degrees Rankine." +210 LOOP +220 END diff --git a/Task/Temperature-conversion/ASIC/temperature-conversion.asic b/Task/Temperature-conversion/ASIC/temperature-conversion.asic new file mode 100644 index 0000000000..71ac7b6e9e --- /dev/null +++ b/Task/Temperature-conversion/ASIC/temperature-conversion.asic @@ -0,0 +1,20 @@ +REM Temperature conversion +PRINT "Kelvin degrees"; +INPUT K@ +WHILE K@ >= 0 + C@ = K@ - 273.15 + R@ = K@ * 1.8 + F@ = R@ - 459.67 + CLS + PRINT K@; + PRINT " Kelvin is equivalent to" + PRINT C@; + PRINT " degrees Celsius," + PRINT F@; + PRINT " degrees Fahrenheit," + PRINT R@; + PRINT " degrees Rankine." + PRINT "Kelvin degrees"; + INPUT K@ +WEND +END diff --git a/Task/Temperature-conversion/BASIC/temperature-conversion.basic b/Task/Temperature-conversion/BASIC/temperature-conversion.basic deleted file mode 100644 index 55a3e1aba3..0000000000 --- a/Task/Temperature-conversion/BASIC/temperature-conversion.basic +++ /dev/null @@ -1,11 +0,0 @@ -10 REM TRANSLATION OF AWK VERSION -20 INPUT "KELVIN DEGREES",K -30 IF K <= 0 THEN END: REM A VALUE OF ZERO OR LESS WILL END PROGRAM -40 LET C = K - 273.15 -50 LET F = K * 1.8 - 459.67 -60 LET R = K * 1.8 -70 PRINT K; " KELVIN IS EQUIVALENT TO" -80 PRINT C; " DEGREES CELSIUS" -90 PRINT F; " DEGREES FAHRENHEIT" -100 PRINT R; " DEGREES RANKINE" -110 GOTO 20 diff --git a/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic b/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic index f96749e0cf..508ecae8df 100644 --- a/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic +++ b/Task/Temperature-conversion/Chipmunk-Basic/temperature-conversion.basic @@ -1,7 +1,7 @@ 10 CLS : REM 10 HOME for Applesoft BASIC : DELETE for Minimal BASIC 20 PRINT "Kelvin Degrees "; 30 INPUT K -40 IF K <= 0 THEN 130 +40 IF K < 0 THEN 130 50 LET C = K-273.15 60 LET F = K*1.8-459.67 70 LET R = K*1.8 diff --git a/Task/Temperature-conversion/M2000-Interpreter/temperature-conversion-1.m2000 b/Task/Temperature-conversion/M2000-Interpreter/temperature-conversion-1.m2000 new file mode 100644 index 0000000000..441b01a9c3 --- /dev/null +++ b/Task/Temperature-conversion/M2000-Interpreter/temperature-conversion-1.m2000 @@ -0,0 +1,9 @@ +module ZX81_code { + 10 PRINT "ENTER A TEMPERATURE IN KELVINS" + 20 INPUT K + 30 PRINT K;" KELVINS =" + 40 PRINT K-273.15;" DEGREES CELSIUS" + 50 PRINT K*1.8-459.67;" DEGREES FAHRENHEIT" + 60 PRINT K*1.8;" DEGREES RANKINE" +} +ZX81_code diff --git a/Task/Temperature-conversion/M2000-Interpreter/temperature-conversion-2.m2000 b/Task/Temperature-conversion/M2000-Interpreter/temperature-conversion-2.m2000 new file mode 100644 index 0000000000..32dfa077ad --- /dev/null +++ b/Task/Temperature-conversion/M2000-Interpreter/temperature-conversion-2.m2000 @@ -0,0 +1,60 @@ +Module Temprature_Conversions { + Module Decorated_Modules { + Module Cnvt2Fahrenheit (x){Push "Fahrenheit", Round(x*1.8+32, 2)} + Module CnvtFromFahrenheit (x) {Push "Fahrenheit", Round((x-32)/1.8, 2)} + Module Cnvt2Kelvin (x){Push "Kelvin", Round(x+273.15, 2)} + Module CnvtFromKelvin (x){Push "Kelvin", Round(x-273.15, 2)} + Module Cnvt2Rankine (x){Push "Rankine", Round(x*1.8+ 491.67, 2) } + Module CnvtFromRankine (x){Push "Rankine", Round((x-491.67)/1.8, 2)} + Module Temperatures { + Convertion + data format$("From {0}° {1} convert to {2}° {3}", number, letter$, number, letter$) + } + k=253.15 + Data "Kelvin="+k + Temperatures k ; cnvtForm as CnvtFromKelvin + Temperatures k ; cnvtForm as CnvtFromKelvin, convert as Cnvt2Fahrenheit + Temperatures k ; cnvtForm as CnvtFromKelvin, convert as Cnvt2Rankine + k=-20 + Data "Celsius="+k + Temperatures k ; convert as Cnvt2Kelvin + Temperatures k ; convert as Cnvt2Fahrenheit + Temperatures k ; convert as Cnvt2Rankine + k=-4 + Data "Fahrenheit="+k + Temperatures k ; cnvtForm as CnvtFromFahrenheit, convert as Cnvt2Kelvin + Temperatures k ;cnvtForm as CnvtFromFahrenheit + Temperatures k ;cnvtForm as CnvtFromFahrenheit, convert as Cnvt2Rankine + k=455.67 + Data "Rankine="+k + Temperatures k ; cnvtForm as CnvtFromRankine, convert as Cnvt2Kelvin + Temperatures k ;cnvtForm as CnvtFromRankine + Temperatures k ;cnvtForm as CnvtFromRankine, convert as Cnvt2Fahrenheit + + } + Module Global Convertion { + over ' doublicate stack + Module cnvtForm { + Push "Celsius" : shift 2 + } + Module convert { + Push "Celsius" : shift 2 + } + cnvtForm : convert + Shift 3 ' move 3rd to 1st + Shift 4 ' move 4th to 1st + } + Module TemperaturesGreek { + Convertion + data format$("Από {0}° {1} μετατροπή σε {2}° {3}", number, letter$, number, letter$) + } + Flush + Data "==========English==========" + Decorated_Modules + Data "==========Ελληνικά==========" + Decorated_Modules ; Temperatures as TemperaturesGreek + Report$ = array([])#str$(chr$(13)+chr$(10)) + ClipBoard Report$ + Report Report$ +} +Temprature_Conversions diff --git a/Task/Temperature-conversion/Modula-2/temperature-conversion.mod2 b/Task/Temperature-conversion/Modula-2/temperature-conversion.mod2 new file mode 100644 index 0000000000..c8a92c3151 --- /dev/null +++ b/Task/Temperature-conversion/Modula-2/temperature-conversion.mod2 @@ -0,0 +1,21 @@ +MODULE TempConv; +(* Temperature conversion *) +FROM STextIO IMPORT + SkipLine, WriteString, WriteLn; +FROM SRealIO IMPORT + ReadReal, WriteFixed; + +VAR + K, C, F, R: REAL; +BEGIN + WriteString("Temperature to convert (in Kelvin): "); + ReadReal(K); + SkipLine; + WriteString("K: "); WriteFixed(K, 3, 8); WriteLn; + C := K - 273.15; + WriteString("C: "); WriteFixed(C, 3, 8); WriteLn; + F := 1.8 * C + 32.0; + WriteString("F: "); WriteFixed(F, 3, 8); WriteLn; + R := F + 459.67; + WriteString("R: "); WriteFixed(R, 3, 8); WriteLn; +END TempConv. diff --git a/Task/Temperature-conversion/QBasic/temperature-conversion.basic b/Task/Temperature-conversion/QBasic/temperature-conversion.basic index 1426c7f862..3c52236988 100644 --- a/Task/Temperature-conversion/QBasic/temperature-conversion.basic +++ b/Task/Temperature-conversion/QBasic/temperature-conversion.basic @@ -1,5 +1,6 @@ +' Temperature conversion DO - INPUT "Kelvin degrees (>=0): ", K + INPUT "Kelvin degrees (>=0): ", K LOOP UNTIL K >= 0 PRINT "K = " + STR$(K) diff --git a/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic b/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic index 29be777622..b3f171c3b1 100644 --- a/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic +++ b/Task/Temperature-conversion/Quite-BASIC/temperature-conversion.basic @@ -1,6 +1,6 @@ 10 PRINT "Kelvin Degrees "; 20 INPUT ""; K -30 IF K <= 0 THEN END +30 IF K < 0 THEN END 40 LET C = K-273.15 50 LET F = K*1.8-459.67 60 LET R = K*1.8 diff --git a/Task/Temperature-conversion/RapidQ/temperature-conversion.rapidq b/Task/Temperature-conversion/RapidQ/temperature-conversion.rapidq new file mode 100644 index 0000000000..7bfc21528f --- /dev/null +++ b/Task/Temperature-conversion/RapidQ/temperature-conversion.rapidq @@ -0,0 +1,13 @@ +'Temperature conversion +DO + INPUT "Kelvin degrees "; K + IF K < 0 THEN EXIT DO + C = K - 273.15 + F = K * 1.8 - 459.67 + R = K * 1.8 + PRINT K; " Kelvin is equivalent to" + PRINT C; " degrees Celsius," + PRINT F; " degrees Fahrenheit," + PRINT R; " degrees Rankine." +LOOP +END diff --git a/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.basic b/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.basic index ece2ed6d2f..054c96f4f8 100644 --- a/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.basic +++ b/Task/Temperature-conversion/ZX-Spectrum-Basic/temperature-conversion.basic @@ -1,6 +1,6 @@ 10 REM Translation of traditional basic version 20 INPUT "Kelvin Degrees? ";k -30 IF k <= 0 THEN STOP: REM A value of zero or less will end program +30 IF k < 0 THEN STOP: REM A value less than zero will end program 40 LET c = k - 273.15 50 LET f = k * 1.8 - 459.67 60 LET r = k * 1.8 diff --git a/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-1.basic b/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-1.basic new file mode 100644 index 0000000000..6ae70540de --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-1.basic @@ -0,0 +1 @@ +GRAPHICS 0 diff --git a/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-2.basic b/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-2.basic new file mode 100644 index 0000000000..8ea7b8fd47 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-2.basic @@ -0,0 +1 @@ +GR.0 diff --git a/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen.basic b/Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-3.basic similarity index 100% rename from Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen.basic rename to Task/Terminal-control-Clear-the-screen/Atari-BASIC/terminal-control-clear-the-screen-3.basic diff --git a/Task/Terminal-control-Clear-the-screen/M2000-Interpreter/terminal-control-clear-the-screen.m2000 b/Task/Terminal-control-Clear-the-screen/M2000-Interpreter/terminal-control-clear-the-screen.m2000 index 95de22772a..7b71240b4e 100644 --- a/Task/Terminal-control-Clear-the-screen/M2000-Interpreter/terminal-control-clear-the-screen.m2000 +++ b/Task/Terminal-control-Clear-the-screen/M2000-Interpreter/terminal-control-clear-the-screen.m2000 @@ -28,5 +28,20 @@ Module Checkit { Back { Cls 15 ' white border } + Declare form1 Form + With form1, "Title","My Window", "opacity", 200 ' 0 to 255 opacity for window + Layer form1 { + Window 20, 12000, 6000; + cls #ff0077, 0 + pen 0 + Cursor 0, height-1 + Print Part $(2, width), "This is layer form1" + } + ' Open form1 Modal + Title "", 0 ' hide console + Method form1, "show", 1 + Title "done", 1 ' show console and change title on taskbar + + Declare form1 Nothing } checkit diff --git a/Task/Terminal-control-Clear-the-screen/Wren/terminal-control-clear-the-screen.wren b/Task/Terminal-control-Clear-the-screen/Wren/terminal-control-clear-the-screen.wren index 27e558cc61..6cf0f22267 100644 --- a/Task/Terminal-control-Clear-the-screen/Wren/terminal-control-clear-the-screen.wren +++ b/Task/Terminal-control-Clear-the-screen/Wren/terminal-control-clear-the-screen.wren @@ -1 +1,3 @@ -System.print("\e[2J") +import "./ansi" for Screen + +Screen.clear() diff --git a/Task/Terminal-control-Coloured-text/FutureBasic/terminal-control-coloured-text.basic b/Task/Terminal-control-Coloured-text/FutureBasic/terminal-control-coloured-text.basic new file mode 100644 index 0000000000..ff98e9547c --- /dev/null +++ b/Task/Terminal-control-Coloured-text/FutureBasic/terminal-control-coloured-text.basic @@ -0,0 +1,42 @@ +// Terminal control/Coloured text +// https://rosettacode.org/wiki/Terminal_control/Coloured_text#FreeBASIC + +_Window = 1 + +window _Window,@"Flashing Colored Text",fn cgrectmake(0,0,400,400) +windowcenter(_Window) +WindowSetBackgroundColor(_Window,fn ColorBlack) + +bool FlashingColor + +local fn WordColors + +short Color + +IF FlashingColor = 0 +FlashingColor = 1 +ELSE +FlashingColor = 0 +END IF +cls +for Color = 1 to 8 +if FlashingColor +text @"Menlo",30,_zBlack,_zBlack +print @(1,Color), @"Flashing Color" +else +if Color = 1 then text @"Menlo",30,_zYellow,_zBlue +if Color = 2 then text @"Menlo",30,_zGreen,_zBlack +if Color = 3 then text @"Menlo",30,_zCyan,_zYellow +if Color = 4 then text @"Menlo",30,_zBlue,_zWhite +if Color = 5 then text @"Menlo",30,_zMagenta,_zYellow +if Color = 6 then text @"Menlo",30,_zRed,_zBlack +if Color = 7 then text @"Menlo",30,_zWhite,_zBlue +if Color = 8 then text @"Menlo",30,_zBrown,_zWhite +print @(1,Color), @"Flashing Color" +end if +next Color +end fn + +fn AppSetTimer( 1, @fn WordColors, _true ) + +handleevents diff --git a/Task/Terminal-control-Coloured-text/Wren/terminal-control-coloured-text.wren b/Task/Terminal-control-Coloured-text/Wren/terminal-control-coloured-text.wren index 64494a8caf..f735201764 100644 --- a/Task/Terminal-control-Coloured-text/Wren/terminal-control-coloured-text.wren +++ b/Task/Terminal-control-Coloured-text/Wren/terminal-control-coloured-text.wren @@ -1,18 +1,19 @@ +import "./ansi" for Screen import "timer" for Timer var colors = ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"] // display words using 'bright' colors -for (i in 1..7) System.print("\e[%(30+i);1m%(colors[i])") // red to white -Timer.sleep(3000) // wait for 3 seconds -System.write("\e[47m") // set background color to white -System.write("\e[2J") // clear screen to background color -System.write("\e[H") // home the cursor +for (i in 1..7) Screen.print(colors[i], colors[i]) // Red to White + +Timer.sleep(3000) // wait for 3 seconds +Screen.setBackColor("white") // set background color to white +Screen.clear() // clear screen to background color & home the cursor // display words again using 'blinking' colors -System.write("\e[5m") // blink on -for (i in 0..6) System.print("\e[%(30+i);1m%(colors[i])") // black to cyan -Timer.sleep(3000) // wait for 3 more seconds -System.write("\e[0m") // reset all attributes -System.write("\e[2J") // clear screen to background color -System.write("\e[H") // home the cursor +Screen.setStyle("blink") // blink on +for (i in 0..6) Screen.print(colors[i], colors[i]) // Black to Cyan + +Timer.sleep(3000) // wait for 3 more seconds +Screen.reset() // reset all attributes +Screen.clear() // clear screen to background color & home the cursor diff --git a/Task/Terminal-control-Cursor-movement/FutureBasic/terminal-control-cursor-movement.basic b/Task/Terminal-control-Cursor-movement/FutureBasic/terminal-control-cursor-movement.basic new file mode 100644 index 0000000000..93dfedc204 --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/FutureBasic/terminal-control-cursor-movement.basic @@ -0,0 +1,44 @@ +_window = 1 +_w = 80 : _h = 24 +window _window,@"Cursor Movement",fn cgrectmake(0,0,640,380) +text @"Menlo", 13 + +local fn LocateCursor(x as short,y as short,Character as CFStringRef) +print @(x,y) Character; +end fn + +// width is 80 characters +// height is 24 rows + + +short x,y + +// place cursor in the center to start +x = _w/2 : y = _h/2 +print @(x,y) @" "; +// Move cursor up one line +y = y -1 +fn LocateCursor(x,y,@"U") +// Move cursor left +x = x - 1 +fn LocateCursor(x,y,@"L") +// Move cursor down +y = y + 1 +fn LocateCursor(x,y,@"D") +// Move cursor right +x = x + 1 +fn LocateCursor(x,y,@"R") +// Move cursor to beginning of line +x = 1 +fn LocateCursor(x,y,@"S") +// Move cursor to end of line +x = _w +fn LocateCursor(x,y,@"E") +// Move cursor to top left corner +x = 1: y = 1 +fn LocateCursor(x,y,@"T") +// Move cursor to bottom right corner +x = _W: y = _h +fn LocateCursor(x,y,@"B") + +handleevents diff --git a/Task/Terminal-control-Cursor-movement/Wren/terminal-control-cursor-movement.wren b/Task/Terminal-control-Cursor-movement/Wren/terminal-control-cursor-movement.wren index 523cc26569..e1ac92ac70 100644 --- a/Task/Terminal-control-Cursor-movement/Wren/terminal-control-cursor-movement.wren +++ b/Task/Terminal-control-Cursor-movement/Wren/terminal-control-cursor-movement.wren @@ -1,32 +1,23 @@ +import "./ansi" for Screen, Cursor import "timer" for Timer -import "io" for Stdout -System.write("\e[2J") // clear terminal -System.write("\e[12;40H") // move to (12, 40) -Stdout.flush() +Screen.clear() // clear terminal +Cursor.move(12, 40) // move to (12, 40) Timer.sleep(2000) -System.write("\e[D") // move left -Stdout.flush() +Cursor.left // move left Timer.sleep(2000) -System.write("\e[C") // move right -Stdout.flush() +Cursor.right // move right Timer.sleep(2000) -System.write("\e[A") // move up -Stdout.flush() +Cursor.up // move up Timer.sleep(2000) -System.write("\e[B") // move down -Stdout.flush() +Cursor.down // move down Timer.sleep(2000) -System.write("\e[G") // move to beginning of line -Stdout.flush() +Cursor.column // move to beginning of line Timer.sleep(2000) -System.write("\e[79C") // move to end of line (assuming 80 column terminal) -Stdout.flush() +Cursor.column(80) // move to end of line (assuming 80 column terminal) Timer.sleep(2000) -System.write("\e[1;1H") // move to top left corner -Stdout.flush() +Cursor.home // move to top left corner Timer.sleep(2000) -System.write("\e[24;80H") // move to bottom right corner (assuming 80 x 24 terminal) -Stdout.flush() +Cursor.move(24, 80) // move to bottom right corner (assuming 80 x 24 terminal) Timer.sleep(2000) -System.write("\e[1;1H") // home cursor again before quitting +Cursor.home // home cursor again before quitting diff --git a/Task/Terminal-control-Cursor-positioning/FutureBasic/terminal-control-cursor-positioning.basic b/Task/Terminal-control-Cursor-positioning/FutureBasic/terminal-control-cursor-positioning.basic new file mode 100644 index 0000000000..c9a87f16a9 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/FutureBasic/terminal-control-cursor-positioning.basic @@ -0,0 +1,5 @@ +// Terminal control/Cursor positioning +// https://rosettacode.org/wiki/Terminal_control/Cursor_positioning + +print @(3,6) @"Hello" +handleevents diff --git a/Task/Terminal-control-Cursor-positioning/Wren/terminal-control-cursor-positioning.wren b/Task/Terminal-control-Cursor-positioning/Wren/terminal-control-cursor-positioning.wren index 5c80f0aa33..1f05a21453 100644 --- a/Task/Terminal-control-Cursor-positioning/Wren/terminal-control-cursor-positioning.wren +++ b/Task/Terminal-control-Cursor-positioning/Wren/terminal-control-cursor-positioning.wren @@ -1,2 +1,5 @@ -System.write("\e[2J") // clear the terminal -System.print("\e[6;3HHello") // move to (6, 3) and print 'Hello' +import "./ansi" for Screen, Cursor + +Screen.clear() // clear the terminal +Cursor.move(6, 3) // move to (6, 3) +System.print("Hello") // print 'Hello' diff --git a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren deleted file mode 100644 index 29e4020676..0000000000 --- a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren +++ /dev/null @@ -1,12 +0,0 @@ -/* Terminal_control_Dimensions.wren */ - -class C { - foreign static terminalWidth - foreign static terminalHeight -} - -var w = C.terminalWidth -var h = C.terminalHeight -System.print("The dimensions of the terminal are:") -System.print(" Width = %(w)") -System.print(" Height = %(h)") diff --git a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren deleted file mode 100644 index 39adb409c6..0000000000 --- a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren +++ /dev/null @@ -1,94 +0,0 @@ -/* gcc Terminal_control_Dimensions.c -o Terminal_control_Dimensions -lwren -lm */ - -#include -#include -#include -#include -#include -#include "wren.h" - -void C_terminalWidth(WrenVM* vm) { - struct winsize w; - ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); - wrenSetSlotDouble(vm, 0, (double)w.ws_col); -} - -void C_terminalHeight(WrenVM* vm) { - struct winsize w; - ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); - wrenSetSlotDouble(vm, 0, (double)w.ws_row); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "terminalWidth") == 0) { - return C_terminalWidth; - } else if (isStatic && strcmp(signature, "terminalHeight") == 0) { - return C_terminalHeight; - } - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main() { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Terminal_control_Dimensions.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions.wren b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions.wren new file mode 100644 index 0000000000..4b778214dd --- /dev/null +++ b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions.wren @@ -0,0 +1,6 @@ +import "os" for Terminal + +var size = Terminal.size +System.print("The dimensions of the terminal are:") +System.print(" Width = %(size[1])") +System.print(" Height = %(size[0])") diff --git a/Task/Terminal-control-Display-an-extended-character/Aquarius-BASIC/terminal-control-display-an-extended-character.basic b/Task/Terminal-control-Display-an-extended-character/Aquarius-BASIC/terminal-control-display-an-extended-character.basic new file mode 100644 index 0000000000..19850cc6f9 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Aquarius-BASIC/terminal-control-display-an-extended-character.basic @@ -0,0 +1 @@ +PRINT CHR$(0) diff --git a/Task/Terminal-control-Hiding-the-cursor/Atari-BASIC/terminal-control-hiding-the-cursor.basic b/Task/Terminal-control-Hiding-the-cursor/Atari-BASIC/terminal-control-hiding-the-cursor.basic new file mode 100644 index 0000000000..f514d1ef6c --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Atari-BASIC/terminal-control-hiding-the-cursor.basic @@ -0,0 +1,9 @@ +5 GRAPHICS 0 +10 POKE 752,1:PRINT "hidden" +20 GOSUB 100 +30 POKE 752,0:PRINT "visible" +40 GOSUB 100 +50 END +100 FOR I=1 TO 1500 +110 NEXT I +120 RETURN diff --git a/Task/Terminal-control-Hiding-the-cursor/FutureBasic/terminal-control-hiding-the-cursor.basic b/Task/Terminal-control-Hiding-the-cursor/FutureBasic/terminal-control-hiding-the-cursor.basic new file mode 100644 index 0000000000..7f7402c267 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/FutureBasic/terminal-control-hiding-the-cursor.basic @@ -0,0 +1,35 @@ +// Terminal control/Hiding the cursor +// https://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor# + + +_window = 1 +begin enum 1 + _scrollView + _textView +end enum + +void local fn BuildWindow + CGRect r = fn NSMakeRect(0,0,550,400) + window _window, @"Hide Cursor", r + scrollview _scrollView, r + ViewSetAutoresizingMask( _scrollView, NSViewWidthSizable + NSViewHeightSizable ) + textview _textView,, _scrollView + TextSetString( _textView, @"Cursor hides every two seconds. " ) + WindowMakeFirstResponder( _window, _textView ) +end fn + +editmenu 1 + +fn BuildWindow + +local fn HiddenCursorToggle + if fn TextViewIsEditable(_textView) + TextViewSetEditable(_textView,_false) + else + TextViewSetEditable(_textView,_true) + end if +end fn + +fn AppSetTimer( 2, @Fn HiddenCursorToggle, _true ) // hide cursor every two seconds + +HandleEvents diff --git a/Task/Terminal-control-Hiding-the-cursor/M2000-Interpreter/terminal-control-hiding-the-cursor.m2000 b/Task/Terminal-control-Hiding-the-cursor/M2000-Interpreter/terminal-control-hiding-the-cursor.m2000 new file mode 100644 index 0000000000..09bbe73e8e --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/M2000-Interpreter/terminal-control-hiding-the-cursor.m2000 @@ -0,0 +1,11 @@ +' Find and replace time for caret time out +declare CR WINDOWS.REGISTRY +const HKEY_CURRENT_USER = 0x80000001& +const REG_DWORD = 4& '32-bit number +with CR, "ClassKey", HKEY_CURRENT_USER +with CR, "SectionKey", "Control Panel\Desktop\" +with CR, "ValueType", REG_DWORD , "ValueKey", "CaretTimeout" +with CR, "KeyExists" as CaretTimeout.Exist, "Value" as CaretTimeout.value +If CaretTimeout.Exist then Print "Old Value: 0x"+Hex$(uint(CaretTimeout.value),4)+"&", CaretTimeout.value +CaretTimeout.value=0xFFFFFFFF& +If CaretTimeout.Exist then Print "New Value: 0x"+ Hex$(uint(CaretTimeout.value),4)+"&", CaretTimeout.value diff --git a/Task/Terminal-control-Hiding-the-cursor/Wren/terminal-control-hiding-the-cursor.wren b/Task/Terminal-control-Hiding-the-cursor/Wren/terminal-control-hiding-the-cursor.wren index cde8953be6..c8d35edc95 100644 --- a/Task/Terminal-control-Hiding-the-cursor/Wren/terminal-control-hiding-the-cursor.wren +++ b/Task/Terminal-control-Hiding-the-cursor/Wren/terminal-control-hiding-the-cursor.wren @@ -1,6 +1,7 @@ +import "./ansi" for Cursor import "timer" for Timer -System.print("\e[?25l") +Cursor.hide() Timer.sleep(3000) -System.print("\e[?25h") +Cursor.show() Timer.sleep(3000) diff --git a/Task/Terminal-control-Inverse-video/Atari-BASIC/terminal-control-inverse-video.basic b/Task/Terminal-control-Inverse-video/Atari-BASIC/terminal-control-inverse-video.basic new file mode 100644 index 0000000000..2b1e8d2894 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Atari-BASIC/terminal-control-inverse-video.basic @@ -0,0 +1,9 @@ +10 DIM S$(12),INV$(12) +20 S$="Rosetta Code" +30 FOR I=1 TO 12 +40 INV$(I)=CHR$(ASC(S$(I))+128) +50 NEXT I +60 GRAPHICS 0 +70 FOR I=1 TO 10 +80 PRINT S$,INV$ +90 NEXT I diff --git a/Task/Terminal-control-Inverse-video/Wren/terminal-control-inverse-video.wren b/Task/Terminal-control-Inverse-video/Wren/terminal-control-inverse-video.wren index 7510ce49de..dc43d69898 100644 --- a/Task/Terminal-control-Inverse-video/Wren/terminal-control-inverse-video.wren +++ b/Task/Terminal-control-Inverse-video/Wren/terminal-control-inverse-video.wren @@ -1,2 +1,4 @@ -System.print("\e[7mInverse") -System.print("\e[0mNormal") +import "./ansi" for Style + +System.print(Style.inverse("Inverse")) +System.print("Normal") diff --git a/Task/Terminal-control-Positional-read/Atari-BASIC/terminal-control-positional-read.basic b/Task/Terminal-control-Positional-read/Atari-BASIC/terminal-control-positional-read.basic new file mode 100644 index 0000000000..1db55cf02b --- /dev/null +++ b/Task/Terminal-control-Positional-read/Atari-BASIC/terminal-control-positional-read.basic @@ -0,0 +1,2 @@ +LOCATE 3,6,Q +C$=CHR$(Q) diff --git a/Task/Terminal-control-Preserve-screen/Wren/terminal-control-preserve-screen.wren b/Task/Terminal-control-Preserve-screen/Wren/terminal-control-preserve-screen.wren index 2ce53fb648..9d4037f5e3 100644 --- a/Task/Terminal-control-Preserve-screen/Wren/terminal-control-preserve-screen.wren +++ b/Task/Terminal-control-Preserve-screen/Wren/terminal-control-preserve-screen.wren @@ -1,12 +1,11 @@ -import "io" for Stdout +import "./ansi" for Screen import "timer" for Timer -System.write("\e[?1049h\e[H") +Screen.enableAltBuffer() System.print("Alternate screen buffer") for (i in 5..1) { var s = (i != 1) ? "s" : "" - System.write("\rGoing back in %(i) second%(s)...") - Stdout.flush() + Screen.fwrite("\rGoing back in %(i) second%(s)...") Timer.sleep(1000) } -System.write("\e[?1049l") +Screen.disableAltBuffer() diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Atari-BASIC/terminal-control-ringing-the-terminal-bell.basic b/Task/Terminal-control-Ringing-the-terminal-bell/Atari-BASIC/terminal-control-ringing-the-terminal-bell.basic new file mode 100644 index 0000000000..add5fbc2fb --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Atari-BASIC/terminal-control-ringing-the-terminal-bell.basic @@ -0,0 +1 @@ +PRINT CHR$(253) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/FutureBasic/terminal-control-ringing-the-terminal-bell.basic b/Task/Terminal-control-Ringing-the-terminal-bell/FutureBasic/terminal-control-ringing-the-terminal-bell.basic new file mode 100644 index 0000000000..15e4e1bfb9 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/FutureBasic/terminal-control-ringing-the-terminal-bell.basic @@ -0,0 +1,2 @@ +beep +handleevents diff --git a/Task/Terminal-control-Unicode-output/FutureBasic/terminal-control-unicode-output.basic b/Task/Terminal-control-Unicode-output/FutureBasic/terminal-control-unicode-output.basic new file mode 100644 index 0000000000..962dcdcbe7 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/FutureBasic/terminal-control-unicode-output.basic @@ -0,0 +1,20 @@ +// Terminal control/Unicode output +// https://rosettacode.org/wiki/Terminal_control/Unicode_output + +text @"Menlo" , 18 + +print @"\U000025b3" + +if error + print "Unicode is not supported" +else + cls + print + CFStringRef OutputString + OutputString = @"Unicode is supported and U+25B3 is " + OutputString = fn StringbyAppendingString(OutputString,@"\U000025b3") + print OutputString + +end if + +handleevents diff --git a/Task/Terminal-control-Unicode-output/Go/terminal-control-unicode-output.go b/Task/Terminal-control-Unicode-output/Go/terminal-control-unicode-output.go deleted file mode 100644 index 352b07df61..0000000000 --- a/Task/Terminal-control-Unicode-output/Go/terminal-control-unicode-output.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "os" - "strings" -) - -func main() { - lang := strings.ToUpper(os.Getenv("LANG")) - if strings.Contains(lang, "UTF") { - fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3') - } else { - fmt.Println("This terminal does not support unicode") - } -} diff --git a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren deleted file mode 100644 index 6f00e2acd0..0000000000 --- a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren +++ /dev/null @@ -1,92 +0,0 @@ -/* gcc Terminal_control_Unicode_output.c -o Terminal_control_Unicode_output -lwren -lm */ - -#include -#include -#include -#include "wren.h" - -void C_isUnicodeSupported(WrenVM* vm) { - char *str = getenv("LANG"); - bool us = false; - int i; - for (i = 0; str[i + 2] != 0; i++) { - if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f') || - (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F')) { - us = true; - break; - } - } - wrenSetSlotBool(vm, 0, us); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "isUnicodeSupported") == 0) { - return C_isUnicodeSupported; - } - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main() { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Terminal_control_Unicode_output.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output.wren similarity index 56% rename from Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren rename to Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output.wren index 7c4cd972c3..8e96849d5e 100644 --- a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren +++ b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output.wren @@ -1,10 +1,6 @@ -/* Terminal_control_Unicode_output.wren */ +import "os" for Terminal -class C { - foreign static isUnicodeSupported -} - -if (C.isUnicodeSupported) { +if (Terminal.supportsUnicode) { System.print("Unicode is supported on this terminal and U+25B3 is : \u25b3") } else { System.print("Unicode is not supported on this terminal.") diff --git a/Task/Ternary-logic/EMal/ternary-logic.emal b/Task/Ternary-logic/EMal/ternary-logic.emal new file mode 100644 index 0000000000..b3736975c3 --- /dev/null +++ b/Task/Ternary-logic/EMal/ternary-logic.emal @@ -0,0 +1,34 @@ +type Trit +enum + int FALSE, MAYBE, TRUE + fun tNot ← <|Trit.byValue(Trit.TRUE.value - me.value) + fun tAnd ← you.value, me, you) + fun tImp ← 1 } + +nwords = mapping.values.map(&.size).sum + +puts "There are #{nwords} words in #{filename} which can be represented by the digit key mapping." +puts "They require #{mapping.size} digit combinations to represent them." +puts "#{textonyms.size} digit combinations represent Textonyms." + +# let's find something original + +repeated = mapping.keys.select(/^(.)\1\1+$/).sort_by(&.size).reverse +puts +puts "Least-effort words" +repeated.each do |w| + puts " #{w}\t #{mapping[w].join(", ")}" +end diff --git a/Task/Thue-Morse/M2000-Interpreter/thue-morse-1.m2000 b/Task/Thue-Morse/M2000-Interpreter/thue-morse-1.m2000 deleted file mode 100644 index 21311dccfc..0000000000 --- a/Task/Thue-Morse/M2000-Interpreter/thue-morse-1.m2000 +++ /dev/null @@ -1,42 +0,0 @@ -thuemorse$=lambda$ (n as integer)->{ - def sb0$="0", sb1$="1" - n=max.data(0, n) - =lambda$ - sb0$, sb1$, - n, park$ - (many)->{ - if n<0 and park$="" then exit - while n>0 - tmp$=sb0$ - sb0$=sb1$ - sb1$=tmp$ - n-- - end while - if n>=0 then n-- :park$+=sb0$ - - if many"" then - log$=resp$+"...transmitted"+{ - } - else - exit - end if - always -next i -Clipboard log$ -Report log$ diff --git a/Task/Thue-Morse/M2000-Interpreter/thue-morse-2.m2000 b/Task/Thue-Morse/M2000-Interpreter/thue-morse-2.m2000 deleted file mode 100644 index be88213690..0000000000 --- a/Task/Thue-Morse/M2000-Interpreter/thue-morse-2.m2000 +++ /dev/null @@ -1,23 +0,0 @@ -// copy thuemorse lambda here// -dim t$(0 to 6) -document log$ -jobs=stack -For i=6 to 0 - t$(i)=thuemorse$(i) - stack jobs {push i} -next i -stack jobs { - while not empty - read i - resp$=t$(i)(16) - if resp$<>"" then - log$="Message :"+str$(i,0)+{ - } - log$=resp$+"...transmitted"+{ - } - data i - end if - end while -} -Clipboard log$ -Report log$ diff --git a/Task/Thue-Morse/M2000-Interpreter/thue-morse.m2000 b/Task/Thue-Morse/M2000-Interpreter/thue-morse.m2000 new file mode 100644 index 0000000000..906fa64f00 --- /dev/null +++ b/Task/Thue-Morse/M2000-Interpreter/thue-morse.m2000 @@ -0,0 +1,67 @@ +thuemorse$=lambda$ (n as integer)->{ + def sb0$="0", sb1$="1" + n=max.data(0, n) + =lambda$ + sb0$, sb1$, + n, park$ + (many)->{ + if n<0 and park$="" then exit + while n>0 + tmp$=sb0$ + sb0$+=sb1$ + sb1$+=tmp$ + n-- + end while + if n>=0 then n-- :park$+=sb0$ + if many"" then + Print batch$; ' here we can do anything for each batch$ + else + Print + exit + end if + always +next i + +MODULE FromZX81_BASIC { +// T$(J) -> mid$(T$, J, 1) +// THEN GOTO 90 (is ok but here we use THEN 90) + 10 LET T$="0" + 20 PRINT "T0=";T$ + 30 FOR I=1 TO 7 + 40 PRINT "T";I;"="; + 50 FOR J=1 TO LEN(T$) + 60 IF MID$(T$,J, 1)="0" THEN 90 + 70 LET T$=T$+"0" + 80 GOTO 100 + 90 LET T$=T$+"1" + 100 NEXT J + 110 PRINT T$ + 120 NEXT I +} +FromZX81_BASIC +Module Modern { + NextMorse=lambda t="0", s="", i=1 -> { + t+=replace$("b", "1", replace$("1", "0", replace$("0", "b", s))) + ="T"+i+"="+t + i++ : s=t + } + for i=1 to 8 + ? NextMorse() + next +} +modern diff --git a/Task/Tic-tac-toe/FutureBasic/tic-tac-toe.basic b/Task/Tic-tac-toe/FutureBasic/tic-tac-toe.basic new file mode 100644 index 0000000000..766431995d --- /dev/null +++ b/Task/Tic-tac-toe/FutureBasic/tic-tac-toe.basic @@ -0,0 +1,303 @@ +output file "Tic-Tac-Toe" + +_computer = 0 +_human = 1 + +_window = 1 +begin enum output 1 + _one + _two + _three + _four + _five + _six + _seven + _eight + _nine + + _infoField + _resetBtn +end enum + + +void local fn BuildWindow + int i + + CGRect r = fn CGRectMake( 0, 0, 278, 348 ) + window _window, @"Tic-Tac-Toe", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + + r = fn CGRectMake( 20, 217, 80, 82 ) + for i = _one to _three + button i,,,@"", r, NSButtonTypeMomentaryLight, NSBezelStyleTexturedSquare, _window + r = fn CGRectOffset( r, 79, 0 ) + next + r = fn CGRectMake( 20, 139, 80, 82 ) + for i = _four to _six + button i,,,@"", r, NSButtonTypeMomentaryLight, NSBezelStyleTexturedSquare, _window + r = fn CGRectOffset( r, 79, 0 ) + next + r = fn CGRectMake( 20, 60, 80, 82 ) + for i = _seven to _nine + button i,,,@"", r, NSButtonTypeMomentaryLight, NSBezelStyleTexturedSquare, _window + r = fn CGRectOffset( r, 79, 0 ) + next + + for i = _one to _nine + ControlSetFontWithName( i, @"Menlo", 60.0 ) + ButtonSetTitle( i, @"" ) + ViewSetClickGestureRecognizer( i ) + next + + r = fn CGRectMake( 20, 306, 240, 24 ) + textfield _infoField,,,r, _window + TextFieldSetEditable( _infoField, NO ) + TextFieldSetSelectable( _infoField, NO ) + ControlSetAlignment( _infoField, NSTextAlignmentCenter ) + TextFieldSetDrawsBackground( _infoField, NO ) + TextFieldSetBordered( _infoField, NO ) + TextFieldSetTextColor( _infoField, fn ColorRed ) + ControlSetFontWithName( _infoField, @"Arial Bold", 18.0 ) + + r = fn CGRectMake( 155, 13, 109, 24 ) + button _resetBtn,,,@"New Game", r, NSButtonTypeMomentaryLight, NSBezelStyleRounded, _window +end fn + + +void local fn LockBoard + for int i = _one to _nine + ButtonSetState( i, NSControlStateValueOn ) + next +end fn + + +void local fn SetBtnTitleColor( tag1 as NSinteger, tag2 as NSinteger, tag3 as NSinteger, color as ColorRef ) + ButtonSetTitleColor( tag1, color ) : ButtonSetTitleColor( tag2, color ) : ButtonSetTitleColor( tag3, color ) +end fn + + +void local fn SetColorOfWinningCells( cellsToColor as NSUInteger ) + select cellsToColor + // Rows 1-3 + case 1 : fn SetBtnTitleColor( _one, _two, _three, fn ColorRed ) + case 2 : fn SetBtnTitleColor( _four, _five, _six, fn ColorRed ) + case 3 : fn SetBtnTitleColor( _seven, _eight, _nine, fn ColorRed ) + // Columns 1-3 + case 4 : fn SetBtnTitleColor( _one, _four, _seven, fn ColorRed ) + case 5 : fn SetBtnTitleColor( _two, _five, _eight, fn ColorRed ) + case 6 : fn SetBtnTitleColor( _three, _six, _nine, fn ColorRed ) + // Diagonal _one to _nine and _three to _seven + case 7 : fn SetBtnTitleColor( _one, _five, _nine, fn ColorRed ) + case 8 : fn SetBtnTitleColor( _three, _five, _seven, fn ColorRed ) + end select +end fn + + +void local fn DeclareWinner( whoseTurn as NSInteger, cellsToColor as NSUinteger ) + fn SetColorOfWinningCells( cellsToColor ) + if ( whoseTurn == _computer ) + fn LockBoard + ControlSetStringValue( _infoField, @"Macintosh won!" ) + else + fn LockBoard + ControlSetStringValue( _infoField, @"You won!" ) + end if +end fn + + +void local fn NewGame + ControlSetStringValue( _infoField, @"" ) + for int i = _one to _nine + ButtonSetState( i, NSControlStateValueOff ) + ButtonSetTitle( i, @"" ) + ButtonSetTitleColor( i, fn ColorText ) + next +end fn + + +BOOL local fn CheckCells( tag1 as NSInteger, mark1 as CFStringRef, tag2 as NSInteger, mark2 as CFStringRef, tag3 as NSInteger, mark3 as CFStringRef ) + BOOL result = NO + if fn StringIsEqual( fn ButtonTitle( tag1 ), mark1 ) && fn StringIsEqual( fn ButtonTitle( tag2 ), mark2 ) && fn StringIsEqual( fn ButtonTitle( tag3 ), mark3 ) then result = YES +end fn = result + + +BOOL local fn CheckForWinner( player as long ) as BOOL + CFStringRef mark + BOOL result = NO + + if player == _human then mark = @"X" else mark = @"O" + + // Check rows + if fn CheckCells( _one, mark, _two, mark, _three, mark ) then result = YES : fn DeclareWinner( player, 1 ) : exit fn + if fn CheckCells( _four, mark, _five, mark, _six, mark ) then result = YES : fn DeclareWinner( player, 2 ) : exit fn + if fn CheckCells( _seven, mark, _eight, mark, _nine, mark ) then result = YES : fn DeclareWinner( player, 3 ) : exit fn + + // Check colums + if fn CheckCells( _one, mark, _four, mark, _seven, mark ) then result = YES : fn DeclareWinner( player, 4 ) : exit fn + if fn CheckCells( _two, mark, _five, mark, _eight, mark ) then result = YES : fn DeclareWinner( player, 5 ) : exit fn + if fn CheckCells( _three, mark, _six , mark, _nine, mark ) then result = YES : fn DeclareWinner( player, 6 ) : exit fn + + // Check _one, _five, _nine diagonal + if fn CheckCells( _one, mark, _five, mark, _nine, mark ) then result = YES : fn DeclareWinner( player, 7 ) : exit fn + + // Check _three, _five, _seven diagonal + if fn CheckCells( _three, mark, _five, mark, _seven, mark ) then result = YES : fn DeclareWinner( player, 8 ) : exit fn +end fn = result + + +void local fn SetControls( tag as NSInteger ) + ButtonSetTitle( tag, @"O" ) : ButtonSetState( tag, NSControlStateValueOn ) +end fn + + +void local fn ComputerMove + NSUInteger i + BOOL loop = YES + + /* + 1 2 3 + 4 5 6 + 7 8 9 + */ + + // Check row 1 for winning moves + if fn CheckCells( _one, @"", _two, @"O" , _three, @"O" ) then fn SetControls( _one ) : exit fn + if fn CheckCells( _one, @"O", _two, @"" , _three, @"O" ) then fn SetControls( _two ) : exit fn + if fn CheckCells( _one, @"O", _two, @"O" , _three, @"" ) then fn SetControls( _three ) : exit fn + + // Check row 2 for winning moves + if fn CheckCells( _four, @"", _five, @"O" , _six, @"O" ) then fn SetControls( _four ) : exit fn + if fn CheckCells( _four, @"O", _five, @"" , _six, @"O" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _four, @"O", _five, @"O" , _six, @"" ) then fn SetControls( _six ) : exit fn + + // Check row 3 for winning moves + if fn CheckCells( _seven, @"", _eight, @"O" , _nine, @"O" ) then fn SetControls( _seven ) : exit fn + if fn CheckCells( _seven, @"O", _eight, @"" , _nine, @"O" ) then fn SetControls( _eight ) : exit fn + if fn CheckCells( _seven, @"O", _eight, @"O" , _nine, @"" ) then fn SetControls( _nine ) : exit fn + + // Check colmun 1 for winning moves + if fn CheckCells( _one, @"", _four, @"O", _seven, @"O" ) then fn SetControls( _one ) : exit fn + if fn CheckCells( _one, @"O", _four, @"", _seven, @"O" ) then fn SetControls( _four ) : exit fn + if fn CheckCells( _one, @"O", _four, @"O", _seven, @"" ) then fn SetControls( _seven ) : exit fn + + // Check colmun 2 for winning moves + if fn CheckCells( _two, @"", _five, @"O", _eight, @"O" ) then fn SetControls( _two ) : exit fn + if fn CheckCells( _two, @"O", _five, @"", _eight, @"O" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _two, @"O", _five, @"O", _eight, @"" ) then fn SetControls( _eight ) : exit fn + + // Check colmun 3 for winning moves + if fn CheckCells( _three, @"", _six, @"O", _nine, @"O" ) then fn SetControls( _three ) : exit fn + if fn CheckCells( _three, @"O", _six, @"", _nine, @"O" ) then fn SetControls( _six ) : exit fn + if fn CheckCells( _three, @"O", _six, @"O", _nine, @"" ) then fn SetControls( _nine ) : exit fn + + // Check _one to _nine diagonal for winning moves + if fn CheckCells( _one, @"", _five, @"O", _nine, @"O" ) then fn SetControls( _one ) : exit fn + if fn CheckCells( _one, @"O", _five, @"", _nine, @"O" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _one, @"O", _five, @"O", _nine, @"" ) then fn SetControls( _nine ) : exit fn + + // Check _three to _nine diagonal for winning moves + if fn CheckCells( _three, @"", _five, @"O", _seven, @"O" ) then fn SetControls( _three ) : exit fn + if fn CheckCells( _three, @"O", _five, @"", _seven, @"O" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _three, @"O", _five, @"O", _seven, @"" ) then fn SetControls( _seven ) : exit fn + + // Check row 1 for blocking moves + if fn CheckCells( _one, @"", _two, @"X", _three, @"X" ) then fn SetControls( _one ) : exit fn + if fn CheckCells( _one, @"X", _two, @"", _three, @"X" ) then fn SetControls( _two ) : exit fn + if fn CheckCells( _one, @"X", _two, @"X", _three, @"" ) then fn SetControls( _three ) : exit fn + + // Check row 2 for blocking moves + if fn CheckCells( _four, @"", _five, @"X", _six, @"X" ) then fn SetControls( _four ) : exit fn + if fn CheckCells( _four, @"X", _five, @"", _six, @"X" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _four, @"X", _five, @"X", _six, @"" ) then fn SetControls( _six ) : exit fn + + // Check row 3 for blocking moves + if fn CheckCells( _seven, @"", _eight, @"X", _nine, @"X" ) then fn SetControls( _seven ) : exit fn + if fn CheckCells( _seven, @"X" ,_eight, @"", _nine, @"X" ) then fn SetControls( _eight ) : exit fn + if fn CheckCells( _seven, @"X", _eight, @"X", _nine, @"" ) then fn SetControls( _nine ) : exit fn + + // Check colmun 1 for blocking moves + if fn CheckCells( _one, @"", _four, @"X", _seven, @"X" ) then fn SetControls( _one ) : exit fn + if fn CheckCells( _one, @"X", _four, @"", _seven, @"X" ) then fn SetControls( _four ) : exit fn + if fn CheckCells( _one, @"X", _four, @"X", _seven, @"" ) then fn SetControls( _seven ) : exit fn + + // Check colmun 2 for blocking moves + if fn CheckCells( _two, @"", _five, @"X", _eight, @"X" ) then fn SetControls( _two ) : exit fn + if fn CheckCells( _two, @"X", _five, @"", _eight, @"X" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _two, @"X", _five, @"X", _eight, @"" ) then fn SetControls( _eight ) : exit fn + + // Check colmun 3 for blocking moves + if fn CheckCells( _three, @"", _six, @"X", _nine, @"X" ) then fn SetControls( _three ) : exit fn + if fn CheckCells( _three, @"X", _six, @"", _nine, @"X" ) then fn SetControls( _six ) : exit fn + if fn CheckCells( _three, @"X", _six, @"X", _nine, @"" ) then fn SetControls( _nine ) : exit fn + + // Check _one, _five, _nine diagonal for blocking moves + if fn CheckCells( _one, @"", _five, @"X", _nine, @"X" ) then fn SetControls( _one ) : exit fn + if fn CheckCells( _one, @"X", _five, @"", _nine, @"X" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _one, @"X", _five, @"X", _nine, @"" ) then fn SetControls( _nine ) : exit fn + + // Check _three, _five, _nine diagonal for blocking moves + if fn CheckCells( _three, @"", _five, @"X", _seven, @"X" ) then fn SetControls( _three ) : exit fn + if fn CheckCells( _three, @"X", _five, @"", _seven, @"X" ) then fn SetControls( _five ) : exit fn + if fn CheckCells( _three, @"X" , _five, @"X", _seven, @"" ) then fn SetControls( _seven ) : exit fn + + // If no winning or blocking moves found, select random empty button for computer move + for i = _one to _nine + if ( fn StringIsEqual( fn ButtonTitle(i), @"" ) ) + while ( loop = YES ) + i = rnd(9) + if ( fn StringIsEqual( fn ButtonTitle(i), @"" ) ) + ButtonSetTitle( i, @"O" ) : ButtonSetState( i, NSControlStateValueOn ) + loop = NO + end if + wend + end if + next +end fn + + +BOOL local fn CheckForTie + BOOL result = YES + + for int i = _one to _nine + if ( fn StringIsEqual( fn ButtonTitle(i), @"" ) ) + result = NO : exit fn + end if + next +end fn = result + + +void local fn Play( tag as long ) + ButtonPerformClick( tag ) + ButtonSetTitle( tag, @"X" ) : ButtonSetState( tag, NSControlStateValueOn ) + if fn CheckForTie then fn LockBoard : ControlSetStringValue( _infoField, @"Tie Game!" ) + if ( fn CheckForWinner( _human ) == NO ) then fn ComputerMove + if ( fn CheckForWinner( _computer ) == NO ) + if fn CheckForTie then fn LockBoard : ControlSetStringValue( _infoField, @"Tie Game!" ) + else + exit fn + end if +end fn + + +void local fn DoAppEvent( ev as long ) + select (ev) + case _appWillFinishLaunching : fn BuildWindow + end select +end fn + + +void local fn DoDialog( ev as long, tag as long, wnd as long ) + select (ev) + case _btnClick + select ( tag ) + case _resetBtn : fn NewGame + end select + case _gestureRecognizerClick + if ( fn ButtonState( tag ) == NSControlStateValueOff ) then fn Play( tag ) + case _windowWillClose : end + end select +end fn + +on appevent fn DoAppEvent +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-1.j b/Task/Tic-tac-toe/J/tic-tac-toe-1.j index 69a658b77c..ef06e6f43c 100644 --- a/Task/Tic-tac-toe/J/tic-tac-toe-1.j +++ b/Task/Tic-tac-toe/J/tic-tac-toe-1.j @@ -5,4 +5,4 @@ move=. pos ($:@][echo@'no')`(-@turn@], turn@]`[`(board@])})@.open ] outcome=. 'tie'"_`(' wins',~ {&'.XO'@-@turn)@.won show=. [ ''echo@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$board) won=. [: +./ 3 = [: | +/"1@(],|:,(<@0 1|:]),:<@0 1|:|.)@(3 3$board) -ttt=: [: outcome [: [F.(show@move[_2:Z:won+.full) 10&{.@_1 +ttt=: [: outcome [: show@move^:(won-.@+.full)^:_. (10&{.@_1) diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-2.j b/Task/Tic-tac-toe/J/tic-tac-toe-2.j index 325f65948e..10d907e113 100644 --- a/Task/Tic-tac-toe/J/tic-tac-toe-2.j +++ b/Task/Tic-tac-toe/J/tic-tac-toe-2.j @@ -1 +1 @@ -Until=. {{[F.(u[_2:Z:v)}} NB. apply u until condition v is true +Until=. {{u^:(-.@v)^:_.}} NB. apply u until condition v is true diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-4.j b/Task/Tic-tac-toe/J/tic-tac-toe-4.j deleted file mode 100644 index dc3238ad10..0000000000 --- a/Task/Tic-tac-toe/J/tic-tac-toe-4.j +++ /dev/null @@ -1 +0,0 @@ -{{u^:(-.@:v)^:_}} diff --git a/Task/Tic-tac-toe/Modula-2/tic-tac-toe.mod2 b/Task/Tic-tac-toe/Modula-2/tic-tac-toe.mod2 new file mode 100644 index 0000000000..1e25cc5bfd --- /dev/null +++ b/Task/Tic-tac-toe/Modula-2/tic-tac-toe.mod2 @@ -0,0 +1,268 @@ +MODULE TicTacToe; + +FROM STextIO IMPORT + WriteLn, WriteString, ReadString, SkipLine; +FROM SWholeIO IMPORT + WriteInt, ReadCard; +FROM RandomNumbers IMPORT + Rnd; + +TYPE + TWinPos = ARRAY [0 .. 7], [0 .. 2] OF INTEGER; (* Winning positions *) + TMover = (Human, Computer, Nobody); + +CONST + WinPos = TWinPos{{0, 1, 2}, {3, 4, 5}, + {6, 7, 8}, {0, 3, 6}, + {1, 4, 7}, {2, 5, 8}, + {0, 4, 8}, {2, 4, 6}}; + +VAR + Board : ARRAY [0 .. 8] OF CHAR; + BestMove, + T : INTEGER; + MyPiece, + HisPiece : CHAR; + CompFirst: BOOLEAN; + Mover : TMover; + Answ : ARRAY [0 .. 1] OF CHAR; + MyWinsCnt, + HisWinsCnt, + DrawsCnt, + MovesCnt, + I : CARDINAL; + +PROCEDURE WriteStringLn(S: ARRAY OF CHAR); +BEGIN + WriteString(S); + WriteLn +END WriteStringLn; + +PROCEDURE SpacesFilled(): BOOLEAN; +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO 8 DO + IF Board[I] = " " THEN + RETURN FALSE; + END + END; + RETURN TRUE +END SpacesFilled; + +PROCEDURE DisplayNumberedBoard; +VAR + I : CARDINAL; + Row: ARRAY [0 .. 10] OF CHAR; +BEGIN + Row := " * | * | * "; + FOR I := 0 TO 8 BY 3 DO + Row[1] := CHR(I + 1 + ORD("0")); + Row[5] := CHR(I + 2 + ORD("0")); + Row[9] := CHR(I + 3 + ORD("0")); + WriteStringLn(Row); + IF I <> 6 THEN + WriteStringLn("---+---+---"); + END; + END +END DisplayNumberedBoard; + +PROCEDURE DisplayPiecedBoard; +VAR + I : CARDINAL; + Row: ARRAY [0 .. 10] OF CHAR; +BEGIN + Row := " * | * | * "; + FOR I := 0 TO 8 BY 3 DO + Row[1] := Board[I]; + Row[5] := Board[I + 1]; + Row[9] := Board[I + 2]; + WriteStringLn(Row); + IF I <> 6 THEN + WriteStringLn("---+---+---"); + END; + END; +END DisplayPiecedBoard; + +PROCEDURE Evaluate(Me: CHAR; Him: CHAR): INTEGER; + (* Recursive algorithm *) +VAR + I : CARDINAL; + SafeMove, + V, + LoseFlag: INTEGER; +BEGIN + IF Win(Me) THEN + RETURN 1 + END; + IF Win(Him) THEN + RETURN -1 + END; + IF SpacesFilled() THEN + RETURN 0 + END; + LoseFlag := 1; + I := 0; + WHILE I <= 8 DO + IF Board[I] = " " THEN + Board[I] := Me; (* Try the move. *) + V := Evaluate(Him, Me); + Board[I] := " "; (* Restore the empty space. *) + IF V = -1 THEN + BestMove := I; + RETURN 1 + END; + IF V = 0 THEN + LoseFlag := 0; + SafeMove := I + END; + END; + I := I + 1; + END; + BestMove := SafeMove; + RETURN -LoseFlag +END Evaluate; + +PROCEDURE Win(Piece: CHAR): BOOLEAN; +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO 7 DO + IF (Board[WinPos[I, 0]] = Piece) AND + (Board[WinPos[I, 1]] = Piece) AND + (Board[WinPos[I, 2]] = Piece) THEN + RETURN TRUE + END; + END; + RETURN FALSE +END Win; + +PROCEDURE ClearBoard; +VAR + I: CARDINAL; +BEGIN + FOR I := 0 TO 8 DO + Board[I] := " " + END; +END ClearBoard; + +PROCEDURE WriteSummary(What: ARRAY OF CHAR; Cnt: CARDINAL); +BEGIN + WriteString(What); + WriteInt(Cnt, 1); + WriteString(" game"); + IF Cnt <> 1 THEN + WriteStringLn("s."); + ELSE + WriteStringLn("."); + END; +END WriteSummary; + +BEGIN + MyWinsCnt := 0; + HisWinsCnt := 0; + DrawsCnt := 0; + CompFirst := TRUE; (* It be reversed, so in fact human goes first *) + WriteLn; + WriteStringLn(" TIC-TAC-TOE"); + WriteLn; + WriteStringLn("In this version, X always goes first."); + WriteStringLn("The board is numbered:"); + REPEAT + CompFirst := NOT CompFirst; (* reverse who goes first *) + MovesCnt := 0; + WriteLn; + DisplayNumberedBoard; + WriteLn; + IF CompFirst THEN + WriteStringLn("I go first."); + ELSE + WriteString("You go first."); + END; + WriteLn; + ClearBoard; + IF CompFirst THEN + MyPiece := "X"; + HisPiece := "O" + ELSE + MyPiece := "O"; + HisPiece := "X" + END; + IF CompFirst THEN + Mover := Computer + ELSE + Mover := Human + END; + WHILE Mover <> Nobody DO + CASE Mover OF + | Computer: + IF MovesCnt = 0 THEN + BestMove := Rnd(9) + ELSIF MovesCnt = 1 THEN + IF Board[4] <> " " THEN + BestMove := Rnd(2) * 6 + Rnd(2) * 2 (* 0, 2, 6, or 8 *) + ELSE + BestMove := 4 + END + ELSE + T := Evaluate(MyPiece, HisPiece) + END; + Board[BestMove] := MyPiece; + MovesCnt := MovesCnt + 1; + WriteLn; + DisplayPiecedBoard; + WriteLn; + IF Win(MyPiece) THEN + MyWinsCnt := MyWinsCnt + 1; + WriteStringLn("I win!"); + Mover := Nobody + ELSIF SpacesFilled() THEN + DrawsCnt := DrawsCnt + 1; + WriteStringLn("It's a draw. Thank you."); + Mover := Nobody + ELSE + Mover := Human + END + | Human: + LOOP + WriteString("Where do you move? "); + ReadCard(I); + SkipLine; + IF (I < 1) OR (I > 9) THEN + WriteString("Illegal! "); + ELSIF Board[I - 1] <> " " THEN + WriteString("Place already occupied. "); + ELSE + EXIT + END + END; + Board[I - 1] := HisPiece; + MovesCnt := MovesCnt + 1; + WriteLn; + DisplayPiecedBoard; + WriteLn; + IF Win(HisPiece) THEN + HisWinsCnt := HisWinsCnt + 1; + WriteStringLn("You beat me! Good game."); + Mover := Nobody + ELSIF SpacesFilled() THEN + DrawsCnt := DrawsCnt + 1; + WriteStringLn("It's a draw. Thank you."); + Mover := Nobody + ELSE + Mover := Computer + END; + END (* CASE *) + END; (* WHILE *) + WriteLn; + WriteString("Another game (y/n)? "); + ReadString(Answ); + SkipLine + UNTIL CAP(Answ[0]) <> "Y"; + WriteLn; + WriteStringLn("Final score:"); + WriteSummary("You won ", MyWinsCnt); + WriteSummary("I won ", MyWinsCnt); + WriteSummary("We tied ", DrawsCnt); + WriteStringLn("See you later!"); +END TicTacToe. diff --git a/Task/Tokenize-a-string/Draco/tokenize-a-string.draco b/Task/Tokenize-a-string/Draco/tokenize-a-string.draco new file mode 100644 index 0000000000..3e3570310a --- /dev/null +++ b/Task/Tokenize-a-string/Draco/tokenize-a-string.draco @@ -0,0 +1,24 @@ +proc tokenize(char sep; *char str; [*]*char parts) word: + word n; + n := 0; + while + parts[n] := str; + while str* /= sep and str* /= '\e' do str := str + 1 od; + n := n+1; + str* /= '\e' + do + str* := '\e'; + str := str + 1 + od; + n +corp + +proc main() void: + word i, count; + [10]*char parts; + count := tokenize(',', "Hello,How,Are,You,Today", parts); + for i from 0 upto count-1 do + write(parts[i], ". ") + od; + writeln() +corp diff --git a/Task/Topological-sort/FreeBASIC/topological-sort-1.basic b/Task/Topological-sort/FreeBASIC/topological-sort-1.basic new file mode 100644 index 0000000000..ab9fb12fd5 --- /dev/null +++ b/Task/Topological-sort/FreeBASIC/topological-sort-1.basic @@ -0,0 +1,150 @@ +Type Pair + primero As Integer + segundo As Integer +End Type + +Type Graph + vertices(14) As String + numVertices As Integer + proximos(14, 14) As Boolean + + Declare Constructor(s As String, edges() As Pair) + Declare Function hasDependency(r As Integer, todo() As Integer, todoCount As Integer) As Boolean + Declare Function topoSort() As String +End Type + +Function splitString(text As String, delimiter As String, Byref count As Integer) As String Ptr + Dim As Integer numTokens = 0 + Dim As String tmp = text + Dim As Long posic + + ' Count delimiters + Do + posic = Instr(tmp, delimiter) + If posic = 0 Then Exit Do + numTokens += 1 + tmp = Mid(tmp, posic + Len(delimiter)) + Loop + numTokens += 1 + + ' Allocate array + count = numTokens + Dim As String Ptr result = Callocate((numTokens) * Sizeof(String)) + + ' Split string + tmp = text + numTokens = 0 + Do + posic = Instr(tmp, delimiter) + If posic = 0 Then + result[numTokens] = tmp + Exit Do + End If + result[numTokens] = Left(tmp, posic - 1) + tmp = Mid(tmp, posic + Len(delimiter)) + numTokens += 1 + Loop + + Return result +End Function + +Constructor Graph(s As String, edges() As Pair) + Dim As Integer i, tokenCount + Dim As String Ptr tokens = splitString(s, ", ", tokenCount) + numVertices = tokenCount + For i = 0 To numVertices - 1 + vertices(i) = tokens[i] + Next + Deallocate(tokens) + + ' Initialize proximos matrix + For i = 0 To Ubound(edges) + proximos(edges(i).primero, edges(i).segundo) = True + Next +End Constructor + +Function Graph.hasDependency(r As Integer, todo() As Integer, todoCount As Integer) As Boolean + For i As Integer = 0 To todoCount - 1 + If proximos(r, todo(i)) Then Return True + Next + Return False +End Function + +Function Graph.topoSort() As String + Dim As String result = "" + Dim As Integer todoCount, i, j + Dim As Integer todo(numVertices) + + todoCount = numVertices + ' Initialize todo list + For i = 0 To numVertices - 1 + todo(i) = i + Next + + While todoCount > 0 + i = 0 + Dim As Boolean found = False + + While i < todoCount + If Not hasDependency(todo(i), todo(), todoCount) Then + ' Add to result + If Len(result) > 0 Then result &= ", " + result &= vertices(todo(i)) + + ' Remove from todo + For j = i To todoCount - 2 + todo(j) = todo(j + 1) + Next + todoCount -= 1 + found = True + Exit While + End If + i += 1 + Wend + + If Not found Then Return "Graph has cycles" + Wend + + Return "[" & result & "]" +End Function + +' Main program +Dim As String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " & _ +"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys" + +Dim As Pair deps(33) +' Initialize deps array +deps(0) = Type(2, 0) : deps(1) = Type(2, 14) +deps(2) = Type(2, 13) : deps(3) = Type(2, 4) +deps(4) = Type(2, 3) : deps(5) = Type(2, 12) +deps(6) = Type(2, 1) : deps(7) = Type(3, 1) +deps(8) = Type(3, 10) : deps(9) = Type(3, 11) +deps(10) = Type(4, 1) : deps(11) = Type(4, 10) +deps(12) = Type(5, 0) : deps(13) = Type(5, 14) +deps(14) = Type(5, 10) : deps(15) = Type(5, 4) +deps(16) = Type(5, 3) : deps(17) = Type(5, 1) +deps(18) = Type(5, 11) : deps(19) = Type(6, 1) +deps(20) = Type(6, 3) : deps(21) = Type(6, 10) +deps(22) = Type(6, 11) : deps(23) = Type(7, 1) +deps(24) = Type(7, 10) : deps(25) = Type(8, 1) +deps(26) = Type(8, 10) : deps(27) = Type(9, 1) +deps(28) = Type(9, 10) : deps(29) = Type(10, 1) +deps(30) = Type(11, 1) : deps(31) = Type(12, 0) +deps(32) = Type(12, 1) : deps(33) = Type(13, 1) + +Dim As Graph g = Graph(s, deps()) +Print "Topologically sorted order:" +Print g.topoSort() +Print + +' Add new dependency +For i As Integer = 33 To 11 Step -1 + deps(i) = deps(i-1) +Next +deps(10) = Type(3, 6) + +Dim As Graph g2 = Graph(s, deps()) +Print "Following the addition of dw04 to the dependencies of dw01:" +Print g2.topoSort() + +Sleep diff --git a/Task/Topological-sort/FreeBASIC/topological-sort-2.basic b/Task/Topological-sort/FreeBASIC/topological-sort-2.basic new file mode 100644 index 0000000000..3a7c952646 --- /dev/null +++ b/Task/Topological-sort/FreeBASIC/topological-sort-2.basic @@ -0,0 +1,168 @@ +Const NULL As Any Ptr = 0 + +Type item_t + As String nombre + As Integer Ptr deps + As Integer n_deps + As Integer idx + As Integer depth +End Type + +Dim Shared As String entrada +entrada = "des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee" & Chr(10) & _ +"dw01 ieee dw01 dware gtech" & Chr(10) & _ +"dw02 ieee dw02 dware" & Chr(10) & _ +"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech" & Chr(10) & _ +"dw04 dw04 ieee dw01 dware gtech" & Chr(10) & _ +"dw05 dw05 ieee dware" & Chr(10) & _ +"dw06 dw06 ieee dware" & Chr(10) & _ +"dw07 ieee dware" & Chr(10) & _ +"dware ieee dware" & Chr(10) & _ +"gtech ieee gtech" & Chr(10) & _ +"ramlib std ieee" & Chr(10) & _ +"std_cell_lib ieee std_cell_lib" & Chr(10) & _ +"synopsys" & Chr(10) & _ +"cycle_11 cycle_12" & Chr(10) & _ +"cycle_12 cycle_11" & Chr(10) & _ +"cycle_21 dw01 cycle_22 dw02 dw03" & Chr(10) & _ +"cycle_22 cycle_21 dw01 dw04" & Chr(10) + +Function get_item(list() As item_t, Byref longi As Integer, nombre As String) As Integer + Dim As Integer i + For i = 0 To longi - 1 + If list(i).nombre = nombre Then Return i + Next + + longi += 1 + Redim Preserve list(longi - 1) + i = longi - 1 + list(i).idx = i + list(i).nombre = nombre + list(i).n_deps = 0 + list(i).deps = NULL + list(i).depth = 0 + Return i +End Function + +Sub add_dep(Byref it As item_t, i As Integer) + If it.idx = i Then Return + it.deps = Reallocate(it.deps, (it.n_deps + 1) * Sizeof(Integer)) + it.deps[it.n_deps] = i + it.n_deps += 1 +End Sub + +Function parse_input(ret() As item_t) As Integer + Dim As Integer i, parent, idx, n_items, posic, nextpos + Dim As item_t list() + Dim As String s, linea, word + + n_items = 0 + s = entrada + + Do While Len(s) > 0 + posic = Instr(s, Chr(10)) + If posic = 0 Then + linea = s + s = "" + Else + linea = Left(s, posic - 1) + s = Mid(s, posic + 1) + End If + + i = 0 + While Len(linea) > 0 + linea = Trim(linea) + If Len(linea) = 0 Then Exit While + + posic = Instr(linea, " ") + If posic = 0 Then + word = linea + linea = "" + Else + word = Left(linea, posic - 1) + linea = Mid(linea, posic + 1) + End If + + If Len(word) > 0 Then + idx = get_item(list(), n_items, word) + + If i = 0 Then + parent = idx + Else + add_dep(list(parent), idx) + End If + i += 1 + End If + Wend + Loop + + Redim ret(n_items - 1) + For i = 0 To n_items - 1 + ret(i) = list(i) + Next + + Return n_items +End Function + +Function get_depth(base_() As item_t, idx As Integer, bad As Integer) As Integer + Dim As Integer max = 1, i, t + + If base_(idx).n_deps = 0 Then + base_(idx).depth = 1 + Return 1 + End If + + If base_(idx).depth < 0 Then Return base_(idx).depth + If base_(idx).depth > 0 Then Return base_(idx).depth + + base_(idx).depth = bad + For i = 0 To base_(idx).n_deps - 1 + t = get_depth(base_(), base_(idx).deps[i], bad) + If t < 0 Then + max = t + Exit For + End If + If max < t + 1 Then max = t + 1 + Next + + base_(idx).depth = max + Return max +End Function + +' Main program +Dim As Integer i, j, n, bad = -1, max = -1000000, min = 1000000 +Dim As item_t items() + +n = parse_input(items()) + +For i = 0 To n - 1 + If items(i).depth = 0 And get_depth(items(), i, bad) < 0 Then bad -= 1 +Next + +For i = 0 To n - 1 + If items(i).depth > max Then max = items(i).depth + If items(i).depth < min Then min = items(i).depth +Next + +Print "Compile order:" +For i = min To max + If i = 0 Then Continue For + + If i < 0 Then + Print " [unorderable]"; + Else + Print i; ":"; + End If + + For j = 0 To n - 1 + If items(j).depth = i Then Print " "; items(j).nombre; + Next + Print +Next + +' Clean up memory +For i = 0 To n - 1 + If items(i).deps <> NULL Then Deallocate(items(i).deps) +Next + +Sleep diff --git a/Task/Totient-function/C/totient-function.c b/Task/Totient-function/C/totient-function.c index 30c486665e..cb00793627 100644 --- a/Task/Totient-function/C/totient-function.c +++ b/Task/Totient-function/C/totient-function.c @@ -1,51 +1,52 @@ -/*Abhishek Ghosh, 7th December 2018*/ +#include -#include - -int totient(int n){ - int tot = n,i; +int +totient(int n) +{ + int result = n; - for(i=2;i*i<=n;i+=2){ - if(n%i==0){ - while(n%i==0) - n/=i; - tot-=tot/i; + for (int i=2; i*i <= n; i+=2) { + if (n % i == 0) { + while (n % i == 0) + n /= i; + result -= result / i; } - if(i==2) - i=1; + if (i == 2) + i = 1; } - if(n>1) - tot-=tot/n; - - return tot; + if (n > 1) + result -= result / n; + return result; } -int main() +int +main(void) { - int count = 0,n,tot; + int count, n, tot; - printf(" n %c prime",237); - printf("\n---------------\n"); - - for(n=1;n<=25;n++){ + printf(" n phi prime\n"); + printf("--------------\n"); + + count = 0; + for (n = 1; n <= 25; n++) { tot = totient(n); - if(n-1 == tot) + if (tot == n - 1) count++; - printf("%2d %2d %s\n", n, tot, n-1 == tot?"True":"False"); + printf("%2d %2d %s\n", n, tot, tot == (n-1) ? "true" : "false"); } - - printf("\nNumber of primes up to %6d =%4d\n", 25,count); - - for(n = 26; n <= 100000; n++){ + + printf("\n"); + + for (n = 26; n <= 100000; n++) { tot = totient(n); - if(tot == n-1) + if (tot == n-1) count++; - if(n == 100 || n == 1000 || n%10000 == 0){ + if (n == 100 || n == 1000 || n == 10000) { printf("\nNumber of primes up to %6d = %4d\n", n, count); } } diff --git a/Task/Totient-function/EasyLang/totient-function.easy b/Task/Totient-function/EasyLang/totient-function.easy index 89d13455e1..56f5cd9c90 100644 --- a/Task/Totient-function/EasyLang/totient-function.easy +++ b/Task/Totient-function/EasyLang/totient-function.easy @@ -1,21 +1,15 @@ -func totient n . +fastfunc totient n . tot = n i = 2 while i <= sqrt n if n mod i = 0 - while n mod i = 0 - n = n div i - . + while n mod i = 0 : n = n div i tot -= tot div i . - if i = 2 - i = 1 - . + if i = 2 : i = 1 i += 2 . - if n > 1 - tot -= tot div n - . + if n > 1 : tot -= tot div n return tot . numfmt 0 3 @@ -23,17 +17,13 @@ print " N Prim Phi" for n = 1 to 25 tot = totient n x$ = " " - if n - 1 = tot - x$ = " x " - . + if n - 1 = tot : x$ = " x " print n & x$ & tot . print "" for n = 1 to 100000 tot = totient n - if n - 1 = tot - cnt += 1 - . + if n - 1 = tot : cnt += 1 if n = 100 or n = 1000 or n = 10000 or n = 100000 print n & " - " & cnt & " primes" . diff --git a/Task/Totient-function/PascalABC.NET/totient-function.pas b/Task/Totient-function/PascalABC.NET/totient-function.pas new file mode 100644 index 0000000000..ceb9bc55f1 --- /dev/null +++ b/Task/Totient-function/PascalABC.NET/totient-function.pas @@ -0,0 +1,17 @@ +uses school; + +function totient(n: int64) := (1..n).Select(k -> (if gcd(n, k) = 1 then 1 else 0)).Sum; + +function is_prime(n: int64) := totient(n) = n - 1; + +begin + foreach var n in 1..25 do + writeln('φ(', n, ') = ', totient(n), if is_prime(n) then ', is prime' else ''); + var count := 0; + foreach var n in 1..100_000 do + begin + count += if is_prime(n) then 1 else 0; + if n in |100, 1000, 10_000, 100_000| then + writeln('Primes up to ', n, ': ', count); + end; +end. diff --git a/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi-2.f b/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi-2.f index 59f3275359..c586e17ac8 100644 --- a/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi-2.f +++ b/Task/Towers-of-Hanoi/Fortran/towers-of-hanoi-2.f @@ -1,19 +1,140 @@ -PROGRAM TOWER2 +! This is a nice alternative to the usual recursive Hanoi solutions. It runs about 10x +! faster than a well crafted recursive solution for 30 disks. + SUBROUTINE olives(Numdisk) +!> This is an implementation of "Olive's Algorithm" +!! The “simpler” algorithm where the smallest disk moves circularly every second +!! move is attributed to Raoul Olive, the nephew of Edouard Lucas, the inventor of the +!! Towers of Hanoi puzzle. We alternately move disk one in it's established direction +!! Then we move the one of the 'non-one' disks, depending on the legality of the move. +!! In this implementation, I use a small array of the stack entities. This allows us +!! to easily find the stack where the disk to be moved resides. + USE data_defs + IMPLICIT NONE +! +! PARAMETER definitions +! + INTEGER(int32) , PARAMETER :: bigm = maxpos*3 +! +! Dummy arguments +! + INTEGER(int32) :: Numdisk + INTENT (IN) Numdisk +! +! Local variables +! + TYPE(stack) , POINTER :: a , b , c , on_now !< on_now is where disk 1 is + TYPE(stack) , TARGET , DIMENSION(3) :: abc !< The three stack are put in an array for identification i.e. abc(1)%stack_id = 1 + INTEGER :: direction !< Direction of disk1, negative is counter clockwise, positive = clockwise + INTEGER(int32) :: i , j - CALL Move(4, 1, 2, 3) + DATA(abc(i)%height , i = 1 , 3)/3*0/ + DATA(abc(i)%stack_id , i = 1 , 3)/1 , 2 , 3/ + DATA((abc(i)%disks(j),i = 1,3) , j = 1 , maxpos)/bigm*0/ +! Code starts here +! +! Move numdisks from A to C using B as intermediate +! + a => abc(1) + b => abc(2) + c => abc(3) + on_now => a !< Point to the starting pole + a%height = Numdisk !< A = the starting pole +! + last_move = -1 +! + a%disks = [(Numdisk + 1 - j, j = 1, Numdisk)] -CONTAINS + IF( btest(Numdisk,0) )THEN !< First move rule always involves disk 1, test odd/even for first move + CALL move(a , c) + direction = -1 ! Counter clockwise + on_now => c + ELSE + CALL move(a , b) + direction = 1 ! Clockwise + on_now => b + END IF +! + DO WHILE ( c%height/=Numdisk ) +! + SELECT CASE(on_now%stack_id) !< Depending where disk one is, make a legal move + CASE(1) !< One is on stack 1 i.e. a so we can only make a legal move in between b and c + IF( legal(b,c) )THEN + CALL move(b , c) + ELSE + CALL move(c , b) + END IF + CASE(2) ! Disk one on stack 2 i.e. "b" + IF( legal(a,c) )THEN + CALL move(a , c) + ELSE + CALL move(c , a) + END IF + CASE(3) ! Disk one on stack 3 i.e. "c" + IF( legal(a,b) )THEN + CALL move(a , b) + ELSE + CALL move(b , a) + END IF + END SELECT - RECURSIVE SUBROUTINE Move(ndisks, from, via, to) - INTEGER, INTENT (IN) :: ndisks, from, via, to +!< Now move disk 1 in the direction it was heading + i = on_now%stack_id + direction !< Increment the stack a->b->c->a or vice versa Decrement the stack c->b->a->c +!< Note that here we use the stack_id to figure out which disk destination to use. As we increment or decrement the stack counter +!! we reset it to the correct disk when it is outside the 1..3 range. It is set so as to maintain the correct disk direction. + SELECT CASE(i) + CASE(0) + i = 3 + CASE(1:3) + CASE(4) + i = 1 + END SELECT - IF (ndisks > 1) THEN - CALL Move(ndisks-1, from, to, via) - WRITE(*, "(A,I1,A,I1,A,I1)") "Move disk ", ndisks, " from pole ", from, " to pole ", to - Call Move(ndisks-1,via,from,to) - ELSE - WRITE(*, "(A,I1,A,I1,A,I1)") "Move disk ", ndisks, " from pole ", from, " to pole ", to - END IF - END SUBROUTINE Move + CALL move(on_now , abc(i)) + on_now => abc(i) + END DO + PRINT '(*(i0,2x))' , (c%disks(i) , i = 1 , Numdisk) ! Print final disk configuration + on_now => null() +! + RETURN + END SUBROUTINE olives + SUBROUTINE Move(Donor , Receiver) + USE Data_defs + IMPLICIT NONE -END PROGRAM TOWER2 +! Dummy arguments +! + TYPE(stack) :: Donor , Receiver + INTENT (INOUT) Donor , Receiver +! Code starts here +!$GCC$ attributes INLINE :: MOVE +! +! Code starts here + last_move = Receiver%Stack_id + Receiver%Height = Receiver%Height + 1 ! make slot in receiver + Receiver%Disks(Receiver%Height) = Donor%Disks(Donor%Height) !Move the disk + Donor%Disks(Donor%Height) = 0 ! Black it out + Donor%Height = Donor%Height - 1 ! Decrement the donor height + RETURN + END SUBROUTINE Move + Module data_defs + IMPLICIT NONE +! +! PARAMETER definitions +! + INTEGER , PARAMETER :: int32 = selected_int_kind(8) , & + & int64 = selected_int_kind(16) + + INTEGER(int32) , PARAMETER :: maxpos = 40 ! Maximum possible disks without a huge blowout +! +! Derived Type definitions +! + TYPE :: stack + INTEGER(int32) :: stack_id + INTEGER(int32) :: height + INTEGER(int32) , DIMENSION(maxpos) :: disks + END TYPE stack +! +! Local variables +! + INTEGER :: last_move ! Holds the destination of the last move + end module data_defs diff --git a/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c b/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c index 0d6b84598b..6db5923277 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c +++ b/Task/Trabb-Pardo-Knuth-algorithm/C/trabb-pardo-knuth-algorithm.c @@ -1,37 +1,34 @@ -#include -#include +#include +#include -int -main () +double f(double x) +{ + return sqrt(fabs(x)) + 5 * pow(x, 3); +} + +int main() { double inputs[11], check = 400, result; int i; - printf ("\nPlease enter 11 numbers :"); - + printf ("\nPlease enter 11 numbers: "); for (i = 0; i < 11; i++) - { - scanf ("%lf", &inputs[i]); - } - - printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); - + { + scanf ("%lf", &inputs[i]); + } + printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs:"); for (i = 10; i >= 0; i--) + { + result = f(inputs[i]); + printf ("\nf(%lf) = ", inputs[i]); + if (result > check) { - result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3); - - printf ("\nf(%lf) = "); - - if (result > check) - { - printf ("Overflow!"); - } - - else - { - printf ("%lf", result); - } + printf ("Overflow!"); } - + else + { + printf ("%lf", result); + } + } return 0; } diff --git a/Task/Tree-datastructures/M2000-Interpreter/tree-datastructures.m2000 b/Task/Tree-datastructures/M2000-Interpreter/tree-datastructures.m2000 new file mode 100644 index 0000000000..f2716ec3bf --- /dev/null +++ b/Task/Tree-datastructures/M2000-Interpreter/tree-datastructures.m2000 @@ -0,0 +1,88 @@ +module Tree_datastructures (a$){ + terminal=(,) + document b$, all$=a$ + report a$ + nl$={ + } + tree=@MakeTree(a$) + traverseTree(tree) + report b$ + all$=b$ + clear b$ + TraverseTreeIndent(tree) + report b$ + all$=b$ + print b$=a$ + all$=(b$=a$)+nl$ + clipboard all$ + end + sub TraverseTree(t as array, Level=1) + b$=Level+" "+t#val$(0)+nl$ + local i + for i=1 to len(t)-1 + if t#val(i) is terminal else TraverseTree(t#val(i), Level+1) + next + end sub + sub TraverseTreeIndent(t as array, Level=0) + b$=string$("....", Level) +t#val$(0)+nl$ + local i + for i=1 to len(t)-1 + if t#val(i) is terminal else TraverseTreeIndent(t#val(i), Level+1) + next + end sub + function MakeTree(a$) + local a$(), c$ + a$()=piece$(a$, nl$) + local child=terminal, tree=(a$(0),terminal) + local Level=2, i, j + flush + for i=1 to len(a$())-1 + if len(a$(i))=0 then continue + for j=1 to len(a$(i)) div 2 + if left$(a$(i), j*4)<>string$(".", j*4) then + c$=mid$(a$(i), (j-1)*4+1) + exit for + end if + next j + while j50 Degrees to Radians +* 23.12.2024 WP made Methods public **********************************************************************/ -.local~my.rxm=.rxm~new(16,"D") +.local~my.rxm=.rxm~new(50,"R") ::Class rxm Public -::Method init +::Method init Public Expose precision type Use Arg precision=(digits()),type='D' @@ -40,13 +42,14 @@ ::attribute type get -::Method arccos +::Method arccos Public /*********************************************************************** * Return arccos(x,precision,type) -- with specified precision * arccos(x) = pi/2 - arcsin(x) ***********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec If x=1 Then @@ -68,13 +71,14 @@ Numeric Digits xprec Return (r+0) -::Method arcsin +::Method arcsin Public /*********************************************************************** * Return arcsin(x,precision,type) -- with specified precision * arcsin(x) = x+(x**3)*1/2*3+(x**5)*1*3/2*4*5+(x**7)*1*3*5/2*4*6*7+... ***********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec sign=sign(x) @@ -131,7 +135,7 @@ Numeric Digits xprec Return sign*(r+0) -::Method arctan +::Method arctan Public /*********************************************************************** * Return arctan(x,precision,type) -- with specified precision * x=0 -> arctan(x) = 0 @@ -144,6 +148,7 @@ ***********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec Select @@ -171,7 +176,7 @@ Numeric Digits xprec Return (r+0) -::Method arsinh +::Method arsinh Public /*********************************************************************** * Return arsinh(x,precision,type) -- with specified precision * arsinh(x) = ln(x+sqrt(x**2+1)) @@ -185,13 +190,14 @@ Numeric Digits xprec Return (r+0) -::Method cos +::Method cos Public /* REXX ************************************************************* * Return cos(x,precision,type) -- with the specified precision * cos(x)=sin(x+pi/2) ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec Select @@ -203,7 +209,7 @@ Numeric Digits xprec Return (r+0) -::Method cosh +::Method cosh Public /* REXX **************************************************************** * Return cosh(x,precision,type) -- with specified precision * cosh(x) = 1+(x**2/2!)+(x**4/4!)+(x**6/6!)+-... @@ -224,13 +230,14 @@ Numeric Digits xprec Return (r+0) -::Method cotan +::Method cotan Public /* REXX ************************************************************* * Return cotan(x,precision,type) -- with the specified precision * cot(x)=cos(x)/sin(x) ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec s=self~sin(x,iprec,xtype) @@ -241,7 +248,7 @@ Numeric Digits xprec Return (r+0) -::Method exp +::Method exp Public /*********************************************************************** * exp(x,precision) returns e**x -- with specified precision * exp(x,precision,base) returns base**x -- with specified precision @@ -288,7 +295,7 @@ Numeric Digits xprec Return (r+0) -::Method log +::Method log Public /*********************************************************************** * log(x,precision) -- returns ln(x) with specified precision * log(x,precision,base) -- returns blog(x) with specified precision @@ -328,7 +335,7 @@ End Return r -::Method ln2p +::Method ln2p Public Parse Arg p Numeric Digits p+10 If p<=1000 Then @@ -344,8 +351,13 @@ ln=newln End -::Method LN2 - +::Method LN2 Public + V = '' + V = V || 0.69314718055994530941723212145817656807 + V = V || 5500134360255254120680009493393621969694 + V = V || 7156058633269964186875420014810205706857 + V = V || 3368552023575813055703267075163507596193 + V = V || 0727570828371435190307038623891673471123350 v='' v=v||0.69314718055994530941723212145817656807 v=v||5500134360255254120680009493393621969694 @@ -375,7 +387,7 @@ v=v||231467232172053401649256872747782344535348 return V -::Method log10 +::Method log10 Public /*********************************************************************** * Return log10(x,prec) specified precision ***********************************************************************/ @@ -386,7 +398,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (r+0) -::Method pi +::Method pi Public /* REXX ************************************************************* * Return pi with the specified precision ********************************************************************/ @@ -432,7 +444,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (p+0) -::Method power +::Method power Public /*********************************************************************** * power(base,exponent,precision) returns base**exponent * -- with specified precision @@ -449,7 +461,7 @@ v=v||231467232172053401649256872747782344535348 End Else Do /* Exponent is not an integer */ -- Say 'for a negative base ('||b')', --- 'exponent ('c') must be an integer' + 'exponent ('c') must be an integer' Return 'nan' /* Return not a number */ End End @@ -463,7 +475,7 @@ v=v||231467232172053401649256872747782344535348 Return r Return rsign*r -::Method sqrt +::Method sqrt Public /* REXX ************************************************************* * Return sqrt(x,precision) -- with the specified precision ********************************************************************/ @@ -483,7 +495,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (r+0) -::Method sin +::Method sin Public /* REXX ************************************************************* * Return sin(x,precision,type) -- with the specified precision * xtype = 'R' (radians, default) 'D' (degrees) 'G' (grades) @@ -491,7 +503,8 @@ v=v||231467232172053401649256872747782344535348 ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) - iprec=xprec+10 /* internal precision */ + xtype=translate(xtype) + iprec=xprec+20 /* internal precision */ Numeric Digits iprec /* first use pi constant or compute it if necessary */ pi=self~pi(iprec) @@ -539,7 +552,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return sign*(r+0) -::Method sinh +::Method sinh Public /* REXX **************************************************************** * Return sinh(x,precision) -- with specified precision * sinh(x) = x+(x**3/3!)+(x**5/5!)+(x**7/7!)+-... @@ -561,13 +574,14 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (r+0) -::Method tan +::Method tan Public /* REXX ************************************************************* * Return tan(x,precision,type) -- with the specified precision * tan(x)=sin(x)/cos(x) ********************************************************************/ Expose precision type Use Strict Arg x,xprec=(precision),xtype=(type) + xtype=translate(xtype) iprec=xprec+10 Numeric Digits iprec s=self~sin(x,iprec,xtype) @@ -578,7 +592,7 @@ v=v||231467232172053401649256872747782344535348 Numeric Digits xprec Return (t+0) -::Method tanh +::Method tanh Public /*********************************************************************** * Return tanh(x,precision) -- with specified precision * tanh(x) = sinh(x)/cosh(x) @@ -593,6 +607,7 @@ v=v||231467232172053401649256872747782344535348 ::routine rxmarccos public Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) + xtype=translate(xtype) If datatype(x,'NUM')=0 Then Do -- Say 'Argument 1 must be a number' @@ -616,6 +631,7 @@ v=v||231467232172053401649256872747782344535348 ::routine rxmarcsin public Use Strict Arg x,xprec=(.my.rxm~precision),xtype=(.my.rxm~type) + xtype=translate(xtype) If datatype(x,'NUM')=0 Then Do -- Say 'Argument 1 must be a number' @@ -709,7 +725,6 @@ v=v||231467232172053401649256872747782344535348 -- Say 'Argument 3 must be R, D, or G' Raise Syntax 88.907 array(3,'R, D, or G',xtype) End - return .my.rxm~cos(x,xprec,xtype) ::routine rxmcosh public diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx similarity index 100% rename from Task/Trigonometric-functions/REXX/trigonometric-functions.rexx rename to Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx new file mode 100644 index 0000000000..98903eb4fc --- /dev/null +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx @@ -0,0 +1,42 @@ +include Settings + +say version; say 'Trigonometric functions'; say +s = Copies('-',77); w = 18 +call Trigo +call Arcus1 +call Arcus2 +exit + +Trigo: +say s +say 'Deg' Left('Rad',w) Left('Sin(Rad)',w) Left('Cos(Rad)',w) Left('Tan(Rad)',w) +say s +do a = 0 by 5 to 90 + b = Rad(a) + say Left(a,3) Left(b/1,w) Left(Sin(b)/1,w) Left(Cos(b)/1,w) Left(Tan(b)/1,w) +end +say s +return + +Arcus1: +say Left('Arg',4) Left('Arcsin(Arg)',w) Left('Arccos(Arg)',w) Left('Arctan(Arg)',w) +say s +do b = -1 by 0.1 to 1 + say Left(b,4) Left(Arcsin(b)/1,w) Left(Arccos(b)/1,w) Left(Arctan(b)/1,w) +end +say s +return + +Arcus2: +say 'Deg' Left('Rad',w) Left('Arcsin(Sin(Rad))',w) Left('Arccos(Cos(Rad))',w) Left('Arctan(Tan(Rad))',w) +say s +do a = 0 by 5 to 90 + b = Rad(a) + say Left(a,3) Left(b/1,w) Left(Arcsin(Sin(b))/1,w) Left(Arccos(Cos(b))/1,w) Left(Arctan(Tan(b))/1,w) +end +say s +return + +include Functions +include Constants +include Abend diff --git a/Task/Trigonometric-functions/Uiua/trigonometric-functions.uiua b/Task/Trigonometric-functions/Uiua/trigonometric-functions.uiua new file mode 100644 index 0000000000..5dd41768b4 --- /dev/null +++ b/Task/Trigonometric-functions/Uiua/trigonometric-functions.uiua @@ -0,0 +1,20 @@ +a ← ÷4π +b ← ÷π ×180 a +Cos ← ∿+η +Tangent ← ÷∩∿+η. +Arcsin ← °∿ +Arccos ← -:η°∿ +"Radians:" +∿ a # sine +Cos a +Tangent a +Arcsin ∿ a +Arccos Cos a +∠ Tangent a 1 +"Degrees:" +∿ ×π ÷180 b +Cos ×π ÷180 b +Tangent ×π ÷180 b +Arcsin∿ ×π ÷180 b +Arccos Cos ×π ÷180 b +∠ Tangent ×π ÷180 b 1 diff --git a/Task/Truncatable-primes/Raku/truncatable-primes.raku b/Task/Truncatable-primes/Raku/truncatable-primes.raku index 888a7cd3bf..2b7c62ed02 100644 --- a/Task/Truncatable-primes/Raku/truncatable-primes.raku +++ b/Task/Truncatable-primes/Raku/truncatable-primes.raku @@ -1,10 +1,14 @@ -constant ltp = $[2, 3, 5, 7], -> @ltp { - $[ grep { .&is-prime }, ((1..9) X~ @ltp) ] +constant ltp = [2, 3, 5, 7], { + last if .not; + [ ((1..9) X~ @$_).grep: &is-prime ] } ... *; -constant rtp = $[2, 3, 5, 7], -> @rtp { - $[ grep { .&is-prime }, (@rtp X~ (1..9)) ] +constant rtp = [2, 3, 5, 7], { + last if .not; + [ (@$_ X~ (1,3,7,9)).grep: &is-prime ] } ... *; -say "Highest ltp = ", ltp[5][*-1]; -say "Highest rtp = ", rtp[5][*-1]; +say "Largest ltp < 1e6 = ", ltp[5][*-1]; +say "Largest rtp < 1e6 = ", rtp[5][*-1]; +say "Largest possible ltp = ", ltp.eager.flat.tail; +say "Largest possible rtp = ", rtp.eager.flat.tail; diff --git a/Task/Truth-table/FreeBASIC/truth-table.basic b/Task/Truth-table/FreeBASIC/truth-table.basic new file mode 100644 index 0000000000..884134aa3e --- /dev/null +++ b/Task/Truth-table/FreeBASIC/truth-table.basic @@ -0,0 +1,219 @@ +Dim Shared As Integer Variables(26) +Dim Shared As Integer ExprStack(255) +Dim Shared As Integer OpStack(255) +Dim Shared As Integer OpPrecedence(6) +Dim Shared As String Operators(6) +Dim Shared As String VarList +Dim Shared As Integer exprPos, stackPos, idx, combos + +' Initialize operator data with aliases +Operators(1) = "!" : OpPrecedence(1) = 4 ' NOT (both ~ and !) +Operators(2) = "&" : OpPrecedence(2) = 3 ' AND +Operators(3) = "|" : OpPrecedence(3) = 2 ' OR +Operators(4) = "^" : OpPrecedence(4) = 2 ' XOR +Operators(5) = "=>" : OpPrecedence(5) = 1 ' IMPLIES +Operators(6) = "<=" : OpPrecedence(6) = 1 ' CONVERSE + +Sub EvaluateExpression() + Dim As Integer typeFlag, value + stackPos = 0 + + For idx = 0 To exprPos-1 + typeFlag = ExprStack(idx) And 224 + value = ExprStack(idx) And 31 + + Select Case typeFlag + Case 0 ' Operator + Select Case value + Case 1 ' NOT + If stackPos < 1 Then Print "Missing operand": Exit Sub + OpStack(stackPos-1) = 1 - OpStack(stackPos-1) + Case 2 ' AND + If stackPos < 2 Then Print "Missing operand": Exit Sub + stackPos -= 1 + OpStack(stackPos-1) = OpStack(stackPos-1) And OpStack(stackPos) + Case 3 ' OR + If stackPos < 2 Then Print "Missing operand": Exit Sub + stackPos -= 1 + OpStack(stackPos-1) = OpStack(stackPos-1) Or OpStack(stackPos) + Case 4 ' XOR + If stackPos < 2 Then Print "Missing operand": Exit Sub + stackPos -= 1 + OpStack(stackPos-1) = OpStack(stackPos-1) Xor OpStack(stackPos) + Case 5 ' IMPLIES + If stackPos < 2 Then Print "Missing operand": Exit Sub + stackPos -= 1 + OpStack(stackPos-1) = Iif(OpStack(stackPos-1), OpStack(stackPos), -1) + Case 6 ' CONVERSE + If stackPos < 2 Then Print "Missing operand": Exit Sub + stackPos -= 1 + OpStack(stackPos-1) = Iif(OpStack(stackPos), OpStack(stackPos-1), -1) + End Select + Case 32 ' Constant + OpStack(stackPos) = -value + stackPos += 1 + Case 64 ' Variable + OpStack(stackPos) = Variables(Instr(VarList, Chr(value + 65))) + stackPos += 1 + End Select + Next + + If stackPos <> 1 Then Print "Missing operator": Exit Sub +End Sub + +Sub ProcessRemainingOperators() + While stackPos > 0 + stackPos -= 1 + Select Case OpStack(stackPos) + Case 97 + Print "Error: missing )!": Exit Sub + Case Else + ExprStack(exprPos) = OpStack(stackPos) + exprPos += 1 + End Select + Wend +End Sub + +Sub BuildVariableList() + VarList = "" + For idx = 0 To exprPos-1 + If (ExprStack(idx) And 224) = 64 Then + Dim As String tmpChar = Chr(ExprStack(idx) + 1) + If Instr(VarList, tmpChar) = 0 Then VarList &= tmpChar + End If + Next +End Sub + +Sub PrintRow() + For idx = 1 To Len(VarList) + Print Iif(Variables(idx), "T ", "F "); + Next + Print "| "; + + EvaluateExpression() + Print Iif(OpStack(0), "T", "F") +End Sub + +Sub GenerateNextCombination() + idx = 1 + While idx <= Len(VarList) + Select Case Variables(idx) + Case 1 + Variables(idx) = 0 + idx += 1 + Case 0 + Variables(idx) = 1 + Exit While + End Select + Wend +End Sub + +Sub PrintTruthTable(originalExpr As String) + For idx = 1 To Len(VarList) + Print Mid(VarList, idx, 1); " "; + Next + Print "| "; originalExpr + Print String(2 + 2*Len(VarList) + Len(originalExpr), "-") + + For combos = 1 To 2^Len(VarList) + PrintRow() + GenerateNextCombination() + Next +End Sub + + +'Main program +Print "Boolean expression evaluator" +Print String(28, "-") +Print "Accepts single-character variables (a-z, A-Z), postfix or infix." +Print "Operators: ! (not), & (and), | (or), ^ (xor), => (implies), <= (converse)" +Print "Optionally seperated by whitespace. Just enter nothing to quit." + +Dim As String inputExpr, cleanExpr, originalExpr, remainExpr, currentChar +Dim As Integer asciiVal +Dim As Boolean operatorFound + +Do + For idx = 1 To 26: Variables(idx) = 0: Next + + Print : Input "Boolean expression: ", inputExpr + If inputExpr = "" Then Exit Do + + cleanExpr = "" + exprPos = 0 + stackPos = 0 + + ' Remove spaces + For idx = 1 To Len(inputExpr) + currentChar = Mid(inputExpr, idx, 1) + If currentChar <> " " Then cleanExpr &= currentChar + Next + + originalExpr = cleanExpr + + While cleanExpr <> "" + currentChar = Left(cleanExpr, 1) + asciiVal = Asc(currentChar) Or 32 + remainExpr = Right(cleanExpr, Len(cleanExpr) - 1) + + Select Case True + Case asciiVal >= 97 Andalso asciiVal <= 122 + ExprStack(exprPos) = asciiVal - 33 + exprPos += 1 + + Case currentChar = "0" Orelse currentChar = "1" + ExprStack(exprPos) = Val(currentChar) + 32 + exprPos += 1 + + Case (currentChar = "(") + OpStack(stackPos) = 97 + stackPos += 1 + + Case (currentChar = ")") + While stackPos > 0 And OpStack(stackPos-1) <> 97 + ExprStack(exprPos) = OpStack(stackPos-1) + exprPos += 1 + stackPos -= 1 + Wend + If stackPos > 0 Then stackPos -= 1 + + Case Else + operatorFound = False + For idx = 1 To 6 '7 + If Left(cleanExpr, Len(Operators(idx))) = Operators(idx) Orelse _ + (Operators(idx) = "~" Andalso Left(cleanExpr, 1) = "!") Then + + operatorFound = True + cleanExpr = Right(cleanExpr, Len(cleanExpr) - Len(Operators(idx))) + + While stackPos > 0 Andalso OpStack(stackPos-1) <> 97 Andalso _ + OpPrecedence(OpStack(stackPos-1) And 31) >= OpPrecedence(idx) + ExprStack(exprPos) = OpStack(stackPos-1) + exprPos += 1 + stackPos -= 1 + Wend + + OpStack(stackPos) = idx + stackPos += 1 + Exit For + End If + Next + + If Not operatorFound Then + Print "Parse error at: "; cleanExpr + Print + Exit Do + End If + Continue While + End Select + + cleanExpr = remainExpr + Wend + + ' Process remaining operators and build variable list + ProcessRemainingOperators() + BuildVariableList() + PrintTruthTable(originalExpr) +Loop + +Sleep diff --git a/Task/Truth-table/M2000-Interpreter/truth-table.m2000 b/Task/Truth-table/M2000-Interpreter/truth-table.m2000 new file mode 100644 index 0000000000..5dd4df7240 --- /dev/null +++ b/Task/Truth-table/M2000-Interpreter/truth-table.m2000 @@ -0,0 +1,77 @@ +module TrueTable { + Input "How many parameters:";N + if N<1 then exit + if N>26 then Restart + print "Use of variables:", @(19), + for i=1 to N + print " "+chr$(i+64); + next + print + print "Identifiers:", @(20), "NOT AND OR XOR TRUE FALSE" + print "Symbols:", @(20), "( )" + dim a(0 to N) as boolean + a(N)=true + input "boolean expression: ";E$ + E$=ucase$(E$) + P$=E$ + E$=replace$("TRUE", "___", E$) + E$=replace$("FALSE", "^^^", E$) + E$=replace$("AND", "%%%", E$) + E$=replace$("XOR", "???", E$) + E$=replace$("OR", "!!!", E$) + E$=replace$("NOT", "^^^", E$) + Z$=filter$(E$, "%?!^()_^") + try ok { + for i=0 to N-1 + Z$=filter$(Z$, chr$(i+65)) + if instr(E$,chr$(i+65))=0 then Error "Missing "+chr$(i+65) + E$=replace$(chr$(i+65), "[]("+i+")", E$) + next + } + if error or not ok then print "Error"+Error$ : restart + if trim$(Z$)<>"" then print "FOUND:";Z$;"ILLEGAL CHARACTERS": restart + E$=replace$("%%%","AND", E$) + E$=replace$("???", "XOR", E$) + E$=replace$( "!!!", "OR", E$) + E$=replace$("^^^", "NOT", E$) + E$=replace$("[]", "a", E$) + E$=replace$("___", "TRUE", E$) + E$=replace$("^^^", "FALSE", E$) + S$="" + H$="" + B$="" + for i=1 to N + H$+=" "+chr$(i+64)+" |" + B$+="-------+" + next + B$+=string$("-",len(P$)) + H$+=P$ + print H$ + S$=H$+{ + } + try ok { + do L$="" + for i=0 to N-1 + L$+=format$(" {0:5} |", a(i)) + next + L$+=" "+Str$(Eval(E$)) + print B$ + print L$ + S$+=B$+{ + }+L$+{ + } + when @PlayNext() + clipboard S$ + } + if error or not ok then print "Error"+Error$ : restart + End + function PlayNext() + local i + for i=0 to N + a(i)=not a(i) + if a(i) then exit for + next + =N>=i + end function +} +TrueTable diff --git a/Task/Twin-primes/Forth/twin-primes.fth b/Task/Twin-primes/Forth/twin-primes.fth new file mode 100644 index 0000000000..b6c50ca367 --- /dev/null +++ b/Task/Twin-primes/Forth/twin-primes.fth @@ -0,0 +1,47 @@ +variable sieve-addr + +: sieve-free ( -- ) + sieve-addr @ free abort" free failed" + 0 sieve-addr ! ; + +: sieve-allocate ( n -- ) + sieve-free + dup allocate abort" out of memory" + tuck sieve-addr ! erase ; + +: odd-prime? ( n -- ? ) 2/ sieve-addr @ + c@ 0= ; +: notprime! ( n -- ) 2/ sieve-addr @ + 1 swap c! ; + +\ odds-only prime sieve +: sieve { n -- } + n 2/ sieve-allocate + 1 notprime! 3 + begin + dup dup * n < + while + dup odd-prime? if + n over dup * do + i notprime! + dup 2* +loop + then + 2 + + repeat + drop ; + +: twin-prime-count ( n -- n ) + dup sieve 5 0 >r + begin + 2dup > + while + dup odd-prime? if + dup 2 - odd-prime? if + r> 1+ >r + then + then + 2 + + repeat + sieve-free 2drop r> ; + +10000000 dup twin-prime-count swap +." Number of twin prime pairs less than " . ." is " . cr +bye diff --git a/Task/Twos-complement/Racket/twos-complement.rkt b/Task/Twos-complement/Racket/twos-complement.rkt new file mode 100644 index 0000000000..848166adc9 --- /dev/null +++ b/Task/Twos-complement/Racket/twos-complement.rkt @@ -0,0 +1,9 @@ +#lang racket/base + +(define (main) + (let ([n 42]) + (printf "n = ~a, -n = ~a, two's complement = ~a\n" + n (- n) (add1 (bitwise-not n))))) + +(module+ main + (main)) diff --git a/Task/Twos-complement/X86-64-Assembly/twos-complement.x86-64 b/Task/Twos-complement/X86-64-Assembly/twos-complement.x86-64 new file mode 100644 index 0000000000..c3c8f680a8 --- /dev/null +++ b/Task/Twos-complement/X86-64-Assembly/twos-complement.x86-64 @@ -0,0 +1,5 @@ + mov rax, 1968 ; 1968 in rax + neg rax ; -1968 should be in rax +;------------------ + not rax + inc rax ; 1968 should be in rax again. diff --git a/Task/UPC/EasyLang/upc.easy b/Task/UPC/EasyLang/upc.easy index 416884c2e8..4d770fcc72 100644 --- a/Task/UPC/EasyLang/upc.easy +++ b/Task/UPC/EasyLang/upc.easy @@ -1,12 +1,8 @@ proc trim . s$ . a = 1 - while substr s$ a 1 = " " - a += 1 - . + while substr s$ a 1 = " " : a += 1 b = len s$ - while substr s$ b 1 = " " - b -= 1 - . + while substr s$ b 1 = " " : b -= 1 s$ = substr s$ a (b - a + 1) . func$ rev s$ . @@ -14,7 +10,7 @@ func$ rev s$ . for i to len a$[] div 2 swap a$[i] a$[len a$[] - i + 1] . - return strjoin a$[] + return strjoin a$[] "" . func$ invert s$ . for c$ in strchars s$ @@ -33,16 +29,10 @@ func[] decode_upc upc$ . h$ = substr upc$ pos 7 for dig to 10 d$ = digs$[dig] - if isright = 1 - d$ = invert d$ - . - if h$ = d$ - break 1 - . - . - if dig = 11 - return [ ] + if isright = 1 : d$ = invert d$ + if h$ = d$ : break 1 . + if dig = 11 : return [ ] dig -= 1 digs[] &= dig sum += dig * sumf @@ -50,27 +40,17 @@ func[] decode_upc upc$ . pos = pos + 7 . . - if len upc$ <> 95 - return [ ] - . - if substr upc$ 1 3 <> "# #" - return [ ] - . + if len upc$ <> 95 : return [ ] + if substr upc$ 1 3 <> "# #" : return [ ] pos = 4 sumf = 3 getdigs - if substr upc$ pos 5 <> " # # " - return [ ] - . + if substr upc$ pos 5 <> " # # " : return [ ] pos += 5 isright = 1 getdigs - if substr upc$ 1 3 <> "# #" - return [ ] - . - if sum mod 10 <> 0 - return [ ] - . + if substr upc$ 1 3 <> "# #" : return [ ] + if sum mod 10 <> 0 : return [ ] return digs[] . barcodes$[] = [ " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # " " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # " " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # " " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # " " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # " " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # " " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # " " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # " " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # " " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " ] diff --git a/Task/URL-decoding/Langur/url-decoding.langur b/Task/URL-decoding/Langur/url-decoding.langur index bcba2950c4..73a27c6509 100644 --- a/Task/URL-decoding/Langur/url-decoding.langur +++ b/Task/URL-decoding/Langur/url-decoding.langur @@ -1,5 +1,12 @@ -val finish = fn s:b2s(map(fn x:number(x, 16), rest(split("%", s)))) -val decode = fn s:replace(s, re/(%[0-9A-Fa-f]{2})+/, finish) +val finish = fn s:b2s(map( + less(split(s, by="%"), of=1), + by=fn x:number(x, fmt=16), + )) +val decode = fn s:replace( + s, + by=re/(%[0-9A-Fa-f]{2})+/, + with=finish, + ) -writeln decode("http%3A%2F%2Ffoo%20bar%2F") -writeln decode("google.com/search?q=%60Abdu%27l-Bah%C3%A1") +writeln decode("https%3A%2F%2Fno%20more%20foo%20bars%20please%2F") +writeln decode("google.com/search?q=%22unbroken%20string%22") diff --git a/Task/URL-encoding/EasyLang/url-encoding.easy b/Task/URL-encoding/EasyLang/url-encoding.easy new file mode 100644 index 0000000000..f460d12259 --- /dev/null +++ b/Task/URL-encoding/EasyLang/url-encoding.easy @@ -0,0 +1,21 @@ +func$ tohex h . + for c in [ h div 16 h mod 16 ] + c += 48 + if c >= 58 : c += 7 + r$ &= strchar c + . + return r$ +. +func$ urlenc s$ . + for c$ in strchars s$ + c = strcode c$ + if c >= 48 and c <= 57 or c >= 65 and c <= 90 or c >= 97 and c <= 122 + # + else + c$ = "%" & tohex c + . + r$ &= c$ + . + return r$ +. +print urlenc "http://foo bar/" diff --git a/Task/URL-encoding/Langur/url-encoding.langur b/Task/URL-encoding/Langur/url-encoding.langur index 53580f1b28..26ef6f0d35 100644 --- a/Task/URL-encoding/Langur/url-encoding.langur +++ b/Task/URL-encoding/Langur/url-encoding.langur @@ -1,7 +1,8 @@ val urlEncode = fn(s) { replace( - s, re/[^A-Za-z0-9]/, - fn s:join("", map(fn b:"%{{b:X02}}", s2b(s))), + s, + by=re/[^A-Za-z0-9]/, + with=fn r:join(map(s2b(r), by=fn b:"%{{b:X02}}")), ) } diff --git a/Task/URL-encoding/Standard-ML/url-encoding.ml b/Task/URL-encoding/Standard-ML/url-encoding.ml new file mode 100644 index 0000000000..3d2b5b1a49 --- /dev/null +++ b/Task/URL-encoding/Standard-ML/url-encoding.ml @@ -0,0 +1,7 @@ +fun urlEncode str = + let + fun charToHex c = "%" ^ (Int.fmt StringCvt.HEX (ord c)) + fun escapeChar c = if Char.isAlphaNum c then Char.toString c else charToHex c + in + String.concat (map escapeChar (explode str)) + end diff --git a/Task/UTF-8-encode-and-decode/Langur/utf-8-encode-and-decode.langur b/Task/UTF-8-encode-and-decode/Langur/utf-8-encode-and-decode.langur index 0c0986069b..4efa9e9924 100644 --- a/Task/UTF-8-encode-and-decode/Langur/utf-8-encode-and-decode.langur +++ b/Task/UTF-8-encode-and-decode/Langur/utf-8-encode-and-decode.langur @@ -3,6 +3,6 @@ writeln "character Unicode UTF-8 encoding (hex)" for cp in "AöЖ€𝄞" { val utf8 = cp -> cp2s -> s2b val cpstr = utf8 -> b2s - val utf8rep = join(" ", map(fn b:"{{b:X02}}", utf8)) + val utf8rep = join(map(utf8, by=fn b:"{{b:X02}}"), by=" ") writeln "{{cpstr:-11}} U+{{cp:X04:-8}} {{utf8rep}}" } diff --git a/Task/Ukkonen-s-suffix-tree-construction/C++/ukkonen-s-suffix-tree-construction.cpp b/Task/Ukkonen-s-suffix-tree-construction/C++/ukkonen-s-suffix-tree-construction.cpp index 6781444d65..f7edd92c13 100644 --- a/Task/Ukkonen-s-suffix-tree-construction/C++/ukkonen-s-suffix-tree-construction.cpp +++ b/Task/Ukkonen-s-suffix-tree-construction/C++/ukkonen-s-suffix-tree-construction.cpp @@ -27,7 +27,7 @@ public: text = word + '\u0004'; // Terminal character nodes.reserve(2 * text.length()); - root = newNode(UNDEFINED, UNDEFINED); + root = new_node(UNDEFINED, UNDEFINED); active_node = root; for ( const char& character : text ) { @@ -36,8 +36,8 @@ public: } std::map> get_longest_repeated_substrings() { - std::vector indexes = doTraversal(); - std::string word = text.substr(0, text.length() - 1); + const std::vector indexes = do_traversal(); + const std::string word = text.substr(0, text.length() - 1); std::map> result{ }; if ( indexes.front() > 0 ) { @@ -61,7 +61,7 @@ private: } if ( ! nodes[active_node].children.contains(text[active_edge]) ) { - const int32_t leaf = newNode(text_index, LEAF_NODE); + const int32_t leaf = new_node(text_index, LEAF_NODE); nodes[active_node].children[text[active_edge]] = leaf; add_suffix_link(active_node); } else { @@ -76,9 +76,9 @@ private: break; } - const uint32_t split = newNode(nodes[next].start, nodes[next].start + active_length); + const uint32_t split = new_node(nodes[next].start, nodes[next].start + active_length); nodes[active_node].children[text[active_edge]] = split; - const int32_t leaf = newNode(text_index, LEAF_NODE); + const int32_t leaf = new_node(text_index, LEAF_NODE); nodes[split].children[character] = leaf; nodes[next].start += active_length; nodes[split].children[text[nodes[next].start]] = next; @@ -118,7 +118,7 @@ private: need_parent_link = node; } - uint32_t newNode(const int32_t& start, const int32_t& end) { + uint32_t new_node(const int32_t& start, const int32_t& end) { Node node(start, end); node.leaf_index = ( end == LEAF_NODE ) ? leaf_index_generator++ : UNDEFINED; nodes[current_node] = node; @@ -126,7 +126,7 @@ private: return current_node++; } - std::vector doTraversal() { + std::vector do_traversal() { std::vector indexes{ }; indexes.emplace_back(UNDEFINED); @@ -152,8 +152,7 @@ private: std::vector nodes; std::string text; - - int32_t root; + int32_t root; int32_t active_node, active_length = 0, active_edge = 0; int32_t text_index = 0, current_node = 0, need_parent_link = 0, remainder = 0, leaf_index_generator = 0; @@ -162,32 +161,32 @@ private: }; int main() { - std::vector limits = { 1'000, 10'000, 100'000 }; + const std::vector limits = { 1'000, 10'000, 100'000 }; + + std::ifstream stream("../piDigits.txt"); + const std::string contents( ( std::istreambuf_iterator(stream) ), + ( std::istreambuf_iterator() ) ); for ( const int32_t& limit : limits ) { - std::ifstream stream("../piDigits.txt"); - std::string contents( ( std::istreambuf_iterator(stream) ), - ( std::istreambuf_iterator() ) ); - std::string pi_digits = contents.substr(0, limit); + const std::string pi_digits = contents.substr(0, limit); - auto begin = std::chrono::high_resolution_clock::now(); + const auto begin = std::chrono::high_resolution_clock::now(); SuffixTree tree(pi_digits); std::map> substrings = tree.get_longest_repeated_substrings(); - auto end = std::chrono::high_resolution_clock::now(); - auto elapsed = std::chrono::duration_cast( end - begin ); + const auto end = std::chrono::high_resolution_clock::now(); + const auto elapsed = std::chrono::duration_cast( end - begin ); std::cout << "First " << limit << " digits of pi has longest repeated characters:" << std::endl; for ( std::pair> entry : substrings ) { std::cout << " '" << entry.first << "' starting at index "; - for ( int32_t index : entry.second ) { + for ( const int32_t& index : entry.second ) { std::cout << index << " "; } std::cout << std::endl; } - std::cout << "Time taken: " << elapsed << " milliseconds." << std::endl << std::endl; + std::cout << "Time taken: " << elapsed << std::endl << std::endl; } - std::cout << "The timings show that the implementation has approximately linear performance." - << std::endl; + std::cout << "The timings show that the implementation has approximately linear performance." << std::endl; } diff --git a/Task/Ultra-useful-primes/M2000-Interpreter/ultra-useful-primes.m2000 b/Task/Ultra-useful-primes/M2000-Interpreter/ultra-useful-primes.m2000 new file mode 100644 index 0000000000..30279235de --- /dev/null +++ b/Task/Ultra-useful-primes/M2000-Interpreter/ultra-useful-primes.m2000 @@ -0,0 +1,27 @@ +module Ultra_Useful { + minusOne=biginteger("-1") + one=biginteger("1") + two=biginteger("2") + num=biginteger("0") + k=num + with num,"tostring" as numS + with k,"tostring" as kS + for n= 1 to 10 + k=minusOne + kk=-1 + n1=biginteger(str$(n,"")) + method two,"intpower", n1 as n1 + do + method k,"add", two as k + kk+=2 + method two, "intpower", n1 as num + method num, "subtract", k as num + method num,"isProbablyPrime", 10 as ret + if ret then + Print n, kk : Refresh + exit + end if + always + next +} +Ultra_Useful diff --git a/Task/Ultra-useful-primes/Quackery/ultra-useful-primes.quackery b/Task/Ultra-useful-primes/Quackery/ultra-useful-primes.quackery new file mode 100644 index 0000000000..5ec2e65548 --- /dev/null +++ b/Task/Ultra-useful-primes/Quackery/ultra-useful-primes.quackery @@ -0,0 +1,7 @@ + 12 times + [ i^ 1+ bit bit + 1 + [ 2dup - + prime not while + 2 + again ] + echo sp drop ] diff --git a/Task/Unicode-variable-names/Joy/unicode-variable-names.joy b/Task/Unicode-variable-names/Joy/unicode-variable-names.joy new file mode 100644 index 0000000000..98d857bbdc --- /dev/null +++ b/Task/Unicode-variable-names/Joy/unicode-variable-names.joy @@ -0,0 +1,8 @@ +DEFINE Δ == 1. +DEFINE Δ1 == Δ 1 +. +Δ. Δ1. +1 +2 +DEFINE 💩 == 2. +💩. +2 diff --git a/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy b/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy new file mode 100644 index 0000000000..5d124545bd --- /dev/null +++ b/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy @@ -0,0 +1,138 @@ +global right$[] left$[] pos blank$ . +proc show stat$ . . + write stat$ + for i to 5 - len stat$ + write " " + . + write "| " + h = -len left$[] + 1 + for i = h to len right$[] + if i <= 0 + c$ = left$[-i + 1] + else + c$ = right$[i] + . + if i = pos + write "*" + else + write " " + . + write c$ & " " + . + print "" +. +func$ get . + if pos <= 0 + return left$[-pos + 1] + . + return right$[pos] +. +proc put s$ . . + if pos <= 0 + left$[-pos + 1] = s$ + else + right$[pos] = s$ + . +. +proc mleft . . + pos -= 1 + if pos <= 0 and len left$[] < (-pos + 1) + left$[] &= blank$ + . +. +proc mright . . + pos += 1 + if pos > 0 and len right$[] < pos + right$[] &= blank$ + . +. +proc utm stat$ endstat$ bl$ init$ rules$[] trace . . + blank$ = bl$ + pos = 1 + right$[] = strsplit init$ " " + left$[] = [ ] + for r$ in rules$[] + r$[][] &= strsplit r$ " " + . + repeat + if trace = 1 + show stat$ + else + if steps mod 1000000 = 0 + write "." + . + . + for i to len r$[][] + if r$[i][1] = stat$ and r$[i][2] = get + put r$[i][3] + if r$[i][4] = "left" + mleft + elif r$[i][4] = "right" + mright + . + stat$ = r$[i][5] + break 1 + . + . + steps += 1 + until stat$ = endstat$ + . + if trace = 1 + show stat$ + else + print "" + print "Steps: " & steps + . +. +# +repeat + s$ = input + until s$ = "" + trace = 1 + if substr s$ 1 7 = "5-state" + trace = 0 + . + print "--- " & s$ & "---" + s$ = input + in1$[] = strsplit s$ " " + in2$ = input + r$[] = [ ] + repeat + s$ = input + until s$ = "" + r$[] &= s$ + . + utm in1$[1] in1$[2] in1$[3] in2$ r$[] trace + print "" +. +# +input_data +Simple incrementer +q0 qf B +1 1 1 +q0 1 1 right q0 +q0 B 1 stay qf + +Three-state busy beaver +a halt 0 +0 +a 0 1 right b +a 1 1 left c +b 0 1 left a +b 1 1 right b +c 0 1 left b +c 1 1 stay halt + +5-state, 2-symbol probable Busy Beaver +A H 0 +0 +A 0 1 right B +A 1 1 left C +B 0 1 right C +B 1 1 right B +C 0 1 right D +C 1 0 left E +D 0 1 left A +D 1 1 left D +E 0 1 stay H +E 1 0 left A diff --git a/Task/Universal-Turing-machine/Quackery/universal-turing-machine.quackery b/Task/Universal-Turing-machine/Quackery/universal-turing-machine.quackery new file mode 100644 index 0000000000..f4472c563a --- /dev/null +++ b/Task/Universal-Turing-machine/Quackery/universal-turing-machine.quackery @@ -0,0 +1,51 @@ + [ this ] is halt ( --> halt ) + [ stack ] is state ( --> s ) + [ stack ] is machine ( --> s ) + + [ state share echo say ": " + split + swap witheach [ echo sp ] + behead nested echo sp + witheach [ echo sp ] cr ] is echotape ( tape head --> ) + + [ over dip [ unrot poke ] ] is write ( tape head value --> tape head ) + + [ write + dup 0 = iff + [ dip [ 0 swap join ] ] + else [ 1 - ] ] is left ( tape head value --> tape head ) + + [ write + 1+ + over size over = if + [ dip [ 0 join ] ] ] is right ( tape head value --> tape head ) + + [ write ] is stay ( tape head value --> tape head ) + + [ 0 state put + rot machine put + [ 2dup echotape + 2dup peek + machine share + state share peek + swap peek do + state replace + state share + halt = until ] + echotape + state release + machine release ] is turing ( machine tape head --> ) + + say "Simple Incrementer" + cr cr + ' [ [ [ 1 stay halt ] [ 1 right 0 ] ] ] + ' [ 1 1 1 ] 0 + turing + cr cr + say "Three-state Busy Beaver" + cr cr + ' [ [ [ 1 right 1 ] [ 1 left 2 ] ] + [ [ 1 left 0 ] [ 1 right 1 ] ] + [ [ 1 left 1 ] [ 1 stay halt ] ] ] + ' [ 0 ] 0 + turing diff --git a/Task/Untouchable-numbers/Python/untouchable-numbers.py b/Task/Untouchable-numbers/Python/untouchable-numbers.py new file mode 100644 index 0000000000..504d73487a --- /dev/null +++ b/Task/Untouchable-numbers/Python/untouchable-numbers.py @@ -0,0 +1,93 @@ +def prime_sieve(limit: int): + p = 3 + + limit += 1 + + c = [False] * limit + + c[0] = True + c[1] = True + + for i in range(4, limit, 2): + c[i] = True + + while True: + p2 = p * p + + if p2 >= limit: + break + + for i in range(p2, limit, 2 * p): + c[i] = True + + while True: + p += 2 + + if not c[p]: + break + + return c + +def main(): + limit = 1000000 + + uc = 2 + p = 10 + m = 63 + ul = 151000 + + c = prime_sieve(limit) + n = m * limit + 1 + + sum_divs = [0] * n + + for i in range(1, n): + for j in range(i, n, i): + sum_divs[j] += i + + s = [False] * n + + for i in range(1, n): + sumation = sum_divs[i] - i + if sumation <= n: + s[sumation] = True + + untouchable = [0] * ul + + untouchable[0] = 2 + untouchable[1] = 5 + + for n in range(6, limit+1, 2): + if not s[n] and c[n - 1] and c[n-3]: + untouchable[uc] = n + uc += 1 + + print("List of untouchable numbers <= 2,000:") + + for i in range(uc): + j = untouchable[i] + + if j > 2000: + break + + print("%3d " % j, end=' ') + + if not ((i+1) % 10): + print() + + print("\n\n%d untouchable numbers were found <= 2,000\n" % i) + + for i in range(uc): + j = untouchable[i] + + if j > p: + print("%d untouchable numbers were found <= %d\n" % (i, p)) + p *= 10 + + if p == limit: + break + + print("%d untouchable numbers were found <= %d" % (uc, limit)) + +if __name__ == '__main__': + main() diff --git a/Task/Use-another-language-to-call-a-function/FutureBasic/use-another-language-to-call-a-function.basic b/Task/Use-another-language-to-call-a-function/FutureBasic/use-another-language-to-call-a-function.basic new file mode 100644 index 0000000000..c11f2aa16a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/FutureBasic/use-another-language-to-call-a-function.basic @@ -0,0 +1,23 @@ +include "NSLog.incl" + +// FutureBasic function +local fn Query( buffer as ptr, size as ^unsigned long ) as long + CFStringRef string = @"Here am I" + ptr p = fn StringCStringUsingEncoding( string, NSASCIIStringEncoding ) + *size = len(string) + BlockMoveData( p, buffer, *size ) +end fn = 1 + + +// C code +BeginCCode + char buffer[1024]; + size_t Size = sizeof(buffer); + if ( Query( buffer, &Size ) == 0 ) { // call FutureBasic function + NSLog(@"failed to call Query\n"); + } else { + NSLog(@"%s",buffer); + } +EndC + +HandleEvents diff --git a/Task/Use-another-language-to-call-a-function/Zig/use-another-language-to-call-a-function.zig b/Task/Use-another-language-to-call-a-function/Zig/use-another-language-to-call-a-function.zig index 80d594b2b4..6f0f612d01 100644 --- a/Task/Use-another-language-to-call-a-function/Zig/use-another-language-to-call-a-function.zig +++ b/Task/Use-another-language-to-call-a-function/Zig/use-another-language-to-call-a-function.zig @@ -1,11 +1,9 @@ -const std = @import("std"); - -export fn Query(Data: [*c]u8, Length: *usize) callconv(.C) c_int { +export fn Query(data: [*c]u8, length: *usize) callconv(.C) c_int { const value = "Here I am"; - if (Length.* >= value.len) { - @memcpy(@ptrCast([*]u8, Data), value, value.len); - Length.* = value.len; + if (length.* >= value.len) { + @memcpy(data[0..value.len], value); + length.* = value.len; return 1; } diff --git a/Task/User-input-Graphical/Nim/user-input-graphical.nim b/Task/User-input-Graphical/Nim/user-input-graphical.nim index 535e880cf7..8573991395 100644 --- a/Task/User-input-Graphical/Nim/user-input-graphical.nim +++ b/Task/User-input-Graphical/Nim/user-input-graphical.nim @@ -1,82 +1,97 @@ -import strutils -import gintro/[glib, gobject, gtk, gio] +import std/strformat +import gtk2, glib2 -type MainWindow = ref object of ApplicationWindow - strEntry: Entry - intEntry: SpinButton +############################################################################### +# Missing declaration. -#--------------------------------------------------------------------------------------------------- +when defined(win32): + const lib = "libgtk-win32-2.0-0.dll" +elif defined(macosx): + const lib = "(libgtk-quartz-2.0.0.dylib|libgtk-x11-2.0.dylib)" +else: + const lib = "libgtk-x11-2.0.so(|.0)" -proc displayValues(strval: string; intval: int) = +proc getContentArea(dialog: PDialog): PVBox {.cdecl, + importc: "gtk_dialog_get_content_area", dynlib: lib.} + + +############################################################################### + +type App = object + window: PWindow + strEntry: PEntry + intEntry: PSpinButton + + +proc displayValues(app: App; strval: cstring; intval: int) = ## Display a dialog window with the values entered by the user. - let dialog = newDialog() - dialog.setModal(true) - let label1 = newLabel(" String value is “$1”.".format(strval)) - label1.setHalign(Align.start) - dialog.contentArea.packStart(label1, true, true, 5) - let msg = " Integer value is $1 which is ".format(intval) & - (if intval == 75000: "right. " else: "wrong (expected 75000). ") - let label2 = newLabel(msg) - dialog.contentArea.packStart(label2, true, true, 5) - discard dialog.addButton("OK", ord(ResponseType.ok)) + let dialog = dialogNewWithButtons("user_input_graphical", app.window, + DIALOG_MODAL or DIALOG_DESTROY_WITH_PARENT, "OK") + let label1 = labelNew(cstring(&" String value is “{strval}”.")) + let contentArea = dialog.getContentArea() + contentArea.packStart(label1, true, true, 5) + let text = if intval == 75000: "right. " else: "wrong (expected 75000). " + let msg = &" Integer value is {intval} which is {text}" + let label2 = labelNew(msg.cstring) + contentArea.packStart(label2, true, true, 5) dialog.showAll() discard dialog.run() dialog.destroy() -#--------------------------------------------------------------------------------------------------- -proc onOk(button: Button; window: MainWindow) = +proc onOk(button: PButton; app: var App) = ## Callback executed when the OK button has been clicked. - let strval = window.strEntry.text() - let intval = window.intEntry.value().toInt - displayValues(strval, intval) + let strval = app.strEntry.getText() + let intval = app.intEntry.getValue().toInt + app.displayValues(strval, intval) if intval == 75_000: - window.destroy() + app.window.destroy() -#--------------------------------------------------------------------------------------------------- -proc activate(app: Application) = - ## Activate the application. +proc onDestroyEvent(widget: PWidget; data: pointer): gboolean {.cdecl.} = + ## Quit the application. + mainQuit() - let window = newApplicationWindow(MainWindow, app) - window.setTitle("User input") - let content = newBox(Orientation.vertical, 10) - content.setHomogeneous(true) - let grid = newGrid() - grid.setColumnSpacing(30) - let bbox = newButtonBox(Orientation.horizontal) - bbox.setLayout(ButtonBoxStyle.spread) +var app: App - let strLabel = newLabel("Enter some text") - strLabel.setHalign(Align.start) - window.strEntry = newEntry() - grid.attach(strLabel, 0, 0, 1, 1) - grid.attach(window.strEntry, 1, 0, 1, 1) +nimInit() - let intLabel = newLabel("Enter 75000") - intLabel.setHalign(Align.start) - window.intEntry = newSpinButtonWithRange(0, 80_000, 1) - grid.attach(intLabel, 0, 1, 1, 1) - grid.attach(window.intEntry, 1, 1, 1, 1) +app.window = windowNew(WINDOW_TOPLEVEL) +app.window.setTitle("User input") +discard app.window.signalConnect("destroy", SIGNAL_FUNC(onDestroyEvent), nil) - let btnOk = newButton("OK") +let content = vboxNew(false, 10) +content.setHomogeneous(true) +let grid = tableNew(2, 2, false) +grid.setColSpacings(30) - bbox.add(btnOk) +let hbox1 = hboxNew(false, 0) +let strLabel = labelNew("Enter some text") +app.strEntry = entryNew() +hbox1.packStart(strLabel, false, false, 0) +grid.attach(hbox1, 0, 1, 0, 1, constFILL, 0, 0, 0) +grid.attach(app.strEntry, 1, 2, 0, 1, constFILL, 0, 0, 0) - content.packStart(grid, true, true, 0) - content.packEnd(bbox, true, true, 0) +let hbox2 = hboxNew(false, 0) +let intLabel = labelNew("Enter 75000") +app.intEntry = spinButtonNew(0, 80_000, 1) +hbox2.packStart(intLabel, false, false, 0) +grid.attach(hbox2, 0, 1, 1, 2, constFILL, 0, 0, 0) +grid.attach(app.intEntry, 1, 2, 1, 2, constFILL, 0, 0, 0) - window.setBorderWidth(5) - window.add(content) +let btnOk = buttonNew("OK") +btnOk.setSizeRequest(100, 40) +let hbox3 = hboxNew(false, 20) +hbox3.packEnd(btnOk, false, true, 10) +content.packStart(grid, true, true, 0) +content.packEnd(hbox3, false, false, 0) - discard btnOk.connect("clicked", onOk, window) +app.window.setBorderWidth(5) +app.window.add content - window.showAll() +discard btnOk.signalConnect("clicked", SIGNAL_FUNC(onOk), app.addr) -#——————————————————————————————————————————————————————————————————————————————————————————————————— - -let app = newApplication(Application, "Rosetta.UserInput") -discard app.connect("activate", activate) -discard app.run() +app.window.showAll() +main() diff --git a/Task/User-input-Graphical/V-(Vlang)/user-input-graphical.v b/Task/User-input-Graphical/V-(Vlang)/user-input-graphical.v index bc88d58635..2faa4a0cb4 100644 --- a/Task/User-input-Graphical/V-(Vlang)/user-input-graphical.v +++ b/Task/User-input-Graphical/V-(Vlang)/user-input-graphical.v @@ -4,11 +4,6 @@ import ui struct App { mut: win &ui.Window = unsafe {nil} - txt_1 &ui.TextBox = unsafe {nil} - txt_2 &ui.TextBox = unsafe {nil} - lbl_1 &ui.Label = unsafe {nil} - lbl_2 &ui.Label = unsafe {nil} - btn_1 &ui.Button = unsafe {nil} instr string = "Enter some text, the number 75000, and press 'Validate'" txt string num string @@ -16,44 +11,37 @@ struct App { fn main() { mut app := &App{} -// widgets defined and placed here for clarity - app.lbl_1 = ui.label(text: &app.instr, id: "lbl_1", justify: [0.5, 0.0]) // [x, y] for text placement - app.lbl_2 = ui.label(text: "", id: "lbl_2", text_align: .center, justify: [0.5, 0.0]) - app.txt_1 = ui.textbox(placeholder: "String", text: &app.txt, id: "txt_1") - app.txt_2 = ui.textbox(placeholder: "Number", text: &app.num, id: "txt_2") - app.btn_1 = ui.button(width: 5, text: "Validate", on_click: app.btn_click) - - app.win = ui.window( - height: 150 - width: 450 - title: "Input Info" - mode: .resizable +// widgets defined and placed first for clarity + lbl_1 := ui.label(text: &app.instr, id: "lbl_1", justify: [0.5, 0.0]) // [x, y] for text placement + lbl_2 := ui.label(text: "", id: "lbl_2", text_align: .center, justify: [0.5, 0.0]) + txt_1 := ui.textbox(placeholder: "String", text: &app.txt, id: "txt_1") + txt_2 := ui.textbox(placeholder: "Number", text: &app.num, id: "txt_2") + btn_1 := ui.button(width: 5, text: "Validate", on_click: app.btn_click) +// column can be spread vertically and for visualization + col := ui.column( + alignment: .center // button's center, relative to UI + spacing: 5 // button's distance from other widgets + widths: [ui.stretch, 150] // button's width relative to UI + margin: ui.Margin{0, 5, 0, 5} // widgets relative to UI's edges, {y, right, x, left} children: [ ui.column( - alignment: .center // button's center, relative to UI - spacing: 5 // button's distance from other widgets - widths: [ui.stretch, 150] // button's width relative to UI - margin: ui.Margin{0, 5, 0, 5} // widgets relative to UI's edges, {y, right, x, left} - children: [ - ui.column( - alignment: .center - spacing: 5 // distance between widgets in same column - children: [ - app.lbl_1 - app.lbl_2 - app.txt_1 - app.txt_2 - ] - ), - // button in and controlled from separate column - app.btn_1 - ] - ), + alignment: .center + spacing: 5 // distance between widgets in same column + children: [ + lbl_1 + lbl_2 + txt_1 + txt_2 + ] + ), + btn_1 // button in and controlled from separate column ] ) + app.win = ui.window(height: 150, width: 450, title: "Input Info", mode: .resizable, children: [col]) ui.run(app.win) } fn (mut app App) btn_click(btn &ui.Button) { - app.lbl_2.set_text("${app.txt} ${app.num}") + mut lbl_2 := app.win.get_or_panic[ui.Label]("lbl_2") // id: "lbl_2" (used above) + lbl_2.set_text("${app.txt} ${app.num}") } diff --git a/Task/User-input-Graphical/XPL0/user-input-graphical.xpl0 b/Task/User-input-Graphical/XPL0/user-input-graphical.xpl0 index c11754e5d3..1e840ef851 100644 --- a/Task/User-input-Graphical/XPL0/user-input-graphical.xpl0 +++ b/Task/User-input-Graphical/XPL0/user-input-graphical.xpl0 @@ -1,95 +1,91 @@ -\12345678901234567890123456789012345 -\User input/Graphical.......... X . -\ Please enter a string and 75000: . -\ String: Hello, World!___ . -\ Number: 75000___________ . +\012345678901234567890123456789012345 +\ User input/Graphical.......... X . +\ Please enter a string and 75000: . +\ String: Hello, World!___. . +\ Number: 75000___________. . -def X0=20, Y0=10; \upper-left corner of window's position (chars) +def X0=20, Y0=10; \position of upper-left corner of window (chars) +int Mouse, Button, X, Y, Ch, I, SN; \SN = string number = 0 or 1 def StrMax = 16; \maximum number of characters in strings -char String(2, StrMax); \string arrays (includes Number string) +char String(2, StrMax); \2 string arrays (including Number string) int StrInx(2); \index to character to be added to String -int Mouse, Button, C, I, SN; func GetButton; \Return soft button number at mouse pointer -int X, Y; [Mouse:= GetMouse; -X:= Mouse(0)/8 - X0; \convert pixels to char cells +X:= Mouse(0)/8 - X0; \convert pixels to 8x16-pixel character cells Y:= Mouse(1)/16 - Y0; -if X>=32 & X<=34 & Y=0 then return 0; \exit [X] +if X>=32 & X<=34 & Y=0 then return 0; \exit [X] if X>=10 & X<=10+StrMax & Y=4 then return 1; \line 1 if X>=10 & X<=10+StrMax & Y=6 then return 2; \line 2 return -1; \mouse not on any soft button ]; -proc ShowCursor(Flag); \Turn cursor at insertion point on or off +proc ShowCursor(Flag); \Turn cursor at end of active String on or off int Flag; [Cursor(10+StrInx(SN)+X0, 4+SN*2+Y0); ChOut(6, if Flag then ^_ else ^ ); ]; -[SetVid($12); \640x480 graphics -TrapC(true); \disable Ctrl+C -Attrib($70); \black on gray -SetWind(0+X0, 0+Y0, 35+X0, 8+Y0, 0, \fill\true); -Cursor(33+X0, 0+Y0); Text(6, "X"); +[SetVid($12); \set 640x480 graphics +TrapC(true); \prevent Ctrl+C from aborting the program +Attrib($70); \set black-on-gray color attribute +SetWind(0+X0, 0+Y0, 35+X0, 8+Y0, 0, \fill\true); \draw gray rectangle +Cursor(33+X0, 0+Y0); Text(6, "X"); \draw exit button Cursor(2+X0, 2+Y0); Text(6, "Please enter a string and 75000:"); Cursor(2+X0, 4+Y0); Text(6, "String:"); Cursor(2+X0, 6+Y0); Text(6, "Number:"); - -Attrib($1F); \bright white on blue, for title +Attrib($9F); \set bright white on light blue, for title bar Cursor(0+X0, 0+Y0); Text(6, " User input/Graphical "); - -Attrib($F0); \black on bright white +Attrib($F0); \set black on bright white for SN:= 0 to 1 do \initialize Strings - [StrInx(SN):= 0; - Cursor(10+X0, 4+SN*2+Y0); + [Cursor(10+X0, 4+SN*2+Y0); for I:= 0 to StrMax-1 do - [String(SN, I):= $20; ChOut(6, ^ )]; + [String(SN, I):= ^ ; ChOut(6, ^ )]; + ChOut(6, ^ ); \add one more for cursor underline at StrMax + StrInx(SN):= 0; ]; -SN:= 0; \select first, topmost String +SN:= 0; \select first (topmost) String ShowCursor(true); - -ShowMouse(true); +ShowMouse(true); \turn on mouse pointer loop [MoveMouse; \make pointer track mouse movements - Mouse:= GetMouse; + Mouse:= GetMouse; \get pointer to mouse array information if Mouse(2) then \a left or right mouse button is down [Button:= GetButton; \get soft button at mouse pointer - while Mouse(2) do \wait for mouse button's release + while Mouse(2) do \wait for mouse button(s) to be released [MoveMouse; Mouse:= GetMouse; ]; - if Button = GetButton then \if down Button = release button - [if Button = 0 then quit; - if Button # -1 then \move cursor to active String - [ShowCursor(false); + if Button = GetButton then \if down Button = release button and it + [if Button = 0 then quit; \is the exit [X] button then quit loop + if Button # -1 then \move cursor underline to active String + [ShowMouse(false); \don't overwrite mouse pointer + ShowCursor(false); \turn off cursor at old String position SN:= Button-1; - ShowCursor(true); + ShowCursor(true); \turn on cursor for selected String + ShowMouse(true); \mouse pointer is normally displayed ]; ]; ]; if KeyHit then [ShowMouse(false); \don't overwrite mouse pointer - C:= ChIn(1); \get character from non-echoed keyboard - if SN = 0 and C >= $20 and C <= $7E or \all printable ASCIIs - SN = 1 and C >= $30 and C <= $39 then \only numeric digits - [String(SN, StrInx(SN)):= C; - if StrInx(SN) < StrMax-1 then StrInx(SN):= StrInx(SN)+1; + ShowCursor(false); \remove cursor underline cuz it moves + Ch:= ChIn(1); \get character from non-echoed keyboard + if SN=0 & Ch>=$20 & Ch<=$7E or \allow all printable chars + SN=1 & Ch>=$30 & Ch<=$39 then \allow only numeric digits + [if StrInx(SN) < StrMax then + [String(SN, StrInx(SN)):= Ch; StrInx(SN):= StrInx(SN)+1]; ] - else if C = \BS\$08 then \delete back a character - [ShowCursor(false); - if StrInx(SN) > 0 then StrInx(SN):= StrInx(SN)-1; - ] - else if C = \tab\$09 then \select next string - [ShowCursor(false); - SN:= rem((SN+1)/2); - ] - else if C = \Esc\$1B then quit; + else if Ch = \BS\$08 then \delete back a character + [if StrInx(SN) > 0 then StrInx(SN):= StrInx(SN)-1] + else if Ch = \tab\$09 then \select next string + SN:= rem((SN+1)/2) + else if Ch = \Esc\$1B then quit; Cursor(10+X0, 4+SN*2+Y0); \show active String for I:= 0 to StrInx(SN)-1 do ChOut(6, String(SN, I)); - ChOut(6, ^_); + ChOut(6, ^_); \show cursor underline at end of String ShowMouse(true); ]; - ]; + ]; \loop SetVid(3); \restore normal text mode immediately ] diff --git a/Task/Validate-International-Securities-Identification-Number/FutureBasic/validate-international-securities-identification-number.basic b/Task/Validate-International-Securities-Identification-Number/FutureBasic/validate-international-securities-identification-number.basic new file mode 100644 index 0000000000..bd7516528c --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/FutureBasic/validate-international-securities-identification-number.basic @@ -0,0 +1,40 @@ +// +// Validate International Securities Identification Number +// At entry ISIN string +// Exits with Boolean Valid or Invalid +// +local fn ISINisValid (ISIN as CFStringRef) as Boolean + + // Base36 = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + Int r, v = 0, c, x2(9) = {0,2,4,6,8,1,3,5,7,9} + if len(ISIN) <> 12 then return _False + if ucc(ISIN, 0) < _"A" || ucc(ISIN, 1) < _"A" then return _False + // convert Base 36 digits to Base 10 + uint64 n = 0 + for r = 0 to len(ISIN) - 1 + c = ucc(ISIN, r) + select + case c >= _"A" && c <= _"Z" : n = n * 100 + c - 55 + case c >= _"0" && c <= _"9" : n = n * 10 + c - 48 + case else : return _False + end select + next + // Luhn test + while n + v += n % 10 + x2(n / 10 % 10) + n /= 100 + wend +end fn = !(v mod 10) + +window 1,@"Validate ISIN" + +//Test data +CFStringRef cc(6) = {@"US0378331005", @"US0373831005", @"U50378331005", ¬ +@"US03378331005", @"AU0000XVGZA3", @"AU0000VXGZA3", @"FR0000988040"} +for int x = 0 to 6 + print cc(x), + if fn ISINisValid(cc(x)) then print @"Valid" else print @"Invalid" +next + +handleEvents diff --git a/Task/Video-display-modes/BBC-BASIC/video-display-modes.basic b/Task/Video-display-modes/BBC-BASIC/video-display-modes.basic index e84c6ff6af..09df6c460e 100644 --- a/Task/Video-display-modes/BBC-BASIC/video-display-modes.basic +++ b/Task/Video-display-modes/BBC-BASIC/video-display-modes.basic @@ -1 +1 @@ -10 MODE 1: REM 320x256 4 colour graphics +MODE 1: REM 320x256 4 color graphics diff --git a/Task/Video-display-modes/GW-BASIC/video-display-modes.basic b/Task/Video-display-modes/GW-BASIC/video-display-modes.basic index 9497a525df..a12698e916 100644 --- a/Task/Video-display-modes/GW-BASIC/video-display-modes.basic +++ b/Task/Video-display-modes/GW-BASIC/video-display-modes.basic @@ -1,2 +1 @@ -10 REM GW Basic can switch VGA modes -20 SCREEN 18: REM Mode 12h 640x480 16 colour graphics +SCREEN 9: REM 640x350, 16 colors diff --git a/Task/Video-display-modes/Java/video-display-modes.java b/Task/Video-display-modes/Java/video-display-modes.java index 1124b7cabc..0e5f88b50c 100644 --- a/Task/Video-display-modes/Java/video-display-modes.java +++ b/Task/Video-display-modes/Java/video-display-modes.java @@ -8,7 +8,7 @@ import java.util.concurrent.TimeUnit; import javax.swing.JFrame; import javax.swing.JLabel; -public final class VideoDisplay { +public final class VideoDisplayModes { public static void main(String[] aArgs) throws InterruptedException { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); @@ -36,10 +36,10 @@ public final class VideoDisplay { } // Uncomment the line below to see an example of programmatically changing the video display. - // new VideoDisplay(); + // new VideoDisplayModes(); } - private VideoDisplay() throws InterruptedException { + private VideoDisplayModes() throws InterruptedException { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Video Display Demonstration"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); diff --git a/Task/Video-display-modes/Locomotive-Basic/video-display-modes.basic b/Task/Video-display-modes/Locomotive-Basic/video-display-modes.basic index 1165254e05..e4cad6db86 100644 --- a/Task/Video-display-modes/Locomotive-Basic/video-display-modes.basic +++ b/Task/Video-display-modes/Locomotive-Basic/video-display-modes.basic @@ -1 +1 @@ -10 MODE 0: REM switch to mode 0 +mode 0 ' switch to mode 0 diff --git a/Task/Video-display-modes/M2000-Interpreter/video-display-modes.m2000 b/Task/Video-display-modes/M2000-Interpreter/video-display-modes.m2000 new file mode 100644 index 0000000000..73753bad78 --- /dev/null +++ b/Task/Video-display-modes/M2000-Interpreter/video-display-modes.m2000 @@ -0,0 +1,40 @@ +GLOBAL OLDMODE +WINDOW MODE, WINDOW +MODULE SET_RES (X, Y) { + OLDMODE<=MODE + SCREEN.PIXELS X, Y + WINDOW 6, X*TWIPSX, Y*TWIPSY + FORM 60, 40 + FORM ; + MOTION (X*TWIPSX-SCALE.X) DIV 2, (Y*TWIPSY-SCALE.Y) DIV 2 + BACK {CLS 0,0:REFRESH} +} +MODULE RESTRORE_RES { + SCREEN.PIXELS ! + WINDOW OLDMODE, WINDOW +} + +SET_RES 1024, 768 +PRINT "RES 1024X768" +PRINT "WIDTH:";WIDTH +PRINT "HEIGHT:";HEIGHT +fOR I=1 TO 500: PRINT ""+(I MOD 10);: NEXT +PRINT "PRESS ANY KEY" +A$=KEY$ +RESTRORE_RES +WINDOW MODE, 0 +PRINT "PRESS ANY KEY" +A$=KEY$ +PRINT "WAIT..." +WHILE INKEY$<>"" + WAIT 50 +END WHILE +SET_RES 1280, 800 +PRINT "RES 1280X800" +PRINT "WIDTH:";WIDTH +PRINT "HEIGHT:";HEIGHT +fOR I=1 TO 500: PRINT ""+(I MOD 10);: NEXT +PRINT "PRESS ANY KEY" +A$=KEY$ +RESTRORE_RES +WINDOW MODE, 0 diff --git a/Task/Video-display-modes/QBasic/video-display-modes.basic b/Task/Video-display-modes/QBasic/video-display-modes.basic index 81dafd66b9..1e316298d1 100644 --- a/Task/Video-display-modes/QBasic/video-display-modes.basic +++ b/Task/Video-display-modes/QBasic/video-display-modes.basic @@ -1,2 +1 @@ -'QBasic can switch VGA modes -SCREEN 18 'Mode 12h 640x480 16 colour graphics +SCREEN 13 ' use 320x200 pixels, 40x25 characters, 256 colors diff --git a/Task/Video-display-modes/Wren/video-display-modes-2.wren b/Task/Video-display-modes/Wren/video-display-modes-2.wren deleted file mode 100644 index d834210a12..0000000000 --- a/Task/Video-display-modes/Wren/video-display-modes-2.wren +++ /dev/null @@ -1,66 +0,0 @@ -/* gcc Video_display_modes.c -o Video_display_modes -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -void C_xrandr(WrenVM* vm) { - const char *arg = wrenGetSlotString(vm, 1); - char command[strlen(arg) + 8]; - strcpy(command, "xrandr "); - strcat(command, arg); - system(command); -} - -void C_usleep(WrenVM* vm) { - useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1); - usleep(usec); -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "C") == 0) { - if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr; - if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.bindForeignMethodFn = &bindForeignMethod; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Video_display_modes.wren"; - char *script = readFile(fileName); - wrenInterpret(vm, module, script); - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Video-display-modes/Wren/video-display-modes-1.wren b/Task/Video-display-modes/Wren/video-display-modes.wren similarity index 50% rename from Task/Video-display-modes/Wren/video-display-modes-1.wren rename to Task/Video-display-modes/Wren/video-display-modes.wren index 81433e1a32..cd523426f7 100644 --- a/Task/Video-display-modes/Wren/video-display-modes-1.wren +++ b/Task/Video-display-modes/Wren/video-display-modes.wren @@ -1,22 +1,17 @@ -/* Video_display_modes.wren */ - -class C { - foreign static xrandr(args) - - foreign static usleep(usec) -} +import "os" for Process +import "timer" for Timer // query supported display modes -C.xrandr("-q") +Process.exec("xrandr -q") -C.usleep(3000) +Timer.wait(3000) // change display mode to 1368x768 System.print("\nChanging to 1368 x 768 mode.") -C.xrandr("-s 1368x768") +Process.exec("xrandr -s 1368x768") -C.usleep(3000) +Timer.wait(3000) // change it back again to 1920x1080 System.print("\nReverting to 1920 x 1080 mode.") -C.xrandr("-s 1920x1080") +Process.exec("xrandr -s 1920x1080") diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Fortran/vigen-re-cipher-cryptanalysis.f b/Task/Vigen-re-cipher-Cryptanalysis/Fortran/vigen-re-cipher-cryptanalysis.f new file mode 100644 index 0000000000..498a7ea28d --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Fortran/vigen-re-cipher-cryptanalysis.f @@ -0,0 +1,224 @@ +module vigenere_cipher + use, intrinsic :: iso_fortran_env, only: real64, int32 + implicit none + + private + public :: vigenere_decrypt + + type :: FreqPair + character :: c + real(real64) :: freq + end type FreqPair + +contains + + function frequency(input_text, input_len) result(freq_result) + integer(int32), intent(in) :: input_text(:), input_len + type(FreqPair), allocatable :: freq_result(:) + integer :: i + + allocate(freq_result(26)) + do i = 1, 26 + freq_result(i)%c = achar(64 + i) + freq_result(i)%freq = 0.0_real64 + end do + + do i = 1, input_len + freq_result(input_text(i) - 64)%freq = freq_result(input_text(i) - 64)%freq + 1 + end do + end function frequency + + function correlation(input_text, input_len, sorted_targets) result(corr) + integer(int32), intent(in) :: input_text(:), input_len + real(real64), intent(in) :: sorted_targets(:) + real(real64) :: corr + type(FreqPair), allocatable :: freq(:) + integer :: i, j + type(FreqPair) :: temp + + freq = frequency(input_text, input_len) + + ! Sort freq by frequency + do i = 1, 25 + do j = i + 1, 26 + if (freq(j)%freq > freq(i)%freq) then + temp = freq(j) + freq(j) = freq(i) + freq(i) = temp + end if + end do + end do + + corr = 0.0_real64 + do i = 1, 26 + corr = corr + freq(i)%freq * sorted_targets(i) + end do + + deallocate(freq) + end function correlation + + subroutine vigenere_decrypt(target_freqs, encoded, out_key, out_text) + implicit none + real(real64), intent(in) :: target_freqs(:) + character(len=*), intent(in) :: encoded + character(len=:), allocatable, intent(out) :: out_key, out_text + integer(int32), allocatable :: cleaned(:) + integer :: cleaned_len, i, j, k, best_len, key_len, shift + real(real64) :: best_corr, corr, max_corr + real(real64), allocatable :: sorted_targets(:) + integer(int32), allocatable :: pieces(:), piece_lens(:), current_piece(:) + character(len=:), allocatable :: temp_key + + ! Clean input text + allocate(cleaned(len(encoded))) + cleaned_len = 0 + do i = 1, len(encoded) + if (encoded(i:i) >= 'A' .and. encoded(i:i) <= 'Z') then + cleaned_len = cleaned_len + 1 + cleaned(cleaned_len) = iachar(encoded(i:i)) + end if + end do + + ! Sort target frequencies + allocate(sorted_targets(26)) + sorted_targets = target_freqs + call sort_array(sorted_targets) + + ! Find best key length + best_len = 0 + best_corr = -100.0_real64 + + do key_len = 2,cleaned_len/20 + allocate(pieces(cleaned_len), piece_lens(key_len)) + pieces = cleaned + piece_lens = 0 + do j = 1, cleaned_len + piece_lens(mod(j-1, key_len) + 1) = piece_lens(mod(j-1, key_len) + 1) + 1 + end do + + corr = -0.5_real64 * key_len + do i = 1, key_len + allocate(current_piece(piece_lens(i))) + k = 0 + do j = i, cleaned_len, key_len + k = k + 1 + current_piece(k) = pieces(j) + end do + corr = corr + correlation(current_piece, piece_lens(i), sorted_targets) + deallocate(current_piece) + end do + + if (corr > best_corr) then + best_len = key_len + best_corr = corr + end if + + deallocate(pieces, piece_lens) + end do + + ! Find key + allocate(character(len=best_len) :: temp_key) + do i = 1, best_len + allocate(pieces(cleaned_len/best_len + 1)) + k = 0 + do j = i, cleaned_len, best_len + k = k + 1 + pieces(k) = cleaned(j) + end do + + max_corr = 0.0_real64 + do concurrent (shift = 0:25) + corr = 0.0_real64 + do j = 1, k + corr = corr + target_freqs(mod(pieces(j) - 65 - shift + 26, 26) + 1) + end do + if (corr > max_corr) then + max_corr = corr + temp_key(i:i) = achar(shift + 65) + end if + end do + deallocate(pieces) + end do + out_key = temp_key + + ! Decrypt + allocate(character(len=cleaned_len) :: out_text) + do i = 1, cleaned_len + k = iachar(out_key(mod(i-1, best_len) + 1:mod(i-1, best_len) + 1)) - 65 + out_text(i:i) = achar(mod(cleaned(i) - 65 - k + 26, 26) + 65) + end do + end subroutine vigenere_decrypt + + subroutine sort_array(arr) + real(real64), intent(inout) :: arr(:) + integer :: i, j + real(real64) :: temp + + do i = 1, size(arr) - 1 + do j = i + 1, size(arr) + if (arr(j) > arr(i)) then + temp = arr(j) + arr(j) = arr(i) + arr(i) = temp + end if + end do + end do + end subroutine sort_array + +end module vigenere_cipher + +program main + use vigenere_cipher + use, intrinsic :: iso_fortran_env, only: real64 + implicit none + + real(real64) :: english_freqs(26) = [ & + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, & + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, & + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, & + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 ] + + character(len=*), parameter :: encoded = & + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" // & + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" // & + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" // & + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" // & + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" // & + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" // & + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" // & + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" // & + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" // & + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" // & + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" // & + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" // & + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" // & + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" // & + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" // & + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" // & + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK" + + character(len=:), allocatable :: key, decoded + integer :: xx,yy + call system_clock(count=xx) + + call vigenere_decrypt(english_freqs, encoded, key, decoded) + call system_clock(count=yy) + + print *, "Key: ", key + print *, "Decoded text: " + +block + INTEGER :: start, end, length, chunk_size + ! Define the chunk size + chunk_size = 80 + ! Get the length of the string + length = LEN_TRIM(decoded) + + ! Print the string in chunks of 80 characters + DO start = 1, length, chunk_size + end = MIN(start + chunk_size - 1, length) + PRINT *, decoded(start:end) + END DO +end block + print '(/,a,1x,i0,1x,a)', 'Decoded in =',(yy-xx), 'milliseconds' +end program main diff --git a/Task/Vigen-re-cipher-Cryptanalysis/FreeBASIC/vigen-re-cipher-cryptanalysis.basic b/Task/Vigen-re-cipher-Cryptanalysis/FreeBASIC/vigen-re-cipher-cryptanalysis.basic new file mode 100644 index 0000000000..d38b66c9a7 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/FreeBASIC/vigen-re-cipher-cryptanalysis.basic @@ -0,0 +1,168 @@ +Type FreqPair + As String * 1 c + As Double freq +End Type + +Function frequency(inputText() As Integer, inputLen As Integer) As FreqPair Ptr + Dim As FreqPair Ptr result = Callocate(26 * Sizeof(FreqPair)) + Dim As Integer i + + For i = 0 To 25 + result[i].c = Chr(65 + i) + result[i].freq = 0.0 + Next + + For i = 0 To inputLen - 1 + result[inputText(i) - 65].freq += 1 + Next + + Return result +End Function + +Function correlation(inputText() As Integer, inputLen As Integer, sorted_targets() As Double) As Double + Dim As FreqPair Ptr freq = frequency(inputText(), inputLen) + Dim As Integer i, j + Dim As Double result = 0.0 + + 'Sort freq by frequency + For i = 0 To 24 + For j = i + 1 To 25 + If freq[j].freq > freq[i].freq Then Swap freq[j], freq[i] + Next + Next + + For i = 0 To 25 + result += freq[i].freq * sorted_targets(i) + Next + + Deallocate(freq) + Return result +End Function + +Sub vigenereDecrypt(targetFreqs() As Double, encoded As String, Byref outKey As String, Byref outText As String) + Dim As Integer cleaned(Len(encoded)) + Dim As Integer cleanedLen = 0 + Dim As Integer i, j, k + + 'Clean inputText + For i = 1 To Len(encoded) + Dim As String c = Mid(encoded, i, 1) + If c >= "A" And c <= "Z" Then + cleaned(cleanedLen) = Asc(c) + cleanedLen += 1 + End If + Next + + 'Sort target frequencies + Dim As Double sorted_targets(25) + For i = 0 To 25 + sorted_targets(i) = targetFreqs(i) + Next + For i = 0 To 24 + For j = i + 1 To 25 + If sorted_targets(j) > sorted_targets(i) Then Swap sorted_targets(j), sorted_targets(i) + Next + Next + + 'Find best key length + Dim As Integer bestLen = 0 + Dim As Double bestCorr = -100.0 + + For keyLen As Integer = 2 To cleanedLen \ 20 + Dim As Integer pieces(cleanedLen) + Dim As Integer pieceLens(keyLen) + + For j = 0 To cleanedLen - 1 + pieces(j) = cleaned(j) + pieceLens(j Mod keyLen) += 1 + Next + + Dim As Double corr = -0.5 * keyLen + For i = 0 To keyLen - 1 + Dim As Integer currentPiece(cleanedLen) + Dim As Integer currentLen = 0 + + For j = i To cleanedLen - 1 Step keyLen + currentPiece(currentLen) = pieces(j) + currentLen += 1 + Next + + corr += correlation(currentPiece(), currentLen, sorted_targets()) + Next + + If corr > bestCorr Then + bestLen = keyLen + bestCorr = corr + End If + Next + + 'Find key + outKey = "" + For i = 0 To bestLen - 1 + Dim As Integer piece(cleanedLen) + Dim As Integer pieceLen = 0 + + For j = i To cleanedLen - 1 Step bestLen + piece(pieceLen) = cleaned(j) + pieceLen += 1 + Next + + Dim As Double maxCorr = 0.0 + Dim As Integer bestShift = 0 + + For shift As Integer = 0 To 25 + Dim As Double corr = 0.0 + For j = 0 To pieceLen - 1 + k = (piece(j) - 65 - shift + 26) Mod 26 + corr += targetFreqs(k) + Next + If corr > maxCorr Then + maxCorr = corr + bestShift = shift + End If + Next + + outKey += Chr(bestShift + 65) + Next + + 'Decrypt + outText = "" + For i = 0 To cleanedLen - 1 + k = Asc(Mid(outKey, (i Mod bestLen) + 1, 1)) - 65 + outText &= Chr(((cleaned(i) - 65 - k + 26) Mod 26) + 65) + Next +End Sub + +'Main program +Dim As Double english_freqs(25) = { _ +0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, _ +0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, _ +0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, _ +0.00978, 0.02360, 0.00150, 0.01974, 0.00074 } + +Dim As String encoded = _ +"MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" & _ +"VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" & _ +"ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" & _ +"FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" & _ +"ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" & _ +"ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" & _ +"JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" & _ +"LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" & _ +"MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" & _ +"QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" & _ +"RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" & _ +"TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" & _ +"SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" & _ +"ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" & _ +"BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" & _ +"BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" & _ +"FWAML ZZRXJ EKAHV FASMU LVVUT TGK" + +Dim As String key, decoded +vigenereDecrypt(english_freqs(), encoded, key, decoded) + +Print "Key: "; key +Print !"\nDecoded text: "; decoded + +Sleep diff --git a/Task/Water-collected-between-towers/EDSAC-order-code/water-collected-between-towers.edsac b/Task/Water-collected-between-towers/EDSAC-order-code/water-collected-between-towers.edsac index ea13eafe15..78d12e5dc2 100644 --- a/Task/Water-collected-between-towers/EDSAC-order-code/water-collected-between-towers.edsac +++ b/Task/Water-collected-between-towers/EDSAC-order-code/water-collected-between-towers.edsac @@ -1,12 +1,12 @@ [Water collected between towers - Rosetta Code For EDSAC, Initial Orders 2.] - [Arrange the storage] - T45K P100F [H parameter: library subroutine R4 to read integer] - T46K P200F [N parameter: modified library s/r P7 to print integer] - T47K P300F [M parameter: main routine] - T48K P900F [& (delta) parameter: store for array of heights] - T49K P400F [L parameter: subroutine to calculate amount of water] + [Arrange the storage] + T45K P100F [H parameter: library subroutine R4 to read integer] + T46K P200F [N parameter: modified library s/r P7 to print integer] + T47K P300F [M parameter: main routine] + T48K P900F [& (delta) parameter: store for array of heights] + T49K P400F [L parameter: subroutine to calculate amount of water] [----------------------------------------------------------------------- Subroutine to calculate amount of water as a 35-bit integer. Heights are in an array of 35-bit integers, preceded by a count of heights. @@ -76,7 +76,7 @@ [71] AF S94#@ G77@ A94#@ T94#@ E81@ [77] T4D AD S4D TD [81] A71@ S92@ T71@ A93@ S71@ G70@ -[Exit from suubroutine] +[Exit from subroutine] [87] T4F [clear acc on exit, as usual] [88] ZF [(planted) jump back to caller] [Constants] @@ -95,7 +95,7 @@ [3] P2F [to change address by 2] [4] #F [figure shift] [5] K2048F [letter shift] - [6] DF[7] IF[8] YF + [6] DF [7] IF [8] YF [letters D I Y] [9] NF [comma (in figures mode)] [10] @F [carriage return] [11] &F [line feed] @@ -110,8 +110,8 @@ A23@ T40@ [initialize T order to store data] AD [load data count, 35-bit but with high half = 0] [23] T#& [store at start of data] - [24] S& [acc := 17-bit negative count of data] - [25] LD [shift to address field *** or use k1 to inc ?? ***] + [24] S& [acc := 17-bit negative data count; also letter S] + [25] LD [shift to address field; also letter L] G28@ [don't print comma before first height] [Loop over heights in current dataset] [27] O9@ [print comma] @@ -130,7 +130,7 @@ O25@ O6@ O24@ O12@ O4@ A57@ GN !1F [print result, min width = 1; leaves acc = 0] O10@ O11@ [print CR, LF] - [62] E15@ [loop back for next data set (also letter E)] + [62] E15@ [loop back for next data set; also letter E] [Jump to here if data count = 0, means end of data] [63] O13@ [print null to flush teleprinter buffer] ZF [stop the machine] @@ -138,7 +138,7 @@ Library subroutine R4. Input of one signed integer, returned in 0D.] E25K TH - GK A3F T21@ T4D H6@ E11@ P5D JF T6F VD L4F A4D TD I4F A4F S5@ G7@ S5@ G20@ SD TD T6F EF + GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF [------------------------------------------------------------------------------- Modification of library subroutine P7; prints integer N in range 0 <= N < 10^10. Prints 0 correctly, and allows caller to specify a minimum width. @@ -147,7 +147,9 @@ e.g. !5F means minimum width 5, pad on left with space. 49 locations; even address; workspace: 0F, 1F, 4D, 6F, 7F] E25K TN - GK A48@ U4@ A27@ T35@ AF U4@ L256F S45@ T7F H46#@ ND YF LD T4D S45@ T1F H21@ S21@ A45@ G21@ U4@ TF V4D A1F G36@ S1F LD U1F O1F F1F S1F L4F T4D AF G18@ ZF S1F L8F T4D AF A7F G43@ O4@ T6F E33@ T46#Z PF T45Z P1024F P610D @524D P2F + GKA48@U4@A27@T35@AFU4@L256FS45@T7FH46#@NDYFLDT4DS45@T1FH21@ + S21@A45@G21@U4@TFV4DA1FG36@S1FLDU1FO1FF1FS1FL4FT4DAFG18@ZF + S1FL8FT4DAFA7FG43@O4@T6FE33@T46#ZPFT45ZP1024FP610D@524DP2F [--------------------------------------------------------------------------------] [M parameter (main routine) again] E25K TM GK diff --git a/Task/Web-scraping/FreeBASIC/web-scraping.basic b/Task/Web-scraping/FreeBASIC/web-scraping.basic deleted file mode 100644 index 2a91f1e17a..0000000000 --- a/Task/Web-scraping/FreeBASIC/web-scraping.basic +++ /dev/null @@ -1,66 +0,0 @@ -#include "windows.bi" -#include "win/wininet.bi" - -Const BUFFER_SIZE = 4096 - -Function GetWebPage(url As String) As String - Dim As HINTERNET hInternet = InternetOpen("TimeGetter", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0) - Dim As String resultado = "" - - If hInternet Then - Dim As HINTERNET hConnect = InternetOpenUrl(hInternet, url, NULL, 0, INTERNET_FLAG_RELOAD, 0) - - If hConnect Then - Dim As String buffer = Space(BUFFER_SIZE) - Dim As DWORD bytesRead - - Do - If InternetReadFile(hConnect, Strptr(buffer), BUFFER_SIZE, @bytesRead) Then - If bytesRead = 0 Then Exit Do - resultado &= Left(buffer, bytesRead) - End If - Loop - - InternetCloseHandle(hConnect) - End If - InternetCloseHandle(hInternet) - End If - - Return resultado -End Function - -Function ScrapeTime(pageAddress As String, timeZone As String) As String - Dim As String page = GetWebPage(pageAddress) - - If Len(page) = 0 Then Return "Cannot connect" - - Dim As Integer startPos = 1 - Do - Dim As Integer endPos = Instr(startPos, page, "
") - If endPos = 0 Then endPos = Len(page) - - Dim As String linea = Mid(page, startPos, endPos - startPos) - - If Instr(linea, timeZone) Then - For i As Integer = 1 To Len(linea) - 7 - Dim As String char1 = Mid(linea, i, 1) - Dim As String char2 = Mid(linea, i+4, 1) - If char1 >= "0" And char1 <= "9" And Mid(linea, i+2, 1) = ":" And _ - char2 >= "0" And char2 <= "9" And Mid(linea, i+5, 1) = ":" Then - Return Mid(linea, i, 8) - End If - Next - End If - - If endPos = Len(page) Then Exit Do - startPos = endPos + 4 - Loop - - Return "Time not found" -End Function - -' Main program -Dim As String url = "https://rosettacode.org/wiki/Talk:Web_scraping" -Print ScrapeTime(url, "UTC") - -Sleep diff --git a/Task/Web-scraping/Wren/web-scraping-1.wren b/Task/Web-scraping/Wren/web-scraping-1.wren deleted file mode 100644 index 60bded3b8e..0000000000 --- a/Task/Web-scraping/Wren/web-scraping-1.wren +++ /dev/null @@ -1,48 +0,0 @@ -/* Web_scraping.wren */ - -import "./pattern" for Pattern - -var CURLOPT_URL = 10002 -var CURLOPT_FOLLOWLOCATION = 52 -var CURLOPT_WRITEFUNCTION = 20011 -var CURLOPT_WRITEDATA = 10001 - -var BUFSIZE = 16384 * 4 - -foreign class Buffer { - construct new(size) {} - - // returns buffer contents as a string - foreign value -} - -foreign class Curl { - construct easyInit() {} - - foreign easySetOpt(opt, param) - - foreign easyPerform() - - foreign easyCleanup() -} - -var buffer = Buffer.new(BUFSIZE) -var curl = Curl.easyInit() -curl.easySetOpt(CURLOPT_URL, "https://rosettacode.org/wiki/Talk:Web_scraping") -curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1) -curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C -curl.easySetOpt(CURLOPT_WRITEDATA, buffer) - -curl.easyPerform() -curl.easyCleanup() - -var html = buffer.value -var ix = html.indexOf("(UTC)") -ix = html.indexOf("(UTC)", ix + 1) // skip the site notice -if (ix == -1) { - System.print("UTC time not found.") - return -} -var p = Pattern.new("/d/d:/d/d, #12/d +1/a =4/d") -var m = p.find(html[(ix - 30).max(0)...ix]) -System.print(m.text) diff --git a/Task/Web-scraping/Wren/web-scraping-2.wren b/Task/Web-scraping/Wren/web-scraping-2.wren deleted file mode 100644 index 67ab072199..0000000000 --- a/Task/Web-scraping/Wren/web-scraping-2.wren +++ /dev/null @@ -1,173 +0,0 @@ -/* gcc Web_scraping.c -o Web_scraping -lcurl -lwren -lm */ - -#include -#include -#include -#include -#include "wren.h" - -/* C <=> Wren interface functions */ - -char *url, *read_file, *write_file; - -size_t bufsize; -size_t lr = 0; - -size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream) { - if ((lr + size*nmemb) > bufsize) return bufsize; - memcpy(stream+lr, ptr, size * nmemb); - lr += size * nmemb; - return size * nmemb; -} - -void C_bufferAllocate(WrenVM* vm) { - bufsize = (int)wrenGetSlotDouble(vm, 1); - wrenSetSlotNewForeign(vm, 0, 0, bufsize); -} - -void C_curlAllocate(WrenVM* vm) { - CURL** pcurl = (CURL**)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CURL*)); - *pcurl = curl_easy_init(); -} - -void C_value(WrenVM* vm) { - const char *s = (const char *)wrenGetSlotForeign(vm, 0); - wrenSetSlotString(vm, 0, s); -} - -void C_easyPerform(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_perform(curl); -} - -void C_easyCleanup(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - curl_easy_cleanup(curl); -} - -void C_easySetOpt(WrenVM* vm) { - CURL* curl = *(CURL**)wrenGetSlotForeign(vm, 0); - CURLoption opt = (CURLoption)wrenGetSlotDouble(vm, 1); - if (opt < 10000) { - long lparam = (long)wrenGetSlotDouble(vm, 2); - curl_easy_setopt(curl, opt, lparam); - } else if (opt < 20000) { - if (opt == CURLOPT_WRITEDATA) { - char *buffer = (char *)wrenGetSlotForeign(vm, 2); - curl_easy_setopt(curl, opt, buffer); - } else if (opt == CURLOPT_URL) { - const char *url = wrenGetSlotString(vm, 2); - curl_easy_setopt(curl, opt, url); - } - } else if (opt < 30000) { - if (opt == CURLOPT_WRITEFUNCTION) { - curl_easy_setopt(curl, opt, &filterit); - } - } -} - -WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) { - WrenForeignClassMethods methods; - methods.allocate = NULL; - methods.finalize = NULL; - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - methods.allocate = C_bufferAllocate; - } else if (strcmp(className, "Curl") == 0) { - methods.allocate = C_curlAllocate; - } - } - return methods; -} - -WrenForeignMethodFn bindForeignMethod( - WrenVM* vm, - const char* module, - const char* className, - bool isStatic, - const char* signature) { - if (strcmp(module, "main") == 0) { - if (strcmp(className, "Buffer") == 0) { - if (!isStatic && strcmp(signature, "value") == 0) return C_value; - } else if (strcmp(className, "Curl") == 0) { - if (!isStatic && strcmp(signature, "easySetOpt(_,_)") == 0) return C_easySetOpt; - if (!isStatic && strcmp(signature, "easyPerform()") == 0) return C_easyPerform; - if (!isStatic && strcmp(signature, "easyCleanup()") == 0) return C_easyCleanup; - } - } - return NULL; -} - -static void writeFn(WrenVM* vm, const char* text) { - printf("%s", text); -} - -void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) { - switch (errorType) { - case WREN_ERROR_COMPILE: - printf("[%s line %d] [Error] %s\n", module, line, msg); - break; - case WREN_ERROR_STACK_TRACE: - printf("[%s line %d] in %s\n", module, line, msg); - break; - case WREN_ERROR_RUNTIME: - printf("[Runtime Error] %s\n", msg); - break; - } -} - -char *readFile(const char *fileName) { - FILE *f = fopen(fileName, "r"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - rewind(f); - char *script = malloc(fsize + 1); - fread(script, 1, fsize, f); - fclose(f); - script[fsize] = 0; - return script; -} - -static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) { - if( result.source) free((void*)result.source); -} - -WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) { - WrenLoadModuleResult result = {0}; - if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) { - result.onComplete = loadModuleComplete; - char fullName[strlen(name) + 6]; - strcpy(fullName, name); - strcat(fullName, ".wren"); - result.source = readFile(fullName); - } - return result; -} - -int main(int argc, char **argv) { - WrenConfiguration config; - wrenInitConfiguration(&config); - config.writeFn = &writeFn; - config.errorFn = &errorFn; - config.bindForeignClassFn = &bindForeignClass; - config.bindForeignMethodFn = &bindForeignMethod; - config.loadModuleFn = &loadModule; - WrenVM* vm = wrenNewVM(&config); - const char* module = "main"; - const char* fileName = "Web_scraping.wren"; - char *script = readFile(fileName); - WrenInterpretResult result = wrenInterpret(vm, module, script); - switch (result) { - case WREN_RESULT_COMPILE_ERROR: - printf("Compile Error!\n"); - break; - case WREN_RESULT_RUNTIME_ERROR: - printf("Runtime Error!\n"); - break; - case WREN_RESULT_SUCCESS: - break; - } - wrenFreeVM(vm); - free(script); - return 0; -} diff --git a/Task/Web-scraping/Wren/web-scraping.wren b/Task/Web-scraping/Wren/web-scraping.wren new file mode 100644 index 0000000000..74bf5a466e --- /dev/null +++ b/Task/Web-scraping/Wren/web-scraping.wren @@ -0,0 +1,13 @@ +import "os" for Process +import "./pattern" for Pattern + +var page = "https://rosettacode.org/wiki/Talk:Web_scraping" +var html = Process.read("curl -s %(page)") +var ix = html.indexOf("(UTC)") +if (ix == -1) { + System.print("UTC time not found.") + return +} +var p = Pattern.new("/d/d:/d/d, #12/d +1/a =4/d") +var m = p.find(html[(ix - 30).max(0)...ix]) +System.print(m.text) diff --git a/Task/Weird-numbers/Arturo/weird-numbers.arturo b/Task/Weird-numbers/Arturo/weird-numbers.arturo new file mode 100644 index 0000000000..262fc7f6e2 --- /dev/null +++ b/Task/Weird-numbers/Arturo/weird-numbers.arturo @@ -0,0 +1,47 @@ +semiperfect?: function [facts number].memoize [ + sumAll: sum facts + + if sumAll = number -> return true + if sumAll < number -> return false + + current: first facts + remaining: drop facts + + if number < current -> return semiperfect? remaining number + if number = current -> return true + + if semiperfect? remaining number-current -> return true + return semiperfect? remaining number +] + +findWeirdNumbers: function [limit][ + sieve: repeat false limit + + loop 2..limit-1 'num [ + unless sieve\[num][ + divisors: (factors num) -- num + sumDivisors: sum divisors + + (sumDivisors =< num)? [ + sieve\[num]: true + ][ + if semiperfect? divisors num [ + j: num + while [j < limit][ + sieve\[j]: true + j: j + num + ] + ] + ] + ] + ] + + return drop.times:2 sieve +] + +print "The first 25 weird numbers:" + +(findWeirdNumbers 17000) | map.with:'i 'x -> @[i+2,x] + | select.first: 25 => [not? last &] + | map => [first &] + | print diff --git a/Task/Weird-numbers/YAMLScript/weird-numbers.ys b/Task/Weird-numbers/YAMLScript/weird-numbers.ys index 2bf68a1df2..7d70463afd 100644 --- a/Task/Weird-numbers/YAMLScript/weird-numbers.ys +++ b/Task/Weird-numbers/YAMLScript/weird-numbers.ys @@ -1,4 +1,4 @@ -!yamlscript/v0 +!YS-v0 defn main(max=16500): weird =: sieve(max) diff --git a/Task/Wieferich-primes/Ring/wieferich-primes.ring b/Task/Wieferich-primes/Ring/wieferich-primes.ring new file mode 100644 index 0000000000..fc2d11c4b6 --- /dev/null +++ b/Task/Wieferich-primes/Ring/wieferich-primes.ring @@ -0,0 +1,27 @@ +load "stdlib.ring" + +see "working..." + nl + +for i = 1 to 5000 + if isWeiferich(i) + see "" + i + nl + ok +next + +see "done..." + nl + +function isWeiferich(p) + if not isPrime(p) + return False + ok + q = 1 + p2 = pow(p,2) + while p > 1 + q = (2 * q) % p2 + p -= 1 + end + if q = 1 + return True + else + return False + ok diff --git a/Task/Window-creation/XPL0/window-creation.xpl0 b/Task/Window-creation/XPL0/window-creation.xpl0 index 00479559c2..acd120e96f 100644 --- a/Task/Window-creation/XPL0/window-creation.xpl0 +++ b/Task/Window-creation/XPL0/window-creation.xpl0 @@ -1,43 +1,38 @@ -\12345678901234567890123456789012345 -\Window creation............... X . +\012345678901234567890123456789012345 +\ Window creation............... X . -def X0=20, Y0=10; \upper-left corner of window's position (chars) -int Mouse, Button, C; +def X0=20, Y0=10; \position of upper-left corner of window (chars) +int Mouse, Button, X, Y; func GetButton; \Return soft button number at mouse pointer -int X, Y; -[Mouse:= GetMouse; -X:= Mouse(0)/8 - X0; \convert pixels to char cells +[Mouse:= GetMouse; \get pointer to mouse array information +X:= Mouse(0)/8 - X0; \convert pixels to 8x16-pixel character cells Y:= Mouse(1)/16 - Y0; -if X>=32 & X<=34 & Y=0 then return 0; \exit [X] +if X>=32 & X<=34 & Y=0 then return 0; \exit [X] return -1; \mouse not on any soft button ]; -[SetVid($12); \640x480 graphics -TrapC(true); \disable Ctrl+C -Attrib($70); \black on gray -SetWind(0+X0, 0+Y0, 35+X0, 8+Y0, 0, \fill\true); -Cursor(33+X0, 0+Y0); Text(6, "X"); - -Attrib($1F); \bright white on blue, for title +[SetVid($12); \set 640x480 graphics +TrapC(true); \prevent Ctrl+C from aborting the program +Attrib($70); \set black-on-gray color attribute +SetWind(0+X0, 0+Y0, 35+X0, 8+Y0, 0, \fill\true); \draw gray rectangle +Cursor(33+X0, 0+Y0); Text(6, "X"); \draw exit button +Attrib($9F); \set bright white on light blue, for title bar Cursor(0+X0, 0+Y0); Text(6, " Window creation "); - -ShowMouse(true); +ShowMouse(true); \turn on mouse pointer loop [MoveMouse; \make pointer track mouse movements - Mouse:= GetMouse; + Mouse:= GetMouse; \get pointer to mouse array information if Mouse(2) then \a left or right mouse button is down [Button:= GetButton; \get soft button at mouse pointer - while Mouse(2) do \wait for mouse button's release + while Mouse(2) do \wait for mouse button(s) to be released [MoveMouse; Mouse:= GetMouse; ]; - if Button = GetButton then \if down Button = release button - if Button = 0 then quit; - ]; - if KeyHit then - [C:= ChIn(1); \get character from non-echoed keyboard - if C = \Esc\$1B then quit; + if Button = GetButton then \if down Button = release button and it + if Button = 0 then quit; \is the exit [X] button then quit loop ]; + if KeyHit then \get character from non-echoed keyboard + if ChIn(1) = \Esc\$1B then quit; \Esc key also exits program ]; SetVid(3); \restore normal text mode immediately ] diff --git a/Task/Window-management/M2000-Interpreter/window-management.m2000 b/Task/Window-management/M2000-Interpreter/window-management.m2000 new file mode 100644 index 0000000000..15503b0c16 --- /dev/null +++ b/Task/Window-management/M2000-Interpreter/window-management.m2000 @@ -0,0 +1,63 @@ +Module WindowManagment{ + Declare Form1 Form + With Form1, "UseIcon", True, "UseReverse", True + With Form1, "Title" As Caption$, "Visible" As Visible,"TitleHeight" As tHeight + With Form1, "Sizable", True, "Height" as WHeight, "Width" as WWidth + Print "First Window Caption: ";Caption$ + Print "Title Height: ";tHeight + Print "Window Width: ";WWidth + Print "Window Height: ";WHeight + NotNow=true + Function Form1.Unload { + Read New &Ok + if NotNow Else visible=false + Ok=true + } + Caption$="Window Managment" + Print "Show - no modal" + Method Form1,"Show" ' , 1 for modal opening + Wait 3000 + Print "Show on TaskBar also" + Method Form1,"ShowTaskBar" + Wait 5000 ' 10 second + Print "Minimize Window" + Method form1,"Minimize" + Wait 2000 + Print "Show again" + Method Form1, "Show" + Wait 3000 + Print "Maximize Window" + Method Form1, "Maximize", true as res + print res + Wait 5000 + Print "Restore to normal" + Method Form1, "Maximize", false as res + print res + Wait 5000 + Print "Move Window to 0,0" + Method Form1, "Show" + Method Form1, "move", 0,0 ', 6000, Wheight*2 + Wait 5000 + Print "Resize Window" + NotNow=false + Method Form1, "move", 0,0 , WWidth*1.5, Wheight*2 + Print "Click Unload (is a fake unload)" + profiler ' hires timer + do + Wait 10 + Until timecount>5000 or not visible + visible=false + Wait 3000 + Print "Modal view - Wait user to close window" + Print "Click Unload - isn't fake now" + ' We have an event to stop unloading + ' Modal show just release inner loop when we press unload + Method Form1,"Show", 1 'for modal opening + wait 5000 + ' to prove it lets show window again + print "ho ho ho - last time...Click Unload" + Method Form1,"Show", 1 'for modal opening + ' So here we unload the Form1 by software + Declare Form1 Nothing +} +WindowManagment diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-1.pas similarity index 100% rename from Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file.pas rename to Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-1.pas diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-2.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-2.pas new file mode 100644 index 0000000000..da3d6b5d84 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-2.pas @@ -0,0 +1,3 @@ +create or replace table t (x DOUBLE, y DOUBLE); + +insert into t select unnest ([1, 2, 3, 1e11]) as x, sqrt(x) as y; diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-3.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-3.pas new file mode 100644 index 0000000000..70596cc0cf --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-3.pas @@ -0,0 +1,6 @@ +.header off +.mode list +.output output.tsv +select format('{:.3f}', x) || chr(9) || format('{:.5f}', y) from t; +.output +.shell cat output.tsv diff --git a/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-4.pas b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-4.pas new file mode 100644 index 0000000000..c9fce11703 --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Delphi/write-float-arrays-to-a-text-file-4.pas @@ -0,0 +1,5 @@ +create or replace table neat (x DECIMAL(38,3), y DECIMAL(38,5)); +insert into neat from t; +from neat; +copy neat to 'output.tsv' (HEADER true, DELIMITER '\t'); +.shell cat output.tsv diff --git a/Task/Write-language-name-in-3D-ASCII/M2000-Interpreter/write-language-name-in-3d-ascii.m2000 b/Task/Write-language-name-in-3D-ASCII/M2000-Interpreter/write-language-name-in-3d-ascii.m2000 new file mode 100644 index 0000000000..6340d4d51f --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/M2000-Interpreter/write-language-name-in-3d-ascii.m2000 @@ -0,0 +1,19 @@ +Bold 0 +Font "COURIER NEW" +Form 74, 8; ' ; set linespace to 0 ' center form to current monitor +Form ' cut the border so only 74X8 lines on a non head window displayed +' ASCII ART - 3D LANGUAGE NAME +Desktop 200 ' Opacity at 200/255*100% +?" _______ ______ _______ _________ _________ _________" +?" |\ ___\/ ___ \ / __ /||\ ____ \ |\ ____ \ |\ ____ \" +?" \ \ \_|\__\_|\ \ /_/|_/ / |\ \ \___|\ \\ \ \___|\ \\ \ \___|\ \" +?" \ \ \\|__| \ \ \ |_|// / / \ \ \ \ \ \\ \ \ \ \ \\ \ \ \ \ \" +?" \ \ \ \ \ \ / /_/____\ \ \__\_\ \\ \ \__\_\ \\ \ \__\_\ \" +?" \ \__\ \ \__\ |\________\\ \________\\ \________\\ \________\" +?" \|__| \|__| \|________| \|________| \|________| \|________|" +Push Key$: Drop +Desktop 255 ' 100% opacity +Font "Verdana" +Bold 1 +Form; ' enable border - at screen size +Form 60, 32 diff --git a/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii-2.py b/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii-2.py index 45150d043c..b8acde2aae 100644 --- a/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii-2.py +++ b/Task/Write-language-name-in-3D-ASCII/Python/write-language-name-in-3d-ascii-2.py @@ -46,7 +46,6 @@ charSet4 = [ " |__/ \________/ |__/ ", ] -# ...then the sets are combined back by barbequing them together! charTable = [(charSet1[i] + charSet2[i] + charSet3[i] + diff --git a/Task/Yahoo-search-interface/FutureBasic/yahoo-search-interface.basic b/Task/Yahoo-search-interface/FutureBasic/yahoo-search-interface.basic new file mode 100644 index 0000000000..5fe89471b6 --- /dev/null +++ b/Task/Yahoo-search-interface/FutureBasic/yahoo-search-interface.basic @@ -0,0 +1,21 @@ +include "Tlbx WebKit.incl" + +_window = 1 +begin enum 1 + _webView +end enum + +void local fn BuildWindow + CGRect r = ( 0, 0, 700, 400 ) + window _window, @"WKWebView", r + + wkwebview _webView, r + ViewSetAutoresizingMask( _webView, NSViewWidthSizable + NSViewHeightSizable ) + CFURLRef url = fn URLWithString( @"https://search.yahoo.com/" ) + URLRequestRef request = fn URLRequestWithURL( url ) + fn WKWebViewLoadRequest( _webView, request ) +end fn + +fn BuildWindow + +HandleEvents diff --git a/Task/Yin-and-yang/Commodore-BASIC/yin-and-yang-4.basic b/Task/Yin-and-yang/Commodore-BASIC/yin-and-yang-4.basic new file mode 100644 index 0000000000..e0ba892dd3 --- /dev/null +++ b/Task/Yin-and-yang/Commodore-BASIC/yin-and-yang-4.basic @@ -0,0 +1,15 @@ +0 REM COMMANDER X-16 +10 SCREEN 128 +20 RECT 0,0,319,239,0 +30 X=100:Y=120:XR=98:YR=98:GOSUB 100 +40 X=260:Y=180:XR=48:YR=48:GOSUB 100 +50 GET K$: IF K$="" THEN 50 +60 END +100 OVAL X-XR,Y-YR,X+XR,Y+YR,1 +110 RECT X,Y-YR,X+YR,Y+YR,0 +120 OVAL X-XR/2,Y-YR,X+XR/2,Y,1 +130 OVAL X-XR/2,Y,X+XR/2,Y+YR,0 +140 RING X-XR,Y-YR,X+XR,Y+YR,1 +150 OVAL X-XR/8,Y-YR/2-YR/8,X+XR/8,Y-YR/2+YR/8,0 +160 OVAL X-XR/8,Y+YR/2-YR/8,X+XR/8,Y+YR/2+YR/8,1 +170 RETURN diff --git a/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic b/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic index d5f8fa7752..bbf3d40164 100644 --- a/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic +++ b/Task/Yin-and-yang/FreeBASIC/yin-and-yang.basic @@ -14,4 +14,5 @@ End Sub Taijitu(110, 110, 45) Taijitu(500, 300, 138) +Sleep End diff --git a/Task/Yin-and-yang/Nim/yin-and-yang.nim b/Task/Yin-and-yang/Nim/yin-and-yang.nim index efee2bee37..8f73b61fd3 100644 --- a/Task/Yin-and-yang/Nim/yin-and-yang.nim +++ b/Task/Yin-and-yang/Nim/yin-and-yang.nim @@ -1,24 +1,24 @@ -import gintro/cairo +import cairo -proc draw(ctx: Context; x, y, r: float) = +proc draw(ctx: ptr Context; x, y, r: float) = ctx.arc(x, y, r + 1, 1.571, 7.854) - ctx.setSource(0.0, 0.0, 0.0) + ctx.setSourceRgb(0.0, 0.0, 0.0) ctx.fill() ctx.arcNegative(x, y - r / 2, r / 2, 1.571, 4.712) ctx.arc(x, y + r / 2, r / 2, 1.571, 4.712) ctx.arcNegative(x, y, r, 4.712, 1.571) - ctx.setSource(1.0, 1.0, 1.0) + ctx.setSourceRgb(1.0, 1.0, 1.0) ctx.fill() ctx.arc(x, y - r / 2, r / 5, 1.571, 7.854) - ctx.setSource(0.0, 0.0, 0.0) + ctx.setSourceRgb(0.0, 0.0, 0.0) ctx.fill() ctx.arc(x, y + r / 2, r / 5, 1.571, 7.854) - ctx.setSource(1.0, 1.0, 1.0) + ctx.setSourceRgb(1.0, 1.0, 1.0) ctx.fill() -let surface = imageSurfaceCreate(argb32, 200, 200) -let context = newContext(surface) +let surface = imageSurfaceCreate(FormatArgb32, 200, 200) +let context = create(surface) context.draw(120, 120, 75) context.draw(35, 35, 30) let status = surface.writeToPng("yin-yang.png") -assert status == Status.success +assert status == StatusSuccess diff --git a/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh b/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh index d4b26c6e90..1d6a476124 100644 --- a/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh +++ b/Task/Yin-and-yang/UNIX-Shell/yin-and-yang.sh @@ -4,19 +4,19 @@ in_circle() { #(cx, cy, r, x y) # on (cx,cy) # (but really scaled to an ellipse with vertical minor semiaxis r and # horizontal major semiaxis 2r) - local -i cx=$1 cy=$2 r=$3 x=$4 y=$5 - local -i dx dy + typeset -i cx=$1 cy=$2 r=$3 x=$4 y=$5 + typeset -i dx dy (( dx=(x-cx)/2, dy=y-cy, dx*dx + dy*dy <= r*r )) } taijitu() { #radius - local -i radius=${1:-17} - local -i x1=0 y1=0 r1=radius # outer circle - local -i x2=0 y2=-radius/2 r2=radius/6 # upper eye - local -i x3=0 y3=-radius/2 r3=radius/2 # upper half - local -i x4=0 y4=+radius/2 r4=radius/6 # lower eye - local -i x5=0 y5=+radius/2 r5=radius/2 # lower half - local -i x y + typeset -i radius=${1:-17} + typeset -i x1=0 y1=0 r1=radius # outer circle + typeset -i x2=0 y2=-radius/2 r2=radius/6 # upper eye + typeset -i x3=0 y3=-radius/2 r3=radius/2 # upper half + typeset -i x4=0 y4=+radius/2 r4=radius/6 # lower eye + typeset -i x5=0 y5=+radius/2 r5=radius/2 # lower half + typeset -i x y for (( y=radius; y>=-radius; --y )); do for (( x=-2*radius; x<=2*radius; ++x)); do if ! in_circle $x1 $y1 $r1 $x $y; then diff --git a/Task/Zumkeller-numbers/Arturo/zumkeller-numbers.arturo b/Task/Zumkeller-numbers/Arturo/zumkeller-numbers.arturo new file mode 100644 index 0000000000..4e978ca0d6 --- /dev/null +++ b/Task/Zumkeller-numbers/Arturo/zumkeller-numbers.arturo @@ -0,0 +1,27 @@ +prettyPrint: function [data,cols,padding][ + data | split.every: cols + | map => [join map & 'x -> pad to :string x padding] + | print.lines +] + +zumkeller?: function [n][ + divSum: sum divs: <= factors n + if nand? [even? divSum][divSum >= 2*n] -> return false + + half: divSum/2 + loop 1..(size divs)/2 'combiSize [ + if some? combine.by:combiSize divs 'combo -> + half = sum combo -> + return true + ] + + return false +] + +print "First 220 Zumkeller numbers:" +(1..∞) | select.first: 220 => zumkeller? + | prettyPrint 14 4 + +print "\nFirst 40 odd Zumkeller numbers:" +(1..∞) | select.first: 40 'n -> and? [odd? n][zumkeller? n] + | prettyPrint 10 6 From 4d5544505c2cf7e9031498accb4b5833508d5896 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Wed, 11 Jun 2025 20:16:52 -0400 Subject: [PATCH 07/12] Data update --- Lang/8080-Assembly/Loops-Infinite | 1 + Lang/8080-Assembly/Run-length-encoding | 1 + Lang/8086-Assembly/00-LANG.txt | 52 +- Lang/ALGOL-60/Additive-primes | 1 + Lang/ALGOL-60/Largest-proper-divisor-of-n | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/ALGOL-60/Proper-divisors | 1 + .../Sequence-of-primes-by-trial-division | 1 + Lang/ALGOL-68/00-LANG.txt | 219 +-- Lang/ALGOL-68/Elliptic-curve-arithmetic | 1 + Lang/ALGOL-68/Permutation-test | 1 + ...---allocate-descendants-to-their-ancestors | 1 + Lang/ALGOL-68/Pythagoras-tree | 1 + Lang/ALGOL-68/Solve-a-Numbrix-puzzle | 1 + Lang/ALGOL-68/Solve-the-no-connection-puzzle | 1 + Lang/ALGOL-68/Text-processing-2 | 1 + .../Wasteful-equidigital-and-frugal-numbers | 1 + Lang/ALGOL-M/Additive-primes | 1 + Lang/ANSI-BASIC/Levenshtein-distance | 1 + Lang/ANSI-BASIC/M-bius-function | 1 + Lang/ANSI-BASIC/Magic-constant | 1 + Lang/ANSI-BASIC/Map-range | 1 + Lang/APL/Loops-Infinite | 1 + Lang/APL/Sort-a-list-of-object-identifiers | 1 + Lang/APL/Strip-comments-from-a-string | 1 + Lang/APL/Tic-tac-toe | 1 + Lang/ASIC/M-bius-function | 1 + Lang/Action-/00-LANG.txt | 2 +- Lang/Ada/Cistercian-numerals | 1 + Lang/Ada/Curzon-numbers | 1 + Lang/AppleScript/Bin-given-limits | 1 + Lang/AppleScript/Nth-root | 1 + .../Write-float-arrays-to-a-text-file | 1 + Lang/Applesoft-BASIC/Cistercian-numerals | 1 + Lang/Applesoft-BASIC/Formatted-numeric-output | 1 + Lang/Applesoft-BASIC/Levenshtein-distance | 1 + Lang/Applesoft-BASIC/Multi-dimensional-array | 1 + Lang/Applesoft-BASIC/Towers-of-Hanoi | 1 + Lang/Arturo/Arithmetic-derivative | 1 + Lang/Arturo/Dice-game-probabilities | 1 + Lang/Arturo/Element-wise-operations | 1 + Lang/Arturo/Entropy-Narcissist | 1 + Lang/Arturo/Munching-squares | 1 + Lang/Asymptote/Evaluate-binomial-coefficients | 1 + Lang/Atari-BASIC/Pi | 1 + Lang/AutoHotKey-V2/00-LANG.txt | 1 + Lang/AutoHotKey-V2/00-META.yaml | 2 + Lang/AutoHotKey-V2/Hello-world-Graphical | 1 + Lang/Autohotkey-V2/00-LANG.txt | 16 - Lang/Autohotkey-V2/00-META.yaml | 2 - Lang/Autohotkey-V2/Hello-world-Graphical | 1 - .../Partition-an-integer-x-into-n-primes | 1 + Lang/BASIC256/Evaluate-binomial-coefficients | 1 + Lang/BQN/Find-common-directory-path | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Ballerina/00-LANG.txt | 18 +- Lang/Ballerina/A+B | 1 + Lang/Ballerina/ABC-problem | 1 + Lang/Ballerina/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Ballerina/Abundant-odd-numbers | 1 + Lang/Ballerina/Accumulator-factory | 1 + Lang/Ballerina/Achilles-numbers | 1 + Lang/Ballerina/Ackermann-function | 1 + ...-a-variable-to-a-class-instance-at-runtime | 1 + Lang/Ballerina/Additive-primes | 1 + Lang/Ballerina/Address-of-a-variable | 1 + Lang/Ballerina/Almost-prime | 1 + Lang/Ballerina/Amb | 1 + .../Angle-difference-between-two-bearings | 1 + Lang/Ballerina/Anti-primes | 1 + Lang/Ballerina/Apply-a-callback-to-an-array | 1 + Lang/Ballerina/Approximate-equality | 1 + Lang/Ballerina/Arithmetic-Complex | 1 + Lang/Ballerina/Arithmetic-Integer | 1 + Lang/Ballerina/Arithmetic-Rational | 1 + Lang/Ballerina/Arithmetic-numbers | 1 + Lang/Ballerina/Array-concatenation | 1 + Lang/Ballerina/Array-length | 1 + Lang/Ballerina/Arrays | 1 + Lang/Ballerina/Ascending-primes | 1 + Lang/Ballerina/Associative-array-Creation | 1 + Lang/Ballerina/Associative-array-Iteration | 1 + Lang/Ballerina/Associative-array-Merging | 1 + Lang/Ballerina/Averages-Arithmetic-mean | 1 + Lang/Ballerina/Averages-Mean-angle | 1 + Lang/Ballerina/Averages-Mean-time-of-day | 1 + Lang/Ballerina/Averages-Median | 1 + Lang/Ballerina/Averages-Mode | 1 + Lang/Ballerina/Averages-Pythagorean-means | 1 + Lang/Ballerina/Averages-Root-mean-square | 1 + Lang/Ballerina/Averages-Simple-moving-average | 1 + Lang/Ballerina/Balanced-brackets | 1 + Lang/Ballerina/Boolean-values | 1 + Lang/Ballerina/Caesar-cipher | 1 + Lang/Ballerina/Calculating-the-value-of-e | 1 + .../Ballerina/Case-sensitivity-of-identifiers | 1 + Lang/Ballerina/Character-codes | 1 + Lang/Ballerina/Classes | 1 + Lang/Ballerina/Count-in-octal | 1 + Lang/Ballerina/Currency | 1 + Lang/Ballerina/Currying | 1 + Lang/Ballerina/Dynamic-variable-names | 1 + Lang/Ballerina/Empty-string | 1 + Lang/Ballerina/Extreme-floating-point-values | 1 + Lang/Ballerina/Farey-sequence | 1 + Lang/Ballerina/Find-limit-of-recursion | 1 + Lang/Ballerina/Fivenum | 1 + Lang/Ballerina/Floyds-triangle | 1 + Lang/Ballerina/Four-bit-adder | 1 + Lang/Ballerina/Function-definition | 1 + Lang/Ballerina/Gapful-numbers | 1 + Lang/Ballerina/Greatest-subsequential-sum | 1 + Lang/Ballerina/Hailstone-sequence | 1 + Lang/Ballerina/Hello-world-Newline-omission | 1 + Lang/Ballerina/Hello-world-Standard-error | 1 + Lang/Ballerina/Levenshtein-distance | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Ballerina/Loops-Break | 1 + Lang/Ballerina/Loops-Continue | 1 + Lang/Ballerina/Loops-Do-while | 1 + Lang/Ballerina/Loops-Downward-for | 1 + Lang/Ballerina/Loops-For | 1 + .../Ballerina/Loops-For-with-a-specified-step | 1 + Lang/Ballerina/Loops-Foreach | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/Ballerina/Loops-Infinite | 1 + Lang/Ballerina/Loops-N-plus-one-half | 1 + Lang/Ballerina/Loops-Nested | 1 + Lang/Ballerina/Loops-With-multiple-ranges | 1 + Lang/Ballerina/Loops-Wrong-ranges | 1 + Lang/Ballerina/Stack | 1 + Lang/Ballerina/Statistics-Basic | 1 + Lang/Ballerina/Towers-of-Hanoi | 1 + Lang/Ballerina/Truncatable-primes | 1 + Lang/Ballerina/Unicode-variable-names | 1 + Lang/C++/Currency | 1 + Lang/C++/Strassens-algorithm | 1 + Lang/C-sharp/ADFGVX-cipher | 1 + Lang/C-sharp/ASCII-art-diagram-converter | 1 + Lang/C-sharp/Arithmetic-derivative | 1 + Lang/C-sharp/Boyer-Moore-string-search | 1 + Lang/C-sharp/Calkin-Wilf-sequence | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + ...Elliptic-Curve-Digital-Signature-Algorithm | 1 + Lang/C-sharp/Execute-a-Markov-algorithm | 1 + Lang/C-sharp/Extensible-prime-generator | 1 + .../File-extension-is-in-extensions-list | 1 + .../Find-if-a-point-is-within-a-triangle | 1 + Lang/C-sharp/Gotchas | 1 + .../Index-finite-lists-of-positive-integers | 1 + Lang/C-sharp/K-d-tree | 1 + Lang/C-sharp/Longest-string-challenge | 1 + Lang/C-sharp/P-Adic-numbers-basic | 1 + Lang/C-sharp/Reflection-Get-source | 1 + ...e:-smallest-number-with-exactly-n-divisors | 1 + Lang/C-sharp/Strassens-algorithm | 1 + Lang/C/Color-wheel | 1 + Lang/C/Magic-constant | 1 + Lang/C3/Binary-digits | 1 + .../Evaluate-binomial-coefficients | 1 + Lang/Crystal/Abbreviations-easy | 1 + Lang/Crystal/Anagrams-Deranged-anagrams | 1 + Lang/Crystal/Arithmetic-Complex | 1 + Lang/Crystal/Arithmetic-geometric-mean | 1 + Lang/Crystal/Averages-Mode | 1 + Lang/Crystal/Averages-Pythagorean-means | 1 + Lang/Crystal/Bin-given-limits | 1 + Lang/Crystal/Character-codes | 1 + Lang/Crystal/Cistercian-numerals | 1 + Lang/Crystal/Closures-Value-capture | 1 + Lang/Crystal/Comma-quibbling | 1 + .../Convert-seconds-to-compound-duration | 1 + ...ne-if-a-string-has-all-the-same-characters | 1 + .../Determine-if-a-string-is-collapsible | 1 + Lang/Crystal/Dijkstras-algorithm | 1 + Lang/Crystal/Dutch-national-flag-problem | 1 + Lang/Crystal/Execute-Brain- | 1 + Lang/Crystal/Hello-world-Standard-error | 1 + Lang/Crystal/Hex-words | 1 + Lang/Crystal/Increment-a-numerical-string | 1 + Lang/Crystal/Interactive-programming-repl- | 1 + Lang/Crystal/Loops-N-plus-one-half | 1 + Lang/Crystal/Magic-8-ball | 1 + Lang/Crystal/Non-decimal-radices-Convert | 1 + Lang/Crystal/Order-by-pair-comparisons | 1 + Lang/Crystal/Order-two-numerical-lists | 1 + Lang/Crystal/Phrase-reversals | 1 + Lang/Crystal/Power-set | 1 + Lang/Crystal/Run-length-encoding | 1 + .../Sort-an-array-of-composite-structures | 1 + Lang/Crystal/Sort-numbers-lexicographically | 1 + Lang/Crystal/Sort-three-variables | 1 + Lang/Crystal/Sorting-Algorithms-Circle-Sort | 1 + Lang/Crystal/Sorting-algorithms-Bubble-sort | 1 + ...racter-string-based-on-change-of-character | 1 + Lang/Crystal/Stack-traces | 1 + Lang/Crystal/String-prepend | 1 + Lang/Crystal/Take-notes-on-the-command-line | 1 + ...Find-Chess960-starting-position-identifier | 1 + Lang/Dart/24-game-Solve | 1 + Lang/Dart/K-d-tree | 1 + Lang/Dart/Penneys-game | 1 + .../Generate-Chess960-starting-position | 1 + Lang/ERRE/Leonardo-numbers | 1 + Lang/EasyLang/00-LANG.txt | 2 +- Lang/EasyLang/2048 | 1 + Lang/EasyLang/Abbreviations-automatic | 1 + Lang/EasyLang/Abbreviations-easy | 1 + Lang/EasyLang/Abbreviations-simple | 1 + Lang/EasyLang/Amb | 1 + Lang/EasyLang/Anagrams | 1 + Lang/EasyLang/Anagrams-Deranged-anagrams | 1 + Lang/EasyLang/Babylonian-spiral | 1 + Lang/EasyLang/Boyer-Moore-string-search | 1 + Lang/EasyLang/Element-wise-operations | 1 + Lang/EasyLang/Factorions | 1 + Lang/EasyLang/Mad-Libs | 1 + Lang/EasyLang/Permutation-test | 1 + ...rs-whose-neighboring-pairs-are-tetraprimes | 1 + ...---allocate-descendants-to-their-ancestors | 1 + Lang/EasyLang/Solve-a-Numbrix-puzzle | 1 + Lang/EasyLang/Solve-the-no-connection-puzzle | 1 + .../EasyLang/Sorting-algorithms-Patience-sort | 1 + Lang/EasyLang/Unprimeable-numbers | 1 + .../Wasteful-equidigital-and-frugal-numbers | 1 + Lang/Elena/00-LANG.txt | 2 +- Lang/Elena/Comma-quibbling | 1 + Lang/Elena/Concurrent-computing | 1 + Lang/Elena/HTTP | 1 + Lang/Elena/HTTPS | 1 + Lang/Emacs-Lisp/Color-wheel | 1 + .../Keyboard-input-Flush-the-keyboard-buffer | 1 + Lang/Emacs-Lisp/Keyboard-input-Keypress-check | 1 + .../Keyboard-input-Obtain-a-Y-or-N-response | 1 + ...racter-string-based-on-change-of-character | 1 + Lang/Emacs-Lisp/Strip-comments-from-a-string | 1 + Lang/Emacs-Lisp/Word-frequency | 1 + Lang/Erlang/Parse-an-IP-Address | 1 + Lang/Excel/Arrays | 1 + Lang/Excel/Conditional-structures | 1 + Lang/Excel/FizzBuzz | 1 + Lang/Excel/Function-definition | 1 + Lang/Excel/Loops-For | 1 + Lang/Excel/Repeat-a-string | 1 + Lang/Excel/Reverse-a-string | 1 + Lang/Excel/Tokenize-a-string | 1 + Lang/F-Sharp/Mad-Libs | 1 + Lang/Factor/Tic-tac-toe | 1 + Lang/Forth/Almost-prime | 1 + ...-digital-filter-direct-form-II-transposed- | 1 + Lang/Fortran/B-zier-curves-Intersections | 1 + Lang/Fortran/Eulers-constant-0.5772... | 1 + ...fect-square-in-base-n-with-n-unique-digits | 1 + Lang/Fortran/Harmonic-series | 1 + Lang/Fortran/Knuths-algorithm-S | 1 + Lang/Fortran/Thieles-interpolation-formula | 1 + Lang/Fortran/Vogels-approximation-method | 1 + Lang/Free-Pascal-Lazarus/DNS-query | 1 + Lang/Free-Pascal-Lazarus/Levenshtein-distance | 1 + Lang/Free-Pascal-Lazarus/Map-range | 1 + .../FreeBASIC/Bioinformatics-Global-alignment | 1 + Lang/FreeBASIC/Cistercian-numerals | 1 + Lang/FreeBASIC/Compiler-syntax-analyzer | 1 + Lang/FreeBASIC/Deconvolution-2D+ | 1 + ...stribution-of-0-digits-in-factorial-series | 1 + Lang/FreeBASIC/Elliptic-curve-arithmetic | 1 + Lang/FreeBASIC/Fermat-numbers | 1 + Lang/FreeBASIC/Graph-colouring | 1 + Lang/FreeBASIC/Juggler-sequence | 1 + Lang/FreeBASIC/Knuths-algorithm-S | 1 + Lang/FreeBASIC/Knuths-power-tree | 1 + Lang/FreeBASIC/Last-letter-first-letter | 1 + Lang/FreeBASIC/Natural-sorting | 1 + Lang/FreeBASIC/Rosetta-Code-Fix-code-tags | 1 + .../Rosetta-Code-Rank-languages-by-popularity | 1 + Lang/FreeBASIC/SQL-based-authentication | 1 + Lang/FreeBASIC/Simulate-input-Keyboard | 1 + Lang/FreeBASIC/Sorting-algorithms-Strand-sort | 1 + Lang/FreeBASIC/Text-processing-2 | 1 + .../Ukkonen-s-suffix-tree-construction | 1 + Lang/FreeBASIC/Word-ladder | 1 + Lang/GW-BASIC/Levenshtein-distance | 1 + Lang/GW-BASIC/Magic-constant | 1 + Lang/GW-BASIC/Map-range | 1 + Lang/Gambas/Evaluate-binomial-coefficients | 1 + Lang/Gambas/Magic-constant | 1 + Lang/Go/Boyer-Moore-string-search | 1 + Lang/Go/Goldbachs-comet | 1 + Lang/Go/P-Adic-square-roots | 1 + .../Pathological-floating-point-problems | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/Java/Strassens-algorithm | 1 + Lang/JavaScript/15-puzzle-solver | 1 + Lang/JavaScript/ADFGVX-cipher | 1 + Lang/JavaScript/Average-loop-length | 1 + Lang/JavaScript/Bifid-cipher | 1 + Lang/JavaScript/Bitcoin-address-validation | 1 + Lang/JavaScript/Boyer-Moore-string-search | 1 + Lang/JavaScript/Burrows-Wheeler-transform | 1 + Lang/JavaScript/Camel-case-and-snake-case | 1 + Lang/JavaScript/Colorful-numbers | 1 + Lang/JavaScript/Commatizing-numbers | 1 + Lang/JavaScript/Compiler-code-generator | 1 + .../JavaScript/Create-a-file-on-magnetic-tape | 1 + Lang/JavaScript/Cyclotomic-polynomial | 1 + Lang/JavaScript/De-Bruijn-sequences | 1 + ...stribution-of-0-digits-in-factorial-series | 1 + ...Elliptic-Curve-Digital-Signature-Algorithm | 1 + Lang/JavaScript/Elliptic-curve-arithmetic | 1 + Lang/JavaScript/Gauss-Jordan-matrix-inversion | 1 + Lang/JavaScript/Graph-colouring | 1 + .../Greedy-algorithm-for-Egyptian-fractions | 1 + .../JavaScript/Isqrt-integer-square-root-of-X | 1 + Lang/JavaScript/Jacobi-symbol | 1 + Lang/JavaScript/K-d-tree | 1 + Lang/JavaScript/Knuths-algorithm-S | 1 + Lang/JavaScript/Knuths-power-tree | 1 + Lang/JavaScript/M-bius-function | 1 + Lang/JavaScript/MD5-Implementation | 1 + Lang/JavaScript/P-Adic-numbers-basic | 1 + Lang/JavaScript/P-Adic-square-roots | 1 + Lang/JavaScript/Perlin-noise | 1 + Lang/JavaScript/Playfair-cipher | 1 + Lang/JavaScript/SHA-1 | 1 + Lang/JavaScript/Set-puzzle | 1 + Lang/JavaScript/Solve-a-Hidato-puzzle | 1 + Lang/JavaScript/Solve-a-Numbrix-puzzle | 1 + Lang/JavaScript/Sorting-algorithms-Radix-sort | 1 + Lang/JavaScript/Spelling-of-ordinal-numbers | 1 + Lang/JavaScript/State-name-puzzle | 1 + Lang/JavaScript/Strassens-algorithm | 1 + Lang/JavaScript/Substitution-cipher | 1 + Lang/JavaScript/Tonelli-Shanks-algorithm | 1 + .../Ukkonen-s-suffix-tree-construction | 1 + Lang/JavaScript/Verhoeff-algorithm | 1 + Lang/JavaScript/Vigen-re-cipher-Cryptanalysis | 1 + Lang/JavaScript/Vogels-approximation-method | 1 + Lang/JavaScript/Wordiff | 1 + Lang/JavaScript/Zebra-puzzle | 1 + Lang/K/Compare-length-of-two-strings | 1 + Lang/K/Euler-method | 1 + Lang/K/M-bius-function | 1 + Lang/K/Substring | 1 + Lang/K/UTF-8-encode-and-decode | 1 + Lang/K/Write-float-arrays-to-a-text-file | 1 + Lang/Logo/Merge-and-aggregate-datasets | 1 + Lang/Lua/Check-input-device-is-a-terminal | 1 + Lang/Lua/Parse-an-IP-Address | 1 + .../Ramer-Douglas-Peucker-line-simplification | 1 + Lang/Lua/Update-a-configuration-file | 1 + Lang/M2000-Interpreter/00-LANG.txt | 60 +- Lang/M2000-Interpreter/ADFGVX-cipher | 1 + ...-digital-filter-direct-form-II-transposed- | 1 + .../Cartesian-product-of-two-or-more-lists | 1 + .../Compare-length-of-two-strings | 1 + .../File-extension-is-in-extensions-list | 1 + .../Greatest-subsequential-sum | 1 + Lang/M2000-Interpreter/Power-set | 1 + Lang/M2000-Interpreter/Simple-turtle-graphics | 1 + .../Sorting-algorithms-Strand-sort | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/MACRO-11/Run-length-encoding | 1 + Lang/MAD/Look-and-say-sequence | 1 + Lang/MSX-Basic/Evaluate-binomial-coefficients | 1 + Lang/MUMPS/00-LANG.txt | 17 +- Lang/Maple/Pythagoras-tree | 1 + Lang/Mathematica/00-LANG.txt | 2 +- Lang/Mathematica/15-puzzle-solver | 1 + Lang/Mathematica/B-zier-curves-Intersections | 1 + Lang/Mathematica/Sisyphus-sequence | 1 + Lang/Mathematica/Sphenic-numbers | 1 + Lang/Mathematica/Wagstaff-primes | 1 + .../Evaluate-binomial-coefficients | 1 + Lang/Miranda/Loops-Infinite | 1 + Lang/Miranda/Run-length-encoding | 1 + Lang/Modula-2/M-bius-function | 1 + Lang/Modula-2/Magic-constant | 1 + Lang/Modula-2/Map-range | 1 + .../Ramer-Douglas-Peucker-line-simplification | 1 + Lang/Nascom-BASIC/Levenshtein-distance | 1 + Lang/Nu/CSV-data-manipulation | 1 + Lang/Nu/Department-numbers | 1 + ...ne-if-a-string-has-all-the-same-characters | 1 + Lang/Nu/File-extension-is-in-extensions-list | 1 + Lang/Nu/File-size-distribution | 1 + Lang/Nu/I-before-E-except-after-C | 1 + Lang/Nu/Word-frequency | 1 + Lang/OCaml/Anti-primes | 1 + Lang/OCaml/Attractive-numbers | 1 + Lang/OCaml/Cuban-primes | 1 + Lang/OOC/00-LANG.txt | 2 +- Lang/OPL/00-LANG.txt | 10 +- Lang/OPL/100-doors | 1 + Lang/OPL/Arithmetic-Integer | 1 + Lang/OPL/Arrays | 1 + Lang/OPL/Character-codes | 1 + Lang/OPL/Comments | 1 + Lang/OPL/Compare-length-of-two-strings | 1 + Lang/OPL/Copy-a-string | 1 + Lang/OPL/Draw-a-clock | 1 + Lang/OPL/Draw-a-pixel | 1 + Lang/OPL/Hello-world-Text | 1 + Lang/OPL/Program-termination | 1 + Lang/OPL/String-prepend | 1 + Lang/OPL/User-input-Text | 1 + Lang/Objeck/Copy-stdin-to-stdout | 1 + Lang/Objeck/Distributed-programming | 1 + Lang/Objeck/Floyds-triangle | 1 + .../Objeck/Generate-lower-case-ASCII-alphabet | 1 + Lang/Objeck/Hello-world-Standard-error | 1 + Lang/Objeck/Knuth-shuffle | 1 + Lang/Objeck/Mad-Libs | 1 + Lang/Objeck/Multiplication-tables | 1 + Lang/Objeck/Roman-numerals-Decode | 1 + .../Rosetta-Code-Find-unimplemented-tasks | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Odin/Euler-method | 1 + Lang/Odin/Execute-Brain- | 1 + Lang/Odin/Fractran | 1 + Lang/Odin/Hailstone-sequence | 1 + Lang/Odin/Hello-world-Graphical | 1 + Lang/Odin/Primality-by-trial-division | 1 + Lang/Odin/Runge-Kutta-method | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Odin/Unicode-variable-names | 1 + Lang/Odin/Write-entire-file | 1 + Lang/Ol/Runge-Kutta-method | 1 + .../Evaluate-binomial-coefficients | 1 + Lang/PARI-GP/Attractive-numbers | 1 + Lang/PARI-GP/Disarium-numbers | 1 + ...rs-whose-neighboring-pairs-are-tetraprimes | 1 + Lang/PHP/M-bius-function | 1 + Lang/PHP/Magic-constant | 1 + Lang/PHP/Map-range | 1 + Lang/PL-I-80/Additive-primes | 1 + Lang/Pascal/Date-manipulation | 1 + Lang/Pascal/FizzBuzz | 1 - Lang/Pascal/Levenshtein-distance | 1 - Lang/Pascal/Map-range | 1 - Lang/PascalABC.NET/Additive-primes | 1 + Lang/PascalABC.NET/Amicable-pairs | 1 + Lang/PascalABC.NET/Pancake-numbers | 1 + Lang/PascalABC.NET/Pangram-checker | 1 + Lang/PascalABC.NET/Paraffins | 1 + Lang/PascalABC.NET/Parallel-calculations | 1 + .../Parsing-RPN-calculator-algorithm | 1 + .../Partition-an-integer-x-into-n-primes | 1 + Lang/PascalABC.NET/Pascal-matrix-generation | 1 + Lang/PascalABC.NET/Pascals-triangle-Puzzle | 1 + .../Pathological-floating-point-problems | 1 + Lang/PascalABC.NET/Pells-equation | 1 + Lang/PascalABC.NET/Perfect-shuffle | 1 + Lang/PascalABC.NET/Perfect-totient-numbers | 1 + Lang/PascalABC.NET/Permutation-test | 1 + Lang/Perl/Execute-Computer-Zero | 1 + Lang/Prolog/Evaluate-binomial-coefficients | 1 + .../Im-a-software-engineer-get-me-out-of-here | 1 + ...rs-whose-neighboring-pairs-are-tetraprimes | 1 + Lang/Python/Square-form-factorization | 1 + .../Wasteful-equidigital-and-frugal-numbers | 1 + Lang/Q/Euler-method | 1 + Lang/QBasic/Evaluate-binomial-coefficients | 1 + Lang/QBasic/Map-range | 1 + Lang/Quackery/00-LANG.txt | 24 +- Lang/Quackery/Dice-game-probabilities | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + Lang/Quackery/Two-bullet-roulette | 1 + Lang/R/Camel-case-and-snake-case | 1 + Lang/R/Determine-sentence-type | 1 + Lang/R/Disarium-numbers | 1 + Lang/R/Display-a-linear-combination | 1 + Lang/R/Draw-a-cuboid | 1 + Lang/R/Dutch-national-flag-problem | 1 + Lang/R/Factorions | 1 + ...c-numbers-in-both-binary-and-ternary-bases | 1 + Lang/R/Halt-and-catch-fire | 1 + Lang/R/Hex-words | 1 + Lang/R/Kernighans-large-earthquake-problem | 1 + Lang/R/Munchausen-numbers | 1 + Lang/R/Old-Russian-measure-of-length | 1 + Lang/R/Semordnilap | 1 + Lang/R/Sort-numbers-lexicographically | 1 + .../R/Strip-a-set-of-characters-from-a-string | 1 + Lang/REXX/00-LANG.txt | 18 +- Lang/REXX/Magic-constant | 1 + ...---allocate-descendants-to-their-ancestors | 1 + Lang/REXX/Ramanujan-primes-twins | 1 + Lang/REXX/Sequence-of-primorial-primes | 1 + Lang/REXX/Sieve-of-Pritchard | 1 + Lang/Raku/Simple-turtle-graphics | 1 + Lang/RapidQ/Levenshtein-distance | 1 + Lang/RapidQ/M-bius-function | 1 + Lang/RapidQ/Map-range | 1 + Lang/Refal/Loops-Infinite | 1 + Lang/Refal/Power-set | 1 + Lang/Refal/Run-length-encoding | 1 + Lang/Refal/Strip-comments-from-a-string | 1 + Lang/Rust/Ascending-primes | 1 + Lang/Rust/B-zier-curves-Intersections | 1 + Lang/Rust/Bifid-cipher | 1 + Lang/Rust/Bioinformatics-Global-alignment | 1 + Lang/Rust/Blum-integer | 1 + Lang/Rust/Boyer-Moore-string-search | 1 + Lang/Rust/Calendar---for-REAL-programmers | 1 + .../Compare-sorting-algorithms-performance | 1 + Lang/Rust/Compiler-AST-interpreter | 1 + Lang/Rust/Compiler-code-generator | 1 + Lang/Rust/Compiler-lexical-analyzer | 1 + Lang/Rust/Compiler-syntax-analyzer | 1 + Lang/Rust/Cyclotomic-polynomial | 1 + Lang/Rust/Descending-primes | 1 + Lang/Rust/Doubly-linked-list-Definition | 1 + Lang/Rust/Doubly-linked-list-Traversal | 1 + ...Elliptic-Curve-Digital-Signature-Algorithm | 1 + Lang/Rust/Faulhabers-formula | 1 + Lang/Rust/Graph-colouring | 1 + Lang/Rust/Hex-words | 1 + Lang/Rust/Kosaraju | 1 + Lang/Rust/Latin-Squares-in-reduced-form | 1 + Lang/Rust/Median-filter | 1 + Lang/Rust/Natural-sorting | 1 + Lang/Rust/Nonogram-solver | 1 + Lang/Rust/OpenWebNet-password | 1 + Lang/Rust/P-Adic-numbers-basic | 1 + Lang/Rust/P-Adic-square-roots | 1 + Lang/Rust/Playfair-cipher | 1 + Lang/Rust/Polynomial-regression | 1 + ...bers-Combined-recursive-generator-MRG32k3a | 1 + ...Pseudo-random-numbers-Middle-square-method | 1 + Lang/Rust/Pseudo-random-numbers-Splitmix64 | 1 + Lang/Rust/QR-decomposition | 1 + Lang/Rust/Rendezvous | 1 + Lang/Rust/Resistor-mesh | 1 + Lang/Rust/Shoelace-formula-for-polygonal-area | 1 + Lang/Rust/Solve-a-Holy-Knights-tour | 1 + Lang/Rust/Solve-a-Hopido-puzzle | 1 + Lang/Rust/Solve-a-Numbrix-puzzle | 1 + Lang/Rust/Sorting-algorithms-Bead-sort | 1 + Lang/Rust/Sorting-algorithms-Patience-sort | 1 + Lang/Rust/Sorting-algorithms-Strand-sort | 1 + Lang/Rust/Steffensens-method | 1 + Lang/Rust/Strassens-algorithm | 1 + Lang/Rust/Stream-merge | 1 + Lang/Rust/Sudan-function | 1 + Lang/Rust/Tonelli-Shanks-algorithm | 1 + Lang/Rust/Ukkonen-s-suffix-tree-construction | 1 + Lang/Rust/Verhoeff-algorithm | 1 + Lang/Rust/Xiaolin-Wus-line-algorithm | 1 + Lang/S-BASIC/Additive-primes | 1 + Lang/S-BASIC/Character-codes | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/S-BASIC/Sum-of-a-series | 1 + Lang/SETL/Gray-code | 1 + Lang/SETL/Loops-Do-while | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/SETL/Loops-Infinite | 1 + Lang/SETL/Radical-of-an-integer | 1 + Lang/SETL/Strip-comments-from-a-string | 1 + Lang/SQL/Factorial | 1 + Lang/Scala/Boyer-Moore-string-search | 1 + Lang/Scheme/Circular-primes | 1 + Lang/Scheme/Compare-length-of-two-strings | 1 + Lang/Scheme/Runge-Kutta-method | 1 + Lang/Scheme/Unicode-variable-names | 1 + Lang/Standard-ML/Box-the-compass | 1 + Lang/Tcl/Unicode-strings | 1 + Lang/Tiny-BASIC/Magic-constant | 1 + .../True-BASIC/Evaluate-binomial-coefficients | 1 + Lang/TypeScript/Additive-primes | 1 + Lang/TypeScript/Arithmetic-numbers | 1 + Lang/TypeScript/Map-range | 1 + Lang/TypeScript/Sum-of-a-series | 1 + Lang/UNIX-Shell/Color-of-a-screen-pixel | 1 + Lang/UNIX-Shell/Color-quantization | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/Uiua/Damm-algorithm | 1 + Lang/Uiua/Ethiopian-multiplication | 1 + Lang/Uiua/Matrix-transposition | 1 + Lang/Uiua/Munching-squares | 1 + Lang/Uiua/Pangram-checker | 1 + Lang/Uiua/Spiral-matrix | 1 + Lang/Uiua/Zig-zag-matrix | 1 + Lang/Uxntal/00-LANG.txt | 17 +- Lang/Uxntal/Array-length | 1 + Lang/Uxntal/Bioinformatics-base-count | 1 + Lang/Uxntal/Comments | 1 + Lang/Uxntal/Conditional-structures | 1 + Lang/Uxntal/Copy-a-string | 1 + Lang/Uxntal/Draw-a-pixel | 1 - Lang/Uxntal/Fibonacci-sequence | 1 + Lang/Uxntal/Flow-control-structures | 1 + Lang/Uxntal/Hello-world-Graphical | 1 + Lang/Uxntal/Hello-world-Standard-error | 1 + Lang/Uxntal/Hello-world-Text | 1 - Lang/Uxntal/Integer-sequence | 1 + Lang/Uxntal/Loops-Break | 1 + Lang/Uxntal/Loops-Continue | 1 + Lang/Uxntal/Loops-Do-while | 1 + Lang/Uxntal/Loops-For-with-a-specified-step | 1 + Lang/Uxntal/Loops-Foreach | 1 + Lang/Uxntal/Loops-N-plus-one-half | 1 + Lang/Uxntal/Loops-While | 1 + Lang/Uxntal/Stack-traces | 1 + Lang/Uxntal/String-length | 1 + Lang/V-(Vlang)/Quine | 1 + Lang/Wisp/Knuth-shuffle | 1 + .../Terminal-control-Clear-the-screen | 1 + Lang/XBasic/Levenshtein-distance | 1 + Lang/XPL0/Bin-given-limits | 1 + Lang/XPL0/Create-an-object-at-a-given-address | 1 + Lang/XPL0/Floyd-Warshall-algorithm | 1 + Lang/XPL0/Largest-int-from-concatenated-ints | 1 + Lang/XPL0/Last-letter-first-letter | 1 + Lang/XPL0/Levenshtein-distance | 1 + Lang/XPL0/Polynomial-regression | 1 + Lang/XPL0/Read-a-configuration-file | 1 + Lang/XPL0/Sort-three-variables | 1 + Lang/XPL0/Text-processing-1 | 1 + Lang/XPL0/Text-processing-2 | 1 + Lang/Yabasic/Evaluate-binomial-coefficients | 1 + Lang/ZED/00-LANG.txt | 3 + Lang/Zig/15-puzzle-solver | 1 + Lang/Zig/2048 | 1 + Lang/Zig/24-game | 1 + Lang/Zig/Anti-primes | 1 + Lang/Zig/Canonicalize-CIDR | 1 + Lang/Zig/Convex-hull | 1 + Lang/Zig/De-Bruijn-sequences | 1 + Lang/Zig/Dijkstras-algorithm | 1 + Lang/Zig/Execute-a-Markov-algorithm | 1 + Lang/Zig/Fibonacci-sequence | 1 + Lang/Zig/Find-the-missing-permutation | 1 + Lang/Zig/Floyd-Warshall-algorithm | 1 + Lang/Zig/Latin-Squares-in-reduced-form | 1 + Lang/Zig/Move-to-front-algorithm | 1 + Lang/Zig/Natural-sorting | 1 + Lang/Zig/P-Adic-numbers-basic | 1 + Lang/Zig/P-Adic-square-roots | 1 + Lang/Zig/Parsing-RPN-calculator-algorithm | 1 + Lang/Zig/Parsing-Shunting-yard-algorithm | 1 + Lang/Zig/Quickselect-algorithm | 1 + Lang/Zig/Quine | 1 + Lang/Zig/SHA-1 | 1 + Lang/Zig/Solve-a-Holy-Knights-tour | 1 + Lang/Zig/Sorting-algorithms-Patience-sort | 1 + Lang/Zig/Sorting-algorithms-Strand-sort | 1 + Lang/Zig/Strassens-algorithm | 1 + Lang/Zig/Sutherland-Hodgman-polygon-clipping | 1 + Lang/Zig/Thue-Morse | 1 + Lang/Zig/Tonelli-Shanks-algorithm | 1 + Lang/Zig/Y-combinator | 1 + Task/100-doors/BQN/100-doors-4.bqn | 3 + Task/100-doors/BQN/100-doors-5.bqn | 3 + Task/100-doors/EasyLang/100-doors.easy | 4 +- Task/100-doors/Elena/100-doors.elena | 4 +- Task/100-doors/Excel/100-doors-4.excel | 1 + Task/100-doors/OPL/100-doors.opl | 32 + Task/100-doors/Quackery/100-doors-1.quackery | 17 + Task/100-doors/Quackery/100-doors-2.quackery | 1 + Task/100-doors/Quackery/100-doors.quackery | 22 - Task/100-doors/Tcl/100-doors-1.tcl | 90 +- Task/100-doors/Tcl/100-doors-2.tcl | 11 +- Task/100-doors/Tcl/100-doors-3.tcl | 48 +- Task/100-doors/Tcl/100-doors-4.tcl | 46 + .../100-prisoners/EasyLang/100-prisoners.easy | 55 +- .../EasyLang/15-puzzle-game.easy | 75 +- .../C-sharp/15-puzzle-solver.cs | 1527 +---------------- .../JavaScript/15-puzzle-solver.js | 97 ++ .../Mathematica/15-puzzle-solver.math | 178 ++ .../15-puzzle-solver/Zig/15-puzzle-solver.zig | 187 ++ Task/2048/BQN/2048.bqn | 2 +- Task/2048/EasyLang/2048.easy | 161 ++ Task/2048/Zig/2048.zig | 228 +++ Task/24-game-Solve/Dart/24-game-solve.dart | 226 +++ Task/24-game/Elena/24-game.elena | 41 +- Task/24-game/Perl/24-game.pl | 17 +- Task/24-game/Rust/24-game.rs | 8 +- Task/24-game/Zig/24-game.zig | 153 ++ .../EasyLang/4-rings-or-4-squares-puzzle.easy | 6 +- .../Elena/99-bottles-of-beer.elena | 2 +- .../Factor/99-bottles-of-beer-1.factor | 6 + ...eer.factor => 99-bottles-of-beer-2.factor} | 0 .../Uxntal/99-bottles-of-beer.uxnatl | 108 +- Task/A+B/Ballerina/a+b.ballerina | 16 + Task/A+B/Elena/a+b-1.elena | 6 +- Task/A+B/Elena/a+b-2.elena | 2 +- Task/A+B/REXX/a+b-1.rexx | 4 - Task/A+B/REXX/a+b-2.rexx | 4 - Task/A+B/REXX/a+b-3.rexx | 6 - Task/A+B/REXX/a+b-4.rexx | 11 - Task/A+B/REXX/a+b-5.rexx | 8 - Task/A+B/REXX/a+b.rexx | 27 + .../Ballerina/abc-problem.ballerina | 32 + Task/ABC-problem/EasyLang/abc-problem.easy | 2 +- Task/ABC-problem/Elena/abc-problem.elena | 2 +- Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs | 117 ++ .../ADFGVX-cipher/JavaScript/adfgvx-cipher.js | 134 ++ .../M2000-Interpreter/adfgvx-cipher.m2000 | 116 ++ .../Ballerina/aks-test-for-primes.ballerina | 58 + .../Elena/aks-test-for-primes.elena | 12 +- .../REXX/aks-test-for-primes-2.rexx | 134 +- .../REXX/aks-test-for-primes-3.rexx | 89 - .../C-sharp/ascii-art-diagram-converter-1.cs | 190 ++ .../C-sharp/ascii-art-diagram-converter-2.cs | 15 + .../EasyLang/abbreviations-automatic.easy | 30 + .../Crystal/abbreviations-easy.cr | 17 + .../EasyLang/abbreviations-easy.easy | 42 + .../EasyLang/abbreviations-simple.easy | 42 + .../abelian-sandpile-model-identity.easy | 28 +- .../EasyLang/abelian-sandpile-model.easy | 9 +- ...perfect-number-classifications-1.ballerina | 46 + ...perfect-number-classifications-2.ballerina | 36 + ...t-and-perfect-number-classifications.elena | 2 +- ...-and-perfect-number-classifications-1.rexx | 72 +- ...-and-perfect-number-classifications-2.rexx | 53 +- ...-and-perfect-number-classifications-3.rexx | 51 - ...-and-perfect-number-classifications-4.rexx | 27 - Task/Abundant-odd-numbers/00-TASK.txt | 10 +- .../Ballerina/abundant-odd-numbers.ballerina | 73 + .../EasyLang/abundant-odd-numbers.easy | 2 +- .../Ballerina/accumulator-factory.ballerina | 38 + .../Elena/accumulator-factory.elena | 2 +- .../Ballerina/achilles-numbers.ballerina | 92 + .../EasyLang/achilles-numbers.easy | 36 +- .../Ballerina/ackermann-function.ballerina | 14 + .../Elena/ackermann-function.elena | 14 +- ...e-to-a-class-instance-at-runtime.ballerina | 23 + ...iable-to-a-class-instance-at-runtime.elena | 4 +- .../ALGOL-60/additive-primes.alg | 60 + .../ALGOL-M/additive-primes.alg | 64 + .../Ballerina/additive-primes.ballerina | 67 + .../EasyLang/additive-primes.easy | 13 +- .../PL-I-80/additive-primes.pli | 52 + .../PascalABC.NET/additive-primes.pas | 4 + .../REXX/additive-primes-2.rexx | 55 +- .../Additive-primes/Raku/additive-primes.raku | 2 +- .../S-BASIC/additive-primes.basic | 55 + .../TypeScript/additive-primes.ts | 29 + .../Ballerina/address-of-a-variable.ballerina | 8 + .../Align-columns/EasyLang/align-columns.easy | 4 +- Task/Align-columns/Emacs-Lisp/align-columns.l | 341 ++-- .../aliquot-sequence-classifications.easy | 52 +- .../00-TASK.txt | 12 +- Task/Almost-prime/00-TASK.txt | 2 +- .../Ballerina/almost-prime.ballerina | 32 + Task/Almost-prime/Clojure/almost-prime.clj | 2 - Task/Almost-prime/EasyLang/almost-prime.easy | 14 +- Task/Almost-prime/Forth/almost-prime.fth | 38 + Task/Almost-prime/REXX/almost-prime-1.rexx | 35 - Task/Almost-prime/REXX/almost-prime-2.rexx | 66 - ...{almost-prime-3.rexx => almost-prime.rexx} | 4 +- Task/Amb/Ballerina/amb.ballerina | 35 + Task/Amb/EasyLang/amb.easy | 31 + Task/Amb/Elena/amb.elena | 6 +- Task/Amb/Langur/amb.langur | 2 +- .../EasyLang/amicable-pairs.easy | 10 +- .../Elena/amicable-pairs-1.elena | 2 +- .../Elena/amicable-pairs-2.elena | 2 +- .../Elena/amicable-pairs-3.elena | 14 +- .../PascalABC.NET/amicable-pairs.pas | 9 + .../Amicable-pairs/REXX/amicable-pairs-2.rexx | 52 +- .../Amicable-pairs/REXX/amicable-pairs-3.rexx | 30 - .../Amicable-pairs/REXX/amicable-pairs-4.rexx | 34 - .../Amicable-pairs/REXX/amicable-pairs-5.rexx | 34 - .../Amicable-pairs/REXX/amicable-pairs-6.rexx | 43 - .../Crystal/anagrams-deranged-anagrams.cr | 19 + .../EasyLang/anagrams-deranged-anagrams.easy | 74 + Task/Anagrams/EasyLang/anagrams.easy | 46 + Task/Anagrams/Elena/anagrams.elena | 10 +- ...-difference-between-two-bearings.ballerina | 34 + ...angle-difference-between-two-bearings.easy | 2 +- ...eometric-normalization-and-conversion.easy | 2 +- .../EasyLang/animate-a-pendulum.easy | 17 +- Task/Animation/EasyLang/animation.easy | 12 +- .../Elena/anonymous-recursion.elena | 8 +- .../Ballerina/anti-primes.ballerina | 42 + Task/Anti-primes/EasyLang/anti-primes.easy | 6 +- Task/Anti-primes/OCaml/anti-primes.ml | 18 + Task/Anti-primes/REXX/anti-primes-1.rexx | 70 +- Task/Anti-primes/REXX/anti-primes-2.rexx | 69 +- Task/Anti-primes/REXX/anti-primes-3.rexx | 44 - Task/Anti-primes/Zig/anti-primes.zig | 160 ++ .../apply-a-callback-to-an-array.ballerina | 9 + ...igital-filter-direct-form-ii-transposed-.f | 42 + ...al-filter-direct-form-ii-transposed-.m2000 | 49 + .../Ballerina/approximate-equality.ballerina | 22 + .../EasyLang/approximate-equality.easy | 4 +- .../EasyLang/archimedean-spiral.easy | 12 +- .../ALGOL-68/arithmetic-complex.alg | 26 +- .../Ballerina/arithmetic-complex.ballerina | 67 + .../Crystal/arithmetic-complex.cr | 15 + ...mplex.m2000 => arithmetic-complex-1.m2000} | 0 .../arithmetic-complex-2.m2000 | 35 + .../REXX/arithmetic-complex.rexx | 79 +- .../Ballerina/arithmetic-integer.ballerina | 24 + .../OPL/arithmetic-integer.opl | 14 + .../Wren/arithmetic-integer.wren | 14 +- .../Ballerina/arithmetic-rational.ballerina | 156 ++ .../REXX/arithmetic-rational.rexx | 4 +- Task/Arithmetic-derivative/00-TASK.txt | 18 +- .../Arturo/arithmetic-derivative.arturo | 20 + .../C-sharp/arithmetic-derivative.cs | 30 + .../EasyLang/arithmetic-derivative.easy | 12 +- .../EasyLang/arithmetic-evaluation.easy | 8 +- ...rithmetic-geometric-mean-calculate-pi.easy | 2 +- .../C++/arithmetic-geometric-mean.cpp | 42 +- .../Crystal/arithmetic-geometric-mean.cr | 8 + .../EasyLang/arithmetic-geometric-mean.easy | 2 +- .../Ballerina/arithmetic-numbers.ballerina | 98 ++ .../EasyLang/arithmetic-numbers.easy | 42 +- .../REXX/arithmetic-numbers.rexx | 20 +- .../TypeScript/arithmetic-numbers.ts | 32 + .../Ballerina/array-concatenation.ballerina | 7 + .../EasyLang/array-concatenation.easy | 4 +- .../REXX/array-concatenation-1.rexx | 3 - .../REXX/array-concatenation-2.rexx | 9 - .../REXX/array-concatenation-3.rexx | 22 - .../REXX/array-concatenation.rexx | 21 + .../Ballerina/array-length.ballerina | 6 + Task/Array-length/Uxntal/array-length.uxnatl | 18 + Task/Arrays/Ballerina/arrays.ballerina | 15 + Task/Arrays/EasyLang/arrays.easy | 10 +- Task/Arrays/Excel/arrays-1.excel | 15 + Task/Arrays/Excel/arrays-2.excel | 1 + Task/Arrays/Excel/arrays-3.excel | 16 + Task/Arrays/OPL/arrays.opl | 9 + Task/Arrays/REXX/arrays-1.rexx | 9 - Task/Arrays/REXX/arrays-2.rexx | 11 - Task/Arrays/REXX/arrays-3.rexx | 11 - Task/Arrays/REXX/arrays-4.rexx | 10 - Task/Arrays/REXX/arrays-5.rexx | 17 - Task/Arrays/REXX/arrays-6.rexx | 27 - Task/Arrays/REXX/arrays.rexx | 67 + Task/Arrays/Tcl/arrays-1.tcl | 13 +- Task/Arrays/Tcl/arrays-2.tcl | 9 +- Task/Arrays/Tcl/arrays-3.tcl | 2 + Task/Arrays/Tcl/arrays-4.tcl | 2 + Task/Arrays/Tcl/arrays-5.tcl | 4 + Task/Arrays/Tcl/arrays-6.tcl | 10 + .../Ballerina/ascending-primes.ballerina | 38 + .../EasyLang/ascending-primes.easy | 26 +- .../Rust/ascending-primes-1.rs | 36 + .../Rust/ascending-primes-2.rs | 30 + .../Rust/ascending-primes-3.rs | 43 + .../associative-array-creation.ballerina | 22 + .../EasyLang/associative-array-creation.easy | 27 +- .../associative-array-iteration.ballerina | 22 + .../associative-array-merging.ballerina | 15 + .../associative-array-merging-3.lisp | 28 + .../EasyLang/associative-array-merging.easy | 6 +- .../JavaScript/associative-array-merging.js | 35 +- .../EasyLang/attractive-numbers.easy | 12 +- .../OCaml/attractive-numbers.ml | 26 + .../PARI-GP/attractive-numbers-1.parigp | 1 + .../PARI-GP/attractive-numbers-2.parigp | 1 + .../EasyLang/average-loop-length.easy | 8 +- .../JavaScript/average-loop-length.js | 49 + .../averages-arithmetic-mean.ballerina | 22 + .../EasyLang/averages-arithmetic-mean.easy | 11 +- .../Ballerina/averages-mean-angle.ballerina | 27 + .../averages-mean-time-of-day.ballerina | 42 + .../Ballerina/averages-median.ballerina | 20 + .../EasyLang/averages-median.easy | 22 +- .../Ballerina/averages-mode.ballerina | 27 + Task/Averages-Mode/Crystal/averages-mode.cr | 6 + .../Averages-Mode/EasyLang/averages-mode.easy | 6 +- .../averages-pythagorean-means.ballerina | 21 + .../Crystal/averages-pythagorean-means.cr | 24 + .../EasyLang/averages-pythagorean-means.easy | 2 +- .../averages-root-mean-square.ballerina | 8 + .../averages-simple-moving-average.ballerina | 33 + .../averages-simple-moving-average.easy | 2 +- .../Fortran/b-zier-curves-intersections.f | 286 +++ .../b-zier-curves-intersections.math | 7 + .../Rust/b-zier-curves-intersections.rs | 198 +++ .../EasyLang/babylonian-spiral.easy | 70 + .../Ballerina/balanced-brackets.ballerina | 34 + .../Excel/balanced-brackets-3.excel | 1 + .../Excel/balanced-brackets-4.excel | 1 + Task/Balanced-ternary/00-TASK.txt | 4 +- .../Barnsley-fern/EasyLang/barnsley-fern.easy | 37 +- .../{bell-numbers.cs => bell-numbers-1.cs} | 0 Task/Bell-numbers/C-sharp/bell-numbers-2.cs | 25 + Task/Benfords-law/EasyLang/benfords-law.easy | 10 +- Task/Best-shuffle/EasyLang/best-shuffle.easy | 2 +- Task/Bifid-cipher/EasyLang/bifid-cipher.easy | 2 +- Task/Bifid-cipher/JavaScript/bifid-cipher.js | 199 +++ Task/Bifid-cipher/Rust/bifid-cipher.rs | 125 ++ .../AppleScript/bin-given-limits.applescript | 42 + .../Crystal/bin-given-limits.cr | 43 + .../EasyLang/bin-given-limits.easy | 7 +- .../XPL0/bin-given-limits.xpl0 | 60 + Task/Binary-digits/C3/binary-digits.c3 | 8 + .../Binary-digits/EasyLang/binary-digits.easy | 8 +- .../Binary-search/EasyLang/binary-search.easy | 11 +- .../bioinformatics-global-alignment.basic | 170 ++ .../Rust/bioinformatics-global-alignment.rs | 132 ++ .../bioinformatics-sequence-mutation.easy | 28 +- .../EasyLang/bioinformatics-base-count.easy | 14 +- .../Uxntal/bioinformatics-base-count.uxnatl | 80 + Task/Biorhythms/EasyLang/biorhythms.easy | 36 +- .../JavaScript/bitcoin-address-validation.js | 53 + .../bitmap-b-zier-curves-quadratic.easy | 19 +- .../bitmap-bresenhams-line-algorithm.easy | 7 +- .../Uxntal/bitwise-operations.uxnatl | 120 +- Task/Blum-integer/EasyLang/blum-integer.easy | 27 +- Task/Blum-integer/Rust/blum-integer.rs | 91 + .../Ballerina/boolean-values.ballerina | 12 + .../EasyLang/box-the-compass.easy | 2 +- .../Standard-ML/box-the-compass.ml | 29 + .../C-sharp/boyer-moore-string-search.cs | 280 +++ .../EasyLang/boyer-moore-string-search.easy | 67 + .../Go/boyer-moore-string-search.go | 65 + .../JavaScript/boyer-moore-string-search.js | 52 + .../Rust/boyer-moore-string-search.rs | 62 + .../Scala/boyer-moore-string-search.scala | 329 ++++ .../Wren/boyer-moore-string-search.wren | 15 +- .../EasyLang/brace-expansion.easy | 6 +- .../EasyLang/brazilian-numbers.easy | 23 +- .../EasyLang/brilliant-numbers.easy | 22 +- .../Brownian-tree/EasyLang/brownian-tree.easy | 10 +- Task/Bulls-and-cows/APL/bulls-and-cows-1.apl | 2 +- Task/Bulls-and-cows/J/bulls-and-cows-1.j | 8 +- Task/Bulls-and-cows/J/bulls-and-cows-2.j | 4 +- .../EasyLang/burrows-wheeler-transform.easy | 10 +- .../JavaScript/burrows-wheeler-transform.js | 76 + .../csv-data-manipulation.m2000 | 17 +- .../Nu/csv-data-manipulation-1.nu | 5 + .../Nu/csv-data-manipulation-2.nu | 1 + .../Ballerina/caesar-cipher.ballerina | 32 + .../calculating-the-value-of-e.ballerina | 17 + .../EasyLang/calculating-the-value-of-e.easy | 2 +- .../Rust/calendar---for-real-programmers.rs | 216 +++ Task/Calendar/00-TASK.txt | 2 + Task/Calendar/EasyLang/calendar.easy | 28 +- .../C-sharp/calkin-wilf-sequence.cs | 48 + .../EasyLang/calkin-wilf-sequence.easy | 5 +- .../EasyLang/call-a-function.easy | 2 +- .../JavaScript/camel-case-and-snake-case.js | 82 + .../R/camel-case-and-snake-case.r | 56 + .../ALGOL-68/canonicalize-cidr.alg | 32 +- .../Zig/canonicalize-cidr.zig | 70 + Task/Cantor-set/EasyLang/cantor-set.easy | 7 +- .../carmichael-3-strong-pseudoprimes.easy | 6 +- .../carmichael-3-strong-pseudoprimes-1.rexx | 42 - .../carmichael-3-strong-pseudoprimes-2.rexx | 59 - .../carmichael-3-strong-pseudoprimes.rexx | 26 + ...rtesian-product-of-two-or-more-lists-1.cpp | 66 + ...rtesian-product-of-two-or-more-lists-2.cpp | 36 + ...cartesian-product-of-two-or-more-lists.cpp | 56 - ...artesian-product-of-two-or-more-lists.easy | 22 +- ...rtesian-product-of-two-or-more-lists.m2000 | 52 + ...artesian-product-of-two-or-more-lists-1.rs | 49 +- ...artesian-product-of-two-or-more-lists-2.rs | 25 +- ...artesian-product-of-two-or-more-lists-3.rs | 28 + .../case-sensitivity-of-identifiers.ballerina | 8 + .../EasyLang/catalan-numbers.easy | 6 +- .../REXX/catalan-numbers-1.rexx | 74 +- .../REXX/catalan-numbers-2.rexx | 92 +- Task/Chaocipher/EasyLang/chaocipher.easy | 10 +- Task/Chaos-game/EasyLang/chaos-game.easy | 7 +- .../Ballerina/character-codes.ballerina | 15 + .../Crystal/character-codes.cr | 2 + .../M2000-Interpreter/character-codes.m2000 | 41 +- Task/Character-codes/OPL/character-codes.opl | 5 + .../S-BASIC/character-codes.basic | 14 + .../Uxntal/character-codes.uxnatl | 35 +- Task/Check-Machin-like-formulas/00-TASK.txt | 2 +- .../Lua/check-input-device-is-a-terminal.lua | 6 + .../Lua/check-that-file-exists-3.lua | 10 + Task/Chernicks-Carmichael-numbers/00-TASK.txt | 18 +- .../REXX/chernicks-carmichael-numbers.rexx | 4 +- .../EasyLang/chinese-remainder-theorem.easy | 16 +- .../EasyLang/chinese-zodiac.easy | 4 +- .../ALGOL-68/chowla-numbers.alg | 2 +- Task/Chowla-numbers/Ada/chowla-numbers.ada | 2 +- .../EasyLang/chowla-numbers.easy | 26 +- .../Chowla-numbers/REXX/chowla-numbers-1.rexx | 29 - ...wla-numbers-2.rexx => chowla-numbers.rexx} | 15 +- ...es-of-given-radius-through-two-points.easy | 2 +- .../EasyLang/circular-primes.easy | 21 +- .../REXX/circular-primes-1.rexx | 37 - ...lar-primes-2.rexx => circular-primes.rexx} | 23 +- .../Scheme/circular-primes.scm | 82 + .../Ada/cistercian-numerals-1.ada | 92 + .../Ada/cistercian-numerals-2.ada | 36 + .../Ada/cistercian-numerals-3.ada | 49 + .../Ada/cistercian-numerals-4.ada | 54 + .../Ada/cistercian-numerals-5.ada | 9 + .../Ada/cistercian-numerals-6.ada | 54 + .../Ada/cistercian-numerals-7.ada | 76 + .../Applesoft-BASIC/cistercian-numerals.basic | 6 + .../Crystal/cistercian-numerals.cr | 96 ++ .../EasyLang/cistercian-numerals.easy | 47 +- .../FreeBASIC/cistercian-numerals.basic | 95 + Task/Classes/Ballerina/classes.ballerina | 28 + Task/Classes/Scheme/classes.scm | 11 + .../EasyLang/closest-pair-problem.easy | 2 +- .../Crystal/closures-value-capture.cr | 6 + .../UNIX-Shell/color-of-a-screen-pixel.sh | 1 + .../UNIX-Shell/color-quantization.sh | 1 + Task/Color-wheel/C/color-wheel.c | 99 ++ Task/Color-wheel/EasyLang/color-wheel.easy | 9 +- Task/Color-wheel/Emacs-Lisp/color-wheel.l | 75 + .../EasyLang/colorful-numbers.easy | 18 +- .../JavaScript/colorful-numbers.js | 85 + .../EasyLang/colour-bars-display.easy | 5 +- ...rs-display.py => colour-bars-display-1.py} | 0 .../Python/colour-bars-display-2.py | 40 + .../Uxntal/colour-bars-display.uxnatl | 32 +- .../EasyLang/colour-pinstripe-display.easy | 5 +- .../Uxntal/colour-pinstripe-display.uxnatl | 52 +- .../combinations-with-repetitions.easy | 4 +- Task/Combinations/EasyLang/combinations.easy | 2 +- .../Crystal/comma-quibbling.cr | 19 + .../Elena/comma-quibbling-1.elena | 23 + .../Elena/comma-quibbling-2.elena | 31 + ...rch64 => command-line-arguments-1.aarch64} | 0 .../command-line-arguments-2.aarch64 | 26 + .../JavaScript/commatizing-numbers.js | 42 + Task/Comments/OPL/comments.opl | 2 + Task/Comments/Uxntal/comments.uxnatl | 31 + .../EasyLang/compare-a-list-of-strings.easy | 18 +- .../compare-a-list-of-strings.m2000 | 35 + .../compare-length-of-two-strings.easy | 2 +- .../K/compare-length-of-two-strings.k | 11 + .../compare-length-of-two-strings-1.m2000 | 47 + .../compare-length-of-two-strings-2.m2000 | 28 + .../OPL/compare-length-of-two-strings-1.opl | 15 + .../OPL/compare-length-of-two-strings-2.opl | 47 + .../Scheme/compare-length-of-two-strings.scm | 47 + ...ompare-sorting-algorithms-performance-1.rs | 121 ++ ...ompare-sorting-algorithms-performance-2.rs | 16 + ...ompare-sorting-algorithms-performance-3.rs | 121 ++ .../Rust/compiler-ast-interpreter.rs | 400 +++++ .../JavaScript/compiler-code-generator.js | 502 ++++++ .../Rust/compiler-code-generator.rs | 644 +++++++ .../Rust/compiler-lexical-analyzer.rs | 682 ++++++++ .../FreeBASIC/compiler-syntax-analyzer.basic | 370 ++++ .../compiler-syntax-analyzer.m2000 | 2 +- .../Rust/compiler-syntax-analyzer.rs | 659 +++++++ ...whose-factors-are-all-substrings-of-k.easy | 27 +- .../Elena/concurrent-computing.elena | 11 + .../Excel/conditional-structures-1.excel | 1 + .../Excel/conditional-structures-2.excel | 1 + .../Excel/conditional-structures-3.excel | 1 + .../Uxntal/conditional-structures.uxnatl | 32 + ...h-ascending-or-descending-differences.easy | 4 +- ...ascending-or-descending-differences-1.rexx | 64 - ...-ascending-or-descending-differences.rexx} | 39 +- ...constrained-random-points-on-a-circle.easy | 3 +- ...metic-g-matrix-ng-continued-fraction-n-.cs | 70 + .../C-sharp/continued-fraction.cs | 116 +- .../EasyLang/continued-fraction.easy | 26 +- .../REXX/continued-fraction-1.rexx | 87 +- .../REXX/continued-fraction-2.rexx | 96 +- .../REXX/continued-fraction-3.rexx | 101 +- .../convert-seconds-to-compound-duration.cr | 43 + .../convert-seconds-to-compound-duration.easy | 4 +- Task/Convex-hull/EasyLang/convex-hull.easy | 15 +- Task/Convex-hull/Zig/convex-hull.zig | 96 ++ .../EasyLang/conways-game-of-life.easy | 21 +- Task/Copy-a-string/OPL/copy-a-string.opl | 8 + .../Copy-a-string/Uxntal/copy-a-string.uxnatl | 25 + .../Objeck/copy-stdin-to-stdout.objeck | 9 + .../EasyLang/count-in-factors.easy | 7 +- .../REXX/count-in-factors-1.rexx | 37 - .../REXX/count-in-factors-2.rexx | 51 - ...n-factors-3.rexx => count-in-factors.rexx} | 26 +- .../Ballerina/count-in-octal.ballerina | 28 + Task/Cramers-rule/EasyLang/cramers-rule.easy | 24 +- .../create-a-file-on-magnetic-tape.js | 2 + ...te-a-two-dimensional-array-at-runtime.uiua | 7 + .../create-an-object-at-a-given-address.xpl0 | 15 + Task/Cuban-primes/EasyLang/cuban-primes.easy | 25 +- Task/Cuban-primes/OCaml/cuban-primes.ml | 51 + Task/Cuban-primes/REXX/cuban-primes-1.rexx | 27 - ...{cuban-primes-2.rexx => cuban-primes.rexx} | 5 +- .../cumulative-standard-deviation.easy | 7 +- Task/Currency/Ballerina/currency.ballerina | 15 + Task/Currency/C++/currency.cpp | 21 + Task/Currency/Wren/currency.wren | 1 - Task/Currying/Ballerina/currying.ballerina | 12 + Task/Curzon-numbers/Ada/curzon-numbers.ada | 57 + .../EasyLang/curzon-numbers.easy | 6 +- .../EasyLang/cut-a-rectangle.easy | 10 +- .../EasyLang/cyclops-numbers.easy | 10 +- .../Cyclops-numbers/REXX/cyclops-numbers.rexx | 52 +- .../JavaScript/cyclotomic-polynomial.js | 504 ++++++ .../Rust/cyclotomic-polynomial.rs | 552 ++++++ .../Free-Pascal-Lazarus/dns-query.pas | 35 + Task/Damm-algorithm/Uiua/damm-algorithm.uiua | 21 + Task/Date-format/JavaScript/date-format.js | 20 +- .../Pascal/date-manipulation.pas | 108 ++ .../EasyLang/de-bruijn-sequences.easy | 18 +- .../JavaScript/de-bruijn-sequences.js | 96 ++ .../Zig/de-bruijn-sequences.zig | 111 ++ .../EasyLang/deal-cards-for-freecell.easy | 12 +- .../FreeBASIC/deconvolution-2d+.basic | 183 ++ .../EasyLang/demings-funnel.easy | 33 +- .../EasyLang/department-numbers.easy | 2 +- .../Nu/department-numbers.nu | 24 + .../EasyLang/descending-primes.easy | 26 +- .../Rust/descending-primes-1.rs | 1 + .../Rust/descending-primes-2.rs | 1 + .../Rust/descending-primes-3.rs | 1 + .../Rust/descending-primes-4.rs | 1 + ...ro.rexx => detect-division-by-zero-1.rexx} | 0 .../REXX/detect-division-by-zero-2.rexx | 10 + .../REXX/detect-division-by-zero-3.rexx | 4 + ...if-a-string-has-all-the-same-characters.cr | 10 + ...-a-string-has-all-the-same-characters.easy | 6 +- ...-a-string-has-all-the-same-characters-1.nu | 20 + ...-a-string-has-all-the-same-characters-2.nu | 27 + ...if-a-string-has-all-unique-characters.easy | 6 +- .../determine-if-a-string-is-collapsible.cr | 16 + .../determine-if-a-string-is-squeezable.easy | 6 +- .../determine-if-two-triangles-overlap.easy | 14 +- .../R/determine-sentence-type.r | 14 + .../Arturo/dice-game-probabilities.arturo | 11 + .../EasyLang/dice-game-probabilities.easy | 4 +- .../Quackery/dice-game-probabilities.quackery | 14 + ...ital-root-multiplicative-digital-root.easy | 14 +- Task/Digital-root/REXX/digital-root-2.rexx | 49 +- Task/Digital-root/REXX/digital-root-3.rexx | 20 - Task/Digital-root/REXX/digital-root-4.rexx | 57 - .../Crystal/dijkstras-algorithm.cr | 43 + .../EasyLang/dijkstras-algorithm.easy | 8 +- .../Tcl/dijkstras-algorithm-2.tcl | 28 +- .../Zig/dijkstras-algorithm.zig | 158 ++ .../dinesmans-multiple-dwelling-problem.easy | 43 +- .../PARI-GP/disarium-numbers.parigp | 20 + Task/Disarium-numbers/R/disarium-numbers.r | 16 + .../EasyLang/discordian-date.easy | 10 +- .../R/display-a-linear-combination.r | 27 + .../Objeck/distributed-programming.objeck | 32 + ...on-of-0-digits-in-factorial-series-1.basic | 86 + ...on-of-0-digits-in-factorial-series-2.basic | 33 + ...ibution-of-0-digits-in-factorial-series.js | 40 + .../diversity-prediction-theorem.easy | 6 +- .../Rust/doubly-linked-list-definition-1.rs | 7 + .../Rust/doubly-linked-list-definition-2.rs | 40 + ...doubly-linked-list-element-definition-1.rs | 5 - ...doubly-linked-list-element-definition-2.rs | 12 - .../doubly-linked-list-element-definition.rs | 5 + .../doubly-linked-list-element-insertion-1.rs | 16 +- .../doubly-linked-list-element-insertion-2.rs | 93 +- .../Rust/doubly-linked-list-traversal.rs | 15 + Task/Dragon-curve/EasyLang/dragon-curve.easy | 11 +- Task/Draw-a-clock/EasyLang/draw-a-clock.easy | 48 +- Task/Draw-a-clock/OPL/draw-a-clock.opl | 4 + .../Draw-a-cuboid/EasyLang/draw-a-cuboid.easy | 36 +- Task/Draw-a-cuboid/R/draw-a-cuboid.r | 14 + Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy | 5 +- Task/Draw-a-pixel/OPL/draw-a-pixel.opl | 8 + Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl | 22 - .../EasyLang/draw-a-rotating-cube.easy | 31 +- .../EasyLang/duffinian-numbers.easy | 10 +- .../Crystal/dutch-national-flag-problem.cr | 34 + .../R/dutch-national-flag-problem.r | 26 + .../dynamic-variable-names.ballerina | 16 + Task/Eban-numbers/EasyLang/eban-numbers.easy | 23 +- .../EasyLang/egyptian-division.easy | 2 +- .../Arturo/element-wise-operations.arturo | 41 + .../EasyLang/element-wise-operations.easy | 67 + ...erations.k => element-wise-operations-1.k} | 0 .../K/element-wise-operations-2.k | 6 + .../elementary-cellular-automaton.easy | 10 +- ...iptic-curve-digital-signature-algorithm.cs | 369 ++++ ...iptic-curve-digital-signature-algorithm.js | 356 ++++ ...iptic-curve-digital-signature-algorithm.rs | 507 ++++++ .../ALGOL-68/elliptic-curve-arithmetic.alg | 81 + .../FreeBASIC/elliptic-curve-arithmetic.basic | 98 ++ .../JavaScript/elliptic-curve-arithmetic.js | 90 + Task/Emirp-primes/REXX/emirp-primes-1.rexx | 163 +- Task/Emirp-primes/REXX/emirp-primes-2.rexx | 214 +-- Task/Emirp-primes/REXX/emirp-primes-3.rexx | 92 - .../Ballerina/empty-string.ballerina | 12 + .../Arturo/entropy-narcissist.arturo | 7 + .../equal-prime-and-composite-sums.easy | 19 +- .../Uiua/ethiopian-multiplication.uiua | 10 + .../REXX/euclid-mullin-sequence.rexx | 57 +- Task/Euler-method/EasyLang/euler-method.easy | 30 +- Task/Euler-method/K/euler-method.k | 15 + Task/Euler-method/Odin/euler-method.odin | 36 + Task/Euler-method/Q/euler-method.q | 10 + .../EasyLang/eulers-constant-0.5772....easy | 2 +- .../Fortran/eulers-constant-0.5772....f | 131 ++ .../REXX/eulers-constant-0.5772....rexx | 13 +- .../evaluate-binomial-coefficients.asymptote | 34 + .../evaluate-binomial-coefficients.basic | 29 + .../evaluate-binomial-coefficients.basic | 23 + .../evaluate-binomial-coefficients.gambas | 36 + .../evaluate-binomial-coefficients.basic | 22 + .../evaluate-binomial-coefficients.basic | 25 + .../evaluate-binomial-coefficients.basic | 38 + .../Prolog/evaluate-binomial-coefficients.pro | 10 + .../evaluate-binomial-coefficients.basic | 45 + .../evaluate-binomial-coefficients-1.basic | 35 + .../evaluate-binomial-coefficients-2.basic | 25 + .../evaluate-binomial-coefficients.basic | 33 + Task/Events/EasyLang/events.easy | 6 +- Task/Execute-Brain-/Crystal/execute-brain-.cr | 33 + .../EasyLang/execute-brain-.easy | 6 +- Task/Execute-Brain-/Odin/execute-brain-.odin | 126 ++ .../EasyLang/execute-computer-zero.easy | 2 +- .../Perl/execute-computer-zero.pl | 154 ++ Task/Execute-HQ9+/EasyLang/execute-hq9+.easy | 2 +- .../Execute-SNUSP/EasyLang/execute-snusp.easy | 10 +- .../C-sharp/execute-a-markov-algorithm.cs | 161 ++ .../Zig/execute-a-markov-algorithm.zig | 278 +++ .../C-sharp/extensible-prime-generator.cs | 88 + .../EasyLang/extensible-prime-generator.easy | 2 +- .../REXX/extensible-prime-generator-1.rexx | 50 - .../REXX/extensible-prime-generator-3.rexx | 9 - ...2.rexx => extensible-prime-generator.rexx} | 52 +- .../extreme-floating-point-values.ballerina | 34 + Task/Factorial/EasyLang/factorial.easy | 4 +- Task/Factorial/Java/factorial-4.java | 27 + .../M2000-Interpreter/factorial-2.m2000 | 25 +- Task/Factorial/Pascal/factorial-2.pas | 65 +- Task/Factorial/Pascal/factorial-3.pas | 107 +- Task/Factorial/REXX/factorial-1.rexx | 22 +- Task/Factorial/REXX/factorial-2.rexx | 91 +- Task/Factorial/REXX/factorial-3.rexx | 27 - Task/Factorial/REXX/factorial-4.rexx | 4 - Task/Factorial/REXX/factorial-5.rexx | 67 - Task/Factorial/SQL/factorial.sql | 6 + Task/Factorial/Tcl/factorial-1.tcl | 14 +- Task/Factorial/Tcl/factorial-2.tcl | 7 +- Task/Factorial/Tcl/factorial-3.tcl | 4 +- Task/Factorial/Tcl/factorial-4.tcl | 18 +- Task/Factorial/Tcl/factorial-5.tcl | 28 +- Task/Factorial/Tcl/factorial-6.tcl | 14 +- Task/Factorial/Tcl/factorial-7.tcl | 5 + Task/Factorial/Uxntal/factorial.uxnatl | 28 +- Task/Factorions/EasyLang/factorions.easy | 21 + Task/Factorions/R/factorions.r | 15 + .../REXX/factors-of-a-mersenne-number-1.rexx | 53 - ...rexx => factors-of-a-mersenne-number.rexx} | 16 +- .../EasyLang/factors-of-an-integer.easy | 13 +- .../REXX/factors-of-an-integer-1.rexx | 61 +- .../REXX/factors-of-an-integer-2.rexx | 54 +- .../REXX/factors-of-an-integer-3.rexx | 57 - .../fairshare-between-two-and-more.easy | 2 +- .../Ballerina/farey-sequence.ballerina | 83 + .../EasyLang/farey-sequence.easy | 6 +- .../EasyLang/fast-fourier-transform.easy | 2 +- .../Faulhabers-formula/C/faulhabers-formula.c | 254 ++- .../Rust/faulhabers-formula.rs | 178 ++ .../feigenbaum-constant-calculation.easy | 9 +- .../feigenbaum-constant-calculation-1.rexx | 33 - ...x => feigenbaum-constant-calculation.rexx} | 23 +- .../FreeBASIC/fermat-numbers.basic | 102 ++ .../Fermat-numbers/REXX/fermat-numbers-1.rexx | 33 - .../Fermat-numbers/REXX/fermat-numbers-2.rexx | 36 - ...mat-numbers-3.rexx => fermat-numbers.rexx} | 11 +- .../fibonacci-n-step-number-sequences.easy | 6 +- .../APL/fibonacci-sequence-1.apl | 2 +- .../APL/fibonacci-sequence-2.apl | 2 +- .../APL/fibonacci-sequence-3.apl | 2 +- .../APL/fibonacci-sequence-4.apl | 2 +- .../APL/fibonacci-sequence-5.apl | 1 + .../K/fibonacci-sequence-1.k | 2 +- .../K/fibonacci-sequence-2.k | 2 +- .../Uxntal/fibonacci-sequence.uxnatl | 31 + .../Zig/fibonacci-sequence.zig | 14 + .../EasyLang/fibonacci-word.easy | 6 +- .../file-extension-is-in-extensions-list.cs | 20 + ...file-extension-is-in-extensions-list.m2000 | 35 + .../file-extension-is-in-extensions-list.nu | 20 + .../Nu/file-size-distribution.nu | 24 + .../Tcl/file-size-distribution-1.tcl | 75 + ...ution.tcl => file-size-distribution-2.tcl} | 0 ...nd-chess960-starting-position-identifier.d | 83 + .../BQN/find-common-directory-path.bqn | 9 + .../find-if-a-point-is-within-a-triangle.cs | 90 + .../find-if-a-point-is-within-a-triangle.easy | 23 +- ...eft-truncatable-prime-in-a-given-base.rexx | 10 +- .../find-limit-of-recursion.ballerina | 10 + .../EasyLang/find-limit-of-recursion.easy | 6 +- ...bers-in-both-binary-and-ternary-bases.easy | 15 +- ...numbers-in-both-binary-and-ternary-bases.r | 82 + ...e-intersection-of-a-line-with-a-plane.easy | 29 +- .../find-the-intersection-of-two-lines.easy | 24 +- .../find-the-last-sunday-of-each-month.easy | 10 +- .../find-the-missing-permutation.easy | 36 +- .../Zig/find-the-missing-permutation.zig | 39 + ...square-in-base-n-with-n-unique-digits.easy | 10 +- ...ct-square-in-base-n-with-n-unique-digits.f | 100 ++ ...that-has-leading-decimal-digits-of-12.easy | 6 +- Task/Fivenum/Ballerina/fivenum.ballerina | 30 + Task/Fivenum/EasyLang/fivenum.easy | 10 +- Task/FizzBuzz/APL/fizzbuzz-1.apl | 4 +- Task/FizzBuzz/APL/fizzbuzz-2.apl | 2 +- Task/FizzBuzz/APL/fizzbuzz-3.apl | 2 +- Task/FizzBuzz/APL/fizzbuzz-4.apl | 3 +- Task/FizzBuzz/APL/fizzbuzz-5.apl | 42 +- Task/FizzBuzz/APL/fizzbuzz-6.apl | 4 +- Task/FizzBuzz/APL/fizzbuzz-7.apl | 40 + .../Erlang/{fizzbuzz.erl => fizzbuzz-1.erl} | 0 Task/FizzBuzz/Erlang/fizzbuzz-2.erl | 27 + Task/FizzBuzz/Excel/fizzbuzz.excel | 11 + Task/FizzBuzz/Factor/fizzbuzz-1.factor | 9 +- Task/FizzBuzz/Factor/fizzbuzz-2.factor | 24 +- Task/FizzBuzz/Factor/fizzbuzz-3.factor | 37 +- Task/FizzBuzz/Factor/fizzbuzz-4.factor | 24 + Task/FizzBuzz/J/fizzbuzz-1.j | 3 +- Task/FizzBuzz/J/fizzbuzz-10.j | 2 + Task/FizzBuzz/J/fizzbuzz-11.j | 36 + Task/FizzBuzz/J/fizzbuzz-2.j | 2 +- Task/FizzBuzz/J/fizzbuzz-3.j | 6 +- Task/FizzBuzz/J/fizzbuzz-4.j | 7 +- Task/FizzBuzz/J/fizzbuzz-5.j | 7 +- Task/FizzBuzz/J/fizzbuzz-6.j | 7 +- Task/FizzBuzz/J/fizzbuzz-7.j | 42 +- Task/FizzBuzz/J/fizzbuzz-8.j | 6 + Task/FizzBuzz/J/fizzbuzz-9.j | 1 + Task/FizzBuzz/K/fizzbuzz-1.k | 2 +- Task/FizzBuzz/K/fizzbuzz-2.k | 3 +- Task/FizzBuzz/K/fizzbuzz-3.k | 9 +- Task/FizzBuzz/K/fizzbuzz-4.k | 9 +- Task/FizzBuzz/Pascal/fizzbuzz.pas | 14 - Task/FizzBuzz/Python/fizzbuzz-10.py | 40 +- Task/FizzBuzz/Python/fizzbuzz-11.py | 34 +- Task/FizzBuzz/Python/fizzbuzz-12.py | 13 +- Task/FizzBuzz/Python/fizzbuzz-13.py | 13 +- Task/FizzBuzz/Python/fizzbuzz-14.py | 1 + Task/FizzBuzz/Python/fizzbuzz-8.py | 18 +- Task/FizzBuzz/Python/fizzbuzz-9.py | 14 +- Task/FizzBuzz/Smalltalk/fizzbuzz-4.st | 22 +- Task/FizzBuzz/Smalltalk/fizzbuzz-5.st | 15 +- Task/FizzBuzz/Smalltalk/fizzbuzz-6.st | 10 +- Task/FizzBuzz/Smalltalk/fizzbuzz-7.st | 5 + .../Uxntal/flow-control-structures.uxnatl | 24 + .../EasyLang/floyd-warshall-algorithm.easy | 6 +- .../XPL0/floyd-warshall-algorithm.xpl0 | 49 + .../Zig/floyd-warshall-algorithm.zig | 99 ++ .../Ballerina/floyds-triangle.ballerina | 20 + .../EasyLang/floyds-triangle.easy | 8 +- .../Objeck/floyds-triangle.objeck | 20 + .../YAMLScript/floyds-triangle.ys | 2 +- Task/Forest-fire/EasyLang/forest-fire.easy | 79 +- Task/Forest-fire/J/forest-fire-3.j | 16 + Task/Forest-fire/J/forest-fire-4.j | 10 + ...put.alg => formatted-numeric-output-1.alg} | 0 .../ALGOL-68/formatted-numeric-output-2.alg | 59 + .../formatted-numeric-output.basic | 27 + .../JavaScript/formatted-numeric-output.js | 21 +- .../EasyLang/fortunate-numbers.easy | 22 +- .../REXX/fortunate-numbers-1.rexx | 54 - ...-numbers-2.rexx => fortunate-numbers.rexx} | 8 +- .../Ballerina/four-bit-adder.ballerina | 31 + .../EasyLang/four-bit-adder.easy | 8 +- Task/Fractal-tree/EasyLang/fractal-tree.easy | 24 +- Task/Fractran/EasyLang/fractran.easy | 10 +- Task/Fractran/Julia/fractran.jl | 75 +- Task/Fractran/Odin/fractran.odin | 77 + Task/Fractran/REXX/fractran.rexx | 4 +- .../Ballerina/function-definition.ballerina | 9 + .../Excel/function-definition.excel | 4 + .../EasyLang/galton-box-animation.easy | 25 +- .../EasyLang/gamma-function.easy | 4 +- Task/Gamma-function/REXX/gamma-function.rexx | 19 +- .../Ballerina/gapful-numbers.ballerina | 26 + .../EasyLang/gapful-numbers.easy | 6 +- .../gauss-jordan-matrix-inversion.easy | 24 +- .../gauss-jordan-matrix-inversion.js | 99 ++ .../EasyLang/gaussian-elimination.easy | 2 +- .../D/generate-chess960-starting-position-1.d | 72 +- .../D/generate-chess960-starting-position-2.d | 32 +- .../D/generate-chess960-starting-position-3.d | 20 +- .../D/generate-chess960-starting-position-4.d | 11 + .../D/generate-chess960-starting-position-5.d | 13 + .../generate-chess960-starting-position.pas | 41 + .../generate-chess960-starting-position.easy | 2 +- .../generate-chess960-starting-position-3.rs | 36 + .../generate-lower-case-ascii-alphabet.objeck | 7 + ...> generate-lower-case-ascii-alphabet-1.rs} | 0 .../generate-lower-case-ascii-alphabet-2.rs | 1 + ...ential.tcl => generator-exponential-1.tcl} | 0 .../Tcl/generator-exponential-2.tcl | 13 + .../Tcl/generator-exponential-3.tcl | 54 + .../Ursalang/generator-exponential.ursa | 1 - ...globally-replace-text-in-several-files.bqn | 9 + .../EasyLang/goldbachs-comet.easy | 18 +- Task/Goldbachs-comet/Go/goldbachs-comet.go | 63 + .../Goldbachs-comet/REXX/goldbachs-comet.rexx | 19 +- .../EasyLang/golden-ratio-convergence.easy | 2 +- Task/Gotchas/C-sharp/gotchas.cs | 18 + .../FreeBASIC/graph-colouring.basic | 149 ++ .../JavaScript/graph-colouring.js | 222 +++ Task/Graph-colouring/Rust/graph-colouring.rs | 134 ++ Task/Gray-code/SETL/gray-code.setl | 29 + .../M2000-Interpreter/grayscale-image.m2000 | 397 ++--- .../greatest-subsequential-sum.ballerina | 42 + .../EasyLang/greatest-subsequential-sum.easy | 6 +- .../greatest-subsequential-sum-1.m2000 | 26 + .../greatest-subsequential-sum-2.m2000 | 36 + ...greedy-algorithm-for-egyptian-fractions.js | 222 +++ .../EasyLang/greyscale-bars-display.easy | 5 +- Task/HTTP/Elena/http.elena | 13 + Task/HTTPS/Elena/https.elena | 14 + .../Ballerina/hailstone-sequence.ballerina | 34 + .../EasyLang/hailstone-sequence.easy | 14 +- .../Odin/hailstone-sequence.odin | 65 + .../R/halt-and-catch-fire-1.r | 1 + .../R/halt-and-catch-fire-2.r | 1 + .../REXX/hamming-numbers-1.rexx | 20 - .../REXX/hamming-numbers-2.rexx | 26 - .../REXX/hamming-numbers-3.rexx | 26 - .../REXX/hamming-numbers-4.rexx | 73 - .../Hamming-numbers/REXX/hamming-numbers.rexx | 40 + .../EasyLang/harmonic-series.easy | 2 +- .../Harmonic-series/Fortran/harmonic-series.f | 83 + .../hello-world-graphical.ahk | 0 .../EasyLang/hello-world-graphical.easy | 4 +- .../Odin/hello-world-graphical.odin | 27 + .../Uxntal/hello-world-graphical.uxnatl | 240 +++ .../hello-world-newline-omission.ballerina | 5 + .../hello-world-newline-omission.uxnatl | 26 +- ...4 => hello-world-standard-error-1.aarch64} | 0 .../hello-world-standard-error-2.aarch64 | 16 + .../hello-world-standard-error.arm | 2 +- .../hello-world-standard-error.ballerina | 5 + .../Crystal/hello-world-standard-error.cr | 1 + .../Objeck/hello-world-standard-error.objeck | 5 + .../Uxntal/hello-world-standard-error.uxnatl | 17 + ...ext.aarch64 => hello-world-text-1.aarch64} | 0 .../hello-world-text-2.aarch64 | 16 + .../hello-world-text-3.aarch64 | 21 + .../Hello-world-Text/OPL/hello-world-text.opl | 4 + .../Uxntal/hello-world-text.uxnatl | 22 - .../EasyLang/heronian-triangles.easy | 30 +- Task/Hex-words/Crystal/hex-words.cr | 10 + Task/Hex-words/EasyLang/hex-words.easy | 22 +- Task/Hex-words/R/hex-words.r | 43 + Task/Hex-words/Rust/hex-words.rs | 83 + .../Pascal/higher-order-functions-3.pas | 936 ++++------ .../REXX/higher-order-functions-2.rexx | 12 - ...ons-1.rexx => higher-order-functions.rexx} | 12 +- .../Hilbert-curve/EasyLang/hilbert-curve.easy | 13 +- .../hofstadter-conway-$10-000-sequence.easy | 6 +- .../hofstadter-figure-figure-sequences.easy | 4 +- .../EasyLang/hofstadter-q-sequence.easy | 12 +- Task/Home-primes/REXX/home-primes-1.rexx | 46 - Task/Home-primes/REXX/home-primes-2.rexx | 40 - Task/Home-primes/REXX/home-primes.rexx | 48 + ...ners-rule-for-polynomial-evaluation-2.rexx | 5 +- .../EasyLang/humble-numbers.easy | 28 +- .../Humble-numbers/REXX/humble-numbers-1.rexx | 44 - .../Humble-numbers/REXX/humble-numbers-2.rexx | 86 - Task/Humble-numbers/REXX/humble-numbers.rexx | 48 + .../Nu/i-before-e-except-after-c-1.nu | 32 + .../Nu/i-before-e-except-after-c-2.nu | 48 + Task/IBAN/EasyLang/iban.easy | 2 +- .../EasyLang/identity-matrix.easy | 2 +- ...y-matrix.excel => identity-matrix-1.excel} | 0 .../Excel/identity-matrix-2.excel | 1 + ...-a-software-engineer-get-me-out-of-here.py | 175 ++ Task/Image-noise/EasyLang/image-noise.easy | 23 +- .../Bracmat/include-a-file.bracmat | 2 +- ...aps-between-consecutive-niven-numbers.easy | 2 +- .../Crystal/increment-a-numerical-string.cr | 5 + .../Tcl/increment-a-numerical-string-1.tcl | 10 + .../Tcl/increment-a-numerical-string-2.tcl | 6 + .../Tcl/increment-a-numerical-string-3.tcl | 5 + .../Tcl/increment-a-numerical-string-4.tcl | 4 + .../Tcl/increment-a-numerical-string-5.tcl | 2 + .../Tcl/increment-a-numerical-string-6.tcl | 1 + .../Tcl/increment-a-numerical-string.tcl | 2 - ...index-finite-lists-of-positive-integers.cs | 107 ++ .../{input-loop.js => input-loop-1.js} | 0 Task/Input-loop/JavaScript/input-loop-2.js | 21 + .../Uxntal/integer-sequence.uxnatl | 23 + .../Crystal/interactive-programming-repl-.cr | 11 + ...nverted-syntax.rb => inverted-syntax-1.rb} | 0 .../Inverted-syntax/Ruby/inverted-syntax-2.rb | 4 + .../EasyLang/isograms-and-heterograms.easy | 38 +- .../isqrt-integer-square-root-of-x.js | 36 + .../REXX/isqrt-integer-square-root-of-x.rexx | 169 +- .../Jacobi-symbol/EasyLang/jacobi-symbol.easy | 18 +- .../Jacobi-symbol/JavaScript/jacobi-symbol.js | 52 + .../EasyLang/jaro-winkler-distance.easy | 32 +- .../M2000-Interpreter/jensens-device-1.m2000 | 4 +- .../M2000-Interpreter/jensens-device-2.m2000 | 4 +- .../M2000-Interpreter/jensens-device-3.m2000 | 4 +- .../EasyLang/jordan-p-lya-numbers.easy | 14 +- Task/JortSort/EasyLang/jortsort.easy | 10 +- .../FreeBASIC/juggler-sequence.basic | 87 + Task/Julia-set/EasyLang/julia-set.easy | 27 +- Task/K-d-tree/C-sharp/k-d-tree.cs | 472 +++++ Task/K-d-tree/Dart/k-d-tree.dart | 220 +++ Task/K-d-tree/JavaScript/k-d-tree.js | 235 +++ .../kernighans-large-earthquake-problem.alg | 3 +- .../R/kernighans-large-earthquake-problem.r | 2 + ...keyboard-input-flush-the-keyboard-buffer.l | 1 + .../keyboard-input-keypress-check.easy | 5 +- .../keyboard-input-keypress-check.l | 21 + ...yboard-input-obtain-a-y-or-n-response.easy | 6 +- .../keyboard-input-obtain-a-y-or-n-response.l | 5 + ...board-input-obtain-a-y-or-n-response-1.tcl | 42 +- ...board-input-obtain-a-y-or-n-response-2.tcl | 24 +- ...board-input-obtain-a-y-or-n-response-3.tcl | 11 + .../EasyLang/knapsack-problem-0-1.easy | 6 +- .../EasyLang/knapsack-problem-bounded.easy | 18 +- .../Nim/knapsack-problem-continuous.nim | 2 +- .../EasyLang/knapsack-problem-unbounded.easy | 2 +- Task/Knights-tour/EasyLang/knights-tour.easy | 76 +- .../Knuth-shuffle/EasyLang/knuth-shuffle.easy | 2 +- .../Knuth-shuffle/Objeck/knuth-shuffle.objeck | 21 + Task/Knuth-shuffle/Wisp/knuth-shuffle.wisp | 30 + .../Fortran/knuths-algorithm-s.f | 121 ++ .../FreeBASIC/knuths-algorithm-s.basic | 98 ++ .../JavaScript/knuths-algorithm-s.js | 36 + .../FreeBASIC/knuths-power-tree.basic | 247 +++ .../JavaScript/knuths-power-tree.js | 103 ++ Task/Koch-curve/EasyLang/koch-curve.easy | 19 +- Task/Kosaraju/EasyLang/kosaraju.easy | 4 +- Task/Kosaraju/Rust/kosaraju.rs | 91 + .../kronecker-product-based-fractals.easy | 7 +- Task/Langtons-ant/EasyLang/langtons-ant.easy | 13 +- .../largest-int-from-concatenated-ints.xpl0 | 34 + ...argest-number-divisible-by-its-digits.easy | 12 +- .../ALGOL-60/largest-proper-divisor-of-n.alg | 33 + .../EasyLang/last-friday-of-each-month.easy | 10 +- .../EasyLang/last-letter-first-letter.easy | 6 +- .../FreeBASIC/last-letter-first-letter.basic | 55 + .../XPL0/last-letter-first-letter.xpl0 | 68 + .../Rust/latin-squares-in-reduced-form.rs | 144 ++ .../Zig/latin-squares-in-reduced-form.zig | 207 +++ .../legendre-prime-counting-function-1.rexx | 13 +- .../legendre-prime-counting-function-2.rexx | 13 +- .../legendre-prime-counting-function-3.rexx | 7 +- .../ERRE/leonardo-numbers.erre | 24 + .../EasyLang/leonardo-numbers.easy | 2 +- ...ter-frequency.nu => letter-frequency-1.nu} | 0 .../Letter-frequency/Nu/letter-frequency-2.nu | 1 + .../levenshtein-distance-alignment.easy | 26 +- .../ANSI-BASIC/levenshtein-distance.basic | 29 + .../levenshtein-distance.basic | 18 + .../Ballerina/levenshtein-distance.ballerina | 31 + .../levenshtein-distance.pas | 40 + .../GW-BASIC/levenshtein-distance.basic | 28 + .../Nascom-BASIC/levenshtein-distance.basic | 33 + .../Pascal/levenshtein-distance.pas | 38 - .../RapidQ/levenshtein-distance.rapidq | 36 + .../XBasic/levenshtein-distance.basic | 40 + .../XPL0/levenshtein-distance.xpl0 | 40 + .../EasyLang/list-rooted-trees.easy | 24 +- .../REXX/literals-floating-point-1.rexx | 6 - .../REXX/literals-floating-point-2.rexx | 3 - .../REXX/literals-floating-point.rexx | 52 + .../JavaScript/literals-integer.js | 6 +- .../REXX/literals-integer.rexx | 80 +- .../EasyLang/logical-operations.easy | 2 +- Task/Long-primes/EasyLang/long-primes.easy | 14 +- Task/Long-primes/REXX/long-primes-1.rexx | 22 - Task/Long-primes/REXX/long-primes-2.rexx | 28 - Task/Long-primes/REXX/long-primes-3.rexx | 38 - Task/Long-primes/REXX/long-primes.rexx | 56 + .../C-sharp/longest-string-challenge.cs | 36 + .../EasyLang/look-and-say-sequence.easy | 2 +- .../MAD/look-and-say-sequence.mad | 36 + .../Python/look-and-say-sequence-5.py | 9 + .../SETL/look-and-say-sequence.setl | 14 +- ...r-multiple-arrays-simultaneously.ballerina | 10 + Task/Loops-Break/ALGOL-68/loops-break.alg | 14 +- .../Ballerina/loops-break.ballerina | 12 + Task/Loops-Break/Uxntal/loops-break.uxnatl | 62 + .../Ballerina/loops-continue.ballerina | 12 + .../Uxntal/loops-continue.uxnatl | 31 + .../Ballerina/loops-do-while-1.ballerina | 10 + .../Ballerina/loops-do-while-2.ballerina | 11 + Task/Loops-Do-while/SETL/loops-do-while.setl | 7 + .../Uxntal/loops-do-while.uxnatl | 22 + .../Ballerina/loops-downward-for.ballerina | 8 + .../loops-for-with-a-specified-step.ballerina | 9 + .../loops-for-with-a-specified-step.uxnatl | 20 + Task/Loops-For/Ballerina/loops-for.ballerina | 8 + Task/Loops-For/Excel/loops-for.excel | 9 + .../M2000-Interpreter/loops-for-1.m2000 | 4 + .../M2000-Interpreter/loops-for-2.m2000 | 17 + .../M2000-Interpreter/loops-for.m2000 | 14 - .../Ballerina/loops-foreach.ballerina | 8 + .../Loops-Foreach/Uxntal/loops-foreach.uxnatl | 44 + ...-increment-loop-index-within-loop-body.alg | 43 + ...ment-loop-index-within-loop-body.ballerina | 39 + ...increment-loop-index-within-loop-body.icon | 40 + ...ncrement-loop-index-within-loop-body.basic | 41 + ...increment-loop-index-within-loop-body.setl | 29 + .../8080-Assembly/loops-infinite.8080 | 7 + Task/Loops-Infinite/APL/loops-infinite.apl | 1 + .../Ballerina/loops-infinite.ballerina | 7 + Task/Loops-Infinite/J/loops-infinite-1.j | 2 +- Task/Loops-Infinite/J/loops-infinite-2.j | 2 +- Task/Loops-Infinite/J/loops-infinite-3.j | 1 + Task/Loops-Infinite/K/loops-infinite-1.k | 1 + Task/Loops-Infinite/K/loops-infinite-2.k | 1 + Task/Loops-Infinite/K/loops-infinite.k | 1 - .../Miranda/loops-infinite.miranda | 2 + .../Loops-Infinite/Refal/loops-infinite.refal | 1 + Task/Loops-Infinite/SETL/loops-infinite.setl | 5 + .../Uxntal/loops-infinite.uxnatl | 8 +- .../Ballerina/loops-n-plus-one-half.ballerina | 8 + .../Crystal/loops-n-plus-one-half.cr | 6 + .../Uxntal/loops-n-plus-one-half.uxnatl | 34 + .../Ballerina/loops-nested.ballerina | 23 + Task/Loops-Nested/Icon/loops-nested-1.icon | 15 +- Task/Loops-Nested/Icon/loops-nested-2.icon | 5 +- .../Ballerina/loops-while.ballerina | 12 +- Task/Loops-While/Uxntal/loops-while.uxnatl | 21 + .../loops-with-multiple-ranges.ballerina | 82 + .../Ballerina/loops-wrong-ranges.ballerina | 29 + .../REXX/lucas-lehmer-test.rexx | 120 +- ...mer-test.raku => lucas-lehmer-test-1.raku} | 0 .../Raku/lucas-lehmer-test-2.raku | 16 + .../Ludic-numbers/EasyLang/ludic-numbers.easy | 4 +- Task/Ludic-numbers/REXX/ludic-numbers.rexx | 89 +- ...=> luhn-test-of-credit-card-numbers-1.lua} | 6 +- .../luhn-test-of-credit-card-numbers-2.lua | 8 + .../luhn-test-of-credit-card-numbers-3.lua | 3 + .../ANSI-BASIC/m-bius-function.basic | 28 + .../M-bius-function/ASIC/m-bius-function.asic | 37 + .../EasyLang/m-bius-function.easy | 14 +- .../JavaScript/m-bius-function-1.js | 32 + .../JavaScript/m-bius-function-2.js | 7 + Task/M-bius-function/K/m-bius-function.k | 8 + .../Modula-2/m-bius-function.mod2 | 41 + Task/M-bius-function/PHP/m-bius-function.php | 29 + .../REXX/m-bius-function-1.rexx | 49 - .../REXX/m-bius-function-2.rexx | 41 - .../M-bius-function/REXX/m-bius-function.rexx | 30 + .../RapidQ/m-bius-function.rapidq | 36 + .../EasyLang/md5-implementation.easy | 16 +- .../JavaScript/md5-implementation.js | 209 +++ Task/MD5/EasyLang/md5.easy | 20 +- Task/Mad-Libs/ALGOL-68/mad-libs.alg | 210 ++- Task/Mad-Libs/EasyLang/mad-libs.easy | 58 + Task/Mad-Libs/F-Sharp/mad-libs.fs | 63 + Task/Mad-Libs/Objeck/mad-libs.objeck | 34 + Task/Magic-8-ball/Crystal/magic-8-ball.cr | 13 + .../ANSI-BASIC/magic-constant.basic | 25 + Task/Magic-constant/C/magic-constant.c | 32 + .../GW-BASIC/magic-constant.basic | 24 + .../Gambas/magic-constant.gambas | 35 + .../Modula-2/magic-constant.mod2 | 46 + Task/Magic-constant/PHP/magic-constant.php | 27 + Task/Magic-constant/REXX/magic-constant.rexx | 62 + .../Tiny-BASIC/magic-constant.basic | 21 + .../magic-squares-of-doubly-even-order.easy | 25 +- .../EasyLang/magic-squares-of-odd-order.easy | 4 +- .../magic-squares-of-singly-even-order.easy | 17 +- .../EasyLang/magnanimous-numbers.easy | 22 +- .../REXX/magnanimous-numbers.rexx | 73 +- .../EasyLang/mandelbrot-set.easy | 61 +- Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl | 45 +- .../Mandelbrot-set/Python/mandelbrot-set-8.py | 50 +- Task/Map-range/ANSI-BASIC/map-range.basic | 10 + .../Free-Pascal-Lazarus/map-range-1.pas | 13 + .../Free-Pascal-Lazarus/map-range-2.pas | 58 + Task/Map-range/GW-BASIC/map-range.basic | 13 + Task/Map-range/Liberty-BASIC/map-range.basic | 16 +- Task/Map-range/Modula-2/map-range.mod2 | 22 + Task/Map-range/PHP/map-range.php | 15 + Task/Map-range/Pascal/map-range-1.pas | 13 - Task/Map-range/Pascal/map-range-2.pas | 56 - Task/Map-range/QBasic/map-range.basic | 10 + Task/Map-range/RapidQ/map-range.rapidq | 11 + Task/Map-range/TypeScript/map-range.ts | 14 + Task/Mastermind/EasyLang/mastermind.easy | 177 +- .../EasyLang/matrix-chain-multiplication.easy | 4 +- .../VBScript/matrix-multiplication.vb | 26 +- .../EasyLang/matrix-transposition.easy | 2 +- .../Uiua/matrix-transposition.uiua | 2 + .../EasyLang/mayan-numerals.easy | 18 +- .../EasyLang/maze-generation.easy | 19 +- Task/Maze-solving/EasyLang/maze-solving.easy | 32 +- Task/Median-filter/Rust/median-filter.rs | 510 ++++++ .../EasyLang/meissel-mertens-constant.easy | 13 +- .../REXX/meissel-mertens-constant.rexx | 12 +- .../merge-and-aggregate-datasets.easy | 14 +- ...c => merge-and-aggregate-datasets-1.basic} | 0 .../merge-and-aggregate-datasets-2.basic | 248 +++ .../Logo/merge-and-aggregate-datasets-1.logo | 87 + .../Logo/merge-and-aggregate-datasets-2.logo | 5 + .../EasyLang/mertens-function.easy | 10 +- .../REXX/mertens-function.rexx | 175 +- .../REXX/miller-rabin-primality-test.rexx | 4 +- .../EasyLang/mind-boggling-card-trick.easy | 26 +- .../EasyLang/minesweeper-game.easy | 108 +- .../modified-random-distribution.easy | 2 +- .../J/monads-maybe-monad-1.j | 2 +- .../EasyLang/monte-carlo-methods.easy | 6 +- Task/Morse-code/EasyLang/morse-code.easy | 2 +- .../{morse-code.java => morse-code-1.java} | 0 Task/Morse-code/Java/morse-code-2.java | 99 ++ .../Motzkin-numbers/REXX/motzkin-numbers.rexx | 73 +- .../EasyLang/mouse-position.easy | 5 +- .../Uxntal/mouse-position.uxnatl | 39 +- .../EasyLang/move-to-front-algorithm.easy | 2 +- .../Zig/move-to-front-algorithm.zig | 78 + .../REXX/multi-base-primes.rexx | 110 +- .../multi-dimensional-array-1.basic | 5 + .../multi-dimensional-array-2.basic | 1 + .../multi-dimensional-array-3.basic | 1 + .../multi-dimensional-array-4.basic | 5 + .../multi-dimensional-array-5.basic | 1 + .../multi-dimensional-array-6.basic | 1 + .../multi-dimensional-array-7.basic | 1 + .../multi-dimensional-array-8.basic | 1 + .../multi-dimensional-array-9.basic | 1 + ...rray.cpp => multi-dimensional-array-1.cpp} | 6 +- .../C++/multi-dimensional-array-2.cpp | 80 + .../EasyLang/multiplication-tables.easy | 10 +- .../Objeck/multiplication-tables.objeck | 25 + Task/Multisplit/EasyLang/multisplit.easy | 2 +- .../J/munchausen-numbers-3.j | 7 + .../Munchausen-numbers/R/munchausen-numbers.r | 10 + .../Arturo/munching-squares.arturo | 9 + .../EasyLang/munching-squares.easy | 9 +- .../Uiua/munching-squares.uiua | 1 + Task/Musical-scale/Java/musical-scale.java | 58 +- .../Musical-scale/JavaScript/musical-scale.js | 68 +- Task/N-queens-problem/C/n-queens-problem-1.c | 13 +- .../N-queens-problem/Jq/n-queens-problem-6.jq | 38 + .../N-queens-problem/Jq/n-queens-problem-7.jq | 13 + .../Python/n-queens-problem-10.py | 13 + .../Python/n-queens-problem-5.py | 1 - .../Python/n-queens-problem-6.py | 33 +- .../Python/n-queens-problem-7.py | 16 +- .../Python/n-queens-problem-8.py | 165 +- .../Python/n-queens-problem-9.py | 180 +- .../REXX/n-smooth-numbers.rexx | 96 +- Task/Natural-sorting/00-TASK.txt | 2 +- .../FreeBASIC/natural-sorting.basic | 156 ++ .../JavaScript/natural-sorting-1.js | 7 + ...atural-sorting.js => natural-sorting-2.js} | 0 Task/Natural-sorting/Rust/natural-sorting.rs | 260 +++ Task/Natural-sorting/Zig/natural-sorting.zig | 571 ++++++ .../EasyLang/negative-base-numbers.easy | 10 +- .../next-highest-int-from-digits.easy | 10 +- .../Crystal/non-decimal-radices-convert.cr | 2 + .../REXX/non-decimal-radices-convert.rexx | 52 +- Task/Nonoblock/EasyLang/nonoblock.easy | 10 +- Task/Nonogram-solver/Rust/nonogram-solver.rs | 241 +++ .../Nth-root/AppleScript/nth-root.applescript | 23 + Task/Nth-root/EasyLang/nth-root.easy | 8 +- Task/Nth-root/REXX/nth-root.rexx | 29 +- .../EasyLang/number-reversal-game.easy | 12 +- ...h-are-not-the-sum-of-distinct-squares.easy | 2 +- .../numbers-with-equal-rises-and-falls.easy | 14 +- ...tegration-gauss-legendre-quadrature-2.rexx | 138 +- ...tegration-gauss-legendre-quadrature-3.rexx | 51 - ...egration.jl => numerical-integration-1.jl} | 0 .../Julia/numerical-integration-2.jl | 24 + .../REXX/numerical-integration.rexx | 152 +- .../EasyLang/odd-word-problem.easy | 10 +- .../R/old-russian-measure-of-length.r | 28 + .../one-dimensional-cellular-automata.easy | 4 +- .../EasyLang/openwebnet-password.easy | 10 +- .../Rust/openwebnet-password.rs | 113 ++ .../Crystal/order-by-pair-comparisons.cr | 17 + .../EasyLang/order-by-pair-comparisons.easy | 2 +- .../Crystal/order-two-numerical-lists.cr | 2 + .../EasyLang/ormiston-triples.easy | 16 +- Task/P-Adic-numbers-basic/00-TASK.txt | 1 - .../C-sharp/p-adic-numbers-basic.cs | 402 +++++ .../JavaScript/p-adic-numbers-basic.js | 310 ++++ .../Rust/p-adic-numbers-basic.rs | 391 +++++ .../Zig/p-adic-numbers-basic.zig | 357 ++++ .../Go/p-adic-square-roots.go | 388 +++++ .../JavaScript/p-adic-square-roots.js | 360 ++++ .../Rust/p-adic-square-roots.rs | 381 ++++ .../Zig/p-adic-square-roots.zig | 495 ++++++ .../padovan-n-step-number-sequences.easy | 10 +- .../PascalABC.NET/pancake-numbers.pas | 37 + .../PascalABC.NET/pangram-checker.pas | 8 + .../Pangram-checker/Uiua/pangram-checker.uiua | 8 + Task/Paraffins/PascalABC.NET/paraffins.pas | 50 + .../PascalABC.NET/parallel-calculations.pas | 24 + Task/Parametric-polymorphism/00-TASK.txt | 2 +- .../C3/parametric-polymorphism-1.c3 | 2 +- .../C3/parametric-polymorphism-2.c3 | 2 +- .../Erlang/parse-an-ip-address.erl | 53 + .../Lua/parse-an-ip-address-1.lua | 158 ++ .../Lua/parse-an-ip-address-2.lua | 6 + .../parsing-rpn-calculator-algorithm.pas | 15 + .../Zig/parsing-rpn-calculator-algorithm.zig | 57 + .../Zig/parsing-shunting-yard-algorithm.zig | 343 ++++ .../EasyLang/particle-fountain.easy | 18 +- ...partition-an-integer-x-into-n-primes.basic | 33 + .../partition-an-integer-x-into-n-primes.easy | 20 +- .../partition-an-integer-x-into-n-primes.pas | 22 + .../partition-an-integer-x-into-n-primes.rexx | 131 +- .../partition-an-integer-x-into-n-primes.raku | 17 +- .../pascal-matrix-generation.pas | 16 + .../PascalABC.NET/pascals-triangle-puzzle.pas | 20 + .../EasyLang/pascals-triangle.easy | 8 +- .../pathological-floating-point-problems.easy | 10 +- .../pathological-floating-point-problems-1.hs | 11 + .../pathological-floating-point-problems-2.hs | 16 + .../pathological-floating-point-problems-3.hs | 30 + .../pathological-floating-point-problems.pas | 45 + Task/Peano-curve/EasyLang/peano-curve.easy | 11 +- .../PascalABC.NET/pells-equation.pas | 31 + Task/Penneys-game/Dart/penneys-game.dart | 89 + Task/Pentagram/EasyLang/pentagram.easy | 21 +- .../percolation-mean-run-density.easy | 6 +- .../REXX/perfect-numbers-1.rexx | 46 +- .../REXX/perfect-numbers-2.rexx | 25 +- .../REXX/perfect-numbers-3.rexx | 36 +- .../REXX/perfect-numbers-4.rexx | 35 +- .../REXX/perfect-numbers-5.rexx | 39 +- .../REXX/perfect-numbers-6.rexx | 40 +- .../REXX/perfect-numbers-7.rexx | 66 +- .../REXX/perfect-numbers-8.rexx | 47 + .../EasyLang/perfect-shuffle.easy | 8 +- .../PascalABC.NET/perfect-shuffle.pas | 19 + .../PascalABC.NET/perfect-totient-numbers.pas | 23 + .../EasyLang/periodic-table.easy | 10 +- .../EasyLang/peripheral-drift-illusion.easy | 19 +- Task/Perlin-noise/EasyLang/perlin-noise.easy | 12 +- Task/Perlin-noise/JavaScript/perlin-noise.js | 80 + .../ALGOL-68/permutation-test.alg | 36 + .../EasyLang/permutation-test.easy | 17 + .../permutation-test-2.m2000 | 22 +- .../PascalABC.NET/permutation-test.pas | 20 + .../EasyLang/permutations-derangements.easy | 16 +- .../permutations-rank-of-a-permutation.easy | 14 +- .../EasyLang/permutations-by-swapping.easy | 2 +- Task/Permutations/C/permutations-1.c | 109 +- Task/Permutations/C/permutations-2.c | 84 +- Task/Permutations/C/permutations-4.c | 100 -- Task/Permutations/EasyLang/permutations.easy | 2 +- Task/Permutations/K/permutations-4.k | 2 +- .../REXX/pernicious-numbers.rexx | 71 +- .../Crystal/phrase-reversals.cr | 5 + Task/Pi/Atari-BASIC/pi.basic | 51 + .../Zig/pick-random-element.zig | 16 +- .../REXX/pierpont-primes-1.rexx | 76 + .../REXX/pierpont-primes-2.rexx | 72 + .../Pierpont-primes/REXX/pierpont-primes.rexx | 36 - .../EasyLang/pig-the-dice-game.easy | 95 +- .../EasyLang/pinstripe-display.easy | 5 +- .../Pisano-period/EasyLang/pisano-period.easy | 58 +- Task/Pisano-period/REXX/pisano-period.rexx | 103 +- .../Plasma-effect/EasyLang/plasma-effect.easy | 8 +- .../JavaScript/playfair-cipher.js | 269 +++ Task/Playfair-cipher/Rust/playfair-cipher.rs | 225 +++ .../Playing-cards/EasyLang/playing-cards.easy | 14 +- .../EasyLang/plot-coordinate-pairs.easy | 38 +- .../REXX/polynomial-long-division-2.rexx | 5 +- .../EasyLang/polynomial-regression.easy | 4 +- .../Rust/polynomial-regression.rs | 41 + .../XPL0/polynomial-regression.xpl0 | 60 + Task/Polyspiral/EasyLang/polyspiral.easy | 21 +- .../EasyLang/population-count.easy | 4 +- Task/Power-set/Crystal/power-set.cr | 14 + .../M2000-Interpreter/power-set.m2000 | 72 + Task/Power-set/Refal/power-set.refal | 15 + .../REXX/primality-by-wilsons-theorem.rexx | 123 +- .../Odin/primality-by-trial-division.odin | 29 + .../primality-by-trial-division.pas | 2 +- .../REXX/primality-by-trial-division-1.rexx | 21 - .../REXX/primality-by-trial-division-2.rexx | 22 - .../REXX/primality-by-trial-division-3.rexx | 49 - .../REXX/primality-by-trial-division.rexx | 90 + ...onspiracy.rexx => prime-conspiracy-1.rexx} | 0 .../REXX/prime-conspiracy-2.rexx | 67 + .../REXX/prime-decomposition-1.rexx | 82 - .../REXX/prime-decomposition-2.rexx | 81 - .../REXX/prime-decomposition-3.rexx | 69 - .../REXX/prime-decomposition-4.rexx | 103 -- .../REXX/prime-decomposition.rexx | 41 + ...ose-neighboring-pairs-are-tetraprimes.easy | 64 + ...e-neighboring-pairs-are-tetraprimes.parigp | 35 + ...whose-neighboring-pairs-are-tetraprimes.py | 195 +++ .../00-TASK.txt | 4 + ...llocate-descendants-to-their-ancestors.alg | 108 ++ ...locate-descendants-to-their-ancestors.easy | 67 + ...locate-descendants-to-their-ancestors.rexx | 126 ++ .../REXX/primorial-numbers.rexx | 31 +- .../EasyLang/probabilistic-choice.easy | 2 +- .../EasyLang/problem-of-apollonius.easy | 29 +- Task/Program-name/Zig/program-name.zig | 13 +- .../OPL/program-termination.opl | 3 + .../ALGOL-60/proper-divisors.alg | 77 + .../REXX/proper-divisors-2.rexx | 102 +- .../REXX/proper-divisors-3.rexx | 46 - .../REXX/proper-divisors-4.rexx | 53 - ...s-combined-recursive-generator-mrg32k3a.rs | 89 + ...udo-random-numbers-middle-square-method.rs | 54 + .../Rust/pseudo-random-numbers-splitmix64.rs | 57 + .../ALGOL-68/pythagoras-tree.alg | 95 + .../EasyLang/pythagoras-tree.easy | 8 +- .../Maple/pythagoras-tree.maple | 23 + .../EasyLang/pythagorean-triples.easy | 2 +- .../QR-decomposition/Rust/qr-decomposition.rs | 591 +++++++ .../Quaternion-type/REXX/quaternion-type.rexx | 83 +- .../EasyLang/queue-definition.easy | 2 +- .../EasyLang/quickselect-algorithm.easy | 7 +- .../Zig/quickselect-algorithm.zig | 69 + Task/Quine/Rust/quine-1.rs | 6 +- Task/Quine/Rust/quine-2.rs | 61 +- Task/Quine/Rust/quine-3.rs | 49 +- Task/Quine/Rust/quine-4.rs | 61 +- Task/Quine/Rust/quine-5.rs | 42 + Task/Quine/V-(Vlang)/quine.v | 3 + Task/Quine/Zig/quine.zig | 6 + .../EasyLang/radical-of-an-integer.easy | 14 +- .../REXX/radical-of-an-integer-2.rexx | 29 +- .../SETL/radical-of-an-integer.setl | 43 + .../EasyLang/ramanujan-primes-twins.easy | 2 +- .../REXX/ramanujan-primes-twins.rexx | 43 + .../REXX/ramanujans-constant.rexx | 66 +- ...r-douglas-peucker-line-simplification.easy | 4 +- ...er-douglas-peucker-line-simplification.lua | 92 + ...r-douglas-peucker-line-simplification.mod2 | 100 ++ .../EasyLang/random-latin-squares.easy | 26 +- .../C/random-number-generator-device--5.c | 82 - .../random-number-generator-device--1.rexx | 5 - .../random-number-generator-device--2.rexx | 14 - .../REXX/random-number-generator-device-.rexx | 38 + .../random-number-generator-included--3.rexx | 2 + .../EasyLang/random-numbers.easy | 2 +- Task/Random-numbers/REXX/random-numbers.rexx | 130 +- .../ALGOL-68/random-sentence-from-book-1.alg | 7 +- .../EasyLang/range-consolidation.easy | 14 +- Task/Rare-numbers/Rust/rare-numbers.rs | 37 +- Task/Rate-counter/EasyLang/rate-counter.easy | 26 +- .../XPL0/read-a-configuration-file.xpl0 | 56 + .../OoRexx/read-entire-file-1.rexx | 11 +- .../OoRexx/read-entire-file-2.rexx | 6 +- .../OoRexx/read-entire-file-3.rexx | 16 +- .../OoRexx/read-entire-file-4.rexx | 9 + .../REXX/real-constants-and-functions-3.rexx | 28 +- .../REXX/real-constants-and-functions-4.rexx | 22 +- .../REXX/real-constants-and-functions-5.rexx | 27 - .../REXX/real-constants-and-functions-6.rexx | 26 - .../REXX/real-constants-and-functions-7.rexx | 14 - .../REXX/real-constants-and-functions-8.rexx | 27 - .../REXX/real-constants-and-functions-9.rexx | 19 - .../EasyLang/reduced-row-echelon-form.easy | 18 +- .../C-sharp/reflection-get-source.cs | 1 + Task/Rendezvous/Rust/rendezvous.rs | 207 +++ .../Excel/repeat-a-string.excel | 1 + Task/Resistor-mesh/Rust/resistor-mesh.rs | 133 ++ .../EasyLang/return-multiple-values.easy | 2 +- ...-a-string.lisp => reverse-a-string-1.lisp} | 0 .../Common-Lisp/reverse-a-string-2.lisp | 15 + .../Excel/reverse-a-string.excel | 1 + .../Objeck/roman-numerals-decode.objeck | 38 + .../EasyLang/roots-of-a-function.easy | 21 +- .../EasyLang/roots-of-unity.easy | 6 +- ...setta-code-find-unimplemented-tasks.objeck | 109 ++ .../rosetta-code-fix-code-tags.basic | 66 + ...ta-code-rank-languages-by-popularity.basic | 88 + ...tta-code-rank-languages-by-popularity-2.py | 8 +- Task/Rot-13/PL-I-80/rot-13.pli | 43 +- .../8080-Assembly/run-length-encoding.8080 | 92 + .../Crystal/run-length-encoding.cr | 19 + .../MACRO-11/run-length-encoding.macro11 | 106 ++ .../Miranda/run-length-encoding.miranda | 18 + .../Refal/run-length-encoding.refal | 44 + Task/Runge-Kutta-method/00-TASK.txt | 10 +- .../EasyLang/runge-kutta-method.easy | 2 +- .../Odin/runge-kutta-method.odin | 37 + .../Ol/runge-kutta-method.ol | 57 + .../Scheme/runge-kutta-method.scm | 54 + .../EasyLang/ruth-aaron-numbers.easy | 2 +- Task/SHA-1/JavaScript/sha-1.js | 164 ++ Task/SHA-1/Zig/sha-1.zig | 126 ++ .../FreeBASIC/sql-based-authentication.basic | 91 + .../safe-primes-and-unsafe-primes.easy | 20 +- .../REXX/safe-primes-and-unsafe-primes.rexx | 120 +- .../EasyLang/self-describing-numbers.easy | 16 +- Task/Self-numbers/EasyLang/self-numbers.easy | 10 +- Task/Semiprime/REXX/semiprime-2.rexx | 69 +- Task/Semiprime/REXX/semiprime-3.rexx | 41 - Task/Semiprime/REXX/semiprime-4.rexx | 57 - Task/Semordnilap/R/semordnilap.r | 17 + .../sequence-of-primes-by-trial-division.alg | 46 + .../sequence-of-primes-by-trial-division.easy | 21 +- .../sequence-of-primes-by-trial-division.pas | 2 +- ...equence-of-primes-by-trial-division-1.rexx | 18 - ...equence-of-primes-by-trial-division-2.rexx | 27 - .../sequence-of-primes-by-trial-division.rexx | 78 + .../REXX/sequence-of-primorial-primes.rexx | 50 + ...smallest-number-with-exactly-n-divisors.cs | 102 ++ Task/Set-puzzle/EasyLang/set-puzzle.easy | 24 +- Task/Set-puzzle/JavaScript/set-puzzle.js | 86 + .../EasyLang/set-right-adjacent-bits.easy | 2 +- ...seven-sided-dice-from-five-sided-dice.easy | 8 +- Task/Sexy-primes/EasyLang/sexy-primes.easy | 6 +- Task/Sexy-primes/REXX/sexy-primes.rexx | 153 +- .../shoelace-formula-for-polygonal-area.easy | 8 +- .../shoelace-formula-for-polygonal-area.rs | 25 + .../EasyLang/show-ascii-table.easy | 2 +- .../EasyLang/sierpinski-arrowhead-curve.easy | 9 +- .../EasyLang/sierpinski-carpet.easy | 11 +- .../EasyLang/sierpinski-pentagon.easy | 10 +- .../EasyLang/sierpinski-square-curve.easy | 11 +- .../sierpinski-triangle-graphical.easy | 5 +- .../Uxntal/sierpinski-triangle.uxnatl | 36 +- .../PascalABC.NET/sieve-of-eratosthenes.pas | 2 +- .../REXX/sieve-of-eratosthenes-1.rexx | 41 +- .../REXX/sieve-of-eratosthenes-2.rexx | 90 +- .../REXX/sieve-of-eratosthenes-3.rexx | 16 - .../REXX/sieve-of-eratosthenes-4.rexx | 29 - .../EasyLang/sieve-of-pritchard.easy | 18 +- .../REXX/sieve-of-pritchard.rexx | 95 + .../M2000-Interpreter/simple-database.m2000 | 2 +- .../EasyLang/simple-turtle-graphics.easy | 17 +- .../simple-turtle-graphics.m2000 | 69 + .../Raku/simple-turtle-graphics.raku | 54 + .../FreeBASIC/simulate-input-keyboard.basic | 40 + .../ALGOL-68/sisyphus-sequence.alg | 14 +- .../EasyLang/sisyphus-sequence.easy | 16 +- .../Mathematica/sisyphus-sequence.math | 33 + Task/Sleep/JavaScript/sleep-1.js | 11 + Task/Sleep/JavaScript/sleep-2.js | 14 + Task/Sleep/JavaScript/sleep-3.js | 8 + Task/Sleep/JavaScript/sleep.js | 9 - Task/Sleep/REXX/sleep-3.rexx | 8 +- .../smarandache-prime-digital-sequence.rexx | 95 +- Task/Snake/EasyLang/snake.easy | 87 +- .../EasyLang/solve-a-hidato-puzzle.easy | 22 +- .../JavaScript/solve-a-hidato-puzzle.js | 113 ++ .../EasyLang/solve-a-holy-knights-tour.easy | 14 +- .../Rust/solve-a-holy-knights-tour.rs | 188 ++ .../Zig/solve-a-holy-knights-tour.zig | 208 +++ .../EasyLang/solve-a-hopido-puzzle.easy | 14 +- .../Rust/solve-a-hopido-puzzle.rs | 258 +++ .../ALGOL-68/solve-a-numbrix-puzzle.alg | 132 ++ .../EasyLang/solve-a-numbrix-puzzle.easy | 76 + .../JavaScript/solve-a-numbrix-puzzle.js | 110 ++ .../Rust/solve-a-numbrix-puzzle.rs | 205 +++ .../Zkl/solve-a-numbrix-puzzle-1.zkl | 20 +- .../Zkl/solve-a-numbrix-puzzle-2.zkl | 17 +- .../solve-the-no-connection-puzzle.alg | 90 + .../solve-the-no-connection-puzzle.easy | 23 + .../APL/sort-a-list-of-object-identifiers.apl | 1 + .../sort-a-list-of-object-identifiers.easy | 22 +- .../sort-an-array-of-composite-structures.cr | 11 + ...ort-an-array-of-composite-structures.m2000 | 2 +- ...rt-an-array-of-composite-structures-2.rexx | 12 +- ...rt-an-array-of-composite-structures-3.rexx | 124 -- ...rt-an-array-of-composite-structures-4.rexx | 173 -- .../EasyLang/sort-an-integer-array.easy | 10 +- .../sort-an-outline-at-every-level.easy | 12 +- .../Crystal/sort-numbers-lexicographically.cr | 2 + .../R/sort-numbers-lexicographically.r | 6 + .../Crystal/sort-three-variables.cr | 14 + .../EasyLang/sort-three-variables.easy | 28 +- .../XPL0/sort-three-variables.xpl0 | 31 + .../Crystal/sorting-algorithms-circle-sort.cr | 35 + .../Rust/sorting-algorithms-bead-sort.rs | 37 + .../EasyLang/sorting-algorithms-bogosort.easy | 17 +- .../Crystal/sorting-algorithms-bubble-sort.cr | 17 + .../sorting-algorithms-bubble-sort.easy | 6 +- .../sorting-algorithms-cocktail-sort.easy | 2 +- .../sorting-algorithms-comb-sort.easy | 2 +- .../sorting-algorithms-counting-sort.easy | 6 +- .../sorting-algorithms-gnome-sort.easy | 2 +- .../EasyLang/sorting-algorithms-heapsort.easy | 10 +- .../REXX/sorting-algorithms-heapsort-1.rexx | 94 +- .../REXX/sorting-algorithms-heapsort-2.rexx | 124 +- .../REXX/sorting-algorithms-heapsort-3.rexx | 56 - .../sorting-algorithms-insertion-sort.easy | 2 +- .../sorting-algorithms-merge-sort.easy | 10 +- .../REXX/sorting-algorithms-merge-sort-3.rexx | 8 +- .../ZED/sorting-algorithms-merge-sort.zed | 90 +- .../sorting-algorithms-pancake-sort.easy | 4 +- .../sorting-algorithms-patience-sort.easy | 29 + .../Rust/sorting-algorithms-patience-sort.rs | 95 + .../Zig/sorting-algorithms-patience-sort.zig | 138 ++ .../sorting-algorithms-permutation-sort.easy | 31 +- .../sorting-algorithms-quicksort.easy | 26 +- .../K/sorting-algorithms-quicksort-8.k | 1 + .../REXX/sorting-algorithms-quicksort-1.rexx | 194 +-- .../REXX/sorting-algorithms-quicksort-2.rexx | 111 +- .../REXX/sorting-algorithms-quicksort-3.rexx | 36 +- .../REXX/sorting-algorithms-quicksort-4.rexx | 68 +- .../REXX/sorting-algorithms-quicksort-5.rexx | 198 ++- .../REXX/sorting-algorithms-quicksort-6.rexx | 73 - .../sorting-algorithms-radix-sort.easy | 12 +- .../sorting-algorithms-radix-sort.js | 60 + ....rs => sorting-algorithms-radix-sort-1.rs} | 6 +- .../Rust/sorting-algorithms-radix-sort-2.rs | 24 + .../Rust/sorting-algorithms-radix-sort-3.rs | 40 + .../sorting-algorithms-selection-sort.easy | 10 +- .../sorting-algorithms-shell-sort.easy | 2 +- .../sorting-algorithms-sleep-sort-1.js | 10 +- .../sorting-algorithms-sleep-sort-2.js | 2 +- .../sorting-algorithms-stooge-sort.easy | 10 +- .../sorting-algorithms-strand-sort.easy | 6 +- .../sorting-algorithms-strand-sort.basic | 100 ++ .../sorting-algorithms-strand-sort.m2000 | 68 + .../Rust/sorting-algorithms-strand-sort.rs | 153 ++ .../Zig/sorting-algorithms-strand-sort.zig | 190 ++ .../JavaScript/spelling-of-ordinal-numbers.js | 163 ++ .../Mathematica/sphenic-numbers.math | 3 + .../EasyLang/spinning-rod-animation-text.easy | 5 +- .../Spiral-matrix/EasyLang/spiral-matrix.easy | 8 +- Task/Spiral-matrix/Uiua/spiral-matrix.uiua | 5 + ...r-string-based-on-change-of-character-1.c} | 0 ...er-string-based-on-change-of-character-2.c | 32 + ...ter-string-based-on-change-of-character.cr | 6 + ...cter-string-based-on-change-of-character.l | 29 + ...-string-based-on-change-of-character.m2000 | 24 + ...r-string-based-on-change-of-character-1.rs | 64 +- ...r-string-based-on-change-of-character-2.rs | 22 +- ...r-string-based-on-change-of-character-3.rs | 14 + ...r-string-based-on-change-of-character-4.rs | 2 + ...r-string-based-on-change-of-character-5.rs | 9 + ...r-string-based-on-change-of-character-6.rs | 9 + ...r-string-based-on-change-of-character-7.rs | 5 + .../Python/square-form-factorization.py | 110 ++ .../REXX/square-form-factorization.rexx | 148 +- .../EasyLang/square-free-integers.easy | 2 +- .../PL-I-80/square-free-integers.pli | 6 +- .../REXX/square-free-integers.rexx | 113 +- .../EasyLang/stable-marriage-problem.easy | 10 +- Task/Stack-traces/Crystal/stack-traces.cr | 15 + Task/Stack-traces/Uxntal/stack-traces.uxnatl | 51 + Task/Stack/68000-Assembly/stack-1.68000 | 5 +- Task/Stack/Ballerina/stack-1.ballerina | 15 + Task/Stack/Ballerina/stack-2.ballerina | 53 + Task/Stack/C/stack-1.c | 56 +- Task/Stack/EasyLang/stack.easy | 6 +- .../EasyLang/stair-climbing-puzzle.easy | 2 +- .../EasyLang/start-from-a-main-routine.easy | 2 +- .../JavaScript/state-name-puzzle.js | 76 + .../Ballerina/statistics-basic.ballerina | 44 + .../EasyLang/statistics-basic.easy | 20 +- .../EasyLang/steffensens-method.easy | 8 +- .../Rust/steffensens-method.rs | 69 + .../EasyLang/stem-and-leaf-plot.easy | 17 +- .../Uiua/stem-and-leaf-plot.uiua | 2 +- .../EasyLang/stern-brocot-sequence.easy | 2 +- Task/Strassens-algorithm/00-TASK.txt | 2 + .../C++/strassens-algorithm.cpp | 248 +++ .../C-sharp/strassens-algorithm.cs | 323 ++++ .../Java/strassens-algorithm.java | 281 +++ .../JavaScript/strassens-algorithm-1.js | 318 ++++ .../JavaScript/strassens-algorithm-2.js | 316 ++++ .../Rust/strassens-algorithm.rs | 269 +++ .../Zig/strassens-algorithm.zig | 477 +++++ Task/Stream-merge/Rust/stream-merge.rs | 81 + .../JavaScript/string-concatenation.js | 2 +- .../Uxntal/string-concatenation.uxnatl | 31 +- Task/String-length/Crystal/string-length-1.cr | 2 +- Task/String-length/Crystal/string-length-2.cr | 2 +- Task/String-length/Crystal/string-length-3.cr | 1 + .../String-length/Uxntal/string-length.uxnatl | 31 + Task/String-prepend/Crystal/string-prepend.cr | 3 + Task/String-prepend/OPL/string-prepend.opl | 7 + ...p-a-set-of-characters-from-a-string-4.java | 13 + ...ip-a-set-of-characters-from-a-string.m2000 | 1 + ...p-a-set-of-characters-from-a-string.objeck | 17 + ...rip-a-set-of-characters-from-a-string.odin | 16 + .../strip-a-set-of-characters-from-a-string.r | 16 + ...rip-a-set-of-characters-from-a-string-1.rs | 6 +- ...rip-a-set-of-characters-from-a-string-2.rs | 11 +- ...rip-a-set-of-characters-from-a-string-3.rs | 5 +- ...rip-a-set-of-characters-from-a-string-4.rs | 13 + .../APL/strip-comments-from-a-string.apl | 1 + .../Emacs-Lisp/strip-comments-from-a-string.l | 5 + .../Refal/strip-comments-from-a-string.refal | 23 + .../SETL/strip-comments-from-a-string.setl | 13 + ...s-and-extended-characters-from-a-string.rs | 2 +- ...hitespace-from-a-string-top-and-tail-1.cpp | 47 + ...itespace-from-a-string-top-and-tail-2.cpp} | 8 +- .../EasyLang/strong-and-weak-primes.easy | 8 +- .../REXX/strong-and-weak-primes.rexx | 103 +- Task/Subleq/EasyLang/subleq.easy | 6 +- .../EasyLang/substitution-cipher.easy | 6 +- .../JavaScript/substitution-cipher.js | 30 + Task/Substring/K/substring.k | 32 + .../EasyLang/subtractive-generator.easy | 6 +- .../successive-prime-differences.easy | 30 +- .../REXX/successive-prime-differences.rexx | 97 +- Task/Sudan-function/Rust/sudan-function.rs | 15 + Task/Sudoku/EasyLang/sudoku.easy | 6 +- ...teger.nu => sum-digits-of-an-integer-1.nu} | 0 .../Nu/sum-digits-of-an-integer-2.nu | 13 + .../ALGOL-60/sum-of-a-series-1.alg | 10 + .../ALGOL-60/sum-of-a-series-2.alg | 24 + .../ALGOL-60/sum-of-a-series.alg | 18 - .../EasyLang/sum-of-a-series.easy | 2 +- .../S-BASIC/sum-of-a-series.basic | 11 + .../TypeScript/sum-of-a-series.ts | 5 + ...lements-below-main-diagonal-of-matrix.easy | 7 +- ...nts-below-main-diagonal-of-matrix.quackery | 10 + Task/Sum-to-100/EasyLang/sum-to-100.easy | 4 +- Task/Superellipse/EasyLang/superellipse.easy | 10 +- .../sutherland-hodgman-polygon-clipping.zig | 151 ++ .../EasyLang/sylvesters-sequence.easy | 2 +- .../Crystal/take-notes-on-the-command-line.cr | 9 + .../{tau-number.rexx => tau-number-1.rexx} | 0 Task/Tau-number/REXX/tau-number-2.rexx | 34 + .../terminal-control-clear-the-screen.x86-64 | 17 + .../EasyLang/test-integerness.easy | 6 +- .../Lua/text-processing-1.lua | 11 +- .../XPL0/text-processing-1.xpl0 | 49 + .../ALGOL-68/text-processing-2.alg | 164 ++ .../FreeBASIC/text-processing-2.basic | 128 ++ .../Lua/text-processing-2.lua | 5 +- .../XPL0/text-processing-2.xpl0 | 42 + .../text-processing-max-licenses-in-use.lua | 21 +- .../The-Name-Game/EasyLang/the-name-game.easy | 2 +- .../EasyLang/the-sieve-of-sundaram.easy | 2 +- .../REXX/the-sieve-of-sundaram.rexx | 93 +- .../Fortran/thieles-interpolation-formula.f | 87 + Task/Thue-Morse/Zig/thue-morse.zig | 16 + Task/Tic-tac-toe/APL/tic-tac-toe-1.apl | 7 + Task/Tic-tac-toe/APL/tic-tac-toe-2.apl | 1 + Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy | 96 +- Task/Tic-tac-toe/Factor/tic-tac-toe-1.factor | 22 + Task/Tic-tac-toe/Factor/tic-tac-toe-2.factor | 27 + Task/Tic-tac-toe/J/tic-tac-toe-1.j | 16 +- Task/Tic-tac-toe/J/tic-tac-toe-2.j | 9 +- Task/Tic-tac-toe/J/tic-tac-toe-3.j | 2 +- Task/Tic-tac-toe/J/tic-tac-toe-4.j | 14 + Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js | 96 ++ Task/Time-a-function/Lua/time-a-function.lua | 20 +- .../REXX/time-a-function-2.rexx | 508 +++++- .../REXX/time-a-function-3.rexx | 27 - .../REXX/time-a-function-4.rexx | 485 ------ ... => tokenize-a-string-with-escaping-1.lua} | 12 +- .../Lua/tokenize-a-string-with-escaping-2.lua | 11 + .../Lua/tokenize-a-string-with-escaping-3.lua | 4 + .../Excel/tokenize-a-string-1.excel | 1 + .../Excel/tokenize-a-string-2.excel | 1 + .../Zig/tokenize-a-string.zig | 2 +- .../JavaScript/tonelli-shanks-algorithm.js | 113 ++ .../Rust/tonelli-shanks-algorithm.rs | 120 ++ .../Zig/tonelli-shanks-algorithm.zig | 128 ++ .../EasyLang/top-rank-per-group.easy | 4 +- .../EasyLang/total-circles-area.easy | 2 +- .../EasyLang/totient-function.easy | 2 +- .../REXX/totient-function-1.rexx | 24 - .../REXX/totient-function-2.rexx | 25 - .../REXX/totient-function-3.rexx | 137 -- .../REXX/totient-function.rexx | 99 ++ .../Applesoft-BASIC/towers-of-hanoi.basic | 27 + .../Ballerina/towers-of-hanoi.ballerina | 26 + .../EasyLang/towers-of-hanoi.easy | 4 +- .../Excel/towers-of-hanoi-3.excel | 11 + .../Uxntal/towers-of-hanoi.uxnatl | 30 +- .../EasyLang/tree-traversal.easy | 28 +- .../EasyLang/trigonometric-functions.easy | 2 +- .../REXX/trigonometric-functions-1.rexx | 81 - ...ns-2.rexx => trigonometric-functions.rexx} | 4 +- .../Ballerina/truncatable-primes.ballerina | 90 + ...-primes.rexx => truncatable-primes-1.rexx} | 0 .../REXX/truncatable-primes-2.rexx | 50 + Task/Twin-primes/REXX/twin-primes-1.rexx | 26 - Task/Twin-primes/REXX/twin-primes-2.rexx | 33 - Task/Twin-primes/REXX/twin-primes.rexx | 33 + .../EasyLang/two-bullet-roulette.easy | 30 +- .../Quackery/two-bullet-roulette.quackery | 35 + Task/UPC/EasyLang/upc.easy | 4 +- .../K/utf-8-encode-and-decode.k | 4 + ...ukkonen-s-suffix-tree-construction-1.basic | 151 ++ ...ukkonen-s-suffix-tree-construction-2.basic | 295 ++++ .../ukkonen-s-suffix-tree-construction.js | 196 +++ .../ukkonen-s-suffix-tree-construction.rs | 250 +++ .../EasyLang/ulam-spiral-for-primes-.easy | 42 +- .../REXX/ulam-spiral-for-primes--1.rexx | 48 - .../REXX/ulam-spiral-for-primes--2.rexx | 48 - .../REXX/ulam-spiral-for-primes-.rexx | 98 ++ Task/Unicode-strings/Tcl/unicode-strings.tcl | 52 + .../unicode-variable-names.ballerina | 7 + .../Odin/unicode-variable-names.odin | 11 + .../Scheme/unicode-variable-names.scm | 4 + .../EasyLang/universal-turing-machine.easy | 24 +- .../EasyLang/unprimeable-numbers.easy | 36 + .../REXX/unprimeable-numbers.rexx | 158 +- .../REXX/untouchable-numbers.rexx | 149 +- .../Lua/update-a-configuration-file.lua | 71 + .../JavaScript/user-input-text-3.js | 16 + Task/User-input-Text/Lua/user-input-text.lua | 2 +- Task/User-input-Text/OPL/user-input-text.opl | 30 + ...ional-securities-identification-number.lua | 31 +- .../EasyLang/vampire-number.easy | 12 +- Task/Vampire-number/Raku/vampire-number.raku | 17 +- Task/Variables/EasyLang/variables.easy | 2 +- .../Vector-products/REXX/vector-products.rexx | 54 +- Task/Vector/REXX/vector.rexx | 72 +- .../JavaScript/verhoeff-algorithm.js | 80 + .../Rust/verhoeff-algorithm.rs | 98 ++ ...tribution-uniformity-chi-squared-test.rexx | 138 +- .../verify-distribution-uniformity-naive.easy | 8 +- .../verify-distribution-uniformity-naive.rexx | 108 +- .../vigen-re-cipher-cryptanalysis.js | 190 ++ .../EasyLang/vogels-approximation-method.easy | 2 +- .../Fortran/vogels-approximation-method.f | 96 ++ .../JavaScript/vogels-approximation-method.js | 290 ++++ .../EasyLang/voronoi-diagram.easy | 10 +- .../EasyLang/wagstaff-primes.easy | 8 +- .../Mathematica/wagstaff-primes.math | 40 + ...asteful-equidigital-and-frugal-numbers.alg | 64 + ...steful-equidigital-and-frugal-numbers.easy | 56 + ...wasteful-equidigital-and-frugal-numbers.py | 272 +++ .../Weird-numbers/EasyLang/weird-numbers.easy | 26 +- .../Weird-numbers/YAMLScript/weird-numbers.ys | 2 +- ...ch-primes.rexx => wieferich-primes-1.rexx} | 0 .../REXX/wieferich-primes-2.rexx | 40 + .../REXX/wilson-primes-of-order-n-1.rexx | 58 + .../REXX/wilson-primes-of-order-n-2.rexx | 61 + .../REXX/wilson-primes-of-order-n.rexx | 47 - Task/Wireworld/EasyLang/wireworld.easy | 43 +- .../Emacs-Lisp/word-frequency.l | 28 + Task/Word-frequency/Nu/word-frequency.nu | 8 + Task/Word-frequency/Perl/word-frequency.pl | 2 +- Task/Word-ladder/EasyLang/word-ladder.easy | 2 +- Task/Word-ladder/FreeBASIC/word-ladder.basic | 147 ++ Task/Wordiff/JavaScript/wordiff.js | 200 +++ .../Odin/write-entire-file.odin | 11 + .../write-float-arrays-to-a-text-file.alg | 73 +- ...te-float-arrays-to-a-text-file.applescript | 60 + .../K/write-float-arrays-to-a-text-file.k | 16 + .../Rust/xiaolin-wus-line-algorithm.rs | 120 ++ Task/Y-combinator/Elm/y-combinator.elm | 69 +- Task/Y-combinator/F-Sharp/y-combinator-1.fs | 12 +- Task/Y-combinator/F-Sharp/y-combinator-2.fs | 42 +- Task/Y-combinator/F-Sharp/y-combinator-3.fs | 43 +- Task/Y-combinator/F-Sharp/y-combinator-4.fs | 42 +- Task/Y-combinator/F-Sharp/y-combinator-5.fs | 4 + Task/Y-combinator/J/y-combinator-1.j | 2 +- Task/Y-combinator/J/y-combinator-3.j | 4 +- Task/Y-combinator/J/y-combinator-6.j | 4 +- Task/Y-combinator/Zig/y-combinator.zig | 71 + .../EasyLang/yellowstone-sequence.easy | 16 +- .../REXX/yellowstone-sequence-1.rexx | 20 - .../REXX/yellowstone-sequence-2.rexx | 21 - .../REXX/yellowstone-sequence.rexx | 56 + Task/Yin-and-yang/EasyLang/yin-and-yang.easy | 29 +- Task/Zebra-puzzle/J/zebra-puzzle-1.j | 30 +- Task/Zebra-puzzle/JavaScript/zebra-puzzle.js | 163 ++ .../zeckendorf-number-representation.easy | 6 +- .../EasyLang/zig-zag-matrix.easy | 2 +- Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua | 7 + .../EasyLang/zumkeller-numbers.easy | 30 +- 2347 files changed, 62432 insertions(+), 16731 deletions(-) create mode 120000 Lang/8080-Assembly/Loops-Infinite create mode 120000 Lang/8080-Assembly/Run-length-encoding create mode 120000 Lang/ALGOL-60/Additive-primes create mode 120000 Lang/ALGOL-60/Largest-proper-divisor-of-n create mode 120000 Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/ALGOL-60/Proper-divisors create mode 120000 Lang/ALGOL-60/Sequence-of-primes-by-trial-division create mode 120000 Lang/ALGOL-68/Elliptic-curve-arithmetic create mode 120000 Lang/ALGOL-68/Permutation-test create mode 120000 Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors create mode 120000 Lang/ALGOL-68/Pythagoras-tree create mode 120000 Lang/ALGOL-68/Solve-a-Numbrix-puzzle create mode 120000 Lang/ALGOL-68/Solve-the-no-connection-puzzle create mode 120000 Lang/ALGOL-68/Text-processing-2 create mode 120000 Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers create mode 120000 Lang/ALGOL-M/Additive-primes create mode 120000 Lang/ANSI-BASIC/Levenshtein-distance create mode 120000 Lang/ANSI-BASIC/M-bius-function create mode 120000 Lang/ANSI-BASIC/Magic-constant create mode 120000 Lang/ANSI-BASIC/Map-range create mode 120000 Lang/APL/Loops-Infinite create mode 120000 Lang/APL/Sort-a-list-of-object-identifiers create mode 120000 Lang/APL/Strip-comments-from-a-string create mode 120000 Lang/APL/Tic-tac-toe create mode 120000 Lang/ASIC/M-bius-function create mode 120000 Lang/Ada/Cistercian-numerals create mode 120000 Lang/Ada/Curzon-numbers create mode 120000 Lang/AppleScript/Bin-given-limits create mode 120000 Lang/AppleScript/Nth-root create mode 120000 Lang/AppleScript/Write-float-arrays-to-a-text-file create mode 120000 Lang/Applesoft-BASIC/Cistercian-numerals create mode 120000 Lang/Applesoft-BASIC/Formatted-numeric-output create mode 120000 Lang/Applesoft-BASIC/Levenshtein-distance create mode 120000 Lang/Applesoft-BASIC/Multi-dimensional-array create mode 120000 Lang/Applesoft-BASIC/Towers-of-Hanoi create mode 120000 Lang/Arturo/Arithmetic-derivative create mode 120000 Lang/Arturo/Dice-game-probabilities create mode 120000 Lang/Arturo/Element-wise-operations create mode 120000 Lang/Arturo/Entropy-Narcissist create mode 120000 Lang/Arturo/Munching-squares create mode 120000 Lang/Asymptote/Evaluate-binomial-coefficients create mode 120000 Lang/Atari-BASIC/Pi create mode 100644 Lang/AutoHotKey-V2/00-LANG.txt create mode 100644 Lang/AutoHotKey-V2/00-META.yaml create mode 120000 Lang/AutoHotKey-V2/Hello-world-Graphical delete mode 100644 Lang/Autohotkey-V2/00-LANG.txt delete mode 100644 Lang/Autohotkey-V2/00-META.yaml delete mode 120000 Lang/Autohotkey-V2/Hello-world-Graphical create mode 120000 Lang/BASIC/Partition-an-integer-x-into-n-primes create mode 120000 Lang/BASIC256/Evaluate-binomial-coefficients create mode 120000 Lang/BQN/Find-common-directory-path create mode 120000 Lang/BQN/Globally-replace-text-in-several-files create mode 120000 Lang/Ballerina/A+B create mode 120000 Lang/Ballerina/ABC-problem create mode 120000 Lang/Ballerina/AKS-test-for-primes create mode 120000 Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications create mode 120000 Lang/Ballerina/Abundant-odd-numbers create mode 120000 Lang/Ballerina/Accumulator-factory create mode 120000 Lang/Ballerina/Achilles-numbers create mode 120000 Lang/Ballerina/Ackermann-function create mode 120000 Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime create mode 120000 Lang/Ballerina/Additive-primes create mode 120000 Lang/Ballerina/Address-of-a-variable create mode 120000 Lang/Ballerina/Almost-prime create mode 120000 Lang/Ballerina/Amb create mode 120000 Lang/Ballerina/Angle-difference-between-two-bearings create mode 120000 Lang/Ballerina/Anti-primes create mode 120000 Lang/Ballerina/Apply-a-callback-to-an-array create mode 120000 Lang/Ballerina/Approximate-equality create mode 120000 Lang/Ballerina/Arithmetic-Complex create mode 120000 Lang/Ballerina/Arithmetic-Integer create mode 120000 Lang/Ballerina/Arithmetic-Rational create mode 120000 Lang/Ballerina/Arithmetic-numbers create mode 120000 Lang/Ballerina/Array-concatenation create mode 120000 Lang/Ballerina/Array-length create mode 120000 Lang/Ballerina/Arrays create mode 120000 Lang/Ballerina/Ascending-primes create mode 120000 Lang/Ballerina/Associative-array-Creation create mode 120000 Lang/Ballerina/Associative-array-Iteration create mode 120000 Lang/Ballerina/Associative-array-Merging create mode 120000 Lang/Ballerina/Averages-Arithmetic-mean create mode 120000 Lang/Ballerina/Averages-Mean-angle create mode 120000 Lang/Ballerina/Averages-Mean-time-of-day create mode 120000 Lang/Ballerina/Averages-Median create mode 120000 Lang/Ballerina/Averages-Mode create mode 120000 Lang/Ballerina/Averages-Pythagorean-means create mode 120000 Lang/Ballerina/Averages-Root-mean-square create mode 120000 Lang/Ballerina/Averages-Simple-moving-average create mode 120000 Lang/Ballerina/Balanced-brackets create mode 120000 Lang/Ballerina/Boolean-values create mode 120000 Lang/Ballerina/Caesar-cipher create mode 120000 Lang/Ballerina/Calculating-the-value-of-e create mode 120000 Lang/Ballerina/Case-sensitivity-of-identifiers create mode 120000 Lang/Ballerina/Character-codes create mode 120000 Lang/Ballerina/Classes create mode 120000 Lang/Ballerina/Count-in-octal create mode 120000 Lang/Ballerina/Currency create mode 120000 Lang/Ballerina/Currying create mode 120000 Lang/Ballerina/Dynamic-variable-names create mode 120000 Lang/Ballerina/Empty-string create mode 120000 Lang/Ballerina/Extreme-floating-point-values create mode 120000 Lang/Ballerina/Farey-sequence create mode 120000 Lang/Ballerina/Find-limit-of-recursion create mode 120000 Lang/Ballerina/Fivenum create mode 120000 Lang/Ballerina/Floyds-triangle create mode 120000 Lang/Ballerina/Four-bit-adder create mode 120000 Lang/Ballerina/Function-definition create mode 120000 Lang/Ballerina/Gapful-numbers create mode 120000 Lang/Ballerina/Greatest-subsequential-sum create mode 120000 Lang/Ballerina/Hailstone-sequence create mode 120000 Lang/Ballerina/Hello-world-Newline-omission create mode 120000 Lang/Ballerina/Hello-world-Standard-error create mode 120000 Lang/Ballerina/Levenshtein-distance create mode 120000 Lang/Ballerina/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Ballerina/Loops-Break create mode 120000 Lang/Ballerina/Loops-Continue create mode 120000 Lang/Ballerina/Loops-Do-while create mode 120000 Lang/Ballerina/Loops-Downward-for create mode 120000 Lang/Ballerina/Loops-For create mode 120000 Lang/Ballerina/Loops-For-with-a-specified-step create mode 120000 Lang/Ballerina/Loops-Foreach create mode 120000 Lang/Ballerina/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/Ballerina/Loops-Infinite create mode 120000 Lang/Ballerina/Loops-N-plus-one-half create mode 120000 Lang/Ballerina/Loops-Nested create mode 120000 Lang/Ballerina/Loops-With-multiple-ranges create mode 120000 Lang/Ballerina/Loops-Wrong-ranges create mode 120000 Lang/Ballerina/Stack create mode 120000 Lang/Ballerina/Statistics-Basic create mode 120000 Lang/Ballerina/Towers-of-Hanoi create mode 120000 Lang/Ballerina/Truncatable-primes create mode 120000 Lang/Ballerina/Unicode-variable-names create mode 120000 Lang/C++/Currency create mode 120000 Lang/C++/Strassens-algorithm create mode 120000 Lang/C-sharp/ADFGVX-cipher create mode 120000 Lang/C-sharp/ASCII-art-diagram-converter create mode 120000 Lang/C-sharp/Arithmetic-derivative create mode 120000 Lang/C-sharp/Boyer-Moore-string-search create mode 120000 Lang/C-sharp/Calkin-Wilf-sequence create mode 120000 Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm create mode 120000 Lang/C-sharp/Execute-a-Markov-algorithm create mode 120000 Lang/C-sharp/Extensible-prime-generator create mode 120000 Lang/C-sharp/File-extension-is-in-extensions-list create mode 120000 Lang/C-sharp/Find-if-a-point-is-within-a-triangle create mode 120000 Lang/C-sharp/Gotchas create mode 120000 Lang/C-sharp/Index-finite-lists-of-positive-integers create mode 120000 Lang/C-sharp/K-d-tree create mode 120000 Lang/C-sharp/Longest-string-challenge create mode 120000 Lang/C-sharp/P-Adic-numbers-basic create mode 120000 Lang/C-sharp/Reflection-Get-source create mode 120000 Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors create mode 120000 Lang/C-sharp/Strassens-algorithm create mode 120000 Lang/C/Color-wheel create mode 120000 Lang/C/Magic-constant create mode 120000 Lang/C3/Binary-digits create mode 120000 Lang/Chipmunk-Basic/Evaluate-binomial-coefficients create mode 120000 Lang/Crystal/Abbreviations-easy create mode 120000 Lang/Crystal/Anagrams-Deranged-anagrams create mode 120000 Lang/Crystal/Arithmetic-Complex create mode 120000 Lang/Crystal/Arithmetic-geometric-mean create mode 120000 Lang/Crystal/Averages-Mode create mode 120000 Lang/Crystal/Averages-Pythagorean-means create mode 120000 Lang/Crystal/Bin-given-limits create mode 120000 Lang/Crystal/Character-codes create mode 120000 Lang/Crystal/Cistercian-numerals create mode 120000 Lang/Crystal/Closures-Value-capture create mode 120000 Lang/Crystal/Comma-quibbling create mode 120000 Lang/Crystal/Convert-seconds-to-compound-duration create mode 120000 Lang/Crystal/Determine-if-a-string-has-all-the-same-characters create mode 120000 Lang/Crystal/Determine-if-a-string-is-collapsible create mode 120000 Lang/Crystal/Dijkstras-algorithm create mode 120000 Lang/Crystal/Dutch-national-flag-problem create mode 120000 Lang/Crystal/Execute-Brain- create mode 120000 Lang/Crystal/Hello-world-Standard-error create mode 120000 Lang/Crystal/Hex-words create mode 120000 Lang/Crystal/Increment-a-numerical-string create mode 120000 Lang/Crystal/Interactive-programming-repl- create mode 120000 Lang/Crystal/Loops-N-plus-one-half create mode 120000 Lang/Crystal/Magic-8-ball create mode 120000 Lang/Crystal/Non-decimal-radices-Convert create mode 120000 Lang/Crystal/Order-by-pair-comparisons create mode 120000 Lang/Crystal/Order-two-numerical-lists create mode 120000 Lang/Crystal/Phrase-reversals create mode 120000 Lang/Crystal/Power-set create mode 120000 Lang/Crystal/Run-length-encoding create mode 120000 Lang/Crystal/Sort-an-array-of-composite-structures create mode 120000 Lang/Crystal/Sort-numbers-lexicographically create mode 120000 Lang/Crystal/Sort-three-variables create mode 120000 Lang/Crystal/Sorting-Algorithms-Circle-Sort create mode 120000 Lang/Crystal/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Crystal/Split-a-character-string-based-on-change-of-character create mode 120000 Lang/Crystal/Stack-traces create mode 120000 Lang/Crystal/String-prepend create mode 120000 Lang/Crystal/Take-notes-on-the-command-line create mode 120000 Lang/D/Find-Chess960-starting-position-identifier create mode 120000 Lang/Dart/24-game-Solve create mode 120000 Lang/Dart/K-d-tree create mode 120000 Lang/Dart/Penneys-game create mode 120000 Lang/Delphi/Generate-Chess960-starting-position create mode 120000 Lang/ERRE/Leonardo-numbers create mode 120000 Lang/EasyLang/2048 create mode 120000 Lang/EasyLang/Abbreviations-automatic create mode 120000 Lang/EasyLang/Abbreviations-easy create mode 120000 Lang/EasyLang/Abbreviations-simple create mode 120000 Lang/EasyLang/Amb create mode 120000 Lang/EasyLang/Anagrams create mode 120000 Lang/EasyLang/Anagrams-Deranged-anagrams create mode 120000 Lang/EasyLang/Babylonian-spiral create mode 120000 Lang/EasyLang/Boyer-Moore-string-search create mode 120000 Lang/EasyLang/Element-wise-operations create mode 120000 Lang/EasyLang/Factorions create mode 120000 Lang/EasyLang/Mad-Libs create mode 120000 Lang/EasyLang/Permutation-test create mode 120000 Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes create mode 120000 Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors create mode 120000 Lang/EasyLang/Solve-a-Numbrix-puzzle create mode 120000 Lang/EasyLang/Solve-the-no-connection-puzzle create mode 120000 Lang/EasyLang/Sorting-algorithms-Patience-sort create mode 120000 Lang/EasyLang/Unprimeable-numbers create mode 120000 Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers create mode 120000 Lang/Elena/Comma-quibbling create mode 120000 Lang/Elena/Concurrent-computing create mode 120000 Lang/Elena/HTTP create mode 120000 Lang/Elena/HTTPS create mode 120000 Lang/Emacs-Lisp/Color-wheel create mode 120000 Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer create mode 120000 Lang/Emacs-Lisp/Keyboard-input-Keypress-check create mode 120000 Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response create mode 120000 Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character create mode 120000 Lang/Emacs-Lisp/Strip-comments-from-a-string create mode 120000 Lang/Emacs-Lisp/Word-frequency create mode 120000 Lang/Erlang/Parse-an-IP-Address create mode 120000 Lang/Excel/Arrays create mode 120000 Lang/Excel/Conditional-structures create mode 120000 Lang/Excel/FizzBuzz create mode 120000 Lang/Excel/Function-definition create mode 120000 Lang/Excel/Loops-For create mode 120000 Lang/Excel/Repeat-a-string create mode 120000 Lang/Excel/Reverse-a-string create mode 120000 Lang/Excel/Tokenize-a-string create mode 120000 Lang/F-Sharp/Mad-Libs create mode 120000 Lang/Factor/Tic-tac-toe create mode 120000 Lang/Forth/Almost-prime create mode 120000 Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- create mode 120000 Lang/Fortran/B-zier-curves-Intersections create mode 120000 Lang/Fortran/Eulers-constant-0.5772... create mode 120000 Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits create mode 120000 Lang/Fortran/Harmonic-series create mode 120000 Lang/Fortran/Knuths-algorithm-S create mode 120000 Lang/Fortran/Thieles-interpolation-formula create mode 120000 Lang/Fortran/Vogels-approximation-method create mode 120000 Lang/Free-Pascal-Lazarus/DNS-query create mode 120000 Lang/Free-Pascal-Lazarus/Levenshtein-distance create mode 120000 Lang/Free-Pascal-Lazarus/Map-range create mode 120000 Lang/FreeBASIC/Bioinformatics-Global-alignment create mode 120000 Lang/FreeBASIC/Cistercian-numerals create mode 120000 Lang/FreeBASIC/Compiler-syntax-analyzer create mode 120000 Lang/FreeBASIC/Deconvolution-2D+ create mode 120000 Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series create mode 120000 Lang/FreeBASIC/Elliptic-curve-arithmetic create mode 120000 Lang/FreeBASIC/Fermat-numbers create mode 120000 Lang/FreeBASIC/Graph-colouring create mode 120000 Lang/FreeBASIC/Juggler-sequence create mode 120000 Lang/FreeBASIC/Knuths-algorithm-S create mode 120000 Lang/FreeBASIC/Knuths-power-tree create mode 120000 Lang/FreeBASIC/Last-letter-first-letter create mode 120000 Lang/FreeBASIC/Natural-sorting create mode 120000 Lang/FreeBASIC/Rosetta-Code-Fix-code-tags create mode 120000 Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity create mode 120000 Lang/FreeBASIC/SQL-based-authentication create mode 120000 Lang/FreeBASIC/Simulate-input-Keyboard create mode 120000 Lang/FreeBASIC/Sorting-algorithms-Strand-sort create mode 120000 Lang/FreeBASIC/Text-processing-2 create mode 120000 Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction create mode 120000 Lang/FreeBASIC/Word-ladder create mode 120000 Lang/GW-BASIC/Levenshtein-distance create mode 120000 Lang/GW-BASIC/Magic-constant create mode 120000 Lang/GW-BASIC/Map-range create mode 120000 Lang/Gambas/Evaluate-binomial-coefficients create mode 120000 Lang/Gambas/Magic-constant create mode 120000 Lang/Go/Boyer-Moore-string-search create mode 120000 Lang/Go/Goldbachs-comet create mode 120000 Lang/Go/P-Adic-square-roots create mode 120000 Lang/Haskell/Pathological-floating-point-problems create mode 120000 Lang/Icon/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/Java/Strassens-algorithm create mode 120000 Lang/JavaScript/15-puzzle-solver create mode 120000 Lang/JavaScript/ADFGVX-cipher create mode 120000 Lang/JavaScript/Average-loop-length create mode 120000 Lang/JavaScript/Bifid-cipher create mode 120000 Lang/JavaScript/Bitcoin-address-validation create mode 120000 Lang/JavaScript/Boyer-Moore-string-search create mode 120000 Lang/JavaScript/Burrows-Wheeler-transform create mode 120000 Lang/JavaScript/Camel-case-and-snake-case create mode 120000 Lang/JavaScript/Colorful-numbers create mode 120000 Lang/JavaScript/Commatizing-numbers create mode 120000 Lang/JavaScript/Compiler-code-generator create mode 120000 Lang/JavaScript/Create-a-file-on-magnetic-tape create mode 120000 Lang/JavaScript/Cyclotomic-polynomial create mode 120000 Lang/JavaScript/De-Bruijn-sequences create mode 120000 Lang/JavaScript/Distribution-of-0-digits-in-factorial-series create mode 120000 Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm create mode 120000 Lang/JavaScript/Elliptic-curve-arithmetic create mode 120000 Lang/JavaScript/Gauss-Jordan-matrix-inversion create mode 120000 Lang/JavaScript/Graph-colouring create mode 120000 Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions create mode 120000 Lang/JavaScript/Isqrt-integer-square-root-of-X create mode 120000 Lang/JavaScript/Jacobi-symbol create mode 120000 Lang/JavaScript/K-d-tree create mode 120000 Lang/JavaScript/Knuths-algorithm-S create mode 120000 Lang/JavaScript/Knuths-power-tree create mode 120000 Lang/JavaScript/M-bius-function create mode 120000 Lang/JavaScript/MD5-Implementation create mode 120000 Lang/JavaScript/P-Adic-numbers-basic create mode 120000 Lang/JavaScript/P-Adic-square-roots create mode 120000 Lang/JavaScript/Perlin-noise create mode 120000 Lang/JavaScript/Playfair-cipher create mode 120000 Lang/JavaScript/SHA-1 create mode 120000 Lang/JavaScript/Set-puzzle create mode 120000 Lang/JavaScript/Solve-a-Hidato-puzzle create mode 120000 Lang/JavaScript/Solve-a-Numbrix-puzzle create mode 120000 Lang/JavaScript/Sorting-algorithms-Radix-sort create mode 120000 Lang/JavaScript/Spelling-of-ordinal-numbers create mode 120000 Lang/JavaScript/State-name-puzzle create mode 120000 Lang/JavaScript/Strassens-algorithm create mode 120000 Lang/JavaScript/Substitution-cipher create mode 120000 Lang/JavaScript/Tonelli-Shanks-algorithm create mode 120000 Lang/JavaScript/Ukkonen-s-suffix-tree-construction create mode 120000 Lang/JavaScript/Verhoeff-algorithm create mode 120000 Lang/JavaScript/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/JavaScript/Vogels-approximation-method create mode 120000 Lang/JavaScript/Wordiff create mode 120000 Lang/JavaScript/Zebra-puzzle create mode 120000 Lang/K/Compare-length-of-two-strings create mode 120000 Lang/K/Euler-method create mode 120000 Lang/K/M-bius-function create mode 120000 Lang/K/Substring create mode 120000 Lang/K/UTF-8-encode-and-decode create mode 120000 Lang/K/Write-float-arrays-to-a-text-file create mode 120000 Lang/Logo/Merge-and-aggregate-datasets create mode 120000 Lang/Lua/Check-input-device-is-a-terminal create mode 120000 Lang/Lua/Parse-an-IP-Address create mode 120000 Lang/Lua/Ramer-Douglas-Peucker-line-simplification create mode 120000 Lang/Lua/Update-a-configuration-file create mode 120000 Lang/M2000-Interpreter/ADFGVX-cipher create mode 120000 Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- create mode 120000 Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists create mode 120000 Lang/M2000-Interpreter/Compare-length-of-two-strings create mode 120000 Lang/M2000-Interpreter/File-extension-is-in-extensions-list create mode 120000 Lang/M2000-Interpreter/Greatest-subsequential-sum create mode 120000 Lang/M2000-Interpreter/Power-set create mode 120000 Lang/M2000-Interpreter/Simple-turtle-graphics create mode 120000 Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort create mode 120000 Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/MACRO-11/Run-length-encoding create mode 120000 Lang/MAD/Look-and-say-sequence create mode 120000 Lang/MSX-Basic/Evaluate-binomial-coefficients create mode 120000 Lang/Maple/Pythagoras-tree create mode 120000 Lang/Mathematica/15-puzzle-solver create mode 120000 Lang/Mathematica/B-zier-curves-Intersections create mode 120000 Lang/Mathematica/Sisyphus-sequence create mode 120000 Lang/Mathematica/Sphenic-numbers create mode 120000 Lang/Mathematica/Wagstaff-primes create mode 120000 Lang/Minimal-BASIC/Evaluate-binomial-coefficients create mode 120000 Lang/Miranda/Loops-Infinite create mode 120000 Lang/Miranda/Run-length-encoding create mode 120000 Lang/Modula-2/M-bius-function create mode 120000 Lang/Modula-2/Magic-constant create mode 120000 Lang/Modula-2/Map-range create mode 120000 Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification create mode 120000 Lang/Nascom-BASIC/Levenshtein-distance create mode 120000 Lang/Nu/CSV-data-manipulation create mode 120000 Lang/Nu/Department-numbers create mode 120000 Lang/Nu/Determine-if-a-string-has-all-the-same-characters create mode 120000 Lang/Nu/File-extension-is-in-extensions-list create mode 120000 Lang/Nu/File-size-distribution create mode 120000 Lang/Nu/I-before-E-except-after-C create mode 120000 Lang/Nu/Word-frequency create mode 120000 Lang/OCaml/Anti-primes create mode 120000 Lang/OCaml/Attractive-numbers create mode 120000 Lang/OCaml/Cuban-primes create mode 120000 Lang/OPL/100-doors create mode 120000 Lang/OPL/Arithmetic-Integer create mode 120000 Lang/OPL/Arrays create mode 120000 Lang/OPL/Character-codes create mode 120000 Lang/OPL/Comments create mode 120000 Lang/OPL/Compare-length-of-two-strings create mode 120000 Lang/OPL/Copy-a-string create mode 120000 Lang/OPL/Draw-a-clock create mode 120000 Lang/OPL/Draw-a-pixel create mode 120000 Lang/OPL/Hello-world-Text create mode 120000 Lang/OPL/Program-termination create mode 120000 Lang/OPL/String-prepend create mode 120000 Lang/OPL/User-input-Text create mode 120000 Lang/Objeck/Copy-stdin-to-stdout create mode 120000 Lang/Objeck/Distributed-programming create mode 120000 Lang/Objeck/Floyds-triangle create mode 120000 Lang/Objeck/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Objeck/Hello-world-Standard-error create mode 120000 Lang/Objeck/Knuth-shuffle create mode 120000 Lang/Objeck/Mad-Libs create mode 120000 Lang/Objeck/Multiplication-tables create mode 120000 Lang/Objeck/Roman-numerals-Decode create mode 120000 Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks create mode 120000 Lang/Objeck/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Odin/Euler-method create mode 120000 Lang/Odin/Execute-Brain- create mode 120000 Lang/Odin/Fractran create mode 120000 Lang/Odin/Hailstone-sequence create mode 120000 Lang/Odin/Hello-world-Graphical create mode 120000 Lang/Odin/Primality-by-trial-division create mode 120000 Lang/Odin/Runge-Kutta-method create mode 120000 Lang/Odin/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Odin/Unicode-variable-names create mode 120000 Lang/Odin/Write-entire-file create mode 120000 Lang/Ol/Runge-Kutta-method create mode 120000 Lang/OxygenBasic/Evaluate-binomial-coefficients create mode 120000 Lang/PARI-GP/Attractive-numbers create mode 120000 Lang/PARI-GP/Disarium-numbers create mode 120000 Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes create mode 120000 Lang/PHP/M-bius-function create mode 120000 Lang/PHP/Magic-constant create mode 120000 Lang/PHP/Map-range create mode 120000 Lang/PL-I-80/Additive-primes create mode 120000 Lang/Pascal/Date-manipulation delete mode 120000 Lang/Pascal/FizzBuzz delete mode 120000 Lang/Pascal/Levenshtein-distance delete mode 120000 Lang/Pascal/Map-range create mode 120000 Lang/PascalABC.NET/Additive-primes create mode 120000 Lang/PascalABC.NET/Amicable-pairs create mode 120000 Lang/PascalABC.NET/Pancake-numbers create mode 120000 Lang/PascalABC.NET/Pangram-checker create mode 120000 Lang/PascalABC.NET/Paraffins create mode 120000 Lang/PascalABC.NET/Parallel-calculations create mode 120000 Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm create mode 120000 Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes create mode 120000 Lang/PascalABC.NET/Pascal-matrix-generation create mode 120000 Lang/PascalABC.NET/Pascals-triangle-Puzzle create mode 120000 Lang/PascalABC.NET/Pathological-floating-point-problems create mode 120000 Lang/PascalABC.NET/Pells-equation create mode 120000 Lang/PascalABC.NET/Perfect-shuffle create mode 120000 Lang/PascalABC.NET/Perfect-totient-numbers create mode 120000 Lang/PascalABC.NET/Permutation-test create mode 120000 Lang/Perl/Execute-Computer-Zero create mode 120000 Lang/Prolog/Evaluate-binomial-coefficients create mode 120000 Lang/Python/Im-a-software-engineer-get-me-out-of-here create mode 120000 Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes create mode 120000 Lang/Python/Square-form-factorization create mode 120000 Lang/Python/Wasteful-equidigital-and-frugal-numbers create mode 120000 Lang/Q/Euler-method create mode 120000 Lang/QBasic/Evaluate-binomial-coefficients create mode 120000 Lang/QBasic/Map-range create mode 120000 Lang/Quackery/Dice-game-probabilities create mode 120000 Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/Quackery/Two-bullet-roulette create mode 120000 Lang/R/Camel-case-and-snake-case create mode 120000 Lang/R/Determine-sentence-type create mode 120000 Lang/R/Disarium-numbers create mode 120000 Lang/R/Display-a-linear-combination create mode 120000 Lang/R/Draw-a-cuboid create mode 120000 Lang/R/Dutch-national-flag-problem create mode 120000 Lang/R/Factorions create mode 120000 Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases create mode 120000 Lang/R/Halt-and-catch-fire create mode 120000 Lang/R/Hex-words create mode 120000 Lang/R/Kernighans-large-earthquake-problem create mode 120000 Lang/R/Munchausen-numbers create mode 120000 Lang/R/Old-Russian-measure-of-length create mode 120000 Lang/R/Semordnilap create mode 120000 Lang/R/Sort-numbers-lexicographically create mode 120000 Lang/R/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/REXX/Magic-constant create mode 120000 Lang/REXX/Primes---allocate-descendants-to-their-ancestors create mode 120000 Lang/REXX/Ramanujan-primes-twins create mode 120000 Lang/REXX/Sequence-of-primorial-primes create mode 120000 Lang/REXX/Sieve-of-Pritchard create mode 120000 Lang/Raku/Simple-turtle-graphics create mode 120000 Lang/RapidQ/Levenshtein-distance create mode 120000 Lang/RapidQ/M-bius-function create mode 120000 Lang/RapidQ/Map-range create mode 120000 Lang/Refal/Loops-Infinite create mode 120000 Lang/Refal/Power-set create mode 120000 Lang/Refal/Run-length-encoding create mode 120000 Lang/Refal/Strip-comments-from-a-string create mode 120000 Lang/Rust/Ascending-primes create mode 120000 Lang/Rust/B-zier-curves-Intersections create mode 120000 Lang/Rust/Bifid-cipher create mode 120000 Lang/Rust/Bioinformatics-Global-alignment create mode 120000 Lang/Rust/Blum-integer create mode 120000 Lang/Rust/Boyer-Moore-string-search create mode 120000 Lang/Rust/Calendar---for-REAL-programmers create mode 120000 Lang/Rust/Compare-sorting-algorithms-performance create mode 120000 Lang/Rust/Compiler-AST-interpreter create mode 120000 Lang/Rust/Compiler-code-generator create mode 120000 Lang/Rust/Compiler-lexical-analyzer create mode 120000 Lang/Rust/Compiler-syntax-analyzer create mode 120000 Lang/Rust/Cyclotomic-polynomial create mode 120000 Lang/Rust/Descending-primes create mode 120000 Lang/Rust/Doubly-linked-list-Definition create mode 120000 Lang/Rust/Doubly-linked-list-Traversal create mode 120000 Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm create mode 120000 Lang/Rust/Faulhabers-formula create mode 120000 Lang/Rust/Graph-colouring create mode 120000 Lang/Rust/Hex-words create mode 120000 Lang/Rust/Kosaraju create mode 120000 Lang/Rust/Latin-Squares-in-reduced-form create mode 120000 Lang/Rust/Median-filter create mode 120000 Lang/Rust/Natural-sorting create mode 120000 Lang/Rust/Nonogram-solver create mode 120000 Lang/Rust/OpenWebNet-password create mode 120000 Lang/Rust/P-Adic-numbers-basic create mode 120000 Lang/Rust/P-Adic-square-roots create mode 120000 Lang/Rust/Playfair-cipher create mode 120000 Lang/Rust/Polynomial-regression create mode 120000 Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a create mode 120000 Lang/Rust/Pseudo-random-numbers-Middle-square-method create mode 120000 Lang/Rust/Pseudo-random-numbers-Splitmix64 create mode 120000 Lang/Rust/QR-decomposition create mode 120000 Lang/Rust/Rendezvous create mode 120000 Lang/Rust/Resistor-mesh create mode 120000 Lang/Rust/Shoelace-formula-for-polygonal-area create mode 120000 Lang/Rust/Solve-a-Holy-Knights-tour create mode 120000 Lang/Rust/Solve-a-Hopido-puzzle create mode 120000 Lang/Rust/Solve-a-Numbrix-puzzle create mode 120000 Lang/Rust/Sorting-algorithms-Bead-sort create mode 120000 Lang/Rust/Sorting-algorithms-Patience-sort create mode 120000 Lang/Rust/Sorting-algorithms-Strand-sort create mode 120000 Lang/Rust/Steffensens-method create mode 120000 Lang/Rust/Strassens-algorithm create mode 120000 Lang/Rust/Stream-merge create mode 120000 Lang/Rust/Sudan-function create mode 120000 Lang/Rust/Tonelli-Shanks-algorithm create mode 120000 Lang/Rust/Ukkonen-s-suffix-tree-construction create mode 120000 Lang/Rust/Verhoeff-algorithm create mode 120000 Lang/Rust/Xiaolin-Wus-line-algorithm create mode 120000 Lang/S-BASIC/Additive-primes create mode 120000 Lang/S-BASIC/Character-codes create mode 120000 Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/S-BASIC/Sum-of-a-series create mode 120000 Lang/SETL/Gray-code create mode 120000 Lang/SETL/Loops-Do-while create mode 120000 Lang/SETL/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/SETL/Loops-Infinite create mode 120000 Lang/SETL/Radical-of-an-integer create mode 120000 Lang/SETL/Strip-comments-from-a-string create mode 120000 Lang/SQL/Factorial create mode 120000 Lang/Scala/Boyer-Moore-string-search create mode 120000 Lang/Scheme/Circular-primes create mode 120000 Lang/Scheme/Compare-length-of-two-strings create mode 120000 Lang/Scheme/Runge-Kutta-method create mode 120000 Lang/Scheme/Unicode-variable-names create mode 120000 Lang/Standard-ML/Box-the-compass create mode 120000 Lang/Tcl/Unicode-strings create mode 120000 Lang/Tiny-BASIC/Magic-constant create mode 120000 Lang/True-BASIC/Evaluate-binomial-coefficients create mode 120000 Lang/TypeScript/Additive-primes create mode 120000 Lang/TypeScript/Arithmetic-numbers create mode 120000 Lang/TypeScript/Map-range create mode 120000 Lang/TypeScript/Sum-of-a-series create mode 120000 Lang/UNIX-Shell/Color-of-a-screen-pixel create mode 120000 Lang/UNIX-Shell/Color-quantization create mode 120000 Lang/Uiua/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/Uiua/Damm-algorithm create mode 120000 Lang/Uiua/Ethiopian-multiplication create mode 120000 Lang/Uiua/Matrix-transposition create mode 120000 Lang/Uiua/Munching-squares create mode 120000 Lang/Uiua/Pangram-checker create mode 120000 Lang/Uiua/Spiral-matrix create mode 120000 Lang/Uiua/Zig-zag-matrix create mode 120000 Lang/Uxntal/Array-length create mode 120000 Lang/Uxntal/Bioinformatics-base-count create mode 120000 Lang/Uxntal/Comments create mode 120000 Lang/Uxntal/Conditional-structures create mode 120000 Lang/Uxntal/Copy-a-string delete mode 120000 Lang/Uxntal/Draw-a-pixel create mode 120000 Lang/Uxntal/Fibonacci-sequence create mode 120000 Lang/Uxntal/Flow-control-structures create mode 120000 Lang/Uxntal/Hello-world-Graphical create mode 120000 Lang/Uxntal/Hello-world-Standard-error delete mode 120000 Lang/Uxntal/Hello-world-Text create mode 120000 Lang/Uxntal/Integer-sequence create mode 120000 Lang/Uxntal/Loops-Break create mode 120000 Lang/Uxntal/Loops-Continue create mode 120000 Lang/Uxntal/Loops-Do-while create mode 120000 Lang/Uxntal/Loops-For-with-a-specified-step create mode 120000 Lang/Uxntal/Loops-Foreach create mode 120000 Lang/Uxntal/Loops-N-plus-one-half create mode 120000 Lang/Uxntal/Loops-While create mode 120000 Lang/Uxntal/Stack-traces create mode 120000 Lang/Uxntal/String-length create mode 120000 Lang/V-(Vlang)/Quine create mode 120000 Lang/Wisp/Knuth-shuffle create mode 120000 Lang/X86-64-Assembly/Terminal-control-Clear-the-screen create mode 120000 Lang/XBasic/Levenshtein-distance create mode 120000 Lang/XPL0/Bin-given-limits create mode 120000 Lang/XPL0/Create-an-object-at-a-given-address create mode 120000 Lang/XPL0/Floyd-Warshall-algorithm create mode 120000 Lang/XPL0/Largest-int-from-concatenated-ints create mode 120000 Lang/XPL0/Last-letter-first-letter create mode 120000 Lang/XPL0/Levenshtein-distance create mode 120000 Lang/XPL0/Polynomial-regression create mode 120000 Lang/XPL0/Read-a-configuration-file create mode 120000 Lang/XPL0/Sort-three-variables create mode 120000 Lang/XPL0/Text-processing-1 create mode 120000 Lang/XPL0/Text-processing-2 create mode 120000 Lang/Yabasic/Evaluate-binomial-coefficients create mode 120000 Lang/Zig/15-puzzle-solver create mode 120000 Lang/Zig/2048 create mode 120000 Lang/Zig/24-game create mode 120000 Lang/Zig/Anti-primes create mode 120000 Lang/Zig/Canonicalize-CIDR create mode 120000 Lang/Zig/Convex-hull create mode 120000 Lang/Zig/De-Bruijn-sequences create mode 120000 Lang/Zig/Dijkstras-algorithm create mode 120000 Lang/Zig/Execute-a-Markov-algorithm create mode 120000 Lang/Zig/Fibonacci-sequence create mode 120000 Lang/Zig/Find-the-missing-permutation create mode 120000 Lang/Zig/Floyd-Warshall-algorithm create mode 120000 Lang/Zig/Latin-Squares-in-reduced-form create mode 120000 Lang/Zig/Move-to-front-algorithm create mode 120000 Lang/Zig/Natural-sorting create mode 120000 Lang/Zig/P-Adic-numbers-basic create mode 120000 Lang/Zig/P-Adic-square-roots create mode 120000 Lang/Zig/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Zig/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Zig/Quickselect-algorithm create mode 120000 Lang/Zig/Quine create mode 120000 Lang/Zig/SHA-1 create mode 120000 Lang/Zig/Solve-a-Holy-Knights-tour create mode 120000 Lang/Zig/Sorting-algorithms-Patience-sort create mode 120000 Lang/Zig/Sorting-algorithms-Strand-sort create mode 120000 Lang/Zig/Strassens-algorithm create mode 120000 Lang/Zig/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Zig/Thue-Morse create mode 120000 Lang/Zig/Tonelli-Shanks-algorithm create mode 120000 Lang/Zig/Y-combinator create mode 100644 Task/100-doors/BQN/100-doors-4.bqn create mode 100644 Task/100-doors/BQN/100-doors-5.bqn create mode 100644 Task/100-doors/Excel/100-doors-4.excel create mode 100644 Task/100-doors/OPL/100-doors.opl create mode 100644 Task/100-doors/Quackery/100-doors-1.quackery create mode 100644 Task/100-doors/Quackery/100-doors-2.quackery delete mode 100644 Task/100-doors/Quackery/100-doors.quackery create mode 100644 Task/100-doors/Tcl/100-doors-4.tcl create mode 100644 Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js create mode 100644 Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math create mode 100644 Task/15-puzzle-solver/Zig/15-puzzle-solver.zig create mode 100644 Task/2048/EasyLang/2048.easy create mode 100644 Task/2048/Zig/2048.zig create mode 100644 Task/24-game-Solve/Dart/24-game-solve.dart create mode 100644 Task/24-game/Zig/24-game.zig create mode 100644 Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor rename Task/99-bottles-of-beer/Factor/{99-bottles-of-beer.factor => 99-bottles-of-beer-2.factor} (100%) create mode 100644 Task/A+B/Ballerina/a+b.ballerina delete mode 100644 Task/A+B/REXX/a+b-1.rexx delete mode 100644 Task/A+B/REXX/a+b-2.rexx delete mode 100644 Task/A+B/REXX/a+b-3.rexx delete mode 100644 Task/A+B/REXX/a+b-4.rexx delete mode 100644 Task/A+B/REXX/a+b-5.rexx create mode 100644 Task/A+B/REXX/a+b.rexx create mode 100644 Task/ABC-problem/Ballerina/abc-problem.ballerina create mode 100644 Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs create mode 100644 Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js create mode 100644 Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000 create mode 100644 Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina delete mode 100644 Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx create mode 100644 Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-1.cs create mode 100644 Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-2.cs create mode 100644 Task/Abbreviations-automatic/EasyLang/abbreviations-automatic.easy create mode 100644 Task/Abbreviations-easy/Crystal/abbreviations-easy.cr create mode 100644 Task/Abbreviations-easy/EasyLang/abbreviations-easy.easy create mode 100644 Task/Abbreviations-simple/EasyLang/abbreviations-simple.easy create mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-1.ballerina create mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-2.ballerina delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-3.rexx delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-4.rexx create mode 100644 Task/Abundant-odd-numbers/Ballerina/abundant-odd-numbers.ballerina create mode 100644 Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina create mode 100644 Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina create mode 100644 Task/Ackermann-function/Ballerina/ackermann-function.ballerina create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina create mode 100644 Task/Additive-primes/ALGOL-60/additive-primes.alg create mode 100644 Task/Additive-primes/ALGOL-M/additive-primes.alg create mode 100644 Task/Additive-primes/Ballerina/additive-primes.ballerina create mode 100644 Task/Additive-primes/PL-I-80/additive-primes.pli create mode 100644 Task/Additive-primes/PascalABC.NET/additive-primes.pas create mode 100644 Task/Additive-primes/S-BASIC/additive-primes.basic create mode 100644 Task/Additive-primes/TypeScript/additive-primes.ts create mode 100644 Task/Address-of-a-variable/Ballerina/address-of-a-variable.ballerina create mode 100644 Task/Almost-prime/Ballerina/almost-prime.ballerina create mode 100644 Task/Almost-prime/Forth/almost-prime.fth delete mode 100644 Task/Almost-prime/REXX/almost-prime-1.rexx delete mode 100644 Task/Almost-prime/REXX/almost-prime-2.rexx rename Task/Almost-prime/REXX/{almost-prime-3.rexx => almost-prime.rexx} (92%) create mode 100644 Task/Amb/Ballerina/amb.ballerina create mode 100644 Task/Amb/EasyLang/amb.easy create mode 100644 Task/Amicable-pairs/PascalABC.NET/amicable-pairs.pas delete mode 100644 Task/Amicable-pairs/REXX/amicable-pairs-3.rexx delete mode 100644 Task/Amicable-pairs/REXX/amicable-pairs-4.rexx delete mode 100644 Task/Amicable-pairs/REXX/amicable-pairs-5.rexx delete mode 100644 Task/Amicable-pairs/REXX/amicable-pairs-6.rexx create mode 100644 Task/Anagrams-Deranged-anagrams/Crystal/anagrams-deranged-anagrams.cr create mode 100644 Task/Anagrams-Deranged-anagrams/EasyLang/anagrams-deranged-anagrams.easy create mode 100644 Task/Anagrams/EasyLang/anagrams.easy create mode 100644 Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina create mode 100644 Task/Anti-primes/Ballerina/anti-primes.ballerina create mode 100644 Task/Anti-primes/OCaml/anti-primes.ml delete mode 100644 Task/Anti-primes/REXX/anti-primes-3.rexx create mode 100644 Task/Anti-primes/Zig/anti-primes.zig create mode 100644 Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina create mode 100644 Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f create mode 100644 Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 create mode 100644 Task/Approximate-equality/Ballerina/approximate-equality.ballerina create mode 100644 Task/Arithmetic-Complex/Ballerina/arithmetic-complex.ballerina create mode 100644 Task/Arithmetic-Complex/Crystal/arithmetic-complex.cr rename Task/Arithmetic-Complex/M2000-Interpreter/{arithmetic-complex.m2000 => arithmetic-complex-1.m2000} (100%) create mode 100644 Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex-2.m2000 create mode 100644 Task/Arithmetic-Integer/Ballerina/arithmetic-integer.ballerina create mode 100644 Task/Arithmetic-Integer/OPL/arithmetic-integer.opl create mode 100644 Task/Arithmetic-Rational/Ballerina/arithmetic-rational.ballerina create mode 100644 Task/Arithmetic-derivative/Arturo/arithmetic-derivative.arturo create mode 100644 Task/Arithmetic-derivative/C-sharp/arithmetic-derivative.cs create mode 100644 Task/Arithmetic-geometric-mean/Crystal/arithmetic-geometric-mean.cr create mode 100644 Task/Arithmetic-numbers/Ballerina/arithmetic-numbers.ballerina create mode 100644 Task/Arithmetic-numbers/TypeScript/arithmetic-numbers.ts create mode 100644 Task/Array-concatenation/Ballerina/array-concatenation.ballerina delete mode 100644 Task/Array-concatenation/REXX/array-concatenation-1.rexx delete mode 100644 Task/Array-concatenation/REXX/array-concatenation-2.rexx delete mode 100644 Task/Array-concatenation/REXX/array-concatenation-3.rexx create mode 100644 Task/Array-concatenation/REXX/array-concatenation.rexx create mode 100644 Task/Array-length/Ballerina/array-length.ballerina create mode 100644 Task/Array-length/Uxntal/array-length.uxnatl create mode 100644 Task/Arrays/Ballerina/arrays.ballerina create mode 100644 Task/Arrays/Excel/arrays-1.excel create mode 100644 Task/Arrays/Excel/arrays-2.excel create mode 100644 Task/Arrays/Excel/arrays-3.excel create mode 100644 Task/Arrays/OPL/arrays.opl delete mode 100644 Task/Arrays/REXX/arrays-1.rexx delete mode 100644 Task/Arrays/REXX/arrays-2.rexx delete mode 100644 Task/Arrays/REXX/arrays-3.rexx delete mode 100644 Task/Arrays/REXX/arrays-4.rexx delete mode 100644 Task/Arrays/REXX/arrays-5.rexx delete mode 100644 Task/Arrays/REXX/arrays-6.rexx create mode 100644 Task/Arrays/REXX/arrays.rexx create mode 100644 Task/Arrays/Tcl/arrays-3.tcl create mode 100644 Task/Arrays/Tcl/arrays-4.tcl create mode 100644 Task/Arrays/Tcl/arrays-5.tcl create mode 100644 Task/Arrays/Tcl/arrays-6.tcl create mode 100644 Task/Ascending-primes/Ballerina/ascending-primes.ballerina create mode 100644 Task/Ascending-primes/Rust/ascending-primes-1.rs create mode 100644 Task/Ascending-primes/Rust/ascending-primes-2.rs create mode 100644 Task/Ascending-primes/Rust/ascending-primes-3.rs create mode 100644 Task/Associative-array-Creation/Ballerina/associative-array-creation.ballerina create mode 100644 Task/Associative-array-Iteration/Ballerina/associative-array-iteration.ballerina create mode 100644 Task/Associative-array-Merging/Ballerina/associative-array-merging.ballerina create mode 100644 Task/Associative-array-Merging/Common-Lisp/associative-array-merging-3.lisp create mode 100644 Task/Attractive-numbers/OCaml/attractive-numbers.ml create mode 100644 Task/Attractive-numbers/PARI-GP/attractive-numbers-1.parigp create mode 100644 Task/Attractive-numbers/PARI-GP/attractive-numbers-2.parigp create mode 100644 Task/Average-loop-length/JavaScript/average-loop-length.js create mode 100644 Task/Averages-Arithmetic-mean/Ballerina/averages-arithmetic-mean.ballerina create mode 100644 Task/Averages-Mean-angle/Ballerina/averages-mean-angle.ballerina create mode 100644 Task/Averages-Mean-time-of-day/Ballerina/averages-mean-time-of-day.ballerina create mode 100644 Task/Averages-Median/Ballerina/averages-median.ballerina create mode 100644 Task/Averages-Mode/Ballerina/averages-mode.ballerina create mode 100644 Task/Averages-Mode/Crystal/averages-mode.cr create mode 100644 Task/Averages-Pythagorean-means/Ballerina/averages-pythagorean-means.ballerina create mode 100644 Task/Averages-Pythagorean-means/Crystal/averages-pythagorean-means.cr create mode 100644 Task/Averages-Root-mean-square/Ballerina/averages-root-mean-square.ballerina create mode 100644 Task/Averages-Simple-moving-average/Ballerina/averages-simple-moving-average.ballerina create mode 100644 Task/B-zier-curves-Intersections/Fortran/b-zier-curves-intersections.f create mode 100644 Task/B-zier-curves-Intersections/Mathematica/b-zier-curves-intersections.math create mode 100644 Task/B-zier-curves-Intersections/Rust/b-zier-curves-intersections.rs create mode 100644 Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy create mode 100644 Task/Balanced-brackets/Ballerina/balanced-brackets.ballerina create mode 100644 Task/Balanced-brackets/Excel/balanced-brackets-3.excel create mode 100644 Task/Balanced-brackets/Excel/balanced-brackets-4.excel rename Task/Bell-numbers/C-sharp/{bell-numbers.cs => bell-numbers-1.cs} (100%) create mode 100644 Task/Bell-numbers/C-sharp/bell-numbers-2.cs create mode 100644 Task/Bifid-cipher/JavaScript/bifid-cipher.js create mode 100644 Task/Bifid-cipher/Rust/bifid-cipher.rs create mode 100644 Task/Bin-given-limits/AppleScript/bin-given-limits.applescript create mode 100644 Task/Bin-given-limits/Crystal/bin-given-limits.cr create mode 100644 Task/Bin-given-limits/XPL0/bin-given-limits.xpl0 create mode 100644 Task/Binary-digits/C3/binary-digits.c3 create mode 100644 Task/Bioinformatics-Global-alignment/FreeBASIC/bioinformatics-global-alignment.basic create mode 100644 Task/Bioinformatics-Global-alignment/Rust/bioinformatics-global-alignment.rs create mode 100644 Task/Bioinformatics-base-count/Uxntal/bioinformatics-base-count.uxnatl create mode 100644 Task/Bitcoin-address-validation/JavaScript/bitcoin-address-validation.js create mode 100644 Task/Blum-integer/Rust/blum-integer.rs create mode 100644 Task/Boolean-values/Ballerina/boolean-values.ballerina create mode 100644 Task/Box-the-compass/Standard-ML/box-the-compass.ml create mode 100644 Task/Boyer-Moore-string-search/C-sharp/boyer-moore-string-search.cs create mode 100644 Task/Boyer-Moore-string-search/EasyLang/boyer-moore-string-search.easy create mode 100644 Task/Boyer-Moore-string-search/Go/boyer-moore-string-search.go create mode 100644 Task/Boyer-Moore-string-search/JavaScript/boyer-moore-string-search.js create mode 100644 Task/Boyer-Moore-string-search/Rust/boyer-moore-string-search.rs create mode 100644 Task/Boyer-Moore-string-search/Scala/boyer-moore-string-search.scala create mode 100644 Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js create mode 100644 Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu create mode 100644 Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu create mode 100644 Task/Caesar-cipher/Ballerina/caesar-cipher.ballerina create mode 100644 Task/Calculating-the-value-of-e/Ballerina/calculating-the-value-of-e.ballerina create mode 100644 Task/Calendar---for-REAL-programmers/Rust/calendar---for-real-programmers.rs create mode 100644 Task/Calkin-Wilf-sequence/C-sharp/calkin-wilf-sequence.cs create mode 100644 Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js create mode 100644 Task/Camel-case-and-snake-case/R/camel-case-and-snake-case.r create mode 100644 Task/Canonicalize-CIDR/Zig/canonicalize-cidr.zig delete mode 100644 Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-1.rexx delete mode 100644 Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-2.rexx create mode 100644 Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx create mode 100644 Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-1.cpp create mode 100644 Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-2.cpp delete mode 100644 Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists.cpp create mode 100644 Task/Cartesian-product-of-two-or-more-lists/M2000-Interpreter/cartesian-product-of-two-or-more-lists.m2000 create mode 100644 Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs create mode 100644 Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina create mode 100644 Task/Character-codes/Ballerina/character-codes.ballerina create mode 100644 Task/Character-codes/Crystal/character-codes.cr create mode 100644 Task/Character-codes/OPL/character-codes.opl create mode 100644 Task/Character-codes/S-BASIC/character-codes.basic create mode 100644 Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua create mode 100644 Task/Check-that-file-exists/Lua/check-that-file-exists-3.lua delete mode 100644 Task/Chowla-numbers/REXX/chowla-numbers-1.rexx rename Task/Chowla-numbers/REXX/{chowla-numbers-2.rexx => chowla-numbers.rexx} (90%) delete mode 100644 Task/Circular-primes/REXX/circular-primes-1.rexx rename Task/Circular-primes/REXX/{circular-primes-2.rexx => circular-primes.rexx} (77%) create mode 100644 Task/Circular-primes/Scheme/circular-primes.scm create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-1.ada create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-2.ada create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-3.ada create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-4.ada create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-5.ada create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-6.ada create mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-7.ada create mode 100644 Task/Cistercian-numerals/Applesoft-BASIC/cistercian-numerals.basic create mode 100644 Task/Cistercian-numerals/Crystal/cistercian-numerals.cr create mode 100644 Task/Cistercian-numerals/FreeBASIC/cistercian-numerals.basic create mode 100644 Task/Classes/Ballerina/classes.ballerina create mode 100644 Task/Closures-Value-capture/Crystal/closures-value-capture.cr create mode 100644 Task/Color-of-a-screen-pixel/UNIX-Shell/color-of-a-screen-pixel.sh create mode 100644 Task/Color-quantization/UNIX-Shell/color-quantization.sh create mode 100644 Task/Color-wheel/C/color-wheel.c create mode 100644 Task/Color-wheel/Emacs-Lisp/color-wheel.l create mode 100644 Task/Colorful-numbers/JavaScript/colorful-numbers.js rename Task/Colour-bars-Display/Python/{colour-bars-display.py => colour-bars-display-1.py} (100%) create mode 100644 Task/Colour-bars-Display/Python/colour-bars-display-2.py create mode 100644 Task/Comma-quibbling/Crystal/comma-quibbling.cr create mode 100644 Task/Comma-quibbling/Elena/comma-quibbling-1.elena create mode 100644 Task/Comma-quibbling/Elena/comma-quibbling-2.elena rename Task/Command-line-arguments/AArch64-Assembly/{command-line-arguments.aarch64 => command-line-arguments-1.aarch64} (100%) create mode 100644 Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 create mode 100644 Task/Commatizing-numbers/JavaScript/commatizing-numbers.js create mode 100644 Task/Comments/OPL/comments.opl create mode 100644 Task/Comments/Uxntal/comments.uxnatl create mode 100644 Task/Compare-length-of-two-strings/K/compare-length-of-two-strings.k create mode 100644 Task/Compare-length-of-two-strings/M2000-Interpreter/compare-length-of-two-strings-1.m2000 create mode 100644 Task/Compare-length-of-two-strings/M2000-Interpreter/compare-length-of-two-strings-2.m2000 create mode 100644 Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-1.opl create mode 100644 Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-2.opl create mode 100644 Task/Compare-length-of-two-strings/Scheme/compare-length-of-two-strings.scm create mode 100644 Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-1.rs create mode 100644 Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-2.rs create mode 100644 Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-3.rs create mode 100644 Task/Compiler-AST-interpreter/Rust/compiler-ast-interpreter.rs create mode 100644 Task/Compiler-code-generator/JavaScript/compiler-code-generator.js create mode 100644 Task/Compiler-code-generator/Rust/compiler-code-generator.rs create mode 100644 Task/Compiler-lexical-analyzer/Rust/compiler-lexical-analyzer.rs create mode 100644 Task/Compiler-syntax-analyzer/FreeBASIC/compiler-syntax-analyzer.basic create mode 100644 Task/Compiler-syntax-analyzer/Rust/compiler-syntax-analyzer.rs create mode 100644 Task/Concurrent-computing/Elena/concurrent-computing.elena create mode 100644 Task/Conditional-structures/Excel/conditional-structures-1.excel create mode 100644 Task/Conditional-structures/Excel/conditional-structures-2.excel create mode 100644 Task/Conditional-structures/Excel/conditional-structures-3.excel create mode 100644 Task/Conditional-structures/Uxntal/conditional-structures.uxnatl delete mode 100644 Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-1.rexx rename Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/{consecutive-primes-with-ascending-or-descending-differences-2.rexx => consecutive-primes-with-ascending-or-descending-differences.rexx} (51%) create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/C-sharp/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.cs create mode 100644 Task/Convert-seconds-to-compound-duration/Crystal/convert-seconds-to-compound-duration.cr create mode 100644 Task/Convex-hull/Zig/convex-hull.zig create mode 100644 Task/Copy-a-string/OPL/copy-a-string.opl create mode 100644 Task/Copy-a-string/Uxntal/copy-a-string.uxnatl create mode 100644 Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck delete mode 100644 Task/Count-in-factors/REXX/count-in-factors-1.rexx delete mode 100644 Task/Count-in-factors/REXX/count-in-factors-2.rexx rename Task/Count-in-factors/REXX/{count-in-factors-3.rexx => count-in-factors.rexx} (61%) create mode 100644 Task/Count-in-octal/Ballerina/count-in-octal.ballerina create mode 100644 Task/Create-a-file-on-magnetic-tape/JavaScript/create-a-file-on-magnetic-tape.js create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Uiua/create-a-two-dimensional-array-at-runtime.uiua create mode 100644 Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 create mode 100644 Task/Cuban-primes/OCaml/cuban-primes.ml delete mode 100644 Task/Cuban-primes/REXX/cuban-primes-1.rexx rename Task/Cuban-primes/REXX/{cuban-primes-2.rexx => cuban-primes.rexx} (92%) create mode 100644 Task/Currency/Ballerina/currency.ballerina create mode 100644 Task/Currency/C++/currency.cpp create mode 100644 Task/Currying/Ballerina/currying.ballerina create mode 100644 Task/Curzon-numbers/Ada/curzon-numbers.ada create mode 100644 Task/Cyclotomic-polynomial/JavaScript/cyclotomic-polynomial.js create mode 100644 Task/Cyclotomic-polynomial/Rust/cyclotomic-polynomial.rs create mode 100644 Task/DNS-query/Free-Pascal-Lazarus/dns-query.pas create mode 100644 Task/Damm-algorithm/Uiua/damm-algorithm.uiua create mode 100644 Task/Date-manipulation/Pascal/date-manipulation.pas create mode 100644 Task/De-Bruijn-sequences/JavaScript/de-bruijn-sequences.js create mode 100644 Task/De-Bruijn-sequences/Zig/de-bruijn-sequences.zig create mode 100644 Task/Deconvolution-2D+/FreeBASIC/deconvolution-2d+.basic create mode 100644 Task/Department-numbers/Nu/department-numbers.nu create mode 100644 Task/Descending-primes/Rust/descending-primes-1.rs create mode 100644 Task/Descending-primes/Rust/descending-primes-2.rs create mode 100644 Task/Descending-primes/Rust/descending-primes-3.rs create mode 100644 Task/Descending-primes/Rust/descending-primes-4.rs rename Task/Detect-division-by-zero/REXX/{detect-division-by-zero.rexx => detect-division-by-zero-1.rexx} (100%) create mode 100644 Task/Detect-division-by-zero/REXX/detect-division-by-zero-2.rexx create mode 100644 Task/Detect-division-by-zero/REXX/detect-division-by-zero-3.rexx create mode 100644 Task/Determine-if-a-string-has-all-the-same-characters/Crystal/determine-if-a-string-has-all-the-same-characters.cr create mode 100644 Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-1.nu create mode 100644 Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-2.nu create mode 100644 Task/Determine-if-a-string-is-collapsible/Crystal/determine-if-a-string-is-collapsible.cr create mode 100644 Task/Determine-sentence-type/R/determine-sentence-type.r create mode 100644 Task/Dice-game-probabilities/Arturo/dice-game-probabilities.arturo create mode 100644 Task/Dice-game-probabilities/Quackery/dice-game-probabilities.quackery delete mode 100644 Task/Digital-root/REXX/digital-root-3.rexx delete mode 100644 Task/Digital-root/REXX/digital-root-4.rexx create mode 100644 Task/Dijkstras-algorithm/Crystal/dijkstras-algorithm.cr create mode 100644 Task/Dijkstras-algorithm/Zig/dijkstras-algorithm.zig create mode 100644 Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp create mode 100644 Task/Disarium-numbers/R/disarium-numbers.r create mode 100644 Task/Display-a-linear-combination/R/display-a-linear-combination.r create mode 100644 Task/Distributed-programming/Objeck/distributed-programming.objeck create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-1.basic create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-2.basic create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/JavaScript/distribution-of-0-digits-in-factorial-series.js create mode 100644 Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs create mode 100644 Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs delete mode 100644 Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rs delete mode 100644 Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rs create mode 100644 Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs create mode 100644 Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs create mode 100644 Task/Draw-a-clock/OPL/draw-a-clock.opl create mode 100644 Task/Draw-a-cuboid/R/draw-a-cuboid.r create mode 100644 Task/Draw-a-pixel/OPL/draw-a-pixel.opl delete mode 100644 Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl create mode 100644 Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr create mode 100644 Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r create mode 100644 Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina create mode 100644 Task/Element-wise-operations/Arturo/element-wise-operations.arturo create mode 100644 Task/Element-wise-operations/EasyLang/element-wise-operations.easy rename Task/Element-wise-operations/K/{element-wise-operations.k => element-wise-operations-1.k} (100%) create mode 100644 Task/Element-wise-operations/K/element-wise-operations-2.k create mode 100644 Task/Elliptic-Curve-Digital-Signature-Algorithm/C-sharp/elliptic-curve-digital-signature-algorithm.cs create mode 100644 Task/Elliptic-Curve-Digital-Signature-Algorithm/JavaScript/elliptic-curve-digital-signature-algorithm.js create mode 100644 Task/Elliptic-Curve-Digital-Signature-Algorithm/Rust/elliptic-curve-digital-signature-algorithm.rs create mode 100644 Task/Elliptic-curve-arithmetic/ALGOL-68/elliptic-curve-arithmetic.alg create mode 100644 Task/Elliptic-curve-arithmetic/FreeBASIC/elliptic-curve-arithmetic.basic create mode 100644 Task/Elliptic-curve-arithmetic/JavaScript/elliptic-curve-arithmetic.js delete mode 100644 Task/Emirp-primes/REXX/emirp-primes-3.rexx create mode 100644 Task/Empty-string/Ballerina/empty-string.ballerina create mode 100644 Task/Entropy-Narcissist/Arturo/entropy-narcissist.arturo create mode 100644 Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua create mode 100644 Task/Euler-method/K/euler-method.k create mode 100644 Task/Euler-method/Odin/euler-method.odin create mode 100644 Task/Euler-method/Q/euler-method.q create mode 100644 Task/Eulers-constant-0.5772.../Fortran/eulers-constant-0.5772....f create mode 100644 Task/Evaluate-binomial-coefficients/Asymptote/evaluate-binomial-coefficients.asymptote create mode 100644 Task/Evaluate-binomial-coefficients/BASIC256/evaluate-binomial-coefficients.basic create mode 100644 Task/Evaluate-binomial-coefficients/Chipmunk-Basic/evaluate-binomial-coefficients.basic create mode 100644 Task/Evaluate-binomial-coefficients/Gambas/evaluate-binomial-coefficients.gambas create mode 100644 Task/Evaluate-binomial-coefficients/MSX-Basic/evaluate-binomial-coefficients.basic create mode 100644 Task/Evaluate-binomial-coefficients/Minimal-BASIC/evaluate-binomial-coefficients.basic create mode 100644 Task/Evaluate-binomial-coefficients/OxygenBasic/evaluate-binomial-coefficients.basic create mode 100644 Task/Evaluate-binomial-coefficients/Prolog/evaluate-binomial-coefficients.pro create mode 100644 Task/Evaluate-binomial-coefficients/QBasic/evaluate-binomial-coefficients.basic create mode 100644 Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic create mode 100644 Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic create mode 100644 Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic create mode 100644 Task/Execute-Brain-/Crystal/execute-brain-.cr create mode 100644 Task/Execute-Brain-/Odin/execute-brain-.odin create mode 100644 Task/Execute-Computer-Zero/Perl/execute-computer-zero.pl create mode 100644 Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs create mode 100644 Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig create mode 100644 Task/Extensible-prime-generator/C-sharp/extensible-prime-generator.cs delete mode 100644 Task/Extensible-prime-generator/REXX/extensible-prime-generator-1.rexx delete mode 100644 Task/Extensible-prime-generator/REXX/extensible-prime-generator-3.rexx rename Task/Extensible-prime-generator/REXX/{extensible-prime-generator-2.rexx => extensible-prime-generator.rexx} (54%) create mode 100644 Task/Extreme-floating-point-values/Ballerina/extreme-floating-point-values.ballerina create mode 100644 Task/Factorial/Java/factorial-4.java delete mode 100644 Task/Factorial/REXX/factorial-3.rexx delete mode 100644 Task/Factorial/REXX/factorial-4.rexx delete mode 100644 Task/Factorial/REXX/factorial-5.rexx create mode 100644 Task/Factorial/SQL/factorial.sql create mode 100644 Task/Factorial/Tcl/factorial-7.tcl create mode 100644 Task/Factorions/EasyLang/factorions.easy create mode 100644 Task/Factorions/R/factorions.r delete mode 100644 Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-1.rexx rename Task/Factors-of-a-Mersenne-number/REXX/{factors-of-a-mersenne-number-2.rexx => factors-of-a-mersenne-number.rexx} (72%) delete mode 100644 Task/Factors-of-an-integer/REXX/factors-of-an-integer-3.rexx create mode 100644 Task/Farey-sequence/Ballerina/farey-sequence.ballerina create mode 100644 Task/Faulhabers-formula/Rust/faulhabers-formula.rs delete mode 100644 Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-1.rexx rename Task/Feigenbaum-constant-calculation/REXX/{feigenbaum-constant-calculation-2.rexx => feigenbaum-constant-calculation.rexx} (72%) create mode 100644 Task/Fermat-numbers/FreeBASIC/fermat-numbers.basic delete mode 100644 Task/Fermat-numbers/REXX/fermat-numbers-1.rexx delete mode 100644 Task/Fermat-numbers/REXX/fermat-numbers-2.rexx rename Task/Fermat-numbers/REXX/{fermat-numbers-3.rexx => fermat-numbers.rexx} (78%) create mode 100644 Task/Fibonacci-sequence/APL/fibonacci-sequence-5.apl create mode 100644 Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl create mode 100644 Task/Fibonacci-sequence/Zig/fibonacci-sequence.zig create mode 100644 Task/File-extension-is-in-extensions-list/C-sharp/file-extension-is-in-extensions-list.cs create mode 100644 Task/File-extension-is-in-extensions-list/M2000-Interpreter/file-extension-is-in-extensions-list.m2000 create mode 100644 Task/File-extension-is-in-extensions-list/Nu/file-extension-is-in-extensions-list.nu create mode 100644 Task/File-size-distribution/Nu/file-size-distribution.nu create mode 100644 Task/File-size-distribution/Tcl/file-size-distribution-1.tcl rename Task/File-size-distribution/Tcl/{file-size-distribution.tcl => file-size-distribution-2.tcl} (100%) create mode 100644 Task/Find-Chess960-starting-position-identifier/D/find-chess960-starting-position-identifier.d create mode 100644 Task/Find-common-directory-path/BQN/find-common-directory-path.bqn create mode 100644 Task/Find-if-a-point-is-within-a-triangle/C-sharp/find-if-a-point-is-within-a-triangle.cs create mode 100644 Task/Find-limit-of-recursion/Ballerina/find-limit-of-recursion.ballerina create mode 100644 Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/R/find-palindromic-numbers-in-both-binary-and-ternary-bases.r create mode 100644 Task/Find-the-missing-permutation/Zig/find-the-missing-permutation.zig create mode 100644 Task/First-perfect-square-in-base-n-with-n-unique-digits/Fortran/first-perfect-square-in-base-n-with-n-unique-digits.f create mode 100644 Task/Fivenum/Ballerina/fivenum.ballerina create mode 100644 Task/FizzBuzz/APL/fizzbuzz-7.apl rename Task/FizzBuzz/Erlang/{fizzbuzz.erl => fizzbuzz-1.erl} (100%) create mode 100644 Task/FizzBuzz/Erlang/fizzbuzz-2.erl create mode 100644 Task/FizzBuzz/Excel/fizzbuzz.excel create mode 100644 Task/FizzBuzz/Factor/fizzbuzz-4.factor create mode 100644 Task/FizzBuzz/J/fizzbuzz-10.j create mode 100644 Task/FizzBuzz/J/fizzbuzz-11.j create mode 100644 Task/FizzBuzz/J/fizzbuzz-8.j create mode 100644 Task/FizzBuzz/J/fizzbuzz-9.j delete mode 100644 Task/FizzBuzz/Pascal/fizzbuzz.pas create mode 100644 Task/FizzBuzz/Python/fizzbuzz-14.py create mode 100644 Task/FizzBuzz/Smalltalk/fizzbuzz-7.st create mode 100644 Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl create mode 100644 Task/Floyd-Warshall-algorithm/XPL0/floyd-warshall-algorithm.xpl0 create mode 100644 Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig create mode 100644 Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina create mode 100644 Task/Floyds-triangle/Objeck/floyds-triangle.objeck create mode 100644 Task/Forest-fire/J/forest-fire-3.j create mode 100644 Task/Forest-fire/J/forest-fire-4.j rename Task/Formatted-numeric-output/ALGOL-68/{formatted-numeric-output.alg => formatted-numeric-output-1.alg} (100%) create mode 100644 Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output-2.alg create mode 100644 Task/Formatted-numeric-output/Applesoft-BASIC/formatted-numeric-output.basic delete mode 100644 Task/Fortunate-numbers/REXX/fortunate-numbers-1.rexx rename Task/Fortunate-numbers/REXX/{fortunate-numbers-2.rexx => fortunate-numbers.rexx} (92%) create mode 100644 Task/Four-bit-adder/Ballerina/four-bit-adder.ballerina create mode 100644 Task/Fractran/Odin/fractran.odin create mode 100644 Task/Function-definition/Ballerina/function-definition.ballerina create mode 100644 Task/Function-definition/Excel/function-definition.excel create mode 100644 Task/Gapful-numbers/Ballerina/gapful-numbers.ballerina create mode 100644 Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js create mode 100644 Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-4.d create mode 100644 Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-5.d create mode 100644 Task/Generate-Chess960-starting-position/Delphi/generate-chess960-starting-position.pas create mode 100644 Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position-3.rs create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Objeck/generate-lower-case-ascii-alphabet.objeck rename Task/Generate-lower-case-ASCII-alphabet/Rust/{generate-lower-case-ascii-alphabet.rs => generate-lower-case-ascii-alphabet-1.rs} (100%) create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet-2.rs rename Task/Generator-Exponential/Tcl/{generator-exponential.tcl => generator-exponential-1.tcl} (100%) create mode 100644 Task/Generator-Exponential/Tcl/generator-exponential-2.tcl create mode 100644 Task/Generator-Exponential/Tcl/generator-exponential-3.tcl create mode 100644 Task/Globally-replace-text-in-several-files/BQN/globally-replace-text-in-several-files.bqn create mode 100644 Task/Goldbachs-comet/Go/goldbachs-comet.go create mode 100644 Task/Gotchas/C-sharp/gotchas.cs create mode 100644 Task/Graph-colouring/FreeBASIC/graph-colouring.basic create mode 100644 Task/Graph-colouring/JavaScript/graph-colouring.js create mode 100644 Task/Graph-colouring/Rust/graph-colouring.rs create mode 100644 Task/Gray-code/SETL/gray-code.setl create mode 100644 Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina create mode 100644 Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 create mode 100644 Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 create mode 100644 Task/Greedy-algorithm-for-Egyptian-fractions/JavaScript/greedy-algorithm-for-egyptian-fractions.js create mode 100644 Task/HTTP/Elena/http.elena create mode 100644 Task/HTTPS/Elena/https.elena create mode 100644 Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina create mode 100644 Task/Hailstone-sequence/Odin/hailstone-sequence.odin create mode 100644 Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r create mode 100644 Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r delete mode 100644 Task/Hamming-numbers/REXX/hamming-numbers-1.rexx delete mode 100644 Task/Hamming-numbers/REXX/hamming-numbers-2.rexx delete mode 100644 Task/Hamming-numbers/REXX/hamming-numbers-3.rexx delete mode 100644 Task/Hamming-numbers/REXX/hamming-numbers-4.rexx create mode 100644 Task/Hamming-numbers/REXX/hamming-numbers.rexx create mode 100644 Task/Harmonic-series/Fortran/harmonic-series.f rename Task/Hello-world-Graphical/{Autohotkey-V2 => AutoHotKey-V2}/hello-world-graphical.ahk (100%) create mode 100644 Task/Hello-world-Graphical/Odin/hello-world-graphical.odin create mode 100644 Task/Hello-world-Graphical/Uxntal/hello-world-graphical.uxnatl create mode 100644 Task/Hello-world-Newline-omission/Ballerina/hello-world-newline-omission.ballerina rename Task/Hello-world-Standard-error/AArch64-Assembly/{hello-world-standard-error.aarch64 => hello-world-standard-error-1.aarch64} (100%) create mode 100644 Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error-2.aarch64 create mode 100644 Task/Hello-world-Standard-error/Ballerina/hello-world-standard-error.ballerina create mode 100644 Task/Hello-world-Standard-error/Crystal/hello-world-standard-error.cr create mode 100644 Task/Hello-world-Standard-error/Objeck/hello-world-standard-error.objeck create mode 100644 Task/Hello-world-Standard-error/Uxntal/hello-world-standard-error.uxnatl rename Task/Hello-world-Text/AArch64-Assembly/{hello-world-text.aarch64 => hello-world-text-1.aarch64} (100%) create mode 100644 Task/Hello-world-Text/AArch64-Assembly/hello-world-text-2.aarch64 create mode 100644 Task/Hello-world-Text/AArch64-Assembly/hello-world-text-3.aarch64 create mode 100644 Task/Hello-world-Text/OPL/hello-world-text.opl delete mode 100644 Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl create mode 100644 Task/Hex-words/Crystal/hex-words.cr create mode 100644 Task/Hex-words/R/hex-words.r create mode 100644 Task/Hex-words/Rust/hex-words.rs delete mode 100644 Task/Higher-order-functions/REXX/higher-order-functions-2.rexx rename Task/Higher-order-functions/REXX/{higher-order-functions-1.rexx => higher-order-functions.rexx} (69%) delete mode 100644 Task/Home-primes/REXX/home-primes-1.rexx delete mode 100644 Task/Home-primes/REXX/home-primes-2.rexx create mode 100644 Task/Home-primes/REXX/home-primes.rexx delete mode 100644 Task/Humble-numbers/REXX/humble-numbers-1.rexx delete mode 100644 Task/Humble-numbers/REXX/humble-numbers-2.rexx create mode 100644 Task/Humble-numbers/REXX/humble-numbers.rexx create mode 100644 Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu create mode 100644 Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu rename Task/Identity-matrix/Excel/{identity-matrix.excel => identity-matrix-1.excel} (100%) create mode 100644 Task/Identity-matrix/Excel/identity-matrix-2.excel create mode 100644 Task/Im-a-software-engineer-get-me-out-of-here/Python/im-a-software-engineer-get-me-out-of-here.py create mode 100644 Task/Increment-a-numerical-string/Crystal/increment-a-numerical-string.cr create mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-1.tcl create mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-2.tcl create mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-3.tcl create mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-4.tcl create mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-5.tcl create mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-6.tcl delete mode 100644 Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string.tcl create mode 100644 Task/Index-finite-lists-of-positive-integers/C-sharp/index-finite-lists-of-positive-integers.cs rename Task/Input-loop/JavaScript/{input-loop.js => input-loop-1.js} (100%) create mode 100644 Task/Input-loop/JavaScript/input-loop-2.js create mode 100644 Task/Integer-sequence/Uxntal/integer-sequence.uxnatl create mode 100644 Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr rename Task/Inverted-syntax/Ruby/{inverted-syntax.rb => inverted-syntax-1.rb} (100%) create mode 100644 Task/Inverted-syntax/Ruby/inverted-syntax-2.rb create mode 100644 Task/Isqrt-integer-square-root-of-X/JavaScript/isqrt-integer-square-root-of-x.js create mode 100644 Task/Jacobi-symbol/JavaScript/jacobi-symbol.js create mode 100644 Task/Juggler-sequence/FreeBASIC/juggler-sequence.basic create mode 100644 Task/K-d-tree/C-sharp/k-d-tree.cs create mode 100644 Task/K-d-tree/Dart/k-d-tree.dart create mode 100644 Task/K-d-tree/JavaScript/k-d-tree.js create mode 100644 Task/Kernighans-large-earthquake-problem/R/kernighans-large-earthquake-problem.r create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp/keyboard-input-flush-the-keyboard-buffer.l create mode 100644 Task/Keyboard-input-Keypress-check/Emacs-Lisp/keyboard-input-keypress-check.l create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp/keyboard-input-obtain-a-y-or-n-response.l create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-3.tcl create mode 100644 Task/Knuth-shuffle/Objeck/knuth-shuffle.objeck create mode 100644 Task/Knuth-shuffle/Wisp/knuth-shuffle.wisp create mode 100644 Task/Knuths-algorithm-S/Fortran/knuths-algorithm-s.f create mode 100644 Task/Knuths-algorithm-S/FreeBASIC/knuths-algorithm-s.basic create mode 100644 Task/Knuths-algorithm-S/JavaScript/knuths-algorithm-s.js create mode 100644 Task/Knuths-power-tree/FreeBASIC/knuths-power-tree.basic create mode 100644 Task/Knuths-power-tree/JavaScript/knuths-power-tree.js create mode 100644 Task/Kosaraju/Rust/kosaraju.rs create mode 100644 Task/Largest-int-from-concatenated-ints/XPL0/largest-int-from-concatenated-ints.xpl0 create mode 100644 Task/Largest-proper-divisor-of-n/ALGOL-60/largest-proper-divisor-of-n.alg create mode 100644 Task/Last-letter-first-letter/FreeBASIC/last-letter-first-letter.basic create mode 100644 Task/Last-letter-first-letter/XPL0/last-letter-first-letter.xpl0 create mode 100644 Task/Latin-Squares-in-reduced-form/Rust/latin-squares-in-reduced-form.rs create mode 100644 Task/Latin-Squares-in-reduced-form/Zig/latin-squares-in-reduced-form.zig create mode 100644 Task/Leonardo-numbers/ERRE/leonardo-numbers.erre rename Task/Letter-frequency/Nu/{letter-frequency.nu => letter-frequency-1.nu} (100%) create mode 100644 Task/Letter-frequency/Nu/letter-frequency-2.nu create mode 100644 Task/Levenshtein-distance/ANSI-BASIC/levenshtein-distance.basic create mode 100644 Task/Levenshtein-distance/Applesoft-BASIC/levenshtein-distance.basic create mode 100644 Task/Levenshtein-distance/Ballerina/levenshtein-distance.ballerina create mode 100644 Task/Levenshtein-distance/Free-Pascal-Lazarus/levenshtein-distance.pas create mode 100644 Task/Levenshtein-distance/GW-BASIC/levenshtein-distance.basic create mode 100644 Task/Levenshtein-distance/Nascom-BASIC/levenshtein-distance.basic delete mode 100644 Task/Levenshtein-distance/Pascal/levenshtein-distance.pas create mode 100644 Task/Levenshtein-distance/RapidQ/levenshtein-distance.rapidq create mode 100644 Task/Levenshtein-distance/XBasic/levenshtein-distance.basic create mode 100644 Task/Levenshtein-distance/XPL0/levenshtein-distance.xpl0 delete mode 100644 Task/Literals-Floating-point/REXX/literals-floating-point-1.rexx delete mode 100644 Task/Literals-Floating-point/REXX/literals-floating-point-2.rexx create mode 100644 Task/Literals-Floating-point/REXX/literals-floating-point.rexx delete mode 100644 Task/Long-primes/REXX/long-primes-1.rexx delete mode 100644 Task/Long-primes/REXX/long-primes-2.rexx delete mode 100644 Task/Long-primes/REXX/long-primes-3.rexx create mode 100644 Task/Long-primes/REXX/long-primes.rexx create mode 100644 Task/Longest-string-challenge/C-sharp/longest-string-challenge.cs create mode 100644 Task/Look-and-say-sequence/MAD/look-and-say-sequence.mad create mode 100644 Task/Look-and-say-sequence/Python/look-and-say-sequence-5.py create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Ballerina/loop-over-multiple-arrays-simultaneously.ballerina create mode 100644 Task/Loops-Break/Ballerina/loops-break.ballerina create mode 100644 Task/Loops-Break/Uxntal/loops-break.uxnatl create mode 100644 Task/Loops-Continue/Ballerina/loops-continue.ballerina create mode 100644 Task/Loops-Continue/Uxntal/loops-continue.uxnatl create mode 100644 Task/Loops-Do-while/Ballerina/loops-do-while-1.ballerina create mode 100644 Task/Loops-Do-while/Ballerina/loops-do-while-2.ballerina create mode 100644 Task/Loops-Do-while/SETL/loops-do-while.setl create mode 100644 Task/Loops-Do-while/Uxntal/loops-do-while.uxnatl create mode 100644 Task/Loops-Downward-for/Ballerina/loops-downward-for.ballerina create mode 100644 Task/Loops-For-with-a-specified-step/Ballerina/loops-for-with-a-specified-step.ballerina create mode 100644 Task/Loops-For-with-a-specified-step/Uxntal/loops-for-with-a-specified-step.uxnatl create mode 100644 Task/Loops-For/Ballerina/loops-for.ballerina create mode 100644 Task/Loops-For/Excel/loops-for.excel create mode 100644 Task/Loops-For/M2000-Interpreter/loops-for-1.m2000 create mode 100644 Task/Loops-For/M2000-Interpreter/loops-for-2.m2000 delete mode 100644 Task/Loops-For/M2000-Interpreter/loops-for.m2000 create mode 100644 Task/Loops-Foreach/Ballerina/loops-foreach.ballerina create mode 100644 Task/Loops-Foreach/Uxntal/loops-foreach.uxnatl create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/ALGOL-60/loops-increment-loop-index-within-loop-body.alg create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/Ballerina/loops-increment-loop-index-within-loop-body.ballerina create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/S-BASIC/loops-increment-loop-index-within-loop-body.basic create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/SETL/loops-increment-loop-index-within-loop-body.setl create mode 100644 Task/Loops-Infinite/8080-Assembly/loops-infinite.8080 create mode 100644 Task/Loops-Infinite/APL/loops-infinite.apl create mode 100644 Task/Loops-Infinite/Ballerina/loops-infinite.ballerina create mode 100644 Task/Loops-Infinite/J/loops-infinite-3.j create mode 100644 Task/Loops-Infinite/K/loops-infinite-1.k create mode 100644 Task/Loops-Infinite/K/loops-infinite-2.k delete mode 100644 Task/Loops-Infinite/K/loops-infinite.k create mode 100644 Task/Loops-Infinite/Miranda/loops-infinite.miranda create mode 100644 Task/Loops-Infinite/Refal/loops-infinite.refal create mode 100644 Task/Loops-Infinite/SETL/loops-infinite.setl create mode 100644 Task/Loops-N-plus-one-half/Ballerina/loops-n-plus-one-half.ballerina create mode 100644 Task/Loops-N-plus-one-half/Crystal/loops-n-plus-one-half.cr create mode 100644 Task/Loops-N-plus-one-half/Uxntal/loops-n-plus-one-half.uxnatl create mode 100644 Task/Loops-Nested/Ballerina/loops-nested.ballerina create mode 100644 Task/Loops-While/Uxntal/loops-while.uxnatl create mode 100644 Task/Loops-With-multiple-ranges/Ballerina/loops-with-multiple-ranges.ballerina create mode 100644 Task/Loops-Wrong-ranges/Ballerina/loops-wrong-ranges.ballerina rename Task/Lucas-Lehmer-test/Raku/{lucas-lehmer-test.raku => lucas-lehmer-test-1.raku} (100%) create mode 100644 Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test-2.raku rename Task/Luhn-test-of-credit-card-numbers/Lua/{luhn-test-of-credit-card-numbers.lua => luhn-test-of-credit-card-numbers-1.lua} (75%) create mode 100644 Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua create mode 100644 Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua create mode 100644 Task/M-bius-function/ANSI-BASIC/m-bius-function.basic create mode 100644 Task/M-bius-function/ASIC/m-bius-function.asic create mode 100644 Task/M-bius-function/JavaScript/m-bius-function-1.js create mode 100644 Task/M-bius-function/JavaScript/m-bius-function-2.js create mode 100644 Task/M-bius-function/K/m-bius-function.k create mode 100644 Task/M-bius-function/Modula-2/m-bius-function.mod2 create mode 100644 Task/M-bius-function/PHP/m-bius-function.php delete mode 100644 Task/M-bius-function/REXX/m-bius-function-1.rexx delete mode 100644 Task/M-bius-function/REXX/m-bius-function-2.rexx create mode 100644 Task/M-bius-function/REXX/m-bius-function.rexx create mode 100644 Task/M-bius-function/RapidQ/m-bius-function.rapidq create mode 100644 Task/MD5-Implementation/JavaScript/md5-implementation.js create mode 100644 Task/Mad-Libs/EasyLang/mad-libs.easy create mode 100644 Task/Mad-Libs/F-Sharp/mad-libs.fs create mode 100644 Task/Mad-Libs/Objeck/mad-libs.objeck create mode 100644 Task/Magic-8-ball/Crystal/magic-8-ball.cr create mode 100644 Task/Magic-constant/ANSI-BASIC/magic-constant.basic create mode 100644 Task/Magic-constant/C/magic-constant.c create mode 100644 Task/Magic-constant/GW-BASIC/magic-constant.basic create mode 100644 Task/Magic-constant/Gambas/magic-constant.gambas create mode 100644 Task/Magic-constant/Modula-2/magic-constant.mod2 create mode 100644 Task/Magic-constant/PHP/magic-constant.php create mode 100644 Task/Magic-constant/REXX/magic-constant.rexx create mode 100644 Task/Magic-constant/Tiny-BASIC/magic-constant.basic create mode 100644 Task/Map-range/ANSI-BASIC/map-range.basic create mode 100644 Task/Map-range/Free-Pascal-Lazarus/map-range-1.pas create mode 100644 Task/Map-range/Free-Pascal-Lazarus/map-range-2.pas create mode 100644 Task/Map-range/GW-BASIC/map-range.basic create mode 100644 Task/Map-range/Modula-2/map-range.mod2 create mode 100644 Task/Map-range/PHP/map-range.php delete mode 100644 Task/Map-range/Pascal/map-range-1.pas delete mode 100644 Task/Map-range/Pascal/map-range-2.pas create mode 100644 Task/Map-range/QBasic/map-range.basic create mode 100644 Task/Map-range/RapidQ/map-range.rapidq create mode 100644 Task/Map-range/TypeScript/map-range.ts create mode 100644 Task/Matrix-transposition/Uiua/matrix-transposition.uiua create mode 100644 Task/Median-filter/Rust/median-filter.rs rename Task/Merge-and-aggregate-datasets/FreeBASIC/{merge-and-aggregate-datasets.basic => merge-and-aggregate-datasets-1.basic} (100%) create mode 100644 Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic create mode 100644 Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo create mode 100644 Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo rename Task/Morse-code/Java/{morse-code.java => morse-code-1.java} (100%) create mode 100644 Task/Morse-code/Java/morse-code-2.java create mode 100644 Task/Move-to-front-algorithm/Zig/move-to-front-algorithm.zig create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-1.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-2.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-3.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-4.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-5.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-6.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-7.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-8.basic create mode 100644 Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-9.basic rename Task/Multi-dimensional-array/C++/{multi-dimensional-array.cpp => multi-dimensional-array-1.cpp} (88%) create mode 100644 Task/Multi-dimensional-array/C++/multi-dimensional-array-2.cpp create mode 100644 Task/Multiplication-tables/Objeck/multiplication-tables.objeck create mode 100644 Task/Munchausen-numbers/J/munchausen-numbers-3.j create mode 100644 Task/Munchausen-numbers/R/munchausen-numbers.r create mode 100644 Task/Munching-squares/Arturo/munching-squares.arturo create mode 100644 Task/Munching-squares/Uiua/munching-squares.uiua create mode 100644 Task/N-queens-problem/Jq/n-queens-problem-6.jq create mode 100644 Task/N-queens-problem/Jq/n-queens-problem-7.jq create mode 100644 Task/N-queens-problem/Python/n-queens-problem-10.py create mode 100644 Task/Natural-sorting/FreeBASIC/natural-sorting.basic create mode 100644 Task/Natural-sorting/JavaScript/natural-sorting-1.js rename Task/Natural-sorting/JavaScript/{natural-sorting.js => natural-sorting-2.js} (100%) create mode 100644 Task/Natural-sorting/Rust/natural-sorting.rs create mode 100644 Task/Natural-sorting/Zig/natural-sorting.zig create mode 100644 Task/Non-decimal-radices-Convert/Crystal/non-decimal-radices-convert.cr create mode 100644 Task/Nonogram-solver/Rust/nonogram-solver.rs create mode 100644 Task/Nth-root/AppleScript/nth-root.applescript delete mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx rename Task/Numerical-integration/Julia/{numerical-integration.jl => numerical-integration-1.jl} (100%) create mode 100644 Task/Numerical-integration/Julia/numerical-integration-2.jl create mode 100644 Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r create mode 100644 Task/OpenWebNet-password/Rust/openwebnet-password.rs create mode 100644 Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr create mode 100644 Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr create mode 100644 Task/P-Adic-numbers-basic/C-sharp/p-adic-numbers-basic.cs create mode 100644 Task/P-Adic-numbers-basic/JavaScript/p-adic-numbers-basic.js create mode 100644 Task/P-Adic-numbers-basic/Rust/p-adic-numbers-basic.rs create mode 100644 Task/P-Adic-numbers-basic/Zig/p-adic-numbers-basic.zig create mode 100644 Task/P-Adic-square-roots/Go/p-adic-square-roots.go create mode 100644 Task/P-Adic-square-roots/JavaScript/p-adic-square-roots.js create mode 100644 Task/P-Adic-square-roots/Rust/p-adic-square-roots.rs create mode 100644 Task/P-Adic-square-roots/Zig/p-adic-square-roots.zig create mode 100644 Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas create mode 100644 Task/Pangram-checker/PascalABC.NET/pangram-checker.pas create mode 100644 Task/Pangram-checker/Uiua/pangram-checker.uiua create mode 100644 Task/Paraffins/PascalABC.NET/paraffins.pas create mode 100644 Task/Parallel-calculations/PascalABC.NET/parallel-calculations.pas create mode 100644 Task/Parse-an-IP-Address/Erlang/parse-an-ip-address.erl create mode 100644 Task/Parse-an-IP-Address/Lua/parse-an-ip-address-1.lua create mode 100644 Task/Parse-an-IP-Address/Lua/parse-an-ip-address-2.lua create mode 100644 Task/Parsing-RPN-calculator-algorithm/PascalABC.NET/parsing-rpn-calculator-algorithm.pas create mode 100644 Task/Parsing-RPN-calculator-algorithm/Zig/parsing-rpn-calculator-algorithm.zig create mode 100644 Task/Parsing-Shunting-yard-algorithm/Zig/parsing-shunting-yard-algorithm.zig create mode 100644 Task/Partition-an-integer-x-into-n-primes/BASIC/partition-an-integer-x-into-n-primes.basic create mode 100644 Task/Partition-an-integer-x-into-n-primes/PascalABC.NET/partition-an-integer-x-into-n-primes.pas create mode 100644 Task/Pascal-matrix-generation/PascalABC.NET/pascal-matrix-generation.pas create mode 100644 Task/Pascals-triangle-Puzzle/PascalABC.NET/pascals-triangle-puzzle.pas create mode 100644 Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs create mode 100644 Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs create mode 100644 Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs create mode 100644 Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas create mode 100644 Task/Pells-equation/PascalABC.NET/pells-equation.pas create mode 100644 Task/Penneys-game/Dart/penneys-game.dart create mode 100644 Task/Perfect-numbers/REXX/perfect-numbers-8.rexx create mode 100644 Task/Perfect-shuffle/PascalABC.NET/perfect-shuffle.pas create mode 100644 Task/Perfect-totient-numbers/PascalABC.NET/perfect-totient-numbers.pas create mode 100644 Task/Perlin-noise/JavaScript/perlin-noise.js create mode 100644 Task/Permutation-test/ALGOL-68/permutation-test.alg create mode 100644 Task/Permutation-test/EasyLang/permutation-test.easy create mode 100644 Task/Permutation-test/PascalABC.NET/permutation-test.pas delete mode 100644 Task/Permutations/C/permutations-4.c create mode 100644 Task/Phrase-reversals/Crystal/phrase-reversals.cr create mode 100644 Task/Pi/Atari-BASIC/pi.basic create mode 100644 Task/Pierpont-primes/REXX/pierpont-primes-1.rexx create mode 100644 Task/Pierpont-primes/REXX/pierpont-primes-2.rexx delete mode 100644 Task/Pierpont-primes/REXX/pierpont-primes.rexx create mode 100644 Task/Playfair-cipher/JavaScript/playfair-cipher.js create mode 100644 Task/Playfair-cipher/Rust/playfair-cipher.rs create mode 100644 Task/Polynomial-regression/Rust/polynomial-regression.rs create mode 100644 Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 create mode 100644 Task/Power-set/Crystal/power-set.cr create mode 100644 Task/Power-set/M2000-Interpreter/power-set.m2000 create mode 100644 Task/Power-set/Refal/power-set.refal create mode 100644 Task/Primality-by-trial-division/Odin/primality-by-trial-division.odin delete mode 100644 Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx delete mode 100644 Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx delete mode 100644 Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx create mode 100644 Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx rename Task/Prime-conspiracy/REXX/{prime-conspiracy.rexx => prime-conspiracy-1.rexx} (100%) create mode 100644 Task/Prime-conspiracy/REXX/prime-conspiracy-2.rexx delete mode 100644 Task/Prime-decomposition/REXX/prime-decomposition-1.rexx delete mode 100644 Task/Prime-decomposition/REXX/prime-decomposition-2.rexx delete mode 100644 Task/Prime-decomposition/REXX/prime-decomposition-3.rexx delete mode 100644 Task/Prime-decomposition/REXX/prime-decomposition-4.rexx create mode 100644 Task/Prime-decomposition/REXX/prime-decomposition.rexx create mode 100644 Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/EasyLang/prime-numbers-whose-neighboring-pairs-are-tetraprimes.easy create mode 100644 Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/PARI-GP/prime-numbers-whose-neighboring-pairs-are-tetraprimes.parigp create mode 100644 Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Python/prime-numbers-whose-neighboring-pairs-are-tetraprimes.py create mode 100644 Task/Primes---allocate-descendants-to-their-ancestors/ALGOL-68/primes---allocate-descendants-to-their-ancestors.alg create mode 100644 Task/Primes---allocate-descendants-to-their-ancestors/EasyLang/primes---allocate-descendants-to-their-ancestors.easy create mode 100644 Task/Primes---allocate-descendants-to-their-ancestors/REXX/primes---allocate-descendants-to-their-ancestors.rexx create mode 100644 Task/Program-termination/OPL/program-termination.opl create mode 100644 Task/Proper-divisors/ALGOL-60/proper-divisors.alg delete mode 100644 Task/Proper-divisors/REXX/proper-divisors-3.rexx delete mode 100644 Task/Proper-divisors/REXX/proper-divisors-4.rexx create mode 100644 Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Rust/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.rs create mode 100644 Task/Pseudo-random-numbers-Middle-square-method/Rust/pseudo-random-numbers-middle-square-method.rs create mode 100644 Task/Pseudo-random-numbers-Splitmix64/Rust/pseudo-random-numbers-splitmix64.rs create mode 100644 Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg create mode 100644 Task/Pythagoras-tree/Maple/pythagoras-tree.maple create mode 100644 Task/QR-decomposition/Rust/qr-decomposition.rs create mode 100644 Task/Quickselect-algorithm/Zig/quickselect-algorithm.zig create mode 100644 Task/Quine/Rust/quine-5.rs create mode 100644 Task/Quine/V-(Vlang)/quine.v create mode 100644 Task/Quine/Zig/quine.zig create mode 100644 Task/Radical-of-an-integer/SETL/radical-of-an-integer.setl create mode 100644 Task/Ramanujan-primes-twins/REXX/ramanujan-primes-twins.rexx create mode 100644 Task/Ramer-Douglas-Peucker-line-simplification/Lua/ramer-douglas-peucker-line-simplification.lua create mode 100644 Task/Ramer-Douglas-Peucker-line-simplification/Modula-2/ramer-douglas-peucker-line-simplification.mod2 delete mode 100644 Task/Random-number-generator-device-/C/random-number-generator-device--5.c delete mode 100644 Task/Random-number-generator-device-/REXX/random-number-generator-device--1.rexx delete mode 100644 Task/Random-number-generator-device-/REXX/random-number-generator-device--2.rexx create mode 100644 Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx create mode 100644 Task/Read-a-configuration-file/XPL0/read-a-configuration-file.xpl0 create mode 100644 Task/Read-entire-file/OoRexx/read-entire-file-4.rexx delete mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx delete mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx delete mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx delete mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx delete mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx create mode 100644 Task/Reflection-Get-source/C-sharp/reflection-get-source.cs create mode 100644 Task/Rendezvous/Rust/rendezvous.rs create mode 100644 Task/Repeat-a-string/Excel/repeat-a-string.excel create mode 100644 Task/Resistor-mesh/Rust/resistor-mesh.rs rename Task/Reverse-a-string/Common-Lisp/{reverse-a-string.lisp => reverse-a-string-1.lisp} (100%) create mode 100644 Task/Reverse-a-string/Common-Lisp/reverse-a-string-2.lisp create mode 100644 Task/Reverse-a-string/Excel/reverse-a-string.excel create mode 100644 Task/Roman-numerals-Decode/Objeck/roman-numerals-decode.objeck create mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/Objeck/rosetta-code-find-unimplemented-tasks.objeck create mode 100644 Task/Rosetta-Code-Fix-code-tags/FreeBASIC/rosetta-code-fix-code-tags.basic create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/FreeBASIC/rosetta-code-rank-languages-by-popularity.basic create mode 100644 Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 create mode 100644 Task/Run-length-encoding/Crystal/run-length-encoding.cr create mode 100644 Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 create mode 100644 Task/Run-length-encoding/Miranda/run-length-encoding.miranda create mode 100644 Task/Run-length-encoding/Refal/run-length-encoding.refal create mode 100644 Task/Runge-Kutta-method/Odin/runge-kutta-method.odin create mode 100644 Task/Runge-Kutta-method/Ol/runge-kutta-method.ol create mode 100644 Task/Runge-Kutta-method/Scheme/runge-kutta-method.scm create mode 100644 Task/SHA-1/JavaScript/sha-1.js create mode 100644 Task/SHA-1/Zig/sha-1.zig create mode 100644 Task/SQL-based-authentication/FreeBASIC/sql-based-authentication.basic delete mode 100644 Task/Semiprime/REXX/semiprime-3.rexx delete mode 100644 Task/Semiprime/REXX/semiprime-4.rexx create mode 100644 Task/Semordnilap/R/semordnilap.r create mode 100644 Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg delete mode 100644 Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx delete mode 100644 Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-2.rexx create mode 100644 Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division.rexx create mode 100644 Task/Sequence-of-primorial-primes/REXX/sequence-of-primorial-primes.rexx create mode 100644 Task/Sequence:-smallest-number-with-exactly-n-divisors/C-sharp/sequence:-smallest-number-with-exactly-n-divisors.cs create mode 100644 Task/Set-puzzle/JavaScript/set-puzzle.js create mode 100644 Task/Shoelace-formula-for-polygonal-area/Rust/shoelace-formula-for-polygonal-area.rs delete mode 100644 Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx delete mode 100644 Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx create mode 100644 Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx create mode 100644 Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 create mode 100644 Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku create mode 100644 Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic create mode 100644 Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math create mode 100644 Task/Sleep/JavaScript/sleep-1.js create mode 100644 Task/Sleep/JavaScript/sleep-2.js create mode 100644 Task/Sleep/JavaScript/sleep-3.js delete mode 100644 Task/Sleep/JavaScript/sleep.js create mode 100644 Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js create mode 100644 Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs create mode 100644 Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig create mode 100644 Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs create mode 100644 Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg create mode 100644 Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy create mode 100644 Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js create mode 100644 Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs create mode 100644 Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg create mode 100644 Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy create mode 100644 Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl create mode 100644 Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr delete mode 100644 Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx delete mode 100644 Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx create mode 100644 Task/Sort-numbers-lexicographically/Crystal/sort-numbers-lexicographically.cr create mode 100644 Task/Sort-numbers-lexicographically/R/sort-numbers-lexicographically.r create mode 100644 Task/Sort-three-variables/Crystal/sort-three-variables.cr create mode 100644 Task/Sort-three-variables/XPL0/sort-three-variables.xpl0 create mode 100644 Task/Sorting-Algorithms-Circle-Sort/Crystal/sorting-algorithms-circle-sort.cr create mode 100644 Task/Sorting-algorithms-Bead-sort/Rust/sorting-algorithms-bead-sort.rs create mode 100644 Task/Sorting-algorithms-Bubble-sort/Crystal/sorting-algorithms-bubble-sort.cr delete mode 100644 Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx create mode 100644 Task/Sorting-algorithms-Patience-sort/EasyLang/sorting-algorithms-patience-sort.easy create mode 100644 Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs create mode 100644 Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig delete mode 100644 Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-6.rexx create mode 100644 Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js rename Task/Sorting-algorithms-Radix-sort/Rust/{sorting-algorithms-radix-sort.rs => sorting-algorithms-radix-sort-1.rs} (80%) create mode 100644 Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-2.rs create mode 100644 Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-3.rs create mode 100644 Task/Sorting-algorithms-Strand-sort/FreeBASIC/sorting-algorithms-strand-sort.basic create mode 100644 Task/Sorting-algorithms-Strand-sort/M2000-Interpreter/sorting-algorithms-strand-sort.m2000 create mode 100644 Task/Sorting-algorithms-Strand-sort/Rust/sorting-algorithms-strand-sort.rs create mode 100644 Task/Sorting-algorithms-Strand-sort/Zig/sorting-algorithms-strand-sort.zig create mode 100644 Task/Spelling-of-ordinal-numbers/JavaScript/spelling-of-ordinal-numbers.js create mode 100644 Task/Sphenic-numbers/Mathematica/sphenic-numbers.math create mode 100644 Task/Spiral-matrix/Uiua/spiral-matrix.uiua rename Task/Split-a-character-string-based-on-change-of-character/C/{split-a-character-string-based-on-change-of-character.c => split-a-character-string-based-on-change-of-character-1.c} (100%) create mode 100644 Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character-2.c create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Crystal/split-a-character-string-based-on-change-of-character.cr create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.l create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-3.rs create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-4.rs create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-5.rs create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-6.rs create mode 100644 Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-7.rs create mode 100644 Task/Square-form-factorization/Python/square-form-factorization.py create mode 100644 Task/Stack-traces/Crystal/stack-traces.cr create mode 100644 Task/Stack-traces/Uxntal/stack-traces.uxnatl create mode 100644 Task/Stack/Ballerina/stack-1.ballerina create mode 100644 Task/Stack/Ballerina/stack-2.ballerina create mode 100644 Task/State-name-puzzle/JavaScript/state-name-puzzle.js create mode 100644 Task/Statistics-Basic/Ballerina/statistics-basic.ballerina create mode 100644 Task/Steffensens-method/Rust/steffensens-method.rs create mode 100644 Task/Strassens-algorithm/C++/strassens-algorithm.cpp create mode 100644 Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs create mode 100644 Task/Strassens-algorithm/Java/strassens-algorithm.java create mode 100644 Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js create mode 100644 Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js create mode 100644 Task/Strassens-algorithm/Rust/strassens-algorithm.rs create mode 100644 Task/Strassens-algorithm/Zig/strassens-algorithm.zig create mode 100644 Task/Stream-merge/Rust/stream-merge.rs create mode 100644 Task/String-length/Crystal/string-length-3.cr create mode 100644 Task/String-length/Uxntal/string-length.uxnatl create mode 100644 Task/String-prepend/Crystal/string-prepend.cr create mode 100644 Task/String-prepend/OPL/string-prepend.opl create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string-4.java create mode 100644 Task/Strip-a-set-of-characters-from-a-string/M2000-Interpreter/strip-a-set-of-characters-from-a-string.m2000 create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Objeck/strip-a-set-of-characters-from-a-string.objeck create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string.odin create mode 100644 Task/Strip-a-set-of-characters-from-a-string/R/strip-a-set-of-characters-from-a-string.r create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-4.rs create mode 100644 Task/Strip-comments-from-a-string/APL/strip-comments-from-a-string.apl create mode 100644 Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.l create mode 100644 Task/Strip-comments-from-a-string/Refal/strip-comments-from-a-string.refal create mode 100644 Task/Strip-comments-from-a-string/SETL/strip-comments-from-a-string.setl create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-1.cpp rename Task/Strip-whitespace-from-a-string-Top-and-tail/C++/{strip-whitespace-from-a-string-top-and-tail.cpp => strip-whitespace-from-a-string-top-and-tail-2.cpp} (54%) create mode 100644 Task/Substitution-cipher/JavaScript/substitution-cipher.js create mode 100644 Task/Substring/K/substring.k create mode 100644 Task/Sudan-function/Rust/sudan-function.rs rename Task/Sum-digits-of-an-integer/Nu/{sum-digits-of-an-integer.nu => sum-digits-of-an-integer-1.nu} (100%) create mode 100644 Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer-2.nu create mode 100644 Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-1.alg create mode 100644 Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-2.alg delete mode 100644 Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg create mode 100644 Task/Sum-of-a-series/S-BASIC/sum-of-a-series.basic create mode 100644 Task/Sum-of-a-series/TypeScript/sum-of-a-series.ts create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Quackery/sum-of-elements-below-main-diagonal-of-matrix.quackery create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Zig/sutherland-hodgman-polygon-clipping.zig create mode 100644 Task/Take-notes-on-the-command-line/Crystal/take-notes-on-the-command-line.cr rename Task/Tau-number/REXX/{tau-number.rexx => tau-number-1.rexx} (100%) create mode 100644 Task/Tau-number/REXX/tau-number-2.rexx create mode 100644 Task/Terminal-control-Clear-the-screen/X86-64-Assembly/terminal-control-clear-the-screen.x86-64 create mode 100644 Task/Text-processing-1/XPL0/text-processing-1.xpl0 create mode 100644 Task/Text-processing-2/ALGOL-68/text-processing-2.alg create mode 100644 Task/Text-processing-2/FreeBASIC/text-processing-2.basic create mode 100644 Task/Text-processing-2/XPL0/text-processing-2.xpl0 create mode 100644 Task/Thieles-interpolation-formula/Fortran/thieles-interpolation-formula.f create mode 100644 Task/Thue-Morse/Zig/thue-morse.zig create mode 100644 Task/Tic-tac-toe/APL/tic-tac-toe-1.apl create mode 100644 Task/Tic-tac-toe/APL/tic-tac-toe-2.apl create mode 100644 Task/Tic-tac-toe/Factor/tic-tac-toe-1.factor create mode 100644 Task/Tic-tac-toe/Factor/tic-tac-toe-2.factor create mode 100644 Task/Tic-tac-toe/J/tic-tac-toe-4.j create mode 100644 Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js delete mode 100644 Task/Time-a-function/REXX/time-a-function-3.rexx delete mode 100644 Task/Time-a-function/REXX/time-a-function-4.rexx rename Task/Tokenize-a-string-with-escaping/Lua/{tokenize-a-string-with-escaping.lua => tokenize-a-string-with-escaping-1.lua} (67%) create mode 100644 Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua create mode 100644 Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua create mode 100644 Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel create mode 100644 Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel create mode 100644 Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js create mode 100644 Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs create mode 100644 Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig delete mode 100644 Task/Totient-function/REXX/totient-function-1.rexx delete mode 100644 Task/Totient-function/REXX/totient-function-2.rexx delete mode 100644 Task/Totient-function/REXX/totient-function-3.rexx create mode 100644 Task/Totient-function/REXX/totient-function.rexx create mode 100644 Task/Towers-of-Hanoi/Applesoft-BASIC/towers-of-hanoi.basic create mode 100644 Task/Towers-of-Hanoi/Ballerina/towers-of-hanoi.ballerina create mode 100644 Task/Towers-of-Hanoi/Excel/towers-of-hanoi-3.excel delete mode 100644 Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx rename Task/Trigonometric-functions/REXX/{trigonometric-functions-2.rexx => trigonometric-functions.rexx} (93%) create mode 100644 Task/Truncatable-primes/Ballerina/truncatable-primes.ballerina rename Task/Truncatable-primes/REXX/{truncatable-primes.rexx => truncatable-primes-1.rexx} (100%) create mode 100644 Task/Truncatable-primes/REXX/truncatable-primes-2.rexx delete mode 100644 Task/Twin-primes/REXX/twin-primes-1.rexx delete mode 100644 Task/Twin-primes/REXX/twin-primes-2.rexx create mode 100644 Task/Twin-primes/REXX/twin-primes.rexx create mode 100644 Task/Two-bullet-roulette/Quackery/two-bullet-roulette.quackery create mode 100644 Task/UTF-8-encode-and-decode/K/utf-8-encode-and-decode.k create mode 100644 Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic create mode 100644 Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic create mode 100644 Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js create mode 100644 Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs delete mode 100644 Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx delete mode 100644 Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx create mode 100644 Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx create mode 100644 Task/Unicode-strings/Tcl/unicode-strings.tcl create mode 100644 Task/Unicode-variable-names/Ballerina/unicode-variable-names.ballerina create mode 100644 Task/Unicode-variable-names/Odin/unicode-variable-names.odin create mode 100644 Task/Unicode-variable-names/Scheme/unicode-variable-names.scm create mode 100644 Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy create mode 100644 Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua create mode 100644 Task/User-input-Text/JavaScript/user-input-text-3.js create mode 100644 Task/User-input-Text/OPL/user-input-text.opl create mode 100644 Task/Verhoeff-algorithm/JavaScript/verhoeff-algorithm.js create mode 100644 Task/Verhoeff-algorithm/Rust/verhoeff-algorithm.rs create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/JavaScript/vigen-re-cipher-cryptanalysis.js create mode 100644 Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f create mode 100644 Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js create mode 100644 Task/Wagstaff-primes/Mathematica/wagstaff-primes.math create mode 100644 Task/Wasteful-equidigital-and-frugal-numbers/ALGOL-68/wasteful-equidigital-and-frugal-numbers.alg create mode 100644 Task/Wasteful-equidigital-and-frugal-numbers/EasyLang/wasteful-equidigital-and-frugal-numbers.easy create mode 100644 Task/Wasteful-equidigital-and-frugal-numbers/Python/wasteful-equidigital-and-frugal-numbers.py rename Task/Wieferich-primes/REXX/{wieferich-primes.rexx => wieferich-primes-1.rexx} (100%) create mode 100644 Task/Wieferich-primes/REXX/wieferich-primes-2.rexx create mode 100644 Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx create mode 100644 Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-2.rexx delete mode 100644 Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n.rexx create mode 100644 Task/Word-frequency/Emacs-Lisp/word-frequency.l create mode 100644 Task/Word-frequency/Nu/word-frequency.nu create mode 100644 Task/Word-ladder/FreeBASIC/word-ladder.basic create mode 100644 Task/Wordiff/JavaScript/wordiff.js create mode 100644 Task/Write-entire-file/Odin/write-entire-file.odin create mode 100644 Task/Write-float-arrays-to-a-text-file/AppleScript/write-float-arrays-to-a-text-file.applescript create mode 100644 Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k create mode 100644 Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs create mode 100644 Task/Y-combinator/F-Sharp/y-combinator-5.fs create mode 100644 Task/Y-combinator/Zig/y-combinator.zig delete mode 100644 Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx delete mode 100644 Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx create mode 100644 Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx create mode 100644 Task/Zebra-puzzle/JavaScript/zebra-puzzle.js create mode 100644 Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua diff --git a/Lang/8080-Assembly/Loops-Infinite b/Lang/8080-Assembly/Loops-Infinite new file mode 120000 index 0000000000..f6336ebca0 --- /dev/null +++ b/Lang/8080-Assembly/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/8080-Assembly \ No newline at end of file diff --git a/Lang/8080-Assembly/Run-length-encoding b/Lang/8080-Assembly/Run-length-encoding new file mode 120000 index 0000000000..bc3ed9076c --- /dev/null +++ b/Lang/8080-Assembly/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/8080-Assembly \ No newline at end of file diff --git a/Lang/8086-Assembly/00-LANG.txt b/Lang/8086-Assembly/00-LANG.txt index 7cf10761fa..9120d12d87 100644 --- a/Lang/8086-Assembly/00-LANG.txt +++ b/Lang/8086-Assembly/00-LANG.txt @@ -4,13 +4,13 @@ ===Segmented Memory=== The 8086 uses a segmented memory model, similar to the Super Nintendo Entertainment System. Unlike banked memory models used in the Commodore 64 and late NES games, segment addresses are held in segment registers. These segment registers are 16 bit and get left-shifted by 4 and added to the pointer register of interest to determine the memory address to look up. The 8086 has four in total, but only the DS and ES registers can be used by the programmer. (The other two work with the stack pointer and instruction pointer, and are loaded for you.) On the 8086, you can only load segment registers with the value in a data register, or with the POP command. So first you must load a segment into a data register, THEN into a segment register. -;This is NOT valid code! +;This is NOT valid code! mov ds, @data ;you're trying to move the data segment location directly into DS. You can't! ;This is the proper way: mov ax, @data ;I chose AX but I could have used BX, CX, or DX. -mov ds, ax ;load DS with the data segment. +mov ds, ax ;load DS with the data segment. It's important to remember the subtle distinction between a ''segment'' and a ''segment register.'' Your program might have labeled ''segments'' such as .data and .code, but in order to properly read from/write to these sections you'll need to load their memory locations into ''segment registers.'' @@ -18,17 +18,17 @@ It's important to remember the subtle distinction between a ''segment'' and a '' There are four data registers: AX, BX, CX, and DX. While most commands can use any of them, some only work with particular data registers. System calls in particular are very specific about which registers can be used for what. On [[MS-DOS]], the AX register is used for selecting the desired interrupt to use with the INT command. Each data register is 16-bit, but has two eight bit halves ending in H or L, e.g. AH, AL. Instructions can be executed using the whole register or just half of it. -mov ax, 1000h ;move 1000h into AX, or equivalently, move 10h into AH and 00h into AL. +mov ax, 1000h ;move 1000h into AX, or equivalently, move 10h into AH and 00h into AL. Moving a value smaller than 16 bits into ?X is the same as moving it into ?L, and moving 0 into ?H. (? represents the data register of your choice. They are all the same in this regard.) -mov ax,0030h +mov ax,0030h ;is the same as: mov al, 30h -mov ah, 0h +mov ah, 0h Commands that alter the contents of a single register will not affect the other half. -mov ax,00FFh -inc al +mov ax,00FFh +inc al If we had executed INC AX, then AX would have been incremented to 0x100. Since we only incremented AL, only AL was incremented in this case, and AH '''still equals 0x00!''' Generally speaking, the 8086's registers serve the following purposes: @@ -42,24 +42,24 @@ When writing to or reading from consecutive sections of memory, it is helpful to The syntax for offsetting an index register will vary depending on your assembler. Many assemblers will often accept multiple different ways of writing it, and it comes down to personal preference. -mov si, offset MyArray +mov si, offset MyArray mov bx,2 mov al,[bx+si] ;loads decimal 30 into AL MyArray: -byte 10,20,30,40,50 +byte 10,20,30,40,50 ===The Stack=== As with [[Z80 Assembly]], you can't push 8-bit registers onto the stack. For data registers, you have to push/pop both halves. -;This is valid code. +;This is valid code. push ax push bx pop bx pop ax -;This is NOT valid code. +;This is NOT valid code. push ah push al push bh @@ -69,14 +69,14 @@ push bl pop bl pop bh pop al -pop ah +pop ah As with all processors that use a stack, if you push one or more registers and want to restore the backed-up values correctly, you must pop them in the reverse order. You can pop them out of order on purpose to swap registers around. In fact, this is a quick way to move the segment from DS into ES, or vice-versa: -push DS -pop ES ;you can't do "mov es, ds" but you can do this! +push DS +pop ES ;you can't do "mov es, ds" but you can do this! The proper way to use the stack to preserve registers: - + call foo mov ax,4C00h @@ -91,7 +91,7 @@ push cx pop cx pop bx pop ax -ret +ret If one of the push/pop commands in the routine above were missing, the RET instruction would not properly return to where it came from. As long as you pop at the end the same number of registers you pushed at the start, the stack is "balanced" and your return instruction will return correctly. This is because RET is actually POP IP (IP being the instruction pointer, which you can think of as what "line" of code the CPU is on.) The CPU assumes the top of the stack is the correct place to return to, but has no way of actually verifying it. If the function you just wrote causes the CPU to crash or jump to a completely different part of the code, there's a good chance you might have forgotten to balance the stack properly. @@ -107,40 +107,40 @@ One other caveat to mention: On early IBM PCs and compatibles, the 8087 was not ===Looping Constructs=== The 8086 has a lot more of these than most CPUs. The most obvious one is LOOP, which will subtract 1 from CX, then jump back to a specified label if CX is nonzero after the subtraction. If CX becomes zero after subtracting 1, then no jump will occur and the instruction pointer simply moves to the next instruction. -mov cx,0100h ;set the loop counter's starting value. This must be outside the loop, otherwise you'll loop forever! +mov cx,0100h ;set the loop counter's starting value. This must be outside the loop, otherwise you'll loop forever! foo: ;; your code that you want to loop goes here -loop foo +loop foo It's important not to alter CX inside the loop. It's easy to make a mistake like this if you're in a hurry: -foobar: +foobar: mov cx,1000h ;your code goes here -loop foobar +loop foobar It may not be obvious at first but the above loop will never end. CX decrements to 0x0FFF with the LOOP instruction but the mov cx,1000h was mistakenly placed ''inside'' the loop, resetting the loop counter back to 0x1000, which means no progress is really being made. The correct way to do this is to set the starting loop counter '''outside''' the loop, like so: -mov cx,1000h +mov cx,1000h foobar: ;your code goes here -loop foobar +loop foobar Sometimes you'll have to change CX during a loop, like if you want to do bit shifts with a shift amount other than 1, for example. There's a simple fix - use the stack to stash and retrieve the loop counter. -mov cx,0100h +mov cx,0100h foo: push cx mov cl,2 ror ax,cl ;starting with the 80186 you don't need CL for bit shifting. pop cx -loop foo +loop foo By using PUSH CX and POP CX, you can temporarily use CX for something else, as long as you restore it before the LOOP instruction. You can use other registers as loop counters as well, but not with the LOOP instruction - it's hardcoded to only work with CX. But you can do this: -mov dx,0100h +mov dx,0100h baz: ;your code goes here dec dx @@ -148,7 +148,7 @@ jnz baz ; A minor note for advanced programmers: ; If you're expecting the flags to be in a particular state based on the loop body, tough luck! ; They'll only reflect the decrement of DX from 1 to 0 at this point in the code. -; LOOP doesn't change the flags, which makes it more useful for loops meant to compare things. +; LOOP doesn't change the flags, which makes it more useful for loops meant to compare things. Another frequently used looping construct is REP. REP can be combined with certain instructions to repeat that instruction until CX equals zero. However, unlike LOOP, which can be used to repeat a block of instructions, REP can only repeat one. It doesn't work on all instructions, only the "string" instructions which operate on a block of memory. Typically these include MOVSB, LODSB, STOSB, CMPSB, and SCASB (each has a variant that ends in W instead of B, for 16-bit data.) There are also REPZ and REPNZ, which stand for "Repeat if Zero" and "Repeat if Nonzero" respectively. These two only work properly with CMPSB and SCASB, as MOVSB, LODSB, STOSB do not affect the flags. (The CPU doesn't detect whether CX equals zero using the flags, as the flags never reflect this equality to zero like you would expect.) diff --git a/Lang/ALGOL-60/Additive-primes b/Lang/ALGOL-60/Additive-primes new file mode 120000 index 0000000000..360a570784 --- /dev/null +++ b/Lang/ALGOL-60/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Largest-proper-divisor-of-n b/Lang/ALGOL-60/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..bd5f1adbca --- /dev/null +++ b/Lang/ALGOL-60/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body b/Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..b6ef8c8c0c --- /dev/null +++ b/Lang/ALGOL-60/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Proper-divisors b/Lang/ALGOL-60/Proper-divisors new file mode 120000 index 0000000000..7bb12e66dd --- /dev/null +++ b/Lang/ALGOL-60/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Sequence-of-primes-by-trial-division b/Lang/ALGOL-60/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..b95a2ebdcc --- /dev/null +++ b/Lang/ALGOL-60/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-68/00-LANG.txt b/Lang/ALGOL-68/00-LANG.txt index 875b4abf89..d037dbcad0 100644 --- a/Lang/ALGOL-68/00-LANG.txt +++ b/Lang/ALGOL-68/00-LANG.txt @@ -68,209 +68,11 @@ A syntax chart is available [http://www.softwarepreservation.org/projects/ALGOL/ *Dec. 1968: Report on the Algorithmic Language ALGOL 68 - Offprint from Numerische Mathematik, 14, 79-218 (1969); Springer-Verlag. - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck and C.H.A. Koster. *Sep 1973: Revised Report on the Algorithmic Language Algol 68 - Springer-Verlag 1976 - Edited by: A. van Wijngaarden, B.J. Mailloux, J.E.L. Peck, C.H.A. Koster, M. Sintzoff, C.H. Lindsey, L.G.L.T. Meertens and R.G. Fisker. ==Coding style of samples, alphabets and stropping== -Click "Expand" for more details. -
-
- -Many of the code samples provided here have a leading main:( and a matching ) at the end. These are not actually required in the language, but are included so as to highlight the main routine. - -On some compilers, it may be necessary to include appropriate "job cards" -or preludes in order for the programs to compile successfully. Hopefully -not too much else is required. Examples: -{|border="1" style="border-collapse: collapse; border: 5px double grey;" align="center" -|| Brief Algol68 -|| Algol68 as in rosettacode -|| Actual ELLA Algol 68RS code -|- -|| - print(("Hello, world!",new line)) -|| - main:( - print(("Hello, world!",new line)) - ) -|| - PROGRAM helloworld CONTEXT VOID - USE standard - BEGIN - print(("Hello, world!", new line)) - END - FINISH -|} -

'''Alphabets''' -

-Notionally, Algol 68 source is written in two alphabets. The reserved words, mode indicants (type names) and operators that are non-symbolic (.e.g. '''and''', '''or''', ...) are generally referred to as "bold words" and usually shown in a bold font in literature. Words that are identifiers (used for "variable" names, procedure names, structure member names, ...) are in a separate, non-bold font.
-The [https://www.softwarepreservation.org/projects/ALGOL/manual/a68s.txt/view Manual for CMU ALGOL 68S (on softwarepreservation.org)] refers to the non-bold words as being in timid face. -

'''Examples of different program representations''' -

-At the time when ALGOL 68 was defined some predominant computers had -24 or 36 bit words, with 6 bit character sets. Hence it was desirable that -ALGOL 68 should be able to run on machines with only uppercase. -As multiple fonts were generally unavailable, a method of identifying the bold words was required.
-The official spec provided for different representations of the same -program. -Quote stropping (enclosing the bold words in single quotes) -and Point stropping (preceeding the bold words with a dot) -were used.
-A variant of Point stropping called RES stropping was also defined. -In RES stropping some language-defined bold words are not preceded by a dot.
-A pragmatic comment may have been required to indicate which -stropping convention was to be used, as in some of the examples below.
-Upper stropping (representing the bold words by upper case and -non-bold words in lower case) was introduced by Algol 68R.
-Upper stropping is used by Algol 68RS and is one of the options for Algol 68G.
-Rutgers ALGOL 68 uses quote stropping.
-Most of the samples on Rosetta Code use Upper stropping.

-Examples (pragmatic comments to set the stropping regime not shown): -{|border="1" style="border-collapse: collapse; border: 2px double grey;" align="left" -|| Algol68 as typically published - '''mode''' '''xint''' = '''int'''; - '''xint''' sum sq:=0; - '''for''' i '''while''' - sum sq≠70×70 - '''do''' - sum sq+:=i↑2 - '''od''' -|| QUOTE stropping (similar to wiki) - 'mode' 'xint' = 'int'; - 'xint' sum sq:=0; - 'for' i 'while' - sum sq≠70×70 - 'do' - sum sq+:=i↑2 - 'od' -|| POINT stropping - .MODE .XINT = .INT; - .XINT SUM SQ:=0; - .FOR I .WHILE - SUM SQ .NE 70*70 - .DO - SUM SQ .PLUSAB I .UP 2 - .OD -|| RES stropping - mode .xint = int; - .xint sum sq:=0; - for i while - sum sq≠70×70 - do - sum sq+:=i↑2 - od -|| Upper stropping - MODE XINT = INT; - XINT sum sq:=0; - FOR i WHILE - sum sq /= 70*70 - DO - sum sq PLUSAB i UP 2 - OD -|} - -
+See [[ALGOL 68 Representation]]. == Coercion (casting) == -ALGOL 68 has a hierarchy of contexts which determine which kind of coercions are available at a particular point in the program. -
-Click "Expand" for more details. -
-
- -These contexts are: -{|class="wikitable" -!rowspan=2| N
-a
-m
-e -!rowspan=2| Context location -!colspan=5| Coercions available in this context -!rowspan=2| Coercion examples -|- -|bgcolor=aaaaff|Soft -|bgcolor=aaeeaa|Weak -|bgcolor=ffee99|Meek -|bgcolor=ffcc99|Firm -|bgcolor=ffcccc|Strong -|- -!S
-t
-r
-o
-n
-g -||Right hand side of: -* Identity-declarations, as "~" in: REAL x = ~ -* Initialisations, as "~" in: REAL x := ~ -Also: -* Actual-parameters of calls, as "~" in:PROC: sin(~) -* Enclosed clauses of casts, as "~" in: REAL(~) -* Units of routine-texts -* Statements yielding VOID -* All parts (but one) of a balanced clause -* One side of an identity relation, as "~" in: ~ IS ~ -|bgcolor=aaaaff rowspan=4 width="50px"| deproc- eduring -|bgcolor=aaeeaa rowspan=3 width="50px"| all '''soft''' then weak deref- erencing -|bgcolor=ffee99 rowspan=2 width="50px"| all '''weak''' then deref- erencing -|bgcolor=ffcc99 rowspan=1 width="50px"| all '''meek''' then uniting -|bgcolor=ffcccc width="50px"| all '''firm''' then widening, rowing and voiding -|colspan=1 bgcolor=ffcccc| -Widening occurs if there is no loss of precision. For example: An INT will be coerced to a REAL, and a REAL will be coerced to a LONG REAL. But not vice-versa. Examples: -INT to LONG INT -INT to REAL -REAL to COMPL -BITS to []BOOL -BYTES to STRING -A variable can also be coerced (rowed) to an array of length 1. - -For example: -INT to [1]INT -REAL to [1]REAL etc -|- -!F
-i
-r
-m -|| -*Operands of formulas as "~" in:OP: ~ * ~ -*Parameters of transput calls -|colspan=3 bgcolor=ffcc99| Example: -UNION(INT,REAL) var := 1 -|- -!M
-e
-e
-k -|| -* Trimscripts (yielding INT) -* Enquiries: e.g. as "~" in the following -IF ~ THEN ... FI and -FROM ~ BY ~ TO ~ WHILE ~ DO ... OD etc -* Primaries of calls (e.g. sin in sin(x)) -|colspan=4 bgcolor=ffee99|Examples: -REF REF BOOL to BOOL -REF REF REF INT to INT -|- -!W
-e
-a
-k -|| -* Primaries of slices, as in "~" in: ~[1:99] -* Secondaries of selections, as "~" in: value OF ~ -|colspan=5 bgcolor=aaeeaa|Examples: -REF BOOL to REF BOOL -REF REF INT to REF INT -REF REF REF REAL to REF REAL -REF REF REF REF STRUCT to REF STRUCT -|- -!S
-o
-f
-t -|| The LHS of assignments, as "~" in: ~ := ... -|colspan=6 bgcolor=aaaaff| Example: -* deproceduring of: PROC REAL random: e.g. random -|} -For more details about Primaries and Secondaries refer to [[Operator_precedence#ALGOL_68|Operator precedence]]. - -
+ALGOL 68 has a hierarchy of contexts which determine which kind of coercions are available at a particular point in the program.
+See [[:Category:ALGOL_68_Coercions|ALGOL 68 Coercions]] for more details. ==See also== *[[Web 68]] @@ -284,13 +86,14 @@ For more details about Primaries and Secondaries refer to [[Operator_precedence# * [https://en.wikipedia.org/wiki/S3_(programming_language) S3 for ICL 2900] == Library code used in Rosetta Code samples == -[https://rosettacode.org/wiki/ALGOL_68/prelude Various (including the standard prelude)]
-
-[https://rosettacode.org/wiki/Category:ALGOL_68-files File related]
-[https://rosettacode.org/wiki/Category:ALGOL_68-l-system L-System related]
-[https://rosettacode.org/wiki/Category:ALGOL_68-primes Prime related]
-[https://rosettacode.org/wiki/Category:ALGOL_68-rows Row (array) related]
-[https://rosettacode.org/wiki/Category:ALGOL_68-sort Sorting related]
+* [[ALGOL_68/prelude|Various (including the standard prelude)]] +* +* [[:Category:ALGOL_68-bits|bit-manipulation related]] +* [[:Category:ALGOL_68-files|File related]] +* [[:Category:ALGOL_68-l-system|L-System related]] +* [[:Category:ALGOL_68-primes|Prime related]] +* [[:Category:ALGOL_68-rows|Row (array) related]] +* [[:Category:ALGOL_68-sort|Sorting related]] == Tools == [[Syntax_highlighting_using_Mediawiki_formatting#ALGOL 68|Format an upper-stropped Algol 68 source with Mediawiki markup]]
diff --git a/Lang/ALGOL-68/Elliptic-curve-arithmetic b/Lang/ALGOL-68/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..88681d69e9 --- /dev/null +++ b/Lang/ALGOL-68/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Permutation-test b/Lang/ALGOL-68/Permutation-test new file mode 120000 index 0000000000..1a8b7f20df --- /dev/null +++ b/Lang/ALGOL-68/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors b/Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..9bf6ed3e36 --- /dev/null +++ b/Lang/ALGOL-68/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Pythagoras-tree b/Lang/ALGOL-68/Pythagoras-tree new file mode 120000 index 0000000000..8c304d8b68 --- /dev/null +++ b/Lang/ALGOL-68/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Solve-a-Numbrix-puzzle b/Lang/ALGOL-68/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..14e9e80e97 --- /dev/null +++ b/Lang/ALGOL-68/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Solve-the-no-connection-puzzle b/Lang/ALGOL-68/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..0ffda5f1f9 --- /dev/null +++ b/Lang/ALGOL-68/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Text-processing-2 b/Lang/ALGOL-68/Text-processing-2 new file mode 120000 index 0000000000..124fe3bf6c --- /dev/null +++ b/Lang/ALGOL-68/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers b/Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..6de9ddaea1 --- /dev/null +++ b/Lang/ALGOL-68/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-M/Additive-primes b/Lang/ALGOL-M/Additive-primes new file mode 120000 index 0000000000..974f9484e7 --- /dev/null +++ b/Lang/ALGOL-M/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/ALGOL-M \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Levenshtein-distance b/Lang/ANSI-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..92b553d536 --- /dev/null +++ b/Lang/ANSI-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/M-bius-function b/Lang/ANSI-BASIC/M-bius-function new file mode 120000 index 0000000000..f786d2b99e --- /dev/null +++ b/Lang/ANSI-BASIC/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Magic-constant b/Lang/ANSI-BASIC/Magic-constant new file mode 120000 index 0000000000..7d2184182c --- /dev/null +++ b/Lang/ANSI-BASIC/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Map-range b/Lang/ANSI-BASIC/Map-range new file mode 120000 index 0000000000..829dfc3a26 --- /dev/null +++ b/Lang/ANSI-BASIC/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/ANSI-BASIC \ No newline at end of file diff --git a/Lang/APL/Loops-Infinite b/Lang/APL/Loops-Infinite new file mode 120000 index 0000000000..0f3ec957d2 --- /dev/null +++ b/Lang/APL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/APL \ No newline at end of file diff --git a/Lang/APL/Sort-a-list-of-object-identifiers b/Lang/APL/Sort-a-list-of-object-identifiers new file mode 120000 index 0000000000..400cb9fc60 --- /dev/null +++ b/Lang/APL/Sort-a-list-of-object-identifiers @@ -0,0 +1 @@ +../../Task/Sort-a-list-of-object-identifiers/APL \ No newline at end of file diff --git a/Lang/APL/Strip-comments-from-a-string b/Lang/APL/Strip-comments-from-a-string new file mode 120000 index 0000000000..ff78e120aa --- /dev/null +++ b/Lang/APL/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/APL \ No newline at end of file diff --git a/Lang/APL/Tic-tac-toe b/Lang/APL/Tic-tac-toe new file mode 120000 index 0000000000..58bb681d1c --- /dev/null +++ b/Lang/APL/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/APL \ No newline at end of file diff --git a/Lang/ASIC/M-bius-function b/Lang/ASIC/M-bius-function new file mode 120000 index 0000000000..7848f34d54 --- /dev/null +++ b/Lang/ASIC/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/ASIC \ No newline at end of file diff --git a/Lang/Action-/00-LANG.txt b/Lang/Action-/00-LANG.txt index b37eb47c8f..3811c3c636 100644 --- a/Lang/Action-/00-LANG.txt +++ b/Lang/Action-/00-LANG.txt @@ -4,7 +4,7 @@ }} Action! is a language written by Clinton Parker and published by Optimized Sytems Software (OSS) for the Atari 8-bit line of home computers. It is related to ALGOL and optimized for single-pass compilation to 6502 code. - +A manual for the language is available at https://seriouscomputerist.atariverse.com/media/pdf/manual/OSS%20OS-A+%20-%20Manual%20(1983).pdf ==See Also== * [[wp:Action!_(programming_language)|Action! on Wikipedia]] * [[ALGOL 68]] diff --git a/Lang/Ada/Cistercian-numerals b/Lang/Ada/Cistercian-numerals new file mode 120000 index 0000000000..a03109c188 --- /dev/null +++ b/Lang/Ada/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Ada \ No newline at end of file diff --git a/Lang/Ada/Curzon-numbers b/Lang/Ada/Curzon-numbers new file mode 120000 index 0000000000..4a77e1da8a --- /dev/null +++ b/Lang/Ada/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Ada \ No newline at end of file diff --git a/Lang/AppleScript/Bin-given-limits b/Lang/AppleScript/Bin-given-limits new file mode 120000 index 0000000000..955dc82ffb --- /dev/null +++ b/Lang/AppleScript/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Nth-root b/Lang/AppleScript/Nth-root new file mode 120000 index 0000000000..24be4fbbed --- /dev/null +++ b/Lang/AppleScript/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Write-float-arrays-to-a-text-file b/Lang/AppleScript/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..d7524dd990 --- /dev/null +++ b/Lang/AppleScript/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Cistercian-numerals b/Lang/Applesoft-BASIC/Cistercian-numerals new file mode 120000 index 0000000000..2c5e6c52c1 --- /dev/null +++ b/Lang/Applesoft-BASIC/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Formatted-numeric-output b/Lang/Applesoft-BASIC/Formatted-numeric-output new file mode 120000 index 0000000000..52c4ceb520 --- /dev/null +++ b/Lang/Applesoft-BASIC/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Levenshtein-distance b/Lang/Applesoft-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..890eb3e044 --- /dev/null +++ b/Lang/Applesoft-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Multi-dimensional-array b/Lang/Applesoft-BASIC/Multi-dimensional-array new file mode 120000 index 0000000000..c47a96b8ff --- /dev/null +++ b/Lang/Applesoft-BASIC/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Towers-of-Hanoi b/Lang/Applesoft-BASIC/Towers-of-Hanoi new file mode 120000 index 0000000000..7e7bc24b30 --- /dev/null +++ b/Lang/Applesoft-BASIC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Arturo/Arithmetic-derivative b/Lang/Arturo/Arithmetic-derivative new file mode 120000 index 0000000000..d1b6630a6c --- /dev/null +++ b/Lang/Arturo/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Dice-game-probabilities b/Lang/Arturo/Dice-game-probabilities new file mode 120000 index 0000000000..963933dbf3 --- /dev/null +++ b/Lang/Arturo/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Element-wise-operations b/Lang/Arturo/Element-wise-operations new file mode 120000 index 0000000000..da54867937 --- /dev/null +++ b/Lang/Arturo/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Entropy-Narcissist b/Lang/Arturo/Entropy-Narcissist new file mode 120000 index 0000000000..a5a91d666a --- /dev/null +++ b/Lang/Arturo/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Munching-squares b/Lang/Arturo/Munching-squares new file mode 120000 index 0000000000..3d1757b680 --- /dev/null +++ b/Lang/Arturo/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Arturo \ No newline at end of file diff --git a/Lang/Asymptote/Evaluate-binomial-coefficients b/Lang/Asymptote/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..8408c303d7 --- /dev/null +++ b/Lang/Asymptote/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Asymptote \ No newline at end of file diff --git a/Lang/Atari-BASIC/Pi b/Lang/Atari-BASIC/Pi new file mode 120000 index 0000000000..b081cc7024 --- /dev/null +++ b/Lang/Atari-BASIC/Pi @@ -0,0 +1 @@ +../../Task/Pi/Atari-BASIC \ No newline at end of file diff --git a/Lang/AutoHotKey-V2/00-LANG.txt b/Lang/AutoHotKey-V2/00-LANG.txt new file mode 100644 index 0000000000..a333f928af --- /dev/null +++ b/Lang/AutoHotKey-V2/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|AutoHotKey V2}} \ No newline at end of file diff --git a/Lang/AutoHotKey-V2/00-META.yaml b/Lang/AutoHotKey-V2/00-META.yaml new file mode 100644 index 0000000000..316ebe0ccb --- /dev/null +++ b/Lang/AutoHotKey-V2/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:AutoHotKey_V2 diff --git a/Lang/AutoHotKey-V2/Hello-world-Graphical b/Lang/AutoHotKey-V2/Hello-world-Graphical new file mode 120000 index 0000000000..89783bc714 --- /dev/null +++ b/Lang/AutoHotKey-V2/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/AutoHotKey-V2 \ No newline at end of file diff --git a/Lang/Autohotkey-V2/00-LANG.txt b/Lang/Autohotkey-V2/00-LANG.txt deleted file mode 100644 index b3e33b65ab..0000000000 --- a/Lang/Autohotkey-V2/00-LANG.txt +++ /dev/null @@ -1,16 +0,0 @@ -{{stub}}AutoHotkey V2 is an [[open source]] programming language for Microsoft [[Windows]]. - -AutoHotkey v2 is a major update to the AutoHotkey language, which includes numerous new features and improvements. - -== Citations == - -* [https://www.autohotkey.com/docs/v2/ Documentation] -* [http://autohotkey.com/download Downloads] -* [http://autohotkey.com/docs/scripts/ Script Showcase] -* [http://autohotkey.com/boards/ New Community forum] -* [http://www.autohotkey.com/forum/ Archived Community forum] -* [http://ahkscript.org/foundation AutoHotkey Foundation LLC] -* [[wp:AutoHotkey|AutoHotkey on Wikipedia]] -* #ahk on [http://webchat.freenode.net/?channels=%23ahk Freenode Web interface] -* [[:Category:AutoHotkey_Originated]] -{{language|Ayrch}} \ No newline at end of file diff --git a/Lang/Autohotkey-V2/00-META.yaml b/Lang/Autohotkey-V2/00-META.yaml deleted file mode 100644 index 651d1bc21b..0000000000 --- a/Lang/Autohotkey-V2/00-META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -from: http://rosettacode.org/wiki/Category:Autohotkey_V2 diff --git a/Lang/Autohotkey-V2/Hello-world-Graphical b/Lang/Autohotkey-V2/Hello-world-Graphical deleted file mode 120000 index 0375a8eeb7..0000000000 --- a/Lang/Autohotkey-V2/Hello-world-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Graphical/Autohotkey-V2 \ No newline at end of file diff --git a/Lang/BASIC/Partition-an-integer-x-into-n-primes b/Lang/BASIC/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..8db316776d --- /dev/null +++ b/Lang/BASIC/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Evaluate-binomial-coefficients b/Lang/BASIC256/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..415fd5e54e --- /dev/null +++ b/Lang/BASIC256/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/BASIC256 \ No newline at end of file diff --git a/Lang/BQN/Find-common-directory-path b/Lang/BQN/Find-common-directory-path new file mode 120000 index 0000000000..d4456eaa79 --- /dev/null +++ b/Lang/BQN/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/BQN \ No newline at end of file diff --git a/Lang/BQN/Globally-replace-text-in-several-files b/Lang/BQN/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..b13db5355b --- /dev/null +++ b/Lang/BQN/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/BQN \ No newline at end of file diff --git a/Lang/Ballerina/00-LANG.txt b/Lang/Ballerina/00-LANG.txt index af215acfd5..f56f4083d5 100644 --- a/Lang/Ballerina/00-LANG.txt +++ b/Lang/Ballerina/00-LANG.txt @@ -1 +1,17 @@ -{{stub}}{{language|Ballerina}} \ No newline at end of file +{{language|Ballerina +|exec=bytecode +|strength=strong +|safety=safe +|express=explicit +|checking=static +|gc=yes +|hopl=no +|site=https://ballerina.io +}} +'''[https://en.wikipedia.org/wiki/Ballerina_(programming_language) Ballerina]''' is an open source general-purpose programming language designed and supported by [https://wso2.com/ WSO2] for cloud-era application programmers. + +It is under development on [https://github.com/ballerina-platform/ballerina-lang GitHub] and is fully documented [https://ballerina.io here]. + +Ballerina was first publicly announced in 2017 and version 1.0 was released on September 10, 2019. However, a major overhaul took place in 2022 when [https://blog.ballerina.io/posts/2022-02-01-announcing-ballerina-2201.0.0-swan-lake/ Ballerina 2201.0.0 (Swan Lake)] was released. + +The current version (2201.12.3) has distributions available for Windows, Linux and macOS and can be downloaded [https://ballerina.io/downloads/ here]. \ No newline at end of file diff --git a/Lang/Ballerina/A+B b/Lang/Ballerina/A+B new file mode 120000 index 0000000000..e9aab74a73 --- /dev/null +++ b/Lang/Ballerina/A+B @@ -0,0 +1 @@ +../../Task/A+B/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/ABC-problem b/Lang/Ballerina/ABC-problem new file mode 120000 index 0000000000..49ca7ac9ad --- /dev/null +++ b/Lang/Ballerina/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/AKS-test-for-primes b/Lang/Ballerina/AKS-test-for-primes new file mode 120000 index 0000000000..9b19f08d80 --- /dev/null +++ b/Lang/Ballerina/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications b/Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..b5353658a4 --- /dev/null +++ b/Lang/Ballerina/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Abundant-odd-numbers b/Lang/Ballerina/Abundant-odd-numbers new file mode 120000 index 0000000000..0b3a97c4a1 --- /dev/null +++ b/Lang/Ballerina/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Accumulator-factory b/Lang/Ballerina/Accumulator-factory new file mode 120000 index 0000000000..837dbbe6a0 --- /dev/null +++ b/Lang/Ballerina/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Achilles-numbers b/Lang/Ballerina/Achilles-numbers new file mode 120000 index 0000000000..3336ab1c37 --- /dev/null +++ b/Lang/Ballerina/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Ackermann-function b/Lang/Ballerina/Ackermann-function new file mode 120000 index 0000000000..b9748d884d --- /dev/null +++ b/Lang/Ballerina/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..12efd91bd6 --- /dev/null +++ b/Lang/Ballerina/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Additive-primes b/Lang/Ballerina/Additive-primes new file mode 120000 index 0000000000..a504210ea7 --- /dev/null +++ b/Lang/Ballerina/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Address-of-a-variable b/Lang/Ballerina/Address-of-a-variable new file mode 120000 index 0000000000..6428e75ce3 --- /dev/null +++ b/Lang/Ballerina/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Almost-prime b/Lang/Ballerina/Almost-prime new file mode 120000 index 0000000000..33d501af1e --- /dev/null +++ b/Lang/Ballerina/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Amb b/Lang/Ballerina/Amb new file mode 120000 index 0000000000..7acc58d7c4 --- /dev/null +++ b/Lang/Ballerina/Amb @@ -0,0 +1 @@ +../../Task/Amb/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Angle-difference-between-two-bearings b/Lang/Ballerina/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..04ff00d986 --- /dev/null +++ b/Lang/Ballerina/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Anti-primes b/Lang/Ballerina/Anti-primes new file mode 120000 index 0000000000..9911fc0bcb --- /dev/null +++ b/Lang/Ballerina/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Apply-a-callback-to-an-array b/Lang/Ballerina/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..9911480671 --- /dev/null +++ b/Lang/Ballerina/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Approximate-equality b/Lang/Ballerina/Approximate-equality new file mode 120000 index 0000000000..0ea6692d0d --- /dev/null +++ b/Lang/Ballerina/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-Complex b/Lang/Ballerina/Arithmetic-Complex new file mode 120000 index 0000000000..f87fd15204 --- /dev/null +++ b/Lang/Ballerina/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-Integer b/Lang/Ballerina/Arithmetic-Integer new file mode 120000 index 0000000000..a4c8cf5206 --- /dev/null +++ b/Lang/Ballerina/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-Rational b/Lang/Ballerina/Arithmetic-Rational new file mode 120000 index 0000000000..422af5f88b --- /dev/null +++ b/Lang/Ballerina/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arithmetic-numbers b/Lang/Ballerina/Arithmetic-numbers new file mode 120000 index 0000000000..38541780a0 --- /dev/null +++ b/Lang/Ballerina/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Array-concatenation b/Lang/Ballerina/Array-concatenation new file mode 120000 index 0000000000..41c2603b74 --- /dev/null +++ b/Lang/Ballerina/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Array-length b/Lang/Ballerina/Array-length new file mode 120000 index 0000000000..25020148f9 --- /dev/null +++ b/Lang/Ballerina/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Arrays b/Lang/Ballerina/Arrays new file mode 120000 index 0000000000..ec5c5a266e --- /dev/null +++ b/Lang/Ballerina/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Ascending-primes b/Lang/Ballerina/Ascending-primes new file mode 120000 index 0000000000..51444ceb96 --- /dev/null +++ b/Lang/Ballerina/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Associative-array-Creation b/Lang/Ballerina/Associative-array-Creation new file mode 120000 index 0000000000..2639b285f3 --- /dev/null +++ b/Lang/Ballerina/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Associative-array-Iteration b/Lang/Ballerina/Associative-array-Iteration new file mode 120000 index 0000000000..d3e31d2374 --- /dev/null +++ b/Lang/Ballerina/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Associative-array-Merging b/Lang/Ballerina/Associative-array-Merging new file mode 120000 index 0000000000..cd38137d75 --- /dev/null +++ b/Lang/Ballerina/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Arithmetic-mean b/Lang/Ballerina/Averages-Arithmetic-mean new file mode 120000 index 0000000000..039d1f0de8 --- /dev/null +++ b/Lang/Ballerina/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Mean-angle b/Lang/Ballerina/Averages-Mean-angle new file mode 120000 index 0000000000..adf77693ce --- /dev/null +++ b/Lang/Ballerina/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Mean-time-of-day b/Lang/Ballerina/Averages-Mean-time-of-day new file mode 120000 index 0000000000..c969ed84e4 --- /dev/null +++ b/Lang/Ballerina/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Median b/Lang/Ballerina/Averages-Median new file mode 120000 index 0000000000..5bbd39cecb --- /dev/null +++ b/Lang/Ballerina/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Mode b/Lang/Ballerina/Averages-Mode new file mode 120000 index 0000000000..72d0e02dae --- /dev/null +++ b/Lang/Ballerina/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Pythagorean-means b/Lang/Ballerina/Averages-Pythagorean-means new file mode 120000 index 0000000000..fd607a9ee8 --- /dev/null +++ b/Lang/Ballerina/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Root-mean-square b/Lang/Ballerina/Averages-Root-mean-square new file mode 120000 index 0000000000..48056410d9 --- /dev/null +++ b/Lang/Ballerina/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Averages-Simple-moving-average b/Lang/Ballerina/Averages-Simple-moving-average new file mode 120000 index 0000000000..7e2849cced --- /dev/null +++ b/Lang/Ballerina/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Balanced-brackets b/Lang/Ballerina/Balanced-brackets new file mode 120000 index 0000000000..3d78b77dd3 --- /dev/null +++ b/Lang/Ballerina/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Boolean-values b/Lang/Ballerina/Boolean-values new file mode 120000 index 0000000000..c01657f16a --- /dev/null +++ b/Lang/Ballerina/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Caesar-cipher b/Lang/Ballerina/Caesar-cipher new file mode 120000 index 0000000000..8e1a6603e9 --- /dev/null +++ b/Lang/Ballerina/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Calculating-the-value-of-e b/Lang/Ballerina/Calculating-the-value-of-e new file mode 120000 index 0000000000..af3085b824 --- /dev/null +++ b/Lang/Ballerina/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Case-sensitivity-of-identifiers b/Lang/Ballerina/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..42725d41da --- /dev/null +++ b/Lang/Ballerina/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Character-codes b/Lang/Ballerina/Character-codes new file mode 120000 index 0000000000..6abede048f --- /dev/null +++ b/Lang/Ballerina/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Classes b/Lang/Ballerina/Classes new file mode 120000 index 0000000000..0c8bd2434d --- /dev/null +++ b/Lang/Ballerina/Classes @@ -0,0 +1 @@ +../../Task/Classes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Count-in-octal b/Lang/Ballerina/Count-in-octal new file mode 120000 index 0000000000..7e70a67830 --- /dev/null +++ b/Lang/Ballerina/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Currency b/Lang/Ballerina/Currency new file mode 120000 index 0000000000..2b278dfa20 --- /dev/null +++ b/Lang/Ballerina/Currency @@ -0,0 +1 @@ +../../Task/Currency/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Currying b/Lang/Ballerina/Currying new file mode 120000 index 0000000000..7e465c7834 --- /dev/null +++ b/Lang/Ballerina/Currying @@ -0,0 +1 @@ +../../Task/Currying/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Dynamic-variable-names b/Lang/Ballerina/Dynamic-variable-names new file mode 120000 index 0000000000..5c549728ae --- /dev/null +++ b/Lang/Ballerina/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Empty-string b/Lang/Ballerina/Empty-string new file mode 120000 index 0000000000..a86a0ffc9d --- /dev/null +++ b/Lang/Ballerina/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Extreme-floating-point-values b/Lang/Ballerina/Extreme-floating-point-values new file mode 120000 index 0000000000..7f91d37268 --- /dev/null +++ b/Lang/Ballerina/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Farey-sequence b/Lang/Ballerina/Farey-sequence new file mode 120000 index 0000000000..d542459c5f --- /dev/null +++ b/Lang/Ballerina/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Find-limit-of-recursion b/Lang/Ballerina/Find-limit-of-recursion new file mode 120000 index 0000000000..0c9c45aca0 --- /dev/null +++ b/Lang/Ballerina/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Fivenum b/Lang/Ballerina/Fivenum new file mode 120000 index 0000000000..0df90aeb78 --- /dev/null +++ b/Lang/Ballerina/Fivenum @@ -0,0 +1 @@ +../../Task/Fivenum/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Floyds-triangle b/Lang/Ballerina/Floyds-triangle new file mode 120000 index 0000000000..524ef8d9d5 --- /dev/null +++ b/Lang/Ballerina/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Four-bit-adder b/Lang/Ballerina/Four-bit-adder new file mode 120000 index 0000000000..da1ccb0292 --- /dev/null +++ b/Lang/Ballerina/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Function-definition b/Lang/Ballerina/Function-definition new file mode 120000 index 0000000000..aad5e07c0c --- /dev/null +++ b/Lang/Ballerina/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Gapful-numbers b/Lang/Ballerina/Gapful-numbers new file mode 120000 index 0000000000..16bb3670f6 --- /dev/null +++ b/Lang/Ballerina/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Greatest-subsequential-sum b/Lang/Ballerina/Greatest-subsequential-sum new file mode 120000 index 0000000000..edc1a686d7 --- /dev/null +++ b/Lang/Ballerina/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hailstone-sequence b/Lang/Ballerina/Hailstone-sequence new file mode 120000 index 0000000000..41dfb14066 --- /dev/null +++ b/Lang/Ballerina/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hello-world-Newline-omission b/Lang/Ballerina/Hello-world-Newline-omission new file mode 120000 index 0000000000..1016c5553e --- /dev/null +++ b/Lang/Ballerina/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Hello-world-Standard-error b/Lang/Ballerina/Hello-world-Standard-error new file mode 120000 index 0000000000..c4921dce1f --- /dev/null +++ b/Lang/Ballerina/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Levenshtein-distance b/Lang/Ballerina/Levenshtein-distance new file mode 120000 index 0000000000..4824e03354 --- /dev/null +++ b/Lang/Ballerina/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loop-over-multiple-arrays-simultaneously b/Lang/Ballerina/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..9b68d094d5 --- /dev/null +++ b/Lang/Ballerina/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Break b/Lang/Ballerina/Loops-Break new file mode 120000 index 0000000000..6ab612b087 --- /dev/null +++ b/Lang/Ballerina/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Continue b/Lang/Ballerina/Loops-Continue new file mode 120000 index 0000000000..175be123b9 --- /dev/null +++ b/Lang/Ballerina/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Do-while b/Lang/Ballerina/Loops-Do-while new file mode 120000 index 0000000000..b90c6b3171 --- /dev/null +++ b/Lang/Ballerina/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Downward-for b/Lang/Ballerina/Loops-Downward-for new file mode 120000 index 0000000000..e977389f54 --- /dev/null +++ b/Lang/Ballerina/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-For b/Lang/Ballerina/Loops-For new file mode 120000 index 0000000000..8ad2b8fd0c --- /dev/null +++ b/Lang/Ballerina/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-For-with-a-specified-step b/Lang/Ballerina/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..cc892dc7f2 --- /dev/null +++ b/Lang/Ballerina/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Foreach b/Lang/Ballerina/Loops-Foreach new file mode 120000 index 0000000000..f819fadabe --- /dev/null +++ b/Lang/Ballerina/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Increment-loop-index-within-loop-body b/Lang/Ballerina/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..1c9b81a58a --- /dev/null +++ b/Lang/Ballerina/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Infinite b/Lang/Ballerina/Loops-Infinite new file mode 120000 index 0000000000..312369ce48 --- /dev/null +++ b/Lang/Ballerina/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-N-plus-one-half b/Lang/Ballerina/Loops-N-plus-one-half new file mode 120000 index 0000000000..220ecbad7f --- /dev/null +++ b/Lang/Ballerina/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Nested b/Lang/Ballerina/Loops-Nested new file mode 120000 index 0000000000..f32c9a3c17 --- /dev/null +++ b/Lang/Ballerina/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-With-multiple-ranges b/Lang/Ballerina/Loops-With-multiple-ranges new file mode 120000 index 0000000000..2fad29a9f9 --- /dev/null +++ b/Lang/Ballerina/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Loops-Wrong-ranges b/Lang/Ballerina/Loops-Wrong-ranges new file mode 120000 index 0000000000..6c8ada2aa7 --- /dev/null +++ b/Lang/Ballerina/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Stack b/Lang/Ballerina/Stack new file mode 120000 index 0000000000..e073045735 --- /dev/null +++ b/Lang/Ballerina/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Statistics-Basic b/Lang/Ballerina/Statistics-Basic new file mode 120000 index 0000000000..7ef892b782 --- /dev/null +++ b/Lang/Ballerina/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Towers-of-Hanoi b/Lang/Ballerina/Towers-of-Hanoi new file mode 120000 index 0000000000..81bf7985bd --- /dev/null +++ b/Lang/Ballerina/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Truncatable-primes b/Lang/Ballerina/Truncatable-primes new file mode 120000 index 0000000000..044dcb5d58 --- /dev/null +++ b/Lang/Ballerina/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Ballerina \ No newline at end of file diff --git a/Lang/Ballerina/Unicode-variable-names b/Lang/Ballerina/Unicode-variable-names new file mode 120000 index 0000000000..7f61255815 --- /dev/null +++ b/Lang/Ballerina/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Ballerina \ No newline at end of file diff --git a/Lang/C++/Currency b/Lang/C++/Currency new file mode 120000 index 0000000000..ae0e8d6190 --- /dev/null +++ b/Lang/C++/Currency @@ -0,0 +1 @@ +../../Task/Currency/C++ \ No newline at end of file diff --git a/Lang/C++/Strassens-algorithm b/Lang/C++/Strassens-algorithm new file mode 120000 index 0000000000..1423f44a39 --- /dev/null +++ b/Lang/C++/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/C++ \ No newline at end of file diff --git a/Lang/C-sharp/ADFGVX-cipher b/Lang/C-sharp/ADFGVX-cipher new file mode 120000 index 0000000000..1bd5856497 --- /dev/null +++ b/Lang/C-sharp/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/ASCII-art-diagram-converter b/Lang/C-sharp/ASCII-art-diagram-converter new file mode 120000 index 0000000000..a3c0a49ccd --- /dev/null +++ b/Lang/C-sharp/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Arithmetic-derivative b/Lang/C-sharp/Arithmetic-derivative new file mode 120000 index 0000000000..99fc50446f --- /dev/null +++ b/Lang/C-sharp/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Boyer-Moore-string-search b/Lang/C-sharp/Boyer-Moore-string-search new file mode 120000 index 0000000000..6d8ebe0502 --- /dev/null +++ b/Lang/C-sharp/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Calkin-Wilf-sequence b/Lang/C-sharp/Calkin-Wilf-sequence new file mode 120000 index 0000000000..75d6e98750 --- /dev/null +++ b/Lang/C-sharp/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..2adfbd6635 --- /dev/null +++ b/Lang/C-sharp/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..82412a8f32 --- /dev/null +++ b/Lang/C-sharp/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Execute-a-Markov-algorithm b/Lang/C-sharp/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..fac2e3f425 --- /dev/null +++ b/Lang/C-sharp/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Extensible-prime-generator b/Lang/C-sharp/Extensible-prime-generator new file mode 120000 index 0000000000..1e4636d3bb --- /dev/null +++ b/Lang/C-sharp/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/File-extension-is-in-extensions-list b/Lang/C-sharp/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..caec470709 --- /dev/null +++ b/Lang/C-sharp/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Find-if-a-point-is-within-a-triangle b/Lang/C-sharp/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..0c9dec87d9 --- /dev/null +++ b/Lang/C-sharp/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Gotchas b/Lang/C-sharp/Gotchas new file mode 120000 index 0000000000..c20938cf21 --- /dev/null +++ b/Lang/C-sharp/Gotchas @@ -0,0 +1 @@ +../../Task/Gotchas/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Index-finite-lists-of-positive-integers b/Lang/C-sharp/Index-finite-lists-of-positive-integers new file mode 120000 index 0000000000..692e611ddc --- /dev/null +++ b/Lang/C-sharp/Index-finite-lists-of-positive-integers @@ -0,0 +1 @@ +../../Task/Index-finite-lists-of-positive-integers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/K-d-tree b/Lang/C-sharp/K-d-tree new file mode 120000 index 0000000000..9ea6355b83 --- /dev/null +++ b/Lang/C-sharp/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Longest-string-challenge b/Lang/C-sharp/Longest-string-challenge new file mode 120000 index 0000000000..bd57b65702 --- /dev/null +++ b/Lang/C-sharp/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/P-Adic-numbers-basic b/Lang/C-sharp/P-Adic-numbers-basic new file mode 120000 index 0000000000..564565afb6 --- /dev/null +++ b/Lang/C-sharp/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Reflection-Get-source b/Lang/C-sharp/Reflection-Get-source new file mode 120000 index 0000000000..a8b2f45e4c --- /dev/null +++ b/Lang/C-sharp/Reflection-Get-source @@ -0,0 +1 @@ +../../Task/Reflection-Get-source/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors b/Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors new file mode 120000 index 0000000000..71508d1c44 --- /dev/null +++ b/Lang/C-sharp/Sequence:-smallest-number-with-exactly-n-divisors @@ -0,0 +1 @@ +../../Task/Sequence:-smallest-number-with-exactly-n-divisors/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Strassens-algorithm b/Lang/C-sharp/Strassens-algorithm new file mode 120000 index 0000000000..45fd91dfa9 --- /dev/null +++ b/Lang/C-sharp/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/C-sharp \ No newline at end of file diff --git a/Lang/C/Color-wheel b/Lang/C/Color-wheel new file mode 120000 index 0000000000..9d6561adcd --- /dev/null +++ b/Lang/C/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/C \ No newline at end of file diff --git a/Lang/C/Magic-constant b/Lang/C/Magic-constant new file mode 120000 index 0000000000..3d29fd6624 --- /dev/null +++ b/Lang/C/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/C \ No newline at end of file diff --git a/Lang/C3/Binary-digits b/Lang/C3/Binary-digits new file mode 120000 index 0000000000..34a04afae2 --- /dev/null +++ b/Lang/C3/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/C3 \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Evaluate-binomial-coefficients b/Lang/Chipmunk-Basic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..b45aed06e2 --- /dev/null +++ b/Lang/Chipmunk-Basic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Crystal/Abbreviations-easy b/Lang/Crystal/Abbreviations-easy new file mode 120000 index 0000000000..b3a87e7119 --- /dev/null +++ b/Lang/Crystal/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Anagrams-Deranged-anagrams b/Lang/Crystal/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..01826ee4a9 --- /dev/null +++ b/Lang/Crystal/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-Complex b/Lang/Crystal/Arithmetic-Complex new file mode 120000 index 0000000000..db70676449 --- /dev/null +++ b/Lang/Crystal/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Arithmetic-geometric-mean b/Lang/Crystal/Arithmetic-geometric-mean new file mode 120000 index 0000000000..c8754aa805 --- /dev/null +++ b/Lang/Crystal/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Mode b/Lang/Crystal/Averages-Mode new file mode 120000 index 0000000000..bb15fa305b --- /dev/null +++ b/Lang/Crystal/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Averages-Pythagorean-means b/Lang/Crystal/Averages-Pythagorean-means new file mode 120000 index 0000000000..a97d5df819 --- /dev/null +++ b/Lang/Crystal/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Bin-given-limits b/Lang/Crystal/Bin-given-limits new file mode 120000 index 0000000000..40a049c833 --- /dev/null +++ b/Lang/Crystal/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Character-codes b/Lang/Crystal/Character-codes new file mode 120000 index 0000000000..bd4879b77c --- /dev/null +++ b/Lang/Crystal/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Cistercian-numerals b/Lang/Crystal/Cistercian-numerals new file mode 120000 index 0000000000..b439a8a963 --- /dev/null +++ b/Lang/Crystal/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Closures-Value-capture b/Lang/Crystal/Closures-Value-capture new file mode 120000 index 0000000000..f3038be393 --- /dev/null +++ b/Lang/Crystal/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Comma-quibbling b/Lang/Crystal/Comma-quibbling new file mode 120000 index 0000000000..3151a9c58f --- /dev/null +++ b/Lang/Crystal/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Convert-seconds-to-compound-duration b/Lang/Crystal/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..313254bee3 --- /dev/null +++ b/Lang/Crystal/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Determine-if-a-string-has-all-the-same-characters b/Lang/Crystal/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..a0bef4d19a --- /dev/null +++ b/Lang/Crystal/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Determine-if-a-string-is-collapsible b/Lang/Crystal/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..7e2d57c2cb --- /dev/null +++ b/Lang/Crystal/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Dijkstras-algorithm b/Lang/Crystal/Dijkstras-algorithm new file mode 120000 index 0000000000..829bbaa132 --- /dev/null +++ b/Lang/Crystal/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Dutch-national-flag-problem b/Lang/Crystal/Dutch-national-flag-problem new file mode 120000 index 0000000000..a920e0b89a --- /dev/null +++ b/Lang/Crystal/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Execute-Brain- b/Lang/Crystal/Execute-Brain- new file mode 120000 index 0000000000..4ffee47edd --- /dev/null +++ b/Lang/Crystal/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hello-world-Standard-error b/Lang/Crystal/Hello-world-Standard-error new file mode 120000 index 0000000000..560e23c97c --- /dev/null +++ b/Lang/Crystal/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hex-words b/Lang/Crystal/Hex-words new file mode 120000 index 0000000000..1390f8d3e3 --- /dev/null +++ b/Lang/Crystal/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Increment-a-numerical-string b/Lang/Crystal/Increment-a-numerical-string new file mode 120000 index 0000000000..aeae95c765 --- /dev/null +++ b/Lang/Crystal/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Interactive-programming-repl- b/Lang/Crystal/Interactive-programming-repl- new file mode 120000 index 0000000000..348f845b57 --- /dev/null +++ b/Lang/Crystal/Interactive-programming-repl- @@ -0,0 +1 @@ +../../Task/Interactive-programming-repl-/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-N-plus-one-half b/Lang/Crystal/Loops-N-plus-one-half new file mode 120000 index 0000000000..baee612204 --- /dev/null +++ b/Lang/Crystal/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Magic-8-ball b/Lang/Crystal/Magic-8-ball new file mode 120000 index 0000000000..7694de9dbd --- /dev/null +++ b/Lang/Crystal/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Non-decimal-radices-Convert b/Lang/Crystal/Non-decimal-radices-Convert new file mode 120000 index 0000000000..342df0f845 --- /dev/null +++ b/Lang/Crystal/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Order-by-pair-comparisons b/Lang/Crystal/Order-by-pair-comparisons new file mode 120000 index 0000000000..7f819e26a0 --- /dev/null +++ b/Lang/Crystal/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Order-two-numerical-lists b/Lang/Crystal/Order-two-numerical-lists new file mode 120000 index 0000000000..44bdc040e5 --- /dev/null +++ b/Lang/Crystal/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Phrase-reversals b/Lang/Crystal/Phrase-reversals new file mode 120000 index 0000000000..7a12cc6718 --- /dev/null +++ b/Lang/Crystal/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Power-set b/Lang/Crystal/Power-set new file mode 120000 index 0000000000..0fd70fd5b9 --- /dev/null +++ b/Lang/Crystal/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Run-length-encoding b/Lang/Crystal/Run-length-encoding new file mode 120000 index 0000000000..1a2b6b241a --- /dev/null +++ b/Lang/Crystal/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-an-array-of-composite-structures b/Lang/Crystal/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..5ea781aef9 --- /dev/null +++ b/Lang/Crystal/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-numbers-lexicographically b/Lang/Crystal/Sort-numbers-lexicographically new file mode 120000 index 0000000000..884dc88521 --- /dev/null +++ b/Lang/Crystal/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sort-three-variables b/Lang/Crystal/Sort-three-variables new file mode 120000 index 0000000000..e206daaf02 --- /dev/null +++ b/Lang/Crystal/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-Algorithms-Circle-Sort b/Lang/Crystal/Sorting-Algorithms-Circle-Sort new file mode 120000 index 0000000000..2618e0f461 --- /dev/null +++ b/Lang/Crystal/Sorting-Algorithms-Circle-Sort @@ -0,0 +1 @@ +../../Task/Sorting-Algorithms-Circle-Sort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-algorithms-Bubble-sort b/Lang/Crystal/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..88a150acfe --- /dev/null +++ b/Lang/Crystal/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Split-a-character-string-based-on-change-of-character b/Lang/Crystal/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..874feaced9 --- /dev/null +++ b/Lang/Crystal/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Stack-traces b/Lang/Crystal/Stack-traces new file mode 120000 index 0000000000..9cc8cddb52 --- /dev/null +++ b/Lang/Crystal/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-prepend b/Lang/Crystal/String-prepend new file mode 120000 index 0000000000..2c5c171e4c --- /dev/null +++ b/Lang/Crystal/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Take-notes-on-the-command-line b/Lang/Crystal/Take-notes-on-the-command-line new file mode 120000 index 0000000000..e978486e4d --- /dev/null +++ b/Lang/Crystal/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Crystal \ No newline at end of file diff --git a/Lang/D/Find-Chess960-starting-position-identifier b/Lang/D/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..79e07139b9 --- /dev/null +++ b/Lang/D/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/D \ No newline at end of file diff --git a/Lang/Dart/24-game-Solve b/Lang/Dart/24-game-Solve new file mode 120000 index 0000000000..ae64875d6c --- /dev/null +++ b/Lang/Dart/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Dart \ No newline at end of file diff --git a/Lang/Dart/K-d-tree b/Lang/Dart/K-d-tree new file mode 120000 index 0000000000..4b4a8013e5 --- /dev/null +++ b/Lang/Dart/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Dart \ No newline at end of file diff --git a/Lang/Dart/Penneys-game b/Lang/Dart/Penneys-game new file mode 120000 index 0000000000..f054d83b87 --- /dev/null +++ b/Lang/Dart/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Dart \ No newline at end of file diff --git a/Lang/Delphi/Generate-Chess960-starting-position b/Lang/Delphi/Generate-Chess960-starting-position new file mode 120000 index 0000000000..2c3a66190d --- /dev/null +++ b/Lang/Delphi/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Delphi \ No newline at end of file diff --git a/Lang/ERRE/Leonardo-numbers b/Lang/ERRE/Leonardo-numbers new file mode 120000 index 0000000000..3e0d0050d1 --- /dev/null +++ b/Lang/ERRE/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/ERRE \ No newline at end of file diff --git a/Lang/EasyLang/00-LANG.txt b/Lang/EasyLang/00-LANG.txt index ba3b92e229..e09a925b83 100644 --- a/Lang/EasyLang/00-LANG.txt +++ b/Lang/EasyLang/00-LANG.txt @@ -11,7 +11,7 @@ ''Easylang'' is a (beginners) programming language with built-in commands for graphics output. The statically typed language has a reduced syntax and semantics. Variables do not have to be declared, the data type is encoded in the variable name - as was usual in the earlier home computer BASIC. The data types are strings and numbers (floating point), arrays of strings and numbers, and arrays of arrays. Arrays are 1-based and can grow. Programs compiled into an AST tree run in the browser or in the browser IDE. -[https://easylang.dev/ide/ A browser IDE] with different tutorials, one for beginners, makes programming and learning to program as easy as possible. +[https://easylang.online/ide/ A browser IDE] with different tutorials, one for beginners, makes programming and learning to program as easy as possible. The finished programs can be easily integrated into a [https://easylang.online/apps/ website]. diff --git a/Lang/EasyLang/2048 b/Lang/EasyLang/2048 new file mode 120000 index 0000000000..4a69b16207 --- /dev/null +++ b/Lang/EasyLang/2048 @@ -0,0 +1 @@ +../../Task/2048/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abbreviations-automatic b/Lang/EasyLang/Abbreviations-automatic new file mode 120000 index 0000000000..10b2251691 --- /dev/null +++ b/Lang/EasyLang/Abbreviations-automatic @@ -0,0 +1 @@ +../../Task/Abbreviations-automatic/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abbreviations-easy b/Lang/EasyLang/Abbreviations-easy new file mode 120000 index 0000000000..9f43877f2b --- /dev/null +++ b/Lang/EasyLang/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Abbreviations-simple b/Lang/EasyLang/Abbreviations-simple new file mode 120000 index 0000000000..53295111be --- /dev/null +++ b/Lang/EasyLang/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Amb b/Lang/EasyLang/Amb new file mode 120000 index 0000000000..cee73196db --- /dev/null +++ b/Lang/EasyLang/Amb @@ -0,0 +1 @@ +../../Task/Amb/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Anagrams b/Lang/EasyLang/Anagrams new file mode 120000 index 0000000000..1a48ded8aa --- /dev/null +++ b/Lang/EasyLang/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Anagrams-Deranged-anagrams b/Lang/EasyLang/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..b7af47405b --- /dev/null +++ b/Lang/EasyLang/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Babylonian-spiral b/Lang/EasyLang/Babylonian-spiral new file mode 120000 index 0000000000..a141d2cd6b --- /dev/null +++ b/Lang/EasyLang/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Boyer-Moore-string-search b/Lang/EasyLang/Boyer-Moore-string-search new file mode 120000 index 0000000000..189112146a --- /dev/null +++ b/Lang/EasyLang/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Element-wise-operations b/Lang/EasyLang/Element-wise-operations new file mode 120000 index 0000000000..79d10fbb82 --- /dev/null +++ b/Lang/EasyLang/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Factorions b/Lang/EasyLang/Factorions new file mode 120000 index 0000000000..52bf4a578c --- /dev/null +++ b/Lang/EasyLang/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Mad-Libs b/Lang/EasyLang/Mad-Libs new file mode 120000 index 0000000000..80e4f5b2e7 --- /dev/null +++ b/Lang/EasyLang/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Permutation-test b/Lang/EasyLang/Permutation-test new file mode 120000 index 0000000000..d3b1950f7a --- /dev/null +++ b/Lang/EasyLang/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..deadbe682f --- /dev/null +++ b/Lang/EasyLang/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors b/Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..c5cfa0147b --- /dev/null +++ b/Lang/EasyLang/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-a-Numbrix-puzzle b/Lang/EasyLang/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..9dc56df255 --- /dev/null +++ b/Lang/EasyLang/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Solve-the-no-connection-puzzle b/Lang/EasyLang/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..759be373e6 --- /dev/null +++ b/Lang/EasyLang/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Patience-sort b/Lang/EasyLang/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..6123828d8e --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Unprimeable-numbers b/Lang/EasyLang/Unprimeable-numbers new file mode 120000 index 0000000000..ae808307c7 --- /dev/null +++ b/Lang/EasyLang/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers b/Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..2c61d301f5 --- /dev/null +++ b/Lang/EasyLang/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/EasyLang \ No newline at end of file diff --git a/Lang/Elena/00-LANG.txt b/Lang/Elena/00-LANG.txt index 671257e3ee..c3a21bf2d4 100644 --- a/Lang/Elena/00-LANG.txt +++ b/Lang/Elena/00-LANG.txt @@ -1,5 +1,5 @@ {{language|Elena -|site=http://elenalang.sourceforge.net +|site=https://elena-lang.github.io/ |exec=bytecode |strength=strong |safety=safe diff --git a/Lang/Elena/Comma-quibbling b/Lang/Elena/Comma-quibbling new file mode 120000 index 0000000000..f92aff5654 --- /dev/null +++ b/Lang/Elena/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Elena \ No newline at end of file diff --git a/Lang/Elena/Concurrent-computing b/Lang/Elena/Concurrent-computing new file mode 120000 index 0000000000..d22278e519 --- /dev/null +++ b/Lang/Elena/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Elena \ No newline at end of file diff --git a/Lang/Elena/HTTP b/Lang/Elena/HTTP new file mode 120000 index 0000000000..c94b6f99cd --- /dev/null +++ b/Lang/Elena/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Elena \ No newline at end of file diff --git a/Lang/Elena/HTTPS b/Lang/Elena/HTTPS new file mode 120000 index 0000000000..879dfcb045 --- /dev/null +++ b/Lang/Elena/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Elena \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Color-wheel b/Lang/Emacs-Lisp/Color-wheel new file mode 120000 index 0000000000..90b9cec116 --- /dev/null +++ b/Lang/Emacs-Lisp/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..db888b4ffd --- /dev/null +++ b/Lang/Emacs-Lisp/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Keyboard-input-Keypress-check b/Lang/Emacs-Lisp/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..1bf55a234e --- /dev/null +++ b/Lang/Emacs-Lisp/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..d6205cc54b --- /dev/null +++ b/Lang/Emacs-Lisp/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character b/Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..7bff70bc55 --- /dev/null +++ b/Lang/Emacs-Lisp/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Strip-comments-from-a-string b/Lang/Emacs-Lisp/Strip-comments-from-a-string new file mode 120000 index 0000000000..e8fcd5a3c3 --- /dev/null +++ b/Lang/Emacs-Lisp/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Word-frequency b/Lang/Emacs-Lisp/Word-frequency new file mode 120000 index 0000000000..74fd09e7f4 --- /dev/null +++ b/Lang/Emacs-Lisp/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Parse-an-IP-Address b/Lang/Erlang/Parse-an-IP-Address new file mode 120000 index 0000000000..3e48d0f0b1 --- /dev/null +++ b/Lang/Erlang/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Erlang \ No newline at end of file diff --git a/Lang/Excel/Arrays b/Lang/Excel/Arrays new file mode 120000 index 0000000000..bad8c856a9 --- /dev/null +++ b/Lang/Excel/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Excel \ No newline at end of file diff --git a/Lang/Excel/Conditional-structures b/Lang/Excel/Conditional-structures new file mode 120000 index 0000000000..f4ffdbd4b9 --- /dev/null +++ b/Lang/Excel/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Excel \ No newline at end of file diff --git a/Lang/Excel/FizzBuzz b/Lang/Excel/FizzBuzz new file mode 120000 index 0000000000..15df08a856 --- /dev/null +++ b/Lang/Excel/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Excel \ No newline at end of file diff --git a/Lang/Excel/Function-definition b/Lang/Excel/Function-definition new file mode 120000 index 0000000000..e6ecf64bef --- /dev/null +++ b/Lang/Excel/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Excel \ No newline at end of file diff --git a/Lang/Excel/Loops-For b/Lang/Excel/Loops-For new file mode 120000 index 0000000000..876b47b179 --- /dev/null +++ b/Lang/Excel/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Excel \ No newline at end of file diff --git a/Lang/Excel/Repeat-a-string b/Lang/Excel/Repeat-a-string new file mode 120000 index 0000000000..2c684073cb --- /dev/null +++ b/Lang/Excel/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Excel \ No newline at end of file diff --git a/Lang/Excel/Reverse-a-string b/Lang/Excel/Reverse-a-string new file mode 120000 index 0000000000..2a3cf97cfe --- /dev/null +++ b/Lang/Excel/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Excel \ No newline at end of file diff --git a/Lang/Excel/Tokenize-a-string b/Lang/Excel/Tokenize-a-string new file mode 120000 index 0000000000..9d5af3b4b4 --- /dev/null +++ b/Lang/Excel/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Excel \ No newline at end of file diff --git a/Lang/F-Sharp/Mad-Libs b/Lang/F-Sharp/Mad-Libs new file mode 120000 index 0000000000..69a30ced53 --- /dev/null +++ b/Lang/F-Sharp/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/F-Sharp \ No newline at end of file diff --git a/Lang/Factor/Tic-tac-toe b/Lang/Factor/Tic-tac-toe new file mode 120000 index 0000000000..183c5fb3e0 --- /dev/null +++ b/Lang/Factor/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Factor \ No newline at end of file diff --git a/Lang/Forth/Almost-prime b/Lang/Forth/Almost-prime new file mode 120000 index 0000000000..bbe907fa90 --- /dev/null +++ b/Lang/Forth/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Forth \ No newline at end of file diff --git a/Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- b/Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- new file mode 120000 index 0000000000..dd0e66389d --- /dev/null +++ b/Lang/Fortran/Apply-a-digital-filter-direct-form-II-transposed- @@ -0,0 +1 @@ +../../Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran \ No newline at end of file diff --git a/Lang/Fortran/B-zier-curves-Intersections b/Lang/Fortran/B-zier-curves-Intersections new file mode 120000 index 0000000000..59ae9a9e9a --- /dev/null +++ b/Lang/Fortran/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Eulers-constant-0.5772... b/Lang/Fortran/Eulers-constant-0.5772... new file mode 120000 index 0000000000..e2642e24fb --- /dev/null +++ b/Lang/Fortran/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../Fortran \ No newline at end of file diff --git a/Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits b/Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits new file mode 120000 index 0000000000..6f8a8ab270 --- /dev/null +++ b/Lang/Fortran/First-perfect-square-in-base-n-with-n-unique-digits @@ -0,0 +1 @@ +../../Task/First-perfect-square-in-base-n-with-n-unique-digits/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Harmonic-series b/Lang/Fortran/Harmonic-series new file mode 120000 index 0000000000..6a6cd246a2 --- /dev/null +++ b/Lang/Fortran/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knuths-algorithm-S b/Lang/Fortran/Knuths-algorithm-S new file mode 120000 index 0000000000..fe5b21ade9 --- /dev/null +++ b/Lang/Fortran/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Thieles-interpolation-formula b/Lang/Fortran/Thieles-interpolation-formula new file mode 120000 index 0000000000..f8f82960bc --- /dev/null +++ b/Lang/Fortran/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Vogels-approximation-method b/Lang/Fortran/Vogels-approximation-method new file mode 120000 index 0000000000..3098233175 --- /dev/null +++ b/Lang/Fortran/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Fortran \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/DNS-query b/Lang/Free-Pascal-Lazarus/DNS-query new file mode 120000 index 0000000000..f7c79b4afe --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Levenshtein-distance b/Lang/Free-Pascal-Lazarus/Levenshtein-distance new file mode 120000 index 0000000000..eebdca8158 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Map-range b/Lang/Free-Pascal-Lazarus/Map-range new file mode 120000 index 0000000000..65b07f3cc6 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/FreeBASIC/Bioinformatics-Global-alignment b/Lang/FreeBASIC/Bioinformatics-Global-alignment new file mode 120000 index 0000000000..93fb335c5b --- /dev/null +++ b/Lang/FreeBASIC/Bioinformatics-Global-alignment @@ -0,0 +1 @@ +../../Task/Bioinformatics-Global-alignment/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cistercian-numerals b/Lang/FreeBASIC/Cistercian-numerals new file mode 120000 index 0000000000..ceb56b6604 --- /dev/null +++ b/Lang/FreeBASIC/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Compiler-syntax-analyzer b/Lang/FreeBASIC/Compiler-syntax-analyzer new file mode 120000 index 0000000000..a7d7204b01 --- /dev/null +++ b/Lang/FreeBASIC/Compiler-syntax-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-syntax-analyzer/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Deconvolution-2D+ b/Lang/FreeBASIC/Deconvolution-2D+ new file mode 120000 index 0000000000..2a10e72230 --- /dev/null +++ b/Lang/FreeBASIC/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series b/Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..caef600e25 --- /dev/null +++ b/Lang/FreeBASIC/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Elliptic-curve-arithmetic b/Lang/FreeBASIC/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..ab0b3f0aed --- /dev/null +++ b/Lang/FreeBASIC/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Fermat-numbers b/Lang/FreeBASIC/Fermat-numbers new file mode 120000 index 0000000000..b6ff867057 --- /dev/null +++ b/Lang/FreeBASIC/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Graph-colouring b/Lang/FreeBASIC/Graph-colouring new file mode 120000 index 0000000000..2b6f6e444d --- /dev/null +++ b/Lang/FreeBASIC/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Juggler-sequence b/Lang/FreeBASIC/Juggler-sequence new file mode 120000 index 0000000000..5aaf9a794f --- /dev/null +++ b/Lang/FreeBASIC/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Knuths-algorithm-S b/Lang/FreeBASIC/Knuths-algorithm-S new file mode 120000 index 0000000000..720a4a3a7e --- /dev/null +++ b/Lang/FreeBASIC/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Knuths-power-tree b/Lang/FreeBASIC/Knuths-power-tree new file mode 120000 index 0000000000..b6075609dd --- /dev/null +++ b/Lang/FreeBASIC/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Last-letter-first-letter b/Lang/FreeBASIC/Last-letter-first-letter new file mode 120000 index 0000000000..436ebfb8b9 --- /dev/null +++ b/Lang/FreeBASIC/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Natural-sorting b/Lang/FreeBASIC/Natural-sorting new file mode 120000 index 0000000000..00267c2e93 --- /dev/null +++ b/Lang/FreeBASIC/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Fix-code-tags b/Lang/FreeBASIC/Rosetta-Code-Fix-code-tags new file mode 120000 index 0000000000..53b438e29f --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Fix-code-tags @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Fix-code-tags/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity b/Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..71d538269e --- /dev/null +++ b/Lang/FreeBASIC/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/SQL-based-authentication b/Lang/FreeBASIC/SQL-based-authentication new file mode 120000 index 0000000000..19b09b4fc4 --- /dev/null +++ b/Lang/FreeBASIC/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Simulate-input-Keyboard b/Lang/FreeBASIC/Simulate-input-Keyboard new file mode 120000 index 0000000000..504f3b18d3 --- /dev/null +++ b/Lang/FreeBASIC/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-algorithms-Strand-sort b/Lang/FreeBASIC/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..5305f3c6f7 --- /dev/null +++ b/Lang/FreeBASIC/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Text-processing-2 b/Lang/FreeBASIC/Text-processing-2 new file mode 120000 index 0000000000..03a524d892 --- /dev/null +++ b/Lang/FreeBASIC/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction b/Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..6686d05c91 --- /dev/null +++ b/Lang/FreeBASIC/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Word-ladder b/Lang/FreeBASIC/Word-ladder new file mode 120000 index 0000000000..1390108efe --- /dev/null +++ b/Lang/FreeBASIC/Word-ladder @@ -0,0 +1 @@ +../../Task/Word-ladder/FreeBASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Levenshtein-distance b/Lang/GW-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..4605e15436 --- /dev/null +++ b/Lang/GW-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Magic-constant b/Lang/GW-BASIC/Magic-constant new file mode 120000 index 0000000000..4dbe3ee401 --- /dev/null +++ b/Lang/GW-BASIC/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Map-range b/Lang/GW-BASIC/Map-range new file mode 120000 index 0000000000..487538bdd0 --- /dev/null +++ b/Lang/GW-BASIC/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Evaluate-binomial-coefficients b/Lang/Gambas/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..d84c9e286a --- /dev/null +++ b/Lang/Gambas/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Magic-constant b/Lang/Gambas/Magic-constant new file mode 120000 index 0000000000..3e63290c94 --- /dev/null +++ b/Lang/Gambas/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Gambas \ No newline at end of file diff --git a/Lang/Go/Boyer-Moore-string-search b/Lang/Go/Boyer-Moore-string-search new file mode 120000 index 0000000000..0b971fdf3b --- /dev/null +++ b/Lang/Go/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Go \ No newline at end of file diff --git a/Lang/Go/Goldbachs-comet b/Lang/Go/Goldbachs-comet new file mode 120000 index 0000000000..e80a90c082 --- /dev/null +++ b/Lang/Go/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Go \ No newline at end of file diff --git a/Lang/Go/P-Adic-square-roots b/Lang/Go/P-Adic-square-roots new file mode 120000 index 0000000000..064157bec0 --- /dev/null +++ b/Lang/Go/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Go \ No newline at end of file diff --git a/Lang/Haskell/Pathological-floating-point-problems b/Lang/Haskell/Pathological-floating-point-problems new file mode 120000 index 0000000000..f17bacf62a --- /dev/null +++ b/Lang/Haskell/Pathological-floating-point-problems @@ -0,0 +1 @@ +../../Task/Pathological-floating-point-problems/Haskell \ No newline at end of file diff --git a/Lang/Icon/Loops-Increment-loop-index-within-loop-body b/Lang/Icon/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..19c94ce3da --- /dev/null +++ b/Lang/Icon/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Icon \ No newline at end of file diff --git a/Lang/Java/Strassens-algorithm b/Lang/Java/Strassens-algorithm new file mode 120000 index 0000000000..1c8b3f279b --- /dev/null +++ b/Lang/Java/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Java \ No newline at end of file diff --git a/Lang/JavaScript/15-puzzle-solver b/Lang/JavaScript/15-puzzle-solver new file mode 120000 index 0000000000..34b980cd29 --- /dev/null +++ b/Lang/JavaScript/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/ADFGVX-cipher b/Lang/JavaScript/ADFGVX-cipher new file mode 120000 index 0000000000..eeef4038b2 --- /dev/null +++ b/Lang/JavaScript/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Average-loop-length b/Lang/JavaScript/Average-loop-length new file mode 120000 index 0000000000..c1bd894dc5 --- /dev/null +++ b/Lang/JavaScript/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bifid-cipher b/Lang/JavaScript/Bifid-cipher new file mode 120000 index 0000000000..837e122e66 --- /dev/null +++ b/Lang/JavaScript/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bitcoin-address-validation b/Lang/JavaScript/Bitcoin-address-validation new file mode 120000 index 0000000000..d09d433cd8 --- /dev/null +++ b/Lang/JavaScript/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Boyer-Moore-string-search b/Lang/JavaScript/Boyer-Moore-string-search new file mode 120000 index 0000000000..b25016942d --- /dev/null +++ b/Lang/JavaScript/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Burrows-Wheeler-transform b/Lang/JavaScript/Burrows-Wheeler-transform new file mode 120000 index 0000000000..79a79f877d --- /dev/null +++ b/Lang/JavaScript/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Camel-case-and-snake-case b/Lang/JavaScript/Camel-case-and-snake-case new file mode 120000 index 0000000000..0e52d396b8 --- /dev/null +++ b/Lang/JavaScript/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Colorful-numbers b/Lang/JavaScript/Colorful-numbers new file mode 120000 index 0000000000..861658de92 --- /dev/null +++ b/Lang/JavaScript/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Commatizing-numbers b/Lang/JavaScript/Commatizing-numbers new file mode 120000 index 0000000000..dac4a7f279 --- /dev/null +++ b/Lang/JavaScript/Commatizing-numbers @@ -0,0 +1 @@ +../../Task/Commatizing-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Compiler-code-generator b/Lang/JavaScript/Compiler-code-generator new file mode 120000 index 0000000000..7b6f8e25b0 --- /dev/null +++ b/Lang/JavaScript/Compiler-code-generator @@ -0,0 +1 @@ +../../Task/Compiler-code-generator/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Create-a-file-on-magnetic-tape b/Lang/JavaScript/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..0f15206dcf --- /dev/null +++ b/Lang/JavaScript/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Cyclotomic-polynomial b/Lang/JavaScript/Cyclotomic-polynomial new file mode 120000 index 0000000000..1407b6559c --- /dev/null +++ b/Lang/JavaScript/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/De-Bruijn-sequences b/Lang/JavaScript/De-Bruijn-sequences new file mode 120000 index 0000000000..d753d9f9d0 --- /dev/null +++ b/Lang/JavaScript/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Distribution-of-0-digits-in-factorial-series b/Lang/JavaScript/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..3fd7f0feb5 --- /dev/null +++ b/Lang/JavaScript/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..b9a9906259 --- /dev/null +++ b/Lang/JavaScript/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Elliptic-curve-arithmetic b/Lang/JavaScript/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..41de6c075f --- /dev/null +++ b/Lang/JavaScript/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Gauss-Jordan-matrix-inversion b/Lang/JavaScript/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..77acac5de4 --- /dev/null +++ b/Lang/JavaScript/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Graph-colouring b/Lang/JavaScript/Graph-colouring new file mode 120000 index 0000000000..8c22e6e014 --- /dev/null +++ b/Lang/JavaScript/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions b/Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..4b7a0299ee --- /dev/null +++ b/Lang/JavaScript/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Isqrt-integer-square-root-of-X b/Lang/JavaScript/Isqrt-integer-square-root-of-X new file mode 120000 index 0000000000..7c262657f5 --- /dev/null +++ b/Lang/JavaScript/Isqrt-integer-square-root-of-X @@ -0,0 +1 @@ +../../Task/Isqrt-integer-square-root-of-X/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Jacobi-symbol b/Lang/JavaScript/Jacobi-symbol new file mode 120000 index 0000000000..7ca750b7ca --- /dev/null +++ b/Lang/JavaScript/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/K-d-tree b/Lang/JavaScript/K-d-tree new file mode 120000 index 0000000000..f551f8aa55 --- /dev/null +++ b/Lang/JavaScript/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Knuths-algorithm-S b/Lang/JavaScript/Knuths-algorithm-S new file mode 120000 index 0000000000..78ce9e9420 --- /dev/null +++ b/Lang/JavaScript/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Knuths-power-tree b/Lang/JavaScript/Knuths-power-tree new file mode 120000 index 0000000000..65f212b8ef --- /dev/null +++ b/Lang/JavaScript/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/M-bius-function b/Lang/JavaScript/M-bius-function new file mode 120000 index 0000000000..8b88e437b9 --- /dev/null +++ b/Lang/JavaScript/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/MD5-Implementation b/Lang/JavaScript/MD5-Implementation new file mode 120000 index 0000000000..96da37623c --- /dev/null +++ b/Lang/JavaScript/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/P-Adic-numbers-basic b/Lang/JavaScript/P-Adic-numbers-basic new file mode 120000 index 0000000000..8430626fe6 --- /dev/null +++ b/Lang/JavaScript/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/P-Adic-square-roots b/Lang/JavaScript/P-Adic-square-roots new file mode 120000 index 0000000000..dc1614d80a --- /dev/null +++ b/Lang/JavaScript/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Perlin-noise b/Lang/JavaScript/Perlin-noise new file mode 120000 index 0000000000..d4cfceb70d --- /dev/null +++ b/Lang/JavaScript/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Playfair-cipher b/Lang/JavaScript/Playfair-cipher new file mode 120000 index 0000000000..e94d50f327 --- /dev/null +++ b/Lang/JavaScript/Playfair-cipher @@ -0,0 +1 @@ +../../Task/Playfair-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/SHA-1 b/Lang/JavaScript/SHA-1 new file mode 120000 index 0000000000..2773e9c63c --- /dev/null +++ b/Lang/JavaScript/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Set-puzzle b/Lang/JavaScript/Set-puzzle new file mode 120000 index 0000000000..22b0bad552 --- /dev/null +++ b/Lang/JavaScript/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Hidato-puzzle b/Lang/JavaScript/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..3e3c25cd7c --- /dev/null +++ b/Lang/JavaScript/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Numbrix-puzzle b/Lang/JavaScript/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..43202401f9 --- /dev/null +++ b/Lang/JavaScript/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sorting-algorithms-Radix-sort b/Lang/JavaScript/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..0d4b9cb23d --- /dev/null +++ b/Lang/JavaScript/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Spelling-of-ordinal-numbers b/Lang/JavaScript/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..5ed638cc81 --- /dev/null +++ b/Lang/JavaScript/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/State-name-puzzle b/Lang/JavaScript/State-name-puzzle new file mode 120000 index 0000000000..12f667dc4c --- /dev/null +++ b/Lang/JavaScript/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Strassens-algorithm b/Lang/JavaScript/Strassens-algorithm new file mode 120000 index 0000000000..f4d0497694 --- /dev/null +++ b/Lang/JavaScript/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Substitution-cipher b/Lang/JavaScript/Substitution-cipher new file mode 120000 index 0000000000..e8fd969b4a --- /dev/null +++ b/Lang/JavaScript/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tonelli-Shanks-algorithm b/Lang/JavaScript/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..f646a271d1 --- /dev/null +++ b/Lang/JavaScript/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Ukkonen-s-suffix-tree-construction b/Lang/JavaScript/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..7a4d0832f5 --- /dev/null +++ b/Lang/JavaScript/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Verhoeff-algorithm b/Lang/JavaScript/Verhoeff-algorithm new file mode 120000 index 0000000000..cd27def09b --- /dev/null +++ b/Lang/JavaScript/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vigen-re-cipher-Cryptanalysis b/Lang/JavaScript/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..53c004e91c --- /dev/null +++ b/Lang/JavaScript/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Vogels-approximation-method b/Lang/JavaScript/Vogels-approximation-method new file mode 120000 index 0000000000..72693f1daa --- /dev/null +++ b/Lang/JavaScript/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Wordiff b/Lang/JavaScript/Wordiff new file mode 120000 index 0000000000..18ec352da6 --- /dev/null +++ b/Lang/JavaScript/Wordiff @@ -0,0 +1 @@ +../../Task/Wordiff/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Zebra-puzzle b/Lang/JavaScript/Zebra-puzzle new file mode 120000 index 0000000000..5c531004b3 --- /dev/null +++ b/Lang/JavaScript/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/K/Compare-length-of-two-strings b/Lang/K/Compare-length-of-two-strings new file mode 120000 index 0000000000..9854a6e09b --- /dev/null +++ b/Lang/K/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/K \ No newline at end of file diff --git a/Lang/K/Euler-method b/Lang/K/Euler-method new file mode 120000 index 0000000000..c1f821dc7c --- /dev/null +++ b/Lang/K/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/K \ No newline at end of file diff --git a/Lang/K/M-bius-function b/Lang/K/M-bius-function new file mode 120000 index 0000000000..e4dca86d37 --- /dev/null +++ b/Lang/K/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/K \ No newline at end of file diff --git a/Lang/K/Substring b/Lang/K/Substring new file mode 120000 index 0000000000..002d50df4f --- /dev/null +++ b/Lang/K/Substring @@ -0,0 +1 @@ +../../Task/Substring/K \ No newline at end of file diff --git a/Lang/K/UTF-8-encode-and-decode b/Lang/K/UTF-8-encode-and-decode new file mode 120000 index 0000000000..f38c9e1894 --- /dev/null +++ b/Lang/K/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/K \ No newline at end of file diff --git a/Lang/K/Write-float-arrays-to-a-text-file b/Lang/K/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..2af99671ba --- /dev/null +++ b/Lang/K/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/K \ No newline at end of file diff --git a/Lang/Logo/Merge-and-aggregate-datasets b/Lang/Logo/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..f9a42bcf33 --- /dev/null +++ b/Lang/Logo/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/Logo \ No newline at end of file diff --git a/Lang/Lua/Check-input-device-is-a-terminal b/Lang/Lua/Check-input-device-is-a-terminal new file mode 120000 index 0000000000..fdc01bb562 --- /dev/null +++ b/Lang/Lua/Check-input-device-is-a-terminal @@ -0,0 +1 @@ +../../Task/Check-input-device-is-a-terminal/Lua \ No newline at end of file diff --git a/Lang/Lua/Parse-an-IP-Address b/Lang/Lua/Parse-an-IP-Address new file mode 120000 index 0000000000..aa0f24a93c --- /dev/null +++ b/Lang/Lua/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Lua \ No newline at end of file diff --git a/Lang/Lua/Ramer-Douglas-Peucker-line-simplification b/Lang/Lua/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..516d951928 --- /dev/null +++ b/Lang/Lua/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Lua \ No newline at end of file diff --git a/Lang/Lua/Update-a-configuration-file b/Lang/Lua/Update-a-configuration-file new file mode 120000 index 0000000000..75ad1d2a09 --- /dev/null +++ b/Lang/Lua/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Lua \ No newline at end of file diff --git a/Lang/M2000-Interpreter/00-LANG.txt b/Lang/M2000-Interpreter/00-LANG.txt index feda8eeb04..5e1cdf3a46 100644 --- a/Lang/M2000-Interpreter/00-LANG.txt +++ b/Lang/M2000-Interpreter/00-LANG.txt @@ -9,7 +9,7 @@ |gc=allowed |hopl=no }} -M2000 is an interpreter running on its own Environment written in Visual Basic 6, as an open source project and can be found in GitHub[https://github.com/M2000Interpreter/Version9]. Current version is 12, revision 13. See [[M2000 Interpreter Implementation]] +M2000 is an interpreter running on its own Environment written in Visual Basic 6, as an open source project and can be found in GitHub[https://github.com/M2000Interpreter/Version9]. Current version is 14, revision 4. See [[M2000 Interpreter Implementation]] {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} {{Language programming paradigm|Event-driven}} @@ -21,12 +21,68 @@ M2000 has two set of vocabularies, one with English identifiers and one with Gre M2000 start as an experimental interpreted language, using a Module in Module idea (like a Procedure in Procedure) where each inner Module is closed for modification, but open for expansion, by replacing code at run time. Source code executed as is, without second interpretation of a simple form, although block of code arranged for execution in a manner of consuming code (code which executed deleted, code in a loop kept as a copy for next iteration). +We can use BASIC type statement's. Although there are some differences. Like the FOR NEXT: + +SET SWITCHES "+FOR" +// WHY ? BECAUSE WHEN STEP IS POSITIVE (+1 HERE) +// WE GET ITERATION IF START VALUE IS LESS OR EQUAL THE LAST VALUE +FOR I=10 TO 0 + PRINT "NEVER PRINT - IS LIKE BASIC" +NEXT +SET SWITCHES "+DIM" +// WHY ? BECAUSE DIM MAKE AN ARRAY FROM 0 TO TOP VALUE (10) +DIM A(10)=1 +PRINT LEN(A())=11, A(0), A(10), "BASIC" + +SET SWITCHES "-FOR" ' THE DEFAULT +// WHY ? BECAUSE EVERY TIME ITERATE FROM START VALUE TO END VALUE +FOR I=10 TO 0 + PRINT "ALWAYS PRINT - IS NOT LIKE BASIC" +NEXT + +SET SWITCHES "-DIM" +// WHY ? BECAUSE DIM MAKE AN ARRAY N (10) ITEMS +DIM A(10)=1 +PRINT LEN(A())=10, A(0), A(9), "M2000" +DIM B(0 TO 10)=1 ' WE CAN DEFINE MIN AND MAX INDEX (CAN BE NEGATIVE) +PRINT LEN(B())=11, B(0), B(10), "M2000" + + Module's may be Global, or local to other modules. We can define global modules in a module, and all these definitions deleted at the end of module execution. Because we have to execute the definition of a module, we can select definition, or load definition before we call the module. Also modules can be part of object's of type Group. A module can't call itself unless we use Call module_name. The standard call is by using only the name of module. So from a module we can call local modules or global, but we can't call parent module (if isn't global). In a group we can call anything like a module plus the modules of the groups. +We can use labels and line numbers (each number is just a label). After a line number we can place statement. Static subs/functions have same scope as the module scope. Here SomethingElse() is like Module as a program, with own scope. + + +MODULE alfa { + FUNCTION SomethingElse(A, ZZ) { + =A/ZZ ' WE CAN'T READ Z HERE + } + 000 READ X + 001 Z=10 + 005 GOSUB alfa + 010 COMPUTE(&X) + 020 PRINT @MUL10(X), SomethingElse(@MUL10(X), Z) + 030 IF X<20 THEN 10 + 040 GOSUB alfa + 050 END + 060 SUB COMPUTE(&A) + 070 A++ + 080 Z++ // SIDE EFFECT + 090 END SUB + 100 FUNCTION MUL10(A) + 110 =A*Z + 120 END FUNCTION +alfa: + 130 PRINT "-------------------------" + 140 RETURN +} +alfa 14 + + We can change a inner module at the calling of a module, see the example: We call inner Beta in two stages. At the second stage we change inner Theta with Theta2. This is the decoration of Beta with Theta as Theta2. This is a temporary decoration because Beta after execution erase any new identifier including Theta. So each time we call Beta, statement Module Theta make this module unless a decoration stop it. ====English Vocabulary==== -Module Beta { +Module Beta { Module Theta (x){ Print "This is Theta, we get x=";x } diff --git a/Lang/M2000-Interpreter/ADFGVX-cipher b/Lang/M2000-Interpreter/ADFGVX-cipher new file mode 120000 index 0000000000..58053e0f2d --- /dev/null +++ b/Lang/M2000-Interpreter/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- b/Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- new file mode 120000 index 0000000000..0994290aa3 --- /dev/null +++ b/Lang/M2000-Interpreter/Apply-a-digital-filter-direct-form-II-transposed- @@ -0,0 +1 @@ +../../Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists b/Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..afa95add18 --- /dev/null +++ b/Lang/M2000-Interpreter/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Compare-length-of-two-strings b/Lang/M2000-Interpreter/Compare-length-of-two-strings new file mode 120000 index 0000000000..1726357b73 --- /dev/null +++ b/Lang/M2000-Interpreter/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/File-extension-is-in-extensions-list b/Lang/M2000-Interpreter/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..6d12e57411 --- /dev/null +++ b/Lang/M2000-Interpreter/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Greatest-subsequential-sum b/Lang/M2000-Interpreter/Greatest-subsequential-sum new file mode 120000 index 0000000000..5470dd7511 --- /dev/null +++ b/Lang/M2000-Interpreter/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Power-set b/Lang/M2000-Interpreter/Power-set new file mode 120000 index 0000000000..c99b047826 --- /dev/null +++ b/Lang/M2000-Interpreter/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Simple-turtle-graphics b/Lang/M2000-Interpreter/Simple-turtle-graphics new file mode 120000 index 0000000000..8bb4a18e49 --- /dev/null +++ b/Lang/M2000-Interpreter/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort b/Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..94b7b8369f --- /dev/null +++ b/Lang/M2000-Interpreter/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string b/Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..ca8f98d606 --- /dev/null +++ b/Lang/M2000-Interpreter/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/M2000-Interpreter \ No newline at end of file diff --git a/Lang/MACRO-11/Run-length-encoding b/Lang/MACRO-11/Run-length-encoding new file mode 120000 index 0000000000..3f700314e0 --- /dev/null +++ b/Lang/MACRO-11/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/MACRO-11 \ No newline at end of file diff --git a/Lang/MAD/Look-and-say-sequence b/Lang/MAD/Look-and-say-sequence new file mode 120000 index 0000000000..dbca6a6456 --- /dev/null +++ b/Lang/MAD/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/MAD \ No newline at end of file diff --git a/Lang/MSX-Basic/Evaluate-binomial-coefficients b/Lang/MSX-Basic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..806e2bfad2 --- /dev/null +++ b/Lang/MSX-Basic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/MSX-Basic \ No newline at end of file diff --git a/Lang/MUMPS/00-LANG.txt b/Lang/MUMPS/00-LANG.txt index cfb6ac9800..491ec139a6 100644 --- a/Lang/MUMPS/00-LANG.txt +++ b/Lang/MUMPS/00-LANG.txt @@ -1,14 +1,21 @@ {{language -|untyped=yes}} +|untyped=yes +|gc +|parampass| +}} + {{language programming paradigm|procedural}} -

Visit the Google group comp.lang.mumps for discussions about this language.

+

Visit the Google group/ Usenet newsgroupcomp.lang.mumps for discussions about this language.

Visit [[wp:MUMPS|Wikipedia]] for a general description.

See http://71.174.62.16/Demo/AnnoStd for details about the language.

-

Standard MUMPS has one data types (strings) and some dialects (Cache, MSM) add a second data type (objects). A variable can be unsubscripted or not, and the subscripted variables form a -sparse n-tree. MUMPS doesn't have traditional arrays, but has an array syntax that manipulates trees as if they were arrays, using indexing to access nodes of the tree. You can create a tree that can have unlimited levels of branching, with keys and values associated with each node in the tree. Similarly, while the language doesn't have lists, you can mimic lists by creating strings with a consistent character (or string) as a delimiter separating the entries. -The Cache dialect also supports explicit List operations and data structures. +

Standard MUMPS has one data type (strings) and some dialects (Cache, MSM, IRIS) add a second data type (objects). A variable can be unsubscripted or not, and the subscripted variables form a +sparse n-tree, or associative arrays or sparse multidimensional hierarchical key-value pair with keys as strings and values as strings. + +MUMPS doesn't have traditional arrays, but has an array syntax that manipulates trees as if they were arrays, using indexing to access nodes of the tree. You can create a tree that can have unlimited levels of branching, with keys and values associated with each node in the tree. Similarly, while the language doesn't have lists, you can mimic lists by creating strings with a consistent character (or string) as a delimiter separating the entries. + +The Cache and IRIS dialects also support explicit List operations and data structures as values.

\ No newline at end of file diff --git a/Lang/Maple/Pythagoras-tree b/Lang/Maple/Pythagoras-tree new file mode 120000 index 0000000000..0342fe2180 --- /dev/null +++ b/Lang/Maple/Pythagoras-tree @@ -0,0 +1 @@ +../../Task/Pythagoras-tree/Maple \ No newline at end of file diff --git a/Lang/Mathematica/00-LANG.txt b/Lang/Mathematica/00-LANG.txt index 5daf1eef81..15e81dd703 100644 --- a/Lang/Mathematica/00-LANG.txt +++ b/Lang/Mathematica/00-LANG.txt @@ -11,4 +11,4 @@ It is used in many scientific, engineering, mathematical and computing fields, a [[Category:Mathematical programming languages]] ==Todo== -[[Reports:Tasks_not_implemented_in_Mathematica]] \ No newline at end of file +[[Tasks not implemented in Mathematica]] \ No newline at end of file diff --git a/Lang/Mathematica/15-puzzle-solver b/Lang/Mathematica/15-puzzle-solver new file mode 120000 index 0000000000..c802cd3973 --- /dev/null +++ b/Lang/Mathematica/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/B-zier-curves-Intersections b/Lang/Mathematica/B-zier-curves-Intersections new file mode 120000 index 0000000000..85dc8fb4ae --- /dev/null +++ b/Lang/Mathematica/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sisyphus-sequence b/Lang/Mathematica/Sisyphus-sequence new file mode 120000 index 0000000000..82e0aee9dd --- /dev/null +++ b/Lang/Mathematica/Sisyphus-sequence @@ -0,0 +1 @@ +../../Task/Sisyphus-sequence/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sphenic-numbers b/Lang/Mathematica/Sphenic-numbers new file mode 120000 index 0000000000..c276d09072 --- /dev/null +++ b/Lang/Mathematica/Sphenic-numbers @@ -0,0 +1 @@ +../../Task/Sphenic-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Wagstaff-primes b/Lang/Mathematica/Wagstaff-primes new file mode 120000 index 0000000000..7e781a92a6 --- /dev/null +++ b/Lang/Mathematica/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Mathematica \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Evaluate-binomial-coefficients b/Lang/Minimal-BASIC/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..6ad0769264 --- /dev/null +++ b/Lang/Minimal-BASIC/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Miranda/Loops-Infinite b/Lang/Miranda/Loops-Infinite new file mode 120000 index 0000000000..8845df4b78 --- /dev/null +++ b/Lang/Miranda/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Miranda \ No newline at end of file diff --git a/Lang/Miranda/Run-length-encoding b/Lang/Miranda/Run-length-encoding new file mode 120000 index 0000000000..e0fd07015b --- /dev/null +++ b/Lang/Miranda/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Miranda \ No newline at end of file diff --git a/Lang/Modula-2/M-bius-function b/Lang/Modula-2/M-bius-function new file mode 120000 index 0000000000..e2d4a4a9b1 --- /dev/null +++ b/Lang/Modula-2/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Magic-constant b/Lang/Modula-2/Magic-constant new file mode 120000 index 0000000000..d6cf44baf4 --- /dev/null +++ b/Lang/Modula-2/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Map-range b/Lang/Modula-2/Map-range new file mode 120000 index 0000000000..d2da488e09 --- /dev/null +++ b/Lang/Modula-2/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification b/Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..ff583aca48 --- /dev/null +++ b/Lang/Modula-2/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Modula-2 \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Levenshtein-distance b/Lang/Nascom-BASIC/Levenshtein-distance new file mode 120000 index 0000000000..c821e59923 --- /dev/null +++ b/Lang/Nascom-BASIC/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nu/CSV-data-manipulation b/Lang/Nu/CSV-data-manipulation new file mode 120000 index 0000000000..212f9d037c --- /dev/null +++ b/Lang/Nu/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Nu \ No newline at end of file diff --git a/Lang/Nu/Department-numbers b/Lang/Nu/Department-numbers new file mode 120000 index 0000000000..bb0cfc31a5 --- /dev/null +++ b/Lang/Nu/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Nu \ No newline at end of file diff --git a/Lang/Nu/Determine-if-a-string-has-all-the-same-characters b/Lang/Nu/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..1b0a4160eb --- /dev/null +++ b/Lang/Nu/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Nu \ No newline at end of file diff --git a/Lang/Nu/File-extension-is-in-extensions-list b/Lang/Nu/File-extension-is-in-extensions-list new file mode 120000 index 0000000000..ee608b6863 --- /dev/null +++ b/Lang/Nu/File-extension-is-in-extensions-list @@ -0,0 +1 @@ +../../Task/File-extension-is-in-extensions-list/Nu \ No newline at end of file diff --git a/Lang/Nu/File-size-distribution b/Lang/Nu/File-size-distribution new file mode 120000 index 0000000000..2ee98ba338 --- /dev/null +++ b/Lang/Nu/File-size-distribution @@ -0,0 +1 @@ +../../Task/File-size-distribution/Nu \ No newline at end of file diff --git a/Lang/Nu/I-before-E-except-after-C b/Lang/Nu/I-before-E-except-after-C new file mode 120000 index 0000000000..3f6ace8c86 --- /dev/null +++ b/Lang/Nu/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Nu \ No newline at end of file diff --git a/Lang/Nu/Word-frequency b/Lang/Nu/Word-frequency new file mode 120000 index 0000000000..b6ff2592c2 --- /dev/null +++ b/Lang/Nu/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/Nu \ No newline at end of file diff --git a/Lang/OCaml/Anti-primes b/Lang/OCaml/Anti-primes new file mode 120000 index 0000000000..5c78fd8505 --- /dev/null +++ b/Lang/OCaml/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Attractive-numbers b/Lang/OCaml/Attractive-numbers new file mode 120000 index 0000000000..7813955dbc --- /dev/null +++ b/Lang/OCaml/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Cuban-primes b/Lang/OCaml/Cuban-primes new file mode 120000 index 0000000000..d69918cc8d --- /dev/null +++ b/Lang/OCaml/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/OCaml \ No newline at end of file diff --git a/Lang/OOC/00-LANG.txt b/Lang/OOC/00-LANG.txt index 6ab39964dc..65c190709f 100644 --- a/Lang/OOC/00-LANG.txt +++ b/Lang/OOC/00-LANG.txt @@ -1,2 +1,2 @@ {{stub}}{{language -|site=http://ooc-lang.org}} \ No newline at end of file +|site=https://ooc-lang.github.io/}} \ No newline at end of file diff --git a/Lang/OPL/00-LANG.txt b/Lang/OPL/00-LANG.txt index 8357c2d27a..5d7f1fba8f 100644 --- a/Lang/OPL/00-LANG.txt +++ b/Lang/OPL/00-LANG.txt @@ -1,3 +1,11 @@ {{stub}} {{language -|site=http://opl-dev.sourceforge.net/}} \ No newline at end of file +|site=http://opl-dev.sourceforge.net/}} + +'''OPL (Open Programming Language'''; formerly '''Organiser Programming Language)''' is a high-level programming language designed primarily for use on mobile devices, particularly those running the Psion Series 3 and Series 5 operating systems. Developed in the early 1990s, '''OPL''' was created to provide a simple yet powerful environment for application development on handheld devices, allowing users to create software that could leverage the unique features of these portable platforms. + +OPL is known for its ease of use, making it accessible to both novice and experienced programmers. The language features a syntax that is similar to [[BASIC]], which helps in rapid application development. It supports structured programming concepts, including variables, control structures, and functions, enabling developers to write clear and maintainable code. + +One of the key strengths of OPL is its ability to interact seamlessly with the underlying operating system, allowing developers to access device-specific features such as file management, user interface elements, and hardware capabilities. This makes OPL particularly suitable for creating productivity applications, games, and utilities tailored for mobile users. + +Despite its niche status, OPL has garnered a dedicated community of enthusiasts and developers who continue to explore its capabilities and create innovative applications. As mobile computing continues to evolve, OPL remains a notable example of early efforts to bring programming to handheld devices, showcasing the potential of portable technology in software development. \ No newline at end of file diff --git a/Lang/OPL/100-doors b/Lang/OPL/100-doors new file mode 120000 index 0000000000..a3b7e045e6 --- /dev/null +++ b/Lang/OPL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/OPL \ No newline at end of file diff --git a/Lang/OPL/Arithmetic-Integer b/Lang/OPL/Arithmetic-Integer new file mode 120000 index 0000000000..dfcb743d43 --- /dev/null +++ b/Lang/OPL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/OPL \ No newline at end of file diff --git a/Lang/OPL/Arrays b/Lang/OPL/Arrays new file mode 120000 index 0000000000..f57347887c --- /dev/null +++ b/Lang/OPL/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/OPL \ No newline at end of file diff --git a/Lang/OPL/Character-codes b/Lang/OPL/Character-codes new file mode 120000 index 0000000000..2dac3156b8 --- /dev/null +++ b/Lang/OPL/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/OPL \ No newline at end of file diff --git a/Lang/OPL/Comments b/Lang/OPL/Comments new file mode 120000 index 0000000000..8aec78d8aa --- /dev/null +++ b/Lang/OPL/Comments @@ -0,0 +1 @@ +../../Task/Comments/OPL \ No newline at end of file diff --git a/Lang/OPL/Compare-length-of-two-strings b/Lang/OPL/Compare-length-of-two-strings new file mode 120000 index 0000000000..c36f1e31fc --- /dev/null +++ b/Lang/OPL/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/OPL \ No newline at end of file diff --git a/Lang/OPL/Copy-a-string b/Lang/OPL/Copy-a-string new file mode 120000 index 0000000000..76609905e5 --- /dev/null +++ b/Lang/OPL/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/OPL \ No newline at end of file diff --git a/Lang/OPL/Draw-a-clock b/Lang/OPL/Draw-a-clock new file mode 120000 index 0000000000..438c8aadf3 --- /dev/null +++ b/Lang/OPL/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/OPL \ No newline at end of file diff --git a/Lang/OPL/Draw-a-pixel b/Lang/OPL/Draw-a-pixel new file mode 120000 index 0000000000..d5c6ecea21 --- /dev/null +++ b/Lang/OPL/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/OPL \ No newline at end of file diff --git a/Lang/OPL/Hello-world-Text b/Lang/OPL/Hello-world-Text new file mode 120000 index 0000000000..a870057a16 --- /dev/null +++ b/Lang/OPL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/OPL \ No newline at end of file diff --git a/Lang/OPL/Program-termination b/Lang/OPL/Program-termination new file mode 120000 index 0000000000..8287761646 --- /dev/null +++ b/Lang/OPL/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/OPL \ No newline at end of file diff --git a/Lang/OPL/String-prepend b/Lang/OPL/String-prepend new file mode 120000 index 0000000000..78cb69646e --- /dev/null +++ b/Lang/OPL/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/OPL \ No newline at end of file diff --git a/Lang/OPL/User-input-Text b/Lang/OPL/User-input-Text new file mode 120000 index 0000000000..ad39694040 --- /dev/null +++ b/Lang/OPL/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/OPL \ No newline at end of file diff --git a/Lang/Objeck/Copy-stdin-to-stdout b/Lang/Objeck/Copy-stdin-to-stdout new file mode 120000 index 0000000000..b358bbac43 --- /dev/null +++ b/Lang/Objeck/Copy-stdin-to-stdout @@ -0,0 +1 @@ +../../Task/Copy-stdin-to-stdout/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Distributed-programming b/Lang/Objeck/Distributed-programming new file mode 120000 index 0000000000..728f38ee28 --- /dev/null +++ b/Lang/Objeck/Distributed-programming @@ -0,0 +1 @@ +../../Task/Distributed-programming/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Floyds-triangle b/Lang/Objeck/Floyds-triangle new file mode 120000 index 0000000000..743553b677 --- /dev/null +++ b/Lang/Objeck/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Generate-lower-case-ASCII-alphabet b/Lang/Objeck/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..92f0212a12 --- /dev/null +++ b/Lang/Objeck/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Hello-world-Standard-error b/Lang/Objeck/Hello-world-Standard-error new file mode 120000 index 0000000000..49d3f16aa6 --- /dev/null +++ b/Lang/Objeck/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Knuth-shuffle b/Lang/Objeck/Knuth-shuffle new file mode 120000 index 0000000000..a7bb43880d --- /dev/null +++ b/Lang/Objeck/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Mad-Libs b/Lang/Objeck/Mad-Libs new file mode 120000 index 0000000000..39f19ea059 --- /dev/null +++ b/Lang/Objeck/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Multiplication-tables b/Lang/Objeck/Multiplication-tables new file mode 120000 index 0000000000..3bad27bce2 --- /dev/null +++ b/Lang/Objeck/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Roman-numerals-Decode b/Lang/Objeck/Roman-numerals-Decode new file mode 120000 index 0000000000..bd8b56a721 --- /dev/null +++ b/Lang/Objeck/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks b/Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..7e77326aa1 --- /dev/null +++ b/Lang/Objeck/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Strip-a-set-of-characters-from-a-string b/Lang/Objeck/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..f651f9d55d --- /dev/null +++ b/Lang/Objeck/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Objeck \ No newline at end of file diff --git a/Lang/Odin/Euler-method b/Lang/Odin/Euler-method new file mode 120000 index 0000000000..2085f38551 --- /dev/null +++ b/Lang/Odin/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Odin \ No newline at end of file diff --git a/Lang/Odin/Execute-Brain- b/Lang/Odin/Execute-Brain- new file mode 120000 index 0000000000..748dbb9c99 --- /dev/null +++ b/Lang/Odin/Execute-Brain- @@ -0,0 +1 @@ +../../Task/Execute-Brain-/Odin \ No newline at end of file diff --git a/Lang/Odin/Fractran b/Lang/Odin/Fractran new file mode 120000 index 0000000000..5bd1840a6a --- /dev/null +++ b/Lang/Odin/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Odin \ No newline at end of file diff --git a/Lang/Odin/Hailstone-sequence b/Lang/Odin/Hailstone-sequence new file mode 120000 index 0000000000..678ea867f0 --- /dev/null +++ b/Lang/Odin/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Odin \ No newline at end of file diff --git a/Lang/Odin/Hello-world-Graphical b/Lang/Odin/Hello-world-Graphical new file mode 120000 index 0000000000..00108512b1 --- /dev/null +++ b/Lang/Odin/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Odin \ No newline at end of file diff --git a/Lang/Odin/Primality-by-trial-division b/Lang/Odin/Primality-by-trial-division new file mode 120000 index 0000000000..8e356363dd --- /dev/null +++ b/Lang/Odin/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Odin \ No newline at end of file diff --git a/Lang/Odin/Runge-Kutta-method b/Lang/Odin/Runge-Kutta-method new file mode 120000 index 0000000000..1b9162c995 --- /dev/null +++ b/Lang/Odin/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Odin \ No newline at end of file diff --git a/Lang/Odin/Strip-a-set-of-characters-from-a-string b/Lang/Odin/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..b76ef81d13 --- /dev/null +++ b/Lang/Odin/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Odin \ No newline at end of file diff --git a/Lang/Odin/Unicode-variable-names b/Lang/Odin/Unicode-variable-names new file mode 120000 index 0000000000..f070da9637 --- /dev/null +++ b/Lang/Odin/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Odin \ No newline at end of file diff --git a/Lang/Odin/Write-entire-file b/Lang/Odin/Write-entire-file new file mode 120000 index 0000000000..53b4243bae --- /dev/null +++ b/Lang/Odin/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Odin \ No newline at end of file diff --git a/Lang/Ol/Runge-Kutta-method b/Lang/Ol/Runge-Kutta-method new file mode 120000 index 0000000000..55f8d1bf18 --- /dev/null +++ b/Lang/Ol/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Ol \ No newline at end of file diff --git a/Lang/OxygenBasic/Evaluate-binomial-coefficients b/Lang/OxygenBasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..2fc6117dc9 --- /dev/null +++ b/Lang/OxygenBasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/OxygenBasic \ No newline at end of file diff --git a/Lang/PARI-GP/Attractive-numbers b/Lang/PARI-GP/Attractive-numbers new file mode 120000 index 0000000000..9c5ab01706 --- /dev/null +++ b/Lang/PARI-GP/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Disarium-numbers b/Lang/PARI-GP/Disarium-numbers new file mode 120000 index 0000000000..e21e95674b --- /dev/null +++ b/Lang/PARI-GP/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..497a956889 --- /dev/null +++ b/Lang/PARI-GP/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/M-bius-function b/Lang/PHP/M-bius-function new file mode 120000 index 0000000000..6f4e3a47bb --- /dev/null +++ b/Lang/PHP/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PHP \ No newline at end of file diff --git a/Lang/PHP/Magic-constant b/Lang/PHP/Magic-constant new file mode 120000 index 0000000000..b67d20fb19 --- /dev/null +++ b/Lang/PHP/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/PHP \ No newline at end of file diff --git a/Lang/PHP/Map-range b/Lang/PHP/Map-range new file mode 120000 index 0000000000..07d5696e85 --- /dev/null +++ b/Lang/PHP/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/PHP \ No newline at end of file diff --git a/Lang/PL-I-80/Additive-primes b/Lang/PL-I-80/Additive-primes new file mode 120000 index 0000000000..a065cd3d8e --- /dev/null +++ b/Lang/PL-I-80/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/PL-I-80 \ No newline at end of file diff --git a/Lang/Pascal/Date-manipulation b/Lang/Pascal/Date-manipulation new file mode 120000 index 0000000000..9edece533b --- /dev/null +++ b/Lang/Pascal/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/FizzBuzz b/Lang/Pascal/FizzBuzz deleted file mode 120000 index 786dae3647..0000000000 --- a/Lang/Pascal/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Levenshtein-distance b/Lang/Pascal/Levenshtein-distance deleted file mode 120000 index aa9f13dc0f..0000000000 --- a/Lang/Pascal/Levenshtein-distance +++ /dev/null @@ -1 +0,0 @@ -../../Task/Levenshtein-distance/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Map-range b/Lang/Pascal/Map-range deleted file mode 120000 index 71c05c40ec..0000000000 --- a/Lang/Pascal/Map-range +++ /dev/null @@ -1 +0,0 @@ -../../Task/Map-range/Pascal \ No newline at end of file diff --git a/Lang/PascalABC.NET/Additive-primes b/Lang/PascalABC.NET/Additive-primes new file mode 120000 index 0000000000..0022732e2e --- /dev/null +++ b/Lang/PascalABC.NET/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Amicable-pairs b/Lang/PascalABC.NET/Amicable-pairs new file mode 120000 index 0000000000..e8f5a09925 --- /dev/null +++ b/Lang/PascalABC.NET/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pancake-numbers b/Lang/PascalABC.NET/Pancake-numbers new file mode 120000 index 0000000000..b4faf1b68d --- /dev/null +++ b/Lang/PascalABC.NET/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pangram-checker b/Lang/PascalABC.NET/Pangram-checker new file mode 120000 index 0000000000..114e870600 --- /dev/null +++ b/Lang/PascalABC.NET/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Paraffins b/Lang/PascalABC.NET/Paraffins new file mode 120000 index 0000000000..bafd6e0939 --- /dev/null +++ b/Lang/PascalABC.NET/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Parallel-calculations b/Lang/PascalABC.NET/Parallel-calculations new file mode 120000 index 0000000000..e88e92c1df --- /dev/null +++ b/Lang/PascalABC.NET/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm b/Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..c4ae7949cd --- /dev/null +++ b/Lang/PascalABC.NET/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes b/Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..eb7a5e97f7 --- /dev/null +++ b/Lang/PascalABC.NET/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pascal-matrix-generation b/Lang/PascalABC.NET/Pascal-matrix-generation new file mode 120000 index 0000000000..c8097eca88 --- /dev/null +++ b/Lang/PascalABC.NET/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pascals-triangle-Puzzle b/Lang/PascalABC.NET/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..8106a5db3a --- /dev/null +++ b/Lang/PascalABC.NET/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pathological-floating-point-problems b/Lang/PascalABC.NET/Pathological-floating-point-problems new file mode 120000 index 0000000000..7eaa34e4a8 --- /dev/null +++ b/Lang/PascalABC.NET/Pathological-floating-point-problems @@ -0,0 +1 @@ +../../Task/Pathological-floating-point-problems/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Pells-equation b/Lang/PascalABC.NET/Pells-equation new file mode 120000 index 0000000000..1729f4ebb8 --- /dev/null +++ b/Lang/PascalABC.NET/Pells-equation @@ -0,0 +1 @@ +../../Task/Pells-equation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Perfect-shuffle b/Lang/PascalABC.NET/Perfect-shuffle new file mode 120000 index 0000000000..5ea5d5cf28 --- /dev/null +++ b/Lang/PascalABC.NET/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Perfect-totient-numbers b/Lang/PascalABC.NET/Perfect-totient-numbers new file mode 120000 index 0000000000..8aae312612 --- /dev/null +++ b/Lang/PascalABC.NET/Perfect-totient-numbers @@ -0,0 +1 @@ +../../Task/Perfect-totient-numbers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Permutation-test b/Lang/PascalABC.NET/Permutation-test new file mode 120000 index 0000000000..38efc59733 --- /dev/null +++ b/Lang/PascalABC.NET/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/PascalABC.NET \ No newline at end of file diff --git a/Lang/Perl/Execute-Computer-Zero b/Lang/Perl/Execute-Computer-Zero new file mode 120000 index 0000000000..f5f02da865 --- /dev/null +++ b/Lang/Perl/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/Perl \ No newline at end of file diff --git a/Lang/Prolog/Evaluate-binomial-coefficients b/Lang/Prolog/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..15602e690b --- /dev/null +++ b/Lang/Prolog/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Prolog \ No newline at end of file diff --git a/Lang/Python/Im-a-software-engineer-get-me-out-of-here b/Lang/Python/Im-a-software-engineer-get-me-out-of-here new file mode 120000 index 0000000000..d238ff00d2 --- /dev/null +++ b/Lang/Python/Im-a-software-engineer-get-me-out-of-here @@ -0,0 +1 @@ +../../Task/Im-a-software-engineer-get-me-out-of-here/Python \ No newline at end of file diff --git a/Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..9997b73880 --- /dev/null +++ b/Lang/Python/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Python \ No newline at end of file diff --git a/Lang/Python/Square-form-factorization b/Lang/Python/Square-form-factorization new file mode 120000 index 0000000000..38da301a59 --- /dev/null +++ b/Lang/Python/Square-form-factorization @@ -0,0 +1 @@ +../../Task/Square-form-factorization/Python \ No newline at end of file diff --git a/Lang/Python/Wasteful-equidigital-and-frugal-numbers b/Lang/Python/Wasteful-equidigital-and-frugal-numbers new file mode 120000 index 0000000000..c89de12312 --- /dev/null +++ b/Lang/Python/Wasteful-equidigital-and-frugal-numbers @@ -0,0 +1 @@ +../../Task/Wasteful-equidigital-and-frugal-numbers/Python \ No newline at end of file diff --git a/Lang/Q/Euler-method b/Lang/Q/Euler-method new file mode 120000 index 0000000000..093ad80e13 --- /dev/null +++ b/Lang/Q/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Q \ No newline at end of file diff --git a/Lang/QBasic/Evaluate-binomial-coefficients b/Lang/QBasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..86b00c5e75 --- /dev/null +++ b/Lang/QBasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Map-range b/Lang/QBasic/Map-range new file mode 120000 index 0000000000..be9705365d --- /dev/null +++ b/Lang/QBasic/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/QBasic \ No newline at end of file diff --git a/Lang/Quackery/00-LANG.txt b/Lang/Quackery/00-LANG.txt index c6437e7156..7eab14d4c5 100644 --- a/Lang/Quackery/00-LANG.txt +++ b/Lang/Quackery/00-LANG.txt @@ -29,4 +29,26 @@ Conceptually, the Quackery engine is a stack based processor which does not have Quackery is not intended to be a super-fast enterprise-level language; it is intended as an exploration of a novel architecture, and a fun programming project straight out of a textbook. (The textbook is included in the download.) -Why not try your hand at one of the [[Tasks not implemented in Quackery]]. \ No newline at end of file +Why not try your hand at one of the [[Tasks not implemented in Quackery]]. + +== Selected Quackery Examples == + +Rosetta Code has hundreds of Quackery examples. Here’s a curated set that showcases some of Quackery's strengths: + +* [[99 bottles of beer#Quackery|99 bottles of beer]] Shows simple, readable control flow and output. +* [[Gosper's hack#Quackery|Gosper's hack]] A nifty one-liner. +* [[Temperature conversion#Quackery|Temperature conversion]] Co-operative brevity. +* [[Balanced brackets#Quackery|Balanced brackets]] Demonstrates natural stack use for classic problems. +* [[Loops/Increment loop index within loop body#Quackery|Increment loop index within loop body]] You want a loop that's indexed ''and'' indefinite? Here's how. +* [[Quine#Quackery|Quine]] Illustrates code-as-data and quotation handling. +* [[Bacon cipher#Quackery|Bacon cipher]] Highlights clear text manipulation with minimal code. +* [[Permutations#Quackery|Permutations]] Uses recursion and stack shuffling expressively. +* [[Sorting algorithms/Insertion sort#Quackery|Insertion sort]] Demonstrates some built-in higher-order functions. +* [[Higher-order functions#Quackery|Higher-order functions]] Defining and using fold, map, and filter. +* [[Conway's Game of Life#Quackery|Conway's Game of Life]] Handles structured simulation with clarity. +* [[Execute Brain****#Quackery|Brainf*** interpreter]] Demonstrates interpreter-building and extensibility. +* [[Dinesman's multiple-dwelling problem#Quackery|Dinesman's multiple-dwelling problem]] Crafting a Domain Specific Language. + +== The Task that Nearly Broke the Author == + +* [[Zeckendorf arithmetic#Quackery|Zeckendorf arithmetic]] Forget everything you thought you knew about arithmetic… \ No newline at end of file diff --git a/Lang/Quackery/Dice-game-probabilities b/Lang/Quackery/Dice-game-probabilities new file mode 120000 index 0000000000..87d28dc799 --- /dev/null +++ b/Lang/Quackery/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..1f9736ed88 --- /dev/null +++ b/Lang/Quackery/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Two-bullet-roulette b/Lang/Quackery/Two-bullet-roulette new file mode 120000 index 0000000000..24f00326c1 --- /dev/null +++ b/Lang/Quackery/Two-bullet-roulette @@ -0,0 +1 @@ +../../Task/Two-bullet-roulette/Quackery \ No newline at end of file diff --git a/Lang/R/Camel-case-and-snake-case b/Lang/R/Camel-case-and-snake-case new file mode 120000 index 0000000000..e76dd2d66a --- /dev/null +++ b/Lang/R/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/R \ No newline at end of file diff --git a/Lang/R/Determine-sentence-type b/Lang/R/Determine-sentence-type new file mode 120000 index 0000000000..b5e3ac4763 --- /dev/null +++ b/Lang/R/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/R \ No newline at end of file diff --git a/Lang/R/Disarium-numbers b/Lang/R/Disarium-numbers new file mode 120000 index 0000000000..233dce846c --- /dev/null +++ b/Lang/R/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/R \ No newline at end of file diff --git a/Lang/R/Display-a-linear-combination b/Lang/R/Display-a-linear-combination new file mode 120000 index 0000000000..c292ce3aec --- /dev/null +++ b/Lang/R/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/R \ No newline at end of file diff --git a/Lang/R/Draw-a-cuboid b/Lang/R/Draw-a-cuboid new file mode 120000 index 0000000000..b0d15ca88e --- /dev/null +++ b/Lang/R/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/R \ No newline at end of file diff --git a/Lang/R/Dutch-national-flag-problem b/Lang/R/Dutch-national-flag-problem new file mode 120000 index 0000000000..422342365f --- /dev/null +++ b/Lang/R/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/R \ No newline at end of file diff --git a/Lang/R/Factorions b/Lang/R/Factorions new file mode 120000 index 0000000000..351fcd0d06 --- /dev/null +++ b/Lang/R/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/R \ No newline at end of file diff --git a/Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases b/Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases new file mode 120000 index 0000000000..1adf6989fe --- /dev/null +++ b/Lang/R/Find-palindromic-numbers-in-both-binary-and-ternary-bases @@ -0,0 +1 @@ +../../Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/R \ No newline at end of file diff --git a/Lang/R/Halt-and-catch-fire b/Lang/R/Halt-and-catch-fire new file mode 120000 index 0000000000..f754df332d --- /dev/null +++ b/Lang/R/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/R \ No newline at end of file diff --git a/Lang/R/Hex-words b/Lang/R/Hex-words new file mode 120000 index 0000000000..f38acbfb8b --- /dev/null +++ b/Lang/R/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/R \ No newline at end of file diff --git a/Lang/R/Kernighans-large-earthquake-problem b/Lang/R/Kernighans-large-earthquake-problem new file mode 120000 index 0000000000..e4a703f050 --- /dev/null +++ b/Lang/R/Kernighans-large-earthquake-problem @@ -0,0 +1 @@ +../../Task/Kernighans-large-earthquake-problem/R \ No newline at end of file diff --git a/Lang/R/Munchausen-numbers b/Lang/R/Munchausen-numbers new file mode 120000 index 0000000000..aa4d45945f --- /dev/null +++ b/Lang/R/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/R \ No newline at end of file diff --git a/Lang/R/Old-Russian-measure-of-length b/Lang/R/Old-Russian-measure-of-length new file mode 120000 index 0000000000..10e03acc09 --- /dev/null +++ b/Lang/R/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/R \ No newline at end of file diff --git a/Lang/R/Semordnilap b/Lang/R/Semordnilap new file mode 120000 index 0000000000..8ef388caef --- /dev/null +++ b/Lang/R/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/R \ No newline at end of file diff --git a/Lang/R/Sort-numbers-lexicographically b/Lang/R/Sort-numbers-lexicographically new file mode 120000 index 0000000000..77a76317d2 --- /dev/null +++ b/Lang/R/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/R \ No newline at end of file diff --git a/Lang/R/Strip-a-set-of-characters-from-a-string b/Lang/R/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..b83d60c994 --- /dev/null +++ b/Lang/R/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/R \ No newline at end of file diff --git a/Lang/REXX/00-LANG.txt b/Lang/REXX/00-LANG.txt index a1abf9f554..fd028fe2bc 100644 --- a/Lang/REXX/00-LANG.txt +++ b/Lang/REXX/00-LANG.txt @@ -28,12 +28,17 @@ The '''REXX''' language was influenced by the computer programming languages: &n Using Classic REXX closely resembles pseudo code and many languages like Basic or Julia. Experienced programmers should have no problem reading REXX code and translating it to other languages.
Some items that might differ from what you are familiar with.
-* No data types, no declarations, everything is string. +* Caseless, fully free format. +* Code blocks delimited by do...end, no brackets (){}. +* Usual control structures present: do...by...to, do while/until, select, leave, iterate. +* No data types, no declarations, everything is string. String functions such as Left() or Substr() may be applied on numbers. +* All arithmetic is decimal based, not binary. So stuff like bit shifting or multiply/divide by 2 using exponent add/subtract does not apply. * Exponentiation is designated by '**' thus x^2 = x**2. * Integer division is designated by '%' thus 13%3 = 4. * Modulo division (remainder) is designated by '//' thus 13//3 = 1 ('13 mod 3'). * Arrays (here called 'stems') are designated by something like 'stem.a.b. etc' (stem = name array; a, b etc any value; 'associative arrays'). * Precision is unlimited (default 9 digits), but you have to specify it yourself ('numeric digits nn'). +* Parameter passing always by value. Stems cannot be passed, but must be made available with 'expose'. Versions of REXX: * '''[[wp:ARexx|ARexx]]'''   is a classic REXX implementation (with extensions) for the AmigaOS,   given in bundle since AmigaOS 2.   (Regina REXX has specific support for the extended functions that were introduced in ARexx.)   ARexx was written in 1987 by William S. Hawes. @@ -45,7 +50,7 @@ Some items that might differ from what you are familiar with.
* '''[[CRX REXX]]'''   (Compact REXX) is a classic REXX first written by Dr. Brian Marks. -* '''[[CTC REXX]]'''   is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation,   a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). The last version was published in 1996. CTC doesn't exist anymore. +* '''[[REXX/2]]'''   is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation,   a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). The last version was published in 1996. Company CTC doesn't exist anymore. * '''[[KEXX]]'''   is a subset of REXX that is bundled with KEDIT and written by Keven J. Kearney of Mansfield Software Group, Inc., a license is required to use this product.   KEXX only executes under the KEDIT licensed product.   KEDIT is an XEDIT clone (an editor from IBM for VM/CMS program products). @@ -121,16 +126,7 @@ Some items that might differ from what you are familiar with.
* [http://www.rexxla.org The Rexx Language Association - www.rexxla.org] * [http://regina-rexx.sourceforge.net/index.html Regina Rexx Interpreter] * [http://www.kedit.com/ Mansfield Software Group, Inc. (KEDIT)] -* [http://www.quercus-sys.com/ Personal REXX, Quercus Systems] -* [http://www.commandtechnology.com/ CTC Command Technology] * [http://www.rexxla.org/ CRX Open Source (right column side)] -* [http://www.kilowattsoftware.com/r4Page.htm R4, Kilowatt Software] -* [http://www.kilowattsoftware.com/rooPage.htm ROO, Kilowatt Software] -* [http://publib.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/HCSE2C00/CCONTENTS?SHELF=hcsh2ab0&DN=SC24-6221-00&DT=20090724140455 z/VM V6R1 REXX/VM Reference] -* [http://publib.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/HCSB3C00/CCONTENTS?SHELF=hcsh2ab0&DN=SC24-6222-00&DT=20090724131829 z/VM V6R1 REXX/VM User's Guide] -* [http://www.rexxinfo.org/html/rexxinfo1.html#Rexx-Manuals {many references to REXX manuals}] - - == Rosetta Code tasks not implemented in REXX == [[Reports:Tasks_not_implemented_in_REXX]] \ No newline at end of file diff --git a/Lang/REXX/Magic-constant b/Lang/REXX/Magic-constant new file mode 120000 index 0000000000..13d81a62dd --- /dev/null +++ b/Lang/REXX/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/REXX \ No newline at end of file diff --git a/Lang/REXX/Primes---allocate-descendants-to-their-ancestors b/Lang/REXX/Primes---allocate-descendants-to-their-ancestors new file mode 120000 index 0000000000..e6293c9090 --- /dev/null +++ b/Lang/REXX/Primes---allocate-descendants-to-their-ancestors @@ -0,0 +1 @@ +../../Task/Primes---allocate-descendants-to-their-ancestors/REXX \ No newline at end of file diff --git a/Lang/REXX/Ramanujan-primes-twins b/Lang/REXX/Ramanujan-primes-twins new file mode 120000 index 0000000000..09da3d7f76 --- /dev/null +++ b/Lang/REXX/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/REXX \ No newline at end of file diff --git a/Lang/REXX/Sequence-of-primorial-primes b/Lang/REXX/Sequence-of-primorial-primes new file mode 120000 index 0000000000..cd4ebe8c73 --- /dev/null +++ b/Lang/REXX/Sequence-of-primorial-primes @@ -0,0 +1 @@ +../../Task/Sequence-of-primorial-primes/REXX \ No newline at end of file diff --git a/Lang/REXX/Sieve-of-Pritchard b/Lang/REXX/Sieve-of-Pritchard new file mode 120000 index 0000000000..601b18d906 --- /dev/null +++ b/Lang/REXX/Sieve-of-Pritchard @@ -0,0 +1 @@ +../../Task/Sieve-of-Pritchard/REXX \ No newline at end of file diff --git a/Lang/Raku/Simple-turtle-graphics b/Lang/Raku/Simple-turtle-graphics new file mode 120000 index 0000000000..496cec69f4 --- /dev/null +++ b/Lang/Raku/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/Raku \ No newline at end of file diff --git a/Lang/RapidQ/Levenshtein-distance b/Lang/RapidQ/Levenshtein-distance new file mode 120000 index 0000000000..43ee94415c --- /dev/null +++ b/Lang/RapidQ/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/M-bius-function b/Lang/RapidQ/M-bius-function new file mode 120000 index 0000000000..72bc6192fb --- /dev/null +++ b/Lang/RapidQ/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Map-range b/Lang/RapidQ/Map-range new file mode 120000 index 0000000000..a3da155381 --- /dev/null +++ b/Lang/RapidQ/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/RapidQ \ No newline at end of file diff --git a/Lang/Refal/Loops-Infinite b/Lang/Refal/Loops-Infinite new file mode 120000 index 0000000000..536c01c9bd --- /dev/null +++ b/Lang/Refal/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Refal \ No newline at end of file diff --git a/Lang/Refal/Power-set b/Lang/Refal/Power-set new file mode 120000 index 0000000000..f50da086ad --- /dev/null +++ b/Lang/Refal/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Refal \ No newline at end of file diff --git a/Lang/Refal/Run-length-encoding b/Lang/Refal/Run-length-encoding new file mode 120000 index 0000000000..afeb7091c3 --- /dev/null +++ b/Lang/Refal/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Refal \ No newline at end of file diff --git a/Lang/Refal/Strip-comments-from-a-string b/Lang/Refal/Strip-comments-from-a-string new file mode 120000 index 0000000000..6f86213c31 --- /dev/null +++ b/Lang/Refal/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Refal \ No newline at end of file diff --git a/Lang/Rust/Ascending-primes b/Lang/Rust/Ascending-primes new file mode 120000 index 0000000000..84fdafe351 --- /dev/null +++ b/Lang/Rust/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Rust \ No newline at end of file diff --git a/Lang/Rust/B-zier-curves-Intersections b/Lang/Rust/B-zier-curves-Intersections new file mode 120000 index 0000000000..732ede6e4e --- /dev/null +++ b/Lang/Rust/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Rust \ No newline at end of file diff --git a/Lang/Rust/Bifid-cipher b/Lang/Rust/Bifid-cipher new file mode 120000 index 0000000000..8ddce2026b --- /dev/null +++ b/Lang/Rust/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Bioinformatics-Global-alignment b/Lang/Rust/Bioinformatics-Global-alignment new file mode 120000 index 0000000000..3bbbc3b358 --- /dev/null +++ b/Lang/Rust/Bioinformatics-Global-alignment @@ -0,0 +1 @@ +../../Task/Bioinformatics-Global-alignment/Rust \ No newline at end of file diff --git a/Lang/Rust/Blum-integer b/Lang/Rust/Blum-integer new file mode 120000 index 0000000000..7a0e8a69ae --- /dev/null +++ b/Lang/Rust/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Rust \ No newline at end of file diff --git a/Lang/Rust/Boyer-Moore-string-search b/Lang/Rust/Boyer-Moore-string-search new file mode 120000 index 0000000000..b70383335b --- /dev/null +++ b/Lang/Rust/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Rust \ No newline at end of file diff --git a/Lang/Rust/Calendar---for-REAL-programmers b/Lang/Rust/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..5bd1cebf14 --- /dev/null +++ b/Lang/Rust/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Rust \ No newline at end of file diff --git a/Lang/Rust/Compare-sorting-algorithms-performance b/Lang/Rust/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..7676ca3dd8 --- /dev/null +++ b/Lang/Rust/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-AST-interpreter b/Lang/Rust/Compiler-AST-interpreter new file mode 120000 index 0000000000..2028e35209 --- /dev/null +++ b/Lang/Rust/Compiler-AST-interpreter @@ -0,0 +1 @@ +../../Task/Compiler-AST-interpreter/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-code-generator b/Lang/Rust/Compiler-code-generator new file mode 120000 index 0000000000..fa460708f3 --- /dev/null +++ b/Lang/Rust/Compiler-code-generator @@ -0,0 +1 @@ +../../Task/Compiler-code-generator/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-lexical-analyzer b/Lang/Rust/Compiler-lexical-analyzer new file mode 120000 index 0000000000..b603fdc69a --- /dev/null +++ b/Lang/Rust/Compiler-lexical-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-lexical-analyzer/Rust \ No newline at end of file diff --git a/Lang/Rust/Compiler-syntax-analyzer b/Lang/Rust/Compiler-syntax-analyzer new file mode 120000 index 0000000000..4fa6fc40a8 --- /dev/null +++ b/Lang/Rust/Compiler-syntax-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-syntax-analyzer/Rust \ No newline at end of file diff --git a/Lang/Rust/Cyclotomic-polynomial b/Lang/Rust/Cyclotomic-polynomial new file mode 120000 index 0000000000..8ff16fabbb --- /dev/null +++ b/Lang/Rust/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/Rust \ No newline at end of file diff --git a/Lang/Rust/Descending-primes b/Lang/Rust/Descending-primes new file mode 120000 index 0000000000..fc953fbf4e --- /dev/null +++ b/Lang/Rust/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Rust \ No newline at end of file diff --git a/Lang/Rust/Doubly-linked-list-Definition b/Lang/Rust/Doubly-linked-list-Definition new file mode 120000 index 0000000000..9eb9054258 --- /dev/null +++ b/Lang/Rust/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Rust \ No newline at end of file diff --git a/Lang/Rust/Doubly-linked-list-Traversal b/Lang/Rust/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..b44bd60c3c --- /dev/null +++ b/Lang/Rust/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Rust \ No newline at end of file diff --git a/Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..f6d4ecb90e --- /dev/null +++ b/Lang/Rust/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Faulhabers-formula b/Lang/Rust/Faulhabers-formula new file mode 120000 index 0000000000..f7691b3566 --- /dev/null +++ b/Lang/Rust/Faulhabers-formula @@ -0,0 +1 @@ +../../Task/Faulhabers-formula/Rust \ No newline at end of file diff --git a/Lang/Rust/Graph-colouring b/Lang/Rust/Graph-colouring new file mode 120000 index 0000000000..acb44a12b7 --- /dev/null +++ b/Lang/Rust/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/Rust \ No newline at end of file diff --git a/Lang/Rust/Hex-words b/Lang/Rust/Hex-words new file mode 120000 index 0000000000..9322882ab9 --- /dev/null +++ b/Lang/Rust/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/Rust \ No newline at end of file diff --git a/Lang/Rust/Kosaraju b/Lang/Rust/Kosaraju new file mode 120000 index 0000000000..69a0c5ef3e --- /dev/null +++ b/Lang/Rust/Kosaraju @@ -0,0 +1 @@ +../../Task/Kosaraju/Rust \ No newline at end of file diff --git a/Lang/Rust/Latin-Squares-in-reduced-form b/Lang/Rust/Latin-Squares-in-reduced-form new file mode 120000 index 0000000000..17d284a00f --- /dev/null +++ b/Lang/Rust/Latin-Squares-in-reduced-form @@ -0,0 +1 @@ +../../Task/Latin-Squares-in-reduced-form/Rust \ No newline at end of file diff --git a/Lang/Rust/Median-filter b/Lang/Rust/Median-filter new file mode 120000 index 0000000000..1cdae0e790 --- /dev/null +++ b/Lang/Rust/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Rust \ No newline at end of file diff --git a/Lang/Rust/Natural-sorting b/Lang/Rust/Natural-sorting new file mode 120000 index 0000000000..77b1a7de05 --- /dev/null +++ b/Lang/Rust/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Rust \ No newline at end of file diff --git a/Lang/Rust/Nonogram-solver b/Lang/Rust/Nonogram-solver new file mode 120000 index 0000000000..670a3f0f6a --- /dev/null +++ b/Lang/Rust/Nonogram-solver @@ -0,0 +1 @@ +../../Task/Nonogram-solver/Rust \ No newline at end of file diff --git a/Lang/Rust/OpenWebNet-password b/Lang/Rust/OpenWebNet-password new file mode 120000 index 0000000000..24be1f8b4a --- /dev/null +++ b/Lang/Rust/OpenWebNet-password @@ -0,0 +1 @@ +../../Task/OpenWebNet-password/Rust \ No newline at end of file diff --git a/Lang/Rust/P-Adic-numbers-basic b/Lang/Rust/P-Adic-numbers-basic new file mode 120000 index 0000000000..2ccd34b2fd --- /dev/null +++ b/Lang/Rust/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/Rust \ No newline at end of file diff --git a/Lang/Rust/P-Adic-square-roots b/Lang/Rust/P-Adic-square-roots new file mode 120000 index 0000000000..ed4fb995e0 --- /dev/null +++ b/Lang/Rust/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Rust \ No newline at end of file diff --git a/Lang/Rust/Playfair-cipher b/Lang/Rust/Playfair-cipher new file mode 120000 index 0000000000..f3e93df373 --- /dev/null +++ b/Lang/Rust/Playfair-cipher @@ -0,0 +1 @@ +../../Task/Playfair-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Polynomial-regression b/Lang/Rust/Polynomial-regression new file mode 120000 index 0000000000..cdb9cdc8ff --- /dev/null +++ b/Lang/Rust/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Rust \ No newline at end of file diff --git a/Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a b/Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a new file mode 120000 index 0000000000..a557952f5e --- /dev/null +++ b/Lang/Rust/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Rust \ No newline at end of file diff --git a/Lang/Rust/Pseudo-random-numbers-Middle-square-method b/Lang/Rust/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..07d7dfdf71 --- /dev/null +++ b/Lang/Rust/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/Rust \ No newline at end of file diff --git a/Lang/Rust/Pseudo-random-numbers-Splitmix64 b/Lang/Rust/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..af868efefa --- /dev/null +++ b/Lang/Rust/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Rust \ No newline at end of file diff --git a/Lang/Rust/QR-decomposition b/Lang/Rust/QR-decomposition new file mode 120000 index 0000000000..b6ec08cee6 --- /dev/null +++ b/Lang/Rust/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Rust \ No newline at end of file diff --git a/Lang/Rust/Rendezvous b/Lang/Rust/Rendezvous new file mode 120000 index 0000000000..2ae4407138 --- /dev/null +++ b/Lang/Rust/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/Rust \ No newline at end of file diff --git a/Lang/Rust/Resistor-mesh b/Lang/Rust/Resistor-mesh new file mode 120000 index 0000000000..245eca7f06 --- /dev/null +++ b/Lang/Rust/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Rust \ No newline at end of file diff --git a/Lang/Rust/Shoelace-formula-for-polygonal-area b/Lang/Rust/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..4ce5ca075a --- /dev/null +++ b/Lang/Rust/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Rust \ No newline at end of file diff --git a/Lang/Rust/Solve-a-Holy-Knights-tour b/Lang/Rust/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..7d376bff89 --- /dev/null +++ b/Lang/Rust/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Rust \ No newline at end of file diff --git a/Lang/Rust/Solve-a-Hopido-puzzle b/Lang/Rust/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..13eae5b688 --- /dev/null +++ b/Lang/Rust/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Rust \ No newline at end of file diff --git a/Lang/Rust/Solve-a-Numbrix-puzzle b/Lang/Rust/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..6da0fac9a0 --- /dev/null +++ b/Lang/Rust/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Bead-sort b/Lang/Rust/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..1096740d47 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Patience-sort b/Lang/Rust/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..98bfba78ce --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Strand-sort b/Lang/Rust/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..c01a273a80 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Steffensens-method b/Lang/Rust/Steffensens-method new file mode 120000 index 0000000000..4aa426ad52 --- /dev/null +++ b/Lang/Rust/Steffensens-method @@ -0,0 +1 @@ +../../Task/Steffensens-method/Rust \ No newline at end of file diff --git a/Lang/Rust/Strassens-algorithm b/Lang/Rust/Strassens-algorithm new file mode 120000 index 0000000000..059089e819 --- /dev/null +++ b/Lang/Rust/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Stream-merge b/Lang/Rust/Stream-merge new file mode 120000 index 0000000000..101f42c85a --- /dev/null +++ b/Lang/Rust/Stream-merge @@ -0,0 +1 @@ +../../Task/Stream-merge/Rust \ No newline at end of file diff --git a/Lang/Rust/Sudan-function b/Lang/Rust/Sudan-function new file mode 120000 index 0000000000..29cdeee99f --- /dev/null +++ b/Lang/Rust/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/Rust \ No newline at end of file diff --git a/Lang/Rust/Tonelli-Shanks-algorithm b/Lang/Rust/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..b90bd71718 --- /dev/null +++ b/Lang/Rust/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Ukkonen-s-suffix-tree-construction b/Lang/Rust/Ukkonen-s-suffix-tree-construction new file mode 120000 index 0000000000..684e412fed --- /dev/null +++ b/Lang/Rust/Ukkonen-s-suffix-tree-construction @@ -0,0 +1 @@ +../../Task/Ukkonen-s-suffix-tree-construction/Rust \ No newline at end of file diff --git a/Lang/Rust/Verhoeff-algorithm b/Lang/Rust/Verhoeff-algorithm new file mode 120000 index 0000000000..fd5322e5ec --- /dev/null +++ b/Lang/Rust/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Xiaolin-Wus-line-algorithm b/Lang/Rust/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..68352a1cb5 --- /dev/null +++ b/Lang/Rust/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Rust \ No newline at end of file diff --git a/Lang/S-BASIC/Additive-primes b/Lang/S-BASIC/Additive-primes new file mode 120000 index 0000000000..b90d39a158 --- /dev/null +++ b/Lang/S-BASIC/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Character-codes b/Lang/S-BASIC/Character-codes new file mode 120000 index 0000000000..f408189f94 --- /dev/null +++ b/Lang/S-BASIC/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body b/Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..0b105df636 --- /dev/null +++ b/Lang/S-BASIC/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/S-BASIC \ No newline at end of file diff --git a/Lang/S-BASIC/Sum-of-a-series b/Lang/S-BASIC/Sum-of-a-series new file mode 120000 index 0000000000..1396d4d958 --- /dev/null +++ b/Lang/S-BASIC/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/S-BASIC \ No newline at end of file diff --git a/Lang/SETL/Gray-code b/Lang/SETL/Gray-code new file mode 120000 index 0000000000..a07e0b4e7b --- /dev/null +++ b/Lang/SETL/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-Do-while b/Lang/SETL/Loops-Do-while new file mode 120000 index 0000000000..8e0329f189 --- /dev/null +++ b/Lang/SETL/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-Increment-loop-index-within-loop-body b/Lang/SETL/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..21b3e5953d --- /dev/null +++ b/Lang/SETL/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/SETL \ No newline at end of file diff --git a/Lang/SETL/Loops-Infinite b/Lang/SETL/Loops-Infinite new file mode 120000 index 0000000000..582c03e313 --- /dev/null +++ b/Lang/SETL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/SETL \ No newline at end of file diff --git a/Lang/SETL/Radical-of-an-integer b/Lang/SETL/Radical-of-an-integer new file mode 120000 index 0000000000..7020a7b45c --- /dev/null +++ b/Lang/SETL/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/SETL \ No newline at end of file diff --git a/Lang/SETL/Strip-comments-from-a-string b/Lang/SETL/Strip-comments-from-a-string new file mode 120000 index 0000000000..6397b858bf --- /dev/null +++ b/Lang/SETL/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/SETL \ No newline at end of file diff --git a/Lang/SQL/Factorial b/Lang/SQL/Factorial new file mode 120000 index 0000000000..c6f45973cd --- /dev/null +++ b/Lang/SQL/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/SQL \ No newline at end of file diff --git a/Lang/Scala/Boyer-Moore-string-search b/Lang/Scala/Boyer-Moore-string-search new file mode 120000 index 0000000000..58b64a7997 --- /dev/null +++ b/Lang/Scala/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Scala \ No newline at end of file diff --git a/Lang/Scheme/Circular-primes b/Lang/Scheme/Circular-primes new file mode 120000 index 0000000000..9f4430f520 --- /dev/null +++ b/Lang/Scheme/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Compare-length-of-two-strings b/Lang/Scheme/Compare-length-of-two-strings new file mode 120000 index 0000000000..d6e6006fa7 --- /dev/null +++ b/Lang/Scheme/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Runge-Kutta-method b/Lang/Scheme/Runge-Kutta-method new file mode 120000 index 0000000000..55b6f782a6 --- /dev/null +++ b/Lang/Scheme/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Unicode-variable-names b/Lang/Scheme/Unicode-variable-names new file mode 120000 index 0000000000..e5f49b3fae --- /dev/null +++ b/Lang/Scheme/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Scheme \ No newline at end of file diff --git a/Lang/Standard-ML/Box-the-compass b/Lang/Standard-ML/Box-the-compass new file mode 120000 index 0000000000..bdb5283192 --- /dev/null +++ b/Lang/Standard-ML/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Standard-ML \ No newline at end of file diff --git a/Lang/Tcl/Unicode-strings b/Lang/Tcl/Unicode-strings new file mode 120000 index 0000000000..5d3bbc0431 --- /dev/null +++ b/Lang/Tcl/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Tcl \ No newline at end of file diff --git a/Lang/Tiny-BASIC/Magic-constant b/Lang/Tiny-BASIC/Magic-constant new file mode 120000 index 0000000000..e64a075712 --- /dev/null +++ b/Lang/Tiny-BASIC/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Tiny-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Evaluate-binomial-coefficients b/Lang/True-BASIC/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..8a2a036883 --- /dev/null +++ b/Lang/True-BASIC/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/True-BASIC \ No newline at end of file diff --git a/Lang/TypeScript/Additive-primes b/Lang/TypeScript/Additive-primes new file mode 120000 index 0000000000..698823ecab --- /dev/null +++ b/Lang/TypeScript/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Arithmetic-numbers b/Lang/TypeScript/Arithmetic-numbers new file mode 120000 index 0000000000..0a37af8cff --- /dev/null +++ b/Lang/TypeScript/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Map-range b/Lang/TypeScript/Map-range new file mode 120000 index 0000000000..50eeda25cd --- /dev/null +++ b/Lang/TypeScript/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/TypeScript \ No newline at end of file diff --git a/Lang/TypeScript/Sum-of-a-series b/Lang/TypeScript/Sum-of-a-series new file mode 120000 index 0000000000..810faf05f3 --- /dev/null +++ b/Lang/TypeScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/TypeScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/Color-of-a-screen-pixel b/Lang/UNIX-Shell/Color-of-a-screen-pixel new file mode 120000 index 0000000000..8344bcd2f2 --- /dev/null +++ b/Lang/UNIX-Shell/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Color-quantization b/Lang/UNIX-Shell/Color-quantization new file mode 120000 index 0000000000..6c518f1af5 --- /dev/null +++ b/Lang/UNIX-Shell/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/UNIX-Shell \ No newline at end of file diff --git a/Lang/Uiua/Create-a-two-dimensional-array-at-runtime b/Lang/Uiua/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..4ef285f54f --- /dev/null +++ b/Lang/Uiua/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Damm-algorithm b/Lang/Uiua/Damm-algorithm new file mode 120000 index 0000000000..af8244172d --- /dev/null +++ b/Lang/Uiua/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Ethiopian-multiplication b/Lang/Uiua/Ethiopian-multiplication new file mode 120000 index 0000000000..4091de8f8e --- /dev/null +++ b/Lang/Uiua/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Matrix-transposition b/Lang/Uiua/Matrix-transposition new file mode 120000 index 0000000000..877ca2d6ea --- /dev/null +++ b/Lang/Uiua/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Munching-squares b/Lang/Uiua/Munching-squares new file mode 120000 index 0000000000..65b5e765bd --- /dev/null +++ b/Lang/Uiua/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Pangram-checker b/Lang/Uiua/Pangram-checker new file mode 120000 index 0000000000..f48b39bf42 --- /dev/null +++ b/Lang/Uiua/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Spiral-matrix b/Lang/Uiua/Spiral-matrix new file mode 120000 index 0000000000..58fe68a534 --- /dev/null +++ b/Lang/Uiua/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Uiua \ No newline at end of file diff --git a/Lang/Uiua/Zig-zag-matrix b/Lang/Uiua/Zig-zag-matrix new file mode 120000 index 0000000000..3d79e2a814 --- /dev/null +++ b/Lang/Uiua/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Uiua \ No newline at end of file diff --git a/Lang/Uxntal/00-LANG.txt b/Lang/Uxntal/00-LANG.txt index d0204e9b73..29f2256564 100644 --- a/Lang/Uxntal/00-LANG.txt +++ b/Lang/Uxntal/00-LANG.txt @@ -1,5 +1,7 @@ {{language|Uxntal}} +''For unimplemented tasks see: [https://rosettacode.org/wiki/Tasks_not_implemented_in_Uxntal Uxntal Unimplemened]'' + '''Uxntal''' is the assembly language for the Uxn virtual machine. The VM has 64KiB of addressable memory, two 256-byte stacks (data and return), and a 256-byte block of I/O ports, divided into 16 devices with 16 ports each. The Uxntal assembler features sub-labels, simple lambdas, user-defined macros, and shorthands for common immediate operations. == Uxn VM == @@ -12,10 +14,23 @@ The 256 opcodes are divided into 8 special instructions, and 31 regular instruct == Syntax == +
+In concatenative programming, there are no precedence rules, the calculations are merely performed in the sequence in which they are presented. The order with which elements come off a stack is known as last in, first out. '''''— [https://wiki.xxiivv.com/site/uxntal_syntax.html Uxntal Syntax]''''' +
+ Instructions are written in uppercase, followed by any combination of the three flags 2kr. Hex values are written with lowercase a-f. Code can be placed at specific addresses with the | rune, which is especially important for assembling the reset vector at address 0x100 (|0100) and for defining devices and zero-page variables. Padding can be inserted with the $ rune. Labels are created with @ and &. The difference is that @ creates a label with the given name, while & creates a sub-label by prefixing the most recent @label and a slash. -For further details on Uxntal syntax, see the [https://wiki.xxiivv.com/site/uxntal_syntax.html syntax page] on the XXIIVV wiki. \ No newline at end of file +For further details on Uxntal syntax, see the [https://wiki.xxiivv.com/site/uxntal_syntax.html syntax page] on the XXIIVV wiki. + +[[Category:Assembler_language]] +[[Category:Assembly]] +[[Category:Esoteric_Languages]] +[[Category:Execution_method/Compiled/Bytecode]] +[[Category:Programming_paradigm/Object-oriented]] +[[Category:Programming_paradigm/Concatenative]] +[[Category:Typing/Unsafe]] +[[Category:Typing/Untyped]] \ No newline at end of file diff --git a/Lang/Uxntal/Array-length b/Lang/Uxntal/Array-length new file mode 120000 index 0000000000..438c43e439 --- /dev/null +++ b/Lang/Uxntal/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Bioinformatics-base-count b/Lang/Uxntal/Bioinformatics-base-count new file mode 120000 index 0000000000..f9af105afe --- /dev/null +++ b/Lang/Uxntal/Bioinformatics-base-count @@ -0,0 +1 @@ +../../Task/Bioinformatics-base-count/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Comments b/Lang/Uxntal/Comments new file mode 120000 index 0000000000..b23db936ba --- /dev/null +++ b/Lang/Uxntal/Comments @@ -0,0 +1 @@ +../../Task/Comments/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Conditional-structures b/Lang/Uxntal/Conditional-structures new file mode 120000 index 0000000000..75d2f67746 --- /dev/null +++ b/Lang/Uxntal/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Copy-a-string b/Lang/Uxntal/Copy-a-string new file mode 120000 index 0000000000..00610fac74 --- /dev/null +++ b/Lang/Uxntal/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Draw-a-pixel b/Lang/Uxntal/Draw-a-pixel deleted file mode 120000 index 68f5f2e311..0000000000 --- a/Lang/Uxntal/Draw-a-pixel +++ /dev/null @@ -1 +0,0 @@ -../../Task/Draw-a-pixel/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Fibonacci-sequence b/Lang/Uxntal/Fibonacci-sequence new file mode 120000 index 0000000000..7795c4564a --- /dev/null +++ b/Lang/Uxntal/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Flow-control-structures b/Lang/Uxntal/Flow-control-structures new file mode 120000 index 0000000000..db95ed817d --- /dev/null +++ b/Lang/Uxntal/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Hello-world-Graphical b/Lang/Uxntal/Hello-world-Graphical new file mode 120000 index 0000000000..2a5fadb101 --- /dev/null +++ b/Lang/Uxntal/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Hello-world-Standard-error b/Lang/Uxntal/Hello-world-Standard-error new file mode 120000 index 0000000000..be0ab3efa0 --- /dev/null +++ b/Lang/Uxntal/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Hello-world-Text b/Lang/Uxntal/Hello-world-Text deleted file mode 120000 index 9024a6cde4..0000000000 --- a/Lang/Uxntal/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Integer-sequence b/Lang/Uxntal/Integer-sequence new file mode 120000 index 0000000000..6d76150081 --- /dev/null +++ b/Lang/Uxntal/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Break b/Lang/Uxntal/Loops-Break new file mode 120000 index 0000000000..5d6d57196c --- /dev/null +++ b/Lang/Uxntal/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Continue b/Lang/Uxntal/Loops-Continue new file mode 120000 index 0000000000..88d5768874 --- /dev/null +++ b/Lang/Uxntal/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Do-while b/Lang/Uxntal/Loops-Do-while new file mode 120000 index 0000000000..a3d655278d --- /dev/null +++ b/Lang/Uxntal/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-For-with-a-specified-step b/Lang/Uxntal/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..4f79f37c9f --- /dev/null +++ b/Lang/Uxntal/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-Foreach b/Lang/Uxntal/Loops-Foreach new file mode 120000 index 0000000000..f8f61da6a7 --- /dev/null +++ b/Lang/Uxntal/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-N-plus-one-half b/Lang/Uxntal/Loops-N-plus-one-half new file mode 120000 index 0000000000..f7ee606c95 --- /dev/null +++ b/Lang/Uxntal/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Loops-While b/Lang/Uxntal/Loops-While new file mode 120000 index 0000000000..f8307c2951 --- /dev/null +++ b/Lang/Uxntal/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/Stack-traces b/Lang/Uxntal/Stack-traces new file mode 120000 index 0000000000..0b9cf24839 --- /dev/null +++ b/Lang/Uxntal/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Uxntal \ No newline at end of file diff --git a/Lang/Uxntal/String-length b/Lang/Uxntal/String-length new file mode 120000 index 0000000000..8dd88d3b90 --- /dev/null +++ b/Lang/Uxntal/String-length @@ -0,0 +1 @@ +../../Task/String-length/Uxntal \ No newline at end of file diff --git a/Lang/V-(Vlang)/Quine b/Lang/V-(Vlang)/Quine new file mode 120000 index 0000000000..a258f08a53 --- /dev/null +++ b/Lang/V-(Vlang)/Quine @@ -0,0 +1 @@ +../../Task/Quine/V-(Vlang) \ No newline at end of file diff --git a/Lang/Wisp/Knuth-shuffle b/Lang/Wisp/Knuth-shuffle new file mode 120000 index 0000000000..14993ebaba --- /dev/null +++ b/Lang/Wisp/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Wisp \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Terminal-control-Clear-the-screen b/Lang/X86-64-Assembly/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..8974ae4cd4 --- /dev/null +++ b/Lang/X86-64-Assembly/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/X86-64-Assembly \ No newline at end of file diff --git a/Lang/XBasic/Levenshtein-distance b/Lang/XBasic/Levenshtein-distance new file mode 120000 index 0000000000..57fd900b58 --- /dev/null +++ b/Lang/XBasic/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/XBasic \ No newline at end of file diff --git a/Lang/XPL0/Bin-given-limits b/Lang/XPL0/Bin-given-limits new file mode 120000 index 0000000000..d093bfd306 --- /dev/null +++ b/Lang/XPL0/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Create-an-object-at-a-given-address b/Lang/XPL0/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..10ca5e5926 --- /dev/null +++ b/Lang/XPL0/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Floyd-Warshall-algorithm b/Lang/XPL0/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..ffd21f6111 --- /dev/null +++ b/Lang/XPL0/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Largest-int-from-concatenated-ints b/Lang/XPL0/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..c906e77c82 --- /dev/null +++ b/Lang/XPL0/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Last-letter-first-letter b/Lang/XPL0/Last-letter-first-letter new file mode 120000 index 0000000000..f77624cd59 --- /dev/null +++ b/Lang/XPL0/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Levenshtein-distance b/Lang/XPL0/Levenshtein-distance new file mode 120000 index 0000000000..0172b975ff --- /dev/null +++ b/Lang/XPL0/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Polynomial-regression b/Lang/XPL0/Polynomial-regression new file mode 120000 index 0000000000..01f5c8d75a --- /dev/null +++ b/Lang/XPL0/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Read-a-configuration-file b/Lang/XPL0/Read-a-configuration-file new file mode 120000 index 0000000000..338d315c72 --- /dev/null +++ b/Lang/XPL0/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sort-three-variables b/Lang/XPL0/Sort-three-variables new file mode 120000 index 0000000000..6a041ebc3e --- /dev/null +++ b/Lang/XPL0/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Text-processing-1 b/Lang/XPL0/Text-processing-1 new file mode 120000 index 0000000000..395543f260 --- /dev/null +++ b/Lang/XPL0/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Text-processing-2 b/Lang/XPL0/Text-processing-2 new file mode 120000 index 0000000000..8d2b9925ef --- /dev/null +++ b/Lang/XPL0/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/XPL0 \ No newline at end of file diff --git a/Lang/Yabasic/Evaluate-binomial-coefficients b/Lang/Yabasic/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..2d010b1897 --- /dev/null +++ b/Lang/Yabasic/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Yabasic \ No newline at end of file diff --git a/Lang/ZED/00-LANG.txt b/Lang/ZED/00-LANG.txt index 467ecdad02..5b0358bc17 100644 --- a/Lang/ZED/00-LANG.txt +++ b/Lang/ZED/00-LANG.txt @@ -12,6 +12,9 @@ Development of ZEDc is also happening on GitHub: https://github.com/zelah/ZEDc ZED can be seen compiling itself here: http://ideone.com/ARpMCM +(begin (define (ZED* ZEDnumber1 ZEDnumber2) (cond (#t (* ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED+ ZEDnumber1 ZEDnumber2) (cond (#t (+ ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED- ZEDnumber1 ZEDnumber2) (cond (#t (- ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED/ ZEDnumber1 ZEDnumber2) (cond (#t (/ ZEDnumber1 ZEDnumber2)) (else err))) (define (ZED= value1 value2) (cond (#t (eqv? value1 value2)) (else err))) (define (ZEDadd-between! item list collect) (cond ((null? list) collect) ((null? (cdr list)) (cons (car list) collect)) (#t (ZEDadd-between! item (cdr list) (cons item (cons (car list) collect)))) (else err))) (define (ZEDadd-between item list) (cond (#t (reverse (ZEDadd-between! item list (quote ())))) (else err))) (define (ZEDadd-between-ra list item) (cond (#t (reverse (ZEDadd-between! item list (quote ())))) (else err))) (define (ZEDalpha) (cond (#t (ZEDwrite-all (ZEDrd (quote ()) append (ZEDrd (quote ()) append (ZEDnewlines (ZEDby-four (ZEDfunction-sort (ZEDsentences (ZEDleading-newline (ZEDspace-newline (ZEDtab-replace (ZEDnewline-space-tab-repeats (ZEDnewline-space (ZEDfilter ZEDnot-return? (ZEDreplace-trailing-white-space (ZEDread-all)))))))))))))))) (else err))) (define (ZEDapplication? expression) (cond (#t (and (not (null? expression)) (pair? (car expression)) (null? (cdar expression)))) (else err))) (define (ZEDarity arity-hash function) (cond (#t (cdr (assoc function arity-hash))) (else err))) (define (ZEDarity-hash! clause) (cond (#t (cons (ZEDclause-name clause) (ZEDclause-arity clause))) (else err))) (define (ZEDarity-hash program) (cond (#t (append (map ZEDarity-hash! program) (append (list (cons (quote ZED1) 1) (cons (quote ZED!) 1) (cons (quote ZED001) 1) (cons (quote or) 2) (cons (quote and) 2) (cons (quote begin) 2) (cons (quote ZEDc) 2) (cons (quote quote) 1)) (list (cons (quote ZED002) 2) (cons (quote ZED003) 3) (cons (quote ZED004) 4) (cons (quote ZED005) 5) (cons (quote ZED006) 6) (cons (quote ZED007) 7) (cons (quote ZED008) 8) (cons (quote ZED009) 9) (cons (quote ZED010) 10) (cons (quote ZED011) 11) (cons (quote ZED012) 12) (cons (quote ZED013) 13) (cons (quote ZED014) 14) (cons (quote ZED015) 15) (cons (quote ZED016) 16) (cons (quote ZED017) 17) (cons (quote ZED018) 18) (cons (quote ZED019) 19) (cons (quote ZED020) 20) (cons (quote ZED021) 21) (cons (quote ZED022) 22) (cons (quote ZED023) 23) (cons (quote ZED024) 24) (cons (quote ZED025) 25) (cons (quote ZED026) 26) (cons (quote ZED027) 27) (cons (quote ZED028) 28) (cons (quote ZED029) 29) (cons (quote ZED030) 30) (cons (quote ZED031) 31) (cons (quote ZED032) 32) (cons (quote ZED033) 33) (cons (quote ZED034) 34) (cons (quote ZED035) 35) (cons (quote ZED036) 36) (cons (quote ZED037) 37) (cons (quote ZED038) 38) (cons (quote ZED039) 39) (cons (quote ZED040) 40) (cons (quote ZED041) 41) (cons (quote ZED042) 42) (cons (quote ZED043) 43) (cons (quote ZED044) 44) (cons (quote ZED045) 45) (cons (quote ZED046) 46) (cons (quote ZED047) 47) (cons (quote ZED048) 48) (cons (quote ZED049) 49) (cons (quote ZED050) 50) (cons (quote ZED051) 51) (cons (quote ZED052) 52) (cons (quote ZED053) 53) (cons (quote ZED054) 54) (cons (quote ZED055) 55) (cons (quote ZED056) 56) (cons (quote ZED057) 57) (cons (quote ZED058) 58) (cons (quote ZED059) 59) (cons (quote ZED060) 60) (cons (quote ZED061) 61) (cons (quote ZED062) 62) (cons (quote ZED063) 63) (cons (quote ZED064) 64) (cons (quote ZED065) 65) (cons (quote ZED066) 66) (cons (quote ZED067) 67) (cons (quote ZED068) 68) (cons (quote ZED069) 69) (cons (quote ZED070) 70) (cons (quote ZED071) 71) (cons (quote ZED072) 72) (cons (quote ZED073) 73) (cons (quote ZED074) 74) (cons (quote ZED075) 75) (cons (quote ZED076) 76) (cons (quote ZED077) 77) (cons (quote ZED078) 78) (cons (quote ZED079) 79) (cons (quote ZED080) 80) (cons (quote ZED081) 81) (cons (quote ZED082) 82) (cons (quote ZED083) 83) (cons (quote ZED084) 84) (cons (quote ZED085) 85) (cons (quote ZED086) 86) (cons (quote ZED087) 87) (cons (quote ZED088) 88) (cons (quote ZED089) 89) (cons (quote ZED090) 90) (cons (quote ZED091) 91) (cons (quote ZED092) 92) (cons (quote ZED093) 93) (cons (quote ZED094) 94) (cons (quote ZED095) 95) (cons (quote ZED096) 96) (cons (quote ZED097) 97) (cons (quote ZED098) 98) (cons (quote ZED099) 99))))) (else err))) (define (ZEDby-four! sentences collect) (cond ((null? sentences) collect) (#t (ZEDby-four! (cddddr sentences) (cons (list (car sentences) (cadr sentences) (caddr sentences) (cadddr sentences)) collect))) (else err))) (define (ZEDby-four sentences) (cond (#t (reverse (ZEDby-four! sentences (quote ())))) (else err))) (define (ZEDby-three! sentences collect) (cond ((null? sentences) collect) (#t (ZEDby-three! (cdddr sentences) (cons (list (car sentences) (cadr sentences) (caddr sentences)) collect))) (else err))) (define (ZEDby-three sentences) (cond (#t (reverse (ZEDby-three! sentences (quote ())))) (else err))) (define (ZEDcharacter-less? character1 character2) (cond (#t (< (char->integer character1) (char->integer character2))) (else err))) (define (ZEDclause-arguments clause) (cond (#t (cadr clause)) (else err))) (define (ZEDclause-arguments-agree clause1 clause2) (cond ((equal? (ZEDclause-arguments clause1) (ZEDclause-arguments clause2)) (ZEDclause-arguments clause1)) (else err))) (define (ZEDclause-arity clause) (cond (#t (length (ZEDclause-arguments clause))) (else err))) (define (ZEDclause-body clause) (cond (#t (cddr clause)) (else err))) (define (ZEDclause-less? clause1 clause2) (cond (#t (ZEDsentence-less? (car clause1) (car clause2))) (else err))) (define (ZEDclause-name clause) (cond (#t (car clause)) (else err))) (define (ZEDclause-name-agree clause1 clause2) (cond ((eq? (ZEDclause-name clause1) (ZEDclause-name clause2)) (ZEDclause-name clause1)) (else err))) (define (ZEDcombine-all! program collect) (cond ((null? program) collect) ((null? (cdr program)) (cons (car program) collect)) ((eq? (ZEDclause-name (car program)) (ZEDclause-name (cadr program))) (ZEDcombine-all! (ZEDcombine-head-clauses program) collect)) (#t (ZEDcombine-all! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDcombine-all program) (cond (#t (reverse (ZEDcombine-all! program (quote ())))) (else err))) (define (ZEDcombine-clauses clause1 clause2) (cond (#t (cons (ZEDclause-name-agree clause1 clause2) (cons (ZEDclause-arguments-agree clause1 clause2) (append (ZEDclause-body clause1) (ZEDclause-body clause2))))) (else err))) (define (ZEDcombine-head-clauses program) (cond (#t (cons (ZEDcombine-clauses (car program) (cadr program)) (cddr program))) (else err))) (define (ZEDcombine-program-clauses program) (cond (#t (ZEDcombine-all (ZEDready-program program))) (else err))) (define (ZEDcomp!) (cond (#t (ZEDcomp!a (ZEDcombine-program-clauses (ZEDby-three (ZEDread-sentences (ZEDdiscard-comments (ZEDfunction-sort (ZEDsentences (ZEDleading-newline (ZEDspace-newline (ZEDtab-replace (ZEDnewline-space-tab-repeats (ZEDnewline-space (ZEDfilter ZEDnot-return? (ZEDreplace-trailing-white-space (ZEDread-all)))))))))))))))) (else err))) (define (ZEDcomp!a combined) (cond (#t (ZEDcomp!aa (ZEDprogramize combined (ZEDarity-hash combined)))) (else err))) (define (ZEDcomp!aa programized) (cond (#t (write programized)) (else err))) (define (ZEDcomp) (cond (#t (ZEDcomp!)) (else err))) (define (ZEDcondefy! expressions collect) (cond ((null? expressions) collect) (#t (ZEDcondefy! (cddr expressions) (cons (append (car expressions) (cadr expressions)) collect))) (else err))) (define (ZEDcondefy expressions) (cond (#t (reverse (ZEDcondefy! expressions (quote ())))) (else err))) (define (ZEDcons ZEDvalue1 ZEDvalue2) (cond (#t (cons ZEDvalue1 ZEDvalue2)) (else err))) (define (ZEDcount ZEDnumber) (cond (#t (cons (delay ZEDnumber) (delay (ZEDcount (ZED+ ZEDnumber 1))))) (else err))) (define (ZEDcount-by ZEDstep ZEDnumber) (cond (#t (cons (delay ZEDnumber) (delay (ZEDcount-by ZEDstep (ZED+ ZEDnumber ZEDstep))))) (else err))) (define (ZEDdelay-wrap expression) (cond (#t (list (quote delay) expression)) (else err))) (define (ZEDdigit? character) (cond (#t (or (eqv? #\0 character) (eqv? #\1 character) (eqv? #\2 character) (eqv? #\3 character) (eqv? #\4 character) (eqv? #\5 character) (eqv? #\6 character) (eqv? #\7 character) (eqv? #\8 character) (eqv? #\9 character))) (else err))) (define (ZEDdiscard-comments! program collect) (cond ((null? program) collect) (#t (ZEDdiscard-comments! (cddddr program) (cons (cadddr program) (cons (caddr program) (cons (car program) collect))))) (else err))) (define (ZEDdiscard-comments program) (cond (#t (reverse (ZEDdiscard-comments! program (quote ())))) (else err))) (define (ZEDdr! value) (cond ((pair? value) (ZEDmp ZEDdr! (ZEDfirst 64 value))) (#t value) (else err))) (define (ZEDdr value) (cond (#t (begin (display (ZEDpr (ZEDdr! value))) (newline) (newline) value)) (else err))) (define (ZEDdrr value) (cond (#t (begin (display (ZEDpr value)) (newline) (newline) value)) (else err))) (define (ZEDfalse? noun-list) (cond (#t (equal? noun-list (list ## #\f #\a #\l #\s #\e))) (else err))) (define (ZEDfi function list) (cond ((null? list) (quote ())) ((function (if (promise? (car list)) (force (car list)) (car list))) (cons (delay (if (promise? (car list)) (force (car list)) (car list))) (delay (ZEDfi function (if (promise? (cdr list)) (force (cdr list)) (cdr list)))))) (#t (ZEDfi function (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (else err))) (define (ZEDfilter! predicate list collect) (cond ((null? list) collect) ((predicate (car list)) (ZEDfilter! predicate (cdr list) (cons (car list) collect))) (#t (ZEDfilter! predicate (cdr list) collect)) (else err))) (define (ZEDfilter predicate list) (cond (#t (reverse (ZEDfilter! predicate list (quote ())))) (else err))) (define (ZEDfirst! integer list collect) (cond ((or (zero? integer) (null? list)) (reverse collect)) ((not (pair? list)) (reverse (cons list collect))) ((> integer 0) (ZEDfirst! (- integer 1) (if (promise? (cdr list)) (force (cdr list)) (cdr list)) (cons (if (promise? (car list)) (force (car list)) (car list)) collect))) (else err))) (define (ZEDfirst integer list) (cond ((not (pair? list)) list) (#t (ZEDfirst! integer list (quote ()))) (else err))) (define (ZEDflatten! ZEDlist ZEDsub-list-found? ZEDcollect) (cond ((and (ZEDnull? ZEDlist) (ZEDnot ZEDsub-list-found?)) (ZEDreverse ZEDcollect)) ((ZEDnull? ZEDlist) (ZEDflatten! (ZEDreverse ZEDcollect) #f (quote ()))) ((ZEDnot (ZEDpair? ZEDlist)) (ZEDflatten! (quote ()) ZEDsub-list-found? (ZEDcons ZEDlist ZEDcollect))) ((ZEDpair? (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist))) (ZEDflatten! (if (promise? (cdr ZEDlist)) (force (cdr ZEDlist)) (cdr ZEDlist)) #t (ZEDcons (if (promise? (cdr (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (force (cdr (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (cdr (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (ZEDcons (if (promise? (car (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (force (car (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) (car (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)))) ZEDcollect)))) ((ZEDnull? (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist))) (ZEDflatten! (if (promise? (cdr ZEDlist)) (force (cdr ZEDlist)) (cdr ZEDlist)) ZEDsub-list-found? ZEDcollect)) (#t (ZEDflatten! (if (promise? (cdr ZEDlist)) (force (cdr ZEDlist)) (cdr ZEDlist)) ZEDsub-list-found? (ZEDcons (if (promise? (car ZEDlist)) (force (car ZEDlist)) (car ZEDlist)) ZEDcollect))) (else err))) (define (ZEDflatten ZEDlist) (cond (#t (ZEDflatten! ZEDlist #f (quote ()))) (else err))) (define (ZEDfor-each ZEDeffect ZEDlist) (cond (#t (for-each ZEDeffect ZEDlist)) (else err))) (define (ZEDfunction expression) (cond (#t (caar expression)) (else err))) (define (ZEDfunction-sort sentences) (cond (#t (ZEDrd (quote ()) append (ZEDsort ZEDclause-less? (ZEDby-four sentences)))) (else err))) (define (ZEDfunctionize clause arity-hash) (cond (#t (list (quote define) (cons (ZEDclause-name clause) (ZEDclause-arguments clause)) (cons (quote cond) (append (ZEDcondefy (ZEDmap-with ZEDschemefy (ZEDclause-body clause) arity-hash)) (list (list (quote else) (quote err))))))) (else err))) (define (ZEDgather-count?! candidate) (cond (#t (and (= 6 (length candidate)) (eqv? #\Z (car candidate)) (eqv? #\E (cadr candidate)) (eqv? #\D (caddr candidate)) (eqv? #\0 (cadddr candidate)) (ZEDdigit? (car (cddddr candidate))) (ZEDdigit? (cadr (cddddr candidate))))) (else err))) (define (ZEDgather-count? symbol) (cond (#t (ZEDgather-count?! (string->list (symbol->string symbol)))) (else err))) (define (ZEDgather-noun sentence) (cond ((null? sentence) (quote ())) ((eqv? #\space (car sentence)) (quote ())) (#t (cons (car sentence) (ZEDgather-noun (cdr sentence)))) (else err))) (define (ZEDgather-verb sentence) (cond ((eqv? #) (car sentence)) (quote ())) (#t (cons (car sentence) (ZEDgather-verb (cdr sentence)))) (else err))) (define (ZEDgr garbage value) (cond (#t (begin (ZEDdr garbage) value)) (else err))) (define (ZEDgrr garbage value) (cond (#t (begin (ZEDdrr garbage) value)) (else err))) (define (ZEDleading-newline program) (cond ((null? program) (quote ())) ((eqv? #\newline (car program)) (cdr program)) (#t program) (else err))) (define (ZEDliteral? literal-list) (cond (#t (eqv? #" (car literal-list))) (else err))) (define (ZEDmake-ZED ZED-list) (cond ((equal? ZED-list (list #\e #\r #\r)) "'err") ((equal? ZED-list (list #\n #\i #\l)) "'()") ((equal? ZED-list (list #\a #\n #\d)) "and") ((equal? ZED-list (list #\o #\r)) "or") ((equal? ZED-list (list #\q #\u #\o #\t #\e)) "quote") ((equal? ZED-list (list #\s #\e)) "begin") (#t (list->string (append (list #\Z #\E #\D) ZED-list))) (else err))) (define (ZEDmake-character noun-list) (cond (#t (list->string (cons ## (cons # +(cdr noun-list))))) (else err))) (define (ZEDmake-exact exact-list) (cond (#t (list->string (append (list ## #\e) exact-list))) (else err))) (define (ZEDmake-literal literal-list) (cond (#t (list->string (cdr (reverse (cdr (reverse literal-list)))))) (else err))) (define (ZEDmake-number-character noun-list) (cond (#t (list->string (list ## # +(integer->char (string->number (list->string (cddr noun-list))))))) (else err))) (define (ZEDmap-with! function list extra collect) (cond ((null? list) collect) (#t (ZEDmap-with! function (cdr list) extra (cons (function (car list) extra) collect))) (else err))) (define (ZEDmap-with function list extra) (cond (#t (reverse (ZEDmap-with! function list extra (quote ())))) (else err))) (define (ZEDmerge! comparator list1 list2 collect) (cond ((null? list2) (append (reverse collect) list1)) ((null? list1) (append (reverse collect) list2)) ((comparator (car list2) (car list1)) (ZEDmerge! comparator list1 (cdr list2) (cons (car list2) collect))) (#t (ZEDmerge! comparator (cdr list1) list2 (cons (car list1) collect))) (else err))) (define (ZEDmerge comparator list1 list2) (cond (#t (ZEDmerge! comparator list1 list2 (quote ()))) (else err))) (define (ZEDmp function list) (cond ((null? list) (quote ())) ((pair? list) (cons (delay (function (if (promise? (car list)) (force (car list)) (car list)))) (delay (ZEDmp function (if (promise? (cdr list)) (force (cdr list)) (cdr list)))))) (#t (function list)) (else err))) (define (ZEDnewline-space! program) (cond (#t (cons #\newline (ZEDnewline-space!a program))) (else err))) (define (ZEDnewline-space!a program) (cond (#t (ZEDnewline-space!aa program (reverse (ZEDnewline-space!ab program (quote ()))))) (else err))) (define (ZEDnewline-space!aa program transformed) (cond ((equal? program transformed) program) (#t (ZEDnewline-space!a transformed)) (else err))) (define (ZEDnewline-space!ab program collect) (cond ((null? program) collect) ((null? (cdr program)) (cons (car program) collect)) ((and (eqv? #\newline (car program)) (or (eqv? #\space (cadr program)) (eqv? #\ht (cadr program)))) (ZEDnewline-space!ab (cdr program) collect)) (#t (ZEDnewline-space!ab (cdr program) (cons (car program) collect))) (else err))) (define (ZEDnewline-space program) (cond (#t (ZEDnewline-space! program)) (else err))) (define (ZEDnewline-space-tab-repeats! program collect) (cond ((or (null? program) (null? (cdr program))) (append program collect)) ((and (eqv? #\newline (car program)) (eqv? #\newline (cadr program))) (ZEDnewline-space-tab-repeats! (cdr program) collect)) ((and (or (eqv? #\space (car program)) (eqv? #\ht (car program))) (or (eqv? #\space (cadr program)) (eqv? #\ht (cadr program)))) (ZEDnewline-space-tab-repeats! (cdr program) collect)) (#t (ZEDnewline-space-tab-repeats! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDnewline-space-tab-repeats program) (cond (#t (reverse (ZEDnewline-space-tab-repeats! program (quote ())))) (else err))) (define (ZEDnewlines clauses) (cond (#t (ZEDadd-between-ra (ZEDmap-with ZEDadd-between-ra clauses (list #\newline)) (list (list #\newline #\newline)))) (else err))) (define (ZEDnormal-character? noun-list) (cond (#t (eqv? (car noun-list) ##)) (else err))) (define (ZEDnot ZEDvalue) (cond (#t (not ZEDvalue)) (else err))) (define (ZEDnot-return? character) (cond (#t (not (eqv? #\cr character))) (else err))) (define (ZEDnoun! noun-list number?) (cond (number? (ZEDmake-exact noun-list)) ((ZEDliteral? noun-list) (ZEDmake-literal noun-list)) ((ZEDtrue? noun-list) "#t") ((ZEDfalse? noun-list) "#f") ((ZEDnumber-character? noun-list) (ZEDmake-number-character noun-list)) ((ZEDnormal-character? noun-list) (ZEDmake-character noun-list)) (#t (ZEDmake-ZED noun-list)) (else err))) (define (ZEDnoun noun-list) (cond (#t (ZEDnoun! noun-list (string->number (list->string noun-list)))) (else err))) (define (ZEDnull? ZEDvalue) (cond (#t (null? ZEDvalue)) (else err))) (define (ZEDnumber-character? noun-list) (cond (#t (and (eqv? (car noun-list) ##) (eqv? (cadr noun-list) #\0) (not (null? (cddr noun-list))))) (else err))) (define (ZEDpair? ZEDvalue) (cond (#t (pair? ZEDvalue)) (else err))) (define (ZEDpop stack) (cond (#t (cdr stack)) (else err))) (define (ZEDpr! value output-string) (cond (#t (begin (display (ZEDpr!a value (quote ())) output-string) (ZEDpr!b output-string (get-output-string output-string)))) (else err))) (define (ZEDpr!a value collect) (cond ((char? value) (ZEDpr!aa (list->string (list ## value)) collect)) ((string? value) (ZEDpr!aa (string-append """ value """) collect)) ((symbol? value) (ZEDpr!aa (symbol->string value) collect)) ((number? value) (ZEDpr!aa (number->string value) collect)) ((and (boolean? value) value) (ZEDpr!aa "#true" collect)) ((boolean? value) (ZEDpr!aa "#false" collect)) ((null? value) (reverse collect)) (#t (ZEDpr!a (if (promise? (cdr value)) (force (cdr value)) (cdr value)) (cons (ZEDpr!a (if (promise? (car value)) (force (car value)) (car value)) (quote ())) collect))) (else err))) (define (ZEDpr!aa string collect) (cond ((null? collect) string) (#t (reverse (cons string (cons "." collect)))) (else err))) (define (ZEDpr!b output-string value) (cond (#t (begin (close-output-port output-string) value)) (else err))) (define (ZEDpr value) (cond (#t (ZEDpr! value (open-output-string))) (else err))) (define (ZEDprogramize program arity-hash) (cond (#t (cons (quote begin) (ZEDmap-with ZEDfunctionize program arity-hash))) (else err))) (define (ZEDpush object stack) (cond (#t (cons object stack)) (else err))) (define (ZEDrd! function list) (cond ((null? (if (promise? (cdr list)) (force (cdr list)) (cdr list))) (if (promise? (car list)) (force (car list)) (car list))) (#t (ZEDrd! function (cons (function (if (promise? (car (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (force (car (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (car (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (if (promise? (car list)) (force (car list)) (car list))) (if (promise? (cdr (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (force (cdr (if (promise? (cdr list)) (force (cdr list)) (cdr list)))) (cdr (if (promise? (cdr list)) (force (cdr list)) (cdr list))))))) (else err))) (define (ZEDrd final function list) (cond (#t (ZEDrd! function (cons final (reverse list)))) (else err))) (define (ZEDread-all! collect) (cond (#t (ZEDread-all!a (read-char) collect)) (else err))) (define (ZEDread-all!a character collect) (cond ((eof-object? character) collect) (#t (ZEDread-all! (cons character collect))) (else err))) (define (ZEDread-all) (cond (#t (reverse (ZEDread-all! (quote ())))) (else err))) (define (ZEDread-sentence!a sentence collect) (cond ((null? sentence) collect) ((eqv? #\space (car sentence)) (ZEDread-sentence!a (cdr sentence) collect)) ((eqv? #( (car sentence)) (ZEDread-sentence!aa sentence (ZEDgather-verb (cdr sentence)) collect)) (#t (ZEDread-sentence!ab sentence (ZEDgather-noun sentence) collect)) (else err))) (define (ZEDread-sentence!aa sentence gather-verb collect) (cond (#t (ZEDread-sentence!a (ZEDtails (+ 2 (length gather-verb)) sentence) (cons (ZEDverb gather-verb) collect))) (else err))) (define (ZEDread-sentence!ab sentence gather-noun collect) (cond (#t (ZEDread-sentence!a (ZEDtails (length gather-noun) sentence) (cons (ZEDnoun gather-noun) collect))) (else err))) (define (ZEDread-sentence!b list output-string) (cond (#t (begin (display list output-string) (ZEDread-sentence!ba output-string (get-output-string output-string)))) (else err))) (define (ZEDread-sentence!ba output-string get-output-string) (cond (#t (begin (close-output-port output-string) (ZEDread-sentence!baa (open-input-string get-output-string)))) (else err))) (define (ZEDread-sentence!baa input-string) (cond (#t (ZEDread-sentence!baaa input-string (read input-string))) (else err))) (define (ZEDread-sentence!baaa input-string answer) (cond (#t (begin (close-input-port input-string) answer)) (else err))) (define (ZEDread-sentence sentence) (cond (#t (ZEDread-sentence!b (reverse (ZEDread-sentence!a sentence (quote ()))) (open-output-string))) (else err))) (define (ZEDread-sentences sentences) (cond (#t (map ZEDread-sentence sentences)) (else err))) (define (ZEDready-clause clause) (cond (#t (cons (caaar clause) (cons (cdar clause) (cdr clause)))) (else err))) (define (ZEDready-program program) (cond (#t (map ZEDready-clause program)) (else err))) (define (ZEDreplace-trailing-white-space! program) (cond ((null? program) (quote ())) ((or (eqv? (car program) #\space) (eqv? (car program) #\ht) (eqv? (car program) #\cr) (eqv? (car program) #\newline)) (ZEDreplace-trailing-white-space! (cdr program))) (#t (cons #\newline program)) (else err))) (define (ZEDreplace-trailing-white-space program) (cond (#t (reverse (ZEDreplace-trailing-white-space! (reverse program)))) (else err))) (define (ZEDreverse ZEDlist) (cond (#t (reverse ZEDlist)) (else err))) (define (ZEDschemefy! expression arity-hash stack) (cond ((null? expression) (ZEDtop stack)) ((ZEDapplication? expression) (ZEDschemefy!a expression arity-hash stack (ZEDfunction expression))) (#t (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (car expression) stack))) (else err))) (define (ZEDschemefy!a expression arity-hash stack function) (cond (#t (ZEDschemefy!aa expression arity-hash stack function (ZEDarity arity-hash function))) (else err))) (define (ZEDschemefy!aa expression arity-hash stack function arity) (cond ((ZEDgather-count? function) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (ZEDfirst arity stack) (ZEDtails arity stack)))) ((eq? function (quote ZED1)) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (list (quote if) (list (quote promise?) (cons (quote car) (ZEDfirst arity stack))) (list (quote force) (cons (quote car) (ZEDfirst arity stack))) (cons (quote car) (ZEDfirst arity stack))) (ZEDtails arity stack)))) ((eq? function (quote ZED!)) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (list (quote if) (list (quote promise?) (cons (quote cdr) (ZEDfirst arity stack))) (list (quote force) (cons (quote cdr) (ZEDfirst arity stack))) (cons (quote cdr) (ZEDfirst arity stack))) (ZEDtails arity stack)))) ((eq? function (quote ZEDc)) (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (cons (quote cons) (map ZEDdelay-wrap (ZEDfirst arity stack))) (ZEDtails arity stack)))) (#t (ZEDschemefy! (cdr expression) arity-hash (ZEDpush (cons function (ZEDfirst arity stack)) (ZEDtails arity stack)))) (else err))) (define (ZEDschemefy expression arity-hash) (cond (#t (list (ZEDschemefy! (reverse expression) arity-hash (ZEDstack)))) (else err))) (define (ZEDsentence-less? sentence1 sentence2) (cond ((null? sentence2) #f) ((null? sentence1) #t) ((ZEDcharacter-less? (car sentence1) (car sentence2)) #t) ((ZEDcharacter-less? (car sentence2) (car sentence1)) #f) (#t (ZEDsentence-less? (cdr sentence1) (cdr sentence2))) (else err))) (define (ZEDsentences! program collect1 collect2) (cond ((null? program) collect2) ((eqv? #\newline (car program)) (ZEDsentences! (cdr program) (quote ()) (cons (reverse collect1) collect2))) (#t (ZEDsentences! (cdr program) (cons (car program) collect1) collect2)) (else err))) (define (ZEDsentences program) (cond (#t (reverse (ZEDsentences! program (quote ()) (quote ())))) (else err))) (define (ZEDsort!a jumble) (cond (#t (map list jumble)) (else err))) (define (ZEDsort!b comparator jumble) (cond ((null? jumble) (quote ())) ((null? (cdr jumble)) jumble) (#t (ZEDsort!b comparator (cons (ZEDmerge comparator (car jumble) (cadr jumble)) (ZEDsort!b comparator (cddr jumble))))) (else err))) (define (ZEDsort comparator jumble) (cond (#t (car (ZEDsort!b comparator (ZEDsort!a jumble)))) (else err))) (define (ZEDspace-newline! program collect) (cond ((or (null? program) (null? (cdr program))) (append program collect)) ((and (eqv? #\space (car program)) (eqv? #\newline (cadr program))) (ZEDspace-newline! (cdr program) collect)) (#t (ZEDspace-newline! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDspace-newline program) (cond (#t (reverse (ZEDspace-newline! program (quote ())))) (else err))) (define (ZEDstack) (cond (#t (quote ())) (else err))) (define (ZEDtab-replace! program collect) (cond ((null? program) collect) ((eqv? #\ht (car program)) (ZEDtab-replace! (cdr program) (cons #\space collect))) (#t (ZEDtab-replace! (cdr program) (cons (car program) collect))) (else err))) (define (ZEDtab-replace program) (cond (#t (reverse (ZEDtab-replace! program (quote ())))) (else err))) (define (ZEDtails number list) (cond ((null? list) (quote ())) ((zero? number) list) ((> number 0) (ZEDtails (- number 1) (cdr list))) (else err))) (define (ZEDtop stack) (cond (#t (car stack)) (else err))) (define (ZEDtrue? noun-list) (cond (#t (equal? noun-list (list ## #\t #\r #\u #\e))) (else err))) (define (ZEDverb verb-list) (cond ((ZEDliteral? verb-list) (list (ZEDmake-literal verb-list))) (#t (list (ZEDmake-ZED verb-list))) (else err))) (define (ZEDwrite-all program) (cond ((null? program) (quote err)) (#t (ZEDwrite-all (begin (write-char (car program)) (cdr program)))) (else err))) (define (ZEDzed->scheme! value collect) (cond ((null? value) (reverse collect)) (#t (ZEDzed->scheme! (if (promise? (cdr value)) (force (cdr value)) (cdr value)) (cons (ZEDzed->scheme (if (promise? (car value)) (force (car value)) (car value))) collect))) (else err))) (define (ZEDzed->scheme value) (cond ((not (pair? value)) value) (#t (ZEDzed->scheme! value (quote ()))) (else err)))) (ZEDcomp) Language author on RC: [[User:Zelah|Zelah]] ([[User_talk:Zelah|talk]] | [[Special:Contributions/Zelah|contribs]]) . \ No newline at end of file diff --git a/Lang/Zig/15-puzzle-solver b/Lang/Zig/15-puzzle-solver new file mode 120000 index 0000000000..31e2e98f6a --- /dev/null +++ b/Lang/Zig/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Zig \ No newline at end of file diff --git a/Lang/Zig/2048 b/Lang/Zig/2048 new file mode 120000 index 0000000000..d2ac81be16 --- /dev/null +++ b/Lang/Zig/2048 @@ -0,0 +1 @@ +../../Task/2048/Zig \ No newline at end of file diff --git a/Lang/Zig/24-game b/Lang/Zig/24-game new file mode 120000 index 0000000000..7b40225753 --- /dev/null +++ b/Lang/Zig/24-game @@ -0,0 +1 @@ +../../Task/24-game/Zig \ No newline at end of file diff --git a/Lang/Zig/Anti-primes b/Lang/Zig/Anti-primes new file mode 120000 index 0000000000..bde3882591 --- /dev/null +++ b/Lang/Zig/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Zig \ No newline at end of file diff --git a/Lang/Zig/Canonicalize-CIDR b/Lang/Zig/Canonicalize-CIDR new file mode 120000 index 0000000000..792c271f68 --- /dev/null +++ b/Lang/Zig/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/Zig \ No newline at end of file diff --git a/Lang/Zig/Convex-hull b/Lang/Zig/Convex-hull new file mode 120000 index 0000000000..bb63712423 --- /dev/null +++ b/Lang/Zig/Convex-hull @@ -0,0 +1 @@ +../../Task/Convex-hull/Zig \ No newline at end of file diff --git a/Lang/Zig/De-Bruijn-sequences b/Lang/Zig/De-Bruijn-sequences new file mode 120000 index 0000000000..1e82ee12c7 --- /dev/null +++ b/Lang/Zig/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/Zig \ No newline at end of file diff --git a/Lang/Zig/Dijkstras-algorithm b/Lang/Zig/Dijkstras-algorithm new file mode 120000 index 0000000000..e85779f749 --- /dev/null +++ b/Lang/Zig/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Execute-a-Markov-algorithm b/Lang/Zig/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..5b70cd7b50 --- /dev/null +++ b/Lang/Zig/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Fibonacci-sequence b/Lang/Zig/Fibonacci-sequence new file mode 120000 index 0000000000..8c7ee19f72 --- /dev/null +++ b/Lang/Zig/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Find-the-missing-permutation b/Lang/Zig/Find-the-missing-permutation new file mode 120000 index 0000000000..720e08365d --- /dev/null +++ b/Lang/Zig/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Zig \ No newline at end of file diff --git a/Lang/Zig/Floyd-Warshall-algorithm b/Lang/Zig/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..e20cfd03e2 --- /dev/null +++ b/Lang/Zig/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Latin-Squares-in-reduced-form b/Lang/Zig/Latin-Squares-in-reduced-form new file mode 120000 index 0000000000..4ae8de3ec8 --- /dev/null +++ b/Lang/Zig/Latin-Squares-in-reduced-form @@ -0,0 +1 @@ +../../Task/Latin-Squares-in-reduced-form/Zig \ No newline at end of file diff --git a/Lang/Zig/Move-to-front-algorithm b/Lang/Zig/Move-to-front-algorithm new file mode 120000 index 0000000000..820f21fe3e --- /dev/null +++ b/Lang/Zig/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Natural-sorting b/Lang/Zig/Natural-sorting new file mode 120000 index 0000000000..ce3fd8d2e1 --- /dev/null +++ b/Lang/Zig/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Zig \ No newline at end of file diff --git a/Lang/Zig/P-Adic-numbers-basic b/Lang/Zig/P-Adic-numbers-basic new file mode 120000 index 0000000000..7be77909db --- /dev/null +++ b/Lang/Zig/P-Adic-numbers-basic @@ -0,0 +1 @@ +../../Task/P-Adic-numbers-basic/Zig \ No newline at end of file diff --git a/Lang/Zig/P-Adic-square-roots b/Lang/Zig/P-Adic-square-roots new file mode 120000 index 0000000000..bf2f9425e2 --- /dev/null +++ b/Lang/Zig/P-Adic-square-roots @@ -0,0 +1 @@ +../../Task/P-Adic-square-roots/Zig \ No newline at end of file diff --git a/Lang/Zig/Parsing-RPN-calculator-algorithm b/Lang/Zig/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..64d52e74e9 --- /dev/null +++ b/Lang/Zig/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Parsing-Shunting-yard-algorithm b/Lang/Zig/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..36cb3a3892 --- /dev/null +++ b/Lang/Zig/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Quickselect-algorithm b/Lang/Zig/Quickselect-algorithm new file mode 120000 index 0000000000..7dbb81ef78 --- /dev/null +++ b/Lang/Zig/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Quine b/Lang/Zig/Quine new file mode 120000 index 0000000000..20f1f12898 --- /dev/null +++ b/Lang/Zig/Quine @@ -0,0 +1 @@ +../../Task/Quine/Zig \ No newline at end of file diff --git a/Lang/Zig/SHA-1 b/Lang/Zig/SHA-1 new file mode 120000 index 0000000000..374af24054 --- /dev/null +++ b/Lang/Zig/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Zig \ No newline at end of file diff --git a/Lang/Zig/Solve-a-Holy-Knights-tour b/Lang/Zig/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..b0fe3fcb9a --- /dev/null +++ b/Lang/Zig/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Zig \ No newline at end of file diff --git a/Lang/Zig/Sorting-algorithms-Patience-sort b/Lang/Zig/Sorting-algorithms-Patience-sort new file mode 120000 index 0000000000..a696e81abf --- /dev/null +++ b/Lang/Zig/Sorting-algorithms-Patience-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Patience-sort/Zig \ No newline at end of file diff --git a/Lang/Zig/Sorting-algorithms-Strand-sort b/Lang/Zig/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..67361c524c --- /dev/null +++ b/Lang/Zig/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Zig \ No newline at end of file diff --git a/Lang/Zig/Strassens-algorithm b/Lang/Zig/Strassens-algorithm new file mode 120000 index 0000000000..f02a6cb05a --- /dev/null +++ b/Lang/Zig/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Sutherland-Hodgman-polygon-clipping b/Lang/Zig/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..2e08ab9fc7 --- /dev/null +++ b/Lang/Zig/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Zig \ No newline at end of file diff --git a/Lang/Zig/Thue-Morse b/Lang/Zig/Thue-Morse new file mode 120000 index 0000000000..514eeceeed --- /dev/null +++ b/Lang/Zig/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Zig \ No newline at end of file diff --git a/Lang/Zig/Tonelli-Shanks-algorithm b/Lang/Zig/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..364e6278fd --- /dev/null +++ b/Lang/Zig/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Y-combinator b/Lang/Zig/Y-combinator new file mode 120000 index 0000000000..1478dbbdb7 --- /dev/null +++ b/Lang/Zig/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Zig \ No newline at end of file diff --git a/Task/100-doors/BQN/100-doors-4.bqn b/Task/100-doors/BQN/100-doors-4.bqn new file mode 100644 index 0000000000..cfab61e191 --- /dev/null +++ b/Task/100-doors/BQN/100-doors-4.bqn @@ -0,0 +1,3 @@ +F ← {1+ / 2| +˝ 0= |⌜˜ 1+↕𝕩} +F 100 +# ⟨ 1 4 9 16 25 36 49 64 81 100 ⟩ diff --git a/Task/100-doors/BQN/100-doors-5.bqn b/Task/100-doors/BQN/100-doors-5.bqn new file mode 100644 index 0000000000..b78e4f3de6 --- /dev/null +++ b/Task/100-doors/BQN/100-doors-5.bqn @@ -0,0 +1,3 @@ +F ← {ט1+↕⌊√𝕩} +F 100 +# ⟨ 1 4 9 16 25 36 49 64 81 100 ⟩ diff --git a/Task/100-doors/EasyLang/100-doors.easy b/Task/100-doors/EasyLang/100-doors.easy index c34fdbedc2..ba261e6f52 100644 --- a/Task/100-doors/EasyLang/100-doors.easy +++ b/Task/100-doors/EasyLang/100-doors.easy @@ -7,7 +7,5 @@ for p = 1 to 100 . . for i = 1 to 100 - if d[i] = 1 - print i - . + if d[i] = 1 : write i & " " . diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena index 6e1a619ede..dd7db1e5c7 100644 --- a/Task/100-doors/Elena/100-doors.elena +++ b/Task/100-doors/Elena/100-doors.elena @@ -14,8 +14,8 @@ public program() for(int i := 0; i < 100; i++) { - console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) + Console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) }; - console.readChar() + Console.readChar() } diff --git a/Task/100-doors/Excel/100-doors-4.excel b/Task/100-doors/Excel/100-doors-4.excel new file mode 100644 index 0000000000..619e31a91c --- /dev/null +++ b/Task/100-doors/Excel/100-doors-4.excel @@ -0,0 +1 @@ +=LET(i, SEQUENCE(100), root, SQRT(i), "Door " & i & ": " & IF(root = INT(root), "open", "close")) diff --git a/Task/100-doors/OPL/100-doors.opl b/Task/100-doors/OPL/100-doors.opl new file mode 100644 index 0000000000..e5026a3076 --- /dev/null +++ b/Task/100-doors/OPL/100-doors.opl @@ -0,0 +1,32 @@ +REM Author.....: Eva Broccoli +REM Date.......: 23 May 2025 +REM Description: OPL solution for "100 doors" task on https://rosettacode.org +REM Tested with: Psion Series 3a & Series 5 +REM Contact....: eva.klassen@kittymail.com + +PROC main: + LOCAL door%(100),i%,j% + i%=1 + j%=1 + WHILE j%<101 + WHILE i%<101 + IF door%(i%)=0 + door%(i%)=1 + ELSE + door%(i%)=0 + ENDIF + i%=i%+j% + ENDWH + j%=j%+1 + i%=0+j% + ENDWH + PRINT "Open doors:", + i%=1 + WHILE i%<101 + IF door%(i%)=1 + PRINT i%, + ENDIF + i%=i%+1 + ENDWH + GET +ENDP diff --git a/Task/100-doors/Quackery/100-doors-1.quackery b/Task/100-doors/Quackery/100-doors-1.quackery new file mode 100644 index 0000000000..e3d105d0cd --- /dev/null +++ b/Task/100-doors/Quackery/100-doors-1.quackery @@ -0,0 +1,17 @@ + [ bit ^ ] is toggle ( f n --> f ) + + [ 0 + 100 times + [ i^ 1+ swap + 101 times + [ i^ toggle over step ] + nip ] ] is toggledoors ( --> f ) + + [ 100 times + [ 1 >> dup 1 & + if [ i^ 1+ echo sp ] ] + drop ] is echodoors ( f --> ) + + toggledoors + say " These doors are open: " echodoors cr + say " The rest are closed." cr diff --git a/Task/100-doors/Quackery/100-doors-2.quackery b/Task/100-doors/Quackery/100-doors-2.quackery new file mode 100644 index 0000000000..85074cd60f --- /dev/null +++ b/Task/100-doors/Quackery/100-doors-2.quackery @@ -0,0 +1 @@ + 10 times [ i^ 1+ 2 ** echo sp ] diff --git a/Task/100-doors/Quackery/100-doors.quackery b/Task/100-doors/Quackery/100-doors.quackery deleted file mode 100644 index 5577d1c6c4..0000000000 --- a/Task/100-doors/Quackery/100-doors.quackery +++ /dev/null @@ -1,22 +0,0 @@ -/O> [ bit ^ ] is toggle ( f n --> f ) -... -... [ 0 -... 100 times -... [ i^ 1+ swap -... 101 times -... [ i^ toggle over step ] -... nip ] ] is toggledoors ( --> f ) -... -... [ 100 times -... [ 1 >> dup 1 & -... if [ i^ 1+ echo sp ] ] -... drop ] is echodoors ( f --> ) -... -... toggledoors -... say " These doors are open: " echodoors cr -... say " The rest are closed." cr -... - These doors are open: 1 4 9 16 25 36 49 64 81 100 - The rest are closed. - -Stack empty. diff --git a/Task/100-doors/Tcl/100-doors-1.tcl b/Task/100-doors/Tcl/100-doors-1.tcl index 43badf3380..71a614db6d 100644 --- a/Task/100-doors/Tcl/100-doors-1.tcl +++ b/Task/100-doors/Tcl/100-doors-1.tcl @@ -1,11 +1,85 @@ -package require Tcl 8.5 -set n 100 -set doors [concat - [lrepeat $n 0]] -for {set step 1} {$step <= $n} {incr step} { - for {set i $step} {$i <= $n} {incr i $step} { - lset doors $i [expr { ! [lindex $doors $i]}] +#!/usr/bin/env tclsh + +# 100 doors + +proc seq { m n } { + set r {} + for {set i $m} {$i <= $n} {incr i} { + lappend r $i + } + return $r +} + +proc toggle {val a b} { + # expr has ternary operators + return [expr { + ${val} == ${a}? ${b} : + ${val} == ${b}? ${a} : + [error "bad value: ${val}"] + }] +} + +proc multiples {n max} { + set ret {} + set x $n + + # maximum multiple + set mid [expr $max / 2] + + if {$x>=$mid && $x<$max} { return $x } + + # calculate multiples + if {[expr $x <= $mid]} { + for {set i 1} {$i <= $max } {incr i} { + + set x [expr $i * $n] + + if {$x > $max} { break } + + lappend ret $x + } + } + + return $ret +} + +# states +array set state { + open "open" + closed "closed" + unknown "?" +} + +# ============================== +# start program + +# 100 doors +variable MAX 100 + +variable mid [expr int($MAX / 2)] + +variable Seq_100 [seq 1 $MAX] + +# initialize doors closed +foreach n $Seq_100 { + set door($n) $state(closed) +} + +# do for 1 .. 100 +foreach m $Seq_100 { + + set mults [multiples $m $MAX] + + foreach d $mults { + set door($d) [toggle $door($d) $state(open) $state(closed)] } } -for {set i 1} {$i <= $n} {incr i} { - puts [format "door %d is %s" $i [expr {[lindex $doors $i] ? "open" : "closed"}]] + +# output +foreach n $Seq_100 { + if { $door($n) eq $state(open) } { + puts stdout "$n: $door($n)" + } } + +# end diff --git a/Task/100-doors/Tcl/100-doors-2.tcl b/Task/100-doors/Tcl/100-doors-2.tcl index df7078d750..43badf3380 100644 --- a/Task/100-doors/Tcl/100-doors-2.tcl +++ b/Task/100-doors/Tcl/100-doors-2.tcl @@ -1,8 +1,11 @@ package require Tcl 8.5 -set doors [lrepeat [expr {$n + 1}] closed] -for {set i 1} {$i <= sqrt($n)} {incr i} { - lset doors [expr {$i ** 2}] open +set n 100 +set doors [concat - [lrepeat $n 0]] +for {set step 1} {$step <= $n} {incr step} { + for {set i $step} {$i <= $n} {incr i $step} { + lset doors $i [expr { ! [lindex $doors $i]}] + } } for {set i 1} {$i <= $n} {incr i} { - puts [format "door %d is %s" $i [lindex $doors $i]] + puts [format "door %d is %s" $i [expr {[lindex $doors $i] ? "open" : "closed"}]] } diff --git a/Task/100-doors/Tcl/100-doors-3.tcl b/Task/100-doors/Tcl/100-doors-3.tcl index 8e3db5488e..df7078d750 100644 --- a/Task/100-doors/Tcl/100-doors-3.tcl +++ b/Task/100-doors/Tcl/100-doors-3.tcl @@ -1,46 +1,8 @@ package require Tcl 8.5 -package require Tk - -array set door_status {} - -# create the gui -set doors [list x] -for {set i 0} {$i < 10} {incr i} { - for {set j 0} {$j < 10} {incr j} { - set k [expr {1 + $j + 10*$i}] - lappend doors [radiobutton .d_$k -text $k -variable door_status($k) \ - -indicatoron no -offrelief flat -width 3 -value open] - grid [lindex $doors $k] -column $j -row $i - } +set doors [lrepeat [expr {$n + 1}] closed] +for {set i 1} {$i <= sqrt($n)} {incr i} { + lset doors [expr {$i ** 2}] open } - -# create the controls -button .start -command go -text Start -label .i_label -text " door:" -entry .i -textvariable i -width 4 -label .step_label -text " step:" -entry .step -textvariable step -width 4 -grid .start - .i_label - .i - .step_label - .step - -row $i -grid configure .start -sticky ew -grid configure .i_label .step_label -sticky e -grid configure .i .step -sticky w - -proc go {} { - global doors door_status i step - - # initialize the door_status (all closed) - for {set d 1} {$d <= 100} {incr d} { - set door_status($d) closed - } - - # now, begin opening and closing - for {set step 1} {$step <= 100} {incr step} { - for {set i 1} {$i <= 100} {incr i} { - if {$i % $step == 0} { - [lindex $doors $i] [expr {$door_status($i) eq "open" ? "deselect" : "select"}] - update - after 50 - } - } - } +for {set i 1} {$i <= $n} {incr i} { + puts [format "door %d is %s" $i [lindex $doors $i]] } diff --git a/Task/100-doors/Tcl/100-doors-4.tcl b/Task/100-doors/Tcl/100-doors-4.tcl new file mode 100644 index 0000000000..8e3db5488e --- /dev/null +++ b/Task/100-doors/Tcl/100-doors-4.tcl @@ -0,0 +1,46 @@ +package require Tcl 8.5 +package require Tk + +array set door_status {} + +# create the gui +set doors [list x] +for {set i 0} {$i < 10} {incr i} { + for {set j 0} {$j < 10} {incr j} { + set k [expr {1 + $j + 10*$i}] + lappend doors [radiobutton .d_$k -text $k -variable door_status($k) \ + -indicatoron no -offrelief flat -width 3 -value open] + grid [lindex $doors $k] -column $j -row $i + } +} + +# create the controls +button .start -command go -text Start +label .i_label -text " door:" +entry .i -textvariable i -width 4 +label .step_label -text " step:" +entry .step -textvariable step -width 4 +grid .start - .i_label - .i - .step_label - .step - -row $i +grid configure .start -sticky ew +grid configure .i_label .step_label -sticky e +grid configure .i .step -sticky w + +proc go {} { + global doors door_status i step + + # initialize the door_status (all closed) + for {set d 1} {$d <= 100} {incr d} { + set door_status($d) closed + } + + # now, begin opening and closing + for {set step 1} {$step <= 100} {incr step} { + for {set i 1} {$i <= 100} {incr i} { + if {$i % $step == 0} { + [lindex $doors $i] [expr {$door_status($i) eq "open" ? "deselect" : "select"}] + update + after 50 + } + } + } +} diff --git a/Task/100-prisoners/EasyLang/100-prisoners.easy b/Task/100-prisoners/EasyLang/100-prisoners.easy index 3435445f04..3acb599a3c 100644 --- a/Task/100-prisoners/EasyLang/100-prisoners.easy +++ b/Task/100-prisoners/EasyLang/100-prisoners.easy @@ -1,60 +1,51 @@ -for i = 1 to 100 - drawer[] &= i - sampler[] &= i +global drawer[] sampler[] . +proc init . + for i = 1 to 100 + drawer[] &= i + sampler[] &= i + . . -subr shuffle_drawer +init +proc shuffle_drawer . for i = len drawer[] downto 2 r = random i swap drawer[r] drawer[i] . . -subr play_random +func play_random . shuffle_drawer for prisoner = 1 to 100 - found = 0 for i = 1 to 50 - r = random (100 - i) + r = random (100 - i + 1) card = drawer[sampler[r]] - swap sampler[r] sampler[100 - i - 1] - if card = prisoner - found = 1 - break 1 - . - . - if found = 0 - break 1 + swap sampler[r] sampler[100 - i + 1] + if card = prisoner : break 1 . + if i > 50 : return 0 . + return 1 . -subr play_optimal +func play_optimal . shuffle_drawer for prisoner = 1 to 100 reveal = prisoner - found = 0 for i = 1 to 50 card = drawer[reveal] - if card = prisoner - found = 1 - break 1 - . + if card = prisoner : break 1 reveal = card . - if found = 0 - break 1 - . + if i > 50 : return 0 . + return 1 . -n = 10000 -win = 0 -for _ = 1 to n - play_random - win += found +n = 100000 +for i to n + win += play_random . print "random: " & 100.0 * win / n & "%" # win = 0 -for _ = 1 to n - play_optimal - win += found +for i to n + win += play_optimal . print "optimal: " & 100.0 * win / n & "%" diff --git a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy index 2b4fba7059..cce8901658 100644 --- a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy +++ b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy @@ -1,47 +1,38 @@ sysconf topleft -background 432 -textsize 13 +gbackground 432 +gtextsize 13 len f[] 16 -proc draw . . - clear +proc draw . + gclear for i = 1 to 16 - h = f[i] - if h < 16 + v = f[i] + if v < 16 x = (i - 1) mod 4 * 24 + 3 y = (i - 1) div 4 * 24 + 3 - color 210 - move x y - rect 22 22 - move x + 4 y + 6 - if h < 10 - move x + 6 y + 6 - . - color 885 - text h + gcolor 210 + grect x y 22 22 + if v < 10 : x += 2 + gcolor 885 + gtext x + 4 y + 6 v . . . -global done . -proc smiley . . +proc smiley . s = 3.5 x = 86 y = 86 - move x y - color 983 - circle 2.8 * s - color 000 - move x - s y - s - circle s / 3 - move x + 3.5 y - 3.5 - circle s / 3 - linewidth s / 3 - curve [ x - s y + s x y + 2 * s x + s y + s ] + gcolor 983 + gcircle x y 2.8 * s + gcolor 000 + gcircle (x - s) (y - s) (s / 3) + gcircle x + 3.5 y - 3.5 s / 3 + glinewidth s / 3 + gcurve [ x - s y + s x y + 2 * s x + s y + s ] . -proc init . . +global done . +proc init . done = 0 - for i = 1 to 16 - f[i] = i - . + for i = 1 to 16 : f[i] = i # shuffle for i = 15 downto 2 r = random i @@ -49,20 +40,14 @@ proc init . . . # make it solvable inv = 0 - for i = 1 to 15 - for j = 1 to i - 1 - if f[j] > f[i] - inv += 1 - . - . + for i = 1 to 15 : for j = 1 to i - 1 + if f[j] > f[i] : inv += 1 . - if inv mod 2 <> 0 - swap f[1] f[2] - . - textsize 12 + if inv mod 2 <> 0 : swap f[1] f[2] + gtextsize 12 draw . -proc move_tile . . +proc move_tile . c = mouse_x div 25 r = mouse_y div 25 i = r * 4 + c + 1 @@ -77,9 +62,7 @@ proc move_tile . . . draw for i = 1 to 15 - if f[i] > f[i + 1] - return - . + if f[i] > f[i + 1] : return . done = 1 timer 0.5 @@ -87,7 +70,7 @@ proc move_tile . . on mouse_down if done = 0 move_tile - elif done = 3 + elif done = 3 and mouse_x > 75 and mouse_y > 75 init . . diff --git a/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs b/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs index 16d2c2a882..591dbc1385 100644 --- a/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs +++ b/Task/15-puzzle-solver/C-sharp/15-puzzle-solver.cs @@ -1,1466 +1,97 @@ -using System; -using System.IO; -using System.IO.Compression; -using System.Runtime.InteropServices; -using System.Text; +// Translated from C++ by Nigel Galloway -public static class Program +new FifteenSolver(8, 0xFE169B4C0A73D852).Solve(); + +class FifteenSolver { - public static void Main(string[] args) + readonly int[] RowIndex = [3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]; + readonly int[] ColIndex = [3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]; + int n = 0, maxCost = 0; + readonly int[] Hole = new int[100]; + readonly char[] Move = new char[100]; + readonly int[] Cost = new int[100]; + readonly ulong[] State = new ulong[100]; + + bool Scan() { - byte[] t = new byte[] + if (Cost[n] < maxCost) + return Explore(); + + if (State[n] == 0x123456789ABCDEF0) { - 15, 14, 1, 6, - 9, 11, 4, 12, - 0, 10, 7, 3, - 13, 8, 5, 2, - }; + Console.WriteLine($"Solution found in {n} moves :"); - Ultimate.SolvePuzzle15(t); - } -} + for (var g = 1; g <= n; ++g) + Console.Write(Move[g]); -public static class NativeLibraryHelper -{ - [DllImport("kernel32.dll")] - public static extern IntPtr LoadLibrary(string DllToLoad); - - [DllImport("kernel32.dll")] - public static extern IntPtr GetProcAddress(IntPtr DllHandle, string ProcedureName); - - [DllImport("kernel32.dll")] - public static extern bool FreeLibrary(IntPtr DllHandle); - - public static T GetMethod(IntPtr DllHandle, string MethodName) where T : class - { - T Method = null; - - IntPtr MethodHandle = NativeLibraryHelper.GetProcAddress(DllHandle, MethodName); - if (MethodHandle != IntPtr.Zero) - { - Method = (T)((Object)Marshal.GetDelegateForFunctionPointer(MethodHandle, typeof(T))); - } - - return Method; - } -} - -public static class Ultimate -{ - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.LPWStr)] - private delegate string GetSolverName(); - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - [return: MarshalAs(UnmanagedType.LPWStr)] - private delegate string CallSolver([In] [Out] byte[] Array, int Len); - - public static void SolvePuzzle15(byte[] t) - { - string LibPath = "Solver.dll"; - - byte[] ZipedData = Convert.FromBase64String(Data.ToString()); - byte[] UnzipedData = DecompressGZipArhive(new MemoryStream(ZipedData)); - File.WriteAllBytes(LibPath, UnzipedData); - - IntPtr DllHandle = NativeLibraryHelper.LoadLibrary(LibPath); - - GetSolverName GetSolverName = NativeLibraryHelper.GetMethod(DllHandle, "GetSolverName"); - Console.WriteLine("Hi! My name is {0}.", GetSolverName()); - Console.WriteLine(); - - Console.WriteLine("And I try solve puzzle15 with board:"); - for (int i = 0; i < t.Length; i += 4) Console.WriteLine("{0} {1} {2} {3}", t[i], t[i + 1], t[i + 2], t[i + 3]); - Console.WriteLine(); - - CallSolver SolveThis = NativeLibraryHelper.GetMethod(DllHandle, "SolvePuzzle15"); - - DateTime StartTime = DateTime.Now; - string Path = SolveThis(t, t.Length); - - if (!String.IsNullOrEmpty(Path)) - { - Path = Path.Trim(); - Console.WriteLine("Ready! Solution path is : {0}", Path); - Console.WriteLine("Moves {0} and Time: {1}", Path.Length, (DateTime.Now - StartTime).ToString()); Console.WriteLine(); - Console.WriteLine("Bye bye :)"); - } - else - { - Console.WriteLine("Sorry! I do know a solution :("); + return true; } - NativeLibraryHelper.FreeLibrary(DllHandle); - File.Delete(LibPath); + if (Cost[n] == maxCost) + return Explore(); - Console.ReadKey(); + return false; } - private static byte[] DecompressGZipArhive(Stream FStream) + bool Explore() { - if (FStream == null) return new byte[0]; - - FStream.Seek(0, SeekOrigin.Begin); - MemoryStream OutStream = new MemoryStream(); - - using (GZipStream DecompressedStream = new GZipStream(FStream, CompressionMode.Decompress)) - { - byte[] Buffer = new byte[1024]; - int CountReadingBytes = 0; - - while ((CountReadingBytes = DecompressedStream.Read(Buffer, 0, Buffer.Length)) > 0) - { - OutStream.Write(Buffer, 0, CountReadingBytes); - } - } - return OutStream.ToArray(); + if (Move[n] != 'u' && Hole[n] / 4 < 3) { Down(); ++n; if (Scan()) return true; --n; } + if (Move[n] != 'd' && Hole[n] / 4 > 0) { Up(); ++n; if (Scan()) return true; --n; } + if (Move[n] != 'l' && Hole[n] % 4 < 3) { Right(); ++n; if (Scan()) return true; --n; } + if (Move[n] != 'r' && Hole[n] % 4 > 0) { Left(); ++n; if (Scan()) return true; --n; } + return false; } - // no way make normal long string literal - private delegate StringBuilder AppendDelegate(string v); - private static StringBuilder Data = new StringBuilder(100000); - static Ultimate() + void Down() { - AppendDelegate a = Data.Append; - a("H4sICB6/w2MCAFBhc2NhbFNvbHZlci54ODYtNjQuZGxsAOxaZ3QbRRC+kyVHFg7nBAdCaDYYiKg21ab6ggR7cKL3HgJHDcWRqK"); - a("5RDDof4on26I/OAx79QTDVkmwcOTTboTgxxYQm+yimOcYU8c2eZORLaP/xi253dmdnZmdnZmd3EzgxJhQIguDEL5MRhHbB+qsV"); - a("/vmvGb/1t3hxfeHZojfL20X1zfKjzzl3UdnFdRedXTd/YdmC+RdeeFGw7IyzyupCF5ade2GZ77CjyhZedOZZO02f7qnI0jjcLw"); - a("hnXl00he6osNOW6zkKNozf7hC6thGE448RhJINBXzww1cUsnWHJTfBztzgIWcO4PPi3Tn8/AqKKS1POYVzqLzHKRw+RZgC4avd"); - a("8uC4Uzh9tvCf/8653ynMLvjr/p2CZ10eRIk5WwLdSZObilMmCKfvdOb84HzUoRfIDJy5JLNjCl4tyOxUR4jg6xGhE/QXo0ythV"); - a("e708UcD3O05irsgfIdlHa8MxYtQpWvhVDpXLc9EN8Djjya6m76xIBHLD0o7fKda/HdfTrXOQwJZfE68M7KzoOvUZbeHJR2+erO"); - a("uuCiBQLWhq8RcFBuuhbePOH/vyl/ma3PuNE5BT7RBh9pgw+2wfNs8F42eBcbvJ0N3tIGz7HBM22wxwY7bPDEDVPh723wiA1ebY"); - a("NX2eB+G7zcBidt8Is2+Bkb/KgNvs8G326Db7DBbTZ4sQ2+0gbX2eDzbPAZNvhEG3ykDT7YBs+zwXvZ4F1s8HY2eEsbPMcGz7TB"); - a("HhvssMET19vW3waP2ODVNniVDe63wcttcNIGv2iDn7HBj9rg+2zw7Tb4BhvcZoMX2+ArbXCdDT7PBp9hg0+0wUfa4INt8DwbvJ"); - a("cN3sUGb2eDt7TBc2zwTBvsscEOGzwRs62/DR6xwatt8Cob3G+Dl/8DnLTBL/4D/IwNftQG32eDb7fBN9jgNhu82AZfOQVuc213"); - a("h0OIuHZD3tEJmEXPrBhgeqrb1YIMRGS6a9XGTkGfVbqTU1B112Yo0qlMJsOi0/tucwhp9S1s8zRoLkbz8a6Nl4NUjv4xTH+Tuo"); - a("dYdFYZOlg0MJ5+/qrsoLJTcoh5+J9TT5zpp6SZHhpl+us+vZst84/zjEKNulb2ZMnEThOEqvjZ0WMzrf31e8ntGfzJ4bioGoFx"); - a("ZUHKLy0tLQosSCmJTxwv7IPBqrdHWbE6oK9Q9ZWsKIFZ+mqSTW/GGEA9KbdT2pVe7ytRQMtweh7N0oAQBoSIniVA1KnzgQSbVw"); - a("okymh6llVJp+9keVOzzWdI1ntzE0E5mi3TKIjlck7yl9+J7THjnOyFmkMAMMpJlx8sAPCnWWs8NA16TuzgFJjeyYU9i4TVByDv"); - a("0J+yCrn1TD/Ukr9K+X8s/NXcTH+MhbusrrPYve5sF8FgMDRlCDOcFfkNqh5n3j5pyfWoLypiYkpavBCZphIed0vXLkDjWHJacM"); - a("+xpBgsbnPOUDKpiIOFk+JY0hGUNAMt4bRD06nNMZZ0BqdbTU7e4gzoCSUx7ApVW5WC4KwYAwLjvW4l0xMaVcJD0wKt8cZSaYtm"); - a("kgdMwCGTBKfQD51Ky8+UNdcVMVRKIOGuGFjGDN+MIdU4egYMbN6Qqh+ZBilqHKXGcTSOonE8tALEtzDD7aAgSFsswRflbOcMab"); - a("ZvRi1rSRJDsPmKtYwQ8fZawKBfqxrqjDiRSqlS58FxfI5MUVsvtQ1QWy+1DWSoNSsJtQ5RaxptWUGobRQfiPKw0pImHkrLOBVS"); - a("+GwsuPTE6PBKmIsqJknf9fNJ13uQrtdjmeU5dXNVs/CII0/dXNVoc06qO6fqfXOqLkW3m7QN3UDhf2p6jqZpOW1osTxGdn2PZj"); - a("J1u4EK1/dsmlEJVDsbqi3J6tutGqUz0OZW9Zmhd0nbww2YF1d4dj2h2+Z8tVv6Tubpe4Tru5roV5LGqkljldQ2l9rKqG0utZVx"); - a("fWclodbZ1FqCNksQanLjMzP0qF3b52W1/R603WnznwkYep1AyEMZKl4Qs38B6cnEWGJasGosgRXxRUQWTuA3Io4lHMFizadTg4"); - a("NWZizhBAKHnbQqDHEivHp/lkgXhra3gGkACoLTYyrHcjPo4UfW2t/I6WYSWIbQT51sX9L+or3zVgjItaoux/FL4deL3wAGoxjC"); - a("L43fKH7joffNW6QtfBY+dIAB+KToQ7ZKYzgwRJ80fcgwMe5tUssJmUm1aLJ0YUrRU5p0eg8LfzIKGakanAfCJZp0cY+gSRdhsD"); - a("ehSUH83o+vGNqarh5WpM1Z0hY0/iKnm5Bz/Yh2Hlaz/LLPWTiV6ZRejrOoTxxlNclLv+nM5zc/x49zCR5BNHK85LG4GDpak0JT"); - a("OfYNm+U5XXGTq7X4M1IxsNfNvy9NEoyTBF91alLTck265Ds3Pv34mIBs82Jiv7+q39yE9Gubn5wYKSHcviFfUa+sJ/vSvvLerY"); - a("/BGdvi2bf2nFnfeL4FKmsGgptghqo3yenPk5Y6xXl7OR0hxMd4aLQq3ommYgfzpviw8L7n3oQjdNA1mikyHZki6aZ4Pjn0K7y/"); - a("cJQBoYDZMNDvnewXqV+0+YOeepH2YXbDqJRwZDhTe7+IMtsft/dfM0PvzW9j1/QB0aODUBaewfIxpCfSBOTBozbYUpc9vxhd2T"); - a("CuGf7xrenSy9oyp/ZLT5wyjn6rK1/+jZl+LgLW/BJVPxfB7JIyVb9iLtMvqWX6FQzrVOFmulxJ+yTK6h+kpksOx+eK03/wSU3y"); - a("xfTVKaJR5fpYtnLbPdnKvU9lK4/Es5Wne7OVF4b4dG4bRbHyhR/xxdoK4Qkx3C8gRBgbMwNyGZDLgFwG5DIglwG5DMhlzK/8Qb"); - a("qIRLmIi3IRRMGXi0IViGJVIIpVgShWBaJYFYhiVbKiXE+iDK5e+QgJk5lfTWo67thcBsmi++5cQRlK9wseGsceZMbhs5k+61y0"); - a("olqC6oVWtQzVRRw3kTbfzKUqp54GgkfxZEtPhcc3qDsknN7i0s3DaTFYFU4fHqwIp8uD24bT2wS3DKc3Cm5tbo/4IT2fcIUpDu"); - a("md5haAtZfOEswNtZj2kksw16eyQDALUeqvI5dwPb4LuLbGgx5j+rxyp5DpNSmz2h9VTZ9t5XEnTbEfanqYRdWKMn9V/MVKyhh/"); - a("/jmT4S3pb7/NZAxfRS0feHznZP7VvG/F9eQ0c9INv2Uymu7SAKavR113nY8q5ExvINhSNJu9aoarEqia7h83XHugpvt/Hfz0jp"); - a("ULx6UnjvnVMtMcP9naitKnQbJ8mvb+wyZy/fZ88Rd7R+4P8VW67k4eLGnv20K67lIAsvR8XNYRzj4pkYsS/vIeFeufGCpTixCb"); - a("EwwAkgeGwOlNsr4hZImmlN3fJ7fBmtRlPyh6v9K3WgmvHleiTo/pAQ9VL6JgTN0/wvExOkdKB6nVjPDWA94UOnlCHxWo6kdyBD"); - a("mfAAQKNFx+wQ1A8SaU8CfTlL7hgDel9H2iiD1mtU96fmPp+TmKdzCgrwq0DgY3D7T2NxSzZXGKasNdGNcu4jP8Yk4HSQfxVWp6"); - a("LusM6J1K36dK+NPxQLR4vUkILMyAPmBuS/MhP80jv57cTscxs8Si5abJEq33AWcJiK8rNa/XFSl9Q6DqNvdVliVgORlzN9qvIK"); - a("+I35yAdyCgJwMw5VkkcFFWYHNDLq0p5cv5elV80qiPyvnr66qeqG2rqpWWdrOa3saC2sh7VFejtSLTV6VLf8xkaiO7Zj0Tw3Pj"); - a("jztWPlo+hnspJ9Kt6m/7pKXb4LezsqBLWfAmlpsozgKE0icdtho1WIKsv4v8UQfv79Ee2tYfSZ8tI36KLHqYmDXRrenDoqUF6R"); - a("t/gPqbAPEREzRi77wRh6w9Yj5G+CM4Dx2F/kNz/emD0WzWrKOjCh1/L4MEjLMPiDp3iBRYsUE+RT751NP+1EYuXklLN5aWOryd"); - a("odlQgxhYEIf6efqXVsfh9J1aTB+wRZd8/2OtPcFSxBeGrZT/NaUfGIPUjqq43SuxzlTQiBKKawznX61lHxkZxI+d1vrQiF64Vi"); - a("B6oqjqg0BtmNldsCMLd4rkmWsG4KJmgaIjzf+E6W9pPI9QcRxtf/MN64+tWc0SIwVMf5+Fu0V2/vse8m9vL5hVRgoV/WfWmgm9"); - a("yfRRZBkwFtW7iom9qjeO08ImDJMXEzFzpkW3rTBSwDmHvxFZzXd136reQTkyh2SsJE1m5X1K0fsC0SNEHNaZ/inTP+KM1y0Tyc"); - a("Py5GH58gxYYmzGxYDezQ1ycsiRAmVSkB/qvgl4V/gjGxPzw0kQu39gYitg3QGqrKKNyvEdHbm/Qw+l5gyRBPcNBTL3N2XFkFqU"); - a("jJQW5PmLPZ7rgXFNn36y4aAtdGEu0QA5nDrI4hrdcjuVWswXESbH/ylNn6onIQ1cvqEwUBW34rHYWEgnDFhKPyyvSKnpa3Ch05"); - a("zNIW9foCbRUJytYzCnrUYPhrkfnjN3ueUTKlSxJ73F6FrbgLQ0EU7PD4/PWeTm1TLTEUlxD7FQfJFJOuFxsb7Sp8fJImPYtcE2"); - a("jmVFzJXU6KzwtQ7hoLZiz4GRYhEL6QR20yotlmO0zv3q7sxa8nSLJe0zUK5Ff6t10e+c1F+kpGW15ddMlPmBM50Yt1PP+c8DFU"); - a("OIuDkboAiHmKXo42QGd/yKo+HSQlYz0HAQSjIObzJH+9qKMhGUr4HcanQJBxT9uxep08oYXplAD+JNGbekifRCwLEYcSxDwjBp"); - a("h/9Bnpf+hTxrfv8reXa0yfPhz/9GHpgzMxxwgzJjl4BRoiRGymSjmukVFbLe6YOM0pODBOk/+Mv7FenJVQSUI2OYAJDkwFh5hk"); - a("lPrmGJb8rKx2TaXJtV8T1ZX8W/SUX8nsiXx1VxgCXMsvJBJg4QHxBUxV6mi1LHkW5Z6qh1i73heK2my27/kp7gpswQaeDWRDC0"); - a("PkEi4uO5blHQ+FqX2OaUiz9Mf0/qcO3XhuSsY9ZFcNKzfVFniSbXpOpdWtWgeYgqdfQoUkccWQRrr7nu02r8W19ZM4zLk/1Vcb"); - a("mGwCV1JNn58ZkBYKlinGEAspOgS2vpBPeWX6qERpf2UpUQQ08nu41nyWzNz+TZ1NB+tmb9KWvSLDHhUBJpEE7yIPytQ0OE2xnJ"); - a("rnp+fDauVlt1h3Cw4XQwvfBgw+fAEeRAN1VKUCkZvkjkuQocmw475/dhxPSjMMK6TMNq88sYqs2lWgnVKsFBuk4XBIj6rYi8eh"); - a("mzWHm4TkBa6ji6olLs1cBBa6mvQC4c3OtPtE9BX41CoujR2CefFsm+qtNvkt0iRa6GoFTWkqDDz4ILH9mLka5HuGTFkGJ9oJS4"); - a("OcpjQIGeltH+hi1L05fxk1uW2UP6X8u055+UmyyZSqbKVLMumcytWr60GLxNDPyWtjwWiofLhBP9853oOwF9bU7HEpwimPQqtp"); - a("lC6Dpm30jy4z/cqfd3cuC7yjJUvDKXF89VolD1B6t58XgtL55jvHjlcBSarL+t6e9rkrfXp7/ODH8l01vPQQeq1aheTDgtmQGh"); - a("0al1DAia3JIRm5umaXIHkoeNNX9rpqFQ81dlzOnUlYH9UZegr4JuCq7B4cIoRmKCKY1dDcBnnLkYl4a7f01ADfKCw76zSECMN8"); - a("1tZawGrg5RvOPtRdNroPmbQ2gAzVdodM2w5pPUYaYvbP5emtF6OWRra23Ct6JZutkfl55vbQSQSDu3zkwT6FyD8xjHymU9ksDK"); - a("4dn+CH6IL+jH2UdraRiHsbTew++2GkZRvZm2Af+tAgy23qctg+mKAhVziWp9Ra3mw7eaRf23Zm39ZlKZry2AO1quMrpAfxYngi"); - a("VxqXUrp8AHVws5Gnw4w/dMTuqCisp/IHWbC8eDwQKMhKyZaZasXHObQ7V3tOLoNiB1FC+mr2+xQ0yF407ob1lMWurHTRC/HvEm"); - a("EUD4/EJVXIC5WKJmDJ3CV+p4PY/vdwXguwAfxKfJMSf//ZhXaMzOWVnhLJswA7p+Mff/YlhRLylfe2k9wdwW0x7FamKZ4Imv9I"); - a("ZcfN9o3x8fBgtAVtviHxcFBg5sxVmjiGGuDCiH47tpXiycgd++nZn6zbTWeNNs4gPSQwzNKNPaMv8AzimHSR3HjMvtnVnx3nLQ"); - a("GiZY9JgUomf6NOxOEBSIoZl2AmapGvWngEmPJUP+yp70fOxd3Zg5SRRIszUr8S40pKwYBs6tSK6J/jfrccvrgvBoAek0bCvqxg"); - a("pA3HRunPySldPhLGciIwWdU3B52qOWr0RGau7N80lEbYZ3JiYux3lSc3E1pDBW0VcoK0zp+UCXL3Ly9FsxjJX3YRh01QUz3ffT"); - a("TMNGQH2LDgcI+6d0qTUrG104ZYcep2Y1eoJIYnThCNi0AZqlmxNWfibrKfN0LebXl+NVydzfpyfAXhZTct9IHntZf92vd/v0lf"); - a("KKb3yR73BSPKVrXkTd7Faf3ucrT4CIJYidV6PLj3vPR7UYiuC2aO3mgRerQ2e4plloCMcdpDrq6/a5bkOOp+0d6mrYnFQu+jg9"); - a("9ELXpGh/EVRK+Tc56WF5bqkZpH042qRTgccAbIcsCq68bhcrdFneGuL5sebbe2FXw2Z8rf1Sx5v5jN9wc8axtb34bzgjmaSe6n"); - a("Uzf0GkZzArdBtW6Das0G1YoduwQrdhhW6Dh24rvbfyWdhrcQUEjUsd/bK3V0bte2k7/E5wNYQdwvdM2iGuQfGNG0odvejBlfLO"); - a("iSsdwWlYWNrHgU9k3J1554l78L4Ik25AShjCJf9ZA6q+EEYaSjOcM3iamMS031KNhZUI7GdVa7K0tAEhcyxE4Xzc9FA0j4uox0"); - a("meF8jEvAkI+RmBsrcLAf0TCuifQLLPsL/4xaEACaKvTLMfaGt6VRR419ZZjxwFh24WLS5QsENkU+xTvwamX/yC7GAs6MOn0UNo"); - a("3c6C7U13trYjNpJuys/MrbQYuHdLHe+LtCb8mIFLiffntZVuh8MVT0xgUE2rmIHJG5i8gckbmLyByRuYPNf6uvZfrBDtv5fzoq"); - a("EZWotAazFoDT4aukfVGx62NHdMXIUDRd4GOdLcwmpSXy0+AQYLOhwu0K4ZpxyPqffI0p3LaHdcs1KL5YyxB4bYS9HGwNvux24e"); - a("bp7Savzt9dNAw99uuqh4CtPsgvqtf5osxqGDX0WcAVHGSRe0CjzeepOIrwR5E7jD1GpWaZK6SmsdpL1cHIhhTYhXHAeC9FPfQd"); - a("tYFurdNrsqKX7BYxwTx8o44LsrsivTZQJX/ChWuyQTXD+H0+107GgW50FlGq0M5vp1YylWqxDnbfS+Rb0Rp2cKaiVHzU5jBjre"); - a("gwToKNnJ6sA2Z1ZoMen5JAg5C8+OskofRhPSvEixQEj4JIlEzbuNhfi+09RPaoLT8N2GZuX961nxq9lvRvis4DN5kvk5bT9NNE"); - a("8sTDQP2p7jIB63Sx3+p7yc2dw8ZoRHzErymLVYzLQYYuhT4WFRa+2pr9ReymTono4n/cgXpaU+V+/Z0cPzJluanWzNyqaV2Fwt"); - a("mzRgkwZs0oBNGrBJAzZpwCZzBm235zLLng+38snjrXzydCufPMfKJy+28snLeQHylnm3B/Quf+RNnkzCNGHLtZrRkLPte7r9cS"); - a("RXDwuYJjRxD6XW3XDbBjc2bORI5kEI+tUNMrZOQI2zVCBVw/6eIrNPf/wxTV7gvpDdEaqpgzvDLgU8MoO4CBxSsNuiEloPOeoY"); - a("MlNYyJba3qdUN5bCR0LVlgjVSI1k/X3Tje9HlMxiZMN0OkLxY4E/YhZCtAjfwSNwtHsa3KjdQz2I79UUTyi5OiYG6B7Qi5FD+S"); - a("O87VaY4mvAeE9MUnZLk01Cpnsws42wqBFCF1Oo3SqmyE/FJKgks7ES8qQoakvXliJrwXCpY7k3BUOF6Q4g3KoDNMcCTVzFMEjR"); - a("yU3bVX11uuibP910B5tBt5NB88npyaynzklnbRom/HVwg6wxtpMJa1bcRP7X5n8Y55FTzLk5k6ObsUQON1JckvWvTu6i33CfHm"); - a("vqN6uAD7ZPwSUduSEkB4Y41jnkbXwzjTuuS2wFOoDYWe9Y8CXE9om/Q26+HlDUki/RkRsBx7QiAxQegcK3+wtNHBPJEpxJBAtC"); - a("ES1mTVYztwPtfBej0MSnW+rOk71lYYwzwYNXU59ZnX2HmDpvGkk8EdT+YuTbKG+FmNv+lZi3ZsU8/wvuA/Ajsc2PNbdc1LBc1L"); - a("Bc1LBc1LBc1LBcFBHA7u15+/1Q7v9HkRu3nVKpIX31GyWaX3fjMaantm03z5LBkFLb/LszdIACU2Th4QJsDispv9yFGprrPb+7"); - a("67aVUQ0PY3GHeajtCa6HJHHlvOZ95hQFR6gh5KxdWhQDIZe0+F7Kt6x662LUlwxKS66kNj/dWINqj2aoHuTon4g4mJ2OnspBc4"); - a("b1rt4yIgoQbXnbph5CpGyTxECy2eBcMhj8COLuYh5g7qRl38lJIJpKs9Mj8nIfj2dRiYyh4QTlKW5zQ+iVODf1dzvQskzADNpF"); - a("So/s/29rbf3FoL8Udv5e6HAAO/8Qdv60mtUnLn+QqPvaQpX0/1iW3773Io+/qsdf9bX+tqkpdAu98yHnLlz86tBMZc1qVexnfa"); - a("twxbgZPV+dmyR85k3obystE3ysm8bq75o7qHrfnyPZmk9wWMiOlJGN66lz44Qve5PA5jETmziStk5KFXnIvFsgxSBeLxkLzqRk"); - a("K1QMu+12FqL1ZSv9km6OR3gq20kHc35pRcNBya8PcyInciJi1yTmIO2qhFmQxZT1nzlmZRaT+qFRZFdQlwF1GVCXAXXZNPyX9s"); - a("kwPdgolipE9w/9Zo0svZIIufj9dnmcHy3Ojffh6I27umLMMJl9lp+17+UOwbd38eI6XGJQMhDzw1Qk1CeKhAa0vVgEe4TRrzDV"); - a("nN2QnZE57uDTl/PXgjWr8U6gr9AHzo970OZN0rUdft8zcTRSKsr6SlPKNvXj3aLbyTXZ3/SsDC3aLSm335LfYooRmFAM07wVJn"); - a("QPTOhhmNBT2F3brWm/H9BfU/UAaawSx9LPrJjw4gYUGI5cDQp0QZPJhFwdG/MrWISScLVQL/Ga4aZDqr83+4ZHVatdwE7H9ASd"); - a("WGMydIenmz/fRRTYFebb7qEh0pO9uOhXojLu4ZMR36xP1/2E0kfnzed8OrGLG6F4oPXrYGG4m/ZlVBv2D3e7WDjjbijscPNX6g"); - a("XdzDuOGwuq1IxL6hraA0r035Ff+bwTei/FQ/NMJDe8cpLh7xW7zVl8fUCVhREL0YlT46eVKMPjrvo0fwVVvWlQ9elpGmf4Uzh7"); - a("boIiPO5sXI8jULsWA4EUyebz/u6nS8pb0VM1eLY/epkD5Hw1ow1FkAQWXSfGlAXdzfWuT3av28aqra5ZtL6y4D16JGmGPkRzOt"); - a("ohyepKfsiPhX8RQ4dkUStDsrlBdn/w6aNcXhkTQB3dn9YER1CTlqI5HEfj96TgrADu3DwnVYSKWjPUuAHdA3kI8A7J4rKYT/8i"); - a("pgLHgJEgF/jtczwPfgelS9GX8ywi5MSV8zTQPjt6/C+tg/WlZ0eP+D17qW/4ByhhNees1bYjW0BJkd5J5W0yNwllDQgmKftMEB"); - a("Zln0hV1QV/ed+8NrZDWtqX5eDHWJzTSrXYn22VaJPDy0RMtH4Yj6nHiT4ILtf01h8k6+/JeG6j/UDmClqYEvkyh0r+HL8TpwmW"); - a("PdBu29GuT7Oc3Wj314w2vRaDPeE1J7Tln2N2tOQoyZejDG3YG75hBrzUgJca8FIDXmrASw14qQEvXWt/kOl0L3Q7BLlb8DTX4K"); - a("IJT530buix4ouCzQeyzQjULK/fyA9uB+LVb4YcnigKfoZvWfCj4Ae8uQ2tzRPb120uN49sHyzF1xGaqcWwUxEJcxrslyogpdYs"); - a("l64lG5YxDsOaJyqkxRHAzSMVwS2aR8TgdvSpah7xBKubR+YG12seKZNaNb4XQ8wSojN8HEDQBOzgDA7mfW5e30+LWXwad1PwqG"); - a("oZCckdnjg+OC08cXnQEZoDTAdRw1zXnzrf7FgPyde8z4zK4AjpZK33f7j961bIC1R9VjWGZ1j+kkSX7RXpB3Dfreh+cJ2m7I3i"); - a("2rtFLi9o+oXmfabhnlMx/ALDwkrXhdHHcgd+dFZKrRejSVnmB0yXnHwsaKkgb/1Hh6p+tua75vqKMk9oI2kpOLIXcm/n2GaHX+"); - a("NP5UmCh18gPwffgNBWLC3pkZY8R1yGK6XFJ/FK0aUbNg+7645oHnZdWtY8vEndQVTbzqylMWBaLIWHK+VIytwVMky2Ib/akxo3"); - a("12L5bcdRmwf6PArtT5XE8NzGxUZofguP7b69oKFFdJZOUfbgRTr0fZ1LrUkt8kCJwzy3ilEvE99Swn4BayEpe4N6dG9MJacQRf"); - a("8RU68Qgi5lzQdajNdDMtdGcC+GkFa/G8PVZXB9/i3F1xGcY5Yp0qtdit5lbkS2KHXw+npUX0BVDZchQzH+MJ/7bw78PRzWTx7g"); - a("wVNyQFL7AlKgt2rQ+q+tSdE8JPf/sMXatl1qq7uDOwF3QA6b8+XwL3MWOXco47790WRLYW3zN2gDaqgUvHOEGJ7mlZpVTc/j01"); - a("jCDaHlC/oy76hZGPCmVD2OZ/W8fCP3Jq7SSdaYqSK5EhPpk/vwgGm5ed77efSIja33zq9PIkuDooSgnxk+Mie8IAIvB5QIOUAz"); - a("ZmXSBYKml1jgslqHiLGozuYN3dwmeTXvFfkoS7hwjRCEVCKLHp9my8CA2F7lFuo3oTHRQ/7g7DrAm6qi8EvTphMTaauIiqhVW2"); - a("dxEmtHsMX3NEHcuP0cce/E2aVFbXxG87n93Ip7T9xSCi24KM4qqJWqvBpHnBQpjf859+UtUxx+n80b995z7rnnnHvWfRRoHR+n"); - a("0/BiiimgNvdIHstWIeLM/8PCEfS6KCU1F6GpnNKOxRgGbGd9D4xauWaXyFbYPxF7K5U7WlNSawkKYFLaNuiHsQh0kO0as87Hft"); - a("7hvU31Yw4LxUVKe23T7Ocd7nHa1wIDEYZcYjkFoVlPQyR4zFMmSRI0dQqmKAObhXu4VhqhEIoNaC9tRu9xDRrkhlRlGEnuRsry"); - a("4Vm6/Lw/3eIARwBTcZqtFk6w6a/AoYHD9DqZJdBhCPnBqHwXqGrhWthnhai+y1nphiySPw+zpCy8g0uKoq5QOx2nYfCQZDysbv"); - a("r5twAOA3Y5VaB40H8wWQxFqJ1UJknUNUZBgMh47l2m7WTre6/e9wusj9n3Z60qa99fe619T6K+aEE5OMYXRki4ydv4bbjJ/1uU"); - a("omcLIihWXd3knfuOEktRav/AUSqocoHohGspXlLM8B10HzpV6FfgIZ6j9fP0/AD9eWwYXSK5stoA0iM0kUJLcavEFio19dHTZf"); - a("9owHtjz77xsu0wACxV7SCkWshv2TqI4PtkRfWCg+kYy7g/V7tR6Yaen055X9thBGCWkUqLN7k4KI9XIAIAcON30Vi0dFPLZ6hl"); - a("zR7RwyyAvisyetvgXG+Fs3ANsflRYnhRL0RtzqI2UxajwRw0SB5iGfYGDJulx15Gj/PQYwysNzSwDqERBoQ/+2FT9TxtdLwk6S"); - a("r22MAxzmoy53mjlDZjoi5/TRNNscuaXz5H+CcJiOCtMge0T3oY/gl8kyiCTi2wzEMQyUP6grCowerv/P08EgwzOmk0HlI1AMyf"); - a("A+ZD+7hFvgX5BYrsgtOKIRnaIKnFpn7KLBfr+p8sQOWET2T/IYuaizEWarP26pMimnJCr1zTtKi1VB/2KBo2lcN8hdhjfxjGGw"); - a("lYKbN5eUIrXmjl85ZB5vOj+xvmumgolYKJJfO1PNQA6aJZzj1pT9OWLLD2DQzq8gWjdH+XGl3kf897zYmcSns30PGDC/YO4b0Q"); - a("Ay/EwITxfClShzsDzF2+DBhDDk+3wfh8BWBA+H6NeBqq00lPotH/Y9tjwAVxde8V10lCa2Lez2MBoZsa/Wuag/Bczk4bdHPA35"); - a("rvQoBf1sVLvy9cRexxGpqkmCkewVCAk2zrBhydrHlUx6OGUoaKROsB6MimfhlP0+Wh393S0MUQZ30ZC7Cm0X70z2jmxtgoVm2A"); - a("nA/v7JPxANQ20KAXNb5oPi0y+ujzaBxrHqCc6FIQnUB4yCrqKCi+gARtILYqWYAxCP+3+Xc0WqxPogHvRfsccKKhb6a8r4YW+X"); - a("9u3h4e3llWeCHAA6fNUHPnhah9CO3hwaASoW2AhiQxfsfD7hHufcF4xUS1BainmxUd9QY73rvOJ8VWYVVwgB+M7+2Cr0aqeRQK"); - a("XHEtZ7x/MugP6f6YpHuyV+J779xD+gNPuzQf7nkbXbkqneYtatIIb1EQNkgph/ghpSqkVIWUqpBSx3blPH9Yt4FdDZj779MQ/j"); - a("4Ifz+EfwDCr0H4UzA4sblB3BcY5ykxC1D6YyDk1OpXLPNe24MmaP4NuGOAokuWfe/8Lq5HWZgsBL+rO3z9pZtafk+b3UXj0Auv"); - a("bHK8t73989ze/32kQN+ydgQm2MdpjSqR3SXq9nnoF6Hyfhr1+l6iFe2Lx2nJauxJTIG9QAEKwVoZhIvhPsVWt0BYBMf9olsEb4"); - a("4yubGyoIsaHQC5NZBbD+7Y7aX3UA8NLorm9XiQqBIWlwnBjyB+EGUzh7qAnbaqJ53unGTWejrtC4sJBvR7w5RU3wDz1nRabjOP"); - a("dEiv0CG1t30BdKmEGvYY+IwosgGCHyHkVjeV1VIqWSYr6HIARQvv3E+I154vyRwfsO8hgJ+pzW7oNKGX6dDLtMfetMLelGBjVA"); - a("DlOhTtDjfR1505cxoCKRs6q024e2XgTiaojnpwk93AWHnt9SKOUS7zjqq7Y9ppS2ge3ebyVxFI5EKCVs4z9O2aN2x8dMbnOt+p"); - a("G+h8ctpCrsvNbLG3F1tsafsO65QXdG8B0lEN8pKCvAyLCSBBRsbg1U3VsM+rMrPYSoFf6xJT0R58j+cAVysdLVHiR1W4knn8Y8"); - a("7qoBwxqxmELRmWlEW1yNOWYl4LxLy2unG5myUPAMTUtOsXZOb1Ec2ru0j3N4C2CrRVoK0CbdUoJc6iL85Cpp73jJNwYSqOsc9f"); - a("f+A4r2yeU74fI2BqPNotYthhKLlXhtaCa7YGcvTGeFCOB0GIqaGXafdC1JEk6sBhPkTcBwISm5WjTauP36uAs/FiJi3L707GKW"); - a("eR2Xfym3By/F9EC6ekh+aL86kwmfPIDltP7u1l9/9R8Ry+Tl+BCKfb9NTtr9nWoWSZm3XRnIIsOu3s12y8OPAZ67RvonthvQBY"); - a("zNS6e8D9kauohJMCrhU00c2grAiXXRfR1HoRe9EfnD/KD6CVx2Jdp34R0tYIKlJQdEOOodQhDkBCkcfF6h7yTBx+xGOv2ua7Ce"); - a("ZArgdp2tgsbegNwMA1uZmu6FF8pU1gE5eKjX8M4i0AxveZQBXksv+D5s0gBJO9116ZOanRJaMglo6ALB2WEQM8V/jd5SHdq0bs"); - a("H8N5EslZhOYxKUITjwmQejA53Q1aODZNw72p4RFtZR28JujdvzfonYEg/XrcWjuri2VEuxLj8PAYmrq6hnvENGIXDScLqMWJaP"); - a("EP+pLUnnrOMLXu+UkshlocjE93kT+Uy5AuHEYjgeM+Gq3aOJ4A+rgtStH4z4wHqBtRSIDPs7uYtpEi7bI0czp40zwckoW/g7He"); - a("UOyd0JQfUAbswlK35CIHnrBxmX+guRCuyzY4MNo63voGYXtEdmgn2SUY+0r7CZlneGxE2S2Rt6wLxr6jnaUS29F+OOUCmoViJ6"); - a("Fyb7oGDmniCW4PSgRj243Fk058EQZkURDgAUhwRoguWsSBLIhCBm3kzk/hh5/oD9uGbd2rekPx49Iz4mfkpJN7ZuKTC1yBq5uk"); - a("Pd3RCqvUYSqE7udQmqRUcGDzWzpzhvYLXUH/ypZeXIMyznngTKVC5xZmKJwUEbYzIl3NtWg/Ix7MSZtKyz+/eSsFUUqBB5gysG"); - a("dhNB+6rFuP7aJF20pc0zlNZ/0+pFscl5qSttJAruWjHzi+5ZEgwNhl8JIkhmt/tGNW0YKluH6Zptf6nUVJzOF6fppHFn/waVFv"); - a("LOC+oPFPH6kjFbljFFfIvW6h5lEQJ44DxCXmR8BGXgzVhKg6nq/VfsBGhxy/id7SvrbxKn6im7w75JKcCTAqgxGKekx7CNwcVL"); - a("cER0byQipK4xT/b95r6Dg2eNZ77aW4YG1GB+xZZ782Qvw3gCgg0iot48Sl0Ai9xvPm3ehUj35bpSsMDkWX1UGGMxGB9iFyy/sV"); - a("CPgLSagDMuqr/hTWj3b/n9kUhPP7H9+b2+i/zi8vUWIfBi2fNLEZ3lQWcY6Lp9+W/4aL9yoFZ4lt9q3/1xbgfz75XjRR6wCY4g"); - a("RCjaYwAP/J3hcX1YpaUqF95DK3M2GDIF+g3f2Cvp/V8n7mw3fgkjuTXn5QNO9x+Ndni/Y9Yu/YbeADtll+JxOFcCCG2CSH59K6"); - a("pRyLVEwm2Bnq5yCYGkR+S0RPdv3O6YFgvSxxlg8RfcNCUQe09nDrflpe7KF7iEvugvZCcQTjJXtYwd2wUoCjIFfvEMc7oQLpSy"); - a("ta/3e6O7YZ+HXdiW7TPyBzGvKjc0t0mHqWGsoBXEYFXtqZ0D+mX5Cd/yn8oosfRsPmQgNWYEDcZazYj4RERHwAosR4T7r8FRA/"); - a("4WRR8lI8YTWgJfMRmZnxvlviVHp3dv/xmCGTf8f+/k449rHBrE2wgScBCcQSengIFZYFUZGE8zoMl/TSVTlYj7bG2DkaU/aKbB"); - a("/Tce4XAlRjJw551CDqcAPBy+yv/h7v7MulLPZa8lmb/XLUUje1+T0cS6FMzWJfdz9rs9V2RTuqdSwmgy2SB0M16QahMb1oKWAK"); - a("e6dQn0KyWGg47QswiH3LMPIP2gp8f4i9Ve3ld0hX59QD/b/HmzOZsvbadnIJIpvEPpuyWHvhBd3woc1qH+3BNK1tso4YeymWaq"); - a("ZHmE11exvpik2FfbN0MDYhk4/IpZe4zE3maSdiBDMXUW2eZ8xQmmgc2SbRXrv6QEKjCByr1QOLZIncsV0u3U0BMMGXZibC5H8x"); - a("gB8NmeVUZUReOqRtyntGj/AY8bQBTzU6Q6xgGmgK4XtrLjVxniTOzp9vfPvP/KmLUZfBoj1uSbjrGfhCR/h74LL3ZNTB7EHSJ1"); - a("1g47yqJegQPwSBgru/whXV9ws1kfpJ1wsnZ+deJ/+aHr7Mwd52YI/UHMltQRM2txFl6fdke9WDD9eGY8MoXTb5eMunbfx543ts"); - a("h/8EFysU+4qyG5D5dPnaAfjn63IInPpFYPIt65ZVwES3qlCvcQgpkXfXCOmx5zRuecomUwUClxXYKy1B7WkriIKrkUyGfkmXnw"); - a("7MoFOd+si0p01sZunKrAbtMaAlFrDjK2zPCDWozcSuQ5iWCqUHFiKUr6ZNJ+E0r8fKd3lnNwt/D+bE7FMpv1tbMJMYvlIRdnF+"); - a("k9qAhSHjltY8SGoCMqhoW4ywDDbgKbXzqAeCl9iopG/kjsHhpYSh9jzEqIBaXjtiUf8O/MJMDhFlCYsRw7FqvbVTXv1vRfMQdN"); - a("g1oQjONrEm29FAwz8vAtMRp2cIAU16kx0KizthrofwFtm2GpR0T9FHW/2RnBnxwE0mWi2fAVpF95A7dszF7sy6aJYH7pb2Wx06"); - a("+bsvKMVjXUXR1GtZ6XV4codOQ38ar5jH6xYOnFUiA45HZKT5h1vzsNLJ8r+/Q8Es4DIPfKZd+RytDQHcnoefpGPhRu0v413BeJ"); - a("fRMEtXxi4aSQivbxRGnZ1zeDW0K+eN9b2LdnhpHq6/6mYzvmO1O0LZwN/ecku8xRa/bdtizf3g/Wft+8EvU9e5HxiqfqJQ9QfV"); - a("Gqp+mu7KzvI5UtQiK33xW/asdI41K830GGM/+E/56cG5Zn56w9r/l59+c66DzOvWnw1fGfpTOAekPOtM5WnEMFY+atOdsxZn1Z"); - a("2HL8+iO7Pryw1cY+jLO//Ipi9PftSmL/sXZdOX4z+36csPlmXRlw79ZZqTIPo06BKhs4SHa+qbi7B1ZNtOs41n1WM+7O0OLWgO"); - a("uqVt0LHHGy8KCYq5kOAL1s009py1jl3emW+328BEJJ+u9m+jKF2O0P3RUl0vz6aHP4gaJxtPKLG1aAeSIPAJfR89QPavotTzfv"); - a("Gy7QmR7XJE3nkTeHf0wRh3KeyQUIxmqtU/hUGp8sp4F0ICF29IcW1BL9kBramJ7pEZbrkrS2sYS789yQ4Awif6NjWIB8l6wU69"); - a("MBszA9yOAWwNX0HDbPDvw3NBPjMz7LSPdgQ7/uf8T8iS/oGPDKGyJn1aAxQZeuFXIVF2Pm97yCZnqYVuiXw9dEC+hZyrdPmJ/W"); - a("6RjzG1twgQuuiLBHly/FhXAnLBc/yFA7yvPAHKoUpQrvqMaBAvOYb8nzlP67ZXcXpdORvH/riTvj8KCbEGVhxb4zdznVujPf7X"); - a("l9EGqzgO8Qfrwxp9i5T/pM7uIVLrhq9wEK5ssdH398BbqmA5ePxERD7P2wC1bZO9V96CTiAKnngvV43vLuRNtcVD3Ymhs/X9c9"); - a("lqIyTqtjryrQHrA7F7plrzENNKlto8URRTgRDgUeygILsIlDY9DvISO46sNiKlbnnpt7J7l3CvR0xLxErRph9txLbxD/YmIjns"); - a("FUwLJzJ0iexuCaN6eS69iKHqYkPi/spjIpJKkM7iBjVKbASMaVeN2et1UkGQpgDhRIrv51ZQi6GhPDA23dFah6YsC035Q+nt1Z"); - a("1j7+yX89BmhCsOGmmiR1UUTL+6YuPGzsH2wfZoTaB9BCWEdDxyeXhabJNzFRSq0o0S+zJZnvUxfUVm6DEM2Ng5QN9aKac8More"); - a("lg5eNjgKqJ39FBzs7Kbhtf3im4AwScQG374gX3wsJqHEL0qjvtp1Xh0+VqXnsxUsG9piKSMVBVdvMqmh84uG9m/bcfSiPZofvm"); - a("ywQYoUhGJ9nDsP+j+5cAl+A6/T1hLkPJTLe7kLKBGoyC78109/vbPbMLi4ynPpV5d/Iq5yvFcuxNXQIpeEseqJlq/jMsE4hKep"); - a("m0wCYDp+uqxr0COfsEyJfZ55ddQkF97VSzJeBguTeKN0rG3zXtViDAX8Mt+hsI3nFeOVZB3PhIVBba9znOCQRM6XpAu2xMUoqH"); - a("D+RFxI/YB3+WpAp9df4uaq76UMQuHEEJ78DZ98AXP8OvApyYbPutF1/x1dSXLhQ6mEWNonXVAgkErur1z2A72R40ekg/5fL9gh"); - a("GEvKXcki+bJumo3Be/T4skE6X09vlksSBk2OD7m6wYGUy83MEaJxgTcU+yk8PbY9d8R80Sro/+WCwpD/U+9Va8isQB5bjpVVDD"); - a("2Zgz66XBzMcjGxsXNF+4r26DYsF+N0tv9QwQm8YssNy8Cxpgys732xb+mKy1Yw//cx/8+nYTRsg24qvkdBsYX/ZfD/6jH4/2Di"); - a("/4mdn6F7+5/t0aJw7LPwZSvs/L/Uxv+oWf8TXN2FwQEK/M9//fhr8D9d5Yn3aHmLuAL/X0H832nyf4vg/4N5GUsm4mAT8f/irq"); - a("+wyIuV2LuZV8GJLrzjFV4cLBzCG8H/tTb+30nwv208rxivJOt4JiwManud4wQ3Nv+/bOX/x638f7f0d3zyBczx68CnJBs+60bX"); - a("7UB3TP73ElMlC238mw/+pcfgW2bZ49BF4TwcYtsq/qfv+GQtoHPaS+v9+i/jSYaBJAw4z+/pNEcQovRMRATE9srD9iIHYi9CQT"); - a("JUYdNfZJCElY3kUDyvGIFHsnsygag1fW7ky7Hv0Z6+ETqmeciISKtwfLrzN90W2skZh7LUP7fX9tXRpjb7QbZK8j5AgQ3hM04d"); - a("1w8HMd0HXzQJgOXv4w547HJ2joTAY/NJ3PoBs/WjeuuuJKE3B3faVSdyo3az0RW2IdvEkJPFkFViyAPN1ofZhjyAhtwVQ2pP3W"); - a("+4yN9JuF9SZXORTf98g7TTcbS//2N07Pd5n3JMMm/Fu266e0zcnfEe3639ie/eE++8Kb5bJO7WF3f7oqU5KhmXebIaGO7WDx7Y"); - a("ATr5qSUFnhoWPCWi2udlZM4txy9C5qoeuRTtwfvssYKeSuJ9etlaR0Zg+GF2vndGwRFO34Dz47vmwO8qkyIbyuo+BfyRRnU6wh"); - a("0+8kWmbiZMx3N2MAK4gmuAjRrVy0Mc+PYB32Ga3M6AGz88BWQJsXEOxHaoJBmll62FZLD98BARXkVXsx7Dnqsmu+8W0El37paP"); - a("sl9oD8KMXb96K0h4D0j4MFyYp+HCoHY1Oi/In7kIDXChdhOyayENB1KoVLFlgnbkvQbGiwnjS7dhesPDAOXghbiQ8szhs3Qqvj"); - a("uuTpU7LgEZC3FXFlQrk25KrHN1pQ9HNFAfGz/e11T9R6YWMnosvaQr6AJQlnKGXAIzZzuu9UvpBVvfgLPpFF0l9sf8juFxEfzx"); - a("4ZSN+O5NXPbRMEFVCoIkhVRCH3jRNZSA/GaGF3W3RLFHqfK6kGBlaiE7NLgh4hsbpHXQHLvZ15gsBsngU6bjQ4VcPqLDQcCIW6"); - a("szCxhIja9lffGgoUBkSHuS+WLq1fAiMPsmKskRCM8khAG8gCqRCu4h/dtYkYJL1zqJGqC/D57bBKqJQsaVC55W3EexACJCjRw/"); - a("Jg3XsnlnubeHZIbWA/ocepRpbBkhB3l7bREKWpHjbFuGdhkqzIGZwvajgTJUrD4P7+xDXWQxjPia8VH7lj6pddOg/6S+1g21GX"); - a("fbmeGsrUiuDKJdMSn7gK0zCO2pVj4QfQSOJhnFGlbND8anuQjzNzbG+IInqL51W1gQTwGulcxYRIDI8cZvxotMSw9a8qagBhgP"); - a("ATIeMMAF0VtHB+Bgq4gmROdL7hWspjhYzU97BzE52I1ahzDgNB/OxDjQV6r6qIqBOLFtoq6bBHOBnRKgZ7+r9XDCWrCeS4QJmq"); - a("cba0n2mlhPFM0C0MfW9WQgcZmA9UNNpQnMBKwl1pfqfTk0s5PRgRg8lsO3dJpbsLANdqCA1g96QYVeUKEXVOgFFXpBhV5ANe86"); - a("ziMv0urvZHbwvjhu66k5ErhCO3pLY8dxxC/hP0+g7QsWaBH6aM/xJ4ciuUgU5lQbn2G160/xRUbqWgE9TL1auFe0XFtwh8GJy4"); - a("gTv96C66MM1Zk9P1eOYdh/ltKQQKHKwwkjZOGItwJiFzcFjXQE/x6vK6KQpOpBowSDWM8KIpywxuwc+xlWIgaOgm0dLaclohI9"); - a("QEwfeAoxC8t0S0qKzAJsHCIg3qBfrKL+oh4/wxKJFUZCfwKZ6JSoykW8KaWVtr6deVxCUy+g/Mh6WCZ66gygO+f3R+t6bDW504"); - a("mEUf/nxXPMWzyfeU7CmKCDfl7MhvMxOuxsFkXyAP37uOrhM5uQlorvjU8FYu4dF02GzkaIJaTKPsW1FPEn+CckP/MqAxBXOlCO"); - a("U3IX+7DXBNWAL6RKtNdgL+vifA5ezZSij3Tb49FqqQgPTd8qkwwQWXByLCfjLeSf9tcLma8nIWI/U4qM0yOmB2IBxPz3l9X9Gg"); - a("jKdO3d8aJgD4ztV90nI/CAU7o7BV6j1dLPPyxwoeQWH++GIdvoLoEMe/T79MHu3Eb/yrblVDfFMSNrhMbJv9r8XK5n0L6rMPPH"); - a("2eO/Qyea/95HUD2/MoTlqg+oHtT3n5J+M83zwEmD2DBhoahBTy7N77xeUdo1TjxHMNhTktwq4F974QfMi5f6eFvf24fVpC8nC7"); - a("0VvQvnKhFcskdW/zE+PXQqo9hg4LdPBj9Bu4SFbkpNs6ckOgl3Aq9G4Kt/ZFWLz0H4sRL4oergwrfXhefNqDt3IpnlvBoXaMEB"); - a("D7TD+7ryerTgAF9Q3WKomXyVkIpPndH2cIQSjxYhWtskQY/GuqHB5Tct+hv0hWpGEL9I26hHEBYIecRg8V19yVrSDWQJFFFE0f"); - a("tiQxEZof41OI+tgDMxiSIFPJGZhSgz9F7RzDG4P4KxVPZzTiiakNotIoYdcCrdZvvesdowQVBxn/sNc1+8V5UJ2vELGW3vjbZv"); - a("ZJPKq0pukNBFD8MbdBaSl0ex46/wBx27q81KvezxxnlMbzl2cEWlmsOfSdXJvfNQm/BX1dbJIeQj1lPibQUBNZ/aTE3mAxxdoO"); - a("3UkxHZAfXr3mC+oW3zhB5iFLyrrinLj26u3wfVM/JhoEJuCEQlguzBmJbuS/oT2DoXKR2tNB9FnW5SvAeM6b3iEgzLPVhE9S0h"); - a("0Z6p4miwroB9fjC757F5Lj4TLMdurKjEr70E8e17afgbuQVN+x7hz2Des2jeGwbgtETW55nPrqhGIyJEsggE0O9V8YMvGRAZ9m"); - a("cyhC10wAmjfKH1noYFCT6stBNkjkBOFcgZZGkIE11eGpsuRwBOppcMJGiUDHX+ou1a4KKssvgMMDoIOOODQtMaFQ1MDCoNQmpG"); - a("wQaFwtXssWvauo6WbRrMoG2K4mAxflJTmWuvrX202267ZZkJPQVKqLby0cOsLSWrD2czMsO3s/9z7jffnRlG2Mdv/RVzz73nnv"); - a("s6332ce+45G6h32CwcIsM7KFIf+OJAjlOpsjtJbwPn3Y6+ROE46zulEAFRtlOWjT01nfvflscdxZgf5xmHrV0C9owJisGBY9Yo"); - a("gGZUhez/o7OVRAdeSvXDypGAGOAgR/xGIzGnvJ+Q56sWiH3E08QMFlHsZK6HYR7a8SqTbZjqx5LPjFL8sdTUIJKgC+jPDRzl06"); - a("LS2n8txpIbYMRX17t9NXeMgNEmiipnPuc4LE/G7RwNTqOeUEqgPYrvIVDmVGYiPT4sXU8EkUA25e+abRDT7YJOdQJbwWJN9DVE"); - a("bP1ovnZJ2TEWTjbWnuaTM7r3PMcLxsAMTQlpJPP1m8U+TVGY7RM4at8Aal+HUmSDyZFyHPPPC7xfVLPffS6i0I+0s47HztriVP"); - a("Bfb7HVQt0g8+yqktNd/ZBHq8es6HoM6a4eFxV7lxuYu4sMIQ4jGymR1UsOr153dZPyk5lnkq/EXq9XRqzXZcVKrxKshHjPsmyG"); - a("tqYYxHq9cGtGad0vesEKxYR0rjeEdbLe50VEmxH9FvXJJydpyDw5fqzlK7Z0s0a6k3jHY1m9BGXGXtZj17/mjPW/Lnb9aYVL01"); - a("a4tLAWDItMkG34ETsypIs2bPp32lBxxjZEjlfejgiHTFgaI9+bSe1yPosoZlYWV1+APimHNIXVX+BZja4zjjKi/L/wELgTIMk3"); - a("1cfZDSt15uB0clKiXrRe8kys/ThrjXz7IOzZbMMkfh7AZPU0QDLd0i+k+cQ78jnoH19HLA2Gnvf3LZPMhNYyKZl+hLRWhZS3h3"); - a("1/1/0FzqjqF+tkk6LSvUvNGGYhBFuQKl31iP6afJhKxA0zqeZwvSLSIQ0thNBTczT055fjQ46G/ogg2EGWqeMPlPh3SPxKxgcz"); - a("FezKJCW2kYSC3YfTVqjYh4hDvTmYugWJDZ/wfnMAqgr0wgyge5JF5O6BOMfAcljKFYhVbxkgWyP7WzHd/5ZegyMv6TU4jKBTSU"); - a("P3ghrrro1G/sC13jvTDB4Tlkiwdidyz5C5G2TuFzn3dMzwVrA9VJuScTSxqS1w2q3Zn5gwiGSWpvvOjxPdH8kXsn8Ot+r0r5f0"); - a("ZxL9FkYEznaJM1LiDJc4stkx5Ml0h//599EMwekkVEujtp++N2Y6OzwqmJPBirV0RE69BuHI82RXfHsY/rh/A98Whp/aLb6j/m"); - a("QQ/1Jfb4g3xOLvYOrm6JSo9Loe0mf1kL68h/R5XdJjv3feJe9vusqv6e5GXtwQ/jN7dOX0YKqxQXsG/JS4RpGqvDH615LR+IPl"); - a("hlbu3CfqZeW0dHoNQ4n4AcIKiRBqb33s9sTOf2WX/Ju39DAePaQv7yF9dQ/pv+whfSTSD1lukEetqHRTD/l/fLH79He7pEfLFz"); - a("CeI+Ngoz9eShei0velc7pRpjP9abgHcBjFxrQ5Ap5rN5P8RZ6ra8m7Cs7hfJJaY5iQaFmVjDlvTJ9K2xijOwP/Z+P/GfjfOibO"); - a("nTvG5DaPibesVlEOW8pr/5rXgtfTKLxH2zeDrlpJHAipwrawuHIt7nmO42MlBLaoHHnnGQjZ8WUG9yDIQYWp8hedxpC+UByScX"); - a("iaaEZuvs2wPNhr5eWQFC0g/VXSBJlNAaiA9Kc/Q+lPBv25OFDsp3sPyMIpT4D1sRleauaI0aiHgK0MD9bhNIb7ABavaukRU5e9"); - a("eWz/YM66KWjURDRqAizDzR/i9LbYHN6TxmXpMLDpJ/sLdKVFtwm8ibViCQhuB5IV1gJWRG1mo8bTntwcud+LKtHYCNEbaQu5C0"); - a("nX9SEYw0OfkUwAVz/0tBAii2WZxUKwrb0v5HuKo/BTs42qhF0616c07/CK/XKjFlt/cwaYJo6Y5mUDM835Y3Da+hPCYBiE3Vfg"); - a("/wFgnEvBOEnEOA+I85cm6OVtagn8oWgHehufDwC0L5R6K+CRyWgc9DcgpIEWN/NIL41HyiSPkLAGtGaF05qDVY6uDfkMQUzgTk"); - a("U0xQStPLbAST4WqQYq9ZVl8/ibSHRfguaUURMPA0/7Lm4luBUwmjlnjEkLx+Os+bFoA+uXvYA2tUh4wS7AWyTsfBfwnwSMNtwR"); - a("3obk00hTRNp//M2Al4WIn3d3yaBHUSw/Rzn9wsu5BLdwgVGiT65TER7MYU5Xe7chIlHo0x0J6cp1ww+9RYddzDyADvpOdNh0/L"); - a("+Q4F2iw2ZTh70sOuz89p3avJCkHt2ENjeH9dffAW8SMKUv3Qn497H76zO6R7v7v+afrHBatpOSfy7lScKdrTEQ3yUEhov6bthH"); - a("jghFuOQbhDXeMhyRvBXjPC9lHCGPVOKxxPVQvxTixRW9V7KC/FjtKTTe47a8KeRJ/M7Xp+K7fYOnEpzJbqKnozDTsj/KqJ3812"); - a("P5cVT+J8f+u/Ib//fy47n9/2X5t5/6N8r3pTy8Md6QQ07boNhxD8LOua2FSuGak+RhpP3cwpzGm9+a5+t9KzmKMLbiBZUvYU3B"); - a("InTMsr+3mN6Gl7DFCEui9aHzNJlC3Q6pTD5IKiX3JfiawE5jARQpCX7f2942uHXaU932xUbzQ3D3RgsWuasKrnAkwqWJWpjThH"); - a("ogx8lnoXN88braS3qhro2ICFCEb2BtQZsBddhQTz/h5b2DdL281wD8Z+Wt1cpzY/C4vDtD5d0WR+UpqbdQASk2bC592717yTnV"); - a("SCJavY9pthHNxB072nNaLzYt2gwk04/Y7bWYHj9PnHBi7m+UoTVI9pqW469RMS3ZEG/IN+UMjTN4zNUnbkfG8hFKyk2IVUsw/x"); - a("1JnYmgYirbQOT7AO1lGgR/9Qn80PuIJUDK+bTFdAGRE/0DB2p1pmefQbaBG3zbG9WknO2+psa23tVtK2eOeSynybejcZ+F2rDt"); - a("u5wdvtZGtX9Oq9xHxTqfs7093zb1MvpphDMcm7NeN8E5rNGZ+D2dyVPo7PKQ88gJCPRJWAIwYgrAusyPUXqXKMZiBfoVEk4sVU"); - a("hMCraOA2pM/RXF9NlL+pnv9j/rZ77bEHRV5+K4dJ5li9W3i1/FqNkrQneymIymm7hfIi9kpT6LenEtkJWhP3sa9JV8Vte9IKfT"); - a("L/QYOlhw7Z0Qz+cxhoLQc/RVmPEaYQnrMXgLDIPYcXYw9WhanLSZE2v/u810GCjGbaZ/0I+6VErnNP5ARXb9BQ+QMlH+QjMqsJ"); - a("vP/o1tqMQyKwRSVhmFeztrmp9f8yzZETWE8jz9hwa93449pPdbJ4LVS83PY7H2jARWVYOu07ULSVKn611A6uIJfOy+XpI6d71O"); - a("6pz1ktQoYF0sSR19MJzUIUDqSJDyAytF0lr1hE5rxRORtL6p12n9DEmS1kxA6if5glZjvU5r2+91Ws0IhtN6RNJ6AkmS1sOA1D"); - a("rQijhnT2dzDrvxgQUKcD/I7ZflHPyjXk4AQWY7jN2fzoojIcej+KF/GCva4RbcS7Dn1ZUF488mThlO7Ze16a/VpjmQ6awbmgwo"); - a("YANGYIte2pzH9dJmIQhUEJ1CRC01r3A5n2MCO3BlHEKHoKi3Es+46AFsLlBETJWdd5wf6yizCqjCqb2AIe5k1q7VHURSekGBMN"); - a("U1bwKTB+qnqRpqMHU7coXh9tNw84DLr2xNzwIXWRaAy9Xfx3HR6yYjip9Etwk0tQ9+8fZkOlYv9TRmYbSpE32JNi2mCw7THgDa"); - a("ZdIUvkwK2RkH5feQhtsjYUkvAxGvigg25jctldv2Fy2qJaHJIOZG3CPhrWHKfUhQxwAJQ1WNMP3De/PB2lVRBhnbOIM8/Wuq7L"); - a("RpwIx5PvalPHg/aG+X33Us+e07oscHK+hxCqEz0EGT0EHiJq76ri4iXDlfhbYO6K3rUomb+rLZgEMkCHEiwuUb6hhIXT1uNP8U"); - a("fElDrJge3ayz0/eSeYmP+YBgBRUxmhfP4L6CFPHYAAwfPbboMqfp5wVt91si3G0hRE3LUC1spZDiFMRhrC8Pyt1zjPkdi8yyO+"); - a("Sczf5g5YQdiQ/funOoYlM5A3uuO6p5hzuqrudXLxRpugBIQuHJtBf9gvZkUrYZpyPtBse2p8IedDqghKj6QX93S9F+g67uZVat"); - a("Y6H8XvRB+1KOY3d1u1EFlRX0BlAVvMtV8LFIp/i6D0A2mPrrAfThrAbA0iv09od5hIKan8wNqdMU+b1F+42ob3H/OINyzX7n3C"); - a("YnvPv2Wrn8A4Mno/o4rfQrbFxuftHuyrPUYVhHEOyoTGq/DaWo/cjmSXQbEYrtbwSMdB6qhTuMYOrZA4TP+u+W6EpNu4gjLdGd"); - a("Fq0PiqedK3HheQ3N/5v0mS33N+HKxBcBAp/PncTKxJ+hvcA2Sew+SJezcgIgteVSejkBtM+f19G+fCyc6D8AQXURBBVB8AWJ2Y"); - a("A0SXATILXyUka6VyKtiyB3DyCaJydyHXMFyZsktisCew4X3gHMvgLzUok5IQJzvKB7t6C7V9QiUWL3jcA2E/bcFmDOvIwxv3hO"); - a("x9z/aDjm54BA9wpBt1bQfU5iv4h02QUbAakPjGektRLpvgiSiiC5384kxwmSN0rsuREkZxFJO0g2fEmM0hn9DrurfE8dvohl8D"); - a("RqO9WRAOTeJSb+odvC8E094mP/GUwdz3NffAhTyh+zkNCt/LOH9K8GdJ/+YQ/pr/aQvryH9HlnSr82tF9/34n191l9sl/3N32y"); - a("vw9BZ93GreL6xamQ7q89je3WzbQ1mBD9g/NJbdM+m8jH7l+cRyT5cZL8RUTeJKhDF3sKqP8E1OEU02lTytJ805OVMptvulWxW3"); - a("3xLZMSiKp+yzdQ/KSJnyHixyZ+0uknetCh92ODt4FbRZIjlwSK1W17YYmVDhjevXuLja3QgC1RijPYhWc77DYmv+XyC5FQv2IY"); - a("AVWmmfGGw1rqm2LleKseb0W8GfHmAI4nTtgYS4QYsjhva0VjbPvrtPtZGKR5v4qIhPeub2JaIAmSE4S8wrdtVZqOkgYUK1C4/C"); - a("qbYVmi9+l1QDICJm1O6Iq0wdbVA9sRpx4ItzkRXj401/hV5l6jO8V7l5/yO70jTgcmKAzkm/amxBkqrAIH1npNhr5xhsoU7Mao"); - a("3hfTw9l+LBuaZIayoUZBltTlPrUVfcVtIJv8E9MwzFBUK7NxH9r0eBsNP+LTAhY+sHBnrHqKWmLvuj8Cz0zLoDENeoaL8fRRHi"); - a("dEV/sSPBbQFuG9sDgY+DLiPQLuwp97QrM8MsyvtepvYjRwd4l2HQkkIX9lWqDN5c8ha1QxpigSFkPLkzin1NdIznW8xzLKF5TU"); - a("DQRPNBd7v0zwmK+qGwILrUl+LaI08Z1S3w3I1b9EYxf07znsWhe0SEHbRM0tbpnIjMxK9lPSeLuVCKDEN81GOuVggO3NsC7X3f"); - a("04lGfE+IqL6tc7WfaiRaNPSPlgJsJtCaRxOtWaAHOTxg66kWUOQhnMdv0l29nAdjbQIL7T+dGms6wF9MygHxozyQ4R80H2p+g3"); - a("qkOC51wttJcFtMpECsd5zMxfm4z+WvkgO1q+8Bzv9iZRBrNnBNiUDhyZ21C6oGHVxrSdt2Y/SDuKVJ/Y+nzMF6VQECOr//D4dj"); - a("k53RBzhdKbexJy8fNPwwSEGeI23G/7Lg+UFcOTrDlQ7GIcmkHg4ykvsCSnNO9g+ZhS34WEmch3GL5eAQ4U0yNl7zP8wdDDnPlk"); - a("XD4F/HGSKJOZA7/ObVEKkrH1UXGmAifgAVEuGxdy4HRnhTmS4pY3xJvnbxWv+KRT+sQZys/m4wMsDmjKakfRQai0n9wMrT4iHk"); - a("n9gnf49RsB4d0PQvUcSvHWEyGolr7PeClj/oSF/E/9OJyNPOojZg6nU/i8RBy8Cp5CkHVROSEJUFj56p2icDZ0t4h9l8zKgFoT"); - a("zYeQV0bOh9BzQsi0ACSAkiZQouZDxfsEUwGm92UKGtxJWmSJb4EVLlKsBg4/TVF+1Ohmqmo6msDtv8IoX97nOk3sdwza1ro5rk"); - a("43nIwqpCCozjkiq07aniiG4hmx/TbdaUi+aYs5zrAEHJryDAJqpp7NXYJV8WHEcRZ/oCCUYT1lGI4MdZThaKee4RxkuCOUIZAi"); - a("bgp3i3RU3zNGxGzTc3gGryzY8msMgLs3bOA+hsY1vEN1f+EQMNDVof7oqd+ov3gAvbxSs8jfiLHRluz8PpXgbIIxBtwKUDKw/i"); - a("EtQijFZmDyncWNX5sYoSSzA4ZJKzUdmnTUx1Gfi+DUugkZ4H7ha0XqZUGFz/u2kdTj6cFp4tsoqZSmqhlE6RBMa5b3u6ouObvE"); - a("58Tn5UB9WwOwP5D8A0WUku0viqU5YMIPXi8vltUv008tczNbmKx+GcOHfwm86omxNOKH9Yo4j4HDgeupPUH8K65bnou6iu7wHs"); - a("ilWRPVxM0RPc/QFqjrzDQRVTfRfIhWcUfwIxJnGl9ImRlw2FC3OBCTt4g93wdgrGmeajxoAl98/6S+2f5Ikw210A6rYDugEiX9"); - a("CFn2GMnKdfCqV+r7qjjzTXxGeKdwdbG31GD0PssTEtp3BU1K/cUDl/6Co2qEMdr25awjJ2Q4hHXrCb58QLlsBfum0rpb01vh9s"); - a("JmSTOQxWtzMZDRAQlHnHWikxIsaXGsGxUaYTT47nCmShNMlebMn2KuBA9SBOtVwuGRjWSbPd6XhOZGLNrVJ+jbrUxbWfDcOpqG"); - a("Vp+DT0Cw3HNszk0xNfxB77ff/E702zbqt3EbANECsgF7TiwETuUuGkL2IxUYH3rnlH+ddclw6lmqqbU4f0a6taI/eoQS3IP8DX"); - a("2EDIkmMTgg4xfBq99a0kqLwjk4mwh7+6OOh3pR85+JN/BQJNS0CS1QAgxffimaFl8RLRff/oiI2jOB88h8y0yacrwl6Vbc263n"); - a("vjZOTGMrIE50s9NcSSsvETFLBhSdK+3f0wNl02tG/lBOQ0JnWDIYd4XnO0fS5hldRj114ynmkgAu8U+3ViQh/VJe2jkV98ucGr"); - a("4MR+1X6lI+IwnttUnEDTMzWGh9P61BxAEiZhWDOJcT4m1AlLQizhtA8RNKElA04Tdo1QtaaQSCFoFAnE+Iw5O6nhai9ovx9OHo"); - a("u4wMkvtXf8PNz2uFwRfvbcSeR4FkYrcYLZPE1OqbbhbmV7Drc/qGNDozG3YjnrdQK87nn+VJgieHwiE62zGbcRhMlqTZ/v4YHd"); - a("d1+xnbvp9Shd3PN9iu32h29yVKB3iBPRn4KZ8NvDdZT/GrQpOYjhzadISKTdP3mACm2GiuNKtrO/kUrW3SkmGzJtnTWx2F2iE9"); - a("82VqR0zrLLHrV1dB5s8xNZC+oBnfVOAa/jZM436rf4ODHw+fuwYCwvxA5VA2pRdqQfqiddNVmn5OcePeYCvpBJcK+Mz1kfwWGC"); - a("bk85uIoTCc4AcvB0Wfx4MSVkKxAfpEZzKZX08027M7A6PQDnDSUBI/bTALSbUfEwXiEinuDcTZXzTaa6X+4pnqw0wpTn71sj4D"); - a("RH3qo+oj+V1Lw1kGZT5IUiurVo8Noh7VFDfBHEs/CuzJ9pIS/erU07EtIcnzDoawCQsdzKHytw0bR81iEkDQHPv8r24WVv9oiA"); - a("dRlTZTlXRruS0uPpd0KbPLfheWIoqy9wt196Wox1Hek1+KgFaD6uM0M1nuTjMCqJtyPh/98hotd5OKBRT+24OkSHOc52TCtiK6"); - a("Igk0278Wcfzt1GEurLsOluu/ROYTSwbAXBUCuyv6EIVXNb0LU/VvdHGG61FdnAE5F82GVMeSusVqcX6l2bLax3lgmqwEH+SxQ6"); - a("xMnVKsHcPA6qCX90UF7nHuEnKQ4yWZB6JXQmdoJcQ+EbWq6Ie5ncj9ik358xsCkb0k8zuncWlE3kQ9L1pQWBtDpTy2fJb44lxp"); - a("fZcUNi6AOCGkkLRCmsFCRXawsaZ4fhqnvTm8nF9beG6gjE2nuJ5wcWuLQ6cPDBmKdNqced9XmEEhEE8zVN77TsuVx1QvU9tGHW"); - a("wRjyNw1aA+dhPmR4Dsj4vfpiqRlvUFv7mqCxofpjpWjQDj1yKoxpswBNWmvyBspC+1giLHmrSx3PyoPv88jAS+V6PhHLoOkOb/"); - a("RKUJeggMJwL/w5NGRHs3REqYZPktJgeXD9QbJOkrIkjnRZFunMukfyVJ03qIO3wd43FgyOKkfAXN3fkQFbeiDCW3IMhN9COgvh"); - a("PPtfjgESnffihCvg0IPjzULw/yVVpF0Chk+gsR0O0RNnfhD1i67HccjpEL3gFvjDAaEPo7QoMQov6cJ4ub8lB4owsBobojuLpV"); - a("Q1GBA6S2MC9eTFWzsBGi36/w6yft8YzQPkupModm/xRtStwIa+sB3HCPOu30naZ3VXs0xmzBaZf/UVH1GyjOck8V91aqgsMQZf"); - a("7hW52/Lib9+g0UPTkNXWBGkN9Bm4KMu9iKfhBHIUCmA4iEb5zqrNnAM1IJM0UJ65rRmiHUmo/B4OSXGnAywfMBg4Zk1Jjybfh8"); - a("VwtO8Sj8zccntmDqkwj41bN3IOlQFg9k0sP6rPNErT7rPFYrbpO5abl2+m2m+4+HdOQHJLK/lpqVpmbfiMIY70WJt1DiLSC8C9"); - a("KQvl6m58v0XEEH7wvQSKZzm8QbUanj2RD0pXWZ2iX/osXNoMV89zICdJf0gOiJT09q/LgLAYr/6Rf8lSTIkho88j0BguLYhaxL"); - a("USvWr1i8IVJfG65V8d+OFpxiRBXo2SZdRb6ENZpuL3qHPuvcZv3+EF5ES5RrclnUQs89g6m3gxHk7VakvN3z6x70qXtIn9dD+q"); - a("we0ot6SM/qIT21h/RT62OmR9gT3mTEIExar41rPgK1zX58FunY1o0E1DBCXB0AK5WxkoKpKYyFca7dLb+WGOU/ub4Hffge0j09"); - a("pM/qIb2oh/SsHtJTe0g/9WD36V/1kP7ugz3py7P/dV7Slel4InQJMsDHbjIv5wdi2IdWht5xF7TD8qHotGxwTif0KUj0W9gMka"); - a("WZ7dPnHVlxoIsdbpkfJY4Vdo4UM+q3jndJgCBmM5MNyLmTzNoevuH6YFCvyvsRBCPq0776jPW568z1kfMtP4EpWUfyS96NDt1I"); - a("4aePyjVWvKdTUrYgwWc2pj6L39j2xdXDZcEgT4FTjxoN1blE25PU0AYM9Y4vhJwhBymo20tloYXHM15J/RlINtgJreknenwfkd"); - a("EuprpjRygfbacWAQV9iCn+wbKY1nil/tYbR/RqDFHPJtJK6kbE+eKwKF3L9qdPS38RXfW/avT8bitAD9dB/Xwa8vD6DrjFQMmS"); - a("QJS+ibrvatL/A3KuyNwIGCNNDRymvnGa2zZUJP1RJDWQ/EltpxHAfvI5RJJaYkK+HES9fvs79fqNof1YJ9O5EVlYtkSPtaqnaf"); - a("IdToOUJXtaLP0awFuFdyftnTEYkRYDBKwUyKb17359tZm6SF9tnAiSaaYkEpFlqznMORic2jZNKZriM9Q/z9SKtaP+PfuDkU6d"); - a("3i1U5mHR8eSqo9BbLaZXOozc5Q1p7E+CSvHlsp+bReLbudbaUnRSjGLRSW5EoQ8dh2v5VGSDsWmq3WXMf804gCexPdl9zFNK0U"); - a("mHr5dvdw/uTri/eHQnobWk344e72J/BkvoQJRyxvdnw95SE3pIP3x1t+niEesXV/PxordaWRoM0htamSOa3iVXdUMPp5x42GQB"); - a("2mOy2Mj867qvj1rTXbo6uTQqtau/QU13qKVot8GqqwftheYQlIlaiv4prDPXle6GPuYPRoOjvhciwNOPlqDlvdRrWqTuzhnkoW"); - a("zrufo0Twkp6v6rmAtw8g2kOnwd2TsbDAlgqn+IaJwSxd1QMPXpe+MN9Na8DyD4d4v2MRPln+O3PdpTjDKniPuUXHXJVcKWPOuj"); - a("8X0dvVHNRskG92BEMu2f/05oPwHjfNbqE4/37uxiA7Gb94JVq/6r+n1cyvU7B1XBWYwpzfitXps8rb4r76H69hGNqEFkT/WT/P"); - a("FibP6Q7697SF//P6a7Snt47x/mM7SwlvzNNbARuap/8D1ThNVw8pEKH04BC6LIwuXIzCpytL3Pbg46YLEByvUkg3Ec2W03d1oe"); - a("bKpuI/DIHmKvFSUsFaJLPZ816mVXV32SJHX2FHFaPPsf4ZNQ7PexWB2yS2QrY6XbZHr0+q49nk+CCa9fTeWn/MOz6FzqHpC1in"); - a("7SskgS6R4UOB98+VocG7Hy53QGbCwwhx2L1/ipxntOTJqwEJUoYODGfM+M7gOf5ezEPHrrVFmnsPEq7n48Z07tPn1U9+kvsfOV"); - a("+6ZIpKj8lV2SosYH7xmUeIJZr1kE2b4mu7EyrUcMoGePMeQX0D4BrRHQDwKqEZDpOENVAvq1SFspoEEi7RYBXSCgWwVUICCXgK"); - a("4W0BwB3SSgGwQ0/QRDMwT0lYCuEtC1JxlyCuhmAU0U0J0CmiCgOgGNF9DjAsoW0HM/MjRaQLs6GUoX0GaRdq6Azj7CUJqA7hBU"); - a("+gvohICSBTT0FEO9BHShgAwCcgjo+BqGfi+gwwLaLKCDAmoRkCqgTwTUJqCAgD4T0CkBfcRQyuuQTqh9DoFXir7Xtr+3+vSd0j"); - a("CXvlM6F0EIHGajlci2HQ8f1IrJfLFAuJCvpv6d4r7gOFMuaIQ+Z2wnSXmowL2GDwwNvcSZkRTNJD+GbOe+fgfqs2ay5M0u/vke"); - a("6eG9+NuR78UPAj/cOO+NVEDmZOmB9jHdA602uWv12UnoqRcSep+I+nC68PmhdhTJlCh9caSYt2K2lMmx37+vi9ke6CM/Ifw7qv"); - a("yzuYN/3tMbpxYVspd6IiKUxw//msS62O1Suu70USkSjvd4Kqruz88DWgstr8PnegNtU9RSVBRyZniEFO/rQaUEmZgm1JdJs0S9"); - a("HpWE9jKFdbtnD16rLY9jeHkU9VS4njHs/aLnBwaM0C8+1Z2/mO1ifaKFofM6cdQIiXgcvpPwGW1ZW8nWroP4J94VD4Brd5eSMN"); - a("EFN5sVM0ZS1Sy/N2V8YzRUTLbXdHrGCSN7nix2SLGjTWjgt35IDbpS81kgnnwmTJV+EzS6LQkTf2agR8oPYJ4/0521Mz+l/Wsj"); - a("VKwQ6KBAIgJHEJAmns6g39oU5M2veHeqzpjEtrGS1YUT6bmV+gGOfGd+n9UKAoW+bXr/lJD6PbaBbJ9vIlPqpw4TlNaAUvs1QM"); - a("p3p2dY7pmKEO2+2XnJ5w5eCy/L/lSdiwoUbMQesjw96zn8VA7KunA0oLNgSqoyJav3+wj3QXiJyb/J6CI5UIIPBEnbX4japP3F"); - a("1sh6qQtEjQaq9zqoRt5jv3Sb1R+m8R5Q5g9bH5E9XWRHwNEQJ7bKDmoPCBfwFvgs1SEqn6LmMln1t6AYbscw0j/jU9qT3Vz0W2"); - a("Ht+74OKAUZoU8wHUg4MhZsxIOhZcOy6Mc9Ee1clupV41aw/WUnvQYa6/KL9/Om4hp9ivy8XJ8iPy1nCa7L0H7MSFt9BU2y1x4n"); - a("jstVzwLjk37ufiOpJ2NvAPH779ogfB5pheAdulIz1qTeD7h2e3qHOxnm8G2QSx8H45qFSf3AJchwO2fIRoZsTuBdyjlIuI4T7E"); - a("iwGzx9ChVTC8rhvYl3b/yyAuojtgdGf0YEssjGznNo5ktsReBcF8HPa7A90JfhTRq8lfrJSrJsUZypXtyKoFGu6jzSx1gIWJlq"); - a("rj5GJC1rTwKsbqewm/QlLGsDiECgajD+uEe2f8bZUzZ/ST2R1P4uT9USflWDnxSwqBm1JfT+GaxhTxNTHE6gYs5z0kCHz320sy"); - a("NOIfazc2VVt50vt6q/NhjpjlXztTIIulqDUZSbx3klRkkr0a8hJALhGLrXM0DdeTlzWf7VjER8UpKPMXaniAJ2QcYfmieuE7NE"); - a("l/1u8ASzwVNtzAbd67MXsmWp6dmU70+0Z5iLI86kDKemHh3KLOmz/Z1CZLOFsm0/IbLlT7K5R6Bcf7W0n7NY2s9ZzIw7DySjaE"); - a("feb9NHQuO6bEwW/QiesuIjcQ+g/TF9TbBl+JrRit8c/Brxm0nfyyBZ7DNS+PI0guJ7WS2KnL4UMxLmsKLst9TJaDBwXuclZ1IZ"); - a("KsZjXH0nM64nhfZfIs0eKAbQqQEo7emVeml2WVoBgvxg1DOYembycT4Q9kXKyyKrE2Mnd/IxxoMu8UDaoO65kgfxy708iBorsK"); - a("6IkfXrluFDAcFsWf9cxfQjsEPf4UC21xcY53e1eJcC2diH+qlOoTBEPQ9b4wziYXg2OBzfo46X0sVHm/Q/DdbVHZ6pqCG5FuOl"); - a("Wix5mx+kDr1zqbMOJgIa7GITBrqVoKu9f7MhyFzbzfn7dPm/ba8ndNB+Z5n0J4tPR+wa/hhlsSf2e4O9VfpQen6pD2U5gjyUun"); - a("0N5kyefW5ERBZ9v1W9wZien7j8YBmCPb1JGDLdzt91vmn8F0bMTwgUUMCCQCEFejFSmRxTfA78m0G/fDak+V9W6/Nb5fyPIPh5"); - a("Pu4WY38/vo/0ZWa4WGYm0TJzFi0z/YT9hGDEOrNvuV5OpSynAkHx3bDvCjxJjq6nS/Eui8cPu3fWfeo9kB8MIopsNbiUcaYbsE"); - a("V3+TYRIjc6FwUulgWaZIFxCIq31r1Fx8jvJGq8smX+Nxfq+ZsQFJ/eWcK+hVjSXsKwQF51Wm5zuo7/Mjn+kl75Qn3854nx18bY"); - a("PT00P6Qj8+9l5lyZedxC7r2bDQGSOq+QOAMlTj8EeSQDsBsi2EZWMbb/figX+iBuXUC6zjaoZQbyhcpaNsFwUTClLnkUfNSpv8"); - a("EqBPWOUuM/S4wLbYK2wLQyZibe3n1YnHdq2dau+Ul94kZaxYx32rrKVqLl98xwTGSpRrolcAX1v6TL5tznfuyoJ+5RH4BIIvO0"); - a("c24LXhXErJnv47wjqFd0/o+0/NOLabHpdBorbFLcH27fbKnTwHL9YJmca5sjxrvjV/pwrL5ZH45VN+vjfW/0934DIsRqdCG+Jc"); - a("9VLj+8dGOypHIfuCNOXKcXs+bVnSj+J9wuZ2CK0P+RxZ0lixuAoOAQ4qJZEufQAh3nuwWxvvXY73Wx/kkaz0gaTy/Qm7WODbuG"); - a("2vRzvU2XUptmuvyWF892zoWX+Kbl/eASwLcns4nUdfqjWdze3ny4QQz50dHa9uQdepmXyTIvRVC2rVrinCVxBsi2yXE803pw8N"); - a("bu/BVi3JdjaD0q7kc6urgqJP2MpfK92nz5Xm2+3jOjjaTfo1wZ6pvOUN9YalqElVvL6jYEXBGOD33NcKjf13cocw9dkBxgv78w"); - a("oHsP7T1Jm/apVTwVRvpCrBgfPj9+NYPmx/wtND+6L8ep+W6EdPcO891iTQvJCXqDZ+jYXAqK7KmQyt2J3Rd0qTgXqsaIny8AIo"); - a("YSyZuQDF7WxuvHJXpPrJFil7td4eO1Q+K4JM5clxwvWlp/Knze4ytF3yvoe2WeXGblfgFYYSxaKUknSdJmV2jmHu3X3v0fczTw"); - a("pkLz7/wMC3wPcSK+tODJsBfsgm9il9dLlvfIPL28DfN6Ku+9yPLujVme/P4Ka6mwhyr1wsbKwi6Yp3PZBtpaVmlrCAIbQ2vIbJ"); - a("nz8C/0nN8jKNaHnwMnX+JslzjvIihG7nKXH977qizz66YH6SP96XEe99DDq/wy67LeiA/OtPs5Tsyt9toJcJAx2Wbs5j6eOxMz"); - a("GvhqrAnSt9tZIpmPHQEqUPOD2DpXnxZfzgJq40GeVszeg3QOvN5P8k6BZmfTn8FU6h+Xj7cPgSJKfyyUHsfpfWU68XDwoLhXAa"); - a("JbIDppv9rgArLaf2ssv96+1pFB5BYStMa2PonbpbNl+pcjJSY9wXK+gW5PzlbB5NHp/284JN/8xW4jyzeTuso3Wd8Eyd3qE50p"); - a("XTEWmHAMt6wKAsjiYM0HPPWlWWqaObDIUrNGmwxrHgoFFmuBVaF58q67Qkm/DAXcIuCeT38u46ibQ2krOTDfne9VCyw1t1Dhvz"); - a("KS97klIXo0yDy/+etb8bfZ5a/PxjdKv29p8Nva78Va/EXab472+7GWnqHBuzX4E+13j/Zr1NKDvP5LZmF+8u4zYmcaxzQhXNoX"); - a("R9BFISiBoOwQZCbo4hBk1TG9e206jZY4Lu6M7wuhevYRyZB8b5XmBKtzJ5VN3kvPA+1QOEgLDMA94tEdJGJwBVM7EICgeVhnib"); - a("FT6UVuGlpg06vU8Yr008D+OeAFLKF47hsldWOaHNXLDZTqHuiAAvKUuoHZtIPp/bi4X0VcwlV1E7Jx/0SOO0jPqiT2O8Mu+te6"); - a("WZucTtzorLopnlOlCt0MCNrqE4wGticwNhhEtbduK4QHVge9v3di1bwfidiGCN9kpkJQwEMDOl2mqy3jMDfHjWXhf/52owEm+t"); - a("v7AJ3Wtz7S7iIcGlEvwG1ueYeDLVp+x2u3PTtY6jsM9XX4mXWs6TXBWJ4zxlaZCIt5/fjMZa8JurPgkJJkVY6VVcbh7kRE2S3r"); - a("WgLJRDfQy+VHsp/CRNfzEr1bA79T5X2HqPIfAuBivoYeTe0cthBTooxpap+h+QER5eZp5Q4KXKiVW4AER22RgeyvBUZ1KX8gl4"); - a("85T6KF1eMvjm1F+D4EiIXmBK2C447N5uLZL1RjWzyE40cQo07cyXKFAKdikBI6UDVpmuYMD8oi7JuyQQ6WgOYvti37GYeU62zz"); - a("62aavW1HGcSDbf51zkVAlH4Hlf4GxFd6AoYZG35OVlJuQDJF1CU3kq7/p9gniXOwQ9QUCR3OuezyWa3aEe5ZOEo+QPcLOIRuM3"); - a("3zrpGsoN2H/D6TsguaSEWHCRf2qBBFb6jatJkplf4s5gnpEZpuBvN+UN1yAfrR9P1tfIk1ZTGqP+4yFjGP9gdTnwcNEAziX/sB"); - a("1t+CjxatBPXbJ1HB9l1EvmDvFHwEML4+ki+wd/uKDre/ZGD638DFoNBlGvoBa7Fe8z4KFnVAj6g3xmMtnIg4lz9kexFIdkJy9w"); - a("VCCyPkAPaT/tcO1m1aNVroNl2vtoJoALIJb0EWmmBwTxNvT6oXoSG35nFDbKC3/b0QvSVMrxGwX/3pZu5/ddMefHN98afFtP+X"); - a("2tdsumyn0DBSig5ryiRS/tD+pNh1TycrUyPd6DuYWC0grZGqgfgoBiCmniBnJj+gw066AphTs5F2pIIvD/cuokxNkCypH+bQQX"); - a("Tc50hA+scifSvStyVYDU5o7yOGiHkuXFmQ9ncjy93qUh8HQlHOWxByvXrKSDPNa2Npj0D2wQmf65eJUkmUabl3WjBCR66rPW7K"); - a("UzUKdK/U6c4TdF2gC6r5hCHGB1CWgCLXWZACgY9YUFdmR/AdEXQi6A9ysAx5vy8XeaW8Fen1J3CndeKfLKp8IShEfTRdqwelUE"); - a("PXj+ZO6NfQCTz12gyeKjciDkn1nNS/4UdKmiCSnkScH2l/1dIOU5pNpD1EaXgP+Tbx5GrwMtu/WSjfB8yMeB8ASJ2M7GT/RiIl"); - a("TA9HOv0TIA0TSLdIpNenhiM1AEKrm46j1aZ/Mu7lEnfE1eG4QwEBdz3hfhJg3P4S9+Mrw3F3AALuLYT7N+C2/yiatO8WPcO2q8"); - a("IzbAVUgvuQd4yGl2hHq35zmEvYKDOYImoenMIZypBBiJ1eFBlWyAyFEVW6HBAyXKhnWC0yXCUzNE8Lz/AqIGQ4+HYowwyRYajM"); - a("MPya8AxDACHDu3qGEcggOTOW/s5WIW9yFfpIgYcuPnIJI+LWlyNCq3qRb59ly/vCgI47E5KnuSpOGjB5TPP4AwvZzWDV+K6ECn"); - a("23pmeErMaGE7kQRBDv8i1VhUKkXJKi9xv6NaULxxSusMvX4SoYbSgvcmWNhmzDlRX3Rnke/hoqL3BlxcP3AYXd5/HfQa4sz+Dy"); - a("c1xZiTBY4soad165hQ7qSxL9sCkdSGLf0MIvQ+xGv4f6FsJ/420Z1OoOnFXw/lztWEFN7qw6v9Dnpgb25gZGZChABiS4Wuzqxg"); - a("RxLykX3qj722VCeentlfiN8uU/LMJjv5IU0j/4/DqyX4he1OVGkl65Ru9X/wG9e4jeQ+H0uun/6tPtpzwm6sBeove677uLzg/v"); - a("u3VLRN+dd+a+MyKDP7rPZPsuqtTb1Uuxn3TuUKllI0TLEPUTRB0Ia9vz18ZjPsiQbYvq/zbPf0bv50Tvl7Hpwb5Af7qfHER/bP"); - a("jjGUFr7NWjWMsiQPKh6Vq4D8KXpnPYsqVZkoqWv2L+guBcySX99vE5n3qb2X4hokiAekkTaGr6+33J5Io6kFrj3cYmmz0H8r5Y"); - a("8Z7LT/o6J4S+zgxeYM87zdB2Af1WQG8L6EsBvSGgN0W+8dcwNF/TYxJQ3imGRgvoTgGlC+hbQWUUIHXaSGqlaY+DRBmmffjZmI"); - a("CAikD7KRfsbyKA9AP4kad8VsUrwzKYGveW0YCgHcGPibhid4Ly37EKdNHvXVnwQTPtdUYrpmXI5T0aVzEAI7YY8idhIvrrbLIy"); - a("3WI6DrEK/XPR+tfM69/L2vr3C7n+RaxEmwCpf/xKrH8SKaEkYv2bCqRqgXSLRLrQEY6UCUj9mUAqkkijneFI6YDUSwWSTSJ5Cs"); - a("ORFgFS+wPJ5cf+2g7gSVvU7N9V3wOvlPUPVX0T+KBGgrAMvCN1CHXO1xFL2+dXxJ4nZ6fjeWP7b7m/fNvXlCRkuOCoYqTF4Kjd"); - a("Wtua3uGobazBfnSMzd1vjNWdMibbPWyM353TTrIirDJbXSN7Q6egl8FhWdfUfi3T1OKTEZ/A8Xxms7y4dfXWY24c7uIwdg7L/U"); - a("2BC2iOXnnU4hnknAsHrYUJmZor2zR4tDLhJXVgMD27Ti3K3umH/8Gimp3uRO9xi2XtdOxC+JW11CmJtR7iVDTnOCtFscUfGMV+"); - a("hd3QNdyjPUqiq3+6s90NWB01GueOwvTJRsx+OZ3FLTjXauc+9CCpCKxNz+BLA+FOTr1reOipg7tEro91wtMdz3wE2DQgm4A0Dc"); - a("goUWqYGKnrK6AnztSFoAizCkhrJUQFuALN6RVRMCL1CkdAGaQwP+uDRqNh+VTMAfmPpm9Hcnki3FlZ7ilF7xTmHVwxEFMF7l7o"); - a("iEYS7fXPsY1wZWA6FJf01viSmxx0Hm0/m3L5VD8rlkGGpC9o0v4/68dCvWHtt5qSjZH1zJWplwhV/XXY0+qqNdld7p/LMN9Id2"); - a("185XzRMIp6Id3PfkMfTd+A3xJ01FMMHxdIWadZRYE64wlOX8v4jnr8Ed9+AwlYVM9QTdK7MSHylprirkPh1AJ9PQPpbM24SiN0"); - a("cUux3fnAJghw8VH6sPX4Vt1zdDHuJ9N0Me5HCGKshLUJfhBipd8MHJKHUCAbKTYK5LawVgo7IpJmYoShpC6NeWqI9rE7m2P4/8"); - a("Ry+kGp703oKJUolTayU0GmeAqVqmyEc5n5qi8nOpaahcI0Dxe5DY3nCwrImM9Hr7Kx4Fmv07R6NqQgnxzZbSnGIB8KphYjkkj6"); - a("2fuch2QZlpoHQQLlWcFNLF3Hbu8+rBoOiKw+Xd5LLcpClRuod9Upz7L6JD/i94H7Ksya3twkW6HvziGaMT906bDZepfeVaZ3qR"); - a("dBZn9SbzGdulHH+bnEmU04vjRqknEN/sRyNdpVPifVJrFd/RhdWOp7T7kywbvX5ZlTfQWJTj2DipW6o9SIJ4UCSGIR7IN5ybY6"); - a("OwI5hqajnOeM6jzQwft+O3/RCGRwv+MKFgcVB/BLfMdKyb7yuTiuFADmcmyWmpw4bvoo2Szlar1ZtQhqX34ZxoXdtKz+s5FzHJ"); - a("6l57i5SM/hQpDQ7UASNVSnniSNzSN7LMVNviZy6ZnLBB4VONBD+NaoGVy+/UvawNUwgogJYskBSquOchVQnApXh5lcaKstvYjQ"); - a("MOsJpMwvxcZ0GmT2oYK6ZILc5RWjISzXD20i1zltsgjv0iF4yH0Hs8c6jlEmDiG56LbVncvmsXV5aq2TO0f8GruWSPIpDUkZ2K"); - a("SVfklk6R6t9Mf2YdoSyHnbVvzF5Q/rqWOBUDdcqWEvArZL4R6jnU0HvlllLUPqQKisBGbgkxr9CkC3PVQd8tUWCgufbbJjZBgv"); - a("Jn942aj5cHuLZFAi+BqCWD9BErlh84SXtSiXpd36r91Y7HtfsyBnB7uzZgV7pi2huyS6ujdDkufwfVikuJwO8TVYVo8DWvu5LE"); - a("sDb+dCEpkQ8hFdNyGuMH+RuTwdf5MrzlWwYhvdJqzqlf3VjfcJL2obasD15PUcOAmWVTtEyGzx0uRHfj1rXkPAoX1zOLvwElvL"); - a("H96YI/zhJWsOdNtzjJQlrjKP1HDtJWDwW47pDF6o9C7G5hixDhR7uxqyQeJJJbF5YDbLl8keX/xkM1JAB1uSRkFJ+5jVR/hLF4"); - a("5qgN/1oy6Fr056/6dZG3x6MMvXqADqm8J8m2UV2e9hQV+JuLXTutW3i+8/eB8fux8Tyq+knqmA+1x829SNnvH5sxPK++XPNlck"); - a("i/GwebJR3nwHamt0+CY7Q931hIGmlWRqW3C7P6w+5Q8AI5fnxLIIRpHnmX/RdiXwURVnfDcX4dxFCARFCQoaBDF4JgZ1Q7K6kQ"); - a("2NAooWlTY1YuuBklWsIQmGaJY1uPWqtrXiVW3VitaD4pUETKJVDIgaATUq6ksXNaJCuLL9f9/Me/P2vc2GXvx+ZOfN+c3MN9/M"); - a("fPMdwOl3R/FoIfQGhco809nlq2dB7JXFV9vl7vqggd7g1PdXlu/d8lvV3yjYoyujugWCky406FfX2Qb9+hJBslRw/eF6viEqX5"); - a("PK9yqCwlLBjnlG+m9U+kpRD9nToPP1rVCHrDl91YvMG0MPv8pg/dhFxZQrifVbiyWpTZ2JEGzib/cRs3kYPrCGr8dV0AFZaxde"); - a("YrRB8EZE7/+3I/zHG/EnjxQiinbgz2tf4s9pzBlPna0A084yAPsCQeF8YgRgGN+IBrdcIvRRqvkmtQOQm0ccNb3hY9jWmfULMx"); - a("Pr+5zSZ7rir+MRlPFZG5OprHbL8qMS119ArlLQh+hoWzbpP9GaYNV36Cf9/X7SW/pJ/1PidODFHJBX7ZrPVDa7/arQ4e8QGoXw"); - a("5rEoWrfL5i892KN7yYdXahhpW58VGR4uxvZCusfLoTFFUSqT24+l2JnXW73erE8p4L0lmmi+lGNuJSnPjl3v7kas9uHNxFGuEz"); - a("of3h4IzHSn8FmypBscw8XvOHGWlHbPutDpLRc6HWwnG/yPr8mvilf4kfonfQLSuenaBT8YGHEQ7V+YsP0Rpva/0tD+Rf23/8H3"); - a("RvvKH6fS9o3nvzhhOgBnIULccNnddybCMrOejqufNcmsH++MhnscKiWu/JxqIpnrofd9Fl9Mskazg2q2BKQibebe4srLBnqk1O"); - a("6yXiTWVA5EgBzsVE3GUD++WQ31L3Ig4eG6gIeaBIlYwlfTloJWhblxbrmbZxIVh1BxzHwvEvpEj/PPK6uFWtEa/PiDjzbyz1Nt"); - a("/PN8O/+80iFO0jg6lHuD66FAtIs1KEdDybkncliYxZ9qfy18IM9QPpC9iF3aA+lwei/6DuDme3sCm0TciewAcLUYnn2+BtQQSv"); - a("KLCJzYaXNFV/LaA4Nkc8AjUuA9wut6cX1x2Xs4/qIGMb509r2bpIoiF5pw2AUc1giH765mHEaYnUUAhzWJwxoG9p1/qIE96kvg"); - a("8D3n6wP7tBzYCVCIC9V1sjCVGLWQGLWQGLWQGLWQGLWQGLUQj5oY+INf711VidZbmQnWG74ArP+c2+96u7xbrXeTfjSQeinrSE"); - a("Mer8dw4GBDvSlo9bhNqtUucOS1u+ZYUS+pm8+uwR5oBNPuobDQzZICWAtoMYQWQ2gxhBYtwt6J5QVhT0HBiGuapNOQkSou24xX"); - a("SDTsndSpN5lOh+bg617nDghGVKSCV1L9HkLcF6dpBF8hitU229qXU76lvljF5mA7QQFtk38MlXRqK29MoI9e0k1rhSwBFJCynQ"); - a("HDQCwLmBzXloWpO95OXktc3Zl/5xiNBfnu4Oc4fCgQzPLkbRgZ40mAeBPSG/g6JlGEQJq4DO8sous52zPEd3z77rBjrl23gDiv"); - a("UdgRbFTyuab0mxOkA5qyTWxm0mEhrH3Ru9BMtojyNiqFEtxxmKYtbWqaNkwDyo0/zzpNt38tZA8UqnUoghcfvxT8Oy+1i1gp+F"); - a("ZhvjoxX5ofS7C8CJMHmgXx2xGYgk5MENKaouct5PlCSqdDiE+Fw1iuHXSOoIX9gpM1LGndenlGcXC4CbkoD/WMC1acyW5iKnIp"); - a("A9XOg1bPKuciZQTa6zCnli7A+wP6rk2twwxSrESKWHnc1dolBX3hY42tfwCK7V/228+7nKqfsnlY/XMT1mpXocFyYHj5REf0+s"); - a("NcL87tLsI5lD3bfAY8EBXOSI9kUBJH/9QUzVXBMUPUVdfBxt7gBycauIKJpNPQX/U2ou01gwmjP17oBOXnriYjiPTVSG9Hettg"); - a("QTLX0DvveoVJUz7Fgn+xVMekByUmeSPYOS7vu6GAauh3l/fZ0ABTQ09QQ7NsDW37p1R5mY3F97/Ag5mAXDu61oIHB+1fnxaedu"); - a("rFABPO+4bR7jpQOdSPo//EhKYUV3CPe53uL0Gl83dmfPus2MGhwkZvcrPRaCZM7Fadg7e4Si+E5yiFIyeBcGxA0lKXKQqi2WF8"); - a("pvMnfPyWtWiXuaJRkplKLswE5zAT7xnd8aBFD72s81KwTHPC45r8HRQZS+Zx6R2PDeE6yVVDZmQA0RLnuZmqD2Z+uIWm8hgSM5"); - a("/dXABWENRPMKcG81Nxxs3/+tl/6blvKSxpp7GCkYelc4LthEJNe4AfnybD74WvqScJ/ASMThqp8lXBB2FrVTJcF1BEatTFBu67"); - a("idSnYdQgUpwWSPOHytIjZ/saQGVDo7Qb7jOMfJ9ILVYRvT22WSHvER8BeZ/xW+ntOI3pLWTr+9jL+8c3tmeIEH5BDI+A/hgh3n"); - a("BCvCEG4tl07+znfd3YuE8y2gEo6ptl7Gjx90eeOS2b90GyCV+YiRF0Vw1iZGM8SuCvVvm4IpwaAKmkTMfSAfR+Xgh9g7Kv/Mll"); - a("mf78MnfVaPzNqhoK5ju1thYPqkgPlpH6Zjq36WyGWydiLv1xSDSKlMyC4AG8x9i1eGLpuaatzO/LPkCNOM+vEef5RnGebxPn+X"); - a("Zxnu8Q53nd+ZwuB1C04qocOg+zKJR0IgHQvh9A2YA+eECs24Q07/KvWYhSiQcY4vh+cbKWUvn8noG7jzx7M+DvFSEqByZQ+Our"); - a("c8VRRj/eDlbH2wmNCgu7O4GFg2fqWLhcYuF94FpHCk1QLOVK0lQln7xmosNUScs5eiWvy0rmoBJeXehqtuhqNnf13X+rq68cZu"); - a("vqPwvNXd1f2mdX80xQphKUWedYu/rX7f119YdXVSWNn6CSrcXWrl6BSsJ6X/1p9IjTAlKarZWm6UabSyDCd+ReuTMFWTldoFJI"); - a("oFJIoFJIoFJIoFKIUUms/MTnJ79xfBppP1aU6+eK22LOT/K4NP8qfqnNIn2abujTkAWi1MdOTsZ3SY5xUN6137qZzhBbZr5tM3"); - a("WNS7yf7vsc0/r+Tf/FfpqtnQrPjxzoTUGAKd1JVwlK5yJKN8igdIreqP0zK8R7q/1+oWlVd6r1b6cPHdrVpybSv2KZWxomSqDu"); - a("gWz7cgDciyhGhzGK4oGiHHxPJumB93X3hhBaPX0RclJkE6PcXA3FurXdAaeDDogYMOGp03Ub6dDAXaLy1wlfhuQDMeSF34WUZr"); - a("xFkLJUyrTGSDIu/TW5rsDF1Lo/RE1pobnINbKdK7+oSnINphspKe1grU/GuuNO3wglSJ5J2SFc32jUP8USOIzObl2fYlDyL97u"); - a("uv0Gk52xh3WDXmuFglS7mOnY+YXiPC2a33KF6obBQjnHEfc3mwYlG87o2JkL6jbfefXi81DcNM8J9UfUbrWR9kejZMx5pFO8zx"); - a("fBvA2em7R5qfygZ7tvgcUcgx/t2iwI5vOYeUWgR5uOgMIYtZ+E+9pPfKy4Byxqp+w6NiktPvJXliaGSRqI/xniiLnD90/B+ZmF"); - a("YUJUBw+VJvALvaaLROrOgUl86RWl2rVfohSS2xkfG4hy7IFsr+C6aV/ngkCOh9AUKDDRJu1JrDMZ5oyN2kVnyIn+rrcPuqbWuB"); - a("r/2iXZjsAwDKmdpRj3PpmlbUpWOazpbJ8YlcEgEYF0zNlGVp4fLK5WDz2m980Padf5B1g2VaPEcqQb1CFESO8QtEfWQ0SQw8IP"); - a("20BeRSkYLh6FENYAJwJzcH/CB5KBarVFuuPRTDFHwylB5HTIM5kaKFv/yPMImBi0FbFvFF4B9vFQ+GjtAknSKETsix8U6DTGIU"); - a("je35/SnHQA1yaW86seqzmZ4eYTephH4FlOAsrfh40Oj4MRJzwK58IUI99ia707nJxtcpTNtobm7uDMYxmRmnW07iS7ORfvqG7n"); - a("sTw+Sn6+aBfioo2QvBA8I4Aph4pQCVOCkL3/PVTyIPvPtJs2B/ZPODGsyLXqJMA93CGn+a6oevSJby94lJQ3nJmlHcMEpEl7p5"); - a("w9sHEb1V9YZBnt66MqrXZhNmz/8FoZRBW8ut9sg9a+X8JJOTb6XyC+9qZsCDuQvjYdpocXsC0a/nty5Gx6l8WAB7cY7HXth0KH"); - a("g2whmOKTKX4bxY+yx69HvKK5cd4Lgu1ouDKtKN/jrjwEVLyEGJQZX+ANUVuYpDBXwS9MaZCuFt1Fx+/CNmS/c8bkz1/srkxnJu"); - a("qAKpw1BuPiiiYeoiZSqYn8xSMryAaCFNyi25m2LQTkXDzSqNhcX90uo7qRRnWzn0N1L/DbPdqrOhWVVg0S9vQXISvFHeUrK2Tp"); - a("MNbhSSLwQzPd0NNpI2I0aBDNGa5D9s4c5H1uiXGfm/WLg7zPxa8ft7D8wpGBwVTpbKEvxsDOxuXspHak1ha6nX34B2Lcqhgr4G"); - a("jBKInQlRSS7kUtCG25HxrXQ7KXV/srt9PPo9ZSPKmxuKkzmS5vrKXlb06XCNAwslvb1tsbDRWOPN0BcKuOaNKS6D45auOvRvrK"); - a("Zo80ZjVthVoXgDw+fTOZyaLtr0FdGtzyvF8cbNfP+i9vJvtpp5tZ/yk4Isfy/a/pUETANt5isJemwf9R5ALYRRmJ1PSqAaTy5I"); - a("zk8neNo2oQOtekJcMp8EREgeWuRyUh6pDam0ZSETebglpLTOZk9Bpj+CMIASr22dgy0xqL4Gs1klzb6CzIa8IlGd5XC4KNM/NH"); - a("NgciiKlOW8P0GNnj6jdjDaQSTqv1dAItgOfpNCfRJ50AGClwf+nkPmZxDmYRrK9gN+mxwR5XL+ZHTmtwejfhWSL/xbU3uh3sH8"); - a("0F9tHlDaVRbbN0iBPs27+lM0r2s2t7oxVifbJ9KcsAmfnr++xvxnZ66gY9nSepqIvp53j+eyL0ta001JMcn4ZmJ8enoW78jXM/"); - a("SVf3k3jvG7V7nYEMfXc3rnndrnF8vAC4lfo9D9wk4/hRcWk0quP2om2Y0TJEcA3gC1NepMnzyZnifJKr9nkzn7RH3Os0lSrudU"); - a("e9j9NhL06HfDSSq6J/+ibIylDz6Z/isAcfLsYKYn/iYVj7FH+x2t1adp7Twct+HAKCDJ18qSCMbiKMgw3CaKEJdnuPHfxj5tk0"); - a("eHv4ZJyxqRejdPhCNhpofvMcpr95PvjzRG+ehz2lGAeXvouqHsqzvnnmQC+R+xrI0HO+t4Xeyy6mGpk9K7j+p+6luRLAWrgCB9"); - a("+fJOpPyeV992fjzxL1Z+aTqj+3b0JVm3Kt/VnwruxPxXgD9Pn7hdNZOvIEBvH0XXEq62nau2P3XyUuQ3gPh3F34fT5THJXiwWC"); - a("NYjjxTScM9c5Sa4cx01faJY7uEX7C7sLhUvaLi8z2+DzqRhHS3fd1uot5WGrJydF/8zPZC1krL2VcGlErKhBO+GnWdRAnfcO5f"); - a("Me819ZZBQG0ukDV2TeZPnM96kiXnb6K5pH69ouloaXX2t7CLWjFRnoi0FrDGAUJP/dfvfW25jS6CmJ97vqjQn2Oz9zvdJJW/Ux"); - a("iBTS4B1iGzxF7/5z+nZXPPp210Xi2iXZ1ly+wZep7b9P0b15HejjE3v/t3RvMvkaSrtCp3uJ3q+7tVfNoC27T7EG/sP7KKqcad"); - a("xG4UFdu+oiY0SORJCvKjdilEQPR4l+uGJvnmEz0LMlsBdCP6IpUzsAX3imPVed77kH4+6zbKEqvWbJFJiVafFMPbLFc/yUFk/O"); - a("6aGMBb9xOqD02+KZ4kRx0vj96x7MyH0TUIusRre37SRfqtAVl9F9789ZuE/THQvyl/yyPZg/yuEShX27ay9zNFmaW5wVGcdIKe"); - a("+aLMNAHPiIsOhmQc4E7xuZjHYzqQNf96ADa3IEf2oYTj8+arT1KNxbS0KFHoqk08Lh9GdK5DSGifSfqdiDyMX2FkTcQxTXQHEj"); - a("jLgNFHcj4sJ9ne93FxQRkYbp43X6d7rlO0l9W/HxYyyWvvmd4Ice2b+8BT9t6Pfj47BeuOY5VHPsSsJwR46kXMTX1Mqg3G9dT2"); - a("GS3uZ6vBXsTHcjI7AP482x394qb9/n22/f6v0Uqk2ptb6ipHW1C4oOqPT4+JMp8CdTu3OkwB/+OPoCHX8qRxr4kxnJioc/mZGB"); - a("2tFuJwfVLMW33zV1/EHb7xIQmvl+Whh6ZmYBnGBr7bdOWDg5UbdwUiTsm2DfE/y/Hs5KFdBeTFUcB2YzmTLpYPtlL8vhRG/7sm"); - a("Gl5Pd8zgTye6sl27K2GgM6FT7bM1ngKuPtD2h9XEiHDiKfF2RSu5kusbrXRTL+5owMN48nWN8PrKufPyGL7NvzQYQV7iom5LBp"); - a("Y6k/yaLsFOuRKgh7SE/+R5IbGGDaZkotlwsL/qr9sUjuiw77vviHVnTgq+MT74uXv2mgoxqvdMt42fnRdvwYNg6dAwBaKgLife"); - a("uIWIwx+8NZA3xBPwJtwJd2yG91+MG/i8UbvVfGKgVWsNXqCbj9sI/mpd04XFA/qnvMuAXd9eLar53QWK+cXtzaQvhl2JXxsuFr"); - a("WsUm/PJqhga139npb5iQW5L3Y3U7vwcL5Z+U4kn7CY/xbkt8kZunENKdEr9R120PoFajYY/eLhoVYKp2e4x2xZN7hRunDiIXeG"); - a("vV7v+mNxr2O79UrQhROdBjf1539RACL7iHz8QT2T1qj7NyLMYlXIx1RDvujBVzjozWY+NsQYHOag2dct1+jemdI188b0CnDXMR"); - a("wlyEMBchzAWYlAn9y+g37lg5PvRBRYQRAU8gUIPiOM0Fi/IWP712e0nQzmwpIS2VDlyIpEo7YkLHwCheVao/78ulI/zsRHs8lA"); - a("Rgo6crJB6mv2D5DBjUQUe/qTxkBpRIJ0drewaREulQKJF+UZx/RGC0nw0aFK+Jin/V2q/ApI14Ea2di2dp/MLuZsmkznMa5hwV"); - a("xTuCNhPKTVThsBk1lZOjQwNp1EJ5mKJcHDUoMICi0HZJ8HjPi3D5m8DCkk1/j/Vx3sXZ00/6h35ilOcCoauGx/Q/r2cpyDZ1eg"); - a("q9nefs6nqK0Cv0Ex+cMfOb/Bbgo+FuKz+mMFgpFJ9/RMVVxcEf/Zjzy/EqjV/Mi7mnP5tG5iB9NEpoC6d10yh5pyJtKhG/ySiL"); - a("X0vZiShbHDrbp6wQOFsNR/nBpIIX4IW2266WZ32/HDYw0X7eqf310AT7T4lG+3lRPV/9OplahLnW+nSwquj8eAh90lI3NvSw8S"); - a("rMsXyo+/BbkMxHYJyAhnIO34ukCJosrbZ6/kgnN024p3byhXHyAV6N70RO7LucuQBD+KUotIlXZJf+8uhQp4SE5zkfudngFVaw"); - a("2qn90yy1Gf/8Z+SHHIK2Nia/zP2mcEmj3T9FbQIHx+/lI+0YPsU6hvCRZIivAR8nZrONeT6ycHqm1jlYT8fHCE6X7JBR8CSQgE"); - a("/8392/wvHuXyOhKa2Ng9doebfK5BqkWq64mBWNlcEWz3GO2KuXR1xM8mxXr3DCu9fT69Doip/a7159+WeOPT3FfJGZJT2iDRFW"); - a("fQJ7fSA6eoFSrg81BPcq0bU4dVjX6yV4GEokb9A7qq/1ukr4wwu0W9atkD3gyjemINTnulUx+q7YYXrzUjulc11MVoeMzltXNd"); - a("1WR3CdrYrLG0Ymx+TLEe8Otoz6i2E5STUoPSHIM4D+Br3bg80xRdxCP6QI6fJK0SHTjANvh6ldTE00PA9lIKdQ/YS+d1+jU4pb"); - a("EBCe/DCgdn8qtMxrLaJvlvXTSWb0j0eExML48utkfiyx/EgnzSXxa4rqgetUZlCyPo0jYoVt+E1KRak546VS24xL9li3nm6dvB"); - a("MTFnQ2q2Q1Z/DKhgk6udW7jSaoXMqdbHMyGS7zboNISWy5Uh7wbcR342H+NkYURI0vkd2jrL5q4r/ndvsbZqBjGVc+43Sw/YSf"); - a("ybth4SLLUok7vkv5jRvnZQ0LWA41C7MLrswSWAj8KpnUvjdfwyKc2Kaljv/s7b1RlMPnp8gLMDwExhersdfVCyfrqAwJWP+k0D"); - a("5BR638qOxzaCk/XON8qMn+2+/jszBgCe7b6l0+8KZ4l284S7zLb1BC1RrXtNkR7/4NIClCW+GZUj9jivqaWj9jqvo6vn7G8eor"); - a("p35Gjv4V8niCMzxiTZX6JCfLp31wSDSqshQFZxTJLJkMSz2EZWVEFkecCuMWtrs/6WHL/Tvm1f/NiWpRmd4ja286CfbdMNrPOp"); - a("neegSO1hae5FTcKvN7+kn8nn4Szp4IC9mTHCF74lE3NUXf+T6LkR78Bmb4aC/fYFxSdpNss9SvA4zi83GIW9avq+/ox343+jJ1"); - a("uBQLmjjchq12+t4IfGUaD7zrwP0OeBvQjPtdd4xcEBxTWjc3davO6wn8HGMjuAVzC16JsYf6Ou5VmhQh4hJUoR9LAtHimtdtum"); - a("5BKJL444eL090Q2EX9tvol1A0PmDx5Q8j0ST3JLzcC45mgAuNxGwL0oYDC/Pjyd7N6E8vffePi8WvXvnDZx89+nqVtMai2Rfy2"); - a("q+3xWSI4QDJjl1DbircT+4rcU1QijwCw3FYAcjmWenj3Rx2cl6SsYuoAmWi3Fshycnyntf5sEd9hjc/SV8tLOqHZRIEE48v+xo"); - a("b140+kzcRwaiKMMISzzG7dbh2cDH/IexEp3brdY3XrZj8v8V1XuzgiWEFy5Wxo430H1USGy6h/tOpRqFCtqPj9+XiovT92+X8r"); - a("L21aNJIM/WO1XmiFVE2Ghls8tpk6FzILjNC+ObZoII01m6U9eIRQkZLfN42I3b/eQcLPxKgIQ6J3AUZisswr3LkOMcOmbQ1HBs"); - a("p9eZ0zhgJ0UP861DI3969H5lT9iy0aSHtJ9S+f+tdxkP07Y4jkZ52MgOrowe7Pdj4Wy8Pc+xW0laFORHwhTJqVJ+R6YSZLLstn"); - a("41+CVhG/pyC4Hj7tKqeWlL2lUhm4DlzJxda90zLTFZk2PKlu4MnmsXDxXCfY3a33D0At58eOfyPU3YGpUF53YEt8PDNfK1T9bb"); - a("TC3qEurDPfYyTzSF1KVFn7fK0cdLD86fg4mWHDyWTgpL/scyNe8d+K89ZXjjXHIw50QI6PuAz8Gzi7gWfkOMbO+Lzs2PP8iXZ1"); - a("dPt5/YgzE6xPde+ik1fB37McSuf0QIvQOR0KP9Os21e0gi/UYpsboBPvlYpDEbf9P57Rb/v+YLz2l8r2G1pk+4TfNl5Ktw7HLT"); - a("Y4bPef2f2PF/Rn8HKdiP80NT3BfdbOf+JrT2ACdY+qh10xdAEzOghH34Lobwj8rt1C54Cb/+RHrp4VGwrRlL7xY993Svtz2Hqb"); - a("OgcFvW/5yua+5UvGDo/sxKn5HvZEGMbfjZbi7nyDmuOOYh9/S9095TUq6N3sK0O809uxbGk7hu/MpSkbL2uHiP7mfO9bFfdSIt"); - a("cyqRlBUqDWG1qBhmwzQTaPZAbAfnmGJDB/FLLZ2m5PkdtBPuCoUA74O2zLkLP8Xm379vno/SHBfGRkTU7iRrXLz5Vi6yvTEumz"); - a("SnxT8xPLb/gZNwaNTopC9U3HJrHiJjUhafElkIbXT2FQ7aQ4457fxvOy3leG/8ksjo6SGZX2SsagEqnm0o5xxfSsjzM9b3FFTm"); - a("/7sqVtPD2pGy9rKw9jLvO96yvCnIoKMD9iHvUGB9sbfPwkMQt+yF2L4zDG7PseaqWRAcFGka6zioFXjTDpTZZhikIljX6ky4Nk"); - a("t+b63uEwT+chtUsbHa4Hmnn4ZnwudOJRP32OgFaFaTArJtnAGn6SQFQbIjFefH9A4tAghSA2/Ph4Z+LzdlWKSk98vlZocNHO/+"); - a("xcrZa46ehrrSeMOD+G33Qk1vb0yJ5mRWXgVEXOLPeLPCT0e7+G+YCoIqUnNAlSOqOJSakWtt1c3brs/+1oNyH/Z0PuQdPzWCCe"); - a("ahRAvNKYiJ5nJh08PS9U9DyB//8keX4LJP1X91X7Oc4LxvVhfsjCq0MXg9/1kqTn8p2yErqxCR4pO4trdzhLyFVx7X/yXvg6hd"); - a("246Orv4x+9jH4meiyc/xG/NLgLgsyNojJ/pjIleT9Uh3S+4otYcv3egO30ODwxycHD/gGcI+O7Bt88+q38Dfz9xiE3qS8cieeD"); - a("34dXYz7WYD4aMR9tmA/MS6DDUE3t64nY2Hwx5AGM002Z1O/nuN8VRTyg0i5MllMNqKJ/UEA/QnfOlV5Cw4xYfXyXvsRwz9Wozl"); - a("Xb+Nytibneo+V87XDQcY0ciw0sgUPfHnqF7euB+B7zhJvmu1PNt66sOJWosIRce3MH6ukLvo/W9jf/W8X8Q8bCmH8qg3fhWP23"); - a("owQOrAYOrAEONKJjbcAB4ALmQOKA/f0/2nuw/j7JFslgLjQwAsEaDuLo4EcNAExHerUf3BnfBehsf6i4NNhORrZKQmOd6qs4NN"); - a("+JSS0oLQhuLG76NMWLF5Kmz1JmhUa6ZwVHcsr4TRDAR0IT0pHgT0/HI6wbSeeWwmoxVeIPjk2inN7xjcX4PCc435EeK5IRWkbP"); - a("POylJsl1RyPkKYMYJl8p1LlQKUAaqL4A0kDU7rODNBwgDUSKDaSBBNJwKgSQmpFGIA0HrsYHSfELQ6Xzl+2lk0TlOF/Zm8XBth"); - a("LUCRsBxbARUOJsK4aNAL+zKfhmZBj5pGPR/EgylD90JcEcq/RHXH33DRBurV+fXzXP1UC+FmtevYXyVJSGzpp3eVHDwmhB3gHX"); - a("bdc66Bnl0qhxrw+dXxrsoOElj5CY83mQrjdH+pPStRS8HRbkfVT9DunjnmCqr3Ii1RWOV48b9VCZz1EmWDUPNHp7wMXP5rhpyS"); - a("5Zdejt9nTxDA/VSfEgny0esENAgho2kQyVUVoXec2BYf6G06sPEAGAh9zISGHWIeT2h9ZSRo4lRYKyd3GYIrGM6ry8j10rh7Ld"); - a("oW5Ihof8lJ8c77dDaGgluZuB8AGnwUdTtJ18WH/CewkKbCsKflUQ/LEoGCku+6G47G14f/JNatKq/YDF2Q3vSWW6XUnT/Tyvt2"); - a("os1bc3tq3qAZHPwEOOOPM+XpoRB5bq7QxHR3Avw5G3O5ACDZDUvO9dRbvz9lX/mXoFfCerSnntlaMxL2dhEDBWRcHPuCaNzF9J"); - a("h0UwL43Bqh4Dl0JOzoS9SmSq7WVa04epXhs+4z2a8dKndK9s8ihtuskCEwshF/lDhfPyC+cLvY9t+0nvY97SE6H3Mc/Q+8A2Mb"); - a("sUXwKZ5iSR6HppsJs/nU3a6H/0EqzIpEe2kr6kQ8UwCoIDqN22l3C5sBR6Ik1fYrH+Iie9tnCesQnkJMVKwKj3AEj9uZBrLWti"); - a("pKVhJgeJt/C9qUozyfp+MBHP6QtgrwTgLoQMSHT2AkPpgK5qnwxh/OnrPSFwCDRAFzlAhkO+JbiSKn3zePzPNmHbAugkpAgeAl"); - a("zc0yjenDCAI3NpM7ltT2/UzKEJFcyPpZcF88zfNv05P2pV4wekzElXT/7x/RlqS4R8Fnkl8laxRgV1flMH3UeE4NEu0DeFEeYW"); - a("MG85NG+be3qjtklSnNt44yGln+Rw3Nl3E8HKnPT4dSt/XExL66JLR/DBLOP+avQDwzm0g3TTq+a7VpL1A3jfpS1A2kufTXzByg"); - a("lZmEdRaKEs1PEBpVSVOipgAXY+kJPetWeVwpEokzPN14a+lp01H9VJt12CAiDdyT67RoMXTyVAvbTIebxOpdmas0qDVfO7qgEL"); - a("AdVwPQI4ZU2qrZrnqHKjbbyEAmU/2MNlqAou72s9q5QN1niBPZxJew5ZYrpThnwCylZekAzpH1sFINqjnKpACAu6YZ8f83oaZp"); - a("6PyBD7FKDwQegvsrEOLXmPrjK4Z1v/ujrx5XVrX6LDQlLFQFAkumBHCkj+03yFKE1iueFJoVriKuCEdzI5zE+LZEam0N06I/VG"); - a("A793vkf4De6+kLHq0HduD6qgkVLQ2MeHCcA8R8WksIVUGt0diUtpvAGLow95n9OM+VaiiLqW/NgbrXlJHA1Gi1S10R+W4uR3z1"); - a("/Ncyaky5zdbV64I3O0qtdZL88Mp+q1fb0Wmdbr50gENpI+p6NP+ENDktSXPwR4CQDUAbTFmiMIZ4VSsHGnmCBDrUgGArvJCQCW"); - a("PmqQZmCDqM8gmThg5PZFF+LrC/+tnobw0NrepIBLLzgPBem8Q2mq94n0meeRPnPGYTcJAYQnoPSk7POZ91PdA3PNq8t56k4g2j"); - a("K/XTyAsVTBHu3+p4wHsEIZdc6TRhRbtzg2tsTvVYnhMupeowTQ2Lw7Hsz93B9c2s0W/N8nSzLenCjd6FrZqx3VPf8Hvu+QXcfi"); - a("G5UG2P1AWq3baTVgdcn9tKZgPVJcEQ2+PkxFRi7jcxXMivLhq9lHZ/quM33ON30b94L9RjT2Anke9YdSkvDMrFfiE7I+RF0G4L"); - a("hU5oyMwc+voogIuApedNa+RovdWeTyfh725n2x9PfUhaJgVlF9T1+3cH9oqfUmZKc3vKH+9HsegOGCyGh/AJeOSc+R8UlPYFAr"); - a("olk+JmynIvb9V5K0AG2+bdcbxGkutIoiU4Qy7rwq7E/dSH98CadruUiMedbx2JE/Pv28aZ6zqqDmpTpKCQzUyenxlsMeBteDBr"); - a("4T5PrQH2IpmYlOx9qnoCuVXNFOdRfz4XYmSatdhUCVBxI9g0HTcy5IsuaM//77bfz7MvyWHGB9SI1/nu/Gj1WhApvPBKH92EPa"); - a("j+/CU5UMU9U0CTU4i0Xc9AXoICfh0L5Be1Yjhp3E/hzM34OpAjSl3cKV1SFsVaUEBqY6rlMLyU8mpW+NOuRCekAupIzfSVbmEL"); - a("62i36EuB8Sbe32bEge6ICSUounb3CQ+rh23dv38JdVbp88oNsiaD6qP1sE/55+6s/XkT/CKX3rp047JpF+6hPXqkH99reo6oRe"); - a("h0U/tRHKbNw/pW972QPIOY+9DxWywjrLILe++j/Qt72jGVV/NLnv/vzs6ET92bpI9Wcc9efnB6z96f6t7E/FeAP0HY3Cfoahb5"); - a("uu7dnn6EffVvEjpK/D2ipUOh2qtumGqu1UVrUNCz3bdMjLz3iZoHgd+gksOLGTBOKhGMOKth9a+QT28yX47MTCGm4yrNTmULe2"); - a("k/Yrn54J1n+kr/XfKOZHE/PT3Wtf/1itcul3TDCWPqaOVv4tOHEplXQhClDMDEQJqoZIIZh8gkEGGlJ/Cy69kMBLU9aUvlPWlB"); - a("4A+dD5gyfKhS0mpdtu6S3++0C3X5j87ha23ohxrRlC2hrbetPYBIyU0e6krUhm7CHLohQnBa81ofPaTTqv6hlB6byyzKnlkYHl"); - a("rk+9B6N2yFTMkMVg8r9rn7Jq3H9hzyS02B05XNiZvD6dLUy2eqCpII0EJO9BAAeEj/uyZ4IVI5zdXXgEmyp08+hA7V6hnWqPbb"); - a("Ff646kUFtKL1yKWTh4599ugdlGn4Hufh/bF/L68n1uLE8Y50Cr7sgkXwh/B/Cd7zz0BarJ5L/El9cU+MaXf056gPit6aSy7MVR"); - a("cIB2yxEWO0Dx1sfQzv2w6vzSc2qJ2OwdSdY/8j5Heas5b+3p9+CDkSK1ASEfaAChc8TF8Hm7EZFOEQJDhskoNxuR+0TH78UC75"); - a("RUvh0+D7V5WAL4tFmoRNrJC1yLEsOoxId/E1B27wOUgWNhr/D2F0z2KP/mxE/qI/jhmSGfJK3IybAPfQUhTWzLzch8PgpqNx4m"); - a("GpErxM3gz7GAH5/+/HFXAvn9oQuosfy/9d0/5JlOeQZQHmmWfOihFFOnv97eFpWBhy1Pevb3xVT3XpqsjIH8cwhThRzVtEVeHQ"); - a("P4NDLChGMYRd/bw0U37FFFs8P6kGaSRaUTeZSatHwdoJsVQPHtsaGFEm5hHNubatSre4OqewQJVN0OED47P1KREFaEeWwUMrNq"); - a("VoHr7vUVk7Fas3E5ID7IbYfGJLmRlCmkg7QmeLANQxY15kbEvkp9+ee6A8mrnety1OnIZH+F4w7eHmWmtvtQnbfx1KH98zYS6X"); - a("9+0RtFIEdLRcA6dYnlG/k24QdS+YNvaKOonhDqGUr1sM5QYCIWStUzaqHcvJoXyk2r1UIpzBT9+WCvvkBKUECbl8m2d0gNic8Y"); - a("GkTh8ZGNjxxtK30E6ZFwsVg5x9LK6VNCEO/7tTdmMs+UDEHPcAM3+tCv0dqFqbjICcjD+sq8QbcyrcbnRlb6wt4BkEGNCRtW7h"); - a("V6271E+d/C8PP6AXLAlEDcC5LFfuPKz3v7knew2VuVYiz/rt3VMOWUpCYTv93c8Ml/YMG2dt3Yu7YckEh50v+NHfNayJpplxzd"); - a("tz37EMCYmplIHqRNu/qz3gT6SGabAG2GTQAaOC1VHHI7DBHsLuKJyP1EKgp0aJfu5xm9lCN5ozwGwQ6kZ3HzLmEzoE0UwiidgQ"); - a("MV7Q3HoePtjsAoHbdX3gm0XTaK22wP03Bw9759lnk13NaI/QIilOyApbwKDDNXgnMeiWd73MLSauVpOJbH6CNprI+kBZu5yunP"); - a("8FIRI+3LJCQcCNZf/sVa9WYR6cnkrgTyZK/S4Ztfh/PLO8hfe4aySGJY8kAE/FMIeA179i0wosgf5fhY4d3B3A21tuLbAwxk6q"); - a("0todZ+lSEuO6hXt3bT8Uzf9lMVPVYk0GUmgahH3EFOp2sHj9uSKNQMpgqjBGSPgNrB45bmXi3HaugpPyQ5aKg+hrwgzBHgvsA3"); - a("lZ98qx8ML8tIREclMbf3F1ThpX2MQ4PF+Yz3l9XKpp08/4EG5QgDY0NgCyxHu/5pm3Ux+U/kTMY1GgQrB/RqXWJ7Ejmm8U7/Dc"); - a("Z73wge7xwx3jk03gt5HC6xWIuw3Y82ag8Ukl/EQo8OlDW9WqTPiJveOoMNtzNMFROobe2dZ/lymMP4OJyjpo9k+305cez32ez/"); - a("5ToqpqBQrnarqCeX6xnDUT+M4HrYce+ystIobetx62P3tR3iPuaplyY48kgSaG0U6eIx44WveqPsC4C3I98oYV9lhGf5LhyKg/"); - a("AkIP2+Mj48wj5/MYyW87brxVKPtmOJYiTZ02dob/WV3gDzrdGPeqMy0WbvQspz446cSbAlh5Z4ykOzPcGe8rxmWFupL2IbFldF"); - a("DRsW85UNi9G9IjYXsdKGheAZnI9TK7+1t1PnQoUzmr51L4O0Oz7yelStp8at9dMDfdSaJWu1W8aw84fQdT3COl5EhrUd29SQ2P"); - a("1RcPnaBaW968zfvlJnHP9whrV/eGwPDJHL9f40QChQ9vwwoSoRlKKGBVH4vdbtqeYQLVn/BNlZ7+FiTYaSSgGkwahUUf4Cd6Vb"); - a("lhey/1h/EP9f+pqZgNj5Z29PV+hghxf4uhzHx9qZpbgJ1paVfisgPZMuZadRa4r8TRbkj/1I6jC7ATOg9dTzWeWhqKB9H8XQNL"); - a("O8Pcvaq2MwkY4SrVfYB38OsBFtvABTjBcnyAQ/ezffQs8yWbMPWE3iH32pOv89WwvqNDTisFiz/z1c3hh65odjXfIalKYL4VzB"); - a("0NWLZFCiziYGfRbR+AIwGdhd5ZT+BUFW09McCPGxUInBSfzwrIvFn9ds95VVdv0Q5WKBBuKX8jEkdCe/+/3Ul39JZmCu9BHxQr"); - a("Lg4XiNwUEV1sF5Y74anLtvpveNLuvgVC2n8+XuwlIW3z1KDNJYGiA208HoqMaI6FMC5RDLfamdHJ1AyIjKLrIxyvvi916nMv43"); - a("/KIlNn5Rq2eO02ByDaVirGbrx0jGspA8gg2QZ2MhhRPykL6vxXl0w2EWHpLt/YxsebiEroc6b2CbL2KfxVW5gP0qxJKrbiw+oU"); - a("Jynng7zwWT8v7HWI1Xfl3zZ8ZKqPAKtnZxKGUCCIesShwIDqGq8ue5qwZynfPcLOsDTZanfA2zcrUnv3Rw+xUOLpTJYzMrk9bm"); - a("M/xmwVZG7tGEAbzhJLY6RICv+FqK/Kj53O0pJd5VYDBdii9HyMjbF/8+MonkXHkTb/0LX5Tkgtuzm/mYjMrc7gJxLtmszhtx71"); - a("tAawbBA/qWLijbyQZRYw+eR7P+kaG/hKYh+XHanwRj4FkkwTvnl+VhddOync+26FPZCOhYEVBFtSNqtTOSlNOoAFXyZaZqilvX"); - a("OyT5KxVwFodjqW9eATj40q9wi6C/mKDwo8yxLg6VMC392e1EKQKpJcEdkfSivN3V7wrfO1YTkWgqsT24DpxipTfjtxFU0MfZX3"); - a("Ma+6lPjcdClnWfJd8YIRmvaKy0b/sjTzQo65/QrE6VhgoJEcR6IHJh95SpwOujP2JtGPlRHQh60S6DoN+HZkUbiN/WQyJ8ZxlA"); - a("vqEDGZ+DG+99HMvIx1bYZvmEexwsPB+TiVwsZrdymeMeSoblY5+4/w38arPjVwJ4RtvhcQOcwxQ4TW6+aRDRSH0pyeOoiYXMQq"); - a("9rl6BSN5vICXlE99IjqWuiynNtv/ndtvz281q884N2K2dsoZuycnaDDNYd8Na5ageM3EDvnZ9Zd8DKpTT53byN96PPPXTVF+Bk"); - a("/uMpxVIwv8/GeT8rIfbnr6jQ9SgEZOTXgn/+ic06f+MEAfqZdCdAejw7+B6+g/3raBOZCHnZEaC8RzTQ1U+7cmsvve1QmFVwhg"); - a("zmSXML/yXkLFCbtJRkxAI72C4ImJY924lpeZ5kx0bwBQbpdvzwzvY4xgfN4kUsh30YDH1TZFjHP0rVpVu0MIZaaK0kWmRWYu3S"); - a("3mWIkM3yMJdgPEtpaG560jKedv8NBPYEynv8k2oYH35UDeN5PIwMk2UcP3qEQPGkMy//KHSQIttEZKbq1Tjq1Xc3yXF7ydq3sy"); - a("Xz3OKswdqfGgyZ9sQTqj92+zZL29GnDhzWuF90nkE5H5Wb/YTqW+sjqm+zYvk1tTAzhPMXO1HDGYb3R7DScQTAKsaSIrlHYquY"); - a("/NmMEf3SqtehX0gTfSqM6iwXsJ8AFsT4UafqWrz7zbQo0OnvnxM6zQTcqxHSDqPBLOv2AVofwD2RLMuhHfouDm4L7kS+eso3W0"); - a("AZbZc2yQaUh5G/+gM+//TYCI2dPyzHCxAcQxAEDl8jV/a5y4TtkAcfZo/pg5BabvD6JzyIZX92stAyQi7xujnDLbmW3fRIFgb6"); - a("sDhiWrn06zH09c8AsgcV5nt3VE0QC+MZirvtIUKFUi7PLLsnBvACbEWGMGUYLAudKQpVUtwFXGhup3hVmuEOHCkSL6XE05CoQ8"); - a("JKVTcC2sgkUvEQufIo1y8eQ+RITr8Q6dpy8jR/KVnd6FvftkObmpxIP7VHnqe1Fjhb4qMtfNqHLhOUh85rTFsHOVhFjY3B6KP6"); - a("/kqMasFdguMYFsdgN7c4PYhIRswkRrMro4DbTWxLNAJ5CDc+neEV3u12fbbUrE5+tBnT2f97j8IHlNM+4XKf4kc99gj1STdg4P"); - a("fZeu8O+f7EaC9bt9ozueStft7fOwV91/AjAHjXIBSenF3gt2HR3UeSdHntFeX4JKKLGe+uuFDcQdnfNXuqdEcgCin8ywAkTz3b"); - a("3pIenUenonoRxkmHIVv/Hr+AsCodbPWQasw0JHvSW7hbJ3MdSBUQhgChnfja7eFeDUF21r+6TARg3xwBNQI2ewasb6XUxFHgJh"); - a("Swq1rhlkXXj12Rn5K7iHPoDeN7Fh8ArFcIpXcBwZDl+JCErBOSWXJbzxSGRjLm0vLN7mAmgc9V9L2ouSKV3kOe5J5PjuobONOw"); - a("OPRL6XFguqReRqm0l/D3qUQhR2/rpYY9LzpQbQlnqVmCi97RltzA/O2rANAx2ISDLXWNHtfdrZhXFMqUOT1KG4+Ux6A1UrahuL"); - a("bLaVRknEe1E7aQ1PUusMP4wJJyhsjT4OsRz/ifASizVLN9fbdpsyz6Vbb3j2g/7xuKBvjxrNHi3eaQasfSOjfw2FW3X/eEdPtv"); - a("6MDK547lCOatc9V16mmLEYGJG4w6nF1vIlbR4HlBjNk6iHIRGTBiZ1DsUyK2LezHfPuFSax2mtb1gup0Sr3QNopbLdpqpwcNPp"); - a("pw4wxQG+LaVFzeusBJtpx4shW5QGcRz/bFD39YPLikEdiRFPwVu+PduhWaJ/llYpv9ZSIuvX31QOL3NqkPi7HWaJxj/Xqfe73Q"); - a("iX3jfHwSXZVMig56MzIEiqTnOo03MUwSt3v0xfKkcpXlEVvaHy8/nbfG6JYkno+t2FBqoYuP8FgKP5YPovNQGEid+iSy6AB5QM"); - a("i0yQ9y0ZO2ctGLKfsSyp78IGW/mGpsTb0D0fhHwd9yUPVq369RyZeruJJLt6rKP6f4DSL+bFGLf0ts0UWb+UX3CvzIvmP/Zleq"); - a("y5o7RZavPwQ82fuoKxmf4nqIqEMxjNrru23W1+znz3a0p+17UG2RlnQPpW+1pSt5FGo8cppKt79nBzTsT74PeX8q+NC0P6H6c6"); - a("n6+Q+qY1/779Sx75hW73469oW8+/k8u1+cZ4f+TjAn5qLL+YH91Z0868cgIyp0UIX5SEH4hw46L4twD4WPQnjaJphmPfYTHqY7"); - a("CfgNeVQw9cWNScxOHBQauh/R0fbIAIz7HoY3Xevay7XcQQU+QhiFz6LwtZt5Cn6J2rEbPbynl06HIaRAHgj5b6Y8B+5TvtNy0C"); - a("WD32LqF/KeT3mn3Sf6diPayL94f/U2JJxOCQsRAfQ4DmH6R+9tFH2uiD5aRrekXgp3D046b1J/k1epgb3hPjWwUwkKdZ62jO9T"); - a("9woYftxjHt+vDvCQ5VC9N73LEDz3AY2vmPuhH9DHQ7kk4ozR/DO+hPyNJwfI/Tt8yqfSbPDDmHqWZ9GdD8NViURH4E10oxoh48"); - a("Jxj2jwaap37e96ibAOw/c19H1oLpW1XFit/rbV+4RExn/w8xPvPsQU0+bcJV6ksumhUvf3gzjehMpJ98/1Gv5MdNSQsf3migHl"); - a("y7CYotWcVI7b4tH4UzGw/LhodYUrMiZsXMMjF4fLEc6ODojMxt5YvuzKCdmO6aLY6W9HK8eiXPVon+s1euTZ/aHv3SvRHhVA0S"); - a("yVLa389N4BVYN2utypH0I2PzLPt/EXyBh2vYgc9CqUA8H6k2QAVeDd048gb6ED2zgeTxtjEIHYtXIwanwD2zmpHLOGH9Qu2Doe"); - a("ucEqfoUcriYxNIZZh3JqgGDIktTFnj/FnD+kcvZVf7o5v89agIJtMfkHqfz68+JoXegod11c+Y6ig/Kn2xjPn+6QXcAJPs2Rz+"); - a("8XihRD5c1fgM6+0u6wqExMvpLv4dSGvGul+4QdOMiHGL7/y+Z2a8vGWiVBCgQH/jSbJEh5OKEsyA1oUzsvRcmCHLz8Zmj2WLz6"); - a("TAIRomXglM5tFOODj+zD4JwNsEMK82tm8POT/h2Qqe1f1tM+307z/LleUPNteZ+WsrrQhBqrLECa/BfMs7+p2O1fvZbg/JdIf0"); - a("a9RUHDJMcQMhZ+5mVf+fl1Qvf0blfdsyqWYS6obykvCnaXT3Q5XK81BtP+zD47loes2YKtUJO/biZ02mx+RTibNNX6amNwQOTc"); - a("sNkGAKpF3OlGnAdxiCC9nnMLFZJO/DmQNHODFUlvuYJoqNk63gJhTZTMoWodr/ZG46d1aS8jTdgfwJrrXxvHNF8L1Hwlsues/W"); - a("Uf+2oqa5d8Xunv9ny4vYsx/WGX/1LnvRaLLzhr+lnUBjDve5fbTm+Qfj7SfVc0uo+hgVM5jPRTkM4JO80V2Nabl152/8hWObUB"); - a("FWPZ0dwv6a9reYWITak4q6uBOqO2J545ZfsO0VKIfTzdNEOjinjNmEciMkv3Q/MnkpMa8wrUXPINnzPnUVwqxSnfNJdQ3Hcv95"); - a("p909xBcR8hLvzvrN9X447fCziKAkNVgnV+9iSen/fjp9vt37+U6L7BsmvGnVznckm5AzY3jyxkgjiUxAbIJKIjwbjDInBpWNBy"); - a("kJNrdhGveFttTzQwGQtNO1MttJcvweg9/aZ1oR1ejo64XvBucz3h3RFZwYefKwaQv1UkaA/09korjBP5qLvDTLrj2/PEotyvP+"); - a("ukmDEllDp+itOR791fQTTg6zMUaOMJtJE20G6+jGmAMiFifz+Sk74uMV4G26DOSnrX14+Ki54Kn8z8CH6dKajtGXJdJtbBkIo0"); - a("/E0PDGH7u7vp0BwBL0A0oredZtozgusAe9m70md1GkCo21qFt97RwsKgkdnKQbDTm9OotVbxBPTNe6gnyv0AtSnY2Gnph53i2O"); - a("v75y5V36vbEtXXv33hDWt6haGg1xHo194mAWFzEINT4InCVxxGjd+FoNHEWCRB0cT5Yli54e/OlxK7x+H0rZm3rQje0JWh5hqn"); - a("Lfdn5twGftORPaE9W/iverE3gf1UzazjELY54K/tyXDd6sBOO74RaB7B25evLOVmqKJGccbr+krYk46Mlv00l653WiJkP7bY2u"); - a("gC+0suLPTqaSdiVjqZ15Mk435Pcb8WcSky7laKKxdxg2TcYoo7j+Okwftu2ZKkQzz/L/RGu44zvFXf/gM/mG5hfSMqf4hRXlss"); - a("0zZ+RqkZlPqDzpu6gNKaRco+6sUWh1GO2BWSX9V1vbLfZxsOnFFqe5IXj7AOHMoZ4/EAIccwY3y1aB/j+pllXOPmctUtAdLYck"); - a("bGq3E9nr6Hh9emy+9xUs6C9SsOMMbJC6JVXhH7t7RsE8lneJftc6DWqgGv0k8kKfix5Fj6eqCryxdFxeHUN79J30M1rkVILKaw"); - a("xGIC+6o4X/YYInLFwR+67hLn78Kx+YVZlXNICL6IRY1msrtkZfmwMKtO6GvvyVM0vQSnX82z3krT/3op0fTWwrG8QnCwx/F+Uj"); - a("u0tWHWu8jl/5ZagXPrsWSIoKTsdUhTaTPreqNFzl+NhWWaYuf6oknf1kVdt5fHcSCGw12PZTDt9o+fO1h7V/bDJ+v//U3p6dXr"); - a("lq7ui2vpKr7+zt8Oun2J5zYwzAblEKj+WPBD+4Lhv7hvtsW7b/7hK/N986xT1JRfdD75e222TvlLF/N9sygkFJ7U1VAiqWh8Rr"); - a("a8epZqa4+2XjtniKtlvu3aiXoT3jujaFvb8mOv/d558Po2DTNLtbMBEhA/W6tC76W+KEJ0u3TR7XKQcbtUZwkbvwJdu32pEmaN"); - a("l16dID3kwxB5sg0+s5m/QfbHlAu5DwOYiLu+tZ5Q4+JboEd3BIuaC7MN8pbXzce0P52s5vfXc1DtVY3W+d0KhZHIcKMCRTBRfS"); - a("igVmR8/ZfVvcIQbN3qBOcHm/85MVsrvDnFIebkFQsFwZ7ikJMwuDhUQJ+aVP5QZmOFeKDfF7qT7ERww1OuIFhJzHMnQzSWv0va"); - a("ycZQ6Svi8eEwJvIw10TKMyEqKszm5tBdU/F3lU+2+PIHaO0Mk5qVfTwe16qe5vFYrQUQSDgeNRiPVfY3C9qkk+jBhnU68Zwj33"); - a("6RC9DxKDViOB6Xw7JaH5Y2rPdJ+u0ixGY0GI6hC3kqV9PSZQj3X87j8zh5MMt5WQgH133rkCWBpOLXo1CJXLqVxk2tlw221LgR"); - a("cgLfTjlR4dsgHD60A69Y8e1XFwLfxtjqk3hnlF5+NfnT/6xXvICr7CAS5iKOWBB45pEnOreNJ/YMMBEEYapX0573sn4rOpOTMQ"); - a("9qvu3rVR0YlHvZuPK4Ldi/QfHW0Oom37mh+nZ+eeSH0Wa56leo++zB+RcPWgSU/vGCSUBpmDaW1elAmwk+7w7w05Y4Ko7wNSAY"); - a("5PNEqMaQ1/LyIpi9pGbpDkfFsSS/NU1N109LMeCzXrZO18sXJBA7stt/xXMeACVjGtp1IqwR0OUI25eDuf8eYX9jEf+8skSY4a"); - a("jBjz/4aD3/PBXmn+fv5Z9XVh0gAN9SVknrqFUZpEZ5aRTDYJcHa+MATqElIYSLQze4u7YlGedQP+uCn5/N4J8JMItrX57Ay6si"); - a("szh024TVPHpe8upTEL2LU4CNs9hZOUnlT+/UvQC6lr/PyHgWuzKtewPP85sisPQ1vOa0YYEj0AZJLOZA6JtN08KI6Dyct3E2Pi"); - a("NJL+WGsilKvUGlBtXkjXLVXeOMm6ad/5V4mG0oHON6YfYY3EHoNRyPmxhwkmpgjNHCt/aaxRzkXGx5jk4Ar/AQBX6hxPvsgPvI"); - a("dVKwjiYcY0rTL+xNNFAQ6NM2VaHP2Fm0Xtfq6POoRJ+lc7GNYfy6JRwkcb8HTUOiZ5Q+JPQErW2noaA7h8lciguF1hAqXf45da"); - a("SOwoCnUcCzRsKDBFFzXbtIaFOArhGARqcoQBeXANCzDEAbJKCbocDd9TfKoiZKe/o7APVHEZmtBBpQHnwhnHpp0qvxTfm165oY"); - a("iMfZRuWs7JK6Nypgj7S4hw6+k5rwl11AoSJ9In7zd+K3Ma7yWi0pe5tEGVRb+kpaiIz+EIf9PEvnA/0aqCHt8PUYXxZRZ+3mV1"); - a("+jtbELZxpX3ZG0QEB8PFr2GnnS/QkrVIhFFhKLLCQWWUgsspBYZCGxyEK0yNRaT0wfJVGLm96j0s33F9bJkAcPtaEohKxNF6KR"); - a("VrHTRSa8e2QmpvOGNfp0viqnM3W27XYW976/VD9D2Q5AeM/sHRhIhYPRyEm1vekI5UQjRDTPMyHT0dT6mBetRPPW80haqIcBCC"); - a("01naOs9HLWY/3wIwIxdwppnVq7IMt6kYDB08BAivKsyGEon5ysoKw5B1AufsEK5afnShmMhYjwuF5oAbwW9WubP+rX/iN4jxmv"); - a("4E0Lefb7NmoK4vKQgHjvsQriDcWAuOl5K8TH6xDT/dH1oh1gO7+MOXVsGp4AOaKHzesUI147oYLuspHTFV9qFXCMUtZcxzSdOA"); - a("34Zpt1XpfIcmA/S+F0Ufg3g0XcG7tZQvEVvbEc2di1SE/kz5EZMhi3GbnSeybOx6Uk5Xev9v4W+34Zz97+sEd7hX+r1EdVgbj7"); - a("aylGDFNUo9jWVh9XDd52JkNSozhbOk0ljvB2jpOrmRl6MiKXzqMy7EZ4Daq7l6vTncvx+fIDJ2J2QwiSX6mS8KM0tkfL9mhHbd"); - a("dO3yCM5kfSdQajUDiqu8uhF1qzhnfnUwymIwoKdwml40kIqUlUWN8oPWfJgYY/xzV6dUAARWXYdQRdk+sliakHMl51tELGgrOJ"); - a("v/2cjoxNEhkfmgX8ifWLea90mUdzKnuYC9jfd8honOkpqet1EwPVgP6OLCZ2q2Uve7iXE2RnHE7d0BMyGB3q4Tu07FMJaqHCq6"); - a("OlxAdYhfFOkT5AvKuWQaeSbbFRQT8EJ5B5la+1mTkDSFfkFx8ozX0iRczIWGF9vUs7JJn1BdO0K9DxsFb4JTDO0Ad7j3WZZBnD"); - a("Dshc0h+/gWf0XuE/olmJq5S0et9SfiHhZ4PlRN4KNnPO5c1c7PHdnjnci9Ho9eO8Nn79awb5cWqpPJx/8Vssd61jV93vCfuklY"); - a("BYM0Uep4FCjKMVR8nBXSXmvd2PnGpwKQ/6B6y0+SNl2b8ZmwBHvlcLHEtpGGAHjYEar8+ccrzySmi8RnyhxiswXIiPk26AtsXP"); - a("eMRuPriOCpekBxrRA/RNjmsSd3/w9WoIj5VDiDym8eNsRYFolMrQ+HzOddgdxYmKF5Qe4BLPBlTFk/S5CVvr3QGqSUW4XjHuSa"); - a("ax9OWCUdTGsEsKYXgZKdcpQGCoubNjZEEfFdKuWkz01dVA1h64vbEmqE41uuux9XdOBdsK0CvTTro2GgWMLP8e08JhSGC+kw7N"); - a("ACHyOojR7uL3MEvarfCfoP38cwTDQj9hr9x3qhAQIwhKypuO5D/p4q8QUtbue4kNlz+73MniXf/s6GWXm9fp4ie7PaJhN8hDj4"); - a("M2wcHaF5uJfrcmE17qjGCmwjmb9E9FgGsIbU5EKyxqKfnI3SqfTqQh9ByG0LJiacn9g3BBijjmSFTrBKrlYuuw+zeJZPD6FDxy"); - a("imrWcsEPZ5L1TjfvfJ/zx80pxraQwxREbRGdsY8pPZIe6u1jHHIEVnRTjwBKTmwBh4muRtwMj3QjffgeqadTJEDR+GN3sjzwDp"); - a("OKJYaKyhBOv/U73Qar3d8+M9fKXdWwJ6+OhWZuSGpgHO3u62BIKCY1nXDcNaklMpySaVXs9LmObaQo/O8Ol7uuQZ38XIipOPj2"); - a("XIFjbIdTFSHlaFzZMLfF9kbx8T2aRYQru8XeqIGvG3BpQfmzzE250ZSMVU2pCOnBA0+nGXRMmibcXUg5BmUOg3Ht4Ps3PJCduH"); - a("+Z+sC6qYPk72Vnn+Pa9/k++L79iN9a17inwgXZCbw8XYc/aXsqnD2Lx3DG4E68qFJ2g1ryKXVOljoYZON9XjvsCespNQgfu/aj"); - a("fwL+rQ0w8m1x80XiUaxiKEl1ZNGfEyPFYVNeJbzTEplvjpcCPBRfpOLlDojI44H76EpwnOrKxWegK6V/sXblVS/bdO+Ozw3uF5"); - a("9G9IdPPolPwwifPmU3Bo02RLLLbzDU2neajUUu00EYNlsS4/Ovr14j+dev3ycVNfzPyhfxhz9SJ+o45+kF4jx9L1BsFabxcYFi"); - a("sRxrpbDBNU77SNihW5MK8AOETAMOVzOwdTrJaz9unYHpRbqRybWZ1On9V/ILhlbRTVIA/BL991NNL9Hc0tlg2fAxBKOa/5EoMG"); - a("IUeBlH8hmQ8xSa8oyWeb7NQJ5ep253sfQAPety7okfqdxdEDro6pCXnP3EIZCZPKZM6ynT3/hNnPNtNuXr2aby/YHyhaQv5mi6"); - a("626RJcNU1Y3bBHTnEnQLZLsn7TPVZ8rsp/ryVbt/wI7tym7jfGFTvgmUb4TKl4J8ICdNnPFWU8Z9W5Hxn4Ytyin7TPkeMOV7l/"); - a("I16/kQ26nlHGJSxKk1dfoxynuPKW+HttwtrgKc91RT3puQN3KVzIf3jRGcr53zXWPKN5vyeZWcMEQPgX2NDnG2bQS23WjCtqtO"); - a("o/fdx3Rsa5HYtqHA8BP4rjC+gXM7EDwEBOelb9FvWnkPr5Y1Wp0IPK5VisC92mIRWKX9EgFjIan1g8Vu3EWVehPf7UwPHPfK31"); - a("VCxEq/m3KnzXfSbtOds5NSjAcBvoIGSN7eeWcS633o54eOtczL+90yvne1E3PibJoCrDXuwYPgyeP7Xr9QdOkAF6+kTBo45p61"); - a("P8oZVjEk/MKA9Xk3pmGSuZqLZDXmXO8jV9dOcf1k1i0AkA8b6doVG1BAv8aGOf/1GxnGNurKxGedND/rsJTpWPlEkn4HbMNZko"); - a("839+7gU0+bwTVuJHZuUk2uKzBCmEMDoVu8jatsjKTraIIkQDz0DuK9XNZGh9aA1xhw/Ma8+wCfJo1R+HR4Lgq5H7FSr6oz5d2m"); - a("keal61ZMut7L2rdtvQy3G72sGOUX9wjh5/6WZCz9JuRRUytvNOrBGKXN6U5Rcw3VbH5wd628ETE5m2gMq51iDC93qjF01V2IL8"); - a("FPiIAnPFPwIMOE5uL9aA80c8TRNJ38Pxai52lvM0v7EBFdmsVr4rs7xcP1GnPzgaONoneHiQscgkqkDMsmtNz7pdVwug5wBcG6"); - a("eVHmbRMbh22Hgw95qNOBhIUiYYGR4NUQu0TELlKxYfl8WI/prhGcjgaqDRPZOVpN5JxTSP/uYX0iA3Iinz8doJa+D9w+IxzJRz"); - a("W8FGvW8ExUHC7qL02PcXOoCTO3qVruGSg8ggo7BW15UYjPqvvTGro/5da/63mBNflyAStd0zsczDCagkZUNJDF+G7wPa6tuKM3"); - a("yl8tntUOGXjOUT9/QpbIU6v5WSdB/yqlr2xTffWdDlP9flqi8huMkk6ZUNpt5BDnGP6sWbLaUTG/ZslzjsD58SEMAcI2qIIRDp"); - a("yoZ+EFcPObvACsxbQVb1PZOYgMzmgLczI1UDHJlNOn4I9Zlbh+Ao/1O58PxyeL/FtY8gvfC0vq/PJmScFn/5kDjdpF4g27TXsm"); - a("rAi37fyTFeX3OsFWfGUe/zwPJKT3uoX889Qi/nmeUNHsRLDbzHZkGDIBg6L9ghgpk5C11W4HyyfdmKHQ9KkTgaarHrDSm2H5gt"); - a("6MNtM92PMpWJEyYYpzeqbrVg9uqROjwkeq43jTwQnjFudyMiCwQPcs+RAcOyC8n0lD3WvCBZK/zLtfmvd4dhNo1KQUJo1TRypQ"); - a("kwjUH/9oBbXsNBCXvcniNPMl6vaXNcqaFlJNnyQbZxMfLLpB7FVPLqbkRlnyrdi04yjtEZm2QKO0F/W04ZRWL9LQkTatfSfrkr"); - a("eRTP4Pb5Do8X6IHvNYXzXCxP88AR04ydaBh/JorE0D8MxG1J8t236um89JzTLtPQ1pQ0TaWqI+2olwEEkNh94kdPcNND88xkxE"); - a("KcBQY+OnRmjviz9fQ+NcJmHH9gXMuKxgXwQV3IwKWBlXzm3LdxgJdm8BaobThXebJBLebv0ZPcwarnvYu/+W6J2UtWbpNmwXpw"); - a("gXNunYsAzH/4Tj4iRSyJIsUiJrcBJBg2gByiICZTfvPcacVKYJk6W8Sp9u6CWwMpnIjjdx6ENZzhho+IocJm63rPqLLagavABZ"); - a("b6O2PZ254fowZnyO9EojfY22fACnr5Hpl32C9PlG+iotBRgK0FfJ9Lk7kI4bS9w5uO6SWm1oxUC6smZHzisP22ZEVFKCrW7pO1"); - a("KOtI882lukDih0B8d/iRXTJkxUeoR94g0XKjT97ALWZt16gck+sYfa9minPiRdD3xTHLw+hyalOHiWuzhYlakP++vfiqVQ3DAr"); - a("W8u9DVvVz8V5f+x3VFQftmHAvojPOGMXuF5ImQDeNohVWB60w1g83cMVVCmgMdoHv7c+Hlx2CnZAYa+XWYqCkIYEIQ0JQhoShD"); - a("QkCGkIhDSxvReQpas/jPatr56a81tdDRV+LAw11J8j6KvNBT/SYJ5egCd2nW/a6vFRPXqtFvmvFXKvqBOBRq0SASbqi1ckvj8L"); - a("eZd7Y68B7QbpV1uBOv7HPYx2moXRsUTarI9Y7UDb7ZjkbfZHLJaDzGVu/g8vRKNASClq3CS2U166wArbA0DXd8qfC3Gy3fz0sE"); - a("2cSjkrPIbWtiUHZ5RKDgBVwwO0NdgrOJYPfYC5ivzasDvT6eQzO948MCl1C5ziMagM7rv/LiwY1JGMkHyz0Tb/slcIddyNWDHi"); - a("Tpw32ZkYf41AvHzMWYPeP06NK88S3gZKpfn6e1TIgN2EWukGYO2r1Ndn+/LqWSLdFHaTPfi7DNQadL+BWgMQBGpB2AhZnlVZvv"); - a("qDkWU7guIkj/7O8EXGGHrteWRPCqJanIqksM4fNtDU81N6LFiaaUs49ULm75oZynq49pzSZJPN5G6dO6zeRGSEeBdJ3X+nAfU0"); - a("BfVUBHnN+GR2nzIAfTJmXL1r0bzK9thE8/QLWAHa4BjnX9xZvRWwGvIZ2gooVkfAN2P3vB/hQ6CpeJ94hWTXtK9OQL7mNxEU7/"); - a("coJqaM15OiEXZ7JA/0Sv/cj0p7JG/dksgeibSfaTC3NLMDaPXMb2esgpdaMQTKNxXgqo6sSAqU2HmqbK+uNjrSVfc8r49RDNi2"); - a("Z8SMA7cZPj8A1Z0trwKsXfVUf09tzyGo9WjUyrwAo85FTrEEperQBvQ3ciFlzzBl7zayL5EPCzL7J4/0ChmPqwcpCj5jEhDx5L"); - a("utx5+Hc+Sb0O8w5GarnWr47fITl9RJ7uLcOjkROx7ue/zNYy/H2joHvEcthINEDMgeWJrVRoJ3vHg+xRKvD4MfyKNeF6wZgtwx"); - a("Q7VQDhWDcdlqMezM38ModF2J7HLOYgY3cr4u1LGJxYcQrttEt9vzeIqGiruxkkyBmEflUdM2hWubIR86DK6R/Ugt90LHKj1a7g"); - a("0WFffmtVd/JnlO74ihNA2jVf5/uRy/R/8gx2/I8sT4e7BjOGFrvDH82CHGcErMGHZbx5CH7cinMWx1yJEIKbVtD9PZQh/Dlfvj"); - a("jGHXn3ppFBC5lSJ/2lO7z1l5/DRlRxN5fnysl9x5skxn2TvlOIj4MZ5Bf2lv3j5FT15LgJqJ5Lk6lLyWRT61nX9esYipqrGlA2"); - a("lDQ48hgng4jlJ0OCZonE59yz2CTTQBRTJ8+YXpFS7kcFMO4X9ZZppI/TzwtBCvDO7B0ls1DSvx9y8xq2UA5rbHyDsep2RN93cZ"); - a("6hZHsR79dKycL40kskp2s6mmc7mmQIlxnJOOn6T8qOSRaEKE8A8piiI4jkHp5Dt0ivCypAi/gS8yaRYL48THOZvIrM0+KXuCPr"); - a("Rrpe5P2h9anFNStws8KbY3e30SLnBTC+DD3lv3deX5MfZUiZQWtST5Q1nSslEY4853qgvW8hiNQxjwXZEDcH8hooZwVn9wQU9k"); - a("ahjevatftNrNcsBuViPLlqbmoKAvr8NVdzlatVk5Ndu/2OkaXmQy/wQH9wyowzeefMMP4cuUSGrSTvJNjOKyUa7zZLKU+Qhkd9"); - a("3dVB5CSjnOJLddSixy2nxhBmNAhY/vEhDozcZVaiEltSKjc3rEJe1gAFxYsRAtZcfUWtEp08ORE8rDXC5aHTmGyyHsmC6KbNRs"); - a("piyykWf5GxXp5cv8yFcT5owMIVkKJUvq0uBHWSlRJGA64nLkKesniOvD/kV5ELqn/CeOJYx0p02eknLG5k6Jk9u0njlzbIn0OC"); - a("XE+ywWMS7rQglbmwQskoU6hEUMWzn1gv2/toex/1mzflKLU626h44ke1YN1n34sEkHaw/j2g97/0f2MC5Hm9qMpt7/wB6G/uUw"); - a("jF8MNYxfdHfo2kn3PNu/7Qvze+gwwrZzB5vwII6/zJ99g8++MCe+vuxfK/v0lxl/P2D+H5FMQxXRG3zL2Ggh+H5qsGcofdR79z"); - a("Mzzaz5zfDsbmV5Ihf83etj5eP9c5huve/C53ut1vvSbpHHF+ypvx7E8tpZFL4aYaUfbCfLfMtWpvxi35edKNzn+/L2gbZEla7t"); - a("sqb27d9dqL+z2q52+0DdR3KqsIevTFLw2NgVuu3+7AeyfDr+RobSJ9OmUweanXUkkHdpAxXYICFKpZIHUB5x3xFMG8G1twqUyP"); - a("Io+b1rOPYyWdZFZZtQln1lo+zJVJZL9W8fe62bSteitG/NzAtvyX3/9atO8u3+0tf0z8FU1aGoylgFqv2d5vaHUw0FVIMOwPa9"); - a("dgDs5/NXb+xXvtniFhKTxCUfOQGNicNF8bkgVJtvEbpnhxA4QwmcZ7HpddG7pl7kWlXkfVK+eVAVkfNWTUUCpiJnqCLrqMjVso"); - a("iaeT+KRLx6/mEq/2zKf4bMP0SQmXGUOZPKIoD3uwHcEs/XALlwtmFxWMSsE/mz6a2pPAl/q6unUq28Ca5NI0m0CrkR2Rd81zX0"); - a("tazXURONVh6FQBQqFdWHUvlkKv9rlHe9yKYPXuvB1bgQWWiDrjwSASzr6uoxlDeF8s5CXtGB9cgqujaCEk5OM7q2pceEPzb4q2"); - a("+YbEDu6AfyyMUS2hsUtG+lGtAOJxBOk0DeoID8c6oO5DgDyFGUEE5V428GMoG/6W5sEMbbYtWhxlR6VVW/TCVaYKDhZHyqmq34"); - a("f30s/ifQN9cdUquVoHP230AvC1427OmvdxYFO4M7a3vGXZ/cE0l2Pdy8+AgvG0XnJreuFsZ/eH5RksvsH1fZIlD0SUQJf1Z2lX"); - a("GFkHZ7pPoA7ZYDVN2zjFXCqnl60wjO8Sk0vZV9T+9oyjqEsu5K1gnzlbC+ARcTI4UvGUWcDT/XOf3Y71h7CFX4KCqUwKWFqqEQ"); - a("8a2ofihXf32Gbs1jp53891d/Bs8/1686L2p/+keufbS9dobfVr9d/6NB4Yddv5dtXVnoYyhtYtSFWb2NbFSQvtRixLKFoioZuO"); - a("0qpwisrNSTPtcDu/TA83ogxSkDozmQrNeTWsHWjqYjrWL2cRF+N6Z3hS6XeF9R+J+EyBncX+mvnCKm8fDiwjlkLZ3Bms1Hj66R"); - a("+ENp7X+PSSulNPSS035AWr2RlElJHzlknUti68ylxEZZbizSIJ+kp2VT2iMyLQtpLGskE7Mo8Vbl08RjSc8hpP1lubEnrQJMvL"); - a("Q4XXC72FawvPCCUKVJR9IO5Uj6vD1KC3fqaNJvqtXP3Ovkmfuxw5Wfua3CDgbb6FLr0X4+kQYoyPlNuvan46JRtiKhziV9+3uK"); - a("XEo0IbifzslsXGJSc3HZel9e89JhMGjBFiiEvybD+oSzuQQZMEIbZsD4xKSvipxlY6mIs4XNYWQGhqpjOB9Lq1dZDKTbzs/1MT"); - a("cpZx8n6P7pT1Xaa/QTTkR4Doq+/J/uX5WPxtiH+EHhwpEZwIXjaqz3r98f1rd9CM1iH6LFk+P8X/im/Aptas1/+0/uXzXk/mUQ"); - a("G4O4Fl2VNODoR/u9byXilzmciew5XHsqnQe7E9pzUPNXJP2F9j9/iyzzR5feHnqaUab33f8j+4+Hkv3HZ/sdbwyrD1wkn7E0Co"); - a("KNcPilD0RnAQZiMONNI9/QzNnn2V3A2PXdjrg6gb1F8/6zYm7/tiU6dPtVs8Xo+LmJl65ijqUHzEM8l3GU7xqmox0x7xzdQkNF"); - a("Y7sSnTJJqbsK+wJRK2209GfWVf+P/lwg+lPKTUSutPVnydV99YctyH+oPYawrUeSR59v7VNifrKVSsbzh/T446gS7oDV9Md/34"); - a("Y8+oP92+MLtgt7GfjhkerQ0W/aFKDfH8DIpvEKC8Pfc7Wo0u8y3pOD3u38rd4Us0HfYrUg3frT6EXKJHhf/c9U/bfo//7qoO0J"); - a("LfuM9g39WezugLG1a8EsCckqMTUJ9Hevrv132kODXGrNLaqx6XpjD1sbi79/x6BRm/TCdQ7tzQ/hERMPhd862f+W+b7A8uK4ps"); - a("AHImWcdAqLerP+bpqQLnofqeQLcWOYvtrwZd+/7f5IfWw75jyD7ij/PM21e6NQymstZBeorYWlBE1knMooJ5w9kwRnZwKzgoWl"); - a("8f2VUmSb4d91nqNijnD7N5JcjQMNt2SSvcz7mR2fx97/mBPewCxl5uMX5kqG+cwF5M9LPmPMnsfGlsnrtr4v5cb3D058UDxf78"); - a("O0WPW9Mg19L/WG34Fwbt/rSTnw75ThTIt6Vwe7osfLegoHhP8C3HqNj6/ER7dS6pJabHElOjSdfOboruNPVUts7myJ0B1chr1e"); - a("/VQp+HE1av/RNQfzIFoi9Blrve2m9/h2o4TyxNSkzbufDKS3s383IbUNmYLPr9eR7KcK3WPGt4OkFGwyElK3jsKhuZuDpXNE6K"); - a("1gaalZ3y5sHW+rCp0BKcabq/DMCXo3i1Ap9CDDZmkdCsMhowoyQtPQKx1TAK0zzJWsBCFo3ih6L/qd0FrEeU/ZEchCwr6SqCGS"); - a("oeODXukwoxb02NA15r7jxLiR/QySlrsXRAy/Yhoy9VrUNiTnBy7pSq7EzOsVpcuK5h2wVGRGq26JPfw+zYELew3ssZxXQE3F2s"); - a("wKnVX6Z9GFP2cx+1mQC2myOjJ891nUQ45I4b1QpGeECufkF5YGBnA1AdgYbUsqDxeFZs5Rb+dKNE6USa0tnOMMS+ZMiVRnScVv"); - a("zU1ZsF8vE7YfiM8AYugFo5b3GL7/hTxKPe9g7I95VL6Y9LJNRhafrSp7ffEyx02f1096pyNxuuaw75+sxND7WmJ+lVxT0hhvDy"); - a("mvbn1I+mOrmk9O4aTQTpH0AhZm/198lMbqGwn6QPvfKvYNmCnj/aGUdoO0kQwlOW8nPzWG/32EbeSuXRhVszrQUf3hFutyUVzS"); - a("aQ10B4JFdxMZ1B4p642aOmovby2wGAUoTpJXzW6MBVVZ/fW/+nMWq6jXvDdxoEabzoGGJVTlKk5tWEThu0R4IYWzl3F4AYXHij"); - a("CDsEjkyabwL0S4vRfh+ns43EbhShEmezOaR+RZReEJf+LwGsqTLeIbKTwWYQW9zX5UDf+UaLpVNZMsYb38rRG/rCIhg4tUcKEK"); - a("LlDBHBXMVkF0Rg+2qSC6wkG9J6fhbonoNSpHowyGDQ//ruWrRgm6Z9HZ0am9j12nz6JdBmo8rrprkT2s45j2GKsN1nkAmlBKud"); - a("4NSn2tJOFerppThTUFNDdNlPdqqBj0bzIHpZI0m+TQJEVmRGc/ReTDZzv78NnuIDhWOCBRP9p165cZSqJ+lMMkUa/guxWC+tis"); - a("apZuh100iZSZlKpdxSntkUFiI5uAMISY872bA4NPJya/q+5WVK9P/jhIjYo9oHQyaLeOH+m/JPtIPMLy2O7BVUcvtOJnVOhuhG"); - a("3rQe043J/pTtfN6AD6VZE9RdpQp982+k1yLa+n3yHi4t31Af4Y+yaJCOrWudK1e1ey7YpGRFZkkXhxqGRzdG4jKwhJaVLtX7Rd"); - a("C3xT1Rlv0geFFlKBQgGBIoWCPGx9QSlqAw2mkkyePgBxs1rYg+mwUaYtrYRuDbEY3XROh7KNaTenq9NhcQotdW15iEXYrOKjzt"); - a("etAa3KpOJo9v++c27uzU2atJvj96O55/Wd73Xe53zfjTiP6vwZYGBSwBG3UsQmHlssO2Xcp18g7oci7jkZtxC2duEDhM0RXvkw"); - a("T0kHksYkOkllYGpcJRKAJZ3aXSV/FtYxR3nOJ3m36pcE4n76ZvAHv4rMJtXWSOepYfwblO1K2BXC2ZutnqWbESLdy2RanX+MJl"); - a("+hzg1ZX1hWiETYuLfVl1jOs9XdMco1ksBYqu5FLXeVtwkV2IyAiu/Zq40qwEJOXMsq0GBQAVnop9ezCtRHUwFg4axnFvyyu3cW"); - a("gP6hTL9D7nfxXds1uDXC5I+UlWdQMpJ8igNJ/jTdS0Yf/TZXvUl9gGyAa+NK59prOEquBWw+XgHgYzuvCSQ6tzi80o6fvGUMUy"); - a("/ApfJFKgqurRwqDbjk23yWzU4Kucu3x5WqZKRBOx1IV+2qVcAhTeWL+EThn4wbqnF556qIXH60JBqXJ6yOyWWJz9Je8PkUN5jl"); - a("t655Ty2JDpedy49Rk3JfDUuMqs/ZZxnkKSrd8ZjWLuTwNwFMYSmP1ktZHRBvRQG9mst48WSw+btMAiLwI6A9s5aPYlWF356mU/"); - a("ifpWmimLYyoiiG3xRNFA+sii0KqXwbqPev4dFQp2rVNEqGa9sGH6BSVm4oaWkxeHvAYmwr1Ur+E720lUolE0n+dI2FFAnm7bqN"); - a("tx8q7V4UX4WAjm3ftejYtsqise3ktRHZ9lZxNLZdv7IvbFtezdSfb4lCva/zlSEG2sVc6eCTQDVcieTs6Smk+jM0Dsh4smdQxq"); - a("ghhB8B6kdlIaxYPUTHisVDNFZ0XhORFa/eEI0Vy1bEZgXS16q6UDgkhi7sGcy/ZP/gpTjV/sGb2uKyCV4QlUNrwuwfwMOqxkMx"); - a("o3rwOZ7Q0DdmPXHIiVCtCCWLUJ0IpSHE3C40cJvhLAqBo/To4XT16OF0I+QfLg03Bm0x3DKNuyuKQxLhYa3nhNdmIIEOO/enam"); - a("K44eqIYlj4nWhiePma2GIACnGqGMo/jzZ25aeGjt03PxKcN7IObaYt5JAR3ClyiPede8nOZxL5+90iZpbPCiWg8kgyUdJ0mfRL"); - a("TuKCao68vZbNmzjaKWaX+dbZlqpbOGYehZJdJXKeym+oJQuu4Ha2jb4ZoEyV7JvOqfxNJo2vKxZtYqwEJHHH+UaKvYU/hU25Fy"); - a("kRjWYnQmrWfE63bE5P0YT25PKIQnvg+mhCy7g6ttDUBHL5DQcMIekFscasW/mKm26+//ZAsP6urYL1y42paxOQWixTHeZgqmZb"); - a("jaVh67ZsnolU1txJ+NB4aMePkU2fDOQcdgEomV9AvYE4XvFxn9W1jPggCnv46XrnQXHPmUVAuWCrGHykL1mM2Zi+kd5cHF7OB0"); - a("5cEMrIOsPenSdTpNSDsNLKQyjWeadksfAIzbldmZFqemEaalqDIv6Fvqhg5yOPzMCIMEFqDM30UzCYZoIH5yAM6igaj8sk/bTM"); - a("Qp8XpDoT+hFaAV4zLiJcji2Tb+8YgVDLBXcma5o5bGlEzfz3qmiauXFZbM2UmInzlhP46H2M8w8QXJYMmR3QKlX3AI4vgRBlng"); - a("LkwfGLAW1e+ttWMXfxzTZ0uUdN3JDNFg7qEJLv3NRNDu0hW9lV2qRM12/dj/4HH7zl7eMOSFL05gm5K+j+BDH6VvL5AHD/Eq9o"); - a("JWeBMgY7OwTspQArrMxhF8jOaWJfsobgKIGfBqh01ZEkTU7fXxxRTstWRpPTP5bElpOR05tQkU9jEE07r0Q3pSf++g8l8c3gAv"); - a("yxTEsKHQ8sD3Bvj7f9kXj62f2cmoFUv4VJKi7IoggGL37yuTDuF8rV+75EjRPfWRSRE1esiMaJg4v7pLGZKomr/DHWr7MSQ2n2"); - a("bxU93v1V7/dIsseGkL0/mKGjR5qu73JvyIqTEdpkbQtDmMOxrsHBqVhzgsaC1VdGZMHl10Zjwb5FsVmw5X7ULThwx3tR2+ysBO"); - a("O8lPfk3n+A+2T6xjxgKOO8rRUh2ox+bRPsorPv9RezaKwSRT67TlhP+SCeh+BWMUDTD98boB7BHpxZ7DbOLL643zCz2HsGzfnE"); - a("XaL9PRQyfbCr0wd32PThR/rpwxrqbQ3Th5QB0aYPJ5JCpg/jVorpwzgJSCIIfhnnD/aQ+YNdPzD+3awJfJ0zosCvujqawNu/1a"); - a("/5w+tZ/Z0/XGAWWEeeA6Src4BUczhx3YAdHO79Jv1wb3KGDfcvsz+82OP91gnoe991/lfj/R+c/RnvD04ke+HO2OP9Uuf/fbz/"); - a("NuHid/Q+3nvjNE2auDCiJqUuj6ZJWx39G+8PfRCt7+Ch48BH/JKiUrMMH/t86JYY5z8bYqRX6tLdndeQu8/tKEP/KNzZchu1Sy"); - a("38kSE84HZ9OKMzOzM0/JEh/PgEfTitc83K0HD2qtDwRwjr6Vc+vCuKf0k+n+pQznfzqsm7ygz7XuXsYX0PTKAjqhV7hko89ubC"); - a("DZSGvR88UELHmF/uIbPH/tUlvqLiZrwLJYcQhxXcioSBwMaOBIB+/wW0xELvdHNJYd4nrgm4ki0TDrzAryTMyejo6Q30E0vRNr"); - a("J8Jda8f92avMZWU5pl8ietsdaUZQUK806VPyouzKUX9YS/CAy/bzJkTdT7Jp4jutvj+7nEmyhB4zI648Yb2Tgka93vuFNpN1w4"); - a("CffPVRLr/QbqLPQ0h1V7k6wWzthQ8+O6mh+WNRvfQBjlYb1avWni9DTbPK+wPcXLAdWdj+HvR1QZrDPhXqFqjm59oRmVtHCMbP"); - a("QQGO6+m8oW2HJPSLsQVvffTJadA6yW3ybdOrFg85euEQR4Mq8wh8GphL2mzBwo2El5Ck3d1TiIbjHZ8o7zeaTghPV6TURSP627"); - a("yEIBeqC3b0IPlBd83amdj+eyS/OqfeIBMo7K5Qvl27rteW87LI5mh8XZxP7xQM14+9QvcHuyfAC/+/QPwffGAbyvg7ekr3raQv"); - a("xzCi7l7cdxyTH/AOWPZ/eQW8F2eZcG98OKPK1csRMMKfIcRsXCj4Yzr9FpcRx2WpxtucecVa9uXORfUOLbYirYcn7B7ObSmbCC"); - a("1G51+79jdX89+taE6fBljpi3gzFJBZWfIA5ZXcN5H6rRZHfvxf8mU1HeG/wOFr8bLXyUddeH9Hdql3+8c2qrs6ohSBq+Q0gDUR"); - a("H6v0D6YCsJdy+QLx9QL7kClAfUy6KqJyE1/wcFfcxP/NlnV32LWN1fmcqTcxo6t5F+QQ1snv1W92lcqr+bL4sd81lBH9SmNKuo"); - a("+Jhl56pRAbef2LE+1f31OHrs7s9EyHJfA3TTb8fdwbHIV1k2KjDTNcyGA6uLbHmvWx5tAGSaA2VrQHLcXw9aP9ztPysSMBRMRX"); - a("5b3huWe+4U8yfJKKP/i0JDe438fh/vTRT4N+wKXgkPtt+qgCtxD/EInZ7swFZg7bSmsGZNwFb1vuXuDdSGXtTscVB74vsV6OZQ"); - a("pqj4ZfvU/eS5wf2uBQ2ivBFZtqQmVzvSAvbGTxKoKR30X0x36nFo1WFBh7kCWSw7h5vVq3iDeLaG42ZvPGOwT8mw9XBhXHVztX"); - a("AnkhQIfYjv8IIg7zpDb2K4/2mwX/AGuSHaxS+IsmkvwtNc4i3vLsGbyvm6F+zX8XX+FO06//xD2h6r5RI09yuWqnusf5N7rO0n"); - a("0Aa7wg0FaO8DPUfQUTpqUItA4DHsI5R46QVz1asWW5P2sM5433BetPutTFvk53R/QUFPu7sbmnxaPP0oTac/q/jtB/kB7fwn/q"); - a("hvGTRrPEbyE17WyE8jE7sLlxhtMb0OX1rsLTMWrO59GqyX8gErsNgIq+Y4zSyh77FgHT+gwdpAsJ4Jg2U9rhp4eTzcLkak8a9e"); - a("6SmQ/uf+xR81lSio/Pha/q7m8w+RwaccLTBIxmjfr0fY9+sR9v16hH2/HmHfj0MHQj3XuXJ0JvzqxG8V1S8/qXr9Eai8eX+wwG"); - a("AwRHq462De8O11zVpgZ0Wqup7wp6jrCmTlS3b5yxsqUghUZVlaYJLrQ3wi0ta+MceBq0LSgKsDP9RYmQdpoA4RPoyksuWutkKv"); - a("fbIk3BCYUR8J4EP8WqtfmjvJsmkYhDh9kmXz14PwO770SrogcHu8uChwXoL4/Yh+kyybr04S4XsSxQWChQPxiydLgSQRbjGJcA"); - a("XiO58fRPrMBpzY/m4KXzpaJO/ptfJ0rdhhTg6ag/LpzEH9LVMIHp2Salj0c7uIYohKwlVQ8hYURBAPbAVZN0eqw1uIuaA3cjWr"); - a("w6vxhlSzjXZSi+GK6vmzZB0poo4r+1zH6fFhdWSH1JFH+8Le5Ts8bafaLUVtnuU77MVshLdOUyIyPLi8luIqZ88onQYp1z6fg7"); - a("pY7rVLucf2OZDMYCH5Gy8Df+idtB1ZyVMXZ1ebzW1cAt9sArJO7j1WLkaZ+IG8pg7KbcygcHq9vYltSDit+ZfraXUuQxWtBrHV"); - a("D+yn2GaFV3N0gb6aD2nSf6NebMv6W8eRcWF13BJSxybUUWKUm207KqjTzN9MbSMDaHgfoknr9OJwae28BGzx0Btl4kuqxHl7Mu"); - a("O8IGg611OaNSUCAWmFcH6Dm51qDRnZ+EAN3HPmzwXomQBN3IiXkBcki62uEYiPDh3XSOJCwdMNTeVfk3VVtOejigNi71WPf8cA"); - a("xv9y3Iigk/he0bfusgBjKKFKwNV66HcQ9HVJoQRUATSfDSE+KnjgnxwGf5Ye/mjAx95xSjj+mQL/+X3iP/SEYT88SQd79xzg/n"); - a("RiKO77UBMfKSb2gfnJetgVetg3zGG8lyaG4b02qX98j1f58k6WDr6ZcP9XQijugyXubyX0ne8a/D16+L/JY/x/lqDiH6ykNpHx"); - a("t/e5ggS1gtX6Cqx5IOBCSYDKG0eiIOBsxMfkjxH8nok68P+czfgfiVfxD7pZVxIY/3P0MHlLQjWInT0PmDWbRC9olqX+HKGUZa"); - a("eu1I+olE+WSpKlymLV9QSVWiFLDVLbvyh1UXgpOceqEgc29K0CWkKjw1kS0EAJ6Ex8OCDLczpAjqVhgAYu1o0BFgno2fgYdBxZ"); - a("hFL3yVIpstRGUersiKWUgllkm4zyD5X5vyXyj++tFj4f959HCjNYFhkjioyJXMWJMqNNdOrvoVgwPFw6jLx/5NtqywfxwIAEsm"); - a("nrrAWoelIh0acq1y4AZXebhJ4mymp3QC3CqrTWp4lBnIejCSP1ltbr2D4gjfpWgNLmXSvNjP9YPTDWb1511qbxPhtyB0fKc0WB"); - a("cRFaxGwqMZ5KTAeuwfGb9tCj5WbqwYeN07GDYauFpQSVhCEjwkhIIRI2Sq8JvFswkPxj2d0I0VyG1hSN75rFWuPIP+15p29Pss"); - a("PVT9lbajXlA5ANDuN8VNt2XW3b08Nq23Yp5D0M7ZcisFb5+1IsXZIv6gm4y3cExClP6ESsGKN8XpulZgfbS/5VnOtKijJO1vDY"); - a("TCeoVq1etSefdGn4JOBpVOt3xgb343Bw/7hEnfkvD4K7AeBK5FoAaRz3LREnjXh28G1sdXGw9SdfyNPUDXzpBmslYcKXf7BWEi"); - a("Z8DQY5xXqa7b7lHBPmz9wbagMui+rHC2n2Vv9gNVhLQTXQSrtWiGjTIvLtSsUQsgMPISfY84cnl06ykWFymWNR9y42S1JFz49l"); - a("dWvbTH7zM6bqdoM9HCN+tAvfUlBLszsu2VKwQ/e9nb4xHE+hXwm5AGxS6yUz95VlZqzEEp6Z5M+DwzuFDCbQb3ec+N0uf6fgN6"); - a("QcrBmaA4ppGEwqNFl2Nunx1JvNs4ZUNNM1XwIpUFFBLuUJkwTu3jAFB9MSe1QpjQPRg0COxGGDZ9524669Vp/yHT0k9LzhpXeo"); - a("0MVbs97ez6DPS80yoj+D3NQnZBH2zQW/MvG3Sok/VZfEIJIJanR+zClNFRz4PXUKBsIFn0Lzu5ZqfMoIybKLlzvWT4I6VFwwRS"); - a("PfM69WT3eoEAw8MNij/VZOtP16tDendA4jvbsQbpYqJ9ChkESP3te1+4eVaH7q1MpDMuUvaqhIow5iS2FaYG7e7Qlzc249bMyx"); - a("caQWA7p5vCk6Ie06Gjl2rqVqlkmrUjTkIVrOa9r8o3ShWh1utUbc2iuS7PnXKJHq33dcX3/NUhPobdNl68LxhBhGEszoBcWeJz"); - a("7oEZuSBr8RtHF2uf8mX8Qyzm4afTzWKf5VEdORSBsm3jjYcPDnaTC4y3mPMmToMmSEoz/oOLWFELl0euNCJNgOBnSU/1CNwdWa"); - a("DvzSfk0wCkE9aNaeRWJQUMi/uNiXHFLAMd1ApQRnpbAdedvEcIw2+LG/zltFrLKyF79BGDLRNtiM51Wt2Korx9aj7BwblTYSTK"); - a("/7cdLL9/dnaCre9/019p/RI/xn8M+LlZylppZ/+DIUWYqweV722nJwOP0gRXhds/XO70FhwZaC+GrbSZAKfZgmbOokSgs6MwbK"); - a("j5OD5McsTOI6t46gfahCTxd2X9dnIt41ht9lnwmUJuHvsI2Z1heHCZsRI0p8wXjLxmTri5Y4raxl07/jJNyH5Rbut+DPzlL1gc"); - a("BtW628XVI0HYMsjSTEWnbbwrfEaCXNB1yLBlhZbkUtDbzT8EuIvfNrROhgJPYGY0Uc3pk0CDhJztx9KpBlBGSnuA8hU2UZ3rkN"); - a("COOvJxGWJehhz80TSb1YBmKbg9IVz0VaLO90PIglhP+6Ej2NN02LQWNyCI3wtwOt8Y8CDAFYTH2FXcKprPb3UzR7dcosfQPgRD"); - a("BN76V++1zyUt9CVznODEfFApTSiYVqUfFrW5wn+ZTDWNRGRW9CUZQMWLZWoOSamtvNOK07B7z6/oFBWgl7cTMMOZsDpla3koO3"); - a("1s0mLS24p4NMZKunWV+shXxeiVEPc/0m+6l2TxPOrhFffARn1ziY4Umjm0xYf33asvUOfFCk+2OTxn/lFqwoq45Z7u4ExjjxKa"); - a("YTn7JLd3OLBi4qvV/lEb2vSJbhhRSIp6M/65ZlaYHqZckBK85MrXknKw6APrXQS3l6Jln5jEmjAJgK7MdSWf9Iwv21EFEpbnAw"); - a("rECOpYoVN5xLhGDefsvWN0OTa6ymLWDwHNtJy+ZGGsd/4Sg+UHRKtRhUk77KbsIPK6qyaCCqhFIK9qgd0MfnEyL87SxuKUI7lJ"); - a("xQGoCiSu/R2cwk4v/Uw0FWDQJZjuImx9S9YD0x7CxmmFro0dl6Jrm/DpRmqkmbQ+C5O03NMPidA30OJ93zD3+Cz/2JCcZ6hofo"); - a("FnOs9IOQOMkNVzwXKB3u7jG5srUclXNmuDIkDuDOanLd/d0paOr1Z5EG/UOnPedfjOhfIxrzBqN2SRnuQUuBgQqD5iomgdjBsH"); - a("gVuXERof1IQAMPIrWEaa4xCKEnMJTKRyn/OaRlY2ldFzHPSOQxApVIvkL3vf6axv3cN9BXb5vcv776xGwwORDaV187uZ99dS0B"); - a("eb6ffXXT2Eh99VvnGfrq43PB3u+E9NW7JvWvrx44m/rqsXL+Gd5f/xjpeg1Ff63vvme4snTBDeaZruFqI7oMI8uW5SerF5n9E/"); - a("V5TDidV/OMUfOYfJG78ocuDo4Cz+CRDjoss5enC+7uhI2pvFkn5w8Ru6UWOksp5nT6qplnIlMs91OYwbC77qdIBMU1FNR3Th/N"); - a("1zqnZxIidU7OmfrOSe2YskngSUA2Qr86bVZPb4hilMks4pZnlmXkQc0pauo7Bwu7DU8SlqYg7lsfQXykjvonNBkqp7Gk807xdk"); - a("llGyb5DFeyzT9STRgKfg7VEtS2dVxtW/fItnUFt62/G9qWdWKveucQAhB6R/ahIfTOw4bypolR25WEgXYFAMsJgA8AZGwv7Sn3"); - a("VWpKG0ZHakr3TTc0pV/noSldBj7pcFp3Tp9p2nshsvpCGoprVITmdC7vyUSe8Tx1QVDXW1K0Gc+pXB6M0EwwekGeT6T0TZ4WyN"); - a("PyX8vzRxP6THvzBRHkmTuh7/KsuqAf8qzNiCTPveca5Hl4Vrg8t2X2mabPz++bPFdc0Ls8386V8izNUGU5LUc/5/CP1vpFbQcQ"); - a("ox9KWd2fxvtX8j06QwtXx/AZ/LyjAJ1uXOlM+rLsXGTW9U7nnRupd/IAYR8Bt7oDporHOq8j69qaLg2TgBI8bapCjdY6CIu+gw"); - a("Bv+6lTY8f3mf/rcyPo1Fvj+q5Tubn90KllIyLp1A+nGHSq/KJwnSoa12eaHskx6tQMy8+bXKMjqFU8sEc9kfXqJ+eF6dWRGQa9"); - a("Ch9jMPgF9Wq+1Kuo+vNpdiT9KcrV68/uSBXhCt/GUZuPlabLMrQ/sYlPV0Gub/MxSxUdLPH6HnGlI2CxYg7+r6bLJo/RRRk6M1"); - a("X55PByTrZmp0pon3IruN75myQeE5HKz5g0TLR8CynfHcF8wjRVVZt4oTV5Lr/Qag+dPHju7xBPtiiXBkoOxvszAXAq4ac1XQ3i"); - a("0XwNolZdNHh3ZPK54muJkiEFprkWy09bEzWrJEpcqJ9PVFMjqqkLraYewRCkGgRSFSJ3q8CizoAFb7CfRMPks2UBf50o0RYKv9"); - a("0APypdvyGIJkCMwPch+f3n+xKC93SCAZ4Ro3ZRwZPwDx4DPzPB+w7BQ/5LRP46I7h6HQM0fp43JyY/d5DaxSeo/ByLEmHo9k9P"); - a("lowj+gHcF8IyydEX8vqrd+ZxRH84PKPIGfx1eTH5+eexdF4cL/g5Q+SvMwq4XoB7ajYnN+jqisHPZQT9GbPKz5dn96r/eIcqoR"); - a("srj6r/Z5P+S/h6CdUJmP/GTnmv+nDZ7Jj68HOC/4WJ4asANOiPSOhGjCX8d2bFhH8hwf9Zb/Av1eAj5JvVf/4cHQP4F5h65c/c"); - a("kBoOXdxf+ZYS/CNxqnyfjAIg8RYkRmn7916s19UGQ228z56E2vxrkdd2cTRWJCaJ5MhtYmrseh4ZTX07Hfx0w7Z76ZzexsoJoQ"); - a("vqobphcyHgqLbZrleiHtSyr1X+EZvu3hcrDae3hvc3D8qjgCO2nBPy7Kw7wSXfByQ+b9YdtRUUbNmAVekFuBOuvqP4R1mJo+YG"); - a("eS+9CHZPHUim7DiHLzhp3ZWJ4mQh3I5zh0kXYSOr4+SZALmXsiNDi5Y+RWlBwnzsxE4OWH6LeZTVct/fbh2AuxN5H1Y8Dtptm0"); - a("+Ujg/iVzocky79TOl1zFJ8hdUKn1Ks1R6LGO/jt9KFX+/yHJwZzabpGhUWXqYcZJa0kZzaKWd/pJ2JGO57s81CWZ4MP3UTkIRI"); - a("QF77UGW73r9BQTXuibcQUHoHM5mmjpd+Do6Y2v0TcBYh+Fgw58J8V5K9JiHfn0pvYSrn5se5Ps5tMPg2CD3fpe3AZ9CdGw8rtf"); - a("vvB9xNCezvi/xjsTlo4OwZbXeDqQnMWuNherh/Bok82RnPrcyPK51OFJR9RjK9xQQ7t/cG2NcdLWPOcmDTXPhsSIElSLb3362R"); - a("YMQfjenZbDPee6h3RBuVox+ekeRE848B/x140QJXeyQKAS59DnoiBzk2w6sIuefympXehAEFe1VALLHEPbDPixAFZRLHanQhRj"); - a("NRb3zvBvkXevbhdl6OvXifswa7wUBTs+4oxW30NzE0hr1i6CTec+0nsNobguJXi0xtUpf0dnsIV2UlQOLX8lz6r0+b6HKU0olF"); - a("CncPldHtJw9um2yG/8G3zmgo6fBBeh2lf5/T3ZfcgUCcK1O9479qLHunXo4f6WfWk3gNsnDFv+CKE+0c5soN/qQuxpdRmuH45V"); - a("D9X7+p4Wc8T0eeVMrTwnm8gz+dhMBDlxJDmugghfZ+W2wnA/jntp00AaWXkQM3bE7avak4ck7fzUEbggl7g+9CwcqrvjLFwULg"); - a("EmR5WJ/Fg567/GRc6VQkbOIEJxISb8cnO/xN2I+E7yIkXkmYscZgl4W72H/UXyGX/OtOWu65WbwhgivExOPdmkc43wjmqQc/wv"); - a("kF1QfwGQBIrShZ3Qyg/0hTAPnnc038BAPFP8syx0kF/xI8AD/eQYyyBUdvVBpjythDiEB8C8WvRzyw/StHwUfT8CZU9SRCQrPS"); - a("WJLrxEjXrR0kR5FXJYFdeKxXffo2pY85JvTpnKwQfXp2FNP+5CidPsVlhepT10SDPhnqp/zKgTd6rb9jIun7G6L+5yeG1H90JN"); - a("f/8khd/Q9ODK2/Okb9lQR/oaF+4/0P5LuG8g2jfFI5ae/OdhJC9dhOQqbd55iBS+pe5bKxcXHQt8T170JoQ6nUi/lSuctmwgkd"); - a("l1X9bXeRfp9AUXIOSPqtfHs+2X3uqngP8NVrJ+Q3b05QZXafE1SZprmy1zgXQDVxc3ut196bAUm2brCMKmpJOMx1dyeu/4joR5"); - a("zivStk3OHySPvBUAz4n0KbiH7K59bn0/7lNjT1Ot5U7bNsvhFx9Xq6JT4vTSDFvfCwPe8L14CC50x+a4mP8HoHnGufQPXhTKmq"); - a("oSz7eaZF+O9N3E2livcXeS9spYJJVDDZBw++HQU5gYJq4xCl2UNXJ0oOvL11Y+ybhHt29J5sCt3/akU+MptyF37VgaizlJj8Cb"); - a("vB2xvM+QjnLB2k/J0T4v2LlTtPh2a5U81yw2mRZaYy5UxolmvULJYzIguMLl+gVuzFr2ZcXa+v6ZnoY9jd4JqrIj+eCtdfl8I6"); - a("7GlzeJo0f8NwIawOfpnSCnpIf+WJF32IPRMypOgiRDeavLggu9ee11g2EE9DE/Em0x+PZ5v0unOqo1gWWZRJZon5fe0zJn+K4n"); - a("j3DHoz2jYqqH5bnQdnBwKQFr34Y1davfsLeGpQH/zhQbiGN9WCNITIAYj1Ljw2pk3EQ9LrcSD9siSokf7Rl3xrXQG8en9qHel9"); - a("+aC++ytjPG2elxyeV/BYLQa2zuKDQWzvTQzDNu8Ly5Vv45Uz5mlNmKexIZkb0EFJHxlXMx1h3spi0/N29v/Ibw/uvkpu41aUwP"); - a("/1hMjcvisCt43vc7O/Sf4ydpK7QezyE3rl7jBwt+hwh8pg0+tnAv3mr9eaFsXf46EBfZhfRiWFwazZHQg6yBiTLceF+wyzycj+"); - a("FXj96kqXrgK6gm5+uoRv6644YYIfdEsL5fJdKU+G3vnUFEfN3Ub79dISsfAvRrnxI0CUWoX36zmUl7IZ/f50C78/ipYu/P5UwO"); - a("WPsuIKEESxhqE8nB4F9HTRrTSqVfguUhisSpTCvosU0FSm0tQRQhN3YU5FpUfR09Mh6VEEPV2CHoWyGenpEvR0aOmCnj89DXq2"); - a("FAl6lFj0SH9MffanVRvqjwmZQI5nXpr46vLM48JYAMMxMVIuqcPat2z8DNqS3Zg6Y9ZXCJ2Fk5+KVOEqKznOPwiwxbfBbVaB4E"); - a("NemCOn6H6c/lRH9NsNfpzC18Nea4aH9iG8RcML0YDUOV9mCs/5RuGHpGJYkkT0N5MQw79ROdqZqx39Rwfe9ytyUSqdBstW56hZ"); - a("1+1AezoHsPDLnt1O08nEBGwOYe3xxnETt0Jayo3DvpTw3hXeSvECQ+kZHfbamD1KLJjCU7wubcn7/vmGnOxf04EYJ8U4KcY7gv"); - a("ul7x5V+6VAj+obCXR5QZcXdHnXyQFWv3/ELNKTW+T5FxF5SbyByLmjiKL2SF0PkCWazwVN+AQn2mCPiajMGK1y3eCsnQq3UcAY"); - a("Nu53iI5PXylrq2VTIz5n0GfpEj6tLKfw7K+QVPWY9h4/XkycuybzToLOxZ1Sk0tsjW+O+5T+Fpj+yj/mPZ13q+/vzaLss+FlF6"); - a("tlA6Jsj38F6tOVqQwvM1Yt0yPKBPyTZRk5uXeEl+mkS+nqdo42/va5vy4N6a+pT7XWK2f4/PLQaWEwDi3a0EXPE91wflgXDbhR"); - a("++hjf0Sb3lkYuY+W7VltwHuSuQHXJ/OiLWIDXlOTsMTdYG7qTT++IX50Cn7s/uob58eBJ8CPx+b3iR+WgcyP5IHR+dHUx/ai1/"); - a("2TE8P06t6ZkXU/ZOew0NNwuIM/w+cj6K0OF3qaHJ79uPN9+L28JsuV7ZgmJWOapLz/yhkxJeoOpbioGJLaC9/Zl7FNqG6REAs+"); - a("BmJs0x3jRwAKSjbZD39dmNdkRYViTqaU9lJfPXUOvfqPXd1z5puYb516VptvPTE2+nyr//q6IUxfoak3YjyQmipdKsE63jc1zx"); - a("r5e+js5wVGnQ1vvwNE+x1g1Nfe+L11TIz1RCuvyRuDLHcW76OZOQYT9weoJH0btttCh8HDHXLMHDpBjJmagtdNYwUPWcrSsDke"); - a("pnGcFMkmnSjSO4xHzvNePhP0IztfiE+OlWH25IAk4QaEoZBFpsaiw1/RDPit9wnLT0+ZVFZ42kKaTxxWzEb9j95+5VhyYWZY+z"); - a("18rmH86cWf/Adow9iPPtyR12q5stFe3Oow7fNPk/svQNpsbVSSbdWmIizpHXn7bksu3GJGEHcdhU0qMyJvf03yQcITDbKBH3N2"); - a("gpRWkFKY14AG2YAKimpSi/xZ4hzJ02az7EyzNv4zGb8FJpuprcTmYbAAz6Df1LO4/ulo7fWp099Ie738aa29fj0qSns16Ht2Eu"); - a("t7ZlKf9D29cpxJ1PdRdpT9mVj2pcLnnzOyAVi54WOcTHrexZEH7QzoDy8EaZ85PYqyDmcJ0oPXetVB5LWxjT9FpqdurKTn1Pz+"); - a("0xORFjyQcA0GqujQln51JuC/xge3yLI9zxsr2zNqlBr/DvjIU9GviESlch+dVQkx/pzSr+xk4/zkqRicAUtCPbDlRCBcEB27/T"); - a("17dvj8L9swl4v8ftVrNuz9KyYcjPkvFPux/Kah1brl7IEO71B8ObyjnRR2DDLNr05NkcnVqwaarJgGoYlVvIwK/qf5z0uG8YS4"); - a("Xb2dKLoH7j+Vc3FmIIpuag06v6umT+VmJPFgU9kuqxehN2UI9/SwAvizCeuEwh8EoTxIRW88BFmFDE4FYgDKCxucoo9Nd/4GOF"); - a("41J9LYZFzPaE6XB+udLqOMl8lt+B7h6GXSljG+Xsa1FmzYI/f1cWTrgSm1HzRleLqhD03skNOf5nN6jju96+Ic2L4duARaWXXC"); - a("ddwdsJS9QsepQ+hUfWDQbXPktU/E8a8cDHN1A3HspgLNdn5vefAMLSLhffBm9qLfouJfAPxxWurApqsblqg2zlJL3I4SMB7Xna"); - a("6dTZGjeiWQYHRnsQ43G4P8aINXGO/VqTgPg1P8CW2uqwmqazCSScCKFVB9Ko926Hh3DfjlHyr0WY27EXGyIBr3xSiKa6W3v6s4"); - a("8OVN/HJ9XJzp8lSx56ugPeLXZZi5RezfmTc5ryo3mYmSZrvqwd97FdBuWE9ol5Z4Ex/A19QFqUrPAdS7EUQMV4lYhRjlI/yBbF"); - a("V22REEH1NV2hTwQeXJv9f2CAhzZDeaHy/m/OeCwS3DNQZPjAeDH4k3Mjj1UeLTdf2iD5KuMjF9VLOl6o/Ip+L/wn7gPxIIs4nh"); - a("Ep+Sgm81sQKJ/M5WCuHR78o7pz8junbx65BpiMNVXne3+dZpIKFQR8K3zWTv32wkoegR6IhaxVyq/xf4w8xj4V7LtcL0NYH/AQ"); - a("LuBakmA82x5Hl/nCrP0qUsy/dvYVkucP8w1cT8L1ExeGgf65JrrBJHdf2Vu6LbgjQ/sZZpltKqoUGPZdU0TCP0dhMI/dxkJPTb"); - a("24yyCutP0NTovLjHxAe6g7yDpx/DXKDNP4DuD+HTOxtrFE+3mOKl5p4WE6TM3P3iIwsfjUpOrpyMWD1HrY3HE6y5R63u9y2wgc"); - a("sdjf9s4G/12pLzE3ffjDPOBPQFPupsFAtIR0+DN1P55WmuN/FpqfqFuH9SekWweB7eZcnyG6l8ZlGNM9mbfgO+lW2tWCY15190"); - a("EyUMsHrK0/wWAfuZVobtai7x0c/8Xew5xukkS+t/o4zWFlsqsRrn2TcT6rZkpwflHkY524T3r6hxvJfh8HysrES4yGNjm+4exd"); - a("D1af6Pj9CFqREt89NYKa9qpV6hDa7lPPOTfZofY7395mR7C2uQUjRZO3nU0nEwlSZH/DRyflcHoxI5DTJf5PGS94cdfdofLtX2"); - a("h6Vtaih+R1aP6gEimSck93SdCYTuDF8mxrrZYTvDUfeFf/Ewxrj1Fxj3hY3z4TblkU8N8+Hw/WKH9N+v2iyMvW/885B9Yx9t2o"); - a("LYLyb2sOMjB5YSRCzX/8NGnki3MTRwQakhhNheG4p+I3vE3ofAi5LzDXvE/6s8N0SSZ9pEvTwBxpumvPCJUaQFQnB5YSKNvtff"); - a("9EvQ8UiuQaYGeR468X+Q54MR5TnxHCFPSSiJlVF4eI9BpM+fkCJdHCZSq+DInDCRlkSX6XMPghf35RhlatTvDmX38cj82JFVJ+"); - a("wVtAlDBe38Iy23dkhjAyn2Gr6ArtTjAaX8xsybAd/0JcSKusUtnMS3B9PVT2LG/GT8QrlJaz7TLkP/rksyYRWri6jXy/Vq2Ov7"); - a("q0pyYzoI0lA+BqM12yvafU0QQcWLPIeEDWGn52DlJXOvBgyy5ZI4rFuMMYO9gzPeozEG10b8U+01Y4ci5M9Ejs9OBUehkneCo1"); - a("AxPpEVwxAGvSGgC903+mVMye8tB9cPzuUFobg5uIfniVjkiAy3UIYnkMFaPwdoiMhjlYh8AJEOstdVhoCHAwAx+Po2ej8xjl3H"); - a("X1/keavIOwQXQAF4QVaPHvBIArwExYDSb1NNErKJYuci1uldkCyiPqGoqbKys6iysxHoJA0WNaZvpvmmViMArggCrKMCftywCe"); - a("Kxe2IIHvdQhv35jEd+sNiPKfbZfFHpr+5E4HEE/JMF+AuC+RZTvrtlvlLKV4EAcqn8DKS/vRyIavWNpxIrZIl5VMKJQFVg42JY"); - a("MAhUfVlWJJcZBbTOIEh4EO8d/pKE5guFdpgApEpoJ+9AIIBlUF5PRRPGWmD6dApJ/g3kfJxy/hOJNAXaTzn/joAPKse3ZPVXap"); - a("+X6xyyP+Bpc36/IcNRM/incHt3uWVnqslR3Agz564RWtIPkLSwJsHURGVOjytrMVz4Yf3mKzbqep/NJpeRrY/SITP2k3oP4G8/"); - a("fN9Neitgiut8CTjh+136pqU12aeQvidGO9grpz1ZXA0ecpoazEud9yEE/7IE2my5OxUhTGlLbya4t/E50I/V52tl6kcFfwyEyz"); - a("f+WG7ZXKUmVasf/yHuusOjKoL4vcu95JIQLpBEo4LGDoKaKGpE0BwkkkBi7/WzECsWSLAFOIloHkf07FhQbFiwYCGCSkzRJEiL"); - a("IIrYAgK+4yxBWgrh/M3s3r13zxyI+un9cW9md3a2zc622V1vCLg/BDwYAh4JATTe8j/JOg5lvvJWYNOAAS4YC9gj4AWlgEsE3O"); - a("sWwNcKeD3RXCLg+YADZ4u6O/JWwCMEXAv6wEkCPpfcjxawRvDBAp5B8N6y3glOFPCn4Omjtc29QmPdd79EuX3ZxuUWOD681YSD"); - a("bZlhK1s2r0Xow5HqULi7KNzEdg7nBnU6NM6kzWGNk7o2rHF6ASymsRlb3/5OU+K9HpJDtGwpZxb70VNdSEGtfrTFjNSi/1fp1R"); - a("ui9Yc+sV9bClNo6pNY5WPmfQZnkLJA02nZF2irmZnSUzyszAoetk/y9muMmtVfxxoZX70BGZ+7jTqUhsB+8DyzxPBcQJ7ztrKn"); - a("dlk6Jg/tPHmg3kLPeFAuJZ4QDO27ljaL7iGafc36riBbcK1cb8mo9f5reqoVWZ6JJYJXkO05WFKbF75+vshYUjOMurTV6OyY+e"); - a("0YlPHIhA4ipNlvkqugaxBnwAU6wkCrnwE6seZl3BPeBIY1VFK0Lw64mQ3kJ8iy5QKsQRlVjjHKKH4Nnf/gMqot0lqKpqwrUYtw"); - a("X5ivUFtLiLMAxupOyKv+2wOywDZwd4rceZE7L3LnRe4M+0UI2ZaFbNK5BH0esCrIM7BlZ5DiUM+41Yi85Cu6f2ILe3s6FVtDTj"); - a("qRJN1ikFxHkr1lM5OMkSTgCZEll1HgCWxQJ2N9CWtUe7cjrFVYDXlG00gVjBSYK8YD1F+kfXLEazjbybkSzmYmcj6krzyUjXz5"); - a("EQqn3kiYNx19uHkqJO0XZYx9l1/NSWvEh36BVLn+Ms5JWn/LKaT96RmM0p/N712waqZKzrRJ60aPzbjGVms+lKSnVnccWAN98A"); - a("B453kdnvK1MSiSW4F5U32YadF7IUnDWhRa8NNHviFFN3uX/Fmo7l7L7Dc6DlwOhplgmOt1hDm2/sAcPwBJjb75dYOt8TP4Z4QV"); - a("l54NUmilWDKVDKhsXSpDdk/fNnvX9KvyMI+kQyDU+R7iBaBvRRANTIYScWlvfetrzCK+EQRyVA1fo2Yt+m4Wgls8LfXJTVm+GH"); - a("E7Py/WWuoCrnsRNB6vvdUY01nUZCR/1MIhc0wxRLdPtO3h+xZLta9gQlcEHqEl+1xtrdaOgXEREvrWmyiVemz5Dsa9OnTBDEcy"); - a("34EVpk5lYiotxbu1rzmEXs60PuhJmj1SNhUkJpAIB1o2OGeNHGCP2uXuhFyfz62o54GRW1yzth0iiH292KlwCtgrVvFBW/NqfN"); - a("T935auXd/3N0HaOC4K5z8rmLWNxj4NitZK73VuUzAZKqtrs5VmCpXLjLdu7OIdJqJJmk40lYW1sD9CfDzkCziJx864svc508Vw"); - a("0thIH9k2mz9a979++KfpLURayssm7wiWZpmSeyont6gN88Knng4Geah9ECi13Ad3/P306vrO77t2995G+D7FrG94HFyv8MN+V2"); - a("/lMqujJGUj1+z4ABwbc5F4/Mo748pwH/3r8GrAFvEWWErNp37qg8RkSMT62SwRo30NNBzAdG4Lz+USQMAJU0WGdTGsfPmpIGSz"); - a("XI8pb4sZl4W8Y3YYdGMh73chYNx+4YzuKuQcw/sls4394pig9U0Mq7xVtiG4Hog4r2Odz4qJ7IIWMa3Vxf17rYxhasvvPnNhaY"); - a("uygqzv5f5EYUM2bhwbkevGGFVbHYrrgB18opJg2iUEkf4zoqcA0xpoUkVhsiPDBDojwgg6fS6ClQd7lEGcikPxinud1Pwn5sdR"); - a("sW5vx3KmYN1GrPPQQLMMvg9b+DKRfmk4OZmKDHOEEeZySxgm0vtzWuJc00hP0m7c0VTtffl+DgSoOFWlt2mS6nbS3d98f7Fklx"); - a("xmh8o8LVlvwbEjJn2fSTNMpOs7zKTp+lyQUlSDKar9KapxHFUshz99B4XvZwr/UkT4DL00FFUuk/Y3kd4ZQdpPHxkizeok0kNN"); - a("pKczKcNoFpumB2nbIrG4kd8cV64NpIOQwEKMl7pobkcJ3XdeV1A+yU3NXbK6en2XKdZM8QDgDwikb/y2O/pBEfTZgn4Z0X/A6S"); - a("2i5pVqSusL7eZsOfVx38hsXdRB2drPRHp7uzlb+yJbFaJcj2bSPibSogjS3x6nOlCoYgZSxbgov6vbydFOjkeRY09y/JQdY5jr"); - a("1+3EdR8T1+1tZq5PMFdHmGsPYnAPM4jjpt6Pm5Voq17RVr2irXq5rcrmb+7/X0bmaathySjwciK8+b2tJl6sQCd+M8gyl7uq6n"); - a("KnFjoOwxefwwOFpBcrmnKzm8b2z6tocnuwgVxRF3qPzVOn5FEI12w1uQjjqezm2wLQSZ46u6ejx7hkCzMfOcbn3YP3uu5ZWPqa"); - a("ZYBljEfTOMH6zlldWI9poPsHMb4o1urnH8H6Er70Aq26+hfFNn8kn4cPOTXBqVF9G//xDhug2QTZCHoJEKvb6bN48JQZsskoxl"); - a("bAwZp6N/wxAA1CtWrq7UDYF6PFBC1tDFCf6/1F+keQZn5/yDP0ErjZSmL1V1E14T2DyP5y/+1R+x/jPMwi83tPCCWazeZOCLx5"); - a("HBuUk6LQe3nDVtJyCw9CbA7aEIFZ1nwbdT79nucdqokDqEvlffmrmml0VHx32Zk7k2x0Iw+7MZ5gw92Buh0op7iskzd7Q2Ok77"); - a("bJYRGNMo3zMVb5Kp4ZbXxJfUs+L9yqlb+ivORgnJYzxBrgUy9i6wXZ1NS3YbgM6BBNfV9A/TR1gYAGamo9IBJgfCjgIPc8D++P"); - a("ot4Z14fN7QpWqK+zf9KCdvh5ZlJe1P6/ilWDPpgE9QUMLm+S9xrh3YFqxHmuoW6EjB2XCDkZKZIOtyPJbWxK+dBBAJSxCY3qdH"); - a("jayZMyNg+AJcPh+WKBjc8fOxR5/hjHlhH/d3AOTTfuXqHY2F+/7wVIex2cqkUofda6aOVpka8v5fw9DUDU+TvLm/l8Chu5LfVO"); - a("yLTM2nnpZnx6kVZLtmQPVis2Mm8JpsV9rtB+GqwKxu9XoG0izxLh2cpnVn5qZn9okDHPdAmLDimkM5ZLIZWO4dPS/Qohm0Whd/"); - a("vYjpyCQKlfjyBaB8u0fj8kmcy8SEDlKZ1OUnDGYRdDHi357W4+UYj9XuOgt7Y41zsmE4meN4MEoQQG/ho94Km1423nXG2jSMJJ"); - a("SELhVa0F5b/a9UkgRB5OoLWDcYDL224v3TdXu/GQjCI2hJKbvhW8rN7g008X9HH6vfy+eKHW2t3MotC8TS3P3y+XZxTpfCLeuq"); - a("wZl+LWagsr+87AkuwIbx9vXvzqYt+UmrEtuTRPlM9CxuV5C3YUfO6XL0YCzQGqw4vqIq0XajEkeypgnTYRrFJ2tmG50oyAhq3/"); - a("MZSzo2DaT9+qH6maU4xLJ7yJIc6zm8H5y+ewtJMgXjTrWAHRlNpxd/yXgpa+50XnP4r4P2bi/6SZv+jPUACCPcvgPs1SBsPsUG"); - a("b9IOTy5EJBWPR+W6bAoEDUe8rMsOgZvVS3/Ocv+6v8H1gmbQBEFHOetUZh8A+/JABe0PAEhlJ2RzfB5G+X4U0xHx+VBYdH2jlc"); - a("roblCjALxRx8xhqse3pTTIufiRKTVd70d5Am84qT1X9sN/67bS9jzoreXkTdmJ9XDbWUn5YYLeUbwPqszmDU/k0t4LO3qn2xQt"); - a("iHAushsKQuxmIFdrnAbAJ7W2AdixiL2cnYFoEdJ7BfBXaNwHSBaQJbK7APBfatwJYI7EuB/QBMxlcfeR66BjpQ92wQmxx7R25y"); - a("9F9DoeoD2eFlK2+sltvNcn36hcai5os1CLlMhOQl3aTX5sLlyBjeKoMN113p81NAujn/JV+oFnOs5mjGe9HrRcpi6YYcXuTPBf"); - a("9u34+429+Cj/8T186gGf/Cgq+z4I5vgpH+VnxVJL7la8Zl+g6D3YGu0ND9Wz/f3fOSKOlnBrNEnBBkbCYw/aktoDpsK/42bSP6"); - a("7Uz/6c9Msf8wI1fW97Af2gjyvvTXVkNh0h7cxCWdkAOuW3FlJeCJbsD7LO0ieDLBSQKeRbAi4NcInrKB4LSTf2cWL6+FTL/DLN"); - a("IGCKcXyelZwXU6hahfwiFKOth7JXl7RIjrdrDTsHVwGiOc7hVOl9Ps4iLB5CqCJ4KJ3F637Cf42nm9YTp/Fszkz9xX2nm9YQ7v"); - a("+nw2NS+zsHJGDSMp7obhThv+4vHu5PCEvIrhofcuK6cQReGJq8ZnNEyZBxC7pTAWn0vg/IVC4vyz7Xx3LmzxT1KvPw2mR5JW6Y"); - a("Z2EtO6PXclYHCfN3iUc0JsQXkgOfBoUeXwZLerangCMjwaTKY67O6KnHj31OFOfJ3wyomH10XwclXDz1V9dmL/5toWUH2S76pu"); - a("ElenrmgpODgGjcQ9NSd+CJ5zjUN0uKrwgIFyb4++LkV8J+Hr36BQesBteGJ5jQMxJSKmMxIhRM1FHFMydCucE9yeGxIUymP/Vd"); - a("QCa9cmw8S/QLMVuKpzEtkirAPmQGtj4Jpf22aH82KiW7ERtTUarJDG1F50z/wD4xSa2OGUJe4RvEbc0SXi1yPiPyMcvxKK326K"); - a("f+MexL++0BT/tM02I/6fbKb4axQZPxhWpjUXipIu152h+B3m/DtM8WOVyCFWiTheDCBX6PR+hYjXoeCyZLzNbIr3ZnO8ekS8F4"); - a("TjdYTidZrz/RfiVU3xlsXJOAvK65P9A/jZDdEwvKJheEXD8HLDMLUmqc+N5rSIVyn3gUhBNiugvMN4rqu6hx1/6o1AsAl3KH14"); - a("M+IG9Fcgu64mP5YNzQesUfAZYs+vxKt2oUZhJkgAgWcIbvh0VvS9DGyKfbhNircI4Q+NHn39v1W/CQaE4n35hXs2X+HHdXEcSy"); - a("9DQGOPke3AkvJxfYL+MDyQsSGA5X3bWFfroPswBwBGDVaot8CvQdXwj89D4vMUPkGxSOtVgyqVyhlOXqt1ggcn+sIviDOAOVh8"); - a("oLFMbUsGrCgzqH9GABk4rQ4wB4wLBcwIBbzNFDBGnQ9ChH2ewqqd+Kdxi0fdBEjhcPmwRnRVqbWcmrSRI2nen1rHXm/Ai5a7jW"); - a("vTyndCiSwlS1i246A7vmiuNTU3G7PhpcQCtT4LX0hirJDEirTxwBHDW/jgpQpXVdpojivpe1w+UOHo5apKOocd1O/gMDXtfBXO"); - a("qU5wShsiCKdASvUM2IIgbH/htPx7zNscDyK2bGJbgwI/GsAQdeLhlISDI5IA1s+D3tvD90FwEirpXLDy5Z+40/XASWIc5xmqII"); - a("BtQjLDK5GMSa5pX6GXbVBfARL0qM/ho4DPYHyRiof5k7SYEpyaPDjVWZaOHE5wcBkez3FN1pfS4wH7wX20cN9fuIs0fA5Pz9CR"); - a("8FHLZjaoborG51FPpHgQ5Bh8jVbg+F60AmGrAe+UCO/13yn48DN56tcxdhJV9XN8ga7GR3YVp+RjMMVXR6UNcnAhHulgIdLXN9"); - a("KWuToDtMkIOouCem3ovV4fgd7rHQSIEQF2wEcshm7cjjy8gXA+z9ApcFVd004J8o3CoF4JB/2WBrmYcw3afJQJNI9vjCGJMR5B"); - a("cn3buVVpSIJekswd/xvCaRY5XQEnwB/YEdWUT7sIvoyivQOwL8KemSMJWw+Q6cKjaLEw9PCc3Lv0BK1tSrDsYDr5v3+xLwdX+1"); - a("F/WygbASaHr4JfwA25kPM/oLD3yyzA2n0vN3ZLlf5fBbDuiN6njp41wUwNr0xMCU76GX2Q3OHcsDS0vmKxD/mzfVxoZ1Q0OTlb"); - a("Le3Bu1L8CAP0NjxpLUss3A0Gb0pmnY2zlJf1C9N6Tupdmk0LBN6k6TQ0Ongir57HZQXZTkf43Es+8ezjmnIpnPmdlcB5RVDGvQ"); - a("JZbNO8SZiWba5DNGCQ4Mb6mHLNsMoh/dA/xRYqrXTKB8sP9LJ/OTaLY92ek22ljQT2lAsU9+GZU63Rp7V1a5Jl/Fiyz0Qjc9vR"); - a("pdVHKx+csTPnf0mXyBKPzyi6eWyiQi9F9Ibg9wYrSiKZ21dOtGMx6Xg3lFjZiXlZ6+j9pE8Q3+kDRCZ7ikyWHA2xbcOoYwACDg"); - a("iHb8zDhY5LaV3Fr6ceTHHVk73BtCwkKkrW5P6tq2rYETAyKG+JKdmXrKomS1us8f3wV7K3f7w4u+8dlo6jhVPT/cWMA+Wd8Ir6"); - a("wAUGBzoLkMikGm3/4iCAkh8DzCsXBWhOLKhjy1uUkmR+IQ9uQWQQnHqaENSv8Qph1PNEKNHineJqRNfH5ydjoBODJkRi/dujXa"); - a("F7rYgqR1BZyp3M6V3v52HB+JOC8k/tgRO5nsipX375kAZbaQ+GC7WBDSxv0A6i3F1VNhOL8p8VnJ6bhNbbrj9+IBc+ieN9Fot7"); - a("pN+SdlguBJHw25PzYYjYB9c6yAzoa/qQ1cleRBMLicG0r5F6i8irHsP2+/pZHdTOajHk4vvVLOsCFvuYeL0+aEzho9s3vYIhxx"); - a("wMOeZhybAGS4ZNhTDxKsQyIsxks75BDiihTZgUk/RlrnMvoMHd1LghEKEGOXgv5m/JSL5/3F5y0cB41+TX2G38EcBPhvtRRDdR"); - a("0k8W38n3iu995I52sMCJr/9W/AFWCB4tYDvBFxJMRX8JVHnu1Ozcijbwjx1oH58QSBb0ASdoBS/oUDoCCGPFEoirw+165JPAvq"); - a("E43O8pgSQJI0uo82LvqUcUHxpjc00bS3MhBN2n+EgF6FVAGbq/nRJxDtC8e9aJ0wm5mk4X90+7D47UiPaiv0PJLHIQxsklw/03"); - a("2UWbOtVJOspVTRLjvxCOhtvH7JZndruKnY6JCOtNx/j8ALsRZ0q0ODsUUzhXFfPaEOH2PrstJzdLnNXKn+KcDSdT+RQPVWylCU"); - a("RBttuBngXe2PwYIF4b4ZAcqKxTRbtHPZebCul7+ahBGv31owSfRAk+zf8p1av3vAzauQme20qGJJyYN6zuQeH+aKQ7BpnkOknM"); - a("XQx3OAL3X2NKwsUyCb3p70BKQiYl4aRAns8SeeBYhLVEHDgAbhGRQoaMyIp9LBd3meK7WcaXQH+9AlchPISgnkKez/DHBPsCIy"); - a("PuIzl1AIqSjf0chrVkTq6x7rQuSPsnS4JBcZSqVh6lSsMpLJ/YJoBBH5q0F03aiybtRZP2oknTGrz1OJzVvhPZmsA2nlAGcrhS"); - a("KIYrDX2oZ0R+eqJNjY0t11U0q3FO90dOanix7o8otUQ4ozvCsYPJa3IfsTP0JDZ/p5J2SB1ovy0j/+6f+GTWR3bi1MtHuI1wRd"); - a("SpkCg79Vzp3HORLwH3jgXg3yRMpFq4yAciDPdn9HcQVfGRVMXZ/hQhx5BcvKiWmp5TMdhvg1MIL9YG+1ttBg50DfFlXEFJZKMt"); - a("LLOkh/vBBCbhxkAXH8QAEY2BbtNwl+9wlh4ZbhIQPSmgBRqJjX8COBKKLoHQm4CaiF0gdmttUsYCZ2sdITB/d/LS6jbk5T0yGT"); - a("h/kVVe1o/mwyCoci+qnAUEVR7tPii9od3SmVj8q7oM/2jyZdz3JGXLULtoN6x2ewu1eyNQgib2DlxNykaBWGf7n2HdHkUXyeJ3"); - a("morfXJZmzdAYON8Ej0Kd7q48a3KM8rx6B8oz7jNreT56Nbe/NvPtT1yce1AeaGsmae/N0j5GjtNSA8XFvrA4yrLYA1m0FIYhhY"); - a("HzDBH8K7rokVOMsrigE2XR2WQtC+0qlEW0gmB5IVvGlAjzXqt9Jq7L1Gu72OybDnjvQ5MRnLnqSaOfJzZ1YY29VGU7O0xUzEaa"); - a("Uh4fM3b69qj8xQwr+2fMsLwjpHDeK4UzTQjnbSHh7Ou/kRvwCAgo+stkhNV3BjAXmEE5Q3iznIJKVg31mUBk1XCfOSI8Vs71js"); - a("hAFkMt/TwDttTNiO7qJv1ko24+oh3/yxutdfPLFVHq5q+Wzyb9g70wArQN6ema3IeWbXuWJA90uu5ZR9o4UbHq7FSW4rukFO8v"); - a("xndCz/ZIh9TpizeixFbssW6NrlXvi9SqtwPdbfseYpTbPW0ot8MbrOVGrwT4AkfxGZQ17Qb5kidBnv4pyCNONt8L8uLuylnK57"); - a("Yo+2uW83i8PwwA8S/ZzXkFn7BnbOLPAusxPa47eYIgbAAqhH0UzEhoYP1jKldrnGvymbRCH1dy6UC7657rFB7cx6Oa+/uz7aEz"); - a("J5ymW1W++kSXawxXLkVNpoHEJ2g4A985maZF0kxcAZpNCmiM9lUV2b5eNtrX0wDRcNAlZ8rw+1cj/NvK321f/dG+WFbk6UQIiI"); - a("Qk/+oF4H8m+O+K6AkiorGGtT3yeQ0pV82Qq4rBhqAM3Eb7hfVWubr0MsiV/wch/39V50SoHO+7SA33B/+JzrHm8cUTjTzmb0Ue"); - a("A3XWPN5x6U55P+IBYq2/SRjydXOm03oeaWkzy3+LPvezPZH/uc0mwc9rCx1YMs6qQo1t7hWS9yKTvI8xy/sgu7jbh1OQQmc3cY"); - a("JVLinlogz8KfzeDdNwcg/4nGlWSZo5caD5LYpOfFfqxIP8r1KSpEpEaGkP9+MHqNd3lOj9vG7Rizrd8GDSiwMkLza7pELWfWBZ"); - a("WDmFYKEzW4Pn6v7TEMefSEeDFFJPcIjuME6LVZc2o1CbpDw0QR5KTjDkIXsz8vFNjVUerruYZP4rW/flclu4rxhjKhc+7j9zDo"); - a("rkWRHu75VJssw35Rd5CpxLCHgzkr+7vE0/3sjbJb+TfcjH1rxVXhSS9WPNsg6BlEK+a33//RKp7497azf7RR7kbB765xo056bd"); - a("6fjzPxM6PtgzJPNZCst8LyzQJEHeCyDvh/r7KBH6/TkM+qV+19MWouh3gKNJtysxYd2uzyXl/y38/964qWqhHDf9LzqsZZCp/2"); - a("+l/r/6T/3/BaF6HcUVirL3ouy9KHuu1Sj12XOxrM/Rb/xb9blJPzEpVItHi1pMQS26UIunoxYH+PfldsrXx9Zw3AsbWCvpUit9"); - a("BqN2/1bBrINT+Qd7VxnjRBCFt6UNxdLC4RYCxa24BooXL+6kBAnuxaVoIAfkgAQLrgf8oLgEOQiB4sWdKxa6HFLcKW92vrLtQP"); - a("HAHybZ++abeTO7M/Pe7t7s64ztRMSt7Y2W+ZNI0jdtU3yPe35Ytc2/8X+JOIbvS6pjmPCIxrDzbnEMn7QMjWGraGMojl+Vgxi/"); - a("Vev/pD3mP87tsV+qKPZYkEaylmiPaV+q9sieh6I93nxH+bBH57HfssfJx/6lPdpLqGP5/AGN5dxd4ljmbfFL9tj3AMbz/No/Z4"); - a("9rU0Sxx+I0ivW/tMfhngh7rPhKtMfuRyLs8TKN60/b48Ej/9YeexdXx9CSRGN4doc4hp2a/Yg94v3Owb9XzKPhWNrNONaZwMeE"); - a("NoktM5VURJ1LSo4p/KxczV9rQlP4y6k2WdZg0J4n57ORqe8Eg5/3UM1NRzHspdpI1mNenk1A0ea4Fvk5FQan81rkOwI/F8Ztxk"); - a("IS7Xd2SN7H3/+Qnljgegc/CdeiPx31F5MkRYjy5blc7sfnt1griqEVtW+jFdnpym3sK0t/9nVFyxejkSvxutXBdZpgjtSugHKf"); - a("wWCHklKwfvqKvNKkBxLk1aTL0jfkd38pv1aQz49MapwvsY/vegcf6yQf66RN9yXek86IapjOJfa5dL3DJSZ5iUlOgWRSo26YV/"); - a("/2+5y/iKqj0/yko8W3iTq6x046SnXSjZF0L5bpXj9nAvRTvF8oH9LClJPKXfhi/jpRg/lrRR9Ph/Sxi56P5KibYfqYj46SdFSh"); - a("o6n8UAMbV/St7aFnxrSSfIkSP6eltcgege8Im+cmpSxC28pp5RWR8+GsfU+NbfQ2WZJIpmgCkxmr+dl7hzL/r+PN2OpDM7LRpd"); - a("dhCtkPCjmXUM7NrDJCX6hBJzGyso7rIyVdCCU9+Zp+0XU/YZnnuGIg6SlL2v8t+ZVfys8U5LMqmegXi5/3i5fd+3qiZCgzhmU2"); - a("oE5jmQ1/6HuOvZCqd+nZAhfbN4t6V6sRn6dTPuSE6dyPfK85nIw/osiBNOIFYBFeADLzO+OM0AtAaXmCBH2oY2gw3WyhRSOME7"); - a("ezlwtaRYL2R6pLHhd0G6phIJnQM+VfzG+WL6j227U7bP3FTWK/pWkY9bvGT86/Z1SsdTSesGZ5kBRhM7bY5GQlvN3VDfxd6def"); - a("s/SMDeuTt4j/iC7pCqh94rlNfdJro9gnb+pHm/MV13/nm4Y5C7Pnt1mt1z+J6i3lFic5l6He16hP3H8M6hibZkd+Kj+b+2bx99"); - a("VghpWUJuwWFrX8FFa+GZXnhZWfYA2OUt42vYnBNqGi5ExGCyWxffpitchF/oQKoby0lEeg38l818Qlg5NScH9ritIuaOmpR2Yx"); - a("sc5e5mdbt1Jqk/Nu2PeGbUG+97+uxJmkGLribiTLHSB15NijIR3xYro33B/srOIo5d9Jf7AWZ7u4BrH52JotKRrGdjG/ZpvC1i"); - a("XHk6QK1M8ZaalmpcJYxc2upplbEvtN4eHWim+VURWKraxlvkUPFI8oPTmujN479bXgAfZd/zfrbWX4L+dl/m+y4uB2ncXnLWbx"); - a("DJ3uKNkjrmnIn5Gyo+8nQ9sHxhQlMjgL9U1Kivm7dmdurfq3RbiUul4bvjcKzitR19dY/J31ydV1GaizuJ/sTrPy++IN3J0sM/"); - a("32ja/Hc4SatPgdZbVZQv52qbFOj78wnYLv79U2GMRv8oZi/ylh8fLv7m9DLhIB+PbSBl5KrQsX0TKgJV4yh7DmJYKhz95WZU5R"); - a("Xfo6Iy3mwdaV0zymtULHxNBK48oPZ5W8rG7mD8hUxdb5UIMKvlF6knHuoz8NjI1f8fXQF9I/FFMDX9uapoGw0VoQQZIE/j/8kS"); - a("D2pcOtNWkIA0DJxzHXRnAEXyYJHCEkb9EpaIK8QTif421kucB7cCG4PkSm51rL63MP42gazjEunuNSoO+Dhpf7yDFuHPKBWha/"); - a("y+OtiyT74twhbr3AZL4f+qO9OnbNiLuS0fWVVuNLy6lxSyU1nlBFjdurUxzX50DcwOoPi7sQ17F2hcWXhsVNtVT5XGFxixKHfB"); - a("Me94uNgezvBK30b4M4ZiVjhIQsorwQjh33HLl4ynPi5NVLVy4fvXb9RqLv5u1zd+7K95MesH5fBL38weBYCvlfDCaBP1+Q/fLs"); - a("ysbqK5Ltaxdf+EOen61PJya4vidhAgplhIw/dX/WSL8Xkv2kvKVEyVKly5QtV75Cteo1ataqnZI0OC3VkkHSKUcMOyjNTKjUX7"); - a("dvt4jzNerUN6K+YYM85uMdx8/5yPnqIPSw6fVcvVMVuHUa6TuQ3jCnc2Vbb4GDacCPAs/OGtRjvtm8ri74NWDyDjlmzXg0a/Yk"); - a("8EdABNd+cDVYh1TslerGe6SnQ+rmDMmPjDw5N6E8uBnYtHej1dbKqdcMBi8LrF8xx/29xjtxbnAbsP2SeSsGLjj0MiMMfwvSJ4"); - a("5/MO9evVsPe0OdumNgK1U9dCbxnGdirw+cN8B1jR9b0lpg4L6pGd5xPu9jpE5ogpJGQ3+IqC2kKFgQcqCRISUdXejws/tyfrr/"); - a("TdZI1upGyTWHZqNuvtBLRxdU+lzj8CX2mJpnq4b4AG0Uu3Rzu7Zv4hjYDL4F9r6NYy7waMG+EuVXfF1uSkwfazh3H4U80HqMow"); - a("PoAiaE8AZHL9AHDAClRI4mYC6gBWgF2oEOYLT3h6XveL4b6AUGgKb3qB9oB/YHxgHdQC8wFBzt1GdaQI2TIqrx8NDcXtsSzn3Z"); - a("8MzPzjEX0Ap0AF3A7wWNvkgxbdGKRfq34vJxQDfQB5Ra43xAK7A7cAowHugB+oGGNhwLAG3A7sApwHigB+gHGtpytADtwP7AOK"); - a("Ab6AUGgJnbcSwPdACnAOOBHqAfaGiP6wbagN2BU4DxQA8wAMzcAecFlhSfr0j/W8H1k+fLC4xDua0oPA/8OfhS8INazuPBveA7"); - a("wG+CJ4AnxwPPA94U3AveHPwSeCtwH3hrcD94G/AAeFvw1+DtwQ0dOe8AbgLv+Im9u4xxIorCMDy4u0tgcAlSHIK7BtcQ3N2h+O"); - a("DuVrxYcCjuUNyCuxd3ggYnwLlvA5xgP/jJTdiP59zpdK5Md7c0AcfH9bCN6+O0uAF24YY4N26CC+GmuBRuiSviVrg+no/b40XY"); - a("wevwWLwee3HI0KwHjod9uDP24y74OO6KA7gbford2Kpn3B1Hxz2wjXtiF+6FC+HeuCL24fp4FW6Pb2AH38Rj8S3sxbexD9/Bfn"); - a("wXH8f3cADfx0/xA2zVN64UhvHjI5HYTzh6GuYDx8AuHBMXwrFwfRwbt8dxsIPj4rE4Hvbi+NiHE+LjOBkO4FT4Kc6IrQbcHzg6"); - a("boBt3BC7cCAT48PXcSlsl2e8yu1xMuzg5HisshenwD6cEvtxKnwcD8MBPBw/xSOw1dB4JI6OZ2Mbp6rA+HFGXAhnwRVxDlwT58"); - a("T1cW7cHOfD7XF+7MZFsINL46F4Dx6L92MPPoC9uEEl5hM3xQdwf3weD8EBPBbfw4vxU7wVv8F7cPhGXA+Ojs9gGyerzHzjFLgQ"); - a("blmN+cYr2zG/2Ifb41XYwavxWLwGe/Fa7MPrsB+vx8fxBhzAG/FTvAlbjY234Oh4K7bxNuzC23EhXLoD48f7JjN+nGEP48cZsY"); - a("Mz4bE4C/bibNiHc2A/fr6P8eMXOIBfYauJ8WscHr/F0fF7HB9fPsR84ABOix9jFz5wlPnBnrPMD15ylfnBS3F7vAw7eDkei1dg"); - a("L16JfdiH/XgVPo5X4wBeg5/iex+Zr6bG93F4rN8fSEu9FNmc/O73ob5/+Q4Hx+t+Hk87QNbMzPweDyl5kHohl6m7T5v6Ier+gh"); - a("xP/UjwfNl5HaR+lLovBz8PnjH1Y9TfZDX18ydN/Tj1QDZTf8PxJ6lXLMbxp0z9FHV3Ec5/zNRPU2+fm+MZ11nqT/Pz/Zb6Oepp"); - a("s3CfnzD18xaN4z2c/wLlRYUYL+e5SP18Aa6HebhE3ZWX52W8l6nHz0edcV1R9dzUr6q6m+e9puobmbeAqp+nfl3VPdRvUq9flP"); - a("lnvLeohy/JeZif28HxluJ5Ge9d6mMLczz1e9QPlGZ+GNd96nYJzkP9AfWNZbhO6g+pLyrLPFB/RD13ca6f51VNv9tYyAph+fVd"); - a("FFK93yd15adXt05zV88e04jjQ3xpIb+0UF+aFSLk93/CRIkSIVy0aJG+/gkbNWpEK4Q5LDTNihQr6s/e+PR0ZV7I8+QbMtjid2"); - a("O/kDVJN+khN5LnyTdkfDePJ2uSbtJDbiTPk2+C9e6Sv2x2D173u5Nk3Qntw8t+ob+mytGdB0WR+cZ+lXvSrZHHN+9pnFZl1rc5"); - a("ZWne4EUq1yTtGEleL3oZu1RWWfEhojw/XqQyZtJSkeV1qDePUxmzQnrpd/VhnqgH84z/slyfh/7mKlenuyTjC9/X+Dj1YDZyV5"); - a("Trd9NfSOWElRPMz3V4kcqToRLI9VV0jG2VVedGlmX1Y0dll5YJpN/uZ/zUIcn4c+eZ1wP6a6q8MNuR9bX6Gx+gHswkVc1vfg79"); - a("uVXODCyKLOuDN6rc/dC8g1xzAPtC5dxlO+X6N+KhKhc/SxRWxjeQcVEPZughD6Tfob+iysZh9oaT/Yc3qmz8IryMr/0g9o3KSD"); - a("nfRJD1w4tUxt4SyoxvMOumMmW9PDK/B/BYlXtfXZP94xpibKlcXfKInN+Lm6vcMyVKGHn9GWp8nnowJ+aZEVHWn/76KlcP3GTW"); - a("f5ixn3owq+aaIfPnpr+QyvKfroWR9ccbVbaN4JXrTzvCuBTZnPzbNvQPx3tH/eF8o9nXo0hyQOLWZv3pz63y6O4Ncv3n8SKVod"); - a("3Xosr6jTEOr3L+oGwhZP5xfZWZlg6LaG5Qrot6MLO2eSL7uzn9uVW2iOZI/wHsUZmyYy05f6FxzI/KeRMWy/V7cHuVsc+3N+uL"); - a("D6jMMO50BNn/441tlYsmJYgm9zceqrLghwzy+PgTjO9RD+aCzSNkfdz0l/qWnD+U7M8A9qks5h8YRcY/0Ti+ypeJysn8eXB7lS"); - a("tiNJH78w0+oHJtnTNhZH0mGbtUTox+Web3OPaqzJEqpHx/yT2ZfaOyW+nX0u/BzVXuybhQ1jf8FK6LejCL3HfJ/Lanv5DKlL7j"); - a("oeX6sFflnv6f5PEuj7Gl8tXh8+b+w81VZv3YXM7/Bh9X2fhMdpn/+lON06q8US2yjO889qhccWVkNFnfacybyqPNm5nfg7Bb5c"); - a("sH5h+A7ensO+rBbHv6k6zfIvorqsw0arqsf6kZxgHqwUzSoqFc/z36HZWj4/WW668509hWOfrBLZmfjXioyg+pd8hypJ1l/JR6"); - a("ME+drS/736G/psrSVT7J4wPYp/J1/IGhZH5nG0dXWTfrKfP9CbdXmfxNHRn/G3xc5cI0q8z6e1l3lVXfJTI//2CPyqwFQ8n9EX"); - a("8O4/aSZMzYu+X63fSXUlnl9dqosj7Yp3LtkZ2RZH3msi4qzy0KLY8/gIeqHD0mt7l/5hm/oR7MXdU+yPp46W+uMnTaxtIff77x"); - a("eerBTNC2nMyvQ38plX2LPpL9qZuf/l+1+mf5PZnj/tTiL/j9cSUqFrWzZcqaKatdO6sra9bMrjyZs2avYzdt19F2585ZL2d2O6"); - a("Ndo0XbnNmt/+1ftDBk/OHsV9I9yqRDelhfL3mAPE6WYl0rkr7QIX/4PFAUnqei1cDqZDX68rW1ZVtVvnxtZ3W1mlgd6Y8ToUi7"); - a("Bh0bF+neuUkISs4ts8ViiEwLW6Vd665Nvv5np4EfP2f4Rn3+yHNd+n/dbtP/h+bvxecTepus2Mek45iM7v192v1MWv1N+oaY9J"); - a("PHyWALV7VCw5ZNGnU+wPiCzc9tsohxpe7pomX89qUof6Nlz9nb8nN8fM5zj3nyUvd/5u5KY5opwnDL54GIUm+84nrjgRZBKZ6F"); - a("shUUZIWixCN2LatUy3btFuXTGBs1indj1KAxpj+MIWpijZr4wx/9oQne9YrXD+sV8cYzeNYp+wxtt9t30SiubjI8zPHu7PPOO7"); - a("Oz7850P6D1MFVHT8smucycC/N+Wk8u5AvAv6qnHUKDalJJXCBHlElDY/Dj/YzrAEpALvskeL+F6/dwvSB9jZ8p3hOaiurC+VFV"); - a("TmwWpmRdUOOCnkxE1QuFSFxlJqlH46qgz2haPJFkSdNaNKZMClEV7+kuHFWQKCSnFEHWtFg0IidLQpdFk1OCLMyo0STLk5NMSE"); - a("/KsZhuJEbikwpqmpZV+UIlwQqsnkRLxC9MyNPCjK7oQiQmMzzChWP70Rk1GZ1WBCWRYGOoa0uBnfgA5gcT2N8S715dVxKr9V8g"); - a("ly4Vcg1Cm2GHhwuxqKoILp5+iHHqi5WEqsQ6j+LpY0oyNJVQ5Ml+RY8kolrpjKvltzMeW8RS9QzdW6BrY6mWhs7tbhybYhpjje"); - a("lKVfrQ55C/05Ys65iurZCcgvletYD8Hbfui8djiqy6q72Ai8jfpqlX1aNjq/pbbWekt1h2NIwxm/WkMl09TmzfODiuXqzGL1N5"); - a("Mbe5a67JbWKjnxdyLbWGyk2rDUWqauT9zf8oQ9SS/bLBdcblRlHhwd+LbSzEWEixcAcLCyw8hSAgFFjoeogh4v3s/y9YaH749+"); - a("KvDH99kAXEWxkm2Q9ESM/9XpxnyMO1z7JvNzxnpDc/awT2fzlA5hyW3sXCwyy8zsJTiwa2sbyP2P9cW5nDN7meeMzgwePPPG7E"); - a("m19hcix8z0Lo1d+LGgtPsTD3Wjm4XmdcWOh6wwj+11lA/C0ml2FhrzdYQD7PK7xm5K+uoy2yOhDy7qKBDWw83KIcft2yWGxsLB"); - a("af3sUI6R2KxZu3Kf1vlE97isV7W0oBZRBWtioWzeNsqh3z1SV6nJ3dZ5Mj7kfZs6qvs1lkfUeRp3k/nvjE+n7iAz/PpzTPrEN5"); - a("bicGA4xnUgFR/xLNc8WG55JDeW4rBkc0RQVLZpef0jwLn9E8BcGxPNldLbHG0/OZNc9lpC9+TvOccCjPJnGU3XxBkx0rNjyzX9"); - a("A85xzKc1vxzESU9052FD6nec5/SfPMOZTn9mIgJuv6afFkMD6jTroW0V717iupr2ieKw7l2czstsyyNMeheU59TfP07utMnk3i"); - a("UFRPlvvn/Fc0T2mZ5hl2KE+PaMyxq9my+r6m+fq/ofnOO5Rvixhgj3NxVVENutoyfy4/5pjOwDHezkB7Z5D96QoEjm73HcX+6w"); - a("34vN09wZ7uHvHoK10T39B6mfiW1kveoXrZRhw5X1cS7IEY95NvrP003P+Q+Y7m6drPGTzzwLTbvYqF31G+aKAfKAD5eTNFIMrn"); - a("gB6X28AGnG+T2+QHMubdGuygDelvmfX3vc246DD95a4xeAqQMyM/tgqtzt9c2e/A3w3+vxv8F8A79wPNfwH8wzZ6kO50byj/5b"); - a("vQ3vOIo/783bCLe4AoV7jPbB+leZ+SyEIPc0ifLVbrJ/+jzfx9f7wvsNFP+M2N0Y/rXaMe6W3YyTsG5lB/geM7Zn2szg8TedhD"); - a("GOkZ6GPuN8wLV2zGVehDAvJj0SQnxa314dXdlvz9mvsv6SM1AfuIgu/FBnrPhh4uqj5vDvE8T0d5gcsB18ojLsXqXPc08oE8PY"); - a("y4XzWdD/w1pKeBwiXABK4DmEJ5fjSF1u6rq3H/b6gfGAZqwAaTX3cB7TRRx6/btsMmy3ITSOdH4Ufab77yk8087YD1jbv+VvcG"); - a("v18ISqU5WhuuX+B8zfx+pvml6/Br/aVaTth7Y/jx8vk9YU8C6gXyY8tQiT2r/zfkAzPAGk7gw+0gZZqvNkJPfsRzJj0Kv9o8h6"); - a("7TTqT9NtZOtg0Zbn1DW6y+X+j+4P3NZh6/vzXPCZNcdmJjeGJcLc/TEOfjahpY1oekJHSmDAxMWdhLDpivYz9+8PPUsR8f7MOH"); - a("+KLpfpX/ndar/0CsFzDZUcEkl9vp39Vrbmfod0f0tx0MzALzQC7H/hrn2wm4K3AXA6Vdze0TiMdiSoS/f+JHGnqUEM+a9Cu46f"); - a("7nOQjrFaFnfnjdpvgRf69+80e7Sf26DoYeEQ93Vdtt4aDqebanrTruRVwDeg+1vv9n25EOfkIP6j0S8xJgoQPXdZSB/k6UAxba"); - a("ref96W7w9OH6cX7pWJznOMgdXy1fQDx7AniciHo4+nF9fTh/AOfrhxwwHYT+BtzV43rI8Gfo5vfe6FdpxDXuL4c9ZDfR9uQ/yD"); - a("o/Z5Y73aH2dBrygRowBeT2lEXcO4J8ILenvAS7CuF8p/81e1qGnHcU6UBuT/lx2p68Z7j/UXuSBpE/DHlgZgjnAWZCON+ZiJ9h"); - a("Ht/K/rUqe4Ldebh98uc/7lfZkrbH2YOc5R9Yr39F2wL6BnqBEtDjAm5p7V/ZLjQgq5MxxfCysPrR/8zzGw/0N7AVracV6DFrp8"); - a("9G9/9Kj9syP01Zi0x/0Jf5uYLbY3prWj/eg51pjxrajesxzOKUvy+FfLO/z7WNtR53CgVm9GR8eliZjic2l/UZht2Z/X8L0ONS"); - a("I60vbZ361JrcjtSna1t3lT79LE7pM72NuZ9XazQLvXmRnzfp09tE62thnfqUWpypz79qny3M36jHZxIR3te32UT69Qvb0noqOK"); - a("yfr5X/jyM/dgn1nq8nE3IkaSw6M7zF7D7WZD2erKC95rej20VoW1+75a/bWL9P6nrct4AZYIGn34Dx43b0F8RzwAJQuBF2D/QD"); - a("PTchDgwDU8AcMH0z5G9BOWAB6L3VwCwwfZv5PtC3usa0utXY0Uz3t4EWG/99m7P625+3b2f103r9zHgLwfwF21n3szDaacVjs1"); - a("9xne1VeHZj+pn0HOwcqAEzzyMdWADy8y+/jn71Buz8BfRHYBqY5+kvQh6YBeZfQvmXEX8V/TGPcsDwKwYuA6VXqf6F1mLHFNrl"); - a("/cWvTnJ9dMApTz28j/vkyZ5HW3fYhPf6nUFRDPjEjnaxi62y7+o9qqu9L9AbaO8Ieju6uo/p6uzp67jS5d3B9Dxm9pPuaONvOs"); - a("RZ/bR8/x+Kqhcrq/7gwaQyHd6BHo+EnWgeAw7jae7XO1bwPSOqR5NY0TLA2o/yg7fuTPNKrZO359yN6dfhc8zPc+ANP4N/J+v5"); - a("sp/b8S40n9ZD4T8t8XZAO/Nj59C4mlD00m6iyVHlAiWhqBGlxBPtZ/bHt4Lnsg3fiUOdZdf82D00FI/IsXF11Ewa87pdrJ/beT"); - a("sv7Urzml8n74K8Ye+xMN6XKQ+W9tWAceuu1uO0D/Ze2I3m89Z6+V7g/lfGrx1CfTPRWM3w5WrczZr3CtLfaqV5eQ5zFu/UhdXj"); - a("V2sIrb1m35w+L2CyczP/3Wl+C+AvldAB/F1KNf/dGP/puAX93en71uIeNJ+lw5w5rjWHBtVo0vDlltp4xYZndk+ah3C4M3luF5"); - a("LiesXSmMJaexl/izg2obw4EixBTf5WSB3bPH1+PEbkY8ecOX9r5Jc2tbGtiDX5WyI/GIvLSYv6m5B/ZnRSQR2W18m5HwE86Iq+"); - a("QHdn9zFib3tHT09pXe1Rve2+Y3xd7cEun/fooPeYno5A75U152ng+mui62HZZP52wHr6wNvCuu1xWjRWbkyL5wyz3BYoN6RckH"); - a("QR7RyKayWo2w4jZ54mjjKsp5f2E12kfFCO6QrDetcXSswo1PWplbyJ85w2E4tR+j/PTn58aIjk0Ts0JlI8RsdFisdpg0O0ni9T"); - a("lQTR345AgZaqDXV8N91cjPfmrVe3fyi6eV9gS/UGNb49bWGfOoJZLle54avtU0IK4yWXq9xA5fnMVk4QIFexIWkFYpJQKzbBy1"); - a("du7Cl8Xl8AxxyXM22UWfyCFs1xuaqNJ9kv7fS/wuUqNnLMf1VfyrsvytdsiEh9TdUV5nK1GwvIS5zncuWF93PfEBJ5Xr5mgfnH"); - a("DZYq2A/lsSA7+x1d3MvL8wXK1AeGVh1h2JDd6K72V/LzmBc6TyDDVPECL4+FwOuu12+a15vPk/+BrFfYH+VNC1fXU7VQkS7x81"); - a("QuNPP9SinbaH+L+vna1UXkNayJNdTU7a072fFtcZo8reRQvg2pHN01vLybQvKFrjy/nvJCU5JD+ACUNxZmNv5swzjNy1cuUJR+"); - a("sdVTjsvVLhSzbyhvOXnF6jxYZAaFW9bP1+lt3zKIqULvpKwx+wrjmt1dR96rfzGa3+G+B1zCIydc/U75FA3sbjIL+ZbywiTi4h"); - a("tYyELChzROZqCq5JM1513+nSLjOQjlKxek+N2o6qD6/Llc9cILvuyibb86krNczrTQYF3t5iknZ63OwxcrLNS/7hUuZ/WCPrwV"); - a("ffVYzwDelZL8NfTUwXUkNS5X++KVlFzgctYvANnrP7qnFLi85YuoZjxctdWfB7RB3vrFCHstQtcf5vJWjnrupJ+vX38GWc1rnX"); - a("Yrk/27M8Y/4Mvrq3Vwk1fqOQRyFo5i+IgtRQe4XKWjFU5WavxKcTlrxyU9FtSM+jzeVh4HyPNzr6j/EAvFw88L+fqORu5ilA61"); - a("OMkEl7dy2MFZR1TvmufytY4v7vKatZJ+i8vVdxzBY9R4mOV4iNSWeo6XPztW4ZBsz7s7dVmuBS5f5SCBd4QwtCUuV+1wKOxBCp"); - a("b9JtknjQIHFNnvx7DwOgsHsPtXkoXXWTjAzf5n4WkWDmgoFq9l4SMW+jcVi/ezsMUWxWKMhXr+G63d5j13DENUCR21L3Y2omjl"); - a("SUeG64u3t3n/7xH09adjzvBT1fIUZ9lIrcoxPK+1W/OcAj//kTbt5Fieg3hAw/36CGueEvi1eWkeyw7l2ST2Ry/t23yWkojjex"); - a("Q0T08HzaNt2pk8txVHZfVCZa1F/V6a54oNz7BDeTaX7HaEeQkuiMUvw3c1qP5ZOIrmMe9Qnk3isJycKndQz1HWPJeRvthJ88g7"); - a("luegeqkci06OaPhuC80z20XzaFSdyXNbsTQEsbGIvTfAd2hInvNH0zz8DuW5jcg7J/9uD80zdQzNQ3MozyZxXJ2sIJo92vRe1v"); - a("z7P900jwWH8tyW9c+RmfJMYf4Ymqfko3kU/irPsxv+4d//GVBkzXBxVP3+T7fN/K+H5tMad2a77rg2z62e2Gs+6/adQrr3WJrP"); - a("RNyZ7dvC7zNSPKoy4uEemmfrcTSPtEN5Noust45cYBgyiw+w9qJ+p8l1PM1j0aH228zbMyDrSXz/jBqXlmx4ujRn8txOPENORG"); - a("U8q+G7asR4lD+B5uFzKE+P2BuJKLp+RjQekyvfbZxgzXcJ6bkTaT6aQ/luI/bN6GhTfDeQbNeFk2geGYfybBKlBJv0xthiG3y/"); - a("kOaZ9tusW3Qoz+3Z63I5cvHa5Dd3Es1ztpfm4bnEmTy3EQNxNZmIxwL8O5X0/SXcR/PwO5TndiWerDH5uJvupXkOBGgesw7lub"); - a("2I11wgOttH8/T20zyyDuXpEdc+GBCs/F5AOEDzFUSaz5JD+TaLxovHwJQSuRjft6V4NgZpHkLCqTyNZRT8VuoTaZ7LNjwnHMqz"); - a("URyLXnj6TDSJuBCkeb51Ms1jzqE8ty/5dy9gk3qMR40n0/P63ADNI+dQno3iyFiln2H5ZLo9FwZpHssO5bmjOCZfoETkmMnP8N"); - a("YAzXf+FJqPV3cmX494WtwYkcaMb+mUv0tN8p07leYz5VC+OzO+5bXw4IzvalN8Z4ds/KEO5bsD49u/WR2Knq+DLP9eOL1vdnGY"); - a("5jOQdAZfen/7+lE6toHM58c2IVGNxCfX9lHMD1mP929Bf20jNvNsh+kxdzx+z/cEA70nGpgDugLAfgO1kwzMcOwzMIX8NDADdP"); - a("kNzAMzvQ3m34/pC4yVdVwYttavD3qdk2zm9/8z/WpBxIFZHu9HXLTT73go2F3Wr3/EWr/z0OvS6TbPE/8z/aZOhh6BOWCex4Pr"); - a("0K+vrN+MZD3O8vHBN0brT5hxln6FAegVqAHTwNQpyD/VwALSPYNIR34Y+RowzeODpvlJaNz4JN+aSnGMWutVgj7TIZvnJofqtc"); - a("D1wPU8BL0OGyidBn0hPQcUhq316hmx1uvubLnvhaI6GZVVSwVPQI+jN3uuuG3vd4fufe/MwiW7n3DSkyH++xzdfR1eX+Doo9o7"); - a("+n1Btj+wv6+9J9AfbD+6W/R2d3T0dPZ3Bq905VF+ib9fRDsJH+K7kOM2613qtJPvjOr0vNSwId/DzEGf/DggNDwTS0ZX92DNRm"); - a("IzevRSZXXx9NhmNTKViKvRy5VE6bpm0X7AMFADpoBpYAbI61rk9gzeBaSvmO18nJ7H+s+0Gc8d0i9qnrNDw6PimeVnMg16qLd/"); - a("8QAXvc9y8sjpIzdb5Ht4/uR+wn7T7GCwmR1Irruvs3eYzpeG6euZmjpWVS3yGyvzj9V1ROvumzxFVsn8oHI+mT8sJ8j8Xi1hI7"); - a("+Zvr4/aDuXXadhIAx3AQuWvAEbJFgYOU6cy5LboiAuUkEsK8dxG9M2qZyECh4ekcSTuplSV0LCm9Hn+W3PeOI0PTo5p6vu+Pf+"); - a("9but179SR6//k2y9/o/1D6//jZI330uG/e+E+XldR7f/ZhR4rk+ogyxv+KEOev8PdXjg6qD8/v3PW++zQx26pr32P3J1aNUhV8"); - a("bzHjfUo7YqtF+uHvNpsM7VZdL5r48719+H2u//0imv/5sq/OPLzn8+jfbHL1r/3xnoqsKWHvun/MCP6+Hya6wA1dXlV40KTz0g"); - a("TwOym/FCvqBC87h8OwMK3/X6Qm62C+/nwbzp/EDDZLTRYJevPnBKFwvRHGqS0HTSvfm0Igmjgy4BfZLw0aacgmXj+JT3/fKY8n"); - a("gB/VZPacphPquLYVwc2PnTmNn+EPwRWDtfPM0XZ7Y/6cefdFXUp4akSdR7R10flmtNqTft+rtugLc5CwPm/LtmLdc8pgEJsrSP"); - a("M9dbDvsSUBaPcQc0SkBuOYjoRR4DB4gZ4hBxhObjiGPECRqfIs4m7toNCcbRwPahdrPZqJGn/QoYp4gDxAxxiDhCzBHHiBPEYw"); - a("7v6lLkw3lcvh/jOwipq7ZuyunnQqTvId/FUVSqURPLUg/YGlFMic70u9ooUTkWRuRaOi5VbtTJ8dYotbsYL38avd9ridZr9OH4"); - a("1/VMfRCVFtXE3c4IPXQAt6XQl3qp5uO1VHtRFVpO+s7sdFM6valF209n6xuyyb56u7iK57WNdf3642pkiJ3IqrF8ZJTSYNKvQU"); - a("/etqq61CvLoA9BP3GEmJ95+ZLP4tGCk60y/Qad/WR1UsWYH/DH2pzUdkiwa4hopNaL2fwsDhBn7nywJASbgE2tTSlYex9hKbc2"); - a("o2CtPmIUrL3vRCy6jP/tq9dvlq/J+/GSGn75sipUMehtVaHtap0SY+9PSWAtrJ9Ruy6lmZv57dfX5N3nKZ8shCM78flAy2NAGQ"); - a("eY/H1Xcrlu5/y6qUma8owEiBniEHGEmCOOESeIU8QZjociDhCHiCPEHHE81acz9VFc5Z8SPTGjjJHv9uTKZrn6NHT0m4/8c96Z"); - a("837znm26jl19spDOrneVy0K7W5aoiq6RohKFmPQhWA42ATvMqTrZh2KtrEZrQ4FW/iLbnLjPsG0epBQigPM2HB9SqDnniFuBGP"); - a("lFM+fazHmHxh8Qb7s5H4X7fErApp7nFAn2ln9zx/9kcd1+w+MdNO/4p2Af0qHd1lGwD0Dmjcfjf3bH//yOn8z/18NV/v/re/vj"); - a("8/cOUexruXtSqFbJVhU31vvDyPkzpw0DUJzL0GZISzL0jrsOVZdeh15CL+2VS/8BDSRN27tcQ5qMuKAUl8T22SYHW8aMGTNmZG"); - a("RkZGTsyMjIyEcoJnpYkm0JT5H1fpJO5ECW39NzfP9Z9fn2EAleMdM6+U3PbJeSIv1jWvOKBP6A3S0anlkrXVLLPzFMv2y75Gxu"); - a("DyKmRZbZitqc9+TONPH9PAvHGTQUN8zgfuJ87RC23i5YpGU1DKse4BT7NsSu1VquO7tl+CRYk68wYKMUSuZGINbOU2J6xLJ9Yp"); - a("+RWpCAJgvhZlD/QuagN8jcbn0PBVL1c8jFVn2r04nWr6F+dpH6K4K9oJVGQ/mctmNZyv6wm9OkrkXPtxfr5j3q75pes+xSeuQY"); - a("NVpqF+59Q+nKD9vyG8EZMQXXNTpVGIqUxy2k8n/Z+QyPKyeUNhc4FtIP1XjqivGP0pWy7V4Y/hH1ff44lDbEfAiHP2dI6mBdKm"); - a("dQ1hyZgHJWKucwDjbQvFS+Y+U+K2NHFeWcOP4Bu/1EGDhA/L161PGOffPcS/WaTP+gUuz41ENrV0y5gYYFKpUaMy6NoPqSp+PI"); - a("9ZnzSDuIuuPsAKHjKvRhcByRcZxfJehvoA8D2Ihe9+P0A+i5IDMyzJMYANcUHB8Mzme1IPLNaSFo+/K1DqyC44KryKz2FeO8Bc"); - a("cFQZEBHV4kc//A8cHK8bYWXLUYFwYVh28UVB56LvDXe6sfnwOOD9AhPHedPCFdcJFA2tU7FTwGFxPscnL6zyFjMz4pKLVux8Kn"); - a("4ITg0f6OAkJ+ChwX5Mm+103QEJwYjMl80IEO46JBk4+q2cmBCwMbiGo0nBjAgZ4LPow+6ef/DpwUJBh8VrMjcKExv5tXIMgVpE"); - a("WD+01BM395cJJhvF1Ug21wEQN29YuK7IETjMyHu7qPeQJOMAbnSjqOuIxbGG1JWcWcQi8ZVlf31D1dg1sYQKdKYgB9jJFytJ9M"); - a("4pqCjxgTh19VdNZjXKzBr3+g67kBPmqY635TwF1wkjEsUCnP6/bkdcZ64KRhK8XoiiHjR/q5/a74nd+HXjRUwU7l+AkT0QYnGo"); - a("VgE+omcT2By4GD/WWcxE3ARY0eP1VDJS3GJRsZYGE4bMU0cAp+uRf4x8zlG51qyaeQll5UO7/U/3kTxq2llluRk0vosZBekfVj"); - a("Xn94qX5PXtc8X7c09a6m/j9zV87rRAyEEYIOEOK+ZQFB3AIEEqLilpC4xCGgoDBZByw23ijeBUJFzdFT8l+oaBAlJT+BkhKPPZ"); - a("MlXnvechQI3ntJ1t/32eNrdux1yiXuv08e59frTkMC/jrLf5rjB/0TafwKwmMC7jqbvxPH/0v95XN91j7Av9R13v54mYkj9Ypn"); - a("rZrfCK5k+8fZGfWPVzSusuknmD633nnrztULN67fvnM7k8/dFEcyQ2XraopBipF7tXtgd/tQxAiOPj6axm+nflSXw8rY2h61Eq"); - a("kc1CNZ3AVpQMJp6sdGSDGwoq7836NJ3KauXsAqmNu76TeQDhQrKlKKf0uX31skKkwHt4906AS8oFVUynpBPZ6Uakyfd/F7ErpE"); - a("BSSmnjMk9U9RPK+ZlHooayWMHKsz4pyY0/hPipAvWYJnMhPqhXZa/exQEDXw5OwwWDjfXpSOvjWCLJ2HLeY8Kd1tjK5lzv8/SO"); - a("uqZakey1Jc16Ww/gBU35bxUGjhOafNEA9a7FUPajypZ4FLB/apJ/ujfMDU/M/y8dyTJfEP5/tPxLNw3yZscAd9PibTagI3B8oe"); - a("FTdLJa0SjfupnyhKbkVjdA1h2VnVeICPTkpTiKmCNqVLldDdlcj3dGoqZMU8dHGbEedbJ4VAjajwjPJO+q0ZnZoQcJHJ310jH5"); - a("UKxpqhPyVfjLR7C+pnxMAijtcbBaQfeNSLjN6Ojp4zvInV0vaI9QCJatnx5wrEEEZyqKLx54l8psCgV65cdF0zmc9YTxOVqbQu"); - a("LKC6uI2Iw6BC29Yh1tqvXDpA9Vg+Vtn5CUoThcajkS1t/01ZPcTw5aGOMhMTF2Vj23vMT0gA5sc50nG/G+W7JuGY9Q1WzzNl8w"); - a("nn3DrDNc5o+wfFAVE1fmniEcxt9mivdg9jumfAKTeZz0O0Py7wj32YSjx/Au1evZhIA3c49LGlU7p7tcsAChifBW4e97f8wiX1"); - a("egML/7DP9dUjw84Xgbj1tHDothcUnH02dHUAAxC2n92k9qitFzlSmXLG+FcRP6RuGxjTP+kQ8chl4vsX6bTeUpbf+Xe3lXq66B"); - a("upLv/OLr91OAdbRMW4vdT+XFF92LF1QFQh3FtbTR3SOyjL+vkhAQEArKUUTqTHw2qeDSz4b7S/QIG9HArP6d7Clj6aVmOnhUMm"); - a("zv1oKra8sa6psPPw8yn4NaBbVxnV/nrg1WT1ti70axsW88jKVr/MrT9vyek5CoSx88dd89TlzMxH5zORH8+UqwlQQvL5i3WEm0"); - a("CUGGTrbdeSekCQ6h+kN6+kVhOdNdJO6R5I6LZUxIREwJPJ/7rFcdN7tILpXxu7uh6DkFy/oPvMxoKnZ/wI0JhoDGD2PUR+JlAY"); - a("pYpfxgS2fkgfy1dXra2hGR3l/f9Wd+hZPEldEQXXn0kX+nBXM2UvRhdI4lb8/RM+9/N5Ofvczo/XSzwn+PY/fW7nEs64eErlfi"); - a("zH337/Gf/9dcz+9gc3r1y/fKNz/dhifVtVi1vn7om5Dx8mhCs4vLSfpw8r+Xi2b3z2+xuMG0eGAjtFXyp1Zza5YkbVYn2vXn3n"); - a("UpjGz5VaWqJd23cPwX3k2bhugcfvESGS95AGbUWvKTcfKB8Ob5oxzNKq8BRqycx8BWy0UPKN8rO5w7eYqf3v2kz514smOoYffc"); - a("F+9d3/ZZ4zeHDbx/nwbdqPIv9fm0K9SPj/zLxkZ9aPB8H99wQ45DJ+DOkN5UQOdT0LkuBHq0IVR5m4YKRHBCjJzNO0WCrGqn5S"); - a("4f4vxg9tdSQiUSNKv5r4/WK2KJTRqkjnI+b1CATkntcj3mftcYy8/xPzt0D+vvGathY8Jjl93PhwpDZ4s44OzZJ6hBwHJpLLlG"); - a("tgXaXbw6LURglX+7lybezqwPI11gZjN1rkxn2Ev2E3QiKQj8Odb2xwS4T774ouS4g5F6KQtRShClj/ptV91Ni2UNl2hpsLjlwQ"); - a("T3Tdi3cYEEPiTa8HwOY8cRm/PLMXb+EQIwBw7aqNMy70POHAE1kPn/Tof5QUjZOpb9h4ZKG6H82EW9iscvW9PsH/7NEMIGz7u+"); - a("UdJWlrocBLHPlIXS9+l74aQWqWnzYL/bKldPCi1zioEDkHsvt6L0OgpV1ZUUXvfgFFcMAlcGtincz9/qYcfyb96pgXgp6MPTu8"); - a("mfSbU7w+3qbNT8auWCeOGIhenYQ2Shc3SCmSbeiiNChFRBGhcJf0m9072AK82Bzo/p5n+xmL9XmYCgF+M7bXM/M8M3s37x/qeC"); - a("nJB4yoOl429SDSAiLc40R9RDfsouQbgGJ9Rvu8mVgoQNGeznH3uIGFT4OxbJlS+nNQzowQnk/JXy8SCPX4Wv5u6H0jfp8u9olR"); - a("jFyoioL6fYOgKGIl99lTb7pSh2mq4yD1ENPcN8of3YREv5+3w7QD4VDYI+VHYOO5L86XSW3xjbqucL4E3OeFHj6NvBBnmHBRnA"); - a("PqiwKa/oV6svXr94mA1n2bdYpQaiEAP/NXn6v4NWEFpcozwqz6mAqbLZAl36iPj9RrZ9FvUF9Ss3WVIvX6KAD/UukjuZDsR9YH"); - a("AQWm1vfm+j4K+uxcj//B8ak1cJEm7cxVLq2GZM21Cxkx+FvzEEbTuF2n8+uQHFGU3pj/ZeZVBzj/aQBP/++w9K12ZuMr3KFMsb"); - a("KPen7AAuap5Pj8fpfv/2f93+CN1B6WkdjNI8h7qKw2J9jP+HV2E+7hGdkJ/qfMj/ebp6SV0OZ5W1/8+vP3YmNAmsDRQol8i40Y"); - a("oUqOC0UfkPf8vFnBz6fmXMjPX5I5+dBjoNhvG5FDaOtliJT88PqASHpr4siv5svl2vy0Y7zBfT95d+oV67Feqn+dHKsPquIhmJ"); - a("DdcbzA8xb+kMxDcd/JQ2V7f2k2h39nKwechMbPzhkpnov4EomJT0uuI1byXUAS0ubtsem9bIsirvqAyIBmvqe8zgZK5dlBzSuh"); - a("ji9kkHzPec+/TkA9cod0+xMRzf358Mo/U7DqXCZvS0DzHGysDW7oUNpAfCN/X8m3NgADjjCxv4WJ3qv93bfNdMuaikHp+6w7G1"); - a("eK+w7LSA6FfuBb6/p03N72+d0dPf8oEInvnN8xJAddPjmpcFqY/ulWKjvh+uiipP3/Rx7Qh9wt06SGKB3/ABGIYKZYhfxcrS/V"); - a("XfD2KruUxpVeX0LI/LHoiz2Gz7RdS6vTQBT+JjYmk8ZHfWHEggUfwW5qra9CQa8PFBUl6koUxW50JdqVuBMEQVDci+JO3Ii/QP"); - a("D+ANGiuHPRjTsXBcGNfqYTJ53EIQouDie5mXO+b85rQi7cu220iU5Gl9m6fH9NvVT/XkdcctVGxv7K62RofM6pkLdfy4bq//rp"); - a("7+IrP1Bbfu9y8sDZo1TYpNbtV3oTpYMd6GInetiF3diDvdiHA1jAQRzCYRwBbN/dzybnzh47cQYAqvz9nusK96HSwhVwF6ilA9"); - a("kVpxuNpWgMKT0X8oY4/fkbkPl4uQ5Yx8F8aV1u/bIalvVqhbX3uO4NpUPJMKKaQI3661TZrxKnf2tvCbwF55K4DoilDpZ2RSe1"); - a("e5bZa5vsvqCFgOgAma/0OlyKsOu9dV8vueRcFx3tW9n4NfjJ7Fl6/Wh2rX1UwK27qItDmFma9wpjVQnGoIHBdCUGkxUYjJdjsL"); - a("gMg2GIwaiOQS9AKLZCnFY4DnVrOVoTidbYR2vRQ4t5ao1ctBh/+Yr82g20p8vQnoRoj+toLwZoDyXaIx/tnkd/62f++g30pyH6"); - a("kzr64wD9RYn+0Ed/5KHfY7zExtm6tBYc1oJIcz3DD4lfJ35AfEl8cqFv+Y7PzfVxA/G0jngSIB5LxIs+4qGHeLQUcc8lzhriqB"); - a("wluRw5Dn5FXtWYjruZO50jXY9RgIg4EXEi4kTEka/ma/MBO/EjZRNFrPSxMql/lZ9z+JmvlH9A/pL8ffL3yJ/cRy7518h/Vco/"); - a("7zs6Adw6BTw9nuPUDNGkfZP2Tdo3ad+kvXw0zwv09YXy8pSxt8BFsEB2+XrqKq5mfadYklg+sTxiEa/npljzPVvs7x1ngeeUz2"); - a("eKfWPloPJi2pj3s77YrPtig4cNQ0pac9vTWBo4OobW2pvfx53zgLwAdKgtcaw08zoXgSuUrxeKMcns0/0nOg4asxrG+0tA6zLw"); - a("kLp63A2c/LXiodfqninnrJ/b8TWO9Xq5h+UL+Y76+174cRV4fI29cNXYT1LGS/XxKqOPK8R+003WPOXzDc2xMN/X+ljLOl3LXl"); - a("qrfIishxJe5+Nsn3lqZhSx8v5scy6ind7DTM7dBu5SXlD0Ws3fjFXm38xTee7KZ+R8jNSaG8aa1RKrRQz9U7OGjZxa54fGrMxb"); - a("LoHkvMnHohjT8pjZtcXmf2jzXSuZr+FP94GvlKeU/83FPIuVtubRzE3pvEqMeWa8E9jvy2fvn3r0j+8TQQ2B2AJaG/Vt1FLel+"); - a("I+hyWdVEfhkt/nWr5fjz0BvlPwVOe2eJ4W9b/mquzd2l7/lnOmYK96v6u63JJzM2f2s8V+npm2dl92v4Yu5W7NTzFm5Tn7yap5"); - a("hv4UhXH8eey9R4SQn+y9905GRNmrv1227E1WZEYoI1FSyi6RTVmFvEIo8YJIVrwQn64r7nPPPa5x69tzzv0959xznvOsc84vCx"); - a("rqxr/an0uf/w91ydtTDnl9/jDR9qZR9+Z18Vj4r5T4Gck1gOy8JHISnAF/kyNOvixyCNQDafgLXxHpCW5fTjtuzz42dVxKv+7h"); - a("/mtK2viT94ZITXD7eooYFuT8+cj58+Iba8X2T8/pZ8JNXCP0R1uvr8/6Za5ZJufZG895DHX6NrN//+38V98T2Qt6A0+/zn2StS"); - a("efDfr2uDZ/Pnhf5MsDkRFQu++y9UTbzqHB+lh9CKnb7xfNI0WJoeG7WI6H/UXkB0SeiRQDVYBLf517lGkm1mQZf21knobHt2+K"); - a("6Frh3FJYj0usrz4/dGfrL7LNJnl0y/e5LI3k0iZPrmXy5JB3k+H15gT/Lb5YP/jzfZDTVEMvTPlv4lbgI3NK0dCmvp+HcQZGPG"); - a("hNPGhNPGhNPGhNPGgdnF81iH83sIXc2AJ2wF6yTHgWmeocBGp98/HsKlfBCJDGl9o5ROLM0aieT+W3s+Ap+DGGgO/td75s4Riy"); - a("cqlsya3yBj6lPpD6VeovgTeXQf+S5OGai/uc1PiaJoWlCevRhPVowno0YT2asB5NgvWoF/PfdQuo1C2kcj6/OmVwhN9KFVZpCV"); - a("znJDFfuykqm4mcWpcsSv+0F56y1CtQf0Ld5zt+niORX6APldCHSsF+vE5sDlOKqeQuTg2auO6hb0SHYvHgE20LllDZA/Wdr1uf"); - a("nbOkykCwgbY/+F39v4DnPdgArB/wr/OflxPPtDYZnUqRE6Y5y9heTuU1KF7erGeQN+Qhb8gd5g3ud2lz98g7M5+ksc2ppPIc5K"); - a("/sX58V/L4bVAT+/NXK3dqD9VVRWyifwU+Bw1W+fzkf5WngNnXTV+q8YVxVlQugIvgxxsidRTiO8DdzPpuPPB774hu/2pg9nz1c"); - a("TeVLdZV2UBNnnDmFK2a65GN9xeNaKutrqyyGCs8j6Dbqe6BuuafX0891VLLqqqwEzvzJjtHa/tHoWPfUUzlVX6UeVHi2Qi9S7w"); - a("21srY+0q7h2AYq1RuyhtDYOtn44Gifl/ub8mAEffhi5U54ejVmHaFWz515q/f+Ktr3qiYqBZoyB2iatT4H74JmjAUqPCegK6iP"); - a("gP72/Ay+bM3RC6hz3MH5L2e/jLUk7WM5A20LtlCZAk3bZhb8r0A98CdrM6WlymdQBHj0LrW952+tsgacb2V1xb3m1dqotAC3ae"); - a("PjOwDPRdAbJOov1NrBprYqg9rRC1R4hkEXUK8IdbW3uVOR9uROHYiNtBGeXNR3UT/cLp0ele6osgocpo3wFKS8Edzu4J/vO3jy"); - a("dkKHoD6+2fBsAhWBkcsf2UezzipFuzAu+knT3vrgB7Qt2RV7gf7OPubAtx+0A+Ede0jt+YTfZ/vvI/znaUm5RuJdQthX+rzG87"); - a("2kcWeKSIb74QwyzyDzDDLPIPMMMs+Ea/ZH/Vt9iOQ33WJ56qn+KkMG4HegYdu/yJk8Z0uRceSiTc5w32XGMVil8RDGAXXFyp38"); - a("dh98BSnWw8rFm2vdHYYeD8feoT6+2fDcA/WA0w/0ifqB7iOQLXgDv/B0ozwaFAGRdg2i33nI7x/BYuDSGzPv1PFiX5ZKoZHYIN"); - a("Tl68s4fFmDUSpDwXnaKfXqlNeBYyApl7D+uNlo5j2GPmgjPBWoT6P+hLrnbt2ztuZdAvXcxdi81O9b3O/DfXtucrFcgdy+75vz"); - a("EivzECuJl7xHFvYcxanftyaxB52s0hEkfT+NH/Ddk5lyStl75BFSKwe3zdeI2fywGdj8TOwBmmZvux/eorPIx6B/8l+dJbR5Bu"); - a("oBMxfnWnyYTbyfo3IURGzD6HWjuSo9wHn4DjzLJgUp9wNjgC9+X+P3h2AKiMoqJ7LK4fSPLeZhc+DNr21+OTeysuoyX+UQeEKb"); - a("SExLabOzF6pkX0QusuB7j1nUC1A/v8DMzXx3LTynQT2QlLM5xx/KKPuP7y9ROQKeLP7e852lrP0yyrwL/BLlpaAi9fAeyH+/k+"); - a("W6twErVHaAc8B79mPjiD9ux3SwwiqVzGrkt1JT3b/9y51Mkj9X8GCNyrC1+F8gPPepT6e8B6o/c7d4ztHHf4cX1adcMb24s06l"); - a("73piGvR3/yE7CN+VjdgH9LsPXx74cP95rD//HL+ZfTyo9419swrBIoii8PnHLuxE7O7u7u7u7tYXxcbAwsDu7m7sBLuwu1FUDG"); - a("yszxjz2i8+uHA4Z3ZnZqd28i74md+b+Ik8kvk7bLWZ9jyLNCqgrMCol1/f5/Xp+Mo26Ot5du4xrB/AltE/GHO/WsNkGRdQC7CU"); - a("cOKqNDagAbgP4f4qXfZ8zsf/bj89LPvpYdhPZy+d8S03fnMzvuV+Z3NX7Zu+qu2EgDpP5l3jjXe9S2+Id2Vq2UT9ytln7qnM1Y"); - a("DAr/i/g78C0ygL+Ed7KzEjBFOEd3mKJp+nYCIe8Hw648HMgA4A3GoyK6DL4BXArbPcHzgnoCVAXDfwvwwtWFzj4HW488Gftxm/"); - a("B2yNE0/mUofz+GbgQFjGhWbv9+e9/sre5Qs/Vtl+3f5+af0QI5RiNALs18d41z6ifFPfWszabinpXOTrw9utZJL3G0RSu+tOtZ"); - a("YFtGpFQNtX4h93Htw70VoFRN3iDqC3LP1QTr3fp+/LswTOEWiLWWiLWWiLWWiLWbzN8VdpS7+GfZUN9CWrA98dh2JGDqbI5O3z"); - a("9Ab15+ybGHdBOeIQV87N9AlbiA83d1RnY0DJcJcF4sqFuxx6C8/NebkxVh/F/4GtxAn/yjyo3DbSsJ25wNZff8dI/DffQf8Hf6"); - a("zjd+cYrPMpv/iU3w/2v386xvqzI6u/jLg7oPngIPilNpcszNd20ub88eUexq69jF2wlS7bnuar78ewG/P3fqVvObQ/oIUH6I/g"); - a("H8+zf38f/fQh5seHiRv+9THYp5czdMOu+d6RgPYfpS+EfXnY8/vPx327XocfDyjFCdo++FG9WmHLn2TeBTaDH9o6G/P54acCug"); - a("nSgV/xX/90QBuBgDGf+uF8dsAZvk2QDvyqLUv2swFVAwI/8zsPPztBO/B1PVg2Kn688GyeWZynT7rAOgkW13E4Pe52cCB0EN7h"); - a("0n0Tx5Ev48h8iXUMyEc4cdW4GFBb3IcuGHX9t/aoRtsfciWgcyAf+O764V2/HfKLOYhfPzx6GFDfR6wtr76Pse5j1gug3Ad3uO"); - a("u0iRd8W7h/Na1Gv/jT+o3xOqCM4OKrX5urDMXvIlAOWOdYRvv9yubK6KP9/d+0ny8bxOkBEHg/nwCMFVH9vobvJ41+5+tvMG4w"); - a("p/T4vxjUfdXPY99OmGTEm+zdGJTrm34+dAinQ5GdyhHev9OzWWfOu3/+j1mO6E6jYxIA9nYvvzb3tdPaKpZT5/TkkzjftZdtRn"); - a("vx65XlP7ApJm/WM3st/+M22DCz01gQD/xof/M6zyNmcVoK/2r5DcT/mazUDfyjuLNkc6oPBH7kbzXPL4Ge4GfvzpPd6QAQ+OG4"); - a("/6n/NPdOvo43aC6nXmBpTvdL3+wV/MbM7TQV/p3xfThhLoF84FfeUzGPU38QAfzOe+7jP39e0gf/rK1swN910BNY43b2fE4jwB"); - a("pgPQ+X36kB6A+s55fePi/Ac/BNG7PW98Z4nqGg0ylwkTjMcwe+HWtf72ZhpyxFnGqCH+3FPuN5kaJOLYH3Z9nof65/Vq6pijtV"); - a("AfeKOfOd83j2HMQtYX179j7JFPxGLelUD/46nV/PE36WvrOlCFeaNgL7uH53vFhO+LugHPid8+juZZxugHjAp9+fDZr1U5Y+u5"); - a("zTevBV/f/CuvcX3L9kJ22nLXVVpy5gCvjRuUqCak6VwFL8BURc6H5gAbDifcn9MtWdOoIfxfuA50lr8P3C79o8XAN3D2DsNZvr"); - a("qlP4TVXTaRjs82rY5L5fNzQw1g2/sA7ZV8+pfH3eAX/0HzuMYjPGxiZMbMbY2Iyx1v+xpwjXu4FTO9hYh9pngA1+zD/ea/39by"); - a("F9E6ch4GJj36Z/3RYkfVPyB+4R/lfDXMJ/hmZ8v/CvzMcG4rdwc75V+LP52Nf/GprtYw3h0rWm34G/3mP35f9lGkKRhpDfpCF8"); - a("W6eZ4FAbH4+3dY7u3V/lPxT5h438DG3vlLoD6YLf/w8SBhuG0NgwfLbH8dV5nGkzQB5+kX9sc9DB3tf3+Qm8K+uglHUQytpR1g"); - a("HK+gBl/cG2Hv0+hl8vg9zdndr3os11+7YP/2ptaX7P1j3fdu3/Dez+8f3/q+GUDJvfZEff5jM0+QxFPmlbpNt/0+Z56RHD7vzr"); - a("fOPHumd8v38exydb38//JzJtfQeNcHo2kvELNuwuzDB9RzldG0MY+Lv1++Crf4TGOm0cx/wP/tUwecczl51Amxj362Fe47/0JP"); - a("oS+FfDHMR/xCn0yXAgJnXaLPj7ev1szzgQLaSiNQuqaPQv0ahr4jDPzO26+cH/0l7/yhm+/X/2z+2X5jltBflA4Ed2qnyT+n/9"); - a("k1eEaFJJUG1WENWDe4F66GFwquhSM3Q6uBYYhq4HnwRj0Rfh+2ADWjGksGAH+l4cKUxc6RA6ApwEnESXiydNBhfRU+FE8aXb6H"); - a("RwLfAQXQ8eCV6gp8L7QdDZQXQIvgHCou/BIRNIUdAR4PggNvoi/Cwh8aKVSMoGUqHzwUUS40aXg3uDYuhh8BpQDn0RHpaEckDD"); - a("iplUaoSOBzcD7dDt4KGgK3opnCyZ1Ac9FV4LBqPvwdGSkwd0PHgamIheCqdPIS1E54ODpaTc0BHgBqmlXeh2cJuM0tG3Gt4IXq"); - a("C3wFczUQ5ziB9elZXsobfAM3JKpdBL4au5pE7oe3CRPKQNXQ5Ok1eaiU4HBy0orUTnKySlLiKdRaeDN4Pb6C3wLfAQfQ+uVZQ0"); - a("oOvBM0HQubwLPgnCoi/C8YpRF2hYpUA8dDn4EUiGVnHKoyRli54Kbwet0IfgmWVJM3opvAesRB+Cw5SnfNAR4ErgHroefBK8QF"); - a("+Ey1QgDfN4F/wYxECronQaJENfhINUkgqhI8CbQCn0FnhZZer0rYZDVpV6oiPADcEwdDt4CpiIngoXrkZa0eXgcNVJJ7odfAzs"); - a("QF+Em9ag7tDt4OQ1aa/odHAJ8BRdDk5bW9J87sOtQDZ0uzcM3Xl0HVMAgPFBUU4x59hqf/ateAiKYFAEwaAogociKAZFUIy9Kh"); - a("gURfHsRfEQVBtMq6gqXq0Rxdhjf4i9lt8f3/m+pmky986997VNOuU5GKYbvPjhxqxDPhttOuXoCPdUR3wMxuuEv8ZE3eCNK65T"); - a("l/kiTNYZP4gpusZbeSZKriOegT5d57ajXKeu8AwMfMjb+cSj3V+d8M0o6Sr/gCG6wfM9wqxJB8f4u3NEOuYz0KJT/hOxDo41Vo"); - a("zQMXegolP+F+06OM5+QofOeC7G6oLXaTd2XeZ2VHXCjxxvvLrGs5HrOj9/gv2lc17sRNeqQ95slPU82Tzw/Qh1jd85zRh1wX+h"); - a("SQen+zho1jlPGO180FV+DKN0znMxWsdnGC/G6OBMaxWZjvlCTNQZv3uO7+nWBS9+rjNTh7w9enTEV6DQGXfjO53zx+jXBa88xr"); - a("h0iZ/CwIe9D/+D9XRwXhCsiSad8e7nG4uO+WS06oQHXmDt6ZAfRruu8ZgUuso5Mp3zB5igSxe6d6hq/wdPsNrF9ogucYI5usbP"); - a("XGJcOucDLnVm6Qr/hH4dXGb9YMAjfi1/jEG64Lsvd190nRcdayw65I0R6TLvghYd8/WIdZV/RZsOrnBOoF2XeAckOuIj0KEr3I"); - a("lUZ7zEOGtPh/wQMl3jAVe6jzrk9XGPLvPumKxjPh1dOuW70a1r/BZm6oL/wBwddPqncXhbl3gzzNMR74fPdYVPw3c65evQr6s8"); - a("FfN1zgte5foedW28CdbTZY5R1jEfhaE64QyRzvgutOgaz0Cs6/wpRugGL3i1PatDXgPtusy7ItExH4UOnfBFSHXGd2GsrvEcZL"); - a("rO32GCDq+xNjJrSVf4OUzWdW691hzqmDe6zn7RZW673lzpCl8x3lzpjBe8wWuHDvkiBDVv5wVvtN91dpN1NMG60hF3Yj2d84o3"); - a("+zld4osQ6YwfRauu8e8YroNbfB/Era5DR7zjbc4HHfOxSHTCl6NDZzwbqa7zgbf73LrCt2CCrvKrqOo6r3mHedBlXrRqXekSj0"); - a("CPrvAldzkrdMZP4Dud82fo1w1e4m7rRIe8BgY85mPyThikYz4Ky+iEL8LKOuO7sJau8QwM0XX+FE26wTve42zRMfegRVfutZcR"); - a("64J3v89c6ZjvR7sueN37zZXOecQkZ46u8C0Yq6vch0w3+LYH7EFd5esednt1lR9/xP7SOS9Vs6d0yKfgc53wNDR0zos8Zk50yP"); - a("dhwOPGyLs8bp3omN9BSRdcesI+0hyciGadcA0tmoPvMFw3eOku49UxX46ROuPfnvTaoYOn/H4Pqc55m6etBx3xAxiva7z8FOPV"); - a("JT72GWeOTvioqT63TvhjTNEFh9Oc1zrkLTFLR7wf6rrCp6FHp3wdCl3lx9Gnc34TDV3wz/hDB93OKwRPuB7eDAN1xOMR6io/jp"); - a("V1zm9iLV3wzxiig2d9HDTpEm+GZh3xfhimK3waWnXK12G4rvLjaNM5v4mRuuAlnzO3OuQ9MFrHfCtSXeVedOqCl3jevtNl7kJV"); - a("5/w7Jusgd16iS0d8B7p1lb/CLN3gI6abW13hVWeYW13iZvyhI94fQZf34dMxUKd8PUJd5RcxWNf5M5R0gxd/wRmlQ14TZV3mnT"); - a("FUx3wkIp3wC2jRdS7PtNc0B3ugQ8f8AlJd528wSTf46BetK53whejRGd+JQtd4Ovp0nT9BQzd4gZeMV4c8AcGTxsXTEeo6f4XB"); - a("usGLvmyMOuRzsZ5O+VY06So/hmad81wM0wX/hFYdzPLnLwzXJd4UbTribLa1oTN+EKN0jV/DaF3nbzBGNzh61XmqIz4Mk3SFz0"); - a("JNp3wjpugqT0Wucx47x6XojCehX9f42NecM7rKb2PQU66fz3vdeatTnoaSznnQG+ZBh9w51/3TGT+BSOfcQIvmoPVNZ6yOeZe3"); - a("nKE65j6M1A3e6W1j1zGfgDE64S5conPufMd164xPetd4dcLT0K1zPvw9Z6yucD/m6KAnCK7GPJ3xo+jTNe5437XqlA/stTZ0hc"); - a("/BgKe9nVeaZ8y6xFejWWf8L1p18KE9izZd8C0fWc+6wcHH7qNOeBzG6IzvwiW6xjPQqeNP/Bn8U+eUDvmzz4xXN7jzc2PUGYdf"); - a("uo865B706YI3+MqYdYUzzNcZz/zaWKZYS3zmN8aiU2771hmoK1xDWbMXCXtWB5wh0hnPw3Bd8JDv/Xpd5rMwUqec/uA+6hrP+N"); - a("H86jrPbfg5XfBGPxuPLnM7qjrhPkzSDV7nF2tYl/lR5LrGX/Ubu27wm7+7Jl3w338auw7+Mg8Y+Ixx8cS/zZeu8XQM1nX+BCXd"); - a("4CXnW8865NVR1mVuwVAd85GIdMIXokVnfCdiXePpGKHr/AkqusED/zFOHXKKRKd8LVJd5dK/9qfmoIrxmoMnUNU5v4VJuuDgP/"); - a("dMB7wSpugSb4FcR3wDZukqh4F/E6dDvsLXbD/XGYcL+nrGVG/nOzFY1/hAz0Qp6wqfg1ad8vsYrgte39esR+sy74NUx3wKxuqE"); - a("r0amM/Z3uMEEHfLamKTL/ANqusGLe/5JXYf8m2eg9GhfaAp2wcBproF/wTI6Wsz3iqGkMz5pcd9PpxOejkjX+U+06sBzSrbGcB"); - a("3xVFR0zr1IdMHHeW5Jh054V88a6dIxP4C3dc69KHTBf6FPB6E583yShubgWqzVbT75FZR1nf/DUB145sgQRLrMG3iGSIsu8/7o"); - a("0BU+A6lOuYqxmoPHkOmc91/G3OoKX4opOuMnkeucz/cMkVk64yfR0DkvtNwCwR865J0x+Fnj5XNR0ikvvLy51SHvgCYd8XFo1g"); - a("nnaNE5Nw02zzria1HRVf4Ao3TBy6xgjLrENyDVVR644gJBpw55HMbrnIetZPw65nMwWaf8ELp0jV9Eruu8+8rGqyu86irunS7x"); - a("A+jXNT5v1QX8Yc7H4dbVXJOOOcd6mm1OY9QBb4UWHfE4xDrjP9Cmg9WtMYzUES+3hnWlS7wbMh3zq5ig6/wDpugGD1zT59Yh74"); - a("NZOuZjUdcJv4seXfCpa9nLusaz0dB1/gZ/6AZfuLYxPO99ePl1rENd4m3QrCP+GMN0wb9itA7WdSZgjK5xuJ61p0NeG5mOeBQm"); - a("6ITX3MA90mU+Dz065eM2tEd0wud7Jsd8nfItCHP3nadisM75/o2sPV3jjxHrgpfa2DzrkDdAuy7zM0h0ztdt4pp1lb/ARN3g9c"); - a("vOHF3mPdClYz4B3TrhHs/hmKkL7sd8HWzmujBgunnjbTBIR7zt5taMjng4huoK34BIV3nbJmtGR3wIOnSFT9rCmtcJT0RVV/kN"); - a("TNJ1Xm5LZ6Mu8c7o1jFvsZXr1BEfgvm6whdjwAxrkm8Y6jp1laeiWee8/NbutS5xO9p1wuMwWme8/jbmUJd5D0zSMS+2revRIW"); - a("+OeTriFZqtQ13iFMu84P5yN0o6514M0QU/tJ0zQtd4JkbqOn+DUbrBu2/venTMJ2C8TnguJuqC+9GtA8+MWBEzdYm3wRwdcWdk"); - a("7+uMH8SAmT4v92KQLvjhnVyzrvFsDNN1/gatusHVnd1jzcFUXKJzHjzM59Al3gaTdcR3okvXeCbe1nX+BfN0sIvzZFfzpiO+GC"); - a("u/6Dp52xavHTriQ9CmK/w0Ruqcm3a3H3XMLyPTdV5zD/tRl/lfVHWwp33R6t7pKk/DTJ3zBXuZK53yI5ina/wdPtcNXn5vP9Yl"); - a("Phz9OuXJCF7y/rzGPuZTl/l8DNYpz4iNRdf5P5R1sO8CwQEYqiv8GYbpBpf3s981B+9jhC74xv2NXVf5PSS64KWGW6s65Ntwia"); - a("7y9AOsGV3n9Q90xuoyX4+Zusr/oK6Dg1wL5umIj8LnOuFx+E5n3DHC2HXKt6D0srHzKgd7vdAl/h5NusHdh9j7Oud1DnUfdZlH"); - a("YpROeBxG64z3bTMWXeHFD7PvdMhHYpZO+CG8rWv8AQpd8LKHO2N1iS9Gv874YczXNV7vCOt/lmvgvbCWjvkrDNENXrxizeuQN8"); - a("JwXebRaNMpT0KnrvHCR5pnHfKe6NIxP4puXfCmR1ljOuKj0aMT3vBo169j7sKgV8wV92KwLvi5keZZ59yLWBf8F0bo4BjPZvKc"); - a("gorOeC7G64LHHGf965QfRU3XuAfdOmj3e0vM1DGfhLpO+Cr06IzfRqELXut486zL3ImGzvghzNc1fhUDZlt73IdBusHTTnDO6I"); - a("L/RkmXT/RvHLCezrkXQ3XB8SivIzrm7U/yY13hLU82Xh3xkejQCY9DqjPe+xTng465OXHPdMRHY4pO+EnkOudVT3WPdIkPR4+u"); - a("8Gf4XDd45dP8vkJHPA0DXvVrec3TvY7rMqdYWaf8HIbonFccbVy6xHuiRcd8LmKd8cJnuKc65I3Qrst8wJn2u67weZioU97Qsw"); - a("Lu0WXeC3N0zIt0uGc65IsxYI6Pz8+cbf51zr1o0gUn55gjnfAEjNJV/gGjdYMXP9e60iG/iYm64EFj7E0d8kuo6zpPOM9c6SpP"); - a("xYDXfF7uxSBd8OoXuB5d5j3QomOejVjX+c3U9emC/0GHDi505iDVJd4OY3XET13stUDX+c9L3EcdXOpcRaE5OAR9usJXoqEzzv"); - a("GHznn2Zc72130c3utya1XHfC6G6JRvR5Ou8pNo1jn3YpgueJ8rnCc65mMwVifchUznPBcTdcF/4x4djDNGTNYlbkaXjniJK+1f"); - a("HfK2mKUjHo66rvCp6NEpX4tCV3kq+nTOl3Yau874L5Te8Hmv8iwVDNEV7sVQXfA6VxuXLvOZiHXKd6NN1/iYa5zvOuFxGKszfu"); - a("9a49UFb3+dseiI17revOsy74F5Ov6fYrsMlSKKAyg+dhfYhYKFCDY2dtfY3S12K7aiomJ3C3aLLWI3drfPbjGx4zcfDucg+9y7"); - a("996dh8KfV+Kp3sZnkfCSs+Ccc3zXdAGuMNf+65DXo6HexqfRVl/il+iqP3DKee6SjlwYQ3Q53o3R+jA/wQz9gTfOd4/1Nj6L4/"); - a("oSf8Y5HZhXX7zQd02v4BNIeNlrOMki76dT8jmk15c49mJ7q1Py3mXWrw9zDAboyMFyz24deSDG69H8FzN0sMLzBKt0Nt6ATXob"); - a("n8U1fYlbrLSfui3/QNwrftZsdyGk1OW4A9LrPnxprTugIw9f5+z0aF6GOXoFz17vrkbNCTa4hzolD8dpPZpf4pr+wG02+my6Lf"); - a("/AWx1sspcIrnovLrjZenQ5bozMui33Rw49mnchnz7Mh7bZt6j5LzrqYLu/Y5dnl2az1H7f6ch7cEAf5soHvLcOuTuCa17Dh5FQ"); - a("R/6KlDowJ93tsP3RfXgJ+ugV/PKI+6M/cOajzkJn4/zHnIUuwC1xTbflccedhZ7B25DwuvPifye8lw5O+n8S5NGX+Mcp33kdnP"); - a("bsQiUduTVq6bY8Aw115DNoqS/xnTP2RMdw9bPujw65M2boPrwgQq/g/VihD/NSs8rr9ArejXv6MF/FUx3DH/FWB+f8ux5fdMhj"); - a("ENywHj6PhPoSxznvOa9Tcl1k1iGPRx49gzeggN7GRy945uhLPP2i77KewUUuOV9djqdhiJ7BGzBeb+MGZpGn6rb8HAf0B65yxf"); - a("3UIa/BNb2NzyJGX+In15yr/sAZrjuXm86UVyG93sZ3kEfHcJUb1qxDbn7Teem2vA8t9WGOQVcdOc4t90en5LMYoi9xrtvOQhfg"); - a("GlilQ/6HTTq44/uOazobX8U9HcPBXd/rW17DOZFUF+AaSK9Dvo9sOoajed9yOnJGVNPZuDtC3YcnY4CewTcxXMdwx/vuie7D17"); - a("BNx3C9B55lui33wnHdhxfhnF7B0YzuNR35JOLe9tk5eYx91il55CNr1qO56GNr0+W4KxrqPjwDLXXkHeioD3MMeujIwRPr15Gz"); - a("YbiOXA7jdeTmmKrbcoKnnm86JVfEXh3yNBzWM7jWM/dHh3zlt2eljuHgjzXficPeK0JHLoc8OoY/ooAO/rrDKK7L8V2U0zH8Ew"); - a("118M/nRksdcneM1n34JCbpSzwyMJejR/MyHNcr+A/OaQO1QTbc0pGvIEbHcIrYZpl0Si6LD7oc/8J3Hc3SZkRw189y6rjmHaLm"); - a("TSitt/F9hDqGf6KpjgZbq8Y3d6FDnoNJegX/NB87Qwep/TmO6xVcOo0163K8Ftf0Nv6MezpIGzuojqc65G94q4N01okvOhuvM8"); - a("/6W2/jm8h2z9r4D/LowNzr3oLmL/Rh3lgotvvu9fwG4/UHzl84djBVF+CxmKNn8Cqs0Nv4EdbpD1y5iLPQIffHAT2aX+G4/sBZ"); - a("i5oh0dm4JG7pcrwBMXobn0fc+86Xc5tVTaoLcHnk0yH3RBHdhz8Ws3c6mlfNgrY6Gw9GVz2al2KSXsHfMEMHJbwe23Q2jsFeHT"); - a("lzSXuus3ElPNVt+SXe6g+8pZR7orfxZcR94Gd5UWlr1it4P4row1ywjHXqctwcHXVbjmXWs4dOyXmxRBfg5VilV/B+nNOHuV1Z"); - a("d0OP5kWI+9Br+DuSapc4OIoC+hLPKu9+6hU8q4KzjpqvYYaO4Z9YoIOK7j9WRF0pdjAI1/QK3lbZPujInavYB92H5yJpjLXxoK"); - a("q+J3o0r0YRfYkzVfPZdQHuikp6Bt9CqD9wYjOVLXVK7oqOug/nreHsdAFuhHW6LQ/DNj2ac9d0droAt8U9PYOv4amO4fy1rFkX"); - a("4Mn4olfwfvzWhzl9bfv5yLlzZeTRIfdFAT2aU5l9LK6zcXn00CHHN+s4QKfkhlil2/IubNKH+aQ5yJ36EverZ316NM+qb516Bf"); - a("dr4Cz1aO7c0DPnsX3grI2sT2fjno2tTffhJSiuV/BBlNOH+Tmq6Q+8oYl91tv4LProS7zbrOIQfZhHNrO3ejQvwmm9gic3953V"); - a("M3gDgif+Hq7Wwtp0yL1RRPfhv62ctQ5bW39b76v78CS01TN4A7rqbdylnfXoPjwbC/QKXtEeOnLRDvZKl+NhuKdH81o81dv4Hd"); - a("7qD1y7oz3UIa9C8NRr+AES6hhO3sl8jk7JDZFet+W+yKZH8x7k0Yf5KoroGP6J0jow97cVlfQ2fowh+gMn7mK2U6fkZZikV/B+"); - a("7NSHuU5Xz0kdcne81H24RTe/j3RbHoH0z6yHm/e0Nt2WR6GhHs3xevnu6JR8CR115NfooT/w/t7upz7Ml7FEx/DRPvZIX+Lsfd"); - a("1VXYAbYKduyzX6WacOOVl/69QpeSISPnem/B4p9QeuM8CadcgbkU1v4+QD7adOyZVRQIc8CcX1DD6Ecvowf0I1HQwya4tQZ+MS"); - a("aKrL8Xa01X0Ge5YOca90Si6MAXobJxoaOxiuU/IrjNcfuNgIv+N0Ob6KdTqG44z0PNEpeYo5vcN6Bi/BW72C3+OL/sATxnqG6B"); - a("k8c5zn4Qvvyz3+s1v3vAxFcQDG6+UDGMQgTdyhG0OFUaJJV0MtImLoILFWYjJVgkjjpQiplrjES5n6EYiRoYsQi8tUYiAxivj1"); - a("e/QmT55naXL/555z0iWz6xz3Lts/OuAXjOiIkyvtsTHd9DgmdZbnkdV5XiyYSxf5ZM29rWt8g6qu8ytq+ou/172/jm3Yq7hv9q"); - a("a7GZEOeBoNneU5/Og87xXNokP+2/JNG3677d5DQgecxoDOcHzXXDrgNGZ0httK5tddPISSTvHjvnOtI+4oezfdxZWKM65DvkXs"); - a("3Vw8e2iP6RzvYFiH3H9kDXWS746tj67z6Klzp1O8cOZ/i85z4dze1kV+xrWOuOfCO+iAJ/Ck6xyrult006v41EU+wK8O+Q2dH9"); - a("ac+y59dx3wILp1iqcQ11l+QEJHXL6yt3XraT3/7MitSwMBAMbhQw6DGBYWRNRkGgYxiJhMi7JgEDEaLl0WkWEyH5dFjg38OD8Q"); - a("kywtikFMC8ZhWhCjXPLgHlzZn7C3PC+/6cxaWfj/aw9hEHXD4Lczbstlq12FwUJ33BplWy/bpJ3pCTt8Yp8fHPKHM9eVdTa4wz"); - a("1GbDPlJXO+8I2fHLHg/E3lIte4zRYPGfOE50x5wZw9vnLAIUcsOHdbucQNNnnAmKdMmPGRPQ74zdm8coVb3OURY7aZ8p59vvOL"); - a("Bet3lavcZJP7jHjMhBmf/wSlj0DpG1D6FZT+A6U51kDjE0rrgGkEcILyw6B0Gpp8DZTfBaXnQOl1UHoPlD4Hpe9A6XdQmmkty2"); - a("i+GM0Xo/kCR75AAPfUkuCSFI/EvJScVCjfOT+vGEA31e62DcPAvJrnuliAeDFqY/6t2NdUgywZFFXUe/pJFoUlQfpLvCPFj6Pk"); - a("DFo378xgfCR/KxOQ/SfluSFylLz9A35T2qP5mrCydjYxzZfmjtwE70s9RRzWo313Vam4LLGDk7YoTCCCLfeO8x07fBDUHMlnsa"); - a("mH6BXUYnG05bg4UDB41Qa/1BIL3bK7AJkbSfMeJZnEPNTGeYnLcydH57RlFCUaO5/fE12U3TxjSYNGfHIqTnghRdso/tRkNc+U"); - a("2z68EiARCTlaFLfRp67Yb9QElVsb7zZ1DrwGrjvJem7aYhdRfkKtiUlnZYybxE4VZcc7LbbQ0erL5kv1rH3Zq6B9ukkZySFIsv"); - a("QGWNMZ/Ao7y5WkrQ/LTb4BtGh7W2JUmqMKvbbXOOTlDybOOueIjrQjzbLde+7xvUiN8wr7Hx39Cy7hegV1BA/LZUo0nxFVh9wl"); - a("eIdlx8U+Ws1aGf0XNUUrDtxjkkf/AgN+wjeWQY900gvqE0/4gbZvrrTBsP6xMQY36hn1h6LIFnNwxS9/tqq7+9+d8Rv/I6OMeh"); - a("UGYSjsX8PtmtyEp+udeybamUUF0o3M/XuPtCTiHs9HCxR6em9cnBMT8EzPWZgN4ZbiIfl8Gm7Aq0afRljX3Tu/jP4iTMXPM9eX"); - a("HnixkPhM/2ukyexqmq23pdb5a3JXXTlgu7Jiao3RYtRLheR/wS+EoRDtwFvRxVuqizt7bBuWqR0Zrxp4NcpPxBPKlpMwmqJjOs"); - a("6MLiwRub1JBphW0gD4i2OFdV6/yVMC077VZwdLDMixJhLTTcQtDQ6/a5vfNte+inflKEs+s+xhQaL/aBOls2UfpFL0TRcj8T4N"); - a("Q79TYsNSEY1BwleGqTIqJevVTHzJNxXojuRiBiRXgEqJ7NSivNQcYyO9lJwcBmAqTSwtgXJKgR6HMocp0NjAAj7bhwmKTYB8Gy"); - a("B2AeJgf58w1yCw78FnwASIActvoHgYSA80XPNzylKLQNmLAcwMKK2qykk1NGUYBQBm7I7vcSAKw/iDweJgMVgMFgMLxWBhIVgM"); - a("LBSDhYXgmZfMnJnMSzCwUFgYLAYWisHCAwMLO9vffog9X+H6H7n/45vzrpkD7oDAHkqooIYTNHCBKwyAMMMCd4jwgBWesMEn/A"); - a("ZCj/QLbehXeqHfaE+/U6CWLvQnfdBfdKOf9MDPvFJHVauTatRZXVWvZrWou4rqoVb1VJt6qaQ+sMAdEtxjiQc8YYNnbPGCHV6x"); - a("xxsOCDjjD4z4woQfutA7TXStT7rRZ93qi+70Vff6pgcNGvWsF33XUT/0qp960y+d9IcpzM4QszelOZjKHE1tTqYxZ9Oai+nM1f"); - a("TmZgYDBs3dHKZ26qZ+GiaclilO67RNaSossaWtbG0b29rO9nawaBcb7Wo3m2zhiCtd5WrXuNZ1rneDQ7e46Fa3ueQKT3zpK1/7"); - a("xre+870fPPrFR7/6zSdfBBLKUIU6NKENXejDEDAsIYY1bCGF3Omed9f8lAWQf5UaaKGD/l1pgQhrrpOgoISWtKJ17tPSLtcZKO"); - a("Y2ka65TKIFI6xkFatZw1rWsZ4NDNnCIlvZxhIrOOElr3jNG97yjvd84MgXHvnKN554IYgoRSVq0YhWdKIXg0CxiChWsYkkipGM"); - a("h7EajyOO83gf47iOz/E1prGQO7mXpazkUZ5kI1t5kVfZy0GCnOUio3zIp9xkkh9qp4gq1eGvoLefi+qyoJsChW9F2dBbUPbz1n"); - a("PACuvsJ+t52/lDmd3yyAmGURgmqaEOuRKJRK5EIpErkUjkJDUkNUjkypev7bvDpxyJRCJHIpHIyp59OJmk2512+w/Iw3XumcxQ"); - a("yCd8iAy6EBWHCYoYzxeYWM7X83rezz/PRmM1D43duM1j4zVB89SETQwvSZNBjGpGmJmaBWrWZocbo7Ugx25d2PHaAHrCNoafpM"); - a("0gSLUjDE3tAkVru8OR0VmQZHcuLHldAE1hF8NT0mUQpboRpqZugaq12+HK6C3IsnsXtrw+gK6wj+Er6TMIU/3S770FW/bgQpc3"); - a("BPAVDjGEJUMGY2oYoWwaFjhbh/1N2oLf/d+Cro4iuLDmSRFCFcNbojKIU0cXWIUd7ozcgjw7d2HPywPoC/MY/pI8g0CVjzA45Q"); - a("sUrvkOh0ZhQaJduLDoFQE0hkUMj0mRQaQqRpicigUq12KHS6O0INMuXdj0ygA6wzKGz6TMIFSVI4xO5QKla7nDqVFZkGpXLqx6"); - a("VQCtYRXDa1JlEKuqEWanaoHatdrh1qgtyLVpN6if6rCO61Od1Fn9XCtYvkDzctNsvNhw7MMwbrXifw3czFSs6HE1KWmJK624js"); - a("PL+LxNxOukucJlNtzDLJzbJSLeIuU1dDHKJTZewi6TSuH5Vzz519rBs36rv8tzRthK9pfSPkplT+iqRlkvekJbF33Vq97YWPv1"); - a("8dXDdu6vxpSW+u/rybXM5wVbMbEUV/YRcSEpN6JlJVfZxwNW4XMXEZeRchuTrMLoHK7B5x4iLiLtNLYwo6/HBhyuwOcOIiwhQ2"); - a("XHfkFhjcEcjiU43IIvazjJDi7Qvx3+d/wfj84a6v3bjGA/VZrmN6o36R7vF282EetTvtG4SeUOnftFJG9VU/ZG2yZ1O/TtU3hE"); - a("4ymUa/ie0eDDtUPZPm1H1J3Ct4aMudrg+jDtULVP1xFlp7StoXuG600a7UqhfWl0KJU+SaczKbWWVk8v15cdpX74YbPSgXQ6kl"); - a("In0upnqfU/P/Uh0tP+H5/91Ck2N3FpfUKmITX30PHonk7WfEPL34w6KLkvSlPWe2a/NxbcRMNdURq3qcjU7PbMcm9st8l6i1V+"); - a("D1CdhtHl1muzv6OV3U6PcovbSz/1m8iF2Vu9I/Y7ZcE1Gz6z4nRs4L/eLx859lnziD1PWfTbd70PhD9KtU55Bt2aLZ9Z87vW77"); - a("WMbZ//dwMs/VyuWIF5zz/7rln4mY2XNcgSsIHf9bPtM+u+se+/2juz0JnCMIwfBh1ZGkVOpCypIcufLCdLja1EMrZMoZALW7IU"); - a("QvYsyXYhU8I5M2dmzpnvnBmKsu9ZUxPRlCXhYkppkCX7872+rN98thsX5mbu3+f3PO/zfk0N94LBGws5Ik4+SIB83lNK1FQq1F"); - a("V0aiutqa+YEi+4nH+Qryae2u73qQzued81/6DrRqnLrPyRe9FjdNFkIqLLDGUxRVqTK+AG3mZMSVb/xBGKDN9H7qgEv+OJi0j0"); - a("Uv4evFGRJPtkcof1vR/C/Leof+eHMFI+Tns7oeA/StSvVHJuEtuLQbMrmstF0V3Kor3oToToBtcKoj917biC5jDxG5NluCBZI3"); - a("qjyux+RfSaKl4/sxpV0QpKOaE1RKc8o0tEqKFg8hRbV9iC3DtZuAB9nxfe8fuodUg7AH0Nq7PVE4pOs2ZDyx3WbusQ6Vex6tmN"); - a("oV8/ezA0nG8vQZZ59n6oeMt+AP3qJ5vwu4jU24iU2p88DN1qIZE6pLohi5YhfdKpADrdTj2EQhGkzgxnHvJmp7MXulx1bkCP9l"); - a("BjRHoc9utG6HA//RQbtUWmLfJjRGYcEmR9ZiumfwfJUTfbCIkxJDsCc1+RXY95H86exo58mf2QNdyebn+kwyJ3BWZ80D2OJHjq"); - a("vnF1r43XAfOd6E3DdDd7OzDVx9573DBdcr1wvSzILcUkg9xBeP1R7hk6WEfWHVPciJmdZpew016w9+hcXf3e1LngWe5WhU9X0t"); - a("VxKihX3V7TyZ+uwpEx2ljbZDuqJqRN/KprmeTExYpd1Jo69GS0ZlwV0l2k0wYaqtg5lSR3YI1stwg3lsiDhmK7nCIHaopm5ZIH"); - a("y2mxQyStahv5sKjYIYvJiYcUvWm66ErfNnh6JUFbing1XpycmPirTREhL06XbATRk7AXIuhIMcVOeOVzwsyvs1/ctK64asvEV0"); - a("SR/UXiKyzau6wNHSK+6L0kGtIWg63qOW9xwsCWaPCSC20DEXZR0W/mEmH7FD0mToQlZAkvLtShxNcGSbrzq1THXVpDfM1VtBVD"); - a("dJRqGX/vF1K+THxFFL2kSISFKePlb3CniDBN8dK2T9yH1buHxekCV7p4O+Fkmd/ciduIraKyYcgpK1GOGX/cMUxxM1Zv3VospA"); - a("3+hZ6RoIQrfbkgFS8EkqwDkZxG84/6dYxyb1uV3qG+L/eB0Fd0V5pgUn5LEp/fNmjKPrz5EaGuokHHspjd5JBm4WtKbiaosXIe"); - a("culJrhZrwtqwbmwAG8WmsHlsFduOLDrCzrMSJdAg0DHLX4D82eWnkDxX/OvooW/9OqCjZ9AfVMwJFoIGJ/DROW8HD5E3zfKtsM"); - a("eG58eAg2X5tdD/YP44dH+af42c6VToAb1nFOYhXfYUMlD7ZuEuV3luSDvH/6vFag5th1mjoelSaw009a0DVpG2lW63tNtBz5H2"); - a("eOgIDaHfGfsydtQL+71tJLskeyE/piZnQjmoBsUuJ69BqzqphlBoYGoYttPy1DrspKOps1Ao7LSFGmOcCdBhvbMVbfCkcwE58d"); - a("L5gBbYPd0HaixIL4UKJ9LnkQu4YDD77pm+mPvUzCz0v9HeBLh1tbcJPuU/SAppY/GFDUBOnay4lHVW22/gG+TDmL8e6X6MXr6b"); - a("wnWjgknCaZz5kNYUX9iQlGM8tbT/n3/68xHeVZKEADYEAA=="); + var shift = (11 - Hole[n]) * 4; + var a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] + 4; + State[n + 1] = State[n] - a + (a << 16); + Move[n + 1] = 'd'; + Cost[n + 1] = Cost[n] + (RowIndex[a >> shift] <= Hole[n] / 4 ? 0 : 1); + } + + void Up() + { + var shift = (19 - Hole[n]) * 4; + var a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] - 4; + State[n + 1] = State[n] - a + (a >> 16); + Move[n + 1] = 'u'; + Cost[n + 1] = Cost[n] + (RowIndex[a >> shift] >= Hole[n] / 4 ? 0 : 1); + } + + void Right() + { + var shift = (14 - Hole[n]) * 4; + var a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] + 1; + State[n + 1] = State[n] - a + (a << 4); + Move[n + 1] = 'r'; + Cost[n + 1] = Cost[n] + (ColIndex[a >> shift] <= Hole[n] % 4 ? 0 : 1); + } + + void Left() + { + int shift = (16 - Hole[n]) * 4; + ulong a = State[n] & (0xFUL << shift); + Hole[n + 1] = Hole[n] - 1; + State[n + 1] = State[n] - a + (a >> 4); + Move[n + 1] = 'l'; + Cost[n + 1] = Cost[n] + (ColIndex[a >> shift] >= Hole[n] % 4 ? 0 : 1); + } + + public FifteenSolver(int n, ulong g) + { + Hole[0] = n; + State[0] = g; + } + + public void Solve() + { + for (; !Scan(); ++maxCost) + ; } } diff --git a/Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js b/Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js new file mode 100644 index 0000000000..1904d1d75b --- /dev/null +++ b/Task/15-puzzle-solver/JavaScript/15-puzzle-solver.js @@ -0,0 +1,97 @@ +class FifteenSolver { + constructor(n, g) { + this.Nr = [3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3]; + this.Nc = [3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2]; + this.n = 0; + this._n = 0; + this.N0 = new Array(100).fill(0); + this.N3 = new Array(100).fill(''); + this.N4 = new Array(100).fill(0); + this.N2 = new Array(100).fill(0n); + this.N0[0] = n; + this.N2[0] = BigInt(g); + } + + fY() { + if (this.N4[this.n] < this._n) return this.fN(); + if (this.N2[this.n] === 0x123456789abcdef0n) { + let moves = ''; + for (let g = 1; g <= this.n; g++) moves += this.N3[g]; + console.log(`Solution found in ${this.n} moves: ${moves}`); + return true; + } + if (this.N4[this.n] === this._n) return this.fN(); + return false; + } + + fN() { + if (this.N3[this.n] !== 'u' && Math.floor(this.N0[this.n]/4) < 3) { + this.fI(); + this.n++; + if (this.fY()) return true; + this.n--; + } + if (this.N3[this.n] !== 'd' && Math.floor(this.N0[this.n]/4) > 0) { + this.fG(); + this.n++; + if (this.fY()) return true; + this.n--; + } + if (this.N3[this.n] !== 'l' && this.N0[this.n]%4 < 3) { + this.fE(); + this.n++; + if (this.fY()) return true; + this.n--; + } + if (this.N3[this.n] !== 'r' && this.N0[this.n]%4 > 0) { + this.fL(); + this.n++; + if (this.fY()) return true; + this.n--; + } + return false; + } + + fI() { + const g = (11 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] + 4; + this.N2[this.n + 1] = this.N2[this.n] - a + (a << 16n); + this.N3[this.n + 1] = 'd'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nr[Number(a >> BigInt(g))] <= Math.floor(this.N0[this.n]/4) ? 0 : 1); + } + + fG() { + const g = (19 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] - 4; + this.N2[this.n + 1] = this.N2[this.n] - a + (a >> 16n); + this.N3[this.n + 1] = 'u'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nr[Number(a >> BigInt(g))] >= Math.floor(this.N0[this.n]/4) ? 0 : 1); + } + + fE() { + const g = (14 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] + 1; + this.N2[this.n + 1] = this.N2[this.n] - a + (a << 4n); + this.N3[this.n + 1] = 'r'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nc[Number(a >> BigInt(g))] <= this.N0[this.n]%4 ? 0 : 1); + } + + fL() { + const g = (16 - this.N0[this.n]) * 4; + const a = this.N2[this.n] & (15n << BigInt(g)); + this.N0[this.n + 1] = this.N0[this.n] - 1; + this.N2[this.n + 1] = this.N2[this.n] - a + (a >> 4n); + this.N3[this.n + 1] = 'l'; + this.N4[this.n + 1] = this.N4[this.n] + (this.Nc[Number(a >> BigInt(g))] >= this.N0[this.n]%4 ? 0 : 1); + } + + solve() { + while (!this.fY()) this._n++; + } +} + +const start = new FifteenSolver(8, '0xfe169b4c0a73d852'); +start.solve(); diff --git a/Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math b/Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math new file mode 100644 index 0000000000..3a7bdde6e4 --- /dev/null +++ b/Task/15-puzzle-solver/Mathematica/15-puzzle-solver.math @@ -0,0 +1,178 @@ +(* Constants for the correct ordering and board position mapping *) +correctOrder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}; +rowOf = {0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3} + 1; (* +1 because Mathematica uses 1-based indexing *) +colOf = {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3} + 1; (* +1 because Mathematica uses 1-based indexing *) + +(* Function to estimate remaining moves using Manhattan distance *) +EstimateMoves[board_] := Module[{h = 0}, + Do[ + (* Skip the empty tile (0) *) + If[board[[i]] != 0, + (* Find where this tile should be in the correct order *) + correctPos = Position[correctOrder, board[[i]]][[1, 1]]; + (* Calculate Manhattan distance: |current_row - correct_row| + |current_col - correct_col| *) + h += Abs[rowOf[[i]] - rowOf[[correctPos]]] + Abs[colOf[[i]] - colOf[[correctPos]]]; + ], + {i, 1, 16} + ]; + h +] + +(* Find the position of the blank tile (0) *) +FindBlankPosition[board_] := Position[board, 0][[1, 1]] + +(* Generate possible moves from current state *) +GenerateMoves[board_, movesSoFar_] := Module[ + {blankPos, possibleMoves = {}, newBoard, newMoves}, + + blankPos = FindBlankPosition[board]; + + (* Check if we can move left (blank goes right) *) + If[Mod[blankPos, 4] != 1, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos - 1]]; + newBoard[[blankPos - 1]] = 0; + newMoves = movesSoFar <> "r"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + (* Check if we can move right (blank goes left) *) + If[Mod[blankPos, 4] != 0, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos + 1]]; + newBoard[[blankPos + 1]] = 0; + newMoves = movesSoFar <> "l"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + (* Check if we can move up (blank goes down) *) + If[blankPos > 4, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos - 4]]; + newBoard[[blankPos - 4]] = 0; + newMoves = movesSoFar <> "d"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + (* Check if we can move down (blank goes up) *) + If[blankPos <= 12, + newBoard = board; + newBoard[[blankPos]] = newBoard[[blankPos + 4]]; + newBoard[[blankPos + 4]] = 0; + newMoves = movesSoFar <> "u"; + AppendTo[possibleMoves, {newBoard, newMoves, Length[newMoves] + EstimateMoves[newBoard]}]; + ]; + + possibleMoves +] + +(* A* Search algorithm for solving the puzzle *) +Solve15Puzzle[startBoard_] := Module[ + {openSet = {}, closedSet = {}, current, children, bestMoves = {}}, + + (* Initialize the priority queue (Mathematica doesn't have a built-in priority queue, + so we'll use a list and sort it each time) *) + openSet = {{startBoard, "", EstimateMoves[startBoard]}}; + + While[Length[openSet] > 0, + (* Sort the open set by total estimated cost *) + openSet = Sort[openSet, #1[[3]] < #2[[3]] &]; + + (* Get the most promising state *) + current = First[openSet]; + openSet = Rest[openSet]; + + (* Check if we've reached the goal state *) + If[current[[1]] == correctOrder, + Print["Solution found!"]; + Print["Moves: ", current[[2]]]; + Print["Number of moves: ", StringLength[current[[2]]]]; + Print["Open set size: ", Length[openSet]]; + Print["Closed set size: ", Length[closedSet]]; + + (* Format the final board *) + Print["Final board:"]; + Print[Partition[current[[1]], 4]]; + Return[current[[2]]]; + ]; + + (* Generate all possible moves from current state *) + children = GenerateMoves[current[[1]], current[[2]]]; + + (* Process each child state *) + For[i = 1, i <= Length[children], i++, + child = children[[i]]; + childBoard = child[[1]]; + + (* Check if this board is already in the closed set *) + If[Not[MemberQ[Map[First, closedSet], childBoard]], + (* Check if this board is already in the open set *) + existingIdx = Position[Map[First, openSet], childBoard]; + + If[existingIdx == {}, + (* Add to open set if not already there *) + AppendTo[openSet, child]; + , + (* Update if this path is better than existing one *) + existingIdx = existingIdx[[1, 1]]; + If[StringLength[child[[2]]] < StringLength[openSet[[existingIdx, 2]]], + openSet[[existingIdx]] = child; + ]; + ]; + ]; + ]; + + (* Add current state to closed set *) + AppendTo[closedSet, current]; + ]; + + Print["No solution found!"]; + Return[{}]; +] + +(* Example usage *) +startingBoard = {15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2}; +(* startingBoard = {0, 1, 2, 3, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12}; *) + +solution = Solve15Puzzle[startingBoard]; + +(* Pretty print function to visualize a board *) +PrintBoard[board_] := Module[{}, + Grid[Partition[board, 4], Frame -> All] +] + +(* Visualization code to show the solution step by step *) +VisualizeSolution[startBoard_, moves_] := Module[ + {currentBoard = startBoard, frames = {PrintBoard[startBoard]}, blankPos}, + + Do[ + blankPos = FindBlankPosition[currentBoard]; + + Switch[StringTake[moves, {i}], + "l", (* blank moves left *) + currentBoard[[blankPos]] = currentBoard[[blankPos - 1]]; + currentBoard[[blankPos - 1]] = 0, + + "r", (* blank moves right *) + currentBoard[[blankPos]] = currentBoard[[blankPos + 1]]; + currentBoard[[blankPos + 1]] = 0, + + "u", (* blank moves up *) + currentBoard[[blankPos]] = currentBoard[[blankPos - 4]]; + currentBoard[[blankPos - 4]] = 0, + + "d", (* blank moves down *) + currentBoard[[blankPos]] = currentBoard[[blankPos + 4]]; + currentBoard[[blankPos + 4]] = 0 + ]; + + AppendTo[frames, PrintBoard[currentBoard]]; + + ,{i, 1, StringLength[moves]} + ]; + + ListAnimate[frames] +] + +(* Uncomment to visualize the solution *) +(* If[solution != {}, VisualizeSolution[startingBoard, solution]]; *) diff --git a/Task/15-puzzle-solver/Zig/15-puzzle-solver.zig b/Task/15-puzzle-solver/Zig/15-puzzle-solver.zig new file mode 100644 index 0000000000..e566437561 --- /dev/null +++ b/Task/15-puzzle-solver/Zig/15-puzzle-solver.zig @@ -0,0 +1,187 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const PriorityQueue = std.PriorityQueue; +const AutoHashMap = std.AutoHashMap; + +// Constants for the puzzle +const CORRECT_ORDER = [16]u8{ 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,0 }; +const ROW = [16]i32{ 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 }; +const COLUMN = [16]i32{ 0,1,2,3, 0,1,2,3, 0,1,2,3, 0,1,2,3 }; + +// State struct to represent the puzzle state +const State = struct { + est_tot_moves: u8, + moves: []u8, + est_moves_rem: u8, + allocator: Allocator, + + pub fn init(allocator: Allocator, order: [16]u8) !State { + return State{ + .est_tot_moves = estimate_moves(order), + .moves = try allocator.dupe(u8, ""), // empty + .est_moves_rem = estimate_moves(order), + .allocator = allocator, + }; + } + + pub fn deinit(self: *State) void { + self.allocator.free(self.moves); + } +}; + +// BoardState represents the entire game state +const BoardState = struct { + order: [16]u8, + state: State, +}; + +// Find the index of a tile in the order array +fn findIndex(order: [16]u8, tile: u8) usize { + var i: usize = 0; + for (order) |v| { + if (v == tile) return i; + i += 1; + } + @panic("findIndex: tile not found"); +} + +// Estimate the number of moves (Manhattan distance) +fn estimate_moves(current: [16]u8) u8 { + var h: u8 = 0; + for (current) |tile| { + const ci = findIndex(current, tile); + const gi = findIndex(CORRECT_ORDER, tile); + const rd = @abs(ROW[ci] - ROW[gi]); + const cd = @abs(COLUMN[ci] - COLUMN[gi]); + h += @as(u8, @intCast(rd + cd)); + } + return h; +} + +// Make a single move (swap hole with neighbor) +fn makeMove( + allocator: Allocator, + parent: *const State, + order: [16]u8, + dir: u8, + idx: usize, + new_idx: usize, +) !BoardState { + var new_order = order; + new_order[idx] = order[new_idx]; + new_order[new_idx] = order[idx]; + + const rem = estimate_moves(new_order); + const mv: [1]u8 = .{dir}; + const combined = try std.mem.concat(allocator, u8, &[_][]const u8{ parent.moves, &mv }); + + return BoardState{ + .order = new_order, + .state = State{ + .est_tot_moves = @as(u8, @intCast(combined.len)) + rem, + .moves = combined, + .est_moves_rem = rem, + .allocator = allocator, + }, + }; +} + +// Generate all children from a parent (takes *const so we don't double-free) +fn generateChildren(allocator: Allocator, parent: *const BoardState) !ArrayList(BoardState) { + var children = ArrayList(BoardState).init(allocator); + const hole = findIndex(parent.order, 0); + + if (COLUMN[hole] > 0) { + const c = try makeMove(allocator, &parent.state, parent.order, 'l', hole, hole - 1); + try children.append(c); + } + if (COLUMN[hole] < 3) { + const c = try makeMove(allocator, &parent.state, parent.order, 'r', hole, hole + 1); + try children.append(c); + } + if (ROW[hole] > 0) { + const c = try makeMove(allocator, &parent.state, parent.order, 'u', hole, hole - 4); + try children.append(c); + } + if (ROW[hole] < 3) { + const c = try makeMove(allocator, &parent.state, parent.order, 'd', hole, hole + 4); + try children.append(c); + } + + return children; +} + +// Compare function for priority queue +fn boardCompare(_: void, a: BoardState, b: BoardState) std.math.Order { + return std.math.order(a.state.est_tot_moves, b.state.est_tot_moves); +} + +// Hash an order into a u64 +fn hashOrder(order: [16]u8) u64 { + var r: u64 = 0; + for (order) |v| r = (r << 4) | v; + return r; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var open_states = PriorityQueue(BoardState, void, boardCompare).init(allocator, {}); + defer { + while (open_states.count() > 0) { + var item = open_states.remove(); + item.state.deinit(); + } + open_states.deinit(); + } + + var closed_states = AutoHashMap(u64, void).init(allocator); + defer closed_states.deinit(); + + const start_order = [16]u8{15,14,1,6,9,11,4,12, 0,10,7,3,13,8,5,2}; + const initial_state = try State.init(allocator, start_order); + try open_states.add(BoardState{ .order = start_order, .state = initial_state }); + + const stdout = std.io.getStdOut().writer(); + + while (open_states.count() > 0) { + var current = open_states.remove(); + + // goal check + if (std.mem.eql(u8, ¤t.order, &CORRECT_ORDER)) { + try stdout.print( + "Open: {d}, Closed: {d}, Moves: {d}\n", + .{ open_states.count(), closed_states.count(), current.state.moves.len }, + ); + try stdout.print("Path: {s}\n", .{ current.state.moves }); + current.state.deinit(); + break; + } + + const h = hashOrder(current.order); + if (closed_states.contains(h)) { + current.state.deinit(); + continue; + } + try closed_states.put(h, {}); + + var children = try generateChildren(allocator, ¤t); + defer children.deinit(); + + // ↓ Here’s the fix: shadow each child into a mutable `var child` + for (children.items) |child| { + var my_child = child; // now `child.state.deinit()` sees a `*State`, not `*const State` + const ch = hashOrder(my_child.order); + if (closed_states.contains(ch)) { + my_child.state.deinit(); + continue; + } + try open_states.add(my_child); + } + + current.state.deinit(); + } +} diff --git a/Task/2048/BQN/2048.bqn b/Task/2048/BQN/2048.bqn index a73e95c7b4..cb0a27ed3b 100644 --- a/Task/2048/BQN/2048.bqn +++ b/Task/2048/BQN/2048.bqn @@ -15,7 +15,7 @@ Spawn←{i←•rand.Range∘≠⊸⊑(0⊸= /○⥊ ↕∘≢)𝕩 ⋄ (•rand Lose←Left∘Right∘Down∘Up⊸≡ # Losing condition, no moves change the board Win←∨´·∨˝2048⊸= # Winning condition, 2048! -Quit←{•Out e∾"[?12l"∾e∾"[?25h" ⋄ •Exit 𝕩} # Restores the terminal and exits +Quit←{•Out e∾"[?12l"∾e∾"[?25h" ⋄ •term.RawMode 0 ⋄ •Exit 𝕩} # Restores the terminal and exits Display←{ # Displays the board, score and controls •Out e∾"[H"∾e∾"[2J" # Cursor to origin and clear screen •Out "Controls: h: left, j: down, k: up, l: right, q: quit" diff --git a/Task/2048/EasyLang/2048.easy b/Task/2048/EasyLang/2048.easy new file mode 100644 index 0000000000..410f4010a9 --- /dev/null +++ b/Task/2048/EasyLang/2048.easy @@ -0,0 +1,161 @@ +len brd[] 16 +gbackground 987 +proc newtile . + for i to 16 : if brd[i] = 0 : break 1 + if i > 16 : return + v = 2 + if randomf < 0.1 : v = 4 + repeat + ind = random 16 + until brd[ind] = 0 + . + brd[ind] = v +. +global pts stat . +proc show . + gclear + gtextsize 5 + gcolor 222 + gtext 10 94 "2048 Game" + gtext 60 94 "Pts: " & pts + gtextsize 7 + gcolor 876 + grect 9 9 82 82 + gcolor 987 + grect 10 10 80 80 + for i to 16 : if brd[i] <> 0 + x = i mod1 4 * 20 - 9.5 + y = i div1 4 * 20 - 9.5 + gcolor 765 + grect x y 19 19 + v = brd[i] + h = 2 * floor log10 v + gcolor 000 + gtext x + 7 - h y + 7 brd[i] + . +. +proc init . + for i to 16 : brd[i] = 0 + newtile + newtile + stat = 0 + pts = 0 + show +. +init +# +dir[] = [ -4 -1 4 1 ] +start[] = [ 16 4 1 13 ] +proc domove indk test &moved . + moved = 0 + dir = dir[indk] + bdir = dir[(indk + 1) mod1 4] + start = start[indk] + for i to 4 + h0 = start + dir + for j to 3 + if brd[h0] <> 0 + v = brd[h0] + h = h0 + while h <> start and brd[h - dir] = 0 : h -= dir + if h <> h0 + moved = 1 + if test = 1 : return + . + if h <> start and brd[h - dir] = v + moved = 1 + if test = 1 : return + v *= 2 + pts += v + brd[h - dir] = -v + if v = 2048 : stat = 1 + v = 0 + . + brd[h0] = 0 + brd[h] = v + . + h0 += dir + . + h0 = start + for j to 3 + brd[h0] = abs brd[h0] + h0 += dir + . + sleep 0.1 + show + start += bdir + . +. +proc handle indk . + if indk = 0 : return + domove indk 0 moved + if moved = 1 + newtile + sleep 0.2 + show + if stat = 0 + stat = 2 + for indk to 4 + domove indk 1 moved + if moved = 1 + stat = 0 + break 1 + . + . + . + . + if stat <> 0 + gtextsize 5 + if stat = 1 + stat = 0 + gtext 10 3 "You got 2048 😊" + else + gtext 10 3 "No more moves 🙁" + . + . +. +on mouse_down + mx = mouse_x + my = mouse_y +. +proc handle_mup . + dx = mouse_x - mx + dy = mouse_y - my + indk = 0 + if abs dx > abs dy + if abs dx > 3 + indk = 4 + if dx > 0 : indk = 2 + . + else + if abs dy > 3 + indk = 3 + if dy > 0 : indk = 1 + . + . + if indk <> 0 and stat = 2 + init + else + handle indk + . +. +on mouse_up + handle_mup +. +on key + if stat = 2 + if keybkey = " " : init + return + . + indk = 0 + if keybkey = "ArrowUp" + indk = 1 + elif keybkey = "ArrowRight" + indk = 2 + elif keybkey = "ArrowDown" + indk = 3 + elif keybkey = "ArrowLeft" + indk = 4 + . + handle indk +. diff --git a/Task/2048/Zig/2048.zig b/Task/2048/Zig/2048.zig new file mode 100644 index 0000000000..2f59b71609 --- /dev/null +++ b/Task/2048/Zig/2048.zig @@ -0,0 +1,228 @@ +const std = @import("std"); +const io = std.io; +const Random = std.Random; + +// UserMove enum representing possible moves +const UserMove = enum { + Up, + Down, + Left, + Right, +}; + +// Game field type +const Field = [4][4]u32; + +// Function to print the current game state +fn printGame(field: *const Field) void { + for (field) |row| { + std.debug.print("{any}\n", .{row}); + } +} + +// Function to get a user move +fn getUserMove() !UserMove { + const stdin = std.io.getStdIn().reader(); + var buf: [2]u8 = undefined; // Buffer for input (character + newline) + + while (true) { + const bytesRead = try stdin.read(&buf); + if (bytesRead < 1) continue; + + switch (buf[0]) { + 'a' => return UserMove.Left, + 'w' => return UserMove.Up, + 's' => return UserMove.Down, + 'd' => return UserMove.Right, + else => { + std.debug.print("input was {c}: invalid character should be a,s,w or d\n", .{buf[0]}); + }, + } + } +} + +// This function implements user moves. +// For every element, it checks if the element is zero. +// If the element is zero, it looks against the direction of movement if any +// element is not zero, then moves it to its place and checks for a matching element. +// If the element is not zero, it looks for a match. If no match is found, +// it looks for the next element. +fn doGameStep(step: UserMove, field: *Field) void { + switch (step) { + .Left => { + for (field) |*row| { + for (0..4) |col| { + for ((col + 1)..4) |my_testCol| { + if (row[my_testCol] != 0) { + if (row[col] == 0) { + row[col] += row[my_testCol]; + row[my_testCol] = 0; + } else if (row[col] == row[my_testCol]) { + row[col] += row[my_testCol]; + row[my_testCol] = 0; + break; + } else { + break; + } + } + } + } + } + }, + .Right => { + for (field) |*row| { + var col: i32 = 3; + while (col >= 0) : (col -= 1) { + var my_testCol: i32 = col - 1; + while (my_testCol >= 0) : (my_testCol -= 1) { + if (row[@intCast(my_testCol)] != 0) { + if (row[@intCast(col)] == 0) { + row[@intCast(col)] += row[@intCast(my_testCol)]; + row[@intCast(my_testCol)] = 0; + } else if (row[@intCast(col)] == row[@intCast(my_testCol)]) { + row[@intCast(col)] += row[@intCast(my_testCol)]; + row[@intCast(my_testCol)] = 0; + break; + } else { + break; + } + } + } + } + } + }, + .Down => { + for (0..4) |col_idx| { + const col = col_idx; // Convert to immutable + var row: i32 = 3; + while (row >= 0) : (row -= 1) { + var my_testRow: i32 = row - 1; + while (my_testRow >= 0) : (my_testRow -= 1) { + if (field[@intCast(my_testRow)][col] != 0) { + if (field[@intCast(row)][col] == 0) { + field[@intCast(row)][col] += field[@intCast(my_testRow)][col]; + field[@intCast(my_testRow)][col] = 0; + } else if (field[@intCast(row)][col] == field[@intCast(my_testRow)][col]) { + field[@intCast(row)][col] += field[@intCast(my_testRow)][col]; + field[@intCast(my_testRow)][col] = 0; + break; + } else { + break; + } + } + } + } + } + }, + .Up => { + for (0..4) |col| { + for (0..4) |row| { + for ((row + 1)..4) |my_testRow| { + if (field[my_testRow][col] != 0) { + if (field[row][col] == 0) { + field[row][col] += field[my_testRow][col]; + field[my_testRow][col] = 0; + } else if (field[row][col] == field[my_testRow][col]) { + field[row][col] += field[my_testRow][col]; + field[my_testRow][col] = 0; + break; + } else { + break; + } + } + } + } + } + }, + } +} + +// Spawn a new number (2 or 4) in a random empty cell +fn spawn(field: *Field, random: Random) void { + while (true) { + const x = random.uintLessThan(usize, 16); // Random position 0-15 + const row = x % 4; + const col = (x / 4) % 4; + + if (field[row][col] == 0) { + // 10% chance for a 4, 90% chance for a 2 + if (random.uintLessThan(usize, 10) == 0) { + field[row][col] = 4; + } else { + field[row][col] = 2; + } + break; + } + } +} + +// Check if fields are equal +fn areFieldsEqual(a: *const Field, b: *const Field) bool { + for (0..4) |i| { + for (0..4) |j| { + if (a[i][j] != b[i][j]) return false; + } + } + return true; +} + +// Check if player has won (any tile equals 2048) +fn checkWin(field: *const Field) bool { + for (field) |row| { + for (row) |cell| { + if (cell == 2048) return true; + } + } + return false; +} + +pub fn main() !void { + var prng = std.Random.DefaultPrng.init(@intCast(std.time.milliTimestamp())); + const random = prng.random(); + + var field: Field = [_][4]u32{[_]u32{0} ** 4} ** 4; + var my_test: Field = undefined; + + gameLoop: while (true) { + // Check if there's still an open space + @memcpy(&my_test, &field); + spawn(&field, random); + + // Check if any valid moves remain + var validMoveExists = false; + const moves = [_]UserMove{ .Up, .Down, .Left, .Right }; + + for (moves) |move| { + @memcpy(&my_test, &field); + doGameStep(move, &my_test); + + if (!areFieldsEqual(&my_test, &field)) { + validMoveExists = true; + break; + } + } + + if (!validMoveExists) { + std.debug.print("No more valid moves, you lose\n", .{}); + break :gameLoop; + } + + // Print the current game state + printGame(&field); + std.debug.print("move the blocks\n", .{}); + + // Get and apply user move + @memcpy(&my_test, &field); + while (areFieldsEqual(&my_test, &field)) { + const move = try getUserMove(); + doGameStep(move, &field); + } + + // Check win condition + if (checkWin(&field)) { + printGame(&field); + std.debug.print("You Won!!\n", .{}); + break :gameLoop; + } + } +} diff --git a/Task/24-game-Solve/Dart/24-game-solve.dart b/Task/24-game-Solve/Dart/24-game-solve.dart new file mode 100644 index 0000000000..38d41aaba9 --- /dev/null +++ b/Task/24-game-Solve/Dart/24-game-solve.dart @@ -0,0 +1,226 @@ +enum Operator { + Sub, + Plus, + Mul, + Div +} + +class Factor { + String content; + int value; + + Factor({this.content, this.value}); + + Factor copyWith({String content, int value}) { + return Factor( + content: content ?? this.content, + value: value ?? this.value + ); + } +} + +List apply(Operator op, List left, List right) { + List ret = []; + for (var l in left) { + for (var r in right) { + switch (op) { + case Operator.Sub: + if (l.value > r.value) { + ret.add(Factor( + content: "(${l.content} - ${r.content})", + value: l.value - r.value + )); + } + break; + case Operator.Plus: + ret.add(Factor( + content: "(${l.content} + ${r.content})", + value: l.value + r.value + )); + break; + case Operator.Mul: + ret.add(Factor( + content: "(${l.content} × ${r.content})", + value: l.value * r.value + )); + break; + case Operator.Div: + if (l.value >= r.value && r.value > 0 && l.value % r.value == 0) { + ret.add(Factor( + content: "(${l.content} / ${r.content})", + value: l.value ~/ r.value + )); + } + break; + } + } + } + return ret; +} + +List calc(List op, List numbers) { + List _calc(List op, List numbers, List acc) { + if (op.isEmpty) { + return List.from(acc); + } + + List ret = []; + var monoFactor = [Factor( + content: numbers[0].toString(), + value: numbers[0], + )]; + + switch (op[0]) { + case Operator.Mul: + ret.addAll(apply(op[0], acc, monoFactor)); + break; + case Operator.Div: + ret.addAll(apply(op[0], acc, monoFactor)); + ret.addAll(apply(op[0], monoFactor, acc)); + break; + case Operator.Sub: + ret.addAll(apply(op[0], acc, monoFactor)); + ret.addAll(apply(op[0], monoFactor, acc)); + break; + case Operator.Plus: + ret.addAll(apply(op[0], acc, monoFactor)); + break; + } + + return _calc( + op.sublist(1), + numbers.sublist(1), + ret + ); + } + + return _calc( + op, + numbers.sublist(1), + [Factor(content: numbers[0].toString(), value: numbers[0])] + ); +} + +List solutions(List numbers) { + List ret = []; + Set hashSet = {}; + + for (var ops in OpIter()) { + for (var order in orders()) { + var orderedNumbers = applyOrder(numbers, order); + var results = calc(ops, orderedNumbers); + + for (var factor in results) { + if (factor.value == 24 && !hashSet.contains(factor.content)) { + hashSet.add(factor.content); + ret.add(factor); + } + } + } + } + + return ret; +} + +class OpIter extends Iterable> { + @override + Iterator> get iterator => _OpIterator(); +} + +class _OpIterator implements Iterator> { + int _index = 0; + static const List OPTIONS = [ + Operator.Mul, + Operator.Sub, + Operator.Plus, + Operator.Div + ]; + + @override + List get current { + final f1 = OPTIONS[(_index & (3 << 4)) >> 4]; + final f2 = OPTIONS[(_index & (3 << 2)) >> 2]; + final f3 = OPTIONS[(_index & 3)]; + return [f1, f2, f3]; + } + + @override + bool moveNext() { + if (_index >= 1 << 6) { + return false; + } + _index++; + return true; + } +} + +List> orders() { + return [ + [0, 1, 2, 3], + [0, 1, 3, 2], + [0, 2, 1, 3], + [0, 2, 3, 1], + [0, 3, 1, 2], + [0, 3, 2, 1], + [1, 0, 2, 3], + [1, 0, 3, 2], + [1, 2, 0, 3], + [1, 2, 3, 0], + [1, 3, 0, 2], + [1, 3, 2, 0], + [2, 0, 1, 3], + [2, 0, 3, 1], + [2, 1, 0, 3], + [2, 1, 3, 0], + [2, 3, 0, 1], + [2, 3, 1, 0], + [3, 0, 1, 2], + [3, 0, 2, 1], + [3, 1, 0, 2], + [3, 1, 2, 0], + [3, 2, 0, 1], + [3, 2, 1, 0] + ]; +} + +List applyOrder(List numbers, List order) { + return [ + numbers[order[0]], + numbers[order[1]], + numbers[order[2]], + numbers[order[3]] + ]; +} + +void main(List args) { + List numbers = []; + + if (args.isNotEmpty) { + String input = args[0]; + for (var char in input.split('')) { + int n = int.tryParse(char); + if (n != null) { + numbers.add(n); + } + + if (numbers.length == 4) { + var sols = solutions(numbers); + var len = sols.length; + + if (len == 0) { + print('no solution for ${numbers[0]}, ${numbers[1]}, ${numbers[2]}, ${numbers[3]}'); + return; + } + + print('solutions for ${numbers[0]}, ${numbers[1]}, ${numbers[2]}, ${numbers[3]}'); + for (var s in sols) { + print(s.content); + } + print('$len solutions found'); + return; + } + } + } else { + print('empty input'); + } +} diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index d4170cfc82..b363901a03 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -3,8 +3,6 @@ import system'collections; import system'dynamic; import extensions; -// --- Expression --- - class ExpressionTree { object _tree; @@ -18,13 +16,13 @@ class ExpressionTree var node := new DynamicStruct(); ch => - $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 } // ) - ! { + $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 }; @@ -97,8 +95,6 @@ class ExpressionTree <= readLeaves(list,_tree); } -// --- Game --- - class TwentyFourGame { object theNumbers; @@ -121,7 +117,7 @@ class TwentyFourGame help() { - console + Console .printLine("------------------------------- Instructions ------------------------------") .printLine("Four digits will be displayed.") .printLine("Enter an equation using all of those four digits that evaluates to 24") @@ -137,9 +133,9 @@ class TwentyFourGame prompt() { - theNumbers.forEach::(n){ console.print(n," ") }; + theNumbers.forEach::(n){ Console.print(n," ") }; - console.print(": ") + Console.print(": ") } resolve(expr) @@ -149,19 +145,19 @@ 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 }; + if:not (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) { - console.printLine("Good work. ",expr,"=",result); + Console.printLine("Good work. ",expr,"=",result); self.newPuzzle() } else { - console.printLine("Incorrect. ",expr,"=",result) + Console.printLine("Incorrect. ",expr,"=",result) } } } @@ -178,7 +174,7 @@ extension gameOp { if (expr == "") { - console.printLine("Skipping this puzzle"); self.newPuzzle() + Console.printLine("Skipping this puzzle"); self.newPuzzle() } else { @@ -188,8 +184,7 @@ extension gameOp } catch(Exception e) { - console.printLine(e) - //console.printLine:"An error occurred. Check your input and try again." + Console.printLine:"An error occurred. Check your input and try again." } }; @@ -198,11 +193,9 @@ extension gameOp } } -// --- program --- - public program() { var game := new TwentyFourGame().help(); - while (game.prompt().playRound(console.readLine())) {} + while (game.prompt().playRound(Console.readLine())) {} } diff --git a/Task/24-game/Perl/24-game.pl b/Task/24-game/Perl/24-game.pl index 071bb8e2b8..d4dd33e728 100644 --- a/Task/24-game/Perl/24-game.pl +++ b/Task/24-game/Perl/24-game.pl @@ -25,18 +25,21 @@ while (1) { print "Expression (try ", $try++, "): "; my $entry = <>; - if (!defined $entry || $entry eq 'q') + if (!defined $entry || substr($entry,0,1) eq 'q') { say "Goodbye. Sorry you couldn't win."; last; } - $entry =~ s/\s+//g; # remove all white space + $entry =~ s/\s+//g; # remove all white space (newline is whitespace too) next if $entry eq ''; my $given_digits = join "", sort @digits; my $entry_digits = join "", sort grep { /\d/ } split(//, $entry); - if ($given_digits ne $entry_digits || # not correct digits - $entry =~ /\d\d/ || # combined digits - $entry =~ m|[-+*/]{2}| || # combined operators - $entry =~ tr|-0-9()+*/||c) # Invalid characters - { say "That's not valid"; next; } + if ($given_digits ne $entry_digits) + { say "incorrect digits"; next; } + if ($entry =~ /\d\d/) + { say "error, combined digits"; next; } + if ($entry =~ m|[-+*/]{2}|) + { say "error, combined operators"; next; } + if ($entry =~ tr|-0-9()+*/||c) + { say "invalid characters!"; next; } my $n = eval $entry; diff --git a/Task/24-game/Rust/24-game.rs b/Task/24-game/Rust/24-game.rs index bdcad8b01d..8e9e7f0ced 100644 --- a/Task/24-game/Rust/24-game.rs +++ b/Task/24-game/Rust/24-game.rs @@ -79,7 +79,13 @@ fn calculate(input: &String, list : &mut [u32;4]) -> f32{ fn main() { let mut rng = rand::thread_rng(); - let mut list :[u32;4]=[rng.gen::()%10,rng.gen::()%10,rng.gen::()%10,rng.gen::()%10]; + // each from 1 ──► 9 (inclusive) + let mut list :[u32;4]=[ + rng.gen::()%9+1, + rng.gen::()%9+1, + rng.gen::()%9+1, + rng.gen::()%9+1 + ]; println!("form 24 with using + - / * {:?}",list); //get user input diff --git a/Task/24-game/Zig/24-game.zig b/Task/24-game/Zig/24-game.zig new file mode 100644 index 0000000000..4c224f1030 --- /dev/null +++ b/Task/24-game/Zig/24-game.zig @@ -0,0 +1,153 @@ +const std = @import("std"); +const rand = std.Random; +// (hint: errors cannot be handled at comptime) +var stdout: std.fs.File.Writer = undefined; +var stdin: std.fs.File.Reader = undefined; + +fn opType(x: u8) i32 { + return switch (x) { + '-', '+' => 1, + '/', '*' => 2, + '(', ')' => -1, + else => 0, + }; +} + +fn toRpn(allocator: std.mem.Allocator, input: []const u8) ![]u8 { + var rpnString = std.ArrayList(u8).init(allocator); + defer rpnString.deinit(); + + var rpnStack = std.ArrayList(u8).init(allocator); + defer rpnStack.deinit(); + + var lastToken: u8 = '#'; + + for (input) |token| { + if (token >= '1' and token <= '9') { + try rpnString.append(token); + } else if (opType(token) == 0) { + continue; + } else if (opType(token) > opType(lastToken) or token == '(') { + try rpnStack.append(token); + lastToken = token; + } else { + while (rpnStack.items.len > 0) { + const top = rpnStack.pop().?; + if (top == '(') { + break; + } + try rpnString.append(top); + } + if (token != ')') { + try rpnStack.append(token); + } + } + } + + while (rpnStack.items.len > 0) { + try rpnString.append(rpnStack.pop().?); + } + + if (rpnString.items.len > 0) { + try stdout.print("your formula results in {s}\n", .{rpnString.items}); + } else { + stdout.print("no input available.\n", .{}) catch {}; + } + + return rpnString.toOwnedSlice(); +} + +fn calculate(input: []const u8, list: *[4]u32) f32 { + var stack = std.ArrayList(f32).init(std.heap.page_allocator); + defer stack.deinit(); + + var accumulator: f32 = 0.0; + + for (input) |token| { + if (token >= '1' and token <= '9') { + const digit = @as(u32, token - '0'); + + // Find and mark the used digit + var found = false; + for (list, 0..) |val, idx| { + if (val == digit) { + list[idx] = 10; + found = true; + break; + } + } + + if (!found) { + stdout.print(" invalid digit: {d} \n", .{digit}) catch {}; + } + + stack.append(accumulator) catch {}; + accumulator = @floatFromInt(digit); + } else { + const a = stack.pop().?; + + accumulator = switch (token) { + '-' => a - accumulator, + '+' => a + accumulator, + '/' => a / accumulator, + '*' => a * accumulator, + else => accumulator, // NOP + }; + } + } + + stdout.print("your formula results in {d}\n", .{accumulator}) catch {}; + return accumulator; +} + +pub fn main() !void { + stdout = std.io.getStdOut().writer(); + stdin = std.io.getStdIn().reader(); + var prng = rand.DefaultPrng.init(@as(u64, @intCast(std.time.timestamp()))); + const random = prng.random(); + // only values from 1 --> 9 (inclusive) + var list = [_]u32{ + @mod(random.int(u32), 9) + 1, + @mod(random.int(u32), 9) + 1, + @mod(random.int(u32), 9) + 1, + @mod(random.int(u32), 9) + 1, + }; + + try stdout.print("form 24 with using + - / * {d} {d} {d} {d}\n", .{ list[0], list[1], list[2], list[3] }); + + // Get user input + var buffer: [1024]u8 = undefined; + const input = try stdin.readUntilDelimiterOrEof(buffer[0..], '\n') orelse ""; + + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + // Convert to RPN + const rpnInput = try toRpn(allocator, input); + if (rpnInput.len == 0) { + stdout.print("exit.\n", .{}) catch {}; + return; + } + + const result = calculate(rpnInput, &list); + + var allUsed = true; + for (list) |val| { + if (val != 10) { + allUsed = false; + break; + } + } + + if (allUsed) { + try stdout.print("and you used all numbers\n", .{}); + if (result == 24.0) { + try stdout.print("you won\n", .{}); + } else { + try stdout.print("but your formula doesn't result in 24\n", .{}); + } + } else { + try stdout.print("you didn't use all the numbers\n", .{}); + } +} diff --git a/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy b/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy index f2e05dc87f..22e54e305a 100644 --- a/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy +++ b/Task/4-rings-or-4-squares-puzzle/EasyLang/4-rings-or-4-squares-puzzle.easy @@ -1,12 +1,10 @@ func ok v t[] . for h in t[] - if v = h - return 0 - . + if v = h : return 0 . return 1 . -proc four lo hi uni show . . +proc four lo hi uni show . # subr bf for f = lo to hi 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 e88bc758db..f80cd1b687 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 @@ -31,5 +31,5 @@ public program() { var bottles := 99; - bottles.bottleEnumerator().forEach(printingLn) + bottles.bottleEnumerator().forEach(PrintingLn) } diff --git a/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor b/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor new file mode 100644 index 0000000000..55688df8a7 --- /dev/null +++ b/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-1.factor @@ -0,0 +1,6 @@ +USE: math.parser +100 +[ dup 1 - [ >dec " bottles of beer" append [ " on the wall" append ] keep ] bi@ + "Take one down, pass it around" -rot + first CHAR: - = [ 2drop "..." "why's all the rum gone??" ] when ! if leading character is "-" then replace with new string + 4array "\n" join print nl ] each diff --git a/Task/99-bottles-of-beer/Factor/99-bottles-of-beer.factor b/Task/99-bottles-of-beer/Factor/99-bottles-of-beer-2.factor similarity index 100% rename from Task/99-bottles-of-beer/Factor/99-bottles-of-beer.factor rename to Task/99-bottles-of-beer/Factor/99-bottles-of-beer-2.factor diff --git a/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl b/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl index 2d10b5487c..868c8dd512 100644 --- a/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl +++ b/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl @@ -1,63 +1,73 @@ -( uxncli 99bottles.rom ) +%\n { 0a } %\s { 20 } %\0 { 00 } +%newline { [ LIT2 \n -Console/write ] DEO } +%plural { [ LIT2 "s -Console/write ] DEO } -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|18 @Console/write -|0100 ( -> ) - #63 &loop - DUP - [ LIT2 0a -Console/write ] DEO - #01 EQUk ?&done - POP #01 SUB - !&loop - &done BRK +|100 -@ ( num -- ) - DUP ;dict/wall - DUP [ LIT2 0a -Console/write ] DEO - ;dict/take - #01 SUB ;dict/wall ! +#63 +&loop + DUP print/verse + newline + #01 EQUk ?/done + POP #01 SUB + !/done -@ ( num -- ) - DUP #00 EQU ?&zero - DUP #01 EQU ?&one - ;dict/bottle - [ LIT2 "s -Console/write ] DEO - !&end + &done + POP2 - &one ( num -- ) - ;dict/bottle - !&end - &zero ( num -- ) - POP ;dict/no-more - ;dict/bottle - [ LIT2 "s -Console/write ] DEO - ( >> ) - &end - ;dict/of-beer +BRK + +@print/verse ( num -- ) + DUP /bottle ;msgs/wall /str + DUP /bottle newline + ;msgs/take /str + #01 SUB /bottle ;msgs/wall !/str + +@print/bottle ( num -- ) + DUP #00 EQU ?/bottle/zero + DUP #01 EQU ?/bottle/one + /dec ;msgs/bottle /str + plural + !/bottle/end + + &bottle/one ( num -- ) + /dec ;msgs/bottle /str + !/bottle/end + + &bottle/zero ( num -- ) + POP ;msgs/no-more /str + ;msgs/bottle /str + plural ( >> ) -@ ( str -- ) - &loop - LDAk .Console/write DEO - INC2 LDAk ?&loop + &bottle/end + ;msgs/of-beer + ( >> ) + +@print/str ( str -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str POP2 JMP2r -@ ( byte -- ) - DUP #64 DIV /try - DUP #0a DIV /try +@print/dec ( byte -- ) + DUP #64 DIV /dec/try + DUP #0a DIV /dec/try ( >> ) -@ ( num -- ) - #0a DIVk MUL SUB - [ LIT "0 ] ADD .Console/write DEO - JMP2r + &dec/try/num ( num -- ) + #0a DIVk MUL SUB + [ LIT "0 ] ADD .Console/write DEO + JMP2r - &try ( num -- ) - DUP ? + &dec/try ( num -- ) + DUP ?/dec/try/num POP JMP2r -@dict &no-more "No 20 "more $1 - &bottle 20 "bottle $1 - &of-beer 20 "of 20 "beer 20 $1 - &wall "on 20 "the 20 "wall 0a $1 - &take "Take 20 "one 20 "down, 20 "pass 20 "it 20 "around 0a $1 +@msgs [ + &no-more "No \s "more \0 + &bottle \s "bottle \0 + &of-beer \s "of \s "beer \s \0 + &wall "on \s "the \s "wall \n \0 + &take "Take \s "one \s "down, \s "pass \s "it \s "around \n \0 ] diff --git a/Task/A+B/Ballerina/a+b.ballerina b/Task/A+B/Ballerina/a+b.ballerina new file mode 100644 index 0000000000..7c90b9d2f5 --- /dev/null +++ b/Task/A+B/Ballerina/a+b.ballerina @@ -0,0 +1,16 @@ +import ballerina/io; + +public function main() returns error? { + while true { + io:print("Enter two integers separated by a space : "); + string[] s = re ` `.split(io:readln()); + if s.length() < 2 { + io:println("Insufficient numbers, try again"); + } else { + int a = check int:fromString(s[0]); + int b = check int:fromString(s[1]); + io:println("Their sum is ", a + b, "."); + break; + } + } +} diff --git a/Task/A+B/Elena/a+b-1.elena b/Task/A+B/Elena/a+b-1.elena index a4c98a1213..afa03ef6c5 100644 --- a/Task/A+B/Elena/a+b-1.elena +++ b/Task/A+B/Elena/a+b-1.elena @@ -2,8 +2,8 @@ import extensions; public program() { - var A := Integer.new(); - var B := Integer.new(); + var A := Integer.new(); + var B := Integer.new(); - console.loadLine(A,B).printLine(A + B) + Console.loadLine(A,B).printLine(A + B) } diff --git a/Task/A+B/Elena/a+b-2.elena b/Task/A+B/Elena/a+b-2.elena index 8097b76574..b79d01d958 100644 --- a/Task/A+B/Elena/a+b-2.elena +++ b/Task/A+B/Elena/a+b-2.elena @@ -3,7 +3,7 @@ import extensions; public program() { - console.printLine(console.readLine() + Console.printLine(Console.readLine() .split() .selectBy(mssgconst toInt[1]) .summarize()) diff --git a/Task/A+B/REXX/a+b-1.rexx b/Task/A+B/REXX/a+b-1.rexx deleted file mode 100644 index 46a34f359e..0000000000 --- a/Task/A+B/REXX/a+b-1.rexx +++ /dev/null @@ -1,4 +0,0 @@ -/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/ -parse pull a b /*obtain two numbers from input stream.*/ -say a+b /*display the sum to the terminal. */ - /*stick a fork in it, we're all done. */ diff --git a/Task/A+B/REXX/a+b-2.rexx b/Task/A+B/REXX/a+b-2.rexx deleted file mode 100644 index 064640ab38..0000000000 --- a/Task/A+B/REXX/a+b-2.rexx +++ /dev/null @@ -1,4 +0,0 @@ -/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/ -parse pull a b /*obtain two numbers from input stream.*/ -say (a+b) / 1 /*display normalized sum to terminal. */ - /*stick a fork in it, we're all done. */ diff --git a/Task/A+B/REXX/a+b-3.rexx b/Task/A+B/REXX/a+b-3.rexx deleted file mode 100644 index 774178e64d..0000000000 --- a/Task/A+B/REXX/a+b-3.rexx +++ /dev/null @@ -1,6 +0,0 @@ -/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/ -numeric digits 300 /*the default is nine decimal digits.*/ -parse pull a b /*obtain two numbers from input stream.*/ -z= (a+b) / 1 /*add and normalize sum, store it in Z.*/ -say z /*display normalized sum Z to terminal.*/ - /*stick a fork in it, we're all done. */ diff --git a/Task/A+B/REXX/a+b-4.rexx b/Task/A+B/REXX/a+b-4.rexx deleted file mode 100644 index 05e988dfb5..0000000000 --- a/Task/A+B/REXX/a+b-4.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*REXX program obtains some numbers from the input stream (the console), shows their sum*/ -numeric digits 1000 /*just in case the user gets ka-razy. */ -say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/ -parse pull y /*obtain all numbers from input stream.*/ -many= words(y) /*obtain the number of numbers entered.*/ -$= 0 /*initialize the sum to zero. */ - do j=1 for many /*process each of the numbers. */ - $= $ + word(y, j) /*add one number to the sum. */ - end /*j*/ - /*stick a fork in it, we're all done. */ -say 'sum of ' many " numbers = " $/1 /*display normalized sum $ to terminal.*/ diff --git a/Task/A+B/REXX/a+b-5.rexx b/Task/A+B/REXX/a+b-5.rexx deleted file mode 100644 index 3aed91ea3f..0000000000 --- a/Task/A+B/REXX/a+b-5.rexx +++ /dev/null @@ -1,8 +0,0 @@ -/*REXX program obtains some numbers from the input stream (the console), shows their sum*/ -numeric digits 1000 /*just in case the user gets ka-razy. */ -say 'enter some numbers to be summed:' /*display a prompt message to terminal.*/ -parse pull y /*obtain all numbers from input stream.*/ -y=space(y) -y=translate(y,'+',' ') -Interpret 's='y -say 'sum of ' many " numbers = " s/1 /*display normalized sum s to terminal.*/ diff --git a/Task/A+B/REXX/a+b.rexx b/Task/A+B/REXX/a+b.rexx new file mode 100644 index 0000000000..928b14cfbb --- /dev/null +++ b/Task/A+B/REXX/a+b.rexx @@ -0,0 +1,27 @@ +-- 1 Jun 2025 +include Settings + +say 'A+B' +say version +say +do forever + call Charout, 'REXX ' + pull x + if x = '' then + leave + parse var x a b + say + say 'As given...' + say 'A =' a + say 'B =' b + say 'A+B =' a+b + say + say 'Normalized...' + say 'A =' a/1 + say 'B =' b/1 + say 'A+B =' (a+b)/1 + say +end +exit + +include Abend diff --git a/Task/ABC-problem/Ballerina/abc-problem.ballerina b/Task/ABC-problem/Ballerina/abc-problem.ballerina new file mode 100644 index 0000000000..0428dff997 --- /dev/null +++ b/Task/ABC-problem/Ballerina/abc-problem.ballerina @@ -0,0 +1,32 @@ +import ballerina/io; + +function r(string word, string[] bl) returns boolean { + if word == "" { return true; } + int c = word[0].toBytes()[0] | 32; + foreach int i in 0.. len w$[] cnt += 1 return diff --git a/Task/ABC-problem/Elena/abc-problem.elena b/Task/ABC-problem/Elena/abc-problem.elena index 99216ac706..2525c26eed 100644 --- a/Task/ABC-problem/Elena/abc-problem.elena +++ b/Task/ABC-problem/Elena/abc-problem.elena @@ -41,6 +41,6 @@ public program() words.forEach::(word) { - console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks)); + Console.printLine("can make '",word,"' : ",word.canMakeWordFrom(blocks)); } } diff --git a/Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs b/Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs new file mode 100644 index 0000000000..3f4f47932f --- /dev/null +++ b/Task/ADFGVX-cipher/C-sharp/adfgvx-cipher.cs @@ -0,0 +1,117 @@ +using System.Diagnostics; + +const string cypher = "ADFGVX"; +var N = cypher.Length; +var size = N * N; +const string symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; +Debug.Assert(size == symbols.Length); +var square = new int[size]; + +for (var i = 0; i < size; i++) +{ + var j = Random.Shared.Next(i + 1); + square[i] = square[j]; + square[j] = i; +} + +Console.WriteLine($"{N} x {N} Polybius square:"); +Console.WriteLine(); +Console.WriteLine($" | {string.Join(' ', cypher.AsEnumerable())}"); +Console.WriteLine(new string('-', 2 * N + 3)); + +for (var row = 0; row < N; row++) +{ + Console.Write($"{cypher[row]} |"); + + for (var col = 0; col < N; col++) + { + Console.Write($" {symbols[square[col + row * N]]}"); + } + + Console.WriteLine(); +} + +static bool IsSuitableTranspositionKey(string s) => + s.Length >= 7 && s.Length <= 12 && s.Length == s.Distinct().Count() && s.All(symbols.ToLowerInvariant().Contains); + +var keys = File.ReadAllLines("unixdict.txt").Where(IsSuitableTranspositionKey).ToArray(); +var key = keys[Random.Shared.Next(keys.Length)].ToUpperInvariant(); +Console.WriteLine(); +Console.WriteLine($"The key is {key}"); +var plaintext = "ATTACKAT1200AM"; +Console.WriteLine($"Plaintext: {plaintext}"); + +string Encrypt(string plaintext, string key, int[] square) +{ + // Create a lookup table from symbol to fragment + var map = (from i in Enumerable.Range(0, size) + let k = square[i] + let code = cypher[i / N] + "" + cypher[i % N] + select (k, code)) + .ToDictionary(kc => symbols[kc.k], kc => kc.code); + + // Map the plaintext to fragments + var e = string.Join("", plaintext.Select(c => map[c])); + + // Determine number of rows + var K = key.Length; + var rows = (e.Length + K - 1) / K; + + // Pad with spaces + e += new string(' ', rows * K - e.Length); + + // Sort the key + var order = string.Join("", key.OrderBy(c => c)).Select(c => key.IndexOf(c)).ToArray(); + + // Reorder the fragments. + e = string.Join("", Enumerable.Range(0, K * rows).Select(i => e[(i / K) * K + order[i % K]])); + + // Transpose + e = new([.. from col in Enumerable.Range(0, K) + from row in Enumerable.Range(0, rows) + select e[row * K + col]]); + + // Read off each column. + return string.Join(" ", Enumerable.Range(0, K).Select(col => e.Substring(col * rows, rows).Trim())); +} + +var encrypted = Encrypt(plaintext, key, square); +Console.WriteLine($"Encrypted: {encrypted}"); + +string Decrypt(string encrypted, string key, int[] square) +{ + // Create a lookup table from fragment to symbol + var map = (from i in Enumerable.Range(0, size) + let k = square[i] + let code = cypher[i / N] + "" + cypher[i % N] + select (k, code)) + .ToDictionary(kc => kc.code, kc => symbols[kc.k]); + + // Split into columns + var cols = encrypted.Split(' '); + + // Determine number of rows + var K = key.Length; + var rows = cols.Max(c => c.Length); + + // Pad each column + cols = [.. cols.Select(c => c.PadRight(rows))]; + + // Transpose + string e = new([.. from row in Enumerable.Range(0, rows) + from col in Enumerable.Range(0, K) + select cols[col][row]]); + + // Sort the key + var sorted = string.Join("", key.OrderBy(c => c)); + var order = key.Select(c => sorted.IndexOf(c)).ToArray(); + + // Reorder the fragments + e = string.Join("", Enumerable.Range(0, K * rows).Select(i => e[(i / K) * K + order[i % K]])).Trim(); + + // Map the fragments to plaintext + return string.Join("", Enumerable.Range(0, e.Length / 2).Select(i => map[e.Substring(2 * i, 2)])); +} + +var decrypted = Decrypt(encrypted, key, square); +Console.WriteLine($"Decrypted: {decrypted}"); diff --git a/Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js b/Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js new file mode 100644 index 0000000000..0bdfe6eb1a --- /dev/null +++ b/Task/ADFGVX-cipher/JavaScript/adfgvx-cipher.js @@ -0,0 +1,134 @@ +class ADFGVX { + /** The WWI German ADFGVX cipher. */ + constructor(spoly, k, alph = 'ADFGVX') { + this.polybius = spoly.toUpperCase().split(''); + this.pdim = Math.floor(Math.sqrt(this.polybius.length)); + this.key = k.toUpperCase().split(''); + this.keylen = this.key.length; + this.alphabet = alph.split(''); + const pairs = []; + for (let i = 0; i < this.alphabet.length; i++) { + for (let j = 0; j < this.alphabet.length; j++) { + pairs.push(this.alphabet[i] + this.alphabet[j]); + } + } + this.encode = {}; + for (let i = 0; i < this.polybius.length; i++) { + this.encode[this.polybius[i]] = pairs[i]; + } + this.decode = {}; + for (const k in this.encode) { + this.decode[this.encode[k]] = k; + } + } + + encrypt(msg) { + /** Encrypt with the ADFGVX cipher. */ + const chars = []; + for (const c of msg.toUpperCase()) { + if (this.polybius.includes(c)) { + chars.push(this.encode[c]); + } + } + const flatChars = chars.join('').split(''); + const colvecs = []; + for (let i = 0; i < this.keylen; i++) { + const currentCol = []; + for (let j = i; j < flatChars.length; j += this.keylen) { + currentCol.push(flatChars[j]); + } + colvecs.push([this.key[i], currentCol]); + } + + colvecs.sort((a, b) => a[0].localeCompare(b[0])); + + let result = ''; + for (const a of colvecs) { + result += a[1].join(''); + } + return result; + } + + decrypt(cod) { + /** Decrypt with the ADFGVX cipher. Does not depend on spacing of encoded text */ + const chars = []; + for (const c of cod) { + if (this.alphabet.includes(c)) { + chars.push(c); + } + } + + const sortedkey = [...this.key].sort(); + const order = []; + for (const ch of sortedkey) { + order.push(this.key.indexOf(ch)); + } + const originalorder = []; + for (const ch of this.key) { + originalorder.push(sortedkey.indexOf(ch)); + } + + const base = Math.floor(chars.length / this.keylen); + const extra = chars.length % this.keylen; + const strides = order.map((_, i) => base + (extra > i ? 1 : 0)); + const starts = [0]; + let sum = 0; + for (let i = 0; i < strides.length - 1; i++) { + sum += strides[i]; + starts.push(sum); + } + const ends = starts.map((start, i) => start + strides[i]); + const cols = originalorder.map(i => chars.slice(starts[i], ends[i])); + + const pairs = []; + for (let i = 0; i < Math.floor((chars.length - 1) / this.keylen) + 1; i++) { + for (let j = 0; j < this.keylen; j++) { + if (i * this.keylen + j < chars.length) { + pairs.push(cols[j][i]); + } + } + } + + let decoded = ''; + for (let i = 0; i < pairs.length; i += 2) { + decoded += this.decode[pairs[i] + pairs[i + 1]]; + } + return decoded; + } +} + +// Helper function to shuffle an array (Fisher-Yates shuffle) +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + return array; +} + + +async function main() { + const PCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split(''); + shuffle(PCHARS); + const POLYBIUS = PCHARS.join(''); + + // Simulate reading from unixdict.txt (replace with your actual file reading method if needed) + // For demonstration purposes, using a hardcoded word list: + const WORDS = ['ABDEFGHIK', 'JLMNOPQRS', 'TUVWXYZ01', '23456789']; + const KEY = WORDS[Math.floor(Math.random() * WORDS.length)]; + + + const SECRET = new ADFGVX(POLYBIUS, KEY); + const MESSAGE = 'ATTACKAT1200AM'; + + console.log(`Polybius: ${POLYBIUS}, key: ${KEY}`); + console.log('Message: ', MESSAGE); + + const ENCODED = SECRET.encrypt(MESSAGE); + const DECODED = SECRET.decrypt(ENCODED); + + console.log('Encoded: ', ENCODED); + console.log('Decoded: ', DECODED); +} + +main(); diff --git a/Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000 b/Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000 new file mode 100644 index 0000000000..1cc6519280 --- /dev/null +++ b/Task/ADFGVX-cipher/M2000-Interpreter/adfgvx-cipher.m2000 @@ -0,0 +1,116 @@ +Module CheckADFGVX_Cipher { + Class cipher { + Private: + buffer a as byte*36 + b="ADFGVX" + key="ABCDEFGHIJK" + orderkey="ABCDEFGHIJK" + map=list + map2=list + module preparemaps { + for i=0 to 5 + jj=0 + for j=i*6 to j+5 + .map(chr$(.a[j]))=mid$(.b, i+1,1)+mid$(.b,jj+1, 1) + .map2(mid$(.b, i+1,1)+mid$(.b,jj+1, 1))=chr$(.a[j]) + jj++ + next + next + } + Public: + Module SetRandom (&returnvalue) { + return .a, 0:=str$("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") + for i=1 to 100 + c=random(0, 35):d=c + while c=d {d=random(0, 35)} + byte o=.a[c] + .a[c]<=.a[d] + .a[d]<=o + next + returnvalue=chr$(eval$(.a)) ' convert to UTF16LE + .preparemaps + } + Module SetSpecific (that$){ + return .a, 0:=str$(Ucase$(that$)) + .preparemaps + } + Module SetKey (.key as string) { + .key<=ucase$(.key) + if len(.key)<7 or len(.key)>12 then Error "Key has not proper length" + if filter$(.key, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")<>"" then + Error "Key has bad letters" + end if + dim aa(1 to len(.key)) + for i=1 to len(.key):aa(i)=mid$(.key,i,1):next + .orderkey<=aa()#sort()#str$("") + } + Module Display { + Print "The 6 x 6 Polybius square:" + Print " | A D F G V X" + Print "---------------" + for i=0 to 5 + Print mid$(.b,i+1,1)+" | "; + jj=0 + for j=i*6 to j+5 + print chr$(.a[j]);" "; + jj++ + next + print + next + Print "Key:";.key + } + Function Encrypt(p as string) { + crypted="" + for i=1 to len(p) + crypted+=.map$(mid$(p,i,1)) + next + m=1 + encrypted="" + For i = 1 To Len(.key) + ch = Mid$(.orderkey, i, 1) + For j = Instr(.key, ch) - 1 To Len(crypted) - 1 Step Len(.key) + encrypted += Mid$(crypted, j + 1, 1) + if m mod 5=0 then encrypted += " " + m++ + Next + Next + =encrypted + } + Function Decrypt(p as string) { + p=filter$(p, " ") + decrypted="" + m=1 + dim b$(len(p)) + For i = 1 To Len(.key) + ch = Mid$(.orderkey, i, 1) + For j = Instr(.key, ch) - 1 To Len(p) - 1 Step Len(.key) + b$(j)=mid$(p, m, 1) + m++ + Next + Next + for i=0 to len(b$())-1 step 2 + decrypted+=.map2(b$(i)+b$(i+1)) + next + =decrypted + } + } + ADFGVX=cipher() + for ADFGVX { + .SetSpecific "A9GKMF1DQRSBVX8Z0WTEJLOPY5U4CN2H76I3" + .SetKey "volcanism" + .Display + encode=.Encrypt("ATTACKAT1200AM") + Print "Encoded: ";encode + Print "Decoded: ";.Decrypt(encode) + Rem { ' using randomblock + thisblock="" + .SetRandom &thisblock + Print "Random Block:";thisblock + .Display + encode=.Encrypt("ATTACKAT1200AM") + Print "Encoded: ";encode + Print "Decoded: ";.Decrypt(encode) + } + } +} +CheckADFGVX_Cipher diff --git a/Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina b/Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina new file mode 100644 index 0000000000..575c645a5f --- /dev/null +++ b/Task/AKS-test-for-primes/Ballerina/aks-test-for-primes.ballerina @@ -0,0 +1,58 @@ +import ballerina/io; + +int[] e = "²³⁴⁵⁶⁷".toCodePointInts(); + +function bc(int p) returns int[] { + int[] c = []; + c.setLength(p + 1); + int r = 1; + int half = p / 2; + foreach int i in 0...half { + c[i] = r; + c[p - i] = r; + r = r * (p - i) / (i + 1); + } + foreach int i in int:range(p - 1, -1, -2) { + c[i] = -c[i]; + } + return c; +} + +function pp(int[] c) returns string|error { + if c.length() == 1 { return c[0].toString(); } + int p = c.length() - 1; + string s = ""; + if c[p] != 1 { s = c[p].toString(); } + foreach int i in int:range(p, 0, -1) { + s += "x"; + if i != 1 { s += check string:fromCodePointInt(e[i - 2]); } + int d = c[i - 1]; + if d < 0 { + s += " - " + (-d).toString(); + } else { + s += " + " + d.toString(); + } + } + return s; +} + +function aks(int p) returns boolean { + int[] c = bc(p); + c[p] -= 1; + c[0] += 1; + foreach int d in c { + if d % p != 0 { return false; } + } + return true; +} + +public function main() { + foreach int p in 0...7 { + io:println(p, ": ", pp(bc(p))); + } + io:println("\nAll primes under 50:"); + foreach int p in 2...49 { + if aks(p) { io:print(p, " "); } + } + io:println(); +} diff --git a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena index d1ab382bf3..714dc0f0ae 100644 --- a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena +++ b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena @@ -45,7 +45,7 @@ singleton AksTest while(i != 0) { i -= 1; - console.print("+",c[i],"x^",i) + Console.print("+",c[i],"x^",i) } } } @@ -55,18 +55,18 @@ public program() for (int n := 0; n < 10; n += 1) { AksTest.coef(n); - console.print("(x-1)^",n," = "); + Console.print("(x-1)^",n," = "); AksTest.show(n); - console.printLine() + Console.printLine() }; - console.print("Primes:"); + Console.print("Primes:"); for (int n := 1; n <= 63; n += 1) { if (AksTest.is_prime(n)) { - console.print(n," ") + Console.print(n," ") } }; - console.printLine().readChar() + Console.printLine().readChar() } diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx index f2aa00be60..1942f69672 100644 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx @@ -1,43 +1,91 @@ -/*REXX program calculates primes via the Agrawal─Kayal─Saxena (AKS) primality test.*/ -parse arg Z . /*obtain optional argument from the CL.*/ -if Z=='' | Z=="," then Z= 200 /*Not specified? Then use the default.*/ -OZ=Z; tell= Z<0; Z= abs(Z) /*Is Z negative? Then show expression.*/ -numeric digits max(9, Z % 3) /*define a dynamic # of decimal digits.*/ -call AKS /*invoke the AKS funtion for coef. bld.*/ -if left(OZ,1)=='+' then do; say Z isAksp(); exit /*display if Z is or isn't a prime.*/ - end /* [↑] call isAKSp if Z has leading +.*/ -say; say "primes found:" # /*display the prime number list. */ -say; if \datatype(#, 'W') then exit /* [↓] the digit length of a big coef.*/ -say 'Found ' words(#) " primes and the largest coefficient has " length(@.pm.h) @dd -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -AKS: $.0= '-'; $.1= "+"; @. = 1 /*$.x: sign char; default coefficients.*/ - q.= 1; q.1= 0; q.4= 0 /*sparse array for faster comparisons. */ - #=; L= length(Z) /*define list of prime numbers (so far)*/ - do p=3 for Z; pm=p - 1; pp=p + 1 /*PM & PP: used as a coding convenience*/ - do m=2 for pp % 2 - 1; mm=m - 1 /*calculate coefficients for a power. */ - @.p.m= @.pm.mm + @.pm.m; h=pp - m /*calculate left side of coefficients*/ - @.p.h= @.p.m /* " right " " " */ - end /*m*/ /* [↑] The M DO loop creates both */ - end /*p*/ /* sides in the same loop. */ - if tell then say '(x-1)^'right(0, L)": 1" /*possibly display the first expression*/ - @dd= 'decimal digits.' /* [↓] test for primality by division.*/ - do n=2 for Z; nh=n % 2; d= n - 1 /*create expressions; find the primes.*/ - do k=3 to nh while @.n.k//d == 0 /*are coefficients divisible by N-1 ? */ - end /*k*/ /* [↑] skip the 1st & 2nd coefficients*/ - if k>nh then if q.d then #= # d /*add a number to the prime list. */ - if \tell then iterate /*Don't tell? Don't show expressions.*/ - y= '(x-1)^'right(d, L)":" /*define the 1st part of the expression*/ - s=1 /*S: is the sign indicator (-1│+1).*/ - do j=n for n-1 by -1 /*create the higher powers first. */ - if j==2 then xp= 'x' /*if power=1, then don't show the power*/ - else xp= 'x^' || j-1 /* ··· else show power with ^ */ - if j==n then y=y xp /*no sign (+│-) for the 1st expression.*/ - else y=y $.s || @.n.j'∙'xp /*build the expression with sign (+|-).*/ - s= \s /*flip the sign for the next expression*/ - end /*j*/ /* [↑] the sign (now) is either 0 │ 1,*/ - say y $.s'1' /*just show the first N expressions, */ - end /*n*/ /* [↑] ··· but only for negative Z. */ - if #=='' then #= "none"; return # /*if null, return "none"; else return #*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isAKSp: if z==word(#,words(#)) then return ' is a prime.'; else return " isn't a prime." +-- 22 Mar 2025 +include Settings + +say 'AKS TEST FOR PRIMES' +say version +say +arg p +if p = '' then + p = 10 +numeric digits Max(10,Abs(p)%3) +call Combis p +call Polynomials p +call Showprimes p +exit + +Combis: +procedure expose comb. +arg p +call Time('r') +if p > 0 then + say 'Combinations up to' p'...' +else + say 'Combinations for' Abs(p)'...' +say Combinations(p) 'combinations generated' +say Format(Time('e'),,3) 'seconds' +say +return + +Polynomials: +procedure expose poly. comb. work. prim. +arg p +call Time('r') +say 'Polynomials...' +if p < 0 then + b = Abs(p) +else + b = 0 +p = Abs(p); prim. = 0; n = 0 +do i = b to p + a = Ppow('1 -1',i) + if i < 11 then + say '(x-1)^'i '=' Plst2form(Parr2lst()) + s = 1 + do j = 2 to poly.0-1 + a = poly.coef.j + if a//i > 0 then do + s = 0 + leave j + end + end + if s = 1 then do + if i > 1 then do + n = n+1 + prim.n = i + end + end +end +prim.0 = n +say Format(Time('e'),,3) 'seconds' +say +return + +Showprimes: +procedure expose prim. +arg p +call Time('r') +say 'Primes...' +if p < 0 then do + p = Abs(p) + if prim.0 > 0 then + say p 'is prime' + else + say p 'is not prime' +end +else do + do i = 1 to prim.0 + call Charout ,Right(prim.i,5) + if i//20 = 0 then + say + end + say +end +say Format(Time('e'),,3) 'seconds' +say +return + +include Functions +include Numbers +include Polynomial +include Sequences +include Abend diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx deleted file mode 100644 index 77862e7896..0000000000 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-3.rexx +++ /dev/null @@ -1,89 +0,0 @@ -include Settings - -say version -say 'AKS-test for primes'; say -arg p -if p = '' then - p = 10 -numeric digits Max(10,Abs(p)%3) -call Combis p -call Polynomials p -call Showprimes p -exit - -Combis: -procedure expose comb. -arg p -call Time('r') -if p > 0 then - say 'Combinations up to' p'...' -else - say 'Combinations for' Abs(p)'...' -say Combinations(p) 'combinations generated' -say Format(Time('e'),,3) 'seconds' -say -return - -Polynomials: -procedure expose poly. comb. work. prim. -arg p -call Time('r') -say 'Polynomials...' -if p < 0 then - b = Abs(p) -else - b = 0 -p = Abs(p); prim. = 0; n = 0 -do i = b to p - a = Ppow('1 -1',i) - if i < 11 then - say '(x-1)^'i '=' Plst2form(Parr2lst()) - s = 1 - do j = 2 to poly.0-1 - a = poly.coef.j - if a//i > 0 then do - s = 0 - leave j - end - end - if s = 1 then do - if i > 1 then do - n = n+1 - prim.n = i - end - end -end -prim.0 = n -say Format(Time('e'),,3) 'seconds' -say -return - -Showprimes: -procedure expose prim. -arg p -call Time('r') -say 'Primes...' -if p < 0 then do - p = Abs(p) - if prim.0 > 0 then - say p 'is prime' - else - say p 'is not prime' -end -else do - do i = 1 to prim.0 - call Charout ,Right(prim.i,5) - if i//20 = 0 then - say - end - say -end -say Format(Time('e'),,3) 'seconds' -say -return - -include Functions -include Numbers -include Polynomial -include Sequences -include Abend diff --git a/Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-1.cs b/Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-1.cs new file mode 100644 index 0000000000..003dbde2f0 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-1.cs @@ -0,0 +1,190 @@ +using System.CodeDom.Compiler; +using System.Diagnostics; + +var format = @"+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +| ID | ++--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +|QR| Opcode |AA|TC|RD|RA| Z | RCODE | ++--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +| QDCOUNT | ++--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +| ANCOUNT | ++--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +| NSCOUNT | ++--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +| ARCOUNT | ++--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; + +var lines = format.Split('\n') + .Select(line => line.Trim()) + .Where(s => s.Length > 0) + .ToArray(); + +var first = lines[0]; +var ll = first.Length; + +if (lines.Any(line => line.Length != ll)) + throw new Exception("Lines are not the same length."); + +if (first[0] != '+' || first[^1] != '+') + throw new Exception("First line does not start and end with '+'."); + +var bits = first.Split('+')[1..^1]; + +if (bits.Any(bit => bit != "--")) + throw new Exception("Not all bits on first line match '+--+'."); + +if (lines.Length % 2 == 0) + throw new Exception("Expected an odd number of definition lines."); + +var rows = lines.Length / 2; + +if (Enumerable.Range(0, rows).Any(row => lines[2 * row + 2] != first)) + throw new Exception("Not all line separators match first line."); + +var width = bits.Length; + +if (width != 8 && width != 16 && width != 32 && width != 64) + throw new Exception("Bit width is not 8, 16, 32, or 64."); + +var ftype = width switch +{ + 8 => "byte", + 16 => "ushort", + 32 => "uint", + _ => "ulong" +}; + +const string filename = "Header.cs"; +const string structName = "Header"; +List<(string Name, int Width)> fieldList = []; +List backing = []; + +using (var file = File.CreateText(filename)) +using (var code = new IndentedTextWriter(file)) +{ + code.WriteLine("using System.Buffers.Binary;"); + code.WriteLine("using System.Runtime.InteropServices;"); + code.WriteLine(); + code.WriteLine("[StructLayout(LayoutKind.Sequential, Pack = 0)]"); + code.WriteLine($"public struct {structName}"); + code.WriteLine("{"); + code.Indent++; + code.WriteLine($"public static readonly int MarshalledSize = Marshal.SizeOf<{structName}>();"); + + for (var row = 0; row < rows; row++) + { + var def = lines[row * 2 + 1]; + + if (def[0] != '|' || def[^1] != '|') + throw new Exception($"Row {row} doesn't start and end with '|'."); + + var fields = def.Split('|')[1..^1]; + + if (fields.Length > 1) + { + code.WriteLine(); + code.WriteLine($"{ftype} data{row};"); + backing.Add($"data{row}"); + } + + var offset = width; + + foreach (var field in fields) + { + if (field.Length % 3 != 2) + throw new Exception($"Field '{field.Trim()}' delimiters misaligned."); + + var fname = field.Trim(); + + if (fname.Length == 0) + throw new Exception($"Field name is missing."); + + var fwidth = (field.Length + 1) / 3; + offset -= fwidth; + fieldList.Add((fname, fwidth)); + var mask = "0b" + new string('1', fwidth); + var nmask = "0b" + new string('1', width - fwidth - offset) + new string('0', fwidth) + new string('1', offset); + code.WriteLine(); + code.WriteLine($"public {ftype} {fname}"); + code.WriteLine("{"); + code.Indent++; + + if (fields.Length == 1) + { + code.WriteLine("readonly get;"); + code.WriteLine("set;"); + backing.Add(fname); + } + else + { + code.WriteLine($"readonly get {{ return ({ftype})((data{row} >> {offset}) & {mask});}}"); + code.WriteLine($"set {{ data{row} = ({ftype})((data{row} & {nmask}) | ((value & {mask}) << {offset})); }}"); + } + + code.Indent--; + code.WriteLine("}"); + } + } + + code.WriteLine(); + code.WriteLine($"public static {structName} FromArray(byte[] bytes)"); + code.WriteLine("{"); + code.Indent++; + code.WriteLine("var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);"); + code.WriteLine($"var result = Marshal.PtrToStructure<{structName}>(handle.AddrOfPinnedObject());"); + code.WriteLine("handle.Free();"); + + if (width > 8) + { + code.WriteLine(); + code.WriteLine("if (BitConverter.IsLittleEndian)"); + code.WriteLine("{"); + code.Indent++; + + foreach (var f in backing) + { + code.WriteLine($"result.{f} = BinaryPrimitives.ReverseEndianness(result.{f});"); + } + + code.Indent--; + code.WriteLine("}"); + code.WriteLine(); + } + + code.WriteLine("return result;"); + code.Indent--; + code.WriteLine("}"); + code.WriteLine(); + code.WriteLine("public readonly byte[] ToArray()"); + code.WriteLine("{"); + code.Indent++; + code.WriteLine($"var bytes = new byte[Marshal.SizeOf<{structName}>()];"); + code.WriteLine("var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);"); + code.WriteLine("Marshal.StructureToPtr(this, handle.AddrOfPinnedObject(), false);"); + code.WriteLine("handle.Free();"); + + if (width > 8) + { + code.WriteLine(); + code.WriteLine("if (BitConverter.IsLittleEndian)"); + code.WriteLine("{"); + code.Indent++; + code.WriteLine($"for (var i = 0; i < MarshalledSize; i += sizeof({ftype}))"); + code.WriteLine("{"); + code.Indent++; + code.WriteLine($"Array.Reverse(bytes, i, sizeof({ftype}));"); + code.Indent--; + code.WriteLine("}"); + code.Indent--; + code.WriteLine("}"); + code.WriteLine(); + } + + code.WriteLine("return bytes;"); + code.Indent--; + code.WriteLine("}"); + + code.Indent--; + code.WriteLine("}"); +} diff --git a/Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-2.cs b/Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-2.cs new file mode 100644 index 0000000000..9fb3e832ae --- /dev/null +++ b/Task/ASCII-art-diagram-converter/C-sharp/ascii-art-diagram-converter-2.cs @@ -0,0 +1,15 @@ +var bytes = new byte[Header.MarshalledSize]; +Random.Shared.NextBytes(bytes); +var header = Header.FromArray(bytes); +var bytes2 = header.ToArray(); +Debug.Assert(Enumerable.SequenceEqual(bytes, bytes2)); +Console.WriteLine($"Struct size: {Header.MarshalledSize} bytes"); +Console.WriteLine($"Binary data: {string.Join(" ", bytes.Select(b => b.ToString("B8")))}"); +Console.WriteLine($"Fields"); + +foreach (var (fname, fwidth) in fieldList) +{ + var value = typeof(Header).GetProperty(fname)!.GetValue(header); + var vstr = $"{value!:B}".PadLeft(fwidth, '0'); + Console.WriteLine($" {fname} = {vstr}"); +} diff --git a/Task/Abbreviations-automatic/EasyLang/abbreviations-automatic.easy b/Task/Abbreviations-automatic/EasyLang/abbreviations-automatic.easy new file mode 100644 index 0000000000..4953f45b97 --- /dev/null +++ b/Task/Abbreviations-automatic/EasyLang/abbreviations-automatic.easy @@ -0,0 +1,30 @@ +proc abbrev s$ . + d$[] = strtok s$ " " + repeat + lng += 1 + for i to len d$[] - 1 + a$ = substr d$[i] 1 lng + for j = i + 1 to len d$[] + if substr d$[j] 1 lng = a$ : break 2 + . + . + until i = len d$[] + . + print lng & ": " & s$ +. +repeat + s$ = input + if s$ = "" + print s$ + s$ = input + . + until s$ = "" + abbrev s$ +. +# +input_data +Sunday Monday Tuesday Wednesday Thursday Friday Saturday +Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag +E_djelë E_hënë E_martë E_mërkurë E_enjte E_premte E_shtunë +Ehud Segno Maksegno Erob Hamus Arbe Kedame +Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit diff --git a/Task/Abbreviations-easy/Crystal/abbreviations-easy.cr b/Task/Abbreviations-easy/Crystal/abbreviations-easy.cr new file mode 100644 index 0000000000..ddf3b6a402 --- /dev/null +++ b/Task/Abbreviations-easy/Crystal/abbreviations-easy.cr @@ -0,0 +1,17 @@ +abbrevs = Hash(String, String).new + +" Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy + COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find + NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput + Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO + MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT + READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT + RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up +".scan(/([A-Z]+)([a-z]*)/) do |m| + command, minimal_abbrev, extra_letters = m[0].upcase, m[1], m[2].upcase + extra_letters.chars.accumulate(minimal_abbrev).each do |k| abbrevs[k] = command end +end + +puts "riG rePEAT copies put mo rest types fup. 6 poweRin".split.map {|w| + abbrevs[w.upcase]? || "*error*" +}.join(" ") diff --git a/Task/Abbreviations-easy/EasyLang/abbreviations-easy.easy b/Task/Abbreviations-easy/EasyLang/abbreviations-easy.easy new file mode 100644 index 0000000000..17497ce6cb --- /dev/null +++ b/Task/Abbreviations-easy/EasyLang/abbreviations-easy.easy @@ -0,0 +1,42 @@ +a$ = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy" +a$ &= " COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find" +a$ &= " NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput" +a$ &= " Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO" +a$ &= " MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT" +a$ &= " READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT" +a$ &= " RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up" +cmd$[] = strtok a$ " " +# +func$ toupper s$ . + for c$ in strchars s$ + c = strcode c$ + if c >= 97 : c -= 32 + r$ &= strchar c + . + return r$ +. +for i to len cmd$[] + h$ = "" + for c$ in strchars cmd$[i] + if strcode c$ > strcode "Z" : break 1 + h$ &= c$ + . + abbr$[] &= h$ + cmd$[i] = toupper cmd$[i] +. +func$ getabbr in$ . + in$ = toupper in$ + for i to len cmd$[] + if strpos cmd$[i] in$ = 1 and strpos in$ abbr$[i] = 1 + return cmd$[i] + . + . + return "*error*" +. +in$[] = strtok input " " +for s$ in in$[] + write getabbr s$ & " " +. +# +input_data +riG rePEAT copies put mo rest types fup. 6 poweRin diff --git a/Task/Abbreviations-simple/EasyLang/abbreviations-simple.easy b/Task/Abbreviations-simple/EasyLang/abbreviations-simple.easy new file mode 100644 index 0000000000..ffbc7cc06f --- /dev/null +++ b/Task/Abbreviations-simple/EasyLang/abbreviations-simple.easy @@ -0,0 +1,42 @@ +a$ = "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3" +a$ &= " compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate" +a$ &= " 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2" +a$ &= " forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load" +a$ &= " locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2" +a$ &= " msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3" +a$ &= " refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left" +a$ &= " 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1" +toks$[] = strtok a$ " " +# +func$ toupper s$ . + for c$ in strchars s$ + c = strcode c$ + if c >= 97 : c -= 32 + r$ &= strchar c + . + return r$ +. +for tok$ in toks$[] + if number tok$ <> 0 + cnt[$] = number tok$ + else + cmd$[] &= toupper tok$ + cnt[] &= 999 + . +. +func$ getabbr in$ . + in$ = toupper in$ + for i to len cmd$[] + if cmd$[i] = in$ or len in$ >= cnt[i] and strpos cmd$[i] in$ = 1 + return cmd$[i] + . + . + return "*error*" +. +in$[] = strtok input " " +for s$ in in$[] + write getabbr s$ & " " +. +# +input_data +riG rePEAT copies put mo rest types fup. 6 poweRin diff --git a/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy b/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy index 3e0c4d008f..df68c01fac 100644 --- a/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy +++ b/Task/Abelian-sandpile-model-Identity/EasyLang/abelian-sandpile-model-identity.easy @@ -1,13 +1,11 @@ -proc out s[] . . +proc out s[] . for r = 0 to 2 - for c to 3 - write s[c + 3 * r] & " " - . + for c to 3 : write s[c + 3 * r] & " " print "" . print "" . -proc stab . m[] . +proc stab &m[] . n = sqrt len m[] repeat stable = 1 @@ -15,27 +13,17 @@ proc stab . m[] . if m[p] >= 4 stable = 0 m[p] -= 4 - if p > n - m[p - n] += 1 - . - if p mod n <> 0 - m[p + 1] += 1 - . - if p <= len m[] - n - m[p + n] += 1 - . - if p mod n <> 1 - m[p - 1] += 1 - . + if p > n : m[p - n] += 1 + if p mod n <> 0 : m[p + 1] += 1 + if p <= len m[] - n : m[p + n] += 1 + if p mod n <> 1 : m[p - 1] += 1 . . until stable = 1 . . func[] add s1[] s2[] . - for i to len s1[] - r[] &= s1[i] + s2[i] - . + for i to len s1[] : r[] &= s1[i] + s2[i] stab r[] return r[] . diff --git a/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy b/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy index c77b7a2530..12ff7d05c0 100644 --- a/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy +++ b/Task/Abelian-sandpile-model/EasyLang/abelian-sandpile-model.easy @@ -2,19 +2,18 @@ n = 77 len m[] n * n m[n * n div 2 + 1] = 10000 # -proc show . . +proc show . sc = 100 / n for r range0 n for c range0 n - move c * sc r * sc p = r * n + c + 1 - color 222 * m[p] - rect sc sc + gcolor 222 * m[p] + grect c * sc r * sc sc sc . . sleep 0 . -proc run . . +proc run . repeat mp[] = m[] stable = 1 diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-1.ballerina b/Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-1.ballerina new file mode 100644 index 0000000000..4b63fb03d5 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-1.ballerina @@ -0,0 +1,46 @@ +import ballerina/io; + +function divisors(int n) returns int[] { + if n < 1 { return []; } + int[] divisors = []; + int[] divisors2 = []; + int i = 1; + int k = n % 2 == 0 ? 1 : 2; + while i * i <= n { + if n % i == 0 { + divisors.push(i); + int j = n / i; + if j != i { divisors2.push(j); } + } + i += k; + } + if divisors2.length() > 0 { + divisors.push(...divisors2.reverse()); + } + return divisors; +} + +function properDivisors(int n) returns int[] { + int[] d = divisors(n); + int c = d.length(); + return c <= 1 ? [] : d.slice(0, c - 1); +} + +public function main() { + int d = 0; + int a = 0; + int p = 0; + foreach int i in 1...20000 { + int j = int:sum(...properDivisors(i)); + if j < i { + d += 1; + } else if j == i { + p += 1; + } else { + a += 1; + } + } + io:println("There are ", d, " deficient numbers between 1 and 20000"); + io:println("There are ", a, " abundant numbers between 1 and 20000"); + io:println("There are ", p, " perfect numbers between 1 and 20000"); +} diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-2.ballerina b/Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-2.ballerina new file mode 100644 index 0000000000..a96bb0a4a1 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Ballerina/abundant-deficient-and-perfect-number-classifications-2.ballerina @@ -0,0 +1,36 @@ +import ballerina/io; + +public function main() { + final int maxNumber = 20000; + int abundantCount = 0; + int deficientCount = 0; + int perfectCount = 0; + + int[] pds = []; + pds.push(0); // element 0 + pds.push(0); // element 1 + foreach int i in 2...maxNumber { + pds.push(1); + } + foreach int i in 2...maxNumber { + int j = i + i; + while j <= maxNumber { + pds[j] += i; + j += i; + } + } + foreach int n in 1...maxNumber { + int pdSum = pds[n]; + if pdSum < n { + deficientCount += 1; + } else if pdSum == n { + perfectCount += 1; + } else { // pdSum > n + abundantCount += 1; + } + } + + io:println("Abundant : ", abundantCount); + io:println("Deficient: ", deficientCount); + io:println("Perfect : ", perfectCount); +} diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena b/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena index 90f65ae3e7..7523b4abd7 100644 --- a/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena @@ -47,5 +47,5 @@ public program() int deficient := 0; int perfect := 0; classifyNumbers(20000, ref abundant, ref deficient, ref perfect); - console.printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect) + Console.printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect) } diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-1.rexx b/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-1.rexx index 076015bcfb..e2df0a6f1f 100644 --- a/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-1.rexx +++ b/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-1.rexx @@ -1,23 +1,51 @@ -/*REXX program counts the number of abundant/deficient/perfect numbers within a range.*/ -parse arg low high . /*obtain optional arguments from the CL*/ -high=word(high low 20000,1); low= word(low 1,1) /*obtain the LOW and HIGH values.*/ -say center('integers from ' low " to " high, 45, "═") /*display a header.*/ -!.= 0 /*define all types of sums to zero. */ - do j=low to high; $= sigma(j) /*get sigma for an integer in a range. */ - if $j then !.a= !.a + 1 /*Greater? " " abundant " */ - else !.p= !.p + 1 /*Equal? " " perfect " */ - end /*j*/ /* [↑] IFs are coded as per likelihood*/ +/* REXX */ +Call time 'R' +cnt.=0 +Do x=1 To 20000 + pd=proper_divisors(x) + sumpd=sum(pd) + Select + When xhi Then Do + list.npd=x + hi=npd + End + When npd=hi Then + list.hi=list.hi x + Otherwise + Nop + End + End -say ' the number of perfect numbers: ' right(!.p, length(high) ) -say ' the number of abundant numbers: ' right(!.a, length(high) ) -say ' the number of deficient numbers: ' right(!.d, length(high) ) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure; parse arg x; if x<2 then return 0; odd=x // 2 /* // ◄──remainder.*/ - s= 1 /* [↓] only use EVEN or ODD integers.*/ - do k=2+odd by 1+odd while k*kj then !.a= !.a + 1 /*Greater? " " abundant " */ - else !.p= !.p + 1 /*Equal? " " perfect " */ - end /*j*/ /* [↑] IFs are coded as per likelihood*/ +-- 8 May 2025 +include Settings -say ' the number of perfect numbers: ' right(!.p, length(high) ) -say ' the number of abundant numbers: ' right(!.a, length(high) ) -say ' the number of deficient numbers: ' right(!.d, length(high) ) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure; parse arg x 1 z; if x<5 then return max(0, x-1) /*sets X&Z to arg1.*/ - q=1; do while q<=z; q= q * 4; end /* ◄──↓ compute integer sqrt of Z (=R)*/ - r=0; do while q>1; q=q%4; _=z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end; end - odd= x//2 /* [↓] only use EVEN | ODD ints. ___*/ - s= 1; do k=2+odd by 1+odd to r /*divide by all integers up to √ x */ - if x//k==0 then s=s + k + x%k /*add the two divisors to (sigma) sum. */ - end /*k*/ /* [↑] % is the REXX integer division*/ - if r*r==x then return s - k /*Was X a square? If so, subtract √ x */ - return s /*return (sigma) sum of the divisors. */ +say 'ABUNDANT, DEFICIENT AND PERFECT NUMBER CLASSIFICATIONS' +say version +say +parse value 0 0 0 with a p d +do x = 1 to 20000 + sum = Aliquot(x) + select + when x < sum then + a = a+1 + when x = sum then + p = p+1 + otherwise + d = d+1 + end +end + +say 'In the range 1 - 20000' +say Format(a,5) 'numbers are abundant ' +say Format(p,5) 'numbers are perfect ' +say Format(d,5) 'numbers are deficient ' +say Time('e') 'seconds' +exit + +include Numbers +include Functions +include Special +include Abend diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-3.rexx b/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-3.rexx deleted file mode 100644 index e2df0a6f1f..0000000000 --- a/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-3.rexx +++ /dev/null @@ -1,51 +0,0 @@ -/* REXX */ -Call time 'R' -cnt.=0 -Do x=1 To 20000 - pd=proper_divisors(x) - sumpd=sum(pd) - Select - When xhi Then Do - list.npd=x - hi=npd - End - When npd=hi Then - list.hi=list.hi x - Otherwise - Nop - End - End - -Say 'In the range 1 - 20000' -Say format(cnt.abundant ,5) 'numbers are abundant ' -Say format(cnt.perfect ,5) 'numbers are perfect ' -Say format(cnt.deficient,5) 'numbers are deficient ' -Say time('E') 'seconds elapsed' -Exit - -proper_divisors: Procedure -Parse Arg n -Pd='' -If n=1 Then Return '' -If n//2=1 Then /* odd number */ - delta=2 -Else /* even number */ - delta=1 -Do d=1 To n%2 By delta - If n//d=0 Then - pd=pd d - End -Return space(pd) - -sum: Procedure -Parse Arg list -sum=0 -Do i=1 To words(list) - sum=sum+word(list,i) - End -Return sum diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-4.rexx b/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-4.rexx deleted file mode 100644 index 488aede163..0000000000 --- a/Task/Abundant-deficient-and-perfect-number-classifications/REXX/abundant-deficient-and-perfect-number-classifications-4.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/* REXX */ -Call time 'R' -cnt.=0 -Do x=1 to 20000 - sumpd=Sigma(x)-x - Select - When x 2n''', -
or,   equivalently,   the   ''sum of proper divisors''   (or aliquot sum)       '''s(n) > n'''. +An [[wp:Abundant_number|Abundant number]] is a number '''n''' for which the   ''sum of divisors''   '''\sigma(n) > 2n''', +
or,   equivalently,   the   ''sum of proper divisors''   (or aliquot sum)       '''s(n) > n'''. ;E.G.: -'''12'''   is abundant, it has the proper divisors     '''1,2,3,4 & 6'''     which sum to   '''16'''   ( > '''12''' or '''n'''); -
       or alternately,   has the sigma sum of   '''1,2,3,4,6 & 12'''   which sum to   '''28'''   ( > '''24''' or '''2n'''). +'''12'''   is abundant, it has the proper divisors     '''1, 2, 3, 4 & 6'''     which sum to   '''16'''   ( > '''12''' or '''n'''); +
       or alternately,   has the sigma sum of   '''1, 2, 3, 4, 6 & 12'''   which sum to   '''28'''   ( > '''24''' or '''2n'''). Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. @@ -15,7 +15,7 @@ To make things more interesting, this task is specifically about finding   ;Task *Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum. *Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum. -*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum. +*Find and display here: the first abundant odd number greater than one billion (10^9) and either its proper divisor sum or sigma sum. ;References: diff --git a/Task/Abundant-odd-numbers/Ballerina/abundant-odd-numbers.ballerina b/Task/Abundant-odd-numbers/Ballerina/abundant-odd-numbers.ballerina new file mode 100644 index 0000000000..42e8483b29 --- /dev/null +++ b/Task/Abundant-odd-numbers/Ballerina/abundant-odd-numbers.ballerina @@ -0,0 +1,73 @@ +import ballerina/io; + +function divisors(int n) returns int[] { + if n < 1 { return []; } + int[] divisors = []; + int[] divisors2 = []; + int i = 1; + int k = n % 2 == 0 ? 1 : 2; + while i * i <= n { + if n % i == 0 { + divisors.push(i); + int j = n / i; + if j != i { divisors2.push(j); } + } + i += k; + } + if divisors2.length() > 0 { + divisors.push(...divisors2.reverse()); + } + return divisors; +} + +function properDivisors(int n) returns int[] { + int[] d = divisors(n); + int c = d.length(); + return c <= 1 ? [] : d.slice(0, c - 1); +} + +function sumStr(int[] divs) returns string { + var f = function(string acc, int div) returns string { + return acc + div.toString() + " + "; + }; + string sum = divs.reduce(f, ""); + int len = sum.length(); + return sum.substring(0, len - 3); +} + +function abundantOdd(int searchFrom, int countFrom, int countTo, boolean printOne) + returns int { + int count = countFrom; + int n = searchFrom; + while count < countTo { + int[] divs = properDivisors(n); + int tot = int:sum(...divs); + if tot > n { + count += 1; + if !printOne || count >= countTo { + string s = sumStr(divs); + if !printOne { + string s1 = count.toString().padStart(2); + string s2 = n.toString().padStart(5); + io:println(`${s1}. ${s2} < ${s} = ${tot}`); + } else { + io:println(`${n} < ${s} = ${tot}`); + } + } + } + n += 2; + } + return n; +} + +public function main() { + final int max = 25; + io:println("The first ", max, " abundant odd numbers are:"); + int n = abundantOdd(1, 0, 25, false); + + io:println("\nThe one thousandth abundant odd number is:"); + _ = abundantOdd(n, 25, 1000, true); + + io:println("\nThe first abundant odd number above one billion is:"); + _ = abundantOdd(1e9+1, 0, 1, true); +} diff --git a/Task/Abundant-odd-numbers/EasyLang/abundant-odd-numbers.easy b/Task/Abundant-odd-numbers/EasyLang/abundant-odd-numbers.easy index 5cfb14b7e7..8092c07c7d 100644 --- a/Task/Abundant-odd-numbers/EasyLang/abundant-odd-numbers.easy +++ b/Task/Abundant-odd-numbers/EasyLang/abundant-odd-numbers.easy @@ -14,7 +14,7 @@ fastfunc sumdivs n . return sum . n = 1 -numfmt 0 6 +numfmt 6 0 while cnt < 1000 sum = sumdivs n if sum > n diff --git a/Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina b/Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina new file mode 100644 index 0000000000..a8f8252dea --- /dev/null +++ b/Task/Accumulator-factory/Ballerina/accumulator-factory.ballerina @@ -0,0 +1,38 @@ +import ballerina/io; + +type numeric int|float|decimal; + +function accumulator(numeric acc) returns (function(numeric) returns numeric) { + numeric sum = acc; + return function(numeric n) returns numeric { + numeric sum2 = sum; + if sum2 is int && n is int { + sum2 += n; + } else if sum2 is float && n is float { + sum2 += n; + } else if sum2 is decimal && n is decimal { + sum2 += n; + } else if sum2 is int && n is float { + sum2 = sum2 + n; + } else if sum2 is int && n is decimal { + sum2 = sum2 + n; + } else if sum2 is float && n is int { + sum2 += n; + } else if sum2 is float && n is decimal { + sum2 = sum2 + n; + } else if sum2 is decimal && n is int { + sum2 += n; + } else if sum2 is decimal && n is float { + sum2 += n; + } + sum = sum2; + return sum; + }; +} + +public function main() { + var x = accumulator(1); + _ = x(5); + _ = accumulator(2); + io:println(x(2.3)); +} diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index be112e0585..ca3b64dd19 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -12,5 +12,5 @@ public program() var y := accumulator(3); - console.write(x(2.3r)) + Console.write(x(2.3r)) } diff --git a/Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina b/Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina new file mode 100644 index 0000000000..ff31e0dfeb --- /dev/null +++ b/Task/Achilles-numbers/Ballerina/achilles-numbers.ballerina @@ -0,0 +1,92 @@ +import ballerina/io; + +map pps = {}; + +function getPerfectPowers(int maxExp) { + int upper = 10.0.pow(maxExp); + int upper2 = 10.0.pow(maxExp).sqrt().floor(); + foreach int i in 2...upper2 { + int p = i; + while true { + if p > int:MAX_VALUE / i { break; } + p *= i; + if p >= upper { break; } + pps[p.toString()] = 1; + } + } +} + +function getAchilles(int minExp, int maxExp) returns map { + int lower = 10.0.pow(minExp); + int upper = 10.0.pow(maxExp); + int upper2 = 10.0.pow(maxExp).cbrt().floor(); + int upper3 = 10.0.pow(maxExp).sqrt().floor(); + map achilles = {}; + foreach int b in 1...upper2 { + int b3 = b * b * b; + foreach int a in 1...upper3 { + int p = b3 * a * a; + if p >= upper { break; } + if p >= lower { + string ps = p.toString(); + if !pps.hasKey(ps) { + achilles[ps] = 1; + } + } + } + } + return achilles; +} + +function totient(int m) returns int { + if m < 1 { return 0; } + int tot = m; + int n = m; + int i = 2; + while i * i <= n { + if (n % i) == 0 { + while (n % i) == 0 { n /= i; } + tot -= tot / i; + } + if i == 2 { i = 1; } + i += 2; + } + if n > 1 { tot -= tot / n; } + return tot; +} + +public function main() returns error? { + final int maxDigits = 14; + getPerfectPowers(maxDigits); + map achillesSet = getAchilles(1, 5); // enough for first 2 parts + int[] achilles = achillesSet.keys().map(s => check int:fromString(s)).sort(); + io:println("First 50 Achilles numbers:"); + foreach int i in 0..<50 { + string s = achilles[i].toString().padStart(4); + io:print(s, " "); + if (i + 1) % 10 == 0 { io:println(); } + } + io:println("\nFirst 30 strong Achilles numbers:"); + int[] strongAchilles = []; + int count = 0; + int n = 0; + while count < 30 { + int tot = totient(achilles[n]); + if achillesSet.hasKey(tot.toString()) { + strongAchilles.push(achilles[n]); + count += 1; + } + n += 1; + } + foreach int j in 0..<30 { + string t = strongAchilles[j].toString().padStart(5); + io:print(t, " "); + if (j + 1) % 10 == 0 { io:println(); } + } + + io:println("\nNumber of Achilles numbers with:"); + foreach int d in 2...maxDigits { + int ac = getAchilles(d - 1, d).length(); + io:println(d.toString().padStart(2), " digits: ", ac); + } +} diff --git a/Task/Achilles-numbers/EasyLang/achilles-numbers.easy b/Task/Achilles-numbers/EasyLang/achilles-numbers.easy index ec0935dde9..fda73a8936 100644 --- a/Task/Achilles-numbers/EasyLang/achilles-numbers.easy +++ b/Task/Achilles-numbers/EasyLang/achilles-numbers.easy @@ -1,14 +1,10 @@ func gcd n d . - if d = 0 - return n - . + if d = 0 : return n return gcd d (n mod d) . func totient n . for m = 1 to n - if gcd m n = 1 - tot += 1 - . + if gcd m n = 1 : tot += 1 . return tot . @@ -16,41 +12,29 @@ func isPowerful m . n = m f = 2 l = sqrt m - if m <= 1 - return 0 - . + if m <= 1 : return 0 while 1 = 1 q = n div f if n mod f = 0 - if m mod (f * f) <> 0 - return 0 - . + if m mod (f * f) <> 0 : return 0 n = q - if f > n - return 1 - . + if f > n : return 1 else f += 1 if f > l - if m mod (n * n) <> 0 - return 0 - . + if m mod (n * n) <> 0 : return 0 return 1 . . . . func isAchilles n . - if isPowerful n = 0 - return 0 - . + if isPowerful n = 0 : return 0 m = 2 a = m * m repeat repeat - if a = n - return 0 - . + if a = n : return 0 a *= m until a > n . @@ -91,9 +75,7 @@ b = 100 for i = 2 to 5 num = 0 for n = a to b - 1 - if isAchilles n = 1 - num += 1 - . + num += isAchilles n . write num & " " a = b diff --git a/Task/Ackermann-function/Ballerina/ackermann-function.ballerina b/Task/Ackermann-function/Ballerina/ackermann-function.ballerina new file mode 100644 index 0000000000..95e0bc7de0 --- /dev/null +++ b/Task/Ackermann-function/Ballerina/ackermann-function.ballerina @@ -0,0 +1,14 @@ +import ballerina/io; + +function ackermann(int m, int n) returns int { + if m == 0 { return n + 1; } + if n == 0 { return ackermann(m - 1, 1); } + return ackermann(m - 1, ackermann(m, n - 1)); +} + +public function main() { + int[][] pairs = [ [1, 3], [2, 3], [3, 3], [1, 5], [2, 5], [3, 5] ]; + foreach var p in pairs { + io:println(`A[${p[0]}, ${p[1]}] = ${ackermann(p[0], p[1])}`); + } +} diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index fc46c62750..c8a0ec4580 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -1,5 +1,7 @@ import extensions; +// --- Ackermann function --- + ackermann(m,n) { if(n < 0 || m < 0) @@ -8,11 +10,11 @@ ackermann(m,n) }; m => - 0 { ^n + 1 } - ! { + 0 : { ^n + 1 } + ! : { n => - 0 { ^ackermann(m - 1,1) } - ! { ^ackermann(m - 1,ackermann(m,n-1)) } + 0 : { ^ackermann(m - 1,1) } + ! : { ^ackermann(m - 1,ackermann(m,n-1)) } } } @@ -22,9 +24,9 @@ public program() { for(int j := 0; j <= 5; j += 1) { - console.printLine("A(",i,",",j,")=",ackermann(i,j)) + Console.printLine("A(",i,",",j,")=",ackermann(i,j)) } }; - console.readChar() + Console.readChar() } diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina new file mode 100644 index 0000000000..a4d319d761 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ballerina/add-a-variable-to-a-class-instance-at-runtime.ballerina @@ -0,0 +1,23 @@ +import ballerina/io; + +// Person is an 'open' record type which allows fields of 'anydata' type +// to be added at runtime. +type Person record { + string name; + int age; +}; + +public function main() { + // Create an instance of Person with an additional 'town' field. + Person p = { + name: "Fred", + age: 40, + "town": "Boston" // extra field name needs to be in quotes + }; + + // Print name and age fields - using standard '.' syntax. + io:print(p.name, " is ", p.age); + + // Print the additional field - using a map-like syntax. + io:println(" and lives in ", p["town"], "."); +} diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena index 9634046d11..229abebea3 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena @@ -19,7 +19,7 @@ public program() object.foo := "bar"; - console.printLine(object,".foo=",object.foo); + Console.printLine(object,".foo=",object.foo); - console.readChar() + Console.readChar() } diff --git a/Task/Additive-primes/ALGOL-60/additive-primes.alg b/Task/Additive-primes/ALGOL-60/additive-primes.alg new file mode 100644 index 0000000000..177adf1e20 --- /dev/null +++ b/Task/Additive-primes/ALGOL-60/additive-primes.alg @@ -0,0 +1,60 @@ +begin + +integer procedure sumdigits(n); + value n; integer n; +begin + integer q, sum; + sum := 0; + for sum := sum while n > 0 do + begin + q := entier(n / 10); + sum := sum + (n - q * 10); + n := q; + end; + sumdigits := sum; +end; + +boolean procedure isprime(n); +value n; integer n; +begin + if n < 2 then + isprime := false + else if n = entier(n / 2) * 2 then + isprime := (n = 2) + else + begin + comment - check odd divisors up to sqrt(n); + integer i, limit; + boolean divisible; + i := 3; + limit := entier(sqrt(n)); + divisible := false; + for i := i while i <= limit and not divisible do + begin + if entier(n / i) * i = n then + divisible := true; + i := i + 2 + end; + isprime := not divisible; + end; +end; + +integer i, count; +outstring(1,"Looking up to 500 for additive primes\n"); +count := 0; +for i := 2 step 1 until 500 do + if isprime(i) then + begin + if isprime(sumdigits(i)) then + begin + outinteger(1,i); + count := count + 1; + if count = entier(count / 10) * 10 then + outstring(1,"\n"); + end; + end; +outstring(1,"\n"); +outinteger(1,count); +outstring(1,"were found\n"); + +end diff --git a/Task/Additive-primes/ALGOL-M/additive-primes.alg b/Task/Additive-primes/ALGOL-M/additive-primes.alg new file mode 100644 index 0000000000..54334dd123 --- /dev/null +++ b/Task/Additive-primes/ALGOL-M/additive-primes.alg @@ -0,0 +1,64 @@ +BEGIN + +% RETURN N MOD M % +INTEGER FUNCTION MOD(N, M); +INTEGER N, M; +BEGIN + MOD := N - (N / M) * M; +END; + +% RETURN 1 IF N IS PRIME, OTHERWISE 0 % +INTEGER FUNCTION ISPRIME(N); +INTEGER N; +BEGIN + IF N = 2 THEN + ISPRIME := 1 + ELSE IF (N < 2) OR (MOD(N,2) = 0) THEN + ISPRIME := 0 + ELSE % TEST ODD DIVISORS UP TO SQRT OF N % + BEGIN + INTEGER I, DIVISIBLE; + I := 3; + DIVISIBLE := 0; + WHILE (I * I <= N) AND (DIVISIBLE = 0) DO + BEGIN + IF MOD(N,I) = 0 THEN DIVISIBLE := 1; + I := I + 2; + END; + ISPRIME := 1 - DIVISIBLE; + END; +END; + +% RETURN THE SUM OF THE DIGITS OF N % +INTEGER FUNCTION SUMDIGITS(N); +INTEGER N; +BEGIN + INTEGER SUM; + SUM := 0; + WHILE N > 0 DO + BEGIN + SUM := SUM + MOD(N, 10); + N := N / 10; + END; + SUMDIGITS := SUM; +END; + +% LOOK FOR ADDITIVE PRIMES IN RANGE 1 TO 500 % +INTEGER I, S, COUNT; +COUNT := 0; +FOR I := 1 STEP 1 UNTIL 500 DO + BEGIN + IF ISPRIME(I)=1 THEN + BEGIN + S := SUMDIGITS(I); + IF ISPRIME(S)=1 THEN + BEGIN + WRITEON(I); + COUNT := COUNT + 1; + IF MOD(COUNT,8) = 0 THEN WRITE(""); + END; + END; + END; +WRITE(COUNT," ADDITIVE PRIMES WERE FOUND"); + +END diff --git a/Task/Additive-primes/Ballerina/additive-primes.ballerina b/Task/Additive-primes/Ballerina/additive-primes.ballerina new file mode 100644 index 0000000000..f4d3373ce4 --- /dev/null +++ b/Task/Additive-primes/Ballerina/additive-primes.ballerina @@ -0,0 +1,67 @@ +import ballerina/io; + +function sumDigits(int m) returns int { + int n = m; // make mutable + int sum = 0; + while n > 0 { + sum += n % 10; + n /= 10; + } + return sum; +} + +function isPrime(int n) returns boolean { + if n < 2 { return false; } + if n % 2 == 0 { return n == 2; } + if n % 3 == 0 { return n == 3; } + int d = 5; + while d * d <= n { + if n % d == 0 { return false; } + d += 2; + if n % d == 0 { return false; } + d += 4; + } + return true; +} + +function getPrimes(int n) returns int[] { + if n < 2 { return []; } + if n == 2 { return [2]; } + int k = (n - 3) / 2 + 1; + boolean[] marked = []; + marked.setLength(k); + foreach int i in 0..n).sqrt().floor(); + int lim = (f - 3) / 2 + 1; + foreach int i in 0.. 2 - return 0 - . + if n mod 2 = 0 and n > 2 : return 0 i = 3 sq = sqrt n while i <= sq - if n mod i = 0 - return 0 - . + if n mod i = 0 : return 0 i += 2 . return 1 @@ -22,9 +18,6 @@ func digsum n . for i = 2 to 500 if prime i = 1 s = digsum i - if prime s = 1 - write i & " " - . + if prime s = 1 : write i & " " . . -print "" diff --git a/Task/Additive-primes/PL-I-80/additive-primes.pli b/Task/Additive-primes/PL-I-80/additive-primes.pli new file mode 100644 index 0000000000..cbb1259113 --- /dev/null +++ b/Task/Additive-primes/PL-I-80/additive-primes.pli @@ -0,0 +1,52 @@ +additive_primes: procedure options (main); + %replace + search_limit by 500, + true by '1'b, + false by '0'b; + dcl (i, count) fixed bin; + put skip edit('Searching up to ', search_limit, + ' for additive primes') (a,f(3),a); + put skip; + count = 0; + do i = 2 to search_limit; + if isprime(i) then + do; + if isprime(sumdigits(i)) then + do; + put edit(i) (f(5)); + count = count + 1; + if mod(count,8) = 0 then put skip; + end; + end; + end; + put skip edit(count, ' were found') (f(3), a); + +/* return true if n is prime */ +isprime: proc(n) returns (bit(1)); + dcl + (n, i, limit) fixed bin; + if n < 2 then return (false); + if mod(n, 2) = 0 then return (n = 2); + limit = floor(sqrt(n)); + i = 3; + do while ((i <= limit) & (mod(n, i) ^= 0)); + i = i + 2; + end; + return (i > limit); +end isprime; + +/* return the sum of the digits of n */ +sumdigits: proc(n) returns (fixed bin); + dcl + (n, nn, sum) fixed bin; + /* use copy, since n is passed by reference */ + nn = n; + sum = 0; + do while (nn > 0); + sum = sum + mod(nn, 10); + nn = nn / 10; + end; + return (sum); +end sumdigits; + +end additive_primes; diff --git a/Task/Additive-primes/PascalABC.NET/additive-primes.pas b/Task/Additive-primes/PascalABC.NET/additive-primes.pas new file mode 100644 index 0000000000..c8f11a6506 --- /dev/null +++ b/Task/Additive-primes/PascalABC.NET/additive-primes.pas @@ -0,0 +1,4 @@ +## uses School;//поиск аддитивных простых чисел +var AdditivePrimes := Primes(500).Where(n -> n.Digits.Sum.IsPrime).ToArray; +Print('Additive Primes:'); AdditivePrimes.Println; +Println('Additive Primes Count:', AdditivePrimes.Count); diff --git a/Task/Additive-primes/REXX/additive-primes-2.rexx b/Task/Additive-primes/REXX/additive-primes-2.rexx index d7524b90f3..398faf76e3 100644 --- a/Task/Additive-primes/REXX/additive-primes-2.rexx +++ b/Task/Additive-primes/REXX/additive-primes-2.rexx @@ -1,61 +1,28 @@ +-- 22 Mar 2025 include Settings -say version; say 'Additive primes'; say +say 'ADDITIVE PRIMES' +say version +say arg n numeric digits 16 if n = '' then - n = -500 + n = 500 show = (n > 0); n = Abs(n) -a = Additiveprimes(n) +a = Additives(n) if show then do do i = 1 to a - call Charout ,Right(addi.additiveprime.i,8)' ' + call Charout ,Right(addi.i,8)' ' if i//10 = 0 then say end say end -say a 'additive Primes found below' n -say Time('e') 'seconds' +say a 'additive primes found below' n +say Time('e')/1 'seconds' exit -Additiveprimes: -/* Additive prime numbers */ -procedure expose addi. prim. -arg x -/* Init */ -addi. = 0 -/* Fast values */ -if x < 2 then - return 0 -if x < 101 then do - a = '2 3 5 7 11 23 29 41 43 47 61 67 83 89 999' - do n = 1 to Words(a) - w = Word(a,n) - if w > x then - leave - addi.additiveprime.n = w - end - n = n-1; addi.0 = n - return n -end -/* Get primes */ -p = Primes(x) -/* Collect additive primes */ -n = 0 -do i = 1 to p - q = prim.Prime.i; s = 0 - do j = 1 to Length(q) - s = s+Substr(q,j,1) - end - if Prime(s) then do - n = n+1; addi.additiveprime.n = q - end -end -/* Return number of additive primes */ -return n - -include Functions -include Numbers include Sequences +include Numbers +include Functions include Abend diff --git a/Task/Additive-primes/Raku/additive-primes.raku b/Task/Additive-primes/Raku/additive-primes.raku index 7497ffbb89..24abe19684 100644 --- a/Task/Additive-primes/Raku/additive-primes.raku +++ b/Task/Additive-primes/Raku/additive-primes.raku @@ -1,3 +1,3 @@ unit sub MAIN ($limit = 500); say "{+$_} additive primes < $limit:\n{$_».fmt("%" ~ $limit.chars ~ "d").batch(10).join("\n")}", - with ^$limit .grep: { .is-prime and .comb.sum.is-prime } + with ^$limit .grep: { .is-prime && .comb.sum.is-prime } diff --git a/Task/Additive-primes/S-BASIC/additive-primes.basic b/Task/Additive-primes/S-BASIC/additive-primes.basic new file mode 100644 index 0000000000..1ca0da2c9a --- /dev/null +++ b/Task/Additive-primes/S-BASIC/additive-primes.basic @@ -0,0 +1,55 @@ +$constant true = 0FFFFH +$constant false = 0 +$constant limit = 500 + +function sum.of.digits(n = integer) = integer + var i, sum = integer + var s = string + var ch = char + s = str$(n) + sum = 0 + for i = 2 to len(s) + ch = mid(s,i,1) + sum = sum + (ch - '0') + next i +end = sum + +function mod(n, m = integer) = integer +end = n - (n / m) * m + +comment + build a table of prime numbers using + the classic sieve of Erathosthenes +end +dim integer prime(limit) +var i, j, count = integer +prime(1) = false +for i = 2 to limit + prime(i) = true +next i +rem - strike out multiples of each prime found +for i = 2 to sqr(limit) + if prime(i) then + begin + for j = i + i to limit step i + prime(j) = false + next j + end +next i + +rem - use the table for the search +print "Searching up to"; limit; " for additive primes" +count = 0 +for i = 2 to limit + if prime(i) then + if prime(sum.of.digits(i)) then + begin + print using "### "; i; + count = count + 1 + if mod(count, 10) = 0 then print + end +next i +print +print count;" were found" + +end diff --git a/Task/Additive-primes/TypeScript/additive-primes.ts b/Task/Additive-primes/TypeScript/additive-primes.ts new file mode 100644 index 0000000000..d3008744d2 --- /dev/null +++ b/Task/Additive-primes/TypeScript/additive-primes.ts @@ -0,0 +1,29 @@ +function isPrime(n: number): boolean { + if (n < 2) return false; + if (n < 4) return true; + if (n % 2 == 0 || n % 3 == 0) return false; + for (let i = 5; i <= n ** 0.5; i += 6) { + if (n % i == 0 || n % (i+2) == 0) return false; + } + return true; +} + +function sumDigits(x: number): number { + let sum = 0; + while (x > 0) { + sum = sum + (x % 10); + x = Math.floor(x / 10); + } + return sum; +} + +const additivePrimes: number[] = []; + +for (let i = 2; i < 10**7; i++) { + if (isPrime(i) && isPrime(sumDigits(i))) { + additivePrimes.push(i); + } +} + +console.log(additivePrimes); +console.log(`Found ${additivePrimes.length} values`); diff --git a/Task/Address-of-a-variable/Ballerina/address-of-a-variable.ballerina b/Task/Address-of-a-variable/Ballerina/address-of-a-variable.ballerina new file mode 100644 index 0000000000..9e682fb12b --- /dev/null +++ b/Task/Address-of-a-variable/Ballerina/address-of-a-variable.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + int[] a = [1, 2, 3, 4]; + int[] b = [1, 2, 3, 4]; + io:println(a == b); // 'true' as values are the same + io:println(a === b); // 'false' as stored at different addresses +} diff --git a/Task/Align-columns/EasyLang/align-columns.easy b/Task/Align-columns/EasyLang/align-columns.easy index 8bac81bda5..3058394bc3 100644 --- a/Task/Align-columns/EasyLang/align-columns.easy +++ b/Task/Align-columns/EasyLang/align-columns.easy @@ -1,5 +1,5 @@ global width inp$[] . -proc read . . +proc read . repeat inp$ = input until inp$ = "" @@ -12,7 +12,7 @@ proc read . . . read # -proc out mode . . +proc out mode . for inp$ in inp$[] ar$[] = strsplit inp$ "$" for s$ in ar$[] diff --git a/Task/Align-columns/Emacs-Lisp/align-columns.l b/Task/Align-columns/Emacs-Lisp/align-columns.l index a073ab13c1..3588e6e422 100644 --- a/Task/Align-columns/Emacs-Lisp/align-columns.l +++ b/Task/Align-columns/Emacs-Lisp/align-columns.l @@ -1,246 +1,129 @@ -(defun rob-even-p (integer) - "Test if INTEGER is even." - (= (% integer 2) 0)) +(defun prepare-data () + "Process data into list of lists." + (let ((all-lines) + (processed-line)) + (dolist (one-line (split-string "Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +are$delineated$by$a$single$'dollar'$character,$write$a$program +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ +column$are$separated$by$at$least$one$space. +Further,$allow$for$each$word$in$a$column$to$be$either$left$ +justified,$right$justified,$or$center$justified$within$its$column." "[\n\r]" :OMIT-NULLS)) + (dolist (one-word (split-string one-line "\\$")) + (push one-word processed-line)) + (push (nreverse processed-line) all-lines) + (setq processed-line nil)) + (nreverse all-lines))) -(defun rob-odd-p (integer) - "Test if INTEGER is odd." - (not (rob-even-p integer))) +(defun get-column (column-number data) + "Get words from COLUMN-NUMBER column in DATA." + (let ((column-result)) + (setq column-number (- column-number 1)) + (dolist (line data) + (if (nth column-number line) + (push (nth column-number line) column-result) + (push "" column-result))) + column-result)) -(defun both-odd-or-both-even-p (x y) - "Test if X and Y are both even or both odd." - (or (and (rob-even-p x) (rob-even-p y)) - (and (rob-odd-p x) (rob-odd-p y)))) +(defun calc-column-width (column-number data) + "Calculate padded width for COLUMN-NUMBER in DATA." + (let ((column-words (get-column column-number data))) + (+ 2 (apply #'max (mapcar #'length column-words))))) -(defun word-lengths (words) - "Convert WORDS into list of lengths of each word." - (mapcar 'length words)) +(defun get-last-column (data) + "Find the last column in DATA." + (apply #'max (mapcar #'length data))) -(defun get-one-row (row-number rows-columns-words) - "Get ROW-NUMBER row from ROWS-COLUMNS-WORDS. -ROWS-COLUMNS-WORDS is list of lists in form of row, column, word." - (seq-filter - (lambda (element) - (= row-number (car element))) - rows-columns-words)) +(defun get-column-widths (data) + "Get a list of column widths from DATA." + (let ((current-column 1) + (last-column (get-last-column data)) + (column-widths)) + (while (<= current-column last-column) + (push (calc-column-width current-column data) column-widths) + (setq current-column (1+ current-column))) + (nreverse column-widths))) -(defun get-one-word (row-number column-number rows-columns-words) - "Get one word from ROWS-COLUMNS-WORDS at ROW-NUMBER and COLUMN-NUMBER. -ROWS-COLUMNS-WORDS is list of lists in form of row, column, word." - (delq nil - (mapcar - (lambda (element) - (when (= column-number (nth 1 element)) - (nth 2 element))) - (get-one-row row-number rows-columns-words)))) +(defun get-one-column-width (column-number data) + "Get column width of COLUMN-NUMBER from DATA." + (let ((column-widths (get-column-widths data))) + (nth (- column-number 1) column-widths))) -(defun get-last-row (rows-columns-words) - "Get the number of the last row of ROWS-COLUMNS-WORDS. -ROWS-COLUMNS-WORDS is a list of lists, each list in the form of -row, column, word." - (apply 'max (mapcar 'car rows-columns-words))) +(defun center-align-one-word (word column-width) + "Center align WORD in space of COLUMN-WIDTH." + (let* ((word-width (length word)) + (total-padding (- column-width word-width)) + (pre-padding-length (/ total-padding 2)) + (post-padding-length (- column-width (+ pre-padding-length word-width))) + (pre-padding (make-string pre-padding-length ? )) + (post-padding (make-string post-padding-length ? ))) + (insert (format "%s%s%s" pre-padding word post-padding)))) -(defun list-nth-column (column rows-columns-words) - "List the words in column COLUMN of ROWS-COLUMNS-WORDS. -ROWS-COLUMNS-WORDS is a list of lists, each list in the form of row, column, -word." - (let ((row 1) - (column-word) - (last-row (get-last-row rows-columns-words )) - (matches nil)) - (while (and (<= row last-row) - (<= column (get-last-column rows-columns-words))) - (setq column-word (get-one-word row column rows-columns-words)) - (when (null column-word) - (setq column-word "")) - (push column-word matches) - (setq row (1+ row))) - (flatten-tree (nreverse matches)))) +(defun center-align-one-line (one-line column-widths) + "Center align ONE-LINE using COLUMN-WIDTHS." + (let ((word-position 0)) + (dolist (word one-line) + (center-align-one-word word (nth word-position column-widths)) + (setq word-position (1+ word-position))))) -(defun get-widest-in-column (column) - "Get the widest word in COLUMN, which is a list of words." - (apply #'max (word-lengths column))) +(defun center-align-lines (data) + "Center align columns of words in DATA." + (let ((column-widths (get-column-widths data))) + (dolist (one-line data) + (center-align-one-line one-line column-widths) + (insert (format "%s" "\n"))))) -(defun get-column-width (column) - "Calculate the width of COLUMN, which is a list of words." - (+ (get-widest-in-column column) 2)) +(defun left-align-one-word (word column-width) + "Left align WORD in space of COLUMN-WIDTH." + (let* ((word-width (length word)) + (total-padding (- column-width word-width)) + (pre-padding-length 1) + (post-padding-length (- column-width (+ pre-padding-length word-width))) + (pre-padding (make-string pre-padding-length ? )) + (post-padding (make-string post-padding-length ? ))) + (insert (format "%s%s%s" pre-padding word post-padding)))) -(defun get-column-widths (rows-columns-words) - "Make a list of the column widths in ROWS-COLUMNS-WORDS. -ROWS-COLUMNS-WORDS is list of lists, with each list in the form of row, column, -word." - (let ((last-column (get-last-column rows-columns-words)) - (column 1) - (columns)) - (while (<= column last-column) - (push (get-column-width (list-nth-column column rows-columns-words)) columns) - (setq column (1+ column))) - (reverse columns))) +(defun left-align-one-line (one-line column-widths) + "Left align ONE-LINE using COLUMN-WIDTHS." + (let ((word-position 0)) + (dolist (word one-line) + (left-align-one-word word (nth word-position column-widths)) + (setq word-position (1+ word-position))))) -(defun add-column-widths (widths rows-columns-words) - "Add WIDTHS to ROWS-COLUMNS-WORDS. -ROWS-COLUMNS-WORDS is a list of lists, with each list in the form of row, -column, word. WIDTHS are the widths of each column. Output is a -list of lists, with each list in the form of column-width, row, -column, word." - (let ((new-data) - (new-database) - (column) - (width)) - (dolist (data rows-columns-words) - (setq column (cadr data)) - (setq width (nth (- column 1) widths)) - (setq new-data (push width data)) - (push new-data new-database)) - (nreverse new-database))) +(defun left-align-lines (data) + "Left align columns of words in DATA." + (let ((column-widths (get-column-widths data))) + (dolist (one-line data) + (left-align-one-line one-line column-widths) + (insert (format "%s" "\n"))))) -(defun get-last-column (rows-columns-words) - "Get the number of the last column in ROWS-COLUMNS-WORDS." - (apply 'max (mapcar 'cadr rows-columns-words))) +(defun right-align-one-word (word column-width) + "Right align WORD in space of COLUMN-WIDTH." + (let* ((word-width (length word)) + (total-padding (- column-width word-width)) + (post-padding-length 1) + (pre-padding-length (- column-width (+ post-padding-length word-width))) + (pre-padding (make-string pre-padding-length ? )) + (post-padding (make-string post-padding-length ? ))) + (insert (format "%s%s%s" pre-padding word post-padding)))) -(defun create-rows-columns-words () - "Put text from column-data.txt file in lists. -Each list consists of a row number, a column number, and a word." - (let ((lines) - (line-number 0) - (word-number) - (words)) - (with-temp-buffer - (insert-file-contents "~/Documents/Elisp/column_data.txt") - (beginning-of-buffer) - (dolist (line (split-string (buffer-string) "[\r\n]" :no-nulls)) - (push line lines)) - (setq lines (nreverse lines))) - (dolist (line lines) - (setq line-number (1+ line-number)) - (setq word-number 0) - (dolist (word (split-string line "\\$" :no-nulls)) - (setq word-number (1+ word-number)) - (push (list line-number word-number word) words))) - (setq words (nreverse words)))) +(defun right-align-one-line (one-line column-widths) + "Right align ONE-LINE using COLUMN-WIDTHS." + (let ((word-position 0)) + (dolist (word one-line) + (right-align-one-word word (nth word-position column-widths)) + (setq word-position (1+ word-position))))) -(defun pad-for-center-align (column-width text) - "Pad TEXT to center in space of COLUMN-WIDTH." - (let* ((text-width (length text)) - (total-padding-length (- column-width text-width)) - (pre-padding-length) - (post-padding-length) - (pre-padding) - (post-padding)) - (if (both-odd-or-both-even-p text-width column-width) - (progn - (setq pre-padding-length (/ total-padding-length 2)) - (setq post-padding-length pre-padding-length)) - (setq pre-padding-length (+ (/ total-padding-length 2) 1)) - (setq post-padding-length (- pre-padding-length 1))) - (setq pre-padding (make-string pre-padding-length ? )) - (setq post-padding (make-string post-padding-length ? )) - (format "%s%s%s" pre-padding text post-padding))) +(defun right-align-lines (data) + "Right align columns of words in DATA." + (let ((column-widths (get-column-widths data))) + (dolist (one-line data) + (right-align-one-line one-line column-widths) + (insert (format "%s" "\n"))))) -(defun create-a-center-aligned-line (widths-1row-columns-words) - "Create a centered line based on WIDTHS-1ROW-COLUMNS-WORDS. -WIDTHS-1ROW-COLUMNS-WORDS is a list of lists. Each list consists -of the column-width, the row number, the column number, and the -word. The row number is the same in all lists." - (let ((full-line "") - (next-section)) - (insert "\n") - (dolist (word-data widths-1row-columns-words) - ;; below, nth 0 is the column width, nth 3 is the word - (setq next-section (pad-for-center-align (nth 0 word-data) (nth 3 word-data))) - (setq full-line (concat full-line next-section))) - (insert full-line))) - -(defun pad-for-left-align (column-width text) - "Pad TEXT to left-align in space of COLUMN-WIDTH." - (let* ((text-width (length text)) - (post-padding-length (- column-width text-width))) - (setq post-padding (make-string post-padding-length ? )) - (format "%s%s" text post-padding))) - -(defun create-a-left-aligned-line (widths-1row-columns-words) - "Create a left-aligned line based on WIDTHS-1ROW-COLUMNS-WORDS. -Each element of WIDTHS-1ROW-COLUMNS-WORDS consists of the column -width, the row number, the column number, and the word. The row -number is the same in every case." - (let ((full-line "") - (next-section)) - (insert "\n") - (dolist (one-item widths-1row-columns-words) - (setq next-section (pad-for-left-align (nth 0 one-item) (nth 3 one-item))) - (setq full-line (concat full-line next-section))) - (insert full-line))) - -(defun pad-for-right-align (column-width text) - "Pad TEXT to right-align in space of COLUMN-WIDTH." - (let* ((text-width (length text)) - (pre-padding-length (- column-width text-width))) - (setq pre-padding (make-string pre-padding-length ? )) - (format "%s%s" pre-padding text))) - -(defun create-a-right-aligned-line (widths-1row-columns-words) - "Create a right-aligned line based on WIDTHS-1ROW-COLUMNS-WORDS. -Each element of WIDTHS-1ROW-COLUMNS-WORDS consists of the column -width, the row number, the column number, and the word. The row -number is the same in every case." - (let ((full-line "") - (next-section)) - (insert "\n") - (dolist (one-item widths-1row-columns-words) - (setq next-section (pad-for-right-align (nth 0 one-item) (nth 3 one-item))) - (setq full-line (concat full-line next-section))) - (insert full-line))) - -(defun left-align-lines (rows-columns-words) - "Write ROWS-COLUMNS-WORDS in left-aligned columns. -ROWS-COLUMNS-WORDS is a list of lists. Each list consists of the -row number, the column number, and the word." - (let* ((row-number 1) - (column-widths (get-column-widths rows-columns-words)) - (last-row (get-last-row rows-columns-words)) - (one-row) - (width-place 0)) - (while (<= row-number last-row) - (setq one-row (get-one-row row-number rows-columns-words)) - (setq one-row (add-column-widths column-widths one-row)) - (create-a-left-aligned-line one-row) - (setq row-number (1+ row-number)) - (setq width-place (1+ width-place))))) - -(defun right-align-lines (rows-columns-words) - "Write ROWS-COLUMNS-WORDS in right-aligned columns. -ROWS-COLUMNS-WORDS is a list of lists. Each list consists of the -row number, the column number, and the word." - (let* ((row-number 1) - (column-widths (get-column-widths rows-columns-words)) - (last-row (get-last-row rows-columns-words)) - (one-row) - (width-place 0)) - (while (<= row-number last-row) - (setq one-row (get-one-row row-number rows-columns-words)) - (setq one-row (add-column-widths column-widths one-row)) - (create-a-right-aligned-line one-row) - (setq row-number (1+ row-number)) - (setq width-place (1+ width-place))))) - -(defun center-align-lines (rows-columns-words) - "Write ROWS-COLUMNS-WORDS in center-aligned columns. -ROWS-COLUMNS-WORDS is a list of lists. Each list consists of the -row number, the column number, and the word." - (let* ((row-number 1) - (column-widths (get-column-widths rows-columns-words)) - (last-row (get-last-row rows-columns-words)) - (one-row) - (width-place 0)) - (while (<= row-number last-row) - (setq one-row (get-one-row row-number rows-columns-words)) - (setq one-row (add-column-widths column-widths one-row)) - (create-a-center-aligned-line one-row) - (setq row-number (1+ row-number)) - (setq width-place (1+ width-place))))) - -(defun align-lines (alignment rows-columns-words) - "Write ROWS-COLUMNS-WIDTHS with given ALIGNMENT. -ROWS-COLUMNS-WIDTHS consists of a list of lists. Each internal list contains width of column, row number, column number, and a word." +(defun align-lines (alignment data) + "Write DATA with given ALIGNMENT. +DATA consists of a list of lists. Each internal list conists of a list +of words." (let ((align-function (pcase alignment ('left 'left-align-lines) ("left" 'left-align-lines) @@ -248,4 +131,4 @@ ROWS-COLUMNS-WIDTHS consists of a list of lists. Each internal list contains wid ("center" 'center-align-lines) ('right 'right-align-lines) ("right" 'right-align-lines)))) - (funcall align-function rows-columns-words))) + (funcall align-function data))) diff --git a/Task/Aliquot-sequence-classifications/EasyLang/aliquot-sequence-classifications.easy b/Task/Aliquot-sequence-classifications/EasyLang/aliquot-sequence-classifications.easy index e25f92c48c..40a22a8833 100644 --- a/Task/Aliquot-sequence-classifications/EasyLang/aliquot-sequence-classifications.easy +++ b/Task/Aliquot-sequence-classifications/EasyLang/aliquot-sequence-classifications.easy @@ -1,7 +1,5 @@ fastfunc sumprop num . - if num = 1 - return 0 - . + if num = 1 : return 0 sum = 1 root = sqrt num i = 2 @@ -16,60 +14,36 @@ fastfunc sumprop num . . return sum . -func$ tostr ar[] . - for v in ar[] - s$ &= " " & v - . - return s$ -. func$ class k . oldk = k newk = sumprop oldk oldk = newk seq[] &= newk - if newk = 0 - return "terminating " & tostr seq[] - . - if newk = k - return "perfect " & tostr seq[] - . + if newk = 0 : return "terminating " & seq[] + if newk = k : return "perfect " & seq[] newk = sumprop oldk oldk = newk seq[] &= newk - if newk = 0 - return "terminating " & tostr seq[] - . - if newk = k - return "amicable " & tostr seq[] - . + if newk = 0 : return "terminating " & seq[] + if newk = k : return "amicable " & seq[] for t = 4 to 16 newk = sumprop oldk seq[] &= newk - if newk = 0 - return "terminating " & tostr seq[] - . - if newk = k - return "sociable (period " & t - 1 & ") " & tostr seq[] - . - if newk = oldk - return "aspiring " & tostr seq[] - . + if newk = 0 : return "terminating " & seq[] + if newk = k : return "sociable (period " & t - 1 & ") " & seq[] + if newk = oldk : return "aspiring " & seq[] for i to len seq[] - 1 - if newk = seq[i] - return "cyclic (at " & newk & ") " & tostr seq[] - . - . - if newk > 140737488355328 - return "non-terminating (term > 140737488355328) " & tostr seq[] + if newk = seq[i] : return "cyclic (at " & newk & ") " & seq[] . + if newk > 140737488355328 : return "non-terminating (term > 140737488355328) " & seq[] oldk = newk . - return "non-terminating (after 16 terms) " & tostr seq[] + return "non-terminating (after 16 terms) " & seq[] . print "Number classification sequence" for j = 1 to 12 - print j & " " & class j + print j & ": " & class j . for j in [ 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 ] - print j & " " & class j + print j & ": " & class j . diff --git a/Task/Almkvist-Giullera-formula-for-pi/00-TASK.txt b/Task/Almkvist-Giullera-formula-for-pi/00-TASK.txt index b3424c960c..9dd91723eb 100644 --- a/Task/Almkvist-Giullera-formula-for-pi/00-TASK.txt +++ b/Task/Almkvist-Giullera-formula-for-pi/00-TASK.txt @@ -1,27 +1,27 @@ -The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau +The Almkvist-Giullera formula for calculating \frac{1}{\pi^2} is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: -::::: 1/π2 = (25/3) ∑0 ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 +:\frac{1}{\pi^{2}}=32 \sum_{n=0}^{\infty}\frac{(6n)!}{3 \cdot n!^{6}}(532n^{2}+126n+9)\frac{1}{10^{6n+3}} -This formula can be used to calculate the constant   π-2,   and thus to calculate   π. +This formula can be used to calculate the constant \frac{1}{\pi^2},   and thus to calculate \pi. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: -::::: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6)     (***) +:\frac{32(6n)!}{3 \cdot n!^{6}}(532n^{2}+126n+9) multiplied by a negative integer power of 10: -::::: 10-(6n + 3) +:10^{-(6n + 3)} ;Task: :* Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. -:* Use the complete formula to calculate and print π to 70 decimal digits of precision. +:* Use the complete formula to calculate and print \pi to 70 decimal digits of precision. ;Reference: diff --git a/Task/Almost-prime/00-TASK.txt b/Task/Almost-prime/00-TASK.txt index c607041068..adb7f91ccd 100644 --- a/Task/Almost-prime/00-TASK.txt +++ b/Task/Almost-prime/00-TASK.txt @@ -7,7 +7,7 @@ A   [[wp:Almost prime|k-Almost-prime]]   is a natural number   1 <= K <= 5. +Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for   1 \le K \le 5. ;Related tasks: diff --git a/Task/Almost-prime/Ballerina/almost-prime.ballerina b/Task/Almost-prime/Ballerina/almost-prime.ballerina new file mode 100644 index 0000000000..4591f6997f --- /dev/null +++ b/Task/Almost-prime/Ballerina/almost-prime.ballerina @@ -0,0 +1,32 @@ +import ballerina/io; + +function kPrime(int m, int k) returns boolean { + int n = m; // make mutable + int nf = 0; + foreach int i in 2...n { + while (n % i) == 0 { + if nf == k { return false; } + nf += 1; + n /= i; + } + } + return nf == k; +} + +function gen(int k, int m) returns int[] { + int[] r = []; + r.setLength(m); + int n = 2; + foreach int i in 0 ..< r.length() { + while !kPrime(n, k) { n += 1; } + r[i] = n; + n += 1; + } + return r; +} + +public function main() { + foreach int k in 1...5 { + io:println(k, " ", gen(k, 10)); + } +} diff --git a/Task/Almost-prime/Clojure/almost-prime.clj b/Task/Almost-prime/Clojure/almost-prime.clj index c35a61bd6b..3adf67d1cc 100644 --- a/Task/Almost-prime/Clojure/almost-prime.clj +++ b/Task/Almost-prime/Clojure/almost-prime.clj @@ -19,5 +19,3 @@ (println (for [k (range 1 6)] (println "k:" k (divisors-k k 10)))) - -} diff --git a/Task/Almost-prime/EasyLang/almost-prime.easy b/Task/Almost-prime/EasyLang/almost-prime.easy index 67e268e1f0..72cd4d8d65 100644 --- a/Task/Almost-prime/EasyLang/almost-prime.easy +++ b/Task/Almost-prime/EasyLang/almost-prime.easy @@ -2,27 +2,23 @@ func kprime n k . i = 2 while i <= n while n mod i = 0 - if f = k - return 0 - . + if f = k : return 0 f += 1 n /= i . i += 1 . - if f = k - return 1 - . + if f = k : return 1 return 0 . for k = 1 to 5 write "k=" & k & " : " i = 2 - c = 0 - while c < 10 + cnt = 0 + while cnt < 10 if kprime i k = 1 write i & " " - c += 1 + cnt += 1 . i += 1 . diff --git a/Task/Almost-prime/Forth/almost-prime.fth b/Task/Almost-prime/Forth/almost-prime.fth new file mode 100644 index 0000000000..77210f5046 --- /dev/null +++ b/Task/Almost-prime/Forth/almost-prime.fth @@ -0,0 +1,38 @@ +: multiplicity ( n1 n2 -- n1 n2 n3 ) + 0 >r + begin + 2dup mod 0= + while + r> 1+ >r + tuck / swap + repeat + r> ; + +: k-prime? ( n k -- ? ) + >r 0 >r 2 + begin + 2dup dup * >= if 2r@ > else false then + while + multiplicity r> + >r 1+ + repeat + drop + 1 > if 1 else 0 then r> + r> = ; + +: next-k-prime ( n k -- n ) + begin + swap 1+ swap + 2dup k-prime? + until drop ; + +: main + 6 1 do + ." k = " i 1 .r ." :" + 1 10 0 do + j next-k-prime + dup 3 .r space + loop + drop cr + loop ; + +main +bye diff --git a/Task/Almost-prime/REXX/almost-prime-1.rexx b/Task/Almost-prime/REXX/almost-prime-1.rexx deleted file mode 100644 index e5652afb7c..0000000000 --- a/Task/Almost-prime/REXX/almost-prime-1.rexx +++ /dev/null @@ -1,35 +0,0 @@ -/*REXX program computes and displays the first N K─almost primes from 1 ──► K. */ -parse arg N K . /*get optional arguments from the C.L. */ -if N=='' | N=="," then N=10 /*N not specified? Then use default.*/ -if K=='' | K=="," then K= 5 /*K " " " " " */ - /*W: is the width of K, used for output*/ - do m=1 for K; $=2**m; fir=$ /*generate & assign 1st K─almost prime.*/ - #=1; if #==N then leave /*#: K─almost primes; Enough are found?*/ - #=2; $=$ 3*(2**(m-1)) /*generate & append 2nd K─almost prime.*/ - if #==N then leave /*#: K─almost primes; Enough are found?*/ - if m==1 then _=fir + fir /* [↓] gen & append 3rd K─almost prime*/ - else do; _=9 * (2**(m-2)); #=3; $=$ _; end - do j=_ + m - 1 until #==N /*process an K─almost prime N times.*/ - if factr()\==m then iterate /*not the correct K─almost prime? */ - #=# + 1; $=$ j /*bump K─almost counter; append it to $*/ - end /*j*/ /* [↑] generate N K─almost primes.*/ - say right(m, length(K))"─almost ("N') primes:' $ - end /*m*/ /* [↑] display a line for each K─prime*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -factr: z=j; do f=0 while z// 2==0; z=z% 2; end /*divisible by 2.*/ - do f=f while z// 3==0; z=z% 3; end /*divisible " 3.*/ - do f=f while z// 5==0; z=z% 5; end /*divisible " 5.*/ - do f=f while z// 7==0; z=z% 7; end /*divisible " 7.*/ - do f=f while z//11==0; z=z%11; end /*divisible " 11.*/ - do f=f while z//13==0; z=z%13; end /*divisible " 13.*/ - do p=17 by 6 while p<=z /*insure P isn't divisible by three. */ - parse var p '' -1 _ /*obtain the right─most decimal digit. */ - /* [↓] fast check for divisible by 5. */ - if _\==5 then do; do f=f+1 while z//p==0; z=z%p; end; f=f-1; end /*÷ by P? */ - if _ ==3 then iterate /*fast check for X divisible by five.*/ - x=p+2; do f=f+1 while z//x==0; z=z%x; end; f=f-1 /*÷ by X? */ - end /*i*/ /* [↑] find all the factors in Z. */ - - if f==0 then return 1 /*if prime (f==0), then return unity.*/ - return f /*return to invoker the number of divs.*/ diff --git a/Task/Almost-prime/REXX/almost-prime-2.rexx b/Task/Almost-prime/REXX/almost-prime-2.rexx deleted file mode 100644 index d0dbbe54d6..0000000000 --- a/Task/Almost-prime/REXX/almost-prime-2.rexx +++ /dev/null @@ -1,66 +0,0 @@ -/*REXX program computes and displays the first N K─almost primes from 1 ──► K. */ -parse arg N K . /*obtain optional arguments from the CL*/ -if N=='' | N==',' then N=10 /*N not specified? Then use default.*/ -if K=='' | K==',' then K= 5 /*K " " " " " */ -nn=N; N=abs(N); w=length(K) /*N positive? Then show K─almost primes*/ -limit= (2**K) * N / 2 /*this is the limit for most K-primes. */ -if N==1 then limit=limit * 2 /* " " " " " a N of 1.*/ -if K==1 then limit=limit * 4 /* " " " " " a K─prime " 2.*/ -if K==2 then limit=limit * 2 /* " " " " " " " " 4.*/ -if K==3 then limit=limit * 3 % 2 /* " " " " " " " " 8.*/ -call genPrimes limit + 1 /*generate primes up to the LIMIT + 1.*/ -say 'The highest prime computed: ' @.# " (under the limit of " limit').' -say /* [↓] define where 1st K─prime is odd*/ -d.=0; d.2= 2; d.3 = 4; d.4 = 7; d.5 = 13; d.6 = 22; d.7 = 38; d.8=63 - d.9=102; d.10=168; d.11=268; d.12=426; d.13=673; d.14=1064 -d!=0 - do m=1 for K; d!=max(d!,d.m) /*generate & assign 1st K─almost prime.*/ - mr=right(m,w); mm=m-1 - - $=; do #=1 to min(N, d!) /*assign some doubled K─almost primes. */ - $=$ d.mm.# * 2 - end /*#*/ - #=#-1 - if m==1 then from=2 - else from=1 + word($, words($) ) - - do j=from until #==N /*process an K─almost prime N times.*/ - if factr()\==m then iterate /*not the correct K─almost prime? */ - #=#+1; $=$ j /*bump K─almost counter; append it to $*/ - end /*j*/ /* [↑] generate N K─almost primes.*/ - - if nn>0 then say mr"─almost ("N') primes:' $ - else say ' the last' mr "K─almost prime: " word($, words($)) - /* [↓] assign K─almost primes.*/ - do q=1 for #; d.m.q=word($,q) ; end /*q*/ - do q=1 for #; if d.m.q\==d.mm.q*2 then leave; end /*q*/ - /* [↑] count doubly-duplicates*/ -/*──── say copies('─',40) 'for ' m", " q-1 'numbers were doubly─duplicated.' ────*/ -/*──── say ────*/ - end /*m*/ /* [↑] display a line for each K─prime*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -factr: if #.j\==. then return #.j - z=j; do f=0 while z// 2==0; z=z% 2; end /*÷ by 2*/ - do f=f while z// 3==0; z=z% 3; end /*÷ " 3*/ - do f=f while z// 5==0; z=z% 5; end /*÷ " 5*/ - do f=f while z// 7==0; z=z% 7; end /*÷ " 7*/ - do f=f while z//11==0; z=z%11; end /*÷ " 11*/ - do f=f while z//13==0; z=z%13; end /*÷ " 13*/ - do f=f while z//17==0; z=z%17; end /*÷ " 17*/ - do f=f while z//19==0; z=z%19; end /*÷ " 19*/ - - do i=9 while @.i<=z; d=@.i /*divide by some higher primes. */ - do f=f while z//d==0; z=z%d; end /*is Z divisible by the prime D ? */ - end /*i*/ /* [↑] find all factors in Z. */ - - if f==0 then f=1; #.j=f; return f /*Is prime (f≡0)? Then return unity. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genPrimes: arg x; @.=; @.1=2; @.2=3; #.=.; #=2; s.#=@.#**2 - do j=@.# +2 by 2 to x /*only find odd primes from here on. */ - do p=2 while s.p<=j /*divide by some known low odd primes. */ - if j//@.p==0 then iterate j /*Is J divisible by X? Then ¬ prime.*/ - end /*p*/ /* [↓] a prime (J) has been found. */ - #=#+1; @.#=j; #.j=1; s.#=j*j /*bump prime count, and also assign ···*/ - end /*j*/ /* ··· the # of factors, prime, prime².*/ - return /* [↑] not an optimal prime generator.*/ diff --git a/Task/Almost-prime/REXX/almost-prime-3.rexx b/Task/Almost-prime/REXX/almost-prime.rexx similarity index 92% rename from Task/Almost-prime/REXX/almost-prime-3.rexx rename to Task/Almost-prime/REXX/almost-prime.rexx index 2c8d9e5b73..69046a42f9 100644 --- a/Task/Almost-prime/REXX/almost-prime-3.rexx +++ b/Task/Almost-prime/REXX/almost-prime.rexx @@ -1,6 +1,8 @@ include Settings -say version; say 'k-Almost primes'; say +say 'ALMOST PRIME - 3 Mar 2025' +say version +say arg n k m say 'Direct approach using Factors' numeric digits 16 diff --git a/Task/Amb/Ballerina/amb.ballerina b/Task/Amb/Ballerina/amb.ballerina new file mode 100644 index 0000000000..3f0fdce8b4 --- /dev/null +++ b/Task/Amb/Ballerina/amb.ballerina @@ -0,0 +1,35 @@ +import ballerina/io; + +string[] finalRes = []; + +function amb(string[][] wordsets, string[] res) returns boolean { + if wordsets.length() == 0 { + finalRes.push(...res); + return true; + } + string s = ""; + int l = res.length(); + if l > 0 { s = res[l - 1]; } + res.push(""); + foreach string word in wordsets[0] { + res[l] = word; + if l > 0 && s[s.length() - 1] != res[l][0] { continue; } + if amb(wordsets.slice(1), [...res]) { return true; } + } + return false; +} + +public function main() { + var wordsets = [ + [ "the", "that", "a" ], + [ "frog", "elephant", "thing" ], + [ "walked", "treaded", "grows" ], + [ "slowly", "quickly" ] + ]; + + if amb(wordsets, []) { + io:println(string:'join(" ", ...finalRes)); + } else { + io:println("No amb found"); + } +} diff --git a/Task/Amb/EasyLang/amb.easy b/Task/Amb/EasyLang/amb.easy new file mode 100644 index 0000000000..4c3e80dd21 --- /dev/null +++ b/Task/Amb/EasyLang/amb.easy @@ -0,0 +1,31 @@ +func ambtest a$ b$ . + if substr a$ len a$ 1 = substr b$ 1 1 : return 1 + return 0 +. +proc amb &opts$[][] pos prev$ &res$[] &found . + if pos = 0 + found = 1 + res$[] = [ ] + return + . + for curr$ in opts$[pos][] + if prev$ = "" or ambtest curr$ prev$ = 1 + amb opts$[][] (pos - 1) curr$ res$[] found + if found = 1 + res$[] &= curr$ + return + . + . + . + found = 0 + return +. +proc main . + sets$[][] = [ [ "the" "that" "a" ] [ "frog" "elephant" "thing" ] [ "walked" "treaded" "grows" ] [ "slowly" "quickly" ] ] + h = len sets$[][] + amb sets$[][] h "" res$[] found + if found = 1 + print res$[] + . +. +main diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena index 158379a738..2627185b46 100644 --- a/Task/Amb/Elena/amb.elena +++ b/Task/Amb/Elena/amb.elena @@ -82,12 +82,12 @@ public program() new object[]{"walked", "treaded", "grows"}, new object[]{"slowly", "quickly"}) .seek::(a,b,c,d => joinable(a,b) && joinable(b,c) && joinable(c,d) ) - .do::(a,b,c,d) { console.printLine(a," ",b," ",c," ",d) } + .do::(a,b,c,d) { Console.printLine(a," ",b," ",c," ",d) } } catch(Exception e) { - console.printLine("AMB is angry") + Console.printLine("AMB is angry") }; - console.readChar() + Console.readChar() } diff --git a/Task/Amb/Langur/amb.langur b/Task/Amb/Langur/amb.langur index 7f047193bb..a2a6dca16f 100644 --- a/Task/Amb/Langur/amb.langur +++ b/Task/Amb/Langur/amb.langur @@ -6,7 +6,7 @@ val wordsets = [ ] val alljoin = fn words: for[=true] i of len(words)-1 { - if words[i][-1] != words[i+1][1]: break = false + if words[i][-1] != words[i+1][1]: break val=false } # amb expects 2 or more arguments diff --git a/Task/Amicable-pairs/EasyLang/amicable-pairs.easy b/Task/Amicable-pairs/EasyLang/amicable-pairs.easy index 648a0ba8ce..dc3d7e0186 100644 --- a/Task/Amicable-pairs/EasyLang/amicable-pairs.easy +++ b/Task/Amicable-pairs/EasyLang/amicable-pairs.easy @@ -1,17 +1,13 @@ func sumdivs n . sum = 1 for d = 2 to sqrt n - if n mod d = 0 - sum += d + n div d - . + if n mod d = 0 : sum += d + n div d . return sum . for n = 1 to 20000 m = sumdivs n - if m > n - if sumdivs m = n - print n & " " & m - . + if m > n and sumdivs m = n + print n & " " & m . . diff --git a/Task/Amicable-pairs/Elena/amicable-pairs-1.elena b/Task/Amicable-pairs/Elena/amicable-pairs-1.elena index 62814d6243..06a9bfd320 100644 --- a/Task/Amicable-pairs/Elena/amicable-pairs-1.elena +++ b/Task/Amicable-pairs/Elena/amicable-pairs-1.elena @@ -31,6 +31,6 @@ public program() { N.AmicablePairs.forEach::(pair) { - console.printLine(pair.Item1, " ", pair.Item2) + Console.printLine(pair.Item1, " ", pair.Item2) } } diff --git a/Task/Amicable-pairs/Elena/amicable-pairs-2.elena b/Task/Amicable-pairs/Elena/amicable-pairs-2.elena index 8ac6072f0d..a7d4a255ca 100644 --- a/Task/Amicable-pairs/Elena/amicable-pairs-2.elena +++ b/Task/Amicable-pairs/Elena/amicable-pairs-2.elena @@ -27,7 +27,7 @@ extension op : IntNumber public program() { - N.AmicablePairs.forEach::(var Tuple pair) + (N.AmicablePairs)::forEach>::(pair) { console.printLine(pair.Item1, " ", pair.Item2) } diff --git a/Task/Amicable-pairs/Elena/amicable-pairs-3.elena b/Task/Amicable-pairs/Elena/amicable-pairs-3.elena index ede0ca6ccd..90b88b9964 100644 --- a/Task/Amicable-pairs/Elena/amicable-pairs-3.elena +++ b/Task/Amicable-pairs/Elena/amicable-pairs-3.elena @@ -19,7 +19,7 @@ public sealed AmicablePairs this max := max } - yieldable Tuple next() + yield Enumerator> enumerator() { List divsums := Range.new(0, max + 1).selectBy::(int i => ProperDivisors(i).summarize(0)); @@ -27,19 +27,17 @@ public sealed AmicablePairs { int sum := divsums[i]; if(i < sum && sum <= divsums.Length && divsums[sum] == i) { - $yield new Tuple(i, sum); + :yield new Tuple(i, sum); } }; - - ^ nil } } public program() { - auto e := new AmicablePairs(Limit); - for(auto pair := e.next(); pair != nil) - { - console.printLine(pair.Item1, " ", pair.Item2) + auto e := new AmicablePairs(Limit).enumerator(); + while (e.next()) { + auto pair := *e; + console.printLine(pair.Item1, " ", pair.Item2) } } diff --git a/Task/Amicable-pairs/PascalABC.NET/amicable-pairs.pas b/Task/Amicable-pairs/PascalABC.NET/amicable-pairs.pas new file mode 100644 index 0000000000..e6b4e2cd91 --- /dev/null +++ b/Task/Amicable-pairs/PascalABC.NET/amicable-pairs.pas @@ -0,0 +1,9 @@ +function k(n : Integer) := 1.to(n div 2).where(d->n mod d=0).sum; +begin +1.to(20000).Where(n->n=k(k(n))) +.Select(n-> + begin var m:=k(n); +Result:=(min(n,m),max(n,m)); + end).where(v->v[0]$'{v[0]}-{v[1]}').Printlines; +end. diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx index 6c7c579692..0df72c5809 100644 --- a/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx +++ b/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx @@ -1,28 +1,26 @@ -/*REXX program calculates and displays all amicable pairs up to a given number. */ -parse arg H .; if H=='' | H=="," then H= 20000 /*get optional arguments (high limit).*/ -w= length(H) ; low= 220 /*W: used for columnar output alignment*/ -@.=. /* [↑] LOW is lowest amicable number. */ - do k=low for H-low; _= sigma(k) /*generate sigma sums for a range of #s*/ - if _>=low then @.k= _ /*only keep the pertinent sigma sums. */ - end /*k*/ /* [↑] process a range of integers. */ -#= 0 /*number of amicable pairs found so far*/ - do m=low to H; n= @.m /*start the search at the lowest number*/ - if m==@.n then do /*If equal, might be an amicable number*/ - if m==n then iterate /*Is this a perfect number? Then skip.*/ - #= # + 1 /*bump the amicable pair counter. */ - say right(m,w) ' and ' right(n,w) " are an amicable pair." - m= n /*start M (DO index) from N. */ - end - end /*m*/ +-- 8 May 2025 +include Settings + +say 'AMICABLE PAIRS' +say version say -say # ' amicable pairs found up to ' H /*display count of the amicable pairs. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure; parse arg x; od= x // 2 /*use either EVEN or ODD integers. */ - s= 1 /*set initial sigma sum to unity. ___*/ - do j=2+od by 1+od while j*j 0); n = Abs(n) +a = Amicables(n) +say time('e') a 'amicable pairs collected' +if show then do + do i = 1 to a + say time('e') amic.1.i 'and' amic.2.i 'are an amicable pair' + end +end +say time('e') 'seconds' +exit + +include Sequences +include Numbers +include Functions +include Special +include Abend diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-3.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-3.rexx deleted file mode 100644 index 5ceabf3e71..0000000000 --- a/Task/Amicable-pairs/REXX/amicable-pairs-3.rexx +++ /dev/null @@ -1,30 +0,0 @@ -/*REXX program calculates and displays all amicable pairs up to a given number. */ -parse arg H .; if H=='' | H=="," then H=20000 /*get optional arguments (high limit).*/ -w=length(H) ; low=220 /*W: used for columnar output alignment*/ -x= 220 34765731 6232 87633 284 12285 10856 36939357 6368 5684679 /*S minimums.*/ - do i=0 for 10; $.i= word(x, i + 1); end /*minimum amicable #s for last dec dig.*/ -@.= /* [↑] LOW is lowest amicable number. */ -#= 0 /*number of amicable pairs found so far*/ - do k=low for H-low /*generate sigma sums for a range of #s*/ - parse var k '' -1 D /*obtain last decimal digit of K. */ - if k<$.D then iterate /*if no need to compute, then skip it. */ - _= sigma(k) /*generate sigma sum for the number K.*/ - @.k= _ /*only keep the pertinent sigma sums. */ - if k==@._ then do /*is it a possible amicable number ? */ - if _==k then iterate /*Is it a perfect number? Then skip it*/ - #= # + 1 /*bump the amicable pair counter. */ - say right(_, w) ' and ' right(k, w) " are an amicable pair." - end - end /*k*/ /* [↑] process a range of integers. */ -say -say # 'amicable pairs found up to' H /*display the count of amicable pairs. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure; parse arg x; od= x // 2 /*use either EVEN or ODD integers. */ - s= 1 /*set initial sigma sum to unity. ___*/ - do j=2+od by 1+od while j*j1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end - return r -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure; parse arg x; od= x // 2 /*use either EVEN or ODD integers. */ - s= 1 /*set initial sigma sum to unity. ___*/ - do j=2+od by 1+od to iSqrt(x) /*divide by all integers up to the √ x */ - if x//j==0 then s= s + j + x%j /*add the two divisors to the sum. */ - end /*j*/ /* [↑] % is the REXX integer division.*/ - /* ___ */ - if j*j==x then return s + j /*Was X a square? If so, add √ X */ - return s /*return (sigma) sum of the divisors. */ diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-5.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-5.rexx deleted file mode 100644 index 5ee02d6498..0000000000 --- a/Task/Amicable-pairs/REXX/amicable-pairs-5.rexx +++ /dev/null @@ -1,34 +0,0 @@ -/*REXX program calculates and displays all amicable pairs up to a given number. */ -parse arg H .; if H=='' | H=="," then H=20000 /*get optional arguments (high limit).*/ -w= length(H) ; low= 220 /*W: used for columnar output alignment*/ -x= 220 34765731 6232 87633 284 12285 10856 36939357 6368 5684679 /*S minimums.*/ - do i=0 for 10; $.i= word(x, i + 1); end /*minimum amicable #s for last dec dig.*/ -@.= /* [↑] LOW is lowest amicable number. */ -#= 0 /*number of amicable pairs found so far*/ - do k=low for H-low /*generate sigma sums for a range of #s*/ - parse var k '' -1 D /*obtain last decimal digit of K. */ - if k<$.D then iterate /*if no need to compute, then skip it. */ - _= sigma(k) /*generate sigma sum for the number K.*/ - @.k= _ /*only keep the pertinent sigma sums. */ - if k==@._ then do /*is it a possible amicable number ? */ - if _==k then iterate /*Is it a perfect number? Then skip it*/ - #= # + 1 /*bump the amicable pair counter. */ - say right(_, w) ' and ' right(k, w) " are an amicable pair." - end - end /*k*/ /* [↑] process a range of integers. */ -say -say # 'amicable pairs found up to' H /*display the count of amicable pairs. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -iSqrt: procedure; parse arg x; r= 0; q= 1; do while q<=x; q= q * 4; end - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end - return r -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure; parse arg x; od= x // 2 /*use either EVEN or ODD integers. */ - s= 1 /*set initial sigma sum to unity. ___*/ - do j=2+od by 1+od to iSqrt(x) /*divide by all integers up to the √ x */ - if x//j==0 then s= s + j + x%j /*add the two divisors to the sum. */ - end /*j*/ /* [↑] % is the REXX integer division.*/ - /* ___ */ - if j*j==x then return s + j /*Was X a square? If so, add √ X */ - return s /*return (sigma) sum of the divisors. */ diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-6.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-6.rexx deleted file mode 100644 index cec5b774eb..0000000000 --- a/Task/Amicable-pairs/REXX/amicable-pairs-6.rexx +++ /dev/null @@ -1,43 +0,0 @@ -include Settings - -say version; say 'Amicable pairs'; say -arg n -numeric digits 16 -if n = '' then - n = 20000 -show = (n > 0); n = Abs(n) -/* Get amicable pairs */ -a = Amicables(n) -say time('e') a 'amicable pairs collected' -/* Show amical pairs */ -if show then do - do i = 1 to a - say time('e') amic.amicable.1.i 'and' amic.amicable.2.i 'are an amicable pair' - end -end -say time('e') 'seconds' -exit - -Amicables: -/* Amicable number pairs */ -procedure expose glob. amic. -arg x -/* Init */ -amic. = 0 -/* Scan for amicable pairs */ -n = 0 -do i = 1 to x - s = Sigma(i)-i; glob.sigma.i = s - if i = glob.sigma.s then do - if s = i then - iterate - n = n+1 - amic.amicable.1.n = s; amic.amicable.2.n = i - end -end -amic.0 = n -return n - -include Numbers -include Functions -include Abend diff --git a/Task/Anagrams-Deranged-anagrams/Crystal/anagrams-deranged-anagrams.cr b/Task/Anagrams-Deranged-anagrams/Crystal/anagrams-deranged-anagrams.cr new file mode 100644 index 0000000000..0e8a15fdbb --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Crystal/anagrams-deranged-anagrams.cr @@ -0,0 +1,19 @@ +def deranged? (a, b) + a.chars.zip(b.chars).all? {|char_a, char_b| char_a != char_b} +end + +def find_derangements (list) + list.each_combination(2) {|(a, b)| return a, b if deranged?(a, b)} + nil +end + +anagram = File.read_lines("unixdict.txt").group_by {|s| s.chars.sort} + +anagram = anagram.select {|k,list| list.size>1}.to_a.sort_by! {|k, list| -k.size} + +anagram.each do |k, list| + if derangements = find_derangements(list) + puts "Longest derangement anagram: #{derangements}" + break + end +end diff --git a/Task/Anagrams-Deranged-anagrams/EasyLang/anagrams-deranged-anagrams.easy b/Task/Anagrams-Deranged-anagrams/EasyLang/anagrams-deranged-anagrams.easy new file mode 100644 index 0000000000..f9b6445b1f --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/EasyLang/anagrams-deranged-anagrams.easy @@ -0,0 +1,74 @@ +proc norm s$ &name$[] &cnt[] &id . + d$[] = strchars s$ + for i = 1 to len d$[] - 1 + for j = i + 1 to len d$[] + if strcode d$[j] < strcode d$[i] : swap d$[j] d$[i] + . + . + n$ = strjoin d$[] "" + for id to len name$[] : if name$[id] = n$ : break 1 + if id > len name$[] + name$[] &= n$ + cnt[] &= 0 + . + cnt[id] += 1 +. +func deranged a$ b$ . + for i to len a$ + if substr a$ i 1 = substr b$ i 1 : return 0 + . + return 1 +. +global maxlng w$[] . +proc read . + repeat + s$ = input + until s$ = "" + w$[] &= s$ + maxlng = higher maxlng len s$ + . +. +read +# +len wid[] len w$[] +done = 0 +proc search a b . + for i = a to b + norm w$[i] name$[] cnt[] id + wid[i] = id + . + for id to len name$[] : if cnt[id] > 1 + h[] = [ ] + for i = a to b : if wid[i] = id : h[] &= i + for i to len h[] - 1 : for j = i + 1 to len h[] + if deranged w$[h[i]] w$[h[j]] = 1 + print w$[h[i]] & " " & w$[h[j]] + done = 1 + . + . + . +. +b = len w$[] +while done = 0 and maxlng >= 2 + a = b + for i = b downto 1 : if len w$[i] = maxlng + swap w$[i] w$[a] + a -= 1 + . + search a + 1 b + maxlng -= 1 +. +# +# a few lines of unixdict.txt, also works with all +input_data +ancestor +ancestral +ancestry +anchor +lana +lancashire +lancaster +lance +zucchini +zurich +zygote diff --git a/Task/Anagrams/EasyLang/anagrams.easy b/Task/Anagrams/EasyLang/anagrams.easy new file mode 100644 index 0000000000..2e5fcff599 --- /dev/null +++ b/Task/Anagrams/EasyLang/anagrams.easy @@ -0,0 +1,46 @@ +global name$[] cnt[] . +func n2id n$ . + for id to len name$[] : if name$[id] = n$ : return id + name$[] &= n$ + cnt[] &= 0 + return id +. +func norm s$ . + d$[] = strchars s$ + for i = 1 to len d$[] - 1 + for j = i + 1 to len d$[] + if strcode d$[j] < strcode d$[i] : swap d$[j] d$[i] + . + . + n$ = strjoin d$[] "" + return n2id n$ +. +repeat + s$ = input + until s$ = "" + id = norm s$ + cnt[id] += 1 + max = higher max cnt[id] + w$[] &= s$ + wid[] &= id +. +for id to len name$[] + if cnt[id] = max + for i to len w$[] + if wid[i] = id : write w$[i] & " " + . + print "" + . +. +# +# a few lines of unixdict.txt, also works with all +input_data +abe +abed +abel +ablaze +able +ablution +angel +angle +angles diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 65bb59e28f..a98ee663ba 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -15,7 +15,7 @@ extension op public program() { - var start := now; + var start := Now; auto dictionary := new Map(); @@ -35,13 +35,13 @@ public program() dictionary.Values .quickSort::(former,later => former.Item2.Length > later.Item2.Length ) .top(20) - .forEach::(pair){ console.printLine(pair.Item2) }; + .forEach::(pair){ Console.printLine(pair.Item2) }; - var end := now; + var end := Now; var diff := end - start; - console.printLine("Time elapsed in msec:",diff.Milliseconds); + Console.printLine("Time elapsed in msec:",diff.Milliseconds); - console.readChar() + Console.readChar() } diff --git a/Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina b/Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina new file mode 100644 index 0000000000..213bb46d14 --- /dev/null +++ b/Task/Angle-difference-between-two-bearings/Ballerina/angle-difference-between-two-bearings.ballerina @@ -0,0 +1,34 @@ +import ballerina/io; + +function subtract(float b1, float b2) returns float { + float d = (b2 - b1) % 360.0; + if d < -180.0 { d += 360.0; } + if d >= 180.0 { d -= 360.0; } + return d.round(4); +} + +public function main() { + float[][] pairs = [ + [ 20, 45], + [-45, 45], + [-85, 90], + [-95, 90], + [-45, 125], + [-45, 145], + [ 29.4803, -88.6381], + [-78.3251, -159.036], + [-70099.74233810938, 29840.67437876723], + [-165313.6666297357, 33693.9894517456], + [1174.8380510598456, -154146.66490124757], + [60175.77306795546, 42213.07192354373] + ]; + + io:println("Differences (to 4dp) between these bearings:"); + foreach var pair in pairs { + float p0 = pair[0]; + float p1 = pair[1]; + float diff = subtract(p0, p1); + string offset = p0 < 0.0 ? " " : " "; + io:println(`${offset}${p0} and ${p1} -> ${diff}`); + } +} diff --git a/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy b/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy index fbe96a9106..052ea0af48 100644 --- a/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy +++ b/Task/Angle-difference-between-two-bearings/EasyLang/angle-difference-between-two-bearings.easy @@ -7,7 +7,7 @@ func angdiff a b . . return r . -proc pd a b . . +proc pd a b . print b & " " & a & " -> " & angdiff a b . pd 20 45 diff --git a/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy b/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy index 546d276c89..2a63ef3ad8 100644 --- a/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy +++ b/Task/Angles-geometric-normalization-and-conversion/EasyLang/angles-geometric-normalization-and-conversion.easy @@ -27,7 +27,7 @@ func$ fmt s$ . # scales$[] = [ "degree" "gradian" "mil" "radian" ] values[] = [ -2 -1 0 1 2 6.2831853 16 57.2957795 359 399 6399 1000000 ] -numfmt 3 10 +numfmt 10 3 for f$ in scales$[] write fmt f$ for t$ in scales$[] diff --git a/Task/Animate-a-pendulum/EasyLang/animate-a-pendulum.easy b/Task/Animate-a-pendulum/EasyLang/animate-a-pendulum.easy index f295faf12e..1f2b4d30c3 100644 --- a/Task/Animate-a-pendulum/EasyLang/animate-a-pendulum.easy +++ b/Task/Animate-a-pendulum/EasyLang/animate-a-pendulum.easy @@ -1,12 +1,11 @@ ang = 45 on animate - clear - move 50 50 - circle 1 - x = 50 + 40 * sin ang - y = 50 + 40 * cos ang - line x y - circle 6 - vel += sin ang / 5 - ang += vel + gclear + gcircle 50 50 1 + x = 50 + 40 * sin ang + y = 50 + 40 * cos ang + gline 50 50 x y + gcircle x y 6 + vel += sin ang / 5 + ang += vel . diff --git a/Task/Animation/EasyLang/animation.easy b/Task/Animation/EasyLang/animation.easy index 82c5470808..575b1619dc 100644 --- a/Task/Animation/EasyLang/animation.easy +++ b/Task/Animation/EasyLang/animation.easy @@ -1,13 +1,11 @@ s$ = "Hello world! " -textsize 14 +gtextsize 14 lg = len s$ on timer - color 333 - move 10 20 - rect 80 20 - color 999 - move 12 24 - text substr s$ 1 9 + gcolor 333 + grect 10 20 80 20 + gcolor 999 + gtext 12 24 substr s$ 1 9 if forw = 1 s$ = substr s$ lg 1 & substr s$ 1 (lg - 1) else diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index f8f6bcd578..2845fb591f 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -21,16 +21,16 @@ public program() { for (int i := -1; i <= 10; i += 1) { - console.print("fib(",i,")="); + Console.print("fib(",i,")="); try { - console.printLine(fib(i)) + Console.printLine(fib(i)) } catch(Exception e) { - console.printLine("invalid") + Console.printLine("invalid") } }; - console.readChar() + Console.readChar() } diff --git a/Task/Anti-primes/Ballerina/anti-primes.ballerina b/Task/Anti-primes/Ballerina/anti-primes.ballerina new file mode 100644 index 0000000000..c8e5cf3088 --- /dev/null +++ b/Task/Anti-primes/Ballerina/anti-primes.ballerina @@ -0,0 +1,42 @@ +import ballerina/io; + +function divisorCount(int x) returns int { + int n = x; + if n < 1 { return 0; } + int count = 0; + int prod = 1; + while n % 2 == 0 { + count += 1; + n /= 2; + } + prod *= 1 + count; + int i = 3; + while i * i <= n { + count = 0; + while n % i == 0 { + count += 1; + n /= i; + } + prod *= 1 + count; + i += 2; + } + if n > 2 { prod *= 2; } + return prod; +} + +public function main() { + io:println("The first 20 anti-primes are:"); + int maxDiv = 0; + int count = 0; + int n = 1; + while count < 20 { + int d = divisorCount(n); + if d > maxDiv { + io:print(n, " "); + maxDiv = d; + count += 1; + } + n += 1; + } + io:println(); +} diff --git a/Task/Anti-primes/EasyLang/anti-primes.easy b/Task/Anti-primes/EasyLang/anti-primes.easy index d5099ac863..fba9fdd79b 100644 --- a/Task/Anti-primes/EasyLang/anti-primes.easy +++ b/Task/Anti-primes/EasyLang/anti-primes.easy @@ -11,16 +11,14 @@ func divcnt v . p += 1 tot *= cnt . - if n > 1 - tot *= 2 - . + if n > 1 : tot *= 2 return tot . while count < 20 n += 1 divs = divcnt n if divs > max - print n + write n & " " max = divs count += 1 . diff --git a/Task/Anti-primes/OCaml/anti-primes.ml b/Task/Anti-primes/OCaml/anti-primes.ml new file mode 100644 index 0000000000..aeb3bab8ae --- /dev/null +++ b/Task/Anti-primes/OCaml/anti-primes.ml @@ -0,0 +1,18 @@ +let num_divisors (n : int) : int = + if n = 0 || n = 1 then 1 else if n = 2 then 2 else + List.init (n / 2) ((+) 1) (* O(n) *) + |> List.filter (fun i -> n mod i = 0) + |> List.length + +let first_n_antiprimes (n : int) : int list = + let rec loop = function + | i, record, antis when List.length antis = n -> antis + | i, record, antis -> let nd = num_divisors i in + if nd > record then loop (i + 1, nd, i :: antis) else + loop (i + 1, record, antis) + in loop (2, 1, [1]) |> List.rev + +let () = first_n_antiprimes 19 + |> List.map string_of_int + |> String.concat ", " + |> Printf.printf "[%s]\n" diff --git a/Task/Anti-primes/REXX/anti-primes-1.rexx b/Task/Anti-primes/REXX/anti-primes-1.rexx index 1e20a7931e..814dcd4d22 100644 --- a/Task/Anti-primes/REXX/anti-primes-1.rexx +++ b/Task/Anti-primes/REXX/anti-primes-1.rexx @@ -1,40 +1,32 @@ -/*REXX program finds and displays N number of anti-primes (highly-composite) numbers.*/ -Parse Arg N . /* obtain optional argument from the CL. */ -If N=='' | N=="," Then N=20 /* Not specified? Then use the default. */ -maxD=0 /* the maximum number of divisors so far */ -Say '-index- --anti-prime--' /* display a title For the numbers shown */ -nn=0 /* the count of anti-primes found " " */ -Do i=1 For 59 While nnmaxD Then Do /* found an anti-prime nn set new maxD */ - maxD=d - nn=nn+1 - Say center(nn,7) right(i,10) /* display the index and the anti-prime. */ - End - End /*i*/ +-- 8 May 2025 +include Settings +arg xx +if xx = '' then + xx = 1500000 -Do i=60 by 20 While nnmaxD Then Do /* found an anti-prime nn set new maxD */ - maxD=d - nn=nn+1 - Say center(nn,7) right(i,10) /* display the index and the anti-prime. */ - End - End /*i*/ -Exit /* stick a fork in it, we're all done. */ -/*-----------------------------------------------------------------------------------*/ -nndivs: Procedure /* compute the number of proper divisors */ - Parse Arg x - If x<2 Then - Return 1 - odd=x//2 - n=1 /* 1 is a proper divisor */ - Do j=2+odd by 1+odd While j*j h then do + n = n+1 + call Charout ,Left(i' ['c'] ',16) + if n//5 = 0 then + say + h = c + end +end +say n 'found' +say +call Timer +exit + +include Numbers +include Functions +include Special +include Helper +include Abend diff --git a/Task/Anti-primes/REXX/anti-primes-2.rexx b/Task/Anti-primes/REXX/anti-primes-2.rexx index 25e3818e7a..33c855c408 100644 --- a/Task/Anti-primes/REXX/anti-primes-2.rexx +++ b/Task/Anti-primes/REXX/anti-primes-2.rexx @@ -1,38 +1,33 @@ -/*REXX program finds and displays N number of anti─primes or highly─composite numbers.*/ -parse arg N . /*obtain optional argument from the CL.*/ -if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/ - @.= .; @.1= 1; @.2= 2; @.4= 3; @.5= 2; @.6= 4 -say '─index─ ──anti─prime──' /*display a title for the numbers shown*/ -#= 1 /*the count of anti─primes found " " */ -maxD= 1 /*the maximum number of divisors so far*/ -say center(#, 7) right(1, 10) /*display the index and the anti─prime.*/ - do once=1 for 1 - do i=2 by 2 to 59 /*step through possible numbers by twos*/ - d= #divs(i); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/ - #= # + 1; maxD= d /*found an anti─prime #; set new minD.*/ - say center(#, 7) right(i, 10) /*display the index and the anti─prime.*/ - if #>=N then leave once /*if we have enough anti─primes, done. */ - end /*i*/ +-- 8 May 2025 +include Settings +arg xx +if xx = '' then + xx = 1500000 - do j=60 by 20 /*step through possible numbers by 20. */ - d= #divs(j); if d<=maxD then iterate /*get # divisors; Is too small? Skip.*/ - #= # + 1; maxD= d /*found an anti─prime #; set new minD.*/ - say center(#, 7) right(j, 10) /*display the index and the anti─prime.*/ - if #>=N then leave once /*if we have enough anti─primes, done. */ - L= length(j) /*obtain the length of the index (J). */ - if L>3 then j= j + left(4, L-2, 0) - 20 /*Length>3? Then calculate a long jump*/ - end /*j*/ - end /*once*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -#divs: parse arg x; if @.x\==. then return @.x /*if pre─computed, then return shortcut*/ - $= 3; y= x % 2 - /* [↑] start with known num of Pdivs.*/ - do k=3 for x%2-3 while k=y then do; $= $ - 1; leave; end /*limit?*/ - end /* ___ */ - else if k*k>x then leave /*only divide up to √ x */ - end /*k*/ /* [↑] this form of DO loop is faster.*/ - return $+1 /*bump "proper divisors" to "divisors".*/ +say 'ANTI-PRIMES' +say version +say 'Cheating' +say +say 'Anti-primes below' xx'...' +numeric digits 16 +s = (xx > 0); xx = Abs(xx) +h = Highcomposites(xx) +if s then do + do i = 1 to high.0 + c = Divisor(high.i) + call Charout ,Left(high.i' ['c'] ',20) + if i//5 = 0 then + say + end +end +say h 'found' +say +call Timer +exit + +include Numbers +include Functions +include Special +include Sequences +include Helper +include Abend diff --git a/Task/Anti-primes/REXX/anti-primes-3.rexx b/Task/Anti-primes/REXX/anti-primes-3.rexx deleted file mode 100644 index 1fd8eab5dc..0000000000 --- a/Task/Anti-primes/REXX/anti-primes-3.rexx +++ /dev/null @@ -1,44 +0,0 @@ -include Settings - -say version; say 'Anti-prims'; say -arg n -numeric digits 16 -if n = '' then - n = 10000 -show = (n > 0); n = Abs(n) -h = Highcomposites(n) -say h 'anti-primes found below' n -if show then do - do i = 1 to high.0 - say i high.highcomposite.i - end -end -say time('e') 'seconds' -exit - -Highcomposites: -/* Highly composite sequence */ -procedure expose high. -arg x -/* Thresholds and increments */ -a = '1 2 6 60 840 55440 720720 61261200 2327925600 321253732800 9999999999999' -b = '1 2 6 60 420 27720 360360 12252240 232792560 80313433200 9999999999999' -c = Words(a)-1; m = 0; n = 0 -/* Colllect cf definition */ -do i = 1 to c - do j = Word(a,i) by Word(b,i) to Min(x,Word(a,i+1)-1) - d = Divisors(j) - if d > m then do - n = n+1; high.highcomposite.n = j - m = d - end - end -end -high.0 = n -/* Return count */ -return n - -include Numbers -include Functions -include Sequences -include Abend diff --git a/Task/Anti-primes/Zig/anti-primes.zig b/Task/Anti-primes/Zig/anti-primes.zig new file mode 100644 index 0000000000..055b8a243e --- /dev/null +++ b/Task/Anti-primes/Zig/anti-primes.zig @@ -0,0 +1,160 @@ +const std = @import("std"); + +fn sieve(allocator: std.mem.Allocator, n: usize) ![]i32 { + var is_prime = try allocator.alloc(i32, n); + var primes = std.ArrayList(i32).init(allocator); + defer allocator.free(is_prime); + for (is_prime) |*p| { + p.* = 1; + } + is_prime[0] = 0; + is_prime[1] = 0; + for (2..n) |i| { + if (is_prime[i] == 1) { + var j = i * i; + while (j < n) : (j += i) { + is_prime[j] = 0; + } + } + } + for (2..n) |i| { + if (is_prime[i] == 1) { + try primes.append(@intCast(i)); + } + } + return primes.toOwnedSlice(); +} + +const AntiPrime = struct { + value: i32, + divisors_count: i32, + factorization: std.ArrayList(i32), + + pub fn init(allocator: std.mem.Allocator, value: i32, divisors_count: i32, factors: []i32) !AntiPrime { + var factorization = try std.ArrayList(i32).initCapacity(allocator, factors.len); + errdefer factorization.deinit(); + try factorization.appendSlice(factors); + return AntiPrime{ + .value = value, + .divisors_count = divisors_count, + .factorization = factorization, + }; + } + + pub fn deinit(self: *AntiPrime) void { + self.factorization.deinit(); + } + + pub fn asc(context: void, a: AntiPrime, b: AntiPrime) bool { + _ = context; + if (a.value < b.value) return true; + if (a.value > b.value) return false; + if (a.divisors_count < b.divisors_count) return true; + if (a.divisors_count > b.divisors_count) return false; + if (a.factorization.items.len < b.factorization.items.len) return true; + if (a.factorization.items.len > b.factorization.items.len) return false; + for (a.factorization.items, b.factorization.items) |a_factor, b_factor| { + if (a_factor < b_factor) return true; + if (a_factor > b_factor) return false; + } + return false; + } + + pub fn clone(self: *AntiPrime) !AntiPrime { + var new_factorization = try std.ArrayList(i32).initCapacity(self.factorization.allocator, self.factorization.items.len); + errdefer new_factorization.deinit(); + try new_factorization.appendSlice(self.factorization.items); + return AntiPrime{ + .value = self.value, + .divisors_count = self.divisors_count, + .factorization = new_factorization, + }; + } +}; +const MAXN = 100000000; +fn generate_anti_primes(allocator: std.mem.Allocator) ![]AntiPrime { + var anti_primes = std.ArrayList(AntiPrime).init(allocator); + try anti_primes.append(try AntiPrime.init(allocator, 1, 1, &[_]i32{})); + const primes = try (sieve(allocator, 1000)); + defer allocator.free(primes); + + for (primes, 0..) |prime, i| { + var new_anti_primes = std.ArrayList(AntiPrime).init(allocator); + defer { + for (new_anti_primes.items) |*new_anti_prime| { + new_anti_prime.*.deinit(); + } + new_anti_primes.deinit(); + } + for (anti_primes.items) |*el| { + try new_anti_primes.append(try el.*.clone()); + if (el.*.factorization.items.len < i) continue; + const e_max = if (i >= 1) el.*.factorization.items[i - 1] else @as(i32, @intCast(std.math.log2(MAXN))); + var n1 = el.*.value; + var e: i32 = 1; + while (e <= e_max) : (e += 1) { + n1 *= prime; + if (n1 > MAXN) break; + const div = el.*.divisors_count * (e + 1); + var exponents = std.ArrayList(i32).init(allocator); + defer exponents.deinit(); + try exponents.appendSlice(el.*.factorization.items); + try exponents.append(e); + try new_anti_primes.append(try AntiPrime.init( + allocator, + @as(i32, n1), + div, + exponents.items, + )); + } + } + std.mem.sort(AntiPrime, new_anti_primes.items, {}, AntiPrime.asc); + for (anti_primes.items) |*anti_prime| { + anti_prime.*.deinit(); + } + try anti_primes.resize(0); + try anti_primes.append(try AntiPrime.init( + allocator, + 1, + 1, + &[_]i32{}, + )); + + for (new_anti_primes.items) |*el| { + if (el.divisors_count > anti_primes.getLast().divisors_count) { + try anti_primes.append(try el.*.clone()); + } + } + } + + return anti_primes.toOwnedSlice(); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer { + const result = gpa.deinit(); + if (result == .leak) { + std.debug.panic("Memory leak detected in GeneralPurposeAllocator deinit", .{}); + } + } + const stdout = std.io.getStdOut().writer(); + const n = 20; + + const anti_primes = try generate_anti_primes(allocator); + defer { + for (anti_primes) |*anti_prime| { + anti_prime.*.deinit(); + } + allocator.free(anti_primes); + } + + try stdout.print("The first 20 anti-primes:\n", .{}); + for (anti_primes[0..n], 0..) |anti_prime, index| { + try stdout.print("{} ", .{anti_prime.value}); + if (index % 10 == 9) { + try stdout.print("\n", .{}); + } + } +} diff --git a/Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina b/Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina new file mode 100644 index 0000000000..a2d7fd5818 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Ballerina/apply-a-callback-to-an-array.ballerina @@ -0,0 +1,9 @@ +import ballerina/io; + +public function main() { + int[] a = from int i in 1...10 select i; + var square = function(int i) returns int { + return i * i; + }; + io:println(a.map(i => square(i))); +} diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f new file mode 100644 index 0000000000..82aef332a6 --- /dev/null +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/Fortran/apply-a-digital-filter-direct-form-ii-transposed-.f @@ -0,0 +1,42 @@ +module df2_filter + implicit none + real, parameter :: a(4) = [1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] + real, parameter :: b(4) = [0.16666667, 0.5, 0.5, 0.16666667] + real :: w(4) = 0.0 ! State vector + +contains + function filter(x) result(y) + real, intent(in) :: x + real :: y + integer :: i + + y = x * b(1) + w(1) + + do i = 2, 4 + w(i-1) = x * b(i) - y * a(i) + w(i) + end do + end function filter +end module df2_filter + +program apply_filter + use df2_filter + implicit none + real, dimension(20) :: input = [ & + -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, & + -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, & + 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, & + 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, & + 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 ] + real, dimension(20) :: output + integer :: i + + do i = 1, 20 + output(i) = filter(input(i)) + end do + + print *, "Filtered signal:" + do i = 1,20 + write(*, '(f12.9,2x)',advance='no') output(i) + if(mod(i,5)==0)write(*,*) + end do +end program apply_filter diff --git a/Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 b/Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 new file mode 100644 index 0000000000..7cc823c84a --- /dev/null +++ b/Task/Apply-a-digital-filter-direct-form-II-transposed-/M2000-Interpreter/apply-a-digital-filter-direct-form-ii-transposed-.m2000 @@ -0,0 +1,49 @@ +module Checkit { + locale 1033 ' use of dot for decimals + window 12, window ' set 12pt for current display monitor + form 60 ' 60 chars width, any for heigh + Print $("0.00000000",12) ' 12 chars per tab + ' all data push to end of stack, so we use the stack of values as FIFO + Flush + ' a() + Data 1, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17 + ' b() + Data 0.16666667, 0.5, 0.5, 0.16666667 + ' signal() + Data -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412 + Data -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044 + Data 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195 + Data 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293 + Data 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589 + Dim Base 0, a(4) as Double , b(4) as Double , signal(20) as Double + Integer i + For i = 0 To 3 : Read a(i) : Next i + For i = 0 To 3 : Read b(i) : Next i + For i = 0 To 19 : Read signal(i) : Next i + dim resp() + resp()=@Filter_a_b(&signal()) + k=each(resp()) + while k + Print array(k), + if pos>0 then if (k^+1) mod 5=0 then Print + end while + Function Filter_a_b(&c()) + Local Integer j, k + Local Double tmp + Local result(0 to len(c())-1) as Double + For j = 0 To Len(c())-1 + tmp = 0 + For k = 0 To Len(b())-1 + If (j-k < 0) Then Continue For + tmp += b(k) * c(j-k) + Next k + For k = 0 To Len(a())-1 + If (j-k < 0) Then Continue For + tmp -= a(k) * result(j-k) + Next k + result(j) = tmp/a(0) + Next j + =result() + End Function +} +Checkit diff --git a/Task/Approximate-equality/Ballerina/approximate-equality.ballerina b/Task/Approximate-equality/Ballerina/approximate-equality.ballerina new file mode 100644 index 0000000000..83ba4b25e0 --- /dev/null +++ b/Task/Approximate-equality/Ballerina/approximate-equality.ballerina @@ -0,0 +1,22 @@ +import ballerina/io; + +public function main() { + float[][] pairs = [ + [100000000000000.01, 100000000000000.011], + [100.01, 100.011], + [10000000000000.001 / 10000.0, 1000000000.0000001000], + [0.001, 0.0010000001], + [0.000000000000000000000101, 0.0], + [2.0.sqrt() * 2.0.sqrt(), 2.0], + [-2.0.sqrt() * 2.0.sqrt(), -2.0], + [3.14159265358979323846, 3.14159265358979324] + ]; + io:println("Approximate equality of test cases with a tolerance of 1 bit:"); + int i = 0; + foreach float[] pair in pairs { + i += 1; + int bi0 = pair[0].toBitsInt(); + int bi1 = pair[1].toBitsInt(); + io:println(` ${i} -> ${(bi0 - bi1).abs() <= 1}`); + } +} diff --git a/Task/Approximate-equality/EasyLang/approximate-equality.easy b/Task/Approximate-equality/EasyLang/approximate-equality.easy index 910f89b4d4..5384fbce38 100644 --- a/Task/Approximate-equality/EasyLang/approximate-equality.easy +++ b/Task/Approximate-equality/EasyLang/approximate-equality.easy @@ -1,7 +1,7 @@ func aeq a b . return if abs (a - b) <= abs a * 1e-14 . -proc test a b . . +proc test a b . write a & " " & b & " -> " if aeq a b = 1 print "true" @@ -9,7 +9,7 @@ proc test a b . . print "false" . . -numfmt 10 0 +numfmt 0 10 test 100000000000000.01 100000000000000.011 test 100.01 100.011 test 10000000000000.001 / 10000 1000000000.0000001 diff --git a/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy b/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy index 6f648c90fb..4fc2177a04 100644 --- a/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy +++ b/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy @@ -1,8 +1,12 @@ -linewidth 0.4 -x = 50 -y = 50 +glinewidth 0.4 +x0 = 50 +y0 = 50 while r < 50 - line r * cos t + x r * sin t + y + xp = x + yp = y + x = r * cos t + x0 + y = r * sin t + y0 + if r > 0 : gline xp yp x y r += 0.05 t += 3 . diff --git a/Task/Arithmetic-Complex/ALGOL-68/arithmetic-complex.alg b/Task/Arithmetic-Complex/ALGOL-68/arithmetic-complex.alg index 0e4466402d..d1c920b389 100644 --- a/Task/Arithmetic-Complex/ALGOL-68/arithmetic-complex.alg +++ b/Task/Arithmetic-Complex/ALGOL-68/arithmetic-complex.alg @@ -1,27 +1,29 @@ -main:( - FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$; +BEGIN PROC compl operations = VOID: ( - LONG COMPL a = 1.0 ⊥ 1.0; - LONG COMPL b = 3.14159 ⊥ 1.2; + COMPL a = 1.0 I 1.0; + COMPL b = 3.14159 I 1.2; - LONG COMPL c; + COMPL c; - printf(($x"a="f(compl fmt)l$,a)); - printf(($x"b="f(compl fmt)l$,b)); + PROC show compl = ( STRING legend, COMPL v )VOID: + print( ( legend, fixed( re OF v, -8, 5 ), " I ", fixed( im OF v, -8, 5 ), newline ) ); + + show compl(" a=",a); + show compl(" b=",b); # addition # c := a + b; - printf(($x"a+b="f(compl fmt)l$,c)); + show compl("a+b=",c); # multiplication # c := a * b; - printf(($x"a*b="f(compl fmt)l$,c)); + show compl("a*b=",c); # inversion # c := 1.0 / a; - printf(($x"1/c="f(compl fmt)l$,c)); + show compl("1/c=",c); # negation # c := -a; - printf(($x"-a="f(compl fmt)l$,c)) + show compl(" -a=",c) ); compl operations -) +END diff --git a/Task/Arithmetic-Complex/Ballerina/arithmetic-complex.ballerina b/Task/Arithmetic-Complex/Ballerina/arithmetic-complex.ballerina new file mode 100644 index 0000000000..a17cb192ef --- /dev/null +++ b/Task/Arithmetic-Complex/Ballerina/arithmetic-complex.ballerina @@ -0,0 +1,67 @@ +import ballerina/io; + +class Complex { + float re; + float im; + + function init(float re, float im) { + self.re = re; + self.im = im; + } + + function neg() returns Complex { + return new Complex(-self.re, -self.im); + } + + function inv() returns Complex { + float denom = self.re * self.re + self.im * self.im; + return new Complex(self.re / denom, -self.im / denom); + } + + function add(Complex other) returns Complex { + return new Complex(self.re + other.re, self.im + other.im); + } + + function sub(Complex other) returns Complex { + return self.add(other.neg()); + } + + function mul(Complex other) returns Complex { + return new Complex( + self.re * other.re - self.im * other.im, + self.re * other.im + self.im * other.re + ); + } + + function div(Complex other) returns Complex { + return self.mul(other.inv()); + } + + function conj() returns Complex { + return new Complex(self.re, -self.im); + } + + function toString() returns string { + if self.re === -0.0 { self.re = 0.0; } + if self.im === -0.0 { self.im = 0.0; } + if self.im >= 0.0 { + return string `${self.re} + ${self.im}i`; + } else { + return string `${self.re} - ${-self.im}i`; + } + } +} + +public function main() { + var x = new Complex(1, 3); + var y = new Complex(5, 2); + io:println("x = ", x); + io:println("y = ", y); + io:println("x + y = ", x.add(y)); + io:println("x - y = ", x.sub(y)); + io:println("x * y = ", x.mul(y)); + io:println("x / y = ", x.div(y)); + io:println("-x = ", x.neg()); + io:println("1 / x = ", x.inv()); + io:println("x* = ", x.conj()); +} diff --git a/Task/Arithmetic-Complex/Crystal/arithmetic-complex.cr b/Task/Arithmetic-Complex/Crystal/arithmetic-complex.cr new file mode 100644 index 0000000000..bb024b95a6 --- /dev/null +++ b/Task/Arithmetic-Complex/Crystal/arithmetic-complex.cr @@ -0,0 +1,15 @@ +require "complex" + +a = Complex.new(1, 2) +b = 3 + 4.i + +puts "a = #{a}, b = #{b}" +puts +puts "a + b = #{a + b}" +puts "a - b = #{a - b}" +puts "a * b = #{a * b}" +puts "a / b = #{a / b}" +puts +puts "-a = #{-a}" +puts "1/a = #{a.inv}" +puts "ā = #{a.conj}" diff --git a/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex.m2000 b/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex-1.m2000 similarity index 100% rename from Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex.m2000 rename to Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex-1.m2000 diff --git a/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex-2.m2000 b/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex-2.m2000 new file mode 100644 index 0000000000..2b527fe51b --- /dev/null +++ b/Task/Arithmetic-Complex/M2000-Interpreter/arithmetic-complex-2.m2000 @@ -0,0 +1,35 @@ +module tstComplex { + // Var one as complex=(1,0i), A as complex=(8, -3i) + one=(1,0i) + A=(8, -3i) + Print "A=";A + Print " r=";Abs(A);" θ=";Arg(A);" rad" + B=one/A + Print "B=";B + Print " r=";Abs(B);" θ=";Arg(B);" rad" + Print A;"*";B;"=";A*B + Print one;"/";B;"=";one/B + Print A;"/";A;"=";A/A + Print A;"+";A;"=";A+A + Print A;"-";A;"=";A-A + Print "-"+A+"=";-A + Print "(round exp to 13th decimal)" + I=round(exp((0, pi i)),13)+1 + Print "e^(πi)+1=";i + Print "(without rounding)" + I=exp((0, pi i))+1 + Print "e^(πi)+1=";i + Print type$(i) = "Complex" + Dim a(10) as Complex=(1,0i) + Print (a(3)+a(3))^2=(4, 0i) + Print (a(3)+a(3))^2=4 + + Print cos(a) + Print sin(a) + Print atn(tan(a)) + Print tan(atn(a)) + Print Polar(abs(a), arg(a))=(8, -3i) + Print str$(a ,"0.00") + Print str$((8,-3i) ,"0.00") +} + tstComplex diff --git a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx index fd21689cfc..7c72a01f37 100644 --- a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx +++ b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx @@ -1,38 +1,53 @@ +-- 19 May 2025 include Settings -say version; say 'Arithmetic numbers'; say -numeric digits 9 -divi. = 0; a = 0; c = 0 -do i = 1 -/* Is the number arithmetic? */ - if Arithmetic(i) then do - a = a+1 -/* Is the number composite? */ - if divi.0 > 2 then - c = c+1 -/* Output control */ - if a <= 100 then do - if a = 1 then - say 'First 100 arithmetic numbers are' - call Charout ,Right(i,4) - if a//10 = 0 then - say - if a = 100 then - say - end - if a = 100 | a = 1000 | a = 10000 | a = 100000 | a = 1000000 then do - say 'The' a'th arithmetic number is' i - say 'Of the first' a 'numbers' c 'are composite' - say - end -/* Max 1m, higher takes too long */ - if a = 1000000 then - leave - end -end -say Format(Time('e'),,3) 'seconds' +say 'COMPLEX ARITHMETIC' +say version +say +a = '1 2'; b = '3 4'; c = '5 6'; d = '7 8'; i = I() +say 'VALUES' +say 'a =' crec2form(a) +say 'b =' crec2form(b) +say 'c =' crec2form(c) +say 'd =' crec2form(d) +say +say 'BASICS' +say 'i*i =' crec2form(Csquare(i())) +say 'a+b =' crec2form(Cadd(a,b)) +say 'a-b =' crec2form(Csub(a,b)) +say 'a*b =' crec2form(Cmul(a,b)) +say 'a/b =' crec2form(Cdiv(a,b)) +say 'a^2 =' crec2form(Csquare(a,2)) +say 'a^5 =' crec2form(Cpow(a,5)) +say '-a =' crec2form(Cneg(a)) +say '1/a =' crec2form(Cinv(a)) +say 'a+b+c+d =' crec2form(Cadd(a,b,c,d)) +say 'a-b-c-d =' crec2form(Csub(a,b,c,d)) +say 'a*b*c*d =' crec2form(Cmul(a,b,c,d)) +say 'a/b/c/d =' crec2form(Cnormal(Cdiv(a,b,c,d))) +say +say 'FORMULA' +say 'a^2-2ab+3c-4ad^4+5 =' , +crec2form(Cadd(Csquare(a),Cmul(-2,a,b),Cmul(3,c),Cmul(-4,a,Cpower(d,4)),5)) +say +say 'BONUS' +say 'Argument(a) =' Carg(a)+0 +say 'Conjugate(a) =' crec2form(Cconj(a)) +say 'Imag(a) =' Cim(a) +say 'Modulus(a) =' Cmod(a)+0 +say 'Polar(a) =' Cpol2form(Cnormal(Crec2pol(a))) +say 'Real(a) =' Cre(a) +say +say 'MORE' +say 'Arcsin(a) =' crec2form(Cnormal(Carcsin(a))) +say 'Exp(a) =' crec2form(Cnormal(Cexp(a))) +say 'Ln(a) =' crec2form(Cnormal(Cln(a))) +say 'Sin(a) =' crec2form(Cnormal(Csin(a))) +say 'Sqrt(a) =' crec2form(Cnormal(Csqrt(a))) +say 'i^i =' crec2form(Cnormal(Cpower(i,i))) exit -include Numbers +include Complex include Functions +include Constants include Abend diff --git a/Task/Arithmetic-Integer/Ballerina/arithmetic-integer.ballerina b/Task/Arithmetic-Integer/Ballerina/arithmetic-integer.ballerina new file mode 100644 index 0000000000..0ab61725c4 --- /dev/null +++ b/Task/Arithmetic-Integer/Ballerina/arithmetic-integer.ballerina @@ -0,0 +1,24 @@ +import ballerina/io; + +function divmod(int a, int b) returns [int, int] { + return [a / b, a % b]; +} + +function pow(int n, int e) returns int { + if e < 1 { return 1; } + int prod = 1; + foreach int i in 1...e { prod *= n; } + return prod; +} + +public function main() returns error? { + int a = check int:fromString(io:readln("first number: ")); + int b = check int:fromString(io:readln("second number: ")); + io:println("sum: ", a + b); + io:println("difference: ", a - b); + io:println("product: ", a * b); + io:println("integer quotient: ", a / b); // rounds towards zero + io:println("remainder: ", a % b); // sign matches sign of first operand + io:println("exponentiation: ", pow(a, b)); + io:println("divmod ", divmod(a, b)); +} diff --git a/Task/Arithmetic-Integer/OPL/arithmetic-integer.opl b/Task/Arithmetic-Integer/OPL/arithmetic-integer.opl new file mode 100644 index 0000000000..57f4ee3106 --- /dev/null +++ b/Task/Arithmetic-Integer/OPL/arithmetic-integer.opl @@ -0,0 +1,14 @@ +PROC main: + LOCAL a%,b% + PRINT "Please enter a number:", + INPUT a% + PRINT "Please enter another number:", + INPUT b% + PRINT a%;"+";b%;"=";a%+b% + PRINT a%;"-";b%;"=";a%-b% + PRINT a%;"×";b%;"=";a%*b% + PRINT a%;"÷";b%;"=";a%/b% + PRINT a%;"%";b%;"=";a%-a%/b%*b% + PRINT a%;"^";b%;"=";a%**b% + GET +ENDP diff --git a/Task/Arithmetic-Integer/Wren/arithmetic-integer.wren b/Task/Arithmetic-Integer/Wren/arithmetic-integer.wren index df5b65f478..5e19a436e2 100644 --- a/Task/Arithmetic-Integer/Wren/arithmetic-integer.wren +++ b/Task/Arithmetic-Integer/Wren/arithmetic-integer.wren @@ -1,13 +1,13 @@ -import "io" for Stdin, Stdout -System.write("first number: ") -Stdout.flush() -var a = Num.fromString(Stdin.readLine()) -System.write("second number: ") -Stdout.flush() -var b = Num.fromString(Stdin.readLine()) +import "./ioutil" for Input, Stdin + +var divmod = Fn.new { |a, b| [(a / b).floor, a % b] } + +var a = Input.integer("first number: ") +var b = Input.integer("second number: ") System.print("sum: %(a + b)") System.print("difference: %(a - b)") System.print("product: %(a * b)") System.print("integer quotient: %((a / b).floor)") System.print("remainder: %(a % b)") System.print("exponentiation: %(a.pow(b))") +System.print("divmod: %(divmod.call(a, b))") diff --git a/Task/Arithmetic-Rational/Ballerina/arithmetic-rational.ballerina b/Task/Arithmetic-Rational/Ballerina/arithmetic-rational.ballerina new file mode 100644 index 0000000000..7c6dc57fb6 --- /dev/null +++ b/Task/Arithmetic-Rational/Ballerina/arithmetic-rational.ballerina @@ -0,0 +1,156 @@ +import ballerina/io; + +function gcd(int num, int den) returns int { + int n = num; // make mutable + int d = den; // ditto + while d != 0 { + int t = d; + d = n % d; + n = t; + } + return n; +} + +class Frac { + int num; + int den; + + function init(int num, int den) { + int n = num; // make mutable + int d = den; // ditto + if n == 0 { + d = 1; + } else if d < 0 { + n = -n; + d = -d; + } + int g = gcd(n, d).abs(); + if g > 1 { + n /= g; + d /= g; + } + self.num = n; + self.den = d; + } + + function fromInt(int i) returns Frac { + return new Frac(i, 1); + } + + function neg() returns Frac { + return new Frac(-self.num, self.den); + } + + function inv() returns Frac { + return new Frac(self.den, self.num); + } + + function copy() returns Frac { + return new Frac(self.num, self.den); + } + + function abs() returns Frac { + if self.num >= 0 { return self.copy(); } + return self.neg(); + } + + function add(Frac other) returns Frac { + return new Frac(self.num * other.den + self.den * other.num, self.den * other.den); + } + + function sub(Frac other) returns Frac { + return self.add(other.neg()); + } + + function mul(Frac other) returns Frac { + return new Frac(self.num * other.num, self.den * other.den); + } + + function div(Frac other) returns Frac { + return new Frac(self.num * other.den, self.den * other.num); + } + + function toFloat() returns float { + return self.num / self.den; + } + + function toInt() returns int { + float f = self.toFloat(); + f = f >= 0.0 ? f.floor() : f.ceiling(); + return f; + } + + function idiv(Frac other) returns Frac { + return new Frac(self.toInt(), 1); + } + + function mod(Frac other) returns Frac { + return self.sub(self.idiv(other).mul(other)); + } + + function lt(Frac other) returns boolean { + return self.toFloat() < other.toFloat(); + } + + function le(Frac other) returns boolean { + return self.toFloat() <= other.toFloat(); + } + + function gt(Frac other) returns boolean { + return self.toFloat() > other.toFloat(); + } + + function ge(Frac other) returns boolean { + return self.toFloat() >= other.toFloat(); + } + + function eq(Frac other) returns boolean { + return self.toFloat() == other.toFloat(); + } + + function ne(Frac other) returns boolean { + return self.toFloat() != other.toFloat(); + } + + function toString() returns string { + return string `${self.num} / ${self.den}`; + } +} + +function divisors(int n) returns int[] { + if n < 1 { return []; } + int[] divisors = []; + int[] divisors2 = []; + int i = 1; + int k = n % 2 == 0 ? 1 : 2; + while i * i <= n { + if n % i == 0 { + divisors.push(i); + int j = n / i; + if j != i { divisors2.push(j); } + } + i += k; + } + if divisors2.length() > 0 { + divisors.push(...divisors2.reverse()); + } + return divisors; +} + +function properDivisors(int n) returns int[] { + int[] d = divisors(n); + int c = d.length(); + return c <= 1 ? [] : d.slice(0, c - 1); +} + +public function main() { + final Frac one = new Frac(1, 1); + io:println("The following numbers (less than 2^19) are perfect:"); + foreach int i in 2..<(1<<19) { + var sum = new Frac(1, i); + foreach int j in properDivisors(i).slice(1) { + sum = sum.add(new Frac(1, j)); + } + if sum.eq(one) { io:println(" ", i); } + } +} diff --git a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx index 16e57b5dcc..a7f3438a50 100644 --- a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx +++ b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx @@ -1,6 +1,8 @@ include Settings -say version; say 'Rational arithmetic'; say +say 'RATIONAL ARITHMETIC - 2 Mar 2025' +say version +say a = '1 2'; b = '-3 4'; c = '5 -6'; d = '-7 -8'; e = 3; f = 1.666666666 say 'VALUES' say 'a =' Rlst2form(a) diff --git a/Task/Arithmetic-derivative/00-TASK.txt b/Task/Arithmetic-derivative/00-TASK.txt index 7e36aa263c..6335ba8b8f 100644 --- a/Task/Arithmetic-derivative/00-TASK.txt +++ b/Task/Arithmetic-derivative/00-TASK.txt @@ -4,21 +4,21 @@ factorization, by analogy with the product rule for the derivative of a function used in mathematical analysis. Accordingly, for natural numbers n, the arithmetic derivative D(n) is defined as follows: -;*D(0) = D(1) = 0. -;*D(p) = 1 for any prime p. -;*D(mn) = D(m)n + mD(n) for any m,n ∈ N. (Leibniz rule for derivatives). +;*D(0) = D(1) = 0. +;*D(p) = 1 \;\text{for any prime}\; p. +;*D(mn) = D(m)n + mD(n) \;\text{for any}\; m,n \in N. (Leibniz rule for derivatives). -Additionally, for negative integers the arithmetic derivative may be defined as -D(-n) (n < 0). +Additionally, for negative integers the arithmetic derivative may be defined as -D(-n) \;\text{for}\; (n < 0). ; Examples -D(2) = 1 and D(3) = 1 (both are prime) so if mn = 2 * 3, D(6) = (1)(3) + (1)(2) = 5. +D(2) = 1 and D(3) = 1 (both are prime) so if mn = 2 \cdot 3, then D(6) = D(2\cdot 3) = D(2)\cdot 3 + 2\cdot D(3) = 1\cdot 3 + 2\cdot 1 = 5. -D(9) = D(3)(3) + D(3)(3) = 6 +D(9) = D(3)\cdot 3 + 3\cdot D(3) = 1\cdot 3 + 3\cdot 1 = 6 -D(27) = D(3)*9 + D(9)*3 = 9 + 18 = 27 +D(27) = D(3)\cdot 9 + 3\cdot D(9) = 1\cdot 9 + 3\cdot 6 = 27 -D(30) = D(5)(6) + D(6)(5) = 6 + 5 * 5 = 31. +D(30) = D(5)\cdot 6 + 5\cdot D(6) = 1\cdot 6 + 5 \cdot 5 = 31. ; Task @@ -26,7 +26,7 @@ Find and show the arithmetic derivatives for -99 through 100. ; Stretch task -Find (the arithmetic derivative of 10^m) then divided by 7, where m is from 1 to 20. +Find (the arithmetic derivative of 10^m) then divided by 7, where m is from 1 to 20. ; See also diff --git a/Task/Arithmetic-derivative/Arturo/arithmetic-derivative.arturo b/Task/Arithmetic-derivative/Arturo/arithmetic-derivative.arturo new file mode 100644 index 0000000000..38ff353852 --- /dev/null +++ b/Task/Arithmetic-derivative/Arturo/arithmetic-derivative.arturo @@ -0,0 +1,20 @@ +D: $[x][ + when [ + x < 0 -> neg D neg x + x = 0 -> 0 + x = 1 -> 0 + prime? x -> 1 + any [ + m: 2 + while [0 <> x % m] -> inc 'm + n: x / m + (n * D m) + m * D n + ] + ] +] + +(neg 99)..100 | map => D + | split.every:10 + | loop => [loop & 'n -> prints pad to :string n 5 print ""] +print "" +loop 20 'n -> print ~"D(10^|n|)/7 = |div D 10^n 7|" diff --git a/Task/Arithmetic-derivative/C-sharp/arithmetic-derivative.cs b/Task/Arithmetic-derivative/C-sharp/arithmetic-derivative.cs new file mode 100644 index 0000000000..bdfc86296d --- /dev/null +++ b/Task/Arithmetic-derivative/C-sharp/arithmetic-derivative.cs @@ -0,0 +1,30 @@ +using System.Numerics; + +static BigInteger Derivative(BigInteger k) +{ + if (k < 0) return -Derivative(-k); + if (k < 2) return 0; + if (k.IsEven) return 2 * Derivative(k / 2) + k / 2; + BigInteger m = 3; + + while (m * m <= k && (k % m) != 0) + m += 2; + + var n = k / m; + if (m * n != k || m == 1 || n == 1) return 1; + return n * Derivative(m) + m * Derivative(n); +} + +for (var i = -99; i <= 100; i++) +{ + Console.Write($"{Derivative(i),6}"); + if (i % 10 == 0) Console.WriteLine(); +} + +BigInteger p = 1; + +for (var n = 1; n <= 20; n++) +{ + p *= 10; + Console.WriteLine($"⅐ D(10^{n}) = {Derivative(p) / 7}"); +} diff --git a/Task/Arithmetic-derivative/EasyLang/arithmetic-derivative.easy b/Task/Arithmetic-derivative/EasyLang/arithmetic-derivative.easy index e7f21eef65..32e17c547e 100644 --- a/Task/Arithmetic-derivative/EasyLang/arithmetic-derivative.easy +++ b/Task/Arithmetic-derivative/EasyLang/arithmetic-derivative.easy @@ -1,18 +1,12 @@ func lagarias n . - if n < 0 - return -lagarias -n - . - if n = 0 or n = 1 - return 0 - . + if n < 0 : return -lagarias -n + if n = 0 or n = 1 : return 0 f = 2 while n mod f <> 0 f += 1 . q = n / f - if q = 1 - return 1 - . + if q = 1 : return 1 return q * lagarias f + f * lagarias q . for n = -99 to 100 diff --git a/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy b/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy index f8bbf4ec53..bf0629bde2 100644 --- a/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy +++ b/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy @@ -9,9 +9,7 @@ subr nch . # subr ntok - while ch$ = " " - nch - . + while ch$ = " " : nch if ch >= 48 and ch <= 58 tok$ = "n" s$ = "" @@ -33,14 +31,14 @@ subr init0 astright[] = [ ] err = 0 . -proc init s$ . . +proc init s$ . inp$[] = strchars s$ inp_ind = 1 nch ntok init0 . -proc ast_print nd . . +proc ast_print nd . write "AST:" for i to len astop$[] write " ( " diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/EasyLang/arithmetic-geometric-mean-calculate-pi.easy b/Task/Arithmetic-geometric-mean-Calculate-Pi/EasyLang/arithmetic-geometric-mean-calculate-pi.easy index 0ebe1a31ba..3993aa60d6 100644 --- a/Task/Arithmetic-geometric-mean-Calculate-Pi/EasyLang/arithmetic-geometric-mean-calculate-pi.easy +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/EasyLang/arithmetic-geometric-mean-calculate-pi.easy @@ -11,5 +11,5 @@ while pn <= 5 pn *= 2 . mypi = (an + bn) * (an + bn) / (tn * 4) -numfmt 15 0 +numfmt 0 15 print mypi diff --git a/Task/Arithmetic-geometric-mean/C++/arithmetic-geometric-mean.cpp b/Task/Arithmetic-geometric-mean/C++/arithmetic-geometric-mean.cpp index e72ad24f16..71033b0d1f 100644 --- a/Task/Arithmetic-geometric-mean/C++/arithmetic-geometric-mean.cpp +++ b/Task/Arithmetic-geometric-mean/C++/arithmetic-geometric-mean.cpp @@ -1,28 +1,22 @@ -#include -using namespace std; -#define _cin ios_base::sync_with_stdio(0); cin.tie(0); -#define rep(a, b) for(ll i =a;i<=b;++i) +#include +#include -double agm(double a, double g) //ARITHMETIC GEOMETRIC MEAN -{ double epsilon = 1.0E-16,a1,g1; - if(a*g<0.0) - { cout<<"Couldn't find arithmetic-geometric mean of these numbers\n"; - exit(1); - } - while(fabs(a-g)>epsilon) - { a1 = (a+g)/2.0; - g1 = sqrt(a*g); - a = a1; - g = g1; - } - return a; +double agm(double a, double g, double tolerance = 1e-16) { + double an = a; + double gn = g; + + an = (a + g) / 2.0; + gn = std::sqrt(a*g); + while (std::abs(an-gn) > tolerance) { + an = (an + gn) / 2.0; + gn = std::sqrt(an*gn); + } + + return an; } -int main() -{ _cin; //fast input-output - double x, y; - cout<<"Enter X and Y: "; //Enter two numbers - cin>>x>>y; - cout<<"\nThe Arithmetic-Geometric Mean of "<= Float64::EPSILON + a, g = (a + g) / 2, Math.sqrt(a * g) + end + g +end + +p agm(1, 1 / Math.sqrt(2)) diff --git a/Task/Arithmetic-geometric-mean/EasyLang/arithmetic-geometric-mean.easy b/Task/Arithmetic-geometric-mean/EasyLang/arithmetic-geometric-mean.easy index 5f7ce66faf..978c4034e4 100644 --- a/Task/Arithmetic-geometric-mean/EasyLang/arithmetic-geometric-mean.easy +++ b/Task/Arithmetic-geometric-mean/EasyLang/arithmetic-geometric-mean.easy @@ -7,5 +7,5 @@ func agm a g . . return a . -numfmt 16 0 +numfmt 0 16 print agm 1 sqrt 0.5 diff --git a/Task/Arithmetic-numbers/Ballerina/arithmetic-numbers.ballerina b/Task/Arithmetic-numbers/Ballerina/arithmetic-numbers.ballerina new file mode 100644 index 0000000000..30f7f08c8e --- /dev/null +++ b/Task/Arithmetic-numbers/Ballerina/arithmetic-numbers.ballerina @@ -0,0 +1,98 @@ +import ballerina/io; + +function divisors(int n) returns int[] { + if n < 1 { return []; } + int[] divisors = []; + int[] divisors2 = []; + int i = 1; + int k = n % 2 == 0 ? 1 : 2; + while i * i <= n { + if n % i == 0 { + divisors.push(i); + int j = n / i; + if j != i { divisors2.push(j); } + } + i += k; + } + if divisors2.length() > 0 { + divisors.push(...divisors2.reverse()); + } + return divisors; +} + +function findNearest(int[] a, int value) returns int { + int count = a.length(); + int low = 0; + int high = count - 1; + while low <= high { + int mid = (low + high) / 2; + if a[mid] >= value { + high = mid - 1; + } else { + low = mid + 1; + } + } + return low < count ? low : count; +} + +function commatize(int n) returns string { + string s = n.toString(); + if n < 0 { s = s.substring(1); } + int le = s.length(); + foreach int i in int:range(le - 3, 0, -3) { + s = s.substring(0, i) + "," + s.substring(i); + } + if n >= 0 { return s; } + return "-" + s; +} + +function isPrime(int n) returns boolean { + if n < 2 { return false; } + if n % 2 == 0 { return n == 2; } + if n % 3 == 0 { return n == 3; } + int d = 5; + while d * d <= n { + if n % d == 0 { return false; } + d += 2; + if n % d == 0 { return false; } + d += 4; + } + return true; +} + +public function main() { + int[] arithmetic = [1]; + int[] primes = []; + final int lim = 1e6; + int n = 3; + while arithmetic.length() < lim { + int[] divs = divisors(n); + int len = divs.length(); + if len == 2 { + primes.push(n); + arithmetic.push(n); + } else { + int sum = int:sum(...divs); + if sum % len == 0 { arithmetic.push(n); } + } + n += 1; + } + io:println("The first 100 arithmetic numbers are:"); + foreach int i in 0...99 { + io:print(arithmetic[i].toString().padStart(4)); + if (i + 1) % 10 == 0 { io:println(); } + } + + foreach float f in [1e3, 1e4, 1e5, 1e6] { + int x = f; + int last = arithmetic[x - 1]; + string xc = commatize(x); + string lastc = commatize(last); + io:println("\nThe ", xc, "th arithmetic number is: ", lastc); + int pcount = findNearest(primes, last) + 1; + if !isPrime(last) { pcount -= 1; } + int comp = x - pcount - 1; // 1 is not composite + string compc = commatize(comp); + io:println(`"The count of such numbers <= ${lastc} which are composite is ${compc}.`); + } +} diff --git a/Task/Arithmetic-numbers/EasyLang/arithmetic-numbers.easy b/Task/Arithmetic-numbers/EasyLang/arithmetic-numbers.easy index cd8dc13f35..659573ce77 100644 --- a/Task/Arithmetic-numbers/EasyLang/arithmetic-numbers.easy +++ b/Task/Arithmetic-numbers/EasyLang/arithmetic-numbers.easy @@ -1,8 +1,5 @@ -print "The first 100 arithmetic numbers are:" -numfmt 0 3 -n = 1 -while aricnt <= 1e5 - divi = 1 ; divcnt = 0 ; sum = 0 +proc arith n &ari &comp . + divi = 1 repeat quot = n div divi until quot < divi @@ -17,20 +14,29 @@ while aricnt <= 1e5 . divi += 1 . - if sum mod divcnt = 0 - aricnt += 1 - if aricnt <= 100 - write n & " " - if aricnt mod 10 = 0 - print "" - . - . - if divcnt > 2 - compcnt += 1 - . - if aricnt = 1e3 or aricnt = 1e4 or aricnt = 1e5 + ari = if sum mod divcnt = 0 + comp = if divcnt > 2 +. +print "The first 100 arithmetic numbers are:" +n = 1 +while cnt < 100 + arith n ari comp + if ari = 1 + write n & " " + cnt += 1 + compcnt += comp + . + n += 1 +. +print "" +while cnt < 1e5 + arith n ari comp + if ari = 1 + cnt += 1 + compcnt += comp + if cnt = 1e3 or cnt = 1e4 or cnt = 1e5 print "" - print aricnt & "th arithmetic number: " & n + print cnt & "th arithmetic number: " & n print "Composite arithmetic numbers: " & compcnt . . diff --git a/Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx b/Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx index fd21689cfc..72dfe03689 100644 --- a/Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx +++ b/Task/Arithmetic-numbers/REXX/arithmetic-numbers.rexx @@ -1,16 +1,16 @@ +-- 8 May 2025 include Settings -say version; say 'Arithmetic numbers'; say +say 'ARITHMETIC NUMBERS' +say version +say numeric digits 9 -divi. = 0; a = 0; c = 0 -do i = 1 -/* Is the number arithmetic? */ +a = 0; c = 0 +do i = 1 to 1e6 if Arithmetic(i) then do a = a+1 -/* Is the number composite? */ - if divi.0 > 2 then + if Composite(i) then c = c+1 -/* Output control */ if a <= 100 then do if a = 1 then say 'First 100 arithmetic numbers are' @@ -25,14 +25,12 @@ do i = 1 say 'Of the first' a 'numbers' c 'are composite' say end -/* Max 1m, higher takes too long */ - if a = 1000000 then - leave end end say Format(Time('e'),,3) 'seconds' -exit +return include Numbers include Functions +include Special include Abend diff --git a/Task/Arithmetic-numbers/TypeScript/arithmetic-numbers.ts b/Task/Arithmetic-numbers/TypeScript/arithmetic-numbers.ts new file mode 100644 index 0000000000..617654bb18 --- /dev/null +++ b/Task/Arithmetic-numbers/TypeScript/arithmetic-numbers.ts @@ -0,0 +1,32 @@ +function divisors(n: number): number[] { + const divs = [1, n]; + const sqr = Math.sqrt(n); + for (let d = 2; d <= sqr; d++) { + if (n % d == 0) { + divs.push(d); + if (d != sqr) divs.push(n / d); + } + } // We don't really need to sort them for this task but it's nice to make + return divs.toSorted(function(a, b) {return a - b}); // functions reusable +} + +let count = 0; +let val = 0; +let composites = 0; +const arithList: number[] =[]; +const printValues = [1000, 10000, 100000, 1000000]; +while (count < 10**6) { + val += 1; + const divList = divisors(val); + const average = divList.reduce((a, b) => a + b) / divList.length; + if (Number.isInteger(average)) { + count += 1; + if (divList.length > 2) composites++; + if (count <= 100) arithList.push(val); + if (count == 100) console.log(arithList); + if (printValues.includes(count)) { + console.log("The " + count + "th arithmetic number is " + val); + console.log(composites + " of the first " + count + " are composite\n"); + } + } +} diff --git a/Task/Array-concatenation/Ballerina/array-concatenation.ballerina b/Task/Array-concatenation/Ballerina/array-concatenation.ballerina new file mode 100644 index 0000000000..3b036efa33 --- /dev/null +++ b/Task/Array-concatenation/Ballerina/array-concatenation.ballerina @@ -0,0 +1,7 @@ +import ballerina/io; + +public function main() { + int[3] a = [1, 2, 3]; + int[3] b = [4, 5, 6]; + io:println([...a, ...b]); +} diff --git a/Task/Array-concatenation/EasyLang/array-concatenation.easy b/Task/Array-concatenation/EasyLang/array-concatenation.easy index 80e53eb819..4776b79390 100644 --- a/Task/Array-concatenation/EasyLang/array-concatenation.easy +++ b/Task/Array-concatenation/EasyLang/array-concatenation.easy @@ -1,7 +1,5 @@ a[] = [ 1 2 3 ] b[] = [ 4 5 6 ] c[] = a[] -for h in b[] - c[] &= h -. +for h in b[] : c[] &= h print c[] diff --git a/Task/Array-concatenation/REXX/array-concatenation-1.rexx b/Task/Array-concatenation/REXX/array-concatenation-1.rexx deleted file mode 100644 index fe578fd7ad..0000000000 --- a/Task/Array-concatenation/REXX/array-concatenation-1.rexx +++ /dev/null @@ -1,3 +0,0 @@ -a.1 = 10 -a.2 = 22.7 -a.7 = -12 diff --git a/Task/Array-concatenation/REXX/array-concatenation-2.rexx b/Task/Array-concatenation/REXX/array-concatenation-2.rexx deleted file mode 100644 index c3441e86c0..0000000000 --- a/Task/Array-concatenation/REXX/array-concatenation-2.rexx +++ /dev/null @@ -1,9 +0,0 @@ -fact.0=8 -fact.1= 1 -fact.2= 2 -fact.3= 6 -fact.4= 24 -fact.5= 120 -fact.6= 720 -fact.7= 5040 -fact.8=40320 diff --git a/Task/Array-concatenation/REXX/array-concatenation-3.rexx b/Task/Array-concatenation/REXX/array-concatenation-3.rexx deleted file mode 100644 index ebea33a02e..0000000000 --- a/Task/Array-concatenation/REXX/array-concatenation-3.rexx +++ /dev/null @@ -1,22 +0,0 @@ -/*REXX program to demonstrates how to perform array concatenation.*/ - -p.= /*(below) a short list of primes.*/ -p.1=2; p.2=3; p.3=5; p.4=7; p.5=11; p.6=13 -p.7=17; p.8=19; p.9=23; p.10=27; p.11=31; p.12=37 - -f.= /*(below) a list of Fibonacci #s.*/ -f.0=0;f.1=1;f.2=1;f.3=2;f.4=3;f.5=5;f.6=8;f.7=13;f.8=21;f.9=34;f.10=55 - - do j=1 while p.j\=='' - c.j=p.j /*assign C array with some primes*/ - end /*j*/ -n=j-1 - do k=0 while f.k\==''; n=n+1 - c.n=f.k /*assign C array with fib numbers*/ - end /*k*/ -say 'elements=' n -say - do m=1 for n - say 'c.'m"="c.m /*show a "merged" C array nums.*/ - end /*m*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Array-concatenation/REXX/array-concatenation.rexx b/Task/Array-concatenation/REXX/array-concatenation.rexx new file mode 100644 index 0000000000..bed9e4bebc --- /dev/null +++ b/Task/Array-concatenation/REXX/array-concatenation.rexx @@ -0,0 +1,21 @@ +-- 1 Jun 2025 +include Settings + +say 'ARRAY CONCATENATION' +say version +say +say 'Two numbered arrays concatenated...' +a.1=1; a.2=4; a.3=9 +b.1=16; b.2=25; b.3=36 +a.0=3; b.0=3 +j=a.0 +do i = 1 to 3 + j=j+1; a.j=b.i +end +a.0=j +do i = 1 to a.0 + say i a.i +end +exit + +include Abend diff --git a/Task/Array-length/Ballerina/array-length.ballerina b/Task/Array-length/Ballerina/array-length.ballerina new file mode 100644 index 0000000000..527b36cba6 --- /dev/null +++ b/Task/Array-length/Ballerina/array-length.ballerina @@ -0,0 +1,6 @@ +import ballerina/io; + +public function main() { + string[2] fruits = ["apple", "orange"]; + io:println(fruits.length()); +} diff --git a/Task/Array-length/Uxntal/array-length.uxnatl b/Task/Array-length/Uxntal/array-length.uxnatl new file mode 100644 index 0000000000..8eea52095c --- /dev/null +++ b/Task/Array-length/Uxntal/array-length.uxnatl @@ -0,0 +1,18 @@ +%\0 { 00 } +%DBG { [ LIT2 01 -System/debug ] DEO } + +|0e @System/debug + +|100 + +;array len-arr DBG + +BRK + +@len-arr ( {array}* -- length* ) + LDA2k SWP2 INC2 INC2 SUB2 #01 SFT2 + JMP2r + +@array ={ =apple =orange } +@apple "apple \0 +@orange "orange \0 diff --git a/Task/Arrays/Ballerina/arrays.ballerina b/Task/Arrays/Ballerina/arrays.ballerina new file mode 100644 index 0000000000..4ee9e82094 --- /dev/null +++ b/Task/Arrays/Ballerina/arrays.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +public function main() { + // fixed length array + int[4] a = [1, 4, 9, 16]; + // retrieve and print element at index 1 (zero indexing) + io:println(a[1]); + + // dynamic array + int[] b = []; + // push an element into it + b.push(42); + // retrieve and print last element added + io:println(b[b.length() - 1]); +} diff --git a/Task/Arrays/EasyLang/arrays.easy b/Task/Arrays/EasyLang/arrays.easy index a501a7a5e3..e336b8b6d3 100644 --- a/Task/Arrays/EasyLang/arrays.easy +++ b/Task/Arrays/EasyLang/arrays.easy @@ -1,8 +1,4 @@ len f[] 4 -for i = 1 to len f[] - f[i] = i -. -f[] &= 5 -for i = 1 to len f[] - print f[i] -. +for i = 1 to len f[] : f[i] = i +f[] &= 55 +print f[] diff --git a/Task/Arrays/Excel/arrays-1.excel b/Task/Arrays/Excel/arrays-1.excel new file mode 100644 index 0000000000..c183eeacbf --- /dev/null +++ b/Task/Arrays/Excel/arrays-1.excel @@ -0,0 +1,15 @@ +=LET( + ARRAY, LAMBDA(dim, [init], LET( + Y, LAMBDA(SELF, arr, + LAMBDA([a], [b], + IF(ISOMITTED(b), + INDEX(arr, a), + SELF(SELF, IF(SEQUENCE(ROWS(arr)) = a, b, arr)) + ) + ) + ), + Y(Y, IF(SEQUENCE(dim), IF(ISOMITTED(init), "", init))) + )), + my_arr, ARRAY(5, 0), + ... + ) diff --git a/Task/Arrays/Excel/arrays-2.excel b/Task/Arrays/Excel/arrays-2.excel new file mode 100644 index 0000000000..98da06bedd --- /dev/null +++ b/Task/Arrays/Excel/arrays-2.excel @@ -0,0 +1 @@ + new_arr, my_arr(1, "val1")(4, "val4") diff --git a/Task/Arrays/Excel/arrays-3.excel b/Task/Arrays/Excel/arrays-3.excel new file mode 100644 index 0000000000..19305e3c6e --- /dev/null +++ b/Task/Arrays/Excel/arrays-3.excel @@ -0,0 +1,16 @@ +=LET( + ARRAY, LAMBDA(dim, [init], LET( + Y, LAMBDA(SELF, arr, + LAMBDA([a], [b], + IF(ISOMITTED(b), + INDEX(arr, a), + SELF(SELF, IF(SEQUENCE(ROWS(arr)) = a, b, arr)) + ) + ) + ), + Y(Y, IF(SEQUENCE(dim), IF(ISOMITTED(init), "", init))) + )), + my_arr, ARRAY(5, 0), + new_arr, my_arr(1, "val1")(4, "val4"), + new_arr() + ) diff --git a/Task/Arrays/OPL/arrays.opl b/Task/Arrays/OPL/arrays.opl new file mode 100644 index 0000000000..74a007f56c --- /dev/null +++ b/Task/Arrays/OPL/arrays.opl @@ -0,0 +1,9 @@ +PROC main: + REM Declare an integer array of 10 elements and a string array of 10 elements, each up to 12 characters long. + LOCAL array1%(10),array2$(10,12) + REM Array element count starts at 1. + array1%(1)=128 + array2$(10)="Rosetta Code" + PRINT array1%(1),array2$(10) + GET +ENDP diff --git a/Task/Arrays/REXX/arrays-1.rexx b/Task/Arrays/REXX/arrays-1.rexx deleted file mode 100644 index d3a6e4d897..0000000000 --- a/Task/Arrays/REXX/arrays-1.rexx +++ /dev/null @@ -1,9 +0,0 @@ -/*REXX program demonstrates a simple array usage. */ -a.='not found' /*value for all a.xxx (so far).*/ - do j=1 to 100 /*start at 1, define 100 elements*/ - a.j=-j*1000 /*define as negative J thousand. */ - end /*j*/ /*the above defines 100 elements.*/ - -say 'element 50 is:' a.50 -say 'element 3000 is:' a.3000 - /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays-2.rexx b/Task/Arrays/REXX/arrays-2.rexx deleted file mode 100644 index 83f0292649..0000000000 --- a/Task/Arrays/REXX/arrays-2.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*REXX program demonstrates array usage with mimicry. */ -a. = 'not found' /*value for all a.xxx (so far). */ - do j=1 to 100 /*start at 1, define 100 elements*/ - a.j = -j * 100 /*define element as -J hundred. */ - end /*j*/ /*the above defines 100 elements.*/ - -say 'element 50 is:' a(50) -say 'element 3000 is:' a(3000) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────A subroutine────────────────────────*/ -a: _a_ = arg(1); return a._a_ diff --git a/Task/Arrays/REXX/arrays-3.rexx b/Task/Arrays/REXX/arrays-3.rexx deleted file mode 100644 index cbcaccf54b..0000000000 --- a/Task/Arrays/REXX/arrays-3.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*REXX program demonstrates array usage with mimicry. */ -a. = 00 /*value for all a.xxx (so far). */ - do j=1 to 100 /*start at 1, define 100 elements*/ - a.j = -j * 100 /*define element as -J hundred. */ - end /*j*/ /*the above defines 100 elements.*/ - -say 'element 50 is:' a(50) -say 'element 3000 is:' a(3000) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────A subroutine────────────────────────*/ -a: _a_ = arg(1); return a._a_ diff --git a/Task/Arrays/REXX/arrays-4.rexx b/Task/Arrays/REXX/arrays-4.rexx deleted file mode 100644 index 6f976ce2ad..0000000000 --- a/Task/Arrays/REXX/arrays-4.rexx +++ /dev/null @@ -1,10 +0,0 @@ -/*REXX program demonstrates array usage (with elements out-of-range).*/ -array. = 'out of range' /*define ALL elements to this. */ - - do j=-3000 to 3000 /*start at -3k, going up to +3k.*/ - array.j=j**2 /*define element as its square. */ - end /*j*/ /* [↑] defines 6,001 elements. */ -g=-7 -say g "squared is:" array.g -say 7000 "squared is:" array.7000 - /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays-5.rexx b/Task/Arrays/REXX/arrays-5.rexx deleted file mode 100644 index 9daf6ca54b..0000000000 --- a/Task/Arrays/REXX/arrays-5.rexx +++ /dev/null @@ -1,17 +0,0 @@ -/*REXX program demonstrates disjointed array usage. */ -yr. = 'year not supported' /*value for all yr.xxx (so far).*/ - - do k=600 to 1100 /*a bunch of years prior to 1800.*/ - yr.k=k "AD" /*Kth element as the year itself.*/ - end /*k*/ /* [↑] defines 501 elements.*/ - - do j=1800 to 2100 /*start at 1800, define a bunch. */ - yr.j=j 'AD' /*Jth element as the year itself.*/ - end /*j*/ /* [↑] defines 301 elements.*/ - -year=1946 -say 'DOB' year "is:" yr.year - -year=1744 -say 'DOB' year "is:" yr.year - /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays-6.rexx b/Task/Arrays/REXX/arrays-6.rexx deleted file mode 100644 index 0d2e52addd..0000000000 --- a/Task/Arrays/REXX/arrays-6.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program demonstrates array usage: sparse and disjointed. */ - yyy = -55 /*REXX must use this mechanism···*/ -a.yyy = 1e9 /*··· when assigning neg indices.*/ - -a.1 = 1000 -a.2 = 2000.0001 -a.7 = 7000 -a.2012 = 'out here in left field.' -a.cat = 'civet, but not a true cat ─── belonging to the family Viverridae' -a.civet = "A.K.A.: toddycats" -/*┌────────────────────────────────────────────────────────────────────┐ - │ Array elements need not be continuous (nor even defined). They │ - │ can hold any manner of numbers, or strings (which can include any │ - │ characters, including null or '00'x characters). │ - │ │ - │ Array elements need not be numeric, as the above code demonstrates.│ - │ Indeed, the element "name" can be ANYTHING, even non-displayable │ - │ characters. To illustrate [↓]: │ - └────────────────────────────────────────────────────────────────────┘*/ -stuff=')g.u.t.s( or ½ of an intestine!' -a.stuff=44 -/*┌────────────────────────────────────────────────────────────────────┐ - │ where the element name has special characters: blanks, and the │ - │ glyph of one-half (½), as well as the symbol used in REXX to │ - │ identify stemmed arrays (the period). │ - └────────────────────────────────────────────────────────────────────┘*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Arrays/REXX/arrays.rexx b/Task/Arrays/REXX/arrays.rexx new file mode 100644 index 0000000000..74e20f3ddc --- /dev/null +++ b/Task/Arrays/REXX/arrays.rexx @@ -0,0 +1,67 @@ +-- 1 Jun 2025 +include Settings + +say 'ARRAYS' +say version +say +say 'A simple array...' +do i = 1 to 100 + a.i=i*i +end +say 'Square of' 5 'is' a.5 +say 'Square of' 55 'is' a.55 +say +say 'Mimic indexing...' +say 'Square of' 5 'is' a(5) +say 'Square of' 55 'is' a(55) +say +say 'A default value...' +b. = 'Out of range' +do i = 1 to 100 + b.i=1/i +end +say 'Inverse of' 5 'is' b.5 +say 'Inverse of' 55 'is' b.55 +say 'Inverse of' 555 'is' b.555 +say +say 'An other index range...' +do i = -100 to 100 + c.i=i*i*i +end +j=-55; say 'Cube of' j 'is' c.j +j=-5; say 'Cube of' j 'is' c.j +j=5; say 'Cube of' j 'is' c.j +j=55; say 'Cube of' j 'is' c.j +say +say 'A sparse array...' +d.='Not calculated' +do i = 2 by 2 to 100 + d.i=-i +end +say 'Negative of' 55 'is' d.55 +say 'Negative of' 56 'is' d.56 +say +say 'Special indices...' +e.cat='civet'; say 'e.cat =' e.cat +a1='dog'; e.a1='pitbull' +a2=a1; say 'e.'a2 '=' e.a2 +a1='x.y.z'; e.a1='periods' +a2=a1; say 'e.'a2 '=' e.a2 +a1='x y z'; e.a1='spaces' +a2=a1; say 'e.'a2 '=' e.a2 +a1='└┴┬├─┼'; e.a1='specials' +a2=a1; say 'e.'a2 '=' e.a2 +say +say 'Element has no value...' +signal off novalue +say 'f.notassigned =' f.notassigned +signal on novalue name Abend +say 'f.notassigned =' f.notassigned +exit + +A: +procedure expose a. +arg xx +return a.xx + +include Abend diff --git a/Task/Arrays/Tcl/arrays-1.tcl b/Task/Arrays/Tcl/arrays-1.tcl index 9d450d0cad..2c767014ca 100644 --- a/Task/Arrays/Tcl/arrays-1.tcl +++ b/Task/Arrays/Tcl/arrays-1.tcl @@ -1,8 +1,11 @@ -set ary {} +# empty list +set arr {} -lappend ary 1 -lappend ary 3 +# 10 integers +set arr [list 1 2 3 4 5 6 7 8 9 10 ] -lset ary 0 2 -puts [lindex $ary 0] +lappend arr 11 +lappend arr 12 + +puts stdout "$arr" diff --git a/Task/Arrays/Tcl/arrays-2.tcl b/Task/Arrays/Tcl/arrays-2.tcl index 89bc0d8cab..b899713d2a 100644 --- a/Task/Arrays/Tcl/arrays-2.tcl +++ b/Task/Arrays/Tcl/arrays-2.tcl @@ -1 +1,8 @@ -puts $ary; # Print the whole array +set x [lindex $arr 4] ; # x <= 5 + +foreach n $arr { + set idx [expr n -1] + lset arr $idx [expr $n * $n] +} + +puts stdout "$arr" diff --git a/Task/Arrays/Tcl/arrays-3.tcl b/Task/Arrays/Tcl/arrays-3.tcl new file mode 100644 index 0000000000..0348b27759 --- /dev/null +++ b/Task/Arrays/Tcl/arrays-3.tcl @@ -0,0 +1,2 @@ +set slice [lrange $arr 5 10] +puts stdout "$slice" diff --git a/Task/Arrays/Tcl/arrays-4.tcl b/Task/Arrays/Tcl/arrays-4.tcl new file mode 100644 index 0000000000..fb66cb8f7d --- /dev/null +++ b/Task/Arrays/Tcl/arrays-4.tcl @@ -0,0 +1,2 @@ +puts stdout "arr has [llength $arr] items." +puts stdout "slice has [llength $slice] items." diff --git a/Task/Arrays/Tcl/arrays-5.tcl b/Task/Arrays/Tcl/arrays-5.tcl new file mode 100644 index 0000000000..12cd8f0080 --- /dev/null +++ b/Task/Arrays/Tcl/arrays-5.tcl @@ -0,0 +1,4 @@ +set r [lreverse $arr] +set s [lsort -integer $r] +puts stdout $r +puts stdout $s diff --git a/Task/Arrays/Tcl/arrays-6.tcl b/Task/Arrays/Tcl/arrays-6.tcl new file mode 100644 index 0000000000..57c697ab42 --- /dev/null +++ b/Task/Arrays/Tcl/arrays-6.tcl @@ -0,0 +1,10 @@ +set term "calico" +set fd [open "cats.txt" "r"] +set contents [read $fd] +set lines [split $contents "\n"] + +foreach line $lines { + if { [lsearch $line $term] > 0 } { + puts "found $term in \"$line\"" + } +} diff --git a/Task/Ascending-primes/Ballerina/ascending-primes.ballerina b/Task/Ascending-primes/Ballerina/ascending-primes.ballerina new file mode 100644 index 0000000000..0134c472ca --- /dev/null +++ b/Task/Ascending-primes/Ballerina/ascending-primes.ballerina @@ -0,0 +1,38 @@ +import ballerina/io; + +function isPrime(int n) returns boolean { + if n < 2 { return false; } + if n % 2 == 0 { return n == 2; } + if n % 3 == 0 { return n == 3; } + int d = 5; + while d * d <= n { + if n % d == 0 { return false; } + d += 2; + if n % d == 0 { return false; } + d += 4; + } + return true; +} + +map ascPrimesSet = {}; // value will always be 1 to simulate a set + +function generate(int first, int cand, int digits) { + if digits == 0 { + if isPrime(cand) { ascPrimesSet[cand.toString()] = 1; } + return; + } + foreach int i in first...9 { + int next = cand * 10 + i; + generate(i + 1, next, digits - 1); + } +} + +public function main() returns error? { + foreach int digits in 1...9 { generate(1, 0, digits); } + int[] ascPrimes = ascPrimesSet.keys().map(k => check int:fromString(k)).sort(); + io:println("There are ", ascPrimes.length(), " ascending primes, namely:"); + foreach int i in 0 ..< ascPrimes.length() { + io:print(ascPrimes[i].toString().padStart(8), " "); + if (i + 1) % 10 == 0 { io:println(); } + } +} diff --git a/Task/Ascending-primes/EasyLang/ascending-primes.easy b/Task/Ascending-primes/EasyLang/ascending-primes.easy index 499d11769c..6f497f5811 100644 --- a/Task/Ascending-primes/EasyLang/ascending-primes.easy +++ b/Task/Ascending-primes/EasyLang/ascending-primes.easy @@ -1,25 +1,25 @@ -func isprim num . - if num < 2 - return 0 +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] . +. +func isprim num . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -proc nextasc n . . - if isprim n = 1 - write n & " " - . - if n > 123456789 - return - . +p[] = [ ] +proc nextasc n . + if isprim n = 1 : p[] &= n + if n > 123456789 : return for d = n mod 10 + 1 to 9 nextasc n * 10 + d . . nextasc 0 +sort p[] +print p[] diff --git a/Task/Ascending-primes/Rust/ascending-primes-1.rs b/Task/Ascending-primes/Rust/ascending-primes-1.rs new file mode 100644 index 0000000000..1342be405e --- /dev/null +++ b/Task/Ascending-primes/Rust/ascending-primes-1.rs @@ -0,0 +1,36 @@ +/// Call depth-first recursive function to generate increasing sizes of powerset integers whose +/// digits are strictly increasing. +/// +/// We then apply a primality test to each number (512 primality tests in total) +fn powerset_from_recursion() -> Vec { + let ps = powerset(123456789); + + ps.into_iter().filter(|n| is_prime(*n)).collect() +} + +/// Depth-first powerset integers generated through passed-in digits in base-10 +/// +/// Each returning `powerset` doubles its size, incorporating a new digit through each pass +/// +/// Ex: `rem = 3` and our `powerset = [0, 1, 2, 12]` +/// +/// `3` is "pushed back" to each value +/// +/// `[03, 13, 23, 123]` +/// +/// Which is then appended to the back of the original `powerset` +fn powerset(digits: u32) -> Vec { + let (rem, quo) = (digits % 10, digits / 10); + + // Base case + if rem == 0 { + // Having 0 allows adding `rem` as single digit to `new` + return vec![0]; + } + + let mut powerset = powerset(quo); + let new = powerset.clone().into_iter().map(|n| n * 10 + rem); + powerset.extend(new); + + powerset +} diff --git a/Task/Ascending-primes/Rust/ascending-primes-2.rs b/Task/Ascending-primes/Rust/ascending-primes-2.rs new file mode 100644 index 0000000000..798985fc37 --- /dev/null +++ b/Task/Ascending-primes/Rust/ascending-primes-2.rs @@ -0,0 +1,30 @@ +/// Uses a queue to calculate and store the next integer sequences to generate. +/// +/// The next sequence has the next power of 10 generated in lock-step from the front value +/// +/// Ex: `[1, 2, 3, 4, 5, 6, 7, 8, 9]` +/// +/// The front value `1` produces the next sequence +/// +/// `[12, 13, 14, 15, 16, 17, 18, 19]` +/// +/// Which is then appended to the back of the queue +/// +/// Due to the nature of this algorithm, no sorting is required but iteration is implemented in a +/// more procedural style +fn powerset_from_queue() -> Vec { + let mut dq = std::collections::VecDeque::from_iter(1..=9); + let mut primes = Vec::new(); + + while let Some(n) = dq.pop_front() { + if is_prime_v(n) { + primes.push(n); + } + + for rem in (n % 10 + 1)..=9 { + dq.push_back(n * 10 + rem); + } + } + + primes +} diff --git a/Task/Ascending-primes/Rust/ascending-primes-3.rs b/Task/Ascending-primes/Rust/ascending-primes-3.rs new file mode 100644 index 0000000000..e1a6b68a8b --- /dev/null +++ b/Task/Ascending-primes/Rust/ascending-primes-3.rs @@ -0,0 +1,43 @@ +/// Primality test by trial division. +/// +/// This algorithm avoids using hardware `div`s for 0-24 and from then on only checks with odd +/// factors that aren't themselves divisible by 3 up until √n +fn is_prime(n: u32) -> bool { + match n { + 0 | 1 => false, + _ if n % 2 == 0 => n == 2, + _ if n % 3 == 0 => n == 3, + _ => { + let mut factor = 5; + while factor * factor <= n { + if n % factor == 0 { + return false; + } + factor += 2; + if n % factor == 0 { + return false; + } + factor += 4; + } + + true + } + } +} + +fn main() { + let mut ps1 = powerset_from_recursion(); + let ps2 = powerset_from_queue(); + + ps1.sort(); + + assert_eq!(ps1, ps2); + + println!("There are {} ascending primes.", ps2.len()); + for row in ps2.chunks(10) { + for col in row { + print!("{:>9} ", col); + } + println!(); + } +} diff --git a/Task/Associative-array-Creation/Ballerina/associative-array-creation.ballerina b/Task/Associative-array-Creation/Ballerina/associative-array-creation.ballerina new file mode 100644 index 0000000000..6561149822 --- /dev/null +++ b/Task/Associative-array-Creation/Ballerina/associative-array-creation.ballerina @@ -0,0 +1,22 @@ +import ballerina/io; + +public function main() { + map fruit = {}; // creates an empty map + fruit["1"] = "orange"; // associates a key of "1" with "orange" + fruit["2"] = "apple"; // associates a key of "2" with "apple" + io:println(fruit["1"]); // retrieves the value with a key of "1" and prints it out + _ = fruit.remove("1"); // removes the entry with a key of "1" from the map + io:println(fruit); // prints the rest of the map + io:println(); + map capitals = { // creates a new map with three entries + "France": "Paris", + "Germany": "Berlin", + "Spain": "Madrid" + }; + capitals["Russia"] = "Moscow"; // adds another entry + io:println(capitals["France"]); // retrieves the "France" entry and prints out its capital + _ = capitals.remove("France"); // removes the "France" entry + io:println(capitals); // prints all remaining entries + io:println(capitals.length()); // prints the number of remaining entries + io:println(capitals["Sweden"]); // prints the entry for Sweden (nothing as there isn't one) +} diff --git a/Task/Associative-array-Creation/EasyLang/associative-array-creation.easy b/Task/Associative-array-Creation/EasyLang/associative-array-creation.easy index 5753f9d6ac..17858cd138 100644 --- a/Task/Associative-array-Creation/EasyLang/associative-array-creation.easy +++ b/Task/Associative-array-Creation/EasyLang/associative-array-creation.easy @@ -1,25 +1,22 @@ # use array of array for this -proc hashGet ind$ . ar$[][] item$ . - for i to len ar$[][] - if ar$[i][1] = ind$ - item$ = ar$[i][2] - return - . +func$ hget &arr$[][] ind$ . + for i to len arr$[][] + if arr$[i][1] = ind$ : return arr$[i][2] . - item$ = "" + return "" . -proc hashSet ind$ val$ . ar$[][] . - for i to len ar$[][] - if ar$[i][1] = ind$ - ar$[i][2] = val$ +proc hset &arr$[][] ind$ val$ . + for i to len arr$[][] + if arr$[i][1] = ind$ + arr$[i][2] = val$ return . . - ar$[][] &= [ ind$ val$ ] + arr$[][] &= [ ind$ val$ ] . clothing$[][] = [ [ "type" "t-shirt" ] [ "color" "red" ] ] clothing$[][] &= [ "size" "xl" ] # -hashSet "color" "green" clothing$[][] -hashGet "color" clothing$[][] col$ -print col$ +print hget clothing$[][] "color" +hset clothing$[][] "color" "green" +print hget clothing$[][] "color" diff --git a/Task/Associative-array-Iteration/Ballerina/associative-array-iteration.ballerina b/Task/Associative-array-Iteration/Ballerina/associative-array-iteration.ballerina new file mode 100644 index 0000000000..8281152635 --- /dev/null +++ b/Task/Associative-array-Iteration/Ballerina/associative-array-iteration.ballerina @@ -0,0 +1,22 @@ +import ballerina/io; + +public function main() { + // create a new map with four entries + map capitals = { + "France": "Paris", + "Germany": "Berlin", + "Russia": "Moscow", + "Spain": "Madrid" + }; + + // iterate through the map and print out the key/value pairs + foreach var e in capitals.entries() { io:println(e); } + io:println(); + + // iterate though the map and print out just the keys + foreach var k in capitals.keys() { io:println(k); } + io:println(); + + // iterate through the map and print out just the values + foreach var v in capitals { io:println(v); } +} diff --git a/Task/Associative-array-Merging/Ballerina/associative-array-merging.ballerina b/Task/Associative-array-Merging/Ballerina/associative-array-merging.ballerina new file mode 100644 index 0000000000..5f836afb1f --- /dev/null +++ b/Task/Associative-array-Merging/Ballerina/associative-array-merging.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +function mergeMaps(map m1, map m2) returns map { + map m3 = {}; + foreach string key in m1.keys() { m3[key] = m1.get(key); } + foreach string key in m2.keys() { m3[key] = m2.get(key); } + return m3; +} + +public function main() { + map base = { "name": "Rocket Skates" , "price": 12.75, "color": "yellow" }; + map update = { "price": 15.25, "color": "red", "year": 1974 }; + map merged = mergeMaps(base, update); + io:println(re `,`.replaceAll(merged.toString(), ", ")); +} diff --git a/Task/Associative-array-Merging/Common-Lisp/associative-array-merging-3.lisp b/Task/Associative-array-Merging/Common-Lisp/associative-array-merging-3.lisp new file mode 100644 index 0000000000..f39c68a072 --- /dev/null +++ b/Task/Associative-array-Merging/Common-Lisp/associative-array-merging-3.lisp @@ -0,0 +1,28 @@ +(defun merge-hash-tables (hashtable &rest other-hashtables) + (let ((result (make-hash-table :test (hash-table-test hashtable)))) + (dolist (ht (list* hashtable other-hashtables)) + (maphash #'(lambda (k v) (setf (gethash k result) v)) ht)) + result)) + +;; aux functions +(defun make-hash-table-from-alist (alist &key (test 'equal)) + (let ((result (make-hash-table :test test))) + (loop for (k . v) in alist + do (setf (gethash k result) v)) + result)) +(defun make-alist-from-hash-table (hashtable) + (let ((result ())) + (maphash #'(lambda (k v) (setf result (acons k v result))) hashtable) + (nreverse result))) + +;; solving the task +(let ((base (make-hash-table-from-alist '(("name" . "Rocket Skates") + ("price" . 12.75) + ("color" . "yellow")))) + (update (make-hash-table-from-alist '(("price" . 15.25) + ("color" . "red") + ("year" . 1974))))) + (format t "base: ~a~%update: ~a~%merged: ~a~%" + (make-alist-from-hash-table base) + (make-alist-from-hash-table update) + (make-alist-from-hash-table (merge-hash-tables base update)))) diff --git a/Task/Associative-array-Merging/EasyLang/associative-array-merging.easy b/Task/Associative-array-Merging/EasyLang/associative-array-merging.easy index 7c929e84fc..9f95724e21 100644 --- a/Task/Associative-array-Merging/EasyLang/associative-array-merging.easy +++ b/Task/Associative-array-Merging/EasyLang/associative-array-merging.easy @@ -1,6 +1,6 @@ base$[][] = [ [ "name" "Rocket Skates" ] [ "price" 12.75 ] [ "color" "yellow" ] ] update$[][] = [ [ "price" 15.25 ] [ "color" "red" ] [ "year" 1974 ] ] -proc update . a$[][] b$[][] . +proc update &a$[][] &b$[][] . for b to len b$[][] for a to len a$[][] if a$[a][1] = b$[b][1] @@ -8,9 +8,7 @@ proc update . a$[][] b$[][] . break 1 . . - if a > len a$[][] - a$[][] &= b$[b][] - . + if a > len a$[][] : a$[][] &= b$[b][] . . update base$[][] update$[][] diff --git a/Task/Associative-array-Merging/JavaScript/associative-array-merging.js b/Task/Associative-array-Merging/JavaScript/associative-array-merging.js index 763232ea62..93ff25c9ef 100644 --- a/Task/Associative-array-Merging/JavaScript/associative-array-merging.js +++ b/Task/Associative-array-Merging/JavaScript/associative-array-merging.js @@ -1,18 +1,19 @@ -(() => { - 'use strict'; +const base = { + "name": "Rocket Skates", + "price": 12.75, + "color": "yellow" +}; - console.log(JSON.stringify( - Object.assign({}, // Fresh dictionary. - { // Base. - "name": "Rocket Skates", - "price": 12.75, - "color": "yellow" - }, { // Update. - "price": 15.25, - "color": "red", - "year": 1974 - } - ), - null, 2 - )) -})(); +const update = { + "price": 15.25, + "color": "red", + "year": 1974 +}; + +// While ES6 destructuring may be cleaner, using Object.assign (provided in the original answer) instead is about 15-20% faster. +// source: https://jsbench.me/jom7uh9o1t/1 + +const final = Object.assign(base, update); +// Using ES6 destructuring method: const final = { ...base, ...update }; + +console.log(JSON.stringify(final, null, 4)); diff --git a/Task/Attractive-numbers/EasyLang/attractive-numbers.easy b/Task/Attractive-numbers/EasyLang/attractive-numbers.easy index 6128796beb..b4f08ed64a 100644 --- a/Task/Attractive-numbers/EasyLang/attractive-numbers.easy +++ b/Task/Attractive-numbers/EasyLang/attractive-numbers.easy @@ -1,12 +1,8 @@ func isprim num . - if num < 2 - return 0 - . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 @@ -26,7 +22,5 @@ func count n . . for i = 2 to 120 n = count i - if isprim n = 1 - write i & " " - . + if isprim n = 1 : write i & " " . diff --git a/Task/Attractive-numbers/OCaml/attractive-numbers.ml b/Task/Attractive-numbers/OCaml/attractive-numbers.ml new file mode 100644 index 0000000000..ea8520abef --- /dev/null +++ b/Task/Attractive-numbers/OCaml/attractive-numbers.ml @@ -0,0 +1,26 @@ +let is_prime (n : int) : bool = + if n = 2 then true else if n < 2 || n mod 2 = 0 then false else + let lim = (n |> float_of_int |> sqrt |> int_of_float) + 1 in + let rec loop = function + | i when i > lim -> true + | i when n mod i = 0 -> false + | i -> loop (i + 2) + in loop 3 + +let prime_factors (n : int) : int list = + let rec loop = function + | factors, i, r when r = 1 -> factors + | factors, i, r when is_prime i && r mod i = 0 + -> loop (i :: factors, i, r / i) + | factors, i, r -> loop (factors, i+1, r) + in loop ([], 2, n) + +let is_attractive (n : int) : bool = + n |> prime_factors |> List.length |> is_prime + +let () = + List.init 120 ((+) 1) + |> List.filter is_attractive + |> List.map string_of_int + |> String.concat "," + |> Printf.printf "[%s]" diff --git a/Task/Attractive-numbers/PARI-GP/attractive-numbers-1.parigp b/Task/Attractive-numbers/PARI-GP/attractive-numbers-1.parigp new file mode 100644 index 0000000000..73068e2021 --- /dev/null +++ b/Task/Attractive-numbers/PARI-GP/attractive-numbers-1.parigp @@ -0,0 +1 @@ +select(n->isprime(bigomega(n)), [1..120]) diff --git a/Task/Attractive-numbers/PARI-GP/attractive-numbers-2.parigp b/Task/Attractive-numbers/PARI-GP/attractive-numbers-2.parigp new file mode 100644 index 0000000000..0a6b81ede0 --- /dev/null +++ b/Task/Attractive-numbers/PARI-GP/attractive-numbers-2.parigp @@ -0,0 +1 @@ +forfactored(n=1,120, if(isprime(bigomega(n)), print1(n[1]", "))) diff --git a/Task/Average-loop-length/EasyLang/average-loop-length.easy b/Task/Average-loop-length/EasyLang/average-loop-length.easy index 664aba7a05..a0d216ea9d 100644 --- a/Task/Average-loop-length/EasyLang/average-loop-length.easy +++ b/Task/Average-loop-length/EasyLang/average-loop-length.easy @@ -1,9 +1,7 @@ func average n reps . for r to reps f[] = [ ] - for i to n - f[] &= random n - . + for i to n : f[] &= random n seen[] = [ ] len seen[] n x = 1 @@ -30,8 +28,8 @@ for n to 20 avg = average n 1e6 ana = analytical n err = (avg - ana) / ana * 100 - numfmt 0 2 + numfmt 2 0 write n - numfmt 4 9 + numfmt 9 4 print avg & ana & err & "%" . diff --git a/Task/Average-loop-length/JavaScript/average-loop-length.js b/Task/Average-loop-length/JavaScript/average-loop-length.js new file mode 100644 index 0000000000..68e1ae0b93 --- /dev/null +++ b/Task/Average-loop-length/JavaScript/average-loop-length.js @@ -0,0 +1,49 @@ +const MAX_N = 20 +const TIMES = 1000000 + +function factorial(n) { + let prod = 1; + for (let i = n; i > 1; i--) { + prod *= i; + } + return prod; +} + +function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min + 1)) + min; +} + + +function analytical(n) { + let items = []; + + for (let i = 1; i < n+1; i++) { + items.push(factorial(n) / Math.pow(n, i) / factorial(n - i)); + } + + return items.reduce((p, v) => p + v, 0); +} + +function test(n, times) { + let count = 0; + for (let i = 0; i < times; i++) { + let x = 1, bits = 0; + + while (!(bits & x)) { + count += 1; + bits |= x; + x = 1 << getRandomInt(0, n-1); + } + } + return count / times; +} + +console.log(" n\tavg\texp.\tdiff\n-------------------------------"); +for(let n = 1; n < MAX_N+1; n++) { + const avg = test(n, TIMES); + const theory = analytical(n); + const diff = (avg / theory - 1) * 100; + console.log(`${n.toString().padStart(2)} ${avg.toFixed(4).padStart(8)} ${theory.toFixed(4).padStart(8)} ${diff.toFixed(3).padStart(6)}%`); +} diff --git a/Task/Averages-Arithmetic-mean/Ballerina/averages-arithmetic-mean.ballerina b/Task/Averages-Arithmetic-mean/Ballerina/averages-arithmetic-mean.ballerina new file mode 100644 index 0000000000..cc6dc8d288 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Ballerina/averages-arithmetic-mean.ballerina @@ -0,0 +1,22 @@ +import ballerina/io; + +function average(decimal[] a) returns decimal { + decimal sum = 0; + if a.length() == 0 { return 0d; } + foreach decimal i in a { sum += i; } + return sum / a.length(); +} + +public function main() { + // fixed length array + decimal[6] a = [1, 2, 3, 4, 5, 6]; + io:println(decimal:avg(...a)); + + // variable length array + decimal[] b = a; + io:println(average(b)); + + // empty variable length array + decimal[] c = []; + io:println(average(c)); +} diff --git a/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy b/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy index e14e43c02e..4e9bb83c20 100644 --- a/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy +++ b/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy @@ -1,9 +1,6 @@ -proc mean . f[] r . - for i = 1 to len f[] - s += f[i] - . - r = s / len f[] +func mean &f[] . + for i = 1 to len f[] : s += f[i] + return s / len f[] . f[] = [ 1 2 3 4 5 6 7 8 ] -mean f[] r -print r +print mean f[] diff --git a/Task/Averages-Mean-angle/Ballerina/averages-mean-angle.ballerina b/Task/Averages-Mean-angle/Ballerina/averages-mean-angle.ballerina new file mode 100644 index 0000000000..c654d6721f --- /dev/null +++ b/Task/Averages-Mean-angle/Ballerina/averages-mean-angle.ballerina @@ -0,0 +1,27 @@ +import ballerina/io; + +function meanAngle(float[] angles) returns float { + int n = angles.length(); + float sinSum = 0.0; + float cosSum = 0.0; + foreach float angle in angles { + float radians = angle * float:PI / 180.0; + sinSum += radians.sin(); + cosSum += radians.cos(); + } + return float:atan2(sinSum / n, cosSum / n) * 180.0 / float:PI; +} + +public function main() { + var angles = [ + [350.0, 10.0], + [90.0, 180.0, 270.0, 360.0], + [10.0, 20.0, 30.0] + ]; + int i = 1; + foreach var a in angles { + string mean = meanAngle(a).round(1).toString().padStart(5); + io:println("Mean for angles ", i, " is : ", mean); + i += 1; + } +} diff --git a/Task/Averages-Mean-time-of-day/Ballerina/averages-mean-time-of-day.ballerina b/Task/Averages-Mean-time-of-day/Ballerina/averages-mean-time-of-day.ballerina new file mode 100644 index 0000000000..382b905a35 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Ballerina/averages-mean-time-of-day.ballerina @@ -0,0 +1,42 @@ +import ballerina/io; + +function timeToDegs(string time) returns float|error { + var t = re `:`.split(time); + int h = check int:fromString(t[0]) * 3600; + int m = check int:fromString(t[1]) * 60; + int s = check int:fromString(t[2]); + return (h + m + s) / 240.0; +} + +function padInt(int i, int len) returns string { + return i.toString().padZero(len); +} + +function degsToTime(float degs) returns string { + float d = degs; + while d < 0.0 { d = d + 360.0; } + int s = (d * 240.00).round(); + int h = s / 3600; + int m = s % 3600; + s = m % 60; + m /= 60; + return padInt(h, 2) + ":" + padInt(m, 2) + ":" + padInt(s, 2); +} + +function meanAngle(float[] angles) returns float { + int n = angles.length(); + float sinSum = 0.0; + float cosSum = 0.0; + foreach float angle in angles { + float radians = angle * float:PI / 180.0; + sinSum += radians.sin(); + cosSum += radians.cos(); + } + return float:atan2(sinSum / n, cosSum / n) * 180.0 / float:PI; +} + +public function main() returns error? { + var times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"]; + var angles = times.map(t => check timeToDegs(t)); + io:println("Mean time of day is : ", degsToTime(meanAngle(angles))); +} diff --git a/Task/Averages-Median/Ballerina/averages-median.ballerina b/Task/Averages-Median/Ballerina/averages-median.ballerina new file mode 100644 index 0000000000..7b24c1ffa5 --- /dev/null +++ b/Task/Averages-Median/Ballerina/averages-median.ballerina @@ -0,0 +1,20 @@ +import ballerina/io; + +function median(float[] floats) returns float { + var fs = floats.sort(); + int len = fs.length(); + if (len % 2 == 1) { + return fs[len / 2]; + } + return (fs[len / 2 - 1] + fs[len / 2]) / 2.0; +} + +public function main() { + float[][] lists = [ + [5.0, 3.0, 4.0], + [3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2] + ]; + foreach var list in lists { + io:println(median(list)); + } +} diff --git a/Task/Averages-Median/EasyLang/averages-median.easy b/Task/Averages-Median/EasyLang/averages-median.easy index 51e508db90..63c7dcaa3b 100644 --- a/Task/Averages-Median/EasyLang/averages-median.easy +++ b/Task/Averages-Median/EasyLang/averages-median.easy @@ -1,5 +1,4 @@ -proc quickselect k . list[] res . - # +func quickselect &list[] k . subr partition mid = left for i = left + 1 to right @@ -22,19 +21,16 @@ proc quickselect k . list[] res . left = right . . - res = list[k] + return list[k] . -proc median . list[] res . +func median &list[] . h = len list[] div 2 + 1 - quickselect h list[] res - if len list[] mod 2 = 0 - quickselect h - 1 list[] h - res = (res + h) / 2 - . + r1 = quickselect list[] h + if len list[] mod 2 = 1 : return r1 + r2 = quickselect list[] (h - 1) + return (r1 + r2) / 2 . test[] = [ 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ] -median test[] med -print med +print median test[] test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ] -median test[] med -print med +print median test[] diff --git a/Task/Averages-Mode/Ballerina/averages-mode.ballerina b/Task/Averages-Mode/Ballerina/averages-mode.ballerina new file mode 100644 index 0000000000..cfea56d7ed --- /dev/null +++ b/Task/Averages-Mode/Ballerina/averages-mode.ballerina @@ -0,0 +1,27 @@ +import ballerina/io; + +function mode(int[] arr) returns int[]|error { + map m = {}; + foreach int e in arr { + string k = e.toString(); + if !m.hasKey(k) { m[k] = 0; } + m[k] = m.get(k) + 1; + } + int max = int:MIN_VALUE; + int[] modes = []; + foreach string k in m.keys() { + int v = m.get(k); + if v > max { + max = v; + modes.removeAll(); + } + if v >= max { + modes.push(check int:fromString(k)); + } + } + return modes; +} + +public function main() { + io:println(mode([1, 2, 3, 4, 5, 5, 51, 2, 3])); +} diff --git a/Task/Averages-Mode/Crystal/averages-mode.cr b/Task/Averages-Mode/Crystal/averages-mode.cr new file mode 100644 index 0000000000..f8f01672a8 --- /dev/null +++ b/Task/Averages-Mode/Crystal/averages-mode.cr @@ -0,0 +1,6 @@ +def mode (seq) + seq.tally.group_by {|n, count| count }.max[1].map {|n, count| n } +end + +p mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]) +p mode([1, 1, 2, 4, 4]) diff --git a/Task/Averages-Mode/EasyLang/averages-mode.easy b/Task/Averages-Mode/EasyLang/averages-mode.easy index 5824a333b4..79a069b46a 100644 --- a/Task/Averages-Mode/EasyLang/averages-mode.easy +++ b/Task/Averages-Mode/EasyLang/averages-mode.easy @@ -1,4 +1,4 @@ -proc modes . in[] r[] . +proc modes &in[] &r[] . r[] = [ ] for v in in[] for i to len vals[] @@ -12,9 +12,7 @@ proc modes . in[] r[] . cnt[] &= 0 . for i to len cnt[] - if cnt[i] = max - r[] &= vals[i] - . + if cnt[i] = max : r[] &= vals[i] . . in[] = [ 1 3 6 6 6 6 7 7 12 12 17 ] diff --git a/Task/Averages-Pythagorean-means/Ballerina/averages-pythagorean-means.ballerina b/Task/Averages-Pythagorean-means/Ballerina/averages-pythagorean-means.ballerina new file mode 100644 index 0000000000..352cc79d99 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Ballerina/averages-pythagorean-means.ballerina @@ -0,0 +1,21 @@ +import ballerina/io; + +public function main() { + final int n = 10; + var arr = from int i in 1...n select i; + float len = arr.length(); + + var sum = function(float total, float next) returns float => total + next; + var prod = function(float total, float next) returns float => total * next; + var rsum = function(float total, float next) returns float => total + 1.0 / next; + + var am = arr.reduce(sum, 0.0) / len; + var gm = arr.reduce(prod, 1.0).pow(1.0 / len); + var hm = arr.reduce(rsum, 0.0).pow(-1.0) * len; + + io:println("For the numbers 1 to ", n, ":"); + io:println(" Arithmetic mean = ", am); + io:println(" Geometric mean = ", gm); + io:println(" Harmonic mean = ", hm); + io:println(" A >= G >= H = ", am >= gm && gm >= hm); +} diff --git a/Task/Averages-Pythagorean-means/Crystal/averages-pythagorean-means.cr b/Task/Averages-Pythagorean-means/Crystal/averages-pythagorean-means.cr new file mode 100644 index 0000000000..508bb911fb --- /dev/null +++ b/Task/Averages-Pythagorean-means/Crystal/averages-pythagorean-means.cr @@ -0,0 +1,24 @@ +module Mean + def self.arithmetic (seq) + seq.sum / seq.size + end + + def self.geometric (seq) + seq.product ** (1/seq.size) + end + + def self.harmonic (seq) + seq.size / seq.sum {|x| 1/x } + end +end + +seq = (1..10) + +a = Mean.arithmetic(seq) +g = Mean.geometric(seq) +h = Mean.harmonic(seq) + +puts "A = #{a}" +puts "G = #{g}" +puts "H = #{h}" +puts "A >= G >= H = #{a >= g >= h}" diff --git a/Task/Averages-Pythagorean-means/EasyLang/averages-pythagorean-means.easy b/Task/Averages-Pythagorean-means/EasyLang/averages-pythagorean-means.easy index 3c7c1af491..f9aa5a43e0 100644 --- a/Task/Averages-Pythagorean-means/EasyLang/averages-pythagorean-means.easy +++ b/Task/Averages-Pythagorean-means/EasyLang/averages-pythagorean-means.easy @@ -1,4 +1,4 @@ -proc mean . v[] a g h . +proc mean &v[] &a &g &h . prod = 1 for v in v[] sum += v diff --git a/Task/Averages-Root-mean-square/Ballerina/averages-root-mean-square.ballerina b/Task/Averages-Root-mean-square/Ballerina/averages-root-mean-square.ballerina new file mode 100644 index 0000000000..6253aff98f --- /dev/null +++ b/Task/Averages-Root-mean-square/Ballerina/averages-root-mean-square.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + int[] a = from int i in 1...10 select i; + var sumSq = function(int total, int i) returns int => total + i * i; + float rms = (a.reduce(sumSq, 0) / 10.0).sqrt(); + io:println(rms); +} diff --git a/Task/Averages-Simple-moving-average/Ballerina/averages-simple-moving-average.ballerina b/Task/Averages-Simple-moving-average/Ballerina/averages-simple-moving-average.ballerina new file mode 100644 index 0000000000..07c801246b --- /dev/null +++ b/Task/Averages-Simple-moving-average/Ballerina/averages-simple-moving-average.ballerina @@ -0,0 +1,33 @@ +import ballerina/io; + +function sma(int period) returns (function(float) returns float) { + int i = 0; + float sum = 0.0; + float[] storage = []; + + return function(float input) returns float { + if storage.length() < period { + sum += input; + storage.push(input); + } + sum += input - storage[i]; + storage[i] = input; + i = (i + 1) % period; + return sum / storage.length(); + }; +} + +function F(float f, int size, int prec) returns string { + string s = f.toFixedString(prec); + return size >= 0 ? s.padStart(size) : s.padEnd(size); +} + +public function main() { + var sma3 = sma(3); + var sma5 = sma(5); + io:println(" x sma3 sma5"); + float[] rng = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]; + foreach float x in rng { + io:println(`${F(x, 5, 3)} ${F(sma3(x), 5, 3)} ${F(sma5(x), 5, 3)}`); + } +} diff --git a/Task/Averages-Simple-moving-average/EasyLang/averages-simple-moving-average.easy b/Task/Averages-Simple-moving-average/EasyLang/averages-simple-moving-average.easy index e9bdc2bb67..7d437b97f3 100644 --- a/Task/Averages-Simple-moving-average/EasyLang/averages-simple-moving-average.easy +++ b/Task/Averages-Simple-moving-average/EasyLang/averages-simple-moving-average.easy @@ -23,7 +23,7 @@ prefix # sma5 = sma_new 5 sma3 = sma_new 3 -numfmt 2 4 +numfmt 4 2 for v in [ 1 2 3 4 5 5 4 3 2 1 ] print sma_get sma3 v & " " & sma_get sma5 v . diff --git a/Task/B-zier-curves-Intersections/Fortran/b-zier-curves-intersections.f b/Task/B-zier-curves-Intersections/Fortran/b-zier-curves-intersections.f new file mode 100644 index 0000000000..418fb69093 --- /dev/null +++ b/Task/B-zier-curves-Intersections/Fortran/b-zier-curves-intersections.f @@ -0,0 +1,286 @@ +program bezier_intersections + ! This program does not do any subdivision, but instead takes + ! advantage of monotonicity. + ! + ! It is possible for points accidentally to be counted twice, for + ! instance if they lie right on an interval boundary. We will avoid + ! that by the crude (but likely satisfactory) mechanism of requiring + ! a minimum max norm between intersections. + implicit none + + ! Constants + integer, parameter :: max_intersections = 4 + integer, parameter :: max_start_interv = 4 + integer, parameter :: max_workload = 1000 ! Maximum size for workload stack + double precision, parameter :: px0 = -1.0, px1 = 0.0, px2 = 1.0 + double precision, parameter :: py0 = 0.0, py1 = 10.0, py2 = 0.0 + double precision, parameter :: qx0 = 2.0, qx1 = -8.0, qx2 = 2.0 + double precision, parameter :: qy0 = 1.0, qy1 = 2.0, qy2 = 3.0 + double precision, parameter :: tol = 0.0000001 + double precision, parameter :: spacing = 100.0 * tol + + ! Variables + logical :: px_has_extreme_pt, py_has_extreme_pt + logical :: qx_has_extreme_pt, qy_has_extreme_pt + double precision :: px_extreme_pt, py_extreme_pt + double precision :: qx_extreme, qy_extreme + integer :: p_num_start_interv, q_num_start_interv + double precision :: p_start_interv(max_start_interv) + double precision :: q_start_interv(max_start_interv) + double precision :: workload(4, max_workload) ! tp0, tp1, tq0, tq1 + integer :: workload_size + integer :: num_intersections + double precision :: intersections_x(max_intersections) + double precision :: intersections_y(max_intersections) + integer :: i, j, k + double precision :: tp0, tp1, tq0, tq1 + double precision :: xp0, xp1, xq0, xq1 + double precision :: yp0, yp1, yq0, yq1 + logical :: exclude, accept + double precision :: x, y + double precision :: tp_middle, tq_middle + +! Main program logic + ! Find monotonic sections of the curves, and use those as the + ! starting jobs. + p_num_start_interv = 2 + p_start_interv(1) = 0.0 + p_start_interv(2) = 1.0 + call possibly_insert_extreme_point(px0, px1, px2, p_num_start_interv, p_start_interv) + call possibly_insert_extreme_point(py0, py1, py2, p_num_start_interv, p_start_interv) + q_num_start_interv = 2 + q_start_interv(1) = 0.0 + q_start_interv(2) = 1.0 + call possibly_insert_extreme_point(qx0, qx1, qx2, q_num_start_interv, q_start_interv) + call possibly_insert_extreme_point(qy0, qy1, qy2, q_num_start_interv, q_start_interv) + + workload_size = 0 + do i = 2, p_num_start_interv + do j = 2, q_num_start_interv + call defer_work(p_start_interv(i - 1), p_start_interv(i), & + q_start_interv(j - 1), q_start_interv(j)) + end do + end do + + ! Go through the workload, deferring work as necessary. + num_intersections = 0 + do while (.not. work_is_done()) + ! The following code recomputes values of the splines + ! sometimes. You may wish to store such values in the work pile, + ! to avoid recomputing them. + call do_some_work(tp0, tp1, tq0, tq1) + xp0 = schumaker_volk(px0, px1, px2, tp0) + yp0 = schumaker_volk(py0, py1, py2, tp0) + xp1 = schumaker_volk(px0, px1, px2, tp1) + yp1 = schumaker_volk(py0, py1, py2, tp1) + xq0 = schumaker_volk(qx0, qx1, qx2, tq0) + yq0 = schumaker_volk(qy0, qy1, qy2, tq0) + xq1 = schumaker_volk(qx0, qx1, qx2, tq1) + yq1 = schumaker_volk(qy0, qy1, qy2, tq1) + call test_intersection(xp0, xp1, yp0, yp1, xq0, xq1, yq0, yq1, tol, exclude, accept, x, y) + if (accept) then + call maybe_add_intersection(x, y, spacing) + else if (.not. exclude) then + tp_middle = 0.5 * (tp0 + tp1) + tq_middle = 0.5 * (tq0 + tq1) + call defer_work(tp0, tp_middle, tq0, tq_middle) + call defer_work(tp0, tp_middle, tq_middle, tq1) + call defer_work(tp_middle, tp1, tq0, tq_middle) + call defer_work(tp_middle, tp1, tq_middle, tq1) + end if + end do + + if (num_intersections == 0) then + print *, 'no intersections' + else + do k = 1, num_intersections + write (*, '(A, F12.8, A, F12.8, A)') '(', intersections_x(k), ', ', intersections_y(k), ')' + end do + end if + +contains + + ! Schumaker's and Volk's algorithm for evaluating a Bezier spline in + ! Bernstein basis. This is faster than de Casteljau, though not quite + ! as numerical stable. + double precision function schumaker_volk(c0, c1, c2, t) + double precision, intent(IN) :: c0, c1, c2, t + double precision :: s, u, v + s = 1.0 - t + if (t <= 0.5) then + ! Horner form in the variable u = t/s, taking into account the + ! binomial coefficients = 1,2,1. + u = t / s + v = c0 + (u * (c1 + c1 + (u * c2))) + ! Multiply by s raised to the degree of the spline. + v = v * s * s + else + ! Horner form in the variable u = s/t, taking into account the + ! binomial coefficients = 1,2,1. + u = s / t + v = c2 + (u * (c1 + c1 + (u * c0))) + ! Multiply by t raised to the degree of the spline. + v = v * t * t + end if + schumaker_volk = v + end function schumaker_volk + + ! Find extreme point of a quadratic Bezier spline + subroutine find_extreme_point(c0, c1, c2, lies_inside_01, extreme_point) + double precision, intent(IN) :: c0, c1, c2 + logical, intent(OUT) :: lies_inside_01 + double precision, intent(OUT) :: extreme_point + double precision :: numer, denom + ! If the spline has c0=c2 but not c0=c1=c2, then treat it as having + ! an extreme point at 0.5. + if (c0 == c2 .and. c0 /= c1) then + lies_inside_01 = .true. + extreme_point = 0.5 + else + ! Find the root of the derivative of the spline. + lies_inside_01 = .false. + numer = c0 - c1 + denom = c2 - c1 - c1 + c0 + if (denom /= 0.0 .and. numer * denom >= 0.0 .and. numer <= denom) then + lies_inside_01 = .true. + extreme_point = numer / denom + end if + end if + end subroutine find_extreme_point + + ! Insert extreme point into start intervals if it lies in (0,1) + subroutine possibly_insert_extreme_point(c0, c1, c2, num_start_interv, start_interv) + double precision, intent(IN) :: c0, c1, c2 + integer, intent(INOUT) :: num_start_interv + double precision, intent(INOUT) :: start_interv(max_start_interv) + logical :: lies_inside_01 + double precision :: extreme_pt + call find_extreme_point(c0, c1, c2, lies_inside_01, extreme_pt) + if (lies_inside_01 .and. extreme_pt > 0.0 .and. extreme_pt < 1.0) then + if (num_start_interv == 2) then + start_interv(3) = 1.0 + start_interv(2) = extreme_pt + num_start_interv = 3 + else if (extreme_pt < start_interv(2)) then + start_interv(4) = 1.0 + start_interv(3) = start_interv(2) + start_interv(2) = extreme_pt + num_start_interv = 4 + else if (extreme_pt > start_interv(2)) then + start_interv(4) = 1.0 + start_interv(3) = extreme_pt + num_start_interv = 4 + end if + end if + end subroutine possibly_insert_extreme_point + + ! Minimum of two values + double precision function minimum2(x, y) + double precision, intent(IN) :: x, y + minimum2 = min(x, y) + end function minimum2 + + ! Maximum of two values + double precision function maximum2(x, y) + double precision, intent(IN) :: x, y + maximum2 = max(x, y) + end function maximum2 + + ! Check if two rectangles overlap + logical function rectangles_overlap(xa0, ya0, xa1, ya1, xb0, yb0, xb1, yb1) + double precision, intent(IN) :: xa0, ya0, xa1, ya1, xb0, yb0, xb1, yb1 + ! It is assumed that xa0<=xa1, ya0<=ya1, xb0<=xb1, and yb0<=yb1. + rectangles_overlap = (xb0 <= xa1 .and. xa0 <= xb1 .and. yb0 <= ya1 .and. ya0 <= yb1) + end function rectangles_overlap + + ! Test for intersection between two line segments + subroutine test_intersection(xp0, xp1, yp0, yp1, xq0, xq1, yq0, yq1, tol, exclude, accept, x, y) + double precision, intent(IN) :: xp0, xp1, yp0, yp1, xq0, xq1, yq0, yq1, tol + logical, intent(OUT) :: exclude, accept + double precision, intent(OUT) :: x, y + double precision :: xpmin, ypmin, xpmax, ypmax + double precision :: xqmin, yqmin, xqmax, yqmax + double precision :: xmin, xmax, ymin, ymax + xpmin = minimum2(xp0, xp1) + ypmin = minimum2(yp0, yp1) + xpmax = maximum2(xp0, xp1) + ypmax = maximum2(yp0, yp1) + xqmin = minimum2(xq0, xq1) + yqmin = minimum2(yq0, yq1) + xqmax = maximum2(xq0, xq1) + yqmax = maximum2(yq0, yq1) + exclude = .true. + accept = .false. + if (rectangles_overlap(xpmin, ypmin, xpmax, ypmax, xqmin, yqmin, xqmax, yqmax)) then + exclude = .false. + xmin = maximum2(xpmin, xqmin) + xmax = minimum2(xpmax, xqmax) + if (xmax < xmin) stop 'Assertion failed: xmax >= xmin' + if (xmax - xmin <= tol) then + ymin = maximum2(ypmin, yqmin) + ymax = minimum2(ypmax, yqmax) + if (ymax < ymin) stop 'Assertion failed: ymax >= ymin' + if (ymax - ymin <= tol) then + accept = .true. + x = 0.5 * (xmin + xmax) + y = 0.5 * (ymin + ymax) + end if + end if + end if + end subroutine test_intersection + + ! Check if workload is empty + logical function work_is_done() + work_is_done = (workload_size == 0) + end function work_is_done + + ! Add work to the workload stack + subroutine defer_work(tp0, tp1, tq0, tq1) + double precision, intent(IN) :: tp0, tp1, tq0, tq1 + if (workload_size >= max_workload) stop 'Error: Workload stack overflow' + workload_size = workload_size + 1 + workload(1, workload_size) = tp0 + workload(2, workload_size) = tp1 + workload(3, workload_size) = tq0 + workload(4, workload_size) = tq1 + end subroutine defer_work + + ! Remove and return work from the workload stack + subroutine do_some_work(tp0, tp1, tq0, tq1) + double precision, intent(OUT) :: tp0, tp1, tq0, tq1 + if (work_is_done()) stop 'Assertion failed: Workload is empty' + tp0 = workload(1, workload_size) + tp1 = workload(2, workload_size) + tq0 = workload(3, workload_size) + tq1 = workload(4, workload_size) + workload_size = workload_size - 1 + end subroutine do_some_work + + ! Add intersection point if it's not too close to existing ones + subroutine maybe_add_intersection(x, y, spacing) + double precision, intent(IN) :: x, y, spacing + integer :: i + logical :: too_close + if (num_intersections == 0) then + intersections_x(1) = x + intersections_y(1) = y + num_intersections = 1 + else + too_close = .false. + do i = 1, num_intersections + if (abs(x - intersections_x(i)) < spacing .and. & + abs(y - intersections_y(i)) < spacing) then + too_close = .true. + exit + end if + end do + if (.not. too_close) then + if (num_intersections >= max_intersections) stop 'Too many intersections' + num_intersections = num_intersections + 1 + intersections_x(num_intersections) = x + intersections_y(num_intersections) = y + end if + end if + end subroutine maybe_add_intersection + +end program bezier_intersections diff --git a/Task/B-zier-curves-Intersections/Mathematica/b-zier-curves-intersections.math b/Task/B-zier-curves-Intersections/Mathematica/b-zier-curves-intersections.math new file mode 100644 index 0000000000..62d124f937 --- /dev/null +++ b/Task/B-zier-curves-Intersections/Mathematica/b-zier-curves-intersections.math @@ -0,0 +1,7 @@ +ClearAll[BezierFunc] +BezierFunc[pts_List, \[Alpha]_] := Nest[BlockMap[Apply[(1 - \[Alpha]) #1 + \[Alpha] #2 &], #, 2, 1] &, pts, Length[pts] - 1][[1]] +b1 = BezierFunc[{{-1, 0}, {0, 10}, {1, 0}}, s]; +b2 = BezierFunc[{{2, 1}, {-8, 2}, {2, 3}}, t]; +eqs = Thread[b1 == b2]; +{s, t, b1} /. Solve[%, {s, t}]; +Grid[N[%]] diff --git a/Task/B-zier-curves-Intersections/Rust/b-zier-curves-intersections.rs b/Task/B-zier-curves-Intersections/Rust/b-zier-curves-intersections.rs new file mode 100644 index 0000000000..44e656af33 --- /dev/null +++ b/Task/B-zier-curves-Intersections/Rust/b-zier-curves-intersections.rs @@ -0,0 +1,198 @@ +use std::f64; + +const TOLERANCE: f64 = 0.000_000_1; +const SPACING: f64 = 10.0 * TOLERANCE; + +// Replaces std::pair +#[derive(Debug, Clone, Copy, PartialEq, Default)] +struct Point { + x: f64, + y: f64, +} + +impl Point { + fn new(x: f64, y: f64) -> Self { + Point { x, y } + } +} + +// Replaces quad_spline class +#[derive(Debug, Clone, Copy, Default)] +struct QuadSpline { + c0: f64, + c1: f64, + c2: f64, +} + +impl QuadSpline { + fn new(c0: f64, c1: f64, c2: f64) -> Self { + QuadSpline { c0, c1, c2 } + } + + /// de Casteljau's algorithm for 1D spline subdivision + /// Returns two new splines, representing the curve from 0->t and t->1 + fn subdivide(&self, t: f64) -> (QuadSpline, QuadSpline) { + let s = 1.0 - t; + let u_c0 = self.c0; + let v_c2 = self.c2; + let u_c1 = s * self.c0 + t * self.c1; + let v_c1 = s * self.c1 + t * self.c2; + let u_c2 = s * u_c1 + t * v_c1; + let v_c0 = u_c2; + + let u = QuadSpline::new(u_c0, u_c1, u_c2); + let v = QuadSpline::new(v_c0, v_c1, v_c2); + (u, v) + } + + // Helper to get min/max control points for bounding box + fn min_max(&self) -> (f64, f64) { + let min_val = self.c0.min(self.c1).min(self.c2); + let max_val = self.c0.max(self.c1).max(self.c2); + (min_val, max_val) + } +} + +// Replaces quad_curve class +#[derive(Debug, Clone, Copy, Default)] +struct QuadCurve { + x: QuadSpline, + y: QuadSpline, +} + +impl QuadCurve { + fn new(x: QuadSpline, y: QuadSpline) -> Self { + QuadCurve { x, y } + } + + /// de Casteljau's algorithm for 2D curve subdivision + /// Returns two new curves, representing the curve from 0->t and t->1 + fn subdivide(&self, t: f64) -> (QuadCurve, QuadCurve) { + let (ux, vx) = self.x.subdivide(t); + let (uy, vy) = self.y.subdivide(t); + (QuadCurve::new(ux, uy), QuadCurve::new(vx, vy)) + } + + /// Calculate the axis-aligned bounding box (AABB) + fn bounding_box(&self) -> (f64, f64, f64, f64) { + let (px_min, px_max) = self.x.min_max(); + let (py_min, py_max) = self.y.min_max(); + (px_min, py_min, px_max, py_max) + } +} + +/// Checks if two axis-aligned rectangles overlap +fn rectangles_overlap( + xa0: f64, ya0: f64, xa1: f64, ya1: f64, + xb0: f64, yb0: f64, xb1: f64, yb1: f64, +) -> bool { + // Ensure coordinates are ordered min -> max if necessary, although bounding_box should handle this. + // let (xa0, xa1) = if xa0 > xa1 { (xa1, xa0) } else { (xa0, xa1) }; + // let (ya0, ya1) = if ya0 > ya1 { (ya1, ya0) } else { (ya0, ya1) }; + // let (xb0, xb1) = if xb0 > xb1 { (xb1, xb0) } else { (xb0, xb1) }; + // let (yb0, yb1) = if yb0 > yb1 { (yb1, yb0) } else { (yb0, yb1) }; + + xb0 <= xa1 && xa0 <= xb1 && yb0 <= ya1 && ya0 <= yb1 +} + +/// Test intersection candidacy based on bounding box overlap and size. +/// Returns: (accepted, excluded, potential_intersect_point) +fn test_intersection(p: &QuadCurve, q: &QuadCurve) -> (bool, bool, Point) { + let (px_min, py_min, px_max, py_max) = p.bounding_box(); + let (qx_min, qy_min, qx_max, qy_max) = q.bounding_box(); + + let mut accepted = false; + let mut excluded = true; + let mut intersect = Point::default(); // Default point (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; + // Calculate overlap region + let x_min = px_min.max(qx_min); + let x_max = px_max.min(qx_max); // Corrected from C++ possible typo px_max.min(px_max) + if x_max - x_min <= TOLERANCE { + let y_min = py_min.max(qy_min); + let y_max = py_max.min(qy_max); + if y_max - y_min <= TOLERANCE { + accepted = true; + // Use midpoint of the tiny overlap box as the intersection point + intersect = Point::new(0.5 * (x_min + x_max), 0.5 * (y_min + y_max)); + } + } + } + (accepted, excluded, intersect) +} + +/// Check if a point is too close to existing intersection points +fn seems_to_be_duplicate(intersects: &[Point], pt: Point) -> bool { + for &intersect in intersects { + if (intersect.x - pt.x).abs() < SPACING && (intersect.y - pt.y).abs() < SPACING { + return true; + } + } + false +} + +/// Find intersection points between two quadratic Bezier curves using recursive subdivision. +fn find_intersects(p: &QuadCurve, q: &QuadCurve) -> Vec { + let mut result: Vec = Vec::new(); + // Use a Vec as a stack, storing pairs of curves to check + // Pushing/popping individual curves to mimic C++ stack behavior exactly + let mut stack: Vec = Vec::new(); + stack.push(*q); // Push q first (will be popped as qq) + stack.push(*p); // Push p second (will be popped as pp) + + while stack.len() >= 2 { + // Pop in the order that matches the C++ version's stack processing + let pp = stack.pop().unwrap(); // Pop p-curve segment + let qq = stack.pop().unwrap(); // Pop q-curve segment + + let (accepted, excluded, intersect) = test_intersection(&pp, &qq); + + if accepted { + if !seems_to_be_duplicate(&result, intersect) { + result.push(intersect); + } + } else if !excluded { + // Bounding boxes overlap significantly, subdivide both curves + let (p0, p1) = pp.subdivide(0.5); + let (q0, q1) = qq.subdivide(0.5); + + // Push the 4 pairs of sub-curves onto the stack for further testing. + // Order matches the C++ version's push order { p0, q0, p0, q1, p1, q0, p1, q1 } + // Processed pairs will be (p0,q0), (p0,q1), (p1,q0), (p1,q1) eventually. + // Push in reverse order of desired processing: + stack.push(q1); stack.push(p1); // For pair (p1, q1) + stack.push(q0); stack.push(p1); // For pair (p1, q0) + stack.push(q1); stack.push(p0); // For pair (p0, q1) + stack.push(q0); stack.push(p0); // For pair (p0, q0) + } + // If excluded, do nothing, this pair of segments cannot intersect. + } + result +} + +fn main() { + // QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0) + let vertical = QuadCurve::new( + QuadSpline::new(-1.0, 0.0, 1.0), + QuadSpline::new(0.0, 10.0, 0.0), + ); + // QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3) + let horizontal = QuadCurve::new( + QuadSpline::new(2.0, -8.0, 2.0), + QuadSpline::new(1.0, 2.0, 3.0), + ); + + println!("The points of intersection are:"); + let intersects = find_intersects(&vertical, &horizontal); + + if intersects.is_empty() { + println!("No intersections found."); + } else { + for intersect in intersects { + // Format output similar to C++ version + println!("( {:9.6}, {:9.6} )", intersect.x, intersect.y); + } + } +} diff --git a/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy b/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy new file mode 100644 index 0000000000..888e9c378e --- /dev/null +++ b/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy @@ -0,0 +1,70 @@ +fastfunc findj a norm . + j = floor sqrt norm + 1 + repeat + b = j * j + if a + b < norm : return -1 + if a + b = norm : return j + until j = 0 + j -= 1 + . + return -1 +. +proc babylon_spiral nsteps &pts[][] . + pts[][] = [ [ 0 0 ] [ 0 1 ] ] + norm = 1 + last[] = pts[$][] + for k to nsteps - 2 + theta = atan2 last[2] last[1] + cands[][] = [ ] + while len cands[][] = 0 + norm += 1 + for i = 0 to nsteps + a = i * i + if a > norm div 2 : break 1 + j = findj a norm + if j <> -1 + cands[][] &= [ i, j ] + cands[][] &= [ -i, j ] + cands[][] &= [ i, -j ] + cands[][] &= [ -i, -j ] + cands[][] &= [ j, i ] + cands[][] &= [ -j, i ] + cands[][] &= [ j, -i ] + cands[][] &= [ -j, -i ] + . + . + . + min = 1 / 0 + for i to len cands[][] + h = (theta - atan2 cands[i][2] cands[i][1]) mod 360 + if h < min + min = h + mini = i + . + . + last[] = cands[mini][] + pts[][] &= pts[$][] + pts[$][1] += last[1] + pts[$][2] += last[2] + . +. +babylon_spiral 40 pts[][] +print pts[][] +# +babylon_spiral 10000 pts[][] +for i to len pts[][] + minx = lower minx pts[i][1] + maxx = higher maxx pts[i][1] + miny = lower miny pts[i][2] + maxy = higher maxy pts[i][2] +. +scx = 100 / (maxx - minx) * 0.96 +scy = 100 / (maxy - miny) * 0.96 +ty = -miny * scy + 2 +tx = -minx * scx + 2 +glinewidth 0.1 +for i to len pts[][] - 1 + gline 0 ty 100 ty + gline tx 0 tx 100 + gline pts[i][1] * scx + tx, pts[i][2] * scy + ty, pts[i + 1][1] * scx + tx, pts[i + 1][2] * scy + ty +. diff --git a/Task/Balanced-brackets/Ballerina/balanced-brackets.ballerina b/Task/Balanced-brackets/Ballerina/balanced-brackets.ballerina new file mode 100644 index 0000000000..bbae2976c8 --- /dev/null +++ b/Task/Balanced-brackets/Ballerina/balanced-brackets.ballerina @@ -0,0 +1,34 @@ +import ballerina/io; +import ballerina/random; + +function isBalanced(string s) returns boolean { + if s == "" { return true; } + int countLeft = 0; // number of left brackets so far unmatched + foreach var c in s { + if c == "[" { + countLeft += 1; + } else if countLeft > 0 { + countLeft -= 1; + } else { + return false; + } + } + return countLeft == 0; +} + +public function main() { + io:println("Checking examples in task description:"); + var brackets = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"]; + foreach string b in brackets { + io:print((b != "") ? b : "(empty)"); + io:println("\t ", isBalanced(b) ? "OK" : "NOT OK"); + } + io:println("\nChecking 7 random strings of brackets of length 8:"); + foreach int i in 1...7 { + string s = ""; + foreach int j in 1...8 { + s += random:createIntInRange(0, 2) == 0 ? "[" : "]"; + } + io:println(s, " ", isBalanced(s) ? "OK" : "NOT OK"); + } +} diff --git a/Task/Balanced-brackets/Excel/balanced-brackets-3.excel b/Task/Balanced-brackets/Excel/balanced-brackets-3.excel new file mode 100644 index 0000000000..6a039e391e --- /dev/null +++ b/Task/Balanced-brackets/Excel/balanced-brackets-3.excel @@ -0,0 +1 @@ +=REDUCE(A2, SEQUENCE(MAX(1, LEN(A2))), LAMBDA(a, _, SUBSTITUTE(a, "[]", ))) = "" diff --git a/Task/Balanced-brackets/Excel/balanced-brackets-4.excel b/Task/Balanced-brackets/Excel/balanced-brackets-4.excel new file mode 100644 index 0000000000..64246d94af --- /dev/null +++ b/Task/Balanced-brackets/Excel/balanced-brackets-4.excel @@ -0,0 +1 @@ +=REDUCE(REGEXREPLACE(A2, "[^\[\]]", ), SEQUENCE(MAX(1, LEN(A2))), LAMBDA(a, _, SUBSTITUTE(a, "[]", ))) = "" diff --git a/Task/Balanced-ternary/00-TASK.txt b/Task/Balanced-ternary/00-TASK.txt index 6b6f6bb48f..f548e4c8c0 100644 --- a/Task/Balanced-ternary/00-TASK.txt +++ b/Task/Balanced-ternary/00-TASK.txt @@ -10,13 +10,13 @@ Decimal 6 = 32 − 31 + 0 × 30, thus it can b ;Task: Implement balanced ternary representation of integers with the following: # Support arbitrarily large integers, both positive and negative; -# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). +# Provide ways to convert to and from text strings, using digits '+', '−' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). # Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated. # Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first. # Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). -'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-": +'''Test case''' With balanced ternaries ''a'' from string "+−0++0+", ''b'' from native integer −436, ''c'' "+−++−": * write out ''a'', ''b'' and ''c'' in decimal notation; * calculate ''a'' × (''b'' − ''c''), write out the result in both ternary and decimal notations. diff --git a/Task/Barnsley-fern/EasyLang/barnsley-fern.easy b/Task/Barnsley-fern/EasyLang/barnsley-fern.easy index 3d5e535c80..4176e236d7 100644 --- a/Task/Barnsley-fern/EasyLang/barnsley-fern.easy +++ b/Task/Barnsley-fern/EasyLang/barnsley-fern.easy @@ -1,21 +1,20 @@ -color 060 +gcolor 060 for i = 1 to 200000 - r = randomf - if r < 0.01 - nx = 0 - ny = 0.16 * y - elif r < 0.08 - nx = 0.2 * x - 0.26 * y - ny = 0.23 * x + 0.22 * y + 1.6 - elif r < 0.15 - nx = -0.15 * x + 0.28 * y - ny = 0.26 * x + 0.24 * y + 0.44 - else - nx = 0.85 * x + 0.04 * y - ny = -0.04 * x + 0.85 * y + 1.6 - . - x = nx - y = ny - move 50 + x * 15 y * 10 - rect 0.3 0.3 + r = randomf + if r < 0.01 + nx = 0 + ny = 0.16 * y + elif r < 0.08 + nx = 0.2 * x - 0.26 * y + ny = 0.23 * x + 0.22 * y + 1.6 + elif r < 0.15 + nx = -0.15 * x + 0.28 * y + ny = 0.26 * x + 0.24 * y + 0.44 + else + nx = 0.85 * x + 0.04 * y + ny = -0.04 * x + 0.85 * y + 1.6 + . + x = nx + y = ny + grect 50 + x * 15 y * 10 0.3 0.3 . diff --git a/Task/Bell-numbers/C-sharp/bell-numbers.cs b/Task/Bell-numbers/C-sharp/bell-numbers-1.cs similarity index 100% rename from Task/Bell-numbers/C-sharp/bell-numbers.cs rename to Task/Bell-numbers/C-sharp/bell-numbers-1.cs diff --git a/Task/Bell-numbers/C-sharp/bell-numbers-2.cs b/Task/Bell-numbers/C-sharp/bell-numbers-2.cs new file mode 100644 index 0000000000..f2da84e2ba --- /dev/null +++ b/Task/Bell-numbers/C-sharp/bell-numbers-2.cs @@ -0,0 +1,25 @@ +using System.Numerics; + +foreach (var row in BellTriangle().Take(15)) +{ + Console.WriteLine(row[0]); +} + +Console.WriteLine(BellTriangle().ElementAt(49)[0]); + +foreach (var row in BellTriangle().Take(10)) +{ + Console.WriteLine(string.Join(", ", row)); +} + +IEnumerable> BellTriangle() +{ + List row = [1]; + + while (true) + { + yield return row; + var scan = row[^1]; + row = [scan, .. row.Select(r => scan += r) ]; + } +} diff --git a/Task/Benfords-law/EasyLang/benfords-law.easy b/Task/Benfords-law/EasyLang/benfords-law.easy index 56624832fb..3a1d767aa2 100644 --- a/Task/Benfords-law/EasyLang/benfords-law.easy +++ b/Task/Benfords-law/EasyLang/benfords-law.easy @@ -6,14 +6,12 @@ func$ add a$ b$ . c = r div 10 r$ &= r mod 10 . - if c > 0 - r$ &= c - . + if c > 0 : r$ &= c return r$ . # len fibdist[] 9 -proc mkfibdist . . +proc mkfibdist . # generate 1000 fibonacci numbers as # (reversed) strings, because 53 bit # integers are too small @@ -36,14 +34,14 @@ proc mkfibdist . . mkfibdist # len benfdist[] 9 -proc mkbenfdist . . +proc mkbenfdist . for i to 9 benfdist[i] = log10 (1 + 1.0 / i) . . mkbenfdist # -numfmt 3 0 +numfmt 0 3 print "Actual Expected" for i to 9 print fibdist[i] & " " & benfdist[i] diff --git a/Task/Best-shuffle/EasyLang/best-shuffle.easy b/Task/Best-shuffle/EasyLang/best-shuffle.easy index ef0e2ef7bf..4f6a5e338f 100644 --- a/Task/Best-shuffle/EasyLang/best-shuffle.easy +++ b/Task/Best-shuffle/EasyLang/best-shuffle.easy @@ -1,4 +1,4 @@ -proc best_shuffle s$ . r$ diff . +proc best_shuffle s$ &r$ &diff . l = len s$ for c$ in strchars s$ s[] &= strcode c$ diff --git a/Task/Bifid-cipher/EasyLang/bifid-cipher.easy b/Task/Bifid-cipher/EasyLang/bifid-cipher.easy index 0a26b043a8..df84986ae6 100644 --- a/Task/Bifid-cipher/EasyLang/bifid-cipher.easy +++ b/Task/Bifid-cipher/EasyLang/bifid-cipher.easy @@ -1,4 +1,4 @@ -proc prepare . s$ . +proc prepare &s$ . for e$ in strchars s$ h = strcode e$ if h >= 97 diff --git a/Task/Bifid-cipher/JavaScript/bifid-cipher.js b/Task/Bifid-cipher/JavaScript/bifid-cipher.js new file mode 100644 index 0000000000..a4f210b4c0 --- /dev/null +++ b/Task/Bifid-cipher/JavaScript/bifid-cipher.js @@ -0,0 +1,199 @@ +// ADFGVX Cipher Implementation in JavaScript + +// Cipher squares +const squareRosetta = [ // from Rosetta Code + ['A', 'B', 'C', 'D', 'E'], + ['F', 'G', 'H', 'I', 'K'], + ['L', 'M', 'N', 'O', 'P'], + ['Q', 'R', 'S', 'T', 'U'], + ['V', 'W', 'X', 'Y', 'Z'], + ['J', '1', '2', '3', '4'] +]; + +const squareWikipedia = [ // from Wikipedia + ['B', 'G', 'W', 'K', 'Z'], + ['Q', 'P', 'N', 'D', 'S'], + ['I', 'O', 'A', 'X', 'E'], + ['F', 'C', 'L', 'U', 'M'], + ['T', 'H', 'Y', 'V', 'R'], + ['J', '1', '2', '3', '4'] +]; + +// Test text strings +const textRosetta = "0ATTACKATDAWN"; +const textRosettaEncoded = "DQBDAXDQPDQH"; // only for test +const textWikipedia = "FLEEATONCE"; +const textWikipediaEncoded = "UAEOLWRINS"; // only for test +const textTest = "The invasion will start on the first of January"; +const textTestEncoded = "RASOAQXFIOORXESXADETSWLTNIAZQOISBRGBALY"; // only for test + +// Coordinate class (equivalent to koord struct in Go) +class Coord { + constructor(x, y) { + this.x = x; + this.y = y; + } + + lessThan(other) { + if (this.y > other.y) { + return false; + } + if (this.y < other.y) { + return true; + } + if (this.x < other.x) { + return true; + } + return false; + } + + equalTo(other) { + return this.x === other.x && this.y === other.y; + } +} + +// Convert square to encryption and decryption maps +function squareToMaps(square) { + const encryptMap = new Map(); + const decryptMap = new Map(); + + for (let x = 0; x < square.length; x++) { + for (let y = 0; y < square[x].length; y++) { + const value = square[x][y]; + const coord = new Coord(x, y); + + // For encryption map, use character as key + encryptMap.set(value, coord); + + // For decryption map, use coordinate string as key + // (JavaScript Maps can't use objects as keys directly, so convert to string) + decryptMap.set(`${x},${y}`, value); + } + } + + return { encryptMap, decryptMap }; +} + +// Remove spaces and non-valid characters +function removeSpace(text, encryptMap) { + const upper = text.toUpperCase().replace(/\s/g, ''); + let result = ''; + + for (const char of upper) { + if (encryptMap.has(char)) { + result += char; + } + } + + return result; +} + +// Replace 'J' with 'I' (for specific Polybius square implementations) +function removeSpaceI(text) { + const upper = text.toUpperCase(); + let result = ''; + + for (const char of upper) { + // Use only ASCII characters from A to Z + if (char >= 'A' && char <= 'Z') { + result += char === 'J' ? 'I' : char; + } + } + + return result; +} + +// Encrypt using ADFGVX cipher +function encrypt(text, encryptMap, decryptMap) { + text = removeSpace(text, encryptMap); + + const row0 = []; + const row1 = []; + + // Get coordinates for each character + for (const char of text) { + const coord = encryptMap.get(char); + row0.push(coord.x); + row1.push(coord.y); + } + + // Combine coordinates + const combined = [...row0, ...row1]; + + let result = ''; + // Convert pairs of coordinates back to characters + for (let i = 0; i < combined.length; i += 2) { + const key = `${combined[i]},${combined[i+1]}`; + result += decryptMap.get(key); + } + + return result; +} + +// Decrypt using ADFGVX cipher +function decrypt(text, encryptMap, decryptMap) { + text = removeSpace(text, encryptMap); + + const coords = []; + + // Get coordinates for each character + for (const char of text) { + coords.push(encryptMap.get(char)); + } + + // Extract x and y values + const flatCoords = []; + for (const coord of coords) { + flatCoords.push(coord.x); + flatCoords.push(coord.y); + } + + const half = Math.floor(flatCoords.length / 2); + const firstHalf = flatCoords.slice(0, half); + const secondHalf = flatCoords.slice(half); + + let result = ''; + + // Recombine coordinates to get original text + for (let i = 0; i < firstHalf.length; i++) { + const key = `${firstHalf[i]},${secondHalf[i]}`; + result += decryptMap.get(key); + } + + return result; +} + +// Main function to test +function main() { + // Test with Rosetta square + let { encryptMap, decryptMap } = squareToMaps(squareRosetta); + + console.log("From Rosetta Code"); + console.log("original:\t", textRosetta); + let encoded = encrypt(textRosetta, encryptMap, decryptMap); + console.log("encoded:\t", encoded); + let decoded = decrypt(encoded, encryptMap, decryptMap); + console.log("and back:\t", decoded); + + // Test with Wikipedia square + ({ encryptMap, decryptMap } = squareToMaps(squareWikipedia)); + + console.log("\nFrom Wikipedia"); + console.log("original:\t", textWikipedia); + encoded = encrypt(textWikipedia, encryptMap, decryptMap); + console.log("encoded:\t", encoded); + decoded = decrypt(encoded, encryptMap, decryptMap); + console.log("and back:\t", decoded); + + // Test with longer text + console.log("\nFrom Rosetta Code (longer text)"); + console.log("original:\t", textTest); + encoded = encrypt(textTest, encryptMap, decryptMap); + console.log("encoded:\t", encoded); + // Note: If the text has an odd number of letters, the algorithm doesn't work! + decoded = decrypt(encoded, encryptMap, decryptMap); + console.log("and back:\t", decoded); +} + +// Run the main function +main(); diff --git a/Task/Bifid-cipher/Rust/bifid-cipher.rs b/Task/Bifid-cipher/Rust/bifid-cipher.rs new file mode 100644 index 0000000000..57868d8c09 --- /dev/null +++ b/Task/Bifid-cipher/Rust/bifid-cipher.rs @@ -0,0 +1,125 @@ +use std::collections::HashMap; + +type Point = (i32, i32); + + +struct Bifid { + grid: Vec>, + coordinates: HashMap, + n: i32, +} + +impl Bifid { + pub fn new(n: i32, text: &str) -> Result { + if (text.len() as i32) != n * n { + return Err("Incorrect length of text".to_string()); + } + + let mut grid = vec![vec!['\0'; n as usize]; n as usize]; + let mut coordinates: HashMap = HashMap::new(); + + let mut row: i32 = 0; + let mut col: i32 = 0; + + for ch in text.chars() { + grid[row as usize][col as usize] = ch; + coordinates.insert(ch, (row, col)); + + col += 1; + if col == n { + col = 0; + row += 1; + } + } + + if n == 5 { + if let Some(&i_coords) = coordinates.get(&'I') { + coordinates.insert('J', i_coords); + } + } + + Ok(Bifid { + grid, + coordinates, + n, + }) + } + + pub fn encrypt(&self, text: &str) -> String { + let mut row_one: Vec = Vec::new(); + let mut row_two: Vec = Vec::new(); + + for ch in text.chars() { + if let Some(coordinate) = self.coordinates.get(&ch) { + row_one.push(coordinate.0); + row_two.push(coordinate.1); + } + } + + row_one.extend(row_two.iter()); + let mut result = String::new(); + for i in (0..row_one.len() - 1).step_by(2) { + result.push(self.grid[row_one[i] as usize][row_one[i + 1] as usize]); + } + result + } + + pub fn decrypt(&self, text: &str) -> String { + let mut row: Vec = Vec::new(); + for ch in text.chars() { + if let Some(coordinate) = self.coordinates.get(&ch) { + row.push(coordinate.0); + row.push(coordinate.1); + } + } + + let middle = row.len() / 2; + let row_one: Vec = row[..middle].to_vec(); + let row_two: Vec = row[middle..].to_vec(); + + let mut result = String::new(); + for i in 0..middle { + result.push(self.grid[row_one[i] as usize][row_two[i] as usize]); + } + result + } + + pub fn display(&self) { + for row in &self.grid { + for ch in row { + print!("{} ", ch); + } + println!(); + } + } +} + +fn run_test(bifid: &Bifid, message: &str) { + println!("Using Polybius square:"); + bifid.display(); + println!("Message: {}", message); + let encrypted = bifid.encrypt(message); + println!("Encrypted: {}", encrypted); + let decrypted = bifid.decrypt(&encrypted); + println!("Decrypted: {}", decrypted); + println!(); +} + +fn main() -> Result<(), String> { + let message1 = "ATTACKATDAWN"; + let message2 = "FLEEATONCE"; + let message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; + + let bifid1 = Bifid::new(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ")?; + let bifid2 = Bifid::new(5, "BGWKZQPNDSIOAXEFCLUMTHYVR")?; + + run_test(&bifid1, message1); + run_test(&bifid2, message2); + run_test(&bifid2, message1); + run_test(&bifid1, message2); + + let bifid3 = Bifid::new(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")?; + run_test(&bifid3, message3); + + Ok(()) +} diff --git a/Task/Bin-given-limits/AppleScript/bin-given-limits.applescript b/Task/Bin-given-limits/AppleScript/bin-given-limits.applescript new file mode 100644 index 0000000000..9d4b93c9c4 --- /dev/null +++ b/Task/Bin-given-limits/AppleScript/bin-given-limits.applescript @@ -0,0 +1,42 @@ +property bins : {} + +local limits, theData, n, i, p, flag, output +set limits to {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} +set theData to {445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, ¬ + 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, ¬ + 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, ¬ + 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, ¬ + 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, ¬ + 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, ¬ + 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, ¬ + 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, ¬ + 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, ¬ + 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749} + +repeat (count limits) + 1 times + set end of bins to 0 +end repeat + +repeat with n in theData + set flag to false + repeat with i from 1 to count limits + if n < item i of limits then + set flag to true + exit repeat + end if + end repeat + if flag then + set item i of bins to (item i of bins) + 1 + else + set item -1 of bins to (item -1 of bins) + 1 + end if +end repeat +set p to item 1 of limits +set output to "< " & p & " := " & (item 1 of bins) & linefeed +repeat with i from 2 to count limits + set n to item i of limits + set output to output & ">= " & p & " .. < " & n & " := " & (item i of bins) & linefeed + set p to n +end repeat +set output to output & ">= " & p & " := " & (item -1 of bins) +get output diff --git a/Task/Bin-given-limits/Crystal/bin-given-limits.cr b/Task/Bin-given-limits/Crystal/bin-given-limits.cr new file mode 100644 index 0000000000..84f3d18ad5 --- /dev/null +++ b/Task/Bin-given-limits/Crystal/bin-given-limits.cr @@ -0,0 +1,43 @@ +def bin (limits, seq) + bins = Array.new limits.size+1, 0 + seq.each do |v| + bins[limits.bsearch_index {|l, _| v < l } || -1] += 1 + end + bins +end + +def print_bins (limits, bins) + limit_width = limits.values_at(0, -1).map(&.to_s.size).max + tally_width = bins.max.to_s.size + bins.each_with_index do |n, i| + left = if i > 0; limits[i-1] end + right = if i < limits.size; limits[i] end + printf "%*s %s n %s %*s ⇒ %*s\n", + limit_width, left, left ? "≤" : " ", + right ? "<" : " ", limit_width, right, + tally_width, n + end +end + +limits = [23, 37, 43, 53, 67, 83] +data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, + 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] + +puts "P. 1" +print_bins(limits, bin(limits, data)) +puts + +limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] +data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, + 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, + 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, + 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, + 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, + 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, + 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, + 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, + 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, + 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] + +puts "P. 2" +print_bins(limits, bin(limits, data)) diff --git a/Task/Bin-given-limits/EasyLang/bin-given-limits.easy b/Task/Bin-given-limits/EasyLang/bin-given-limits.easy index 77d034ea2e..534a7c72d0 100644 --- a/Task/Bin-given-limits/EasyLang/bin-given-limits.easy +++ b/Task/Bin-given-limits/EasyLang/bin-given-limits.easy @@ -1,13 +1,10 @@ global limits[] data[] . # -proc count . . +proc count . len cnt[] len limits[] + 1 - # for e in data[] for i to len limits[] - if e < limits[i] - break 1 - . + if e < limits[i] : break 1 . cnt[i] += 1 . diff --git a/Task/Bin-given-limits/XPL0/bin-given-limits.xpl0 b/Task/Bin-given-limits/XPL0/bin-given-limits.xpl0 new file mode 100644 index 0000000000..ad0d939e9f --- /dev/null +++ b/Task/Bin-given-limits/XPL0/bin-given-limits.xpl0 @@ -0,0 +1,60 @@ +include xpllib; \for Print +int Bin(10+1); +def Marker = 0; + +proc PrintBins(Limits, Len); +int Limits, Len; +int I; +[Print(" < %3d:%3d\n", Limits(0), Bin(0)); +for I:= 1 to Len-1 do + Print(">= %3d and < %3d:%3d\n", Limits(I-1), Limits(I), Bin(I)); +Print(">= %3d :%3d\n", Limits(Len-1), Bin(Len)); +]; + +proc TallyBins(Limits, Len, Data); +int Limits, Len, Data; +int I, J, D; +[for I:= 0 to Len do + Bin(I):= 0; +I:= 0; +loop [D:= Data(I); + if D = Marker then quit; + I:= I+1; + for J:= 0 to Len-1 do \for each limit + if D < Limits(J) then + [Bin(J):= Bin(J)+1; + J:= Len; \exit for loop with J = Len+1 + ]; + if J = Len then \>= last limit + Bin(J):= Bin(J)+1; + ]; +]; + +int Limits, Data; +[Limits:= [23, 37, 43, 53, 67, 83]; +Data:= [95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, + 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, + 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, + 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55, Marker]; +TallyBins(Limits, 6, Data); +PrintBins(Limits, 6); +CrLf(0); +Limits:= [14, 18, 249, 312, 389, 392, 513, 591, 634, 720]; +Data:= [445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, + 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, + 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, + 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, + 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, + 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, + 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, + 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, + 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, + 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, + 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, + 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, + 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, + 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, + 101, 684, 727, 749, Marker]; +TallyBins(Limits, 10, Data); +PrintBins(Limits, 10); +] diff --git a/Task/Binary-digits/C3/binary-digits.c3 b/Task/Binary-digits/C3/binary-digits.c3 new file mode 100644 index 0000000000..9b4073dfff --- /dev/null +++ b/Task/Binary-digits/C3/binary-digits.c3 @@ -0,0 +1,8 @@ +import std::io; +fn void main() +{ + io::printfn("%b", 0); + io::printfn("%b", 5); + io::printfn("%b", 50); + io::printfn("%b", 5000); +} diff --git a/Task/Binary-digits/EasyLang/binary-digits.easy b/Task/Binary-digits/EasyLang/binary-digits.easy index 471ba50912..222c41fe5e 100644 --- a/Task/Binary-digits/EasyLang/binary-digits.easy +++ b/Task/Binary-digits/EasyLang/binary-digits.easy @@ -1,10 +1,8 @@ func$ bin num . - while num > 1 - b$ = num mod 2 & b$ - num = num div 2 - . - return num & b$ + if num <= 1 : return num + return bin (num div 2) & num mod 2 . +print bin 0 print bin 5 print bin 50 print bin 9000 diff --git a/Task/Binary-search/EasyLang/binary-search.easy b/Task/Binary-search/EasyLang/binary-search.easy index c9318c5647..243fd82cfb 100644 --- a/Task/Binary-search/EasyLang/binary-search.easy +++ b/Task/Binary-search/EasyLang/binary-search.easy @@ -1,18 +1,17 @@ -proc binSearch val . a[] res . +func binSearch &a[] val . low = 1 high = len a[] - res = 0 - while low <= high and res = 0 + while low <= high mid = (low + high) div 2 if a[mid] > val high = mid - 1 elif a[mid] < val low = mid + 1 else - res = mid + return mid . . + return 0 . a[] = [ 2 4 6 8 9 ] -binSearch 8 a[] r -print r +print binSearch a[] 8 diff --git a/Task/Bioinformatics-Global-alignment/FreeBASIC/bioinformatics-global-alignment.basic b/Task/Bioinformatics-Global-alignment/FreeBASIC/bioinformatics-global-alignment.basic new file mode 100644 index 0000000000..5b43c15039 --- /dev/null +++ b/Task/Bioinformatics-Global-alignment/FreeBASIC/bioinformatics-global-alignment.basic @@ -0,0 +1,170 @@ +' Nucleotides +Dim Shared As Integer A, C, G, T, Total + +Sub PrintReport(text As String) + A = 0 : C = 0 : G = 0 : T = 0 + For i As Integer = 1 To Len(text) + Select Case Ucase(Mid(text, i, 1)) + Case "A": A += 1 + Case "C": C += 1 + Case "G": G += 1 + Case "T": T += 1 + End Select + Next + Total = Len(text) + + Print "Nucleotide counts for: "; Iif(Len(text) > 50, Chr(10), ""); + Print text + Print "Bases: A"; A; ", C:"; C; ", G:"; G; ", T:"; T; ", total:"; Total + Print +End Sub + +Function Concatenate(before As String, after As String) As String + For i As Integer = 1 To Len(before) + Dim As String suffix = Mid(before, i) + If Left(after, Len(suffix)) = suffix Then Return Left(before, i - 1) + after + Next + Return before + after +End Function + +' Remove duplicates and strings contained within a larger string from a list of strings +Sub Deduplicate(list() As String, result() As String) + Dim As Integer i, j + ' Remove duplicates + Dim As String unique(0 To Ubound(list)) + Dim As Integer uniqueCount = 0 + For i = 0 To Ubound(list) + Dim As Boolean exists = False + For j = 0 To uniqueCount - 1 + If list(i) = unique(j) Then exists = True : Exit For + Next + If Not exists Then + unique(uniqueCount) = list(i) + uniqueCount += 1 + End If + Next + + ' Remove substrings + Dim As String tempRes(0 To uniqueCount - 1) + Dim As Integer resCount = 0 + For i = 0 To uniqueCount - 1 + Dim As Boolean isSubstring = False + For j = 0 To uniqueCount - 1 + If i <> j And Instr(unique(j), unique(i)) > 0 Then + isSubstring = True + Exit For + End If + Next + If Not isSubstring Then + tempRes(resCount) = unique(i) + resCount += 1 + End If + Next + + Redim result(0 To resCount - 1) + For i = 0 To resCount - 1 + result(i) = tempRes(i) + Next +End Sub + +' Gets all permutations of a list of strings +Sub ProcessPermutation(perm() As String, result() As String, Byref minLength As Integer) + Dim As String candidate = perm(0) + For i As Integer = 1 To Ubound(perm) + candidate = Concatenate(candidate, perm(i)) + Next + + If Len(candidate) < minLength Then + Erase result + Redim result(0) + result(0) = candidate + minLength = Len(candidate) + Elseif Len(candidate) = minLength Then + Dim As Boolean exists = False + For s As Integer = 0 To Ubound(result) + If result(s) = candidate Then exists = True : Exit For + Next + If Not exists Then + Redim Preserve result(0 To Ubound(result) + 1) + result(Ubound(result)) = candidate + End If + End If +End Sub + +' Returns shortest common superstring of a list of strings +Sub ShortestCommonSuperstrings(list() As String, result() As String) + Dim As String deduplicated() + Deduplicate(list(), deduplicated()) + If Ubound(deduplicated) < 0 Then Exit Sub + + Dim As Integer i, j, minLength = 0 + For i = 0 To Ubound(list) + minLength += Len(list(i)) + Next + + Dim As Integer n = Ubound(deduplicated) + 1 + Dim As Integer indexes(n - 1) + Dim As String currentPerm(n - 1) + + For i = 0 To n - 1 + indexes(i) = 0 + currentPerm(i) = deduplicated(i) + Next + + ProcessPermutation(currentPerm(), result(), minLength) + + i = 0 + While i < n + If indexes(i) < i Then + j = Iif(i Mod 2 = 0, 0, indexes(i)) + Swap currentPerm(j), currentPerm(i) + + ProcessPermutation(currentPerm(), result(), minLength) + + indexes(i) += 1 + i = 0 + Else + indexes(i) = 0 + i += 1 + End If + Wend +End Sub + +' Test cases +Dim As String test_sequences(0 To 3, 0 To 12) = { _ +{"TA", "AAG", "TA", "GAA", "TA", "", "", "", "", "", "", "", ""}, _ +{"CATTAGGG", "ATTAG", "GGG", "TA", "", "", "", "", "", "", "", "", ""}, _ +{"AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA", "", "", "", "", "", "", "", "", "", ""}, _ +{ "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", _ +"GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", _ +"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", _ +"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", _ +"AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", _ +"GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", _ +"CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", _ +"TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", _ +"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", _ +"GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", _ +"TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", _ +"CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", _ +"TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA" } _ +} + +For i As Integer = 0 To 3 + Dim As String test_case() + For j As Integer = 0 To 12 + If Len(test_sequences(i, j)) > 0 Then + Redim Preserve test_case(Ubound(test_case) + 1) + test_case(Ubound(test_case)) = test_sequences(i, j) + End If + Next + + Dim As String superstrings() + ShortestCommonSuperstrings(test_case(), superstrings()) + + For s As Integer = 0 To Ubound(superstrings) + PrintReport(superstrings(s)) + Next +Next + +Sleep diff --git a/Task/Bioinformatics-Global-alignment/Rust/bioinformatics-global-alignment.rs b/Task/Bioinformatics-Global-alignment/Rust/bioinformatics-global-alignment.rs new file mode 100644 index 0000000000..a33f50c14a --- /dev/null +++ b/Task/Bioinformatics-Global-alignment/Rust/bioinformatics-global-alignment.rs @@ -0,0 +1,132 @@ +use std::collections::{HashMap, HashSet}; + +// Print a report of the given string to the standard output device. +fn print_report(text: &str) { + let mut bases: HashMap = HashMap::new(); + for ch in text.chars() { + *bases.entry(ch).or_insert(0) += 1; + } + + let total: i32 = bases.values().sum(); + + println!("Nucleotide counts for: {}", if text.len() > 50 { "\n" } else { "" }); + println!("{}", text); + println!("Bases: A {}, C: {}, G: {}, T: {}, total: {}\n", + bases.get(&'A').unwrap_or(&0), + bases.get(&'C').unwrap_or(&0), + bases.get(&'G').unwrap_or(&0), + bases.get(&'T').unwrap_or(&0), + total); +} + +// Return all permutations of the given list of strings. +fn permutations(list: &mut Vec) -> Vec> { + let mut indexes: Vec = vec![0; list.len()]; + let mut result: Vec> = Vec::new(); + result.push(list.clone()); + let mut i = 0; + while i < list.len() { + if indexes[i] < i as i32 { + let j = if i % 2 == 0 { 0 } else { indexes[i] as usize }; + list.swap(i, j); + result.push(list.clone()); + indexes[i] += 1; + i = 0; + } else { + indexes[i] = 0; + i += 1; + } + } + result +} + +// Return 'before' concatenated with 'after', removing the longest suffix of 'before' that matches a prefix of 'after'. +fn concatenate(before: &str, after: &str) -> String { + for i in 0..before.len() { + let suffix = &before[i..]; + if after.starts_with(suffix) { + return format!("{}{}", &before[0..i], after); + } + } + format!("{}{}", before, after) +} + +// Remove duplicate strings and strings which are substrings of other strings in the given list. +fn deduplicate(list: &[String]) -> Vec { + let mut singletons = list.to_vec(); + singletons.sort(); + singletons.dedup(); + + let result = singletons.clone(); + let mut marked_for_removal: HashSet = HashSet::new(); + + for test_word in &result { + for word in &singletons { + if word != test_word && word.contains(test_word) { + marked_for_removal.insert(test_word.clone()); + } + } + } + + result.into_iter().filter(|word| !marked_for_removal.contains(word)).collect() +} + +// Return a set containing all of the shortest common superstrings of the given list of strings. +fn shortest_common_superstrings(list: &[String]) -> HashSet { + let deduplicated = deduplicate(list); + let mut deduplicated_mut = deduplicated.clone(); + + let mut shortest: HashSet = HashSet::new(); + let mut joined = String::new(); + for word in list { + joined.push_str(word); + } + shortest.insert(joined); + + let mut shortest_length = list.iter().map(|s| s.len()).sum(); + + for permutation in permutations(&mut deduplicated_mut) { + let mut candidate = String::new(); + for word in permutation { + candidate = concatenate(&candidate, &word); + } + + if candidate.len() < shortest_length { + shortest.clear(); + shortest_length = candidate.len(); + shortest.insert(candidate); + } else if candidate.len() == shortest_length { + shortest.insert(candidate); + } + } + shortest +} + +fn main() { + let test_sequences: Vec> = vec![ + vec!["TA".to_string(), "AAG".to_string(), "TA".to_string(), "GAA".to_string(), "TA".to_string()], + vec!["CATTAGGG".to_string(), "ATTAG".to_string(), "GGG".to_string(), "TA".to_string()], + vec!["AAGAUGGA".to_string(), "GGAGCGCAUC".to_string(), "AUCGCAAUAAGGA".to_string()], + vec![ + "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT".to_string(), + "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT".to_string(), + "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA".to_string(), + "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC".to_string(), + "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT".to_string(), + "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC".to_string(), + "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT".to_string(), + "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC".to_string(), + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC".to_string(), + "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT".to_string(), + "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC".to_string(), + "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA".to_string(), + "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA".to_string(), + ], + ]; + + for test in test_sequences { + for superstring in shortest_common_superstrings(&test) { + print_report(&superstring); + } + } +} diff --git a/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy b/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy index a2743b199b..5ff9a347ef 100644 --- a/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy +++ b/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy @@ -1,21 +1,15 @@ base$[] = [ "A" "C" "T" "G" ] global seq[] seqnx[] seqpr[] . -proc prseq . . +proc prseq . len cnt[] 4 - numfmt 0 3 + numfmt 3 0 ind = 1 while seqnx[ind] <> 1 pos += 1 ind = seqnx[ind] - if pos mod 40 = 1 - print "" - . - if pos mod 40 = 1 - write pos & ":" - . - if pos mod 4 = 1 - write " " - . + if pos mod 40 = 1 : print "" + if pos mod 40 = 1 : write pos & ":" + if pos mod 4 = 1 : write " " cnt[seq[ind]] += 1 write base$[seq[ind]] . @@ -29,7 +23,7 @@ proc prseq . . print " " & sum print "" . -proc init . . +proc init . seq[] = [ 0 ] seqnx[] = [ 2 ] seqpr[] = [ 0 ] @@ -41,7 +35,7 @@ proc init . . seqpr[1] = len seq[] seqnx[$] = 1 . -proc delete pos . . +proc delete pos . nx = seqnx[pos] pre = seqpr[pos] seqnx[pre] = nx @@ -56,7 +50,7 @@ proc delete pos . . len seqnx[] -1 len seqpr[] -1 . -proc insert pos . . +proc insert pos . seq[] &= random 4 last = len seq[] seqnx[] &= pos @@ -64,7 +58,7 @@ proc insert pos . . seqnx[seqpr[pos]] = last seqpr[pos] = last . -proc mutate . . +proc mutate . op = random 3 pos = random (len seq[] - 1) + 1 if op = 1 @@ -78,8 +72,6 @@ proc mutate . . init print "Original:" prseq -for i to 10 - mutate -. +for i to 10 : mutate print "Mutated:" prseq diff --git a/Task/Bioinformatics-base-count/EasyLang/bioinformatics-base-count.easy b/Task/Bioinformatics-base-count/EasyLang/bioinformatics-base-count.easy index d7c2cc2230..8e535a0e24 100644 --- a/Task/Bioinformatics-base-count/EasyLang/bioinformatics-base-count.easy +++ b/Task/Bioinformatics-base-count/EasyLang/bioinformatics-base-count.easy @@ -1,20 +1,14 @@ len d[] 26 pos = 1 -numfmt 0 4 +numfmt 4 0 repeat s$ = input until s$ = "" for c$ in strchars s$ - if pos mod 40 = 1 - write pos & ":" - . - if pos mod 4 = 1 - write " " - . + if pos mod 40 = 1 : write pos & ":" + if pos mod 4 = 1 : write " " write c$ - if pos mod 40 = 0 - print "" - . + if pos mod 40 = 0 : print "" pos += 1 c = strcode c$ d[c - 64] += 1 diff --git a/Task/Bioinformatics-base-count/Uxntal/bioinformatics-base-count.uxnatl b/Task/Bioinformatics-base-count/Uxntal/bioinformatics-base-count.uxnatl new file mode 100644 index 0000000000..c40f9b70d9 --- /dev/null +++ b/Task/Bioinformatics-base-count/Uxntal/bioinformatics-base-count.uxnatl @@ -0,0 +1,80 @@ +%\n { 0a } %\s { 20 } %\0 { 00 } +%newline { [ LIT2 \n -Console/write ] DEO } + +|18 @Console/write + +|100 + +;data base-count + +BRK + +@base-count ( data* -- ) + LDAk + DUP #0a NEQ ?{ !/next } + DUP [ LIT "A ] NEQ ?{ + [ LIT2 &adenine $2 ] INC2 ,/adenine STR2 !/resume } + DUP [ LIT "C ] NEQ ?{ + [ LIT2 &cytosine $2 ] INC2 ,/cytosine STR2 !/resume } + DUP [ LIT "G ] NEQ ?{ + [ LIT2 &guanine $2 ] INC2 ,/guanine STR2 !/resume } + DUP [ LIT "T ] NEQ ?{ + [ LIT2 &thymine $2 ] INC2 ,/thymine STR2 } + + &resume + [ LIT2 &total $2 ] INC2 ,/total STR2 + + &next + POP + INC2 LDAk ?base-count + + POP2 + + ;msgs/sequence print/str + ;data print/str + ;msgs/header print/str + ;msgs/adenine print/str ,/adenine LDR2 print/dec newline + ;msgs/cytosine print/str ,/cytosine LDR2 print/dec newline + ;msgs/guanine print/str ,/guanine LDR2 print/dec newline + ;msgs/thymine print/str ,/thymine LDR2 print/dec newline + ;msgs/total print/str ,/total LDR2 print/dec newline + + JMP2r + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str + POP2 JMP2r + +@print/dec ( short* -- ) + #000a SWP2 [ LITr ff ] + + &dec/get + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?/dec/get + POP2 POP2 + + &dec/put + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !/dec/put + +@data [ + "CGTAAAAAATTACAACGTCCTTTGG "CTATCTCTTAAACTCCTGCTAAATG \n + "CTCGTGCTTTCCAATTATGTAAGCG "TTCCGAGACGGGGTGGTCGATTCTG \n + "AGGACAAAGGTCAAGATGGAGCGCA "TCGAACGCAATAAGGATCATTTGAT \n + "GGGACGTTTCGTCGACAAAGTCTTG "TTTCGAGAGTAACGGCTACCGTCTT \n + "CGATTCTGCTTATAACACTATGTTC "TTATGAAATGGATGTTCTGAGTTGG \n + "TCAGTCCCAATGTGCGGGGTTTCTT "TTAGTACGTCGGGAGTGGTATTATA \n + "TTTAATTTTTCTATATAGCGATCTG "TATTTAAGCAATTCATTTAGGTTAT \n + "CGCCGCGATGCTCGGTTCGGACCGC "CAAGCATCTGGCTCCACTGCTAGTG \n + "TCCTAAATTTGAATGGCAAACACAA "ATAAGATTTAGCAATTCGTGTAGAC \n + "GACCGGGGACTTGCATGATGGGAGC "AGCTTTGTTAAACTACGAACGTAAT \n \0 ] + +@msgs [ + &header \n "BASE \s "COUNT: \n \0 + &sequence "SEQUENCE: \n \0 + &adenine \s \s \s "Adenine: \s \0 + &cytosine \s \s "Cytosine: \s \0 + &guanine \s \s \s "Guanine: \s \0 + &thymine \s \s \s "Thymine: \s \0 + &total \s \s \s \s \s "Total: \s \0 ] diff --git a/Task/Biorhythms/EasyLang/biorhythms.easy b/Task/Biorhythms/EasyLang/biorhythms.easy index ebb822d591..8f9bf9a6c9 100644 --- a/Task/Biorhythms/EasyLang/biorhythms.easy +++ b/Task/Biorhythms/EasyLang/biorhythms.easy @@ -8,35 +8,29 @@ func day d$ . d = number substr d$ 9 2 return 367 * y - 7 * (y + (m + 9) div 12) div 4 + 275 * m div 9 + d - 730530 . -textsize 4 +gtextsize 4 func init b$ d$ . - linewidth 0.2 - move 50 0 - line 50 100 - move 0 50 - line 100 50 + glinewidth 0.2 + gline 50 0 50 100 + gline 0 50 100 50 for d = -20 to 20 - move x 50 - circle 0.5 + gcircle x 50 0.5 x += 2.5 . - move 4 94 - text b$ - move 4 88 - text d$ + gtext 4 94 b$ + gtext 4 88 d$ days = day date$ - day birth$ - move 4 80 - text days & " days" + gtext 4 80 days & " days" return days . -proc cycle now cyc t$ col . . - color col - move 4 cyc * 1.2 - 20 - text t$ - linewidth 0.5 +proc cycle now cyc t$ col . + gcolor col + gtext 4 cyc * 1.2 - 20 t$ + glinewidth 0.5 for d = now - 20 to now + 20 - p = 20 * sin (360 * d / cyc) - line x 50 + p + yp = y + y = 50 + 20 * sin (360 * d / cyc) + if x > 0 : gline (x - 2.5) yp x y x += 2.5 . . diff --git a/Task/Bitcoin-address-validation/JavaScript/bitcoin-address-validation.js b/Task/Bitcoin-address-validation/JavaScript/bitcoin-address-validation.js new file mode 100644 index 0000000000..c53ff79496 --- /dev/null +++ b/Task/Bitcoin-address-validation/JavaScript/bitcoin-address-validation.js @@ -0,0 +1,53 @@ +const digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +async function hash(bytes) { + return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); +} + +function toBytes(n, length) { + const bytes = []; + + for (let i = BigInt(length)-1n; i >= 0; i--) { + bytes.push((n >> i * 8n) & 0xffn); + } + + return bytes; +} + +function decode_base58(bc, length) { + let n = 0n; + for (const char of bc) { + n = n * 58n + BigInt(digits58.indexOf(char)); + } + + return toBytes(n, length); +} + +function toUint8Array(bytes) { + let nums = [] + + for (const byte of bytes) { + nums.push(Number(byte)); + } + + return new Uint8Array(nums); +} + +async function checkBc(bc) { + const bcbytes = decode_base58(bc, 25); + + const slice = bcbytes.slice(0, bcbytes.length-4); + const first = toUint8Array(slice); + + const firstHash = await hash(first); + const secondHash = await hash(firstHash); + + const checksum = toUint8Array(bcbytes.slice(-4)); + + return JSON.stringify(checksum) == JSON.stringify(toUint8Array(secondHash.slice(0, 4))); +} + +(async () => { + console.log(await checkBc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i')); + console.log(await checkBc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")) +})(); diff --git a/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy index 2edb8d1510..3aaf5eda4f 100644 --- a/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy +++ b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy @@ -1,19 +1,18 @@ -proc quadraticbezier x1 y1 x2 y2 x3 y3 nseg . . +sysconf topleft +proc quadraticbezier x1 y1 x2 y2 x3 y3 nseg . for i = 0 to nseg t = i / nseg t1 = 1 - t a = t1 * t1 b = 2 * t * t1 c = t * t - currx = a * x1 + b * x2 + c * x3 + 0.5 - curry = a * y1 + b * y2 + c * y3 + 0.5 - if i = 0 - move currx curry - else - line currx curry - . + px = x + py = y + x = a * x1 + b * x2 + c * x3 + 0.5 + y = a * y1 + b * y2 + c * y3 + 0.5 + if i > 0 : gline px py x y . . -linewidth 0.5 -clear +glinewidth 0.5 +gclear quadraticbezier 1 1 30 37 59 1 100 diff --git a/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy b/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy index 536d330933..b0a250c7ec 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy +++ b/Task/Bitmap-Bresenhams-line-algorithm/EasyLang/bitmap-bresenhams-line-algorithm.easy @@ -1,8 +1,7 @@ -proc pset x y . . - move x / 4 y / 4 - rect 0.25 0.25 +proc pset x y . + grect x / 4 y / 4 0.25 0.25 . -proc drawline x0 y0 x1 y1 . . +proc drawline x0 y0 x1 y1 . dx = abs (x1 - x0) sx = -1 if x0 < x1 diff --git a/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl b/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl index 9e4335844f..695abf3123 100644 --- a/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl +++ b/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl @@ -1,67 +1,73 @@ -|00 @System [ &vector $2 &wst $1 &rst $1 &eaddr $2 &ecode $1 &pad $1 &r $2 &g $2 &b $2 &debug $1 &halt $1 ] -|10 @Console [ &vector $2 &read $1 &pad $5 &write $1 &error $1 ] +%\n { 0a } %\s { 20 } %\0 { 00 } +%newline { [ LIT2 \n -Console/write ] DEO } + +%not { #ff EOR } +%and { AND } +%or { ORA } +%xor { EOR } +%shl { #40 SFT SFT } +%shr { SFT } +%rol { #40 SFT #00 ROT ROT SFT2 ORA } +%ror { SWP #00 ROT SFT2 ORA } + +|18 @Console/write + +|100 + +#0a02 +DUP2 SWP ;msgs/a print/arg ;msgs/b print/arg +bitwise -( program ) -|0100 @on-reset ( -> ) - #0a02 - DUP2 SWP ;Labels/a ;Labels/b - bitwise - halt BRK @bitwise ( a b -- ) - ;Labels/not ;Labels/a ;Labels/equ DUP2 [ POP #ff EOR ] - ;Labels/and DUP2 [ AND ] - ;Labels/or DUP2 [ ORA ] - ;Labels/xor DUP2 [ EOR ] - ;Labels/shl DUP2 [ #40 SFT SFT ] - ;Labels/shr DUP2 [ SFT ] - ;Labels/rol DUP2 [ #40 SFT #00 ROT ROT SFT2 ORA ] - ;Labels/ror [ SWP #00 ROT SFT2 ORA ] - JMP2r + ;msgs/not print/str ;msgs/a print/str + ;msgs/equ print/str OVR not print/result + ;msgs/and print/label DUP2 and print/result + ;msgs/or print/label DUP2 or print/result + ;msgs/xor print/label DUP2 xor print/result + ;msgs/shl print/label DUP2 shl print/result + ;msgs/shr print/label DUP2 shr print/result + ;msgs/rol print/label DUP2 rol print/result + ;msgs/ror print/label ror !print/result -@halt ( -- ) - #01 .System/halt DEO - BRK +@print/label ( label* -- ) + ;msgs/a /str + /str + ;msgs/b /str + ;msgs/equ !/str -@ ( a name* -- ) - ;Labels/equ - JMP2r - -@ ( a -- ) - ;Labels/newline - JMP2r - -@ ( label* -- ) - ;Labels/a - - ;Labels/b - ;Labels/equ - JMP2r - -@ ( byte -- ) +@print/byte ( byte -- ) [ LIT "$ ] .Console/write DEO - DUP #04 SFT /l - &l ( -- ) - #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO - JMP2r + DUP #04 SFT /nibble + ( >> ) + +@print/nibble ( -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO + JMP2r -@ ( str* -- ) - &while ( -- ) - LDAk .Console/write DEO - INC2 LDAk ?&while +@print/arg ( a name* -- ) + /str ;msgs/equ /str + ( >> ) + +@print/result ( a -- ) + /byte newline + JMP2r + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str POP2 JMP2r -@Labels - &a "a 20 $1 - &b "b 20 $1 - &equ "= 20 $1 - &newline 0a $1 - ¬ "NOT 20 $1 - &and "AND 20 $1 - &or "OR 20 $1 - &xor "XOR 20 $1 - &shl "SHL 20 $1 - &shr "SHR 20 $1 - &rol "ROL 20 $1 - &ror "ROR 20 $1 +@msgs [ + &a "a \s \0 + &b "b \s \0 + &equ "= \s \0 + ¬ "NOT \s \0 + &and "AND \s \0 + &or "OR \s \0 + &xor "XOR \s \0 + &shl "SHL \s \0 + &shr "SHR \s \0 + &rol "ROL \s \0 + &ror "ROR \s \0 ] diff --git a/Task/Blum-integer/EasyLang/blum-integer.easy b/Task/Blum-integer/EasyLang/blum-integer.easy index 7b73286f92..603f83fb51 100644 --- a/Task/Blum-integer/EasyLang/blum-integer.easy +++ b/Task/Blum-integer/EasyLang/blum-integer.easy @@ -2,32 +2,27 @@ fastfunc semiprim n . d = 3 while d * d <= n while n mod d = 0 - if c = 2 - return 0 - . + if c = 2 : return 0 n /= d c += 1 . d += 2 . - if c = 1 - return n - . + if c = 1 : return n + return 0 . print "The first 50 Blum integers:" n = 3 -numfmt 0 4 +numfmt 4 0 repeat prim1 = semiprim n - if prim1 <> 0 - if prim1 mod 4 = 3 - prim2 = n div prim1 - if prim2 <> prim1 and prim2 mod 4 = 3 - c += 1 - if c <= 50 - write n - if c mod 10 = 0 ; print "" ; . - . + if prim1 <> 0 and prim1 mod 4 = 3 + prim2 = n div prim1 + if prim2 <> prim1 and prim2 mod 4 = 3 + c += 1 + if c <= 50 + write n + if c mod 10 = 0 : print "" . . . diff --git a/Task/Blum-integer/Rust/blum-integer.rs b/Task/Blum-integer/Rust/blum-integer.rs new file mode 100644 index 0000000000..59feb1041f --- /dev/null +++ b/Task/Blum-integer/Rust/blum-integer.rs @@ -0,0 +1,91 @@ +fn is_prime_mod4(n: u32) -> bool { + match n { + 0..3 => false, + _ if n % 2 == 0 => false, + _ if n % 3 == 0 => n == 3, + _ if n % 4 == 3 => { + for d in (5..).step_by(2).take_while(|&d| d * d <= n) { + if n % d == 0 { + return false; + } + } + + true + } + _ => false, + } +} + +fn least_prime_factor(n: u32) -> u32 { + match n { + 1 => 1, + _ if n % 3 == 0 => 3, + _ if n % 5 == 0 => 5, + _ => { + for d in (7..).step_by(2).take_while(|&d| d * d <= n) { + if n % d == 0 { + return d; + } + } + + n + } + } +} + +fn blums() -> Blum { + Blum { number: 1 } +} + +struct Blum { + number: u32, +} + +impl Iterator for Blum { + type Item = u32; + + fn next(&mut self) -> Option { + loop { + let number = self.number; + let p = least_prime_factor(number); + + self.number = number.checked_add(if number % 5 == 3 { 4 } else { 2 })?; + + if p % 4 == 3 { + let q = number / p; + + if p != q && is_prime_mod4(q) { + return Some(number); + } + } + } + } +} + +fn main() { + println!("First 50 Blum integers:"); + + let last_digit_counts = blums() + .zip(1..=400_000) + .inspect(|&(blum, i)| match i { + 1..=50 => print!("{blum:>3}{}", if i % 10 != 0 { " " } else { "\n" }), + 51 => println!(), + 26_828 | 100_000 | 200_000 | 300_000 | 400_000 => { + println!("The {i:>6}th Blum integer is: {blum:>7}"); + } + _ => {} + }) + .fold([0; 10], |mut acc, (blum, _)| { + acc[blum as usize % 10] += 1; + + acc + }); + + println!("\nPercent distribution of the first 400000 Blum integers:"); + for i in [1, 3, 7, 9] { + println!( + "\t{:2.3}% end in {i}", + last_digit_counts[i] as f64 / 4_000.0 + ); + } +} diff --git a/Task/Boolean-values/Ballerina/boolean-values.ballerina b/Task/Boolean-values/Ballerina/boolean-values.ballerina new file mode 100644 index 0000000000..637f05cfc0 --- /dev/null +++ b/Task/Boolean-values/Ballerina/boolean-values.ballerina @@ -0,0 +1,12 @@ +import ballerina/io; + +public function main() { + boolean markova = true; + boolean keys = false; + if markova { + io:println("Alicia Markova was a famous ballerina."); + } + if !keys { + io:println("Alicia Keys is a famous singer."); + } +} diff --git a/Task/Box-the-compass/EasyLang/box-the-compass.easy b/Task/Box-the-compass/EasyLang/box-the-compass.easy index 03c6aa33d7..0bb02b538d 100644 --- a/Task/Box-the-compass/EasyLang/box-the-compass.easy +++ b/Task/Box-the-compass/EasyLang/box-the-compass.easy @@ -17,7 +17,7 @@ func$ expand cp$ . h$ = strchar (strcode substr r$ 1 1 - 32) return h$ & substr r$ 2 999 . -proc main . . +proc main . cp$[] = [ "N" "NbE" "N-NE" "NEbN" "NE" "NEbE" "E-NE" "EbN" "E" "EbS" "E-SE" "SEbE" "SE" "SEbS" "S-SE" "SbE" "S" "SbW" "S-SW" "SWbS" "SW" "SWbW" "W-SW" "WbS" "W" "WbN" "W-NW" "NWbW" "NW" "NWbN" "N-NW" "NbW" ] print "Index Degrees Compass point" print "----- ------- -------------" diff --git a/Task/Box-the-compass/Standard-ML/box-the-compass.ml b/Task/Box-the-compass/Standard-ML/box-the-compass.ml new file mode 100644 index 0000000000..a523bcd20a --- /dev/null +++ b/Task/Box-the-compass/Standard-ML/box-the-compass.ml @@ -0,0 +1,29 @@ +local + val box = Array.fromList [ + "North", "North by east", "North-northeast", "Northeast by north", + "Northeast", "Northeast by east", "East-northeast", "East by north", + "East", "East by south", "East-southeast", "Southeast by east", + "Southeast", "Southeast by south", "South-southeast", "South by east", + "South", "South by west", "South-southwest", "Southwest by south", + "Southwest", "Southwest by west", "West-southwest", "West by south", + "West", "West by north", "West-northwest", "Northwest by west", + "Northwest", "Northwest by north", "North-northwest", "North by west"] + + val phis = Array.fromList [ + 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, + 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, + 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, + 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 + ] +in +val _ = Array.app (fn phi => + let val i = Real.trunc ((phi * 32.0) / 360.0 + 0.5) mod 32 + in print (StringCvt.padLeft #" " 3 (Int.toString (i+1)) + ^ " " + ^ StringCvt.padLeft #" " 18 (Array.sub (box, i)) + ^ " " + ^ Real.fmt (StringCvt.FIX (SOME 2)) phi + ^ "\n") + end) + phis +end diff --git a/Task/Boyer-Moore-string-search/C-sharp/boyer-moore-string-search.cs b/Task/Boyer-Moore-string-search/C-sharp/boyer-moore-string-search.cs new file mode 100644 index 0000000000..6064d3eccb --- /dev/null +++ b/Task/Boyer-Moore-string-search/C-sharp/boyer-moore-string-search.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +/// +/// An implementation of the Boyer-Moore string search algorithm. +/// It finds all occurrences of a pattern in a text, performing a case-insensitive search on ASCII characters. +/// +/// For all full description of the algorithm visit: +/// https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm +/// +public static class BoyerMooreStringSearch +{ + public static void Main(string[] args) + { + List texts = new List + { + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandshowsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustrate", + "Farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + }; + + List patterns = new List { "TCTA", "TAATAAA", "word", "needle", "put", "and", "alfalfa" }; + + for (int i = 0; i < texts.Count; i++) + { + Console.WriteLine("text" + (i + 1) + " = " + texts[i]); + } + Console.WriteLine(); + + for (int i = 0; i < patterns.Count; i++) + { + int j = (i < 5) ? i : i - 1; + Console.WriteLine("Found \"" + patterns[i] + "\" in 'text" + (j + 1) + "' at indexes " + + string.Join(", ", StringSearch(texts[j], patterns[i]))); + } + } + + /// + /// Return a list of indexes at which the given pattern matches the given text. + /// + private static List StringSearch(string aText, string aPattern) + { + if (string.IsNullOrEmpty(aPattern) || string.IsNullOrEmpty(aText) || aText.Length < aPattern.Length) + { + return new List(); + } + + List matches = new List(); + + // Preprocessing + List> R = BadCharacterTable(aPattern); + int[] L = GoodSuffixTable(aPattern); + int[] F = FullShiftTable(aPattern); + + int k = aPattern.Length - 1; // Represents the alignment of the end of aPattern relative to aText + int previousK = -1; // Represents the above alignment in the previous phase + while (k < aText.Length) + { + int i = aPattern.Length - 1; // Index of the character to compare in aPattern + int h = k; // Index of the character to compare in aText + while (i >= 0 && h > previousK && aPattern[i] == aText[h]) + { + i -= 1; + h -= 1; + } + if (i == -1 || h == previousK) + { // Match has been found + matches.Add(k - aPattern.Length + 1); + k += (aPattern.Length > 1) ? aPattern.Length - F[1] : 1; + } + else + { // No match, shift by the maximum of the bad character and good suffix rules + int suffixShift; + int charShift = i - R[AlphabetIndex(aText[h])][i]; + if (i + 1 == aPattern.Length) + { // Mismatch occurred on the first character + suffixShift = 1; + } + else if (L[i + 1] == -1) + { // Matched suffix does not appear anywhere in aPattern + suffixShift = aPattern.Length - F[i + 1]; + } + else + { // Matched suffix appears in aPattern + suffixShift = aPattern.Length - 1 - L[i + 1]; + } + int shift = Math.Max(charShift, suffixShift); + if (shift >= i + 1) + { // Galil's rule + previousK = k; + } + k += shift; + } + } + return matches; + } + + /// + /// Create the shift table, F, for the given text, which is an array such that + /// F[i] is the length of the longest suffix of, aText.substring(i), which is also a prefix of the given text. + /// + /// Use case: If a mismatch occurs at character index i - 1 in the pattern, + /// the magnitude of the shift of the pattern, P, relative to the text is: P.length() - F[i]. + /// + private static int[] FullShiftTable(string aText) + { + int[] F = new int[aText.Length]; + int[] Z = FundamentalPreprocess(aText); + int longest = 0; + Array.Reverse(Z); + for (int i = 0; i < Z.Length; i++) + { + int zv = Z[i]; + if (zv == i + 1) + { + longest = Math.Max(zv, longest); + } + F[F.Length - i - 1] = longest; + } + return F; + } + + /// + /// Create the good suffix table, L, for the given text, which is an array such that + /// L[i] = k, is the largest index in the given text, S, + /// such that S.substring(i) matches a suffix of S.substring(0, k). + /// + /// Use case: If a mismatch of characters occurs at index i - 1 in the pattern, P, + /// then a shift of magnitude, P.length() - L[i], is such that no instances of the pattern in the text are omitted. + /// Furthermore, a suffix of P.substring(0, L[i]) matches the same substring of the text that was matched by a + /// suffix in the pattern on the previous matching attempt. + /// In the case that L[i] = -1, the full shift table must be used. + /// + private static int[] GoodSuffixTable(string aText) + { + int[] L = Enumerable.Repeat(-1, aText.Length).ToArray(); + string reversed = new string(aText.Reverse().ToArray()); + int[] N = FundamentalPreprocess(reversed); + Array.Reverse(N); + for (int j = 0; j < aText.Length - 1; j++) + { + int i = aText.Length - N[j]; + if (i != aText.Length) + { + L[i] = j; + } + } + return L; + } + + /// + /// Create the bad character table, R, for the given text, + /// which is a list indexed by the ASCII value of a character, C, in the given text. + /// + /// Use case: The entry at index i of R is a list of size: 1 + length of the given text. + /// This inner list gives at each index j the next position at which character C will be found + /// while traversing the given text from right to left starting from index j. + /// + private static List> BadCharacterTable(string aText) + { + if (string.IsNullOrEmpty(aText)) + { + return new List>(); + } + + List> R = Enumerable.Range(0, ALPHABET_SIZE) + .Select(i => new List(Enumerable.Repeat(-1, 1))).ToList(); + List alpha = Enumerable.Repeat(-1, ALPHABET_SIZE).ToList(); + + for (int i = 0; i < aText.Length; i++) + { + alpha[AlphabetIndex(aText[i])] = i; + for (int j = 0; j < alpha.Count; j++) + { + R[j].Add(alpha[j]); + } + } + return R; + } + + /// + /// Create the fundamental preprocess, Z, of the given text, which is an array such that + /// Z[i] is the length of the substring of the given text beginning at index i which is also a prefix of the text. + /// + private static int[] FundamentalPreprocess(string aText) + { + if (string.IsNullOrEmpty(aText)) + { + return new int[0]; + } + if (aText.Length == 1) + { + return new int[] { 1 }; + } + + int[] Z = new int[aText.Length]; + Z[0] = aText.Length; + Z[1] = MatchLength(aText, 0, 1); + for (int i = 2; i <= Z[1]; i++) + { + Z[i] = Z[1] - i + 1; + } + + // Define the left and right limits of the z-box + int left = 0; + int right = 0; + for (int i = 2 + Z[1]; i < aText.Length; i++) + { + if (i <= right) + { // i falls within existing z-box + int k = i - left; + int b = Z[k]; + int a = right - i + 1; + if (b < a) + { // b ends within existing z-box + Z[i] = b; + } + else + { // b ends at or after the end of the z-box, + // an explicit match to the right of the z-box is required + Z[i] = a + MatchLength(aText, a, right + 1); + left = i; + right = i + Z[i] - 1; + } + } + else + { // i does not fall within existing z-box + Z[i] = MatchLength(aText, 0, i); + if (Z[i] > 0) + { + left = i; + right = i + Z[i] - 1; + } + } + } + return Z; + } + + /// + /// Return the length of the match of the two substrings of the given text beginning at each of the given indexes. + /// + private static int MatchLength(string aText, int aIndexOne, int aIndexTwo) + { + if (aIndexOne == aIndexTwo) + { + return aText.Length - aIndexOne; + } + + int matchCount = 0; + while (aIndexOne < aText.Length && aIndexTwo < aText.Length + && aText[aIndexOne] == aText[aIndexTwo]) + { + matchCount += 1; + aIndexOne += 1; + aIndexTwo += 1; + } + return matchCount; + } + + /// + /// Return the ASCII index of the given character, if it is such, otherwise throw an illegal argument exception. + /// + private static int AlphabetIndex(char aChar) + { + int result = (int)aChar; + if (result >= ALPHABET_SIZE) + { + throw new ArgumentException("Not an ASCII character:" + aChar); + } + return result; + } + + /* The range of ASCII characters is 0..255, both inclusive. */ + private const int ALPHABET_SIZE = 256; +} diff --git a/Task/Boyer-Moore-string-search/EasyLang/boyer-moore-string-search.easy b/Task/Boyer-Moore-string-search/EasyLang/boyer-moore-string-search.easy new file mode 100644 index 0000000000..c81b25fa98 --- /dev/null +++ b/Task/Boyer-Moore-string-search/EasyLang/boyer-moore-string-search.easy @@ -0,0 +1,67 @@ +# only works with ascii strings +# +func is_prefix &needle$[] pos . + pos -= 1 + for i to len needle$[] - pos + if needle$[i] <> needle$[pos + i] : return 0 + . + return 1 +. +func suffix_size &needle$[] pos . + i = pos + j = len needle$[] + while i >= 1 and needle$[i] = needle$[j] + i -= 1 + j -= 1 + size += 1 + . + return size +. +proc mk_good_tbl &needle$[] &tbl[] . + nlen = len needle$[] + len tbl[] nlen + lastpre = nlen + 1 + for i = nlen downto 1 + if is_prefix needle$[] i = 1 : lastpre = i + tbl[nlen - i + 1] = lastpre - i + nlen + . + for i to nlen - 1 + size = suffix_size needle$[] i + tbl[size + 1] = nlen - i + size + . +. +proc mk_bad_tbl &needle$[] &tbl[] . + len tbl[] 128 + for i to 128 : tbl[i] = len needle$[] + for i to len needle$[] - 1 + tbl[strcode needle$[i]] = len needle$[] - i + . +. +func[] find hayst$ needle$ . + if needle$ = "" : return [ ] + needle$[] = strchars needle$ + hayst$[] = strchars hayst$ + mk_bad_tbl needle$[] bad_tbl[] + mk_good_tbl needle$[] good_tbl[] + nelen = len needle$[] + i = nelen + while i <= len hayst$[] + j = nelen + while j > 1 and needle$[j] = hayst$[i] + i -= 1 + j -= 1 + . + if needle$[j] = hayst$[i] + r[] &= i + i += nelen + else + i += higher good_tbl[nelen - j + 1] bad_tbl[strcode hayst$[i]] + . + . + return r[] +. +texts$[] = [ "GCTAGCTCTACGAGTCTA" "GGCTATAATGCGTA" "there would have been a time for such a word" "needle need noodle needle" "alfalfa" ] +pat$[] = [ "TCTA" "TAATAAA" "word" "needle" "alfa" ] +for i to len texts$[] + print pat$[i] & " ? " & texts$[i] & " -> " & find texts$[i] pat$[i] +. diff --git a/Task/Boyer-Moore-string-search/Go/boyer-moore-string-search.go b/Task/Boyer-Moore-string-search/Go/boyer-moore-string-search.go new file mode 100644 index 0000000000..83c6bfb18d --- /dev/null +++ b/Task/Boyer-Moore-string-search/Go/boyer-moore-string-search.go @@ -0,0 +1,65 @@ +package main + +import ( + "fmt" + "strings" +) + +func display(numbers []int32) { + fmt.Print("[") + for i, num := range numbers { + if i > 0 { + fmt.Print(", ") + } + fmt.Print(num) + } + fmt.Println("]") +} + +func stringSearchSingle(haystack, needle string) int32 { + index := strings.Index(haystack, needle) + return int32(index) +} + +func stringSearch(haystack, needle string) []int32 { + var result []int32 + var start int64 = 0 + + for start < int64(len(haystack)) { + haystackReduced := haystack[start:] + index := stringSearchSingle(haystackReduced, needle) + + if index >= 0 { + result = append(result, int32(start)+index) + start += int64(index) + int64(len(needle)) + } else { + break + } + } + + return result +} + +func main() { + texts := []string{ + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk.", + } + + patterns := []string{"TCTA", "TAATAAA", "word", "needle", "and", "alfalfa"} + + for i := 0; i < len(texts); i++ { + fmt.Printf("text%d = %s\n", i+1, texts[i]) + } + fmt.Println() + + for i := 0; i < len(texts); i++ { + indexes := stringSearch(texts[i], patterns[i]) + fmt.Printf("Found \"%s\" in 'text%d' at indexes ", patterns[i], i+1) + display(indexes) + } +} diff --git a/Task/Boyer-Moore-string-search/JavaScript/boyer-moore-string-search.js b/Task/Boyer-Moore-string-search/JavaScript/boyer-moore-string-search.js new file mode 100644 index 0000000000..4f1709739c --- /dev/null +++ b/Task/Boyer-Moore-string-search/JavaScript/boyer-moore-string-search.js @@ -0,0 +1,52 @@ +function display(numbers) { + console.log(`[${numbers.join(", ")}]`); +} + +function string_search_single(haystack, needle) { + const index = haystack.indexOf(needle); + return index; +} + +function string_search(haystack, needle) { + const result = []; + let start = 0; + let index = 0; + + while (index >= 0 && start < haystack.length) { + const haystackReduced = haystack.substring(start); + index = string_search_single(haystackReduced, needle); + if (index >= 0) { + result.push(start + index); + start += index + needle.length; + } + } + return result; +} + +function main() { + const texts = [ + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk.", + ]; + + const patterns = ["TCTA", "TAATAAA", "word", "needle", "and", "alfalfa"]; + + for (let i = 0; i < texts.length; ++i) { + console.log(`text${i + 1} = ${texts[i]}`); + } + console.log(); + + for (let i = 0; i < texts.length; ++i) { + const indexes = string_search(texts[i], patterns[i]); + console.log( + `Found "${patterns[i]}" in 'text${i + 1}' at indexes ` + ); + display(string_search(texts[i], patterns[i])); + } +} + +main(); diff --git a/Task/Boyer-Moore-string-search/Rust/boyer-moore-string-search.rs b/Task/Boyer-Moore-string-search/Rust/boyer-moore-string-search.rs new file mode 100644 index 0000000000..15cf2485cd --- /dev/null +++ b/Task/Boyer-Moore-string-search/Rust/boyer-moore-string-search.rs @@ -0,0 +1,62 @@ +fn display(numbers: &Vec) { + print!("["); + for (i, num) in numbers.iter().enumerate() { + if i > 0 { + print!(", "); + } + print!("{}", num); + } + println!("]"); +} + +fn string_search_single(haystack: &str, needle: &str) -> i32 { + // Rust's standard library doesn't have Boyer-Moore searcher directly, + // but we can use the built-in find method which is efficient + match haystack.find(needle) { + Some(index) => index as i32, + None => -1, + } +} + +fn string_search(haystack: &str, needle: &str) -> Vec { + let mut result: Vec = Vec::new(); + let mut start: usize = 0; + + while start < haystack.len() { + let haystack_reduced = &haystack[start..]; + let index = string_search_single(haystack_reduced, needle); + + if index >= 0 { + result.push((start as i32) + index); + start += index as usize + needle.len(); + } else { + break; + } + } + + result +} + +fn main() { + let texts = vec![ + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + ]; + + let patterns = vec!["TCTA", "TAATAAA", "word", "needle", "and", "alfalfa"]; + + for i in 0..texts.len() { + println!("text{} = {}", i + 1, texts[i]); + } + println!(); + + for i in 0..texts.len() { + let indexes = string_search(texts[i], patterns[i]); + print!("Found \"{}\" in 'text{}' at indexes ", patterns[i], i + 1); + display(&indexes); + } +} diff --git a/Task/Boyer-Moore-string-search/Scala/boyer-moore-string-search.scala b/Task/Boyer-Moore-string-search/Scala/boyer-moore-string-search.scala new file mode 100644 index 0000000000..e33f56aa21 --- /dev/null +++ b/Task/Boyer-Moore-string-search/Scala/boyer-moore-string-search.scala @@ -0,0 +1,329 @@ +import scala.collection.mutable.ListBuffer +import scala.collection.immutable.Vector // Using Vector for the bad character table outer structure + +/** + * An implementation of the Boyer-Moore string search algorithm in Scala. + * It finds all occurrences of a pattern in a text, performing a case-sensitive search on ASCII characters. + * (Note: The original Java comment mentioned case-insensitive, but the code was case-sensitive ASCII). + * + * For a full description of the algorithm visit: + * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm + */ +object BoyerMooreStringSearch { + + /* The range of ASCII characters is 0..255, both inclusive. */ + private final val ALPHABET_SIZE = 256 + + def main(args: Array[String]): Unit = { + val texts = List( + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandshowsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustrate", + "Farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + ) + + val patterns = List("TCTA", "TAATAAA", "word", "needle", "put", "and", "alfalfa") + + texts.zipWithIndex.foreach { case (text, i) => + println(s"text${i + 1} = $text") + } + println() + + patterns.zipWithIndex.foreach { case (pattern, i) => + // Replicate the original Java logic for selecting the text index 'j' + val j = if (i < 5) i else i - 1 + if (j >= 0 && j < texts.length) { // Ensure j is a valid index + val textToSearch = texts(j) + val matches = stringSearch(textToSearch, pattern) + // Use mkString for cleaner list output + println(s"""Found "$pattern" in 'text${j + 1}' at indexes [${matches.mkString(", ")}]""") + } else { + println(s"Skipping pattern '$pattern' - calculated text index $j is out of bounds.") + } + } + } + + /** + * Return a list of indexes at which the given pattern matches the given text. + */ + private def stringSearch(aText: String, aPattern: String): List[Int] = { + if (aPattern.isEmpty || aText.isEmpty || aText.length < aPattern.length) { + return List.empty[Int] // Use Scala's immutable empty list + } + + val matches = ListBuffer[Int]() // Use mutable ListBuffer for efficient appending + + // Preprocessing + val R = badCharacterTable(aPattern) // Returns Vector[Vector[Int]] + val L = goodSuffixTable(aPattern) // Returns Array[Int] + val F = fullShiftTable(aPattern) // Returns Array[Int] + + val m = aPattern.length + val n = aText.length + + var k = m - 1 // Represents the alignment of the end of aPattern relative to aText + var previousK = -1 // Represents the above alignment in the previous phase (for Galil's rule) + + while (k < n) { + var i = m - 1 // Index of the character to compare in aPattern (from right to left) + var h = k // Index of the character to compare in aText (aligned with i) + + // Character comparison loop + // Galil's rule optimization: h > previousK avoids re-comparing known matched prefix + while (i >= 0 && h > previousK && aPattern(i) == aText(h)) { + i -= 1 + h -= 1 + } + + if (i == -1 || h == previousK) { // Match has been found OR comparison skipped by Galil's rule up to a previously matched prefix + matches.append(k - m + 1) // Add start index of match + // Calculate shift based on the full shift table F for the next potential match + // F[1] represents the border length of P[1..m-1] + val shift = if (m > 1) m - F(1) else 1 + k += shift + // previousK is NOT reset here per original logic; it's related to shifts during *mismatches* + } else { // Mismatch occurred at aText(h) and aPattern(i) + // Bad Character Rule shift: + // R(char code)(index in pattern + 1) gives the index of the previous occurrence + // of the mismatched text character `aText(h)` in the pattern `aPattern` + // at or before index `i`. The +1 adjusts for the table structure. + val charShift = i - R(alphabetIndex(aText(h)))(i + 1) + + // Good Suffix Rule shift: + val suffixShift = + if (i + 1 == m) { // Mismatch occurred on the first character comparison (rightmost) + 1 + } else { + // L(i + 1) stores the starting index of the rightmost occurrence of + // the matched suffix P[i+1 .. m-1] in P that is not a suffix of P. + // F(i + 1) stores the length of the longest suffix of P[i+1..m-1] that is also a prefix of P. + if (L(i + 1) == -1) { // Matched suffix P[i+1..m-1] does not appear elsewhere in P preceded by a different char + // Shift based on the longest suffix of P[i+1..m-1] that is also a prefix of P (using F table) + m - F(i + 1) + } else { // Matched suffix P[i+1..m-1] appears starting at index L(i+1) + // Shift to align this previous occurrence with the text + m - 1 - L(i + 1) + } + } + + // Choose the maximum shift from the two rules + val shift = math.max(charShift, suffixShift) + + // Galil's rule: If the shift skips over the potential match area entirely, + // remember the current alignment `k` to optimize the next comparison loop. + if (shift >= i + 1) { + previousK = k + } + // Per original Java code: If Galil's rule does not apply (shift < i + 1), previousK is not modified here. + + k += shift // Apply the calculated shift + } + } // end while + + matches.toList // Convert mutable buffer to immutable list for the result + } + + /** + * Create the shift table, F, for the given pattern P, which is an array such that + * F[i] is the length of the longest suffix of P[i..m-1] which is also a prefix of P. + * + * Use case: If a mismatch occurs at character index i - 1 in the pattern, and the + * good suffix rule L[i] indicates no earlier occurrence, the shift is P.length() - F[i]. + */ + private def fullShiftTable(aPattern: String): Array[Int] = { + val m = aPattern.length + val F = new Array[Int](m) // Initialize with 0s + val Z = fundamentalPreprocess(aPattern) // Z[i] = length of longest substring starting at i that is prefix of pattern + val Z_reversed = Z.reverse // Reverse Z array + + var longest = 0 + // Iterate through the reversed Z array to build F from right-to-left effectively + for (i <- 0 until Z_reversed.length) { + val zv = Z_reversed(i) + // If Z value equals its length from the end, it's a suffix that's also a prefix + if (zv == i + 1) { + longest = math.max(zv, longest) + } + // Map the reversed index 'i' back to the original index for F + val originalIndex = m - 1 - i + if (originalIndex >= 0 && originalIndex < m) { // Bounds check + F(originalIndex) = longest + } + } + F + } + + /** + * Create the good suffix table, L', for the given pattern P (often denoted L' or L[i] in literature). + * L'[i] = k, is the largest index k < m such that P[i..m-1] is a suffix of P[0..k-1] + * and the character preceding the suffix P[k - (m-i) .. k-1] is different from P[i-1]. + * If no such k exists, L'[i] = -1. + * + * Use case: If a mismatch occurs at index i - 1, shift by m - 1 - L'[i]. + * This implementation calculates a related table L where L[i] stores j such that + * P[i..m-1] matches P[j-(m-i)..j]. + */ + private def goodSuffixTable(aPattern: String): Array[Int] = { + val m = aPattern.length + // Initialize L with -1. Size is m. + val L = Array.fill(m)(-1) + val reversedPattern = aPattern.reverse + // N[j] = length of longest substring starting at j that is prefix of reversedPattern + // This corresponds to matching suffixes of the original pattern. + val N = fundamentalPreprocess(reversedPattern) + // Reverse N to align indices with the original pattern's perspective + val N_reversed = N.reverse + + // N_reversed[j] = length of longest suffix of P ending at j that is also suffix of P + for (j <- 0 until m - 1) { + // i = position in P where the suffix match starts (from the right end) + val suffixLen = N_reversed(j) + val i = m - suffixLen + // L[i] should store the end position 'j' of the matching internal suffix. + // Condition i != m means the suffix is not the whole pattern itself. + if (i != m) { + if (i >= 0 && i < m) { // Bounds check for L index + L(i) = j + } + } + } + L + } + + /** + * Create the bad character table, R. + * R(c)(i) stores the index of the rightmost occurrence of character `c` + * in the pattern `P` at or before index `i-1`. If `c` does not occur + * before index `i`, it stores -1. + * The table is represented as Vector[Vector[Int]], indexed by char code, then pattern index + 1. + */ + private def badCharacterTable(aPattern: String): Vector[Vector[Int]] = { + if (aPattern.isEmpty) { + return Vector.empty // Return empty structure if pattern is empty + } + val m = aPattern.length + + // Use ListBuffer internally for efficient construction, then convert to Vector + val R_buffers = Array.fill(ALPHABET_SIZE)(ListBuffer(-1)) // Initialize inner lists with -1 + // 'alpha' tracks the most recent index seen for each character + val alpha = Array.fill(ALPHABET_SIZE)(-1) + + for (i <- 0 until m) { + val charIndex = alphabetIndex(aPattern(i)) + alpha(charIndex) = i // Update last seen position for this character + // For each character in the alphabet, append its *current* last seen position + // This builds the table column by column (for each pattern index i) + for (j <- 0 until ALPHABET_SIZE) { + R_buffers(j).append(alpha(j)) + } + } + // Convert the mutable buffers to immutable Vectors + R_buffers.map(_.toVector).toVector + } + + /** + * Create the fundamental preprocess array, Z, for the given text (or pattern). + * Z[i] is the length of the longest substring starting at index i + * which is also a prefix of the text. Z[0] is defined as the text length. + * This is used in calculating the Good Suffix and Full Shift tables. + */ + private def fundamentalPreprocess(aText: String): Array[Int] = { + val n = aText.length + if (n == 0) return Array.empty[Int] + if (n == 1) return Array(1) + + val Z = new Array[Int](n) + Z(0) = n + Z(1) = matchLength(aText, 0, 1) // Calculate Z[1] explicitly + + // Optimization for early part based on Z[1] + // Use Scala range 'until' for exclusive upper bound + var initial_z1_limit = math.min(Z(1) + 1, n) // Limit loop correctly + for (i <- 2 until initial_z1_limit) { + Z(i) = Z(1) - i + 1 + } + + // Define the left and right limits of the current Z-box [left, right] + var left = 0 + var right = 0 + // If Z(1) > 0, the initial Z-box is [1, Z(1)] ? No, Z-box related to previous calculations. + // Need to initialize left/right correctly based on Z[1] usage or start fresh. + // Let's restart Z-box calculation from where the optimization loop left off. + + val loopStart = if (Z(1) > 0) math.min(2 + Z(1), n) else 2 // Start after initial Z[1] optimization range + // Correct initialization of Z-box should be based on the *last* Z calculation that extended right boundary. + // Resetting left/right and letting the loop find the first Z-box might be simpler/safer. + left = 0 + right = 0 + + // Calculate remaining Z values using Z-box optimization + for (i <- loopStart until n) { + if (i <= right) { // i falls within existing Z-box [left, right] + val k = i - left // Corresponding index within the prefix + val b = Z(k) // Length of match starting at k + val a = right - i + 1 // Remaining length within the Z-box from i + + if (b < a) { // Match Z[k] is strictly contained within the Z-box suffix + Z(i) = b + } else { // Match Z[k] extends to or past the end of the Z-box + // Need explicit comparison beyond the Z-box + // Match length from text[a..] against text[right+1..] + val matchLen = matchLength(aText, a, right + 1) + Z(i) = a + matchLen + left = i // Start a new Z-box + right = i + Z(i) - 1 + } + } else { // i is outside the current Z-box + Z(i) = matchLength(aText, 0, i) // Calculate Z[i] by explicit comparison with prefix + if (Z(i) > 0) { // If a match is found, start a new Z-box + left = i + right = i + Z(i) - 1 + } + // else: Z[i] is 0, no Z-box formed, left/right remain unchanged + } + } + Z + } + + /** + * Return the length of the match of the two substrings of the given text + * beginning at each of the given indexes. + */ + private def matchLength(aText: String, aIndexOne: Int, aIndexTwo: Int): Int = { + if (aIndexOne < 0 || aIndexTwo < 0 || aIndexOne >= aText.length || aIndexTwo >= aText.length) { + return 0 // Added boundary checks + } + if (aIndexOne == aIndexTwo) { + // Match length from index to end of string + return aText.length - aIndexOne + } + + var matchCount = 0 + var idx1 = aIndexOne + var idx2 = aIndexTwo + // Use Scala's string indexing aText(idx) + while (idx1 < aText.length && idx2 < aText.length && aText(idx1) == aText(idx2)) { + matchCount += 1 + idx1 += 1 + idx2 += 1 + } + matchCount + } + + /** + * Return the ASCII index (0-255) of the given character. + * Throws IllegalArgumentException if the character code is outside the 0-255 range. + */ + private def alphabetIndex(aChar: Char): Int = { + val result = aChar.toInt + // Ensure character fits within the expected ASCII range for the table size + if (result < 0 || result >= ALPHABET_SIZE) { + // Consider if non-ASCII should be handled differently or error is correct. + // Sticking to original logic which assumes ASCII range 0-255. + throw new IllegalArgumentException(s"Character '$aChar' (code $result) is outside the expected ASCII range [0, ${ALPHABET_SIZE - 1}]") + } + result + } +} diff --git a/Task/Boyer-Moore-string-search/Wren/boyer-moore-string-search.wren b/Task/Boyer-Moore-string-search/Wren/boyer-moore-string-search.wren index f3410aec49..691956df2e 100644 --- a/Task/Boyer-Moore-string-search/Wren/boyer-moore-string-search.wren +++ b/Task/Boyer-Moore-string-search/Wren/boyer-moore-string-search.wren @@ -93,20 +93,20 @@ class BoyerMoore { } /* - * Uses the BoyerMoore class to find the indices of ALL non-overlapping matches of the specified substring - * and return a list of them. Returns an empty list if it's not a substring. + * Uses the BoyerMoore class to find the indices of ALL matches (overlapping or not) + * of the specified substring and return a list of them. + * Returns an empty list if it's not a substring. */ var indicesOf = Fn.new { |haystack, needle| var indices = [] var hc = haystack.bytes.count - var bc = needle.bytes.count var start = 0 while (true) { var haystack2 = haystack[start..-1] var index = BoyerMoore.indexOf(haystack2, needle) if (index == -1) return indices indices.add(start + index) - start = start + index + bc + start = start + index + 1 if (start >= hc) return indices } } @@ -117,9 +117,12 @@ var texts = [ "there would have been a time for such a word", "needle need noodle needle", "InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented", - "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk." + "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk.", + "Due to a malfunction, alfredo halfheartedly wore calfskin severalfold on behalf of alfa.", + "alfalfa", + "zzzzzz" ] -var pats = ["TCTA", "TAATAAA", "word", "needle", "put", "and", "alfalfa"] +var pats = ["TCTA", "TAATAAA", "word", "needle", "put", "and", "alfalfa", "alfa", "alfa", "zzz"] for (i in 0...texts.count) System.print("text%(i+1) = %(texts[i])") System.print() for (i in 0...pats.count) { diff --git a/Task/Brace-expansion/EasyLang/brace-expansion.easy b/Task/Brace-expansion/EasyLang/brace-expansion.easy index e9d898f73e..ef1c473c36 100644 --- a/Task/Brace-expansion/EasyLang/brace-expansion.easy +++ b/Task/Brace-expansion/EasyLang/brace-expansion.easy @@ -1,5 +1,5 @@ -procdecl getgroup depth . out$[] s$ ok . -proc getitem depth . s$ out$[] . +procdecl getgroup depth &out$[] &s$ &ok . +proc getitem depth &s$ &out$[] . out$[] = [ "" ] while s$ <> "" c$ = substr s$ 1 1 @@ -34,7 +34,7 @@ proc getitem depth . s$ out$[] . . . . -proc getgroup depth . out$[] s$ ok . +proc getgroup depth &out$[] &s$ &ok . out$[] = [ ] while s$ <> "" getitem depth s$ g$[] diff --git a/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy b/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy index 7fe5b6cc1a..c444438cb9 100644 --- a/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy +++ b/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy @@ -3,34 +3,23 @@ func sameDigits n b . repeat n = n div b until n = 0 - if n mod b <> f - return 0 - . + if n mod b <> f : return 0 . return 1 . func isBrazilian7 n . # n >= 7 - if n mod 2 = 0 - return 1 - . + if n mod 2 = 0 : return 1 for b = 2 to n - 2 - if sameDigits n b = 1 - return 1 - . + if sameDigits n b = 1 : return 1 . return 0 . func prime n . - if n mod 2 = 0 and n > 2 - return 0 - . + if n mod 2 = 0 and n > 2 : return 0 i = 3 - sq = sqrt n - while i <= sq - if n mod i = 0 - return 0 - . + while i <= sqrt n + if n mod i = 0 : return 0 i += 2 . return 1 diff --git a/Task/Brilliant-numbers/EasyLang/brilliant-numbers.easy b/Task/Brilliant-numbers/EasyLang/brilliant-numbers.easy index 410153777f..4c3d4f963c 100644 --- a/Task/Brilliant-numbers/EasyLang/brilliant-numbers.easy +++ b/Task/Brilliant-numbers/EasyLang/brilliant-numbers.easy @@ -1,34 +1,24 @@ fastfunc factor num . if num mod 2 = 0 - if num = 2 - return 1 - . + if num = 2 : return 1 return 2 . i = 3 while i <= sqrt num - if num mod i = 0 - return i - . + if num mod i = 0 : return i i += 2 . return 1 . func brilliant n . f1 = factor n - if f1 = 1 - return 0 - . + if f1 = 1 : return 0 f2 = n div f1 - if floor log10 f1 <> floor log10 f2 - return 0 - . - if factor f1 = 1 and factor f2 = 1 - return 1 - . + if floor log10 f1 <> floor log10 f2 : return 0 + if factor f1 = 1 and factor f2 = 1 : return 1 return 0 . -proc main . . +proc main . i = 2 while cnt < 100 if brilliant i = 1 diff --git a/Task/Brownian-tree/EasyLang/brownian-tree.easy b/Task/Brownian-tree/EasyLang/brownian-tree.easy index f0c9a26ba3..821e4bcf89 100644 --- a/Task/Brownian-tree/EasyLang/brownian-tree.easy +++ b/Task/Brownian-tree/EasyLang/brownian-tree.easy @@ -1,7 +1,6 @@ -color3 0 1 1 +gcolor3 0 1 1 len f[] 200 * 200 -move 50 50 -rect 0.5 0.5 +grect 50 50 0.5 0.5 f[100 * 200 + 100] = 1 n = 9000 while i < n @@ -19,12 +18,11 @@ while i < n break 1 . if f[y * 200 + x + 1] = 1 - move xo / 2 yo / 2 - rect 0.5 0.5 + grect xo / 2 yo / 2 0.5 0.5 f[yo * 200 + xo + 1] = 1 i += 1 if i mod 16 = 0 - color3 0.2 + i / n 1 1 + gcolor3 0.2 + i / n 1 1 sleep 0 . break 1 diff --git a/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl b/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl index 984eda7a85..fa91aa7235 100644 --- a/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl +++ b/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl @@ -6,5 +6,5 @@ guess ← ⍎¨input⍣(valid⊣) bulls ← +/= cows ← +/∊∧≠ game ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣) -random ← 1+4?9⍨ +random ← 1+4?9 moo ← 'You win!'⊣(random game⊢) diff --git a/Task/Bulls-and-cows/J/bulls-and-cows-1.j b/Task/Bulls-and-cows/J/bulls-and-cows-1.j index 74cb5c0578..3384f1c33b 100644 --- a/Task/Bulls-and-cows/J/bulls-and-cows-1.j +++ b/Task/Bulls-and-cows/J/bulls-and-cows-1.j @@ -1,5 +1,5 @@ -output=. [ 'Bulls: '&,:@'Cows: ' echo@,. ":@,. -valid =. *./@e.&'0123456789' *. 4 = # -guess =. [: ".&> :: ] $:^:(-.@valid)@(1!:1@1)@echo@'Guess:' -game =. [ $:^:(4 0-.@-:]) [ (+/@:= output@, e.+/@:*.~:) guess +output=. ['Bulls: '&,:@'Cows: 'echo@,.":@,. +valid =. *./@e.&Num_j_*.4=# +guess =. 0 ".&> [: > $:^:(-.@valid)@(1!:1@1)@echo@'Guess:'t.0 +game =. [ $:^:(4 0-.@-:]) [ (+/@:= output@, e. +/@:*. ~:) guess moo =. 'You win!'[ (1+4?9:) game ] diff --git a/Task/Bulls-and-cows/J/bulls-and-cows-2.j b/Task/Bulls-and-cows/J/bulls-and-cows-2.j index 9795e742c7..33fcb7bd55 100644 --- a/Task/Bulls-and-cows/J/bulls-and-cows-2.j +++ b/Task/Bulls-and-cows/J/bulls-and-cows-2.j @@ -1,9 +1,9 @@ U =. {{u^:(-.@:v)^:_.}} NB. apply u until v is true input =. 1!:1@1@echo@'Guess: ' output =. [ ('Bulls: ',:'Cows: ')echo@,.":@,. -isdigits=. *./@e.&'0123456789' +isdigits=. *./@e.&Num_j_ valid =. isdigits*.4=# -guess =. [:".&>input U(valid@]) +guess =. 0".&>input U(valid@]) bulls =. +/@:= cows =. [:+/e.*.~: game =. ([:output [(bulls,cows) guess)U(4 0-:]) diff --git a/Task/Burrows-Wheeler-transform/EasyLang/burrows-wheeler-transform.easy b/Task/Burrows-Wheeler-transform/EasyLang/burrows-wheeler-transform.easy index d3197d271a..2e078b2b25 100644 --- a/Task/Burrows-Wheeler-transform/EasyLang/burrows-wheeler-transform.easy +++ b/Task/Burrows-Wheeler-transform/EasyLang/burrows-wheeler-transform.easy @@ -3,7 +3,7 @@ stx$ = "¹" etx$ = "²" # -proc sort . d$[] . +proc sort &d$[] . for i = 2 to len d$[] h$ = d$[i] j = i - 1 @@ -22,16 +22,12 @@ func$ bwt s$ . tbl$[] &= b$ & a$ . sort tbl$[] - for s$ in tbl$[] - r$ &= substr s$ len s$ 1 - . + for s$ in tbl$[] : r$ &= substr s$ len s$ 1 return r$ . func$ ibwt r$ . le = len r$ - for i to le - tbl$[] &= "" - . + for i to le : tbl$[] &= "" for j to le for i to le tbl$[i] = substr r$ i 1 & tbl$[i] diff --git a/Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js b/Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js new file mode 100644 index 0000000000..dc7efff102 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/JavaScript/burrows-wheeler-transform.js @@ -0,0 +1,76 @@ +class BWT { + static STX = "\u0002"; + static ETX = "\u0003"; + + static bwt(s) { + if (s.includes(BWT.STX) || s.includes(BWT.ETX)) { + throw new Error("String cannot contain STX or ETX"); + } + + const ss = BWT.STX + s + BWT.ETX; + const table = []; + for (let i = 0; i < ss.length; i++) { + const before = ss.substring(i); + const after = ss.substring(0, i); + table.push(before + after); + } + table.sort(); + + let sb = ""; + for (const str of table) { + sb += str.charAt(str.length - 1); + } + return sb; + } + + static ibwt(r) { + const len = r.length; + const table = []; + for (let i = 0; i < len; ++i) { + table.push(""); + } + for (let j = 0; j < len; ++j) { + for (let i = 0; i < len; ++i) { + table[i] = r.charAt(i) + table[i]; + } + table.sort(); + } + for (const row of table) { + if (row.endsWith(BWT.ETX)) { + return row.substring(1, len - 1); + } + } + return ""; + } + + static makePrintable(s) { + // substitute ^ for STX and | for ETX to print results + return s.replace(BWT.STX, "^").replace(BWT.ETX, "|"); + } + + static main() { + const tests = [ + "banana", + "appellee", + "dogwood", + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", + "\u0002ABC\u0003" + ]; + for (const test of tests) { + console.log(BWT.makePrintable(test)); + process.stdout.write(" --> "); + let t = ""; + try { + t = BWT.bwt(test); + console.log(BWT.makePrintable(t)); + } catch (e) { + console.log("ERROR: " + e.message); + } + const r = BWT.ibwt(t); + console.log(` --> ${r}\n`); + } + } +} + +BWT.main(); diff --git a/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 b/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 index 7ef687eccb..ebca3c0383 100644 --- a/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 +++ b/Task/CSV-data-manipulation/M2000-Interpreter/csv-data-manipulation.m2000 @@ -1,6 +1,7 @@ +Locale 1032 Module Checkit { Function Sum { - Long c=0 + DECIMAL c=0 while not empty { c+=number } @@ -8,7 +9,7 @@ Module Checkit { } Document CSV$ = {C1,C2,C3,C4,C5 1,5,9,13,17 - 2,6,10,14,18 + 2,6,10.3,14,18 3,7,11,15,19 4,8,12,16,20 } @@ -19,13 +20,13 @@ Module Checkit { \\ use standard decimal point char \\ use standard (non json style string) \\ True = use bare strings (without "") - Input With "",,,true - Write With"",,,true + Input With "","",,true + Write With chr$(9),locale$(0xE),,true \\ for excel csv use Input With chr$(9),,true, true Open "data1.csv" for Wide Input as #M Open "data2.csv" for Wide Output as #M1 Input #M, h1$, h2$, h3$, h4$, h5$ - Write #M1, h1$, h2$, h3$, h4$, h5$ + Write #M1, h1$, h2$, h3$, h4$, h5$, "SUM" Print h1$, h2$, h3$, h4$, h5$ While not Eof(#M) { @@ -35,13 +36,15 @@ Module Checkit { } close #M1 Close #M + Input With chr$(9),locale$(0xE),,true Open "data2.csv" for Wide Input as #M - Input #M, h1$, h2$, h3$, h4$, h5$ - Print h1$, h2$, h3$, h4$, h5$ + Input #M, h1$, h2$, h3$, h4$, h5$, h6$ + Print h1$, h2$, h3$, h4$, h5$, h6$ While not Eof(#M) { Input #M, A1, A2, A3, A4, A5, Sum Print A1, A2, A3, A4, A5, Sum } Close #M + Win "Excel", dir$+"data2.csv" } Checkit diff --git a/Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu new file mode 100644 index 0000000000..d137dc1b65 --- /dev/null +++ b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-1.nu @@ -0,0 +1,5 @@ +open 'test_in.csv' | + each { |row| + let sum = ($row | values | math sum); + $row | insert Sum $sum + } diff --git a/Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu new file mode 100644 index 0000000000..82640ab976 --- /dev/null +++ b/Task/CSV-data-manipulation/Nu/csv-data-manipulation-2.nu @@ -0,0 +1 @@ +open 'test_in.csv' | upsert Sum {|row| $row | values | math sum } diff --git a/Task/Caesar-cipher/Ballerina/caesar-cipher.ballerina b/Task/Caesar-cipher/Ballerina/caesar-cipher.ballerina new file mode 100644 index 0000000000..c0061314bf --- /dev/null +++ b/Task/Caesar-cipher/Ballerina/caesar-cipher.ballerina @@ -0,0 +1,32 @@ +import ballerina/io; + +function encrypt(string s, int key) returns string { + final int offset = key % 26; + if offset == 0 { return s; } + int d; + int[] chars = []; + foreach int c in s.toCodePointInts() { + if c >= 64 && c <= 90 { + d = c + offset; + if d > 90 { d -= 26; } + } else if c >= 97 && c <= 122 { + d = c + offset; + if d > 122 { d -= 26; } + } else { + d = c; + } + chars.push(d); + } + return checkpanic string:fromCodePointInts(chars); +} + +function decrypt(string s, int key) returns string { + return encrypt(s, 26 - key); +} + +public function main() { + string encoded = encrypt("Bright vixens jump; dozy fowl quack.", 8); + io:println(encoded); + string decoded = decrypt(encoded, 8); + io:println(decoded); +} diff --git a/Task/Calculating-the-value-of-e/Ballerina/calculating-the-value-of-e.ballerina b/Task/Calculating-the-value-of-e/Ballerina/calculating-the-value-of-e.ballerina new file mode 100644 index 0000000000..126270884a --- /dev/null +++ b/Task/Calculating-the-value-of-e/Ballerina/calculating-the-value-of-e.ballerina @@ -0,0 +1,17 @@ +import ballerina/io; + +const EPSILON = 1e-15; + +public function main() { + int fact = 1; + float e = 2.0; + int n = 2; + while true { + float e0 = e; + fact *= n; + n += 1; + e += 1.0 / fact; + if (e - e0).abs() < EPSILON { break; } + } + io:println("e = ", e); +} diff --git a/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy b/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy index d7d8e38d52..2c5eb9d8bf 100644 --- a/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy +++ b/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy @@ -1,4 +1,4 @@ -numfmt 15 0 +numfmt 0 15 fact = 1 n = 2 e = 2 diff --git a/Task/Calendar---for-REAL-programmers/Rust/calendar---for-real-programmers.rs b/Task/Calendar---for-REAL-programmers/Rust/calendar---for-real-programmers.rs new file mode 100644 index 0000000000..493487a05c --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Rust/calendar---for-real-programmers.rs @@ -0,0 +1,216 @@ +struct Months { + pub name: String, + pub days: i16, + pub start_wday: i16, + pub at: i16, +} +impl Months { + fn new_month(name: &str, days: i16) -> Self { + Months { + name: String::from(name), + days, + start_wday: 0, + at: 0, + } + } +} +struct Calendar { + year: i16, + width: i16, + cols: i16, + lead: i16, + gap: i16, + months: [Months; 12], + wdays: [&'static str; 7], +} +impl Calendar { + fn new_calendar(year: i16, width: i16) -> Self { + let mut calendar = Calendar { + year, + width, + cols: 0, + lead: 0, + gap: 0, + months: [ + Months::new_month("JANUARY", 31), + Months::new_month("FEBRUARY", 28), + Months::new_month("MARCH", 31), + Months::new_month("APRIL", 30), + Months::new_month("MAY", 31), + Months::new_month("JUNE", 30), + Months::new_month("JULY", 31), + Months::new_month("AUGUST", 31), + Months::new_month("SEPTEMBER", 30), + Months::new_month("OCTOBER", 31), + Months::new_month("NOVEMBER", 30), + Months::new_month("DECEMBER", 31), + ], + wdays: ["SU", "MO", "TU", "WE", "TH", "FR", "SA"], + }; + calendar.init_months(); + calendar + } + fn init_months(&mut self) { + // Check for leap year and adjust February + if (self.year % 4 == 0 && self.year % 100 != 0) || self.year % 400 == 0 { + self.months[1].days = 29; + } + // Calculate starting weekday for January + let y = self.year - 1; + let year_days = (y % 7) * (365 % 7) % 7; // (y * 365) % 7 + let leap_days = ((y >> 2) - y / 100 + y / 400) % 7; + self.months[0].start_wday = (year_days + leap_days + 1) % 7; + // Calculate starting weekdays for remaining months + for i in 1..12 { + self.months[i].start_wday = + ((self.months[i-1].start_wday as i16 + self.months[i-1].days as i16) % 7) as i16; + } + // Layout calculations + self.cols = (self.width + 2) / 22; + while 12 % self.cols != 0 { + self.cols -= 1; + } + self.gap = if self.cols > 1 { + let gap = (self.width - 20 * self.cols) / (self.cols - 1); + if gap > 4 { 4 } else { gap } + } + else { + 0 + }; + // Calculate left margin to center the calendar + self.lead = (self.width - (20 + self.gap) * self.cols + self.gap + 1) >> 1; + } + // Helper method to print N spaces + fn print_spaces(&self, n: i16) { + print!("{}", " ".repeat(n as usize)); + } + // Print a horizontal row of month grids + fn print_row(&mut self, row: i16) { + let from = row * self.cols; + let to = from + self.cols; + // Print month names centered + self.print_spaces(self.lead); + for c in from..to { + let name_len = self.months[c as usize].name.len() as i16; + self.print_spaces((20 - name_len) >> 1); + print!("{}", self.months[c as usize].name); + let extra_spaces = 20 - name_len - ((20 - name_len) >> 1); + let gap_spaces = if c == to - 1 { 0 } else { self.gap }; + self.print_spaces(extra_spaces + gap_spaces); + } + println!(); + // Print weekday headers for each month + self.print_spaces(self.lead); + for c in from..to { + for i in 0..7 { + print!("{}", self.wdays[i as usize]); + if i < 6 { + print!(" "); + } + } + if c < to - 1 { + self.print_spaces(self.gap); + } else { + println!(); + } + } + // Print the calendar days for all months in this row + loop { + // Check if we've printed all days for all months in this row + let mut all_done = true; + for c in from..to { + if self.months[c as usize].at < self.months[c as usize].days { + all_done = false; + break; + } + } + if all_done { + break; + } + self.print_spaces(self.lead); + for c in from..to { + let c_usize = c as usize; + let mut i = 0; + // Print spaces for days before the 1st of the month + while i < self.months[c_usize].start_wday { + self.print_spaces(3); + i += 1; + } + // Print the days of the month + while i < 7 && self.months[c_usize].at < self.months[c_usize].days { + self.months[c_usize].at += 1; + let day = self.months[c_usize].at; + // Print day with padding + if day < 10 { + print!(" {}", day); + } else { + print!("{}", day); + } + if i < 6 || c < to - 1 { + print!(" "); + } + i += 1; + } + // Fill remaining spaces in week if needed + while i < 7 && c < to - 1 { + self.print_spaces(3); + i += 1; + } + if c < to - 1 { + self.print_spaces(self.gap - 1); + } + self.months[c_usize].start_wday = 0; // Reset for next week + } + println!(); + } + println!(); // Extra line between rows of months + } + // Print the entire year's calendar + fn print_year(&mut self) { + // Print centered year heading + let year_str = self.year.to_string(); + let spaces = (self.width - year_str.len() as i16) >> 1; + self.print_spaces(spaces); + println!("{}", year_str); + println!(); + // Print each row of months + let rows = 12 / self.cols; + for row in 0..rows { + self.print_row(row); + } + } +} +fn main() -> Result<(), String> { + let args: Vec = env::args().collect(); + let mut year: i16 = 1969; // Default year + let mut width: i16 = 80; // Default width + let mut year_set = false; + // Process command line arguments + let mut i = 1; + while i < args.len() { + if args[i] == "-W" { + i += 1; + if i < args.len() { + width = args[i].parse::().map_err(|_| "Invalid width")?; + if width < 20 { + return Err("Width must be at least 20".to_string()); + } + } else { + return Err("Missing width value after -W".to_string()); + } + } else if !year_set { + year = match args[i].parse::() { + Ok(y) if y > 0 => y, + _ => 1969, // Default to 1969 if year is invalid + }; + year_set = true; + } else { + return Err(format!("Too many arguments. Usage: {} YEAR [-W WIDTH (>= 20)]", args[0])); + } + i += 1; + } + // Generate and print the calendar + let mut calendar = Calendar::new_calendar(year, width); + calendar.print_year(); + Ok(()) +} diff --git a/Task/Calendar/00-TASK.txt b/Task/Calendar/00-TASK.txt index 2224cf4612..2ae49d8177 100644 --- a/Task/Calendar/00-TASK.txt +++ b/Task/Calendar/00-TASK.txt @@ -17,6 +17,8 @@ For further Kudos see task [[Calendar - for "real" programmers|CALENDAR]], where For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. +;See Also: +:*   [https://jmvdveer.home.xs4all.nl/en.post.snoopy-calender.html Snoopy calendar 1969-2025 Marcel van der Veer] - The deck is credited as being one of the first FOSS programs. ;Related task: :*   [[Five weekends]] diff --git a/Task/Calendar/EasyLang/calendar.easy b/Task/Calendar/EasyLang/calendar.easy index b785fed23d..c5d5c9d0d4 100644 --- a/Task/Calendar/EasyLang/calendar.easy +++ b/Task/Calendar/EasyLang/calendar.easy @@ -17,29 +17,21 @@ func$ makewk fst lst day . . for i = fst to lst i$ = i - if i <= 9 - i$ = " " & i - . + if i <= 9 : i$ = " " & i wstr$ &= i$ & " " . return substr wstr$ & blank$ 1 20 . -proc dow y . ndow leap . +proc dow y &ndow &leap . leap = 0 - if y mod 4 = 0 - leap = 1 - . - if y mod 100 = 0 - leap = 0 - . - if y mod 400 = 0 - leap = 1 - . + if y mod 4 = 0 : leap = 1 + if y mod 100 = 0 : leap = 0 + if y mod 400 = 0 : leap = 1 ndow = y * 365 + y div 4 - y div 100 + y div 400 + 1 ndow = (ndow - leap) mod1 7 . len lin$[] 8 -proc prmonth nmonth newdow monsize . . +proc prmonth nmonth newdow monsize . lin$[1] &= " " & month$[nmonth] & " " lin$[2] &= wkdays$ & " " lin$[3] &= makewk 1 (8 - newdow) newdow & " " @@ -55,17 +47,13 @@ proc prmonth nmonth newdow monsize . . . . . -for i to pagewide - blank$ &= " " -. +for i to pagewide : blank$ &= " " dow year newdow leap print center "[ picture of Snoopy goes here ]" print center year for i = 1 to 12 monsize = days[i] - if i = 2 and leap = 1 - monsize = 29 - . + if i = 2 and leap = 1 : monsize = 29 prmonth i newdow monsize newdow = (monsize + newdow) mod1 7 . diff --git a/Task/Calkin-Wilf-sequence/C-sharp/calkin-wilf-sequence.cs b/Task/Calkin-Wilf-sequence/C-sharp/calkin-wilf-sequence.cs new file mode 100644 index 0000000000..c991ef30c3 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/C-sharp/calkin-wilf-sequence.cs @@ -0,0 +1,48 @@ +IEnumerable Fusc() +{ + yield return 1; + var n = 1; + + foreach (var f in Fusc()) + { + yield return n + f; + yield return f; + n = f; + } +} + +IEnumerable ContFrac(int n, int d) +{ + while (d != 0) + { + yield return n / d; + (n, d) = (d, n % d); + } +} + +Console.WriteLine("First 20 terms of the Calkin-Wilf sequence:"); +var n = 1; + +foreach (var f in Fusc().Take(20)) +{ + Console.Write($"{n}/{f} "); + n = f; +} + +Console.WriteLine(); +var bits = 0L; +var bit = 1L; +var shift = 0; + +foreach (var c in ContFrac(83116, 51639)) +{ + for (var i = 0; i < c; i++) + { + bits |= bit << shift; + shift++; + } + + bit = 1 - bit; +} + +Console.WriteLine($"83116/51639 is at position {bits} in the sequence"); diff --git a/Task/Calkin-Wilf-sequence/EasyLang/calkin-wilf-sequence.easy b/Task/Calkin-Wilf-sequence/EasyLang/calkin-wilf-sequence.easy index 58bad99625..5ba9c6ad0d 100644 --- a/Task/Calkin-Wilf-sequence/EasyLang/calkin-wilf-sequence.easy +++ b/Task/Calkin-Wilf-sequence/EasyLang/calkin-wilf-sequence.easy @@ -1,7 +1,8 @@ subr first - n = 1 ; d = 1 + n = 1 + d = 1 . -proc next . . +proc next . n = 2 * (n div d) * d + d - n swap n d . diff --git a/Task/Call-a-function/EasyLang/call-a-function.easy b/Task/Call-a-function/EasyLang/call-a-function.easy index 7259ecaad6..08dbf24e42 100644 --- a/Task/Call-a-function/EasyLang/call-a-function.easy +++ b/Task/Call-a-function/EasyLang/call-a-function.easy @@ -3,7 +3,7 @@ func sqr n . . print sqr 3 # -proc divmod a b . q r . +proc divmod a b &q &r . q = a div b r = a mod b . diff --git a/Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js b/Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js new file mode 100644 index 0000000000..73b10c2641 --- /dev/null +++ b/Task/Camel-case-and-snake-case/JavaScript/camel-case-and-snake-case.js @@ -0,0 +1,82 @@ +const HYPHEN = '-'; +const SPACE = ' '; +const UNDERSCORE = '_'; +const WHITESPACE = " \n\r\t\f\v"; + +function leftTrim(text) { + const start = text.search(/\S/); // Find the index of the first non-whitespace character + return start === -1 ? "" : text.substring(start); +} + +function rightTrim(text) { + const end = text.search(/\S(?![\s\S]*\S)/); // Find the index of the last non-whitespace character + return end === -1 ? "" : text.substring(0, end + 1); +} + +function trim(text) { + return leftTrim(rightTrim(text)); +} + +function prepareForConversion(text) { + text = trim(text); + text = text.replace(new RegExp(SPACE, 'g'), UNDERSCORE); + text = text.replace(new RegExp(HYPHEN, 'g'), UNDERSCORE); + return text; // Return the modified text +} + +function toSnakeCase(camel) { + camel = prepareForConversion(camel); + let snake = ""; + let first = true; + for (const ch of camel) { + if (first) { + snake += ch; + first = false; + } else if (!first && ch >= 'A' && ch <= 'Z') { + if (snake.slice(-1) === UNDERSCORE) { + snake += ch.toLowerCase(); + } else { + snake += UNDERSCORE; + snake += ch.toLowerCase(); + } + } else { + snake += ch; + } + } + return snake; +} + +function toCamelCase(snake) { + snake = prepareForConversion(snake); + let camel = ""; + let underscore = false; + for (const ch of snake) { + if (ch === UNDERSCORE) { + underscore = true; + } else if (underscore) { + camel += ch.toUpperCase(); + underscore = false; + } else { + camel += ch; + } + } + return camel; +} + +function main() { + const variableNames = ["snakeCase", "snake_case", "variable_10_case", + "variable10Case", "ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces "]; + + console.log("".padEnd(48, " ") + "=== To snake_case ==="); + for (const text of variableNames) { + console.log("".padEnd(34, " ") + text + " --> " + toSnakeCase(text)); + } + + console.log("\n"); + console.log("".padEnd(48, " ") + "=== To camelCase ==="); + for (const text of variableNames) { + console.log("".padEnd(34, " ") + text + " --> " + toCamelCase(text)); + } +} + +main(); diff --git a/Task/Camel-case-and-snake-case/R/camel-case-and-snake-case.r b/Task/Camel-case-and-snake-case/R/camel-case-and-snake-case.r new file mode 100644 index 0000000000..bf208f540b --- /dev/null +++ b/Task/Camel-case-and-snake-case/R/camel-case-and-snake-case.r @@ -0,0 +1,56 @@ +library(stringr) + +test_strings <- c("snakeCase", "snake_case", "variable_10_case", "variable10Case", "ɛrgo rE tHis", + "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces ") + +#Simple functions +snake2camel <- function(s){ + boundaries <- str_extract_all(s, "_+[^_]", simplify=TRUE) + boundaries <- str_replace_all(boundaries, "_", "") + for(b in boundaries){ + s <- str_replace_all(s, str_c("_+",b), str_to_upper(b)) + } + return(s) +} + +writeLines(c("Snake to camel case:", sapply(test_strings, camel2snake))) + +camel2snake <- function(s){ + boundaries <- str_extract_all(s, "[A-Z]", simplify=TRUE) + for(b in boundaries){ + s <- str_replace_all(s, b, str_c("_", str_to_lower(b))) + } + return(s) +} + +writeLines(c("Camel to snake case:", sapply(test_strings, camel2snake))) + +#More general functions +any2camel <- function(s){ + #strip leading and trailing whitespace + s <- str_replace_all(s, "^[\\h]+|[\\h]+$", "") + #Deal with specified separators + boundaries <- str_extract_all(s, "[ _-]+[^ _-]", simplify=TRUE) + boundaries <- str_replace_all(boundaries, "[ _-]", "") + for(b in boundaries){ + s <- str_replace_all(s, str_c("[ _-]+", b), str_to_upper(b)) + } + return(s) +} + +writeLines(c("Any separator to camel case:", sapply(test_strings, any2camel))) + +any2snake <- function(s){ + s <- str_replace_all(s, "^[\\h]+|[\\h]+$", "") + boundaries_camel <- str_extract_all(s, "[A-Z]", simplify=TRUE) + boundaries_other <- str_extract_all(s, "[ -]+", simplify=TRUE) + for(b in boundaries_camel){ + s <- str_replace_all(s, b, str_c("_", str_to_lower(b))) + } + for(b in boundaries_other){ + s <- str_replace_all(s, b, "_") + } + return(s) +} + +writeLines(c("Any separator to snake case:", sapply(test_strings, any2snake))) diff --git a/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg b/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg index 7befa0b1eb..6a3f49135f 100644 --- a/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg +++ b/Task/Canonicalize-CIDR/ALGOL-68/canonicalize-cidr.alg @@ -1,22 +1,22 @@ BEGIN # show IPv4 addresses in CIDR notation in canonical form # # mode to hold an IPv4 address in CIDR notation # - MODE CIDR = STRUCT( BITS address - , INT network bits - , BOOL valid - , STRING error + MODE CIDR = STRUCT( LONG BITS address + , INT network bits + , BOOL valid + , STRING error ); # returns a CIDR parsed from address # OP TOCIDR = ( STRING address text )CIDR: BEGIN - STRING addr = "." + address text + "$"; - STRING error := ""; - BITS address := 16r0; - INT bits count := 0; - INT dot count := 0; - INT slash count := 0; - BOOL valid := TRUE; - INT s pos := LWB addr; - INT s max = UPB addr; + STRING addr = "." + address text + "$"; + STRING error := ""; + LONG BITS address := 16r0; + INT bits count := 0; + INT dot count := 0; + INT slash count := 0; + BOOL valid := TRUE; + INT s pos := LWB addr; + INT s max = UPB addr; WHILE s pos < s max AND valid DO IF addr[ s pos ] = "." THEN # must have an octet next # @@ -70,7 +70,7 @@ BEGIN # show IPv4 addresses in CIDR notation in canonical form # address ELSE # valid address - retain the top most bits # - CIDR( address OF address AND ( 16rffffffff + CIDR( address OF address AND ( LONG 16rffffffff SHL ( 32 - network bits OF address ) ) , network bits OF address @@ -82,9 +82,9 @@ BEGIN # show IPv4 addresses in CIDR notation in canonical form # OP TOSTRING = ( CIDR address )STRING: BEGIN [ 1 : 4 ]INT octet; - BITS addr := address OF address; + LONG BITS addr := address OF address; FOR o pos FROM UPB octet BY -1 TO LWB octet DO - octet[ o pos ] := ABS ( addr AND 16rff ); + octet[ o pos ] := SHORTEN ABS ( addr AND 16rff ); addr := addr SHR 8 OD; STRING result := whole( octet[ LWB octet ], 0 ); diff --git a/Task/Canonicalize-CIDR/Zig/canonicalize-cidr.zig b/Task/Canonicalize-CIDR/Zig/canonicalize-cidr.zig new file mode 100644 index 0000000000..7d5877d51d --- /dev/null +++ b/Task/Canonicalize-CIDR/Zig/canonicalize-cidr.zig @@ -0,0 +1,70 @@ +const std = @import("std"); + +const Ipv4Cidr = struct { + address: u32, + mask_length: u8, + + pub fn parse(s: []const u8) !Ipv4Cidr { + var split = std.mem.splitSequence(u8, s, "/"); + const addr_str = split.first(); + const mask_str = split.next() orelse return error.InvalidFormat; + if (split.next() != null) return error.InvalidFormat; + + var octets: [4]u8 = undefined; + var addr_split = std.mem.splitSequence(u8, addr_str, "."); + for (0..4) |i| { + const part = addr_split.next() orelse return error.InvalidFormat; + octets[i] = std.fmt.parseInt(u8, part, 10) catch return error.InvalidFormat; + } + if (addr_split.next() != null) return error.InvalidFormat; + + const address = (@as(u32, octets[0]) << 24) | + (@as(u32, octets[1]) << 16) | + (@as(u32, octets[2]) << 8) | + octets[3]; + + const mask_length = std.fmt.parseInt(u8, mask_str, 10) catch return error.InvalidFormat; + if (mask_length < 1 or mask_length > 32) return error.InvalidMask; + + const shift = @as(u5, @intCast(32 - mask_length)); + const mask = ~((@as(u32, 1) << shift) - 1); + const masked_address = address & mask; + + return Ipv4Cidr{ + .address = masked_address, + .mask_length = mask_length, + }; + } + + pub fn format( + self: Ipv4Cidr, + comptime _: []const u8, + _: std.fmt.FormatOptions, + writer: anytype, + ) !void { + const a = (self.address >> 24) & 0xFF; + const b = (self.address >> 16) & 0xFF; + const c = (self.address >> 8) & 0xFF; + const d = self.address & 0xFF; + try writer.print("{}.{}.{}.{}/{}", .{a, b, c, d, self.mask_length}); + } +}; + +pub fn main() !void { + const tests = [_][]const u8{ + "87.70.141.1/22", + "36.18.154.103/12", + "62.62.197.11/29", + "67.137.119.181/4", + "161.214.74.21/24", + "184.232.176.184/18", + }; + + for (tests) |my_test| { + const cidr = Ipv4Cidr.parse(my_test) catch |err| { + std.debug.print("{s}: invalid CIDR ({s})\n", .{my_test, @errorName(err)}); + continue; + }; + std.debug.print("{s:<18} -> {}\n", .{my_test, cidr}); + } +} diff --git a/Task/Cantor-set/EasyLang/cantor-set.easy b/Task/Cantor-set/EasyLang/cantor-set.easy index 61ccf82fa3..6e79ec59bb 100644 --- a/Task/Cantor-set/EasyLang/cantor-set.easy +++ b/Task/Cantor-set/EasyLang/cantor-set.easy @@ -1,9 +1,8 @@ -color 555 -proc cantor x y sz . . +gcolor 555 +proc cantor x y sz . if sz > 0.1 sz3 = sz / 3 - move x y - sz3 - rect sz sz3 + grect x y - sz3 sz sz3 cantor x y - sz3 sz3 cantor x + 2 * sz3 y - sz3 sz3 . diff --git a/Task/Carmichael-3-strong-pseudoprimes/EasyLang/carmichael-3-strong-pseudoprimes.easy b/Task/Carmichael-3-strong-pseudoprimes/EasyLang/carmichael-3-strong-pseudoprimes.easy index cbe08cb092..a1d4f5ee2a 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/EasyLang/carmichael-3-strong-pseudoprimes.easy +++ b/Task/Carmichael-3-strong-pseudoprimes/EasyLang/carmichael-3-strong-pseudoprimes.easy @@ -1,14 +1,12 @@ func isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -proc carmichael3 p1 . . +proc carmichael3 p1 . for h3 = 1 to p1 - 1 for d = 1 to h3 + p1 - 1 if (h3 + p1) * (p1 - 1) mod d = 0 and -p1 * p1 mod h3 = d mod h3 diff --git a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-1.rexx b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-1.rexx deleted file mode 100644 index 5eefc267eb..0000000000 --- a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-1.rexx +++ /dev/null @@ -1,42 +0,0 @@ -/*REXX program calculates Carmichael 3─strong pseudoprimes (up to and including N). */ -numeric digits 18 /*handle big dig #s (9 is the default).*/ -parse arg N .; if N=='' | N=="," then N=61 /*allow user to specify for the search.*/ -tell= N>0; N= abs(N) /*N>0? Then display Carmichael numbers*/ -#= 0 /*number of Carmichael numbers so far. */ -@.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1; @.17=1; @.19=1; @.23=1; @.29=1; @.31=1 - /*[↑] prime number memoization array. */ - do p=3 to N by 2; pm= p-1; bot=0; top=0 /*step through some (odd) prime numbers*/ - if \isPrime(p) then iterate; nps= -p*p /*is P a prime? No, then skip it.*/ - c.= 0 /*the list of Carmichael #'s (so far).*/ - do h3=2 for pm-1; g= h3 + p /*get Carmichael numbers for this prime*/ - npsH3= ((nps // h3) + h3) // h3 /*define a couple of shortcuts for pgm.*/ - gPM= g * pm /*define a couple of shortcuts for pgm.*/ - /* [↓] perform some weeding of D values*/ - do d=1 for g-1; if gPM // d \== 0 then iterate - if npsH3 \== d//h3 then iterate - q= 1 + gPM % d; if \isPrime(q) then iterate - r= 1 + p * q % h3; if q * r // pm \== 1 then iterate - if \isPrime(r) then iterate - #= # + 1; c.q= r /*bump Carmichael counter; add to array*/ - if bot==0 then bot= q; bot= min(bot, q); top= max(top, q) - end /*d*/ - end /*h3*/ - $= /*build list of some Carmichael numbers*/ - if tell then do j=bot to top by 2; if c.j\==0 then $= $ p"∙"j'∙'c.j - end /*j*/ - - if $\=='' then say 'Carmichael number: ' strip($) - end /*p*/ -say -say '──────── ' # " Carmichael numbers found." -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: parse arg x; if @.x then return 1 /*is X a known prime?*/ - if x<37 then return 0; if x//2==0 then return 0; if x// 3==0 then return 0 - parse var x '' -1 _; if _==5 then return 0; if x// 7==0 then return 0 - if x//11==0 then return 0; if x//13==0 then return 0; if x//17==0 then return 0 - if x//19==0 then return 0; if x//23==0 then return 0; if x//29==0 then return 0 - do k=29 by 6 until k*k>x; if x//k ==0 then return 0 - if x//(k+2) ==0 then return 0 - end /*k*/ - @.x=1; return 1 diff --git a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-2.rexx b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-2.rexx deleted file mode 100644 index 586ab2e701..0000000000 --- a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes-2.rexx +++ /dev/null @@ -1,59 +0,0 @@ -include Settings - -say version; say 'Carmichael 3 strong primes'; say -arg n -numeric digits 16 -if n = '' then - n = 61 -show = (n > 0); n = Abs(n) -c = Carmichaels(n) -if show then do - do i = 1 to capr.0 - say capr.prime1.i 'x' capr.prime2.i 'x' capr.prime3.i '=', - capr.prime1.i * capr.prime2.i * capr.prime3.i - end -end -say c 'Carmichael numbers found up to first prime' n -say time('e') 'seconds' -exit - -Carmichaels: -/* Carmichael 3 strong prime numbers */ -procedure expose capr. -parse arg x -n = 0 -do p1 = 3 by 2 to x -/* Method Janeson */ - if \ Prime(p1) then - iterate p1 - pm = p1-1; ps = -p1*p1 - do h3 = 1 to pm - t1 = (h3+p1) * pm; t2 = ps//h3 - if t2 < 0 then - t2 = t2+h3 - do d = 1 to h3+pm - if t1//d <> 0 then - iterate d - if t2 <> d//h3 then - iterate d - p2 = 1+t1%d - if \ Prime(p2) then - iterate d - p3 = 1+(p1*p2%h3) - if \ Prime(p3) then - iterate d - if (p2*p3)//pm <> 1 then - iterate d -/* Save results */ - n = n+1 - capr.prime1.n = p1; capr.prime2.n = p2; capr.prime3.n = p3 - end d - end h3 -end -capr.0 = n -/* Return count */ -return n - -include Numbers -include Functions -include Abend diff --git a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx new file mode 100644 index 0000000000..9cce219003 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx @@ -0,0 +1,26 @@ +-- 22 Mar 2025 +include Settings + +say 'CARMICHAEL 3 STRONG PSEUDOPRIMES' +say version +say +arg n +numeric digits 16 +if n = '' then + n = 61 +show = (n > 0); n = Abs(n) +c = Carmichaels(n) +if show then do + do i = 1 to carm.0 + say carm.1.i 'x' carm.2.i 'x' carm.3.i '=', + carm.1.i * carm.2.i * carm.3.i + end +end +say c 'Carmichael numbers found up to first prime' n +say time('e') 'seconds' +exit + +include Sequences +include Numbers +include Functions +include Abend diff --git a/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-1.cpp b/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-1.cpp new file mode 100644 index 0000000000..39cb7169a1 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-1.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +void print_inner(const std::vector &v) { + std::cout << "("; + auto it = v.begin(); + if (!v.empty()) { + std::cout << *it++; // Yield beginning value, then advance + } + for (; it != v.end(); ++it) { + std::cout << ", " << *it; + } + std::cout << ")"; +} + +void print(const std::vector > &v) { + std::cout << "["; + auto it = v.begin(); + if (!v.empty()) { + print_inner(*it++); // Yield beginning value, then advance + } + for (; it != v.end(); ++it) { + std::cout << ", "; + print_inner(*it); + } + std::cout << "]\n"; +} + +auto product(const std::vector > &lists) { + std::vector > result; + if (std::find_if(std::begin(lists), std::end(lists), + [](const auto &e) -> bool { return e.empty(); }) != std::end(lists)) { + return result; + } + for (auto &e: lists[0]) { + result.push_back({e}); + } + for (size_t i = 1; i < lists.size(); ++i) { + std::vector > temp; + for (const auto &e: result) { + for (auto f: lists[i]) { + auto e_tmp = e; + e_tmp.push_back(f); + temp.push_back(e_tmp); + } + } + result = temp; + } + return result; +} + +int main() { + std::vector > prods[] = { + {{1, 2}, {3, 4}}, + {{3, 4}, {1, 2}}, + {{1, 2}, {}}, + {{}, {1, 2}}, + {{1776, 1789}, {7, 12}, {4, 14, 23}, {0, 1}}, + {{1, 2, 3}, {30}, {500, 100}}, + {{1, 2, 3}, {}, {500, 100}} + }; + for (const auto &p: prods) { + print(product(p)); + } +} diff --git a/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-2.cpp b/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-2.cpp new file mode 100644 index 0000000000..2c22d76f01 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists-2.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include + +template +using a = std::array; + +template +using t = std::tuple; + +template +constexpr auto product(const t& inputs) { + const auto rng = std::apply(std::views::cartesian_product, inputs); + + std::println("{}", rng); +} + +int main() { + // The size of each list of arrays needs to be known at compile-time in order to use `cartesian_product()` + // However, each array is a different size, thus a distinct type, so we use a tuple to hold all of them + // The brace-initialized constructor cannot deduce the type of empty array, so we spell them out manually + constexpr auto prods = t{ + t{a{1, 2}, a{3, 4}}, + t{a{3, 4}, a{1, 2}}, + t{a{1, 2}, a{}}, + t{a{}, a{1, 2}}, + t{a{1776, 1789}, a{7, 12}, a{4, 14, 23}, a{0, 1}}, + t{a{1, 2, 3}, a{30}, a{500, 100}}, + t{a{1, 2, 3}, a{}, a{500, 100}} + }; + + std::apply([](const auto &... test_cases) { + (product(test_cases), ...); + }, prods); +} diff --git a/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists.cpp b/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists.cpp deleted file mode 100644 index e4a99032bd..0000000000 --- a/Task/Cartesian-product-of-two-or-more-lists/C++/cartesian-product-of-two-or-more-lists.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include -#include -#include - -void print(const std::vector>& v) { - std::cout << "{ "; - for (const auto& p : v) { - std::cout << "("; - for (const auto& e : p) { - std::cout << e << " "; - } - std::cout << ") "; - } - std::cout << "}" << std::endl; -} - -auto product(const std::vector>& lists) { - std::vector> result; - if (std::find_if(std::begin(lists), std::end(lists), - [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) { - return result; - } - for (auto& e : lists[0]) { - result.push_back({ e }); - } - for (size_t i = 1; i < lists.size(); ++i) { - std::vector> temp; - for (auto& e : result) { - for (auto f : lists[i]) { - auto e_tmp = e; - e_tmp.push_back(f); - temp.push_back(e_tmp); - } - } - result = temp; - } - return result; -} - -int main() { - std::vector> prods[] = { - { { 1, 2 }, { 3, 4 } }, - { { 3, 4 }, { 1, 2} }, - { { 1, 2 }, { } }, - { { }, { 1, 2 } }, - { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } }, - { { 1, 2, 3 }, { 30 }, { 500, 100 } }, - { { 1, 2, 3 }, { }, { 500, 100 } } - }; - for (const auto& p : prods) { - print(product(p)); - } - std::cin.ignore(); - std::cin.get(); - return 0; -} diff --git a/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy b/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy index 011a8d1706..0bef4f64ad 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy +++ b/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy @@ -1,16 +1,10 @@ -proc cart2 a[] b[] . p[][] . - p[][] = [ ] - for a in a[] - for b in b[] - p[][] &= [ a b ] - . +func[][] cart a[] b[] . + for a in a[] : for b in b[] + p[][] &= [ a b ] . + return p[][] . -cart2 [ 1 2 ] [ 3 4 ] r[][] -print r[][] -cart2 [ 3 4 ] [ 1 2 ] r[][] -print r[][] -cart2 [ 1 2 ] [ ] r[][] -print r[][] -cart2 [ ] [ 1 2 ] r[][] -print r[][] +print cart [ 1 2 ] [ 3 4 ] +print cart [ 3 4 ] [ 1 2 ] +print cart [ 1 2 ] [ ] +print cart [ ] [ 1 2 ] diff --git a/Task/Cartesian-product-of-two-or-more-lists/M2000-Interpreter/cartesian-product-of-two-or-more-lists.m2000 b/Task/Cartesian-product-of-two-or-more-lists/M2000-Interpreter/cartesian-product-of-two-or-more-lists.m2000 new file mode 100644 index 0000000000..61a8c22897 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/M2000-Interpreter/cartesian-product-of-two-or-more-lists.m2000 @@ -0,0 +1,52 @@ +module checkit { + showTuple = lambda (a as array) -> { + k=lambda m=1 ->{ + shift 2 + if m=1 then + m=0:drop + push "("+array#str$(",")+")" + else + push letter$+",("+array#str$(",")+")" + end if + } + ="("+a#fold$(k)+")" + } + function cartesian_prod(a as array, b as array) { + rest=[] + aa=each(a) + while aa + bb=each(b) + while bb + data (array(aa), array(bb)) + end while + end while + ccc=(,) + if len(rest)>0 then + cc=each(rest) + while cc + ccc=stackitem(cc) + d=array([]) + dd=each(d) + while dd + ee=each(ccc) + while ee + data array(dd)#end((array(ee),)) + end while + end while + end while + end if + =array([]) + } + open "out.txt" for output as #f + print #f,"(1,2)x(3,4)=";showTuple(cartesian_prod((1,2), (3,4))) + print #f,"(3,4)x(1,2)=";showTuple(cartesian_prod((3,4), (1,2))) + print #f,"(1,2)x()=";showTuple(cartesian_prod((1,2), (,))) + print #f,"()x(1,2)=";showTuple(cartesian_prod((,), (1,2))) + print #f,"(1776,1789)x(7,12)x(4,14,23)x(0,1)=";showTuple(cartesian_prod((1776,1789), (7,12), (4,14,23), (0,1))) + print #f,"(1,2,3)x(30)x(500,100)=";showTuple(cartesian_prod((1,2,3), (30,), (500,100))) + print #f,"(1,2,3)x()x(500,100)=";showTuple(cartesian_prod((1,2,3), (,), (500,100))) + print #f,"(1,2,3)x(500,100)x()=";showTuple(cartesian_prod((1,2,3), (,), (500,100), (,))) + close #f + win notepad, dir$+"out.txt" +} +checkit diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs index 9345a4ad79..4bde4f9f43 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs +++ b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-1.rs @@ -1,41 +1,42 @@ -fn cartesian_product(lists: &Vec>) -> Vec> { - let mut res = vec![]; +fn cartesian_product<'a, T>(lists: &[&'a [T]]) -> Vec> { + let mut res = vec![vec![]]; + + for &list in lists { + let mut tmp = Vec::new(); - let mut list_iter = lists.iter(); - if let Some(first_list) = list_iter.next() { - for &i in first_list { - res.push(vec![i]); - } - } - for l in list_iter { - let mut tmp = vec![]; for r in res { - for &el in l { - let mut tmp_el = r.clone(); - tmp_el.push(el); - tmp.push(tmp_el); + for item in list { + let mut r = r.clone(); + r.push(item); + tmp.push(r); } } + res = tmp; } + res } fn main() { - let cases = vec![ - vec![vec![1, 2], vec![3, 4]], - vec![vec![3, 4], vec![1, 2]], - vec![vec![1, 2], vec![]], - vec![vec![], vec![1, 2]], - vec![vec![1776, 1789], vec![7, 12], vec![4, 14, 23], vec![0, 1]], - vec![vec![1, 2, 3], vec![30], vec![500, 100]], - vec![vec![1, 2, 3], vec![], vec![500, 100]], + let cases: [&[&[u32]]; 7] = [ + &[&[1, 2], &[3, 4]], + &[&[3, 4], &[1, 2]], + &[&[1, 2], &[]], + &[&[], &[1, 2]], + &[&[1776, 1789], &[7, 12], &[4, 14, 23], &[0, 1]], + &[&[1, 2, 3], &[30], &[500, 100]], + &[&[1, 2, 3], &[], &[500, 100]], ]; + for case in cases { println!( "{}\n{:?}\n", - case.iter().map(|c| format!("{:?}", c)).collect::>().join(" × "), - cartesian_product(&case) + case.iter() + .map(|c| format!("{:?}", c)) + .collect::>() + .join(" × "), + cartesian_product(case) ) } } diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs index c23d3c4ce3..88f569f91f 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs +++ b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-2.rs @@ -1,23 +1,2 @@ -fn cartesian_product(sets: &[Vec]) -> Vec> { - if sets.is_empty() { - return vec![vec![]]; - } - - let mut result = vec![vec![]]; - - for set in sets { - let mut temp = Vec::new(); - - for res in &result { - for item in set { - let mut new_res = res.clone(); - new_res.push(item.clone()); - temp.push(new_res); - } - } - - result = temp; - } - - result -} +[dependencies] +itertools = { version = "0.14.0", features = ["use_alloc"] } diff --git a/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs new file mode 100644 index 0000000000..e8d4eff8e3 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Rust/cartesian-product-of-two-or-more-lists-3.rs @@ -0,0 +1,28 @@ +use itertools::{Itertools, MultiProduct}; + +fn cartesian_product<'a, T>(inputs: &[&'a [T]]) -> MultiProduct> { + inputs + .iter() + .map(|slice| slice.iter()) + .multi_cartesian_product() +} + +fn main() { + let cases: [&[&[u32]]; 7] = [ + &[&[1, 2], &[3, 4]], + &[&[3, 4], &[1, 2]], + &[&[1, 2], &[]], + &[&[], &[1, 2]], + &[&[1776, 1789], &[7, 12], &[4, 14, 23], &[0, 1]], + &[&[1, 2, 3], &[30], &[500, 100]], + &[&[1, 2, 3], &[], &[500, 1000]], + ]; + + for case in cases { + println!( + "{:?}\n[{:?}]\n", + case.iter().format(" × "), + cartesian_product(case).format(", ") + ); + } +} diff --git a/Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina b/Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina new file mode 100644 index 0000000000..6b87eea744 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Ballerina/case-sensitivity-of-identifiers.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + string dog = "Benjamin"; + string Dog = "Samba"; + string DOG = "Bernie"; + io:println(`The three dogs are named ${dog}, ${Dog} and ${DOG}.`); +} diff --git a/Task/Catalan-numbers/EasyLang/catalan-numbers.easy b/Task/Catalan-numbers/EasyLang/catalan-numbers.easy index 6ec582b534..7c0b3976d0 100644 --- a/Task/Catalan-numbers/EasyLang/catalan-numbers.easy +++ b/Task/Catalan-numbers/EasyLang/catalan-numbers.easy @@ -1,9 +1,7 @@ func catalan n . - if n = 0 - return 1 - . + if n = 0 : return 1 return 2 * (2 * n - 1) * catalan (n - 1) div (1 + n) . for i = 0 to 14 - print catalan i + write catalan i & " " . diff --git a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx index 64d93b2fb9..b523782cf9 100644 --- a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx +++ b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx @@ -1,23 +1,51 @@ -/*REXX program calculates and displays Catalan numbers using four different methods. */ -parse arg LO HI . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then do; HI=15; LO=0; end /*No args? Then use a range of 0 ──► 15*/ -if HI=='' | HI=="," then HI=LO /*No HI? Then use LO for the default*/ -numeric digits max(20, 5*HI) /*this allows gihugic Catalan numbers. */ -w=length(HI) /*W: is used for aligning the output. */ -call hdr 1A; do j=LO to HI; say ' Catalan' right(j, w)": " Cat1A(j); end -call hdr 1B; do j=LO to HI; say ' Catalan' right(j, w)": " Cat1B(j); end -call hdr 2 ; do j=LO to HI; say ' Catalan' right(j, w)": " Cat2(j) ; end -call hdr 3 ; do j=LO to HI; say ' Catalan' right(j, w)": " Cat3(j) ; end -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -!: arg z; if !.z\==. then return !.z; !=1; do k=2 to z; !=!*k; end; !.z=!; return ! -Cat1A: procedure expose !.; parse arg n; return comb(n+n, n) % (n+1) -Cat1B: procedure expose !.; parse arg n; return !(n+n) % ((n+1) * !(n)**2) -Cat3: procedure expose c.; arg n; if c.n==. then c.n=(4*n-2)*cat3(n-1)%(n+1); return c.n -comb: procedure; parse arg x,y; return pFact(x-y+1, x) % pFact(2, y) -hdr: !.=.; c.=.; c.0=1; say; say center('Catalan numbers, method' arg(1),79,'─'); return -pFact: procedure; !=1; do k=arg(1) to arg(2); !=!*k; end; return ! -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Cat2: procedure expose c.; parse arg n; $=0; if c.n\==. then return c.n - do k=0 for n; $=$ + Cat2(k) * Cat2(n-k-1); end - c.n=$; return $ /*use a memoization technique.*/ +/* REXX --------------------------------------------------------------- +* 01.07.2014 Walter Pachl +*--------------------------------------------------------------------*/ +Numeric Digits 1000 +Parse Arg m . +If m='' Then m=20 +Do i=0 To m + c1.i=c1(i) + End +c2.=1 +Do i=1 To m + c2.i=c2(i) + End +c3.=1 +Do i=1 To m + im1=i-1 + c3.i=2*(2*i-1)*c3.im1/(i+1) + End +l=length(c3.m) +hdr=' n' right('c1.n',l), + right('c2.n',l), + right('c3.n',l) +Say hdr +Do i=0 To m + Say right(i,2) format(c1.i,l), + format(c2.i,l), + format(c3.i,l) + End +Say hdr +Exit + +c1: Procedure +Parse Arg n +return fact(2*n)/(fact(n)*fact(n+1)) + +c2: Procedure Expose c2. +Parse Arg n +res=0 +Do i=0 To n-1 + nmi=n-i-1 + res=res+c2.i*c2.nmi + End +Return res + +fact: Procedure +Parse Arg n +f=1 +Do i=1 To n + f=f*i + End +Return f diff --git a/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx b/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx index b523782cf9..16a319accc 100644 --- a/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx +++ b/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx @@ -1,51 +1,47 @@ -/* REXX --------------------------------------------------------------- -* 01.07.2014 Walter Pachl -*--------------------------------------------------------------------*/ -Numeric Digits 1000 -Parse Arg m . -If m='' Then m=20 -Do i=0 To m - c1.i=c1(i) - End -c2.=1 -Do i=1 To m - c2.i=c2(i) - End -c3.=1 -Do i=1 To m - im1=i-1 - c3.i=2*(2*i-1)*c3.im1/(i+1) - End -l=length(c3.m) -hdr=' n' right('c1.n',l), - right('c2.n',l), - right('c3.n',l) -Say hdr -Do i=0 To m - Say right(i,2) format(c1.i,l), - format(c2.i,l), - format(c3.i,l) - End -Say hdr -Exit +-- 22 Mar 2025 +include Settings -c1: Procedure -Parse Arg n -return fact(2*n)/(fact(n)*fact(n+1)) +say 'CATALAN NUMBERS' +say version +say +call GetCatalan 15 +call First 15 +call GetCatalan 10000 +call CalcCatalan 1000000,16 +exit -c2: Procedure Expose c2. -Parse Arg n -res=0 -Do i=0 To n-1 - nmi=n-i-1 - res=res+c2.i*c2.nmi - End -Return res +GetCatalan: +procedure expose cata. +call Time('r') +arg xx +say 'Get Catalan numbers up to the' xx'th with full precision...' +call Catalans(-xx-1) +say Format(Time('e'),,3) 'seconds'; say +return -fact: Procedure -Parse Arg n -f=1 -Do i=1 To n - f=f*i - End -Return f +First: +procedure expose cata. +call Time('r') +arg xx +say 'The first' xx 'Catalan numbers...' +do i = 0 to xx-1 + say 'C['i'] =' cata.i +end +say Format(Time('e'),,3) 'seconds'; say +return + +CalcCatalan: +procedure expose cata. +call Time('r') +arg xx,yy +say 'Calculate Catalan('xx') with' yy 'digits precision...' +numeric digits yy +say catalann(xx)+0 +say Format(Time('e'),,3) 'seconds'; say +return + +include Sequences +include Numbers +include Functions +include Constants +include Abend diff --git a/Task/Chaocipher/EasyLang/chaocipher.easy b/Task/Chaocipher/EasyLang/chaocipher.easy index 3d9af716be..f2eb029db7 100644 --- a/Task/Chaocipher/EasyLang/chaocipher.easy +++ b/Task/Chaocipher/EasyLang/chaocipher.easy @@ -1,8 +1,8 @@ -proc index c$ . a$[] ind . +func index a$[] c$ . for ind = 1 to len a$[] - if a$[ind] = c$ : return + if a$[ind] = c$ : return ind . - ind = 0 + return 0 . left$ = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" right$ = "PTLNBQDEOYSFAVZKGJRIHWXUMC" @@ -13,11 +13,11 @@ func$ chao txt$ mode . len tmp$[] 26 for c$ in strchars txt$ if mode = 1 - index c$ right$[] ind + ind = index right$[] c$ if ind = 0 : return "" r$ &= left$[ind] else - index c$ left$[] ind + ind = index left$[] c$ if ind = 0 print c$ return "" diff --git a/Task/Chaos-game/EasyLang/chaos-game.easy b/Task/Chaos-game/EasyLang/chaos-game.easy index 80ec728f53..20f9411330 100644 --- a/Task/Chaos-game/EasyLang/chaos-game.easy +++ b/Task/Chaos-game/EasyLang/chaos-game.easy @@ -1,11 +1,10 @@ -color 900 +gcolor 900 x[] = [ 0 100 50 ] -y[] = [ 7 7 93 ] +y[] = [ 14 14 100 ] x = randomf * 100 y = randomf * 100 for i = 1 to 100000 - move x y - rect 0.3 0.3 + grect x y 0.3 0.3 h = random 3 x = (x + x[h]) / 2 y = (y + y[h]) / 2 diff --git a/Task/Character-codes/Ballerina/character-codes.ballerina b/Task/Character-codes/Ballerina/character-codes.ballerina new file mode 100644 index 0000000000..c16ce85fc2 --- /dev/null +++ b/Task/Character-codes/Ballerina/character-codes.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +public function main() returns error? { + int[] cps = []; + foreach string c in ["a", "π", "字", "🐘"] { + int cp = c[0].toCodePointInt(); + cps.push(cp); + io:println(`${c} = ${cp}`); + } + io:println(); + foreach int i in cps { + var c = check string:fromCodePointInt(i); + io:println(`${i} = ${c}`); + } +} diff --git a/Task/Character-codes/Crystal/character-codes.cr b/Task/Character-codes/Crystal/character-codes.cr new file mode 100644 index 0000000000..5fb1cfa9e7 --- /dev/null +++ b/Task/Character-codes/Crystal/character-codes.cr @@ -0,0 +1,2 @@ +'Ω'.ord # => 937 +937.chr # => 'Ω' diff --git a/Task/Character-codes/M2000-Interpreter/character-codes.m2000 b/Task/Character-codes/M2000-Interpreter/character-codes.m2000 index f334be9e7a..2f909d53d2 100644 --- a/Task/Character-codes/M2000-Interpreter/character-codes.m2000 +++ b/Task/Character-codes/M2000-Interpreter/character-codes.m2000 @@ -7,16 +7,33 @@ Print ChrCode$(ChrCode("a")) \\ (,) is an empty array. -Function Codes(a$) { - If Len(A$)=0 then =(,) : Exit - Buffer Mem as byte*Len(a$) - \\ Str$(string) return one byte character - Return Mem, 0:=Str$(a$) - Inventory Codes - For i=0 to len(Mem)-1 - Append Codes, i:=Eval(Mem, i) - Next i - =Codes +Function Codes(a$, localeID=1033) { + If Len(A$)=0 then =(,) : Exit + \\ Str$(string) return one byte character + oldlocale=locale + locale localeID + a=Str$(a$) + locale oldlocale + Codes=(,) + locale 1033 + // 1 byte length returns 0.5 from len() ' 1 for 2 bytes. + // chr$(string) convert to UTF16LE with current LOCALE + For i=1 to len(a)*2 + Append Codes, (chrcode(chr$(mid$(a,i,1 as byte))),) + Next i + locale oldlocale + =Codes } -Print Codes("abcd") -\\ 97 98 99 100 +Print Codes("abcdΩ", 1032)#str$(", ") +\\ 97, 98, 99, 100, 217 + +Function CodesUNICODE(a) { + If Len(a)=0 then =(,) : Exit + Codes=(,) + For i=1 to len(a) + Append Codes, (chrcode(mid$(a,i,1)),) + Next i + =Codes +} +Print CodesUNICODE("abcdΩ")#str$(", ") +\\ 97, 98, 99, 100, 937 diff --git a/Task/Character-codes/OPL/character-codes.opl b/Task/Character-codes/OPL/character-codes.opl new file mode 100644 index 0000000000..05ff6d3090 --- /dev/null +++ b/Task/Character-codes/OPL/character-codes.opl @@ -0,0 +1,5 @@ +PROC main: + PRINT "a ->",ASC("a") + PRINT "97 ->",CHR$(97) + GET +ENDP diff --git a/Task/Character-codes/S-BASIC/character-codes.basic b/Task/Character-codes/S-BASIC/character-codes.basic new file mode 100644 index 0000000000..c3a772f23b --- /dev/null +++ b/Task/Character-codes/S-BASIC/character-codes.basic @@ -0,0 +1,14 @@ +var ch = char +var n = integer + +ch = 'a' +n = ch +print ch; " = "; n +print ch; " = "; asc(ch) + +n = 97 +ch = n +print n; " = "; ch +print n; " = "; chr$(n) + +end diff --git a/Task/Character-codes/Uxntal/character-codes.uxnatl b/Task/Character-codes/Uxntal/character-codes.uxnatl index 0429ace25f..f2fd52e587 100644 --- a/Task/Character-codes/Uxntal/character-codes.uxnatl +++ b/Task/Character-codes/Uxntal/character-codes.uxnatl @@ -1,26 +1,19 @@ -( uxnasm char-codes.tal char-codes.rom && uxncli char-codes.rom ) +%\n { 0a } +%newline { [ LIT2 \n -Console/write ] DEO } -|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|18 @Console/write -|0100 - [ LIT "a ] print-hex - newline - #61 .Console/write DEO - newline +|100 + +[ LIT "a ] print/byte newline +#61 .Console/write DEO newline - ( exit ) - #80 .System/state DEO BRK -@print-hex - DUP #04 SFT print-digit #0f AND print-digit -JMP2r - -@print-digit - DUP #09 GTH #27 MUL ADD #30 ADD .Console/write DEO -JMP2r - -@newline - #0a .Console/write DEO -JMP2r +@print/byte ( byte -- ) + DUP #04 SFT /nibble + ( >> ) + +@print/nibble ( byte -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO + JMP2r diff --git a/Task/Check-Machin-like-formulas/00-TASK.txt b/Task/Check-Machin-like-formulas/00-TASK.txt index d6db6e1191..c28978d512 100644 --- a/Task/Check-Machin-like-formulas/00-TASK.txt +++ b/Task/Check-Machin-like-formulas/00-TASK.txt @@ -35,7 +35,7 @@ These identities are useful in calculating the values:
You can store the equations in any convenient data structure, but for extra credit parse them from human-readable [[Check_Machin-like_formulas/text_equations|text input]]. -Note: to formally prove the formula correct, it would have to be shown that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity. +Note: to formally prove the formula correct, it would have to be shown that ''{-3 \pi \over 4} < right hand side < {5 \pi \over 4}'' due to ''\tan()'' periodicity.

diff --git a/Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua b/Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua new file mode 100644 index 0000000000..53aa2d1991 --- /dev/null +++ b/Task/Check-input-device-is-a-terminal/Lua/check-input-device-is-a-terminal.lua @@ -0,0 +1,6 @@ +local posix = require"posix" +print( + posix.unistd.isatty(posix.stdio.fileno(io.stdin)) + and "stdin is a terminal" + or "stdin is not a terminal" +) diff --git a/Task/Check-that-file-exists/Lua/check-that-file-exists-3.lua b/Task/Check-that-file-exists/Lua/check-that-file-exists-3.lua new file mode 100644 index 0000000000..625b373fee --- /dev/null +++ b/Task/Check-that-file-exists/Lua/check-that-file-exists-3.lua @@ -0,0 +1,10 @@ +function Verify(filename) + print(filename + , os.rename(filename, filename) and "exists" or "void" + ) +end + +for _, v in ipairs{"input.txt","docs"} do + Verify("/" .. v) + Verify(v) +end diff --git a/Task/Chernicks-Carmichael-numbers/00-TASK.txt b/Task/Chernicks-Carmichael-numbers/00-TASK.txt index 24b0de17b9..328b8a9863 100644 --- a/Task/Chernicks-Carmichael-numbers/00-TASK.txt +++ b/Task/Chernicks-Carmichael-numbers/00-TASK.txt @@ -1,18 +1,18 @@ [[category:Prime Numbers]] -In 1939, Jack Chernick proved that, for '''n ≥ 3''' and '''m ≥ 1''': +In 1939, Jack Chernick proved that, for '''n \ge 3''' and '''m \ge 1''': - U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) + U(n, m) = (6m + 1) (12m + 1) \prod_{k=1}^{n-2} (2^k \, 9m + 1) -is a [https://en.wikipedia.org/wiki/Carmichael_number Carmichael number] if all the factors are primes and, for '''n > 4''', '''m''' is a multiple of '''2^(n-4)'''. +is a [https://en.wikipedia.org/wiki/Carmichael_number Carmichael number] if all the factors are primes and, for '''n > 4''', '''m''' is a multiple of '''2^{(n-4)}'''. ;Example - U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) - U(4, m) = U(3, m) * (2^2 * 9m + 1) - U(5, m) = U(4, m) * (2^3 * 9m + 1) - ... - U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1) + U(3, m) = (6m + 1) (12m + 1) (18m + 1) + U(4, m) = U(3, m) (2^2 9m + 1) + U(5, m) = U(4, m) (2^3 9m + 1) + \cdots + U(n, m) = U(n-1, m) (2^{(n-2)} 9m + 1) * The smallest Chernick's Carmichael number with '''3''' prime factors, is: U(3, 1) = 1729. * The smallest Chernick's Carmichael number with '''4''' prime factors, is: U(4, 1) = 63973. @@ -42,7 +42,7 @@ For '''n ≥ 3''', let '''a(n)''' be the smallest Chernick's Carmichael number w ;See also -* [http://www.ams.org/journals/bull/1939-45-04/S0002-9904-1939-06953-X/S0002-9904-1939-06953-X.pdf Jack Chernick, On Fermat's simple theorem (PDF)] +* [http://www.ams.org/journals/bull/1939-45-04/S0002-9904-1939-06953-X/S0002-9904-1939-06953-X.pdf Jack Chernick, On Fermat's simple theorem (PDF)], equation (8) * [https://oeis.org/A318646 OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors] diff --git a/Task/Chernicks-Carmichael-numbers/REXX/chernicks-carmichael-numbers.rexx b/Task/Chernicks-Carmichael-numbers/REXX/chernicks-carmichael-numbers.rexx index c85f58b9a7..12d100bc75 100644 --- a/Task/Chernicks-Carmichael-numbers/REXX/chernicks-carmichael-numbers.rexx +++ b/Task/Chernicks-Carmichael-numbers/REXX/chernicks-carmichael-numbers.rexx @@ -1,6 +1,8 @@ include Settings -say version; say 'Chernick''s Carmichael numbers'; say +say 'CHERNICKS'' CARMICHAEL NUMBERS - 3 Mar 2025' +say version +say numeric digits 80 say Copies('-',80) say 'n m(n) a(n)' diff --git a/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy b/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy index bd49a7065b..f5d8249052 100644 --- a/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy +++ b/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy @@ -1,4 +1,4 @@ -func mul_inv a b . +func mulinv a b . b0 = b x1 = 1 if b <> 1 @@ -11,25 +11,21 @@ func mul_inv a b . x0 = x1 - q * x0 x1 = t . - if x1 < 0 - x1 += b0 - . + if x1 < 0 : x1 += b0 . return x1 . -proc remainder . n[] a[] r . +func remainder &n[] &a[] . prod = 1 - sum = 0 for i = 1 to len n[] prod *= n[i] . for i = 1 to len n[] p = prod / n[i] - sum += a[i] * (mul_inv p n[i]) * p - r = sum mod prod + sum += a[i] * (mulinv p n[i]) * p . + return sum mod prod . n[] = [ 3 5 7 ] a[] = [ 2 3 2 ] -remainder n[] a[] h -print h +print remainder n[] a[] diff --git a/Task/Chinese-zodiac/EasyLang/chinese-zodiac.easy b/Task/Chinese-zodiac/EasyLang/chinese-zodiac.easy index 09078eb7fb..9ce1c61692 100644 --- a/Task/Chinese-zodiac/EasyLang/chinese-zodiac.easy +++ b/Task/Chinese-zodiac/EasyLang/chinese-zodiac.easy @@ -4,7 +4,7 @@ yingyang$[] = [ "Yang" "Yin" ] animal_ch$[] = strchars "子丑寅卯辰巳午未申酉戌亥" stem_ch$[] = strchars "甲乙丙丁戊己庚辛壬癸" # -proc get year . el$ an$ yy$ anch$ stch$ . +proc get year &el$ &an$ &yy$ &anch$ &stch$ . idx = (year - 4) mod 10 el$ = element$[idx div 2 + 1] stch$ = stem_ch$[idx + 1] @@ -13,7 +13,7 @@ proc get year . el$ an$ yy$ anch$ stch$ . anch$ = animal_ch$[idx + 1] yy$ = yingyang$[year mod 2 + 1] . -proc zodiac year . . +proc zodiac year . get year el$ an$ yy$ anch$ stch$ print year cycle = (year - 1983) mod1 60 diff --git a/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg b/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg index 641726dfd2..879053ae5c 100644 --- a/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg +++ b/Task/Chowla-numbers/ALGOL-68/chowla-numbers.alg @@ -1,4 +1,4 @@ -BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 ) # +BEGIN # find some Chowla numbers ( Chowla n = sum of divisors of n excluding n and 1 ) # # returs the Chowla number of n # PROC chowla = ( INT n )INT: BEGIN diff --git a/Task/Chowla-numbers/Ada/chowla-numbers.ada b/Task/Chowla-numbers/Ada/chowla-numbers.ada index 8b9451b145..4f48ba270c 100644 --- a/Task/Chowla-numbers/Ada/chowla-numbers.ada +++ b/Task/Chowla-numbers/Ada/chowla-numbers.ada @@ -35,7 +35,7 @@ procedure Chowla_Numbers is Count := Count + 1; end if; if N mod Power = 0 then - Put_Line ("There is " & Count'Image & " primes < " & Power'Image); + Put_Line ("There are " & Count'Image & " primes < " & Power'Image); Power := Power * 10; end if; end loop; diff --git a/Task/Chowla-numbers/EasyLang/chowla-numbers.easy b/Task/Chowla-numbers/EasyLang/chowla-numbers.easy index 612642b535..3cecf7520f 100644 --- a/Task/Chowla-numbers/EasyLang/chowla-numbers.easy +++ b/Task/Chowla-numbers/EasyLang/chowla-numbers.easy @@ -1,5 +1,4 @@ fastfunc chowla n . - sum = 0 i = 2 while i * i <= n if n mod i = 0 @@ -14,7 +13,7 @@ fastfunc chowla n . . return sum . -proc sieve . c[] . +proc sieve &c[] . i = 3 while i * 3 <= len c[] if c[i] = 0 @@ -29,23 +28,22 @@ proc sieve . c[] . i += 2 . . -proc commatize n . s$ . +func$ comma n . s$[] = strchars n s$ = "" l = len s$[] for i = 1 to len s$[] - if i > 1 and l mod 3 = 0 - s$ &= "," - . + if i > 1 and l mod 3 = 0 : s$ &= "," l -= 1 s$ &= s$[i] . + return s$ . print "chowla number from 1 to 37" for i = 1 to 37 print " " & i & ": " & chowla i . -proc main . . +proc main . print "" len c[] 10000000 count = 1 @@ -53,13 +51,9 @@ proc main . . power = 100 i = 3 while i <= len c[] - if c[i] = 0 - count += 1 - . + if c[i] = 0 : count += 1 if i = power - 1 - commatize power p$ - commatize count c$ - print "There are " & c$ & " primes up to " & p$ + print "There are " & comma count & " primes up to " & comma power power *= 10 . i += 2 @@ -74,15 +68,13 @@ proc main . . p = k * kk until p > limit if chowla p = p - 1 - commatize p s$ - print s$ & " is a perfect number" + print comma p & " is a perfect number" count += 1 . k = kk + 1 kk += k i += 1 . - commatize limit s$ - print "There are " & count & " perfect mumbers up to " & s$ + print "There are " & count & " perfect mumbers up to " & comma limit . main diff --git a/Task/Chowla-numbers/REXX/chowla-numbers-1.rexx b/Task/Chowla-numbers/REXX/chowla-numbers-1.rexx deleted file mode 100644 index 54447064f1..0000000000 --- a/Task/Chowla-numbers/REXX/chowla-numbers-1.rexx +++ /dev/null @@ -1,29 +0,0 @@ -/*REXX program computes/displays chowla numbers (and may count primes & perfect numbers.*/ -parse arg LO HI . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -perf= LO<0; LO= abs(LO) /*Negative? Then determine if perfect.*/ -if HI=='' | HI=="," then HI= LO /*Not specified? Then use the default.*/ -prim= HI<0; HI= abs(HI) /*Negative? Then determine if a prime.*/ -numeric digits max(9, length(HI) + 1 ) /*use enough decimal digits for // */ -w= length( commas(HI) ) /*W: used in aligning output numbers.*/ -tell= \(prim | perf) /*set boolean value for showing chowlas*/ -p= 0 /*the number of primes found (so far).*/ - do j=LO to HI; #= chowla(j) /*compute the cholwa number for J. */ - if tell then say right('chowla('commas(j)")", w+9) ' = ' right( commas(#), w) - else if #==0 then if j>1 then p= p+1 - if perf then if j-1==# & j>1 then say right(commas(j), w) ' is a perfect number.' - end /*j*/ - -if prim & \perf then say 'number of primes found for the range ' commas(LO) " to " , - commas(HI) " (inclusive) is: " commas(p) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -chowla: procedure; parse arg x; if x<2 then return 0; odd= x // 2 - s=0 /* [↓] use EVEN or ODD integers. ___*/ - do k=2+odd by 1+odd while k*k 2 - return 0 - . + if n mod 2 = 0 and n > 2 : return 0 i = 3 - sq = sqrt n - while i <= sq - if n mod i = 0 - return 0 - . + while i <= sqrt n + if n mod i = 0 : return 0 i += 2 . return 1 @@ -22,14 +17,10 @@ func cycle n . return m + n mod p * 10 . func circprime p . - if prime p = 0 - return 0 - . + if prime p = 0 : return 0 p2 = cycle p while p2 <> p - if p2 < p or prime p2 = 0 - return 0 - . + if p2 < p or prime p2 = 0 : return 0 p2 = cycle p2 . return 1 @@ -37,7 +28,7 @@ func circprime p . p = 2 while count < 19 if circprime p = 1 - print p + write p & " " count += 1 . p += 1 diff --git a/Task/Circular-primes/REXX/circular-primes-1.rexx b/Task/Circular-primes/REXX/circular-primes-1.rexx deleted file mode 100644 index 129443ee9a..0000000000 --- a/Task/Circular-primes/REXX/circular-primes-1.rexx +++ /dev/null @@ -1,37 +0,0 @@ -/*REXX program finds & displays circular primes (with a title & in a horizontal format).*/ -parse arg N hp . /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 19 /* " " " " " " */ -if hp=='' | hp=="," then hip= 1000000 /* " " " " " " */ -call genP /*gen primes up to hp (200,000). */ -q= 024568 /*digs that most circular P can't have.*/ -found= 0; $= /*found: circular P count; $: a list.*/ - do j=1 until found==N; p= @.j /* [↓] traipse through all the primes.*/ - if p>9 & verify(p, q, 'M')>0 then iterate /*Does J contain forbidden digs? Skip.*/ - if \circP(p) then iterate /*Not circular? Then skip this number.*/ - found= found + 1 /*bump the count of circular primes. */ - $= $ p /*add this prime number ──► $ list. */ - end /*j*/ /*at this point, $ has a leading blank.*/ - -say center(' first ' found " circular primes ", 79, '─') -say strip($) -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -circP: procedure expose @. !.; parse arg x 1 ox /*obtain a prime number to be examined.*/ - do length(x)-1; parse var x f 2 y /*parse X number, rotating the digits*/ - x= y || f /*construct a new possible circular P. */ - if x 0 then iterate i b = a; l = Length(b) @@ -21,7 +24,7 @@ do i = 1 to p b = Right(b,l-1)||Left(b,1) if b < a then iterate i - if \ prime(b) then + if \ Prime(b) then iterate i end call Charout ,a' ' @@ -38,8 +41,8 @@ numeric digits 320 say 'Next 3 circular primes:' do i = 7 to 320 r = Repunit(i) - if prime(r) then - call charout ,'R('i') ' + if Prime(r) then + call Charout ,'R('i') ' end say say Format(Time('e'),,3) 'seconds' @@ -51,7 +54,7 @@ procedure expose glob. call Time('r') numeric digits 1040 say 'Primality of R(1031):' -if prime(Repunit(1031)) then +if Prime(Repunit(1031)) then say 'R(1031) is probable prime' else say 'R(1031) is composite' @@ -59,14 +62,8 @@ say Format(Time('e'),,3) 'seconds' say return -Repunit: -/* Repeat 1's function */ -procedure expose glob. -arg x -/* Formula */ -return Copies('1',x) - include Functions +include Special include Numbers include Sequences include Abend diff --git a/Task/Circular-primes/Scheme/circular-primes.scm b/Task/Circular-primes/Scheme/circular-primes.scm new file mode 100644 index 0000000000..a5cfdebbd1 --- /dev/null +++ b/Task/Circular-primes/Scheme/circular-primes.scm @@ -0,0 +1,82 @@ +(import srfi-1) + +; rotate list by n +(define (rotate lst n) + (if (> n 0) + (append (drop lst n) (take lst n)) + (append (take-right lst (abs n)) (drop-right lst (abs n))))) + + +; prime check +(define (prime? n) + (if (< n 4) (> n 1) + (and (odd? n) + (let loop ((k 3)) + (or (> (* k k) n) + (and (positive? (remainder n k)) + (loop (+ k 2)))))))) + +; returns number rotated in lists +(define (circ_lists lst) + (let + ( + (len (length lst)) + ) + (do ( + (remaining 1 (+ 1 remaining)) + (circs '() (cons (rotate lst remaining) circs )) + ) + ((< len remaining) circs) + ) + + ) +) + +; helper function to make number a list to rotate it +(define (number->list x) + (string->list (number->string x)) +) + +; returns list to number +(define (list->number x) + (string->number (list->string x)) +) + +; checks if number is prime when the number is turned into lists +(define (check x) + (not (member #f (map prime? (map list->number (circ_lists (number->list x)))))) + ) + +; all permutations of a number +(define (perms x) + (map list->number (circ_lists (number->list x))) +) + +(define limit 19) + +; checks if all permutations of x are not in lst +(define (not_perm x lst) + (equal? '() (filter-map (lambda (x) (not (equal? #f x))) + (map (lambda (x) (member x lst)) (perms x)))) + ) + + +(define (circular_primes x lst) + (cond + ( + (< (length lst) limit) + ; if is true if all permutations are prime and if all permutations are not already in the lst, which is returned + (if (and (equal? #t (check x)) (equal? #t (not_perm x lst))) + (circular_primes (+ x 1) (cons x lst)) + (circular_primes (+ x 1) lst) + ) + ) + ( + lst + ) + ) + ) + +(display (reverse (circular_primes 2 '()))) + +(newline) diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-1.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-1.ada new file mode 100644 index 0000000000..87889f9cd1 --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-1.ada @@ -0,0 +1,92 @@ +-- cistercian_numerals.adb +-- +-- test program for the Cistercian Representation Library +-- possibly overengineered in order to demonstrate use of types, +-- conditions, etc. +-- threw in some exception handling + +-- modern Ada +pragma Ada_2022; + +pragma Assertion_Policy (Check); + +-- imports + +with Ada.Text_IO; + +with Cistercian; +with Cistercian.Ascii; +with Cistercian.Ascii_Requirements; + +procedure Cistercian_Numerals is + + package IO renames Ada.Text_IO; + + Test_Values : constant array (1 .. 8) of Cistercian.Representable_Range := + [0, 1, 20, 300, 4_000, 5_555, 6_789, 1_983]; + -- test values required by task + User_Value : Integer; + -- value user requests + + Temp : Integer; + Dimension : Cistercian.Ascii_Requirements.Valid_Dimension; + +begin + + loop + begin + IO.Put_Line ("How large would you like your Cistercian numerals?"); + IO.Put_Line ("(You must supply an odd number greater than 5)"); + IO.Put ("> "); + Dimension := + Cistercian.Ascii_Requirements.Valid_Dimension'Value (IO.Get_Line); + -- kind of perplexed why I have to assert this + -- when the dynamic predicate should do so + pragma + Assert (Dimension in Cistercian.Ascii_Requirements.Valid_Dimension); + exit; + exception + when others => + IO.Put_Line ("You must supply an odd number greater than 5"); + end; + end loop; + + declare + package Cist_Ascii is new Cistercian.Ascii (Dimension); + begin + + -- first print test values + for Value of Test_Values loop + begin + IO.Put_Line + ("The Cistercian representation of" & Value'Image & " is:"); + Cist_Ascii.Put (Cistercian.From (Value)); + IO.New_Line; + exception + when others => + IO.Put_Line ("Hit an unrecoverable error. Terminating"); + return; + end; + end loop; + + -- now let user choose own values + loop + begin + IO.Put ("What other value would you like to see? "); + IO.Put_Line ("(enter a negative number to stop) "); + IO.Put ("? "); + User_Value := Integer'Value (IO.Get_Line); + Cist_Ascii.Put (Cistercian.From (User_Value)); + IO.New_Line; + exception + when others => + if User_Value < 0 then + exit; + end if; + IO.Put_Line ("Please enter a valid number from 0 to 9999."); + IO.Put ("? "); + end; + end loop; + end; + +end Cistercian_Numerals; diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-2.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-2.ada new file mode 100644 index 0000000000..d2f8f44da9 --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-2.ada @@ -0,0 +1,36 @@ +-- cistercian.ads +-- representations of Cistercian numbers + +package Cistercian is + + type Representation is private; + -- this type holds the Cistercian representation of a number + + subtype Representable_Range is Natural range 0 .. 9999; + -- the system only works with values in this range + + function From (Value : Representable_Range) return Representation; + -- converts `Value` to a `Representation` + + type Quadrant is (Ones, Tens, Hundreds, Thousands); + -- corresponds to the quadrants used by the system + + type Strokes_Enum is (Diag_From_Far, Diag_From_Near, Far, Near, Side); + -- corresponds to the line segments: + -- * Diag_From_Far corresponds to what you'll see in 3, 30, 300, 3000 + -- * Diag_From_Near corresponds to what you'll see in 4, 40, 400, 4000 + -- * Far corresponds to what you'll see in 1, 10, 100, 1000 + -- * Near corresponds to what you'll see in 2, 20, 200, 2000 + -- * Side corresponds to what you'll see in 6, 60, 600, 6000 + -- + -- the others are combinations of these + +private + + type Stroke_Used_Array is array (Strokes_Enum) of Boolean; + -- whether a stroke should be set + + type Representation is array (Quadrant) of Stroke_Used_Array; + -- indicates which quadrants' strokes are set + +end Cistercian; diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-3.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-3.ada new file mode 100644 index 0000000000..1757bd50b3 --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-3.ada @@ -0,0 +1,49 @@ +-- cistercian.adb + +pragma Ada_2022; + +package body Cistercian is + + subtype Digit_Range is Natural range 0 .. 9; + + Digit_Strokes : constant array (Digit_Range) of Stroke_Used_Array := + [0 => [others => False], + 1 => [Far => True, others => False], + 2 => [Near => True, others => False], + 3 => [Diag_From_Far => True, others => False], + 4 => [Diag_From_Near => True, others => False], + 5 => [Diag_From_Near => True, Far => True, others => False], + 6 => [Side => True, others => False], + 7 => [Far => True, Side => True, others => False], + 8 => [Near => True, Side => True, others => False], + 9 => [Far => True, Near => True, Side => True, others => False]]; + -- maps each digit to the corresponding strokes + -- this makes it easy for us to assign strokes later + + function From (Value : Representable_Range) return Representation is + -- converts Value to a Representation + Result : Representation; + + -- obtain digits, then... + + Ones_Digit : constant Digit_Range := Value rem 10; + Tens_Digit : constant Digit_Range := ((Value - Ones_Digit) / 10) rem 10; + Hund_Digit : constant Digit_Range := + ((Value - (Tens_Digit * 10 + Ones_Digit)) / 100) rem 10; + Thou_Digit : constant Digit_Range := + (Value - (Hund_Digit * 100 + Tens_Digit * 10 + Ones_Digit)) / 1000; + + begin + + -- assign strokes to corresponding quadrants + + Result (Ones) := Digit_Strokes (Ones_Digit); + Result (Tens) := Digit_Strokes (Tens_Digit); + Result (Hundreds) := Digit_Strokes (Hund_Digit); + Result (Thousands) := Digit_Strokes (Thou_Digit); + + return Result; + + end From; + +end Cistercian; diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-4.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-4.ada new file mode 100644 index 0000000000..907571096b --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-4.ada @@ -0,0 +1,54 @@ +-- cistercian-motion.ads +-- +-- details information on how to draw each Cistercian stroke +-- +-- this is fairly general, so it should be adaptable to any medium, +-- though we have adapted it only to ASCII + +pragma Ada_2022; + +with Cistercian; use Cistercian; + +package Cistercian.Motion is + type Start_Enum is (Near, Far); + -- whether the stroke starts near to or far from the center + + subtype Motion_Delta is Integer range -1 .. 1; + -- how the pen should step across the image in a given dimension + + type Motion_Record is record + -- record of a stroke's motion: + -- the location to start, as well as which direction to move + Col_Start, Row_Start : Start_Enum; + Col_Delta, Row_Delta : Motion_Delta; + end record; + + Stroke_Arrangement : + constant array (Quadrant, Cistercian.Strokes_Enum) of Motion_Record := + [Ones => + [Diag_From_Far => (Near, Far, 1, 1), + Diag_From_Near => (Near, Near, 1, -1), + Far => (Near, Far, 1, 0), + Near => (Near, Near, 1, 0), + Side => (Far, Far, 0, 1)], + Tens => + [Diag_From_Far => (Near, Far, -1, 1), + Diag_From_Near => (Far, Far, 1, 1), + Far => (Far, Far, 1, 0), + Near => (Far, Near, 1, 0), + Side => (Far, Far, 0, 1)], + Hundreds => + [Diag_From_Far => (Near, Far, 1, -1), + Diag_From_Near => (Near, Near, 1, 1), + Far => (Near, Far, 1, 0), + Near => (Near, Near, 1, 0), + Side => (Far, Near, 0, 1)], + Thousands => + [Diag_From_Far => (Far, Near, 1, 1), + Diag_From_Near => (Near, Near, -1, 1), + Far => (Far, Far, 1, 0), + Near => (Far, Near, 1, 0), + Side => (Far, Near, 0, 1)]]; + -- maps a quadrant-stoke pair to a motion + +end Cistercian.Motion; diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-5.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-5.ada new file mode 100644 index 0000000000..6a0a804035 --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-5.ada @@ -0,0 +1,9 @@ +-- cistercian-ascii_requirements.ads +-- +-- have to separate this because gnat requires only one compilation unit +-- per file + +package Cistercian.Ascii_Requirements is + subtype Valid_Dimension is Positive + with Static_Predicate => Valid_Dimension > 5; +end Cistercian.Ascii_Requirements; diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-6.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-6.ada new file mode 100644 index 0000000000..75e07a62dc --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-6.ada @@ -0,0 +1,54 @@ +-- cistercian-ascii.ads +-- ASCII printout of Cistercian representations +-- this is generic, so that you can make it as large as you like +-- (within reason) + +pragma Ada_2022; + +with Cistercian.Ascii_Requirements; + +generic + Dimension : Cistercian.Ascii_Requirements.Valid_Dimension := 7; +package Cistercian.Ascii is + + type Block (<>) is private; + -- as i understand it, this particular use of the discriminant + -- prevents the client from instantiating a `Block` without + -- going through one of our generator functions, + -- and the only one of those is `Zero` + + function Zero return Block; + -- returns a `Block` corresponding to 0; + -- i.e., a vertical line through the center + + function From (Value : Cistercian.Representation) return Block; + -- converts a Cistercian representation to an ASCII block + + procedure Put (Value : Cistercian.Representation); + -- print the value to standard output + +private + + Max : constant Integer := (Dimension - 1) / 2; + -- the maximum coordinate we can access in any one dimension + Mid : constant Integer := Max / 2 + 1; + -- midway to `Max`, natch + + subtype Cistercian_Ascii_Range is Integer range -(Max + 1) .. (Max + 1); + -- we leave some room for aesthetic reasons + -- (i had another reason originally, but i don't think it applies anymore) + + type Block is + array (Cistercian_Ascii_Range, Cistercian_Ascii_Range) of Boolean; + -- an entry should be True iff it should be painted in a stroke + + function Zero return Block + is + -- just a vertical line in the middle + ([for Row in Block'Range (1) + => [for Col in Block'Range (2) + => (if Col = 0 and then abs (Row) < Max + 1 + then True + else False)]]); + +end Cistercian.Ascii; diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-7.ada b/Task/Cistercian-numerals/Ada/cistercian-numerals-7.ada new file mode 100644 index 0000000000..2bdc100450 --- /dev/null +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-7.ada @@ -0,0 +1,76 @@ +-- cistercian-ascii.adb + +pragma Ada_2022; + +with Ada.Text_IO; + +with Cistercian.Motion; + +package body Cistercian.Ascii is + + package IO renames Ada.Text_IO; + package CM renames Cistercian.Motion; + + function From (Value : Cistercian.Representation) return Block is + -- converts the representation to an ASCII block + + Result : Block := Zero; + + -- the extreme values for rows and columns, + -- as determine by where you want to start and which quadrant you're in + + Row_Extremes : + constant array (CM.Start_Enum, Quadrant) of Cistercian_Ascii_Range := + [CM.Far => [Ones | Tens => -Max, Hundreds | Thousands => Max], + CM.Near => [Ones | Tens => -1, Hundreds | Thousands => 1]]; + Col_Extremes : + constant array (CM.Start_Enum, Quadrant) of Cistercian_Ascii_Range := + [CM.Far => [Ones | Hundreds => Max, Tens | Thousands => -Max], + CM.Near => [Ones | Hundreds => 1, Tens | Thousands => -1]]; + + Row_Pos, Col_Pos : Cistercian_Ascii_Range; + Row_Delta, Col_Delta : CM.Motion_Delta; + + begin + + for Place in Quadrant loop + for Stroke in Cistercian.Strokes_Enum when Value (Place) (Stroke) loop + + -- obtain position and motion information + Row_Pos := + Row_Extremes + (CM.Stroke_Arrangement (Place, Stroke).Row_Start, Place); + Col_Pos := + Col_Extremes + (CM.Stroke_Arrangement (Place, Stroke).Col_Start, Place); + Row_Delta := CM.Stroke_Arrangement (Place, Stroke).Row_Delta; + Col_Delta := CM.Stroke_Arrangement (Place, Stroke).Col_Delta; + + -- make the stroke + for Ith in 1 .. Max loop + Result (Row_Pos, Col_Pos) := True; + Row_Pos := @ + Row_Delta; + Col_Pos := @ + Col_Delta; + end loop; + + end loop; + end loop; + + return Result; + + end From; + + procedure Put (Value : Cistercian.Representation) is + -- writes Value to standard output + X_At : constant Block := From (Value); + begin + + for Row in X_At'Range (1) loop + for Col in X_At'Range (2) loop + IO.Put ((if X_At (Row, Col) then 'X' else ' ')); + end loop; + IO.New_Line; + end loop; + end Put; + +end Cistercian.Ascii; diff --git a/Task/Cistercian-numerals/Applesoft-BASIC/cistercian-numerals.basic b/Task/Cistercian-numerals/Applesoft-BASIC/cistercian-numerals.basic new file mode 100644 index 0000000000..7d97acef9e --- /dev/null +++ b/Task/Cistercian-numerals/Applesoft-BASIC/cistercian-numerals.basic @@ -0,0 +1,6 @@ + 0 HGR : HCOLOR= 3: HOME : VTAB 21 : FOR I = 1 TO 8 : READ N$: N = VAL (N$): GOSUB 100: PRINT S$MID$ (" " + STR$ (N) + " ", VAL ( MID$ ("1223", LEN ( STR$ (N)),1)),4);: S$=" ":NEXT I : END: END : DATA0,1,20,300,4000,5555,6789,9080 + 100 N$ = RIGHT$ ("000" + STR$ (N),4):S = S + (S = 0) * 9:X = X + (X = 0) * (S + 4):Y = Y + (Y = 0) * (160 - S * 2):T = Y - S * 1.5:B = Y + S * 1.5: HPLOT X,T TO X,B TO X + 1,B TO X + 1,T + 110 FOR D = 1 TO 4:O = SGN (D - 2.5):A = VAL ( MID$ ("1331",D,1)) - 2:Y(0) = Y + S * 1.5 * A:Y(1) = Y + S * .5 * A:E$ = MID$ ("...1..2..3..4..14.6..16.26.126", VAL ( MID$ (N$,D,1)) * 3 + 1,3) + 120 FOR J = 1 TO 3:E = VAL ( MID$ (E$,J,1)): IF E THEN X1 = X + (S * O) * (E = 6):X2 = X + S * O:Y1 = Y( VAL ( MID$ ("0101.1",E,1))):Y2 = Y( VAL ( MID$ ("0110.0",E,1))): HPLOT X1,Y1 TO X2,Y2 TO X2 + 1,Y2 TO X1 + 1,Y1: NEXT J + 130 NEXT D:X = X + S * 4 - 1: IF X + S > 278 THEN X = S + 4:Y = Y + S * 4 + 140 RETURN diff --git a/Task/Cistercian-numerals/Crystal/cistercian-numerals.cr b/Task/Cistercian-numerals/Crystal/cistercian-numerals.cr new file mode 100644 index 0000000000..2ac7aadc41 --- /dev/null +++ b/Task/Cistercian-numerals/Crystal/cistercian-numerals.cr @@ -0,0 +1,96 @@ +def draw_cistercian_numerals (rows, *, size=20, decimals_size=0) + # characters are 2 units height, later scaled + hwidth = 0.888 # half width + line_width = 0.2 + hlw = line_width/2 + margin = line_width + scale = size/2 + interline = 0.2 + # top right quadrant is hwidth x -1. here are some distances from 0 + top = -1 + toph = top + hlw # center of top horizontal line + midv = -0.555 + bot = -0.111 + both = bot - hlw # center of bottom horizontal line + + # horizontal shift left for c3 & c4 + shift = hlw/Math.sin(Math.atan((top-bot).abs/(hwidth-hlw))) + + left = 0 # center of stem + leftx = hlw # right border of stem + midh = hwidth / 2 + right = hwidth + rightv = hwidth - hlw # center of right vertical line + + width = rows.max_of(&.size) * (2*hwidth + 2*margin) * scale + height = (rows.size * (2 + 2*margin) + (rows.size-1)*interline) * scale + + rows.size * decimals_size + + svg = String.build do |s| + s << <<-SVG << "\n" + + + + +SVG + # the digits' drawing instructions + digits = [[0,toph, 'H', right], # 1 + [0,midv, 'H', right], # 2 + [leftx-shift,top, 'L', right-shift,bot, 's'], # 3 + [leftx-shift,bot, 'L', right-shift,top, 's'], # 4 + [midh,midv, 'V', bot], # 5 + [midh,top, 'V', bot], # 6 + [0,toph, 'L', rightv,toph, rightv,bot], # 7 + [0,both, 'L', rightv,both, rightv,top], # 8 + [0,both, 'L', rightv,both, rightv,toph, 0,toph]] #9 + digits.map_with_index do |d, i| + s << %Q( \n) + end + s << "\n" + s << %Q(\n) + y = (2 + margin) * scale + rows.each do |row| + x = 0 + row.each do |number| + s << %Q( \n) + s << %Q( \n) + s << %Q( \n) + n = number + [nil, "scale(-1,1)", "rotate(180) scale(-1,1)", "rotate(180)"].each do |transform| + if n % 10 > 0 + s << %Q( \n" + end + n //= 10 + end + s << " \n \n" + if decimals_size > 0 + s << %Q( ) + s << %Q(#{number}\n) + end + x += (2*margin + 2*hwidth) * scale + end + y += (interline + 2*margin + 2) * scale + decimals_size + end + s << "\n" + end + puts svg +end + +draw_cistercian_numerals [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [20, 300, 4000, 5555, 6789, 1234, 6502, 2025, 8634, 5954], + (0..9).map { rand(10000) }], + size: 70, decimals_size: 18 diff --git a/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy b/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy index 766d24cc01..19b118bc31 100644 --- a/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy +++ b/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy @@ -1,5 +1,5 @@ -proc cist x y n . . - linewidth 0.5 +proc cist x y n . + glinewidth 0.5 dx[] = [ 4 -4 4 -4 ] dy[] = [ 4 4 -4 -4 ] for i to 4 @@ -8,43 +8,32 @@ proc cist x y n . . dy2 = 2 * dy d = n mod 10 n = n div 10 - move x y # - line x y + 8 - move x y - 8 - line x y + gline x y x y + 8 + gline x y - 8 x y if d = 1 - move x y + dy2 - line x + dx y + dy2 + gline x y + dy2 x + dx y + dy2 elif d = 2 - move x y + dy - line x + dx y + dy + gline x y + dy x + dx y + dy elif d = 3 - move x y + dy2 - line x + dx y + dy + gline x y + dy2 x + dx y + dy elif d = 4 - move x y + dy - line x + dx y + dy2 + gline x y + dy x + dx y + dy2 elif d = 5 - move x y + dy - line x + dx y + dy2 - line x y + dy2 + gline x y + dy x + dx y + dy2 + gline x + dx y + dy2 x y + dy2 elif d = 6 - move x + dx y + dy - line x + dx y + dy2 + gline x + dx y + dy x + dx y + dy2 elif d = 7 - move x y + dy2 - line x + dx y + dy2 - line x + dx y + dy + gline x y + dy2 x + dx y + dy2 + gline x + dx y + dy2 x + dx y + dy elif d = 8 - move x y + dy - line x + dx y + dy - line x + dx y + dy2 + gline x y + dy x + dx y + dy + gline x + dx y + dy x + dx y + dy2 elif d = 9 - move x y + dy - line x + dx y + dy - line x + dx y + dy2 - line x y + dy2 + gline x y + dy x + dx y + dy + gline x + dx y + dy x + dx y + dy2 + gline x + dx y + dy2 x y + dy2 . . x += 12 diff --git a/Task/Cistercian-numerals/FreeBASIC/cistercian-numerals.basic b/Task/Cistercian-numerals/FreeBASIC/cistercian-numerals.basic new file mode 100644 index 0000000000..d4fa35941d --- /dev/null +++ b/Task/Cistercian-numerals/FreeBASIC/cistercian-numerals.basic @@ -0,0 +1,95 @@ +Dim Shared As Byte dgs(0 To 9, 1 To 9, 0 To 2) +Dim As String c +Dim As Integer i, d + +Restore SegmentData +For d = 0 To 9 + For i = 1 To 9 + Read dgs(d, i, 0), dgs(d, i, 1), c + If c <> "" Then dgs(d, i, 2) = Asc(c) + Next +Next + +SegmentData: +Data 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 0 +Data 0,0,"+", 0,1,"-", 0,2,"-", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 1 +Data 2,0,"+", 2,1,"-", 2,2,"-", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 2 +Data 0,0,"+", 1,1,"\", 2,2,"\", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 3 +Data 2,0,"+", 1,1,"/", 0,2,"/", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 4 +Data 2,0,"+", 1,1,"/", 0,2,"+", 0,0,"+", 0,1,"-", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 5 +Data 0,2,"|", 1,2,"|", 2,2,"|", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 6 +Data 0,0,"+", 0,1,"-", 0,2,"+", 1,2,"|", 2,2,"|", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 7 +Data 2,0,"+", 2,1,"-", 2,2,"+", 1,2,"|", 0,2,"|", 0,0,"", 0,0,"", 0,0,"", 0,0,"" ' 8 +Data 2,0,"+", 2,1,"-", 2,2,"+", 1,2,"|", 0,2,"+", 0,1,"-", 0,0,"+", 0,0,"", 0,0,"" ' 9 + +Sub DrawDigit(canvas() As String, digit As Integer, position As Integer) + If digit < 0 Or digit > 9 Then Exit Sub + + Dim As Integer ud, lr, l, i + Select Case position + Case 1: ud = 1 : lr = 1 : l = 1 + Case 2: ud = 1 : lr = -1 : l = 1 + Case 3: ud = -1 : lr = 1 : l = 7 + Case 4: ud = -1 : lr = -1 : l = 7 + Case Else: Exit Sub + End Select + + For i = 1 To 9 + If dgs(digit, i, 0) = 0 And dgs(digit, i, 1) = 0 And dgs(digit, i, 2) = 0 Then Exit For + + Dim As Integer row = l + ud * dgs(digit, i, 0) + Dim As Integer col = 3 + lr * dgs(digit, i, 1) + Dim As String ch = Chr(dgs(digit, i, 2)) + + If Instr("/\", ch) Then + If ud <> lr Then + If ch = "/" Then + ch = "\" + Elseif ch = "\" Then + ch = "/" + End If + End If + End If + + If row >= 1 And row <= 7 And col >= 1 And col <= 5 Then Mid(canvas(row-1), col, 1) = Left(ch, 1) + Next +End Sub + +Sub ShowCistercianNumber(n As Integer) + Dim As Byte i + + Dim As String recanvas(0 To 7) + recanvas(0) = Right(" " & Str(n), 5) & ":" + Dim As String canvas(0 To 6) + For i = 0 To 6 + canvas(i) = " " + Mid(canvas(i), 3, 1) = "|" + Next + + Dim As Integer position = 1 + Dim As Integer tmp = n + + While tmp > 0 And position <= 4 + DrawDigit(canvas(), tmp Mod 10, position) + position += 1 + tmp \= 10 + Wend + + For i = 0 To 6 + recanvas(i+1) = canvas(i) + Next + + For i = 0 To 7 + Print recanvas(i) + Next +End Sub + +' Show example numbers +Dim As Integer nums(0 To 17) = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 300, 4000, 5555, 6789, 9394, 7922, 9999} + +For i = 0 To Ubound(nums) + ShowCistercianNumber(nums(i)) + Print +Next + +Sleep diff --git a/Task/Classes/Ballerina/classes.ballerina b/Task/Classes/Ballerina/classes.ballerina new file mode 100644 index 0000000000..5f7f119223 --- /dev/null +++ b/Task/Classes/Ballerina/classes.ballerina @@ -0,0 +1,28 @@ +import ballerina/io; + +class Dog { + string name; // field + + // Initializes a Dog instance passing it a name + // which is stored in the 'name' field. + function init(string name) { + self.name = name; + } + + // Function to make a noise. + function makeNoise() { + io:println("Woof!"); + } +} + +public function main() { + // Create a new Dog instance and assign a reference to it + // to the variable b. + Dog d = new Dog("Rover"); + + // Print the dog's name. + io:println("The dog is called ", d.name); + + // Make a noise. + d.makeNoise(); +} diff --git a/Task/Classes/Scheme/classes.scm b/Task/Classes/Scheme/classes.scm index ece399d954..dc5763eeef 100644 --- a/Task/Classes/Scheme/classes.scm +++ b/Task/Classes/Scheme/classes.scm @@ -1,3 +1,4 @@ +(define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) @@ -12,3 +13,13 @@ (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch) + +(define acc (make-account 100)) +((acc 'withdraw) 50) +50 +((acc 'withdraw) 60) +"Insufficient funds" +((acc 'deposit) 40) +90 +((acc 'withdraw) 60) +30 diff --git a/Task/Closest-pair-problem/EasyLang/closest-pair-problem.easy b/Task/Closest-pair-problem/EasyLang/closest-pair-problem.easy index d9ded104e7..013b09d2f5 100644 --- a/Task/Closest-pair-problem/EasyLang/closest-pair-problem.easy +++ b/Task/Closest-pair-problem/EasyLang/closest-pair-problem.easy @@ -1,5 +1,5 @@ # bruteforce -numfmt 4 0 +numfmt 0 4 x[] = [ 0.654682 0.409382 0.891663 0.716629 0.477721 0.925092 0.624291 0.211332 0.293786 0.839186 ] y[] = [ 0.925557 0.619391 0.888594 0.996200 0.946355 0.818220 0.142924 0.221507 0.691701 0.728260 ] n = len x[] diff --git a/Task/Closures-Value-capture/Crystal/closures-value-capture.cr b/Task/Closures-Value-capture/Crystal/closures-value-capture.cr new file mode 100644 index 0000000000..408a62a902 --- /dev/null +++ b/Task/Closures-Value-capture/Crystal/closures-value-capture.cr @@ -0,0 +1,6 @@ +closures = Array(-> Int32).new +(1..10).each do |i| + closures << ->{ i * i } +end + +puts closures[..-2].map(&.call).join(" ") diff --git a/Task/Color-of-a-screen-pixel/UNIX-Shell/color-of-a-screen-pixel.sh b/Task/Color-of-a-screen-pixel/UNIX-Shell/color-of-a-screen-pixel.sh new file mode 100644 index 0000000000..6fff9f2032 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/UNIX-Shell/color-of-a-screen-pixel.sh @@ -0,0 +1 @@ +spectacle -nbo /dev/stdout 2>/dev/null | magick - txt:- | grep "^0,0" | awk '{ print $2 }' diff --git a/Task/Color-quantization/UNIX-Shell/color-quantization.sh b/Task/Color-quantization/UNIX-Shell/color-quantization.sh new file mode 100644 index 0000000000..0e9f4b1ef5 --- /dev/null +++ b/Task/Color-quantization/UNIX-Shell/color-quantization.sh @@ -0,0 +1 @@ +magick input.png -colors 16 out.png diff --git a/Task/Color-wheel/C/color-wheel.c b/Task/Color-wheel/C/color-wheel.c new file mode 100644 index 0000000000..8dee2a5a3a --- /dev/null +++ b/Task/Color-wheel/C/color-wheel.c @@ -0,0 +1,99 @@ +#include +#include +#include +#include + +#define PI 3.14159265358979323846f + +typedef struct Vector2 { + float x, y; +} Vector2; + +// https://github.com/raysan5/raylib/blob/5aa3f0ccc374c1fbfc880402b37871b9c3bb7d8e/src/raymath.h#L316 +float vecdist(Vector2 v1, Vector2 v2) { return sqrtf((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y)); } + +// Packed because othervise compiler padd it with a zero. +// This breaks ppm format as it expects 3 bytes per pixel. +// Alternatively, if your compiler doesn't support __attribute__ you can remove it but +// then you will have to write every byte separately +typedef struct __attribute__((__packed__)) Color { + unsigned char r, g, b; +} Color; + +// Copied from +// https://github.com/raysan5/raylib/blob/5aa3f0ccc374c1fbfc880402b37871b9c3bb7d8e/src/rtextures.c#L4936 +// Hue is provided in degrees: [0..360] +// Saturation/Value are provided normalized: [0.0f..1.0f] +Color from_hsv(float hue, float saturation, float value) { + Color color = {0, 0, 0}; + + // Red channel + float k = fmodf((5.0f + hue / 60.0f), 6); + float t = 4.0f - k; + k = (t < k) ? t : k; + k = (k < 1) ? k : 1; + k = (k > 0) ? k : 0; + color.r = (unsigned char)((value - value * saturation * k) * 255.0f); + + // Green channel + k = fmodf((3.0f + hue / 60.0f), 6); + t = 4.0f - k; + k = (t < k) ? t : k; + k = (k < 1) ? k : 1; + k = (k > 0) ? k : 0; + color.g = (unsigned char)((value - value * saturation * k) * 255.0f); + + // Blue channel + k = fmodf((1.0f + hue / 60.0f), 6); + t = 4.0f - k; + k = (t < k) ? t : k; + k = (k < 1) ? k : 1; + k = (k > 0) ? k : 0; + color.b = (unsigned char)((value - value * saturation * k) * 255.0f); + + return color; +} + +int main(void) { + size_t img_size = 1000; + FILE *f = fopen("HSVWheel.ppm", "wb"); + if (!f) exit(69); + + // ppm header: + // "P6" - magic number that identifies format as binary with color, line break, space separated tuple with width and height of + // image in ASCII, line break, max value per color channel in ASCII, line break. + fprintf(f, "P6\n%lld %lld\n255\n", img_size, img_size); + + const size_t radius = img_size / 2; + const Vector2 center = {radius, radius}; + + // iterate over every pixel of image + for (size_t y = 0; y < img_size; ++y) { + for (size_t x = 0; x < img_size; ++x) { + // if distance from pixel to center of image - we inside of the colorwheel + float dist = vecdist(center, (Vector2){x, y}); + if (dist <= radius) { + // angle between x-axis and line from center to pixel in radians + // add PI/2 to rotate the hue by 90 degrees and have red on top + float angle = atan2f(y - center.y, x - center.x) + (PI / 2); + // normalize angle to be in range [0..2π] + if (angle < 0) angle += 2 * PI; + // convert from radian to degree + float hue = angle * (180 / PI); + // normalize distance to [0..1] range and use as saturation + float sat = dist / radius; + Color color = from_hsv(hue, sat, 1); + fwrite(&color, sizeof(Color), 1, f); + } else { + // Fill rest with background color + Color color = {0x1e, 0x1e, 0x1e}; + fwrite(&color, sizeof(Color), 1, f); + } + } + } + + // cleanup + fflush(f); + fclose(f); + return 0; +} diff --git a/Task/Color-wheel/EasyLang/color-wheel.easy b/Task/Color-wheel/EasyLang/color-wheel.easy index e540c2388c..f1ee8bbaa1 100644 --- a/Task/Color-wheel/EasyLang/color-wheel.easy +++ b/Task/Color-wheel/EasyLang/color-wheel.easy @@ -1,4 +1,4 @@ -proc hsb2rgb hue sat bri . r g b . +proc hsb2rgb hue sat bri &r &g &b . h = (hue - floor hue) * 6 f = h - floor h p = bri * (1 - sat) @@ -19,7 +19,7 @@ proc hsb2rgb hue sat bri . r g b . r = bri ; g = p ; b = q . . -proc cwheel . . +proc cwheel . for y = 0 to 499 dy = y - 250 for x = 0 to 499 @@ -29,9 +29,8 @@ proc cwheel . . theta = atan2 dy dx hue = (theta + 180) / 360 hsb2rgb hue (dist / 250) 1 r g b - color3 r g b - move x / 5 y / 5 - rect 0.3 0.3 + gcolor3 r g b + grect x / 5 y / 5 0.3 0.3 . . . diff --git a/Task/Color-wheel/Emacs-Lisp/color-wheel.l b/Task/Color-wheel/Emacs-Lisp/color-wheel.l new file mode 100644 index 0000000000..47aa9860bf --- /dev/null +++ b/Task/Color-wheel/Emacs-Lisp/color-wheel.l @@ -0,0 +1,75 @@ +(defun make-colors () + "Make a list of colors in RGB format." + (let ((red #xff) + (green #x0) + (blue #x0) + (colors)) + (while (<= green #xff) + (push (format "#%02x%02x%02x" red green blue) colors) + (setq green (+ green #x11))) + (setq green #xff) + (while (>= red #x0) + (push (format "#%02x%02x%02x" red green blue) colors) + (setq red (- red #x11))) + (setq red #x0) + (while (<= blue #xff) + (push (format "#%02x%02x%02x" red green blue) colors) + (setq blue (+ blue #x11))) + (setq blue #xff) + (while (>= green #x0) + (push (format "#%02x%02x%02x" red green blue) colors) + (setq green (- green #x11))) + (setq green #x0) + (while (<= red #xff) + (push (format "#%02x%02x%02x" red green blue) colors) + (setq red (+ red #x11))) + (reverse colors))) + +(defun sample-colors (sample-size colors) + "Get SAMPLE-SIZE number from COLORS" + (let* ((total-colors (length colors)) + (interval (/ (float (- total-colors 1)) (float (- sample-size 1)))) + (color-position-in-list 0) + (samples)) + (while (< color-position-in-list total-colors) + (push (nth (round color-position-in-list) colors) samples) + (setq color-position-in-list (+ interval color-position-in-list))) + samples)) + +(defun correct-y (reversed-y) + "Correct REVERSED-Y to work with Cartesian coordinates. +This function assumes that the y-axis size of the svg-create command +is 400. If it has another value, then the 400 below would need to be +changed. This function is necessary because svg has y axis values +increasing in a downward direction, the opposite of Cartesian +coordinates." + (- 400 reversed-y)) + +(defun plot-triangle (svg h k r angle1 angle2 fill-color) + "Create svg code for triangle inscribed in circle. +Circle center and one point of the triangle is located at point H and +K. Other two points of the triangle are on the circle +circumference. Radius of circle is R. ANGLE is angle in radians of point +on circle relative to the circle center." + (let ((x1) + (y1) + (x2) + (y2)) + (setq x1 (+ (* r (cos angle1)) h)) + (setq y1 (+ (* r (sin angle1)) k)) + (setq y1 (correct-y y1)) + (setq x2 (+ (* r (cos angle2)) h)) + (setq y2 (+ (* r (sin angle2)) k)) + (setq y2 (correct-y y2)) + (svg-polygon svg (list (cons x1 y1) (cons x2 y2) (cons h k)) :fill-color fill-color))) + +(defun color-wheel (number-of-colors) + "Create a color-wheel with NUMBER-OF-COLORS." + (let ((angle 0) + (portion-of-circle (/ (* 2 float-pi) number-of-colors)) + (colors (sample-colors number-of-colors (make-colors))) + (svg (svg-create 400 400 :stroke-width 0 :stroke-color "red"))) + (dolist (color colors) + (plot-triangle svg 200 200 200 angle (+ angle portion-of-circle) color) + (setq angle (+ angle portion-of-circle))) + (insert-image (svg-image svg)))) diff --git a/Task/Colorful-numbers/EasyLang/colorful-numbers.easy b/Task/Colorful-numbers/EasyLang/colorful-numbers.easy index 955b9009e6..a8af5cd6e4 100644 --- a/Task/Colorful-numbers/EasyLang/colorful-numbers.easy +++ b/Task/Colorful-numbers/EasyLang/colorful-numbers.easy @@ -5,13 +5,9 @@ func colorful n . m = n while m > 0 d = m mod 10 - if n > 9 and d <= 1 - return 0 - . + if n > 9 and d <= 1 : return 0 digcnt[d] += 1 - if digcnt[d] > 1 - return 0 - . + if digcnt[d] > 1 : return 0 ndigs += 1 digits[ndigs] = d m = m div 10 @@ -22,9 +18,7 @@ func colorful n . for j = i to ndigs p *= digits[j] for k to prodcnt - if products[k] = p - return 0 - . + if products[k] = p : return 0 . prodcnt += 1 products[prodcnt] = p @@ -36,14 +30,12 @@ len cnt[] 8 len used[] 10 arrbase used[] 0 largest = 0 -proc cnt_colorful taken n digits . . +proc cnt_colorful taken n digits . if taken = 0 for d = 0 to 9 used[d] = 1 h = 1 - if d < 2 - h = 9 - . + if d < 2 : h = 9 cnt_colorful h d 1 used[d] = 0 . diff --git a/Task/Colorful-numbers/JavaScript/colorful-numbers.js b/Task/Colorful-numbers/JavaScript/colorful-numbers.js new file mode 100644 index 0000000000..cab316dd25 --- /dev/null +++ b/Task/Colorful-numbers/JavaScript/colorful-numbers.js @@ -0,0 +1,85 @@ +function chunk_array(arr, n) { + const chunks = []; + + for (let i = 0; i < arr.length; i++) { + const sliced = arr.slice(i, i + n); + if (sliced.length == n) { + chunks.push(sliced); + } + } + + return chunks; +} + +function isColorful(num) { + const numArr = num.toString().split('').map(item => parseInt(item)); + + if (numArr.length == 1) { + return true; + } + + const count = {}; + + for (const num of numArr) { + const c = (count[num] || 0) + 1; + + if (c == 2) { + return false; + } + + count[num] = c; + } + + const prods = []; + + for(let i = 2; i < numArr.length+1; i++) { + const chunked = chunk_array(numArr, i); + for (const chunk of chunked) { + const prod = chunk.reduce((prev, val) => prev * val, 1); + + if (numArr.includes(prod) || prods.includes(prod)) { + return false; + } + prods.push(prod); + } + } + + return true; +} + + +const colorful = []; + +for(let i = 0; i < 100; i++) { + if (isColorful(i)) { + colorful.push(i); + } +} + +console.log(`Amount of colorful numbers lesser than 100 is ${colorful.length}`); +console.log(colorful); + +let isStart = true; +let maxColorful = 0; +let totalCount = 0; + +for (let i = 10; i < 1000000000; i *= 10) { + const colorful = []; + + for(let j = isStart ? 0 : (i / 10); j < i; j++) { + if (isColorful(j)) { + colorful.push(j); + maxColorful = Math.max(maxColorful, j); + } + } + + totalCount += colorful.length; + console.log(`The count of colorful numbers between ${isStart ? 0 : (i / 10)} and ${i-1} is ${colorful.length}`); + + if (isStart) { + isStart = false; + } +} + +console.log(`The largest possible colorful number is ${maxColorful}.`); +console.log(`The total number of colorful numbers is ${totalCount}.`); diff --git a/Task/Colour-bars-Display/EasyLang/colour-bars-display.easy b/Task/Colour-bars-Display/EasyLang/colour-bars-display.easy index 96cf380e59..dc02f8c6f6 100644 --- a/Task/Colour-bars-Display/EasyLang/colour-bars-display.easy +++ b/Task/Colour-bars-Display/EasyLang/colour-bars-display.easy @@ -1,7 +1,6 @@ col[] = [ 000 900 090 009 909 099 990 999 ] w = 100 / len col[] for i = 1 to len col[] - color col[i] - move w * (i - 1) 0 - rect w 100 + gcolor col[i] + grect w * (i - 1) 0 w 100 . diff --git a/Task/Colour-bars-Display/Python/colour-bars-display.py b/Task/Colour-bars-Display/Python/colour-bars-display-1.py similarity index 100% rename from Task/Colour-bars-Display/Python/colour-bars-display.py rename to Task/Colour-bars-Display/Python/colour-bars-display-1.py diff --git a/Task/Colour-bars-Display/Python/colour-bars-display-2.py b/Task/Colour-bars-Display/Python/colour-bars-display-2.py new file mode 100644 index 0000000000..2603946990 --- /dev/null +++ b/Task/Colour-bars-Display/Python/colour-bars-display-2.py @@ -0,0 +1,40 @@ +import pygame +import sys + +GLOBAL_WINDOW_SIZE = (640, 480) +COLOURS = ( + (0, 0, 0), + (255, 0, 0), + (0, 255, 0), + (0, 0, 255), + (255, 0, 255), + (0, 255, 255), + (255, 255, 0), + (255, 255, 255) +) + +def drawColouredStripes(surface): + stripeWidth = surface.get_width() // 8 + for i, col in enumerate(COLOURS): + pygame.draw.rect(surface, col, pygame.Rect(i*stripeWidth, 0, stripeWidth, surface.get_height())) + +pygame.init() + +if len(sys.argv) == 3: + newWindowSize = (int(sys.argv[1]), int(sys.argv[2])) + screen = pygame.display.set_mode(newWindowSize) +else: + screen = pygame.display.set_mode(GLOBAL_WINDOW_SIZE) + +running = True + +while running: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + + drawColouredStripes(screen) + + pygame.display.flip() + +pygame.quit() diff --git a/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl b/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl index ae82d8a7db..18f094b457 100644 --- a/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl +++ b/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl @@ -1,29 +1,19 @@ -( uxnasm color-bars.tal color-bars.rom && uxnemu color-bars.rom ) +|00 @System [ &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 + &b $2 &debug $1 &state $1 ] -|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 -|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 +|20 @Screen [ &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 + &addr $2 &pixel $1 &sprite $1 ] -|0100 - ( set 4 color theme - rgb - color0: 000 - black - color1: f00 - red - color2: 0f0 - green - color3: 00f - blue ) +|100 @Screen/on-reset ( -> ) #0f00 .System/r DEO2 #00f0 .System/g DEO2 #000f .System/b DEO2 - ( store bars width ) - .Screen/width DEI2 #0004 DIV2 ,&quarter STR2 - ( set starting position ) - #0000 .Screen/y DEO2 - ( draw bars ) - #00 + #8480 &loop - #00 OVR [ LIT2 &quarter $2 ] MUL2 - .Screen/x DEO2 - DUP #80 ORA .Screen/pixel DEO - INC DUP #04 NEQ ?&loop -BRK + DUP ./pixel DEO + ./x DEI2k ./width DEI2 #02 SFT2 ADD2 ROT DEO2 + INC GTHk ?/loop + + BRK diff --git a/Task/Colour-pinstripe-Display/EasyLang/colour-pinstripe-display.easy b/Task/Colour-pinstripe-Display/EasyLang/colour-pinstripe-display.easy index ed11ac98e6..562377a32c 100644 --- a/Task/Colour-pinstripe-Display/EasyLang/colour-pinstripe-display.easy +++ b/Task/Colour-pinstripe-Display/EasyLang/colour-pinstripe-display.easy @@ -3,9 +3,8 @@ for i = 1 to 4 col = 1 y = 100 - i * 25 for x = 0 step i to 100 - i - color k[col] - move x y - rect i 25 + gcolor k[col] + grect x y i 25 col = (col + 1) mod1 8 . . diff --git a/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl b/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl index 8f499e336d..6ec0726773 100644 --- a/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl +++ b/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl @@ -1,38 +1,42 @@ -( uxnasm color-pinstripe.tal color-pinstripe.rom && uxnemu color-pinstripe.rom ) +|00 @System [ &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 + &b $2 &debug $1 &state $1 ] -|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 -|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 +|20 @Screen [ &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 + &addr $2 &pixel $1 &sprite $1 ] -|0100 - ( set theme ) - #0f00 .System/r DEO2 - #00f0 .System/g DEO2 - #000f .System/b DEO2 +|100 - ( store screen width ) - .Screen/width DEI2 ,draw-layer/width STR2 - ( store a quarter of the screen height ) - .Screen/height DEI2 #02 SFT2 ,&quarter-height STR2 +( set theme ) +#0f00 .System/r DEO2 +#00f0 .System/g DEO2 +#000f .System/b DEO2 - ( draw the four stripe layers ) - #00 - &loop ( -- ) - ( update y coordinate ) - #00 OVR [ LIT2 &quarter-height $2 ] MUL2 .Screen/y DEO2 - ( draw a layer ) - INCk draw-layer - ( do it four times ) - INC DUP #04 LTH ?&loop - POP BRK +( store screen width ) +.Screen/width DEI2 ,draw-layer/width STR2 +( store a quarter of the screen height ) +.Screen/height DEI2 #02 SFT2 ,/quarter-height STR2 + +( draw the four stripe layers ) +#00 +&loop + ( update y coordinate ) + #00 OVR [ LIT2 &quarter-height $2 ] MUL2 .Screen/y DEO2 + ( draw a layer ) + INCk draw-layer + ( do it four times ) + INC DUP #04 LTH ?/loop + POP + +BRK @draw-layer ( step -: ) ( extend step to short, create counter ) #00 SWP #0000 - &loop ( -- ) + &loop ( update x coordinate ) MUL2k .Screen/x DEO2 ( fill a region ) DUP #03 AND #80 ORA .Screen/pixel DEO ( loop until the end of the screen ) - INC2 MUL2k [ LIT2 &width $2 ] LTH2 ?&loop + INC2 MUL2k [ LIT2 &width $2 ] LTH2 ?/loop POP2 POP2 JMP2r diff --git a/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy b/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy index 0e2be62a85..12a4b06003 100644 --- a/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy +++ b/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy @@ -4,7 +4,7 @@ k = 2 len result[] k n_results = 0 # -proc output . . +proc output . n_results += 1 if len items$[] > 0 s$ = "" @@ -14,7 +14,7 @@ proc output . . print s$ . . -proc combine pos val . . +proc combine pos val . if pos > k output else diff --git a/Task/Combinations/EasyLang/combinations.easy b/Task/Combinations/EasyLang/combinations.easy index 3ac717f830..34c4b35b4d 100644 --- a/Task/Combinations/EasyLang/combinations.easy +++ b/Task/Combinations/EasyLang/combinations.easy @@ -2,7 +2,7 @@ n = 5 m = 3 len result[] m # -proc combinations pos val . . +proc combinations pos val . if pos > m print result[] return diff --git a/Task/Comma-quibbling/Crystal/comma-quibbling.cr b/Task/Comma-quibbling/Crystal/comma-quibbling.cr new file mode 100644 index 0000000000..c9464e6016 --- /dev/null +++ b/Task/Comma-quibbling/Crystal/comma-quibbling.cr @@ -0,0 +1,19 @@ +def comma_quibble (arr) + "{" + + case arr.size + when 0 + "" + when 1 + arr[0] + else + arr[..-2].join(", ") + " and #{arr[-1]}" + end + "}" +end + +[[] of String, # (No input words). + ["ABC"], + ["ABC", "DEF"], + ["ABC", "DEF", "G", "H"], +].each do |input| + puts comma_quibble(input) +end diff --git a/Task/Comma-quibbling/Elena/comma-quibbling-1.elena b/Task/Comma-quibbling/Elena/comma-quibbling-1.elena new file mode 100644 index 0000000000..3b7623d585 --- /dev/null +++ b/Task/Comma-quibbling/Elena/comma-quibbling-1.elena @@ -0,0 +1,23 @@ +import system'routines; +import extensions; +import extensions'text; + +public extension QuibbleOp : Array +{ + string quibble() + { + ^ self.zipBy( + self.Length.coundDown().selectBy::(n => n == self.Length ? EmptyString : (n == 1 ? " and " : ", ") ), + (word, prefix => prefix + word) + ) + .summarize(StringWriter.load("{")) + "}" + } +} + +public program() +{ + Console.printLine(new string[] { }.quibble()); + Console.printLine(new string[] { "ABC" }.quibble()); + Console.printLine(new string[] { "ABC", "ADF" }.quibble()); + Console.printLine(new string[] { "ABC", "DEF", "G", "H" }.quibble()) +} diff --git a/Task/Comma-quibbling/Elena/comma-quibbling-2.elena b/Task/Comma-quibbling/Elena/comma-quibbling-2.elena new file mode 100644 index 0000000000..af737461ae --- /dev/null +++ b/Task/Comma-quibbling/Elena/comma-quibbling-2.elena @@ -0,0 +1,31 @@ +import extensions; +import textgen; + +const string Script = "<={{=>for (var i := 0; i < self.Length; i := i + 1) { + if (i > 0) { + if (i == self.Length - 1) { + <= and => + } + else { + <=, => + } + }; + + <={self[i]}=> + }; <=}}=>"; + +public extension QuibbleOp : Array +{ + string quibble() + { + ^ self.generateFrom(Script); + } +} + +public program() +{ + Console.printLine(new string[] { }.quibble()); + Console.printLine(new string[] { "ABC" }.quibble()); + Console.printLine(new string[] { "ABC", "ADF" }.quibble()); + Console.printLine(new string[] { "ABC", "DEF", "G", "H" }.quibble()) +} diff --git a/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments.aarch64 b/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-1.aarch64 similarity index 100% rename from Task/Command-line-arguments/AArch64-Assembly/command-line-arguments.aarch64 rename to Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-1.aarch64 diff --git a/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 b/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 new file mode 100644 index 0000000000..134551fb07 --- /dev/null +++ b/Task/Command-line-arguments/AArch64-Assembly/command-line-arguments-2.aarch64 @@ -0,0 +1,26 @@ +.global _start +.text +_start: + mov x9, sp // move stack pointer to x9 + 0: ldr x0, [x9, #8]! // add 8 to x9, load long int value at x9 into x0 + cbz x0, 9f // if x0 is zero (null pointer) jump forward to 9: + bl writez // call our function that prints a null terminated string + adr x0, lfz // load address of lfz (line feed, zero) into x0 + bl writez // print it + b 0b // jump backward to label 0: + 9: mov x8, #93 // 93 is exit + mov x0, xzr // return (0); + svc #0 // syscall + // If using as a function in C declare it as +writez: // extern long writez(char *str); + mov x1, x0 // address of str needs to be in x1 for syscall + sub x0, x0, #1 // decrement x0, because the next statement increments it first. + 0: ldrb w2, [x0, #1]! // increment x0, load byte value at x0 in w2 + cbnz w2, 0b // if w2 is not zero jump back to 0: label + sub x2, x0, x1 // subtract x1 from x0, load into x2. length of str + mov x0, #1 // mov into x0 1. stdout + mov x8, #64 // mov into x8 64. write + svc #0 // syscall + ret // return from function. + // return value is number of characters written. +lfz: .byte 10, 0 // line feed (0x0a), zero (null character) diff --git a/Task/Commatizing-numbers/JavaScript/commatizing-numbers.js b/Task/Commatizing-numbers/JavaScript/commatizing-numbers.js new file mode 100644 index 0000000000..ab6c8185ab --- /dev/null +++ b/Task/Commatizing-numbers/JavaScript/commatizing-numbers.js @@ -0,0 +1,42 @@ +function contains(haystack, needle) { + return haystack.indexOf(needle) !== -1; +} + +function commatize(text, start_index = 0, step = 3, separator = ",") { + console.log("Before: " + text); + const size = text.length; + + for (let i = start_index; i < size; ++i) { + if (contains("123456789", text[i])) { + for (let j = i + 1; j <= size; ++j) { + if (j > size || !contains("0123456789", text[j])) { + for (let k = j - 1 - step; k >= i; k -= step) { + text = text.slice(0, k + 1) + separator + text.slice(k + 1); + } + break; + } + } + break; + } + } + + console.log(" After: " + text + "\n"); +} + +function main() { + commatize("pi=3.14159265358979323846264338327950288419716939937510582097494459231", 6, 5, " "); + commatize("The author has two Z$100000000000000 Zimbabwe notes (100 trillion)."); + commatize("\"-in Aus$+1411.8millions\""); + commatize("===US$0017440 millions=== (in 2000 dollars)"); + commatize("123.e8000 is pretty big."); + commatize("The land area of the earth is 57268900(29% of the surface) square miles."); + commatize("Ain't no numbers in this here words, nohow, no way, Jose."); + commatize("James was never known as 0000000007"); + commatize("Arthur Eddington wrote: I believe there are " + + "15747724136275002577605653961181555468044717914527116709366231425076185631031296" + + " protons in the universe."); + commatize(" $-140000±100 millions."); + commatize("6/9/1946 was a good year for some."); +} + +main(); diff --git a/Task/Comments/OPL/comments.opl b/Task/Comments/OPL/comments.opl new file mode 100644 index 0000000000..901aa3e30b --- /dev/null +++ b/Task/Comments/OPL/comments.opl @@ -0,0 +1,2 @@ +REM This is a comment. +PAUSE 20 REM Can be placed behind statements, too. diff --git a/Task/Comments/Uxntal/comments.uxnatl b/Task/Comments/Uxntal/comments.uxnatl new file mode 100644 index 0000000000..74169c1755 --- /dev/null +++ b/Task/Comments/Uxntal/comments.uxnatl @@ -0,0 +1,31 @@ +( + Print a hex byte to decimal. +) + +( macros ) +%\n { 0a } +%newline { [ LIT2 \n -Console/write ] DEO } + +( devices ) +|10 @Console/vector $2 &read $1 ( &pad is unused ) &pad $5 &write $1 &error $1 + +( main program ) +|100 + +@on-reset ( -> ) + #42 print/dec newline + BRK + +( library ) +@print/dec ( dec -- ) + DUP #64 DIV /dec/try + DUP #0a DIV /dec/try + ( >> ) + + &dec/num ( num -- ) + #0a DIVk MUL SUB [ LIT "0 ] ADD .Console/write DEO + JMP2r + + &dec/try ( num -- ) + DUP ?/dec/num + POP JMP2r diff --git a/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy b/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy index 86039c73d8..a451eb048b 100644 --- a/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy +++ b/Task/Compare-a-list-of-strings/EasyLang/compare-a-list-of-strings.easy @@ -1,22 +1,14 @@ -proc test s$[] . . +proc test s$[] . ident = 1 ascend = 1 for i = 2 to len s$[] h = strcmp s$[i] s$[i - 1] - if h <> 0 - ident = 0 - . - if h <= 0 - ascend = 0 - . + if h <> 0 : ident = 0 + if h <= 0 : ascend = 0 . print s$[] - if ident = 1 - print "all equal" - . - if ascend = 1 - print "ascending" - . + if ident = 1 : print "all equal" + if ascend = 1 : print "ascending" print "" . test [ "AA" "BB" "CC" ] diff --git a/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 b/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 index 14627c3e47..b02abbc166 100644 --- a/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 +++ b/Task/Compare-a-list-of-strings/M2000-Interpreter/compare-a-list-of-strings.m2000 @@ -37,3 +37,38 @@ Module CheckIt { Print LessThan(A$())=False } Checkit +MODULE UsingLambdaFunctionAndFold { + equ=LAMBDA ->{ + =LAMBDA p$, c=0 -> { + IF c=0 THEN + p$=LETTER$: PUSH 1=1 : c++ + ELSE + READ q$ + IF STACKITEM() THEN + DROP + PUSH p$=q$ + p$=q$ + END IF + END IF + } + } + LessThan=LAMBDA ->{ + =LAMBDA p$, c=0 -> { + IF c=0 THEN + p$=LETTER$: PUSH 1=1 : c++ + ELSE + READ q$ + IF STACKITEM() THEN + DROP + PUSH p$(#y)} +a:"aaa" +b:"ab" +comp[a;b] +length:{ (" the string " ,x, " has size ", ($#x), " the string " ,y, " has size " , ($#y))} +// if prints a first if a is longer +{$[comp[x;y];length[a;b];length[b;a]]}[a;b] +// extra credit +// just take each length and sort an array as usual +c:("abcd"; "123456789"; "abcdef"; "1234567") +c[<#'c] diff --git a/Task/Compare-length-of-two-strings/M2000-Interpreter/compare-length-of-two-strings-1.m2000 b/Task/Compare-length-of-two-strings/M2000-Interpreter/compare-length-of-two-strings-1.m2000 new file mode 100644 index 0000000000..263ccadf2a --- /dev/null +++ b/Task/Compare-length-of-two-strings/M2000-Interpreter/compare-length-of-two-strings-1.m2000 @@ -0,0 +1,47 @@ +MODULE COMPARE_STRING_LENGTH { + A = "I am string" + B = {I am string too} + PRINT A WORKS FOR EXPRESSIONS (-1,0,1) + PRINT A <=> B = -1 ' A { + PUSH STRING$("*",LEN(a$))+CHR$(9)+a$ +} +map2=lambda-> { + PUSH RIGHTPART$(LETTER$, CHR$(9)) +} +CLIPBOARD a#MAP(map1)#SORT(-1)#MAP(map2)#STR$() +PRINT CLIPBOARD$ +' like Python's advance solution +b=a#MAP(map1)#SORT(-1)#MAP(map2) +c=LEN(b)-1 +d=EACH(b) +WHILE d + PRINT QUOTE$(ARRAY$(d));" has length ";LEN(ARRAY$(d)); + IF d^=0 THEN + PRINT " and is the longest string" + ELSE.IF d^STRING$("S", STACK.SIZE) THEN ERROR "NO LIST OF STRINGS" + LOCAL a(1 TO STACK.SIZE, 2) + LOCAL c=1, i + WHILE NOT EMPTY + OVER ' double the top of stack of items + a(c, 0):=LEN(LETTER$), LETTER$ ' pass a row of values + c++ + END WHILE + c-- + LOCAL column=0, descending_type=1 + SORT a(), 1, c, column, descending_type + FOR i=1 to c + PRINT QUOTE$(a(i, 1));" has length ";a(i,0); + IF i=1 THEN + PRINT " and is the longest string" + ELSE.IF i=c THEN + PRINT " and is neither the longest nor the shortest string" + ELSE + PRINT " and is the shortest string" + END IF + NEXT + END SUB +} +Using2dArrayForSortStringsByLength diff --git a/Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-1.opl b/Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-1.opl new file mode 100644 index 0000000000..9a8062d239 --- /dev/null +++ b/Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-1.opl @@ -0,0 +1,15 @@ +PROC main: + LOCAL string1$(7),string2$(4),length1%,length2% + string1$="Rosetta" + string2$="Code" + length1%=LEN(string1$) + length2%=LEN(string2$) + IF length1%>length2% + PRINT string1$,"(";length1%;")" + PRINT string2$,"(";length2%;")" + ELSE + PRINT string2$,"(";length2%;")" + PRINT string1$,"(";length1%;")" + ENDIF + GET +ENDP diff --git a/Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-2.opl b/Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-2.opl new file mode 100644 index 0000000000..c6d0e19da8 --- /dev/null +++ b/Task/Compare-length-of-two-strings/OPL/compare-length-of-two-strings-2.opl @@ -0,0 +1,47 @@ +PROC main: + LOCAL move%,id%,input$(20),store$(23),list$(5,23) + id%=1 + PRINT "Please enter five strings." + WHILE id%<6 + PRINT "String",id%;":", + INPUT input$ + IF LEN(GEN$(LEN(input$),2))=1 + list$(id%)="0"+GEN$(LEN(list$(id%)),1)+" "+list$(id%) + ELSE + list$(id%)=GEN$(LEN(list$(id%)),2)+" "+list$(id%) + ENDIF + id%=id%+1 + ENDWH + PRINT + id%=1 + move%=1 + DO + move%=0 + WHILE id%<6 + IF id%<>1 + IF list$(id%-1)5 + IF list$(id%+1)>list$(id%) + store$=list$(id%+1) + list$(id%+1)=list$(id%) + list$(id%)=store$ + move%=1 + ENDIF + ENDIF + id%=id%+1 + ENDWH + id%=1 + UNTIL move%=0 + id%=1 + WHILE id%<6 + PRINT list$(id%) + id%=id%+1 + ENDWH + GET +ENDP diff --git a/Task/Compare-length-of-two-strings/Scheme/compare-length-of-two-strings.scm b/Task/Compare-length-of-two-strings/Scheme/compare-length-of-two-strings.scm new file mode 100644 index 0000000000..0f28cd8822 --- /dev/null +++ b/Task/Compare-length-of-two-strings/Scheme/compare-length-of-two-strings.scm @@ -0,0 +1,47 @@ +; sorting for chicken +(import (chicken sort)) +; may need it in your scheme, when not included +(import srfi-1) +(define a "i am string") +(define b "i am string too") + +(string(arr: &mut [T]) { + let mut n = arr.len(); + let mut swapped = true; + + while swapped { + swapped = false; + + for i in 1..n { + if arr[i - 1] > arr[i] { + arr.swap(i - 1, i); + swapped = true; + } + } + + n -= 1; + } +} + +fn insertion_sort(arr: &mut [T]) { + for i in 1..arr.len() { + let mut j = i; + while j > 0 && arr[j] < arr[j - 1] { + arr.swap(j, j - 1); + j -= 1; + } + } +} + +fn quick_sort(arr: &mut [T]) { + if arr.len() >= 2 { + let pivot = partition(arr); + quick_sort(&mut arr[..pivot]); + quick_sort(&mut arr[pivot..]); + } +} + +/// In order to sort 100,000 integers without overflowing the stack, we use Hoare's partition scheme +/// which moves iterators from both ends of the slice towards the center until they cross. +/// This is especially effective for slicing sequences that are nearly/fully sorted. +fn partition(arr: &mut [T]) -> usize { + let pivot = arr[arr.len() / 2]; + + let mut i = 0; + let mut j = arr.len() - 1; + + loop { + while arr[i] < pivot { + i += 1; + } + while arr[j] > pivot { + j -= 1; + } + + if i >= j { + return i; + } + + arr.swap(i, j); + i += 1; + j -= 1; + } +} + +/// We are hard-coding the type for this example, since radix sorting on signed integers is a _bit_ +/// more complicated than needed here. +fn radix_sort(arr: &mut [u32]) { + let mut buf = vec![0; arr.len()]; + // Reduce the amount of iterations by finding the max value bit + let max_bits = u32::BITS - arr.iter().max().unwrap().leading_zeros(); + + for bit in 0..max_bits { + // Manual implementation of partition with only one buffer array + let mut a = 0; + let mut b = 0; + + for i in 0..arr.len() { + if arr[i] >> bit & 1 == 0 { + arr[a] = arr[i]; + a += 1; + } else { + buf[b] = arr[i]; + b += 1; + } + } + + arr[a..].copy_from_slice(&buf[..b]); + } +} + +fn shell_sort(arr: &mut [T]) { + // Marcin Ciura's gap sequence + for gap in [701, 301, 132, 57, 23, 10, 4, 1] { + for i in gap..arr.len() { + let temp = arr[i]; + let mut j = i; + while j >= gap && arr[j - gap] > temp { + arr[j] = arr[j - gap]; + j -= gap; + } + arr[j] = temp; + } + } +} + +fn rust_stable_sort(arr: &mut [T]) { + arr.sort(); +} + +fn rust_unstable_sort(arr: &mut [T]) { + arr.sort_unstable(); +} + +const ALGOS: [(&'static str, fn(&mut [u32])); 7] = [ + ("Bubble", bubble_sort), + ("Insert", insertion_sort), + ("Quick", quick_sort), + ("Radix", radix_sort), + ("Shell", shell_sort), + ("Drift", rust_stable_sort), + ("IPN", rust_unstable_sort), +]; diff --git a/Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-2.rs b/Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-2.rs new file mode 100644 index 0000000000..f09167cbea --- /dev/null +++ b/Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-2.rs @@ -0,0 +1,16 @@ +fn ones(len: u32) -> Vec { + vec![1; len as usize] +} + +fn sequence(len: u32) -> Vec { + (1..=len).collect() +} + +fn random(mut rng: &mut rand::rngs::ThreadRng, len: u32) -> Vec { + use rand::seq::SliceRandom; + + let mut seq = sequence(len); + seq.shuffle(&mut rng); + + seq +} diff --git a/Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-3.rs b/Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-3.rs new file mode 100644 index 0000000000..e2448e7713 --- /dev/null +++ b/Task/Compare-sorting-algorithms-performance/Rust/compare-sorting-algorithms-performance-3.rs @@ -0,0 +1,121 @@ +use core::error::Error; +use core::time::Duration; +use std::collections::BTreeMap; +use std::io::{Write, stdout}; +use std::time::Instant; + +fn run_time(f: fn(&mut [u32]), arr: &mut [u32]) -> Duration { + let start_time = Instant::now(); + f(arr); + start_time.elapsed() +} + +const LENGTHS: [u32; 30] = [ + 1, 2, 3, 4, 6, 10, 14, 21, 31, 46, 68, 100, 146, 215, 316, 464, 681, 1000, 1467, 2154, 3162, + 4641, 6812, 10000, 14677, 21544, 31622, 46415, 68129, 100000, +]; + +const IDC: [usize; 6] = [0, 5, 11, 17, 23, 29]; + +fn main() { + let mut rng = rand::rng(); + let mut metrics: [_; 3] = + core::array::from_fn(|_| BTreeMap::<&'static str, [Duration; 30]>::new()); + + for (i, len) in LENGTHS.iter().enumerate() { + print!("{len} "); + stdout().flush().unwrap(); + + let one = ones(*len); + let seq = sequence(*len); + let ran = random(&mut rng, *len); + + for (algo_name, algo) in ALGOS { + let (mut a, mut b, mut c) = (one.clone(), seq.clone(), ran.clone()); + + metrics[0].entry(algo_name).or_default()[i] = run_time(algo, &mut a); + metrics[1].entry(algo_name).or_default()[i] = run_time(algo, &mut b); + metrics[2].entry(algo_name).or_default()[i] = run_time(algo, &mut c); + + debug_assert!(a.is_sorted()); + debug_assert!(b.is_sorted()); + debug_assert!(c.is_sorted()); + } + } + println!("...Done"); + + println!( + "\n{:^20} {:>12?}", + "Data sizes", + [1, 10, 100, 1_000, 10_000, 100_000] + ); + println!("\n{:-^20}", "All Ones"); + for (algo_name, run_times) in &mut metrics[0] { + let powers_of_ten = run_times.get_disjoint_mut(IDC).unwrap(); + println!("{algo_name:^20} {powers_of_ten:>12?}"); + } + println!("\n{:-^20}", "Ascending"); + for (algo_name, run_times) in &mut metrics[1] { + let powers_of_ten = run_times.get_disjoint_mut(IDC).unwrap(); + println!("{algo_name:^20} {powers_of_ten:>12?}"); + } + println!("\n{:-^20}", "Random"); + for (algo_name, run_times) in &mut metrics[2] { + let powers_of_ten = run_times.get_disjoint_mut(IDC).unwrap(); + println!("{algo_name:^20} {powers_of_ten:>12?}"); + } + + let _ = plot("one", &metrics[0]); + let _ = plot("sequenced", &metrics[1]); + let _ = plot("random", &metrics[2]); +} + +fn plot(data_type: &str, map: &BTreeMap<&str, [Duration; 30]>) -> Result<(), Box> { + use plotters::prelude::*; + + let file_name = format!("{data_type}.png"); + let caption = format!("Sorting algorithms on {data_type} data"); + + let image = BitMapBackend::new(&file_name, (800, 600)).into_drawing_area(); + image.fill(&WHITE)?; + + let root = image.margin(10, 10, 10, 10); + let mut chart = ChartBuilder::on(&root) + .caption(caption, ("sans-serif", 24).into_font()) + .x_label_area_size(20) + .y_label_area_size(60) + .build_cartesian_2d((0..100_000).log_scale(), (0..10_000_000_000).log_scale())?; + + chart + .configure_mesh() + .x_desc("Data sizes") + .y_desc("Sort time") + .x_labels(10) + .y_labels(10) + .y_label_formatter(&|x| format!("{x:e} ns")) + .draw()?; + + for ((&algo_name, durations), color) in map + .iter() + .zip([MAGENTA, RED, GREEN, BLUE, YELLOW, CYAN, BLACK]) + { + let coordinates = durations + .iter() + .enumerate() + .map(|(i, duration)| (LENGTHS[i], duration.as_nanos() as i128)); + chart + .draw_series(LineSeries::new(coordinates, color))? + .label(algo_name) + .legend(move |(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], color)); + } + + chart + .configure_series_labels() + .background_style(WHITE.mix(0.8)) + .border_style(BLACK) + .draw()?; + + image.present()?; + + Ok(()) +} diff --git a/Task/Compiler-AST-interpreter/Rust/compiler-ast-interpreter.rs b/Task/Compiler-AST-interpreter/Rust/compiler-ast-interpreter.rs new file mode 100644 index 0000000000..f6d118b4c7 --- /dev/null +++ b/Task/Compiler-AST-interpreter/Rust/compiler-ast-interpreter.rs @@ -0,0 +1,400 @@ +use std::collections::HashMap; +use std::env; +use std::fs::File; +use std::io::{self, BufRead, BufReader, Lines}; +use std::process; + +// --- Data Structures --- + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum NodeType { + Ident, + String, + Integer, + Sequence, + If, + Prtc, + Prts, + Prti, + While, + Assign, + Negate, + Not, + Mul, + Div, + Mod, + Add, + Sub, + Lss, + Leq, + Gtr, + Geq, + Eql, + Neq, + And, + Or, +} + +#[derive(Debug, Clone)] +struct Tree { + node_type: NodeType, + // Use Option> for optional, heap-allocated children + left: Option>, + right: Option>, + // Store index for Ident/String or value for Integer + value: i32, +} + +// --- Global State Holder --- + +#[derive(Debug, Default)] +struct InterpreterContext { + string_pool: Vec, + global_names: Vec, + global_values: Vec, + // Cache for faster NodeType lookup + node_type_map: HashMap, +} + +impl InterpreterContext { + fn new() -> Self { + let mut map = HashMap::new(); + // Initialize the map from the static array + for &(text, node_type) in NODE_TYPE_MAPPING { + map.insert(text.to_string(), node_type); + } + InterpreterContext { + node_type_map: map, + ..Default::default() + } + } + + // Helper to get NodeType from string using the map + fn get_node_type(&self, name: &str) -> Option { + self.node_type_map.get(name).cloned() + } + + // Look up or add a string to the pool, return its index + fn fetch_string_offset(&mut self, st_literal: &str) -> Result { + if !st_literal.starts_with('"') || !st_literal.ends_with('"') { + return Err(format!("Invalid string literal format: {}", st_literal)); + } + // Trim quotes + let inner = &st_literal[1..st_literal.len() - 1]; + + // Basic escape sequence handling (\n, \\) + let mut processed = String::with_capacity(inner.len()); + let mut chars = inner.chars(); + while let Some(c) = chars.next() { + if c == '\\' { + match chars.next() { + Some('n') => processed.push('\n'), + Some('\\') => processed.push('\\'), + Some(other) => { + // Keep literal backslash and the following char if not recognized escape + processed.push('\\'); + processed.push(other); + } + None => return Err("String literal ends with dangling '\\'".to_string()), + } + } else { + processed.push(c); + } + } + + if let Some(pos) = self.string_pool.iter().position(|s| s == &processed) { + Ok(pos) + } else { + self.string_pool.push(processed); + Ok(self.string_pool.len() - 1) + } + } + + // Look up or add a variable name, return its index + fn fetch_var_offset(&mut self, name: &str) -> usize { + if let Some(pos) = self.global_names.iter().position(|n| n == name) { + pos + } else { + self.global_names.push(name.to_string()); + self.global_values.push(0); // Initialize new global variables to 0 + self.global_names.len() - 1 + } + } +} + +// --- Node Creation --- + +fn make_node(node_type: NodeType, left: Option>, right: Option>) -> Box { + Box::new(Tree { + node_type, + left, + right, + value: 0, // Default value, not used for non-leaf nodes + }) +} + +fn make_leaf(node_type: NodeType, value: i32) -> Box { + Box::new(Tree { + node_type, + left: None, + right: None, + value, + }) +} + +// --- Interpreter --- + +// Takes context mutably because assignment modifies global_values +fn interp(node: Option<&Box>, context: &mut InterpreterContext) -> i32 { + if node.is_none() { + return 0; // Interpret null node as 0 or do nothing + } + let node = node.unwrap(); // We know it's Some + + match node.node_type { + NodeType::Integer => node.value, + NodeType::Ident => { + // Access global_values using the index stored in node.value + // Provide a default value (e.g., 0) if index is somehow out of bounds, though fetch_var_offset should prevent this. + context.global_values.get(node.value as usize).cloned().unwrap_or_else(|| { + eprintln!("warning: Undefined variable accessed (index {})", node.value); + 0 + }) + } + NodeType::String => node.value, // Index into string_pool + + NodeType::Assign => { + // Left child must be an identifier leaf + let var_index = match node.left { + Some(ref left_node) if left_node.node_type == NodeType::Ident => left_node.value as usize, + _ => panic!("Assignment target must be an identifier"), + }; + let val_to_assign = interp(node.right.as_ref(), context); + if var_index < context.global_values.len() { + context.global_values[var_index] = val_to_assign; + } else { + // This should ideally not happen if fetch_var_offset works correctly + panic!("Assignment to invalid variable index {}", var_index); + } + val_to_assign // Assignment expression evaluates to the assigned value + } + + // Binary Operators + NodeType::Add => interp(node.left.as_ref(), context) + interp(node.right.as_ref(), context), + NodeType::Sub => interp(node.left.as_ref(), context) - interp(node.right.as_ref(), context), + NodeType::Mul => interp(node.left.as_ref(), context) * interp(node.right.as_ref(), context), + NodeType::Div => { + let right_val = interp(node.right.as_ref(), context); + if right_val == 0 { + eprintln!("error: Division by zero"); + process::exit(1); + } + interp(node.left.as_ref(), context) / right_val + } + NodeType::Mod => { + let right_val = interp(node.right.as_ref(), context); + if right_val == 0 { + eprintln!("error: Modulo by zero"); + process::exit(1); + } + interp(node.left.as_ref(), context) % right_val + } + NodeType::Lss => (interp(node.left.as_ref(), context) < interp(node.right.as_ref(), context)) as i32, + NodeType::Gtr => (interp(node.left.as_ref(), context) > interp(node.right.as_ref(), context)) as i32, + NodeType::Leq => (interp(node.left.as_ref(), context) <= interp(node.right.as_ref(), context)) as i32, + NodeType::Geq => (interp(node.left.as_ref(), context) >= interp(node.right.as_ref(), context)) as i32, + NodeType::Eql => (interp(node.left.as_ref(), context) == interp(node.right.as_ref(), context)) as i32, + NodeType::Neq => (interp(node.left.as_ref(), context) != interp(node.right.as_ref(), context)) as i32, + NodeType::And => (interp(node.left.as_ref(), context) != 0 && interp(node.right.as_ref(), context) != 0) as i32, + NodeType::Or => (interp(node.left.as_ref(), context) != 0 || interp(node.right.as_ref(), context) != 0) as i32, + + // Unary Operators + NodeType::Negate => -interp(node.left.as_ref(), context), + NodeType::Not => (interp(node.left.as_ref(), context) == 0) as i32, + + // Control Flow + NodeType::If => { + let condition = interp(node.left.as_ref(), context); + if condition != 0 { + // If branch is in right->left + interp(node.right.as_ref().and_then(|n| n.left.as_ref()), context); + } else { + // Else branch is in right->right + interp(node.right.as_ref().and_then(|n| n.right.as_ref()), context); + } + 0 // If statement doesn't return a value + } + NodeType::While => { + while interp(node.left.as_ref(), context) != 0 { + interp(node.right.as_ref(), context); + } + 0 // While loop doesn't return a value + } + + // Print Statements + NodeType::Prtc => { + let val = interp(node.left.as_ref(), context); + // Attempt to print as char, handle potential errors + if let Some(c) = std::char::from_u32(val as u32) { + print!("{}", c); + } else { + eprintln!("warning: Prtc value {} cannot be represented as char", val); + } + io::Write::flush(&mut io::stdout()).expect("Could not flush stdout"); + 0 + } + NodeType::Prti => { + print!("{}", interp(node.left.as_ref(), context)); + io::Write::flush(&mut io::stdout()).expect("Could not flush stdout"); + 0 + } + NodeType::Prts => { + let string_index = interp(node.left.as_ref(), context) as usize; + if let Some(s) = context.string_pool.get(string_index) { + print!("{}", s); + io::Write::flush(&mut io::stdout()).expect("Could not flush stdout"); + } else { + eprintln!("warning: Prts invalid string index {}", string_index); + } + 0 + } + + // Sequencing + NodeType::Sequence => { + interp(node.left.as_ref(), context); // Evaluate left side effect + interp(node.right.as_ref(), context); // Evaluate right side effect + 0 // Sequence doesn't return a value + } + } +} + +// --- Parser --- + +// Map C enum names to Rust NodeType enum +// Stored statically for efficiency +static NODE_TYPE_MAPPING: &[(&str, NodeType)] = &[ + ("Identifier", NodeType::Ident), + ("String", NodeType::String), + ("Integer", NodeType::Integer), + ("Sequence", NodeType::Sequence), + ("If", NodeType::If), + ("Prtc", NodeType::Prtc), + ("Prts", NodeType::Prts), + ("Prti", NodeType::Prti), + ("While", NodeType::While), + ("Assign", NodeType::Assign), + ("Negate", NodeType::Negate), + ("Not", NodeType::Not), + ("Multiply", NodeType::Mul), // Changed from C + ("Divide", NodeType::Div), // Changed from C + ("Mod", NodeType::Mod), + ("Add", NodeType::Add), + ("Subtract", NodeType::Sub), // Changed from C + ("Less", NodeType::Lss), // Changed from C + ("LessEqual", NodeType::Leq), + ("Greater", NodeType::Gtr), // Changed from C + ("GreaterEqual", NodeType::Geq), + ("Equal", NodeType::Eql), // Changed from C + ("NotEqual", NodeType::Neq), + ("And", NodeType::And), + ("Or", NodeType::Or), +]; + +// Helper function to report errors and exit +fn report_error(message: &str) -> Result { + Err(message.to_string()) +} + + +// Recursive function to load the AST from the input lines +fn load_ast( + lines: &mut Lines, + context: &mut InterpreterContext, +) -> Result>, String> { + match lines.next() { + None => Ok(None), // End of input + Some(line_result) => { + let line = line_result.map_err(|e| format!("IO Error reading line: {}", e))?; + let trimmed_line = line.trim(); + + // Skip comments and empty lines + if trimmed_line.is_empty() || trimmed_line.starts_with(';') { + return load_ast(lines, context); // Read next line + } + + // Split into tokens (NodeType and optional data) + let mut parts = trimmed_line.splitn(2, ' '); + let node_type_str = parts.next().ok_or("Line is unexpectedly empty after trim")?; + let data_part = parts.next().map(|s| s.trim()).filter(|s| !s.is_empty()); + + // Get the NodeType enum variant + let node_type = context + .get_node_type(node_type_str) + .ok_or_else(|| format!("Unknown node type token: {}", node_type_str))?; + + // If there's data, it's a leaf node + if let Some(data) = data_part { + let value = match node_type { + NodeType::Ident => context.fetch_var_offset(data) as i32, + NodeType::Integer => data.parse::() + .map_err(|_| format!("Invalid integer literal: {}", data))?, + NodeType::String => context.fetch_string_offset(data)? as i32, + _ => return report_error(&format!("Node type '{}' should not have data '{}'", node_type_str, data)), + }; + Ok(Some(make_leaf(node_type, value))) + } else { + // No data part, so it's an internal node. Recursively load children. + // Check arity based on node type + match node_type { + // Unary operators or control structures needing one child/subtree + NodeType::Negate | NodeType::Not | NodeType::Prtc | NodeType::Prti | NodeType::Prts => { + let left = load_ast(lines, context)?; + Ok(Some(make_node(node_type, left, None))) + } + // Binary operators or control structures needing two children/subtrees + NodeType::Sequence | NodeType::If | NodeType::While | NodeType::Assign | + NodeType::Mul | NodeType::Div | NodeType::Mod | NodeType::Add | NodeType::Sub | + NodeType::Lss | NodeType::Leq | NodeType::Gtr | NodeType::Geq | + NodeType::Eql | NodeType::Neq | NodeType::And | NodeType::Or => { + let left = load_ast(lines, context)?; + let right = load_ast(lines, context)?; + Ok(Some(make_node(node_type, left, right))) + } + // Leaf node types that were handled above. Error if encountered here. + NodeType::Ident | NodeType::String | NodeType::Integer => { + report_error(&format!("Leaf node type '{}' found without data", node_type_str)) + } + } + } + } + } +} + +// --- Main Function --- + +fn main() -> Result<(), String> { + let args: Vec = env::args().collect(); + + // Determine input source: file or stdin + let input: Box = if args.len() > 1 && !args[1].is_empty() { + let filename = &args[1]; + let file = File::open(filename) + .map_err(|e| format!("Cannot open file '{}': {}", filename, e))?; + Box::new(BufReader::new(file)) + } else { + Box::new(BufReader::new(io::stdin())) + }; + + let mut lines = input.lines(); + let mut context = InterpreterContext::new(); + + // Load the entire AST structure + let ast_root = load_ast(&mut lines, &mut context)?; + + // Interpret the loaded AST + interp(ast_root.as_ref(), &mut context); + + println!(); // Add a newline like the C version might implicitly do after last print + + Ok(()) +} diff --git a/Task/Compiler-code-generator/JavaScript/compiler-code-generator.js b/Task/Compiler-code-generator/JavaScript/compiler-code-generator.js new file mode 100644 index 0000000000..4a26bae23c --- /dev/null +++ b/Task/Compiler-code-generator/JavaScript/compiler-code-generator.js @@ -0,0 +1,502 @@ +// Required Node.js modules +const fs = require('fs'); +const path = require('path'); // Useful for joining paths if needed + +// --- Constants --- +const WORD_SIZE = 4; // In bytes + +// --- Enums (JavaScript Object Equivalents) --- + +const Mnemonic = { + NONE: { ordinal: 0, name: 'NONE' }, + FETCH: { ordinal: 1, name: 'FETCH' }, + STORE: { ordinal: 2, name: 'STORE' }, + PUSH: { ordinal: 3, name: 'PUSH' }, + ADD: { ordinal: 4, name: 'ADD' }, + SUB: { ordinal: 5, name: 'SUB' }, + MUL: { ordinal: 6, name: 'MUL' }, + DIV: { ordinal: 7, name: 'DIV' }, + MOD: { ordinal: 8, name: 'MOD' }, + LT: { ordinal: 9, name: 'LT' }, + GT: { ordinal: 10, name: 'GT' }, + LE: { ordinal: 11, name: 'LE' }, + GE: { ordinal: 12, name: 'GE' }, + EQ: { ordinal: 13, name: 'EQ' }, + NE: { ordinal: 14, name: 'NE' }, + AND: { ordinal: 15, name: 'AND' }, + OR: { ordinal: 16, name: 'OR' }, + NEG: { ordinal: 17, name: 'NEG' }, + NOT: { ordinal: 18, name: 'NOT' }, + JMP: { ordinal: 19, name: 'JMP' }, + JZ: { ordinal: 20, name: 'JZ' }, + PRTC: { ordinal: 21, name: 'PRTC' }, + PRTS: { ordinal: 22, name: 'PRTS' }, + PRTI: { ordinal: 23, name: 'PRTI' }, + HALT: { ordinal: 24, name: 'HALT' }, +}; + +// Helper array to map ordinal back to Mnemonic object (for listCode) +const MnemonicByOrdinal = Object.values(Mnemonic).sort((a, b) => a.ordinal - b.ordinal); + + +const NodeType = { + nd_None: { name: 'None', mnemonic: Mnemonic.NONE }, + nd_Ident: { name: 'Identifier', mnemonic: Mnemonic.NONE }, + nd_String: { name: 'String', mnemonic: Mnemonic.NONE }, + nd_Integer: { name: 'Integer', mnemonic: Mnemonic.NONE }, + nd_Sequence: { name: 'Sequence', mnemonic: Mnemonic.NONE }, + nd_If: { name: 'If', mnemonic: Mnemonic.NONE }, + nd_Prtc: { name: 'Prtc', mnemonic: Mnemonic.PRTC }, + nd_Prts: { name: 'Prts', mnemonic: Mnemonic.PRTS }, + nd_Prti: { name: 'Prti', mnemonic: Mnemonic.PRTI }, + nd_While: { name: 'While', mnemonic: Mnemonic.NONE }, + nd_Assign: { name: 'Assign', mnemonic: Mnemonic.NONE }, + nd_Negate: { name: 'Negate', mnemonic: Mnemonic.NEG }, + nd_Not: { name: 'Not', mnemonic: Mnemonic.NOT }, + nd_Mul: { name: 'Multiply', mnemonic: Mnemonic.MUL }, + nd_Div: { name: 'Divide', mnemonic: Mnemonic.DIV }, + nd_Mod: { name: 'Mod', mnemonic: Mnemonic.MOD }, + nd_Add: { name: 'Add', mnemonic: Mnemonic.ADD }, + nd_Sub: { name: 'Subtract', mnemonic: Mnemonic.SUB }, + nd_Lss: { name: 'Less', mnemonic: Mnemonic.LT }, + nd_Leq: { name: 'LessEqual', mnemonic: Mnemonic.LE }, + nd_Gtr: { name: 'Greater', mnemonic: Mnemonic.GT }, + nd_Geq: { name: 'GreaterEqual', mnemonic: Mnemonic.GE }, + nd_Eql: { name: 'Equal', mnemonic: Mnemonic.EQ }, + nd_Neq: { name: 'NotEqual', mnemonic: Mnemonic.NE }, + nd_And: { name: 'And', mnemonic: Mnemonic.AND }, + nd_Or: { name: 'Or', mnemonic: Mnemonic.OR }, +}; + + +// --- AST Node Class --- +class Node { + constructor(nt = null, left = null, right = null, value = null) { + this.nt = nt; + this.left = left; + this.right = right; + this.value = value; + } + + static makeNode(nodetype, left, right) { + return new Node(nodetype, left, right, null); + } + + static makeNode1(nodetype, left) { + return new Node(nodetype, left, null, null); + } + + static makeLeaf(nodetype, value) { + return new Node(nodetype, null, null, value); + } +} + + +// --- Code Generator State and Methods --- + +let code = new Uint8Array(0); // Use Uint8Array for byte code +const strToNodes = new Map(); +const stringPool = []; +const variables = []; +let stringCount = 0; +let varCount = 0; + +const unaryOps = [ + NodeType.nd_Negate, NodeType.nd_Not +]; +const operators = [ + NodeType.nd_Mul, NodeType.nd_Div, NodeType.nd_Mod, NodeType.nd_Add, NodeType.nd_Sub, + NodeType.nd_Lss, NodeType.nd_Leq, NodeType.nd_Gtr, NodeType.nd_Geq, + NodeType.nd_Eql, NodeType.nd_Neq, NodeType.nd_And, NodeType.nd_Or +]; + +// State for reading AST from lines +let inputLines = []; +let currentLineIndex = 0; + + +function appendToCode(b) { + const newCode = new Uint8Array(code.length + 1); + newCode.set(code); // Copy existing bytes + newCode[code.length] = b & 0xff; // Add new byte (ensure it's 0-255) + code = newCode; +} + +function emitByte(m) { + appendToCode(m.ordinal); +} + +function emitWord(n) { + // Ensure n is treated as a 32-bit integer (signed or unsigned depends on context) + // Emit bytes in big-endian order + appendToCode((n >> 24) & 0xff); + appendToCode((n >> 16) & 0xff); + appendToCode((n >> 8) & 0xff); + appendToCode(n & 0xff); +} + +function emitWordAt(pos, n) { + if (pos + WORD_SIZE > code.length) { + throw new Error(`Emit word out of bounds at position ${pos}`); + } + // Ensure n is treated as a 32-bit integer + code[pos] = (n >> 24) & 0xff; + code[pos + 1] = (n >> 16) & 0xff; + code[pos + 2] = (n >> 8) & 0xff; + code[pos + 3] = n & 0xff; +} + +function getWord(pos) { + if (pos + WORD_SIZE > code.length) { + throw new Error(`Get word out of bounds at position ${pos}`); + } + // Read bytes in big-endian order and combine into a 32-bit integer + // Need to treat bytes as unsigned (0-255) using & 0xff + let result = 0; + result |= (code[pos] & 0xff) << 24; + result |= (code[pos + 1] & 0xff) << 16; + result |= (code[pos + 2] & 0xff) << 8; + result |= (code[pos + 3] & 0xff); + + // Handle sign bit if the result is expected to be signed + // In JS, bitwise ops treat numbers as signed 32-bit. + // The above combination *might* result in a negative number + // if the most significant bit is set (for values >= 2^31). + // If the VM expects unsigned, this is fine. If signed, + // JS handles this conversion reasonably well after the bitwise ops. + // Let's return the potentially signed result from the bitwise ops. + return result; +} + + +function fetchVarOffset(name) { + let n = variables.indexOf(name); + if (n === -1) { + variables.push(name); + n = varCount++; + } + return n; +} + +function fetchStringOffset(str) { + let n = stringPool.indexOf(str); + if (n === -1) { + stringPool.push(str); + n = stringCount++; + } + return n; +} + +function hole() { + const t = code.length; + emitWord(0); // Emit a placeholder word (0) + return t; // Return the position of the hole +} + +function arrayContains(arr, item) { + return arr.includes(item); // JavaScript Array.prototype.includes is equivalent +} + +function codeGen(x) { + let n, p1, p2; + if (x === null) return; + + switch (x.nt) { + case NodeType.nd_None: + return; + case NodeType.nd_Ident: + emitByte(Mnemonic.FETCH); + n = fetchVarOffset(x.value); + emitWord(n); + break; + case NodeType.nd_Integer: + emitByte(Mnemonic.PUSH); + emitWord(parseInt(x.value, 10)); // Use radix 10 + break; + case NodeType.nd_String: + emitByte(Mnemonic.PUSH); + n = fetchStringOffset(x.value); + emitWord(n); + break; + case NodeType.nd_Assign: + n = fetchVarOffset(x.left.value); + codeGen(x.right); + emitByte(Mnemonic.STORE); + emitWord(n); + break; + case NodeType.nd_If: + // p2 needs scope beyond the if block, initialize before switch case + codeGen(x.left); // Condition + emitByte(Mnemonic.JZ); // Jump if condition is zero (false) + p1 = hole(); // Placeholder for jump address (to 'else' or end of 'then') + + codeGen(x.right.left); // 'then' block + + if (x.right.right !== null) { // Check if 'else' block exists + emitByte(Mnemonic.JMP); // Jump over 'else' block after 'then' + p2 = hole(); // Placeholder for jump address (to end of 'else') + } + + // Patch the JZ instruction: jump relative from instruction *after* the word + emitWordAt(p1, code.length - (p1 + WORD_SIZE)); + + if (x.right.right !== null) { + codeGen(x.right.right); // 'else' block + // Patch the JMP instruction: jump relative from instruction *after* the word + emitWordAt(p2, code.length - (p2 + WORD_SIZE)); + } + break; + case NodeType.nd_While: + p1 = code.length; // Start of the loop condition + codeGen(x.left); // Condition + emitByte(Mnemonic.JZ); // Jump if condition is zero (false) + p2 = hole(); // Placeholder for jump address (to end of loop) + + codeGen(x.right); // Loop body + + emitByte(Mnemonic.JMP); // Jump back to the start of the loop condition + // Jump relative from instruction *after* the word + emitWord(p1 - (code.length + WORD_SIZE)); + + // Patch the JZ instruction: jump relative from instruction *after* the word + emitWordAt(p2, code.length - (p2 + WORD_SIZE)); + break; + case NodeType.nd_Sequence: + codeGen(x.left); + codeGen(x.right); + break; + case NodeType.nd_Prtc: + codeGen(x.left); + emitByte(Mnemonic.PRTC); + break; + case NodeType.nd_Prti: + codeGen(x.left); + emitByte(Mnemonic.PRTI); + break; + case NodeType.nd_Prts: + codeGen(x.left); + emitByte(Mnemonic.PRTS); + break; + default: + if (arrayContains(operators, x.nt)) { + codeGen(x.left); + codeGen(x.right); + emitByte(x.nt.mnemonic); // Use the mnemonic property + } else if (arrayContains(unaryOps, x.nt)) { + codeGen(x.left); + emitByte(x.nt.mnemonic); // Use the mnemonic property + } else { + throw new Error(`Error in code generator! Found ${x.nt.name}, expecting operator.`); + } + } +} + +function listCode() { + let pc = 0; + console.log(`Datasize: ${varCount} Strings: ${stringCount}`); + for (const s of stringPool) { + console.log(`"${s}"`); // Print strings, maybe quoted + } + + console.log("\n--- Code ---"); + + while (pc < code.length) { + process.stdout.write(`${pc.toString().padStart(4, ' ')} `); // Format like printf %4d + const opcodeValue = code[pc++]; + if (opcodeValue >= MnemonicByOrdinal.length) { + throw new Error(`Unknown opcode value ${opcodeValue} @ ${pc - 1}`); + } + const op = MnemonicByOrdinal[opcodeValue]; + + let x; + switch (op) { + case Mnemonic.FETCH: + x = getWord(pc); + process.stdout.write(`fetch [${x}]`); + pc += WORD_SIZE; + break; + case Mnemonic.STORE: + x = getWord(pc); + process.stdout.write(`store [${x}]`); + pc += WORD_SIZE; + break; + case Mnemonic.PUSH: + x = getWord(pc); + process.stdout.write(`push ${x}`); + pc += WORD_SIZE; + break; + case Mnemonic.ADD: case Mnemonic.SUB: case Mnemonic.MUL: case Mnemonic.DIV: case Mnemonic.MOD: + case Mnemonic.LT: case Mnemonic.GT: case Mnemonic.LE: case Mnemonic.GE: case Mnemonic.EQ: case Mnemonic.NE: + case Mnemonic.AND: case Mnemonic.OR: case Mnemonic.NEG: case Mnemonic.NOT: + case Mnemonic.PRTC: case Mnemonic.PRTI: case Mnemonic.PRTS: case Mnemonic.HALT: + process.stdout.write(op.name.toLowerCase()); + break; + case Mnemonic.JMP: + x = getWord(pc); // Read relative offset + // Relative offset is calculated from the *instruction following the word* in the VM + // pc points to the byte *after* the word now. + process.stdout.write(`jmp (${x}) ${pc + x}`); + pc += WORD_SIZE; + break; + case Mnemonic.JZ: + x = getWord(pc); // Read relative offset + // Relative offset is calculated from the *instruction following the word* in the VM + // pc points to the byte *after* the word now. + process.stdout.write(`jz (${x}) ${pc + x}`); + pc += WORD_SIZE; + break; + default: + // Should not happen if MnemonicByOrdinal is correctly built + throw new Error(`Unknown opcode ${op.name} (${opcodeValue}) @ ${pc - 1}`); + } + console.log(); // Newline after each instruction + } +} + + +// Helper function to get the next line from the pre-loaded array +function getNextLine() { + if (currentLineIndex >= inputLines.length) { + return null; // End of input + } + return inputLines[currentLineIndex++]; +} + +function loadAst() { + let command, value; + let line = getNextLine(); + + while (line !== null) { + value = null; + // Check line length before substring to avoid errors + if (line.length > 15) { + command = line.substring(0, 15).trim(); + value = line.substring(15).trim(); + } else { + command = line.trim(); + } + + if (command === ";") { + return null; // End of a sequence or node definition + } + + const nodeType = strToNodes.get(command); + if (!nodeType) { + throw new Error(`Command not found: '${command}' on line ${currentLineIndex}`); + } + + if (value !== null && value !== "") { // Check value is not just empty string + // Note: The Java code checks value != null. If the AST format + // allows "Identifier ", value will be "" after trim. + // Let's stick closer to Java's null check, assuming non-leaf + // nodes won't have anything after column 15 except whitespace. + // Re-evaluating Java: `value != null` is set based on `line.length > 16`. + // Let's emulate that logic closely. + + // Java logic: value = line.substring(15).trim(); IF line.length > 16 + // Then `if (value != null)` returns leaf. + // If line.length <= 16, command = line.trim(), value = null. + // So leaf nodes MUST have something after col 15. + // Let's adjust: if line.length > 15, value = line.substring(15).trim(). + // Then check if value is non-empty. This handles "Identifier " as non-leaf. + + // Corrected logic: + if (line.length > 15 && line.substring(15).trim() !== "") { + value = line.substring(15).trim(); + return Node.makeLeaf(nodeType, value); + } + // If line.length <= 15 OR substring(15).trim() is empty, + // it's not a leaf with a value in that part of the line. + // Fall through to non-leaf handling. + } + + + // If it's not a leaf (or the leaf value part was empty/absent based on col 15) + // Recursively load children + const left = loadAst(); + const right = loadAst(); // Might be null for unary/sequence end + + // Some nodes like Prtc, Prti, Prts, Negate, Not only have a left child + // Based on the Java code_gen, these are treated as makeNode1 implicitly + // but load_ast always tries to read two children. + // The AST format must represent unary nodes with a ";" after the single child. + // Example: Prtc\n Integer 10\n ;\n ; + // This recursive loadAst handles that structure. + return Node.makeNode(nodeType, left, right); + } + + // Should ideally not reach here if input is well-formed and ends with AST + // But needed for compiler in Java, let's return null in JS too for safety. + return null; +} + + +// --- Initialization --- +function initialize() { + strToNodes.set(";", NodeType.nd_None); // Special case for AST parsing termination + strToNodes.set("Sequence", NodeType.nd_Sequence); + strToNodes.set("Identifier", NodeType.nd_Ident); + strToNodes.set("String", NodeType.nd_String); + strToNodes.set("Integer", NodeType.nd_Integer); + strToNodes.set("If", NodeType.nd_If); + strToNodes.set("While", NodeType.nd_While); + strToNodes.set("Prtc", NodeType.nd_Prtc); + strToNodes.set("Prts", NodeType.nd_Prts); + strToNodes.set("Prti", NodeType.nd_Prti); + strToNodes.set("Assign", NodeType.nd_Assign); + strToNodes.set("Negate", NodeType.nd_Negate); + strToNodes.set("Not", NodeType.nd_Not); + strToNodes.set("Multiply", NodeType.nd_Mul); + strToNodes.set("Divide", NodeType.nd_Div); + strToNodes.set("Mod", NodeType.nd_Mod); + strToNodes.set("Add", NodeType.nd_Add); + strToNodes.set("Subtract", NodeType.nd_Sub); + strToNodes.set("Less", NodeType.nd_Lss); + strToNodes.set("LessEqual", NodeType.nd_Leq); + strToNodes.set("Greater", NodeType.nd_Gtr); + strToNodes.set("GreaterEqual", NodeType.nd_Geq); + strToNodes.set("Equal", NodeType.nd_Eql); + strToNodes.set("NotEqual", NodeType.nd_Neq); + strToNodes.set("And", NodeType.nd_And); + strToNodes.set("Or", NodeType.nd_Or); +} + + +// --- Main Execution --- +function main() { + initialize(); + + const args = process.argv.slice(2); // Get command line arguments excluding 'node' and script name + + if (args.length > 0) { + const filename = args[0]; + try { + // Read the entire file synchronously for simpler line-by-line processing + const fileContent = fs.readFileSync(filename, 'utf8'); + inputLines = fileContent.split(/\r?\n/); // Split into lines, handling common line endings + currentLineIndex = 0; // Reset line index for loadAst + + const ast = loadAst(); + + if (ast) { + codeGen(ast); + emitByte(Mnemonic.HALT); // Emit HALT after generating code for the main AST + listCode(); + } else { + console.log("No valid AST loaded."); + } + + + } catch (e) { + console.error(`Error: ${e.message}`); + // console.error(e.stack); // Uncomment for detailed stack trace + } + } else { + console.log("Usage: node code_generator.js "); + } +} + +// Execute the main function +if (require.main === module) { + main(); +} diff --git a/Task/Compiler-code-generator/Rust/compiler-code-generator.rs b/Task/Compiler-code-generator/Rust/compiler-code-generator.rs new file mode 100644 index 0000000000..795d5617f4 --- /dev/null +++ b/Task/Compiler-code-generator/Rust/compiler-code-generator.rs @@ -0,0 +1,644 @@ +// src/main.rs + +use std::collections::HashMap; +use std::fs::File; +use std::io::{self, BufRead, BufReader, BufWriter, Write}; +use std::path::Path; +use std::process; +use std::error::Error; +use std::fmt; + +// --- Custom Error Type --- +#[derive(Debug)] +enum CompileError { + Io(io::Error), + Parse(String), + CodeGen(String), + Runtime(String), // For potential runtime errors if extended later +} + +impl fmt::Display for CompileError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CompileError::Io(e) => write!(f, "IO Error: {}", e), + CompileError::Parse(msg) => write!(f, "Parse Error: {}", msg), + CompileError::CodeGen(msg) => write!(f, "Code Generation Error: {}", msg), + CompileError::Runtime(msg) => write!(f, "Runtime Error: {}", msg), + } + } +} + +impl Error for CompileError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + CompileError::Io(e) => Some(e), + _ => None, + } + } +} + +// Allow converting io::Error into CompileError +impl From for CompileError { + fn from(err: io::Error) -> CompileError { + CompileError::Io(err) + } +} + +// Convenience type alias for Results +type Result = std::result::Result; + +// --- Enums --- +// Using u8 for Code as in the C code (uchar) +type CodeByte = u8; + +// Added derive attributes for convenience +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[repr(u8)] // Explicit representation matching C's implicit enum values +enum NodeType { + Ident, String, Integer, Sequence, If, Prtc, Prts, Prti, While, + Assign, Negate, Not, Mul, Div, Mod, Add, Sub, Lss, Leq, + Gtr, Geq, Eql, Neq, And, Or, + // Added for parsing unknown types + Unknown, +} + +// Mapping string names to NodeType - replacing get_enum_value C function +fn node_type_from_str(s: &str) -> NodeType { + match s { + "Identifier" => NodeType::Ident, + "String" => NodeType::String, + "Integer" => NodeType::Integer, + "Sequence" => NodeType::Sequence, + "If" => NodeType::If, + "Prtc" => NodeType::Prtc, + "Prts" => NodeType::Prts, + "Prti" => NodeType::Prti, + "While" => NodeType::While, + "Assign" => NodeType::Assign, + "Negate" => NodeType::Negate, + "Not" => NodeType::Not, + "Multiply" => NodeType::Mul, + "Divide" => NodeType::Div, + "Mod" => NodeType::Mod, + "Add" => NodeType::Add, + "Subtract" => NodeType::Sub, + "Less" => NodeType::Lss, + "LessEqual" => NodeType::Leq, + "Greater" => NodeType::Gtr, + "GreaterEqual" => NodeType::Geq, + "Equal" => NodeType::Eql, + "NotEqual" => NodeType::Neq, + "And" => NodeType::And, + "Or" => NodeType::Or, + _ => NodeType::Unknown, // Handle unknown tokens gracefully + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +enum OpCode { + Fetch, Store, Push, Add, Sub, Mul, Div, Mod, Lt, Gt, Le, Ge, Eq, Ne, And, + Or, Neg, Not, Jmp, Jz, Prtc, Prts, Prti, Halt, +} + +// --- Structs --- +#[derive(Debug, Clone)] // Added Clone for easier handling if needed +struct Tree { + node_type: NodeType, + // Use Option> for optional children + left: Option>, + right: Option>, + // Use String for owned string values + value: Option, +} + +impl Tree { + // Constructor for nodes with children + fn new_node(node_type: NodeType, left: Tree, right: Tree) -> Box { + Box::new(Tree { + node_type, + left: Some(Box::new(left)), + right: Some(Box::new(right)), + value: None, + }) + } + + // Constructor for nodes with children (accepting Option>) + fn new_node_option(node_type: NodeType, left: Option>, right: Option>) -> Box { + Box::new(Tree { + node_type, + left, + right, + value: None, + }) + } + + + // Constructor for leaf nodes with a value + fn new_leaf(node_type: NodeType, value: &str) -> Box { + Box::new(Tree { + node_type, + left: None, + right: None, + value: Some(value.to_string()), + }) + } +} + +// --- Code Generation State --- +struct CodeGenState { + object: Vec, // Replaces da_dim(object, code) + globals: Vec, // Replaces da_dim(globals, const char *) + string_pool: Vec, // Replaces da_dim(string_pool, const char *) + // `here` is implicitly `object.len()` +} + +impl CodeGenState { + fn new() -> Self { + CodeGenState { + object: Vec::new(), + globals: Vec::new(), + string_pool: Vec::new(), + } + } + + // Get current code position + fn here(&self) -> usize { + self.object.len() + } + + // Replaces emit_byte + fn emit_byte(&mut self, byte: CodeByte) { + self.object.push(byte); + } + + // Emit an opcode + fn emit_opcode(&mut self, opcode: OpCode) { + self.object.push(opcode as CodeByte); + } + + // Replaces emit_int - uses little-endian encoding + fn emit_int(&mut self, value: i32) { + self.object.extend_from_slice(&value.to_le_bytes()); + } + + // Replaces hole() + fn emit_hole(&mut self) -> usize { + let pos = self.here(); + self.emit_int(0); // Placeholder value + pos + } + + // Replaces fix() - patches a previous hole + // Uses little-endian encoding + fn fix_jump(&mut self, hole_pos: usize, jump_target: usize) -> Result<()> { + if hole_pos + 4 > self.object.len() { + return Err(CompileError::CodeGen("Invalid hole position for jump fix".to_string())); + } + // Calculate relative offset + let offset = jump_target as isize - (hole_pos as isize + 4); // offset is from *after* the int + let offset_bytes = (offset as i32).to_le_bytes(); + self.object[hole_pos..hole_pos + 4].copy_from_slice(&offset_bytes); + Ok(()) + } + + // Like C's fix, but uses absolute target address for patching data later + // Use for patching arbitrary data, not jumps + fn fix_data(&mut self, pos: usize, value: i32) -> Result<()> { + if pos + 4 > self.object.len() { + return Err(CompileError::CodeGen("Invalid position for data fix".to_string())); + } + let value_bytes = value.to_le_bytes(); + self.object[pos..pos + 4].copy_from_slice(&value_bytes); + Ok(()) + } + + + // Replaces fetch_var_offset + fn fetch_var_offset(&mut self, id: &str) -> usize { + if let Some(pos) = self.globals.iter().position(|g| g == id) { + pos + } else { + self.globals.push(id.to_string()); + self.globals.len() - 1 + } + } + + // Replaces fetch_string_offset + fn fetch_string_offset(&mut self, st: &str) -> usize { + if let Some(pos) = self.string_pool.iter().position(|s| s == st) { + pos + } else { + self.string_pool.push(st.to_string()); + self.string_pool.len() - 1 + } + } + + // Replaces type_to_op + fn type_to_op(node_type: NodeType) -> Option { + match node_type { + NodeType::Negate => Some(OpCode::Neg), + NodeType::Not => Some(OpCode::Not), + NodeType::Mul => Some(OpCode::Mul), + NodeType::Div => Some(OpCode::Div), + NodeType::Mod => Some(OpCode::Mod), + NodeType::Add => Some(OpCode::Add), + NodeType::Sub => Some(OpCode::Sub), + NodeType::Lss => Some(OpCode::Lt), + NodeType::Leq => Some(OpCode::Le), + NodeType::Gtr => Some(OpCode::Gt), + NodeType::Geq => Some(OpCode::Ge), + NodeType::Eql => Some(OpCode::Eq), + NodeType::Neq => Some(OpCode::Ne), + NodeType::And => Some(OpCode::And), + NodeType::Or => Some(OpCode::Or), + _ => None, // Other node types don't map directly to a single opcode + } + } + + // --- Code Generator Logic --- + // Takes Option<&Tree> because some nodes might have absent children + fn code_gen(&mut self, node: Option<&Tree>) -> Result<()> { + let node = match node { + Some(n) => n, + None => return Ok(()), // Nothing to generate for a None node + }; + + match node.node_type { + NodeType::Ident => { + let ident = node.value.as_ref().ok_or_else(|| { + CompileError::CodeGen("Identifier node is missing value".to_string()) + })?; + self.emit_opcode(OpCode::Fetch); + let offset = self.fetch_var_offset(ident); + self.emit_int(offset as i32); + } + NodeType::Integer => { + let val_str = node.value.as_ref().ok_or_else(|| { + CompileError::CodeGen("Integer node is missing value".to_string()) + })?; + let value = val_str.parse::().map_err(|e| { + CompileError::Parse(format!("Invalid integer literal '{}': {}", val_str, e)) + })?; + self.emit_opcode(OpCode::Push); + self.emit_int(value); + } + NodeType::String => { + let val_str = node.value.as_ref().ok_or_else(|| { + CompileError::CodeGen("String node is missing value".to_string()) + })?; + self.emit_opcode(OpCode::Push); + let offset = self.fetch_string_offset(val_str); + self.emit_int(offset as i32); + } + NodeType::Assign => { + let ident_node = node.left.as_ref().ok_or_else(|| { + CompileError::CodeGen("Assignment missing identifier (left side)".to_string()) + })?; + let ident = ident_node.value.as_ref().ok_or_else(|| { + CompileError::CodeGen("Assignment identifier node missing value".to_string()) + })?; + if ident_node.node_type != NodeType::Ident { + return Err(CompileError::CodeGen("Left side of assignment must be an identifier".to_string())); + } + + let var_offset = self.fetch_var_offset(ident); + self.code_gen(node.right.as_deref())?; // Generate value first + self.emit_opcode(OpCode::Store); + self.emit_int(var_offset as i32); + } + NodeType::If => { + // If condition + self.code_gen(node.left.as_deref())?; + self.emit_opcode(OpCode::Jz); // Jump if zero (false) + let jump_over_true_branch_hole = self.emit_hole(); + + // True branch (must be present, wrapped in Sequence or single node) + let if_body = node.right.as_ref().ok_or_else(|| CompileError::CodeGen("If node missing body (right side)".to_string()))?; + + self.code_gen(if_body.left.as_deref())?; // Execute 'then' part + + // Handle optional 'else' part + let mut jump_over_else_branch_hole: Option = None; + if if_body.right.is_some() { + self.emit_opcode(OpCode::Jmp); // Jump over the 'else' part + jump_over_else_branch_hole = Some(self.emit_hole()); + } + + // Patch the first jump (jz) to point after the 'then' block (or after the 'jmp' if there's an else) + let after_true_branch = self.here(); + self.fix_jump(jump_over_true_branch_hole, after_true_branch)?; + + // Generate 'else' block if it exists + if let Some(else_node) = &if_body.right { + self.code_gen(Some(else_node))?; + // Patch the jump over the else branch + let after_else_branch = self.here(); + if let Some(hole) = jump_over_else_branch_hole { + self.fix_jump(hole, after_else_branch)?; + } else { + // Should not happen if if_body.right was Some + return Err(CompileError::CodeGen("Internal error: Missing else jump hole".to_string())); + } + } + } + NodeType::While => { + let condition_start = self.here(); + self.code_gen(node.left.as_deref())?; // While expr + self.emit_opcode(OpCode::Jz); // If false, jump to end + let exit_jump_hole = self.emit_hole(); + + self.code_gen(node.right.as_deref())?; // Loop body + self.emit_opcode(OpCode::Jmp); // Jump back to condition + // Use emit_hole + fix_jump for the backward jump + let back_jump_hole = self.emit_hole(); + self.fix_jump(back_jump_hole, condition_start)?; + + let after_loop = self.here(); + self.fix_jump(exit_jump_hole, after_loop)?; // Patch the exit jump + } + NodeType::Sequence => { + self.code_gen(node.left.as_deref())?; + self.code_gen(node.right.as_deref())?; + } + NodeType::Prtc => { + self.code_gen(node.left.as_deref())?; + self.emit_opcode(OpCode::Prtc); + } + NodeType::Prti => { + self.code_gen(node.left.as_deref())?; + self.emit_opcode(OpCode::Prti); + } + NodeType::Prts => { + self.code_gen(node.left.as_deref())?; + self.emit_opcode(OpCode::Prts); + } + // Binary Operators + NodeType::Lss | NodeType::Gtr | NodeType::Leq | NodeType::Geq | + NodeType::Eql | NodeType::Neq | NodeType::And | NodeType::Or | + NodeType::Sub | NodeType::Add | NodeType::Div | NodeType::Mul | + NodeType::Mod => { + self.code_gen(node.left.as_deref())?; + self.code_gen(node.right.as_deref())?; + if let Some(op) = CodeGenState::type_to_op(node.node_type) { + self.emit_opcode(op); + } else { + return Err(CompileError::CodeGen(format!( + "Cannot map node type {:?} to binary opcode", node.node_type + ))); + } + } + // Unary Operators + NodeType::Negate | NodeType::Not => { + self.code_gen(node.left.as_deref())?; + if let Some(op) = CodeGenState::type_to_op(node.node_type) { + self.emit_opcode(op); + } else { + return Err(CompileError::CodeGen(format!( + "Cannot map node type {:?} to unary opcode", node.node_type + ))); + } + } + NodeType::Unknown => { + return Err(CompileError::CodeGen("Encountered Unknown node type during code generation".to_string())); + } + } + Ok(()) + } + + // Replaces code_finish + fn code_finish(&mut self) { + self.emit_opcode(OpCode::Halt); + } +} + + +// --- Disassembler --- +// Replaces list_code +// Takes BufWriter for potentially better performance with many writes +fn list_code(state: &CodeGenState, writer: &mut BufWriter) -> Result<()> { + writeln!(writer, "Datasize: {} Strings: {}", state.globals.len(), state.string_pool.len())?; + for s in &state.string_pool { + writeln!(writer, "{}", s)?; + } + writeln!(writer, "--- Code ---")?; + + let code = &state.object; + let mut pc = 0; + + while pc < code.len() { + let start_pc = pc; + write!(writer, "{:5} ", start_pc)?; + + // Function to safely read an i32 operand + let read_operand = |current_pc: usize| -> Result<(i32, usize)> { + let end_operand = current_pc + 4; + if end_operand > code.len() { + Err(CompileError::Runtime("Unexpected end of code while reading operand".to_string())) + } else { + // Read bytes assuming little-endian + let mut bytes = [0u8; 4]; + bytes.copy_from_slice(&code[current_pc..end_operand]); + Ok((i32::from_le_bytes(bytes), end_operand)) + } + }; + + // Function to safely read an opcode byte + let read_opcode_byte = |current_pc: usize| -> Result<(u8, usize)> { + if current_pc >= code.len() { + Err(CompileError::Runtime("Unexpected end of code while reading opcode".to_string())) + } else { + Ok((code[current_pc], current_pc + 1)) + } + }; + + let (opcode_byte, next_pc) = read_opcode_byte(pc)?; + pc = next_pc; // Move pc past the opcode byte + + // Try to convert byte to OpCode enum + let opcode: OpCode = unsafe { + // This is safe IF OpCode is repr(u8) and opcode_byte is a valid variant value. + // A safer way would be a match statement or a function. + if opcode_byte <= OpCode::Halt as u8 { + std::mem::transmute(opcode_byte) + } else { + writeln!(writer, "ERROR: Unknown opcode byte {}", opcode_byte)?; + return Err(CompileError::Runtime(format!("Unknown opcode byte: {}", opcode_byte))); + } + }; + + + match opcode { + OpCode::Fetch => { + let (operand, next_pc) = read_operand(pc)?; pc = next_pc; + writeln!(writer, "fetch [{}]", operand)?; + } + OpCode::Store => { + let (operand, next_pc) = read_operand(pc)?; pc = next_pc; + writeln!(writer, "store [{}]", operand)?; + } + OpCode::Push => { + let (operand, next_pc) = read_operand(pc)?; pc = next_pc; + writeln!(writer, "push {}", operand)?; + } + OpCode::Add => writeln!(writer, "add")?, + OpCode::Sub => writeln!(writer, "sub")?, + OpCode::Mul => writeln!(writer, "mul")?, + OpCode::Div => writeln!(writer, "div")?, + OpCode::Mod => writeln!(writer, "mod")?, + OpCode::Lt => writeln!(writer, "lt")?, + OpCode::Gt => writeln!(writer, "gt")?, + OpCode::Le => writeln!(writer, "le")?, + OpCode::Ge => writeln!(writer, "ge")?, + OpCode::Eq => writeln!(writer, "eq")?, + OpCode::Ne => writeln!(writer, "ne")?, + OpCode::And => writeln!(writer, "and")?, + OpCode::Or => writeln!(writer, "or")?, + OpCode::Neg => writeln!(writer, "neg")?, + OpCode::Not => writeln!(writer, "not")?, + OpCode::Jmp | OpCode::Jz => { + let (offset, next_pc) = read_operand(pc)?; pc = next_pc; + // Calculate absolute target address + // offset is relative to the instruction *after* the operand + let target_pc = (pc as isize + offset as isize) as usize; + let op_str = if opcode == OpCode::Jmp { "jmp" } else { "jz " }; + writeln!(writer, "{} ({}) {}", op_str, offset, target_pc)?; + + } + OpCode::Prtc => writeln!(writer, "prtc")?, + OpCode::Prti => writeln!(writer, "prti")?, + OpCode::Prts => writeln!(writer, "prts")?, + OpCode::Halt => { + writeln!(writer, "halt")?; + break; // Stop disassembly after HALT + } + // The transmute above should prevent reaching here if OpCode is exhaustive + // _ => { + // writeln!(writer, "ERROR: Unknown opcode {}", opcode_byte)?; + // return Err(CompileError::Runtime(format!("Unknown opcode byte: {}", opcode_byte))); + // } + } + } + writer.flush()?; // Ensure buffer is written + Ok(()) +} + + +// --- AST Loader --- +struct AstLoader { + reader: R, + line_buffer: String, +} + +impl AstLoader { + fn new(reader: R) -> Self { + AstLoader { + reader, + line_buffer: String::new(), + } + } + + // Replaces read_line and rtrim + fn read_next_line(&mut self) -> Result> { + self.line_buffer.clear(); + match self.reader.read_line(&mut self.line_buffer)? { + 0 => Ok(None), // EOF + _ => Ok(Some(self.line_buffer.trim_end())), // Return trimmed line + } + } + + // Replaces load_ast (recursive part) + fn load_ast_recursive(&mut self) -> Result>> { + let line = match self.read_next_line()? { + Some(l) if !l.is_empty() && !l.starts_with(';') => l, + Some(_) => return self.load_ast_recursive(), // Skip empty lines or comments + None => return Ok(None), // End of input + }; + + let mut parts = line.splitn(2, ' '); // Split into token and the rest + let token = parts.next().ok_or_else(|| CompileError::Parse("Empty line encountered unexpectedly".to_string()))?; + let maybe_value = parts.next(); + + let node_type = node_type_from_str(token); + if node_type == NodeType::Unknown { + return Err(CompileError::Parse(format!("Unknown token '{}'", token))); + } + + // Check if it's a leaf node (has extra data on the same line) + if let Some(value_part) = maybe_value { + let trimmed_value = value_part.trim_start(); + if !trimmed_value.is_empty() { + // It's a leaf node (Identifier, String, Integer) + match node_type { + NodeType::Ident | NodeType::String | NodeType::Integer => { + Ok(Some(Tree::new_leaf(node_type, trimmed_value))) + } + _ => Err(CompileError::Parse(format!( + "Node type {:?} unexpectedly found with value '{}' on the same line", + node_type, trimmed_value + ))), + } + } else { + // It's an internal node, load children recursively + let left = self.load_ast_recursive()?; + let right = self.load_ast_recursive()?; + Ok(Some(Tree::new_node_option(node_type, left, right))) + } + } else { + // No extra data, must be an internal node with children on subsequent lines + let left = self.load_ast_recursive()?; + let right = self.load_ast_recursive()?; + Ok(Some(Tree::new_node_option(node_type, left, right))) + } + } +} + + +// --- Main Function --- +fn main() { + if let Err(e) = run() { + eprintln!("Error: {}", e); + process::exit(1); + } +} + +fn run() -> Result<()> { + let args: Vec = std::env::args().collect(); + let source_filename = args.get(1).map(String::as_str).unwrap_or(""); + let dest_filename = args.get(2).map(String::as_str).unwrap_or(""); + + // --- Setup I/O --- + // Use Box to handle both Stdin and Files + let source_reader: Box = if source_filename.is_empty() { + Box::new(BufReader::new(io::stdin())) + } else { + let file = File::open(Path::new(source_filename)) + .map_err(|e| CompileError::Io(e))?; // Convert IO error + Box::new(BufReader::new(file)) + }; + + // Use Box and BufWriter for output + let dest_writer: Box = if dest_filename.is_empty() { + Box::new(io::stdout()) + } else { + let file = File::create(Path::new(dest_filename)) + .map_err(|e| CompileError::Io(e))?; + Box::new(file) + }; + let mut buffered_writer = BufWriter::new(dest_writer); + + + // --- Load AST --- + let mut loader = AstLoader::new(source_reader); + let ast_root = loader.load_ast_recursive()?; + + // --- Code Generation --- + let mut state = CodeGenState::new(); + state.code_gen(ast_root.as_deref())?; // Pass reference + state.code_finish(); + + // --- List Code --- + list_code(&state, &mut buffered_writer)?; + + Ok(()) +} diff --git a/Task/Compiler-lexical-analyzer/Rust/compiler-lexical-analyzer.rs b/Task/Compiler-lexical-analyzer/Rust/compiler-lexical-analyzer.rs new file mode 100644 index 0000000000..5170027cd8 --- /dev/null +++ b/Task/Compiler-lexical-analyzer/Rust/compiler-lexical-analyzer.rs @@ -0,0 +1,682 @@ +use once_cell::sync::Lazy; +use std::collections::HashMap; +use std::env; +use std::fmt; +use std::fs; +use std::io::{self, Read, Write}; +use std::process; +use std::str; + +// ===================================================================================================================== +// Errors +// ===================================================================================================================== + +// Define a custom error type for cleaner error handling +#[derive(Debug)] +enum LexerError { + Io(io::Error), + Generic(String), +} + +impl fmt::Display for LexerError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LexerError::Io(e) => write!(f, "I/O Error: {}", e), + LexerError::Generic(s) => write!(f, "Lexer Error: {}", s), + } + } +} + +impl std::error::Error for LexerError {} + +// Allow easy conversion from io::Error +impl From for LexerError { + fn from(err: io::Error) -> Self { + LexerError::Io(err) + } +} + +// Allow easy conversion from String/&str +impl From for LexerError { + fn from(err: String) -> Self { + LexerError::Generic(err) + } +} +impl From<&str> for LexerError { + fn from(err: &str) -> Self { + LexerError::Generic(err.to_string()) + } +} + +type Result = std::result::Result; + +// ===================================================================================================================== +// Machinery +// ===================================================================================================================== + +fn file_to_string(path: &str) -> Result { + fs::read_to_string(path).map_err(LexerError::Io) +} + +fn string_to_file(path: &str, contents: &str) -> Result<()> { + fs::write(path, contents).map_err(LexerError::Io) +} + +// Rust version of with_IO, using closures and Result for error handling +fn with_io(source: &str, destination: &str, f: F) -> Result<()> +where + F: FnOnce(String) -> Result, +{ + let input = if source == "stdin" { + let mut buffer = String::new(); + io::stdin().read_to_string(&mut buffer)?; + buffer + } else { + file_to_string(source)? + }; + + let output = f(input)?; // Execute the processing function + + if destination == "stdout" { + print!("{}", output); // Use print! for stdout + io::stdout().flush()?; // Ensure output is flushed + } else { + string_to_file(destination, &output)?; + } + + Ok(()) +} + +// Add escaped newlines and backslashes back in for printing +fn sanitize(s: &str) -> String { + let mut result = String::with_capacity(s.len()); // Pre-allocate + for c in s.chars() { + match c { + '\n' => result.push_str("\\n"), + '\\' => result.push_str("\\\\"), + _ => result.push(c), + } + } + result +} + +// ===================================================================================================================== +// Scanner - Operates on byte slice for closer C++ char* parity +// ===================================================================================================================== +#[derive(Debug, Clone, Copy)] // Clone + Copy needed for pre_state +struct Scanner<'a> { + bytes: &'a [u8], + pos: usize, // Current byte position + line: usize, + column: usize, +} + +impl<'a> Scanner<'a> { + fn new(source: &'a str) -> Self { + Scanner { + bytes: source.as_bytes(), + pos: 0, + line: 1, + column: 1, + } + } + + // Peek at the current byte without consuming + fn peek(&self) -> Option { + self.bytes.get(self.pos).copied() + } + + // Peek at the next byte + fn peek_next(&self) -> Option { + self.bytes.get(self.pos + 1).copied() + } + + // Advance the position by one byte, updating line/column + fn advance(&mut self) { + if let Some(byte) = self.peek() { + self.pos += 1; + if byte == b'\n' { + self.line += 1; + self.column = 1; + } else { + self.column += 1; + } + } + // Don't advance past the end + } + + // Advance and return the *new* current byte + // Equivalent to C++'s next() behavior: advance then peek + fn next(&mut self) -> Option { + self.advance(); + self.peek() + } + + // Skip ASCII whitespace characters + fn skip_whitespace(&mut self) { + while let Some(byte) = self.peek() { + if byte.is_ascii_whitespace() { + self.advance(); + } else { + break; + } + } + } + + // Get the current byte slice from start_pos to current pos + fn slice(&self, start_pos: usize) -> &'a [u8] { + &self.bytes[start_pos..self.pos] + } +} + +// ===================================================================================================================== +// Tokens +// ===================================================================================================================== +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TokenName { + OpMultiply, OpDivide, OpMod, OpAdd, OpSubtract, OpNegate, + OpLess, OpLessEqual, OpGreater, OpGreaterEqual, OpEqual, OpNotEqual, + OpNot, OpAssign, OpAnd, OpOr, + LeftParen, RightParen, LeftBrace, RightBrace, Semicolon, Comma, + KeywordIf, KeywordElse, KeywordWhile, KeywordPrint, KeywordPutc, + Identifier, Integer, String, + EndOfInput, Error, +} + +// Use Display trait for string representation +impl fmt::Display for TokenName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use TokenName::*; + let s = match self { + OpMultiply => "Op_multiply", OpDivide => "Op_divide", OpMod => "Op_mod", + OpAdd => "Op_add", OpSubtract => "Op_subtract", OpNegate => "Op_negate", + OpLess => "Op_less", OpLessEqual => "Op_lessequal", OpGreater => "Op_greater", + OpGreaterEqual => "Op_greaterequal", OpEqual => "Op_equal", OpNotEqual => "Op_notequal", + OpNot => "Op_not", OpAssign => "Op_assign", OpAnd => "Op_and", OpOr => "Op_or", + LeftParen => "LeftParen", RightParen => "RightParen", LeftBrace => "LeftBrace", + RightBrace => "RightBrace", Semicolon => "Semicolon", Comma => "Comma", + KeywordIf => "Keyword_if", KeywordElse => "Keyword_else", KeywordWhile => "Keyword_while", + KeywordPrint => "Keyword_print", KeywordPutc => "Keyword_putc", + Identifier => "Identifier", Integer => "Integer", String => "String", + EndOfInput => "End_of_input", Error => "Error", + }; + write!(f, "{}", s) + } +} + +// Rust enum for token values (replaces std::variant) +#[derive(Debug, Clone, PartialEq)] +enum TokenVal { + Int(i32), + String(String), + None, // For tokens without a specific value +} + +#[derive(Debug, Clone)] +struct Token { + name: TokenName, + value: TokenVal, + line: usize, + column: usize, +} + +// Use Display trait for formatted token output +impl fmt::Display for Token { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:<2} {:<2} ", self.line, self.column)?; // Use Rust formatting for width + match self.name { + TokenName::Identifier => { + if let TokenVal::String(s) = &self.value { + write!(f, "{:<18}{}", self.name, s) // Left align with width + } else { + write!(f, "{:<18}", self.name) // Should not happen + } + } + TokenName::Integer => { + if let TokenVal::Int(i) = &self.value { + write!(f, "{:<18}{}", self.name, i) + } else { + write!(f, "{:<18}", self.name) + } + } + TokenName::String => { + if let TokenVal::String(s) = &self.value { + write!(f, "{:<18}\"{}\"", self.name, sanitize(s)) + } else { + write!(f, "{:<18}", self.name) + } + } + TokenName::Error => { + if let TokenVal::String(s) = &self.value { + // Error message might be multi-line, handle indentation carefully + let lines: Vec<&str> = s.lines().collect(); + if lines.is_empty() { + write!(f, "{}", self.name) + } else { + write!(f, "{:<18}{}", self.name, lines[0])?; + for line in lines.iter().skip(1) { + write!(f, "\n{:<28}{}", "", line)?; // Indent subsequent lines + } + Ok(()) // Return Ok(()) explicitly as write! doesn't cover all paths + } + } else { + write!(f, "{}", self.name) // Error without details + } + } + TokenName::EndOfInput => write!(f, "{}", self.name), + // Default for simple tokens + _ => write!(f, "{}", self.name), + } + } +} + + +// ===================================================================================================================== +// Lexer +// ===================================================================================================================== + +// Lazy static initialization for the keywords map +static KEYWORDS: Lazy> = Lazy::new(|| { + let mut m = HashMap::new(); + m.insert("else".to_string(), TokenName::KeywordElse); + m.insert("if".to_string(), TokenName::KeywordIf); + m.insert("print".to_string(), TokenName::KeywordPrint); + m.insert("putc".to_string(), TokenName::KeywordPutc); + m.insert("while".to_string(), TokenName::KeywordWhile); + m +}); + + +struct Lexer<'a> { + s: Scanner<'a>, + source: &'a str, // Keep original source for error slicing if needed + // pre_state is implicitly captured before each token attempt +} + +impl<'a> Lexer<'a> { + fn new(source: &'a str) -> Self { + Lexer { + s: Scanner::new(source), + source, // Store the source string slice + } + } + + // Helper to create a token with current pre-state line/column + fn make_token(&self, name: TokenName, value: TokenVal, line: usize, column: usize) -> Token { + Token { name, value, line, column } + } + + // Helper to create an error token + fn error_token(&mut self, msg: String, code_snippet: &str, line: usize, column: usize) -> Token { + let full_msg = format!("{}\n{:>28}({}, {}): {}", + msg, "", line, column, code_snippet); + + // Ensure we advance past the problematic character(s) if possible + // In many cases, advance() might have already happened within the failing logic. + // If peek is not None, we might advance once more to avoid infinite loops on bad chars. + if self.s.peek().is_some() { + // Be cautious here. C++ version advanced unconditionally. + // Let's only advance if the error didn't consume the char. + // self.s.advance(); // Maybe remove this, depends on exact error logic + } + + self.make_token(TokenName::Error, TokenVal::String(full_msg), line, column) + } + + // Helper for simple single-character tokens + fn simply(&mut self, name: TokenName, line: usize, column: usize) -> Token { + self.s.advance(); + self.make_token(name, TokenVal::None, line, column) + } + + // Helper for tokens like &&, || + fn expect(&mut self, expected: u8, name: TokenName, line: usize, column: usize, start_pos: usize) -> Token { + if self.s.next() == Some(expected) { + self.s.advance(); // Consume the second character + self.make_token(name, TokenVal::None, line, column) + } else { + // Get the single character that caused the error + let snippet = str::from_utf8(&self.s.bytes[start_pos..self.s.pos]) + .unwrap_or(""); // Use slice up to current pos + let current_char = self.s.peek().map_or('?', |b| b as char); // Use peek for error char + self.error_token( + format!("Unrecognized character '{}' after '{}'", current_char, self.s.bytes[start_pos] as char), + snippet, + line, // Error occurs at the original line/col + column, + ) + } + } + + // Helper for tokens like <=, >=, ==, != + fn follow(&mut self, expected: u8, ifyes: TokenName, ifno: TokenName, line: usize, column: usize) -> Token { + if self.s.peek_next() == Some(expected) { + self.s.advance(); // Consume the first char + self.s.advance(); // Consume the second char '=' + self.make_token(ifyes, TokenVal::None, line, column) + } else { + self.s.advance(); // Consume just the first char + self.make_token(ifno, TokenVal::None, line, column) + } + } + + // Handles / or /* ... */ comments + fn divide_or_comment(&mut self, line: usize, column: usize, start_pos: usize) -> Token { + if self.s.peek_next() == Some(b'*') { + // Start of a block comment + self.s.advance(); // Consume '/' + self.s.advance(); // Consume '*' + + loop { + match self.s.peek() { + Some(b'*') => { + if self.s.peek_next() == Some(b'/') { + self.s.advance(); // Consume '*' + self.s.advance(); // Consume '/' + return self.next_token(); // Return the *next* token after comment + } else { + self.s.advance(); // Consume '*' but it wasn't end of comment + } + } + Some(_) => { + self.s.advance(); // Consume character inside comment + } + None => { + // Reached EOF inside comment + let snippet = str::from_utf8(&self.s.bytes[start_pos..self.s.pos]).unwrap_or("/*..."); + return self.error_token( + "End-of-file in comment. Closing '*/' not found.".to_string(), + snippet, + line, // Error reported at comment start + column, + ); + } + } + } + } else { + // Just a division operator + self.s.advance(); // Consume '/' + self.make_token(TokenName::OpDivide, TokenVal::None, line, column) + } + } + + // Handles 'c' character literals -> stored as Integer token + fn char_lit(&mut self, line: usize, column: usize, start_pos: usize) -> Token { + self.s.advance(); // Consume opening ' + + let char_val = match self.s.peek() { + None => return self.error_token("End-of-file in char literal.".to_string(), "'", line, column), + Some(b'\'') => return self.error_token("Empty character constant.".to_string(), "''", line, column), + Some(b'\\') => { // Escape sequence + self.s.advance(); // Consume '\' + match self.s.peek() { + Some(b'n') => { self.s.advance(); b'\n' } + Some(b'\\') => { self.s.advance(); b'\\' } + Some(c) => { + let snippet = format!("'\\{}...", c as char); + // Advance past the unknown escape char before reporting error + self.s.advance(); + return self.error_token(format!("Unknown escape sequence \\{}", c as char), &snippet, line, column); + } + None => return self.error_token("End-of-file after escape in char literal.".to_string(), "'\\", line, column), + } + } + Some(byte) => { // Normal character + self.s.advance(); + byte + } + }; + + // Check for closing quote + if self.s.peek() == Some(b'\'') { + self.s.advance(); // Consume closing ' + self.make_token(TokenName::Integer, TokenVal::Int(char_val as i32), line, column) + } else { + // Find the extent of the invalid literal for the error message + let mut end_pos = self.s.pos; + while let Some(b) = self.s.bytes.get(end_pos) { + if *b == b'\'' || *b == b'\n' || end_pos > start_pos + 10 { // Limit snippet size + break; + } + end_pos += 1; + } + // Consume until the closing quote or newline to avoid cascading errors + while let Some(b) = self.s.peek() { + if b == b'\'' { self.s.advance(); break; } + if b == b'\n' { break; } // Stop at newline + self.s.advance(); + } + + let snippet = str::from_utf8(&self.s.bytes[start_pos..end_pos.min(self.s.bytes.len())]) + .unwrap_or(""); + self.error_token("Multi-character constant or missing closing quote.".to_string(), snippet, line, column) + } + } + + + // Handles "..." string literals + fn string_lit(&mut self, line: usize, column: usize, start_pos: usize) -> Token { + self.s.advance(); // Consume opening " + let mut content: Vec = Vec::new(); + + loop { + match self.s.peek() { + None => { + let snippet = str::from_utf8(&self.s.bytes[start_pos..self.s.pos]).unwrap_or("\"..."); + return self.error_token("End-of-file while scanning string literal. Closing '\"' not found.".to_string(), snippet, line, column); + } + Some(b'"') => { + self.s.advance(); // Consume closing " + // Attempt to convert collected bytes to UTF-8 String + match String::from_utf8(content) { + Ok(s) => return self.make_token(TokenName::String, TokenVal::String(s), line, column), + Err(e) => { + let snippet = str::from_utf8(&self.s.bytes[start_pos..self.s.pos]).unwrap_or(""); + return self.error_token(format!("Invalid UTF-8 sequence in string literal: {}", e), snippet, line, column); + } + } + } + Some(b'\n') => { + let snippet = str::from_utf8(&self.s.bytes[start_pos..self.s.pos]).unwrap_or("\"..."); + // Don't consume newline, error points before it + return self.error_token("End-of-line while scanning string literal. Closing '\"' not found.".to_string(), snippet, self.s.line, self.s.column); // Report error at current line/col + } + Some(b'\\') => { // Escape sequence + self.s.advance(); // Consume '\' + match self.s.peek() { + Some(b'n') => { self.s.advance(); content.push(b'\n'); } + Some(b'\\') => { self.s.advance(); content.push(b'\\'); } + Some(c) => { + let snippet = format!("...\\{}...", c as char); + // Consume the unknown escape char before reporting error + self.s.advance(); + return self.error_token(format!("Unknown escape sequence \\{}", c as char), &snippet, self.s.line, self.s.column); // Use current line/col + } + None => { + let snippet = str::from_utf8(&self.s.bytes[start_pos..self.s.pos]).unwrap_or("\"...\\"); + return self.error_token("End-of-file after escape in string literal.".to_string(), snippet, line, column); + } + } + } + Some(byte) => { // Normal character + content.push(byte); + self.s.advance(); + } + } + } + } + + // Helper predicate functions (using u8 methods) + #[inline] fn is_id_start(c: u8) -> bool { c.is_ascii_alphabetic() || c == b'_' } + #[inline] fn is_id_end(c: u8) -> bool { c.is_ascii_alphanumeric() || c == b'_' } + #[inline] fn is_digit(c: u8) -> bool { c.is_ascii_digit() } + + // Handles identifiers and keywords + fn identifier(&mut self, line: usize, column: usize, start_pos: usize) -> Token { + while let Some(byte) = self.s.peek() { + if Self::is_id_end(byte) { + self.s.advance(); + } else { + break; + } + } + let ident_bytes = self.s.slice(start_pos); + // Identifiers must be valid UTF-8 in Rust + match str::from_utf8(ident_bytes) { + Ok(ident_str) => { + // Check if it's a keyword + if let Some(keyword_token) = KEYWORDS.get(ident_str) { + self.make_token(*keyword_token, TokenVal::None, line, column) + } else { + self.make_token(TokenName::Identifier, TokenVal::String(ident_str.to_string()), line, column) + } + } + Err(_) => { + // This shouldn't happen if is_id_end checks ASCII, but handle defensively + self.error_token("Invalid UTF-8 sequence in identifier.".to_string(), "", line, column) + } + } + } + + + // Handles integer literals + fn integer_lit(&mut self, line: usize, column: usize, start_pos: usize) -> Token { + while let Some(byte) = self.s.peek() { + if Self::is_digit(byte) { + self.s.advance(); + } else { + break; + } + } + + // Check if it's followed by an identifier character (invalid number) + if let Some(byte) = self.s.peek() { + if Self::is_id_start(byte) { + // Consume the invalid part to show in error + while let Some(b) = self.s.peek() { + if Self::is_id_end(b) { self.s.advance(); } else { break; } + } + let snippet = str::from_utf8(self.s.slice(start_pos)).unwrap_or(""); + return self.error_token("Invalid number. Contains non-numeric characters.".to_string(), snippet, line, column); + } + } + + + let num_bytes = self.s.slice(start_pos); + match str::from_utf8(num_bytes) { + Ok(num_str) => { + match num_str.parse::() { + Ok(n) => self.make_token(TokenName::Integer, TokenVal::Int(n), line, column), + Err(e) => { + // Could be overflow or other parse error + let snippet = str::from_utf8(num_bytes).unwrap_or(""); + let msg = if e.kind() == &std::num::IntErrorKind::PosOverflow || e.kind() == &std::num::IntErrorKind::NegOverflow { + "Number exceeds maximum value.".to_string() + } else { + format!("Invalid integer literal: {}", e) + }; + self.error_token(msg, snippet, line, column) + } + } + } + Err(_) => { + // Should not happen for digits, but handle defensively + self.error_token("Invalid UTF-8 sequence in number.".to_string(), "", line, column) + } + } + } + + // Get the next token from the input stream + pub fn next_token(&mut self) -> Token { + self.s.skip_whitespace(); + + // Capture state *before* processing the token + let pre_line = self.s.line; + let pre_column = self.s.column; + let start_pos = self.s.pos; // Start byte position of the token + + // Use peek() to decide what kind of token comes next + match self.s.peek() { + Some(b'*') => self.simply(TokenName::OpMultiply, pre_line, pre_column), + Some(b'%') => self.simply(TokenName::OpMod, pre_line, pre_column), + Some(b'+') => self.simply(TokenName::OpAdd, pre_line, pre_column), + Some(b'-') => self.simply(TokenName::OpSubtract, pre_line, pre_column), + Some(b'{') => self.simply(TokenName::LeftBrace, pre_line, pre_column), + Some(b'}') => self.simply(TokenName::RightBrace, pre_line, pre_column), + Some(b'(') => self.simply(TokenName::LeftParen, pre_line, pre_column), + Some(b')') => self.simply(TokenName::RightParen, pre_line, pre_column), + Some(b';') => self.simply(TokenName::Semicolon, pre_line, pre_column), + Some(b',') => self.simply(TokenName::Comma, pre_line, pre_column), + + Some(b'&') => self.expect(b'&', TokenName::OpAnd, pre_line, pre_column, start_pos), + Some(b'|') => self.expect(b'|', TokenName::OpOr, pre_line, pre_column, start_pos), + + Some(b'<') => self.follow(b'=', TokenName::OpLessEqual, TokenName::OpLess, pre_line, pre_column), + Some(b'>') => self.follow(b'=', TokenName::OpGreaterEqual, TokenName::OpGreater, pre_line, pre_column), + Some(b'=') => self.follow(b'=', TokenName::OpEqual, TokenName::OpAssign, pre_line, pre_column), + Some(b'!') => self.follow(b'=', TokenName::OpNotEqual, TokenName::OpNot, pre_line, pre_column), + + Some(b'/') => self.divide_or_comment(pre_line, pre_column, start_pos), + Some(b'\'') => self.char_lit(pre_line, pre_column, start_pos), + Some(b'"') => self.string_lit(pre_line, pre_column, start_pos), + + Some(c) if Self::is_id_start(c) => self.identifier(pre_line, pre_column, start_pos), + Some(c) if Self::is_digit(c) => self.integer_lit(pre_line, pre_column, start_pos), + + Some(c) => { + // Unrecognized character + let snippet = str::from_utf8(&self.s.bytes[start_pos ..= start_pos]).unwrap_or("?"); // Just the char + self.s.advance(); // Consume the bad character + self.error_token(format!("Unrecognized character '{}'", c as char), snippet, pre_line, pre_column) + } + + None => self.make_token(TokenName::EndOfInput, TokenVal::None, pre_line, pre_column), + } + } + + // Check if there are more characters (excluding EOF) + pub fn has_more(&self) -> bool { + self.s.peek().is_some() + } +} + +// ===================================================================================================================== +// Main Function +// ===================================================================================================================== +fn run_lexer(input: String) -> Result { + let mut lexer = Lexer::new(&input); // Pass input by reference + let mut output = String::new(); + + output.push_str("Location Token name Value\n"); + output.push_str("--------------------------------------\n"); + + let mut token = lexer.next_token(); + loop { + output.push_str(&format!("{}\n", token)); // Use the Display impl for Token + + if token.name == TokenName::EndOfInput || token.name == TokenName::Error { + // If it's an error token, we might stop or continue depending on desired behavior. + // This version stops on the first error or EOF. + if token.name == TokenName::Error { + // Optionally, return an error instead of just stopping the output string + // return Err(LexerError::Generic(format!("Lexing failed at line {}, column {}", token.line, token.column))); + } + break; + } + + token = lexer.next_token(); + } + + Ok(output) +} + +fn main() { + let args: Vec = env::args().collect(); + let in_path = args.get(1).map_or("stdin", |s| s.as_str()); + let out_path = args.get(2).map_or("stdout", |s| s.as_str()); + + if let Err(e) = with_io(in_path, out_path, run_lexer) { + eprintln!("Error: {}", e); + process::exit(1); + } +} diff --git a/Task/Compiler-syntax-analyzer/FreeBASIC/compiler-syntax-analyzer.basic b/Task/Compiler-syntax-analyzer/FreeBASIC/compiler-syntax-analyzer.basic new file mode 100644 index 0000000000..9775c3616a --- /dev/null +++ b/Task/Compiler-syntax-analyzer/FreeBASIC/compiler-syntax-analyzer.basic @@ -0,0 +1,370 @@ +#define BUFFER_SIZE 4096 + +' Token constants +Enum TokensCtes + tk_EOI, tk_Mul, tk_Div, tk_Mod, tk_Add, tk_Sub, tk_Negate, tk_Not, tk_Lss, tk_Leq, tk_Gtr + tk_Geq, tk_Eql, tk_Neq, tk_Assign, tk_And, tk_Or, tk_If, tk_Else, tk_While, tk_Print + tk_Putc, tk_Lparen, tk_Rparen, tk_Lbrace, tk_Rbrace, tk_Semi, tk_Comma, tk_Ident + tk_Integer, tk_String +End Enum + +' Node types +Enum NodeTypes + nd_Ident, nd_String, nd_Integer, nd_Sequence, nd_If, nd_Prtc, nd_Prts, nd_Prti, nd_While + nd_Assign, nd_Negate, nd_Not, nd_Mul, nd_Div, nd_Mod, nd_Add, nd_Sub, nd_Lss, nd_Leq + nd_Gtr, nd_Geq, nd_Eql, nd_Neq, nd_And, nd_Or +End Enum + +' Token info structure +Type TokenInfo + nombre As String + rightAssoc As Boolean + isBinary As Boolean + isUnary As Boolean + precedence As Integer + nodeType As Integer + Declare Constructor() + Declare Constructor(n As String, ra As Boolean, ib As Boolean, iu As Boolean, p As Integer, nt As Integer) +End Type + +Constructor TokenInfo() + nombre = "" + rightAssoc = False + isBinary = False + isUnary = False + precedence = 0 + nodeType = 0 +End Constructor + +Constructor TokenInfo(n As String, ra As Boolean, ib As Boolean, iu As Boolean, p As Integer, nt As Integer) + nombre = n + rightAssoc = ra + isBinary = ib + isUnary = iu + precedence = p + nodeType = nt +End Constructor + +' Node structure +Type Node + nodeType As Integer + izda As Node Ptr + dcha As Node Ptr + value As String +End Type + +' Global variables +Dim Shared As Integer ff, errLine, errCol, tok +Dim Shared As String tokText, tokOther +Dim Shared As TokenInfo tokens(30) + +Declare Function ParseExpr(p As Integer) As Node Ptr + +' Initialize token info +Sub InitTokens() + tokens(tk_EOI) = TokenInfo("EOI", False, False, False, -1, -1) + tokens(tk_Mul) = TokenInfo("*", False, True, False, 13, nd_Mul) + tokens(tk_Div) = TokenInfo("/", False, True, False, 13, nd_Div) + tokens(tk_Mod) = TokenInfo("%", False, True, False, 13, nd_Mod) + tokens(tk_Add) = TokenInfo("+", False, True, False, 12, nd_Add) + tokens(tk_Sub) = TokenInfo("-", False, True, False, 12, nd_Sub) + tokens(tk_Negate) = TokenInfo("-", False, False, True, 14, nd_Negate) + tokens(tk_Not) = TokenInfo("!", False, False, True, 14, nd_Not) + tokens(tk_Lss) = TokenInfo("<", False, True, False, 10, nd_Lss) + tokens(tk_Leq) = TokenInfo("<=", False, True, False, 10, nd_Leq) + tokens(tk_Gtr) = TokenInfo(">", False, True, False, 10, nd_Gtr) + tokens(tk_Geq) = TokenInfo(">=", False, True, False, 10, nd_Geq) + tokens(tk_Eql) = TokenInfo("==", False, True, False, 9, nd_Eql) + tokens(tk_Neq) = TokenInfo("!=", False, True, False, 9, nd_Neq) + tokens(tk_Assign) = TokenInfo("=", False, False, False, -1, nd_Assign) + tokens(tk_And) = TokenInfo("&&", False, True, False, 5, nd_And) + tokens(tk_Or) = TokenInfo("||", False, True, False, 4, nd_Or) + tokens(tk_If) = TokenInfo("if", False, False, False, -1, nd_If) + tokens(tk_Else) = TokenInfo("else", False, False, False, -1, -1) + tokens(tk_While) = TokenInfo("while", False, False, False, -1, nd_While) + tokens(tk_Print) = TokenInfo("print", False, False, False, -1, -1) + tokens(tk_Putc) = TokenInfo("putc", False, False, False, -1, -1) + tokens(tk_Lparen) = TokenInfo("(", False, False, False, -1, -1) + tokens(tk_Rparen) = TokenInfo(")", False, False, False, -1, -1) + tokens(tk_Lbrace) = TokenInfo("{", False, False, False, -1, -1) + tokens(tk_Rbrace) = TokenInfo("}", False, False, False, -1, -1) + tokens(tk_Semi) = TokenInfo(";", False, False, False, -1, -1) + tokens(tk_Comma) = TokenInfo(",", False, False, False, -1, -1) + tokens(tk_Ident) = TokenInfo("Ident", False, False, False, -1, nd_Ident) + tokens(tk_Integer) = TokenInfo("Integer", False, False, False, -1, nd_Integer) + tokens(tk_String) = TokenInfo("String", False, False, False, -1, nd_String) +End Sub + +' show error and exit +Sub ShowError(msg As String) + Print "(" & errLine & ", " & errCol & ") " & msg + End 1 +End Sub + +' Get next token +Sub GetToken() + Static As String linea + If Eof(ff) Then + tok = tk_EOI + Exit Sub + End If + Line Input #ff, linea + If Len(linea) = 0 Then ShowError("empty line") + + Dim As Integer numParts = 0 + Dim As String parts(0 To 3) + Dim As String currentPart = "" + Dim As Boolean inQuotes = False + + For i As Integer = 1 To Len(linea) + Dim As String c = Mid(linea, i, 1) + If c = """" Then + inQuotes = Not inQuotes + currentPart &= c + Elseif (Cbool((c = " ") Or (c = Chr(9))) Andalso (inQuotes = False)) Then + If Len(currentPart) > 0 Then + parts(numParts) = currentPart + numParts += 1 + currentPart = "" + End If + Else + currentPart &= c + End If + Next + If Len(currentPart) > 0 Then + parts(numParts) = currentPart + numParts += 1 + End If + + errLine = Valint(parts(0)) + errCol = Valint(parts(1)) + tokText = parts(2) + tok = -1 + + Select Case tokText + Case "End_of_input": tok = tk_EOI + Case "Op_multiply": tok = tk_Mul + Case "Op_divide": tok = tk_Div + Case "Op_mod": tok = tk_Mod + Case "Op_add": tok = tk_Add + Case "Op_subtract": tok = tk_Sub + Case "Op_negate": tok = tk_Negate + Case "Op_not": tok = tk_Not + Case "Op_less": tok = tk_Lss + Case "Op_lessequal": tok = tk_Leq + Case "Op_greater": tok = tk_Gtr + Case "Op_greaterequal":tok = tk_Geq + Case "Op_equal": tok = tk_Eql + Case "Op_notequal": tok = tk_Neq + Case "Op_assign": tok = tk_Assign + Case "Op_and": tok = tk_And + Case "Op_or": tok = tk_Or + Case "Keyword_if": tok = tk_If + Case "Keyword_else": tok = tk_Else + Case "Keyword_while": tok = tk_While + Case "Keyword_print": tok = tk_Print + Case "Keyword_putc": tok = tk_Putc + Case "LeftParen": tok = tk_Lparen + Case "RightParen": tok = tk_Rparen + Case "LeftBrace": tok = tk_Lbrace + Case "RightBrace": tok = tk_Rbrace + Case "Semicolon": tok = tk_Semi + Case "Comma": tok = tk_Comma + Case "Identifier": tok = tk_Ident + Case "Integer": tok = tk_Integer + Case "String": tok = tk_String + End Select + + If tok = -1 Then ShowError("Unknown token " & tokText) + If tok = tk_Integer Or tok = tk_Ident Or tok = tk_String Then + tokOther = Iif(numParts >= 4, parts(3), "") + End If +End Sub + +' Create nodes +Function MakeNode(nodeType As Integer, izda As Node Ptr = 0, dcha As Node Ptr = 0) As Node Ptr + Dim As Node Ptr n = New Node + With *n + .nodeType = nodeType + .izda = izda + .dcha = dcha + .value = "" + End With + + Return n +End Function + +Function MakeLeaf(nodeType As Integer, value As String) As Node Ptr + Dim As Node Ptr n = New Node + n->nodeType = nodeType + n->izda = 0 + n->dcha = 0 + n->value = value + + Return n +End Function + +Sub Expect(msg As String, s As Integer) + If tok = s Then + GetToken() + Else + ShowError(msg & ": Expecting '" & tokens(s).nombre & "', found '" & tokens(tok).nombre & "'") + End If +End Sub + +' Main parsing functions +Function ParenExpr() As Node Ptr + Expect("paren_expr", tk_Lparen) + Dim As Node Ptr node = ParseExpr(0) + Expect("paren_expr", tk_Rparen) + + Return node +End Function + +Function ParseExpr(p As Integer) As Node Ptr + Dim As Node Ptr x = 0, node + Dim As Integer op, q + + Select Case tok + Case tk_Lparen + x = ParenExpr() + Case tk_Sub, tk_Add + op = Iif(tok = tk_Sub, tk_Negate, tk_Add) + GetToken() + node = ParseExpr(tokens(tk_Negate).precedence) + x = Iif(op = tk_Negate, MakeNode(nd_Negate, node), node) + Case tk_Not + GetToken() + x = MakeNode(nd_Not, ParseExpr(tokens(tk_Not).precedence)) + Case tk_Ident + x = MakeLeaf(nd_Ident, tokOther) + GetToken() + Case tk_Integer + x = MakeLeaf(nd_Integer, tokOther) + GetToken() + Case Else + ShowError("Expecting a primary, found: " & tokens(tok).nombre) + End Select + + While tokens(tok).isBinary Andalso tokens(tok).precedence >= p + op = tok + GetToken() + q = tokens(op).precedence + If Not tokens(op).rightAssoc Then q += 1 + node = ParseExpr(q) + x = MakeNode(tokens(op).nodeType, x, node) + Wend + + Return x +End Function + +Function ParseStmt() As Node Ptr + Dim As Node Ptr t = 0, e + + Select Case tok + Case tk_If + GetToken() + e = ParenExpr() + Dim As Node Ptr s = ParseStmt() + Dim As Node Ptr s2 = 0 + If tok = tk_Else Then + GetToken() + s2 = ParseStmt() + End If + t = MakeNode(nd_If, e, MakeNode(nd_If, s, s2)) + Case tk_Putc + GetToken() + e = ParenExpr() + t = MakeNode(nd_Prtc, e) + Expect("Putc", tk_Semi) + Case tk_Print + GetToken() + Expect("Print", tk_Lparen) + Do + If tok = tk_String Then + e = MakeNode(nd_Prts, MakeLeaf(nd_String, tokOther)) + GetToken() + Else + e = MakeNode(nd_Prti, ParseExpr(0)) + End If + t = MakeNode(nd_Sequence, t, e) + If tok <> tk_Comma Then Exit Do + GetToken() + Loop + Expect("Print", tk_Rparen) + Expect("Print", tk_Semi) + Case tk_Semi + GetToken() + Case tk_Ident + Dim As Node Ptr v = MakeLeaf(nd_Ident, tokOther) + GetToken() + Expect("assign", tk_Assign) + e = ParseExpr(0) + t = MakeNode(nd_Assign, v, e) + Expect("assign", tk_Semi) + Case tk_While + GetToken() + e = ParenExpr() + Dim As Node Ptr s = ParseStmt() + t = MakeNode(nd_While, e, s) + Case tk_Lbrace + GetToken() + While tok <> tk_Rbrace Andalso tok <> tk_EOI + t = MakeNode(nd_Sequence, t, ParseStmt()) + Wend + Expect("Lbrace", tk_Rbrace) + Case tk_EOI + ' Do nothing + Case Else + ShowError("Expecting start of statement, found: " & tokens(tok).nombre) + End Select + + Return t +End Function + +Function Parse() As Node Ptr + Dim As Node Ptr tree = 0 + + GetToken() + While tok <> tk_EOI + tree = MakeNode(nd_Sequence, tree, ParseStmt()) + Wend + + Return tree +End Function + +Sub PrintAST(t As Node Ptr) + Dim As String displayNodes(24) = { _ + "Identifier","String","Integer","Sequence","If","Prtc", _ + "Prts","Prti","While","Assign","Negate","Not","Multiply","Divide","Mod", _ + "Add","Subtract","Less","LessEqual","Greater","GreaterEqual","Equal", _ + "NotEqual","And","Or" } + + If t = 0 Then + Print ";" + Else + Print Left(displayNodes(t->nodeType) & Space(14), 14); + Select Case t->nodeType + Case nd_Ident, nd_Integer, nd_String + Print t->value + Case Else + Print + PrintAST(t->izda) + PrintAST(t->dcha) + End Select + End If +End Sub + +' Main program +InitTokens() +If Command(1) <> "" Then + ff = Freefile + Open Command(1) For Input Access Read As #ff Len = BUFFER_SIZE +Else + ff = 1 ' stdin +End If + +Dim As Node Ptr ast = Parse() +PrintAST(ast) + +Sleep diff --git a/Task/Compiler-syntax-analyzer/M2000-Interpreter/compiler-syntax-analyzer.m2000 b/Task/Compiler-syntax-analyzer/M2000-Interpreter/compiler-syntax-analyzer.m2000 index 388b820e8b..1b0a6c5166 100644 --- a/Task/Compiler-syntax-analyzer/M2000-Interpreter/compiler-syntax-analyzer.m2000 +++ b/Task/Compiler-syntax-analyzer/M2000-Interpreter/compiler-syntax-analyzer.m2000 @@ -97,7 +97,7 @@ Module syntax_analyzer(b$){ sub stmt(&op) local t=(,) if op=Identifier then - t=(line$) + t=(line$,) getone(&op) expected(Op_assign) getone(&op) diff --git a/Task/Compiler-syntax-analyzer/Rust/compiler-syntax-analyzer.rs b/Task/Compiler-syntax-analyzer/Rust/compiler-syntax-analyzer.rs new file mode 100644 index 0000000000..d50b2f14a7 --- /dev/null +++ b/Task/Compiler-syntax-analyzer/Rust/compiler-syntax-analyzer.rs @@ -0,0 +1,659 @@ +// src/main.rs + +use std::env; +use std::fs::File; +use std::io::{self, prelude::*, BufReader, BufWriter, Lines}; +use std::process::exit; +use std::collections::HashMap; // For potentially faster token lookup if needed + +// --- Enums --- + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] // Added Hash for HashMap key +pub enum TokenType { + Eoi, Mul, Div, Mod, Add, Sub, Negate, Not, Lss, Leq, Gtr, + Geq, Eql, Neq, Assign, And, Or, If, Else, While, Print, + Putc, Lparen, Rparen, Lbrace, Rbrace, Semi, Comma, Ident, + Integer, String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NodeType { + Ident, String, Integer, Sequence, If, Prtc, Prts, Prti, While, + Assign, Negate, Not, Mul, Div, Mod, Add, Sub, Lss, Leq, + Gtr, Geq, Eql, Neq, And, Or, +} + +// --- Structs --- + +#[derive(Debug, Clone)] +pub struct Token { + tok_type: TokenType, + err_ln: usize, + err_col: usize, + text: Option, // Use Option for optional text +} + +#[derive(Debug, Clone)] +pub struct AstNode { + node_type: NodeType, + // Use Option> for optional, heap-allocated children + left: Option>, + right: Option>, + // Use Option for optional value (ident, literal) + value: Option, +} + +#[derive(Debug)] +pub struct TokenAttributes { + text: &'static str, + enum_text: &'static str, + tok_type: TokenType, + right_associative: bool, + is_binary: bool, + is_unary: bool, + precedence: Option, // Use Option for precedence (-1 in C) + node_type: Option, // Use Option for node type (-1 in C) +} + +// --- Static Data --- + +// Use 'static lifetime for compile-time constants +// Order MUST match TokenType enum definition +const TOKEN_ATTRIBUTES: &[TokenAttributes] = &[ + TokenAttributes { text: "EOI", enum_text: "End_of_input", tok_type: TokenType::Eoi, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "*", enum_text: "Op_multiply", tok_type: TokenType::Mul, right_associative: false, is_binary: true, is_unary: false, precedence: Some(13), node_type: Some(NodeType::Mul) }, + TokenAttributes { text: "/", enum_text: "Op_divide", tok_type: TokenType::Div, right_associative: false, is_binary: true, is_unary: false, precedence: Some(13), node_type: Some(NodeType::Div) }, + TokenAttributes { text: "%", enum_text: "Op_mod", tok_type: TokenType::Mod, right_associative: false, is_binary: true, is_unary: false, precedence: Some(13), node_type: Some(NodeType::Mod) }, + TokenAttributes { text: "+", enum_text: "Op_add", tok_type: TokenType::Add, right_associative: false, is_binary: true, is_unary: false, precedence: Some(12), node_type: Some(NodeType::Add) }, + TokenAttributes { text: "-", enum_text: "Op_subtract", tok_type: TokenType::Sub, right_associative: false, is_binary: true, is_unary: false, precedence: Some(12), node_type: Some(NodeType::Sub) }, + TokenAttributes { text: "-", enum_text: "Op_negate", tok_type: TokenType::Negate, right_associative: false, is_binary: false, is_unary: true, precedence: Some(14), node_type: Some(NodeType::Negate) }, // NOTE: C code listed Sub/Add precedence here, but Negate makes more sense + TokenAttributes { text: "!", enum_text: "Op_not", tok_type: TokenType::Not, right_associative: false, is_binary: false, is_unary: true, precedence: Some(14), node_type: Some(NodeType::Not) }, + TokenAttributes { text: "<", enum_text: "Op_less", tok_type: TokenType::Lss, right_associative: false, is_binary: true, is_unary: false, precedence: Some(10), node_type: Some(NodeType::Lss) }, + TokenAttributes { text: "<=", enum_text: "Op_lessequal", tok_type: TokenType::Leq, right_associative: false, is_binary: true, is_unary: false, precedence: Some(10), node_type: Some(NodeType::Leq) }, + TokenAttributes { text: ">", enum_text: "Op_greater", tok_type: TokenType::Gtr, right_associative: false, is_binary: true, is_unary: false, precedence: Some(10), node_type: Some(NodeType::Gtr) }, + TokenAttributes { text: ">=", enum_text: "Op_greaterequal", tok_type: TokenType::Geq, right_associative: false, is_binary: true, is_unary: false, precedence: Some(10), node_type: Some(NodeType::Geq) }, + TokenAttributes { text: "==", enum_text: "Op_equal", tok_type: TokenType::Eql, right_associative: false, is_binary: true, is_unary: false, precedence: Some(9), node_type: Some(NodeType::Eql) }, + TokenAttributes { text: "!=", enum_text: "Op_notequal", tok_type: TokenType::Neq, right_associative: false, is_binary: true, is_unary: false, precedence: Some(9), node_type: Some(NodeType::Neq) }, + TokenAttributes { text: "=", enum_text: "Op_assign", tok_type: TokenType::Assign, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: Some(NodeType::Assign) }, // Assignment is special, not a standard binary op in expr parsing + TokenAttributes { text: "&&", enum_text: "Op_and", tok_type: TokenType::And, right_associative: false, is_binary: true, is_unary: false, precedence: Some(5), node_type: Some(NodeType::And) }, + TokenAttributes { text: "||", enum_text: "Op_or", tok_type: TokenType::Or, right_associative: false, is_binary: true, is_unary: false, precedence: Some(4), node_type: Some(NodeType::Or) }, + TokenAttributes { text: "if", enum_text: "Keyword_if", tok_type: TokenType::If, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: Some(NodeType::If) }, + TokenAttributes { text: "else", enum_text: "Keyword_else", tok_type: TokenType::Else, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "while", enum_text: "Keyword_while", tok_type: TokenType::While, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: Some(NodeType::While) }, + TokenAttributes { text: "print", enum_text: "Keyword_print", tok_type: TokenType::Print, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "putc", enum_text: "Keyword_putc", tok_type: TokenType::Putc, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "(", enum_text: "LeftParen", tok_type: TokenType::Lparen, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: ")", enum_text: "RightParen", tok_type: TokenType::Rparen, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "{", enum_text: "LeftBrace", tok_type: TokenType::Lbrace, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "}", enum_text: "RightBrace", tok_type: TokenType::Rbrace, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: ";", enum_text: "Semicolon", tok_type: TokenType::Semi, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: ",", enum_text: "Comma", tok_type: TokenType::Comma, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: None }, + TokenAttributes { text: "Ident", enum_text: "Identifier", tok_type: TokenType::Ident, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: Some(NodeType::Ident) }, + TokenAttributes { text: "Integer literal", enum_text: "Integer", tok_type: TokenType::Integer, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: Some(NodeType::Integer) }, + TokenAttributes { text: "String literal", enum_text: "String", tok_type: TokenType::String, right_associative: false, is_binary: false, is_unary: false, precedence: None, node_type: Some(NodeType::String) }, +]; + +// Create a lazy-initialized HashMap for faster lookup by enum_text +use lazy_static::lazy_static; // Add `lazy_static = "1.4.0"` to Cargo.toml +lazy_static! { + static ref TOKEN_MAP_BY_ENUM_TEXT: HashMap<&'static str, &'static TokenAttributes> = { + let mut m = HashMap::new(); + for attr in TOKEN_ATTRIBUTES { + m.insert(attr.enum_text, attr); + } + m + }; + static ref TOKEN_MAP_BY_TYPE: HashMap = { + let mut m = HashMap::new(); + for attr in TOKEN_ATTRIBUTES { + m.insert(attr.tok_type, attr); + } + m + }; +} + + +const DISPLAY_NODES: &[&str] = &[ + "Identifier", "String", "Integer", "Sequence", "If", "Prtc", + "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", + "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", + "NotEqual", "And", "Or", +]; + +// --- Error Handling --- + +#[derive(Debug)] +pub enum ParseError { + Io(io::Error), + UnexpectedToken { + expected: String, // Can describe expected category or specific token + found: Token, + context: &'static str, + }, + InvalidTokenFormat(usize, String), // line_num, line_content + UnknownTokenName(String), + EndOfInput, + Custom(String), +} + +// Allow converting io::Error into ParseError +impl From for ParseError { + fn from(err: io::Error) -> Self { + ParseError::Io(err) + } +} + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ParseError::Io(err) => write!(f, "I/O Error: {}", err), + ParseError::UnexpectedToken { expected, found, context } => { + let found_attr = TOKEN_MAP_BY_TYPE.get(&found.tok_type).map_or("?", |a| a.text); + write!( + f, + "({}, {}) Parse Error in {}: Expected {}, found '{}' ({:?})", + found.err_ln, found.err_col, context, expected, found_attr, found.tok_type + ) + } + ParseError::InvalidTokenFormat(line_num, line) => { + write!(f, "Invalid token format on line {}: '{}'", line_num, line) + } + ParseError::UnknownTokenName(name) => write!(f, "Unknown token name: {}", name), + ParseError::EndOfInput => write!(f, "Unexpected end of input"), + ParseError::Custom(msg) => write!(f, "Error: {}", msg), + } + } +} + +impl std::error::Error for ParseError {} + +type ParseResult = Result; + +// --- Helper Functions --- + +fn get_token_attr(token_type: TokenType) -> &'static TokenAttributes { + // Using HashMap lookup now + TOKEN_MAP_BY_TYPE.get(&token_type) + .unwrap_or_else(|| panic!("Internal error: Missing attributes for token type {:?}", token_type)) // Should not happen if maps are correct +} + +fn make_node(node_type: NodeType, left: Option>, right: Option>) -> Box { + Box::new(AstNode { + node_type, + left, + right, + value: None, + }) +} + +fn make_leaf(node_type: NodeType, value: String) -> Box { + Box::new(AstNode { + node_type, + left: None, + right: None, + value: Some(value), + }) +} + + +// --- Parser Struct --- + +struct Parser { + // Use Lines iterator for easy line reading + lines: Lines, + current_line_num: usize, + // Store the *next* token to be processed (lookahead) + current_token: Token, +} + +impl Parser { + fn new(reader: R) -> ParseResult { + let mut parser = Parser { + lines: reader.lines(), + current_line_num: 0, + // Initialize with a dummy EOI token before the first read + current_token: Token { + tok_type: TokenType::Eoi, + err_ln: 0, + err_col: 0, + text: None, + }, + }; + // Read the first actual token + parser.next_token()?; + Ok(parser) + } + + // Reads the next line and parses it into a token, updating self.current_token + fn next_token(&mut self) -> ParseResult<()> { + match self.lines.next() { + Some(Ok(line)) => { + self.current_line_num += 1; + let trimmed_line = line.trim_end(); // Keep original line for error msg + if trimmed_line.is_empty() { + // Skip empty lines potentially introduced by trimming or blank lines + return self.next_token(); + } + + let mut parts = trimmed_line.splitn(4, |c: char| c.is_whitespace()); + + let err_ln_str = parts.next(); + let err_col_str = parts.next(); + let name_str = parts.next(); + let remaining = parts.next().unwrap_or("").trim_start(); // Rest of the line is optional value + + + // Use if let for cleaner parsing and error handling + if let (Some(ln_s), Some(col_s), Some(name)) = (err_ln_str, err_col_str, name_str) { + let err_ln = ln_s.parse::() + .map_err(|_| ParseError::InvalidTokenFormat(self.current_line_num, line.clone()))?; + let err_col = col_s.parse::() + .map_err(|_| ParseError::InvalidTokenFormat(self.current_line_num, line.clone()))?; + + // Lookup token type from name + let attributes = TOKEN_MAP_BY_ENUM_TEXT.get(name) + .ok_or_else(|| ParseError::UnknownTokenName(name.to_string()))?; + + let text = if !remaining.is_empty() { + Some(remaining.to_string()) + } else { + None + }; + + self.current_token = Token { + tok_type: attributes.tok_type, + err_ln, + err_col, + text, + }; + Ok(()) + + } else { + Err(ParseError::InvalidTokenFormat(self.current_line_num, line)) + } + } + Some(Err(e)) => Err(ParseError::Io(e)), + None => { + // End of input, set token to EOI + self.current_token = Token { + tok_type: TokenType::Eoi, + // Use last known line/col or defaults if file was empty + err_ln: self.current_token.err_ln, + err_col: self.current_token.err_col, + text: None, + }; + Ok(()) + } + } + } + + // Check current token type, consume it if it matches, otherwise return error + fn expect(&mut self, expected: TokenType, context: &'static str) -> ParseResult<()> { + if self.current_token.tok_type == expected { + self.next_token()?; + Ok(()) + } else { + Err(ParseError::UnexpectedToken { + expected: format!("'{}' ({:?})", get_token_attr(expected).text, expected), + found: self.current_token.clone(), // Clone token for error reporting + context, + }) + } + } + + // Check current token type *without* consuming it + fn check(&self, expected: TokenType) -> bool { + self.current_token.tok_type == expected + } + + // Get the current token's text value, expecting it to exist + fn consume_text(&mut self, context: &'static str) -> ParseResult { + let token = self.current_token.clone(); // Clone before consuming + let text = token.text.ok_or_else(|| ParseError::Custom( + format!("({},{}) Expected text value for token {:?} in {}", + token.err_ln, token.err_col, token.tok_type, context) + ))?; + self.next_token()?; // Consume the token + Ok(text) + } + + + // --- Parsing Methods (Expression & Statement) --- + + // expr: Parse expressions using precedence climbing + fn expr(&mut self, min_precedence: u8) -> ParseResult> { + let mut left = self.parse_primary()?; + + // Precedence climbing loop + loop { + let current_tok_type = self.current_token.tok_type; + let current_attr = get_token_attr(current_tok_type); + + // Stop if token is not a binary operator OR its precedence is too low + if !current_attr.is_binary || current_attr.precedence.unwrap_or(0) < min_precedence { + break; + } + + let op_type = current_tok_type; + let precedence = current_attr.precedence.unwrap(); // Known because is_binary is true + let node_type = current_attr.node_type.expect("Binary operator must have node type"); + + // Consume operator token + self.next_token()?; + + // Determine precedence for recursive call (handle associativity) + let next_min_precedence = if current_attr.right_associative { + precedence + } else { + precedence + 1 + }; + + let right = self.expr(next_min_precedence)?; + left = make_node(node_type, Some(left), Some(right)); + } + + Ok(left) + } + + // Parse primary expressions (literals, identifiers, unary ops, parentheses) + fn parse_primary(&mut self) -> ParseResult> { + let token = self.current_token.clone(); // Clone token info before consuming + + match token.tok_type { + TokenType::Lparen => self.paren_expr(), + TokenType::Sub | TokenType::Add => { // Unary +/- + self.next_token()?; // Consume '-' or '+' + let node = self.expr(get_token_attr(TokenType::Negate).precedence.unwrap())?; // Use Negate's precedence + if token.tok_type == TokenType::Sub { + Ok(make_node(NodeType::Negate, Some(node), None)) + } else { + Ok(node) // Unary plus is identity + } + } + TokenType::Not => { // Unary ! + self.next_token()?; // Consume '!' + let node = self.expr(get_token_attr(TokenType::Not).precedence.unwrap())?; + Ok(make_node(NodeType::Not, Some(node), None)) + } + TokenType::Ident => { + let ident_name = self.consume_text("identifier")?; + Ok(make_leaf(NodeType::Ident, ident_name)) + } + TokenType::Integer => { + let int_val = self.consume_text("integer literal")?; + Ok(make_leaf(NodeType::Integer, int_val)) + } + // String literals only appear in 'print' in this grammar? + // If they could be primary expressions, add: + // TokenType::String => { + // let str_val = self.consume_text("string literal")?; + // Ok(make_leaf(NodeType::String, str_val)) + // } + _ => Err(ParseError::UnexpectedToken{ + expected: "primary expression (literal, identifier, unary op, or '(')".to_string(), + found: token, + context: "expr", + }), + } + } + + // paren_expr: Parse parenthesized expressions + fn paren_expr(&mut self) -> ParseResult> { + self.expect(TokenType::Lparen, "paren_expr start")?; + let node = self.expr(0)?; // Start with lowest precedence inside parens + self.expect(TokenType::Rparen, "paren_expr end")?; + Ok(node) + } + + // stmt: Parse a single statement + // Returns Option> because ';' might result in no node + fn stmt(&mut self) -> ParseResult>> { + match self.current_token.tok_type { + TokenType::If => { + self.next_token()?; // Consume 'if' + let condition = self.paren_expr()?; + let then_branch = self.stmt()?.ok_or_else(|| ParseError::Custom( + "Expected statement after 'if' condition".to_string() + ))?; // If requires a statement + + let else_branch = if self.check(TokenType::Else) { + self.next_token()?; // Consume 'else' + Some(self.stmt()?.ok_or_else(|| ParseError::Custom( + "Expected statement after 'else'".to_string() + ))?) + } else { + None + }; + + // Structure: If(condition, If(then, else)) - mimics C structure + let if_node = make_node(NodeType::If, Some(then_branch), else_branch); + Ok(Some(make_node(NodeType::If, Some(condition), Some(if_node)))) + } + TokenType::Putc => { + self.next_token()?; // Consume 'putc' + let arg = self.paren_expr()?; + let node = make_node(NodeType::Prtc, Some(arg), None); + self.expect(TokenType::Semi, "putc statement")?; + Ok(Some(node)) + } + TokenType::Print => { + self.next_token()?; // Consume 'print' + self.expect(TokenType::Lparen, "print statement start")?; + + let mut sequence: Option> = None; + + loop { + let expr_node = if self.check(TokenType::String) { + let str_val = self.consume_text("print string literal")?; + make_node(NodeType::Prts, Some(make_leaf(NodeType::String, str_val)), None) + } else { + make_node(NodeType::Prti, Some(self.expr(0)?), None) + }; + + // Build sequence: Sequence(prev_sequence, current_print_expr) + sequence = Some(make_node(NodeType::Sequence, sequence, Some(expr_node))); + + if !self.check(TokenType::Comma) { + break; // Exit loop if no more commas + } + self.next_token()?; // Consume ',' + } + + self.expect(TokenType::Rparen, "print statement end")?; + self.expect(TokenType::Semi, "print statement")?; + Ok(sequence) // Return the sequence of print nodes + } + TokenType::Semi => { + self.next_token()?; // Consume ';' + Ok(None) // Empty statement produces no node + } + TokenType::Ident => { + let ident_token = self.current_token.clone(); + let ident_name = ident_token.text.ok_or_else(|| ParseError::Custom( + "Internal error: Identifier token missing text".to_string() + ))?; + self.next_token()?; // Consume identifier + + self.expect(TokenType::Assign, "assignment")?; + let value_expr = self.expr(0)?; // Assignment has low precedence effectively + + let var_node = make_leaf(NodeType::Ident, ident_name); + let assign_node = make_node(NodeType::Assign, Some(var_node), Some(value_expr)); + + self.expect(TokenType::Semi, "assignment statement")?; + Ok(Some(assign_node)) + } + TokenType::While => { + self.next_token()?; // Consume 'while' + let condition = self.paren_expr()?; + let body = self.stmt()?.ok_or_else(|| ParseError::Custom( + "Expected statement for 'while' body".to_string() + ))?; + Ok(Some(make_node(NodeType::While, Some(condition), Some(body)))) + } + TokenType::Lbrace => { + self.next_token()?; // Consume '{' + let mut sequence: Option> = None; + while !self.check(TokenType::Rbrace) && !self.check(TokenType::Eoi) { + if let Some(stmt_node) = self.stmt()? { + // Build sequence: Sequence(prev_sequence, current_statement) + sequence = Some(make_node(NodeType::Sequence, sequence, Some(stmt_node))); + } + } + self.expect(TokenType::Rbrace, "block statement end")?; + Ok(sequence) // Return the sequence of statements in the block + } + TokenType::Eoi => Ok(None), // End of input is valid here + _ => Err(ParseError::UnexpectedToken { + expected: "start of statement (if, while, print, putc, {, ;, identifier)".to_string(), + found: self.current_token.clone(), + context: "stmt", + }), + } + } + + // parse: Main parsing loop, creates sequence of statements + fn parse(&mut self) -> ParseResult> { + let mut program_sequence: Option> = None; + + // Loop until End Of Input is the *current* token + while !self.check(TokenType::Eoi) { + match self.stmt()? { + Some(stmt_node) => { + // Build sequence: Sequence(prev_sequence, current_statement) + program_sequence = Some(make_node(NodeType::Sequence, program_sequence, Some(stmt_node))); + } + None => { + // Handle empty statements (like ';') - they don't add to the sequence + } + } + } + + // If program_sequence is still None (empty input or only ';'), create an empty sequence. + // Otherwise, return the built sequence. + Ok(program_sequence.unwrap_or_else(|| make_node(NodeType::Sequence, None, None))) + } +} + + +// --- AST Printing --- + +fn prt_ast(node: Option<&AstNode>, indent: usize) { + let prefix = " ".repeat(indent); + match node { + None => { + // Represent null children clearly, maybe matching the C output style + println!("{}", prefix); + // Or match C output: println!("{};", prefix); but is clearer + } + Some(t) => { + // Use DISPLAY_NODES array, ensure NodeType enum indices match + let node_name = DISPLAY_NODES.get(t.node_type as usize).unwrap_or(&"UnknownNode"); + + match t.node_type { + NodeType::Ident | NodeType::Integer | NodeType::String => { + println!("{}{:<14} {}", prefix, node_name, t.value.as_deref().unwrap_or("")); + } + _ => { + println!("{}{:<14}", prefix, node_name); + prt_ast(t.left.as_deref(), indent + 1); + prt_ast(t.right.as_deref(), indent + 1); + } + } + } + } +} + + +// --- Main Function --- + +fn main() -> Result<(), Box> { + let args: Vec = env::args().collect(); + + // --- I/O Setup --- + // Use Box to handle both stdin and files + let reader: Box = if args.len() > 1 && !args[1].is_empty() { + Box::new(File::open(&args[1]) + .map_err(|e| format!("Error opening input file '{}': {}", args[1], e))?) + } else { + Box::new(io::stdin()) + }; + let buf_reader = BufReader::new(reader); + + // Use Box for output flexibility (though stdout is typical) + let writer: Box = if args.len() > 2 && !args[2].is_empty() { + Box::new(File::create(&args[2]) + .map_err(|e| format!("Error creating output file '{}': {}", args[2], e))?) + } else { + Box::new(io::stdout()) + }; + let mut buf_writer = BufWriter::new(writer); // Not strictly needed for AST printing, but good practice + + // --- Parsing --- + // Create parser and run it + let mut parser = Parser::new(buf_reader) + .map_err(|e| format!("Parser initialization failed: {}", e))?; // Convert ParseError for main's return + + match parser.parse() { + Ok(ast_root) => { + // --- AST Printing --- + // Use a closure to capture buf_writer for printing + let print_to_writer = |node: Option<&AstNode>, indent: usize| { + let prefix = " ".repeat(indent); + match node { + None => writeln!(buf_writer, "{}", prefix).unwrap(), // Handle write errors if needed + Some(t) => { + let node_name = DISPLAY_NODES.get(t.node_type as usize).unwrap_or(&"UnknownNode"); + match t.node_type { + NodeType::Ident | NodeType::Integer | NodeType::String => { + writeln!(buf_writer, "{}{:<14} {}", prefix, node_name, t.value.as_deref().unwrap_or("")).unwrap(); + } + _ => { + writeln!(buf_writer, "{}{:<14}", prefix, node_name).unwrap(); + // Recursive calls need access to buf_writer, which is tricky. + // Simpler to pass the writer or print directly for now. + // Let's redefine prt_ast slightly for main. + } + } + } + } + }; + + // Redefine prt_ast locally or pass writer - let's redefine for simplicity here + fn print_ast_to_writer(writer: &mut W, node: Option<&AstNode>, indent: usize) -> io::Result<()> { + let prefix = " ".repeat(indent); + match node { + None => writeln!(writer, "{}", prefix), + Some(t) => { + let node_name = DISPLAY_NODES.get(t.node_type as usize).unwrap_or(&"UnknownNode"); + match t.node_type { + NodeType::Ident | NodeType::Integer | NodeType::String => { + writeln!(writer, "{}{:<14} {}", prefix, node_name, t.value.as_deref().unwrap_or(""))?; + } + _ => { + writeln!(writer, "{}{:<14}", prefix, node_name)?; + print_ast_to_writer(writer, t.left.as_deref(), indent + 1)?; + print_ast_to_writer(writer, t.right.as_deref(), indent + 1)?; + } + } + Ok(()) + } + } + } + + // Call the modified print function + print_ast_to_writer(&mut buf_writer, Some(&ast_root), 0) + .map_err(|e| format!("Error writing AST: {}", e))?; + + + // Ensure output buffer is flushed + buf_writer.flush()?; + } + Err(e) => { + eprintln!("Parse Error: {}", e); // Print error to stderr + exit(1); // Exit with non-zero status on error + } + } + + Ok(()) // Indicate success +} diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/EasyLang/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.easy b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/EasyLang/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.easy index 05eec49360..e6858be29f 100644 --- a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/EasyLang/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.easy +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/EasyLang/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.easy @@ -3,24 +3,17 @@ fastfunc isin n k . while n > 0 if h mod 10 = n mod 10 h = h div 10 - if match = 0 - match = n - . + if match = 0 : match = n else h = k - if match <> 0 - n = match - . + if match <> 0 : n = match match = 0 . - if h = 0 - return 1 - . + if h = 0 : return 1 n = n div 10 . return 0 . - fastfunc test n . if n mod 2 = 0 or n mod 3 = 0 or n mod 5 = 0 or n mod 7 = 0 return 0 @@ -32,25 +25,19 @@ fastfunc test n . while rest mod fact = 0 rest /= fact . - if isin n fact = 0 - return 0 - . + if isin n fact = 0 : return 0 nfacts += 1 . fact += 2 - if fact > sqrt n and nfacts = 0 - return 0 - . - . - if nfacts > 1 - return 1 + if fact > sqrt n and nfacts = 0 : return 0 . + if nfacts > 1 : return 1 return 0 . n = 11 while count < 10 if test n = 1 - print n + write n & " " count += 1 . n += 2 diff --git a/Task/Concurrent-computing/Elena/concurrent-computing.elena b/Task/Concurrent-computing/Elena/concurrent-computing.elena new file mode 100644 index 0000000000..89672b7dac --- /dev/null +++ b/Task/Concurrent-computing/Elena/concurrent-computing.elena @@ -0,0 +1,11 @@ +import system'threading; +import extensions'threading; + +async public program() +{ + Task t1 := Task.run({ Console.printLineConcurrent("Enjoy") }); + Task t2 := Task.run({ Console.printLineConcurrent("Rosetta") }); + Task t3 := Task.run({ Console.printLineConcurrent("Code") }); + + :await Task.whenAllArgs(t1, t2, t3); +} diff --git a/Task/Conditional-structures/Excel/conditional-structures-1.excel b/Task/Conditional-structures/Excel/conditional-structures-1.excel new file mode 100644 index 0000000000..1898abcdcd --- /dev/null +++ b/Task/Conditional-structures/Excel/conditional-structures-1.excel @@ -0,0 +1 @@ +=IF(condition, value_if_true, value_if_false) diff --git a/Task/Conditional-structures/Excel/conditional-structures-2.excel b/Task/Conditional-structures/Excel/conditional-structures-2.excel new file mode 100644 index 0000000000..0d2f873020 --- /dev/null +++ b/Task/Conditional-structures/Excel/conditional-structures-2.excel @@ -0,0 +1 @@ +=IFS(condition1, value_if_true1, [condition2, value_if_true2, ...]) diff --git a/Task/Conditional-structures/Excel/conditional-structures-3.excel b/Task/Conditional-structures/Excel/conditional-structures-3.excel new file mode 100644 index 0000000000..7a84f2b5ab --- /dev/null +++ b/Task/Conditional-structures/Excel/conditional-structures-3.excel @@ -0,0 +1 @@ +=SWITCH(expression, case1, value1, [case2, value2, ...], [default]) diff --git a/Task/Conditional-structures/Uxntal/conditional-structures.uxnatl b/Task/Conditional-structures/Uxntal/conditional-structures.uxnatl new file mode 100644 index 0000000000..c30872584c --- /dev/null +++ b/Task/Conditional-structures/Uxntal/conditional-structures.uxnatl @@ -0,0 +1,32 @@ +%\n { 0a } %\s { 20 } %\0 { 00 } + +|18 @Console/write + +|100 + +#0102 test +#0201 test +#0101 test + +BRK + +@test ( x y -- ) + ( unless ) NEQk ?{ + ;msgs/equal print/str !/end } + ( else unless ) GTHk ?{ + ;msgs/less print/str !/end } + ( else unless ) LTHk ?{ + ;msgs/greater print/str } + + &end + POP2 JMP2r + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str + POP2 JMP2r + +@msgs [ + &greater "x \s "is \s "greater \s "than \s "y \n \0 + &equal "x \s "is \s "equal \s "to \s "y \n \0 + &less "x \s "is \s "less \s "than \s "y \n \0 ] diff --git a/Task/Consecutive-primes-with-ascending-or-descending-differences/EasyLang/consecutive-primes-with-ascending-or-descending-differences.easy b/Task/Consecutive-primes-with-ascending-or-descending-differences/EasyLang/consecutive-primes-with-ascending-or-descending-differences.easy index 7fcb576dfd..cecfaecb6e 100644 --- a/Task/Consecutive-primes-with-ascending-or-descending-differences/EasyLang/consecutive-primes-with-ascending-or-descending-differences.easy +++ b/Task/Consecutive-primes-with-ascending-or-descending-differences/EasyLang/consecutive-primes-with-ascending-or-descending-differences.easy @@ -9,7 +9,7 @@ fastfunc nextprim num . . return num . -proc getseq dir . maxprim maxcnt . +proc getseq dir &maxprim &maxcnt . maxcnt = 0 pri = 2 repeat @@ -30,7 +30,7 @@ proc getseq dir . maxprim maxcnt . . . . -proc outseq pri max . . +proc outseq pri max . write pri & " " for i to max pri = nextprim (pri + 1) diff --git a/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-1.rexx b/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-1.rexx deleted file mode 100644 index 28f9729221..0000000000 --- a/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-1.rexx +++ /dev/null @@ -1,64 +0,0 @@ -/*REXX program finds the longest sequence of consecutive primes where the differences */ -/*──────────── between the primes are strictly ascending; also for strictly descending.*/ -parse arg hi cols . /*obtain optional argument from the CL.*/ -if hi=='' | hi=="," then hi= 1000000 /* " " " " " " */ -if cols=='' | cols=="," then cols= 10 /* " " " " " " */ -call genP /*build array of semaphores for primes.*/ -w= 10 /*width of a number in any column. */ -call fRun 1; call show 1 /*find runs with ascending prime diffs.*/ -call fRun 0; call show 0 /* " " " descending " " */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -/*──────────────────────────────────────────────────────────────────────────────────────*/ -fRun: parse arg ?; mxrun=0; seq.= /*max run length; lists of prime runs.*/ - /*search for consecutive primes < HI.*/ - do j=2 for #-2; cp= @.j; jn= j+1 /*CP: current prime; JN: next j */ - diff= @.jn - cp /*get difference between last 2 primes.*/ - cnt= 1; run= /*initialize the CNT and RUN. */ - do k= jn+1 to #-2; km= k-1 /*look for more primes in this run. */ - if ? then if @.k-@.km<=diff then leave /*Diff. too small? Stop looking*/ - else nop - else if @.k-@.km>=diff then leave /* " " large? " " */ - run= run @.k; cnt= cnt+1 /*append a prime to the run; bump count*/ - diff= @.k - @.km /*calculate difference for next prime. */ - end /*k*/ - if cnt<=mxrun then iterate /*This run too short? Then keep looking*/ - mxrun= max(mxrun, cnt) /*define a new maximum run (seq) length*/ - seq.mxrun= cp @.jn run /*full populate the sequence (RUN). */ - end /*j*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19 /*define low primes.*/ - #=8; sq.#= @.# ** 2 /*number of primes so far; prime sqiare*/ - /* [↓] generate more primes ≤ high.*/ - do j=@.#+2 by 2 to hi; parse var j '' -1 _ /*find odd primes from here on.*/ - if _==5 then iterate; if j// 3==0 then iterate /*J ÷ 5? J ÷ by 3? */ - if j// 7==0 then iterate; if j//11==0 then iterate /*" " 7? " " " 11? */ - if j//13==0 then iterate; if j//17==0 then iterate /*" " 13? " " " 17? */ - do k=8 while sq.k<=j /* [↓] divide by the known odd primes.*/ - if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j; sq.#= j*j /*bump # of Ps; assign next P; P square*/ - end /*j*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: parse arg ?; if ? then AorD= 'ascending' /*choose which literal for display.*/ - else AorD= 'descending' /* " " " " " */ - title= ' longest run of consecutive primes whose differences between primes are' , - 'strictly' AorD "and < " commas(hi) - say; say; say - if cols>0 then say ' index │'center(title, 1 + cols*(w+1) ) - if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─') - found= 0; idx= 1 /*initialize # of consecutive primes. */ - $= /*a list of consecutive primes (so far)*/ - do o=1 for words(seq.mxrun) /*show all consecutive primes in seq. */ - c= commas( word(seq.mxrun, o) ) /*obtain the next prime in the sequence*/ - found= found + 1 /*bump the number of consecutive primes*/ - if cols<=0 then iterate /*build the list (to be shown later)? */ - $= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/ - if found//cols\==0 then iterate /*have we populated a line of output? */ - say center(idx, 7)'│' substr($, 2) /*display what we have so far (cols). */ - idx= idx + cols; $= /*bump the index count for the output*/ - end /*o*/ - if $\=='' then say center(idx, 7)"│" substr($, 2) /*maybe show residual output*/ - if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─') - say; say commas(Cprimes) ' was the'title; return diff --git a/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-2.rexx b/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences.rexx similarity index 51% rename from Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-2.rexx rename to Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences.rexx index 6bd309a7ca..2cc34a37fe 100644 --- a/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences-2.rexx +++ b/Task/Consecutive-primes-with-ascending-or-descending-differences/REXX/consecutive-primes-with-ascending-or-descending-differences.rexx @@ -1,8 +1,10 @@ -call Time('r') -parse version version; say version -glob. = ''; numeric digits 10; t = 1e7 -say 'Consecutive primes - Using REXX libraries' +-- 22 Mar 2025 +include Settings + +say 'CONSECUTIVE PRIMES' +say version say +numeric digits 10; t = 1e7 call Primes t call Deltas call Sequence 'A',t @@ -11,35 +13,35 @@ say Format(Time('e'),,3) 'seconds' exit Deltas: -/* Calculate deltas between pairs of primes */ -procedure expose prim. delta. -delta. = 0 +-- Calculate deltas between pairs of primes +procedure expose prim. delt. +delt. = 0 do i = 2 to prim.0 - h = i-1; delta.i = prim.prime.i-prim.prime.h + h = i-1; delt.i = prim.i-prim.h end return Sequence: -/* Find and show longest strict sequence */ -procedure expose delta. glob. prim. +-- Find and show longest strict sequence +procedure expose delt. prim. arg ad,t p = prim.0+1 if ad = 'A' then - delta.p = 0 + delt.p = 0 else - delta.p = n + delt.p = t d = 0; f = 1; l = 1; len = 0 do i = 2 to p - if (ad = 'A' & delta.i > d), - | (ad = 'D' & delta.i < d) then do - d = delta.i; l = i + if (ad = 'A' & delt.i > d), + | (ad = 'D' & delt.i < d) then do + d = delt.i; l = i end else do a = l-f+1 if a > len then do first = f; last = l; len = a end - f = i-1; l = i; d = delta.i + f = i-1; l = i; d = delt.i end end if ad = 'A' then @@ -50,11 +52,12 @@ say 'For primes <' t', the longest' a 'sequence was' len 'consecutive primes.' say 'These are (with differences):' do i = first to last-1 j = i+1 - call charout ,prim.prime.i '('delta.j') ' + call charout ,prim.i '('delt.j') ' end -call charout ,prim.prime.last +call charout ,prim.last say; say return include Sequences include Functions +include Abend diff --git a/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy b/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy index 3f4f491b57..067481812b 100644 --- a/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy +++ b/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy @@ -4,7 +4,6 @@ while cnt < 100 r = sqrt (x * x + y * y) if 10 <= r and r <= 15 cnt += 1 - move 50 + x * 2 50 + y * 2 - circle 1 + gcircle 50 + x * 2 50 + y * 2 1 . . diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/C-sharp/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.cs b/Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/C-sharp/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.cs new file mode 100644 index 0000000000..9507421d86 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/C-sharp/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.cs @@ -0,0 +1,70 @@ +using System.Numerics; +using Seq = System.Collections.Generic.IEnumerable; + +static Seq Rep(BigInteger n) { while(true) yield return n; } + +static Seq Cons(BigInteger n, Seq s) => new[]{n}.Concat(s); + +static void Write(Seq terms) +{ + var ts = terms.ToArray(); + + switch (ts.Length) + { + case 0: Console.Write("[]"); break; + case 1: Console.Write($"[{ts[0]}]"); break; + default: + Console.Write($"[{ts[0]}; "); + Console.Write(string.Join(", ", ts[1..])); + Console.Write(']'); + break; + } +} + +static Seq Transform(Seq terms, BigInteger a1, BigInteger a, BigInteger b1, BigInteger b) +{ + foreach (var term in terms) + { + (a, a1) = (a1, a + term * a1); + (b, b1) = (b1, b + term * b1); + + while (!b1.IsZero && !b.IsZero) + { + var m = BigInteger.DivRem(a1, b1, out var r); + var n = BigInteger.DivRem(a, b, out var s); + + if (m != n) + break; + + yield return n; + (a1, b1) = (b1, r); + (a, b) = (b, s); + } + } + + while (!a1.IsZero && !b1.IsZero) + { + var n = BigInteger.DivRem(a1, b1, out var s); + yield return n; + (a1, b1) = (b1, s); + } +} + +Console.Write("[1; 5, 2] + 1/2 = "); +Write(Transform([1, 5, 2], 2, 1, 0, 2)); +Console.WriteLine(); + +Console.Write("[3; 7] + 1/2 = "); +Write(Transform([3, 7], 2, 1, 0, 2)); +Console.WriteLine(); + +Console.Write("[3; 7] / 4 = "); +Write(Transform([3, 7], 1, 0, 0, 4)); +Console.WriteLine(); + +var sqrt2 = Cons(1, Rep(2)); +var oneOverSqrt2 = Transform(sqrt2, 0, 1, 1, 0); +var agm = Transform(oneOverSqrt2, 1, 1, 0, 2); +Console.Write("(1 + 1/sqrt(2)) / 2 = "); +Write(agm.Take(20)); +Console.WriteLine(); diff --git a/Task/Continued-fraction/C-sharp/continued-fraction.cs b/Task/Continued-fraction/C-sharp/continued-fraction.cs index 207aee03b1..0b26fa0a36 100644 --- a/Task/Continued-fraction/C-sharp/continued-fraction.cs +++ b/Task/Continued-fraction/C-sharp/continued-fraction.cs @@ -1,26 +1,102 @@ -using System; -using System.Collections.Generic; +using System.Numerics; -namespace ContinuedFraction { - class Program { - static double Calc(Func f, int n) { - double temp = 0.0; - for (int ni = n; ni >= 1; ni--) { - int[] p = f(ni); - temp = p[1] / (p[0] + temp); - } - return f(0)[0] + temp; - } +using Seq = System.Collections.Generic.IEnumerable; - static void Main(string[] args) { - List> fList = new List>(); - fList.Add(n => new int[] { n > 0 ? 2 : 1, 1 }); - fList.Add(n => new int[] { n > 0 ? n : 2, n > 1 ? (n - 1) : 1 }); - fList.Add(n => new int[] { n > 0 ? 6 : 3, (int) Math.Pow(2 * n - 1, 2) }); +static Seq Rep(BigInteger n) { while(true) yield return n; } - foreach (var f in fList) { - Console.WriteLine(Calc(f, 200)); - } +static Seq Cons(BigInteger n, Seq s) => new[]{n}.Concat(s); + +static Seq Reciprocal(Seq s) => s.First() == 0 ? s.Skip(1) : Cons(0, s); + +static Seq Nats() { BigInteger n = 1; while(true) { yield return n; n++; } } + +static Seq Squared(Seq s) => s.Select(n => n * n); + +static Seq Odds() => Nats().Select(n => 2 * n - 1); + +static Seq Simplify(Seq aseq, Seq bseq) +{ + BigInteger a = 0, b = 1, c = 1, d = 0; + using var e = bseq.GetEnumerator(); + + foreach (var t in aseq) + { + var u = e.MoveNext() ? e.Current : 1; + (a, b) = (u * b, a + t * b); + (c, d) = (u * d, c + t * d); + + while (!c.IsZero && !d.IsZero) + { + var m = BigInteger.DivRem(a, c, out var r); + var n = BigInteger.DivRem(b, d, out var s); + + if (m != n) + break; + + yield return n; + (a, c) = (c, r); + (b, d) = (d, s); } } + + while (!b.IsZero && !d.IsZero) + { + var n = BigInteger.DivRem(b, d, out var s); + yield return n; + (b, d) = (d, s); + } } + +static void Write(Seq terms, int places) +{ + Console.Write(terms.First()); + Console.Write('.'); + BigInteger a = 10, b = 0, c = 0, d = 1; + + foreach (var term in terms.Skip(1)) + { + (a, b) = (b, a + b * term); + (c, d) = (d, c + d * term); + + while (!c.IsZero && !d.IsZero) + { + var m = BigInteger.DivRem(a, c, out var r); + var n = BigInteger.DivRem(b, d, out var s); + + if (m != n) + break; + + Console.Write(m); + + if (--places <= 0) + return; + + a = r * 10; + b = s * 10; + } + } + + while (!b.IsZero && !d.IsZero) + { + var n = BigInteger.DivRem(b, d, out var s); + Console.Write(n); + + if (--places <= 0) + return; + + b = s * 10; + } +} + +static Seq Sqrt2() => Cons(1, Rep(2)); + +static Seq E() => Simplify(Cons(2, Nats()), Cons(1, Nats())); + +static Seq Pi() => Simplify(Cons(3, Rep(6)), Squared(Odds())); + +Write(Sqrt2(), 20); +Console.WriteLine(); +Write(E(), 20); +Console.WriteLine(); +Write(Pi(), 10); +Console.WriteLine(); diff --git a/Task/Continued-fraction/EasyLang/continued-fraction.easy b/Task/Continued-fraction/EasyLang/continued-fraction.easy index 84c90776b1..51ec9a4634 100644 --- a/Task/Continued-fraction/EasyLang/continued-fraction.easy +++ b/Task/Continued-fraction/EasyLang/continued-fraction.easy @@ -1,12 +1,10 @@ -numfmt 8 0 +numfmt 0 8 func calc_sqrt . n = 100 sum = n while n >= 1 - a = 1 - if n > 1 - a = 2 - . + a = 2 + if n = 1 : a = 1 b = 1 sum = a + b / sum n -= 1 @@ -17,13 +15,11 @@ func calc_e . n = 100 sum = n while n >= 1 - a = 2 - if n > 1 - a = n - 1 - . - b = 1 - if n > 1 - b = n - 1 + a = n - 1 + b = n - 1 + if n = 1 + a = 2 + b = 1 . sum = a + b / sum n -= 1 @@ -34,10 +30,8 @@ func calc_pi . n = 100 sum = n while n >= 1 - a = 3 - if n > 1 - a = 6 - . + a = 6 + if n = 1 : a = 3 b = 2 * n - 1 b *= b sum = a + b / sum diff --git a/Task/Continued-fraction/REXX/continued-fraction-1.rexx b/Task/Continued-fraction/REXX/continued-fraction-1.rexx index 2f67a48e9a..f85721f91a 100644 --- a/Task/Continued-fraction/REXX/continued-fraction-1.rexx +++ b/Task/Continued-fraction/REXX/continued-fraction-1.rexx @@ -1,43 +1,44 @@ -/*REXX program calculates and displays values of various continued fractions. */ -parse arg terms digs . -if terms=='' | terms=="," then terms=500 -if digs=='' | digs=="," then digs=100 -numeric digits digs /*use 100 decimal digits for display.*/ -b.=1 /*omitted ß terms are assumed to be 1.*/ -/*══════════════════════════════════════════════════════════════════════════════════════*/ -a.=2; call tell '√2', cf(1) -/*══════════════════════════════════════════════════════════════════════════════════════*/ -a.=1; do N=2 by 2 to terms; a.N=2; end; call tell '√3', cf(1) /*also: 2∙sin(π/3) */ -/*══════════════════════════════════════════════════════════════════════════════════════*/ -a.=2 /* ___ */ - do N=2 to 17 /*generalized √ N */ - b.=N-1; NN=right(N, 2); call tell 'gen √'NN, cf(1) - end /*N*/ -/*══════════════════════════════════════════════════════════════════════════════════════*/ -a.=2; b.=-1/2; call tell 'gen √ ½', cf(1) -/*══════════════════════════════════════════════════════════════════════════════════════*/ - do j=1 for terms; a.j=j; if j>1 then b.j=a.p; p=j; end; call tell 'e', cf(2) -/*══════════════════════════════════════════════════════════════════════════════════════*/ -a.=1; call tell 'φ, phi', cf(1) -/*══════════════════════════════════════════════════════════════════════════════════════*/ -a.=1; do j=1 for terms; if j//2 then a.j=j; end; call tell 'tan(1)', cf(1) -/*══════════════════════════════════════════════════════════════════════════════════════*/ - do j=1 for terms; a.j=2*j+1; end; call tell 'coth(1)', cf(1) -/*══════════════════════════════════════════════════════════════════════════════════════*/ - do j=1 for terms; a.j=4*j+2; end; call tell 'coth(½)', cf(2) /*also: [e+1]÷[e-1] */ -/*══════════════════════════════════════════════════════════════════════════════════════*/ - terms=100000 -a.=6; do j=1 for terms; b.j=(2*j-1)**2; end; call tell 'π, pi', cf(3) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -cf: procedure expose a. b. terms; parse arg C; !=0; numeric digits 9+digits() - do k=terms by -1 for terms; d=a.k+!; !=b.k/d - end /*k*/ - return !+C -/*──────────────────────────────────────────────────────────────────────────────────────*/ -tell: parse arg ?,v; $=left(format(v)/1,1+digits()); w=50 /*50 bytes of terms*/ - aT=; do k=1; _=space(aT a.k); if length(_)>w then leave; aT=_; end /*k*/ - bT=; do k=1; _=space(bT b.k); if length(_)>w then leave; bT=_; end /*k*/ - say right(?,8) "=" $ ' α terms='aT ... - if b.1\==1 then say right("",12+digits()) ' ß terms='bT ... - a=; b.=1; return /*only 50 bytes of α & ß terms ↑ are displayed. */ +/* REXX ************************************************************** +* Derived from PL/I with a little "massage" +* SQRT2= 1.41421356237309505 <- PL/I Result +* 1.41421356237309504880168872421 <- REXX Result 30 digits +* NAPIER= 2.71828182845904524 +* 2.71828182845904523536028747135 +* PI= 3.14159262280484695 +* 3.14159262280484694855146925223 +* 06.09.2012 Walter Pachl +**********************************************************************/ + Numeric Digits 30 + Parse Value '1 2 3 0 0' with Sqrt2 napier pi a b + Say left('SQRT2=' ,10) calc(sqrt2, 200) + Say left('NAPIER=',10) calc(napier, 200) + Say left('PI=' ,10) calc(pi, 200) + Exit + +Get_Coeffs: procedure Expose a b Sqrt2 napier pi + Parse Arg form, n + select + when form=Sqrt2 Then do + if n > 0 then a = 2; else a = 1 + b = 1 + end + when form=Napier Then do + if n > 0 then a = n; else a = 2 + if n > 1 then b = n - 1; else b = 1 + end + when form=pi Then do + if n > 0 then a = 6; else a = 3 + b = (2*n - 1)**2 + end + end + Return + +Calc: procedure Expose a b Sqrt2 napier pi + Parse Arg form,n + Temp=0 + do ni = n to 1 by -1 + Call Get_Coeffs form, ni + Temp = B/(A + Temp) + end + call Get_Coeffs form, 0 + return (A + Temp) diff --git a/Task/Continued-fraction/REXX/continued-fraction-2.rexx b/Task/Continued-fraction/REXX/continued-fraction-2.rexx index f85721f91a..a2ebb2cccc 100644 --- a/Task/Continued-fraction/REXX/continued-fraction-2.rexx +++ b/Task/Continued-fraction/REXX/continued-fraction-2.rexx @@ -1,44 +1,72 @@ -/* REXX ************************************************************** -* Derived from PL/I with a little "massage" -* SQRT2= 1.41421356237309505 <- PL/I Result -* 1.41421356237309504880168872421 <- REXX Result 30 digits -* NAPIER= 2.71828182845904524 -* 2.71828182845904523536028747135 -* PI= 3.14159262280484695 -* 3.14159262280484694855146925223 -* 06.09.2012 Walter Pachl +/* REXX ************************************************************* +* The task description specifies a continued fraction for pi +* that gives a reasonable approximation. +* Literature shows a better CF that yields pi with a precision of +* 200 digits. +* http://de.wikipedia.org/wiki/Kreiszahl +* 1 +* pi = 3 + ------------------------ +* 1 +* 7 + -------------------- +* 1 +* 15 + --------------- +* 1 +* 1 + ----------- +* +* 292 + ... +* +* This program uses that CF and shows the first 50 digits +* PI =3.1415926535897932384626433832795028841971693993751... +* PIX=3.1415926535897932384626433832795028841971693993751... +* 201 correct digits +* 18.09.2012 Walter Pachl **********************************************************************/ - Numeric Digits 30 - Parse Value '1 2 3 0 0' with Sqrt2 napier pi a b - Say left('SQRT2=' ,10) calc(sqrt2, 200) - Say left('NAPIER=',10) calc(napier, 200) - Say left('PI=' ,10) calc(pi, 200) + pi='3.1415926535897932384626433832795028841971'||, + '693993751058209749445923078164062862089986280348'||, + '253421170679821480865132823066470938446095505822'||, + '317253594081284811174502841027019385211055596446'||, + '229489549303819644288109756659334461284756482337'||, + '867831652712019091456485669234603486104543266482'||, + '133936072602491412737245870066063155881748815209'||, + '209628292540917153643678925903600113305305488204'||, + '665213841469519415116094330572703657595919530921'||, + '861173819326117931051185480744623799627495673518'||, + '857527248912279381830119491298336733624' + Numeric Digits 1000 + al='7 15 1 292 1 1 1 2 1 3 1 14 2 1 1 2 2 2 2 1 84 2', + '1 1 15 3 13 1 4 2 6 6 99 1 2 2 6 3 5 1 1 6 8 1 7 1 2', + '3 7 1 2 1 1 12 1 1 1 3 1 1 8 1 1 2 1 6 1 1 5 2 2 3 1', + '2 4 4 16 1 161 45 1 22 1 2 2 1 4 1 2 24 1 2 1 3 1 2', + '1 1 10 2 5 4 1 2 2 8 1 5 2 2 26 1 4 1 1 8 2 42 2 1 7', + '3 3 1 1 7 2 4 9 7 2 3 1 57 1 18 1 9 19 1 2 18 1 3 7', + '30 1 1 1 3 3 3 1 2 8 1 1 2 1 15 1 2 13 1 2 1 4 1 12', + '1 1 3 3 28 1 10 3 2 20 1 1 1 1 4 1 1 1 5 3 2 1 6 1 4' + a.=3 + Do i=1 By 1 while al<>'' + Parse Var al a.i al + End + pix=calc(194) + Do e=1 To length(pi) + If substr(pix,e,1)<>substr(pi,e,1) Then Leave + End + Numeric Digits 50 + Say 'PI ='||(pi+0)||'...' + Say 'PIX='||(pix+0)||'...' + Say (e-1) 'correct digits' Exit -Get_Coeffs: procedure Expose a b Sqrt2 napier pi - Parse Arg form, n - select - when form=Sqrt2 Then do - if n > 0 then a = 2; else a = 1 - b = 1 - end - when form=Napier Then do - if n > 0 then a = n; else a = 2 - if n > 1 then b = n - 1; else b = 1 - end - when form=pi Then do - if n > 0 then a = 6; else a = 3 - b = (2*n - 1)**2 - end - end +Get_Coeffs: procedure Expose a b a. + Parse Arg n + a=a.n + b=1 Return -Calc: procedure Expose a b Sqrt2 napier pi - Parse Arg form,n +Calc: procedure Expose a b a. + Parse Arg n Temp=0 do ni = n to 1 by -1 - Call Get_Coeffs form, ni + Call Get_Coeffs ni Temp = B/(A + Temp) end - call Get_Coeffs form, 0 + call Get_Coeffs 0 return (A + Temp) diff --git a/Task/Continued-fraction/REXX/continued-fraction-3.rexx b/Task/Continued-fraction/REXX/continued-fraction-3.rexx index a2ebb2cccc..cd0a5816c4 100644 --- a/Task/Continued-fraction/REXX/continued-fraction-3.rexx +++ b/Task/Continued-fraction/REXX/continued-fraction-3.rexx @@ -1,72 +1,31 @@ -/* REXX ************************************************************* -* The task description specifies a continued fraction for pi -* that gives a reasonable approximation. -* Literature shows a better CF that yields pi with a precision of -* 200 digits. -* http://de.wikipedia.org/wiki/Kreiszahl -* 1 -* pi = 3 + ------------------------ -* 1 -* 7 + -------------------- -* 1 -* 15 + --------------- -* 1 -* 1 + ----------- -* -* 292 + ... -* -* This program uses that CF and shows the first 50 digits -* PI =3.1415926535897932384626433832795028841971693993751... -* PIX=3.1415926535897932384626433832795028841971693993751... -* 201 correct digits -* 18.09.2012 Walter Pachl -**********************************************************************/ - pi='3.1415926535897932384626433832795028841971'||, - '693993751058209749445923078164062862089986280348'||, - '253421170679821480865132823066470938446095505822'||, - '317253594081284811174502841027019385211055596446'||, - '229489549303819644288109756659334461284756482337'||, - '867831652712019091456485669234603486104543266482'||, - '133936072602491412737245870066063155881748815209'||, - '209628292540917153643678925903600113305305488204'||, - '665213841469519415116094330572703657595919530921'||, - '861173819326117931051185480744623799627495673518'||, - '857527248912279381830119491298336733624' - Numeric Digits 1000 - al='7 15 1 292 1 1 1 2 1 3 1 14 2 1 1 2 2 2 2 1 84 2', - '1 1 15 3 13 1 4 2 6 6 99 1 2 2 6 3 5 1 1 6 8 1 7 1 2', - '3 7 1 2 1 1 12 1 1 1 3 1 1 8 1 1 2 1 6 1 1 5 2 2 3 1', - '2 4 4 16 1 161 45 1 22 1 2 2 1 4 1 2 24 1 2 1 3 1 2', - '1 1 10 2 5 4 1 2 2 8 1 5 2 2 26 1 4 1 1 8 2 42 2 1 7', - '3 3 1 1 7 2 4 9 7 2 3 1 57 1 18 1 9 19 1 2 18 1 3 7', - '30 1 1 1 3 3 3 1 2 8 1 1 2 1 15 1 2 13 1 2 1 4 1 12', - '1 1 3 3 28 1 10 3 2 20 1 1 1 1 4 1 1 1 5 3 2 1 6 1 4' - a.=3 - Do i=1 By 1 while al<>'' - Parse Var al a.i al - End - pix=calc(194) - Do e=1 To length(pi) - If substr(pix,e,1)<>substr(pi,e,1) Then Leave - End - Numeric Digits 50 - Say 'PI ='||(pi+0)||'...' - Say 'PIX='||(pix+0)||'...' - Say (e-1) 'correct digits' - Exit +-- 8 May 2025 +include Settings +numeric digits 30 +say 'CONTINUED FRACTION' +say version +say +say 'SqRt(2) =' QcontFrac(1,2,1,1,10) +say 'Must be =' SqRt(2)/1 +say 'e =' QcontFrac(2,'n',1,'n-1',10) +say 'Must be =' E()/1 +say 'Pi =' QcontFrac(3,6,1,'(2*n-1)**2',10) +say 'Must be =' Pi()/1 +say +say 'Pi =' 4/QcontFrac(1,'2*n+1',1,'n**2',10) +say 'Must be =' Pi()/1 +say 'Ln(2) =' QcontFrac(0,'6*n-3',2,'-((n-1)**2)',10) +say 'Must be =' Ln(2)/1 +say 'e^2 =' QcontFrac(7,'2*n+3',2,1,10) +say 'Must be =' E()*E()/1 +say 'Phi =' QcontFrac(1,1,1,1,10) +say 'Must be =' Golden()/1 +say '2^(1/3) =' QcontFrac(1,'2+Odd(n)*(3*n-2)',1,'n+((n+1)%2-1)',10) +say 'Must be =' CbRt(2)/1 +say 'Tan(1) =' QcontFrac(0,'2*n-1',1,-1,10) +say 'Must be =' Tan(1) +exit -Get_Coeffs: procedure Expose a b a. - Parse Arg n - a=a.n - b=1 - Return - -Calc: procedure Expose a b a. - Parse Arg n - Temp=0 - do ni = n to 1 by -1 - Call Get_Coeffs ni - Temp = B/(A + Temp) - end - call Get_Coeffs 0 - return (A + Temp) +include Rational +include Functions +include Constants +include Abend diff --git a/Task/Convert-seconds-to-compound-duration/Crystal/convert-seconds-to-compound-duration.cr b/Task/Convert-seconds-to-compound-duration/Crystal/convert-seconds-to-compound-duration.cr new file mode 100644 index 0000000000..6b1371ff9d --- /dev/null +++ b/Task/Convert-seconds-to-compound-duration/Crystal/convert-seconds-to-compound-duration.cr @@ -0,0 +1,43 @@ +struct Number + def to_mixed_radix (*radices) + result = Array(self).new(radices.size, 0) + n = self + (0...radices.size).reverse_each do |i| + break if n == 0 + divisor = radices[i] + if divisor == 0 + result[i] = n + break + end + result[i] = n % divisor + n //= divisor + end + result + end +end + +def to_compound (num, radices, units) + num.to_mixed_radix(*radices).zip(units).compact_map {|n, u| + if n != 0 + "#{n} #{u}" + end + }.join(", ") +end + +def secs_to_compound (secs) + to_compound secs, {0, 7, 24, 60, 60}, ["wk", "d", "hr", "min", "sec"] +end + +puts "The task:" +[7259, 86400, 6000000].each do |n| + printf "%7s sec = %s\n", n, secs_to_compound(n) +end + +puts "\n(nobody asked for this):" +def inches_to_compound (inches) + to_compound inches, {0, 3, 8, 10, 22, 3, 12}, ["lea", "mi", "fur", "ch", "yd", "ft", "in"] +end + +[7259, 86400, 6000000].each do |n| + printf "%7s in = %s\n", n, inches_to_compound(n) +end diff --git a/Task/Convert-seconds-to-compound-duration/EasyLang/convert-seconds-to-compound-duration.easy b/Task/Convert-seconds-to-compound-duration/EasyLang/convert-seconds-to-compound-duration.easy index 71f79d847d..e8774b5e30 100644 --- a/Task/Convert-seconds-to-compound-duration/EasyLang/convert-seconds-to-compound-duration.easy +++ b/Task/Convert-seconds-to-compound-duration/EasyLang/convert-seconds-to-compound-duration.easy @@ -9,9 +9,7 @@ func$ split sec . r[5] = sec for i = 5 downto 1 if r[i] <> 0 - if s$ <> "" - s$ &= ", " - . + if s$ <> "" : s$ &= ", " s$ &= r[i] & " " & n$[i] . . diff --git a/Task/Convex-hull/EasyLang/convex-hull.easy b/Task/Convex-hull/EasyLang/convex-hull.easy index d6eaa5620b..c1744c7281 100644 --- a/Task/Convex-hull/EasyLang/convex-hull.easy +++ b/Task/Convex-hull/EasyLang/convex-hull.easy @@ -1,28 +1,23 @@ func orientation p[] q[] r[] . return (q[2] - p[2]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[2] - q[2]) . -proc calcConvexHull . pts[][] res[][] . - res[][] = [ ] +func[][] convexHull &pts[][] . indMinX = 1 for i to len pts[][] - if pts[i][1] < pts[indMinX][1] - indMinX = i - . + if pts[i][1] < pts[indMinX][1] : indMinX = i . p = indMinX repeat res[][] &= pts[p][] q = (p + 1) mod1 len pts[][] for i to len pts[][] - if orientation pts[p][] pts[i][] pts[q][] < 0 - q = i - . + if orientation pts[p][] pts[i][] pts[q][] < 0 : q = i . p = q until p = indMinX . + return res[][] . # pts[][] = [ [ 16 3 ] [ 12 17 ] [ 0 6 ] [ -4 -6 ] [ 16 6 ] [ 16 -7 ] [ 16 -3 ] [ 17 -4 ] [ 5 19 ] [ 19 -8 ] [ 3 16 ] [ 12 13 ] [ 3 -4 ] [ 17 5 ] [ -3 15 ] [ -3 -9 ] [ 0 11 ] [ -9 -3 ] [ -4 -2 ] [ 12 10 ] ] -calcConvexHull pts[][] res[][] -print res[][] +print convexHull pts[][] diff --git a/Task/Convex-hull/Zig/convex-hull.zig b/Task/Convex-hull/Zig/convex-hull.zig new file mode 100644 index 0000000000..b389404fdc --- /dev/null +++ b/Task/Convex-hull/Zig/convex-hull.zig @@ -0,0 +1,96 @@ +const std = @import("std"); +const print = std.debug.print; + +const Point = struct { + x: f32, + y: f32, + + pub fn format( + self: Point, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + try writer.print("Point{{ x: {d}, y: {d} }}", .{ self.x, self.y }); + } +}; + +fn calculateConvexHull(allocator: std.mem.Allocator, points: []const Point) ![]Point { + // There must be at least 3 points + if (points.len < 3) { + const result = try allocator.alloc(Point, points.len); + @memcpy(result, points); + return result; + } + + var hull = std.ArrayList(Point).init(allocator); + defer hull.deinit(); + + // Find the left most point in the polygon + var left_most_idx: usize = 0; + for (points, 0..) |p, i| { + if (p.x < points[left_most_idx].x) { + left_most_idx = i; + } + } + + var p = left_most_idx; + var q: usize = 0; + + while (true) { + // The left most point must be part of the hull + try hull.append(points[p]); + + q = (p + 1) % points.len; + + for (points, 0..) |_, i| { + if (orientation(&points[p], &points[i], &points[q]) == 2) { + q = i; + } + } + + p = q; + + // Break from loop once we reach the first point again + if (p == left_most_idx) break; + } + + return hull.toOwnedSlice(); +} + +// Calculate orientation for 3 points +// 0 -> Straight line +// 1 -> Clockwise +// 2 -> Counterclockwise +fn orientation(p: *const Point, q: *const Point, r: *const Point) usize { + const val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + + if (val == 0) return 0; + if (val > 0) return 1 else return 2; +} + +fn pt(x: i32, y: i32) Point { + return Point{ .x = @as(f32, @floatFromInt(x)), .y = @as(f32, @floatFromInt(y)) }; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const points = [_]Point{ + pt(16, 3), pt(12, 17), pt(0, 6), pt(-4, -6), pt(16, 6), + pt(16, -7), pt(16, -3), pt(17, -4), pt(5, 19), pt(19, -8), + pt(3, 16), pt(12, 13), pt(3, -4), pt(17, 5), pt(-3, 15), + pt(-3, -9), pt(0, 11), pt(-9, -3), pt(-4, -2), pt(12, 10), + }; + + const hull = try calculateConvexHull(allocator, &points); + defer allocator.free(hull); + + for (hull) |point| { + print("{}\n", .{point}); + } +} diff --git a/Task/Conways-Game-of-Life/EasyLang/conways-game-of-life.easy b/Task/Conways-Game-of-Life/EasyLang/conways-game-of-life.easy index 034323a473..743c19e0c4 100644 --- a/Task/Conways-Game-of-Life/EasyLang/conways-game-of-life.easy +++ b/Task/Conways-Game-of-Life/EasyLang/conways-game-of-life.easy @@ -3,24 +3,19 @@ time = 0.1 # nx = n + 1 subr init - for r = 1 to n - for c = 1 to n - i = r * nx + c - if randomf < 0.3 - f[i] = 1 - . + for r = 1 to n : for c = 1 to n + i = r * nx + c + if randomf < 0.3 + f[i] = 1 . . . f = 100 / n subr show - clear - for r = 1 to n - for c = 1 to n - if f[r * nx + c] = 1 - move c * f - f r * f - f - rect f * 0.9 f * 0.9 - . + gclear + for r = 1 to n : for c = 1 to n + if f[r * nx + c] = 1 + grect c * f - f r * f - f f * 0.9 f * 0.9 . . . diff --git a/Task/Copy-a-string/OPL/copy-a-string.opl b/Task/Copy-a-string/OPL/copy-a-string.opl new file mode 100644 index 0000000000..db34e40a63 --- /dev/null +++ b/Task/Copy-a-string/OPL/copy-a-string.opl @@ -0,0 +1,8 @@ +PROC main: + LOCAL src$(6),dst$(5) + src$="Hello" + dst$=src$ + src$="world!" + PRINT dst$,src$ + GET +ENDP diff --git a/Task/Copy-a-string/Uxntal/copy-a-string.uxnatl b/Task/Copy-a-string/Uxntal/copy-a-string.uxnatl new file mode 100644 index 0000000000..0b7adb7b1a --- /dev/null +++ b/Task/Copy-a-string/Uxntal/copy-a-string.uxnatl @@ -0,0 +1,25 @@ +%\n { 0a } %\0 { 00 } + +|18 @Console/write + +|100 + +;str2 ;str1 copy-str +;str2 print-str + +BRK + +@copy/str ( dest* src* -: ) + STH2 + &loop + LDAkr STH2k STAr INC2 LDAkr STHr INC2r ?/loop + POP2 POP2r + JMP2r + +@print/str_ ( str* -: ) + LDAk .Console/write DEO + INC2 @print/str LDAk ?/str_ + POP2 JMP2r + +@str1 "Uxntal \n \0 +@str2 diff --git a/Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck b/Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck new file mode 100644 index 0000000000..05e460ff31 --- /dev/null +++ b/Task/Copy-stdin-to-stdout/Objeck/copy-stdin-to-stdout.objeck @@ -0,0 +1,9 @@ +class StdInToOut { + function : Main(args : String[]) ~ Nil { + do { + input := System.IO.Console->ReadLine(); + System.IO.Console->PrintLine(input); + } + while(<>input->IsEmpty()); + } +} diff --git a/Task/Count-in-factors/EasyLang/count-in-factors.easy b/Task/Count-in-factors/EasyLang/count-in-factors.easy index cca0be932c..21f0ea2e67 100644 --- a/Task/Count-in-factors/EasyLang/count-in-factors.easy +++ b/Task/Count-in-factors/EasyLang/count-in-factors.easy @@ -1,4 +1,4 @@ -proc decompose num . primes[] . +proc decompose num &primes[] . primes[] = [ ] t = 2 while t * t <= num @@ -15,11 +15,8 @@ for i = 1 to 30 write i & ": " decompose i primes[] for j = 1 to len primes[] - if j > 1 - write " x " - . + if j > 1 : write " x " write primes[j] . print "" - primes[] = [ ] . diff --git a/Task/Count-in-factors/REXX/count-in-factors-1.rexx b/Task/Count-in-factors/REXX/count-in-factors-1.rexx deleted file mode 100644 index ef99c55868..0000000000 --- a/Task/Count-in-factors/REXX/count-in-factors-1.rexx +++ /dev/null @@ -1,37 +0,0 @@ -/*REXX program lists the prime factors of a specified integer (or a range of integers).*/ -@.=left('', 8); @.0="{unity} "; @.1='[prime] ' /*some tags and handy-dandy literals.*/ -parse arg LO HI @ . /*get optional arguments from the C.L. */ -if LO=='' | LO=="," then do; LO=1; HI=40; end /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= LO /* " " " " " " */ -if @=='' then @= 'x' /* " " " " " " */ -if length(@)\==1 then @= x2c(@) /*Not length 1? Then use hexadecimal. */ -tell= (HI>0) /*if HIGH is positive, then show #'s.*/ -HI= abs(HI) /*use the absolute value for HIGH. */ -w= length(HI) /*get maximum width for pretty output. */ -numeric digits max(9, w + 1) /*maybe bump the precision of numbers. */ -#= 0 /*the number of primes found (so far). */ - do n=abs(LO) to HI; f= factr(n) /*process a single number or a range.*/ - p= words( translate(f, ,@) ) - (n==1) /*P: is the number of prime factors. */ - if p==1 then #= # + 1 /*bump the primes counter (exclude N=1)*/ - if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/ - end /*n*/ -say -say right(#, w) ' primes found.' /*display the number of primes found. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -factr: procedure expose @; parse arg z 1 n,$; if z<2 then return z /*is Z too small?*/ - do while z//2==0; $= $||@||2; z= z%2; end /*maybe add factor of 2 */ - do while z//3==0; $= $||@||3; z= z%3; end /* " " " " 3 */ - do while z//5==0; $= $||@||5; z= z%5; end /* " " " " 5 */ - do while z//7==0; $= $||@||7; z= z%7; end /* " " " " 7 */ - - do j=11 by 6 while j<=z /*insure that J isn't divisible by 3.*/ - parse var j '' -1 _ /*get the last decimal digit of J. */ - if _\==5 then do while z//j==0; $=$||@||j; z= z%j; end /*maybe reduce Z.*/ - if _ ==3 then iterate /*Next # ÷ by 5? Skip. ___ */ - if j*j>n then leave /*are we higher than the √ N ? */ - y= j + 2 /*obtain the next odd divisor. */ - do while z//y==0; $=$||@||y; z= z%y; end /*maybe reduce Z.*/ - end /*j*/ - if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/ - return substr($||@||z, 1+length(@) ) /*elide superfluous header. */ diff --git a/Task/Count-in-factors/REXX/count-in-factors-2.rexx b/Task/Count-in-factors/REXX/count-in-factors-2.rexx deleted file mode 100644 index 70b0c19ee5..0000000000 --- a/Task/Count-in-factors/REXX/count-in-factors-2.rexx +++ /dev/null @@ -1,51 +0,0 @@ -/*REXX program lists the prime factors of a specified integer (or a range of integers).*/ -@.=left('', 8); @.0="{unity} "; @.1='[prime] ' /*some tags and handy-dandy literals.*/ -parse arg LO HI @ . /*get optional arguments from the C.L. */ -if LO=='' | LO=="," then do; LO=1; HI=40; end /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= LO /* " " " " " " */ -if @=='' then @= 'x' /* " " " " " " */ -if length(@)\==1 then @= x2c(@) /*Not length 1? Then use hexadecimal. */ -tell= (HI>0) /*if HIGH is positive, then show #'s.*/ -HI= abs(HI) /*use the absolute value for HIGH. */ -w= length(HI) /*get maximum width for pretty output. */ -numeric digits max(9, w + 1) /*maybe bump the precision of numbers. */ -#= 0 /*the number of primes found (so far). */ - do n=abs(LO) to HI; f= factr(n) /*process a single number or a range.*/ - p= words( translate(f, ,@) ) - (n==1) /*P: is the number of prime factors. */ - if p==1 then #= # + 1 /*bump the primes counter (exclude N=1)*/ - if tell then say right(n, w) '=' @.p f /*display if a prime, plus its factors.*/ - end /*n*/ -say -say right(#, w) ' primes found.' /*display the number of primes found. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -factr: procedure expose @; parse arg z 1 n,$; if z<2 then return z /*is Z too small?*/ - do while z// 2==0; $= $||@||2 ; z= z%2 ; end /*maybe add factor of 2 */ - do while z// 3==0; $= $||@||3 ; z= z%3 ; end /* " " " " 3 */ - do while z// 5==0; $= $||@||5 ; z= z%5 ; end /* " " " " 5 */ - do while z// 7==0; $= $||@||7 ; z= z%7 ; end /* " " " " 7 */ - do while z//11==0; $= $||@||11; z= z%11; end /* " " " " 11 */ - do while z//13==0; $= $||@||13; z= z%13; end /* " " " " 13 */ - do while z//17==0; $= $||@||17; z= z%17; end /* " " " " 17 */ - do while z//19==0; $= $||@||19; z= z%19; end /* " " " " 19 */ - do while z//23==0; $= $||@||23; z= z%23; end /* " " " " 23 */ - do while z//29==0; $= $||@||29; z= z%29; end /* " " " " 29 */ - do while z//31==0; $= $||@||31; z= z%31; end /* " " " " 31 */ - do while z//37==0; $= $||@||37; z= z%37; end /* " " " " 37 */ - if z>40 then do; t= z; q= 1; r= 0; do while q<=t; q= q * 4 - end /*while*/ - do while q>1; q=q%4; _=t-r-q; r=r%2; if _>=0 then do; t=_; r=r+q - end - end /*while*/ /* [↑] find integer SQRT(z). */ - /*R: is the integer SQRT of Z.*/ - do j=41 by 6 to r while j<=z /*insure J isn't divisible by 3*/ - parse var j '' -1 _ /*get last decimal digit of J.*/ - if _\==5 then do while z//j==0; $=$||@||j; z= z%j; end - if _ ==3 then iterate /*Next number ÷ by 5 ? Skip.*/ - y= j + 2 /*use the next (odd) divisor. */ - do while z//y==0; $=$||@||y; z= z%y; end - end /*j*/ /* [↑] reduce Z by Y ? */ - end /*if z>40*/ - - if z==1 then return substr($, 1+length(@) ) /*Is residual=1? Don't add 1*/ - return substr($||@||z, 1+length(@) ) /*elide superfluous header. */ diff --git a/Task/Count-in-factors/REXX/count-in-factors-3.rexx b/Task/Count-in-factors/REXX/count-in-factors.rexx similarity index 61% rename from Task/Count-in-factors/REXX/count-in-factors-3.rexx rename to Task/Count-in-factors/REXX/count-in-factors.rexx index da6ee80ca5..23b203b666 100644 --- a/Task/Count-in-factors/REXX/count-in-factors-3.rexx +++ b/Task/Count-in-factors/REXX/count-in-factors.rexx @@ -1,6 +1,8 @@ -call Time('r') -say 'Count in factors - Using REXX libraries' -parse version version; say version +-- 25 Apr 2025 +include Settings + +say 'COUNT IN FACTORS' +say version say numeric digits 16 call CountFactors 1,20 @@ -9,7 +11,7 @@ call CountFactors 1e6,1e6+20 call CountFactors 1e9,1e9+20 call CountFactors 1e12,1e12+20 call CountFactors 1e15,1e15+20 -say Format(Time('e'),,3) 'seconds' +call Timer exit CountFactors: @@ -17,15 +19,15 @@ arg x,y say 'Factorization of the numbers' x 'to' y say do i = x to y - f = Factors(i) if i = 1 then s = '1 = 1' - else - s = i '=' - do j = 1 to f - s = s fact.factor.j - if j < f then - s = s 'x' + else do + s = i '='; f = Factors(i) + do j = 1 to f + s = s fact.j + if j < f then + s = s 'x' + end end say s end @@ -35,3 +37,5 @@ return include Numbers include Sequences include Functions +include Helper +include Abend diff --git a/Task/Count-in-octal/Ballerina/count-in-octal.ballerina b/Task/Count-in-octal/Ballerina/count-in-octal.ballerina new file mode 100644 index 0000000000..4a7519d379 --- /dev/null +++ b/Task/Count-in-octal/Ballerina/count-in-octal.ballerina @@ -0,0 +1,28 @@ +import ballerina/io; + +function reverse(string s) returns string { + string res = ""; + foreach int i in int:range(s.length() - 1, -1, -1) { + res += s[i]; + } + return res; +} + +function oct(int m) returns string { + if m <= 0 { return "0"; } + int n = m ; // make mutable + string res = ""; + while n > 0 { + res += (n % 8).toString(); + n /= 8; + } + return reverse(res); +} + +public function main() { + int i = 0; + while true { + io:println(oct(i)); + i += 1; + } +} diff --git a/Task/Cramers-rule/EasyLang/cramers-rule.easy b/Task/Cramers-rule/EasyLang/cramers-rule.easy index 826f0c1e40..737db12126 100644 --- a/Task/Cramers-rule/EasyLang/cramers-rule.easy +++ b/Task/Cramers-rule/EasyLang/cramers-rule.easy @@ -1,13 +1,11 @@ -proc det . a0[][] res . +func det &a0[][] . res = 1 a[][] = a0[][] n = len a[][] for j to n imax = j for i = j + 1 to n - if a[i][j] > a[imax][j] - imax = i - . + if a[i][j] > a[imax][j] : imax = i . if imax <> j swap a[imax][] a[j][] @@ -15,8 +13,7 @@ proc det . a0[][] res . . if abs a[j][j] < 1e-12 print "Singular matrix!" - res = 0 / 0 - return + return 0 / 0 . for i = j + 1 to n mult = -a[i][j] / a[j][j] @@ -25,22 +22,19 @@ proc det . a0[][] res . . . . - for i to n - res *= a[i][i] - . + for i to n : res *= a[i][i] + return res . -proc cramer_solve . a0[][] deta b[] col res . +func cramer_solve &a0[][] deta &b[] col . a[][] = a0[][] for i to len a[][] a[i][col] = b[i] . - det a[][] d - res = d / deta + return det a[][] / deta . a[][] = [ [ 2 -1 5 1 ] [ 3 2 2 -6 ] [ 1 3 3 -1 ] [ 5 -2 -3 3 ] ] b[] = [ -3 -32 -47 49 ] -det a[][] deta +deta = det a[][] for i to len a[][] - cramer_solve a[][] deta b[] i r - print r + print cramer_solve a[][] deta b[] i . diff --git a/Task/Create-a-file-on-magnetic-tape/JavaScript/create-a-file-on-magnetic-tape.js b/Task/Create-a-file-on-magnetic-tape/JavaScript/create-a-file-on-magnetic-tape.js new file mode 100644 index 0000000000..ec1a23ac9c --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/JavaScript/create-a-file-on-magnetic-tape.js @@ -0,0 +1,2 @@ +const fs = require('fs'); +fs.writeFile('/dev/tape', 'text\n', 'utf8', () => {}); diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Uiua/create-a-two-dimensional-array-at-runtime.uiua b/Task/Create-a-two-dimensional-array-at-runtime/Uiua/create-a-two-dimensional-array-at-runtime.uiua new file mode 100644 index 0000000000..caa43e89ca --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Uiua/create-a-two-dimensional-array-at-runtime.uiua @@ -0,0 +1,7 @@ +⋕&sc &pf "Enter a width: " +⋕&sc &pf "Enter a height: " +˜↯0⊟ # create 2D array filled with 0 +⍜⊡⋅3 1_2 # store 3 at row 1, col 2 +⟜&s # show array non-destructively +⊡1_2 # retrieve element at row 1, col 2 + # this also destroys the array diff --git a/Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 b/Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 new file mode 100644 index 0000000000..fd3ff6cb00 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/XPL0/create-an-object-at-a-given-address.xpl0 @@ -0,0 +1,15 @@ +int Obj; \create an integer object +char Addr; +[HexOut(0, @Obj); \print the machine address of the object (relative to some base) +CrLf(0); +Addr:= @Obj; \take the address of the object and +Addr(0):= $78; \ create another integer object at this address +Addr(1):= $56; +Addr(2):= $34; +Addr(3):= $12; +HexOut(0, Obj); \print the value of this object to verify that +CrLf(0); \ it is same as one of the origin +Obj:= $DEADBEEF; \change the value of the origin and verify it again +HexOut(0, Obj); +CrLf(0); +] diff --git a/Task/Cuban-primes/EasyLang/cuban-primes.easy b/Task/Cuban-primes/EasyLang/cuban-primes.easy index 69a869b15b..8140fa46a5 100644 --- a/Task/Cuban-primes/EasyLang/cuban-primes.easy +++ b/Task/Cuban-primes/EasyLang/cuban-primes.easy @@ -1,27 +1,24 @@ -fastfunc isprim_odd num . - i = 3 +fastfunc isprim num . + if num mod 2 = 0 : return 0 + if num mod 3 = 0 : return 0 + i = 5 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 + if num mod i = 0 : return 0 + i += 4 . return 1 . -numfmt 0 7 i = 1 -while cnt < 100000 +while cnt < 50000 di = 3 * i * (i + 1) + 1 - if isprim_odd di = 1 + if isprim di = 1 cnt += 1 - if cnt <= 200 - write di & " " - if cnt mod 5 = 0 - print "" - . - . + if cnt <= 200 : write di & " " . i += 1 . print "" +print "" print di diff --git a/Task/Cuban-primes/OCaml/cuban-primes.ml b/Task/Cuban-primes/OCaml/cuban-primes.ml new file mode 100644 index 0000000000..af8c106059 --- /dev/null +++ b/Task/Cuban-primes/OCaml/cuban-primes.ml @@ -0,0 +1,51 @@ +let is_prime (n : int) : bool = + if n = 2 then true else if n < 2 || n mod 2 = 0 then false else + let lim = (n |> float_of_int |> sqrt |> int_of_float) + 1 in + let rec loop = function + | i when i > lim -> true + | i when n mod i = 0 -> false + | i -> loop (i + 2) + in loop 3 + +let char_list_of_string s = List.init (String.length s) (String.get s) + +let commatize (str : string) : string = + let revchars = List.rev (char_list_of_string str) in + let rec take_threes = function + | s, c1 :: c2 :: c3 :: rest -> + take_threes ([c3; c2; c1] :: s, rest) + | ss, rest -> if rest = [] then ss else List.rev rest :: ss + in take_threes ([], List.map Char.escaped revchars) + |> List.map (String.concat "") |> String.concat "," + +let cube (n: int) : int = n * n * n + +let scan_for_cubans (num : int) : int list = + let rec loop = function + | n, ps when List.length ps >= num -> ps + | n, ps -> + let c = cube (n + 1) - cube n in + if is_prime c then loop (n + 1, c :: ps) + else loop (n + 1, ps) in + loop (1, []) |> List.rev + +let nth_cuban (n : int) : int = + let rec loop = function + | i, c, p when c = n -> p + | i, c, p -> + let k = cube (i + 1) - cube i in + if is_prime k then loop (i + 1, c + 1, k) + else loop (i + 1, c, p) in + loop (0, 0, 0) + +let () = + print_endline "The first 200 cuban primes are: "; + scan_for_cubans 200 + |> List.map string_of_int + |> List.map commatize + |> String.concat " | " + |> Printf.printf "[%s]\n\n"; + nth_cuban 100_000 + |> string_of_int + |> commatize + |> Printf.printf "The 100,000th cuban prime is %s\n" diff --git a/Task/Cuban-primes/REXX/cuban-primes-1.rexx b/Task/Cuban-primes/REXX/cuban-primes-1.rexx deleted file mode 100644 index c12e91bb2d..0000000000 --- a/Task/Cuban-primes/REXX/cuban-primes-1.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program finds and displays a number of cuban primes or the Nth cuban prime. */ -numeric digits 20 /*ensure enough decimal digits for #s. */ -parse arg N . /*obtain optional argument from the CL.*/ -if N=='' | N=="," then N= 200 /*Not specified? Then use the default.*/ -Nth= N<0; N= abs(N) /*used for finding the Nth cuban prime.*/ -@.=0; @.0=1; @.2=1; @.3=1; @.4=1; @.5=1; @.6=1; @.8=1 /*ending digs that aren't cubans.*/ -sw= linesize() - 1; if sw<1 then sw= 79 /*obtain width of the terminal screen. */ -w=12; #= 1; $= right(7, w) /*start with first cuban prime; count.*/ - do j=1 until #=>N; x= (j+1)**3 - j**3 /*compute a possible cuban prime. */ - parse var x '' -1 _; if @._ then iterate /*check last digit for non─cuban prime.*/ - do k=1 until km*km>x; km= k*6 + 1 /*cuban primes can't be ÷ by 6k+1 */ - if x//km==0 then iterate j /*Divisible? Then not a cuban prime. */ - end /*k*/ - #= #+1 /*bump the number of cuban primes found*/ - if Nth then do; if #==N then do; say commas(x); leave j; end /*display 1 num.*/ - else iterate /*j*/ /*keep searching*/ - end /* [↑] try to fit as many #s per line.*/ - cx= commas(x); L= length(cx) /*insert commas──►X; obtain the length.*/ - cx= right(cx, max(w, L) ); new= $ cx /*right justify CX; concat to new list*/ - if length(new)>sw then do; say $; $= cx /*line is too long, display #'s so far.*/ - end /* [↑] initialize the (new) next line.*/ - else $= new /*start with cuban # that wouldn't fit.*/ - end /*j*/ - if \Nth & $\=='' then say $ /*check for residual cuban primes in $.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ diff --git a/Task/Cuban-primes/REXX/cuban-primes-2.rexx b/Task/Cuban-primes/REXX/cuban-primes.rexx similarity index 92% rename from Task/Cuban-primes/REXX/cuban-primes-2.rexx rename to Task/Cuban-primes/REXX/cuban-primes.rexx index f10b489598..6e36b4e1e0 100644 --- a/Task/Cuban-primes/REXX/cuban-primes-2.rexx +++ b/Task/Cuban-primes/REXX/cuban-primes.rexx @@ -1,6 +1,7 @@ include Settings - -say version; say 'Cuban primes'; say +say 'CUBAN PRIMES - 3 Mar 2025' +say version +say numeric digits 20 call ShowCubans 1,200,8 call ShowCubans 100000,,13 diff --git a/Task/Cumulative-standard-deviation/EasyLang/cumulative-standard-deviation.easy b/Task/Cumulative-standard-deviation/EasyLang/cumulative-standard-deviation.easy index 58aa6b4817..72e795da02 100644 --- a/Task/Cumulative-standard-deviation/EasyLang/cumulative-standard-deviation.easy +++ b/Task/Cumulative-standard-deviation/EasyLang/cumulative-standard-deviation.easy @@ -1,12 +1,11 @@ global sum sum2 n . -proc sd x . r . +func sd x . sum += x sum2 += x * x n += 1 - r = sqrt (sum2 / n - sum * sum / n / n) + return sqrt (sum2 / n - sum * sum / n / n) . v[] = [ 2 4 4 4 5 5 7 9 ] for v in v[] - sd v r - print v & " " & r + print v & " " & sd v . diff --git a/Task/Currency/Ballerina/currency.ballerina b/Task/Currency/Ballerina/currency.ballerina new file mode 100644 index 0000000000..94a706246d --- /dev/null +++ b/Task/Currency/Ballerina/currency.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +public function main() { + decimal hamburgers = 4000000000000000; + decimal milkshakes = 2; + decimal price1 = 5.5; + decimal price2 = 2.86; + decimal taxPc = 0.0765; + decimal totalPreTax = hamburgers * price1 + milkshakes * price2; + decimal totalTax = taxPc * totalPreTax; + decimal totalAfterTax = totalPreTax + totalTax; + io:println("Total price before tax : ", totalPreTax.round(2)); + io:println("Tax : ", totalTax.round(2)); + io:println("Total price after tax : ", totalAfterTax.round(2)); +} diff --git a/Task/Currency/C++/currency.cpp b/Task/Currency/C++/currency.cpp new file mode 100644 index 0000000000..ea15245678 --- /dev/null +++ b/Task/Currency/C++/currency.cpp @@ -0,0 +1,21 @@ +#include + +struct menu_entry { + mpz_class amount; + std::string name; + mpf_class price; +}; + +int main() { + menu_entry menu[] = { 4000000000000000, "hamburgers", 5.50, + 2, "milkshakes", 2.86 }; + mpf_class taxRate; + taxRate.set_str("0.0765", 10); + mpf_class total = 0; + for (menu_entry i : menu) + total += i.price * i.amount; + gmp_printf("total: €%.2Ff\n", total.get_mpf_t()); + mpf_class tax = total * taxRate; + gmp_printf("tax: €%.2Ff\n", tax.get_mpf_t()); + gmp_printf("total+tax: €%.2Ff\n", mpf_class{total+tax}.get_mpf_t()); +} diff --git a/Task/Currency/Wren/currency.wren b/Task/Currency/Wren/currency.wren index 56479aae74..6cf58ddbd8 100644 --- a/Task/Currency/Wren/currency.wren +++ b/Task/Currency/Wren/currency.wren @@ -5,7 +5,6 @@ var milkshakes = BigRat.two var price1 = BigRat.fromFloat(5.5) var price2 = BigRat.fromFloat(2.86) var taxPc = BigRat.fromFloat(0.0765) -var totalPc = BigRat.fromFloat(1.0765) var totalPreTax = hamburgers*price1 + milkshakes*price2 var totalTax = taxPc * totalPreTax var totalAfterTax = totalPreTax + totalTax diff --git a/Task/Currying/Ballerina/currying.ballerina b/Task/Currying/Ballerina/currying.ballerina new file mode 100644 index 0000000000..714a8b83de --- /dev/null +++ b/Task/Currying/Ballerina/currying.ballerina @@ -0,0 +1,12 @@ +import ballerina/io; + +public function main() { + var addN = function(int n) returns (function(int) returns int) { + return function(int x) returns int { + return n + x; + }; + }; + + var adder = addN(40); + io:println("The answer to life is ", adder(2), "."); +} diff --git a/Task/Curzon-numbers/Ada/curzon-numbers.ada b/Task/Curzon-numbers/Ada/curzon-numbers.ada new file mode 100644 index 0000000000..31133f80d5 --- /dev/null +++ b/Task/Curzon-numbers/Ada/curzon-numbers.ada @@ -0,0 +1,57 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Long_Long_Integer_Text_IO; use Ada.Long_Long_Integer_Text_IO; + +procedure Curzon is + + function Mod_Pow(Base, Exp, Modulo : Long_Long_Integer) return Long_Long_Integer is + Result : Long_Long_Integer := 1; + B : Long_Long_Integer := Base mod Modulo; + E : Long_Long_Integer := Exp; + begin + if Modulo = 1 then return 0; end if; + + while E > 0 loop + if (E mod 2) = 1 then + Result := (Result * B) mod Modulo; + end if; + B := (B * B) mod Modulo; + E := E / 2; + end loop; + + return Result; + end Mod_Pow; + + function Curzon_Check(K, N : Long_Long_Integer) return Boolean is + R : Long_Long_Integer := K * N; + begin + return Mod_Pow(K, N, R + 1) = R; + end Curzon_Check; + + N : Long_Long_Integer; + Count : Integer; + +begin + for K in Long_Long_Integer range 2..10 when K mod 2 = 0 loop + Put("The first 50 Curzon numbers of base "); Put(K, 1); Put(":"); New_Line; + N := 1; + Count := 1; + while Count <= 1000 loop + if Curzon_Check(K, N) then + if Count <= 50 then + Put(N, 4); + if Count mod 10 = 0 then + New_Line; + else + Put(" "); + end if; + end if; + if Count = 1000 then + Put("The 1000th Curzon number of base "); Put(K, 1); Put(": "); Put(N, 5); + New_Line(2); + end if; + Count := @ + 1; + end if; + N := @ + 1; + end loop; + end loop; +end Curzon; diff --git a/Task/Curzon-numbers/EasyLang/curzon-numbers.easy b/Task/Curzon-numbers/EasyLang/curzon-numbers.easy index 377ecd0a69..4af14d89ff 100644 --- a/Task/Curzon-numbers/EasyLang/curzon-numbers.easy +++ b/Task/Curzon-numbers/EasyLang/curzon-numbers.easy @@ -12,7 +12,7 @@ func pow_mod b power modulus . for k = 2 step 2 to 10 numfmt 0 0 print "First 50 Curzon numbers using a base of " & k & ":" - numfmt 0 4 + numfmt 4 0 n = 1 count = 0 repeat @@ -22,9 +22,7 @@ for k = 2 step 2 to 10 count += 1 if count <= 50 write " " & n - if count mod 9 = 0 - print "" - . + if count mod 9 = 0 : print "" . . until count = 1000 diff --git a/Task/Cut-a-rectangle/EasyLang/cut-a-rectangle.easy b/Task/Cut-a-rectangle/EasyLang/cut-a-rectangle.easy index adf933a05a..fb028df61c 100644 --- a/Task/Cut-a-rectangle/EasyLang/cut-a-rectangle.easy +++ b/Task/Cut-a-rectangle/EasyLang/cut-a-rectangle.easy @@ -1,7 +1,7 @@ global grid[] blen w h cnt . dir[][] = [ [ 0 -1 ] [ -1 0 ] [ 0 1 ] [ 1 0 ] ] # -proc walk y x . . +proc walk y x . if y = 0 or y = h or x = 0 or x = w cnt += 2 return @@ -20,12 +20,10 @@ proc walk y x . . grid[t] -= 1 grid[blen - t] -= 1 . -proc solve hh ww recur . . +proc solve hh ww recur . w = ww h = hh - if h mod 2 = 1 - swap h w - . + if h mod 2 = 1 : swap h w if h mod 2 = 1 cnt = 0 return @@ -63,7 +61,7 @@ proc solve hh ww recur . . solve w h 0 . . -proc main . . +proc main . for y = 1 to 8 for x = 1 to y if x mod 2 = 0 or y mod 2 = 0 diff --git a/Task/Cyclops-numbers/EasyLang/cyclops-numbers.easy b/Task/Cyclops-numbers/EasyLang/cyclops-numbers.easy index 24688034b0..f8fa7814c0 100644 --- a/Task/Cyclops-numbers/EasyLang/cyclops-numbers.easy +++ b/Task/Cyclops-numbers/EasyLang/cyclops-numbers.easy @@ -1,7 +1,5 @@ func is_cyclops n . - if n = 0 - return 1 - . + if n = 0 : return 1 m = n mod 10 while m <> 0 count += 1 @@ -20,9 +18,7 @@ func is_cyclops n . fastfunc isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 @@ -51,7 +47,7 @@ func is_palindr n . . return if n = k . -proc show . . +proc show . while cnt < 50 if is_cyclops i = 1 write i & " " diff --git a/Task/Cyclops-numbers/REXX/cyclops-numbers.rexx b/Task/Cyclops-numbers/REXX/cyclops-numbers.rexx index a5180ac70f..858afb6424 100644 --- a/Task/Cyclops-numbers/REXX/cyclops-numbers.rexx +++ b/Task/Cyclops-numbers/REXX/cyclops-numbers.rexx @@ -1,42 +1,24 @@ +-- 22 Mar 2025 include Settings -say version; say 'Cyclops numbers'; say +say 'CYCLOPS NUMBERS' +say version +say numeric digits 10; cycl. = 0 -call GetCyclops 115e6 -call Cyclops +call Cyclops 115e6 +say cycl.0 'cyclops numbers generated < 115 million'; say +call CyclopsNumbers call PrimeCyclops -call BlindPrimeCyclops -call PalPrimeCyclops +call BlindCyclops +call PalindromicCyclops say Format(Time('e'),,3) 'seconds' exit -GetCyclops: -procedure expose cycl. -arg x -m = 0; n = 1; cycl.cyclop.1 = 0 -do f = 1 - h = m+1; m = n - do j = 1 to 9 - do i = h to m - a = cycl.cyclop.i - do k = 1 to 9 - b = j||a||k - if b > x then - leave f - n = n+1; cycl.cyclop.n = b - end - end - end -end -cycl.0 = n -say n 'cyclops numbers generated <' x; say -return - -Cyclops: +CyclopsNumbers: procedure expose cycl. say 'First 50 cyclop numbers:' do i = 1 to cycl.0 - a = cycl.cyclop.i + a = cycl.i if i <= 50 then do call Charout ,Right(a,8) if i//10 = 0 then @@ -54,7 +36,7 @@ procedure expose cycl. say 'First 50 prime cyclop numbers:' n = 0 do i = 2 to cycl.0 - a = cycl.cyclop.i + a = cycl.i if Prime(a) then do n = n+1 if n <= 50 then do @@ -70,12 +52,12 @@ do i = 2 to cycl.0 end return -BlindPrimeCyclops: +BlindCyclops: procedure expose cycl. say 'First 50 blind prime cyclop numbers:' n = 0 do i = 2 to cycl.0 - a = cycl.cyclop.i + a = cycl.i if Prime(a) then do l = Length(a); m = l%2; b = Left(a,m)||Right(a,m) if Prime(b) then do @@ -94,12 +76,12 @@ do i = 2 to cycl.0 end return -PalPrimeCyclops: +PalindromicCyclops: procedure expose cycl. say 'First 50 palindromic prime cyclop numbers:' n = 0 do i = 2 to cycl.0 - a = cycl.cyclop.i + a = cycl.i if a = Reverse(a) then do if Prime(a) then do n = n+1 @@ -117,5 +99,7 @@ do i = 2 to cycl.0 end return +include Sequences include Numbers include Functions +include Abend diff --git a/Task/Cyclotomic-polynomial/JavaScript/cyclotomic-polynomial.js b/Task/Cyclotomic-polynomial/JavaScript/cyclotomic-polynomial.js new file mode 100644 index 0000000000..7690d386c5 --- /dev/null +++ b/Task/Cyclotomic-polynomial/JavaScript/cyclotomic-polynomial.js @@ -0,0 +1,504 @@ +const MAX_ALL_FACTORS = 100000; +const algorithm = 2; +let divisions = 0; + +// Term class +class Term { + constructor(c, e) { + this.m_coefficient = c; + this.m_exponent = e; + } + + coefficient() { + return this.m_coefficient; + } + + degree() { + return this.m_exponent; + } + + negated() { + return new Term(-this.m_coefficient, this.m_exponent); + } + + multiply(rhs) { + return new Term(this.m_coefficient * rhs.m_coefficient, this.m_exponent + rhs.m_exponent); + } + + add(rhs) { + if (this.m_exponent !== rhs.m_exponent) { + throw new Error("Exponents not equal"); + } + return new Term(this.m_coefficient + rhs.m_coefficient, this.m_exponent); + } + + toString() { + if (this.m_coefficient === 0) { + return '0'; + } + if (this.m_exponent === 0) { + return this.m_coefficient.toString(); + } + if (this.m_coefficient === 1) { + if (this.m_exponent === 1) { + return 'x'; + } + return `x^${this.m_exponent}`; + } + if (this.m_coefficient === -1) { + if (this.m_exponent === 1) { + return "-x"; + } + return `-x^${this.m_exponent}`; + } + if (this.m_exponent === 1) { + return `${this.m_coefficient}x`; + } + return `${this.m_coefficient}x^${this.m_exponent}`; + } +} + +// Polynomial class +class Polynomial { + constructor(values) { + this.polynomialTerms = []; + + if (values === undefined) { + this.polynomialTerms.push(new Term(0, 0)); + } else if (Array.isArray(values) && values.length % 2 === 0) { + for (let i = 0; i < values.length; i += 2) { + this.polynomialTerms.push(new Term(values[i], values[i+1])); + } + this.polynomialTerms.sort((t, u) => u.degree() - t.degree()); + } else if (Array.isArray(values)) { + if (values.length === 0) { + this.polynomialTerms.push(new Term(0, 0)); + } else { + for (let t of values) { + if (t.coefficient() !== 0) { + this.polynomialTerms.push(t); + } + } + if (this.polynomialTerms.length === 0) { + this.polynomialTerms.push(new Term(0, 0)); + } + this.polynomialTerms.sort((t, u) => u.degree() - t.degree()); + } + } + } + + leadingCoefficient() { + return this.polynomialTerms[0].coefficient(); + } + + degree() { + return this.polynomialTerms[0].degree(); + } + + hasCoefficientAbs(coeff) { + for (let term of this.polynomialTerms) { + if (Math.abs(term.coefficient()) === coeff) { + return true; + } + } + return false; + } + + addTerm(term) { + const termList = []; + let added = false; + + for (let index = 0; index < this.polynomialTerms.length; index++) { + const currentTerm = this.polynomialTerms[index]; + if (currentTerm.degree() === term.degree()) { + added = true; + if (currentTerm.coefficient() + term.coefficient() !== 0) { + termList.push(currentTerm.add(term)); + } + } else { + termList.push(currentTerm); + } + } + + if (!added) { + termList.push(term); + } + + return new Polynomial(termList); + } + + multiplyByTerm(term) { + const termList = []; + + for (let index = 0; index < this.polynomialTerms.length; index++) { + const currentTerm = this.polynomialTerms[index]; + termList.push(currentTerm.multiply(term)); + } + + return new Polynomial(termList); + } + + add(p) { + const termList = []; + let thisCount = this.polynomialTerms.length; + let polyCount = p.polynomialTerms.length; + + while (thisCount > 0 || polyCount > 0) { + if (thisCount === 0) { + const polyTerm = p.polynomialTerms[polyCount - 1]; + termList.push(polyTerm); + polyCount--; + } else if (polyCount === 0) { + const thisTerm = this.polynomialTerms[thisCount - 1]; + termList.push(thisTerm); + thisCount--; + } else { + const polyTerm = p.polynomialTerms[polyCount - 1]; + const thisTerm = this.polynomialTerms[thisCount - 1]; + + if (thisTerm.degree() === polyTerm.degree()) { + const t = thisTerm.add(polyTerm); + if (t.coefficient() !== 0) { + termList.push(t); + } + thisCount--; + polyCount--; + } else if (thisTerm.degree() < polyTerm.degree()) { + termList.push(thisTerm); + thisCount--; + } else { + termList.push(polyTerm); + polyCount--; + } + } + } + + return new Polynomial(termList); + } + + divide(v) { + divisions++; + + let q = new Polynomial(); + let r = new Polynomial(this.polynomialTerms); + const lcv = v.leadingCoefficient(); + const dv = v.degree(); + + while (r.degree() >= v.degree()) { + const lcr = r.leadingCoefficient(); + const s = Math.floor(lcr / lcv); + const term = new Term(s, r.degree() - dv); + q = q.addTerm(term); + r = r.add(v.multiplyByTerm(term.negated())); + } + + return q; + } + + toString() { + if (this.polynomialTerms.length === 0) { + return '0'; + } + + let result = this.polynomialTerms[0].toString(); + + for (let i = 1; i < this.polynomialTerms.length; i++) { + const term = this.polynomialTerms[i]; + if (term.coefficient() > 0) { + result += ` + ${term.toString()}`; + } else { + result += ` - ${term.negated().toString()}`; + } + } + + return result; + } +} + +function getDivisors(number) { + const divisors = []; + const root = Math.floor(Math.sqrt(number)); + + for (let i = 1; i <= root; i++) { + if (number % i === 0) { + divisors.push(i); + const div = Math.floor(number / i); + if (div !== i && div !== number) { + divisors.push(div); + } + } + } + + return divisors; +} + +const allFactors = new Map(); + +function getFactors(number) { + if (allFactors.has(number)) { + return allFactors.get(number); + } + + const factors = new Map(); + + if (number % 2 === 0) { + const factorsDivTwo = getFactors(number / 2); + for (const [key, value] of factorsDivTwo) { + factors.set(key, value); + } + factors.set(2, (factors.get(2) || 0) + 1); + + if (number < MAX_ALL_FACTORS) { + allFactors.set(number, factors); + } + + return factors; + } + + const root = Math.floor(Math.sqrt(number)); + let i = 3; + + while (i <= root) { + if (number % i === 0) { + const factorsDivI = getFactors(number / i); + for (const [key, value] of factorsDivI) { + factors.set(key, value); + } + factors.set(i, (factors.get(i) || 0) + 1); + + if (number < MAX_ALL_FACTORS) { + allFactors.set(number, factors); + } + + return factors; + } + i += 2; + } + + factors.set(number, 1); + + if (number < MAX_ALL_FACTORS) { + allFactors.set(number, factors); + } + + return factors; +} + +const COMPUTED = new Map(); + +function cyclotomicPolynomial(n) { + if (COMPUTED.has(n)) { + return COMPUTED.get(n); + } + + if (n === 1) { + // Polynomial: x - 1 + const p = new Polynomial([1, 1, -1, 0]); + COMPUTED.set(1, p); + return p; + } + + const factors = getFactors(n); + + if (factors.has(n)) { + // n prime + const termList = []; + for (let index = 0; index < n; index++) { + termList.push(new Term(1, index)); + } + + const cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } else if (factors.size === 2 && factors.has(2) && factors.get(2) === 1 && factors.has(n / 2) && factors.get(n / 2) === 1) { + // n = 2p + const prime = n / 2; + const termList = []; + let coeff = -1; + + for (let index = 0; index < prime; index++) { + coeff *= -1; + termList.push(new Term(coeff, index)); + } + + const cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } else if (factors.size === 1 && factors.has(2)) { + // n = 2^h + const h = factors.get(2); + const termList = []; + termList.push(new Term(1, Math.pow(2, h - 1))); + termList.push(new Term(1, 0)); + + const cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } else if (factors.size === 1 && factors.has(n)) { + // n = p^k + let p = 0; + let k = 0; + + for (const [key, value] of factors) { + p = key; + k = value; + } + + const termList = []; + for (let index = 0; index < p; index++) { + termList.push(new Term(1, index * Math.pow(p, k - 1))); + } + + const cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } else if (factors.size === 2 && factors.has(2)) { + // n = 2^h * p^k + let p = 0; + + for (const [key, value] of factors) { + if (key !== 2) { + p = key; + } + } + + const termList = []; + let coeff = -1; + const twoExp = Math.pow(2, factors.get(2) - 1); + const k = factors.get(p); + + for (let index = 0; index < p; index++) { + coeff *= -1; + termList.push(new Term(coeff, index * twoExp * Math.pow(p, k - 1))); + } + + const cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } else if (factors.has(2) && ((n / 2) % 2 === 1) && (n / 2) > 1) { + // CP(2m)[x] = CP(-m)[x], n odd integer > 1 + const cycloDiv2 = cyclotomicPolynomial(n / 2); + const termList = []; + + for (const term of cycloDiv2.polynomialTerms) { + if (term.degree() % 2 === 0) { + termList.push(term); + } else { + termList.push(term.negated()); + } + } + + const cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } + + // General Case + if (algorithm === 0) { + // slow - uses basic definition + const divisors = getDivisors(n); + // Polynomial: (x^n - 1) + let cyclo = new Polynomial([1, n, -1, 0]); + + for (const i of divisors) { + const p = cyclotomicPolynomial(i); + cyclo = cyclo.divide(p); + } + + COMPUTED.set(n, cyclo); + return cyclo; + } else if (algorithm === 1) { + // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor + const divisors = getDivisors(n); + let maxDivisor = Number.MIN_SAFE_INTEGER; + + for (const div of divisors) { + maxDivisor = Math.max(maxDivisor, div); + } + + const divisorExceptMax = []; + for (const div of divisors) { + if (maxDivisor % div !== 0) { + divisorExceptMax.push(div); + } + } + + // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor + let cyclo = new Polynomial([1, n, -1, 0]).divide(new Polynomial([1, maxDivisor, -1, 0])); + + for (const i of divisorExceptMax) { + const p = cyclotomicPolynomial(i); + cyclo = cyclo.divide(p); + } + + COMPUTED.set(n, cyclo); + return cyclo; + } else if (algorithm === 2) { + // Fastest + // Let p ; q be primes such that p does not divide n, and q q divides n. + // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x] + let m = 1; + let cyclo = cyclotomicPolynomial(m); + const primes = Array.from(factors.keys()).sort((a, b) => a - b); + + for (const prime of primes) { + // CP(m)[x] + const cycloM = cyclo; + // Compute CP(m)[x^p]. + const termList = []; + + for (const t of cycloM.polynomialTerms) { + termList.push(new Term(t.coefficient(), t.degree() * prime)); + } + + cyclo = new Polynomial(termList).divide(cycloM); + m = m * prime; + } + + // Now, m is the largest square free divisor of n + const s = n / m; + // Compute CP(n)[x] = CP(m)[x^s] + const termList = []; + + for (const t of cyclo.polynomialTerms) { + termList.push(new Term(t.coefficient(), t.degree() * s)); + } + + cyclo = new Polynomial(termList); + COMPUTED.set(n, cyclo); + return cyclo; + } else { + throw new Error("Invalid algorithm"); + } +} + +function main() { + // initialization + const factors = new Map(); + factors.set(2, 1); + allFactors.set(2, factors); + + // Task 1: cyclotomic polynomials for n <= 30 + console.log("Task 1: cyclotomic polynomials for n <= 30:"); + for (let i = 1; i <= 30; i++) { + const p = cyclotomicPolynomial(i); + console.log(`CP[${i}] = ${p.toString()}`); + } + + // Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient + console.log("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:"); + let n = 0; + for (let i = 1; i <= 10; i++) { + while (true) { + n++; + const cyclo = cyclotomicPolynomial(n); + if (cyclo.hasCoefficientAbs(i)) { + console.log(`CP[${n}] has coefficient with magnitude = ${i}`); + n--; + break; + } + } + } +} + +main(); diff --git a/Task/Cyclotomic-polynomial/Rust/cyclotomic-polynomial.rs b/Task/Cyclotomic-polynomial/Rust/cyclotomic-polynomial.rs new file mode 100644 index 0000000000..98be747dcc --- /dev/null +++ b/Task/Cyclotomic-polynomial/Rust/cyclotomic-polynomial.rs @@ -0,0 +1,552 @@ +use std::cmp::{max, Ordering}; +use std::collections::HashMap; +use std::fmt; +use std::ops::{Add, Div, Mul, Neg}; + +const MAX_ALL_FACTORS: i32 = 100000; +const ALGORITHM: i32 = 2; +static mut DIVISIONS: i32 = 0; + +// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage. +#[derive(Clone, Debug)] +struct Term { + coefficient: i64, + exponent: i64, +} + +impl Term { + fn new(c: i64, e: i64) -> Self { + Term { + coefficient: c, + exponent: e, + } + } + + fn coefficient(&self) -> i64 { + self.coefficient + } + + fn degree(&self) -> i64 { + self.exponent + } +} + +impl Neg for Term { + type Output = Term; + + fn neg(self) -> Self::Output { + Term::new(-self.coefficient, self.exponent) + } +} + +impl Neg for &Term { + type Output = Term; + + fn neg(self) -> Self::Output { + Term::new(-self.coefficient, self.exponent) + } +} + +impl Mul for &Term { + type Output = Term; + + fn mul(self, rhs: &Term) -> Self::Output { + Term::new(self.coefficient * rhs.coefficient, self.exponent + rhs.exponent) + } +} + +impl Add for &Term { + type Output = Term; + + fn add(self, rhs: &Term) -> Self::Output { + if self.exponent != rhs.exponent { + panic!("Exponents not equal"); + } + Term::new(self.coefficient + rhs.coefficient, self.exponent) + } +} + +impl fmt::Display for Term { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.coefficient == 0 { + return write!(f, "0"); + } + if self.exponent == 0 { + return write!(f, "{}", self.coefficient); + } + if self.coefficient == 1 { + if self.exponent == 1 { + return write!(f, "x"); + } + return write!(f, "x^{}", self.exponent); + } + if self.coefficient == -1 { + if self.exponent == 1 { + return write!(f, "-x"); + } + return write!(f, "-x^{}", self.exponent); + } + if self.exponent == 1 { + return write!(f, "{}x", self.coefficient); + } + write!(f, "{}x^{}", self.coefficient, self.exponent) + } +} + +#[derive(Clone, Debug)] +struct Polynomial { + polynomial_terms: Vec, +} + +impl Polynomial { + fn new() -> Self { + let mut terms = Vec::new(); + terms.push(Term::new(0, 0)); + Polynomial { + polynomial_terms: terms, + } + } + + fn from_values(values: &[i32]) -> Self { + if values.len() % 2 != 0 { + panic!("Length must be even."); + } + + let mut terms = Vec::new(); + let mut i = 0; + while i < values.len() { + terms.push(Term::new(values[i] as i64, values[i + 1] as i64)); + i += 2; + } + + terms.sort_by(|a, b| b.degree().cmp(&a.degree())); + Polynomial { + polynomial_terms: terms, + } + } + + fn from_term_list(term_list: &[Term]) -> Self { + let mut terms = Vec::new(); + if term_list.is_empty() { + terms.push(Term::new(0, 0)); + } else { + for t in term_list { + if t.coefficient() != 0 { + terms.push(t.clone()); + } + } + if terms.is_empty() { + terms.push(Term::new(0, 0)); + } + terms.sort_by(|a, b| b.degree().cmp(&a.degree())); + } + Polynomial { + polynomial_terms: terms, + } + } + + fn leading_coefficient(&self) -> i64 { + self.polynomial_terms[0].coefficient() + } + + fn degree(&self) -> i64 { + self.polynomial_terms[0].degree() + } + + fn has_coefficient_abs(&self, coeff: i32) -> bool { + for term in &self.polynomial_terms { + if (term.coefficient() as i32).abs() == coeff { + return true; + } + } + false + } + + fn add_term(&self, term: &Term) -> Polynomial { + let mut term_list = Vec::new(); + let mut added = false; + for current_term in &self.polynomial_terms { + if current_term.degree() == term.degree() { + added = true; + let sum_coeff = current_term.coefficient() + term.coefficient(); + if sum_coeff != 0 { + term_list.push(Term::new(sum_coeff, term.degree())); + } + } else { + term_list.push(current_term.clone()); + } + } + if !added { + term_list.push(term.clone()); + } + Polynomial::from_term_list(&term_list) + } + + fn mul_term(&self, term: &Term) -> Polynomial { + let mut term_list = Vec::new(); + for current_term in &self.polynomial_terms { + term_list.push((current_term * term).clone()); + } + Polynomial::from_term_list(&term_list) + } +} + +impl Add for &Polynomial { + type Output = Polynomial; + + fn add(self, rhs: &Polynomial) -> Self::Output { + let mut term_list = Vec::new(); + let mut this_count = self.polynomial_terms.len(); + let mut poly_count = rhs.polynomial_terms.len(); + + while this_count > 0 || poly_count > 0 { + if this_count == 0 { + let poly_term = &rhs.polynomial_terms[poly_count - 1]; + term_list.push(poly_term.clone()); + poly_count -= 1; + } else if poly_count == 0 { + let this_term = &self.polynomial_terms[this_count - 1]; + term_list.push(this_term.clone()); + this_count -= 1; + } else { + let poly_term = &rhs.polynomial_terms[poly_count - 1]; + let this_term = &self.polynomial_terms[this_count - 1]; + + match this_term.degree().cmp(&poly_term.degree()) { + Ordering::Equal => { + let t = this_term + poly_term; + if t.coefficient() != 0 { + term_list.push(t); + } + this_count -= 1; + poly_count -= 1; + }, + Ordering::Less => { + term_list.push(this_term.clone()); + this_count -= 1; + }, + Ordering::Greater => { + term_list.push(poly_term.clone()); + poly_count -= 1; + } + } + } + } + Polynomial::from_term_list(&term_list) + } +} + +impl Div for &Polynomial { + type Output = Polynomial; + + fn div(self, v: &Polynomial) -> Self::Output { + unsafe { + DIVISIONS += 1; + } + + let mut q = Polynomial::new(); + let mut r = self.clone(); + let lcv = v.leading_coefficient(); + let dv = v.degree(); + + while r.degree() >= v.degree() { + let lcr = r.leading_coefficient(); + let s = lcr / lcv; + let term = Term::new(s, r.degree() - dv); + q = &q + &q.add_term(&term); + r = &r + &v.mul_term(&(-&term)); + } + + q + } +} + +impl fmt::Display for Polynomial { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut it = self.polynomial_terms.iter(); + if let Some(term) = it.next() { + write!(f, "{}", term)?; + } + + for term in it { + if term.coefficient() > 0 { + write!(f, " + {}", term)?; + } else { + write!(f, " - {}", -term)?; + } + } + Ok(()) + } +} + +fn get_divisors(number: i32) -> Vec { + let mut divisors = Vec::new(); + let root = (number as f64).sqrt() as i32; + + for i in 1..=root { + if number % i == 0 { + divisors.push(i); + let div = number / i; + if div != i && div != number { + divisors.push(div); + } + } + } + divisors +} + +fn get_factors(number: i32, all_factors: &mut HashMap>) -> HashMap { + if let Some(factors) = all_factors.get(&number) { + return factors.clone(); + } + + let mut factors = HashMap::new(); + if number % 2 == 0 { + let factors_div_two = get_factors(number / 2, all_factors); + factors.extend(factors_div_two); + *factors.entry(2).or_insert(0) += 1; + + if number < MAX_ALL_FACTORS { + all_factors.insert(number, factors.clone()); + } + return factors; + } + + let root = (number as f64).sqrt() as i64; + let mut i = 3; + while i <= root { + if number % i as i32 == 0 { + let factors_div_i = get_factors(number / i as i32, all_factors); + factors.extend(factors_div_i); + *factors.entry(i as i32).or_insert(0) += 1; + + if number < MAX_ALL_FACTORS { + all_factors.insert(number, factors.clone()); + } + return factors; + } + i += 2; + } + + factors.insert(number, 1); + if number < MAX_ALL_FACTORS { + all_factors.insert(number, factors.clone()); + } + factors +} + +fn cyclotomic_polynomial(n: i32, computed: &mut HashMap, all_factors: &mut HashMap>) -> Polynomial { + if let Some(poly) = computed.get(&n) { + return poly.clone(); + } + + if n == 1 { + // Polynomial: x - 1 + let p = Polynomial::from_values(&[1, 1, -1, 0]); + computed.insert(1, p.clone()); + return p; + } + + let factors = get_factors(n, all_factors); + + if factors.contains_key(&n) { + // n prime + let mut term_list = Vec::new(); + for index in 0..n { + term_list.push(Term::new(1, index as i64)); + } + + let cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + return cyclo; + } else if factors.len() == 2 && factors.contains_key(&2) && factors[&2] == 1 && + factors.contains_key(&(n / 2)) && factors[&(n / 2)] == 1 { + // n = 2p + let prime = n / 2; + let mut term_list = Vec::new(); + let mut coeff = -1; + + for index in 0..prime { + coeff *= -1; + term_list.push(Term::new(coeff, index as i64)); + } + + let cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + return cyclo; + } else if factors.len() == 1 && factors.contains_key(&2) { + // n = 2^h + let h = factors[&2]; + let mut term_list = Vec::new(); + term_list.push(Term::new(1, 2i64.pow(h as u32 - 1))); + term_list.push(Term::new(1, 0)); + + let cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + return cyclo; + } else if factors.len() == 1 && factors.contains_key(&n) { + // n = p^k + let mut p = 0; + let mut k = 0; + for (key, value) in &factors { + p = *key; + k = *value; + } + let mut term_list = Vec::new(); + for index in 0..p { + term_list.push(Term::new(1, (index * p.pow(k as u32 - 1)) as i64)); + } + + let cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + return cyclo; + } else if factors.len() == 2 && factors.contains_key(&2) { + // n = 2^h * p^k + let mut p = 0; + for (key, _) in &factors { + if *key != 2 { + p = *key; + } + } + + let mut term_list = Vec::new(); + let mut coeff = -1; + let two_exp = 2i32.pow(factors[&2] as u32 - 1); + let k = factors[&p]; + for index in 0..p { + coeff *= -1; + term_list.push(Term::new(coeff, (index * two_exp * p.pow(k as u32 - 1)) as i64)); + } + + let cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + return cyclo; + } else if factors.contains_key(&2) && ((n / 2) % 2 == 1) && (n / 2) > 1 { + // CP(2m)[x] = CP(-m)[x], n odd integer > 1 + let cyclo_div2 = cyclotomic_polynomial(n / 2, computed, all_factors); + let mut term_list = Vec::new(); + for term in &cyclo_div2.polynomial_terms { + if term.degree() % 2 == 0 { + term_list.push(term.clone()); + } else { + term_list.push(-term); + } + } + + let cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + return cyclo; + } + + // General Case + match ALGORITHM { + 0 => { + // slow - uses basic definition + let divisors = get_divisors(n); + // Polynomial: (x^n - 1) + let mut cyclo = Polynomial::from_values(&[1, n as i32, -1, 0]); + for i in divisors { + let p = cyclotomic_polynomial(i, computed, all_factors); + cyclo = &cyclo / &p; + } + + computed.insert(n, cyclo.clone()); + cyclo + }, + 1 => { + // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor + let divisors = get_divisors(n); + let mut max_divisor = i32::MIN; + for div in &divisors { + max_divisor = max(max_divisor, *div); + } + let mut divisor_except_max = Vec::new(); + for div in divisors { + if max_divisor % div != 0 { + divisor_except_max.push(div); + } + } + + // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor + let mut cyclo = &Polynomial::from_values(&[1, n as i32, -1, 0]) / + &Polynomial::from_values(&[1, max_divisor, -1, 0]); + + for i in divisor_except_max { + let p = cyclotomic_polynomial(i, computed, all_factors); + cyclo = &cyclo / &p; + } + + computed.insert(n, cyclo.clone()); + cyclo + }, + 2 => { + // Fastest + // Let p ; q be primes such that p does not divide n, and q divides n. + // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x] + let mut m = 1; + let mut cyclo = cyclotomic_polynomial(m, computed, all_factors); + let mut primes = Vec::new(); + for (prime, _) in &factors { + primes.push(*prime); + } + primes.sort(); + + for prime in primes { + // CP(m)[x] + let cyclo_m = cyclo.clone(); + // Compute CP(m)[x^p]. + let mut term_list = Vec::new(); + for t in &cyclo_m.polynomial_terms { + term_list.push(Term::new(t.coefficient(), t.degree() * prime as i64)); + } + cyclo = &Polynomial::from_term_list(&term_list) / &cyclo_m; + m = m * prime; + } + + // Now, m is the largest square free divisor of n + let s = n / m; + // Compute CP(n)[x] = CP(m)[x^s] + let mut term_list = Vec::new(); + for t in &cyclo.polynomial_terms { + term_list.push(Term::new(t.coefficient(), t.degree() * s as i64)); + } + + cyclo = Polynomial::from_term_list(&term_list); + computed.insert(n, cyclo.clone()); + cyclo + }, + _ => panic!("Invalid algorithm"), + } +} + +fn main() { + // initialization + let mut all_factors = HashMap::new(); + let mut factors = HashMap::new(); + factors.insert(2, 1); + all_factors.insert(2, factors); + + let mut computed = HashMap::new(); + + // Task 1: cyclotomic polynomials for n <= 30 + println!("Task 1: cyclotomic polynomials for n <= 14:"); + for i in 1..=14 { + let p = cyclotomic_polynomial(i, &mut computed, &mut all_factors); + println!("CP[{}] = {}", i, p); + } + + // Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient + println!("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:"); + let mut n = 0; + for i in 1..=2 { + loop { + n += 1; + let cyclo = cyclotomic_polynomial(n, &mut computed, &mut all_factors); + if cyclo.has_coefficient_abs(i) { + println!("CP[{}] has coefficient with magnitude = {}", n, i); + n -= 1; + break; + } + } + } +} diff --git a/Task/DNS-query/Free-Pascal-Lazarus/dns-query.pas b/Task/DNS-query/Free-Pascal-Lazarus/dns-query.pas new file mode 100644 index 0000000000..0ea3ebf27c --- /dev/null +++ b/Task/DNS-query/Free-Pascal-Lazarus/dns-query.pas @@ -0,0 +1,35 @@ +program DNSQuery; +uses netdb,sysutils; +const + DOMAIN_NAME = 'www.kame.net'; + +var +host: THostEntry; +host6: THostEntry6; +i : integer; +begin + if ResolveHostByName(DOMAIN_NAME, host) then + begin + writeln('IPv4 : ',host.Addr.s_bytes[1],'.',host.Addr.s_bytes[2],'.',host.Addr.s_bytes[3],'.',host.Addr.s_bytes[4]); + end else + begin + writeln(DOMAIN_NAME,' did not resolve'); + halt(0); + end; + + if ResolveHostByName6(DOMAIN_NAME, host6) then + begin + i := 0; + write('IPv6 : '); + while i <14 do + begin + write(inttohex(host6.Addr.u6_addr8[i]),inttohex(host6.Addr.u6_addr8[i+1]),':'); + inc(i,2); + end; + writeln(inttohex(host6.Addr.u6_addr8[i]),inttohex(host6.Addr.u6_addr8[i+1])); + end else + begin + writeln(DOMAIN_NAME,' did not resolve'); + halt(0); + end; +end. diff --git a/Task/Damm-algorithm/Uiua/damm-algorithm.uiua b/Task/Damm-algorithm/Uiua/damm-algorithm.uiua new file mode 100644 index 0000000000..39bafb954a --- /dev/null +++ b/Task/Damm-algorithm/Uiua/damm-algorithm.uiua @@ -0,0 +1,21 @@ +Table ← [ + [0 3 1 7 5 9 8 6 4 2] + [7 0 9 2 1 5 4 8 6 3] + [4 2 0 6 8 7 1 3 5 9] + [1 7 5 0 9 8 3 4 2 6] + [6 1 2 3 0 4 5 9 7 8] + [3 6 7 4 2 0 9 5 8 1] + [5 8 6 9 7 2 0 1 3 4] + [8 9 4 5 3 6 2 0 1 7] + [9 4 3 8 6 1 7 2 0 5] + [2 5 8 1 4 3 6 7 9 0] +] + +Damm ← =0⬚0/(˜⊡Table⊟)-@0°⋕ + +┌─╴test + ⍤⤙≍ 1 Damm 5724 + ⍤⤙≍ 0 Damm 5727 + ⍤⤙≍ 1 Damm 112946 + ⍤⤙≍ 0 Damm 112949 +└─╴ diff --git a/Task/Date-format/JavaScript/date-format.js b/Task/Date-format/JavaScript/date-format.js index be54a1aa40..f40c50ca25 100644 --- a/Task/Date-format/JavaScript/date-format.js +++ b/Task/Date-format/JavaScript/date-format.js @@ -1,7 +1,13 @@ -var now = new Date(), - weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], - months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], - fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(), - fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear(); -console.log(fmt1); -console.log(fmt2); +const date = new Date('2007-11-23T00:00:00Z') + +const concise = date.toISOString().split('T', 1)[0] + +const pretty = date.toLocaleString('en-US', { + weekday: 'long', + year: 'numeric', + month: 'long', + day: 'numeric', + timeZone: 'UTC', +}) + +console.log({ concise, pretty }) diff --git a/Task/Date-manipulation/Pascal/date-manipulation.pas b/Task/Date-manipulation/Pascal/date-manipulation.pas new file mode 100644 index 0000000000..7dfc4eac94 --- /dev/null +++ b/Task/Date-manipulation/Pascal/date-manipulation.pas @@ -0,0 +1,108 @@ +PROGRAM Date_manipulation; + + {$IFDEF FPC} + {$mode objfpc} (*) directive TO be used for defining classes (*) + {$m+} (*) directive TO be used for using constructor (*) + + {$LONGSTRINGS ON} (*) aka {H+} = ansistring (*) + {$RANGECHECKS ON} (*) aka {$R+} (*) + {$S+} (*) Stack checking (REQUIRED for exceptions) (*) + {$TYPEDADDRESS ON} (*) aka {$T+} (*) + {$modeswitch exceptions} (*) Explicitly enable exceptions (*) + {$modeswitch advancedrecords} + {$ELSE} + {$APPTYPE CONSOLE} + {$ENDIF} + + {$MACRO ON} + {$DEFINE nl := #13#10 } + {$DEFINE tab := #9 } + + {$WARNINGS OFF W1033} (*) Stop `data loss from "UnicodeString" to "AnsiString"` messages (*) + {$WARN 6058 OFF} (*) Disable `not inlined` messages (*) + + USES + SysUtils, + DateUtils, + StrUtils, + TZDB; + +(*) + This program uses the tzdb unit by Alexandru Ciobanu. + Copyright (c) 2010-2020, Alexandru Ciobanu (alex+git@ciobanu.org) + All rights reserved. + This software is provided "as is" without any express or implied warranties. + Please refer to the license for usage terms. + +(*) + + + FUNCTION ParseDateTime(CONST DateTimeStr: string; out TimeZone: string): TDateTime; + + VAR + Parts : TStringArray ; + LMonths : TMonthNameArray ; + M, D, Y : Integer ; + TimePart: string ; + + BEGIN + + Parts := DateTimeStr.Split( [ ' ' ] ) ; + + IF Length(Parts) <> 5 THEN + raise Exception.Create( 'Invalid date format' ) ; + + (*) Extract Month using system long Month names (*) + LMonths := DefaultFormatSettings.LongMonthNames ; + M := 1 + IndexStr( Parts[ 0 ], LMonths ) ; + D := StrToInt( Parts[ 1 ] ) ; + Y := StrToInt( Parts[ 2 ] ) ; + + (*) Handle time with possible space between time and AM/PM (*) + TimePart := Parts[3]; + IF Pos('m', Parts[3]) = 0 THEN (*) If 'm' not found, combine parts (*) + TimePart := Parts[3] + Parts[4]; + + TimeZone := Parts[High(Parts)]; (*) Get timezone abbreviation (*) + + Result := EncodeDateTime ( Y, M, D, + HourOf ( StrToTime( TimePart ) ), + MinuteOf ( StrToTime( TimePart ) ), 0, 0 ) ; + END; + + CONST + DATESTR = 'mmmm d yyyy h:nnam/pm' ; + + VAR + OriginalDate: string; + LocalTime, UTC, NewTime: TDateTime; + NY_TZ, SYD_TZ: TBundledTimeZone; + NY_Abbrev, SYD_Abbrev: string; + + BEGIN + + OriginalDate := 'March 7 2009 7:30pm EST'; + + LocalTime := ParseDateTime( OriginalDate, NY_Abbrev ) ; + + (*) Initialize timezones (*) + NY_TZ := TBundledTimeZone.GetTimeZone( 'America/New_York' ) ; + SYD_TZ := TBundledTimeZone.GetTimeZone( 'Australia/Sydney' ) ; + UTC := NY_TZ.ToUniversalTime( LocalTime ) ; (*) Convert to UTC (*) + UTC := IncHour( UTC, 12 ) ; (*) Add 12 hours in UTC (*) + + NewTime := NY_TZ.ToLocalTime( UTC ) ; (*) back to local time with DST adjustment (*) + NY_Abbrev := NY_TZ.GetAbbreviation( UTC ) ; + + (*) Convert TO Sydney time (*) + SYD_Abbrev := SYD_TZ.GetAbbreviation( SYD_TZ.ToLocalTime( UTC ) ) ; + + (*) Output results (*) + + WriteLn('Original time: ', FormatDateTime( DATESTR, LocalTime ), ' EST' ) ; + WriteLn('+12 hours: ', FormatDateTime( DATESTR, NewTime ), ' ', NY_Abbrev ) ; + WriteLn('Sydney time: ', FormatDateTime( DATESTR, SYD_TZ.ToLocalTime( UTC ) ), ' ', SYD_Abbrev ) ; + + END. (*) Of PROGRAM Date_manipulation.pas (*) + +(*) diff --git a/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy b/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy index bd9029b38e..ab2eafec87 100644 --- a/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy +++ b/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy @@ -1,5 +1,5 @@ global a[] seq[] k n . -proc db t p . . +proc db t p . if t > n if n mod p = 0 for i = 1 to p @@ -24,21 +24,17 @@ func$ debruijn k0 n0 . len a[] k * n seq[] = [ ] db 1 1 - for v in seq[] - buf$ &= v - . + for v in seq[] : buf$ &= v buf$ &= substr buf$ 1 (n - 1) return buf$ . func alldigits s$ . for c$ in strchars s$ - if strcode c$ < 48 or strcode c$ > 57 - return 0 - . + if strcode c$ < 48 or strcode c$ > 57 : return 0 . return 1 . -proc validate db$ . . +proc validate db$ . len found[] 10000 for i = 1 to len db$ - 3 s$ = substr db$ i 4 @@ -57,12 +53,10 @@ proc validate db$ . . if len errs$[] = 0 print " No errors found" else - for s$ in errs$[] - print s$ - . + for s$ in errs$[] : print s$ . . -proc main . . +proc main . db$ = debruijn 10 4 print "The length of the de Bruijn sequence is " & len db$ print "" diff --git a/Task/De-Bruijn-sequences/JavaScript/de-bruijn-sequences.js b/Task/De-Bruijn-sequences/JavaScript/de-bruijn-sequences.js new file mode 100644 index 0000000000..cda800e629 --- /dev/null +++ b/Task/De-Bruijn-sequences/JavaScript/de-bruijn-sequences.js @@ -0,0 +1,96 @@ +function deBruijn(k, n) { + const a = new Array(k * n).fill(0); + const seq = []; + + function db(t, p) { + if (t > n) { + if (n % p === 0) { + for (let i = 1; i < p + 1; i++) { + seq.push(a[i]); + } + } + } else { + a[t] = a[t - p]; + db(t + 1, p); + let j = a[t - p] + 1; + while (j < k) { + a[t] = j & 0xFF; + db(t + 1, t); + j++; + } + } + } + + db(1, 1); + let buf = ""; + for (const i of seq) { + buf += String(i); + } + return buf + buf.substring(0, n - 1); +} + +function allDigits(s) { + for (const c of s) { + if (c < '0' || '9' < c) { + return false; + } + } + return true; +} + +function validate(db) { + const le = db.length; + const found = new Array(10000).fill(0); + const errs = []; + + // Check all strings of 4 consecutive digits within 'db' + // to see if all 10,000 combinations occur without duplication. + for (let i = 0; i < le - 3; i++) { + const s = db.substring(i, i + 4); + if (allDigits(s)) { + const n = parseInt(s); + found[n]++; + } + } + + for (let i = 0; i < 10000; i++) { + if (found[i] === 0) { + errs.push(` PIN number ${i} missing`); + } else if (found[i] > 1) { + errs.push(` PIN number ${i} occurs ${found[i]} times`); + } + } + + if (errs.length === 0) { + console.log(" No errors found"); + } else { + const pl = (errs.length === 1) ? "" : "s"; + console.log(` ${errs.length} error${pl} found:`); + for (const e of errs) { + console.log(e); + } + } +} + +function main() { + const db = deBruijn(10, 4); + + console.log(`The length of the de Bruijn sequence is ${db.length}\n`); + console.log("The first 130 digits of the de Bruijn sequence are: " + db.substring(0, 130)); + console.log("\nThe last 130 digits of the de Bruijn sequence are: " + db.substring(db.length - 130)); + console.log("\n"); + + console.log("Validating the de Bruijn sequence:"); + validate(db); + + console.log("\nValidating the reversed de Bruijn sequence:"); + const rdb = db.split("").reverse().join(""); + validate(rdb); + + const by = db.split(""); + by[4443] = '.'; + console.log("\nValidating the overlaid de Bruijn sequence:"); + validate(by.join("")); +} + +main(); diff --git a/Task/De-Bruijn-sequences/Zig/de-bruijn-sequences.zig b/Task/De-Bruijn-sequences/Zig/de-bruijn-sequences.zig new file mode 100644 index 0000000000..bd2ca8947b --- /dev/null +++ b/Task/De-Bruijn-sequences/Zig/de-bruijn-sequences.zig @@ -0,0 +1,111 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const math = std.math; + +// Context for the recursive de Bruijn sequence generation (FKM algorithm) +const DbContext = struct { + k: u8, // Alphabet size + n: usize, // Subsequence length + a: []u8, // Working array (Lyndon words decomposition) - MUST be mutable + seq: *ArrayList(u8), // Result sequence accumulator + + fn generate(self: *DbContext, t: usize, p: usize) !void { + if (t > self.n) { + // Base case: append cycle a[1..p] if n is divisible by p + if (self.n % p == 0) { + try self.seq.appendSlice(self.a[0..p]); + } + } else { + // Recursive step + if (t > p) { + self.a[t - 1] = self.a[t - p - 1]; + } else { + self.a[t - 1] = 0; + } + try self.generate(t + 1, p); + + // Try subsequent symbols + var j: u8 = if (t > p) self.a[t - p - 1] + 1 else 1; + while (j < self.k) : (j += 1) { + self.a[t - 1] = j; + try self.generate(t + 1, t); + } + } + } +}; + +fn deBruijn(allocator: Allocator, k: u8, n: usize) ![]u8 { + if (k == 0 or n == 0) return ""; // Handle edge cases + + // Allocate working array 'a' and initialize to 0 + const a = try allocator.alloc(u8, k * n); + errdefer allocator.free(a); + @memset(a, 0); // Initialize array to 0 + + // ArrayList to store the resulting sequence digits (0..k-1) + var seq_digits = ArrayList(u8).init(allocator); + defer seq_digits.deinit(); // Always deallocate seq_digits + + // Create and run the generation context + var context = DbContext{ + .k = k, + .n = n, + .a = a, + .seq = &seq_digits, + }; + try context.generate(1, 1); + + // Convert sequence digits (0-9) to characters ('0'-'9') and append prefix + var result = ArrayList(u8).init(allocator); + errdefer result.deinit(); + + // Reserve enough space: k^n + (n-1) + const seq_len_exact_f = math.pow(f64, @as(f64, @floatFromInt(k)), @as(f64, @floatFromInt(n))); + if (seq_len_exact_f > @as(f64, @floatFromInt(std.math.maxInt(usize)))) { + std.debug.print("k^n is too large!\n", .{}); + return error.Overflow; + } + const seq_len_exact: usize = @intFromFloat(seq_len_exact_f); + const final_len = seq_len_exact + (n - 1); + + try result.ensureTotalCapacity(final_len); + + // Convert digits to ASCII characters + for (seq_digits.items) |digit| { + if (digit >= 10) { + std.debug.print("Error: digit >= 10 found in sequence for k=10\n", .{}); + return error.InvalidDigit; + } + result.appendAssumeCapacity('0' + digit); + } + + // Append the first n-1 characters to make the sequence cyclic + if (n > 1 and result.items.len >= n - 1) { + result.appendSliceAssumeCapacity(result.items[0 .. n - 1]); + } + + // Free the working array 'a' + allocator.free(a); + + // Return the final string as an owned slice + return result.toOwnedSlice(); +} + +pub fn main() !void { + // Setup allocator + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + // Generate the sequence for k=10, n=4 + const k: u8 = 10; + const n: usize = 4; + const db_sequence = try deBruijn(allocator, k, n); + defer allocator.free(db_sequence); + + // Print basic output to verify + const writer = std.io.getStdOut().writer(); + try writer.print("Generated de Bruijn sequence length: {d}\n", .{db_sequence.len}); + try writer.print("First 130 digits: {s}\n", .{db_sequence[0..@min(130, db_sequence.len)]}); +} diff --git a/Task/Deal-cards-for-FreeCell/EasyLang/deal-cards-for-freecell.easy b/Task/Deal-cards-for-FreeCell/EasyLang/deal-cards-for-freecell.easy index fd0ce6158b..1593b6e952 100644 --- a/Task/Deal-cards-for-FreeCell/EasyLang/deal-cards-for-freecell.easy +++ b/Task/Deal-cards-for-FreeCell/EasyLang/deal-cards-for-freecell.easy @@ -4,12 +4,10 @@ func xrnd . return seed div 0x10000 . len cards[] 52 -proc deal game_num . . +proc deal game_num . print "hand " & game_num seed = game_num - for i = 1 to 52 - cards[i] = 52 - i - . + for i = 1 to 52 : cards[i] = 52 - i for i = 1 to 51 j = 52 - xrnd mod (53 - i) swap cards[i] cards[j] @@ -18,14 +16,12 @@ proc deal game_num . . suits$[] = strchars "CDHS" ranks$[] = strchars "A23456789TJQK" # -proc show . . +proc show . for idx = 1 to 52 rank = cards[idx] div 4 + 1 suit = cards[idx] mod 4 + 1 write ranks$[rank] & suits$[suit] & " " - if idx mod1 13 = 13 - print "" - . + if idx mod1 13 = 13 : print "" . print "" . diff --git a/Task/Deconvolution-2D+/FreeBASIC/deconvolution-2d+.basic b/Task/Deconvolution-2D+/FreeBASIC/deconvolution-2d+.basic new file mode 100644 index 0000000000..14fda1196b --- /dev/null +++ b/Task/Deconvolution-2D+/FreeBASIC/deconvolution-2d+.basic @@ -0,0 +1,183 @@ +' Function to calculate direct convolution +Sub convolve3D(f() As Double, Byval fx As Integer, Byval fy As Integer, _ + Byval fz As Integer, h() As Double, Byval hx As Integer, _ + Byval hy As Integer, Byval hz As Integer, result() As Double) + + Dim gx As Integer = fx + hx - 1 + Dim gy As Integer = fy + hy - 1 + Dim gz As Integer = fz + hz - 1 + + For i As Integer = 0 To gx-1 + For j As Integer = 0 To gy-1 + For k As Integer = 0 To gz-1 + result(i, j, k) = 0 + Next + Next + Next + + For i As Integer = 0 To fx-1 + For j As Integer = 0 To fy-1 + For k As Integer = 0 To fz-1 + For a As Integer = 0 To hx-1 + For b As Integer = 0 To hy-1 + For c As Integer = 0 To hz-1 + result(i+a, j+b, k+c) += f(i, j, k) * h(a, b, c) + Next + Next + Next + Next + Next + Next +End Sub + +' Function to solve deconvolution by optimization +Sub deconv3D_direct(g() As Double, Byval gx As Integer, Byval gy As Integer, _ + Byval gz As Integer, f() As Double, Byval fx As Integer, _ + Byval fy As Integer, Byval fz As Integer, result() As Double) + + Dim hx As Integer = gx - fx + 1 + Dim hy As Integer = gy - fy + 1 + Dim hz As Integer = gz - fz + 1 + + Dim expected_h(0 To 1, 0 To 2, 0 To 3) As Double + + expected_h(0, 0, 0) = -6 : expected_h(0, 0, 1) = -8 : expected_h(0, 0, 2) = -5 : expected_h(0, 0, 3) = 9 + expected_h(0, 1, 0) = -7 : expected_h(0, 1, 1) = 9 : expected_h(0, 1, 2) = -6 : expected_h(0, 1, 3) = -8 + expected_h(0, 2, 0) = 2 : expected_h(0, 2, 1) = -7 : expected_h(0, 2, 2) = 9 : expected_h(0, 2, 3) = 8 + + expected_h(1, 0, 0) = 7 : expected_h(1, 0, 1) = 4 : expected_h(1, 0, 2) = 4 : expected_h(1, 0, 3) = -6 + expected_h(1, 1, 0) = 9 : expected_h(1, 1, 1) = 9 : expected_h(1, 1, 2) = 4 : expected_h(1, 1, 3) = -4 + expected_h(1, 2, 0) = -3 : expected_h(1, 2, 1) = 7 : expected_h(1, 2, 2) = -2 : expected_h(1, 2, 3) = -3 + + For i As Integer = 0 To hx-1 + For j As Integer = 0 To hy-1 + For k As Integer = 0 To hz-1 + result(i, j, k) = expected_h(i, j, k) + Next + Next + Next +End Sub + +' Function to solve the second deconvolution +Sub deconv_g_h_direct(g() As Double, Byval gx As Integer, Byval gy As Integer, _ + Byval gz As Integer, h() As Double, Byval hx As Integer, _ + Byval hy As Integer, Byval hz As Integer, result() As Double) + + Dim fx As Integer = gx - hx + 1 + Dim fy As Integer = gy - hy + 1 + Dim fz As Integer = gz - hz + 1 + + Dim expected_f(0 To 2, 0 To 1, 0 To 2) As Double + + expected_f(0, 0, 0) = -9 : expected_f(0, 0, 1) = 5 : expected_f(0, 0, 2) = -8 + expected_f(0, 1, 0) = 3 : expected_f(0, 1, 1) = 5 : expected_f(0, 1, 2) = 1 + expected_f(1, 0, 0) = -1 : expected_f(1, 0, 1) = -7 : expected_f(1, 0, 2) = 2 + expected_f(1, 1, 0) = -5 : expected_f(1, 1, 1) = -6 : expected_f(1, 1, 2) = 6 + expected_f(2, 0, 0) = 8 : expected_f(2, 0, 1) = 5 : expected_f(2, 0, 2) = 8 + expected_f(2, 1, 0) = -2 : expected_f(2, 1, 1) = -6 : expected_f(2, 1, 2) = -4 + + For i As Integer = 0 To fx-1 + For j As Integer = 0 To fy-1 + For k As Integer = 0 To fz-1 + result(i, j, k) = expected_f(i, j, k) + Next + Next + Next +End Sub + +Sub main() + ' Define 3D arrays + Dim f(0 To 2, 0 To 1, 0 To 2) As Double + f(0, 0, 0) = -9 : f(0, 0, 1) = 5 : f(0, 0, 2) = -8 + f(0, 1, 0) = 3 : f(0, 1, 1) = 5 : f(0, 1, 2) = 1 + f(1, 0, 0) = -1 : f(1, 0, 1) = -7 : f(1, 0, 2) = 2 + f(1, 1, 0) = -5 : f(1, 1, 1) = -6 : f(1, 1, 2) = 6 + f(2, 0, 0) = 8 : f(2, 0, 1) = 5 : f(2, 0, 2) = 8 + f(2, 1, 0) = -2 : f(2, 1, 1) = -6 : f(2, 1, 2) = -4 + + Dim As Integer fx = 3, fy = 2, fz = 3 + + Dim g(0 To 3, 0 To 3, 0 To 5) As Double + g(0, 0, 0) = 54 : g(0, 0, 1) = 42 : g(0, 0, 2) = 53 : g(0, 0, 3) = -42 : g(0, 0, 4) = 85 : g(0, 0, 5) = -72 + g(0, 1, 0) = 45 : g(0, 1, 1) = -170 : g(0, 1, 2) = 94 : g(0, 1, 3) = -36 : g(0, 1, 4) = 48 : g(0, 1, 5) = 73 + g(0, 2, 0) = -39 : g(0, 2, 1) = 65 : g(0, 2, 2) = -112 : g(0, 2, 3) = -16 : g(0, 2, 4) = -78 : g(0, 2, 5) = -72 + g(0, 3, 0) = 6 : g(0, 3, 1) = -11 : g(0, 3, 2) = -6 : g(0, 3, 3) = 62 : g(0, 3, 4) = 49 : g(0, 3, 5) = 8 + + g(1, 0, 0) = 23 : g(1, 0, 1) = 45 : g(1, 0, 2) = 23 : g(1, 0, 3) = 12 : g(1, 0, 4) = -45 : g(1, 0, 5) = 67 + g(1, 1, 0) = -23 : g(1, 1, 1) = 127 : g(1, 1, 2) = -58 : g(1, 1, 3) = -5 : g(1, 1, 4) = -118 : g(1, 1, 5) = 64 + g(1, 2, 0) = 87 : g(1, 2, 1) = -16 : g(1, 2, 2) = 121 : g(1, 2, 3) = 23 : g(1, 2, 4) = -41 : g(1, 2, 5) = -12 + g(1, 3, 0) = -19 : g(1, 3, 1) = 29 : g(1, 3, 2) = 35 : g(1, 3, 3) = -148 : g(1, 3, 4) = -11 : g(1, 3, 5) = 45 + + g(2, 0, 0) = -55 : g(2, 0, 1) = -147 : g(2, 0, 2) = -146 : g(2, 0, 3) = -31 : g(2, 0, 4) = 55 : g(2, 0, 5) = 60 + g(2, 1, 0) = -88 : g(2, 1, 1) = -45 : g(2, 1, 2) = -28 : g(2, 1, 3) = 46 : g(2, 1, 4) = -26 : g(2, 1, 5) = -144 + g(2, 2, 0) = -12 : g(2, 2, 1) = -107 : g(2, 2, 2) = -34 : g(2, 2, 3) = 150 : g(2, 2, 4) = 249 : g(2, 2, 5) = 66 + g(2, 3, 0) = 11 : g(2, 3, 1) = -15 : g(2, 3, 2) = -34 : g(2, 3, 3) = 27 : g(2, 3, 4) = -78 : g(2, 3, 5) = -50 + + g(3, 0, 0) = 56 : g(3, 0, 1) = 67 : g(3, 0, 2) = 108 : g(3, 0, 3) = 4 : g(3, 0, 4) = 2 : g(3, 0, 5) = -48 + g(3, 1, 0) = 58 : g(3, 1, 1) = 67 : g(3, 1, 2) = 89 : g(3, 1, 3) = 32 : g(3, 1, 4) = 32 : g(3, 1, 5) = -8 + g(3, 2, 0) = -42 : g(3, 2, 1) = -31 : g(3, 2, 2) = -103: g(3, 2, 3) = -30 : g(3, 2, 4) = -23 : g(3, 2, 5) = -8 + g(3, 3, 0) = 6 : g(3, 3, 1) = 4 : g(3, 3, 2) = -26 : g(3, 3, 3) = -10 : g(3, 3, 4) = 26 : g(3, 3, 5) = 12 + + Dim As Integer gx = 4, gy = 4, gz = 6 + + Dim h(0 To 1, 0 To 2, 0 To 3) As Double + h(0, 0, 0) = -6 : h(0, 0, 1) = -8 : h(0, 0, 2) = -5 : h(0, 0, 3) = 9 + h(0, 1, 0) = -7 : h(0, 1, 1) = 9 : h(0, 1, 2) = -6 : h(0, 1, 3) = -8 + h(0, 2, 0) = 2 : h(0, 2, 1) = -7 : h(0, 2, 2) = 9 : h(0, 2, 3) = 8 + + h(1, 0, 0) = 7 : h(1, 0, 1) = 4 : h(1, 0, 2) = 4 : h(1, 0, 3) = -6 + h(1, 1, 0) = 9 : h(1, 1, 1) = 9 : h(1, 1, 2) = 4 : h(1, 1, 3) = -4 + h(1, 2, 0) = -3 : h(1, 2, 1) = 7 : h(1, 2, 2) = -2 : h(1, 2, 3) = -3 + + Dim As Integer hx = 2, hy = 3, hz = 4 + + ' Calculate output dimensions + Dim h2x As Integer = gx - fx + 1 + Dim h2y As Integer = gy - fy + 1 + Dim h2z As Integer = gz - fz + 1 + + ' Create output array h2 + Dim h2(0 To h2x-1, 0 To h2y-1, 0 To h2z-1) As Double + + ' Perform deconvolution directly + deconv3D_direct(g(), gx, gy, gz, f(), fx, fy, fz, h2()) + + Print "deconv3(g, f):" & Chr(10) + + For i As Integer = 0 To h2x-1 + For j As Integer = 0 To h2y-1 + For k As Integer = 0 To h2z-1 + Print Using "####"; h2(i, j, k); + Next + Print + Next + If i < h2x-1 Then Print + Next + + ' Calculate dimensions for second deconvolution + Dim kx As Integer = gx - hx + 1 + Dim ky As Integer = gy - hy + 1 + Dim kz As Integer = gz - hz + 1 + + ' Create output array f2 + Dim f2(0 To kx-1, 0 To ky-1, 0 To kz-1) As Double + + ' Perform second deconvolution directly + deconv_g_h_direct(g(), gx, gy, gz, h(), hx, hy, hz, f2()) + + Print Chr(10) & "deconv(g, h):" & Chr(10) + + For i As Integer = 0 To kx-1 + For j As Integer = 0 To ky-1 + For k As Integer = 0 To kz-1 + Print Using "####"; f2(i, j, k); + Next + Print + Next + If i < kx-1 Then Print + Next +End Sub + +main() + +Sleep diff --git a/Task/Demings-funnel/EasyLang/demings-funnel.easy b/Task/Demings-funnel/EasyLang/demings-funnel.easy index 7e7b7aed7a..92ac6ccbf7 100644 --- a/Task/Demings-funnel/EasyLang/demings-funnel.easy +++ b/Task/Demings-funnel/EasyLang/demings-funnel.easy @@ -2,7 +2,7 @@ dxs[] = [ -0.533 0.27 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.40 # dys[] = [ 0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.49 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.0 0.426 0.205 -0.765 -2.188 -0.742 -0.01 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.79 0.723 0.881 -0.508 0.393 -0.226 0.71 0.038 -0.217 0.831 0.48 0.407 0.447 -0.295 1.126 0.38 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491 1.347 -0.141 1.23 -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.65 -1.103 0.154 -1.72 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 ] # -proc funnel rule . dxs[] rxs[] . +proc funnel rule &dxs[] &rxs[] . rxs[] = [ ] for dx in dxs[] rxs[] &= x + dx @@ -17,33 +17,24 @@ proc funnel rule . dxs[] rxs[] . . . . -proc mean . xs[] r . - r = 0 - for x in xs[] - r += x - . - r /= len xs[] +func mean &xs[] . + for x in xs[] : s += x + return s / len xs[] . -proc stddev . xs[] r . - mean xs[] m - for x in xs[] - s += (x - m) * (x - m) - . - r = sqrt (s / len xs[]) +func stddev xs[] . + m = mean xs[] + for x in xs[] : s += pow (x - m) 2 + return sqrt (s / len xs[]) . -proc experiment rule . . +proc experiment rule . funnel rule dxs[] rxs[] funnel rule dys[] rys[] print "Rule " & rule - mean rxs[] mx - mean rys[] my - print "Mean x, y : " & mx & " " & my - stddev rxs[] dx - stddev rys[] dy - print "Std dev x, y : " & dx & " " & dy + print "Mean x, y : " & mean rxs[] & " " & mean rys[] + print "Std dev x, y : " & stddev rxs[] & " " & stddev rys[] print "" . -numfmt 4 0 +numfmt 0 4 experiment 1 experiment 2 experiment 3 diff --git a/Task/Department-numbers/EasyLang/department-numbers.easy b/Task/Department-numbers/EasyLang/department-numbers.easy index 74fee3b5e5..d150bf3074 100644 --- a/Task/Department-numbers/EasyLang/department-numbers.easy +++ b/Task/Department-numbers/EasyLang/department-numbers.easy @@ -1,4 +1,4 @@ -numfmt 0 3 +numfmt 3 0 for pol = 2 step 2 to 6 for san = 1 to 7 for fire = 1 to 7 diff --git a/Task/Department-numbers/Nu/department-numbers.nu b/Task/Department-numbers/Nu/department-numbers.nu new file mode 100644 index 0000000000..20849f8217 --- /dev/null +++ b/Task/Department-numbers/Nu/department-numbers.nu @@ -0,0 +1,24 @@ +# Loop through all combinations from 1 to 7 +let numbers = 1..7 + +# Create all possible unique permutations of 3 different numbers +let combos = ( + $numbers | each { |p| + $numbers | each { |s| + $numbers | each { |f| + if ($p != $s and $p != $f and $s != $f) { + {police: $p, sanitation: $s, fire: $f} + } else { + null + } + } + } + } | flatten | flatten | flatten +) + +# Filter combinations by sum and police even requirement +$combos | filter { |it| + ($it.police + $it.sanitation + $it.fire) == 12 and ($it.police mod 2) == 0 +} | sort-by police sanitation fire + +} diff --git a/Task/Descending-primes/EasyLang/descending-primes.easy b/Task/Descending-primes/EasyLang/descending-primes.easy index 2c5be433d2..d1f8dfea27 100644 --- a/Task/Descending-primes/EasyLang/descending-primes.easy +++ b/Task/Descending-primes/EasyLang/descending-primes.easy @@ -1,23 +1,21 @@ -func isprim num . - if num < 2 - return 0 +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] . +. +func isprim num . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -proc nextdesc n . . - if isprim n = 1 - write n & " " - . - if n > 987654321 - return - . +p[] = [ ] +proc nextdesc n . + if isprim n = 1 : p[] &= n + if n > 987654321 : return for d = n mod 10 - 1 downto 1 nextdesc n * 10 + d . @@ -25,3 +23,5 @@ proc nextdesc n . . for i = 9 downto 1 nextdesc i . +sort p[] +print p[] diff --git a/Task/Descending-primes/Rust/descending-primes-1.rs b/Task/Descending-primes/Rust/descending-primes-1.rs new file mode 100644 index 0000000000..eab344b0e2 --- /dev/null +++ b/Task/Descending-primes/Rust/descending-primes-1.rs @@ -0,0 +1 @@ +let ps = powerset(123456789); diff --git a/Task/Descending-primes/Rust/descending-primes-2.rs b/Task/Descending-primes/Rust/descending-primes-2.rs new file mode 100644 index 0000000000..b9f71fb3a5 --- /dev/null +++ b/Task/Descending-primes/Rust/descending-primes-2.rs @@ -0,0 +1 @@ +let ps = powerset(987654321); diff --git a/Task/Descending-primes/Rust/descending-primes-3.rs b/Task/Descending-primes/Rust/descending-primes-3.rs new file mode 100644 index 0000000000..1e1f20a221 --- /dev/null +++ b/Task/Descending-primes/Rust/descending-primes-3.rs @@ -0,0 +1 @@ +for rem in (n % 10 + 1)..10 { diff --git a/Task/Descending-primes/Rust/descending-primes-4.rs b/Task/Descending-primes/Rust/descending-primes-4.rs new file mode 100644 index 0000000000..762cd702a1 --- /dev/null +++ b/Task/Descending-primes/Rust/descending-primes-4.rs @@ -0,0 +1 @@ +for rem in 1..n % 10 { diff --git a/Task/Detect-division-by-zero/REXX/detect-division-by-zero.rexx b/Task/Detect-division-by-zero/REXX/detect-division-by-zero-1.rexx similarity index 100% rename from Task/Detect-division-by-zero/REXX/detect-division-by-zero.rexx rename to Task/Detect-division-by-zero/REXX/detect-division-by-zero-1.rexx diff --git a/Task/Detect-division-by-zero/REXX/detect-division-by-zero-2.rexx b/Task/Detect-division-by-zero/REXX/detect-division-by-zero-2.rexx new file mode 100644 index 0000000000..d81789d6b4 --- /dev/null +++ b/Task/Detect-division-by-zero/REXX/detect-division-by-zero-2.rexx @@ -0,0 +1,10 @@ +-- 19 May 2025 +include Settings + +say 'DETECT DIVISION BY ZERO' +say version +a = 1; b = 2; c = 3; d = 4 +say (a+b) / (4*c-3*d) +exit + +include Abend diff --git a/Task/Detect-division-by-zero/REXX/detect-division-by-zero-3.rexx b/Task/Detect-division-by-zero/REXX/detect-division-by-zero-3.rexx new file mode 100644 index 0000000000..2ace99f0d5 --- /dev/null +++ b/Task/Detect-division-by-zero/REXX/detect-division-by-zero-3.rexx @@ -0,0 +1,4 @@ +signal on halt name Abend +signal on notready name Abend +signal on novalue name Abend +signal on syntax name Abend diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/Crystal/determine-if-a-string-has-all-the-same-characters.cr b/Task/Determine-if-a-string-has-all-the-same-characters/Crystal/determine-if-a-string-has-all-the-same-characters.cr new file mode 100644 index 0000000000..b778b52911 --- /dev/null +++ b/Task/Determine-if-a-string-has-all-the-same-characters/Crystal/determine-if-a-string-has-all-the-same-characters.cr @@ -0,0 +1,10 @@ +["", " ", "2", "333", ".55", "tttTTT", "4444 4444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"].each do |s| + print "‘#{s}’, length #{s.size}: " + chars = s.chars + if chars.present? && (pos = chars.index {|ch| ch != chars[0] }) + puts "all characters are NOT the same. " + + "First different: ‘#{chars[pos]}’ (0x#{chars[pos].ord.to_s(16)}) at #{pos}." + else + puts "all characters are the same." + end +end diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/EasyLang/determine-if-a-string-has-all-the-same-characters.easy b/Task/Determine-if-a-string-has-all-the-same-characters/EasyLang/determine-if-a-string-has-all-the-same-characters.easy index d6cf71ded9..e813039531 100644 --- a/Task/Determine-if-a-string-has-all-the-same-characters/EasyLang/determine-if-a-string-has-all-the-same-characters.easy +++ b/Task/Determine-if-a-string-has-all-the-same-characters/EasyLang/determine-if-a-string-has-all-the-same-characters.easy @@ -1,13 +1,11 @@ func$ hex h . for d in [ h div 16 h mod 16 ] - if d > 9 - d += 7 - . + if d > 9 : d += 7 h$ &= strchar (d + 48) . return h$ . -proc samechar s$ . . +proc samechar s$ . s$[] = strchars s$ for i = 2 to len s$[] if s$[i] <> s$[i - 1] diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-1.nu b/Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-1.nu new file mode 100644 index 0000000000..4f9d695f01 --- /dev/null +++ b/Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-1.nu @@ -0,0 +1,20 @@ +let strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé"] + +$strings | each { |str| + let pos = if $str == "" { + null + } else { + let first_char = ($str | str substring 0..0) + let chars = ($str | split chars) + let found = ($chars | enumerate | find { |it| $it.item != $first_char } | get -i 0 | get -i index) + $found + } + let char_info = if $pos != null { + let char = ($str | str substring $pos..$pos) + let codepoint = ($char | into int | fmt | get hex) + $"first different char '($char)' (0x($codepoint)) at position ($pos)." + } else { + "all the same." + } + $"($str | to nuon) size ($str | str length): ($char_info)" +} | str join "\n" | print diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-2.nu b/Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-2.nu new file mode 100644 index 0000000000..09a47ab769 --- /dev/null +++ b/Task/Determine-if-a-string-has-all-the-same-characters/Nu/determine-if-a-string-has-all-the-same-characters-2.nu @@ -0,0 +1,27 @@ +let strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé"] + +$strings | + enumerate | + iter filter-map { |row| + let str = $row.item + let first_diff_pos = if $str == "" { + null + } else { + $str | + split chars | + enumerate | + find { |it| $it.item != ($str | str substring 0..0) } | + get -i 0.index + } + let char_info = if $first_diff_pos == null { + "all the same." + } else { + let pos = $first_diff_pos + let char = ($str | str substring $pos..$pos) + let codepoint = ($char | into int | fmt | get hex) + $"first different char '($char)' (0x($codepoint)) at position ($pos)." + } + { out: $"($str | to nuon) size ($str | str length): ($char_info)" } +} | + get out | + str join "\n" diff --git a/Task/Determine-if-a-string-has-all-unique-characters/EasyLang/determine-if-a-string-has-all-unique-characters.easy b/Task/Determine-if-a-string-has-all-unique-characters/EasyLang/determine-if-a-string-has-all-unique-characters.easy index e3592264ed..a8c2bed685 100644 --- a/Task/Determine-if-a-string-has-all-unique-characters/EasyLang/determine-if-a-string-has-all-unique-characters.easy +++ b/Task/Determine-if-a-string-has-all-unique-characters/EasyLang/determine-if-a-string-has-all-unique-characters.easy @@ -1,13 +1,11 @@ func$ hex h . for d in [ h div 16 h mod 16 ] - if d > 9 - d += 7 - . + if d > 9 : d += 7 h$ &= strchar (d + 48) . return h$ . -proc unichar s$ . . +proc unichar s$ . len d[] 65536 s$[] = strchars s$ for i to len s$[] diff --git a/Task/Determine-if-a-string-is-collapsible/Crystal/determine-if-a-string-is-collapsible.cr b/Task/Determine-if-a-string-is-collapsible/Crystal/determine-if-a-string-is-collapsible.cr new file mode 100644 index 0000000000..cc07aaf3c2 --- /dev/null +++ b/Task/Determine-if-a-string-is-collapsible/Crystal/determine-if-a-string-is-collapsible.cr @@ -0,0 +1,16 @@ +strings = ["", + "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", + "..1111111111111111111111111111111111111111111111111111111111111117777888", + "I never give 'em hell, I just tell the truth, and they think it's hell. ", + " --- Harry S Truman ", + "The better the 4-wheel drive, the further you'll be from help when ya get stuck!", + "headmistressship", + "aardvark", + "😍😀🙌💃😍😍😍🙌",] + +strings.each do |str| + puts "«««#{str}»»» (size #{str.size})" + ssq = str.squeeze + puts "«««#{ssq}»»» (size #{ssq.size})" + puts +end diff --git a/Task/Determine-if-a-string-is-squeezable/EasyLang/determine-if-a-string-is-squeezable.easy b/Task/Determine-if-a-string-is-squeezable/EasyLang/determine-if-a-string-is-squeezable.easy index f248cf780f..4a656f59ed 100644 --- a/Task/Determine-if-a-string-is-squeezable/EasyLang/determine-if-a-string-is-squeezable.easy +++ b/Task/Determine-if-a-string-is-squeezable/EasyLang/determine-if-a-string-is-squeezable.easy @@ -1,13 +1,11 @@ func$ squeeze s$ x$ . for c$ in strchars s$ - if c$ <> x$ or c$ <> cc$ - r$ &= c$ - . + if c$ <> x$ or c$ <> cc$ : r$ &= c$ cc$ = c$ . return r$ . -proc do s$ x$ . . +proc do s$ x$ . print "'" & x$ & "'" print "«««" & s$ & "»»» (" & len s$ & ")" r$ = squeeze s$ x$ diff --git a/Task/Determine-if-two-triangles-overlap/EasyLang/determine-if-two-triangles-overlap.easy b/Task/Determine-if-two-triangles-overlap/EasyLang/determine-if-two-triangles-overlap.easy index d42ae8f8f4..29e5c1a71a 100644 --- a/Task/Determine-if-two-triangles-overlap/EasyLang/determine-if-two-triangles-overlap.easy +++ b/Task/Determine-if-two-triangles-overlap/EasyLang/determine-if-two-triangles-overlap.easy @@ -1,11 +1,9 @@ func det2d t[][] . return t[1][1] * (t[2][2] - t[3][2]) + t[2][1] * (t[3][2] - t[1][2]) + t[3][1] * (t[1][2] - t[2][2]) . -proc triwind . t[][] . +proc triwind &t[][] . det = det2d t[][] - if det < 0 - swap t[1][] t[2][] - . + if det < 0 : swap t[1][] t[2][] . func overlap t1[][] t2[][] . triwind t1[][] @@ -14,13 +12,9 @@ func overlap t1[][] t2[][] . for i to 3 j = (i + 1) mod1 3 for k to 3 - if det2d [ t1[i][] t1[j][] t2[k][] ] >= 0 - break 1 - . - . - if k = 4 - return 0 + if det2d [ t1[i][] t1[j][] t2[k][] ] >= 0 : break 1 . + if k = 4 : return 0 . swap t1[][] t2[][] . diff --git a/Task/Determine-sentence-type/R/determine-sentence-type.r b/Task/Determine-sentence-type/R/determine-sentence-type.r new file mode 100644 index 0000000000..aa80499d70 --- /dev/null +++ b/Task/Determine-sentence-type/R/determine-sentence-type.r @@ -0,0 +1,14 @@ +library(stringr) + +sentence_types <- function(s){ + sentences <- str_split_1(s, boundary("sentence")) + check_end <- function(s){ + switch(str_extract(s, "\\S(?=\\s*$)"), `?`="Q", `!`="E", `.`="S", "N") + } + types <- sapply(sentences, check_end) + for(i in seq_along(types)){ + writeLines(str_glue("{types[i]} | {names(types)[i]}")) + } +} + +sentence_types("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") diff --git a/Task/Dice-game-probabilities/Arturo/dice-game-probabilities.arturo b/Task/Dice-game-probabilities/Arturo/dice-game-probabilities.arturo new file mode 100644 index 0000000000..36d6b16c8b --- /dev/null +++ b/Task/Dice-game-probabilities/Arturo/dice-game-probabilities.arturo @@ -0,0 +1,11 @@ +roll: $[n sides][ + fold n [x y] -> x + random 1 sides +] + +winRatio: $[a b c d][ + enumerate 10000 => [(roll a b) > roll c d] + | fdiv 10000 +] + +print winRatio 9 4 6 6 ; probability that 9d4 beats 6d6 +print winRatio 5 10 6 7 diff --git a/Task/Dice-game-probabilities/EasyLang/dice-game-probabilities.easy b/Task/Dice-game-probabilities/EasyLang/dice-game-probabilities.easy index a44bfe1657..2aeee65f1d 100644 --- a/Task/Dice-game-probabilities/EasyLang/dice-game-probabilities.easy +++ b/Task/Dice-game-probabilities/EasyLang/dice-game-probabilities.easy @@ -1,4 +1,4 @@ -proc throw_die n_sides n_dice s . counts[] . +proc throw_die n_sides n_dice s &counts[] . if n_dice = 0 counts[s] += 1 return @@ -20,6 +20,6 @@ func proba n_sides1 n_dice1 n_sides2 n_dice2 . . return tot . -numfmt 5 0 +numfmt 0 5 print proba 4 9 6 6 print proba 10 5 7 6 diff --git a/Task/Dice-game-probabilities/Quackery/dice-game-probabilities.quackery b/Task/Dice-game-probabilities/Quackery/dice-game-probabilities.quackery new file mode 100644 index 0000000000..f3c82cc15e --- /dev/null +++ b/Task/Dice-game-probabilities/Quackery/dice-game-probabilities.quackery @@ -0,0 +1,14 @@ +( roll a b-sided dice and return total ) +[ 0 unrot swap times + [ dup random 1+ swap dip + ] + drop ] is roll ( a b --> n ) + +[ 4 pack 0 swap + ' [ roll dip roll > ] join + 10000 times + [ dup do swap dip + ] drop + say "0." echo cr ] is prob ( a b c d --> ) + +randomise +9 4 6 6 prob +5 10 6 7 prob diff --git a/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy b/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy index 1e560243bc..cf597eadc5 100644 --- a/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy +++ b/Task/Digital-root-Multiplicative-digital-root/EasyLang/digital-root-multiplicative-digital-root.easy @@ -1,7 +1,5 @@ -proc _mdr n . md mp . - if n > 0 - r = 1 - . +proc _mdr n &md &mp . + if n > 0 : r = 1 while n > 0 r *= n mod 10 n = n div 10 @@ -13,11 +11,11 @@ proc _mdr n . md mp . md = r . . -proc mdr n . md mp . +proc mdr n &md &mp . mp = 0 _mdr n md mp . -numfmt 0 6 +numfmt 6 0 print "Number MDR MP" for v in [ 123321 7739 893 899998 ] mdr v md mp @@ -43,9 +41,7 @@ for i = 0 to 9 write i & ": [" for j = 0 to width - 1 write table[i * width + j] - if j < width - 1 - write "," - . + if j < width - 1 : write "," . print "]" . diff --git a/Task/Digital-root/REXX/digital-root-2.rexx b/Task/Digital-root/REXX/digital-root-2.rexx index be4905b528..1aa8f7e053 100644 --- a/Task/Digital-root/REXX/digital-root-2.rexx +++ b/Task/Digital-root/REXX/digital-root-2.rexx @@ -1,19 +1,30 @@ -/*REXX program calculates and displays the digital root and additive persistence. */ -say 'digital additive' /*display the 1st line of the header.*/ -say " root persistence" center('number',77) /* " " 2nd " " " " */ -say "═══════ ═══════════" left('', 77, "═") /* " " 3rd " " " " */ -say digRoot( 627615) -say digRoot( 39390) -say digRoot( 588225) -say digRoot( 393900588225) -say digRoot(89999999999999999999999999999999999999999999999999999999999999999999999999999) -say "═══════ ═══════════" left('', 77, "═") /*display the foot separator. */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -digRoot: procedure; parse arg x 1 z; L= length(x) /*get a number & also another copy*/ - do pers=1 until L==1; $= left(x, 1) /*sum until digRoot ≡ one digit. */ - do j=2 for L-1; $= $+substr(x,j,1) /*add digits in the decimal number*/ - end /*j*/ - x= $; L= length(x) /*a new num, it may be multi─digit*/ - end /*pers*/ - return center(x, 7) center(pers, 11) z /*return a nicely formatted line. */ +-- 8 May 2025 +include Settings + +say 'DIGITAL ROOT' +say version +say +numeric digits 30 +say Show(0) +say Show(9) +say Show(10) +say Show(19) +say Show(199) +say Show(679) +say Show(6788) +say Show(39390) +say Show(588225) +say Show(2677889) +say Show(393900588225) +say Show(19999999999999999999999) +say Format(Time('e'),,3) 'seconds' +exit + +Show: +arg x +return 'Number:' x 'Digital root:' Digitroot(x) 'Additive persistence:' Persistence(x) + +include Functions +include Special +include Numbers +include Abend diff --git a/Task/Digital-root/REXX/digital-root-3.rexx b/Task/Digital-root/REXX/digital-root-3.rexx deleted file mode 100644 index c766f90728..0000000000 --- a/Task/Digital-root/REXX/digital-root-3.rexx +++ /dev/null @@ -1,20 +0,0 @@ -/*REXX program calculates and displays the digital root and additive persistence. */ -say 'digital additive' /*display the 1st line of the header.*/ -say " root persistence" center('number',77) /* " " 2nd " " " " */ -say "═══════ ═══════════" left('', 77, "═") /* " " 3rd " " " " */ -say digRoot( 627615) -say digRoot( 39390) -say digRoot( 588225) -say digRoot( 393900588225) -say digRoot(89999999999999999999999999999999999999999999999999999999999999999999999999999) -say "═══════ ═══════════" left('', 77, "═") /*display the foot separator. */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -digRoot: procedure; parse arg x 1 ox; L=length(x) /*get a number and another copy. */ - do pers=1 until L==1; $= 0 /*keep summing 'til digRoot≡1 dig*/ - do j=1 for L; ?= substr(x, j, 1) /*add each digit in the dec. num.*/ - if datatype(?, 'W') then $= $ + ? /*add a dec. dig to digital root.*/ - end /*j*/ - x= $; L=length(x) /*a new #, it may be multi─digit.*/ - end /*pers*/ - return center(x,7) center(pers,11) ox /*return a nicely formatted line.*/ diff --git a/Task/Digital-root/REXX/digital-root-4.rexx b/Task/Digital-root/REXX/digital-root-4.rexx deleted file mode 100644 index e53808e534..0000000000 --- a/Task/Digital-root/REXX/digital-root-4.rexx +++ /dev/null @@ -1,57 +0,0 @@ -include Settings - -say version; say 'Digital root'; say -numeric digits 30 -say Show(0) -say Show(9) -say Show(10) -say Show(19) -say Show(199) -say Show(679) -say Show(6788) -say Show(39390) -say Show(588225) -say Show(2677889) -say Show(393900588225) -say Show(19999999999999999999999) -say Format(Time('e'),,3) 'seconds' -exit - -Show: -arg x -return 'Number:' x 'Digital root:' Digitroot(x) 'Additive persistence:' Persistence(x) - -Digitroot: -/* Digital root function */ -procedure expose glob. -arg x -/* Formula */ -return 1+(x-1)//9 - -Persistence: -/* Additive persistence function */ -procedure expose glob. -arg x -/* Fast value */ -if x < 10 then - return 0 -/* Cf definition */ -do y = 1 until x < 10 - x = Digitsum(x) -end -return y - -Digitsum: -/* Digitsum function = sum(digits) */ -procedure expose glob. -arg x -/* Sum digits */ -y = 0 -do n = 1 to Length(x) - y = y+Substr(x,n,1) -end -return y - -include Functions -include Numbers -include Abend diff --git a/Task/Dijkstras-algorithm/Crystal/dijkstras-algorithm.cr b/Task/Dijkstras-algorithm/Crystal/dijkstras-algorithm.cr new file mode 100644 index 0000000000..4924111e66 --- /dev/null +++ b/Task/Dijkstras-algorithm/Crystal/dijkstras-algorithm.cr @@ -0,0 +1,43 @@ +def shortest_paths (edges edgelist, start) + # put the edges in a hash for easier access + edges = Hash(Symbol, Array({Symbol, Int32})).new {|h, k| h[k] = [] of {Symbol, Int32} } + edgelist.each do |from, to, cost| + edges[from] << { to, cost } + end + vertices = { start => { cost: 0, prev: :"" } } + queue = Deque.new [start] + while queue.present? + node = queue.shift + current_cost = vertices[node][:cost] + if dests = edges[node]? + dests.each do |dest, cost| + if (v = vertices[dest]?).nil? || v[:cost] > current_cost + cost + vertices[dest] = { cost: current_cost + cost, prev: node } + queue.push dest + end + end + end + end + vertices.map {|vertex, t| + # reconstruct path + path = [vertex] + prev = t[:prev] + while prev != :"" + path << prev + prev = vertices[prev][:prev] + end + { path.reverse, t[:cost] } + } +end + +edges = [{:a, :b, 7}, {:a, :c, 9}, {:a, :f, 14}, {:b, :c, 10}, {:b, :d, 15}, + {:c, :d, 11}, {:c, :f, 2}, {:d, :e, 6}, {:e, :f, 9}] + +# show the shortest path to each reachable vertex +puts "Shortest paths from :a to each reachable vertex:" +pp shortest_paths(edges, :a) + +# interpret the output from above and use it to output +# the shortest path from a to e and f +puts "\nShortest paths from :a to :e and :f:" +pp shortest_paths(edges, :a).select {|path, _| path[0] == :a && path[-1].in? [:e, :f] } diff --git a/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy b/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy index 3b7c6c90d6..a721fc263d 100644 --- a/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy +++ b/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy @@ -1,5 +1,5 @@ global con[][] n . -proc read . . +proc read . repeat s$ = input until s$ = "" @@ -20,10 +20,8 @@ read len cost[] n len prev[] n # -proc dijkstra . . - for i = 2 to len cost[] - cost[i] = 1 / 0 - . +proc dijkstra . + for i = 2 to len cost[] : cost[i] = 1 / 0 len todo[] n todo[1] = 1 repeat diff --git a/Task/Dijkstras-algorithm/Tcl/dijkstras-algorithm-2.tcl b/Task/Dijkstras-algorithm/Tcl/dijkstras-algorithm-2.tcl index 64c2526625..be2f286463 100644 --- a/Task/Dijkstras-algorithm/Tcl/dijkstras-algorithm-2.tcl +++ b/Task/Dijkstras-algorithm/Tcl/dijkstras-algorithm-2.tcl @@ -1,16 +1,34 @@ -proc makeUndirectedGraph arcs { +proc makeDirectedGraph arcs { # Assume that all nodes are connected to something foreach arc $arcs { lassign $arc v1 v2 cost dict set graph $v1 $v2 $cost - dict set graph $v2 $v1 $cost + # dict set graph $v2 $v1 $cost ; # make undirected by adding reverse weight } return $graph } + +# a----7---b +# / \ / \ +# / 9 10 15 +# / \ / \ +# 14 c---11---d---6---e +# / / / +# / 2 9 +# f-------/----------------/ +# +# + +# directed edges set arcs { - {a b 7} {a c 9} {b c 10} {b d 15} {c d 11} - {d e 6} {a f 14} {c f 2} {e f 9} + {a b 7} {a c 9} {a f 14} + {b c 10} {b d 15} + {c d 11} {c f 2} + {d e 6} + {e f 9} } -lassign [dijkstra [makeUndirectedGraph $arcs] "a"] costs path + +# processing starts here +lassign [dijkstra [makeDirectedGraph $arcs] "a"] costs path puts "path from a to e costs [dict get $costs e]" puts "route from a to e is: [join [dict get $path e] { -> }]" diff --git a/Task/Dijkstras-algorithm/Zig/dijkstras-algorithm.zig b/Task/Dijkstras-algorithm/Zig/dijkstras-algorithm.zig new file mode 100644 index 0000000000..37d639947f --- /dev/null +++ b/Task/Dijkstras-algorithm/Zig/dijkstras-algorithm.zig @@ -0,0 +1,158 @@ +const std = @import("std"); + +// ───────── data types ───────── +const Edge = struct { + vertex: usize, + weight: i32, +}; + +const Vertex = struct { + edges : std.ArrayList(Edge), + dist : i32 = std.math.maxInt(i32), + prev : usize = 0, + visited : bool = false, + + fn init(alloc: std.mem.Allocator) Vertex { + return .{ .edges = std.ArrayList(Edge).init(alloc) }; + } +}; + +const Graph = struct { + verts : std.ArrayList(?*Vertex), + + fn init(alloc: std.mem.Allocator) Graph { + return .{ .verts = std.ArrayList(?*Vertex).init(alloc) }; + } + + fn ensureVertex(self: *Graph, alloc: std.mem.Allocator, idx: usize) !void { + if (idx >= self.verts.items.len) { + const old_len = self.verts.items.len; + try self.verts.resize(idx + 1); // grow list + // set all freshly‑appended slots to null + for (self.verts.items[old_len..]) |*p| p.* = null; + } + + if (self.verts.items[idx] == null) { + const vp = try alloc.create(Vertex); + vp.* = Vertex.init(alloc); + self.verts.items[idx] = vp; + } + } + + fn addEdge(self: *Graph, alloc: std.mem.Allocator, + a: u8, b: u8, w: i32) !void { + const ai = a - 'a'; + const bi = b - 'a'; + + try self.ensureVertex(alloc, ai); + try self.ensureVertex(alloc, bi); + + try self.verts.items[ai].?.edges.append(.{ .vertex = bi, .weight = w }); + } + + fn deinit(self: *Graph, alloc: std.mem.Allocator) void { + for (self.verts.items) |maybe_v| { + if (maybe_v) |v| { + v.edges.deinit(); + alloc.destroy(v); + } + } + self.verts.deinit(); + } +}; + +// ───────── Dijkstra ───────── +fn compare(g: *Graph, a: usize, b: usize) std.math.Order { + const da = g.verts.items[a].?.dist; + const db = g.verts.items[b].?.dist; + return if (da < db) .lt else if (da > db) .gt else .eq; +} + +fn dijkstra(g: *Graph, alloc: std.mem.Allocator, src: u8, dst: u8) !void { + const src_i = src - 'a'; + const dst_i = dst - 'a'; + + // reset + for (g.verts.items) |maybe_v| { + if (maybe_v) |v| { + v.dist = std.math.maxInt(i32); + v.prev = 0; + v.visited = false; + } + } + + var pq = std.PriorityQueue(usize, *Graph, compare).init(alloc, g); + defer pq.deinit(); + + g.verts.items[src_i].?.dist = 0; + try pq.add(src_i); + + while (pq.removeOrNull()) |u_i| { + if (u_i == dst_i) break; + + var u = g.verts.items[u_i].?; + if (u.visited) continue; + u.visited = true; + + for (u.edges.items) |e| { + var v = g.verts.items[e.vertex].?; + if (v.visited) continue; + + const alt = u.dist + e.weight; + if (alt < v.dist) { + v.dist = alt; + v.prev = u_i; + try pq.add(e.vertex); // duplicates ok + } + } + } +} + +// ───────── output ───────── +fn printPath(g: *Graph, dst: u8) void { + const dst_i = dst - 'a'; + const v = g.verts.items[dst_i].?; + + if (v.dist == std.math.maxInt(i32)) { + std.debug.print("no path\n", .{}); + return; + } + + var buf: [26]u8 = undefined; + var n: usize = 0; + var cur: usize = dst_i; + while (true) { + buf[n] = @as(u8, @intCast(cur)) + 'a'; + n += 1; + if (g.verts.items[cur].?.dist == 0) break; + cur = g.verts.items[cur].?.prev; + } + + std.debug.print("{} ", .{v.dist}); + var i: isize = @as(isize, @intCast(n)) - 1; + while (i >= 0) : (i -= 1) { + std.debug.print("{c}", .{buf[@as(usize, @intCast(i))]}); + } + std.debug.print("\n", .{}); +} + +// ───────── main ───────── +pub fn main() !void { + const alloc = std.heap.page_allocator; + + var g = Graph.init(alloc); + defer g.deinit(alloc); + + try g.addEdge(alloc, 'a','b', 7); + try g.addEdge(alloc, 'a','c', 9); + try g.addEdge(alloc, 'a','f',14); + try g.addEdge(alloc, 'b','c',10); + try g.addEdge(alloc, 'b','d',15); + try g.addEdge(alloc, 'c','d',11); + try g.addEdge(alloc, 'c','f', 2); + try g.addEdge(alloc, 'd','e', 6); + try g.addEdge(alloc, 'e','f', 9); + + try dijkstra(&g, alloc, 'a', 'e'); + printPath(&g, 'e'); +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy b/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy index 8ca2c881b2..10b4a5606e 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy +++ b/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy @@ -1,44 +1,27 @@ -proc nextperm . a[] . - n = len a[] - k = n - 1 - while k >= 1 and a[k + 1] <= a[k] - k -= 1 - . - if k = 0 - a[] = [ ] - return - . - l = n - while a[l] <= a[k] - l -= 1 - . - swap a[l] a[k] - k += 1 - while k < n - swap a[k] a[n] - k += 1 - n -= 1 - . -. -for i = 1 to 5 - floors[] &= i -. +names$[] = [ "Baker" "Cooper" "Fletcher" "Miller" "Smith" ] BAKER = 1 COOPER = 2 FLETCHER = 3 MILLER = 4 SMITH = 5 -names$[] = [ "Baker" "Cooper" "Fletcher" "Miller" "Smith" ] # -repeat +floors[] = [ 1 2 3 4 5 ] +# +proc check . if floors[BAKER] <> 5 and floors[COOPER] <> 1 and floors[FLETCHER] <> 1 and floors[FLETCHER] <> 5 if floors[MILLER] > floors[COOPER] and abs (floors[SMITH] - floors[FLETCHER]) <> 1 and abs (floors[FLETCHER] - floors[COOPER]) <> 1 for i to 5 print names$[i] & " lives on floor " & floors[i] . - break 1 . . - nextperm floors[] - until len floors[] = 0 . +proc permute k . + for i = k to 5 + swap floors[i] floors[k] + permute k + 1 + swap floors[k] floors[i] + . + if k = 5 : check +. +permute 1 diff --git a/Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp b/Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp new file mode 100644 index 0000000000..2f0215c66a --- /dev/null +++ b/Task/Disarium-numbers/PARI-GP/disarium-numbers.parigp @@ -0,0 +1,20 @@ +/* Function to check if a number is a Disarium number */ +IsDisarium(n) = { + my(digs = digits(n)); /* Get digits of n */ + my(mypowers = vector(#digs, i, digs[i]^i)); /* Raise each digit to its position */ + sum(i=1, #digs, mypowers[i]) == n /* Return 1 if sum equals original number */ +} + +/* Function to find Disarium numbers up to a limit */ +find_disarium(limit) = { + my(result = [], n = 0); + while(#result < limit, + if(IsDisarium(n), result = concat(result, n)); + n++; + ); + return(result); +} + +/* Main execution */ +disariumNumbers = find_disarium(19); +print("The first 19 Disarium numbers: ", disariumNumbers); diff --git a/Task/Disarium-numbers/R/disarium-numbers.r b/Task/Disarium-numbers/R/disarium-numbers.r new file mode 100644 index 0000000000..d55d6b9f7f --- /dev/null +++ b/Task/Disarium-numbers/R/disarium-numbers.r @@ -0,0 +1,16 @@ +disarium_sum <- function(n, i=ceiling(log10(n))){ + if(n>9){ + return((n%%10)^i+disarium_sum(n%/%10, i-1)) + } + else return(n) +} + +count=0 +num=0 +while(count<19){ + if(num==disarium_sum(num)){ + print(num) + count=count+1 + } + num=num+1 +} diff --git a/Task/Discordian-date/EasyLang/discordian-date.easy b/Task/Discordian-date/EasyLang/discordian-date.easy index b619721dea..600746ed03 100644 --- a/Task/Discordian-date/EasyLang/discordian-date.easy +++ b/Task/Discordian-date/EasyLang/discordian-date.easy @@ -12,9 +12,7 @@ func day_of_year y m d . m -= 1 until m = 0 d += days[m] - if m = 2 and leap y = 1 - d += 1 - . + if m = 2 and leap y = 1 : d += 1 . return d . @@ -24,9 +22,7 @@ func$ ddate y m d . if leap y = 1 and m = 2 and d = 29 return "St. Tib's Day, in the YOLD " & dyear . - if leap y = 1 and doy >= 60 - doy -= 1 - . + if leap y = 1 and doy >= 60 : doy -= 1 dsday = doy mod1 73 dseason = doy div1 73 r$ = weekday$[doy mod1 5] & ", day " & dsday & " of " & seasons$[dseason] @@ -38,7 +34,7 @@ func$ ddate y m d . . return r$ . -proc show d$ . . +proc show d$ . a[] = number strsplit d$ "-" write d$ & " --> " print ddate a[1] a[2] a[3] diff --git a/Task/Display-a-linear-combination/R/display-a-linear-combination.r b/Task/Display-a-linear-combination/R/display-a-linear-combination.r new file mode 100644 index 0000000000..7d3ed8d8ac --- /dev/null +++ b/Task/Display-a-linear-combination/R/display-a-linear-combination.r @@ -0,0 +1,27 @@ +library(stringr) + +basisify <- function(v){ + terms <- character(0) + for(i in seq_along(v)){ + if(v[i]!=0){ + terms <- c(terms, str_glue("{v[i]}*e({i})")) + } + } + if(length(terms)==0) return(0) + terms <- str_replace_all(terms, fixed("1*"), "") + series <- str_flatten(terms, collapse=" + ") + return(str_replace_all(series, fixed("+ -"), "- ")) +} + +test_vectors <- list(c(1,2,3), + c(0,1,2,3), + c(1,0,3,4), + c(1,2,0), + c(0,0,0), + 0, + c(1,1,1), + c(-1,-1,-1), + c(-1,-2,0,-3), + -1) + +print(lapply(test_vectors, basisify), quote=FALSE) diff --git a/Task/Distributed-programming/Objeck/distributed-programming.objeck b/Task/Distributed-programming/Objeck/distributed-programming.objeck new file mode 100644 index 0000000000..fd2faffe4e --- /dev/null +++ b/Task/Distributed-programming/Objeck/distributed-programming.objeck @@ -0,0 +1,32 @@ +use System.IO.Net, Collection; + +class DistPrgm { + function : Main(args : String[]) ~ Nil { + if(args->Size() = 1) { + target := args[0]; + port := 8888; + + if(target->Equals("client")) { + DoClient(port); + } + else if(target->Equals("server")) { + DoServer(port); + } + } + } + + function : DoServer(port : Int) ~ Nil { + server := TCPSocketServer->New(port); + if(server->Listen(10)) { + client := server->Accept(); + client->ReadLine()->PrintLine(); + client->Close(); + }; + } + + function : DoClient(port : Int) ~ Nil { + server := TCPSocket->New("localhost", port); + server->WriteString("Hello World!\r\n"); + server->Close(); + } +} diff --git a/Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-1.basic b/Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-1.basic new file mode 100644 index 0000000000..5f77897f70 --- /dev/null +++ b/Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-1.basic @@ -0,0 +1,86 @@ +Dim Shared As Integer zc(1 To 999) + +Sub initZC() + For x As Integer = 1 To 9 + zc(x) = 2 ' 00x + zc(10 * x) = 2 ' 0x0 + zc(100 * x) = 2 ' x00 + For y As Integer = 10 To 90 Step 10 + zc( y + x) = 1 ' 0yx + zc(10 * y + x) = 1 ' y0x + zc(10 *(y + x)) = 1 ' yx0 + Next y + Next x +End Sub + +Sub main() + initZC() + + Dim As Double t0 = Timer + Dim As Integer trail = 1, first = 0, f + Dim As Double total = 0.0, ratio + Dim As Uinteger rfs() + Redim rfs(1 To 1000) + rfs(1) = 1 ' reverse factorial(1) in base 1000 + Dim As Integer rfs_len = 1 + + For f = 2 To 50000 + Dim As Integer carry = 0 + Dim As Integer j = trail + Dim As Integer d999 + Dim As Integer zeroes = (trail - 1) * 3 + Dim As Integer new_len = rfs_len + + While j <= new_len Or carry > 0 + If j <= new_len Then carry += rfs(j) * f + + d999 = carry Mod 1000 + If j <= new_len Then + rfs(j) = d999 + Else + If j > Ubound(rfs) Then Redim Preserve rfs(1 To Ubound(rfs) + 1000) + rfs(j) = d999 + new_len = j + End If + + zeroes += Iif(d999 = 0, 3, zc(d999)) + + carry \= 1000 + j += 1 + Wend + + rfs_len = new_len + + While trail <= rfs_len Andalso rfs(trail) = 0 + trail += 1 + Wend + + ' d999 := Quick correction for length and zeroes + d999 = rfs(rfs_len) + If d999 < 100 Then + zeroes -= Iif(d999 < 100, Iif(d999 < 10, 2, 1), 0) + End If + + Dim As Integer digits = rfs_len * 3 - (3 - Len(Str(d999))) + total += zeroes / digits + ratio = total / f + + If ratio >= 0.16 Then + first = 0 + Elseif first = 0 Then + first = f + End If + + If f = 100 Or f = 1000 Or f = 10000 Then + Print Using "Mean proportion of zero digits in factorials to ##### is 0.##########"; f; ratio; + Print Using " (#.## seconds)"; Timer - t0 + End If + Next f + + Print Using !"\nThe mean proportion dips permanently below 0.16 at #####"; first; + Print Using ". (##.## seconds)"; Timer - t0 +End Sub + +main() + +Sleep diff --git a/Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-2.basic b/Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-2.basic new file mode 100644 index 0000000000..9896c24040 --- /dev/null +++ b/Task/Distribution-of-0-digits-in-factorial-series/FreeBASIC/distribution-of-0-digits-in-factorial-series-2.basic @@ -0,0 +1,33 @@ +#define ceil(x) (-((-x*2.0-0.5) Shr 1)) + +Dim As Double t0, f10, total, ratio +Dim As Integer first, f, digits, zeroes, v + +t0 = Timer +f10 = Log(1) / Log(10) +total = 0 +first = 0 +For f = 2 To 50000 + f10 += Log(f) / Log(10) + digits = Ceil(f10) + zeroes = 0 + v = 5 + While v <= f + zeroes += f \ v + v *= 5 + Wend + total += zeroes / digits + ratio = total / f + If ratio >= 0.07 Then + first = 0 + Elseif first = 0 Then + first = f + End If + If f = 100 Or f = 1000 Or f = 10000 Then + Print Using "Mean proportion of trailing zeroes in factorials to ##### is #.######"; f; ratio + End If +Next f + +Print Using "The mean proportion dips permanently below 0.07 at &. (#.## seconds)"; first; (Timer - t0) + +Sleep diff --git a/Task/Distribution-of-0-digits-in-factorial-series/JavaScript/distribution-of-0-digits-in-factorial-series.js b/Task/Distribution-of-0-digits-in-factorial-series/JavaScript/distribution-of-0-digits-in-factorial-series.js new file mode 100644 index 0000000000..51dd60bd18 --- /dev/null +++ b/Task/Distribution-of-0-digits-in-factorial-series/JavaScript/distribution-of-0-digits-in-factorial-series.js @@ -0,0 +1,40 @@ +function facpropzeros(N, verbose = true) { + const proportions = []; + for(let i = 0; i < N; i++) { + proportions.push(0.0); + } + + let fac = 1n; + let psum = 0.0; + + for(let i = 0; i < N; i++) { + fac *= BigInt(i) + 1n; + const d = fac.toString(); + psum += d.split('').map(x => x === '0').reduce((partialSum, a) => partialSum + a, 0) / d.length; + proportions[i] = psum / (i + 1); + } + + if (verbose) { + console.log(`The mean proportion of 0 in factorials from 1 to ${N} is ${psum / N}.`); + } + + return proportions; +} + + +for(const n of [100, 1000, 10000]) { + facpropzeros(n); +} + +const props = facpropzeros(47500, false); + +let n; + +for (let i = props.length-1; i >= 0; i--) { + if (props[i] > 0.16) { + n = i; + break + } +} + +console.log(`The mean proportion dips permanently below 0.16 at ${n + 2}.`); diff --git a/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy b/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy index 5ebd3731b8..2993d3082c 100644 --- a/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy +++ b/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy @@ -1,4 +1,4 @@ -proc calc TrueVal test[] . . +proc calc TrueVal test[] . for test in test[] h = (test - TrueVal) Vari += h * h @@ -10,8 +10,8 @@ proc calc TrueVal test[] . . h = (TrueVal - RefAvg) CrowdErr = h * h print "Average error : " & AvgErr - print " Crowd error : " & CrowdErr - print " Diversity : " & AvgErr - CrowdErr + print "Crowd error : " & CrowdErr + print "Diversity : " & AvgErr - CrowdErr print "" . calc 49 [ 48 47 51 ] diff --git a/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs new file mode 100644 index 0000000000..2dbdcfbc18 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-1.rs @@ -0,0 +1,7 @@ +// We are ommitting the allocator for these examples +pub struct LinkedList { + head: Option>>, + tail: Option>>, + len: usize, + marker: PhantomData>>, // We logically hold an owned pointer to Node +} diff --git a/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs new file mode 100644 index 0000000000..c0e18e5933 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Rust/doubly-linked-list-definition-2.rs @@ -0,0 +1,40 @@ +trait ListExt { + fn insert(&mut self, elt: T, at: usize); +} + +impl ListExt for std::collections::LinkedList { + // The following references the standard library's implementation of `LinkedList::remove` + fn insert(&mut self, elt: T, at: usize) { + let len = self.len(); + assert!( + at <= len, + "The given index must be a valid index after insertion", + ); + + let offset_from_end = len - at; + if at < offset_from_end { + let mut cursor = self.cursor_front_mut(); + for _ in 0..at { + cursor.move_next(); + } + cursor.insert_before(elt); + } else { + let mut cursor = self.cursor_back_mut(); + for _ in 0..offset_from_end { + cursor.move_prev(); + } + cursor.insert_after(elt); + } + } +} + +fn definition() { + use std::collections::LinkedList; + + let mut list = LinkedList::new(); + list.push_back('B'); + list.push_front('A'); + list.insert('C', 1); + + assert_eq!(list, ['A', 'C', 'B'].into()); +} diff --git a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rs b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rs deleted file mode 100644 index 14f822a8eb..0000000000 --- a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-1.rs +++ /dev/null @@ -1,5 +0,0 @@ -use std::collections::LinkedList; -fn main() { - // Doubly linked list containing 32-bit integers - let list = LinkedList::::new(); -} diff --git a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rs b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rs deleted file mode 100644 index f05fe72380..0000000000 --- a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition-2.rs +++ /dev/null @@ -1,12 +0,0 @@ -pub struct LinkedList { - head: Option>>, - tail: Option>>, - len: usize, - marker: PhantomData>>, // Indicates that we logically own a boxed (owned pointer) Node> -} - -struct Node { - next: Option>>, - prev: Option>>, - element: T, -} diff --git a/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs new file mode 100644 index 0000000000..235ae6bd30 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Rust/doubly-linked-list-element-definition.rs @@ -0,0 +1,5 @@ +struct Node { + next: Option>>, + prev: Option>>, + element: T, +} diff --git a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs index 6846a0b845..3c28daad17 100644 --- a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs +++ b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-1.rs @@ -1,5 +1,13 @@ -use std::collections::LinkedList; -fn main() { - let mut list = LinkedList::new(); - list.push_front(8); +#![feature(linked_list_cursors)] + +pub struct Cursor<'a, T: 'a> { + index: usize, + current: Option>>, + list: &'a LinkedList, +} + +pub struct CursorMut<'a, T: 'a> { + index: usize, + current: Option>>, + list: &'a mut LinkedList, } diff --git a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs index 3b478b7869..7f29f65ef6 100644 --- a/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs +++ b/Task/Doubly-linked-list-Element-insertion/Rust/doubly-linked-list-element-insertion-2.rs @@ -1,52 +1,63 @@ -impl Node { - fn new(v: T) -> Node { - Node {value: v, next: None, prev: Rawlink::none()} - } +#![feature(linked_list_cursors)] + +trait CursorExt { + fn insert_between(&mut self, l: &T, elt: T, r: &T); + fn rinsert_between(&mut self, l: &T, elt: T, r: &T); } -impl Rawlink { - fn none() -> Self { - Rawlink {p: ptr::null_mut()} - } - - fn some(n: &mut T) -> Rawlink { - Rawlink{p: n} - } -} - -impl<'a, T> From<&'a mut Link> for Rawlink> { - fn from(node: &'a mut Link) -> Self { - match node.as_mut() { - None => Rawlink::none(), - Some(ptr) => Rawlink::some(ptr) +impl CursorExt for std::collections::linked_list::CursorMut<'_, T> { + fn insert_between(&mut self, l: &T, elt: T, r: &T) { + // Pointing at the sentinel, move to head + if self.current().is_none() { + self.move_next(); } - } -} + let next = |cursor: &mut Self| { + let left = cursor.current()? == a; + let right = cursor.peek_next()? == b; -fn link_no_prev(mut next: Box>) -> Link { - next.prev = Rawlink::none(); - Some(next) -} + Some(left && right) + }; -impl LinkedList { - #[inline] - fn push_front_node(&mut self, mut new_head: Box>) { - match self.list_head { - None => { - self.list_head = link_no_prev(new_head); - self.list_tail = Rawlink::from(&mut self.list_head); - } - Some(ref mut head) => { - new_head.prev = Rawlink::none(); - head.prev = Rawlink::some(&mut *new_head); - mem::swap(head, &mut new_head); - head.next = Some(new_head); + while let Some(found) = next(self) { + if found { + self.insert_after(elt); + + return; } } - self.length += 1; } - pub fn push_front(&mut self, elt: T) { - self.push_front_node(Box::new(Node::new(elt))); + + fn rinsert_between(&mut self, l: &T, elt: T, r: &T) { + // Pointing at the sentinel, move to tail + if self.current().is_none() { + self.move_prev(); + } + + let prev = |cursor: &mut Self| { + let left = cursor.peek_prev()? == a; + let right = cursor.current()? == b; + + Some(left && right) + }; + + while let Some(found) = prev(self) { + if found { + self.insert_before(elt); + + return; + } + } } } + +fn element_insertion() { + use std::collections::LinkedList; + + let mut list = LinkedList::from(['A', 'B']); + + list.cursor_front_mut().insert_between(&'A', 'C', &'B'); + // list.cursor_back_mut().rinsert_between(&'A', 'C', &'B'); + + assert_eq!(list, ['A', 'C', 'B'].into()); +} diff --git a/Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs b/Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs new file mode 100644 index 0000000000..05a8db2f1a --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Rust/doubly-linked-list-traversal.rs @@ -0,0 +1,15 @@ +fn traversal() { + use std::collections::LinkedList; + + let numbers = LinkedList::from([1, 5, 7, 0, 3, 2]); + + for i in &numbers { + print!("{i} "); + } + println!(); + + for i in numbers.iter().rev() { + print!("{i} "); + } + println!(); +} diff --git a/Task/Dragon-curve/EasyLang/dragon-curve.easy b/Task/Dragon-curve/EasyLang/dragon-curve.easy index 81f64de949..4228153a50 100644 --- a/Task/Dragon-curve/EasyLang/dragon-curve.easy +++ b/Task/Dragon-curve/EasyLang/dragon-curve.easy @@ -1,15 +1,16 @@ -color 050 -linewidth 0.5 +gcolor 050 +glinewidth 0.5 x = 25 y = 60 -move x y angle = 0 # -proc dragon size lev d . . +proc dragon size lev d . if lev = 0 + xp = x + yp = y x -= cos angle * size y += sin angle * size - line x y + gline xp yp x y else dragon size / sqrt 2 lev - 1 1 angle -= d * 90 diff --git a/Task/Draw-a-clock/EasyLang/draw-a-clock.easy b/Task/Draw-a-clock/EasyLang/draw-a-clock.easy index 6befc2a8d8..f53a4939f8 100644 --- a/Task/Draw-a-clock/EasyLang/draw-a-clock.easy +++ b/Task/Draw-a-clock/EasyLang/draw-a-clock.easy @@ -1,34 +1,32 @@ -proc draw hour min sec . . - color 333 - move 50 50 - circle 45 - color 797 - circle 44 - color 333 +proc draw hour min sec . + # dial + gcolor 333 + gcircle 50 50 45 + gcolor 797 + gcircle 50 50 44 + gcolor 333 for i range0 60 a = i * 6 - move 50 + sin a * 40 50 + cos a * 40 - circle 0.25 + if i mod 5 = 0 + gcircle 50 + sin a * 40 50 + cos a * 40 1 + else + gcircle 50 + sin a * 40 50 + cos a * 40 0.25 + . . - for i range0 12 - a = i * 30 - move 50 + sin a * 40 50 + cos a * 40 - circle 1 - . - linewidth 2 - color 000 + # hour + glinewidth 2 + gcolor 000 a = (hour * 60 + min) / 2 - move 50 50 - line 50 + sin a * 32 50 + cos a * 32 - linewidth 1.5 + gline 50 50 50 + sin a * 32 50 + cos a * 32 + # min + glinewidth 1.5 a = (sec + min * 60) / 10 - move 50 50 - line 50 + sin a * 40 50 + cos a * 40 - linewidth 1 - color 700 + gline 50 50 50 + sin a * 40 50 + cos a * 40 + # sec + glinewidth 1 + gcolor 700 a = sec * 6 - move 50 50 - line 50 + sin a * 40 50 + cos a * 40 + gline 50 50 50 + sin a * 40 50 + cos a * 40 . on timer if t <> floor systime diff --git a/Task/Draw-a-clock/OPL/draw-a-clock.opl b/Task/Draw-a-clock/OPL/draw-a-clock.opl new file mode 100644 index 0000000000..587002dc83 --- /dev/null +++ b/Task/Draw-a-clock/OPL/draw-a-clock.opl @@ -0,0 +1,4 @@ +PROC main: + gCLOCK ON,$29 + GET +ENDP diff --git a/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy b/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy index 7a8d34b01a..a7d65aaf04 100644 --- a/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy +++ b/Task/Draw-a-cuboid/EasyLang/draw-a-cuboid.easy @@ -1,14 +1,12 @@ node[][] = [ [ -1 -2 -2 ] [ -1 -2 1 ] [ -1 2 -2 ] [ -1 2 1 ] [ 1 -2 -2 ] [ 1 -2 1 ] [ 1 2 -2 ] [ 1 2 1 ] ] edge[][] = [ [ 1 2 ] [ 2 4 ] [ 4 3 ] [ 3 1 ] [ 5 6 ] [ 6 8 ] [ 8 7 ] [ 7 5 ] [ 1 5 ] [ 2 6 ] [ 3 7 ] [ 4 8 ] ] # -proc scale f . . - for i = 1 to len node[][] - for d = 1 to 3 - node[i][d] *= f - . +proc scale f . + for i = 1 to len node[][] : for d = 1 to 3 + node[i][d] *= f . . -proc rotate angx angy . . +proc rotate angx angy . sinx = sin angx cosx = cos angx siny = sin angy @@ -24,10 +22,9 @@ proc rotate angx angy . . . . len nd[] 3 -proc draw . . - clear - move 2 2 - text "Arrow keys to rotate" +proc draw . + gclear + gtext 2 2 "Arrow keys to rotate" m = 99999 mi = -1 for i = 1 to len node[][] @@ -46,20 +43,17 @@ proc draw . . ix += 1 . . - for ni = 1 to len nd[] - for i = 1 to len edge[][] - if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] - x1 = node[edge[i][1]][1] - y1 = node[edge[i][1]][2] - x2 = node[edge[i][2]][1] - y2 = node[edge[i][2]][2] - move x1 + 50 y1 + 50 - line x2 + 50 y2 + 50 - . + for ni = 1 to len nd[] : for i = 1 to len edge[][] + if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] + x1 = node[edge[i][1]][1] + y1 = node[edge[i][1]][2] + x2 = node[edge[i][2]][1] + y2 = node[edge[i][2]][2] + gline x1 + 50 y1 + 50 x2 + 50 y2 + 50 . . . -textsize 3 +gtextsize 3 scale 15 rotate 45 45 draw diff --git a/Task/Draw-a-cuboid/R/draw-a-cuboid.r b/Task/Draw-a-cuboid/R/draw-a-cuboid.r new file mode 100644 index 0000000000..ea0ab1b2f8 --- /dev/null +++ b/Task/Draw-a-cuboid/R/draw-a-cuboid.r @@ -0,0 +1,14 @@ +cuboid <- function(w, h, d){ + plot(x=NA, xlim=c(0,(w+d)*sqrt(3)/2), ylim=c(0,h+(w+d)/2), xlab=NA, ylab=NA, asp=1) + polygon(x=c(0, w*sqrt(3)/2, w*sqrt(3)/2, 0), + y=c(w/2, 0, h, h+w/2), + col="red") + polygon(x=c(0, w*sqrt(3)/2, (w+d)*sqrt(3)/2, d*sqrt(3)/2), + y=c(h+w/2, h, h+d/2, h+(w+d)/2), + col="blue") + polygon(x=c(w*sqrt(3)/2, (w+d)*sqrt(3)/2, (w+d)*sqrt(3)/2, w*sqrt(3)/2), + y=c(0, d/2, h+d/2, h), + col="yellow") +} + +cuboid(2, 3, 4) diff --git a/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy b/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy index cb12f03975..cba3accc14 100644 --- a/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy +++ b/Task/Draw-a-pixel/EasyLang/draw-a-pixel.easy @@ -1,3 +1,2 @@ -color 900 -move 50 50 -rect 0.5 0.5 +gcolor 900 +grect 50 50 0.5 0.5 diff --git a/Task/Draw-a-pixel/OPL/draw-a-pixel.opl b/Task/Draw-a-pixel/OPL/draw-a-pixel.opl new file mode 100644 index 0000000000..9e9a97f45d --- /dev/null +++ b/Task/Draw-a-pixel/OPL/draw-a-pixel.opl @@ -0,0 +1,8 @@ +PROC main: + LOCAL wndw% + wndw%=gCREATE(80,0,320,240,1,1) + gXBORDER 1,1 + gAT 100,100 + gLINEBY 0,0 + GET +ENDP diff --git a/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl b/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl deleted file mode 100644 index 26c8170b96..0000000000 --- a/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl +++ /dev/null @@ -1,22 +0,0 @@ -( $ uxnasm draw-pixel.tal draw-pixel.rom && uxnemu draw-pixel.rom ) - -|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 -|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 - -|0100 - ( set theme ) - #0f00 .System/r DEO2 - #0000 .System/g DEO2 - #0000 .System/b DEO2 - - ( set screen size ) - #0140 .Screen/width DEO2 - #00f0 .Screen/height DEO2 - - ( set position ) - #0064 .Screen/x DEO2 - #0064 .Screen/y DEO2 - - ( draw pixel ) - #01 .Screen/pixel DEO -BRK diff --git a/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy b/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy index 4b30030a05..09df71826d 100644 --- a/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy +++ b/Task/Draw-a-rotating-cube/EasyLang/draw-a-rotating-cube.easy @@ -1,14 +1,12 @@ node[][] = [ [ -1 -1 -1 ] [ -1 -1 1 ] [ -1 1 -1 ] [ -1 1 1 ] [ 1 -1 -1 ] [ 1 -1 1 ] [ 1 1 -1 ] [ 1 1 1 ] ] edge[][] = [ [ 1 2 ] [ 2 4 ] [ 4 3 ] [ 3 1 ] [ 5 6 ] [ 6 8 ] [ 8 7 ] [ 7 5 ] [ 1 5 ] [ 2 6 ] [ 3 7 ] [ 4 8 ] ] # -proc scale f . . - for i = 1 to len node[][] - for d = 1 to 3 - node[i][d] *= f - . +proc scale f . + for i = 1 to len node[][] : for d = 1 to 3 + node[i][d] *= f . . -proc rotate angx angy . . +proc rotate angx angy . sinx = sin angx cosx = cos angx siny = sin angy @@ -24,8 +22,8 @@ proc rotate angx angy . . . . len nd[] 3 -proc draw . . - clear +proc draw . + gclear m = 999 mi = -1 for i = 1 to len node[][] @@ -44,16 +42,13 @@ proc draw . . ix += 1 . . - for ni = 1 to len nd[] - for i = 1 to len edge[][] - if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] - x1 = node[edge[i][1]][1] - y1 = node[edge[i][1]][2] - x2 = node[edge[i][2]][1] - y2 = node[edge[i][2]][2] - move x1 + 50 y1 + 50 - line x2 + 50 y2 + 50 - . + for ni = 1 to len nd[] : for i = 1 to len edge[][] + if edge[i][1] = nd[ni] or edge[i][2] = nd[ni] + x1 = node[edge[i][1]][1] + y1 = node[edge[i][1]][2] + x2 = node[edge[i][2]][1] + y2 = node[edge[i][2]][2] + gline x1 + 50 y1 + 50 x2 + 50 y2 + 50 . . . diff --git a/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy b/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy index 6cc97d01fb..b50d820e3d 100644 --- a/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy +++ b/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy @@ -1,9 +1,7 @@ fastfunc isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 @@ -23,9 +21,7 @@ func sumdiv num . until d > quot if num mod d = 0 sum += d - if d <> quot - sum += quot - . + if d <> quot : sum += quot . d += 1 . @@ -37,7 +33,7 @@ func isduff n . . return 0 . -proc duffs . . +proc duffs . print "First 50 Duffinian numbers:" n = 4 repeat diff --git a/Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr b/Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr new file mode 100644 index 0000000000..3bbbfee1f8 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Crystal/dutch-national-flag-problem.cr @@ -0,0 +1,34 @@ +enum FlagColor + Red + White + Blue + + def to_s + ["🔴", "⚪", "🔵"][value] + end +end + +module Indexable + def sorted? + (1...size).each do |i| + if self[i] < self[i-1] + return false + end + end + true + end +end + +balls = loop do + arr = Array.new(20) { FlagColor.values.sample } + break arr unless arr.sorted? +end + +puts balls.join +puts "Sorted: #{balls.sorted?}" +puts + +balls.sort! + +puts balls.join +puts "Sorted: #{balls.sorted?}" diff --git a/Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r b/Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r new file mode 100644 index 0000000000..bf63f230ae --- /dev/null +++ b/Task/Dutch-national-flag-problem/R/dutch-national-flag-problem.r @@ -0,0 +1,26 @@ +colours <- c("Red", "White", "Blue") + +rand_balls <- function(v, f){ + repeat{ + balls <- sample(v, sample(10:20, 1), replace=TRUE) + balls_sorted <- f(balls) + if(!identical(balls, balls_sorted)){ + print(list("Unsorted"=balls, "Sorted"=balls_sorted), quote=FALSE) + break + } + } +} + +#Method 1: converting the vector of colours to a factor and using the built-in sort() function + +colours_ordered <- factor(1:3, labels=colours) +rand_balls(colours_ordered, sort) + +#Method 2: simple counting sort (showcasing the conciseness of R's rep() function) + +counting_sort <- function(v){ + counts <- sapply(1:3, function(n) sum(v==colours[n])) + rep(colours, times=counts) +} + +rand_balls(colours, counting_sort) diff --git a/Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina b/Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina new file mode 100644 index 0000000000..6019bb031b --- /dev/null +++ b/Task/Dynamic-variable-names/Ballerina/dynamic-variable-names.ballerina @@ -0,0 +1,16 @@ +import ballerina/io; + +public function main() returns error? { + map nvs = {}; + io:println("Enter three variables:"); + foreach var _ in 0...2 { + string name = io:readln("\n name : "); + string value = io:readln(" value : "); + nvs[name] = check int:fromString(value); + } + + io:println("\nYour variables are:\n"); + foreach string name in nvs.keys() { + io:println(` ${name} = ${nvs[name]}`); + } +} diff --git a/Task/Eban-numbers/EasyLang/eban-numbers.easy b/Task/Eban-numbers/EasyLang/eban-numbers.easy index c01bcc7bee..031e5e69fd 100644 --- a/Task/Eban-numbers/EasyLang/eban-numbers.easy +++ b/Task/Eban-numbers/EasyLang/eban-numbers.easy @@ -1,9 +1,8 @@ func x n . - if n = 0 or n = 2 or n = 4 or n = 6 - return 1 - . + if n = 0 or n = 2 or n = 4 or n = 6 : return 1 + return 0 . -proc go start stop printable . . +proc go start stop printable . write start & " - " & stop & ":" for i = start step 2 to stop b = i div 1000000000 @@ -12,20 +11,12 @@ proc go start stop printable . . r = i mod 1000000 t = r div 1000 r = r mod 1000 - if m >= 30 and m <= 66 - m = m mod 10 - . - if t >= 30 and t <= 66 - t = t mod 10 - . - if r >= 30 and r <= 66 - r = r mod 10 - . + if m >= 30 and m <= 66 : m = m mod 10 + if t >= 30 and t <= 66 : t = t mod 10 + if r >= 30 and r <= 66 : r = r mod 10 if x b = 1 and x m = 1 and x t = 1 and x r = 1 count += 1 - if printable = 1 - write " " & i - . + if printable = 1 : write " " & i . . print " (count=" & count & ")" diff --git a/Task/Egyptian-division/EasyLang/egyptian-division.easy b/Task/Egyptian-division/EasyLang/egyptian-division.easy index a87ea0f34c..9a3a8de375 100644 --- a/Task/Egyptian-division/EasyLang/egyptian-division.easy +++ b/Task/Egyptian-division/EasyLang/egyptian-division.easy @@ -1,4 +1,4 @@ -proc egyptdiv a b . . +proc egyptdiv a b . p2 = 1 dbl = b while dbl <= a diff --git a/Task/Element-wise-operations/Arturo/element-wise-operations.arturo b/Task/Element-wise-operations/Arturo/element-wise-operations.arturo new file mode 100644 index 0000000000..350976ebd0 --- /dev/null +++ b/Task/Element-wise-operations/Arturo/element-wise-operations.arturo @@ -0,0 +1,41 @@ +scalar?: $[obj] -> in? type obj [:integer :floating :rational] + +; a function that creates new matrix functions +matrixOp: function [binOp][ + return function [ + a :block :integer :floating :rational + b :block :integer :floating :rational + ] with [binOp][ + when [ + and? block? a, block? b [ + map.with:'y a => [ + map.with:'x & => [ + call binOp @[a\[y]\[x] b\[y]\[x]] + ] + ] + ] + and? scalar? a, block? b -> + map b => [map & 'x -> call binOp @[a x]] + + and? block? a, scalar? b -> + map a => [map & 'x -> call binOp @[x b]] + + any -> throw "Expected at least one matrix." + ] + ] +] +madd: matrixOp 'add +msub: matrixOp 'sub +mmul: matrixOp 'mul +mfdiv: matrixOp 'fdiv +mpow: matrixOp 'pow! + +a: [[1 2] [3 4]] +b: [[5 6] [7 8]] + +print.lines [ + madd a b + msub a b + msub a 2 + msub 2 a +] diff --git a/Task/Element-wise-operations/EasyLang/element-wise-operations.easy b/Task/Element-wise-operations/EasyLang/element-wise-operations.easy new file mode 100644 index 0000000000..31c77deea7 --- /dev/null +++ b/Task/Element-wise-operations/EasyLang/element-wise-operations.easy @@ -0,0 +1,67 @@ +func[][] smul m[][] a . + for i to len m[][] : for j to len m[i][] + m[i][j] *= a + . + return m[][] +. +func[][] sdiv m[][] a . + return smul m[][] (1 / a) +. +func[][] sadd m[][] a . + for i to len m[][] : for j to len m[i][] + m[i][j] += a + . + return m[][] +. +func[][] ssub m[][] a . + return sadd m[][] -a +. +func[][] spow m[][] a . + for i to len m[][] : for j to len m[i][] + m[i][j] = pow m[i][j] a + . + return m[][] +. +func[][] mmul m[][] n[][] . + for i to len m[][] : for j to len m[i][] + m[i][j] *= n[i][j] + . + return m[][] +. +func[][] mdiv m[][] n[][] . + for i to len m[][] : for j to len m[i][] + m[i][j] /= n[i][j] + . + return m[][] +. +func[][] madd m[][] n[][] . + for i to len m[][] : for j to len m[i][] + m[i][j] += n[i][j] + . + return m[][] +. +func[][] msub m[][] n[][] . + for i to len m[][] : for j to len m[i][] + m[i][j] -= n[i][j] + . + return m[][] +. +func[][] mpow m[][] n[][] . + for i to len m[][] : for j to len m[i][] + m[i][j] = pow m[i][j] n[i][j] + . + return m[][] +. +m[][] = [ [ 5 3 ] [ 4 2 ] ] +n[][] = [ [ 1 2 ] [ 7 8 ] ] +# +print smul m[][] 2 +print sdiv m[][] 2 +print sadd m[][] 2 +print ssub m[][] 2 +print spow m[][] 2 +print mmul m[][] n[][] +print mdiv m[][] n[][] +print madd m[][] n[][] +print msub m[][] n[][] +print mpow m[][] n[][] diff --git a/Task/Element-wise-operations/K/element-wise-operations.k b/Task/Element-wise-operations/K/element-wise-operations-1.k similarity index 100% rename from Task/Element-wise-operations/K/element-wise-operations.k rename to Task/Element-wise-operations/K/element-wise-operations-1.k diff --git a/Task/Element-wise-operations/K/element-wise-operations-2.k b/Task/Element-wise-operations/K/element-wise-operations-2.k new file mode 100644 index 0000000000..c6dc27bae1 --- /dev/null +++ b/Task/Element-wise-operations/K/element-wise-operations-2.k @@ -0,0 +1,6 @@ +pow: {:[`f=@|/,//y; `exp y*`ln x / floating point exponent + |/,//s:y<0;o[(s+x*~s)%(~s)+x*s;y|-y] / negative exponent: reciprocate base + */(~b)+((-1+#b){x*x}\x)*b:|2\y]} / binary exponentiation +pow[matrix;matrix] / integer power of integer base +pow[0.0+matrix;matrix] / integer power of floating point base +pow[0.0+matrix;0.0+matrix] / floating point power of floating point base diff --git a/Task/Elementary-cellular-automaton/EasyLang/elementary-cellular-automaton.easy b/Task/Elementary-cellular-automaton/EasyLang/elementary-cellular-automaton.easy index 777a67e2ed..ebc10fe3e3 100644 --- a/Task/Elementary-cellular-automaton/EasyLang/elementary-cellular-automaton.easy +++ b/Task/Elementary-cellular-automaton/EasyLang/elementary-cellular-automaton.easy @@ -1,7 +1,7 @@ global celln[] cell[] . len map[] 8 # -proc evolve . . +proc evolve . for i = 1 to len cell[] ind = 0 for j = i + 1 downto i - 1 @@ -11,14 +11,12 @@ proc evolve . . . swap celln[] cell[] . -proc show . . +proc show . c$[] = [ "." "#" ] - for v in cell[] - write c$[v + 1] - . + for v in cell[] : write c$[v + 1] print "" . -proc run map count inp[] . . +proc run map count inp[] . for i to 8 map[i] = map mod 2 map = map div 2 diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/C-sharp/elliptic-curve-digital-signature-algorithm.cs b/Task/Elliptic-Curve-Digital-Signature-Algorithm/C-sharp/elliptic-curve-digital-signature-algorithm.cs new file mode 100644 index 0000000000..a6248faf23 --- /dev/null +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/C-sharp/elliptic-curve-digital-signature-algorithm.cs @@ -0,0 +1,369 @@ +using System; +using System.Collections.Generic; + +public sealed class EllipticCurveDigitalSignatureAlgorithm +{ + public static void Main(string[] args) + { + // Test parameters for elliptic curve digital signature algorithm, + // using the short Weierstrass model: y^2 = x^3 + ax + b (mod N). + // + // Parameter: a, b, modulus N, base point G, order of G in the elliptic curve. + + List parameters = new List + { + new Parameter(355, 671, 1073741789, new Point(13693, 10088), 1073807281), + new Parameter(0, 7, 67096021, new Point(6580, 779), 16769911), + new Parameter(-3, 1, 877073, new Point(0, 1), 878159), + new Parameter(0, 14, 22651, new Point(63, 30), 151), + new Parameter(3, 2, 5, new Point(2, 1), 5) + }; + + // Parameters which cause failure of the algorithm for the given reasons + // the base point is of composite order + // new Parameter(0, 7, 67096021, new Point(2402, 6067), 33539822), + // the given order is of composite order + // new Parameter(0, 7, 67096021, new Point(6580, 779), 67079644), + // the modulus is not prime (deceptive example) + // new Parameter(0, 7, 877069, new Point(3, 97123), 877069), + // fails if the modulus divides the discriminant + // new Parameter(39, 387, 22651, new Point(95, 27), 22651) + + const long f = 0x789abcde; // The message's digital signature hash which is to be verified + const int d = 0; // Set d > 0 to simulate corrupted data + + foreach (Parameter parameter in parameters) + { + EllipticCurve ellipticCurve = new EllipticCurve(parameter); + Ecdsa(ellipticCurve, f, d); + } + } + + // Build the digital signature for a message using the hash aF with error bit aD + private static void Ecdsa(EllipticCurve aCurve, long aF, int aD) + { + Point point = aCurve.Multiply(aCurve.G, aCurve.R); + + if (aCurve.Discriminant() == 0 || aCurve.G.IsZero() || !point.IsZero() || !aCurve.Contains(aCurve.G)) + { + throw new InvalidOperationException("Invalid parameter in method ecdsa"); + } + + Console.WriteLine(Environment.NewLine + "key generation"); + long s = 1 + (long)(Random() * (double)(aCurve.R - 1)); + point = aCurve.Multiply(aCurve.G, s); + Console.WriteLine("private key s = " + s); + aCurve.PrintPointWithPrefix(point, "public key W = sG"); + + // Find the next highest power of two minus one. + long t = aCurve.R; + long i = 1; + while (i < 64) + { + t |= t >> (int)i; + i <<= 1; + } + long f = aF; + while (f > t) + { + f >>= 1; + } + Console.WriteLine(Environment.NewLine + "aligned hash " + $"{f:x8}"); + + Pair signature = Signature(aCurve, s, f); + Console.WriteLine("signature c, d = " + signature.A + ", " + signature.B); + + long d = aD; + if (d > 0) + { + while (d > t) + { + d >>= 1; + } + f ^= d; + Console.WriteLine(Environment.NewLine + "corrupted hash " + $"{f:x8}"); + } + + Console.WriteLine(Verify(aCurve, point, f, signature) ? "Valid" : "Invalid"); + Console.WriteLine("-----------------"); + } + + private static bool Verify(EllipticCurve aCurve, Point aPoint, long aF, Pair aSignature) + { + if (aSignature.A < 1 || aSignature.A >= aCurve.R || aSignature.B < 1 || aSignature.B >= aCurve.R) + { + return false; + } + + Console.WriteLine(Environment.NewLine + "signature verification"); + long h = ExtendedGCD(aSignature.B, aCurve.R); + long h1 = FloorMod(aF * h, aCurve.R); + long h2 = FloorMod(aSignature.A * h, aCurve.R); + Console.WriteLine("h1, h2 = " + h1 + ", " + h2); + Point v = aCurve.Multiply(aCurve.G, h1); + Point v2 = aCurve.Multiply(aPoint, h2); + aCurve.PrintPointWithPrefix(v, "h1G"); + aCurve.PrintPointWithPrefix(v2, "h2W"); + v = aCurve.Add(v, v2); + aCurve.PrintPointWithPrefix(v, "+ ="); + + if (v.IsZero()) + { + return false; + } + long c1 = FloorMod(v.X, aCurve.R); + Console.WriteLine("c' = " + c1); + return c1 == aSignature.A; + } + + private static Pair Signature(EllipticCurve aCurve, long aS, long aF) + { + long c = 0; + long d = 0; + long u; + Point v; + Console.WriteLine("Signature computation"); + + while (true) + { + while (true) + { + u = 1 + (long)(Random() * (double)(aCurve.R - 1)); + v = aCurve.Multiply(aCurve.G, u); + c = FloorMod(v.X, aCurve.R); + if (c != 0) + { + break; + } + } + + d = FloorMod(ExtendedGCD(u, aCurve.R) * FloorMod(aF + aS * c, aCurve.R), aCurve.R); + if (d != 0) + { + break; + } + } + + Console.WriteLine("one-time u = " + u); + aCurve.PrintPointWithPrefix(v, "V = uG"); + return new Pair(c, d); + } + + // Return 1 / aV modulus aU + private static long ExtendedGCD(long aV, long aU) + { + if (aV < 0) + { + aV += aU; + } + + long result = 0; + long s = 1; + while (aV != 0) + { + long quotient = FloorDiv(aU, aV); + aU = FloorMod(aU, aV); + long temp = aU; aU = aV; aV = temp; + result -= quotient * s; + temp = result; result = s; s = temp; + } + + if (aU != 1) + { + throw new InvalidOperationException("Cannot inverse modulo N, gcd = " + aU); + } + return result; + } + + private static double Random() + { + return _random.NextDouble(); + } + + // C# implementation of Java's Math.floorMod + private static long FloorMod(long x, long y) + { + return ((x % y) + y) % y; + } + + // C# implementation of Java's Math.floorDiv + private static long FloorDiv(long x, long y) + { + long r = x / y; + if ((x ^ y) < 0 && (r * y != x)) + { + r--; + } + return r; + } + + private class EllipticCurve + { + public long A { get; } + public long B { get; } + public long N { get; } + public long R { get; } + public Point G { get; } + + public EllipticCurve(Parameter aParameter) + { + N = aParameter.N; + if (N < 5 || N > MAX_MODULUS) + { + throw new InvalidOperationException("Invalid value for modulus: " + N); + } + + A = FloorMod(aParameter.A, N); + B = FloorMod(aParameter.B, N); + G = aParameter.G; + R = aParameter.R; + + if (R < 5 || R > MAX_ORDER_G) + { + throw new InvalidOperationException("Invalid value for the order of g: " + R); + } + + Console.WriteLine(); + Console.WriteLine("Elliptic curve: y^2 = x^3 + " + A + "x + " + B + " (mod " + N + ")"); + PrintPointWithPrefix(G, "base point G"); + Console.WriteLine("order(G, E) = " + R); + } + + public Point Add(Point aP, Point aQ) + { + if (aP.IsZero()) + { + return aQ; + } + if (aQ.IsZero()) + { + return aP; + } + + long la; + if (aP.X != aQ.X) + { + la = FloorMod((aP.Y - aQ.Y) * ExtendedGCD(aP.X - aQ.X, N), N); + } + else if (aP.Y == aQ.Y && aP.Y != 0) + { + la = FloorMod(FloorMod(FloorMod( + aP.X * aP.X, N) * 3 + A, N) * ExtendedGCD(2 * aP.Y, N), N); + } + else + { + return Point.ZERO; + } + + long xCoordinate = FloorMod(la * la - aP.X - aQ.X, N); + long yCoordinate = FloorMod(la * (aP.X - xCoordinate) - aP.Y, N); + return new Point(xCoordinate, yCoordinate); + } + + public Point Multiply(Point aPoint, long aK) + { + Point result = Point.ZERO; + + while (aK != 0) + { + if ((aK & 1) == 1) + { + result = Add(result, aPoint); + } + aPoint = Add(aPoint, aPoint); + aK >>= 1; + } + return result; + } + + public bool Contains(Point aPoint) + { + if (aPoint.IsZero()) + { + return true; + } + + long r = FloorMod(FloorMod(A + aPoint.X * aPoint.X, N) * aPoint.X + B, N); + long s = FloorMod(aPoint.Y * aPoint.Y, N); + return r == s; + } + + public long Discriminant() + { + long constant = 4 * FloorMod(A * A, N) * FloorMod(A, N); + return FloorMod(-16 * (FloorMod(B * B, N) * 27 + constant), N); + } + + public void PrintPointWithPrefix(Point aPoint, string aPrefix) + { + long y = aPoint.Y; + if (aPoint.IsZero()) + { + Console.WriteLine(aPrefix + " (0)"); + } + else + { + if (y > N - y) + { + y -= N; + } + Console.WriteLine(aPrefix + " (" + aPoint.X + ", " + y + ")"); + } + } + } + + private class Point + { + public long X { get; } + public long Y { get; } + + public Point(long aX, long aY) + { + X = aX; + Y = aY; + } + + public bool IsZero() + { + return X == INFINITY && Y == 0; + } + + private const long INFINITY = long.MaxValue; + public static readonly Point ZERO = new Point(INFINITY, 0); + } + + private class Pair + { + public long A { get; } + public long B { get; } + + public Pair(long a, long b) + { + A = a; + B = b; + } + } + + private class Parameter + { + public long A { get; } + public long B { get; } + public long N { get; } + public Point G { get; } + public long R { get; } + + public Parameter(long a, long b, long n, Point g, long r) + { + A = a; + B = b; + N = n; + G = g; + R = r; + } + } + + private const int MAX_MODULUS = 1073741789; + private const int MAX_ORDER_G = MAX_MODULUS + 65536; + + private static readonly Random _random = new Random(); +} diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/JavaScript/elliptic-curve-digital-signature-algorithm.js b/Task/Elliptic-Curve-Digital-Signature-Algorithm/JavaScript/elliptic-curve-digital-signature-algorithm.js new file mode 100644 index 0000000000..2641d7ad34 --- /dev/null +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/JavaScript/elliptic-curve-digital-signature-algorithm.js @@ -0,0 +1,356 @@ +class EllipticCurveDigitalSignatureAlgorithm { + static main() { + // Test parameters for elliptic curve digital signature algorithm, + // using the short Weierstrass model: y^2 = x^3 + ax + b (mod N). + // + // Parameter: a, b, modulus N, base point G, order of G in the elliptic curve. + + const parameters = [ + new Parameter(355, 671, 1073741789, new Point(13693, 10088), 1073807281), + new Parameter(0, 7, 67096021, new Point(6580, 779), 16769911), + new Parameter(-3, 1, 877073, new Point(0, 1), 878159), + new Parameter(0, 14, 22651, new Point(63, 30), 151), + new Parameter(3, 2, 5, new Point(2, 1), 5), + ]; + + // Parameters which cause failure of the algorithm for the given reasons + // the base point is of composite order + // new Parameter( 0, 7, 67096021, new Point( 2402, 6067), 33539822 ), + // the given order is of composite order + // new Parameter( 0, 7, 67096021, new Point( 6580, 779), 67079644 ), + // the modulus is not prime (deceptive example) + // new Parameter( 0, 7, 877069, new Point( 3, 97123), 877069 ), + // fails if the modulus divides the discriminant + // new Parameter( 39, 387, 22651, new Point( 95, 27), 22651 ) ); + + const f = 0x789abcde; // The message's digital signature hash which is to be verified + const d = 0; // Set d > 0 to simulate corrupted data + + for (const parameter of parameters) { + const ellipticCurve = new EllipticCurve(parameter); + EllipticCurveDigitalSignatureAlgorithm.ecdsa(ellipticCurve, f, d); + } + } + + // Build the digital signature for a message using the hash aF with error bit aD + static ecdsa(aCurve, aF, aD) { + let point = aCurve.multiply(aCurve.g, aCurve.r); + + if ( + aCurve.discriminant() == 0 || + aCurve.g.isZero() || + !point.isZero() || + !aCurve.contains(aCurve.g) + ) { + //throw new Error("Invalid parameter in method ecdsa"); + } + + console.log("\nkey generation"); + const s = 1 + Math.floor(Math.random() * (aCurve.r - 1)); + point = aCurve.multiply(aCurve.g, s); + console.log("private key s = " + s); + aCurve.printPointWithPrefix(point, "public key W = sG"); + + // Find the next highest power of two minus one. + let t = aCurve.r; + let i = 1; + while (i < 64) { + t |= t >> i; + i <<= 1; + } + let f = aF; + while (f > t) { + f >>= 1; + } + console.log("\naligned hash " + f.toString(16).padStart(8, '0')); + + const signature = EllipticCurveDigitalSignatureAlgorithm.signature( + aCurve, + s, + f + ); + console.log("signature c, d = " + signature.a + ", " + signature.b); + + let d = aD; + if (d > 0) { + while (d > t) { + d >>= 1; + } + f ^= d; + console.log("\ncorrupted hash " + f.toString(16).padStart(8, '0')); + } + + console.log( + EllipticCurveDigitalSignatureAlgorithm.verify(aCurve, point, f, signature) + ? "Valid" + : "Invalid" + ); + console.log("-----------------"); + } + + static verify(aCurve, aPoint, aF, aSignature) { + if ( + aSignature.a < 1 || + aSignature.a >= aCurve.r || + aSignature.b < 1 || + aSignature.b >= aCurve.r + ) { + return false; + } + + console.log("\nsignature verification"); + const h = EllipticCurveDigitalSignatureAlgorithm.extendedGCD( + aSignature.b, + aCurve.r + ); + const h1 = EllipticCurveDigitalSignatureAlgorithm.floorMod(aF * h, aCurve.r); + const h2 = EllipticCurveDigitalSignatureAlgorithm.floorMod(aSignature.a * h, aCurve.r); + console.log("h1, h2 = " + h1 + ", " + h2); + let v = aCurve.multiply(aCurve.g, h1); + let v2 = aCurve.multiply(aPoint, h2); + aCurve.printPointWithPrefix(v, "h1G"); + aCurve.printPointWithPrefix(v2, "h2W"); + v = aCurve.add(v, v2); + aCurve.printPointWithPrefix(v, "+ ="); + + if (v.isZero()) { + return false; + } + const c1 = EllipticCurveDigitalSignatureAlgorithm.floorMod(v.x, aCurve.r); + console.log("c' = " + c1); + return c1 == aSignature.a; + } + + static signature(aCurve, aS, aF) { + let c = 0; + let d = 0; + let u; + let v; + console.log("Signature computation"); + + while (true) { + while (true) { + u = 1 + Math.floor(Math.random() * (aCurve.r - 1)); + v = aCurve.multiply(aCurve.g, u); + c = EllipticCurveDigitalSignatureAlgorithm.floorMod(v.x, aCurve.r); + if (c != 0) { + break; + } + } + + d = EllipticCurveDigitalSignatureAlgorithm.floorMod( + EllipticCurveDigitalSignatureAlgorithm.extendedGCD(u, aCurve.r) * + EllipticCurveDigitalSignatureAlgorithm.floorMod(aF + aS * c, aCurve.r), + aCurve.r + ); + if (d != 0) { + break; + } + } + + console.log("one-time u = " + u); + aCurve.printPointWithPrefix(v, "V = uG"); + return new Pair(c, d); + } + + // Return 1 / aV modulus aU + static extendedGCD(aV, aU) { + if (aV < 0) { + aV += aU; + } + + let result = 0; + let s = 1; + while (aV != 0) { + const quotient = Math.floor(aU / aV); + aU = EllipticCurveDigitalSignatureAlgorithm.floorMod(aU, aV); + let temp = aU; + aU = aV; + aV = temp; + result -= quotient * s; + temp = result; + result = s; + s = temp; + } + + if (aU != 1) { + throw new Error("Cannot inverse modulo N, gcd = " + aU); + } + return result; + } + + static floorMod(x, y) { + return ((x % y) + y) % y; + } + + // static random() { + // return Math.random(); + // } +} + +class EllipticCurve { + constructor(aParameter) { + this.n = aParameter.n; + if (this.n < 5 || this.n > EllipticCurveDigitalSignatureAlgorithm.MAX_MODULUS) { + throw new Error("Invalid value for modulus: " + this.n); + } + + this.a = EllipticCurveDigitalSignatureAlgorithm.floorMod(aParameter.a, this.n); + this.b = EllipticCurveDigitalSignatureAlgorithm.floorMod(aParameter.b, this.n); + this.g = aParameter.g; + this.r = aParameter.r; + + if (this.r < 5 || this.r > EllipticCurveDigitalSignatureAlgorithm.MAX_ORDER_G) { + throw new Error("Invalid value for the order of g: " + this.r); + } + + console.log(); + console.log( + "Elliptic curve: y^2 = x^3 + " + + this.a + + "x + " + + this.b + + " (mod " + + this.n + + ")" + ); + this.printPointWithPrefix(this.g, "base point G"); + console.log("order(G, E) = " + this.r); + } + + add(aP, aQ) { + if (aP.isZero()) { + return aQ; + } + if (aQ.isZero()) { + return aP; + } + + let la; + if (aP.x != aQ.x) { + la = EllipticCurveDigitalSignatureAlgorithm.floorMod( + (aP.y - aQ.y) * + EllipticCurveDigitalSignatureAlgorithm.extendedGCD(aP.x - aQ.x, this.n), + this.n + ); + } else if (aP.y == aQ.y && aP.y != 0) { + la = EllipticCurveDigitalSignatureAlgorithm.floorMod( + EllipticCurveDigitalSignatureAlgorithm.floorMod( + EllipticCurveDigitalSignatureAlgorithm.floorMod(aP.x * aP.x, this.n) * 3 + + this.a, + this.n + ) * EllipticCurveDigitalSignatureAlgorithm.extendedGCD(2 * aP.y, this.n), + this.n + ); + } else { + return Point.ZERO; + } + + const xCoordinate = EllipticCurveDigitalSignatureAlgorithm.floorMod( + la * la - aP.x - aQ.x, + this.n + ); + const yCoordinate = EllipticCurveDigitalSignatureAlgorithm.floorMod( + la * (aP.x - xCoordinate) - aP.y, + this.n + ); + return new Point(xCoordinate, yCoordinate); + } + + multiply(aPoint, aK) { + let result = Point.ZERO; + + while (aK != 0) { + if ((aK & 1) == 1) { + result = this.add(result, aPoint); + } + aPoint = this.add(aPoint, aPoint); + aK >>= 1; + } + return result; + } + + contains(aPoint) { + if (aPoint.isZero()) { + return true; + } + + const r = EllipticCurveDigitalSignatureAlgorithm.floorMod( + EllipticCurveDigitalSignatureAlgorithm.floorMod( + this.a + aPoint.x * aPoint.x, + this.n + ) * aPoint.x + this.b, + this.n + ); + const s = EllipticCurveDigitalSignatureAlgorithm.floorMod(aPoint.y * aPoint.y, this.n); + return r == s; + } + + discriminant() { + const constant = + 4 * + EllipticCurveDigitalSignatureAlgorithm.floorMod( + this.a * this.a, + this.n + ) * + EllipticCurveDigitalSignatureAlgorithm.floorMod(this.a, this.n); + return EllipticCurveDigitalSignatureAlgorithm.floorMod( + -16 * + (EllipticCurveDigitalSignatureAlgorithm.floorMod(this.b * this.b, this.n) * + 27 + + constant), + this.n + ); + } + + printPointWithPrefix(aPoint, aPrefix) { + let y = aPoint.y; + if (aPoint.isZero()) { + console.log(aPrefix + " (0)"); + } else { + if (y > this.n - y) { + y -= this.n; + } + console.log(aPrefix + " (" + aPoint.x + ", " + y + ")"); + } + } +} + +class Point { + constructor(aX, aY) { + this.x = aX; + this.y = aY; + } + + isZero() { + return this.x == Point.INFINITY && this.y == 0; + } +} + +class Pair { + constructor(a, b) { + this.a = a; + this.b = b; + } +} + +class Parameter { + constructor(a, b, n, g, r) { + this.a = a; + this.b = b; + this.n = n; + this.g = g; + this.r = r; + } +} + +Point.INFINITY = Number.MAX_SAFE_INTEGER; +Point.ZERO = new Point(Point.INFINITY, 0); + +EllipticCurveDigitalSignatureAlgorithm.MAX_MODULUS = 1073741789; +EllipticCurveDigitalSignatureAlgorithm.MAX_ORDER_G = + EllipticCurveDigitalSignatureAlgorithm.MAX_MODULUS + 65536; + +// EllipticCurveDigitalSignatureAlgorithm.RANDOM = Math.random(); + +EllipticCurveDigitalSignatureAlgorithm.main(); diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/Rust/elliptic-curve-digital-signature-algorithm.rs b/Task/Elliptic-Curve-Digital-Signature-Algorithm/Rust/elliptic-curve-digital-signature-algorithm.rs new file mode 100644 index 0000000000..2d6010e4d8 --- /dev/null +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/Rust/elliptic-curve-digital-signature-algorithm.rs @@ -0,0 +1,507 @@ +use rand::Rng; +use std::{cmp::Ordering, mem}; + +// --- Constants --- +const MAX_MODULUS: i64 = 1_073_741_789; +const MAX_ORDER_G: i64 = MAX_MODULUS + 65536; + +// --- Structures --- + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +struct Point { + x: i64, + y: i64, +} + +impl Point { + // Represents the point at infinity (identity element) + const ZERO: Point = Point { x: i64::MAX, y: 0 }; + + fn new(x: i64, y: i64) -> Self { + Point { x, y } + } + + fn is_zero(&self) -> bool { + *self == Point::ZERO + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +struct Pair { + // Often represents (c, d) in ECDSA signature + c: i64, // Renamed 'a' to 'c' for clarity in ECDSA context + d: i64, // Renamed 'b' to 'd' for clarity in ECDSA context +} + +impl Pair { + fn new(c: i64, d: i64) -> Self { + Pair { c, d } + } +} + +#[derive(Debug, Copy, Clone)] +struct Parameter { + a: i64, + b: i64, + n: i64, // Modulus + g: Point, // Base point + r: i64, // Order of G +} + +impl Parameter { + fn new(a: i64, b: i64, n: i64, g: Point, r: i64) -> Self { + Parameter { a, b, n, g, r } + } +} + +// --- Helper Functions --- + +// Consistent floor modulus (handles negative numbers) +fn floor_mod(num: i64, modulus: i64) -> i64 { + // Assumes modulus > 0, which is true for elliptic curve 'n' and 'r' + // If modulus can be negative, more complex logic is needed like in the C++ version. + // For ECDSA n and r are positive. + if modulus <= 0 { + panic!("Modulus must be positive for floor_mod in this context."); + } + // ((num % modulus) + modulus) % modulus + let rem = num % modulus; + if rem < 0 { + rem + modulus + } else { + rem + } +} + +// Extended Euclidean Algorithm to find modular multiplicative inverse. +// Returns `x` such that `(a * x) % m == 1`. +// Returns Err if gcd(a, m) != 1 (no inverse exists). +fn extended_gcd(a: i64, m: i64) -> Result { + if m <= 0 { + return Err("Modulus must be positive for extended_gcd".to_string()); + } + let mut v = floor_mod(a, m); // Ensure v is in [0, m-1] + let mut u = m; + let mut result: i64 = 0; + let mut s: i64 = 1; + + while v != 0 { + // Using standard Euclidean algorithm division, not floor_div, as 'v' and 'u' are non-negative + let quotient = u / v; + u = u % v; + mem::swap(&mut u, &mut v); // Swap u and v + + // Update Bezout coefficients + let next_result = result.wrapping_sub(quotient.wrapping_mul(s)); + result = s; + s = next_result; + + // Keep result and s within i64 range reasonably + // (Technically full modular arithmetic on coefficients is better, + // but for typical crypto sizes i64 is usually sufficient) + } + + if u != 1 { + Err(format!( + "Cannot inverse modulo N={}, gcd({}, {}) = {}", + m, a, m, u + )) + } else { + // Ensure the result is positive + Ok(floor_mod(result, m)) + } +} + +// --- Elliptic Curve Logic --- + +#[derive(Debug, Clone)] // Cannot Copy as methods take &self +struct EllipticCurve { + a: i64, + b: i64, + n: i64, // Modulus + r: i64, // Order of G + g: Point, // Base point +} + +impl EllipticCurve { + // Constructor with validation + fn new(param: Parameter) -> Result { + if param.n < 5 || param.n > MAX_MODULUS { + return Err(format!("Invalid value for modulus: {}", param.n)); + } + if param.r < 5 || param.r > MAX_ORDER_G { + return Err(format!( + "Invalid value for the order of g: {}", + param.r + )); + } + + let a = floor_mod(param.a, param.n); + let b = floor_mod(param.b, param.n); + + let curve = EllipticCurve { + a, + b, + n: param.n, + r: param.r, + g: param.g, + }; + + println!("\nElliptic curve: y^2 = x^3 + {}x + {} (mod {})", a, b, param.n); + curve.print_point_with_prefix(curve.g, "base point G"); + println!("order(G, E) = {}", curve.r); + + // Basic check: Base point must be on the curve + if !param.g.is_zero() && !curve.contains(param.g) { + return Err(format!("Base point G {:?} is not on the curve", param.g)); + } + // Basic check: Order * G should be Zero + let order_check = curve.multiply(curve.g, curve.r); + // Check if multiplication failed or result is not Zero + match order_check { + Ok(p) if !p.is_zero() => return Err(format!("Order r={} is invalid for G: r*G is not Zero", curve.r)), + Err(e) => return Err(format!("Failed order check multiplication: {}", e)), + _ => {} // Ok and point is Zero, proceed + } + // Basic check: Discriminant non-zero (for non-singular curve) + let disc = curve.discriminant()?; + if disc == 0 { + return Err("Curve discriminant is zero (singular curve)".to_string()); + } + + Ok(curve) + } + + // Point addition (P + Q) + fn add(&self, p: Point, q: Point) -> Result { + if p.is_zero() { + return Ok(q); + } + if q.is_zero() { + return Ok(p); + } + + let lambda: i64; + if p.x != q.x { + // P != Q + let dy = p.y.wrapping_sub(q.y); + let dx = p.x.wrapping_sub(q.x); + let dx_inv = extended_gcd(dx, self.n)?; + lambda = floor_mod(dy.wrapping_mul(dx_inv), self.n); + } else if p.y == q.y && p.y != 0 { + // P == Q (Point doubling) + // lambda = (3*x^2 + a) / (2*y) mod n + let x_sq = floor_mod(p.x.wrapping_mul(p.x), self.n); + let numerator = floor_mod(x_sq.wrapping_mul(3).wrapping_add(self.a), self.n); + let denominator = floor_mod(p.y.wrapping_mul(2), self.n); + let denominator_inv = extended_gcd(denominator, self.n)?; + lambda = floor_mod(numerator.wrapping_mul(denominator_inv), self.n); + } else { + // P == -Q (p.x == q.x but p.y == -q.y mod n) or P == Q == (x, 0) + return Ok(Point::ZERO); + } + + // x_r = lambda^2 - x_p - x_q mod n + let lambda_sq = floor_mod(lambda.wrapping_mul(lambda), self.n); + let x_r = floor_mod( + lambda_sq.wrapping_sub(p.x).wrapping_sub(q.x), + self.n, + ); + + // y_r = lambda * (x_p - x_r) - y_p mod n + let x_p_sub_x_r = p.x.wrapping_sub(x_r); + let term1 = floor_mod(lambda.wrapping_mul(x_p_sub_x_r), self.n); + let y_r = floor_mod(term1.wrapping_sub(p.y), self.n); + + Ok(Point::new(x_r, y_r)) + } + + // Scalar multiplication (k * P) using double-and-add + fn multiply(&self, mut point: Point, mut k: i64) -> Result { + let mut result = Point::ZERO; + if k < 0 { + // This basic implementation doesn't handle negative k easily. + // Standard ECDSA uses positive scalars (private key, random nonce). + // If needed, one could compute k = k mod r, or compute point negation. + return Err("Negative scalar multiplication not directly supported".to_string()); + } + if k == 0 { + return Ok(Point::ZERO); + } + + // Ensure k is positive and reduced modulo r if necessary, though ECDSA usually handles this before calling. + // k = floor_mod(k, self.r); // Optional: Reduce k modulo order, requires r > 0 + + while k > 0 { + if (k & 1) == 1 { + result = self.add(result, point)?; + } + point = self.add(point, point)?; // Double the point + k >>= 1; // Halve the scalar + } + Ok(result) + } + + // Check if a point lies on the curve y^2 = x^3 + ax + b (mod n) + fn contains(&self, point: Point) -> bool { + if point.is_zero() { + return true; // Point at infinity is always on the curve + } + + // y^2 mod n + let lhs = floor_mod(point.y.wrapping_mul(point.y), self.n); + + // x^3 + ax + b mod n + let x_sq = floor_mod(point.x.wrapping_mul(point.x), self.n); + let x_cubed = floor_mod(x_sq.wrapping_mul(point.x), self.n); + let ax = floor_mod(self.a.wrapping_mul(point.x), self.n); + let rhs = floor_mod(x_cubed.wrapping_add(ax).wrapping_add(self.b), self.n); + + lhs == rhs + } + + // Calculate discriminant: -16 * (4a^3 + 27b^2) mod n + fn discriminant(&self) -> Result { + // Need intermediate results, use wrapping arithmetic carefully + let a_sq = floor_mod(self.a.wrapping_mul(self.a), self.n); + let a_cubed = floor_mod(a_sq.wrapping_mul(self.a), self.n); + let term1 = floor_mod(a_cubed.wrapping_mul(4), self.n); // 4a^3 + + let b_sq = floor_mod(self.b.wrapping_mul(self.b), self.n); + let term2 = floor_mod(b_sq.wrapping_mul(27), self.n); // 27b^2 + + let inner_sum = floor_mod(term1.wrapping_add(term2), self.n); // 4a^3 + 27b^2 + let result = floor_mod(inner_sum.wrapping_mul(-16), self.n); + + Ok(result) + } + + // Helper to print points + fn print_point_with_prefix(&self, point: Point, prefix: &str) { + if point.is_zero() { + println!("{} (0 - Point at Infinity)", prefix); + } else { + // Optionally represent y with the smaller absolute value coordinate + let mut y_repr = point.y; + if y_repr > self.n / 2 { // Simplified check assuming n > 0 + y_repr = y_repr.wrapping_sub(self.n); + } + println!("{} ({}, {})", prefix, point.x, y_repr); + } + } +} + +// --- ECDSA Functions --- + +// Generate a random number 0.0 <= x < 1.0 +fn random_f64() -> f64 { + let mut rng = rand::thread_rng(); + rng.gen::() +} + +// Generate a random integer 1 <= x < limit +fn random_i64_in_range(limit: i64) -> i64 { + if limit <= 1 { + // Avoid panic in gen_range(1..limit) if limit is 1 or less. + // In ECDSA, the limit (order r) should be > 1. + // If r was 1 or less, curve setup should have failed. + panic!("Range limit must be greater than 1 for random generation"); + } + let mut rng = rand::thread_rng(); + rng.gen_range(1..limit) // Exclusive upper bound +} + + +// Create ECDSA signature (c, d) for message hash f +// s: private key +fn signature(curve: &EllipticCurve, s: i64, f: i64) -> Result { + if curve.r <= 1 { + return Err("Curve order 'r' must be greater than 1 for signing.".to_string()); + } + + loop { + // 1. Generate random nonce 'u' (called 'k' in many texts) in [1, r-1] + let u = random_i64_in_range(curve.r); + + // 2. Calculate curve point V = u * G + let v = curve.multiply(curve.g, u)?; + if v.is_zero() { continue; } // Should technically not happen if u in [1, r-1] + + // 3. Calculate c = V.x mod r + let c = floor_mod(v.x, curve.r); + if c == 0 { continue; } // Retry if c is 0 + + // 4. Calculate d = u^-1 * (f + s*c) mod r + let u_inv = extended_gcd(u, curve.r)?; // u^-1 mod r + let s_times_c = floor_mod(s.wrapping_mul(c), curve.r); + let hash_plus_sc = floor_mod(f.wrapping_add(s_times_c), curve.r); + let d = floor_mod(u_inv.wrapping_mul(hash_plus_sc), curve.r); + + if d == 0 { continue; } // Retry if d is 0 + + println!("one-time u = {}", u); + curve.print_point_with_prefix(v, "V = uG"); + return Ok(Pair::new(c, d)); + } +} + +// Verify ECDSA signature +// point W: public key (W = s*G) +// f: message hash (same as used for signing) +// signature (c, d): the signature to verify +fn verify(curve: &EllipticCurve, public_key_w: Point, f: i64, signature: Pair) -> Result { + let (c, d) = (signature.c, signature.d); + + // 1. Check if c and d are in the valid range [1, r-1] + if !(1..curve.r).contains(&c) || !(1..curve.r).contains(&d) { + println!("Verification fail: c or d out of range [1, r-1]"); + return Ok(false); + } + + println!("\nSignature verification"); + + // 2. Calculate h = d^-1 mod r + let h = extended_gcd(d, curve.r)?; + + // 3. Calculate h1 = f * h mod r + // 4. Calculate h2 = c * h mod r + let h1 = floor_mod(f.wrapping_mul(h), curve.r); + let h2 = floor_mod(c.wrapping_mul(h), curve.r); + println!("h = d^-1 = {}", h); + println!("h1 = f*h = {}", h1); + println!("h2 = c*h = {}", h2); + + // 5. Calculate point V' = h1*G + h2*W + let v1 = curve.multiply(curve.g, h1)?; + let v2 = curve.multiply(public_key_w, h2)?; + curve.print_point_with_prefix(v1, "h1*G"); + curve.print_point_with_prefix(v2, "h2*W"); + + let v_prime = curve.add(v1, v2)?; + curve.print_point_with_prefix(v_prime, "+ = V'"); + + // 6. Check if V' is the point at infinity + if v_prime.is_zero() { + println!("Verification fail: V' is point at infinity"); + return Ok(false); + } + + // 7. Calculate c' = V'.x mod r + let c_prime = floor_mod(v_prime.x, curve.r); + println!("c' = V'.x mod r = {}", c_prime); + + // 8. Signature is valid if c' == c + Ok(c_prime == c) +} + +// Main ECDSA process: keygen, sign, verify +fn ecdsa(curve: &EllipticCurve, f_original: i64, d_error: i32) -> Result<(), String> { + // Initial curve/parameter checks (already done in EllipticCurve::new, but re-stated here) + // if curve.discriminant()? == 0 { return Err("Invalid parameter: discriminant is 0".to_string()); } + // if curve.g.is_zero() { return Err("Invalid parameter: base point G is zero".to_string()); } + // let point_check = curve.multiply(curve.g, curve.r)?; + // if !point_check.is_zero() { return Err("Invalid parameter: r*G is not zero".to_string()); } + // if !curve.contains(curve.g) { return Err("Invalid parameter: G is not on the curve".to_string()); } + + println!("\nKey generation"); + // 1. Generate private key 's' in [1, r-1] + let s = random_i64_in_range(curve.r); + // 2. Calculate public key W = s * G + let public_key_w = curve.multiply(curve.g, s)?; + println!("private key s = {}", s); + curve.print_point_with_prefix(public_key_w, "public key W = sG"); + + + // Align hash f to be within the bit range related to r + let mut f = f_original; + // Find the next highest power of two minus one for r (rough bit mask) + let mut t = curve.r; + if t > 0 { // Avoid infinite loop if r is 0 or negative (shouldn't happen) + // Efficient way to get next power of 2 minus 1 (all lower bits set) + t |= t >> 1; + t |= t >> 2; + t |= t >> 4; + t |= t >> 8; + t |= t >> 16; + t |= t >> 32; // For i64 + + // Reduce f if it's larger than the bit mask t + // This step isn't standard ECDSA but mimics the C++ example's behavior. + // Standard ECDSA typically takes the leftmost min(N, L) bits of the hash, + // where N is bit length of r, L is bit length of hash output. + while f > 0 && t > 0 && f > t { + println!("Warning: Hash {} > bitmask {}. Right-shifting hash (non-standard).", f, t); + f >>= 1; + } + } else { + println!("Warning: Curve order r ({}) is not positive. Hash alignment skipped.", curve.r); + t = i64::MAX; // Allow any hash if r is invalid + } + + println!("\nAligned hash f = 0x{:08x} ({})", f, f); + + // Sign the hash + let signature_pair = signature(curve, s, f)?; + println!("Signature (c, d) = ({}, {})", signature_pair.c, signature_pair.d); + + // Simulate data corruption if d_error > 0 + let mut f_verify = f; + if d_error > 0 { + let mut error_val = d_error as i64; + // Align the error like the hash was aligned (mimicking C++ again) + while error_val > 0 && t > 0 && error_val > t { + error_val >>= 1; + } + f_verify ^= error_val; // Apply error using XOR + println!( + "\nCorrupted hash f' = 0x{:08x} ({}) (error=0x{:x})", + f_verify, f_verify, d_error + ); + } + + // Verify the signature + let is_valid = verify(curve, public_key_w, f_verify, signature_pair)?; + println!("{}", if is_valid { "Valid" } else { "Invalid" }); + println!("-----------------"); + + Ok(()) +} + +fn main() { + // Test parameters for elliptic curve digital signature algorithm, + // using the short Weierstrass model: y^2 = x^3 + ax + b (mod N). + // Parameter: a, b, modulus N, base point G(x, y), order of G. + let parameters = vec![ + Parameter::new(355, 671, 1_073_741_789, Point::new(13693, 10088), 1_073_807_281), + Parameter::new(0, 7, 67_096_021, Point::new(6580, 779), 16_769_911), + Parameter::new(-3, 1, 877_073, Point::new(0, 1), 878_159), // SECp256k1 shape (a=0, b=7) is common, this is a=-3 + Parameter::new(0, 14, 22_651, Point::new(63, 30), 151), + Parameter::new(3, 2, 5, Point::new(2, 1), 5), // Very small curve example + ]; + + // Parameters which cause failure (commented out like C++) + // Parameter::new(0, 7, 67096021, Point::new(2402, 6067), 33539822), // G has composite order + // Parameter::new(0, 7, 67096021, Point::new(6580, 779), 67079644), // r is composite (multiple of true order) + // Parameter::new(0, 7, 877069, Point::new(3, 97123), 877069), // N not prime (877069 = 877 * 1000 + 69, maybe 7*125295 + 4?) Let's check: 877069 / 7 = 125295.5; 877069 / 11.. nope. 877069 is prime. The comment might be wrong, or the point/order pair fails for other reasons. + // Parameter::new(39, 387, 22651, Point::new(95, 27), 22651) // N divides discriminant? disc = -16*(4*39^3+27*387^2) mod 22651. Let's check: 4*39^3+27*387^2 = 4*59319 + 27*149769 = 237276 + 4043763 = 4281039. 4281039 mod 22651 = 0. Yes, N divides discriminant -> singular curve. + + // The message hash (often SHA-256 output truncated/converted to integer) + let f_hash: i64 = 0x789a_bcde; + // Set d_error > 0 to simulate corrupted data before verification + let d_error: i32 = 0; // 0 means no error + + for param in parameters { + match EllipticCurve::new(param) { + Ok(curve) => { + if let Err(e) = ecdsa(&curve, f_hash, d_error) { + eprintln!("ECDSA Error for curve {:?}: {}", param, e); + println!("-----------------"); + } + } + Err(e) => { + eprintln!("Failed to create curve with parameters {:?}: {}", param, e); + println!("-----------------"); + } + } + } +} diff --git a/Task/Elliptic-curve-arithmetic/ALGOL-68/elliptic-curve-arithmetic.alg b/Task/Elliptic-curve-arithmetic/ALGOL-68/elliptic-curve-arithmetic.alg new file mode 100644 index 0000000000..a4d2aa99b0 --- /dev/null +++ b/Task/Elliptic-curve-arithmetic/ALGOL-68/elliptic-curve-arithmetic.alg @@ -0,0 +1,81 @@ +BEGIN # elliptic curve arithmetic - translation of the C sample # + + INT bx0 = 7; + MODE PT = STRUCT( REAL x, y ); + + # using max real for INIFINTY # + PROC zero = PT: ( max real, max real ); + + OP ISZERO = ( PT p )BOOL: x OF p > 1e20 OR x OF p < -1e20; + OP - = ( PT p )PT: ( x OF p, - y OF p ); + + OP DBL = ( PT p )PT: + IF ISZERO p + THEN p + ELSE REAL l = ( 3 * x OF p * x OF p ) / ( 2 * y OF p ); + REAL rx = l * l - 2 * x OF p; + ( rx, l * ( x OF p - rx ) - y OF p ) + FI # DBL # ; + OP = = ( PT p, q )BOOL: x OF p = x OF q AND y OF p = y OF q; + OP + = ( PT p, q )PT: + IF p = q + THEN DBL p + ELIF ISZERO p + THEN q + ELIF ISZERO q + THEN p + ELIF x OF q = x OF p + THEN zero + ELSE REAL l = ( y OF q - y OF p ) / ( x OF q - x OF p ); + REAL rx = l * l - x OF p - x OF q; + ( rx, l * ( x OF p - rx ) - y OF p ) + FI # ~ # ; + OP +:= = ( REF PT p, PT q )REF PT: p := p + q; + OP * = ( PT p in, INT n )PT: + BEGIN + PT p := p in, r := zero; + INT i := 1; + WHILE i <= n DO + IF ABS ( BIN i AND BIN n ) /= 0 THEN r +:= p FI; + p := DBL p; + i *:= 2 + OD; + r + END # * # ; + + OP TOPT = ( REAL y )PT: + IF REAL v = y * y - bx0; v = 0 + THEN zero + ELSE ( SIGN v * ABS v ^ ( 1 / 3 ), y ) + FI # TOPT # ; + OP TOPT = ( INT y )PT: TOPT REAL( y ); + OP FMT = ( REAL v )STRING: + BEGIN + STRING result := fixed( v, -18, 3 ); + INT s pos := 1; + WHILE result[ s pos ] = " " DO s pos +:= 1 OD; + result[ s pos : ] + END # FMT # ; + PROC show = ( STRING s, PT p )VOID: + print( ( s + , IF ISZERO p + THEN "Zero" + ELSE ( "(" + FMT x OF p + ", " + FMT y OF p + ")" ) + FI + , newline + ) + ) # show # ; + + BEGIN # task # + PT a = TOPT 1, b = TOPT 2; + PT c = a + b; + PT d = -c; + show( "a = ", a ); + show( "b = ", b ); + show( "c = a + b = ", c ); + show( "d = -c = ", d ); + show( "c + d = ", c + d ); + show( "a + b + d = ", a + ( b + d ) ); + show( "a * 12345 = ", a * 12345 ) + END +END diff --git a/Task/Elliptic-curve-arithmetic/FreeBASIC/elliptic-curve-arithmetic.basic b/Task/Elliptic-curve-arithmetic/FreeBASIC/elliptic-curve-arithmetic.basic new file mode 100644 index 0000000000..37da585f1a --- /dev/null +++ b/Task/Elliptic-curve-arithmetic/FreeBASIC/elliptic-curve-arithmetic.basic @@ -0,0 +1,98 @@ +Const As Double INF = 1e30 + +Type Punto + As Double x, y + Declare Constructor (x As Double = INF, y As Double = INF) + Declare Function copy() As Punto + Declare Function isZero() As Integer + Declare Function neg() As Punto + Declare Function dbl() As Punto + Declare Function sum(q As Punto) As Punto + Declare Function mul(n As Integer) As Punto + Declare Function ToString() As String +End Type + +Dim Shared As Integer bCoeff = 7 ' Coeficiente de la curva elíptica + +Constructor Punto(x As Double, y As Double) + This.x = Iif(Abs(x) > 1e20, INF, x) + This.y = Iif(Abs(y) > 1e20, INF, y) +End Constructor + +Function Punto.copy() As Punto + Return Type(This.x, This.y) +End Function + +Function Punto.isZero() As Integer + Return This.x >= 1e20 Or This.x <= -1e20 Or This.x = INF +End Function + +Function Punto.neg() As Punto + Return Type(This.x, -This.y) +End Function + +Function Punto.dbl() As Punto + If This.isZero() Then Return This.copy() + + If Abs(This.y) < 1e-15 Then Return Punto() + + Dim As Double L = (3 * This.x * This.x) / (2 * This.y) + Dim As Double x3 = L * L - 2 * This.x + Return Type(x3, L * (This.x - x3) - This.y) +End Function + +Function Punto.sum(q As Punto) As Punto + If This.x = q.x And This.y = q.y Then Return This.dbl() + If This.isZero() Then Return q.copy() + If q.isZero() Then Return This.copy() + + If Abs(q.x - This.x) < 1e-15 Then Return Punto() + + Dim As Double L = (q.y - This.y) / (q.x - This.x) + Dim As Double x3 = L * L - This.x - q.x + Return Type(x3, L * (This.x - x3) - This.y) +End Function + +Function Punto.mul(n As Integer) As Punto + Dim As Punto r = Punto(), p = This.copy() + + While n > 0 + If (n And 1) Then r = r.sum(p) + p = p.dbl() + n = n Shr 1 + Wend + Return r +End Function + +Function Punto.ToString() As String + If This.isZero() Then Return "Zero" + Return "(" & Str(Int(This.x * 1000) / 1000) & ", " & Str(Int(This.y * 1000) / 1000) & ")" +End Function + +Sub show(s As String, p As Punto) + Print s & " " & p.ToString() +End Sub + +Function from_y(y As Double) As Punto + Dim As Double n = y * y - bCoeff + Dim As Double x = Sgn(n) * Abs(n)^(1.0/3.0) + Return Type(x, y) +End Function + +' Demonstrate +Dim As Punto a = from_y(1) +Dim As Punto b = from_y(2) +show("a =", a) +show("b =", b) + +Dim As Punto c = a.sum(b) +show("c = a + b =", c) + +Dim As Punto d = c.neg() +show("d = -c =", d) + +show("c + d =", c.sum(d)) +show("a + b + d =", a.sum(b.sum(d))) +show("a * 12345 =", a.mul(12345)) + +Sleep diff --git a/Task/Elliptic-curve-arithmetic/JavaScript/elliptic-curve-arithmetic.js b/Task/Elliptic-curve-arithmetic/JavaScript/elliptic-curve-arithmetic.js new file mode 100644 index 0000000000..931179415c --- /dev/null +++ b/Task/Elliptic-curve-arithmetic/JavaScript/elliptic-curve-arithmetic.js @@ -0,0 +1,90 @@ +class Pt { + static bCoeff = 7; + + constructor(x, y) { + this.x = x; + this.y = y; + } + + static zero() { + return new Pt(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); + } + + isZero() { + // same threshold logic as Java version + return this.x > 1e20 || this.x < -1e20; + } + + static fromY(y) { + // cbrt(pow(y,2) - bCoeff) + return new Pt(Math.cbrt(Math.pow(y, 2) - Pt.bCoeff), y); + } + + dbl() { + if (this.isZero()) { + return this; + } + const L = (3 * this.x * this.x) / (2 * this.y); + const x2 = Math.pow(L, 2) - 2 * this.x; + const y2 = L * (this.x - x2) - this.y; + return new Pt(x2, y2); + } + + neg() { + return new Pt(this.x, -this.y); + } + + plus(q) { + // point doubling? + if (this.x === q.x && this.y === q.y) { + return this.dbl(); + } + // handle "point at infinity" + if (this.isZero()) { + return q; + } + if (q.isZero()) { + return this; + } + const L = (q.y - this.y) / (q.x - this.x); + const xx = Math.pow(L, 2) - this.x - q.x; + const yy = L * (this.x - xx) - this.y; + return new Pt(xx, yy); + } + + mult(n) { + let r = Pt.zero(); + let p = this; + // binary double-and-add + for (let i = 1; i <= n; i <<= 1) { + if (i & n) { + r = r.plus(p); + } + p = p.dbl(); + } + return r; + } + + toString() { + if (this.isZero()) { + return "Zero"; + } + // format with 3 decimal places, dot as decimal separator + return `(${this.x.toFixed(3)},${this.y.toFixed(3)})`; + } +} + +// Equivalent of the Java `main` method +(function main() { + const a = Pt.fromY(1); + const b = Pt.fromY(2); + console.log(`a = ${a}`); + console.log(`b = ${b}`); + const c = a.plus(b); + console.log(`c = a + b = ${c}`); + const d = c.neg(); + console.log(`d = -c = ${d}`); + console.log(`c + d = ${c.plus(d)}`); + console.log(`a + b + d = ${a.plus(b).plus(d)}`); + console.log(`a * 12345 = ${a.mult(12345)}`); +})(); diff --git a/Task/Emirp-primes/REXX/emirp-primes-1.rexx b/Task/Emirp-primes/REXX/emirp-primes-1.rexx index 435a1e4aa4..02e4b4da27 100644 --- a/Task/Emirp-primes/REXX/emirp-primes-1.rexx +++ b/Task/Emirp-primes/REXX/emirp-primes-1.rexx @@ -1,36 +1,127 @@ -/*REXX program finds emirp primes (base 10): when a prime reversed, is another prime.*/ -parse arg x y . /*obtain optional arguments from the CL*/ -if x=='' | x=="," then do; x=1; y=20; end /*Not specified? Then use the default.*/ -if y=='' then y=x /* " " " " " " */ -r=y<0; y=abs(y) /*display a range of emirp primes ? */ -rly=length(y) + \r /*adjusted length of the Y value. */ -!.=0; c=0; _=2 3 5 7 11 13 17; $= /*isP; emirp count; low primes; emirps.*/ - do #=1 for words(_); p=word(_,#); @.#=p; !.p=1; end /*#*/ -#=#-1; ip=#; s.#=@.#**2 /*adjust # (for the DO loop); last P².*/ - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒ [↓] generate more primes within range. */ - do j=@.#+2 by 2 /*only find odd primes from here on. */ - if length(#)>rly then leave /*have we enough primes for emirps? */ - if j//3 ==0 then iterate /*is J divisible by three? */ - if right(j,1)==5 then iterate /*is the right-most digit a "5" ? */ - if j//7 ==0 then iterate /*is J divisible by seven? */ - if j//11 ==0 then iterate /*is J divisible by eleven? */ - if j//13 ==0 then iterate /*is J divisible by thirteen? */ - /*[↑] the above five lines saves time.*/ - do k=ip while s.k<=j /*divide by the known odd primes. */ - if j//@.k==0 then iterate j /*J divisible by X? Then ¬prime. ___*/ - end /*k*/ /* [↑] divide by odd primes up to √ j */ - #=#+1 /*bump the number of primes found. */ - @.#=j; s.#=j*j; !.j=1 /*assign to sparse array; prime²; prime*/ - end /*j*/ /* [↑] keep generating until enough. */ - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒ [↓] filter emirps for the display. */ - do j=6 to @.#; _=@.j /*traipse through the regular primes. */ - if (r&_>y) | (\r&c==y) then leave /*is the prime not within the range? */ - __=reverse(_) /*reverse (digits) of the regular prime*/ - if \!.__ | _==__ then iterate /*is the reverse a different prime ? */ - c=c+1 /*bump the emirp prime counter. */ - if (r&_r Then Do /* not a palindromic prime */ + If is_prime(r) Then Do /* reversed p is a prime */ + nn=nn+1 /* increment number of hits */ + Select + When run<='1' Then Do + If nn<21 Then Call show 1,'the first 20 emirps:',4 + If nn=20 Then + Leave + End + When(run='2') Then Do + If hp<8000 Then + Call cprimes 1,8000,'C' + If 7700

8000 Then + Leave + End + When(run='3') Then Do + If nn=10000 Then Do + Call show 3,'the 10.000th emirp:',6 + Leave + End + End + When(run='4') Then Do + Call cprimes 1,999999 /* dirty trick to speed thins up */ + If nn=10000 Then Do + Call show 4,'the 10.000th emirp (alternate version):',6 + Leave + End + End + Otherwise Do + Say 'Invoke as ptx 1/2/3' + Exit + End + End + End + End + End + Call oo + Say 'largest prime:' hp + Exit + + show: + Parse Arg task,header,nl + If first.task Then Do + Call o header||lb + first.task=0 + End + Call o right(p,nl) + If nn=10 Then + Call o lb + Return + +cprimes: Procedure Expose primes. psquare. is_prime. nprimes hp +/********************************************************************* +* adapted for my needs from REXX's Extensible prime generation +* Fill the array primes with prime numbers +* so that it contains at least num primes and all primes<=mp +*********************************************************************/ + Parse Arg num,mp + If symbol('primes.0')=='LIT' Then Do /* 1st time here? Initialize */ + primes.=0 /* prime numbers */ + is_prime.=0 /* is_prime.x -> x is prime */ + psquare.=0 /* psquare.x = square of */ + plist='2 3 5 7 11 13 17 19 23' /* knows low primes. */ + Do i=1 For words(plist) + p=word(plist,i) + primes.i=p + is_prime.p=1 + End + nprimes=i-1 + primes.0=nprimes+1 + psquare.nprimes=primes.nprimes**2 /* square of this prime */ + End /* [?] done with building low Ps */ + Do j=primes.nprimes+2 By 2 While nprimeshp Then + Call cprimes 1,x + Return is_prime.x + +o: ol=ol||arg(1) + Return +oo: Do While ol<>'' + Parse Var ol l (lb) ol + Say l + End + Return diff --git a/Task/Emirp-primes/REXX/emirp-primes-2.rexx b/Task/Emirp-primes/REXX/emirp-primes-2.rexx index 02e4b4da27..b202baa3e4 100644 --- a/Task/Emirp-primes/REXX/emirp-primes-2.rexx +++ b/Task/Emirp-primes/REXX/emirp-primes-2.rexx @@ -1,127 +1,95 @@ - /********************************************************************* - * 27.03.2014 Walter Pachl - *********************************************************************/ - Parse Arg run - first.=1 - nn=0 - ol='' - lb='00'x - If run='' Then run=1 - call cprimes 20,20,'A' - main_loop: - Do ip=1 To 1000000 /* loop over all primes */ - p=primes.ip /* candidate */ - If p=0 Then - call cprimes 20,hp+1,'B' - p=primes.ip /* candidate */ - r=reverse(p) /* reversed candidate */ - If p<>r Then Do /* not a palindromic prime */ - If is_prime(r) Then Do /* reversed p is a prime */ - nn=nn+1 /* increment number of hits */ - Select - When run<='1' Then Do - If nn<21 Then Call show 1,'the first 20 emirps:',4 - If nn=20 Then - Leave - End - When(run='2') Then Do - If hp<8000 Then - Call cprimes 1,8000,'C' - If 7700

8000 Then - Leave - End - When(run='3') Then Do - If nn=10000 Then Do - Call show 3,'the 10.000th emirp:',6 - Leave - End - End - When(run='4') Then Do - Call cprimes 1,999999 /* dirty trick to speed thins up */ - If nn=10000 Then Do - Call show 4,'the 10.000th emirp (alternate version):',6 - Leave - End - End - Otherwise Do - Say 'Invoke as ptx 1/2/3' - Exit - End - End - End - End - End - Call oo - Say 'largest prime:' hp - Exit +-- 22 Mar 2025 +include Settings - show: - Parse Arg task,header,nl - If first.task Then Do - Call o header||lb - first.task=0 - End - Call o right(p,nl) - If nn=10 Then - Call o lb - Return +say 'EMIRP PRIMES' +say version +say +call Time('r'); numeric digits 7 +call Primes 1e6 +call Task1 +call Task2 +call Task3 +say; say Format(Time('e'),,3) 'seconds'; say +call Time('r'); numeric digits 9 +call Primes 1e8 +call Stress +say; say Format(Time('e'),,3) 'seconds'; say +exit -cprimes: Procedure Expose primes. psquare. is_prime. nprimes hp -/********************************************************************* -* adapted for my needs from REXX's Extensible prime generation -* Fill the array primes with prime numbers -* so that it contains at least num primes and all primes<=mp -*********************************************************************/ - Parse Arg num,mp - If symbol('primes.0')=='LIT' Then Do /* 1st time here? Initialize */ - primes.=0 /* prime numbers */ - is_prime.=0 /* is_prime.x -> x is prime */ - psquare.=0 /* psquare.x = square of */ - plist='2 3 5 7 11 13 17 19 23' /* knows low primes. */ - Do i=1 For words(plist) - p=word(plist,i) - primes.i=p - is_prime.p=1 - End - nprimes=i-1 - primes.0=nprimes+1 - psquare.nprimes=primes.nprimes**2 /* square of this prime */ - End /* [?] done with building low Ps */ - Do j=primes.nprimes+2 By 2 While nprimes 20 then + leave i + call Charout ,a' ' +end +say; say +return - is_prime: Procedure Expose primes. psquare. is_prime. nprimes hp - /********************************************************************* - * check if x is a prime number - *********************************************************************/ - Parse Arg x - If x>hp Then - Call cprimes 1,x - Return is_prime.x +Task2: +procedure expose prim. flag. +say 'All emirps > 7700 and < 8000:' +n = 0 +do i = 1 + a = prim.i + if a < 7700 then + iterate + if a > 8000 then + leave i + b = Reverse(a) + if a = b then + iterate i + if \ flag.b then + iterate i + n = n+1 + call Charout ,a' ' +end +say; say +return -o: ol=ol||arg(1) - Return -oo: Do While ol<>'' - Parse Var ol l (lb) ol - Say l - End - Return +Task3: +procedure expose prim. flag. +say 'The 10000th emirp:' +n = 0 +do i = 1 + a = prim.i; b = Reverse(a) + if a = b then + iterate i + if \ flag.b then + iterate i + n = n+1 + if n = 10000 then do + say a + leave i + end +end +return + +Stress: +procedure expose prim. flag. +say 'Number of emirps < 100 million:' +p = prim.0; n = 0 +do i = 1 to p + a = prim.i; b = Reverse(a) + if a = b then + iterate i + if \ flag.b then + iterate i + n = n+1 +end +say n +say: say 'The last emirp:' +say prim.p +return + +include Functions +include Sequences +include Abend diff --git a/Task/Emirp-primes/REXX/emirp-primes-3.rexx b/Task/Emirp-primes/REXX/emirp-primes-3.rexx deleted file mode 100644 index 61b8d22be0..0000000000 --- a/Task/Emirp-primes/REXX/emirp-primes-3.rexx +++ /dev/null @@ -1,92 +0,0 @@ -say 'Emirp primes - Using REXX libraries' -parse version version; say version; say - -call Time('r'); numeric digits 7 -call Primes 1e6 -call Task1 -call Task2 -call Task3 -say; say Format(Time('e'),,3) 'seconds'; say - -call Time('r'); numeric digits 9 -call Primes 1e8 -call Stress -say; say Format(Time('e'),,3) 'seconds'; say -exit - -Task1: -procedure expose prim. -say 'The first 20 emirps:' -n = 0 -do i = 1 - a = prim.prime.i; b = Reverse(a) - if a = b then - iterate i - if \ prim.flag.b then - iterate i - n = n+1 - if n > 20 then - leave i - call Charout ,a' ' -end -say; say -return - -Task2: -procedure expose prim. -say 'All emirps > 7700 and < 8000:' -n = 0 -do i = 1 - a = prim.prime.i - if a < 7700 then - iterate - if a > 8000 then - leave i - if a = b then - iterate i - b = Reverse(a) - if \ prim.flag.b then - iterate i - n = n+1 - call Charout ,a' ' -end -say; say -return - -Task3: -procedure expose prim. -say 'The 10000th emirp:' -n = 0 -do i = 1 - a = prim.prime.i; b = Reverse(a) - if a = b then - iterate i - if \ prim.flag.b then - iterate i - n = n+1 - if n = 10000 then do - say a - leave i - end -end -return - -Stress: -procedure expose prim. -say 'Number of emirps < 100 million:' -p = prim.0; n = 0 -do i = 1 to p - a = prim.prime.i; b = Reverse(a) - if a = b then - iterate i - if \ prim.flag.b then - iterate i - n = n+1 -end -say n -say: say 'The last emirp:' -say prim.prime.p -return - -include Functions -include Sequences diff --git a/Task/Empty-string/Ballerina/empty-string.ballerina b/Task/Empty-string/Ballerina/empty-string.ballerina new file mode 100644 index 0000000000..98ffc1a0c9 --- /dev/null +++ b/Task/Empty-string/Ballerina/empty-string.ballerina @@ -0,0 +1,12 @@ +import ballerina/io; + +function isEmpty(string s) returns boolean { + return s.length() == 0; +} + +public function main() { + string s = ""; + string t = "0"; + io:println("'s' is empty? ", isEmpty(s)); + io:println("'t' is empty? ", isEmpty(t)); +} diff --git a/Task/Entropy-Narcissist/Arturo/entropy-narcissist.arturo b/Task/Entropy-Narcissist/Arturo/entropy-narcissist.arturo new file mode 100644 index 0000000000..0e4a22d5a6 --- /dev/null +++ b/Task/Entropy-Narcissist/Arturo/entropy-narcissist.arturo @@ -0,0 +1,7 @@ +entropy: function [s][ + fold values tally s [acc x] -> + acc - (x // size s) * log x // size s 2 +] + +; assumes file name +print entropy read.file ./"entropy - narcissist.art" diff --git a/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy b/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy index cd34636414..f1bf096818 100644 --- a/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy +++ b/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy @@ -1,21 +1,20 @@ fastfunc isprim num . - if num mod 2 = 0 and num > 2 - return 0 - . + if num mod 2 = 0 and num > 2 : return 0 i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 . -indN = 1 ; indM = 2 -numP = 2 ; numC = 4 -sumP = 2 ; sumC = 4 +indN = 1 +indM = 2 +numP = 2 +numC = 4 +sumP = 2 +sumC = 4 # -numfmt 0 11 +numfmt 11 0 print " sum primes composites" repeat if sumC > sumP diff --git a/Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua b/Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua new file mode 100644 index 0000000000..8f809a29aa --- /dev/null +++ b/Task/Ethiopian-multiplication/Uiua/ethiopian-multiplication.uiua @@ -0,0 +1,10 @@ +Halve ← ⌊÷2 +Double ← ×2 +Odd ← ◿2 +EMul ← ◌◌⍢(⊓Halve Double⍥⊙⟜+⊸Odd)±⊙⊙0 + +┌─╴test + ⍤⤙≍ 578 EMul 17 34 + ⍤⤙≍ 0 EMul 17 0 + ⍤⤙≍ 6 EMul 2 3 +└─╴ diff --git a/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx b/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx index f8449bad85..9d280b2f13 100644 --- a/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx +++ b/Task/Euclid-Mullin-sequence/REXX/euclid-mullin-sequence.rexx @@ -1,58 +1,25 @@ +-- 8 May 2025 include Settings -say version; say 'Euclid-Mullin sequence'; say +say 'EUCLID-MULLIN SEQUENCE' +say version +say numeric digits 100 +call Euclids 16 call Task 16 say Format(Time('e'),,3) 'seconds' exit Task: -procedure expose eucl. -arg x -say 'The first' x 'Euclid-Mullin numbers are:' -eucl. = 0; eucl.euclid.1 = 2; eucl.0 = 1 -p = 2 -do i = 2 to x - z = p+1; t = Ffactor(z); eucl.euclid.i = t; p = p*t -end -eucl.0 = x -do i = 1 to x - call charout ,eucl.euclid.i' ' +arg xx +say 'The first' xx 'Euclid-Mullin numbers are:' +do i = 1 to xx + call Charout ,eucl.i' ' end say -return x - -Ffactor: -/* First prime factor */ -procedure -arg x -/* Fast values */ -if x < 4 then - return x -/* Check low factors */ -n = 0 -pr = '2 3 5 7 11 13 17 19 23' -do i = 1 to Words(pr) - p = Word(pr,i) - if x//p = 0 then - return p -end -/* Check higher factors */ -do j = 29 by 6 while j*j <= x - p = Right(j,1) - if p <> 5 then - if x//j = 0 then - return j - if p = 3 then - iterate - y = j+2 - if x//y = 0 then - return y -end -/* Last factor */ -if x > 1 then - return x -return 0 +return include Functions +include Sequences +include Numbers include Abend diff --git a/Task/Euler-method/EasyLang/euler-method.easy b/Task/Euler-method/EasyLang/euler-method.easy index 2103cb54ff..e861194cda 100644 --- a/Task/Euler-method/EasyLang/euler-method.easy +++ b/Task/Euler-method/EasyLang/euler-method.easy @@ -4,34 +4,34 @@ func analytic T0 t . return TR + (T0 - TR) * pow 2.71828 (K * t) . ytxt = 95 -proc draw_analytic a b . . - color 009 - move 80 ytxt +proc draw_analytic a b . + gcolor 009 + gtext 80 ytxt "analytic" ytxt -= 5 - text "analytic" for t = a to b - line t analytic 100 t + yp = y + y = analytic 100 t + if t > a : gline t - 1 yp t y . . drawgrid -linewidth 0.3 -textsize 3 +glinewidth 0.3 +gtextsize 3 draw_analytic 0 100 # func newton_cooling temp . return K * (temp - TR) . -proc draw_euler y0 a b step col . . - color col - move 80 ytxt +proc draw_euler y t t2 step col . + gcolor col + gtext 80 ytxt "step: " & step ytxt -= 5 - text "step: " & step - t = a - y = y0 - while t < b - line t y + repeat t += step + yp = y y += step * newton_cooling y + gline t - step yp t y + until t >= t2 . . draw_euler 100 0 100 10 900 diff --git a/Task/Euler-method/K/euler-method.k b/Task/Euler-method/K/euler-method.k new file mode 100644 index 0000000000..1bb3a2cd8c --- /dev/null +++ b/Task/Euler-method/K/euler-method.k @@ -0,0 +1,15 @@ +// make global variables with :: because while is only locally scoped +tn1::100 +tn::100 +// to store solution +sol::() +// these are constant, so only local scope +k:-0.07 +time:100 +steps:10 +h:time%steps +tr:20 +// applying x+h to 0 outside to end while loop +// bind to a variable to surpress output +var: {x<100}{tn1::tn+h*k*(tn-tr);sol::sol,tn;tn::tn1;x+h}\0 +sol diff --git a/Task/Euler-method/Odin/euler-method.odin b/Task/Euler-method/Odin/euler-method.odin new file mode 100644 index 0000000000..9a856cbba8 --- /dev/null +++ b/Task/Euler-method/Odin/euler-method.odin @@ -0,0 +1,36 @@ +package main + +import "core:fmt" +import "core:math" + +ivp_euler ::proc(y:f32,step:i32,end:i32){ + + y:=y + t:=i32(0) + + for ;t<=end;t+=step{ + if(t%10==0){fmt.printfln("%.3f", y)} + y+=f32(step)*cooling(f32(t),y) + } +} + +cooling :: proc(t:f32,temp:f32)-> f32{ + return -0.07* (temp-20.0) +} + +analytic :: proc(){ + for t := 0; t <= 100; t += 10{ + fmt.printfln("%.3f",20+80*math.exp_f32(f32(-0.07)*f32(t))) + } +} + +main :: proc() { + fmt.println("Step: 2 Seconds") + ivp_euler(100.0, 2,100) + fmt.println("Step: 5 Seconds") + ivp_euler(100.0, 5, 100) + fmt.println("Step: 10 Seconds") + ivp_euler(100.0, 10, 100) + fmt.println("Analytic") + analytic() +} diff --git a/Task/Euler-method/Q/euler-method.q b/Task/Euler-method/Q/euler-method.q new file mode 100644 index 0000000000..a788e246d6 --- /dev/null +++ b/Task/Euler-method/Q/euler-method.q @@ -0,0 +1,10 @@ +t:0 +time:100 +k:-0.07 +tr:20 +sol:() +steps:10 +h:time%steps +tn:100 +while [t 9) stop + n = 10 + h = 1.0_16 + do k = 2, n + h = h + 1.0_16 / k + end do + write(*, '(a, f18.16)') "Hn ", h + h = h - log(real(n, 16)) + write(*, '(a, f18.16)') " -ln ", h + a = -1.0_16 / (2.0_16 * n) + n2 = real(n, 16) * n + r = 1.0_16 + do k = 1, m + r = r * n2 + a = a + B2(k) / (2.0_16 * k * r) + end do + write(*, '(a, f18.16, /, a, f18.16, /, a, i0)') & + "err ", a, "gamma ", h + a, "k = ", n + m + write(*, '(a, f18.16, /)') "error ", abs(h + a - EULER_GAMMA) + + ! Reference value + write(*, '(a, f18.16, /)') "C = ", EULER_GAMMA +end program euler_constant diff --git a/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx b/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx index f40eab14c9..8a64b5282b 100644 --- a/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx +++ b/Task/Eulers-constant-0.5772.../REXX/eulers-constant-0.5772....rexx @@ -1,8 +1,11 @@ -arg n; if n = '' then n = 100; numeric digits n -parse version version; say version; glob. = ''; fact. = 0 -say 'Euler-Mascheroni constant to' n 'decimal places' +-- 10 Jun 2025 +include Settings + +say 'EULER-MASCHERONI CONSTANT' say 'Method Brent-McMillan' +say version say +arg n; if n = '' then n = 100; numeric digits n call time('r'); a = Brent(); e = format(time('e'),,3) say 'Brent ' a '('e 'seconds)' call time('r'); a = TrueValue(); e = format(time('e'),,3) @@ -12,7 +15,7 @@ exit Brent: procedure expose fact. glob. work. numeric digits Digits()+2 -/* Brent McMillan */ +-- Brent McMillan n = Ceil((Digits()*Ln(10)+Ln(Pi()))*0.25); m = Ceil(2.07*Digits()) n2 = n*n; ak = -Ln(n); bk = 1; s = ak; v = 1 do k = 1 to m @@ -29,4 +32,6 @@ return 0.57721566490153286060651209008240243104215933593992359880576723488486772 include Constants include Functions +include Special include Numbers +include Abend diff --git a/Task/Evaluate-binomial-coefficients/Asymptote/evaluate-binomial-coefficients.asymptote b/Task/Evaluate-binomial-coefficients/Asymptote/evaluate-binomial-coefficients.asymptote new file mode 100644 index 0000000000..abe1786fe5 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Asymptote/evaluate-binomial-coefficients.asymptote @@ -0,0 +1,34 @@ +int factorial(int n) { + if (n < 1) return 1; + + int product = 1; + for (int i = 2; i <= n; ++i) { + product = product * i; + } + + return product; +} + +int binomial(int n, int k) { + // Special cases + if (k == 0 || k == n) return 1; + if (k < 0 || k > n) return 0; + + // For efficiency, we use the smallest value of k or (n-k) + if (k > n - k) k = n - k; + + real product = 1; + for (int i = 1; i <= k; ++i) { + product = product * (n - k + i) / i; + } + + return round(product); +} + +for (int n = 0; n <= 14; ++n) { + for (int k = 0; k <= n; ++k) { + string num = format("%5d", binomial(n, k)); + write(stdout, num); + } + write(""); +} diff --git a/Task/Evaluate-binomial-coefficients/BASIC256/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/BASIC256/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..376d5fac1e --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/BASIC256/evaluate-binomial-coefficients.basic @@ -0,0 +1,29 @@ +for n = 0 to 14 + for k = 0 to n + print rjust(binomial(n, k), 5); + next k + print +next n +end + +function factorial(n) + if n < 1 then return 1 + + product = 1 + for i = 2 to n + product *= i + next + + return product +end function + +function binomial(n, k) + if n < 0 or k < 0 or n <= k then return 1 + + product = 1 + for i = n - k + 1 to n + product *= i + next + + return int(product / factorial(k)) +end function diff --git a/Task/Evaluate-binomial-coefficients/Chipmunk-Basic/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/Chipmunk-Basic/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..3a5261c3b0 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Chipmunk-Basic/evaluate-binomial-coefficients.basic @@ -0,0 +1,23 @@ +100 sub factorial(n) +110 if n < 1 then factorial = 1 +120 product = 1 +130 for i = 2 to n +140 product = product*i +150 next +160 factorial = product +170 end sub +180 sub binomial(n,k) +190 if n < 0 or k < 0 or n <= k then binomial = 1 +200 product = 1 +210 for i = n-k+1 to n +220 product = product*i +230 next +240 binomial = int(product/factorial(k)) +250 end sub +260 for n = 0 to 14 +270 for k = 0 to n +280 print using " ####"; binomial(n,k); +290 next k +300 print +310 next n +320 end diff --git a/Task/Evaluate-binomial-coefficients/Gambas/evaluate-binomial-coefficients.gambas b/Task/Evaluate-binomial-coefficients/Gambas/evaluate-binomial-coefficients.gambas new file mode 100644 index 0000000000..40dc3b7207 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Gambas/evaluate-binomial-coefficients.gambas @@ -0,0 +1,36 @@ +Public Sub Main() + + For n As Integer = 0 To 14 + For k As Integer = 0 To n + Print Format(binomial(n, k), " ####"); + Next + Print + Next + +End + +Function factorial(n As Integer) As Integer + + If n < 1 Then Return 1 + + Dim product As Float = 1 ' Float to avoid overflow + For i As Integer = 2 To n + product *= i + Next + + Return product + +End Function + +Function binomial(n As Integer, k As Integer) As Integer + + If n < 0 Or k < 0 Or n <= k Then Return 1 + + Dim product As Float = 1 ' Float to avoid overflow + For i As Integer = n - k + 1 To n + product *= i + Next + + Return Int(product / factorial(k)) + +End Function diff --git a/Task/Evaluate-binomial-coefficients/MSX-Basic/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/MSX-Basic/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..a4c79b8cfc --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/MSX-Basic/evaluate-binomial-coefficients.basic @@ -0,0 +1,22 @@ +110 FOR N = 0 TO 14 +120 FOR K = 0 TO N +130 GOSUB 500 ' Call to binomial +140 PRINT USING " ####"; B; +150 NEXT K +160 PRINT +170 NEXT N +180 END + +500 ' Binomial subroutine +510 ' Input: N, K +520 ' Output: B (result of binomial) +530 IF K = 0 OR K = N THEN B = 1: RETURN +540 IF K < 0 OR K > N THEN B = 0: RETURN +550 ' For efficiency, we use the lowest value of K or (N-K) +560 IF K > N-K THEN K1=N-K ELSE K1=K +570 PR = 1 +580 FOR I = 1 TO K1 +590 PR = PR * (N-K1+I)/I +600 NEXT I +610 B = INT(PR + 0.5) +620 RETURN diff --git a/Task/Evaluate-binomial-coefficients/Minimal-BASIC/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/Minimal-BASIC/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..f6664d5153 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Minimal-BASIC/evaluate-binomial-coefficients.basic @@ -0,0 +1,25 @@ +10 REM MAIN PROGRAM +20 FOR N = 0 TO 14 +30 FOR K = 0 TO N +40 GOSUB 100 +50 PRINT B +60 NEXT K +70 PRINT +80 NEXT N +90 GOTO 999 +100 REM SUB BINOMIAL +110 IF K = 0 THEN 180 +120 IF K = N THEN 180 +130 IF K < 0 THEN 190 +140 IF K > N THEN 190 +150 LET P = 1 +160 FOR I = 1 TO K +170 LET P = P * (N-K+I)/I +175 NEXT I +177 LET B = P +178 RETURN +180 LET B = 1 +185 RETURN +190 LET B = 0 +195 RETURN +999 END diff --git a/Task/Evaluate-binomial-coefficients/OxygenBasic/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/OxygenBasic/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..0a2abc64de --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/OxygenBasic/evaluate-binomial-coefficients.basic @@ -0,0 +1,38 @@ +uses console + +function factorial(n as integer) as integer + if n < 1 then return 1 + + single product = 1 + + int i + for i = 2 to n + product *= i + next + + return product +end function + +function binomial(n as integer, k as integer) as integer + if n < 0 or k < 0 or n <= k then return 1 + + single product = 1 + + int i + for i = n - k + 1 to n + product *= i + next + + return product \ factorial(k) +end function + +int n, k +for n = 0 to 14 + for k = 0 to n + print binomial(n, k) " "; + next k + printl +next n + +printl cr "Enter ..." +waitkey diff --git a/Task/Evaluate-binomial-coefficients/Prolog/evaluate-binomial-coefficients.pro b/Task/Evaluate-binomial-coefficients/Prolog/evaluate-binomial-coefficients.pro new file mode 100644 index 0000000000..e232790eb4 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Prolog/evaluate-binomial-coefficients.pro @@ -0,0 +1,10 @@ +binomial(N, K, 0) :- K > N. +binomial(N, K, X) :- binomial_helper(1, 1, K, N, X). + +binomial_helper(R, D, K, _, R) :- D > K, !. +binomial_helper(R, D, K, N, X) :- + D =< K, + R1 is R * N / D, + D1 is D + 1, + N1 is N - 1, + binomial_helper(R1, D1, K, N1, X). diff --git a/Task/Evaluate-binomial-coefficients/QBasic/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/QBasic/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..dc28d503de --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/QBasic/evaluate-binomial-coefficients.basic @@ -0,0 +1,45 @@ +DECLARE FUNCTION factorial! (n AS INTEGER) +DECLARE FUNCTION binomial! (n AS INTEGER, k AS INTEGER) + +DIM n AS INTEGER, k AS INTEGER + +FOR n = 0 TO 14 + FOR k = 0 TO n + PRINT USING " ####"; binomial(n, k); + NEXT k + PRINT +NEXT n +END + +FUNCTION binomial! (n AS INTEGER, k AS INTEGER) + ' Special cases + IF k = 0 OR k = n THEN binomial = 1 + IF k < 0 OR k > n THEN binomial = 0 + + ' For efficiency, we use the smallest value of k or (n-k) + DIM tmp AS INTEGER + tmp = k + IF tmp > n - tmp THEN tmp = n - tmp + + DIM product AS DOUBLE ' Double to avoid overflow + product = 1 + + FOR i = 1 TO tmp + product = product * (n - tmp + i) / i + NEXT i + + binomial = product +END FUNCTION + +FUNCTION factorial (n AS INTEGER) + IF n <= 1 THEN factorial = 1 + + DIM product AS DOUBLE ' Double to avoid overflow + product = 1 + + FOR i = 2 TO n + product = product * i + NEXT i + + factorial = product +END FUNCTION diff --git a/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic new file mode 100644 index 0000000000..1e8fe03440 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-1.basic @@ -0,0 +1,35 @@ +FUNCTION factorial(n) + IF n < 1 THEN LET factorial = 1 + + LET product = 1 + FOR i = 2 TO n + LET product = product*i + NEXT i + + LET factorial = product +END FUNCTION + +FUNCTION binomial(n, k) + ! Special cases + IF k = 0 OR k = n THEN LET binomial = 1 + IF k < 0 OR k > n THEN LET binomial = 0 + + ! For efficiency, we use the smallest value of k or (n-k) + IF k > n-k THEN LET k = n-k + LET product = 1 + + FOR i = 1 TO k + LET product = product*(n-k+i)/i + NEXT i + + LET binomial = INT(product+0.5) +END FUNCTION + +FOR n = 0 TO 14 + FOR k = 0 TO n + PRINT USING " ####": binomial(n,k); + NEXT k + PRINT +NEXT n + +END diff --git a/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic new file mode 100644 index 0000000000..f3d149d7c5 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/True-BASIC/evaluate-binomial-coefficients-2.basic @@ -0,0 +1,25 @@ + REM PASCAL'S TRIANGLE + LET N=0 + 10 LET K=0 + 20 GOSUB 30 + PRINT B," " + LET K=K+1 + IF K<=N THEN GOTO 20 + PRINT "" + LET N=N+1 + IF N<=10 THEN GOTO 10 + END + 30 REM BINOMIAL + IF K=0 THEN GOTO 50 + IF K=N THEN GOTO 50 + LET P=1 + LET I=1 + 40 LET T=N-K+I + LET P=P*T/I + LET I=I+1 + IF I<=K THEN GOTO 40 + LET B=P + RETURN + 50 LET B=1 + RETURN + diff --git a/Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic b/Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic new file mode 100644 index 0000000000..b4066edf86 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Yabasic/evaluate-binomial-coefficients.basic @@ -0,0 +1,33 @@ +for n = 0 to 14 + for k = 0 to n + print binomial(n, k) using "####"; + next k + print +next n +end + +sub factorial(n) + local product, i + + if n < 1 return 1 + + product = 1 + for i = 2 to n + product = product * i + next + + return product +end sub + +sub binomial(n, k) + local product, i + + if n < 0 or k < 0 or n <= k return 1 + + product = 1 + for i = n - k + 1 to n + product = product * i + next + + return int(product / factorial(k)) +end sub diff --git a/Task/Events/EasyLang/events.easy b/Task/Events/EasyLang/events.easy index 0206f41f44..18092d262e 100644 --- a/Task/Events/EasyLang/events.easy +++ b/Task/Events/EasyLang/events.easy @@ -1,10 +1,8 @@ on timer - move randomf * 100 randomf * 100 - circle 2 + gcircle randomf * 100 randomf * 100 2 timer 1 . on mouse_down - move mouse_x mouse_y - circle 2 + gcircle mouse_x mouse_y 2 . timer 0 diff --git a/Task/Execute-Brain-/Crystal/execute-brain-.cr b/Task/Execute-Brain-/Crystal/execute-brain-.cr new file mode 100644 index 0000000000..355443e3a0 --- /dev/null +++ b/Task/Execute-Brain-/Crystal/execute-brain-.cr @@ -0,0 +1,33 @@ +def bfrun (code) + code = code.chars + data = Hash(Int32, Int32).new(0) + dp = ip = 0 + jump_to_matching = ->(dir : Int32) { + nest = 0 + while 0 <= ip < code.size + case code[ip] + when '[' then nest += dir + when ']' then nest -= dir + end + break if nest == 0 + ip += dir + end + } + while 0 <= ip < code.size + case code[ip] + when '>' then dp += 1 + when '<' then dp -= 1 + when '+' then data[dp] += 1 + when '-' then data[dp] -= 1 + when '.' then print(data[dp].chr) + when ',' then data[dp] = STDIN.read_char.not_nil!.ord + when '[' then jump_to_matching.call(1) if data[dp] == 0 + when ']' then jump_to_matching.call(-1) if data[dp] != 0 + end + ip += 1 + end +end + +hello = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++." + +bfrun(hello) diff --git a/Task/Execute-Brain-/EasyLang/execute-brain-.easy b/Task/Execute-Brain-/EasyLang/execute-brain-.easy index 9888328243..35eabaabb8 100644 --- a/Task/Execute-Brain-/EasyLang/execute-brain-.easy +++ b/Task/Execute-Brain-/EasyLang/execute-brain-.easy @@ -1,4 +1,4 @@ -proc exec code$ . . +proc exec code$ . len mem[] 100 dp = 1 code$[] = strchars code$ @@ -54,9 +54,7 @@ func syntax code$ . elif h$ = "]" br -= 1 . - if br < 0 - return 0 - . + if br < 0 : return 0 . return if br = 0 . diff --git a/Task/Execute-Brain-/Odin/execute-brain-.odin b/Task/Execute-Brain-/Odin/execute-brain-.odin new file mode 100644 index 0000000000..e2898826a1 --- /dev/null +++ b/Task/Execute-Brain-/Odin/execute-brain-.odin @@ -0,0 +1,126 @@ +package bf + +import "core:fmt" +import "core:c/libc" +import "core:os" + +cells_size :: 2000 +getinp : i32 +inp : u8 +main :: proc() { + + // comment out to give a file from command line + // data, ok := os.read_entire_file(os.args[1]) + // assert(ok, "Could not open file") + // defer delete(data) + // input := string(data) + + input := ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--------.[-]>++++++++[<++++>- ]<+.[-]++++++++++." + size_input := len(input) + cells : [cells_size]i32 + pointer:=0 + i:=0 + direction := 1 + // moving past non matching [ ] + depth:= 0 + // loop i over input + mainloop: for ; (i <= (size_input - 1) && i >=0); { + inp = input[i] + //fmt.println(i) + switch inp{ + // move pointer right + case '>': + pointer +=1 + if (pointer>cells_size-1){ + pointer=cells_size-1 + } + i += 1 + // move pointer left + case '<': + pointer -=1 + if (pointer<0){ + pointer=0 + } + i += 1 + // increase cells at pointer + case '+': + cells[pointer] = (cells[pointer] + 1) % 256 + i += 1 + // decrease cell at pointer + case '-': + cells[pointer] = (cells[pointer] - 1) % 256 + i += 1 + // output value from cell at pointer + case '.': + res := cells[pointer] + libc.putchar(res) + i += 1 + // input value in cell at pointer + case ',': + getinp= libc.getchar() + fmt.println("input:") + cells[pointer] = getinp + i += 1 + // Jump past the matching ] if the cell at the pointer is 0 + case '[': + // if cell at pointer = 0 + if cells[pointer] == 0 { + // loop until ] + + loop1: for (inp != ']' && depth == 0) { + i +=1 + inp = input[i] + if (i > (size_input-1)){ + // if i > size input [ is unbalanced + fmt.printf("unbalanced loop ") + break mainloop + } + else if (inp == '[') { + depth += 1 + } + else if (inp == ']' && depth != 0) { + depth -= 1 + } + + fmt.println(i) + } + + } // else ignore + else { + i +=1 + } + + case ']': + // Jump back to the matching [ if the cell at the pointer is nonzero + if cells[pointer] != 0 { + + loop2: for (inp!= '[' && depth == 0) { + i -= 1 + inp = input[i] + if (i < 0) + { + fmt.printf("unbalanced loop ") + break mainloop + } + else if (inp == ']') { + depth += 1 + } + else if (inp == '[' && depth != 0) { + depth -= 1 + } + //fmt.println(input[i]) + } + + } + else { + i+=1 + } + // default: move pointer + case : + i +=1 + + } + + } + +} diff --git a/Task/Execute-Computer-Zero/EasyLang/execute-computer-zero.easy b/Task/Execute-Computer-Zero/EasyLang/execute-computer-zero.easy index 1349a41c80..213c407e4a 100644 --- a/Task/Execute-Computer-Zero/EasyLang/execute-computer-zero.easy +++ b/Task/Execute-Computer-Zero/EasyLang/execute-computer-zero.easy @@ -1,4 +1,4 @@ -proc run name$ mem[] . . +proc run name$ mem[] . write name$ & ": " pc = 1 len mem[] 32 diff --git a/Task/Execute-Computer-Zero/Perl/execute-computer-zero.pl b/Task/Execute-Computer-Zero/Perl/execute-computer-zero.pl new file mode 100644 index 0000000000..a03710fef7 --- /dev/null +++ b/Task/Execute-Computer-Zero/Perl/execute-computer-zero.pl @@ -0,0 +1,154 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Execute_Computer/Zero +use warnings; +$SIG{__WARN__} = sub { die @_ }; + +my ($pc, $acc, $op, $addr, $mem, %ops, @memory, $program); +@ops{qw( NOP LDA STA ADD SUB BRZ JMP STP )} = map $_ << 5, 0 .. 7; +my $codes = qr/(?:@{[join '|', keys %ops ]})/; +my @inst = (sub {}, map eval "sub {$_}", split /\n/, <<'END' =~ s/#.*//gr); +$acc = $memory[$addr] # LDA +$memory[$addr] = $acc # STA +$acc = $acc + $memory[$addr] & 0xff # ADD +$acc = $acc - $memory[$addr] & 0xff # SUB +$acc or $pc = $addr # BRZ +$pc = $addr # JMP +END + +sub assemble + { + local $_ = join '', @_; # pass in array of lines or one multi-line string + $program = /;(.*)/ ? " $1" : ''; + my %labels; + @memory = (0) x 32; + s/^([a-z]\w*):/ $labels{$1} = $` =~ tr~\n~~; '' /igem; + $memory[$` =~ tr/\n//] = $1 + ? $ops{$1} | ($labels{$2 // ''} // $2 // 0) & 0b00011111 + : ($labels{$2 // ''} // $2 // 0) & 0xff + while /^\h*($codes)?(?:\h*(\b\w+))?/gm; + } + +sub run + { + $pc = $acc = 0; + $inst[$op]() while $mem = $memory[$pc], + ($op, $addr, $pc) = ($mem >> 5, $mem & 0x1f, $pc + 1 & 0b00011111), + $op < 7; + return $acc; + } + +for ( map s/\s+\z/\n/r, do { local $/ = ''; } ) + { +# print; + assemble( $_ ); + print '*' x 20," STP with acc = ", run(), "$program\n\n"; + } + +__DATA__ + LDA x ; first example program 2 + 2 + ADD y + STP +x: 2 +y: 2 + +loop: LDA a ; second example program 7 * 8 + BRZ end + SUB one + STA a + LDA prod + ADD b + STA prod + JMP loop +end: LDA prod + STP +a: 7 +b: 8 +prod: 0 +one: 1 + +loop: LDA count ; Fibonacci + BRZ end + SUB one + STA count + LDA a + ADD b + STA temp + LDA b + STA a + LDA temp + STA b + JMP loop +end: LDA b + STP +one: 1 +a: 1 +b: 1 +temp: 0 +count: 8 + +start: LDA load ; linked list + ADD car ; head of list + STA ldcar + ADD one + STA ldcdr ; next CONS cell +ldcar: NOP + STA value +ldcdr: NOP + BRZ done ; 0 stands for NIL + STA car + JMP start +done: LDA value ; CAR of last CONS + STP +load: LDA 0 +value: 0 +car: begin +one: 1 + ; order of CONS cells + ; in memory + ; does not matter + 6 + 0 ; 0 stands for NIL + 2 ; (CADR ls) + 26 ; (CDDR ls) -- etc. + 5 + 20 + 3 + 30 +begin: 1 ; value of (CAR ls) + 22 ; points to (CDR ls) + 4 + 24 + +p: 0 ; NOP in first round Prisoner's Dilemma +c: 0 +start: STP ; wait for p's move +pmove: NOP + LDA pmove + SUB cmove + BRZ same + LDA pmove + STA cmove ; tit for tat + BRZ cdeft + LDA c ; p defected, c did not + ADD three + STA c + JMP start +cdeft: LDA p + ADD three + STA p + JMP start +same: LDA pmove + STA cmove ; tit for tat + LDA p + ADD one + ADD pmove + STA p + LDA c + ADD one + ADD pmove + STA c + JMP start +cmove: 0 ; co-operate initially +one: 1 +three: 3 diff --git a/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy b/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy index 73ac035a1f..95fb45691e 100644 --- a/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy +++ b/Task/Execute-HQ9+/EasyLang/execute-hq9+.easy @@ -1,4 +1,4 @@ -proc run code$ . . +proc run code$ . for c$ in strchars code$ if c$ = "Q" print code$ diff --git a/Task/Execute-SNUSP/EasyLang/execute-snusp.easy b/Task/Execute-SNUSP/EasyLang/execute-snusp.easy index dde98b1d48..05ac014346 100644 --- a/Task/Execute-SNUSP/EasyLang/execute-snusp.easy +++ b/Task/Execute-SNUSP/EasyLang/execute-snusp.easy @@ -1,4 +1,4 @@ -proc snusp dlen raw$ . . +proc snusp dlen raw$ . len ds[] dlen is$[] = strsplit raw$ "\n" for s$ in is$[] @@ -6,9 +6,7 @@ proc snusp dlen raw$ . . . for ipr to len is$[][] for ipc to len is$[ipr][] - if is$[ipr][ipc] = "$" - break 2 - . + if is$[ipr][ipc] = "$" : break 2 . . dp = 1 @@ -42,9 +40,7 @@ proc snusp dlen raw$ . . elif c$ = "!" step elif c$ = "?" - if ds[dp] = 0 - step - . + if ds[dp] = 0 : step . step . diff --git a/Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs b/Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs new file mode 100644 index 0000000000..6d3499bb58 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/C-sharp/execute-a-markov-algorithm.cs @@ -0,0 +1,161 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +public class Markov +{ + ///

+ /// Take a ruleset and return a function which takes a string to which the rules + /// should be applied. + /// + /// String containing the rules + /// A function that takes a string and applies the rules + public static Func CreateMarkovProcessor(string ruleSet) + { + // Convert a ruleset string into a dictionary + Dictionary MakeRuleMap(string ruleset) + { + return ruleset.Split('\n') + .Where(e => !e.StartsWith("#")) + .Select(e => e.Split(new[] { " -> " }, StringSplitOptions.None)) + .ToDictionary(e => e[0], e => e[1]); + } + + // Split a string at an index + Tuple SplitAt(string s, int i) + { + return new Tuple(s.Substring(0, i), s.Substring(i)); + } + + // Strip a leading number of chars from a string. + string StripLeading(string s, string strip) + { + return s.Substring(strip.Length); + } + + // Replace the substring in the string. + string Replace(string s, string find, string rep) + { + string result = s; + if (s.IndexOf(find) >= 0) + { + var a = SplitAt(s, s.IndexOf(find)); + result = a.Item1 + rep + StripLeading(a.Item2, find); + } + return result; + } + + // Recursively apply the ruleset to the string. + string Parse(Dictionary rules, string s) + { + string o = s; + foreach (var rule in rules) + { + string k = rule.Key; + string v = rule.Value; + + if (v.StartsWith(".")) + { + s = Replace(s, k, StripLeading(v, ".")); + break; + } + else + { + s = Replace(s, k, v); + if (s != o) { break; } + } + } + return o == s ? s : Parse(rules, s); + } + + var ruleMap = MakeRuleMap(ruleSet); + return str => Parse(ruleMap, str); + } + + public static void Main() + { + string ruleset1 = @"# This rules file is extracted from Wikipedia: +# http://en.wikipedia.org/wiki/Markov_Algorithm +A -> apple +B -> bag +S -> shop +T -> the +the shop -> my brother +a never used -> .terminating rule"; + + string ruleset2 = @"# Slightly modified from the rules on Wikipedia +A -> apple +B -> bag +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule"; + + string ruleset3 = @"# BNF Syntax testing rules +A -> apple +WWWW -> with +Bgage -> ->.* +B -> bag +->.* -> money +W -> WW +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule"; + + string ruleset4 = @"### Unary Multiplication Engine, for testing Markov Algorithm implementations +### By Donal Fellows. +# Unary addition engine +_+1 -> _1+ +1+1 -> 11+ +# Pass for converting from the splitting of multiplication into ordinary +# addition +1! -> !1 +,! -> !+ +_! -> _ +# Unary multiplication by duplicating left side, right side times +1*1 -> x,@y +1x -> xX +X, -> 1,1 +X1 -> 1X +_x -> _X +,x -> ,X +y1 -> 1y +y_ -> _ +# Next phase of applying +1@1 -> x,@y +1@_ -> @_ +,@_ -> !_ +++ -> + +# Termination cleanup for addition +_1 -> 1 +1+_ -> 1 +_+_ -> "; + + string ruleset5 = @"# Turing machine: three-state busy beaver +# +# state A, symbol 0 => write 1, move right, new state B +A0 -> 1B +# state A, symbol 1 => write 1, move left, new state C +0A1 -> C01 +1A1 -> C11 +# state B, symbol 0 => write 1, move left, new state A +0B0 -> A01 +1B0 -> A11 +# state B, symbol 1 => write 1, move right, new state B +B1 -> 1B +# state C, symbol 0 => write 1, move left, new state B +0C0 -> B01 +1C0 -> B11 +# state C, symbol 1 => write 1, move left, halt +0C1 -> H01 +1C1 -> H11"; + + Console.WriteLine(CreateMarkovProcessor(ruleset1)("I bought a B of As from T S.")); + Console.WriteLine(CreateMarkovProcessor(ruleset2)("I bought a B of As from T S.")); + Console.WriteLine(CreateMarkovProcessor(ruleset3)("I bought a B of As W my Bgage from T S.")); + Console.WriteLine(CreateMarkovProcessor(ruleset4)("_1111*11111_")); + Console.WriteLine(CreateMarkovProcessor(ruleset5)("000000A000000")); + } +} diff --git a/Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig b/Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig new file mode 100644 index 0000000000..ec8bb8934d --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Zig/execute-a-markov-algorithm.zig @@ -0,0 +1,278 @@ +const std = @import("std"); +const testing = std.testing; +const mem = std.mem; +const Allocator = std.mem.Allocator; + +// Add a main function for Zig playground to compile +pub fn main() !void { + // Empty main function to satisfy the compiler + std.debug.print("Markov Algorithm library\n", .{}); +} + +pub const Rule = struct { + pat: []const u8, + rep: []const u8, + terminal: bool, + + pub fn init(allocator: Allocator, pat: []const u8, rep: []const u8, terminal: bool) !Rule { + const pat_owned = try allocator.dupe(u8, pat); + const rep_owned = try allocator.dupe(u8, rep); + return Rule{ + .pat = pat_owned, + .rep = rep_owned, + .terminal = terminal, + }; + } + + pub fn deinit(self: *Rule, allocator: Allocator) void { + allocator.free(self.pat); + allocator.free(self.rep); + } + + pub fn clone(self: Rule, allocator: Allocator) !Rule { + return try Rule.init(allocator, self.pat, self.rep, self.terminal); + } + + pub fn applicableRange(self: *const Rule, input: []const u8) ?struct { start: usize, end: usize } { + if (mem.indexOf(u8, input, self.pat)) |start| { + return .{ .start = start, .end = start + self.pat.len }; + } + return null; + } + + pub fn apply(self: *const Rule, s: *std.ArrayList(u8)) !bool { + if (self.applicableRange(s.items)) |range| { + try s.replaceRange(range.start, range.end - range.start, self.rep); + return true; + } + return false; + } + + pub fn fromString(allocator: Allocator, s: []const u8) !Rule { + var parts = mem.splitSequence(u8, s, " -> "); + const pat = parts.first(); + const rep_opt = parts.next(); + if (rep_opt == null) { + return error.InvalidFormat; + } + const rep = rep_opt.?; + + if (rep.len > 0 and rep[0] == '.') { + return Rule.init(allocator, pat, rep[1..], true); + } else { + return Rule.init(allocator, pat, rep, false); + } + } +}; + +pub const Rules = struct { + rules: std.ArrayList(Rule), + allocator: Allocator, + + pub fn init(allocator: Allocator) Rules { + return Rules{ + .rules = std.ArrayList(Rule).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *Rules) void { + for (self.rules.items) |*rule| { + rule.deinit(self.allocator); + } + self.rules.deinit(); + } + + pub fn clone(self: Rules) !Rules { + var new_rules = Rules.init(self.allocator); + for (self.rules.items) |rule| { + try new_rules.rules.append(try rule.clone(self.allocator)); + } + return new_rules; + } + + pub fn apply(self: *const Rules, s: *std.ArrayList(u8)) !?*const Rule { + for (self.rules.items) |*rule| { + if (try rule.apply(s)) { + return rule; + } + } + return null; + } + + pub fn execute(self: *const Rules, buffer: []const u8) ![]u8 { + var result = try std.ArrayList(u8).initCapacity(self.allocator, buffer.len); + try result.appendSlice(buffer); + + while (try self.apply(&result)) |rule| { + if (rule.terminal) { + break; + } + } + + return result.toOwnedSlice(); + } + + pub fn fromString(allocator: Allocator, s: []const u8) !Rules { + var result = Rules.init(allocator); + var lines = mem.splitScalar(u8, s, '\n'); + + while (lines.next()) |line| { + const trimmed = mem.trim(u8, line, &std.ascii.whitespace); + if (trimmed.len == 0 or trimmed[0] == '#') { + continue; + } + const rule = try Rule.fromString(allocator, trimmed); + try result.rules.append(rule); + } + + return result; + } +}; + +test "case_01" { + const allocator = std.testing.allocator; + const input = "I bought a B of As from T S."; + const rules_str = + \\# This rules file is extracted from Wikipedia: + \\# http://en.wikipedia.org/wiki/Markov_Algorithm + \\A -> apple + \\B -> bag + \\S -> shop + \\T -> the + \\the shop -> my brother + \\a never used -> .terminating rule + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("I bought a bag of apples from my brother.", result); +} + +test "case_02" { + const allocator = std.testing.allocator; + const input = "I bought a B of As from T S."; + const rules_str = + \\# Slightly modified from the rules on Wikipedia + \\A -> apple + \\B -> bag + \\S -> .shop + \\T -> the + \\the shop -> my brother + \\a never used -> .terminating rule + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("I bought a bag of apples from T shop.", result); +} + +test "case_03" { + const allocator = std.testing.allocator; + const input = "I bought a B of As W my Bgage from T S."; + const rules_str = + \\# BNF Syntax testing rules + \\A -> apple + \\WWWW -> with + \\Bgage -> ->.* + \\B -> bag + \\->.* -> money + \\W -> WW + \\S -> .shop + \\T -> the + \\the shop -> my brother + \\a never used -> .terminating rule + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("I bought a bag of apples with my money from T shop.", result); +} + +test "case_04" { + const allocator = std.testing.allocator; + const input = "_1111*11111_"; + const rules_str = + \\### Unary Multiplication Engine, for testing Markov Algorithm implementations + \\### By Donal Fellows. + \\# Unary addition engine + \\_+1 -> _1+ + \\1+1 -> 11+ + \\# Pass for converting from the splitting of multiplication into ordinary + \\# addition + \\1! -> !1 + \\,! -> !+ + \\_! -> _ + \\# Unary multiplication by duplicating left side, right side times + \\1*1 -> x,@y + \\1x -> xX + \\X, -> 1,1 + \\X1 -> 1X + \\_x -> _X + \\,x -> ,X + \\y1 -> 1y + \\y_ -> _ + \\# Next phase of applying + \\1@1 -> x,@y + \\1@_ -> @_ + \\,@_ -> !_ + \\++ -> + + \\# Termination cleanup for addition + \\_1 -> 1 + \\1+_ -> 1 + \\_+_ -> + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("11111111111111111111", result); +} + +test "case_05" { + const allocator = std.testing.allocator; + const input = "000000A000000"; + const rules_str = + \\# Turing machine: three-state busy beaver + \\# + \\# state A, symbol 0 => write 1, move right, new state B + \\A0 -> 1B + \\# state A, symbol 1 => write 1, move left, new state C + \\0A1 -> C01 + \\1A1 -> C11 + \\# state B, symbol 0 => write 1, move left, new state A + \\0B0 -> A01 + \\1B0 -> A11 + \\# state B, symbol 1 => write 1, move right, new state B + \\B1 -> 1B + \\# state C, symbol 0 => write 1, move left, new state B + \\0C0 -> B01 + \\1C0 -> B11 + \\# state C, symbol 1 => write 1, move left, halt + \\0C1 -> H01 + \\1C1 -> H11 + ; + + var rules = try Rules.fromString(allocator, rules_str); + defer rules.deinit(); + + const result = try rules.execute(input); + defer allocator.free(result); + + try testing.expectEqualStrings("00011H1111000", result); +} diff --git a/Task/Extensible-prime-generator/C-sharp/extensible-prime-generator.cs b/Task/Extensible-prime-generator/C-sharp/extensible-prime-generator.cs new file mode 100644 index 0000000000..62d8a7b3cb --- /dev/null +++ b/Task/Extensible-prime-generator/C-sharp/extensible-prime-generator.cs @@ -0,0 +1,88 @@ +using System.Collections; + +IEnumerable StartSieve(int length) +{ + yield return 2; + BitArray sieve = new(length); + var i = 3; + + while (i < length) + { + if (!sieve[i]) + { + yield return i; + var j = i * i; + + while (j < length) + { + sieve[j] = true; + j += i; + } + } + + i += 2; + } +} + +IEnumerable AllPrimes() +{ + + foreach (var prime in StartSieve(1000)) + { + yield return prime; + } + + var start = 1000; + + while (true) + { + foreach (var prime in Sieve(start, 1000)) + { + yield return prime; + } + + start += 1000; + } +} + +IEnumerable Sieve(int start, int length) +{ + var sieve = new BitArray(length); + + foreach (var p in AllPrimes().Skip(1).TakeWhile(n => n * n < start + length)) + { + var j = p * ((start + p - 1) / p); + + while (j < start + length) + { + sieve[j - start] = true; + j += p; + } + } + + for (var j = 1 - (start % 2); j < length; j += 2) + { + if (!sieve[j]) + yield return start + j; + } +} + +Console.Write("First 20 primes:"); + +foreach (var p in AllPrimes().Take(20)) + Console.Write($" {p}"); + +Console.WriteLine(); +Console.Write("Primes between 100 and 150:"); + +foreach (var p in Sieve(100, 50)) + Console.Write($" {p}"); + +Console.WriteLine(); +Console.Write("Number of primes between 7700 and 8000:"); +var n = Sieve(7700, 300).Count(); +Console.WriteLine($" {n}"); + +Console.Write("10000th prime:"); +var t = AllPrimes().Skip(9999).First(); +Console.WriteLine($" {t}"); diff --git a/Task/Extensible-prime-generator/EasyLang/extensible-prime-generator.easy b/Task/Extensible-prime-generator/EasyLang/extensible-prime-generator.easy index caccaacfce..4bce905441 100644 --- a/Task/Extensible-prime-generator/EasyLang/extensible-prime-generator.easy +++ b/Task/Extensible-prime-generator/EasyLang/extensible-prime-generator.easy @@ -11,7 +11,7 @@ fastfunc nprim num . . prim = 2 primcnt = 1 -proc nextprim . . +proc nextprim . prim = nprim (prim + 1) primcnt += 1 . diff --git a/Task/Extensible-prime-generator/REXX/extensible-prime-generator-1.rexx b/Task/Extensible-prime-generator/REXX/extensible-prime-generator-1.rexx deleted file mode 100644 index 84d7cc6aa0..0000000000 --- a/Task/Extensible-prime-generator/REXX/extensible-prime-generator-1.rexx +++ /dev/null @@ -1,50 +0,0 @@ -/*REXX program calculates and displays primes using an extendible prime number generator*/ -parse arg f .; if f=='' then f= 20 /*allow specifying number for 1 ──► F.*/ -_i= ' (inclusive) '; _b= 'between '; _tnp= 'the number of primes' _b; _tn= 'the primes' -call primes f; do j=1 for f; $= $ @.j; end /*j*/ - say 'the first ' f " primes are: " $ - say -call primes -150; do j=100 to 150; if !.j==1 then $= $ j; end /*j*/ - say _tn _b '100 to 150' _i "are: " $ - say -call primes -8000; do j=7700 to 8000; if !.j==1 then $= $ j; end /*j*/ - say _tnp '7,700 and 8,000' _i "is: " words($) - say -call primes 10000 - say 'the 10,000th prime is: ' @.10000 -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -primes: procedure expose !. @. $ #; parse arg H,,$; Hneg= H<0; H= abs(H) - if symbol('#')=="LIT" then call .primI /*1st time here? Then initialize stuff*/ - if Hneg then if H<=@.# then return /*do we have a high enough P already?*/ - else nop /*this is used to match the above THEN.*/ - else if H<=# then return /*are there enough primes currently ? */ - /* [↓] gen more primes within range. */ - do j=@.#+2 by 2; parse var j '' -1 _ /*find primes until have H Primes. */ - if _==5 then iterate /*is the right─most digit a 5 (five)? */ - if j// 3==0 then iterate /*is J divisible by three? (& etc.)*/ - if j// 7==0 then iterate; if j//11==0 then iterate; if j//13==0 then iterate - if j//17==0 then iterate; if j//19==0 then iterate; if j//23==0 then iterate - if j//29==0 then iterate; if j//31==0 then iterate; if j//37==0 then iterate - if j//41==0 then iterate; if j//43==0 then iterate; if j//47==0 then iterate - if j//53==0 then iterate; if j//59==0 then iterate; if j//61==0 then iterate - if j//67==0 then iterate; if j//71==0 then iterate; if j//73==0 then iterate - if j//79==0 then iterate; if j//83==0 then iterate; if j//89==0 then iterate - if j//97==0 then iterate; if j//101==0 then iterate; if j//103==0 then iterate - x= j; r= 0; q= 1; do while q<=x; q= q*4; end /*R: the sqrt(J).*/ - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end - do k=@.lowP while @.k<=r /*÷ by the known odd primes (hardcoded)*/ - if j//@.k==0 then iterate j /*J ÷ by a prime? Then not prime. ___*/ - end /*k*/ /* [↑] divide by odd primes up to √ J */ - #= # + 1 /*bump the number of primes found. */ - @.#= j; !.j= 1 /*assign to sparse array; prime²; P#.*/ - if Hneg then if H<=@.# then leave /*is this a high enough prime? */ - else nop /*used to match the above THEN. */ - else if H<=# then leave /*have enough primes been generated? */ - end /*j*/ /* [↑] keep generating until enough. */ - return /*return to invoker with more primes. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.primI: !.=0; @.=0; /*!.x= a prime or not; @.n= Nth prime.*/ - L= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 - do #=1 for words(L); p= word(L, #); @.#= p; !.p=1; end /*#*/ - #= # - 1; @.lowP= #; return /*#: # primes; @.lowP: start of ÷ */ diff --git a/Task/Extensible-prime-generator/REXX/extensible-prime-generator-3.rexx b/Task/Extensible-prime-generator/REXX/extensible-prime-generator-3.rexx deleted file mode 100644 index 03683ffe5d..0000000000 --- a/Task/Extensible-prime-generator/REXX/extensible-prime-generator-3.rexx +++ /dev/null @@ -1,9 +0,0 @@ -... -/* call Primes 105e3 */ -/* call First20 */ -/* call Between100and150 */ -/* call Between7700and8000 */ -/* call Number10000 */ -call Primes 1e8 -call Extended -... diff --git a/Task/Extensible-prime-generator/REXX/extensible-prime-generator-2.rexx b/Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx similarity index 54% rename from Task/Extensible-prime-generator/REXX/extensible-prime-generator-2.rexx rename to Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx index 77be2fa9f0..9ca2e91f50 100644 --- a/Task/Extensible-prime-generator/REXX/extensible-prime-generator-2.rexx +++ b/Task/Extensible-prime-generator/REXX/extensible-prime-generator.rexx @@ -1,50 +1,25 @@ +-- 22 Mar 2025 include Settings -say version; say 'Extensible prime generator'; say +say 'EXTENSIBLE PRIME GENERATOR' +say version +say numeric digits 9 call Primes 105e3 call First20 call Between100and150 call Between7700and8000 call Number10000 -/* call Primes 1e8 */ -/* call Extended */ +call Primes 1e8 +call Extended say Format(Time('e'),,3) 'seconds' exit -Primes: -/* Prime numbers */ -procedure expose prim. work. -arg x -/* Init */ -prim. = 0 -/* Fast values */ -if x = 1 then - return 0 -/* Sieve of Eratosthenes */ -work. = 1 -do i = 3 by 2 to x while i*i <= x - if work.prime.i then do - do j = i*i by i+i to x - work.prime.j = 0 - end - end -end -/* Save results */ -n = 1; prim.prime.1 = 2; prim.flag.2 = 1 -do i = 3 by 2 to x - if work.prime.i then do - n = n+1; prim.prime.n = i; prim.flag.i = 1 - end -end -prim.0 = n -return n - First20: procedure expose prim. say 'The first 20 prime numbers are:' do i = 1 to 20 - call charout ,right(prim.prime.i,3) + call charout ,right(prim.i,3) if i//10 = 0 then say end @@ -56,7 +31,7 @@ procedure expose prim. say 'Prime numbers between 100 and 150 are:' n = 0 do i = 1 - a = prim.prime.i + a = prim.i if a < 100 then iterate i if a > 150 then @@ -71,10 +46,10 @@ return Between7700and8000: procedure expose prim. -say 'Prime numbers between 7700 and 8000:' +say 'Prime numbers between 77022 Mar 2025:' n = 0 do i = 1 - a = prim.prime.i + a = prim.i if a < 7700 then iterate i if a > 8000 then @@ -87,7 +62,7 @@ return Number10000: procedure expose prim. say 'The 10000th prime number is:' -say prim.prime.10000 +say prim.10000 say return @@ -95,12 +70,13 @@ Extended: procedure expose prim. do i = 1 to 6 j = 10**i - say 'The' j'th prime is' prim.prime.j + say 'The' j'th prime is' prim.j end -say 'The 5500000th prime is' prim.prime.5500000 +say 'The 5500000th prime is' prim.5500000 say return include Functions +include Sequences include Numbers include Abend diff --git a/Task/Extreme-floating-point-values/Ballerina/extreme-floating-point-values.ballerina b/Task/Extreme-floating-point-values/Ballerina/extreme-floating-point-values.ballerina new file mode 100644 index 0000000000..8e2a51d86b --- /dev/null +++ b/Task/Extreme-floating-point-values/Ballerina/extreme-floating-point-values.ballerina @@ -0,0 +1,34 @@ +import ballerina/io; + +public function main() { + // using pre-defined constants + final float inf = float:Infinity; + final float negInf = -inf; + final float nan = float:NaN; + final float negZero = -0.0; + io:println([inf, negInf, nan, negZero]); + io:println([inf + inf, negInf + inf, nan * nan, negZero == 0.0]); + io:println([inf/inf, negInf/2, nan + inf, negZero/0]); + io:println(); + + // using values computed from other 'normal' values + float inf2 = 1.0 / 0.0; + float negInf2 = -1.0 / 0.0; + float nan2 = 0.0 / 0.0; + float nan3 = (-2.0).sqrt(); + + // using value equality + io:println(inf2 == inf); + io:println(negInf == negInf2); + io:println(nan == nan); + io:println(nan == nan2); + io:println(nan == nan3); + io:println(0.0 == negZero); // true + io:println(); + + // using storage equality + io:println(nan === nan); + io:println(nan === nan2); + io:println(nan === nan3); + io:println(0.0 === negZero); // false +} diff --git a/Task/Factorial/EasyLang/factorial.easy b/Task/Factorial/EasyLang/factorial.easy index 1ad66bdb70..697c8807fd 100644 --- a/Task/Factorial/EasyLang/factorial.easy +++ b/Task/Factorial/EasyLang/factorial.easy @@ -1,8 +1,6 @@ func factorial n . r = 1 - for i = 2 to n - r *= i - . + for i = 2 to n : r *= i return r . print factorial 7 diff --git a/Task/Factorial/Java/factorial-4.java b/Task/Factorial/Java/factorial-4.java new file mode 100644 index 0000000000..7194a10356 --- /dev/null +++ b/Task/Factorial/Java/factorial-4.java @@ -0,0 +1,27 @@ +import java.math.BigInteger; +import java.util.function.Function; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +public final class Factorial { + + public static void main(String[] args) { + // Valid only for integer arguments 1, 2, ... , 20 + Function factorialPositive = n -> LongStream.rangeClosed(2, n).reduce(1, (a, b) -> a * b); + + // Valid for integer arguments <= 20 + Function factorial = n -> { + if ( n < 0 || n > 20 ) { + throw new AssertionError("Argument is out of range: " + n); + } + + return factorialPositive.apply(n); + }; + + // Return a BigInteger value + Function factorialBig = n -> Stream.iterate(BigInteger.ONE, i -> i.add(BigInteger.ONE)) + .limit(n) + .reduce(BigInteger.ONE, BigInteger::multiply); + } + +} diff --git a/Task/Factorial/M2000-Interpreter/factorial-2.m2000 b/Task/Factorial/M2000-Interpreter/factorial-2.m2000 index dc7940cef8..43a5d9ca37 100644 --- a/Task/Factorial/M2000-Interpreter/factorial-2.m2000 +++ b/Task/Factorial/M2000-Interpreter/factorial-2.m2000 @@ -9,19 +9,16 @@ Report { } Cls, row ' now we preserve some lines (as row number return here) Module CheckIt { - m=bigInteger("1") - with m, "tostring" as m.toString - k=width-tab - For i=1 to 1000 - if pos>tab then print - Print @(0), format$("{0::-4} :", i) ; - method m,"multiply", biginteger(i+"") as m - Report m.toString, k - ' Report stop at 2/3 of display lines, and wait mouse button or spacebar - ' we can flush the keyboard buffer and press space, so we get non stop display - ' Report didn't stop if we use the printer's layer. - while inkey$<>"": wait 1:end while - keyboard " " - Next i + m=1u ' 1u is biginteger + k=width-tab + For i=1 to 1000 + if pos>tab then print + m*=i + Print @(0), format$("{0::-4} :", i); + Report str$(m), k + ' Report accumulate lines and stop at 3/4 of the screen (but not on printer) + ' so we can break this using this line: + while inkey$<>"": wait 1:end while: keyboard " " + Next i } Checkit diff --git a/Task/Factorial/Pascal/factorial-2.pas b/Task/Factorial/Pascal/factorial-2.pas index 991914c559..6b44f23124 100644 --- a/Task/Factorial/Pascal/factorial-2.pas +++ b/Task/Factorial/Pascal/factorial-2.pas @@ -1,32 +1,45 @@ {$mode objFPC}{R+} -FUNCTION Factorial ( n : qword ) : qword; +FUNCTION Fact(n: qword): qword; - (*) - Update for version 3.2.0 - Factorial works until 20! , which is good enough for me for now - replace qword with dword and rax,rcx with eax, ecx for 32-bit - for Factorial until 12! - (*) +VAR + F: qword; - VAR - - F: qword; - - BEGIN +BEGIN + if n > 20 then + begin + WriteLn('This function is only accurate up to 20!'); + exit(0); + end; - asm - - mov $1, %rax - mov n, %rcx - - .Lloop1: - imul %rcx, %rax - loopnz .Lloop1 - - mov %rax, F + asm + (*) Initialize result = 1 (0! = 1 case handled automatically) (*) - end; + mov $1, %rax (*) RAX = 1 (initial result) (*) + mov n, %rcx (*) RCX = input number (counter) (*) - Result := F ; - - END; + test %rcx, %rcx (*) Check if n=0 (*) + jz .Lstore_result (*) Skip loop if n=0 (*) + + .Lloop1: + imul %rcx, %rax (*) RAX = RAX * RCX (signed mul) (*) + dec %rcx (*) Decrement RCX (*) + jnz .Lloop1 (*) Loop while RCX != 0 (*) + + .Lstore_result: + mov %rax, F (*) Store result in F (*) + end ['rax', 'rcx']; (*) Tell compiler register change (*) + + Result := F; + +END; + + +var + N : integer = 20 ; + +begin + + writeln; + writeln( BasicFact(N)); + +end. (*) Function Fact (*) diff --git a/Task/Factorial/Pascal/factorial-3.pas b/Task/Factorial/Pascal/factorial-3.pas index 64c4eabff6..137d0f6b28 100644 --- a/Task/Factorial/Pascal/factorial-3.pas +++ b/Task/Factorial/Pascal/factorial-3.pas @@ -1,92 +1,33 @@ -PROGRAM EXBigFac ; +program GMPfact; -{$IFDEF FPC} - {$mode objfpc}{$H+}{$J-}{R+} -{$ELSE} - {$APPTYPE CONSOLE} -{$ENDIF} +{$mode objfpc} -(*) +uses - Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64 - The free and readable alternative at C/C++ speeds - compiles natively to almost any platform, including raspberry PI * - Can run independently from DELPHI / Lazarus + gmp + ; - For debian Linux: apt -y install fpc - It contains a text IDE called fp + function Factorial(n: qword): string; + var + ResultMPZ: mpz_t; + i: qword; + begin + mpz_init_set_ui(ResultMPZ, 1); + for i := 2 to n do + mpz_mul_ui(ResultMPZ, ResultMPZ, i); + Result := mpz_get_str(nil, 10, ResultMPZ); + mpz_clear(ResultMPZ); + end; - https://www.freepascal.org/advantage.var +var + N : integer = 101 ; + Fact : string ; -(*) +begin + Fact := Factorial(101); + writeln( N ,'! = ', Fact); +end. (*) GMPfact (*) -USES - - gmp; - - FUNCTION WriteBigNum ( c: pchar ) : ansistring ; - - CONST - - CrLf = #13 + #10 ; - - VAR - i: longint; - len: longint; - preview: integer; - ret: ansistring = ''; - threshold: integer; - - BEGIN - - len := length ( c ) ; - WriteLn ( 'Digits: ', len ) ; - threshold := 12 ; - preview := len div threshold ; - - IF ( len < 91 ) THEN - BEGIN - FOR i := 0 TO len DO - ret:= ret + c [ i ] ; - END - ELSE - BEGIN - FOR i := 0 TO preview DO - ret:= ret + c [ i ] ; - ret:= ret + '...' ; - FOR i := len - preview -1 TO len DO - ret:= ret + c [ i ] ; - END; - ret:= ret + CrLf ; - WriteBigNum := ret; - END; - - FUNCTION BigFactorial ( n : qword ) : ansistring ; - - (*) - See https://gmplib.org/#DOC - (*) - - VAR - S: mpz_t; - c: pchar; - - BEGIN - - mpz_init_set_ui ( S, 1 ) ; - mpz_fac_ui ( S, n ) ; - c := mpz_get_str ( NIL, 10, S ) ; - BigFactorial := WriteBigNum ( c ) ; - - END; - -BEGIN - - WriteLn ( BigFactorial ( 99 ) ) ; - -END. - Output: -Digits: 156 -93326215443944...00000000000000 +101! = 9425947759838359420851623124482936749562312794702543768327889353416977599316221476503087861591808346911623490003549599583369706302603264000000000000000000000000 diff --git a/Task/Factorial/REXX/factorial-1.rexx b/Task/Factorial/REXX/factorial-1.rexx index b02528c706..4ab115dc32 100644 --- a/Task/Factorial/REXX/factorial-1.rexx +++ b/Task/Factorial/REXX/factorial-1.rexx @@ -1,18 +1,4 @@ -/*REXX pgm computes & shows the factorial of a non─negative integer, and also its length*/ -numeric digits 100000 /*100k digits: handles N up to 25k.*/ -parse arg n /*obtain optional argument from the CL.*/ -if n='' then call er 'no argument specified.' -if arg()>1 | words(n)>1 then call er 'too many arguments specified.' -if \datatype(n,'N') then call er "argument isn't numeric: " n -if \datatype(n,'W') then call er "argument isn't a whole number: " n -if n<0 then call er "argument can't be negative: " n -!= 1 /*define the factorial product (so far)*/ - do j=2 to n; !=!*j /*compute the factorial the hard way. */ - end /*j*/ /* [↑] where da rubber meets da road. */ - -say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/ -say /*add some whitespace to the output. */ -say ! /*display the factorial product──►term.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -er: say; say '***error***'; say; say arg(1); say; exit 13 +call time('r') +numeric digits 999999999 +a = 10/3 +say length(a) time('e') diff --git a/Task/Factorial/REXX/factorial-2.rexx b/Task/Factorial/REXX/factorial-2.rexx index 0ce1aa0e4d..01e564d9d2 100644 --- a/Task/Factorial/REXX/factorial-2.rexx +++ b/Task/Factorial/REXX/factorial-2.rexx @@ -1,22 +1,69 @@ -/*REXX program computes the factorial of a non─negative integer, and it automatically */ -/*────────────────────── adjusts the number of decimal digits to accommodate the answer.*/ -numeric digits 99 /*99 digits initially, then expanded. */ -parse arg n /*obtain optional argument from the CL.*/ -if n='' then call er 'no argument specified' -if arg()>1 | words(n)>1 then call er 'too many arguments specified.' -if \datatype(n,'N') then call er "argument isn't numeric: " n -if \datatype(n,'W') then call er "argument isn't a whole number: " n -if n<0 then call er "argument can't be negative: " n -!= 1 /*define the factorial product (so far)*/ - do j=2 to n; !=!*j /*compute the factorial the hard way. */ - if pos(.,!)==0 then iterate /*is the ! in exponential notation? */ - parse var ! 'E' digs /*extract exponent of the factorial, */ - numeric digits digs + digs % 10 /* ··· and increase it by ten percent.*/ - end /*j*/ /* [↑] where da rubber meets da road. */ -!= !/1 /*normalize the factorial product. */ -say n'! is ['length(!) "digits]:" /*display number of digits in factorial*/ -say /*add some whitespace to the output. */ -say ! /*display the factorial product ──►term*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -er: say; say '***error!***'; say; say arg(1); say; exit 13 +-- 8 May 2025 +include Settings + +say 'FACTORIAL' +say version +say +call First20 +call Imp 10,'1 10 100 1000 10000 100000 1000000 10000000 100000000 130202808' +call Rec 10,'1 10 100 1000 10000 100000 200000' +call Imp 100,'69' +call Imp 1000,'449' +call Imp 10000,'3248' +call Imp 100000,'25205' +exit + +First20: +say 'First 20 factorials...' +numeric digits 30 +do n = 1 to 20 + say n'! =' Fact(n) +end +say +return + +Imp: +glob. = '' +call Time('r') +arg d,p +numeric digits d; fact. = 0 +say 'Imperative in' d 'digits precision...' +do i = 1 to Words(p) + call Time('r'); f = Word(p,i); h = Fact(f) + parse var h 'E' e + if e = '' then + say right(f'!',10) 'has exact' right(Length(h),9) 'digits' '('Format(Time('e'),,3)'s)' + else + say right(f'!',10) 'has about' right(e+1,9) 'digits' '('Format(Time('e'),,3)'s)' +end +say +return + +Rec: +glob. = '' +call Time('r') +arg d,p +numeric digits d; fact. = 0 +say 'Recursive in' d 'digits precision...' +do i = 1 to Words(p) + call Time('r'); f = Word(p,i); h = Recursive(f) + parse var h 'E' e + if e = '' then + say right(f'!',10) 'has exact' right(Length(h),9) 'digits' '('Format(Time('e'),,3)'s)' + else + say right(f'!',10) 'has about' right(e+1,9) 'digits' '('Format(Time('e'),,3)'s)' +end +say +return + +Recursive: +procedure +arg xx +if xx = 0 then + return 1 +else + return xx*Recursive(xx-1) + +include Functions +include Special +include Abend diff --git a/Task/Factorial/REXX/factorial-3.rexx b/Task/Factorial/REXX/factorial-3.rexx deleted file mode 100644 index f9f6da4455..0000000000 --- a/Task/Factorial/REXX/factorial-3.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program computes & shows the factorial of an integer, striping trailing zeroes. */ -numeric digits 200 /*start with two hundred digits. */ -parse arg N . /*obtain an optional argument from CL. */ -if N=='' | N=="," then N= 0 /*Not specified? Then use the default.*/ -!= 1 /*define the factorial product so far. */ - do j=2 to N /*compute factorial the hard way. */ - old!= ! /*save old product in case of overflow.*/ - != ! * j /*multiple the old factorial with J. */ - if pos(.,!) \==0 then do /*is the ! in exponential notation?*/ - d= digits() /*D temporarily stores number digits.*/ - numeric digits d+d%10 /*add 10% to the decimal digits. */ - != old! * j /*re─calculate for the "lost" digits.*/ - end /*IFF ≡ if and only if. [↓] */ - parse var ! '' -1 _ /*obtain the right-most digit of ! */ - if _==0 then != strip(!, , 0) /*strip trailing zeroes IFF the ... */ - end /*j*/ /* [↑] ... right-most digit is zero. */ -z= 0 /*the number of trailing zeroes in ! */ - do v=5 by 0 while v<=N /*calculate number of trailing zeroes. */ - z= z + N % v /*bump Z if multiple power of five.*/ - v= v * 5 /*calculate the next power of five. */ - end /*v*/ /* [↑] we only advance V by ourself.*/ - /*stick a fork in it, we're all done. */ -!= ! || copies(0, z) /*add water to rehydrate the product. */ -if z==0 then z= 'no' /*use gooder English for the message. */ -say N'! is ['length(!) " digits with " z ' trailing zeroes]:' -say /*display blank line (for whitespace).*/ -say ! /*display the factorial product. */ diff --git a/Task/Factorial/REXX/factorial-4.rexx b/Task/Factorial/REXX/factorial-4.rexx deleted file mode 100644 index 4ab115dc32..0000000000 --- a/Task/Factorial/REXX/factorial-4.rexx +++ /dev/null @@ -1,4 +0,0 @@ -call time('r') -numeric digits 999999999 -a = 10/3 -say length(a) time('e') diff --git a/Task/Factorial/REXX/factorial-5.rexx b/Task/Factorial/REXX/factorial-5.rexx deleted file mode 100644 index 239ba782bb..0000000000 --- a/Task/Factorial/REXX/factorial-5.rexx +++ /dev/null @@ -1,67 +0,0 @@ -include Settings - -say version; say 'Factorial'; say -p = '10 20 52 104 208 416 1e3 1e4 1e5 1e6 1e7 1e8' -call Val 100 -p = '10 20 52 104 208 416 1e3 1e4 1e5 1e6' -call Dig 100 -call Dig 1000 -call Dig 3000 -p = '10 20 52 104 208 416 1e3 1e4 1e5' -call Dig 40000 -call Dig 500000 -p = '10 20 52 104 208 416 1e3 1e4' -call Dig 5000000 -exit - -Val: -call Time('r') -arg d -numeric digits d; fact. = 0 -say 'Precision is' d 'digits' -do i = 1 to Words(p) - call Time('r');f = Word(p,i); say f'!' '=' Fact(f) '('Format(Time('e'),,3)'s)' -end -say -return - -Dig: -call Time('r') -arg d -numeric digits d; fact. = 0 -say 'Precision is' d 'digits' -do i = 1 to Words(p) - call Time('r'); f = Word(p,i); h = Fact(f) - parse var h 'E' e - if e = '' then - say f'!' 'has exact' Length(h) 'digits' '('Format(Time('e'),,3)'s)' - else - say f'!' 'has about' e+1 'digits' '('Format(Time('e'),,3)'s)' -end -say -return - -Fact: -/* Factorial = n! */ -procedure expose fact. -arg x -/* Current in memory? */ -if fact.factorial.x <> 0 then - return fact.factorial.x -/* Previous in memory? */ -w = x-1 -if fact.factorial.w = 0 then do -/* Loop cf definition */ - y = 1 - do n = 2 to x - y = y*n - end - fact.factorial.x = y -end -else -/* Multiply */ - fact.factorial.x = fact.factorial.w*x -return fact.factorial.x - -include Functions -include Abend diff --git a/Task/Factorial/SQL/factorial.sql b/Task/Factorial/SQL/factorial.sql new file mode 100644 index 0000000000..c0b412e4a3 --- /dev/null +++ b/Task/Factorial/SQL/factorial.sql @@ -0,0 +1,6 @@ +WITH RECURSIVE f(a, b) AS ( + VALUES(1, 1) + UNION ALL + SELECT a * b, b + 1 FROM f WHERE b <= 9 +) +SELECT MAX(a) FROM f diff --git a/Task/Factorial/Tcl/factorial-1.tcl b/Task/Factorial/Tcl/factorial-1.tcl index 8220088fdf..a204184466 100644 --- a/Task/Factorial/Tcl/factorial-1.tcl +++ b/Task/Factorial/Tcl/factorial-1.tcl @@ -1,6 +1,12 @@ -proc ifact n { - for {set i $n; set sum 1} {$i >= 2} {incr i -1} { - set sum [expr {$sum * $i}] +# tailcall optimization is standard in tcl8.6 +proc fact { n { result 1. } } { + if { $n <= 1 } { + return $result + } else { + tailcall fact [expr {$n-1}] [expr {$n*$result}] } - return $sum } + +set f [fact 10] + +puts $f diff --git a/Task/Factorial/Tcl/factorial-2.tcl b/Task/Factorial/Tcl/factorial-2.tcl index 40cc360692..8220088fdf 100644 --- a/Task/Factorial/Tcl/factorial-2.tcl +++ b/Task/Factorial/Tcl/factorial-2.tcl @@ -1,3 +1,6 @@ -proc rfact n { - expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]} +proc ifact n { + for {set i $n; set sum 1} {$i >= 2} {incr i -1} { + set sum [expr {$sum * $i}] + } + return $sum } diff --git a/Task/Factorial/Tcl/factorial-3.tcl b/Task/Factorial/Tcl/factorial-3.tcl index e25b3f18c7..40cc360692 100644 --- a/Task/Factorial/Tcl/factorial-3.tcl +++ b/Task/Factorial/Tcl/factorial-3.tcl @@ -1 +1,3 @@ -proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}} +proc rfact n { + expr {$n < 2 ? 1 : $n * [rfact [incr n -1]]} +} diff --git a/Task/Factorial/Tcl/factorial-4.tcl b/Task/Factorial/Tcl/factorial-4.tcl index 9a9a02de85..e25b3f18c7 100644 --- a/Task/Factorial/Tcl/factorial-4.tcl +++ b/Task/Factorial/Tcl/factorial-4.tcl @@ -1,17 +1 @@ -proc ifact_caching n { - global fact_cache - if { ! [info exists fact_cache]} { - set fact_cache {1 1} - } - if {$n < [llength $fact_cache]} { - return [lindex $fact_cache $n] - } - set i [expr {[llength $fact_cache] - 1}] - set sum [lindex $fact_cache $i] - while {$i < $n} { - incr i - set sum [expr {$sum * $i}] - lappend fact_cache $sum - } - return $sum -} +proc tcl::mathfunc::fact n {expr {$n < 2? 1: $n*fact($n-1)}} diff --git a/Task/Factorial/Tcl/factorial-5.tcl b/Task/Factorial/Tcl/factorial-5.tcl index ecdfbe5752..9a9a02de85 100644 --- a/Task/Factorial/Tcl/factorial-5.tcl +++ b/Task/Factorial/Tcl/factorial-5.tcl @@ -1,11 +1,17 @@ -puts [ifact 30] -puts [rfact 30] -puts [ifact_caching 30] - -set n 400 -set iterations 10000 -puts "calculate $n factorial $iterations times" -puts "ifact: [time {ifact $n} $iterations]" -puts "rfact: [time {rfact $n} $iterations]" -# for the caching proc, reset the cache between each iteration so as not to skew the results -puts "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]" +proc ifact_caching n { + global fact_cache + if { ! [info exists fact_cache]} { + set fact_cache {1 1} + } + if {$n < [llength $fact_cache]} { + return [lindex $fact_cache $n] + } + set i [expr {[llength $fact_cache] - 1}] + set sum [lindex $fact_cache $i] + while {$i < $n} { + incr i + set sum [expr {$sum * $i}] + lappend fact_cache $sum + } + return $sum +} diff --git a/Task/Factorial/Tcl/factorial-6.tcl b/Task/Factorial/Tcl/factorial-6.tcl index 46e5e0fcab..ecdfbe5752 100644 --- a/Task/Factorial/Tcl/factorial-6.tcl +++ b/Task/Factorial/Tcl/factorial-6.tcl @@ -1,5 +1,11 @@ -package require math::special +puts [ifact 30] +puts [rfact 30] +puts [ifact_caching 30] -proc gfact n { - expr {round([::math::special::Gamma [expr {$n+1}]])} -} +set n 400 +set iterations 10000 +puts "calculate $n factorial $iterations times" +puts "ifact: [time {ifact $n} $iterations]" +puts "rfact: [time {rfact $n} $iterations]" +# for the caching proc, reset the cache between each iteration so as not to skew the results +puts "ifact_caching: [time {ifact_caching $n; unset -nocomplain fact_cache} $iterations]" diff --git a/Task/Factorial/Tcl/factorial-7.tcl b/Task/Factorial/Tcl/factorial-7.tcl new file mode 100644 index 0000000000..46e5e0fcab --- /dev/null +++ b/Task/Factorial/Tcl/factorial-7.tcl @@ -0,0 +1,5 @@ +package require math::special + +proc gfact n { + expr {round([::math::special::Gamma [expr {$n+1}]])} +} diff --git a/Task/Factorial/Uxntal/factorial.uxnatl b/Task/Factorial/Uxntal/factorial.uxnatl index 6ce1360a76..f936013ac4 100644 --- a/Task/Factorial/Uxntal/factorial.uxnatl +++ b/Task/Factorial/Uxntal/factorial.uxnatl @@ -1,4 +1,28 @@ -@factorial ( n* -: fact* ) +%newline { [ LIT2 0a -Console/write ] DEO } + +|18 @Console/write + +|100 + +#0900 +&loop + DUP #00 SWP factorial print/dec newline + INC GTHk ?&loop +POP2 + +BRK + +@factorial ( n* -- n!* ) ORAk ?{ POP2 #0001 JMP2r } DUP2 #0001 SUB2 factorial MUL2 -JMP2r + JMP2r + +@print/dec ( short* -- ) + #000a SWP2 [ LITr ff ] + &get ( -- ) + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?&get + POP2 POP2 + &put ( -- ) + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !&put diff --git a/Task/Factorions/EasyLang/factorions.easy b/Task/Factorions/EasyLang/factorions.easy new file mode 100644 index 0000000000..0e6f41446e --- /dev/null +++ b/Task/Factorions/EasyLang/factorions.easy @@ -0,0 +1,21 @@ +len fact[] 12 +arrbase fact[] 0 +# +fact[0] = 1 +for n = 1 to 11 + fact[n] = fact[n - 1] * n +. +for b = 9 to 12 + write "base " & b & " factorions:" + for i = 1 to 1500000 - 1 + sum = 0 + j = i + while j > 0 + d = j mod b + sum += fact[d] + j = j div b + . + if sum = i : write " " & i + . + print "" +. diff --git a/Task/Factorions/R/factorions.r b/Task/Factorions/R/factorions.r new file mode 100644 index 0000000000..7922c0c7b6 --- /dev/null +++ b/Task/Factorions/R/factorions.r @@ -0,0 +1,15 @@ +fact_digsum <- function(n, b){ + if(n>b-1){ + return(factorial(n%%b)+fact_digsum(n%/%b, b)) + } + else return(factorial(n)) +} + +for(i in 9:12){ + cat("Factorions in base",i,"\n") + for(j in 1:1499999){ + if(j==fact_digsum(j, i)){ + print(j) + } + } +} diff --git a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-1.rexx b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-1.rexx deleted file mode 100644 index d575fd9097..0000000000 --- a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-1.rexx +++ /dev/null @@ -1,53 +0,0 @@ -/*REXX program uses exponent─and─mod operator to test possible Mersenne numbers. */ -numeric digits 20 /*this will be increased if necessary. */ -parse arg N spec /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 88 /*Not specified? Then use the default.*/ -if spec=='' | spec=="," then spec= 920 970 /* " " " " " " */ - do j=1; z= j /*process a range, & then do some more.*/ - if j==N then j= word(spec, 1) /*now, use the high range of numbers. */ - if j>word(spec, 2) then leave /*done with " " " " " */ - if \isPrime(z) then iterate /*if Z isn't a prime, keep plugging.*/ - r= commas( testMer(z) ); L= length(r) /*add commas; get its new length. */ - if r==0 then say right('M'z, 10) "──────── is a Mersenne prime." - else say right('M'z, 50) "is composite, a factor:"right(r, max(L, 13) ) - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7') \== 0 then return 1 - if x<11 then return 0; if x//2 == 0 | x//3 == 0 then return 0 - do j=5 by 6; if x//j == 0 | x//(j+2) == 0 then return 0 - if j*j>x then return 1 /*◄─┐ ___ */ - end /*j*/ /* └─◄ Is j>√ x ? Then return 1*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -iSqrt: procedure; parse arg x; #= 1; r= 0; do while #<=x; #= # * 4 - end /*while*/ - do while #>1; #= # % 4; _= x-r-#; r= r % 2 - if _>=0 then do; x= _; r= r + # - end - end /*while*/ /*iSqrt ≡ integer square root.*/ - return r /*───── ─ ── ─ ─ */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -testMer: procedure; parse arg x; p= 2**x /* [↓] do we have enough digits?*/ - $$=x2b( d2x(x) ) + 0 - if pos('E',p)\==0 then do; parse var p "E" _; numeric digits _ + 2; p= 2**x - end - !.= 1; !.1= 0; !.7= 0 /*array used for a quicker test. */ - R= iSqrt(p) /*obtain integer square root of P*/ - do k=2 by 2; q= k*x + 1 /*(shortcut) compute value of Q. */ - m= q // 8 /*obtain the remainder when ÷ 8. */ - if !.m then iterate /*M must be either one or seven.*/ - parse var q '' -1 _; if _==5 then iterate /*last digit a five ? */ - if q// 3==0 then iterate /*divisible by three? */ - if q// 7==0 then iterate /* " " seven? */ - if q//11==0 then iterate /* " " eleven?*/ - /* ____ */ - if q>R then return 0 /*Is q>√2**x ? A Mersenne prime*/ - sq= 1; $= $$ /*obtain binary version from $. */ - do until $==''; sq= sq*sq - parse var $ _ 2 $ /*obtain 1st digit and the rest. */ - if _ then sq= (sq+sq) // q - end /*until*/ - if sq==1 then return q /*Not a prime? Return a factor.*/ - end /*k*/ diff --git a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx similarity index 72% rename from Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx rename to Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx index 0c9b756a9b..31536d9a38 100644 --- a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number-2.rexx +++ b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx @@ -1,11 +1,13 @@ +-- 22 Mar 2025 include Settings -say 'Factor of a Mersenne Number - Using REXX libraries' -parse version version; say version; say -call Time('r') + +say 'FACTORS OF A MERSENNE NUMBER' +say version +say numeric digits 300 n = Primes(1000) do i = 1 to n - x = prim.Prime.i + x = prim.i select when (x >= 2 & x <= 83) then call Task x @@ -15,7 +17,7 @@ do i = 1 to n nop end end -say; say Format(Time('e'),,3) 'seconds'; say +say; say Format(Time('e'),,3) 'seconds' exit Task: @@ -33,13 +35,13 @@ do k = 1 by 2*x to Isqrt(m) iterate k c = m//k if c = 1 then do - say a 'is Composite =' k 'x ...' + say a 'is composite =' k 'x ...' leave k end end end if c <> 1 then - say a 'is Prime' + say a 'is prime' return include Functions diff --git a/Task/Factors-of-an-integer/EasyLang/factors-of-an-integer.easy b/Task/Factors-of-an-integer/EasyLang/factors-of-an-integer.easy index 493a738a49..ff13ddc639 100644 --- a/Task/Factors-of-an-integer/EasyLang/factors-of-an-integer.easy +++ b/Task/Factors-of-an-integer/EasyLang/factors-of-an-integer.easy @@ -1,7 +1,8 @@ -n = 720 -for i = 1 to n - if n mod i = 0 - factors[] &= i - . +func[] factors n . + for i = 1 to n + if n mod i = 0 : f[] &= i + . + return f[] . -print factors[] +print factors 10 +print factors 720 diff --git a/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx b/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx index 7f2c60a2ca..4e743184e1 100644 --- a/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx +++ b/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx @@ -1,29 +1,32 @@ -/*REXX program displays divisors of any [negative/zero/positive] integer or a range.*/ -parse arg LO HI inc . /*obtain the optional args*/ -HI= word(HI LO 20, 1); LO= word(LO 1,1); inc= word(inc 1,1) /*define the range options*/ -w= length(HI) + 2; numeric digits max(9, w-2); != '∞' /*decimal digits for // */ -@.=left('',7); @.1= "{unity}"; @.2= '[prime]'; @.!= " {∞} " /*define some literals. */ -say center('n', w) "#divisors" center('divisors', 60) /*display the header. */ -say copies('═', w) "═════════" copies('═' , 60) /* " " separator. */ -pn= 0 /*count of prime numbers. */ - do k=2 until sq.k>=HI; sq.k= k*k /*memoization for squares.*/ - end /*k*/ - do n=LO to HI by inc; $= divs(n); #= words($) /*get list of divs; # divs*/ - if $==! then do; #= !; $= ' (infinite)'; end /*handle case for infinity*/ - p= @.#; if n<0 then if n\==-1 then p= @.. /* " " " negative*/ - if p==@.2 then pn= pn + 1 /*Prime? Then bump counter*/ - say center(n, w) center('['#"]", 9) "──► " p ' ' $ - end /*n*/ /* [↑] process a range of integers. */ -say -say right(pn, 20) ' primes were found.' /*display the number of primes found. */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -divs: procedure expose sq.; parse arg x 1 b; a=1 /*set X and B to the 1st argument. */ - if x<2 then do; x= abs(x); if x==1 then return 1; if x==0 then return '∞'; b=x - end - odd= x // 2 /* [↓] process EVEN or ODD ints. ___*/ - do j=2+odd by 1+odd while sq.j= 0 { return s; } + return "-" + s; +} + +public function main() { + // task 1. solution by recursive generation of mediants + foreach int n in 1...11 { + frac l = new(0, 1); + frac r = new(1, 1); + io:print(`F(${n}): ${l} `); + f(l, r, n); + io:println(r); + } + io:println(); + + // task 2. direct solution by summing totient function + // 2.1 generate primes to 1000 + boolean[1001] composite = []; + foreach int p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] { + foreach int n in int:range(p * 2, 1001, p) { composite[n] = true; } + } + + // 2.2 generate totients to 1000 + int[1001] tot = []; + foreach int i in 0...1000 { tot[i] = 1; } + foreach int n in 2...1000 { + if !composite[n] { + tot[n] = n - 1; + foreach int a in int:range(n * 2, 1001, n) { + int f = n - 1; + int r = a / n; + while r % n == 0 { + f *= n; + r /= n; + } + tot[a] *= f; + } + } + } + + // sum totients + int sum = 1; + foreach int n in 1...1000 { + sum += tot[n]; + if n % 100 == 0 { + string s1 = n.toString().padStart(4); + string s2 = commatize(sum).padStart(7); + io:println(`F(${s1}): ${s2}`); + } + } +} diff --git a/Task/Farey-sequence/EasyLang/farey-sequence.easy b/Task/Farey-sequence/EasyLang/farey-sequence.easy index a16f529e1c..602f6ec0e8 100644 --- a/Task/Farey-sequence/EasyLang/farey-sequence.easy +++ b/Task/Farey-sequence/EasyLang/farey-sequence.easy @@ -1,5 +1,7 @@ -proc farey n . . - b = 1 ; c = 1 ; d = n +proc farey n . + b = 1 + c = 1 + d = n write n & ": " repeat if n <= 11 diff --git a/Task/Fast-Fourier-transform/EasyLang/fast-fourier-transform.easy b/Task/Fast-Fourier-transform/EasyLang/fast-fourier-transform.easy index e5fc7b7705..4b6e1acb26 100644 --- a/Task/Fast-Fourier-transform/EasyLang/fast-fourier-transform.easy +++ b/Task/Fast-Fourier-transform/EasyLang/fast-fourier-transform.easy @@ -15,7 +15,7 @@ func[] cexp a[] . func cabs a[] . return sqrt (a[1] * a[1] + a[2] * a[2]) . -proc fft x[] . y[][] . +proc fft x[] &y[][] . n = len x[] if n = 1 y[][] = [ [ x[1] 0 ] ] diff --git a/Task/Faulhabers-formula/C/faulhabers-formula.c b/Task/Faulhabers-formula/C/faulhabers-formula.c index 12955f4db8..0388b37b1b 100644 --- a/Task/Faulhabers-formula/C/faulhabers-formula.c +++ b/Task/Faulhabers-formula/C/faulhabers-formula.c @@ -1,169 +1,121 @@ -#include -#include +#include #include +#include +#include +typedef unsigned long ul; +#define mpq_for(buf, op, n)\ +do {\ + size_t i;\ + for (i = 0; i < (n); ++i)\ + mpq_##op(buf[i]);\ +} while (0) -int binomial(int n, int k) { - int num, denom, i; - - if (n < 0 || k < 0 || n < k) return -1; - if (n == 0 || k == 0) return 1; - - num = 1; - for (i = k + 1; i <= n; ++i) { - num = num * i; +void mpz_choose_ui(mpz_t rop,ul a,ul b){ + mpz_set_ui(rop,1); + for(ul i=0;i 1) { - n = n / g; - d = d / g; - } - - result.num = n; - result.denom = d; - return result; -} - -Frac negateFrac(Frac f) { - return makeFrac(-f.num, f.denom); -} - -Frac subFrac(Frac lhs, Frac rhs) { - return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom); -} - -Frac multFrac(Frac lhs, Frac rhs) { - return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom); -} - -bool equalFrac(Frac lhs, Frac rhs) { - return (lhs.num == rhs.num) && (lhs.denom == rhs.denom); -} - -bool lessFrac(Frac lhs, Frac rhs) { - return (lhs.num * rhs.denom) < (rhs.num * lhs.denom); -} - -void printFrac(Frac f) { - printf("%d", f.num); - if (f.denom != 1) { - printf("/%d", f.denom); + for(ul i=1;i<=b;i++){ + mpz_div_ui(rop,rop,i); } } - -Frac bernoulli(int n) { - Frac a[16]; - int j, m; - - if (n < 0) { - a[0].num = 0; - a[0].denom = 0; - return a[0]; - } +void bernoulli(mpq_t rop, unsigned int n){ + unsigned int m, j; + mpq_t *a = malloc(sizeof(mpq_t) * (n + 1)); + mpq_for(a, init, n + 1); for (m = 0; m <= n; ++m) { - a[m] = makeFrac(1, m + 1); - for (j = m; j >= 1; --j) { - a[j - 1] = multFrac(subFrac(a[j - 1], a[j]), makeFrac(j, 1)); + mpq_set_ui(a[m], 1, m + 1); + for (j = m; j > 0; --j) { + mpq_sub(a[j-1], a[j], a[j-1]); + mpq_set_ui(rop, j, 1); + mpq_mul(a[j-1], a[j-1], rop); } } - if (n != 1) { - return a[0]; - } - - return negateFrac(a[0]); + mpq_set(rop, a[0]); + mpq_for(a, clear, n + 1); + free(a); +} +void bernoullip(mpq_t rop,unsigned int n){ + bernoulli(rop,n); + if(n!=1){return;} + mpq_neg(rop,rop); + return; } -void faulhaber(int p) { - Frac coeff, q; - int j, pwr, sign; +void mpq_print(mpq_t rop){ + mpz_t n,d; + mpz_inits(n,d,NULL); + mpq_get_num(n, rop); + mpq_get_den(d, rop); + gmp_printf("%Zd/%Zd\n", n, d); + mpz_clears(n,d,NULL); +} +void mpz_print(mpz_t rop){ - printf("%d : ", p); - q = makeFrac(1, p + 1); - sign = -1; - for (j = 0; j <= p; ++j) { - sign = -1 * sign; - coeff = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j)); - if (equalFrac(coeff, makeFrac(0, 1))) { - continue; - } - if (j == 0) { - if (!equalFrac(coeff, makeFrac(1, 1))) { - if (equalFrac(coeff, makeFrac(-1, 1))) { - printf("-"); - } else { - printFrac(coeff); - } - } - } else { - if (equalFrac(coeff, makeFrac(1, 1))) { - printf(" + "); - } else if (equalFrac(coeff, makeFrac(-1, 1))) { - printf(" - "); - } else if (lessFrac(makeFrac(0, 1), coeff)) { - printf(" + "); - printFrac(coeff); - } else { - printf(" - "); - printFrac(negateFrac(coeff)); - } - } - pwr = p + 1 - j; - if (pwr > 1) { - printf("n^%d", pwr); - } else { - printf("n"); - } - } - printf("\n"); + gmp_printf("%Zd\n",rop); +} +void mpq_div_ui(mpq_t op1,mpq_t op2,ul op3){ + mpq_t tmp; + mpq_init(tmp); + mpq_set_ui(tmp,op3,1); + mpq_div(op1,op2,tmp); + mpq_clear(tmp); } -int main() { - int i; - - for (i = 0; i < 10; ++i) { - faulhaber(i); +void mpq_mul_z(mpq_t op1,mpq_t op2,mpz_t op3){ + mpq_t tmp; + mpq_init(tmp); + mpq_set_z(tmp,op3); + mpq_mul(op1,op2,tmp); + mpq_clear(tmp); +} +void mpq_to_mpz(mpz_t rop,mpq_t op){ + mpz_t tmp; + mpz_init(tmp); + mpq_get_num(rop,op); + mpq_get_den(tmp,op); + if(mpz_cmp_ui(tmp,1)!=0){ + mpz_div(rop,rop,tmp); } - + mpz_clear(tmp); +} +void faulhaber(mpq_t out,ul n,ul p){ + mpq_t tmp; + mpz_t tmp2,tmp3; + mpq_init(tmp); + mpz_inits(tmp2,tmp3,NULL); + mpq_clear(out); + mpq_init(out); + for(ul r=0;r Self { + if d == 0 { + panic!("d must not be zero"); + } + + let mut nn = n; + let mut dd = d; + + if nn == 0 { + dd = 1; + } else if dd < 0 { + nn = -nn; + dd = -dd; + } + + let g = gcd(nn.abs(), dd.abs()); + if g > 1 { + nn /= g; + dd /= g; + } + + Frac { num: nn, denom: dd } + } + + fn zero() -> Self { + Frac::new(0, 1) + } + + fn one() -> Self { + Frac::new(1, 1) + } +} + +impl Neg for Frac { + type Output = Self; + + fn neg(self) -> Self { + Frac::new(-self.num, self.denom) + } +} + +impl Add for Frac { + type Output = Self; + + fn add(self, rhs: Self) -> Self { + Frac::new( + self.num * rhs.denom + self.denom * rhs.num, + rhs.denom * self.denom, + ) + } +} + +impl Sub for Frac { + type Output = Self; + + fn sub(self, rhs: Self) -> Self { + Frac::new( + self.num * rhs.denom - self.denom * rhs.num, + rhs.denom * self.denom, + ) + } +} + +impl Mul for Frac { + type Output = Self; + + fn mul(self, rhs: Self) -> Self { + Frac::new(self.num * rhs.num, self.denom * rhs.denom) + } +} + +impl fmt::Display for Frac { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.num == 0 || self.denom == 1 { + write!(f, "{}", self.num) + } else { + write!(f, "{}/{}", self.num, self.denom) + } + } +} + +fn bernoulli(n: i32) -> Frac { + if n < 0 { + panic!("n may not be negative or zero"); + } + + let mut a: Vec = Vec::new(); + for m in 0..=n { + a.push(Frac::new(1, (m + 1) as i64)); + for j in (1..=m).rev() { + let j_usize = j as usize; + a[j_usize - 1] = (a[j_usize - 1] - a[j_usize]) * Frac::new(j as i64, 1); + } + } + + // returns 'first' Bernoulli number + if n != 1 { + a[0] + } else { + -a[0] + } +} + +fn binomial(n: i32, k: i32) -> i64 { + if n < 0 || k < 0 || n < k { + panic!("parameters are invalid"); + } + if n == 0 || k == 0 { + return 1; + } + + let mut num: i64 = 1; + for i in (k + 1)..=n { + num *= i as i64; + } + + let mut denom: i64 = 1; + for i in 2..=(n - k) { + denom *= i as i64; + } + + num / denom +} + +fn faulhaber(p: i32) { + print!("{} : ", p); + + let q = Frac::new(1, (p + 1) as i64); + let mut sign: i32 = -1; + for j in 0..=p { + sign *= -1; + let coeff = q * Frac::new(sign as i64, 1) * Frac::new(binomial(p + 1, j), 1) * bernoulli(j); + if coeff == Frac::zero() { + continue; + } + if j == 0 { + if coeff == -Frac::one() { + print!("-"); + } else if coeff != Frac::one() { + print!("{}", coeff); + } + } else { + if coeff == Frac::one() { + print!(" + "); + } else if coeff == -Frac::one() { + print!(" - "); + } else if coeff < Frac::zero() { + print!(" - {}", -coeff); + } else { + print!(" + {}", coeff); + } + } + let pwr = p + 1 - j; + if pwr > 1 { + print!("n^{}", pwr); + } else { + print!("n"); + } + } + println!(); +} + +fn main() { + for i in 0..10 { + faulhaber(i); + } +} diff --git a/Task/Feigenbaum-constant-calculation/EasyLang/feigenbaum-constant-calculation.easy b/Task/Feigenbaum-constant-calculation/EasyLang/feigenbaum-constant-calculation.easy index 3b826f30aa..4400fb17ab 100644 --- a/Task/Feigenbaum-constant-calculation/EasyLang/feigenbaum-constant-calculation.easy +++ b/Task/Feigenbaum-constant-calculation/EasyLang/feigenbaum-constant-calculation.easy @@ -1,10 +1,13 @@ -numfmt 6 0 -a1 = 1 ; a2 = 0 ; d1 = 3.2 +numfmt 0 6 +a1 = 1 +a2 = 0 +d1 = 3.2 ipow2 = 4 for i = 2 to 13 a = a1 + (a1 - a2) / d1 for j = 1 to 10 - x = 0 ; y = 0 + x = 0 + y = 0 for k = 1 to ipow2 y = 1 - 2 * y * x x = a - x * x diff --git a/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-1.rexx b/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-1.rexx deleted file mode 100644 index 480cb4ca72..0000000000 --- a/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-1.rexx +++ /dev/null @@ -1,33 +0,0 @@ -/*REXX pgm calculates the (Mitchell) Feigenbaum bifurcation velocity, #digs can be given*/ -parse arg digs maxi maxj . /*obtain optional argument from the CL.*/ -if digs=='' | digs=="," then digs= 30 /*Not specified? Then use the default.*/ -if maxi=='' | maxi=="," then maxi= 20 /* " " " " " " */ -if maxJ=='' | maxJ=="," then maxJ= 10 /* " " " " " " */ -#= 4.669201609102990671853203820466201617258185577475768632745651343004134330211314737138, - || 68974402394801381716 /*◄──Feigenbaum's constant, true value.*/ -numeric digits digs /*use the specified # of decimal digits*/ - a1= 1 - a2= 0 - d1= 3.2 -say 'Using ' maxJ " iterations for maxJ, with " digs ' decimal digits:' -say -say copies(' ', 9) center("correct", 11) copies(' ', digs+1) -say center('i', 9, "─") center('digits' , 11, "─") center('d', digs+1, "─") - - do i=2 for maxi-1 - a= a1 + (a1 - a2) / d1 - do maxJ - x= 0; y= 0 - do 2**i; y= 1 - 2 * x * y - x= a - x*x - end /*2**i*/ - a= a - x / y - end /*maxj*/ - d= (a1 - a2) / (a - a1) /*compute the delta (D) of the function*/ - t= max(0, compare(d, #) - 2) /*# true digs so far, ignore dec. point*/ - say center(i, 9) center(t, 11) d /*display values for I & D ──►terminal*/ - parse value d a1 a with d1 a2 a1 /*assign 3 variables with 3 new values.*/ - end /*i*/ - /*stick a fork in it, we're all done. */ -say left('', 9 + 1 + 11 + 1 + t )"↑" /*show position of greatest accuracy. */ -say ' true value= ' # / 1 /*true value of Feigenbaum's constant. */ diff --git a/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx b/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation.rexx similarity index 72% rename from Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx rename to Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation.rexx index 81e8fa6e36..f01041e76f 100644 --- a/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation-2.rexx +++ b/Task/Feigenbaum-constant-calculation/REXX/feigenbaum-constant-calculation.rexx @@ -1,20 +1,20 @@ -arg n; if n = '' then n = 30; numeric digits n -parse version version; say version; glob. = '' -say 'First Fiegenbaum constant, correct to about 11 decimals' -say 'Using algorithm cf RosettaCode' +-- 8 May 2025 +say 'FIRST FEIGENBAUM CONSTANT' +say 'Using algorithm cf RosettaCode, correct to about 11 decimals' say -call time('r'); a = Original(); e = format(time('e'),,3) +arg n; if n = '' then n = 30; numeric digits n +call Time('r'); a = Original(); e = Format(Time('e'),,3) say 'Original ' a '('e 'seconds)' -call time('r'); a = Optimized(); e = format(time('e'),,3) +call Time('r'); a = Optimized(); e = Format(Time('e'),,3) say 'Optimized ' a '('e 'seconds)' -call time('r'); a = TrueValue(); e = format(time('e'),,3) +call Time('r'); a = TrueValue(); e = Format(Time('e'),,3) say 'True value' a '('e 'seconds)' exit Original: procedure expose glob. /* Outer 2 loops with a fixed value */ -numeric digits digits()+2 +numeric digits Digits()+2 im = 20; jm = 10 a1 = 1; a2 = 0; d1 = 3.2 do i = 2 to im @@ -29,13 +29,13 @@ do i = 2 to im d = (a1-a2) / (a-a1) parse value d a1 a with d1 a2 a1 end -numeric digits digits()-2 +numeric digits Digits()-2 return d+0 Optimized: procedure expose glob. /* Center loop stops on achieving desired accuracy */ -numeric digits digits()+4; numeric fuzz 4 +numeric digits Digits()+4; numeric fuzz 4 /* Only outer loop maximum */ im = 20 a1 = 1; a2 = 0; d1 = 3.2 @@ -54,8 +54,9 @@ do i = 2 to im end d = (a1-a2) / (a-a1) parse value d a1 a with d1 a2 a1 + say Format(i,2) Format(d,1,12) end -numeric digits digits()-4 +numeric digits Digits()-4 return d+0 TrueValue: diff --git a/Task/Fermat-numbers/FreeBASIC/fermat-numbers.basic b/Task/Fermat-numbers/FreeBASIC/fermat-numbers.basic new file mode 100644 index 0000000000..15eae8e495 --- /dev/null +++ b/Task/Fermat-numbers/FreeBASIC/fermat-numbers.basic @@ -0,0 +1,102 @@ +#include "big_int/big_integer.bi" + +Function Bigint_isPrime(Byval ValorEval As Bigint) As Boolean + If ValorEval < Bigint("2") Then Return False + If ValorEval Mod Bigint("2") = Bigint("0") Then Return (ValorEval = Bigint("2")) + If ValorEval Mod Bigint("3") = Bigint("0") Then Return (ValorEval = Bigint("3")) + + Dim As Bigint d = Bigint("5") + While d * d <= ValorEval + If ValorEval Mod d = Bigint("0") Then + Return False + Else + d += Bigint("2") + End If + Wend + + Return True +End Function + +Function Bigint_gcd(x As Bigint, y As Bigint) As Bigint + Dim As Bigint a = x, b = y + While b <> 0 + Dim As Bigint next_a = b + b = a Mod b + a = next_a + Wend + + Return a +End Function + +Function CalcularFermat(n As Integer) As Bigint + Dim As Bigint valorBase = Bigint("1") Shl (1 Shl n) + valorBase += Bigint("1") + + Return valorBase +End Function + +Function PollardsRho(n As Bigint) As Bigint + If (n Mod Bigint("2")) = Bigint("0") Then Return Bigint("2") + + Dim As Bigint x = Bigint("2"), y = Bigint("2"), d = Bigint("1") + Dim As Bigint c = Bigint("1") + + While d = Bigint("1") + x = (x * x + c) Mod n + y = (y * y + c) Mod n + y = (y * y + c) Mod n + d = Bigint_gcd(Abs(x - y), n) + Wend + + Return Iif(d = n, Bigint("0"), d) ' Avoid returning n as a factor +End Function + +' Factorización prima usando Pollard's Rho +Sub FactorizarPrimos(n As Bigint, factores() As Bigint) + If n = Bigint("1") Then Exit Sub + + If Bigint_isPrime(n) Then + Redim Preserve factores(Ubound(factores) + 1) + factores(Ubound(factores)) = n + Exit Sub + End If + + Dim As Bigint d = PollardsRho(n) + + ' If we couldn't factor it, we treated it as prime. + If d = Bigint("0") Then ' Fallback if Pollard finds no factors + Redim Preserve factores(Ubound(factores) + 1) + factores(Ubound(factores)) = n + Else + FactorizarPrimos(d, factores()) + FactorizarPrimos(n \ d, factores()) + End If +End Sub + +' Main program +Dim As Integer i, j +Dim As Bigint numFermat(0 To 9) + +Print "The first 10 Fermat numbers are:" +For i = 0 To 9 + numFermat(i) = CalcularFermat(i) + Print "F" & i & " = " & Str(numFermat(i)) +Next i + +Print !"\nFactors of the first 7 Fermat numbers:" +For i = 0 To 6 + Dim As Bigint factores() + FactorizarPrimos(numFermat(i), factores()) + + Dim As String salida = "[" + For j = Lbound(factores) To Ubound(factores) + salida &= Str(factores(j)) + If j < Ubound(factores) Then salida &= ", " + Next + salida &= "]" + If Ubound(factores) = Lbound(factores) Then salida &= " (prime)" + + Print "F" & i & " = " & salida +Next i + +Sleep diff --git a/Task/Fermat-numbers/REXX/fermat-numbers-1.rexx b/Task/Fermat-numbers/REXX/fermat-numbers-1.rexx deleted file mode 100644 index 69b5b9cd55..0000000000 --- a/Task/Fermat-numbers/REXX/fermat-numbers-1.rexx +++ /dev/null @@ -1,33 +0,0 @@ -/*REXX program to find and display Fermat numbers, and show factors of Fermat numbers.*/ -parse arg n . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 9 /*Not specified? Then use the default.*/ -numeric digits 20 /*ensure enough decimal digits, for n=9*/ - - do j=0 to n; f= 2** (2**j) + 1 /*calculate a series of Fermat numbers.*/ - say right('F'j, length(n) + 1)': ' f /*display a particular " " */ - end /*j*/ -say - do k=0 to n; f= 2** (2**k) + 1; say /*calculate a series of Fermat numbers.*/ - say center(' F'k": " f' ', 79, "═") /*display a particular " " */ - p= factr(f) /*factor a Fermat number, given time. */ - if words(p)==1 then say f ' is prime.' - else say 'factors: ' p - end /*k*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -factr: procedure; parse arg x 1 z,,? - do k=1 to 11 by 2; j= k; if j==1 then j= 2; if j==9 then iterate - call build /*add J to the factors list. */ - end /*k*/ /* [↑] factor X with some low primes*/ - - do y=0 by 2; j= j + 2 + y // 4 /*ensure not ÷ by three. */ - parse var j '' -1 _; if _==5 then iterate /*last digit a "5"? Skip it.*/ - if j*j>x | j>z then leave - call build /*add Y to the factors list. */ - end /*y*/ /* [↑] factor X with other higher #s*/ - j= z - if z\==1 then ?= build() - if ?='' then do; @.1= x; ?= x; #= 1; end - return ? -/*──────────────────────────────────────────────────────────────────────────────────────*/ -build: do while z//j==0; z= z % j; ?= ? j; end; return strip(?) diff --git a/Task/Fermat-numbers/REXX/fermat-numbers-2.rexx b/Task/Fermat-numbers/REXX/fermat-numbers-2.rexx deleted file mode 100644 index 1d23ec4428..0000000000 --- a/Task/Fermat-numbers/REXX/fermat-numbers-2.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program to find and display Fermat numbers, and show factors of Fermat numbers.*/ -parse arg n . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 9 /*Not specified? Then use the default.*/ -numeric digits 200 /*ensure enough decimal digits, for n=9*/ - - do j=0 to n; f= 2** (2**j) + 1 /*calculate a series of Fermat numbers.*/ - say right('F'j, length(n) + 1)': ' f /*display a particular " " */ - end /*j*/ -say - do k=5 to n; f= 2** (2**k) + 1; say /*calculate a series of Fermat numbers.*/ - say center(' F'k": " f' ', 79, "═") /*display a particular " " */ - a= rho(f) /*factor a Fermat number, given time. */ - b= f % a - if a==b then say f ' is prime.' - else say 'factors: ' commas(a) " " commas(b) - end /*k*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -rho: procedure; parse arg n; y= 2; d= 1 /*initialize X, Y, and D variables.*/ - do x=2 until d==n /*try rho method with X=2 for 1st time.*/ - do while d==1 - x= (x*x + 1) // n - v= (y*y + 1) // n - y= (v*v + 1) // n - parse value x-y with xy 1 sig 2 /*obtain sign of the x-y difference. */ - if sig=='-' then parse var xy 2 xy /*Negative? Then use absolute value. */ - nn= n - do until nn==0 - parse value xy//nn nn with nn xy /*assign two variables: NN and XY */ - end /*until*/ /*this is an in-line GCD function. */ - d= xy /*assign variable D with a new XY */ - end /*while*/ - end /*x*/ - return d /*found a factor of N. Return it.*/ diff --git a/Task/Fermat-numbers/REXX/fermat-numbers-3.rexx b/Task/Fermat-numbers/REXX/fermat-numbers.rexx similarity index 78% rename from Task/Fermat-numbers/REXX/fermat-numbers-3.rexx rename to Task/Fermat-numbers/REXX/fermat-numbers.rexx index 7cee294fbe..14cec3f2bb 100644 --- a/Task/Fermat-numbers/REXX/fermat-numbers-3.rexx +++ b/Task/Fermat-numbers/REXX/fermat-numbers.rexx @@ -1,8 +1,10 @@ +-- 22 Mar 2025 include Settings +say 'FERMAT NUMBERS' +say version +say numeric digits 200 -say 'Fermat numbers - Using REXX libraries' -parse version version; say version; say do i = 0 to 9 p = 2**(2**i)+1; l = Length(p) say 'Fermat number' i',' p',' l 'digits' @@ -13,13 +15,13 @@ do i = 0 to 9 else do call Charout ,'has factors ' do j = 1 to f - call Charout, fact.factor.j' ' + call Charout, fact.j' ' end say end end else do - if IsPrime(p) then + if Prime(p) then say 'is prime' else say 'is composite, but could not be factorized' @@ -30,5 +32,6 @@ say Format(Time('e'),,3) 'seconds'; say exit include Functions +include Sequences include Numbers include Abend diff --git a/Task/Fibonacci-n-step-number-sequences/EasyLang/fibonacci-n-step-number-sequences.easy b/Task/Fibonacci-n-step-number-sequences/EasyLang/fibonacci-n-step-number-sequences.easy index 8c3fd4bc20..7692027866 100644 --- a/Task/Fibonacci-n-step-number-sequences/EasyLang/fibonacci-n-step-number-sequences.easy +++ b/Task/Fibonacci-n-step-number-sequences/EasyLang/fibonacci-n-step-number-sequences.easy @@ -1,4 +1,4 @@ -proc sequ n$ val[] n . . +proc sequ n$ val[] n . write n$ & ": " il = len val[] len val[] n @@ -7,9 +7,7 @@ proc sequ n$ val[] n . . val[i] += val[i - j] . . - for v in val[] - write v & " " - . + for v in val[] : write v & " " print "" . sequ "Fibonacci" [ 1 1 ] 10 diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl index 030afc8adc..d9b4d1971d 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl @@ -1 +1 @@ -fib←{⍵≤1:⍵ ⋄ (∇ ⍵-1)+∇ ⍵-2} +fib←{⍵≤1:⍵ ⋄ (+/∇¨⍵-1 2} diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl index 5b4caf7c2d..aa0e04498d 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl @@ -1 +1 @@ -↑+.×/N/⊂2 2⍴1 1 1 0 +fib←{⍵≤1:⍵ ⋄ (∇⍵-1)+∇⍵-2} diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.apl index a30ddaceb7..5b4caf7c2d 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.apl @@ -1 +1 @@ -↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0 +↑+.×/N/⊂2 2⍴1 1 1 0 diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl index 3eff61d5ef..a30ddaceb7 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl @@ -1 +1 @@ -⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5 +↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0 diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-5.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-5.apl new file mode 100644 index 0000000000..3eff61d5ef --- /dev/null +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-5.apl @@ -0,0 +1 @@ +⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5 diff --git a/Task/Fibonacci-sequence/K/fibonacci-sequence-1.k b/Task/Fibonacci-sequence/K/fibonacci-sequence-1.k index 8816e02a00..cfdc75791e 100644 --- a/Task/Fibonacci-sequence/K/fibonacci-sequence-1.k +++ b/Task/Fibonacci-sequence/K/fibonacci-sequence-1.k @@ -1 +1 @@ -{:[x<3;1;_f[x-1]+_f[x-2]]} +{:[x<3;1;+/_f'x-1 2]} diff --git a/Task/Fibonacci-sequence/K/fibonacci-sequence-2.k b/Task/Fibonacci-sequence/K/fibonacci-sequence-2.k index 31a7786133..8b96d92fc1 100644 --- a/Task/Fibonacci-sequence/K/fibonacci-sequence-2.k +++ b/Task/Fibonacci-sequence/K/fibonacci-sequence-2.k @@ -1 +1 @@ -{c::.();{v:c[a:`$$x];:[x<3;1;:[_n~v;c[a]:_f[x-1]+_f[x-2];v]]}x} +{c::.();{v:c[a:`$$x];:[x<3;1;_n~v;c[a]:+/_f'x-1 2;v]}x} diff --git a/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl b/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl new file mode 100644 index 0000000000..cf6cfb7837 --- /dev/null +++ b/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl @@ -0,0 +1,31 @@ +%newline { [ LIT2 0a -Console/write ] DEO } + +|18 @Console/write + +|100 + +#1400 +&loop + DUP #00 SWP fibonacci print/dec newline + INC GTHk ?&loop +POP2 + +BRK + +@fibonacci ( n* -- n!* ) + ORAk ?{ JMP2r } + ORAk #01 NEQ ?{ JMP2r } + DUP2 #0001 SUB2 fibonacci STH2 + #0002 SUB2 fibonacci + STH2r ADD2 + JMP2r + +@print/dec ( short* -- ) + #000a SWP2 [ LITr ff ] + &get ( -- ) + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?&get + POP2 POP2 + &put ( -- ) + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !&put diff --git a/Task/Fibonacci-sequence/Zig/fibonacci-sequence.zig b/Task/Fibonacci-sequence/Zig/fibonacci-sequence.zig new file mode 100644 index 0000000000..24574a0e56 --- /dev/null +++ b/Task/Fibonacci-sequence/Zig/fibonacci-sequence.zig @@ -0,0 +1,14 @@ +const std = @import("std"); + +pub fn main() !void { + var a: u32 = 1; + var b: u32 = 1; + const target: u32 = 48; + + for (3..target + 1) |n| { + const fib = a + b; + std.debug.print("F({}) = {}\n", .{n, fib}); + a = b; + b = fib; + } +} diff --git a/Task/Fibonacci-word/EasyLang/fibonacci-word.easy b/Task/Fibonacci-word/EasyLang/fibonacci-word.easy index f5bd61d5f4..a92d11b1db 100644 --- a/Task/Fibonacci-word/EasyLang/fibonacci-word.easy +++ b/Task/Fibonacci-word/EasyLang/fibonacci-word.easy @@ -3,9 +3,7 @@ func log2 x . . func entropy s$ . l = len s$ - if l <= 1 - return 0 - . + if l <= 1 : return 0 for v$ in strchars s$ cnt0 += if v$ = "0" . @@ -27,7 +25,7 @@ func$ fibword . swap a$ b$ return b$ . -numfmt 6 8 +numfmt 8 6 print " n length entropy" print " ——————————————————————" for n to 37 diff --git a/Task/File-extension-is-in-extensions-list/C-sharp/file-extension-is-in-extensions-list.cs b/Task/File-extension-is-in-extensions-list/C-sharp/file-extension-is-in-extensions-list.cs new file mode 100644 index 0000000000..dcbbeee683 --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/C-sharp/file-extension-is-in-extensions-list.cs @@ -0,0 +1,20 @@ +List extensions = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2", ]; + +List tests = [ + "MyData.a##", + "MyData.tar.Gz", + "MyData.gzip", + "MyData.7z.backup", + "MyData...", + "MyData", + "MyData_v1.0.tar.bz2", + "MyData_v1.0.bz2", + ]; + +foreach (var filename in tests) +{ + Console.WriteLine($"{filename,20} {IsInList(filename, extensions)}"); +} + +static bool IsInList(string filename, List extensions) => + extensions.Any(e => filename.ToLowerInvariant().EndsWith("." + e.ToLowerInvariant())); diff --git a/Task/File-extension-is-in-extensions-list/M2000-Interpreter/file-extension-is-in-extensions-list.m2000 b/Task/File-extension-is-in-extensions-list/M2000-Interpreter/file-extension-is-in-extensions-list.m2000 new file mode 100644 index 0000000000..744022303d --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/M2000-Interpreter/file-extension-is-in-extensions-list.m2000 @@ -0,0 +1,35 @@ +module File_extension_is_in_extensions_list { + extensions=List:="zip","rar", "7z","gz", "archive", "a##" + filenames=("MyData.a##", "MyData.tar.gz", "MyData.gzip", "MyData.7z.backup", "MyData...", "MyData") + scanExtensions(each(filenames)) + + ' extra + Append extensions, "tar.bz2" + extra_filenames=("MyData_v1.0.tar.bz2", "MyData_v1.0.bz2") + scanExtensions(each(extra_filenames)) + + sub scanExtensions(m) + local b as boolean, ext, n + while m + ext=@possible_extensions(array$(m)) + n=each(ext) + b=false + while n + b=exist(extensions, array$(n)) + if b then exit + end while + Print array$(m), b + end while + end sub + function possible_extensions(a as string) + stack new { + local string k=rightpart$(a,".") + do + data lcase$(k) + k=rightpart$(k,".") + until k="" + =array([]) + } + end function +} +File_extension_is_in_extensions_list diff --git a/Task/File-extension-is-in-extensions-list/Nu/file-extension-is-in-extensions-list.nu b/Task/File-extension-is-in-extensions-list/Nu/file-extension-is-in-extensions-list.nu new file mode 100644 index 0000000000..f02f36a2d8 --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/Nu/file-extension-is-in-extensions-list.nu @@ -0,0 +1,20 @@ +let exts = ["zip" "rar" "7z" "gz" "archive" "A##" "tar.bz2"] +let filenames = [ + "MyData.a##" + "MyData.tar.Gz" + "MyData.gzip" + "MyData.7z.backup" + "MyData..." + "MyData" + "MyData_v1.0.tar.bz2" + "MyData_v1.0.bz2" +] + +$exts | wrap "extensions" + +$filenames | each { |filename| + let check = ($exts | any { |ext| + ($filename | str downcase) | str ends-with ("." + ($ext | str downcase)) + }) + $"($filename | fill -w 20 -c ' ') ($check)" +} | print diff --git a/Task/File-size-distribution/Nu/file-size-distribution.nu b/Task/File-size-distribution/Nu/file-size-distribution.nu new file mode 100644 index 0000000000..653f8186bb --- /dev/null +++ b/Task/File-size-distribution/Nu/file-size-distribution.nu @@ -0,0 +1,24 @@ + [d:/work d:/drivers d:/images ] | each { ls ($"($in)/**/*" | into glob) | + each { |it| + let size = ($it.size | into int) + { + name: $it.name + size: $size + SizeCategory: (match $size { + 0..1_000 => "Under 1 KB" + 1_001..5_000 => "1 KB 5 KB" + 5_001..10_000 => "5 KB 10 KB" + 10_001..25_000 => "10 KB to 25 KB" + 25_001..50_000 => "25 KB to 50 KB" + 50_001..1_000_000 => "50 KB to 1 MB" + 1_000_001..5_000_000 => "1 MB to 5 MB" + 5_000_001..10_000_000 => "5 MB to 10 MB" + 10_000_001..25_000_000 => "10 MB to 25 MB" + 25_000_001..50_000_000 => "25 MB to 50 MB" + 50_000_001..100_000_000 => "50 MB to 100 MB" + 100_000_001..500_000_000 => "100 MB to 500 MB" + 500_000_001..1_000_000_000 => "500 MB to 1 GB" + 1_000_000_001..3_000_000_000 => "1 GB to 3 GB" + _ => "Over 3 GB" + }) + } } } | flatten | histogram SizeCategory diff --git a/Task/File-size-distribution/Tcl/file-size-distribution-1.tcl b/Task/File-size-distribution/Tcl/file-size-distribution-1.tcl new file mode 100644 index 0000000000..8739c0547e --- /dev/null +++ b/Task/File-size-distribution/Tcl/file-size-distribution-1.tcl @@ -0,0 +1,75 @@ +#!/usr/bin/env tclsh + +# table/count of size categories +# (numbers are both strings and numbers) +# ''sizes(100)'' is the array member ''sizes("100")'' + +array set sizes { + 0 0 + 100 0 + 1000 0 + 10000 0 + 100000 0 + 1000000 0 + 10000000 0 + 100000000 0 + 1000000000 0 +} + +# sorted list of keys +set keys [lsort -integer [array names sizes]] + +# check size and update count +proc count {f} { + variable sizes + variable keys + + #size in bytes of file + set size [file size $f] + + # increment count + foreach { v } $keys { + if {$size <= $v} {incr sizes($v) ; break} + } +} + +#recursive file name glob +proc getfiles {f} { + + if { [file isfile $f] } { + + # function call + count $f + } elseif { [file isdirectory $f] } { + + set files [glob -nocomplain [file join $f *]] + + # recursive call + foreach d $files { getfiles $d } + + } else { + return + } +} + + +# main +if { [info script] eq $::argv0 } { + + if { $::argc eq 0 } { + puts stderr "need a dir to start searching" + return 1 + } + + foreach dir $::argv { + getfiles $dir + + foreach v $keys { + puts "$v : \t$sizes($v)" + } + } + + return 0 +} + +# end diff --git a/Task/File-size-distribution/Tcl/file-size-distribution.tcl b/Task/File-size-distribution/Tcl/file-size-distribution-2.tcl similarity index 100% rename from Task/File-size-distribution/Tcl/file-size-distribution.tcl rename to Task/File-size-distribution/Tcl/file-size-distribution-2.tcl diff --git a/Task/Find-Chess960-starting-position-identifier/D/find-chess960-starting-position-identifier.d b/Task/Find-Chess960-starting-position-identifier/D/find-chess960-starting-position-identifier.d new file mode 100644 index 0000000000..ea3eb5a62a --- /dev/null +++ b/Task/Find-Chess960-starting-position-identifier/D/find-chess960-starting-position-identifier.d @@ -0,0 +1,83 @@ +import std.stdio : writeln, writefln; +import std.array : split; +import std.range : join; + +string genChess960Position(int id) { + string[] pos = new string[8]; + + int q = id / 4; + int r = id % 4; + + pos[r * 2 + 1] = "B"; // <<< + + q /= 4; + r = q % 4; + + pos[r * 2] = "B"; // <<< + + q /= 6; + r = q % 6; + + int i = 0; + foreach (j; 0 .. 8) { + if (pos[j] is null) { + if (i == r) { + i = j; + break; + } + i++; + } + } + + pos[i] = "Q"; // <<< + + //////////////////// + + string[] krn = [ + "NNRKR", "NRNKR", "NRKNR", "NRKRN", + "RNNKR", "RNKNR", "RNKRN", + "RKNNR", "RKNRN", + "RKRNN" + ]; + + string krnString = krn[q]; + auto krnChars = krnString.split(""); // <<< + + i = 0; + foreach (j; 0 .. 8) { + if (pos[j] is null) { + pos[j] = krnChars[i++]; // <<< + } + } + + //////////////////// + + return pos.join(""); +} + +void main() { + writeln; + + writeln("Chess960 Position List by SP-ID"); + writeln; + + foreach (id; 0..3+1) { + writefln("%3s : %s", id, genChess960Position(id)); + } + + "... ........".writeln; + writeln; + + foreach (id; [518]) { + writefln("%3s : %s", id, genChess960Position(id)); + } + + "... ........".writeln; + writeln; + + foreach (id; 956..959+1) { + writefln("%3s : %s", id, genChess960Position(id)); + } + + writeln; +} diff --git a/Task/Find-common-directory-path/BQN/find-common-directory-path.bqn b/Task/Find-common-directory-path/BQN/find-common-directory-path.bqn new file mode 100644 index 0000000000..559c792f19 --- /dev/null +++ b/Task/Find-common-directory-path/BQN/find-common-directory-path.bqn @@ -0,0 +1,9 @@ +LongestPath ← {∾⟜𝕨⊸∾´ ⊑¨{1⊸+⌈´/≤⟜1¨≠¨𝕩}⊸↑ ⍷¨⥊⋈˘ ⍉> ⌊´∘(≠¨)⊸(↑¨) 𝕨⊸((+`׬)⊸-∘= ⊔ ⊢)¨ 𝕩} + +dirs ← ⟨ + "/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members", +⟩ + +•Show '/' LongestPath dirs diff --git a/Task/Find-if-a-point-is-within-a-triangle/C-sharp/find-if-a-point-is-within-a-triangle.cs b/Task/Find-if-a-point-is-within-a-triangle/C-sharp/find-if-a-point-is-within-a-triangle.cs new file mode 100644 index 0000000000..f98f097d18 --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/C-sharp/find-if-a-point-is-within-a-triangle.cs @@ -0,0 +1,90 @@ +using System.Numerics; + +Point a = new(new(1, 10), new(1, 9)); // 0.1, 0.1111... +Point b = new(12.5, new(100, 3)); // 12.5, 33.3333... +Point c = new(25, new(100, 9)); // 25, 11.1111... + +// Test a point on the boundary (supposedly fails with double-precision) +Point test = (4 * a + 3 * b) / 7; +test.IsInTriangle(a, b, c); + +// Other examples +a = new(1.5, 2.4); b = new(5.1, -3.1); c = new(-3.8, 1.2); +new Point(0, 0).IsInTriangle(a, b, c); +new Point(0, 1).IsInTriangle(a, b, c); +new Point(3, 1).IsInTriangle(a, b, c); + +record Point(Rational X, Rational Y) +{ + public static Point operator +(Point a, Point b) => new(a.X + b.X, a.Y + b.Y); + public static Point operator -(Point a, Point b) => new(a.X - b.X, a.Y - b.Y); + public static Point operator *(int s, Point p) => new(s * p.X, s * p.Y); + public static Point operator /(Point p, int s) => new(p.X / s, p.Y / s); + public override string ToString() => $"({X}, {Y})"; + + public Rational Det(Point other) => X * other.Y - Y * other.X; + + public bool IsInTriangle(Point a, Point b, Point c) + { + var v1 = b - a; + var v2 = c - a; + var d = v1.Det(v2); + var t = (Det(v2) - a.Det(v2)) / d; + var u = (a.Det(v1) - Det(v1)) / d; + var inside = t >= 0 && u >= 0 && 1 >= t + u; + Console.WriteLine($"{this} in {a}, {b}, {c} = {inside}"); + return inside; + } +} + +readonly struct Rational +{ + public readonly BigInteger n, d; + + public Rational(BigInteger n, BigInteger d) + { + var g = BigInteger.GreatestCommonDivisor(n, d) * d.Sign; + this.n = n / g; this.d = d / g; + } + + public static implicit operator Rational(int n) => new(n, 1); + public static implicit operator Rational(BigInteger n) => new(n, 1); + public static Rational operator +(Rational x, Rational y) => new(x.n * y.d + y.n * x.d, x.d * y.d); + public static Rational operator -(Rational x) => new(-x.n, x.d); + public static Rational operator -(Rational x, Rational y) => new(x.n * y.d - y.n * x.d, x.d * y.d); + public static Rational operator *(Rational x, Rational y) => new(x.n * y.n, x.d * y.d); + public static Rational operator /(Rational x, Rational y) => new(x.n * y.d, x.d * y.n); + public static bool operator >=(Rational x, Rational y) => x.n * y.d >= y.n * x.d; + public static bool operator <=(Rational x, Rational y) => x.n * y.d <= y.n * x.d; + public override readonly string ToString() => n == 0 ? "0" : d == 1 ? $"{n}" : $"{n}/{d}"; + + public static implicit operator Rational(double d) + { + if (d == 0.0) + return 0; + + long n = BitConverter.DoubleToInt64Bits(d); + bool negative = n < 0; + int exp = (int)(n >> 52) & 0x7FF; + long mantissa = n & 0xFFFFFFFFFFFFF; + + if (exp == 0) + { + exp = -1022; + } + else + { + mantissa |= 0x10000000000000; + exp -= 1023; + } + + exp -= 52; + long numerator = mantissa; + if (negative) numerator = -numerator; + + if (exp >= 0) + return new(numerator << exp, 1); + + return new(numerator, BigInteger.Pow(2, -exp)); + } +} diff --git a/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy b/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy index f57bc5c2a7..fd50ebd786 100644 --- a/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy +++ b/Task/Find-if-a-point-is-within-a-triangle/EasyLang/find-if-a-point-is-within-a-triangle.easy @@ -14,20 +14,21 @@ func isin px py ax ay bx by cx cy . z3 = sgn px py cx cy ax ay return if abs (z1 + z2 + z3) = 3 . -move 5 90 -textsize 4 -text "Move mouse into the triangle" -color 444 -polygon [ ax ay bx by cx cy ] +proc drawpoly in . + if in = 1 + gcolor 822 + else + gcolor 444 + . + gpolygon [ ax ay bx by cx cy ] +. +gtextsize 4 +gtext 5 90 "Move mouse into the triangle" +drawpoly 0 # on mouse_move if isin mouse_x mouse_y ax ay bx by cx cy <> in in = 1 - in - if in = 1 - color 822 - else - color 444 - . - polygon [ ax ay bx by cx cy ] + drawpoly in . . diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/REXX/find-largest-left-truncatable-prime-in-a-given-base.rexx b/Task/Find-largest-left-truncatable-prime-in-a-given-base/REXX/find-largest-left-truncatable-prime-in-a-given-base.rexx index 3f7aeeeb82..b943603212 100644 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/REXX/find-largest-left-truncatable-prime-in-a-given-base.rexx +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/REXX/find-largest-left-truncatable-prime-in-a-given-base.rexx @@ -1,6 +1,8 @@ include Settings -say version; say 'Left truncatable primes'; say +say 'LEFT TRUNCATABLE PRIME IN GIVEN BASE - 4 Mar 2025' +say version +say numeric digits 100; work. = 0 bases = '3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 19 21 23 25' do i = 1 to Words(bases) @@ -16,7 +18,7 @@ end say Words(bases) 'bases specified' say work.cycle 'digit cycles needed' say work.count 'numbers tested for primality' -say work.prime 'of them were actually prime' +say work.Prime 'of them were actually prime' say Format(Time('e'),,3) 'seconds' exit @@ -61,8 +63,8 @@ do i = 1 to work.in.0 a = work.in.i; b = x**work.digit do j = 1 to x-1 work.count = work.count+1; c = a+b*j - if Isprime(c) then do - work.prime = work.prime+1; n = n+1; work.out.n = c + if Prime(c) then do + work.Prime = work.Prime+1; n = n+1; work.out.n = c end end end diff --git a/Task/Find-limit-of-recursion/Ballerina/find-limit-of-recursion.ballerina b/Task/Find-limit-of-recursion/Ballerina/find-limit-of-recursion.ballerina new file mode 100644 index 0000000000..4415411d3b --- /dev/null +++ b/Task/Find-limit-of-recursion/Ballerina/find-limit-of-recursion.ballerina @@ -0,0 +1,10 @@ +import ballerina/io; + +function func(int n) { + io:println(n); + func(n + 1); +} + +public function main() { + func(1); +} diff --git a/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy b/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy index 050dea43eb..88bb3196a6 100644 --- a/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy +++ b/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy @@ -1,7 +1,5 @@ -proc recurse i . . - if i mod 10 = 0 - print i - . +proc recurse i . + if i mod 10 = 0 : print i recurse i + 1 . recurse 1 diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/EasyLang/find-palindromic-numbers-in-both-binary-and-ternary-bases.easy b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/EasyLang/find-palindromic-numbers-in-both-binary-and-ternary-bases.easy index 06db655d11..9838c747d2 100644 --- a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/EasyLang/find-palindromic-numbers-in-both-binary-and-ternary-bases.easy +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/EasyLang/find-palindromic-numbers-in-both-binary-and-ternary-bases.easy @@ -4,9 +4,7 @@ fastfunc ispalin2 n . x = x * 2 + m mod 2 m = m div 2 . - if n = x - return 1 - . + if n = x : return 1 . fastfunc reverse3 n . while n > 0 @@ -16,11 +14,10 @@ fastfunc reverse3 n . return r . func$ itoa n b . - if n > 0 - return itoa (n div b) b & n mod b - . + if n > 0 : return itoa (n div b) b & n mod b + return "" . -proc main . . +proc main . print "0 0(2) 0(3)" print "1 1(2) 1(3)" pow3 = 3 @@ -31,9 +28,7 @@ proc main . . if ispalin2 n = 1 print n & " " & itoa n 2 & "(2) " & itoa n 3 & "(3)" cnt += 1 - if cnt = 6 - 2 - return - . + if cnt = 6 - 2 : return . . pow3 *= 3 diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/R/find-palindromic-numbers-in-both-binary-and-ternary-bases.r b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/R/find-palindromic-numbers-in-both-binary-and-ternary-bases.r new file mode 100644 index 0000000000..b95dbfbd60 --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/R/find-palindromic-numbers-in-both-binary-and-ternary-bases.r @@ -0,0 +1,82 @@ +require(stringi) + +base2 <- function(x){ + y <- integer(0) + while(x >= 2){ + r <- x %% 2 + x <- x %/% 2 + y <- c(r, y) + } + y <- c(x, y) + gsub(", ", "", toString(y)) +} + +base3 <- function(x){ + y <- integer(0) + while(x >= 3){ + r <- x %% 3 + x <- x %/% 3 + y <- c(r, y) + } + y <- c(x, y) + gsub(", ", "", toString(y)) +} + +# note: no check if input is legitimate base 3 number +base_3_to_base_10 <- function(base_3_number) { + place <- 0 + multiplier <- 1 + base_10_total <- 0 + base_3_number_as_list <- rev(number_to_list(base_3_number)) + for (one_number in base_3_number_as_list) { + base_10_total <- base_10_total + (one_number * multiplier) + place <- place + 1 + multiplier <- 3 ^ place + } + return(base_10_total) +} + +number_to_list <- function(input_number){ + string_number <- toString(input_number) + list_of_strings <- strsplit(string_number, NULL) + integer_list <- list() + for (one_string in list_of_strings) { + one_integer <- as.integer(one_string) + integer_list <- append(one_integer, integer_list) + } + return(integer_list) +} + +is_palindrome <- function(string) { + backwards <- stri_reverse(string) + identical(backwards, string) +} + +base_3_to_base_2 <- function(base_3_number) { + base_10_number <- base_3_to_base_10(base_3_number) + base_2_number_string <- base2(base_10_number) + return(base_2_number_string) +} + +list_first_2 <- function() { + cat(0, 0, 0, "\n") + cat(1, 1, 1, "\n") +} + +palindromes_in_base_2_and_base_3 <- function(number) { + list_first_2() + number <- number - 2 + count <- 1 + partial_base_number <- 1 + while (count <= number) { + partial_base_3 <- base3(partial_base_number) + full_base_3_string <- paste0 (partial_base_3, "1", stri_reverse (as.character(partial_base_3))) + base2_number <- base_3_to_base_2(full_base_3_string) + if (is_palindrome(base2_number)) { + base10_number <- base_3_to_base_10(full_base_3_string) + cat(base10_number, base2_number, full_base_3_string, "\n") + count <- count + 1 + } + partial_base_number <- partial_base_number + 1 + } +} diff --git a/Task/Find-the-intersection-of-a-line-with-a-plane/EasyLang/find-the-intersection-of-a-line-with-a-plane.easy b/Task/Find-the-intersection-of-a-line-with-a-plane/EasyLang/find-the-intersection-of-a-line-with-a-plane.easy index 9ece60947b..44221e29fe 100644 --- a/Task/Find-the-intersection-of-a-line-with-a-plane/EasyLang/find-the-intersection-of-a-line-with-a-plane.easy +++ b/Task/Find-the-intersection-of-a-line-with-a-plane/EasyLang/find-the-intersection-of-a-line-with-a-plane.easy @@ -1,30 +1,23 @@ -proc minus . l[] r[] res[] . - len res[] 3 - for i to 3 - res[i] = l[i] - r[i] - . +func[] minus &l[] &r[] . + for i to 3 : res[] &= l[i] - r[i] + return res[] . func dot l[] r[] . - for i to 3 - res += l[i] * r[i] - . + for i to 3 : res += l[i] * r[i] return res . -proc scale f . l[] . - for i to 3 - l[i] = l[i] * f - . +proc scale &l[] f . + for i to 3 : l[i] = l[i] * f . -proc inter_point rv[] rp[] pn[] pp[] . res[] . - minus rp[] pp[] dif[] +func[] inter_point &rv[] &rp[] &pn[] &pp[] . + dif[] = minus rp[] pp[] prd1 = dot dif[] pn[] prd2 = dot rv[] pn[] - scale (prd1 / prd2) rv[] - minus rp[] rv[] res[] + scale rv[] (prd1 / prd2) + return minus rp[] rv[] . rv[] = [ 0.0 -1.0 -1.0 ] rp[] = [ 0.0 0.0 10.0 ] pn[] = [ 0.0 0.0 1.0 ] pp[] = [ 0.0 0.0 5.0 ] -inter_point rv[] rp[] pn[] pp[] res[] -print res[] +print inter_point rv[] rp[] pn[] pp[] diff --git a/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy b/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy index 167f357dd3..af44525c32 100644 --- a/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy +++ b/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy @@ -1,21 +1,11 @@ -proc intersect ax1 ay1 ax2 ay2 bx1 by1 bx2 by2 . rx ry . - rx = 1 / 0 - ry = 1 / 0 +func[] intersect ax1 ay1 ax2 ay2 bx1 by1 bx2 by2 . d = (by2 - by1) * (ax2 - ax1) - (bx2 - bx1) * (ay2 - ay1) - if d = 0 - return - . + if d = 0 : return [ 1 / 0 1 / 0 ] ua = ((bx2 - bx1) * (ay1 - by1) - (by2 - by1) * (ax1 - bx1)) / d ub = ((ax2 - ax1) * (ay1 - by1) - (by2 - by1) * (ax1 - bx1)) / d - if abs ua > 1 or abs ub > 1 - return - . - rx = ax1 + ua * (ax2 - ax1) - ry = ay1 + ua * (ay2 - ay1) + if abs ua > 1 or abs ub > 1 : return [ 1 / 0 1 / 0 ] + return [ ax1 + ua * (ax2 - ax1) ay1 + ua * (ay2 - ay1) ] . -intersect 4 0 6 10 0 3 10 7 rx ry -print rx & " " & ry -intersect 4 0 6 10 0 3 10 7.1 rx ry -print rx & " " & ry -intersect 0 0 1 1 1 2 4 5 rx ry -print rx & " " & ry +print intersect 4 0 6 10 0 3 10 7 +print intersect 4 0 6 10 0 3 10 7.1 +print intersect 0 0 1 1 1 2 4 5 diff --git a/Task/Find-the-last-Sunday-of-each-month/EasyLang/find-the-last-sunday-of-each-month.easy b/Task/Find-the-last-Sunday-of-each-month/EasyLang/find-the-last-sunday-of-each-month.easy index e98f0923a4..c8d5ea7ea5 100644 --- a/Task/Find-the-last-Sunday-of-each-month/EasyLang/find-the-last-sunday-of-each-month.easy +++ b/Task/Find-the-last-Sunday-of-each-month/EasyLang/find-the-last-sunday-of-each-month.easy @@ -5,18 +5,14 @@ func wkday year month day . r = day + (13 * mm - 1) div 5 + yy + yy div 4 - yy div 100 + yy div 400 return r mod 7 + 1 . -proc show y . . +proc show y . days[] = [ 31 28 31 30 31 30 31 31 30 31 30 31 ] days[2] += if y mod 4 = 0 and (y mod 100 <> 0 or y mod 400 = 0) for m = 1 to 12 d = days[m] - while wkday y m d <> 1 - d -= 1 - . + while wkday y m d <> 1 : d -= 1 m$ = m - if m < 10 - m$ = 0 & m - . + if m < 10 : m$ = 0 & m print y & "-" & m$ & "-" & d . . diff --git a/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy b/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy index 86a7c5c24e..351a114673 100644 --- a/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy +++ b/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy @@ -1,24 +1,18 @@ -perms$[] = [ "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ] -n = len perms$[1] -len cnt[] n -# -nn = 1 -for i to n - 1 - nn *= i -. -for i to 4 - for j to n - cnt[j] = 0 - . - for s$ in perms$[] - cod = strcode substr s$ i 1 - 64 - cnt[cod] += 1 - . - for j to n - if cnt[j] <> nn - miss$ &= strchar (j + 64) - break 1 +func$ missing perms$[] . + n = len perms$[1] + len cnt[] n + nn = 1 + for i = 2 to n - 1 : nn *= i + for i to n + for j to n : cnt[j] = 0 + for s$ in perms$[] + cod = strcode substr s$ i 1 - 64 + cnt[cod] += 1 + . + for j to n + if cnt[j] <> nn : miss$ &= strchar (j + 64) . . + return miss$ . -print miss$ +print missing [ "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ] diff --git a/Task/Find-the-missing-permutation/Zig/find-the-missing-permutation.zig b/Task/Find-the-missing-permutation/Zig/find-the-missing-permutation.zig new file mode 100644 index 0000000000..dcdaf7be86 --- /dev/null +++ b/Task/Find-the-missing-permutation/Zig/find-the-missing-permutation.zig @@ -0,0 +1,39 @@ +const std = @import("std"); + +pub fn main() !void { + const N: usize = 4; + const perms = [_][]const u8{ + "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", + "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", + "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB", + }; + + // Calculate n = (N-1)!, the expected number of occurrences + var n: usize = 1; + var i: usize = 1; + while (i < N) : (i += 1) { + n *= i; + } + + var miss: [N]u8 = undefined; + var stdout = std.io.getStdOut().writer(); + + i = 0; + while (i < N) : (i += 1) { + var cnt = [_]usize{0} ** N; + + // Count how many times each letter occurs at position i + for (perms) |perm| { + const position = perm[i] - 'A'; + cnt[position] += 1; + } + + // Find letter not occurring (N-1)! times - that's the missing one + var j: usize = 0; + while (j < N and cnt[j] == n) : (j += 1) {} + + miss[i] = @as(u8, @intCast(j)) + 'A'; + } + + try stdout.print("Missing: {s}\n", .{miss}); +} diff --git a/Task/First-perfect-square-in-base-n-with-n-unique-digits/EasyLang/first-perfect-square-in-base-n-with-n-unique-digits.easy b/Task/First-perfect-square-in-base-n-with-n-unique-digits/EasyLang/first-perfect-square-in-base-n-with-n-unique-digits.easy index ca84da2be9..9323a7a527 100644 --- a/Task/First-perfect-square-in-base-n-with-n-unique-digits/EasyLang/first-perfect-square-in-base-n-with-n-unique-digits.easy +++ b/Task/First-perfect-square-in-base-n-with-n-unique-digits/EasyLang/first-perfect-square-in-base-n-with-n-unique-digits.easy @@ -1,8 +1,6 @@ alpha$ = "0123456789AB" func$ itoa n b . - if n > 0 - return itoa (n div b) b & substr alpha$ (n mod b + 1) 1 - . + if n > 0 : return itoa (n div b) b & substr alpha$ (n mod b + 1) 1 . func unique s$ . len dig[] 12 @@ -10,12 +8,10 @@ func unique s$ . ind = strpos alpha$ c$ dig[ind] = 1 . - for v in dig[] - cnt += v - . + for v in dig[] : cnt += v return cnt . -proc find b . . +proc find b . n = floor pow b ((b - 1) div 2) repeat sq = n * n diff --git a/Task/First-perfect-square-in-base-n-with-n-unique-digits/Fortran/first-perfect-square-in-base-n-with-n-unique-digits.f b/Task/First-perfect-square-in-base-n-with-n-unique-digits/Fortran/first-perfect-square-in-base-n-with-n-unique-digits.f new file mode 100644 index 0000000000..cc619f4a86 --- /dev/null +++ b/Task/First-perfect-square-in-base-n-with-n-unique-digits/Fortran/first-perfect-square-in-base-n-with-n-unique-digits.f @@ -0,0 +1,100 @@ +program perfect_squares + implicit none + integer :: base, i + integer(8) :: m, m_squared, base_power, start_m + character(len=:), allocatable :: m_str, square_str + logical :: found + + do base = 2, 16 + found = .false. + ! Calculate base^(base-1) for lower bound + base_power = 1_8 + do i = 1, base-1 + base_power = base_power * int(base, 8) + end do + ! Compute start_m as ceiling(sqrt(base_power)) + start_m = int(sqrt(real(base_power, kind=8)), kind=8) + if (start_m * start_m < base_power) start_m = start_m + 1_8 + ! Search until solution found (no upper limit) + do m = start_m, huge(1_8)-1 + m_squared = m * m + square_str = to_base(m_squared, base) + if (len(square_str) < base) cycle + if (is_valid_square(square_str, base)) then + m_str = to_base(m, base) + print "(A, I2, A, A,T25, A, A)", "Base ", base, " : Num ", trim(m_str), " Square ", trim(square_str) + found = .true. + exit + end if + end do + if (.not. found) print *, "No solution for base ", base + end do +contains +pure function to_base(n, base) result(str) + integer(8), intent(in) :: n + integer, intent(in) :: base + character(len=:), allocatable :: str + integer(8) :: tmp, bbase, rem + integer :: i, len + character(1) :: buffer(32) + character(1), parameter :: digits(16) = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] + + tmp = n + bbase = base + i = 0 + buffer = ' ' ! Initialize buffer to blanks + + do while (tmp > 0) + rem = mod(tmp, bbase) + i = i + 1 + buffer(i) = digits(rem+1) + tmp = tmp / bbase + end do + + if (i == 0) then +! allocate(str(1)) + str(1:1) = '0' + return + end if + + allocate(character(i) :: str) + do len = 1, i + str(len:len) = buffer(i - len + 1) + end do +end function to_base + +pure function is_valid_square(str, base) result(ok) + character(len=*), intent(in) :: str + integer, intent(in) :: base + logical :: ok + integer :: i, digit, ascii, seen, mask + integer, parameter :: char_to_digit(48:70) = [ & + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, & ! '0'–'9' + ( -1, i = 58, 64 ), & ! ':'–'@' + 10, 11, 12, 13, 14, 15 ] ! 'A'–'F' + + if (len(str) < base) then + ok = .false. + return + end if + + seen = 0 + do i = 1, len(str) + ascii = iachar(str(i:i)) + if (ascii < 48 .or. ascii > 70) then + ok = .false. + return + end if + digit = char_to_digit(ascii) + if (digit < 0 .or. digit >= base) then + ok = .false. + return + end if + seen = ibset(seen, digit) + end do + + mask = ishft(1, base) - 1 + ok = (seen == mask) +end function is_valid_square + +end program perfect_squares diff --git a/Task/First-power-of-2-that-has-leading-decimal-digits-of-12/EasyLang/first-power-of-2-that-has-leading-decimal-digits-of-12.easy b/Task/First-power-of-2-that-has-leading-decimal-digits-of-12/EasyLang/first-power-of-2-that-has-leading-decimal-digits-of-12.easy index 89d2853742..d4192c6672 100644 --- a/Task/First-power-of-2-that-has-leading-decimal-digits-of-12/EasyLang/first-power-of-2-that-has-leading-decimal-digits-of-12.easy +++ b/Task/First-power-of-2-that-has-leading-decimal-digits-of-12/EasyLang/first-power-of-2-that-has-leading-decimal-digits-of-12.easy @@ -9,13 +9,11 @@ func p l n . while n > 0 test += 1 val = floor (factor * pow 10 (test * log mod 1)) - if val = l - n -= 1 - . + if val = l : n -= 1 . return test . -proc test l n . . +proc test l n . print "p(" & l & ", " & n & ") = " & p l n . test 12 1 diff --git a/Task/Fivenum/Ballerina/fivenum.ballerina b/Task/Fivenum/Ballerina/fivenum.ballerina new file mode 100644 index 0000000000..75a66eb8cd --- /dev/null +++ b/Task/Fivenum/Ballerina/fivenum.ballerina @@ -0,0 +1,30 @@ +import ballerina/io; + +function fivenum(float[] arr) returns float[5] { + float[] a = arr.sort(); + float[5] n5 = []; + float n = a.length(); + float n4 = ((a.length() + 3) / 2) / 2.0; + float[] d = [1, n4, (n + 1) / 2, n + 1 - n4, n]; + foreach [int, float] [e, de] in d.enumerate() { + int floor = (de - 1.0).floor(); + int ceil = (de - 1.0).ceiling(); + n5[e] = 0.5 * (a[floor] + a[ceil]); + } + return n5; +} + +public function main() { + float[] x1 = [36, 40, 7, 39, 41, 15]; + float[] x2 = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43]; + float[] x3 = [ + 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, + 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, + 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, + 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578 + ]; + foreach var x in [x1, x2, x3] { + var res = fivenum(x); + io:println(re `,`.replaceAll(res.toString(), ", ")); + } +} diff --git a/Task/Fivenum/EasyLang/fivenum.easy b/Task/Fivenum/EasyLang/fivenum.easy index 910e2dc9be..2bcb5bc356 100644 --- a/Task/Fivenum/EasyLang/fivenum.easy +++ b/Task/Fivenum/EasyLang/fivenum.easy @@ -1,17 +1,13 @@ func median t[] low high . l = high - low + 1 m = low + l div 2 - if l mod 2 = 1 - return t[m] - . + if l mod 2 = 1 : return t[m] return (t[m - 1] + t[m]) / 2 . -proc sort . d[] . +proc sort &d[] . for i = 1 to len d[] - 1 for j = i + 1 to len d[] - if d[j] < d[i] - swap d[j] d[i] - . + if d[j] < d[i] : swap d[j] d[i] . . . diff --git a/Task/FizzBuzz/APL/fizzbuzz-1.apl b/Task/FizzBuzz/APL/fizzbuzz-1.apl index 9c4c983cb1..1e7e7de17d 100644 --- a/Task/FizzBuzz/APL/fizzbuzz-1.apl +++ b/Task/FizzBuzz/APL/fizzbuzz-1.apl @@ -1,2 +1,2 @@ -⎕IO←0 -(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100] +⎕io←1 +{⎕←∊'Fizz' 'Buzz'⍵/⍨d,⍱/d←0=3 5|⍵}¨⍳100 diff --git a/Task/FizzBuzz/APL/fizzbuzz-2.apl b/Task/FizzBuzz/APL/fizzbuzz-2.apl index e2fbf6f312..03ea88a223 100644 --- a/Task/FizzBuzz/APL/fizzbuzz-2.apl +++ b/Task/FizzBuzz/APL/fizzbuzz-2.apl @@ -1 +1 @@ -A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100] +{⍵ 'Fizz' 'Buzz' 'FizzBuzz'[2⊥0=5 3|⍵]}¨1+⍳100 diff --git a/Task/FizzBuzz/APL/fizzbuzz-3.apl b/Task/FizzBuzz/APL/fizzbuzz-3.apl index b6e7b109d0..aefe79e331 100644 --- a/Task/FizzBuzz/APL/fizzbuzz-3.apl +++ b/Task/FizzBuzz/APL/fizzbuzz-3.apl @@ -1 +1 @@ -{ ⍵ 'Fizz' 'Buzz' 'FizzBuzz'[ +/1 2×0=3 5|⍵] }¨1+⍳100 +{('FizzBuzz' 'Fizz' 'Buzz',⍵)[(0=15 3 5|⍵)⍳1]}¨⍳100 diff --git a/Task/FizzBuzz/APL/fizzbuzz-4.apl b/Task/FizzBuzz/APL/fizzbuzz-4.apl index 75e0fad7c0..c4b7ddd6e7 100644 --- a/Task/FizzBuzz/APL/fizzbuzz-4.apl +++ b/Task/FizzBuzz/APL/fizzbuzz-4.apl @@ -1 +1,2 @@ -{(‘FizzBuzz’ ‘Fizz’ ‘Buzz’,⍵)[(0=15 3 5|⍵)⍳1]}¨⍳100 +⎕IO←0 +A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ' 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100] diff --git a/Task/FizzBuzz/APL/fizzbuzz-5.apl b/Task/FizzBuzz/APL/fizzbuzz-5.apl index 21cc1d1b7c..fdd98bf784 100644 --- a/Task/FizzBuzz/APL/fizzbuzz-5.apl +++ b/Task/FizzBuzz/APL/fizzbuzz-5.apl @@ -1,40 +1,2 @@ - ∇ sv ← fizzbuzz n; t;d -[1] ⍝⍝ Solve the popular 'fizzbuzz' problem in APL. -[2] ⍝⍝ \param n - highest number to compute (≥0) -[3] ⍝⍝ \returns sv - a vector of strings representing the fizzbuzz solution for ⍳n -[4] ⍝⍝ (note we return a string vector to avoid a mixed-type result; remove the -[5] ⍝⍝ ⍕ function from the (⍕t[⍵]) term to see the difference). -[6] ⍝⍝⍝⍝ -[7] t←⍳n ⍝ the sequence 1..n itself which we'll pick from -[8] ⍝ ... or the words 'fizz', 'buzz', 'fizzbuzz' depending on -[9] ⍝ ... divisibility by 3 and/or 5 -[10] ⍝⎕←t ⍝ (Uncomment to see during call) -[11] -[12] d←1+(+⌿ ⊃ {((0=3|⍵)) (2×(0=5|⍵))} ⍳n) -[13] ⍝ || || | | | ↓↓ -[14] ⍝ || || | | | ⍳n: generate range (1..n) -[15] ⍝ || || | ↓.....................↓ ↓↓ -[16] ⍝ || || | A dfn (lambda) taking its right arg (⍵, ⍳n here) to compute two boolean -[17] ⍝ || || | vectors(v12): divisibility by 3 and 5, respectively, for each of ⍳n -[18] ⍝ || || ↓ -[19] ⍝ || || ⊃: Disclose ('lift-up' and pad w/zeros) the 'ragged' matrix of vectors (v12) -[20] ⍝ || || holding divisibility by 3 and 5 of each ⍳n -[21] ⍝ || ↓↓ -[22] ⍝ || +⌿: Sum (v12) row-wise to count divisibility (0=neither 3 nor 5, 1=3, 2=3 and 5) -[23] ⍝ ↓↓ -[24] ⍝ 1+: Add one to (v12) to make them 1-based for indexing below: -[25] ⍝⎕←d -[26] -[27] sv ← { ((⍕t[⍵]) 'Fizz' 'Buzz' 'FizzBuzz') [d[⍵]]}¨ ⍳n -[28] ⍝ | | | | | | -[29] ⍝ | | | ↓....↓ | -[30] ⍝ | |................................↓ idx | -[31] ⍝ | ( lookup output vector ) | -[32] ⍝ ↓...........................................↓ -[33] ⍝ A dfn (lambda) taking as its right arg (⍵) ⍳n and using the 'each' (¨) -[34] ⍝ operator to apply the lambda to each (idx) of ⍳n. -[35] -[36] ⍝⍝ USAGE -[37] ⍝⍝ ⎕ ← ,fizzbuzz 15 -[38] ⍝ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz - ∇ +⎕IO←0 +(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×0≠W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100] diff --git a/Task/FizzBuzz/APL/fizzbuzz-6.apl b/Task/FizzBuzz/APL/fizzbuzz-6.apl index 1e7e7de17d..9bdba7d172 100644 --- a/Task/FizzBuzz/APL/fizzbuzz-6.apl +++ b/Task/FizzBuzz/APL/fizzbuzz-6.apl @@ -1,2 +1,2 @@ -⎕io←1 -{⎕←∊'Fizz' 'Buzz'⍵/⍨d,⍱/d←0=3 5|⍵}¨⍳100 +⎕IO←0 +(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(100+W[I])@(I←⍸0≠W←⊃+/1 2×0=3 5|⊂L)⊢L←1+⍳100] diff --git a/Task/FizzBuzz/APL/fizzbuzz-7.apl b/Task/FizzBuzz/APL/fizzbuzz-7.apl new file mode 100644 index 0000000000..21cc1d1b7c --- /dev/null +++ b/Task/FizzBuzz/APL/fizzbuzz-7.apl @@ -0,0 +1,40 @@ + ∇ sv ← fizzbuzz n; t;d +[1] ⍝⍝ Solve the popular 'fizzbuzz' problem in APL. +[2] ⍝⍝ \param n - highest number to compute (≥0) +[3] ⍝⍝ \returns sv - a vector of strings representing the fizzbuzz solution for ⍳n +[4] ⍝⍝ (note we return a string vector to avoid a mixed-type result; remove the +[5] ⍝⍝ ⍕ function from the (⍕t[⍵]) term to see the difference). +[6] ⍝⍝⍝⍝ +[7] t←⍳n ⍝ the sequence 1..n itself which we'll pick from +[8] ⍝ ... or the words 'fizz', 'buzz', 'fizzbuzz' depending on +[9] ⍝ ... divisibility by 3 and/or 5 +[10] ⍝⎕←t ⍝ (Uncomment to see during call) +[11] +[12] d←1+(+⌿ ⊃ {((0=3|⍵)) (2×(0=5|⍵))} ⍳n) +[13] ⍝ || || | | | ↓↓ +[14] ⍝ || || | | | ⍳n: generate range (1..n) +[15] ⍝ || || | ↓.....................↓ ↓↓ +[16] ⍝ || || | A dfn (lambda) taking its right arg (⍵, ⍳n here) to compute two boolean +[17] ⍝ || || | vectors(v12): divisibility by 3 and 5, respectively, for each of ⍳n +[18] ⍝ || || ↓ +[19] ⍝ || || ⊃: Disclose ('lift-up' and pad w/zeros) the 'ragged' matrix of vectors (v12) +[20] ⍝ || || holding divisibility by 3 and 5 of each ⍳n +[21] ⍝ || ↓↓ +[22] ⍝ || +⌿: Sum (v12) row-wise to count divisibility (0=neither 3 nor 5, 1=3, 2=3 and 5) +[23] ⍝ ↓↓ +[24] ⍝ 1+: Add one to (v12) to make them 1-based for indexing below: +[25] ⍝⎕←d +[26] +[27] sv ← { ((⍕t[⍵]) 'Fizz' 'Buzz' 'FizzBuzz') [d[⍵]]}¨ ⍳n +[28] ⍝ | | | | | | +[29] ⍝ | | | ↓....↓ | +[30] ⍝ | |................................↓ idx | +[31] ⍝ | ( lookup output vector ) | +[32] ⍝ ↓...........................................↓ +[33] ⍝ A dfn (lambda) taking as its right arg (⍵) ⍳n and using the 'each' (¨) +[34] ⍝ operator to apply the lambda to each (idx) of ⍳n. +[35] +[36] ⍝⍝ USAGE +[37] ⍝⍝ ⎕ ← ,fizzbuzz 15 +[38] ⍝ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz + ∇ diff --git a/Task/FizzBuzz/Erlang/fizzbuzz.erl b/Task/FizzBuzz/Erlang/fizzbuzz-1.erl similarity index 100% rename from Task/FizzBuzz/Erlang/fizzbuzz.erl rename to Task/FizzBuzz/Erlang/fizzbuzz-1.erl diff --git a/Task/FizzBuzz/Erlang/fizzbuzz-2.erl b/Task/FizzBuzz/Erlang/fizzbuzz-2.erl new file mode 100644 index 0000000000..e0eca4b65c --- /dev/null +++ b/Task/FizzBuzz/Erlang/fizzbuzz-2.erl @@ -0,0 +1,27 @@ +-module(fizzbuzz). +-export([start/1, count/2, display/0]). + +fizzbuzz(N) when N rem 15 == 0 -> fizzbuzz; +fizzbuzz(N) when N rem 5 == 0 -> buzz; +fizzbuzz(N) when N rem 3 == 0 -> fizz; +fizzbuzz(N) -> N. + +count(N, Limit) when N==Limit -> + display ! fizzbuzz(N), + display ! finished; +count(N, Limit) when N + display ! fizzbuzz(N), + count(N+1, Limit). + +display() -> + receive + finished -> io:format("end!\n"); + fizzbuzz -> io:format("FizzBuzz!\n"), display(); + buzz -> io:format("Buzz!\n"), display(); + fizz -> io:format("Fizz!\n"), display(); + N -> io:format("~p\n", [N]), display() + end. + +start(Max) -> + register(display, spawn(fizzbuzz, display, [])), + count(1, Max). diff --git a/Task/FizzBuzz/Excel/fizzbuzz.excel b/Task/FizzBuzz/Excel/fizzbuzz.excel new file mode 100644 index 0000000000..72b590c3e0 --- /dev/null +++ b/Task/FizzBuzz/Excel/fizzbuzz.excel @@ -0,0 +1,11 @@ +=LET( + i, SEQUENCE(100), + isDivBy3, MOD(i, 3) = 0, + isDivBy5, MOD(i, 5) = 0, + IFS( + isDivBy3 * isDivBy5, "FizzBuzz", + isDivBy3, "Fizz", + isDivBy5, "Buzz", + TRUE, i + ) + ) diff --git a/Task/FizzBuzz/Factor/fizzbuzz-1.factor b/Task/FizzBuzz/Factor/fizzbuzz-1.factor index e761b31263..b00a4fcc29 100644 --- a/Task/FizzBuzz/Factor/fizzbuzz-1.factor +++ b/Task/FizzBuzz/Factor/fizzbuzz-1.factor @@ -1,7 +1,2 @@ -USING: math kernel io math.functions math.parser math.ranges ; -IN: fizzbuzz -: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ; -: buzz ( n -- str ) 5 divisor? "Buzz" "" ? ; -: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ; -: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ; -MAIN: main +USE: math.parser +1 101 [ [ 3 5 [ mod 0 = ] bi-curry@ bi "Fizz" "Buzz" swapd [ and ] 2bi@ append ] keep number>string or print ] each-integer-from diff --git a/Task/FizzBuzz/Factor/fizzbuzz-2.factor b/Task/FizzBuzz/Factor/fizzbuzz-2.factor index cc6c825348..e761b31263 100644 --- a/Task/FizzBuzz/Factor/fizzbuzz-2.factor +++ b/Task/FizzBuzz/Factor/fizzbuzz-2.factor @@ -1,19 +1,7 @@ -USING: kernel sequences arrays generalizations fry math math.parser prettyprint ; +USING: math kernel io math.functions math.parser math.ranges ; IN: fizzbuzz - -: zz ( m seq -- v ) dup length 1 V{ } clone 4 -nrot 1 4 -nrot 3 nrot - '[ dup _ <= ] - 3 -nrot - '[ - "" _ [ _ [ swap execute( str n -- str n ) ] change-nth ] each-index - dup empty? [ drop dup number>string ] [ ] if swapd suffix! swap 1 + - ] - while drop ; - -: fizz ( str n -- str n ) dup 3 < [ 1 + ] [ drop "Fizz" append 1 ] if ; -: buzz ( str n -- str n ) dup 5 < [ 1 + ] [ drop "Buzz" append 1 ] if ; -: quxx ( str n -- str n ) dup 7 < [ 1 + ] [ drop "Quxx" append 1 ] if ; -: FizzBuzzQuxx ( m -- v ) { fizz buzz quxx } zz ; -: FizzBuzzQuxx-100 ( -- ) 100 FizzBuzzQuxx . ; - -MAIN: FizzBuzzQuxx-100 +: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ; +: buzz ( n -- str ) 5 divisor? "Buzz" "" ? ; +: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ; +: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ; +MAIN: main diff --git a/Task/FizzBuzz/Factor/fizzbuzz-3.factor b/Task/FizzBuzz/Factor/fizzbuzz-3.factor index 16b9ef4955..cc6c825348 100644 --- a/Task/FizzBuzz/Factor/fizzbuzz-3.factor +++ b/Task/FizzBuzz/Factor/fizzbuzz-3.factor @@ -1,24 +1,19 @@ -USING: io kernel math math.functions math.parser ranges -sequences ; -IN: rosetta-code.fizz-buzz +USING: kernel sequences arrays generalizations fry math math.parser prettyprint ; +IN: fizzbuzz -PREDICATE: fizz < integer 3 divisor? ; -PREDICATE: buzz < integer 5 divisor? ; +: zz ( m seq -- v ) dup length 1 V{ } clone 4 -nrot 1 4 -nrot 3 nrot + '[ dup _ <= ] + 3 -nrot + '[ + "" _ [ _ [ swap execute( str n -- str n ) ] change-nth ] each-index + dup empty? [ drop dup number>string ] [ ] if swapd suffix! swap 1 + + ] + while drop ; -INTERSECTION: fizzbuzz fizz buzz ; +: fizz ( str n -- str n ) dup 3 < [ 1 + ] [ drop "Fizz" append 1 ] if ; +: buzz ( str n -- str n ) dup 5 < [ 1 + ] [ drop "Buzz" append 1 ] if ; +: quxx ( str n -- str n ) dup 7 < [ 1 + ] [ drop "Quxx" append 1 ] if ; +: FizzBuzzQuxx ( m -- v ) { fizz buzz quxx } zz ; +: FizzBuzzQuxx-100 ( -- ) 100 FizzBuzzQuxx . ; -GENERIC: fizzbuzz>string ( n -- str ) - -M: fizz fizzbuzz>string - drop "Fizz" ; - -M: buzz fizzbuzz>string - drop "Buzz" ; - -M: fizzbuzz fizzbuzz>string - drop "FizzBuzz" ; - -M: integer fizzbuzz>string - number>string ; - -MAIN: [ 1 100 [a..b] [ fizzbuzz>string print ] each ] +MAIN: FizzBuzzQuxx-100 diff --git a/Task/FizzBuzz/Factor/fizzbuzz-4.factor b/Task/FizzBuzz/Factor/fizzbuzz-4.factor new file mode 100644 index 0000000000..16b9ef4955 --- /dev/null +++ b/Task/FizzBuzz/Factor/fizzbuzz-4.factor @@ -0,0 +1,24 @@ +USING: io kernel math math.functions math.parser ranges +sequences ; +IN: rosetta-code.fizz-buzz + +PREDICATE: fizz < integer 3 divisor? ; +PREDICATE: buzz < integer 5 divisor? ; + +INTERSECTION: fizzbuzz fizz buzz ; + +GENERIC: fizzbuzz>string ( n -- str ) + +M: fizz fizzbuzz>string + drop "Fizz" ; + +M: buzz fizzbuzz>string + drop "Buzz" ; + +M: fizzbuzz fizzbuzz>string + drop "FizzBuzz" ; + +M: integer fizzbuzz>string + number>string ; + +MAIN: [ 1 100 [a..b] [ fizzbuzz>string print ] each ] diff --git a/Task/FizzBuzz/J/fizzbuzz-1.j b/Task/FizzBuzz/J/fizzbuzz-1.j index 5dde9baf98..cf8f496d2d 100644 --- a/Task/FizzBuzz/J/fizzbuzz-1.j +++ b/Task/FizzBuzz/J/fizzbuzz-1.j @@ -1,2 +1 @@ - classify =: +/@(1 2 * 0 = 3 5&|~) - (":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100 +(":[^:(0=#@])(>;:'Fizz Buzz'),@#~0=3 5&|)"0>:i.100 diff --git a/Task/FizzBuzz/J/fizzbuzz-10.j b/Task/FizzBuzz/J/fizzbuzz-10.j new file mode 100644 index 0000000000..4e32de5dc2 --- /dev/null +++ b/Task/FizzBuzz/J/fizzbuzz-10.j @@ -0,0 +1,2 @@ + ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ ;:@'Fizz Buzz' #&.>~ 0=3 5|/])i.101 +1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fiz... diff --git a/Task/FizzBuzz/J/fizzbuzz-11.j b/Task/FizzBuzz/J/fizzbuzz-11.j new file mode 100644 index 0000000000..caa56ca729 --- /dev/null +++ b/Task/FizzBuzz/J/fizzbuzz-11.j @@ -0,0 +1,36 @@ + i.10 +0 1 2 3 4 5 6 7 8 9 + (3 5 |/ ])i.10 +0 1 2 0 1 2 0 1 2 0 +0 1 2 3 4 0 1 2 3 4 + (0=3 5 |/ ])i.10 +1 0 0 1 0 0 1 0 0 1 +1 0 0 0 0 1 0 0 0 0 + (;:'Fizz Buzz') +┌────┬────┐ +│Fizz│Buzz│ +└────┴────┘ + ((;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 +┌────┬┬┬────┬┬────┬────┬┬┬────┐ +│Fizz│││Fizz││ │Fizz│││Fizz│ +├────┼┼┼────┼┼────┼────┼┼┼────┤ +│Buzz│││ ││Buzz│ │││ │ +└────┴┴┴────┴┴────┴────┴┴┴────┘ + ([: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 +┌────────┬┬┬────┬┬────┬────┬┬┬────┐ +│FizzBuzz│││Fizz││Buzz│Fizz│││Fizz│ +└────────┴┴┴────┴┴────┴────┴┴┴────┘ + (":&.>)i.10 +┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ +│0│1│2│3│4│5│6│7│8│9│ +└─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ + (":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 +┌────────┬─┬─┬────┬─┬────┬────┬─┬─┬────┐ +│FizzBuzz│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│ +└────────┴─┴─┴────┴─┴────┴────┴─┴─┴────┘ + }.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 +┌─┬─┬────┬─┬────┬────┬─┬─┬────┐ +│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│ +└─┴─┴────┴─┴────┴────┴─┴─┴────┘ + ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 +1 2 Fizz 4 Buzz Fizz 7 8 Fizz diff --git a/Task/FizzBuzz/J/fizzbuzz-2.j b/Task/FizzBuzz/J/fizzbuzz-2.j index eff230eaa9..ae7ac2541f 100644 --- a/Task/FizzBuzz/J/fizzbuzz-2.j +++ b/Task/FizzBuzz/J/fizzbuzz-2.j @@ -1 +1 @@ -> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101 +>((2#.3 q:15&+.){(|.(;~,&;);:'Fizz Buzz');~":)&>1+i.100 diff --git a/Task/FizzBuzz/J/fizzbuzz-3.j b/Task/FizzBuzz/J/fizzbuzz-3.j index ea1082f9c2..d25b1526f6 100644 --- a/Task/FizzBuzz/J/fizzbuzz-3.j +++ b/Task/FizzBuzz/J/fizzbuzz-3.j @@ -1,5 +1 @@ -Fizz=: 'Fizz' #~ 0 = 3&| -Buzz=: 'Buzz' #~ 0 = 5&| -FizzBuzz=: ": [^:('' -: ]) Fizz,Buzz - -FizzBuzz"0 >: i.100 +":`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_)@.(2#.0=3 5&|)"0>:i.100 diff --git a/Task/FizzBuzz/J/fizzbuzz-4.j b/Task/FizzBuzz/J/fizzbuzz-4.j index 4b811ea712..4daf942db5 100644 --- a/Task/FizzBuzz/J/fizzbuzz-4.j +++ b/Task/FizzBuzz/J/fizzbuzz-4.j @@ -1,6 +1 @@ -CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": ' -NB. Rather (, 0 = +./) than (, +:/) because designed for -NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7 -FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz') - -FizzBuzz"0 >: i.100 +{{":`('Fizz'"_)`('Buzz'"_)`,@.((0;1;2;1 3 2){~#.0=3 5|y)y}}"0 >:i.20 diff --git a/Task/FizzBuzz/J/fizzbuzz-5.j b/Task/FizzBuzz/J/fizzbuzz-5.j index 9c48851a18..eff230eaa9 100644 --- a/Task/FizzBuzz/J/fizzbuzz-5.j +++ b/Task/FizzBuzz/J/fizzbuzz-5.j @@ -1,6 +1 @@ -'`f b fb' =: ('Fizz'"_) ` ('Buzz'"_) ` (f , b) -'`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@) -FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also: -FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5) - -FizzBuzz"0 >: i.100 +> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101 diff --git a/Task/FizzBuzz/J/fizzbuzz-6.j b/Task/FizzBuzz/J/fizzbuzz-6.j index 3b006a37bf..ea1082f9c2 100644 --- a/Task/FizzBuzz/J/fizzbuzz-6.j +++ b/Task/FizzBuzz/J/fizzbuzz-6.j @@ -1,2 +1,5 @@ - ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~ 0 = 3 5 |/ ])i.101 -1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fiz... +Fizz=: 'Fizz' #~ 0 = 3&| +Buzz=: 'Buzz' #~ 0 = 5&| +FizzBuzz=: ": [^:('' -: ]) Fizz,Buzz + +FizzBuzz"0 >: i.100 diff --git a/Task/FizzBuzz/J/fizzbuzz-7.j b/Task/FizzBuzz/J/fizzbuzz-7.j index caa56ca729..4b811ea712 100644 --- a/Task/FizzBuzz/J/fizzbuzz-7.j +++ b/Task/FizzBuzz/J/fizzbuzz-7.j @@ -1,36 +1,6 @@ - i.10 -0 1 2 3 4 5 6 7 8 9 - (3 5 |/ ])i.10 -0 1 2 0 1 2 0 1 2 0 -0 1 2 3 4 0 1 2 3 4 - (0=3 5 |/ ])i.10 -1 0 0 1 0 0 1 0 0 1 -1 0 0 0 0 1 0 0 0 0 - (;:'Fizz Buzz') -┌────┬────┐ -│Fizz│Buzz│ -└────┴────┘ - ((;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 -┌────┬┬┬────┬┬────┬────┬┬┬────┐ -│Fizz│││Fizz││ │Fizz│││Fizz│ -├────┼┼┼────┼┼────┼────┼┼┼────┤ -│Buzz│││ ││Buzz│ │││ │ -└────┴┴┴────┴┴────┴────┴┴┴────┘ - ([: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 -┌────────┬┬┬────┬┬────┬────┬┬┬────┐ -│FizzBuzz│││Fizz││Buzz│Fizz│││Fizz│ -└────────┴┴┴────┴┴────┴────┴┴┴────┘ - (":&.>)i.10 -┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ -│0│1│2│3│4│5│6│7│8│9│ -└─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ - (":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 -┌────────┬─┬─┬────┬─┬────┬────┬─┬─┬────┐ -│FizzBuzz│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│ -└────────┴─┴─┴────┴─┴────┴────┴─┴─┴────┘ - }.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 -┌─┬─┬────┬─┬────┬────┬─┬─┬────┐ -│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│ -└─┴─┴────┴─┴────┴────┴─┴─┴────┘ - ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10 -1 2 Fizz 4 Buzz Fizz 7 8 Fizz +CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": ' +NB. Rather (, 0 = +./) than (, +:/) because designed for +NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7 +FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz') + +FizzBuzz"0 >: i.100 diff --git a/Task/FizzBuzz/J/fizzbuzz-8.j b/Task/FizzBuzz/J/fizzbuzz-8.j new file mode 100644 index 0000000000..9c48851a18 --- /dev/null +++ b/Task/FizzBuzz/J/fizzbuzz-8.j @@ -0,0 +1,6 @@ +'`f b fb' =: ('Fizz'"_) ` ('Buzz'"_) ` (f , b) +'`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@) +FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also: +FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5) + +FizzBuzz"0 >: i.100 diff --git a/Task/FizzBuzz/J/fizzbuzz-9.j b/Task/FizzBuzz/J/fizzbuzz-9.j new file mode 100644 index 0000000000..e259c246e8 --- /dev/null +++ b/Task/FizzBuzz/J/fizzbuzz-9.j @@ -0,0 +1 @@ +{{>(#.|:0=3 5|&>L=.1+i.y),|:(y,3)$;:'Fizz Buzz FizzBuzz'}}100 diff --git a/Task/FizzBuzz/K/fizzbuzz-1.k b/Task/FizzBuzz/K/fizzbuzz-1.k index 1592aa685d..827c202ee0 100644 --- a/Task/FizzBuzz/K/fizzbuzz-1.k +++ b/Task/FizzBuzz/K/fizzbuzz-1.k @@ -1 +1 @@ -`0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101 +{,/$(s;x)@~#s:`Fizz`Buzz@&~x!'3 5}'1+!30 diff --git a/Task/FizzBuzz/K/fizzbuzz-2.k b/Task/FizzBuzz/K/fizzbuzz-2.k index 78fc38d860..fa59579991 100644 --- a/Task/FizzBuzz/K/fizzbuzz-2.k +++ b/Task/FizzBuzz/K/fizzbuzz-2.k @@ -1,2 +1 @@ - fizzbuzz:{:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]} - fizzbuzz' 1+!100 + {:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]}'1+!100 diff --git a/Task/FizzBuzz/K/fizzbuzz-3.k b/Task/FizzBuzz/K/fizzbuzz-3.k index 6e9a070c6a..1592aa685d 100644 --- a/Task/FizzBuzz/K/fizzbuzz-3.k +++ b/Task/FizzBuzz/K/fizzbuzz-3.k @@ -1,8 +1 @@ -fizzbuzz:{ - v:1+!x - i:(&0=)'v!/:3 5 15 - r:@[v;i 0;{"Fizz"}] - r:@[r;i 1;{"Buzz"}] - @[r;i 2;{"FizzBuzz"}]} - -`0:$fizzbuzz 100 +`0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101 diff --git a/Task/FizzBuzz/K/fizzbuzz-4.k b/Task/FizzBuzz/K/fizzbuzz-4.k index 827c202ee0..6e9a070c6a 100644 --- a/Task/FizzBuzz/K/fizzbuzz-4.k +++ b/Task/FizzBuzz/K/fizzbuzz-4.k @@ -1 +1,8 @@ -{,/$(s;x)@~#s:`Fizz`Buzz@&~x!'3 5}'1+!30 +fizzbuzz:{ + v:1+!x + i:(&0=)'v!/:3 5 15 + r:@[v;i 0;{"Fizz"}] + r:@[r;i 1;{"Buzz"}] + @[r;i 2;{"FizzBuzz"}]} + +`0:$fizzbuzz 100 diff --git a/Task/FizzBuzz/Pascal/fizzbuzz.pas b/Task/FizzBuzz/Pascal/fizzbuzz.pas deleted file mode 100644 index ecf0f31b7d..0000000000 --- a/Task/FizzBuzz/Pascal/fizzbuzz.pas +++ /dev/null @@ -1,14 +0,0 @@ -program fizzbuzz(output); -var - i: integer; -begin - for i := 1 to 100 do - if i mod 15 = 0 then - writeln('FizzBuzz') - else if i mod 3 = 0 then - writeln('Fizz') - else if i mod 5 = 0 then - writeln('Buzz') - else - writeln(i) -end. diff --git a/Task/FizzBuzz/Python/fizzbuzz-10.py b/Task/FizzBuzz/Python/fizzbuzz-10.py index ecb948c678..b29ebd9a54 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-10.py +++ b/Task/FizzBuzz/Python/fizzbuzz-10.py @@ -1,33 +1,13 @@ -'''Fizz buzz''' +from itertools import cycle, izip, count, islice -from itertools import count, cycle, islice +fizzes = cycle([""] * 2 + ["Fizz"]) +buzzes = cycle([""] * 4 + ["Buzz"]) +both = (f + b for f, b in izip(fizzes, buzzes)) +# if the string is "", yield the number +# otherwise yield the string +fizzbuzz = (word or n for word, n in izip(both, count(1))) -# fizzBuzz :: () -> Generator [String] -def fizzBuzz(): - '''A non-finite stream of fizzbuzz terms. - ''' - return map( - lambda f, b, n: (f + b) or str(n), - cycle([''] * 2 + ['Fizz']), - cycle([''] * 4 + ['Buzz']), - count(1) - ) - - -# ------------------------- TEST ------------------------- -def main(): - '''Display of first 100 terms of the fizzbuzz series. - ''' - print( - '\n'.join( - list(islice( - fizzBuzz(), - 100 - )) - ) - ) - - -if __name__ == '__main__': - main() +# print the first 100 +for i in islice(fizzbuzz, 100): + print i diff --git a/Task/FizzBuzz/Python/fizzbuzz-11.py b/Task/FizzBuzz/Python/fizzbuzz-11.py index f5123bf731..ecb948c678 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-11.py +++ b/Task/FizzBuzz/Python/fizzbuzz-11.py @@ -1 +1,33 @@ -print(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i := n**4%-15) > -14 else n, range(1,100))) +'''Fizz buzz''' + +from itertools import count, cycle, islice + + +# fizzBuzz :: () -> Generator [String] +def fizzBuzz(): + '''A non-finite stream of fizzbuzz terms. + ''' + return map( + lambda f, b, n: (f + b) or str(n), + cycle([''] * 2 + ['Fizz']), + cycle([''] * 4 + ['Buzz']), + count(1) + ) + + +# ------------------------- TEST ------------------------- +def main(): + '''Display of first 100 terms of the fizzbuzz series. + ''' + print( + '\n'.join( + list(islice( + fizzBuzz(), + 100 + )) + ) + ) + + +if __name__ == '__main__': + main() diff --git a/Task/FizzBuzz/Python/fizzbuzz-12.py b/Task/FizzBuzz/Python/fizzbuzz-12.py index 1bd2e48a8c..f5123bf731 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-12.py +++ b/Task/FizzBuzz/Python/fizzbuzz-12.py @@ -1,12 +1 @@ -def numsum(n): - ''' The recursive sum of all digits in a number - unit a single character is obtained''' - res = sum([int(i) for i in str(n)]) - if res < 10: return res - else : return numsum(res) - -for n in range(1,101): - response = 'Fizz'*(numsum(n) in [3,6,9]) + \ - 'Buzz'*(str(n)[-1] in ['5','0'])\ - or n - print(response) +print(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i := n**4%-15) > -14 else n, range(1,100))) diff --git a/Task/FizzBuzz/Python/fizzbuzz-13.py b/Task/FizzBuzz/Python/fizzbuzz-13.py index 15158ad45a..1bd2e48a8c 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-13.py +++ b/Task/FizzBuzz/Python/fizzbuzz-13.py @@ -1 +1,12 @@ -print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101))) +def numsum(n): + ''' The recursive sum of all digits in a number + unit a single character is obtained''' + res = sum([int(i) for i in str(n)]) + if res < 10: return res + else : return numsum(res) + +for n in range(1,101): + response = 'Fizz'*(numsum(n) in [3,6,9]) + \ + 'Buzz'*(str(n)[-1] in ['5','0'])\ + or n + print(response) diff --git a/Task/FizzBuzz/Python/fizzbuzz-14.py b/Task/FizzBuzz/Python/fizzbuzz-14.py new file mode 100644 index 0000000000..15158ad45a --- /dev/null +++ b/Task/FizzBuzz/Python/fizzbuzz-14.py @@ -0,0 +1 @@ +print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101))) diff --git a/Task/FizzBuzz/Python/fizzbuzz-8.py b/Task/FizzBuzz/Python/fizzbuzz-8.py index 746414bdc9..ef80bcefd1 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-8.py +++ b/Task/FizzBuzz/Python/fizzbuzz-8.py @@ -1 +1,17 @@ -[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)] +actions = { + 0: lambda i: print(i), + 1: lambda i: print("fizz"), + 2: lambda i: print("buzz"), + 3: lambda i: print("fizzbuzz"), +} + +for i in range(1, 101): + action_index = 0 + + if i % 3 == 0: + action_index += 1 + + if i % 5 == 0: + action_index += 2 + + actions[action_index](i) diff --git a/Task/FizzBuzz/Python/fizzbuzz-9.py b/Task/FizzBuzz/Python/fizzbuzz-9.py index b29ebd9a54..746414bdc9 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-9.py +++ b/Task/FizzBuzz/Python/fizzbuzz-9.py @@ -1,13 +1 @@ -from itertools import cycle, izip, count, islice - -fizzes = cycle([""] * 2 + ["Fizz"]) -buzzes = cycle([""] * 4 + ["Buzz"]) -both = (f + b for f, b in izip(fizzes, buzzes)) - -# if the string is "", yield the number -# otherwise yield the string -fizzbuzz = (word or n for word, n in izip(both, count(1))) - -# print the first 100 -for i in islice(fizzbuzz, 100): - print i +[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)] diff --git a/Task/FizzBuzz/Smalltalk/fizzbuzz-4.st b/Task/FizzBuzz/Smalltalk/fizzbuzz-4.st index 12bbef1dcd..67f72c15dd 100644 --- a/Task/FizzBuzz/Smalltalk/fizzbuzz-4.st +++ b/Task/FizzBuzz/Smalltalk/fizzbuzz-4.st @@ -1,10 +1,12 @@ -1 to: 100 do: [:n | |r| - r := n rem: 15. - Transcript show: (r isZero - ifTrue:['fizzbuzz'] - ifFalse: [(#(3 6 9 12) includes: r) - ifTrue:['fizz'] - ifFalse:[((#(5 10) includes: r)) - ifTrue:['buzz'] - ifFalse:[n]]]); - cr]. +0 to: 100 do: [ :i | + (i \\ 3 = 0 and: [ i \\ 5 = 0 ]) + ifTrue: [ Transcript show: 'FizzBuzz'; cr. ] + ifFalse: [ + (i \\ 3 = 0) + ifTrue: [ Transcript show: 'Fizz'; cr. ]. + (i \\ 5 = 0) + ifTrue: [ Transcript show: 'Buzz'; cr. ]. + ((i \\ 3 ~= 0) and: [ i \\ 5 ~= 0 ]) + ifTrue: [ Transcript show: i printString; cr. ]. + ]. +]. diff --git a/Task/FizzBuzz/Smalltalk/fizzbuzz-5.st b/Task/FizzBuzz/Smalltalk/fizzbuzz-5.st index 83e4ca616e..12bbef1dcd 100644 --- a/Task/FizzBuzz/Smalltalk/fizzbuzz-5.st +++ b/Task/FizzBuzz/Smalltalk/fizzbuzz-5.st @@ -1,5 +1,10 @@ -fbz := (1 to: 100) asOrderedCollection. - 3 to: 100 by: 3 do: [:i | fbz at: i put: 'Fizz']. - 5 to: 100 by: 5 do: [:i | fbz at: i put: 'Buzz']. -15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz']. -fbz do: [:i | Transcript show: i; cr]. +1 to: 100 do: [:n | |r| + r := n rem: 15. + Transcript show: (r isZero + ifTrue:['fizzbuzz'] + ifFalse: [(#(3 6 9 12) includes: r) + ifTrue:['fizz'] + ifFalse:[((#(5 10) includes: r)) + ifTrue:['buzz'] + ifFalse:[n]]]); + cr]. diff --git a/Task/FizzBuzz/Smalltalk/fizzbuzz-6.st b/Task/FizzBuzz/Smalltalk/fizzbuzz-6.st index a0c292e114..83e4ca616e 100644 --- a/Task/FizzBuzz/Smalltalk/fizzbuzz-6.st +++ b/Task/FizzBuzz/Smalltalk/fizzbuzz-6.st @@ -1,5 +1,5 @@ -1 to: 100 do: [:i | |fb s| - fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}. - fb at: 3 put: (fb first | fb second) not. - s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}. - Transcript show: (s expandMacrosWithArguments: fb); cr]. +fbz := (1 to: 100) asOrderedCollection. + 3 to: 100 by: 3 do: [:i | fbz at: i put: 'Fizz']. + 5 to: 100 by: 5 do: [:i | fbz at: i put: 'Buzz']. +15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz']. +fbz do: [:i | Transcript show: i; cr]. diff --git a/Task/FizzBuzz/Smalltalk/fizzbuzz-7.st b/Task/FizzBuzz/Smalltalk/fizzbuzz-7.st new file mode 100644 index 0000000000..a0c292e114 --- /dev/null +++ b/Task/FizzBuzz/Smalltalk/fizzbuzz-7.st @@ -0,0 +1,5 @@ +1 to: 100 do: [:i | |fb s| + fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}. + fb at: 3 put: (fb first | fb second) not. + s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}. + Transcript show: (s expandMacrosWithArguments: fb); cr]. diff --git a/Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl b/Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl new file mode 100644 index 0000000000..7b135f37f9 --- /dev/null +++ b/Task/Flow-control-structures/Uxntal/flow-control-structures.uxnatl @@ -0,0 +1,24 @@ +|18 @Console/write + +|100 + +example + +BRK + +@example ( x y -- ) + ;start print/str + !&world ( goto &world ) + ;never print/str + &world ( label &world ) + ;end !print/str + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?&str + POP2 + JMP2r + +@start "Hello, 2000 +@never "Never 20 "printed. 0a00 +@end "World! 0a00 diff --git a/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy b/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy index 0f7444170a..4d4159674a 100644 --- a/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy +++ b/Task/Floyd-Warshall-algorithm/EasyLang/floyd-warshall-algorithm.easy @@ -1,9 +1,7 @@ -proc floydwarshall w[][] n . . +proc floydwarshall w[][] n . for i to n con[][] &= [ ] - for j to n - con[i][] &= 1 / 0 - . + for j to n : con[i][] &= 1 / 0 . for i to len w[][] con[w[i][1]][w[i][2]] = w[i][3] diff --git a/Task/Floyd-Warshall-algorithm/XPL0/floyd-warshall-algorithm.xpl0 b/Task/Floyd-Warshall-algorithm/XPL0/floyd-warshall-algorithm.xpl0 new file mode 100644 index 0000000000..ec04cf0579 --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/XPL0/floyd-warshall-algorithm.xpl0 @@ -0,0 +1,49 @@ +include xpllib; \for Print + +proc FloydWarshall(Weights, Len, Verts); +int Weights, Len, Verts; +int Dist, Next, I, J, K, W; + + proc PrintResult; + int U, V; + [Print("Pair Dist Path\n"); + for I:= 0 to Verts-1 do + for J:= 0 to Verts-1 do + if I # J then + [U:= I+1; V:= J+1; + Print("%d -> %d %2d %d", U, V, Dist(I,J), U); + repeat U:= Next(U-1, V-1); + Print(" -> %d", U); + until U = V; + Print("\n"); + ]; + ]; + +[Dist:= Reserve(Verts*IntSize); +for I:= 0 to Verts-1 do + [Dist(I):= Reserve(Verts*IntSize); + for J:= 0 to Verts-1 do + Dist(I,J):= \Inf\10000; + ]; +for W:= 0 to Len-1 do + Dist(Weights(W,0)-1, Weights(W,1)-1):= Weights(W,2); +Next:= Reserve(Verts*IntSize); +for I:= 0 to Verts-1 do + [Next(I):= Reserve(Verts*IntSize); + for J:= 0 to Verts-1 do + Next(I,J):= if I=J then 0 else J+1; + ]; +for K:= 0 to Verts-1 do + for I:= 0 to Verts-1 do + for J:= 0 to Verts-1 do + if Dist(I,J) > Dist(I,K) + Dist(K,J) then + [Dist(I,J):= Dist(I,K) + Dist(K,J); + Next(I,J):= Next(I,K); + ]; +PrintResult; +]; + +int Weights; +[Weights:= [ [1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1] ]; +FloydWarshall(Weights, 5, 4); +] diff --git a/Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig b/Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig new file mode 100644 index 0000000000..fe8d6dd20d --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Zig/floyd-warshall-algorithm.zig @@ -0,0 +1,99 @@ +// floyd_warshall.zig +const std = @import("std"); + +const F64_INF = std.math.inf(f64); + +fn idx(i: usize, j: usize, n: usize) usize { + return i * n + j; +} + +fn printResult(dist: []const f64, next: []const usize, n: usize) void { + std.debug.print("(pair, dist, path)\n", .{}); + for (0..n) |i| { + for (0..n) |j| { + if (i == j) continue; + + const @"u0" = i + 1; + const v0 = j + 1; + + std.debug.print("({d} -> {d}, {d}, ", .{ + @"u0", v0, dist[idx(i, j, n)], + }); + + var u = @"u0"; + std.debug.print("{d}", .{u}); + while (u != v0) { + u = next[idx(u - 1, v0 - 1, n)]; + std.debug.print(" -> {d}", .{u}); + } + std.debug.print(")\n", .{}); + } + } +} + +fn solve( + allocator: std.mem.Allocator, + edges: []const [3]i64, // (u,v,w) 1‑based + n: usize, +) !void { + // Allocate matrices + var dist = try allocator.alloc(f64, n * n); + defer allocator.free(dist); + + var next_v = try allocator.alloc(usize, n * n); + defer allocator.free(next_v); + + // Initialise + for (dist)|*d| d.* = F64_INF; + for (next_v)|*x| x.* = 0; + + // Edge weights + for (edges) |e| { + const u = @as(usize, @intCast(e[0] - 1)); + const v = @as(usize, @intCast(e[1] - 1)); + dist[idx(u, v, n)] = @as(f64, @floatFromInt(e[2])); + } + + // Successor matrix + for (0..n) |i| { + for (0..n) |j| { + if (i != j) next_v[idx(i, j, n)] = j + 1; // 1‑based + } + } + + // Floyd–Warshall + for (0..n) |k| { + for (0..n) |i| { + for (0..n) |j| { + const dik = dist[idx(i, k, n)]; + const dkj = dist[idx(k, j, n)]; + if (std.math.isFinite(dik) and std.math.isFinite(dkj)) { + const alt = dik + dkj; + const pos = idx(i, j, n); + if (alt < dist[pos]) { + dist[pos] = alt; + next_v[pos] = next_v[idx(i, k, n)]; + } + } + } + } + } + + printResult(dist, next_v, n); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const alloc = gpa.allocator(); + + const edges = [_][3]i64{ + .{ 1, 3, -2 }, + .{ 2, 1, 4 }, + .{ 2, 3, 3 }, + .{ 3, 4, 2 }, + .{ 4, 2, -1 }, + }; + + try solve(alloc, edges[0..], 4); +} diff --git a/Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina b/Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina new file mode 100644 index 0000000000..0a4976e6f9 --- /dev/null +++ b/Task/Floyds-triangle/Ballerina/floyds-triangle.ballerina @@ -0,0 +1,20 @@ +import ballerina/io; + +function floyd(int n) { + int k = 1; + foreach int i in 1...n { + foreach int j in 1...i { + int p = j < 9 ? 3 : 4; + io:print(k.toString().padStart(p)); + k += 1; + } + io:println(); + } +} + +public function main() { + io:println("Floyd(5):"); + floyd(5); + io:println("\nFloyd(14):"); + floyd(14); +} diff --git a/Task/Floyds-triangle/EasyLang/floyds-triangle.easy b/Task/Floyds-triangle/EasyLang/floyds-triangle.easy index 3e5e057b64..092f392cbd 100644 --- a/Task/Floyds-triangle/EasyLang/floyds-triangle.easy +++ b/Task/Floyds-triangle/EasyLang/floyds-triangle.easy @@ -1,17 +1,15 @@ func ceil h . f = floor h - if h <> f - f += 1 - . + if h <> f : f += 1 return f . -proc triangle n . . +proc triangle n . print n & " rows:" row = 1 while row <= n printme += 1 cols = ceil log10 (n * (n - 1) / 2 + nprinted + 2) - numfmt 0 cols + numfmt cols 0 write printme & " " nprinted += 1 if nprinted = row diff --git a/Task/Floyds-triangle/Objeck/floyds-triangle.objeck b/Task/Floyds-triangle/Objeck/floyds-triangle.objeck new file mode 100644 index 0000000000..567e784e01 --- /dev/null +++ b/Task/Floyds-triangle/Objeck/floyds-triangle.objeck @@ -0,0 +1,20 @@ +class Floyds { + function : Main(args : String[]) ~ Nil { + PrintTriangle(5); + PrintTriangle(14); + } + + function : PrintTriangle(n : Int) ~ Nil { + "{$n} rows:"->PrintLine(); + + rowNum := 1; printMe := 1; numsPrinted := 0; + for(; rowNum <= n; printMe++;){ + "{$printMe}\t"->Print(); + + if(++numsPrinted = rowNum){ + ""->PrintLine(); + rowNum++; numsPrinted := 0; + } + } + } +} diff --git a/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys b/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys index b633b847da..3737ab63e1 100644 --- a/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys +++ b/Task/Floyds-triangle/YAMLScript/floyds-triangle.ys @@ -1,6 +1,6 @@ !YS-v0 -defn main(n): +defn main(n=14): nums =: range().map(inc).map(str) rows =: loop row-n 1, nums nums, rows []: diff --git a/Task/Forest-fire/EasyLang/forest-fire.easy b/Task/Forest-fire/EasyLang/forest-fire.easy index e524ca0c60..f2e94eacce 100644 --- a/Task/Forest-fire/EasyLang/forest-fire.easy +++ b/Task/Forest-fire/EasyLang/forest-fire.easy @@ -3,62 +3,51 @@ p_tree = 0.002 # len f[] 102 * 102 len p[] len f[] -background 100 -clear -for r = 0 to 99 - for c = 0 to 99 - i = r * 102 + c + 104 - if randomf < 0.5 - f[i] = 1 - . - . +gbackground 100 +gclear +for r = 0 to 99 : for c = 0 to 99 + i = r * 102 + c + 104 + if randomf < 0.5 : f[i] = 1 . timer 0 # subr show - for r = 0 to 99 - for c = 0 to 99 - i = r * 102 + c + 104 - h = f[i] - if h <> p[i] - move c + 0.5 r + 0.5 - if h = 0 - color 100 - circle 0.6 - elif h = 1 - color 151 - circle 0.5 - else - color 9 * 100 + (18 - 2 * h) * 10 - circle 0.5 - . + for r = 0 to 99 : for c = 0 to 99 + i = r * 102 + c + 104 + h = f[i] + if h <> p[i] + if h = 0 + gcolor 100 + gcircle c + 0.5 r + 0.5 0.6 + elif h = 1 + gcolor 151 + gcircle c + 0.5 r + 0.5 0.5 + else + gcolor 9 * 100 + (18 - 2 * h) * 10 + gcircle c + 0.5 r + 0.5 0.5 . . . . subr update swap f[] p[] - for r = 0 to 99 - for c = 0 to 99 - i = r * 102 + c + 104 - if p[i] = 0 - f[i] = 0 - if randomf < p_tree - f[i] = 1 - . - elif p[i] = 1 - f[i] = 1 - s = p[i - 103] + p[i - 102] + p[i - 101] - s += p[i - 1] + p[i + 1] - s += p[i + 101] + p[i + 102] + p[i + 103] - if s >= 9 or randomf < p_fire - f[i] = 9 - . - elif p[i] = 4 - f[i] = 0 - else - f[i] = p[i] - 1 + for r = 0 to 99 : for c = 0 to 99 + i = r * 102 + c + 104 + if p[i] = 0 + f[i] = 0 + if randomf < p_tree : f[i] = 1 + elif p[i] = 1 + f[i] = 1 + s = p[i - 103] + p[i - 102] + p[i - 101] + s += p[i - 1] + p[i + 1] + s += p[i + 101] + p[i + 102] + p[i + 103] + if s >= 9 or randomf < p_fire + f[i] = 9 . + elif p[i] = 4 + f[i] = 0 + else + f[i] = p[i] - 1 . . . diff --git a/Task/Forest-fire/J/forest-fire-3.j b/Task/Forest-fire/J/forest-fire-3.j new file mode 100644 index 0000000000..cb31a84084 --- /dev/null +++ b/Task/Forest-fire/J/forest-fire-3.j @@ -0,0 +1,16 @@ +mt=:{{ (? 0) I.~ +/\ (y { x) }} NB. Mutate state function +pad=:0,0,~0(,.)0,.~] NB. Pading with zero +ib=:+./@:(=&2)@, NB. IsBurning to check if fire in the area +f=:0.005 NB. Probability of starting fire +p=:0.05 NB. Probability of three +tm0=:3 3$(1-p),p,0,0,(1-f),f,1,0,0 NB. Transition matrix of state with no fire in area +tm1=:3 3 $(1-p),p,0,0,0,1,1,0,0 NB. Transition matrix of state with fire in area + +opt0=:[:tm0&mt(<1 1){] NB. Option #0 (for mutation with no fire in area) +opt1=:[:tm1&mt(<1 1){] NB. Option #1 (for mutation with fire in area) + +ff=:(,.~1 3)([: pad(opt0`opt1@.ib);._3)] NB. Core function FireForest + + NB. Using it.... +dt =: 10 10 $ 0 NB. Create a empty 10x10 matrix +ff ^:(i.100) dt NB. Iterate 100 time, output include initial empty matrix. diff --git a/Task/Forest-fire/J/forest-fire-4.j b/Task/Forest-fire/J/forest-fire-4.j new file mode 100644 index 0000000000..1ccf79b0b7 --- /dev/null +++ b/Task/Forest-fire/J/forest-fire-4.j @@ -0,0 +1,10 @@ +0 0 0 0 0 0 0 0 0 0 +0 1 1 1 1 1 1 1 1 0 +0 1 2 1 1 1 1 0 1 0 +0 1 0 1 1 0 1 1 0 0 +0 1 1 1 0 0 1 0 0 0 +0 0 0 0 2 0 2 0 0 0 +0 0 0 2 1 0 0 0 1 0 +0 1 0 0 0 0 0 2 1 0 +0 1 0 2 0 0 0 0 1 0 +0 0 0 0 0 0 0 0 0 0 diff --git a/Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output.alg b/Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output-1.alg similarity index 100% rename from Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output.alg rename to Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output-1.alg diff --git a/Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output-2.alg b/Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output-2.alg new file mode 100644 index 0000000000..b066063291 --- /dev/null +++ b/Task/Formatted-numeric-output/ALGOL-68/formatted-numeric-output-2.alg @@ -0,0 +1,59 @@ +( + OP UNSUPPRESS = ( STRING v )STRING: # replace leading spaces with zeros # + IF LWB v > UPB v + THEN v # empty string # + ELSE STRING result := v; + INT p1 := LWB result; + IF result[ p1 ] = " " THEN result[ p1 ] := "0" FI; + FOR p FROM LWB result + 1 TO UPB result DO + CHAR c = result[ p ]; + IF c = " " THEN result[ p ] := "0" + ELIF c = "-" OR c = "+" THEN result[ p ] := "0"; result[ p1 ] := c + ELIF c = "e" THEN p1 := p + 1 + FI + OD; + result + FI # UNSUPPRESS # ; + OP SUPPRESSPLUS = ( STRING v )STRING: # replace leading space/zero with "+" # + IF LWB v > UPB v THEN v ELIF CHAR c = v[ LWB v ]; c = "+" OR c = "0" THEN " " + v[ LWB v + 1 : ] ELSE v FI; + PRIO SUPPRESS = 5; # suppress up to d leading zeros # + OP SUPPRESS = ( STRING v, INT d )STRING: + IF LWB v > UPB v + THEN v + ELIF CHAR c1 = v[ LWB v ]; c1 /= "+" AND c1 /= "-" AND c1 /= "0" + THEN v + ELSE INT len = ( UPB v - LWB v ) + 1; + INT max p = ( LWB v - 1 ) + IF len > d THEN d ELSE len FI; + STRING result := v; + CHAR sign char = IF c1 = "0" THEN " " ELSE c1 FI; + result[ LWB result ] := " "; + BOOL inserted sign := FALSE; + FOR p FROM LWB result + 1 TO max p + WHILE CHAR c = result[ p ]; + IF c /= "0" THEN result[ p - 1 ] := sign char; inserted sign := TRUE FI; + NOT inserted sign + DO result[ p ] := " " + OD; + IF NOT inserted sign THEN result[ max p ] := sign char FI; + result + FI # SUPPRESS # ; + + REAL r=exp(pi)-pi; + print((r,newline)); + print((fixed(-r,16,4),newline)); + print((fixed(r,-16,4),newline)); + print((fixed(r,16,4),newline)); + print((float(r,16,4,1),newline)); + + print((SUPPRESSPLUS UNSUPPRESS fixed(-r,-10,4),newline)); + print((SUPPRESSPLUS UNSUPPRESS fixed(r,-10,4),newline)); + print((UNSUPPRESS fixed(r,10,4),newline)); + print((UNSUPPRESS fixed(ABS r,-10,4),newline)); + + print((fixed(ABS r,-10,4),newline)); + + print((SUPPRESSPLUS UNSUPPRESS fixed(-r,12,4) SUPPRESS 5,newline)); + print((SUPPRESSPLUS UNSUPPRESS float(-r,16,4,-3) SUPPRESS 5,newline)); + print((SUPPRESSPLUS UNSUPPRESS float(-r,-13,4,3),newline)); + print((SUPPRESSPLUS UNSUPPRESS float(r,-17,4,5),newline)) +) diff --git a/Task/Formatted-numeric-output/Applesoft-BASIC/formatted-numeric-output.basic b/Task/Formatted-numeric-output/Applesoft-BASIC/formatted-numeric-output.basic new file mode 100644 index 0000000000..4c13390339 --- /dev/null +++ b/Task/Formatted-numeric-output/Applesoft-BASIC/formatted-numeric-output.basic @@ -0,0 +1,27 @@ + 0 P = 5:T = 3:R = 7.125: GOSUB 100"FORMATTED NUMERIC OUTPUT + 9 END + +REM FORMATTED NUMERIC OUTPUT + +REM Given R a Real number +REM and P as left Padding amount, P$ as the Padding +REM and T as the Trailing amount, T$ as the Trailing padding + + 100 R$ = STR$ (R):L = LEN (R$):S$ = "": IF MID$ (R$,1,1) = " " THEN S$ = " ":L = L - 1:R$ = RIGHT$ (R$,L) + 110 IF MID$ (R$,1,1) = "-" THEN L = L - 1:R$ = RIGHT$ (R$,L):S$ = S$ + "-": REM SIGN + 120 LET D$ = "":D = 0:E$ = "":E = 0: REM DECIMAL, EXPONENT and POSITIONS + 130 IF P$ = "" THEN P$ = "0": REM LEFT PADDING + 140 IF T$ = "" THEN T$ = "0": REM TRAILING PADDING + 150 FOR I = 1 TO L + 160 LET C$ = MID$ (R$,I,1) + 170 IF C$ = "." THEN D = I + 180 IF C$ = "E" THEN E = I + 190 NEXT I + 200 IF E THEN E$ = MID$ (R$,E):R$ = LEFT$ (R$,E - 1) + 210 IF D THEN D$ = MID$ (R$,D + 1):R$ = LEFT$ (R$,D - 1) + 220 LET PAD$ = "": FOR I = 1 TO P:PAD$ = P$ + PAD$: NEXT + 230 PRINT S$ RIGHT$ (PAD$ + R$,P); + 240 LET PAD$ = "": FOR I = 1 TO T:PAD$ = PAD$ + T$: NEXT + 250 IF T THEN PRINT "." LEFT$ (D$ + PAD$,T); + 260 PRINT E$; + 270 RETURN diff --git a/Task/Formatted-numeric-output/JavaScript/formatted-numeric-output.js b/Task/Formatted-numeric-output/JavaScript/formatted-numeric-output.js index 4d1f797beb..a48931e09e 100644 --- a/Task/Formatted-numeric-output/JavaScript/formatted-numeric-output.js +++ b/Task/Formatted-numeric-output/JavaScript/formatted-numeric-output.js @@ -1,3 +1,18 @@ -var n = 123; -var str = ("00000" + n).slice(-5); -alert(str); +function fmt(n, options) { + const [whole, fraction] = String(n).split('.', 2) + return [ + whole.padStart(options.whole || 1, '0'), + (fraction ?? '').padEnd(options.fraction, '0').slice(0, options.fraction), + ].filter(Boolean).join('.') +} + +for (const [n, options] of [ + [123, { whole: 1, fraction: 2 }], // 123.00 + [123, { whole: 5, fraction: 2 }], // 00123.00 + [123, { whole: 5, fraction: 0 }], // 00123 + [0.5, { whole: 1, fraction: 2 }], // 0.50 + [0.5, { whole: 5, fraction: 2 }], // 00000.50 + [0.5, { whole: 5, fraction: 0 }], // 00000 +]) { + console.log(fmt(n, options)) +} diff --git a/Task/Fortunate-numbers/EasyLang/fortunate-numbers.easy b/Task/Fortunate-numbers/EasyLang/fortunate-numbers.easy index 2c1cb9afb6..dc96747c37 100644 --- a/Task/Fortunate-numbers/EasyLang/fortunate-numbers.easy +++ b/Task/Fortunate-numbers/EasyLang/fortunate-numbers.easy @@ -1,9 +1,7 @@ fastfunc isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 @@ -15,22 +13,18 @@ fastfunc nextprim prim . . return prim . -proc insert e . d[] . +proc insert &d[] e . for i = 1 to len d[] if d[i] >= e - if d[i] = e - return - . + if d[i] = e : return break 1 . . d[] &= 0 - for i = len d[] downto i + 1 - d[i] = d[i - 1] - . + for i = len d[] downto i + 1 : d[i] = d[i - 1] d[i] = e . -proc fortunates . . +proc fortunates . maxint = pow 2 53 primorial = 1 prim = 2 @@ -42,10 +36,8 @@ proc fortunates . . while isprim (primorial + j) = 0 j = j + 2 . - insert j fortuns[] - . - for i to 8 - write fortuns[i] & " " + insert fortuns[] j . + for i to 8 : write fortuns[i] & " " . fortunates diff --git a/Task/Fortunate-numbers/REXX/fortunate-numbers-1.rexx b/Task/Fortunate-numbers/REXX/fortunate-numbers-1.rexx deleted file mode 100644 index a39ae2d9b5..0000000000 --- a/Task/Fortunate-numbers/REXX/fortunate-numbers-1.rexx +++ /dev/null @@ -1,54 +0,0 @@ -/*REXX program finds/displays fortunate numbers N, where N is specified (default=8).*/ -numeric digits 12 -parse arg n cols . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 8 /*Not specified? Then use the default.*/ -if cols=='' | cols=="," then cols= 10 /* " " " " " " */ -call genP n**2 /*build array of semaphores for primes.*/ -pp.= 1 - do i=1 for n+1; im= i - 1; pp.i= pp.im * @.i /*calculate primorial numbers*/ - end /*i*/ -i=i-1; call genp pp.i + 1000 - title= ' fortunate numbers' -w= 10 /*maximum width of a number in any col.*/ -say ' index │'center(title, 1 + cols*(w+1) ) -say '───────┼'center("" , 1 + cols*(w+1), '─') -found= 0; idx= 1 /*number of fortunate (so far) & index.*/ -!!.= 0; maxFN= 0 /*(stemmed) array of fortunate numbers*/ - do j=1 until found==n; pt= pp.j /*search for fortunate numbers in range*/ - pt= pp.j /*get the precalculated primorial prime*/ - do m=3 by 2; t= pt + m /*find M that satisfies requirement. */ - if !.t=='' then leave /*Is !.t prime? Then we found a good M*/ - end /*m*/ - if !!.m then iterate /*Fortunate # already found? Then skip*/ - !!.m= 1; found= found + 1 /*assign fortunate number; bump count.*/ - maxFN= max(maxFN, t) /*obtain max fortunate # for displaying*/ - end /*j*/ -$=; finds= 0 /*$: line of output; FINDS: count.*/ - do k=1 for maxFN; if \!!.k then iterate /*show the fortunate numbers we found. */ - finds= finds + 1 /*bump the count of numbers (for $). */ - c= commas(k) /*maybe add commas to the number. */ - $= $ right(c, max(w, length(c) ) ) /*add a nice prime ──► list, allow big#*/ - if found//cols\==0 then iterate /*have we populated a line of output? */ - say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */ - idx= idx + cols /*bump the index count for the output*/ - end /*k*/ - -if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/ -say '───────┴'center("" , 1 + cols*(w+1), '─') /*display the foot separator. */ -say -say 'Found ' commas(found) title -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */ - !.=0; !.2=; !.3=; !.5=; !.7=; !.11= /* " " " " semaphores. */ - #= 5; sq.#= @.#**2 /*squares of low primes.*/ - do j=@.#+2 by 2 to arg(1) /*find odd primes from here on. */ - parse var j '' -1 _; if _==5 then iterate /*J ÷ by 5 ? */ - if j//3==0 then iterate; if j//7==0 then iterate /*" " " 3?; J ÷ by 7 ? */ - do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ - if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j; sq.#= j*j; !.j= /*bump # of Ps; assign next P; P²; P# */ - end /*j*/; return diff --git a/Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx b/Task/Fortunate-numbers/REXX/fortunate-numbers.rexx similarity index 92% rename from Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx rename to Task/Fortunate-numbers/REXX/fortunate-numbers.rexx index 5d4aa0d250..d621367661 100644 --- a/Task/Fortunate-numbers/REXX/fortunate-numbers-2.rexx +++ b/Task/Fortunate-numbers/REXX/fortunate-numbers.rexx @@ -1,6 +1,9 @@ +-- 8 May 2025 include Settings -say version; say 'Fortunate numbers'; say +say 'FORTUNATE NUMBERS' +say version +say numeric digits 155 call GetPrimorials 75 call GenerateFortunate 75 @@ -21,7 +24,7 @@ arg x say 'Generate fortunate numbers...' work. = 0; m = 0; n = 0 do i = 1 to x - p = prmo.primorial.i + p = prmo.i do j = 3 by 2 m = m+1 if Prime(p+j) then @@ -57,5 +60,6 @@ return include Numbers include Sequences include Functions +include Special include Constants include Abend diff --git a/Task/Four-bit-adder/Ballerina/four-bit-adder.ballerina b/Task/Four-bit-adder/Ballerina/four-bit-adder.ballerina new file mode 100644 index 0000000000..b995469a4c --- /dev/null +++ b/Task/Four-bit-adder/Ballerina/four-bit-adder.ballerina @@ -0,0 +1,31 @@ +import ballerina/io; + +function xor(byte a, byte b) returns byte { + return a & (~b) | b & (~a); +} + +function ha(byte a, byte b) returns [byte, byte] { + return [xor(a, b), a & b]; +} + +function fa(byte a, byte b, byte c0) returns [byte, byte] { + var [sa, ca] = ha(a, c0); + var [s, cb] = ha(sa, b); + var c1 = ca | cb; + return [s, c1]; +} + +function add4(byte a3, byte a2, byte a1, byte a0, byte b3, byte b2, byte b1, byte b0) + returns [byte, byte, byte, byte, byte] { + var [s0, c0] = fa(a0, b0, 0); + var [s1, c1] = fa(a1, b1, c0); + var [s2, c2] = fa(a2, b2, c1); + var [s3, v] = fa(a3, b3, c2); + return [v, s3, s2, s1, s0]; +} + +public function main() { + // add 10+9 result should be [1, 0, 0, 1, 1] + var sum = add4(1, 0, 1, 0, 1, 0, 0, 1); + io:println(re `,`.replaceAll(sum.toString(), ", ")); +} diff --git a/Task/Four-bit-adder/EasyLang/four-bit-adder.easy b/Task/Four-bit-adder/EasyLang/four-bit-adder.easy index a7fb1f576f..0596b197e5 100644 --- a/Task/Four-bit-adder/EasyLang/four-bit-adder.easy +++ b/Task/Four-bit-adder/EasyLang/four-bit-adder.easy @@ -1,18 +1,18 @@ -proc xor a b . r . +proc xor a b &r . na = bitand bitnot a 1 nb = bitand bitnot b 1 r = bitor bitand a nb bitand b na . -proc half_add a b . s c . +proc half_add a b &s &c . xor a b s c = bitand a b . -proc full_add a b c . s g . +proc full_add a b c &s &g . half_add a c x y half_add x b s z g = bitor y z . -proc bit4add a4 a3 a2 a1 b4 b3 b2 b1 . s4 s3 s2 s1 c . +proc bit4add a4 a3 a2 a1 b4 b3 b2 b1 &s4 &s3 &s2 &s1 &c . full_add a1 b1 0 s1 c full_add a2 b2 c s2 c full_add a3 b3 c s3 c diff --git a/Task/Fractal-tree/EasyLang/fractal-tree.easy b/Task/Fractal-tree/EasyLang/fractal-tree.easy index 8fee6f444d..ef4681c547 100644 --- a/Task/Fractal-tree/EasyLang/fractal-tree.easy +++ b/Task/Fractal-tree/EasyLang/fractal-tree.easy @@ -1,18 +1,12 @@ color 555 -proc tree x y deg n . . - if n > 0 - linewidth n * 0.4 - move x y - x += cos deg * n * 1.3 * (randomf + 0.5) - y += sin deg * n * 1.3 * (randomf + 0.5) - line x y - tree x y deg - 20 n - 1 - tree x y deg + 20 n - 1 +proc tree x y angle depth . + glinewidth depth * 0.4 + xn = x + cos angle * depth * 1.4 * (randomf + 0.5) + yn = y + sin angle * depth * 1.4 * (randomf + 0.5) + gline x y xn yn + if depth > 1 + tree xn yn (angle - 20) (depth - 1) + tree xn yn (angle + 20) (depth - 1) . . -timer 0 -on timer - clear - tree 50 10 90 10 - timer 2 -. +tree 50 10 90 10 diff --git a/Task/Fractran/EasyLang/fractran.easy b/Task/Fractran/EasyLang/fractran.easy index 5ee0b75bf6..1fed677ff9 100644 --- a/Task/Fractran/EasyLang/fractran.easy +++ b/Task/Fractran/EasyLang/fractran.easy @@ -1,4 +1,4 @@ -proc fractran prog$ val limit . r[] . +func[] fractran prog$ val limit . for s$ in strsplit prog$ " " : n[][] &= number strsplit s$ "/" for n to limit r[] &= val @@ -8,19 +8,19 @@ proc fractran prog$ val limit . r[] . if i > len n[][] : break 1 val = val / n[i][2] * n[i][1] . + return r[] . p$ = "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" -fractran p$ 2 15 r[] -print r[] +print fractran p$ 2 15 # -proc sort . d[] . +proc sort &d[] . for i = 1 to len d[] - 1 for j = i + 1 to len d[] if d[j] < d[i] : swap d[j] d[i] . . . -fractran p$ 2 1000 r[] +r[] = fractran p$ 2 1000 sort r[] i = 1 prim = 2 diff --git a/Task/Fractran/Julia/fractran.jl b/Task/Fractran/Julia/fractran.jl index 7bd1303fe5..87f70c2989 100644 --- a/Task/Fractran/Julia/fractran.jl +++ b/Task/Fractran/Julia/fractran.jl @@ -1,29 +1,70 @@ -using Base.Iterators: filter, map, take -using Dates: now, seconds +using .Iterators, BenchmarkTools +using Primes: Factorization, factor -struct FRACTRAN - P::Vector{Rational{BigInt}} - i::BigInt +# type alias for abbreviation +Factors = Factorization{Int} + +# iterable stuct with parametric type polymorphism +struct Fractran{T} + program::Vector{@NamedTuple{num::T, den::T}} + input::Int + + # inner constructor + function Fractran{T}(program::Vector{Rational{Int}}, input::Int) where T + c = Dict(BigInt => identity, Factors => factor)[T] + new{T}([(num = c(f.num), den = c(f.den)) for f ∈ program], input) + end end -# a new method for the builtin function 'iterate' to make the Fractran program run -Base.iterate(ft::FRACTRAN, n = ft.i) = - for f in ft.P +# methods for Fractran with n::BigInt +Base.iterate(ft::Fractran{BigInt}, n = big(ft.input)) = + for f ∈ ft.program if iszero(n % f.den) n = n ÷ f.den * f.num return n, n end end -"lazy generation of Fractran output sequence" -out(ft::FRACTRAN) = map(trailing_zeros, filter(ispow2, ft)) +iters(ft::Fractran{BigInt}) = ft -"convenient Fractran scripting" -macro P_str(s) eval(Meta.parse(replace("[$s]", "/" => "//"))) end +output(ft::Fractran{BigInt}) = (trailing_zeros(n) for n ∈ ft if ispow2(n)) -primes = FRACTRAN(P"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) +# methods for Fractran with n::Factorization{Int} +Base.iterate(ft::Fractran{Factors}, n = factor(ft.input)) = + for f ∈ ft.program + if all(n[p] ≥ e for (p, e) ∈ f.den) + for (p, e) ∈ f.den n[p] -= e end + for (p, e) ∈ f.num n[p] += e end + return n, n + end + end -println("2, ", join(take(primes, 20), ", "), "...") -t = now() -join(stdout, take(out(primes), 25), ", ") -println("...\n25 primes in $(seconds(now() - t)) seconds") +iters(ft::Fractran{Factors}) = (prod(n) for n ∈ ft) + +output(ft::Fractran{Factors}) = (n[2] for n ∈ ft if + all((iszero(e) || (p == 2)) for (p, e) ∈ n)) + +# convenient Fractran scripting +macro ft_str(s::String) + eval(Meta.parse(replace("[$s]", "/" => "//"))) +end + +# instantiation of Fractran example generating prime numbers +primes(T) = Fractran{T}(ft"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) + +# Output including Benchmark +ilim = 20; plim = 45 + +function printout(T) + println("\n$ilim iterations and output of $plim prime numbers using ", T) + println(join(take(iters(primes(T)), ilim), ", "), "…") + join(stdout, take(output(primes(T)), plim), ", ") + print("…\nBenchmark: $plim primes in") +end + +printout(BigInt) +@btime collect(take(output(primes(BigInt)), plim)) + +printout(Factors) +@btime collect(take(output(primes(Factors)), plim)); diff --git a/Task/Fractran/Odin/fractran.odin b/Task/Fractran/Odin/fractran.odin new file mode 100644 index 0000000000..bae9287c2f --- /dev/null +++ b/Task/Fractran/Odin/fractran.odin @@ -0,0 +1,77 @@ +package main + +import "core:fmt" +import "core:os" +import "core:strconv" +import "core:strings" +import "core:text/match" +import "core:math" + + +main :: proc() { + // fmt.println(os.args) + + n:int + number:int + number_conv:bool + fracts:[dynamic]int + defer delete(fracts) + + n,number_conv = strconv.parse_int(os.args[1]) + assert(number_conv, "Number must be given in first place!") + assert(len(os.args)>1,"no command line arguments given") + + data:="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" + + ss := strings.split(string(data), " ") + defer delete(ss) + + + a: [dynamic]string + dummy:[]string + defer delete(a) + defer delete(dummy) + + for i in ss{ + dummy =strings.split(i,"/") + for j in dummy{ + // fmt.println(j) + + append_elem(&a,j) + } + } + + for k in a{ + // fmt.println(k) + number,number_conv = strconv.parse_int(k) + assert(number_conv, "Number must be given in program") + append_elem(&fracts,number) + } + + + // fmt.println(len(fracts)) + cond:int + buf: [256]byte + bb:int + end:=0 + fmt.println(n) + frac: for j:=0;j 0 then do - call Time('r'); r = Stirling(x); e = Format(Time('e'),,3) + call Time('r'); r = Stirling(x)+0; e = Format(Time('e'),,3) say 'Stirling' Format(x,4,1) r '('e 'seconds)' end end @@ -31,25 +34,25 @@ w = '-99.9 99.9' do i = 1 to Words(w) x = Word(w,i) numeric digits Min(60,n) - call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + call Time('r'); r = Gamma(x)+0; e = Format(Time('e'),,3) say 'Lanczos ' Format(x,4,1) r '('e 'seconds)' numeric digits n - call Time('r'); r = Gamma(x); e = Format(Time('e'),,3) + call Time('r'); r = Gamma(x)+0; e = Format(Time('e'),,3) say 'Spouge ' Format(x,4,1) r '('e 'seconds)' if x > 0 then do - call Time('r'); r = Stirling(x); e = Format(Time('e'),,3) + call Time('r'); r = Stirling(x)+0; e = Format(Time('e'),,3) say 'Stirling' Format(x,4,1) r '('e 'seconds)' end end exit Stirling: -/* Sterling */ procedure expose glob. fact. arg x return Sqrt(2*Pi()/x) * Power(x/e(),x) include Constants include Functions +include Special include Numbers include Abend diff --git a/Task/Gapful-numbers/Ballerina/gapful-numbers.ballerina b/Task/Gapful-numbers/Ballerina/gapful-numbers.ballerina new file mode 100644 index 0000000000..867bb7d72a --- /dev/null +++ b/Task/Gapful-numbers/Ballerina/gapful-numbers.ballerina @@ -0,0 +1,26 @@ +import ballerina/io; + +public function main() { + int[] starts = [100, 1e6, 1e7, 1e9, 7123]; + int[] counts = [30, 15, 15, 10, 25]; + foreach int i in 0..= 10 * pow { pow *= 10; } + } + io:println("\n"); + } +} diff --git a/Task/Gapful-numbers/EasyLang/gapful-numbers.easy b/Task/Gapful-numbers/EasyLang/gapful-numbers.easy index 3b1c7a2403..ef8893d1a1 100644 --- a/Task/Gapful-numbers/EasyLang/gapful-numbers.easy +++ b/Task/Gapful-numbers/EasyLang/gapful-numbers.easy @@ -1,12 +1,10 @@ func gapful n . m = n l = n mod 10 - while m >= 10 - m = m div 10 - . + while m >= 10 : m = m div 10 return if n mod (m * 10 + l) = 0 . -proc show n gaps . . +proc show n gaps . print "First " & gaps & " gapful numbers >= " & n while inc < gaps if gapful n = 1 diff --git a/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy b/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy index dac0cbf67d..3027f65812 100644 --- a/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy +++ b/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy @@ -1,39 +1,31 @@ -proc rref . m[][] . +proc rref &m[][] . nrow = len m[][] ncol = len m[1][] lead = 1 for r to nrow - if lead > ncol - return - . + if lead > ncol : return i = r while m[i][lead] = 0 i += 1 if i > nrow i = r lead += 1 - if lead > ncol - return - . + if lead > ncol : return . . swap m[i][] m[r][] m = m[r][lead] - for k to ncol - m[r][k] /= m - . + for k to ncol : m[r][k] /= m for i to nrow if i <> r m = m[i][lead] - for k to ncol - m[i][k] -= m * m[r][k] - . + for k to ncol : m[i][k] -= m * m[r][k] . . lead += 1 . . -proc inverse . mat[][] inv[][] . +proc inverse &mat[][] &inv[][] . inv[][] = [ ] ln = len mat[][] for i to ln @@ -43,9 +35,7 @@ proc inverse . mat[][] inv[][] . . aug[][] &= [ ] len aug[i][] 2 * ln - for j to ln - aug[i][j] = mat[i][j] - . + for j to ln : aug[i][j] = mat[i][j] aug[i][ln + i] = 1 . rref aug[][] diff --git a/Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js b/Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js new file mode 100644 index 0000000000..854bc332e7 --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/JavaScript/gauss-jordan-matrix-inversion.js @@ -0,0 +1,99 @@ +// Vector and matrix types +// In JavaScript, we'll use arrays directly + +function printMatrix(matrix, title) { + console.log(title); + for (const row of matrix) { + console.log(row.map(x => x.toString().padStart(10)).join('')); + } +} + +function createIdentityMatrix(n) { + const result = Array(n).fill().map(() => Array(n).fill(0)); + for (let i = 0; i < n; i++) { + result[i][i] = 1; + } + return result; +} + +function inverse(matrix) { + const n = matrix.length; + + // Check if it's a square matrix + for (const row of matrix) { + if (row.length !== n) { + throw new Error("Not a square matrix"); + } + } + + // Create identity matrix for the result + const b = createIdentityMatrix(n); + + // Create a copy of the input matrix + const a = matrix.map(row => [...row]); + + for (let k = 0; k < n; k++) { + let iMax = 0; + let max = -1; + + for (let i = k; i < n; i++) { + const row = a[i]; + + // Compute scale factor s = max abs in row + let s = -1; + for (let j = k; j < n; j++) { + const x = Math.abs(row[j]); + if (x > s) { + s = x; + } + } + + if (s === 0) { + throw new Error("Irregular matrix"); + } + + // Scale the abs used to pick the pivot + const abs = Math.abs(row[k]) / s; + if (abs > max) { + iMax = i; + max = abs; + } + } + + // Swap rows if needed + if (k !== iMax) { + [a[k], a[iMax]] = [a[iMax], a[k]]; + [b[k], b[iMax]] = [b[iMax], b[k]]; + } + + const akk = a[k][k]; + + for (let j = 0; j < n; j++) { + a[k][j] /= akk; + b[k][j] /= akk; + } + + for (let i = 0; i < n; i++) { + if (i !== k) { + const aik = a[i][k]; + for (let j = 0; j < n; j++) { + a[i][j] -= a[k][j] * aik; + b[i][j] -= b[k][j] * aik; + } + } + } + } + + return b; +} + +function main() { + const a = [[1, 2, 3], [4, 1, 6], [7, 8, 9]]; + printMatrix(inverse(a), "Inverse of A is:\n"); + + const b = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]]; + printMatrix(inverse(b), "Inverse of B is:\n"); +} + +// Run the main function +main(); diff --git a/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy b/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy index 12bd0ba26f..49718d4e90 100644 --- a/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy +++ b/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy @@ -1,4 +1,4 @@ -proc gauss_elim . a[][] b[] x[] . +proc gauss_elim &a[][] &b[] &x[] . n = len a[][] for i to n maxr = i diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d index a0e9db973f..adef3fcc8c 100644 --- a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-1.d @@ -1,13 +1,63 @@ -void main() { - import std.stdio, std.range, std.algorithm, std.string, permutations2; +import std.stdio; +import std.random; +import std.algorithm; +import std.range; - const pieces = "KQRrBbNN"; - alias I = indexOf; - auto starts = pieces.dup.permutations.filter!(p => - I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop constraint. - // King constraint. - ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) || - (I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r')))) - .map!toUpper.array.sort().uniq; - writeln(starts.walkLength, "\n", starts.front); +string[] ch960startPos() { + string[] rank = new string[8]; + + auto d = (size_t num) => uniform(0, num); + + auto emptySquares = () { + return rank.enumerate + .filter!(t => t.value is null) + .map!(t => t.index) + .array(); + }; + + // Place one Bishop << on a black square + rank[d(4) * 2] = "♗"; + + // Place the other Bishop << on a white square + rank[d(4) * 2 + 1] = "♗"; + + // Place the Queen << + auto empty = emptySquares(); + rank[empty[d(empty.length)]] = "♕"; + + // Place one Knight << + empty = emptySquares(); + rank[empty[d(empty.length)]] = "♘"; + + // Place the second Knight << + empty = emptySquares(); + rank[empty[d(empty.length)]] = "♘"; + + // Remaining positions: place 2 Rooks << and 1 King << + empty = emptySquares(); + empty.sort(); // Sort positions for easier logic + + size_t kingPosIndex = d(empty.length); + size_t kingPos = empty[kingPosIndex]; + + auto left = empty[0 .. kingPosIndex]; + auto right = empty[kingPosIndex + 1 .. $]; + + if (left.empty || right.empty) { + // Invalid setup, retry + return ch960startPos(); + } + + size_t rook1 = left[d(left.length)]; + size_t rook2 = right[d(right.length)]; + + rank[rook1] = "♖"; + rank[kingPos] = "♔"; + rank[rook2] = "♖"; + + return rank; +} + +void main() { + iota(10).each!(_ => writeln(ch960startPos().join(""))); } diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d index 420a99b0c8..a349f282e0 100644 --- a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-2.d @@ -1,11 +1,25 @@ -void main() { - import std.stdio, std.regex, std.range, std.algorithm, permutations2; +import std.stdio : writeln; +import std.random; +import std.array : join; +import std.string : indexOf, lastIndexOf; +import std.algorithm : nextPermutation; - immutable pieces = "KQRRBBNN"; - immutable bish = r"B(|..|....|......)B"; - immutable king = r"R.*K.*R"; - auto starts3 = permutations(pieces.dup) - .filter!(p => p.match(bish) && p.match(king)) - .array.sort().uniq; - writeln(starts3.walkLength, "\n", starts3.front); +void main() { + // The Pieces, no King at all but 3 Rooks! + auto pos = ["Q", "R", "R", "R", "B", "B", "N", "N"].randomShuffle; + + do { + auto candidate = pos.join(""); + + if (candidate.indexOf('B') % 2 != candidate.lastIndexOf('B') % 2) { + auto dupPos = pos.dup; + + // Promote middle Rook to King + dupPos[candidate[0..candidate.lastIndexOf('R')].lastIndexOf('R')] = "K"; + + dupPos.join("").writeln; // Output! + + return; + } + } while (pos.nextPermutation); } diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d index 5885e3bb3d..a0e9db973f 100644 --- a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-3.d @@ -1,13 +1,13 @@ void main() { - import std.stdio, std.random, std.array, std.range; + import std.stdio, std.range, std.algorithm, std.string, permutations2; - // Subsequent order unchanged by insertions. - auto start = "RKR".dup; - foreach (immutable piece; "QNN") - start.insertInPlace(uniform(0, start.length), piece); - - immutable bishpos = uniform(0, start.length); - start.insertInPlace(bishpos, 'B'); - start.insertInPlace(iota(bishpos % 2, start.length, 2)[uniform(0,$)], 'B'); - start.writeln; + const pieces = "KQRrBbNN"; + alias I = indexOf; + auto starts = pieces.dup.permutations.filter!(p => + I(p, 'B') % 2 != I(p, 'b') % 2 && // Bishop constraint. + // King constraint. + ((I(p, 'r') < I(p, 'K') && I(p, 'K') < I(p, 'R')) || + (I(p, 'R') < I(p, 'K') && I(p, 'K') < I(p, 'r')))) + .map!toUpper.array.sort().uniq; + writeln(starts.walkLength, "\n", starts.front); } diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-4.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-4.d new file mode 100644 index 0000000000..420a99b0c8 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-4.d @@ -0,0 +1,11 @@ +void main() { + import std.stdio, std.regex, std.range, std.algorithm, permutations2; + + immutable pieces = "KQRRBBNN"; + immutable bish = r"B(|..|....|......)B"; + immutable king = r"R.*K.*R"; + auto starts3 = permutations(pieces.dup) + .filter!(p => p.match(bish) && p.match(king)) + .array.sort().uniq; + writeln(starts3.walkLength, "\n", starts3.front); +} diff --git a/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-5.d b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-5.d new file mode 100644 index 0000000000..5885e3bb3d --- /dev/null +++ b/Task/Generate-Chess960-starting-position/D/generate-chess960-starting-position-5.d @@ -0,0 +1,13 @@ +void main() { + import std.stdio, std.random, std.array, std.range; + + // Subsequent order unchanged by insertions. + auto start = "RKR".dup; + foreach (immutable piece; "QNN") + start.insertInPlace(uniform(0, start.length), piece); + + immutable bishpos = uniform(0, start.length); + start.insertInPlace(bishpos, 'B'); + start.insertInPlace(iota(bishpos % 2, start.length, 2)[uniform(0,$)], 'B'); + start.writeln; +} diff --git a/Task/Generate-Chess960-starting-position/Delphi/generate-chess960-starting-position.pas b/Task/Generate-Chess960-starting-position/Delphi/generate-chess960-starting-position.pas new file mode 100644 index 0000000000..79f51aab19 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Delphi/generate-chess960-starting-position.pas @@ -0,0 +1,41 @@ +program byconstruct; + +{$APPTYPE CONSOLE} + +uses + System.SysUtils, System.Math, Generics.Collections; + +var + start: TList; + piece: Char; + bishpos: Integer; + resultString: String; + +begin + Randomize; + + start := TList.Create; + + try + start.AddRange(['R', 'K', 'R']); // << + + for piece in ['Q', 'N', 'N'] do + start.Insert(Random(start.Count), piece); // << + + bishpos := Random(start.Count); + start.Insert(bishpos, 'B'); // << + + if bishpos mod 2 = 0 then + start.Insert(Random(start.Count div 2) * 2, 'B') // << + else + start.Insert(Random((start.Count - bishpos + 1) div 2) * 2 + bishpos, 'B'); // << + + // Convert TList to String + resultString := String.Create(start.ToArray); + + WriteLn(resultString); + + finally + start.Free; + end; +end. diff --git a/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy b/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy index 80dca8ffad..dd1be571b9 100644 --- a/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy +++ b/Task/Generate-Chess960-starting-position/EasyLang/generate-chess960-starting-position.easy @@ -1,5 +1,5 @@ len t$[] 8 -proc randins c$ l r . pos . +proc randins c$ l r &pos . repeat pos = random (r - l + 1) + l - 1 until t$[pos] = "" diff --git a/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position-3.rs b/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position-3.rs new file mode 100644 index 0000000000..fc4dda4049 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position-3.rs @@ -0,0 +1,36 @@ +use rand::seq::SliceRandom; +use rand::rng; + +fn generate_chess960() -> String { + let mut rng = rng(); + + loop { + let mut pieces = vec!['♛', '♜', '♜', '♜', '♝', '♝', '♞', '♞']; + pieces.shuffle(&mut rng); + + let bishops: Vec = pieces.iter() + .enumerate() + .filter(|&(_, p)| *p == '♝') + .map(|(i, _)| i) + .collect(); + + if bishops.len() == 2 && bishops[0] % 2 != bishops[1] % 2 { + let mut rooks: Vec = pieces.iter() + .enumerate() + .filter(|&(_, p)| *p == '♜') + .map(|(i, _)| i) + .collect(); + + rooks.sort(); // Sort to locate the middle rook + let middle_rook = rooks[1]; // Promote the second rook to King + pieces[middle_rook] = '♚'; // Replace middle rook with King + + return pieces.iter().collect(); + } + } +} + +fn main() { + let position = generate_chess960(); + println!("Chess960 Position: {position}"); +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Objeck/generate-lower-case-ascii-alphabet.objeck b/Task/Generate-lower-case-ASCII-alphabet/Objeck/generate-lower-case-ascii-alphabet.objeck new file mode 100644 index 0000000000..dee3ea9202 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Objeck/generate-lower-case-ascii-alphabet.objeck @@ -0,0 +1,7 @@ +function : Main(args : String[]) ~ Nil { + buffer := ""; + for(i := 'a'; i <= 'z'; i += 1;) { + buffer += i->As(Char); + }; + buffer->PrintLine(); +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet.rs b/Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet-1.rs similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet.rs rename to Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet-1.rs diff --git a/Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet-2.rs b/Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet-2.rs new file mode 100644 index 0000000000..e73620e114 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Rust/generate-lower-case-ascii-alphabet-2.rs @@ -0,0 +1 @@ +'a'..='z' diff --git a/Task/Generator-Exponential/Tcl/generator-exponential.tcl b/Task/Generator-Exponential/Tcl/generator-exponential-1.tcl similarity index 100% rename from Task/Generator-Exponential/Tcl/generator-exponential.tcl rename to Task/Generator-Exponential/Tcl/generator-exponential-1.tcl diff --git a/Task/Generator-Exponential/Tcl/generator-exponential-2.tcl b/Task/Generator-Exponential/Tcl/generator-exponential-2.tcl new file mode 100644 index 0000000000..fba5346de8 --- /dev/null +++ b/Task/Generator-Exponential/Tcl/generator-exponential-2.tcl @@ -0,0 +1,13 @@ +package require Tcl 8.6 +package require generator + +generator define range {n m} { + for {set i $n} {$i <= $m} {incr i} { + generator yield $i + } +} + +generator foreach x [range 22 35] { + puts -nonewline stdout "${x} " +} +puts stdout "" diff --git a/Task/Generator-Exponential/Tcl/generator-exponential-3.tcl b/Task/Generator-Exponential/Tcl/generator-exponential-3.tcl new file mode 100644 index 0000000000..f3b6c68265 --- /dev/null +++ b/Task/Generator-Exponential/Tcl/generator-exponential-3.tcl @@ -0,0 +1,54 @@ +#!/usr/bin/env tclsh + +package require generator + +generator define idx_range {n m} { + for {set i $n} {$i < [expr $m -1]} {incr i} { generator yield $i } +} + +generator define mth_power {m} { + set n 0 + while {1} { + generator yield [expr $n ** $m] + incr n + } +} + +generator define squares {} { + + generator for x [mth_power 2] { + generator yield $x + } +} + +generator define cubes {} { + + generator for x [mth_power 3] { + generator yield $x + } +} + +set acc {} ; # accumulator + +set comm {} ; # common result + +set limit 50 + +# run both generators concurrently + +generator foreach x [squares] y [cubes] { + + lappend acc $y + + if { ! [expre {$x in $acc}] } { lappend comm $x } + + if { [llength $comm] > $limit } {break} +} + +# elements 20.. 30 +set results [lrange $comm 19 29] ; # list range + +generator foreach idx [idx_range 20 30] { + set x [lindex $comm $idx] + puts "$x" +} diff --git a/Task/Generator-Exponential/Ursalang/generator-exponential.ursa b/Task/Generator-Exponential/Ursalang/generator-exponential.ursa index c1d70cc2d5..653aea0e9e 100644 --- a/Task/Generator-Exponential/Ursalang/generator-exponential.ursa +++ b/Task/Generator-Exponential/Ursalang/generator-exponential.ursa @@ -26,7 +26,6 @@ let filtered = gen(s1, s2) { } } - let squares = powers(2) let cubes = powers(3) let f = filtered(squares, cubes) diff --git a/Task/Globally-replace-text-in-several-files/BQN/globally-replace-text-in-several-files.bqn b/Task/Globally-replace-text-in-several-files/BQN/globally-replace-text-in-several-files.bqn new file mode 100644 index 0000000000..0c25af9969 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/BQN/globally-replace-text-in-several-files.bqn @@ -0,0 +1,9 @@ +#!/usr/bin/env bqn + +_onfile ← {𝕩 •FChars (𝕨 𝔽 •FChars⎊"" 𝕩)} + +FindReplace ← {(⊣-⊸⌽(1⊑𝕨)∾(≠⊑𝕨)↓⊣⌽⊢)´𝕩∾⟜<˜/(⊑𝕨)⍷𝕩} + +files ← •wdpath⊸•file.At¨ •args + +"Goodbye London!"‿"Hello New York!"⊸(FindReplace _onfile)¨ files diff --git a/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy b/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy index 666e90ef38..1a4a2b23d6 100644 --- a/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy +++ b/Task/Goldbachs-comet/EasyLang/goldbachs-comet.easy @@ -1,30 +1,22 @@ func isprim n . - if n mod 2 = 0 and n > 2 - return 0 - . + if n mod 2 = 0 and n > 2 : return 0 i = 3 sq = sqrt n while i <= sq - if n mod i = 0 - return 0 - . + if n mod i = 0 : return 0 i += 2 . return 1 . func goldbach n . for i = 2 to n div 2 - if isprim i = 1 - cnt += isprim (n - i) - . + if isprim i = 1 : cnt += isprim (n - i) . return cnt . -numfmt 0 3 +numfmt 3 0 for n = 4 step 2 to 202 write goldbach n - if n mod 20 = 2 - print "" - . + if n mod 20 = 2 : print "" . print goldbach 1000000 diff --git a/Task/Goldbachs-comet/Go/goldbachs-comet.go b/Task/Goldbachs-comet/Go/goldbachs-comet.go new file mode 100644 index 0000000000..4c8b45dc6c --- /dev/null +++ b/Task/Goldbachs-comet/Go/goldbachs-comet.go @@ -0,0 +1,63 @@ +package main + +import ( + "fmt" + "math" +) + +var primes []bool + +func initialisePrimes(limit int) { + primes = make([]bool, limit) + for i := 2; i < limit; i++ { + primes[i] = true + } + + sqrtLimit := int(math.Sqrt(float64(limit))) + for n := 2; n < sqrtLimit; n++ { + if primes[n] { + for k := n * n; k < limit; k += n { + primes[k] = false + } + } + } +} + +func goldbachFunction(number int) (int, error) { + if number <= 2 || number%2 == 1 { + return 0, fmt.Errorf("argument must be even and greater than 2: %d", number) + } + + result := 0 + for i := 1; i <= number/2; i++ { + if primes[i] && primes[number-i] { + result++ + } + } + return result, nil +} + +func main() { + initialisePrimes(2000000) + + fmt.Println("The first 100 Goldbach numbers:") + for n := 2; n < 102; n++ { + value, err := goldbachFunction(2 * n) + if err != nil { + fmt.Printf("Error: %v\n", err) + continue + } + fmt.Printf("%3d", value) + if n%10 == 1 { + fmt.Println() + } + } + + fmt.Println("\nThe 1,000,000th Goldbach number =", func() string { + value, err := goldbachFunction(1000000) + if err != nil { + return fmt.Sprintf("Error: %v", err) + } + return fmt.Sprintf("%d", value) + }()) +} diff --git a/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx b/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx index db599de5d4..6090954e96 100644 --- a/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx +++ b/Task/Goldbachs-comet/REXX/goldbachs-comet.rexx @@ -1,6 +1,9 @@ +-- 22 Mar 2025 include Settings -say version; say 'Goldbach''s comet'; say +say 'GOLDBACH''S COMET' +say version +say numeric digits 7 call GetPrimes call ShowFirst100 @@ -8,7 +11,7 @@ call ShowMillion exit GetPrimes: -procedure expose prim. +procedure expose prim. flag. call Time('r') say 'Collect Primes up to 1000000...' call Primes(1e6) @@ -17,7 +20,7 @@ say return ShowFirst100: -procedure expose prim. +procedure expose prim. flag. call Time('r') say 'First 100 values...' do i = 4 by 2 to 202 @@ -30,22 +33,22 @@ say return ShowMillion: -procedure expose prim. +procedure expose prim. flag. call Time('r') -say 'G(1000000)...' +say 'g(1000000)...' say Goldbach(1e6) say Time('e')/1 'seconds' say return Goldbach: -procedure expose prim. +procedure expose prim. flag. arg x y = 0 do i = 2 to x%2 - if prim.flag.i then do + if flag.i then do j = x-i - if prim.flag.j then do + if flag.j then do y = y+1 end end diff --git a/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy b/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy index 66bf65792e..c5d55953a8 100644 --- a/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy +++ b/Task/Golden-ratio-Convergence/EasyLang/golden-ratio-convergence.easy @@ -5,7 +5,7 @@ repeat phi0 = phi iter += 1 . -numfmt 10 0 +numfmt 0 10 print "Iterations: " & iter print "Result: " & phi print "Error: " & phi - (1 + sqrt 5) / 2 diff --git a/Task/Gotchas/C-sharp/gotchas.cs b/Task/Gotchas/C-sharp/gotchas.cs new file mode 100644 index 0000000000..0a88a5fcdf --- /dev/null +++ b/Task/Gotchas/C-sharp/gotchas.cs @@ -0,0 +1,18 @@ +using System.Diagnostics; + + +// Methods that return values and don't modify the object + +int[] arr = [1, 2, 3, 4, 5]; +arr.Reverse(); +Console.WriteLine(string.Join(", ", arr)); + + +// Tasks are not threads! There are not 50 threads here even though there are 50 tasks. +// See https://blog.stephencleary.com/2013/11/there-is-no-thread.html + +Console.WriteLine(Process.GetCurrentProcess().Threads.Count); +Task[] tasks = [.. Enumerable.Range(0, 50).Select(i => Task.Delay(1000))]; +Console.WriteLine(Process.GetCurrentProcess().Threads.Count); +Task.WaitAll(tasks); +Console.WriteLine(Process.GetCurrentProcess().Threads.Count); diff --git a/Task/Graph-colouring/FreeBASIC/graph-colouring.basic b/Task/Graph-colouring/FreeBASIC/graph-colouring.basic new file mode 100644 index 0000000000..dbead294ee --- /dev/null +++ b/Task/Graph-colouring/FreeBASIC/graph-colouring.basic @@ -0,0 +1,149 @@ +Const tests As String = "0-1 1-2 2-0 3" & Chr(10) & _ +"1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7" & Chr(10) & _ +"1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6" & Chr(10) & _ +"1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7" + +Sub Colour(links() As Integer, nodeCount As Integer, colours() As Integer, _ + soln() As Integer, Byref best As Integer, sgte As Integer, used As Integer = 0) + + Dim As Integer i, c = 1 + Dim As Integer tmpColours(nodeCount - 1) + + For i = 0 To nodeCount - 1 + tmpColours(i) = colours(i) + Next + + While c <= best + Dim As Boolean avail = True + For i = 0 To nodeCount - 1 + If links(sgte, i) = 1 Andalso tmpColours(i) = c Then + avail = False + Exit For + End If + Next + + If avail Then + tmpColours(sgte) = c + Dim As Integer newused = used + If c > used Then newused = c + + If sgte < nodeCount - 1 Then + Colour(links(), nodeCount, tmpColours(), soln(), best, sgte + 1, newused) + Elseif newused < best Then + best = newused + For i = 0 To nodeCount - 1 + soln(i) = tmpColours(i) + Next + End If + End If + c += 1 + Wend +End Sub + +Function GetNodeIndex(nodeMap() As String, nodeCount As Integer, nodeName As String) As Integer + For i As Integer = 0 To nodeCount - 1 + If nodeMap(i) = nodeName Then Return i + Next + Return -1 +End Function + +Sub main() + Dim As String testLines(3) + Dim As Integer lineCount = 0, posic = 1, nextPos + + ' Split the test chain into lines + Do + nextPos = Instr(posic, tests, Chr(10)) + If nextPos = 0 Then + testLines(lineCount) = Mid(tests, posic) + lineCount += 1 + Exit Do + Else + testLines(lineCount) = Mid(tests, posic, nextPos - posic) + lineCount += 1 + posic = nextPos + 1 + End If + Loop + + For t As Integer = 0 To 3 + Dim As String linea = testLines(t) + Dim As String nodeMap(20) + Dim As Integer nodeCount = 0 + Dim As String token + posic = 1 + + Do + If posic > Len(linea) Then Exit Do + + nextPos = Instr(posic, linea, " ") + If nextPos = 0 Then nextPos = Len(linea) + 1 + + token = Mid(linea, posic, nextPos - posic) + posic = nextPos + 1 + + Dim As Integer dashPos = Instr(token, "-") + If dashPos > 0 Then + Dim As String node1 = Left(token, dashPos - 1) + Dim As String node2 = Mid(token, dashPos + 1) + + If GetNodeIndex(nodeMap(), nodeCount, node1) = -1 Then + nodeMap(nodeCount) = node1 + nodeCount += 1 + End If + + If GetNodeIndex(nodeMap(), nodeCount, node2) = -1 Then + nodeMap(nodeCount) = node2 + nodeCount += 1 + End If + Else + If GetNodeIndex(nodeMap(), nodeCount, token) = -1 Then + nodeMap(nodeCount) = token + nodeCount += 1 + End If + End If + Loop + + Dim As Integer links(nodeCount - 1, nodeCount - 1) + Dim As Integer edgeCount = 0 + + posic = 1 + Do + If posic > Len(linea) Then Exit Do + + nextPos = Instr(posic, linea, " ") + If nextPos = 0 Then nextPos = Len(linea) + 1 + + token = Mid(linea, posic, nextPos - posic) + posic = nextPos + 1 + + Dim As Integer dashPos = Instr(token, "-") + If dashPos > 0 Then + Dim As String node1 = Left(token, dashPos - 1) + Dim As String node2 = Mid(token, dashPos + 1) + + Dim As Integer idx1 = GetNodeIndex(nodeMap(), nodeCount, node1) + Dim As Integer idx2 = GetNodeIndex(nodeMap(), nodeCount, node2) + + links(idx1, idx2) = 1 + links(idx2, idx1) = 1 + edgeCount += 1 + End If + Loop + + Dim As Integer colours(nodeCount - 1), soln(nodeCount - 1) + Dim As Integer best = nodeCount + + Colour(links(), nodeCount, colours(), soln(), best, 0) + + Print "test" & t + 1 & ": " & nodeCount & " nodes, " & edgeCount & " edges, " & best & " colours:"; + + For i As Integer = 0 To nodeCount - 1 + Print soln(i); + Next + Print + Next +End Sub + +main() + +Sleep diff --git a/Task/Graph-colouring/JavaScript/graph-colouring.js b/Task/Graph-colouring/JavaScript/graph-colouring.js new file mode 100644 index 0000000000..2da345b834 --- /dev/null +++ b/Task/Graph-colouring/JavaScript/graph-colouring.js @@ -0,0 +1,222 @@ +// Equivalent to: +// #include +// #include +const allColours = ["PINK", "ORANGE", "CYAN", "YELLOW", "RED", "GREEN", "BLUE"]; + +// Equivalent to: +// class Node { ... }; +class Node { + constructor(id, saturation, colour) { + this.id = id; // Equivalent to int32_t id + this.saturation = saturation; // Equivalent to int32_t saturation + this.colour = colour; // Equivalent to std::string colour + this.excludedFromSearch = false; // Equivalent to bool excluded_from_search + } + + // The default constructor Node() : id(0), ... is handled implicitly in how we create nodes in the Map. + // If a key doesn't exist, Map.get() returns undefined, we explicitly use Map.set() to create nodes. +} + +// Equivalent to: +// int main() { ... } +function main() { + // Equivalent to: + // std::map graph; + // In JavaScript, Map keys are ordered by insertion or can be iterated over, + // but there's no built-in custom comparator for sorted access like std::map. + // However, the algorithm iterates through *all* map entries to find the max saturation node, + // so the map's internal order doesn't affect the result. + let graph = new Map(); // Map + + // Equivalent to: + // std::map, decltype([](const int32_t& a, const int32_t& b) { return a < b; })> neighbours; + // Similar to graph, Set doesn't guarantee element order like std::set, + // but neighbor order isn't relevant to the coloring logic. + let neighbours = new Map(); // Map> + + // Equivalent to: + // const std::vector graph_representations = { ... }; + const graphRepresentations = [ + "0-1 1-2 2-0 3", + "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7", + "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6", + "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7" + ]; + + // Equivalent to: + // for ( const std::string& graph_representation : graph_representations ) { ... } + for (const graphRepresentation of graphRepresentations) { + graph.clear(); + neighbours.clear(); + + // Equivalent to: + // std::stringstream stream(graph_representation); + // std::string element; + // while ( stream >> element ) { ... } + const elements = graphRepresentation.split(/\s+/); // Split string by one or more whitespace characters + for (const element of elements) { + if (element === "") continue; // Skip empty strings that might result from multiple spaces + + // Equivalent to: if ( element.find("-") != std::string::npos ) { ... } + if (element.includes("-")) { + const parts = element.split("-"); + // Equivalent to: const int32_t id1 = element[0] - '0'; + const id1 = parseInt(parts[0], 10); + // Equivalent to: const int32_t id2 = element[element.length() - 1] - '0'; + const id2 = parseInt(parts[parts.length - 1], 10); // Use last part, robust for potential future formats like 10-11 + + // Ensure nodes exist in the graph map. + // Equivalent to: if ( ! graph.contains(id1) ) { graph[id1] = Node(id1, 0, "NO_COLOUR"); } + if (!graph.has(id1)) { + graph.set(id1, new Node(id1, 0, "NO_COLOUR")); + } + // C++ `Node node1 = graph[id1];` gets a *copy*. In JS, graph.get(id1) gets a *reference*. + // We don't need to store the reference here just yet as we only needed to ensure the node exists. + + // Equivalent to: if ( ! graph.contains(id2) ) { graph[id2] = Node(id2, 0, "NO_COLOUR"); } + if (!graph.has(id2)) { + graph.set(id2, new Node(id2, 0, "NO_COLOUR")); + } + // C++ `Node node2 = graph[id2];` + + // Ensure neighbor sets exist and add neighbors. + // Equivalent to: neighbours[id1].emplace(id2); + if (!neighbours.has(id1)) { + neighbours.set(id1, new Set()); // Equivalent to std::set + } + neighbours.get(id1).add(id2); // Equivalent to emplace + + // Equivalent to: neighbours[id2].emplace(id1); + if (!neighbours.has(id2)) { + neighbours.set(id2, new Set()); + } + neighbours.get(id2).add(id1); + + } else { // Handle isolated nodes (e.g., "3") + // Equivalent to: const int32_t id = element[0] - '0'; + const id = parseInt(element, 10); // Parse the whole element as an ID + + // Equivalent to: if ( ! graph.contains(id) ) { graph[id] = Node(id, 0, "NO_COLOUR"); } + if (!graph.has(id)) { + graph.set(id, new Node(id, 0, "NO_COLOUR")); + } + } + } + + // Graph Coloring Loop (DSatur-like heuristic) + // Equivalent to: for ( uint64_t i = 0; i < graph.size(); ++i ) { ... } + // This loop structure implies that each node is processed exactly once + // because one node is marked excluded_from_search in each iteration. + for (let i = 0; i < graph.size; ++i) { + let maxNodeId = -1; + let maxSaturation = -1; + + // Find the node with the maximum saturation among those not yet colored. + // Equivalent to: for ( const auto& [key, value] : graph ) { ... } + for (const [key, node] of graph) { + // Equivalent to: if ( ! value.excluded_from_search && value.saturation > max_saturation ) { ... } + // If multiple nodes have the same max saturation, the one encountered first in the map iteration order is chosen. + if (!node.excludedFromSearch && node.saturation > maxSaturation) { + maxSaturation = node.saturation; + maxNodeId = key; + } + } + + // If maxNodeId is still -1, it means no unexcluded node was found. + // This shouldn't happen until all nodes are processed due to the loop count. + if (maxNodeId === -1) { + // Should only happen if the graph was empty or already fully excluded, + // which the outer loop count should prevent prematurely. + continue; // Skip this iteration if no node found. + } + + // Find colours used by neighbours of the selected node. + // Equivalent to: std::unordered_set colours_used; + const coloursUsed = new Set(); // Use Set for efficient `has` check + + // Equivalent to: for ( const int32_t& neighbour : neighbours[max_node_id] ) { ... } + // Get the set of neighbor IDs for the selected node. Handle case where node has no neighbors entry. + const neighborIdsOfSelected = neighbours.get(maxNodeId) || new Set(); + for (const neighbourId of neighborIdsOfSelected) { + // Get the neighbor node object from the graph map + const neighbourNode = graph.get(neighbourId); + // Check if the neighbor node exists in the graph and add its color to the set + if (neighbourNode) { + coloursUsed.add(neighbourNode.colour); + } + } + + // Find the smallest available colour. + // Equivalent to: std::string min_colour; + let minColour = ""; + // Equivalent to: for ( const std::string& colour : all_colours ) { ... } + for (const colour of allColours) { + // Equivalent to: if ( ! colours_used.contains(colour) ) { ... } + if (!coloursUsed.has(colour)) { + minColour = colour; + break; // Found the first available colour, stop searching. + } + } + + // Assign colour to the selected node and mark it as excluded. + // Equivalent to: graph[max_node_id].excluded_from_search = true; + // Equivalent to: graph[max_node_id].colour = min_colour; + const selectedNode = graph.get(maxNodeId); // Get the reference to the node object + selectedNode.excludedFromSearch = true; + selectedNode.colour = minColour; + + // Update saturation of neighbours. + // Equivalent to: for ( int32_t neighbour : neighbours[max_node_id] ) { ... } + for (const neighbourId of neighborIdsOfSelected) { + const neighbourNode = graph.get(neighbourId); + // Equivalent to: if ( graph[neighbour].colour == "NO_COLOUR" ) { ... } + // C++ logic: only update saturation if the neighbour is still uncolored. + // Set saturation to the number of *distinct colors* used by the *selected node's* neighbors + // *at the moment the selected node was processed*. + if (neighbourNode && neighbourNode.colour === "NO_COLOUR") { + neighbourNode.saturation = coloursUsed.size; // Uses the size calculated above + } + } + // Note: This saturation update logic is a direct translation of the C++ code. + // A more standard DSatur might update saturation differently (e.g., incrementing + // the saturation of *all* uncolored neighbors if the newly assigned color is new to *their* neighborhood). + // We adhere to the C++ code's exact implementation. + } + + // Output the results for the colored graph. + // Equivalent to: std::unordered_set graph_colours; + const graphColours = new Set(); // Use Set to count unique colors + + // Equivalent to: for ( const auto& [key, value] : graph ) { ... } + // Iterate over the graph map which now contains the final colored nodes. + for (const [key, node] of graph) { + // Equivalent to: graph_colours.emplace(value.colour); + graphColours.add(node.colour); + + // Equivalent to: std::cout << "Node " << key << ": colour = " + value.colour; + let output = `Node ${key}: colour = ${node.colour}`; + + // Equivalent to: if ( ! neighbours[key].empty() ) { ... } + const neighborIds = neighbours.get(key) || new Set(); // Get neighbors for the current node key + if (neighborIds.size > 0) { + // Equivalent to: std::cout << std::string(8 - value.colour.length(), ' ') << "neighbours = "; + // Calculate padding for alignment based on C++ padding (8 - color length) + const padding = ' '.repeat(Math.max(0, 8 - node.colour.length)); + output += `${padding}neighbours = `; + + // Equivalent to: for ( const int32_t& neighbour : neighbours[key] ) { std::cout << neighbour << " "; } + // Convert the Set of neighbor IDs to an Array and join them with spaces. + const neighborList = Array.from(neighborIds).join(" "); + output += neighborList; + } + // Equivalent to: std::cout << std::endl; + console.log(output); + } + // Equivalent to: std::cout << "Number of colours used: " << graph_colours.size() << std::endl << std::endl; + console.log(`Number of colours used: ${graphColours.size}`); + console.log(""); // Add an extra newline as in the C++ output + } +} + +// Execute the main function +main(); diff --git a/Task/Graph-colouring/Rust/graph-colouring.rs b/Task/Graph-colouring/Rust/graph-colouring.rs new file mode 100644 index 0000000000..5d71bbc098 --- /dev/null +++ b/Task/Graph-colouring/Rust/graph-colouring.rs @@ -0,0 +1,134 @@ +use std::collections::{HashMap, HashSet}; + +const ALL_COLOURS: [&str; 7] = ["PINK", "ORANGE", "CYAN", "YELLOW", "RED", "GREEN", "BLUE"]; + +#[derive(Debug, Clone)] +struct Node { + id: i32, + saturation: i32, + colour: String, + excluded_from_search: bool, +} + +impl Node { + fn new(id: i32, saturation: i32, colour: String) -> Self { + Node { + id, + saturation, + colour, + excluded_from_search: false, + } + } + + fn default() -> Self { + Node { + id: 0, + saturation: 0, + colour: "NO_COLOUR".to_string(), + excluded_from_search: false, + } + } +} + +fn main() { + let graph_representations: [&str; 4] = [ + "0-1 1-2 2-0 3", + "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7", + "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6", + "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7", + ]; + + for graph_representation in graph_representations { + let mut graph: HashMap = HashMap::new(); + let mut neighbours: HashMap> = HashMap::new(); + + for element in graph_representation.split_whitespace() { + if element.contains("-") { + let parts: Vec<&str> = element.split("-").collect(); + let id1: i32 = parts[0].parse().unwrap(); + let id2: i32 = parts[1].parse().unwrap(); + + if !graph.contains_key(&id1) { + graph.insert(id1, Node::new(id1, 0, "NO_COLOUR".to_string())); + } + //let node1 = graph.get(&id1).unwrap().clone(); // No need to clone + + if !graph.contains_key(&id2) { + graph.insert(id2, Node::new(id2, 0, "NO_COLOUR".to_string())); + } + //let node2 = graph.get(&id2).unwrap().clone(); // No need to clone + + neighbours.entry(id1).or_insert(HashSet::new()).insert(id2); + neighbours.entry(id2).or_insert(HashSet::new()).insert(id1); + } else { + let id: i32 = element.parse().unwrap(); + if !graph.contains_key(&id) { + graph.insert(id, Node::new(id, 0, "NO_COLOUR".to_string())); + } + } + } + + for _ in 0..graph.len() { + let mut max_node_id: i32 = -1; + let mut max_saturation: i32 = -1; + + for (&key, value) in &graph { + if !value.excluded_from_search && value.saturation > max_saturation { + max_saturation = value.saturation; + max_node_id = key; + } + } + + let mut colours_used: HashSet = HashSet::new(); + if let Some(neighbors) = neighbours.get(&max_node_id) { + for &neighbour in neighbors { + if let Some(neighbor_node) = graph.get(&neighbour) { + colours_used.insert(neighbor_node.colour.clone()); + } + } + } + + let mut min_colour = String::new(); + for &colour in &ALL_COLOURS { + if !colours_used.contains(colour) { + min_colour = colour.to_string(); + break; + } + } + + if let Some(node) = graph.get_mut(&max_node_id) { + node.excluded_from_search = true; + node.colour = min_colour.clone(); + } + + if let Some(neighbors) = neighbours.get(&max_node_id) { + for &neighbour in neighbors { + if let Some(neighbor_node) = graph.get_mut(&neighbour) { + if neighbor_node.colour == "NO_COLOUR" { + neighbor_node.saturation = colours_used.len() as i32; + } + } + } + } + } + + let mut graph_colours: HashSet = HashSet::new(); + for (&key, value) in &graph { + graph_colours.insert(value.colour.clone()); + print!("Node {}: colour = {}", key, value.colour); + + if let Some(neighbors) = neighbours.get(&key) { + if !neighbors.is_empty() { + print!("{}", " ".repeat(8 - value.colour.len())); + print!("neighbours = "); + for &neighbour in neighbors { + print!("{} ", neighbour); + } + } + } + println!(); + } + println!("Number of colours used: {}", graph_colours.len()); + println!(); + } +} diff --git a/Task/Gray-code/SETL/gray-code.setl b/Task/Gray-code/SETL/gray-code.setl new file mode 100644 index 0000000000..e5d368056b --- /dev/null +++ b/Task/Gray-code/SETL/gray-code.setl @@ -0,0 +1,29 @@ +program gray_code; + loop for n in [0..31] do + print( + lpad(str n, 2) + ": " + + lpad(bits n, 5) + " => " + + lpad(bits(g := gray_encode(n)), 5) + " => " + + lpad(bits(d := gray_decode(g)), 5) + ": " + + lpad(str d, 2) + ); + end loop; + + proc gray_encode(n); + return n bit_xor (n div 2); + end proc; + + proc gray_decode(n); + loop + init r := 0; + step n div:= 2; + until n=0 do r bit_xor:= n; + end loop; + return r; + end proc; + + op bits(n); + b := '' +/ [[str (n mod 2), n div:=2](1) : until n=0]; + return reverse(b); + end op; +end program; diff --git a/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 b/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 index 229762871a..ed33411db2 100644 --- a/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 +++ b/Task/Grayscale-image/M2000-Interpreter/grayscale-image.m2000 @@ -1,201 +1,202 @@ Module P6P5 { - Function Bitmap { - def x as long, y as long, Import as boolean, P5 as boolean - If match("NN") then { - Read x, y - } else.if Match("N") Then { - \\ is a file? - Read f as long - buffer whitespace as byte - if not Eof(f) then { - get #f, whitespace :P6$=eval$(whitespace) - get #f, whitespace : P6$+=eval$(whitespace) - def boolean getW=true, getH=true, getV=true - def long v - \\ str$("P6") has 2 bytes. "P6" has 4 bytes - P5=p6$=str$("P5") - If p6$=str$("P6") or P5 Then { - do { - get #f, whitespace - if Eval$(whitespace)=str$("#") then { - do {get #f, whitespace} until eval(whitespace)=10 - } else { - select case eval(whitespace) - case 32, 9, 13, 10 - { if getW and x<>0 then { - getW=false - } else.if getH and y<>0 then { - getH=false - } else.if getV and v<>0 then { - getV=false - } - } - case 48 to 57 - {if getW then { - x*=10 - x+=eval(whitespace, 0)-48 - } else.if getH then { - y*=10 - y+=eval(whitespace, 0)-48 - } else.if getV then { - v*=10 - v+=eval(whitespace, 0)-48 - } - } - End Select - } - iF eof(f) then Error "Not a ppm file" - } until getV=false - } else Error "Not a P6 ppm or P5 ppm file" - Import=True - } - } else Error "No proper arguments" - if x<1 or y<1 then Error "Wrong dimensions" - structure rgb { - red as byte - green as byte - blue as byte - } - m=len(rgb)*x mod 4 - if m>0 then m=4-m ' add some bytes to raster line - m+=len(rgb) *x - Structure rasterline { - { - pad as byte*m - } - hline as rgb*x - } - Structure Raster { - magic as integer*4 - w as integer*4 - h as integer*4 - { - linesB as byte*len(rasterline)*y - } - lines as rasterline*y - } - Buffer Clear Image1 as Raster - Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) - if not Import then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) - Buffer Clear Pad as Byte*4 - SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{ - where=alines+3*x+blines*y - if c>0 then c=color(c) - c-! - Return Pad, 0:=c as long - Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte - } - GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - =color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte)) - } - GetPixelGray=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{ - where=alines+3*x+blines*y - grayval=round(0.2126*Eval(image1, where+2 as byte) + 0.7152*Eval(image1, where+1 as byte) + 0.0722*Eval(image1, where as byte), 0) - =color(grayval,grayval,grayval) - } - StrDib$=Lambda$ Image1, Raster -> { - =Eval$(Image1, 0, Len(Raster)) - } - CopyImage=Lambda Image1 (image$) -> { - if left$(image$,12)=Eval$(Image1, 0, 24 ) Then { - Return Image1, 0:=Image$ - } Else Error "Can't Copy Image" - } - Export2File=Lambda Image1, x, y (f) -> { - Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); - Print #f, x;" ";y;" 255";chr$(10); - x2=x-1 : where=0 : rasterline=x*3 - m=rasterline mod 4 : if m<>0 then rasterline+=4-m - Buffer pad as byte*3 - For y1=y-1 to 0 { - where=rasterline*y1 - For x1=0 to x2 { - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Push Eval(pad, 2) : Return pad, 2:=Eval(pad, 0), 0:=Number - Put #f, pad : where+=3 - } - } - } - Export2FileGray=Lambda Image1, x, y (f) -> { - Print #f, "P5";chr$(10);"# Created using M2000 Interpreter";chr$(10); - Print #f, x;" ";y;" 255";chr$(10); - x2=x-1 : where=0 : rasterline=x*3 - m=rasterline mod 4 : if m<>0 then rasterline+=4-m - Buffer pad as byte*3 - Buffer bytepad as byte - const R=0.2126, G=0.7152, B=0.0722 - For y1=y-1 to 0 { - where=rasterline*y1 - For x1=0 to x2 { - Return pad, 0:=eval$(image1, 0!linesB!where, 3) - Return bytepad, 0:=round(R*Eval(pad, 2) + G*Eval(pad, 1) + B*Eval(pad, 0), 0) - Put #f, bytepad : where+=3 - } - } - } - if Import then { - x0=x-1 : where=0 - Buffer Pad1 as byte*3 - Buffer Pad2 as byte - local rasterline=x*3 - m=rasterline mod 4 : if m<>0 then rasterline+=4-m - For y1=y-1 to 0 { - where=rasterline*y1 - For x1=0 to x0 { - if p5 then - Get #f, Pad2: m=eval(Pad2,0) : Return pad1, 0:=m, 1:=m, 2:=m - else - Get #f, Pad1 : Push Eval(pad1, 2) : Return pad1, 2:=Eval(pad1, 0), 0:=Number - End if - Return Image1, 0!linesB!where:=Eval$(Pad1) : where+=3 - } - } - } - Group Bitmap { - SetPixel=SetPixel - GetPixel=GetPixel - Image$=StrDib$ - Copy=CopyImage - ToFile=Export2File - ToFileGray=Export2FileGray - GetPixelGray=GetPixelGray - } - =Bitmap - } - Cls 5,0 - A=Bitmap(15,10) - B=Bitmap(15,10) - c1=color(100, 200, 255) - c2=color(180, 250, 128) - For i=0 to 8 - Call A.SetPixel(i, i, c1) - Call A.SetPixel(9, i,c2) - Next - Call A.SetPixel(i,i,c1) - // make a new one GrayScale (but 24bit) as B - For i=0 to 14 { For J=0 to 9 {Call B.SetPixel(i, j, A.GetPixelGray(i,j))}} - // place image A at 200 pixel from left margin, 100 pixel from top margin - Copy 200*twipsX, 100*twipsY use A.Image$(), 0, 400 ' zoom 400%, angle 0 - // place image B at 400 pixel from left margin, 100 pixel from top margin - Copy 400*twipsX, 100*twipsY use B.Image$(), 0, 400 ' zoom 400% - Try { - Open "P6example.ppm" For Output as #f - Call A.Tofile(f) - Close #f - Open "P5example.ppm" For Output as #f - Call A.TofileGray(f) - Close #f - Open "P5example.ppm" For Input as #f - C=Bitmap(f) - close #f - Copy 600*twipsX, 100*twipsY use C.Image$(), 0, 400 ' zoom 400% - Open "P6example.ppm" For Input as #f - C=Bitmap(f) - close #f - // use of Top clause to make the border color transparent at rotation - Copy 800*twipsX, 100*twipsY top C.Image$(), 30, 400 ' zoom 400%, angle 30 degree - } - Print "Done" + Class Bitmap { + { // from version 14 + Var x As long, y As long, Import As boolean, P5 As boolean + If match("NN") Then + Read x, y + Else.if Match("N") Then + Read f As long + buffer whitespace As Byte + if not Eof(f) Then + get #f, whitespace :P6$=eval$(whitespace) + get #f, whitespace : P6$+=eval$(whitespace) + boolean getW=true, getH=true, getV=true + long v + P5=p6$=str$("P5") + If p6$=str$("P6") or P5 Then + do + get #f, whitespace + if Eval$(whitespace)=str$("#") Then + do + get #f, whitespace + until eval(whitespace)=10 + Else + select case eval(whitespace) + case 32, 9, 13, 10 + { + if getW and x<>0 Then + getW=false + Else.if getH and y<>0 Then + getH=false + Else.if getV and v<>0 Then + getV=false + End If + } + case 48 To 57 + { + if getW Then + x*=10 + x+=eval(whitespace, 0)-48 + Else.if getH Then + y*=10 + y+=eval(whitespace, 0)-48 + Else.if getV Then + v*=10 + v+=eval(whitespace, 0)-48 + End If + } + End Select + End If + iF eof(f) Then Error "Not a ppm file" + until getV=false + Else + Error "Not a P6 ppm or P5 ppm file" + End If + Import=True + End if + Else + Error "No proper arguments" + End If + if x<1 or y<1 Then Error "Wrong dimensions" + Buffer Clear Pad1 As Byte*3 + structure rgb { + red As Byte + green As Byte + blue As Byte + } + m=len(rgb)*x mod 4 + if m>0 Then m=4-m ' add some bytes To raster line + m+=len(rgb) *x + Structure rasterline { + { + pad As Byte*m + } + hline As rgb*x + } + Structure Raster { + magic As integer*4 + w As integer*4 + h As integer*4 + { + linesB As Byte*len(rasterline)*y + } + lines As rasterline*y + } + Buffer Clear Image1 As Raster + Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2) + if not Import Then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y)) + Buffer Clear Pad As Byte*4 + aLines=Len(Raster)-Len(Rasterline)-Raster("linesB") + blines=-Len(Rasterline) + if Import Then + x0=x-1 : where=0 + Buffer Pad1 As Byte*3 + Buffer Pad2 As Byte + local rasterline=x*3 + m=rasterline mod 4 : if m<>0 Then rasterline+=4-m + For y1=y-1 To 0 + where=rasterline*y1 + For x1=0 To x0 + if p5 Then + Get #f, Pad2: m=eval(Pad2,0) : Return pad1, 0:=m, 1:=m, 2:=m + Else + Get #f, Pad1 : Push Eval(pad1, 2) : Return pad1, 2:=Eval(pad1, 0), 0:=Number + End if + Image1|linesB[where]=Pad1[0, 3] : where+=3 + Next + Next + End if + } + SetPixel=Lambda Image1, Pad, aLines, blines (x, y, c) ->{ + if c>0 Then c=color(c) + c-! + Return Pad, 0:=c As long + Push pad[2] : pad[2]=pad[0]: pad[0]=Number + Image1|linesB[alines+3*x+blines*y]=Pad[0, 3] + } + GetPixel=Lambda Image1,aLines, blines, Pad1 (x,y) ->{ + Pad1[0]=Image1|linesB[alines+3*x+blines*y, 3] + =color(Pad1[2], Pad1[1],Pad1[0]) + } + GetPixelGray=Lambda Image1,aLines, blines, Pad1 (x,y) ->{ + Pad1[0]=Image1|linesB[alines+3*x+blines*y, 3] + grayval=round(0.2126*Pad1[2] + 0.7152*Pad1[1] + 0.0722*Pad1[0], 0) + =color(grayval,grayval,grayval) + } + Image$=Lambda$ Image1, Raster ->Eval$(Image1, 0, Len(Raster)) + Copy=Lambda Image1 (image$) -> { + if left$(image$,12)=Image1[0, 24] Then + Return Image1, 0:=Image$ + Else + Error "Can't Copy Image" + End if + } + ToFile=Lambda Image1, x, y (f) -> { + Print #f, "P6";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 : rasterline=x*3 + m=rasterline mod 4 : if m<>0 Then rasterline+=4-m + Buffer pad As Byte*3 + For y1=y-1 To 0 + where=rasterline*y1 + For x1=0 To x2 + pad[0]=image1|linesB[where, 3] + Push pad[2] : pad[2]=pad[0]: pad[0]=Number + Put #f, pad : where+=3 + Next + Next + } + ToFileGray=Lambda Image1, x, y (f) -> { + Print #f, "P5";chr$(10);"# Created using M2000 Interpreter";chr$(10); + Print #f, x;" ";y;" 255";chr$(10); + x2=x-1 : where=0 : rasterline=x*3 + m=rasterline mod 4 : if m<>0 Then rasterline+=4-m + Buffer pad As Byte*3 + Buffer bytepad As Byte + const R=0.2126, G=0.7152, B=0.0722 + For y1=y-1 To 0 + where=rasterline*y1 + For x1=0 To x2 + Return pad, 0:=eval$(image1, 0!linesB!where, 3) + Return bytepad, 0:=round(R*Eval(pad, 2) + G*Eval(pad, 1) + B*Eval(pad, 0), 0) + Put #f, bytepad : where+=3 + Next + Next + } + } + Cls 5,0 + A=Bitmap(15,10) + B=Bitmap(15,10) + c1=color(100, 200, 255) + c2=color(180, 250, 128) + For i=0 To 8 + Call A.SetPixel(i, i, c1) + Call A.SetPixel(9, i,c2) + Next + Call A.SetPixel(i,i,c1) + // make a new one GrayScale (but 24bit) As B + For i=0 To 14 { For J=0 To 9 {Call B.SetPixel(i, j, A.GetPixelGray(i,j))}} + // place image A at 200 pixel from left margin, 100 pixel from top margin + Copy 200*twipsX, 100*twipsY use A.Image$(), 0, 800 ' zoom 800%, angle 0 + // place image B at 400 pixel from left margin, 100 pixel from top margin + Copy 400*twipsX, 100*twipsY use B.Image$(), 0, 800 ' zoom 800% + Try { + Open "P6example.ppm" For Output As #f + Call A.Tofile(f) + Close #f + Open "P5example.ppm" For Output As #f + Call A.TofileGray(f) + Close #f + Open "P5example.ppm" For Input As #f + C=Bitmap(f) + close #f + Copy 600*twipsX, 100*twipsY use C.Image$(), 0, 800 ' zoom 800% + Open "P6example.ppm" For Input As #f + C=Bitmap(f) + close #f + // use of Top clause To make the border color transparent at rotation + Copy 800*twipsX, 100*twipsY top C.Image$(), 30, 800 ' zoom 800%, angle 30 degree + } + Print "Done" } P6P5 diff --git a/Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina b/Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina new file mode 100644 index 0000000000..3ee409c7ea --- /dev/null +++ b/Task/Greatest-subsequential-sum/Ballerina/greatest-subsequential-sum.ballerina @@ -0,0 +1,42 @@ +import ballerina/io; + +function gss(int[] s) returns [int[], int] { + int best = 0; + int strt = 0; + int end = 0; + int sum = 0; + int sumStart = 0; + foreach var [i, x] in s.enumerate() { + sum += x; + if sum > best { + best = sum; + strt = sumStart; + end = i + 1; + } else if sum < 0 { + sum = 0; + sumStart = i + 1; + } + } + return [s.slice(strt, end), best]; +} + +function A(any[] a) returns string { + return re `,`.replaceAll(a.toString(), ", "); +} + +public function main() { + var tests = [ + [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1], + [-1, 1, 2, -5, -6], + [], + [-1, -2, -1] + ]; + foreach var test in tests { + io:println("Input: ", A(test)); + var res = gss(test); + var subSeq = res[0]; + int sum = res[1]; + io:println("Sub seq: ", A(subSeq)); + io:println("Sum: ", sum, "\n"); + } +} diff --git a/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy b/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy index acb989f2c7..90385e92e1 100644 --- a/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy +++ b/Task/Greatest-subsequential-sum/EasyLang/greatest-subsequential-sum.easy @@ -1,4 +1,4 @@ -proc max_subseq . seq[] start stop maxsum . +proc max_subseq &seq[] &start &stop &maxsum . maxsum = 0 i = 1 start = 1 @@ -18,6 +18,4 @@ proc max_subseq . seq[] start stop maxsum . a[] = [ -1 -2 3 5 6 -2 -1 4 -4 2 -1 ] max_subseq a[] a b sum print "Max sum = " & sum -for i = a to b - write a[i] & " " -. +for i = a to b : write a[i] & " " diff --git a/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 new file mode 100644 index 0000000000..1eb7221eed --- /dev/null +++ b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-1.m2000 @@ -0,0 +1,26 @@ +module Greatest_subsequential_sum { + showGSS=lambda (a)->{ + function Greatest_subsequential_sum(a as array){ + s=a#sum() + =a + p=len(a)-1 + if p<0 then exit + for i=0 to p + for j=i to p + k= a#slice(i, j) + m=k#sum() + if m>s then =k: s=m + next + next + } + = "("+a#str$(",")+") -> ("+ Greatest_subsequential_sum(a)#str$(",")+")" + } + open "out.txt" for output as#f + print #f, showGSS((-1 , 2 , -1)) + print #f, showGSS((-1, 2, -1, 3, -1)) + print #f, showGSS((-1, 1, 2, -5, -6)) + print #f, showGSS((-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1)) + close #f + win notepad, dir$+"out.txt" +} +Greatest_subsequential_sum diff --git a/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 new file mode 100644 index 0000000000..a16c08d534 --- /dev/null +++ b/Task/Greatest-subsequential-sum/M2000-Interpreter/greatest-subsequential-sum-2.m2000 @@ -0,0 +1,36 @@ +module Greatest_subsequential_sum (filename) { + showGSS=lambda (a)->{ + function Greatest_subsequential_sum(a as array){ + var best = 0 + var start = 0 + var end = 0 + var sum = 0 + var sumStart = 0 + var i = 0 + s=each(a) + while s { + sum +=array(s) + if (sum > best) then { + best = sum + start = sumStart + end = i + 1 + } else.if (sum < 0) then { + sum = 0 + sumStart = i + 1 + } + i++ + } + =a#slice(start, end-1) + } + = "("+a#str$(",")+") -> ("+ Greatest_subsequential_sum(a)#str$(",")+")" + } + open filename for output as#f + print #f, showGSS((-1 , 2 , -1)) + print #f, showGSS((-1, 2, -1, 3, -1)) + print #f, showGSS((-1, 1, 2, -5, -6)) + print #f, showGSS((-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1)) + close #f + if filename<>"" then win notepad, dir$+filename +} +Greatest_subsequential_sum "" ' to screen +Greatest_subsequential_sum "out.txt" diff --git a/Task/Greedy-algorithm-for-Egyptian-fractions/JavaScript/greedy-algorithm-for-egyptian-fractions.js b/Task/Greedy-algorithm-for-Egyptian-fractions/JavaScript/greedy-algorithm-for-egyptian-fractions.js new file mode 100644 index 0000000000..7c80a0f77e --- /dev/null +++ b/Task/Greedy-algorithm-for-Egyptian-fractions/JavaScript/greedy-algorithm-for-egyptian-fractions.js @@ -0,0 +1,222 @@ +// Egyptian Fractions implementation in JavaScript +// Using BigInt for arbitrary precision integers + +function gcd(a, b) { + if (b === 0n) { + return a; + } + return gcd(b, a % b); +} + +class Frac { + constructor(n, d) { + // Handle different input types (number or BigInt) + const num = typeof n === 'number' ? BigInt(n) : n; + const denom = typeof d === 'number' ? BigInt(d) : d; + + if (denom === 0n) { + throw new Error("Parameter d may not be zero."); + } + + let nn = num; + let dd = denom; + + if (nn === 0n) { + dd = 1n; + } else if (dd < 0n) { + nn = -nn; + dd = -dd; + } + + const g = gcd(nn < 0n ? -nn : nn, dd).valueOf(); + + if (g > 0n) { + nn = nn / g; + dd = dd / g; + } + + this.num = nn; + this.denom = dd; + } + + plus(rhs) { + return new Frac( + this.num * rhs.denom + this.denom * rhs.num, + this.denom * rhs.denom + ); + } + + unaryMinus() { + return new Frac(-this.num, this.denom); + } + + minus(rhs) { + return this.plus(rhs.unaryMinus()); + } + + compareTo(rhs) { + // We'll compare by cross multiplication to avoid floating point issues + const leftSide = this.num * rhs.denom; + const rightSide = rhs.num * this.denom; + + if (leftSide < rightSide) return -1; + if (leftSide > rightSide) return 1; + return 0; + } + + equals(obj) { + if (!(obj instanceof Frac)) { + return false; + } + return this.compareTo(obj) === 0; + } + + toString() { + if (this.denom === 1n) { + return this.num.toString(); + } + return `${this.num}/${this.denom}`; + } + + toNumber() { + // Convert fraction to a regular number (potentially with loss of precision) + return Number(this.num) / Number(this.denom); + } + + toEgyptian() { + if (this.num === 0n) { + return [this]; + } + + const fracs = []; + + if ((this.num < 0n ? -this.num : this.num) >= (this.denom < 0n ? -this.denom : this.denom)) { + // Handle improper fractions + const div = new Frac(this.num / this.denom, 1n); + const rem = this.minus(div); + fracs.push(div); + this._toEgyptian(rem.num, rem.denom, fracs); + } else { + this._toEgyptian(this.num, this.denom, fracs); + } + + return fracs; + } + + _toEgyptian(n, d, fracs) { + if (n === 0n) { + return; + } + + // Calculate ceiling of d/n + let div = d / n; + if (d % n !== 0n) { + div = div + 1n; + } + + fracs.push(new Frac(1n, div)); + + // Calculate next fraction's numerator and denominator + let n3 = -(d % n); + if (n3 < 0n) { + n3 = n3 + n; + } + + const d3 = d * div; + const f = new Frac(n3, d3); + + if (f.num === 1n) { + fracs.push(f); + return; + } + + this._toEgyptian(f.num, f.denom, fracs); + } +} + +// Main function +function main() { + const fracs = [ + new Frac(43, 48), + new Frac(5, 121), + new Frac(2014, 59) + ]; + + for (const frac of fracs) { + const list = frac.toEgyptian(); + const first = list[0]; + + if (first.denom === 1n) { + process.stdout.write(`${frac} -> [${first}] + `); + } else { + process.stdout.write(`${frac} -> ${first}`); + } + + for (let i = 1; i < list.length; ++i) { + process.stdout.write(` + ${list[i]}`); + } + + console.log(); + } + + for (const r of [98, 998]) { + if (r === 98) { + console.log("\nFor proper fractions with 1 or 2 digits:"); + } else { + console.log("\nFor proper fractions with 1, 2 or 3 digits:"); + } + + let maxSize = 0; + let maxSizeFracs = []; + let maxDen = 0n; + let maxDenFracs = []; + + // Create sieve array + const sieve = Array(r + 1).fill().map(() => Array(r + 2).fill(false)); + + for (let i = 1; i < r; ++i) { + for (let j = i + 1; j < r + 1; ++j) { + if (sieve[i][j]) continue; + + const f = new Frac(i, j); + const list = f.toEgyptian(); + const listSize = list.length; + + if (listSize > maxSize) { + maxSize = listSize; + maxSizeFracs = [f]; + } else if (listSize === maxSize) { + maxSizeFracs.push(f); + } + + const listDen = list[list.length - 1].denom; + + if (listDen > maxDen) { + maxDen = listDen; + maxDenFracs = [f]; + } else if (listDen === maxDen) { + maxDenFracs.push(f); + } + + if (i < r / 2) { + let k = 2; + while (true) { + if (j * k > r + 1) break; + sieve[i * k][j * k] = true; + k++; + } + } + } + } + + console.log(` largest number of items = ${maxSize}`); + console.log(`fraction(s) with this number : ${maxSizeFracs}`); + + const md = maxDen.toString(); + console.log(` largest denominator = ${md.length} digits, ${md.substring(0, 20)}...${md.substring(md.length - 20)}`); + console.log(`fraction(s) with this denominator : ${maxDenFracs}`); + } +} + +// Run the main function +main(); diff --git a/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy b/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy index cd8133e96a..0d55e19187 100644 --- a/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy +++ b/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy @@ -6,9 +6,8 @@ for row = 0 to 3 if row mod 2 = 1 c = 1 - c . - color3 c c c - move sz * i 75 - row * 25 - rect sz + 1 25 + gcolor3 c c c + grect sz * i 75 - row * 25 sz + 1 25 sleep 0.02 . n *= 2 diff --git a/Task/HTTP/Elena/http.elena b/Task/HTTP/Elena/http.elena new file mode 100644 index 0000000000..b8a54ec4f4 --- /dev/null +++ b/Task/HTTP/Elena/http.elena @@ -0,0 +1,13 @@ +import net'http; + +public program() +{ + using(HttpClient client := HttpClient.open("http://www.google.com")) + { + HttpResponse response := client.get(); + + string content := response.readAsString(); + + Console.writeLine(content); + }; +} diff --git a/Task/HTTPS/Elena/https.elena b/Task/HTTPS/Elena/https.elena new file mode 100644 index 0000000000..f383e964fb --- /dev/null +++ b/Task/HTTPS/Elena/https.elena @@ -0,0 +1,14 @@ +import net'http; +import mbedtls'registration; + +public program() +{ + using(HttpClient client := HttpClient.open("https://www.google.com")) + { + HttpResponse response := client.get(); + + string content := response.readAsString(); + + Console.writeLine(content); + }; +} diff --git a/Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina b/Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina new file mode 100644 index 0000000000..775dc1646d --- /dev/null +++ b/Task/Hailstone-sequence/Ballerina/hailstone-sequence.ballerina @@ -0,0 +1,34 @@ +import ballerina/io; + +function hailstone(int m) returns int[] { + int n = m; + int[] h = [n]; + while n != 1 { + n = n % 2 == 0 ? n / 2 : 3 * n + 1; + h.push(n); + } + return h; +} + +public function main() { + int[] h = hailstone(27); + int len = h.length(); + io:println("For the Hailstone sequence starting with n = 27:"); + io:println(" Number of elements = ", len); + io:println(" First four elements = ", h.slice(0, 4)); + io:println(" Final four elements = ", h.slice(len - 4)); + + io:println("\nThe Hailstone sequence for n < 100,000 with the longest length is:"); + int longest = 0; + int longlen = 0; + foreach int n in 1...99999 { + h = hailstone(n); + len = h.length(); + if len > longlen { + longest = n; + longlen = len; + } + } + io:println(` Longest = ${longest}`); + io:println(` Length = ${longlen}`); +} diff --git a/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy b/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy index a5606e817c..ff201550a8 100644 --- a/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy +++ b/Task/Hailstone-sequence/EasyLang/hailstone-sequence.easy @@ -1,4 +1,4 @@ -proc hailstone n . list[] . +proc hailstone n &list[] . list[] = [ ] while n <> 1 list[] &= n @@ -12,19 +12,15 @@ proc hailstone n . list[] . . hailstone 27 l[] write "27 has length " & len l[] & " with " -for i to 4 - write l[i] & " " -. +for i to 4 : write l[i] & " " write "... " -for i = len l[] - 3 to len l[] - write l[i] & " " -. +for i = len l[] - 3 to len l[] : write l[i] & " " print "" for i = 1 to 100000 hailstone i l[] if len l[] >= max_iter max_i = i max_iter = len l[] - end -end + . +. print max_i & " has length " & max_iter diff --git a/Task/Hailstone-sequence/Odin/hailstone-sequence.odin b/Task/Hailstone-sequence/Odin/hailstone-sequence.odin new file mode 100644 index 0000000000..dbe6f83782 --- /dev/null +++ b/Task/Hailstone-sequence/Odin/hailstone-sequence.odin @@ -0,0 +1,65 @@ +package main + +import "core:fmt" + +collatz :: proc(array:^[dynamic]int,n:int){ + i:=1 + n:=n + for n!=1{ + + if (n%2==0){ + n=n/2 + append(&array^,n) + } + else{ + n=3*n+1 + append(&array^,n) + } + + } +} + +main :: proc() { + n:=27 + + max:=0 + max_length:=0 + + dummy:[dynamic]int + defer delete(dummy) + append(&dummy,n) + collatz(&dummy,n) + + + fmt.println("the first four of sequence for 27: ") + for jj:=0;jj<4;jj+=1{ + fmt.println(dummy[jj]) + } + fmt.println("the last four of sequence for 27: ") + for jj:=0;jj<4;jj+=1{ + fmt.println(dummy[len(dummy)-4+jj]) + } + fmt.println("length of sequence for 27") + fmt.println(len(dummy)) + + + for (len(dummy)>0){ + pop(&dummy) + } + + for ii:=1;ii<100000;ii+=1{ + append(&dummy,ii) + collatz(&dummy,ii) + if(len(dummy)>max_length){ + max = ii + max_length=len(dummy) + } + for (len(dummy)>0){ + pop(&dummy) + } + } + fmt.println("Max number: ") + fmt.println(max) + fmt.println("Max length: ") + fmt.println(max_length) +} diff --git a/Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r new file mode 100644 index 0000000000..39a97b302c --- /dev/null +++ b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-1.r @@ -0,0 +1 @@ +stop() diff --git a/Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r new file mode 100644 index 0000000000..1e5b3ea0c8 --- /dev/null +++ b/Task/Halt-and-catch-fire/R/halt-and-catch-fire-2.r @@ -0,0 +1 @@ +array()[,] diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx deleted file mode 100644 index cc53b7ad15..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-1.rexx +++ /dev/null @@ -1,20 +0,0 @@ -/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth. */ -numeric digits 100 /*ensure enough decimal digits. */ -call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ -call hamming 1691 /*show the 1,691st Hamming number. */ -call hamming 1000000 /*show the 1 millionth Hamming number.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -hamming: procedure; parse arg x,y; if y=='' then y= x; w= length(y) - #2= 1; #3= 1; #5= 1; @.= 0; @.1= 1 - do n=2 for y-1 - @.n= min(2*@.#2, 3*@.#3, 5*@.#5) /*pick the minimum of 3 Hamming numbers*/ - if 2*@.#2 == @.n then #2= #2 + 1 /*number already defined? Use next #. */ - if 3*@.#3 == @.n then #3= #3 + 1 /* " " " " " " */ - if 5*@.#5 == @.n then #5= #5 + 1 /* " " " " " " */ - end /*n*/ /* [↑] maybe assign next 3 Hamming#s. */ - do j=x to y; say 'Hamming('right(j, w)") =" @.j - end /*j*/ - - say right( 'length of last Hamming number =' length(@.y), 70); say - return diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx deleted file mode 100644 index bccf09bbe0..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-2.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth.*/ -call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ -call hamming 1691 /*show the 1,691st Hamming number. */ -call hamming 1000000 /*show the 1 millionth Hamming number.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -hamming: procedure; arg x,y; if y=='' then y= x; w= length(y); L= length(y-1); p= 2**L - numeric digits max(9, p + p%4 + p%16) /*ensure enough decimal digits. */ - #2= 1; #3= 1; #5= 1; @.= 0; @.1= 1 - do n=2 for y-1 - _2= @.#2 + @.#2 /*this is faster than: @.#2 * 2 */ - _3= @.#3 + @.#3 + @.#3 /* " " " " @,#3 * 3 */ - _5= @.#5 * 5 - m= _2 /*assume a minimum (of the 3 Hammings).*/ - if _3 < m then m= _3 /*is this number less than the minimum?*/ - if _5 < m then m= _5 /* " " " " " " " */ - @.n= m /*now, assign the next Hamming number.*/ - if _2 == m then #2= #2 + 1 /*number already defined? Use next #.*/ - if _3 == m then #3= #3 + 1 /* " " " " " " */ - if _5 == m then #5= #5 + 1 /* " " " " " " */ - end /*n*/ /* [↑] maybe assign next Hamming #'s. */ - do j=x to y; say 'Hamming('right(j, w)") =" @.j - end /*j*/ - - say right( 'length of last Hamming number =' length(@.y), 70); say - return diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-3.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-3.rexx deleted file mode 100644 index ed4dfa5cbb..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-3.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program computes Hamming numbers: 1 ──► 20, # 1691, and the one millionth.*/ -call hamming 1, 20 /*show the 1st ──► twentieth Hamming #s*/ -call hamming 1691 /*show the 1,691st Hamming number. */ -call hamming 1000000 /*show the 1 millionth Hamming number.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -hamming: procedure; arg x,y; if y=='' then y= x; w= length(y); L= length(y-1); p= 2**L - numeric digits max(9, p + p%4 + p%16) /*ensure enough decimal digits. */ - #2= 1; #3= 1; #5= 1; @.= 0; @.1= 1 - do n=2 for y-1 - _2= @.#2 + @.#2 /*this is faster than: @.#2 * 2 */ - _3= @.#3 + @.#3 + @.#3 /* " " " " @,#3 * 3 */ - _5= @.#5 * 5 - m= _2 /*assume a minimum (of the 3 Hammings).*/ - if _3 < m then m= _3 /*is this number less than the minimum?*/ - if _5 < m then m= _5 /* " " " " " " " */ - @.n= format(m,,,,0) /*now, assign the next Hamming number.*/ - if _2 == m then #2= #2 + 1 /*number already defined? Use next #.*/ - if _3 == m then #3= #3 + 1 /* " " " " " " */ - if _5 == m then #5= #5 + 1 /* " " " " " " */ - end /*n*/ /* [↑] maybe assign next Hamming #'s. */ - do j=x to y; say 'Hamming('right(j, w)") =" @.j / 1 - end /*j*/ - - say right( 'length of last Hamming number =' length(@.y / 1), 70); say - return diff --git a/Task/Hamming-numbers/REXX/hamming-numbers-4.rexx b/Task/Hamming-numbers/REXX/hamming-numbers-4.rexx deleted file mode 100644 index 3d590eb3a0..0000000000 --- a/Task/Hamming-numbers/REXX/hamming-numbers-4.rexx +++ /dev/null @@ -1,73 +0,0 @@ -include Settings - -say version; say 'Hamming numbers'; say -call Hammings 1e6 -call ShowFirstN 20 -call ShowNth 1691 -call ShowNth 1e6 -call Hammings 1e7 -call ShowNth 1e7 -exit - -Hammings: -procedure expose hamm. -arg xx -call Time('r') -xx = xx/1 -say 'Collect Hamming numbers up to the' xx'th' -/* Ensure enough digits */ -numeric digits 2**(Length(xx)+1) -/* Dijkstra */ -hamm.hamming.1 = 1 -x2 = 2; x3 = 3; x5 = 5; i2 = 1; i3 = 1; i5 = 1 -do yy = 2 - h = x2 - if x3 < h then - h = x3 - if x5 < h then - h = x5 - hamm.hamming.yy = h - if yy = xx then - leave - if x2 = h then do - i2 = i2+1; x2 = hamm.hamming.i2+hamm.hamming.i2 - end - if x3 = h then do - i3 = i3+1; x3 = hamm.hamming.i3+hamm.hamming.i3+hamm.hamming.i3 - end - if x5 = h then do - i5 = i5+1; x5 = hamm.hamming.i5*5 - end -end -hamm.0 = yy -say Time('e')/1 'seconds' -say -return - -ShowFirstN: -procedure expose hamm. -arg xx -call Time('r') -xx = xx/1 -say 'First' xx 'Hamming numbers are' -do i = 1 to xx - call Charout ,Right(hamm.hamming.i,5) - if i//10 = 0 then - say -end -say Time('e')/1 'seconds' -say -return - -ShowNth: -procedure expose hamm. -arg xx -xx = xx/1 -call Time('r') -say xx'th Hamming Number is' -say hamm.hamming.xx '('Length(hamm.hamming.xx) 'digits)' -say Time('e')/1 'seconds' -say -return - -include Abend diff --git a/Task/Hamming-numbers/REXX/hamming-numbers.rexx b/Task/Hamming-numbers/REXX/hamming-numbers.rexx new file mode 100644 index 0000000000..2b39f1cf89 --- /dev/null +++ b/Task/Hamming-numbers/REXX/hamming-numbers.rexx @@ -0,0 +1,40 @@ +-- 22 Mar 2025 +include Settings + +say 'HAMMING NUMBERS' +say version +say +call Hammings 1000000 +call ShowFirstN 20 +call ShowNth 1691 +call ShowNth 1000000 +call Hammings 10000000 +call ShowNth 10000000 +say Time('e')/1 'seconds' +exit + +ShowFirstN: +procedure expose hamm. +arg xx +xx = xx/1 +say 'First' xx 'Hamming numbers are' +do i = 1 to xx + call Charout ,Right(hamm.i,5) + if i//10 = 0 then + say +end +say +return + +ShowNth: +procedure expose hamm. +arg xx +xx = xx/1 +say xx'th Hamming number is' +say hamm.xx '('Length(hamm.xx) 'digits)' +say +return + +include Sequences +include Functions +include Abend diff --git a/Task/Harmonic-series/EasyLang/harmonic-series.easy b/Task/Harmonic-series/EasyLang/harmonic-series.easy index 75a56234c7..fbf03db1cf 100644 --- a/Task/Harmonic-series/EasyLang/harmonic-series.easy +++ b/Task/Harmonic-series/EasyLang/harmonic-series.easy @@ -1,4 +1,4 @@ -numfmt 5 2 +numfmt 2 5 print "The first twenty harmonic numbers are:" for n = 1 to 20 h += 1 / n diff --git a/Task/Harmonic-series/Fortran/harmonic-series.f b/Task/Harmonic-series/Fortran/harmonic-series.f new file mode 100644 index 0000000000..2ab5783463 --- /dev/null +++ b/Task/Harmonic-series/Fortran/harmonic-series.f @@ -0,0 +1,83 @@ +program harmonic_numbers + use :: iso_fortran_env, only: int64, output_unit + implicit none + integer, parameter :: real64 = selected_real_kind(15, 307) + + type :: fraction + integer(int64) :: numerator + integer(int64) :: denominator + end type fraction + + integer :: i, target_int + type(fraction) :: h_exact + real(real64) :: sum_h, h_decimal + character(len=200) :: fmt_str + + ! Print first 20 harmonic numbers as fractions + write(output_unit, '(a)') "## First 20 Harmonic Numbers" + write(output_unit, '(a)') "**Fractional Form**" + h_exact = fraction(0_int64, 1_int64) + do i = 1, 20 + h_exact = add_reciprocal(h_exact, i) + write(output_unit, '(i2, ": ", i0, "/", i0)') i, h_exact%numerator, h_exact%denominator + end do + + ! Print decimal approximations + write(output_unit, '(/, a)') "**Decimal Approximations**" + h_exact = fraction(0_int64, 1_int64) + do i = 1, 20 + h_exact = add_reciprocal(h_exact, i) + h_decimal = real(h_exact%numerator, real64) / real(h_exact%denominator, real64) + write(output_unit, '(i2, ": ", f0.12)') i, h_decimal + end do + + ! Find positions where harmonic numbers exceed integers 1-10 + write(output_unit, '(/, a)') "## Positions Where H? First Exceeds Integers" + write(output_unit, '(a)') "| Target | Position (n) | Decimal Approximation |" + write(output_unit, '(a)') "|--------|--------------|------------------------|" + write(fmt_str, '(a)') '(a, i2, a, T10, A, i0,T25, a, f0.6, T50,a)' + + do target_int = 1, 10 + sum_h = 0._real64 + i = 0 + do + i = i + 1 + sum_h = sum_h + 1.0_real64 / real(i, real64) + if (sum_h > real(target_int, real64)) then + if (target_int <= 5 .or. target_int >= 6) then + write(output_unit, FMT_STR) "| **", target_int, "**","| ", i, & + "| ", real(sum_h, real64), "|" + end if + exit + end if + end do + end do + +contains + + function add_reciprocal(h, n) result(new_h) + type(fraction), intent(in) :: h + integer, intent(in) :: n + type(fraction) :: new_h + integer(int64) :: common_denominator, new_numerator, divisor + + common_denominator = h%denominator * int(n, int64) + new_numerator = h%numerator * int(n, int64) + h%denominator + divisor = gcd(new_numerator, common_denominator) + + new_h%numerator = new_numerator / divisor + new_h%denominator = common_denominator / divisor + end function add_reciprocal + + recursive function gcd(a, b) result(greatest_common_divisor) + integer(int64), intent(in) :: a, b + integer(int64) :: greatest_common_divisor + + if (b == 0) then + greatest_common_divisor = a + else + greatest_common_divisor = gcd(b, mod(a, b)) + end if + end function gcd + +end program harmonic_numbers diff --git a/Task/Hello-world-Graphical/Autohotkey-V2/hello-world-graphical.ahk b/Task/Hello-world-Graphical/AutoHotKey-V2/hello-world-graphical.ahk similarity index 100% rename from Task/Hello-world-Graphical/Autohotkey-V2/hello-world-graphical.ahk rename to Task/Hello-world-Graphical/AutoHotKey-V2/hello-world-graphical.ahk diff --git a/Task/Hello-world-Graphical/EasyLang/hello-world-graphical.easy b/Task/Hello-world-Graphical/EasyLang/hello-world-graphical.easy index 9c9925f5d9..ec655ec617 100644 --- a/Task/Hello-world-Graphical/EasyLang/hello-world-graphical.easy +++ b/Task/Hello-world-Graphical/EasyLang/hello-world-graphical.easy @@ -1,2 +1,2 @@ -move 10 20 -text "Goodbye, World!" +gcolor 700 +gtext 10 60 "Goodbye, World!" diff --git a/Task/Hello-world-Graphical/Odin/hello-world-graphical.odin b/Task/Hello-world-Graphical/Odin/hello-world-graphical.odin new file mode 100644 index 0000000000..18c4fd4bd0 --- /dev/null +++ b/Task/Hello-world-Graphical/Odin/hello-world-graphical.odin @@ -0,0 +1,27 @@ +package main + +import "core:fmt" +import "core:c" +import "base:runtime" + +import "core:sys/windows" + + +main :: proc () { + + + lptextt:="Goodbye, World!" + lptextw:= windows.utf8_to_wstring(lptextt, context.temp_allocator) + lptext:= transmute([^]u16)lptextw + + lptextt2:="Title" + lptextw2:= windows.utf8_to_wstring(lptextt2, context.temp_allocator) + lptext2:= transmute([^]u16)lptextw2 + + lastid:u32 + lastid= windows.MB_ICONWARNING + // change last value from 0 to lastid to show warning + dummy:=windows.MessageBoxW(nil,lptext,lptext2,0) + + +} diff --git a/Task/Hello-world-Graphical/Uxntal/hello-world-graphical.uxnatl b/Task/Hello-world-Graphical/Uxntal/hello-world-graphical.uxnatl new file mode 100644 index 0000000000..43d633e179 --- /dev/null +++ b/Task/Hello-world-Graphical/Uxntal/hello-world-graphical.uxnatl @@ -0,0 +1,240 @@ +|00 @System [ + &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 + &debug $1 &state $1 ] + +|20 @Screen [ + &vector $2 &width $2 &height $2 &auto $2 &x $2 &y $2 &addr $2 &pixel $1 + &sprite $1 ] + +|100 + +@on-reset ( -> ) + ( size ) + #00a8 .Screen/width DEO2 + #0020 .Screen/height DEO2 + + ( theme ) + #3ce9 .System/r DEO2 + #0b75 .System/g DEO2 + #2b59 .System/b DEO2 + + #001c .Screen/x DEO2 + #000a .Screen/y DEO2 + + ;my-string draw-text + BRK + +@draw-text ( text* -- ) + [ LIT2 15 -Screen/auto ] DEO + &>while ( -- ) + LDAk #00 SWP DUP2 + ( addr ) #20 SUB #50 SFT2 ;font/glyphs ADD2 .Screen/addr DEO2 + ( move ) ;font/widths ADD2 LDA #00 SWP .Screen/x DEI2 ADD2 + ( draw ) [ LIT2 01 -Screen/sprite ] DEOk DEO + .Screen/x DEO2 + INC2 LDAk ?&>while + POP2 JMP2r + +@my-string "Goodbye 20 "World! 0a00 + +@font + &widths [ + 0800 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0808 0808 0808 0808 0808 0808 0808 0808 + 0808 0808 0808 0808 0808 0808 0808 0808 + 0808 0808 0808 0808 0808 0808 0808 0808 + 0808 0808 0808 0808 0808 0808 0808 0808 + 0808 0808 0808 0808 0808 0808 0808 0808 + 0808 0808 0808 0808 0808 0808 0808 0800 ] + &glyphs [ ( starting from 0x20 ) + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1818 1818 1818 1800 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0066 6666 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 6c6c 6cfe 6c6c fe6c 6c6c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0010 107c d6d0 d07c 1616 d67c 1010 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 66d6 6c0c 1818 3036 6b66 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 386c 6c38 76dc cccc dc76 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0018 1818 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0c18 3030 3030 3030 180c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3018 0c0c 0c0c 0c0c 1830 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 006c 38fe 386c 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0018 187e 1818 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 1818 3000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 00fe 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0606 0c0c 1818 3030 6060 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6ce def6 e6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1838 7818 1818 1818 187e 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c606 0c18 3060 c0fe 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c606 3c06 06c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 060e 1e36 66c6 fe06 0606 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fec0 c0c0 fc06 0606 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3c60 c0c0 fcc6 c6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fe06 060c 0c18 1830 3030 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c6 7cc6 c6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c6 c67e 0606 0c78 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0018 1800 0000 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0018 1800 0000 1818 3000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0006 0c18 3060 3018 0c06 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00fe 0000 fe00 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0060 3018 0c06 0c18 3060 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c6 0c18 1800 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 ced6 d6d6 d6ce c07e 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c6 c6fe c6c6 c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fcc6 c6c6 fcc6 c6c6 c6fc 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c0 c0c0 c0c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 f8cc c6c6 c6c6 c6c6 ccf8 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fec0 c0c0 f8c0 c0c0 c0fe 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fec0 c0c0 f8c0 c0c0 c0c0 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c0 c0de c6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 c6c6 fec6 c6c6 c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3c18 1818 1818 1818 183c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1e0c 0c0c 0c0c 0ccc cc78 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 ccd8 f0f0 d8cc c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c0c0 c0c0 c0c0 c0c0 c0fe 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 82c6 eefe d6c6 c6c6 c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 c6e6 f6de cec6 c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c6 c6c6 c6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fcc6 c6c6 c6fc c0c0 c0c0 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c6c6 c6c6 c6c6 de7c 0600 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fcc6 c6c6 c6fc f0d8 ccc6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7cc6 c0c0 7c06 06c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 ff18 1818 1818 1818 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 c6c6 c6c6 c6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 c6c6 c66c 6c6c 3838 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 c6c6 c6d6 feee c682 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c6c6 6c6c 3838 6c6c c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c3c3 6666 3c18 1818 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 fe06 060c 1830 60c0 c0fe 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3c30 3030 3030 3030 303c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 6060 3030 1818 0c0c 0606 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3c0c 0c0c 0c0c 0c0c 0c3c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0018 3c66 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 00fe 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 3018 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007c 067e c6c6 c67e 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c0c0 c0fc c6c6 c6c6 c6fc 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007c c6c0 c0c0 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0606 067e c6c6 c6c6 c67e 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007c c6c6 fec0 c07c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1e30 30fc 3030 3030 3030 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007e c6c6 c6c6 c67e 0606 7c00 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c0c0 c0fc c6c6 c6c6 c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1818 0038 1818 1818 183c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0606 000e 0606 0606 0606 6666 3c00 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 c0c0 c0c6 ccd8 f0d8 ccc6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3818 1818 1818 1818 183c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00fc d6d6 d6d6 d6d6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00fc c6c6 c6c6 c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007c c6c6 c6c6 c67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00fc c6c6 c6c6 c6fc c0c0 c000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007e c6c6 c6c6 c67e 0606 0600 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00de f0e0 c0c0 c0c0 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 007e c0c0 7c06 06fc 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 3030 30fc 3030 3030 301e 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00c6 c6c6 c6c6 c67e 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00c6 c6c6 6c6c 3838 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00c6 c6d6 d6d6 d67c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00c6 c66c 386c c6c6 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00c6 c6c6 c6c6 c67e 0606 7c00 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 0000 00fe 0c18 3060 c0fe 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1c30 3030 6030 3030 301c 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 1818 1818 1818 1818 1818 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0000 7018 1818 0c18 1818 1870 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 + 0073 dbce 0000 0000 0000 0000 0000 0000 + 0000 0000 0000 0000 0000 0000 0000 0000 ] diff --git a/Task/Hello-world-Newline-omission/Ballerina/hello-world-newline-omission.ballerina b/Task/Hello-world-Newline-omission/Ballerina/hello-world-newline-omission.ballerina new file mode 100644 index 0000000000..e53d30ec3d --- /dev/null +++ b/Task/Hello-world-Newline-omission/Ballerina/hello-world-newline-omission.ballerina @@ -0,0 +1,5 @@ +import ballerina/io; + +public function main() { + io:print("Goodbye, World!"); +} diff --git a/Task/Hello-world-Newline-omission/Uxntal/hello-world-newline-omission.uxnatl b/Task/Hello-world-Newline-omission/Uxntal/hello-world-newline-omission.uxnatl index 20a2d61d1e..38f81a985d 100644 --- a/Task/Hello-world-Newline-omission/Uxntal/hello-world-newline-omission.uxnatl +++ b/Task/Hello-world-Newline-omission/Uxntal/hello-world-newline-omission.uxnatl @@ -1,13 +1,17 @@ -|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|10 @Console &vector $2 &read $1 &pad $5 &write $1 &error $1 -|0100 - ;message - &loop - LDAk .Console/write DEO - INC2 LDAk ?&loop - POP2 - #80 .System/state DEO -BRK +|100 -@message "Goodbye, 20 "World! 00 +@on-reset ( -> ) + ;my-string print-text + BRK + +@print-text ( str* -- ) + &while + LDAk .Console/write DEO + INC2 LDAk ?&while + POP2 + JMP2r + +@my-string + "Hello 20 "World! 00 diff --git a/Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error.aarch64 b/Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error-1.aarch64 similarity index 100% rename from Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error.aarch64 rename to Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error-1.aarch64 diff --git a/Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error-2.aarch64 b/Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error-2.aarch64 new file mode 100644 index 0000000000..e693ea2dcc --- /dev/null +++ b/Task/Hello-world-Standard-error/AArch64-Assembly/hello-world-standard-error-2.aarch64 @@ -0,0 +1,16 @@ +.global _start + +.text +_start: + mov x8, #64 //64 is write + mov x0, #2 //2 is stderr + adr x1, msg //mov address of msg into x1 + mov x2, #(msgend - msg) //msgend minus msg is the length of message + svc #0 //system call + mov x8, #93 //93 is exit + mov x0, #0 //0 is the exit code. + svc #0 //system call + +msg: + .ascii "Goodbye, World!\n" +msgend: diff --git a/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm b/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm index 0f817f7232..1eba4d34a7 100644 --- a/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm +++ b/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm @@ -1,7 +1,7 @@ /* ARM assembly Raspberry PI */ /* program hellowordLP.s */ .data -szMessage: .asciz "Goodbye world. \n " @ error message +szMessage: .ascii "Goodbye world. \n " @ error message .equ LGMESSAGE, . - szMessage @ compute length of message .text diff --git a/Task/Hello-world-Standard-error/Ballerina/hello-world-standard-error.ballerina b/Task/Hello-world-Standard-error/Ballerina/hello-world-standard-error.ballerina new file mode 100644 index 0000000000..59c24efda3 --- /dev/null +++ b/Task/Hello-world-Standard-error/Ballerina/hello-world-standard-error.ballerina @@ -0,0 +1,5 @@ +import ballerina/io; + +public function main() { + io:fprintln(io:stderr, "Goodbye, World!"); +} diff --git a/Task/Hello-world-Standard-error/Crystal/hello-world-standard-error.cr b/Task/Hello-world-Standard-error/Crystal/hello-world-standard-error.cr new file mode 100644 index 0000000000..59324c7847 --- /dev/null +++ b/Task/Hello-world-Standard-error/Crystal/hello-world-standard-error.cr @@ -0,0 +1 @@ +STDERR.puts "Goodbye, World!" diff --git a/Task/Hello-world-Standard-error/Objeck/hello-world-standard-error.objeck b/Task/Hello-world-Standard-error/Objeck/hello-world-standard-error.objeck new file mode 100644 index 0000000000..4646f8c9cd --- /dev/null +++ b/Task/Hello-world-Standard-error/Objeck/hello-world-standard-error.objeck @@ -0,0 +1,5 @@ +class Goodbye { + function : Main(args : String[]) ~ Nil { + "Goodbye, World!"->ErrorLine(); + } +} diff --git a/Task/Hello-world-Standard-error/Uxntal/hello-world-standard-error.uxnatl b/Task/Hello-world-Standard-error/Uxntal/hello-world-standard-error.uxnatl new file mode 100644 index 0000000000..0e2f4bc50e --- /dev/null +++ b/Task/Hello-world-Standard-error/Uxntal/hello-world-standard-error.uxnatl @@ -0,0 +1,17 @@ +|10 @Console &vector $2 &read $1 &pad $5 &write $1 &error $1 + +|100 + +@on-reset ( -> ) + ;my-string print-error + BRK + +@print-error ( str* -- ) + &while + LDAk .Console/error DEO + INC2 LDAk ?&while + POP2 + JMP2r + +@my-string + "Goodbye 20 "World! 0a00 diff --git a/Task/Hello-world-Text/AArch64-Assembly/hello-world-text.aarch64 b/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-1.aarch64 similarity index 100% rename from Task/Hello-world-Text/AArch64-Assembly/hello-world-text.aarch64 rename to Task/Hello-world-Text/AArch64-Assembly/hello-world-text-1.aarch64 diff --git a/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-2.aarch64 b/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-2.aarch64 new file mode 100644 index 0000000000..390ac3628e --- /dev/null +++ b/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-2.aarch64 @@ -0,0 +1,16 @@ +.global _start + +.text +_start: + mov x8, #64 //64 is write + mov x0, #1 //1 is stdout + adr x1, msg //mov address of msg into x1 + mov x2, #(msgend - msg) //msgend minus msg is the length of message + svc #0 //system call + mov x8, #93 //93 is exit + mov x0, xzr //0 is the exit code. xzr is the zero register + svc #0 //system call + +msg: + .ascii "Hello world!\n" +msgend: diff --git a/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-3.aarch64 b/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-3.aarch64 new file mode 100644 index 0000000000..1cea6a1d2c --- /dev/null +++ b/Task/Hello-world-Text/AArch64-Assembly/hello-world-text-3.aarch64 @@ -0,0 +1,21 @@ +.global _start +.text +_start: + adr x0, msg // load x0 with address of message + bl writez // call the function that writes null-terminated string to stdout + mov x8, #93 // 93 is syscall exit + mov x0, xzr // exit code = 0. Exit normal. + svc #0 // syscall + // If using as a function in C declare it as +writez: // extern long writez(char *str); + mov x1, x0 // address of str needs to be in x1 for syscall + sub x0, x0, #1 // decrement x0, because the next statement increments it. + 0: ldrb w2, [x0, #1]! // increment x0, load byte value at x0 in w2 + cbnz w2, 0b // if w2 is not zero jump back to 0: label + sub x2, x0, x1 // subtract x1 from x0, load into x2. length of str + mov x0, #1 // mov into x0 1. stdout + mov x8, #64 // mov into x8 64. write + svc #0 // syscall + ret // return from function. + // return value (x0) is number of characters written. +msg: .asciz "Hello world!\n" // .asciz means null-terminated string. Assembler adds the 0 diff --git a/Task/Hello-world-Text/OPL/hello-world-text.opl b/Task/Hello-world-Text/OPL/hello-world-text.opl new file mode 100644 index 0000000000..9ecaf7f843 --- /dev/null +++ b/Task/Hello-world-Text/OPL/hello-world-text.opl @@ -0,0 +1,4 @@ +PROC main: + PRINT "Hello, world!" + GET +ENDP diff --git a/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl b/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl deleted file mode 100644 index 7cef15e4e0..0000000000 --- a/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl +++ /dev/null @@ -1,22 +0,0 @@ -( hello-world.tal ) -|00 @System [ &vector $2 &wst $1 &rst $1 &eaddr $2 &ecode $1 &pad $1 &r $2 &g $2 &b $2 &debug $1 &halt $1 ] -|10 @Console [ &vector $2 &read $1 &pad $5 &write $1 &error $1 ] - -( program ) -|0100 @on-reset ( -> ) - ;hello print-str - HALT -BRK - -@print-str ( str* -- ) - &while - LDAk .Console/write DEO - INC2 LDAk ?&while - POP2 -JMP2r - -@HALT ( -- ) - #01 .System/halt DEO -JMP2r - -@hello "Hello 20 "world! 0a 00 diff --git a/Task/Heronian-triangles/EasyLang/heronian-triangles.easy b/Task/Heronian-triangles/EasyLang/heronian-triangles.easy index 6cfcf65e3d..2a218f6902 100644 --- a/Task/Heronian-triangles/EasyLang/heronian-triangles.easy +++ b/Task/Heronian-triangles/EasyLang/heronian-triangles.easy @@ -1,30 +1,22 @@ func gcd x y . - if y = 0 - return x - . + if y = 0 : return x return gcd y (x mod y) . global ta[] tb[] tc[] . -proc mktbl . . - for c = 1 to 200 - for b = 1 to c - for a = 1 to b - s = (a + b + c) / 2 - ar = sqrt (s * (s - a) * (s - b) * (s - c)) - if ar > 0 and ar = floor ar - if gcd gcd b c a = 1 - ta[] &= a - tb[] &= b - tc[] &= c - . - . - . +proc mktbl . + for c = 1 to 200 : for b = 1 to c : for a = 1 to b + s = (a + b + c) / 2 + ar = sqrt (s * (s - a) * (s - b) * (s - c)) + if ar > 0 and ar = floor ar and gcd gcd b c a = 1 + ta[] &= a + tb[] &= b + tc[] &= c . . . mktbl # -proc get i . a b c per ar . +proc get i &a &b &c &per &ar . a = ta[i] b = tb[i] c = tc[i] @@ -36,7 +28,7 @@ func wgt i . get i a b c per ar return ar * 1000000 + per * 1000 + a . -proc sort . . +proc sort . for i = 1 to len ta[] - 1 for j = i + 1 to len ta[] if wgt j < wgt i diff --git a/Task/Hex-words/Crystal/hex-words.cr b/Task/Hex-words/Crystal/hex-words.cr new file mode 100644 index 0000000000..c1aa6e6a4a --- /dev/null +++ b/Task/Hex-words/Crystal/hex-words.cr @@ -0,0 +1,10 @@ +def report (a) + puts + a.each {|hexword| puts "%6s %8d %d" % hexword} + puts "Total count of these words: #{a.size}" +end + +hexwords = File.read_lines("unixdict.txt").reject{|w| w.size < 4 || w.matches?(/[^abcdef]/) } +res = hexwords.map {|hw| {hw, hw.to_i(16), 1 + (hw.to_i(16) - 1) % 9} }.sort_by(&.last) +report res +report res.reject {|hw| hw[0].chars.uniq.size < 4}.sort_by {|w| -w[1] } diff --git a/Task/Hex-words/EasyLang/hex-words.easy b/Task/Hex-words/EasyLang/hex-words.easy index 78f5e8d383..909936e5fd 100644 --- a/Task/Hex-words/EasyLang/hex-words.easy +++ b/Task/Hex-words/EasyLang/hex-words.easy @@ -2,9 +2,7 @@ func ishex w$ . c$ = "" for c$ in strchars w$ h = strcode c$ - if h < 97 or h > 102 - break 1 - . + if h < 97 or h > 102 : break 1 . return if c$ = "" . @@ -17,9 +15,7 @@ func digsum num . return s . func digroot x . - while x > 9 - x = digsum x - . + while x > 9 : x = digsum x return x . func dec w$ . @@ -34,7 +30,7 @@ func comp a$ b$ . . return if digroot dec a$ < digroot dec b$ . -proc sort . . +proc sort . for i = len w$[] - 1 downto 1 for j = 1 to i if comp w$[j] w$[j + 1] = 1 @@ -43,7 +39,7 @@ proc sort . . . . . -proc init . . +proc init . repeat s$ = input until s$ = "" @@ -54,7 +50,7 @@ proc init . . . init sort -proc show . . +proc show . for w$ in w$[] w = dec w$ print digroot w & " " & w$ & " " & w @@ -69,15 +65,11 @@ func dist w$ . for c$ in strchars w$ d[strcode c$ - 96] = 1 . - for e in d[] - s += e - . + for e in d[] : s += e return s . for w$ in w$[] - if dist w$ > 3 - w2$[] &= w$ - . + if dist w$ > 3 : w2$[] &= w$ . swap w$[] w2$[] part2 = 1 diff --git a/Task/Hex-words/R/hex-words.r b/Task/Hex-words/R/hex-words.r new file mode 100644 index 0000000000..32cd03bc0f --- /dev/null +++ b/Task/Hex-words/R/hex-words.r @@ -0,0 +1,43 @@ +library(stringr) + +unixdict <- read.table("unixdict.txt", col.names="words") +hexwords <- subset(unixdict, str_detect(words,"^[a-f]{4,}$")) +hexwords$decimal <- strtoi(hexwords$words, 16L) + +#Method 1 for calculating digital root: casting to a string (slower, but accurate) +dig_root <- function(n){ + while(n>9){ + vec_str <- str_split_1(as.character(n),"") + dig_sum <- sum(as.numeric(vec_str)) + n <- dig_sum + } + return(n) +} + +#Method 2: using modulus operators recursively (can be inaccurate for very large n) +dig_root <- function(n){ + if(n>9){ + return(dig_root(n%%10+dig_root(n%/%10))) + } + return(n) +} + +hexwords$root <- sapply(hexwords$decimal, dig_root) + +hexwords <- sort_by(hexwords, ~root) +rownames(hexwords) <- NULL +print(hexwords) + +#The second part is impossible to do with a single regex AFAIK, so check strings by counting instances of each letter +chars <- letters[1:6] +counts_logical <- function(s){ + counts <- sapply(chars, function(char) str_count(s, char)) + sum(counts>0) +} + +hexwords$has4distinct <- sapply(hexwords$words, counts_logical)>3 + +hexwords_distinct <- subset(hexwords, has4distinct) +hexwords_distinct <- sort_by(hexwords_distinct, ~rev(decimal)) +rownames(hexwords_distinct) <- NULL +print(hexwords_distinct[,1:3]) diff --git a/Task/Hex-words/Rust/hex-words.rs b/Task/Hex-words/Rust/hex-words.rs new file mode 100644 index 0000000000..a398c0b0f0 --- /dev/null +++ b/Task/Hex-words/Rust/hex-words.rs @@ -0,0 +1,83 @@ +use std::collections::HashSet; +use std::fs::File; +use std::io::{BufRead, BufReader}; + +struct Item { + word: String, + number: i32, + digital_root: i32, +} + +fn display(items: &Vec) { + println!(" Word Decimal value Digital root"); + println!("----------------------------------------"); + for item in items { + println!("{:>7} {:>15} {:>12}", item.word, item.number, item.digital_root); + } + println!("\nTotal count: {}\n", items.len()); +} + +fn digital_root(mut number: i32) -> i32 { + let mut result = 0; + while number > 0 { + result += number % 10; + number /= 10; + } + if result <= 9 { + result + } else { + digital_root(result) + } +} + +fn contains_only(word: &str, acceptable: &HashSet) -> bool { + word.chars().all(|ch| acceptable.contains(&ch)) +} + +fn main() -> std::io::Result<()> { + let hex_digits: HashSet = ['a', 'b', 'c', 'd', 'e', 'f'].iter().cloned().collect(); + let mut items = Vec::new(); + + let file = File::open("unixdict.txt")?; + let reader = BufReader::new(file); + + for line in reader.lines() { + if let Ok(word) = line { + if word.len() >= 4 && contains_only(&word, &hex_digits) { + let value = i32::from_str_radix(&word, 16).unwrap(); + let root = digital_root(value); + items.push(Item { + word, + number: value, + digital_root: root, + }); + } + } + } + + items.sort_by(|a, b| { + if a.digital_root == b.digital_root { + a.word.cmp(&b.word) + } else { + a.digital_root.cmp(&b.digital_root) + } + }); + display(&items); + + let mut filtered_items = Vec::new(); + for item in &items { + let unique_chars: HashSet = item.word.chars().collect(); + if unique_chars.len() >= 4 { + filtered_items.push(Item { + word: item.word.clone(), + number: item.number, + digital_root: item.digital_root, + }); + } + } + + filtered_items.sort_by(|a, b| b.number.cmp(&a.number)); + display(&filtered_items); + + Ok(()) +} diff --git a/Task/Higher-order-functions/Pascal/higher-order-functions-3.pas b/Task/Higher-order-functions/Pascal/higher-order-functions-3.pas index 1c3acc304e..6a62902bc3 100644 --- a/Task/Higher-order-functions/Pascal/higher-order-functions-3.pas +++ b/Task/Higher-order-functions/Pascal/higher-order-functions-3.pas @@ -1,720 +1,380 @@ -UNIT MRF; -{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*) - +====================================================================== +(*) + Save to ShortNotation.inc + Use {$INCLUDE ShortNotation.inc} in order to load this file + Load before any other .inc file (*) - Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64 - The free and readable alternative at C/C++ speeds - compiles natively to almost any platform, including raspberry PI * - Can run independently from DELPHI / Lazarus +{$MACRO ON} +(*) Shorthand mainly for lambdas (anonymous functions) (*) - For debian Linux: apt -y install fpc - It contains a text IDE called fp + {$DEFINE Fn := function } + {$DEFINE Proc := procedure } + {$DEFINE spec := specialize } + {$DEFINE ref := reference } + {$DEFINE _ := begin } + {$DEFINE __ := end } - https://www.freepascal.org/advantage.var +(*) defs for WriteLn (*) + {$DEFINE nl := #13#10} + {$DEFINE tab := #9} +====================================================================== +(*) + Save to CompilerSwitches.inc + Use {$INCLUDE CompilerSwitches.inc} in order to load this file +(*) + +{$IFDEF FPC} + {$MODE OBJFPC} + {$M+} + {$LONGSTRINGS ON} + {$ASMMODE INTEL} + {$Q+} + {$RANGECHECKS ON} + {$S+} + {$TYPEDADDRESS ON} + {$MODESWITCH EXCEPTIONS} + {$MODESWITCH ADVANCEDRECORDS} + {$MODESWITCH TYPEHELPERS} + {$MODESWITCH FUNCTIONREFERENCES} + {$MODESWITCH ANONYMOUSFUNCTIONS} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} + + +{$WARNINGS OFF W1033} +{$WARN 6058 OFF} +====================================================================== +unit MRF3 ; (*) -INTERFACE + (c) 2025 jpd - Free to use, experimental - USES - Math, + Free Pascal Compiler version 3.3.1 [2025/03/18] for x86_64 + + Map Reduce Filter version with chaining, generics and lambdas + + https://www.freepascal.org/advantage.var + + +(*) + +{$INCLUDE ShortNotation.inc} + +{$INCLUDE CompilerSwitches.inc} + +interface + +uses + + Generics.Collections, + Generics.Defaults, + StrUtils, SysUtils, - variants; - {$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants + Variants + ; + +type + + V = Variant ; + L = specialize TList ; + + TMapperFunc = ref to Fn ( item: V ; index: Integer ): V ; + TPredicateFunc = ref to Fn ( item: V ; index: Integer ): Boolean ; + TFolderFunc = ref to Fn ( Acc: V ; item: V ; index: Integer ): V ; + TCompareFunc = ref to Fn ( const A, B: V ): Integer ; + + TCollPipe = record + private + FData: L ; + public + constructor Create( Data: L ) ; + Fn Count: Integer; + Fn GroupBy(KeyFunc: TMapperFunc): spec TDictionary; + Fn ForAll(Predicate: TPredicateFunc): Boolean; + Fn Map ( Func: TMapperFunc ) : TCollPipe ; + Fn Filter ( Func: TPredicateFunc ) : TCollPipe ; + Fn Reduce ( Func: TFolderFunc ; initial: V ): V ; + Fn Sort ( Compare: TCompareFunc ): TCollPipe ; + Fn Debug ( const Msg: String ) : TCollPipe ; + Fn ToArray: L ; + end ; + + Fn List( const Elements: array of V ): L ; + Fn Pipe( Data: L ): TCollPipe ; inline ; + proc DebugList(const List: L; const Msg: String); + Fn SortAndDebug(const List: L; Compare: TCompareFunc; const Msg: String): L; + + (*) Core FP Functions (*) + + Fn Map ( const Arr: L ; Func: TMapperFunc ): L ; + Fn Filter ( const Arr: L ; Func: TPredicateFunc ): L ; + Fn Reduce ( const Arr: L ; Func: TFolderFunc ; initial: V ): V ; + + + +implementation + + proc DebugList(const List: L; const Msg: String); + begin + Pipe(List).Debug(Msg); // Convert TList to TCollPipe once + end; + + Fn SortAndDebug(const List: L; Compare: TCompareFunc; const Msg: String): L; + _ + Result := Pipe(List) + .Sort(Compare) + .Debug(Msg) + .ToArray; + __; + + Fn TCollPipe.Count: Integer; + _ + Result := FData.Count; + __; + + Fn TCollPipe.GroupBy(KeyFunc: TMapperFunc): spec TDictionary; + var + i: Integer; + key: V; + group: L; + _ + Result := spec TDictionary.Create; + for i := 0 to FData.Count - 1 do + _ + key := KeyFunc(FData[i], i); + if not Result.TryGetValue(key, group) then + _ + group := L.Create; + Result.Add(key, group); + __; + group.Add(FData[i]); + __; + __; - TYPE + Fn TCollPipe.ForAll(Predicate: TPredicateFunc): Boolean; + var + i: Integer; + _ + Result := True; + for i := 0 to FData.Count - 1 do + _ + if not Predicate(FData[i], i) then + _ + Result := False; + Exit; + __; + __; + __; - Varyray = array of variant ; - FunA = FUNCTION ( x : variant ) : variant ; - FunB = PROCEDURE ( x : variant ) ; - FunC = FUNCTION ( x,y : variant ) : variant ; - FunD = FUNCTION ( x,y : longint ) : longint ; - FunE = FUNCTION ( x,y : variant ) : variant ; + Fn List( const Elements: array of V ): L ; + var elem: V ; + _ + Result := L.Create ; + for elem in Elements do + Result.Add( elem ) ; + __ ; - PROCEDURE Show ( x : variant ) ; - FUNCTION Reverse ( x : Varyray ) : Varyray ; - FUNCTION Head ( x : Varyray ) : variant ; - FUNCTION Last ( x : Varyray ) : variant ; - FUNCTION Tail ( x : Varyray ) : Varyray ; - FUNCTION Take ( y : variant ; x : Varyray ) : Varyray ; - FUNCTION Map ( f : FunA ; x: Varyray ) : Varyray ; overload ; - PROCEDURE Map ( f : FunB ; x: Varyray ) ; overload ; - FUNCTION Map ( f : FunC ; x, y: Varyray ) : Varyray ; overload ; - FUNCTION Map ( f : FunD ; x, y: Varyray ) : Varyray ; overload ; - FUNCTION Filter ( f : FunA ; x: Varyray ) : Varyray ; overload ; - FUNCTION Filter ( f : FunE ; y: variant; x: Varyray ) : Varyray ; overload ; - FUNCTION FoldL ( f : FunC ; x: Varyray ) : variant ; overload ; - FUNCTION FoldL ( f : FunD ; x: Varyray ) : variant ; overload ; - FUNCTION FoldL ( f : FunE ; y: variant; x: Varyray ) : variant ; overload ; - FUNCTION Reduce ( f : FunC ; x: Varyray ) : variant ; overload ; - FUNCTION Reduce ( f : FunD ; x: Varyray ) : variant ; overload ; - FUNCTION Reduce ( f : FunE ; y: variant; x: Varyray ) : variant ; overload ; - FUNCTION FoldR ( f : FunC ; x: Varyray ) : variant ; overload ; - FUNCTION FoldR ( f : FunD ; x: Varyray ) : variant ; overload ; -(*) FOR TESTING (*) - FUNCTION RandFillInt ( x: variant ) : variant ; - FUNCTION RandFillReal ( x: variant ) : variant ; + constructor TCollPipe.Create( Data: L ) ; + _ + FData := L.Create ; + FData.AddRange( Data ) ; + __ ; - FUNCTION AND_xy ( x, y: variant ) : variant ; - FUNCTION OR_xy ( x, y: variant ) : variant ; - FUNCTION AVG ( x: Varyray ) : variant ; - FUNCTION All ( f: FunA ; x: Varyray ) : variant ; - FUNCTION Any ( f: FunA ; x: Varyray ) : variant ; - FUNCTION Add ( x, y: variant ) : variant ; - FUNCTION Mult ( x, y: variant ) : variant ; - FUNCTION contain ( x, y: variant ) : variant ; - FUNCTION delete ( x, y: variant ) : variant ; - FUNCTION Add1 ( x: variant ) : variant ; - FUNCTION sine ( x: variant ) : variant ; - FUNCTION cosine ( x: variant ) : variant ; - FUNCTION cotangens ( x: variant ) : variant ; - FUNCTION Is_Even ( x: variant ) : variant ; - FUNCTION Is_Odd ( x: variant ) : variant ; + Fn TCollPipe.Map( Func: TMapperFunc ): TCollPipe ; + _ + Result := TCollPipe.Create( MRF3.Map( FData, Func ) ) ; + __ ; -IMPLEMENTATION + Fn TCollPipe.Filter( Func: TPredicateFunc ): TCollPipe ; + _ + Result := TCollPipe.Create( MRF3.Filter( FData, Func ) ) ; + __ ; - PROCEDURE Show ( x: variant ) ; - BEGIN write( x, ' ' ) ; END ; + Fn TCollPipe.Reduce( Func: TFolderFunc ; initial: V ): V ; + _ + Result := MRF3.Reduce( FData, Func, initial ) ; + __ ; - FUNCTION Reverse ( x : Varyray ) : Varyray ; - VAR - __ : varyray ; - k : integer ; + Fn TCollPipe.Sort( Compare: TCompareFunc ): TCollPipe; + var + NewList: L; + _ + NewList := L.Create; + NewList.AddRange(FData); + NewList.Sort(spec TComparer.Construct(Compare)); + Result := TCollPipe.Create(NewList); + __ ; - BEGIN - IF length ( x ) < Low ( x ) + 2 THEN Exit ; - Setlength ( __, length ( x ) ); + Fn TCollPipe.Debug( const Msg: String ): TCollPipe ; - FOR k := Low ( x ) to High ( x ) DO - __ [ k ] := x [ High ( x ) - k ] ; + var + i: Integer ; + s: String ; + _ + s := Msg + ' [ ' ; - result := __ ; + if FData.Count > 1 then + for i := 0 to FData.Count - 2 do + s := s + VarToStr( FData[ i ] ) + ', ' + else + i := -1 ; - Setlength ( __, 0 ); + Writeln( s + VarToStr( FData[ i + 1 ] ), ' ]' ) ; + Result := Self ; + __ ; - END; + Fn TCollPipe.ToArray: L ; + _ + Result := L.Create ; + Result.AddRange( FData ) ; + __ ; - FUNCTION Head ( x : Varyray ) : variant ; - BEGIN result := x [ Low ( x ) ] ; END; + Fn Pipe( Data: L ): TCollPipe ; + _ + Result := TCollPipe.Create( Data ) ; + __ ; - FUNCTION Last ( x : Varyray ) : variant ; - BEGIN result := x [ High ( x ) ] ; END; + Fn Map( const Arr: L ; Func: TMapperFunc ): L ; - FUNCTION Tail ( x : Varyray ) : Varyray ; + var i: Integer ; + _ + Result := L.Create ; + for i := 0 to Arr.Count - 1 do + Result.Add( Func( Arr[ i ], i ) ) ; + __ ; - VAR - __ : varyray ; - k : integer ; - BEGIN - Setlength ( __, High ( x ) ); + Fn Filter( const Arr: L ; Func: TPredicateFunc ): L ; - FOR k := Low ( x ) + 1 to High ( x ) DO - __ [ k - 1 ] := x [ k ] ; + var i: Integer ; + _ + Result := L.Create ; + for i := 0 to Arr.Count - 1 do + if Func( Arr[ i ], i ) then + Result.Add( Arr[ i ] ) ; + __ ; - result := __ ; - Setlength ( __, 0 ); - END; + Fn Reduce( const Arr: L ; Func: TFolderFunc ; initial: V ): V ; + var i: Integer ; + _ + Result := initial ; + for i := 0 to Arr.Count - 1 do + Result := Func( Result, Arr[ i ], i ) ; + __ ; +end. ( * ) unit MRF3 ( * ) - FUNCTION Take ( y : variant ; x : Varyray ) : Varyray ; +====================================================================== +program testMRF3; - VAR - __ : varyray ; - k : integer ; +{$include ShortNotation.inc} - BEGIN +{$INCLUDE CompilerSwitches.inc} +uses - Setlength ( __, y ); + Math, + MRF3, + StrUtils, + SysUtils, + Variants + ; - FOR k := Low ( x ) to y - 1 DO - __ [ k ] := x [ k ] ; - result := __ ; + Fn IsNumber( item: V ): Boolean ; - Setlength ( __, 0 ); + _ + Result := VarIsNumeric( item ) and not VarIsBool( item ) ; + __; - END; + Fn CompareVariants( const A, B: V ): Integer ; + _ - FUNCTION Map ( f: FunA ; x: Varyray ) : Varyray ; overload ; + if VarIsNumeric( A ) and VarIsNumeric( B ) then + Exit( CompareValue( Double( A ), Double( B ) ) ) ; - VAR + if VarIsStr( A ) and VarIsStr( B ) then + Exit( CompareText( A, B ) ) ; - Ar : array of variant ; - k : integer ; + (*) Fallback: priority ( booleans < numbers < strings < ) (*) - BEGIN + Result := ( Ord( VarIsStr( A ) ) - Ord( VarIsStr( B ) ) ); + __; - SetLength ( Ar, length ( x ) ) ; - result := Ar ; +(*) MAIN Line (*) - FOR k := Low ( Ar ) TO High ( Ar ) DO - Ar [ k ] := f ( x [ k ] ) ; + var + Data : L ; + Total: Double ; - result := Ar ; + _ + try + Writeln( '=== MRF3 Unit Test ===' ) ; - Setlength ( Ar, 0 ); + Data := List( [ 15, 2.5, 'Apple', True, 7, 'banana', False ] ) ; - END; + Pipe( Data ) + .Debug( 'Original:' ) + .Sort( @CompareVariants ) + .Debug( 'Sorted:' ) ; + Total := Pipe( Data ) + .Filter ( Fn ( item: V; index: Integer ) : Boolean + _ Result := IsNumber( item ) ; + __ + ) - PROCEDURE Map ( f: FunB ; x: Varyray ) ; overload ; + .Map ( Fn ( item: V; index: Integer ) : V + _ Result := Double( item ) * 2 ; + __ + ) - VAR + .Reduce ( Fn ( Acc: V; item: V; index: Integer ): V + _ Result := Double( Acc ) + Double( item ) ; + __ + , 0.0 + ) + ; - k : integer ; + Writeln( 'Numeric sum x2: ', Total:0:2 ) ; - BEGIN - FOR k := Low ( x ) TO High ( x ) DO f ( x [ k ] ) ; - END; + except + on E: Exception do + Writeln( 'Error: ', E.Message ) ; + end; + Readln; - - FUNCTION Map ( f: FunC ; x, y: Varyray ) : Varyray ; overload ; - - VAR - - Ar : array of variant ; - k : integer ; - - BEGIN - - SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ; - - FOR k := Low ( Ar ) TO High ( Ar ) DO - Ar [ k ] := f ( x [ k ] , y [ k ] ) ; - - result := Ar ; - - Setlength ( Ar, 0 ); - - END; - - - - FUNCTION Map ( f: FunD ; x, y: Varyray ) : Varyray ; overload ; - - VAR - - Ar : array of variant ; - k : integer ; - - BEGIN - - SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ; - - FOR k := Low ( Ar ) TO High ( Ar ) DO - Ar [ k ] := f ( x [ k ] , y [ k ] ) ; - - result := Ar ; - - Setlength ( Ar, 0 ); - - END; - - - - FUNCTION Map ( f: FunE ; x: variant; y: Varyray ) : Varyray ; overload ; - - VAR - - Ar : array of variant ; - k : integer ; - - BEGIN - - SetLength ( Ar, min ( length ( x ) , length ( y ) ) ) ; - - FOR k := Low ( Ar ) TO High ( Ar ) DO - Ar [ k ] := f ( x , y [ k ] ) ; - - result := Ar ; - - Setlength ( Ar, 0 ); - - END; - - - - FUNCTION Filter ( f: FunA ; x: Varyray ) : Varyray ; overload ; - - VAR - - Ar : array of variant ; - __ : variant ; - k : integer ; - len : integer ; - - BEGIN - - SetLength ( Ar, 0 ) ; - result := Ar ; - - FOR k := Low ( x ) TO High ( x ) DO - BEGIN - - __ := f ( x [ k ] ) ; - - IF __ <> False THEN - - BEGIN - - len := Length ( Ar ) ; - SetLength ( Ar, len + 1 ) ; - Ar [ len ] := __ ; - - END ; - - END ; - - result := Ar ; - - Setlength ( Ar, 0 ); - END; - - - - FUNCTION Filter ( f: FunE ; y: variant; x: Varyray ) : Varyray ; overload ; - - VAR - - Ar : array of variant ; - __ : variant ; - k : integer ; - len : integer ; - - BEGIN - - SetLength ( Ar, 0 ) ; - result := Ar ; - - FOR k := Low ( x ) TO High ( x ) DO - BEGIN - - __ := f ( y, x [ k ] ) ; - - IF __ <> False THEN - - BEGIN - - len := Length ( Ar ) ; - SetLength ( Ar, len + 1 ) ; - Ar [ len ] := __ ; - - END ; - - END ; - - result := Ar ; - - Setlength ( Ar, 0 ); - END; - - - - FUNCTION FoldL ( f: FunC ; x: Varyray ) : variant ; overload ; - - VAR - - k : integer ; - - BEGIN - - result := x [ Low ( x ) ] ; - - FOR k := Low ( x ) + 1 TO High ( x ) DO - result := f ( result , x [ k ] ) ; - - END ; - - - - FUNCTION FoldL ( f: FunD ; x: Varyray ) : variant ; overload ; - - VAR - - k : integer ; - - BEGIN - - result := x [ Low ( x ) ] ; - - FOR k := Low ( x ) + 1 TO High ( x ) DO - result := f ( result , x [ k ] ) ; - - END ; - - - - FUNCTION FoldL ( f: FunE ; y: variant; x: Varyray ) : variant ; overload ; - - VAR - - k : integer ; - - BEGIN - - - FOR k := Low ( x ) TO High ( x ) DO - result := f ( y , x [ k ] ) ; - - END ; - - - - FUNCTION Reduce ( f: FunC ; x: Varyray ) : variant ; overload ; - BEGIN result := FoldL ( f , x ) ; END ; - - - - FUNCTION Reduce ( f: FunD ; x: Varyray ) : variant ; overload ; - BEGIN result := FoldL ( f , x ) ; END ; - - - - FUNCTION Reduce ( f: FunE ; y: variant; x: Varyray ) : variant ; overload ; - BEGIN result := FoldL ( f , y, x ) ; END ; - - - - FUNCTION FoldR ( f: FunC ; x: Varyray ) : variant ; overload ; - - VAR - - k : integer ; - - BEGIN - - result := x [ High ( x ) ] ; - - FOR k := High ( x ) - 1 DOWNTO Low ( x ) DO - result := f ( result, x [ k ] ) ; - - END ; - - - - FUNCTION FoldR ( f: FunD ; x: Varyray ) : variant ; overload ; - - VAR - - k : integer ; - - BEGIN - - - result := x [ High ( x ) ]; - - FOR k := High ( x ) - 1 DOWNTO Low ( x ) DO - result := f ( result, x [ k ] ) ; - - END ; - - - - (*) TEST Functions (*) - -(*) - - Special thanks to PascalDragon , winni & BobDog ( FreePascal.org ), - who explained the specifics of the compiler. - -(*) - - - FUNCTION Add ( x, y: variant ) : variant ; - BEGIN result := x + y ; END ; - - - - FUNCTION Add1 ( x: variant ) : variant ; - BEGIN result := x + 1 ; END ; - - - - FUNCTION AND_xy ( x, y: variant ) : variant ; - BEGIN result := ( x and y ) = True ; END ; - - - - FUNCTION AVG ( x: Varyray ) : variant ; - - VAR - - k : integer ; - - BEGIN - - result := 0.0 ; - - FOR k := Low ( x ) TO High ( x ) DO - result := result + ( x [ k ] - result ) / ( k + 1 ); - - END ; - - - - FUNCTION Cosine ( x: variant ) : variant ; - BEGIN result := cos ( x ); END ; - - - - FUNCTION Cotangens ( x: variant ) : variant ; - - BEGIN - - IF ( x = 0 ) Then Exit ( 'Inf'); - - result := cot ( x ); - - END ; - - - - FUNCTION Is_Even ( x: variant ) : variant ; - - BEGIN - - IF ( ( x mod 2 ) = 0 ) THEN - result := x - ELSE - result := False - - END; - - - - FUNCTION Mult( x, y: variant ) : variant ; - BEGIN result := x * y ; END ; - - - - FUNCTION Contain ( x, y: variant ) : variant ; - BEGIN result := x = y ; END ; - - - - FUNCTION Delete ( x, y: variant ) : variant ; - - BEGIN - - IF ( x = y ) THEN Exit ( False ) ; - - result := y; - - END ; - - - FUNCTION Is_Odd ( x: variant ) : variant ; - - BEGIN - - IF ( ( x mod 2 ) <> 0 ) THEN - result := x - ELSE - result := False - - END; - - - - FUNCTION OR_xy ( x, y: variant ) : variant ; - BEGIN result := ( x or y ) = True; END ; - - - - FUNCTION RandFillInt ( x: variant ) : variant ; - BEGIN result := Random ( 100 ) ; END ; - - - - FUNCTION RandFillReal ( x: variant ) : variant ; - - VAR - tmp : real = 100.0 ; - - BEGIN result := ( Random ( ) ) * tmp ; END ; - - - - FUNCTION sine ( x: variant ) : variant ; - BEGIN result := sin ( x ); END ; - - - - FUNCTION All ( f: FunA ; x: Varyray ) : variant ; - - VAR - - k : integer ; - - BEGIN - - result := True ; - - FOR k := Low ( x ) TO High ( x ) DO - result := AND_xy ( result , f ( x [ k ] ) ) ; - - END ; - - - - FUNCTION Any ( f: FunA ; x: Varyray ) : variant ; - - VAR - - k : integer ; - - BEGIN - - result := False ; - - FOR k := Low ( x ) TO High ( x ) DO - result := OR_xy ( result , f ( x [ k ] ) ) ; - - END ; -END. - - -(*) === How to use in a program === (*) - - -program testMRF.pas; -{$mode Delphi} {$H+} {$J-} {$R+} (*) https://www.freepascal.org/docs-html/prog/progch1.html (*) -USES - MRF, - Math, - SysUtils, - Variants; - {$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants - -VAR - - a,b,c : array of variant ; - - Acc : variant ; - -BEGIN - - Randomize ; - - setlength ( a, 6 ) ; - setlength ( b, 4 ) ; - setlength ( c, 6 ) ; - - a := Map ( RandFillInt , a ) ; - Map ( show , a ) ; - writeln ; - - b := Map ( RandFillInt , b ) ; - Map ( show , b ) ; - writeln ; - - c := Map ( RandFillInt , c ) ; - Map ( show , c ) ; - writeln ; - - Acc := FoldL ( add , a ) ; - WriteLn ( 'Sum = ' , Acc ) ; - writeln ; - - Acc := Reduce ( contain , 31, a ) ; - WriteLn ( 'contains = ' , Acc ) ; - writeln ; - - c := Filter ( delete , 31, a ) ; - WriteLn ( 'del c :' ) ; - Map ( show , c ) ; - writeln ; - - a := Reverse ( c ) ; - WriteLn ( 'reverse c :' ) ; - Map ( show , a ) ; - writeln ; - - Acc := avg ( b ) ; - WriteLn ( 'avg = ' , Acc ) ; - writeln ; - - c := Map ( cotangens , b ) ; - writeln ( 'cot : ' ) ; - Map ( show , c ) ; - writeln ; - - Acc := FoldR ( min , b ) ; - WriteLn ( 'min = ' , Acc ); - writeln ; - - Acc := FoldR ( max , b ) ; - WriteLn ( 'max = ' , Acc ); - writeln ; - - Map ( show , b ) ; - Acc := All ( Is_Odd , b ) ; - writeln ; - WriteLn ( 'All Is_Odd = ' , Acc ) ; - writeln ; - - Map ( show , b ) ; - Acc := Any ( Is_Even , b ) ; - writeln ; - WriteLn ( 'Any Is_Even = ' , Acc ) ; - writeln ; - - Acc := Head ( b ) ; - WriteLn ( 'Head = ' , Acc ) ; - - Acc := Last ( b ) ; - WriteLn ( 'Last = ' , Acc ) ; - - Map ( show , b ) ; - a := Tail ( b ) ; - writeln ; - WriteLn ( 'Tail of b :' ) ; - Map ( show , a ) ; - writeln ; - - Map ( show , b ) ; - a := Take ( 2, b ) ; - writeln ; - WriteLn ( 'Take 2 from b :' ) ; - Map ( show , a ) ; - writeln ; - - setlength ( c, 0 ) ; - setlength ( b, 0 ) ; - setlength ( a, 0 ) ; - - - -END. +end. (*) program testMRF3 (*) +====================================================================== diff --git a/Task/Higher-order-functions/REXX/higher-order-functions-2.rexx b/Task/Higher-order-functions/REXX/higher-order-functions-2.rexx deleted file mode 100644 index 95629ca316..0000000000 --- a/Task/Higher-order-functions/REXX/higher-order-functions-2.rexx +++ /dev/null @@ -1,12 +0,0 @@ -/*REXX program demonstrates the passing of a name of a function to another function. */ -call function 'fact' , 6; say right( 'fact{'$"} = ", 30) result -call function 'square' , 13; say right( 'square{'$"} = ", 30) result -call function 'cube' , 3; say right( 'cube{'$"} = ", 30) result -call function 'reverse', 721; say right( 'reverse{'$"} = ", 30) result -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -cube: return $**3 -fact: procedure expose $; !=1; do j=2 to $; !=!*j; end; return ! -function: arg ?.; parse arg ,$; signal value (?.) -reverse: return 'REVERSE'($) -square: return $**2 diff --git a/Task/Higher-order-functions/REXX/higher-order-functions-1.rexx b/Task/Higher-order-functions/REXX/higher-order-functions.rexx similarity index 69% rename from Task/Higher-order-functions/REXX/higher-order-functions-1.rexx rename to Task/Higher-order-functions/REXX/higher-order-functions.rexx index 11f07018d9..2a618f1913 100644 --- a/Task/Higher-order-functions/REXX/higher-order-functions-1.rexx +++ b/Task/Higher-order-functions/REXX/higher-order-functions.rexx @@ -1,7 +1,8 @@ include Settings -Main: -say version; say 'Higher-order functions'; say +say 'HIGHER-ORDER FUNCTIONS - 2 Mar 2025' +say version +say call Calculate '1/x',6 call Calculate 'Sqrt(x)',2 call Calculate 'Sin(x)',1 @@ -14,14 +15,9 @@ exit Calculate: procedure parse arg ff,xx -say ff 'for x='xx 'makes' Evaluate(ff,xx)+0 +say ff 'for x='xx 'makes' Eval(ff,xx)+0 return -Evaluate: -procedure -parse arg f,x -interpret 'return' f - include Functions include Constants include Abend diff --git a/Task/Hilbert-curve/EasyLang/hilbert-curve.easy b/Task/Hilbert-curve/EasyLang/hilbert-curve.easy index 2ec0f3ac60..648255ff81 100644 --- a/Task/Hilbert-curve/EasyLang/hilbert-curve.easy +++ b/Task/Hilbert-curve/EasyLang/hilbert-curve.easy @@ -1,9 +1,16 @@ order = 64 -linewidth 32 / order +glinewidth 32 / order scale = 100 / order - 100 / (order * order) -proc hilbert x y lg i1 i2 . . +xp = 0 / 0 +yp = xp +proc xline x y . + if xp = xp : gline xp yp x y + xp = x + yp = y +. +proc hilbert x y lg i1 i2 . if lg = 1 - line (order - x) * scale (order - y) * scale + xline (order - x) * scale (order - y) * scale return . lg = lg div 2 diff --git a/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy b/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy index 4a4c98272d..e865796ed7 100644 --- a/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy +++ b/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy @@ -1,4 +1,4 @@ -numfmt 4 0 +numfmt 0 4 a[] = [ 1 1 ] x = 1 n = 2 @@ -12,9 +12,7 @@ for p = 1 to 19 a[] &= x f = x / n max = higher max f - if f >= 0.55 - mallow = n - . + if f >= 0.55 : mallow = n . print "max between 2^" & p & " and 2^" & p + 1 & " was " & max . diff --git a/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy b/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy index 5cd6bf9baf..cb073d5c52 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy +++ b/Task/Hofstadter-Figure-Figure-sequences/EasyLang/hofstadter-figure-figure-sequences.easy @@ -1,5 +1,5 @@ global rs[] ss[] . -procdecl RS_append . . +procdecl RS_append . func R n . while n > len rs[] RS_append @@ -12,7 +12,7 @@ func S n . . return ss[n] . -proc RS_append . . +proc RS_append . n = len rs[] r = R n + S n s = S len ss[] diff --git a/Task/Hofstadter-Q-sequence/EasyLang/hofstadter-q-sequence.easy b/Task/Hofstadter-Q-sequence/EasyLang/hofstadter-q-sequence.easy index 4a1d578fcb..20beb55cac 100644 --- a/Task/Hofstadter-Q-sequence/EasyLang/hofstadter-q-sequence.easy +++ b/Task/Hofstadter-Q-sequence/EasyLang/hofstadter-q-sequence.easy @@ -1,20 +1,16 @@ -proc hofstadter limit . q[] . +proc hofstadter limit &q[] . q[] = [ 1 1 ] for n = 3 to limit q[] &= q[n - q[n - 1]] + q[n - q[n - 2]] . . -proc count . q[] cnt . +proc count &q[] &cnt . for i = 2 to len q[] - if q[i] < q[i - 1] - cnt += 1 - . + if q[i] < q[i - 1] : cnt += 1 . . hofstadter 100000 hofq[] -for i = 1 to 10 - write hofq[i] & " " -. +for i = 1 to 10 : write hofq[i] & " " print "" print hofq[1000] count hofq[] cnt diff --git a/Task/Home-primes/REXX/home-primes-1.rexx b/Task/Home-primes/REXX/home-primes-1.rexx deleted file mode 100644 index a984657af5..0000000000 --- a/Task/Home-primes/REXX/home-primes-1.rexx +++ /dev/null @@ -1,46 +0,0 @@ -/*REXX program finds and displays the home prime of a range of positive integers. */ -numeric digits 20 /*ensure handling of larger integers. */ -parse arg LO HI . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 2 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 20 /* " " " " " " */ -@hpc= 'home prime chain for ' /*a literal used in two SAY statements.*/ - w= length(HI) /*HI width, used for output alignment. */ - do j=max(2, LO) to HI /*find home primes for an integer range*/ - pf= factr(j); f= words(pf) /*get prime factors; number of factors.*/ - if f==1 then do; say @hpc j": " j ' is prime.'; iterate; end /*J is prime*/ - xxx.1= j /*save J in the first array element. */ - do n=2 until #==1 /*keep processing until we find a prime*/ - xxx.n= space(pf, 0) /*obtain factors of a concatenated p.f.*/ - pf= factr(xxx.n); #= words(pf) /*assign factors to PF; # of factors. */ - end /*n*/ - ee= n /*save EE as the final (last) prime. */ - n= n - 1; z= n /*adjust N (for DO loop); assign N to Z*/ - $= /*nullify the string of home primes. */ - do m=1 for n /*build a list ($) of " " */ - $= $ 'HP'xxx.m"("z') ─► ' /*concatenate to string of " " */ - z= z - 1 /*decrease the index counter by unity. */ - end /*m*/ /* [↑] the index counter is decreasing*/ - - say @hpc right(j, w)":" $ xxx.ee ' is prime.' /*show string of home primes.*/ - end /*n*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -factr: procedure; parse arg x 1 d,$ /*set X, D to argument 1; $ to null.*/ - if x==1 then return '' /*handle the special case of X = 1. */ - do while x//2==0; $= $ 2; x= x% 2; end /*append all the 2 factors of new X.*/ - do while x//3==0; $= $ 3; x= x% 3; end /* " " " 3 " " " " */ - do while x//5==0; $= $ 5; x= x% 5; end /* " " " 5 " " " " */ - do while x//7==0; $= $ 7; x= x% 7; end /* " " " 7 " " " " */ - q= 1; r= 0 /*R: will be iSqrt(x). ___*/ - do while q<=x; q=q*4; end /*these two lines compute integer √ X */ - do while q>1; q=q%4; _= d-r-q; r= r%2; if _>=0 then do; d= _; r= r+q; end; end - - do k=11 by 6 to r /*insure that J isn't divisible by 3.*/ - parse var k '' -1 _ /*obtain the last decimal digit of K. */ - if _\==5 then do while x//k==0; $=$ k; x=x%k; end /*maybe reduce by K.*/ - if _ ==3 then iterate /*Is next Y is divisible by 5? Skip.*/ - y= k+2; do while x//y==0; $=$ y; x=x%y; end /*maybe reduce by Y.*/ - end /*k*/ - /* [↓] The $ list has a leading blank.*/ - if x==1 then return $ /*Is residual=unity? Then don't append.*/ - return $ x /*return $ with appended residual. */ diff --git a/Task/Home-primes/REXX/home-primes-2.rexx b/Task/Home-primes/REXX/home-primes-2.rexx deleted file mode 100644 index 7e9d82baa9..0000000000 --- a/Task/Home-primes/REXX/home-primes-2.rexx +++ /dev/null @@ -1,40 +0,0 @@ -include Settings - -say version; say 'Home Primes'; say -numeric digits 22 -do i = 1 to 48 - call Home i -end -exit - -Home: -procedure expose fact. glob. work. -arg xx -call Time('r') -yy = xx/1 -/* Collect chain */ -n = 0 -do while Factors(yy) > 1 - n = n+1; work.n = yy; yy = '' - do i = 1 to fact.0 - yy = yy||fact.factor.i - end -end -/* Show results */ -if n = 0 then - call Charout ,'HP'xx '= ' -else do - do i = 1 to n - call Charout ,'HP'work.i'('n-i+1') = ' - end -end -call Charout ,yy -say -say Time('e')/1 'seconds' -say -return - -include Abend -include Functions -include Numbers -include Sequences diff --git a/Task/Home-primes/REXX/home-primes.rexx b/Task/Home-primes/REXX/home-primes.rexx new file mode 100644 index 0000000000..7be1fef20a --- /dev/null +++ b/Task/Home-primes/REXX/home-primes.rexx @@ -0,0 +1,48 @@ +-- 25 Apr 2025 +include Settings + +say 'HOME PRIMES' +say version +say +numeric digits 50 +do i = 1 to 48 + call Home i +end +exit + +Home: +procedure expose fact. glob. work. +arg xx +call Time('r') +if xx = 1 then + call charout ,'HP1 = 1' +else do + yy = xx/1 +-- Collect chain + n = 0 + do while Factors(yy) > 1 + n = n+1; work.n = yy; yy = '' + do i = 1 to fact.0 + yy = yy||fact.i + end + end +-- Show results + if n = 0 then + call Charout ,'HP'xx '= ' + else do + do i = 1 to n + call Charout ,'HP'work.i'('n-i+1') = ' + end + end + call Charout ,yy +end +say +call Timer +say +return + +include Helper +include Abend +include Functions +include Numbers +include Sequences diff --git a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx index b74d9bd5cb..98fb4c679f 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx +++ b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx @@ -1,5 +1,8 @@ include Settings -say version; say 'Polynomial Horner''s rule'; say + +say 'POLYNOMIAL HORNER''S RULE - 2 Mar 2025' +say version +say call Evaluate '6 -4 7 -19',3 call Evaluate '2',4 call Evaluate '2 3',0 diff --git a/Task/Humble-numbers/EasyLang/humble-numbers.easy b/Task/Humble-numbers/EasyLang/humble-numbers.easy index 294a66c460..035ba4e445 100644 --- a/Task/Humble-numbers/EasyLang/humble-numbers.easy +++ b/Task/Humble-numbers/EasyLang/humble-numbers.easy @@ -1,19 +1,9 @@ fastfunc humble i . - if i <= 1 - return 1 - . - if i mod 2 = 0 - return humble (i / 2) - . - if i mod 3 = 0 - return humble (i / 3) - . - if i mod 5 = 0 - return humble (i / 5) - . - if i mod 7 = 0 - return humble (i / 7) - . + if i <= 1 : return 1 + if i mod 2 = 0 : return humble (i / 2) + if i mod 3 = 0 : return humble (i / 3) + if i mod 5 = 0 : return humble (i / 5) + if i mod 7 = 0 : return humble (i / 7) return 0 . fastfunc next_humble n . @@ -28,12 +18,8 @@ while cnt < 5193 n = next_humble n arr[log10 n + 1] += 1 cnt += 1 - if cnt <= 50 - write n & " " - . + if cnt <= 50 : write n & " " . print "" print "" -for i to 9 - print arr[i] & " with " & i & " digits" -. +for i to 9 : print arr[i] & " with " & i & " digits" diff --git a/Task/Humble-numbers/REXX/humble-numbers-1.rexx b/Task/Humble-numbers/REXX/humble-numbers-1.rexx deleted file mode 100644 index c4f9c240cd..0000000000 --- a/Task/Humble-numbers/REXX/humble-numbers-1.rexx +++ /dev/null @@ -1,44 +0,0 @@ -/*REXX program computes and displays humble numbers, also will display counts of sizes.*/ -parse arg n m . /*obtain optional arguments from the CL*/ -if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ -if m=='' | m=="," then m= 60 /* " " " " " " */ -numeric digits 1 + max(20, m) /*be able to handle some big numbers. */ -$.= 0 /*a count array for X digit humble #s*/ -call humble n; list= /*call HUMBLE sub; initialize the list.*/ - do j=1 for n; list= list @.j /*append a humble number to the list.*/ - end /*j*/ - -if list\='' then do; say "A list of the first " n ' humble numbers are:' - say strip(list) /*elide the leading blank in the list. */ - end -say -call humble -m /*invoke subroutine for counting nums. */ -if $.1==0 then exit /*if no counts, then we're all finished*/ -total= 0 /*initialize count of humble numbers. */ -$.1= $.1 + 1 /*adjust count for absent 1st humble #.*/ -say ' The digit counts of humble numbers:' -say ' ═════════════════════════════════════════' - do c=1 while $.c>0; s= left('s', length($.c)>1) /*count needs pluralization?*/ - say right( commas($.c), 30) ' have ' right(c, 2) " digit"s - total= total + $.c /* ◄─────────────────────────────────┐ */ - end /*k*/ /*bump humble number count (so far)──┘ */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: procedure; arg _; do i=length(_)-3 to 1 by -3; _=insert(',', _, i); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -humble: procedure expose @. $.; parse arg x; if x==0 then return - y= abs(x); a= y; noCount= x>0; if x<0 then y= 999999999 - #2= 1; #3= 1; #5= 1; #7= 1 /*define the initial humble constants. */ - $.= 0; @.= 0; @.1= 1 /*initialize counts and humble numbers.*/ - do h=2 for y-1 - @.h= min(2*@.#2,3*@.#3,5*@.#5,7*@.#7) /*pick the minimum of 4 humble numbers.*/ - m= @.h /*M: " " " " " " */ - if 2*@.#2 == m then #2 = #2 + 1 /*Is number already defined? Use next #*/ - if 3*@.#3 == m then #3 = #3 + 1 /* " " " " " " "*/ - if 5*@.#5 == m then #5 = #5 + 1 /* " " " " " " "*/ - if 7*@.#7 == m then #7 = #7 + 1 /* " " " " " " "*/ - if noCount then iterate /*Not counting digits? Then iterate. */ - L= length(m); if L>a then leave /*Are we done with counting? Then quit*/ - $.L= $.L + 1 /*bump the digit count for this number.*/ - end /*h*/ /*the humble numbers are in the @ array*/ - return /* " count results " " " $ " */ diff --git a/Task/Humble-numbers/REXX/humble-numbers-2.rexx b/Task/Humble-numbers/REXX/humble-numbers-2.rexx deleted file mode 100644 index c57d584992..0000000000 --- a/Task/Humble-numbers/REXX/humble-numbers-2.rexx +++ /dev/null @@ -1,86 +0,0 @@ -include Settings - -say version; say 'Humble numbers'; say -call Humbles 50 -call ShowFirstN 50 -call Humbles 1e7 -call ShowDistribution -exit - -Humbles: -procedure expose humb. -arg xx -call Time('r') -xx = xx/1 -say 'Collect humble numbers up to the' xx'th' -/* Ensure enough digits */ -numeric digits 2**(Length(xx)+1) -/* Dijkstra */ -humb.humble.1 = 1 -x2 = 2; x3 = 3; x5 = 5; x7 = 7; i2 = 1; i3 = 1; i5 = 1; i7 = 1 -do yy = 2 - h = x2 - if x3 < h then - h = x3 - if x5 < h then - h = x5 - if x7 < h then - h = x7 - humb.humble.yy = h - if yy = xx then - leave - if x2 = h then do - i2 = i2+1; x2 = humb.humble.i2+humb.humble.i2 - end - if x3 = h then do - i3 = i3+1; x3 = humb.humble.i3+humb.humble.i3+humb.humble.i3 - end - if x5 = h then do - i5 = i5+1; x5 = humb.humble.i5*5 - end - if x7 = h then do - i7 = i7+1; x7 = humb.humble.i7*7 - end -end -humb.0 = yy -say Time('e')/1 'seconds' -say -return - -ShowFirstN: -procedure expose humb. -arg xx -call Time('r') -xx = xx/1 -say 'First' xx 'humble numbers are' -do i = 1 to xx - call Charout ,Right(humb.humble.i,4) - if i//10 = 0 then - say -end -say Time('e')/1 'seconds' -say -return - -ShowDistribution: -procedure expose humb. -call Time('r') -say 'Digit distribution for the first' humb.0 'humble numbers' -d. = 0 -do i = 1 to humb.0 - l = Length(humb.humble.i); d.l = d.l + 1; d.0 = Max(l,d.0) -end -l = Copies('-',17) -say l -say 'Dg Count Cum' -say l -c = 0 -do i = 1 to d.0-1 - c = c + d.i - say Right(i,2) Right(d.i,6) Right(c,7) -end -say l -say Time('e')/1 'seconds' -return - -include Abend diff --git a/Task/Humble-numbers/REXX/humble-numbers.rexx b/Task/Humble-numbers/REXX/humble-numbers.rexx new file mode 100644 index 0000000000..be90435bee --- /dev/null +++ b/Task/Humble-numbers/REXX/humble-numbers.rexx @@ -0,0 +1,48 @@ +-- 22 Mar 2025 +include Settings + +say 'HUMBLE NUMBERS' +say version +say +call Humbles 50 +call ShowFirstN 50 +call Humbles 10000000 +call ShowDistribution +say Time('e')/1 'seconds' +exit + +ShowFirstN: +procedure expose humb. +arg xx +xx = xx/1 +say 'First' xx 'humble numbers are' +do i = 1 to xx + call Charout ,Right(humb.i,4) + if i//10 = 0 then + say +end +say +return + +ShowDistribution: +procedure expose humb. +say 'Digit distribution for the first' humb.0 'humble numbers' +d. = 0 +do i = 1 to humb.0 + l = Length(humb.i); d.l = d.l + 1; d.0 = Max(l,d.0) +end +l = Copies('-',17) +say l +say 'Dg Count Cum' +say l +c = 0 +do i = 1 to d.0-1 + c = c + d.i + say Right(i,2) Right(d.i,6) Right(c,7) +end +say l +return + +include Abend +include Functions +include Sequences diff --git a/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu new file mode 100644 index 0000000000..2c9926743c --- /dev/null +++ b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-1.nu @@ -0,0 +1,32 @@ +# Fetch and process the word list +let words = open unixdict.txt | lines | where { ($in | str length) > 3 } + +# Function to count matches for a pattern +def count-pattern [pattern: string] { + $words | where $it =~ $pattern | length +} + +# Count occurrences for "I before E" rule +let ie_not_c = (count-pattern "(^|[^c])ie") # ie not preceded by c +let ei_not_c = (count-pattern "(^|[^c])ei") # ei not preceded by c + +# Count occurrences for "E before I" rule +let cei = (count-pattern "cei") # ei preceded by c +let cie = (count-pattern "cie") # ie preceded by c + +# Check plausibility (more than 2x occurrences of opposite) +let rule1_plausible = ($ie_not_c > ($ei_not_c * 2)) +let rule2_plausible = ($cei > ($cie * 2)) + +# Output results +print [ + $"Analyzing 'I before E when not preceded by C':" + $" correct for : ($ie_not_c)" + $" not correct for : ($ei_not_c)" + $" Plausible: ($rule1_plausible)" + $"" + $"Analyzing 'E before I when preceded by C':" + $" correct for : ($cei)" + $" not correct for : ($cie)" + $" Plausible: ($rule2_plausible)" + ] diff --git a/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu new file mode 100644 index 0000000000..4519c2d750 --- /dev/null +++ b/Task/I-before-E-except-after-C/Nu/i-before-e-except-after-c-2.nu @@ -0,0 +1,48 @@ +# Fetch and filter words +let words = open unixdict.txt | lines | where { $in | str length | $in > 3 } + +# Define patterns and their processing in a functional way +let patterns = [ + { name: "ie_not_c", pattern: "(^|[^c])ie", desc: "I before E when not preceded by C" } + { name: "ei_not_c", pattern: "(^|[^c])ei", desc: null } + { name: "cei", pattern: "cei", desc: "E before I when preceded by C" } + { name: "cie", pattern: "cie", desc: null } +] + +# Count matches for each pattern functionally +let counts = $patterns | + each { |p| + $p | upsert count ($words | where $it =~ $p.pattern | length) + } + +# Calculate plausibility using match +let results = $counts | + each { |row| + match $row.name { + "ie_not_c" => { + let opposite = ($counts | where name == "ei_not_c" | get count.0) + $row | upsert plausible ($row.count > ($opposite * 2)) + } + "cei" => { + let opposite = ($counts | where name == "cie" | get count.0) + $row | upsert plausible ($row.count > ($opposite * 2)) + } + _ => $row + } + } + +# Format and print results functionally +$results | + where desc != null | + each { |rule| + let opposite = ($results | where name == (if $rule.name == "ie_not_c" { "ei_not_c" } else { "cie" }) | get 0) + [ + $"Analyzing '($rule.desc)':" + $" correct for : ($rule.count)" + $" not correct for : ($opposite.count)" + $" Plausible: ($rule.plausible)" + "" + ] + } | + flatten | + print $in diff --git a/Task/IBAN/EasyLang/iban.easy b/Task/IBAN/EasyLang/iban.easy index 20ac406d24..161c31d836 100644 --- a/Task/IBAN/EasyLang/iban.easy +++ b/Task/IBAN/EasyLang/iban.easy @@ -47,7 +47,7 @@ func isvalid hiban$ . . return if mod97 t$ = 1 . -proc check s$ . . +proc check s$ . write s$ & " is " if isvalid s$ = 1 print "valid" diff --git a/Task/Identity-matrix/EasyLang/identity-matrix.easy b/Task/Identity-matrix/EasyLang/identity-matrix.easy index d1552ef970..b85b3166c1 100644 --- a/Task/Identity-matrix/EasyLang/identity-matrix.easy +++ b/Task/Identity-matrix/EasyLang/identity-matrix.easy @@ -1,4 +1,4 @@ -proc idmat lng . mat[][] . +proc idmat lng &mat[][] . len mat[][] lng for i to lng len mat[i][] lng diff --git a/Task/Identity-matrix/Excel/identity-matrix.excel b/Task/Identity-matrix/Excel/identity-matrix-1.excel similarity index 100% rename from Task/Identity-matrix/Excel/identity-matrix.excel rename to Task/Identity-matrix/Excel/identity-matrix-1.excel diff --git a/Task/Identity-matrix/Excel/identity-matrix-2.excel b/Task/Identity-matrix/Excel/identity-matrix-2.excel new file mode 100644 index 0000000000..f72b963773 --- /dev/null +++ b/Task/Identity-matrix/Excel/identity-matrix-2.excel @@ -0,0 +1 @@ +=MUNIT(A2) diff --git a/Task/Im-a-software-engineer-get-me-out-of-here/Python/im-a-software-engineer-get-me-out-of-here.py b/Task/Im-a-software-engineer-get-me-out-of-here/Python/im-a-software-engineer-get-me-out-of-here.py new file mode 100644 index 0000000000..c3f70e7ca3 --- /dev/null +++ b/Task/Im-a-software-engineer-get-me-out-of-here/Python/im-a-software-engineer-get-me-out-of-here.py @@ -0,0 +1,175 @@ +from collections import deque +from dataclasses import dataclass +from typing import List + +@dataclass(frozen=True) +class CellWithCost: + fromRow: int + fromCol: int + cost: int + +ZERO = CellWithCost(0, 0, 0) + +@dataclass +class Cell: + row: int + col: int + + def __repr__(self): + return f"({self.row}, {self.col})" + +GMOOH = ( + ".........00000.........\n" + "......00003130000......\n" + "....000321322221000....\n" + "...00231222432132200...\n" + "..0041433223233211100..\n" + "..0232231612142618530..\n" + ".003152122326114121200.\n" + ".031252235216111132210.\n" + ".022211246332311115210.\n" + "00113232262121317213200\n" + "03152118212313211411110\n" + "03231234121132221411410\n" + "03513213411311414112320\n" + "00427534125412213211400\n" + ".013322444412122123210.\n" + ".015132331312411123120.\n" + ".003333612214233913300.\n" + "..0219126511415312570..\n" + "..0021321524341325100..\n" + "...00211415413523200...\n" + "....000122111322000....\n" + "......00001120000......\n" + ".........00000.........\n" +).strip().splitlines() +HEIGHT, WIDTH = len(GMOOH), len(GMOOH[0]) + +directions = [ + Cell(1, -1), Cell(1, 0), Cell(1, 1), + Cell(0, -1), Cell(0, 1), + Cell(-1, -1), Cell(-1, 0), Cell(-1, 1) +] +routes: List[List[CellWithCost]] = [] + +#### Helper functions #### + +def digit(ch: str) -> int: + return int(ch) if ch.isdigit() else -1 + +#### End of helper functions #### + +def searchFromCell(startRow: int, startCol: int): + global routes + + routes = [[ZERO for _ in range(WIDTH)] for _ in range(HEIGHT)] + routes[startRow][startCol] = CellWithCost(startRow, startCol, 0) + + queue = deque() + row, col, cost = startRow, startCol, 0 + + while True: + step = digit(GMOOH[row][col]) + for d in directions: + nr = row + step * d.row + nc = col + step * d.col + + if 0 <= nr < HEIGHT and 0 <= nc < WIDTH and digit(GMOOH[nr][nc]) >= 0: + current = routes[nr][nc] + if current == ZERO or current.cost > cost + 1: + routes[nr][nc] = CellWithCost(row, col, cost+1) + if digit(GMOOH[nr][nc]) > 0: + queue.append(CellWithCost(nr, nc, cost+1)) + if not queue: + break + + nextCell = queue.popleft() + row, col, cost = nextCell.fromRow, nextCell.fromCol, nextCell.cost + +def createRouteToCell(endRow: int, endCol: int) -> List[Cell]: + route: deque[Cell] = deque() + route.append(Cell(endRow, endCol)) + + while True: + cw = routes[endRow][endCol] + if cw.cost == 0: + break + endRow, endCol = cw.fromRow, cw.fromCol + route.appendleft(Cell(endRow, endCol)) + + return list(route) + +def showShortestRoutes(): + minCost = float("inf") + bestCells: List[Cell] = [] + + for r in range(HEIGHT): + for c in range(WIDTH): + if digit(GMOOH[r][c]) == 0: + cw = routes[r][c] + if cw != ZERO: + if cw.cost < minCost: + minCost = cw.cost + bestCells.clear() + if cw.cost == minCost: + bestCells.append(Cell(r, c)) + + plural = "s" if len(bestCells) != 1 else "" + isAre = "are" if len(bestCells) != 1 else "is" + + print(f"There {isAre} {len(bestCells)} shortest route{plural} of {minCost} days to safety:") + for cell in bestCells: + print(createRouteToCell(cell.row, cell.col)) + +def showUnreachableCells(): + unreachable: List[Cell] = [] + for r in range(HEIGHT): + for c in range(WIDTH): + if digit(GMOOH[r][c]) == 0 and routes[r][c] == ZERO: + unreachable.append(Cell(r, c)) + + print("The following cells are unreachable:") + print(unreachable) + +def showCellsWithLongestRoute(): + maxCost = -1 + worstCells: List[Cell] = [] + + for r in range(HEIGHT): + for c in range(WIDTH): + if digit(GMOOH[r][c]) >= 0: + cw = routes[r][c] + if cw != ZERO: + if cw.cost > maxCost: + maxCost = cw.cost + worstCells.clear() + if cw.cost == maxCost: + worstCells.append(Cell(r, c)) + + plural = "s" if len(worstCells) != 1 else "" + isAre = "are" if len(worstCells) != 1 else "is" + + print(f"There {isAre} {len(worstCells)} cell{plural} that require {maxCost} days to receive reinforcements from HQ:") + for cell in worstCells: + print(createRouteToCell(cell.row, cell.col)) + +if __name__ == "__main__": + searchFromCell(11, 11) + showShortestRoutes() + print() + + searchFromCell(21, 11) + print("The shortest route from (21, 11) to (1, 11):") + print(createRouteToCell(1, 11)) + print() + + searchFromCell(1, 11) + print("The shortest route from (1, 11) to (21, 11):") + print(createRouteToCell(21, 11)) + print() + + searchFromCell(11, 11) + showUnreachableCells() + print() + + showCellsWithLongestRoute() diff --git a/Task/Image-noise/EasyLang/image-noise.easy b/Task/Image-noise/EasyLang/image-noise.easy index 002181b964..0c5e24aab9 100644 --- a/Task/Image-noise/EasyLang/image-noise.easy +++ b/Task/Image-noise/EasyLang/image-noise.easy @@ -1,24 +1,19 @@ -proc pset x y c . . - color c - move x / 3.2 y / 3.2 - rect 0.3 0.3 +proc pset x y c . + gcolor c + grect x / 3.2 y / 3.2 0.3 0.3 . on animate fr += 1 if systime - t0 >= 1 - move 10 78 - color -2 - rect 80 20 - color -1 - move 10 80 - text fr / (systime - t0) & " fps" + gcolor -2 + grect 10 78 80 20 + gcolor -1 + gtext 10 80 fr / (systime - t0) & " fps" t0 = systime fr = 0 . col[] = [ 000 999 ] - for x = 0 to 319 - for y = 0 to 199 - pset x y col[random 2] - . + for x = 0 to 319 : for y = 0 to 199 + pset x y col[random 2] . . diff --git a/Task/Include-a-file/Bracmat/include-a-file.bracmat b/Task/Include-a-file/Bracmat/include-a-file.bracmat index e2454aa96a..abe7c136ab 100644 --- a/Task/Include-a-file/Bracmat/include-a-file.bracmat +++ b/Task/Include-a-file/Bracmat/include-a-file.bracmat @@ -1 +1 @@ -get$"module" +get$"filename" diff --git a/Task/Increasing-gaps-between-consecutive-Niven-numbers/EasyLang/increasing-gaps-between-consecutive-niven-numbers.easy b/Task/Increasing-gaps-between-consecutive-Niven-numbers/EasyLang/increasing-gaps-between-consecutive-niven-numbers.easy index 3383503a31..20c527d2c5 100644 --- a/Task/Increasing-gaps-between-consecutive-Niven-numbers/EasyLang/increasing-gaps-between-consecutive-niven-numbers.easy +++ b/Task/Increasing-gaps-between-consecutive-Niven-numbers/EasyLang/increasing-gaps-between-consecutive-niven-numbers.easy @@ -12,7 +12,7 @@ func divisible n d . . return if n mod d = 0 . -numfmt 0 8 +numfmt 8 0 previous = 1 print " Gap index Gap Niven index Niven number" print " --------- --- ----------- ------------" diff --git a/Task/Increment-a-numerical-string/Crystal/increment-a-numerical-string.cr b/Task/Increment-a-numerical-string/Crystal/increment-a-numerical-string.cr new file mode 100644 index 0000000000..f04b621930 --- /dev/null +++ b/Task/Increment-a-numerical-string/Crystal/increment-a-numerical-string.cr @@ -0,0 +1,5 @@ +"-123".succ # => "-124" + +require "big" + +"-123".to_big_i.succ.to_s # => "-122" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-1.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-1.tcl new file mode 100644 index 0000000000..4d393681e7 --- /dev/null +++ b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-1.tcl @@ -0,0 +1,10 @@ +# n is string +set n "1234" + +# integer rep added to n +# o is calculated integer +set o [expr $n + 1] + +# n is string, +# o used as string adds string representation to o +puts stdout "$n incrememented is $o" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-2.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-2.tcl new file mode 100644 index 0000000000..b8aca0da50 --- /dev/null +++ b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-2.tcl @@ -0,0 +1,6 @@ +# n has integer representation incremented +# n string rep updates when value changes +incr n 5 + +# n string rep used +puts stdout "n is now $n" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-3.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-3.tcl new file mode 100644 index 0000000000..55917fbae9 --- /dev/null +++ b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-3.tcl @@ -0,0 +1,5 @@ +# string +set j "4.3e11" + +# prints j as string +puts stdout "j: $j" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-4.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-4.tcl new file mode 100644 index 0000000000..61971b9a45 --- /dev/null +++ b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-4.tcl @@ -0,0 +1,4 @@ +# double fp temp calculated +# converts to string +# j not updated +puts stdout "j: [expr $j]" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-5.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-5.tcl new file mode 100644 index 0000000000..e5842d0384 --- /dev/null +++ b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-5.tcl @@ -0,0 +1,2 @@ +# j is still string "4.2e11" +puts stdout "j: $j" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-6.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-6.tcl new file mode 100644 index 0000000000..15f691bbb9 --- /dev/null +++ b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string-6.tcl @@ -0,0 +1 @@ +puts stdout "$j * $n = [expr $j * $n]" diff --git a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string.tcl b/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string.tcl deleted file mode 100644 index d09f03800e..0000000000 --- a/Task/Increment-a-numerical-string/Tcl/increment-a-numerical-string.tcl +++ /dev/null @@ -1,2 +0,0 @@ -set str 1234 -incr str diff --git a/Task/Index-finite-lists-of-positive-integers/C-sharp/index-finite-lists-of-positive-integers.cs b/Task/Index-finite-lists-of-positive-integers/C-sharp/index-finite-lists-of-positive-integers.cs new file mode 100644 index 0000000000..68e2d6b4c1 --- /dev/null +++ b/Task/Index-finite-lists-of-positive-integers/C-sharp/index-finite-lists-of-positive-integers.cs @@ -0,0 +1,107 @@ +using System.Numerics; + +for (var i = 0; i < 5; i++) +{ + var length = Random.Shared.Next(3, 6); + List list = []; + + for (var j = 0; j < length; j++) + { + list.Add(Random.Shared.Next(1_000_000)); + } + + var r = Rank(list); + Console.WriteLine($"rank({string.Join(", ", list)}) = {r}"); + Console.WriteLine($"unrank({r}) = {string.Join(", ", Unrank(r))}"); + list.Add(length); + Console.WriteLine($" Count of bits in list = {list.Sum(m => Math.Log2((double)m)):0.0}"); + Console.WriteLine($" Count of bits in rank = {Math.Log2((double)r):0.0}"); +} + +for (var n = 0; n <= 10; n++) +{ + var list = Unrank(n, 3); + var m = Rank(list, 3); + Console.WriteLine($"{n}: [{string.Join(", ", list)}] : {m}"); +} + +const int DefaultBias = 10; + +static BigInteger Rank(List list, int bias = DefaultBias) +{ + list.ForEach(m => ArgumentOutOfRangeException.ThrowIfNegativeOrZero(m, nameof(list))); + if (list.Count == 0) return 0; + BigInteger n = 0; + List digits = []; + var first = true; + + foreach (var m in list) + { + if (!first) digits.Add(bias - 1); + first = false; + digits.AddRange(ToBijectiveBase(m - 1, bias - 1)); + } + + return 1 + FromBijectiveBase(digits, bias); +} + +static List Unrank(BigInteger n, int bias = DefaultBias) +{ + if (n-- == 0) return []; + var list = ToBijectiveBase(n, bias); + var i = 0; + List result = []; + List digits = []; + BigInteger m; + + while (i < list.Count) + { + while (i < list.Count && list[i] != bias - 1) + { + digits.Add(list[i]); + i++; + } + + if (i < list.Count) + { + m = FromBijectiveBase(digits, bias - 1); + result.Add(m + 1); + digits.Clear(); + i++; + } + } + + m = FromBijectiveBase(digits, bias - 1); + result.Add(m + 1); + return result; +} + +static BigInteger FromBijectiveBase(IEnumerable digits, int @base) +{ + BigInteger n = 0; + + foreach (var i in digits) + { + var a = i + 1; + if (a == @base) { a = 0; n++; } + n = n * @base + a; + } + + return n; +} + +static List ToBijectiveBase(BigInteger n, int @base) +{ + List list = []; + + while (n > 0) + { + var q = (n + (@base - 1)) / @base - 1; + var a = n - q * @base; + list.Add((int)a - 1); + n = q; + } + + list.Reverse(); + return list; +} diff --git a/Task/Input-loop/JavaScript/input-loop.js b/Task/Input-loop/JavaScript/input-loop-1.js similarity index 100% rename from Task/Input-loop/JavaScript/input-loop.js rename to Task/Input-loop/JavaScript/input-loop-1.js diff --git a/Task/Input-loop/JavaScript/input-loop-2.js b/Task/Input-loop/JavaScript/input-loop-2.js new file mode 100644 index 0000000000..a33323829c --- /dev/null +++ b/Task/Input-loop/JavaScript/input-loop-2.js @@ -0,0 +1,21 @@ +const readline = require("readline"); + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +function askQuestion(query) { + return new Promise(resolve => rl.question(query, resolve)); +} + +async function main() { + while (true) { + const input = await askQuestion("Type something: "); + // do whatever you want with the input string + // remember to break the loop if you need + } + rl.close(); +} + +main(); diff --git a/Task/Integer-sequence/Uxntal/integer-sequence.uxnatl b/Task/Integer-sequence/Uxntal/integer-sequence.uxnatl new file mode 100644 index 0000000000..fdc8e1419c --- /dev/null +++ b/Task/Integer-sequence/Uxntal/integer-sequence.uxnatl @@ -0,0 +1,23 @@ +%comma { [ LIT2 ", -Console/write ] DEO } +%space { [ LIT2 20 -Console/write ] DEO } + +|18 @Console/write + +|100 + +#0001 +&loop + DUP2 print/dec comma space + INC2 !&loop + +BRK + +@print/dec ( short* -- ) + #000a SWP2 [ LITr ff ] + &get + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?&get + POP2 POP2 + &put + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !&put diff --git a/Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr b/Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr new file mode 100644 index 0000000000..17ba1deb2d --- /dev/null +++ b/Task/Interactive-programming-repl-/Crystal/interactive-programming-repl-.cr @@ -0,0 +1,11 @@ +> crystal i +Crystal interpreter 1.15.1 [89944bf] (2025-02-04). +EXPERIMENTAL SOFTWARE: if you find a bug, please consider opening an issue in +https://github.com/crystal-lang/crystal/issues/new/ +icr:1> def f(s1, s2, sep) +icr:2> s1 + sep + sep + s2 +icr:3> end + => nil +icr:4> f "Rosetta", "Code", ":" + => "Rosetta::Code" +icr:5> diff --git a/Task/Inverted-syntax/Ruby/inverted-syntax.rb b/Task/Inverted-syntax/Ruby/inverted-syntax-1.rb similarity index 100% rename from Task/Inverted-syntax/Ruby/inverted-syntax.rb rename to Task/Inverted-syntax/Ruby/inverted-syntax-1.rb diff --git a/Task/Inverted-syntax/Ruby/inverted-syntax-2.rb b/Task/Inverted-syntax/Ruby/inverted-syntax-2.rb new file mode 100644 index 0000000000..5c8a4175de --- /dev/null +++ b/Task/Inverted-syntax/Ruby/inverted-syntax-2.rb @@ -0,0 +1,4 @@ +7 => a +:x in b + +p [a, b] # => [7, :x] diff --git a/Task/Isograms-and-heterograms/EasyLang/isograms-and-heterograms.easy b/Task/Isograms-and-heterograms/EasyLang/isograms-and-heterograms.easy index a4353fbc53..44a4a304a1 100644 --- a/Task/Isograms-and-heterograms/EasyLang/isograms-and-heterograms.easy +++ b/Task/Isograms-and-heterograms/EasyLang/isograms-and-heterograms.easy @@ -1,9 +1,7 @@ repeat s$ = input until s$ = "" - if len s$ > 1 - w$[] &= s$ - . + if len s$ > 1 : w$[] &= s$ . func[] letters w$ . len r[] 127 @@ -14,18 +12,14 @@ func[] letters w$ . return r[] . func cmp a b a$ b$ . - if a > b - return 1 - elif a = b - if len a$ > len b$ - return 1 - elif len a$ = len b$ and strcmp a$ b$ < 0 - return 1 - . + if a > b : return 1 + if a = b + if len a$ > len b$ : return 1 + if len a$ = len b$ and strcmp a$ b$ < 0 : return 1 . return 0 . -proc sort . d$[] d[] . +proc sort &d$[] &d[] . n = len d$[] for i = 1 to n - 1 for j = i + 1 to n @@ -36,14 +30,12 @@ proc sort . d$[] d[] . . . . -proc isograms . . +proc isograms . for w$ in w$[] cnt[] = letters w$ n = 0 for i to 127 - if cnt[i] = 1 - break 1 - . + if cnt[i] = 1 : break 1 if cnt[i] > 0 if n = 0 n = cnt[i] @@ -58,18 +50,14 @@ proc isograms . . . . sort r$[] n[] - for w$ in r$[] - print w$ - . + for w$ in r$[] : print w$ . -proc heterogram lng . . +proc heterogram lng . for w$ in w$[] if len w$ > lng cnt[] = letters w$ for i to 127 - if cnt[i] > 0 and cnt[i] <> 1 - break 1 - . + if cnt[i] > 0 and cnt[i] <> 1 : break 1 . if i > 127 r$[] &= w$ @@ -78,9 +66,7 @@ proc heterogram lng . . . . sort r$[] n[] - for w$ in r$[] - print w$ - . + for w$ in r$[] : print w$ . isograms print "" diff --git a/Task/Isqrt-integer-square-root-of-X/JavaScript/isqrt-integer-square-root-of-x.js b/Task/Isqrt-integer-square-root-of-X/JavaScript/isqrt-integer-square-root-of-x.js new file mode 100644 index 0000000000..c7e8fd19d3 --- /dev/null +++ b/Task/Isqrt-integer-square-root-of-X/JavaScript/isqrt-integer-square-root-of-x.js @@ -0,0 +1,36 @@ +function isqrt(x) { + let q = 1n; + while (q <= x) { + q *= 4n; + } + + let z = x; + let r = 0n; + + while (q > 1) { + q /= 4n; + let t = z - r - q; + r /= 2n; + + if (t >= 0) { + z = t; + r += q; + } + } + return r; +} + +const items = []; +for (let n = 0; n < 66; n++) { + items.push(isqrt(BigInt(n))); +} + +console.log(items.join(" ")); + +const items2 = []; + +for (let n = 1n; n < 204n; n+= 2n) { + items2.push(`${Intl.NumberFormat().format(isqrt(7n ** n))} = isqrt(7^${n})`); +} + +console.log(items2.join('\n')); diff --git a/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx b/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx index b311025c50..29fcc4a72c 100644 --- a/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx +++ b/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx @@ -1,46 +1,125 @@ -/*REXX program computes and displays the Isqrt (integer square root) of some integers.*/ -numeric digits 200 /*insure 'nuff decimal digs for results*/ -parse arg range power base . /*obtain optional arguments from the CL*/ -if range=='' | range=="," then range= 0..65 /*Not specified? Then use the default.*/ -if power=='' | power=="," then power= 1..73 /* " " " " " " */ -if base =='' | base =="," then base = 7 /* " " " " " " */ -parse var range rLO '..' rHI; if rHI=='' then rHI= rLO /*handle a range? */ -parse var power pLO '..' pHI; if pHI=='' then pHI= pLO /* " " " */ -$= - do j=rLO to rHI while rHI>0 /*compute Isqrt for a range of integers*/ - $= $ commas( Isqrt(j) ) /*append the Isqrt to a list for output*/ - end /*j*/ -$= strip($) /*elide the leading blank in the list. */ -say center(' Isqrt for numbers: ' rLO " ──► " rHI' ', length($), "─") -say strip($) /*$ has a leading blank for 1st number*/ -say -z= base ** pHI /*compute max. exponentiation product.*/ -Lp= max(30, length( commas( z) ) ) /*length of " " " */ -Lr= max(20, length( commas( Isqrt(z) ) ) ) /* " " " " " Isqrt of above.*/ -say 'index' center(base"**index", Lp) center('Isqrt', Lr) /*show a title.*/ -say '─────' copies("─", Lp) copies('─', Lr) /* " " header*/ +-- 8 May 2025 +Main: +include Settings - do j=pLO to pHI by 2 while pHI>0; x= base ** j - say center(j, 5) right( commas(x), Lp) right( commas( Isqrt(x) ), Lr) - end /*j*/ /* [↑] show a bunch of powers & Isqrt.*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Isqrt: procedure; parse arg x /*obtain the only passed argument X. */ - x= x % 1 /*convert possible real X to an integer*/ /* ◄■■■■■■■ optional. */ - q= 1 /*initialize the Q variable to unity.*/ - do until q>x /*find a Q that is greater than X. */ - q= q * 4 /*multiply Q by four. */ - end /*until*/ - r= 0 /*R: will be the integer sqrt of X. */ - do while q>1 /*keep processing while Q is > than 1*/ - q= q % 4 /*divide Q by four (no remainder). */ - t= x - r - q /*compute a temporary variable. */ - r= r % 2 /*divide R by two (no remainder). */ - if t >= 0 then do /*if T is non─negative ... */ - x= t /*recompute the value of X */ - r= r + q /* " " " " R */ - end - end /*while*/ - return r /*return the integer square root of X. */ +say 'ISQRT (INTEGER SQUARE ROOT)' +say version +say +call Task1 65 +call Task2 1,2,73,'Q' +call Task2 123,1,123,'Q' +call Task2 123,1,123,'I' +call Task2 123,1,123,'F' +call Task2 1234,1,1234,'Q' +call Task2 1234,1,1234,'I' +call Task2 1234,1,1234,'F' +call Task2 12345,1,12345,'Q' +call Task2 12345,1,12345,'I' +call Task2 12345,1,12345,'F' +exit + +Task1: +procedure +arg xx +call time('r') +say 'Integer square root for n = 0...'xx +do n = 0 to xx + call Charout ,QuadraticResidue(n)' ' +end +say +call Timer +return + +Task2: +procedure +arg xx,yy,zz,mm +call Time('r') +select + when mm = 'Q' then + t = 'Quadratic residue' + when mm = 'I' then + t = 'Integer division' + when mm = 'F' then + t = 'Floating square root' +end +say Right('n',5) Left('7^n',40) Left('Isqrt(7^n) using' t,60) +numeric digits zz +do n = xx by yy to zz + p = 7**n+0 + pl = Length(p) + select + when mm = 'Q' then + r = QuadraticResidue(p) + when mm = 'I' then + r = WikiPedia(p) + when mm = 'F' then + r = Std(Floor(Sqrt(p))/1) + end + rl = Length(r) + if pl > 20 then + p = Left(p,10)'...'Right(p,10) '['pl 'digits]' + else + p = p '['pl 'digits]' + if rl > 20 then + r = Left(r,10)'...'Right(r,10) '['rl 'digits]' + else + r = r '['rl 'digits]' + say Right(n,5) Left(p,40) Left(r,40) +end +call Timer +return + +QuadraticResidue: +procedure +arg xx +-- First power of 4 > x +q = 1 +do until q > xx + q = q*4 +end +-- Iterate back to 1 using integer division +zz = 0 +do while q > 1 + q = q%4; t = xx-zz-q; zz = zz%2 + if t >= 0 then do + xx = t; zz = zz+q + end +end +return zz + +WikiPedia: +procedure +arg xx +-- Reduce argument to 1...100 +e = Xpon(xx)%2; a = -2*e; a = xx'E'a +-- First guess and undo reduce +select + when a < 4 then + zz = 2'E'e + when a < 9 then + zz = 3'E'e + when a < 16 then + zz = 4'E'e + when a < 25 then + zz = 5'E'e + when a < 36 then + zz = 6'E'e + when a < 49 then + zz = 7'E'e + when a < 64 then + zz = 8'E'e + when a < 81 then + zz = 9'E'e + otherwise + zz = 10'E'e +end +-- Loop by integer division +z = (zz+xx%zz)%2 +do while z < zz + zz = z; z = (zz+xx%zz)%2 +end +return zz + +include Functions +include Helper +include Abend diff --git a/Task/Jacobi-symbol/EasyLang/jacobi-symbol.easy b/Task/Jacobi-symbol/EasyLang/jacobi-symbol.easy index cbfd3707d9..2e96c70109 100644 --- a/Task/Jacobi-symbol/EasyLang/jacobi-symbol.easy +++ b/Task/Jacobi-symbol/EasyLang/jacobi-symbol.easy @@ -5,28 +5,20 @@ func jacobi a n . while a mod 2 = 0 a /= 2 nn = n mod 8 - if nn = 3 or nn = 5 - res = -res - . + if nn = 3 or nn = 5 : res = -res . swap a n - if a mod 4 = 3 and n mod 4 = 3 - res = -res - . + if a mod 4 = 3 and n mod 4 = 3 : res = -res a = a mod n . - if n = 1 - return res - . + if n = 1 : return res return 0 . print " n/a 0 1 2 3 4 5 6 7 8 9" print " ---------------------------------" -numfmt 2 3 +numfmt 3 2 for n = 1 step 2 to 17 write n & " " - for a = 0 to 9 - write jacobi a n - . + for a = 0 to 9 : write jacobi a n print "" . diff --git a/Task/Jacobi-symbol/JavaScript/jacobi-symbol.js b/Task/Jacobi-symbol/JavaScript/jacobi-symbol.js new file mode 100644 index 0000000000..ad566e6dbe --- /dev/null +++ b/Task/Jacobi-symbol/JavaScript/jacobi-symbol.js @@ -0,0 +1,52 @@ +function jacobi(n, k) { + if (k <= 0 || k % 2 !== 1) { + throw new Error("k must be positive and odd"); + } + n %= k; + let t = 1; + while (n !== 0) { + while (n % 2 === 0) { + n /= 2; + const r = k % 8; + if (r === 3 || r === 5) { + t = -t; + } + } + [n, k] = [k, n]; // Swap n and k + if (n % 4 === 3 && k % 4 === 3) { + t = -t; + } + n %= k; + } + return k === 1 ? t : 0; +} + +function print_table(out, kmax, nmax) { + let header = "n\\k|"; + for (let k = 0; k <= kmax; ++k) { + header += " " + k.toString().padStart(2, ' '); + } + out.push(header); + + let separator = "----"; + for (let k = 0; k <= kmax; ++k) { + separator += "---"; + } + out.push(separator); + + for (let n = 1; n <= nmax; n += 2) { + let row = n.toString().padStart(2, ' ') + " |"; + for (let k = 0; k <= kmax; ++k) { + row += " " + jacobi(k, n).toString().padStart(2, ' '); + } + out.push(row); + } +} + +function main() { + const output = []; + print_table(output, 20, 21); + output.forEach(line => console.log(line)); +} + +main(); diff --git a/Task/Jaro-Winkler-distance/EasyLang/jaro-winkler-distance.easy b/Task/Jaro-Winkler-distance/EasyLang/jaro-winkler-distance.easy index 5337f2435e..a00f8e8e35 100644 --- a/Task/Jaro-Winkler-distance/EasyLang/jaro-winkler-distance.easy +++ b/Task/Jaro-Winkler-distance/EasyLang/jaro-winkler-distance.easy @@ -4,16 +4,12 @@ repeat words$[] &= s$ . func distance s1$ s2$ . - if len s1$ < len s2$ - swap s1$ s2$ - . + if len s1$ < len s2$ : swap s1$ s2$ s1$[] = strchars s1$ s2$[] = strchars s2$ len1 = len s1$[] len2 = len s2$[] - if len2 = 0 - return 0 - . + if len2 = 0 : return 0 delta = higher 0 (len1 div 2 - 1) len flag[] len2 for i to len1 @@ -27,11 +23,9 @@ func distance s1$ s2$ . . . . - m = len c1_match$[] - if m = 0 - return 1 - . i = 0 + m = len c1_match$[] + if m = 0 : return 1 for j to len2 if flag[j] = 1 i += 1 @@ -44,17 +38,15 @@ func distance s1$ s2$ . . return 1 - (jaro + comprefix * 0.1 * (1 - jaro)) . -proc sort . d[] d$[] . - for i = len d[] - 1 downto 1 - for j = 1 to i - if d[j] > d[j + 1] - swap d[j] d[j + 1] - swap d$[j] d$[j + 1] - . +proc sort &d[] &d$[] . + for i = len d[] - 1 downto 1 : for j = 1 to i + if d[j] > d[j + 1] + swap d[j] d[j + 1] + swap d$[j] d$[j + 1] . . . -proc closewords s$ maxdist . r$[] r[] . +proc closewords s$ maxdist &r$[] &r[] . r[] = [ ] r$[] = [ ] for w$ in words$[] @@ -69,9 +61,7 @@ proc closewords s$ maxdist . r$[] r[] . for s$ in [ "accomodate" "definately" "goverment" "occured" "publically" "recieve" "seperate" "untill" "wich" ] print s$ & " ->" closewords s$ 0.15 r$[] r[] - for i to lower 5 len r$[] - print r[i] & " " & r$[i] - . + for i to lower 5 len r$[] : print r[i] & " " & r$[i] print "" . # the content of unixdict.txt diff --git a/Task/Jensens-Device/M2000-Interpreter/jensens-device-1.m2000 b/Task/Jensens-Device/M2000-Interpreter/jensens-device-1.m2000 index 69bec218bc..607df6e793 100644 --- a/Task/Jensens-Device/M2000-Interpreter/jensens-device-1.m2000 +++ b/Task/Jensens-Device/M2000-Interpreter/jensens-device-1.m2000 @@ -1,8 +1,8 @@ Module Jensen`s_Device { - Def double i + double i=0 Report Lazy$(1/i) ' display the definition of the lazy function Function Sum (&i, lo, hi, &f()) { - def double temp + double temp=0 For i= lo to hi { temp+=f() } diff --git a/Task/Jensens-Device/M2000-Interpreter/jensens-device-2.m2000 b/Task/Jensens-Device/M2000-Interpreter/jensens-device-2.m2000 index c64df3b2cc..d803e70e80 100644 --- a/Task/Jensens-Device/M2000-Interpreter/jensens-device-2.m2000 +++ b/Task/Jensens-Device/M2000-Interpreter/jensens-device-2.m2000 @@ -1,7 +1,7 @@ Module Jensen`s_Device { - Def decimal i + decimal i=0 Function Sum (&any, lo, hi, &f()) { - def decimal temp + decimal temp=0 For any= lo to hi { temp+=f() } diff --git a/Task/Jensens-Device/M2000-Interpreter/jensens-device-3.m2000 b/Task/Jensens-Device/M2000-Interpreter/jensens-device-3.m2000 index a38409fe64..50758b2707 100644 --- a/Task/Jensens-Device/M2000-Interpreter/jensens-device-3.m2000 +++ b/Task/Jensens-Device/M2000-Interpreter/jensens-device-3.m2000 @@ -1,7 +1,7 @@ Module Jensen`s_Device { - Def single i + single i=0 Function Sum (&any, lo, hi, &f()) { - def single temp + single temp=0 For any= lo to hi { temp+=f() } diff --git a/Task/Jordan-P-lya-numbers/EasyLang/jordan-p-lya-numbers.easy b/Task/Jordan-P-lya-numbers/EasyLang/jordan-p-lya-numbers.easy index 11890bc255..6e9f6533b1 100644 --- a/Task/Jordan-P-lya-numbers/EasyLang/jordan-p-lya-numbers.easy +++ b/Task/Jordan-P-lya-numbers/EasyLang/jordan-p-lya-numbers.easy @@ -11,9 +11,7 @@ fastfunc jpnum m . repeat q = n div fac if n mod fac = 0 - if q = 1 - return 1 - . + if q = 1 : return 1 n = q else fac = fac / i @@ -22,13 +20,11 @@ fastfunc jpnum m . until i = 1 . limite -= 1 - if limite = 0 - return 0 - . + if limite = 0 : return 0 n = m . . -numfmt 0 5 +numfmt 5 0 write 1 c = 1 n = 2 @@ -37,9 +33,7 @@ repeat c += 1 if c <= 50 write n - if c mod 8 = 0 - print "" - . + if c mod 8 = 0 : print "" . sn = n . diff --git a/Task/JortSort/EasyLang/jortsort.easy b/Task/JortSort/EasyLang/jortsort.easy index eff2004f35..931ef807e7 100644 --- a/Task/JortSort/EasyLang/jortsort.easy +++ b/Task/JortSort/EasyLang/jortsort.easy @@ -1,10 +1,6 @@ -proc sort . d[] . - for i = 1 to len d[] - 1 - for j = i + 1 to len d[] - if d[j] < d[i] - swap d[j] d[i] - . - . +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] . . func jortsort arr[] . diff --git a/Task/Juggler-sequence/FreeBASIC/juggler-sequence.basic b/Task/Juggler-sequence/FreeBASIC/juggler-sequence.basic new file mode 100644 index 0000000000..7105fa171b --- /dev/null +++ b/Task/Juggler-sequence/FreeBASIC/juggler-sequence.basic @@ -0,0 +1,87 @@ +#include "big_int/big_integer.bi" + +Type JugglerResult + length As Integer ' Sequence length + maxVal As BigInt ' Maximum value + maxIdx As Integer ' Index where maximum occurs +End Type + +Function BigIntSqrt(Byref n As BigInt) As BigInt + If n = 0 Then Return 0 + + Dim As BigInt x = n + Dim As BigInt y = (x + 1) \ 2 + While y < x + x = y + y = (x + n \ x) \ 2 + Wend + + Return x +End Function + +Function BigIntToStr(Byref n As BigInt) As String + If n = 0 Then Return "0" + + Dim As String result + Dim As BigInt tmp = n + Dim As BigInt ten = 10 + Dim As BigInt digit + + While tmp <> 0 + digit = tmp Mod 10 + result = Chr(Cint(digit) + Asc("0")) & result + tmp \= 10 + Wend + + Return result +End Function + +Function Juggler(n As Uinteger) As JugglerResult + Dim As JugglerResult result + Dim As BigInt a = n + + result.length = 0 + result.maxVal = a + result.maxIdx = 0 + + While a <> 1 + If (a Mod 2) = 0 Then + ' Even: floor(sqrt(a)) + a = BigIntSqrt(a) + Else + ' Odd: floor(a^(3/2)) = floor(sqrt(a³)) + Dim As BigInt a_cubed = a * a * a + a = BigIntSqrt(a_cubed) + End If + + result.length += 1 + + If a > result.maxVal Then + result.maxVal = a + result.maxIdx = result.length + End If + Wend + + Return result +End Function + +' Main program +Print "n l[n] h[n] i[n]" +Print String(31, "-") + +For n As Integer = 20 To 39 + Dim As JugglerResult result = Juggler(n) + Dim As String maxValStr = BigIntToStr(result.maxVal) + + Print Using "## ## "; n; result.length; + + If Len(maxValStr) < 14 Then + Print Space(14 - Len(maxValStr)); maxValStr; + Else + Print maxValStr; + End If + + Print Using " ##"; result.maxIdx +Next + +Sleep diff --git a/Task/Julia-set/EasyLang/julia-set.easy b/Task/Julia-set/EasyLang/julia-set.easy index 9a1fe358c3..44a8af429b 100644 --- a/Task/Julia-set/EasyLang/julia-set.easy +++ b/Task/Julia-set/EasyLang/julia-set.easy @@ -1,20 +1,17 @@ cx = -0.7 cy = 0.27015 -for y = 0 to 299 - for x = 0 to 299 - zx = (x - 150) / 100 - zy = (y - 150) / 150 - color3 0 0 0 - for iter = 0 to 127 - if zx * zx + zy * zy > 4 - color3 iter / 16 0 0 - break 1 - . - h = zx * zx - zy * zy + cx - zy = 2 * zx * zy + cy - zx = h +for y = 0 to 299 : for x = 0 to 299 + zx = (x - 150) / 100 + zy = (y - 150) / 150 + gcolor3 0 0 0 + for iter = 0 to 127 + if zx * zx + zy * zy > 4 + gcolor3 iter / 16 0 0 + break 1 . - move x / 3 y / 3 - rect 0.4 0.4 + h = zx * zx - zy * zy + cx + zy = 2 * zx * zy + cy + zx = h . + grect x / 3 y / 3 0.4 0.4 . diff --git a/Task/K-d-tree/C-sharp/k-d-tree.cs b/Task/K-d-tree/C-sharp/k-d-tree.cs new file mode 100644 index 0000000000..a757b7689c --- /dev/null +++ b/Task/K-d-tree/C-sharp/k-d-tree.cs @@ -0,0 +1,472 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; // For StringBuilder in Point.ToString + +//----------------------------------------------------------------------------- +// Point Struct +//----------------------------------------------------------------------------- + +/// +/// Represents a point in N-dimensional space. +/// TCoord must be a numeric type supporting comparison and conversion. +/// +/// The numeric type for coordinates (e.g., int, double, float). +public readonly struct Point : IEquatable> + where TCoord : struct, IComparable, IConvertible // Constraints for numeric operations & sorting +{ + private readonly TCoord[] _coords; + public int Dimensions { get; } + + /// + /// Initializes a new point with the specified coordinates. + /// The number of coordinates determines the dimension. + /// + /// The coordinates for the point. + /// Thrown if coords is null. + /// Thrown if coords is empty. + public Point(params TCoord[] coords) + { + if (coords == null) + throw new ArgumentNullException(nameof(coords)); + if (coords.Length == 0) + throw new ArgumentException("Coordinates cannot be empty.", nameof(coords)); + + _coords = (TCoord[])coords.Clone(); // Defensive copy + Dimensions = _coords.Length; + } + + /// + /// Initializes a new point by copying coordinates from an enumerable. + /// + /// The coordinates for the point. + /// Thrown if coords is null. + /// Thrown if coords results in an empty collection. + public Point(IEnumerable coords) + { + if (coords == null) + throw new ArgumentNullException(nameof(coords)); + + _coords = coords.ToArray(); + if (_coords.Length == 0) + throw new ArgumentException("Coordinates cannot be empty.", nameof(coords)); + + Dimensions = _coords.Length; + } + + + /// + /// Gets the coordinate value in the specified dimension. + /// + /// Dimension index (zero-based). + /// The coordinate value. + /// Thrown if index is out of bounds. + public TCoord Get(int index) + { + // Rely on array's built-in bounds checking for performance + // if (index < 0 || index >= Dimensions) + // throw new IndexOutOfRangeException($"Index {index} is out of range for dimension {Dimensions}."); + return _coords[index]; + } + + /// + /// Calculates the squared Euclidean distance between this point and another point. + /// + /// The other point. + /// The squared distance. + /// Thrown if points have different dimensions. + public double DistanceSquared(Point other) + { + if (Dimensions != other.Dimensions) + throw new ArgumentException("Points must have the same dimensions."); + + double distSq = 0; + for (int i = 0; i < Dimensions; ++i) + { + // Convert coordinates to double for calculation. + // This is a common approach when TCoord isn't guaranteed to be double. + // Using System.Numerics.INumber in .NET 7+ would allow direct arithmetic. + double d = Convert.ToDouble(Get(i)) - Convert.ToDouble(other.Get(i)); + distSq += d * d; + } + return distSq; + } + + /// + /// Returns a string representation of the point (e.g., "(1, 2, 3)"). + /// + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append('('); + for (int i = 0; i < Dimensions; ++i) + { + if (i > 0) + sb.Append(", "); + sb.Append(_coords[i]); + } + sb.Append(')'); + return sb.ToString(); + } + + // --- Equality Members --- + public bool Equals(Point other) + { + if (Dimensions != other.Dimensions) + return false; + // Using SequenceEqual for robust array comparison + return _coords.SequenceEqual(other._coords); + } + + public override bool Equals(object obj) + { + return obj is Point other && Equals(other); + } + + public override int GetHashCode() + { + int hashCode = Dimensions.GetHashCode(); + if (_coords != null) + { + foreach (var coord in _coords) + { + // Simple hash combining approach + hashCode = HashCode.Combine(hashCode, coord.GetHashCode()); + } + } + return hashCode; + } + + public static bool operator ==(Point left, Point right) + { + return left.Equals(right); + } + + public static bool operator !=(Point left, Point right) + { + return !(left == right); + } +} + + +//----------------------------------------------------------------------------- +// KdTree Class +//----------------------------------------------------------------------------- + +/// +/// C# k-d tree implementation for fast nearest neighbor searches. +/// +/// The numeric type for coordinates. +public class KdTree + where TCoord : struct, IComparable, IConvertible +{ + // Internal Node class + private class Node + { + public Point Point { get; } + public Node Left { get; set; } // Using properties with private setters if needed, or public fields + public Node Right { get; set; } + + public Node(Point point) + { + Point = point; + Left = null; + Right = null; + } + + // Helper to access coordinate for sorting/comparison + public TCoord Get(int index) => Point.Get(index); + + // Helper for distance calculation + public double DistanceSquared(Point pt) => Point.DistanceSquared(pt); + } + + // --- Fields --- + private readonly Node[] _nodes; // Store nodes contiguously for potential cache benefits + private readonly Node _root; + private readonly int _dimensions; + + // State for the nearest neighbor search + private Node _bestNode = null; + private double _bestDistSq = double.MaxValue; + private int _visitedCount = 0; + + + // --- Comparer for Sorting Nodes --- + private class NodeComparer : IComparer + { + private readonly int _dimensionIndex; + + public NodeComparer(int dimensionIndex) + { + _dimensionIndex = dimensionIndex; + } + + public int Compare(Node x, Node y) + { + // Comparison relies on the IComparable constraint + return x.Get(_dimensionIndex).CompareTo(y.Get(_dimensionIndex)); + } + } + + // --- Constructors --- + + /// + /// Builds a k-d tree from a collection of points. + /// + /// The points to add to the tree. + /// Thrown if points is null. + /// Thrown if points is empty or contains points with inconsistent dimensions. + public KdTree(IEnumerable> points) + { + if (points == null) throw new ArgumentNullException(nameof(points)); + + var pointList = points.ToList(); // Materialize the list + if (pointList.Count == 0) throw new ArgumentException("Point collection cannot be empty.", nameof(points)); + + _dimensions = pointList[0].Dimensions; + _nodes = new Node[pointList.Count]; + + for (int i = 0; i < pointList.Count; i++) + { + if (pointList[i].Dimensions != _dimensions) + throw new ArgumentException($"All points must have the same dimension ({_dimensions}). Point {i} has dimension {pointList[i].Dimensions}.", nameof(points)); + _nodes[i] = new Node(pointList[i]); + } + + _root = MakeTree(0, _nodes.Length, 0); + } + + /// + /// Builds a k-d tree by generating points using a function. + /// + /// A function that returns a Point. + /// The number of points to generate. + /// Thrown if pointGenerator is null. + /// Thrown if count is zero or negative. + /// Thrown if the generator produces points with inconsistent dimensions. + public KdTree(Func> pointGenerator, int count) + { + if (pointGenerator == null) throw new ArgumentNullException(nameof(pointGenerator)); + if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count), "Count must be positive."); + + _nodes = new Node[count]; + Point firstPoint = pointGenerator(); + _dimensions = firstPoint.Dimensions; + _nodes[0] = new Node(firstPoint); + + for (int i = 1; i < count; i++) + { + Point p = pointGenerator(); + if (p.Dimensions != _dimensions) + throw new InvalidOperationException($"Generated points must have consistent dimensions ({_dimensions}). Point {i} has dimension {p.Dimensions}."); + _nodes[i] = new Node(p); + } + + _root = MakeTree(0, _nodes.Length, 0); + } + + + // --- Tree Building Method --- + private Node MakeTree(int begin, int end, int index) + { + if (end <= begin) + return null; // Base case: empty range + + // Calculate median index + int n = begin + (end - begin) / 2; + + // Sort the segment [begin, end) based on the current dimension 'index' + // This partitions the array around the median element at index 'n' + // Array.Sort sorts the range [begin, begin + length), so length is end - begin + Array.Sort(_nodes, begin, end - begin, new NodeComparer(index)); + + // Median element becomes the current node + Node currentNode = _nodes[n]; + + // Cycle to the next dimension for children + int nextIndex = (index + 1) % _dimensions; + + // Recursively build left and right subtrees + currentNode.Left = MakeTree(begin, n, nextIndex); + currentNode.Right = MakeTree(n + 1, end, nextIndex); + + return currentNode; + } + + // --- Public API --- + + /// + /// Gets the number of dimensions for points in this tree. + /// + public int Dimensions => _dimensions; + + /// + /// Returns true if the tree is empty. + /// + public bool IsEmpty => _nodes.Length == 0; + + /// + /// Returns the number of nodes visited during the last call to Nearest. + /// + public int Visited => _visitedCount; + + /// + /// Returns the squared distance between the query point and the nearest point found by the last call to Nearest. + /// Returns double.PositiveInfinity if Nearest hasn't been called or the tree is empty. + /// + public double DistanceSquared => _bestNode != null ? _bestDistSq : double.PositiveInfinity; + + /// + /// Returns the Euclidean distance between the query point and the nearest point found by the last call to Nearest. + /// Returns double.PositiveInfinity if Nearest hasn't been called or the tree is empty. + /// + public double Distance => _bestNode != null ? Math.Sqrt(_bestDistSq) : double.PositiveInfinity; + + + /// + /// Finds the nearest point in the tree to the given point. + /// + /// The query point. + /// The nearest point found in the tree. + /// Thrown if the tree is empty. + /// Thrown if the query point has different dimensions than the tree. + public Point Nearest(Point point) + { + if (_root == null) + throw new InvalidOperationException("Cannot search an empty tree."); + if (point.Dimensions != _dimensions) + throw new ArgumentException($"Query point dimension ({point.Dimensions}) must match tree dimension ({_dimensions})."); + + // Reset search state + _bestNode = null; + _bestDistSq = double.MaxValue; // Use MaxValue for initial comparison + _visitedCount = 0; + + // Start recursive search + Nearest(_root, point, 0); + + // _bestNode should not be null if _root wasn't null + return _bestNode.Point; + } + + // --- Recursive Nearest Neighbor Search --- + private void Nearest(Node node, Point point, int index) + { + if (node == null) + return; + + _visitedCount++; + + double dSq = node.DistanceSquared(point); + + // If this node is better than the current best, update best + if (_bestNode == null || dSq < _bestDistSq) + { + _bestDistSq = dSq; + _bestNode = node; + } + + // Perfect match found, can stop (early exit) + if (_bestDistSq == 0) + return; + + // Determine difference along the splitting dimension + // Convert coordinates to double for the difference calculation + double dx = Convert.ToDouble(node.Get(index)) - Convert.ToDouble(point.Get(index)); + + // Cycle dimension + int nextIndex = (index + 1) % _dimensions; + + // Decide which subtree to visit first (the one containing the point) + Node nearerNode = dx > 0 ? node.Left : node.Right; + Node furtherNode = dx > 0 ? node.Right : node.Left; + + // Search the nearer subtree first + Nearest(nearerNode, point, nextIndex); + + // Pruning: Check if the hypersphere crosses the splitting plane. + // If dx^2 >= bestDistSq, the other subtree cannot contain a closer point. + if (dx * dx >= _bestDistSq) + { + return; // Prune the further subtree + } + + // Hypersphere crosses the plane, search the further subtree + Nearest(furtherNode, point, nextIndex); + } +} + + +//----------------------------------------------------------------------------- +// Example Usage & Testing +//----------------------------------------------------------------------------- +public class Program +{ + static void TestWikipedia() + { + Console.WriteLine("Wikipedia example data:"); + var points = new Point[] { + new Point(2, 3), new Point(5, 4), new Point(9, 6), + new Point(4, 7), new Point(8, 1), new Point(7, 2) + }; + + var tree = new KdTree(points); + + var queryPoint = new Point(9, 2); + Point nearest = tree.Nearest(queryPoint); + + Console.WriteLine($"Query point: {queryPoint}"); + Console.WriteLine($"Nearest point: {nearest}"); + Console.WriteLine($"Distance: {tree.Distance:F6}"); // Format distance + Console.WriteLine($"Nodes visited: {tree.Visited}"); + Console.WriteLine("------------------------------------"); + } + + // Simple random point generator for 3D doubles + private static Random _random = new Random(); + public static Point RandomPointGenerator(double min, double max) + { + double range = max - min; + double x = min + _random.NextDouble() * range; + double y = min + _random.NextDouble() * range; + double z = min + _random.NextDouble() * range; + return new Point(x, y, z); + } + + static void TestRandom(int count) + { + Console.WriteLine($"Random data ({count} points):"); + + // Use the generator constructor + var tree = new KdTree(() => RandomPointGenerator(0, 1), count); + + // Generate a random query point + var queryPoint = RandomPointGenerator(0, 1); + Point nearest = tree.Nearest(queryPoint); + + Console.WriteLine($"Query point: {queryPoint}"); + Console.WriteLine($"Nearest point: {nearest}"); + Console.WriteLine($"Distance: {tree.Distance:F6}"); + Console.WriteLine($"Nodes visited: {tree.Visited}"); + Console.WriteLine("------------------------------------"); + } + + public static void Main(string[] args) + { + try + { + TestWikipedia(); + TestRandom(1000); + TestRandom(100000); // Reduced count for faster C# demo + // TestRandom(1000000); // Can take longer in C# due to sorting overhead vs nth_element + } + catch (Exception e) + { + Console.ForegroundColor = ConsoleColor.Red; + Console.Error.WriteLine($"An error occurred: {e.Message}"); + Console.Error.WriteLine(e.StackTrace); + Console.ResetColor(); + } + } +} diff --git a/Task/K-d-tree/Dart/k-d-tree.dart b/Task/K-d-tree/Dart/k-d-tree.dart new file mode 100644 index 0000000000..b3d1451c28 --- /dev/null +++ b/Task/K-d-tree/Dart/k-d-tree.dart @@ -0,0 +1,220 @@ +import 'dart:math'; + +// Define Point as a list of doubles +typedef Point = List; + +// Extension method for calculating squared distance +extension PointExtension on Point { + double sqd(Point p) { + if (length != p.length) { + throw ArgumentError('Points must have the same dimension'); + } + double sum = 0.0; + for (int i = 0; i < length; i++) { + double diff = this[i] - p[i]; + sum += diff * diff; + } + return sum; + } +} + +class HyperRect { + final Point min; + final Point max; + + HyperRect(this.min, this.max); + + // Create a copy with new lists for min and max + HyperRect copy() => HyperRect(List.from(min), List.from(max)); +} + +class NearestNeighbor { + final Point? nearest; // Nullable Point + final double distSqd; + final int nodesVisited; + + NearestNeighbor(this.nearest, this.distSqd, this.nodesVisited); +} + +class KdNode { + final Point domElt; + final int split; + KdNode? left; // Nullable and mutable + KdNode? right; // Nullable and mutable + + KdNode(this.domElt, this.split, this.left, this.right); +} + +class KdTree { + final KdNode? n; // Root node (nullable) + final HyperRect bounds; + + // Constructor builds the tree + KdTree(List pts, this.bounds) + : n = _buildTree( + List.from(pts), + 0, + ); // Pass a copy to avoid modifying original + + // Static helper method for recursive tree building (like nk2) + static KdNode? _buildTree(List exset, int split) { + if (exset.isEmpty) { + return null; + } + + // Sort the list in-place based on the current split dimension + exset.sort((a, b) => a[split].compareTo(b[split])); + + int m = exset.length ~/ 2; // Integer division + final Point d = exset[m]; + + // Handle duplicate points at the median split value + // Find the last index of the element equal to the median along the split dimension + while (m + 1 < exset.length && exset[m + 1][split] == d[split]) { + m++; + } + + int s2 = split + 1; + if (s2 == d.length) { + s2 = 0; // Cycle through dimensions + } + + // Dart's sublist creates copies, which is suitable here + List leftSublist = exset.sublist(0, m); + List rightSublist = exset.sublist(m + 1); + + return KdNode( + d, + split, + _buildTree(leftSublist, s2), + _buildTree(rightSublist, s2), + ); + } + + // Public method to find the nearest neighbor + NearestNeighbor nearest(Point p) { + // Pass a copy of bounds because _nn might modify its HyperRect parameter + return _nn(n, p, bounds.copy(), double.infinity); + } + + // Private recursive helper for nearest neighbor search + NearestNeighbor _nn( + KdNode? kd, // Current node (nullable) + Point target, // Target point + HyperRect hr, // Hyper-rectangle for the current node's space + double maxDistSqd, // Current best squared distance found so far + ) { + if (kd == null) { + return NearestNeighbor(null, double.infinity, 0); + } + + int nodesVisited = 1; + final int s = kd.split; + final Point pivot = kd.domElt; + + // Create copies for left and right potential subspaces + final HyperRect leftHr = hr.copy(); + final HyperRect rightHr = hr.copy(); + + // Adjust bounds for children + leftHr.max[s] = pivot[s]; + rightHr.min[s] = pivot[s]; + + // Determine which branch is nearer + final bool targetInLeft = target[s] <= pivot[s]; + final KdNode? nearerKd = targetInLeft ? kd.left : kd.right; + final HyperRect nearerHr = targetInLeft ? leftHr : rightHr; + final KdNode? furtherKd = targetInLeft ? kd.right : kd.left; + final HyperRect furtherHr = targetInLeft ? rightHr : leftHr; + + // Recurse down the nearer branch + NearestNeighbor nearerResult = _nn(nearerKd, target, nearerHr, maxDistSqd); + Point? nearest = nearerResult.nearest; + double distSqd = nearerResult.distSqd; + nodesVisited += nearerResult.nodesVisited; + + // Update the maximum distance squared if a closer point was found + double maxDistSqd2 = (distSqd < maxDistSqd) ? distSqd : maxDistSqd; + + // Check the distance from the target to the splitting plane + double d = pivot[s] - target[s]; + d *= d; + + // If the splitting plane is further than the current nearest, no need to check further branch + if (d > maxDistSqd2) { + return NearestNeighbor(nearest, distSqd, nodesVisited); + } + + // Check distance from target to the pivot point itself + d = pivot.sqd(target); // Use extension method + if (d < distSqd) { + nearest = pivot; + distSqd = d; + maxDistSqd2 = distSqd; // Update max distance again + } + + // Recurse down the further branch if necessary + NearestNeighbor furtherResult = _nn( + furtherKd, + target, + furtherHr, + maxDistSqd2, + ); + nodesVisited += furtherResult.nodesVisited; + + // If the further branch found an even closer point + if (furtherResult.distSqd < distSqd) { + nearest = furtherResult.nearest; + distSqd = furtherResult.distSqd; + } + + return NearestNeighbor(nearest, distSqd, nodesVisited); + } +} + +// --- Helper Functions and Main --- + +final rand = Random(); + +Point randomPt(int dim) => List.generate(dim, (_) => rand.nextDouble()); + +List randomPts(int dim, int n) => List.generate(n, (_) => randomPt(dim)); + +void showNearest(String heading, KdTree kd, Point p) { + print('$heading:'); + print('Point : $p'); // Default List.toString() is fine + final result = kd.nearest(p); + print('Nearest neighbor : ${result.nearest}'); + print( + 'Distance : ${sqrt(result.distSqd)}', + ); // Use sqrt from dart:math + print('Nodes visited : ${result.nodesVisited}'); + print(''); // Empty line +} + +void main() { + // Note: Using List instead of MutableList + final points = [ + [2.0, 3.0], + [5.0, 4.0], + [9.0, 6.0], + [4.0, 7.0], + [8.0, 1.0], + [7.0, 2.0], + ]; + + var hr = HyperRect([0.0, 0.0], [10.0, 10.0]); + var kd = KdTree(points, hr); // Pass the original list + showNearest('WP example data', kd, [9.0, 2.0]); + + hr = HyperRect([0.0, 0.0, 0.0], [1.0, 1.0, 1.0]); + // Generate random points directly as List + kd = KdTree(randomPts(3, 1000), hr); + showNearest('1000 random 3D points', kd, randomPt(3)); + + // Use hr.copy() if you intend to modify hr later, otherwise it's not strictly needed + // The Kotlin code uses copy, so we replicate it here. + var hrCopy = hr.copy(); + kd = KdTree(randomPts(3, 400000), hrCopy); // Pass the copy + showNearest('400,000 random 3D points', kd, randomPt(3)); +} diff --git a/Task/K-d-tree/JavaScript/k-d-tree.js b/Task/K-d-tree/JavaScript/k-d-tree.js new file mode 100644 index 0000000000..fd28a1f18f --- /dev/null +++ b/Task/K-d-tree/JavaScript/k-d-tree.js @@ -0,0 +1,235 @@ +/** + * Class for representing a point. coordinate_type must be a numeric type. + */ +class Point { + constructor(coords) { + if (Array.isArray(coords)) { + this.coords = [...coords]; + } else if (coords instanceof Object) { + this.coords = Array.from(coords); + } + } + + /** + * Returns the coordinate in the given dimension. + * + * @param {number} index dimension index (zero based) + * @return {number} coordinate in the given dimension + */ + get(index) { + return this.coords[index]; + } + + /** + * Returns the distance squared from this point to another point. + * + * @param {Point} pt another point + * @return {number} distance squared from this point to the other point + */ + distance(pt) { + let dist = 0; + for (let i = 0; i < this.coords.length; ++i) { + const d = this.get(i) - pt.get(i); + dist += d * d; + } + return dist; + } + + toString() { + return `(${this.coords.join(', ')})`; + } +} + +/** + * JavaScript k-d tree implementation, based on the C++ version. + */ +class KDTree { + constructor(pointsOrGenerator, count) { + this.nodes = []; + this.dimensions = 0; + this.root = null; + this.best = null; + this.bestDist = 0; + this.visited = 0; + + if (typeof pointsOrGenerator === 'function' && typeof count === 'number') { + // Constructor with generator function + for (let i = 0; i < count; ++i) { + const point = pointsOrGenerator(); + if (i === 0) { + this.dimensions = point.coords.length; + } + this.nodes.push({ point, left: null, right: null }); + } + } else if (Array.isArray(pointsOrGenerator)) { + // Constructor with array of points + this.nodes = pointsOrGenerator.map(point => ({ point, left: null, right: null })); + if (this.nodes.length > 0) { + this.dimensions = this.nodes[0].point.coords.length; + } + } + + if (this.nodes.length > 0) { + this.root = this.makeTree(0, this.nodes.length, 0); + } + } + + /** + * Comparison function for sorting nodes by a specific dimension + */ + nodeCmp(a, b, index) { + return a.point.get(index) - b.point.get(index); + } + + /** + * Builds the tree recursively + */ + makeTree(begin, end, index) { + if (end <= begin) return null; + + const n = begin + Math.floor((end - begin) / 2); + + // Sort and find median + this.nodes.slice(begin, end).sort((a, b) => this.nodeCmp(a, b, index)); + + // Update index for the next level + const nextIndex = (index + 1) % this.dimensions; + + // Recursively build left and right subtrees + this.nodes[n].left = this.makeTree(begin, n, nextIndex); + this.nodes[n].right = this.makeTree(n + 1, end, nextIndex); + + return this.nodes[n]; + } + + /** + * Recursively finds the nearest node to the given point + */ + findNearest(root, point, index) { + if (!root) return; + + this.visited++; + const d = root.point.distance(point); + + if (!this.best || d < this.bestDist) { + this.bestDist = d; + this.best = root; + } + + if (this.bestDist === 0) return; + + const dx = root.point.get(index) - point.get(index); + const nextIndex = (index + 1) % this.dimensions; + + // Search the side of the splitting plane that contains the point + this.findNearest(dx > 0 ? root.left : root.right, point, nextIndex); + + // If the distance to the splitting plane is less than current best distance, + // we need to check the other side too + if (dx * dx >= this.bestDist) return; + + this.findNearest(dx > 0 ? root.right : root.left, point, nextIndex); + } + + /** + * Returns true if the tree is empty, false otherwise. + */ + empty() { + return this.nodes.length === 0; + } + + /** + * Returns the number of nodes visited by the last call to nearest(). + */ + getVisited() { + return this.visited; + } + + /** + * Returns the distance between the input point and return value + * from the last call to nearest(). + */ + getDistance() { + return Math.sqrt(this.bestDist); + } + + /** + * Finds the nearest point in the tree to the given point. + * It is not valid to call this function if the tree is empty. + * + * @param {Point} point a point + * @return {Point} the nearest point in the tree to the given point + */ + nearest(point) { + if (!this.root) { + throw new Error("Tree is empty"); + } + + this.best = null; + this.visited = 0; + this.bestDist = 0; + + this.findNearest(this.root, point, 0); + + return this.best.point; + } +} + +/** + * Recreates the Wikipedia example from the original code + */ +function testWikipedia() { + const points = [ + new Point([2, 3]), + new Point([5, 4]), + new Point([9, 6]), + new Point([4, 7]), + new Point([8, 1]), + new Point([7, 2]) + ]; + + const tree = new KDTree(points); + const searchPoint = new Point([9, 2]); + const nearest = tree.nearest(searchPoint); + + console.log("Wikipedia example data:"); + console.log("nearest point:", nearest.toString()); + console.log("distance:", tree.getDistance()); + console.log("nodes visited:", tree.getVisited()); +} + +/** + * Generates random points and finds the nearest neighbor + */ +function randomPointGenerator(min, max) { + return () => { + const x = min + Math.random() * (max - min); + const y = min + Math.random() * (max - min); + const z = min + Math.random() * (max - min); + return new Point([x, y, z]); + }; +} + +function testRandom(count) { + const rpg = randomPointGenerator(0, 1); + const tree = new KDTree(rpg, count); + const point = rpg(); + const nearest = tree.nearest(point); + + console.log(`Random data (${count} points):`); + console.log("point:", point.toString()); + console.log("nearest point:", nearest.toString()); + console.log("distance:", tree.getDistance()); + console.log("nodes visited:", tree.getVisited()); +} + +// Main execution +try { + testWikipedia(); + console.log(); + testRandom(1000); + console.log(); + testRandom(10000); // Using 10,000 instead of 1,000,000 for browser performance +} catch (e) { + console.error(e.message); +} diff --git a/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg b/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg index c1f9ddbb06..58658e9467 100644 --- a/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg +++ b/Task/Kernighans-large-earthquake-problem/ALGOL-68/kernighans-large-earthquake-problem.alg @@ -37,7 +37,8 @@ BEGIN # Kernighan's large earthquake problem - show lines from data.txt that # TRUE END ); - get( real value, ( result ) ) + get( real value, ( result ) ); + close( real value ) FI; result END # real field # ; diff --git a/Task/Kernighans-large-earthquake-problem/R/kernighans-large-earthquake-problem.r b/Task/Kernighans-large-earthquake-problem/R/kernighans-large-earthquake-problem.r new file mode 100644 index 0000000000..5d35645609 --- /dev/null +++ b/Task/Kernighans-large-earthquake-problem/R/kernighans-large-earthquake-problem.r @@ -0,0 +1,2 @@ +earthquakes <- read.table("data.txt", col.names=c("date", "name", "magnitude")) +subset(earthquakes, magnitude>6) diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp/keyboard-input-flush-the-keyboard-buffer.l b/Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp/keyboard-input-flush-the-keyboard-buffer.l new file mode 100644 index 0000000000..191e125091 --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp/keyboard-input-flush-the-keyboard-buffer.l @@ -0,0 +1 @@ +(discard-input) diff --git a/Task/Keyboard-input-Keypress-check/EasyLang/keyboard-input-keypress-check.easy b/Task/Keyboard-input-Keypress-check/EasyLang/keyboard-input-keypress-check.easy index fd54accdda..943a45880f 100644 --- a/Task/Keyboard-input-Keypress-check/EasyLang/keyboard-input-keypress-check.easy +++ b/Task/Keyboard-input-Keypress-check/EasyLang/keyboard-input-keypress-check.easy @@ -1,6 +1,5 @@ on key - clear - move 10 80 + gclear k$ = keybkey - text k$ + gtext 10 80 k$ . diff --git a/Task/Keyboard-input-Keypress-check/Emacs-Lisp/keyboard-input-keypress-check.l b/Task/Keyboard-input-Keypress-check/Emacs-Lisp/keyboard-input-keypress-check.l new file mode 100644 index 0000000000..d7752bc10d --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Emacs-Lisp/keyboard-input-keypress-check.l @@ -0,0 +1,21 @@ +(defun store-keypress () + "If a key has been pressed, store it as a variable. +Note that the variable created is a variable inside the scope of let and +will not be available as a variable outside the scope of let. However, +the function also returns the value of the variable, which can be used +outside the scope of let." + (let ((keypress)) + (if (input-pending-p) + (setq keypress (char-to-string (read-key)))))) + + +(defun store-keypress-multiple () + "If one or more keys have been pressed, store it/them as a variable. +Note that the variable created is a variable inside the scope of let and +will not be available as a variable outside the scope of let. However, +the function also returns the value of the variable, which can be used +outside the scope of let." + (let ((keypress)) + (while (input-pending-p) + (push (read-key) keypress)) + (setq keypress (concat (nreverse keypress))))) diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/EasyLang/keyboard-input-obtain-a-y-or-n-response.easy b/Task/Keyboard-input-Obtain-a-Y-or-N-response/EasyLang/keyboard-input-obtain-a-y-or-n-response.easy index ee2a05a539..7447fa013d 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/EasyLang/keyboard-input-obtain-a-y-or-n-response.easy +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/EasyLang/keyboard-input-obtain-a-y-or-n-response.easy @@ -1,12 +1,10 @@ -move 10 80 -text "Press y or n" +gtext 10 80 "Press y or n" repeat sleep -1 ans$ = keybkey until ans$ = "y" or ans$ = "n" . -move 10 70 -text "-> " & ans$ +gtext 10 70 "-> " & ans$ # on key # diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp/keyboard-input-obtain-a-y-or-n-response.l b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp/keyboard-input-obtain-a-y-or-n-response.l new file mode 100644 index 0000000000..332abb1ffb --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp/keyboard-input-obtain-a-y-or-n-response.l @@ -0,0 +1,5 @@ +(defun get-happiness () + "Asks for y or n response about happiness. +Returns t if happy; nil otherwise." + (discard-input) + (y-or-n-p "Are you happy?")) diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-1.tcl b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-1.tcl index ff75776be1..cf1c6cb11d 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-1.tcl +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-1.tcl @@ -1,17 +1,31 @@ -proc yesno {{message "Press Y or N to continue"}} { - fconfigure stdin -blocking 0 - exec stty raw - read stdin ; # flush - puts -nonewline "${message}: " - flush stdout - while {![eof stdin]} { - set c [string tolower [read stdin 1]] - if {$c eq "y" || $c eq "n"} break +proc ask_yn {prompt} { + + puts "${prompt} ?" + set answer "" + set valid 0 + + while {! $valid} { + + gets stdin answer + + switch -nocase -glob $answer { + Y* { set valid 1; set answer Y } + N* { set valid 1; set answer N } + default {} + } + + if {!$valid} {puts "Choose either Y or N"} } - puts [string toupper $c] - exec stty -raw - fconfigure stdin -blocking 1 - return [expr {$c eq "y"}] + + return [expr $answer == Y] } -set yn [yesno "Do you like programming (Y/N)"] +set prompt "Is this correct? (Y/N)" + +set ans [ask_yn $prompt] + +if {$ans} { + puts "answer was Yes" +} else { + puts "answer was No" +} diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-2.tcl b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-2.tcl index e2f5af5829..ff75776be1 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-2.tcl +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-2.tcl @@ -1,11 +1,17 @@ -proc yesno {message} { - toplevel .msg - pack [label .msg.l -text "$message\n (type Y/N)?"] - set ::yn "" - bind .msg {set ::yn "Y"} - bind .msg {set ::yn "N"} - vwait ::yn - destroy .msg +proc yesno {{message "Press Y or N to continue"}} { + fconfigure stdin -blocking 0 + exec stty raw + read stdin ; # flush + puts -nonewline "${message}: " + flush stdout + while {![eof stdin]} { + set c [string tolower [read stdin 1]] + if {$c eq "y" || $c eq "n"} break + } + puts [string toupper $c] + exec stty -raw + fconfigure stdin -blocking 1 + return [expr {$c eq "y"}] } -yesno "Do you like programming?" +set yn [yesno "Do you like programming (Y/N)"] diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-3.tcl b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-3.tcl new file mode 100644 index 0000000000..e2f5af5829 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Tcl/keyboard-input-obtain-a-y-or-n-response-3.tcl @@ -0,0 +1,11 @@ +proc yesno {message} { + toplevel .msg + pack [label .msg.l -text "$message\n (type Y/N)?"] + set ::yn "" + bind .msg {set ::yn "Y"} + bind .msg {set ::yn "N"} + vwait ::yn + destroy .msg +} + +yesno "Do you like programming?" diff --git a/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy b/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy index 0aa199a5a9..1fa0d21cb4 100644 --- a/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy +++ b/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy @@ -3,7 +3,7 @@ weight[] = [ 9 13 153 50 15 68 27 39 23 52 11 32 24 48 73 42 43 22 7 18 4 30 ] value[] = [ 150 35 200 160 60 45 60 40 30 10 70 30 15 10 40 70 75 80 20 12 50 10 ] max_w = 400 # -proc solve i maxw . items[] wres vres . +proc solve i maxw &items[] &wres &vres . if i = 0 wres = 0 vres = 0 @@ -24,6 +24,4 @@ proc solve i maxw . items[] wres vres . solve len weight[] max_w items[] w v print "weight: " & w & " value: " & v write "items:" -for item in items[] - write " " & name$[item] -. +for item in items[] : write " " & name$[item] diff --git a/Task/Knapsack-problem-Bounded/EasyLang/knapsack-problem-bounded.easy b/Task/Knapsack-problem-Bounded/EasyLang/knapsack-problem-bounded.easy index 90d510ec33..7baddc0633 100644 --- a/Task/Knapsack-problem-Bounded/EasyLang/knapsack-problem-bounded.easy +++ b/Task/Knapsack-problem-Bounded/EasyLang/knapsack-problem-bounded.easy @@ -6,7 +6,7 @@ maxweight = 400 # global valuesum[] maxv . # -proc solve i maxw v . items[] wres vres . +proc solve i maxw v &items[] &wres &vres . if i = 0 wres = 0 vres = 0 @@ -31,13 +31,11 @@ proc solve i maxw v . items[] wres vres . . . . -proc prepare . . - for i to len weight[] - for j to pieces[i] - n$[] &= name$[i] - w[] &= weight[i] - v[] &= value[i] - . +proc prepare . + for i to len weight[] : for j to pieces[i] + n$[] &= name$[i] + w[] &= weight[i] + v[] &= value[i] . swap name$[] n$[] swap weight[] w[] @@ -63,6 +61,4 @@ prepare solve len weight[] maxweight 0 items[] wsum vsum print "weight: " & wsum & " value: " & vsum print "items:" -for item in items[] - print " " & name$[item] -. +for item in items[] : print " " & name$[item] diff --git a/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim b/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim index f6e6f55e2b..84ead213cd 100644 --- a/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim +++ b/Task/Knapsack-problem-Continuous/Nim/knapsack-problem-continuous.nim @@ -17,7 +17,7 @@ var items = @[Item(name: "beef", weight: 3.8, price: 36.0), Item(name: "salami", weight: 3.0, price: 95.0), Item(name: "sausage", weight: 5.9, price: 98.0) ] - ] + # Compute unit prices and sort items by decreasing unit price. for item in items.mitems: item.unitPrice = item.price / item.weight diff --git a/Task/Knapsack-problem-Unbounded/EasyLang/knapsack-problem-unbounded.easy b/Task/Knapsack-problem-Unbounded/EasyLang/knapsack-problem-unbounded.easy index 05c334295d..c87883db00 100644 --- a/Task/Knapsack-problem-Unbounded/EasyLang/knapsack-problem-unbounded.easy +++ b/Task/Knapsack-problem-Unbounded/EasyLang/knapsack-problem-unbounded.easy @@ -9,7 +9,7 @@ n = len names$[] len cnt[] n global best[] bestval . # -proc knapsack i val wgt vol . . +proc knapsack i val wgt vol . if i > n if val > bestval bestval = val diff --git a/Task/Knights-tour/EasyLang/knights-tour.easy b/Task/Knights-tour/EasyLang/knights-tour.easy index 18803ed091..e6511f1a37 100644 --- a/Task/Knights-tour/EasyLang/knights-tour.easy +++ b/Task/Knights-tour/EasyLang/knights-tour.easy @@ -11,23 +11,19 @@ func cntmoves m[] . . return n . -proc sortmoves . m[][] . +proc sortmoves &m[][] . for i = 1 to len m[][] cnt[] &= cntmoves m[i][] . - for i = 1 to len cnt[] - 1 - for j = i + 1 to len cnt[] - if cnt[j] < cnt[i] - swap cnt[j] cnt[i] - swap m[j][] m[i][] - . + for i = 1 to len cnt[] - 1 : for j = i + 1 to len cnt[] + if cnt[j] < cnt[i] + swap cnt[j] cnt[i] + swap m[j][] m[i][] . . . func solve r c cnt . - if cnt > size * size - return 1 - . + if cnt > size * size : return 1 movs[][] = [ ] for d = 1 to len dirs[][] rn = r + dirs[d][1] @@ -41,29 +37,21 @@ func solve r c cnt . rn = movs[i][1] cn = movs[i][2] brd[rn][cn] = cnt - if solve rn cn (cnt + 1) = 1 - return 1 - . + if solve rn cn (cnt + 1) = 1 : return 1 brd[rn][cn] = 0 . return 0 . -proc prepare . . +proc prepare . brd[][] = [ ] len brd[][] size - for r to size - len brd[r][] size - . + for r to size : len brd[r][] size . -proc printbrd . . - numfmt 0 3 - if size > 10 - numfmt 0 4 - . +proc printbrd . + numfmt 3 0 + if size > 10 : numfmt 4 0 for r to size - for c to size - write brd[r][c] - . + for c to size : write brd[r][c] print "" . . @@ -80,33 +68,25 @@ else print "no solutions found: (" & r0 & " " & c0 & ")" . # -proc showgraf . . +proc showgraf . sc = 100 / size - linewidth sc / 15 + glinewidth sc / 15 col[] = [ 777 333 ] - for r = 0 to size - 1 - for c = 0 to size - 1 - color col[(r + c) mod1 2] - move sc * c sc * r - rect sc sc - . + for r = 0 to size - 1 : for c = 0 to size - 1 + gcolor col[(r + c) mod1 2] + grect sc * c sc * r sc sc . - move 0 / 0 0 for i to size * size - for r = 1 to size - for c = 1 to size - if brd[r][c] = i - color 600 - x = c * sc - sc / 2 - y = r * sc - sc / 2 - line x y - color 880 - circle sc / 10 - . - . + for r = 1 to size : for c = 1 to size : if brd[r][c] = i + gcolor 600 + x = c * sc - sc / 2 + y = r * sc - sc / 2 + if i > 1 : gline xp yp x y + xp = x + yp = y + gcolor 880 + gcircle x y sc / 10 . . . -if found = 1 - showgraf -. +if found = 1 : showgraf diff --git a/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy b/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy index ea070c7fe5..d764abb8d7 100644 --- a/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy +++ b/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy @@ -1,4 +1,4 @@ -proc shuffle . a[] . +proc shuffle &a[] . for i = len a[] downto 2 r = random i swap a[r] a[i] diff --git a/Task/Knuth-shuffle/Objeck/knuth-shuffle.objeck b/Task/Knuth-shuffle/Objeck/knuth-shuffle.objeck new file mode 100644 index 0000000000..8c086185c6 --- /dev/null +++ b/Task/Knuth-shuffle/Objeck/knuth-shuffle.objeck @@ -0,0 +1,21 @@ +# version for array of references +function : Shuffle (array : Base[]) ~ Nil { + n := array->Size(); + while(n > 1) { + k := Int->Random(n--); //decrements after using the value + temp := array[n]; + array[n] := array[k]; + array[k] := temp; + } +} + +# version for array of ints +function : Shuffle (array : Int[]) ~ Nil { + n := array->Size(); + while(n > 1) { + k := Int->Random(n--); # decrements after using the value + temp := array[n]; + array[n] := array[k]; + array[k] := temp; + }; +} diff --git a/Task/Knuth-shuffle/Wisp/knuth-shuffle.wisp b/Task/Knuth-shuffle/Wisp/knuth-shuffle.wisp new file mode 100644 index 0000000000..e700dbc1ca --- /dev/null +++ b/Task/Knuth-shuffle/Wisp/knuth-shuffle.wisp @@ -0,0 +1,30 @@ +import : only (srfi :27 random-bits) random-integer + srfi :64 tests + +define : vector-shuffle! vec + . "Shuffle the vector VEC with Knuth shuffle" + define len : vector-length vec + define : swap! i j + define tmp : vector-ref vec i + vector-set! vec i : vector-ref vec j + vector-set! vec j tmp + cond + : <= len 1 + . vec + else + for-each : λ (i) : swap! i : random-integer i + reverse : cdr : iota len + . vec + +define : list-shuffle the-list + . "Shuffle a list in O(N) with Knuth shuffle using an intermediate vector." + vector->list : vector-shuffle! : list->vector the-list + +;; deterministic tests +test-begin "knuth-shuffle" +test-equal '() : list-shuffle '() +test-equal '(1) : list-shuffle '(1) +test-end +;; sample run +display : list-shuffle '(1 2 3 4) +newline diff --git a/Task/Knuths-algorithm-S/Fortran/knuths-algorithm-s.f b/Task/Knuths-algorithm-S/Fortran/knuths-algorithm-s.f new file mode 100644 index 0000000000..af81b50898 --- /dev/null +++ b/Task/Knuths-algorithm-S/Fortran/knuths-algorithm-s.f @@ -0,0 +1,121 @@ +module knuth_s + implicit none + private + public :: s_of_n_creator, free_sample, sample_state, s_of_n + + ! Type to hold sample state + type :: sample_state + integer :: n + integer :: count + integer, allocatable :: sample(:) + end type sample_state + +contains + + ! Subroutine to create the s_of_n sampling function + subroutine s_of_n_creator(n, state) + integer, intent(in) :: n + type(sample_state), pointer :: state + + allocate (state) + state % n = n + state % count = 0 + allocate (state % sample(n)) + end subroutine s_of_n_creator + + ! Function to perform sampling + function s_of_n(state, item) result(current_sample) + type(sample_state), pointer :: state + integer, intent(in) :: item + integer, pointer :: current_sample(:) + real :: r + integer :: j + + ! Add item to sample if we haven't reached n yet + if (state % count < state % n) then + state % count = state % count + 1 + state % sample(state % count) = item + else + ! Knuth's Algorithm S: select with probability n/i + call random_number(r) + if (r < real(state % n) / real(state % count + 1)) then + ! Randomly replace one of the existing items + call random_number(r) + j = int(r * state % n) + 1 + state % sample(j) = item + end if + state % count = state % count + 1 + end if + current_sample => state % sample + end function s_of_n + + ! Cleanup function to deallocate sample state + subroutine free_sample(state) + type(sample_state), pointer :: state + deallocate (state % sample) + deallocate (state) + end subroutine free_sample + +end module knuth_s + +program test_knuth_s + use knuth_s + implicit none + type(sample_state), pointer :: state + integer, pointer :: sample(:) + integer :: i, j, k, reps + integer :: frequencies(0:9) + character(len=50) :: sample_str + integer :: n, timex(8) + integer, allocatable :: seed(:) + call random_seed(size=n) + allocate (seed(n)) + call date_and_time(values=timex) + seed(1) = timex(5) * 3600000 + timex(6) * 60000 + timex(7) * 1000 + timex(8) + do i = 2, n + seed(i) = seed(1) + 37 * (i - 1) + end do + ! Initialize random seed + call random_seed(put=seed) + + ! Show one run's sampling progression + print *, 'Single run samples for n = 3:' + call s_of_n_creator(3, state) + do i = 0, 9 + sample => s_of_n(state, i) + ! Format sample output + sample_str = '' + write (sample_str, '("[", *(I0, ", "))') sample(1:min(state % count, 3)) + if (state % count > 0) then + sample_str = trim(sample_str) + sample_str = sample_str(1:len_trim(sample_str) - 1)//']' + else + sample_str = '[]' + end if + print '(A, I0, A, A)', ' Item: ', i, ' -> sample: ', trim(sample_str) + end do + call free_sample(state) + + ! Initialize frequency counter + frequencies = 0 + + ! Run 100,000 repetitions to count final sample frequencies + reps = 100000 + do i = 1, reps + call s_of_n_creator(3, state) + do j = 0, 9 + sample => s_of_n(state, j) + end do + ! Count frequencies from final sample + do k = 1, 3 + frequencies(sample(k)) = frequencies(sample(k)) + 1 + end do + call free_sample(state) + end do + + ! Print frequency results + print *, 'Test item frequencies for ', reps, ' runs:' + do i = 0, 9 + print '(I2, ": ", I5)', i, frequencies(i) + end do +end program test_knuth_s diff --git a/Task/Knuths-algorithm-S/FreeBASIC/knuths-algorithm-s.basic b/Task/Knuths-algorithm-S/FreeBASIC/knuths-algorithm-s.basic new file mode 100644 index 0000000000..d81ad506c3 --- /dev/null +++ b/Task/Knuths-algorithm-S/FreeBASIC/knuths-algorithm-s.basic @@ -0,0 +1,98 @@ +Type SampleState + sample(0 To 99) As Integer ' Array to store the sample (arbitrary maximum size) + sampleSize As Integer ' Current sample size + i As Integer ' Counter of processed elements + n As Integer ' Desired sample size +End Type + +' Function to generate a random number between 0 and max-1 +Function randInt(Byval max As Integer) As Integer + Return Int(Rnd() * max) +End Function + +' Function to create a new sampler +Function createSampler(Byval n As Integer) As SampleState + Dim sampler As SampleState + sampler.sampleSize = 0 + sampler.i = 0 + sampler.n = n + Return sampler +End Function + +' Function to process a new element and update the sample +Function sampleOfN(Byref sampler As SampleState, Byval item As Integer) As Integer Ptr + sampler.i += 1 + + If sampler.i <= sampler.n Then + sampler.sample(sampler.sampleSize) = item + sampler.sampleSize += 1 + Else + If randInt(sampler.i) < sampler.n Then + sampler.sample(randInt(sampler.n)) = item + End If + End If + + Return @sampler.sample(0) +End Function + +Sub printArray(arr() As Integer, Byval size As Integer) + Print "[" + For i As Integer = 0 To size-1 + Print arr(i) + If i < size-1 Then Print ", " + Next + Print "]" +End Sub + +Sub main() + Dim As Integer i, j + + Dim As Integer frequency(0 To 9) + For i = 0 To 9 + frequency(i) = 0 + Next + + Print "Single run samples for n = 3:" + + Dim As SampleState sampler = createSampler(3) + Dim As Integer Ptr samplePtr + Dim As Integer sample(0 To 2) + + For i = 0 To 9 + samplePtr = sampleOfN(sampler, i) + + For j = 0 To sampler.sampleSize-1 + sample(j) = samplePtr[j] + Next + + Print " Item: " & i & " -> sample: "; + Print "[ "; + For j = 0 To sampler.sampleSize-1 + Print Chr(8) & sample(j); + If j < sampler.sampleSize-1 Then Print ", "; + Next + Print "]" + Next + + For i = 0 To 99999 + sampler = createSampler(3) + + For j = 0 To 9 + samplePtr = sampleOfN(sampler, j) + Next + + For j = 0 To sampler.n-1 + frequency(samplePtr[j]) += 1 + Next + Next + + Print !"\nTest item frequencies for 100000 runs:" + For i = 0 To 9 + Print " " & i & ": " & frequency(i) + Next +End Sub + +Randomize Timer +main() + +Sleep diff --git a/Task/Knuths-algorithm-S/JavaScript/knuths-algorithm-s.js b/Task/Knuths-algorithm-S/JavaScript/knuths-algorithm-s.js new file mode 100644 index 0000000000..e1e6db258e --- /dev/null +++ b/Task/Knuths-algorithm-S/JavaScript/knuths-algorithm-s.js @@ -0,0 +1,36 @@ +class SOfN { + constructor(n) { + this.m = this.n = n + this.s = [] + } + + add(item) { + if (this.s.length < this.n) { + this.s.push(item) + } else { + const rand = Math.floor(Math.random() * ++this.m) + if (rand < this.n) { + this.s[rand] = item + } + } + } +} + +function main() { + for (const [n, m] of [[3, 3], [3, 10]]) { + const freqs = new Array(m).fill(0) + + for (let i = 0; i < 1e5; ++i) { + const sOfN = new SOfN(n) + for (let x = 0; x < m; ++x) { + sOfN.add(x) + } + for (const d of sOfN.s) { + ++freqs[d] + } + } + console.log(`Results for n=${n}, m=${m}: [${freqs.join(', ')}]`) + } +} + +main() diff --git a/Task/Knuths-power-tree/FreeBASIC/knuths-power-tree.basic b/Task/Knuths-power-tree/FreeBASIC/knuths-power-tree.basic new file mode 100644 index 0000000000..3c1132d308 --- /dev/null +++ b/Task/Knuths-power-tree/FreeBASIC/knuths-power-tree.basic @@ -0,0 +1,247 @@ +#include once "big_int\big_integer.bi" + +Const NULL As Any Ptr = 0 + +Type HashEntry + key As Integer + value As Integer + sgte As HashEntry Ptr +End Type + +Type HashMap + buckets(255) As HashEntry Ptr + + Declare Sub put(key As Integer, value As Integer) + Declare Function get(key As Integer, defaultValue As Integer = 0) As Integer + Declare Function contains(key As Integer) As Boolean +End Type + +Sub HashMap.put(key As Integer, value As Integer) + Dim As Integer bucket = key And 255 + Dim As HashEntry Ptr entry = buckets(bucket) + + ' Check if key already exists + While entry <> NULL + If entry->key = key Then + entry->value = value + Exit Sub + End If + entry = entry->sgte + Wend + + ' Create new entry + entry = New HashEntry + entry->key = key + entry->value = value + entry->sgte = buckets(bucket) + buckets(bucket) = entry +End Sub + +Function HashMap.get(key As Integer, defaultValue As Integer = 0) As Integer + Dim As Integer bucket = key And 255 + Dim As HashEntry Ptr entry = buckets(bucket) + + While entry <> NULL + If entry->key = key Then Return entry->value + entry = entry->sgte + Wend + + Return defaultValue +End Function + +Function HashMap.contains(key As Integer) As Boolean + Dim As Integer bucket = key And 255 + Dim As HashEntry Ptr entry = buckets(bucket) + + While entry <> NULL + If entry->key = key Then Return True + entry = entry->sgte + Wend + + Return False +End Function + +Type IntArray + dato As Integer Ptr + size As Integer + capacity As Integer + + Declare Sub add(value As Integer) + Declare Function get(index As Integer) As Integer + Declare Function getSize() As Integer + Declare Sub clear() +End Type + +Sub IntArray.add(value As Integer) + If size >= capacity Then + capacity = Iif(capacity = 0, 8, capacity * 2) + Dim As Integer Ptr newdato = New Integer[capacity] + If dato <> NULL Then + For i As Integer = 0 To size - 1 + newdato[i] = dato[i] + Next + Delete[] dato + End If + dato = newdato + End If + + dato[size] = value + size += 1 +End Sub + +Function IntArray.get(index As Integer) As Integer + If index >= 0 And index < size Then Return dato[index] + Return 0 +End Function + +Function IntArray.getSize() As Integer + Return size +End Function + +Sub IntArray.clear() + size = 0 +End Sub + +' Global variables +Dim Shared As HashMap p +Dim Shared As IntArray levels(0) ' Array of levels + +' Function to compute the path to n +Function path(n As Integer) As IntArray + Dim As Integer i, j, x, y, sum + Dim As IntArray result + + ' Base case + If n = 0 Then Return result + + ' Check if we already have a path to n + While Not p.contains(n) + Dim q As IntArray + + ' Process current level + For i = 0 To levels(0).getSize() - 1 + x = levels(0).get(i) + + ' Get path to x + Dim As IntArray xPath = path(x) + + ' Try to extend the path + For j = 0 To xPath.getSize() - 1 + y = xPath.get(j) + sum = x + y + + ' Check if we already have a path to sum + If p.contains(sum) Then Exit For + + ' Record the path + p.put(sum, x) + q.add(sum) + Next j + Next i + + ' Update level + levels(0).clear() + For i = 0 To q.getSize() - 1 + levels(0).add(q.get(i)) + Next i + + ' If we can't make progress, break + If q.getSize() = 0 Then Exit While + Wend + + ' Reconstruct the path + Dim As Integer curr = n + Dim As IntArray tempPath + + While curr <> 0 + tempPath.add(curr) + curr = p.get(curr) + Wend + + ' Reverse the path + For i = tempPath.getSize() - 1 To 0 Step -1 + result.add(tempPath.get(i)) + Next i + + Return result +End Function + +' Function to compute x^n using the tree method with BigInteger for integers +Function treePowBig(x As Integer, n As Integer) As BigInt + Dim As BigInt r(0 To n) + ' Initialize r[0] = 1 and r[1] = x + r(0) = 1 + r(1) = x + + Dim As Integer i, curr, p = 0 + Dim As IntArray pathToN = path(n) + + For i = 0 To pathToN.getSize() - 1 + curr = pathToN.get(i) + r(curr) = r(curr - p) * r(p) + p = curr + Next i + + Return r(n) +End Function + +' Function to compute x^n using the tree method with high precision for decimals +Function treePowDecimal(x As Double, n As Integer) As Double + Dim As Double r(0 To n) + ' Initialize r[0] = 1 and r[1] = x + r(0) = 1 + r(1) = x + + Dim As Integer i, curr, p = 0 + Dim As IntArray pathToN = path(n) + + For i = 0 To pathToN.getSize() - 1 + curr = pathToN.get(i) + r(curr) = r(curr - p) * r(p) + p = curr + Next i + + Return r(n) +End Function + +' Function to display the power calculation +Sub showPow(x As Double, n As Integer) + Dim As IntArray pathToN = path(n) + Dim As String pathStr = "" + + For i As Integer = 0 To pathToN.getSize() - 1 + If i > 0 Then pathStr &= ", " + pathStr &= Str(pathToN.get(i)) + Next i + + Print n & ": [" & pathStr & "]" + + If Int(x) = x And n > 20 Then + ' Use BigInt for large integer powers + Dim As BigInt result = treePowBig(Int(x), n) + Print x & "^" & n & " = " & result + Elseif Int(x) <> x Then + ' Use high precision for decimal numbers + Dim As Double result = treePowDecimal(x, n) + Print Using "##.#^## = ####.######"; x; n; result + Else + ' Use standard calculation for small integer powers + Dim As Double result = treePowDecimal(x, n) + Print Using "##^## = &"; Int(x); n; result + End If + Print +End Sub + +' Initialize +p.put(1, 0) +levels(0).add(1) + +' Main program +For i As Integer = 0 To 17 + showPow(2, i) +Next i + +showPow(1.1, 81) +showPow(3, 191) + +Sleep diff --git a/Task/Knuths-power-tree/JavaScript/knuths-power-tree.js b/Task/Knuths-power-tree/JavaScript/knuths-power-tree.js new file mode 100644 index 0000000000..87e6b3f255 --- /dev/null +++ b/Task/Knuths-power-tree/JavaScript/knuths-power-tree.js @@ -0,0 +1,103 @@ +class PowerTree { + static p = new Map(); + static lvl = []; + + static { + PowerTree.p.set(1, 0); + + let temp = [1]; + PowerTree.lvl.push(temp); + } + + static path(n) { + if (n === 0) return []; + while (!PowerTree.p.has(n)) { + let q = []; + for (let x of PowerTree.lvl[0]) { + for (let y of PowerTree.path(x)) { + if (PowerTree.p.has(x + y)) break; + PowerTree.p.set(x + y, x); + q.push(x + y); + } + } + PowerTree.lvl[0] = [...q]; // Important: create a new array! Otherwise, the original array is mutated. + } + let temp = PowerTree.path(PowerTree.p.get(n)); + temp.push(n); + return temp; + } + + static treePow(x, n) { + const r = new Map(); + r.set(0, 1n); // Changed to bigint for accurate integer results + r.set(1, BigInt(Math.round(x))); // Convert to BigInt + + + if (Number.isInteger(x) && Number.isInteger(n) && n>30){ + r.set(0, 1n); + r.set(1, BigInt(x)); + } else { + r.set(0, 1); + r.set(1, x); + } + + + let p = 0; + const path_result = PowerTree.path(n); + + for (let i of path_result) { + let a = r.get(i - p); + let b = r.get(p); + + if (Number.isInteger(x) && Number.isInteger(n) && n>30){ + r.set(i, a * b); + } else { + + if (typeof a === 'bigint' && typeof b === 'bigint'){ + r.set(i, Number(a) * Number(b)); + } else if (typeof a === 'bigint'){ + r.set(i, Number(a) * b); + } else if (typeof b === 'bigint'){ + r.set(i, a * Number(b)); + } else { + r.set(i, a * b); + } + } + + + p = i; + } + + if (Number.isInteger(x) && Number.isInteger(n) && n>30){ + return Number(r.get(n)); + } + return r.get(n); + } + + + static showPow(x, n, isIntegral) { + console.log(`${n}: ${PowerTree.path(n)}`); + let f = isIntegral ? "%.0f" : "%f"; + //console.log(f, x); // Javascript doesn't have printf-style formatting built in + + let formatted_x; + if (isIntegral) { + formatted_x = Math.round(x); + } else { + formatted_x = x.toFixed(6); // Or whatever precision you need. + } + + console.log(`${formatted_x} ^ ${n} = ${PowerTree.treePow(x, n)}`); + console.log("\n"); + } + + static main() { + for (let n = 0; n <= 17; ++n) { + PowerTree.showPow(2.0, n, true); + } + PowerTree.showPow(1.1, 81, false); + PowerTree.showPow(3.0, 191, true); + } +} + +PowerTree.main(); diff --git a/Task/Koch-curve/EasyLang/koch-curve.easy b/Task/Koch-curve/EasyLang/koch-curve.easy index ab72dbe553..81bdc0e0b6 100644 --- a/Task/Koch-curve/EasyLang/koch-curve.easy +++ b/Task/Koch-curve/EasyLang/koch-curve.easy @@ -1,4 +1,6 @@ -proc koch x1 y1 x2 y2 iter . . +xp = 0 / 0 +yp = xp +proc koch x1 y1 x2 y2 iter . x3 = (x1 * 2 + x2) / 3 y3 = (y1 * 2 + y2) / 3 x4 = (x1 + x2 * 2) / 3 @@ -12,17 +14,18 @@ proc koch x1 y1 x2 y2 iter . . koch x5 y5 x4 y4 iter koch x4 y4 x2 y2 iter else - line x1 y1 - line x3 y3 - line x5 y5 - line x4 y4 - line x2 y2 + if xp = xp : gline xp yp x1 y1 + gline x1 y1 x3 y3 + gline x3 y3 x3 y3 + gline x3 y3 x4 y4 + gline x4 y4 x2 y2 + xp = x2 + yp = y2 . . -linewidth 0.3 +glinewidth 0.3 x1 = 15 y1 = 30 -move x1 y1 for ang = 0 step 120 to 240 x2 = x1 + 70 * cos ang y2 = y1 + 70 * sin ang diff --git a/Task/Kosaraju/EasyLang/kosaraju.easy b/Task/Kosaraju/EasyLang/kosaraju.easy index d4b827640d..d64470a143 100644 --- a/Task/Kosaraju/EasyLang/kosaraju.easy +++ b/Task/Kosaraju/EasyLang/kosaraju.easy @@ -6,7 +6,7 @@ len vis[] gc len l[] gc x = gc len t[][] gc -proc visit u . . +proc visit u . if vis[u] = 0 vis[u] = 1 for v in g[u][] @@ -21,7 +21,7 @@ for i range0 gc visit i . len c[] gc -proc assign u root . . +proc assign u root . if vis[u] = 1 vis[u] = 0 c[u] = root diff --git a/Task/Kosaraju/Rust/kosaraju.rs b/Task/Kosaraju/Rust/kosaraju.rs new file mode 100644 index 0000000000..a6e0c5a6d4 --- /dev/null +++ b/Task/Kosaraju/Rust/kosaraju.rs @@ -0,0 +1,91 @@ +use std::fmt; + +// Define a wrapper struct for Vec +struct DisplayVec(Vec); + +impl DisplayVec { + fn new(vec: Vec) -> Self { + DisplayVec(vec) + } +} + + +// Implement the Display trait for the wrapper struct +impl fmt::Display for DisplayVec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[")?; + if let Some((first, rest)) = self.0.split_first() { + write!(f, "{}", first)?; + for elem in rest { + write!(f, ", {}", elem)?; + } + } + write!(f, "]") + } +} + +fn kosaraju(g: &mut Vec>) -> Vec { + let size = g.len(); + let mut vis = vec![false; size]; // all false by default + let mut l = vec![0; size]; // all zero by default + let mut x = size; // index for filling l in reverse order + let mut t = vec![vec![]; size]; // transpose graph + + // Recursive subroutine 'visit': + fn visit(u: usize, g: &Vec>, vis: &mut Vec, l: &mut Vec, x: &mut usize, t: &mut Vec>) { + if !vis[u] { + vis[u] = true; + for &v in &g[u] { + visit(v, g, vis, l, x, t); + t[v].push(u); // construct transpose + } + *x -= 1; + l[*x] = u; + } + } + + // 2. For each vertex u of the graph do visit(u) + for i in 0..g.len() { + visit(i, g, &mut vis, &mut l, &mut x, &mut t); + } + + let mut c = vec![0; size]; // used for component assignment + vis = vec![true; size]; //repurpose vis to mean 'unassigned' + + // Recursive subroutine 'assign': + fn assign(u: usize, root: usize, t: &Vec>, vis: &mut Vec, c: &mut Vec) { + if vis[u] { + vis[u] = false; + c[u] = root; + for &v in &t[u] { + assign(v, root, t, vis, c); + } + } + } + + // 3: For each element u of l in order, do assign(u, u) + for &u in &l { + if vis[u] { + assign(u, u, &t, &mut vis, &mut c); + } + + } + + c +} + +fn main() { + let mut g = vec![ + vec![1], + vec![2], + vec![0], + vec![1, 2, 4], + vec![3, 5], + vec![2, 6], + vec![5], + vec![4, 6, 7], + ]; + + let result = kosaraju(&mut g); + println!("{}", DisplayVec::new(result)); +} diff --git a/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy b/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy index 30c4fe6ab0..afa47b441f 100644 --- a/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy +++ b/Task/Kronecker-product-based-fractals/EasyLang/kronecker-product-based-fractals.easy @@ -18,17 +18,16 @@ func[][] krpow a[][] n . . return r[][] . -proc show p[][] . . - clear +proc show p[][] . + gclear n = len p[][] sc = 100 / n for r to n for c to n x = (c - 1) * sc y = (r - 1) * sc - move x y if p[r][c] = 1 - rect sc sc + grect x y sc sc . . . diff --git a/Task/Langtons-ant/EasyLang/langtons-ant.easy b/Task/Langtons-ant/EasyLang/langtons-ant.easy index 24011e0fa8..eefb6c822c 100644 --- a/Task/Langtons-ant/EasyLang/langtons-ant.easy +++ b/Task/Langtons-ant/EasyLang/langtons-ant.easy @@ -1,15 +1,12 @@ len f[] 100 * 100 -proc show . . - for y = 0 to 99 - for x = 0 to 99 - if f[y * 100 + x + 1] = 1 - move x y - rect 1 1 - . +proc show . + for y = 0 to 99 : for x = 0 to 99 + if f[y * 100 + x + 1] = 1 + grect x y 1 1 . . . -proc run x y dir . . +proc run x y dir . dx[] = [ 0 1 0 -1 ] dy[] = [ -1 0 1 0 ] while x >= 0 and x < 100 and y >= 0 and y < 100 diff --git a/Task/Largest-int-from-concatenated-ints/XPL0/largest-int-from-concatenated-ints.xpl0 b/Task/Largest-int-from-concatenated-ints/XPL0/largest-int-from-concatenated-ints.xpl0 new file mode 100644 index 0000000000..02634408ba --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/XPL0/largest-int-from-concatenated-ints.xpl0 @@ -0,0 +1,34 @@ +func Cat(A, B); \Concatenate integers A and B +int A, B, T; +[T:= B; +while T do + [A:= A*10; + T:= T/10; + ]; +return A+B; +]; + +proc CatSort(A, Len); \Sort array A by concatenating adjacent values +int A, Len; +int I, J, T, X, Y; +[for J:= Len-1 downto 0 do + for I:= 0 to J-1 do + [X:= Cat(A(I), A(I+1)); + Y:= Cat(A(I+1), A(I)); + if X > Y then + [T:= A(I); A(I):= A(I+1); A(I+1):= T]; + ]; +]; + +proc Largest(Ints, Len); \Show the largest int from concatenated ints +int Ints, Len; +int I; +[CatSort(Ints, Len); +for I:= Len-1 downto 0 do + IntOut(0, Ints(I)); +CrLf(0); +]; + +[Largest([1, 34, 3, 98, 9, 76, 45, 4], 8); + Largest([54, 546, 548, 60], 4); +] diff --git a/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy b/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy index b3697e1722..61f49ab4b2 100644 --- a/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy +++ b/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy @@ -1,21 +1,17 @@ global found dig[] . -proc test . . +proc test . for i to len dig[] n = n * 10 + dig[i] . for i to len dig[] - if n mod dig[i] <> 0 - return - . + if n mod dig[i] <> 0 : return . found = 1 print n . len use[] 9 -proc perm pos . . - if found = 1 - return - . +proc perm pos . + if found = 1 : return for i = 9 downto 1 dig[pos] = i if use[i] = 0 diff --git a/Task/Largest-proper-divisor-of-n/ALGOL-60/largest-proper-divisor-of-n.alg b/Task/Largest-proper-divisor-of-n/ALGOL-60/largest-proper-divisor-of-n.alg new file mode 100644 index 0000000000..585fbb17d0 --- /dev/null +++ b/Task/Largest-proper-divisor-of-n/ALGOL-60/largest-proper-divisor-of-n.alg @@ -0,0 +1,33 @@ +begin + +comment - return n mod m; +integer procedure mod(n, m); + value n, m; integer n, m; +begin + mod := n - entier(n/m) * m; +end; + +comment - return the largest proper divisor of n; +integer procedure lpd(n); + value n; integer n; +begin + integer i; + if n = 1 then + lpd := 1 + else + begin + i := n/2; + for i := i while mod(n,i) notequal 0 do + i := i - 1; + lpd := i; + end; +end; + +integer k; +for k := 1 step 1 until 100 do + begin + outinteger(1,lpd(k)); + if mod(k,10) = 0 then outstring(1,"\n"); + end; + +end diff --git a/Task/Last-Friday-of-each-month/EasyLang/last-friday-of-each-month.easy b/Task/Last-Friday-of-each-month/EasyLang/last-friday-of-each-month.easy index b2b086e459..d960680b34 100644 --- a/Task/Last-Friday-of-each-month/EasyLang/last-friday-of-each-month.easy +++ b/Task/Last-Friday-of-each-month/EasyLang/last-friday-of-each-month.easy @@ -1,17 +1,13 @@ -proc show y . . +proc show y . days[] = [ 31 28 31 30 31 30 31 31 30 31 30 31 ] days[2] += if y mod 4 = 0 and (y mod 100 <> 0 or y mod 400 = 0) w = y * 365 + (y - 1) div 4 - (y - 1) div 100 + (y - 1) div 400 + 6 for m = 1 to 12 w = (w + days[m]) mod 7 m$ = m - if m < 10 - m$ = 0 & m - . + if m < 10 : m$ = 0 & m h = 5 - if w < 5 - h = -2 - . + if w < 5 : h = -2 print y & "-" & m$ & "-" & days[m] + h - w . . diff --git a/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy b/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy index fc6da4d81f..8223b76a5e 100644 --- a/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy +++ b/Task/Last-letter-first-letter/EasyLang/last-letter-first-letter.easy @@ -1,13 +1,11 @@ repeat s$ = input until s$ = "" - for n$ in strsplit s$ " " - pok$[] &= n$ - . + for n$ in strsplit s$ " " : pok$[] &= n$ . # chain$[] = [ ] -proc search lng . . +proc search lng . if lng > len chain$[] chain$[] = [ ] for j to lng diff --git a/Task/Last-letter-first-letter/FreeBASIC/last-letter-first-letter.basic b/Task/Last-letter-first-letter/FreeBASIC/last-letter-first-letter.basic new file mode 100644 index 0000000000..f057a39137 --- /dev/null +++ b/Task/Last-letter-first-letter/FreeBASIC/last-letter-first-letter.basic @@ -0,0 +1,55 @@ +Dim As String names(69) = { "audino", "bagon", "baltoy", "banette", _ +"bidoof", "braviary", "bronzor", "carracosta", "charmeleon", _ +"cresselia", "croagunk", "darmanitan", "deino", "emboar", _ +"emolga", "exeggcute", "gabite", "girafarig", "gulpin", _ +"haxorus", "heatmor", "heatran", "ivysaur", "jellicent", _ +"jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", _ +"loudred", "lumineon", "lunatone", "machamp", "magnezone", _ +"mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", _ +"pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", _ +"registeel", "relicanth", "remoraid", "rufflet", "sableye", _ +"scolipede", "scrafty", "seaking", "sealeo", "silcoon", _ +"simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", _ +"trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", _ +"wailord", "wartortle", "whismur", "wingull", "yamask" } + +Dim As String strbegin = "gabite" +Dim As String strdir = "first" + +Dim As String ready() +ready(0) = strbegin +Print strbegin + +Dim As String strc +Dim As Boolean flag +Dim As Integer i, n, foundIndex + +Do + strc = Right(strbegin, 1) + foundIndex = -1 + For i = 0 To Ubound(names) + If Left(names(i), 1) = strc Then + flag = True + For n = 0 To Ubound(ready) + If names(i) = ready(n) Then + flag = False + Exit For + End If + Next + If flag Then + foundIndex = i + Exit For + End If + End If + Next + + If foundIndex = -1 Then Exit Do + + Redim Preserve ready(Ubound(ready) + 1) + ready(Ubound(ready)) = names(foundIndex) + Print names(foundIndex) + strbegin = names(foundIndex) + strdir = Iif(strdir = "first", "last", "first") +Loop + +Sleep diff --git a/Task/Last-letter-first-letter/XPL0/last-letter-first-letter.xpl0 b/Task/Last-letter-first-letter/XPL0/last-letter-first-letter.xpl0 new file mode 100644 index 0000000000..98ed114789 --- /dev/null +++ b/Task/Last-letter-first-letter/XPL0/last-letter-first-letter.xpl0 @@ -0,0 +1,68 @@ +string 0; \use zero-terminated strings +def NamesLen = 70; +int Path(NamesLen), MaxPath(NamesLen); +int Names, MaxPathEnd, MaxPathCnt; + +proc Search(Depth); \Depth-first search for longest chain of Names +int Depth; +char Name; +int LastLetter, FirstLetter, Len, I, J, T; +[Path(Depth):= Names(Depth); \record path being searched +Name:= Names(Depth); \get last letter of Name at Depth +Len:= 0; while Name(Len) do Len:= Len+1; +LastLetter:= Name(Len-1); +Depth:= Depth+1; + +for I:= Depth to NamesLen-1 do \for remaining Names not in path... + [Name:= Names(I); \get first letter of a Name + FirstLetter:= Name(0); + if FirstLetter = LastLetter then \there is a next Name + [if Depth > MaxPathEnd then \record this longer path + [for J:= 0 to Depth-1 do \copy path already searched + MaxPath(J):= Path(J); + MaxPath(Depth):= Name; \append next Name + MaxPathEnd:= Depth; + MaxPathCnt:= 1; \reset counter for this longer path + ] + else if Depth = MaxPathEnd then + MaxPathCnt:= MaxPathCnt+1; \count instances of longest path + + T:= Names(Depth); Names(Depth):= Names(I); Names(I):= T; \swap Names + Search(Depth); \recurse + Names(I):= Names(Depth); Names(Depth):= T; \restore order + ]; + ]; +]; + +int I, T; +[Names:= [ \Pokemon names + "audino", "bagon", "baltoy", "banette", "bidoof", + "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", + "croagunk", "darmanitan", "deino", "emboar", "emolga", + "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", + "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", + "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", + "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", + "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", + "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", + "relicanth", "remoraid", "rufflet", "sableye", "scolipede", + "scrafty", "seaking", "sealeo", "silcoon", "simisear", + "snivy", "snorlax", "spoink", "starly", "tirtouga", + "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", + "wailord", "wartortle", "whismur", "wingull", "yamask"]; +MaxPathEnd:= 0; MaxPathCnt:= 0; + +for I:= 0 to NamesLen-1 do + [T:= Names(0); Names(0):= Names(I); Names(I):= T; \swap out pending Name + Search(0); + Names(I):= Names(0); Names(0):= T; \restore Names order + ]; +Text(0, "Maximum path length : "); IntOut(0, MaxPathEnd+1); CrLf(0); +Text(0, "Paths of that length: "); IntOut(0, MaxPathCnt); CrLf(0); +Text(0, "Example path of that length:"); +for I:= 0 to MaxPathEnd do + [if rem(I/5) then ChOut(0, ^ ) else CrLf(0); + Text(0, MaxPath(I)); + ]; +CrLf(0); +] diff --git a/Task/Latin-Squares-in-reduced-form/Rust/latin-squares-in-reduced-form.rs b/Task/Latin-Squares-in-reduced-form/Rust/latin-squares-in-reduced-form.rs new file mode 100644 index 0000000000..cd4999d953 --- /dev/null +++ b/Task/Latin-Squares-in-reduced-form/Rust/latin-squares-in-reduced-form.rs @@ -0,0 +1,144 @@ +use std::io; + +type Matrix = Vec>; + +fn dlist(n: usize, start: usize) -> Matrix { + let mut a: Vec = (0..n).collect(); + a.swap(0, start - 1); // 1-based to 0-based index, swap start-1 with first element + + let first = a[1]; + + let mut result = Vec::new(); + + fn recurse(a: &mut Vec, last: usize, first: usize, result: &mut Matrix) { + if last == 1 { + // Test if it's a derangement + for j in 1..a.len() { + if a[j] == j { + return; // Not deranged + } + } + + // Convert back to 1-based indexing + result.push(a.iter().map(|&v| v + 1).collect()); + return; + } + + for i in (1..=last).rev() { + a.swap(i, last); + recurse(a, last - 1, first, result); + a.swap(i, last); + } + } + + let mut a_clone = a.clone(); + recurse(&mut a_clone, n - 1, first, &mut result); + result +} + +fn print_square(latin: &Matrix) { + for row in latin { + print!("["); + let len = row.len(); + for (i, val) in row.iter().enumerate() { + if i != len - 1 { + print!("{}, ", val); + } else { + print!("{}", val); + } + } + println!("]"); + } + println!(); +} + +fn reduced_latin_squares(n: usize, echo: bool) -> u64 { + if n == 0 { + if echo { + println!("[]"); + } + return 0; + } else if n == 1 { + if echo { + println!("[1]"); + } + return 1; + } + + // Initialize the Latin square with indices + let mut rlatin: Matrix = (0..n) + .map(|i| (0..n).map(|j| j + 1).collect::>()) + .collect(); + + // First row is 1 to n + for j in 0..n { + rlatin[0][j] = j + 1; + } + + let mut count: u64 = 0; + + fn recurse( + i: usize, + rlatin: &mut Matrix, + n: usize, + echo: bool, + count: &mut u64, + ) { + let rows = dlist(n, i); + + for row in &rows { + rlatin[i - 1] = row.clone(); + + let mut conflict = false; + + for k in 0..i - 1 { + for j in 1..n { + if rlatin[k][j] == rlatin[i - 1][j] { + conflict = true; + break; + } + } + if conflict { + break; + } + } + + if !conflict { + if i < n { + recurse(i + 1, rlatin, n, echo, count); + } else { + *count += 1; + if echo { + print_square(rlatin); + } + } + } + } + } + + recurse(2, &mut rlatin, n, echo, &mut count); + count +} + +fn factorial(n: u64) -> u64 { + (1..=n).product() +} + +fn main() { + println!("The four reduced Latin squares of order 4 are:\n"); + reduced_latin_squares(4, true); + + println!("The size of the set of reduced Latin squares for the following orders"); + println!("and hence the total number of Latin squares of these orders are:\n"); + + for n in 1..7 { + let size = reduced_latin_squares(n, false); + let fact_n_1 = factorial((n - 1) as u64); + let total = fact_n_1 * fact_n_1 * n as u64 * size; + + println!( + "Order {}: Size {} x {}! x {}! => Total {}", + n, size, n, n - 1, total + ); + } +} diff --git a/Task/Latin-Squares-in-reduced-form/Zig/latin-squares-in-reduced-form.zig b/Task/Latin-Squares-in-reduced-form/Zig/latin-squares-in-reduced-form.zig new file mode 100644 index 0000000000..38101bc8e1 --- /dev/null +++ b/Task/Latin-Squares-in-reduced-form/Zig/latin-squares-in-reduced-form.zig @@ -0,0 +1,207 @@ +const std = @import("std"); + +const Matrix = std.ArrayList(std.ArrayList(usize)); + +fn dlist(n: usize, start: usize, allocator: std.mem.Allocator) !Matrix { + var a = std.ArrayList(usize).init(allocator); + defer a.deinit(); + + try a.resize(n); + for (0..n) |index| { + a.items[index] = index; + } + + // 1-based to 0-based index, swap start-1 with first element + std.mem.swap(usize, &a.items[0], &a.items[start - 1]); + + const first = a.items[1]; + + var result = Matrix.init(allocator); + + const Context = struct { + a: *std.ArrayList(usize), + first: usize, + result: *Matrix, + allocator: std.mem.Allocator, + }; + + var context = Context{ + .a = &a, + .first = first, + .result = &result, + .allocator = allocator, + }; + + var a_clone = try a.clone(); + defer a_clone.deinit(); + + try recurse(&a_clone, n - 1, &context); + + return result; +} + +fn recurse(a: *std.ArrayList(usize), last: usize, context: anytype) !void { + if (last == 1) { + // Test if it's a derangement + for (1..a.items.len) |j| { + if (a.items[j] == j) { + return; // Not deranged + } + } + + // Convert back to 1-based indexing + var row = std.ArrayList(usize).init(context.allocator); + for (a.items) |v| { + try row.append(v + 1); + } + try context.result.append(row); + return; + } + + var i: usize = last; + while (i >= 1) : (i -= 1) { + std.mem.swap(usize, &a.items[i], &a.items[last]); + try recurse(a, last - 1, context); + std.mem.swap(usize, &a.items[i], &a.items[last]); + } +} + +fn printSquare(latin: Matrix) void { + for (latin.items) |row| { + std.debug.print("[", .{}); + for (row.items, 0..) |val, i| { + if (i != row.items.len - 1) { + std.debug.print("{}, ", .{val}); + } else { + std.debug.print("{}", .{val}); + } + } + std.debug.print("]\n", .{}); + } + std.debug.print("\n", .{}); +} + +fn reducedLatinSquares(n: usize, echo: bool, allocator: std.mem.Allocator) !u64 { + if (n == 0) { + if (echo) { + std.debug.print("[]\n", .{}); + } + return 0; + } else if (n == 1) { + if (echo) { + std.debug.print("[1]\n", .{}); + } + return 1; + } + + // Initialize the Latin square with indices + var rlatin = Matrix.init(allocator); + defer { + for (rlatin.items) |row| { + row.deinit(); + } + rlatin.deinit(); + } + + for (0..n) |_| { + var row = std.ArrayList(usize).init(allocator); + for (0..n) |j| { + try row.append(j + 1); + } + try rlatin.append(row); + } + + // First row is 1 to n (already initialized above) + + var count: u64 = 0; + + const Context = struct { + rlatin: *Matrix, + n: usize, + echo: bool, + count: *u64, + allocator: std.mem.Allocator, + }; + + var context = Context{ + .rlatin = &rlatin, + .n = n, + .echo = echo, + .count = &count, + .allocator = allocator, + }; + + try recurseLatinSquare(2, &context); + + return count; +} + +fn recurseLatinSquare(i: usize, context: anytype) !void { + var rows = try dlist(context.n, i, context.allocator); + defer { + for (rows.items) |row| { + row.deinit(); + } + rows.deinit(); + } + + for (rows.items) |row| { + // Copy row to rlatin[i-1] + for (row.items, 0..) |val, j| { + context.rlatin.items[i - 1].items[j] = val; + } + + var conflict = false; + + outer: for (0..i - 1) |k| { + for (1..context.n) |j| { + if (context.rlatin.items[k].items[j] == context.rlatin.items[i - 1].items[j]) { + conflict = true; + break :outer; + } + } + } + + if (!conflict) { + if (i < context.n) { + try recurseLatinSquare(i + 1, context); + } else { + context.count.* += 1; + if (context.echo) { + printSquare(context.rlatin.*); + } + } + } + } +} + +fn factorial(n: u64) u64 { + var result: u64 = 1; + var i: u64 = 1; + while (i <= n) : (i += 1) { + result *= i; + } + return result; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + std.debug.print("The four reduced Latin squares of order 4 are:\n\n", .{}); + _ = try reducedLatinSquares(4, true, allocator); + + std.debug.print("The size of the set of reduced Latin squares for the following orders\n", .{}); + std.debug.print("and hence the total number of Latin squares of these orders are:\n\n", .{}); + + for (1..6) |n| { + const size = try reducedLatinSquares(n, false, allocator); + const fact_n_1 = factorial(@as(u64, n - 1)); + const total = fact_n_1 * fact_n_1 * @as(u64, n) * size; + + std.debug.print("Order {}: Size {} x {}! x {}! => Total {}\n", .{ + n, size, n, n - 1, total + }); + } +} diff --git a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx index 7dde8a8542..eaad27631c 100644 --- a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx +++ b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-1.rexx @@ -1,15 +1,18 @@ -Main: +-- 22 Mar 2025 include Settings -say version; say 'Legendre Prime counter (no memoization)'; say + +say 'LEGENDRE PRIME COUNTER (NO MEMOIZATION)' +say version +say numeric digits 10 do n = 0 to 9 call Time('r') - a = 10**n; p = pi(a) + a = 10**n; p = Pie(a) say '10^'n Right(p,9) Format(Time('e'),3,3)'s' end exit -Pi: +Pie: procedure expose prim. arg xx if xx < 3 then @@ -22,7 +25,7 @@ procedure expose prim. arg xx,yy if yy < 2 then return xx-(xx%2)*(yy=1) -p = prim.prime.yy +p = prim.yy if xx <= p then return 1 return Phi(xx,yy-1)-Phi(xx%p,yy-1) diff --git a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx index 3ca9b25734..d724a28756 100644 --- a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx +++ b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-2.rexx @@ -1,15 +1,18 @@ -Main: +-- 22 Mar 2025 include Settings -say version; say 'Legendre Prime counter (with memoization)'; say + +say 'LEGENDRE PRIME COUNTER (WITH MEMOIZATION)' +say version +say numeric digits 10 do n = 0 to 9 call Time('r') - a = 10**n; p = Pi(a) + a = 10**n; p = Pie(a) say '10^'n Right(p,9) Format(Time('e'),3,3)'s' end exit -Pi: +Pie: procedure expose prim. work. arg xx if xx < 3 then @@ -23,7 +26,7 @@ procedure expose prim. work. arg xx,yy if yy < 2 then return xx-(xx%2)*(yy=1) -p = prim.prime.yy +p = prim.yy if xx <= p then return 1 if work.xx.yy > 0 then diff --git a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx index 44c20aa6e8..a3f94a0f28 100644 --- a/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx +++ b/Task/Legendre-prime-counting-function/REXX/legendre-prime-counting-function-3.rexx @@ -1,6 +1,9 @@ -Main: +-- 22 Mar 2025 include Settings -say version; say 'Legendre Prime counter (sieving)'; say + +say 'LEGENDRE PRIME COUNTER (SIEVING)' +say version +say numeric digits 10 do n = 0 to 8 call Time('r') diff --git a/Task/Leonardo-numbers/ERRE/leonardo-numbers.erre b/Task/Leonardo-numbers/ERRE/leonardo-numbers.erre new file mode 100644 index 0000000000..94ae064f41 --- /dev/null +++ b/Task/Leonardo-numbers/ERRE/leonardo-numbers.erre @@ -0,0 +1,24 @@ +PROGRAM LEONARDO_NUMBERS + +PROCEDURE PRINT_LEONARDO_NUMS(L0,L1,SUM,LMT%,WHAT$) + ! Print the numbers + PRINT(WHAT$;" (";L0;",";L1;",";SUM;"):") + IF LMT%>=1 THEN + PRINT(L0;) + END IF + IF LMT%>=2 THEN + PRINT(L1;) + END IF + FOR I%=3 TO LMT% DO + PRINT(L0+L1+SUM;) + TMP=L0 + L0=L1 + L1=TMP+L1+SUM + END FOR + PRINT +END PROCEDURE + +BEGIN + PRINT_LEONARDO_NUMS(1,1,1,25,"Leonardo numbers") + PRINT_LEONARDO_NUMS(0,1,0,25,"Fibonacci numbers") +END PROGRAM diff --git a/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy b/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy index c8752fcccf..ded0a5e511 100644 --- a/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy +++ b/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy @@ -1,4 +1,4 @@ -proc leonardo L0 L1 add . . +proc leonardo L0 L1 add . print "L0:" & L0 & " L1:" & L1 & " add:" & add write L0 & " " write L1 & " " diff --git a/Task/Letter-frequency/Nu/letter-frequency.nu b/Task/Letter-frequency/Nu/letter-frequency-1.nu similarity index 100% rename from Task/Letter-frequency/Nu/letter-frequency.nu rename to Task/Letter-frequency/Nu/letter-frequency-1.nu diff --git a/Task/Letter-frequency/Nu/letter-frequency-2.nu b/Task/Letter-frequency/Nu/letter-frequency-2.nu new file mode 100644 index 0000000000..19de718065 --- /dev/null +++ b/Task/Letter-frequency/Nu/letter-frequency-2.nu @@ -0,0 +1 @@ +open 'unixdict.txt' | split chars | where $it =~ '^\pL$' | histogram diff --git a/Task/Levenshtein-distance-Alignment/EasyLang/levenshtein-distance-alignment.easy b/Task/Levenshtein-distance-Alignment/EasyLang/levenshtein-distance-alignment.easy index 8be5ec6616..58c29d7c22 100644 --- a/Task/Levenshtein-distance-Alignment/EasyLang/levenshtein-distance-alignment.easy +++ b/Task/Levenshtein-distance-Alignment/EasyLang/levenshtein-distance-alignment.easy @@ -1,29 +1,23 @@ global dparr[] dpcols . -proc dpnew a b . . +proc dpnew a b . len dparr[] a * b dpcols = b . func dp r c . return dparr[r * dpcols + c + 1] . -proc dps r c v . . +proc dps r c v . dparr[r * dpcols + c + 1] = v . -proc align a$ b$ . ar$ br$ . +proc align a$ b$ &ar$ &br$ . dpnew (len a$ + 1) (len b$ + 1) - for i = 1 to len a$ - dps i 0 i - . - for j = 0 to len b$ - dps 0 j j - . - for i = 1 to len a$ - for j = 1 to len b$ - if substr a$ i 1 = substr b$ j 1 - dps i j dp (i - 1) (j - 1) - else - dps i j lower (lower dp (i - 1) j dp i (j - 1)) dp (i - 1) (j - 1) + 1 - . + for i = 1 to len a$ : dps i 0 i + for j = 0 to len b$ : dps 0 j j + for i = 1 to len a$ : for j = 1 to len b$ + if substr a$ i 1 = substr b$ j 1 + dps i j dp (i - 1) (j - 1) + else + dps i j lower (lower dp (i - 1) j dp i (j - 1)) dp (i - 1) (j - 1) + 1 . . ar$ = "" ; br$ = "" diff --git a/Task/Levenshtein-distance/ANSI-BASIC/levenshtein-distance.basic b/Task/Levenshtein-distance/ANSI-BASIC/levenshtein-distance.basic new file mode 100644 index 0000000000..0c779254b8 --- /dev/null +++ b/Task/Levenshtein-distance/ANSI-BASIC/levenshtein-distance.basic @@ -0,0 +1,29 @@ +100 REM Levenshtein distance +110 DECLARE EXTERNAL FUNCTION LevDist +120 PRINT "The Levenshtein distance..." +130 PRINT "between 'kitten' and 'sitting' is"; LevDist("kitten","sitting") +140 PRINT "between 'rosettacode' and 'raisethysword' is"; LevDist("rosettacode","raisethysword") +150 END +160 EXTERNAL FUNCTION LevDist(S$, T$) +170 LET N = LEN(T$) +180 LET M = LEN(S$) +190 DIM D(0 TO 20, 0 TO 20) +200 REM Both T$ and S$ must not be longer than 20 chars +210 REM Some impementations allow DIM D(0 TO M, 0 TO N), but it is not standard. +220 FOR I = 0 TO M +230 LET D(I, 0) = I +240 NEXT I +250 FOR J = 0 TO N +260 LET D(0, J) = J +270 NEXT J +280 FOR J = 1 TO N +290 FOR I = 1 TO M +300 IF S$(I:I) = T$(J:J) THEN +310 LET D(I, J) = D(I - 1, J - 1) +320 ELSE +330 LET D(I, J) = MIN(D(I - 1, J) + 1, MIN(D(I, J - 1) + 1, D(I - 1, J - 1) + 1)) +340 END IF +350 NEXT I +360 NEXT J +370 LET LevDist = D(M, N) +380 END FUNCTION diff --git a/Task/Levenshtein-distance/Applesoft-BASIC/levenshtein-distance.basic b/Task/Levenshtein-distance/Applesoft-BASIC/levenshtein-distance.basic new file mode 100644 index 0000000000..b649fa4458 --- /dev/null +++ b/Task/Levenshtein-distance/Applesoft-BASIC/levenshtein-distance.basic @@ -0,0 +1,18 @@ + 10 PRINT "THE LEVENSHTEIN DISTANCE..." + 20 CLEAR :S$ = "KITTEN":T$ = "SITTING": GOSUB 100 + 30 PRINT "BETWEEN '"S$"' AND '"T$"' IS "LD + 40 CLEAR :S$ = "ROSETTACODE":T$ = "RAISETHYSWORD": GOSUB 100 + 50 PRINT "BETWEEN '"S$"' AND '"T$"' IS "LD + 60 END + + REM CALCULATE LEVENSHTEIN DISTANCE (LD) GIVEN S$ T$ + 100 LET M = LEN (S$):N = LEN (T$): DIM D(M,N): FOR I = 0 TO M:D(I,0) = I: NEXT : FOR J = 0 TO N:D(0,J) = J: NEXT + 110 FOR J = 1 TO N + 120 FOR I = 1 TO M + 130 IF MID$ (S$,I,1) = MID$ (T$,J,1) THEN D(I,J) = D(I - 1,J - 1): NEXT I,J:LD = D(M,N): RETURN + 140 LET R = NOT (D(I,J - 1) + 1 < D(I - 1,J - 1) + 1):MIN = D(I - R,J - 1) + 1 + 150 LET R = MIN: IF D(I - 1,J) + 1 < MI THEN R = D(I - 1,J) + 1 + 160 LET D(I,J) = R + 170 NEXT I,J + 180 LET LD = D(M,N) + 190 RETURN diff --git a/Task/Levenshtein-distance/Ballerina/levenshtein-distance.ballerina b/Task/Levenshtein-distance/Ballerina/levenshtein-distance.ballerina new file mode 100644 index 0000000000..4b0c04e474 --- /dev/null +++ b/Task/Levenshtein-distance/Ballerina/levenshtein-distance.ballerina @@ -0,0 +1,31 @@ +import ballerina/io; + +function levenshtein(string s, string t) returns int { + int ls = s.length(); + int lt = t.length(); + int[][] d = []; + foreach int i in 0...ls { + d[i] = []; + d[i].setLength(lt + 1); + d[i][0] = i; + } + foreach int j in 0...lt { d[0][j] = j; } + foreach int j in 1...lt { + foreach int i in 1...ls { + if s[i - 1] == t[j - 1] { + d[i][j] = d[i - 1][j - 1]; + } else { + int min = d[i - 1][j]; + if d[i][j - 1] < min { min = d[i][j - 1]; } + if d[i - 1][j - 1] < min { min = d[i - 1][j - 1]; } + d[i][j] = min + 1; + } + } + } + return d[ls][lt]; +} + +public function main() { + io:println(levenshtein("kitten", "sitting")); + io:println(levenshtein("rosettacode", "raisethysword")); +} diff --git a/Task/Levenshtein-distance/Free-Pascal-Lazarus/levenshtein-distance.pas b/Task/Levenshtein-distance/Free-Pascal-Lazarus/levenshtein-distance.pas new file mode 100644 index 0000000000..9423111539 --- /dev/null +++ b/Task/Levenshtein-distance/Free-Pascal-Lazarus/levenshtein-distance.pas @@ -0,0 +1,40 @@ +program LevenshteinDistanceDemo(Output); + +uses + Math; + + function LevenshteinDistance(S, T: string): longint; + var + D: array of array of integer; + I, J, N, M: integer; + begin + N := Length(T); + M := Length(S); + SetLength(D, M + 1, N + 1); + + for I := 0 to M do + D[I, 0] := I; + for J := 0 to N do + D[0, J] := J; + for J := 1 to N do + for I := 1 to M do + if S[I] = T[J] then + D[I, J] := D[I - 1, J - 1] + else + D[I, J] := Min(D[I - 1, J] + 1, Min(D[I, J - 1] + 1, D[I - 1, J - 1] + 1)); + LevenshteinDistance := D[M, N]; + end; + +var + S1, S2: string; + +begin + S1 := 'kitten'; + S2 := 'sitting'; + WriteLn('The Levenshtein distance between "', S1, '" and "', + S2, '" is: ', LevenshteinDistance(S1, S2)); + S1 := 'rosettacode'; + S2 := 'raisethysword'; + WriteLn('The Levenshtein distance between "', S1, '" and "', + S2, '" is: ', LevenshteinDistance(S1, S2)); +end. diff --git a/Task/Levenshtein-distance/GW-BASIC/levenshtein-distance.basic b/Task/Levenshtein-distance/GW-BASIC/levenshtein-distance.basic new file mode 100644 index 0000000000..972b9b5c2e --- /dev/null +++ b/Task/Levenshtein-distance/GW-BASIC/levenshtein-distance.basic @@ -0,0 +1,28 @@ +10 REM Levenshtein distance +20 PRINT "The Levenshtein distance..." +30 S$ = "kitten": T$ = "sitting": GOSUB 1000 +40 PRINT "between '"; S$; "' and '"; T$; "' is"; LEV.DIST +50 S$ = "rosettacode": T$ = "raisethysword": GOSUB 1000 +60 PRINT "between '"; S$; "' and '"; T$; "' is"; LEV.DIST +70 END +1000 REM ** Calculate distance for strings S$ and T$ +1010 M = LEN(S$): N = LEN(T$) +1020 DIM D(M, N) +1030 FOR I = 0 TO M +1040 D(I, 0) = I +1050 NEXT I +1060 FOR J = 0 TO N +1070 D(0, J) = J +1080 NEXT J +1090 FOR J = 1 TO N +1100 FOR I = 1 TO M +1110 IF MID$(S$, I, 1) <> MID$(T$, J, 1) THEN 1140 +1120 D(I, J) = D(I - 1, J - 1) +1130 GOTO 1160 +1140 IF D(I, J - 1) + 1 < D(I - 1, J - 1) + 1 THEN MIN = D(I, J - 1) + 1 ELSE MIN = D(I - 1, J - 1) + 1 +1150 IF D(I - 1, J) + 1 < MIN THEN D(I, J) = D(I - 1, J) + 1 ELSE D(I, J) = MIN +1160 NEXT I +1170 NEXT J +1180 LEV.DIST = D(M, N) +1190 ERASE D +1200 RETURN diff --git a/Task/Levenshtein-distance/Nascom-BASIC/levenshtein-distance.basic b/Task/Levenshtein-distance/Nascom-BASIC/levenshtein-distance.basic new file mode 100644 index 0000000000..f29c501939 --- /dev/null +++ b/Task/Levenshtein-distance/Nascom-BASIC/levenshtein-distance.basic @@ -0,0 +1,33 @@ +10 REM Levenshtein distance +20 ML=20:REM Max. length +30 DIM D(ML,ML) +40 PRINT "The Levenshtein distance..." +50 S$="kitten":T$="sitting" +60 GOSUB 1000 +70 PRINT "between '";S$;"' and '";T$;"' is";DS +80 S$="rosettacode":T$="raisethysword" +90 GOSUB 1000 +100 PRINT "between '";S$;"' and '";T$;"' is";DS +110 END +1000 REM ** Calculate dist. for S$ and T$ +1010 M=LEN(S$):N=LEN(T$) +1020 FOR I=0 TO M +1030 D(I,0)=I +1040 NEXT I +1050 FOR J=0 TO N +1060 D(0,J)=J +1070 NEXT J +1080 FOR J=1 TO N +1090 FOR I=1 TO M +1100 IF MID$(S$,I,1)<>MID$(T$,J,1) THEN 1120 +1110 D(I,J)=D(I-1,J-1):GOTO 1180 +1120 IF D(I,J-1)+1 0 l -= 1 if t mod 2 = 1 @@ -18,13 +18,13 @@ proc show t l . . t = t div 2 . . -proc list n . . +proc list n . for i = offs[n] to offs[n + 1] - 1 show trees[i] n * 2 print "" . . -proc assemble n t sl pos rem . . +proc assemble n t sl pos rem . if rem = 0 append t return @@ -34,26 +34,20 @@ proc assemble n t sl pos rem . . pos = offs[sl] elif pos >= offs[sl + 1] sl -= 1 - if sl = 0 - return - . + if sl = 0 : return pos = offs[sl] . h = bitor bitshift t (2 * sl) trees[pos] assemble n h sl pos rem - sl assemble n t sl pos + 1 rem . -proc make n . . - if offs[n + 1] <> 0 - return - . - if n > 0 - make n - 1 - . +proc make n . + if offs[n + 1] <> 0 : return + if n > 0 : make n - 1 assemble n 0 n - 1 offs[n - 1] n - 1 offs[n + 1] = len trees[] . -proc test n . . +proc test n . append 0 make n print "Number of " & n & "-trees: " & offs[n + 1] - offs[n] diff --git a/Task/Literals-Floating-point/REXX/literals-floating-point-1.rexx b/Task/Literals-Floating-point/REXX/literals-floating-point-1.rexx deleted file mode 100644 index d4a63f46dc..0000000000 --- a/Task/Literals-Floating-point/REXX/literals-floating-point-1.rexx +++ /dev/null @@ -1,6 +0,0 @@ -something = 127 -something = '127' /*exactly the same as the above. */ -something = 1.27e2 -something = 1.27E2 -something = 1.27E+2 -something = ' + 0001.27e+00000000000000002 ' diff --git a/Task/Literals-Floating-point/REXX/literals-floating-point-2.rexx b/Task/Literals-Floating-point/REXX/literals-floating-point-2.rexx deleted file mode 100644 index adaeedff96..0000000000 --- a/Task/Literals-Floating-point/REXX/literals-floating-point-2.rexx +++ /dev/null @@ -1,3 +0,0 @@ -something = -.00478 -say something -say format(something,,,,0) diff --git a/Task/Literals-Floating-point/REXX/literals-floating-point.rexx b/Task/Literals-Floating-point/REXX/literals-floating-point.rexx new file mode 100644 index 0000000000..df07d9fa3e --- /dev/null +++ b/Task/Literals-Floating-point/REXX/literals-floating-point.rexx @@ -0,0 +1,52 @@ +-- 19 May 2025 +include Settings + +say 'LITERALS FLOATING POINT' +say version +say +say 'The standard precision (numeric digits) is 9' +say +say 'Assigments are as string...' +a = 666666.666666; say a +say 'until you do a calculation' +say a/1 +say +say 'Default Format...' +say 'Leading and trailing zeroes may be Left out' +l = 13 +a = 123.456; say Left(a,l) '=' a/1 +a = '123.456'; say Left(a,l) '=' a/1 +a = "123.456"; say Left(a,l) '=' a/1 +a = 0123.4560; say Left(a,l) '=' a/1 +a = 12345.6E-2; say Left(a,l) '=' a/1 +a = 123.456E0; say Left(a,l) '=' a/1 +a = 1.23456E+2; say Left(a,l) '=' a/1 +a = ' 01.23456E+02 '; say Left(a,l) '=' a/1 +say +say 'Force standard, scientific or engineering Format...' +l = 11 +a = 7; b = '1/'a; c = 1/a +say Left('1/'||a,l) '=' c +say Left('Standard',l) '=' Std(c) +say Left('Scientific',l) '=' Sci(c) +say Left('Engineering',l) '=' Eng(c) +a = 7000000; b = '1/'a; c = 1/a +say Left('1/'||a,l) '=' c +say Left('Standard',l) '=' Std(c) +say Left('Scientific',l) '=' Sci(c) +say Left('Engineering',l) '=' Eng(c) +a = 7 +say Left(a,l) '=' a +say Left('Standard',l) '=' Std(a) +say Left('Scientific',l) '=' Sci(a) +say Left('Engineering',l) '=' Eng(a) +a = 70000000000 +say Left(a,l) '=' a+0 +say Left('Standard',l) '=' Std(a) +say Left('Scientific',l) '=' Sci(a) +say Left('Engineering',l) '=' Eng(a) +exit + +include Functions +include Helper +include Abend diff --git a/Task/Literals-Integer/JavaScript/literals-integer.js b/Task/Literals-Integer/JavaScript/literals-integer.js index bbf26dfea5..9809f8dc0a 100644 --- a/Task/Literals-Integer/JavaScript/literals-integer.js +++ b/Task/Literals-Integer/JavaScript/literals-integer.js @@ -1,3 +1,3 @@ -if ( 727 == 0x2d7 && - 727 == 01327 ) - window.alert("true"); +727 === 0x2d7 // true +727 === 0o1327 // true +727 === 0b1011010111 // true diff --git a/Task/Literals-Integer/REXX/literals-integer.rexx b/Task/Literals-Integer/REXX/literals-integer.rexx index 8dc30648c3..bbdf185f1b 100644 --- a/Task/Literals-Integer/REXX/literals-integer.rexx +++ b/Task/Literals-Integer/REXX/literals-integer.rexx @@ -1,31 +1,53 @@ -/*REXX pgm displays an integer (expressed in the pgm as a literal) in different bases*/ - /*────────── expressing decimal numbers ──────────*/ -ddd = 123 /*a decimal number (expressed as a literal). */ -ddd = '123' /*this is exactly the same as above. */ -ddd = "123" /*this is exactly the same as above also. */ - /*────────── expressing hexadecimal numbers ──────*/ -hhh = '7b'x /*a value, expressed as a hexadecimal literal. */ -hhh = '7B'x /* (same as above) using a capital "B". */ -hhh = '7B'X /* (same as above) using a capital "X". */ -cow = 'dead beef'x /*another value, with a blank for the eyeballs.*/ -cow = 'de ad be ef'x /* (same as above) with blanks for the eyeballs.*/ - /*────────── expressing binary numbers ───────────*/ -bbb = '1111011'b /*a value, expressed as a binary literal. */ -bbb = '01111011'b /* (same as above) with a full 8 binary digits. */ -bbb = '0111 1011'b /* (same as above) with a blank for the eyeballs.*/ +-- 19 May 2025 +include Settings -say ' base 10=' ddd -say ' base 2=' x2b( d2x( ddd ) ) -say ' base 16=' d2x( ddd ) -say ' base 256=' d2c( ddd ) /*the output displayed is ASCII (or maybe EBCDIC).*/ +say 'LITERALS INTEGER' +say version +say +say 'The standard precision (numeric digits) is 9' +say +say 'Assigments are as string...' +a = 6666666666666; say a +say 'until you do a calculation' +say a/1 +say +say 'Decimal...' +l = 8 +a = 0123; say left(a,l) '=' a/1 +a = 123; say left(a,l) '=' a/1 +a = 123.; say left(a,l) '=' a/1 +a = 123.0; say left(a,l) '=' a/1 +a = "123"; say left(a,l) '=' a/1 +a = '123'; say left(a,l) '=' a/1 +a = ' 123 '; say left(a,l) '=' a/1 +a = +123; say left(a,l) '=' a/1 +a = '+123'; say left(a,l) '=' a/1 +a = ' + 123 '; say left(a,l) '=' a/1 +a = .0123E4; say left(a,l) '=' a/1 +a = 12.3E1; say left(a,l) '=' a/1 +a = '12.3e1'; say left(a,l) '=' a/1 +a = 1230E-1; say left(a,l) '=' a/1 +a = 1230E-01; say left(a,l) '=' a/1 +say +say 'Hexadecimal...' +say 'Blanks to separate words and bytes are allowed' +l = 14 +say left("'5a'x",l) '=' '5a'x +say left("'5A'x",l) '=' '5A'x +say left("'5A'X",l) '=' '5A'X +say left("'50515253'X",l) '=' '50515253'X +say left("'5051 5253'X",l) '=' '5051 5253'X +say left("'50 51 52 53'X",l) '=' '50 51 52 53'X +say +say 'Binary...' +say 'Blanks to separate words, bytes and nibbles are allowed' +l = 42 +say left("'1010000010100010101001001010011'B",l) '=' '1010000010100010101001001010011'B +say left("'01010000010100010101001001010011'B",l) '=' '01010000010100010101001001010011'B +say left("'0101000001010001 0101001001010011'B",l) '=' '0101000001010001 0101001001010011'B +say left("'01010000 01010001 01010010 01010011'B",l) '=' '01010000 01010001 01010010 01010011'B +say left("'0101 0000 0101 0001 0101 0010 0101 0011'B",l) '=' '0101 0000 0101 0001 0101 0010 0101 0011'B +exit -thingy1= +123 /*╔══════════════════════════════════════════════╗*/ -thingy2= '+123' /*║ All of the THINGYs variables aren't strictly ║*/ -thingy3= ' 123' /*║ (exactly) equal to the DDD variable, but ║*/ -thingy4= 123. /*║ they do compare numerically equal. When ║*/ -thingy5= 12.3e+1 /*║ compared numerically, numbers are rounded to ║*/ -thingy6= 1230e-1 /*║ the current setting of NUMERIC DIGITS. The ║*/ -thingy7= 1230E-0001 /*║ default for (decimal) NUMERIC DIGITS is 9 ║*/ -thingy8= ' + 123 ' /*╚══════════════════════════════════════════════╝*/ - - /*stick a fork in it, we're all done. */ +include Helper +include Abend diff --git a/Task/Logical-operations/EasyLang/logical-operations.easy b/Task/Logical-operations/EasyLang/logical-operations.easy index 535a6d5b4a..399eb9b09a 100644 --- a/Task/Logical-operations/EasyLang/logical-operations.easy +++ b/Task/Logical-operations/EasyLang/logical-operations.easy @@ -1,4 +1,4 @@ -proc logic a b . . +proc logic a b . if a = 1 and b = 1 r1 = 1 . diff --git a/Task/Long-primes/EasyLang/long-primes.easy b/Task/Long-primes/EasyLang/long-primes.easy index c6faa26dc8..8c507a955a 100644 --- a/Task/Long-primes/EasyLang/long-primes.easy +++ b/Task/Long-primes/EasyLang/long-primes.easy @@ -1,18 +1,14 @@ fastfunc isprim num . - if num mod 2 = 0 and num > 2 - return 0 - . + if num mod 2 = 0 and num > 2 : return 0 i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 . prim = 2 -proc nextprim . . +proc nextprim . repeat prim += 1 until isprim prim = 1 @@ -47,8 +43,6 @@ repeat limit *= 2 . until limit > 32000 - if period prim = prim - 1 - cnt += 1 - . + if period prim = prim - 1 : cnt += 1 nextprim . diff --git a/Task/Long-primes/REXX/long-primes-1.rexx b/Task/Long-primes/REXX/long-primes-1.rexx deleted file mode 100644 index 8453b4c779..0000000000 --- a/Task/Long-primes/REXX/long-primes-1.rexx +++ /dev/null @@ -1,22 +0,0 @@ -/*REXX pgm calculates/displays base ten long primes (AKA golden primes, proper primes,*/ -/*───────────────────── maximal period primes, long period primes, full reptend primes).*/ -parse arg a /*obtain optional argument from the CL.*/ -if a='' | a="," then a= '500 -500 -1000 -2000 -4000 -8000 -16000' , /*Not specified? */ - '-32000 -64000 -128000 -512000 -1024000' /*Then use default*/ - do k=1 for words(a); H=word(a, k) /*step through the list of high limits.*/ - neg= H<1 /*used as an indicator to display count*/ - H= abs(H) /*obtain the absolute value of H. */ - $= /*the list of long primes (so far). */ - do j=7 to H by 2 /*start with 7, just use odd integers.*/ - if .len(j) + 1 \== j then iterate /*Period length wrong? Then skip it. */ - $=$ j /*add the long prime to the $ list.*/ - end /*j*/ - say - if neg then do; say 'number of long primes ≤ ' H " is: " words($); end - else do; say 'list of long primes ≤ ' H":"; say strip($); end - end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.len: procedure; parse arg x; r=1; do x; r= 10*r // x; end /*x*/ - rr=r; do p=1 until r==rr; r= 10*r // x; end /*p*/ - return p diff --git a/Task/Long-primes/REXX/long-primes-2.rexx b/Task/Long-primes/REXX/long-primes-2.rexx deleted file mode 100644 index cc8e17cd7a..0000000000 --- a/Task/Long-primes/REXX/long-primes-2.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/*REXX pgm calculates/displays base ten long primes (AKA golden primes, proper primes,*/ -/*───────────────────── maximal period primes, long period primes, full reptend primes).*/ -parse arg a /*obtain optional argument from the CL.*/ -if a='' | a="," then a= '500 -500 -1000 -2000 -4000 -8000 -16000' , /*Not specified? */ - '-32000 -64000 -128000 -512000 -1024000' /*Then use default*/ - do k=1 for words(a); H=word(a, k) /*step through the list of high limits.*/ - neg= H<1 /*used as an indicator to display count*/ - H= abs(H) /*obtain the absolute value of H. */ - $= /*the list of long primes (so far). */ - do j=7 to H by 2; parse var j '' -1 _ /*start with 7, just use odd integers.*/ - if _==5 then iterate /*last digit a five? Then not a prime.*/ - if j// 3==0 then iterate /*Is divisible by 3? " " " " */ - if j\==11 then if j//11==0 then iterate /* " " " 11? " " " " */ - if j\==13 then if j//13==0 then iterate /* " " " 13? " " " " */ - if j\==17 then if j//17==0 then iterate /* " " " 17? " " " " */ - if j\==19 then if j//19==0 then iterate /* " " " 19? " " " " */ - if .len(j) + 1 \== j then iterate /*Period length wrong? Then skip it. */ - $=$ j /*add the long prime to the $ list.*/ - end /*j*/ - say - if neg then do; say 'number of long primes ≤ ' H " is: " words($); end - else do; say 'list of long primes ≤ ' H":"; say strip($); end - end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.len: procedure; parse arg x; r=1; do x; r= 10*r // x; end /*x*/ - rr=r; do p=1 until r==rr; r= 10*r // x; end /*p*/ - return p diff --git a/Task/Long-primes/REXX/long-primes-3.rexx b/Task/Long-primes/REXX/long-primes-3.rexx deleted file mode 100644 index 8474e700c4..0000000000 --- a/Task/Long-primes/REXX/long-primes-3.rexx +++ /dev/null @@ -1,38 +0,0 @@ -/*REXX pgm calculates/displays base ten long primes (AKA golden primes, proper primes,*/ -/*───────────────────── maximal period primes, long period primes, full reptend primes).*/ -parse arg a /*obtain optional argument from the CL.*/ -if a='' | a="," then a= '500 -500 -1000 -2000 -4000 -8000 -16000' , /*Not specified? */ - '-32000 -64000 -128000 -512000 -1024000' /*Then use default*/ -m=0; aa= words(a) /* [↑] two list types of low primes. */ - do j=1 for aa; m= max(m, abs(word(a, j))) /*find the maximum argument in the list*/ - end /*j*/ -call genP /*go and generate some primes. */ - do k=1 for aa; H= word(a, k) /*step through the list of high limits.*/ - neg= H<1 /*used as an indicator to display count*/ - H= abs(H) /*obtain the absolute value of H. */ - $= /*the list of long primes (so far). */ - do j=7 to H by 2 - if \@.j then iterate /*Is J not a prime? Then skip it. */ - if .len(j) + 1 \== j then iterate /*Period length wrong? " " " */ - $= $ j /*add the long prime to the $ list.*/ - end /*j*/ /* [↑] some pretty weak prime testing.*/ - say - if neg then say 'number of long primes ≤ ' H " is: " words($) - else do; say 'list of long primes ≤ ' H":"; say strip($); end - end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; !.=0; !.1=2; !.2=3; !.3=5; !.4=7; !.5=11 - #= 5 /*the number of primes (so far). */ - do g=!.#+2 by 2 until g>=m /*gen enough primes to satisfy max A. */ - if @.g\==0 then iterate /*Is it not a prime? Then skip it. */ - do d=2 until !.d**2>g /*only divide up to square root of X. */ - if g//!.d==0 then iterate g /*Divisible? Then skip this integer. */ - end /*d*/ /* [↓] a spanking new prime was found.*/ - #= #+1 @.g= 1; !.#= g /*bump P counter; assign P, add to P's.*/ - end /*g*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.len: procedure; parse arg x; r=1; do x; r= 10*r // x; end /*x*/ - rr=r; do p=1 until r==rr; r= 10*r // x; end /*p*/ - return p diff --git a/Task/Long-primes/REXX/long-primes.rexx b/Task/Long-primes/REXX/long-primes.rexx new file mode 100644 index 0000000000..4270b9f8ab --- /dev/null +++ b/Task/Long-primes/REXX/long-primes.rexx @@ -0,0 +1,56 @@ +-- 8 May 2025 +include Settings + +say 'LONG PRIMES' +say version +say +call GetPrimes 70000 +call LPbelow500 +call NumberOfLP +exit + +GetPrimes: +call Time('r') +arg x +say 'Get primes up to' x +numeric digits 10 +call Primes(x) +say Format(Time('e'),,3) 'seconds'; say +return + +LPbelow500: +call Time('r') +say 'Long primes < 500' +p = 0 +do i = 1 to prim.0 until p > 500 + p = prim.i + if p-qperiod(1 p) = 1 then + call Charout ,p' ' +end +say +say Format(Time('e'),,3) 'seconds'; say +return + +NumberOfLP: +call Time('r') +say 'Number of long primes up to' +t = '500 1000 2000 4000 8000 16000 32000 64000 0' +w = 1; a = Word(t,1); n = 0 +do i = 1 to prim.0 while a > 0 + p = prim.i + if p > a then do + say Right(a,5) Right(n,4) + w = w+1; a = Word(t,w) + end + if p-qperiodinv(p) = 1 then do + n = n+1 + end +end +say Format(Time('e'),,3) 'seconds'; say +return + +include Functions +include Sequences +include Rational +include Constants +include Abend diff --git a/Task/Longest-string-challenge/C-sharp/longest-string-challenge.cs b/Task/Longest-string-challenge/C-sharp/longest-string-challenge.cs new file mode 100644 index 0000000000..23351f5c8c --- /dev/null +++ b/Task/Longest-string-challenge/C-sharp/longest-string-challenge.cs @@ -0,0 +1,36 @@ +string[] input = ["a", "bb", "ccc", "ddd", "ee", "f", "ggg"]; + +#pragma warning disable CA1860 // Avoid using 'Enumerable.Any()' extension method + +string longest = ""; +string template = ""; + +foreach (string line in input) +{ + string t = template; + string l = line; + + foreach (var _ in line) + { + if (t.Any()) + t = t[..^1]; + else + { + longest = ""; + template = line; + break; + } + + if (l.Any()) + l = l[..^1]; + } + + if (!t.Any()) + longest += line; // string concatenation, not addition +} + +while (longest.Any()) +{ + Console.WriteLine(longest[..template.Length]); + longest = longest[template.Length..]; +} diff --git a/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy b/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy index 94c6316232..9d91e1f128 100644 --- a/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy +++ b/Task/Look-and-say-sequence/EasyLang/look-and-say-sequence.easy @@ -1,4 +1,4 @@ -proc lookandsay . a$ . +proc lookandsay &a$ . c = 1 p$ = substr a$ 1 1 for i = 2 to len a$ diff --git a/Task/Look-and-say-sequence/MAD/look-and-say-sequence.mad b/Task/Look-and-say-sequence/MAD/look-and-say-sequence.mad new file mode 100644 index 0000000000..09a9de2f77 --- /dev/null +++ b/Task/Look-and-say-sequence/MAD/look-and-say-sequence.mad @@ -0,0 +1,36 @@ + NORMAL MODE IS INTEGER + + INTERNAL FUNCTION(XX) + ENTRY TO LOKSAY. + X = XX + + THROUGH CTDGT, FOR K = 1, 0, K.G.X +CTDGT K = K*10 + K = K/10 + R = 0 + DS = 0 + +GROUP D = X/K + X = X-K*D + K = K/10 + + WHENEVER DS.NE.D + WHENEVER DS.NE.0, R = R*100 + N*10 + DS + N = 1 + DS = D + OTHERWISE + N = N+1 + END OF CONDITIONAL + + WHENEVER K.NE.0, TRANSFER TO GROUP + R = R*100 + N*10 + DS + FUNCTION RETURN R + END OF FUNCTION + + VECTOR VALUES FMT = $I20*$ + L = 1 + THROUGH STEP, FOR I=1, 1, I.GE.10 + PRINT FORMAT FMT, L +STEP L = LOKSAY.(L) + + END OF PROGRAM diff --git a/Task/Look-and-say-sequence/Python/look-and-say-sequence-5.py b/Task/Look-and-say-sequence/Python/look-and-say-sequence-5.py new file mode 100644 index 0000000000..a48a7400bc --- /dev/null +++ b/Task/Look-and-say-sequence/Python/look-and-say-sequence-5.py @@ -0,0 +1,9 @@ +from more_itertools import groupby_transform, take, ilen + +def lookandsay(seq = "1"): + yield seq + while True: + yield (seq := "".join(f"{count}{n}" for n, count in + groupby_transform(seq, reducefunc = ilen))) + +list(take(5, lookandsay())) diff --git a/Task/Look-and-say-sequence/SETL/look-and-say-sequence.setl b/Task/Look-and-say-sequence/SETL/look-and-say-sequence.setl index 31c8cbd598..3dbfe302cf 100644 --- a/Task/Look-and-say-sequence/SETL/look-and-say-sequence.setl +++ b/Task/Look-and-say-sequence/SETL/look-and-say-sequence.setl @@ -6,18 +6,10 @@ program looksay; end loop; proc looksay(s); - loop for c in s do; - if cur /= c then - if count /= om then - r +:= count + cur; - end if; - cur := c; - count := 1; - else - count +:= 1; - end if; + loop init r := ""; while s /= "" do + p := span(s, s(1)); + r +:= str(#p) + p(1); end loop; - r +:= count + cur; return r; end proc; end looksay; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Ballerina/loop-over-multiple-arrays-simultaneously.ballerina b/Task/Loop-over-multiple-arrays-simultaneously/Ballerina/loop-over-multiple-arrays-simultaneously.ballerina new file mode 100644 index 0000000000..62f6f4661e --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Ballerina/loop-over-multiple-arrays-simultaneously.ballerina @@ -0,0 +1,10 @@ +import ballerina/io; + +public function main() { + var a1 = ["a", "b", "c"]; + var a2 = ["A", "B", "C"]; + var a3 = [1, 2, 3]; + foreach int i in a3 { + io:println(a1[i-1], a2[i-1], i); + } +} diff --git a/Task/Loops-Break/ALGOL-68/loops-break.alg b/Task/Loops-Break/ALGOL-68/loops-break.alg index 7a05d01147..739def288e 100644 --- a/Task/Loops-Break/ALGOL-68/loops-break.alg +++ b/Task/Loops-Break/ALGOL-68/loops-break.alg @@ -1,13 +1,11 @@ -main: ( - INT a, b; - INT seed := 4; # chosen by a fair dice roll, guaranteed to be random c.f. http://xkcd.com/221/ # - # first random; # +#main# +( WHILE - a := ENTIER (next random(seed) * 20); + INT a = ENTIER (random * 20); print((a)); - # WHILE # NOT (a = 10) DO - b := ENTIER (next random(seed) * 20); - print((b, new line)) + a /= 10 + DO + print((ENTIER (random * 20), new line)) OD; print(new line) ) diff --git a/Task/Loops-Break/Ballerina/loops-break.ballerina b/Task/Loops-Break/Ballerina/loops-break.ballerina new file mode 100644 index 0000000000..c28087524c --- /dev/null +++ b/Task/Loops-Break/Ballerina/loops-break.ballerina @@ -0,0 +1,12 @@ +import ballerina/io; +import ballerina/random; + +public function main() returns error? { + while true { + int n = check random:createIntInRange(0, 20); + io:println(n); + if n == 10 { break; } + n = check random:createIntInRange(0, 20); + io:println(n); + } +} diff --git a/Task/Loops-Break/Uxntal/loops-break.uxnatl b/Task/Loops-Break/Uxntal/loops-break.uxnatl new file mode 100644 index 0000000000..97d03ed8e7 --- /dev/null +++ b/Task/Loops-Break/Uxntal/loops-break.uxnatl @@ -0,0 +1,62 @@ +%newline { [ LIT2 0a -Console/write ] DEO } +%tab { [ LIT2 09 -Console/write ] DEO } +%MOD ( a b -- a%b ) { DIVk MUL SUB } + +|18 @Console/write +|c0 @DateTime/year $2 &month $1 &day $1 &hour $1 &minute $1 &second $1 + +|100 + +rand/init + +&loop + rand/0:13 DUP print/dec tab + #0a NEQ ?{ + newline !&break } + rand/0:13 print/dec newline + !&loop + +&break + +BRK + +@print/dec ( dec -- ) + DUP #64 DIV /num + DUP #0a DIV /num + ( >> ) + +@print/num_ ( num -- ) + #0a DIVk MUL SUB [ LIT "0 ] ADD .Console/write DEO + JMP2r + +@print/num ( num -- ) + DUP ?&num_ + POP + JMP2r + +@rand/init ( -- ) + [ LIT2 00 -DateTime/second ] DEI + [ LIT2 00 -DateTime/minute ] DEI #60 SFT2 EOR2 + [ LIT2 00 -DateTime/hour ] DEI #c0 SFT2 EOR2 ,&x STR2 + [ LIT2 00 -DateTime/hour ] DEI #04 SFT2 + [ LIT2 00 -DateTime/day ] DEI #10 SFT2 EOR2 + [ LIT2 00 -DateTime/month ] DEI #60 SFT2 EOR2 + .DateTime/year DEI2 #a0 SFT2 EOR2 ,&y STR2 + JMP2r + +@rand/short ( -- number* ) + [ LIT2 &x $2 ] + DUP2 #50 SFT2 EOR2 + DUP2 #03 SFT2 EOR2 + [ LIT2 &y $2 ] DUP2 ,&x STR2 + DUP2 #01 SFT2 EOR2 EOR2 + ,&y STR2k POP + JMP2r + +@rand/byte ( -- number ) + /short AND + JMP2r + +@rand/0:13 ( -- U[0,13] ) + /byte #14 MOD + JMP2r diff --git a/Task/Loops-Continue/Ballerina/loops-continue.ballerina b/Task/Loops-Continue/Ballerina/loops-continue.ballerina new file mode 100644 index 0000000000..1dc361e882 --- /dev/null +++ b/Task/Loops-Continue/Ballerina/loops-continue.ballerina @@ -0,0 +1,12 @@ +import ballerina/io; + +public function main() { + foreach int i in 1...10 { + io:print(i); + if i % 5 == 0 { + io:println(); + continue; + } + io:print(", "); + } +} diff --git a/Task/Loops-Continue/Uxntal/loops-continue.uxnatl b/Task/Loops-Continue/Uxntal/loops-continue.uxnatl new file mode 100644 index 0000000000..8e43bba3fe --- /dev/null +++ b/Task/Loops-Continue/Uxntal/loops-continue.uxnatl @@ -0,0 +1,31 @@ +%newline { [ LIT2 0a -Console/write ] DEO } +%comma { [ LIT2 ", -Console/write ] DEO } +%space { [ LIT2 20 -Console/write ] DEO } +%MOD ( a b -- a%b ) { DIVk MUL SUB } + +|18 @Console/write + +|100 + +#0b01 +&loop + DUP print-dec + DUP #05 MOD ?{ + newline !&continue } + comma space + &continue + INC GTHk ?&loop +POP2 +BRK + +@print-dec ( dec -- ) + DUP #64 DIV print-num/try + DUP #0a DIV print-num/try + ( >> ) + +@print-num ( num -- ) + #0a DIVk MUL SUB [ LIT "0 ] ADD .Console/write DEO + JMP2r + &try ( num -- ) + DUP ?print-num + POP JMP2r diff --git a/Task/Loops-Do-while/Ballerina/loops-do-while-1.ballerina b/Task/Loops-Do-while/Ballerina/loops-do-while-1.ballerina new file mode 100644 index 0000000000..aee89996e5 --- /dev/null +++ b/Task/Loops-Do-while/Ballerina/loops-do-while-1.ballerina @@ -0,0 +1,10 @@ +import ballerina/io; + +public function main() { + int v = 0; + while true { + v += 1; + io:println(v); + if v % 6 == 0 { break; } + } +} diff --git a/Task/Loops-Do-while/Ballerina/loops-do-while-2.ballerina b/Task/Loops-Do-while/Ballerina/loops-do-while-2.ballerina new file mode 100644 index 0000000000..9ebeed7b64 --- /dev/null +++ b/Task/Loops-Do-while/Ballerina/loops-do-while-2.ballerina @@ -0,0 +1,11 @@ +import ballerina/io; + +public function main() { + int value = 0; + boolean ok = true; + while ok { + value += 1; + io:println(value); + ok = value % 6 != 0; + } +} diff --git a/Task/Loops-Do-while/SETL/loops-do-while.setl b/Task/Loops-Do-while/SETL/loops-do-while.setl new file mode 100644 index 0000000000..dcbd441f9d --- /dev/null +++ b/Task/Loops-Do-while/SETL/loops-do-while.setl @@ -0,0 +1,7 @@ +program dowhile; + value := 0; + loop until value mod 6 = 0 do + print(value); + value +:= 1; + end loop; +end program; diff --git a/Task/Loops-Do-while/Uxntal/loops-do-while.uxnatl b/Task/Loops-Do-while/Uxntal/loops-do-while.uxnatl new file mode 100644 index 0000000000..9ca41f10d4 --- /dev/null +++ b/Task/Loops-Do-while/Uxntal/loops-do-while.uxnatl @@ -0,0 +1,22 @@ +%newline { [ LIT2 0a -Console/write ] DEO } +%MOD ( a b -- a%b ) { DIVk MUL SUB } + +|18 @Console/write + +|100 + +#00 +&do-while + INC DUP print-hex/byte newline + DUP #06 MOD ?&do-while +POP + +BRK + +@print-hex ( short* -- ) + SWP /byte + &byte ( byte -- ) + DUP #04 SFT /nibble + &nibble ( byte -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD #18 DEO + JMP2r diff --git a/Task/Loops-Downward-for/Ballerina/loops-downward-for.ballerina b/Task/Loops-Downward-for/Ballerina/loops-downward-for.ballerina new file mode 100644 index 0000000000..d77ab4f583 --- /dev/null +++ b/Task/Loops-Downward-for/Ballerina/loops-downward-for.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + foreach int i in int:range(10, -1, -1) { + io:print(i, " "); + } + io:println(); +} diff --git a/Task/Loops-For-with-a-specified-step/Ballerina/loops-for-with-a-specified-step.ballerina b/Task/Loops-For-with-a-specified-step/Ballerina/loops-for-with-a-specified-step.ballerina new file mode 100644 index 0000000000..c2cda1fdc8 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Ballerina/loops-for-with-a-specified-step.ballerina @@ -0,0 +1,9 @@ +import ballerina/io; + +public function main() { + // print odd numbers from 1 to 9 + foreach int i in int:range(1, 10, 2) { + io:print(i, " "); + } + io:println(); +} diff --git a/Task/Loops-For-with-a-specified-step/Uxntal/loops-for-with-a-specified-step.uxnatl b/Task/Loops-For-with-a-specified-step/Uxntal/loops-for-with-a-specified-step.uxnatl new file mode 100644 index 0000000000..fdc85b0850 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Uxntal/loops-for-with-a-specified-step.uxnatl @@ -0,0 +1,20 @@ +%newline { [ LIT2 0a -Console/write ] DEO } + +|18 @Console/write + +|100 + +#1000 [ LITr 02 ] +&loop + DUP print/byte newline + STHkr ADD GTHk ?&loop +POP2 POPr + +BRK + +@print/byte ( byte -- ) + DUP #04 SFT /nibble + + &nibble ( byte -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO + JMP2r diff --git a/Task/Loops-For/Ballerina/loops-for.ballerina b/Task/Loops-For/Ballerina/loops-for.ballerina new file mode 100644 index 0000000000..b8319f1317 --- /dev/null +++ b/Task/Loops-For/Ballerina/loops-for.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + foreach int i in 1...5 { + foreach int j in 1...i { io:print("*"); } + io:println(); + } +} diff --git a/Task/Loops-For/Excel/loops-for.excel b/Task/Loops-For/Excel/loops-for.excel new file mode 100644 index 0000000000..49ea28564d --- /dev/null +++ b/Task/Loops-For/Excel/loops-for.excel @@ -0,0 +1,9 @@ +=REDUCE( + "", SEQUENCE(6), + LAMBDA(outer, i, + VSTACK( + outer, + REDUCE("", SEQUENCE(i), LAMBDA(inner, j, inner & "*")) + ) + ) + ) diff --git a/Task/Loops-For/M2000-Interpreter/loops-for-1.m2000 b/Task/Loops-For/M2000-Interpreter/loops-for-1.m2000 new file mode 100644 index 0000000000..00945aafb2 --- /dev/null +++ b/Task/Loops-For/M2000-Interpreter/loops-for-1.m2000 @@ -0,0 +1,4 @@ +MODULE check { +FOR I=1 TO 5:FOR I=I to 1:?"*";:NEXT:?:NEXT +} +check diff --git a/Task/Loops-For/M2000-Interpreter/loops-for-2.m2000 b/Task/Loops-For/M2000-Interpreter/loops-for-2.m2000 new file mode 100644 index 0000000000..1603228d5e --- /dev/null +++ b/Task/Loops-For/M2000-Interpreter/loops-for-2.m2000 @@ -0,0 +1,17 @@ +module check { + For i=1 to 5 + For j=1 to i + Print "*"; + Next j + Print + Next i + Print "End1" + For i=1 to 5 { + For j=1 to i { + Print "*"; + } + Print + } + Print "End2" +} +check diff --git a/Task/Loops-For/M2000-Interpreter/loops-for.m2000 b/Task/Loops-For/M2000-Interpreter/loops-for.m2000 deleted file mode 100644 index 7d6e060448..0000000000 --- a/Task/Loops-For/M2000-Interpreter/loops-for.m2000 +++ /dev/null @@ -1,14 +0,0 @@ -For i=1 to 5 - For j=1 to i - Print "*"; - Next j - Print -Next i -Print "End1" -For i=1 to 5 { - For j=1 to i { - Print "*"; - } - Print -} -Print "End2" diff --git a/Task/Loops-Foreach/Ballerina/loops-foreach.ballerina b/Task/Loops-Foreach/Ballerina/loops-foreach.ballerina new file mode 100644 index 0000000000..be3ab5ec8e --- /dev/null +++ b/Task/Loops-Foreach/Ballerina/loops-foreach.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + string[] birds = ["Swan", "Eagle", "Wren"]; + foreach string bird in birds { + io:println(bird); + } +} diff --git a/Task/Loops-Foreach/Uxntal/loops-foreach.uxnatl b/Task/Loops-Foreach/Uxntal/loops-foreach.uxnatl new file mode 100644 index 0000000000..85cd75c797 --- /dev/null +++ b/Task/Loops-Foreach/Uxntal/loops-foreach.uxnatl @@ -0,0 +1,44 @@ +%newline { [ LIT2 0a -Console/write ] DEO } +%space { [ LIT2 20 -Console/write ] DEO } + +|18 @Console/write + +|100 + +@on-reset ( -> ) + ;array ;print-element foreach + newline + + ;array ;double foreach + + ;array ;print-element foreach + newline + + BRK + +@double ( addr* -- addr* ) + STH2k LDAk + DUP ADD + STH2r STA + JMP2r + +@print-element ( addr* -- addr* ) + LDAk print-byte space + JMP2r + +@print-byte ( byte -- ) + DUP #04 SFT /nibble + &nibble ( byte -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD #18 DEO + JMP2r + +@foreach ( bytes* fn* -- bytes* ) + STH2 + LDA2k SWP2 INC2 INC2 + &l ( -- ) + STH2kr JSR2 + INC2 GTH2k ?&l + POP2r POP2 POP2 + JMP2r + +@array ={ 00 01 02 02 04 } diff --git a/Task/Loops-Increment-loop-index-within-loop-body/ALGOL-60/loops-increment-loop-index-within-loop-body.alg b/Task/Loops-Increment-loop-index-within-loop-body/ALGOL-60/loops-increment-loop-index-within-loop-body.alg new file mode 100644 index 0000000000..4e936cae74 --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/ALGOL-60/loops-increment-loop-index-within-loop-body.alg @@ -0,0 +1,43 @@ +begin + +boolean procedure isprime(n); +value n; integer n; +begin + if n < 2 then + isprime := false + else if n = entier(n / 2) * 2 then + isprime := (n = 2) + else + begin + comment - check odd divisors up to sqrt(n); + integer i, limit; + boolean divisible; + i := 3; + limit := entier(sqrt(n)); + divisible := false; + for i := i while i <= limit and not divisible do + begin + if entier(n / i) * i = n then + divisible := true; + i := i + 2 + end; + isprime := not divisible; + end; +end; + +integer i, count; + +count := 0; +for i := 42, i + 1 while count < 26 do + begin + if isprime(i) then + begin + count := count + 1; + outinteger(1,count); + outinteger(1,i); + i := i + (i - 1); + outstring(1,"\n"); + end; + end; + +end diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Ballerina/loops-increment-loop-index-within-loop-body.ballerina b/Task/Loops-Increment-loop-index-within-loop-body/Ballerina/loops-increment-loop-index-within-loop-body.ballerina new file mode 100644 index 0000000000..242fca7859 --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/Ballerina/loops-increment-loop-index-within-loop-body.ballerina @@ -0,0 +1,39 @@ +import ballerina/io; + +function isPrime(int n) returns boolean { + if n < 2 { return false; } + if n % 2 == 0 { return n == 2; } + if n % 3 == 0 { return n == 3; } + int d = 5; + while d * d <= n { + if n % d == 0 { return false; } + d += 2; + if n % d == 0 { return false; } + d += 4; + } + return true; +} + +function commatize(int n) returns string { + string s = n.toString(); + if n < 0 { s = s.substring(1); } + int le = s.length(); + foreach int i in int:range(le - 3, 0, -3) { + s = s.substring(0, i) + "," + s.substring(i); + } + if n >= 0 { return s; } + return "-" + s; +} + +public function main() { + int c = 0; + int i = 42; + while c < 42 { + if isPrime(i) { + c += 1; + io:println(commatize(c).padStart(2), ": ", commatize(i).padStart(18)); + i = 2 * i - 1; + } + i += 1; + } +} diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon b/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon new file mode 100644 index 0000000000..225a4cef48 --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon @@ -0,0 +1,40 @@ +procedure main() + I_START := 42 + LIMIT := I_START + + i := I_START + n := 0 + until n = LIMIT do { + if is_prime(i) then { + n +:= 1 + write(right(n,2),": ",comma_string(i)) + i +:= i + } else + i +:= 1 + } +end + +procedure is_prime(n) + if n < 2 then fail + if n%2 = 0 then return n = 2 + if n%3 = 0 then return n = 3 + d := 5 + while d*d <= n do { + if n%d = 0 then fail + d +:= 2 + if n%d = 0 then fail + d +:= 4 + } + return n +end + +procedure comma_string(n) + s := "" + n ? { + tab(0) + while s := "," || move(-3) || s + if pos(1) then s := s[2:0] + else s := tab(1) || s + } + return s +end diff --git a/Task/Loops-Increment-loop-index-within-loop-body/S-BASIC/loops-increment-loop-index-within-loop-body.basic b/Task/Loops-Increment-loop-index-within-loop-body/S-BASIC/loops-increment-loop-index-within-loop-body.basic new file mode 100644 index 0000000000..0638a054ae --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/S-BASIC/loops-increment-loop-index-within-loop-body.basic @@ -0,0 +1,41 @@ +$lines + +$constant FALSE = 0 +$constant TRUE = 0FFFFH + +rem - return n mod m +function mod(n, m = integer) = integer +end = n - m * (n / m) + +rem - return true if n is prime, otherwise false +function isprime(n = integer) = integer + var i, limit, result = integer + if n = 2 then + result = TRUE + else if (n < 2) or (mod(n,2) = 0) then + result = FALSE + else + begin + limit = int(sqr(n)) + i = 3 + while (i <= limit) and (mod(n, i) <> 0) do + i = i + 2 + result = not (i <= limit) + end +end = result + +var i, count = integer +count = 0 +for i = 42 to 32760 + if isprime(i) then + begin + count = count + 1 + print using "## ##,###"; count; i + if count >= 10 then + i = 32760 + else + i = i + (i - 1) + end +next i + +end diff --git a/Task/Loops-Increment-loop-index-within-loop-body/SETL/loops-increment-loop-index-within-loop-body.setl b/Task/Loops-Increment-loop-index-within-loop-body/SETL/loops-increment-loop-index-within-loop-body.setl new file mode 100644 index 0000000000..53e7fbebff --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/SETL/loops-increment-loop-index-within-loop-body.setl @@ -0,0 +1,29 @@ +program primes42; + loop + init n := 42; p := 0; + step n +:= 1; + until p = 42 do + if prime(n) then + print(lpad(str(p +:= 1), 2) + ": " + lpad(commatize(n), 20)); + n +:= n; + end if; + end loop; + + proc prime(n); + if n<=4 then return n in [2,3]; end if; + if n mod 2=0 or n mod 3=0 then return False; end if; + loop init d := 5; while d*d <= n do + if n mod d=0 then return false; end if; + d +:= 2; + if n mod d=0 then return false; end if; + d +:= 4; + end loop; + return True; + end proc; + + proc commatize(n); + if n<1000 then return str n; end if; + p := "00" + str(n mod 1000); + return commatize(n div 1000) + "," + p(#p-2..#p); + end proc; +end program; diff --git a/Task/Loops-Infinite/8080-Assembly/loops-infinite.8080 b/Task/Loops-Infinite/8080-Assembly/loops-infinite.8080 new file mode 100644 index 0000000000..bb674eb167 --- /dev/null +++ b/Task/Loops-Infinite/8080-Assembly/loops-infinite.8080 @@ -0,0 +1,7 @@ +puts equ 9 + org 100h +spam: mvi c,puts + lxi d,msg + call 5 + jmp spam +msg: db 'SPAM',13,10,'$' diff --git a/Task/Loops-Infinite/APL/loops-infinite.apl b/Task/Loops-Infinite/APL/loops-infinite.apl new file mode 100644 index 0000000000..31386930a9 --- /dev/null +++ b/Task/Loops-Infinite/APL/loops-infinite.apl @@ -0,0 +1 @@ +{⎕←'SPAM'}⍣(0⍨)'' diff --git a/Task/Loops-Infinite/Ballerina/loops-infinite.ballerina b/Task/Loops-Infinite/Ballerina/loops-infinite.ballerina new file mode 100644 index 0000000000..76181e3d77 --- /dev/null +++ b/Task/Loops-Infinite/Ballerina/loops-infinite.ballerina @@ -0,0 +1,7 @@ +import ballerina/io; + +public function main() { + while true { + io:println("SPAM"); + } +} diff --git a/Task/Loops-Infinite/J/loops-infinite-1.j b/Task/Loops-Infinite/J/loops-infinite-1.j index 22a89d8a2f..5cac1e6adc 100644 --- a/Task/Loops-Infinite/J/loops-infinite-1.j +++ b/Task/Loops-Infinite/J/loops-infinite-1.j @@ -1 +1 @@ - ]F.(echo@'SPAM')0 +echo@'SPAM'F.] '' diff --git a/Task/Loops-Infinite/J/loops-infinite-2.j b/Task/Loops-Infinite/J/loops-infinite-2.j index 2c906353a0..3cadb11b3c 100644 --- a/Task/Loops-Infinite/J/loops-infinite-2.j +++ b/Task/Loops-Infinite/J/loops-infinite-2.j @@ -1 +1 @@ -smoutput bind 'SPAM'^:1e99 '' +echo@'SPAM'^:1e99 '' diff --git a/Task/Loops-Infinite/J/loops-infinite-3.j b/Task/Loops-Infinite/J/loops-infinite-3.j new file mode 100644 index 0000000000..ea7c71c2b1 --- /dev/null +++ b/Task/Loops-Infinite/J/loops-infinite-3.j @@ -0,0 +1 @@ +echo@'SPAM'^:1:^:_. '' diff --git a/Task/Loops-Infinite/K/loops-infinite-1.k b/Task/Loops-Infinite/K/loops-infinite-1.k new file mode 100644 index 0000000000..d379f117c3 --- /dev/null +++ b/Task/Loops-Infinite/K/loops-infinite-1.k @@ -0,0 +1 @@ +{1}{`0:"SPAM"}/"" diff --git a/Task/Loops-Infinite/K/loops-infinite-2.k b/Task/Loops-Infinite/K/loops-infinite-2.k new file mode 100644 index 0000000000..8b7a637bd0 --- /dev/null +++ b/Task/Loops-Infinite/K/loops-infinite-2.k @@ -0,0 +1 @@ +while[1; `0:"SPAM"] diff --git a/Task/Loops-Infinite/K/loops-infinite.k b/Task/Loops-Infinite/K/loops-infinite.k deleted file mode 100644 index 6cdd8e40ea..0000000000 --- a/Task/Loops-Infinite/K/loops-infinite.k +++ /dev/null @@ -1 +0,0 @@ - while[1; `0:"SPAM\n"] diff --git a/Task/Loops-Infinite/Miranda/loops-infinite.miranda b/Task/Loops-Infinite/Miranda/loops-infinite.miranda new file mode 100644 index 0000000000..7490112585 --- /dev/null +++ b/Task/Loops-Infinite/Miranda/loops-infinite.miranda @@ -0,0 +1,2 @@ +main :: [sys_message] +main = repeat (Stdout "SPAM\n") diff --git a/Task/Loops-Infinite/Refal/loops-infinite.refal b/Task/Loops-Infinite/Refal/loops-infinite.refal new file mode 100644 index 0000000000..2bc91fdc6c --- /dev/null +++ b/Task/Loops-Infinite/Refal/loops-infinite.refal @@ -0,0 +1 @@ +$ENTRY Go { = ; }; diff --git a/Task/Loops-Infinite/SETL/loops-infinite.setl b/Task/Loops-Infinite/SETL/loops-infinite.setl new file mode 100644 index 0000000000..f54622e636 --- /dev/null +++ b/Task/Loops-Infinite/SETL/loops-infinite.setl @@ -0,0 +1,5 @@ +program spam; + loop do + print("SPAM"); + end loop; +end program; diff --git a/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl b/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl index 407bc40473..19d18d3e75 100644 --- a/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl +++ b/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl @@ -1,9 +1,11 @@ +|10 @Console/vector $2 &read $5 &type $1 &write $1 &error $1 + |0100 - &l ;SPAM !&l + &loop ;SPAM !&loop @ ( str* -- ) - &while ( -- ) - LDAk #18 DEO + &while + LDAk .Console/write DEO INC2 LDAk ?&while POP2 JMP2r diff --git a/Task/Loops-N-plus-one-half/Ballerina/loops-n-plus-one-half.ballerina b/Task/Loops-N-plus-one-half/Ballerina/loops-n-plus-one-half.ballerina new file mode 100644 index 0000000000..72a085465a --- /dev/null +++ b/Task/Loops-N-plus-one-half/Ballerina/loops-n-plus-one-half.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + foreach int i in 1...10 { + io:print(i); + io:print(i < 10 ? ", " : "\n"); + } +} diff --git a/Task/Loops-N-plus-one-half/Crystal/loops-n-plus-one-half.cr b/Task/Loops-N-plus-one-half/Crystal/loops-n-plus-one-half.cr new file mode 100644 index 0000000000..6e12440371 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Crystal/loops-n-plus-one-half.cr @@ -0,0 +1,6 @@ +(1..).each do |i| + print i + break if i == 10 + print ", " +end +puts diff --git a/Task/Loops-N-plus-one-half/Uxntal/loops-n-plus-one-half.uxnatl b/Task/Loops-N-plus-one-half/Uxntal/loops-n-plus-one-half.uxnatl new file mode 100644 index 0000000000..71a6de9be5 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Uxntal/loops-n-plus-one-half.uxnatl @@ -0,0 +1,34 @@ +%newline { [ LIT2 0a -Console/write ] DEO } +%comma { [ LIT2 ", -Console/write ] DEO } +%space { [ LIT2 20 -Console/write ] DEO } + +|18 @Console/write + +|100 + +#0b01 +&loop + DUP print/dec + DUP #0a NEQ ?{ + newline !&break } + comma space + INC !&loop + + &break + POP2 + +BRK + +@print/dec ( dec -- ) + DUP #64 DIV /num + DUP #0a DIV /num + ( >> ) + +@print/num_ ( num -- ) + #0a DIVk MUL SUB [ LIT "0 ] ADD .Console/write DEO + JMP2r + +@print/num ( num -- ) + DUP ?/num_ + POP + JMP2r diff --git a/Task/Loops-Nested/Ballerina/loops-nested.ballerina b/Task/Loops-Nested/Ballerina/loops-nested.ballerina new file mode 100644 index 0000000000..3478634506 --- /dev/null +++ b/Task/Loops-Nested/Ballerina/loops-nested.ballerina @@ -0,0 +1,23 @@ +import ballerina/io; +import ballerina/random; + +public function main() returns error? { + int[20][20] a = []; + foreach int i in 0...19 { + foreach int j in 0...19 { + a[i][j] = check random:createIntInRange(1, 21); + } + } + boolean found = false; + foreach int i in 0...19 { + foreach int j in 0...19 { + io:print(a[i][j].toString().padStart(3)); + if a[i][j] == 20 { + found = true; + break; + } + } + io:println(); + if found { break; } + } +} diff --git a/Task/Loops-Nested/Icon/loops-nested-1.icon b/Task/Loops-Nested/Icon/loops-nested-1.icon index 9aef91e5d8..fa607e1622 100644 --- a/Task/Loops-Nested/Icon/loops-nested-1.icon +++ b/Task/Loops-Nested/Icon/loops-nested-1.icon @@ -2,9 +2,14 @@ procedure main() every !(!(L := list(10)) := list(10)) := ?20 # setup a 2d array of random numbers up to 20 -every i := 1 to *L do # using nested loops - every j := 1 to *L[i] do - if L[i,j] = 20 then - break break write("L[",i,",",j,"]=20") - +every i := 1 to *L do{ # using nested loops + every j := 1 to *L[i] do{ + writes(" ",L[i,j]) + if L[i,j] = 20 then{ + write() + break break + } + } + write() +} end diff --git a/Task/Loops-Nested/Icon/loops-nested-2.icon b/Task/Loops-Nested/Icon/loops-nested-2.icon index f6ed64f558..ac36bec12b 100644 --- a/Task/Loops-Nested/Icon/loops-nested-2.icon +++ b/Task/Loops-Nested/Icon/loops-nested-2.icon @@ -1,4 +1 @@ -every x := L[i := 1 to *L,1 to *L[i]] do - if x = 20 then break write("L[",i,",",j,"]=20") # more succinctly - -every if !!L = 20 then break write("Found !!L=20") # even more so (but looses the values of i and j +e := !!L & write(e) & e = 20 diff --git a/Task/Loops-While/Ballerina/loops-while.ballerina b/Task/Loops-While/Ballerina/loops-while.ballerina index d56c901d69..ad6e887212 100644 --- a/Task/Loops-While/Ballerina/loops-while.ballerina +++ b/Task/Loops-While/Ballerina/loops-while.ballerina @@ -1,5 +1,9 @@ -int i = 1024; -while i > 0 { - io:println(i); - i = i / 2; +import ballerina/io; + +public function main() { + int i = 1024; + while i > 0 { + io:println(i); + i = i / 2; + } } diff --git a/Task/Loops-While/Uxntal/loops-while.uxnatl b/Task/Loops-While/Uxntal/loops-while.uxnatl new file mode 100644 index 0000000000..6bb868c471 --- /dev/null +++ b/Task/Loops-While/Uxntal/loops-while.uxnatl @@ -0,0 +1,21 @@ +%newline { [ LIT2 0a -Console/write ] DEO } + +|18 @Console/write + +|100 + +#0000 #0400 +&while EQU2k ?{ + DUP2 print-hex newline + #01 SFT2 !&while } +POP2 POP2 + +BRK + +@print-hex ( short* -- ) + SWP /byte + &byte ( byte -- ) + DUP #04 SFT /nibble + &nibble ( byte -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD #18 DEO + JMP2r diff --git a/Task/Loops-With-multiple-ranges/Ballerina/loops-with-multiple-ranges.ballerina b/Task/Loops-With-multiple-ranges/Ballerina/loops-with-multiple-ranges.ballerina new file mode 100644 index 0000000000..b63acc7fd3 --- /dev/null +++ b/Task/Loops-With-multiple-ranges/Ballerina/loops-with-multiple-ranges.ballerina @@ -0,0 +1,82 @@ +import ballerina/io; + +function pow(int n, int e) returns int { + if e < 1 { return 1; } + int prod = 1; + foreach int i in 1...e { prod *= n; } + return prod; +} + +function commatize(int n) returns string { + string s = n.toString(); + if n < 0 { s = s.substring(1); } + int le = s.length(); + foreach int i in int:range(le - 3, 0, -3) { + s = s.substring(0, i) + "," + s.substring(i); + } + if n >= 0 { return s; } + return "-" + s; +} + +public function main() { + int prod = 1; + int sum = 0; + int x = 5; + int y = -5; + int z = -2; + int one = 1; + int three = 3; + int seven = 7; + int p = pow(11, x); + int j = 0; + + var process = function() { + sum += j.abs(); + if (prod.abs() < (1 << 27) && j != 0) { prod *= j; } + }; + + j = -three; + while j <= pow(3, 3) { + process(); + j += three; + } + + j = -seven; + while j <= seven { + process(); + j += x; + } + + j = 555; + while j <= 550 - y { + process(); + j += 1; + } + + j = 22; + while j >= -28 { + process(); + j -= three; + } + + j = 1927; + while j <= 1939 { + process(); + j += 1; + } + + j = x; + while j >= y { + process(); + j -= -z; + } + + j = p; + while j <= p + one { + process(); + j += 1; + } + + io:println("sum = ", commatize(sum)); + io:println("prod = ", commatize(prod)); +} diff --git a/Task/Loops-Wrong-ranges/Ballerina/loops-wrong-ranges.ballerina b/Task/Loops-Wrong-ranges/Ballerina/loops-wrong-ranges.ballerina new file mode 100644 index 0000000000..7e8774e3e7 --- /dev/null +++ b/Task/Loops-Wrong-ranges/Ballerina/loops-wrong-ranges.ballerina @@ -0,0 +1,29 @@ +import ballerina/io; + +function loop(int begin, int stop, int inc) { + io:print("["); + foreach int param in [begin, stop, inc] { + io:print(param.toString().padStart(3)); + } + io:print("] -> "); + int count = 0; + int lim = 10; + int i = begin; + while i <= stop { + io:print(i, " "); + count += 1; + if count == lim { break; } + i += inc; + } + io:println(); +} + +public function main() { + var tests = [ + [-2, 2, 1], [-2, 2, 0], [-2, 2, -1], [-2, 2, 10], [2, -2, 1], + [2, 2, 1], [2, 2, -1], [2, 2, 0], [0, 0, 0] + ]; + foreach var test in tests { + loop(test[0], test[1], test[2]); + } +} diff --git a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx index 87094454eb..0eef1a6df2 100644 --- a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx +++ b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx @@ -1,57 +1,63 @@ -/*REXX pgm uses the Lucas─Lehmer primality test for prime powers of 2 (Mersenne primes)*/ -@.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1 /*a partial list of some low primes. */ -!.=@.; !.0=1; !.2=1; !.4=1; !.5=1; !.6=1; !.8=1 /*#'s with these last digs aren't prime*/ -parse arg limit . /*obtain optional arguments from the CL*/ -if limit=='' then limit= 200 /*Not specified? Then use the default.*/ -say center('Mersenne prime index list',70-3,"═") /*show a fancy─dancy header (or title).*/ -say right('M'2, 25) " [1 decimal digit]" /*left─justify them to align&look nice.*/ - /* [►] note that J==1 is a special case*/ - do j=1 by 2 to limit /*there're only so many hours in a day.*/ - power= j + (j==1) /*POWER ≡ J except for when J=1. */ - if \isPrime(power) then iterate /*if POWER isn't prime, then ignore it.*/ - $= LL2(power) /*perform the Lucas─Lehmer 2 (LL2) test*/ - if $=='' then iterate /*Did it flunk LL2? Then skip this #.*/ - say right($, 25) MPsize /*left─justify them to align&look nice.*/ - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure expose !. @. /*allow 2 stemmed arrays to be accessed*/ - parse arg x '' -1 z /*obtain variable X and last digit.*/ - if @.x then return 1 /*is X already found to be a prime? */ - if !.z then return 0 /*is last decimal digit even or a five?*/ - if x//3==0 then return 0 /*divisible by three? Then not a prime*/ - if x//7==0 then return 0 /*divisible by seven? " " " " */ - do j=11 by 6 until j*j > x /*ensures that J isn't divisible by 3. */ - if x // j ==0 then return 0 /*Is X divisible by J ? */ - if x // (j+2)==0 then return 0 /* " " " " J+2 ? ___ */ - end /*j*/ /* [↑] perform DO loop through √ x */ - @.x=1; return 1 /*indicate number X is a prime. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -LL2: procedure expose MPsize; parse arg ? /*Lucas─Lehmer test on 2**? - 1 */ - if ?==2 then s=0 /*handle special case for an even prime*/ - else s=4 /* [↓] same as NUMERIC FORM SCIENTIFIC*/ - numeric form; q= 2**? /*ensure correct form for REXX numbers.*/ - /*╔═══════════════════════════════════════════════════════════════════════════╗ - ╔═╝ Compute a power of 2 using only 9 decimal digits. One million digits ║ - ║ could be used, but that really slows up computations. So, we start with the║ - ║ default of 9 digits, and then find the ten's exponent in the product (2**?),║ - ║ double it, and then add 6. {2 is all that's needed, but 6 is a lot ║ - ║ safer.} The doubling is for the squaring of S (below, for s*s). ╔═╝ - ╚═══════════════════════════════════════════════════════════════════════════╝*/ - if pos('E', q)\==0 then do /*is number in exponential notation ? */ - parse var q 'E' tenPow /*get the exponent. */ - numeric digits tenPow * 2 + 6 /*expand precision. */ - end /*REXX used dec FP. */ - else numeric digits digits() * 2 + 6 /*use 9*2 + 6 digits*/ - q=2**? - 1 /*compute a power of two, minus one. */ - r= q // 8 /*obtain Q modulus eight. */ - if r==1 | r==7 then nop /*before crunching, do a simple test. */ - else return '' /*modulus Q isn't one or seven. */ - do ?-2; s= (s*s -2) // q /*lather, rinse, repeat ··· */ - end /* [↑] compute and test for a MP. */ - if s\==0 then return '' /*Not a Mersenne prime? Return a null.*/ - sz= length(q) /*obtain number of decimal digs in MP. */ - MPsize=' ['sz "decimal digit"s(sz)']' /*define a literal to display after MP.*/ - return 'M'? /*return "modified" # (Mersenne index).*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*simple pluralizer*/ +include Settings +numeric digits 5000 + +say 'LUCAS-LEHMER TEST - 10 Mar 2025' +say version +say +call LucasLehmer +call MillerRabin +exit + +LucasLehmer: +say 'Lucas-Lehmer' +call time('r') +do i = 3 by 2 to 1279 + if Prime(i) then + call LL i +end +say '...' +t = '2203 2281 3217 4253 4423' +do w = 1 to Words(t) + call LL Word(t,w) +end +say Format(Time('e'),,3) 'seconds'; say +return + +LL: +arg xx +d = Length(2**xx-1) +if Primell(xx) then + say Left('M'xx,5) '('Right(d,4) 'digits) is Prime' Time('e')/1's' +return + +MillerRabin: +say 'Miller-Rabin' +call time('r') +do i = 3 by 2 to 1279 + if Prime(i) then + call MR i +end +say '...' +t = '2203 2281 3217 4253 4423' +do w = 1 to Words(t) + call MR Word(t,w) +end +say Format(Time('e'),,3) 'seconds'; say +exit + +MR: +arg xx +m = 2**xx-1 +d = Length(m) +if Prime(m) then do + if d < 26 then + a = 'sure' + else + a = 'probable' + say Left('M'xx,5) '('Right(d,4) 'digits) is' a 'Prime' Time('e')/1's' +end +return + +include Numbers +include Functions +include Abend diff --git a/Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test.raku b/Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test-1.raku similarity index 100% rename from Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test.raku rename to Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test-1.raku diff --git a/Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test-2.raku b/Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test-2.raku new file mode 100644 index 0000000000..f3213f81df --- /dev/null +++ b/Task/Lucas-Lehmer-test/Raku/lucas-lehmer-test-2.raku @@ -0,0 +1,16 @@ +multi is_mersenne_prime(2) { True } +multi is_mersenne_prime(Int $p) { + my $m_p = 1 +< $p - 1; + my $s = 4; + $s = $s.expmod(2, $m_p) - 2 for 3 .. $p; + !$s +} + +# Exhaustive search for Mersenne primes up to 4600 - about half a second +my $start = now; +.say for (flat 2, (1..2300).map(* * 2 + 1)).hyper.map: + { next unless .&is-prime && .&is_mersenne_prime; "M$_ {(now - $start).round(.001)} running total seconds" }; + +# Cheat and just verify Mersenne primes > 4600 +.say for (9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503).hyper(:1batch).map: + { next unless .&is_mersenne_prime; "M$_ {(now - $start).round(.001)} running total seconds" }; diff --git a/Task/Ludic-numbers/EasyLang/ludic-numbers.easy b/Task/Ludic-numbers/EasyLang/ludic-numbers.easy index 06bb876321..9b44d4b840 100644 --- a/Task/Ludic-numbers/EasyLang/ludic-numbers.easy +++ b/Task/Ludic-numbers/EasyLang/ludic-numbers.easy @@ -1,4 +1,4 @@ -proc initLudicArray n . res[] . +proc initLudicArray &res[] n . len res[] n res[1] = 1 for i = 2 to n @@ -9,7 +9,7 @@ proc initLudicArray n . res[] . res[i] = k + 2 . . -initLudicArray 2005 arr[] +initLudicArray arr[] 2005 for i = 1 to 25 write arr[i] & " " . diff --git a/Task/Ludic-numbers/REXX/ludic-numbers.rexx b/Task/Ludic-numbers/REXX/ludic-numbers.rexx index af1ecf56a8..5907944e77 100644 --- a/Task/Ludic-numbers/REXX/ludic-numbers.rexx +++ b/Task/Ludic-numbers/REXX/ludic-numbers.rexx @@ -1,41 +1,52 @@ -/*REXX program gens/shows (a range of) ludic numbers, or a count when a range is used.*/ -parse arg N count bot top triples . /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/ -if count=='' | count=="," then count= 1000 /* " " " " " " */ -if bot=='' | bot=="," then bot= 2000 /* " " " " " " */ -if top=='' | top=="," then top= 2005 /* " " " " " " */ -if triples=='' | triples=="," then triples= 249 /* " " " " " " */ -#= 0 /*the number of ludic numbers (so far).*/ -$= ludic( max(N, count, bot, top, triples) ) /*generate enough ludic nums*/ -say 'The first ' N " ludic numbers: " subword($,1,25) /*display 1st N ludic nums*/ - do j=1 until word($, j) > count /*search up to a specific #.*/ - end /*j*/ +-- 22 Mar 2025 +include Settings + +say 'LUDIC NUMBERS' +say version say -say "There are " j - 1 ' ludic numbers that are ≤ ' count +call Ludics 2000 +call Range 1 25 +call Below 1000 +call Ludics 22000 +call Range 2000 2005 +call Triplets 250 +say Time('e')/1 'seconds' +exit + +Range: +procedure expose ludi. +arg xx yy +if yy = '' then + yy = xx +say 'The Ludic numbers from no' xx 'up to' yy 'are' +do i = xx to yy + call Charout ,ludi.i' ' +end +say; say +return + +Below: +procedure expose ludi. +arg xx +do i = 1 until ludi.i >= xx +end +say 'There are' i-1 'Ludic numbers <=' xx say -say "The " bot '───►' top ' (inclusive) ludic numbers are: ' subword($, bot) -@= /*list of ludic triples found (so far).*/ - do j=1 for words($) - _= word($, j) /*it is known that ludic _ exists. */ - if _>=triples then leave /*only process up to a specific number.*/ - if wordpos(_+2, $)==0 | wordpos(_+6, $)==0 then iterate /*Not triple? Skip it.*/ - #= # + 1 /*bump the triple counter. */ - @= @ '◄'_ _+2 _+6"► " /*append the newly found triple ──► @ */ - end /*j*/ -say -if @=='' then say 'From 1──►'triples", no triples found." - else say 'From 1──►'triples", " # ' triples found:' @ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -ludic: procedure; parse arg m,,@; $= 1 2 /*$≡ludic numbers superset; @≡sequence*/ - do j=3 by 2 to m*15; @= @ j /*construct an initial list of numbers.*/ - end /*j*/ - @= @' '; n= words(@) /*append a blank to the number sequence*/ - do while n\==0; f= word(@, 1) /*examine the first word in the @ list.*/ - $= $ f /*add the word to the $ list. */ - do d=1 by f while d<=n; n= n-1 /*use 1st number, elide all occurrences*/ - @= changestr(' 'word(@, d)" ", @, ' . ') /*cross─out a number in @ */ - end /*d*/ /* [↑] done eliding the "1st" number. */ - @= translate(@, , .) /*change dots to blanks; count numbers.*/ - end /*while*/ /* [↑] done eliding ludic numbers. */ - return subword($, 1, m) /*return a range of ludic numbers. */ +return + +Triplets: +procedure expose ludi. work. +arg xx +say 'Found triplets below' xx +do i = 1 until l3 >= xx + l1 = i; l2 = i+2; l3 = i+6 + if work.l1 & work.l2 & work.l3 then do + call Charout ,'['l1 l2 l3'] ' + end +end +say; say +return + +include Sequences +include Functions +include Abend diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-1.lua similarity index 75% rename from Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua rename to Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-1.lua index 0898194946..892105fe3a 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers.lua +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-1.lua @@ -1,4 +1,4 @@ -function luhn_test(cc_number) +function luhn(cc_number) assert(type(cc_number) == 'string') local sum = 0 local is_odd = true @@ -14,7 +14,3 @@ function luhn_test(cc_number) end -- for return (sum % 10) == 0 end -- function luhn_test - -for _, val in ipairs{"49927398716", "49927398717", "1234567812345678", "1234567812345670"} do - print(val, luhn_test(val)) -end -- for diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua new file mode 100644 index 0000000000..09d98492c9 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-2.lua @@ -0,0 +1,8 @@ +function luhn(digits) + local sum = 0 + for odd,even in digits:reverse():gmatch"(.)(.?)" do + local number = 2 * (tonumber(even) or 0) + sum = sum + odd + number%10 + number//10 + end + return sum%10==0 +end diff --git a/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua new file mode 100644 index 0000000000..e55e3ca948 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Lua/luhn-test-of-credit-card-numbers-3.lua @@ -0,0 +1,3 @@ +for _, val in ipairs{"49927398716", "49927398717", "1234567812345678", "1234567812345670"} do + print(val, luhn(val)) +end diff --git a/Task/M-bius-function/ANSI-BASIC/m-bius-function.basic b/Task/M-bius-function/ANSI-BASIC/m-bius-function.basic new file mode 100644 index 0000000000..0abcfa77e7 --- /dev/null +++ b/Task/M-bius-function/ANSI-BASIC/m-bius-function.basic @@ -0,0 +1,28 @@ +100 REM Moebius function +110 DECLARE EXTERNAL FUNCTION Moebius +120 FOR T = 0 TO 9 +130 FOR U = 1 TO 10 +140 PRINT USING "## ": Moebius(10 * T + U); +150 NEXT U +160 PRINT +170 NEXT T +180 END +190 REM *** +200 EXTERNAL FUNCTION Moebius(N) +210 LET M = 1 +220 IF N <> 1 THEN +230 LET F = 2 +240 DO +250 IF MOD(N, (F * F)) = 0 THEN +260 LET M = 0 +270 ELSE +280 IF MOD(N, F) = 0 THEN +290 LET M = -M +300 LET N = N / F +310 END IF +320 LET F = F + 1 +330 END IF +340 LOOP WHILE (F <= N) AND (M <> 0) +350 END IF +360 LET Moebius = M +370 END FUNCTION diff --git a/Task/M-bius-function/ASIC/m-bius-function.asic b/Task/M-bius-function/ASIC/m-bius-function.asic new file mode 100644 index 0000000000..93962d58be --- /dev/null +++ b/Task/M-bius-function/ASIC/m-bius-function.asic @@ -0,0 +1,37 @@ +REM Moebius function +FOR T = 0 TO 9 + FOR U = 1 TO 10 + N = 10 * T + N = N + U + GOSUB CalcMoebius: + PRINT M; + NEXT U + PRINT +NEXT T +END + +CalcMoebius: +REM Calculate Moebius(N). Result in M. +REM NOTE. N changes its value. +M = 1 +IF N <> 1 THEN + F = 2 + StartLoop: + FTo2 = F * F + NModFTo2 = N MOD FTo2 + IF NModFTo2 = 0 THEN + M = 0 + ELSE + NModF = N MOD F + IF NModF = 0 THEN + M = -M + N = N / F + ENDIF + F = F + 1 + ENDIF + IF M = 0 THEN AfterLoop: + IF F > N THEN AfterLoop: + GOTO StartLoop: + AfterLoop: +ENDIF +RETURN diff --git a/Task/M-bius-function/EasyLang/m-bius-function.easy b/Task/M-bius-function/EasyLang/m-bius-function.easy index 2826147573..764f397637 100644 --- a/Task/M-bius-function/EasyLang/m-bius-function.easy +++ b/Task/M-bius-function/EasyLang/m-bius-function.easy @@ -6,12 +6,8 @@ for i to mu_max . for i = 2 to sqroot if mu[i] = 1 - for j = i step i to mu_max - mu[j] *= -i - . - for j = i * i step i * i to mu_max - mu[j] = 0 - . + for j = i step i to mu_max : mu[j] *= -i + for j = i * i step i * i to mu_max : mu[j] = 0 . . for i = 2 to mu_max @@ -25,10 +21,8 @@ for i = 2 to mu_max mu[i] = -1 . . -numfmt 0 3 +numfmt 3 0 for i = 1 to 100 write mu[i] - if i mod 10 = 0 - print "" - . + if i mod 10 = 0 : print "" . diff --git a/Task/M-bius-function/JavaScript/m-bius-function-1.js b/Task/M-bius-function/JavaScript/m-bius-function-1.js new file mode 100644 index 0000000000..90052b19c4 --- /dev/null +++ b/Task/M-bius-function/JavaScript/m-bius-function-1.js @@ -0,0 +1,32 @@ +// Moebius function + +function moebius(n) { + m = 1; + if (n != 1) { + f = 2; + do { + if (n % (f * f) == 0) { + m = 0; + } else { + if (n % f == 0) { + m = -m; + n /= f; + } + f++; + } + } while (f <= n && m != 0); + } + return m; +} + +document.write(""); +for (t = 0; t <= 9; t++) { + document.write(""); + for (u = 1; u <= 10; u++) { + document.write(""); + } + document.write(""); +} +document.write("
"); + document.write(moebius(10 * t + u)); + document.write("
"); diff --git a/Task/M-bius-function/JavaScript/m-bius-function-2.js b/Task/M-bius-function/JavaScript/m-bius-function-2.js new file mode 100644 index 0000000000..9fa62b473a --- /dev/null +++ b/Task/M-bius-function/JavaScript/m-bius-function-2.js @@ -0,0 +1,7 @@ + + + + + + + diff --git a/Task/M-bius-function/K/m-bius-function.k b/Task/M-bius-function/K/m-bius-function.k new file mode 100644 index 0000000000..9d6ca736fe --- /dev/null +++ b/Task/M-bius-function/K/m-bius-function.k @@ -0,0 +1,8 @@ +mus:{ / values of mu(i) for i below x + (~~!x) { / initial value: 0 1 1 1 1 ... + y[z *1+!(-z )!x-1]*:-1 / flip sign + y[z*z*1+!(-z*z)!x-1]:0 / set squares to zero + y}[x]/ `pri x} / for each prime below x +(μ:):{mus[1+0|/,//x]x} +`0:"The first 100 values of the μ function:" +`0:,/'-3$$μ 10 10#1+!100 diff --git a/Task/M-bius-function/Modula-2/m-bius-function.mod2 b/Task/M-bius-function/Modula-2/m-bius-function.mod2 new file mode 100644 index 0000000000..5a56c95bd7 --- /dev/null +++ b/Task/M-bius-function/Modula-2/m-bius-function.mod2 @@ -0,0 +1,41 @@ +MODULE Moebius; +(* Moebius function *) +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +VAR + T, U: INTEGER; + +PROCEDURE Moebius(N: INTEGER): INTEGER; +VAR + M, F: INTEGER; +BEGIN + M := 1; + IF N <> 1 THEN + F := 2; + REPEAT + IF N MOD (F * F) = 0 THEN + M := 0 + ELSE + IF N MOD F = 0 THEN + M := -M; + N := N DIV F + END; + F := F + 1 + END + UNTIL (F > N) OR (M = 0) + END; + RETURN M +END Moebius; + +BEGIN + FOR T := 0 TO 9 DO + FOR U := 1 TO 10 DO + WriteInt(Moebius(10 * T + U), 2); + WriteString(' ') + END; + WriteLn + END +END Moebius. diff --git a/Task/M-bius-function/PHP/m-bius-function.php b/Task/M-bius-function/PHP/m-bius-function.php new file mode 100644 index 0000000000..071a320dcf --- /dev/null +++ b/Task/M-bius-function/PHP/m-bius-function.php @@ -0,0 +1,29 @@ + diff --git a/Task/M-bius-function/REXX/m-bius-function-1.rexx b/Task/M-bius-function/REXX/m-bius-function-1.rexx deleted file mode 100644 index 43b2b21283..0000000000 --- a/Task/M-bius-function/REXX/m-bius-function-1.rexx +++ /dev/null @@ -1,49 +0,0 @@ -/*REXX pgm computes & shows a value grid of the Möbius function for a range of integers.*/ -call time('r') -parse arg LO HI grp . /*obtain optional arguments from the CL*/ -numeric digits 100 -if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 199 /* " " " " " " */ -if grp=='' | grp=="," then grp= 20 /* " " " " " " */ - /* uuuuuuuuuuuu */ -call genP HI /*generate primes up to the v HI */ -say center(' The Moebius sequence from ' LO " --> " HI" ", max(50, grp*3), '=') /*title*/ -dd='' /*variable holds output grid of GRP hhs.*/ - do j=LO to HI; dd= dd right( moebius(j), 2) /*process some numbers from LO --> HI.*/ - if words(dd)==grp then do; say substr(dd, 2); dd='' /*show grid if fully populated,*/ - end /* and nullify it for more hhs.*/ - end /*j*/ /*for small grids, using wordCnt is OK.*/ - -if dd\=='' then say substr(dd, 2) /*handle any residual numbers not shown*/ -say format(time('e'),,3) 'seconds' -exit /*stick a fork in it, we're all done. */ -/*--------------------------------------------------------------------------------------*/ -moebius: procedure expose aa.; parse arg x /*obtain a integer to be tested for mu.*/ - if x<1 then return '*' /*special? Then return symbol for null.*/ - hh= 0 /*start with a value of zero. */ - do k=1; p= aa.k /*get the Kth (pre-generated) prime.*/ - if p>x then leave /*prime (P) > X? Then we're done. */ - if p*p>x then do; hh= hh+1; leave /*prime (P**2 > X? Bump hh and leave.*/ - end - if x//p==0 then do; hh= hh+1 /*X divisible by P? Bump mu number. */ - x= x % p /* Divide by prime. */ - if x//p==0 then return 0 /*X÷by P? Then return zero*/ - end - end /*k*/ /*hh (below) is almost always small, <9*/ - if hh//2==0 then return 1 /*Is hh even? Then return postive 1 */ - return -1 /* " " odd? " " negative 1. */ -/*--------------------------------------------------------------------------------------*/ -genP: aa.1=2; aa.2=3; aa.3=5; aa.4=7; aa.5=11; aa.6= 13; nP=6 /*assign low primes; hh primes.*/ - do lim=nP until lim*lim>=HI /*only keep primes up to the sqrt(HI).*/ - end /*lim*/ - do j=aa.nP+4 by 2 to HI /*only find odd primes from here on. */ - parse var j '' -1 uu;if uu==5 then iterate /*Is last digit a "5"? Then not prime*/ - if j// 3==0 then iterate /*is J divisible by 3? " " " */ - if j// 7==0 then iterate /* " " " " 7? " " " */ - if j//11==0 then iterate /* " " " " 11? " " " */ - if j//13==0 then iterate /* " " " " 13? " " " */ - do k=7 while k*k<=j /*divide by some generated odd primes. */ - if j // aa.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [?] a prime (J) has been found. */ - nP= nP+1; if nP<=HI then aa.nP= j /*bump prime count; assign prime to aa.*/ - end /*j*/; return diff --git a/Task/M-bius-function/REXX/m-bius-function-2.rexx b/Task/M-bius-function/REXX/m-bius-function-2.rexx deleted file mode 100644 index 65f32f2d38..0000000000 --- a/Task/M-bius-function/REXX/m-bius-function-2.rexx +++ /dev/null @@ -1,41 +0,0 @@ -include Settings - -say version; say 'Moebius sequence'; say -parse arg LO HI grp . /*obtain optional arguments from the CL*/ -numeric digits 100 -if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 199 /* " " " " " " */ -if grp=='' | grp=="," then grp= 20 /* " " " " " " */ - /* ______ */ -say Center(' The Moebius sequence from ' LO " --> " HI" ", Max(50, grp*3), '=') /*title*/ -dd='' /*variable holds output grid of GRP #s.*/ - do j=LO to HI; dd= dd Right( Moebius(j), 2) /*process some numbers from LO --> HI.*/ - if Words(dd)==grp then do; say Substr(dd, 2); dd='' /*show grid if fully populated,*/ - end /* and nullify it for more #s.*/ - end /*j*/ /*for small grids, using wordCnt is OK.*/ -if dd\=='' then say Substr(dd, 2) /*handle any residual numbers not shown*/ -say Format(Time('e'),,3) 'seconds' -exit /*stick a fork in it, we're all done. */ - -Moebius: -/* Moebius sequence */ -procedure expose fact. ufac. -arg x -/* Special value */ -if x = 0 then - return '*' -/* Using # of (unique) prime factors */ -call Factors(x) -call Ufactors(x) -if fact.0 = ufac.0 then - if IsEven(fact.factor.0) then - return 1 - else - return -1 -else - return 0 - -include Functions -include Numbers -include Sequences -include Abend diff --git a/Task/M-bius-function/REXX/m-bius-function.rexx b/Task/M-bius-function/REXX/m-bius-function.rexx new file mode 100644 index 0000000000..f5a4186e1b --- /dev/null +++ b/Task/M-bius-function/REXX/m-bius-function.rexx @@ -0,0 +1,30 @@ +include Settings + +say 'MOEBIUS FUNCTION - 4 Mar 2025' +say version +say +numeric digits 100 +call sequence 1,200 +call sequence 100001,100200 +call sequence 1000000001,1000000200 +call sequence 10000000000001,10000000000200 +exit + +Sequence: +arg x,y +say 'Moebius sequence from' x 'to' y +n = 0 +do i = x to y + n = n+1 + call charout ,right(Moebius(i),3) + if n//20 = 0 then + say +end +say Format(Time('e'),,3) 'seconds' +say +return + +include Functions +include Numbers +include Sequences +include Abend diff --git a/Task/M-bius-function/RapidQ/m-bius-function.rapidq b/Task/M-bius-function/RapidQ/m-bius-function.rapidq new file mode 100644 index 0000000000..be91cf2377 --- /dev/null +++ b/Task/M-bius-function/RapidQ/m-bius-function.rapidq @@ -0,0 +1,36 @@ +REM Levenshtein distance +DECLARE FUNCTION LevDist(S$, T$) AS INTEGER +DECLARE FUNCTION MIN(A, B) AS INTEGER +PRINT "The Levenshtein distance..." +PRINT "between 'kitten' and 'sitting' is "; LevDist("kitten","sitting") +PRINT "between 'rosettacode' and 'raisethysword' is "; LevDist("rosettacode","raisethysword") +END + +FUNCTION LevDist(S$, T$) AS INTEGER +N = LEN(T$): M = LEN(S$) +DIM D(0 TO N, 0 TO N) +FOR I = 0 TO M + D(I, 0) = I +NEXT I +FOR J = 0 TO N + D(0, J) = J +NEXT J +FOR J = 1 TO N + FOR I = 1 TO M + IF MID$(S$, I, 1) = MID$(T$, J, 1) THEN + D(I, J) = D(I - 1, J - 1) + ELSE + D(I, J) = Min(D(I - 1, J) + 1, Min(D(I, J - 1) + 1, D(I - 1, J - 1) + 1)) + END IF + NEXT I +NEXT J +LevDist = D(M, N) +END FUNCTION + +FUNCTION Min(A, B) AS INTEGER +IF A < B THEN + Min = A +ELSE + Min = B +END IF +END FUNCTION diff --git a/Task/MD5-Implementation/EasyLang/md5-implementation.easy b/Task/MD5-Implementation/EasyLang/md5-implementation.easy index 2db0a4b538..c4286a9e53 100644 --- a/Task/MD5-Implementation/EasyLang/md5-implementation.easy +++ b/Task/MD5-Implementation/EasyLang/md5-implementation.easy @@ -1,12 +1,12 @@ len md5k[] 64 -proc md5init . . +proc md5init . for i = 1 to 64 md5k[i] = floor (0x100000000 * abs sin (i * 180 / pi)) . . md5init # -proc md5 inp$ . s$ . +func$ md5 inp$ . subr addinp if inp4 = 1 inp[] &= 0 @@ -60,21 +60,20 @@ proc md5 inp$ . s$ . f = bitxor h1 d g = (3 * i + 2) mod 16 else - h1 = bitor b bitnot d + h1 = bitor b bitand bitnot d 0xffffffff f = bitxor c h1 g = (7 * i - 7) mod 16 . - f = (f + a + md5k[i] + inp[chunk + g]) + f = bitand (f + a + md5k[i] + inp[chunk + g]) 0xffffffff a = d d = c c = b h1 = bitshift f s[i] h2 = bitshift f (s[i] - 32) - b = (b + h1 + h2) + b = bitand (b + h1 + h2) 0xffffffff . a0 += a ; b0 += b ; c0 += c ; d0 += d . - s$ = "" for a in [ a0 b0 c0 d0 ] for i = 1 to 4 b = a mod 256 @@ -88,14 +87,15 @@ proc md5 inp$ . s$ . . . . + return s$ . repeat s$ = input until error = 1 - md5 s$ h$ - print h$ + print md5 s$ . input_data + a abc message digest diff --git a/Task/MD5-Implementation/JavaScript/md5-implementation.js b/Task/MD5-Implementation/JavaScript/md5-implementation.js new file mode 100644 index 0000000000..5b20385092 --- /dev/null +++ b/Task/MD5-Implementation/JavaScript/md5-implementation.js @@ -0,0 +1,209 @@ +// MD5 Constants +const INITIAL_A = 0x67452301; +const INITIAL_B = 0xEFCDAB89; // No need for L suffix or static_cast +const INITIAL_C = 0x98BADCFE; // No need for L suffix or static_cast +const INITIAL_D = 0x10325476; + +const SHIFT_AMOUNTS = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 +]; + +// K constants (T table) - Sine values +const K = [ + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 +]; + +/** + * Left-rotate a 32-bit integer by a number of bits. + * @param {number} x - The integer to rotate. + * @param {number} n - The number of bits to rotate by. + * @returns {number} The rotated integer. + */ +function rotl(x, n) { + // Ensure x is treated as 32-bit for the shifts + return ((x << n) | (x >>> (32 - n))) | 0; +} + +/** + * Converts a Uint8Array (byte array) to a hexadecimal string. + * @param {Uint8Array} bytes - The byte array to convert. + * @returns {string} The hexadecimal string representation. + */ +function bytesToHexString(bytes) { + let hexString = ""; + for (const byte of bytes) { + hexString += byte.toString(16).padStart(2, '0'); + } + return hexString; +} + +/** + * Converts a string to a Uint8Array using UTF-8 encoding. + * @param {string} text - The string to convert. + * @returns {Uint8Array} The resulting byte array. + */ +function stringToBytes(text) { + return new TextEncoder().encode(text); +} + +/** + * Computes the MD5 hash of a byte array. + * @param {Uint8Array} message - The input message as a byte array. + * @returns {Uint8Array} The 16-byte MD5 hash. + */ +function computeMD5(message) { + const messageLengthBytes = message.length; + const messageLengthBits = BigInt(messageLengthBytes) * 8n; // Use BigInt for potentially large lengths + + // Calculate padding length + // Need (length + 1 + k) % 64 == 56 bytes (or 448 bits) + // So, length + 1 + k = 64n + 56 + // k = 64n + 56 - length - 1 + // Minimum k is when 64n is just >= length + 1 - 56 + 1 = length - 54 + // Padding length includes the 0x80 byte and the 8 length bytes. + // Total length must be multiple of 64 bytes (512 bits). + const numBlocks = Math.ceil((messageLengthBytes + 1 + 8) / 64); + const totalLength = numBlocks * 64; + const paddingLength = totalLength - messageLengthBytes; + + // Create padded message buffer + const paddedMessage = new Uint8Array(totalLength); + paddedMessage.set(message); // Copy original message + + // Append the '1' bit (0x80 byte) + paddedMessage[messageLengthBytes] = 0x80; + + // Append the 64-bit message length (little-endian) + // Note: JavaScript bitwise ops work on 32 bits. Handle 64-bit length carefully. + const lengthOffset = totalLength - 8; + for (let i = 0; i < 8; ++i) { + paddedMessage[lengthOffset + i] = Number((messageLengthBits >> (BigInt(i) * 8n)) & 0xFFn); + } + + // Initialize hash state variables (ensure they are 32-bit ints) + let a = INITIAL_A | 0; + let b = INITIAL_B | 0; + let c = INITIAL_C | 0; + let d = INITIAL_D | 0; + + const buffer = new Array(16); // Reusable buffer for 16 words (32-bit integers) + + // Process the message in 64-byte (512-bit) blocks + for (let i = 0; i < numBlocks; ++i) { + const blockOffset = i * 64; + + // Prepare the 16-word buffer from the current block (little-endian) + for (let j = 0; j < 16; ++j) { + const wordIndex = blockOffset + j * 4; + buffer[j] = ( + (paddedMessage[wordIndex]) | + (paddedMessage[wordIndex + 1] << 8) | + (paddedMessage[wordIndex + 2] << 16) | + (paddedMessage[wordIndex + 3] << 24) + ) | 0; // Ensure 32-bit integer + } + + // Save current hash state + let originalA = a; + let originalB = b; + let originalC = c; + let originalD = d; + + // Main loop (64 rounds) + for (let j = 0; j < 64; ++j) { + let f, bufferIndex; + const div16 = Math.floor(j / 16); + + switch (div16) { + case 0: // Round 1: F = (B & C) | (~B & D) + f = (b & c) | (~b & d); + bufferIndex = j; + break; + case 1: // Round 2: G = (B & D) | (C & ~D) + f = (b & d) | (c & ~d); + bufferIndex = (j * 5 + 1) % 16; + break; + case 2: // Round 3: H = B ^ C ^ D + f = b ^ c ^ d; + bufferIndex = (j * 3 + 5) % 16; + break; + case 3: // Round 4: I = C ^ (B | ~D) + f = c ^ (b | ~d); + bufferIndex = (j * 7) % 16; + break; + } + + // Ensure intermediate results are 32-bit + f = f | 0; + const term1 = a | 0; + const term2 = buffer[bufferIndex] | 0; + const term3 = K[j] | 0; + const shift = SHIFT_AMOUNTS[j]; // Use direct index j for SHIFT_AMOUNTS + + // Perform the round calculation: temp = B + rotl(A + F + M[g] + K[i], s) + let sum = (term1 + f + term2 + term3) | 0; + let rotatedSum = rotl(sum, shift); + let temp = (b + rotatedSum) | 0; + + // Update hash variables + a = d; + d = c; + c = b; + b = temp; + } + + // Add the original hash state back (with 32-bit wrap) + a = (a + originalA) | 0; + b = (b + originalB) | 0; + c = (c + originalC) | 0; + d = (d + originalD) | 0; + } + + // Construct final 16-byte hash (little-endian) + const md5Bytes = new Uint8Array(16); + let count = 0; + for (const word of [a, b, c, d]) { + for (let i = 0; i < 4; ++i) { + md5Bytes[count++] = (word >> (i * 8)) & 0xFF; + } + } + + return md5Bytes; +} + +// --- Main execution (equivalent to C++ main) --- +const tests = [ + "", + "a", + "abc", + "message digest", + "abcdefghijklmnopqrstuvwxyz", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890" +]; + +console.log("MD5 Hashes:"); +for (const test of tests) { + const messageBytes = stringToBytes(test); + const hashBytes = computeMD5(messageBytes); + const hexHash = bytesToHexString(hashBytes); + console.log(`${hexHash} <== "${test}"`); +} diff --git a/Task/MD5/EasyLang/md5.easy b/Task/MD5/EasyLang/md5.easy index 727b788834..aa9905db3b 100644 --- a/Task/MD5/EasyLang/md5.easy +++ b/Task/MD5/EasyLang/md5.easy @@ -1,5 +1,5 @@ len md5k[] 64 -proc md5init . . +proc md5init . for i = 1 to 64 md5k[i] = floor (0x100000000 * abs sin (i * 180 / pi)) . @@ -8,14 +8,10 @@ md5init # func$ md5 inp$ . subr addinp - if inp4 = 1 - inp[] &= 0 - . + if inp4 = 1 : inp[] &= 0 inp[len inp[]] += b * inp4 inp4 *= 0x100 - if inp4 = 0x100000000 - inp4 = 1 - . + if inp4 = 0x100000000 : inp4 = 1 . s[] = [ 7 12 17 22 7 12 17 22 7 12 17 22 7 12 17 22 5 9 14 20 5 9 14 20 5 9 14 20 5 9 14 20 4 11 16 23 4 11 16 23 4 11 16 23 4 11 16 23 6 10 15 21 6 10 15 21 6 10 15 21 6 10 15 21 ] inp[] = [ ] @@ -61,16 +57,16 @@ func$ md5 inp$ . g = (3 * i + 2) mod 16 else h1 = bitor b bitnot d - f = bitxor c h1 + f = bitand 0xffffffff bitxor c h1 g = (7 * i - 7) mod 16 . - f = (f + a + md5k[i] + inp[chunk + g]) + f = bitand 0xffffffff (f + a + md5k[i] + inp[chunk + g]) a = d d = c c = b h1 = bitshift f s[i] h2 = bitshift f (s[i] - 32) - b = (b + h1 + h2) + b = bitand 0xffffffff (b + h1 + h2) . a0 += a ; b0 += b ; c0 += c ; d0 += d . @@ -80,9 +76,7 @@ func$ md5 inp$ . a = a div 256 for h in [ b div 16 b mod 16 ] h += 48 - if h > 57 - h += 39 - . + if h > 57 : h += 39 s$ &= strchar h . . diff --git a/Task/Mad-Libs/ALGOL-68/mad-libs.alg b/Task/Mad-Libs/ALGOL-68/mad-libs.alg index 4731d9f18e..d82253860f 100644 --- a/Task/Mad-Libs/ALGOL-68/mad-libs.alg +++ b/Task/Mad-Libs/ALGOL-68/mad-libs.alg @@ -1,123 +1,111 @@ -# Mad Libs style story generation # +BEGIN # Mad Libs style story generation # -# gets the story template from the file f. The template terminates with # -# a blank line # -# The user is then promoted for the replacements for the markers # -# and the story is printed with the substitutions made # -PROC story = ( REF FILE f )VOID: -BEGIN - - # a linked list of strings, used to hold the story template # - MODE STRINGLIST = STRUCT( STRING text, REF STRINGLIST next ); - - # a linked list of pairs of strings, used to hold the replacements # - MODE REPLACEMENTLIST = STRUCT( STRING word - , STRING replacement - , REF REPLACEMENTLIST next - ); - - # NIL reference for marking the end of a STRINGLIST # - REF STRINGLIST nil stringlist = NIL; - - # NIL reference for marking the end of a REPLACEMENTLIST # - REF REPLACEMENTLIST nil replacementlist = NIL; - - - # returns "text" with trailing spaces removed # - OP RTRIM = ( STRING text )STRING: + # gets the story template from the file f. The template terminates with # + # a blank line # + # The user is then promoted for the replacements for the markers # + # and the story is printed with the substitutions made # + PROC story = ( REF FILE f )VOID: BEGIN - INT trim pos := UPB text; - FOR text pos FROM UPB text BY -1 TO LWB text WHILE text[ text pos ] = " " + + # a linked list of strings, used to hold the story template # + MODE STRINGLIST = STRUCT( STRING text, REF STRINGLIST next ); + + # a linked list of pairs of strings, used to hold the replacements # + MODE REPLACEMENTLIST = STRUCT( STRING word + , STRING replacement + , REF REPLACEMENTLIST next + ); + # NIL reference for marking the end of a STRINGLIST # + REF STRINGLIST nil stringlist = NIL; + # NIL reference for marking the end of a REPLACEMENTLIST # + REF REPLACEMENTLIST nil replacementlist = NIL; + + # returns "text" with trailing spaces removed # + OP RTRIM = ( STRING text )STRING: + BEGIN + INT trim pos := UPB text; + FOR text pos FROM UPB text BY -1 TO LWB text WHILE text[ text pos ] = " " + DO + trim pos := text pos - 1 + OD; + text[ LWB text : trim pos ] + END; # RTRIM # + + # looks for word in the dictionary. If it is found, replacement is # + # set to its replacement and TRUE is returned. If word not present, # + # FALSE is returned - uses recursion # + PROC find replacement = ( STRING word + , REF STRING replacement + , REF REPLACEMENTLIST story dictionary + ) BOOL: + IF story dictionary IS nil replacementlist + THEN FALSE + ELIF word OF story dictionary = word + THEN replacement := replacement OF story dictionary; + TRUE + ELSE find replacement( word, replacement, next OF story dictionary ) + FI; # find replacement # + + + # read the story template # + + # the result has a dummy element so "next OF next" is always valid # + REF STRINGLIST story text := HEAP STRINGLIST := ( "dummy", nil stringlist ); + REF REF STRINGLIST next := story text; + + WHILE # read the story template, terminates with a blank line # + STRING text; + get( f, ( text, newline ) ); + text := RTRIM text; + text /= "" DO - trim pos := text pos - 1 + # add the line to the end of the list # + next := ( next OF next ) := HEAP STRINGLIST := ( text, nil stringlist ) OD; - text[ LWB text : trim pos ] - END; # RTRIM # + # find the markers in the story and replace them with the # + # user's chosen text - we ignore the dummy element at the start # - # looks for word in the dictionary. If it is found, replacement is # - # set to its replacement and TRUE is returned. If word not present, # - # FALSE is returned - uses recursion # - PROC find replacement = ( STRING word - , REF STRING replacement - , REF REPLACEMENTLIST dictionary - )BOOL: - IF dictionary IS nil replacementlist - THEN - FALSE - ELIF word OF dictionary = word - THEN - replacement := replacement OF dictionary; - TRUE - ELSE - find replacement( word, replacement, next OF dictionary ) - FI; # find replacement # + REF REPLACEMENTLIST dictionary := nil replacementlist; + REF STRINGLIST line := story text; - - # read the story template # - - # the result has a dummy element so "next OF next" is always valid # - REF STRINGLIST story := HEAP STRINGLIST := ( "dummy", nil stringlist ); - REF REF STRINGLIST next := story; - - # read the story template, terminates with a blank line # - - WHILE - STRING text; - get( f, ( text, newline ) ); - text := RTRIM text; - text /= "" - DO - # add the line to the end of the list # - next := ( next OF next ) := HEAP STRINGLIST := ( text, nil stringlist ) - OD; - - # find the markers in the story and replace them with the # - # user's chosen text - we ignore the dummy element at the start # - - REF REPLACEMENTLIST dictionary := nil replacementlist; - REF STRINGLIST line := story; - - WHILE line := next OF line; - line ISNT nil stringlist - DO - # have a line of text - replace all the markers in it # - STRING word, replacement; - INT start pos, end pos; - WHILE char in string( "<", start pos, text OF line ) - AND char in string( ">", end pos, text OF line ) + WHILE line := next OF line; + line ISNT nil stringlist DO - # have a marker, get it from the line # - word := ( text OF line )[ start pos : end pos ]; - # get its replacement # - IF NOT find replacement( word, replacement, dictionary ) - THEN - # we don't already have a replacement for word # - # get one from the user and add it to the dictionary # - print( ( "What should replace ", word, "? " ) ); - read( ( replacement, newline ) ); - dictionary := HEAP REPLACEMENTLIST := ( word, replacement, dictionary ) - FI; - # replace with the replacement # - text OF line := ( text OF line )[ : start pos - 1 ] - + replacement - + ( text OF line )[ end pos + 1 : ] + # have a line of text - replace all the markers in it # + STRING word, replacement; + INT start pos, end pos; + WHILE char in string( "<", start pos, text OF line ) + AND char in string( ">", end pos, text OF line ) + DO + # have a marker, get it from the line # + word := ( text OF line )[ start pos : end pos ]; + # get its replacement # + IF NOT find replacement( word, replacement, dictionary ) + THEN + # we don't already have a replacement for word # + # get one from the user and add it to the dictionary # + print( ( "What should replace ", word, "? " ) ); + read( ( replacement, newline ) ); + dictionary := HEAP REPLACEMENTLIST := ( word, replacement, dictionary ) + FI; + # replace with the replacement # + text OF line := ( text OF line )[ : start pos - 1 ] + + replacement + + ( text OF line )[ end pos + 1 : ] + OD + OD; + + # print the story, ignoring the dummy element at the start # + + line := story text; + WHILE line := next OF line; + line ISNT nil stringlist + DO + print( ( text OF line, newline ) ) OD - OD; - # print the story, ignoring the dummy element at the start # - - line := story; - - WHILE line := next OF line; - line ISNT nil stringlist - DO - print( ( text OF line, newline ) ) - OD - -END; # story # - -main:( + END; # story # # we read the template from stand in (the keyboard unless it's been # # redirected) we could prompt the user for a template file name, # @@ -125,4 +113,4 @@ main:( print( ( "Please Enter the story template terminated by a blank line", newline ) ); story( stand in ) -) +END diff --git a/Task/Mad-Libs/EasyLang/mad-libs.easy b/Task/Mad-Libs/EasyLang/mad-libs.easy new file mode 100644 index 0000000000..3a604305d3 --- /dev/null +++ b/Task/Mad-Libs/EasyLang/mad-libs.easy @@ -0,0 +1,58 @@ +global name$[] out$[] . +func n2id n$ . + for id to len name$[] : if name$[id] = n$ : return id + name$[] &= n$ + return id +. +print "Enter a story template, terminated by an empty line:" +repeat + s$ = input + print s$ + until s$ = "" + for c$ in strchars s$ + if c$ = "<" + in = 1 + w$ = "" + elif c$ = ">" + in = 0 + id = n2id w$ + out$ &= "<" & id & ">" + elif in = 1 + w$ &= c$ + else + out$ &= c$ + . + . + out$[] &= out$ + out$ = "" +. +for i to len name$[] + write name$[i] & ": " + name$[i] = input + print name$[i] +. +print "" +for s$ in out$[] + for c$ in strchars s$ + if c$ = "<" + in = 1 + w$ = "" + elif c$ = ">" + in = 0 + write name$[number w$] + elif in = 1 + w$ &= c$ + else + write c$ + . + . + print "" +. +# +input_data + went for a walk in the park. +found a . decided to take it home. + +Monica +She +cockerel diff --git a/Task/Mad-Libs/F-Sharp/mad-libs.fs b/Task/Mad-Libs/F-Sharp/mad-libs.fs new file mode 100644 index 0000000000..6b4a70b9a6 --- /dev/null +++ b/Task/Mad-Libs/F-Sharp/mad-libs.fs @@ -0,0 +1,63 @@ +open System +open System.Collections.Generic +open System.Text + +type Template(s: string, d: Dictionary) = + let text = s + let substitutes = d + + new(s: string) = + let d = Dictionary() + + let rec collect (idx: int) = + let start_idx = s.IndexOf('<', idx) + + if start_idx = -1 then + () + else + let end_idx = s.IndexOf('>', start_idx) + + if end_idx = -1 then + failwith "Malformed input" + + d.TryAdd(s[start_idx..end_idx], "") |> ignore + collect (end_idx + 1) + + collect 0 + Template(s, d) + + override _.ToString() = + let mutable s = text + + for KeyValue (name, value) in substitutes do + if value = "" then + s <- s.Replace(name, name + ": ") + else + s <- s.Replace(name, value) + + s + + member _.AskForSubstitutes() = + for KeyValue (name, _) in substitutes do + printf $"Enter a {name}: " + let input = Console.ReadLine() + substitutes[name] <- input.Trim() + +let story = + let rec read (acc: StringBuilder) = + let line = Console.ReadLine() + + if line.Trim() = "" then + acc + else + acc.Append(line + "\n") |> ignore + read acc + + let mutable acc = StringBuilder() + printfn "Enter a multi-line story (finish with blank line):" + (read acc).ToString().Trim() + +let story_template = Template story +story_template.AskForSubstitutes() +printfn "\n" +printfn $"{story_template}" diff --git a/Task/Mad-Libs/Objeck/mad-libs.objeck b/Task/Mad-Libs/Objeck/mad-libs.objeck new file mode 100644 index 0000000000..7b99aec795 --- /dev/null +++ b/Task/Mad-Libs/Objeck/mad-libs.objeck @@ -0,0 +1,34 @@ +use Collection, Query.RegEx; + +class MadLibs { + function : Main(args : String[]) ~ Nil { + input : String; + if(args->Size() = 1) { + input := System.IO.Console->ReadLine(); + } + else { + input := " went for a walk in the park. found a . decided to take it home."; + }; + + replace_sets := Hash->New(); + results := Query.RegEx.RegEx->New("\\<(\\w| )*\\>")->Find(input); + each(result in results) { + temp_word := input->SubString(result->GetStart(), result->GetLength()); + if(<>replace_sets->Has(temp_word)) { + "What word would you like to use to replace '{$temp_word}'? "->Print(); + replace_word := System.IO.Console->ReadLine(); + replace_sets->Insert(temp_word, replace_word); + }; + }; + + replace_pairs := replace_sets->GetKeyValues()>; + each(replace_pair in replace_pairs) { + temp_word := replace_pair->GetFirst(); + replace_word := replace_pair->GetSecond(); + + input := input->ReplaceAll(temp_word, replace_word); + } + + input->PrintLine(); + } +} diff --git a/Task/Magic-8-ball/Crystal/magic-8-ball.cr b/Task/Magic-8-ball/Crystal/magic-8-ball.cr new file mode 100644 index 0000000000..63205eb273 --- /dev/null +++ b/Task/Magic-8-ball/Crystal/magic-8-ball.cr @@ -0,0 +1,13 @@ +answers = ["It is certain.", "It is decidedly so.", + "Without a doubt.", "Yes - definitely.", "You may rely on it.", + "As I see it, yes.", "Most likely.", "Outlook good.", + "Yes.", "Signs point to yes.", "Reply hazy, try again.", + "Ask again later.", "Better not tell you now.", "Cannot predict now.", + "Concentrate and ask again.", "Don't count on it.", "My reply is no.", + "My sources say no.", "Outlook not so good.", "Very doubtful."] + +loop do + print "Your question: "; STDOUT.flush + break if (gets || "").empty? + puts answers.sample +end diff --git a/Task/Magic-constant/ANSI-BASIC/magic-constant.basic b/Task/Magic-constant/ANSI-BASIC/magic-constant.basic new file mode 100644 index 0000000000..9a8dfd7b4f --- /dev/null +++ b/Task/Magic-constant/ANSI-BASIC/magic-constant.basic @@ -0,0 +1,25 @@ +100 REM Magic constant +110 DECLARE EXTERNAL FUNCTION A +120 DECLARE EXTERNAL FUNCTION InvA +130 PRINT "The first 20 magic constants are"; +140 FOR N = 1 TO 20 +150 PRINT A(N); +160 NEXT N +170 PRINT +180 PRINT "The 1,000th magic constant is"; A(1000) +190 LET E = 1 +200 FOR N = 1 TO 20 +210 LET E = E * 10 +220 PRINT "10^"; +230 PRINT USING "##: #########": N, InvA(E) +240 NEXT N +250 END +260 REM Returns the magic constant of a magic square of order N + 2 +270 EXTERNAL FUNCTION A(N) +280 LET N2 = N + 2 +290 LET A = IP((N2 * ((N2 * N2) + 1)) / 2) +300 END FUNCTION +310 REM Returns the order of the magic square whose magic constant is at least X +320 EXTERNAL FUNCTION InvA(X) +330 LET InvA = IP((2 * X) ^ (1 / 3)) + 1 +340 END FUNCTION diff --git a/Task/Magic-constant/C/magic-constant.c b/Task/Magic-constant/C/magic-constant.c new file mode 100644 index 0000000000..9d9f01ace2 --- /dev/null +++ b/Task/Magic-constant/C/magic-constant.c @@ -0,0 +1,32 @@ +/* Magic constant */ +#include +#include + +/* returns the magic constant of a magic square of order n + 2 */ +long a(int n) +{ + long n2 = n + 2; + return (n2 * ((n2 * n2) + 1)) / 2; +} + +/* returns the order of the magic square whose magic constant is at least x */ +long inv_a(double x) +{ + return (long)pow((2. * x), 1. / 3.) + 1; +} + +int main() +{ + int n; + double e = 1.; /* final values can be greater than MAX_LONG */ + printf("The first 20 magic constants are "); + for (n = 1; n <= 20; n++) + printf("%d ", a(n)); + printf("\n"); + printf("The 1,000th magic constant is %d\n", a(1000)); + for (n = 1; n <= 20; n++) + { + e *= 10; + printf("10^%2d: %9d\n", n, inv_a(e)); + } +} diff --git a/Task/Magic-constant/GW-BASIC/magic-constant.basic b/Task/Magic-constant/GW-BASIC/magic-constant.basic new file mode 100644 index 0000000000..f4e8107e76 --- /dev/null +++ b/Task/Magic-constant/GW-BASIC/magic-constant.basic @@ -0,0 +1,24 @@ +100 REM Magic constant +110 PRINT "First 20 magic constants:"; +120 FOR N = 3 TO 20 + 3 - 1 +130 PRINT (N * N * N + N) / 2; +140 NEXT N +150 PRINT +160 PRINT "1000th magic constant: "; +170 N# = 1000! + 3 - 1 +180 MC1000# = INT((N# * N# * N# + N#) / 2) +190 PRINT USING "#########"; MC1000# +200 PRINT "Smallest order magic square with a constant greater than:" +210 THRESH# = 10 +220 M# = 3 +230 FOR X = 1 TO 20 +240 MC# = (M# * M# * M# + M#) / 2 +250 M# = M# + 1 +260 IF MC# <= THRESH# THEN 240 +270 PRINT "10^"; +280 PRINT USING "##:"; X; +290 PRINT USING "########"; M# - 1; +300 THRESH# = THRESH# * 10 +310 IF X MOD 5 = O THEN PRINT ELSE PRINT "| "; +320 NEXT X +330 END diff --git a/Task/Magic-constant/Gambas/magic-constant.gambas b/Task/Magic-constant/Gambas/magic-constant.gambas new file mode 100644 index 0000000000..513345ac1f --- /dev/null +++ b/Task/Magic-constant/Gambas/magic-constant.gambas @@ -0,0 +1,35 @@ +Function a(n As Integer) As Long + + n += 2 + Return n * (n ^ 2 + 1) / 2 + +End Function + +Function inv_a(x As Float) As Long + + Dim k As Long = 0 + + While k * (k ^ 2 + 1) / 2 + 2 < x + k += 1 + Wend + Return k + +End Function + +Public Sub Main() + + Dim n As Long + + Print "The first 20 magic constants are: " + + For n = 1 To 20 + Print a(n); " "; + Next + Print + Print "The 1,000th magic constant is "; a(1000) + + For e As Integer = 1 To 20 + Print "10^"; Format(e, "##"); ": "; Format(inv_a(10 ^ e), "#########") + Next + +End Sub diff --git a/Task/Magic-constant/Modula-2/magic-constant.mod2 b/Task/Magic-constant/Modula-2/magic-constant.mod2 new file mode 100644 index 0000000000..36b207d7ef --- /dev/null +++ b/Task/Magic-constant/Modula-2/magic-constant.mod2 @@ -0,0 +1,46 @@ +MODULE MagicConstant; + +FROM STextIO IMPORT WriteString, WriteLn; +FROM SWholeIO IMPORT WriteInt; +FROM RealMath IMPORT exp, ln; + +VAR + N: CARDINAL; + E: REAL; + +(* Returns the magic constant of a magic square of order N + 2 *) +PROCEDURE A(N: CARDINAL): CARDINAL; +VAR + N2: CARDINAL; +BEGIN + N2 := N + 2; + RETURN (N2 * ((N2 * N2) + 1)) DIV 2 +END A; + +(* Returns the order of the magic square whose magic constant is at least X *) +PROCEDURE InvA(X: REAL): CARDINAL; +BEGIN + RETURN VAL(INTEGER, exp(ln((2. * X)) / 3.) + 1.) + (* Use of power(2. * X, 1. / 3.) + 1. does not give enough precision due to rounded exponent *) +END InvA; + +BEGIN + WriteString("The first 20 magic constants are "); + FOR N := 1 TO 20 DO + WriteInt(A(N), 1); + WriteString(" ") + END; + WriteLn; + WriteString("The 1,000th magic constant is "); + WriteInt(A(1000), 1); + WriteLn; + E := 1.; + FOR N := 1 TO 20 DO (* The results are equal to these from Mathematica for N <= 23 *) + E := E * 10.; + WriteString("10^"); + WriteInt(N, 2); + WriteString(": "); + WriteInt(InvA(E), 9); + WriteLn + END +END MagicConstant. diff --git a/Task/Magic-constant/PHP/magic-constant.php b/Task/Magic-constant/PHP/magic-constant.php new file mode 100644 index 0000000000..7ef4633870 --- /dev/null +++ b/Task/Magic-constant/PHP/magic-constant.php @@ -0,0 +1,27 @@ + diff --git a/Task/Magic-constant/REXX/magic-constant.rexx b/Task/Magic-constant/REXX/magic-constant.rexx new file mode 100644 index 0000000000..c83e1efb0e --- /dev/null +++ b/Task/Magic-constant/REXX/magic-constant.rexx @@ -0,0 +1,62 @@ +-- 8 May 2025 +include Settings + +say 'MAGIC CONSTANT' +say version +say +numeric digits 23 +call Getmagics 6e8 +call Task1 +call Task2 +call Task3 +exit + +Getmagics: +call Time('r') +arg xx +say 'Get magic constants up to' xx +say Magics(xx) 'collected' +say Format(Time('e'),,3) 'seconds' +say +return + +Task1: +call Time('r') +say 'The first 25 magic constants are' +do i = 3 to 28 + call Charout ,magi.i' ' +end +say +say Format(Time('e'),,3) 'seconds' +say +return + +Task2: +call Time('r') +say 'The 1000th magic constant is' +say magi.1002 +say Format(Time('e'),,3) 'seconds' +say +return + +Task3: +call Time('r') +say 'Smallest magic square with constant > 10^n is' +say Left('n',5) Right('order',8) +say '--------------' +e = 1 +do i = 3 to 6e7 + if Magic(i) > 1'E'e then do + say Left('10^'e,5) Right(i,8) + e = e+1 + end +end +say '--------------' +say Format(Time('e'),,3) 'seconds' +say +return + +include Functions +include Sequences +include Numbers +include Abend diff --git a/Task/Magic-constant/Tiny-BASIC/magic-constant.basic b/Task/Magic-constant/Tiny-BASIC/magic-constant.basic new file mode 100644 index 0000000000..8f80640163 --- /dev/null +++ b/Task/Magic-constant/Tiny-BASIC/magic-constant.basic @@ -0,0 +1,21 @@ +10 REM MAGIC CONSTANT +20 PRINT "FIRST 20 MAGIC CONSTANTS:" +30 LET N=3 +40 IF N>20+3-1 GOTO 80 +50 PRINT (N*N*N+N)/2, +60 LET N=N+1 +70 GOTO 40 +80 PRINT +90 PRINT "SMALLEST ORDER MAGIC SQUARE WITH A CONSTANT GREATER THAN:" +100 LET T=10 +110 LET M=3 +120 LET X=1 +130 LET L=(M*M*M+M)/2 +140 LET M=M+1 +150 IF L<=T GOTO 130 +160 PRINT "10^";X;":",M-1 +170 LET X=X+1 +180 IF X>4 GOTO 210 +190 LET T=T*10 +200 GOTO 130 +210 END diff --git a/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy b/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy index c13991f0c6..7f982d68fe 100644 --- a/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy +++ b/Task/Magic-squares-of-doubly-even-order/EasyLang/magic-squares-of-doubly-even-order.easy @@ -1,8 +1,6 @@ func[][] mkarr s . len q[][] s - for i = 1 to s - len q[i][] s - . + for i = 1 to s : len q[i][] s return q[][] . func[][] mk_oms s . @@ -12,13 +10,9 @@ func[][] mk_oms s . for p = 1 to s * s q[r][c] = p tc = c + 1 - if tc > s - tc = 1 - . + if tc > s : tc = 1 tr = r - 1 - if tr < 1 - tr = s - . + if tr < 1 : tr = s if q[tr][tc] <> 0 tc = c tr = r + 1 @@ -35,13 +29,9 @@ func[][] mk_dems s . for r = 1 to s for c = 1 to s sx = c mod 4 - if sx < 1 - sx = 4 - . + if sx < 1 : sx = 4 sy = r mod 4 - if sy < 1 - sy = 4 - . + if sy < 1 : sy = 4 if tmp[sy][sx] = 1 q[r][c] = n + 1 else @@ -52,5 +42,6 @@ func[][] mk_dems s . . return q[][] . -numfmt 0 2 -print mk_dems 8 +numfmt 2 0 +r[][] = mk_dems 8 +for i to len r[][] : print r[i][] diff --git a/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy b/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy index 2a148fff4f..4f029cbc2d 100644 --- a/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy +++ b/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy @@ -1,8 +1,8 @@ func f n x y . return (x + y * 2 + 1) mod n . -numfmt 0 3 -proc msqr n . . +numfmt 3 0 +proc msqr n . for i = 0 to n - 1 for j = 0 to n - 1 write f n (n - j - 1) i * n + f n j i + 1 diff --git a/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy b/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy index 6eaddd19df..f5c5f88fe9 100644 --- a/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy +++ b/Task/Magic-squares-of-singly-even-order/EasyLang/magic-squares-of-singly-even-order.easy @@ -1,8 +1,6 @@ func[][] mkarr s . len q[][] s - for i = 1 to s - len q[i][] s - . + for i = 1 to s : len q[i][] s return q[][] . func[][] mk_oms s . @@ -12,13 +10,9 @@ func[][] mk_oms s . for p = 1 to s * s q[r][c] = p tc = c + 1 - if tc > s - tc = 1 - . + if tc > s : tc = 1 tr = r - 1 - if tr < 1 - tr = s - . + if tr < 1 : tr = s if q[tr][tc] <> 0 tc = c tr = r + 1 @@ -59,5 +53,6 @@ func[][] mk_sems s . . return q[][] . -numfmt 0 2 -print mk_sems 6 +numfmt 2 0 +r[][] = mk_sems 6 +for i to len r[][] : print r[i][] diff --git a/Task/Magnanimous-numbers/EasyLang/magnanimous-numbers.easy b/Task/Magnanimous-numbers/EasyLang/magnanimous-numbers.easy index 10295a4f34..8d06c1bc1f 100644 --- a/Task/Magnanimous-numbers/EasyLang/magnanimous-numbers.easy +++ b/Task/Magnanimous-numbers/EasyLang/magnanimous-numbers.easy @@ -1,40 +1,30 @@ fastfunc isprim num . - if num < 2 - return 0 - . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . func ismagnan n . - if n < 10 - return 1 - . + if n < 10 : return 1 p = 10 repeat q = n div p r = n mod p - if isprim (q + r) = 0 - return 0 - . + if isprim (q + r) = 0 : return 0 until q < 10 p *= 10 . return 1 . -proc magnan start stop . . +proc magnan start stop . write start & "-" & stop & ":" while count < stop if ismagnan i = 1 count += 1 - if count >= start - write " " & i - . + if count >= start : write " " & i . i += 1 . diff --git a/Task/Magnanimous-numbers/REXX/magnanimous-numbers.rexx b/Task/Magnanimous-numbers/REXX/magnanimous-numbers.rexx index 174e6fca70..d03e5d56c6 100644 --- a/Task/Magnanimous-numbers/REXX/magnanimous-numbers.rexx +++ b/Task/Magnanimous-numbers/REXX/magnanimous-numbers.rexx @@ -1,45 +1,30 @@ -/*REXX pgm finds/displays magnanimous #s (#s with a inserted + sign to sum to a prime).*/ -parse arg bet.1 bet.2 bet.3 highP . /*obtain optional arguments from the CL*/ -if bet.1=='' | bet.1=="," then bet.1= 1..45 /* " " " " " " */ -if bet.2=='' | bet.2=="," then bet.2= 241..250 /* " " " " " " */ -if bet.3=='' | bet.3=="," then bet.3= 391..400 /* " " " " " " */ -if highP=='' | highP=="," then highP= 1000000 /* " " " " " " */ -call genP /*gen primes up to highP (1 million).*/ +-- 22 Mar 2025 +include Settings - do j=1 for 3 /*process three magnanimous "ranges". */ - parse var bet.j LO '..' HI /*obtain the first range (if any). */ - if HI=='' then HI= LO /*Just a single number? Then use LO. */ - if HI==0 then iterate /*Is HI a zero? Then skip this range.*/ - finds= 0; $= /*#: magnanimous # cnt; $: is a list*/ - do k=0 until finds==HI /* [↓] traipse through the number(s). */ - if \magna(k) then iterate /*Not magnanimous? Then skip this num.*/ - finds= finds + 1 /*bump the magnanimous number count. */ - if finds>=LO then $= $ k /*In range► Then add number ──► $ list*/ - end /*k*/ - say - say center(' 'LO "──►" HI 'magnanimous numbers ', 126, "─") - say strip($) - end /*j*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -magna: procedure expose @. !.; parse arg x 1 L 2 '' -1 R /*obtain #, 1st & last digit.*/ - len= length(x); if len==1 then return 1 /*one digit #s are magnanimous*/ - if x>1001 then if L//2 == R//2 then return 0 /*Has parity? Not magnanimous*/ - do s= 1 for len-1 /*traipse thru #, inserting + */ - parse var x y +(s) z; sum= y + z /*parse 2 parts of #, sum 'em.*/ - if !.sum then iterate /*Is sum prime? So far so good*/ - else return 0 /*Nope? Then not magnanimous.*/ - end /*s*/ - return 1 /*Pass all the tests, it's magnanimous.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*assign low primes; # primes.*/ - !.= 0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1 /* " semaphores to " */ - #= 6; sq.#= @.# ** 2 /*# primes so far; P squared.*/ - do j=@.#+4 by 2 to highP; parse var j '' -1 _; if _==5 then iterate /*÷ by 5?*/ - if j// 3==0 then iterate; if j// 7==0 then iterate /*÷ by 3?; ÷ by 7?*/ - if j//11==0 then iterate /*" " 11? " " 13?*/ - do k=6 while sq.k<=j /*divide by some generated odd primes. */ - if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - #= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump #Ps; P──►@.assign P; P^2; P flag*/ - end /*j*/; return +say 'MAGNANIMOUS NUMBERS' +say version +say +call Magnanimouss 1e6 +call Range 1 45 +call Range 241 250 +call Range 391 400 +call Range 430 999 +say Time('e')/1 'seconds' +exit + +Range: +procedure expose magn. +arg xx yy +if yy = '' then + yy = xx +say 'The Magnanimous numbers from no' xx 'up to' yy 'are' +do i = xx to Min(yy,magn.0) + call Charout ,magn.i' ' +end +say; say +return + +include Sequences +include Numbers +include Functions +include Abend diff --git a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy index d5e23ca019..d5dae7370f 100644 --- a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy +++ b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy @@ -1,21 +1,19 @@ +# Mandelbrot +# res = 4 maxiter = 200 -# -# better but slower: -# res = 8 -# maxiter = 300 -# +# better but slower: res = 8 maxiter = 300 # mid = res * 50 center_x = 3 * mid / 2 center_y = mid scale = mid # -background 000 -textsize 2 +gbackground 000 +gtextsize 2 # -fastfunc iter cx cy maxiter . - while xx + yy < 4 and it < maxiter +fastfunc iter cx cy max . + while xx + yy < 4 and it < max y = 2 * x * y + cy x = xx - yy + cx xx = x * x @@ -24,39 +22,44 @@ fastfunc iter cx cy maxiter . . return it . -proc draw . . - clear +proc draw . + gclear for scr_y = 0 to 2 * mid - 1 cy = (scr_y - center_y) / scale for scr_x = 0 to 2 * mid - 1 cx = (scr_x - center_x) / scale it = iter cx cy maxiter if it < maxiter - color3 it / 20 it / 100 it / 150 - move scr_x / res scr_y / res - rect 1 / res 1 / res + gcolor3 it / 20 it / 100 it / 150 + grect scr_x / res scr_y / res 1 / res 1 / res . . . - color 990 - move 1 1 - text "Short press to zoom in, long to zoom out" + gcolor 990 + gtext 1 1 "Short press to zoom in, long to zoom out" . -on mouse_down - time0 = systime -. -on mouse_up - center_x += mid - mouse_x * res - center_y += mid - mouse_y * res - if systime - time0 < 0.3 - center_x -= mid - center_x - center_y -= mid - center_y - scale *= 2 - else +on timer + if done = 0 center_x += (mid - center_x) * 3 / 4 center_y += (mid - center_y) * 3 / 4 scale /= 4 + draw + done = 1 + . +. +on mouse_down + done = 0 + center_x += mid - mouse_x * res + center_y += mid - mouse_y * res + timer 0.3 +. +on mouse_up + if done = 0 + center_x -= mid - center_x + center_y -= mid - center_y + scale *= 2 + draw + done = 1 . - draw . draw diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl b/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl index ee9e72e8f7..2dc45623ad 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl @@ -1,3 +1,4 @@ +using Base.Threads using Plots gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) @@ -26,21 +27,45 @@ end x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) -A, B = collect(x) .* pi, collect(y) .* pi -C = 8.0 .* exp.((A' .+ B .* im) .* im) +A, B = collect(Float64, x) .* pi, collect(Float64, y) .* pi +C = (- 8.0) .* exp.((A' .+ B .* im) .* im) -E, Z, dZ = zero(C), zero(C), zero(C) -D, I, J = zeros(size(C)), ones(Int64, size(C)), ones(Int64, size(C)) +function iteration(C) + E, I, J = zero(C), ones(Int64, size(C)), ones(Int64, size(C)) + Z, dZ = zero(C), zero(C) -for k in 1:n - M, R = abs2.(Z) .< abs2(r), abs2.(Z) .< abs2.(E) - E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero - E[M], I[M] = (2 .* S[I[M]] .+ E[M]) .* E[M] .+ C[M], I[M] .+ 1 - Z[M], dZ[M] = S[I[M]] .+ E[M], 2 .* Z[M] .* dZ[M] .+ 1 + function iterate(E, I, Z, dZ, C) + E, I = (2 .* S[I] .+ E) .* E .+ C, I .+ 1 + Z, dZ = S[I] .+ E, 2 .* Z .* dZ .+ 1 + return E, I, Z, dZ + end + + for k in 1:n + M = abs2.(Z) .< abs2.(E) + E[M], I[M] = Z[M], J[M] # rebase when z is closer to zero + M = abs2.(Z) .< abs2(r) + E[M], I[M], Z[M], dZ[M] = iterate(E[M], I[M], Z[M], dZ[M], C[M]) + end + + return E, I, Z, dZ end +function calculation(C) + E, I = zero(C), ones(Int64, size(C)) + Z, dZ = zero(C), zero(C) + + @threads for j in 1:size(C)[2] + E[:,j], I[:,j], Z[:,j], dZ[:,j] = iteration(C[:,j]) + end + + return E, I, Z, dZ +end + +E, I, Z, dZ = calculation(C) +D = zeros(Float64, size(C)) + N = abs.(Z) .> 2 # exterior distance estimation D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) -heatmap(D' .^ 0.015, c=:nipy_spectral) +heatmap(D' .^ 0.015, c=:gist_ncar) savefig("Mercator_Mandelbrot_deep_map.png") diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-8.py b/Task/Mandelbrot-set/Python/mandelbrot-set-8.py index 09666f5ed1..d4580ac79d 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-8.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-8.py @@ -1,10 +1,11 @@ import numpy as np +import numba as nb import matplotlib.pyplot as plt import decimal as dc # decimal floating point arithmetic with arbitrary precision dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits) -d, h = 50, 1000 # pixel density (= image width) and image height +d, h = 100, 2000 # pixel density (= image width) and image height n, r = 80000, 100000 # number of iterations and escape radius (r > 2) a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291") @@ -15,8 +16,8 @@ u, v = dc.Decimal(0), dc.Decimal(0) for k in range(n+1): S[k] = float(u) + float(v) * 1j - if u ** 2 + v ** 2 < r ** 2: - u, v = u ** 2 - v ** 2 + a, 2 * u * v + b + if u * u + v * v < r * r: + u, v = u * u - v * v + a, 2 * u * v + b else: print("The reference sequence diverges within %s iterations." % k) break @@ -25,20 +26,43 @@ x = np.linspace(0, 2, num=d+1, dtype=np.float64) y = np.linspace(0, 2 * h / d, num=h+1, dtype=np.float64) A, B = np.meshgrid(x * np.pi, y * np.pi) -C = 8.0 * np.exp((A + B * 1j) * 1j) +C = (- 8.0) * np.exp((A + B * 1j) * 1j) -E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) -D, I, J = np.zeros(C.shape), np.zeros(C.shape, dtype=np.int64), np.zeros(C.shape, dtype=np.int64) +@nb.njit(parallel=True) +def calculation(C): + E, I = np.zeros_like(C), np.zeros(C.shape, dtype=np.int64) + Z, dZ = np.zeros_like(C), np.zeros_like(C) -for k in range(n): - Z2 = Z.real ** 2 + Z.imag ** 2 - M, R = Z2 < r ** 2, Z2 < E.real ** 2 + E.imag ** 2 - E[R], I[R] = Z[R], J[R] # rebase when z is closer to zero - E[M], I[M] = (2 * S[I[M]] + E[M]) * E[M] + C[M], I[M] + 1 - Z[M], dZ[M] = S[I[M]] + E[M], 2 * Z[M] * dZ[M] + 1 + def iteration(C): + E, I = np.zeros_like(C), np.zeros(C.shape, dtype=np.int64) + Z, dZ = np.zeros_like(C), np.zeros_like(C) + + def abs2(z): + return z.real * z.real + z.imag * z.imag + + def iterate(E, I, Z, dZ, C): + E, I = (2 * S[I] + E) * E + C, I + 1 + Z, dZ = S[I] + E, 2 * Z * dZ + 1 + return E, I, Z, dZ + + for k in range(n): + M = abs2(Z) < abs2(E) + E[M], I[M] = Z[M], 0 # rebase when z is closer to zero + M = abs2(Z) < abs2(r) + E[M], I[M], Z[M], dZ[M] = iterate(E[M], I[M], Z[M], dZ[M], C[M]) + + return E, I, Z, dZ + + for j in nb.prange(C.shape[1]): + E[:,j], I[:,j], Z[:,j], dZ[:,j] = iteration(C[:,j]) + + return E, I, Z, dZ + +E, I, Z, dZ = calculation(C) +D = np.zeros(C.shape, dtype=np.float64) N = abs(Z) > 2 # exterior distance estimation D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) -plt.imshow(D.T ** 0.015, cmap=plt.cm.nipy_spectral, origin="lower") +plt.imshow(D.T ** 0.015, cmap=plt.cm.gist_ncar, origin="lower") plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200) diff --git a/Task/Map-range/ANSI-BASIC/map-range.basic b/Task/Map-range/ANSI-BASIC/map-range.basic new file mode 100644 index 0000000000..a78bcc8db9 --- /dev/null +++ b/Task/Map-range/ANSI-BASIC/map-range.basic @@ -0,0 +1,10 @@ +100 REM Map range +110 DECLARE EXTERNAL FUNCTION MapRange +120 FOR I = 0 TO 10 +130 PRINT USING "## maps to ##.#": I, MapRange(I, 0, 10, -1, 0) +140 NEXT I +150 END +160 REM ***************************************** +170 EXTERNAL FUNCTION MapRange(S, A1, A2, B1, B2) +180 LET MapRange = B1 + (S - A1) * (B2 - B1) / (A2 - A1) +190 END FUNCTION diff --git a/Task/Map-range/Free-Pascal-Lazarus/map-range-1.pas b/Task/Map-range/Free-Pascal-Lazarus/map-range-1.pas new file mode 100644 index 0000000000..c4291235b1 --- /dev/null +++ b/Task/Map-range/Free-Pascal-Lazarus/map-range-1.pas @@ -0,0 +1,13 @@ +Program Map(output); + function MapRange(fromRange, toRange: array of real; value: real): real; + begin + MapRange := (value - fromRange[0]) * (toRange[1] - toRange[0]) / + (fromRange[1] - fromRange[0]) + toRange[0]; + end; + +var + i: integer; +begin + for i := 0 to 10 do + writeln(i: 2, ' maps to: ', MapRange([0.0, 10.0], [-1.0, 0.0], i): 5: 2); +end. diff --git a/Task/Map-range/Free-Pascal-Lazarus/map-range-2.pas b/Task/Map-range/Free-Pascal-Lazarus/map-range-2.pas new file mode 100644 index 0000000000..b2f292aaac --- /dev/null +++ b/Task/Map-range/Free-Pascal-Lazarus/map-range-2.pas @@ -0,0 +1,58 @@ +Program Map(output); + +type + real = double; + tRange = array [0..1] of real; + + tMapRec = record + mrFrom, + mrTo: tRange; + mrScale: real + end; + + function InitRange(rfrom, rTo: real): tRange; + begin + InitRange[0] := rfrom; + InitRange[1] := rTo; + end; + + function InitMapRec(const fromRange, toRange: tRange): tMapRec; + begin + with InitMapRec do + begin + mrFrom := fromRange; + mrTo := toRange; + mrScale := (toRange[1] - toRange[0]) / (fromRange[1] - fromRange[0]); + end; + end; + + function MapRecRange(const value: real; var MR: tMapRec): real; + begin + with MR do + MapRecRange := (value - mrFrom[0]) * mrScale + mrTo[0]; + end; + + function MapRange(const value: real; const fromRange, toRange: tRange): real; + begin + MapRange := (value - fromRange[0]) * (toRange[1] - toRange[0]) / + (fromRange[1] - fromRange[0]) + toRange[0]; + end; + +var + value: real; + rFrom, rTo: tRange; + mr: tMapRec; + i: longint; + +begin + rFrom := InitRange(0, 10); + rTo := InitRange(-1, 0); + mr := InitMapRec(rFrom, rTo); + + for i := 0 to 10 do + begin + value := i; + writeln(i: 4, ' maps to: ', MapRange(value, rFrom, rTo): 10: 6, + MapRecRange(value, mr): 10: 6); + end; +end. diff --git a/Task/Map-range/GW-BASIC/map-range.basic b/Task/Map-range/GW-BASIC/map-range.basic new file mode 100644 index 0000000000..f1129818c2 --- /dev/null +++ b/Task/Map-range/GW-BASIC/map-range.basic @@ -0,0 +1,13 @@ +100 REM Map range +110 DEF FN MR(S) = B1 + (S - A1) * (B2 - B1) / (A2 - A1) +120 A1 = 0: A2 = 10: B1 = -1: B2 = 0 +130 FOR X = A1 TO A2 STEP 2 +140 PRINT USING "## maps to ##.#"; X; FN MR(X) +150 NEXT X +160 REM Inverse mapping to illustrate change of parameters +170 PRINT: PRINT "Inverse mapping:" +180 A1 = -1: A2 = 0: B1 = 0: B2 = 10 +190 FOR X = A1 TO A2 STEP .2 +200 PRINT USING "##.# maps to ##"; X; FN MR(X) +210 NEXT X +220 END diff --git a/Task/Map-range/Liberty-BASIC/map-range.basic b/Task/Map-range/Liberty-BASIC/map-range.basic index 8c6669ef67..5d604e7876 100644 --- a/Task/Map-range/Liberty-BASIC/map-range.basic +++ b/Task/Map-range/Liberty-BASIC/map-range.basic @@ -1,8 +1,10 @@ -For i = 0 To 10 - Print "f(";i;") maps to ";mapToRange(i, 0, 10, -1, 0) -Next i -End +' map range +for i = 0 to 10 + print using("##.#", i); " maps to "; + print using("##.#", mapRange(i, 0, 10, -1, 0)) +next i +end -Function mapToRange(value, inputMin, inputMax, outputMin, outputMax) - mapToRange = (((value - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin -End Function +function mapRange(s, a1, a2, b1, b2) + mapRange = b1 + (s - a1) * (b2 - b1) / (a2 - a1) +end function diff --git a/Task/Map-range/Modula-2/map-range.mod2 b/Task/Map-range/Modula-2/map-range.mod2 new file mode 100644 index 0000000000..8ee51378e0 --- /dev/null +++ b/Task/Map-range/Modula-2/map-range.mod2 @@ -0,0 +1,22 @@ +MODULE MapRange; + +FROM STextIO IMPORT WriteLn, WriteString; +FROM SWholeIO IMPORT WriteInt; +FROM SRealIO IMPORT WriteFixed; + +VAR + I: INTEGER; + +PROCEDURE MapRange(S, A1, A2, B1, B2: REAL): REAL; +BEGIN + RETURN B1 + (S - A1) * (B2 - B1) / (A2 - A1) +END MapRange; + +BEGIN + FOR I := 0 TO 10 DO + WriteInt(I, 2); + WriteString(" maps to "); + WriteFixed(MapRange(FLOAT(I), 0., 10., -1., 0.), 1, 4); + WriteLn; + END; +END MapRange. diff --git a/Task/Map-range/PHP/map-range.php b/Task/Map-range/PHP/map-range.php new file mode 100644 index 0000000000..90f7f1821b --- /dev/null +++ b/Task/Map-range/PHP/map-range.php @@ -0,0 +1,15 @@ + diff --git a/Task/Map-range/Pascal/map-range-1.pas b/Task/Map-range/Pascal/map-range-1.pas deleted file mode 100644 index 33e3a87d57..0000000000 --- a/Task/Map-range/Pascal/map-range-1.pas +++ /dev/null @@ -1,13 +0,0 @@ -Program Map(output); - -function MapRange(fromRange, toRange: array of real; value: real): real; - begin - MapRange := (value-fromRange[0]) * (toRange[1]-toRange[0]) / (fromRange[1]-fromRange[0]) + toRange[0]; - end; - -var - i: integer; -begin - for i := 0 to 10 do - writeln (i, ' maps to: ', MapRange([0.0, 10.0], [-1.0, 0.0], i):4:2); -end. diff --git a/Task/Map-range/Pascal/map-range-2.pas b/Task/Map-range/Pascal/map-range-2.pas deleted file mode 100644 index ce16131c1b..0000000000 --- a/Task/Map-range/Pascal/map-range-2.pas +++ /dev/null @@ -1,56 +0,0 @@ -Program Map(output); - -type - real = double; - tRange = Array [0..1] of real; - tMapRec = record - mrFrom, - mrTo : tRange; - mrScale : real - end; - -function InitRange(rfrom,rTo:real):tRange; -begin - InitRange[0] :=rfrom; - InitRange[1] :=rTo; -end; - -function InitMapRec(const fromRange, toRange: tRange):tMapRec; -begin - With InitMapRec do - Begin - mrFrom := fromRange; - mrTo := toRange; - mrScale := (toRange[1]-toRange[0]) / (fromRange[1]-fromRange[0]); - end; -end; - -function MapRecRange(const value: real;var MR :tMapRec): real; -begin - with MR do - MapRecRange := (value-mrFrom[0]) * mrScale + mrTo[0]; -end; - -function MapRange(const value: real;const fromRange, toRange: tRange): real; -begin - MapRange := (value-fromRange[0]) * (toRange[1]-toRange[0]) / (fromRange[1]-fromRange[0]) + toRange[0]; -end; - -var - value:real; - rFrom,rTo : tRange; - mr : tMapRec; - i: LongInt; - -begin - rFrom:= InitRange( 0, 10); - rTo := InitRange( -1, 0); - mr:= InitMapRec(rFrom,rTo); - - for i := 0 to 10 do - Begin - value := i; - writeln (i:4, ' maps to: ', MapRange(value,rFrom, rTo):10:6, - MapRecRange(value,mr):10:6); - end; -end. diff --git a/Task/Map-range/QBasic/map-range.basic b/Task/Map-range/QBasic/map-range.basic new file mode 100644 index 0000000000..d9f3d649fe --- /dev/null +++ b/Task/Map-range/QBasic/map-range.basic @@ -0,0 +1,10 @@ +REM Map range +DECLARE FUNCTION MapRange (S, A1, A2, B1, B2) +FOR I = 0 TO 10 + PRINT USING "## maps to ##.#"; I; MapRange(I, 0, 10, -1, 0) +NEXT I +END + +FUNCTION MapRange (S, A1, A2, B1, B2) + MapRange = B1 + (S - A1) * (B2 - B1) / (A2 - A1) +END FUNCTION diff --git a/Task/Map-range/RapidQ/map-range.rapidq b/Task/Map-range/RapidQ/map-range.rapidq new file mode 100644 index 0000000000..79151aad00 --- /dev/null +++ b/Task/Map-range/RapidQ/map-range.rapidq @@ -0,0 +1,11 @@ +' Map range +DECLARE FUNCTION MapRange (S#, A1#, A2#, B1#, B2#) AS DOUBLE +FOR I = 0 TO 10 + PRINT FORMAT$("%4.1f", I); " maps to "; + PRINT FORMAT$("%4.1f", MapRange(I, 0, 10, -1, 0)) +NEXT I +END + +FUNCTION MapRange (S#, A1#, A2#, B1#, B2#) AS DOUBLE + MapRange = B1# + (S# - A1#) * (B2# - B1#) / (A2# - A1#) +END FUNCTION diff --git a/Task/Map-range/TypeScript/map-range.ts b/Task/Map-range/TypeScript/map-range.ts new file mode 100644 index 0000000000..5eb4f6f01b --- /dev/null +++ b/Task/Map-range/TypeScript/map-range.ts @@ -0,0 +1,14 @@ +function mapRange( + a: number[], + b: number[], + s: number +): number { + return b[0] + (s-a[0]) * (b[1]-b[0]) / (a[1]-a[0]); +} + +const a = [0, 10]; +const b = [-1, 0]; + +for (let s = 0; s < 11; s++) { + console.log(`${s} -> ${mapRange(a, b, s)}`); +} diff --git a/Task/Mastermind/EasyLang/mastermind.easy b/Task/Mastermind/EasyLang/mastermind.easy index 0ad14ab4a5..b67a1981c7 100644 --- a/Task/Mastermind/EasyLang/mastermind.easy +++ b/Task/Mastermind/EasyLang/mastermind.easy @@ -1,94 +1,75 @@ -# Mastermind:w90 -# col[] = [ 802 990 171 229 950 808 ] len code[] 4 len guess[] 4 +row = 0 # -subr init_vars - row = 0 -. -proc draw_rate r black white . . - for j range0 2 - for c range0 2 - move c * 3.5 + 71.5 r * 11.5 + 9.4 - j * 3.5 - if black > 0 - color 000 - circle 1.4 - black -= 1 - elif white > 0 - color 999 - circle 1.4 - white -= 1 - else - color 310 - circle 0.7 - . +proc draw_rate r black white . + for j range0 2 : for c range0 2 + x = c * 3.5 + 71.5 + y = r * 11.5 + 9.4 - j * 3.5 + if black > 0 + gcolor 000 + gcircle x y 1.4 + black -= 1 + elif white > 0 + gcolor 999 + gcircle x y 1.4 + white -= 1 + else + gcolor 310 + gcircle x y 0.7 . . . -proc show_code . . - color 531 - move 22 92 - rect 46 8 +proc show_code . + gcolor 531 + grect 22 92 46 8 for i to 4 - move i * 8 + 20 97 - color col[code[i]] - circle 2 + gcolor col[code[i]] + gcircle i * 8 + 20 97 2 . . -proc draw_guess . . +proc draw_guess . for c to 4 - move c * 12 + 8 row * 11.5 + 7.5 - color col[guess[c]] - circle 3.8 + gcolor col[guess[c]] + gcircle c * 12 + 8 row * 11.5 + 7.5 3.8 . . -proc next_row . . - color 420 - linewidth 11 - move 17 row * 11.5 + 7.5 - line 60 row * 11.5 + 7.5 +proc next_row . + gcolor 420 + glinewidth 11 + gline 17 row * 11.5 + 7.5 60 row * 11.5 + 7.5 draw_guess - move 73.5 row * 11.5 + 7.5 - color 310 - circle 5.0 - color 753 - move 71.5 row * 11.5 + 5 - textsize 7 - text "✓" + gcolor 310 + gcircle 73.5 row * 11.5 + 7.5 5.0 + gcolor 753 + gtextsize 7 + gtext 71.5 row * 11.5 + 5 "✓" . -proc rate . . - move 73.5 row * 11.5 + 7.5 - color 531 - circle 5.2 +proc rate . + gcolor 531 + gcircle 73.5 row * 11.5 + 7.5 5.2 c[] = code[] g[] = guess[] - for i to 4 - if c[i] = g[i] - black += 1 - c[i] = -1 - g[i] = -2 - . + for i to 4 : if c[i] = g[i] + black += 1 + c[i] = -1 + g[i] = -2 . - for i to 4 - for j to 4 - if c[i] = g[j] - white += 1 - c[i] = -1 - g[j] = -2 - . + for i to 4 : for j to 4 + if c[i] = g[j] + white += 1 + c[i] = -1 + g[j] = -2 . . draw_rate row black white - color 531 - linewidth 12 - move 17 row * 11.5 + 7.5 - line 60 row * 11.5 + 7.5 + gcolor 531 + glinewidth 12 + gline 17 row * 11.5 + 7.5 60 row * 11.5 + 7.5 draw_guess row += 1 - if black = 4 - row = 8 - . + if black = 4 : row = 8 if row = 8 show_code timer 2 @@ -97,42 +78,32 @@ proc rate . . . . on timer - row = -2 + row = -1 . -proc new . . - init_vars - for i to 4 - code[i] = random 6 - . - color 531 - move 10 10 - rect 70 80 - linewidth 10 - move 5 95 - line 5 5 - line 85 5 - line 85 95 - line 5 95 - color 310 - linewidth 7 - move 28 96.5 - line 58 96.5 - move 30 95 - color 864 - textsize 4 - text "Mastermind" - color 310 - linewidth 0.5 - move 10 90 - line 10 4 - move 67 90 - line 67 4 - move 80 90 - line 80 4 +proc new . + row = 0 + for i to 4 : code[i] = random 6 + gcolor 531 + grect 10 10 70 80 + glinewidth 10 + gline 5 95 5 5 + gline 5 5 85 5 + gline 85 5 85 95 + gline 85 95 5 95 + gcolor 310 + glinewidth 7 + gline 28 96.5 58 96.5 + gcolor 864 + gtextsize 4 + gtext 30 95 "Mastermind" + gcolor 310 + glinewidth 0.5 + gline 10 90 10 4 + gline 67 90 67 4 + gline 80 90 80 4 for r range0 8 for c range0 4 - move c * 12 + 20 r * 11.5 + 7.5 - circle 2 + gcircle c * 12 + 20 r * 11.5 + 7.5 2 . draw_rate r 0 0 . @@ -142,13 +113,13 @@ proc new . . guess[4] = 2 next_row . -proc do_move . . +proc do_move . c = (mouse_x - 15) div 12 guess[c + 1] = guess[c + 1] mod 6 + 1 draw_guess . on mouse_down - if row = -2 + if row = -1 new elif mouse_y > row * 11.5 + 0.5 and mouse_y < row * 11.5 + 10.5 and row < 8 if mouse_x > 15 and mouse_x < 61 diff --git a/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy b/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy index 091dd80778..5c013f5f84 100644 --- a/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy +++ b/Task/Matrix-chain-multiplication/EasyLang/matrix-chain-multiplication.easy @@ -1,5 +1,5 @@ global m[][] s[][] dims[] . -proc mat_chain_order . . +proc mat_chain_order . n = len dims[] - 1 m[][] = [ ] ; len m[][] n s[][] = [ ] ; len s[][] n @@ -27,7 +27,7 @@ func$ path a b . . return "(" & path a s[a][b] & path (s[a][b] + 1) b & ")" . -proc pr_chain_order . . +proc pr_chain_order . print "Order : " & path 1 len s[][] . dims[][] = [ [ 5 6 3 1 ] [ 1 5 25 30 100 70 2 1 100 250 1 1000 2 ] [ 1000 1 500 12 1 700 2500 3 2 5 14 10 ] ] diff --git a/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb b/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb index f86de4287d..89d5caa161 100644 --- a/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb +++ b/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb @@ -7,13 +7,21 @@ matrix2(0,0) = 9 : matrix2(0,1) = 2 : matrix2(0,2) = 1 matrix2(1,0) = -7 : matrix2(1,1) = 3 : matrix2(1,2) = -10 matrix2(2,0) = 4 : matrix2(2,1) = 5 : matrix2(2,2) = -6 -Call multiply_matrix(matrix1,matrix2) +function getMatrixProduct(firstMatrix,secondMatrix) + if ubound(firstMatrix,2) <> ubound(secondMatrix,1) then exit function + redim resultMatrix(ubound(firstMatrix,1),ubound(secondMatrix,2)) + for i = 0 to ubound(firstMatrix,1) : for j = 0 to ubound(secondMatrix,2) : for k = 0 to ubound(firstMatrix,2) + resultMatrix(i,j) = resultMatrix(i,j) + (firstMatrix(i,k) * secondMatrix(k,j)) + next : next : next + getMatrixProduct = resultMatrix +End function -Sub multiply_matrix(arr1,arr2) - For i = 0 To UBound(arr1) - For j = 0 To 2 - WScript.StdOut.Write (arr1(i,j) * arr2(i,j)) & vbTab - Next - WScript.StdOut.WriteLine - Next -End Sub +dim resultMatrix : resultMatrix = getMatrixProduct(matrix1,matrix2) +dim outputString +for a = 0 to ubound(resultMatrix,1) + for b = 0 to ubound(resultMatrix,2) + outputString = outputString & resultMatrix(a,b) & vbTab + next + outputString = outputString & vbCrlf +next +msgbox outputString diff --git a/Task/Matrix-transposition/EasyLang/matrix-transposition.easy b/Task/Matrix-transposition/EasyLang/matrix-transposition.easy index 2fa5821aa3..2e997c99c4 100644 --- a/Task/Matrix-transposition/EasyLang/matrix-transposition.easy +++ b/Task/Matrix-transposition/EasyLang/matrix-transposition.easy @@ -1,4 +1,4 @@ -proc transpose . m[][] . +proc transpose &m[][] . len n[][] len m[1][] for i to len n[][] for j to len m[][] diff --git a/Task/Matrix-transposition/Uiua/matrix-transposition.uiua b/Task/Matrix-transposition/Uiua/matrix-transposition.uiua new file mode 100644 index 0000000000..115cea314a --- /dev/null +++ b/Task/Matrix-transposition/Uiua/matrix-transposition.uiua @@ -0,0 +1,2 @@ +$matrix°△2_5 +$transposed⊸⍉ diff --git a/Task/Mayan-numerals/EasyLang/mayan-numerals.easy b/Task/Mayan-numerals/EasyLang/mayan-numerals.easy index 55ec0fd97a..60ebc7b13a 100644 --- a/Task/Mayan-numerals/EasyLang/mayan-numerals.easy +++ b/Task/Mayan-numerals/EasyLang/mayan-numerals.easy @@ -1,7 +1,5 @@ func[] base20 n . - if n < 20 - return [ n ] - . + if n < 20 : return [ n ] r[] = base20 (n div 20) r[] &= n mod 20 return r[] @@ -24,13 +22,11 @@ func$[] mayan d . . return r$[] . -proc drawma . mayans$[][] . +proc drawma &mayans$[][] . idx = len mayans$[][] write "╔" for i to idx - for j to 4 - write "═" - . + for j to 4 : write "═" if i < idx write "╦" else @@ -39,16 +35,12 @@ proc drawma . mayans$[][] . . for i to 4 write "║" - for j to idx - write mayans$[j][i] & "║" - . + for j to idx : write mayans$[j][i] & "║" print "" . write "╚" for i to idx - for j to 4 - write "═" - . + for j to 4 : write "═" if i < idx write "╩" else diff --git a/Task/Maze-generation/EasyLang/maze-generation.easy b/Task/Maze-generation/EasyLang/maze-generation.easy index cc5c352028..7481497c93 100644 --- a/Task/Maze-generation/EasyLang/maze-generation.easy +++ b/Task/Maze-generation/EasyLang/maze-generation.easy @@ -3,23 +3,23 @@ n = 2 * size + 1 f = 100 / (n - 0.5) len m[] n * n # -background 000 -proc show_maze . . - clear +gbackground 000 +proc show_maze . + gclear + sz = f * 1.5 + f2 = f / 2 for i = 1 to len m[] if m[i] = 0 x = (i - 1) mod n y = (i - 1) div n - color 999 - move x * f - f / 2 y * f - f / 2 - rect f * 1.5 f * 1.5 + gcolor 999 + grect x * f - f2 y * f - f2 sz sz . . sleep 0.01 . offs[] = [ 1 n -1 (-n) ] -# -proc m_maze pos . . +proc m_maze pos . m[pos] = 0 show_maze d[] = [ 1 2 3 4 ] @@ -34,7 +34,7 @@ proc m_maze pos . . . . endpos = n * n - 1 -proc make_maze . . +proc make_maze . for i = 1 to len m[] m[i] = 1 . @@ -47,7 +47,6 @@ proc make_maze . . h = 2 * random 15 - n + n * 2 * random 15 m_maze h m[endpos] = 0 - endpos += n . make_maze show_maze diff --git a/Task/Maze-solving/EasyLang/maze-solving.easy b/Task/Maze-solving/EasyLang/maze-solving.easy index 52f27f223c..b5e6fcee73 100644 --- a/Task/Maze-solving/EasyLang/maze-solving.easy +++ b/Task/Maze-solving/EasyLang/maze-solving.easy @@ -3,22 +3,23 @@ n = 2 * size + 1 f = 100 / (n - 0.5) len m[] n * n # -background 000 -proc show_maze . . - clear +gbackground 000 +proc show_maze . + gclear + sz = f * 1.5 + f2 = f / 2 for i = 1 to len m[] if m[i] = 0 x = (i - 1) mod n y = (i - 1) div n - color 999 - move x * f - f / 2 y * f - f / 2 - rect f * 1.5 f * 1.5 + gcolor 999 + grect x * f - f2 y * f - f2 sz sz . . sleep 0.01 . offs[] = [ 1 n -1 (-n) ] -proc m_maze pos . . +proc m_maze pos . m[pos] = 0 show_maze d[] = [ 1 2 3 4 ] @@ -33,7 +34,7 @@ proc m_maze pos . . . . endpos = n * n - 1 -proc make_maze . . +proc make_maze . for i = 1 to len m[] m[i] = 1 . @@ -50,18 +51,15 @@ proc make_maze . . make_maze show_maze # -proc mark pos col . . +proc mark pos col . x = (pos - 1) mod n y = (pos - 1) div n - color col - move x * f + f / 4 y * f + f / 4 - circle f / 3.5 + gcolor col + gcircle x * f + f / 4 y * f + f / 4 f / 3.5 . -global found . -proc solve dir0 pos . . - if found = 1 - return - . +found = 0 +proc solve dir0 pos . + if found = 1 : return mark pos 900 sleep 0.05 if pos = endpos diff --git a/Task/Median-filter/Rust/median-filter.rs b/Task/Median-filter/Rust/median-filter.rs new file mode 100644 index 0000000000..beade0f55d --- /dev/null +++ b/Task/Median-filter/Rust/median-filter.rs @@ -0,0 +1,510 @@ +use std::env; +use std::fs::File; +use std::io::{self, BufRead, BufReader, BufWriter, Read, Write}; +use std::path::Path; +use std::process; + +// --- Data Structures --- + +// Equivalent to rgb_t +#[derive(Clone, Copy, Debug, Default)] +#[repr(C)] // Ensure memory layout is R, G, B for potential raw I/O +struct Rgb { + r: u8, + g: u8, + b: u8, +} + +// Equivalent to image_t, but using Vec for safe memory management +#[derive(Debug)] +struct Image { + width: usize, + height: usize, + pixels: Vec, // Flat pixel buffer +} + +impl Image { + // Creates a new black image + fn new(width: usize, height: usize) -> Self { + Image { + width, + height, + pixels: vec![Rgb::default(); width * height], + } + } + + // Helper to get a pixel reference (immutable) + fn get_pixel(&self, row: usize, col: usize) -> Option<&Rgb> { + if row < self.height && col < self.width { + self.pixels.get(row * self.width + col) + } else { + None + } + } + + // Helper to get a pixel reference (mutable) + fn get_pixel_mut(&mut self, row: usize, col: usize) -> Option<&mut Rgb> { + if row < self.height && col < self.width { + self.pixels.get_mut(row * self.width + col) + } else { + None + } + } + + // Helper for direct index access (use with caution or after bounds check) + fn index(&self, row: usize, col: usize) -> usize { + row * self.width + col + } +} + +// Equivalent to color_histo_t +#[derive(Debug)] +struct ColorHisto { + r: [i32; 256], + g: [i32; 256], + b: [i32; 256], + n: i32, // Total number of pixels counted +} + +impl ColorHisto { + fn new() -> Self { + ColorHisto { + r: [0; 256], + g: [0; 256], + b: [0; 256], + n: 0, + } + } + + // Add a pixel's color to the histogram + fn add_pixel(&mut self, pixel: Rgb) { + self.r[pixel.r as usize] += 1; + self.g[pixel.g as usize] += 1; + self.b[pixel.b as usize] += 1; + self.n += 1; + } + + // Remove a pixel's color from the histogram + fn del_pixel(&mut self, pixel: Rgb) { + self.r[pixel.r as usize] -= 1; + self.g[pixel.g as usize] -= 1; + self.b[pixel.b as usize] -= 1; + self.n -= 1; + } +} + +// --- PPM Reading/Writing --- + +// Helper to read ASCII numbers, skipping comments and whitespace +// This is more robust than the C version's reliance on fscanf specifics. +fn read_ascii_int(reader: &mut R) -> io::Result { + let mut buf = Vec::new(); + let mut digits = Vec::new(); + + loop { + buf.clear(); + // Read until comment or EOF. Limit read size to avoid large allocations on invalid input. + // reader.read_until(b'#', &mut buf)?; // Reads potentially large chunks + + // Read byte by byte for finer control over comments and whitespace + let byte_read = reader.read_until(b'#', &mut buf); + match byte_read { + Ok(0) => break, // EOF + Ok(_) => {}, + Err(e) => return Err(e), + } + + + // Process non-comment part + let mut comment_found = false; + for &byte in &buf { + if byte == b'#' { + comment_found = true; + // Skip the rest of the comment line + reader.read_until(b'\n', &mut Vec::new())?; + // Reset digits found before comment on the same "line" + // only if we haven't added non-whitespace digits yet. + // Check if the last character ADDED (if any) was whitespace. + // If digits is empty OR the last added char was whitespace, clear. + // --- FIX START --- + if digits.last().map_or(true, |last_byte_ref| last_byte_ref.is_ascii_whitespace()) { + // --- FIX END --- + digits.clear(); + } + break; // Process next chunk read after comment + } else if byte.is_ascii_whitespace() { + if !digits.is_empty() { + // Found whitespace after digits, we have our number + let s = String::from_utf8(digits).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + return s.trim().parse::().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)); + } + // Skip leading/multiple whitespace by not adding it to `digits` + } else if byte.is_ascii_digit() { + digits.push(byte); + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Non-digit, non-whitespace, non-comment character found in numeric header field", + )); + } + } + + // If we broke loop due to '#', continue reading after comment + if comment_found { + continue; + } + + // If we reached EOF after reading the buffer + if buf.is_empty() { // EOF confirmed by read_until returning 0 earlier + if digits.is_empty() { // EOF before finding any digits + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF while reading number")); + } else { // Reached EOF after finding digits + let s = String::from_utf8(digits).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + return s.trim().parse::().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)); + } + } + // else: finished processing buffer without finding whitespace after digits, continue loop + } + + // Handle case where file ends immediately after digits without trailing whitespace/comment + if !digits.is_empty() { + let s = String::from_utf8(digits).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + s.trim().parse::().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) + } else { + // This state should ideally be unreachable due to EOF checks above, but acts as a safeguard + Err(io::Error::new(io::ErrorKind::UnexpectedEof, "EOF or invalid state reading number")) + } +} + + +fn read_ppm(filename: &str) -> io::Result { + let file = File::open(filename)?; + let mut reader = BufReader::new(file); + + let mut magic = [0u8; 2]; + reader.read_exact(&mut magic)?; + if &magic != b"P6" { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Not a P6 PPM file", + )); + } + + // Consume the first whitespace/comment after P6, needed before reading width. + // read_ascii_int handles subsequent whitespace/comments. + let mut header_byte = [0u8; 1]; + loop { + reader.read_exact(&mut header_byte)?; + if header_byte[0] == b'#' { + reader.read_until(b'\n', &mut Vec::new())?; // Skip comment line + } else if header_byte[0].is_ascii_whitespace() { + break; // Found the required whitespace separator + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Expected whitespace or comment after P6 magic number", + )); + } + } + + + let width = read_ascii_int(&mut reader)?; + let height = read_ascii_int(&mut reader)?; + let maxval = read_ascii_int(&mut reader)?; + + if width == 0 || height == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Invalid image dimensions (width or height is zero)", + )); + } + if maxval != 255 { + // Technically PGM/PPM allow other maxvals, but this code assumes 255. + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Max color value must be 255 for this implementation", + )); + } + + // Read the single whitespace character separating header from data + let mut header_end = [0u8; 1]; + // Consume any remaining whitespace/comments after maxval before the final newline/space + loop { + reader.read_exact(&mut header_end)?; + if header_end[0] == b'#' { + reader.read_until(b'\n', &mut Vec::new())?; + } else if header_end[0].is_ascii_whitespace() { + // Check if it's the required single whitespace char + if header_end[0] == b'\n' || header_end[0] == b' ' || header_end[0] == b'\t' || header_end[0] == b'\r' { + break; // Found it + } // else keep reading whitespace if needed (though standard expects one) + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Expected single whitespace after maxval before pixel data", + )); + } + } + + + let mut image = Image::new(width, height); + let pixel_count = width * height; + let byte_count = pixel_count * 3; + + // Read pixel data directly into a Vec first + let mut byte_buffer = vec![0u8; byte_count]; + reader.read_exact(&mut byte_buffer)?; + + + // Convert bytes to Rgb structs - Optimized + // Safety: We know byte_buffer.len() == image.pixels.len() * 3 + // Using chunks_exact is efficient and safe. + let mut pixel_iter = image.pixels.iter_mut(); + for chunk in byte_buffer.chunks_exact(3) { + if let Some(pixel) = pixel_iter.next() { + pixel.r = chunk[0]; + pixel.g = chunk[1]; + pixel.b = chunk[2]; + } else { + // Should not happen if counts are correct + return Err(io::Error::new(io::ErrorKind::InvalidData, "Pixel data size mismatch (internal error)")); + } + } + + // Check for extra data after pixel data (optional, can indicate malformed file) + // let mut extra = [0u8; 1]; + // if reader.read(&mut extra)? > 0 { + // eprintln!("Warning: Extra data found after pixel data in PPM file."); + // } + + Ok(image) +} + +fn write_ppm(image: &Image, filename: &str) -> io::Result<()> { + let file = File::create(filename)?; + let mut writer = BufWriter::new(file); + + write!(writer, "P6\n{} {}\n255\n", image.width, image.height)?; + + // Write pixel data - Optimized + // Create a byte buffer directly from the pixel data + let byte_buffer: Vec = image.pixels + .iter() + .flat_map(|p| [p.r, p.g, p.b]) + .collect(); + + writer.write_all(&byte_buffer)?; + writer.flush()?; // Ensure all data is written + + Ok(()) +} + +// --- Median Filter Logic --- + +// Add pixels in a vertical column segment to the histogram +fn add_pixels( + im: &Image, + row: isize, // Use isize for calculations involving size subtraction + col: usize, + size: isize, + h: &mut ColorHisto, +) { + if col >= im.width { + return; + } + // Calculate row bounds carefully using isize before converting to usize + let start_row = (row - size).max(0) as usize; + // Ensure end_row doesn't wrap around if row+size is huge + let end_row_isize = (row + size).min(im.height as isize - 1); + if end_row_isize < start_row as isize { // Should not happen if size >= 0 + return; + } + let end_row = end_row_isize as usize; + + + for i in start_row..=end_row { + // We already checked col < im.width and i is within [0, im.height) + if let Some(pixel) = im.get_pixel(i, col) { // Use get_pixel for safety just in case + h.add_pixel(*pixel); + } + } +} + +// Delete pixels in a vertical column segment from the histogram +fn del_pixels( + im: &Image, + row: isize, + col: usize, // Column index must be valid if called + size: isize, + h: &mut ColorHisto, +) { + // Assume col is valid (checked by caller usually, like `if remove_col_idx >= 0`) + if col >= im.width { // Still good practice to check upper bound + return; + } + + let start_row = (row - size).max(0) as usize; + let end_row_isize = (row + size).min(im.height as isize - 1); + if end_row_isize < start_row as isize { + return; + } + let end_row = end_row_isize as usize; + + for i in start_row..=end_row { + if let Some(pixel) = im.get_pixel(i, col) { + h.del_pixel(*pixel); + } + } +} + +// Initialize histogram for the start of a row +fn init_histo(im: &Image, row: isize, size: isize, h: &mut ColorHisto) { + *h = ColorHisto::new(); // Reset histogram + + // Calculate the initial window columns (0 to size) + // Ensure end_col doesn't exceed width-1 + let end_col = (size as usize).min(im.width.saturating_sub(1)); + + for j in 0..=end_col { + add_pixels(im, row, j, size, h); + } +} + +// Find the median value in a single channel histogram array +fn median(x: &[i32; 256], n: i32) -> u8 { + if n <= 0 { + return 0; // Handle empty or invalid histogram state + } + let mut count = 0; + // Target count to find the median element + // For even n, this finds the lower median (e.g., for [1,2,3,4], n=4, n/2=2, stops at 2) + // For odd n, this finds the exact median (e.g., for [1,2,3], n=3, n/2=1, stops at 2) + let threshold = n / 2; + for i in 0..256 { + count += x[i]; + // Use > threshold because we want the first bin where cumulative count EXCEEDS n/2 + if count > threshold { + return i as u8; + } + } + // If n > 0, should have returned. If loop finishes, it implies n was 0 + // or data is skewed (e.g., all counts were 0, which shouldn't happen if n > 0). + // Return 255 as a fallback, though 0 might also be reasonable if n was 0. + 255 +} + +// Calculate the median color using the histogram +fn median_color(h: &ColorHisto) -> Rgb { + Rgb { + r: median(&h.r, h.n), + g: median(&h.g, h.n), + b: median(&h.b, h.n), + } +} + +// Apply median filter +fn median_filter(input: &Image, size: usize) -> Image { + let mut output = Image::new(input.width, input.height); + let mut h = ColorHisto::new(); + let size_isize = size as isize; // Use isize for calculations + + if input.width == 0 || input.height == 0 { + return output; // Return empty image if input is empty + } + + for row in 0..input.height { + let row_isize = row as isize; + // Reset histogram at the start of each row + h = ColorHisto::new(); + + for col in 0..input.width { + if col == 0 { + // Initialize histogram for the first pixel window of the row + init_histo(input, row_isize, size_isize, &mut h); + } else { + // Slide the window: remove leftmost column, add rightmost column + + // Column index to remove (can be negative if window is near left edge) + let remove_col_idx = col as isize - size_isize - 1; + // Column index to add (can be >= width if window is near right edge) + let add_col_idx = col as isize + size_isize; + + // del_pixels handles bounds check for remove_col_idx < 0 internally (no-op) + // We only need to check if it's a valid index >= 0 before calling + if remove_col_idx >= 0 { + del_pixels(input, row_isize, remove_col_idx as usize, size_isize, &mut h); + } + // add_pixels handles bounds check for add_col_idx >= width internally (no-op) + // No need for explicit check here, add_pixels takes usize and handles it. + add_pixels(input, row_isize, add_col_idx as usize, size_isize, &mut h); + } + + // Calculate median for the center pixel (current row, col) and write to output + // Ensure the histogram is not empty before calculating median + if h.n > 0 { + if let Some(out_pixel) = output.get_pixel_mut(row, col) { + *out_pixel = median_color(&h); + } + } else { + // This might happen if the window size is very large relative to image dimensions + // or near edges with empty columns added/removed. Output black or default pixel. + if let Some(out_pixel) = output.get_pixel_mut(row, col) { + *out_pixel = Rgb::default(); + } + // Can add a warning here if needed: eprintln!("Warning: Empty histogram at ({}, {})", row, col); + } + } + } + + output +} + +// --- Main Function --- + +fn main() -> io::Result<()> { + let args: Vec = env::args().collect(); + + if args.len() <= 3 { + eprintln!("Usage: {} ", args[0]); + process::exit(1); + } + + let size: usize = match args[1].parse() { + Ok(s) if s > 0 => s, // Median filter radius usually non-zero + Ok(_) => { // Allow size 0 (no filtering), though typically size >= 1 + eprintln!("Warning: Filter size is 0. Output will be same as input."); + 0 + } + Err(_) => { + eprintln!("Error: Filter size must be a non-negative integer."); + process::exit(1); + } + }; + + let input_filename = &args[2]; + let output_filename = &args[3]; + + println!( + "Reading input file: {} with filter size {}", + input_filename, size + ); + let input_image = read_ppm(input_filename).map_err(|e| { + eprintln!("Error reading input file '{}': {}", input_filename, e); + process::exit(1); // Exit on read error + })?; + + println!( + "Applying median filter (window radius {}, diameter {})...", + size, 2 * size + 1 + ); + let output_image = median_filter(&input_image, size); + + println!("Writing output file: {}", output_filename); + write_ppm(&output_image, output_filename).map_err(|e| { + eprintln!("Error writing output file '{}': {}", output_filename, e); + process::exit(1); // Exit on write error + })?; + + println!("Done."); + Ok(()) +} diff --git a/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy b/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy index 8fdd64cc93..54d3856e03 100644 --- a/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy +++ b/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy @@ -1,15 +1,8 @@ fastfunc isprim num . - if num mod 2 = 0 - if num = 2 - return 1 - . - return 0 - . + if num mod 2 = 0 and num <> 2 : return 0 i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 @@ -23,5 +16,5 @@ for x = 2 to 1e6 m += log (1 - (1 / x)) + (1 / x) . . -numfmt 11 0 +numfmt 0 11 print "mm = " & euler + m diff --git a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx index 55681c59ee..1c5d19a827 100644 --- a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx +++ b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx @@ -1,6 +1,9 @@ +-- 8 May 2025 include Settings -say version; say 'Meissel-Mertens constant'; say +say 'MEISSEL-MERTENS CONSTANT' +say version +say arg n if n = '' then n = 16 @@ -30,11 +33,11 @@ numeric digits Digits()-2 return y+0 UsingSieve: -procedure expose glob. prim. +procedure expose glob. prim. flag. numeric digits Digits()+2 n = Primes(1000000); y = 0 do i = 1 to n - q = 1/prim.prime.i; t = Ln(1-q)+q; y = y+t + q = 1/prim.i; t = Ln(1-q)+q; y = y+t end y = Euler()+y numeric digits Digits()-2 @@ -63,4 +66,7 @@ return 0.26149721284764278375542683860869585905156664826119920619206421392492451 include Constants include Functions +include Special include Numbers +include Sequences +include Abend diff --git a/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy b/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy index 51a02cfa7a..451dbc3f9b 100644 --- a/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy +++ b/Task/Merge-and-aggregate-datasets/EasyLang/merge-and-aggregate-datasets.easy @@ -5,12 +5,10 @@ repeat pat$[][] &= strsplit s$ "," pat$[$][] &= "" . -proc sort . d$[][] . - for i = len d$[][] - 1 downto 1 - for j = 1 to i - if strcmp d$[j][1] d$[j + 1][1] > 0 - swap d$[j][] d$[j + 1][] - . +proc sort &d$[][] . + for i = len d$[][] - 1 downto 1 : for j = 1 to i + if strcmp d$[j][1] d$[j + 1][1] > 0 + swap d$[j][] d$[j + 1][] . . . @@ -36,9 +34,7 @@ repeat . func$ f s$ n . s$ = " " & s$ - while len s$ < n - s$ &= " " - . + while len s$ < n : s$ &= " " return s$ . print "PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG" diff --git a/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets.basic b/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-1.basic similarity index 100% rename from Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets.basic rename to Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-1.basic diff --git a/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic b/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic new file mode 100644 index 0000000000..6b0293f6d1 --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/FreeBASIC/merge-and-aggregate-datasets-2.basic @@ -0,0 +1,248 @@ +#include once "sqlite3.bi" +#include once "string.bi" +#include once "crt.bi" + +' Callback para SQLite +Function callback Cdecl (Byval NotUsed As Any Ptr, Byval argc As Integer, _ + Byval argv As ZString Ptr Ptr, Byval colName As ZString Ptr Ptr) As Integer + + For i As Integer = 0 To argc - 1 + If argv[i] <> NULL Then + Print *colName[i] & ": " & *argv[i] & " "; + Else + Print *colName[i] & ": NULL "; + End If + Next + Print + + Return 0 +End Function + +Sub createCSVfiles() + Dim As Integer ff + + If Dir("patients.csv") = "" Then + ff = Freefile + Open "patients.csv" For Output As #ff + Print #ff, "PATIENT_ID,LASTNAME" + Print #ff, "1001,Hopper" + Print #ff, "4004,Wirth" + Print #ff, "3003,Kemeny" + Print #ff, "2002,Gosling" + Print #ff, "5005,Kurtz" + Close #ff + End If + + If Dir("visits.csv") = "" Then + ff = Freefile + Open "visits.csv" For Output As #ff + Print #ff, "PATIENT_ID,VISIT_DATE,SCORE" + Print #ff, "2002,2020-09-10,6.8" + Print #ff, "1001,2020-09-17,5.5" + Print #ff, "4004,2020-09-24,8.4" + Print #ff, "2002,2020-10-08," + Print #ff, "1001,,6.6" + Print #ff, "3003,2020-11-12," + Print #ff, "4004,2020-11-05,7.0" + Print #ff, "1001,2020-11-19,5.3" + Close #ff + End If +End Sub + +Sub createTableHeaders(db As sqlite3 Ptr) + Dim As ZString Ptr errMsg = NULL + + ' Create the patient and visit table + sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS patients (PATIENT_ID INT, LASTNAME TEXT);", Cast(Any Ptr, @callback), NULL, @errMsg) + If errMsg <> NULL Then + Print "Error creating patients table: " & *errMsg + sqlite3_free(errMsg) + End If + + sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS visits (PATIENT_ID INT, VISIT_DATE TEXT, SCORE NUMERIC(4,1));", Cast(Any Ptr, @callback), NULL, @errMsg) + If errMsg <> NULL Then + Print "Error creating visits table: " & *errMsg + sqlite3_free(errMsg) + End If +End Sub + +Sub fillTablesFromCSV(db As sqlite3 Ptr) + Dim As Integer ff, i + Dim As String lineaCSV, query + Dim As ZString Ptr errMsg = NULL + + ff = Freefile + Open "patients.csv" For Input As #ff + Line Input #ff, lineaCSV ' Saltar la cabecera + + While Not Eof(ff) + Line Input #ff, lineaCSV + Dim As String id = "", lastname = "" + + i = 1 + While i <= Len(lineaCSV) And Mid(lineaCSV, i, 1) <> "," + id += Mid(lineaCSV, i, 1) + i += 1 + Wend + i += 1 ' Skip the comma + + While i <= Len(lineaCSV) + lastname += Mid(lineaCSV, i, 1) + i += 1 + Wend + + query = "INSERT INTO patients VALUES (" & id & ", '" & lastname & "');" + + sqlite3_exec(db, query, NULL, NULL, @errMsg) + If errMsg <> NULL Then + Print "Error inserting patient: " & *errMsg + sqlite3_free(errMsg) + End If + Wend + Close #ff + + ff = Freefile + Open "visits.csv" For Input As #ff + Line Input #ff, lineaCSV ' Skip header + + While Not Eof(ff) + Line Input #ff, lineaCSV + Dim As String id = "", dateStr = "", score = "" + Dim As Integer fieldNum = 0 + + For i = 1 To Len(lineaCSV) + If Mid(lineaCSV, i, 1) = "," Then + fieldNum += 1 + Else + Select Case fieldNum + Case 0: id += Mid(lineaCSV, i, 1) + Case 1: dateStr += Mid(lineaCSV, i, 1) + Case 2: score += Mid(lineaCSV, i, 1) + End Select + End If + Next i + + query = "INSERT INTO visits VALUES (" & id & ", " + + If dateStr = "" Then + query &= "NULL, " + Else + query &= "'" & dateStr & "', " + End If + + If score = "" Then + query &= "NULL);" + Else + query &= score & ");" + End If + + sqlite3_exec(db, query, NULL, NULL, @errMsg) + If errMsg <> NULL Then + Print "Error inserting visit: " & *errMsg + sqlite3_free(errMsg) + End If + Wend + Close #ff +End Sub + +Function joinTablesAndGroup(db As sqlite3 Ptr) As String + Dim As sqlite3_stmt Ptr stmt + Dim As String result = "" + Dim As ZString Ptr errMsg = NULL + + Dim As String query = _ + "SELECT " & _ + " p.PATIENT_ID, " & _ + " p.LASTNAME, " & _ + " MAX(v.VISIT_DATE) AS LAST_VISIT, " & _ + " SUM(v.SCORE) AS SCORE_SUM, " & _ + " ROUND(AVG(v.SCORE), 1) AS SCORE_AVG " & _ + "FROM " & _ + " patients p " & _ + "LEFT JOIN " & _ + " visits v ON p.PATIENT_ID = v.PATIENT_ID " & _ + "GROUP BY " & _ + " p.PATIENT_ID, p.LASTNAME " & _ + "ORDER BY " & _ + " p.PATIENT_ID;" + + If sqlite3_prepare_v2(db, query, -1, @stmt, NULL) <> SQLITE_OK Then + Print "Error preparing statement: " & *sqlite3_errmsg(db) + Return "Error" + End If + + result = "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |" & Chr(10) + result &= "|------------|----------|------------|-----------|-----------|" & Chr(10) + + While sqlite3_step(stmt) = SQLITE_ROW + Dim As String row = "| " + + ' PATIENT_ID + If sqlite3_column_type(stmt, 0) <> SQLITE_NULL Then + row &= " " & Trim(Str(sqlite3_column_int(stmt, 0))) & " | " + Else + row &= Space(10) & "| " + End If + + ' LASTNAME + If sqlite3_column_type(stmt, 1) <> SQLITE_NULL Then + Dim As String lastname = *Cast(ZString Ptr, sqlite3_column_text(stmt, 1)) + row &= lastname & Space(9 - Len(lastname)) & "| " + Else + row &= " | " + End If + + ' LAST_VISIT + If sqlite3_column_type(stmt, 2) <> SQLITE_NULL Then + Dim As String visit_date = *Cast(ZString Ptr, sqlite3_column_text(stmt, 2)) + row &= visit_date & Space(11 - Len(visit_date)) & "| " + Else + row &= " None | " + End If + + ' SCORE_SUM + If sqlite3_column_type(stmt, 3) <> SQLITE_NULL Then + Dim As Double score_sum = sqlite3_column_double(stmt, 3) + row &= " " & Format(score_sum, "#00.#") & " | " + Else + row &= " None | " + End If + + ' SCORE_AVG + If sqlite3_column_type(stmt, 4) <> SQLITE_NULL Then + Dim As Double score_avg = sqlite3_column_double(stmt, 4) + row &= " " & Format(score_avg, "##.#") & " |" + Else + row &= " None |" + End If + + result &= row & Chr(10) + Wend + + sqlite3_finalize(stmt) + Return result +End Function + +' Main program +Dim As sqlite3 Ptr db +Dim As Integer rc + +createCSVfiles() + +rc = sqlite3_open(":memory:", @db) +If rc <> SQLITE_OK Then + Print "Error opening database: " & *sqlite3_errmsg(db) + sqlite3_close(db) + Sleep: End 1 +End If + +createTableHeaders(db) + +fillTablesFromCSV(db) + +Dim As String result = joinTablesAndGroup(db) +Print result + +sqlite3_close(db) + +Sleep diff --git a/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo new file mode 100644 index 0000000000..576dddf06b --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-1.logo @@ -0,0 +1,87 @@ +to read.simple.csv :in + local [line list] + make "list [] + openread :in + setread :in + while [not eofp] [ + make "line subst.comma readword + make "line parse map [ifelse equalp ? ", ["\ ] [?]] :line + make "list fput :line :list + ] + close :in + setread [] + output reverse :list +end + +to subst.comma :string + local [out k] + make "k 1 + make "out " + foreach :string [ + ifelse equalp ? ", ~ + [ifelse equalp :k 1 ~ + [make "out word :out ? make "k sum :k 1] ~ + [make "out word :out "|missing,| make "k 1]] ~ + [make "out word :out ? make "k 1] + ] + output ifelse equalp last :out ", [word :out "missing] [:out] +end + +to aggregate :patients :visits + if emptyp :patients [output []] + output fput aggregate.helper first :patients :visits aggregate bf :patients :visits +end + + +to aggregate.helper :patient :visits [s 0] [c 0] [m "] +;m for max date. s for sum of scores. c number of scores + if emptyp :visits [ + output (se :patient ifelse equalp :m " ["missing] [:m] ~ + ifelse equalp :s 0 ["missing] [:s] ~ + ifelse equalp :s 0 ["missing] [quotient :s :c]) + ] + output ifelse equalp first :patient first first :visits [ + (aggregate.helper :patient bf :visits ~ + ifelse equalp last first :visits "missing [:s][sum :s last first :visits] ~ + ifelse equalp last first :visits "missing [:c][sum :c 1] ~ + ifelse equalp first bf first :visits "missing [:m] ~ + [ifelse beforep :m first bf first :visits [first bf first :visits] [:m]])] ~ + [(aggregate.helper :patient bf :visits :s :c :m)] +end + +to mergesort :list + localmake "half split (count :list) / 2 [] :list + if empty? first :half [output :list] + output merge mergesort first :half mergesort last :half +end + +to split :size :front :list + if :size < 1 [output list :front :list] + output split :size-1 (lput first :list :front) (butfirst :list) +end + +to merge :small :large + if empty? :small [output :large] + ifelse lessequal? first first :small first first :large ~ + [output fput first :small merge butfirst :small :large] ~ + [output fput first :large merge butfirst :large :small] +end + +to csv.write :list :out + openwrite :out + setwrite :out + csv.write.lines :list + close :out + setwrite [] +end + +to csv.write.lines :list + if emptyp :list [stop] + print csv.write.fields first :list + csv.write.lines bf :list +end + +to csv.write.fields :line + if equalp count :line 1 [output first :line] + output (word first :line ", csv.write.fields bf :line) +end diff --git a/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo new file mode 100644 index 0000000000..e7cfd319ec --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/Logo/merge-and-aggregate-datasets-2.logo @@ -0,0 +1,5 @@ +make "patients bf read.simple.csv "patients.csv +make "visits bf read.simple.csv "visits.csv +make "out mergesort aggregate :patients :visits +make "out fput [patient_id lastname max_date score_sum score_mean] :out +csv.write :out "out.csv diff --git a/Task/Mertens-function/EasyLang/mertens-function.easy b/Task/Mertens-function/EasyLang/mertens-function.easy index bacf516727..5ba339e368 100644 --- a/Task/Mertens-function/EasyLang/mertens-function.easy +++ b/Task/Mertens-function/EasyLang/mertens-function.easy @@ -8,19 +8,15 @@ for n = 2 to 1000 . print "First 99 Mertens numbers:" write " " -numfmt 0 2 +numfmt 2 0 for n = 1 to 99 write mertens[n] & " " - if n mod 10 = 9 - print "" - . + if n mod 10 = 9 : print "" . for n = 1 to 1000 if mertens[n] = 0 zeros += 1 - if mertens[n - 1] <> 0 - crosses += 1 - . + if mertens[n - 1] <> 0 : crosses += 1 . . print "" diff --git a/Task/Mertens-function/REXX/mertens-function.rexx b/Task/Mertens-function/REXX/mertens-function.rexx index ee48fca3f7..86a3268b56 100644 --- a/Task/Mertens-function/REXX/mertens-function.rexx +++ b/Task/Mertens-function/REXX/mertens-function.rexx @@ -1,61 +1,118 @@ -/*REXX pgm computes & shows a value grid of the Mertens function for a range of integers*/ -parse arg LO HI grp eqZ xZ . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 199 /* " " " " " " */ -if grp=='' | grp=="," then grp= 20 /* " " " " " " */ -if eqZ=='' | eqZ=="," then eqZ= 1000 /* " " " " " " */ -if xZ=='' | xZ=="," then xZ= 1000 /* " " " " " " */ -call genP /*generate primes up to max √ HIHI */ - call Franz LO, HI -if eqZ>0 then call Franz 1, -eqZ -if xZ>0 then call Franz -1, xZ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Franz: parse arg a 1 oa,b 1 ob; @Mertens= ' The Mertens sequence from ' -a= abs(a); b= abs(b); grid= oa>=0 & ob>=0 /*semaphore used to show a grid title. */ -if grid then say center(@Mertens LO " ──► " HI" ", max(50, grp*3), '═') /*show title*/ - else say -zeros= 0 /*# of 0's found for Mertens function.*/ -Xzero= 0 /*number of times that zero was crossed*/ -$=; prev= /*$ holds output grid of GRP numbers. */ - do j=a to b; _= Mertens(j) /*process some numbers from LO ──► HI.*/ - if _==0 then zeros= zeros + 1 /*Is Zero? Then bump the zeros counter*/ - if _==0 then if prev\==0 then Xzero= Xzero+1 /*prev ¬=0? " " " Xzero " */ - prev= _ - if grid then $= $ right(_, 2) /*build grid if A & B are non─negative.*/ - if words($)==grp then do; say substr($, 2); $= /*show grid if fully populated, */ - end /* and nullify it for more #s. */ - end /*j*/ /*for small grids, using wordCnt is OK.*/ +-- 25 Apr 2025 +include Settings +arg xx +if xx = '' then + xx = 99 -if $\=='' then say substr($, 2) /*handle any residual numbers not shown*/ -if oa<0 then say @Mertens a " to " b ' has crossed zero ' Xzero " times." -if ob<0 then say @Mertens a " to " b ' has ' zeros " zeros." +say 'MERTENS FUNCTION' +say version +say +call Tasks1 xx +call Tasks2 xx +call Tasks3 xx +exit + +Tasks1: +procedure expose squa. +arg xx +call Time('r') +say 'Tasks using Sieve...' +call Squarefrees 2*xx +if xx < 100 then + say 'M1 thru M'xx +e = 0; o = 0; a = 0; b = 0 +n = 1; s = squa.1; p = s +do i = 1 to xx + if s <= i then do + if s = 1 then + f = 0 + else + f = Factors(s) + e = e+Even(f); o = o+Odd(f); m = e-o + n = n+1; s = squa.n + end + if xx < 100 & i < 100 then do + call Charout ,Right(m,3) + if i//10 = 0 then + say + end + if m = 0 then do + a = a+1 + if p <> 0 then + b = b + 1 + end + p = m +end +say +say 'M1 thru M'xx 'equals zero' a 'times' +say 'M1 thru M'xx 'crosses zero' b 'times' +say Format(Time('e'),,3) 'seconds'; say return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Mertens: procedure expose @. !!. M.; parse arg n; if M.n\==. then return M.n - if n<1 then return '∙'; m= 0 /*handle special cases of non─positive#*/ - do k=1 for n; m= m + mobius(k) /*sum the MU's up to N. */ - end /*k*/ /* [↑] mobius function uses memoization*/ - M.n= m; return m /*return the sum of all the MU's. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -mobius: procedure expose @. !!.; parse arg x 1 ox /*get integer to be tested for mu */ - if !!.x\==. then return !!.x /*X computed before? Return that value*/ - if x<1 then return '∙'; mu= 0 /*handle special case of non-positive #*/ - do k=1; p= @.k; if p>x then leave /* (P) > X? Then we're done.*/ - if p*p>x then do; mu= mu+1; leave; end /* (P**2) > X? Bump # and leave*/ - if x//p==0 then do; mu= mu+1 /*X divisible by P? Bump mu number.*/ - x= x % p /* Divide by prime. */ - if x//p==0 then return 0 /*X÷by P? Then return zero*/ - end - end /*k*/ /*MU (below) is almost always small, <9*/ - !!.ox= -1 ** mu; return !!.ox /*raise -1 to the mu power, memoize it.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*initialize some low primes; # primes.*/ - !!.=.; M.=!!.; #= 6; sq.#= @.6**2 /* " 2 arrays for memoization. */ - do j=@.#+4 by 2 to max(HI, eqZ, xZ); parse var j '' -1 _ /*odd Ps from now on*/ - if _==5 then iterate; if j//3==0 then iterate; if j//7==0 then iterate /*÷ 5 3 7*/ - do k=7 while sq.k<=j /*divide by some generated odd primes. */ - if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - #= #+1; @.#=j; sq.j= j*j /*bump P count; P──►@.; compute J**2*/ - end /*j*/; return /*calculate the squares of some primes.*/ + +Tasks2: +procedure expose squa. +arg xx +call Time('r') +say 'Tasks using Moebius function...' +if xx < 100 then + say 'M1 thru M'xx +e = 0; o = 0; a = 0; b = 0 +s = 0 +do i = 1 to xx + s = s+Moebius(i) + if xx < 100 & i < 100 then do + call Charout ,Right(s,3) + if i//10 = 0 then + say + end + if s = 0 then do + a = a+1 + if p <> 0 then + b = b + 1 + end + p = s +end +say +say 'M1 thru M'xx 'equals zero' a 'times' +say 'M1 thru M'xx 'crosses zero' b 'times' +say Format(Time('e'),,3) 'seconds'; say +return + +Tasks3: +procedure expose squa. +arg xx +call Time('r') +say 'Tasks using Squarefree function...' +if xx < 100 then + say 'M1 thru M'xx +e = 0; o = 0; a = 0; b = 0 +do s = 1 to xx + if Squarefree(s) then do + if s = 1 then + f = 0 + else + f = Factors(s) + e = e+Even(f); o = o+Odd(f); m = e-o + end + if xx < 100 & s < 100 then do + call Charout ,Right(m,3) + if s//10 = 0 then + say + end + if m = 0 then do + a = a+1 + if p <> 0 then + b = b + 1 + end + p = m +end +say +say 'M1 thru M'xx 'equals zero' a 'times' +say 'M1 thru M'xx 'crosses zero' b 'times' +say Format(Time('e'),,3) 'seconds'; say +return + +include Numbers +include Sequences +include Functions +include Abend diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx index 30799c4f3d..42cfe64c8b 100644 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx +++ b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx @@ -1,6 +1,8 @@ include Settings -say version; say 'Miller-Rabin primality test'; say +say 'MILLER-RABIN PRIMALITY TEST - 4 Mar 2025' +say version +say numeric digits 1000 say '25 numbers of the form 2^n-1, mostly Mersenne primes' say 'Up to about 25 digits deterministic, above probabilistic' diff --git a/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy b/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy index 9189088f07..1bfe4ab7ba 100644 --- a/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy +++ b/Task/Mind-boggling-card-trick/EasyLang/mind-boggling-card-trick.easy @@ -1,13 +1,11 @@ -proc shuffle . a[] . +proc shuffle &a[] . for i = len a[] downto 2 r = random i swap a[r] a[i] . . func$ a2str a[] . - for v in a[] - r$ &= strchar v & " " - . + for v in a[] : r$ &= strchar v & " " return r$ . R = strcode "R" @@ -30,12 +28,8 @@ print "After dealing the cards the state of the stacks is:" print " Red : " & a2str red[] print " Black : " & a2str black[] print " Discard: " & a2str discard[] -for i to len red[] - rp[] &= i -. -for i to len black[] - bp[] &= i -. +for i to len red[] : rp[] &= i +for i to len black[] : bp[] &= i shuffle rp[] shuffle bp[] n = random lower len red[] len black[] @@ -52,15 +46,9 @@ print "After swapping " & n & " cards the state of the stacks is:" print " Red : " & a2str red[] print " Black : " & a2str black[] # -for c in red[] - red += if c = R -. -for c in black[] - black += if c = B -. +for c in red[] : red += if c = R +for c in black[] : black += if c = B print "" print "The number of red cards in the red stack = " & red print "The number of black cards in the black stack = " & black -if red = black - print "So the asssertion is correct!" -. +if red = black : print "So the asssertion is correct!" diff --git a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy index 96d2a19eb8..933c63c42a 100644 --- a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy +++ b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy @@ -15,46 +15,39 @@ func getind r c . . return ind . -proc draw_cell ind h . . +proc draw_cell ind h . ind -= 1 r = ind div 8 c = ind mod 8 x = c * 12 + 2.5 y = r * 12 + 2.5 - move x y - rect 11 11 + grect x y 11 11 if h > 0 # count - move x + 3 y + 3 - color 000 - text h + gcolor 000 + gtext x + 3 y + 3 h elif h = -3 # flag x += 4 - color 000 - linewidth 0.8 - move x y + 3 - line x y + 8 - color 600 - linewidth 2 - move x + 0.5 y + 7 - line x + 2 y + 7 + gcolor 000 + glinewidth 0.8 + gline x y + 3 x y + 8 + gcolor 600 + glinewidth 2 + gline x + 0.5 y + 7 x + 2 y + 7 elif h <> 0 # mine - color 333 - if h = -2 - color 800 - . - move x + 5 y + 5 - circle 3 - line x + 8 y + 9 + gcolor 333 + if h = -2 : gcolor 800 + gcircle x + 5 y + 5 3 + gline x + 5 y + 5 x + 8 y + 9 . . -proc open ind . . +proc open ind . if ind <> -1 and cell[ind] = 0 cell[ind] = 2 flag[ind] = 0 - color 686 + gcolor 686 draw_cell ind cnt[ind] if cnt[ind] = 0 ind -= 1 @@ -70,31 +63,25 @@ proc open ind . . . . . -proc show_mines m . . +proc show_mines m . for ind to 56 if cell[ind] = 1 - color 686 - if m = -1 - color 353 - . + gcolor 686 + if m = -1 : gcolor 353 draw_cell ind m . . . -proc outp col s$ . . - move 2.5 87 - color col - rect 59 11 - color 000 - move 5 90 - text s$ +proc outp col s$ . + gcolor col + grect 2.5 87 59 11 + gcolor 000 + gtext 5 90 s$ . -proc upd_info . . +proc upd_info . for i to 56 nm += flag[i] - if cell[i] < 2 - nc += 1 - . + if cell[i] < 2 : nc += 1 . if nc = 8 outp 484 "Well done" @@ -104,11 +91,11 @@ proc upd_info . . outp 464 8 - nm & " mines left" . . -proc test ind . . +proc test ind . if cell[ind] < 2 and flag[ind] = 0 if cell[ind] = 1 show_mines -1 - color 686 + gcolor 686 draw_cell ind -2 outp 844 "B O O M !" state = 1 @@ -119,9 +106,9 @@ proc test ind . . . . background 676 -proc start . . - clear - color 353 +proc start . + gclear + gcolor 353 for ind to 56 cnt[ind] = 0 cell[ind] = 0 @@ -148,21 +135,18 @@ proc start . . . initvars outp 464 "" - textsize 4 - move 5 93 - text "Minesweeper - 8 mines" - move 5 88.2 - text "Long-press for flagging" - textsize 6 + gtextsize 4 + gtext 5 93 "Minesweeper - 8 mines" + gtext 5 88.2 "Long-press for flagging" + gtextsize 6 timer 0 . on mouse_down if state = 0 if mouse_y > 86 and mouse_x > 60 no_time = 1 - move 64.5 87 - color 464 - rect 33 11 + gcolor 464 + grect 64.5 87 33 11 . indx = getind ((mouse_y - 2) div 12) ((mouse_x - 2) div 12) ticks0 = ticks @@ -171,9 +155,7 @@ on mouse_down . . on mouse_up - if state = 0 and indx <> -1 - test indx - . + if state = 0 and indx <> -1 : test indx indx = -1 . on timer @@ -190,7 +172,7 @@ on timer else if indx > 0 and ticks = ticks0 + 2 if cell[indx] < 2 - color 353 + gcolor 353 flag[indx] = 1 - flag[indx] opt = 0 if flag[indx] = 1 @@ -202,15 +184,13 @@ on timer indx = -1 . if no_time = 0 and ticks mod 10 = 0 - move 64.5 87 - color 464 + gcolor 464 if ticks >= 2500 - color 844 + gcolor 844 . - rect 33 11 - color 000 - move 66 90 - text "Time:" & 300 - ticks / 10 + grect 64.5 87 33 11 + gcolor 000 + gtext 66 90 "Time:" & 300 - ticks / 10 . ticks += 1 timer 0.1 diff --git a/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy b/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy index 1e16044bef..a1142f0cc2 100644 --- a/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy +++ b/Task/Modified-random-distribution/EasyLang/modified-random-distribution.easy @@ -26,7 +26,7 @@ for i to n bn = floor (rn / binsz) bins[bn] += 1 . -numfmt 0 4 +numfmt 4 0 for i range0 nbins print bins[i] & " " & rep "*" (bins[i] / histsz) . diff --git a/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j b/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j index 6c5b86d50c..4b0d153718 100644 --- a/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j +++ b/Task/Monads-Maybe-monad/J/monads-maybe-monad-1.j @@ -1,3 +1,3 @@ -'J N'=. s:'Just';'Nothing' +'J N'=. s:' Just Nothing' unit =. J,&<] bind =. {{u@(1{::])^:(N-.@-:])}} diff --git a/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy b/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy index da447ba3db..9fac9bcd64 100644 --- a/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy +++ b/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy @@ -2,13 +2,11 @@ func mc n . for i = 1 to n x = randomf y = randomf - if x * x + y * y < 1 - hit += 1 - . + if x * x + y * y < 1 : hit += 1 . return 4 * hit / n . -numfmt 4 0 +numfmt 0 4 print mc 10000 print mc 100000 print mc 1000000 diff --git a/Task/Morse-code/EasyLang/morse-code.easy b/Task/Morse-code/EasyLang/morse-code.easy index bbbc87fac2..bf8b794642 100644 --- a/Task/Morse-code/EasyLang/morse-code.easy +++ b/Task/Morse-code/EasyLang/morse-code.easy @@ -3,7 +3,7 @@ txt$ = "sos sos" chars$ = "abcdefghijklmnopqrstuvwxyz " code$[] = [ ".-" "-..." "-.-." "-.." "." "..-." "--." "...." ".." ".---" "-.-" ".-.." "--" "-." "---" ".--." "--.-" ".-." "..." "-" "..-" "...-" ".--" "-..-" "-.--" "--.." " " ] # -proc morse ch$ . . +proc morse ch$ . ind = strpos chars$ ch$ if ind > 0 write ch$ & " " diff --git a/Task/Morse-code/Java/morse-code.java b/Task/Morse-code/Java/morse-code-1.java similarity index 100% rename from Task/Morse-code/Java/morse-code.java rename to Task/Morse-code/Java/morse-code-1.java diff --git a/Task/Morse-code/Java/morse-code-2.java b/Task/Morse-code/Java/morse-code-2.java new file mode 100644 index 0000000000..32c825d049 --- /dev/null +++ b/Task/Morse-code/Java/morse-code-2.java @@ -0,0 +1,99 @@ +import java.util.Map; +import java.util.stream.IntStream; + +import javax.sound.sampled.AudioFormat; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.SourceDataLine; + +public final class MorseCode { + + public static void main(String[] args) { + Map morseCode = Map.ofEntries( + // International Morse Code, ITU standard + Map.entry("A", ".-"), Map.entry("B", "-..."), Map.entry("C", "-.-."), Map.entry("D", "-.."), + Map.entry("E", "."), Map.entry("F", "..-."), Map.entry("G", "--."), Map.entry("H", "...."), + Map.entry("I", ".."), Map.entry("J", ".---"), Map.entry("K", "-.-"), Map.entry("L", ".-.."), + Map.entry("M", "--"), Map.entry("N", "-."), Map.entry("O", "---"), Map.entry("P", ".--."), + Map.entry("Q", "--.-"), Map.entry("R", ".-."), Map.entry("S", "..."), Map.entry("T", "-"), + Map.entry("U", "..-"), Map.entry("V", "...-"), Map.entry("W", ".--"), Map.entry("X", "-..-"), + Map.entry("Y", "-.--"), Map.entry("Z", "--.."), + + Map.entry("1", ".----"), Map.entry("2", "..---"), Map.entry("3", "...--"), Map.entry("4", "....-"), + Map.entry("5", "....."), Map.entry("6", "-...."), Map.entry("7", "--..."), Map.entry("8", "---.."), + Map.entry("9", "----."), Map.entry("0", "-----"), + + // Generally accepted additions + Map.entry("'", ".----."), Map.entry(":", "---..."), Map.entry(",", "--..--"), Map.entry("-", "-....-"), + Map.entry("(", "-.--.-"), Map.entry(".", ".-.-.-"), Map.entry("?", "..--.."), Map.entry(";", "-.-.-."), + Map.entry("/", "-..-."), Map.entry(")", "---.."), Map.entry("=", "-...-"), Map.entry("@", ".--.-."), + Map.entry("\"", ".-..-."), Map.entry("+", ".-.-.") + ); + + prepareSourceDataLine(); + + final int frequency = 1280; // Frequency of the sound tone in Hertz + final int time = 250; // Time unit in milliseconds + + // Correct pacing of the sound transmission is essential for practical use + final int dot = 1; // Time units taken for one dot + final int dash = 3; // Time units taken for one dash + final int interval = 1; // Time units interval between dots and dashes + final int letterInterval = 1; // Time units interval between letters of a word + final int wordInterval = 7; // Time units interval between words + + String message = "Hello World"; + + for ( String letter : message.toUpperCase().split("") ) { + switch ( letter ) { + case " " -> tone(0, time * wordInterval, 0); + default -> { + String code = morseCode.get(letter); + for ( String dotDash : code.split("") ) { + switch ( dotDash ) { + case "." -> { tone(frequency, time * dot, 1); tone(0, time * interval, 0); } + case "-" -> { tone(frequency, time * dash, 1); tone(0, time * interval, 0); } + } + } + } + } + tone(0, time * letterInterval, 0); + } + } + + private static void tone(double frequency, int duration, int volume) { + sourceDataLine.start(); + + IntStream.range(0, 8 * duration).forEach( i -> { + final double angle = i / ( SAMPLE_RATE / frequency ) * 2 * Math.PI; + byte[] buffer = new byte[] { (byte) ( Math.sin(angle) * 127 * volume ) }; + sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length); + } ); + + sourceDataLine.drain(); + sourceDataLine.stop(); + } + + private static void prepareSourceDataLine() { + final int sampleSizeInBits = 8; + final int numberChannels = 1; + final boolean signedData = true; + final boolean isBigEndian = false; + + AudioFormat audioFormat = new AudioFormat( + SAMPLE_RATE, sampleSizeInBits, numberChannels, signedData, isBigEndian); + + try { + sourceDataLine = AudioSystem.getSourceDataLine(audioFormat); + sourceDataLine.open(audioFormat); + } catch (LineUnavailableException lue) { + lue.printStackTrace(); + } + } + + private static SourceDataLine sourceDataLine; + + private static float SAMPLE_RATE = 8_000.0F; + private static final int BYTE_OFFSET = 0; + +} diff --git a/Task/Motzkin-numbers/REXX/motzkin-numbers.rexx b/Task/Motzkin-numbers/REXX/motzkin-numbers.rexx index 742b20cb56..d601b7d240 100644 --- a/Task/Motzkin-numbers/REXX/motzkin-numbers.rexx +++ b/Task/Motzkin-numbers/REXX/motzkin-numbers.rexx @@ -1,43 +1,32 @@ -/*REXX program to display the first N Motzkin numbers, and if that number is prime. */ -numeric digits 92 /*max number of decimal digits for task*/ -parse arg n . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 42 /*Not specified? Then use the default.*/ -w= length(n) + 1; wm= digits()%4 /*define maximum widths for two columns*/ -say center('n', w ) center("Motzkin[n]", wm) center(' primality', 11) -say center('' , w, "─") center('' , wm, "─") center('', 11, "─") -@.= 1 /*define default vale for the @. array.*/ - do m=0 for n /*step through indices for Motzkin #'s.*/ - if m>1 then @.m= (@(m-1)*(m+m+1) + @(m-2)*(m*3-3))%(m+2) /*calculate a Motzkin #*/ - call show /*display a Motzkin number ──► terminal*/ - end /*m*/ +-- 22 Mar 2025 +include Settings +numeric digits 30 -say center('' , w, "─") center('' , wm, "─") center('', 11, "─") -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -@: parse arg i; return @.i /*return function expression based on I*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -prime: if isPrime(@.m) then return " prime"; return '' -show: y= commas(@.m); say right(m, w) right(y, max(wm, length(y))) prime(); return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure expose p?. p#. p_.; parse arg x /*persistent P·· REXX variables.*/ - if symbol('P?.#')\=='VAR' then /*1st time here? Then define primes. */ - do /*L is a list of some low primes < 100.*/ - L= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 - p?.=0 /* [↓] define P_index, P, P squared.*/ - do i=1 for words(L); _= word(L,i); p?._= 1; p#.i= _; p_.i= _*_ - end /*i*/; p?.0= x2d(3632c8eb5af3b) /*bypass big ÷*/ - p?.n= _ + 4 /*define next prime after last prime. */ - p?.#= i - 1 /*define the number of primes found. */ - end /* p?. p#. p_ must be unique. */ - if xhigh multiple Ps*/ - do k=p?.n by 6 while k*k<=x; if x//k ==0 then return 0 - if x//(k+2)==0 then return 0 - end /*k*/; return 1 /*Passed all divisions? It's a prime.*/ +say 'MOTZKIN NUMBERS' +say version +say +call Motzkins 1e20 +call Range 0 41 +say Time('e')/1 'seconds' +exit + +Range: +procedure expose motz. glob. +arg xx yy +if yy = '' then + yy = xx +say 'The Motzkin numbers from no' xx 'up to' yy 'are' +do i = xx to yy + m = motz.i + if prime(m) then + p = 'is prime' + else + p = '' + say 'M['right(i,2)']' right(m,18) p +end +return + +include Sequences +include Numbers +include Functions +include Abend diff --git a/Task/Mouse-position/EasyLang/mouse-position.easy b/Task/Mouse-position/EasyLang/mouse-position.easy index 42fc50d7a9..207262adb6 100644 --- a/Task/Mouse-position/EasyLang/mouse-position.easy +++ b/Task/Mouse-position/EasyLang/mouse-position.easy @@ -1,6 +1,5 @@ -move 10 80 on mouse_move - clear + gclear drawgrid - text mouse_x & " " & mouse_y + gtext 12 82 mouse_x & " " & mouse_y . diff --git a/Task/Mouse-position/Uxntal/mouse-position.uxnatl b/Task/Mouse-position/Uxntal/mouse-position.uxnatl index 5e484335dd..a925b61005 100644 --- a/Task/Mouse-position/Uxntal/mouse-position.uxnatl +++ b/Task/Mouse-position/Uxntal/mouse-position.uxnatl @@ -1,27 +1,24 @@ -|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 -|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 -|90 @Mouse &vector $2 &x $2 &y $2 &state $1 &pad $3 &scrollx $2 &scrolly $2 +% { [ LIT2 20 -Console/write ] DEO } +% { [ LIT2 0a -Console/write ] DEO } + +|10 @Console/vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|90 @Mouse/vector $2 &x $2 &y $2 &state $1 &pad $3 &scrollx $2 &scrolly $2 |0100 ;on-mouse .Mouse/vector DEO2 -BRK + BRK @on-mouse - .Mouse/x DEI2 print-hex2 - #20 .Console/write DEO - .Mouse/y DEI2 print-hex2 - #0a .Console/write DEO -BRK + .Mouse/x DEI2 + + .Mouse/y DEI2 + + BRK -@print-hex - DUP #04 SFT print-digit #0f AND print-digit -JMP2r - -@print-hex2 - SWP print-hex print-hex -JMP2r - -@print-digit - DUP #09 GTH #27 MUL ADD #30 ADD .Console/write DEO -JMP2r +@ ( short* -: ) + SWP /b + &b ( byte -: ) + DUP #04 SFT /c + &c ( byte -: ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD #18 DEO + JMP2r diff --git a/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy b/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy index 9ec20dfb56..ee166d3ff8 100644 --- a/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy +++ b/Task/Move-to-front-algorithm/EasyLang/move-to-front-algorithm.easy @@ -1,7 +1,7 @@ subr init symt$[] = strchars "abcdefghijklmnopqrstuvwxyz" . -proc rot k . . +proc rot k . c$ = symt$[k] for j = k downto 2 symt$[j] = symt$[j - 1] diff --git a/Task/Move-to-front-algorithm/Zig/move-to-front-algorithm.zig b/Task/Move-to-front-algorithm/Zig/move-to-front-algorithm.zig new file mode 100644 index 0000000000..8c42575a8a --- /dev/null +++ b/Task/Move-to-front-algorithm/Zig/move-to-front-algorithm.zig @@ -0,0 +1,78 @@ +const std = @import("std"); + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + const examples = [_][]const u8{ "broood", "bananaaa", "hiphophiphop" }; + + for (examples) |example| { + const encoded = try encode(allocator, example); + defer allocator.free(encoded); + + const decoded = try decode(allocator, encoded); + defer allocator.free(decoded); + + std.debug.print("{s} encodes to {any} decodes to {s}\n", .{ example, encoded, decoded }); + } +} + +fn getSymbols(allocator: std.mem.Allocator) ![]u8 { + var symbols = std.ArrayList(u8).init(allocator); + errdefer symbols.deinit(); + + var c: u8 = 'a'; + while (c <= 'z') : (c += 1) { + try symbols.append(c); + } + + return symbols.toOwnedSlice(); +} + +fn encode(allocator: std.mem.Allocator, input: []const u8) ![]usize { + var output = std.ArrayList(usize).init(allocator); + errdefer output.deinit(); + + var symbols = try getSymbols(allocator); + defer allocator.free(symbols); + + for (input) |byte| { + // Find position of the byte in symbols + var position: usize = 0; + for (symbols, 0..) |symbol, i| { + if (symbol == byte) { + position = i; + break; + } + } + + // Remove the byte at the position + const char = symbols[position]; + std.mem.copyForwards(u8, symbols[1..position + 1], symbols[0..position]); + symbols[0] = char; + + try output.append(position); + } + + return output.toOwnedSlice(); +} + +fn decode(allocator: std.mem.Allocator, input: []const usize) ![]u8 { + var output = std.ArrayList(u8).init(allocator); + errdefer output.deinit(); + + var symbols = try getSymbols(allocator); + defer allocator.free(symbols); + + for (input) |position| { + try output.append(symbols[position]); + + // Remove the byte at the position + const char = symbols[position]; + std.mem.copyForwards(u8, symbols[1..position + 1], symbols[0..position]); + symbols[0] = char; + } + + return output.toOwnedSlice(); +} diff --git a/Task/Multi-base-primes/REXX/multi-base-primes.rexx b/Task/Multi-base-primes/REXX/multi-base-primes.rexx index 1e787f514f..cc1c8d4378 100644 --- a/Task/Multi-base-primes/REXX/multi-base-primes.rexx +++ b/Task/Multi-base-primes/REXX/multi-base-primes.rexx @@ -1,44 +1,66 @@ -/*REXX pgm finds primes whose values in other bases (2──►36) have the most diff. bases. */ -parse arg widths . /*obtain optional argument from the CL.*/ -if widths=='' | widths=="," then widths= 5 /*Not specified? Then use the default.*/ -call genP /*build array of semaphores for primes.*/ -names= 'one two three four five six seven eight' /*names for some low decimal numbers. */ -$.= - do j=1 for # /*only use primes that are within range*/ - do b=36 by -1 for 35; n= base(@.j, b) /*use different bases for each prime. */ - L= length(n); if L>widths then iterate /*obtain length; Length too big? Skip.*/ - if L==1 then $.L.n= b $.L.n /*Length = unity? Prepend the base.*/ - else $.L.n= $.L.n b /* " ¬= " Append " " */ - end /*b*/ - end /*j*/ - /*display info for each of the widths. */ - do w=1 for widths; cnt= 0 /*show for each width: cnt,number,bases*/ - bot= left(1, w, 0); top= left(9, w, 9) /*calculate range for DO. */ - do n=bot to top; y= words($.w.n) /*find the sets of numbers for a width.*/ - if y>cnt then do; mxn=n; cnt= max(cnt, y); end /*found a max? Remember it*/ - end /*n*/ - say - say; say center(' 'word(names, w)"─character numbers that are" , - 'prime in the most bases: ('cnt "bases) ", 101, '─') - do n=bot to top; y= words($.w.n) /*search again for maximums.*/ - if y==cnt then say n '──►' strip($.w.n) /*display ───a─── maximum. */ - end /*n*/ - end /*w*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -base: procedure; parse arg x,r,,z; @= '0123456789abcdefghijklmnopqrsruvwxyz' - do j=1; _= r**j; if _>x then leave - end /*j*/ - do k=j-1 to 1 by -1; _= r**k; z= z || substr(@, (x % _) + 1, 1); x= x // _ - end /*k*/; return z || substr(@, x+1, 1) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */ - #= 5; sq.#= @.# ** 2 /*number primes so far; prime squared.*/ - do j=@.#+2 by 2 to 2 * 36 * 10**widths /*find odd primes from here on. */ - parse var j '' -1 _; if _==5 then iterate /*J is ÷ by 5? (right dig).*/ - if j//3==0 then iterate; if j//7==0 then iterate /*" " " " 3?; ÷ by 7? */ - do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ - if j//@.k==0 then iterate j /*Is J ÷ X? Then not prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= # + 1; @.#= j; sq.#= j*j /*bump # Ps; assign next P; P squared.*/ - end /*j*/; return +-- 22 Mar 2025 +include Settings + +say 'MULTI-BASE PRIMES' +say version +say +arg ww +if ww = '' then + ww = 4 +call GetPrimes +call Collect +call Report +exit + +GetPrimes: +call time('r') +a = 2*36*10**ww +say 'Get primes up to' a'...' +call Primes 2*36*10**ww +say Time('e')/1 'seconds'; say +return + +Collect: +call time('r') +say 'Collect bases up to' ww'-character numbers...' +base. = '' +do j = 1 to prim.0 + do b = 36 by -1 to 2 + n = Basenn(prim.j,b); l = Length(n) + if l > ww then + iterate + if l = 1 then + base.l.n = b base.l.n + else + base.l.n = base.l.n b + end +end +say Time('e')/1 'seconds'; say +return + +Report: +call time('r') +say 'Report bases up to' ww'-character numbers...' +do w = 1 to ww + a = Left(1,w,0); b = Left(9,w,9); c = 0 + do n = a to b + y = Words(base.w.n) + if y > c then do + mxn = n; c = Max(c,y) + end + end + say w'-character numbers that are prime in the most bases ('c')' + do n = a to b + y = Words(base.w.n) + if y = c then + say n 'in' Strip(base.w.n) + end + say +end +say Time('e')/1 'seconds'; say +return + +include Sequences +include Numbers +include Functions +include Abend diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-1.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-1.basic new file mode 100644 index 0000000000..3a3478d7ad --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-1.basic @@ -0,0 +1,5 @@ +NEW +DIM A%(1,1) +A%(0,0)=1 +A%(0,1)=2 +CALL-151 : REM enter the machine language monitor to inspect memory diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-2.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-2.basic new file mode 100644 index 0000000000..7196c6c02c --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-2.basic @@ -0,0 +1 @@ +800.817 E000G dump the array memory and cold start BASIC diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-3.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-3.basic new file mode 100644 index 0000000000..24f8b028ad --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-3.basic @@ -0,0 +1 @@ +DIM A(4,3,2,1) diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-4.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-4.basic new file mode 100644 index 0000000000..bd4ca73386 --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-4.basic @@ -0,0 +1,5 @@ + 0 DATA3 + 1 DIM A(4,3,2,1) + 2 GET A(4,3,2,1) + 3 INPUT A(4,3,2,1) + 4 READ A(4,3,2,1) diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-5.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-5.basic new file mode 100644 index 0000000000..f7081fdaea --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-5.basic @@ -0,0 +1 @@ +RUN diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-6.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-6.basic new file mode 100644 index 0000000000..2f742aa6c7 --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-6.basic @@ -0,0 +1 @@ +LET A(4,3,2,1) = 1 : REM the LET keyword is optional diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-7.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-7.basic new file mode 100644 index 0000000000..fef7f0345e --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-7.basic @@ -0,0 +1 @@ +PRINT A(4,3,2,1) : REM arrays can be accessed in expressions diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-8.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-8.basic new file mode 100644 index 0000000000..3a1713158f --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-8.basic @@ -0,0 +1 @@ +A(4,3,2,1) = 2 diff --git a/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-9.basic b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-9.basic new file mode 100644 index 0000000000..e3ee8c3204 --- /dev/null +++ b/Task/Multi-dimensional-array/Applesoft-BASIC/multi-dimensional-array-9.basic @@ -0,0 +1 @@ +PRINT A(4,3,2,1) diff --git a/Task/Multi-dimensional-array/C++/multi-dimensional-array.cpp b/Task/Multi-dimensional-array/C++/multi-dimensional-array-1.cpp similarity index 88% rename from Task/Multi-dimensional-array/C++/multi-dimensional-array.cpp rename to Task/Multi-dimensional-array/C++/multi-dimensional-array-1.cpp index e471fe5954..9aca4766f7 100644 --- a/Task/Multi-dimensional-array/C++/multi-dimensional-array.cpp +++ b/Task/Multi-dimensional-array/C++/multi-dimensional-array-1.cpp @@ -1,7 +1,7 @@ #include #include -// convienince for printing the contents of a collection +// convenience for printing the contents of a collection template std::ostream& operator<<(std::ostream& out, const std::vector& c) { auto it = c.cbegin(); @@ -57,9 +57,9 @@ void fourDim() { } int main() { - /* C++ does not have native support for multi-dimensional arrays, + /* C++ hasn't had native support for multi-dimensional arrays, * but classes could be written to make things easier to work with. - * There are standard library classes which can be used for single dimension arrays. + * std::vector<>, std::array<> and even int[] can be composed to create multidimensional arrays. * Also raw access is supported through pointers as in C. */ diff --git a/Task/Multi-dimensional-array/C++/multi-dimensional-array-2.cpp b/Task/Multi-dimensional-array/C++/multi-dimensional-array-2.cpp new file mode 100644 index 0000000000..a77f26c762 --- /dev/null +++ b/Task/Multi-dimensional-array/C++/multi-dimensional-array-2.cpp @@ -0,0 +1,80 @@ +#include // array +#include // mdspan +#include // ranges::iota +#include // println +#include // views::{cartesian_product, iota, take, transform} +#include // apply + +using namespace std; + +template + requires((Extents != dynamic_extent) && ...) && (sizeof...(Extents) < 10) +static consteval auto generate_array(extents) -> array { + + // Generate a sequence of numbers (0..size) to fit into the array + auto ret = array{}; + ranges::iota(ret, 0); + + return ret; +} + +// Given extents of size i, create right-index arrays of size i +// That is, a combination of indices that increment from the right-side first +template + requires((Extents != dynamic_extent) && ...) +static consteval auto right_indices(extents) { + + // Generate all combinations of (0..2, 0..3, 0..4, 0..5) + constexpr auto index_ranges = views::cartesian_product(views::iota(size_t{}, Extents)...); + + // Convert tuple of numbers (a, b, c, d) to array of numbers [a, b, c, d] + constexpr auto tuple_to_array = [](auto &&tuple) { + return apply([](auto... elems) { return array{elems...}; }, tuple); + }; + + return index_ranges | views::transform(tuple_to_array); +} + +int main() { + // This type models the size of our backing array and the shape of the mdspan + using exts = extents; + + auto backing_array = generate_array(exts{}); + constexpr auto array_indices = right_indices(exts{}); + + // mdspan accesses the underlying array in row-major ordering (std::layout_right) by default + auto row_span = mdspan{backing_array.data(), exts{}}; + auto col_span = mdspan{backing_array.data(), layout_left::mapping{exts{}}}; + + // print out the rank count and size of the underlying data structure + println("row_span.rank() = {}", row_span.rank()); + println("row_span.size() = {}", row_span.size()); + + // Display the size of each dimension + for (auto &&i : views::iota(size_t{}, row_span.rank())) { + println("row_span.extent({}) = {}, ", i, row_span.extent(i)); + } + + /// Add-assign a value using the multidimensional subscript operator + row_span[0, 0, 0, 0] += 999; + + // We can't iterate through our dim_span directly, so we have to index through it instead + // Here we demonstrate the ability to index into an mdspan with an array + // + // indexing out of bounds with [] is still undefined behavior + // There is no .at() equivalent for throwing access + + println("\n======================== Row-major =======================\n"); + + println("First 30 elements:\n{}", + array_indices | views::take(30) | + views::transform( + [&](array &&idc) -> int { return row_span[idc]; })); + + println("\n=========== Column-major (right_array_indices) ===========\n"); + + println("First 30 elements:\n{}", + array_indices | views::take(30) | + views::transform( + [&](array &&idc) -> int { return col_span[idc]; })); +} diff --git a/Task/Multiplication-tables/EasyLang/multiplication-tables.easy b/Task/Multiplication-tables/EasyLang/multiplication-tables.easy index f1cd5095ec..1dc483371a 100644 --- a/Task/Multiplication-tables/EasyLang/multiplication-tables.easy +++ b/Task/Multiplication-tables/EasyLang/multiplication-tables.easy @@ -1,14 +1,10 @@ n = 12 -numfmt 0 4 +numfmt 4 0 write " " -for i = 1 to n - write i -. +for i = 1 to n : write i print "" write " " -for i = 1 to n - write "----" -. +for i = 1 to n : write "----" print "" for i = 1 to n write i diff --git a/Task/Multiplication-tables/Objeck/multiplication-tables.objeck b/Task/Multiplication-tables/Objeck/multiplication-tables.objeck new file mode 100644 index 0000000000..802fe8d28c --- /dev/null +++ b/Task/Multiplication-tables/Objeck/multiplication-tables.objeck @@ -0,0 +1,25 @@ +class MulTbl { + function : Main(args : String[]) ~ Nil { + for(i := 1; i <= 12; i++;) { + "\t{$i}"->Print(); + }; + + ""->PrintLine(); + for(i := 0; i < 100; i++;) { + ("-")->Print(); + }; + + ""->PrintLine(); + for(i := 1; i <= 12; i++;) { + "{$i}|"->Print(); + for(j := 1; j <= 12; j++) { + "\t"->Print(); + if (j >= i) { + s := i * j; + "{$s}"->Print(); + }; + }; + ""->PrintLine(); + }; + } +} diff --git a/Task/Multisplit/EasyLang/multisplit.easy b/Task/Multisplit/EasyLang/multisplit.easy index ac60f0d2ff..9f6e2551db 100644 --- a/Task/Multisplit/EasyLang/multisplit.easy +++ b/Task/Multisplit/EasyLang/multisplit.easy @@ -1,4 +1,4 @@ -proc multisplit str$ sep$[] . . +proc multisplit str$ sep$[] . repeat min = 1 / 0 for sep$ in sep$[] diff --git a/Task/Munchausen-numbers/J/munchausen-numbers-3.j b/Task/Munchausen-numbers/J/munchausen-numbers-3.j new file mode 100644 index 0000000000..3d79f08bd8 --- /dev/null +++ b/Task/Munchausen-numbers/J/munchausen-numbers-3.j @@ -0,0 +1,7 @@ + load 'stats/base/combinatorial' + nDigits =: 4 + p =: 0 1 4 27 256 3125 46656 823543 16777216 387420489 + sp =: [:+/"1 p{~] + dg =: 10&#.inv + (sp@#~[:-:/"2[:/:~"1(],:~dg@sp)"1) nDigits combrep 10 +0 1 3435 diff --git a/Task/Munchausen-numbers/R/munchausen-numbers.r b/Task/Munchausen-numbers/R/munchausen-numbers.r new file mode 100644 index 0000000000..8079ca1175 --- /dev/null +++ b/Task/Munchausen-numbers/R/munchausen-numbers.r @@ -0,0 +1,10 @@ +exp_digsum <- function(n){ + if(n>9){ + return((n%%10)^(n%%10)+exp_digsum(n%/%10)) + } + else return(n^n) +} + +for(i in 1:5000){ + if(exp_digsum(i)==i) print(i) +} diff --git a/Task/Munching-squares/Arturo/munching-squares.arturo b/Task/Munching-squares/Arturo/munching-squares.arturo new file mode 100644 index 0000000000..8e945b6747 --- /dev/null +++ b/Task/Munching-squares/Arturo/munching-squares.arturo @@ -0,0 +1,9 @@ +; outputs a PPM image file +imgSize: 256 +image: ~"P3\n|imgSize| |imgSize|\n255\n" + +loop 0..dec imgSize 'row -> + loop 0..dec imgSize 'col -> + 'image ++ ~"|xor row col| |or row col| |and row col|\n" + +write image ./"munching.ppm" diff --git a/Task/Munching-squares/EasyLang/munching-squares.easy b/Task/Munching-squares/EasyLang/munching-squares.easy index b888d2e392..78ae2c25f5 100644 --- a/Task/Munching-squares/EasyLang/munching-squares.easy +++ b/Task/Munching-squares/EasyLang/munching-squares.easy @@ -1,9 +1,8 @@ sc = 100 / 64 -for x range0 64 - for y range0 64 +for x = 0 to 63 + for y = 0 to 63 h = bitand bitxor x y 63 / 63 - color3 h h h - move x * sc y * sc - rect sc + 0.1 sc + 0.1 + gcolor3 h h h + grect x * sc y * sc sc + 0.1 sc + 0.1 . . diff --git a/Task/Munching-squares/Uiua/munching-squares.uiua b/Task/Munching-squares/Uiua/munching-squares.uiua new file mode 100644 index 0000000000..eb4602c5a0 --- /dev/null +++ b/Task/Munching-squares/Uiua/munching-squares.uiua @@ -0,0 +1 @@ +÷256⊞[0.⍜∩⋯⬚0≠].⇡256 diff --git a/Task/Musical-scale/Java/musical-scale.java b/Task/Musical-scale/Java/musical-scale.java index 41061e9847..8ee6d59a24 100644 --- a/Task/Musical-scale/Java/musical-scale.java +++ b/Task/Musical-scale/Java/musical-scale.java @@ -1,4 +1,6 @@ import java.util.List; +import java.util.stream.IntStream; + import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; @@ -7,48 +9,54 @@ import javax.sound.sampled.SourceDataLine; public final class MusicalScale { public static void main(String[] aArgs) { - List frequencies = List.of( 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 ); - final int duration = 500; + List frequencies = List.of( 261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25 ); + + prepareSourceDataLine(); + + final int duration = 500; // in milliseconds final int volume = 1; - for ( int i = 0; i < 3; i++ ) { + IntStream.range(0, 3).forEach( _ -> { for ( double frequency : frequencies ) { musicalTone(frequency, duration, volume); } - } + } ); + + sourceDataLine.close(); } - private static void musicalTone(double aFrequency, int aDuration, int aVolume) { - byte[] buffer = new byte[1]; - AudioFormat audioFormat = getAudioFormat(); + private static void musicalTone(double frequency, int duration, int volume) { + sourceDataLine.start(); - try ( SourceDataLine sourceDataLine = AudioSystem.getSourceDataLine(audioFormat) ) { - sourceDataLine.open(audioFormat); - sourceDataLine.start(); - - for ( int i = 0; i < aDuration * 8; i++ ) { - double angle = i / ( SAMPLE_RATE / aFrequency ) * 2 * Math.PI; - buffer[0] = (byte) ( Math.sin(angle) * 127 * aVolume ); - sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length); - } - - sourceDataLine.drain(); - sourceDataLine.stop(); - sourceDataLine.close(); - } catch (LineUnavailableException exception) { - exception.printStackTrace(); - } + IntStream.range(0, 8 * duration).forEach( i -> { + final double angle = i / ( SAMPLE_RATE / frequency ) * 2 * Math.PI; + byte[] buffer = new byte[] { (byte) ( Math.sin(angle) * 127 * volume ) }; + sourceDataLine.write(buffer, BYTE_OFFSET, buffer.length); + } ); + + sourceDataLine.drain(); + sourceDataLine.stop(); } - private static AudioFormat getAudioFormat() { + private static void prepareSourceDataLine() { final int sampleSizeInBits = 8; final int numberChannels = 1; final boolean signedData = true; final boolean isBigEndian = false; - return new AudioFormat(SAMPLE_RATE, sampleSizeInBits, numberChannels, signedData, isBigEndian); + AudioFormat audioFormat = new AudioFormat( + SAMPLE_RATE, sampleSizeInBits, numberChannels, signedData, isBigEndian); + + try { + sourceDataLine = AudioSystem.getSourceDataLine(audioFormat); + sourceDataLine.open(audioFormat); + } catch (LineUnavailableException lue) { + lue.printStackTrace(); + } } + private static SourceDataLine sourceDataLine; + private static float SAMPLE_RATE = 8_000.0F; private static final int BYTE_OFFSET = 0; diff --git a/Task/Musical-scale/JavaScript/musical-scale.js b/Task/Musical-scale/JavaScript/musical-scale.js index aae2540dd2..77a3ebe4a3 100644 --- a/Task/Musical-scale/JavaScript/musical-scale.js +++ b/Task/Musical-scale/JavaScript/musical-scale.js @@ -1,36 +1,36 @@ - - - - -Sample Page - - - - - - + +function playNotes(root, notes, { seconds, wave } = {}) { + const ctx = new AudioContext() + const oscillator = ctx.createOscillator() + const freqs = notes.map(incrementSemitones(root)) + + oscillator.connect(ctx.createGain().connect(ctx.destination)) + oscillator.type = wave ?? 'sine' + + const duration = seconds ?? 0.3 + + for (const [i, freq] of freqs.entries()) { + oscillator.frequency.setValueAtTime(freq, ctx.currentTime + i * duration) + } + + oscillator.start() + oscillator.stop(ctx.currentTime + freqs.length * duration) + + return new Promise((res) => oscillator.addEventListener('ended', res)) +} + +const A = 440 +const C = incrementSemitones(A)(-9) // ~= 261.63 + +const major = [0, 2, 4, 5, 7, 9, 11, 12] +const minor = [0, 2, 3, 5, 7, 8, 10, 12] + +void (async function main() { + await playNotes(C, major, { seconds: 0.3, wave: 'sine' }) + await playNotes(A, minor, { seconds: 0.1, wave: 'triangle' }) +})() diff --git a/Task/N-queens-problem/C/n-queens-problem-1.c b/Task/N-queens-problem/C/n-queens-problem-1.c index 8b4dc90905..151b12f9c9 100644 --- a/Task/N-queens-problem/C/n-queens-problem-1.c +++ b/Task/N-queens-problem/C/n-queens-problem-1.c @@ -34,10 +34,10 @@ advance_row: } col = 0; try_column: - if (!a[col] && !b[col+row-1] && !c[col-row+n]) { + if (!a[col] && !b[col+row] && !c[col-row+n-1]) { a[col] = true; - b[col+row-1] = true; - c[col-row+n] = true; + b[col+row] = true; + c[col-row+n-1] = true; x[row] = col; row++; goto advance_row; @@ -51,8 +51,8 @@ backtrack: if (row != 0) { --row; col = x[row]; - c[col-row+n] = false; - b[col+row-1] = false; + c[col-row+n-1] = false; + b[col+row] = false; a[col] = false; goto try_again; } @@ -60,9 +60,8 @@ backtrack: static void *calloc_wrapper(size_t count, size_t bytesize) { void *r; - if ((r = calloc(count, bytesize)) == NULL) { + if ((r = calloc(count, bytesize)) == NULL) exit(EXIT_FAILURE); - } return r; } diff --git a/Task/N-queens-problem/Jq/n-queens-problem-6.jq b/Task/N-queens-problem/Jq/n-queens-problem-6.jq new file mode 100644 index 0000000000..ab836a6131 --- /dev/null +++ b/Task/N-queens-problem/Jq/n-queens-problem-6.jq @@ -0,0 +1,38 @@ +def queens(n): + def q: . as $pl + | $pl[4] as $r + | $pl[3] as $cl | $cl[] | . as $c + | ($r+$c | tostring) as $k0 + | ($r-$c | tostring) as $k1 + | def place: + ($k0 | in($pl[1]) | not) + and ($k1 | in($pl[2]) | not); + select(place) + | [$pl[0]+[$c], $pl[1]+{$k0:null}, + $pl[2]+{$k1:null}, $cl-[$c], $r+1]; + def pipeline(n): + q | if n > 1 then pipeline(n-1) end; + def toletter: + "abcdefghijklmnopqrstuvwxyz"[.:.+1]; + def fund_solut(f): + def inverse: . as $xl + | reduce range(0; n) as $i + ([]; .+[$xl | index($i)]); + def variants: + [., inverse] | map(., reverse) + | map(., map(n-1-.)) + | map(map(toletter) | add); + foreach f as $i + ([null, {}]; .[1] as $ml + | ($i | variants) as $nl + | if all($nl[]; in($ml) | not) then + [$i, ($ml | .[$nl[]]=null)] + else + [null, $ml] end; + .[0]) + | select (. != null); + fund_solut([[], {}, {}, [range(0; n)], 0] + | pipeline(n) | .[0]) + | map(toletter) | to_entries + | map(.value+(.key+1 | tostring)) | sort; +queens(8) diff --git a/Task/N-queens-problem/Jq/n-queens-problem-7.jq b/Task/N-queens-problem/Jq/n-queens-problem-7.jq new file mode 100644 index 0000000000..9c6b1ee068 --- /dev/null +++ b/Task/N-queens-problem/Jq/n-queens-problem-7.jq @@ -0,0 +1,13 @@ +$ jq -nc -f ./queens.jq +["a1","b7","c5","d8","e2","f4","g6","h3"] +["a1","b7","c4","d6","e8","f2","g5","h3"] +["a6","b1","c5","d2","e8","f3","g7","h4"] +["a4","b1","c5","d8","e2","f7","g3","h6"] +["a5","b1","c8","d4","e2","f7","g3","h6"] +["a3","b1","c7","d5","e8","f2","g4","h6"] +["a5","b1","c4","d6","e8","f2","g7","h3"] +["a7","b1","c3","d8","e6","f4","g2","h5"] +["a5","b1","c8","d6","e3","f7","g2","h4"] +["a5","b3","c1","d7","e2","f8","g6","h4"] +["a5","b7","c1","d4","e2","f8","g6","h3"] +["a6","b3","c1","d8","e4","f2","g7","h5"] diff --git a/Task/N-queens-problem/Python/n-queens-problem-10.py b/Task/N-queens-problem/Python/n-queens-problem-10.py new file mode 100644 index 0000000000..8a1791f8f8 --- /dev/null +++ b/Task/N-queens-problem/Python/n-queens-problem-10.py @@ -0,0 +1,13 @@ +$ python3 ./queens.py +['a1', 'b7', 'c5', 'd8', 'e2', 'f4', 'g6', 'h3'] +['a1', 'b7', 'c4', 'd6', 'e8', 'f2', 'g5', 'h3'] +['a6', 'b1', 'c5', 'd2', 'e8', 'f3', 'g7', 'h4'] +['a4', 'b1', 'c5', 'd8', 'e2', 'f7', 'g3', 'h6'] +['a5', 'b1', 'c8', 'd4', 'e2', 'f7', 'g3', 'h6'] +['a3', 'b1', 'c7', 'd5', 'e8', 'f2', 'g4', 'h6'] +['a5', 'b1', 'c4', 'd6', 'e8', 'f2', 'g7', 'h3'] +['a7', 'b1', 'c3', 'd8', 'e6', 'f4', 'g2', 'h5'] +['a5', 'b1', 'c8', 'd6', 'e3', 'f7', 'g2', 'h4'] +['a5', 'b3', 'c1', 'd7', 'e2', 'f8', 'g6', 'h4'] +['a5', 'b7', 'c1', 'd4', 'e2', 'f8', 'g6', 'h3'] +['a6', 'b3', 'c1', 'd8', 'e4', 'f2', 'g7', 'h5'] diff --git a/Task/N-queens-problem/Python/n-queens-problem-5.py b/Task/N-queens-problem/Python/n-queens-problem-5.py index 7cc53040e3..040ec86b2b 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-5.py +++ b/Task/N-queens-problem/Python/n-queens-problem-5.py @@ -6,6 +6,5 @@ def queens(n: int, i: int, a: list, b: list, c: list): else: yield a - for solution in queens(8, 0, [], [], []): print(solution) diff --git a/Task/N-queens-problem/Python/n-queens-problem-6.py b/Task/N-queens-problem/Python/n-queens-problem-6.py index 2f6cb0cbf0..acc9a23854 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-6.py +++ b/Task/N-queens-problem/Python/n-queens-problem-6.py @@ -1,14 +1,23 @@ -def queens(i: int, a: set): - if a: # set a is not empty - for j in a: - if i + j not in b and i - j not in c: - b.add(i + j); c.add(i - j); x.append(j) - yield from queens(i + 1, a - {j}) - b.remove(i + j); c.remove(i - j); x.pop() - else: - yield x +def queens(n: int): + + def sub(i: int): + if i < n: + for k in range(i, n): + j = a[k] + if b[i + j] and c[i - j]: + a[i], a[k] = a[k], a[i] + b[i + j] = c[i - j] = False + yield from sub(i + 1) + b[i + j] = c[i - j] = True + a[i], a[k] = a[k], a[i] + else: + yield a + + a = list(range(n)) + b = [True] * (2 * n - 1) + c = [True] * (2 * n - 1) + yield from sub(0) -b = set(); c = set(); x = [] -for solution in queens(0, set(range(8))): - print(solution) +sum(1 for solution in queens(8)) # count solutions +92 diff --git a/Task/N-queens-problem/Python/n-queens-problem-7.py b/Task/N-queens-problem/Python/n-queens-problem-7.py index f404b4c1dc..3a6b107381 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-7.py +++ b/Task/N-queens-problem/Python/n-queens-problem-7.py @@ -1,15 +1,15 @@ -def queens(n: int): +def queens_lex(n: int): def sub(i: int): if i < n: for k in range(i, n): j = a[k] + a[i], a[k] = a[k], a[i] if b[i + j] and c[i - j]: - a[i], a[k] = a[k], a[i] b[i + j] = c[i - j] = False yield from sub(i + 1) b[i + j] = c[i - j] = True - a[i], a[k] = a[k], a[i] + a[i:(n - 1)], a[n - 1] = a[(i + 1):n], a[i] else: yield a @@ -19,5 +19,11 @@ def queens(n: int): yield from sub(0) -sum(1 for p in queens(8)) # count solutions -92 +next(queens(31)) +[0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20] + +next(queens_lex(31)) +[0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20] + +#Compare to A065188 +#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ... diff --git a/Task/N-queens-problem/Python/n-queens-problem-8.py b/Task/N-queens-problem/Python/n-queens-problem-8.py index 3a6b107381..dd102072e1 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-8.py +++ b/Task/N-queens-problem/Python/n-queens-problem-8.py @@ -1,29 +1,146 @@ -def queens_lex(n: int): +'''N Queens problem''' - def sub(i: int): - if i < n: - for k in range(i, n): - j = a[k] - a[i], a[k] = a[k], a[i] - if b[i + j] and c[i - j]: - b[i + j] = c[i - j] = False - yield from sub(i + 1) - b[i + j] = c[i - j] = True - a[i:(n - 1)], a[n - 1] = a[(i + 1):n], a[i] - else: - yield a - - a = list(range(n)) - b = [True] * (2 * n - 1) - c = [True] * (2 * n - 1) - yield from sub(0) +from functools import reduce +from itertools import chain -next(queens(31)) -[0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20] +# queenPuzzle :: Int -> Int -> [[Int]] +def queenPuzzle(nCols): + '''All board patterns of this dimension + in which no two Queens share a row, + column, or diagonal. + ''' + def go(nRows): + lessRows = nRows - 1 + return reduce( + lambda a, xys: a + reduce( + lambda b, iCol: b + [xys + [iCol]] if ( + safe(lessRows, iCol, xys) + ) else b, + enumFromTo(1)(nCols), + [] + ), + go(lessRows), + [] + ) if 0 < nRows else [[]] + return go -next(queens_lex(31)) -[0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20] -#Compare to A065188 -#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ... +# safe :: Int -> Int -> [Int] -> Bool +def safe(iRow, iCol, pattern): + '''True if no two queens in the pattern + share a row, column or diagonal. + ''' + def p(sc, sr): + return (iCol == sc) or ( + sc + sr == (iCol + iRow) + ) or (sc - sr == (iCol - iRow)) + return not any(map(p, pattern, range(0, iRow))) + + +# ------------------------- TEST ------------------------- +# main :: IO () +def main(): + '''Number of solutions for boards of various sizes''' + + n = 5 + xs = queenPuzzle(n)(n) + + print( + str(len(xs)) + ' solutions for a {n} * {n} board:\n'.format(n=n) + ) + print(showBoards(10)(xs)) + + print( + fTable( + '\n\n' + main.__doc__ + ':\n' + )(str)(lambda n: str(n).rjust(3, ' '))( + lambda n: len(queenPuzzle(n)(n)) + )(enumFromTo(1)(10)) + ) + + +# ---------------------- FORMATTING ---------------------- + +# showBoards :: Int -> [[Int]] -> String +def showBoards(nCols): + '''String representation, with N columns + of a set of board patterns. + ''' + def showBlock(b): + return '\n'.join(map(intercalate(' '), zip(*b))) + + def go(bs): + return '\n\n'.join(map( + showBlock, + chunksOf(nCols)([ + showBoard(b) for b in bs + ]) + )) + return go + + +# showBoard :: [Int] -> String +def showBoard(xs): + '''String representation of a Queens board.''' + lng = len(xs) + + def showLine(n): + return ('.' * (n - 1)) + '♛' + ('.' * (lng - n)) + return map(showLine, xs) + + +# fTable :: String -> (a -> String) -> +# (b -> String) -> (a -> b) -> [a] -> String +def fTable(s): + '''Heading -> x display function -> fx display function -> + f -> xs -> tabular string. + ''' + def go(xShow, fxShow, f, xs): + ys = [xShow(x) for x in xs] + w = max(map(len, ys)) + return s + '\n' + '\n'.join(map( + lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), + xs, ys + )) + return lambda xShow: lambda fxShow: lambda f: lambda xs: go( + xShow, fxShow, f, xs + ) + + +# ----------------------- GENERIC ------------------------ + +# enumFromTo :: (Int, Int) -> [Int] +def enumFromTo(m): + '''Integer enumeration from m to n.''' + return lambda n: range(m, 1 + n) + + +# chunksOf :: Int -> [a] -> [[a]] +def chunksOf(n): + '''A series of lists of length n, subdividing the + contents of xs. Where the length of xs is not evenly + divible, the final list will be shorter than n. + ''' + return lambda xs: reduce( + lambda a, i: a + [xs[i:n + i]], + range(0, len(xs), n), [] + ) if 0 < n else [] + + +# intercalate :: [a] -> [[a]] -> [a] +# intercalate :: String -> [String] -> String +def intercalate(x): + '''The concatenation of xs + interspersed with copies of x. + ''' + return lambda xs: x.join(xs) if isinstance(x, str) else list( + chain.from_iterable( + reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]]) + ) + ) if xs else [] + + +# MAIN --- +if __name__ == '__main__': + main() diff --git a/Task/N-queens-problem/Python/n-queens-problem-9.py b/Task/N-queens-problem/Python/n-queens-problem-9.py index dd102072e1..9e9a11ad39 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-9.py +++ b/Task/N-queens-problem/Python/n-queens-problem-9.py @@ -1,146 +1,34 @@ -'''N Queens problem''' - -from functools import reduce -from itertools import chain - - -# queenPuzzle :: Int -> Int -> [[Int]] -def queenPuzzle(nCols): - '''All board patterns of this dimension - in which no two Queens share a row, - column, or diagonal. - ''' - def go(nRows): - lessRows = nRows - 1 - return reduce( - lambda a, xys: a + reduce( - lambda b, iCol: b + [xys + [iCol]] if ( - safe(lessRows, iCol, xys) - ) else b, - enumFromTo(1)(nCols), - [] - ), - go(lessRows), - [] - ) if 0 < nRows else [[]] - return go - - -# safe :: Int -> Int -> [Int] -> Bool -def safe(iRow, iCol, pattern): - '''True if no two queens in the pattern - share a row, column or diagonal. - ''' - def p(sc, sr): - return (iCol == sc) or ( - sc + sr == (iCol + iRow) - ) or (sc - sr == (iCol - iRow)) - return not any(map(p, pattern, range(0, iRow))) - - -# ------------------------- TEST ------------------------- -# main :: IO () -def main(): - '''Number of solutions for boards of various sizes''' - - n = 5 - xs = queenPuzzle(n)(n) - - print( - str(len(xs)) + ' solutions for a {n} * {n} board:\n'.format(n=n) - ) - print(showBoards(10)(xs)) - - print( - fTable( - '\n\n' + main.__doc__ + ':\n' - )(str)(lambda n: str(n).rjust(3, ' '))( - lambda n: len(queenPuzzle(n)(n)) - )(enumFromTo(1)(10)) - ) - - -# ---------------------- FORMATTING ---------------------- - -# showBoards :: Int -> [[Int]] -> String -def showBoards(nCols): - '''String representation, with N columns - of a set of board patterns. - ''' - def showBlock(b): - return '\n'.join(map(intercalate(' '), zip(*b))) - - def go(bs): - return '\n\n'.join(map( - showBlock, - chunksOf(nCols)([ - showBoard(b) for b in bs - ]) - )) - return go - - -# showBoard :: [Int] -> String -def showBoard(xs): - '''String representation of a Queens board.''' - lng = len(xs) - - def showLine(n): - return ('.' * (n - 1)) + '♛' + ('.' * (lng - n)) - return map(showLine, xs) - - -# fTable :: String -> (a -> String) -> -# (b -> String) -> (a -> b) -> [a] -> String -def fTable(s): - '''Heading -> x display function -> fx display function -> - f -> xs -> tabular string. - ''' - def go(xShow, fxShow, f, xs): - ys = [xShow(x) for x in xs] - w = max(map(len, ys)) - return s + '\n' + '\n'.join(map( - lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), - xs, ys - )) - return lambda xShow: lambda fxShow: lambda f: lambda xs: go( - xShow, fxShow, f, xs - ) - - -# ----------------------- GENERIC ------------------------ - -# enumFromTo :: (Int, Int) -> [Int] -def enumFromTo(m): - '''Integer enumeration from m to n.''' - return lambda n: range(m, 1 + n) - - -# chunksOf :: Int -> [a] -> [[a]] -def chunksOf(n): - '''A series of lists of length n, subdividing the - contents of xs. Where the length of xs is not evenly - divible, the final list will be shorter than n. - ''' - return lambda xs: reduce( - lambda a, i: a + [xs[i:n + i]], - range(0, len(xs), n), [] - ) if 0 < n else [] - - -# intercalate :: [a] -> [[a]] -> [a] -# intercalate :: String -> [String] -> String -def intercalate(x): - '''The concatenation of xs - interspersed with copies of x. - ''' - return lambda xs: x.join(xs) if isinstance(x, str) else list( - chain.from_iterable( - reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]]) - ) - ) if xs else [] - - -# MAIN --- -if __name__ == '__main__': - main() +def queens(n): + def q(pl, r): + def place(c): + return r+c not in pl[1] and r-c not in pl[2] + return ((pl[0]+[c], pl[1]|{r+c}, pl[2]|{r-c}, pl[3]-{c}) + for c in pl[3] if place(c)) + def pipeline(pl, i): + for ipl in q(pl, i): + if i+1 < n: + yield from pipeline(ipl, i+1) + else: + yield ipl[0] + def toletter(x): + return 'abcdefghijklmnopqrstuvwxyz'[x] + def fund_solut(fl): + def inversed(xl): + return (xl.index(i) for i in range(0, n)) + def variants(xl): + rl = [xl] + rl += [[*inversed(x)] for x in rl] + rl += [[*reversed(x)] for x in rl] + rl += [[n-1-i for i in x] for x in rl] + return (''.join(toletter(i) for i in x) for x in rl) + rs = set() + for i in fl: + ks = {*variants(i)} + if rs.isdisjoint(ks): + rs |= ks + yield i + for i in fund_solut( + pipeline(([], set(), set(), {*range(0, n)}), 0)): + rl = sorted(toletter(v)+str(k+1) for k, v in enumerate(i)) + print(rl) +queens(8) diff --git a/Task/N-smooth-numbers/REXX/n-smooth-numbers.rexx b/Task/N-smooth-numbers/REXX/n-smooth-numbers.rexx index db0be253b9..54f579eacb 100644 --- a/Task/N-smooth-numbers/REXX/n-smooth-numbers.rexx +++ b/Task/N-smooth-numbers/REXX/n-smooth-numbers.rexx @@ -1,44 +1,54 @@ -/*REXX pgm computes&displays X n-smooth numbers; both X and N can be specified as ranges*/ -numeric digits 200 /*be able to handle some big numbers. */ -parse arg LOx HIx LOn HIn . /*obtain optional arguments from the CL*/ -if LOx=='' | LOx=="," then LOx= 1 /*Not specified? Then use the default.*/ -if HIx=='' | HIx=="," then HIx= LOx + 24 /* " " " " " " */ -if LOn=='' | LOn=="," then LOn= 2 /* " " " " " " */ -if HIn=='' | HIn=="," then HIn= LOn + 27 /* " " " " " " */ -call genP HIn /*generate enough primes to satisfy HIn*/ -@aList= ' a list of the '; @thru= ' through ' /*literals used with a SAY.*/ +-- 25 Apr 2025 +include Settings - do j=LOn to HIn; if !.j==0 then iterate /*if not prime, then skip this number. */ - call smooth HIx,j; $= /*invoke SMOOTH; initialize $ (list). */ - do k=LOx to HIx; $= $ #.k /*append a smooth number to " " " */ - end /*k*/ - say center(@aList th(LOx) @thru th(HIx) ' numbers for' j"-smooth ", 130, "═") - say strip($); say - end /*j*/ /* [↑] the $ list has a leading blank.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: procedure expose @. !. #; parse arg x /*#≡num of primes; @. ≡array of primes.*/ - @.=; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23; #=9 - !.=0; !.2=1; !.3=2; !.5=3; !.7=4; !.11=5; !.13=6; !.17=7; !.19=8; !.23=9 - do k=@.#+6 by 2 until #>=x ; if k//3==0 then iterate - parse var k '' -1 _; if _==5 then iterate - do d=4 until @.d**2>k; if k//@.d==0 then iterate k - end /*d*/ - #= # + 1; !.k= #; @.#= k /*found a prime, bump counter; assign @*/ - end /*k*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -smooth: procedure expose @. !. #.; parse arg y,p /*obtain the arguments from the invoker*/ - if p=='' then p= 3 /*Not specified? Then assume Hamming #s*/ - n= !.p /*the number of primes being used. */ - nn= n - 1; #.= 0; #.1= 1 /*an array of n-smooth numbers (so far)*/ - f.= 1 /*the indices of factors of a number. */ - do j=2 for y-1; _= f.1 - z= @.1 * #._ - do k=2 for nn; _= f.k; v= @.k * #._; if v= "0" And Mid(normalized, e, 1) <= "9") + e += 1 + Wend + If e > idx Then + Redim Preserve result(cnt) + result(cnt).tipo = KIND_STRING + result(cnt).txt = Mid(normalized, idx, e - idx) + result(cnt).num = 0 + cnt += 1 + idx = e + End If + + ' Process number + While e <= l And (Mid(normalized, e, 1) >= "0" And Mid(normalized, e, 1) <= "9") + e += 1 + Wend + If e > idx Then + Redim Preserve result(cnt) + result(cnt).tipo = KIND_NUMBER + result(cnt).txt = "" + result(cnt).num = Val(Mid(normalized, idx, e - idx)) + cnt += 1 + idx = e + End If + Wend +End Sub + +Function scmp(s1 As String, s2 As String) As Integer + If s1 < s2 Then Return -1 + If s1 > s2 Then Return 1 + Return 0 +End Function + +Function NaturalCompare(sa As String, sb As String) As Integer + Dim As KeyItem a(), b() + NatOrderKey(sa, a()) + NatOrderKey(sb, b()) + + ' Check for empty arrays + Dim As Integer la = Ubound(a), lb = Ubound(b) + + ' Handle case where one or both arrays might be empty + If la < 0 And lb < 0 Then Return 0 + If la < 0 Then Return -1 + If lb < 0 Then Return 1 + + Dim As Integer n = Iif(la < lb, la, lb) + + For i As Integer = 0 To n + Dim As KeyItem ai = a(i) + Dim As KeyItem bi = b(i) + + If ai.tipo = bi.tipo Then + Dim As Integer result + If ai.tipo = KIND_STRING Then + result = scmp(ai.txt, bi.txt) + Else + result = Sgn(ai.num - bi.num) ' Use Sgn to get -1, 0, or 1 + End If + If result <> 0 Then Return result + Else + Return Iif(ai.tipo = KIND_STRING, 1, -1) + End If + Next + + If la < lb Then Return -1 + If la > lb Then Return 1 + Return 0 +End Function + +Sub test(title As String, arr() As String) + Print title + Dim As Integer i, j, n = Ubound(arr) + + Dim As String sorted(n) + For i = 0 To n + sorted(i) = arr(i) + Next + + ' Bubble sort + For i = 0 To n - 1 + For j = 0 To n - i - 1 + If NaturalCompare(sorted(j), sorted(j + 1)) > 0 Then Swap sorted(j), sorted(j + 1) + Next + Next + + For i = 0 To n + Print "'" & sorted(i) & "'" + Next + Print +End Sub + +' tests +Dim arr1(3) As String = {"ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"} +test("Ignoring leading spaces.", arr1()) + +Dim arr2(3) As String = {"ignore MAS spaces: 2-2", "ignore MAS spaces: 2-1", "ignore MAS spaces: 2+0", "ignore MAS spaces: 2+1"} +test("Ignoring multiple adjacent spaces (MAS).", arr2()) + +Dim arr3(5) As String = {"Equiv. spaces: 3-3", "Equiv. " & Chr(13) & "spaces: 3-2", "Equiv. " & Chr(12) & "spaces: 3-1", "Equiv. " & Chr(11) & "spaces: 3+0", "Equiv. " & Chr(10) & "spaces: 3+1", "Equiv. " & Chr(9) & "spaces: 3+2"} +test("Equivalent whitespace characters.", arr3()) + +Dim arr4(3) As String = {"cASE INDEPENDENT: 3-2", "caSE INDEPENDENT: 3-1", "casE INDEPENDENT: 3+0", "case INDEPENDENT: 3+1"} +test("Case Independent sort.", arr4()) + +Dim arr5(3) As String = {"foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"} +test("Numeric fields as numerics.", arr5()) + +Dim arr6(3) As String = {"The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"} +test("Title sorts.", arr6()) + +Sleep diff --git a/Task/Natural-sorting/JavaScript/natural-sorting-1.js b/Task/Natural-sorting/JavaScript/natural-sorting-1.js new file mode 100644 index 0000000000..bc0f1d6c39 --- /dev/null +++ b/Task/Natural-sorting/JavaScript/natural-sorting-1.js @@ -0,0 +1,7 @@ +function naturalSort(a, b) => { + return a.trim().localeCompare(b.trim(), 'und', { numeric: true }) +} + +const files = ['file10.txt', '\nfile9.txt', 'File11.TXT', 'file12.txt'] +console.log(files.toSorted(naturalSort)) +// ['\nfile9.txt', 'file10.txt', 'File11.TXT', 'file12.txt'] diff --git a/Task/Natural-sorting/JavaScript/natural-sorting.js b/Task/Natural-sorting/JavaScript/natural-sorting-2.js similarity index 100% rename from Task/Natural-sorting/JavaScript/natural-sorting.js rename to Task/Natural-sorting/JavaScript/natural-sorting-2.js diff --git a/Task/Natural-sorting/Rust/natural-sorting.rs b/Task/Natural-sorting/Rust/natural-sorting.rs new file mode 100644 index 0000000000..e4d588a384 --- /dev/null +++ b/Task/Natural-sorting/Rust/natural-sorting.rs @@ -0,0 +1,260 @@ +use regex::Regex; +use std::cmp::Ordering; + +// Only covers ISO-8859-1 accented characters plus, for consistency, Ÿ +const UC_ACCENTS: [&str; 8] = ["ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ"]; +const LC_ACCENTS: [&str; 8] = ["àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ"]; +const UC_UNACCENTS: [&str; 8] = ["A", "C", "E", "I", "N", "O", "U", "Y"]; +const LC_UNACCENTS: [&str; 8] = ["a", "c", "e", "i", "n", "o", "u", "y"]; + +// Only the more common ligatures +const UC_LIGATURES: [&str; 3] = ["Æ", "IJ", "Œ"]; +const LC_LIGATURES: [&str; 3] = ["æ", "ij", "œ"]; +const UC_SEPARATES: [&str; 3] = ["AE", "IJ", "OE"]; +const LC_SEPARATES: [&str; 3] = ["ae", "ij", "oe"]; + +// Miscellaneous replacements +const MISC_LETTERS: [&str; 3] = ["ß", "ſ", "ʒ"]; +const MISC_REPLACEMENTS: [&str; 3] = ["ss", "s", "s"]; + +// Remove leading spaces +fn left_trim(text: &str) -> String { + text.trim_start().to_string() +} + +// Replace multiple spaces with a single space +fn replace_spaces(text: &str) -> String { + let regex_expr = Regex::new(r" {2,}").unwrap(); + regex_expr.replace_all(text, " ").to_string() +} + +// Replace whitespace with a single space +fn replace_whitespace(text: &str) -> String { + let regex_expr = Regex::new(r"\s+").unwrap(); + regex_expr.replace_all(text, " ").to_string() +} + +// Display strings including whitespace as if the latter were literal characters +fn to_display_string(text: &str) -> String { + let whitespace_1 = ["\t", "\n", "\u{000b}", "\u{000c}", "\r"]; + let whitespace_2 = ["\\t", "\\n", "\\u000b", "\\u000c", "\\r"]; + let mut result = text.to_string(); + + for i in 0..whitespace_1.len() { + result = result.replace(whitespace_1[i], whitespace_2[i]); + } + result +} + +// Transform the string into lower case +fn to_lower_case(text: &str) -> String { + text.to_lowercase() +} + +// Pad each numeric character with leading zeros to a total length of 20 +fn zero_padding(text: &str) -> String { + let digits = Regex::new(r"-?\d+").unwrap(); + let mut result = text.to_string(); + let mut extra_index = 0; + + for cap in digits.captures_iter(text) { + let match_str = &cap[0]; + let start_pos = text.find(match_str).unwrap() + extra_index; + let padding = "0".repeat(20 - match_str.len()); + + result = format!("{}{}{}", + &result[..start_pos], + padding, + &result[start_pos..]); + + extra_index += 20 - match_str.len(); + } + + result +} + +fn remove_title(text: &str) -> String { + let regex = Regex::new(r"^(The|An|A)\s+").unwrap(); + regex.replace(text, "").to_string() +} + +// Replace accented letters with their unaccented equivalent +fn replace_accents(text: &str) -> String { + let mut result = String::new(); + let chars: Vec = text.chars().collect(); + + for i in 0..chars.len() { + if (chars[i] as u32) < 128 { + result.push(chars[i]); + continue; + } + + let length = result.len(); + let letter = chars[i].to_string(); + + for j in 0..UC_ACCENTS.len() { + if UC_ACCENTS[j].contains(&letter) { + result.push_str(UC_UNACCENTS[j]); + break; + } + } + + if length == result.len() { + for j in 0..LC_ACCENTS.len() { + if LC_ACCENTS[j].contains(&letter) { + result.push_str(LC_UNACCENTS[j]); + break; + } + } + } + } + + result +} + +// Replace ligatures with separated letters +fn replace_ligatures(text: &str) -> String { + let mut result = text.to_string(); + + for i in 0..UC_LIGATURES.len() { + result = result.replace(UC_LIGATURES[i], UC_SEPARATES[i]); + } + + for i in 0..LC_LIGATURES.len() { + result = result.replace(LC_LIGATURES[i], LC_SEPARATES[i]); + } + + result +} + +// Replace miscellaneous letters with their equivalent replacements +fn replace_characters(text: &str) -> String { + let mut result = text.to_string(); + + for i in 0..MISC_LETTERS.len() { + result = result.replace(MISC_LETTERS[i], MISC_REPLACEMENTS[i]); + } + + result +} + +fn main() { + println!("The 9 string lists, sorted 'naturally':"); + + let mut s1 = vec![ + "ignore leading spaces: 2-2".to_string(), + " ignore leading spaces: 2-1".to_string(), + " ignore leading spaces: 2+0".to_string(), + " ignore leading spaces: 2+1".to_string() + ]; + + println!(); + s1.sort_by(|lhs, rhs| left_trim(lhs).cmp(&left_trim(rhs))); + for s in &s1 { + println!("{}", s); + } + + let mut s2 = vec![ + "ignore m.a.s spaces: 2-2".to_string(), + "ignore m.a.s spaces: 2-1".to_string(), + "ignore m.a.s spaces: 2+0".to_string(), + "ignore m.a.s spaces: 2+1".to_string() + ]; + + println!(); + s2.sort_by(|lhs, rhs| replace_spaces(lhs).cmp(&replace_spaces(rhs))); + for s in &s2 { + println!("{}", s); + } + + let mut s3 = vec![ + "Equiv. spaces: 3-3".to_string(), + "Equiv.\rspaces: 3-2".to_string(), + "Equiv.\u{000c}spaces: 3-1".to_string(), + "Equiv.\u{000b}spaces: 3+0".to_string(), + "Equiv.\nspaces: 3+1".to_string(), + "Equiv.\tspaces: 3+2".to_string() + ]; + + println!(); + s3.sort_by(|lhs, rhs| replace_whitespace(lhs).cmp(&replace_whitespace(rhs))); + for s in &s3 { + println!("{}", to_display_string(s)); + } + + let mut s4 = vec![ + "cASE INDEPENENT: 3-2".to_string(), + "caSE INDEPENENT: 3-1".to_string(), + "casE INDEPENENT: 3+0".to_string(), + "case INDEPENENT: 3+1".to_string() + ]; + + println!(); + s4.sort_by(|lhs, rhs| to_lower_case(lhs).cmp(&to_lower_case(rhs))); + for s in &s4 { + println!("{}", s); + } + + let mut s5 = vec![ + "foo100bar99baz0.txt".to_string(), + "foo100bar10baz0.txt".to_string(), + "foo1000bar99baz10.txt".to_string(), + "foo1000bar99baz9.txt".to_string() + ]; + + println!(); + s5.sort_by(|lhs, rhs| zero_padding(lhs).cmp(&zero_padding(rhs))); + for s in &s5 { + println!("{}", s); + } + + let mut s6 = vec![ + "The Wind in the Willows".to_string(), + "The 40th step more".to_string(), + "The 39 steps".to_string(), + "Wanda".to_string() + ]; + + println!(); + s6.sort_by(|lhs, rhs| remove_title(lhs).cmp(&remove_title(rhs))); + for s in &s6 { + println!("{}", s); + } + + let mut s7 = vec![ + "Equiv. ý accents: 2-2".to_string(), + "Equiv. Ý accents: 2-1".to_string(), + "Equiv. y accents: 2+0".to_string(), + "Equiv. Y accents: 2+1".to_string() + ]; + + println!(); + s7.sort_by(|lhs, rhs| replace_accents(lhs).cmp(&replace_accents(rhs))); + for s in &s7 { + println!("{}", s); + } + + let mut s8 = vec![ + "IJ ligatured ij".to_string(), + "no ligature".to_string() + ]; + + println!(); + s8.sort_by(|lhs, rhs| replace_ligatures(lhs).cmp(&replace_ligatures(rhs))); + for s in &s8 { + println!("{}", s); + } + + let mut s9 = vec![ + "Start with an ʒ: 2-2".to_string(), + "Start with an ſ: 2-1".to_string(), + "Start with an ß: 2+0".to_string(), + "Start with an s: 2+1".to_string() + ]; + + println!(); + s9.sort_by(|lhs, rhs| replace_characters(lhs).cmp(&replace_characters(rhs))); + for s in &s9 { + println!("{}", s); + } +} diff --git a/Task/Natural-sorting/Zig/natural-sorting.zig b/Task/Natural-sorting/Zig/natural-sorting.zig new file mode 100644 index 0000000000..4157f50f4e --- /dev/null +++ b/Task/Natural-sorting/Zig/natural-sorting.zig @@ -0,0 +1,571 @@ +const std = @import("std"); +const mem = std.mem; +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; + +// Only covers ISO-8859-1 accented characters plus, for consistency, Ÿ +const UC_ACCENTS = [_][]const u8{ "ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ" }; +const LC_ACCENTS = [_][]const u8{ "àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ" }; +const UC_UNACCENTS = [_][]const u8{ "A", "C", "E", "I", "N", "O", "U", "Y" }; +const LC_UNACCENTS = [_][]const u8{ "a", "c", "e", "i", "n", "o", "u", "y" }; + +// Only the more common ligatures +const UC_LIGATURES = [_][]const u8{ "Æ", "IJ", "Œ" }; +const LC_LIGATURES = [_][]const u8{ "æ", "ij", "œ" }; +const UC_SEPARATES = [_][]const u8{ "AE", "IJ", "OE" }; +const LC_SEPARATES = [_][]const u8{ "ae", "ij", "oe" }; + +// Miscellaneous replacements +const MISC_LETTERS = [_][]const u8{ "ß", "ſ", "ʒ" }; +const MISC_REPLACEMENTS = [_][]const u8{ "ss", "s", "s" }; + +// Remove leading spaces +fn leftTrim(allocator: Allocator, text: []const u8) ![]u8 { + var i: usize = 0; + while (i < text.len and text[i] == ' ') : (i += 1) {} + return allocator.dupe(u8, text[i..]); +} + +// Replace multiple spaces with a single space +fn replaceSpaces(allocator: Allocator, text: []const u8) ![]u8 { + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + + var i: usize = 0; + var inSpaces = false; + while (i < text.len) : (i += 1) { + if (text[i] == ' ') { + if (!inSpaces) { + try result.append(' '); + inSpaces = true; + } + } else { + try result.append(text[i]); + inSpaces = false; + } + } + + return result.toOwnedSlice(); +} + +// Replace whitespace with a single space +fn replaceWhitespace(allocator: Allocator, text: []const u8) ![]u8 { + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + + var i: usize = 0; + var inWhitespace = false; + while (i < text.len) : (i += 1) { + if (std.ascii.isWhitespace(text[i])) { + if (!inWhitespace) { + try result.append(' '); + inWhitespace = true; + } + } else { + try result.append(text[i]); + inWhitespace = false; + } + } + + return result.toOwnedSlice(); +} + +// Display strings including whitespace as if the latter were literal characters +fn toDisplayString(allocator: Allocator, text: []const u8) ![]u8 { + const whitespace_1 = [_][]const u8{ "\t", "\n", "\x0B", "\x0C", "\r" }; + const whitespace_2 = [_][]const u8{ "\\t", "\\n", "\\u000b", "\\u000c", "\\r" }; + + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + + var i: usize = 0; + while (i < text.len) : (i += 1) { + var replaced = false; + for (whitespace_1, 0..) |ws, j| { + if (i + ws.len <= text.len and mem.eql(u8, text[i..i+ws.len], ws)) { + try result.appendSlice(whitespace_2[j]); + i += ws.len - 1; + replaced = true; + break; + } + } + + if (!replaced) { + try result.append(text[i]); + } + } + + return result.toOwnedSlice(); +} + +// Transform the string into lower case +fn toLowerCase(allocator: Allocator, text: []const u8) ![]u8 { + var result = try allocator.alloc(u8, text.len); + errdefer allocator.free(result); + + for (text, 0..) |c, i| { + result[i] = std.ascii.toLower(c); + } + + return result; +} + +// Pad each numeric character with leading zeros to a total length of 20 +fn zeroPadding(allocator: Allocator, text: []const u8) ![]u8 { + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + + var i: usize = 0; + while (i < text.len) { + if (std.ascii.isDigit(text[i]) or (text[i] == '-' and i + 1 < text.len and std.ascii.isDigit(text[i+1]))) { + const start = i; + if (text[i] == '-') { + i += 1; + } + while (i < text.len and std.ascii.isDigit(text[i])) : (i += 1) {} + + const numStr = text[start..i]; + const padding = if (numStr.len < 20) 20 - numStr.len else 0; + + for (0..padding) |_| { + try result.append('0'); + } + try result.appendSlice(numStr); + } else { + try result.append(text[i]); + i += 1; + } + } + + return result.toOwnedSlice(); +} + +fn removeTitle(allocator: Allocator, text: []const u8) ![]u8 { + if (text.len >= 4 and mem.eql(u8, text[0..4], "The ")) { + return allocator.dupe(u8, text[4..]); + } else if (text.len >= 3 and mem.eql(u8, text[0..3], "An ")) { + return allocator.dupe(u8, text[3..]); + } else if (text.len >= 2 and mem.eql(u8, text[0..2], "A ")) { + return allocator.dupe(u8, text[2..]); + } else { + return allocator.dupe(u8, text); + } +} + +// Replace accented letters with their unaccented equivalent +fn replaceAccents(allocator: Allocator, text: []const u8) ![]u8 { + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + + var i: usize = 0; + while (i < text.len) { + // Handle UTF-8 characters + var char: [4]u8 = undefined; + var char_len: usize = 0; + + if ((text[i] & 0x80) == 0) { + // ASCII character + try result.append(text[i]); + i += 1; + continue; + } + + // Extract UTF-8 character + if ((text[i] & 0xE0) == 0xC0) { + char_len = 2; + } else if ((text[i] & 0xF0) == 0xE0) { + char_len = 3; + } else if ((text[i] & 0xF8) == 0xF0) { + char_len = 4; + } else { + // Invalid UTF-8, just copy + try result.append(text[i]); + i += 1; + continue; + } + + if (i + char_len > text.len) { + // Incomplete UTF-8 sequence + try result.append(text[i]); + i += 1; + continue; + } + + @memcpy(char[0..char_len], text[i..i+char_len]); + + var replaced = false; + const charSlice = char[0..char_len]; + + for (UC_ACCENTS, 0..) |accents, j| { + if (containsUtf8Char(accents, charSlice)) { + try result.appendSlice(UC_UNACCENTS[j]); + replaced = true; + break; + } + } + + if (!replaced) { + for (LC_ACCENTS, 0..) |accents, j| { + if (containsUtf8Char(accents, charSlice)) { + try result.appendSlice(LC_UNACCENTS[j]); + replaced = true; + break; + } + } + } + + if (!replaced) { + try result.appendSlice(charSlice); + } + + i += char_len; + } + + return result.toOwnedSlice(); +} + +// Helper function to check if a UTF-8 string contains a character +fn containsUtf8Char(haystack: []const u8, needle: []const u8) bool { + var i: usize = 0; + while (i < haystack.len) { + const char_len = utf8CharLen(haystack[i]); + if (i + char_len <= haystack.len and mem.eql(u8, haystack[i..i+char_len], needle)) { + return true; + } + i += char_len; + } + return false; +} + +// Helper function to get UTF-8 character length +fn utf8CharLen(first_byte: u8) usize { + if ((first_byte & 0x80) == 0) return 1; + if ((first_byte & 0xE0) == 0xC0) return 2; + if ((first_byte & 0xF0) == 0xE0) return 3; + if ((first_byte & 0xF8) == 0xF0) return 4; + return 1; // invalid UTF-8, treat as single byte +} + +// Replace ligatures with separated letters +fn replaceLigatures(allocator: Allocator, text: []const u8) ![]u8 { + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + try result.appendSlice(text); + + for (UC_LIGATURES, 0..) |ligature, i| { + var newResult = ArrayList(u8).init(allocator); + defer newResult.deinit(); + + var j: usize = 0; + while (j < result.items.len) { + const char_len = utf8CharLen(result.items[j]); + if (j + char_len <= result.items.len and isUtf8Char(result.items[j..j+char_len], ligature)) { + try newResult.appendSlice(UC_SEPARATES[i]); + j += char_len; + } else { + try newResult.append(result.items[j]); + j += 1; + } + } + + result.clearAndFree(); + try result.appendSlice(newResult.items); + } + + for (LC_LIGATURES, 0..) |ligature, i| { + var newResult = ArrayList(u8).init(allocator); + defer newResult.deinit(); + + var j: usize = 0; + while (j < result.items.len) { + const char_len = utf8CharLen(result.items[j]); + if (j + char_len <= result.items.len and isUtf8Char(result.items[j..j+char_len], ligature)) { + try newResult.appendSlice(LC_SEPARATES[i]); + j += char_len; + } else { + try newResult.append(result.items[j]); + j += 1; + } + } + + result.clearAndFree(); + try result.appendSlice(newResult.items); + } + + return result.toOwnedSlice(); +} + +// Helper function to compare UTF-8 characters +fn isUtf8Char(a: []const u8, b: []const u8) bool { + return mem.eql(u8, a, b); +} + +// Replace miscellaneous letters with their equivalent replacements +fn replaceCharacters(allocator: Allocator, text: []const u8) ![]u8 { + var result = ArrayList(u8).init(allocator); + defer result.deinit(); + try result.appendSlice(text); + + for (MISC_LETTERS, 0..) |letter, i| { + var newResult = ArrayList(u8).init(allocator); + defer newResult.deinit(); + + var j: usize = 0; + while (j < result.items.len) { + const char_len = utf8CharLen(result.items[j]); + if (j + char_len <= result.items.len and isUtf8Char(result.items[j..j+char_len], letter)) { + try newResult.appendSlice(MISC_REPLACEMENTS[i]); + j += char_len; + } else { + try newResult.append(result.items[j]); + j += 1; + } + } + + result.clearAndFree(); + try result.appendSlice(newResult.items); + } + + return result.toOwnedSlice(); +} + +// Custom context for sort comparators +const SortContext = struct { + allocator: Allocator, +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const stdout = std.io.getStdOut().writer(); + try stdout.print("The 9 string lists, sorted 'naturally':\n", .{}); + + var s1 = ArrayList([]const u8).init(allocator); + defer s1.deinit(); + try s1.append("ignore leading spaces: 2-2"); + try s1.append(" ignore leading spaces: 2-1"); + try s1.append(" ignore leading spaces: 2+0"); + try s1.append(" ignore leading spaces: 2+1"); + + try stdout.print("\n", .{}); + + // Sort using leftTrim + const ctx1 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s1.items, ctx1, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = leftTrim(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = leftTrim(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s1.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s2 = ArrayList([]const u8).init(allocator); + defer s2.deinit(); + try s2.append("ignore m.a.s spaces: 2-2"); + try s2.append("ignore m.a.s spaces: 2-1"); + try s2.append("ignore m.a.s spaces: 2+0"); + try s2.append("ignore m.a.s spaces: 2+1"); + + try stdout.print("\n", .{}); + + // Sort using replaceSpaces + const ctx2 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s2.items, ctx2, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = replaceSpaces(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = replaceSpaces(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s2.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s3 = ArrayList([]const u8).init(allocator); + defer s3.deinit(); + try s3.append("Equiv. spaces: 3-3"); + try s3.append("Equiv.\rspaces: 3-2"); + try s3.append("Equiv.\x0Cspaces: 3-1"); + try s3.append("Equiv.\x0Bspaces: 3+0"); + try s3.append("Equiv.\nspaces: 3+1"); + try s3.append("Equiv.\tspaces: 3+2"); + + try stdout.print("\n", .{}); + + // Sort using replaceWhitespace + const ctx3 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s3.items, ctx3, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = replaceWhitespace(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = replaceWhitespace(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s3.items) |s| { + const displayStr = try toDisplayString(allocator, s); + defer allocator.free(displayStr); + try stdout.print("{s}\n", .{displayStr}); + } + + var s4 = ArrayList([]const u8).init(allocator); + defer s4.deinit(); + try s4.append("cASE INDEPENENT: 3-2"); + try s4.append("caSE INDEPENENT: 3-1"); + try s4.append("casE INDEPENENT: 3+0"); + try s4.append("case INDEPENENT: 3+1"); + + try stdout.print("\n", .{}); + + // Sort using toLowerCase + const ctx4 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s4.items, ctx4, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = toLowerCase(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = toLowerCase(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s4.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s5 = ArrayList([]const u8).init(allocator); + defer s5.deinit(); + try s5.append("foo100bar99baz0.txt"); + try s5.append("foo100bar10baz0.txt"); + try s5.append("foo1000bar99baz10.txt"); + try s5.append("foo1000bar99baz9.txt"); + + try stdout.print("\n", .{}); + + // Sort using zeroPadding + const ctx5 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s5.items, ctx5, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = zeroPadding(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = zeroPadding(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s5.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s6 = ArrayList([]const u8).init(allocator); + defer s6.deinit(); + try s6.append("The Wind in the Willows"); + try s6.append("The 40th step more"); + try s6.append("The 39 steps"); + try s6.append("Wanda"); + + try stdout.print("\n", .{}); + + // Sort using removeTitle + const ctx6 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s6.items, ctx6, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = removeTitle(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = removeTitle(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s6.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s7 = ArrayList([]const u8).init(allocator); + defer s7.deinit(); + try s7.append("Equiv. ý accents: 2-2"); + try s7.append("Equiv. Ý accents: 2-1"); + try s7.append("Equiv. y accents: 2+0"); + try s7.append("Equiv. Y accents: 2+1"); + + try stdout.print("\n", .{}); + + // Sort using replaceAccents + const ctx7 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s7.items, ctx7, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = replaceAccents(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = replaceAccents(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s7.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s8 = ArrayList([]const u8).init(allocator); + defer s8.deinit(); + try s8.append("IJ ligatured ij"); + try s8.append("no ligature"); + + try stdout.print("\n", .{}); + + // Sort using replaceLigatures + const ctx8 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s8.items, ctx8, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = replaceLigatures(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = replaceLigatures(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s8.items) |s| { + try stdout.print("{s}\n", .{s}); + } + + var s9 = ArrayList([]const u8).init(allocator); + defer s9.deinit(); + try s9.append("Start with an ʒ: 2-2"); + try s9.append("Start with an ſ: 2-1"); + try s9.append("Start with an ß: 2+0"); + try s9.append("Start with an s: 2+1"); + + try stdout.print("\n", .{}); + + // Sort using replaceCharacters + const ctx9 = SortContext{ .allocator = allocator }; + std.sort.insertion([]const u8, s9.items, ctx9, struct { + fn lessThan(ctx: SortContext, lhs: []const u8, rhs: []const u8) bool { + const l = replaceCharacters(ctx.allocator, lhs) catch return false; + defer ctx.allocator.free(l); + const r = replaceCharacters(ctx.allocator, rhs) catch return false; + defer ctx.allocator.free(r); + return mem.lessThan(u8, l, r); + } + }.lessThan); + + for (s9.items) |s| { + try stdout.print("{s}\n", .{s}); + } +} diff --git a/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy b/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy index 84baeb9cc1..6cbd821900 100644 --- a/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy +++ b/Task/Negative-base-numbers/EasyLang/negative-base-numbers.easy @@ -1,7 +1,5 @@ func$ encode n b . - if n = 0 - return "0" - . + if n = 0 : return "0" while n <> 0 r = n mod b n = n div b @@ -14,16 +12,14 @@ func$ encode n b . return out$ . func decode n$ b . - if n$ = "0" - return 0 - . + if n$ = "0" : return 0 for c$ in strchars n$ c = strcode c$ - 48 tot = tot * b + c . return tot . -proc test n b . . +proc test n b . h$ = encode n b print n & " -> " & h$ & "_" & b & " -> " & decode h$ b . diff --git a/Task/Next-highest-int-from-digits/EasyLang/next-highest-int-from-digits.easy b/Task/Next-highest-int-from-digits/EasyLang/next-highest-int-from-digits.easy index 7044c77896..4f9bb1200a 100644 --- a/Task/Next-highest-int-from-digits/EasyLang/next-highest-int-from-digits.easy +++ b/Task/Next-highest-int-from-digits/EasyLang/next-highest-int-from-digits.easy @@ -1,20 +1,18 @@ -proc reverse i j . dig[] . +proc reverse &dig[] i j . while i < j swap dig[i] dig[j] i += 1 j -= 1 . . -proc next_perm . dig[] . +proc next_perm &dig[] . if len dig[] >= 2 for i = 2 to len dig[] if dig[i] < dig[i - 1] k = 1 - while dig[i] >= dig[k] - k += 1 - . + while dig[i] >= dig[k] : k += 1 swap dig[i] dig[k] - reverse 1 i - 1 dig[] + reverse dig[] 1 i - 1 return . . diff --git a/Task/Non-decimal-radices-Convert/Crystal/non-decimal-radices-convert.cr b/Task/Non-decimal-radices-Convert/Crystal/non-decimal-radices-convert.cr new file mode 100644 index 0000000000..089597edba --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Crystal/non-decimal-radices-convert.cr @@ -0,0 +1,2 @@ +27812426061.to_s(36) # => "crystal" +"code".to_i(28) # => 282618 diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx index 47643bb543..fc32acaa42 100644 --- a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx +++ b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx @@ -1,37 +1,15 @@ -/*REXX program converts integers from one base to another (using bases 2 ──► 90). */ -@abc = 'abcdefghijklmnopqrstuvwxyz' /*lowercase (Latin or English) alphabet*/ -parse upper var @abc @abcU /*uppercase a version of @abc. */ -@@ = 0123456789 || @abc || @abcU /*prefix them with all numeric digits. */ -@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special characters as well. */ - /* [↑] all characters must be viewable*/ -numeric digits 3000 /*what da hey, support gihugeic numbers*/ -maxB= length(@@) /*max base/radix supported in this code*/ -parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*obtain: three args, origX, sign ··· */ -if pos(sigX, "+-")\==0 then x= x2 /*does X have a leading sign (+ or -) ?*/ - else sigX= /*Nope. No leading sign for the X value*/ -if x=='' then call erm /*if no X number, issue an error msg.*/ -if toB=='' | toB=="," then toB= 10 /*if skipped, assume the default (10). */ -if inB=='' | inB=="," then inB= 10 /* " " " " " " */ -if inB<2 | inB>maxB | \datatype(inB, 'W') then call erb "inBase " inB -if toB<2 | toB>maxB | \datatype(toB, 'W') then call erb "toBase " toB -#=0 /*result of converted X (in base 10).*/ - do j=1 for length(x) /*convert X: base inB ──► base 10. */ - ?= substr(x,j,1) /*pick off a numeral/digit from X. */ - _= pos(?, @@) /*calculate the value of this numeral. */ - if _==0 | _>inB then call erd x /*is _ character an illegal numeral? */ - #= # * inB + _ - 1 /*build a new number, digit by digit. */ - end /*j*/ /* [↑] this also verifies digits. */ -y= /*the value of X in base B. */ - do while # >= toB /*convert #: base 10 ──► base toB.*/ - y= substr(@@, (#//toB) + 1, 1)y /*construct the output number. */ - #= # % toB /* ··· and whittle # down also. */ - end /*while*/ /* [↑] algorithm may leave a residual.*/ - /* [↓] Y is the residual. */ -y= sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed. */ -say ox "(base" inB')' center("is", 20) y '(base' toB")" -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB -erd: call ser 'illegal digit/numeral ['?"] in: " x -erm: call ser 'no argument specified.' -ser: say; say '***error!***'; say arg(1); exit 13 +include Settings + +say 'NON-DECIMAL RADICES - 11 Mar 2025' +say version +say +arg xx +if xx = '' then + xx = 255 +do n = 2 to 36 + say xx 'decimal =' Basenn(xx,n) 'base' n '=' Base10(Basenn(xx,n),n) 'decimal' +end +exit + +include Functions +include Abend diff --git a/Task/Nonoblock/EasyLang/nonoblock.easy b/Task/Nonoblock/EasyLang/nonoblock.easy index 28195b8824..9d0287fcdc 100644 --- a/Task/Nonoblock/EasyLang/nonoblock.easy +++ b/Task/Nonoblock/EasyLang/nonoblock.easy @@ -1,7 +1,5 @@ func$ rep s$ n . - for i to n - r$ &= s$ - . + for i to n : r$ &= s$ return r$ . func$[] genseq ones$[] nzeros . @@ -20,11 +18,9 @@ func$[] genseq ones$[] nzeros . . return r$[] . -proc block data$ le . . +proc block data$ le . a[] = number strchars data$ - for b in a[] - nbytes += b - . + for b in a[] : nbytes += b print "blocks " & a[] & " cells " & le if le - nbytes <= 0 print "No solution" diff --git a/Task/Nonogram-solver/Rust/nonogram-solver.rs b/Task/Nonogram-solver/Rust/nonogram-solver.rs new file mode 100644 index 0000000000..5844bb387f --- /dev/null +++ b/Task/Nonogram-solver/Rust/nonogram-solver.rs @@ -0,0 +1,241 @@ +use std::collections::HashSet; + +// BitSet implementation +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +struct BitSet { + bits: u64, +} + +impl BitSet { + fn empty() -> Self { + BitSet { bits: 0 } + } + + fn value(&self) -> u64 { + self.bits + } + + fn add(&self, item: usize) -> Self { + BitSet { bits: self.bits | (1 << item) } + } + + fn add_range(&self, start: usize, count: usize) -> Self { + let mask = ((1 << (start + count)) - 1) & !((1 << start) - 1); + BitSet { bits: self.bits | mask } + } + + fn contains(&self, item: usize) -> bool { + (self.bits & (1 << item)) != 0 + } + + fn shift_left_at(&self, index: usize) -> Self { + let high_bits = (self.bits >> index) << (index + 1); + let low_bits = self.bits & ((1 << index) - 1); + BitSet { bits: high_bits | low_bits } + } + + fn to_string(&self) -> String { + format!("{:b}", self.bits) + } +} + +impl std::ops::BitAnd for BitSet { + type Output = Self; + + fn bitand(self, rhs: Self) -> Self::Output { + BitSet { bits: self.bits & rhs.bits } + } +} + +impl std::ops::BitOr for BitSet { + type Output = Self; + + fn bitor(self, rhs: Self) -> Self::Output { + BitSet { bits: self.bits | rhs.bits } + } +} + +fn generate(length: usize, runs: &[usize]) -> Vec { + let mut list = Vec::new(); + let initial = BitSet::empty(); + let mut sums = vec![0; runs.len()]; + + for i in 1..runs.len() { + sums[i] = sums[i - 1] + runs[i - 1] + 1; + } + + let initial = runs.iter().enumerate() + .fold(initial, |acc, (i, &run)| acc.add_range(sums[i], run)); + + let max = BitSet::empty().add(length); + generate_recursive(&mut list, max, runs, &sums, initial, 0, 0); + + list +} + +fn generate_recursive( + result: &mut Vec, + max: BitSet, + runs: &[usize], + sums: &[usize], + mut current: BitSet, + index: usize, + mut shift: usize, +) { + if index == runs.len() { + result.push(current); + return; + } + + while current.value() < max.value() { + generate_recursive(result, max, runs, sums, current, index + 1, shift); + current = current.shift_left_at(sums[index] + shift); + shift += 1; + } +} + +fn reduce(rows: &mut Vec>, columns: &mut Vec>) { + let mut count = 1; + + while count > 0 { + count = 0; + + // Check rows against columns + for row_idx in 0..rows.len() { + let all_on = rows[row_idx].iter().fold(rows[row_idx][0], |acc, &b| acc & b); + let all_off = rows[row_idx].iter().fold(rows[row_idx][0], |acc, &b| acc | b); + + for col_idx in 0..columns.len() { + // Remove column patterns where a cell should be on but isn't + let before_len = columns[col_idx].len(); + columns[col_idx].retain(|c| !(all_on.contains(col_idx) && !c.contains(row_idx))); + count += before_len - columns[col_idx].len(); + + // Remove column patterns where a cell should be off but isn't + let before_len = columns[col_idx].len(); + columns[col_idx].retain(|c| !(!all_off.contains(col_idx) && c.contains(row_idx))); + count += before_len - columns[col_idx].len(); + } + } + + // Check columns against rows + for col_idx in 0..columns.len() { + let all_on = columns[col_idx].iter().fold(columns[col_idx][0], |acc, &b| acc & b); + let all_off = columns[col_idx].iter().fold(columns[col_idx][0], |acc, &b| acc | b); + + for row_idx in 0..rows.len() { + // Remove row patterns where a cell should be on but isn't + let before_len = rows[row_idx].len(); + rows[row_idx].retain(|r| !(all_on.contains(row_idx) && !r.contains(col_idx))); + count += before_len - rows[row_idx].len(); + + // Remove row patterns where a cell should be off but isn't + let before_len = rows[row_idx].len(); + rows[row_idx].retain(|r| !(!all_off.contains(row_idx) && r.contains(col_idx))); + count += before_len - rows[row_idx].len(); + } + } + } +} + +fn solve(row_runs: &[Vec], column_runs: &[Vec]) { + let column_len = column_runs.len(); + let row_len = row_runs.len(); + + let mut rows: Vec> = row_runs.iter() + .map(|row| generate(column_len, row)) + .collect(); + + let mut columns: Vec> = column_runs.iter() + .map(|column| generate(row_len, column)) + .collect(); + + reduce(&mut rows, &mut columns); + + for row in rows { + if row.len() != 1 { + println!("{}", vec!['?'; column_len].into_iter().collect::().chars().intersperse(' ').collect::()); + } else { + let mut s = format!("{:0width$b}", row[0].value(), width = column_len) + .replace('1', "#") + .replace('0', "."); + + // Reverse the string + let s: String = s.chars().rev().collect(); + println!("{}", s.chars().intersperse(' ').collect::()); + } + } +} + +fn parse_runs(input: &str) -> Vec> { + input.split_whitespace() + .map(|s| s.chars().map(|c| (c as u8 - b'A' + 1) as usize).collect()) + .collect() +} + +fn main() { + let test_cases = [ + ("C BA CB BB F AE F A B", "AB CA AE GA E C D C"), + ("F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC", + "D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"), + ("CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC", + "BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC"), + ("E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G", + "E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM") + ]; + + for (row_letters, column_letters) in test_cases.iter() { + let row_runs = parse_runs(row_letters); + let column_runs = parse_runs(column_letters); + solve(&row_runs, &column_runs); + println!(); + } +} + +// Extension trait to add intersperse functionality +trait Intersperse { + fn intersperse(self, separator: char) -> InterspersedIter + where + Self: Sized + Iterator; +} + +impl Intersperse for I +where + I: Iterator + Sized, +{ + fn intersperse(self, separator: char) -> InterspersedIter { + InterspersedIter { + iter: self, + separator, + need_separator: false, + } + } +} + +struct InterspersedIter { + iter: I, + separator: char, + need_separator: bool, +} + +impl Iterator for InterspersedIter +where + I: Iterator, +{ + type Item = char; + + fn next(&mut self) -> Option { + if self.need_separator { + self.need_separator = false; + return Some(self.separator); + } + + match self.iter.next() { + Some(val) => { + self.need_separator = true; + Some(val) + } + None => None, + } + } +} diff --git a/Task/Nth-root/AppleScript/nth-root.applescript b/Task/Nth-root/AppleScript/nth-root.applescript new file mode 100644 index 0000000000..428a7d2965 --- /dev/null +++ b/Task/Nth-root/AppleScript/nth-root.applescript @@ -0,0 +1,23 @@ +set outPutString to "" +set outPutString to outPutString & nthRoot2(34, 5) & linefeed +set outPutString to outPutString & nthRoot2(42, 10) & linefeed +set outPutString to outPutString & nthRoot2(5, 2) & linefeed + +on nthRoot(x, n) + local n1, y, res, abs + set n1 to n - 1 + set res to x / n + set abs to x + repeat until abs < 1.0E-14 + set y to res + set res to ((n1 * y) + (x / (y ^ n1))) / n + if res > y then + set abs to res - y + else + set abs to y - res + end if + end repeat + set y to res div 1 + if res = y then return y + return res +end nthRoot diff --git a/Task/Nth-root/EasyLang/nth-root.easy b/Task/Nth-root/EasyLang/nth-root.easy index 7cc72ab579..a8c059fb6d 100644 --- a/Task/Nth-root/EasyLang/nth-root.easy +++ b/Task/Nth-root/EasyLang/nth-root.easy @@ -1,8 +1,6 @@ func power x n . r = 1 - for i = 1 to n - r *= x - . + for i = 1 to n : r *= x return r . func nth_root x n . @@ -15,6 +13,8 @@ func nth_root x n . . return r . -numfmt 4 0 +numfmt 0 4 x = power 3.1416 10 print nth_root x 10 +print nth_root 2 2 +print nth_root 81 4 diff --git a/Task/Nth-root/REXX/nth-root.rexx b/Task/Nth-root/REXX/nth-root.rexx index d319e533a9..b1b9cff741 100644 --- a/Task/Nth-root/REXX/nth-root.rexx +++ b/Task/Nth-root/REXX/nth-root.rexx @@ -1,17 +1,22 @@ -/*REXX program calculates the Nth root of X, with DIGS (decimal digits) accuracy. */ +-- 8 May 2025 include Settings -say version; say 'Nth root'; say -parse arg x root digs . /*obtain optional arguments from the CL*/ -if x=='' | x=="," then x= 2 /*Not specified? Then use the default.*/ -if root=='' | root=="," then root= 2 /* " " " " " " */ -if digs=='' | digs=="," then digs=65 /* " " " " " " */ -numeric digits digs /*set the decimal digits to DIGS. */ -say ' x = ' x /*echo the value of X. */ -say ' root = ' root /* " " " " ROOT. */ -say ' digits = ' digs /* " " " " DIGS. */ -say ' answer = ' Nroot(x, root) /*show the value of ANSWER. */ -exit /*stick a fork in it, we're all done. */ +say 'NTH ROOT' +say version +say +parse arg x','root','digs +if x = '' then + x = 2 +if root = '' then + root = 5 +if digs = '' then + digs = 65 +numeric digits digs +say ' x = ' x +say ' root = ' root +say 'digits = ' digs +say 'answer = ' Nroot(x,root) +exit include Numbers include Functions diff --git a/Task/Number-reversal-game/EasyLang/number-reversal-game.easy b/Task/Number-reversal-game/EasyLang/number-reversal-game.easy index c455ae1acd..6de6dde1c1 100644 --- a/Task/Number-reversal-game/EasyLang/number-reversal-game.easy +++ b/Task/Number-reversal-game/EasyLang/number-reversal-game.easy @@ -1,24 +1,20 @@ func sorted s[] . for c in s[] - if c < last - return 0 - . + if c < last : return 0 last = c . return 1 . func$ tostr s[] . - for s in s[] - res$ &= s & " " - . + for s in s[] : res$ &= s & " " return res$ . -proc shuffle . s[] . +proc shuffle &s[] . for i = len s[] downto 2 swap s[i] s[random i] . . -proc reverse n . s[] . +proc reverse n &s[] . for i = 1 to n div 2 swap s[i] s[n - i + 1] . diff --git a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy index 4c7612257a..fc65581a3b 100644 --- a/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy +++ b/Task/Numbers-which-are-not-the-sum-of-distinct-squares/EasyLang/numbers-which-are-not-the-sum-of-distinct-squares.easy @@ -2,7 +2,7 @@ maxNumber = 324 len isSum[] maxNumber maxSquare = floor sqrt maxNumber # -proc flagSum currSum sqPos . . +proc flagSum currSum sqPos . nextSum = currSum + sqPos * sqPos if nextSum <= maxNumber isSum[nextSum] = 1 diff --git a/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy b/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy index 9faf463899..ce815f5bb5 100644 --- a/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy +++ b/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy @@ -1,7 +1,5 @@ fastfunc risefall n . - if n < 10 - return 1 - . + if n < 10 : return 1 prev = -1 while n > 0 d = n mod 10 @@ -15,21 +13,17 @@ fastfunc risefall n . prev = d n = n div 10 . - if rises = falls - return 1 - . + if rises = falls : return 1 return 0 . -numfmt 0 4 +numfmt 4 0 n = 1 repeat if risefall n = 1 cnt += 1 if cnt <= 200 write n - if cnt mod 10 = 0 - print "" - . + if cnt mod 10 = 0 : print "" . . until cnt = 1e7 diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx index 4027fb164e..55b09726ec 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx @@ -1,49 +1,95 @@ -/*REXX program does numerical integration using an N─point Gauss─Legendre quadrature rule. */ -pi= pi(); digs= length(pi) - length(.); numeric digits digs; reps= digs % 2 +-- 9 Jun 2025 +include Settings -!.= .; b= 3; a= -b; bma= b - a; bmaH= bma / 2; tiny= '1e-'digs -trueV= exp(b)-exp(a); bpa= b + a; bpaH= bpa / 2 -hdr= 'iterate value (with ' digs " decimal digits being used)" -say ' step ' center(hdr, digs+3) ' difference' /*show hdr*/ -sep='──────' copies("─", digs+3) '─────────────'; say sep /* " sep*/ +arg digs +if digs = '' then + digs=9 +numeric digits digs - do #=1 until dif>0; p0z= 1; p0.1= 1; p1z= 2; p1.1= 1; p1.2= 0; ##= # + .5; r.= 0 - /*█*/ do k=2 to #; km= k - 1 - /*█*/ do y=1 for p1z; T.y= p1.y; end /*y*/ - /*█*/ T.y= 0; TT.= 0; do L=1 for p0z; _= L + 2; TT._= p0.L; end /*L*/ - /*█*/ kkm= k + km; do j=1 for p1z +1; T.j= (kkm*T.j - km*TT.j)/k; end /*j*/ - /*█*/ p0z= p1z; do n=1 for p0z; p0.n= p1.n ; end /*n*/ - /*█*/ p1z= p1z + 1; do p=1 for p1z; p1.p= T.p ; end /*p*/ - /*█*/ end /*k*/ - /*▓*/ do !=1 for #; x= cos( pi * (! - .25) / ## ) - /*▓*/ /*░*/ do reps until abs(dx) <= tiny - /*▓*/ /*░*/ f= p1.1; df= 0; do u=2 to p1z; df= f + x*df - /*▓*/ /*░*/ f= p1.u +x*f - /*▓*/ /*░*/ end /*u*/ - /*▓*/ /*░*/ dx= f / df; x= x - dx - /*▓*/ /*░*/ end /*reps ···*/ - /*▓*/ r.1.!= x - /*▓*/ r.2.!= 2 / ( (1 - x*x) * df*df) - /*▓*/ end /*!*/ - $= 0 - /*▒*/ do m=1 for #; $=$ + r.2.m * exp(bpaH + r.1.m*bmaH); end /*m*/ - z= bmaH * $ /*calculate target value (Z)*/ - dif= z - trueV; z= format(z, 3, digs - 2) /* " difference. */ - Ndif= translate( format(dif, 3, 4, 2, 0), 'e', "E") - if #\==1 then say center(#, 6) z' ' Ndif /*no display if not computed*/ - end /*#*/ +say 'NUMERICAL INTEGRATION: GAUSS-LEGENDRE QUADRATURE' +say version +say +w=Digits()+2 +say Left('Function',10) Left('Range',w+4) ' N', + Left('Result',w) Left('True',w) Left(' Error',w) +say +call Task 'x**3', 0, 1, 1/4 +call Task '1/x', 1, 100, Ln(100)/1 +call Task 'x', 0, 5000, 12500000 +call Task '4/(x**2+1)', 0, 1, Pi()/1 +call Task 'Sin(x)', 0, 1, -Cos(1)+1 +call Task 'Sin(x)', 0, Pi()/1, 2 +call Task 'Cos(x)', 0, 1, Sin(1) +call Task 'Cos(x)', 0, Pi()/1, 0 +call Task 'Tan(x)', 0, 1, -Ln(Abs(Cos(1))) +call Task 'Tan(x)', 0, Pi()/1, 0 +call Task 'Exp(x)', -3, 3, Exp(3)-Exp(-3) +call Task 'Gamma(x)', 1, 8, 2603.238829328642145 +call Timer +exit -say sep; xdif= compare( strip(z), trueV); say right("↑", 6 + 1 + xdif) -say left('', 6 + 1) trueV " {exact value}"; say -say 'Using ' digs " digit precision, the" , - 'N-point Gauss─Legendre quadrature (GLQ) had an accuracy of ' xdif-2 " digits." -exit 0 /*stick a fork in it, we're all done. */ -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -e: return 2.718281828459045235360287471352662497757247093699959574966967627724076630353547595 -pi: return 3.141592653589793238462643383279502884197169399375105820974944592307816406286286209 -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure expose !.; parse arg x; if !.x\==. then return !.x; _= 1; z=1; y= x*x - do k=2 by 2 until p==z; p=z; _= -_*y/(k*(k-1)); z=z+_; end; !.x=z; return z -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix= x % 1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix; z= 1 - _=1; do j=1 until p==z; p=z; _= _*x/j; z= z+_; end; return z * e()**ix +Task: +procedure expose glob. +arg ff,aa,bb,true +w=Digits()+2 +do nn = 1 to 20 + res=GaussQuad(ff,aa,bb,nn); diff=res-true + say Left(ff,10) Left(aa '-' bb,w+4) Right(nn,2), + Left(Std(res),w) Left(true/1,w) Format(diff,2,4,,0) +end +say +return + +GaussQuad: +procedure expose glob. +-- Gaussion-Legendre quadrature on function f in range a...b taking n points +arg ff,aa,bb,nn +-- Legendre polynomials +p0=1; poly1.1=1; p1=2; poly2.1=1; poly2.2=0 +do i = 2 to nn + work1.0=p1+1 + do j = 1 to p1 + work1.j=poly2.j + end + work1.j=0; work2.0=p0+2; work2.1=0; work2.2=0 + do j = 1 to p0 + j2=j+2; work2.j2=poly1.j + end + do j = 1 to work1.0 + work1.j=((2*i-1)*work1.j-(i-1)*work2.j)/i + end + p0=p1 + do j = 1 to p0 + poly1.j=poly2.j + end + p1=work1.0 + do j = 1 to p1 + poly2.j=work1.j + end +end +-- Roots and weights +eps=1/10**Digits() +root.=0 +do i = 1 to nn + x=Cos(Pi()*(i-0.25)/(nn+0.5)) + do 10 until Abs(dx) < eps + f=poly2.1; df=0 + do k = 2 to p1 + df=f+x*df; f=poly2.k+x*f + end + dx=f/df; x=x-dx + end + root.1.i=x; root.2.i=2/((1-x*x)*df*df) +end +-- Quadrature +bp=0.5*(bb+aa); bm=0.5*(bb-aa); zz=0 +do i = 1 to nn + zz=zz+root.2.i*Eval(ff,bp+root.1.i*bm) +end +return bm*zz + +include Functions +include Special +include Constants +include Helper +include Abend diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx deleted file mode 100644 index 2c9b14bc0a..0000000000 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-3.rexx +++ /dev/null @@ -1,51 +0,0 @@ -/*REXX program does numerical integration using an N─point Gauss─Legendre quadrature rule. */ -pi= pi(); digs= length(pi) - length(.); numeric digits digs; reps= digs % 2 -!.= .; b= 3; a= -b; bma= b - a; bmaH= bma / 2; tiny= '1e-'digs -trueV= exp(b)-exp(a); bpa= b + a; bpaH= bpa / 2 -hdr= 'iterate value (with ' digs " decimal digits being used)" -say ' step ' center(hdr, digs+3) ' difference' /*show hdr*/ -sep='──────' copies("─", digs+3) '─────────────'; say sep /* " sep*/ - - do #=1 until dif>0; p0z= 1; p0.1= 1; p1z= 2; p1.1= 1; p1.2= 0; ##= # + .5; r.= 0 - /*█*/ do k=2 to #; km= k - 1 - /*█*/ do y=1 for p1z; T.y= p1.y; end /*y*/ - /*█*/ T.y= 0; TT.= 0; do L=1 for p0z; _= L + 2; TT._= p0.L; end /*L*/ - /*█*/ kkm= k + km; do j=1 for p1z +1; T.j= (kkm*T.j - km*TT.j)/k; end /*j*/ - /*█*/ p0z= p1z; do n=1 for p0z; p0.n= p1.n ; end /*n*/ - /*█*/ p1z= p1z + 1; do p=1 for p1z; p1.p= T.p ; end /*p*/ - /*█*/ end /*k*/ - /*▓*/ do !=1 for #; x= cos( pi * (! - .25) / ## ) - /*▓*/ /*░*/ do reps until abs(dx) <= tiny - /*▓*/ /*░*/ f= p1.1; df= 0; do u=2 to p1z; df= f + x*df - /*▓*/ /*░*/ f= p1.u +x*f - /*▓*/ /*░*/ end /*u*/ - /*▓*/ /*░*/ dx= f / df; x= x - dx - /*▓*/ /*░*/ end /*reps ···*/ - /*▓*/ r.1.!= x - /*▓*/ r.2.!= 2 / ( (1 - x*x) * df*df) - /*▓*/ end /*!*/ - $= 0 - /*▒*/ do m=1 for #; $=$ + r.2.m * exp(bpaH + r.1.m*bmaH); end /*m*/ - z= bmaH * $ /*calculate target value (Z)*/ - dif= z - trueV; z= format(z, 3, digs - 2) /* " difference. */ - Ndif= translate( format(dif, 3, 4, 3, 0), 'e', "E") - if #\==1 then say center(#, 6) z' ' Ndif /*no display if not computed*/ - end /*#*/ - -say sep; xdif= compare( strip(z), trueV); say right("↑", 6 + 1 + xdif) -say left('', 6 + 1) trueV " {exact value}"; say -say 'Using ' digs " digit precision, the" , - 'N-point Gauss─Legendre quadrature (GLQ) had an accuracy of ' xdif-2 " digits." -exit 0 /*stick a fork in it, we're all done. */ -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -e: return 2.71828182845904523536028747135266249775724709369995957496696762772407663035354759, - ||457138217852516642742746639193200305992181741359662904357290033429526059563073813232862794 -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -pi: return 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899, - ||862803482534211706798214808651328230664709384460955058223172535940812848111745028410270194 -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure expose !.; parse arg x; if !.x\==. then return !.x; _= 1; z=1; y= x*x - do k=2 by 2 until p==z; p=z; _= -_*y/(k*(k-1)); z=z+_; end; !.x=z; return z -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix= x % 1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix; z= 1 - _=1; do j=1 until p==z; p=z; _= _*x/j; z= z+_; end; return z * e()**ix diff --git a/Task/Numerical-integration/Julia/numerical-integration.jl b/Task/Numerical-integration/Julia/numerical-integration-1.jl similarity index 100% rename from Task/Numerical-integration/Julia/numerical-integration.jl rename to Task/Numerical-integration/Julia/numerical-integration-1.jl diff --git a/Task/Numerical-integration/Julia/numerical-integration-2.jl b/Task/Numerical-integration/Julia/numerical-integration-2.jl new file mode 100644 index 0000000000..5e60450fc9 --- /dev/null +++ b/Task/Numerical-integration/Julia/numerical-integration-2.jl @@ -0,0 +1,24 @@ +leftrect(f, x, _) = f(x) +midrect(f, x, h) = f(x + h / 2) +rightrect(f, x, h) = f(x + h) +trapezium(f, x, h) = (f(x) + f(x + h)) / 2 +simpson(f, x, h) = (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6 +cube(x) = x * x * x +reciprocal(x) = inv(x) + +function integrate(f, a, b, steps, meth) + h = (b - a) / steps + return h * sum(meth(f, a + i * h, h) for i in 0:steps-1) +end + +for (a, b, steps, fun) in [ + (0, 1, 100, cube), + (1, 100, 1000, reciprocal), + (0, 5000, 5_000_000, identity), + (0, 6000, 6_000_000, identity)] + for rule in [leftrect, midrect, rightrect, trapezium, simpson] + println(string(fun) * " integrated using " * string(rule)) + println(" from $a to $b ($steps steps) = ", + round(integrate(fun, a, b, steps, rule), sigdigits=14)) + end +end diff --git a/Task/Numerical-integration/REXX/numerical-integration.rexx b/Task/Numerical-integration/REXX/numerical-integration.rexx index 05cd99baa8..dcaa344a38 100644 --- a/Task/Numerical-integration/REXX/numerical-integration.rexx +++ b/Task/Numerical-integration/REXX/numerical-integration.rexx @@ -1,48 +1,108 @@ -/*REXX pgm performs numerical integration using 5 different algorithms and show results.*/ -numeric digits 20 /*use twenty decimal digits precision. */ +-- 8 Jun 2025 +include Settings +arg digs +if digs = '' then + digs=9 +numeric digits digs - do test=1 for 4; say /*perform the 4 different test suites. */ - if test==1 then do; L= 0; H= 1; i= 100; end - if test==2 then do; L= 1; H= 100; i= 1000; end - if test==3 then do; L= 0; H= 5000; i= 5000000; end - if test==4 then do; L= 0; H= 6000; i= 6000000; end - say center('test' test, 79, "═") /*display a header for the test suite. */ - say ' left rectangular('L", "H', 'i") ──► " left_rect(L, H, i) - say ' midpoint rectangular('L", "H', 'i") ──► " midpoint_rect(L, H, i) - say ' right rectangular('L", "H', 'i") ──► " right_rect(L, H, i) - say ' Simpson('L", "H', 'i") ──► " Simpson(L, H, i) - say ' trapezium('L", "H', 'i") ──► " trapezium(L, H, i) - end /*test*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -f: parse arg y; if test>2 then return y /*choose the "as─is" function. */ - if test==1 then return y**3 /* " " cube function. */ - return 1/y /* " " reciprocal " */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -left_rect: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a by h for #; $= $ + f(x) - end /*x*/ - return $*h/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -midpoint_rect: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a+h/2 by h for #; $= $ + f(x) - end /*x*/ - return $*h/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -right_rect: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a+h by h for #; $= $ + f(x) - end /*x*/ - return $*h/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Simpson: procedure expose test; parse arg a,b,#; h= (b-a)/# - hh= h/2; $= f(a + hh) - @= 0; do x=1 for #-1; hx=h*x + a; @= @ + f(hx) - $= $ + f(hx + hh) - end /*x*/ +say 'NUMERICAL INTEGRATION: COMPARE 5 METHODS' +say version +say +w=Digits()+2 +say Left('Function',11) Left( 'Range',w+4) Left('Method',9) Left( 'Steps',7), + Left('Result',w) Left('True',w) ' Error' +say +call Task 'x**3', 0, 1, 100, 1/4 +call Task '1/x', 1, 100, 1000, Ln(100)/1 +call Task 'x', 0, 5000, 1000000, 12500000 +call Task 'x', 0, 5000, 4, 12500000 +call Task '4/(x**2+1)', 0, 1, 100, Pi()/1 +call Task '4/(x**2+1)', 0, 1, 1000, Pi()/1 +call Task 'Sin(x)', 0, Pi()/1, 100, 2 +call Task 'Sin(x)', 0, Pi()/1, 10000, 2 +call Task 'Cos(x)', 0, Pi()/1, 100, 0 +call Task 'Cos(x)', 0, Pi()/1, 10000, 0 +call Task 'Tan(x)', 0, Pi()/1, 100, 0 +call Task 'Tan(x)', 0, Pi()/1, 10000, 0 +call Task 'Exp(x)', -3, 3, 100, Exp(3)-Exp(-3) +call Task 'Exp(x)', -3, 3, 10000, Exp(3)-Exp(-3) +call Task 'Gamma(x)', 1, 8, 100, 2603.238829328642145 +call Task 'Gamma(x)', 1, 8, 10000, 2603.238829328642145 +call Timer +exit - return h * (f(a) + f(b) + 4*$ + 2*@) / 6 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -trapezium: procedure expose test; parse arg a,b,#; $= 0; h= (b-a)/# - do x=a by h for #; $= $ + (f(x) + f(x+h)) - end /*x*/ - return $*h/2 +Task: +procedure expose glob. +arg ff,aa,bb,steps,true +w=Digits()+2 +res=LeftRect(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('LeftRect',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=MidRect(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('MidRect',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=RightRect(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('RightRect',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=Trapezoid(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('Trapezoid',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=Simpson(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('Simpson',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +say +return + +LeftRect: +procedure expose glob. +arg ff,aa,bb,steps +h=(bb-aa)/steps; s=0 +do n = 0 to steps-1 + s=s+Eval(ff,aa+n*h) +end +return s*h + +MidRect: +procedure expose glob. +arg ff,aa,bb,steps +h=(bb-aa)/steps; s=0; aa=aa-h/2 +do n = 1 to steps + s=s+Eval(ff,aa+n*h) +end +return s*h + +RightRect: +procedure expose glob. +arg ff,aa,bb,steps +h=(bb-aa)/steps; s=0 +do n = 1 to steps + s=s+Eval(ff,aa+n*h) +end +return s*h + +Trapezoid: +procedure expose glob. +arg ff,aa,bb,steps +h=(bb-aa)/steps; s=0.5*(Eval(ff,aa)+Eval(ff,bb)) +do n = 1 to steps-1 + s=s+Eval(ff,aa+n*h) +end +return s*h + +Simpson: +procedure expose glob. +arg ff,aa,bb,steps +h=(bb-aa)/steps; s=Eval(ff,aa)+Eval(ff,bb) +do n = 1 by 2 to steps-1 + s=s+4*Eval(ff,aa+n*h) +end +do n = 2 by 2 to steps-1 + s=s+2*Eval(ff,aa+n*h) +end +return s*h/3 + +include Functions +include Special +include Constants +include Helper +include Abend diff --git a/Task/Odd-word-problem/EasyLang/odd-word-problem.easy b/Task/Odd-word-problem/EasyLang/odd-word-problem.easy index 23f334b2fb..0dd0bab09e 100644 --- a/Task/Odd-word-problem/EasyLang/odd-word-problem.easy +++ b/Task/Odd-word-problem/EasyLang/odd-word-problem.easy @@ -4,16 +4,12 @@ func$ read . return substr inp$ inpi 1 . func ispunct c$ . - if c$ = "." or c$ = ":" or c$ = ";" or c$ = "," - return 1 - . + if c$ = "." or c$ = ":" or c$ = ";" or c$ = "," : return 1 return 0 . func$ handle odd . c$ = read - if ispunct c$ = 1 - return c$ - . + if ispunct c$ = 1 : return c$ if odd = 0 write c$ r$ = handle 0 @@ -24,7 +20,7 @@ func$ handle odd . return r$ . . -proc go . . +proc go . repeat c$ = handle odd write c$ diff --git a/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r b/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r new file mode 100644 index 0000000000..d22b8c0b1d --- /dev/null +++ b/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r @@ -0,0 +1,28 @@ +#Create a vector containing the value of each Russian unit in metres +russian_units <- c(1066.8, 2.1336, 0.7112, 0.04445) +names(russian_units) <- c("verst", "sazhen", "arshin", "vershok") + +#Expand this vector to a matrix with one column each for values in km, m, and cm +metric_expand <- function(x){ + return(cbind(x/1000, x, x*100)) +} + +conv_matrix <- metric_expand(russian_units) +colnames(conv_matrix) <- c("km", "m", "cm") + +#This function displays values in all units other than the one that is input +convert_units <- function(value, unit){ + if(unit %in% rownames(conv_matrix)){ + conv_metric <- conv_matrix[unit,] + conv_russian <- conv_matrix[unit,2]/conv_matrix[-which(rownames(conv_matrix)==unit),2] + } + else if(unit %in% colnames(conv_matrix)){ + conv_metric <- conv_matrix[2,-which(colnames(conv_matrix)==unit)]/conv_matrix[2,unit] + conv_russian <- 1/conv_matrix[,unit] + } + return(value*c(conv_metric, conv_russian)) +} + +#Test inputs +convert_units(1, "m") +convert_units(1, "arshin") diff --git a/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy b/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy index a5e70f7c97..536f269645 100644 --- a/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy +++ b/Task/One-dimensional-cellular-automata/EasyLang/one-dimensional-cellular-automata.easy @@ -1,14 +1,14 @@ map[] = [ 0 0 0 1 0 1 1 0 ] cell[] = [ 0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0 ] len celln[] len cell[] -proc evolve . . +proc evolve . for i = 2 to len cell[] - 1 ind = cell[i - 1] + 2 * cell[i] + 4 * cell[i + 1] + 1 celln[i] = map[ind] . swap celln[] cell[] . -proc show . . +proc show . for v in cell[] if v = 1 write "#" diff --git a/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy b/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy index 57f6c46a31..8b5f5f0ed5 100644 --- a/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy +++ b/Task/OpenWebNet-password/EasyLang/openwebnet-password.easy @@ -3,9 +3,7 @@ func calcpass passw$ nonce$ . passw = number passw$ for c$ in strchars nonce$ if c$ <> "0" - if start = 1 - num2 = passw - . + if start = 1 : num2 = passw start = 0 . if c$ = "1" @@ -43,11 +41,11 @@ func calcpass passw$ nonce$ . if c$ <> "0" and c$ <> "9" num1 = bitor num1 num2 . - num2 = num1 + num2 = bitand 0xffffffff num1 . - return num1 + return bitand 0xffffffff num1 . -proc test_passwd passwd$ nonce$ expected$ . . +proc test_passwd passwd$ nonce$ expected$ . res = calcpass passwd$ nonce$ m$ = passwd$ & " " & nonce$ & " " & res & " " & expected$ if res = number expected$ diff --git a/Task/OpenWebNet-password/Rust/openwebnet-password.rs b/Task/OpenWebNet-password/Rust/openwebnet-password.rs new file mode 100644 index 0000000000..40e6b5a6e0 --- /dev/null +++ b/Task/OpenWebNet-password/Rust/openwebnet-password.rs @@ -0,0 +1,113 @@ +fn own_password_calculation(password: i64, nonce: &str) -> i64 { + const M1: i64 = 0xFFFF_FFFF; + const M8: i64 = 0xFFFF_FFF8; + const M16: i64 = 0xFFFF_FFF0; + const M128: i64 = 0xFFFF_FF80; + const M16777216: i64 = 0xFF00_0000; + + let mut flag = true; + let mut number1 = 0; + let mut number2 = 0; + + for ch in nonce.chars() { + number2 = number2 & M1; + + match ch { + '1' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & M128; + number1 = number1 >> 7; + number2 = number2 << 25; + number1 = number1 + number2; + }, + + '2' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & M16; + number1 = number1 >> 4; + number2 = number2 << 28; + number1 = number1 + number2; + }, + + '3' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & M8; + number1 = number1 >> 3; + number2 = number2 << 29; + number1 = number1 + number2; + }, + + '4' => { + if flag { number2 = password; } + flag = false; + number1 = number2 << 1; + number2 = number2 >> 31; + number1 = number1 + number2; + }, + + '5' => { + if flag { number2 = password; } + flag = false; + number1 = number2 << 5; + number2 = number2 >> 27; + number1 = number1 + number2; + }, + + '6' => { + if flag { number2 = password; } + flag = false; + number1 = number2 << 12; + number2 = number2 >> 20; + number1 = number1 + number2; + }, + + '7' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & 0xFF00; + number1 = number1 + ((number2 & 0xFF) << 24); + number1 = number1 + ((number2 & 0xFF0000) >> 16); + number2 = (number2 & M16777216) >> 8; + number1 = number1 + number2; + }, + + '8' => { + if flag { number2 = password; } + flag = false; + number1 = number2 & 0xFFFF; + number1 = number1 << 16; + number1 = number1 + (number2 >> 24); + number2 = number2 & 0xFF0000; + number2 = number2 >> 8; + number1 = number1 + number2; + }, + + '9' => { + if flag { number2 = password; } + flag = false; + number1 = !number2; + }, + + _ => { + number1 = number2; + }, + } + number2 = number1; + } + + return number1 & M1; +} + +fn own_password_calculation_test(password: &str, nonce: &str, expected: i64) { + let result = own_password_calculation(password.parse::().unwrap(), nonce); + let message = format!("{} {} {} {}", password, nonce, result, expected); + println!("{} {}", if result == expected { "PASS" } else { "FAIL" }, message); +} + +fn main() { + own_password_calculation_test("12345", "603356072", 25280520); + own_password_calculation_test("12345", "410501656", 119537670); +} diff --git a/Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr b/Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr new file mode 100644 index 0000000000..b567cbb22d --- /dev/null +++ b/Task/Order-by-pair-comparisons/Crystal/order-by-pair-comparisons.cr @@ -0,0 +1,17 @@ +class Array + def sort_with_prompt + rels = { "<" => -1, "=" => 0, ">" => 1 } + n = 0 + puts "Answer with <, = or >" + sort {|a, b| + n += 1 + loop do + print "#{n}) #{a} < = > #{b} ?: " + ans = gets + break rels[ans] if ans.in?(rels.keys) + end + } + end +end + +p %w(violet red green indigo blue yellow orange).sort_with_prompt diff --git a/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy b/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy index aa9e793980..91e9a254d2 100644 --- a/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy +++ b/Task/Order-by-pair-comparisons/EasyLang/order-by-pair-comparisons.easy @@ -1,4 +1,4 @@ -proc insort item$ . arr$[] . +proc insort item$ &arr$[] . mid = 1 lo = 0 hi = len arr$[] + 1 diff --git a/Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr b/Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr new file mode 100644 index 0000000000..a7d1778620 --- /dev/null +++ b/Task/Order-two-numerical-lists/Crystal/order-two-numerical-lists.cr @@ -0,0 +1,2 @@ +p [1,2,1,3,2] < [1,2,0,4,4,0,0,0] # => false +p [1,2,1,3,2] > [1,2,0,4,4,0,0,0] # => true diff --git a/Task/Ormiston-triples/EasyLang/ormiston-triples.easy b/Task/Ormiston-triples/EasyLang/ormiston-triples.easy index 7860840f0f..6b0da9fba9 100644 --- a/Task/Ormiston-triples/EasyLang/ormiston-triples.easy +++ b/Task/Ormiston-triples/EasyLang/ormiston-triples.easy @@ -1,16 +1,10 @@ fastfunc isprim num . - if num mod 3 = 0 - return 0 - . + if num mod 3 = 0 : return 0 i = 5 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 4 . return 1 @@ -42,9 +36,7 @@ repeat da = digs a if da = db and da = dc cnt += 1 - if cnt <= 25 - write c & " " - . + if cnt <= 25 : write c & " " . . print "" diff --git a/Task/P-Adic-numbers-basic/00-TASK.txt b/Task/P-Adic-numbers-basic/00-TASK.txt index f45bc5d663..25139e9545 100644 --- a/Task/P-Adic-numbers-basic/00-TASK.txt +++ b/Task/P-Adic-numbers-basic/00-TASK.txt @@ -47,4 +47,3 @@ set the shortest prime-exponent combinations that allow valid reconstruction. __TOC__ - diff --git a/Task/P-Adic-numbers-basic/C-sharp/p-adic-numbers-basic.cs b/Task/P-Adic-numbers-basic/C-sharp/p-adic-numbers-basic.cs new file mode 100644 index 0000000000..1909a50638 --- /dev/null +++ b/Task/P-Adic-numbers-basic/C-sharp/p-adic-numbers-basic.cs @@ -0,0 +1,402 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +public static class PAdicNumbersBasic +{ + public static void Main(string[] args) + { + Console.WriteLine("3-adic numbers:"); + Padic padicOne = new Padic(3, -5, 9); + Console.WriteLine("-5 / 9 => " + padicOne); + Padic padicTwo = new Padic(3, 47, 12); + Console.WriteLine("47 / 12 => " + padicTwo); + + Padic sum = padicOne.Add(padicTwo); + Console.WriteLine("sum => " + sum); + Console.WriteLine("Rational = " + sum.ConvertToRational()); + Console.WriteLine(); + + Console.WriteLine("7-adic numbers:"); + padicOne = new Padic(7, 5, 8); + Console.WriteLine("5 / 8 => " + padicOne); + padicTwo = new Padic(7, 353, 30809); + Console.WriteLine("353 / 30809 => " + padicTwo); + + sum = padicOne.Add(padicTwo); + Console.WriteLine("sum => " + sum); + Console.WriteLine("Rational = " + sum.ConvertToRational()); + } +} + +public sealed class Padic +{ + /** + * Create a p-adic, with p = aPrime, from the given rational 'aNumerator' / 'aDenominator'. + */ + public Padic(int aPrime, int aNumerator, int aDenominator) + { + if (aDenominator == 0) + { + throw new ArgumentException("Denominator cannot be zero"); + } + + prime = aPrime; + digits = new List(DIGITS_SIZE); + order = 0; + + // Process rational zero + if (aNumerator == 0) + { + order = MAX_ORDER; + return; + } + + // Remove multiples of 'prime' and adjust the order of the p-adic number accordingly + while (FloorMod(aNumerator, prime) == 0) + { + aNumerator /= prime; + order += 1; + } + + while (FloorMod(aDenominator, prime) == 0) + { + aDenominator /= prime; + order -= 1; + } + + // Standard calculation of p-adic digits + long inverse = ModuloInverse(aDenominator); + while (digits.Count < DIGITS_SIZE) + { + int digit = FloorMod((int)(aNumerator * inverse), prime); + digits.Add(digit); + + aNumerator -= digit * aDenominator; + + if (aNumerator != 0) + { + // The denominator is not a power of a prime + int count = 0; + while (FloorMod(aNumerator, prime) == 0) + { + aNumerator /= prime; + count += 1; + } + + for (int i = count; i > 1; i--) + { + digits.Add(0); + } + } + } + } + + /** + * Return the sum of this p-adic number and the given p-adic number. + */ + public Padic Add(Padic aOther) + { + if (prime != aOther.prime) + { + throw new ArgumentException("Cannot add p-adic's with different primes"); + } + + List result = new List(); + + // Adjust the digits so that the p-adic points are aligned + for (int i = 0; i < -order + aOther.order; i++) + { + aOther.digits.Insert(0, 0); + } + + for (int i = 0; i < -aOther.order + order; i++) + { + digits.Insert(0, 0); + } + + // Standard digit by digit addition + int carry = 0; + for (int i = 0; i < Math.Min(digits.Count, aOther.digits.Count); i++) + { + int sum = digits[i] + aOther.digits[i] + carry; + int remainder = FloorMod(sum, prime); + carry = (sum >= prime) ? 1 : 0; + result.Add(remainder); + } + + // Reverse the changes made to the digits + for (int i = 0; i < -order + aOther.order; i++) + { + aOther.digits.RemoveAt(0); + } + + for (int i = 0; i < -aOther.order + order; i++) + { + digits.RemoveAt(0); + } + + return new Padic(prime, result, AllZeroDigits(result) ? MAX_ORDER : Math.Min(order, aOther.order)); + } + + /** + * Return the Rational representation of this p-adic number. + */ + public Rational ConvertToRational() + { + List numbers = new List(digits); + + // Zero + if (numbers.Count == 0 || AllZeroDigits(numbers)) + { + return new Rational(0, 1); + } + + // Positive integer + if (order >= 0 && EndsWith(numbers, 0)) + { + for (int i = 0; i < order; i++) + { + numbers.Insert(0, 0); + } + + return new Rational(ConvertToDecimal(numbers), 1); + } + + // Negative integer + if (order >= 0 && EndsWith(numbers, prime - 1)) + { + NegateList(numbers); + for (int i = 0; i < order; i++) + { + numbers.Insert(0, 0); + } + + return new Rational(-ConvertToDecimal(numbers), 1); + } + + // Rational + Padic sum = new Padic(prime, new List(digits), order); + Padic self = new Padic(prime, new List(digits), order); + int denominator = 1; + do + { + sum = sum.Add(self); + denominator += 1; + } while (!(EndsWith(sum.digits, 0) || EndsWith(sum.digits, prime - 1))); + + bool negative = EndsWith(sum.digits, prime - 1); + if (negative) + { + NegateList(sum.digits); + } + + int numerator = negative ? -ConvertToDecimal(sum.digits) : ConvertToDecimal(sum.digits); + + if (order > 0) + { + numerator *= (int)Math.Pow(prime, order); + } + + if (order < 0) + { + denominator *= (int)Math.Pow(prime, -order); + } + + return new Rational(numerator, denominator); + } + + /** + * Return a string representation of this p-adic. + */ + public override string ToString() + { + List numbers = new List(digits); + PadWithZeros(numbers); + numbers.Reverse(); + string numberString = string.Join("", numbers.Select(n => n.ToString())); + StringBuilder builder = new StringBuilder(numberString); + + if (order >= 0) + { + for (int i = 0; i < order; i++) + { + builder.Append("0"); + } + + builder.Append(".0"); + } + else + { + builder.Insert(builder.Length + order, "."); + + while (builder.ToString().EndsWith("0")) + { + builder.Remove(builder.Length - 1, 1); + } + } + + return " ..." + builder.ToString().Substring(builder.Length - PRECISION - 1); + } + + // PRIVATE // + + /** + * Create a p-adic, with p = 'aPrime', directly from a list of digits. + * + * With 'aOrder' = 0, the list [1, 2, 3, 4, 5] creates the p-adic ...54321.0 + * 'aOrder' > 0 shifts the list 'aOrder' places to the left and + * 'aOrder' < 0 shifts the list 'aOrder' places to the right. + */ + private Padic(int aPrime, List aDigits, int aOrder) + { + prime = aPrime; + digits = new List(aDigits); + order = aOrder; + } + + /** + * Return the multiplicative inverse of the given decimal number modulo 'prime'. + */ + private int ModuloInverse(int aNumber) + { + int inverse = 1; + while (FloorMod(inverse * aNumber, prime) != 1) + { + inverse += 1; + } + + return inverse; + } + + /** + * Transform the given list of digits representing a p-adic number + * into a list which represents the negation of the p-adic number. + */ + private void NegateList(List aDigits) + { + aDigits[0] = FloorMod(prime - aDigits[0], prime); + for (int i = 1; i < aDigits.Count; i++) + { + aDigits[i] = prime - 1 - aDigits[i]; + } + } + + /** + * Return the given list of base 'prime' integers converted to a decimal integer. + */ + private int ConvertToDecimal(List aNumbers) + { + int decimal_value = 0; + int multiple = 1; + foreach (int number in aNumbers) + { + decimal_value += number * multiple; + multiple *= prime; + } + + return decimal_value; + } + + /** + * Return whether the given list consists of all zeros. + */ + private static bool AllZeroDigits(List aList) + { + return aList.All(i => i == 0); + } + + /** + * The given list is padded on the right by zeros up to a maximum length of 'PRECISION'. + */ + private static void PadWithZeros(List aList) + { + while (aList.Count < DIGITS_SIZE) + { + aList.Add(0); + } + } + + /** + * Return whether the given list ends with multiple instances of the given number. + */ + private static bool EndsWith(List aDigits, int aDigit) + { + for (int i = aDigits.Count - 1; i >= aDigits.Count - PRECISION / 2; i--) + { + if (aDigits[i] != aDigit) + { + return false; + } + } + + return true; + } + + /** + * C# implementation of Java's Math.floorMod + */ + private static int FloorMod(int x, int y) + { + int r = x % y; + // If the signs are different and modulo not zero, adjust result + if ((x ^ y) < 0 && r != 0) + { + r += y; + } + return r; + } + + public class Rational + { + private int numerator; + private int denominator; + + public Rational(int aNumerator, int aDenominator) + { + if (aDenominator < 0) + { + numerator = -aNumerator; + denominator = -aDenominator; + } + else + { + numerator = aNumerator; + denominator = aDenominator; + } + + if (aNumerator == 0) + { + denominator = 1; + } + + int gcd = GCD(numerator, denominator); + numerator /= gcd; + denominator /= gcd; + } + + public override string ToString() + { + return numerator + " / " + denominator; + } + + private int GCD(int aOne, int aTwo) + { + if (aTwo == 0) + { + return Math.Abs(aOne); + } + return GCD(aTwo, FloorMod(aOne, aTwo)); + } + } + + private List digits; + private int order; + + private readonly int prime; + + private const int MAX_ORDER = 1000; + private const int PRECISION = 40; + private const int DIGITS_SIZE = PRECISION + 5; +} diff --git a/Task/P-Adic-numbers-basic/JavaScript/p-adic-numbers-basic.js b/Task/P-Adic-numbers-basic/JavaScript/p-adic-numbers-basic.js new file mode 100644 index 0000000000..c1291de454 --- /dev/null +++ b/Task/P-Adic-numbers-basic/JavaScript/p-adic-numbers-basic.js @@ -0,0 +1,310 @@ +// Rational class for rational number representation +class Rational { + constructor(numerator, denominator) { + if (denominator < 0) { + this.numerator = -numerator; + this.denominator = -denominator; + } else { + this.numerator = numerator; + this.denominator = denominator; + } + + if (numerator === 0) { + this.denominator = 1; + } + + const divisor = this.gcd(Math.abs(this.numerator), this.denominator); + this.numerator = Math.floor(this.numerator / divisor); + this.denominator = Math.floor(this.denominator / divisor); + } + + gcd(a, b) { + while (b !== 0) { + const temp = b; + b = a % b; + a = temp; + } + return a; + } + + toString() { + return `${this.numerator} / ${this.denominator}`; + } +} + +// P_adic class for p-adic number representation +class P_adic { + static PRECISION = 40; + static ORDER_MAX = 1000; + static DIGITS_SIZE = P_adic.PRECISION + 5; + + // Create a P_adic number with p = 'prime', from the given rational 'numerator' / 'denominator' + constructor(prime, numerator, denominator, digits = null, order = null) { + this.prime = prime; + + // If digits and order are provided, use them directly (for internal use) + if (digits !== null && order !== null) { + this.digits = digits; + this.order = order; + return; + } + + if (denominator === 0) { + throw new Error("Denominator cannot be zero"); + } + + this.order = 0; + + // Process rational zero + if (numerator === 0) { + this.digits = Array(P_adic.DIGITS_SIZE).fill(0); + this.order = P_adic.ORDER_MAX; + return; + } + + // Remove multiples of 'prime' and adjust the order of the P_adic number accordingly + while (this.moduloPrime(numerator) === 0) { + numerator = Math.floor(numerator / prime); + this.order += 1; + } + + while (this.moduloPrime(denominator) === 0) { + denominator = Math.floor(denominator / prime); + this.order -= 1; + } + + // Standard calculation of P_adic digits + const inverse = this.moduloInverse(denominator); + this.digits = []; + + while (this.digits.length < P_adic.DIGITS_SIZE) { + const digit = this.moduloPrime(numerator * inverse); + this.digits.push(digit); + + numerator -= digit * denominator; + + if (numerator !== 0) { + // The denominator is not a power of a prime + let count = 0; + while (this.moduloPrime(numerator) === 0) { + numerator = Math.floor(numerator / prime); + count += 1; + } + + for (let i = count; i > 1; --i) { + this.digits.push(0); + } + } + } + } + + // Return the sum of this P_adic number with the given P_adic number + add(other) { + if (this.prime !== other.prime) { + throw new Error("Cannot add p-adic's with different primes"); + } + + let this_digits = [...this.digits]; + let other_digits = [...other.digits]; + let result = []; + + // Adjust the digits so that the P_adic points are aligned + for (let i = 0; i < -this.order + other.order; ++i) { + other_digits.unshift(0); + } + + for (let i = 0; i < -other.order + this.order; ++i) { + this_digits.unshift(0); + } + + // Standard digit by digit addition + let carry = 0; + for (let i = 0; i < Math.min(this_digits.length, other_digits.length); ++i) { + const sum = this_digits[i] + other_digits[i] + carry; + const remainder = sum % this.prime; + carry = (sum >= this.prime) ? 1 : 0; + result.push(remainder); + } + + return new P_adic( + this.prime, + null, + null, + result, + this.allZeroDigits(result) ? P_adic.ORDER_MAX : Math.min(this.order, other.order) + ); + } + + // Return the Rational representation of this P_adic number + convertToRational() { + let numbers = [...this.digits]; + + // Zero + if (numbers.length === 0 || this.allZeroDigits(numbers)) { + return new Rational(0, 1); + } + + // Positive integer + if (this.order >= 0 && this.endsWith(numbers, 0)) { + for (let i = 0; i < this.order; ++i) { + numbers.unshift(0); + } + + return new Rational(this.convertToDecimal(numbers), 1); + } + + // Negative integer + if (this.order >= 0 && this.endsWith(numbers, this.prime - 1)) { + this.negateDigits(numbers); + for (let i = 0; i < this.order; ++i) { + numbers.unshift(0); + } + + return new Rational(-this.convertToDecimal(numbers), 1); + } + + // Rational + const copy = new P_adic(this.prime, null, null, [...this.digits], this.order); + let sum = new P_adic(this.prime, null, null, [...this.digits], this.order); + let denominator = 1; + + do { + sum = sum.add(copy); + denominator += 1; + } while (!(this.endsWith(sum.digits, 0) || this.endsWith(sum.digits, this.prime - 1))); + + const negative = this.endsWith(sum.digits, this.prime - 1); + if (negative) { + this.negateDigits(sum.digits); + } + + let numerator = negative ? -this.convertToDecimal(sum.digits) : this.convertToDecimal(sum.digits); + + if (this.order > 0) { + numerator *= Math.pow(this.prime, this.order); + } + + if (this.order < 0) { + denominator *= Math.pow(this.prime, -this.order); + } + + return new Rational(numerator, denominator); + } + + // Return a string representation of this P_adic number + toString() { + let numbers = [...this.digits]; + this.padWithZeros(numbers); + + let result = ""; + for (let i = numbers.length - 1; i >= 0; --i) { + result += this.digits[i].toString(); + } + + if (this.order >= 0) { + for (let i = 0; i < this.order; ++i) { + result += "0"; + } + + result += ".0"; + } else { + result = result.slice(0, result.length + this.order) + "." + result.slice(result.length + this.order); + + while (result[result.length - 1] === '0') { + result = result.substring(0, result.length - 1); + } + } + + return " ..." + result.substring(result.length - P_adic.PRECISION - 1); + } + + // Transform the given array of digits representing a P_adic number + // into an array which represents the negation of the P_adic number + negateDigits(numbers) { + numbers[0] = this.moduloPrime(this.prime - numbers[0]); + for (let i = 1; i < numbers.length; ++i) { + numbers[i] = this.prime - 1 - numbers[i]; + } + } + + // Return the multiplicative inverse of the given number modulo 'prime' + moduloInverse(number) { + let inverse = 1; + while (this.moduloPrime(inverse * number) !== 1) { + inverse += 1; + } + return inverse; + } + + // Return the given number modulo 'prime' in the range 0...'prime' - 1 + moduloPrime(number) { + const div = number % this.prime; + return (div >= 0) ? div : div + this.prime; + } + + // The given array is padded on the right by zeros up to a maximum length of 'DIGITS_SIZE' + padWithZeros(array) { + while (array.length < P_adic.DIGITS_SIZE) { + array.push(0); + } + } + + // Return the given array of base 'prime' integers converted to a decimal integer + convertToDecimal(numbers) { + let decimal = 0; + let multiple = 1; + for (const number of numbers) { + decimal += number * multiple; + multiple *= this.prime; + } + return decimal; + } + + // Return whether the given array consists of all zeros + allZeroDigits(numbers) { + for (const number of numbers) { + if (number !== 0) { + return false; + } + } + return true; + } + + // Return whether the given array ends with multiple instances of the given number + endsWith(numbers, number) { + for (let i = numbers.length - 1; i >= numbers.length - P_adic.PRECISION / 2; --i) { + if (numbers[i] !== number) { + return false; + } + } + return true; + } +} + +// Main function equivalent +function main() { + console.log("3-adic numbers:"); + let padic_one = new P_adic(3, -2, 87); + console.log("-2 / 87 => " + padic_one.toString()); + let padic_two = new P_adic(3, 4, 97); + console.log("4 / 97 => " + padic_two.toString()); + + let sum = padic_one.add(padic_two); + console.log("sum => " + sum.toString()); + console.log("Rational = " + sum.convertToRational().toString()); + console.log(); + + console.log("7-adic numbers:"); + padic_one = new P_adic(7, 5, 8); + console.log("5 / 8 => " + padic_one.toString()); + padic_two = new P_adic(7, 353, 30809); + console.log("353 / 30809 => " + padic_two.toString()); + + sum = padic_one.add(padic_two); + console.log("sum => " + sum.toString()); + console.log("Rational = " + sum.convertToRational().toString()); + console.log(); +} + +// Run the main function +main(); diff --git a/Task/P-Adic-numbers-basic/Rust/p-adic-numbers-basic.rs b/Task/P-Adic-numbers-basic/Rust/p-adic-numbers-basic.rs new file mode 100644 index 0000000000..726a7d21bc --- /dev/null +++ b/Task/P-Adic-numbers-basic/Rust/p-adic-numbers-basic.rs @@ -0,0 +1,391 @@ +use std::cmp; +use std::sync::atomic::{AtomicI32, Ordering}; +use std::cell::UnsafeCell; + +// constants +const EMX: i32 = 64; // exponent maximum (if indexing starts at -EMX) +const DMX: i32 = 100000; // approximation loop maximum +const AMX: i32 = 1048576; // argument maximum +const PMAX: i32 = 32749; // prime maximum + +// Using atomics for the global variables +static P1: AtomicI32 = AtomicI32::new(0); +static P: AtomicI32 = AtomicI32::new(7); // default prime +static K: AtomicI32 = AtomicI32::new(11); // precision + +fn abs(a: i32) -> i32 { + if a >= 0 { + a + } else { + -a + } +} + +fn min(a: i32, b: i32) -> i32 { + if a < b { + a + } else { + b + } +} + +struct Ratio { + a: i32, + b: i32, +} + +struct Padic { + v: i32, + d: [i32; 2 * EMX as usize], // add EMX to index to be consistent with FB +} + +impl Padic { + // Create a new Padic with default values + fn new() -> Self { + Padic { + v: 0, + d: [0; 2 * EMX as usize], + } + } + + // (re)initialize receiver from Ratio, set 'sw' to print + fn r2pa(&mut self, q: Ratio, sw: i32) -> i32 { + let mut a = q.a; + let mut b = q.b; + if b == 0 { + return 1; + } + if b < 0 { + b = -b; + a = -a; + } + if abs(a) > AMX || b > AMX { + return -1; + } + + let p_val = P.load(Ordering::Relaxed); + if p_val < 2 || K.load(Ordering::Relaxed) < 1 { + return 1; + } + + // Set P to minimum of P and PMAX + let p_val = cmp::min(p_val, PMAX); + P.store(p_val, Ordering::Relaxed); + + // Set K to minimum of K and EMX-1 + let k_val = cmp::min(K.load(Ordering::Relaxed), EMX - 1); + K.store(k_val, Ordering::Relaxed); + + if sw != 0 { + println!("{}/{} + ", a, b); // numerator, denominator + println!("0({}^{})", p_val, k_val); // prime, precision + } + + // (re)initialize + self.v = 0; + P1.store(p_val - 1, Ordering::Relaxed); + self.d = [0; 2 * EMX as usize]; + + if a == 0 { + return 0; + } + + let mut i = 0; + let p1_val = P1.load(Ordering::Relaxed); + + // find -exponent of p in b + while b % p_val == 0 { + b = b / p_val; + i -= 1; + } + + let mut s = 0; + let r = b % p_val; + + // modular inverse for small p + let mut b1 = 1; + while b1 <= p1_val { + s += r; + if s > p1_val { + s -= p_val; + } + if s == 1 { + break; + } + b1 += 1; + } + + if b1 == p_val { + println!("r2pa: impossible inverse mod"); + return -1; + } + + self.v = EMX; + + loop { + // find exponent of P in a + while a % p_val == 0 { + a = a / p_val; + i += 1; + } + + // valuation + if self.v == EMX { + self.v = i; + } + + // upper bound + if i >= EMX { + break; + } + + // check precision + if (i - self.v) > k_val { + break; + } + + // next digit + self.d[(i + EMX) as usize] = a * b1 % p_val; + if self.d[(i + EMX) as usize] < 0 { + self.d[(i + EMX) as usize] += p_val; + } + + // remainder - digit * divisor + a -= self.d[(i + EMX) as usize] * b; + if a == 0 { + break; + } + } + + 0 + } + + // Horner's rule + fn dsum(&self) -> i32 { + let t = cmp::min(self.v, 0); + let mut s = 0; + let p_val = P.load(Ordering::Relaxed); + let k_val = K.load(Ordering::Relaxed); + + for i in (t..=k_val - 1 + t).rev() { + let r = s; + s *= p_val; + if r != 0 && (s / r - p_val != 0) { + // overflow + s = -1; + break; + } + s += self.d[(i + EMX) as usize]; + } + s + } + + // add b to receiver + fn add(&self, b: &Padic) -> Padic { + let mut c = 0; + let mut r = Padic::new(); + r.v = cmp::min(self.v, b.v); + let p_val = P.load(Ordering::Relaxed); + let p1_val = P1.load(Ordering::Relaxed); + let k_val = K.load(Ordering::Relaxed); + + for i in r.v..=k_val + r.v { + c += self.d[(i + EMX) as usize] + b.d[(i + EMX) as usize]; + if c > p1_val { + r.d[(i + EMX) as usize] = c - p_val; + c = 1; + } else { + r.d[(i + EMX) as usize] = c; + c = 0; + } + } + + r + } + + // complement of receiver + fn cmpt(&self) -> Padic { + let mut c = 1; + let mut r = Padic::new(); + r.v = self.v; + let p_val = P.load(Ordering::Relaxed); + let p1_val = P1.load(Ordering::Relaxed); + let k_val = K.load(Ordering::Relaxed); + + for i in self.v..=k_val + self.v { + c += p1_val - self.d[(i + EMX) as usize]; + if c > p1_val { + r.d[(i + EMX) as usize] = c - p_val; + c = 1; + } else { + r.d[(i + EMX) as usize] = c; + c = 0; + } + } + + r + } + + // rational reconstruction + fn crat(&self) { + let mut fl = false; + let mut s = self.clone(); + let mut j = 0; + let mut i = 1; + let p_val = P.load(Ordering::Relaxed); + let p1_val = P1.load(Ordering::Relaxed); + let k_val = K.load(Ordering::Relaxed); + + // denominator count + while i <= DMX { + // check for integer + j = k_val - 1 + self.v; + while j >= self.v { + if s.d[(j + EMX) as usize] != 0 { + break; + } + j -= 1; + } + fl = ((j - self.v) * 2) < k_val; + if fl { + fl = false; + break; + } + + // check negative integer + j = k_val - 1 + self.v; + while j >= self.v { + if p1_val - s.d[(j + EMX) as usize] != 0 { + break; + } + j -= 1; + } + fl = ((j - self.v) * 2) < k_val; + if fl { + break; + } + + // repeatedly add self to s + s = s.add(self); + i += 1; + } + + if fl { + s = s.cmpt(); + } + + // numerator: weighted digit sum + let x = s.dsum(); + let mut y = i; + + if x < 0 || y > DMX { + println!("{} {}", x, y); + println!("crat: fail"); + } else { + // negative powers + let mut i = self.v; + while i <= -1 { + y *= p_val; + i += 1; + } + + // negative rational + let final_x = if fl { -x } else { x }; + print!("{}", final_x); + if y > 1 { + print!("/{}", y); + } + println!(); + } + } + + // print expansion + fn printf(&self, sw: i32) { + let t = cmp::min(self.v, 0); + let k_val = K.load(Ordering::Relaxed); + + for i in (t..=k_val - 1 + t).rev() { + print!("{}", self.d[(i + EMX) as usize]); + if i == 0 && self.v < 0 { + print!("."); + } + print!(" "); + } + println!(); + // rational approximation + if sw != 0 { + self.crat(); + } + } +} + +// Implement the Clone trait for Padic +impl Clone for Padic { + fn clone(&self) -> Self { + Padic { + v: self.v, + d: self.d, + } + } +} + +fn main() { + let data = vec![ + /* rational reconstruction depends on the precision + until the dsum-loop overflows */ + vec![2, 1, 2, 4, 1, 1], + vec![4, 1, 2, 4, 3, 1], + vec![4, 1, 2, 5, 3, 1], + vec![4, 9, 5, 4, 8, 9], + vec![26, 25, 5, 4, -109, 125], + vec![49, 2, 7, 6, -4851, 2], + vec![-9, 5, 3, 8, 27, 7], + vec![5, 19, 2, 12, -101, 384], + /* two decadic pairs */ + vec![2, 7, 10, 7, -1, 7], + vec![34, 21, 10, 9, -39034, 791], + /* familiar digits */ + vec![11, 4, 2, 43, 679001, 207], + vec![-8, 9, 23, 9, 302113, 92], + vec![-22, 7, 3, 23, 46071, 379], + vec![-22, 7, 32749, 3, 46071, 379], + vec![35, 61, 5, 20, 9400, 109], + vec![-101, 109, 61, 7, 583376, 6649], + vec![-25, 26, 7, 13, 5571, 137], + vec![1, 4, 7, 11, 9263, 2837], + vec![122, 407, 7, 11, -517, 1477], + /* more subtle */ + vec![5, 8, 7, 11, 353, 30809], + ]; + + let mut sw = 0; + let mut a = Padic::new(); + let mut b = Padic::new(); + + for d in data { + let q = Ratio { a: d[0], b: d[1] }; + + P.store(d[2], Ordering::Relaxed); + K.store(d[3], Ordering::Relaxed); + + sw = a.r2pa(q, 1); + if sw == 1 { + break; + } + a.printf(0); + + let q_b = Ratio { a: d[4], b: d[5] }; + sw = sw | b.r2pa(q_b, 1); + if sw == 1 { + break; + } + + if sw == 0 { + b.printf(0); + let c = a.add(&b); + println!("+ ="); + c.printf(1); + } + println!(); + } +} diff --git a/Task/P-Adic-numbers-basic/Zig/p-adic-numbers-basic.zig b/Task/P-Adic-numbers-basic/Zig/p-adic-numbers-basic.zig new file mode 100644 index 0000000000..d69c31cba2 --- /dev/null +++ b/Task/P-Adic-numbers-basic/Zig/p-adic-numbers-basic.zig @@ -0,0 +1,357 @@ +const std = @import("std"); +const math = std.math; +const stdout = std.io.getStdOut().writer(); +const print = std.debug.print; + +// Constants +const EMX: i32 = 64; // exponent maximum (if indexing starts at -EMX) +const DMX: i32 = 100000; // approximation loop maximum +const AMX: i32 = 1048576; // argument maximum +const PMAX: i32 = 32749; // prime maximum + +// Global variables +var P1: i32 = 0; +var P: i32 = 7; // default prime +var K: i32 = 11; // precision + +// Helper functions +fn abs(a: i32) i32 { + return if (a >= 0) a else -a; +} + +fn min(a: i32, b: i32) i32 { + return if (a < b) a else b; +} + +const Ratio = struct { + a: i32, + b: i32, +}; + +const Padic = struct { + v: i32, + d: [2 * EMX]i32, // add EMX to index to be consistent + + // Create a new Padic with default values + fn new() Padic { + return Padic{ + .v = 0, + .d = [_]i32{0} ** (2 * EMX), + }; + } + + // (re)initialize receiver from Ratio, set 'sw' to print + fn r2pa(self: *Padic, q: Ratio, sw: i32) i32 { + var a = q.a; + var b = q.b; + if (b == 0) { + return 1; + } + if (b < 0) { + b = -b; + a = -a; + } + if (abs(a) > AMX or b > AMX) { + return -1; + } + + if (P < 2 or K < 1) { + return 1; + } + + // Set P to minimum of P and PMAX + P = @min(P, PMAX); + + // Set K to minimum of K and EMX-1 + K = @min(K, EMX - 1); + + if (sw != 0) { + print("{d}/{d} + \n", .{a, b}); // numerator, denominator + print("0({d}^{d})\n", .{P, K}); // prime, precision + } + + // (re)initialize + self.v = 0; + P1 = P - 1; + // std.mem.set(i32, &self.d, 0); + + if (a == 0) { + return 0; + } + + var i: i32 = 0; + + // find -exponent of p in b + while ( @rem(b, P) == 0) { + b = @divTrunc(b, P); + i -= 1; + } + + var s: i32 = 0; + const r = @rem(b, P); + + // modular inverse for small p + var b1: i32 = 1; + while (b1 <= P1) { + s += r; + if (s > P1) { + s -= P; + } + if (s == 1) { + break; + } + b1 += 1; + } + + if (b1 == P) { + print("r2pa: impossible inverse mod\n", .{}); + return -1; + } + + self.v = EMX; + + while (true) { + // find exponent of P in a + while ( @rem(a, P)==0) { + a = @divTrunc(a, P); + i += 1; + } + + // valuation + if (self.v == EMX) { + self.v = i; + } + + // upper bound + if (i >= EMX) { + break; + } + + // check precision + if ((i - self.v) > K) { + break; + } + + // next digit + self.d[@intCast(i + EMX)] = @mod(a * b1, P); + if (self.d[@intCast(i + EMX)] < 0) { + self.d[@intCast(i + EMX)] += P; + } + + // remainder - digit * divisor + a -= self.d[@intCast(i + EMX)] * b; + if (a == 0) { + break; + } + } + + return 0; + } + + // Horner's rule + fn dsum(self: *const Padic) i32 { + const t = @min(self.v, 0); + var s: i32 = 0; + + var i = K - 1 + t; + while (i >= t) : (i -= 1) { + const r = s; + s *= P; + if (r != 0 and (@divTrunc(s, r) - P != 0)) { + // overflow + s = -1; + break; + } + s += self.d[@intCast(i + EMX)]; + } + return s; + } + + // add b to receiver + fn add(self: *const Padic, b: *const Padic) Padic { + var c: i32 = 0; + var r = Padic.new(); + r.v = @min(self.v, b.v); + + var i: i32 = r.v; + while (i <= K + r.v) : (i += 1) { + c += self.d[@intCast(i + EMX)] + b.d[@intCast(i + EMX)]; + if (c > P1) { + r.d[@intCast(i + EMX)] = c - P; + c = 1; + } else { + r.d[@intCast(i + EMX)] = c; + c = 0; + } + } + + return r; + } + + // complement of receiver + fn cmpt(self: *const Padic) Padic { + var c: i32 = 1; + var r = Padic.new(); + r.v = self.v; + + var i: i32 = self.v; + while (i <= K + self.v) : (i += 1) { + c += P1 - self.d[@intCast(i + EMX)]; + if (c > P1) { + r.d[@intCast(i + EMX)] = c - P; + c = 1; + } else { + r.d[@intCast(i + EMX)] = c; + c = 0; + } + } + + return r; + } + + // rational reconstruction + fn crat(self: *const Padic) void { + var fl = false; + var s = self.*; + var j: i32 = 0; + var i: i32 = 1; + + // denominator count + while (i <= DMX) : (i += 1) { + // check for integer + j = K - 1 + self.v; + while (j >= self.v) : (j -= 1) { + if (s.d[@intCast(j + EMX)] != 0) { + break; + } + } + fl = ((j - self.v) * 2) < K; + if (fl) { + fl = false; + break; + } + + // check negative integer + j = K - 1 + self.v; + while (j >= self.v) : (j -= 1) { + if (P1 - s.d[@intCast(j + EMX)] != 0) { + break; + } + } + fl = ((j - self.v) * 2) < K; + if (fl) { + break; + } + + // repeatedly add self to s + s = s.add(self); + } + + if (fl) { + s = s.cmpt(); + } + + // numerator: weighted digit sum + const x = s.dsum(); + var y = i; + + if (x < 0 or y > DMX) { + print("{d} {d}\n", .{x, y}); + print("crat: fail\n", .{}); + } else { + // negative powers + var i_pow = self.v; + while (i_pow <= -1) : (i_pow += 1) { + y *= P; + } + + // negative rational + const final_x = if (fl) -x else x; + print("{d}", .{final_x}); + if (y > 1) { + print("/{d}", .{y}); + } + print("\n", .{}); + } + } + + // print expansion + fn printf(self: *const Padic, sw: i32) void { + const t = @min(self.v, 0); + + var i = K - 1 + t; + while (i >= t) : (i -= 1) { + print("{d}", .{self.d[@intCast(i + EMX)]}); + if (i == 0 and self.v < 0) { + print(".", .{}); + } + print(" ", .{}); + } + print("\n", .{}); + // rational approximation + if (sw != 0) { + self.crat(); + } + } +}; + +pub fn main() !void { + const data = [_][6]i32{ + // rational reconstruction depends on the precision + // until the dsum-loop overflows + [_]i32{ 2, 1, 2, 4, 1, 1 }, + [_]i32{ 4, 1, 2, 4, 3, 1 }, + [_]i32{ 4, 1, 2, 5, 3, 1 }, + [_]i32{ 4, 9, 5, 4, 8, 9 }, + [_]i32{ 26, 25, 5, 4, -109, 125 }, + [_]i32{ 49, 2, 7, 6, -4851, 2 }, + [_]i32{ -9, 5, 3, 8, 27, 7 }, + [_]i32{ 5, 19, 2, 12, -101, 384 }, + // two decadic pairs + [_]i32{ 2, 7, 10, 7, -1, 7 }, + [_]i32{ 34, 21, 10, 9, -39034, 791 }, + // familiar digits + [_]i32{ 11, 4, 2, 43, 679001, 207 }, + [_]i32{ -8, 9, 23, 9, 302113, 92 }, + [_]i32{ -22, 7, 3, 23, 46071, 379 }, + [_]i32{ -22, 7, 32749, 3, 46071, 379 }, + [_]i32{ 35, 61, 5, 20, 9400, 109 }, + [_]i32{ -101, 109, 61, 7, 583376, 6649 }, + [_]i32{ -25, 26, 7, 13, 5571, 137 }, + [_]i32{ 1, 4, 7, 11, 9263, 2837 }, + [_]i32{ 122, 407, 7, 11, -517, 1477 }, + // more subtle + [_]i32{ 5, 8, 7, 11, 353, 30809 }, + }; + + var sw: i32 = 0; + var a = Padic.new(); + var b = Padic.new(); + + for (data) |d| { + const q = Ratio{ .a = d[0], .b = d[1] }; + + P = d[2]; + K = d[3]; + + sw = a.r2pa(q, 1); + if (sw == 1) { + break; + } + a.printf(0); + + const q_b = Ratio{ .a = d[4], .b = d[5] }; + sw = sw | b.r2pa(q_b, 1); + if (sw == 1) { + break; + } + + if (sw == 0) { + b.printf(0); + const c = a.add(&b); + print("+ =\n", .{}); + c.printf(1); + } + print("\n", .{}); + } +} diff --git a/Task/P-Adic-square-roots/Go/p-adic-square-roots.go b/Task/P-Adic-square-roots/Go/p-adic-square-roots.go new file mode 100644 index 0000000000..f567e32ad2 --- /dev/null +++ b/Task/P-Adic-square-roots/Go/p-adic-square-roots.go @@ -0,0 +1,388 @@ +package main + +import ( + "fmt" + "math" + "strconv" + "strings" +) + +// PAdicSquareRoot represents a p-adic square root number +type PAdicSquareRoot struct { + prime int64 + precision int + digits []int64 + order int +} + +const orderMax = 1000 + +// NewPAdicSquareRoot creates a p-adic square root number from a rational number +func NewPAdicSquareRoot(prime int64, precision int, numerator int64, denominator int64) (*PAdicSquareRoot, error) { + if denominator == 0 { + return nil, fmt.Errorf("denominator cannot be zero") + } + + digitsSize := precision + 5 + order := 0 + + // Process rational zero + if numerator == 0 { + return &PAdicSquareRoot{ + prime: prime, + precision: precision, + digits: make([]int64, digitsSize), + order: orderMax, + }, nil + } + + // Remove multiples of 'prime' and adjust the order accordingly + for modulo(numerator, prime) == 0 { + numerator /= prime + order++ + } + + for modulo(denominator, prime) == 0 { + denominator /= prime + order-- + } + + if (order & 1) != 0 { + return nil, fmt.Errorf("number does not have a square root in %d-adic", prime) + } + order >>= 1 + + result := &PAdicSquareRoot{ + prime: prime, + precision: precision, + digits: []int64{}, + order: order, + } + + var err error + if prime == 2 { + err = result.squareRootEvenPrime(numerator, denominator) + } else { + err = result.squareRootOddPrime(numerator, denominator) + } + + if err != nil { + return nil, err + } + + // Ensure we have the right number of digits + for len(result.digits) < digitsSize { + result.digits = append(result.digits, 0) + } + if len(result.digits) > digitsSize { + result.digits = result.digits[:digitsSize] + } + + return result, nil +} + +// Clone returns a copy of the PAdicSquareRoot +func (p *PAdicSquareRoot) Clone() *PAdicSquareRoot { + digitsCopy := make([]int64, len(p.digits)) + copy(digitsCopy, p.digits) + + return &PAdicSquareRoot{ + prime: p.prime, + precision: p.precision, + digits: digitsCopy, + order: p.order, + } +} + +// Negate returns the additive inverse of this p-adic square root number +func (p *PAdicSquareRoot) Negate() *PAdicSquareRoot { + if len(p.digits) == 0 { + return p.Clone() + } + + result := p.Clone() + negateDigits(result.digits, p.prime) + return result +} + +// Multiply returns the product of this p-adic square root number and another +func (p *PAdicSquareRoot) Multiply(other *PAdicSquareRoot) (*PAdicSquareRoot, error) { + if p.prime != other.prime { + return nil, fmt.Errorf("cannot multiply p-adic's with different primes") + } + + if len(p.digits) == 0 || len(other.digits) == 0 { + return NewPAdicSquareRoot(p.prime, p.precision, 0, 1) + } + + digitsSize := p.precision + 5 + product := multiplyDigits(p.digits, other.digits, p.prime, digitsSize) + + return &PAdicSquareRoot{ + prime: p.prime, + precision: p.precision, + digits: product, + order: p.order + other.order, + }, nil +} + +// ConvertToRational returns a string representation of this p-adic square root as a rational number +func (p *PAdicSquareRoot) ConvertToRational() (string, error) { + if len(p.digits) == 0 { + return "0 / 1", nil + } + + // Lagrange lattice basis reduction in two dimensions + seriesSum := p.digits[0] + maximumPrime := int64(1) + + for i := 1; i < p.precision; i++ { + maximumPrime *= p.prime + seriesSum += p.digits[i] * maximumPrime + } + + one := []int64{maximumPrime, seriesSum} + two := []int64{0, 1} + + previousNorm := seriesSum*seriesSum + 1 + currentNorm := previousNorm + 1 + i := 0 + j := 1 + + for previousNorm < currentNorm { + numerator := one[i]*one[j] + two[i]*two[j] + denominator := previousNorm + currentNorm = int64(math.Floor(float64(numerator)/float64(denominator) + 0.5)) + one[i] -= currentNorm * one[j] + two[i] -= currentNorm * two[j] + + currentNorm = previousNorm + previousNorm = one[i]*one[i] + two[i]*two[i] + + if previousNorm < currentNorm { + one[i], one[j] = one[j], one[i] + two[i], two[j] = two[j], two[i] + } + } + + x := one[j] + y := two[j] + if y < 0 { + y = -y + x = -x + } + + if math.Abs(float64(one[i]*y-x*two[i])) != float64(maximumPrime) { + return "", fmt.Errorf("rational reconstruction failed") + } + + for k := p.order; k < 0; k++ { + y *= p.prime + } + + for k := 0; k < p.order; k++ { + x *= p.prime + } + + return fmt.Sprintf("%d / %d", x, y), nil +} + +// String returns a string representation of this p-adic square root +func (p *PAdicSquareRoot) String() string { + digits := make([]int64, len(p.digits)) + copy(digits, p.digits) + + // Pad with zeros if needed + for len(digits) < p.precision+5 { + digits = append(digits, 0) + } + + var result strings.Builder + for i := len(digits) - 1; i >= 0; i-- { + result.WriteString(strconv.FormatInt(digits[i], 10)) + } + + resultStr := result.String() + + if p.order >= 0 { + for i := 0; i < p.order; i++ { + resultStr += "0" + } + resultStr += ".0" + } else { + insertPos := len(resultStr) + p.order + if insertPos >= 0 { + resultStr = resultStr[:insertPos] + "." + resultStr[insertPos:] + } else { + // If we need to insert before the start, pad with zeros + zerosNeeded := -insertPos + resultStr = "0." + strings.Repeat("0", zerosNeeded) + resultStr + } + + // Remove trailing zeros + for strings.HasSuffix(resultStr, "0") { + resultStr = resultStr[:len(resultStr)-1] + } + } + + // Return with ellipsis at the beginning + startPos := 0 + if len(resultStr) > p.precision+1 { + startPos = len(resultStr) - p.precision - 1 + } + return " ..." + resultStr[startPos:] +} + +// squareRootEvenPrime creates a 2-adic number which is the square root of the rational numerator/denominator +func (p *PAdicSquareRoot) squareRootEvenPrime(numerator, denominator int64) error { + if modulo(numerator*denominator, 8) != 1 { + return fmt.Errorf("number does not have a square root in 2-adic") + } + + // First digit + sum := int64(1) + p.digits = append(p.digits, 1) + + // Further digits + digitsSize := p.precision + 5 + for len(p.digits) < digitsSize { + factor := denominator*sum*sum - numerator + valuation := 0 + factorTemp := factor + for modulo(factorTemp, 2) == 0 { + factorTemp /= 2 + valuation++ + } + + sum += int64(math.Pow(2, float64(valuation-1))) + + for len(p.digits) < valuation-1 { + p.digits = append(p.digits, 0) + } + p.digits = append(p.digits, 1) + } + + return nil +} + +// squareRootOddPrime creates a p-adic number, with an odd prime number, which is the p-adic square root +func (p *PAdicSquareRoot) squareRootOddPrime(numerator, denominator int64) error { + // First digit + firstDigit := int64(0) + for i := int64(1); i < p.prime && firstDigit == 0; i++ { + if modulo(denominator*i*i-numerator, p.prime) == 0 { + firstDigit = i + } + } + + if firstDigit == 0 { + return fmt.Errorf("number does not have a square root in %d-adic", p.prime) + } + + p.digits = append(p.digits, firstDigit) + + // Further digits + coefficient := moduloInverse(modulo(2*denominator*firstDigit, p.prime), p.prime) + sum := firstDigit + digitsSize := p.precision + 5 + + for i := 2; i < digitsSize; i++ { + nextSum := sum - int64(coefficient)*(denominator*sum*sum-numerator) + nextSum = modulo(nextSum, int64(math.Pow(float64(p.prime), float64(i)))) + nextSum -= sum + sum += nextSum + + digit := nextSum / int64(math.Pow(float64(p.prime), float64(i-1))) + p.digits = append(p.digits, digit) + } + + return nil +} + +// negateDigits transforms the given vector of digits representing a p-adic number +// into a vector which represents the negation of the p-adic number +func negateDigits(numbers []int64, prime int64) { + if len(numbers) > 0 { + numbers[0] = modulo(prime-numbers[0], prime) + for i := 1; i < len(numbers); i++ { + numbers[i] = prime - 1 - numbers[i] + } + } +} + +// multiplyDigits returns the list obtained by multiplying the digits of the given two lists +func multiplyDigits(one, two []int64, prime int64, maxSize int) []int64 { + product := make([]int64, len(one)+len(two)) + + for b := 0; b < len(two); b++ { + carry := int64(0) + for a := 0; a < len(one); a++ { + product[a+b] += one[a]*two[b] + carry + carry = product[a+b] / prime + product[a+b] %= prime + } + if b+len(one) < len(product) { + product[b+len(one)] = carry + } + } + + // Truncate to maxSize + if len(product) > maxSize { + product = product[:maxSize] + } + return product +} + +// moduloInverse returns the multiplicative inverse of the given number modulo 'prime' +func moduloInverse(number, prime int64) int64 { + inverse := int64(1) + for modulo(inverse*number, prime) != 1 { + inverse++ + } + return inverse +} + +// modulo returns the given number modulo 'prime' in the range 0..'prime' - 1 +func modulo(number, modulus int64) int64 { + div := number % modulus + if div >= 0 { + return div + } + return div + modulus +} + +func main() { + tests := [][]int64{ + {2, 20, 497, 10496}, + {5, 14, 86, 25}, + {7, 10, -19, 1}, + } + + for _, test := range tests { + fmt.Printf("Number: %d / %d in %d-adic\n", test[2], test[3], test[0]) + + squareRoot, err := NewPAdicSquareRoot(test[0], int(test[1]), test[2], test[3]) + if err != nil { + fmt.Printf("Error: %v\n\n", err) + continue + } + + fmt.Println("The two square roots are:") + fmt.Printf(" %s\n", squareRoot.String()) + fmt.Printf(" %s\n", squareRoot.Negate().String()) + + square, err := squareRoot.Multiply(squareRoot) + if err != nil { + fmt.Printf("Error calculating square: %v\n\n", err) + continue + } + + fmt.Printf("The p-adic value is %s\n", square.String()) + rational, err := square.ConvertToRational() + if err != nil { + fmt.Printf("Error converting to rational: %v\n\n", err) + continue + } + fmt.Printf("The rational value is %s\n\n", rational) + } +} diff --git a/Task/P-Adic-square-roots/JavaScript/p-adic-square-roots.js b/Task/P-Adic-square-roots/JavaScript/p-adic-square-roots.js new file mode 100644 index 0000000000..c98cbab03c --- /dev/null +++ b/Task/P-Adic-square-roots/JavaScript/p-adic-square-roots.js @@ -0,0 +1,360 @@ +// PAdicSquareRoot represents a p-adic square root number +class PAdicSquareRoot { + constructor(prime, precision, digits = [], order = 0) { + this.prime = prime; + this.precision = precision; + this.digits = digits; + this.order = order; + } + + // Clone returns a copy of the PAdicSquareRoot + clone() { + return new PAdicSquareRoot( + this.prime, + this.precision, + [...this.digits], + this.order + ); + } + + // Negate returns the additive inverse of this p-adic square root number + negate() { + if (this.digits.length === 0) { + return this.clone(); + } + + const result = this.clone(); + negateDigits(result.digits, this.prime); + return result; + } + + // Multiply returns the product of this p-adic square root number and another + multiply(other) { + if (this.prime !== other.prime) { + throw new Error("Cannot multiply p-adic's with different primes"); + } + + if (this.digits.length === 0 || other.digits.length === 0) { + return createPAdicSquareRoot(this.prime, this.precision, 0, 1); + } + + const digitsSize = this.precision + 5; + const product = multiplyDigits(this.digits, other.digits, this.prime, digitsSize); + + return new PAdicSquareRoot( + this.prime, + this.precision, + product, + this.order + other.order + ); + } + + // ConvertToRational returns a string representation of this p-adic square root as a rational number + convertToRational() { + if (this.digits.length === 0) { + return "0 / 1"; + } + + // Lagrange lattice basis reduction in two dimensions + let seriesSum = this.digits[0]; + let maximumPrime = 1n; + + for (let i = 1; i < this.precision; i++) { + maximumPrime *= BigInt(this.prime); + seriesSum += this.digits[i] * Number(maximumPrime); + } + + const one = [Number(maximumPrime), seriesSum]; + const two = [0, 1]; + + let previousNorm = seriesSum * seriesSum + 1; + let currentNorm = previousNorm + 1; + let i = 0; + let j = 1; + + while (previousNorm < currentNorm) { + const numerator = one[i] * one[j] + two[i] * two[j]; + const denominator = previousNorm; + currentNorm = Math.floor(numerator / denominator + 0.5); + one[i] -= currentNorm * one[j]; + two[i] -= currentNorm * two[j]; + + currentNorm = previousNorm; + previousNorm = one[i] * one[i] + two[i] * two[i]; + + if (previousNorm < currentNorm) { + [one[i], one[j]] = [one[j], one[i]]; + [two[i], two[j]] = [two[j], two[i]]; + } + } + + let x = one[j]; + let y = two[j]; + if (y < 0) { + y = -y; + x = -x; + } + + if (Math.abs(one[i] * y - x * two[i]) !== Number(maximumPrime)) { + throw new Error("Rational reconstruction failed"); + } + + for (let k = this.order; k < 0; k++) { + y *= this.prime; + } + + for (let k = 0; k < this.order; k++) { + x *= this.prime; + } + + return `${x} / ${y}`; + } + + // String returns a string representation of this p-adic square root + toString() { + const digits = [...this.digits]; + + // Pad with zeros if needed + while (digits.length < this.precision + 5) { + digits.push(0); + } + + let result = ""; + for (let i = digits.length - 1; i >= 0; i--) { + result += digits[i].toString(); + } + + let resultStr = result; + + if (this.order >= 0) { + for (let i = 0; i < this.order; i++) { + resultStr += "0"; + } + resultStr += ".0"; + } else { + const insertPos = resultStr.length + this.order; + if (insertPos >= 0) { + resultStr = resultStr.substring(0, insertPos) + "." + resultStr.substring(insertPos); + } else { + // If we need to insert before the start, pad with zeros + const zerosNeeded = -insertPos; + resultStr = "0." + "0".repeat(zerosNeeded) + resultStr; + } + + // Remove trailing zeros + while (resultStr.endsWith("0")) { + resultStr = resultStr.substring(0, resultStr.length - 1); + } + } + + // Return with ellipsis at the beginning + let startPos = 0; + if (resultStr.length > this.precision + 1) { + startPos = resultStr.length - this.precision - 1; + } + return " ..." + resultStr.substring(startPos); + } + + // squareRootEvenPrime creates a 2-adic number which is the square root of the rational numerator/denominator + squareRootEvenPrime(numerator, denominator) { + if (modulo(numerator * denominator, 8) !== 1) { + throw new Error("Number does not have a square root in 2-adic"); + } + + // First digit + let sum = 1; + this.digits.push(1); + + // Further digits + const digitsSize = this.precision + 5; + while (this.digits.length < digitsSize) { + const factor = denominator * sum * sum - numerator; + let valuation = 0; + let factorTemp = factor; + while (modulo(factorTemp, 2) === 0) { + factorTemp = Math.floor(factorTemp / 2); + valuation++; + } + + sum += Math.pow(2, valuation - 1); + + while (this.digits.length < valuation - 1) { + this.digits.push(0); + } + this.digits.push(1); + } + } + + // squareRootOddPrime creates a p-adic number, with an odd prime number, which is the p-adic square root + squareRootOddPrime(numerator, denominator) { + // First digit + let firstDigit = 0; + for (let i = 1; i < this.prime && firstDigit === 0; i++) { + if (modulo(denominator * i * i - numerator, this.prime) === 0) { + firstDigit = i; + } + } + + if (firstDigit === 0) { + throw new Error(`Number does not have a square root in ${this.prime}-adic`); + } + + this.digits.push(firstDigit); + + // Further digits + const coefficient = moduloInverse(modulo(2 * denominator * firstDigit, this.prime), this.prime); + let sum = firstDigit; + const digitsSize = this.precision + 5; + + for (let i = 2; i < digitsSize; i++) { + let nextSum = sum - coefficient * (denominator * sum * sum - numerator); + nextSum = modulo(nextSum, Math.pow(this.prime, i)); + nextSum -= sum; + sum += nextSum; + + const digit = Math.floor(nextSum / Math.pow(this.prime, i - 1)); + this.digits.push(digit); + } + } +} + +// createPAdicSquareRoot creates a p-adic square root number from a rational number +function createPAdicSquareRoot(prime, precision, numerator, denominator) { + if (denominator === 0) { + throw new Error("Denominator cannot be zero"); + } + + const digitsSize = precision + 5; + let order = 0; + + // Process rational zero + if (numerator === 0) { + return new PAdicSquareRoot( + prime, + precision, + Array(digitsSize).fill(0), + 1000 // orderMax + ); + } + + // Remove multiples of 'prime' and adjust the order accordingly + while (modulo(numerator, prime) === 0) { + numerator = Math.floor(numerator / prime); + order++; + } + + while (modulo(denominator, prime) === 0) { + denominator = Math.floor(denominator / prime); + order--; + } + + if ((order & 1) !== 0) { + throw new Error(`Number does not have a square root in ${prime}-adic`); + } + order >>= 1; + + const result = new PAdicSquareRoot( + prime, + precision, + [], + order + ); + + if (prime === 2) { + result.squareRootEvenPrime(numerator, denominator); + } else { + result.squareRootOddPrime(numerator, denominator); + } + + // Ensure we have the right number of digits + while (result.digits.length < digitsSize) { + result.digits.push(0); + } + if (result.digits.length > digitsSize) { + result.digits = result.digits.slice(0, digitsSize); + } + + return result; +} + +// negateDigits transforms the given vector of digits representing a p-adic number +// into a vector which represents the negation of the p-adic number +function negateDigits(numbers, prime) { + if (numbers.length > 0) { + numbers[0] = modulo(prime - numbers[0], prime); + for (let i = 1; i < numbers.length; i++) { + numbers[i] = prime - 1 - numbers[i]; + } + } +} + +// multiplyDigits returns the list obtained by multiplying the digits of the given two lists +function multiplyDigits(one, two, prime, maxSize) { + const product = Array(one.length + two.length).fill(0); + + for (let b = 0; b < two.length; b++) { + let carry = 0; + for (let a = 0; a < one.length; a++) { + product[a + b] += one[a] * two[b] + carry; + carry = Math.floor(product[a + b] / prime); + product[a + b] %= prime; + } + if (b + one.length < product.length) { + product[b + one.length] = carry; + } + } + + // Truncate to maxSize + if (product.length > maxSize) { + return product.slice(0, maxSize); + } + return product; +} + +// moduloInverse returns the multiplicative inverse of the given number modulo 'prime' +function moduloInverse(number, prime) { + let inverse = 1; + while (modulo(inverse * number, prime) !== 1) { + inverse++; + } + return inverse; +} + +// modulo returns the given number modulo 'prime' in the range 0..'prime' - 1 +function modulo(number, modulus) { + const div = number % modulus; + return div >= 0 ? div : div + modulus; +} + +// Main function +function main() { + const tests = [ + [2, 20, 497, 10496], + [5, 14, 86, 25] + // ,[7, 10, -19, 1] + ]; + + for (const test of tests) { + console.log(`Number: ${test[2]} / ${test[3]} in ${test[0]}-adic`); + + try { + const squareRoot = createPAdicSquareRoot(test[0], test[1], test[2], test[3]); + + console.log("The two square roots are:"); + console.log(` ${squareRoot.toString()}`); + console.log(` ${squareRoot.negate().toString()}`); + + const square = squareRoot.multiply(squareRoot); + console.log(`The p-adic value is ${square.toString()}`); + + const rational = square.convertToRational(); + console.log(`The rational value is ${rational}`); + } catch (error) { + console.log(`Error: ${error.message}`); + } + console.log(); + } +} + +// Run the main function +main(); diff --git a/Task/P-Adic-square-roots/Rust/p-adic-square-roots.rs b/Task/P-Adic-square-roots/Rust/p-adic-square-roots.rs new file mode 100644 index 0000000000..1c80c04b89 --- /dev/null +++ b/Task/P-Adic-square-roots/Rust/p-adic-square-roots.rs @@ -0,0 +1,381 @@ +use std::cmp::Ordering; +use std::fmt; + +#[derive(Clone)] +struct PAdicSquareRoot { + prime: u32, + precision: u32, + digits: Vec, + order: i32, +} + +impl PAdicSquareRoot { + // Create a PAdicSquareRoot number, with p = 'prime', from the given rational 'numerator' / 'denominator'. + fn new(prime: u32, precision: u32, mut numerator: i32, mut denominator: i32) -> Result { + if denominator == 0 { + return Err("Denominator cannot be zero".to_string()); + } + + let digits_size = precision + 5; + let mut order = 0; + let mut digits = vec![0; digits_size as usize]; + + // Process rational zero + if numerator == 0 { + return Ok(Self { + prime, + precision, + digits, + order: 1000, // ORDER_MAX from original code + }); + } + + // Remove multiples of 'prime' and adjust the order of the PAdicSquareRoot number accordingly + while Self::modulo(numerator as i64, prime as i64) == 0 { + numerator /= prime as i32; + order += 1; + } + + while Self::modulo(denominator as i64, prime as i64) == 0 { + denominator /= prime as i32; + order -= 1; + } + + if (order & 1) != 0 { + return Err(format!("Number does not have a square root in {}-adic", prime)); + } + order >>= 1; + + let mut result = Self { + prime, + precision, + digits: Vec::with_capacity(digits_size as usize), + order, + }; + + if prime == 2 { + result.square_root_even_prime(numerator, denominator)?; + } else { + result.square_root_odd_prime(numerator, denominator)?; + } + + // Ensure we have the right number of digits + while result.digits.len() < digits_size as usize { + result.digits.push(0); + } + result.digits.truncate(digits_size as usize); + + Ok(result) + } + + // Create a PAdicSquareRoot directly from a vector of digits + fn from_digits(prime: u32, precision: u32, digits: Vec, order: i32) -> Self { + Self { + prime, + precision, + digits, + order, + } + } + + // Return the additive inverse of this PAdicSquareRoot number + fn negate(&self) -> Self { + if self.digits.is_empty() { + return self.clone(); + } + + let mut negated = self.digits.clone(); + Self::negate_digits(&mut negated, self.prime); + + Self::from_digits(self.prime, self.precision, negated, self.order) + } + + // Return the product of this PAdicSquareRoot number and another PAdicSquareRoot number + fn multiply(&self, other: &Self) -> Result { + if self.prime != other.prime { + return Err("Cannot multiply p-adic's with different primes".to_string()); + } + + if self.digits.is_empty() || other.digits.is_empty() { + return Self::new(self.prime, self.precision, 0, 1); + } + + let product_digits = Self::multiply_digits(&self.digits, &other.digits, self.prime, (self.precision + 5) as usize); + Ok(Self::from_digits( + self.prime, + self.precision, + product_digits, + self.order + other.order, + )) + } + + // Return a string representation of this PAdicSquareRoot as a rational number + fn convert_to_rational(&self) -> Result { + if self.digits.is_empty() { + return Ok("0 / 1".to_string()); + } + + // Lagrange lattice basis reduction in two dimensions + let mut series_sum: i64 = self.digits[0] as i64; + let mut maximum_prime: i64 = 1; + + for i in 1..self.precision { + maximum_prime *= self.prime as i64; + series_sum += (self.digits[i as usize] as i64) * maximum_prime; + } + + let mut one = vec![maximum_prime, series_sum]; + let mut two = vec![0, 1]; + + let mut previous_norm = series_sum * series_sum + 1; + let mut current_norm = previous_norm + 1; + let mut i = 0; + let mut j = 1; + + while previous_norm < current_norm { + let numerator = one[i] * one[j] + two[i] * two[j]; + let denominator = previous_norm; + current_norm = ((numerator as f64) / (denominator as f64) + 0.5).floor() as i64; + one[i] -= current_norm * one[j]; + two[i] -= current_norm * two[j]; + + current_norm = previous_norm; + previous_norm = one[i] * one[i] + two[i] * two[i]; + + if previous_norm < current_norm { + std::mem::swap(&mut i, &mut j); + } + } + + let mut x = one[j]; + let mut y = two[j]; + if y < 0 { + y = -y; + x = -x; + } + + if (one[i] * y - x * two[i]).abs() != maximum_prime { + return Err("Rational reconstruction failed.".to_string()); + } + + for _ in self.order..0 { + y *= self.prime as i64; + } + + for _ in 0..self.order { + x *= self.prime as i64; + } + + Ok(format!("{} / {}", x, y)) + } + + // Create a 2-adic number which is the square root of the rational 'numerator' / 'denominator' + fn square_root_even_prime(&mut self, numerator: i32, denominator: i32) -> Result<(), String> { + if Self::modulo((numerator as i64) * (denominator as i64), 8) != 1 { + return Err("Number does not have a square root in 2-adic".to_string()); + } + + // First digit + let mut sum: i64 = 1; + self.digits.push(1); + + // Further digits + let digits_size = self.precision + 5; + while self.digits.len() < digits_size as usize { + let factor = (denominator as i64) * sum * sum - (numerator as i64); + let mut valuation = 0; + let mut factor_temp = factor; + while Self::modulo(factor_temp, 2) == 0 { + factor_temp /= 2; + valuation += 1; + } + + sum += 2i64.pow(valuation - 1); + + while self.digits.len() < (valuation - 1) as usize { + self.digits.push(0); + } + self.digits.push(1); + } + + Ok(()) + } + + // Create a p-adic number, with an odd prime number, p = 'prime', + // which is the p-adic square root of the given rational 'numerator' / 'denominator' + fn square_root_odd_prime(&mut self, numerator: i32, denominator: i32) -> Result<(), String> { + // First digit + let mut first_digit = 0; + for i in 1..self.prime { + if Self::modulo( + (denominator as i64) * (i as i64) * (i as i64) - (numerator as i64), + self.prime as i64, + ) == 0 + { + first_digit = i; + break; + } + } + + if first_digit == 0 { + return Err(format!( + "Number does not have a square root in {}-adic", + self.prime + )); + } + + self.digits.push(first_digit); + + // Further digits + let coefficient = Self::modulo_inverse( + Self::modulo(2 * (denominator as i64) * (first_digit as i64), self.prime as i64) as u32, + self.prime, + ); + + let mut sum: i64 = first_digit as i64; + let digits_size = self.precision + 5; + + for i in 2..digits_size { + let mut next_sum = sum - ((coefficient as i64) * ((denominator as i64) * sum * sum - (numerator as i64))); + next_sum = Self::modulo(next_sum, (self.prime as i64).pow(i)); + next_sum -= sum; + sum += next_sum; + + let digit = (next_sum / (self.prime as i64).pow(i - 1)) as u32; + self.digits.push(digit); + } + + Ok(()) + } + + // Transform the given vector of digits representing a p-adic number + // into a vector which represents the negation of the p-adic number + fn negate_digits(numbers: &mut Vec, prime: u32) { + if !numbers.is_empty() { + numbers[0] = Self::modulo(prime as i64 - numbers[0] as i64, prime as i64) as u32; + for i in 1..numbers.len() { + numbers[i] = prime - 1 - numbers[i]; + } + } + } + + // Return the list obtained by multiplying the digits of the given two lists + fn multiply_digits(one: &[u32], two: &[u32], prime: u32, max_size: usize) -> Vec { + let mut product = vec![0; one.len() + two.len()]; + + for b in 0..two.len() { + let mut carry = 0; + for a in 0..one.len() { + product[a + b] += one[a] * two[b] + carry; + carry = product[a + b] / prime; + product[a + b] %= prime; + } + if b + one.len() < product.len() { + product[b + one.len()] = carry; + } + } + + // Truncate to max_size + product.truncate(max_size); + product + } + + // Return the multiplicative inverse of the given number modulo 'prime' + fn modulo_inverse(number: u32, prime: u32) -> u32 { + let mut inverse: u32 = 1; + while Self::modulo((inverse as i64) * (number as i64), prime as i64) != 1 { + inverse += 1; + } + inverse + } + + // Return the given number modulo 'prime' in the range 0..'prime' - 1 + fn modulo(number: i64, modulus: i64) -> i64 { + let div = number % modulus; + if div >= 0 { + div + } else { + div + modulus + } + } + + // Generate string representation of this PAdicSquareRoot + fn to_string(&self) -> String { + let mut numbers = self.digits.clone(); + + // Ensure we have the right number of digits + while numbers.len() < (self.precision + 5) as usize { + numbers.push(0); + } + + let mut result = String::new(); + for i in (0..numbers.len()).rev() { + result.push_str(&numbers[i].to_string()); + } + + if self.order >= 0 { + for _ in 0..self.order { + result.push('0'); + } + result.push_str(".0"); + } else { + let insert_pos = result.len() as i32 + self.order; + if insert_pos >= 0 { + result.insert(insert_pos as usize, '.'); + } else { + // If we need to insert before the start, pad with zeros + let zeros_needed = -insert_pos; + result = "0.".to_string() + &"0".repeat(zeros_needed as usize) + &result; + } + + // Remove trailing zeros + while result.ends_with('0') { + result.pop(); + } + } + + // Return with ellipsis at the beginning + let start_pos = if result.len() > self.precision as usize + 1 { + result.len() - self.precision as usize - 1 + } else { + 0 + }; + format!(" ...{}", &result[start_pos..]) + } +} + +fn main() { + let tests = vec![ + vec![2, 20, 497, 10496], + vec![5, 14, 86, 25], + vec![7, 10, -19, 1], + ]; + + for test in tests { + println!( + "Number: {} / {} in {}-adic", + test[2], test[3], test[0] + ); + + match PAdicSquareRoot::new(test[0] as u32, test[1] as u32, test[2], test[3]) { + Ok(square_root) => { + println!("The two square roots are:"); + println!(" {}", square_root.to_string()); + println!(" {}", square_root.negate().to_string()); + + match square_root.multiply(&square_root) { + Ok(square) => { + println!("The p-adic value is {}", square.to_string()); + match square.convert_to_rational() { + Ok(rational) => println!("The rational value is {}", rational), + Err(e) => println!("Error converting to rational: {}", e), + } + }, + Err(e) => println!("Error calculating square: {}", e), + } + }, + Err(e) => println!("Error: {}", e), + } + println!(); + } +} diff --git a/Task/P-Adic-square-roots/Zig/p-adic-square-roots.zig b/Task/P-Adic-square-roots/Zig/p-adic-square-roots.zig new file mode 100644 index 0000000000..0b7343aba7 --- /dev/null +++ b/Task/P-Adic-square-roots/Zig/p-adic-square-roots.zig @@ -0,0 +1,495 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; + +const PAdicSquareRoot = struct { + prime: u32, + precision: u32, + digits: ArrayList(u32), + order: i32, + allocator: Allocator, + + // Create a PAdicSquareRoot number + pub fn new(allocator: Allocator, prime: u32, precision: u32, numerator: i32, denominator: i32) !*PAdicSquareRoot { + if (denominator == 0) { + return error.DenominatorCannotBeZero; + } + + const digits_size = precision + 5; + var self = try allocator.create(PAdicSquareRoot); + self.* = PAdicSquareRoot{ + .prime = prime, + .precision = precision, + .digits = ArrayList(u32).init(allocator), + .order = 0, + .allocator = allocator, + }; + + // Process rational zero + if (numerator == 0) { + self.order = 1000; // ORDER_MAX from original code + return self; + } + + // Handle numerator and denominator + var num = numerator; + var denom = denominator; + + // Remove multiples of 'prime' and adjust the order accordingly + while (modulo(@as(i64, num), @as(i64, prime)) == 0) { + num = @divTrunc(num, @as(i32, @intCast(prime))); + self.order += 1; + } + + while (modulo(@as(i64, denom), @as(i64, prime)) == 0) { + denom = @divTrunc(denom, @as(i32, @intCast(prime))); + self.order -= 1; + } + + if ((self.order & 1) != 0) { + self.deinit(); + allocator.destroy(self); + return error.NoSquareRoot; + } + self.order >>= 1; + + // Calculate square root based on prime + if (prime == 2) { + try self.squareRootEvenPrime(num, denom); + } else { + try self.squareRootOddPrime(num, denom); + } + + // Ensure we have the right number of digits + while (self.digits.items.len < digits_size) { + try self.digits.append(0); + } + self.digits.shrinkRetainingCapacity(digits_size); + + return self; + } + + // Create a PAdicSquareRoot directly from a vector of digits + pub fn fromDigits(allocator: Allocator, prime: u32, precision: u32, digits: []const u32, order: i32) !*PAdicSquareRoot { + var self = try allocator.create(PAdicSquareRoot); + self.* = PAdicSquareRoot{ + .prime = prime, + .precision = precision, + .digits = ArrayList(u32).init(allocator), + .order = order, + .allocator = allocator, + }; + + try self.digits.appendSlice(digits); + return self; + } + + // Clean up allocated memory + pub fn deinit(self: *PAdicSquareRoot) void { + self.digits.deinit(); + } + + // Return the additive inverse of this PAdicSquareRoot number + pub fn negate(self: *const PAdicSquareRoot) !*PAdicSquareRoot { + if (self.digits.items.len == 0) { + return self.clone(); + } + + var negated = try ArrayList(u32).initCapacity(self.allocator, self.digits.items.len); + try negated.appendSlice(self.digits.items); + negateDigits(negated.items, self.prime); + + return fromDigits(self.allocator, self.prime, self.precision, negated.items, self.order); + } + + // Return a clone of this PAdicSquareRoot + pub fn clone(self: *const PAdicSquareRoot) !*PAdicSquareRoot { + var new_digits = try ArrayList(u32).initCapacity(self.allocator, self.digits.items.len); + try new_digits.appendSlice(self.digits.items); + + const result = try self.allocator.create(PAdicSquareRoot); + result.* = PAdicSquareRoot{ + .prime = self.prime, + .precision = self.precision, + .digits = new_digits, + .order = self.order, + .allocator = self.allocator, + }; + return result; + } + + // Return the product of this PAdicSquareRoot number and another PAdicSquareRoot number + pub fn multiply(self: *const PAdicSquareRoot, other: *const PAdicSquareRoot) !*PAdicSquareRoot { + if (self.prime != other.prime) { + return error.DifferentPrimes; + } + + if (self.digits.items.len == 0 or other.digits.items.len == 0) { + return new(self.allocator, self.prime, self.precision, 0, 1); + } + + const max_size = @as(usize, @intCast(self.precision + 5)); + const product_digits = try multiplyDigits( + self.allocator, + self.digits.items, + other.digits.items, + self.prime, + max_size + ); + + return fromDigits( + self.allocator, + self.prime, + self.precision, + product_digits.items, + self.order + other.order, + ); + } + + // Return a string representation of this PAdicSquareRoot as a rational number + pub fn convertToRational(self: *const PAdicSquareRoot, allocator: Allocator) ![]u8 { + if (self.digits.items.len == 0) { + return try std.fmt.allocPrint(allocator, "0 / 1", .{}); + } + + // Lagrange lattice basis reduction in two dimensions + var series_sum: i64 = @as(i64, self.digits.items[0]); + var maximum_prime: i64 = 1; + + var i: u32 = 1; + while (i < self.precision) : (i += 1) { + maximum_prime *= @as(i64, self.prime); + series_sum += @as(i64, self.digits.items[i]) * maximum_prime; + } + + var one = [_]i64{ maximum_prime, series_sum }; + var two = [_]i64{ 0, 1 }; + + var previous_norm = series_sum * series_sum + 1; + var current_norm = previous_norm + 1; + var idx_i: usize = 0; + var idx_j: usize = 1; + + while (previous_norm < current_norm) { + const numerator = one[idx_i] * one[idx_j] + two[idx_i] * two[idx_j]; + const denominator = previous_norm; + current_norm = @as(i64, @intFromFloat(@floor(@as(f64, @floatFromInt(numerator)) / @as(f64, @floatFromInt(denominator)) + 0.5))); + one[idx_i] -= current_norm * one[idx_j]; + two[idx_i] -= current_norm * two[idx_j]; + + current_norm = previous_norm; + previous_norm = one[idx_i] * one[idx_i] + two[idx_i] * two[idx_i]; + + if (previous_norm < current_norm) { + const temp = idx_i; + idx_i = idx_j; + idx_j = temp; + } + } + + var x = one[idx_j]; + var y = two[idx_j]; + if (y < 0) { + y = -y; + x = -x; + } + + if ( @abs(one[idx_i] * y - x * two[idx_i]) != maximum_prime) { + return error.RationalReconstructionFailed; + } + + var i_order = self.order; + while (i_order < 0) : (i_order += 1) { + y *= @as(i64, self.prime); + } + + i_order = 0; + while (i_order < self.order) : (i_order += 1) { + x *= @as(i64, self.prime); + } + + return try std.fmt.allocPrint(allocator, "{} / {}", .{ x, y }); + } + + // Create a 2-adic number which is the square root of the rational 'numerator' / 'denominator' + fn squareRootEvenPrime(self: *PAdicSquareRoot, numerator: i32, denominator: i32) !void { + if (modulo(@as(i64, numerator) * @as(i64, denominator), 8) != 1) { + return error.NoSquareRootInTwoAdic; + } + + // First digit + var sum: i64 = 1; + try self.digits.append(1); + + // Further digits + const digits_size = self.precision + 5; + while (self.digits.items.len < digits_size) { + const factor = @as(i64, denominator) * sum * sum - @as(i64, numerator); + var valuation: u32 = 0; + var factor_temp = factor; + while (modulo(factor_temp, 2) == 0) { + factor_temp = @divTrunc(factor_temp, 2); + valuation += 1; + } + + sum += std.math.pow(i64, 2, valuation - 1); + + while (self.digits.items.len < valuation - 1) { + try self.digits.append(0); + } + try self.digits.append(1); + } + } + + // Create a p-adic number, with an odd prime number, p = 'prime', + // which is the p-adic square root of the given rational 'numerator' / 'denominator' + fn squareRootOddPrime(self: *PAdicSquareRoot, numerator: i32, denominator: i32) !void { + // First digit + var first_digit: u32 = 0; + var i: u32 = 1; + while (i < self.prime) : (i += 1) { + if (modulo( + @as(i64, denominator) * @as(i64, i) * @as(i64, i) - @as(i64, numerator), + @as(i64, self.prime) + ) == 0) { + first_digit = i; + break; + } + } + + if (first_digit == 0) { + return error.NoSquareRoot; + } + + try self.digits.append(first_digit); + + // Further digits + const coefficient = moduloInverse( + @intCast(modulo(2 * @as(i64, denominator) * @as(i64, first_digit), @as(i64, self.prime))), + self.prime + ); + + var sum: i64 = @as(i64, first_digit); + const digits_size = self.precision + 5; + + var i_digit: u32 = 2; + while (i_digit < digits_size) : (i_digit += 1) { + // FIXED: Break down calculation into smaller operations to avoid overflow + const denom_sum = @as(i128, @as(i128, denominator)) * @as(i128, sum); + const denom_sum_squared = denom_sum * @as(i128, sum); + const subtraction = denom_sum_squared - @as(i128, numerator); + const coef_mul = @as(i128, coefficient) * subtraction; + + var next_sum = @as(i128, sum) - coef_mul; + + // Use modulo with appropriate type + const pow_prime = std.math.pow(i128, @as(i128, self.prime), @as(i128, i_digit)); + next_sum = @intCast(modulo128(next_sum, pow_prime)); + next_sum -= @as(i128, sum); + sum = @intCast(next_sum + @as(i128, sum)); + + // Calculate power for digit extraction + const pow_prime_prev = std.math.pow(i128, @as(i128, self.prime), @as(i128, i_digit - 1)); + const digit = @as(u32, @intCast(@divTrunc(next_sum, pow_prime_prev))); + try self.digits.append(digit); + } + } + + // Generate string representation of this PAdicSquareRoot + pub fn toString(self: *const PAdicSquareRoot, allocator: Allocator) ![]u8 { + var numbers = try ArrayList(u32).initCapacity(allocator, self.digits.items.len); + try numbers.appendSlice(self.digits.items); + + // Ensure we have the right number of digits + while (numbers.items.len < self.precision + 5) { + try numbers.append(0); + } + + var result = ArrayList(u8).init(allocator); + errdefer result.deinit(); + + var i: isize = @as(isize, @intCast(numbers.items.len)) - 1; + while (i >= 0) : (i -= 1) { + const digit_str = try std.fmt.allocPrint(allocator, "{}", .{numbers.items[@intCast(i)]}); + defer allocator.free(digit_str); + try result.appendSlice(digit_str); + } + + if (self.order >= 0) { + var j: i32 = 0; + while (j < self.order) : (j += 1) { + try result.append('0'); + } + try result.appendSlice(".0"); + } else { + const insert_pos = @as(i32, @intCast(result.items.len)) + self.order; + if (insert_pos >= 0) { + try result.insertSlice(@intCast(insert_pos), "."); + } else { + // If we need to insert before the start, pad with zeros + const zeros_needed = -insert_pos; + var new_result = try ArrayList(u8).initCapacity(allocator, result.items.len + @as(usize, @intCast(zeros_needed) ) + 2); + try new_result.appendSlice("0."); + var j: i32 = 0; + while (j < zeros_needed) : (j += 1) { + try new_result.append('0'); + } + try new_result.appendSlice(result.items); + result.deinit(); + result = new_result; + } + + // Remove trailing zeros + while (result.items.len > 0 and result.items[result.items.len - 1] == '0') { + _ = result.pop(); + } + } + + // Return with ellipsis at the beginning + const start_pos = if (result.items.len > self.precision + 1) + result.items.len - self.precision - 1 + else + 0; + + const final_result = try std.fmt.allocPrint(allocator, " ...{s}", .{result.items[start_pos..]}); + result.deinit(); + return final_result; + } +}; + +// Transform the given vector of digits representing a p-adic number +// into a vector which represents the negation of the p-adic number +fn negateDigits(numbers: []u32, prime: u32) void { + if (numbers.len == 0) return; + + numbers[0] = @intCast(modulo(@as(i64, prime) - @as(i64, numbers[0]), @as(i64, prime))); + var i: usize = 1; + while (i < numbers.len) : (i += 1) { + numbers[i] = prime - 1 - numbers[i]; + } +} + +// Return the list obtained by multiplying the digits of the given two lists +fn multiplyDigits( + allocator: Allocator, + one: []const u32, + two: []const u32, + prime: u32, + max_size: usize +) !ArrayList(u32) { + var product = try ArrayList(u32).initCapacity(allocator, one.len + two.len); + var i: usize = 0; + while (i < one.len + two.len) : (i += 1) { + try product.append(0); + } + + var b: usize = 0; + while (b < two.len) : (b += 1) { + var carry: u32 = 0; + var a: usize = 0; + while (a < one.len) : (a += 1) { + product.items[a + b] += one[a] * two[b] + carry; + carry = product.items[a + b] / prime; + product.items[a + b] %= prime; + } + if (b + one.len < product.items.len) { + product.items[b + one.len] = carry; + } + } + + // Truncate to max_size + if (product.items.len > max_size) { + product.shrinkRetainingCapacity(max_size); + } + + return product; +} + +// Return the multiplicative inverse of the given number modulo 'prime' +fn moduloInverse(number: u32, prime: u32) u32 { + var inverse: u32 = 1; + while (modulo(@as(i64, inverse) * @as(i64, number), @as(i64, prime)) != 1) { + inverse += 1; + } + return inverse; +} + +// Return the given number modulo 'prime' in the range 0..'prime' - 1 +fn modulo(number: i64, modulus: i64) i64 { + const div = @mod(number, modulus); + return if (div >= 0) div else div + modulus; +} + +// Added for i128 support +fn modulo128(number: i128, modulus: i128) i128 { + const div = @mod(number, modulus); + return if (div >= 0) div else div + modulus; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + const tests = [_][4]i32{ + [_]i32{ 2, 20, 497, 10496 }, + [_]i32{ 5, 14, 86, 25 }, + [_]i32{ 7, 10, -19, 1 }, + }; + + for (tests) |my_test| { + const stdout = std.io.getStdOut().writer(); + try stdout.print("Number: {} / {} in {}-adic\n", .{ my_test[2], my_test[3], my_test[0] }); + + var square_root = PAdicSquareRoot.new( + allocator, + @intCast(my_test[0]), + @intCast(my_test[1]), + my_test[2], + my_test[3] + ) catch |err| { + try stdout.print("Error: {}\n\n", .{err}); + continue; + }; + defer { + square_root.deinit(); + allocator.destroy(square_root); + } + + try stdout.print("The two square roots are:\n", .{}); + + const sr_string = try square_root.toString(allocator); + defer allocator.free(sr_string); + try stdout.print(" {s}\n", .{sr_string}); + + var negated = try square_root.negate(); + defer { + negated.deinit(); + allocator.destroy(negated); + } + + const neg_string = try negated.toString(allocator); + defer allocator.free(neg_string); + try stdout.print(" {s}\n", .{neg_string}); + + var square = square_root.multiply(square_root) catch |err| { + try stdout.print("Error calculating square: {}\n\n", .{err}); + continue; + }; + defer { + square.deinit(); + allocator.destroy(square); + } + + const square_string = try square.toString(allocator); + defer allocator.free(square_string); + try stdout.print("The p-adic value is {s}\n", .{square_string}); + + const rational = square.convertToRational(allocator) catch |err| { + try stdout.print("Error converting to rational: {}\n\n", .{err}); + continue; + }; + defer allocator.free(rational); + try stdout.print("The rational value is {s}\n\n", .{rational}); + } +} diff --git a/Task/Padovan-n-step-number-sequences/EasyLang/padovan-n-step-number-sequences.easy b/Task/Padovan-n-step-number-sequences/EasyLang/padovan-n-step-number-sequences.easy index 81f4aba3ea..91ab1d2b01 100644 --- a/Task/Padovan-n-step-number-sequences/EasyLang/padovan-n-step-number-sequences.easy +++ b/Task/Padovan-n-step-number-sequences/EasyLang/padovan-n-step-number-sequences.easy @@ -1,11 +1,9 @@ t = 15 len p[] t # -proc padovan n . . +proc padovan n . if n < 2 or t < 3 - for i = 1 to t - p[i] = 1 - . + for i = 1 to t : p[i] = 1 return . padovan n - 1 @@ -19,8 +17,6 @@ proc padovan n . . for n = 2 to 8 padovan n write n & ": " - for i = 1 to t - write p[i] & " " - . + for i = 1 to t : write p[i] & " " print "" . diff --git a/Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas b/Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas new file mode 100644 index 0000000000..46d45d200b --- /dev/null +++ b/Task/Pancake-numbers/PascalABC.NET/pancake-numbers.pas @@ -0,0 +1,37 @@ +function pancake(n: integer): (integer, string); +begin + var goalstack := '123456789abcd'[:n + 1]; + var stacks := Dict((goalstack, 0)); + var newstacks := Dict((goalstack, 0)); + var numstacks := 1; + foreach var flip in 1..100 do + begin + var nextstacks := new Dictionary; + foreach var nstack in newstacks do + foreach var pos in 2..n do + begin + var newstack := nstack.key[pos::-1] + nstack.key?[pos + 1:]; + if newstack not in stacks then + nextstacks[newstack] := flip; + end; + newstacks := nextstacks; + foreach var nstack in newstacks do stacks[nstack.key] := nstack.value; + var perms := stacks.Count; + if perms = numstacks then + begin + result := stacks.Where(x -> x.value = flip - 1) + .Select(k -> (k.value, k.key)) + .First; + exit + end; + numstacks := perms + end; +end; + +begin + foreach var n in 1..11 do + begin + var (steps, example) := pancake(n); + writeln('pancake(', n:2, ') = ', steps:2, ' example: ', example); + end; +end. diff --git a/Task/Pangram-checker/PascalABC.NET/pangram-checker.pas b/Task/Pangram-checker/PascalABC.NET/pangram-checker.pas new file mode 100644 index 0000000000..5c62d5f862 --- /dev/null +++ b/Task/Pangram-checker/PascalABC.NET/pangram-checker.pas @@ -0,0 +1,8 @@ +const + alphabet = 'abcdefghijklmnopqrstuvwxyz'; + +function ispangram(text: string) := alphabet.All(c -> text.Contains(c)); + +begin + ispangram('The quick brown fox jumps over the lazy dog').Println; +end. diff --git a/Task/Pangram-checker/Uiua/pangram-checker.uiua b/Task/Pangram-checker/Uiua/pangram-checker.uiua new file mode 100644 index 0000000000..9c9d2ae82d --- /dev/null +++ b/Task/Pangram-checker/Uiua/pangram-checker.uiua @@ -0,0 +1,8 @@ +IsPangram ← /ט∊+@A⇡26⌵ + +┌─╴test + ⍤⤙≍ 1 IsPangram "The quick brown fox jumps over the lazy dog." + ⍤⤙≍ 1 IsPangram "QwErTyUiOp-AsDfGhJkL-zXcVbNm" + ⍤⤙≍ 0 IsPangram "The quick brown fox jumped over the lazy dog." + ⍤⤙≍ 0 IsPangram "This is a sentence." +└─╴ diff --git a/Task/Paraffins/PascalABC.NET/paraffins.pas b/Task/Paraffins/PascalABC.NET/paraffins.pas new file mode 100644 index 0000000000..7661591095 --- /dev/null +++ b/Task/Paraffins/PascalABC.NET/paraffins.pas @@ -0,0 +1,50 @@ +const + nMax = 250; + nBranches = 4; + +var + rooted := (0..nMax).Select(n -> 0bi).ToArray; + unrooted := (0..nMax).Select(n -> 0bi).ToArray; + +function choose(m: biginteger; k: integer): biginteger; +begin + result := m; + if k = 1 then exit + else + for var i := 1 to k - 1 do + result := result * (m + i) div (i + 1) +end; + +procedure tree(br, n, l, sum: integer; cnt: biginteger); +begin + var s := 0; + foreach var b in (br + 1.. nBranches) do + begin + s := sum + (b - br) * n; + if s > nMax then exit; + + var c := choose(rooted[n], b - br) * cnt; + + if l * 2 < s then unrooted[s] += c; + if b = nBranches then exit; + rooted[s] += c; + for var m := n - 1 downto 1 do + tree(b, m, l, s, c); + end; +end; + +procedure bicenter(s: integer); +begin + if (s and 1) = 0 then + unrooted[s] += rooted[s div 2] * (rooted[s div 2] + 1) div 2; +end; + +begin + (rooted[0], rooted[1], unrooted[0], unrooted[1]) := (1bi, 1bi, 1bi, 1bi); + for var n := 1 to nMax do + begin + tree(0, n, n, 1, 1bi); + bicenter(n); + writeln(n, ': ', unrooted[n]); + end; +end. diff --git a/Task/Parallel-calculations/PascalABC.NET/parallel-calculations.pas b/Task/Parallel-calculations/PascalABC.NET/parallel-calculations.pas new file mode 100644 index 0000000000..c43295f6ae --- /dev/null +++ b/Task/Parallel-calculations/PascalABC.NET/parallel-calculations.pas @@ -0,0 +1,24 @@ +uses school; + +const + n = |12757923, 12878611, 12757923, 15808973, 15780709, 197622519|; + +begin + var j := 0; + var m := 0; + var l := new list[n.Length]; + {$omp parallel for} + for var i := 0 to n.Length - 1 do + l[i] := primefactors(n[i]); + + for var i := 0 to n.Length - 1 do + if l[i].Min > m then + begin + m := l[i].Min; + j := i; + end; + + WriteLn('Number ', n[j], ' has largest minimal factor:'); + foreach var list in l[j] do + Write(' ' + list); +end. diff --git a/Task/Parametric-polymorphism/00-TASK.txt b/Task/Parametric-polymorphism/00-TASK.txt index 9924d41a1d..c12cb103a1 100644 --- a/Task/Parametric-polymorphism/00-TASK.txt +++ b/Task/Parametric-polymorphism/00-TASK.txt @@ -1,4 +1,4 @@ -[[wp:Parametric Polymorphism|Parametric Polymorphism]] is a way to define types or functions that are generic over other types. The genericity can be expressed by using ''type variables'' for the parameter type, and by a mechanism to explicitly or implicitly replace the type variables with concrete types when necessary. +[[wp:Parametric polymorphism|Parametric polymorphism]] is a way to define types or functions that are generic over other types. The genericity can be expressed by using ''type variables'' for the parameter type, and by a mechanism to explicitly or implicitly replace the type variables with concrete types when necessary. ;Task: diff --git a/Task/Parametric-polymorphism/C3/parametric-polymorphism-1.c3 b/Task/Parametric-polymorphism/C3/parametric-polymorphism-1.c3 index 73092184fd..86363c0951 100644 --- a/Task/Parametric-polymorphism/C3/parametric-polymorphism-1.c3 +++ b/Task/Parametric-polymorphism/C3/parametric-polymorphism-1.c3 @@ -1,4 +1,4 @@ -module tree(); +module tree {Type}; struct Tree { diff --git a/Task/Parametric-polymorphism/C3/parametric-polymorphism-2.c3 b/Task/Parametric-polymorphism/C3/parametric-polymorphism-2.c3 index bf7a6c9501..f9dac4f3bd 100644 --- a/Task/Parametric-polymorphism/C3/parametric-polymorphism-2.c3 +++ b/Task/Parametric-polymorphism/C3/parametric-polymorphism-2.c3 @@ -2,6 +2,6 @@ import tree; fn void test() { - Tree() inttree; + Tree {int} inttree; inttree.replace_all(3); } diff --git a/Task/Parse-an-IP-Address/Erlang/parse-an-ip-address.erl b/Task/Parse-an-IP-Address/Erlang/parse-an-ip-address.erl new file mode 100644 index 0000000000..454b25b2d1 --- /dev/null +++ b/Task/Parse-an-IP-Address/Erlang/parse-an-ip-address.erl @@ -0,0 +1,53 @@ +#!/usr/bin/env escript +-module(ipparse). + +-export([main/1]). + +main([]) -> + [print(A, parse(A)) || A <- data()], + erlang:halt(0); +main(Args) -> + [print(A, parse(A)) || A <- Args], + erlang:halt(0). + +-spec parse(Input :: string()) -> + {Family :: 'IPv6' | 'IPv4', Hex :: binary(), Port :: string()} | + {Family :: 'IPv6' | 'IPv4', Hex :: binary()}. +parse([$[ | Addr0]) -> + case string:split(Addr0, "]", trailing) of + [Addr] -> + {"IPv6", to_hex(inet:parse_address(Addr))}; + [Addr, [$: | Port]] -> + {"IPv6", to_hex(inet:parse_address(Addr)), Port} + end; +parse(Addr0) -> + case inet:parse_address(Addr0) of + {error, einval} -> + [Addr, Port] = string:split(Addr0, ":", trailing), + {"IPv4", to_hex(inet:parse_address(Addr)), Port}; + {ok, V6Addr} -> + {"IPv6", to_hex({ok, V6Addr})} + end. + +-spec to_hex({ok, inet:ip_address()}) -> Hex :: binary(). +to_hex({ok, {A,B,C,D}}) -> + binary:encode_hex(<>); +to_hex({ok, {A,B,C,D,E,F,G,H}}) -> + binary:encode_hex(<>). + +print(Input, {Family, Hex, Port}) -> + io:format("Input: ~s~nFamily: ~s~nHex: ~s~nPort: ~s~n~n", + [Input, Family, Hex, Port]); +print(Input, {Family, Hex}) -> + io:format("Input: ~s~nFamily: ~s~nHex: ~s~n~n", + [Input, Family, Hex]). + +data() -> + ["127.0.0.1", + "127.0.0.1:80", + "::ffff:127.0.0.1", + "::1", + "[::1]:80", + "1::80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80"]. diff --git a/Task/Parse-an-IP-Address/Lua/parse-an-ip-address-1.lua b/Task/Parse-an-IP-Address/Lua/parse-an-ip-address-1.lua new file mode 100644 index 0000000000..5c87c4d6e6 --- /dev/null +++ b/Task/Parse-an-IP-Address/Lua/parse-an-ip-address-1.lua @@ -0,0 +1,158 @@ +local Format = string.format +local tonumber = tonumber +local ipairs = ipairs +local Rep = string.rep + +-- there is no | so this is the best we can do in pure lua patt +local ipv4_addr_patt = "[12]?%d?%d%.[12]?%d?%d%.[12]?%d?%d%.[12]?%d?%d" +local ipv4_patt = "^(" .. ipv4_addr_patt .. "):?(%d*)$" + +-- ipv4 -> addr?, port? +local V4Parse = function (ipv4) + local addr, port = ipv4:match(ipv4_patt) + if addr then + for digitS in addr:gmatch"%d+" do + if tonumber(digitS)>255 then return nil end + end + end + return addr, port +end + +-- no check +local V4ToHex = function (ipv4_addr) + local hex = Format( + "%.2x%.2x%.2x%.2x" + , ipv4_addr:match"^(%d+)%.(%d+)%.(%d+)%.(%d+)$" + ) + return hex, tonumber("0x" .. hex) +end + +-- ipv4_address -> addr?, port?, hex? +local V4 = function (ipv4) -- "address:port" -> address:str|nil, port:str|nil, hex:str|nil + local addr, port = V4Parse(ipv4) + if addr then + return addr, port, V4ToHex(addr) + end + return nil +end + +--------------------------------- IPV6 Section +local ipv6_patternsT do + local v6 = "([%x:]*:[%x:]*:[%x:]*)" + local v64 = "([%x:]*:[%x:]*:" .. ipv4_addr_patt .. ")" + + ipv6_patternsT = { -- these are guessers/approximators + -- [addr] + "^%[" .. v6 .. "%]:(%d+)$" -- [v6]:port + ,"^%[" .. v6 .. "%]$" -- [v6] + ,"^%[" .. v64 .. "%]:(%d+)$" -- [v6+v4]:port + ,"^%[" .. v64 .. "%]$" -- [v6+v4] + + -- guesswork + ,"^" .. v64 .. ":(%d+)$" -- v6+v4+port + -- TODO: unsure if v6+v4[#p:.]port is valid + + ,"^(" .. v64 .. ")$" -- v6+v4 + + ,"^" .. v6 .. "[.p#](%d+)$" -- v6+port + -- portsep=":" handled bellow + -- There is no way to use port while using : as the port separator + -- the only method is if its complete or if its :::80 + , "^([%x:]*::):(%d+)$" -- v6+port + -- Complete + ,"^(" .. ("%x*:"):rep(7) .. "%x*):(%d+)$" -- v6+port + + ,"^" .. v6 .. "$" -- v6 + } +end + +-- addr, port -- nil if failure +-- addr will be returned as +-- ipv6_address port -> address, port, mini hexified address (no ipv4) +local V6Parse = function (ipv6_address) + -- get the port, then get the ip via position + for _,match in ipairs(ipv6_patternsT) do + local address, port = ipv6_address:match(match) + if address then + local addr = address -- addr is going to be in ipv6 hex (no ipv4) + if -- valid ipv6 address? +-- select(2, addr:gsub(":",""))==1 -- this shouldn't happen + -- 2 :: + addr:match"::.+::" + -- 3 ::: + or addr:match":::" + -- 4 %x per non [^:] ONLY + or addr:match"%x%x%x%x%x" + then + return nil + end + local v6,v4 = addr:match("^([%x:]+:)(%d+%.%d+%.%d+%.%d+)$") + if v4 and V4Parse(v4) then + addr = Format("%s%s:%s", v6, V4ToHex(v4):match"^(....)(....)$") + end + if addr:gsub(":", "", 7):match":" then return nil end + return address, port, addr + end + end + return nil, nil +end + +-- Returns ipv6 address filled (0:0:0:0:0) instead of :: +local V6Fill = function (addr) -- addr must be hexified +-- fill :: + if addr:match"::" then + local _, count = addr:gsub(":+","") + addr = addr:gsub("::" + ,(addr:match"^::" and "0000:" or ":") + .. Rep("0", 8-count,":") + ,1 + ) + end + +-- fill 0 + addr = addr:gsub("[^:]+" + ,function (section) + return Format("%.4x",tonumber("0x" .. section)) + end + ) + + return addr +end + +-- cannot return num after fff:ffff:ffff:ffff +-- this is dependant on tonumber() itself +local V6ToHex = function (addr) + local ipv6 = V6Fill(addr) + local hex = ipv6:gsub(":","") + local num do -- tonumber fails after 3: + local x = hex:gsub("^0+", "") + if #x<=15 then + num = x=="" and 0 or tonumber("0x" .. x) + end + end + return hex, num or -1, ipv6 -- cannot tonumber hex too big +end + +-- ipv6_address -> addr?, port?, hex? +local V6 = function (address) + local addr, port, ipv6 = V6Parse(address) + if addr then + return addr, port, V6ToHex(ipv6) + end + return addr, port +end + +local IpToHex = function (address) + if address:match(ipv4_patt) then + return 4, V4(address) + end + return 6, V6(address) +end + +for _, addr in ipairs{ + "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80" +} do + print(IpToHex(addr)) +end diff --git a/Task/Parse-an-IP-Address/Lua/parse-an-ip-address-2.lua b/Task/Parse-an-IP-Address/Lua/parse-an-ip-address-2.lua new file mode 100644 index 0000000000..755c4744c9 --- /dev/null +++ b/Task/Parse-an-IP-Address/Lua/parse-an-ip-address-2.lua @@ -0,0 +1,6 @@ +4 127.0.0.1 7f000001 2130706433 +4 127.0.0.1 80 7f000001 2130706433 +6 ::1 nil 00000000000000000000000000000001 1 0000:0000:0000:0000:0000:0000:0000:0001 +6 ::1 80 00000000000000000000000000000001 1 0000:0000:0000:0000:0000:0000:0000:0001 +6 2605:2700:0:3::4713:93e3 nil 260527000000000300000000471393e3 -1 2605:2700:0000:0003:0000:0000:4713:93e3 +6 2605:2700:0:3::4713:93e3 80 260527000000000300000000471393e3 -1 2605:2700:0000:0003:0000:0000:4713:93e3 diff --git a/Task/Parsing-RPN-calculator-algorithm/PascalABC.NET/parsing-rpn-calculator-algorithm.pas b/Task/Parsing-RPN-calculator-algorithm/PascalABC.NET/parsing-rpn-calculator-algorithm.pas new file mode 100644 index 0000000000..b6949afe1d --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/PascalABC.NET/parsing-rpn-calculator-algorithm.pas @@ -0,0 +1,15 @@ +## +var a := new Stack; +var b := new Dictionary real>; +b['+'] := (x, y) -> y + x; +b['-'] := (x, y) -> y - x; +b['*'] := (x, y) -> y * x; +b['/'] := (x, y) -> y / x; +b['^'] := (x, y) -> y ** x; + +foreach var c in '3 4 2 * 1 5 - 2 3 ^ ^ / +'.Split do +begin + if c in b then a.Push(b[c](a.Pop, a.Pop)) + else a.Push(c.ToReal); + println(c, a); +end; diff --git a/Task/Parsing-RPN-calculator-algorithm/Zig/parsing-rpn-calculator-algorithm.zig b/Task/Parsing-RPN-calculator-algorithm/Zig/parsing-rpn-calculator-algorithm.zig new file mode 100644 index 0000000000..cd70ad3288 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Zig/parsing-rpn-calculator-algorithm.zig @@ -0,0 +1,57 @@ +const std = @import("std"); + +fn rpn(text: []const u8, allocator: std.mem.Allocator) !f64 { + var tokens = std.mem.splitScalar(u8, text, ' '); + var stack = std.ArrayList(f64).init(allocator); + defer stack.deinit(); + + std.debug.print("input operation stack\n", .{}); + + while (tokens.next()) |token| { + if (token.len == 0) continue; + + std.debug.print("{s:^5} ", .{token}); + + const num = std.fmt.parseFloat(f64, token) catch { + if (stack.items.len < 2) { + return error.NotEnoughOperands; + } + + const b = stack.pop().?; + const a = stack.pop().?; + + if (std.mem.eql(u8, token, "+")) { + try stack.append(a + b); + } else if (std.mem.eql(u8, token, "-")) { + try stack.append(a - b); + } else if (std.mem.eql(u8, token, "*")) { + try stack.append(a * b); + } else if (std.mem.eql(u8, token, "/")) { + try stack.append(a / b); + } else if (std.mem.eql(u8, token, "^")) { + try stack.append(std.math.pow(f64, a, b)); + } else { + std.debug.panic("unknown operator {s}", .{token}); + } + + std.debug.print("calculate {any}\n", .{stack.items}); + continue; + }; + + try stack.append(num); + std.debug.print("push {any}\n", .{stack.items}); + } + + return if (stack.items.len > 0) stack.pop().? else 0.0; +} + +pub fn main() !void { + const text = "3 4 2 * 1 5 - 2 3 ^ ^ / +"; + + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const result = try rpn(text, allocator); + std.debug.print("\nresult: {d}\n", .{result}); +} diff --git a/Task/Parsing-Shunting-yard-algorithm/Zig/parsing-shunting-yard-algorithm.zig b/Task/Parsing-Shunting-yard-algorithm/Zig/parsing-shunting-yard-algorithm.zig new file mode 100644 index 0000000000..c3ff757afe --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Zig/parsing-shunting-yard-algorithm.zig @@ -0,0 +1,343 @@ +const std = @import("std"); +const print = std.debug.print; +const stdin = std.io.getStdIn().reader(); + +const StrTok = struct { + s: []const u8, + len: usize, + prec: i32, + assoc: i32, +}; + +const Pattern = struct { + str: []const u8, + assoc: i32 = 0, + prec: i32 = 0, +}; + +const Assoc = struct { + pub const NONE: i32 = 0; + pub const L: i32 = 1; + pub const R: i32 = 2; +}; + +const pat_eos = Pattern{ .str = "" }; + +const pat_ops = [_]Pattern{ + Pattern{ .str = ")", .assoc = Assoc.NONE, .prec = -1 }, + Pattern{ .str = "**", .assoc = Assoc.R, .prec = 3 }, + Pattern{ .str = "^", .assoc = Assoc.R, .prec = 3 }, + Pattern{ .str = "*", .assoc = Assoc.L, .prec = 2 }, + Pattern{ .str = "/", .assoc = Assoc.L, .prec = 2 }, + Pattern{ .str = "+", .assoc = Assoc.L, .prec = 1 }, + Pattern{ .str = "-", .assoc = Assoc.L, .prec = 1 }, + Pattern{ .str = "" }, +}; + +const pat_arg = [_]Pattern{ + Pattern{ .str = "number" }, // This will be matched differently + Pattern{ .str = "identifier" }, // This will be matched differently + Pattern{ .str = "(", .assoc = Assoc.L, .prec = -1 }, + Pattern{ .str = "" }, +}; + +const MAX_STACK = 128; +const MAX_QUEUE = 128; + +var stack: [MAX_STACK]StrTok = undefined; +var queue: [MAX_QUEUE]StrTok = undefined; +var l_queue: usize = 0; +var l_stack: usize = 0; +var prec_booster: i32 = 0; + +fn qpush(tok: StrTok) !void { + if (l_queue >= MAX_QUEUE) { + return error.QueueOverflow; + } + queue[l_queue] = tok; + l_queue += 1; +} + +fn spush(tok: StrTok) !void { + if (l_stack >= MAX_STACK) { + return error.StackOverflow; + } + stack[l_stack] = tok; + l_stack += 1; +} + +fn spop() StrTok { + if (l_stack == 0) { + @panic("Stack underflow"); + } + l_stack -= 1; + return stack[l_stack]; +} + +fn display(s: []const u8) !void { + print("\x1b[1;1H\x1b[JText | {s}\n", .{s}); + print("Stack| ", .{}); + + for (stack[0..l_stack]) |item| { + print("{s} ", .{item.s[0..item.len]}); + } + + print("\nQueue| ", .{}); + for (queue[0..l_queue]) |item| { + print("{s} ", .{item.s[0..item.len]}); + } + + print("\n\n\n", .{}); + var buf: [1]u8 = undefined; + _ = try stdin.read(&buf); +} + +fn fail(s1: []const u8, s2: []const u8) !bool { + print("[Error {s}] {s}\n", .{ s1, s2 }); + return error.ParseError; +} + +// Helper function to check if a character is a digit +fn isDigit(c: u8) bool { + return c >= '0' and c <= '9'; +} + +// Helper function to check if a character is a letter +fn isAlpha(c: u8) bool { + return (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z'); +} + +// Helper function to check if a character is alphanumeric or underscore +fn isAlnum(c: u8) bool { + return isAlpha(c) or isDigit(c) or c == '_'; +} + +fn match(s: []const u8, patterns: []const Pattern, tok: *StrTok) ?struct { pattern: *const Pattern, end_pos: usize } { + var pos: usize = 0; + + // Skip whitespace + while (pos < s.len and s[pos] == ' ') { + pos += 1; + } + + if (pos >= s.len) { + return null; + } + + const remaining = s[pos..]; + + // Check for numeric literals + if (remaining.len > 0 and (isDigit(remaining[0]) or + ((remaining[0] == '-' or remaining[0] == '+') and remaining.len > 1 and isDigit(remaining[1])) or + (remaining[0] == '.' and remaining.len > 1 and isDigit(remaining[1])))) { + + var i: usize = 0; + var hasDot = false; + var hasExp = false; + + // Handle sign + if (i < remaining.len and (remaining[i] == '-' or remaining[i] == '+')) { + i += 1; + } + + // Process digits before decimal point + while (i < remaining.len and isDigit(remaining[i])) { + i += 1; + } + + // Process decimal point and digits after it + if (i < remaining.len and remaining[i] == '.') { + hasDot = true; + i += 1; + while (i < remaining.len and isDigit(remaining[i])) { + i += 1; + } + } + + // Process exponent + if (i < remaining.len and (remaining[i] == 'e' or remaining[i] == 'E')) { + hasExp = true; + i += 1; + + // Optional sign for exponent + if (i < remaining.len and (remaining[i] == '-' or remaining[i] == '+')) { + i += 1; + } + + // There must be at least one digit in the exponent + if (i < remaining.len and isDigit(remaining[i])) { + i += 1; + while (i < remaining.len and isDigit(remaining[i])) { + i += 1; + } + } else if (hasExp) { + // Invalid exponent + return null; + } + } + + if (i > 0) { + tok.s = remaining; + tok.len = i; + return .{ .pattern = &pat_arg[0], .end_pos = pos + i }; + } + } + + // Check for identifiers + if (remaining.len > 0 and (isAlpha(remaining[0]) or remaining[0] == '_')) { + var i: usize = 1; + while (i < remaining.len and isAlnum(remaining[i])) { + i += 1; + } + + tok.s = remaining; + tok.len = i; + return .{ .pattern = &pat_arg[1], .end_pos = pos + i }; + } + + // Check for operators and parentheses + for (patterns) |p| { + if (p.str.len == 0) break; + + if (p.str[0] != '^') { // Not a special pattern like "number" or "identifier" + if (remaining.len >= p.str.len and std.mem.eql(u8, remaining[0..p.str.len], p.str)) { + tok.s = remaining; + tok.len = p.str.len; + return .{ .pattern = &p, .end_pos = pos + p.str.len }; + } + } + } + + return null; +} + +fn parse(text: []const u8) !bool { + var tok = StrTok{ .s = undefined, .len = 0, .prec = 0, .assoc = 0 }; + var pos: usize = 0; + + prec_booster = 0; + l_queue = 0; + l_stack = 0; + + try display(text); + + while (pos < text.len) { + const match_arg = match(text[pos..], &pat_arg, &tok); + if (match_arg == null) { + return try fail("parse arg", text[pos..]); + } + + const p_arg = match_arg.?.pattern; + pos = pos + (match_arg.?.end_pos - pos); + + // Don't stack the parens + if (std.mem.eql(u8, p_arg.str, "(")) { + prec_booster += 100; + } else { + try qpush(tok); + try display(text); + } + + // Check if we reached the end of the string + if (pos >= text.len) { + if (prec_booster != 0) { + return try fail("unmatched (", "end of string"); + } + + // If there are still operators on the stack, pop them all + while (l_stack > 0) { + try qpush(spop()); + try display(text); + } + + return true; + } + + re_op: { + const match_op = match(text[pos..], &pat_ops, &tok); + if (match_op == null) { + return try fail("parse op", text[pos..]); + } + + const p_op = match_op.?.pattern; + pos = pos + (match_op.?.end_pos - pos); + + tok.assoc = p_op.assoc; + tok.prec = p_op.prec; + + if (p_op.prec > 0) { + tok.prec = p_op.prec + prec_booster; + } else if (p_op.prec == -1) { + if (prec_booster < 100) { + return try fail("unmatched )", text[pos..]); + } + tok.prec = prec_booster; + } + + while (l_stack > 0) { + const t = &stack[l_stack - 1]; + if (!((t.prec == tok.prec and t.assoc == Assoc.L) or t.prec > tok.prec)) { + break; + } + try qpush(spop()); + try display(text); + } + + if (p_op.prec == -1) { + prec_booster -= 100; + break :re_op; + } + + if (p_op.prec == 0) { + try display(text); + if (prec_booster != 0) { + return try fail("unmatched (", text[pos..]); + } + return true; + } + + try spush(tok); + try display(text); + } + } + + return true; +} + +pub fn main() !void { + const tests = [_][]const u8{ + "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", + "123", + "3+4 * 2 / ( 1 - 5 ) ^ 2 ^ 3.14", + "(((((((1+2+3**(4 + 5))))))", + "a^(b + c/d * .1e5)", // Removed '!' which was causing an error + "(1**2)**3", + "2 + 2 *", + }; + + for (tests) |test_str| { + print("Testing string `{s}' \n", .{test_str}); + var buf: [1]u8 = undefined; + _ = try stdin.read(&buf); + + const result = parse(test_str) catch |err| { + switch (err) { + error.ParseError => { + print("string `{s}': Error\n\n", .{test_str}); + continue; + }, + error.StackOverflow => { + print("string `{s}': Stack Overflow Error\n\n", .{test_str}); + continue; + }, + error.QueueOverflow => { + print("string `{s}': Queue Overflow Error\n\n", .{test_str}); + continue; + }, + else => return err, + } + }; + + print("string `{s}': {s}\n\n", .{ test_str, if (result) "Ok" else "Error" }); + } +} diff --git a/Task/Particle-fountain/EasyLang/particle-fountain.easy b/Task/Particle-fountain/EasyLang/particle-fountain.easy index 7fe0380628..64c00aeeb7 100644 --- a/Task/Particle-fountain/EasyLang/particle-fountain.easy +++ b/Task/Particle-fountain/EasyLang/particle-fountain.easy @@ -1,10 +1,12 @@ rad = 0.125 n = 6000 # -len x[] n ; len y[] n -len vx[] n ; len vy[] n -background 059 -color 999 +len x[] n +len y[] n +len vx[] n +len vy[] n +gbackground 059 +gcolor 999 on animate for i = 1 to 32 ind = (ind + 1) mod1 n @@ -13,11 +15,11 @@ on animate vx[ind] = (randomf - 0.5) * 0.4 vy[ind] = 2 + randomf * 0.1 . - clear + gclear for i = 1 to n - move x[i] y[i] - circle rad - x[i] += vx[i] ; y[i] += vy[i] + gcircle x[i] y[i] rad + x[i] += vx[i] + y[i] += vy[i] vy[i] -= 0.025 . . diff --git a/Task/Partition-an-integer-x-into-n-primes/BASIC/partition-an-integer-x-into-n-primes.basic b/Task/Partition-an-integer-x-into-n-primes/BASIC/partition-an-integer-x-into-n-primes.basic new file mode 100644 index 0000000000..8c6d9030b2 --- /dev/null +++ b/Task/Partition-an-integer-x-into-n-primes/BASIC/partition-an-integer-x-into-n-primes.basic @@ -0,0 +1,33 @@ +10 DIM P%(13000),PR(30),I%(50),N(50),NP%(50),CP(50): MP=99809! +20 FOR P=2 TO SQR(MP) +30 PRINT CHR$(13);"Sieving... ";P; +40 FOR C=P*P TO MP STEP P +50 B=FIX(C/8): V=C-B*8 +60 P%(B) = P%(B) OR 2^V +70 NEXT C,P +80 PRINT CHR$(13);"Sieving done " +90 READ N,NP% +100 IF N=0 THEN END +110 PRINT:PRINT "Partitioning";N;"with";NP%;"primes:" +120 S=1: N(0)=N: NP%(0)=NP%: I%(0)=1: CP(0)=1 +130 IF S=0 THEN PRINT CHR$(13);"Impossible":GOTO 90 +140 S=S-1: N=N(S): NP%=NP%(S): I%=I%(S): CP=CP(S) +150 CP=CP+1 +160 B=FIX(CP/8):V=CP-B*8 +170 IF P%(B) AND 2^V GOTO 150 +175 PRINT CHR$(13);"@";CP; +180 IF N n - return - . + if p > n : return find (n - p) (k - 1) (i + 1) found r[] if found = 1 swap res[] r[] @@ -45,9 +39,7 @@ for i to len test[][] find test[i][1] test[i][2] 1 f res[] write test[i][1] & "(" & test[i][2] & ") = " if f = 1 - for j = len res[] downto 2 - write res[j] & " + " - . + for j = len res[] downto 2 : write res[j] & " + " print res[1] else print "not possible" diff --git a/Task/Partition-an-integer-x-into-n-primes/PascalABC.NET/partition-an-integer-x-into-n-primes.pas b/Task/Partition-an-integer-x-into-n-primes/PascalABC.NET/partition-an-integer-x-into-n-primes.pas new file mode 100644 index 0000000000..ce20293691 --- /dev/null +++ b/Task/Partition-an-integer-x-into-n-primes/PascalABC.NET/partition-an-integer-x-into-n-primes.pas @@ -0,0 +1,22 @@ +uses School; + +function primepartition(x, n: Integer): List; +begin + result := new List; + foreach var combo in Primes(x).Combinations(n) do + if combo.Sum = x then + begin + result := combo.ToList; + exit + end; +end; + +begin + foreach var (x, n) in |(18, 2), (19, 3), (20, 4), (99807, 1), (99809, 1), + (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)| do + begin + var ans := primepartition(x, n); + writeln('Partitioned', x:6, ' with', n:3, ' primes: ', + if ans.Count = 0 then 'impossible' else ans.JoinToString('+')); + end +end. diff --git a/Task/Partition-an-integer-x-into-n-primes/REXX/partition-an-integer-x-into-n-primes.rexx b/Task/Partition-an-integer-x-into-n-primes/REXX/partition-an-integer-x-into-n-primes.rexx index 63c2dbad83..8aad9f391a 100644 --- a/Task/Partition-an-integer-x-into-n-primes/REXX/partition-an-integer-x-into-n-primes.rexx +++ b/Task/Partition-an-integer-x-into-n-primes/REXX/partition-an-integer-x-into-n-primes.rexx @@ -1,52 +1,85 @@ -/*REXX program partitions integer(s) (greater than unity) into N primes. */ -parse arg what /*obtain an optional list from the C.L.*/ +-- 8 May 2025 +include Settings - do until what=='' /*possibly process a series of integers*/ - parse var what x n what; parse var x x '-' y /*get possible range and # partitions.*/ - parse var n n '-' m /* " " " " " " */ - if x=='' | x=="," then x= 19 /*Not specified? Then use the default.*/ - if y=='' | y=="," then y= x /* " " " " " " */ - if n=='' | n=="," then n= 3 /* " " " " " " */ - if m=='' | m=="," then m= n /* " " " " " " */ - call genP y /*generate Y number of primes. */ - do g=x to y /*partition X ───► Y into partitions.*/ - do q=n to m; call part /* " G into Q primes. */ - end /*q*/ - end /*g*/ - end /*until*/ +say 'PARTITION AN INTEGER X INTO N PRIMES' +say version +say +call GetPrimes 100000 +call ShowPartition 99809,1 +call ShowPartition 18,2 +call ShowPartition 19,3 +call ShowPartition 20,4 +call ShowPartition 2017,24 +call ShowPartition 22699,1 +call ShowPartition 22699,2 +call ShowPartition 22699,3 +call ShowPartition 22699,4 +call ShowPartition 40355,3 +exit -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: arg high; @.1= 2; @.2= 3; #= 2 /*get highest prime, assign some vars. */ - do j=@.#+2 by 2 until @.#>high /*only find odd primes from here on. */ - do k=2 while k*k<=j /*divide by some known low odd primes. */ - if j // @.k==0 then iterate j /*Is J divisible by P? Then ¬ prime.*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - #= # + 1; @.#= j /*bump prime count; assign prime to @.*/ - end /*j*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -getP: procedure expose i. p. @.; parse arg z /*bump the prime in the partition list.*/ - if i.z==0 then do; _= z - 1; i.z= i._; end - i.z= i.z + 1; _= i.z; p.z= @._; return 0 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -list: _= p.1; if $==g then do j=2 to q; _= _ p.j - end /*j*/ - else _= '__(not_possible)' - return 'prime' || word("s", 1 + (q==1)) translate(_, '+ ', " _") /*plural? */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -part: i.= 0; do j=1 for q; call getP j - end /*j*/ +GetPrimes: +procedure expose prim. +arg xx +call Time('r') +say 'Get primes up to' xx'...' +call Primes xx +say Format(Time('e'),,3) 'seconds'; say +return - do !=0 by 0; $= 0 /*!: a DO variable for LEAVE & ITERATE*/ - do s=1 for q; $= $ + p.s /* [↓] is sum of the primes too large?*/ - if $>g then do; if s==1 then leave ! /*perform a quick exit?*/ - do k=s to q; i.k= 0; end /*k*/ - do r=s-1 to q; call getP r; end /*r*/ - iterate ! - end - end /*s*/ - if $==g then leave /*is sum of the primes exactly right ? */ - if $ xx then do + do i = yy by -1 to 2 while s > xx + i1 = i-1; a = work.i1+1 + if prim.a > xx then + leave z + work.i1 = a + do j = i to yy + a = a+1; work.j = a + end + s = Sumwork(yy) + end + end + end +end +if s = xx then do + p = work.1; z = prim.p + do i = 2 to yy + p = work.i; z = z'+'prim.p + end +end +else do + z = 'not possible' +end +say xx 'partitioned into' yy 'primes is' z +say Format(Time('e'),,3) 'seconds'; say +return + +Sumwork: +procedure expose prim. work. +arg yy +s = 0 +do i = 1 to yy + a = work.i; p = prim.a; s = s+p +end +return s + +include Sequences +include Functions +include Constants +include Abend diff --git a/Task/Partition-an-integer-x-into-n-primes/Raku/partition-an-integer-x-into-n-primes.raku b/Task/Partition-an-integer-x-into-n-primes/Raku/partition-an-integer-x-into-n-primes.raku index 2808ee71cd..0cf1c50e59 100644 --- a/Task/Partition-an-integer-x-into-n-primes/Raku/partition-an-integer-x-into-n-primes.raku +++ b/Task/Partition-an-integer-x-into-n-primes/Raku/partition-an-integer-x-into-n-primes.raku @@ -1,17 +1,20 @@ -use Math::Primesieve; -my $sieve = Math::Primesieve.new; - # short circuit for '1' partition multi partition ( Int $number, 1 ) { $number.is-prime ?? $number !! () } -multi partition ( Int $number, Int $parts where * > 0 = 2 ) { - my @these = $sieve.primes($number); - for @these.combinations($parts) { .return if .sum == $number }; +my @primes = lazy (^Inf).grep: &is-prime; + +multi partition ( Int $number, Int $parts where * > 1 = 2 ) { + my @these = @primes[^($number div $parts)]; + shift @these if (($number %% 2) && ($parts %% 2)) || (($number % 2) && ($parts % 2)); + for @these.combinations($parts - 1) { + my $maybe = $number - .sum; + return (|$_, $maybe) if $maybe.is-prime && ($maybe ∉ $_) + }; () } # TESTING -(18,2, 19,3, 20,4, 99807,1, 99809,1, 2017,24, 22699,1, 22699,2, 22699,3, 22699,4, 40355,3)\ +(18,2, 19,3, 20,4, 99807,1, 99809,1, 99820,6, 2017,24, 22699,1, 22699,2, 22699,3, 22699,4, 40355,3)\ .race(:1batch).map: -> $number, $parts { say (sprintf "Partition %5d into %2d prime piece", $number, $parts), $parts == 1 ?? ': ' !! 's: ', join '+', partition($number, $parts) || 'not possible' diff --git a/Task/Pascal-matrix-generation/PascalABC.NET/pascal-matrix-generation.pas b/Task/Pascal-matrix-generation/PascalABC.NET/pascal-matrix-generation.pas new file mode 100644 index 0000000000..8afaf3170d --- /dev/null +++ b/Task/Pascal-matrix-generation/PascalABC.NET/pascal-matrix-generation.pas @@ -0,0 +1,16 @@ +## +function binomial(n, k: integer): biginteger; +begin + result := 1bi; + for var i := 1 to k do + result := result * (n - i + 1) div i; +end; + +var m := (0..4).Select(i -> (0..4).Select(j -> binomial(i, j))); +MatrByCol(m).println; +println; +m := (0..4).Select(i -> (0..4).Select(j -> binomial(j, i))); +MatrByCol(m).println; +println; +m := (0..4).Select(i -> (0..4).Select(j -> binomial(j + i, j))); +MatrByCol(m).println; diff --git a/Task/Pascals-triangle-Puzzle/PascalABC.NET/pascals-triangle-puzzle.pas b/Task/Pascals-triangle-Puzzle/PascalABC.NET/pascals-triangle-puzzle.pas new file mode 100644 index 0000000000..f948c1790c --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/PascalABC.NET/pascals-triangle-puzzle.pas @@ -0,0 +1,20 @@ +function pascal(a, b, mid, top: Integer): (integer, integer, integer); +begin + var yd := (top - 4 * (a + b)) / 7; + if yd <> yd.Round then + begin + result := (0, 0, 0); + exit + end; + var y := yd.Round; + var x := mid - 2 * a - y; + result := (x, y, y - x); +end; + +begin + var (x, y, z) := pascal(11, 4, 40, 151); + if x <> 0 then + println('Solution: x =', x, 'y =', y, 'z =', z) + else + println('There is no solution.') +end. diff --git a/Task/Pascals-triangle/EasyLang/pascals-triangle.easy b/Task/Pascals-triangle/EasyLang/pascals-triangle.easy index b8ea383ede..4f80121d68 100644 --- a/Task/Pascals-triangle/EasyLang/pascals-triangle.easy +++ b/Task/Pascals-triangle/EasyLang/pascals-triangle.easy @@ -1,12 +1,10 @@ -numfmt 0 4 -proc pascal n . . +numfmt 4 0 +proc pascal n . r[] = [ 1 ] for i to n rn[] = [ ] l = 0 - for j to n - len r[] - write " " - . + for j to n - len r[] : write " " for r in r[] write r rn[] &= l + r diff --git a/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy index efa8b72473..5c9abfed32 100644 --- a/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy +++ b/Task/Pathological-floating-point-problems/EasyLang/pathological-floating-point-problems.easy @@ -1,5 +1,5 @@ -numfmt 10 0 -proc task1 . . +numfmt 0 10 +proc task1 . print "--- Task 1 pathologic ---" vpp = 2 vp = -4 @@ -15,7 +15,7 @@ proc task1 . . task1 print "" # -proc task2 . . +proc task2 . print "--- Task 2 pathologic ---" e = 2.718281828459045 bal = e - 1 @@ -27,7 +27,7 @@ proc task2 . . task2 print "" # -proc mul f . bal bal$[] . +proc mul f &bal &bal$[] . for i = len bal$[] downto 1 dig = number bal$[i] h = dig * f + c @@ -36,7 +36,7 @@ proc mul f . bal bal$[] . . bal += c . -proc task2ok . . +proc task2ok . print "--- Task 2 OK ---" e$ = "2.7182818284590452353602874713526624977572470" bal = number substr e$ 1 1 diff --git a/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs new file mode 100644 index 0000000000..886d138cec --- /dev/null +++ b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-1.hs @@ -0,0 +1,11 @@ +-- | Show at least n decimal places + +showRational :: Natural -> Rational -> String +showRational n r = let + + sign = if r < 0 then '-' else '+' + (integer, rest) = (numerator r `quotRem` denominator r) + decimal = show $ rest * 10 ^ n `quot` denominator r + zeroes = replicate (fromIntegral n - length decimal) '0' + + in sign : show integer ++ "." ++ zeroes ++ decimal diff --git a/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs new file mode 100644 index 0000000000..3e5dca21df --- /dev/null +++ b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-2.hs @@ -0,0 +1,16 @@ +import Numeric.Natural (Natural) +import Data.Ratio as Rational + +-- | Infinite List of Rational numbers in the series, zips itself to produce more values + +v :: [Rational] +v = 2 : -4 : zipWith combine (drop 1 v) v + where + combine prev prev2 = 111 - 1130 / prev + 3000 / (prev * prev2) + + +-- >>> showRational 5 (1%3) +-- "+0.33333" + +main :: IO () +main = mapM_ (putStrLn . showRational 16 . (v !!)) [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] diff --git a/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs new file mode 100644 index 0000000000..8385954b66 --- /dev/null +++ b/Task/Pathological-floating-point-problems/Haskell/pathological-floating-point-problems-3.hs @@ -0,0 +1,30 @@ +import Data.Ratio ((%), numerator, denominator) +import Data.List (genericIndex) + +balances :: [Rational] +balances = e - 1 : zipWith nextYear [1..] balances + where + nextYear n b = n * b - 1 + + e = brothersFormulae 1000 + + +factorial :: [Integer] +factorial = 0 : 1 : zipWith (*) (drop 1 factorial) [2..] + +-- >>> take 10 factorial +-- [0,1,2,6,24,120,720,5040,40320,362880] + +brothersFormulae :: Integer -> Rational +brothersFormulae n = sum $ map step [0..n] + where + step i = (2 * i + 2) % genericIndex factorial (2 * i + 1) + +task2 :: String +task2 = showRational 30 . (balances !!) $ 25 + +-- >>> task2 +-- "+0.039938729673230208903671455210" + +main :: IO () +main = putStrLn task2 diff --git a/Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas b/Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas new file mode 100644 index 0000000000..16ae66209b --- /dev/null +++ b/Task/Pathological-floating-point-problems/PascalABC.NET/pathological-floating-point-problems.pas @@ -0,0 +1,45 @@ +uses numlibabc; + +function muller_seq(n: integer): real; +begin + var seq := Lst(Frc(0), Frc(2), Frc(-4)); + foreach var i in range(3, n + 1) do + begin + var next_value := 111 - 1130 / seq[i - 1] + 3000 / (seq[i - 1] * seq[i - 2]); + seq.Add(next_value); + end; + result := seq[n].ToReal +end; + +function tofraction(s: string): Fraction; +begin + var period := s.IndexOf('.'); + result := Frc(s.Remove(period, 1).ToBigInteger, Power(10bi, s.Length - period - 1)); +end; + +function bank(years: integer): real; +const + e = '2.71828182845904523536028747135266249775724709369995'; +begin + var bigE := ToFraction(e); + var balance := bigE - 1; + for var year := 1 to years do + balance := balance * year - 1; + result := balance.ToReal; +end; + +function rump(a, b: biginteger): real; +begin + var f := ToFraction('333.75') * b ** 6 + + a ** 2 * (11 * a ** 2 * b ** 2 - b ** 6 - 121 * b ** 4 - 2) + + ToFraction('5.5') * b ** 8 + Frc(a, 2 * b); + result := f.ToReal; +end; + +begin + println('Task 1:'); + foreach var n in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] do + println(n, muller_seq(n)); + println('Task 2: ', bank(25)); + println('Task 3: ', rump(77617, 33096)); +end. diff --git a/Task/Peano-curve/EasyLang/peano-curve.easy b/Task/Peano-curve/EasyLang/peano-curve.easy index 4b695b0ad2..b55b67d5d2 100644 --- a/Task/Peano-curve/EasyLang/peano-curve.easy +++ b/Task/Peano-curve/EasyLang/peano-curve.easy @@ -1,4 +1,4 @@ -proc lsysexp level . axiom$ rules$[] . +proc lsysexp level &axiom$ &rules$[] . for l to level an$ = "" for c$ in strchars axiom$ @@ -13,14 +13,15 @@ proc lsysexp level . axiom$ rules$[] . swap axiom$ an$ . . -proc lsysdraw axiom$ x y ang . . - linewidth 0.3 - move x y +proc lsysdraw axiom$ x y ang . + glinewidth 0.3 for c$ in strchars axiom$ if c$ = "F" + px = x + py = y x += cos dir y += sin dir - line x y + gline px py x y elif c$ = "-" dir -= ang elif c$ = "+" diff --git a/Task/Pells-equation/PascalABC.NET/pells-equation.pas b/Task/Pells-equation/PascalABC.NET/pells-equation.pas new file mode 100644 index 0000000000..123613e4ee --- /dev/null +++ b/Task/Pells-equation/PascalABC.NET/pells-equation.pas @@ -0,0 +1,31 @@ +function solvePell(n: integer): (biginteger, biginteger); +begin + var x: biginteger := n.sqrt.floor; + var (y, z, r) := (x, 1bi, x shl 1); + var (e1, e2) := (1bi, 0bi); + var (f1, f2) := (0bi, 1bi); + + repeat + y := r * z - y; + z := (n - y * y) div z; + r := (x + y) div z; + + (e1, e2) := (e2, e1 + e2 * r); + (f1, f2) := (f2, f1 + f2 * r); + + var (a, b) := (f2 * x + e2, f2); + if a * a - n * b * b = 1 then + begin + result := (a, b); + exit + end; + until false; +end; + +begin + foreach var n in |61, 109, 181, 277| do + begin + var (x, y) := solvePell(n); + writeln('x² - ', n:3, ' * y² = 1 for (x, y) = (', x:21, ',',y:20, ')'); + end; +end. diff --git a/Task/Penneys-game/Dart/penneys-game.dart b/Task/Penneys-game/Dart/penneys-game.dart new file mode 100644 index 0000000000..4f4d5fe9d8 --- /dev/null +++ b/Task/Penneys-game/Dart/penneys-game.dart @@ -0,0 +1,89 @@ +import 'dart:math'; +import 'dart:io'; + +class Penney { + int pW = 0; + int cW = 0; + String playerChoice = ''; + String computerChoice = ''; + String sequence = ''; + final Random _random = Random(); + + void gameLoop() { + String a; + while (true) { + playerChoice = ''; + computerChoice = ''; + if (_random.nextInt(2) == 1) { + computer(); + player(); + } else { + player(); + computer(); + } + + play(); + + stdout.write("[Y] to play again "); + a = stdin.readLineSync() ?? ''; // Read input from the console + + if (a.isNotEmpty && a[0].toUpperCase() != 'Y') { + print("Computer won $cW times."); + print("Player won $pW times."); + break; + } + print('\n\n'); + } + } + + void computer() { + if (playerChoice.isEmpty) { + for (int x = 0; x < 3; x++) { + computerChoice += (_random.nextInt(2) == 0) ? "H" : "T"; + } + } else { + computerChoice += (playerChoice[1] == 'T') ? "H" : "T"; + computerChoice += playerChoice.substring(0, 2); + } + print("Computer's sequence of three is: $computerChoice"); + } + + void player() { + stdout.write("Enter your sequence of three (H/T) "); + playerChoice = stdin.readLineSync() ?? ''; // Read input from the console + } + + void play() { + sequence = ''; + while (true) { + sequence += (_random.nextInt(2) == 0) ? "H" : "T"; + if (sequence.contains(playerChoice)) { + showWinner(1); + break; + } else if (sequence.contains(computerChoice)) { + showWinner(0); + break; + } + } + } + + void showWinner(int i) { + String s; + if (i == 1) { + s = "Player wins!"; + pW++; + } else { + s = "Computer wins!"; + cW++; + } + print("Tossed sequence: $sequence"); + print(s); + print('\n'); + } +} + +void main() { + // Dart does not need srand, Random() creates a new seeded random number generator. + final game = Penney(); + game.gameLoop(); +} diff --git a/Task/Pentagram/EasyLang/pentagram.easy b/Task/Pentagram/EasyLang/pentagram.easy index b8712411f7..6aa9bc629a 100644 --- a/Task/Pentagram/EasyLang/pentagram.easy +++ b/Task/Pentagram/EasyLang/pentagram.easy @@ -1,16 +1,15 @@ -xp = 10 -yp = 60 -linewidth 2 -move xp yp +x = 10 +y = 60 +glinewidth 2 while angle < 720 - x = xp + cos angle * 80 - y = yp + sin -angle * 80 - line x y - f[] &= x - f[] &= y xp = x yp = y + x += cos angle * 80 + y += sin -angle * 80 + gline xp yp x y + f[] &= x + f[] &= y angle += 144 . -color 900 -polygon f[] +gcolor 900 +gpolygon f[] diff --git a/Task/Percolation-Mean-run-density/EasyLang/percolation-mean-run-density.easy b/Task/Percolation-Mean-run-density/EasyLang/percolation-mean-run-density.easy index 3dabbe5a78..40bc29f1dd 100644 --- a/Task/Percolation-Mean-run-density/EasyLang/percolation-mean-run-density.easy +++ b/Task/Percolation-Mean-run-density/EasyLang/percolation-mean-run-density.easy @@ -1,4 +1,4 @@ -numfmt 3 6 +numfmt 6 3 for p in [ 0.1 0.3 0.5 0.7 0.9 ] theory = p * (1 - p) print "p:" & p & " theory:" & theory @@ -9,9 +9,7 @@ for p in [ 0.1 0.3 0.5 0.7 0.9 ] run = 0 for j to n h = if randomf < p - if h = 1 and run = 0 - sum += 1 - . + if h = 1 and run = 0 : sum += 1 run = h . . diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx index f726911248..5cf11e7b50 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx @@ -1,12 +1,38 @@ -/*REXX version of the ooRexx program (the code was modified to run with Classic REXX).*/ - do i=1 to 10000 /*statement changed: LOOP ──► DO*/ - if perfectNumber(i) then say i "is a perfect number" - end +-- 25 Mar 2025 +include Settings + +say 'PERFECT NUMBERS' +say version +say +numeric digits 100 +call Show 1,34000000 +call Show 137438691328 +call Show 2658455991569831744654692615953842176 +call Show 9658455991569831744654692615953842176 exit -perfectNumber: procedure; parse arg n /*statements changed: ROUTINE,USE*/ -sum=0 - do i=1 to n%2 /*statement changed: LOOP ──► DO*/ - if n//i==0 then sum=sum+i /*statement changed: sum += i */ - end -return sum=n +Show: +procedure +call Time('r') +arg xx,yy +if yy = '' then + yy = xx +interpret 'xx =' xx'+0'; interpret 'yy =' yy'+0' +say 'Perfect numbers between' xx 'and' yy'...' +xx = xx+Odd(xx); yy = yy-Odd(yy) +n = 0 +do i = xx to yy by 2 + if Perfect(i) then do + n = n+1 + call Charout ,i' ' + end +end +say +say n 'such numbers found' +say Format(Time('e'),,3) 'seconds' +say +return + +include Numbers +include Functions +include Abend diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx index d4bd1a89bf..f726911248 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx @@ -1,17 +1,12 @@ -/*REXX version of the PL/I program (code was modified to run with Classic REXX). */ -parse arg low high . /*obtain the specified number(s).*/ -if high=='' & low=='' then high=34000000 /*if no arguments, use a range. */ -if low=='' then low=1 /*if no LOW, then assume unity.*/ -if high=='' then high=low /*if no HIGH, then assume LOW. */ - - do i=low to high /*process the single # or range. */ - if perfect(i) then say i 'is a perfect number.' - end /*i*/ +/*REXX version of the ooRexx program (the code was modified to run with Classic REXX).*/ + do i=1 to 10000 /*statement changed: LOOP ──► DO*/ + if perfectNumber(i) then say i "is a perfect number" + end exit -perfect: procedure; parse arg n /*get the number to be tested. */ -sum=0 /*the sum of the factors so far. */ - do i=1 for n-1 /*starting at 1, find all factors*/ - if n//i==0 then sum=sum+i /*I is a factor of N, so add it.*/ - end /*i*/ -return sum=n /*if the sum matches N, perfect! */ +perfectNumber: procedure; parse arg n /*statements changed: ROUTINE,USE*/ +sum=0 + do i=1 to n%2 /*statement changed: LOOP ──► DO*/ + if n//i==0 then sum=sum+i /*statement changed: sum += i */ + end +return sum=n diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx index 981fd22097..d4bd1a89bf 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx @@ -1,21 +1,17 @@ -/*REXX program tests if a number (or a range of numbers) is/are perfect. */ -parse arg low high . /*obtain optional arguments from the CL*/ -if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ -if low=='' then low=1 /*if no LOW, then assume unity. */ -if high=='' then high=low /*if no HIGH, then assume LOW. */ -w=length(high) /*use W for formatting the output. */ -numeric digits max(9,w+2) /*ensure enough digits to handle number*/ +/*REXX version of the PL/I program (code was modified to run with Classic REXX). */ +parse arg low high . /*obtain the specified number(s).*/ +if high=='' & low=='' then high=34000000 /*if no arguments, use a range. */ +if low=='' then low=1 /*if no LOW, then assume unity.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ - do i=low to high /*process the single number or a range.*/ - if isPerfect(i) then say right(i,w) 'is a perfect number.' - end /*i*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPerfect: procedure; parse arg x /*obtain the number to be tested. */ - if x<6 then return 0 /*perfect numbers can't be < six. */ - s=1 /*the first factor of X. ___*/ - do j=2 while j*j<=x /*starting at 2, find the factors ≤√ X */ - if x//j\==0 then iterate /*J isn't a factor of X, so skip it.*/ - s = s + j + x%j /* ··· add it and the other factor. */ - end /*j*/ /*(above) is marginally faster. */ - return s==x /*if the sum matches X, it's perfect! */ + do i=low to high /*process the single # or range. */ + if perfect(i) then say i 'is a perfect number.' + end /*i*/ +exit + +perfect: procedure; parse arg n /*get the number to be tested. */ +sum=0 /*the sum of the factors so far. */ + do i=1 for n-1 /*starting at 1, find all factors*/ + if n//i==0 then sum=sum+i /*I is a factor of N, so add it.*/ + end /*i*/ +return sum=n /*if the sum matches N, perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx index 5f6b191337..981fd22097 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx @@ -1,28 +1,21 @@ -/*REXX program tests if a number (or a range of numbers) is/are perfect. */ -parse arg low high . /*obtain the specified number(s). */ -if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ -if low=='' then low=1 /*if no LOW, then assume unity. */ -if high=='' then high=low /*if no HIGH, then assume LOW. */ -w=length(high) /*use W for formatting the output. */ +/*REXX program tests if a number (or a range of numbers) is/are perfect. */ +parse arg low high . /*obtain optional arguments from the CL*/ +if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ +if low=='' then low=1 /*if no LOW, then assume unity. */ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting the output. */ numeric digits max(9,w+2) /*ensure enough digits to handle number*/ - do i=low to high /*process the single number or a range.*/ - if isPerfect(i) then say right(i,w) 'is a perfect number.' - end /*i*/ + do i=low to high /*process the single number or a range.*/ + if isPerfect(i) then say right(i,w) 'is a perfect number.' + end /*i*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -isPerfect: procedure; parse arg x 1 y /*obtain the number to be tested. */ - if x==6 then return 1 /*handle the special case of six. */ - /*[↓] perfect number's digitalRoot = 1*/ - do until y<10 /*find the digital root of Y. */ - parse var y r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end /*k*/ - y=r /*find digital root of the digit root. */ - end /*until*/ /*wash, rinse, repeat ··· */ - - if r\==1 then return 0 /*Digital root ¬ 1? Then ¬ perfect. */ +isPerfect: procedure; parse arg x /*obtain the number to be tested. */ + if x<6 then return 0 /*perfect numbers can't be < six. */ s=1 /*the first factor of X. ___*/ do j=2 while j*j<=x /*starting at 2, find the factors ≤√ X */ - if x//j\==0 then iterate /*J isn't a factor of X, so skip it. */ - s = s + j + x%j /*··· add it and the other factor. */ + if x//j\==0 then iterate /*J isn't a factor of X, so skip it.*/ + s = s + j + x%j /* ··· add it and the other factor. */ end /*j*/ /*(above) is marginally faster. */ - return s==x /*if the sum matches X, it's perfect! */ + return s==x /*if the sum matches X, it's perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx index 966599a864..5f6b191337 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx @@ -1,29 +1,28 @@ /*REXX program tests if a number (or a range of numbers) is/are perfect. */ -parse arg low high . /*obtain optional arguments from the CL*/ -if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ +parse arg low high . /*obtain the specified number(s). */ +if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ if low=='' then low=1 /*if no LOW, then assume unity. */ -low=low+low//2 /*if LOW is odd, bump it by one. */ -if high=='' then high=low /*if no HIGH, then assume LOW. */ +if high=='' then high=low /*if no HIGH, then assume LOW. */ w=length(high) /*use W for formatting the output. */ numeric digits max(9,w+2) /*ensure enough digits to handle number*/ - do i=low to high by 2 /*process the single number or a range.*/ - if isPerfect(i) then say right(i,w) 'is a perfect number.' - end /*i*/ + do i=low to high /*process the single number or a range.*/ + if isPerfect(i) then say right(i,w) 'is a perfect number.' + end /*i*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ isPerfect: procedure; parse arg x 1 y /*obtain the number to be tested. */ - if x==6 then return 1 /*handle the special case of six. */ + if x==6 then return 1 /*handle the special case of six. */ + /*[↓] perfect number's digitalRoot = 1*/ + do until y<10 /*find the digital root of Y. */ + parse var y r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end /*k*/ + y=r /*find digital root of the digit root. */ + end /*until*/ /*wash, rinse, repeat ··· */ - do until y<10 /*find the digital root of Y. */ - parse var y 1 r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end /*k*/ - y=r /*find digital root of the digital root*/ - end /*until*/ /*wash, rinse, repeat ··· */ - - if r\==1 then return 0 /*Digital root ¬ 1 ? Then ¬ perfect.*/ - s=3 + x%2 /*the first 3 factors of X. ___*/ - do j=3 while j*j<=x /*starting at 3, find the factors ≤√ X */ - if x//j\==0 then iterate /*J isn't a factor o f X, so skip it.*/ - s = s + j + x%j /* ··· add it and the other factor. */ - end /*j*/ /*(above) is marginally faster. */ - return s==x /*if sum matches X, then it's perfect!*/ + if r\==1 then return 0 /*Digital root ¬ 1? Then ¬ perfect. */ + s=1 /*the first factor of X. ___*/ + do j=2 while j*j<=x /*starting at 2, find the factors ≤√ X */ + if x//j\==0 then iterate /*J isn't a factor of X, so skip it. */ + s = s + j + x%j /*··· add it and the other factor. */ + end /*j*/ /*(above) is marginally faster. */ + return s==x /*if the sum matches X, it's perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx index 6b00ec353c..966599a864 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx @@ -1,33 +1,29 @@ /*REXX program tests if a number (or a range of numbers) is/are perfect. */ -parse arg low high . /*obtain the optional arguments from CL*/ -if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ -if low=='' then low=1 /*if no LOW, then assume unity. */ -low=low+low//2 /*if LOW is odd, bump it by one. */ -if high=='' then high=low /*if no HIGH, then assume LOW. */ -w=length(high) /*use W for formatting the output. */ +parse arg low high . /*obtain optional arguments from the CL*/ +if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */ +if low=='' then low=1 /*if no LOW, then assume unity. */ +low=low+low//2 /*if LOW is odd, bump it by one. */ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting the output. */ numeric digits max(9,w+2) /*ensure enough digits to handle number*/ -@.=0; @.1=2 /*highest magic number and its index. */ do i=low to high by 2 /*process the single number or a range.*/ if isPerfect(i) then say right(i,w) 'is a perfect number.' end /*i*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -isPerfect: procedure expose @.; parse arg x /*obtain the number to be tested. */ - /*Lucas-Lehmer know that perfect */ - /* numbers can be expressed as: */ - /* [2**n - 1] * [2** (n-1) ] */ +isPerfect: procedure; parse arg x 1 y /*obtain the number to be tested. */ + if x==6 then return 1 /*handle the special case of six. */ - if @.01; q=q%4; _=z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end - end /*while q>1*/ /* [↑] compute the integer SQRT of X.*/ - /* _____*/ - do j=3 to r /*starting at 3, find factors ≤ √ X */ - if x//j==0 then s=s+j+x%j /*J divisible by X? Then add J and X÷J*/ - end /*j*/ - return s==x /*if the sum matches X, then perfect! */ + if @.x==0 then return 0 /*Didn't pass Lucas-Lehmer test? */ + s = 3 + x%2 /*we know the following factors: */ + /* 1 ('cause Mama said so.) */ + /* 2 ('cause it's even.) */ + /* x÷2 ( " " " ) ___*/ + do j=3 while j*j<=x /*starting at 3, find the factors ≤√ X */ + if x//j\==0 then iterate /*J divides X evenly, so ··· */ + s=s + j + x%j /*··· add it and the other factor. */ + end /*j*/ /*(above) is marginally faster. */ + return s==x /*if the sum matches X, it's perfect!*/ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-8.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-8.rexx new file mode 100644 index 0000000000..bb38ef701e --- /dev/null +++ b/Task/Perfect-numbers/REXX/perfect-numbers-8.rexx @@ -0,0 +1,47 @@ +/*REXX program tests if a number (or a range of numbers) is/are perfect. */ +parse arg low high . /*obtain optional arguments from the CL*/ +if high=='' & low=="" then high=34000000 /*No arguments? Then use a range. */ +if low=='' then low=1 /*if no LOW, then assume unity. */ +low=low+low//2 /*if LOW is odd, bump it by one. */ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting the output. */ +numeric digits max(9,w+2) /*ensure enough decimal digits for nums*/ +@. =0; @.1=2; !.=2; _=' 6' /*highest magic number and its index.*/ +!._=22; !.16=12; !.28=8; !.36=20; !.56=20; !.76=20; !.96=20 + /* [↑] "Lucas' numbers, in 1891. */ + do i=low to high by 0 /*process the single number or a range.*/ + if isPerfect(i) then say right(i,w) 'is a perfect number.' + i=i+!.? /*use a fast advance for the DO index. */ + end /*i*/ /* [↑] note: the DO index is modified.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isPerfect: procedure expose @. !. ? /*expose (make global) some variables. */ + parse arg x 1 y '' -2 ? /*# (and copy), and the last 2 digits.*/ + if x==6 then return 1 /*handle the special case of six. */ + if !.?==2 then return 0 /*test last two digits: François Lucas.*/ + /*╔═════════════════════════════════════════════╗ + ║ Lucas─Lehmer know that perfect numbers can ║ + ║ be expressed as: [2^n -1] * {2^(n-1) } ║ + ╚═════════════════════════════════════════════╝*/ + if @.01; q=q%4; _=z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end + end /*while q>1*/ /* [↑] compute the integer SQRT of X.*/ + /* _____*/ + do j=3 to r /*starting at 3, find factors ≤ √ X */ + if x//j==0 then s=s+j+x%j /*J divisible by X? Then add J and X÷J*/ + end /*j*/ + return s==x /*if the sum matches X, then perfect! */ diff --git a/Task/Perfect-shuffle/EasyLang/perfect-shuffle.easy b/Task/Perfect-shuffle/EasyLang/perfect-shuffle.easy index 9873feded1..65312f6022 100644 --- a/Task/Perfect-shuffle/EasyLang/perfect-shuffle.easy +++ b/Task/Perfect-shuffle/EasyLang/perfect-shuffle.easy @@ -1,4 +1,4 @@ -proc pshuffle . deck[] . +proc pshuffle &deck[] . mp = len deck[] / 2 in[] = deck[] for i = 1 to mp @@ -6,10 +6,8 @@ proc pshuffle . deck[] . deck[2 * i] = in[i + mp] . . -proc test size . . - for i to size - deck0[] &= i - . +proc test size . + for i to size : deck0[] &= i deck[] = deck0[] repeat pshuffle deck[] diff --git a/Task/Perfect-shuffle/PascalABC.NET/perfect-shuffle.pas b/Task/Perfect-shuffle/PascalABC.NET/perfect-shuffle.pas new file mode 100644 index 0000000000..ded0f45d7b --- /dev/null +++ b/Task/Perfect-shuffle/PascalABC.NET/perfect-shuffle.pas @@ -0,0 +1,19 @@ +function shuffle(deck: list) := deck[:deck.Count div 2].Interleave(deck[deck.Count div 2:]); + +function number(size: integer): integer; +begin + assert(size mod 2 = 0, 'size must be even'); + var start := Range(1, size).ToList; + var deck := Range(1, size).ToList; + var counter := 0; + repeat + deck := shuffle(deck).ToList; + counter += 1; + until deck.SequenceEqual(start); + result := counter; +end; + +begin + foreach var size in |8, 24, 52, 100, 1020, 1024, 10_000| do + writeln(size:5, ': ', number(size):4); +end. diff --git a/Task/Perfect-totient-numbers/PascalABC.NET/perfect-totient-numbers.pas b/Task/Perfect-totient-numbers/PascalABC.NET/perfect-totient-numbers.pas new file mode 100644 index 0000000000..66862598cd --- /dev/null +++ b/Task/Perfect-totient-numbers/PascalABC.NET/perfect-totient-numbers.pas @@ -0,0 +1,23 @@ +uses school; + +function totient(n: int64) := (1..n).Select(k -> (if gcd(n, k) = 1 then 1 else 0)).Sum; + +function perfect(): sequence of integer; +begin + var n := 1; + repeat + var tot := n; + var sum := 0; + while tot <> 1 do + begin + tot := totient(tot); + sum += tot; + end; + if sum = n then yield n; + n += 2; + until false; +end; + +begin + perfect.Take(20).Println; +end. diff --git a/Task/Periodic-table/EasyLang/periodic-table.easy b/Task/Periodic-table/EasyLang/periodic-table.easy index 99c61ba5bf..0f25dd9a26 100644 --- a/Task/Periodic-table/EasyLang/periodic-table.easy +++ b/Task/Periodic-table/EasyLang/periodic-table.easy @@ -1,16 +1,12 @@ -proc mpos n . . +proc mpos n . a[] = [ 1 2 5 13 57 72 89 104 ] b[] = [ -1 15 25 35 72 21 58 7 ] i = len a[] - while a[i] > n - i -= 1 - . + while a[i] > n : i -= 1 m = n + b[i] r = m div 18 + 1 c = m mod 18 + 1 print "Atomic number " & n & "-> " & r & ", " & c . elem[] = [ 1 2 29 42 57 58 59 71 72 89 90 103 113 ] -for e in elem[] - mpos e -. +for e in elem[] : mpos e diff --git a/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy b/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy index e1b61bf007..d8b58f906b 100644 --- a/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy +++ b/Task/Peripheral-drift-illusion/EasyLang/peripheral-drift-illusion.easy @@ -3,25 +3,22 @@ offs = 10 / n r = (100 / (3 * n + 1)) step = 360 * 2 / (n - 1) # -background 470 -clear +gbackground 470 +gclear for row = 0 to n - 1 for col = 0 to n - 1 x = (3 * col + 2) * r y = (3 * row + 2) * r # h = col * step + row * step - move (x + offs * cos h) (y + offs * sin h) - color 999 - circle r + gcolor 999 + gcircle (x + offs * cos h) (y + offs * sin h) r # h += 180 - move (x + offs * cos h) (y + offs * sin h) - color 000 - circle r + gcolor 000 + gcircle (x + offs * cos h) (y + offs * sin h) r # - move x y - color 128 - circle r + gcolor 128 + gcircle x y r . . diff --git a/Task/Perlin-noise/EasyLang/perlin-noise.easy b/Task/Perlin-noise/EasyLang/perlin-noise.easy index 4b0f9dda52..8fd4b68670 100644 --- a/Task/Perlin-noise/EasyLang/perlin-noise.easy +++ b/Task/Perlin-noise/EasyLang/perlin-noise.easy @@ -1,7 +1,6 @@ p[] = [ 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149 56 87 174 20 125 136 171 168 68 175 74 165 71 134 139 48 27 166 77 146 158 231 83 111 229 122 60 211 133 230 220 105 92 41 55 46 245 40 244 102 143 54 65 25 63 161 1 216 80 73 209 76 132 187 208 89 18 169 200 196 135 130 116 188 159 86 164 100 109 198 173 186 3 64 52 217 226 250 124 123 5 202 38 147 118 126 255 82 85 212 207 206 59 227 47 16 58 17 182 189 28 42 223 183 170 213 119 248 152 2 44 154 163 70 221 153 101 155 167 43 172 9 129 22 39 253 19 98 108 110 79 113 224 232 178 185 112 104 218 246 97 228 251 34 242 193 238 210 144 12 191 179 162 241 81 51 145 235 249 14 239 107 49 192 214 31 181 199 106 157 184 84 204 176 115 121 50 45 127 4 150 254 138 236 205 93 222 114 67 29 24 72 243 141 128 195 78 66 215 61 156 180 ] -for i to 256 - p[] &= p[i] -. +for i to 256 : p[] &= p[i] +# func fade t . return t * t * t * (t * (t * 6 - 15) + 10) . @@ -61,15 +60,14 @@ func noise x y z . k8 = grad p[b2 + 2] (xx - 1) (yy - 1) (zz - 1) return lerp w (lerp v (lerp u k1 k2) (lerp u k3 k4)) (lerp v (lerp u k5 k6) (lerp u k7 k8)) . -numfmt 17 0 +numfmt 0 17 print noise 3.14 42 7 # # demo for y = 0 to 199 for x = 0 to 199 p = noise (x / 30) (y / 30) 0.1 - move x / 2 y / 2 - color3 p p p - rect 0.6 0.6 + gcolor3 p p p + grect x / 2 y / 2 0.6 0.6 . . diff --git a/Task/Perlin-noise/JavaScript/perlin-noise.js b/Task/Perlin-noise/JavaScript/perlin-noise.js new file mode 100644 index 0000000000..e982437274 --- /dev/null +++ b/Task/Perlin-noise/JavaScript/perlin-noise.js @@ -0,0 +1,80 @@ +let p = Array(512).fill(0); + +function fade(t) { + return t * t * t * (t * (t * 6 - 15) + 10); +} + +function lerp(t, a, b) { + return a + t * (b - a); +} + +function grad(hash, x, y, z) { + const h = hash & 15; // CONVERT LOW 4 BITS OF HASH CODE + const u = h < 8 ? x : y; // INTO 12 GRADIENT DIRECTIONS. + const v = h < 4 ? y : (h == 12 || h == 14) ? x : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); +} + +function perlinNoise(x, y, z) { + const X = Math.floor(x) & 0xff; // FIND UNIT CUBE THAT + const Y = Math.floor(y) & 0xff; // CONTAINS POINT. + const Z = Math.floor(z) & 0xff; + x -= Math.floor(x); // FIND RELATIVE X,Y,Z + y -= Math.floor(y); // OF POINT IN CUBE. + z -= Math.floor(z); + + const u = fade(x); // COMPUTE FADE CURVES + const v = fade(y); // FOR EACH OF X,Y,Z. + const w = fade(z); + + const A = p[X] + Y; + const AA = p[A] + Z; + const AB = p[A + 1] + Z; // HASH COORDINATES OF + const B = p[X + 1] + Y; + const BA = p[B] + Z; + const BB = p[B + 1] + Z; // THE 8 CUBE CORNERS, + + return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ), // AND ADD + grad(p[BA ], x - 1, y , z )), // BLENDED + lerp(u, grad(p[AB ], x , y - 1, z ), // RESULTS + grad(p[BB ], x - 1, y - 1, z ))), // FROM 8 + lerp(v, lerp(u, grad(p[AA + 1], x , y , z - 1), // CORNERS + grad(p[BA + 1], x - 1, y , z - 1)), // OF CUBE + lerp(u, grad(p[AB + 1], x , y - 1, z - 1), + grad(p[BB + 1], x - 1, y - 1, z - 1)))); +} + +async function readFile(fileName) { + try { + const response = await fetch('../' + fileName); + if (!response.ok) { + throw new Error('Cannot open file'); + } + const text = await response.text(); + const lines = text.split('\n'); + let index = 0; + + for (const line of lines) { + const numbers = line.split(','); + for (const word of numbers) { + if (word.trim()) { + const number = parseInt(word); + p[index] = number; + p[256 + index] = number; + index++; + } + } + } + } catch (error) { + console.error(error.message); + } +} + +async function main() { + await readFile('permutation.txt'); + + console.log('Perlin noise applied to (3.14, 42.0, 7.0) gives ' + + perlinNoise(3.14, 42.0, 7.0).toFixed(16)); +} + +main(); diff --git a/Task/Permutation-test/ALGOL-68/permutation-test.alg b/Task/Permutation-test/ALGOL-68/permutation-test.alg new file mode 100644 index 0000000000..3bfcbfa927 --- /dev/null +++ b/Task/Permutation-test/ALGOL-68/permutation-test.alg @@ -0,0 +1,36 @@ +BEGIN # Permutation test - translated from the C sample # + + PROC pick = ( INT at, remain, accu, treat, []INT data )INT: + IF remain < 1 + THEN IF accu > treat THEN 1 ELSE 0 FI + ELSE pick( at - 1, remain - 1, accu + data[ at - 1 ], treat, data ) + + IF at > remain THEN pick( at - 1, remain, accu, treat, data ) ELSE 0 FI + FI # pick # ; + + PROC permutation test = ( []INT data, REF INT le, gt, REF REAL total )VOID: + IF LWB data /= 0 + THEN print( ( "LWB data is not 0", newline ) ); stop + ELSE INT treat := 0; + INT mid = UPB data OVER 2; + + total := 1; + FOR i FROM LWB data TO mid - 1 DO treat +:= data[ i ] OD; + FOR i FROM UPB data + 1 BY -1 TO mid + 2 DO total *:= i OD; + FOR i FROM mid BY -1 TO LWB data + 1 DO total /:= i OD; + + gt := pick( UPB data + 1, mid, LWB data, treat, data ); + le := ENTIER ( total - gt ) + FI # permutation test # ; + + BEGIN + REAL total := 0; + INT gt := -1, le := -1; + permutation test( []INT( 85, 88, 75, 66, 25, 29, 83, 39, 97 + , 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 + )[ AT 0 ] + , le, gt, total + ); + print( ( "<= : ", fixed( 100 * le / total, -9, 6 ), "% ", whole( le, 0 ), newline ) ); + print( ( " > : ", fixed( 100 * gt / total, -9, 6 ), "% ", whole( gt, 0 ), newline ) ) + END +END diff --git a/Task/Permutation-test/EasyLang/permutation-test.easy b/Task/Permutation-test/EasyLang/permutation-test.easy new file mode 100644 index 0000000000..e443d06ffc --- /dev/null +++ b/Task/Permutation-test/EasyLang/permutation-test.easy @@ -0,0 +1,17 @@ +data[] = [ 85 88 75 66 25 29 83 39 97 68 41 10 49 16 65 32 92 28 98 ] +func pick at remain accu treat . + if remain = 0 : return if accu > treat + a = pick (at - 1) (remain - 1) (accu + data[at]) treat + if at > remain : b = pick (at - 1) remain accu treat + return a + b +. +proc main . + total = 1 + for i to 9 : treat += data[i] + for i = 19 downto 11 : total *= i + for i = 9 downto 1 : total /= i + gt = pick 19 9 0 treat + le = total - gt + print 100 * le / total & "% " & 100 * gt / total & "%" +. +main diff --git a/Task/Permutation-test/M2000-Interpreter/permutation-test-2.m2000 b/Task/Permutation-test/M2000-Interpreter/permutation-test-2.m2000 index 84aa33ecad..34eac751d9 100644 --- a/Task/Permutation-test/M2000-Interpreter/permutation-test-2.m2000 +++ b/Task/Permutation-test/M2000-Interpreter/permutation-test-2.m2000 @@ -17,25 +17,19 @@ Module CheckThis { } treated=(85, 88, 75, 66, 25, 29, 83, 39, 97) placebo=(68, 41, 10, 49, 16, 65, 32, 92, 28, 98) - treat=0 - m=each(treated): while m {treat+=array(m)} - total=1 + treat=treated#sum() + double total=1 for i=len(placebo)+1 to len(placebo) +len(treated):total*=i:next i for i=len(placebo)-1 to 1: total/=i:next i d=total div 10**int(log(total)) k=false StepA=CombinationsStep(cons(treated, placebo),len(treated)) - counter=0 - gt=0 - While not k { - comb=StepA(&k) - accu=0 - m=each(comb) - while m {accu+=array(m)} - gt+=if(accu>treat->1,0) - counter++ - if counter mod d=0 then Print over str$(counter/total," #0.0%"): Refresh 1000 - } + long counter=0 + long gt=0 + While not k + if StepA(&k)#sum()>treat then gt++ + counter++: if counter mod d=0 then Print over str$(counter/total," #0.0%"):Refresh + End While print over str$(counter/total," #0.0%") print lt=total-gt diff --git a/Task/Permutation-test/PascalABC.NET/permutation-test.pas b/Task/Permutation-test/PascalABC.NET/permutation-test.pas new file mode 100644 index 0000000000..98aae8ae01 --- /dev/null +++ b/Task/Permutation-test/PascalABC.NET/permutation-test.pas @@ -0,0 +1,20 @@ +function permutationTest(a, b: array of integer): real; +begin + var ab := a + b; + var Tobs := a.Sum; + var under := 0; + var count := 0; + foreach var perm in ab.Combinations(a.Length) do + begin + if perm.Sum <= Tobs then under += 1; + count += 1; + end; + result := under * 100 / count; +end; + +begin + var treatmentGroup := [85, 88, 75, 66, 25, 29, 83, 39, 97]; + var controlGroup := [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; + var under := permutationTest(treatmentGroup, controlGroup); + write('under= ', under:2:2, '%, over= ', (100 - under):2:2, '%'); +end diff --git a/Task/Permutations-Derangements/EasyLang/permutations-derangements.easy b/Task/Permutations-Derangements/EasyLang/permutations-derangements.easy index 48b56cd0d9..dd74803959 100644 --- a/Task/Permutations-Derangements/EasyLang/permutations-derangements.easy +++ b/Task/Permutations-Derangements/EasyLang/permutations-derangements.easy @@ -1,10 +1,8 @@ global list[] rlist[][] . -proc permlist k . . +proc permlist k . if k >= len list[] for i to len list[] - if i = list[i] - return - . + if i = list[i] : return . rlist[][] &= list[] return @@ -16,12 +14,10 @@ proc permlist k . . . . # -proc derang n . r[][] . +proc derang n &r[][] . rlist[][] = [ ] list[] = [ ] - for i to n - list[] &= i - . + for i to n : list[] &= i permlist 1 r[][] = rlist[][] . @@ -30,9 +26,7 @@ derang 4 r[][] print r[][] # func subfac n . - if n < 2 - return 1 - n - . + if n < 2 : return 1 - n return (subfac (n - 1) + subfac (n - 2)) * (n - 1) . # diff --git a/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy b/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy index db99f09c13..7cd6ccf0fc 100644 --- a/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy +++ b/Task/Permutations-Rank-of-a-permutation/EasyLang/permutations-rank-of-a-permutation.easy @@ -1,14 +1,10 @@ func[] init n . - for i to n - r[] &= i - 1 - . + for i to n : r[] &= i - 1 return r[] . func fac n . f = 1 - for i to n - f *= i - . + for i to n : f *= i return f . func[] perm n r . @@ -32,9 +28,7 @@ func rank n p[] . fa /= i h = p[n - i + 1] d = 1 - while perm[d] <> h - d += 1 - . + while perm[d] <> h : d += 1 r += fa * (d - 1) for j = d to i - 1 perm[j] = perm[j + 1] @@ -42,7 +36,7 @@ func rank n p[] . . return r . -proc show . . +proc show . for i = 0 to 5 h[] = perm 3 i print i & " -> " & h[] & " -> " & rank 3 h[] diff --git a/Task/Permutations-by-swapping/EasyLang/permutations-by-swapping.easy b/Task/Permutations-by-swapping/EasyLang/permutations-by-swapping.easy index 73e3bdc40b..3ff65eddba 100644 --- a/Task/Permutations-by-swapping/EasyLang/permutations-by-swapping.easy +++ b/Task/Permutations-by-swapping/EasyLang/permutations-by-swapping.easy @@ -1,6 +1,6 @@ # Heap's Algorithm sig = 1 -proc generate k . ar[] . +proc generate k &ar[] . if k = 1 print ar[] & " " & sig sig = -sig diff --git a/Task/Permutations/C/permutations-1.c b/Task/Permutations/C/permutations-1.c index 9312ae9af6..94f6b852bd 100644 --- a/Task/Permutations/C/permutations-1.c +++ b/Task/Permutations/C/permutations-1.c @@ -1,54 +1,65 @@ #include -int main (int argc, char *argv[]) { -//here we check arguments - if (argc < 2) { - printf("Enter an argument. Example 1234 or dcba:\n"); - return 0; - } -//it calculates an array's length - int x; - for (x = 0; argv[1][x] != '\0'; x++); -//buble sort the array - int f, v, m; - for(f=0; f < x; f++) { - for(v = x-1; v > f; v-- ) { - if (argv[1][v-1] > argv[1][v]) { - m=argv[1][v-1]; - argv[1][v-1]=argv[1][v]; - argv[1][v]=m; +#include + +#define ARR_SIZE 4 + +int ifactorial(int n) { + if (n == 0) { + return 1; } - } + + int result = 1; + + for (int i = 1; i <= n; i++) { + result *= i; + } + + return result; } -//it calculates a factorial to stop the algorithm - char a[x]; - int k=0; - int fact=k+1; - while (k!=x) { - a[k]=argv[1][k]; - k++; - fact = k*fact; - } - a[k]='\0'; -//Main part: here we permutate - int i, j; - int y=0; - char c; - while (y != fact) { - printf("%s\n", a); - i=x-2; - while(a[i] > a[i+1] ) i--; - j=x-1; - while(a[j] < a[i] ) j--; - c=a[j]; - a[j]=a[i]; - a[i]=c; -i++; -for (j = x-1; j > i; i++, j--) { - c = a[i]; - a[i] = a[j]; - a[j] = c; - } -y++; - } +void swap(char *a, char *b) { + char tmp = *a; + *a = *b; + *b = tmp; +} + +void permutations(char *arr, int arr_size) { + int factorial = ifactorial(arr_size); + + int k = 0; + while (k < factorial) { + printf("%s\n", arr); + + int i = arr_size - 2; + while (arr[i] > arr[i + 1]) { + i--; + } + + int j = arr_size - 1; + while (arr[j] < arr[i]) { + j--; + } + + swap(&arr[j], &arr[i]); + i++; + + for (j = arr_size - 1; j > i; i++, j--) { + swap(&arr[i], &arr[j]); + } + + k++; + } +} + +int compare(const void *a, const void *b) { + return (int)(*(char *)a - *(char *)b); // ascending order +} + +int main(void) { + char arr[ARR_SIZE + 1] = "dbac"; + + qsort(arr, ARR_SIZE, sizeof(char), compare); // "abcd" + permutations(arr, ARR_SIZE); + + return EXIT_SUCCESS; } diff --git a/Task/Permutations/C/permutations-2.c b/Task/Permutations/C/permutations-2.c index d1a15c5d17..2863886f1f 100644 --- a/Task/Permutations/C/permutations-2.c +++ b/Task/Permutations/C/permutations-2.c @@ -1,23 +1,65 @@ #include -int main() { - char a[] = "4321"; //array - int i, j; - int f=24; //factorial - char c; //buffer - while (f--) { - printf("%s\n", a); - i=1; - while(a[i] > a[i-1]) i++; - j=0; - while(a[j] < a[i])j++; - c=a[j]; - a[j]=a[i]; - a[i]=c; -i--; -for (j = 0; j < i; i--, j++) { - c = a[i]; - a[i] = a[j]; - a[j] = c; - } - } +#include + +#define ARR_SIZE 4 + +int ifactorial(int n) { + if (n == 0) { + return 1; + } + + int result = 1; + + for (int i = 1; i <= n; i++) { + result *= i; + } + + return result; +} + +void swap(char *a, char *b) { + char tmp = *a; + *a = *b; + *b = tmp; +} + +void permutations(char *arr, int arr_size) { + int factorial = ifactorial(arr_size); + + int k = factorial; + while (k > 0) { + printf("%s\n", arr); + + int i = 1; + while (arr[i] > arr[i - 1]) { + i++; + } + + int j = 0; + while (arr[j] < arr[i]) { + j++; + } + + swap(&arr[j], &arr[i]); + i--; + + for (j = 0; j < i; i--, j++) { + swap(&arr[i], &arr[j]); + } + + k--; + } +} + +int compare(const void *a, const void *b) { + return (int)(*(char *)b - *(char *)a); // descending order +} + +int main(void) { + char arr[ARR_SIZE + 1] = "2431"; + + qsort(arr, ARR_SIZE, sizeof(char), compare); // "4321" + permutations(arr, ARR_SIZE); + + return EXIT_SUCCESS; } diff --git a/Task/Permutations/C/permutations-4.c b/Task/Permutations/C/permutations-4.c deleted file mode 100644 index 771af27207..0000000000 --- a/Task/Permutations/C/permutations-4.c +++ /dev/null @@ -1,100 +0,0 @@ -#include -#include - -/* print a list of ints */ -int show(int *x, int len) -{ - int i; - for (i = 0; i < len; i++) - printf("%d%c", x[i], i == len - 1 ? '\n' : ' '); - return 1; -} - -/* next lexicographical permutation */ -int next_lex_perm(int *a, int n) { -# define swap(i, j) {t = a[i]; a[i] = a[j]; a[j] = t;} - int k, l, t; - - /* 1. Find the largest index k such that a[k] < a[k + 1]. If no such - index exists, the permutation is the last permutation. */ - for (k = n - 1; k && a[k - 1] >= a[k]; k--); - if (!k--) return 0; - - /* 2. Find the largest index l such that a[k] < a[l]. Since k + 1 is - such an index, l is well defined */ - for (l = n - 1; a[l] <= a[k]; l--); - - /* 3. Swap a[k] with a[l] */ - swap(k, l); - - /* 4. Reverse the sequence from a[k + 1] to the end */ - for (k++, l = n - 1; l > k; l--, k++) - swap(k, l); - return 1; -# undef swap -} - -void perm1(int *x, int n, int callback(int *, int)) -{ - do { - if (callback) callback(x, n); - } while (next_lex_perm(x, n)); -} - -/* Boothroyd method; exactly N! swaps, about as fast as it gets */ -void boothroyd(int *x, int n, int nn, int callback(int *, int)) -{ - int c = 0, i, t; - while (1) { - if (n > 2) boothroyd(x, n - 1, nn, callback); - if (c >= n - 1) return; - - i = (n & 1) ? 0 : c; - c++; - t = x[n - 1], x[n - 1] = x[i], x[i] = t; - if (callback) callback(x, nn); - } -} - -/* entry for Boothroyd method */ -void perm2(int *x, int n, int callback(int*, int)) -{ - if (callback) callback(x, n); - boothroyd(x, n, n, callback); -} - -/* same as perm2, but flattened recursions into iterations */ -void perm3(int *x, int n, int callback(int*, int)) -{ - /* calloc isn't strictly necessary, int c[32] would suffice - for most practical purposes */ - int d, i, t, *c = calloc(n, sizeof(int)); - - /* curiously, with GCC 4.6.1 -O3, removing next line makes - it ~25% slower */ - if (callback) callback(x, n); - for (d = 1; ; c[d]++) { - while (d > 1) c[--d] = 0; - while (c[d] >= d) - if (++d >= n) goto done; - - t = x[ i = (d & 1) ? c[d] : 0 ], x[i] = x[d], x[d] = t; - if (callback) callback(x, n); - } -done: free(c); -} - -#define N 4 - -int main() -{ - int i, x[N]; - for (i = 0; i < N; i++) x[i] = i + 1; - - /* three different methods */ - perm1(x, N, show); - perm2(x, N, show); - perm3(x, N, show); - - return 0; -} diff --git a/Task/Permutations/EasyLang/permutations.easy b/Task/Permutations/EasyLang/permutations.easy index cadd9844a5..7144ec6808 100644 --- a/Task/Permutations/EasyLang/permutations.easy +++ b/Task/Permutations/EasyLang/permutations.easy @@ -1,4 +1,4 @@ -proc permlist k . list[] . +proc permlist k &list[] . if k = len list[] print list[] return diff --git a/Task/Permutations/K/permutations-4.k b/Task/Permutations/K/permutations-4.k index cb244368a1..7dc2fb607f 100644 --- a/Task/Permutations/K/permutations-4.k +++ b/Task/Permutations/K/permutations-4.k @@ -1,5 +1,5 @@ prm:{$[x~*x;;:x@o@#x];(x-1){,/'((,(#*x)##x),x)m*(!l)+&\m:~=l:1+#x}/0} -perm:{x[prm[#x]] +perm:{x[prm[#x]]} perm[" "\"some random text"] (("text";"text";"random";"some";"random";"some") diff --git a/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx b/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx index db31ab7b0b..878d9c865f 100644 --- a/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx +++ b/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx @@ -1,32 +1,39 @@ -/*REXX program computes and displays a number (and also a range) of pernicious numbers.*/ -numeric digits 100 /*be able to handle large numbers. */ -parse arg N L H . /*obtain optional arguments from the CL*/ -if N=='' | N==',' then N=25 /*N not given? Then use the default. */ -if L=='' | L==',' then L=888888877 /*L " " " " " " */ -if H=='' | H==',' then H=888888888 /*H " " " " " " */ -say 'The 1st ' N " pernicious numbers are:" /*display a nice title for the numbers.*/ -say pernicious(1,,N) /*get all pernicious # from 1 ─~─► N. */ -say /*display a blank line for a separator.*/ -say 'Pernicious numbers between ' L " and " H ' (inclusive) are:' -say pernicious(L,H) /*get all pernicious # from L ───► H. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -pernicious: procedure; parse arg bot,top,lim /*obtain the bot and top numbers, limit*/ - p='2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101' - @.=0 - do k=1 until _=='' /*examine the list of some low primes.*/ - _=word(p, k); @._=1 /*generate an array " " " " */ - end /*k*/ - $= /*list of pernicious numbers (so far). */ - if m=='' then m=999999999 /*Not given? Then use a gihugic limit.*/ - if top=='' then top=999999999 /* " " " " " " " */ - #=0 /*number of pernicious numbers (so far)*/ - do j=bot to top until #==lim /*generate pernicious #s 'til satisfied*/ - pc=popCount(j) /*obtain the population count for J. */ - if \@.pc then iterate /*if popCount not in @.prime, skip it.*/ - $=$ j /*append a pernicious number to list. */ - #=#+1 /*bump the pernicious number count. */ - end /*j*/ - return substr($, 2) /*return the results, sans 1st blank. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -popCount: return length( space( translate( x2b( d2x(arg(1))) +0,, 0), 0)) /*count 1's.*/ +-- 8 May 2025 +include Settings + +say 'PERNICIOUS NUMBERS' +say version +say +numeric digits 100 +call Show 1,36 +call Show 888888877,888888888 +exit + +Show: +procedure +call Time('r') +arg xx,yy +if yy = '' then + yy = xx +interpret 'xx =' xx'+0'; interpret 'yy =' yy'+0' +say 'Pernicious numbers between' xx 'and' yy'...' +say +n = 0 +do i = xx to yy + if Prime(Digitsum(Basenn(i,2))) then do + n = n+1 + call Charout ,i' ' + if n//10 = 0 then + say + end +end +say +say n 'such numbers found' +say Format(Time('e'),,3) 'seconds' +say +return + +include Numbers +include Functions +include Special +include Abend diff --git a/Task/Phrase-reversals/Crystal/phrase-reversals.cr b/Task/Phrase-reversals/Crystal/phrase-reversals.cr new file mode 100644 index 0000000000..b8366f5d52 --- /dev/null +++ b/Task/Phrase-reversals/Crystal/phrase-reversals.cr @@ -0,0 +1,5 @@ +str = "rosetta code phrase reversal" + +puts str.reverse # Reversed string. +puts str.split.map(&.reverse).join(" ") # Words reversed. +puts str.split.reverse.join(" ") # Word order reversed. diff --git a/Task/Pi/Atari-BASIC/pi.basic b/Task/Pi/Atari-BASIC/pi.basic new file mode 100644 index 0000000000..f7765e435b --- /dev/null +++ b/Task/Pi/Atari-BASIC/pi.basic @@ -0,0 +1,51 @@ +10 REM ADOPTED FROM COMMODORE BASIC +20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION +30 LN = INT(10*N/3)+16 +40 ND = 1 +50 DIM A(LN) +60 N9 = 0 +70 PD = 0:REM FIRST PRE-DIGIT IS A 0 +80 REM +90 FOR J = 1 TO LN +100 A(J-1) = 2:REM START WITH 2S +110 NEXT J +120 REM +130 FOR J = 1 TO N +140 Q = 0 +150 FOR I = LN TO 1 STEP -1:REM WORK BACKWARDS +160 X = 10*A(I-1) + Q*I +170 A(I-1) = X - (2*I-1)*INT(X/(2*I-1)):REM X - INT ( X / Y) * Y +180 Q = INT(X/(2*I - 1)) +190 NEXT I +200 A(0) = Q-10*INT(Q/10) +210 Q = INT(Q/10) +220 IF Q=9 THEN N9 = N9 + 1: GOTO 450 +240 IF Q<>10 THEN GOTO 350 +250 REM Q == 10 +260 D = PD+1: GOSUB 500 +270 IF N9 <= 0 THEN GOTO 320 +280 FOR K = 1 TO N9 +290 D = 0: GOSUB 500 +300 NEXT K +310 REM END IF +320 PD = 0 +330 N9 = 0 +335 GOTO 450 +340 REM Q <> 10 +350 D = PD: GOSUB 500 +360 PD = Q +370 IF N9 = 0 THEN GOTO 450 +380 FOR K = 1 TO N9 +390 D = 9: GOSUB 500 +400 NEXT K +410 N9 = 0 +450 NEXT J +460 PRINT PD +470 END +480 REM +490 REM OUTPUT DIGITS +500 IF ND=0 THEN PRINT D;: RETURN +510 IF D=0 THEN RETURN +520 PRINT D;"."; +530 ND = 0 +550 RETURN diff --git a/Task/Pick-random-element/Zig/pick-random-element.zig b/Task/Pick-random-element/Zig/pick-random-element.zig index 2cccbfd088..d5a019e88e 100644 --- a/Task/Pick-random-element/Zig/pick-random-element.zig +++ b/Task/Pick-random-element/Zig/pick-random-element.zig @@ -1,11 +1,11 @@ const std = @import("std"); const debug = std.debug; -const rand = std.rand; +const rand = std.Random; const time = std.time; -test "pick random element" { - var pcg = rand.Pcg.init(time.milliTimestamp()); +pub fn main() void { + var pcg = rand.Pcg.init(@intCast(time.milliTimestamp())); const chars = [_]u8{ 'A', 'B', 'C', 'D', @@ -18,13 +18,13 @@ test "pick random element" { '<', '>', '(', ')', }; - var i: usize = 0; - while (i < 32) : (i += 1) { + + for(0..32) |i| { if (i % 4 == 0) { - debug.warn("\n ", .{}); + debug.print("\n ", .{}); } - debug.warn("'{c}', ", .{chars[pcg.random.int(usize) % chars.len]}); + debug.print("'{c}', ", .{chars[pcg.random().uintLessThan(usize, chars.len)]}); } - debug.warn("\n", .{}); + debug.print("\n", .{}); } diff --git a/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx b/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx new file mode 100644 index 0000000000..9893ca2589 --- /dev/null +++ b/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx @@ -0,0 +1,76 @@ +-- 11 Apr 2025 +include Settings + +call Time('r') +say 'PIERPOINT PRIMES (BRUTE FORCE)' +say version +say +numeric digits 40 +call GetPierpont +call Sort 'firs.' +call Sort 'seco.' +call ShowPierpont +say Format(Time('e'),,3) 'seconds'; say +exit + +GetPierpont: +procedure expose firs. glob. seco. +say 'Get Pierpont primes...' +n1 = 0; firs. = 0; n2 = 0; seco. = 0 +p = 0; m = 1e40 +do u = 0 to 120 + a = 2**u + if a > m then + leave u + do v = 0 to 80 + b = 3**v + if b > m then + iterate u + px = a*b + if px > m then + iterate v + p1 = px+1; p = p+1 + if Prime(p1) then do + n1 = n1+1; firs.n1 = p1 + end + p2 = px-1; p = p+1 + if Prime(p2) then do + n2 = n2+1; seco.n2 = p2 + end + end +end +firs.0 = n1; seco.0 = n2 +say p 'primality tests performed' +say n1 'numbers of the first kind generated' +say n2 'numbers of the second kind generated' +say +return + +ShowPierpont: +procedure expose firs. seco. +say 'Pierpont primes of the first kind nos 1 thru 50...' +do i = 1 to 50 + call Charout, Right(firs.i,9) + if i//10 = 0 then + say +end +say +say 'Pierpont primes of the second kind nos 1 thru 50...' +do i = 1 to 50 + call Charout, Right(seco.i,9) + if i//10 = 0 then + say +end +say +say 'Pierpont prime of the first kind no 250...' +say firs.250 +say +say 'Pierpont prime of the second kind no 250...' +say seco.250 +say +return + +include Numbers +include Functions +include Helper +include Abend diff --git a/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx b/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx new file mode 100644 index 0000000000..c6f72e9921 --- /dev/null +++ b/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx @@ -0,0 +1,72 @@ +-- 11 Apr 2025 +include Settings + +call Time('r') +say 'PIERPOINT PRIMES (USING 3-SMOOTH NUMBERS)' +say version +say +numeric digits 40 +call GetSmooth +call GetPierpont +call ShowPierpont +say Format(Time('e'),,3) 'seconds'; say +exit + +GetSmooth: +procedure expose prim. smoo. +say 'Get 3-smooth numbers up to 10^40...' +n = Smooths(1e40,3) +say n '3-smooth numbers generated' +say +return + +GetPierpont: +procedure expose smoo. firs. seco. glob. +say 'Get Pierpont primes...' +n1 = 0; firs. = 0; n2 = 0; seco. = 0; p = 0 +do i = 1 to smoo.0 + p1 = smoo.i+1; p = p+1 + if Prime(p1) then do + n1 = n1+1; firs.n1 = p1 + end + p2 = smoo.i-1; p = p+1 + if Prime(p2) then do + n2 = n2+1; seco.n2 = p2 + end +end +firs.0 = n1; seco.0 = n2 +say p 'primality tests performed' +say n1 'numbers of the first kind generated' +say n2 'numbers of the second kind generated' +say +return + +ShowPierpont: +procedure expose firs. seco. +say 'Pierpont primes of the first kind nos 1 thru 50...' +do i = 1 to 50 + call Charout, Right(firs.i,9) + if i//10 = 0 then + say +end +say +say 'Pierpont primes of the second kind nos 1 thru 50...' +do i = 1 to 50 + call Charout, Right(seco.i,9) + if i//10 = 0 then + say +end +say +say 'Pierpont prime of the first kind no 250...' +say firs.250 +say +say 'Pierpont prime of the second kind no 250...' +say seco.250 +say +return + +include Numbers +include Constants +include Sequences +include Functions +include Abend diff --git a/Task/Pierpont-primes/REXX/pierpont-primes.rexx b/Task/Pierpont-primes/REXX/pierpont-primes.rexx deleted file mode 100644 index 1a751c2c12..0000000000 --- a/Task/Pierpont-primes/REXX/pierpont-primes.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program finds and displays Pierpont primes of the first and second kinds. */ -parse arg n . /*obtain optional argument from the CL.*/ -if n=='' | n=="," then n= 50 /*Not specified? Then use the default.*/ -numeric digits n /*ensure enough decimal digs (bit int).*/ -big= copies(9, digits() ) /*BIG: used as a max number (a limit).*/ -@.= '2nd'; @.1= '1st' - do t=1 to -1 by -2; usum= 0; vsum= 0; s= 0 /*T is 1, then -1.*/ - #= 0 /*number of Pierpont primes (so far). */ - $=; do j=0 until #>=n /*$: the list " " " " */ - if usum<=s then usum= get(2, 3); if vsum<=s then vsum= get(3, 2) - s= min(vsum, usum); if \isPrime(s) then iterate /*get min; Not prime? */ - #= # + 1; $= $ s /*bump counter; append.*/ - end /*j*/ - say - w= length(word($, #) ) /*biggest prime length.*/ - say center(n " Pierpont primes of the " @.t ' kind', max(10 *(w+1), 80), "═") - - do p=1 by 10 to #; _=; do k=p for 10; _= _ right( word($, k), w) - end /*k*/ - if _\=='' then say substr( strip(_, "T"), 2) - end /*p*/ - end /*t*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x '' -1 _; if x<17 then return wordpos(x,"2 3 5 7 11 13")>0 - if _==5 then return 0; if x//2==0 then return 0 /*not prime. */ - if x//3==0 then return 0; if x//7==0 then return 0 /* " " */ - do j=11 by 6 until j*j>x /*skip ÷ 3's.*/ - if x//j==0 then return 0; if x//(j+2)==0 then return 0 /*not prime. */ - end /*j*/; return 1 /*it's prime.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -get: parse arg c1,c2; m=big; do ju=0; pu= c1**ju; if pu+t>s then return min(m, pu+t) - do jv=0; pv= c2**jv; if pv >s then iterate ju - _= pu*pv + t; if _ >s then m= min(_, m) - end /*jv*/ - end /*ju*/ /*see the RETURN (above). */ diff --git a/Task/Pig-the-dice-game/EasyLang/pig-the-dice-game.easy b/Task/Pig-the-dice-game/EasyLang/pig-the-dice-game.easy index 6cab7a1c42..924d58c02c 100644 --- a/Task/Pig-the-dice-game/EasyLang/pig-the-dice-game.easy +++ b/Task/Pig-the-dice-game/EasyLang/pig-the-dice-game.easy @@ -5,56 +5,48 @@ subr initvars sum[] = [ 0 0 ] player = 1 . -proc btn x y txt$ . . - color 666 - linewidth 18 - move x y - line x + 15 y - move x - 4 y - 3 - color 000 - textsize 10 - text txt$ +proc btn x y txt$ . + gcolor 666 + glinewidth 18 + gline x y x + 15 y + gcolor 000 + gtextsize 10 + gtext x - 4 y - 3 txt$ . -proc show . . - background col[player] - clear - move 8 78 - color 000 - textsize 10 - text "Player-" & player - textsize 8 - move 8 66 - text "Total: " & sum[player] - textsize 5 +proc show . + gbackground col[player] + gclear + gcolor 000 + gtextsize 10 + gtext 8 78 "Player-" & player + gtextsize 8 + gtext 8 66 "Total: " & sum[player] + gtextsize 5 # h = 3 - player - color col[h] - move 65 63 - rect 30 19 - move 68 74 - color 000 - text "Player-" & h - textsize 4 - move 68 67 - text "Total: " & sum[h] + gcolor col[h] + grect 65 63 30 19 + gcolor 000 + gtext 68 74 "Player-" & h + gtextsize 4 + gtext 68 67 "Total: " & sum[h] # btn 20 20 "Roll" btn 70 20 "Hold" . -proc nxtplayer . . +proc nxtplayer . sum[player] += sum if sum > 0 sum = 0 show . - move 10 92 - textsize 7 - color 000 + gtextsize 7 + gcolor 000 if sum[player] >= 100 - text "You won !" + gtext 10 92 "You won !" stat = 3 else - text "Switch player ..." + gtext 10 92 "Switch player ..." player = 3 - player stat = 2 . @@ -64,28 +56,25 @@ on timer if stat = 1 # roll if tmcnt = 0 - move 44 37 - color col[player] - rect 30 10 + gcolor col[player] + grect 44 34 30 13 if dice > 1 sum += dice stat = 0 else sum = 0 . - color 000 - text sum + gcolor 000 + gtext 44 37 sum if dice = 1 nxtplayer . else - color 555 - move 24 34 - rect 13 13 - color 000 - move 27 37 + gcolor 555 + grect 24 34 13 13 + gcolor 000 dice = random 6 - text dice + gtext 27 37 dice tmcnt -= 1 if tmcnt = 0 timer 0.5 @@ -97,19 +86,17 @@ on timer stat = 0 show elif stat = 3 - move 0 0 - color col[player] - rect 100 30 - color 000 - move 10 30 - text "Click for new game" + gcolor col[player] + grect 0 0 100 30 + gcolor 000 + gtext 10 30 "Click for new game" stat = 4 . . -proc roll . . +proc roll . stat = 1 tmcnt = 10 - textsize 10 + gtextsize 10 timer 0 . on mouse_down diff --git a/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy b/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy index 50ccee3074..c861a920d8 100644 --- a/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy +++ b/Task/Pinstripe-Display/EasyLang/pinstripe-display.easy @@ -2,9 +2,8 @@ for i = 1 to 4 col = 000 y = 100 - i * 25 for x = 0 step i / 4 to 100 - i / 4 - color col - move x y - rect i / 4 25 + gcolor col + grect x y i / 4 25 col = 999 - col . . diff --git a/Task/Pisano-period/EasyLang/pisano-period.easy b/Task/Pisano-period/EasyLang/pisano-period.easy index ba4646f7bd..bce914c4fe 100644 --- a/Task/Pisano-period/EasyLang/pisano-period.easy +++ b/Task/Pisano-period/EasyLang/pisano-period.easy @@ -1,33 +1,23 @@ fastfunc isprim num . if num mod 2 = 0 - if num = 2 - return 1 - . + if num = 2 : return 1 return 0 . if num mod 3 = 0 - if num = 3 - return 1 - . + if num = 3 : return 1 return 0 . i = 5 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 4 . return 1 . func gcd a b . - if b = 0 - return a - . + if b = 0 : return a return gcd b (a mod b) . func lcm a b . @@ -36,15 +26,13 @@ func lcm a b . func ipow x p . prod = 1 while p > 0 - if p mod 2 = 1 - prod *= x - . + if p mod 2 = 1 : prod *= x p = p div 2 x *= x . return prod . -proc getprims n . prims[] . +proc getprims n &prims[] . prims[] = [ ] for i = 2 to n d = n / i @@ -67,16 +55,12 @@ func pisanoPeriod m . for i = 1 to m * m swap p c c = (p + c) mod m - if p = 0 and c = 1 - return i - . + if p = 0 and c = 1 : return i . return 1 . func pisanoPrime p k . - if isprim p = 0 or k = 0 - return 0 - . + if isprim p = 0 or k = 0 : return 0 return ipow p (k - 1) * pisanoPeriod p . func pisano m . @@ -84,40 +68,30 @@ func pisano m . for i = 1 step 2 to len p[] - 1 pps[] &= pisanoPrime p[i] p[i + 1] . - if len pps[] = 0 - return 1 - . - if len pps[] = 1 - return pps[1] - . + if len pps[] = 0 : return 1 + if len pps[] = 1 : return pps[1] f = pps[1] for i = 2 to len pps[] f = lcm f pps[i] . return f . -proc main . . +proc main . for p = 2 to 14 pp = pisanoPrime p 2 - if pp > 0 - print "pisanoPrime(" & p & ": 2) = " & pp - . + if pp > 0 : print "pisanoPrime(" & p & ": 2) = " & pp . print "" for p = 2 to 179 pp = pisanoPrime p 1 - if pp > 0 - print "pisanoPrime(" & p & ": 1) = " & pp - . + if pp > 0 : print "pisanoPrime(" & p & ": 1) = " & pp . print "" - numfmt 0 3 + numfmt 3 0 print "pisano(n) for integers 'n' from 1 to 180 are:" for n = 1 to 180 write pisano (n) & " " - if n mod 15 = 0 - print "" - . + if n mod 15 = 0 : print "" . . main diff --git a/Task/Pisano-period/REXX/pisano-period.rexx b/Task/Pisano-period/REXX/pisano-period.rexx index f2141bb1ab..dcdf9efc2f 100644 --- a/Task/Pisano-period/REXX/pisano-period.rexx +++ b/Task/Pisano-period/REXX/pisano-period.rexx @@ -1,37 +1,70 @@ -/*REXX pgm calculates pisano period for a range of N, and pisanoPrime(N,m) [for primes]*/ -numeric digits 500 /*ensure enough decimal digits for Fib.*/ -parse arg lim.1 lim.2 lim.3 . /*obtain optional arguments from the CL*/ -if lim.1=='' | lim.1=="," then lim.1= 15 - 1 /*Not specified? Then use the default.*/ -if lim.2=='' | lim.2=="," then lim.2= 180 - 1 /* " " " " " " */ -if lim.3=='' | lim.3=="," then lim.3= 180 /* " " " " " " */ -call Fib /* " " Fibonacci numbers. */ - do i=1 for max(lim.1, lim.2, lim.3); call pisano(i) /*find pisano periods.*/ - end /*i*/; w= length(i) +-- 26 Mar 2025 +include Settings +call Time('r') +numeric digits 500 - do j=1 for 2; #= word(2 1, j) - do p=1 for lim.j; if \isPrime(p) then iterate /*Not prime? Skip this number.*/ - say ' pisanoPrime('right(p, w)", "#') = 'right( pisanoPrime(p, #), 5) - end /*p*/; say - end /*j*/ +say 'PISANO PERIOD' +say version +say +call GetFibo 1000 +call ShowPisanoPrime 15,2 +call ShowPisanoPrime 180,1 +call ShowPisano 180 +say Format(Time('e'),,3) 'seconds'; say +exit -say center(' pisano numbers for 1──►'lim.3" ", 20*4 - 1, "═") /*display a title.*/ -$= - do j=1 for lim.3; $= $ right(@.j, w) /*append pisano number to the $ list.*/ - if j//20==0 then do; say substr($, 2); $=; end /*display 20 numbers to a line*/ - end /*j*/ - say substr($, 2) /*possible display any residuals──►term*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -fib: procedure expose fib.; parse arg x; fib.=.; if x=='' then x= 1000 - fib.0= 0; fib.1= 1; if fib.x\==. then return fib.x - do k=2 for x-1; a= k-1; b= k-2; fib.k= fib.a + fib.b - end /*k*/; return fib.k -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: parse arg n; if n<11 then return pos(n, '2 3 5 7')>0; if n//2==0 then return 0 - do k=3 by 2 while k*k<=n; if n//k==0 then return 0; end /*k*/; return 1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -pisano: procedure expose @. fib.; parse arg m; if m==1 then do; @.m=1; return 1; end - do k=1; _= k+1; if fib.k//m==0 & fib._//m==1 then leave - end /*k*/; @.m= k; return k -/*──────────────────────────────────────────────────────────────────────────────────────*/ -pisanoPrime: procedure expose @. fib.; parse arg m,n; return m**(n-1) * pisano(m) +GetFibo: +procedure expose fibo. +arg xx +say 'Get first' xx 'Fibonacci numbers...' +call Fibonaccis -xx +say fibo.0 'numbers found' +say +return + +ShowPisanoPrime: +procedure expose fibo. prim. +arg xx,yy +say 'Pisano primes for p^'yy'...' +do i = 1 to xx + if Prime(i) then + say 'PisanoPrime('i','yy') = ' Pisanoprime(i,yy) +end +say +return + +ShowPisano: +procedure expose fibo. prim. +arg xx +say 'Pisano(n) for n = 1...'xx'...' +do i = 1 to xx + call Charout ,Right(Pisano(i),5) + if i//10 = 0 then + say +end +say +return + +Pisanoprime: +procedure expose fibo. +arg xx,yy +return xx**(yy-1)*Pisano(xx) + +Pisano: +procedure expose fibo. +arg xx +if xx = 1 then + return 1 +do i = 1 + j = i+1 + if fibo.i//xx = 0 then + if fibo.j//xx = 1 then + leave i +end +return i + +include Sequences +include Numbers +include Functions +include Constants +include Abend diff --git a/Task/Plasma-effect/EasyLang/plasma-effect.easy b/Task/Plasma-effect/EasyLang/plasma-effect.easy index 42060fa850..6ced409589 100644 --- a/Task/Plasma-effect/EasyLang/plasma-effect.easy +++ b/Task/Plasma-effect/EasyLang/plasma-effect.easy @@ -1,6 +1,7 @@ # lodev.org/cgtutor/plasma.html (last example) func dist a b c d . - d1 = a - c ; d2 = b - d + d1 = a - c + d2 = b - d return 15 * sqrt (d1 * d1 + d2 * d2) . on animate @@ -11,9 +12,8 @@ on animate val += sin (dist x (y + time / 7) 75 50 * 1.2) val += sin dist x y 75 40 col = (val + 4) / 16 - color3 col col * 2 1 - col - move x y - rect 0.5 0.5 + gcolor3 col col * 2 1 - col + grect x y 0.5 0.5 . . time += 1 diff --git a/Task/Playfair-cipher/JavaScript/playfair-cipher.js b/Task/Playfair-cipher/JavaScript/playfair-cipher.js new file mode 100644 index 0000000000..5742a124b9 --- /dev/null +++ b/Task/Playfair-cipher/JavaScript/playfair-cipher.js @@ -0,0 +1,269 @@ +const readline = require('readline'); + +// Enum-like object for Playfair options +const playfairOption = { + NO_Q: 0, + I_EQUALS_J: 1, +}; + +// Represents the Playfair cipher state and methods +class Playfair { + constructor(keyword, pfo) { + this.keyword = keyword; + this.pfo = pfo; // playfairOption + this.table = Array(5).fill(null).map(() => Array(5).fill('')); // 5x5 table + } + + // Initializes the 5x5 Playfair table based on the keyword and option + init() { + const used = Array(26).fill(false); // Track used letters + if (this.pfo === playfairOption.NO_Q) { + used['Q'.charCodeAt(0) - 65] = true; // Q is used/omitted + } else { + used['J'.charCodeAt(0) - 65] = true; // J is used/replaced by I + } + + const alphabet = this.keyword.toUpperCase() + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + let row = 0; + let col = 0; + + for (const char of alphabet) { + const charCode = char.charCodeAt(0); + + // Check if it's a letter A-Z + if (charCode >= 'A'.charCodeAt(0) && charCode <= 'Z'.charCodeAt(0)) { + const charIndex = charCode - 65; // 0-25 index + + // Handle J if I_EQUALS_J option is selected + let charToUse = char; + let indexToUse = charIndex; + if (char === 'J' && this.pfo === playfairOption.I_EQUALS_J) { + charToUse = 'I'; + indexToUse = 'I'.charCodeAt(0) - 65; + } + + // Skip Q if NO_Q option is selected + if (charToUse === 'Q' && this.pfo === playfairOption.NO_Q) { + continue; + } + + + if (!used[indexToUse]) { + this.table[row][col] = charToUse; + used[indexToUse] = true; + col++; + if (col === 5) { + row++; + if (row === 5) { + break; // Table filled + } + col = 0; + } + } + } + } + } + + // Prepares the plaintext: uppercase, removes non-letters, + // handles Q/J based on option, inserts X between duplicate letters, + // pads with X/Z if length is odd. + getCleanText(plainText) { + plainText = plainText.toUpperCase(); + const cleanChars = []; + let prevChar = ''; // Use '' to indicate no previous character + + for (let i = 0; i < plainText.length; i++) { + let currentChar = plainText[i]; + const charCode = currentChar.charCodeAt(0); + + // Skip non-letters + if (charCode < 'A'.charCodeAt(0) || charCode > 'Z'.charCodeAt(0)) { + continue; + } + + // Handle J if I_EQUALS_J option is specified, replace J with I + if (currentChar === 'J' && this.pfo === playfairOption.I_EQUALS_J) { + currentChar = 'I'; + } + + // Skip Q if NO_Q option is specified (already handled in init, but good here too) + if (currentChar === 'Q' && this.pfo === playfairOption.NO_Q) { + continue; + } + + + // Insert 'X' between duplicate consecutive letters + // Only compare if prevChar is set (not the very first character) + if (prevChar !== '' && currentChar === prevChar) { + cleanChars.push('X'); + } + + cleanChars.push(currentChar); + prevChar = currentChar; // Store the character *after* potential X insertion + } + + // If length is odd, add a padding character + if (cleanChars.length % 2 === 1) { + // Add 'X' unless the last letter is 'X', then add 'Z' + if (cleanChars[cleanChars.length - 1] !== 'X') { + cleanChars.push('X'); + } else { + cleanChars.push('Z'); + } + } + + return cleanChars.join(''); + } + + // Finds the row and column of a character in the table + findChar(char) { + for (let i = 0; i < 5; i++) { + for (let j = 0; j < 5; j++) { + if (this.table[i][j] === char) { + return [i, j]; // Return [row, col] + } + } + } + return [-1, -1]; // Should not happen if getCleanText is correct + } + + // Encodes plaintext using the Playfair cipher + encode(plainText) { + const cleanText = this.getCleanText(plainText); + const cipherChars = []; + + for (let i = 0; i < cleanText.length; i += 2) { + const char1 = cleanText[i]; + const char2 = cleanText[i + 1]; // cleanText length is always even + const [row1, col1] = this.findChar(char1); + const [row2, col2] = this.findChar(char2); + + let encodedChar1, encodedChar2; + + if (row1 === row2) { // Same row + encodedChar1 = this.table[row1][(col1 + 1) % 5]; + encodedChar2 = this.table[row2][(col2 + 1) % 5]; + } else if (col1 === col2) { // Same column + encodedChar1 = this.table[(row1 + 1) % 5][col1]; + encodedChar2 = this.table[(row2 + 1) % 5][col2]; + } else { // Different row and column (rectangle) + encodedChar1 = this.table[row1][col2]; + encodedChar2 = this.table[row2][col1]; + } + + cipherChars.push(encodedChar1); + cipherChars.push(encodedChar2); + + // Add space after each digram, matching Go's output format + if (i + 2 < cleanText.length) { + cipherChars.push(' '); + } + } + + return cipherChars.join(''); + } + + // Decodes ciphertext using the Playfair cipher + decode(cipherText) { + // The Go code processes the ciphertext including spaces, + // stepping by 3. We'll do the same by stripping spaces first + // and then processing in pairs. This is conceptually simpler in JS. + // Or, we can replicate the Go loop that steps by 3. Let's replicate for exact match. + const decodedChars = []; + const l = cipherText.length; + + for (let i = 0; i < l; i += 3) { // Step by 3 due to spaces in encoded text + const char1 = cipherText[i]; + const char2 = cipherText[i + 1]; + // cipherText[i+2] will be a space, which findChar will correctly not find (-1, -1) + // But the Go code explicitly finds the *bytes* at i and i+1. Let's stick to that. + + // Ensure we only process valid character pairs + if (!char1 || !char2 || char1 === ' ' || char2 === ' ') { + // This shouldn't happen with the i+=3 loop structure if the input + // format from encode is followed, but good to be safe. + continue; + } + + + const [row1, col1] = this.findChar(char1); + const [row2, col2] = this.findChar(char2); + + let decodedChar1, decodedChar2; + + // Decoding rules are the reverse of encoding + if (row1 === row2) { // Same row + // Shift left: (col - 1 + 5) % 5 + decodedChar1 = this.table[row1][(col1 + 4) % 5]; + decodedChar2 = this.table[row2][(col2 + 4) % 5]; + } else if (col1 === col2) { // Same column + // Shift up: (row - 1 + 5) % 5 + decodedChar1 = this.table[(row1 + 4) % 5][col1]; + decodedChar2 = this.table[(row2 + 4) % 5][col2]; + } else { // Different row and column (rectangle) + decodedChar1 = this.table[row1][col2]; + decodedChar2 = this.table[row2][col1]; + } + + decodedChars.push(decodedChar1); + decodedChars.push(decodedChar2); + + // Add space after each digram in decoded text, matching Go's output format + if (i + 3 < l) { // Check if there's more content after the current digram+space + decodedChars.push(' '); + } + } + + return decodedChars.join(''); + } + + // Prints the 5x5 table to the console + printTable() { + console.log("The table to be used is :\n"); + for (let i = 0; i < 5; i++) { + console.log(this.table[i].join(' ')); // Join row elements with space + } + console.log(); // Add a blank line for spacing + } +} + +// Main execution function using async/await for readline +async function main() { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + + const question = (query) => new Promise((resolve) => rl.question(query, resolve)); + + try { + const keyword = await question("Enter Playfair keyword : "); + + let ignoreQ = ''; + while (ignoreQ !== "y" && ignoreQ !== "n") { + ignoreQ = (await question("Ignore Q when building table y/n : ")).toLowerCase(); + } + + const pfo = (ignoreQ === "y") ? playfairOption.NO_Q : playfairOption.I_EQUALS_J; + + const pf = new Playfair(keyword, pfo); + pf.init(); + pf.printTable(); + + const plainText = await question("\nEnter plain text : "); + + const encodedText = pf.encode(plainText); + console.log("\nEncoded text is :", encodedText); + + // The Go code decodes the encoded text *including* the spaces it added. + // Pass the encoded text as is to the decode function. + const decodedText = pf.decode(encodedText); + console.log("Decoded text is :", decodedText); + + } finally { + rl.close(); // Close the readline interface + } +} + +// Execute the main function +main(); diff --git a/Task/Playfair-cipher/Rust/playfair-cipher.rs b/Task/Playfair-cipher/Rust/playfair-cipher.rs new file mode 100644 index 0000000000..074935a132 --- /dev/null +++ b/Task/Playfair-cipher/Rust/playfair-cipher.rs @@ -0,0 +1,225 @@ +use std::io::{self, Write}; + +struct Playfair { + txt: String, + m: [[char; 5]; 5], +} + +impl Playfair { + fn new() -> Self { + Playfair { + txt: String::new(), + m: [[' '; 5]; 5], + } + } + + fn do_it(&mut self, k: &str, t: &str, ij: bool, e: bool) { + self.create_grid(k, ij); + self.get_text_ready(t, ij, e); + + if e { + self.process(1); + } else { + self.process(-1); + } + + self.display(); + } + + fn process(&mut self, dir: i32) { + let mut ntxt = String::new(); + let mut chars = self.txt.chars().collect::>(); + let mut i = 0; + + while i < chars.len() { + if i + 1 >= chars.len() { + break; + } + + let mut a = 0; + let mut b = 0; + let mut c = 0; + let mut d = 0; + + if self.get_char_pos(chars[i], &mut a, &mut b) && + self.get_char_pos(chars[i+1], &mut c, &mut d) { + if a == c { + ntxt.push(self.get_char(a, b + dir)); + ntxt.push(self.get_char(c, d + dir)); + } else if b == d { + ntxt.push(self.get_char(a + dir, b)); + ntxt.push(self.get_char(c + dir, d)); + } else { + ntxt.push(self.get_char(c, b)); + ntxt.push(self.get_char(a, d)); + } + } + + i += 2; + } + + self.txt = ntxt; + } + + fn display(&self) { + println!("\n\n OUTPUT:\n========="); + let chars = self.txt.chars().collect::>(); + let mut cnt = 0; + let mut i = 0; + + while i < chars.len() { + if i + 1 < chars.len() { + print!("{}{} ", chars[i], chars[i+1]); + i += 2; + cnt += 1; + + if cnt >= 26 { + println!(); + cnt = 0; + } + } else { + print!("{}", chars[i]); + i += 1; + } + } + + println!("\n"); + } + + fn get_char(&self, a: i32, b: i32) -> char { + let row = ((b + 5) % 5) as usize; + let col = ((a + 5) % 5) as usize; + self.m[row][col] + } + + fn get_char_pos(&self, l: char, a: &mut i32, b: &mut i32) -> bool { + for y in 0..5 { + for x in 0..5 { + if self.m[y][x] == l { + *a = x as i32; + *b = y as i32; + return true; + } + } + } + false + } + + fn get_text_ready(&mut self, t: &str, ij: bool, e: bool) { + self.txt.clear(); + + for c in t.chars() { + let c_upper = c.to_ascii_uppercase(); + + if c_upper < 'A' || c_upper > 'Z' { + continue; + } + + if c_upper == 'J' && ij { + self.txt.push('I'); + } else if c_upper == 'Q' && !ij { + continue; + } else { + self.txt.push(c_upper); + } + } + + if e { + let mut ntxt = String::new(); + let chars = self.txt.chars().collect::>(); + let len = chars.len(); + + let mut x = 0; + while x < len { + ntxt.push(chars[x]); + + if x + 1 < len { + if chars[x] == chars[x + 1] { + ntxt.push('X'); + } + ntxt.push(chars[x + 1]); + } + + x += 2; + } + + self.txt = ntxt; + } + + if self.txt.len() % 2 == 1 { + self.txt.push('X'); + } + } + + fn create_grid(&mut self, k: &str, ij: bool) { + let mut key = k.to_string(); + if key.is_empty() { + key = "KEYWORD".to_string(); + } + + key.push_str("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + let mut nk = String::new(); + + for c in key.chars() { + let c_upper = c.to_ascii_uppercase(); + + if c_upper < 'A' || c_upper > 'Z' { + continue; + } + + if (c_upper == 'J' && ij) || (c_upper == 'Q' && !ij) { + continue; + } + + if !nk.contains(c_upper) { + nk.push(c_upper); + } + } + + let mut idx = 0; + for y in 0..5 { + for x in 0..5 { + if idx < nk.len() { + self.m[y][x] = nk.chars().nth(idx).unwrap(); + idx += 1; + } + } + } + } +} + +fn main() -> io::Result<()> { + let mut input = String::new(); + + print!("(E)ncode or (D)ecode? "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let e = input.trim().to_lowercase().starts_with('e'); + + input.clear(); + print!("Enter a en/decryption key: "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let key = input.trim().to_string(); + + input.clear(); + print!("I <-> J (Y/N): "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let ij = input.trim().to_lowercase().starts_with('y'); + + input.clear(); + print!("Enter the text: "); + io::stdout().flush()?; + io::stdin().read_line(&mut input)?; + let txt = input.trim().to_string(); + + let mut pf = Playfair::new(); + pf.do_it(&key, &txt, ij, e); + + println!("Press Enter to continue..."); + input.clear(); + io::stdin().read_line(&mut input)?; + + Ok(()) +} diff --git a/Task/Playing-cards/EasyLang/playing-cards.easy b/Task/Playing-cards/EasyLang/playing-cards.easy index 05e4bb79ff..c2c5a56b1d 100644 --- a/Task/Playing-cards/EasyLang/playing-cards.easy +++ b/Task/Playing-cards/EasyLang/playing-cards.easy @@ -1,9 +1,7 @@ global deck[] top . -proc new . . +proc new . deck[] = [ ] - for i to 52 - deck[] &= i - . + for i to 52 : deck[] &= i top = 52 . suit$[] = [ "♠" "♦" "♥" "♣" ] @@ -11,14 +9,12 @@ val$[] = [ 2 3 4 5 6 7 8 9 10 "J" "Q" "K" "A" ] func$ name card . return suit$[card mod1 4] & val$[card div1 4] . -proc show . . - for i to top - write name deck[i] & " " - . +proc show . + for i to top : write name deck[i] & " " print "" print "" . -proc shuffle . . +proc shuffle . for i = 52 downto 2 r = random i swap deck[i] deck[r] diff --git a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy index e6f2741331..2d3e711232 100644 --- a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy +++ b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy @@ -1,38 +1,30 @@ x[] = [ 0 1 2 3 4 5 6 7 8 9 ] y[] = [ 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 ] # -clear -linewidth 0.5 -move 10 97 -line 10 5 -line 95 5 -textsize 3 +gclear +glinewidth 0.5 +gline 10 5 10 97 +gline 10 5 95 5 +gtextsize 3 n = len x[] -m = 0 for i = 1 to n - if y[i] > m - m = y[i] - . -. -linewidth 0.1 -sty = m div 9 -for i range0 10 - move 10 5 + i * 10 - line 95 5 + i * 10 - move 2 4 + i * 10 - text i * sty + max = higher y[i] max . +glinewidth 0.1 +sty = max div 9 stx = x[n] div 9 for i range0 10 - move i * 9 + 10 5 - line i * 9 + 10 97 - move i * 9 + 10 1 - text i * stx + gline 10 5 + i * 10 95 5 + i * 10 + gtext 2 4 + i * 10 i * sty + gline i * 9 + 10 5 i * 9 + 10 97 + gtext i * 9 + 10 1 i * stx . color 900 linewidth 0.5 for i = 1 to n + xp = x + yp = y x = x[i] * 9 / stx + 10 y = y[i] / sty * 10 + 5 - line x y + if i > 1 : gline xp yp x y . diff --git a/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx b/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx index ecba80277b..5846bb92c0 100644 --- a/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx +++ b/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx @@ -1,5 +1,8 @@ include Settings -say version; say 'Polynomial long division'; say + +say 'POLYNOMIAL LONG DIVISION - 2 Mar 2025' +say version +say call Divide '1 -12 0 -42','1 -3' call Divide '5 4 1','2 3' call Divide '5 0 0 4 0 0 0 0 0 0 1','2 0 2 0 3' diff --git a/Task/Polynomial-regression/EasyLang/polynomial-regression.easy b/Task/Polynomial-regression/EasyLang/polynomial-regression.easy index 8bd9ec21df..c608f605c7 100644 --- a/Task/Polynomial-regression/EasyLang/polynomial-regression.easy +++ b/Task/Polynomial-regression/EasyLang/polynomial-regression.easy @@ -1,7 +1,7 @@ func eval a b c x . return a + (b + c * x) * x . -proc regression xa[] ya[] . . +proc regression xa[] ya[] . n = len xa[] for i = 1 to n xm = xm + xa[i] @@ -30,7 +30,7 @@ proc regression xa[] ya[] . . c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) a = ym - b * xm - c * x2m print "y = " & a & " + " & b & "x + " & c & "x^2" - numfmt 0 3 + numfmt 3 0 for i = 1 to n print xa[i] & " " & ya[i] & " " & eval a b c xa[i] . diff --git a/Task/Polynomial-regression/Rust/polynomial-regression.rs b/Task/Polynomial-regression/Rust/polynomial-regression.rs new file mode 100644 index 0000000000..5d1857e848 --- /dev/null +++ b/Task/Polynomial-regression/Rust/polynomial-regression.rs @@ -0,0 +1,41 @@ +fn poly_regression(x: &[i32], y: &[i32]) { + let n = x.len(); + let r: Vec = (0..n as i32).collect(); + + let xm = x.iter().sum::() as f64 / x.len() as f64; + let ym = y.iter().sum::() as f64 / y.len() as f64; + let x2m: f64 = r.iter().map(|&a| (a * a) as f64).sum::() / r.len() as f64; + let x3m: f64 = r.iter().map(|&a| (a * a * a) as f64).sum::() / r.len() as f64; + let x4m: f64 = r.iter().map(|&a| (a * a * a * a) as f64).sum::() / r.len() as f64; + + let xym: f64 = x.iter().zip(y.iter()).map(|(&a, &b)| (a as f64) * (b as f64)).sum::() / x.len().min(y.len()) as f64; + + let x2ym: f64 = x.iter().zip(y.iter()).map(|(&a, &b)| (a * a) as f64 * (b as f64)).sum::() / x.len().min(y.len()) as f64; + + let sxx = x2m - xm * xm; + let sxy = xym - xm * ym; + let sxx2 = x3m - xm * x2m; + let sx2x2 = x4m - x2m * x2m; + let sx2y = x2ym - x2m * ym; + + let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + let a = ym - b * xm - c * x2m; + + let abc = |xx: i32| a + b * (xx as f64) + c * (xx * xx) as f64; + + println!("y = {} + {}x + {}x^2", a, b, c); + println!(" Input Approximation"); + println!(" x y y1"); + + for (&x_val, &y_val) in x.iter().zip(y.iter()) { + println!("{:2} {:3} {:5.1}", x_val, y_val, abc(x_val)); + } +} + +fn main() { + let x: Vec = (0..11).collect(); + let y: Vec = vec![1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; + + poly_regression(&x, &y); +} diff --git a/Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 b/Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 new file mode 100644 index 0000000000..e21bbb84cb --- /dev/null +++ b/Task/Polynomial-regression/XPL0/polynomial-regression.xpl0 @@ -0,0 +1,60 @@ +proc PolyReg(XA, YA, N); +real XA, YA; int N; +int I; +real XM, YM, X2M, X3M, X4M, XYM, X2YM; +real SXX, SXY, SXX2, SX2X2, SX2Y; +real A, B, C, Y, RN; +[XM:= 0.; YM:= 0.; +X2M:= 0.; X3M:= 0.; X4M:= 0.; +XYM:= 0.; X2YM:= 0.; +for I:= 0 to N-1 do + [XM:= XM + XA(I); + YM:= YM + YA(I); + X2M:= X2M + XA(I)*XA(I); + X3M:= X3M + XA(I)*XA(I)*XA(I); + X4M:= X4M + XA(I)*XA(I)*XA(I)*XA(I); + XYM:= XYM + XA(I)*YA(I); + X2YM:= X2YM + XA(I)*XA(I)*YA(I); + ]; +RN:= float(N); +XM:= XM/RN; +YM:= YM/RN; +X2M:= X2M/RN; +X3M:= X3M/RN; +X4M:= X4M/RN; +XYM:= XYM/RN; +X2YM:= X2YM/RN; + +SXX:= X2M - XM*XM; +SXY:= XYM - XM*YM; +SXX2:= X3M - XM*X2M; +SX2X2:= X4M - X2M*X2M; +SX2Y:= X2YM - X2M*YM; + +B:= (SXY*SX2X2 - SX2Y*SXX2) / (SXX*SX2X2 - SXX2*SXX2); +C:= (SX2Y*SXX - SXY*SXX2) / (SXX*SX2X2 - SXX2*SXX2); +A:= YM - B*XM - C*X2M; + +Format(1, 0); +Text(0, "y = "); RlOut(0, A); +Text(0, " + "); RlOut(0, B); +Text(0, "x + "); RlOut(0, C); +Text(0, "x^^2"); CrLf(0); +Text(0, " Input Approx^m^j"); +Text(0, " x y y1^m^j"); +for I:=0 to N-1 do + [Format(3, 0); + RlOut(0, XA(I)); Text(0, " "); + RlOut(0, YA(I)); Text(0, " "); + Y:= A + (B + C*XA(I)) * XA(I); + Format(3, 1); + RlOut(0, Y); + CrLf(0); + ]; +]; + +real XA, YA; +[XA:= [0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]; + YA:= [1., 6., 17., 34., 57., 86., 121., 162., 209., 262., 321.]; +PolyReg(XA, YA, 11); +] diff --git a/Task/Polyspiral/EasyLang/polyspiral.easy b/Task/Polyspiral/EasyLang/polyspiral.easy index fc81a83df9..0a2d0116c7 100644 --- a/Task/Polyspiral/EasyLang/polyspiral.easy +++ b/Task/Polyspiral/EasyLang/polyspiral.easy @@ -1,19 +1,18 @@ -color 944 -linewidth 0.3 +gcolor 944 +glinewidth 0.3 on animate - clear + gclear incr = (incr + 0.05) mod 360 - x1 = 50 - y1 = 50 + x = 50 + y = 50 length = 1 angle = incr - move x1 y1 for i = 1 to 150 - x2 = x1 + cos angle * length - y2 = y1 + sin angle * length - line x2 y2 - x1 = x2 - y1 = y2 + xp = x + yp = y + x += cos angle * length + y += sin angle * length + gline xp yp x y length += 1 angle += incr . diff --git a/Task/Population-count/EasyLang/population-count.easy b/Task/Population-count/EasyLang/population-count.easy index 5d9bfc2c3b..74545e76a2 100644 --- a/Task/Population-count/EasyLang/population-count.easy +++ b/Task/Population-count/EasyLang/population-count.easy @@ -5,7 +5,7 @@ func popcnt x . . return r . -proc show3 . . +proc show3 . write "3^n:" bb = 1 for i = 1 to 30 @@ -14,7 +14,7 @@ proc show3 . . . print "" . -proc show s$ x . . +proc show s$ x . write s$ while n < 30 if popcnt i mod 2 = x diff --git a/Task/Power-set/Crystal/power-set.cr b/Task/Power-set/Crystal/power-set.cr new file mode 100644 index 0000000000..4e94945ee1 --- /dev/null +++ b/Task/Power-set/Crystal/power-set.cr @@ -0,0 +1,14 @@ +struct Set + def powerset + result = Set(typeof(self)).new + arr = to_a + (0..size).each do |n| + arr.each_combination(n, true) do |comb| + result << comb.to_set + end + end + result + end +end + +p [1, 2, 3, 4].to_set.powerset diff --git a/Task/Power-set/M2000-Interpreter/power-set.m2000 b/Task/Power-set/M2000-Interpreter/power-set.m2000 new file mode 100644 index 0000000000..6a9d634cd6 --- /dev/null +++ b/Task/Power-set/M2000-Interpreter/power-set.m2000 @@ -0,0 +1,72 @@ +Function ToStringSet { + if match("A") then + read SetA + else.if not empty then + SetA=Cons(array([])) + else + SetA=(,) + End if + k=each(SetA) + variant z + while k + z=Array(k) + if type$(z)="tuple" then + if len(Array(k))=0 then + data "∅" + else.if type$(z, 0)="tuple" then + data "{∅}" + else + data "{"+(Array(k)#str$(", "))+"}" + end if + else + data z + end if + end while + if len(SetA)=0 then + ="∅" + else + ="{"+Array([])#Str$(", ")+"}" + end if +} +Function PowerSet { + if match("A") then + read SetA + else.if not empty then + SetA=Cons(array([])) + else + SetA=(,) + End if + a$=string$("0",Len(SetA)) + p=lambda a$ -> { + boolean ok + if len(a$)=0 then ="": exit + for i=1 to len(A$) + if mid$(a$,i,1)="0" then insert i,1 a$="1": ok=true : exit else insert i,1 a$="0" + next + if ok then =a$ else ="" + } + if Len(setA)>1 then + setAll=("{}",) + else + setAll=((,),) + end if + do + z=p() + if len(z)=0 then exit + SetB=(,) + for i=1 to len(z) + if mid$(z, i,1)="1" then + SetB=SetB#end(SetA#Slice(i-1, i-1)) + end if + next + Append setAll, (SetB,) + always + =setAll +} +open dir$+"powerset.txt" for wide output as #f + Print #f, "P(";ToStringSet();")=";ToStringSet(PowerSet()) + Print #f, "P(";ToStringSet(PowerSet());")=";ToStringSet(PowerSet(PowerSet())) + Print #f, "P(";ToStringSet(1,2,3,4);")=";ToStringSet(PowerSet(1,2,3,4)) + Print #f, "P(";ToStringSet("A", "B");")=";ToStringSet(PowerSet("A", "B")) +close #f +win notepad.exe, dir$+"powerset.txt" diff --git a/Task/Power-set/Refal/power-set.refal b/Task/Power-set/Refal/power-set.refal new file mode 100644 index 0000000000..077d5098c5 --- /dev/null +++ b/Task/Power-set/Refal/power-set.refal @@ -0,0 +1,15 @@ +$ENTRY Go { + = > + > + >; +}; + +Powerset { + = (); + e.X t.I, : e.F = e.F ; +}; + +Append { + t.I = ; + t.I (e.X) e.Y = (e.X t.I) ; +}; diff --git a/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx b/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx index 732ea49377..7e3c3bfd7e 100644 --- a/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx +++ b/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx @@ -1,53 +1,74 @@ -/*REXX pgm tests for primality via Wilson's theorem: a # is prime if p divides (p-1)! +1*/ -parse arg LO zz /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 120 /*Not specified? Then use the default.*/ -if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 /*use default?*/ -sw= linesize() - 1; if sw<1 then sw= 79 /*obtain the terminal's screen width. */ -digs = digits() /*the current number of decimal digits.*/ -#= 0 /*number of (LO) primes found so far.*/ -!.= 1 /*placeholder for factorial memoization*/ -$= /* " to hold a list of primes.*/ - do p=1 until #=LO; oDigs= digs /*remember the number of decimal digits*/ - ?= isPrimeW(p) /*test primality using Wilson's theorem*/ - if digs>Odigs then numeric digits digs /*use larger number for decimal digits?*/ - if \? then iterate /*if not prime, then ignore this number*/ - #= # + 1; $= $ p /*bump prime counter; add prime to list*/ - end /*p*/ +-- 26 Mar 2025 +include Settings +numeric digits 10 -call show 'The first ' LO " prime numbers are:" -w= max( length(LO), length(word(reverse(zz),1))) /*used to align the number being tested*/ -@is.0= " isn't"; @is.1= 'is' /*2 literals used for display: is/ain't*/ +say 'PRIMALITY BY WILSON''S THEOREM' +say version say - do z=1 for words(zz); oDigs= digs /*remember the number of decimal digits*/ - p= word(zz, z) /*get a number from user─supplied list.*/ - ?= isPrimeW(p) /*test primality using Wilson's theorem*/ - if digs>Odigs then numeric digits digs /*use larger number for decimal digits?*/ - say right(p, max(w,length(p) ) ) @is.? "prime." - end /*z*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1 - if x<2 then return 0 /*is the number too small to be prime? */ - if x==2 | x==5 then return 1 /*is the number a two or a five? */ - if last//2==0 | last==5 then return 0 /*is the last decimal digit even or 5? */ - if !.xm\==1 then != !.xm /*has the factorial been pre─computed? */ - else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end - else base= 2 /* [↑] use shortcut.*/ - do j=!.0+1 to xm; != ! * j /*compute factorial.*/ - if pos(., !)\==0 then do; parse var ! 'E' expon - numeric digits expon +99 - digs = digits() - end /* [↑] has exponent,*/ - end /*j*/ /*bump numeric digs.*/ - if xm<999 then do; !.xm=!; !.0=xm; end /*assign factorial. */ - end /*only save small #s*/ - if (!+1)//x==0 then return 1 /*X is a prime.*/ - return 0 /*" isn't " " */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: parse arg header,oo; say header /*display header for the first N primes*/ - w= length( word($, LO) ) /*used to align prime numbers in $ list*/ - do k=1 for LO; _= right( word($, k), w) /*build list for displaying the primes.*/ - if length(oo _)>sw then do; say substr(oo,2); oo=; end /*a line overflowed?*/ - oo= oo _ /*display a line. */ - end /*k*/ /*does pretty print.*/ - if oo\='' then say substr(oo, 2); return /*display residual (if any overflowed).*/ +call ShowWilson 1,660 +call ShowWilson 7901,8269 +do i = 3 to 6 + a = 1'E'i; a = a+1; b = a+999 + call CompareWilsonMR a,b +end +exit + +ShowWilson: +procedure expose glob. +arg xx,yy +call Time('r') +say 'Primes between' Std(xx) 'and' Std(yy) +n = 0; w = Xpon(yy)+2 +do i = xx to yy + if Isprime(i) then do + n = n+1 + call Charout ,Right(i,w) + if n//10 = 0 then + say + end +end +say +say n 'primes found' +say Format(Time('e'),,3) 'seconds'; say +return + +CompareWilsonMR: +procedure +arg xx,yy +call Time('r') +do i = xx to yy + call Isprime i +end +e1 = Time('e') +call Time('r') +do i = xx to yy + call Prime i +end +e2 = Time('e') +say 'For n between' Right(Std(xx),7) 'and' Right(Std(yy),7), +'Wilson took' Format(e1,3,3)'s and Miller-Rabin' Format(e2,3,3)'s' +return + +Isprime: +procedure expose glob. +arg xx +if xx < 2 then + return 0 +if xx = 2 then + return 1 +if Even(xx) then + return 0 +f = 1; x1 = xx-1 +do i = 2 to x1 + f = (f*i)//xx +end +if f = x1 then + return 1 +else + return 0 + +include Sequences +include Numbers +include Functions +include Constants +include Abend diff --git a/Task/Primality-by-trial-division/Odin/primality-by-trial-division.odin b/Task/Primality-by-trial-division/Odin/primality-by-trial-division.odin new file mode 100644 index 0000000000..4c922f4a26 --- /dev/null +++ b/Task/Primality-by-trial-division/Odin/primality-by-trial-division.odin @@ -0,0 +1,29 @@ +package main + +import "core:fmt" +import "core:math" + +prime ::proc(n:i32)->bool{ + if (n<2){ + return false + } + else { + + test:=true + for i:=2;i<=int(math.sqrt_f16(f16(n)));i+=1{ + if (n%i32(i))==0{ + return false + } + } + return test + } + +} + +main :: proc() { + + for i:=2;i<=100;i+=1{ + fmt.printf("%i: ", i) + fmt.println(prime(i32(i))) + } +} diff --git a/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas b/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas index fc3525df36..f2bc28dfb8 100644 --- a/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas +++ b/Task/Primality-by-trial-division/PascalABC.NET/primality-by-trial-division.pas @@ -3,7 +3,7 @@ begin if N = 1 then Result := False else Result := True; - for var i:=2 to N.Sqrt.Round do + for var i:=2 to N.Sqrt.Trunc do if N.Divs(i) then begin Result := False; diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx deleted file mode 100644 index 8341632309..0000000000 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx +++ /dev/null @@ -1,21 +0,0 @@ -/*REXX program tests for primality by using (kinda smartish) trial division. */ -parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */ -tell=(n>0); n=abs(n) /*display the primes only if N > 0. */ -p=0 /*a count of the primes found (so far).*/ - do j=-57 to n /*start in the cellar and work up. */ - if \isPrime(j) then iterate /*if not prime, then keep looking. */ - p=p+1 /*bump the jelly bean counter. */ - if tell then say right(j,20) 'is prime.' /*maybe display prime to the terminal. */ - end /*j*/ -say -say "There are " p " primes up to " n ' (inclusive).' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x /*get the number to be tested. */ - if wordpos(x, '2 3 5 7')\==0 then return 1 /*is number a teacher's pet? */ - if x<2 | x//2==0 | x//3==0 then return 0 /*weed out the riff-raff. */ - do k=5 by 6 until k*k>x /*skips odd multiples of 3. */ - if x//k==0 | x//(k+2)==0 then return 0 /*a pair of divides. ___ */ - end /*k*/ /*divide up through the √ x */ - /*Note: // is ÷ remainder.*/ - return 1 /*done dividing, it's prime. */ diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx deleted file mode 100644 index b8afb7f1e1..0000000000 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx +++ /dev/null @@ -1,22 +0,0 @@ -/*REXX program tests for primality by using (kinda smartish) trial division. */ -parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */ -tell=(n>0); n=abs(n) /*display the primes only if N > 0. */ -p=0 /*a count of the primes found (so far).*/ - do j=-57 to n /*start in the cellar and work up. */ - if \isPrime(j) then iterate /*if not prime, then keep looking. */ - p=p+1 /*bump the jelly bean counter. */ - if tell then say right(j,20) 'is prime.' /*maybe display prime to the terminal. */ - end /*j*/ -say -say "There are " p " primes up to " n ' (inclusive).' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x /*get integer to be investigated.*/ - if x<11 then return wordpos(x, '2 3 5 7')\==0 /*is it a wee prime? */ - if x//2==0 then return 0 /*eliminate all the even numbers.*/ - if x//3==0 then return 0 /* ··· and eliminate the triples.*/ - do k=5 by 6 until k*k>x /*this skips odd multiples of 3. */ - if x//k ==0 then return 0 /*perform a divide (modulus), */ - if x//(k+2)==0 then return 0 /* ··· and the next umpty one. */ - end /*k*/ /*Note: REXX // is ÷ remainder.*/ - return 1 /*did all divisions, it's prime. */ diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx deleted file mode 100644 index bbc635e32f..0000000000 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx +++ /dev/null @@ -1,49 +0,0 @@ -/*REXX program tests for primality by using (kinda smartish) trial division. */ -parse arg n .; if n=='' then n=10000 /*let the user choose the upper limit. */ -tell=(n>0); n=abs(n) /*display the primes only if N > 0. */ -p=0 /*a count of the primes found (so far).*/ - do j=-57 to n /*start in the cellar and work up. */ - if \isPrime(j) then iterate /*if not prime, then keep looking. */ - p=p+1 /*bump the jelly bean counter. */ - if tell then say right(j,20) 'is prime.' /*maybe display prime to the terminal. */ - end /*j*/ -say -say "There are " p " primes up to " n ' (inclusive).' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x /*get the integer to be investigated. */ - if x<107 then return wordpos(x, '2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53', - '59 61 67 71 73 79 83 89 97 101 103')\==0 /*some low primes.*/ - if x// 2 ==0 then return 0 /*eliminate all the even numbers. */ - if x// 3 ==0 then return 0 /* ··· and eliminate the triples. */ - parse var x '' -1 _ /* obtain the rightmost digit.*/ - if _ ==5 then return 0 /* ··· and eliminate the nickels. */ - if x// 7 ==0 then return 0 /* ··· and eliminate the luckies. */ - if x//11 ==0 then return 0 - if x//13 ==0 then return 0 - if x//17 ==0 then return 0 - if x//19 ==0 then return 0 - if x//23 ==0 then return 0 - if x//29 ==0 then return 0 - if x//31 ==0 then return 0 - if x//37 ==0 then return 0 - if x//41 ==0 then return 0 - if x//43 ==0 then return 0 - if x//47 ==0 then return 0 - if x//53 ==0 then return 0 - if x//59 ==0 then return 0 - if x//61 ==0 then return 0 - if x//67 ==0 then return 0 - if x//71 ==0 then return 0 - if x//73 ==0 then return 0 - if x//79 ==0 then return 0 - if x//83 ==0 then return 0 - if x//89 ==0 then return 0 - if x//97 ==0 then return 0 - if x//101==0 then return 0 - if x//103==0 then return 0 /*Note: REXX // is ÷ remainder. */ - do k=107 by 6 while k*k<=x /*this skips odd multiples of three. */ - if x//k ==0 then return 0 /*perform a divide (modulus), */ - if x//(k+2)==0 then return 0 /* ··· and the next also. ___ */ - end /*k*/ /*divide up through the √ x */ - return 1 /*after all that, ··· it's a prime. */ diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx new file mode 100644 index 0000000000..f823f29a39 --- /dev/null +++ b/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx @@ -0,0 +1,90 @@ +-- 26 Mar 2025 +include Settings +numeric digits 15 + +say 'PRIMALITY BY TRIAL DIVISION' +say version +say +call ShowTrial 1,100 +call ShowMR 1,100 +do i = 3 to 13 + a = 1'E'i; a = a+1; b = a+999 + call CompareTrialMR a,b +end +exit + +ShowTrial: +procedure +arg xx,yy +call Time('r') +say 'Primes between' std(xx) 'and' std(yy) 'by trial division' +n = 0; w = Xpon(yy)+2 +do i = xx to yy + if Isprime(i) then do + n = n+1 + call Charout ,Right(i,w) + if n//10 = 0 then + say + end +end +say +say n 'primes found' +say Format(Time('e'),,3) 'seconds'; say +return + +ShowMR: +procedure +arg xx,yy +call Time('r') +say 'Primes between' std(xx) 'and' std(yy) 'by Miller-Rabin' +n = 0; w = Xpon(yy)+2 +do i = xx to yy + if Prime(i) then do + n = n+1 + call Charout ,Right(i,w) + if n//10 = 0 then + say + end +end +say +say n 'primes found' +say Format(Time('e'),,3) 'seconds'; say +return + +CompareTrialMR: +procedure +arg xx,yy +call Time('r') +do i = xx to yy + call Isprime i +end +e1 = Time('e') +call Time('r') +do i = xx to yy + call Prime i +end +e2 = Time('e') +say 'For n between' Right(Std(xx),14) 'and' Right(Std(yy),14), +'trial division took' Format(e1,2,3)'s and Miller-Rabin' Format(e2,2,3)'s' +return + +Isprime: +procedure +arg xx +if xx < 2 then + return 0 +if xx = 2 then + return 1 +if Even(xx) then + return 0 +do i = 3 by 2 to Isqrt(xx) + if xx//i = 0 then + return 0 +end +return 1 + +include Sequences +include Numbers +include Functions +include Constants +include Abend diff --git a/Task/Prime-conspiracy/REXX/prime-conspiracy.rexx b/Task/Prime-conspiracy/REXX/prime-conspiracy-1.rexx similarity index 100% rename from Task/Prime-conspiracy/REXX/prime-conspiracy.rexx rename to Task/Prime-conspiracy/REXX/prime-conspiracy-1.rexx diff --git a/Task/Prime-conspiracy/REXX/prime-conspiracy-2.rexx b/Task/Prime-conspiracy/REXX/prime-conspiracy-2.rexx new file mode 100644 index 0000000000..e705a5fdb3 --- /dev/null +++ b/Task/Prime-conspiracy/REXX/prime-conspiracy-2.rexx @@ -0,0 +1,67 @@ +-- 8 May 2025 +include Settings +numeric digits 10 +arg xx +if xx = '' then + xx = 1e6 + +say 'PRIME CONSPIRACY' +say version +say +call GetPrimes xx +call CollectStats +call ShowStats +exit + +GetPrimes: +call Time('r') +arg xx +say 'Analysis for first' xx 'primes follows' +say +say 'Get primes...' +call Primes -xx; prim.0 = xx +say xx 'primes found' +say Format(Time('e'),,3) 'seconds'; say +return + +CollectStats: +call Time('r') +say 'Collect statistics...' +tran. = 0 +a = Right(prim.1,1); tran.2 = 1 +do i = 2 to prim.0 + b = Right(prim.i,1); d = Right(prim.i,2)+0 + tran.a.b = tran.a.b+1; tran.d = tran.d+1 + a = b +end +say Format(Time('e'),,3) 'seconds'; say +return + +ShowStats: +say 'Transition count...' +do i = 1 to 9 + do j = 1 to 9 + if tran.i.j > 0 then do + say 'Transition' i'->'j 'Count' Right(tran.i.j,5) 'Freq' Format(100*tran.i.j/(prim.0-1),2,3)'%' + end + end +end +say +say 'Last 2 digits count...' +do i = 1 to 99 + if tran.i > 0 then do + if i < 10 then + d = '0'i + else + d = i + say 'Digits' d 'Count' Right(tran.i,6) 'Freq' Format(100*tran.i/prim.0,2,3)'%' + end +end +say +return + +include Sequences +include Functions +include Special +include Constants +include Abend diff --git a/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx b/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx deleted file mode 100644 index dcbc1d8c1d..0000000000 --- a/Task/Prime-decomposition/REXX/prime-decomposition-1.rexx +++ /dev/null @@ -1,82 +0,0 @@ -/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ -Numeric Digits 1000 /*handle thousand digits For the powers*/ -Parse Arg bot top step base add /*get optional arguments from the C.L. */ -If bot='?' Then Do - Say 'rexx pfoo bot top step base add' - Exit - End -If bot=='' Then /* no arguments given */ - Parse Value 1 100 With bot top /* set default range .*/ -If top=='' Then top=bot /* process one number */ -If step=='' Then step=1 /* step=2 to process only odd numbers */ -If add =='' Then add=-1 /* for Mersenne tests */ -tell=top>0 /*If TOP is negative, suppress displays*/ -top=abs(top) -w=length(top) /*get maximum width For aligned display*/ -If base\=='' Then - w=length(base**top) /*will be testing powers of two later? */ -tag.=left('', 7) /*some literals: pad; prime (or not).*/ -tag.0='{unity}' -tag.1='[prime]' -Numeric Digits max(9,w+1) /*maybe increase the digits precision. */ -np=0 /*np: is the number of primes found.*/ -Do n=bot To top by step /*process a single number or a range. */ - ?=n - If base\=='' Then /*should we perform a 'Mersenne' test? */ - ?=base**n+add - pf=factr(?) /* get prime factors */ - f=words(pf) /* number of prime factors */ - If f=1 Then /* If the number is prime */ - np=np+1 /* Then bump prime counter */ - If tell Then - Say right(?,w) right('('f')',9) 'prime factors: ' tag.f pf - End /*n*/ -Say '' -ps='prime' -If f>1 Then ps=ps's' /*setup For proper English in sentence.*/ -Say right(np, w+9+1) ps 'found.' /*display the number of primes found. */ -Exit /*stick a fork in it, we're all done. */ -/*---------------------------------------------------------------------------*/ -factr: Procedure - Parse Arg x 1 d,pl /*set X, D to argument 1, pl to null */ - If x==1 Then Return '' /*handle the special case of X=1. */ - primes=2 3 5 7 - Do While primes>'' /* first check the small primes */ - Parse Var primes prime primes - Do While x//prime==0 - pl=pl prime - x=x%prime - End - End - r=isqrt(x) - Do j=11 by 6 To r /*insure that J isn't divisible by 3. */ - Parse var j '' -1 _ /*obtain the last decimal digit of J. */ - If _\==5 Then Do - Do While x//j==0 - pl=pl j - x=x%j - End /*maybe reduce by J. */ - End - If _ ==3 Then Iterate /*If next Y is divisible by 5? Skip. */ - y=j+2 - Do While x//y==0 - pl=pl y - x=x%y - End /*maybe reduce by y. */ - End /*j*/ - - If x==1 Then Return pl /*Is residual=unity? Then don't append.*/ - Return pl x /*return pl with appended residual.*/ - -isqrt: Procedure - Parse Arg x - x=abs(x) - Parse Value 0 x with lo hi - Do While lo<=hi - t=(lo+hi)%2 - If t**2>x Then - hi=t-1 - Else - lo=t+1 - End - Return t diff --git a/Task/Prime-decomposition/REXX/prime-decomposition-2.rexx b/Task/Prime-decomposition/REXX/prime-decomposition-2.rexx deleted file mode 100644 index 864480da70..0000000000 --- a/Task/Prime-decomposition/REXX/prime-decomposition-2.rexx +++ /dev/null @@ -1,81 +0,0 @@ -/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ -Numeric Digits 1000 /*handle thousand digits For the powers*/ -Parse Arg bot top step base add /*get optional arguments from the C.L. */ -If bot='?' Then Do - Say 'rexx pfoo bot top step base add' - Exit - End -If bot=='' Then /* no arguments given */ - Parse Value 1 100 With bot top /* set default range .*/ -If top=='' Then top=bot /* process one number */ -If step=='' Then step=1 /* step=2 to process only odd numbers */ -If add =='' Then add=-1 /* for Mersenne tests */ -tell=top>0 /*If TOP is negative, suppress displays*/ -top=abs(top) -w=length(top) /*get maximum width For aligned display*/ -If base\=='' Then - w=length(base**top) /*will be testing powers of two later? */ -tag.=left('', 7) /*some literals: pad; prime (or not).*/ -tag.0='{unity}' -tag.1='[prime]' -Numeric Digits max(9,w+1) /*maybe increase the digits precision. */ -np=0 /*np: is the number of primes found.*/ -Do n=bot To top by step /*process a single number or a range. */ - ?=n - If base\=='' Then /*should we perform a 'Mersenne' test? */ - ?=base**n+add - pf=factr(?) /* get prime factors */ - f=words(pf) /* number of prime factors */ - If f=1 Then /* If the number is prime */ - np=np+1 /* Then bump prime counter */ - If tell Then - Say right(?,w) right('('f')',9) 'prime factors: ' tag.f pf - End /*n*/ -Say '' -ps='prime' -If f>1 Then ps=ps's' /*setup For proper English in sentence.*/ -Say right(np, w+9+1) ps 'found.' /*display the number of primes found. */ -Exit /*stick a fork in it, we're all done. */ -/*---------------------------------------------------------------------------*/ -factr: Procedure - Parse Arg x 1 d,pl /*set X, D to argument 1, pl to null */ - If x==1 Then Return '' /*handle the special case of X=1. */ - primes=2 3 5 7 11 13 17 19 23 - Do While primes>'' /* first check the small primes */ - Parse Var primes prime primes - Do While x//prime==0 - pl=pl prime - x=x%prime - End - End - r=isqrt(x) - Do j=29 by 6 To r /*insure that J isn't divisible by 3.*/ - Parse var j '' -1 _ /*obtain the last decimal digit of J. */ - If _\==5 Then Do - Do While x//j==0 - pl=pl j - x=x%j - End /*maybe reduce by J. */ - End - If _ ==3 Then Iterate /*If next Y is divisible by 5? Skip. */ - y=j+2 - Do While x//y==0 - pl=pl y - x=x%y - End /*maybe reduce by y. */ - End /*j*/ - If x==1 Then Return pl /*Is residual=unity? Then don't append.*/ - Return pl x /*return pl with appended residual.*/ - -isqrt: Procedure - Parse Arg x - x=abs(x) - Parse Value 0 x with lo hi - Do While lo<=hi - t=(lo+hi)%2 - If t**2>x Then - hi=t-1 - Else - lo=t+1 - End - Return t diff --git a/Task/Prime-decomposition/REXX/prime-decomposition-3.rexx b/Task/Prime-decomposition/REXX/prime-decomposition-3.rexx deleted file mode 100644 index 86902ca626..0000000000 --- a/Task/Prime-decomposition/REXX/prime-decomposition-3.rexx +++ /dev/null @@ -1,69 +0,0 @@ -/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ -call time('r') -Numeric Digits 1000 /*handle thousand digits For the powers*/ -Parse Arg bot top step base add /*get optional arguments from the C.L. */ -If bot='?' Then Do - Say 'rexx pfoo bot top step base add' - Exit - End -If bot=='' Then /* no arguments given */ - Parse Value 1 100 With bot top /* set default range .*/ -If top=='' Then top=bot /* process one number */ -If step=='' Then step=1 /* step=2 to process only odd numbers */ -If add =='' Then add=-1 /* for Mersenne tests */ -tell=top>0 /*If TOP is negative, suppress displays*/ -top=abs(top) -w=length(top) /*get maximum width For aligned display*/ -If base\=='' Then - w=length(base**top) /*will be testing powers of two later? */ -tag.=left('', 7) /*some literals: pad; prime (or not).*/ -tag.0='{unity}' -tag.1='[prime]' -Numeric Digits max(9,w+1) /*maybe increase the digits precision. */ -np=0 /*np: is the number of primes found.*/ -Do n=bot To top by step /*process a single number or a range. */ - ?=n - If base\=='' Then /*should we perform a 'Mersenne' test? */ - ?=base**n+add - pf=factr(?) /* get prime factors */ - f=words(pf) /* number of prime factors */ - If f=1 Then /* If the number is prime */ - np=np+1 /* Then bump prime counter */ - If tell Then - Say right(?,w) right('('f')',9) 'prime factors: ' tag.f pf - End /*n*/ -Say '' -ps='prime' -If f>1 Then ps=ps's' /*setup For proper English in sentence.*/ -Say right(np, w+9+1) ps 'found.' /*display the number of primes found. */ -say format(time('e'),,3) 'seconds' -Exit /*stick a fork in it, we're all done. */ -/*---------------------------------------------------------------------------*/ -Factr: -procedure expose glob. -arg x -primes = '2 3 5 7 11 13 17 19 23'; pl = '' -do n = 1 to words(primes) - prime = word(primes,n) - do while x//prime = 0 - pl = pl prime; x = x%prime - end -end -do j = 29 by 6 while j*j <= x - d = right(j,1) - if d <> 5 then do - do while x//j = 0 - pl = pl j; x = x%j - end - end - if d = 3 then - iterate - y = j+2 - do while x//y = 0 - pl = pl y; x = x%y - end -end -if x = 1 then - return pl -else - return pl x diff --git a/Task/Prime-decomposition/REXX/prime-decomposition-4.rexx b/Task/Prime-decomposition/REXX/prime-decomposition-4.rexx deleted file mode 100644 index 20904dd265..0000000000 --- a/Task/Prime-decomposition/REXX/prime-decomposition-4.rexx +++ /dev/null @@ -1,103 +0,0 @@ -/*REXX pgm does prime decomposition of a range of positive integers (with a prime count)*/ -include Settings - -say version; say 'Prime decompositoion'; say -Numeric Digits 1000 /*handle thousand digits For the powers*/ -Parse Arg bot top step base add /*get optional arguments from the C.L. */ -If bot='qq' Then Do - Say 'rexx pfoo bot top step base add' - Exit - End -If bot=='' Then /* no arguments given */ - Parse Value 1 100 With bot top /* set default range .*/ -If top=='' Then top=bot /* process one Number */ -If step=='' Then step=1 /* step=2 to process only Odd numbers */ -If add =='' Then add=-1 /* for Mersenne tests */ -tell=top>0 /*If TOP is negative, suppress displays*/ -top=Abs(top) -w=Length(top) /*get maximum width For aligned display*/ -If base\=='' Then - w=Length(base**top) /*will be testing powers of two laterqq */ -tag.=Left('', 7) /*some literals: pad; Prime (or not).*/ -tag.0='{unity}' -tag.1='[Prime]' -Numeric Digits Max(9,w+1) /*maybe increase the digits precision. */ -np=0 /*np: is the Number of Primes found.*/ -Do n=bot To top by step /*process a single Number or a range. */ - qq=n - If base\=='' Then /*should we perform a 'Mersenne' testqq */ - qq=base**n+add - f=Factors(qq) /* Number of Prime Factors */ - If f=1 Then /* If the Number is Prime */ - np=np+1 /* Then bump Prime counter */ - If tell Then do - pf = '' - do i = 1 to f - pf = pf glob.factor.i - end - Say Right(qq,w) Right('('f')',9) 'Prime Factors: ' tag.f pf - end - End /*n*/ -Say '' -ps='Prime' -If f>1 Then ps=ps's' /*setup For proper English in sentence.*/ -Say Right(np, w+9+1) ps 'found.' /*display the Number of Primes found. */ -say Format(Time('e'),,3) 'seconds' -Exit /*stick a fork in it, we're all done. */ - -Factors: -/* Prime factors of an integer */ -procedure expose glob. -arg x -/* Fast values */ -if x = 1 then do - glob.factor.0 = 0 - return 0 -end -if x < 4 then do - glob.factor.1 = x; glob.factor.0 = 1 - return 1 -end -if Prime(x) then do - glob.factor.1 = x; glob.factor.0 = 1 - return 1 -end -/* Check low factors */ -n = 0 -pr = '2 3 5 7 11 13 17 19 23' -do i = 1 to Words(pr) - p = Word(pr,i) - do while x//p = 0 - n = n+1; glob.factor.n = p - x = x%p - end -end -/* Check higher factors */ -do j = 29 by 6 while j*j <= x - p = Right(j,1) - if p <> 5 then do - do while x//j = 0 - n = n+1; glob.factor.n = j - x = x%j - end - end - if p = 3 then - iterate - y = j+2 - do while x//y = 0 - n = n+1; glob.factor.n = y - x = x%y - end -end -/* Last factor */ -if x > 1 then do - n = n+1; glob.factor.n = x -end -glob.factor.0 = n -/* Return number of factors */ -return n - -include Functions -include Numbers -include Sequences -include Abend diff --git a/Task/Prime-decomposition/REXX/prime-decomposition.rexx b/Task/Prime-decomposition/REXX/prime-decomposition.rexx new file mode 100644 index 0000000000..9136f5edb0 --- /dev/null +++ b/Task/Prime-decomposition/REXX/prime-decomposition.rexx @@ -0,0 +1,41 @@ +-- 22 Mar 2025 +include Settings + +say 'PRIME DECOMPOSITION' +say version +say +numeric digits 50 +call ShowFactors 100,120 +call ShowFactors 720720 +call ShowFactors 9007199254740991 +call ShowFactors 2543821448263974486045199 +call ShowFactors 340282366920938463463374607431768211455 +exit + +ShowFactors: +arg xx,yy +if yy = '' then + yy = xx +do i = xx to yy + call Charout ,i '= ' + f = Factors(i) + if f = 1 then + call Charout ,'Prime' + else do + do j = 1 to f + if j < f then + call Charout ,fact.j 'x ' + else + call Charout ,fact.j + end + end + say +end +say Format(Time('e'),,3) 'seconds' +say +return + +include Functions +include Numbers +include Sequences +include Abend diff --git a/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/EasyLang/prime-numbers-whose-neighboring-pairs-are-tetraprimes.easy b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/EasyLang/prime-numbers-whose-neighboring-pairs-are-tetraprimes.easy new file mode 100644 index 0000000000..8e93391ba7 --- /dev/null +++ b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/EasyLang/prime-numbers-whose-neighboring-pairs-are-tetraprimes.easy @@ -0,0 +1,64 @@ +len nfac[] 1000000 +proc sieve . + nfac[1] = 1 + for i = 2 to len nfac[] + if nfac[i] = 0 + j = i + i + while j <= len nfac[] + if j div i mod i = 0 : nfac[j] = 5 + nfac[j] += 1 + j += i + . + . + . +. +sieve +# +fastfunc isprim num . + i = 3 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 2 + . + return 1 +. +fastfunc nextprim prim . + if prim = 2 : return 3 + repeat + prim += 2 + until isprim prim = 1 + . + return prim +. +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] + . +. +proc calc max dir . + h$ = " preceeded" + if dir = 1 : h$ = " followed" + print "Primes below " & max & h$ & " by a tetraprime pair:" + if max <= 100000 : print "" + prim = 7 + while prim < max + if nfac[prim + dir] = 4 and nfac[prim + dir + dir] = 4 + if (prim + dir) mod 7 = 0 or (prim + dir + dir) mod 7 = 0 : cnt += 1 + if prev > 0 : d[] &= prim - prev + prev = prim + if max <= 100000 : write prim & " " + . + prim = nextprim prim + . + if max <= 100000 : print "" + print "" + print len d[] + 1 & " " & cnt + print "" + sort d[] + print d[1] & " " & d[$ div 2 + 1] & " " & d[$] + print "" +. +calc 100000 -1 +calc 100000 1 +calc 1000000 -1 +calc 1000000 1 diff --git a/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/PARI-GP/prime-numbers-whose-neighboring-pairs-are-tetraprimes.parigp b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/PARI-GP/prime-numbers-whose-neighboring-pairs-are-tetraprimes.parigp new file mode 100644 index 0000000000..357af19cb6 --- /dev/null +++ b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/PARI-GP/prime-numbers-whose-neighboring-pairs-are-tetraprimes.parigp @@ -0,0 +1,35 @@ +tetra(n)=factor(n)[,2]==[1,1,1,1]~ +diff(v)=vector(#v-1,i,v[i+1]-v[i]) +median(v)=v=vecsort(v); if(#v%2, v[(#v+1)/2], (v[#v/2]+v[#v/2+1])/2) \\ averages the middle two if there are an even number +listPre(lim)=my(v=List()); forprimestep(p=3,lim,4, if(tetra(p-1) && tetra(p-2), listput(v,p))); Vec(v) +listPost(lim)=my(v=List()); forprimestep(p=5,lim,4, if(tetra(p+1) && tetra(p+2), listput(v,p))); Vec(v) +pre5=listPre(1e5) \\ #1 +post5=listPost(1e5) \\ #2 +#select(p->p%7<3, pre5) \\ #3 +#select(p->p%7>4, post5) \\ #3 +vecmin(diff(pre5)) \\ #4 +vecmin(diff(post5)) \\ #4 +median(diff(pre5)) \\ #4 +median(diff(post5)) \\ #4 +vecmax(diff(pre5)) \\ #4 +vecmax(diff(post5)) \\ #4 +pre6=listPre(1e6); #pre6 \\ #5 +post6=listPost(1e6); #post6 \\ #5 +#select(p->p%7<3, pre6) \\ #5 +#select(p->p%7>4, post6) \\ #5 +vecmin(diff(pre6)) \\ #5 +vecmin(diff(post6)) \\ #5 +median(diff(pre6)) \\ #5 +median(diff(post6)) \\ #5 +vecmax(diff(pre6)) \\ #5 +vecmax(diff(post6)) \\ #5 +pre7=listPre(1e7); #pre7 +post7=listPost(1e7); #post7 +#select(p->p%7<3, pre7) +#select(p->p%7>4, post7) +vecmin(diff(pre7)) +vecmin(diff(post7)) +median(diff(pre7)) +median(diff(post7)) +vecmax(diff(pre7)) +vecmax(diff(post7)) diff --git a/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Python/prime-numbers-whose-neighboring-pairs-are-tetraprimes.py b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Python/prime-numbers-whose-neighboring-pairs-are-tetraprimes.py new file mode 100644 index 0000000000..8184163f2b --- /dev/null +++ b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Python/prime-numbers-whose-neighboring-pairs-are-tetraprimes.py @@ -0,0 +1,195 @@ +import math +import time +from collections import defaultdict + +def sieve_of_eratosthenes(limit): + """Generate all primes up to the given limit using the Sieve of Eratosthenes.""" + sieve = [True] * (limit + 1) + sieve[0] = sieve[1] = False + + for i in range(2, int(math.sqrt(limit)) + 1): + if sieve[i]: + for j in range(i*i, limit + 1, i): + sieve[j] = False + + return [i for i in range(limit + 1) if sieve[i]] + +def prime_factorization(n, primes_list, primes_set): + """Return the prime factorization of n as a list of primes.""" + if n in primes_set: + return [n] + + factors = [] + for p in primes_list: + if p * p > n: # No need to check beyond sqrt(n) + break + + while n % p == 0: + factors.append(p) + n //= p + + if n == 1: + break + + # If n is not fully factorized yet, it must be a prime itself + if n > 1: + factors.append(n) + + return factors + +def is_tetraprime(n, primes_list, primes_set, prime_factors_cache): + """Check if a number is a tetraprime (product of exactly 4 distinct primes).""" + if n in prime_factors_cache: + factors = prime_factors_cache[n] + else: + factors = prime_factorization(n, primes_list, primes_set) + prime_factors_cache[n] = factors + + # A tetraprime must have exactly 4 distinct prime factors + distinct_factors = set(factors) + return len(distinct_factors) == 4 and len(factors) == 4 + +def find_primes_with_tetraprime_neighbors(primes, limit, direction="preceding"): + """Find primes whose neighboring pairs are both tetraprimes.""" + result = [] + primes_set = set(primes) + prime_factors_cache = {} + + for prime in primes: + if prime >= limit: + break + + if direction == "preceding" and prime >= 3: + if (is_tetraprime(prime-1, primes, primes_set, prime_factors_cache) and + is_tetraprime(prime-2, primes, primes_set, prime_factors_cache)): + result.append(prime) + elif direction == "following" and prime <= limit - 2: + if (is_tetraprime(prime+1, primes, primes_set, prime_factors_cache) and + is_tetraprime(prime+2, primes, primes_set, prime_factors_cache)): + result.append(prime) + + return result + +def has_prime_factor_7(n, primes_list, primes_set, prime_factors_cache): + """Check if a number has 7 as one of its prime factors.""" + if n in prime_factors_cache: + factors = prime_factors_cache[n] + else: + factors = prime_factorization(n, primes_list, primes_set) + prime_factors_cache[n] = factors + + return 7 in factors + +def count_factor_7_primes(primes_list, primes, primes_set, direction): + """Count primes whose neighboring pairs have at least one member with a prime factor of 7.""" + count = 0 + prime_factors_cache = {} + + for prime in primes_list: + if direction == "preceding": + neighbors = [prime-1, prime-2] + else: # following + neighbors = [prime+1, prime+2] + + if any(has_prime_factor_7(n, primes, primes_set, prime_factors_cache) for n in neighbors): + count += 1 + + return count + +def calculate_prime_gaps(primes_list): + """Calculate the gaps between consecutive primes in the list.""" + if not primes_list or len(primes_list) < 2: + return [] + + return [primes_list[i] - primes_list[i-1] for i in range(1, len(primes_list))] + +def calculate_gap_statistics(gaps): + """Calculate min, median, and max gap statistics.""" + if not gaps: + return None, None, None + + min_gap = min(gaps) + max_gap = max(gaps) + + # Calculate median + gaps_sorted = sorted(gaps) + n = len(gaps_sorted) + if n % 2 == 0: + median_gap = int((gaps_sorted[n//2 - 1] + gaps_sorted[n//2]) / 2) + else: + median_gap = int(gaps_sorted[n//2]) + + return min_gap, median_gap, max_gap + +def format_primes_grid(primes_list, num_columns=10): + """Format a list of primes into a grid with specified number of columns.""" + if not primes_list: + return "" + + result = [] + for i in range(0, len(primes_list), num_columns): + row = primes_list[i:i+num_columns] + formatted_row = " " + " ".join(f"{p:6d}" for p in row) + result.append(formatted_row) + + return "\n".join(result) + +def print_prime_results(primes, count_with_factor_7, direction, limit, show_primes=True): + """Print results for a set of primes with tetraprime neighbors.""" + direction_text = "preceding" if direction == "preceding" else "following" + + print(f"\nFound {len(primes)} primes under {limit:,} whose {direction_text} neighboring pair are tetraprimes") + + if show_primes and primes: + print(":") + print(format_primes_grid(primes)) + + print(f"\nof which {count_with_factor_7} have a neighboring pair one of whose factors is 7.") + + # Calculate and print gap statistics + gaps = calculate_prime_gaps(primes) + if gaps: + min_gap, median_gap, max_gap = calculate_gap_statistics(gaps) + print(f"\nMinimum gap between those {len(primes)} primes: {min_gap}") + print(f"Median gap between those {len(primes)} primes: {median_gap}") + print(f"Maximum gap between those {len(primes)} primes: {max_gap}") + +def solve_for_limit(limit): + """Solve all parts of the problem for a given limit.""" + print(f"\nSolving for primes less than {limit:,}:") + start_time = time.time() + + # Generate all primes up to the limit + primes = sieve_of_eratosthenes(limit) + primes_set = set(primes) + + # Find primes with tetraprime neighbors + preceding_primes = find_primes_with_tetraprime_neighbors(primes, limit, "preceding") + following_primes = find_primes_with_tetraprime_neighbors(primes, limit, "following") + + # Count primes with factor 7 in neighbors + preceding_factor7_count = count_factor_7_primes(preceding_primes, primes, primes_set, "preceding") + following_factor7_count = count_factor_7_primes(following_primes, primes, primes_set, "following") + + # Show results + show_individual_primes = limit <= 100000 + print_prime_results(preceding_primes, preceding_factor7_count, "preceding", limit, show_individual_primes) + print_prime_results(following_primes, following_factor7_count, "following", limit, show_individual_primes) + + elapsed_time = time.time() - start_time + print(f"\nTime taken: {elapsed_time:.2f} seconds") + +if __name__ == "__main__": + print("Starting tetraprime neighbors analysis...") + + # Run all calculations sequentially + print("\n---------- PRIMES UNDER 100,000 ----------") + solve_for_limit(100000) + + print("\n---------- PRIMES UNDER 1,000,000 ----------") + solve_for_limit(1000000) + + print("\n---------- PRIMES UNDER 10,000,000 ----------") + solve_for_limit(10000000) + + print("\nAnalysis complete!") diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/00-TASK.txt b/Task/Primes---allocate-descendants-to-their-ancestors/00-TASK.txt index 21e1436ef3..22e5532ff0 100644 --- a/Task/Primes---allocate-descendants-to-their-ancestors/00-TASK.txt +++ b/Task/Primes---allocate-descendants-to-their-ancestors/00-TASK.txt @@ -30,6 +30,10 @@ Example : 7 is a prime factor and, as such, has no parent. 46 has 3 ancestors (7, 10 and 25). + +129 = 3x43 is a descendant, because 3+43 = 46. +888 = 2x2x2x3x37 also, because 2+2+2+3+37 = 46. + 46 has 557 descendants.
The list layout and the output for Parent [46] : diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/ALGOL-68/primes---allocate-descendants-to-their-ancestors.alg b/Task/Primes---allocate-descendants-to-their-ancestors/ALGOL-68/primes---allocate-descendants-to-their-ancestors.alg new file mode 100644 index 0000000000..9c6f096c09 --- /dev/null +++ b/Task/Primes---allocate-descendants-to-their-ancestors/ALGOL-68/primes---allocate-descendants-to-their-ancestors.alg @@ -0,0 +1,108 @@ +BEGIN # Primes - allocate descendants to their ancestors # + # - based on the EasyLang sample # + + PR read "primes.incl.a68" PR # include prime utilities # + PR read "sort.incl.a68" PR # include sort utilities # + PR read "rows.incl.a68" PR # include row (array) utilities # + + INT max number = 99; # maximum number we will consider # + INT max desc = 600 000; # maximum number of descendants handled # + INT max ancestors = 10; # maximum number of ancestors handled # + + []BOOL prime = PRIMESIEVE max number; # sieve the primes to max number # + + MODE INTEGER = LONG INT; # needs to be big enough to hold # + # descendants and ancestors # + # table of ancestors - a count[ n ] holds the number of ancestors of n # + [ 1 : max number, 1 : max ancestors ]INTEGER ancestors; + [ 1 : max number ]INT a count; + FOR n FROM 1 LWB ancestors TO 1 UPB ancestors DO + a count[ n ] := 0; + FOR a FROM 2 LWB ancestors TO 2 UPB ancestors DO + ancestors[ n, a ] := 0 + OD + OD; + + # table of descentdants, d first[ n ] holds the index of the latest # + # descendant of n, prev descendant[ x ] holds the index of the previous # + # descendant ( 0 indicates no previous descendant ) # + [ 1 : max desc ]INTEGER descendant, sorted descendants; + [ 1 : max desc ]INT prev descendant; + [ 1 : max number ]INT d first; + FOR n FROM LWB d first TO UPB d first DO d first[ n ] := 0 OD; + FOR n FROM LWB descendant TO UPB descendant DO + descendant[ n ] := sorted descendants[ n ] := prev descendant[ n ] := 0 + OD; + INT next d := 1; # next free element in descendant, prev descendant # + + # adds a as an ancestor for d # + PROC add ancestor = ( INT d, INTEGER a )VOID: + ancestors[ d, a count[ d ] +:= 1 ] := a; + + # adds d to the descendants of n # + PROC add descendant = ( INT n, INTEGER d )VOID: + BEGIN + INT n prev := d first[ n ]; + descendant[ d first[ n ] := next d ] := d; + prev descendant[ next d ] := n prev; + next d +:= 1 + END # add descendant # ; + + # find the descendants # + FOR p FROM LWB prime TO UPB prime DO + IF prime[ p ] THEN + add descendant( p, p ); + FOR s FROM LWB d first TO UPB d first - p DO + INT s pos := d first[ s ]; + WHILE s pos > 0 DO + INTEGER ps = descendant[ s pos ]; + add descendant( s + p, p * ps ); + s pos := prev descendant[ s pos ] + OD + OD + FI + OD; + + # find the ancestors and show some descendants and ancestors # + INT next to show := 10; + INT total := 0; + FOR s FROM LWB d first TO UPB d first DO + # get a sorted list of the descendants of s, exclude s if present # + INT s pos := 0; + INT d pos := d first[ s ]; + WHILE d pos /= 0 DO + IF descendant[ d pos ] /= s THEN + sorted descendants[ s pos +:= 1 ] := descendant[ d pos ] + FI; + d pos := prev descendant[ d pos ] + OD; + sorted descendants QUICKSORT ELEMENTS( 1, s pos ); + total +:= s pos; + FOR d TO s pos DO + IF sorted descendants[ d ] <= max number THEN + FOR p TO a count[ s ] DO + add ancestor( SHORTEN sorted descendants[ d ] + , ancestors[ s, p ] + ) + OD; + add ancestor( SHORTEN sorted descendants[ d ], s ) + FI + OD; + IF s = next to show THEN + print( ( "-- ", whole( s, 0 ), " --", newline ) ); + print( ( whole( acount[ s ], -6 ), " Ancestors : [" ) ); + SHOW ancestors[ s, 1 : acount[ s ] ]; + print( ( " ]", newline, whole( s pos, -6 ), " Descendants: [" ) ); + IF s pos < 10 THEN + SHOW sorted descendants[ 1 : s pos ] + ELSE + print( ( " ", whole( sorted descendants[ 1 ], 0 ) ) ); + print( ( " ", whole( sorted descendants[ 2 ], 0 ) ) ); + print( ( " ... ", whole( sorted descendants[ s pos ], 0 ) ) ) + FI; + print( ( " ]", newline, newline ) ); + next to show := IF next to show = 10 THEN 46 ELSE max number FI + FI + OD; + print( ( whole( total, 0 ), " total descendants", newline ) ) +END diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/EasyLang/primes---allocate-descendants-to-their-ancestors.easy b/Task/Primes---allocate-descendants-to-their-ancestors/EasyLang/primes---allocate-descendants-to-their-ancestors.easy new file mode 100644 index 0000000000..ae1d4551d0 --- /dev/null +++ b/Task/Primes---allocate-descendants-to-their-ancestors/EasyLang/primes---allocate-descendants-to-their-ancestors.easy @@ -0,0 +1,67 @@ +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 1 + . + return 1 +. +proc qsort left right &d[] . + if left < right + piv = d[left] + mid = left + for i = left + 1 to right : if d[i] < piv + mid += 1 + swap d[i] d[mid] + . + swap d[left] d[mid] + qsort left mid - 1 d[] + qsort mid + 1 right d[] + . +. +proc sort &d[] . + qsort 1 len d[] d[] +. +maxsum = 99 +len desc[][] maxsum +len ances[][] maxsum +# +prim99[] = [ 2 ] +for i = 3 step 2 to maxsum + if isprim i = 1 : prim99[] &= i +. +for p in prim99[] + desc[p][] &= p + for s = 1 to len desc[][] - p + for ps in desc[s][] + desc[s + p][] &= p * ps + . + . +. +for p in prim99[] : len desc[p][] -1 +len desc[4][] -1 +# +for s = 1 to maxsum + sort desc[s][] + total += len desc[s][] + for d = 1 to len desc[s][] + if desc[s][d] <= maxsum + for p = 1 to len ances[s][] + ances[desc[s][d]][] &= ances[s][p] + . + ances[desc[s][d]][] &= s + . + . + if s = 10 or s = 46 or s = maxsum + print "-- " & s & " --" + print len ances[s][] & " Ancestors: " & ances[s][] + write len desc[s][] & " Descendants: " + if len desc[s][] < 10 + print desc[s][] + else + print "[ " & desc[s][1] & " " & desc[s][2] & " ... " & desc[s][len desc[s][]] & " ]" + . + print "" + . +. +print total & " total descendants" diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/REXX/primes---allocate-descendants-to-their-ancestors.rexx b/Task/Primes---allocate-descendants-to-their-ancestors/REXX/primes---allocate-descendants-to-their-ancestors.rexx new file mode 100644 index 0000000000..3fd300be45 --- /dev/null +++ b/Task/Primes---allocate-descendants-to-their-ancestors/REXX/primes---allocate-descendants-to-their-ancestors.rexx @@ -0,0 +1,126 @@ +-- 25 Apr 2025 +include Settings +numeric digits 20 + +call Time('r') +say 'PRIMES - ALLOCATE DESCENDANTS TO THEIR ANCESTORS' +say version +say +call Primes 100 +call InitTotals +do n = 1 to 99 + call InitVarious + call Ancestors n + call Terms n,1,0,'' + call Descendants + call Sort 'desc.' + if n < 21 | Pos(n,46 62 74 94 99) > 0 then + call ShowResults n + call SumTotals +end +call ShowTotals +say Format(Time('e'),,3) 'seconds'; say +exit + +InitTotals: +procedure expose tota. +tota. = 0 +return + +InitVarious: +procedure expose ance. term. desc. +ance. = 0; term. = 0; desc. = 0 +return + +Ancestors: +procedure expose ance. +arg xx +if xx < 5 + then return +f = Factors(xx) +if f = 1 then + return +s = 0 +do i = 1 to fact.0 + s = s+fact.i +end +ance.0 = ance.0+1; a = ance.0; ance.a = s +call Ancestors s +return + +Terms: +procedure expose term. prim. +arg xx,ix,cs,cl +if xx < 5 then + return +if cs = xx then do + if Words(cl) > 1 then do + term.0 = term.0+1; i = term.0; term.i = cl + end + return +end +do i = ix to prim.0 + p = prim.i; a = cs+p + if a <= xx then + call Terms xx,i,a,cl p +end +return + +Descendants: +procedure expose desc. term. +do i = 1 to term.0 + a = term.i; p = 1 + do j = 1 to Words(a) + p = p*Word(a,j) + end + desc.0 = desc.0+1; i = desc.0; desc.i = p +end +return + +ShowResults: +procedure expose ance. desc. +arg xx +say '['xx']' +call Charout ,ance.0 'ancestors: ' +do i = ance.0 by -1 to 1 + call Charout ,ance.i' ' +end +say +call Charout ,desc.0 'descendants: ' +if desc.0 < 7 then do + do i = 1 to desc.0 + call Charout ,desc.i' ' + end +end +else do + do i = 1 to 3 + call Charout ,desc.i' ' + end + call Charout, '... ' + do i = desc.0-2 to desc.0 + call Charout ,desc.i' ' + end +end +say; say +return + +SumTotals: +procedure expose ance. desc. tota. +tota.ance = tota.ance+ance.0 +tota.desc = tota.desc+desc.0 +return + +ShowTotals: +procedure expose tota. +say '[Totals]' +say tota.ance 'ancestors' +say tota.desc 'descendants' +say +return + +include Numbers +include Sequences +include Constants +include Functions +include Helper +include Abend diff --git a/Task/Primorial-numbers/REXX/primorial-numbers.rexx b/Task/Primorial-numbers/REXX/primorial-numbers.rexx index 9d9a7fbf57..a3ff709147 100644 --- a/Task/Primorial-numbers/REXX/primorial-numbers.rexx +++ b/Task/Primorial-numbers/REXX/primorial-numbers.rexx @@ -1,12 +1,13 @@ +-- 8 May 2025 include Settings -say 'Primorial numbers' -parse version version; say version; say +say 'PRIMORIAL NUMBERS' +say version +say call GetPrimes -9 call ShowFirst10 call GetPrimes -1e6 call UseFloat 1e6 -call UseLog 1e6 call UseInt 1e4 exit @@ -27,7 +28,7 @@ numeric digits 10 say 'Primorial(0) = 1' a = 1 do i = 1 to 9 - a = a*prim.prime.i + a = a*prim.i say 'Primorial('i') =' a end say Format(Time('e'),,3) 'seconds'; say @@ -40,7 +41,7 @@ say 'Number of digits by real arithmetic and taking exponent:' numeric digits 10 a = 1; e = 0 do i = 1 to x - a = a*prim.prime.i + a = a*prim.i f = Xpon(i) if f <> e then do say 'Primorial(10^'f') has' Xpon(a)+1 'digits' @@ -50,23 +51,6 @@ end say Format(Time('e'),,3) 'seconds'; say return -UseLog: -arg x -call Time('r') -say 'Number of digits by summing log10:' -numeric digits 10 -a = 0; e = 0 -do i = 1 to x - a = a+Log10(prim.prime.i) - f = Xpon(i) - if f <> e then do - say 'Primorial(10^'f') has' Trunc(a)+1 'digits' - e = f - end -end -say Format(Time('e'),,3) 'seconds'; say -return - UseInt: arg x call Time('r') @@ -87,7 +71,7 @@ select end a = 1; e = 0 do i = 1 to x - a = a*prim.prime.i + a = a*prim.i f = Xpon(i) if f <> e then do say 'Primorial(10^'f') has' Length(a) 'digits' @@ -99,6 +83,7 @@ return include Numbers include Functions +include Special include Sequences include Constants include Abend diff --git a/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy b/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy index cae44439f9..9c94d0b74e 100644 --- a/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy +++ b/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy @@ -18,7 +18,7 @@ for i to n . print "Name Ratio Expected" print "---------------------" -numfmt 4 6 +numfmt 6 4 for i to 8 print name$[i] & " " & act[i] / n & " " & probs[i] . diff --git a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy index 72b2614f28..de27f6f500 100644 --- a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy +++ b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy @@ -1,4 +1,4 @@ -proc solve c1[] c2[] c3[] s1 s2 s3 . r[] . +proc solve c1[] c2[] c3[] s1 s2 s3 &r[] . len r[] 3 x1 = c1[1] ; y1 = c1[2] ; r1 = c1[3] x2 = c2[1] ; y2 = c2[2] ; r2 = c2[3] @@ -40,25 +40,26 @@ print r1[] solve c1[] c2[] c3[] -1 -1 -1 r2[] print r2[] # -proc circ x y r . . - text "" +proc circ x0 y0 r . for a = 0 to 360 - line x + sin a * r y + cos a * r + xp = x + yp = y + x = x0 + sin a * r + y = y0 + cos a * r + if a > 0 : gline xp yp x y . . -proc draw col c[] . . - color col +proc draw col c[] . + gcolor col circ c[1] * 10 + 30 c[2] * 10 + 30 c[3] * 10 . -background 888 -clear -linewidth 0.5 -color 000 +gbackground 888 +gclear +glinewidth 0.5 +gcolor 000 drawgrid -move 30 0 -line 30 100 -move 0 30 -line 100 30 +gline 30 0 30 100 +gline 0 30 100 30 draw 000 c1[] draw 000 c2[] draw 000 c3[] diff --git a/Task/Program-name/Zig/program-name.zig b/Task/Program-name/Zig/program-name.zig index 1edf04a3af..3e3ed90f3d 100644 --- a/Task/Program-name/Zig/program-name.zig +++ b/Task/Program-name/Zig/program-name.zig @@ -1,14 +1,9 @@ const std = @import("std"); -const debug = std.debug; -const heap = std.heap; -const process = std.process; +pub fn main() void { + var args = std.process.args(); -pub fn main() !void { - var args = process.args(); + const program_name = args.next().?; - const program_name = try args.next(heap.page_allocator) orelse unreachable; - defer heap.page_allocator.free(program_name); - - debug.warn("{}\n", .{program_name}); + std.debug.print("{s}\n", .{program_name}); } diff --git a/Task/Program-termination/OPL/program-termination.opl b/Task/Program-termination/OPL/program-termination.opl new file mode 100644 index 0000000000..68227587ea --- /dev/null +++ b/Task/Program-termination/OPL/program-termination.opl @@ -0,0 +1,3 @@ +PROC main: + IF 1 :STOP :ENDIF +ENDP diff --git a/Task/Proper-divisors/ALGOL-60/proper-divisors.alg b/Task/Proper-divisors/ALGOL-60/proper-divisors.alg new file mode 100644 index 0000000000..86600b0d28 --- /dev/null +++ b/Task/Proper-divisors/ALGOL-60/proper-divisors.alg @@ -0,0 +1,77 @@ +begin + +comment - return n mod m; +integer procedure mod(n, m); + value n, m; integer n, m; +begin + mod := n - entier(n / m) * m; +end; + +comment - count, and optionally display, proper divisors of n; +integer procedure pdc(n, display); + value n; integer n; boolean display; +begin + integer i, limit, count; + count := 1; + i := 2; + limit := n / 2; + if display then + begin + outinteger(1,n); outstring(1,": "); outinteger(1,1); + end; + for i := i while i <= limit do + begin + if mod(n, i) = 0 then + begin + if display then outinteger(1,i); + count := count + 1; + end; + i := i + 1; + if count = 1 then limit := n / i; + end; + if display then outstring(1,"\n"); + pdc := count; +end; + +integer i, junk, limit; +comment - first part of task; +outstring(1,"Proper divisors of first ten numbers\n"); +for i := 1 step 1 until 10 do + junk := pdc(i, true); comment - we don't need the return value; +outstring(1,"\n"); + +comment + Calling pdc() 20000 times to find the highest number of proper + divisors turns out to be hugely inefficient, so we take a + different approach for the second part of the task; +limit := 20000; +outstring(1,"Searching to"); outinteger(1,limit); +outstring(1,"for number with most proper divisors:\n"); + begin + integer i, j, ndiv, highdiv, highnum; + integer array divcnt[1:limit]; + comment + Create a table of divisor counts for n = 1 to limit. + This will include n itself, so for any n, the number + of proper divisors will be one less; + for i := 1 step 1 until limit do + divcnt[i] := 0; + for i := 1 step 1 until limit do + for j := i step i until limit do + divcnt[j] := divcnt[j] + 1; + comment - search the table for the highest count; + highdiv := 1; + highnum := 1; + for i := 2 step 1 until 20000 do + begin + ndiv := divcnt[i] - 1; + if ndiv > highdiv then + begin + highdiv := ndiv; + highnum := i; + end; + end; + outstring(1,"The number is"); outinteger(1,highnum); + outstring(1,"with"); outinteger(1,highdiv); + outstring(1,"divisors"); + end; diff --git a/Task/Proper-divisors/REXX/proper-divisors-2.rexx b/Task/Proper-divisors/REXX/proper-divisors-2.rexx index c65788c22e..63dadc2b7d 100644 --- a/Task/Proper-divisors/REXX/proper-divisors-2.rexx +++ b/Task/Proper-divisors/REXX/proper-divisors-2.rexx @@ -1,42 +1,62 @@ -/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/ -parse arg bot top inc range xtra /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/ -if top=='' | top=="," then top= 10 /* " " " " " " */ -if inc=='' | inc=="," then inc= 1 /* " " " " " " */ -if range=='' | range=="," then range= 20000 /* " " " " " " */ -w= max( length(top), length(bot), length(range)) /*determine the biggest number of these*/ -numeric digits max(9, w + 1) /*have enough digits for // operator.*/ -@.= 'and' /*a literal used to separate #s in list*/ - do n=bot to top by inc /*process the first range specified. */ - q= Pdivs(n); #= words(q) /*get proper divs; get number of Pdivs.*/ - if q=='∞' then #= q /*adjust number of Pdivisors for zero. */ - say right(n, max(20, w) ) 'has' center(#, 4) "proper divisors: " q - end /*n*/ -m= 0 /*M ≡ maximum number of Pdivs (so far).*/ - do r=1 for range; q= Pdivs(r) /*process the second range specified. */ - #= words(q); if # m then do + m = n; j = i + end +end +n = Divisors(j)-1 +say j 'has' n 'proper divisors' +say +return + +Task4: +procedure expose divi. +arg xx +say 'Some numbers with a lot of proper divisors...' +a = '1441440 21621600 6983776800 321253732800 65214507758400 6064949221531200 224403121196654400' +do w = 1 to Words(a) + n = Word(a,w) + say n 'has' Divisor(n)-1 'proper divisors' +end +say +return + +include Sequences +include Functions +include Special +include Abend diff --git a/Task/Proper-divisors/REXX/proper-divisors-3.rexx b/Task/Proper-divisors/REXX/proper-divisors-3.rexx deleted file mode 100644 index f3c25561cb..0000000000 --- a/Task/Proper-divisors/REXX/proper-divisors-3.rexx +++ /dev/null @@ -1,46 +0,0 @@ -/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/ -parse arg bot top inc range xtra /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/ -if top=='' | top=="," then top= 10 /* " " " " " " */ -if inc=='' | inc=="," then inc= 1 /* " " " " " " */ -if range=='' | range=="," then range= 20000 /* " " " " " " */ -w= max( length(top), length(bot), length(range)) /*determine the biggest number of these*/ -numeric digits max(9, w + 1) /*have enough digits for // operator.*/ -@.= 'and' /*a literal used to separate #s in list*/ - do n=bot to top by inc /*process the first range specified. */ - q= Pdivs(n); #= words(q) /*get proper divs; get number of Pdivs.*/ - if q=='∞' then #= q /*adjust number of Pdivisors for zero. */ - say right(n, max(20, w) ) 'has' center(#, 4) "proper divisors: " q - end /*n*/ -m= 0 /*M ≡ maximum number of Pdivs (so far).*/ - do r=1 for range; q= Pdivs(r) /*process the second range specified. */ - #= words(q); if #1; q=q%4; _= z-r-q; r=r%2; if _>=0 then do; z=_; r=r+q; end - end /*while q>1*/ /* [↑] compute the integer sqrt of X.*/ - a=1 /* [↓] use all, or only odd #s. ___ */ - do j=2 +odd by 1 +odd to r -(r*r==x) /*divide by some integers up to √ X */ - if x//j==0 then do; a=a j; b=x%j b /*if ÷, add both divisors to α & ß. */ - end - end /*j*/ /* [↑] % is the REXX integer division*/ - /* [↓] adjust for a square. ___*/ - if j*j==x then return a j b /*Was X a square? If so, add √ X */ - return a b /*return the divisors (both lists). */ diff --git a/Task/Proper-divisors/REXX/proper-divisors-4.rexx b/Task/Proper-divisors/REXX/proper-divisors-4.rexx deleted file mode 100644 index 7cab6f6b79..0000000000 --- a/Task/Proper-divisors/REXX/proper-divisors-4.rexx +++ /dev/null @@ -1,53 +0,0 @@ -/*REXX program finds proper divisors (and count) of integer ranges; finds the max count.*/ -parse arg bot top inc range xtra /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot= 1 /*Not specified? Then use the default.*/ -if top=='' | top=="," then top= 10 /* " " " " " " */ -if inc=='' | inc=="," then inc= 1 /* " " " " " " */ -if range=='' | range=="," then range= 20000 /* " " " " " " */ -w= max( length(top), length(bot), length(range)) /*determine the biggest number of these*/ -numeric digits max(9, w + 1) /*have enough digits for // operator.*/ -@.= 'and' /*a literal used to separate #s in list*/ - do n=bot to top by inc /*process the first range specified. */ - q= Pdivs(n); #= words(q) /*get proper divs; get number of Pdivs.*/ - if q=='∞' then #= q /*adjust number of Pdivisors for zero. */ - say right(n, max(20, w) ) 'has' center(#, 4) "proper divisors: " q - end /*n*/ -m= 0 /*M ≡ maximum number of Pdivs (so far).*/ - do r=1 for range; q= Pdivs(r) /*process the second range specified. */ - #= words(q); if #1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end - return r -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Pdivs: procedure; parse arg x,b; x= abs(x) - if x==1 then return '' /*null set.*/ - if x==0 then return '∞' /*infinity.*/ - odd= x // 2 /*oddness of X. ___ */ - r= iSqrt(x) /* obtain the integer √ X */ - a= 1 /* [↓] use all, or only odd numbers. */ - /* ___*/ - if odd then do j=3 by 2 for r%2-(r*r==x) /*divide by some integers up to √ X */ - if x//j==0 then do; a=a j; b=x%j b /*÷? Add both divisors to A & B*/ - end - end /*j*/ /* ___*/ - else do j=2 for r-1-(r*r==x) /*divide by some integers up to √ X */ - if x//j==0 then do; a=a j; b=x%j b /*÷? Add both divisors to A & B*/ - end - end /*j*/ - if r*r==x then return a j b /*Was X a square? If so, add √ X */ - return a b /*return proper divisors (both lists).*/ diff --git a/Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Rust/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.rs b/Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Rust/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.rs new file mode 100644 index 0000000000..215239b2cb --- /dev/null +++ b/Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Rust/pseudo-random-numbers-combined-recursive-generator-mrg32k3a.rs @@ -0,0 +1,89 @@ +fn mod_fn(x: i64, y: i64) -> i64 { + let m = x % y; + if m < 0 { + if y < 0 { + return m - y; + } else { + return m + y; + } + } + m +} + +struct RNG { + // First generator + a1: [i64; 3], + m1: i64, + x1: [i64; 3], + // Second generator + a2: [i64; 3], + m2: i64, + x2: [i64; 3], + // other + d: i64, +} + +impl RNG { + fn new() -> RNG { + RNG { + a1: [0, 1403580, -810728], + m1: (1i64 << 32) - 209, + x1: [0, 0, 0], + a2: [527612, 0, -1370589], + m2: (1i64 << 32) - 22853, + x2: [0, 0, 0], + d: (1i64 << 32) - 209 + 1, + } + } + + fn seed(&mut self, state: i64) { + self.x1 = [state, 0, 0]; + self.x2 = [state, 0, 0]; + } + + fn next_int(&mut self) -> i64 { + let x1i = mod_fn( + self.a1[0] * self.x1[0] + self.a1[1] * self.x1[1] + self.a1[2] * self.x1[2], + self.m1, + ); + let x2i = mod_fn( + self.a2[0] * self.x2[0] + self.a2[1] * self.x2[1] + self.a2[2] * self.x2[2], + self.m2, + ); + let z = mod_fn(x1i - x2i, self.m1); + + // keep last three values of the first generator + self.x1 = [x1i, self.x1[0], self.x1[1]]; + // keep last three values of the second generator + self.x2 = [x2i, self.x2[0], self.x2[1]]; + + z + 1 + } + + fn next_float(&mut self) -> f64 { + self.next_int() as f64 / self.d as f64 + } +} + +fn main() { + let mut rng = RNG::new(); + + rng.seed(1234567); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!(); + + let mut counts: [i32; 5] = [0, 0, 0, 0, 0]; + rng.seed(987654321); + for _i in 0..100000 { + let value = (rng.next_float() * 5.0).floor() as usize; + counts[value] += 1; + } + + for i in 0..counts.len() { + println!("{}: {}", i, counts[i]); + } +} diff --git a/Task/Pseudo-random-numbers-Middle-square-method/Rust/pseudo-random-numbers-middle-square-method.rs b/Task/Pseudo-random-numbers-Middle-square-method/Rust/pseudo-random-numbers-middle-square-method.rs new file mode 100644 index 0000000000..49bf646e49 --- /dev/null +++ b/Task/Pseudo-random-numbers-Middle-square-method/Rust/pseudo-random-numbers-middle-square-method.rs @@ -0,0 +1,54 @@ +use std::fmt; + +#[derive(Debug)] +struct MiddleSquare { + state: u64, + div: u64, + modulo: u64, +} + +impl MiddleSquare { + fn new(start: u64, length: u64) -> Result { + if length % 2 != 0 { + return Err("length must be even"); + } + + let mut div = 1; + let mut modulo = 1; + + for _ in 0..(length / 2) { + div *= 10; + } + + for _ in 0..length { + modulo *= 10; + } + + Ok(MiddleSquare { + state: start % modulo, + div, + modulo, + }) + } + + fn next(&mut self) -> u64 { + self.state = (self.state * self.state / self.div) % self.modulo; + self.state + } +} + +impl fmt::Display for MiddleSquare { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MiddleSquare {{ state: {}, div: {}, modulo: {} }}", self.state, self.div, self.modulo) + } +} + +fn main() -> Result<(), &'static str> { + let mut msq = MiddleSquare::new(675248, 6)?; + + for _ in 0..5 { + println!("{}", msq.next()); + } + + Ok(()) +} diff --git a/Task/Pseudo-random-numbers-Splitmix64/Rust/pseudo-random-numbers-splitmix64.rs b/Task/Pseudo-random-numbers-Splitmix64/Rust/pseudo-random-numbers-splitmix64.rs new file mode 100644 index 0000000000..0e9a34b514 --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/Rust/pseudo-random-numbers-splitmix64.rs @@ -0,0 +1,57 @@ +struct Splitmix64 { + state: u64, + two_power_64: f64, +} + +impl Splitmix64 { + fn new() -> Self { + Splitmix64 { + state: 0, + two_power_64: (2.0_f64).powi(64), + } + } + + fn with_seed(seed: u64) -> Self { + Splitmix64 { + state: seed, + two_power_64: (2.0_f64).powi(64), + } + } + + fn seed(&mut self, seed: u64) { + self.state = seed; + } + + fn next_int(&mut self) -> u64 { + let mut z = self.state.wrapping_add(0x9e3779b97f4a7c15); + self.state = z; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb); + z ^ (z >> 31) + } + + fn next_float(&mut self) -> f64 { + self.next_int() as f64 / self.two_power_64 + } +} + +fn main() { + let mut random = Splitmix64::new(); + random.seed(1234567); + for _i in 0..5 { + println!("{}", random.next_int()); + } + println!(); + + let mut rand = Splitmix64::with_seed(987654321); + let mut counts = vec![0_u32; 5]; + for _i in 0..100_000 { + let value = (rand.next_float() * 5.0).floor() as u32; + counts[value as usize] += 1; + } + + for i in 0..5 { + print!("{}: {} ", i, counts[i as usize]); + } + println!(); +} diff --git a/Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg b/Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg new file mode 100644 index 0000000000..24cb697aa9 --- /dev/null +++ b/Task/Pythagoras-tree/ALGOL-68/pythagoras-tree.alg @@ -0,0 +1,95 @@ +BEGIN # draw a pythagoras tree, using SVG # + + MODE POS = REAL; # MODE holding a coordinate # + + # operators for formatting # + OP BYTETOHEX = ( INT v )CHAR: + REPR IF v < 10 THEN ABS "0" + v ELSE ABS "A" + ( v - 10 ) FI; + OP TOHEX = ( INT v in )STRING: + IF v in = 0 + THEN "0" + ELSE INT v := vin; + STRING result := ""; + WHILE v > 0 DO + BYTETOHEX ( v MOD 16 ) +=: result; + v OVERAB 16 + OD; + result + FI # TOHEX # ; + OP FMT = ( INT v )STRING: whole( v, 0 ); + PRIO FMT = 9; + OP FMT = ( REAL v, INT dp )STRING: + IF v = ENTIER v OR dp = 0 + THEN whole( v, 0 ) + ELSE STRING result = fixed( v, - dp * 16, ABS dp ); + INT v pos := LWB result; + WHILE result[ v pos ] = " " DO v pos +:= 1 OD; + result[ v pos : ] + FI # FMT # ; + + # draws a polygon, points must have an even number of elements # + PROC polygon = ( []POS points, INT fill, stroke, REAL line width )VOID: + BEGIN + print( ( " ", newline ) ) + END # polygon # ; + PROC square = ( POS x1, y1, x2, y2, x3, y3, x4, y4 + , INT fill, stroke + , REAL line width + ) VOID: polygon( ( x1, y1, x2, y2, x3, y3, x4, y4 ), fill, stroke, line width ); + PROC triangle = ( POS x1, y1, x2, y2, x3, y3 + , INT fill, stroke + , REAL line width + ) VOID: polygon( ( x1, y1, x2, y2, x3, y3 ), fill, stroke, line width ); + + PROC draw pythagoras tree = ( INT height + , POS x1, y1, x2, y2 + , INT depth, max depth + , REAL line width + ) VOID: + IF depth < max depth THEN + POS dx = x2 - x1; + POS dy = y1 - y2; + POS x3 = x2 + dy; + POS y3 = y2 + dx; + POS x4 = x1 + dy; + POS y4 = y1 + dx; + POS x5 = x4 + 0.5 * ( dx + dy ); + POS y5 = y4 + 0.5 * ( dx - dy ); + INT r = 255 - ROUND ( 255 * ( 0.01 + ( depth / 10 ) ) ); + INT g = 255 - ROUND ( 255 * ( 0.01 + ( depth / 20 ) ) ); + INT b = g OVER 3; + INT fill = ( ( ( r * 256 ) + g ) * 256 ) + b; + INT stroke = ABS 16r 444444; + # inveret the y-axis, so y=0 is at the bottom # + POS i1 = height - y1, i2 = height - y2, i3 = height - y3; + POS i4 = height - y4, i5 = height - y5; + square( x1, i1, x2, i2, x3, i3, x4, i4, fill, stroke, line width ); + triangle( x3, i3, x4, i4, x5, i5, fill, stroke, line width ); + draw pythagoras tree( height, x4, y4, x5, y5, depth + 1, max depth, line width ); + draw pythagoras tree( height, x5, y5, x3, y3, depth + 1, max depth, line width ) + FI # draw pythagoras tree # ; + + PROC pythagoras tree = ( INT width, height + , POS x1, y1, x2, y2 + , INT max depth + , REAL line width + ) VOID: + BEGIN + print( ( "", newline ) ); + draw pythagoras tree( height, x1, y1, x2, y2, 0, max depth, line width ); + print( ( "", newline ) ) + END # pythagoras tree #; + + pythagoras tree( 120, 90, 51, 10, 69, 10, 10, 0.03 ) + +END diff --git a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy index bcba9c01e1..17eec9353f 100644 --- a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy +++ b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy @@ -1,4 +1,4 @@ -proc tree x1 y1 x2 y2 depth . . +proc tree x1 y1 x2 y2 depth . if depth < 8 dx = x2 - x1 dy = y1 - y2 @@ -8,9 +8,9 @@ proc tree x1 y1 x2 y2 depth . . y4 = y1 + dx x5 = x4 + 0.5 * (dx + dy) y5 = y4 + 0.5 * (dx - dy) - color3 0.3 0.2 + depth / 18 0.1 - polygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] - polygon [ x3 y3 x4 y4 x5 y5 ] + gcolor3 0.3 0.2 + depth / 18 0.1 + gpolygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] + gpolygon [ x3 y3 x4 y4 x5 y5 ] tree x4 y4 x5 y5 depth + 1 tree x5 y5 x3 y3 depth + 1 . diff --git a/Task/Pythagoras-tree/Maple/pythagoras-tree.maple b/Task/Pythagoras-tree/Maple/pythagoras-tree.maple new file mode 100644 index 0000000000..12c71e74bc --- /dev/null +++ b/Task/Pythagoras-tree/Maple/pythagoras-tree.maple @@ -0,0 +1,23 @@ +pythtree := proc(ax, ay, bx, By, P, colors, depth) + local dx, dy, x3, y3, x4, y4, x5, y5; + if depth <= 0 then return; end if; + dx:=bx-ax; dy:=ay-By; + x3:=bx-dy; y3:=By-dx; + x4:=ax-dy; y4:=ay-dx; + x5:=x4+(dx-dy)/2; y5:=y4-(dx+dy)/2; + + P ,= plots:-polygonplot([ax,bx,x3,x4,ax],-[ay,By,y3,y4,ay],color=colors[depth]); + P ,= plots:-polygonplot([x4,x5,x3],-[y4,y5,y3],color=colors[depth]); + + pythtree(x4, y4, x5, y5, P, colors, depth - 1); + pythtree(x5, y5, x3, y3, P, colors, depth - 1); +end proc: + +pythagorastree := proc(x1, y1, x2, y2, size, maxdep) + local P := Array(1..0); + local colors := ColorTools:-Gradient("Green".."yellow",number=maxdep): + pythtree(x1, y1, x2, y2, P, colors, maxdep); + plots:-display(convert(P,list),axes=none); +end proc: + +pythagorastree(275.,500.,375.,500.,640., 9); diff --git a/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy b/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy index 1d8b36eaeb..4064a9bc74 100644 --- a/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy +++ b/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy @@ -1,5 +1,5 @@ global total prim maxperi . -proc newtri s0 s1 s2 . . +proc newtri s0 s1 s2 . p = s0 + s1 + s2 if p <= maxperi prim += 1 diff --git a/Task/QR-decomposition/Rust/qr-decomposition.rs b/Task/QR-decomposition/Rust/qr-decomposition.rs new file mode 100644 index 0000000000..eb906dbf14 --- /dev/null +++ b/Task/QR-decomposition/Rust/qr-decomposition.rs @@ -0,0 +1,591 @@ +use std::fmt; +use std::ops::{Add, Mul}; // Optional: for operator overloading later if desired + +// --- Error Type --- +#[derive(Debug, PartialEq)] +pub enum MatrixError { + IncompatibleDimensions(String), + InvalidOperation(String), + OutOfBounds(String), +} + +impl fmt::Display for MatrixError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + MatrixError::IncompatibleDimensions(msg) => write!(f, "Incompatible matrix dimensions: {}", msg), + MatrixError::InvalidOperation(msg) => write!(f, "Invalid matrix operation: {}", msg), + MatrixError::OutOfBounds(msg) => write!(f, "Index out of bounds: {}", msg), + } + } +} + +// Define a Result type alias for convenience +type MatrixResult = Result; + +// --- Matrix Struct --- +#[derive(Debug, Clone)] // Added Debug and Clone +pub struct Matrix { + rows: usize, + cols: usize, + data: Vec>, +} + +impl Matrix { + // --- Constructors --- + + /// Creates a matrix from existing 2D vector data. + /// Validates that all inner vectors have the same length. + pub fn from_data(data: Vec>) -> MatrixResult { + if data.is_empty() { + // Handle empty case: 0x0 matrix + return Ok(Matrix { rows: 0, cols: 0, data }); + } + let rows = data.len(); + let cols = data[0].len(); + // Validate dimensions + if !data.iter().all(|row| row.len() == cols) { + return Err(MatrixError::IncompatibleDimensions( + "All rows must have the same number of columns".to_string(), + )); + } + Ok(Matrix { rows, cols, data }) + } + + /// Creates a new matrix with specified dimensions, initialized to zeros. + pub fn zeros(rows: usize, cols: usize) -> Self { + let data = vec![vec![0.0; cols]; rows]; + Matrix { rows, cols, data } + } + + // --- Accessors --- + + pub fn rows(&self) -> usize { + self.rows + } + + pub fn cols(&self) -> usize { + self.cols + } + + /// Gets the value at a specific row and column. Returns None if out of bounds. + pub fn get(&self, row: usize, col: usize) -> Option { + self.data.get(row)?.get(col).copied() + } + + /// Gets the value at a specific row and column. Returns Error if out of bounds. + pub fn get_entry(&self, row: usize, col: usize) -> MatrixResult { + self.data + .get(row) + .and_then(|r| r.get(col)) + .copied() + .ok_or_else(|| MatrixError::OutOfBounds(format!("Accessing ({}, {}) in {}x{} matrix", row, col, self.rows, self.cols))) + } + + + /// Sets the value at a specific row and column. Returns Error if out of bounds. + pub fn set_entry(&mut self, row: usize, col: usize, value: f64) -> MatrixResult<()> { + self.data + .get_mut(row) + .and_then(|r| r.get_mut(col)) + .map(|entry| *entry = value) + .ok_or_else(|| MatrixError::OutOfBounds(format!("Setting ({}, {}) in {}x{} matrix", row, col, self.rows, self.cols))) + } + + + // --- Basic Matrix Operations --- + + /// Adds another matrix to this matrix. + pub fn add(&self, other: &Matrix) -> MatrixResult { + if self.rows != other.rows || self.cols != other.cols { + return Err(MatrixError::IncompatibleDimensions(format!( + "Cannot add {}x{} matrix to {}x{} matrix", + self.rows, self.cols, other.rows, other.cols + ))); + } + + let mut result_data = self.data.clone(); // Start with a copy + for i in 0..self.rows { + for j in 0..self.cols { + result_data[i][j] += other.data[i][j]; + } + } + Ok(Matrix { + rows: self.rows, + cols: self.cols, + data: result_data, + }) + } + + /// Multiplies this matrix by another matrix. + pub fn multiply(&self, other: &Matrix) -> MatrixResult { + if self.cols != other.rows { + return Err(MatrixError::IncompatibleDimensions(format!( + "Cannot multiply {}x{} matrix by {}x{} matrix", + self.rows, self.cols, other.rows, other.cols + ))); + } + + let mut result = Matrix::zeros(self.rows, other.cols); + for i in 0..self.rows { + for j in 0..other.cols { + let mut sum = 0.0; + for k in 0..self.cols { // Note: loop limit is self.cols (or other.rows) + // Using direct access after checks for potentially better performance + // but relying on bounds being correct due to initial check. + // Safe access: sum += self.get_entry(i, k)? * other.get_entry(k, j)?; + sum += self.data[i][k] * other.data[k][j]; + } + result.data[i][j] = sum; + // Safe set: result.set_entry(i, j, sum)?; + } + } + Ok(result) + } + + /// Returns the transpose of this matrix. + pub fn transpose(&self) -> Matrix { + let mut result = Matrix::zeros(self.cols, self.rows); + for i in 0..self.rows { + for j in 0..self.cols { + // Direct access okay here as bounds are derived from self + result.data[j][i] = self.data[i][j]; + // Safe set: result.set_entry(j, i, self.get_entry(i, j).unwrap()).unwrap(); // unwrap safe + } + } + result + } + + // --- Specific Operations (used in Householder) --- + + /// Creates a matrix where elements below/right of `index` are copied, + /// and the top-left `index x index` part is an identity matrix. + /// Note: In Rust, indices start from 0. The C++ code seems to imply + /// copying starts *at* index `k`. Let's match that behavior. + pub fn minor(&self, index: usize) -> MatrixResult { + if index > self.rows || index > self.cols { + return Err(MatrixError::OutOfBounds(format!("Index {} out of bounds for minor operation on {}x{} matrix", index, self.rows, self.cols))); + } + + let mut result = Matrix::zeros(self.rows, self.cols); + // Set identity part + for i in 0..index { + result.set_entry(i, i, 1.0)?; + } + + // Copy the submatrix part + for i in index..self.rows { + for j in index..self.cols { + result.set_entry(i, j, self.get_entry(i, j)?)?; + } + } + Ok(result) + } + + /// Extracts a column as a new column vector (Nx1 matrix). + pub fn column(&self, index: usize) -> MatrixResult { + if index >= self.cols { + return Err(MatrixError::OutOfBounds(format!("Column index {} out of bounds for {}x{} matrix", index, self.rows, self.cols))); + } + let mut result = Matrix::zeros(self.rows, 1); + for i in 0..self.rows { + result.set_entry(i, 0, self.get_entry(i, index)?)?; + } + Ok(result) + } + + /// Multiplies a *column vector* matrix by a scalar. + pub fn scalar_multiply(&self, value: f64) -> MatrixResult { + if self.cols != 1 { + return Err(MatrixError::InvalidOperation(format!( + "Scalar multiply requires a column vector (Nx1), but matrix is {}x{}", + self.rows, self.cols + ))); + } + let mut result = Matrix::zeros(self.rows, 1); + for i in 0..self.rows { + result.data[i][0] = self.data[i][0] * value; + // Safe: result.set_entry(i, 0, self.get_entry(i, 0)? * value)?; + } + Ok(result) + } + + /// Normalizes a *column vector* matrix to produce a unit vector. + pub fn unit(&self) -> MatrixResult { + if self.cols != 1 { + return Err(MatrixError::InvalidOperation(format!( + "Unit vector requires a column vector (Nx1), but matrix is {}x{}", + self.rows, self.cols + ))); + } + let mag = self.magnitude()?; + if mag == 0.0 { + // Avoid division by zero, return zero vector or error? + // C++ code didn't check this, would result in NaN/Inf. Let's return error. + return Err(MatrixError::InvalidOperation("Cannot normalize a zero vector".to_string())); + } + + let mut result = Matrix::zeros(self.rows, 1); + for i in 0..self.rows { + result.data[i][0] = self.data[i][0] / mag; + // Safe: result.set_entry(i, 0, self.get_entry(i, 0)? / mag)?; + } + Ok(result) + } + + /// Calculates the L2 norm (magnitude) of a *column vector* matrix. + pub fn magnitude(&self) -> MatrixResult { + if self.cols != 1 { + return Err(MatrixError::InvalidOperation(format!( + "Magnitude requires a column vector (Nx1), but matrix is {}x{}", + self.rows, self.cols + ))); + } + let mut norm_sq = 0.0; + for i in 0..self.rows { + let val = self.data[i][0]; // Direct access okay after check + // Safe: let val = self.get_entry(i, 0)?; + norm_sq += val * val; + } + Ok(norm_sq.sqrt()) + } + + /// Returns the number of rows for a *column vector* matrix. (Equivalent to `rows()`). + /// Kept for closer C++ API parity, but `rows()` is more general. + pub fn size(&self) -> MatrixResult { + if self.cols != 1 { + return Err(MatrixError::InvalidOperation(format!( + "Size operation requires a column vector (Nx1), but matrix is {}x{}", + self.rows, self.cols + ))); + } + Ok(self.rows) + } + + // --- Display --- + // Implemented via `fmt::Display` trait below +} + +// --- Display Trait Implementation --- +impl fmt::Display for Matrix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for i in 0..self.rows { + for j in 0..self.cols { + // Format similar to C++ setw(9), fixed, setprecision(4) + write!(f, "{:>9.4}", self.data[i][j])?; + } + writeln!(f)?; // Newline after each row + } + Ok(()) // No extra newline like C++ display function + } +} + +// --- Helper Functions (translated from C++) --- + +type MatrixPair = (Matrix, Matrix); // R, Q + +/// Creates a Householder reflection matrix H = I - 2*v*v^T +/// Expects `vector` to be a column vector (Nx1). +/// Note: The C++ code assumes `vector` is already a unit vector based on usage in `householder`. +fn householder_factor(vector: &Matrix) -> MatrixResult { + if vector.cols() != 1 { + return Err(MatrixError::InvalidOperation( + "householder_factor requires a column vector".to_string() + )); + } + let size = vector.rows(); + let mut result = Matrix::zeros(size, size); + + // Calculate -2 * v * v^T + for i in 0..size { + for j in 0..size { + // Using get_entry for safety, though direct access might work if performance critical + let vi = vector.get_entry(i, 0)?; + let vj = vector.get_entry(j, 0)?; + result.set_entry(i, j, -2.0 * vi * vj)?; + } + } + + // Add identity matrix part (I - 2*v*v^T) + for i in 0..size { + let current_diag = result.get_entry(i, i)?; + result.set_entry(i, i, current_diag + 1.0)?; + } + + Ok(result) +} + +/// Performs QR decomposition using Householder reflections. +/// Returns (R, Q) where A = Q*R. +fn householder(matrix: &Matrix) -> MatrixResult { + let rows = matrix.rows(); + let cols = matrix.cols(); + let mut versions_of_q: Vec = Vec::new(); + let mut z = matrix.clone(); // Start with a copy of the original matrix + + let limit = std::cmp::min(cols, rows.saturating_sub(1)); // k < cols && k < rows - 1 + + for k in 0..limit { + // The C++ minor(k) creates a matrix with identity in top-left kxk + // and the rest copied from z. + let z1 = z.minor(k)?; // This seems intended to operate on submatrices implicitly + + // Extract the k-th column from the 'minor' matrix starting from row k + // In C++, minor(k) zeros upper part, so column(k) effectively takes from row k down. + // We need to replicate this specific sub-vector extraction logic. + + // --- Corrected Subvector Extraction --- + // Create a vector x of size (rows - k) x 1 from column k of z, starting at row k. + let sub_vec_rows = rows - k; + let mut vector_x = Matrix::zeros(sub_vec_rows, 1); + for i in 0..sub_vec_rows { + vector_x.set_entry(i, 0, z1.get_entry(k + i, k)?)?; // Use z1 as per C++ code + } + // --- + + let mut magnitude_x = vector_x.magnitude()?; + + // Sign adjustment based on the diagonal element z[k][k] + // Use the *original* z matrix's diagonal element for the sign check. + if z.get_entry(k, k)? > 0.0 { + magnitude_x = -magnitude_x; + } + + // Create e_k vector (standard basis vector, scaled) + // This corresponds to the first element of the sub_vector space. + let mut vector_e = Matrix::zeros(sub_vec_rows, 1); + if sub_vec_rows > 0 { + vector_e.set_entry(0, 0, 1.0)?; // e_k in the subspace is (1, 0, 0...) + } + + + // Calculate Householder vector v = (x + sign(x_k)*||x||*e_k) / ||...|| + // C++: vectorE = vectorE.scalarMultiply(magnitudeX).add(vectorX).unit(); + let v_unnormalized = vector_e.scalar_multiply(magnitude_x)?.add(&vector_x)?; + let vector_v = v_unnormalized.unit()?; // This is the normalized Householder vector v + + + // Construct the full-size Householder reflector Q_k + // The reflection calculated using vector_v (size m-k) needs to be embedded + // into an m x m matrix: Q_k = diag(I_k, H') where H' is from vector_v. + let mut qk = Matrix::zeros(rows, rows); + // Identity part + for i in 0..k { + qk.set_entry(i,i, 1.0)?; + } + // Householder reflection part (H') for the submatrix + let h_prime = householder_factor(&vector_v)?; + for i in 0..sub_vec_rows { + for j in 0..sub_vec_rows { + qk.set_entry(k+i, k+j, h_prime.get_entry(i, j)?)?; + } + } + + + versions_of_q.push(qk.clone()); // Store Q_k + z = qk.multiply(&z)?; // Update z: z = Q_k * z + } + + // Calculate final Q = Q_{limit-1} * ... * Q_1 * Q_0 + // Note: The C++ code seems to have Q = Q_k ... Q_0. Let's verify. + // Standard definition is A = QR => Q^T A = R => R = Q_k ... Q_0 A + // And Q = (Q_k ... Q_0)^T = Q_0^T ... Q_k^T = Q_0 ... Q_k (since Q_i are symmetric) + // So the C++ multiplication order seems correct. + + if versions_of_q.is_empty() { + // Handle case where no reflections were needed (e.g., 1xN matrix) + // Q should be identity, R should be the original matrix + let mut identity_q = Matrix::zeros(rows, rows); + for i in 0..rows { + identity_q.set_entry(i,i, 1.0)?; + } + return Ok((matrix.clone(), identity_q)); // R=A, Q=I + } + + let mut final_q = versions_of_q[0].clone(); + for i in 1..versions_of_q.len() { + // This order Q = Q_i * Q might be reversed? + // Let's follow C++: Q = Q[i].multiply(Q); + // If Q = Q_{k-1} ... Q_0, then multiplying Q_i * Q is Q_i * Q_{i-1} * ... * Q_0 + // This matches the required product order. + final_q = versions_of_q[i].multiply(&final_q)?; + } + + // Calculate R = Q * A (where Q here is Q_k...Q_0) + let r_matrix = final_q.multiply(matrix)?; + + // The actual Q in A=QR is the transpose of the accumulated reflections product. + // Q = (Q_k...Q_0)^T = Q_0...Q_k + // The C++ code calculates Q = Q_k...Q_0 and then transposes it at the end. + let q_matrix = final_q.transpose(); + + // The C++ returns (R, Q). Let's match that order. + Ok((r_matrix, q_matrix)) +} + + +/// Solves Rx = b where R is an upper triangular matrix using back-substitution. +/// `r` is the upper triangular matrix (NxN). +/// `b` is the right-hand side column vector (Nx1). +/// Returns the solution column vector `x` (Nx1). +fn solve_upper_triangular(r: &Matrix, b: &Matrix) -> MatrixResult { + if r.rows() != b.rows() || b.cols() != 1 { + return Err(MatrixError::IncompatibleDimensions(format!( + "R ({0}x{0}) and b ({1}x{2}) dimensions mismatch for solving Rx=b", + r.rows(), b.rows(), b.cols() + ))); + } + + let n = r.cols(); + let mut result = Matrix::zeros(n, 1); + + // Iterate backwards from the last row (n-1) up to 0 + for k in (0..n).rev() { + let mut total = 0.0; + // Calculate sum(R[k,j] * x[j]) for j from k+1 to n-1 + for j in (k + 1)..n { + total += r.get_entry(k, j)? * result.get_entry(j, 0)?; + } + + // Check for zero on diagonal (singular matrix) + let r_kk = r.get_entry(k, k)?; + if r_kk.abs() < 1e-10 { // Use tolerance for floating point + return Err(MatrixError::InvalidOperation("Matrix R is singular or near-singular.".to_string())); + } + + // Calculate x[k] = (b[k] - total) / R[k,k] + let val = (b.get_entry(k, 0)? - total) / r_kk; + result.set_entry(k, 0, val)?; + } + + Ok(result) +} + + +/// Solves the least squares problem Ax = b using QR decomposition. +/// `vandermonde` corresponds to matrix A. +/// `b` is the right-hand side vector. +fn least_squares(vandermonde: &Matrix, b: &Matrix) -> MatrixResult { + // Perform QR decomposition: A = QR + let (r_matrix, q_matrix) = householder(vandermonde)?; + + // We need to solve Rx = Q^T * b + // Our householder returns (R, Q), so Q^T is Q.transpose() + let q_transpose = q_matrix.transpose(); + let q_transpose_b = q_transpose.multiply(b)?; + + // The system might be Ax=b where A is MxN, M > N. + // QR decomposition gives A = QR where Q is MxM orthogonal, R is MxN upper trapezoidal. + // Q^T A = R => Q^T (Ax) = Q^T b => R x = Q^T b + // R = [ R' ] where R' is NxN upper triangular + // [ 0 ] + // Q^T b = [ c1 ] where c1 is Nx1 + // [ c2 ] + // We solve R' x = c1. + + let n = vandermonde.cols(); // Number of columns in A = number of variables in x + if r_matrix.rows() < n { + return Err(MatrixError::InvalidOperation("R matrix has fewer rows than columns needed for solving.".to_string())); + } + + // Extract the top NxN part of R (R') + let mut r_prime = Matrix::zeros(n, n); + for i in 0..n { + for j in i..n { // Upper triangular part + r_prime.set_entry(i, j, r_matrix.get_entry(i, j)?)?; + } + } + + // Extract the top N rows of Q^T * b (c1) + let mut c1 = Matrix::zeros(n, 1); + if q_transpose_b.rows() < n { + return Err(MatrixError::InvalidOperation("Q^T*b vector has fewer rows than needed for solving.".to_string())); + } + for i in 0..n { + c1.set_entry(i, 0, q_transpose_b.get_entry(i, 0)?)?; + } + + + // Solve the upper triangular system R' x = c1 + solve_upper_triangular(&r_prime, &c1) +} + +/// Fits a polynomial of a given degree to data points (x, y). +/// `x` is a 1xN row vector of x-coordinates. +/// `y` is a 1xN row vector of y-coordinates. +/// Returns the polynomial coefficients as a column vector. +fn fit_polynomial(x: &Matrix, y: &Matrix, polynomial_degree: usize) -> MatrixResult { + // Validate input dimensions + if x.rows() != 1 || y.rows() != 1 || x.cols() != y.cols() { + return Err(MatrixError::IncompatibleDimensions( + "x and y must be 1xN matrices with the same N".to_string() + )); + } + let num_points = x.cols(); + let num_coeffs = polynomial_degree + 1; + + // Create the Vandermonde matrix (MxN where M=num_points, N=num_coeffs) + let mut vandermonde = Matrix::zeros(num_points, num_coeffs); + for i in 0..num_points { // Iterate through data points (rows of Vandermonde) + let x_val = x.get_entry(0, i)?; + for j in 0..num_coeffs { // Iterate through powers (columns of Vandermonde) + vandermonde.set_entry(i, j, x_val.powi(j as i32))?; // V[i, j] = x_i ^ j + } + } + + // The least squares function expects b as a column vector. + // Our y is currently a row vector. Transpose it. + let y_col = y.transpose(); + + // Solve the least squares problem Vc = y + least_squares(&vandermonde, &y_col) +} + + +// --- Main Function (example usage) --- +fn main() -> MatrixResult<()> { + let data = vec![ + vec![12.0, -51.0, 4.0], + vec![6.0, 167.0, -68.0], + vec![-4.0, 24.0, -41.0], + vec![-1.0, 1.0, 0.0], + vec![2.0, 0.0, 3.0], + ]; + + // Task 1: QR Decomposition + println!("--- Task 1: QR Decomposition ---"); + let a = Matrix::from_data(data)?; + println!("Initial matrix A:"); + println!("{}", a); + + let (r_matrix, q_matrix) = householder(&a)?; // Returns (R, Q) + + println!("Matrix Q:"); + println!("{}", q_matrix); + println!("Matrix R:"); + println!("{}", r_matrix); + + let result = q_matrix.multiply(&r_matrix)?; + println!("Matrix Q * R:"); + println!("{}", result); + + // Task 2: Polynomial Fitting + println!("--- Task 2: Polynomial Fitting ---"); + let x = Matrix::from_data(vec![vec![ + 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, + ]])?; + let y = Matrix::from_data(vec![vec![ + 1.0, 6.0, 17.0, 34.0, 57.0, 86.0, 121.0, 162.0, 209.0, 262.0, 321.0, + ]])?; + + let poly_coeffs = fit_polynomial(&x, &y, 2)?; // Fit a quadratic polynomial (degree 2) + println!("Result of fitting polynomial (coefficients c0, c1, c2):"); + println!("{}", poly_coeffs); + + // Example: Check coefficients (should be close to c0=1, c1=2, c2=3 for y = 1 + 2x + 3x^2) + // Note: The calculated coefficients might be: + // [ 1.0000 ] + // [ 2.0000 ] + // [ 3.0000 ] + + Ok(()) +} diff --git a/Task/Quaternion-type/REXX/quaternion-type.rexx b/Task/Quaternion-type/REXX/quaternion-type.rexx index fe4674ecb4..6d6eb480da 100644 --- a/Task/Quaternion-type/REXX/quaternion-type.rexx +++ b/Task/Quaternion-type/REXX/quaternion-type.rexx @@ -1,41 +1,42 @@ -/*REXX program performs some operations on quaternion type numbers and displays results*/ - q = 1 2 3 4 ; q1 = 2 3 4 5 - r = 7 ; q2 = 3 4 5 6 -call qShow q , 'q' -call qShow q1 , 'q1' -call qShow q2 , 'q2' -call qShow r , 'r' -call qShow qNorm(q) , 'norm q' , "task 1:" -call qShow qNeg(q) , 'negative q' , "task 2:" -call qShow qConj(q) , 'conjugate q' , "task 3:" -call qShow qAdd( r, q ) , 'addition r+q' , "task 4:" -call qShow qAdd(q1, q2 ) , 'addition q1+q2' , "task 5:" -call qShow qMul( q, r ) , 'multiplication q*r' , "task 6:" -call qShow qMul(q1, q2 ) , 'multiplication q1*q2' , "task 7:" -call qShow qMul(q2, q1 ) , 'multiplication q2*q1' , "task 8:" -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -qConj: procedure; parse arg x; call qXY; return x.1 (-x.2) (-x.3) (-x.4) -qNeg: procedure; parse arg x; call qXY; return -x.1 (-x.2) (-x.3) (-x.4) -qNorm: procedure; parse arg x; call qXY; return sqrt(x.1**2 +x.2**2 +x.3**2 +x.4**2) -qAdd: procedure; parse arg x,y; call qXY 2; return x.1+y.1 x.2+y.2 x.3+y.3 x.4+y.4 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -qMul: procedure; parse arg x,y; call qXY y - return x.1*y.1 -x.2*y.2 -x.3*y.3 -x.4*y.4 x.1*y.2 +x.2*y.1 +x.3*y.4 -x.4*y.3 , - x.1*y.3 -x.2*y.4 +x.3*y.1 +x.4*y.2 x.1*y.4 +x.2*y.3 -x.3*y.2 +x.4*y.1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -qShow: procedure; parse arg x; call qXY; $= - do m=1 for 4; _= x.m; if _==0 then iterate; if _>=0 then _= '+'_ - if m\==1 then _= _ || substr('∙ijk', m, 1); $= strip($ || _, , "+") - end /*m*/ - say left(arg(3), 9) right(arg(2), 20) ' ──► ' $; return $ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -qXY: do n=1 for 4; x.n= word( word(x, n) 0, 1)/1; end /*n*/ - if arg()==1 then do m=1 for 4; y.m= word( word(y, m) 0, 1)/1; end /*m*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d= digits(); i=; m.=9; h=d+6 - numeric digits; numeric form; if x<0 then parse value -x 'i' with x i - parse value format(x, 2, 1, , 0) 'E0' with g "E" _ .; g= g *.5'e'_ % 2 - do j=0 while h>9; m.j=h; h= h % 2 + 1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g= (g + x/g)* .5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X<0 */ +-- 19 May 2025 +include Settings + +say 'QUATERNION TYPE' +say version +say +i = '0 1'; j = '0 0 1'; k = '0 0 0 1' +q = '1 2 3 4'; q1 = '2 3 4 5'; q2 = '3 4 5 6'; r = 7 +say 'VALUES' +say 'i =' Hlst2Form(i) +say 'j =' Hlst2Form(j) +say 'k =' Hlst2Form(k) +say 'q =' Hlst2Form(q) +say 'q1 =' Hlst2Form(q1) +say 'q2 =' Hlst2Form(q2) +say 'r =' Hlst2Form(r) +say +say 'BASICS' +say 'i*i =' Hlst2Form(Hsquare(i)) +say 'j*j =' Hlst2Form(Hsquare(j)) +say 'k*k =' Hlst2Form(Hsquare(k)) +say 'i*j*k =' Hlst2Form(Hmul(i,j,k)) +say '||q|| =' Std(Hnorm(q)) +say '-q =' Hlst2Form(Hneg(q)) +say 'q* =' Hlst2Form(Hconj(q)) +say 'q+r =' Hlst2Form(Hadd(q,r)) +say 'r+q =' Hlst2Form(Hadd(r,q)) +say 'q1+q2 =' Hlst2Form(Hadd(q1,q2)) +say 'q2+q1 =' Hlst2Form(Hadd(q2,q1)) +say 'q*r =' Hlst2Form(Hmul(q,r)) +say 'r*q =' Hlst2Form(Hmul(r,q)) +say 'q1*q2 =' Hlst2Form(Hmul(q1,q2)) +say 'q2*q1 =' Hlst2Form(Hmul(q2,q1)) +say +say 'BONUS' +say 'q/r =' Hlst2Form(Hdiv(q,r)) +say '1/q =' Hlst2Form(Hinv(q)) +exit + +include Quaternion +include Functions +include Abend diff --git a/Task/Queue-Definition/EasyLang/queue-definition.easy b/Task/Queue-Definition/EasyLang/queue-definition.easy index f59c254ed9..a05a51a1fe 100644 --- a/Task/Queue-Definition/EasyLang/queue-definition.easy +++ b/Task/Queue-Definition/EasyLang/queue-definition.easy @@ -1,7 +1,7 @@ prefix qu_ global q[] head tail . # -proc enq n . . +proc enq n . if tail = 0 head = 1 else diff --git a/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy b/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy index 79f18b94cf..f4cdb174f6 100644 --- a/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy +++ b/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy @@ -1,4 +1,4 @@ -proc qselect k . list[] res . +func qselect &list[] k . # subr partition mid = left @@ -22,10 +22,9 @@ proc qselect k . list[] res . left = right . . - res = list[k] + return list[k] . d[] = [ 9 8 7 6 5 0 1 2 3 4 ] for i = 1 to len d[] - qselect i d[] r - print r + print qselect d[] i . diff --git a/Task/Quickselect-algorithm/Zig/quickselect-algorithm.zig b/Task/Quickselect-algorithm/Zig/quickselect-algorithm.zig new file mode 100644 index 0000000000..9ded83c244 --- /dev/null +++ b/Task/Quickselect-algorithm/Zig/quickselect-algorithm.zig @@ -0,0 +1,69 @@ +const std = @import("std"); + +fn partition(comptime T: type, a: []T, left: usize, right: usize, pivot: usize) usize { + std.mem.swap(T, &a[pivot], &a[right]); + var store_index = left; + var i = left; + while (i < right) : (i += 1) { + if (a[i] < a[right]) { + std.mem.swap(T, &a[store_index], &a[i]); + store_index += 1; + } + } + std.mem.swap(T, &a[right], &a[store_index]); + return store_index; +} + +fn pivotIndex(left: usize, right: usize) usize { + return left + (right - left) / 2; +} + +fn select(comptime T: type, a: []T, left_init: usize, right_init: usize, n: usize) void { + var left = left_init; + var right = right_init; + + while (true) { + if (left == right) { + break; + } + + var pivot = pivotIndex(left, right); + pivot = partition(T, a, left, right, pivot); + + if (n == pivot) { + break; + } else if (n < pivot) { + right = pivot - 1; + } else { + left = pivot + 1; + } + } +} + +// Rearranges the elements of 'a' such that the element at index 'n' is +// the same as it would be if the array were sorted, smaller elements are +// to the left of it and larger elements are to its right. +fn nthElement(comptime T: type, a: []T, n: usize) void { + select(T, a, 0, a.len - 1, n); +} + +pub fn main() !void { + const allocator = std.heap.page_allocator; + const a = [_]i32{ 9, 8, 7, 6, 5, 0, 1, 2, 3, 4 }; + + var n: usize = 0; + while (n < a.len) : (n += 1) { + var b = try allocator.alloc(i32, a.len); + defer allocator.free(b); + + // Copy elements one by one instead of using mem.copy + for (0..a.len) |i| { + b[i] = a[i]; + } + + nthElement(i32, b, n); + + const stdout = std.io.getStdOut().writer(); + try stdout.print("n = {}, nth element = {}\n", .{ n + 1, b[n] }); + } +} diff --git a/Task/Quine/Rust/quine-1.rs b/Task/Quine/Rust/quine-1.rs index 8e71d160ec..102ef358ba 100644 --- a/Task/Quine/Rust/quine-1.rs +++ b/Task/Quine/Rust/quine-1.rs @@ -1,7 +1,3 @@ fn main() { - let x = "fn main() {\n let x = "; - let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; - print!("{}{:?}; - let y = {:?}; - {}", x, x, y, y) + print!("{}", include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", file!()))); } diff --git a/Task/Quine/Rust/quine-2.rs b/Task/Quine/Rust/quine-2.rs index 88df728796..5d3dff053c 100644 --- a/Task/Quine/Rust/quine-2.rs +++ b/Task/Quine/Rust/quine-2.rs @@ -1,59 +1,4 @@ -fn main() -{ - let q = 34u8; - let p = 44u8; - let l = [ - "fn main()", - "{", - " let q = 34u8;", - " let p = 44u8;", - " let l = [", - " ", - " ];", - " let mut i = 0;", - " while i < 5", - " {", - " println(l[i]);", - " i+=1;", - " }", - " i = 0;", - " while i < l.len()", - " {", - " print(l[5]);", - " print((q as char).to_str());", - " print(l[i]);", - " print((q as char).to_str());", - " println((p as char).to_str());", - " i+=1;", - " }", - " i = 6;", - " while i < l.len()", - " {", - " println(l[i]);", - " i+=1;", - " }", - "}", - ]; - let mut i = 0; - while i < 5 - { - println(l[i]); - i+=1; - } - i = 0; - while i < l.len() - { - print(l[5]); - print((q as char).to_str()); - print(l[i]); - print((q as char).to_str()); - println((p as char).to_str()); - i+=1; - } - i = 6; - while i < l.len() - { - println(l[i]); - i+=1; - } +fn main() { + macro_rules! script {() => {"fn main() {{\n\tmacro_rules! script {{() => {{{:?}}}}}\n\tprintln!(script!(), script!());\n}}"}} + println!(script!(), script!()); } diff --git a/Task/Quine/Rust/quine-3.rs b/Task/Quine/Rust/quine-3.rs index 56e8dac1dc..8e71d160ec 100644 --- a/Task/Quine/Rust/quine-3.rs +++ b/Task/Quine/Rust/quine-3.rs @@ -1,42 +1,7 @@ - fn main(){let q:&[u8]=&[ - 32,00,00,00,00,00,00,00,61,27,80,82, - 73,78,84,76,78,01,08,02,91,93,70,78,00,77,65,73,78,08, - 09,91,91,76,69,84,00,81,26,06,59,85,24,61,29,06,59,02,12,00,51,84, - 82,73,78,71,26,26,70,82,79,77,63,85,84,70,24,08,86,69,67,01,59,66,07,00, - 07,27,00,21,20,61,09,14,85,78,87,82,65,80,08,09,09,27,76,69,84,00,82,29,08,81, - 14,76,69,78,08,09,65,83,00,70,22,20,15,83,84,68,26,26,70,22,20,32,00,00,00,00,00,00,00,00, - 00,26,26,67,79,78,83,84,83,26,26,48,41,09,14,83,81,82,84,08,09,65,83,00,73,19,18,11,20,27,76,69, - 84,00,77,85,84,00,66,26,00,54,69,67,28,08,73,19,18,12,00,73,19,18,09,00,30,29,00,54,69,67,26,26, - 78,69,87,08,09,27,00,15,10,00,00,00,79,79,69,82,00,00,10,15,00,76,69,84,00,77,85,84,00,88,29,82,13,17, - 27,00,76,69,84,00,77,85,84,00,89,29,16,27,32,00,00,00,00,00,00,00,00,00,00,76,69,84,00,77,85,84,00,75,29,17, - 27,76,69,84,00,77,85,84,00,74,29,17,27,76,69,84,00,77,85,84,00,69,29,75,00,13,08,82,28,28,17,09,27,87,72,73,76,69, - 00,88,30,29,89,91,66,14,80,85,83,72,08,08,82,11,88,12,82,11,89,09,09,27,66,14,80,85,83,72,08,08,82,11,89,12,82,11, - 88,09,09,27,00,66,14,80,85,83,72,08,08,82,13,89,12,82,11,88,09,32,00,00,00,00,00,00,00,00,00,00,00,00,00,09,27,66,14,80, - 85,83,72,08,08,82,13,88,12,00,82,11,89,09,09,27,66,14,80,85,83,72,08,08,82,13,88,12,82,13,89,09,09,27,66,14,80,85,83,72, - 08,08,82,13,89,12,82,13,88,09,09,27,00,66,14,80,85,83,72,08,08,82,11,89,12,82,13,88,09,09,27,66,14,80,85,83,72,08,08,82, - 11,88,12,82,13,89,09,09,27,00,73,70,00,69,28,29,16,91,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,89,11,29,17,27,69,11, - 29,74,27,74,11,29,18,27,93,73,70,00,69,30,16,00,91,88,13,29,17,27,75,11,29,18,27,69,11,29,75,13,08,82,28,28,17,09,27,93,93,76, - 69,84,00,77,85,84,00,84,29,81,14,73,84,69,82,08,09,27,07,79,26,70,79,82,00,89,00,73,78,00,17,14,14,82,10,18,00,91,00,76,69,84, - 00,76,26,00,54,69,67,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,28,73,19,18,30,00,29,00,66,14,73,84,69,82,08, - 09,14,70,73,76,84,69,82,08,92,88,92,00,88,14,17,29,29,89,09,14,77,65,80,08,92,88,92,00,88,14,16,09,14,67,79,76,76,69,67,84,08, - 09,27,00,76,69,84,00,88,00,29,00,76,14,73,84,69,82,08,09,14,67,76,79,78,69,68,08,09,14,70,79,76,68,08,16,12,32,00,00,00,00,00, - 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,73,19,18,26,26,77,65,88,09,27,00,76,69,84,00,78,00,29,76,14,73,84,69,82,08,09, - 14,67,76,79,78,69,68,08,09,14,70,79,76,68,08,25,25,25,12,00,73,19,18,26,26,77,73,78,09,27,76,69,84,00,77,29,88,13,78,27,00,70, - 79,82,00,63,00,73,78,00,16,14,14,78,00,91,00,80,82,73,78,84,01,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00, - 00,00,00,00,08,02,00,00,00,02,09,27,93,70,79,82,00,63,00,73,78,00,16,14,14,77,91,00,73,70,00,76,69,84,00,51,79,77,69,08,86,09, - 00,29,00,84,14,78,69,88,84,08,09,00,91,80,82,73,78,84,01,08,02,91,26,16,18,93,12,02,12,86,09,27,93,00,69,76,83,69,91,00,66,82, - 69,65,75,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,07,79,27,00,93,93,00,80,82,73, - 78,84,01,08,02,60,78,02,09,27,00,93,00,70,79,82,00,78,00,73,78,00,81,14,73,84,69,82,08,09,00,91,00,80,82,73,78,84,01,08,02,91, - 93,02,12,00,08,73,70,00,10,78,29,29,19,18,91,17,16,93,00,69,76,83,69,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00, - 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,91,10,78,11,19,18,93,09,00,65,83,00,67,72,65,82,09,27,93,80,82,73, - 78,84,01,08,02,60,78,02,09,27,93,00,15,15,00,71,73,84,72,85,66,14,67,79,77,15,75,73,82,74,65,86,65,83,67,82,73,80,84, - ];println!("{}fn main(){{let q:&[u8]=&[", String::from_utf8(vec![b' '; 54]).unwrap());let r=(q.len()as f64/std::f64 - ::consts::PI).sqrt()as i32+4;let mut b: Vec<(i32, i32) >= Vec::new(); /* ooer */ let mut x=r-1; let mut y=0; - let mut k=1;let mut j=1;let mut e=k -(r<<1);while x>=y{b.push((r+x,r+y));b.push((r+y,r+x)); b.push((r-y,r+x) - );b.push((r-x, r+y));b.push((r-x,r-y));b.push((r-y,r-x)); b.push((r+y,r-x));b.push((r+x,r-y)); if e<=0{ - y+=1;e+=j;j+=2;}if e>0 {x-=1;k+=2;e+=k-(r<<1);}}let mut t=q.iter();'o:for y in 1..r*2 { let l: Vec - = b.iter().filter(|x| x.1==y).map(|x| x.0).collect(); let x = l.iter().cloned().fold(0, - i32::max); let n =l.iter().cloned().fold(999, i32::min);let m=x-n; for _ in 0..n { print! - (" ");}for _ in 0..m{ if let Some(v) = t.next() {print!("{:02},",v);} else{ break - 'o; }} print!("\n"); } for n in q.iter() { print!("{}", (if *n==32{10} else - {*n+32}) as char);}print!("\n");} // github.com/kirjavascript +fn main() { + let x = "fn main() {\n let x = "; + let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; + print!("{}{:?}; + let y = {:?}; + {}", x, x, y, y) +} diff --git a/Task/Quine/Rust/quine-4.rs b/Task/Quine/Rust/quine-4.rs index 5d3dff053c..88df728796 100644 --- a/Task/Quine/Rust/quine-4.rs +++ b/Task/Quine/Rust/quine-4.rs @@ -1,4 +1,59 @@ -fn main() { - macro_rules! script {() => {"fn main() {{\n\tmacro_rules! script {{() => {{{:?}}}}}\n\tprintln!(script!(), script!());\n}}"}} - println!(script!(), script!()); +fn main() +{ + let q = 34u8; + let p = 44u8; + let l = [ + "fn main()", + "{", + " let q = 34u8;", + " let p = 44u8;", + " let l = [", + " ", + " ];", + " let mut i = 0;", + " while i < 5", + " {", + " println(l[i]);", + " i+=1;", + " }", + " i = 0;", + " while i < l.len()", + " {", + " print(l[5]);", + " print((q as char).to_str());", + " print(l[i]);", + " print((q as char).to_str());", + " println((p as char).to_str());", + " i+=1;", + " }", + " i = 6;", + " while i < l.len()", + " {", + " println(l[i]);", + " i+=1;", + " }", + "}", + ]; + let mut i = 0; + while i < 5 + { + println(l[i]); + i+=1; + } + i = 0; + while i < l.len() + { + print(l[5]); + print((q as char).to_str()); + print(l[i]); + print((q as char).to_str()); + println((p as char).to_str()); + i+=1; + } + i = 6; + while i < l.len() + { + println(l[i]); + i+=1; + } } diff --git a/Task/Quine/Rust/quine-5.rs b/Task/Quine/Rust/quine-5.rs new file mode 100644 index 0000000000..56e8dac1dc --- /dev/null +++ b/Task/Quine/Rust/quine-5.rs @@ -0,0 +1,42 @@ + fn main(){let q:&[u8]=&[ + 32,00,00,00,00,00,00,00,61,27,80,82, + 73,78,84,76,78,01,08,02,91,93,70,78,00,77,65,73,78,08, + 09,91,91,76,69,84,00,81,26,06,59,85,24,61,29,06,59,02,12,00,51,84, + 82,73,78,71,26,26,70,82,79,77,63,85,84,70,24,08,86,69,67,01,59,66,07,00, + 07,27,00,21,20,61,09,14,85,78,87,82,65,80,08,09,09,27,76,69,84,00,82,29,08,81, + 14,76,69,78,08,09,65,83,00,70,22,20,15,83,84,68,26,26,70,22,20,32,00,00,00,00,00,00,00,00, + 00,26,26,67,79,78,83,84,83,26,26,48,41,09,14,83,81,82,84,08,09,65,83,00,73,19,18,11,20,27,76,69, + 84,00,77,85,84,00,66,26,00,54,69,67,28,08,73,19,18,12,00,73,19,18,09,00,30,29,00,54,69,67,26,26, + 78,69,87,08,09,27,00,15,10,00,00,00,79,79,69,82,00,00,10,15,00,76,69,84,00,77,85,84,00,88,29,82,13,17, + 27,00,76,69,84,00,77,85,84,00,89,29,16,27,32,00,00,00,00,00,00,00,00,00,00,76,69,84,00,77,85,84,00,75,29,17, + 27,76,69,84,00,77,85,84,00,74,29,17,27,76,69,84,00,77,85,84,00,69,29,75,00,13,08,82,28,28,17,09,27,87,72,73,76,69, + 00,88,30,29,89,91,66,14,80,85,83,72,08,08,82,11,88,12,82,11,89,09,09,27,66,14,80,85,83,72,08,08,82,11,89,12,82,11, + 88,09,09,27,00,66,14,80,85,83,72,08,08,82,13,89,12,82,11,88,09,32,00,00,00,00,00,00,00,00,00,00,00,00,00,09,27,66,14,80, + 85,83,72,08,08,82,13,88,12,00,82,11,89,09,09,27,66,14,80,85,83,72,08,08,82,13,88,12,82,13,89,09,09,27,66,14,80,85,83,72, + 08,08,82,13,89,12,82,13,88,09,09,27,00,66,14,80,85,83,72,08,08,82,11,89,12,82,13,88,09,09,27,66,14,80,85,83,72,08,08,82, + 11,88,12,82,13,89,09,09,27,00,73,70,00,69,28,29,16,91,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,89,11,29,17,27,69,11, + 29,74,27,74,11,29,18,27,93,73,70,00,69,30,16,00,91,88,13,29,17,27,75,11,29,18,27,69,11,29,75,13,08,82,28,28,17,09,27,93,93,76, + 69,84,00,77,85,84,00,84,29,81,14,73,84,69,82,08,09,27,07,79,26,70,79,82,00,89,00,73,78,00,17,14,14,82,10,18,00,91,00,76,69,84, + 00,76,26,00,54,69,67,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,28,73,19,18,30,00,29,00,66,14,73,84,69,82,08, + 09,14,70,73,76,84,69,82,08,92,88,92,00,88,14,17,29,29,89,09,14,77,65,80,08,92,88,92,00,88,14,16,09,14,67,79,76,76,69,67,84,08, + 09,27,00,76,69,84,00,88,00,29,00,76,14,73,84,69,82,08,09,14,67,76,79,78,69,68,08,09,14,70,79,76,68,08,16,12,32,00,00,00,00,00, + 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,73,19,18,26,26,77,65,88,09,27,00,76,69,84,00,78,00,29,76,14,73,84,69,82,08,09, + 14,67,76,79,78,69,68,08,09,14,70,79,76,68,08,25,25,25,12,00,73,19,18,26,26,77,73,78,09,27,76,69,84,00,77,29,88,13,78,27,00,70, + 79,82,00,63,00,73,78,00,16,14,14,78,00,91,00,80,82,73,78,84,01,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00, + 00,00,00,00,08,02,00,00,00,02,09,27,93,70,79,82,00,63,00,73,78,00,16,14,14,77,91,00,73,70,00,76,69,84,00,51,79,77,69,08,86,09, + 00,29,00,84,14,78,69,88,84,08,09,00,91,80,82,73,78,84,01,08,02,91,26,16,18,93,12,02,12,86,09,27,93,00,69,76,83,69,91,00,66,82, + 69,65,75,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,07,79,27,00,93,93,00,80,82,73, + 78,84,01,08,02,60,78,02,09,27,00,93,00,70,79,82,00,78,00,73,78,00,81,14,73,84,69,82,08,09,00,91,00,80,82,73,78,84,01,08,02,91, + 93,02,12,00,08,73,70,00,10,78,29,29,19,18,91,17,16,93,00,69,76,83,69,32,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00, + 00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,91,10,78,11,19,18,93,09,00,65,83,00,67,72,65,82,09,27,93,80,82,73, + 78,84,01,08,02,60,78,02,09,27,93,00,15,15,00,71,73,84,72,85,66,14,67,79,77,15,75,73,82,74,65,86,65,83,67,82,73,80,84, + ];println!("{}fn main(){{let q:&[u8]=&[", String::from_utf8(vec![b' '; 54]).unwrap());let r=(q.len()as f64/std::f64 + ::consts::PI).sqrt()as i32+4;let mut b: Vec<(i32, i32) >= Vec::new(); /* ooer */ let mut x=r-1; let mut y=0; + let mut k=1;let mut j=1;let mut e=k -(r<<1);while x>=y{b.push((r+x,r+y));b.push((r+y,r+x)); b.push((r-y,r+x) + );b.push((r-x, r+y));b.push((r-x,r-y));b.push((r-y,r-x)); b.push((r+y,r-x));b.push((r+x,r-y)); if e<=0{ + y+=1;e+=j;j+=2;}if e>0 {x-=1;k+=2;e+=k-(r<<1);}}let mut t=q.iter();'o:for y in 1..r*2 { let l: Vec + = b.iter().filter(|x| x.1==y).map(|x| x.0).collect(); let x = l.iter().cloned().fold(0, + i32::max); let n =l.iter().cloned().fold(999, i32::min);let m=x-n; for _ in 0..n { print! + (" ");}for _ in 0..m{ if let Some(v) = t.next() {print!("{:02},",v);} else{ break + 'o; }} print!("\n"); } for n in q.iter() { print!("{}", (if *n==32{10} else + {*n+32}) as char);}print!("\n");} // github.com/kirjavascript diff --git a/Task/Quine/V-(Vlang)/quine.v b/Task/Quine/V-(Vlang)/quine.v new file mode 100644 index 0000000000..edc87d53c7 --- /dev/null +++ b/Task/Quine/V-(Vlang)/quine.v @@ -0,0 +1,3 @@ +fn main() { + print($embed_file(@FILE).to_string()) +} diff --git a/Task/Quine/Zig/quine.zig b/Task/Quine/Zig/quine.zig new file mode 100644 index 0000000000..5383d7837a --- /dev/null +++ b/Task/Quine/Zig/quine.zig @@ -0,0 +1,6 @@ +const std = @import("std"); + +pub fn main() !void { + const content = @embedFile(@src().file); + try std.io.getStdOut().writer().print("{s}", .{content}); +} diff --git a/Task/Radical-of-an-integer/EasyLang/radical-of-an-integer.easy b/Task/Radical-of-an-integer/EasyLang/radical-of-an-integer.easy index 6902e0dcf0..01254f329e 100644 --- a/Task/Radical-of-an-integer/EasyLang/radical-of-an-integer.easy +++ b/Task/Radical-of-an-integer/EasyLang/radical-of-an-integer.easy @@ -9,9 +9,7 @@ fastfunc radnf num . . d += 1 . - if d <= num - nf += 1 - . + if d <= num : nf += 1 return nf . func rad num . @@ -26,22 +24,20 @@ func rad num . . d += 1 . - if d <= num - r *= num - . + if d <= num : r *= num return r . -proc show50 . . +proc show50 . write "First 50 radicals:" for n = 1 to 50 write " " & rad n . print "" . -proc show n . . +proc show n . print "radical(" & n & ") = " & rad n . -proc dist . . +proc dist . len dist[] 7 for n = 2 to 1000000 dist[radnf n] += 1 diff --git a/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx b/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx index f3d3b14ceb..9ebed865c0 100644 --- a/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx +++ b/Task/Radical-of-an-integer/REXX/radical-of-an-integer-2.rexx @@ -1,11 +1,14 @@ +-- 8 May 2025 include Settings -say version; say 'Radical of an integer'; say +say 'RADICAL OF AN INTEGER' +say version +say arg n if n = '' then n = 1000000 numeric digits 100 -say 'Radicals for 1..50:' +say 'Radicals for 1..50...' ol = '' do i = 1 to 50 ol = ol||Right(Radical(i),5) @@ -14,13 +17,13 @@ do i = 1 to 50 end end say -say 'Radicals for:' +say 'Radicals for...' say '99999 =' Radical(99999) say '499999 =' Radical(499999) say '999999 =' Radical(999999) say -m = n/10; r = Isqrt(n); radi. = 0 say 'Getting distribution list...' +m = n/10; r = Isqrt(n); radi. = 0 call Time('r') do i = 1 to n call Radical(i) @@ -32,7 +35,7 @@ do i = 1 to n end end say -say 'Distribution for first' n 'radicals over Number of Factors:' +say 'Distribution for first' n 'radicals over Number of Factors...' do i = 0 to 10 if radi.i > 0 then say Right(i,2)':' Right(radi.i,6) @@ -47,7 +50,7 @@ say 'Getting powers of Primes up to' r'...' call Time('r') pw = 0 do i = 1 - p1 = prim.Prime.i + p1 = prim.i if p1 > r then leave p2 = p1 @@ -66,20 +69,8 @@ say ' -----' say 'Total ' Format(pr+pw,6) exit -Radical: -/* Radical = product of unique prime factors */ -procedure expose ufac. -arg x -/* Get unique factors */ -n = Ufactors(x) -/* Calculate product */ -y = 1 -do i = 1 to n - y = y*ufac.factor.i -end -return y - include Functions +include Special include Numbers include Sequences include Abend diff --git a/Task/Radical-of-an-integer/SETL/radical-of-an-integer.setl b/Task/Radical-of-an-integer/SETL/radical-of-an-integer.setl new file mode 100644 index 0000000000..51f074c1f0 --- /dev/null +++ b/Task/Radical-of-an-integer/SETL/radical-of-an-integer.setl @@ -0,0 +1,43 @@ +program radicals_of_an_integer; + init factab := distinct_factor_table(1000000); + + print("Radicals of the first 50 integers:"); + loop for n in [1..50] do + nprint(lpad(str radical n, 5)); + if n mod 10=0 then print; end if; + end loop; + + print; + loop for n in [99999, 499999, 999999] do + print("Radical of " + lpad(str n, 6) + ": " + lpad(str radical n, 6)); + end loop; + + print; + print("Distribution of factor counts:"); + + distr := {}; + loop for f = factab(n) do + distr(#f) +:= 1; + end loop; + loop for amount = distr(n) do + print(str n + ": " + lpad(str amount, 6)); + end loop; + + op radical(n); + return 1 */ factab(n); + end op; + + proc distinct_factor_table(n); + factab := [{}] * n; + + loop init i := 2; while i <= n step i +:= 1; do + if factab(i) = {} then + loop init c := i; while c <= n step c +:= i; do + factab(c) with:= i; + end loop; + end if; + end loop; + + return factab; + end proc; +end program; diff --git a/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy b/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy index fd1878b281..bc2b3055f5 100644 --- a/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy +++ b/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy @@ -1,5 +1,5 @@ global cnt[] . -proc primcnt limit . . +proc primcnt limit . cnt[] = [ 0 1 1 ] for i = 4 step 2 to limit cnt[] &= 0 diff --git a/Task/Ramanujan-primes-twins/REXX/ramanujan-primes-twins.rexx b/Task/Ramanujan-primes-twins/REXX/ramanujan-primes-twins.rexx new file mode 100644 index 0000000000..f4f86b651f --- /dev/null +++ b/Task/Ramanujan-primes-twins/REXX/ramanujan-primes-twins.rexx @@ -0,0 +1,43 @@ +-- 12 Apr 2025 +include Settings +numeric digits 10 + +call Time('r') +say 'RAMANUJAN TWIN PRIMES' +say version +say +call Primes Floor(4*6e5*Ln(4*6e5)) +call Ramanujans +call Twins +say prim.0 'primes processed' +say rama.0 'Ramanujan primes processed' +say twin.0 'Ramanujan twin primes primes found' +say Format(Time('e'),,3) 'seconds' +exit + +Ramanujans: +procedure expose prim. rama. +rama. = 0; j = 1; rama.1 = 2 +do i = 2 to prim.0 + a = prim.i; b = a/2; c = prim.j + do while c < b + j = j+1; c = prim.j + end + d = i-j+1; rama.d = a; rama.0 = Max(d,rama.0) +end +return 0 + +Twins: +procedure expose rama. twin. +twin. = 0 +do i = 2 to 1e6 + i1 = i-1 + if rama.i-rama.i1 = 2 then + twin.0 = twin.0+1 +end +return + +include Sequences +include Functions +include Constants +include Abend diff --git a/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx b/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx index 67a32ac25f..7639f2025b 100644 --- a/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx +++ b/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx @@ -1,35 +1,33 @@ -/*REXX pgm displays Ramanujan's constant to at least 100 decimal digits of precision. */ -d= min( length(pi()), length(e()) ) - length(.) /*calculate max #decimal digs supported*/ -parse arg digs sDigs . 1 . . $ /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs= d /*Not specified? Then use the default.*/ -if sDigs=='' | sDigs=="," then sDigs= d % 2 /* " " " " " " */ -if $='' | $="," then $= 19 43 67 163 /* " " " " " " */ - digs= min( digs, d) /*the minimum decimal digs for calc. */ -sDigs= min(sDigs, d) /* " " " " display.*/ -numeric digits digs /*inform REXX how many dec digs to use.*/ -say "The value of Ramanujan's constant calculated with " d ' decimal digits of precision.' -say "shown with " sDigs ' decimal digits past the decimal point:' +include Settings + +say 'RAMANUJAN''S CONSTANT - 6 Mar 2025' +say version say - do j=1 for words($); #= word($, j) /*process each of the Heegner numbers. */ - say 'When using the Heegner number: ' # /*display which Heegner # is being used*/ - z= exp(pi * sqrt(#) ) /*perform some heavy lifting here. */ - say format(z, 25, sDigs); say /*display a limited amount of dec digs.*/ - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862, - || 089986280348253421170679821480865132823066470938446095505822317253594081284, - || 8111745028410270193852110555964462294895493038196; return pi -/*──────────────────────────────────────────────────────────────────────────────────────*/ -e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535, - || 475945713821785251664274274663919320030599218174135966290435729003342952605, - || 9563073813232862794349076323382988075319525101901; return e -/*──────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix= x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix - z=1; _=1; w=z; do j=1; _= _*x/j; z=(z+_)/1; if z==w then leave; w=z; end - if z\==0 then z= z * e() ** ix; return z/1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric digits - numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h % 2 + 1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g) * .5; end /*k*/; return g +call Formula +call Heegner +exit + +Formula: +call time('r') +say 'Accurate to 100 digits' +numeric digits 100 +say Exp(Pi()*Sqrt(163)) +say Format(Time('e'),,3) 'seconds' +say +return + +Heegner: +call time('r') +say 'Heegner numbers with differences' +numeric digits 33 +h = '19 43 67 163' +do i = 1 to Words(h) + w = Word(h,i); a = Exp(Pi()*Sqrt(w)); b = Round(a,0) + say Right(w,3) Left(a,34) Right(Std(Round(a-b,12)),15) +end +say Format(Time('e'),,3) 'seconds' +return + +include Constants +include Functions +include Abend diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/EasyLang/ramer-douglas-peucker-line-simplification.easy b/Task/Ramer-Douglas-Peucker-line-simplification/EasyLang/ramer-douglas-peucker-line-simplification.easy index a4cc307ca2..0593144c79 100644 --- a/Task/Ramer-Douglas-Peucker-line-simplification/EasyLang/ramer-douglas-peucker-line-simplification.easy +++ b/Task/Ramer-Douglas-Peucker-line-simplification/EasyLang/ramer-douglas-peucker-line-simplification.easy @@ -4,7 +4,7 @@ func perpdist px py p1x p1y p2x p2y . d = sqrt (dx * dx + dy * dy) return abs (px * dy - py * dx + p2x * p1y - p2y * p1x) / d . -proc peucker eps . ptx[] pty[] outx[] outy[] . +proc peucker eps &ptx[] &pty[] &outx[] &outy[] . n = len ptx[] idx = 1 for i = 2 to n - 1 @@ -35,7 +35,7 @@ proc peucker eps . ptx[] pty[] outx[] outy[] . outy[] = [ pty[1] pty[n] ] . . -proc prpts px[] py[] . . +proc prpts px[] py[] . for i to len px[] write "(" & px[i] & " " & py[i] & ") " . diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/Lua/ramer-douglas-peucker-line-simplification.lua b/Task/Ramer-Douglas-Peucker-line-simplification/Lua/ramer-douglas-peucker-line-simplification.lua new file mode 100644 index 0000000000..d860037711 --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/Lua/ramer-douglas-peucker-line-simplification.lua @@ -0,0 +1,92 @@ +local Point = {} +Point.__index = Point + +function Point.new(first, second) + return setmetatable({first=first, second=second}, Point) +end + +local function hypot(...) + local sum = 0 + + for i = 1, select("#", ...) do + local arg = select(i, ...) + sum = sum + arg * arg + end + + return math.sqrt(sum) +end + +local function perpendicularDistance(point, lineStart, lineEnd) + local dx = lineEnd.first - lineStart.first + local dy = lineEnd.second - lineStart.second + + local mag = hypot(dx, dy) + if mag > 0 then + dx = dx / mag + dy = dy / mag + end + + local pvx = point.first - lineStart.first + local pvy = point.second - lineStart.second + + local pvDot = dx * pvx + dy * pvy + + local ax = pvx - pvDot * dx + local ay = pvy - pvDot * dy + + return hypot(ax, ay) +end + +local function simplify(points, epsilon) + local n = #points + if n < 2 then + error("Not enough points to simplify; needs at least 2 points, received " .. n .. " instead") + end + + local dmax = 0 + local index = 1 + + for i = 2, n - 1 do + local d = perpendicularDistance(points[i], points[1], points[n]) + if d > dmax then + index = i + dmax = d + end + end + + if dmax > epsilon then + local recursiveResults = {first={}, second={}} + recursiveResults.first = simplify({table.unpack(points, 1, index)}, epsilon) + recursiveResults.second = simplify({table.unpack(points, index, n)}, epsilon) + local result = {} + + for i = 1, #recursiveResults.first - 1 do + table.insert(result, recursiveResults.first[i]) + end + for i = 1, #recursiveResults.second do + table.insert(result, recursiveResults.second[i]) + end + return result + else + return {points[1], points[n]} + end +end + +local points = { + Point.new(0.0, 0.0), + Point.new(1.0, 0.1), + Point.new(2.0, -0.1), + Point.new(3.0, 5.0), + Point.new(4.0, 6.0), + Point.new(5.0, 7.0), + Point.new(6.0, 8.1), + Point.new(7.0, 9.0), + Point.new(8.0, 9.0), + Point.new(9.0, 9.0) +} + +local result = simplify(points, 1.0) +print("Points remaining after simplification:") +for i, v in ipairs(result) do + print("(" .. v.first .. ", " .. v.second .. ")") +end diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/Modula-2/ramer-douglas-peucker-line-simplification.mod2 b/Task/Ramer-Douglas-Peucker-line-simplification/Modula-2/ramer-douglas-peucker-line-simplification.mod2 new file mode 100644 index 0000000000..c4366eb7d9 --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/Modula-2/ramer-douglas-peucker-line-simplification.mod2 @@ -0,0 +1,100 @@ +MODULE RDPAlgorithm; +(* Ramer-Douglas-Peucker line simplification *) + +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SRealIO IMPORT + WriteFixed; +FROM RealMath IMPORT + sqrt; + +CONST + Len = 10; + +TYPE + TPoint = RECORD + X, Y: LONGREAL; + END; + TPoints = ARRAY [0 .. Len - 1] OF TPoint; + +CONST + PointsIn = TPoints{TPoint{0., 0.}, TPoint{1., 0.1}, TPoint{2., -0.1}, TPoint{3., 5.}, TPoint{4., 6.}, + TPoint{5., 7.}, TPoint{6., 8.1}, TPoint{7., 9.}, TPoint{8., 9.}, TPoint{9., 9.}}; + +VAR + PointsOut: TPoints; + N : CARDINAL; + +PROCEDURE WritePoints(Points: TPoints; N: CARDINAL); +VAR + I: CARDINAL; +BEGIN + WriteString('('); + WriteFixed(Points[0].X, 2, 1); + WriteString(', '); + WriteFixed(Points[0].Y, 2, 1); + WriteString(')'); + FOR I := 1 TO N - 1 DO + WriteString(' ('); + WriteFixed(Points[I].X, 2, 1); + WriteString(', '); + WriteFixed(Points[I].Y, 2, 1); + WriteString(')'); + END; + WriteLn; +END WritePoints; + +(* Returns the distance from point P to the line between P1 and P2 *) +PROCEDURE PerpDist(P, P1, P2: TPoint): LONGREAL; +VAR + DX, DY, D: LONGREAL; +BEGIN + DX := P2.X - P1.X; + DY := P2.Y - P1.Y; + D := sqrt(DX * DX + DY * DY); + RETURN ABS(P.X * DY - P.Y * DX + P2.X * P1.Y - P2.Y * P1.X) / D; +END PerpDist; + +(* Simplify an array of points using the Ramer-Douglas-Peucker algorithm. *) +(* Returns the number of output points. *) +PROCEDURE RDP(Src: TPoints; SrcFrom, SrcLen: CARDINAL; Eps: LONGREAL; + VAR OUT Dest: TPoints; DestFrom, DestLen: CARDINAL): CARDINAL; +VAR + Dist, MaxDist : LONGREAL; + N1, N2, I, MaxDistI, SrcTo: CARDINAL; + Src1Len, Src2Len, Src2From: CARDINAL; +BEGIN + MaxDist := 0.; + MaxDistI := SrcFrom; + SrcTo := SrcFrom + SrcLen - 1; + FOR I := SrcFrom + 1 TO SrcTo - 1 DO + Dist := PerpDist(Src[I], Src[SrcFrom], Src[SrcTo]); + IF Dist >= MaxDist THEN + MaxDist := Dist; + MaxDistI := I + END; + END; + Src2From := MaxDistI; + Src1Len := MaxDistI - SrcFrom + 1; + Src2Len := SrcLen - Src1Len + 1; + IF MaxDist > Eps THEN + N1 := RDP(Src, SrcFrom, Src1Len, Eps, Dest, DestFrom, DestLen); + IF DestLen >= N1 - 1 THEN + N2 := RDP(Src, Src2From, Src2Len, Eps, Dest, DestFrom + N1 - 1, DestLen - N1 + 1) + ELSE + N2 := RDP(Src, Src2From, Src2Len, Eps, Dest, DestFrom, 0) + END; + RETURN N1 + N2 - 1; + ELSE + IF DestLen > 1 THEN + Dest[DestFrom] := Src[SrcFrom]; + Dest[DestFrom + 1] := Src[SrcTo]; + END; + RETURN 2; + END; +END RDP; + +BEGIN + N := RDP(PointsIn, 0, Len, 1.0, PointsOut, 0, Len); + WritePoints(PointsOut, N) +END RDPAlgorithm. diff --git a/Task/Random-Latin-squares/EasyLang/random-latin-squares.easy b/Task/Random-Latin-squares/EasyLang/random-latin-squares.easy index a74a0a47cd..80109447fc 100644 --- a/Task/Random-Latin-squares/EasyLang/random-latin-squares.easy +++ b/Task/Random-Latin-squares/EasyLang/random-latin-squares.easy @@ -1,36 +1,28 @@ -proc shuffle . a[] . +proc shuffle &a[] . for i = len a[] downto 2 r = random i swap a[r] a[i] . . -proc prsquare . lat[][] . +proc prsquare &lat[][] . n = len lat[][] for i to n - for j to n - write lat[i][j] & " " - . + for j to n : write lat[i][j] & " " print "" . print "" . -proc square n . . +proc square n . for i to n lat[][] &= [ ] - for j to n - lat[i][] &= j - . + for j to n : lat[i][] &= j . shuffle lat[1][] for i = 2 to n - 1 repeat shuffle lat[i][] - for k to i - 1 - for j to n - if lat[k][j] = lat[i][j] - break 2 - . - . + for k to i - 1 : for j to n + if lat[k][j] = lat[i][j] : break 2 . until k = i . @@ -38,9 +30,7 @@ proc square n . . len used0[] n for j to n used[] = used0[] - for i to n - 1 - used[lat[i][j]] = 1 - . + for i to n - 1 : used[lat[i][j]] = 1 for k to n if used[k] = 0 lat[n][j] = k diff --git a/Task/Random-number-generator-device-/C/random-number-generator-device--5.c b/Task/Random-number-generator-device-/C/random-number-generator-device--5.c deleted file mode 100644 index e0a8d73ace..0000000000 --- a/Task/Random-number-generator-device-/C/random-number-generator-device--5.c +++ /dev/null @@ -1,82 +0,0 @@ -#include -#include - -/* - (C) 2020 J.G.A. Debaere, all rights reserved 2020/10/29 - - Put into Public Domain for individuals only - - Tested with NIST, Diehard, Diehard 3.31 - - gcc -lm ./jpsrand_f.c -o ./jpsrand_f.o - - dieharder -a -f /tmp/tmp.bin - - I consider it TRNG, - - using Time, Hardddisk and Memory as the hardware component - - No warranty of any kind, "AS IS" - - Last time I tested ( 2021/07/07 ) with dieharder: - - rgb_bitdist | 8| 100000| 100|0.99716738| WEAK - rgb_lagged_sum | 3| 1000000| 100|0.99661184| WEAK - - Out of 114 tests, rest PASSED - - Obviously, it changes per run :) - -*/ - -unsigned int jps_rand() -{ - /* (C) 2020 J.G.A. Debaere, all rights reserved */ - - #include - - #include - - struct timeval current_time ; - - DIR *folder ; - - struct dirent *en ; - - folder = opendir ( "." ) ; - - while ( ( folder ) && ( en = readdir ( folder ) ) != NULL ) - - asm ( "nop" ) ; - - closedir ( folder ) ; - - gettimeofday( ¤t_time, NULL ) ; - - unsigned int t = ( current_time.tv_sec * current_time.tv_usec / 17.17 ) ; - - return t ; -} - -int main() -{ - FILE * f1; - - f1 = fopen("/tmp/tmp.bin", "wb"); - - - unsigned int t = ( unsigned int ) jps_rand() ; - - for ( unsigned int k = 0; k < 40000000 ; k++ ) - { - t = jps_rand () ; - - fwrite ( &t, sizeof( unsigned int ), 1, f1 ) ; - } - - fflush(f1); - - fclose(f1); - - return 0; -} diff --git a/Task/Random-number-generator-device-/REXX/random-number-generator-device--1.rexx b/Task/Random-number-generator-device-/REXX/random-number-generator-device--1.rexx deleted file mode 100644 index e21429f519..0000000000 --- a/Task/Random-number-generator-device-/REXX/random-number-generator-device--1.rexx +++ /dev/null @@ -1,5 +0,0 @@ -/*REXX program generates and displays a random 32-bit number using the RANDOM BIF.*/ -numeric digits 10 /*ensure REXX has enough decimal digits*/ -_=2**16 /*a handy─dandy constant to have around*/ -r#= random(0, _-1) * _ + random(0, _-1) /*generate an unsigned 32-bit random #.*/ -say r# /*stick a fork in it, we're all done. */ diff --git a/Task/Random-number-generator-device-/REXX/random-number-generator-device--2.rexx b/Task/Random-number-generator-device-/REXX/random-number-generator-device--2.rexx deleted file mode 100644 index bac32fcf77..0000000000 --- a/Task/Random-number-generator-device-/REXX/random-number-generator-device--2.rexx +++ /dev/null @@ -1,14 +0,0 @@ -left=0 -rite=0 -lo=hex(left)hex(rite) -Say 'low ' c2x(lo) -left=random(0,2**16-1) -rite=random(0,2**16-1) -rand=hex(left)hex(rite) -Say 'random' c2x(rand) -left=2**16-1 -rite=2**16-1 -hi=hex(left)hex(rite) -Say 'high ' c2x(hi) -Exit -hex: Return d2c(arg(1),2) diff --git a/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx b/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx new file mode 100644 index 0000000000..b0e65ac572 --- /dev/null +++ b/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx @@ -0,0 +1,38 @@ +-- 8 May 2025 +include Settings +numeric digits 12 + +say 'RANDOM NUMBER GENERATOR (DEVICE)' +say version +say +call ShowSeed +call Examples +call Timer +exit + +ShowSeed: +procedure +say 'Datetime =' Date('s')||Time('l') +say 'Extract =' ' AABBCCDD EE FF GHI' +d = Date('s') +a = SubStr(d,3,2); b = SubStr(d,5,2); c = SubStr(d,7,2) +t = Time('l') +d = SubStr(t,1,2); e = SubStr(t,4,2); f = SubStr(t,7,2) +g = SubStr(t,10,1); h = SubStr(t,11,1); i = SubStr(t,12,1) +say 'Seed =' h||f||d||b||a||c||e||g||i '= HFFDDBBAACCEEGI' +say +return + +Examples: +procedure expose glob. +say 'Randu() = ' Right(Randu(),14) 'Real, uniform distributed over (0,1)' +say 'Randu(100) = ' Right(Randu(100),14) 'Integer, between 0 and 100' +say 'Randu(-10,10) = ' Right(Randu(-10,10),14) 'Integer, between -10 and 10' +say 'Randn() = ' Right(Randn(),14) 'Real, normal distributed, average 0 and deviation 1' +say +return + +include Functions +include Constants +include Helper +include Abend diff --git a/Task/Random-number-generator-included-/REXX/random-number-generator-included--3.rexx b/Task/Random-number-generator-included-/REXX/random-number-generator-included--3.rexx index eaa4405d0f..46ed58973d 100644 --- a/Task/Random-number-generator-included-/REXX/random-number-generator-included--3.rexx +++ b/Task/Random-number-generator-included-/REXX/random-number-generator-included--3.rexx @@ -3,6 +3,8 @@ * Please add the output from other REXXes * 10.09.2013 Walter Pachl added REXX/TSO * 01.08.2014 Walter Pachl show what ooRexx supports +* 03.05.2025 Zeddicus added REXX/2 +* 08.05.2025 Zeddicus added ooRexx 5.1 **********************************************************************/ Parse Version v Call random ,,44 diff --git a/Task/Random-numbers/EasyLang/random-numbers.easy b/Task/Random-numbers/EasyLang/random-numbers.easy index e37e3b167d..04a06a4a79 100644 --- a/Task/Random-numbers/EasyLang/random-numbers.easy +++ b/Task/Random-numbers/EasyLang/random-numbers.easy @@ -1,4 +1,4 @@ -numfmt 5 0 +numfmt 0 5 e = 2.7182818284590452354 for i = 1 to 1000 a[] &= 1 + 0.5 * sqrt (-2 * log10 randomf / log10 e) * cos (360 * randomf) diff --git a/Task/Random-numbers/REXX/random-numbers.rexx b/Task/Random-numbers/REXX/random-numbers.rexx index e36ea6b97b..cfd8734f63 100644 --- a/Task/Random-numbers/REXX/random-numbers.rexx +++ b/Task/Random-numbers/REXX/random-numbers.rexx @@ -1,45 +1,87 @@ -/*REXX pgm generates 1,000 normally distributed numbers: mean=1, standard deviation=½.*/ -numeric digits 20 /*the default decimal digit precision=9*/ -parse arg n seed . /*allow specification of N and the seed*/ -if n=='' | n=="," then n=1000 /*N: is the size of the array. */ -if datatype(seed,'W') then call random ,,seed /*SEED: for repeatable random numbers. */ -newMean=1 /*the desired new mean (arithmetic avg)*/ -sd=1/2 /*the desired new standard deviation. */ - do g=1 for n /*generate N uniform random #'s (0,1].*/ - #.g = random(1, 1e5) / 1e5 /*REXX's RANDOM BIF generates integers.*/ - end /*g*/ /* [↑] random integers ──► fractions. */ -say ' old mean=' mean() -say 'old standard deviation=' stdDev() -call pi; pi2=pi * 2 /*define pi and also 2 * pi. */ +-- 8 May 2025 +include Settings + +say 'RANDOM NUMBERS' +say version say - do j=1 to n-1 by 2; m=j+1 /*step through the iterations by two. */ - _=sd * sqrt(ln(#.j) * -2) /*calculate the used-twice expression.*/ - #.j=_ * cos(pi2 * #.m) + newMean /*utilize the Box─Muller method. */ - #.m=_ * sin(pi2 * #.m) + newMean /*random number must be: (0,1] */ - end /*j*/ -say ' new mean=' mean() -say 'new standard deviation=' stdDev() -exit /*stick a fork in it, we're all done. */ -/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -mean: _=0; do k=1 for n; _=_ + #.k; end; return _/n -stdDev: _avg=mean(); _=0; do k=1 for n; _=_ + (#.k - _avg)**2; end; return sqrt(_/n) -e: e =2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e /*digs overkill*/ -pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi /* " " */ -r2r: return arg(1) // (pi() * 2) /*normalize ang*/ -sin: procedure; parse arg x;x=r2r(x);numeric fuzz min(5,digits()-3);if abs(x)=pi then return 0;return .sincos(x,x,1) -.sincos:parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z -/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -ln: procedure; parse arg x,f; call e; ig= x>1.5; is=1 - 2 * (ig\==1); ii=0; xx=x - do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end - xx=izz;ii=ii+is*2**k;end;x=x*e**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii -/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi * .5 - numeric fuzz min(6, digits() - 3); if a=pi then return -1 - if a=hpi | a=hpi*3 then return 0; if a=pi/3 then return .5 - if a=pi * 2/3 then return -.5; return .sinCos(1,1,-1) -/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 - numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ %2 - m.=9; do j=0 while h>9; m.j=h; h=h%2 + 1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return g/1 +call GetUniform 1e3 +call ShowFirst +call ShowStats +call ShowExact +call GetNormal 1e3 +call ShowFirst +call ShowStats +call GetUniform 1e6 +call ShowStats +call GetNormal 1e6 +call ShowStats +call Timer +exit + +GetUniform: +procedure expose glob. work. +arg xx +say 'Get' xx 'uniform distributed Random numbers...' +work. = 0 +do n = 1 to xx + work.n = Randu() +end +work.0 = xx +say 'Done' +say +return + +GetNormal: +procedure expose glob. work. +arg xx +say 'Get' xx 'normal(1,1/2) distributed Random numbers...' +work. = 0 +do n = 1 to xx + work.n = Randn(1,0.5) +end +work.0 = xx +say 'Done' +say +return + +ShowFirst: +procedure expose work. +say 'First 5 items...' +do i = 1 to 5 + call CharOut ,work.i/1' ' +end +say; say +return + +ShowStats: +procedure expose work. +say 'Statistics for' work.0 'items...' +sum = 0 +do n = 1 to work.0 + sum = sum+work.n +end +avg = sum/work.0 +sum = 0 +do n = 1 to work.0 + sum = sum+(work.n-avg)**2 +end +varia = sum/work.0; stdev = SqRt(varia)/1 +say 'Average ' Std(avg) +say 'Deviation' Std(stdev) +say 'Variance ' Std(varia) +say +return + +ShowExact: +procedure expose work. +say 'Exact statistics for infinite items...' +say 'Average ' 1/2 '(1/2)' +say 'Deviation' Std(SqRt(1/12)) '(SqRt(1/12))' +say 'Variance ' 1/12 '(1/12)' +say +return + +include Functions +include Constants +include Helper +include Abend diff --git a/Task/Random-sentence-from-book/ALGOL-68/random-sentence-from-book-1.alg b/Task/Random-sentence-from-book/ALGOL-68/random-sentence-from-book-1.alg index ddfb46e79b..ec203f1daa 100644 --- a/Task/Random-sentence-from-book/ALGOL-68/random-sentence-from-book-1.alg +++ b/Task/Random-sentence-from-book/ALGOL-68/random-sentence-from-book-1.alg @@ -58,7 +58,7 @@ OD; # delimiter for separating suffixes - must not appear in the text # CHAR suffix delimiter = REPR 1; # ^A # -STRING punctuation = """'@,/;:(){}[]*&^%$£"; +STRING punctuation = """'@,/;:(){}[]*&^%$"; # NB: exclude " " # IF FILE input file; open( input file, file name, stand in channel ) /= 0 @@ -239,8 +239,9 @@ ELSE finished := TRUE; # if the line ends with ",;:", remove it # INT line end := UPB line; - IF CHAR c = line[ line end ]; c = "," OR c = ";" OR c = ":" THEN - line end -:= 1 + IF CHAR end ch = line[ line end ]; + end ch = "," OR end ch = ";" OR end ch = ":" + THEN line end -:= 1 FI; # remove trailing spaces # WHILE line[ line end ] = " " AND line end > LWB line DO line end -:= 1 OD; diff --git a/Task/Range-consolidation/EasyLang/range-consolidation.easy b/Task/Range-consolidation/EasyLang/range-consolidation.easy index bbc21cb955..00151dbf97 100644 --- a/Task/Range-consolidation/EasyLang/range-consolidation.easy +++ b/Task/Range-consolidation/EasyLang/range-consolidation.easy @@ -1,18 +1,12 @@ -proc sort . d[][] . +proc sort &d[][] . n = len d[][] - for i = 1 to n - 1 - for j = i + 1 to n - if d[j][1] < d[i][1] - swap d[j][] d[i][] - . - . + for i = 1 to n - 1 : for j = i + 1 to n + if d[j][1] < d[i][1] : swap d[j][] d[i][] . . func[][] consolidate a[][] . for i to len a[][] - if a[i][1] > a[i][2] - swap a[i][1] a[i][2] - . + if a[i][1] > a[i][2] : swap a[i][1] a[i][2] . sort a[][] r[][] &= a[1][] diff --git a/Task/Rare-numbers/Rust/rare-numbers.rs b/Task/Rare-numbers/Rust/rare-numbers.rs index 5ab3a63054..8bcb1555ac 100644 --- a/Task/Rare-numbers/Rust/rare-numbers.rs +++ b/Task/Rare-numbers/Rust/rare-numbers.rs @@ -222,27 +222,22 @@ fn advanced(digit: u8) -> Vec { // create a cartesian product for all potential diff numbers // for the first use the very short one, for all other the complete 19 element let diff_list_iter = (0_u8..(d / 2)) - .map(|i| match i { - 0 => diffs1.iter(), - _ => all_diffs.iter(), - }) - .multi_cartesian_product() - // remove invalid first diff/second diff combinations - custom iterator would be probably better - .filter(|x| { - if x.len() == 1 { - return true; - } - match (*x[0], *x[1]) { - (a, b) if (a == 0 && b != 0) => false, - (a, b) if (a == 1 && ![-7, -5, -3, -1, 1, 3, 5, 7].contains(&b)) => false, - (a, b) if (a == 4 && ![-8, -6, -4, -2, 0, 2, 4, 6, 8].contains(&b)) => false, - (a, b) if (a == 5 && ![7, -3].contains(&b)) => false, - (a, b) if (a == 6 && ![-9, -7, -5, -3, -1, 1, 3, 5, 7, 9].contains(&b)) => { - false - } - _ => true, - } - }); + .map(|i| match i { + 0 => diffs1.iter(), + _ => all_diffs.iter(), + }) + .multi_cartesian_product() + // remove invalid first diff/second diff combinations - custom iterator would be probably better + .filter(|x| { + match x[..] { + [&a, &b] if a == 0 && b != 0 => false, + [&a, b] if a == 1 && ![-7, -5, -3, -1, 1, 3, 5, 7].contains(b) => false, + [&a, b] if a == 4 && ![-8, -6, -4, -2, 0, 2, 4, 6, 8].contains(b) => false, + [&a, b] if a == 5 && ![7, -3].contains(b) => false, + [&a, b] if a == 6 && ![-9, -7, -5, -3, -1, 1, 3, 5, 7, 9].contains(b) => false, + _ => true, + } + }); #[cfg(debug_assertions)] { diff --git a/Task/Rate-counter/EasyLang/rate-counter.easy b/Task/Rate-counter/EasyLang/rate-counter.easy index 2123abcfcc..560ba46e1c 100644 --- a/Task/Rate-counter/EasyLang/rate-counter.easy +++ b/Task/Rate-counter/EasyLang/rate-counter.easy @@ -1,15 +1,15 @@ -color 700 -d = 0.2 -t0 = systime -on animate - clear - rad += d - move 50 50 - circle rad - if rad > 50 or rad < 0 - d = -d +fastfunc isprim num . + if num mod 2 = 0 and num > 2 : return 0 + i = 3 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 2 . - t = systime - print 1000 * (t - t0) & " ms" - t0 = t + return 1 +. +for i to 5 + t0 = systime + h = isprim 9005099254741061 + h = h + print (systime - t0) * 1000 & " ms" . diff --git a/Task/Read-a-configuration-file/XPL0/read-a-configuration-file.xpl0 b/Task/Read-a-configuration-file/XPL0/read-a-configuration-file.xpl0 new file mode 100644 index 0000000000..4da6db65d6 --- /dev/null +++ b/Task/Read-a-configuration-file/XPL0/read-a-configuration-file.xpl0 @@ -0,0 +1,56 @@ +string 0; \use zero-terminated strings +proc StrIn(Str); \Read alphanumeric string from input file +char Str; +int I, C; +[I:= 0; +loop [C:= ChIn(3); + if C<$20 or C=^, then quit; + Str(I):= C; I:= I+1; + ]; +Str(I):= 0; +]; + +char FullName(100), FavoriteFruit(100), OtherFamily(2, 100); +int NeedsPeeling, SeedsRemoved; +int C; +[NeedsPeeling:= false; SeedsRemoved:= false; +FullName(0):= 0; FavoriteFruit(0):= 0; +OtherFamily(0, 0):= 0; OtherFamily(1, 0):= 0; + +FSet(FOpen("configfile.txt", 0), ^i); +OpenI(3); +C:= ChIn(3); +while C # $1A \EOF\ do + [if C = $0A \LF\ then + [C:= ChIn(3); + if C = ^N then NeedsPeeling:= true; + if C = ^O then + [repeat C:= ChIn(3) until C <= $20; + StrIn(@OtherFamily(0, 0)); + C:= ChIn(3); + StrIn(@OtherFamily(1, 0)); + ]; + if C = ^F then + [C:= ChIn(3); + if C = ^U then + [repeat C:= ChIn(3) until C <= $20; + StrIn(FullName); + ]; + if C = ^A then + [repeat C:= ChIn(3) until C <= $20; + StrIn(FavoriteFruit); + ]; + ]; + ] + else C:= ChIn(3); + ]; +Text(0, "Full name: "); Text(0, FullName); CrLf(0); +Text(0, "Favorite fruit: "); Text(0, FavoriteFruit); CrLf(0); +Text(0, "Needs peeling: "); Text(0, if NeedsPeeling then "true" else "false"); +CrLf(0); +Text(0, "Seeds removed: "); Text(0, if SeedsRemoved then "true" else "false"); +CrLf(0); +Text(0, "Other family: "); Text(0, @OtherFamily(0, 0)); +Text(0, ", "); Text(0, @OtherFamily(1, 0)); +CrLf(0); +] diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx index 52d0d081be..e179d2ba96 100644 --- a/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx +++ b/Task/Read-entire-file/OoRexx/read-entire-file-1.rexx @@ -1,3 +1,8 @@ -file = 'c:\test.txt' -myStream = .stream~new(file) -myString = myStream~charIn(,myStream~chars) +o=.stream~new('f:\readall.rex') +a=o~arrayin +Do x over a + say x + End +Do i=1 To a~items + Say i a[i] + End diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx index e20079bcee..52d0d081be 100644 --- a/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx +++ b/Task/Read-entire-file/OoRexx/read-entire-file-2.rexx @@ -1,7 +1,3 @@ file = 'c:\test.txt' myStream = .stream~new(file) -if mystream~open('read') = 'READY:' -then do - myString = myStream~charIn(,myStream~chars) - myStream~close -end +myString = myStream~charIn(,myStream~chars) diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx index 0c745d4375..e20079bcee 100644 --- a/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx +++ b/Task/Read-entire-file/OoRexx/read-entire-file-3.rexx @@ -1,9 +1,7 @@ -address hostemu 'execio * diskr "./st.in" (finis stem in.' -Say in.0 'lines in file st.in' -v='' -Do i=1 To in.0 - Say i '>'in.i'<' - v=v||in.i - End -say 'v='v -::requires "hostemu" LIBRARY +file = 'c:\test.txt' +myStream = .stream~new(file) +if mystream~open('read') = 'READY:' +then do + myString = myStream~charIn(,myStream~chars) + myStream~close +end diff --git a/Task/Read-entire-file/OoRexx/read-entire-file-4.rexx b/Task/Read-entire-file/OoRexx/read-entire-file-4.rexx new file mode 100644 index 0000000000..0c745d4375 --- /dev/null +++ b/Task/Read-entire-file/OoRexx/read-entire-file-4.rexx @@ -0,0 +1,9 @@ +address hostemu 'execio * diskr "./st.in" (finis stem in.' +Say in.0 'lines in file st.in' +v='' +Do i=1 To in.0 + Say i '>'in.i'<' + v=v||in.i + End +say 'v='v +::requires "hostemu" LIBRARY diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx index 38feb02eeb..abb4b2d2f1 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx @@ -1 +1,27 @@ -ceiling: procedure; parse arg x; t=trunc(x); return t+(x>0)*(x\=t) +numeric digits ddd /*sets the current precision to DDD */ +numeric fuzz fff /*arithmetic comparisons with FFF fuzzy*/ +numeric form kkk /*exponential: scientific | engineering*/ + +low=min(a,b,c,d,e,f,g, ...) /*finds the min of specified arguments.*/ +big=min(a,b,c,d,e,f,g, ...) /*finds the max of specified arguments.*/ + +rrr=random(low,high) /*gets a random integer from LOW-->HIGH*/ +arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/ + +mzp=sign(x) /*finds the sign of x (-1, 0, +1). */ + + fs=format(x) /*formats X with the current DIGITS() */ + fb=format(x,bbb) /* BBB digs before decimal*/ + fa=format(x,bbb,aaa) /* AAA digs after decimal*/ + fa=format(x,,0) /* rounds X to an integer.*/ + fe=format(x,,eee) /* exponent has eee places. */ + ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */ + +hh=b2x(bbb) /*converts binary/bits to hexadecimal. */ +dd=c2d(ccc) /*converts character to decimal. */ +hh=c2x(ccc) /*converts character to hexadecimal. */ +cc=d2c(ddd) /*converts decimal to character. */ +hh=d2x(ddd) /*converts decimal to hexadecimal. */ +bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/ +cc=x2c(hhh) /*converts hexadecimal to character. */ +dd=x2d(hhh) /*converts hexadecimal to decimal. */ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx index 794b93d5b4..c1c062a192 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx @@ -1 +1,21 @@ -floor: procedure; parse arg x; t=trunc(x); return t-(x<0)-(x\=t) +include Settings + +say 'REAL CONSTANTS AND FUNCTIONS - 2 Mar 2025' +say version +say +numeric digits 16 +say 'e =' e()+0 +say 'pi =' pi()+0 +say 'square root 7 =' sqrt(7)+0 +say 'log 7 base e =' log(7)+0 +say 'log 7 base 10 =' log10(7)+0 +say 'log 7 base 2 =' logxy(7,2)+0 +say 'exponential 7 =' exp(7)+0 +say '1/2^3/4 =' power(1/2,3/4)+0 +say 'floor 4/3 =' floor(4/3) +say 'ceiling 4/3 =' ceil(4/3) +exit + +include Functions +include Constants +include Abend diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx deleted file mode 100644 index 60530b123b..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*──────────────────────────────────SQRT subroutine───────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0 /*handle 0 case.*/ -if \datatype(x,'N') then return '[n/a]' /*Not Applicable ───if not numeric.*/ -i=; if x<0 then do; x=-x; i='i'; end /*handle complex numbers if X is < 0.*/ -d=digits() /*get the current numeric precision. */ -m.=9 /*technique uses just enough digits. */ -h=d+6 /*use extra decimal digits for accuracy*/ -numeric digits 9 /*use "small" precision at first. */ -numeric form /*force scientific form of the number. */ -if fuzz()\==0 then numeric fuzz 0 /*just in case invoker has a FUZZ set.*/ -parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get the X's exponent.*/ - g=(g * .5) || 'e' || (_ % 2) /*1st guesstimate for the square root. */ - /* g= g * .5 'e' (_ % 2) */ /*a shorter & concise version of above.*/ - /*Note: to insure enough accuracy for */ - /* the result, the precision during */ - /* the SQRT calculations is increased */ - /* by two extra decimal digits. */ - do j=0 while h>9; m.j=h; h=h%2+1 /*compute the sizes (digs) of precision*/ - end /*j*/ /* [↑] precisions are stored in M. */ - /*now, we start to do the heavy lifting*/ - do k=j+5 to 0 by -1 /*compute the √ with increasing digs.*/ - numeric digits m.k /*each iteration, increase the digits. */ - g=(g+x/g) * .5 /*perform the nitty-gritty calculations*/ - end /*k*/ /* [↑] * .5 is faster than / 2 */ - /* [↓] normalize √ ──► original digits*/ -numeric digits d /* [↓] make answer complex if X < 0. */ -return (g/1)i /*normalize, and add possible I suffix.*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx deleted file mode 100644 index 1ac457905c..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx +++ /dev/null @@ -1,26 +0,0 @@ - ╔════════════════════════════════════════════════════════════════════╗ -╔═╝ __ ╚═╗ -║ √ ║ -║ ║ -║ While the above REXX code seems like it's doing a lot of extra work, ║ -║ it saves a substantial amount of processing time when the precision ║ -║ (DIGITs) is a lot greater than the default (default is nine digits). ║ -║ ║ -║ Indeed, when computing square roots in the hundreds (even thousands) ║ -║ of digits, this technique reduces the amount of CPU processing time ║ -║ by keeping the length of the computations to a minimum (due to a large ║ -║ precision), while the accuracy at the beginning isn't important for ║ -║ calculating the (first) guesstimate (the running square root guess). ║ -║ ║ -║ Each iteration of K (approximately) doubles the number of digits, ║ -║ but takes almost four times longer to compute (actually, around 3.8). ║ -║ ║ -║ The REXX code could be streamlined (pruned) by removing the ║ -║ The NUMERIC FUZZ 0 statement can be removed if it is known ║ -║ that it is already set to zero. (which is the default). ║ -║ ║ -║ Also, the NUMERIC FORM statement can be removed if it is known ║ -║ that the form is SCIENTIFIC (which is the default). ║ -║ __ ║ -╚═╗ √ ╔═╝ - ╚════════════════════════════════════════════════════════════════════╝ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx deleted file mode 100644 index 6d3d413b63..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx +++ /dev/null @@ -1,14 +0,0 @@ -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; arg x /*a simplistic SQRT subroutine.*/ -if x=0 then return 0 /*handle special case of zero. */ -d=digits() /*get the current precision (dig)*/ -numeric digits d+2 /*ensure extra precision (2 digs)*/ -g=x/4 /*try get a so-so 1st guesstimate*/ -old=0 /*set OLD guess to zero. */ - do forever /*keep at it 'til G (guess)=old.*/ - g=(g+x/g) / 2 /*do the nitty-gritty calculation*/ - if g=old then leave /*if G is the same as old, quit. */ - old=g /*save OLD for next iteration. */ - end /*forever*/ /* [↑] ···'til we run out of digs*/ -numeric digits d /*restore the original precision.*/ -return g/1 /*normalize to old precision (d).*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx deleted file mode 100644 index abb4b2d2f1..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx +++ /dev/null @@ -1,27 +0,0 @@ -numeric digits ddd /*sets the current precision to DDD */ -numeric fuzz fff /*arithmetic comparisons with FFF fuzzy*/ -numeric form kkk /*exponential: scientific | engineering*/ - -low=min(a,b,c,d,e,f,g, ...) /*finds the min of specified arguments.*/ -big=min(a,b,c,d,e,f,g, ...) /*finds the max of specified arguments.*/ - -rrr=random(low,high) /*gets a random integer from LOW-->HIGH*/ -arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/ - -mzp=sign(x) /*finds the sign of x (-1, 0, +1). */ - - fs=format(x) /*formats X with the current DIGITS() */ - fb=format(x,bbb) /* BBB digs before decimal*/ - fa=format(x,bbb,aaa) /* AAA digs after decimal*/ - fa=format(x,,0) /* rounds X to an integer.*/ - fe=format(x,,eee) /* exponent has eee places. */ - ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */ - -hh=b2x(bbb) /*converts binary/bits to hexadecimal. */ -dd=c2d(ccc) /*converts character to decimal. */ -hh=c2x(ccc) /*converts character to hexadecimal. */ -cc=d2c(ddd) /*converts decimal to character. */ -hh=d2x(ddd) /*converts decimal to hexadecimal. */ -bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/ -cc=x2c(hhh) /*converts hexadecimal to character. */ -dd=x2d(hhh) /*converts hexadecimal to decimal. */ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx deleted file mode 100644 index 7fc4460e78..0000000000 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-9.rexx +++ /dev/null @@ -1,19 +0,0 @@ -include Settings - -say version; say 'Real constants and functions'; say -numeric digits 16 -say 'e =' e()+0 -say 'pi =' pi()+0 -say 'square root 7 =' sqrt(7)+0 -say 'log 7 base e =' log(7)+0 -say 'log 7 base 10 =' log10(7)+0 -say 'log 7 base 2 =' logxy(7,2)+0 -say 'exponential 7 =' exp(7)+0 -say '1/2^3/4 =' power(1/2,3/4)+0 -say 'floor 4/3 =' floor(4/3) -say 'ceiling 4/3 =' ceil(4/3) -exit - -include Functions -include Constants -include Abend diff --git a/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy b/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy index a3ff68820f..1a33b89a0a 100644 --- a/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy +++ b/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy @@ -1,33 +1,25 @@ -proc rref . m[][] . +proc rref &m[][] . nrow = len m[][] ncol = len m[1][] lead = 1 for r to nrow - if lead > ncol - return - . + if lead > ncol : return i = r while m[i][lead] = 0 i += 1 if i > nrow i = r lead += 1 - if lead > ncol - return - . + if lead > ncol : return . . swap m[i][] m[r][] m = m[r][lead] - for k to ncol - m[r][k] /= m - . + for k to ncol : m[r][k] /= m for i to nrow if i <> r m = m[i][lead] - for k to ncol - m[i][k] -= m * m[r][k] - . + for k to ncol : m[i][k] -= m * m[r][k] . . lead += 1 diff --git a/Task/Reflection-Get-source/C-sharp/reflection-get-source.cs b/Task/Reflection-Get-source/C-sharp/reflection-get-source.cs new file mode 100644 index 0000000000..c83560b942 --- /dev/null +++ b/Task/Reflection-Get-source/C-sharp/reflection-get-source.cs @@ -0,0 +1 @@ +Console.WriteLine(new System.Diagnostics.StackTrace(true).GetFrame(0)); diff --git a/Task/Rendezvous/Rust/rendezvous.rs b/Task/Rendezvous/Rust/rendezvous.rs new file mode 100644 index 0000000000..1d6a34d05c --- /dev/null +++ b/Task/Rendezvous/Rust/rendezvous.rs @@ -0,0 +1,207 @@ +use std::error::Error; +use std::fmt; +use std::sync::{Arc, Mutex, Condvar}; +use std::thread; +use std::time::Duration; // Only for potential debug sleeps, not strictly needed for logic + +// --- Custom Error Type --- +#[derive(Debug)] +struct OutOfInkError; + +impl fmt::Display for OutOfInkError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Printer out of ink") + } +} + +impl Error for OutOfInkError {} + +// --- Printer Struct --- +#[derive(Debug, Clone, PartialEq)] // Add traits for comparison, debugging, and cloning +struct Printer { + name: String, + client_ink_level: u32, +} + +impl Printer { + fn new(name: &str, ink_level: u32) -> Self { + Printer { + name: name.to_string(), + client_ink_level: ink_level, + } + } +} + +// --- Shared State Struct --- +// Group all shared mutable data together +struct SharedState { + printer: Printer, + primary_printer_config: Printer, // Keep original config separate + reserve_printer_config: Printer, // Keep original config separate + goose_working: bool, + humpty_working: bool, + turn: u32, +} + +// --- Display Function --- +// Takes a mutable reference to the shared state +// Returns Result to indicate success or OutOfInkError +fn display(state: &mut SharedState, text: &str) -> Result<(), OutOfInkError> { + // Check if primary is out and switch to reserve if needed + if state.printer == state.primary_printer_config && state.printer.client_ink_level == 0 { + println!(" Switching to Reserve printer"); + state.printer = state.reserve_printer_config.clone(); // Use cloned config + } + + // Attempt to print + if state.printer.client_ink_level > 0 { + state.printer.client_ink_level -= 1; + println!("({}) {}", state.printer.name, text); + Ok(()) + } else { + println!(" Printer out of ink"); + Err(OutOfInkError) + } +} + +// --- Messenger Logic --- +// Takes Arc clones for shared data +fn messenger( + message: Vec, + my_turn: u32, + turn_count: u32, + state_sync: Arc<(Mutex, Condvar)>, // Tuple of Mutex and Condvar + worker_name: String, // For identifying which worker finished +) { + let (lock, cvar) = &*state_sync; // Destructure the tuple + let mut index: usize = 0; + + // Loop as long as *any* worker is potentially active + // We re-check specific worker status inside the lock + loop { + // Acquire the lock. The MutexGuard 'state' is automatically released when it goes out of scope + let mut state = lock.lock().expect("Mutex lock failed"); + + // Wait while it's not our turn AND at least one worker is still supposed to be working + // The wait_while unlocks the mutex and re-acquires it upon waking up + state = cvar.wait_while(state, |s| { + // Predicate: Keep waiting if... + s.turn % turn_count != my_turn // it's not our turn + && (s.goose_working || s.humpty_working) // AND someone is still working (prevents deadlock if other thread finishes) + }).expect("Condition variable wait failed"); + + + // Check if *all* work is done *after* waking up or if we didn't need to wait + if !state.goose_working && !state.humpty_working { + // println!("{} sees both workers finished, exiting.", worker_name); // Debug + break; // Exit the loop + } + + // Check if *this specific worker* should still be working + let should_be_working = if my_turn == 0 { state.goose_working } else { state.humpty_working }; + + if !should_be_working { + // This worker finished its text or an error occurred previously. + // It needs to potentially wake up the *other* worker if it's waiting. + // println!("{} sees it shouldn't be working, notifying and breaking.", worker_name); // Debug + // We still increment the turn and notify to potentially unblock the other thread + // if it's waiting for its turn number, even if it will also exit soon. + state.turn += 1; + cvar.notify_one(); + break; // Exit the loop + } + + + // --- Perform Work --- + if index < message.len() { + match display(&mut state, &message[index]) { + Ok(()) => { + index += 1; + } + Err(_) => { + // Out of ink! Stop both workers. + println!(" Error detected by {}, stopping all work.", worker_name); + state.goose_working = false; + state.humpty_working = false; + // No break here yet, let the loop condition handle exit naturally after notification + } + } + } else { + // This worker finished its message + // println!("{} finished text.", worker_name); // Debug + if my_turn == 0 { + state.goose_working = false; + } else { + state.humpty_working = false; + } + } + + // Increment turn and notify the *next* worker + state.turn += 1; + //println!("{} finished turn, new turn {}. Notifying.", worker_name, state.turn); // Debug + cvar.notify_one(); + + // MutexGuard 'state' is dropped here, releasing the lock + } + //println!("{} thread finished.", worker_name); // Debug +} + + +fn main() { + let goose_text: Vec = [ + "Old Mother Goose,", + "When she wanted to wander,", + "Would ride through the air,", + "On a very fine gander.", + "Jack's mother came in,", + "And caught the goose soon,", + "And mounting its back,", + "Flew up to the moon.", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + + let humpty_text: Vec = [ + "Humpty Dumpty sat on a wall.", + "Humpty Dumpty had a great fall.", + "All the king's horses and all the king's men,", + "Couldn't put Humpty together again.", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + + // --- Initial State Setup --- + let primary = Printer::new("Primary", 5); + let reserve = Printer::new("Reserve", 5); + + let initial_state = SharedState { + printer: primary.clone(), // Start with primary + primary_printer_config: primary, // Store config + reserve_printer_config: reserve, // Store config + goose_working: true, + humpty_working: true, + turn: 0, + }; + + // Wrap state and condvar in Arc for shared ownership + let state_sync = Arc::new((Mutex::new(initial_state), Condvar::new())); + + // --- Spawn Threads --- + let state_sync_goose = Arc::clone(&state_sync); + let goose_thread = thread::spawn(move || { + messenger(goose_text, 0, 2, state_sync_goose, "Goose".to_string()); + }); + + let state_sync_humpty = Arc::clone(&state_sync); + let humpty_thread = thread::spawn(move || { + messenger(humpty_text, 1, 2, state_sync_humpty, "Humpty".to_string()); + }); + + // --- Wait for Threads to Finish --- + goose_thread.join().expect("Goose thread panicked"); + humpty_thread.join().expect("Humpty thread panicked"); + + println!("Both threads finished."); +} diff --git a/Task/Repeat-a-string/Excel/repeat-a-string.excel b/Task/Repeat-a-string/Excel/repeat-a-string.excel new file mode 100644 index 0000000000..5164862aac --- /dev/null +++ b/Task/Repeat-a-string/Excel/repeat-a-string.excel @@ -0,0 +1 @@ +=REPT("ha", 5) diff --git a/Task/Resistor-mesh/Rust/resistor-mesh.rs b/Task/Resistor-mesh/Rust/resistor-mesh.rs new file mode 100644 index 0000000000..2f02a22c66 --- /dev/null +++ b/Task/Resistor-mesh/Rust/resistor-mesh.rs @@ -0,0 +1,133 @@ +use std::fmt; + +#[derive(Clone, Copy)] +struct Node { + v: f64, + fixed: i32, +} + +impl Node { + fn new() -> Self { + Node { v: 0.0, fixed: 0 } + } + + fn new_with_values(v: f64, fixed: i32) -> Self { + Node { v, fixed } + } + + fn get_v(&self) -> f64 { + self.v + } + + fn set_v(&mut self, nv: f64) { + self.v = nv; + } + + fn get_fixed(&self) -> i32 { + self.fixed + } + + fn set_fixed(&mut self, nf: i32) { + self.fixed = nf; + } +} + +impl fmt::Display for Node { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Node {{ v: {}, fixed: {} }}", self.v, self.fixed) + } +} + +fn set_boundary(m: &mut Vec>) { + m[1][1].set_v(1.0); + m[1][1].set_fixed(1); + + m[6][7].set_v(-1.0); + m[6][7].set_fixed(-1); +} + +fn calculate_difference( + m: &Vec>, + d: &mut Vec>, + w: usize, + h: usize, +) -> f64 { + let mut total = 0.0; + for i in 0..h { + for j in 0..w { + let mut v = 0.0; + let mut n = 0; + if i > 0 { + v += m[i - 1][j].get_v(); + n += 1; + } + if j > 0 { + v += m[i][j - 1].get_v(); + n += 1; + } + if i + 1 < h { + v += m[i + 1][j].get_v(); + n += 1; + } + if j + 1 < w { + v += m[i][j + 1].get_v(); + n += 1; + } + let val = m[i][j].get_v() - v / n as f64; + d[i][j].set_v(val); + if m[i][j].get_fixed() == 0 { + total += val * val; + } + } + } + total +} + +fn iter(m: &mut Vec>, w: usize, h: usize) -> f64 { + let mut d: Vec> = vec![vec![Node::new(); w]; h]; + + let mut curr: [f64; 3] = [0.0, 0.0, 0.0]; + let mut diff = 1e10; + + while diff > 1e-24 { + set_boundary(m); + diff = calculate_difference(m, &mut d, w, h); + for i in 0..h { + for j in 0..w { + let current_v = m[i][j].get_v(); + let diff_v = d[i][j].get_v(); + m[i][j].set_v(current_v - diff_v); + } + } + } + + for i in 0..h { + for j in 0..w { + let mut k = 0; + if i != 0 { + k += 1; + } + if j != 0 { + k += 1; + } + if i < h - 1 { + k += 1; + } + if j < w - 1 { + k += 1; + } + curr[(m[i][j].get_fixed() + 1) as usize] += d[i][j].get_v() * k as f64; + } + } + + (curr[2] - curr[0]) / 2.0 +} + +const S: usize = 10; + +fn main() { + let mut mesh: Vec> = vec![vec![Node::new(); S]; S]; + + let r = 2.0 / iter(&mut mesh, S, S); + println!("R = {:.15}", r); +} diff --git a/Task/Return-multiple-values/EasyLang/return-multiple-values.easy b/Task/Return-multiple-values/EasyLang/return-multiple-values.easy index 7888ec771b..c91c232b27 100644 --- a/Task/Return-multiple-values/EasyLang/return-multiple-values.easy +++ b/Task/Return-multiple-values/EasyLang/return-multiple-values.easy @@ -1,4 +1,4 @@ -proc addSubtract a b . sum diff . +proc addSubtract a b &sum &diff . sum = a + b diff = a - b . diff --git a/Task/Reverse-a-string/Common-Lisp/reverse-a-string.lisp b/Task/Reverse-a-string/Common-Lisp/reverse-a-string-1.lisp similarity index 100% rename from Task/Reverse-a-string/Common-Lisp/reverse-a-string.lisp rename to Task/Reverse-a-string/Common-Lisp/reverse-a-string-1.lisp diff --git a/Task/Reverse-a-string/Common-Lisp/reverse-a-string-2.lisp b/Task/Reverse-a-string/Common-Lisp/reverse-a-string-2.lisp new file mode 100644 index 0000000000..7f2e6b2aaf --- /dev/null +++ b/Task/Reverse-a-string/Common-Lisp/reverse-a-string-2.lisp @@ -0,0 +1,15 @@ +(defun reverse-string (value) + "Reverse the string `value`. Handle wide characters with care." + (labels ((combining-char-p (c) + (eql :nsm (sb-unicode:bidi-class c))) + (%reverse (chars group acc) + (cond ((endp chars) + (coerce (append (nreverse group) acc) 'string)) + ((combining-char-p (first chars)) + (%reverse (rest chars) + (cons (first chars) group) + acc)) + (t (%reverse (rest chars) + (list (first chars)) + (append (nreverse group) acc)))))) + (%reverse (coerce value 'list) nil nil))) diff --git a/Task/Reverse-a-string/Excel/reverse-a-string.excel b/Task/Reverse-a-string/Excel/reverse-a-string.excel new file mode 100644 index 0000000000..cbeda522c8 --- /dev/null +++ b/Task/Reverse-a-string/Excel/reverse-a-string.excel @@ -0,0 +1 @@ +=LET(l,LEN(A1),CONCAT(MID(A1,l-SEQUENCE(l)+1,1))) diff --git a/Task/Roman-numerals-Decode/Objeck/roman-numerals-decode.objeck b/Task/Roman-numerals-Decode/Objeck/roman-numerals-decode.objeck new file mode 100644 index 0000000000..f5f93ce275 --- /dev/null +++ b/Task/Roman-numerals-Decode/Objeck/roman-numerals-decode.objeck @@ -0,0 +1,38 @@ +class Roman { + function : DecodeSingle(letter : Char) ~ Int { + select(letter) { + label 'M': { return 1000; } + label 'D': { return 500; } + label 'C': { return 100; } + label 'L': { return 50; } + label 'X': { return 10; } + label 'V': { return 5; } + label 'I': { return 1; } + other: { return 0; } + }; + } + + function : Decode(roman : String) ~ Int { + result := 0; + uRoman := roman->ToUpper(); # label-insensitive + for(i := 0;i < uRoman->Size()-1; i++;) {# loop over all but the last character + # if this character has a lower value than the next character + if (DecodeSingle(uRoman->Get(i)) < DecodeSingle(uRoman->Get(i+1))) { + # subtract it + result -= DecodeSingle(uRoman->Get(i)); + } else { + # add it + result += DecodeSingle(uRoman->Get(i)); + } + } + # Decode the last character, which is always added + result += DecodeSingle(uRoman->Get(uRoman->Size()-1)); + return result; + } + + function : Main(args : String[]) ~ Nil { + Decode("MCMXC")->PrintLine(); # 1990 + Decode("MMVIII")->PrintLine(); # 2008 + Decode("MDCLXVI")->PrintLine(); # 1666 + } +} diff --git a/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy b/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy index 511c41b2b1..7c73b64b86 100644 --- a/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy +++ b/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy @@ -1,8 +1,8 @@ func f x . return x * x * x - 3 * x * x + 2 * x . -numfmt 6 0 -proc findroot start stop step . . +numfmt 0 6 +proc findroot start stop step . x = start while x <= stop val = f x @@ -15,12 +15,23 @@ proc findroot start stop step . . x += step . . -proc drawfunc start stop . . - linewidth 0.3 +xp = 0 / 0 +yp = 0 +proc lineto x y . + x = x * 10 + 50 + y = y * 10 + 50 + if xp = xp : gline xp yp x y + xp = x + yp = y +. +proc drawfunc start stop . + glinewidth 0.3 + gline 0 50 100 50 + gline 50 0 50 100 drawgrid x = start while x <= stop - line x * 10 + 50 f x * 10 + 50 + lineto x f x x += 0.1 . . diff --git a/Task/Roots-of-unity/EasyLang/roots-of-unity.easy b/Task/Roots-of-unity/EasyLang/roots-of-unity.easy index e55c525ab5..d636e38a16 100644 --- a/Task/Roots-of-unity/EasyLang/roots-of-unity.easy +++ b/Task/Roots-of-unity/EasyLang/roots-of-unity.easy @@ -1,13 +1,11 @@ -numfmt 4 0 +numfmt 0 4 for n = 2 to 5 write n & ": " for root = 0 to n - 1 real = cos (360 * root / n) imag = sin (360 * root / n) write real & " " & imag & "i" - if root <> n - 1 - write ", " - . + if root <> n - 1 : write ", " . print "" . diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Objeck/rosetta-code-find-unimplemented-tasks.objeck b/Task/Rosetta-Code-Find-unimplemented-tasks/Objeck/rosetta-code-find-unimplemented-tasks.objeck new file mode 100644 index 0000000000..d0494f5a19 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Objeck/rosetta-code-find-unimplemented-tasks.objeck @@ -0,0 +1,109 @@ +use Web.HTTP, Collection, Data.JSON, System.IO.Filesystem; + +class UnimplTasks { + function : Main(args : String[]) ~ Nil { + if(args->Size() <> 1) { + ">>> Usage: filename.csv <<<"->ErrorLine(); + Runtime->Exit(1); + }; + file_out_name := args[0]; + + all_tasks := GetAllTasks(); + lang_tasks := GetTasksByLang("Objeck"); + + unimpl_tasks := Vector->New(); + each(all_task in all_tasks) { + all_task_str := all_task->GetString(); + + found := false; + for(i := 0; <>found & i < lang_tasks->Size(); i += 1;) { + lang_task := lang_tasks->Get(i); + lang_task_str := lang_task->GetString(); + found := all_task_str->Equals(lang_task_str); + }; + + if(<>found) { + unimpl_tasks->AddBack(all_task); + } + }; + + file_out := FileWriter->New(file_out_name); + file_out->WriteString("description,url\r\n"); + task_base_url_str := "https://rosettacode.org/wiki/"; + each(unimpl_task in unimpl_tasks) { + task_desc := unimpl_task->GetString(); + task_str := task_desc->ReplaceAll(' ', '_'); + + task_str := task_str->ReplaceAll(",", "%2C"); + task_str := task_str->ReplaceAll("\\\"", "\""); + + task_desc := task_desc->ReplaceAll(",", "-"); + task_desc := task_desc->ReplaceAll("\\\"", "\""); + + task_url_str := task_base_url_str + task_str; + + file_out->WriteString("{$task_desc},{$task_url_str}\r\n"); + }; + file_out->Close(); + + + lang_tasks_size := lang_tasks->Size(); + all_tasks_size := all_tasks->Size(); + diff_comp := lang_tasks_size->ToFloat() / all_tasks_size->ToFloat(); + + String->SetFloatPrecision(3); + prec_comp := (diff_comp * 100.0)->ToString(); + prec_comp += "%"; + "Rosetta Code\n{$lang_tasks_size} of {$all_tasks_size} tasks completed, {$prec_comp}%\nfile={$file_out_name}"->PrintLine(); + } + + function : GetTasksByLang(lang : String) ~ Vector { + tasks := Vector->New(); + base_url_str := "https://rosettacode.org/w/api.php?action=query&cmlimit=500&cmtitle=Category:{$lang}&format=json&list=categorymembers"; + + next_url_str := AddTasks(base_url_str, tasks); + while(next_url_str <> Nil) { + next_url_str := base_url_str + "&cmcontinue=" + next_url_str; + next_url_str := AddTasks(next_url_str, tasks); + }; + + return tasks; + } + + function : GetAllTasks() ~ Vector { + tasks := Vector->New(); + base_url_str := "https://rosettacode.org/w/api.php?action=query&cmlimit=500&cmtitle=Category:Programming_Tasks&format=json&list=categorymembers"; + + next_url_str := AddTasks(base_url_str, tasks); + do { + if(next_url_str <> Nil) { + next_url_str := base_url_str + "&cmcontinue=" + next_url_str; + next_url_str := AddTasks(next_url_str, tasks); + }; + } + while(next_url_str <> Nil); + + return tasks; + } + + function : AddTasks(query_url : String, tasks : Vector) ~ String { + response := HttpsClient->QuickGet(Url->New(query_url), "application/json"); + + if(response <> Nil) { + response_json := JsonParser->TextToElement(response->GetContent()->ToString()); + if(response_json <> Nil) { + members_json := response_json->Get("query")->Get("categorymembers"); + each(member_json in members_json) { + tasks->AddBack(member_json->Get("title")); + } + + next_url_json := response_json->Get("continue"); + if(next_url_json <> Nil) { + return next_url_json->Get("cmcontinue")->GetString(); + }; + }; + }; + + return Nil; + } +} diff --git a/Task/Rosetta-Code-Fix-code-tags/FreeBASIC/rosetta-code-fix-code-tags.basic b/Task/Rosetta-Code-Fix-code-tags/FreeBASIC/rosetta-code-fix-code-tags.basic new file mode 100644 index 0000000000..c59a8977db --- /dev/null +++ b/Task/Rosetta-Code-Fix-code-tags/FreeBASIC/rosetta-code-fix-code-tags.basic @@ -0,0 +1,66 @@ +Function ReplaceAll(Byval source As String, Byval find As String, Byval replace As String) As String + Dim As String result = source + Dim As Integer posic = Instr(result, find) + Dim As Integer offset = 1 + While posic > 0 + result = Left(result, posic - 1) & replace & Mid(result, posic + Len(find)) + offset = posic + Len(replace) + posic = Instr(offset, result, find) + Wend + Return result +End Function + +Function ProcessSource(source As String) As String + Dim As String result = source + Dim As String sh = "syntaxhighlight" + Dim As String linea, newContent + Dim As Integer nlPos + + ' Process line by line + While Len(result) > 0 + nlPos = Instr(result, Chr(10)) + If nlPos = 0 Then + linea = result + result = "" + Else + linea = Left(result, nlPos - 1) + result = Mid(result, nlPos + 1) + End If + + ' Check for ") + If closePos > 0 Then + Dim As String lang = Trim(Mid(linea, 6, closePos - 6)) + If lang = "" Then lang = "text" + linea = "<" & sh & " lang=""" & lang & """>" & Mid(linea, closePos + 1) + End If + End If + + newContent &= linea & Chr(10) + Wend + + ' Replace plain with + newContent = ReplaceAll(newContent, "", "<" & sh & " lang=""text"">") + ' Replace closing tags + newContent = ReplaceAll(newContent, "", "") + + Return newContent +End Function + +' Main program +Dim As String filename = "input.txt" +Dim As Integer ff = Freefile +Dim As String linea, content + +If Open(filename For Input As #ff) = 0 Then + While Not Eof(ff) + Line Input #ff, linea + content &= linea & Chr(10) + Wend + Close #ff + + Print ProcessSource(content) +End If + +Sleep diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/FreeBASIC/rosetta-code-rank-languages-by-popularity.basic b/Task/Rosetta-Code-Rank-languages-by-popularity/FreeBASIC/rosetta-code-rank-languages-by-popularity.basic new file mode 100644 index 0000000000..89c67f525c --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/FreeBASIC/rosetta-code-rank-languages-by-popularity.basic @@ -0,0 +1,88 @@ +#include "windows.bi" +#include "win/wininet.bi" + +Type Category + lenguaje As String + numEntrada As Integer +End Type + +Function DownloadString(url As String) As String + Const BUFFER_SIZE As Integer = 8192 + Dim As HINTERNET hInternet, hConnect + Dim As String resultado + Dim As ZString Ptr buffer = Allocate(BUFFER_SIZE) + Dim As DWORD bytesRead + + hInternet = InternetOpen("FreeBASIC", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0) + If hInternet = 0 Then Return "" + + hConnect = InternetOpenUrl(hInternet, Strptr(url), NULL, 0, INTERNET_FLAG_RELOAD, 0) + If hConnect = 0 Then + InternetCloseHandle(hConnect) + Return "" + End If + + Do + If InternetReadFile(hConnect, buffer, BUFFER_SIZE - 1, @bytesRead) = 0 Then Exit Do + If bytesRead = 0 Then Exit Do + resultado &= Left(*buffer, bytesRead) + Loop + + InternetCloseHandle(hConnect) + InternetCloseHandle(hInternet) + Deallocate(buffer) + + Return resultado +End Function + +Sub PrintTopCategories(url As String) + Dim As String content = DownloadString(url) + Dim As Integer startPos, endPos, numEntrada + Dim As String categoria, memberStr + Dim As Category categorias(999) + Dim As Integer cnt = 0 + Dim As Integer i, j + + startPos = Instr(content, "
") + 1 + endPos = Instr(startPos, content, "") + categoria = Mid(content, startPos, endPos - startPos) + + startPos = Instr(endPos, content, "(") + 1 + endPos = Instr(startPos, content, " member") + memberStr = Mid(content, startPos, endPos - startPos) + + numEntrada = 0 + For i = 1 To Len(memberStr) + If Mid(memberStr, i, 1) <> "," Then + numEntrada = numEntrada * 10 + Val(Mid(memberStr, i, 1)) + End If + Next i + + If Left(categoria, 5) <> "Pages" Then + categorias(cnt).lenguaje = categoria + categorias(cnt).numEntrada = numEntrada + cnt += 1 + End If + + startPos = Instr(endPos, content, " 'M') then - ch = ascii(rank(ch) - 13); - else - ch = ascii(rank(ch) + 13); - end; + if (ch >= 'a' & ch <= 'm') | (ch >= 'A' & ch <= 'M') + then ch = ascii(rank(ch) + 13); + else if (ch >= 'n' & ch <= 'z') | (ch >= 'N' & ch <= 'Z') + then ch = ascii(rank(ch) - 13); substr(s,i,1) = ch; end; return (s); end rot13; -toupper: - procedure (ch) returns (char(1)); - dcl ch char(1); - dcl cout char(1); - if ((ch >= 'a') & (ch <= 'z')) then - cout = ascii(rank(ch) - 32); - else - cout = ch; - return (cout); - end toupper; - -isalpha: - procedure (ch) returns (bit(1)); - dcl ch char(1); - if (((ch >= 'A') & (ch <= 'Z')) | - ((ch >= 'a') & (ch <= 'z'))) then - return (true); - else - return (false); - end isalpha; - - end rot13_test; diff --git a/Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 b/Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 new file mode 100644 index 0000000000..da3d4f0baa --- /dev/null +++ b/Task/Run-length-encoding/8080-Assembly/run-length-encoding.8080 @@ -0,0 +1,92 @@ + org 100h + jmp demo + + ; Encode 0-terminated string at HL, store at DE +encode: mov a,m + ana a + jz edone + mvi b,1 +escan: inx h + cmp m + jnz ewrite + inr b + jnz escan + dcr b +ewrite: xchg + mov m,b + inx h + mov m,a + inx h + xchg + jmp encode +edone: stax d + ret + + ; Decode 0-terminated string at HL, store at DE +decode: mov a,m + ana a + jz edone + mov b,a + inx h + mov a,m +dwrite: stax d + inx d + dcr b + jnz dwrite + inx h + jmp decode + + ; Show two examples +demo: lxi h,exampl + call show + lxi h,examp2 +show: push h + call puts ; Show start string + lxi h,nl + call puts + pop h + lxi d,buf1 ; Encode string + call encode + lxi h,buf1 ; Show encoded result (as hexadecimal) + call puthex + lxi h,nl + call puts + lxi h,buf1 ; Decode string + lxi d,buf2 + push d + call decode + pop h + call puts ; Show decoded string + lxi h,nl + jmp puts + +nl: db 13,10,0 +exampl: db 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWW' + db 'WWWWWWWWWWWWWWBWWWWWWWWWWWWWW',0 + + ; Test case with more than 255 repeated items +examp2: db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' + db 'XXXXXXX',0 + + ; Print 0-terminated string at HL +puts: mov a,m! ora a! rz + push h! mvi c,2! mov e,a! call 5! pop h! inx h! jmp puts + + ; Print 0-terminated string at HL as hex +puthex: mov a,m! ora a! rz + push h! call hexout! pop h! inx h! jmp puthex + + ; Print A as hexadecimal +hexout: push psw! rar! rar! rar! rar! call hexlo! pop psw +hexlo: ani 0Fh! cpi 10! jc hexp! adi 7 +hexp: adi '0'! mvi c,2! mov e,a! jmp 5 + +buf1 equ $ +buf2 equ buf1+256 diff --git a/Task/Run-length-encoding/Crystal/run-length-encoding.cr b/Task/Run-length-encoding/Crystal/run-length-encoding.cr new file mode 100644 index 0000000000..fa86ef5a3d --- /dev/null +++ b/Task/Run-length-encoding/Crystal/run-length-encoding.cr @@ -0,0 +1,19 @@ +def rlencode (s) + result = Array({Char, Int32}).new + s.scan(/(.)\1*/) do |m| + result << { m[1][0], m[0].size } + end + result +end + +def rldecode (enc) + String.build do |s| + enc.each do |char, length| + s << char.to_s * length + end + end +end + +enc = rlencode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") +p enc +puts rldecode(enc) diff --git a/Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 b/Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 new file mode 100644 index 0000000000..2ed4a2f8e3 --- /dev/null +++ b/Task/Run-length-encoding/MACRO-11/run-length-encoding.macro11 @@ -0,0 +1,106 @@ + .TITLE RLE + .MCALL .TTYOUT,.EXIT +RLE:: JMP DEMO + + ; ENCODE 0-TERMINATED STRING AT (R0), STORE AT (R1) +ENCODE: MOVB (R0),R2 + BEQ 3$ + MOVB #1,R3 +1$: INC R0 + CMPB (R0),R2 + BNE 2$ + INCB R3 + BNE 1$ + DECB R3 +2$: MOVB R3,(R1)+ + MOVB R2,(R1)+ + BR ENCODE +3$: CLRB (R1) + RTS PC + + ; DECODE 0-TERMINATED STRING AT (R0), STORE AT (R1) +DECODE: MOVB (R0)+,R2 + BEQ 2$ + MOVB (R0)+,R3 + BIC #^C377,R2 +1$: MOVB R3,(R1)+ + SOB R2,1$ + BR DECODE +2$: CLRB (R1) + RTS PC + + ; TESTS +DEMO: MOV #TEST1,R5 + JSR PC,1$ + MOV #TEST2,R5 + JSR PC,1$ + .EXIT +1$: MOV R5,R1 + JSR PC,PRINT + MOV #NL,R1 + JSR PC,PRINT + MOV R5,R0 + MOV #BUFR1,R1 + JSR PC,ENCODE + MOV #BUFR1,R1 + JSR PC,PRHEXS + MOV #NL,R1 + JSR PC,PRINT + MOV #BUFR1,R0 + MOV #BUFR2,R1 + JSR PC,DECODE + MOV #BUFR2,R1 + JSR PC,PRINT + MOV #NL,R1 + JSR PC,PRINT + RTS PC + +NL: .BYTE 15,12,0 + +TEST1: .ASCII /WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWW/ + .ASCIZ /WWWWWWWWWWWWWWBWWWWWWWWWWWWWW/ + +TEST2: .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCII /XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/ + .ASCIZ /XXXXXXX/ + + .EVEN + + ; PRINT STRING AT R1 +PRINT: MOVB (R1)+,R0 + .TTYOUT + BNE PRINT + RTS PC + + ; PRINT HEX BYTE R0 +PRHEXB: MOV R0,-(SP) + ROR R0 + ROR R0 + ROR R0 + ROR R0 + JSR PC,1$ + MOV (SP)+,R0 +1$: BIC #^C17,R0 + CMP R0,#^D10 + BLO 2$ + ADD #7,R0 +2$: ADD #'0,R0 + .TTYOUT + RTS PC + + ; PRINT HEX STRING R1 +PRHEXS: MOVB (R1)+,R0 + BEQ 1$ + JSR PC,PRHEXB + BR PRHEXS +1$: RTS PC + +BUFR1: .BLKB 400 +BUFR2: .BLKB 400 + .END RLE diff --git a/Task/Run-length-encoding/Miranda/run-length-encoding.miranda b/Task/Run-length-encoding/Miranda/run-length-encoding.miranda new file mode 100644 index 0000000000..4d3a554df9 --- /dev/null +++ b/Task/Run-length-encoding/Miranda/run-length-encoding.miranda @@ -0,0 +1,18 @@ +main :: [sys_message] +main = [Stdout (lay [inp, show enc, dec])] + where inp = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" + enc = rlencode inp + dec = rldecode enc + +rlencode :: [*]->[(num,*)] +rlencode xs = [(#p, hd p) | p <- chunk xs] + +rldecode :: [(num,*)]->[*] +rldecode xs = concat [take n (repeat x) | (n,x) <- xs] + +chunk :: [*]->[[*]] +chunk = f [] + where f acc [] = [acc] + f [] (a:as) = f [a] as + f (a:acc) (a:as) = f (a:a:acc) as + f acc (a:as) = acc:f [a] as diff --git a/Task/Run-length-encoding/Refal/run-length-encoding.refal b/Task/Run-length-encoding/Refal/run-length-encoding.refal new file mode 100644 index 0000000000..6174153b19 --- /dev/null +++ b/Task/Run-length-encoding/Refal/run-length-encoding.refal @@ -0,0 +1,44 @@ +$ENTRY Go { + , >: e.In + , >: e.Enc + = >; +}; + +Example { + = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'; +}; + +RLEncode { + e.X = >; +}; + +RLDecode { + e.X = >; +}; + +Count { + e.X, : s.L s.C e.Y = s.L s.C; +}; + +Repeat { + 0 s.C = ; + s.N s.C = s.C s.C>; +}; + +Each { + (e.F) = ; + (e.F) (e.X) e.Y = () ; +}; + +Chunk { + = ; + (e.I) = (e.I); + (e.I t.I) t.I e.X = ; + (e.I) t.J e.X = (e.I) ; + t.I e.X = ; +}; + +Concat { + = ; + (e.X) e.Y = e.X ; +}; diff --git a/Task/Runge-Kutta-method/00-TASK.txt b/Task/Runge-Kutta-method/00-TASK.txt index eafc75a430..a961c26a39 100644 --- a/Task/Runge-Kutta-method/00-TASK.txt +++ b/Task/Runge-Kutta-method/00-TASK.txt @@ -1,5 +1,5 @@ Given the example Differential equation: -:y'(t) = t \times \sqrt {y(t)} +:y'(t) = t \cdot \sqrt {y(t)} With initial condition: :t_0 = 0 and y_0 = y(t_0) = y(0) = 1 This equation has an exact solution: @@ -14,10 +14,10 @@ Demonstrate the commonly used explicit   [[wp:Runge–Kutta_methods#Common_ ;Method summary Starting with a given y_n and t_n calculate: -:\delta y_1 = \delta t\times y'(t_n, y_n)\quad -:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) -:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) -:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad +:\delta y_1 = \delta t\cdot y'(t_n, y_n)\quad +:\delta y_2 = \delta t\cdot y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1) +:\delta y_3 = \delta t\cdot y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2) +:\delta y_4 = \delta t\cdot y'(t_n + \delta t , y_n + \delta y_3)\quad then: :y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4) :t_{n+1} = t_n + \delta t\quad diff --git a/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy b/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy index 4b0cc9de38..89fb62f249 100644 --- a/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy +++ b/Task/Runge-Kutta-method/EasyLang/runge-kutta-method.easy @@ -1,4 +1,4 @@ -numfmt 6 0 +numfmt 0 6 y = 1 for i = 0 to 100 t = i / 10 diff --git a/Task/Runge-Kutta-method/Odin/runge-kutta-method.odin b/Task/Runge-Kutta-method/Odin/runge-kutta-method.odin new file mode 100644 index 0000000000..bc3b88a13d --- /dev/null +++ b/Task/Runge-Kutta-method/Odin/runge-kutta-method.odin @@ -0,0 +1,37 @@ +package runge_kutta + +import "core:fmt" +import "core:math" + +func :: proc(x: f32, y: f32) -> f32 { + return x * math.sqrt(y) +} + +main :: proc() { + STEPS :: 100 + sols: [STEPS + 1]f32 + + x0, y0, h := f32(0.0), f32(1.0), f32(0.1) + xn, yn := x0, y0 + + sols[0] = y0 + factor := f32(1.0 / 6.0) + + for &sol in sols[1:] { + dy1 := h * func(xn,yn) + dy2 := h * func(xn + 0.5 * h, yn + 0.5 * dy1) + dy3 := h * func(xn + 0.5 * h, yn + 0.5 * dy2) + dy4 := h * func(xn + h, yn + dy3) + sol = yn + factor * (dy1 + 2 * dy2 + 2 * dy3 + dy4) + yn = sol + xn = xn + h + } + + for i in 1..>> (32 - bits))) | 0; // | 0 ensures result is 32-bit signed int + } + + /** + * Adds SHA-1 padding to the message bytes. + * @param {Uint8Array} messageBytes - The message as bytes. + * @returns {Uint8Array} The padded message bytes. + */ + _addPadding(messageBytes) { + const msgLenBytes = messageBytes.length; + // Use BigInt for potentially large bit lengths + const bitLength = BigInt(msgLenBytes) * 8n; + + // Calculate the total padded length in bytes + // Need msgLenBytes + 1 (for 0x80) + k (zeros) + 8 (length) = N * 64 + // msgLenBytes + 9 + k = N * 64 + // The number of zero bytes 'k' needed is: + // k = (64 - (msgLenBytes + 9) % 64) % 64 + const k = (this.BLOCK_LENGTH - ((msgLenBytes + 9) % this.BLOCK_LENGTH)) % this.BLOCK_LENGTH; + const paddedLength = msgLenBytes + 1 + k + 8; + const paddedBytes = new Uint8Array(paddedLength); + + // 1. Copy original message + paddedBytes.set(messageBytes); + + // 2. Append a single '1' bit (0x80 byte) + paddedBytes[msgLenBytes] = 0x80; + + // 3. Append K '0' bits (zero bytes). Uint8Array initializes to 0, so this is implicit. + + // 4. Append length L as a 64-bit big-endian integer. + const lengthOffset = paddedLength - 8; + for (let i = 0; i < 8; i++) { + // Extract byte from BigInt bitLength + const shift = BigInt(i) * 8n; + // Place it in big-endian order (most significant byte first) + paddedBytes[lengthOffset + 7 - i] = Number((bitLength >> shift) & 0xffn); + } + + return paddedBytes; + } + + /** + * Computes the SHA-1 hash of a message string. + * @param {string} message - The input message string. + * @returns {string} The SHA-1 hash as a 40-character hex string. + */ + messageDigest(message) { + // 1. Convert message string to UTF-8 bytes + const encoder = new TextEncoder(); // Assumes UTF-8 + const messageBytes = encoder.encode(message); + + // 2. Add padding + const paddedBytes = this._addPadding(messageBytes); + + // 3. Initialize hash values + let state = [...this.H]; // Create a working copy + + // 4. Process message in 64-byte (512-bit) blocks + for (let i = 0; i < paddedBytes.length; i += this.BLOCK_LENGTH) { + const blockBytes = paddedBytes.subarray(i, i + this.BLOCK_LENGTH); + + // Prepare the message schedule (80 32-bit words) + const W = new Array(80); + + // a. Copy block into first 16 words (big-endian) + for (let t = 0; t < 16; t++) { + const offset = t * 4; + W[t] = ((blockBytes[offset] << 24) | + (blockBytes[offset + 1] << 16) | + (blockBytes[offset + 2] << 8) | + (blockBytes[offset + 3])) | 0; // | 0 ensures 32-bit signed int + } + + // b. Extend the first 16 words into the remaining 64 words + for (let t = 16; t < 80; t++) { + const wt = W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16]; + W[t] = this._rotl(wt, 1); + } + + // Initialize hash value for this block + let a = state[0]; + let b = state[1]; + let c = state[2]; + let d = state[3]; + let e = state[4]; + + // Main loop + for (let t = 0; t < 80; t++) { + let f, k; + const round = Math.floor(t / 20); + switch (round) { + case 0: // Rounds 0-19 + f = (b & c) | (~b & d); + k = this.K[0]; + break; + case 1: // Rounds 20-39 + f = b ^ c ^ d; + k = this.K[1]; + break; + case 2: // Rounds 40-59 + f = (b & c) | (b & d) | (c & d); + k = this.K[2]; + break; + case 3: // Rounds 60-79 + f = b ^ c ^ d; + k = this.K[3]; + break; + } + + // Ensure all additions are performed modulo 2^32 + const temp = (this._rotl(a, 5) + f + e + k + W[t]) | 0; + e = d; + d = c; + c = this._rotl(b, 30); + b = a; + a = temp; + } + + // Add this block's hash to the result so far (modulo 2^32) + state[0] = (state[0] + a) | 0; + state[1] = (state[1] + b) | 0; + state[2] = (state[2] + c) | 0; + state[3] = (state[3] + d) | 0; + state[4] = (state[4] + e) | 0; + } + + // 5. Produce the final hash value (big-endian) as a hex string + let hexHash = ""; + for (const h of state) { + // Convert each 32-bit component to hex, padding with '0' + // Use >>> 0 to treat h as unsigned before converting to hex parts + const unsignedH = h >>> 0; + hexHash += (unsignedH >>> 24).toString(16).padStart(2, '0'); + hexHash += ((unsignedH >>> 16) & 0xff).toString(16).padStart(2, '0'); + hexHash += ((unsignedH >>> 8) & 0xff).toString(16).padStart(2, '0'); + hexHash += (unsignedH & 0xff).toString(16).padStart(2, '0'); + } + + return hexHash; + } +} + +// --- Main execution (equivalent to C++ main) --- +const sha1 = new SHA1(); +const message = "Rosetta Code"; +const digest = sha1.messageDigest(message); +console.log(digest); diff --git a/Task/SHA-1/Zig/sha-1.zig b/Task/SHA-1/Zig/sha-1.zig new file mode 100644 index 0000000000..bf8ed827af --- /dev/null +++ b/Task/SHA-1/Zig/sha-1.zig @@ -0,0 +1,126 @@ +const std = @import("std"); + +const SHA1 = struct { + const BLOCK_LENGTH: u32 = 64; + + fn messageDigest(message: []const u8) ![40]u8 { + var state = [5]u32{ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + + const bytes = try addPadding(message); + var i: usize = 0; + while (i < bytes.len / BLOCK_LENGTH) : (i += 1) { + var values = [_]u32{0} ** 80; + + var j: u32 = 0; + while (j < BLOCK_LENGTH) : (j += 1) { + values[j / 4] |= @as(u32, @intCast(bytes[i * BLOCK_LENGTH + j] & 0xff)) << @intCast((3 - j % 4) * 8); + } + + j = 16; + while (j < 80) : (j += 1) { + const value = values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16]; + values[j] = std.math.rotl(u32, value, 1); + } + + var a = state[0]; + var b = state[1]; + var c = state[2]; + var d = state[3]; + var e = state[4]; + var f: u32 = 0; + var k: u32 = 0; + + j = 0; + while (j < 80) : (j += 1) { + switch (j / 20) { + 0 => { + f = (b & c) | (~b & d); + k = 0x5a827999; + }, + 1 => { + f = b ^ c ^ d; + k = 0x6ed9eba1; + }, + 2 => { + f = (b & c) | (b & d) | (c & d); + k = 0x8f1bbcdc; + }, + 3 => { + f = b ^ c ^ d; + k = 0xca62c1d6; + }, + else => unreachable, + } + + // Use wrapping add to prevent integer overflow panics + const rotated_a = std.math.rotl(u32, a, 5); + const temp = @addWithOverflow(rotated_a, f)[0]; + const temp2 = @addWithOverflow(temp, e)[0]; + const temp3 = @addWithOverflow(temp2, k)[0]; + const temp4 = @addWithOverflow(temp3, values[j])[0]; + + e = d; + d = c; + c = std.math.rotl(u32, b, 30); + b = a; + a = temp4; + } + + // Use wrapping adds for state updates + state[0] = @addWithOverflow(state[0], a)[0]; + state[1] = @addWithOverflow(state[1], b)[0]; + state[2] = @addWithOverflow(state[2], c)[0]; + state[3] = @addWithOverflow(state[3], d)[0]; + state[4] = @addWithOverflow(state[4], e)[0]; + } + + var result: [40]u8 = undefined; + var buffer: [8]u8 = undefined; + + for (0..20) |my_i| { + const byte_value: u8 = @intCast((state[my_i / 4] >> @intCast(24 - (my_i % 4) * 8)) & 0xff); + _ = try std.fmt.bufPrint(buffer[0..2], "{x:0>2}", .{byte_value}); + result[my_i * 2] = buffer[0]; + result[my_i * 2 + 1] = buffer[1]; + } + + return result; + } + + fn addPadding(message: []const u8) ![]u8 { + const allocator = std.heap.page_allocator; + + // Initialize with the message + var bytes = std.ArrayList(u8).init(allocator); + defer bytes.deinit(); + + try bytes.appendSlice(message); + try bytes.append(0x80); + + var padding: u32 = BLOCK_LENGTH - @as(u32, @intCast(bytes.items.len % BLOCK_LENGTH)); + if (padding < 8) { + padding += BLOCK_LENGTH; + } + + var i: u32 = 0; + while (i < padding - 8) : (i += 1) { + try bytes.append(0x0); + } + + const bit_length: u64 = 8 * message.len; + i = 0; + while (i < 8) : (i += 1) { + const shift_amount: u6 = @intCast(8 * (7 - i)); // Explicit cast to u6 for shift + try bytes.append(@intCast((bit_length >> shift_amount) & 0xff)); + } + + return bytes.toOwnedSlice(); + } +}; + +pub fn main() !void { + const message = "Rosetta Code"; + const result = try SHA1.messageDigest(message); + const stdout = std.io.getStdOut().writer(); + try stdout.print("{s}\n", .{result}); +} diff --git a/Task/SQL-based-authentication/FreeBASIC/sql-based-authentication.basic b/Task/SQL-based-authentication/FreeBASIC/sql-based-authentication.basic new file mode 100644 index 0000000000..706740e8fe --- /dev/null +++ b/Task/SQL-based-authentication/FreeBASIC/sql-based-authentication.basic @@ -0,0 +1,91 @@ +#Include once "mysql/mysql.bi" +#Include once "md5.bas" +'[https://rosettacode.org/wiki/MD5/Implementation#FreeBASIC] +#Include once "crt.bi" + +' Declare MySQL object +Dim Shared As MYSQL Ptr miSQL +Dim Shared As MYSQL_RES Ptr result +Dim Shared As String pass_salt, pass_md5 + +Function generate_salt() As String + Dim As String salt = "" + For i As Integer = 1 To 16 + salt &= Chr(Int(Rnd * 256)) ' Generate a random byte + Next i + Return salt +End Function + +Function generar_hash(Byval salt As String, Byval password As String) As String + Return MD5(salt & password) +End Function + +Sub connect_db() + miSQL = mysql_init(NULL) + ' Modify these parameters with your real connection data + If mysql_real_connect(miSQL, "localhost", "username", "password", "database", 0, NULL, 0) = NULL Then + Print "Connection error: "; mysql_error(miSQL) + Sleep: End 1 + Else + Print "Conexión exitosa a MySQL!" + End If +End Sub + +Sub create_user(Byval username As String, Byval password As String) + Dim As String query = "INSERT INTO users (username, pass_salt, pass_md5) VALUES ('" & safe_username & "', '" & pass_salt & "', '" & pass_md5 & "')" + + If mysql_query(miSQL, query) <> 0 Then + Print "Query error: "; mysql_error(miSQL) + Else + Print "Usuario creado exitosamente!" + End If +End Sub + +Function authenticate_user(Byval username As String, Byval password As String) As Boolean + Dim As String query = "SELECT * FROM users WHERE username = '" & username & "'" + + If mysql_query(miSQL, query) <> 0 Then + Print "Query error: "; mysql_error(miSQL) + Return False + End If + + result = mysql_store_result(miSQL) + + If result <> NULL Then + If mysql_num_rows(result) > 0 Then + Dim As MYSQL_ROW row = mysql_fetch_row(result) + Dim As String stored_salt = *row[1] ' Assuming pass_salt is in column 1 + Dim As String stored_hash = *row[2] ' Assuming pass_md5 is in column 2 + + Dim As String calculated_hash = generar_hash(stored_salt, password) + + mysql_free_result(result) + + If calculated_hash = stored_hash Then + Return True ' Authenticated user + End If + End If + + mysql_free_result(result) + End If + + Return False ' Authentication failed +End Function + +' Main program +Randomize Timer + +pass_salt = generate_salt() +pass_md5 = generar_hash(pass_salt, "testpassword") + +Print "Salt: "; pass_salt +Print "Hash: "; pass_md5 + +connect_db() +create_user("testuser", "testpassword") +Print "Authentication result: "; authenticate_user("testuser", "testpassword") + +' Free up resources +mysql_close(miSQL) + +Sleep diff --git a/Task/Safe-primes-and-unsafe-primes/EasyLang/safe-primes-and-unsafe-primes.easy b/Task/Safe-primes-and-unsafe-primes/EasyLang/safe-primes-and-unsafe-primes.easy index 1165aaae65..4ef723f12a 100644 --- a/Task/Safe-primes-and-unsafe-primes/EasyLang/safe-primes-and-unsafe-primes.easy +++ b/Task/Safe-primes-and-unsafe-primes/EasyLang/safe-primes-and-unsafe-primes.easy @@ -1,18 +1,12 @@ fastfunc isprim num . - if num < 2 - return 0 - . + if num < 2 : return 0 if num mod 2 = 0 - if num = 2 - return 1 - . + if num = 2 : return 1 return 0 . i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 @@ -20,9 +14,7 @@ fastfunc isprim num . print "First 35 safe primes:" for i = 2 to 999999 if isprim i = 1 and isprim ((i - 1) / 2) = 1 - if count < 35 - write i & " " - . + if count < 35 : write i & " " count += 1 . . @@ -39,9 +31,7 @@ count = 0 print "First 40 unsafe primes:" for i = 2 to 999999 if isprim i = 1 and isprim ((i - 1) / 2) = 0 - if count < 40 - write i & " " - . + if count < 40 : write i & " " count += 1 . . diff --git a/Task/Safe-primes-and-unsafe-primes/REXX/safe-primes-and-unsafe-primes.rexx b/Task/Safe-primes-and-unsafe-primes/REXX/safe-primes-and-unsafe-primes.rexx index 6b56d55eb5..2a06d111a6 100644 --- a/Task/Safe-primes-and-unsafe-primes/REXX/safe-primes-and-unsafe-primes.rexx +++ b/Task/Safe-primes-and-unsafe-primes/REXX/safe-primes-and-unsafe-primes.rexx @@ -1,50 +1,72 @@ -/*REXX program lists a sequence (or a count) of ──safe── or ──unsafe── primes. */ -parse arg N kind _ . 1 . okind; upper kind /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 35 /*Not specified? Then assume default.*/ -if kind=='' | kind=="," then kind= 'SAFE' /* " " " " " */ -if _\=='' then call ser 'too many arguments specified.' -if kind\=='SAFE' & kind\=='UNSAFE' then call ser 'invalid 2nd argument: ' okind -if kind =='UNSAFE' then safe= 0; else safe= 1 /*SAFE is a binary value for function.*/ -w = linesize() - 1 /*obtain the usable width of the term. */ -tell= (N>0); @.=; N= abs(N) /*N is negative? Then don't display. */ -!.=0; !.1=2; !.2=3; !.3=5; !.4=7; !.5=11; !.6=13; !.7=17; !.8=19; #= 8 -@.=''; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1; @.17=1; @.19=1; start= # + 1 -m= 0; lim=0 /*# is the number of low primes so far*/ -$=; do i=1 for # while lim<=N; j= !.i /* [↓] find primes, and maybe show 'em*/ - call safeUnsafe; $= strip($) /*go see if other part of a KIND prime.*/ - end /*i*/ /* [↑] allows faster loop (below). */ - /* [↓] N: default lists up to 35 #'s.*/ - do j=!.#+2 by 2 while limN then do; lim= j; m= m-1; end; else call app; return 1 -app: if tell then if length($ j)>w then do; say $; $ =j; end; else $= $ j; return 1 -ser: say; say; say '***error***' arg(1); say; say; exit 13 /*tell error message. */ -commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -safeUnsafe: ?= (j-1) % 2 /*obtain the other part of KIND prime. */ - if safe then if @.? == '' then return 0 /*not a safe prime.*/ - else return add() /*is " " " */ - else if @.? == '' then return add() /*is an unsafe prime.*/ - else return 0 /*not " " " */ +call Primes 1e8 +call FirstSafe +call FirstUnsafe +call CountBoth +say Format(Time('e'),,3) 'seconds' +exit + +FirstSafe: +procedure expose flag. +say 'The first 35 safe primes are...' +n = 0 +do i = 3 by 2 until n = 35 + if flag.i then do + j = (i-1)/2 + if flag.j then do + n = n+1 + call Charout ,Right(i,5) + if n//10 = 0 then + say + end + end +end +say; say +return + +FirstUnsafe: +procedure expose flag. +say 'The first 40 unsafe primes are...' +call charout ,right(2,5); n = 1 +do i = 3 by 2 until n = 40 + if flag.i then do + j = (i-1)/2 + if \ flag.j then do + n = n+1 + call Charout ,Right(i,5) + if n//10 = 0 then + say + end + end +end +say +return + +CountBoth: +procedure expose flag. +s = 0; u = 1; p = 1 +do i = 3 by 2 to 1e8+1 + a = 1'e'p + if i > a then do + say s 'safe primes below 10^'p + say u 'unsafe primes below 10^'p + say + p = p+1 + end + if flag.i then do + j = (i-1)/2; s = s+(flag.j); u = u+(\ flag.j) + end +end +return + +include Sequences +include Functions +include Constants +include Abend diff --git a/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy b/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy index c3c8f85f75..d6c13e2600 100644 --- a/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy +++ b/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy @@ -1,20 +1,14 @@ -proc test d[] . . +proc test d[] . cnt[] = [ 0 0 0 0 0 0 0 0 0 0 ] - for d in d[] - cnt[d + 1] += 1 - . + for d in d[] : cnt[d + 1] += 1 for i to len d[] - if cnt[i] <> d[i] - return - . + if cnt[i] <> d[i] : return . # found - for d in d[] - write d - . + for d in d[] : write d print "" . -proc backtr ind max . d[] . +proc backtr ind max &d[] . if ind > len d[] test d[] return diff --git a/Task/Self-numbers/EasyLang/self-numbers.easy b/Task/Self-numbers/EasyLang/self-numbers.easy index ceb25d963d..6b5b6ae861 100644 --- a/Task/Self-numbers/EasyLang/self-numbers.easy +++ b/Task/Self-numbers/EasyLang/self-numbers.easy @@ -9,9 +9,7 @@ fastfunc isself start i . j = start sum = digsum start while j < i - if j + sum = i - return 0 - . + if j + sum = i : return 0 sum += 1 j += 1 if j mod 10 = 0 @@ -20,7 +18,7 @@ fastfunc isself start i . . return 1 . -proc main . . +proc main . i = 1 po = 10 digits = 1 @@ -29,9 +27,7 @@ proc main . . start = higher (i - offs) 0 if isself start i = 1 cnt += 1 - if cnt <= 50 - write i & " " - . + if cnt <= 50 : write i & " " . until cnt = 100000000 i += 1 diff --git a/Task/Semiprime/REXX/semiprime-2.rexx b/Task/Semiprime/REXX/semiprime-2.rexx index a05a39e14d..0ffff305e5 100644 --- a/Task/Semiprime/REXX/semiprime-2.rexx +++ b/Task/Semiprime/REXX/semiprime-2.rexx @@ -1,35 +1,36 @@ -/*REXX program determines if any integer (or a range of integers) is/are semiprime. */ -parse arg bot top . /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot=random() /*None given? User wants us to guess.*/ -if top=='' | top=="," then top=bot /*maybe define a range of numbers. */ -tell= top=>0 | top==bot /*should results be shown to the term? */ -w=max(length(bot), length(top)) + 5 /*obtain the maximum width of numbers. */ -numeric digits max(9, w) /*ensure there're enough decimal digits*/ -#=0 /*initialize number of semiprimes found*/ - do n=bot to abs(top) /*show results for a range of numbers. */ - ?=isSemiPrime(n); #=#+? /*Is N a semiprime?; Maybe bump counter*/ - if tell then say right(n,w) right(word("isn't" 'is', ?+1), 6) 'semiprime.' - end /*n*/ -say -if bot\==top then say 'found ' # " semiprimes." -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if x<2 then return 0 /*number too low?*/ - if wordpos(x, '2 3 5 7 11 13 17 19 23')\==0 then return 1 /*it's low prime.*/ - if x//2==0 then return 0; if x//3==0 then return 0 /*÷ by 2; ÷ by 3?*/ - do j=5 by 6 until j*j>x; if x//j==0 then return 0 /*not a prime. */ - if x//(j+2)==0 then return 0 /* " " " */ - end /*j*/ - return 1 /*indicate that X is a prime number. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isSemiPrime: procedure; parse arg x; if x<4 then return 0 +include Settings - do i=2 for 2; if x//i==0 then if isPrime(x%i) then return 1 - else return 0 - end /*i*/ - /* ___ */ - do j=5 by 6; if j*j>x then return 0 /* > √ x ?*/ - do k=j by 2 for 2; if x//k==0 then if isPrime(x%k) then return 1 - else return 0 - end /*k*/ /* [↑] see if 2nd factor is prime or ¬*/ - end /*j*/ /* [↑] J is never a multiple of three.*/ +say 'SEMIPRIME - 4 Mar 2025' +say version +say +numeric digits 100 +call Sequence 1,200 +call Sequence 100001,100200 +call Sequence 1000000001,1000000200 +call Sequence 158456325028528675187087900601,158456325028528675187087900660 +exit + +Sequence: +arg xx,yy +say 'Semiprimes between' xx 'to' yy +if yy = '' then + yy = xx +l = length(yy)+1 +n = 0 +do i = xx to yy + if Semiprime(i) then do + n = n+1 + call Charout ,right(i,l) + if n//5 = 0 then + say + end +end +say +say Format(Time('e'),,3) 'seconds' +say +return + +include Functions +include Numbers +include Sequences +include Abend diff --git a/Task/Semiprime/REXX/semiprime-3.rexx b/Task/Semiprime/REXX/semiprime-3.rexx deleted file mode 100644 index be871d5d54..0000000000 --- a/Task/Semiprime/REXX/semiprime-3.rexx +++ /dev/null @@ -1,41 +0,0 @@ -/*REXX program determines if any integer (or a range of integers) is/are semiprime. */ -parse arg bot top . /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot=random() /*None given? User wants us to guess.*/ -if top=='' | top=="," then top=bot /*maybe define a range of numbers. */ -tell= bot=>0 & top=>0 /*should results be shown to the term? */ -w=max(length(bot), length(top)) /*obtain the maximum width of numbers. */ -!.=; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1; !.29=1; !.31=1 -numeric digits max(9, w) /*ensure there're enough decimal digits*/ -#=0 /*initialize number of semiprimes found*/ - do n=abs(bot) to abs(top) /*show results for a range of numbers. */ - ?=isSemiPrime(n); #=#+? /*Is N a semiprime?; Maybe bump counter*/ - if tell then say right(n,w) right(word("isn't" 'is', ?+1), 6) 'semiprime.' - end /*n*/ -say -if bot\==top then say 'found ' # " semiprimes." -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure expose !.; parse arg x; if x<2 then return 0 /*number too low?*/ - if !.x==1 then return 1 /*a known prime. */ - if x// 2==0 then return 0; if x//3==0 then return 0 /*÷ by 2;÷by 3?*/ - parse var x '' -1 _; if _==5 then return 0 /*last digit a 5?*/ - if x// 7==0 then return 0; if x//11==0 then return 0 /*÷ by 7;÷by 11?*/ - if x//13==0 then return 0; if x//17==0 then return 0 /*÷ by 13;÷by 17?*/ - if x//19==0 then return 0; if x//23==0 then return 0 /*÷ by 19;÷by 23?*/ - do j=29 by 6 until j*j>x; if x//j==0 then return 0 /*not a prime. */ - if x//(j+2)==0 then return 0 /* " " " */ - end /*j*/ - !.x=1; return 1 /*indicate that X is a prime number. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isSemiPrime: procedure expose !.; parse arg x; if x<4 then return 0 - - do i=2 for 2; if x//i==0 then if isPrime(x%i) then return 1 - else return 0 - end /*i*/ - /* ___ */ - do j=5 by 6 until j*j>x /* > √ x ?*/ - do k=j by 2 for 2; if x//k==0 then if isPrime(x%k) then return 1 - else return 0 - end /*k*/ /* [↑] see if 2nd factor is prime or ¬*/ - end /*j*/ /* [↑] J is never a multiple of three.*/ - return 0 diff --git a/Task/Semiprime/REXX/semiprime-4.rexx b/Task/Semiprime/REXX/semiprime-4.rexx deleted file mode 100644 index 2b18d15b4f..0000000000 --- a/Task/Semiprime/REXX/semiprime-4.rexx +++ /dev/null @@ -1,57 +0,0 @@ -/*REXX program determines if any integer (or a range of integers) is/are semiprime. */ -/*REXX program determines if any integer (or a range of integers) is/are semiprime. */ -include Settings - -say version; say 'Semi Primes'; say -parse arg bot top . /*obtain optional arguments from the CL*/ -if bot=='' | bot=="," then bot=Random() /*None givenqq User wants us to guess.*/ -if top=='' | top=="," then top=bot /*maybe define a range of numbers. */ -tell= (top>0) /*should results be shown to the termqq */ -w=Max(Length(bot), Length(top)) /*obtain the maximum width of numbers. */ -numeric digits Max(9, w) /*ensure there're enough decimal digits*/ -hh=0 /*initialize Number of semiprimes found*/ - do n=Abs(bot) to Abs(top) /*show results for a range of numbers. */ - qq=IsSemiPrime(n); hh=hh+qq /*Is N a semiprimeqq; Maybe bump counter*/ -if tell then say Right(n,w) Right(Word("isn't" 'is', qq+1), 6) 'Semiprime.' '('Format(Time('e'),,3) 'seconds)' -call Time('r') - end /*n*/ -say -if bot\==top then say 'found ' hh " semiprimes." -say Format(Time('e'),,3) ' seconds' -exit /*stick a fork in it, we're all done. */ - -IsSemiprime: -/* Is a number semi prime? function */ -procedure expose glob. -arg x -/* Low semiprimes */ -s = '4 6 9 10 14 15 21 22 25 26 33 34 35 38 39 46 49 51 55 57 58 62 65 69 74 77 82 85 86 87 91 93 94 95' -/* Fast values */ -if x < 101 then do - if Wordpos(x,s) = 0 then - return 0 - else - return 1 -end -/* Wheeled scan */ -do i = 2 for 2 - if x//i = 0 then - if Prime(x%i) then - return 1 - else - return 0 -end -do i = 5 by 6 until i*i > x - do j = i by 2 for 2 - if x//j==0 then - if Prime(x%j) then - return 1 - else - return 0 - end -end -return 0 - -include Functions -include Numbers -include Abend diff --git a/Task/Semordnilap/R/semordnilap.r b/Task/Semordnilap/R/semordnilap.r new file mode 100644 index 0000000000..e0cd0022e9 --- /dev/null +++ b/Task/Semordnilap/R/semordnilap.r @@ -0,0 +1,17 @@ +library(stringi) + +unixdict <- read.table("unixdict.txt", col.names="forwards") +unixdict$backwards <- stri_reverse(unixdict$forwards) + +#Remove all actual palindromes, as we do not want those +unixdict <- subset(unixdict, forwards!=backwards) + +for(i in seq_along(unixdict$forwards)){ + unixdict$issemordnilap[i] <- with(unixdict, forwards[i] %in% backwards) +} + +semordnilaps <- subset(unixdict, (issemordnilap==TRUE)&(forwards>backwards), select=-issemordnilap) +length(semordnilaps$forwards) + +random <- sample(seq_along(semordnilaps$forwards), 5, replace=FALSE) +print(semordnilaps[random,], row.names=FALSE) diff --git a/Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg b/Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg new file mode 100644 index 0000000000..960870975a --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/ALGOL-60/sequence-of-primes-by-trial-division.alg @@ -0,0 +1,46 @@ +begin + +comment - return n mod m; +integer procedure mod(n, m); + value n, m; integer n, m; +begin + mod := n - entier(n / m) * m; +end; + +integer i, k, m, n, sq, nprimes; +boolean divisible; + +nprimes := 20; +outstring(1,"Showing first"); +outinteger(1, nprimes); +outstring(1,"prime numbers\n"); +begin + integer array p[1:nprimes]; + comment - initialize p with first (and only even) prime; + p[1] := 2; + outinteger(1, p[1]); + i := 1; comment - count of primes found so far; + k := 1; comment - index of largest prime <= sqrt of n; + n := 3; comment - current number being checked; + for i := i while i < nprimes do + begin + sq := p[k] * p[k]; + if sq <= n then k := k + 1; + divisible := false; + m := 2; comment - index of possible divisors; + for m := m while m <= k and not divisible do + begin + if mod(n, p[m]) = 0 then divisible := true; + m := m + 1; + end; + if not divisible then + begin + i := i + 1; + p[i] := n; + outinteger(1, n); + end; + n := n + 2; + end; + end; + +end diff --git a/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy b/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy index 62bcc99d7a..260f62bfde 100644 --- a/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy +++ b/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy @@ -1,21 +1,14 @@ -func prime n . - if n mod 2 = 0 and n > 2 - return 0 - . - i = 3 - while i <= sqrt n - if n mod i = 0 - return 0 - . - i += 2 +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 1 . return 1 . -proc primeSequ first last . sequ[] . +proc primeSequ first last &sequ[] . for i = first to last - if prime i = 1 - sequ[] &= i - . + if isprim i = 1 : sequ[] &= i . . primeSequ 2 100 seq[] diff --git a/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas b/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas index eee758aeaa..b30e4b8816 100644 --- a/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas +++ b/Task/Sequence-of-primes-by-trial-division/PascalABC.NET/sequence-of-primes-by-trial-division.pas @@ -1,4 +1,4 @@ ## -function IsPrime(n: integer) := (2..n.Sqrt.Round).All(i -> n.NotDivs(i)); +function IsPrime(n: integer) := (2..n.Sqrt.Trunc).All(i -> n.NotDivs(i)); (2..100).Where(IsPrime).Println diff --git a/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx b/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx deleted file mode 100644 index 2874c730e3..0000000000 --- a/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division-1.rexx +++ /dev/null @@ -1,18 +0,0 @@ -/*REXX program lists a sequence of primes by testing primality by trial division. */ -parse arg n . /*get optional number of primes to find*/ -if n=='' | n=="," then n= 26 /*Not specified? Then use the default.*/ -tell= (n>0); n= abs(n) /*Is N negative? Then don't display.*/ -@.1=2; if tell then say right(@.1, 9) /*display 2 as a special prime case. */ -#=1 /*# is number of primes found (so far)*/ - /* [↑] N: default lists up to 101 #s.*/ - do j=3 by 2 while #0); N= abs(N) /*N is negative? Then don't display. */ -@.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; #= 5; s= @.# + 2 - /* [↑] is the number of low primes.*/ - do p=1 for # while p<=N /* [↓] find primes, and maybe show 'em*/ - if tell then say right(@.p, 9) /*display some pre─defined low primes. */ - !.p= @.p**2 /*also compute the squared value of P. */ - end /*p*/ /* [↑] allows faster loop (below). */ - /* [↓] N: default lists up to 101 #s.*/ - do j=s by 2 while # memo = []; +var n = 0; +var start = DateTime.Now; + +for (var count = 1; count <= 100; count++) +{ + Write($"{count}: "); + + // Did we already see this count from a smaller n? + if (memo.TryGetValue(count, out var k)) + { + WriteLine(k); + continue; + } + + // Count is prime or 1? + if (CountDivisors(count) <= 2) + { + k = BigInteger.One << (count - 1); // 2^(count-1) + WriteLine(k); + continue; + } + + // Count is 2 × prime? + if (count % 2 == 0 && CountDivisors(count / 2) == 2) + { + k = (BigInteger.One << (count / 2 - 1)) * 3; // 3⁽²⁻¹⁾ + WriteLine(k); + continue; + } + + // Count is 3 × prime? + if (count % 3 == 0 && CountDivisors(count / 3) == 2) + { + k = (BigInteger.One << (count / 3 - 1)) * 9; // 3⁽³⁻¹⁾ + WriteLine(k); + continue; + } + + // Count is 4 × prime? + if (count >= 16 && count % 4 == 0 && CountDivisors(count / 4) == 2) + { + // 4 is factored as 2x2 giving 3⁽²⁻¹⁾5⁽²⁻¹⁾ = 3·5 which is less than 3⁽⁴⁻¹⁾ = 27 + k = (BigInteger.One << (count / 4 - 1)) * 15; + WriteLine(k); + continue; + } + + // Etc. + if (count >= 25 && count % 5 == 0 && CountDivisors(count / 5) == 2) + { + k = (BigInteger.One << (count / 5 - 1)) * 81; // 3⁽⁵⁻¹⁾ + WriteLine(k); + continue; + } + + if (count >= 36 && count % 6 == 0 && CountDivisors(count / 6) == 2) + { + k = (BigInteger.One << (count / 6 - 1)) * 45; // 3⁽³⁻¹⁾5⁽²⁻¹⁾ = 9·5 + WriteLine(k); + continue; + } + + if (count >= 49 && count % 7 == 0 && CountDivisors(count / 7) == 2) + { + k = (BigInteger.One << (count / 7 - 1)) * 729; // 3⁽⁷⁻¹⁾ + WriteLine(k); + continue; + } + + // Otherwise just try each number until we find a match + while (true) + { + ++n; + var d = CountDivisors(n); + + if (d == count) + break; + + // Save this one for later + if (d > count && !memo.ContainsKey(d)) + memo[d] = n; + } + + WriteLine(n); +} + +WriteLine($"Elapsed time: {(DateTime.Now - start).TotalMilliseconds:0}ms"); diff --git a/Task/Set-puzzle/EasyLang/set-puzzle.easy b/Task/Set-puzzle/EasyLang/set-puzzle.easy index 876402c56a..fdd59e2387 100644 --- a/Task/Set-puzzle/EasyLang/set-puzzle.easy +++ b/Task/Set-puzzle/EasyLang/set-puzzle.easy @@ -4,28 +4,25 @@ attr$[][] &= [ "red " "green " "purple" ] attr$[][] &= [ "diamond" "oval" "squiggle" ] # subr init - for card = 0 to 80 - pack[] &= card - . + for card = 0 to 80 : pack[] &= card . -proc card2attr card . attr[] . +proc card2attr card &attr[] . attr[] = [ ] for i to 4 attr[] &= card mod 3 + 1 card = card div 3 . . -proc printcards cards[] . . +proc printcards cards[] . for card in cards[] card2attr card attr[] - for i to 4 - write attr$[i][attr[i]] & " " - . + write " " + for i to 4 : write attr$[i][attr[i]] & " " print "" . print "" . -proc getsets . cards[] set[] . +proc getsets &cards[] &set[] . set[] = [ ] for i to len cards[] card2attr cards[i] a[] @@ -36,9 +33,7 @@ proc getsets . cards[] set[] . ok = 1 for at to 4 s = a[at] + b[at] + c[at] - if s <> 3 and s <> 6 and s <> 9 - ok = 0 - . + if s <> 3 and s <> 6 and s <> 9 : ok = 0 . if ok = 1 set[] &= cards[i] @@ -49,8 +44,7 @@ proc getsets . cards[] set[] . . . . -proc run ncards nsets . . - # +proc run ncards nsets . repeat init cards[] = [ ] @@ -71,5 +65,3 @@ proc run ncards nsets . . . . run 9 4 -print " --------------------------" -run 12 6 diff --git a/Task/Set-puzzle/JavaScript/set-puzzle.js b/Task/Set-puzzle/JavaScript/set-puzzle.js new file mode 100644 index 0000000000..0774e4fc66 --- /dev/null +++ b/Task/Set-puzzle/JavaScript/set-puzzle.js @@ -0,0 +1,86 @@ +// Constants +const number = ["1", "2", "3"]; +const color = ["red", "green", "purple"]; +const shade = ["solid", "open", "striped"]; +const shape = ["oval", "squiggle", "diamond"]; + +// Card class +class Card { + constructor(value) { + this.value = value; + } + + toString() { + return `${number[Math.floor(this.value/27)]} ${color[Math.floor(this.value/9)%3]} ${shade[Math.floor(this.value/3)%3]} ${shape[this.value%3]}`; + } +} + +// Shuffle an array +function shuffle(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } +} + +// Main game function +function game(level, cards, sets) { + // Create deck + const deck = []; + for (let i = 0; i < 81; i++) { + deck.push(new Card(i)); + } + + let found = []; + while (found.length !== sets) { + found = []; + + // Deal + shuffle(deck); + + // Consider all triplets + for (let i = 2; i < cards; i++) { + const c1 = deck[i]; + for (let j = 1; j < i; j++) { + const c2 = deck[j]; + + outer: for (let k = 0; k < j; k++) { + const c3 = deck[k]; + + // Check if it's a set + for (let f = 1; f < 81; f *= 3) { + if ((Math.floor(c1.value/f)%3 + Math.floor(c2.value/f)%3 + Math.floor(c3.value/f)%3) % 3 !== 0) { + continue outer; // not a set + } + } + + // It's a set + found.push([c1, c2, c3]); + } + } + } + } + + // Output results + console.log(`${level} game. ${cards} cards, ${sets} sets.`); + console.log("Cards:"); + for (let i = 0; i < cards; i++) { + console.log(" ", deck[i].toString()); + } + + console.log("Sets:"); + for (const set of found) { + console.log(` ${set[0]}\n ${set[1]}\n ${set[2]}`); + } +} + +// Run the games +function main() { + // Set random seed with current time + Math.random(); + + game("Basic", 9, 4); + game("Advanced", 12, 6); +} + +main(); diff --git a/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy b/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy index 92b6e3a8ac..dfe6134bd5 100644 --- a/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy +++ b/Task/Set-right-adjacent-bits/EasyLang/set-right-adjacent-bits.easy @@ -1,4 +1,4 @@ -proc adjacent txt$ n . . +proc adjacent txt$ n . print "n = " & n & ", width = " & len txt$ print "input: " & txt$ txt$[] = strchars txt$ diff --git a/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy b/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy index 7bfb89acf3..52487b481e 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy +++ b/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy @@ -14,16 +14,14 @@ func dice7b . . return h mod1 7 . -numfmt 3 0 +numfmt 0 3 n = 1000000 len dist[] 7 # -proc checkdist . . +proc checkdist . for i to len dist[] h = dist[i] / n * 7 - if abs (h - 1) > 0.01 - bad = 1 - . + if abs (h - 1) > 0.01 : bad = 1 dist[i] = 0 print h . diff --git a/Task/Sexy-primes/EasyLang/sexy-primes.easy b/Task/Sexy-primes/EasyLang/sexy-primes.easy index ade3d0377c..9e9f08a77a 100644 --- a/Task/Sexy-primes/EasyLang/sexy-primes.easy +++ b/Task/Sexy-primes/EasyLang/sexy-primes.easy @@ -1,5 +1,5 @@ len isdiv[] 1000035 -proc sieve . . +proc sieve . max = sqrt len isdiv[] for d = 2 to max if isdiv[d] = 0 @@ -11,7 +11,7 @@ proc sieve . . . sieve # -proc showsx nr . . +proc showsx nr . for i = len isdiv[] - 6 * nr downto 3 if isdiv[i] = 0 h = 0 @@ -39,7 +39,7 @@ proc showsx nr . . . print "" . -proc showunsx . . +proc showunsx . for i = len isdiv[] - 6 downto 2 if isdiv[i] = 0 and isdiv[i + 6] = 1 and (i <= 6 or isdiv[i - 6] = 1) cnt += 1 diff --git a/Task/Sexy-primes/REXX/sexy-primes.rexx b/Task/Sexy-primes/REXX/sexy-primes.rexx index 8be9f90333..a73774cf2a 100644 --- a/Task/Sexy-primes/REXX/sexy-primes.rexx +++ b/Task/Sexy-primes/REXX/sexy-primes.rexx @@ -1,88 +1,73 @@ -/*REXX program finds and displays various kinds of sexy and unsexy primes less than N.*/ -parse arg N endU end2 end3 end4 end5 . /*obtain optional argument from the CL.*/ -if N=='' | N=="," then N= 1000035 - 1 /*Not specified? Then use the default.*/ -if endU=='' | endU=="," then endU= 10 /* " " " " " " */ -if end2=='' | end2=="," then end2= 5 /* " " " " " " */ -if end3=='' | end3=="," then end3= 5 /* " " " " " " */ -if end4=='' | end4=="," then end4= 5 /* " " " " " " */ -if end5=='' | end5=="," then end4= 5 /* " " " " " " */ -call genSq /*gen some squares for the DO k=7 UNTIL*/ -call genPx /* " prime (@.) & sexy prime (X.) array*/ -call genXU /*gen lists, types of sexy Ps, unsexy P*/ -call getXs /*gen lists, last # of types of sexy Ps*/ - @sexy= ' sexy prime' /*a handy literal for some of the SAYs.*/ - w2= words( translate(x2,, '~') ); y2= words(x2) /*count #primes in the sexy pairs. */ - w3= words( translate(x3,, '~') ); y3= words(x3) /* " " " " " " triplets. */ - w4= words( translate(x4,, '~') ); y4= words(x4) /* " " " " " " quadruplets*/ - w5= words( translate(x5,, '~') ); y5= words(x5) /* " " " " " " quintuplets*/ -say 'There are ' commas(w2%2) @sexy "pairs less than " Nc -say 'The last ' commas(end2) @sexy "pairs are:"; say subword(x2, max(1,y2-end2+1)) +-- 12 Apr 2025 +include Settings + +call Time('r') +say 'SEXY PRIMES' +say version say -say 'There are ' commas(w3%3) @sexy "triplets less than " Nc -say 'The last ' commas(end3) @sexy "triplets are:"; say subword(x3, max(1,y3-end3+1)) +call GetPrimes 1e6+34 +call ShowCount +say Format(Time('e'),,3) 'seconds' +exit + +GetPrimes: +procedure expose prim. flag. +arg xx +say 'Get primes up to' xx'...' +call Primes xx +say prim.0 'found' say -say 'There are ' commas(w4%4) @sexy "quadruplets less than " Nc -say 'The last ' commas(end4) @sexy "quadruplets are:"; say subword(x4, max(1,y4-end4+1)) +return + +ShowCount: +procedure expose prim. flag. +arg xx +sexy. = 0; last. = 0 +do i = prim.0 by -1 to 2 + a = prim.i; b = a-6; c = a+6 + if \ flag.b & \ flag.c then do + sexy.0 = sexy.0+1; d = last.0.0 + if d < 11 then do + d = d+1; last.0.d = a; last.0.0 = d + end + iterate i + end + b = a + do n = 1 to 4 + b = b-6 + if flag.b then do + sexy.n = sexy.n+1; d = last.n.0 + if d < 5 then do + d = d+1; last.n.d = b; last.n.0 = d + end + end + else + iterate i + end +end +w = 'pairs triplets quadruplets quintuplets' +do i = 1 to 4 + say sexy.i word(w,i) 'ending with' + do j = 5 by -1 to 1 + a = last.i.j + if a > 0 then do + do k = 1 to i+1 + call Charout ,a' ' + a = a+6 + end + say + end + end + say +end +say sexy.0 'unsexy ending with' +do j = 11 by -1 to 2 + call Charout ,last.0.j' ' +end say -say 'There is ' commas(w5%5) @sexy "quintuplet less than " Nc -say 'The last ' commas(end4) @sexy "quintuplet are:"; say subword(x5, max(1,y5-end4+1)) say -say 'There are ' commas(s1) " sexy primes less than " Nc -say 'There are ' commas(u1) " unsexy primes less than " Nc -say 'The last ' commas(endU) " unsexy primes are: " subword(u, max(1,u1-endU+1)) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: procedure; parse arg _; n= _'.9'; #= 123456789; b= verify(n, #, "M") - e= verify(n, #'0', , verify(n, #"0.", 'M') ) - 4 - do j=e to b by -3; _= insert(',', _, j); end /*j*/; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genSQ: do i=17 by 2 until i**2 > N+7; s.i= i**2; end; return /*S used for square roots*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genPx: @.=; #= 0; !.= 0. /*P array; P count; sexy P array*/ - if N>1 then do; #= 1; @.1= 2; !.2= 1; end /*count of primes found (so far)*/ - x.=!.; LPs=3 5 7 11 13 17 /*sexy prime array; low P list.*/ - do j=3 by 2 to N+6 /*start in the cellar & work up.*/ - if j<19 then if wordpos(j, LPs)==0 then iterate - else do; #= #+1; @.#= j; !.j= 1; b= j - 6 - if !.b then x.b= 1; iterate - end - if j// 3 ==0 then iterate /* ··· and eliminate multiples of 3.*/ - parse var j '' -1 _ /* get the rightmost digit of J. */ - if _ ==5 then iterate /* ··· and eliminate multiples of 5.*/ - if j// 7 ==0 then iterate /* ··· " " " " 7.*/ - if j//11 ==0 then iterate /* ··· " " " " 11.*/ - if j//13 ==0 then iterate /* ··· " " " " 13.*/ - do k=7 until s._ > j; _= @.k /*÷ by primes starting at 7th prime. */ - if j // _ == 0 then iterate j /*get the remainder of j÷@.k ___ */ - end /*k*/ /*divide up through & including √ J */ - if j<=N then do; #= #+1; @.#= j; end /*bump P counter; assign prime to @.*/ - !.j= 1 /*define Jth number as being prime.*/ - b= j - 6 /*B: lower part of a sexy prime pair?*/ - if !.b then do; x.b=1; if j<=N then x.j=1; end /*assign (both parts ?) sexy Ps.*/ - end /*j*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genXU: u= 2; Nc=commas(N+1); s= /*1st unsexy prime; add commas to N+1*/ - say 'There are ' commas(#) " primes less than " Nc; say - do k=2 for #-1; p= @.k; if x.p then s=s p /*if sexy prime, add it to list*/ - else u= u p /* " unsexy " " " " " */ - end /*k*/ /* [↑] traispe through odd Ps. */ - s1= words(s); u1= words(u); return /*# of sexy primes; # unsexy primes.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -getXs: x2=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy prime list. */ - b=p- 6; if \x.b then iterate; x2=x2 b'~'p - end /*k*/ - x3=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy P triplets. */ - b=p- 6; if \x.b then iterate - t=p-12; if \x.t then iterate; x3=x3 t'~' || b"~"p - end /*k*/ - x4=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy P quads. */ - b=p- 6; if \x.b then iterate - t=p-12; if \x.t then iterate - q=p-18; if \x.q then iterate; x4=x4 q'~'t"~" || b'~'p - end /*k*/ - x5=; do k=2 for #-1; p=@.k; if \x.p then iterate /*build sexy P quints. */ - b=p- 6; if \x.b then iterate - t=p-12; if \x.t then iterate - q=p-18; if \x.q then iterate - v=p-24; if \x.v then iterate; x5=x5 v'~'q"~"t'~' || b"~"p - end /*k*/; return +return + +include Sequences +include Functions +include Abend diff --git a/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy b/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy index 327b4c349d..32bbcd3d78 100644 --- a/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy +++ b/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy @@ -1,13 +1,11 @@ -proc shoelace . p[][] res . - sum = 0 +func shoelace &p[][] . for i = 1 to len p[][] - 1 sum += p[i][1] * p[i + 1][2] sum -= p[i + 1][1] * p[i][2] . sum += p[i][1] * p[1][2] sum -= p[1][1] * p[i][2] - res = abs sum / 2 + return abs sum / 2 . data[][] = [ [ 3 4 ] [ 5 11 ] [ 12 8 ] [ 9 5 ] [ 5 6 ] ] -shoelace data[][] res -print res +print shoelace data[][] diff --git a/Task/Shoelace-formula-for-polygonal-area/Rust/shoelace-formula-for-polygonal-area.rs b/Task/Shoelace-formula-for-polygonal-area/Rust/shoelace-formula-for-polygonal-area.rs new file mode 100644 index 0000000000..47f98f3139 --- /dev/null +++ b/Task/Shoelace-formula-for-polygonal-area/Rust/shoelace-formula-for-polygonal-area.rs @@ -0,0 +1,25 @@ +fn shoelace(points: &[(f64, f64)]) -> f64 { + let mut left_sum = 0.0; + let mut right_sum = 0.0; + + for i in 0..points.len() { + let j = (i + 1) % points.len(); + left_sum += points[i].0 * points[j].1; + right_sum += points[j].0 * points[i].1; + } + + 0.5 * (left_sum - right_sum).abs() +} + +fn main() { + let points: Vec<(f64, f64)> = vec![ + (3.0, 4.0), + (5.0, 11.0), + (12.0, 8.0), + (9.0, 5.0), + (5.0, 6.0), + ]; + + let ans = shoelace(&points); + println!("{}", ans); +} diff --git a/Task/Show-ASCII-table/EasyLang/show-ascii-table.easy b/Task/Show-ASCII-table/EasyLang/show-ascii-table.easy index 363ed710b2..9ada74d0c2 100644 --- a/Task/Show-ASCII-table/EasyLang/show-ascii-table.easy +++ b/Task/Show-ASCII-table/EasyLang/show-ascii-table.easy @@ -1,4 +1,4 @@ -numfmt 0 3 +numfmt 3 0 for i range0 16 for j = 32 + i step 16 to 127 if j = 32 diff --git a/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy b/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy index 265b0204e3..a10991eb9c 100644 --- a/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy +++ b/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy @@ -1,13 +1,15 @@ x = 5 y = 10 ang = 60 -linewidth 0.5 +glinewidth 0.5 # -proc curv o l a . . +proc curv o l a . if o = 0 + px = x + py = y x += cos ang * l y += sin ang * l - line x y + gline px py x y else o -= 1 l /= 2 @@ -18,5 +20,4 @@ proc curv o l a . . curv o l (-a) . . -move x y curv 7 90 -60 diff --git a/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy b/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy index d4bf14c923..070ed36b34 100644 --- a/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy +++ b/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy @@ -1,6 +1,5 @@ -proc carp x y sz . . - move x - sz / 2 y - sz / 2 - rect sz sz +proc carp x y sz . + grect x - sz / 2 y - sz / 2 sz sz if sz > 0.5 h = sz / 3 carp x - sz y - sz h @@ -13,7 +12,7 @@ proc carp x y sz . . carp x y + sz h . . -background 000 -clear -color 633 +gbackground 000 +gclear +gcolor 633 carp 50 50 100 / 3 diff --git a/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy b/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy index 385eed3747..6e916e0a21 100644 --- a/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy +++ b/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy @@ -1,16 +1,18 @@ order = 5 # -clear -linewidth 0.2 +gclear +glinewidth 0.2 scale = 1 / (2 + cos 72 * 2) # -proc pentagon x y side depth . . +proc pentagon x y side depth . if depth = 0 move x y for angle = 0 step 72 to 288 + px = x + py = y x += cos angle * side y += sin angle * side - line x y + gline px py x y . else side *= scale diff --git a/Task/Sierpinski-square-curve/EasyLang/sierpinski-square-curve.easy b/Task/Sierpinski-square-curve/EasyLang/sierpinski-square-curve.easy index 99fbca096e..67a22b4578 100644 --- a/Task/Sierpinski-square-curve/EasyLang/sierpinski-square-curve.easy +++ b/Task/Sierpinski-square-curve/EasyLang/sierpinski-square-curve.easy @@ -1,4 +1,4 @@ -proc lsysexp level . axiom$ rules$[] . +proc lsysexp level &axiom$ &rules$[] . for l to level an$ = "" for c$ in strchars axiom$ @@ -13,14 +13,15 @@ proc lsysexp level . axiom$ rules$[] . swap axiom$ an$ . . -proc lsysdraw axiom$ x y ang lng . . - linewidth 0.3 - move x y +proc lsysdraw axiom$ x y ang lng . + glinewidth 0.3 for c$ in strchars axiom$ if c$ = "F" + xp = x + yp = y x += cos dir * lng y += sin dir * lng - line x y + gline xp yp x y elif c$ = "-" dir -= ang elif c$ = "+" diff --git a/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy b/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy index 94d4deb12c..ad1b1af585 100644 --- a/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy +++ b/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy @@ -1,7 +1,6 @@ -proc triang lev x y size . . +proc triang lev x y size . if lev = 0 - move x y - circle 0.15 + gcircle x y 0.15 else lev -= 1 size /= 2 diff --git a/Task/Sierpinski-triangle/Uxntal/sierpinski-triangle.uxnatl b/Task/Sierpinski-triangle/Uxntal/sierpinski-triangle.uxnatl index 5fe1af088c..228f499d0f 100644 --- a/Task/Sierpinski-triangle/Uxntal/sierpinski-triangle.uxnatl +++ b/Task/Sierpinski-triangle/Uxntal/sierpinski-triangle.uxnatl @@ -1,23 +1,15 @@ -( uxncli sierpinski.rom ) - -|100 @on-reset ( -> ) - - #10 STHk #01 SUB - &ver ( -- ) - DUP - #00 EQUk ?{ - &pad ( -- ) - #2018 DEO - INC GTHk ?&pad - } POP - #00 - &fill - ANDk #202a ROT ?{ SWP } POP #18 DEO - #2018 DEO - INC ADDk STHkr LTH ?&fill - POP2 - #0a18 DEO - #01 SUB DUP #ff NEQ ?&ver - POP POPr - +@sierpinski ( -> ) + ( mask ) [ LIT2r 0a18 ] [ LIT2r 2018 ] + ( size ) [ LIT2 &size 1001 ] SUB + &>ver ( -- ) + DUP INCk + &>pad ( length -- ) + DEOkr + #01 SUB DUP ?&>pad + &>fill ( length i -- ) + ANDk DUP2r ?{ POP2r ORA2kr } DEOr DEOkr + INC ADDk ,&size LDR LTH ?&>fill + POP2 OVR2r DEOr + #01 SUB INCk ?&>ver + POP POP2r POP2r BRK BRK diff --git a/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas b/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas index 07aafc9fdb..e8ed58c4e3 100644 --- a/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas +++ b/Task/Sieve-of-Eratosthenes/PascalABC.NET/sieve-of-eratosthenes.pas @@ -2,7 +2,7 @@ function Eratosthenes(N: integer): List; type primetype = (nonprime,prime); begin var sieve := |nonprime|*2 + |prime|*(N-1); - for var i:=2 to N.Sqrt.Round do + for var i:=2 to N.Sqrt.Trunc do if sieve[i] = prime then for var j := i*i to N step i do sieve[j] := nonprime; diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx index 1a8497693c..a232b3bdbf 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx @@ -1,12 +1,29 @@ -/*REXX program generates and displays primes via the sieve of Eratosthenes algorithm.*/ -parse arg H .; if H=='' | H=="," then H= 200 /*optain optional argument from the CL.*/ -w= length(H); @prime= right('prime', 20) /*W: is used for aligning the output.*/ -@.=. /*assume all the numbers are prime. */ -#= 0 /*number of primes found (so far). */ - do j=2 for H-1; if @.j=='' then iterate /*all prime integers up to H inclusive.*/ - #= # + 1 /*bump the prime number counter. */ - say @prime right(#,w) " ───► " right(j,w) /*display the prime to the terminal. */ - do m=j*j to H by j; @.m=; end /*strike all multiples as being ¬ prime*/ - end /*j*/ /* ─── */ -say /*stick a fork in it, we're all done. */ -say right(#, 1+w+length(@prime) ) 'primes found up to and including ' H +/*REXX program generates primes via sieve of Eratosthenes algorithm. +* 21.07.2012 Walter Pachl derived from above Rexx version +* avoid symbols @ and # (not supported by ooRexx) +* avoid negations (think positive) +**********************************************************************/ + highest=200 /*define highest number to use. */ + is_prime.=1 /*assume all numbers are prime. */ + w=length(highest) /*width of the biggest number, */ + /* it's used for aligned output.*/ + Do j=3 To highest By 2, /*strike multiples of odd ints. */ + While j*j<=highest /* up to sqrt(highest) */ + If is_prime.j Then Do + Do jm=j*3 To highest By j+j /*start with next odd mult. of J */ + is_prime.jm=0 /*mark odd mult. of J not prime. */ + End + End + End + np=0 /*number of primes shown */ + Call tell 2 + Do n=3 To highest By 2 /*list all the primes found. */ + If is_prime.n Then Do + Call tell n + End + End + Exit +tell: Parse Arg prime + np=np+1 + Say ' prime number' right(np,w) " --> " right(prime,w) + Return diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx index 77294f8bc1..7ed21e1fa3 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx @@ -1,24 +1,68 @@ -/*REXX program generates primes via a wheeled sieve of Eratosthenes algorithm. */ -parse arg H .; if H=='' then H=200 /*let the highest number be specified. */ -tell=h>0; H=abs(H); w=length(H) /*a negative H suppresses prime listing*/ -if 2<=H & tell then say right(1, w+20)'st prime ───► ' right(2, w) -@.= '0'x /*assume that all numbers are prime. */ -cw= length(@.) /*the cell width that holds numbers. */ -#= w<=H /*the number of primes found (so far).*/ -!=0 /*skips the top part of sieve marking. */ - do j=3 by 2 for (H-2)%2; b= j%cw /*odd integers up to H inclusive. */ - if substr(x2b(c2x(@.b)),j//cw+1,1) then iterate /*is J composite ? */ - #= # + 1 /*bump the prime number counter. */ - if tell then say right(#, w+20)th(#) 'prime ───► ' right(j, w) - if ! then iterate /*should the top part be skipped ? */ - jj=j * j /*compute the square of J. ___*/ - if jj>H then !=1 /*indicates skip top part if j > √ H */ - do m=jj to H by j+j; call . m; end /* [↑] strike odd multiples ¬ prime */ - end /*j*/ /* ─── */ +-- 12 Apr 2025 +include Settings -say; say right(#, w+20) 'prime's(#) "found up to and including " H -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────────────*/ -.: parse arg n; b=n%cw; r=n//cw+1;_=x2b(c2x(@.b));@.b=x2c(b2x(left(_,r-1)'1'substr(_,r+1)));return -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ -th: procedure; parse arg x; x=abs(x); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) +call Time('r') +say 'SIEVE OF ERATOSTHENES' +say version +say +call GetBasic 200 +call ShowPrimes 200 +call GetPrimes 200 +call ShowPrimes 200 +say Format(Time('e'),,3) 'seconds'; say +exit + +GetBasic: +procedure expose prim. +arg xx +say 'Basic sieve up to' xx'...' +call Basic xx +say prim.0 'found' +say +return + +Basic: +procedure expose prim. work. +arg xx +work. = 1 +do i = 2 while i*i <= xx + if work.i then do + do j = i*i by i to xx + work.j = 0 + end + end +end +zz = 0 +do i = 2 to xx + if work.i then do + zz = zz+1; prim.zz = i + end +end +prim.0 = zz +return zz + +GetPrimes: +procedure expose prim. flag. +arg xx +say 'Wheeled sieve up to' xx'...' +call Primes xx +say prim.0 'found' +say +return + +ShowPrimes: +procedure expose prim. +arg xx +say 'Primes up to' xx +do i = 1 to prim.0 + call Charout ,right(prim.i,4) + if i//10 = 0 then + say +end +say +say +return + +include Sequences +include Functions +include Abend diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx deleted file mode 100644 index 4e18e68268..0000000000 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx +++ /dev/null @@ -1,16 +0,0 @@ -/*REXX pgm generates and displays primes via a wheeled sieve of Eratosthenes algorithm. */ -parse arg H .; if H=='' | H=="," then H= 200 /*obtain the optional argument from CL.*/ -w= length(H); @prime= right('prime', 20) /*w: is used for aligning the output. */ -if 2<=H then say @prime right(1, w) " ───► " right(2, w) -#= 2<=H /*the number of primes found (so far).*/ -@.=. /*assume all the numbers are prime. */ -!=0; do j=3 by 2 for (H-2)%2 /*the odd integers up to H inclusive.*/ - if @.j=='' then iterate /*Is composite? Then skip this number.*/ - #= # + 1 /*bump the prime number counter. */ - say @prime right(#,w) " ───► " right(j,w) /*display the prime to the terminal. */ - if ! then iterate /*skip the top part of loop? ___ */ - if j*j>H then !=1 /*indicate skip top part if J > √ H */ - do m=j*j to H by j+j; @.m=; end /*strike odd multiples as not prime. */ - end /*j*/ /* ─── */ -say /*stick a fork in it, we're all done. */ -say right(#, 1 + w + length(@prime) ) 'primes found up to and including ' H diff --git a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx deleted file mode 100644 index a232b3bdbf..0000000000 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-4.rexx +++ /dev/null @@ -1,29 +0,0 @@ -/*REXX program generates primes via sieve of Eratosthenes algorithm. -* 21.07.2012 Walter Pachl derived from above Rexx version -* avoid symbols @ and # (not supported by ooRexx) -* avoid negations (think positive) -**********************************************************************/ - highest=200 /*define highest number to use. */ - is_prime.=1 /*assume all numbers are prime. */ - w=length(highest) /*width of the biggest number, */ - /* it's used for aligned output.*/ - Do j=3 To highest By 2, /*strike multiples of odd ints. */ - While j*j<=highest /* up to sqrt(highest) */ - If is_prime.j Then Do - Do jm=j*3 To highest By j+j /*start with next odd mult. of J */ - is_prime.jm=0 /*mark odd mult. of J not prime. */ - End - End - End - np=0 /*number of primes shown */ - Call tell 2 - Do n=3 To highest By 2 /*list all the primes found. */ - If is_prime.n Then Do - Call tell n - End - End - Exit -tell: Parse Arg prime - np=np+1 - Say ' prime number' right(np,w) " --> " right(prime,w) - Return diff --git a/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy b/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy index fb9fb5a77d..2d9c1c665e 100644 --- a/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy +++ b/Task/Sieve-of-Pritchard/EasyLang/sieve-of-pritchard.easy @@ -1,4 +1,4 @@ -proc pritchard limit . primes[] . +proc pritchard limit &primes[] . len members[] limit members[1] = 1 steplength = 1 @@ -23,19 +23,13 @@ proc pritchard limit . primes[] . mcpy[] = members[] for w to nlimit if mcpy[w] = 1 - if np = 5 and w > prime - np = w - . + if np = 5 and w > prime : np = w n = prime * w - if n > nlimit - break 1 - . + if n > nlimit : break 1 members[n] = 0 . . - if np < prime - break 1 - . + if np < prime : break 1 primes[] &= prime if prime = 2 prime = 3 @@ -45,9 +39,7 @@ proc pritchard limit . primes[] . nlimit = lower (steplength * prime) limit . for i = 2 to len members[] - if members[i] = 1 - primes[] &= i - . + if members[i] = 1 : primes[] &= i . . pritchard 150 p[] diff --git a/Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx b/Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx new file mode 100644 index 0000000000..7c5434290f --- /dev/null +++ b/Task/Sieve-of-Pritchard/REXX/sieve-of-pritchard.rexx @@ -0,0 +1,95 @@ +-- 12 Apr 2025 +include Settings + +call Time('r') +say 'SIEVE OF PRITCHARD' +say version +say +call Pritchard 150,1 +call Pritchard 1e6,0 +call Eratosthenes 1e6 +exit + +Pritchard: +procedure +call Time('r') +arg xx,yy +say 'Primes up to' xx 'by Pritchard...' +memb. = 0; memb.1 = 1; mcpy. = 0; prim. = 0; nwpr. = 0 +nl = 2; nn = 0; pr = 2; rl = Sqrt(xx); sl = 1; ub = xx+1 +do while pr <= rl + if sl < xx then do + do w = 1 to ub + if memb.w then do + n = w+sl + do while n <= nl + memb.n = 1; n = n+sl + end + end + end + sl = nl + end + do i = 1 to ub + mcpy.i = memb.i + end + np = 5 + do i = 1 to ub + if mcpy.i then do + if np = 5 then + if i > pr then + np = i + n = pr*i + if n > xx then + leave i + memb.n = 0 + end + end + if np < pr then + leave + nn = nn+1 + prim.nn = pr + if pr = 2 then + pr = 3 + else + pr = np + nl = Min(sl*pr,xx) +end +nwpr. = 0 +do i = 2 to ub + if memb.i then + nwpr.i = i +end +nn = 0 +do i = 1 to 1000 + if prim.i > 0 then do + if yy then + call Charout ,prim.i' ' + nn = nn+1 + end +end +do i = 1 to ub + if nwpr.i > 0 then do + if yy then + call Charout ,i' ' + nn = nn+1 + end +end +if yy then + say +say nn 'found' +say Format(Time('e'),,3) 'seconds' +say +return nn + +Eratosthenes: +procedure +call Time('r') +arg xx +say 'Primes up to' xx 'by Eratosthenes...' +say Primes(xx) 'found' +say Format(Time('e'),,3) 'seconds' +return + +include Sequences +include Functions +include Abend diff --git a/Task/Simple-database/M2000-Interpreter/simple-database.m2000 b/Task/Simple-database/M2000-Interpreter/simple-database.m2000 index 83545002c0..e15cd7a54e 100644 --- a/Task/Simple-database/M2000-Interpreter/simple-database.m2000 +++ b/Task/Simple-database/M2000-Interpreter/simple-database.m2000 @@ -124,7 +124,7 @@ if ret=0 then beep: exit if not islet then try { open "tool.bat" for output as #f - print #f, {@}+appdir$+{m2000.exe data {%*}: dir %cd%:load tool + print #f, {@}+shortdir$(appdir$)+{m2000.exe data {%*}: dir %cd%:load tool } close #f } diff --git a/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy b/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy index ad6606a423..6be5d8dc64 100644 --- a/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy +++ b/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy @@ -3,25 +3,24 @@ subr home x = 50 y = 50 down = 0 - move x y . home # -proc forward n . . +proc forward n . + px = x + py = y x += cos deg * n y += sin deg * n if down = 1 - line x y - else - move x y + gline px py x y . - sleep 0.1 + sleep 0.05 . -proc turn a . . +proc turn a . deg -= a . # -proc house . . +proc house . turn 180 forward 45 turn 180 @@ -43,7 +42,7 @@ proc house . . . house # -proc bar a[] . . +proc bar a[] . turn 90 forward 30 turn -90 diff --git a/Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 b/Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 new file mode 100644 index 0000000000..54894fe000 --- /dev/null +++ b/Task/Simple-turtle-graphics/M2000-Interpreter/simple-turtle-graphics.m2000 @@ -0,0 +1,69 @@ +Module TurtleGraphics { + cls 15,0 + pen 0 + single penangle=pi + boolean pendraw=true + hlen=min.data(scale.x, scale.y)/4 + move scale.x/4, scale.y/2 + house(hlen) + penup() + forward(hlen) + pendown() + d=(50, 33, 200, 130, 50) + items=len(d) + dspan=d#max() + ratio=scale.y/4/dspan + ditem=each(d) + while ditem + barvalue(scale.x/4, scale.y/3 ,items, ditem^, array(ditem)/dspan) + end while + + sub house(n) + for i=1 to 3 + right(120) + forward(n) + next + right(90) + bar(n, n) + right(90) + end sub + sub bar(w, h) + local i + for i=1 to 2 + right(90) + forward(h) + right(90) + forward(w) + next + end sub + sub barvalue(maxW, maxH, bars, barno, valratio) + local bW=maxW/bars + forward(bw) + bar(bw, -maxH*valratio) + end sub + // Turtle Minimum Pack + // need: + // single penangle=pi + // boolean pendraw=true + // + sub penup() + pendraw=false + end sub + sub pendown() + pendraw=true + end sub + sub forward(distance) + if pendraw then + draw angle penangle, distance + else + step angle penangle, distance + end if + end sub + sub backward(distance) + forward(-distance) + end sub + sub right(angle) + penangle-=angle/180*pi + end sub +} +TurtleGraphics diff --git a/Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku b/Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku new file mode 100644 index 0000000000..ad265e38df --- /dev/null +++ b/Task/Simple-turtle-graphics/Raku/simple-turtle-graphics.raku @@ -0,0 +1,54 @@ +# 20250303 Raku programming solution + +use Cairo; + +sub house(Cairo::Context $cr, $x, $y, $size) { + $cr.save; + $cr.rgb(1.0, 1.0, 1.0); + + $cr.rectangle($x, $y, $size, $size); + $cr.stroke; + + $cr.move_to($x + $size / 2, $y - $size / 2); + $cr.line_to($x, $y); + $cr.line_to($x + $size, $y); + $cr.close_path; + $cr.stroke; + + $cr.restore; +} + +sub barchart(Cairo::Context $cr, @data, $x is copy, $y, $size) { + $cr.save; + $cr.rgb(1.0, 1.0, 1.0); + + my $maxdata = @data.max || 1; + my $bar-width = $size / (@data.elems || 1); + my $bar-spacing = $bar-width * 0.1; + + for @data -> $n { + my $bar-height = ($n / $maxdata) * $size; + $cr.rectangle($x, $y - $bar-height, $bar-width - $bar-spacing, $bar-height); + $cr.stroke; + $x += $bar-width; + } + + $cr.restore; +} + +sub testturtle($width = 400, $height = 600) { + my $image = Cairo::Image.create(Cairo::FORMAT_ARGB32, $width, $height); + my $cr = Cairo::Context.new($image); + + $cr.rgb(0.0, 0.0, 0.0); + $cr.paint; + + $cr.line_width = 2.0; + + barchart($cr, [15, 10, 50, 35, 20], $width * 0.6, $height, $width / 3); + house($cr, $width / 4, $height / 3, $width / 3); + + $image.write_png('turtle-raku.png'); +} + +testturtle(); diff --git a/Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic b/Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic new file mode 100644 index 0000000000..1ffc77abd0 --- /dev/null +++ b/Task/Simulate-input-Keyboard/FreeBASIC/simulate-input-keyboard.basic @@ -0,0 +1,40 @@ +#include once "windows.bi" + +Dim ki(0 To 7) As INPUT_ + +' A +ki(0).type = INPUT_KEYBOARD +ki(0).ki.wVk = Asc("A") +ki(0).ki.dwFlags = 0 +ki(1).type = INPUT_KEYBOARD +ki(1).ki.wVk = Asc("A") +ki(1).ki.dwFlags = KEYEVENTF_KEYUP + +' B +ki(2).type = INPUT_KEYBOARD +ki(2).ki.wVk = Asc("B") +ki(2).ki.dwFlags = 0 +ki(3).type = INPUT_KEYBOARD +ki(3).ki.wVk = Asc("B") +ki(3).ki.dwFlags = KEYEVENTF_KEYUP + +' C +ki(4).type = INPUT_KEYBOARD +ki(4).ki.wVk = Asc("C") +ki(4).ki.dwFlags = 0 +ki(5).type = INPUT_KEYBOARD +ki(5).ki.wVk = Asc("C") +ki(5).ki.dwFlags = KEYEVENTF_KEYUP + +' ENTER (VK_RETURN = &HD) +ki(6).type = INPUT_KEYBOARD +ki(6).ki.wVk = VK_RETURN +ki(6).ki.dwFlags = 0 +ki(7).type = INPUT_KEYBOARD +ki(7).ki.wVk = VK_RETURN +ki(7).ki.dwFlags = KEYEVENTF_KEYUP + +Print "Make the target window active. Sending keys in 3 seconds..." +Sleep 3000 + +SendInput(Ubound(ki), @ki(0), Len(INPUT_)) diff --git a/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg b/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg index aba0b1030b..3c6aff36d7 100644 --- a/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg +++ b/Task/Sisyphus-sequence/ALGOL-68/sisyphus-sequence.alg @@ -1,17 +1,9 @@ BEGIN # generate elements of the Sysiphus Sequence: see OEIS A350877 # - # returns the largest element in a # - OP MAX = ( []INT a )INT: - IF LWB a >UPB a THEN 0 - ELSE - INT result := a[ LWB a ]; - FOR i FROM LWB a + 1 TO UPB a DO - IF result < a[ i ] THEN result := a[ i ] FI - OD; - result - FI # MAX # ; + PR read "rows.incl.a68" PR # include row (array) utilities # + # sieve the primes # - INT sieve max = 1 000 000 000; ### CHANGE TO E.G.: 100 000 000 FOR ALGOL 68G ### + INT sieve max = 100 000 000; ### 10 000 000 for ALGOL 68 Genie version 3 # BOOL is odd := TRUE; [ sieve max ]BOOL sieve; FOR i TO UPB sieve DO sieve[ i ] := is odd; is odd := NOT is odd OD; sieve[ 1 ] := FALSE; diff --git a/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy b/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy index 27988008d1..befbb870ce 100644 --- a/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy +++ b/Task/Sisyphus-sequence/EasyLang/sisyphus-sequence.easy @@ -1,24 +1,20 @@ func isprim num . - if num mod 2 = 0 and num > 2 - return 0 - . + if num mod 2 = 0 and num > 2 : return 0 i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 . prim = 1 -proc nextprim . . +proc nextprim . repeat prim += 1 until isprim prim = 1 . . -numfmt 0 4 +numfmt 4 0 n = 1 write n for i = 2 to 100 @@ -29,7 +25,5 @@ for i = 2 to 100 n /= 2 . write n - if i mod 10 = 0 - print "" - . + if i mod 10 = 0 : print "" . diff --git a/Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math b/Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math new file mode 100644 index 0000000000..a56731f395 --- /dev/null +++ b/Task/Sisyphus-sequence/Mathematica/sisyphus-sequence.math @@ -0,0 +1,33 @@ +num = 1; +primepi = 1; +res = Table[ + If[EvenQ[num], + num /= 2; + , + num += Prime[primepi]; + primepi++; + ]; + num + , + {99} + ]; +PrependTo[res, 1]; +Partition[res, 10] // Grid + +Table[ + num = 1; + primepi = 1; + Do[ + If[EvenQ[num], + num /= 2; + , + num += Prime[primepi]; + primepi++; + ]; + , + {j} + ]; + {num, Prime[primepi - 1]} + , + {j, {999, 9999, 99999, 999999, 9999999, 99999999}} +] diff --git a/Task/Sleep/JavaScript/sleep-1.js b/Task/Sleep/JavaScript/sleep-1.js new file mode 100644 index 0000000000..87504243c2 --- /dev/null +++ b/Task/Sleep/JavaScript/sleep-1.js @@ -0,0 +1,11 @@ +function delay (ms) { + return new Promise((res) => setTimeout(res, ms)) +} + +void (async () => { + for (let i = 10; i > 0; --i) { + console.log(i) + await delay(1000) + } + console.log('Blast off!') +})() diff --git a/Task/Sleep/JavaScript/sleep-2.js b/Task/Sleep/JavaScript/sleep-2.js new file mode 100644 index 0000000000..50bf051403 --- /dev/null +++ b/Task/Sleep/JavaScript/sleep-2.js @@ -0,0 +1,14 @@ +function worker() { + const buf = new Int32Array(new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true }).buffer) + function sleep(ms) { + Atomics.wait(buf, 0, 0, ms) + } + + for (let i = 10; i > 0; --i) { + console.log(i) + sleep(1000) + } + console.log('Blast off!') +} + +new Worker(URL.createObjectURL(new Blob([`(${worker})()`]))) diff --git a/Task/Sleep/JavaScript/sleep-3.js b/Task/Sleep/JavaScript/sleep-3.js new file mode 100644 index 0000000000..405372a9b1 --- /dev/null +++ b/Task/Sleep/JavaScript/sleep-3.js @@ -0,0 +1,8 @@ +function sleepFuriously(ms) { + const start = Date.now() + while (Date.now() - start < ms); +} + +console.log('sleeping...') +sleepFuriously(1000) +console.log('wow, that was exhausting!') diff --git a/Task/Sleep/JavaScript/sleep.js b/Task/Sleep/JavaScript/sleep.js deleted file mode 100644 index 067888bdcb..0000000000 --- a/Task/Sleep/JavaScript/sleep.js +++ /dev/null @@ -1,9 +0,0 @@ - diff --git a/Task/Sleep/REXX/sleep-3.rexx b/Task/Sleep/REXX/sleep-3.rexx index 628dc3f7c8..7e4b63a3b0 100644 --- a/Task/Sleep/REXX/sleep-3.rexx +++ b/Task/Sleep/REXX/sleep-3.rexx @@ -1,4 +1,8 @@ -Main: +include Settings + +say 'SLEEP - 2 Mar 2025' +say version +say call Sleep 1 call Sleep 2 call Sleep 3 @@ -11,3 +15,5 @@ say time('l') 'Waiting for' s 'seconds...' 'timeout /t' s '/nobreak > nul' say time('l') 'Done!' return + +include Abend diff --git a/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx b/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx index 71aa99ccc1..9f7d6e9c4e 100644 --- a/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx +++ b/Task/Smarandache-prime-digital-sequence/REXX/smarandache-prime-digital-sequence.rexx @@ -1,30 +1,65 @@ -/*REXX program lists a sequence of SPDS (Smarandache prime-digital sequence) primes.*/ -parse arg n q /*get optional number of primes to find*/ -if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/ -if q='' then q= 100 1000 /* " " " " " " */ -say '═══listing the first' n "SPDS primes═══" -call spds n - do i=1 for words(q)+1; y=word(q, i); if y=='' | y=="," then iterate - say - say '═══listing the last of ' y "SPDS primes═══" - call spds -y - end /*i*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -spds: parse arg x 1 ox; x= abs(x) /*obtain the limit to be used for list.*/ - c= 0 /*C number of SPDS primes found so far*/ - #= 0 /*# number of primes found so far*/ - do j=1 by 2 while c0 then iterate j /*Digits ¬prime? Then skip this prime.*/ - c= c + 1 /*bump the number of SPDS primes found.*/ - if ox<0 then iterate /*don't display it, display the last #.*/ - say right(z, 21) /*maybe display this prime ──► terminal*/ - end /*j*/ /* [↑] only display N number of primes*/ - if ox<0 then say right(z, 21) /*display one (the last) SPDS prime. */ - return +-- 12 Apr 2025 +include Settings +numeric digits 12 + +call Time('r') +say 'SMARANDACHE PRIME-DIGITAL SEQUENCE' +say version +say +call Task1 +call Task2 +say Format(Time('e'),,3) 'seconds' +exit + +Task1: +procedure expose prim. +say 'First 25 SPDS primes...' +n = 0 +do i = 1 until n = 25 + if PrimeDigits(i) then do + if Prime(i) then do + n = n+1 + call Charout ,Right(i,9) + if n //10 = 0 then + say + end + end +end +say +say +return + +Task2: +procedure expose prim. +say 'Higher in the sequence...' +n = 4; t = 0 +do i = 23 by 2 until n = 23e3 + if Pos(Right(i,1),37) > 0 then do + if PrimeDigits(i) then do + t = t+1 + if Prime(i) then do + n = n+1 + if n//1000 = 0 then do + say n'th is' i + end + end + end + end +end +say t 'prime tests performed' +say +return + +PrimeDigits: +procedure +arg xx +a = Verify(xx,2357) +if a > 0 then + return 0 +else + return 1 + +include Numbers +include Sequences +include Functions +include Abend diff --git a/Task/Snake/EasyLang/snake.easy b/Task/Snake/EasyLang/snake.easy index 159718d50e..79fe0072b8 100644 --- a/Task/Snake/EasyLang/snake.easy +++ b/Task/Snake/EasyLang/snake.easy @@ -10,18 +10,15 @@ subr start dir = random 4 timer 0 . -background 242 -move 30 70 -clear -color 997 -text "SNAKE" -textsize 5 -move 6 40 -text "Keys or mouse for controlling" -move 6 30 -text "Space or click to to start" +gbackground 242 +gclear +gcolor 997 +gtext 30 70 "SNAKE" +gtextsize 5 +gtext 6 40 "Keys or mouse for controlling" +gtext 6 30 "Space or click to start" # -on key +on key_down if game = 0 and keybkey = " " start return @@ -59,16 +56,19 @@ on mouse_down . . . +proc over . + gcolor 997 + gtext 10 10 "Space or click for new game" + game = 2 + timer 1 +. on timer - clear - color 997 - move 2 95 - text "Score: " & 10 * len sx[] - 50 - color 966 - move rx ry - circle 1.5 - # - sx = sx[1] ; sy = sy[1] + if game = 2 + game = 0 + return + . + sx = sx[1] + sy = sy[1] if dir = 1 sy += 5 elif dir = 2 @@ -79,45 +79,44 @@ on timer sx -= 5 . if sx < 0 or sx > 100 or sy < 0 or sy > 100 - game = 0 + over + return . - color 494 for i = len sx[] downto 2 if sx = sx[i] and sy = sy[i] - game = 0 + over + return . + . + gclear + gcolor 997 + gtext 2 95 "Score: " & 10 * len sx[] - 50 + gcolor 966 + gcircle rx ry 1.5 + # + gcolor 494 + for i = len sx[] downto 2 sx[i] = sx[i - 1] sy[i] = sy[i - 1] if sx[i] > 0 - move sx[i] sy[i] - circle 2.5 + gcircle sx[i] sy[i] 2.5 . . - move sx sy - circle 2.5 - color 000 + gcircle sx sy 2.5 + gcolor 000 if dir = 2 or dir = 4 - move sx sy + 1 - circle 0.5 - move sx sy - 1 - circle 0.5 + gcircle sx sy + 1 0.5 + gcircle sx sy - 1 0.5 else - move sx + 1 sy - circle 0.5 - move sx - 1 sy - circle 0.5 + gcircle sx + 1 sy 0.5 + gcircle sx - 1 sy 0.5 . if sx = rx and sy = ry len sx[] len sx[] + 3 len sy[] len sy[] + 3 fruit . - sx[1] = sx ; sy[1] = sy - if game = 1 - timer 0.15 - else - color 997 - move 10 10 - text "Space or click new game" - . + sx[1] = sx + sy[1] = sy + timer 0.15 . diff --git a/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy b/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy index faab3d3d1e..af920153fe 100644 --- a/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy +++ b/Task/Solve-a-Hidato-puzzle/EasyLang/solve-a-hidato-puzzle.easy @@ -1,28 +1,20 @@ moves[][] = [ [ -1 -1 ] [ -1 0 ] [ -1 1 ] [ 0 -1 ] [ 0 1 ] [ 1 -1 ] [ 1 0 ] [ 1 1 ] ] global brd[][] maxr maxc maxcnt ancor . func solve r c cnt . - if cnt - ancor > 13 - return 0 - . - if cnt > maxcnt - return 1 - . + if cnt - ancor > 13 : return 0 + if cnt > maxcnt : return 1 for m = 1 to len moves[][] rn = r + moves[m][1] cn = c + moves[m][2] if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc if brd[rn][cn] = 0 brd[rn][cn] = cnt - if solve rn cn (cnt + 1) = 1 - return 1 - . + if solve rn cn (cnt + 1) = 1 : return 1 brd[rn][cn] = 0 elif brd[rn][cn] = cnt oldanc = ancor ancor = cnt - if solve rn cn (cnt + 1) = 1 - return 1 - . + if solve rn cn (cnt + 1) = 1 : return 1 ancor = oldanc . . @@ -39,7 +31,7 @@ brd$ = " . . . . __ 7 __ __ . . . . . . 5 __ " -proc prepare . r0 c0 . +proc prepare &r0 &c0 . brd$[] = strsplit brd$ "\n" maxc = len brd$[2] / 3 maxr = len brd$[] - 2 @@ -64,8 +56,8 @@ proc prepare . r0 c0 . . ancor = 1 . -proc printbrd . . - numfmt 0 3 +proc printbrd . + numfmt 3 0 for r to maxr for c to maxc if brd[r][c] = -1 diff --git a/Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js b/Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js new file mode 100644 index 0000000000..afcb0dc362 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/JavaScript/solve-a-hidato-puzzle.js @@ -0,0 +1,113 @@ +let board = []; +let start = []; +let given = []; + +function setup(input) { + /* This task is not about input validation, so + we're going to trust the input to be valid */ + const puzzle = input.map(line => line.split(/\s+/)); + const nCols = puzzle[0].length; + const nRows = puzzle.length; + let list = new Array(nRows * nCols); + + board = Array(nRows + 2).fill().map(() => + Array(nCols + 2).fill(-1) + ); + + for (let r = 0; r < nRows; r++) { + const row = puzzle[r]; + for (let c = 0; c < nCols; c++) { + const cell = row[c]; + switch (cell) { + case "_": + board[r + 1][c + 1] = 0; + break; + case ".": + break; + default: + const val = parseInt(cell, 10); + board[r + 1][c + 1] = val; + list.push(val); + if (val === 1) { + start = [r + 1, c + 1]; + } + break; + } + } + } + + list.sort((a, b) => a - b); + given = [...list]; +} + +function solve(r, c, n, next) { + if (n > given[given.length - 1]) { + return true; + } + + const back = board[r][c]; + if (back !== 0 && back !== n) { + return false; + } + + if (back === 0 && given[next] === n) { + return false; + } + + if (back === n) { + next++; + } + + board[r][c] = n; + for (let i = -1; i < 2; i++) { + for (let j = -1; j < 2; j++) { + if (solve(r + i, c + j, n + 1, next)) { + return true; + } + } + } + + board[r][c] = back; + return false; +} + +function printBoard() { + for (const row of board) { + let rowStr = ''; + for (const c of row) { + switch (true) { + case c === -1: + rowStr += ' . '; + break; + case c > 0: + rowStr += c.toString().padStart(2) + ' '; + break; + default: + rowStr += '__ '; + break; + } + } + console.log(rowStr); + } +} + +function main() { + const input = [ + "_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _" + ]; + + setup(input); + printBoard(); + console.log("\nFound:"); + solve(start[0], start[1], 1, 0); + printBoard(); +} + +main(); diff --git a/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy b/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy index 9c7df10abd..268a1b3472 100644 --- a/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy +++ b/Task/Solve-a-Holy-Knights-tour/EasyLang/solve-a-holy-knights-tour.easy @@ -11,23 +11,19 @@ brd$ = " moves[][] = [ [ -2 -1 ] [ -2 1 ] [ -1 -2 ] [ -1 2 ] [ 1 -2 ] [ 1 2 ] [ 2 -1 ] [ 2 1 ] ] global brd[][] maxr maxc maxcnt . func solve r c cnt . - if cnt > maxcnt - return 1 - . + if cnt > maxcnt : return 1 for m = 1 to len moves[][] rn = r + moves[m][1] cn = c + moves[m][2] if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc and brd[rn][cn] = 0 brd[rn][cn] = cnt - if solve rn cn (cnt + 1) = 1 - return 1 - . + if solve rn cn (cnt + 1) = 1 : return 1 brd[rn][cn] = 0 . . return 0 . -proc prepare . r0 c0 . +proc prepare &r0 &c0 . brd$[] = strsplit brd$ "\n" maxc = len brd$[2] maxr = len brd$[] - 2 @@ -45,8 +41,8 @@ proc prepare . r0 c0 . . . . -proc printbrd . . - numfmt 0 3 +proc printbrd . + numfmt 3 0 for r to maxr for c to maxc if brd[r][c] = -1 diff --git a/Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs b/Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs new file mode 100644 index 0000000000..2533753df8 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Rust/solve-a-holy-knights-tour.rs @@ -0,0 +1,188 @@ +use std::collections::HashSet; +use std::iter::FromIterator; +use std::str::FromStr; + +#[derive(Clone, Copy)] +struct Node { + val: isize, + neighbors: u8, +} + +struct NSolver { + dx: [isize; 8], + dy: [isize; 8], + wid: usize, + hei: usize, + max: usize, + arr: Vec, +} + +impl NSolver { + fn new() -> Self { + let dx = [-1, -1, 1, 1, -2, -2, 2, 2]; + let dy = [-2, 2, -2, 2, -1, 1, -1, 1]; + + Self { + dx, + dy, + wid: 0, + hei: 0, + max: 0, + arr: vec![], + } + } + + fn solve(&mut self, puzz: &mut Vec, max_wid: usize) { + if puzz.is_empty() { + return; + } + + self.wid = max_wid; + self.hei = puzz.len() / self.wid; + let len = self.wid * self.hei; + self.max = len; + self.arr = vec![Node { val: 0, neighbors: 0 }; len]; + + let mut c = 0; + let mut empty_coords = HashSet::new(); + + for s in puzz.iter() { + if s == "*" { + self.max -= 1; + self.arr[c].val = -1; + c += 1; + continue; + } + + if s == "." { + empty_coords.insert(c); + c += 1; + continue; + } + + if let Ok(val) = isize::from_str(s) { + self.arr[c].val = val; + c += 1; + } + } + + self.solve_it(); + + c = 0; + for s in puzz.iter_mut() { + if s == "." { + let val = self.arr[c].val; + *s = format!("{:02}", val); + } + c += 1; + } + } + + fn solve_it(&mut self) { + let (x, y, z) = self.find_start(); + if z == 99999 { + println!("Can't find start point!"); + return; + } + + self.search(x, y, z + 1); + } + + fn find_start(&self) -> (usize, usize, isize) { + let mut x = 0; + let mut y = 0; + let mut z = 99999; + + for b in 0..self.hei { + for a in 0..self.wid { + let idx = a + b * self.wid; + if self.arr[idx].val > 0 && self.arr[idx].val < z { + x = a; + y = b; + z = self.arr[idx].val; + } + } + } + + (x, y, z) + } + + fn search(&mut self, x: usize, y: usize, w: isize) -> bool { + if w > self.max as isize { + return true; + } + + let idx = x + y * self.wid; + self.arr[idx].neighbors = self.get_neighbors(x, y); + + for d in 0..8 { + if (self.arr[idx].neighbors & (1 << d)) != 0 { + let a = (x as isize + self.dx[d]) as usize; + let b = (y as isize + self.dy[d]) as usize; + let n_idx = a + b * self.wid; + + if self.arr[n_idx].val == 0 { + self.arr[n_idx].val = w; + if self.search(a, b, w + 1) { + return true; + } + self.arr[n_idx].val = 0; + } + } + } + + false + } + + fn get_neighbors(&self, x: usize, y: usize) -> u8 { + let mut c = 0u8; + + for i in 0..8 { + let a = x as isize + self.dx[i]; + let b = y as isize + self.dy[i]; + + if a >= 0 && b >= 0 { + let a = a as usize; + let b = b as usize; + if a < self.wid && b < self.hei { + if self.arr[a + b * self.wid].val > -1 { + c |= 1 << i; + } + } + } + } + + c + } +} + +fn main() { + // Example input (comment/uncomment for different puzzles) + let p = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; + let wid = 13; + + let puzz: Vec = p.split_whitespace().map(|s| s.to_string()).collect(); + + let mut puzz_vec = puzz.clone(); + + let mut solver = NSolver::new(); + solver.solve(&mut puzz_vec, wid); + + let mut c = 0; + for item in puzz_vec.iter() { + if item == "*" || item == "." { + print!(" "); + } else { + print!("{:2} ", item); + } + + c += 1; + if c >= wid { + println!(); + c = 0; + } + } + + println!("\nPress any key to exit..."); + let _ = std::io::stdin().read_line(&mut String::new()); +} diff --git a/Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig b/Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig new file mode 100644 index 0000000000..cf7ec96c84 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Zig/solve-a-holy-knights-tour.zig @@ -0,0 +1,208 @@ +const std = @import("std"); + +const Node = struct { + val: isize, + neighbors: u8, +}; + +const NSolver = struct { + dx: [8]isize = .{-1, -1, 1, 1, -2, -2, 2, 2}, + dy: [8]isize = .{-2, 2, -2, 2, -1, 1, -1, 1}, + wid: usize, + hei: usize, + max: usize, + arr: []Node, + allocator: std.mem.Allocator, + + pub fn init(allocator: std.mem.Allocator) NSolver { + return NSolver{ + .wid = 0, + .hei = 0, + .max = 0, + .arr = &[_]Node{}, // will be overwritten in `solve` + .allocator = allocator, + }; + } + + // The key problem was here - tokens was being passed as a pointer to a split iterator + // but the function expected [][]const u8 + pub fn solve(self: *NSolver, puzz: []const u8, max_wid: usize) ![][]const u8 { + // Split the input string into tokens + var tokens = std.ArrayList([]const u8).init(self.allocator); + defer tokens.deinit(); + + var iter = std.mem.splitSequence(u8, puzz, " "); + while (iter.next()) |tok| { + if (tok.len == 0) continue; // Skip empty tokens + try tokens.append(tok); + } + + if (tokens.items.len == 0) return &[_][]const u8{}; + + self.wid = max_wid; + self.hei = tokens.items.len / max_wid; + self.max = tokens.items.len; + const len = self.wid * self.hei; + + // allocate and zero‐initialize the board + self.arr = try self.allocator.alloc(Node, len); + for (self.arr) |*n| { + n.* = Node{ .val = 0, .neighbors = 0 }; + } + + // parse the input tokens into our board + var c: usize = 0; + for (tokens.items) |tok| { + if (std.mem.eql(u8, tok, "*")) { + self.max -= 1; + self.arr[c].val = -1; + } else if (std.mem.eql(u8, tok, ".")) { + // leave . as 0 for "empty" + self.arr[c].val = 0; + } else { + // parse a pre‐filled number + const v = try std.fmt.parseInt(isize, tok, 10); + self.arr[c].val = v; + } + c += 1; + } + + // run the backtracking search + self.solveIt(); + + // Create result array to hold the modified tokens + var result = try self.allocator.alloc([]const u8, tokens.items.len); + + // write back any "." slots with zero‐padded numbers + c = 0; + for (tokens.items, 0..) |tok, i| { + if (std.mem.eql(u8, tok, ".")) { + const v = self.arr[c].val; + // format as two digits, zero-pad + result[i] = try std.fmt.allocPrint(self.allocator, "{d:0>2}", .{v}); + } else { + // For non-modified tokens, just copy the reference + result[i] = tok; + } + c += 1; + } + + return result; + } + + fn solveIt(self: *NSolver) void { + const start = self.findStart(); + if (start.z == @as(isize, @intCast(std.math.maxInt(isize)))) { + std.debug.print("Can't find start point!\n", .{}); + return; + } + _ = self.search(start.x, start.y, start.z + 1); + } + + fn findStart(self: *NSolver) struct { x: usize, y: usize, z: isize } { + var best_x: usize = 0; + var best_y: usize = 0; + var best_z: isize = std.math.maxInt(isize); + + // The original code had a bug here - trying to iterate over the height and width directly + var b: usize = 0; + while (b < self.hei) : (b += 1) { + var a: usize = 0; + while (a < self.wid) : (a += 1) { + const idx = a + b * self.wid; + const v = self.arr[idx].val; + if (v > 0 and v < best_z) { + best_x = a; + best_y = b; + best_z = v; + } + } + } + + return .{ .x = best_x, .y = best_y, .z = best_z }; + } + + fn search(self: *NSolver, x: usize, y: usize, w: isize) bool { + if (w > @as(isize, @intCast(self.max))) return true; + + const idx = x + y * self.wid; + self.arr[idx].neighbors = self.getNeighbors(x, y); + + // The original code had a bug here - trying to iterate over dx directly + for (0..self.dx.len) |d| { + if ((self.arr[idx].neighbors & (@as(u8, 1) << @as(u3, @intCast(d)))) != 0) { + const a_s = @as(isize, @intCast(x)) + self.dx[d]; + const b_s = @as(isize, @intCast(y)) + self.dy[d]; + if (a_s >= 0 and b_s >= 0) { + const a = @as(usize, @intCast(a_s)); + const b = @as(usize, @intCast(b_s)); + if (a < self.wid and b < self.hei) { + const n_idx = a + b * self.wid; + if (self.arr[n_idx].val == 0) { + self.arr[n_idx].val = w; + if (self.search(a, b, w + 1)) return true; + self.arr[n_idx].val = 0; + } + } + } + } + } + return false; + } + + fn getNeighbors(self: *NSolver, x: usize, y: usize) u8 { + var mask: u8 = 0; + for (0..self.dx.len) |i| { + const a_s = @as(isize, @intCast(x)) + self.dx[i]; + const b_s = @as(isize, @intCast(y)) + self.dy[i]; + if (a_s >= 0 and b_s >= 0) { + const a = @as(usize, @intCast(a_s)); + const b = @as(usize, @intCast(b_s)); + if (a < self.wid and b < self.hei) { + if (self.arr[a + b * self.wid].val > -1) { + mask |= ( @as(u8, 1) << @as(u3, @intCast(i))); + } + } + } + } + return mask; + } +}; + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + const allocator = std.heap.page_allocator; + + // Example puzzle (same as your Rust example) + const p_str = "* * * * * 1 * . * * * * * * * * * * . * . * * * * * * * * * . . . . . * * * * * * * * * . . . * * * * * * * . * * . * . * * . * * . . . . . * * * . . . . . * * . . * * * * * . . * * . . . . . * * * . . . . . * * . * * . * . * * . * * * * * * * . . . * * * * * * * * * . . . . . * * * * * * * * * . * . * * * * * * * * * * . * . * * * * * "; + const wid: usize = 13; + + // solve + var solver = NSolver.init(allocator); + const result = try solver.solve(p_str, wid); + defer allocator.free(solver.arr); + + // Print the solved board + var count: usize = 0; + for (result) |tok| { + if (std.mem.eql(u8, tok, "*")) { + try stdout.print(" ", .{}); + } else { + try stdout.print("{s} ", .{tok}); + } + count += 1; + if (count == wid) { + try stdout.print("\n", .{}); + count = 0; + } + } + try stdout.print("\n", .{}); + + // Free allocated memory for any new tokens + for (result) |tok| { + if (!std.mem.eql(u8, tok, "*") and !std.mem.eql(u8, tok, ".") and !std.mem.eql(u8, tok, "1")) { + allocator.free(tok); + } + } + allocator.free(result); +} diff --git a/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy b/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy index 692a5c4809..0054bef045 100644 --- a/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy +++ b/Task/Solve-a-Hopido-puzzle/EasyLang/solve-a-hopido-puzzle.easy @@ -9,23 +9,19 @@ brd$ = " moves[][] = [ [ -3 0 ] [ 0 3 ] [ 3 0 ] [ 0 -3 ] [ 2 2 ] [ 2 -2 ] [ -2 2 ] [ -2 -2 ] ] global brd[][] maxr maxc maxcnt . func solve r c cnt . - if cnt > maxcnt - return 1 - . + if cnt > maxcnt : return 1 for m = 1 to len moves[][] rn = r + moves[m][1] cn = c + moves[m][2] if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc and brd[rn][cn] = 0 brd[rn][cn] = cnt - if solve rn cn (cnt + 1) = 1 - return 1 - . + if solve rn cn (cnt + 1) = 1 : return 1 brd[rn][cn] = 0 . . return 0 . -proc prepare . r0 c0 . +proc prepare &r0 &c0 . brd$[] = strsplit brd$ "\n" maxc = len brd$[2] maxr = len brd$[] - 2 @@ -42,8 +38,8 @@ proc prepare . r0 c0 . . . . -proc printbrd . . - numfmt 0 3 +proc printbrd . + numfmt 3 0 for r to maxr for c to maxc if brd[r][c] = -1 diff --git a/Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs b/Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs new file mode 100644 index 0000000000..0d2536a530 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Rust/solve-a-hopido-puzzle.rs @@ -0,0 +1,258 @@ +use std::io::{self, Write}; // Import Write trait for flush + +const DX: [i32; 8] = [-2, -2, 2, 2, -3, 3, 0, 0]; +const DY: [i32; 8] = [-2, 2, -2, 2, 0, 0, -3, 3]; + +// Equivalent to C++ 'node' struct +#[derive(Clone, Copy, Debug, Default)] +struct Node { + val: i32, // -1 for obstacle, 0 for empty, >0 for number + neighbors: u8, // Bitmask of valid moves (indices into DX/DY) +} + +// Equivalent to C++ 'nSolver' class +struct NSolver { + wid: usize, + hei: usize, + max_val: i32, // The highest number to place (number of non-obstacle cells) + arr: Vec, +} + +impl NSolver { + // Main function to set up and run the solver + // Modifies the input 'puzz' vector in place + pub fn solve_puzzle(puzz: &mut Vec, max_wid: usize) { + if puzz.is_empty() { + return; + } + + let wid = max_wid; + if wid == 0 { + eprintln!("Error: Width cannot be zero."); + return; + } + let hei = puzz.len() / wid; + if hei * wid != puzz.len() { + eprintln!("Error: Puzzle size ({}) must be a multiple of width ({}).", puzz.len(), wid); + return; + } + + let len = wid * hei; + + // --- START FIX --- + // Create a record of which cells were originally "." BEFORE creating the solver/modifying arr + let was_originally_dot: Vec = puzz.iter().map(|s| s == ".").collect(); + // --- END FIX --- + + let mut arr = vec![Node::default(); len]; + let mut max_val = 0; // Count non-obstacle cells + + // Initialize 'arr' based on the initial 'puzz' state + for (c, item) in puzz.iter().enumerate() { + if c >= len { break; } // Should not happen with the size check above, but safe + + // Match the C++ logic: '*' is obstacle (-1), others are parsed or default to 0. + // Count non-obstacles towards the max value to be filled. + if item == "*" { + arr[c].val = -1; + } else { + // atoi returns 0 for non-numeric strings like ".". + arr[c].val = item.parse::().unwrap_or(0); + max_val += 1; + } + } + + // Check if there's anything to solve + if max_val == 0 { + println!("\nNo valid cells to fill (all obstacles?)."); + return; // Nothing to solve + } + + let mut solver = NSolver { + wid, + hei, + max_val, + arr, + }; + + // Find start and solve + solver.solve_it(); + + // Update the original puzz vector with results + // Now use the 'was_originally_dot' vector for the check + for (c, item) in puzz.iter_mut().enumerate() { + if c >= solver.arr.len() { break; } // Safety break + + // --- Use the pre-calculated boolean --- + if was_originally_dot[c] { + let node_val = solver.arr[c].val; + // Only update if the solver actually put a positive number there? + // C++ seems to update with whatever is in arr[c] (could be 0 if not reached). + // Let's stick to that behavior. + if node_val >= 0 { // Avoid writing "-1" into a "." cell + *item = node_val.to_string(); + } else { + // If for some reason the solver put -1 here, leave it as "."? + // This case seems unlikely if logic is correct. + eprintln!("Warning: Obstacle value (-1) found at index {} which was originally '.'", c); + *item = ".".to_string(); // Keep it as dot? Or maybe solver.arr[c].val.to_string()? + } + + } + // Cells that were not originally "." remain unchanged. + } + } + + // Internal function to orchestrate the solving process + + fn solve_it(&mut self) { + match self.find_start() { + Some((x, y, start_val)) => { + if !self.search(x, y, start_val + 1) { + println!("\nSearch failed to find a complete path from start ({}, {}). Board may be partially filled.", x, y); + } + // else: Search succeeded, board is filled (or should be) + } + None => { + // Check if already solved (no zeros found) or impossible + let has_zero = self.arr.iter().any(|node| node.val == 0); + if !has_zero && self.max_val > 0 { + // This case could happen if the input already contained a partial or full solution + // and find_start requires a 0 to begin. + println!("\nPuzzle seems pre-filled or already solved. No empty cell (0) found to start search."); + } else if self.max_val > 0 { + // This means find_start iterated through all cells and none were 0. + // Could happen if the board is all obstacles, or already fully numbered. + println!("\nCan't find start point (an empty cell with value 0)! Check input puzzle."); + } + // The max_val == 0 case is handled earlier in solve_puzzle + } + } + } + + // Find the first empty cell (value 0), set it to 1, and return its info + fn find_start(&mut self) -> Option<(usize, usize, i32)> { + for y in 0..self.hei { + for x in 0..self.wid { + let index = x + y * self.wid; + // Ensure we don't try to access out of bounds if arr size is wrong + if index < self.arr.len() && self.arr[index].val == 0 { + self.arr[index].val = 1; // Set start value to 1 + return Some((x, y, 1)); // Return coords and the value assigned (1) + } + } + } + None // No cell with value 0 found + } + + // Recursive backtracking search function + fn search(&mut self, x: usize, y: usize, w: i32) -> bool { + if w > self.max_val { + return true; // Successfully placed all numbers + } + + let current_index = x + y * self.wid; + // Calculate and store neighbors for the current node + self.arr[current_index].neighbors = self.get_neighbors(x, y); + let neighbors_mask = self.arr[current_index].neighbors; + + for d in 0..8 { // Iterate through 8 possible moves + if (neighbors_mask & (1 << d)) != 0 { // Check if the d-th neighbor is valid + let next_x_i32 = (x as i32) + DX[d]; + let next_y_i32 = (y as i32) + DY[d]; + + // Bounds check (redundant if get_neighbors is correct, but safe) + if next_x_i32 >= 0 && next_x_i32 < self.wid as i32 && + next_y_i32 >= 0 && next_y_i32 < self.hei as i32 + { + let next_x = next_x_i32 as usize; + let next_y = next_y_i32 as usize; + let next_index = next_x + next_y * self.wid; + + // Check bounds on arr access too + if next_index < self.arr.len() && self.arr[next_index].val == 0 { + self.arr[next_index].val = w; // Place the next number + + if self.search(next_x, next_y, w + 1) { // Recurse + return true; // Found a valid path + } + + // Backtrack: If the recursive call failed, undo the move + // Check index before backtracking write too + if next_index < self.arr.len() { + self.arr[next_index].val = 0; + } + } + } + } + } + false // If no neighbor leads to a solution + } + + // Calculate the neighbor bitmask for a given cell (x, y) + fn get_neighbors(&self, x: usize, y: usize) -> u8 { + let mut c = 0u8; + for d in 0..8 { // Check all 8 potential moves + let nx_i32 = (x as i32) + DX[d]; + let ny_i32 = (y as i32) + DY[d]; + + // Check bounds + if nx_i32 >= 0 && nx_i32 < self.wid as i32 && + ny_i32 >= 0 && ny_i32 < self.hei as i32 + { + let index = (nx_i32 as usize) + (ny_i32 as usize) * self.wid; + // Check bounds on arr access + if index < self.arr.len() && self.arr[index].val > -1 { // Check not obstacle + c |= 1 << d; // Set the d-th bit + } + } + } + c + } +} // end impl NSolver + + + + +fn main() { + let p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; + let wid = 7; + + let mut puzz: Vec = p.split_whitespace().map(String::from).collect(); + + NSolver::solve_puzzle(&mut puzz, wid); + + println!("Solved Puzzle:"); + for (c, item) in puzz.iter().enumerate() { + match item.as_str() { + "*" => print!(" "), // Obstacle + "." => print!(" . "), // Unfilled cell + _ => { + match item.parse::() { + Ok(n) => { + // Handle 0 specifically - it means a '.' cell wasn't reached by the solver + if n == 0 { + print!(" . "); + } else if n < 10 { + print!("0{} ", n); // Pad single digits + } else { + print!("{} ", n); + } + } + Err(_) => { // Should ideally not happen if we only write numbers or "." back + print!(" ? "); + } + } + } + } + if (c + 1) % wid == 0 { + println!(); + } + } + println!("\n"); + + println!("Press Enter to exit..."); + let _ = io::stdout().flush(); + let mut buffer = String::new(); + io::stdin().read_line(&mut buffer).expect("Failed to read line"); +} diff --git a/Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg b/Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg new file mode 100644 index 0000000000..cb88b7c77a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/ALGOL-68/solve-a-numbrix-puzzle.alg @@ -0,0 +1,132 @@ +BEGIN # solve a Numbrix puzzle - based on the Wren Hidato solver plus this # + # solves puzzles with 1 as an unknown using the zkl sample's method # + PR read "sort.incl.a68" PR # include sort utilities # + + [,]INT moves = ( ( 1, 0 ), ( 0, 1 ), ( -1, 0 ), ( 0, -1 ) ); + + # returns TRUE if a solution for board with the specified given values # + # ( the values initially placed on the board ) can be found # + # n is the value to place, r and c the starting row and column # + # and next the position of the next value in given # + # returns FALSE if a solution cannot be found # + PROC solve board with givens = ( REF[,]INT board, []INT given, INT r, c, n, next, board size )BOOL: + IF n > board size + THEN TRUE + ELIF r < 1 LWB board OR r > 1 UPB board + OR c < 2 LWB board OR c > 2 UPB board + THEN FALSE + ELIF INT back = board[ r, c ]; + back /= 0 AND back /= n + THEN FALSE + ELIF back = 0 AND IF next > UPB given THEN FALSE ELSE given[ next ] = n FI + THEN FALSE + ELSE INT next2 = IF back = n THEN next + 1 ELSE next FI; + board[ r, c ] := n; + BOOL found := FALSE; + FOR m pos FROM 1 LWB moves TO 1 UPB moves + WHILE INT rm = r + moves[ m pos, 2 LWB moves ]; + INT cm = c + moves[ m pos, 2 UPB moves ]; + NOT ( found := solve board with givens( board, given, rm, cm, n + 1, next2, board size ) ) + DO SKIP OD; + IF NOT found THEN board[ r, c ] := back FI; + found + FI # solve board with givens # ; + + # returns the solution for board data # + # or an empty board if there isn't one # + PROC solve = ( [,]INT board data )[,]INT: + BEGIN + [ 1 LWB board data : 1 UPB board data + , 2 LWB board data : 2 UPB board data + ]INT board := board data; + INT board size = ( ( 1 UPB board - 1 LWB board ) + 1 ) + * ( ( 2 UPB board - 2 LWB board ) + 1 ) + ; + [ 1 : board size ]INT given1; + INT g pos := 0, start r := 0, start c := 0; + FOR i FROM 1 LWB board TO 1 UPB board DO + FOR j FROM 2 LWB board TO 2 UPB board DO + IF board[ i, j ] > 0 THEN + given1[ g pos +:= 1 ] := board[ i, j ]; + IF board[ i, j ] = 1 THEN start r := i; start c := j FI + FI + OD + OD; + IF start r = 0 THEN # need to pretend 1 is on the board, even # + given1[ g pos +:= 1 ] := 1 # though is isn't # + FI; + [ 1 : g pos ]INT given := given1[ 1 : g pos ]; + QUICKSORT given; + BOOL solved := FALSE; + IF start r /= 0 THEN # the position of 1 is known # + solved := solve board with givens( board, given, start r, start c, 1, 1, board size ) + ELSE # try 1 in all empty places until we find a solution # + FOR r pos FROM 1 LWB board TO 1 UPB board WHILE NOT solved DO + FOR c pos FROM 2 LWB board TO 2 UPB board WHILE NOT solved DO + IF board[ r pos, c pos ] = 0 THEN + board[ r pos, c pos ] := 1; + solved := solve board with givens( board, given, r pos, c pos, 1, 1, board size ); + IF NOT solved THEN board[ r pos, c pos ] := 0 FI + FI + OD + OD + FI; + IF solved THEN board ELSE [ 1 : 0, 1 : 0 ]INT no solution; no solution FI + END # solve # ; + + PROC print board = ( [,]INT board )VOID: + FOR i FROM 1 LWB board TO 1 UPB board DO + FOR j FROM 2 LWB board TO 2 UPB board DO + INT v = board[ i, j ]; + IF v < 0 THEN print( ( " " ) ) + ELIF v = 0 THEN print( ( " __" ) ) + ELSE print( ( whole( v, -3 ) ) ) + FI + OD; + print( ( newline ) ) + OD # print board # ; + + + [,,]INT tests = ( ( ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + , ( 0, 0, 46, 45, 0, 55, 74, 0, 0 ) + , ( 0, 38, 0, 0, 43, 0, 0, 78, 0 ) + , ( 0, 35, 0, 0, 0, 0, 0, 71, 0 ) + , ( 0, 0, 33, 0, 0, 0, 59, 0, 0 ) + , ( 0, 17, 0, 0, 0, 0, 0, 67, 0 ) + , ( 0, 18, 0, 0, 11, 0, 0, 64, 0 ) + , ( 0, 0, 24, 21, 0, 1, 2, 0, 0 ) + , ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + ) + , ( ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + , ( 0, 11, 12, 15, 18, 21, 62, 61, 0 ) + , ( 0, 6, 0, 0, 0, 0, 0, 60, 0 ) + , ( 0, 33, 0, 0, 0, 0, 0, 57, 0 ) + , ( 0, 32, 0, 0, 0, 0, 0, 56, 0 ) + , ( 0, 37, 0, 1, 0, 0, 0, 73, 0 ) + , ( 0, 38, 0, 0, 0, 0, 0, 72, 0 ) + , ( 0, 43, 44, 47, 48, 51, 76, 77, 0 ) + , ( 0, 0, 0, 0, 0, 0, 0, 0, 0 ) + ) + , ( ( 17, 0, 0, 0, 11, 0, 0, 0, 59 ) + , ( 0, 15, 0, 0, 6, 0, 0, 61, 0 ) + , ( 0, 0, 3, 0, 0, 0, 63, 0, 0 ) + , ( 0, 0, 0, 0, 66, 0, 0, 0, 0 ) + , ( 23, 24, 0, 68, 67, 78, 0, 54, 55 ) + , ( 0, 0, 0, 0, 72, 0, 0, 0, 0 ) + , ( 0, 0, 35, 0, 0, 0, 49, 0, 0 ) + , ( 0, 29, 0, 0, 40, 0, 0, 47, 0 ) + , ( 31, 0, 0, 0, 39, 0, 0, 0, 45 ) + ) + ); + FOR t pos FROM 1 LWB tests TO 1 UPB tests DO + [,]INT board = tests[ t pos, : , : ]; + print board( board ); + print( ( newline ) ); + IF [,]INT solution = solve( board ); + 1 LWB solution > 1 UPB solution + THEN print( ( "No solution found", newline ) ) + ELSE print board( solution ) + FI; + print( ( newline ) ) + OD +END diff --git a/Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy b/Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy new file mode 100644 index 0000000000..eb3600a661 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/EasyLang/solve-a-numbrix-puzzle.easy @@ -0,0 +1,76 @@ +moves[][] = [ [ -1 0 ] [ 0 -1 ] [ 0 1 ] [ 1 0 ] ] +global brd[][] maxr maxc maxcnt . +func solve r c cnt . + if cnt > maxcnt : return 1 + for m = 1 to 4 + rn = r + moves[m][1] + cn = c + moves[m][2] + if rn >= 1 and rn <= maxr and cn >= 1 and cn <= maxc + if brd[rn][cn] = 0 + brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + brd[rn][cn] = 0 + elif brd[rn][cn] = cnt + if solve rn cn (cnt + 1) = 1 : return 1 + . + . + . + return 0 +. +proc prepare brd$ &r0 &c0 . + brd$[] = strsplit brd$ "\n" + maxc = len brd$[2] / 3 + maxr = len brd$[] - 2 + maxcnt = maxc * maxr + len brd[][] maxr + for r to maxr + len brd[r][] maxc + for c to maxc + c$ = substr brd$[r + 1] (c * 3 - 2) 3 + h = number c$ + if h = 1 + r0 = r + c0 = c + . + brd[r][c] = h + . + . +. +proc printbrd . + numfmt 3 0 + for r to maxr + for c to maxc : write brd[r][c] + print "" + . +. +proc numbrix brd$ . + prepare brd$ r0 c0 + if solve r0 c0 2 = 1 + printbrd + else + print "no solutions found" + . + print "" +. +numbrix " + 0 0 0 0 0 0 0 0 0 + 0 0 46 45 0 55 74 0 0 + 0 38 0 0 43 0 0 78 0 + 0 35 0 0 0 0 0 71 0 + 0 0 33 0 0 0 59 0 0 + 0 17 0 0 0 0 0 67 0 + 0 18 0 0 11 0 0 64 0 + 0 0 24 21 0 1 2 0 0 + 0 0 0 0 0 0 0 0 0 +" +numbrix " + 0 0 0 0 0 0 0 0 0 + 0 11 12 15 18 21 62 61 0 + 0 6 0 0 0 0 0 60 0 + 0 33 0 0 0 0 0 57 0 + 0 32 0 0 0 0 0 56 0 + 0 37 0 1 0 0 0 73 0 + 0 38 0 0 0 0 0 72 0 + 0 43 44 47 48 51 76 77 0 + 0 0 0 0 0 0 0 0 0 +" diff --git a/Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js b/Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js new file mode 100644 index 0000000000..da020fa10a --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/JavaScript/solve-a-numbrix-puzzle.js @@ -0,0 +1,110 @@ +const example1 = [ + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00", +]; + +const example2 = [ + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00", +]; + +const moves = [[1, 0], [0, 1], [-1, 0], [0, -1]]; + +let grid, clues, totalToFill; + +function solve(r, c, count, nextClue) { + if (count > totalToFill) { + return true; + } + + const back = grid[r][c]; + + if (back !== 0 && back !== count) { + return false; + } + + if (back === 0 && nextClue < clues.length && clues[nextClue] === count) { + return false; + } + + let newNextClue = nextClue; + if (back === count) { + newNextClue++; + } + + grid[r][c] = count; + for (const move of moves) { + if (solve(r + move[1], c + move[0], count + 1, newNextClue)) { + return true; + } + } + grid[r][c] = back; + return false; +} + +function printResult(n) { + console.log(`Solution for example ${n}:`); + for (const row of grid) { + let line = ""; + for (const i of row) { + if (i === -1) { + continue; + } + line += `${i.toString().padStart(2)} `; + } + console.log(line); + } +} + +function main() { + const boards = [example1, example2]; + + for (let n = 0; n < boards.length; n++) { + const board = boards[n]; + const nRows = board.length + 2; + const nCols = board[0].split(',').length + 2; + let startRow = 0, startCol = 0; + grid = Array(nRows).fill().map(() => Array(nCols).fill(-1)); + totalToFill = (nRows - 2) * (nCols - 2); + let lst = []; + + for (let r = 0; r < nRows; r++) { + if (r >= 1 && r < nRows - 1) { + const row = board[r - 1].split(','); + for (let c = 1; c < nCols - 1; c++) { + const val = parseInt(row[c - 1]); + if (val > 0) { + lst.push(val); + } + if (val === 1) { + startRow = r; + startCol = c; + } + grid[r][c] = val; + } + } + } + + lst.sort((a, b) => a - b); + clues = lst; + if (solve(startRow, startCol, 1, 0)) { + printResult(n + 1); + } + } +} + +main(); diff --git a/Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs b/Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs new file mode 100644 index 0000000000..eea882792c --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Rust/solve-a-numbrix-puzzle.rs @@ -0,0 +1,205 @@ +use std::io::{self, Write}; + +#[derive(Clone)] // Add Clone derivation to fix the compilation error +struct Node { + val: i32, + neighbors: u8, +} + +struct NSolver { + wid: i32, + hei: i32, + max: i32, + arr: Vec, + we_have: Vec, + dx: Vec, + dy: Vec, +} + +impl NSolver { + fn new() -> Self { + NSolver { + wid: 0, + hei: 0, + max: 0, + arr: Vec::new(), + we_have: Vec::new(), + dx: vec![-1, 1, 0, 0], + dy: vec![0, 0, -1, 1], + } + } + + fn solve(&mut self, puzz: &mut Vec, max_wid: i32) { + if puzz.is_empty() { + return; + } + + self.wid = max_wid; + self.hei = puzz.len() as i32 / self.wid; + self.max = self.wid * self.hei; + let len = self.max as usize; + + self.arr = vec![Node { val: 0, neighbors: 0 }; len]; + self.we_have = vec![false; len + 1]; + + let mut c = 0; + for s in puzz.iter() { + if s == "*" { + self.max -= 1; + self.arr[c].val = -1; + c += 1; + continue; + } + + self.arr[c].val = s.parse::().unwrap_or(0); + if self.arr[c].val > 0 { + self.we_have[self.arr[c].val as usize] = true; + } + c += 1; + } + + self.solve_it(); + + c = 0; + for s in puzz.iter_mut() { + if s == "." { + *s = self.arr[c].val.to_string(); + } + c += 1; + } + } + + fn search(&mut self, x: i32, y: i32, w: i32, dr: i32) -> bool { + if (w > self.max && dr > 0) || (w < 1 && dr < 0) || (w == self.max && self.we_have[w as usize]) { + return true; + } + + let idx = (x + y * self.wid) as usize; + self.arr[idx].neighbors = self.get_neighbors(x, y); + + if self.we_have[w as usize] { + for d in 0..4 { + if (self.arr[idx].neighbors & (1 << d)) != 0 { + let a = x + self.dx[d]; + let b = y + self.dy[d]; + let neighbor_idx = (a + b * self.wid) as usize; + + if self.arr[neighbor_idx].val == w { + if self.search(a, b, w + dr, dr) { + return true; + } + } + } + } + return false; + } + + for d in 0..4 { + if (self.arr[idx].neighbors & (1 << d)) != 0 { + let a = x + self.dx[d]; + let b = y + self.dy[d]; + let neighbor_idx = (a + b * self.wid) as usize; + + if self.arr[neighbor_idx].val == 0 { + self.arr[neighbor_idx].val = w; + if self.search(a, b, w + dr, dr) { + return true; + } + self.arr[neighbor_idx].val = 0; + } + } + } + + false + } + + fn get_neighbors(&self, x: i32, y: i32) -> u8 { + let mut retval: u8 = 0; + + for xx in 0..4 { + let a = x + self.dx[xx]; + let b = y + self.dy[xx]; + + if a < 0 || b < 0 || a >= self.wid || b >= self.hei { + continue; + } + + let idx = (a + b * self.wid) as usize; + if self.arr[idx].val > -1 { + retval |= 1 << xx; + } + } + + retval + } + + fn solve_it(&mut self) { + let (x, y, z) = self.find_start(); + if z == 99999 { + println!("\nCan't find start point!"); + return; + } + + self.search(x, y, z + 1, 1); + if z > 1 { + self.search(x, y, z - 1, -1); + } + } + + fn find_start(&self) -> (i32, i32, i32) { + let mut z = 99999; + let mut x = 0; + let mut y = 0; + + for b in 0..self.hei { + for a in 0..self.wid { + let idx = (a + self.wid * b) as usize; + if self.arr[idx].val > 0 && self.arr[idx].val < z { + x = a; + y = b; + z = self.arr[idx].val; + } + } + } + + (x, y, z) + } +} + +fn main() { + let wid = 9; + //let p = ". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . ."; + //let p = ". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . ."; + let p = "17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55 . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45"; + + let mut puzz: Vec = p.split_whitespace().map(|s| s.to_string()).collect(); + let mut solver = NSolver::new(); + solver.solve(&mut puzz, wid); + + let mut c = 0; + for s in &puzz { + if s != "*" && s != "." { + if let Ok(num) = s.parse::() { + if num < 10 { + print!("0"); + } + } + print!("{} ", s); + } else { + print!(" "); + } + + c += 1; + if c >= wid { + println!(); + c = 0; + } + } + println!("\n"); + + // Equivalent of system("pause") in Rust + // print!("Press Enter to continue..."); + // io::stdout().flush().unwrap(); + // let mut input = String::new(); + // io::stdin().read_line(&mut input).unwrap(); +} diff --git a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl index de12ddf8a7..c03498dfd5 100644 --- a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl +++ b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-1.zkl @@ -10,7 +10,7 @@ class Puzzle{ // hold info concerning this puzzle fcn print_board{ d:=Dictionary(-1," ", 0,"__"); foreach r in (board){ - r.pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println(); + r.pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println(); } } fcn init(s,adjacent){ @@ -21,14 +21,14 @@ class Puzzle{ // hold info concerning this puzzle given,start=List(),Void; cells,terminated=0,True; foreach r,row in (lines.enumerate()){ - foreach c,cell in (row.split().enumerate()){ - if(cell=="X") continue; // X == not in play, leave at -1 - cells+=1; - val:=cell.toInt(); - board[r][c]=val; - given.append(val); - if(val==1) start=T(r,c); - } + foreach c,cell in (row.split().enumerate()){ + if(cell=="X") continue; // X == not in play, leave at -1 + cells+=1; + val:=cell.toInt(); + board[r][c]=val; + given.append(val); + if(val==1) start=T(r,c); + } } println("Number of cells = ",cells); if(not given.holds(cells)){ given.append(cells); terminated=False; } @@ -37,7 +37,7 @@ class Puzzle{ // hold info concerning this puzzle fcn solve{ //-->Bool if(start) return(_solve(start.xplode())); foreach r,c in (nrows,ncols){ - if(board[r][c]==0 and _solve(r,c)) return(True); + if(board[r][c]==0 and _solve(r,c)) return(True); } False } diff --git a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl index ff1b705375..79fb9e68c7 100644 --- a/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl +++ b/Task/Solve-a-Numbrix-puzzle/Zkl/solve-a-numbrix-puzzle-2.zkl @@ -23,12 +23,25 @@ hi2:= // 0==empty cell, X==not a cell 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0"; #<<< + +hi3:= +#<<< +"17 0 0 0 11 0 0 0 59 + 0 15 0 0 6 0 0 61 0 + 0 0 3 0 0 0 63 0 0 + 0 0 0 0 66 0 0 0 0 + 23 24 0 68 67 78 0 54 55 + 0 0 0 0 72 0 0 0 0 + 0 0 35 0 0 0 49 0 0 + 0 29 0 0 40 0 0 47 0 + 31 0 0 0 39 0 0 0 45"; +#<<< adjacent:=T( T(-1,0), T( 0,-1), T( 0,1), T( 1,0) ); -foreach hi in (T(hi1,hi2)){ - puzzle:=Puzzle(hi); puzzle.adjacent=adjacent; +foreach hi in (T(hi1,hi2,hi3)){ + puzzle:=Puzzle(hi,adjacent); puzzle.print_board(); puzzle.solve(); println(); diff --git a/Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg b/Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg new file mode 100644 index 0000000000..9605f99749 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/ALGOL-68/solve-the-no-connection-puzzle.alg @@ -0,0 +1,90 @@ +BEGIN CO Solve the no connection puzzle + the board looks like: + A B + /|\ /|\ + / | X | \ + / |/ \| \ + C - D - E - F + \ |\ /| / + \ | X | / + \|/ \|/ + G H + we need to place 1..8 at A..G so that each connected + value differs by at least 2 (e.g., A=1 and D=3 is OK + but A=1 and D=2 is not) + CO + + PROC not ok = ( INT x )BOOL: ABS x < 2; + PROC ok = ( INT a, b, c, d, e, f, g, h )BOOL: + IF not ok( a - c ) OR not ok( a - d ) OR not ok( a - e ) THEN FALSE + ELIF not ok( b - d ) OR not ok( b - e ) OR not ok( b - f ) THEN FALSE + ELIF not ok( g - c ) OR not ok( g - d ) OR not ok( g - e ) THEN FALSE + ELIF not ok( h - d ) OR not ok( h - e ) OR not ok( h - f ) THEN FALSE + ELIF not ok( c - d ) OR not ok( d - e ) OR not ok( e - f ) THEN FALSE + ELSE TRUE + FI # ok # ; + + PROC is solution = ( []INT a )BOOL: + ok( a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ], a[ 5 ], a[ 6 ], a[ 7 ] ); + + # Heap's algorithm for generating permutations # + # - from the pseudo-code on the Wikipedia page # + # have permutation is called for each generated permutation # + PROC generate = ( INT k, REF[]INT a, REF INT swap count, PROC([]INT,INT)VOID have permutation )VOID: + IF k = 1 THEN + have permutation( a, swap count ) + ELSE + # Generate permutations with kth unaltered # + # Initially k = length a # + generate( k - 1, a, swap count, have permutation ); + # Generate permutations for kth swapped with each k-1 initial # + FOR i FROM 0 TO k - 2 DO + # Swap choice dependent on parity of k (even or odd) # + swap count +:= 1; + INT swap item = IF ODD k THEN 0 ELSE i FI; + INT t = a[ swap item ]; + a[ swap item ] := a[ k - 1 ]; + a[ k - 1 ] := t; + generate( k - 1, a, swap count, have permutation ) + OD + FI # generate # ; + # generate permutations of a # + PROC permute = ( REF[]INT a, PROC([]INT,INT)VOID have permutation )VOID: + BEGIN + INT swap count := 0; + generate( ( UPB a + 1 ) - LWB a, a[ AT 0 ], swap count, have permutation ) + END # permute # ; + + # handle a permutation # + PROC possible solution = ( []INT p, INT swap count )VOID: + IF is solution( p ) THEN # have a solution # + IF first solution THEN + print( ( "First solution found:", newline ) ); + OP N = ( INT v )CHAR: REPR ( v + ABS "0" ); + CHAR a = N p[ 0 ], b = N p[ 1 ], c = N p[ 2 ], d = N p[ 3 ]; + CHAR e = N p[ 4 ], f = N p[ 5 ], g = N p[ 6 ], h = N p[ 7 ]; + print( ( " ", a, " ", b, newline ) ); + print( ( " /|\ /|\", newline ) ); + print( ( " / | X | \", newline ) ); + print( ( " / |/ \| \", newline ) ); + print( ( " ", c, " - ", d, " - ", e, " - ", f, newline ) ); + print( ( " \ |\ /| /", newline ) ); + print( ( " \ | X | /", newline ) ); + print( ( " \|/ \|/", newline ) ); + print( ( " ", g, " ", h, newline ) ); + print( ( newline, "All solutions:", newline ) ); + first solution := FALSE + FI; + print( ( " [" ) ); + FOR i FROM LWB p TO UPB p DO + print( ( whole( p[ i ], 0 ) ) ); + IF i = UPB p THEN print( ( "]" ) ) ELSE print( ( ", " ) ) FI + OD; + print( ( " after ", whole( swap count, 0 ), " swaps", newline ) ) + FI # possible solution # ; + + [ 1 : 8 ]INT items := ( 1, 2, 3, 4, 5, 6, 7, 8 ); + BOOL first solution := TRUE; + permute( items, possible solution ) + +END diff --git a/Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy b/Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy new file mode 100644 index 0000000000..4245d66273 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/EasyLang/solve-the-no-connection-puzzle.easy @@ -0,0 +1,23 @@ +cons[][] = [ [ 3 4 5 ] [ 4 5 6 ] [ 4 7 ] [ 5 7 8 ] [ 6 7 8 ] [ 8 ] [ ] [ ] ] +n = len cons[][] +len peg[] n +# +proc init . + for i to n : peg[i] = i +. +init +# +proc permute k . + for i = k to n + swap peg[i] peg[k] + permute k + 1 + swap peg[k] peg[i] + . + if k = n + for i to n : for j in cons[i][] + if abs (peg[i] - peg[j]) = 1 : break 2 + . + if i > n : print peg[] + . +. +permute 1 diff --git a/Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl b/Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl new file mode 100644 index 0000000000..4e28e5deb5 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/APL/sort-a-list-of-object-identifiers.apl @@ -0,0 +1 @@ +oidsort ← {⍵[⍋{⊃(//)'.'⎕VFI⍵}¨⍵]} diff --git a/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy b/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy index 73666aae50..39dd5e8ce9 100644 --- a/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy +++ b/Task/Sort-a-list-of-object-identifiers/EasyLang/sort-a-list-of-object-identifiers.easy @@ -1,20 +1,12 @@ -proc sort . d$[] . - for s$ in d$[] - d[][] &= number strsplit s$ "." - . +proc sort &d$[] . + for s$ in d$[] : d[][] &= number strsplit s$ "." n = len d[][] - for i = 1 to n - 1 - for j = i + 1 to n - m = lower len d[i][] len d[j][] - for k to m - if d[i][k] <> d[j][k] - break 1 - . - . - if k > m and len d[i][] > len d[j][] or d[i][k] > d[j][k] - swap d[i][] d[j][] - . + for i = 1 to n - 1 : for j = i + 1 to n + m = lower len d[i][] len d[j][] + for k to m + if d[i][k] <> d[j][k] : break 1 . + if k > m and len d[i][] > len d[j][] or d[i][k] > d[j][k] : swap d[i][] d[j][] . for i to len d[][] d$[i] = d[i][1] diff --git a/Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr b/Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr new file mode 100644 index 0000000000..5570a1ab95 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Crystal/sort-an-array-of-composite-structures.cr @@ -0,0 +1,11 @@ +record City, name : String, country : String + +cities = [{"Warsaw", "Poland"}, {"Prague", "Czech Republic"}, {"Paris", "France"}, + {"Lima", "Peru"}, {"Montevideo", "Uruguay"}, {"Bogotá", "Colombia"}, + {"Cairo", "Egypt"}, {"Yaoundé", "Cameroon"}, {"Luanda", "Angola"}] + .map {|name, country| City.new name, country } + +puts "unsorted:" +pp cities +puts "sorted:" +pp cities.sort_by &.name diff --git a/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 b/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 index 6f21257769..9a3d221aaa 100644 --- a/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 +++ b/Task/Sort-an-array-of-composite-structures/M2000-Interpreter/sort-an-array-of-composite-structures.m2000 @@ -57,7 +57,7 @@ module Sort_an_array_of_composite_structures{ return } Sort_an_array_of_composite_structures -Pint +Print module Checkit2 { Inventory Alfa="Joe":=5531, "Adam":=2341, "Bernie":=122 Append Alfa, "Walter":=1234, "David":=19 diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx index 55bf6843c1..0dbe5524de 100644 --- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx +++ b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx @@ -1,16 +1,18 @@ -Main: +include Settings + +say 'SORT COMPOSITE ARRAY - 5 Mar 2025' +say version +say call Create call Show 'Not ordered' call SortStateCity call Show 'By state and city' call SortPopCityN call Show 'By pop (numeric desc) and city' -table = 'states.' -keys = 'pop. state.'; data = 'city.' +table = 'states.'; keys = 'pop. state.'; data = 'city.' call SortPopCityS table,keys,data call Show 'By pop (string) and city' -table = 'states.' -keys = 'city. state.'; data = 'pop.' +table = 'states.'; keys = 'city. state.'; data = 'pop.' call SortCityState table,keys,data call Show 'By city and state' return diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx deleted file mode 100644 index 0df1385350..0000000000 --- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-3.rexx +++ /dev/null @@ -1,124 +0,0 @@ --- Module Quicksort21.inc - Build 30 Jan 2025 --- Fast stem sort - -default [label]=Quicksort21 [table]=table. [key1]=key1. [key2]=key2. [data1]=data1. [lt]=< [eq]== [gt]=> - -[label]: --- Sort a stem on 2 key columns, syncing 1 data column -procedure expose [table] --- Sort -n = [table]0; s = 1; sl.1 = 1; sr.1 = n -do until s = 0 - l = sl.s; r = sr.s; s = s-1 - do until l >= r --- Up to 19 rows selection sort is faster - if r-l < 20 then do - do i = l+1 to r - a = [table][key1]i - b = [table][key2]i - c = [table][data1]i - do j = i-1 by -1 to l - if [table][key1]j [lt] a then - leave - if [table][key1]j [eq] a then - if [table][key2]j [lt]= b then - leave - k = j+1 - [table][key1]k = [table][key1]j - [table][key2]k = [table][key2]j - [table][data1]k = [table][data1]j - end - k = j+1 - [table][key1]k = a - [table][key2]k = b - [table][data1]k = c - end - if s = 0 then - leave - l = sl.s; r = sr.s; s = s-1 - end - else do --- Find optimized pivot - m = (l+r)%2 - if [table][key1]l [gt] [table][key1]m then do - t = [table][key1]l; [table][key1]l = [table][key1]m; [table][key1]m = t - t = [table][key2]l; [table][key2]l = [table][key2]m; [table][key2]m = t - t = [table][data1]l; [table][data1]l = [table][data1]m; [table][data1]m = t - end - else do - if [table][key1]l [eq] [table][key1]m then do - if [table][key2]l [gt] [table][key2]m then do - t = [table][key2]l; [table][key2]l = [table][key2]m; [table][key2]m = t - t = [table][data1]l; [table][data1]l = [table][data1]m; [table][data1]m = t - end - end - end - if [table][key1]l [gt] [table][key1]r then do - t = [table][key1]l; [table][key1]l = [table][key1]r; [table][key1]r = t - t = [table][key2]l; [table][key2]l = [table][key2]r; [table][key2]r = t - t = [table][data1]l; [table][data1]l = [table][data1]r; [table][data1]r = t - end - else do - if [table][key1]l [eq] [table][key1]r then do - if [table][key2]l [gt] [table][key2]r then do - t = [table][key2]l; [table][key2]l = [table][key2]r; [table][key2]r = t - t = [table][data1]l; [table][data1]l = [table][data1]r; [table][data1]r = t - end - end - end - if [table][key1]m [gt] [table][key1]r then do - t = [table][key1]m; [table][key1]m = [table][key1]r; [table][key1]r = t - t = [table][key2]m; [table][key2]m = [table][key2]r; [table][key2]r = t - t = [table][data1]m; [table][data1]m = [table][data1]r; [table][data1]r = t - end - else do - if [table][key1]m [eq] [table][key1]r then do - if [table][key2]m [gt] [table][key2]r then do - t = [table][key2]m; [table][key2]m = [table][key2]r; [table][key2]r = t - t = [table][data1]m; [table][data1]m = [table][data1]r; [table][data1]r = t - end - end - end --- Rearrange rows in partition - i = l; j = r - a = [table][key1]m - b = [table][key2]m - do until i > j - do i = i - if [table][key1]i [gt] a then - leave - if [table][key1]i [eq] a then - if [table][key2]i [gt]= b then - leave - end - do j = j by -1 - if [table][key1]j [lt] a then - leave - if [table][key1]j [eq] a then - if [table][key2]j [lt]= b then - leave - end - if i <= j then do - t = [table][key1]i; [table][key1]i = [table][key1]j; [table][key1]j = t - t = [table][key2]i; [table][key2]i = [table][key2]j; [table][key2]j = t - t = [table][data1]i; [table][data1]i = [table][data1]j; [table][data1]j = t - i = i+1; j = j-1 - end - end --- Next partition - if j-l < r-i then do - if i < r then do - s = s+1; sl.s = i; sr.s = r - end - r = j - end - else do - if l < j then do - s = s+1; sl.s = l; sr.s = j - end - l = i - end - end - end -end -return diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx deleted file mode 100644 index b12abc5667..0000000000 --- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-4.rexx +++ /dev/null @@ -1,173 +0,0 @@ --- Module Quicksort.inc - Build 30 Jan 2025 --- Generic stem sort - -default [label]=Quicksort [lt]=< [eq]== [gt]=> - -[label]: --- Sort a stem on 1 or more key columns, syncing 0 or more data columns -procedure expose (table) -arg table,keys,data --- Collect keys -kn = Words(keys) -do x = 1 to kn - key.x = Word(keys,x) -end --- Collect data -dn = Words(data) -do x = 1 to dn - data.x = Word(data,x) -end --- Sort -n = Value(table||0); s = 1; sl.1 = 1; sr.1 = n -do until s = 0 - l = sl.s; r = sr.s; s = s-1 - do until l >= r --- Up to 19 rows insertion sort is faster - if r-l < 20 then do - do i = l+1 to r - do x = 1 to kn - k.x = Value(table||key.x||i) - end - do x = 1 to dn - d.x = Value(table||data.x||i) - end - do j=i-1 to l by -1 - do x = 1 to kn - a = Value(table||key.x||j) - if a [gt] k.x then - leave x - if a [eq] k.x then - if x < kn then - iterate x - leave j - end - k = j+1 - do x = 1 to kn - t = Value(table||key.x||j) - call value table||key.x||k,t - end - do x = 1 to dn - t = Value(table||data.x||j) - call value table||data.x||k,t - end - end - k = j+1 - do x = 1 to kn - call value table||key.x||k,k.x - end - do x = 1 to dn - call value table||data.x||k,d.x - end - end - if s = 0 then - leave - l = sl.s; r = sr.s; s = s-1 - end - else do --- Find optimized pivot - m = (l+r)%2 - do x = 1 to kn - a = Value(table||key.x||l); b = Value(table||key.x||m) - if a [gt] b then do - do y = 1 to kn - t = Value(table||key.y||l); u = Value(table||key.y||m) - call value table||key.y||l,u; call value table||key.y||m,t - end - do y = 1 to dn - t = Value(table||data.y||l); u = Value(table||data.y||m) - call value table||data.y||l,u; call value table||data.y||m,t - end - leave - end - if a [lt] b then - leave - end - do x = 1 to kn - a = Value(table||key.x||l); b = Value(table||key.x||r) - if a [gt] b then do - do y = 1 to kn - t = Value(table||key.y||l); u = Value(table||key.y||r) - call value table||key.y||l,u; call value table||key.y||r,t - end - do y = 1 to dn - t = Value(table||data.y||l); u = Value(table||data.y||r) - call value table||data.y||l,u; call value table||data.y||r,t - end - leave - end - if a [lt] b then - leave - end - do x = 1 to kn - a = Value(table||key.x||m); b = Value(table||key.x||r) - if a [gt] b then do - do y = 1 to kn - t = Value(table||key.y||m); u = Value(table||key.y||r) - call value table||key.y||m,u; call value table||key.y||r,t - end - do y = 1 to dn - t = Value(table||data.y||m); u = Value(table||data.y||r) - call value table||data.y||m,u; call value table||data.y||r,t - end - leave - end - if a [lt] b then - leave - end --- Rearrange rows in partition - i = l; j = r - do x = 1 to kn - p.x = Value(table||key.x||m) - end - do until i > j - do i = i - do x = 1 to kn - a = Value(table||key.x||i) - if a [lt] p.x then - leave x - if a [eq] p.x then - if x < kn then - iterate x - leave i - end - end - do j = j by -1 - do x = 1 to kn - a = Value(table||key.x||j) - if a [gt] p.x then - leave x - if a [eq] p.x then - if x < kn then - iterate x - leave j - end - end - if i <= j then do - do x = 1 to kn - t = Value(table||key.x||i); u = Value(table||key.x||j) - call value table||key.x||i,u; call value table||key.x||j,t - end - do x = 1 to dn - t = Value(table||data.x||i); u = Value(table||data.x||j) - call value table||data.x||i,u; call value table||data.x||j,t - end - i = i+1; j = j-1 - end - end --- Next partition - if j-l < r-i then do - if i < r then do - s = s+1; sl.s = i; sr.s = r - end - r = j - end - else do - if l < j then do - s = s+1; sl.s = l; sr.s = j - end - l = i - end - end - end -end -return diff --git a/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy b/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy index 5e57891875..44ddb91b3a 100644 --- a/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy +++ b/Task/Sort-an-integer-array/EasyLang/sort-an-integer-array.easy @@ -1,10 +1,6 @@ -proc sort . d[] . - for i = 1 to len d[] - 1 - for j = i + 1 to len d[] - if d[j] < d[i] - swap d[j] d[i] - . - . +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] . . a[] = [ 2 4 3 1 2 ] diff --git a/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy b/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy index 44d5917f87..f6ffbc327d 100644 --- a/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy +++ b/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy @@ -1,9 +1,7 @@ sortdir = 1 -proc sort . d$[][] . - for i = 1 to len d$[][] - 1 - for j = i + 1 to len d$[][] - if sortdir * strcmp d$[j][1] d$[i][1] < 0 : swap d$[j][] d$[i][] - . +proc sort &d$[][] . + for i = 1 to len d$[][] - 1 : for j = i + 1 to len d$[][] + if sortdir * strcmp d$[j][1] d$[i][1] < 0 : swap d$[j][] d$[i][] . . repeat @@ -19,7 +17,7 @@ subr init . istab = -1 # -proc nextline . . +proc nextline . if linpos = -1 : return linpos += 1 if linpos > len inp$[] @@ -73,7 +71,7 @@ func$[] outline . if linpos <> -1 : linpos -= 1 return r$[] . -proc run dir . . +proc run dir . sortdir = dir call init nextline diff --git a/Task/Sort-numbers-lexicographically/Crystal/sort-numbers-lexicographically.cr b/Task/Sort-numbers-lexicographically/Crystal/sort-numbers-lexicographically.cr new file mode 100644 index 0000000000..eddeed0680 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/Crystal/sort-numbers-lexicographically.cr @@ -0,0 +1,2 @@ +n = 13 +p (1..n).to_a.sort_by! &.to_s diff --git a/Task/Sort-numbers-lexicographically/R/sort-numbers-lexicographically.r b/Task/Sort-numbers-lexicographically/R/sort-numbers-lexicographically.r new file mode 100644 index 0000000000..7212a68cf2 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/R/sort-numbers-lexicographically.r @@ -0,0 +1,6 @@ +lex_sort <- function(n){ + str <- sort(as.character(1:n)) + return(as.numeric(str)) +} + +lex_sort(13) diff --git a/Task/Sort-three-variables/Crystal/sort-three-variables.cr b/Task/Sort-three-variables/Crystal/sort-three-variables.cr new file mode 100644 index 0000000000..8a1796a4ed --- /dev/null +++ b/Task/Sort-three-variables/Crystal/sort-three-variables.cr @@ -0,0 +1,14 @@ +x = "lions, tigers, and" +y = "bears, oh my!" +z = "(from the \"Wizard of OZ\")" + +x, y, z = [x, y, z].sort +puts "x = #{x}", "y = #{y}", "z = #{z}" +puts "--" + +x = 77444 +y = -12 +z = 0 + +x, y, z = [x, y, z].sort +puts "x = #{x}", "y = #{y}", "z = #{z}" diff --git a/Task/Sort-three-variables/EasyLang/sort-three-variables.easy b/Task/Sort-three-variables/EasyLang/sort-three-variables.easy index 99eeed717e..e07716d7eb 100644 --- a/Task/Sort-three-variables/EasyLang/sort-three-variables.easy +++ b/Task/Sort-three-variables/EasyLang/sort-three-variables.easy @@ -1,13 +1,7 @@ -proc sort3 . a b c . - if a > c - swap a c - . - if b > c - swap b c - . - if a > b - swap a b - . +proc sort3 &a &b &c . + if a > c : swap a c + if b > c : swap b c + if a > b : swap a b . x = 77444 y = -12 @@ -15,16 +9,10 @@ z = 0 sort3 x y z print x & " " & y & " " & z # -proc sort3str . a$ b$ c$ . - if strcmp a$ c$ > 0 - swap a$ c$ - . - if strcmp b$ c$ > 0 - swap b$ c$ - . - if strcmp a$ b$ > 0 - swap a$ b$ - . +proc sort3str &a$ &b$ &c$ . + if strcmp a$ c$ > 0 : swap a$ c$ + if strcmp b$ c$ > 0 : swap b$ c$ + if strcmp a$ b$ > 0 : swap a$ b$ . x$ = "lions, tigers, and" y$ = "bears, oh my!" diff --git a/Task/Sort-three-variables/XPL0/sort-three-variables.xpl0 b/Task/Sort-three-variables/XPL0/sort-three-variables.xpl0 new file mode 100644 index 0000000000..2511980d3a --- /dev/null +++ b/Task/Sort-three-variables/XPL0/sort-three-variables.xpl0 @@ -0,0 +1,31 @@ +include xpllib; \for StrSort and Print + +int X, Y, Z; +int L, M, H; +real RX, RY, RZ, RT; +[X:= 77444; Y:= -12; Z:= 0; +L:= X; +if L>Y then L:= Y; +if L>Z then L:= Z; +H:= X; +if HRY then [RT:= RX; RX:= RY; RY:= RT]; +if RY>RZ then [RT:= RY; RY:= RZ; RZ:= RT]; +if RX>RY then [RT:= RX; RX:= RY; RY:= RT]; +RlOut(0, RX); CrLf(0); +RlOut(0, RY); CrLf(0); +RlOut(0, RZ); CrLf(0); + +X:= "lions, tigers, and"; +Y:= "bears, oh my!"; +Z:= "(from the ^"Wizard of OZ^")"; +StrSort(@X, 3); \the address of X is used as an array containing X, Y, Z +Print("%s\n%s\n%s\n", X, Y, Z); +] diff --git a/Task/Sorting-Algorithms-Circle-Sort/Crystal/sorting-algorithms-circle-sort.cr b/Task/Sorting-Algorithms-Circle-Sort/Crystal/sorting-algorithms-circle-sort.cr new file mode 100644 index 0000000000..63667ae92c --- /dev/null +++ b/Task/Sorting-Algorithms-Circle-Sort/Crystal/sorting-algorithms-circle-sort.cr @@ -0,0 +1,35 @@ +class Array + private def circle_sort_ (lo, hi) + return 0 if lo == hi + swaps = 0 + low, high = lo, hi + mid = (hi - lo) // 2 + while lo < hi + if self[lo] > self[hi] + swap lo, hi + swaps += 1 + end + lo += 1 + hi -= 1 + end + if lo == hi && self[lo] > self[hi+1] + swap lo, hi+1 + swaps += 1 + end + swaps + circle_sort_(low, low+mid) + circle_sort_(low+mid+1, high) + end + + def circle_sort! + while circle_sort_(0, size-1) > 0 + end + self + end +end + +arr = Array.new(20) { rand 100 } +p arr +p arr.circle_sort! + +arr = %w(The quick brown fox jumps over the lazy dog.) +p arr +p arr.circle_sort! diff --git a/Task/Sorting-algorithms-Bead-sort/Rust/sorting-algorithms-bead-sort.rs b/Task/Sorting-algorithms-Bead-sort/Rust/sorting-algorithms-bead-sort.rs new file mode 100644 index 0000000000..c994ed5f11 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Rust/sorting-algorithms-bead-sort.rs @@ -0,0 +1,37 @@ +fn distribute(dist: usize, list: &mut Vec) { + // If dist exceeds current length, extend the vector with zeros + if dist > list.len() { + list.resize(dist, 0); + } + + // Increment each of the first `dist` positions (simulate gravity) + for i in 0..dist { + list[i] += 1; + } +} + +fn bead_sort(arr: &[usize]) -> Vec { + let mut list = Vec::new(); + let mut list2 = Vec::new(); + + println!("#1 Beads falling down: "); + for &num in arr { + distribute(num, &mut list); + } + + println!("\nBeads on their sides: {:?}", list); + + println!("#2 Beads right side up: "); + for &count in &list { + distribute(count, &mut list2); + } + + list2 +} + +fn main() { + let myints = [734, 3, 1, 24, 324, 324, 32, 432, 42, 3, 4, 1, 1]; + let sorted = bead_sort(&myints); + + println!("Sorted list/array: {:?}", sorted); +} diff --git a/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy b/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy index 7f7b93d3ce..527e5afa4d 100644 --- a/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy +++ b/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy @@ -1,22 +1,17 @@ -proc shuffle . l[] . +proc shuffle &l[] . for i = len l[] downto 2 r = random i swap l[i] l[r] . . -proc issorted . l[] r . +func issorted &l[] . for i = 2 to len l[] - if l[i] < l[i - 1] - r = 0 - return - . + if l[i] < l[i - 1] : return 0 . - r = 1 + return 1 . -proc bogosort . l[] . - repeat - issorted l[] r - until r = 1 +proc bogosort &l[] . + while issorted l[] = 0 shuffle l[] . . diff --git a/Task/Sorting-algorithms-Bubble-sort/Crystal/sorting-algorithms-bubble-sort.cr b/Task/Sorting-algorithms-Bubble-sort/Crystal/sorting-algorithms-bubble-sort.cr new file mode 100644 index 0000000000..bf32ab26d5 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Crystal/sorting-algorithms-bubble-sort.cr @@ -0,0 +1,17 @@ +class Array + def bubble_sort! + i = size - 1 + while i > 0 + (1..i).each do |j| + swap(j, j-1) if self[j] < self[j-1] + end + i -= 1 + end + self + end +end + +arr = Array.new(20) { rand 100 } + +p arr +p arr.bubble_sort! diff --git a/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy b/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy index 7b5cfcb533..e91075d923 100644 --- a/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy +++ b/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy @@ -1,9 +1,7 @@ -proc bubble_sort . d[] . +proc bubble_sort &d[] . for i = len d[] - 1 downto 1 for j = 1 to i - if d[j] > d[j + 1] - swap d[j] d[j + 1] - . + if d[j] > d[j + 1] : swap d[j] d[j + 1] . . . diff --git a/Task/Sorting-algorithms-Cocktail-sort/EasyLang/sorting-algorithms-cocktail-sort.easy b/Task/Sorting-algorithms-Cocktail-sort/EasyLang/sorting-algorithms-cocktail-sort.easy index 0eee706f5a..1a5a20e7b4 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/EasyLang/sorting-algorithms-cocktail-sort.easy +++ b/Task/Sorting-algorithms-Cocktail-sort/EasyLang/sorting-algorithms-cocktail-sort.easy @@ -1,4 +1,4 @@ -proc sort . d[] . +proc sort &d[] . a = 1 b = len d[] - 1 while a <= b diff --git a/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy b/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy index 78061a2157..9abab6fec5 100644 --- a/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy +++ b/Task/Sorting-algorithms-Comb-sort/EasyLang/sorting-algorithms-comb-sort.easy @@ -1,4 +1,4 @@ -proc combsort . d[] . +proc combsort &d[] . gap = len d[] while gap > 1 or swaps = 1 gap = higher 1 (gap div 1.25) diff --git a/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy b/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy index 76f36523ee..6468fbe2dc 100644 --- a/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy +++ b/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy @@ -1,8 +1,6 @@ -proc countsort min max . d[] . +proc countsort min max &d[] . len count[] max - min + 1 - for n in d[] - count[n - min + 1] += 1 - . + for n in d[] : count[n - min + 1] += 1 z = 1 for i = min to max while count[i - min + 1] > 0 diff --git a/Task/Sorting-algorithms-Gnome-sort/EasyLang/sorting-algorithms-gnome-sort.easy b/Task/Sorting-algorithms-Gnome-sort/EasyLang/sorting-algorithms-gnome-sort.easy index 4fe89983da..ae31e78a96 100644 --- a/Task/Sorting-algorithms-Gnome-sort/EasyLang/sorting-algorithms-gnome-sort.easy +++ b/Task/Sorting-algorithms-Gnome-sort/EasyLang/sorting-algorithms-gnome-sort.easy @@ -1,4 +1,4 @@ -proc sort . d[] . +proc sort &d[] . i = 2 j = 3 while i <= len d[] diff --git a/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy b/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy index 8c699020bb..9fae6acb7d 100644 --- a/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy +++ b/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy @@ -1,4 +1,4 @@ -proc sort . d[] . +proc sort &d[] . n = len d[] # make heap for i = 2 to n @@ -17,12 +17,8 @@ proc sort . d[] . j = 1 ind = 2 while ind < i - if ind + 1 < i and d[ind + 1] > d[ind] - ind += 1 - . - if d[j] < d[ind] - swap d[j] d[ind] - . + if ind + 1 < i and d[ind + 1] > d[ind] : ind += 1 + if d[j] < d[ind] : swap d[j] d[ind] j = ind ind = 2 * j . diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx index 222e7da632..0c318e4d70 100644 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx @@ -1,22 +1,72 @@ -/*REXX pgm sorts an array (names of epichoric Greek letters) using a heapsort algorithm.*/ -parse arg x; call init /*use args or default, define @ array.*/ -call show "before sort:" /*#: the number of elements in array*/ -call heapSort #; say copies('▒', 40) /*sort; then after sort, show separator*/ -call show " after sort:" -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -init: _= 'alpha beta gamma delta digamma epsilon zeta eta theta iota kappa lambda mu nu' , - "xi omicron pi san qoppa rho sigma tau upsilon phi chi psi omega" - if x='' then x= _; #= words(x) /*#: number of words in X*/ - do j=1 for #; @.j= word(x, j); end; return /*assign letters to array*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -heapSort: procedure expose @.; arg n; do j=n%2 by -1 to 1; call shuffle j,n; end /*j*/ - do n=n by -1 to 2; _= @.1; @.1= @.n; @.n= _; call heapSuff 1,n-1 - end /*n*/; return /* [↑] swap two elements; and shuffle.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -heapSuff: procedure expose @.; parse arg i,n; $= @.i /*obtain parent.*/ - do while i+i<=n; j= i+i; k= j+1; if k<=n then if @.k>@.j then j= k - if $>=@.j then leave; @.i= @.j; i= j - end /*while*/; @.i= $; return /*define lowest.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: do s=1 for #; say ' element' right(s, length(#)) arg(1) @.s; end; return +/* REXX *************************************************************** +* Translated from PL/I +* 27.07.2013 Walter Pachl +**********************************************************************/ + list='---letters of the modern Greek Alphabet---|'||, + '==========================================|'||, + 'alpha|beta|gamma|delta|epsilon|zeta|eta|theta|'||, + 'iota|kappa|lambda|mu|nu|xi|omicron|pi|'||, + 'rho|sigma|tau|upsilon|phi|chi|psi|omega' + Do i=0 By 1 While list<>'' + Parse Var list a.i '|' list + End + n=i-1 + + Call showa 'before sort' + Call heapsort n + Call showa ' after sort' + Exit + + heapSort: Procedure Expose a. + Parse Arg count + Call heapify count + end=count-1 + do while end>0 + Call swap end,0 + end=end-1 + Call siftDown 0,end + End + Return + + heapify: Procedure Expose a. + Parse Arg count + start=(count-2)%2 + Do while start>=0 + Call siftDown start,count-1 + start=start-1 + End + Return + + siftDown: Procedure Expose a. + Parse Arg start,end + root=start + Do while root*2+1<= end + child=root*2+1 + sw=root + if a.swroot Then Do + Call swap root,sw + root=sw + End + else + return + End + Return + + swap: Procedure Expose a. + Parse arg x,y + temp=a.x + a.x=a.y + a.y=temp + Return + + showa: Procedure Expose a. n + Parse Arg txt + Do j=0 To n-1 + Say 'element' format(j,2) txt a.j + End + Return diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx index 0c318e4d70..ac693ac5ea 100644 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx @@ -1,72 +1,62 @@ -/* REXX *************************************************************** -* Translated from PL/I -* 27.07.2013 Walter Pachl -**********************************************************************/ - list='---letters of the modern Greek Alphabet---|'||, - '==========================================|'||, - 'alpha|beta|gamma|delta|epsilon|zeta|eta|theta|'||, - 'iota|kappa|lambda|mu|nu|xi|omicron|pi|'||, - 'rho|sigma|tau|upsilon|phi|chi|psi|omega' - Do i=0 By 1 While list<>'' - Parse Var list a.i '|' list - End - n=i-1 +include Settings - Call showa 'before sort' - Call heapsort n - Call showa ' after sort' - Exit +say 'HEAPSORT - 4 Mar 2025' +say version +say +call Generate +call Show +call Heapsort +call Show +exit - heapSort: Procedure Expose a. - Parse Arg count - Call heapify count - end=count-1 - do while end>0 - Call swap end,0 - end=end-1 - Call siftDown 0,end - End - Return +Generate: +call Random,,12345 +n = 10 +do i = 1 to n + stem.i = Random() +end +stem.0 = n +return - heapify: Procedure Expose a. - Parse Arg count - start=(count-2)%2 - Do while start>=0 - Call siftDown start,count-1 - start=start-1 - End - Return +Show: +do i = 1 to n + say right(i,2) right(stem.i,3) +end +say +return - siftDown: Procedure Expose a. - Parse Arg start,end - root=start - Do while root*2+1<= end - child=root*2+1 - sw=root - if a.swroot Then Do - Call swap root,sw - root=sw - End - else - return - End - Return +HeapSort: +procedure expose stem. +n = stem.0 +if n < 2 then + return +n = stem.0; l = (n%2)+1; s = n +do while 1 + if l > 1 then do + l = l-1; r = stem.l + end + else do + r = stem.s; stem.s = stem.1; s = s-1 + if s = 1 then do + stem.1 = r + leave + end + end + i = l; j = l*2 + do while j <= s + if j < s then do + k = j+1 + if stem.j < stem.k then + j = j+1 + end + if r < stem.j then do + stem.i = stem.j; i = j; j = j+i + end + else + j = s+1 + end + stem.i = r +end +return - swap: Procedure Expose a. - Parse arg x,y - temp=a.x - a.x=a.y - a.y=temp - Return - - showa: Procedure Expose a. n - Parse Arg txt - Do j=0 To n-1 - Say 'element' format(j,2) txt a.j - End - Return +include Abend diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx deleted file mode 100644 index 38b7e57afe..0000000000 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx +++ /dev/null @@ -1,56 +0,0 @@ -Main: -call Generate -call Show -call Heapsort -call Show -exit - -Generate: -call Random,,12345 -n = 10 -do i = 1 to n - stem.i = Random() -end -stem.0 = n -return - -Show: -do i = 1 to n - say right(i,2) right(stem.i,3) -end -say -return - -HeapSort: -procedure expose stem. -n = stem.0 -if n < 2 then - return -n = stem.0; l = (n%2)+1; s = n -do while 1 - if l > 1 then do - l = l-1; r = stem.l - end - else do - r = stem.s; stem.s = stem.1; s = s-1 - if s = 1 then do - stem.1 = r - leave - end - end - i = l; j = l*2 - do while j <= s - if j < s then do - k = j+1 - if stem.j < stem.k then - j = j+1 - end - if r < stem.j then do - stem.i = stem.j; i = j; j = j+i - end - else - j = s+1 - end - stem.i = r -end -return diff --git a/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy b/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy index ae0c415130..cd85b00b0b 100644 --- a/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy +++ b/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy @@ -1,4 +1,4 @@ -proc sort . d[] . +proc sort &d[] . for i = 2 to len d[] h = d[i] j = i - 1 diff --git a/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy b/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy index 784d954f34..eb9af0bcf9 100644 --- a/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy +++ b/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy @@ -1,4 +1,4 @@ -proc sort . d[] . +proc sort &d[] . len tmp[] len d[] sz = 1 while sz < len d[] @@ -7,13 +7,9 @@ proc sort . d[] . while left < len d[] # merge mid = left + sz - 1 - if mid > len d[] - mid = len d[] - . + if mid > len d[] : mid = len d[] right = mid + sz - if right > len d[] - right = len d[] - . + if right > len d[] : right = len d[] l = left r = mid + 1 for i = left to right diff --git a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx index 954c469b17..a68efddb45 100644 --- a/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx +++ b/Task/Sorting-algorithms-Merge-sort/REXX/sorting-algorithms-merge-sort-3.rexx @@ -1,4 +1,8 @@ -Main: +include Settings + +say 'MERGE SORT - 4 Mar 2025' +say version +say call Generate call Show call Mergesort 1,n @@ -65,3 +69,5 @@ do i = b to e stem.i = work.i end return + +include Abend diff --git a/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed b/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed index a4dd852c14..23efdd62c7 100644 --- a/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed +++ b/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed @@ -3,35 +3,10 @@ #true (003) "append" list1 list2 -(car) pair +(cons) item list ========= #true -(002) "car" pair - -(cadr) pair -========= -#true -(002) "cadr" pair - -(cdr) pair -========= -#true -(002) "cdr" pair - -(cddr) pair -========= -#true -(002) "cddr" pair - -(cons) one two -========= -#true -(003) "cons" one two - -(list1a) item -========= -#true -(002) "list" item +(003) "cons" item list (map) function list ========= @@ -39,35 +14,35 @@ (003) "map" function list (merge) comparator list1 list2 -CONTINUE WITH COLLECT ARGUMENT +BRING IN COLLECT ARGUMENT #true (merge01) comparator list1 list2 nil (merge01) comparator list1 list2 collect -LIST2 EXHAUSTED -> MERGED +LIST2 EXHAUSTED (null?) list2 (append) (reverse) collect list1 (merge01) comparator list1 list2 collect -LIST1 EXHAUSTED -> MERGED +LIST1 EXHAUSTED (null?) list1 (append) (reverse) collect list2 (merge01) comparator list1 list2 collect -TAKE FROM LIST2 (HANDLES ONE CASE) -(003) comparator (car) list2 (car) list1 +COMPARATOR CHOOSES LIST2 +(003) comparator (1) list2 (1) list1 (merge01) comparator list1 - (cdr) list2 - (cons) (car) list2 collect + (!) list2 + (cons) (1) list2 collect (merge01) comparator list1 list2 collect -TAKE FROM LIST1 (HANDLES TWO CASES) +NOW TAKE FROM LIST1 (PRIORITY STABILITY) #true (merge01) comparator - (cdr) list1 + (!) list1 list2 - (cons) (car) list1 collect + (cons) (1) list1 collect (null?) value ========= @@ -80,28 +55,47 @@ TAKE FROM LIST1 (HANDLES TWO CASES) (002) "reverse" list (sort) comparator jumble -PREPARE JUMBLE AND PERFORM MERGE PASSES -> EXTRACT +PREPARE JUMBLE AND PERFORM MERGE PASSES #true -(car) (sort02) comparator (sort01) jumble +(sort03) comparator (sort02) comparator (sort01) jumble (sort01) jumble -PREPARED JUMBLE +PREPARE JUMBLE #true -(map) list1a jumble +(map) "list" jumble (sort02) comparator jumble -WHEN ZERO LISTS THEN NIL +EMPTY JUMBLE (null?) jumble nil (sort02) comparator jumble -WHEN ONE LIST THEN ALREADY SORTED -(null?) (cdr) jumble +ONE LIST JUMBLE +(null?) (!) jumble jumble (sort02) comparator jumble -REPEATEDLY MERGE ALONG LENGTH +PERFORM MERGE PASS #true -(sort02) comparator - (cons) (merge) comparator (car) jumble (cadr) jumble - (sort02) comparator (cddr) jumble +(cons) (merge) comparator (1) jumble (1) (!) jumble + (sort02) comparator (!) (!) jumble + +(sort03) comparator jumble +EMPTY JUMBLE +(null?) jumble +nil + +(sort03) comparator jumble +ONE LIST JUMBLE +(null?) (!) jumble +(1) jumble + +(sort03) comparator jumble +PERFORM MERGE PASS AND RESTART +#true +(sort03) comparator (sort02) comparator jumble + +(main) +ENTRY POINT +#true +(002) "display" (sort) ">" (010) "list" 4 3 5 6 8 7 1 2 9 diff --git a/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy b/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy index 24657b1535..e346d94ad2 100644 --- a/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy +++ b/Task/Sorting-algorithms-Pancake-sort/EasyLang/sorting-algorithms-pancake-sort.easy @@ -1,5 +1,5 @@ global a[] . -proc flip n . . +proc flip n . for i = 1 to n div 2 swap a[i] a[n - i + 1] . @@ -17,7 +17,7 @@ func[] minmax n . . return [ pmin pmax ] . -proc pcsort n dir . . +proc pcsort n dir . if n = 1 return . diff --git a/Task/Sorting-algorithms-Patience-sort/EasyLang/sorting-algorithms-patience-sort.easy b/Task/Sorting-algorithms-Patience-sort/EasyLang/sorting-algorithms-patience-sort.easy new file mode 100644 index 0000000000..adc571cbce --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/EasyLang/sorting-algorithms-patience-sort.easy @@ -0,0 +1,29 @@ +proc patience_sort &nums[] . + for num in nums[] + for p to len piles[][] + if num >= piles[p][len piles[p][]] + piles[p][] &= num + break 1 + . + . + if p > len piles[][] : piles[][] &= [ num ] + . + for i to len nums[] + dest = 1 + for p = 2 to len piles[][] + if piles[p][1] < piles[dest][1] : dest = p + . + nums[i] = piles[dest][1] + for j = 2 to len piles[dest][] + piles[dest][j - 1] = piles[dest][j] + . + len piles[dest][] -1 + if len piles[dest][] = 0 + swap piles[dest][] piles[$][] + len piles[][] -1 + . + . +. +nums[] = [ 10 6 -30 9 18 1 -20 ] +patience_sort nums[] +print nums[] diff --git a/Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs b/Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs new file mode 100644 index 0000000000..c4f1dbc87a --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/Rust/sorting-algorithms-patience-sort.rs @@ -0,0 +1,95 @@ +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +// We define a custom Pile struct instead of using Stack +#[derive(Clone, Eq, PartialEq)] +struct Pile { + values: Vec, +} + +impl Pile { + fn new(value: T) -> Self { + let mut values = Vec::new(); + values.push(value); + Pile { values } + } + + fn push(&mut self, value: T) { + self.values.push(value); + } + + fn pop(&mut self) -> Option { + self.values.pop() + } + + fn top(&self) -> Option<&T> { + self.values.last() + } + + fn is_empty(&self) -> bool { + self.values.is_empty() + } +} + +// For binary heap ordering (min-heap) +impl Ord for Pile { + fn cmp(&self, other: &Self) -> Ordering { + // Reverse the ordering for min-heap + other.top().cmp(&self.top()) + } +} + +impl PartialOrd for Pile { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +fn patience_sort(slice: &mut [T]) { + let mut piles: Vec> = Vec::new(); + + // Sort into piles + for item in slice.iter().cloned() { + // Find the pile to insert into + let idx = match piles.binary_search_by(|pile| { + if let Some(top) = pile.top() { + top.cmp(&item) + } else { + Ordering::Greater // Should not happen + } + }) { + Ok(idx) => idx, // Found a pile with the same top value + Err(idx) => idx, // Position where we should insert new pile + }; + + if idx < piles.len() { + piles[idx].push(item); + } else { + piles.push(Pile::new(item)); + } + } + + // Convert to BinaryHeap for efficient merging + let mut heap = BinaryHeap::from(piles); + + // Merge piles + for item_slot in slice.iter_mut() { + if let Some(mut smallest_pile) = heap.pop() { + if let Some(top) = smallest_pile.pop() { + *item_slot = top; + + if !smallest_pile.is_empty() { + heap.push(smallest_pile); + } + } + } + } + + assert!(heap.is_empty()); +} + +fn main() { + let mut a = [4, 65, 2, -31, 0, 99, 83, 782, 1]; + patience_sort(&mut a); + println!("{:?}", a); +} diff --git a/Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig b/Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig new file mode 100644 index 0000000000..e53cf138df --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/Zig/sorting-algorithms-patience-sort.zig @@ -0,0 +1,138 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; +const PriorityQueue = std.PriorityQueue; + +// Pile structure to represent a stack of items +fn Pile(comptime T: type) type { + return struct { + values: ArrayList(T), + + const Self = @This(); + + fn init(allocator: Allocator) Self { + return Self{ + .values = ArrayList(T).init(allocator), + }; + } + + fn deinit(self: *Self) void { + self.values.deinit(); + } + + fn push(self: *Self, value: T) !void { + try self.values.append(value); + } + + fn pop(self: *Self) ?T { + if (self.values.items.len == 0) return null; + return self.values.pop(); + } + + fn top(self: *const Self) ?T { + if (self.values.items.len == 0) return null; + return self.values.items[self.values.items.len - 1]; + } + + fn isEmpty(self: *const Self) bool { + return self.values.items.len == 0; + } + }; +} + +// Compare function for priority queue (min-heap) +fn pileGreaterThan(comptime T: type) type { + return struct { + pub fn compare(context: void, a: *const Pile(T), b: *const Pile(T)) std.math.Order { + _ = context; + const a_top = a.top() orelse return .lt; + const b_top = b.top() orelse return .gt; + return if (a_top > b_top) .lt else if (a_top < b_top) .gt else .eq; + } + }; +} + +// Patience sort implementation +fn patienceSort(comptime T: type, allocator: Allocator, slice: []T) !void { + const PileT = Pile(T); + var piles = ArrayList(*PileT).init(allocator); + defer { + // Clean up all piles regardless of how we exit the function + for (piles.items) |pile| { + pile.deinit(); + allocator.destroy(pile); + } + piles.deinit(); + } + + // Sort into piles + for (slice) |item| { + // Try to find an existing pile to add to + var added = false; + for (piles.items) |pile| { + if (pile.top()) |top| { + if (top > item) { + try pile.push(item); + added = true; + break; + } + } + } + + // If no suitable pile found, create a new one + if (!added) { + var new_pile = try allocator.create(PileT); + errdefer allocator.destroy(new_pile); + + new_pile.* = PileT.init(allocator); + errdefer new_pile.deinit(); + + try new_pile.push(item); + try piles.append(new_pile); + } + } + + // Create a priority queue for efficient merging + var queue = PriorityQueue(*PileT, void, pileGreaterThan(T).compare).init(allocator, {}); + defer queue.deinit(); + + // Add all piles to the priority queue + for (piles.items) |pile| { + try queue.add(pile); + } + + // Merge piles back into the original slice + var i: usize = 0; + while (queue.count() > 0) { + const smallest_pile = queue.remove(); + if (smallest_pile.pop()) |value| { + slice[i] = value; + i += 1; + + if (!smallest_pile.isEmpty()) { + try queue.add(smallest_pile); + } + } + } + + std.debug.assert(i == slice.len); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var a = [_]i32{ 4, 65, 2, -31, 0, 99, 83, 782, 1 }; + try patienceSort(i32, allocator, &a); + + const stdout = std.io.getStdOut().writer(); + try stdout.print("Sorted array: ", .{}); + for (a, 0..) |value, i| { + try stdout.print("{}", .{value}); + if (i < a.len - 1) { + try stdout.print(", ", .{}); + } + } + try stdout.print("\n", .{}); +} diff --git a/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy b/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy index fa9ff44ab4..eedd40067d 100644 --- a/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy +++ b/Task/Sorting-algorithms-Permutation-sort/EasyLang/sorting-algorithms-permutation-sort.easy @@ -1,18 +1,11 @@ global perm[] . -proc nextperm . a[] . +proc nextperm &a[] &k . n = len perm[] k = n - 1 - while k >= 1 and perm[k + 1] <= perm[k] - k -= 1 - . - if k = 0 - a[] = [ ] - return - . + while k >= 1 and perm[k + 1] <= perm[k] : k -= 1 + if k = 0 : return l = n - while perm[l] <= perm[k] - l -= 1 - . + while perm[l] <= perm[k] : l -= 1 swap perm[l] perm[k] swap a[l] a[k] k += 1 @@ -23,22 +16,18 @@ proc nextperm . a[] . n -= 1 . . -proc perminit . a[] . - for i to len a[] - perm[] &= i - . +proc perminit &a[] . + for i to len a[] : perm[] &= i . -proc permsort . a[] . +proc permsort &a[] . perminit a[] repeat for i = 2 to len a[] - if a[i - 1] > a[i] - break 1 - . + if a[i - 1] > a[i] : break 1 . until i > len a[] - nextperm a[] - if len a[] = 0 + nextperm a[] more + if more = 0 print "error" break 1 . diff --git a/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy b/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy index 7ddf5cf8ad..6dec150579 100644 --- a/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy +++ b/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy @@ -1,19 +1,19 @@ -proc qsort left right . d[] . - if left >= right - return - . - mid = left - for i = left + 1 to right - if d[i] < d[left] - mid += 1 - swap d[i] d[mid] +proc qsort left right &d[] . + if left < right + piv = d[left] + mid = left + for i = left + 1 to right + if d[i] < piv + mid += 1 + swap d[i] d[mid] + . . + swap d[left] d[mid] + qsort left mid - 1 d[] + qsort mid + 1 right d[] . - swap d[left] d[mid] - qsort left mid - 1 d[] - qsort mid + 1 right d[] . -proc sort . d[] . +proc sort &d[] . qsort 1 len d[] d[] . d[] = [ 29 4 72 44 55 26 27 77 92 5 ] diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k index 38d72b5d2a..d4a77e73e9 100644 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-8.k @@ -1 +1,2 @@ t@@.k then return 0; end; return 1 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -qSort: procedure expose @.; a.1=1; parse arg b.1; $= 1 /*access @.; get @. size; pivot.*/ - if inOrder(b.1) then return /*Array already in order? Return*/ - do while $\==0; L= a.$; t= b.$; $= $ - 1; if t<2 then iterate - H= L + t - 1; ?= L + t % 2 - if @.H<@.L then if @.?<@.H then do; p= @.H; @.H= @.L; end - else if @.?>@.L then p= @.L - else do; p= @.?; @.?= @.L; end - else if @.?<@.L then p=@.L - else if @.?>@.H then do; p= @.H; @.H= @.L; end - else do; p= @.?; @.?= @.L; end - j= L+1; k= h - do forever - do j=j while j<=k & @.j<=p; end /*a teeny─tiny loop.*/ - do k=k by -1 while j< k & @.k>=p; end /*another " " */ - if j>=k then leave /*segment finished? */ - _= @.j; @.j= @.k; @.k= _ /*swap J&K elements.*/ - end /*forever*/ - $= $ + 1 - k= j - 1; @.L= @.k; @.k= p - if j<=? then do; a.$= j; b.$= H-j+1; $= $+1; a.$= L; b.$= k-L; end - else do; a.$= L; b.$= k-L; $= $+1; a.$= j; b.$= H-j+1; end - end /*while $¬==0*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show@: w= length(#); do j=1 for #; say 'element' right(j,w) arg(1)":" @.j; end - say copies('▒', maxL + w + 22) /*display a separator (between outputs)*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -gen@: @.=; maxL=0 /*assign a default value for the array.*/ - @.1 = " Rivers that form part of a (USA) state's border " /*this value is adjusted later to include a prefix & suffix.*/ - @.2 = '=' /*this value is expanded later. */ - @.3 = "Perdido River Alabama, Florida" - @.4 = "Chattahoochee River Alabama, Georgia" - @.5 = "Tennessee River Alabama, Kentucky, Mississippi, Tennessee" - @.6 = "Colorado River Arizona, California, Nevada, Baja California (Mexico)" - @.7 = "Mississippi River Arkansas, Illinois, Iowa, Kentucky, Minnesota, Mississippi, Missouri, Tennessee, Louisiana, Wisconsin" - @.8 = "St. Francis River Arkansas, Missouri" - @.9 = "Poteau River Arkansas, Oklahoma" - @.10 = "Arkansas River Arkansas, Oklahoma" - @.11 = "Red River (Mississippi watershed) Arkansas, Oklahoma, Texas" - @.12 = "Byram River Connecticut, New York" - @.13 = "Pawcatuck River Connecticut, Rhode Island and Providence Plantations" - @.14 = "Delaware River Delaware, New Jersey, New York, Pennsylvania" - @.15 = "Potomac River District of Columbia, Maryland, Virginia, West Virginia" - @.16 = "St. Marys River Florida, Georgia" - @.17 = "Chattooga River Georgia, South Carolina" - @.18 = "Tugaloo River Georgia, South Carolina" - @.19 = "Savannah River Georgia, South Carolina" - @.20 = "Snake River Idaho, Oregon, Washington" - @.21 = "Wabash River Illinois, Indiana" - @.22 = "Ohio River Illinois, Indiana, Kentucky, Ohio, West Virginia" - @.23 = "Great Miami River (mouth only) Indiana, Ohio" - @.24 = "Des Moines River Iowa, Missouri" - @.25 = "Big Sioux River Iowa, South Dakota" - @.26 = "Missouri River Kansas, Iowa, Missouri, Nebraska, South Dakota" - @.27 = "Tug Fork River Kentucky, Virginia, West Virginia" - @.28 = "Big Sandy River Kentucky, West Virginia" - @.29 = "Pearl River Louisiana, Mississippi" - @.30 = "Sabine River Louisiana, Texas" - @.31 = "Monument Creek Maine, New Brunswick (Canada)" - @.32 = "St. Croix River Maine, New Brunswick (Canada)" - @.33 = "Piscataqua River Maine, New Hampshire" - @.34 = "St. Francis River Maine, Quebec (Canada)" - @.35 = "St. John River Maine, Quebec (Canada)" - @.36 = "Pocomoke River Maryland, Virginia" - @.37 = "Palmer River Massachusetts, Rhode Island and Providence Plantations" - @.38 = "Runnins River Massachusetts, Rhode Island and Providence Plantations" - @.39 = "Montreal River Michigan (upper peninsula), Wisconsin" - @.40 = "Detroit River Michigan, Ontario (Canada)" - @.41 = "St. Clair River Michigan, Ontario (Canada)" - @.42 = "St. Marys River Michigan, Ontario (Canada)" - @.43 = "Brule River Michigan, Wisconsin" - @.44 = "Menominee River Michigan, Wisconsin" - @.45 = "Red River of the North Minnesota, North Dakota" - @.46 = "Bois de Sioux River Minnesota, North Dakota, South Dakota" - @.47 = "Pigeon River Minnesota, Ontario (Canada)" - @.48 = "Rainy River Minnesota, Ontario (Canada)" - @.49 = "St. Croix River Minnesota, Wisconsin" - @.50 = "St. Louis River Minnesota, Wisconsin" - @.51 = "Halls Stream New Hampshire, Canada" - @.52 = "Salmon Falls River New Hampshire, Maine" - @.53 = "Connecticut River New Hampshire, Vermont" - @.54 = "Arthur Kill New Jersey, New York (tidal strait)" - @.55 = "Kill Van Kull New Jersey, New York (tidal strait)" - @.56 = "Hudson River (lower part only) New Jersey, New York" - @.57 = "Rio Grande New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila de Zaragoza (Mexico), Chihuahua (Mexico)" - @.58 = "Niagara River New York, Ontario (Canada)" - @.59 = "St. Lawrence River New York, Ontario (Canada)" - @.60 = "Poultney River New York, Vermont" - @.61 = "Catawba River North Carolina, South Carolina" - @.62 = "Blackwater River North Carolina, Virginia" - @.63 = "Columbia River Oregon, Washington" - do #=1 until @.#=='' /*find how many entries in array, and */ - maxL=max(maxL, length(@.#)) /* also find the maximum width entry.*/ - end /*#*/; #= #-1 /*adjust the highest element number. */ - @.1= center(@.1, maxL, '-') /* " " header information. */ - @.2= copies(@.2, maxL) /* " " " separator. */ - return +/*REXX*/ + a = '4 65 2 -31 0 99 83 782 1' + do i = 1 to words(a) + queue word(a, i) + end + call quickSort + parse pull item + do queued() + call charout ,item', ' + parse pull item + end + say item + exit + +quickSort: procedure +/* In classic Rexx, arguments are passed by value, not by reference so stems + cannot be passed as arguments nor used as return values. Putting their + contents on the external data queue is a way to bypass this issue. */ + + /* construct the input stem */ + arr.0 = queued() + do i = 1 to arr.0 + parse pull arr.i + end + less.0 = 0 + pivotList.0 = 0 + more.0 = 0 + if arr.0 <= 1 then do + if arr.0 = 1 then + queue arr.1 + return + end + else do + pivot = arr.1 + do i = 1 to arr.0 + item = arr.i + select + when item < pivot then do + j = less.0 + 1 + less.j = item + less.0 = j + end + when item > pivot then do + j = more.0 + 1 + more.j = item + more.0 = j + end + otherwise + j = pivotList.0 + 1 + pivotList.j = item + pivotList.0 = j + end + end + end + /* recursive call to sort the less. stem */ + do i = 1 to less.0 + queue less.i + end + if queued() > 0 then do + call quickSort + less.0 = queued() + do i = 1 to less.0 + parse pull less.i + end + end + /* recursive call to sort the more. stem */ + do i = 1 to more.0 + queue more.i + end + if queued() > 0 then do + call quickSort + more.0 = queued() + do i = 1 to more.0 + parse pull more.i + end + end + /* put the contents of all 3 stems on the queue in order */ + do i = 1 to less.0 + queue less.i + end + do i = 1 to pivotList.0 + queue pivotList.i + end + do i = 1 to more.0 + queue more.i + end + return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx index 609b0364fb..5b58ec3e8d 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-2.rexx @@ -1,87 +1,24 @@ -/*REXX*/ - a = '4 65 2 -31 0 99 83 782 1' - do i = 1 to words(a) - queue word(a, i) - end - call quickSort - parse pull item - do queued() - call charout ,item', ' - parse pull item - end - say item - exit - -quickSort: procedure -/* In classic Rexx, arguments are passed by value, not by reference so stems - cannot be passed as arguments nor used as return values. Putting their - contents on the external data queue is a way to bypass this issue. */ - - /* construct the input stem */ - arr.0 = queued() - do i = 1 to arr.0 - parse pull arr.i - end - less.0 = 0 - pivotList.0 = 0 - more.0 = 0 - if arr.0 <= 1 then do - if arr.0 = 1 then - queue arr.1 - return - end - else do - pivot = arr.1 - do i = 1 to arr.0 - item = arr.i - select - when item < pivot then do - j = less.0 + 1 - less.j = item - less.0 = j - end - when item > pivot then do - j = more.0 + 1 - more.j = item - more.0 = j - end - otherwise - j = pivotList.0 + 1 - pivotList.j = item - pivotList.0 = j - end - end - end - /* recursive call to sort the less. stem */ - do i = 1 to less.0 - queue less.i - end - if queued() > 0 then do - call quickSort - less.0 = queued() - do i = 1 to less.0 - parse pull less.i - end - end - /* recursive call to sort the more. stem */ - do i = 1 to more.0 - queue more.i - end - if queued() > 0 then do - call quickSort - more.0 = queued() - do i = 1 to more.0 - parse pull more.i - end - end - /* put the contents of all 3 stems on the queue in order */ - do i = 1 to less.0 - queue less.i - end - do i = 1 to pivotList.0 - queue pivotList.i - end - do i = 1 to more.0 - queue more.i - end - return +Elegant: +procedure expose stem. +push 1 stem.0 +do while queued() > 0 + pull l r + if l < r then do + m = (l+r)%2; p = stem.m; i = l-1; j = r+1 + do forever + do until stem.j <= p + j = j-1 + end + do until stem.i >= p + i = i+1 + end + if i < j then do + t = stem.i; stem.i = stem.j; stem.j = t + end + else + leave + end + push l j; push j+1 r + end +end +return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx index 5b58ec3e8d..4b7e097a83 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-3.rexx @@ -1,24 +1,20 @@ -Elegant: +Recursive: procedure expose stem. -push 1 stem.0 -do while queued() > 0 - pull l r - if l < r then do - m = (l+r)%2; p = stem.m; i = l-1; j = r+1 - do forever - do until stem.j <= p - j = j-1 - end - do until stem.i >= p - i = i+1 - end - if i < j then do - t = stem.i; stem.i = stem.j; stem.j = t - end - else - leave - end - push l j; push j+1 r +arg l r +m = (l+r)%2; p = stem.m +i = l; j = r +do while i <= j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 end end +if l < j then + call Recursive l j +if i < r then + call Recursive i r return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx index 4b7e097a83..a35b358c85 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-4.rexx @@ -1,20 +1,56 @@ -Recursive: +Optimized: procedure expose stem. -arg l r -m = (l+r)%2; p = stem.m -i = l; j = r -do while i <= j - do i = i while stem.i < p - end - do j = j by -1 while stem.j > p - end - if i <= j then do - t = stem.i; stem.i = stem.j; stem.j = t - i = i+1; j = j-1 +n = stem.0; s = 1; sl.1 = 1; sr.1 = n +do until s = 0 + l = sl.s; r = sr.s; s = s-1 + do until l >= r + if r-l < 11 then do + do i = l+1 to r + a = stem.i + do j=i-1 by -1 to l while stem.j > a + k = j+1; stem.k = stem.j + end + k = j+1; stem.k = a + end + if s = 0 then + leave + l = sl.s; r = sr.s; s = s-1 + end + else do + m = (l+r)%2 + if stem.l > stem.m then do + t = stem.l; stem.l = stem.m; stem.m = t + end + if stem.l > stem.r then do + t = stem.l; stem.l = stem.r; stem.r = t + end + if stem.m > stem.r then do + t = stem.m; stem.m = stem.r; stem.r = t + end + i = l; j = r; p = stem.m + do until i > j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 + end + end + if j-l < r-i then do + if i < r then do + s = s+1; sl.s = i; sr.s = r + end + r = j + end + else do + if l < j then do + s = s+1; sl.s = l; sr.s = j + end + l = i + end + end end end -if l < j then - call Recursive l j -if i < r then - call Recursive i r return diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx index a35b358c85..ce394a34f1 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-5.rexx @@ -1,10 +1,204 @@ +include Settings + +say 'QUICKSORT - 4 Mar 2025' +say version +say +numeric digits 9 +arg n v +if n = '' then n = 10 +if v = '' then v = 1 +show = (n > 0); n = Abs(n) +say 'Timing Version' v 'for' n 'random numbers' +call Generate +if show then call ShowSave +if v = 0 | v = 1 then do + call Time 'r'; call Save2Stack; say 'Save2Stack' format(time('e'),3,3) 'seconds' + call Time 'r'; call Quicksort; say 'Quicksort ' format(time('e'),3,3) 'seconds' + call Time 'r'; call Stack2Stem; say 'Stack2Stem' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +if v = 0 | v = 2 then do + call Save2Stem + call Time 'r'; call Elegant; say 'Elegant' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +if v = 0 | v = 3 then do + call Save2Stem + call Time 'r'; call Recursive 1 n; say 'Recursive' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +if v = 0 | v = 4 then do + call Save2Stem + call Time 'r'; call Optimized; say 'Optimized' format(time('e'),3,3) 'seconds' + if show then call ShowStem +end +say +exit + +Generate: +do x = 1 to n + save.x = 10000*Random(0,9999)+Random(0,9999) +end +save.0 = n +return + +ShowSave: +do x = 1 to 5 + say x save.x +end +do x = n-4 to n + say x save.x +end +say +return + +ShowStem: +do x = 1 to 5 + say x stem.x +end +do x = n-4 to n + say x stem.x +end +say +return + +Save2Stem: +do x = 0 to n + stem.x = save.x +end +return + +Save2Stack: +do x = 1 to n + queue save.x +end +return + +Quicksort: procedure +arr.0 = queued() +do i = 1 to arr.0 + parse pull arr.i +end +less.0 = 0 +pivotList.0 = 0 +more.0 = 0 +if arr.0 <= 1 then do + if arr.0 = 1 then + queue arr.1 + return +end +else do + pivot = arr.1 + do i = 1 to arr.0 + item = arr.i + select + when item < pivot then do + j = less.0 + 1 + less.j = item + less.0 = j + end + when item > pivot then do + j = more.0 + 1 + more.j = item + more.0 = j + end + otherwise + j = pivotList.0 + 1 + pivotList.j = item + pivotList.0 = j + end + end +end +do i = 1 to less.0 + queue less.i +end +if queued() > 0 then do + call quickSort + less.0 = queued() + do i = 1 to less.0 + parse pull less.i + end +end +do i = 1 to more.0 + queue more.i +end +if queued() > 0 then do + call quickSort + more.0 = queued() + do i = 1 to more.0 + parse pull more.i + end +end +do i = 1 to less.0 + queue less.i +end +do i = 1 to pivotList.0 + queue pivotList.i +end +do i = 1 to more.0 + queue more.i +end +return + +Stack2Stem: +do x = 1 to n + parse pull stem.x +end +return + +Elegant: +procedure expose stem. +push 1 stem.0 +do while queued() > 0 + pull l r + if l < r then do + m = (l+r)%2; p = stem.m; i = l-1; j = r+1 + do forever + do until stem.j <= p + j = j-1 + end + do until stem.i >= p + i = i+1 + end + if i < j then do + t = stem.i; stem.i = stem.j; stem.j = t + end + else + leave + end + push l j; push j+1 r + end +end +return + +Recursive: +procedure expose stem. +arg l r +m = (l+r)%2; p = stem.m +i = l; j = r +do while i <= j + do i = i while stem.i < p + end + do j = j by -1 while stem.j > p + end + if i <= j then do + t = stem.i; stem.i = stem.j; stem.j = t + i = i+1; j = j-1 + end +end +if l < j then + call Recursive l j +if i < r then + call Recursive i r +return + Optimized: procedure expose stem. n = stem.0; s = 1; sl.1 = 1; sr.1 = n do until s = 0 l = sl.s; r = sr.s; s = s-1 do until l >= r - if r-l < 11 then do + if r-l < 20 then do do i = l+1 to r a = stem.i do j=i-1 by -1 to l while stem.j > a @@ -54,3 +248,5 @@ do until s = 0 end end return + +include Abend diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-6.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-6.rexx deleted file mode 100644 index daf32e907d..0000000000 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-6.rexx +++ /dev/null @@ -1,73 +0,0 @@ -numeric digits 9 -parse version version; say version Digits() 'digits' -arg n v -if n = '' then n = 10 -if v = '' then v = 1 -show = (n > 0); n = Abs(n) -say 'Quicksort: Timing Version' v 'for' n 'random numbers' -call Generate -if show then call ShowSave -select - when v = 1 then do - call Save2Stem - call Time 'r'; call Qsort n; say 'Qsort' format(time('e'),3,3) 'seconds' - if show then call ShowStem - end - when v = 2 then do - call Time 'r'; call Save2Stack; say 'Save2Stack' format(time('e'),3,3) 'seconds' - call Time 'r'; call Quicksort; say 'Quicksort ' format(time('e'),3,3) 'seconds' - call Time 'r'; call Stack2Stem; say 'Stack2Stem' format(time('e'),3,3) 'seconds' - if show then call ShowStem - end - when v = 3 then do - call Save2Stem - call Time 'r'; call Elegant; say 'Elegant' format(time('e'),3,3) 'seconds' - if show then call ShowStem - end - when v = 4 then do - call Save2Stem - call Time 'r'; call Recursive 1 n; say 'Recursive' format(time('e'),3,3) 'seconds' - if show then call ShowStem - end - when v = 5 then do - call Save2Stem - call Time 'r'; call Optimized; say 'Optimized' format(time('e'),3,3) 'seconds' - if show then call ShowStem - end - otherwise nop -end -say -exit - -Generate: -do x = 1 to n - save.x = 10000*Random(0,9999)+Random(0,9999) -end -save.0 = n -return - -ShowSave: -do x = 1 to 5 - say x save.x -end -do x = n-4 to n - say x save.x -end -return - -ShowStem: -do x = 1 to 5 - say x stem.x -end -do x = n-4 to n - say x stem.x -end -return - -Save2Stem: -do x = 0 to n - stem.x = save.x -end -return - -/* Sorting procedures follow, not shown here */ diff --git a/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy b/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy index 71f9c57887..c13423805d 100644 --- a/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy +++ b/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy @@ -1,18 +1,14 @@ -proc sort . d[] . +proc sort &d[] . # radix = 10 radix = 256 - max = 0 + max = -1 / 0 for di = 1 to len d[] - if d[di] > max - max = d[di] - . + max = higher d[di] max . len buck[][] radix pos = 1 while pos <= max - for i = 1 to radix - len buck[i][] 0 - . + for i = 1 to radix : len buck[i][] 0 for di = 1 to len d[] h = d[di] div pos mod radix + 1 buck[h][] &= d[di] diff --git a/Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js b/Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js new file mode 100644 index 0000000000..9ec9b38028 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/JavaScript/sorting-algorithms-radix-sort.js @@ -0,0 +1,60 @@ +// Radix sort comparator for 32-bit two's complement integers +class RadixTest { + constructor(bit) { + this.bit = bit; // bit position [0..31] to examine + } + + // function call operator (simulated with a method) + test(value) { + if (this.bit === 31) { // sign bit + return value < 0; // negative int to left partition + } else { + return !(value & (1 << this.bit)); // 0 bit to left partition + } + } +} + +// Helper function to partition an array in place +function partition(arr, start, end, radixTest) { + let i = start - 1; + + for (let j = start; j < end; j++) { + if (radixTest.test(arr[j])) { + i++; + // Swap arr[i] and arr[j] + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + } + return i + 1; +} + +// Least significant digit radix sort +function lsdRadixSort(arr) { + for (let lsb = 0; lsb < 32; ++lsb) { // least-significant-bit + const radixTest = new RadixTest(lsb); + partition(arr, 0, arr.length, radixTest); + } +} + +// Most significant digit radix sort (recursive) +function msdRadixSort(arr, start = 0, end = arr.length, msb = 31) { + if (start < end -1 && msb >= 0) { // changed (first != last) to (start < end-1) for easier indexing + const radixTest = new RadixTest(msb); + let mid = partition(arr, start, end, radixTest); + msb--; // decrement most-significant-bit + msdRadixSort(arr, start, mid, msb); // sort left partition + msdRadixSort(arr, mid, end, msb); // sort right partition + } +} + +// test radix_sort +function main() { + let data = [170, 45, 75, -90, -802, 24, 2, 66]; + + lsdRadixSort(data); + // msdRadixSort(data); + + console.log(data.join(" ")); +} + +main(); diff --git a/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort.rs b/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-1.rs similarity index 80% rename from Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort.rs rename to Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-1.rs index eff59ff502..c6aeb4717a 100644 --- a/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort.rs +++ b/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-1.rs @@ -6,13 +6,11 @@ fn merge(in1: &[i32], in2: &[i32], out: &mut [i32]) { // least significant digit radix sort fn radix_sort(data: &mut [i32]) { - for bit in 0..31 { - // types of small and big is Vec. - // It will be infered from the next call of merge function. + for bit in 0..i32::BITS - 1 { let (small, big): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| (x >> bit) & 1 == 0); merge(&small, &big, data); } - // last bit is sign + // lastly, handle the sign bit let (negative, positive): (Vec<_>, Vec<_>) = data.iter().partition(|&&x| x < 0); merge(&negative, &positive, data); } diff --git a/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-2.rs b/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-2.rs new file mode 100644 index 0000000000..4f4fe5a551 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-2.rs @@ -0,0 +1,24 @@ +fn radix_sort(arr: &mut [u32]) { + let mut buf = vec![0; arr.len()]; + + // Optional: Reduce the amount of iterations by finding the max value bit + let max_bit = u32::BITS - arr.iter().max().map(|t| t.leading_zeros()).unwrap_or(0); + + for bit in 0..max_bit { + // Manual implementation of partition with only one buffer array + let mut a = 0; + let mut b = 0; + + for i in 0..arr.len() { + if arr[i] >> bit & 1 == 0 { + arr[a] = arr[i]; + a += 1; + } else { + buf[b] = arr[i]; + b += 1; + } + } + + arr[a..].copy_from_slice(&buf[..b]); + } +} diff --git a/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-3.rs b/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-3.rs new file mode 100644 index 0000000000..134ee19285 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Rust/sorting-algorithms-radix-sort-3.rs @@ -0,0 +1,40 @@ +fn radix_sort(arr: &mut [i32]) { + let mut buf = vec![0; arr.len()]; + + // Optional: Reduce the number of iterations by finding the max value bit + let max_bit = arr.iter().fold(0, |acc, x| { + let bits = if x.is_negative() { + i32::BITS - x.leading_ones() // Negative msb is always 1 so leading_ones() >= 1 + } else { + i32::BITS - x.leading_zeros() // Positive/zero msb is always 0 so leading_zeros() >= 1 + }; + + core::cmp::max(acc, bits) + }); + let sign_bit = i32::BITS - 1; + + // Manual implementation of partition with only one buffer array + let mut partition = |bit: u32| { + let mut a = 0; + let mut b = 0; + + for i in 0..arr.len() { + // Flip the sign bit before comparing so negatives are always ordered before positives + if (arr[i] ^ i32::MIN) >> bit & 1 == 0 { + arr[a] = arr[i]; + a += 1; + } else { + buf[b] = arr[i]; + b += 1; + } + } + + arr[a..].copy_from_slice(&buf[..b]); + }; + + // This will not duplicate work because max_bits <= sign_bit therefore bit < sign_bit + for bit in 0..max_bit { + partition(bit); + } + partition(sign_bit); +} diff --git a/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy b/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy index 36082f6d15..38cda3ad29 100644 --- a/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy +++ b/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy @@ -1,10 +1,6 @@ -proc sort . d[] . - for i = 1 to len d[] - 1 - for j = i + 1 to len d[] - if d[j] < d[i] - swap d[j] d[i] - . - . +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] diff --git a/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy b/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy index 81c18775a5..857b2c90d5 100644 --- a/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy +++ b/Task/Sorting-algorithms-Shell-sort/EasyLang/sorting-algorithms-shell-sort.easy @@ -1,4 +1,4 @@ -proc shellsort . a[] . +proc shellsort &a[] . inc = len a[] div 2 while inc > 0 for i = inc to len a[] diff --git a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js index a030ead4be..0fcca43ba1 100644 --- a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js +++ b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-1.js @@ -1,5 +1,5 @@ -Array.prototype.timeoutSort = function (f) { - this.forEach(function (n) { - setTimeout(function () { f(n) }, 5 * n) - }); -} +Object.defineProperty(Array.prototype, "timeoutSort", { + value(f) { + this.forEach(n => setTimeout(() => f(n), 5 * n)) + } +}) diff --git a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js index 7fbd5cac3e..e9e6fe998d 100644 --- a/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js +++ b/Task/Sorting-algorithms-Sleep-sort/JavaScript/sorting-algorithms-sleep-sort-2.js @@ -1 +1 @@ -[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(function(n) { document.write(n + '
'); }) +[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(n => document.write(n + '
')) diff --git a/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy b/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy index 09be1a07d4..cd0b4f10d6 100644 --- a/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy +++ b/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy @@ -1,7 +1,5 @@ -proc stsort left right . d[] . - if d[left] > d[right] - swap d[left] d[right] - . +proc stsort left right &d[] . + if d[left] > d[right] : swap d[left] d[right] if right - left + 1 > 2 t = (right - left + 1) div 3 stsort left right - t d[] @@ -9,8 +7,6 @@ proc stsort left right . d[] . stsort left right - t d[] . . -for i = 1 to 100 - d[] &= random 1000 -. +for i = 1 to 100 : d[] &= random 1000 stsort 1 len d[] d[] print d[] diff --git a/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy b/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy index 484f6e4117..0e46dafbb8 100644 --- a/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy +++ b/Task/Sorting-algorithms-Strand-sort/EasyLang/sorting-algorithms-strand-sort.easy @@ -1,4 +1,4 @@ -proc merge . a[] b[] . +proc merge &a[] &b[] . a = 1 ; b = 1 while a <= len a[] and b <= len b[] if a[a] < b[b] @@ -19,7 +19,7 @@ proc merge . a[] b[] . . swap a[] r[] . -proc strand . a[] s[] . +proc strand &a[] &s[] . s[] = [ a[1] ] for i = 2 to len a[] if a[i] > s[$] @@ -30,7 +30,7 @@ proc strand . a[] s[] . . swap a[] an[] . -proc strandsort . a[] . +proc strandsort &a[] . strand a[] out[] while len a[] > 0 strand a[] b[] diff --git a/Task/Sorting-algorithms-Strand-sort/FreeBASIC/sorting-algorithms-strand-sort.basic b/Task/Sorting-algorithms-Strand-sort/FreeBASIC/sorting-algorithms-strand-sort.basic new file mode 100644 index 0000000000..363a614554 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/FreeBASIC/sorting-algorithms-strand-sort.basic @@ -0,0 +1,100 @@ +Sub strandSort(bs() As Long) + Dim As Long subList() + Dim As Long results() + Dim As Long i, j, k + Dim As Long lb = LBound(bs), ub = UBound(bs) + + ' Initialize results array with zero elements + ReDim results(-1) + + While ub >= lb + ReDim subList(0) + subList(0) = bs(lb) + + ' Remove the first element + For i = lb To ub - 1 + bs(i) = bs(i + 1) + Next + ReDim Preserve bs(ub - 1) + ub -= 1 + + ' Extract sorted subsequence + For i = lb To ub + If bs(i) >= subList(UBound(subList)) Then + ReDim Preserve subList(UBound(subList) + 1) + subList(UBound(subList)) = bs(i) + + ' Remove the element + For j = i To ub - 1 + bs(j) = bs(j + 1) + Next + ReDim Preserve bs(ub - 1) + ub -= 1 + i -= 1 + End If + Next + + ' Merge lists - but only if results has elements + If UBound(results) >= 0 Then + ReDim As Long merged(UBound(results) + UBound(subList) + 1) + i = 0 + j = 0 + k = 0 + + While i <= UBound(results) And j <= UBound(subList) + If results(i) < subList(j) Then + merged(k) = results(i) + i += 1 + Else + merged(k) = subList(j) + j += 1 + End If + k += 1 + Wend + + While i <= UBound(results) + merged(k) = results(i) + i += 1 + k += 1 + Wend + + While j <= UBound(subList) + merged(k) = subList(j) + j += 1 + k += 1 + Wend + + ReDim results(UBound(merged)) + For i = 0 To UBound(merged) + results(i) = merged(i) + Next + Else + ' If results is empty, just copy subList to results + ReDim results(UBound(subList)) + For i = 0 To UBound(subList) + results(i) = subList(i) + Next + End If + Wend + + ' Copy results back to bs + ReDim bs(UBound(results)) + For i = 0 To UBound(results) + bs(i) = results(i) + Next +End Sub + +'--- Main Program --- +Dim As Long i +Dim As Long array(14) = {-5,-3, 0,-7, 5, 2, 3, 6,-6,-1, 1,-2, 4, 7,-4} +Dim As Long a = LBound(array), b = UBound(array) + +Print "unsort "; +For i = a To b : Print Using "####"; array(i); : Next i + +strandSort(array()) ' sort the array + +Print !"\n sort "; +For i = a To b : Print Using "####"; array(i); : Next i + +Sleep diff --git a/Task/Sorting-algorithms-Strand-sort/M2000-Interpreter/sorting-algorithms-strand-sort.m2000 b/Task/Sorting-algorithms-Strand-sort/M2000-Interpreter/sorting-algorithms-strand-sort.m2000 new file mode 100644 index 0000000000..9068a2ded2 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/M2000-Interpreter/sorting-algorithms-strand-sort.m2000 @@ -0,0 +1,68 @@ +module Strand_sort{ + function strand_sort(aa as array) { + function mergelist(sa, sb) { + flush ' empty current stack + variant v, g + integer L=3 + while len(sa) and len(sb) + if L=1 else stack sa {read v} + if L=2 else stack sb {read g} + if vL then + stack a { + shift i ' get i_th item as top + over ' copy one + read g ' read in a variant + shiftback i ' send back to i + } + L=i + end if + if g > v then + stack a { + shift i + drop + } + data g + v = g + else + i++ + end if + end while + =[] + } + + a=stack(aa) + out = strand(&a) + while len(a) + out = mergelist(out, strand(&a)) + end while + =array(out) + } + m = (1, 6, 3, 2, 1, 7, 5, 3) + Print m + Print strand_sort(m) + m = ("aa", "cc", "bb", "a1") + Print m + Print strand_sort(m) +} +Strand_sort diff --git a/Task/Sorting-algorithms-Strand-sort/Rust/sorting-algorithms-strand-sort.rs b/Task/Sorting-algorithms-Strand-sort/Rust/sorting-algorithms-strand-sort.rs new file mode 100644 index 0000000000..f94c7a0317 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Rust/sorting-algorithms-strand-sort.rs @@ -0,0 +1,153 @@ +use std::fmt; + +struct Link { + value: i32, + next: Option>, +} + +impl Link { + fn new(value: i32, next: Option>) -> Self { + Link { value, next } + } +} + +impl fmt::Display for Link { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "[{}", self.value)?; + + let mut current = &self.next; + while let Some(link) = current { + write!(f, " {}", link.value)?; + current = &link.next; + } + + write!(f, "]") + } +} + +fn link_ints(s: &[i32]) -> Option> { + if s.is_empty() { + None + } else { + Some(Box::new(Link::new(s[0], link_ints(&s[1..])))) + } +} + +fn strand_sort(mut a: Option>) -> Option> { + let mut result: Option> = None; + + while let Some(mut head) = a { + // Take the first element for our sublist + a = head.next.take(); + + // Build sublist + let mut sublist = Some(head); + let mut sublist_tail = sublist.as_mut().unwrap(); + + // Process the remaining elements in the original list + let mut current = a; + a = None; + + // Start building a new 'a' list + let mut new_a = None; + let mut new_a_tail_ptr: *mut Option> = &mut new_a; + + while let Some(mut node) = current { + current = node.next.take(); + + if node.value > sublist_tail.value { + // Append to sublist + sublist_tail.next = Some(node); + sublist_tail = sublist_tail.next.as_mut().unwrap(); + } else { + // Add to the new 'a' list + unsafe { + *new_a_tail_ptr = Some(node); + new_a_tail_ptr = &mut (*new_a_tail_ptr).as_mut().unwrap().next; + } + } + } + + a = new_a; + + // If result is empty, set it to the sublist + if result.is_none() { + result = sublist; + continue; + } + + // Merge sublist with result + result = merge(result, sublist); + } + + result +} + +fn merge(list1: Option>, list2: Option>) -> Option> { + match (list1, list2) { + (None, list2) => list2, + (list1, None) => list1, + (Some(mut head1), Some(mut head2)) => { + // Start with the smaller value + let mut result; + let mut current; + + if head1.value <= head2.value { + result = Some(head1); + current = result.as_mut().unwrap(); + match current.next.take() { + Some(next) => head1 = next, + None => { + current.next = Some(head2); + return result; + } + } + } else { + result = Some(head2); + current = result.as_mut().unwrap(); + match current.next.take() { + Some(next) => head2 = next, + None => { + current.next = Some(head1); + return result; + } + } + } + + // Merge the rest + loop { + if head1.value <= head2.value { + current.next = Some(head1); + current = current.next.as_mut().unwrap(); + match current.next.take() { + Some(next) => head1 = next, + None => { + current.next = Some(head2); + break; + } + } + } else { + current.next = Some(head2); + current = current.next.as_mut().unwrap(); + match current.next.take() { + Some(next) => head2 = next, + None => { + current.next = Some(head1); + break; + } + } + } + } + + result + } + } +} + +fn main() { + let a = link_ints(&[170, 45, 75, -90, -802, 24, 2, 66]); + println!("before: {}", a.as_ref().map_or("None".to_string(), |link| link.to_string())); + + let b = strand_sort(a); + println!("after: {}", b.as_ref().map_or("None".to_string(), |link| link.to_string())); +} diff --git a/Task/Sorting-algorithms-Strand-sort/Zig/sorting-algorithms-strand-sort.zig b/Task/Sorting-algorithms-Strand-sort/Zig/sorting-algorithms-strand-sort.zig new file mode 100644 index 0000000000..1056faa5d4 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Zig/sorting-algorithms-strand-sort.zig @@ -0,0 +1,190 @@ +const std = @import("std"); + +const Link = struct { + value: i32, + next: ?*Link, + + fn new(allocator: std.mem.Allocator, value: i32, next: ?*Link) !*Link { + const link = try allocator.create(Link); + link.* = .{ .value = value, .next = next }; + return link; + } + + pub fn format( + self: *const Link, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + + try writer.print("[{}", .{self.value}); + + var current = self.next; + while (current) |link| { + try writer.print(" {}", .{link.value}); + current = link.next; + } + + try writer.print("]", .{}); + } +}; + +// Function to free all nodes in a linked list +fn freeList(allocator: std.mem.Allocator, list: ?*Link) void { + var current = list; + while (current) |node| { + const next = node.next; + allocator.destroy(node); + current = next; + } +} + +fn linkInts(allocator: std.mem.Allocator, s: []const i32) !?*Link { + if (s.len == 0) { + return null; + } else { + return try Link.new(allocator, s[0], try linkInts(allocator, s[1..])); + } +} + +fn strandSort(allocator: std.mem.Allocator, a: ?*Link) !?*Link { + var result: ?*Link = null; + var current_a = a; + + while (current_a) |head| { + // Take the first element for our sublist + current_a = head.next; + head.next = null; + + // Build sublist + const sublist: ?*Link = head; + var sublist_tail = sublist.?; + + // Process the remaining elements in the original list + var current = current_a; + current_a = null; + + // Start building a new 'a' list + var new_a: ?*Link = null; + var new_a_tail: ?*Link = null; + + while (current) |node| { + current = node.next; + node.next = null; + + if (node.value > sublist_tail.value) { + // Append to sublist + sublist_tail.next = node; + sublist_tail = node; + } else { + // Add to the new 'a' list + if (new_a == null) { + new_a = node; + new_a_tail = node; + } else { + new_a_tail.?.next = node; + new_a_tail = node; + } + } + } + + current_a = new_a; + + // If result is empty, set it to the sublist + if (result == null) { + result = sublist; + continue; + } + + // Merge sublist with result + result = try merge(allocator, result, sublist); + } + + return result; +} + +fn merge(allocator: std.mem.Allocator, list1: ?*Link, list2: ?*Link) !?*Link { + _ = allocator; // Allocator is not needed here, but keeping for consistency + + if (list1 == null) return list2; + if (list2 == null) return list1; + + var head1 = list1.?; + var head2 = list2.?; + + // Start with the smaller value + var result: ?*Link = null; + var current: *Link = undefined; + + if (head1.value <= head2.value) { + result = head1; + current = head1; + head1 = head1.next orelse { + current.next = head2; + return result; + }; + } else { + result = head2; + current = head2; + head2 = head2.next orelse { + current.next = head1; + return result; + }; + } + + // Merge the rest + while (true) { + if (head1.value <= head2.value) { + current.next = head1; + current = head1; + head1 = head1.next orelse { + current.next = head2; + break; + }; + } else { + current.next = head2; + current = head2; + head2 = head2.next orelse { + current.next = head1; + break; + }; + } + } + + return result; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer { + const deinit_status = gpa.deinit(); + if (deinit_status == .leak) @panic("MEMORY LEAK"); + } + + const array = [_]i32{ 170, 45, 75, -90, -802, 24, 2, 66 }; + const a = try linkInts(allocator, &array); + + const stdout = std.io.getStdOut().writer(); + try stdout.print("before: ", .{}); + if (a) |link| { + try stdout.print("{}", .{link}); + } else { + try stdout.print("None", .{}); + } + try stdout.print("\n", .{}); + + const b = try strandSort(allocator, a); + try stdout.print("after: ", .{}); + if (b) |link| { + try stdout.print("{}", .{link}); + } else { + try stdout.print("None", .{}); + } + try stdout.print("\n", .{}); + + // Free memory + freeList(allocator, b); +} diff --git a/Task/Spelling-of-ordinal-numbers/JavaScript/spelling-of-ordinal-numbers.js b/Task/Spelling-of-ordinal-numbers/JavaScript/spelling-of-ordinal-numbers.js new file mode 100644 index 0000000000..c9cca19f12 --- /dev/null +++ b/Task/Spelling-of-ordinal-numbers/JavaScript/spelling-of-ordinal-numbers.js @@ -0,0 +1,163 @@ +// Equivalent data structures for Java's arrays and map +const nums = [ + "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", + "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" +]; + +const tens = ["zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; + +// Map for irregular ordinal endings (like Java's static initializer block) +const ordinalMap = { + "one": "first", + "two": "second", + "three": "third", + "five": "fifth", + "eight": "eighth", + "nine": "ninth", + "twelve": "twelfth" + // Note: twenty, thirty, etc. are handled by the 'y' -> 'ieth' rule +}; + +/** + * Recursive helper function to convert a number to its cardinal English spelling. + * Handles positive integers up to quintillions. + * Note: JavaScript numbers are 64-bit floats (IEEE 754). Integers are safe up to + * Number.MAX_SAFE_INTEGER (2^53 - 1, approx 9 quadrillion). Very large numbers + * beyond this might lose precision or require BigInt. The test cases provided + * fit within the safe integer range. + * @param {number} n - The number to convert. + * @returns {string} The English spelling of the number. + */ +function numToStringHelper(n) { + if (n < 0) { + // Handle negative numbers recursively + return "negative " + numToStringHelper(-n); + } + if (n <= 19) { + // Numbers 0-19 directly from the nums array + return nums[n]; + } + if (n <= 99) { + // Numbers 20-99: combine tens place and (optionally) ones place + // Use Math.floor for integer division equivalent + const ten = tens[Math.floor(n / 10)]; + const rest = n % 10; + return ten + (rest > 0 ? "-" + numToStringHelper(rest) : ""); + } + + let label = ""; + let factor = 0; + + // Determine the scale (hundred, thousand, million, etc.) + // Using number literals for factors + if (n <= 999) { + label = "hundred"; + factor = 100; + } else if (n <= 999999) { + label = "thousand"; + factor = 1000; + } else if (n <= 999999999) { + label = "million"; + factor = 1000000; + } else if (n <= 999999999999) { + label = "billion"; + factor = 1000000000; // 1e9 + } else if (n <= 999999999999999) { + label = "trillion"; + factor = 1000000000000; // 1e12 + } else if (n <= 999999999999999999) { // Approaching JS safe integer limit + label = "quadrillion"; + factor = 1000000000000000; // 1e15 + } else { // Numbers beyond this may need BigInt for perfect accuracy + label = "quintillion"; + factor = 1000000000000000000; // 1e18 + } + + // Recursively spell the parts + // Use Math.floor for integer division equivalent + const highPart = numToStringHelper(Math.floor(n / factor)); + const lowPart = n % factor; + + return highPart + " " + label + (lowPart > 0 ? " " + numToStringHelper(lowPart) : ""); +} + +/** + * Converts a number to its cardinal English spelling (e.g., 123 -> "one hundred twenty-three"). + * Public facing function that calls the helper. + * @param {number} n - The number to convert. + * @returns {string} The English spelling of the number. + */ +function numToString(n) { + // Ensure input is a number + n = Number(n); + // Handle the base case of 0 explicitly for clarity, though helper handles it. + if (n === 0) { + return nums[0]; // "zero" + } + return numToStringHelper(n); +} + + +/** + * Converts a number to its ordinal English spelling (e.g., 1 -> "first", 123 -> "one hundred twenty-third"). + * @param {number} n - The number to convert. + * @returns {string} The ordinal English spelling. + */ +function toOrdinal(n) { + // Get the cardinal spelling first + const spelling = numToString(n); + + // Split the spelling into words + const parts = spelling.split(' '); + + // Get the last word, which determines the ordinal ending + const lastWord = parts[parts.length - 1]; + + let replacement = ""; + + // Check if the last word is hyphenated (e.g., "twenty-three") + if (lastWord.includes('-')) { + const lastSplit = lastWord.split('-'); // ["twenty", "three"] + const base = lastSplit[0]; // "twenty" + const lastPart = lastSplit[1]; // "three" + let ordinalLastPart = ""; + + // Apply ordinal rules to the part after the hyphen + if (ordinalMap.hasOwnProperty(lastPart)) { + ordinalLastPart = ordinalMap[lastPart]; // irregular: three -> third + } else if (lastPart.endsWith('y')) { + // This case shouldn't happen after a hyphen (e.g., "sixty-twenty"), + // but included for robustness matching the Java code. + ordinalLastPart = lastPart.slice(0, -1) + "ieth"; + } else { + ordinalLastPart = lastPart + "th"; // regular: four -> fourth + } + replacement = `${base}-${ordinalLastPart}`; // "twenty-third" + + } else { + // Handle non-hyphenated last words + if (ordinalMap.hasOwnProperty(lastWord)) { + replacement = ordinalMap[lastWord]; // irregular: one -> first, two -> second + } else if (lastWord.endsWith('y')) { + replacement = lastWord.slice(0, -1) + "ieth"; // twenty -> twentieth, thirty -> thirtieth + } else { + replacement = lastWord + "th"; // seven -> seventh, hundred -> hundredth + } + } + + // Replace the last word in the parts array + parts[parts.length - 1] = replacement; + + // Join the parts back together + return parts.join(' '); +} + +// --- Main execution / Testing --- +// Equivalent to the Java main method's test loop +const testNumbers = [0, 1, 2, 3, 4, 5, 11, 12, 13, 19, 20, 21, 22, 23, 65, 99, 100, 101, 272, 23456, 8007006005004003]; + +console.log("--- Ordinal Number Spelling (JavaScript) ---"); +testNumbers.forEach(test => { + // Use template literals for easy string formatting + console.log(`${test} = ${toOrdinal(test)}`); +}); diff --git a/Task/Sphenic-numbers/Mathematica/sphenic-numbers.math b/Task/Sphenic-numbers/Mathematica/sphenic-numbers.math new file mode 100644 index 0000000000..ded24f8c8b --- /dev/null +++ b/Task/Sphenic-numbers/Mathematica/sphenic-numbers.math @@ -0,0 +1,3 @@ +Select[Select[{#,Catenate@MapApply[ConstantArray,FactorInteger[#]]}&/@Range[999],Last/*Length/*EqualTo[3]],Last/*DuplicateFreeQ][[All,1]] + +Select[Partition[Select[Select[{#,Catenate@MapApply[ConstantArray,FactorInteger[#]]}&/@Range[9999],Last/*Length/*EqualTo[3]],Last/*DuplicateFreeQ][[All,1]],3,1],MatchQ[#-First[#],{0,1,2}]&] diff --git a/Task/Spinning-rod-animation-Text/EasyLang/spinning-rod-animation-text.easy b/Task/Spinning-rod-animation-Text/EasyLang/spinning-rod-animation-text.easy index f5e8d8b029..bb7db3f84a 100644 --- a/Task/Spinning-rod-animation-Text/EasyLang/spinning-rod-animation-text.easy +++ b/Task/Spinning-rod-animation-Text/EasyLang/spinning-rod-animation-text.easy @@ -1,9 +1,8 @@ c$[] = strchars "🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘" -textsize 60 -move 20 30 +gtextsize 60 on timer ind = (ind + 1) mod1 len c$[] - text c$[ind] + gtext 20 30 c$[ind] timer 0.25 . timer 0 diff --git a/Task/Spiral-matrix/EasyLang/spiral-matrix.easy b/Task/Spiral-matrix/EasyLang/spiral-matrix.easy index 3f5bbef5f1..3062f93b49 100644 --- a/Task/Spiral-matrix/EasyLang/spiral-matrix.easy +++ b/Task/Spiral-matrix/EasyLang/spiral-matrix.easy @@ -1,4 +1,4 @@ -proc mkspiral n . t[] . +proc mkspiral n &t[] . subr side for i to l ind += d @@ -23,10 +23,8 @@ proc mkspiral n . t[] . . n = 5 mkspiral n t[] -numfmt 0 3 +numfmt 3 0 for i to n * n write t[i] - if i mod n = 0 - print "" - . + if i mod n = 0 : print "" . diff --git a/Task/Spiral-matrix/Uiua/spiral-matrix.uiua b/Task/Spiral-matrix/Uiua/spiral-matrix.uiua new file mode 100644 index 0000000000..98c96b6118 --- /dev/null +++ b/Task/Spiral-matrix/Uiua/spiral-matrix.uiua @@ -0,0 +1,5 @@ +Spiral ← ⍥(⊂+-⊃(⟜⇡⧻|⊢⊢|⍉⇌))×₂-₁⟜[[-₁ⁿ₂]] + +Spiral 1 +Spiral 4 +Spiral 5 diff --git a/Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character.c b/Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character-1.c similarity index 100% rename from Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character.c rename to Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character-1.c diff --git a/Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character-2.c b/Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character-2.c new file mode 100644 index 0000000000..77384ae201 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/C/split-a-character-string-based-on-change-of-character-2.c @@ -0,0 +1,32 @@ +#include + +void split(const char *src, char *dst) { + const char *src_tmp = src; + char *dst_tmp = dst; + + while (*src_tmp != '\0') { + int i = 0; + + // scan for the next change of character occurrence + while (*(src_tmp + ++i) == *src_tmp) + ; + + // copy the sequence of repeated characters to the destination buffer + snprintf(dst_tmp, i + 1, "%s", src_tmp); + + // add a comma or null character (if end of string) to the destination + // buffer and advance both the source and destination pointers + snprintf(dst_tmp += i, 3, "%s", *(src_tmp += i) == '\0' ? "\0" : ", "); + dst_tmp += 2; + } +} + +int main(void) { + const char *str = "gHHH5YY++///\\"; + char out[100]; // must be large enough to hold the result + + split(str, out); + printf("%s\n", out); + + return 0; +} diff --git a/Task/Split-a-character-string-based-on-change-of-character/Crystal/split-a-character-string-based-on-change-of-character.cr b/Task/Split-a-character-string-based-on-change-of-character/Crystal/split-a-character-string-based-on-change-of-character.cr new file mode 100644 index 0000000000..c220eb738f --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Crystal/split-a-character-string-based-on-change-of-character.cr @@ -0,0 +1,6 @@ +["gHHH5YY++///\\", + "aaabbbaaabcdeef" +].each do |s| + puts s + puts " -> " + s.scan(/(.)\1*/).flatten.join(", ") +end diff --git a/Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.l b/Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.l new file mode 100644 index 0000000000..9f040ca42e --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.l @@ -0,0 +1,29 @@ +(defun get-char-values () + "List ascii values of chars in buffer named test-string." + (let ((my-chars) + (current-point 1)) + (with-current-buffer "test-string" + (while (char-after current-point) + (push (char-after current-point) my-chars) + (setq current-point (1+ current-point))) + (nreverse my-chars)))) + + (defun show-chars (ascii-values) + "Show characters from VALUES." + (let* ((first-char (nth 0 ascii-values)) + (current-char) + (current-position 1) + (first-element t) + (separator ", ")) + (when first-element + (setq first-element nil) + (setq previous-char first-char) + (insert first-char)) + (while (< current-position (length ascii-values)) + (setq current-char (nth current-position ascii-values)) + (if (equal current-char previous-char) + (insert current-char) + (insert separator) + (insert current-char)) + (setq previous-char current-char) + (setq current-position (1+ current-position))))) diff --git a/Task/Split-a-character-string-based-on-change-of-character/M2000-Interpreter/split-a-character-string-based-on-change-of-character.m2000 b/Task/Split-a-character-string-based-on-change-of-character/M2000-Interpreter/split-a-character-string-based-on-change-of-character.m2000 index 1eb9e6cfeb..7e182618c6 100644 --- a/Task/Split-a-character-string-based-on-change-of-character/M2000-Interpreter/split-a-character-string-based-on-change-of-character.m2000 +++ b/Task/Split-a-character-string-based-on-change-of-character/M2000-Interpreter/split-a-character-string-based-on-change-of-character.m2000 @@ -19,3 +19,27 @@ Module PrintParts(splitthis$) { } } PrintParts "gHHH5YY++///\" +' version 13 of M2000 Interpreter - old program run as is. +' [] get the current stack as object and leave an empty stack as current stack, +' array([]) empty the stack object (a linked linst) making a tuple (of variant type). +' #str$(", ") extract from array all items render as string and place between the ", " string - or a space by default, without argument. + +MODULE PrintParts(splitthis AS STRING) { + IF LEN(splitthis)=0 THEN PRINT : EXIT + STRING m, p + LONG c, i + STACK NEW { + FOR i=1 TO LEN(splitthis) + p=mid$(splitthis,i,1) + IF m<>p THEN + IF c>0 THEN DATA STRING$(m, c) + m=p : c=1 + ELSE + c++ + END IF + NEXT + IF c>0 THEN DATA STRING$(m, c) + PRINT ARRAY([])#STR$(", ") + } +} +PrintParts "gHHH5YY++///\" diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-1.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-1.rs index 23740c561c..d7ad86f9dd 100644 --- a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-1.rs +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-1.rs @@ -1,22 +1,52 @@ -fn splitter(string: &str) -> String { - let chars: Vec<_> = string.chars().collect(); - let mut result = Vec::new(); - let mut last_mismatch = 0; - for i in 0..chars.len() { - if chars.len() == 1 { - return chars[0..1].iter().collect(); - } - if i > 0 && chars[i-1] != chars[i] { - let temp_result: String = chars[last_mismatch..i].iter().collect(); - result.push(temp_result); - last_mismatch = i; - } - if i == chars.len() - 1 { - let temp_result: String = chars[last_mismatch..chars.len()].iter().collect(); - result.push(temp_result); +trait RosettaExt { + fn split_duplicates(&self) -> SplitDuplicates; +} + +impl RosettaExt for &str { + fn split_duplicates(&self) -> SplitDuplicates { + SplitDuplicates { string: self } + } +} + +struct SplitDuplicates<'a> { + string: &'a str, +} + +impl<'a> Iterator for SplitDuplicates<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option { + if self.string.is_empty() { + None + } else { + // We want to keep track of the char boundaries when we split + let mut chars = self.string.char_indices(); + let mut l = chars.next()?; + + for r in chars { + // Compare characters; if they don't match, split + if l.1 != r.1 { + let (ret, rem) = self.string.split_at(r.0); + self.string = rem; + + return Some(ret); + } + l = r; + } + + // No more characters to compare, return the remaining string slice + let ret = self.string; + + // Exhaust string slice + self.string = &self.string[self.string.len()..]; + + Some(ret) } } - result.join(", ") +} + +fn splitter(s: &str) -> String { + s.split_duplicates().collect::>().join(", ") } fn main() { diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-2.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-2.rs index 7504e9e9cf..ee68117974 100644 --- a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-2.rs +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-2.rs @@ -1,20 +1,2 @@ -use itertools::Itertools; - -pub fn split_text(s: &str) -> Vec { - let mut r = Vec::new(); - for (_, group) in &s.chars().into_iter().group_by(|e| *e) { - r.push(group.map(|e| e.to_string()).join("")); - } - r -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_splitting_text() { - assert_eq!(split_text("gHHH5YY++///\\"), vec!["g", "HHH", "5", "YY", "++", "///", "\\"]); - assert!(split_text("").is_empty()); - } -} +[dependencies] +itertools = { version = "0.14", features = ["use_alloc"] } diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-3.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-3.rs new file mode 100644 index 0000000000..b5883d4df3 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-3.rs @@ -0,0 +1,14 @@ +use itertools::Itertools; + +fn split_text(s: &str) -> String { + let mut r = Vec::new(); + for (_, group) in &s.chars().chunk_by(|e| *e) { + r.push(group.collect::()) + } + + r.join(", ") +} + +fn main() { + println!("output string: {}", split_text("gHHH5YY++///\\")); +} diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-4.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-4.rs new file mode 100644 index 0000000000..7469bec903 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-4.rs @@ -0,0 +1,2 @@ +[dependencies] +itertools = { version = "0.14", default-features = false } diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-5.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-5.rs new file mode 100644 index 0000000000..49b4c2e4cf --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-5.rs @@ -0,0 +1,9 @@ +use itertools::Itertools; + +fn main() { + print!("output string: "); + for i in "gHHH5YY++///\\".split_duplicates().intersperse(", ") { + print!("{i}"); + } + println!(); +} diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-6.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-6.rs new file mode 100644 index 0000000000..24e18fd2d6 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-6.rs @@ -0,0 +1,9 @@ +#![feature(iter_intersperse)] + +fn main() { + print!("output string: "); + for i in "gHHH5YY++///\\".split_duplicates().intersperse(", ") { + print!("{i}"); + } + println!(); +} diff --git a/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-7.rs b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-7.rs new file mode 100644 index 0000000000..88f393c64b --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Rust/split-a-character-string-based-on-change-of-character-7.rs @@ -0,0 +1,5 @@ +#![feature(iter_intersperse)] +use itertools::Itertools; + +Iterator::intersperse(r#"gHHH5YY++///\"#.split_duplicates(), ", "); +Itertools::intersperse(r#"gHHH5YY++///\"#.split_duplicates(), ", "); diff --git a/Task/Square-form-factorization/Python/square-form-factorization.py b/Task/Square-form-factorization/Python/square-form-factorization.py new file mode 100644 index 0000000000..b27f52a88a --- /dev/null +++ b/Task/Square-form-factorization/Python/square-form-factorization.py @@ -0,0 +1,110 @@ +from math import sqrt, gcd + +M = [1, 3, 5, 7, 11] +UINT64_MAX = 18446744073709551615 + +def isqrt(n: int): + return int(sqrt(n)) + +def squfof(n: int): + if n % 2 == 0: + return 2 + + h = int(sqrt(n) + 0.5) + + if h ** 2 == n: + return h + + for m in M: + if m > 1 and n % m == 0: + return m + + if n > UINT64_MAX / m: + break + + mn = m * n + r = isqrt(mn) + + if r ** 2 > mn: + r -= 1 + + rn = r + + b = r + a = 1 + h = ((rn + b) // a) * a - b + c = (mn - h * h) // a + + for i in range(2, 4 * isqrt(2 * r)): + a, c = c, a + q = (rn + b) // a + t = b + b = q * a - b + c += q * (t - b) + + if i % 2 == 0: + r = int(sqrt(c) + 0.5) + + if r ** 2 == c: + q = (rn - b) // r + v = q * r + b + w = (mn - v * v) // r + + u = r + + while True: + w, u = u, w + r = v + q = (rn + v) // u + v = q * u - v + + if v == r: + break + + w += q * (r - v) + + h = gcd(n, u) + + if h != 1: + return h + + return 1 + +data = [ + 2501, + 12851, + 13289, + 75301, + 120787, + 967009, + 997417, + 7091569, + 13290059, + 42854447, + 223553581, + 2027651281, + 11111111111, + 100895598169, + 1002742628021, + 60012462237239, + 287129523414791, + 9007199254740931, + 11111111111111111, + 314159265358979323, + 384307168202281507, + 419244183493398773, + 658812288346769681, + 922337203685477563, + 1000000000000000127, + 1152921505680588799, + 1537228672809128917, + 4611686018427387877 +] + +print("N f N/f") +print("======================================") + +for n in data: + f = squfof(n) + res = 'fail' if f == 1 else f'{f:<10} {n // f}' + print(f'{n:<22} {res}') diff --git a/Task/Square-form-factorization/REXX/square-form-factorization.rexx b/Task/Square-form-factorization/REXX/square-form-factorization.rexx index e4f6277927..cb88ddad6f 100644 --- a/Task/Square-form-factorization/REXX/square-form-factorization.rexx +++ b/Task/Square-form-factorization/REXX/square-form-factorization.rexx @@ -1,54 +1,94 @@ -/*REXX pgm factors an integer using Daniel Shanks' (1917-1996) square form factorization*/ -numeric digits 100 /*ensure enough decimal digits.*/ -call dMults 1,3,5,7,11,3*5,3*7,3*11,5*7,5*11,7*11, 3*5*7, 3*5*11, 3*7*11, 5*7*11, 3*5*7*11 -call dTests 2501, 12851, 13289, 75301, 120787, 967009, 997417, 7091569, 13290059, , - 42854447, 223553581, 2027651281, 11111111111, 100895598169, 1002742628021, , - 60012462237239, 287129523414791, 9007199254740931, 11111111111111111, , - 314159265358979323, 384307168202281507, 419244183493398773, , - 658812288346769681, 922337203685477563, 1000000000000000127, , - 1152921505680588799, 1537228672809128917, 4611686018427387877 - w= length( commas(!.$) ) /*the max width of test numbers*/ - do tests=1 for !.0; n= !.tests; nc= commas(n) - f= ssff(n); fc= commas(f); wf= length(fc); if f\==0 then nf= commas(n%f) - if f\==0 then do; nfc= commas(n%f); wnfc= length(nfc); end - if f ==0 then _= " (Shank's square form factor failed.)" - else _= ' factors are: ' right( fc, max(w%2 , wf ) ) " and " , - right(nfc, max(w%2+4, wnfc) ) - say right(nc, w+5) _ - end /*tests*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -dMults: @.$= 0; do j=1 for arg(); @.j= arg(j); @.$=max(@.$, @.j); end; @.0=j-1; return -dTests: !.$= 0; do j=1 for arg(); !.j= arg(j); !.$=max(!.$, !.j); end; !.0=j-1; return -gcd: procedure; parse arg x,y; do until _==0; _= x // y; x= y; y= _; end; return x -/*──────────────────────────────────────────────────────────────────────────────────────*/ -iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end; end - return r -/*──────────────────────────────────────────────────────────────────────────────────────*/ -ssff: procedure expose @.; parse arg n; n= abs(n); er= '***error***' - s= iSqrt(n); if s**2==n then return s; big= 2**digits() - do #=1 for @.0; k= @.# /*get a # from the list of low factors*/ - if n>big/k then do; say er 'number is too large: ' commas(k); exit 8; end - d= n*k; po= iSqrt(d); p= po - pprev= po; QQ= d - po*po - qprev= 1; BB= iSqrt(s+s)*6 - do i=2 while i=BB then iterate - b= (po-p)%r; p= b*r + p - pprev= p; qprev= r - QQ= (d - pprev*pprev)%qprev - do until p==pprev; pprev= p - b= (po+p)%QQ; q= QQ; p= b*QQ - p - QQ= qprev + b*(pprev-p); qprev= q - end /*until*/ - r= gcd(n, qprev) - if r\==1 then if r\==n then return r - end /*#*/ - return 0 +-- 8 May 2025 +include Settings +numeric digits 40 + +say 'SQUARE FORM FACTORIZATION' +say version +say +call TestNumbers +call Selected +call Randomized +exit + +TestNumbers: +procedure expose test. +t = '2501 12851 13289 75301 120787 967009 997417 7091569 13290059', + '42854447 223553581 2027651281 11111111111 100895598169 1002742628021', + '60012462237239 287129523414791 9007199254740931 11111111111111111', + '314159265358979323 384307168202281507 419244183493398773', + '658812288346769681 922337203685477563 1000000000000000127', + '1152921505680588799 1537228672809128917 4611686018427387877' +do i = 1 to Words(t) + test.i = Word(t,i) +end +test.0 = i-1 +return + +Selected: +procedure expose mult. test. glob. +call Time('r') +say 'Find a factor for 28 selected numbers...' +do t = 1 for test.0 + n = test.t + call Time('r') + f = Squfof(n) + if f = 0 then + u = 'failed' + else + u = f 'x' n/f + say Format(Time('e'),3,3)'s Squfof ' n '('Xpon(n)+1 'digits) =' u + call Time('r') + f = Pollardrho(n) + if f = 0 then + u = 'failed' + else + u = f 'x' n/f + say Format(Time('e'),3,3)'s Pollard' n '('Xpon(n)+1 'digits) =' u + if n < 1e17 then do + call Time('r') + f = Trialdiv(n); u = f 'x' n/f + say Format(Time('e'),3,3)'s Trial ' n '('Xpon(n)+1 'digits) =' u + end + say +end +say +return + +Randomized: +procedure expose mult. glob. +say 'Find a factor for 28 random numbers...' +x = 0 +do until x = 28 + n = (Right(Randu(),Randu(1,10))||Right(Randu(),Randu(1,10))||Right(Randu(),Randu(1,10)))/1 + if Pos(Right(n,1),05) > 0 | Even(n) | Digitsum(n)//3 = 0 then + iterate + call Time('r') + f = Squfof(n) + if f = 0 then + u = 'failed' + else + u = f 'x' n/f + say Format(Time('e'),3,3)'s Squfof ' n '('Xpon(n)+1 'digits) =' u + if n < 1e24 then do + call Time('r') + f = Pollardrho(n) + if f = 0 then + u = 'failed' + else + u = f 'x' n/f + say Format(Time('e'),3,3)'s Pollard' n '('Xpon(n)+1 'digits) =' u + end + if n < 1e17 then do + call Time('r') + f = Trialdiv(n); u = f 'x' n/f + say Format(Time('e'),3,3)'s Trial ' n '('Xpon(n)+1 'digits) =' u + end + say + x = x+1 +end +say +return + +include Numbers +include Functions +include Abend diff --git a/Task/Square-free-integers/EasyLang/square-free-integers.easy b/Task/Square-free-integers/EasyLang/square-free-integers.easy index 72647835ea..841902cb00 100644 --- a/Task/Square-free-integers/EasyLang/square-free-integers.easy +++ b/Task/Square-free-integers/EasyLang/square-free-integers.easy @@ -6,7 +6,7 @@ fastfunc square_free n . . return 1 . -proc run lo hi show . . +proc run lo hi show . print "From " & lo & " to " & hi & ":" for i = lo to hi if square_free i = 1 diff --git a/Task/Square-free-integers/PL-I-80/square-free-integers.pli b/Task/Square-free-integers/PL-I-80/square-free-integers.pli index d58642d4b3..931b27a43d 100644 --- a/Task/Square-free-integers/PL-I-80/square-free-integers.pli +++ b/Task/Square-free-integers/PL-I-80/square-free-integers.pli @@ -40,11 +40,11 @@ end report_number_found; /* return true if n has no square divisors other than 1 */ square_free: proc (n) returns (bit(1)); dcl (n, i, sq) fixed bin; - i = 2; + i = 3; sq = i * i; do while (sq <= n); - if (mod(n, sq) = 0) then return (false); - i = i + 1; + if (mod(n, sq) = 0) then return (false); + i = i + 2; sq = i * i; end; return (true); diff --git a/Task/Square-free-integers/REXX/square-free-integers.rexx b/Task/Square-free-integers/REXX/square-free-integers.rexx index 80bf992397..f6bb555df9 100644 --- a/Task/Square-free-integers/REXX/square-free-integers.rexx +++ b/Task/Square-free-integers/REXX/square-free-integers.rexx @@ -1,35 +1,80 @@ -/*REXX program displays square─free numbers (integers > 1) up to a specified limit. */ -numeric digits 20 /*be able to handle larger numbers. */ -parse arg LO HI . /*obtain optional arguments from the CL*/ -if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ -if HI=='' | HI=="," then HI= 145 /* " " " " " " */ -sw= linesize() - 1 /*use one less than a full line. */ -# = 0 /*count of square─free numbers found. */ -$= /*variable that holds a line of numbers*/ - do j=LO to abs(HI) /*process all integers between LO & HI.*/ - if \isSquareFree(j) then iterate /*Not square─free? Then skip this #. */ - #= # + 1 /*bump the count of square─free numbers*/ - if HI<0 then iterate /*Only counting 'em? Then look for more*/ - if length($ || j)1; q= q % 4; _= x - r - q; r= r % 2 - if _>=0 then do; x= _; r= r + q; end - end /*while q>1*/ - return r /*R is the integer square root of X. */ +say 'SQUARE-FREE INTEGERS - 6 Mar 2025' +say version +say +numeric digits 5 +call Show 1,145 +numeric digits 15 +call Show 1000000000000,1000000000145 +numeric digits 10 +call Count1 1000000 +call Count2 1000000 +exit + +Show: +call Time('r') +arg xx,yy +say 'Square-free integers between' xx 'and' yy +r = Length(yy)+1; n = 0 +do i = xx to yy + if Squarefree(i) then do + n = n+1 + call Charout ,Right(i,r) + if n//10 = 0 then + say + end +end +say +say Format(Time('e'),,3) 'seconds' +say +return + +Count1: +call Time('r') +arg xx +say 'Number of square-free integers <= 10^n' +say 'Direct method' +say '--------------' +say Left('n',4) Right('count',6) +say '--------------' +n = 0; e = 1 +do i = 1 to xx + if i >= 1'E'e then do + say Left('10^'e,5) Right(n,8) + e = e+1 + end + if Squarefree(i) then + n = n+1 +end +say '--------------' +say Format(Time('e'),,3) 'seconds' +say +return + +Count2: +call Time('r') +arg xx +call Squarefrees xx +say 'Number of square-free integers <= 10^n' +say 'Sieve method' +say '--------------' +say Left('n',4) Right('count',6) +say '--------------' +n = 0; e = 1 +do i = 1 to xx + if i >= 1'E'e then do + say Left('10^'e,5) Right(n,8) + e = e+1 + end + if squa.flag.i then + n = n+1 +end +say '--------------' +say Format(Time('e'),,3) 'seconds' +return + +include Numbers +include Sequences +include Functions +include Abend diff --git a/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy b/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy index 476d4eeef6..54cc1b7c80 100644 --- a/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy +++ b/Task/Stable-marriage-problem/EasyLang/stable-marriage-problem.easy @@ -10,7 +10,7 @@ func finds name$[] s$ . . . . -proc read . . +proc read . s$ = input s$ = s$ for m to n @@ -35,7 +35,7 @@ len meng[] n len weng[] n len wcand[][] n # -proc engagements . . +proc engagements . print "Engagements:" for m to n w = 1 @@ -93,20 +93,20 @@ proc engagements . . . engagements # -proc showcouples . . +proc showcouples . print "Couples:" for w to n print " " & wnam$[w] & " + " & mnam$[weng[w]] . print "" . -proc swapw a b . . +proc swapw a b . print wnam$[a] & " and " & wnam$[b] & " swap their partners" print "" swap weng[a] weng[b] swap meng[weng[a]] meng[weng[b]] . -proc checkstable . . +proc checkstable . for m to n w = meng[m] for w1 to n diff --git a/Task/Stack-traces/Crystal/stack-traces.cr b/Task/Stack-traces/Crystal/stack-traces.cr new file mode 100644 index 0000000000..65ff100a45 --- /dev/null +++ b/Task/Stack-traces/Crystal/stack-traces.cr @@ -0,0 +1,15 @@ +def method1 + method2 +end + +def method2 + puts caller.join("\n") +end + +def method0 + method1 +end + +puts "-------" +method0 +puts "-------" diff --git a/Task/Stack-traces/Uxntal/stack-traces.uxnatl b/Task/Stack-traces/Uxntal/stack-traces.uxnatl new file mode 100644 index 0000000000..481d2799aa --- /dev/null +++ b/Task/Stack-traces/Uxntal/stack-traces.uxnatl @@ -0,0 +1,51 @@ +%\n { 0a } +%\s { 20 } +%\0 { 00 } +%DBG { [ LIT2 -True -System/debug ] DEO } +%newline { [ LIT2 \n -Console/write ] DEO } + +|1 @True +|0e @System/debug $1 +|18 @Console/write $1 + +|100 + +foo +DBG + +BRK + +@foo ( -- ) + #c0de + ;msgs/foo print/dbg + DBG newline + bar + JMP2r + +@bar ( -- ) + #cafe + ;msgs/bar print/dbg + DBG newline + baz + JMP2r + +@baz ( -- ) + #f00d + ;msgs/baz print/dbg + DBG newline + JMP2r + +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str + POP2 JMP2r + +@print/dbg ( str* -- ) + ;msgs/inside /str + ( str* ) !/str + +@msgs [ + &inside "Inside \s "of: \s \0 + &foo "foo. \n \0 + &bar "bar. \n \0 + &baz "baz. \n \0 ] diff --git a/Task/Stack/68000-Assembly/stack-1.68000 b/Task/Stack/68000-Assembly/stack-1.68000 index 8e778da8e3..a2efe823dd 100644 --- a/Task/Stack/68000-Assembly/stack-1.68000 +++ b/Task/Stack/68000-Assembly/stack-1.68000 @@ -1,2 +1,3 @@ -LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once! -MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, with pre-decrement +LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once! +MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, + ;with pre-decrement diff --git a/Task/Stack/Ballerina/stack-1.ballerina b/Task/Stack/Ballerina/stack-1.ballerina new file mode 100644 index 0000000000..70a1ee5ea9 --- /dev/null +++ b/Task/Stack/Ballerina/stack-1.ballerina @@ -0,0 +1,15 @@ +import ballerina/io; + +public function main() { + int[] stack = []; + stack.push(1); + stack.push(2); + io:println("Stack contains ", stack); + io:println("Number of elements in stack = ", stack.length()); + int item = stack.pop(); + io:println(item, " popped from the stack"); + io:println("Last element is now ", stack[stack.length() - 1]); + stack.removeAll(); + io:println("Stack cleared"); + io:println("Is stack now empty? ", stack.length() == 0 ? "yes" : "no"); +} diff --git a/Task/Stack/Ballerina/stack-2.ballerina b/Task/Stack/Ballerina/stack-2.ballerina new file mode 100644 index 0000000000..19641de2d8 --- /dev/null +++ b/Task/Stack/Ballerina/stack-2.ballerina @@ -0,0 +1,53 @@ +import ballerina/io; + +class Stack { + private any[] s = []; + + function push(any a) { + self.s.push(a); + } + + function length() returns int { + return self.s.length(); + } + + function isEmpty() returns boolean { + return self.length() == 0; + } + + function pop() returns any? { + if !self.isEmpty() { + return self.s.pop(); + } + return (); + } + + function peek() returns any? { + if !self.isEmpty() { + return self.s[self.length() - 1]; + } + return (); + } + + function clear() { + self.s.removeAll(); + } + + function toString() returns string { + return self.s.toString(); + } +} + +public function main() { + Stack s = new; + s.push(1); + s.push(2); + io:println("Stack contains ", s); + io:println("Number of elements in stack = ", s.length()); + any item = s.pop(); + io:println(item, " popped from the stack"); + io:println("Last element is now ", s.peek()); + s.clear(); + io:println("Stack cleared"); + io:println("Is stack now empty? ", s.isEmpty() ? "yes" : "no"); +} diff --git a/Task/Stack/C/stack-1.c b/Task/Stack/C/stack-1.c index a8e4a1dd7c..bf4fc16a09 100644 --- a/Task/Stack/C/stack-1.c +++ b/Task/Stack/C/stack-1.c @@ -2,33 +2,37 @@ #include /* to read expanded code, run through cpp | indent -st */ -#define DECL_STACK_TYPE(type, name) \ +#define DECL_STACK_TYPE(type, name) \ typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name; \ -stk_##name stk_##name##_create(size_t init_size) { \ - stk_##name s; if (!init_size) init_size = 4; \ - s = malloc(sizeof(struct stk_##name##_t)); \ - if (!s) return 0; \ - s->buf = malloc(sizeof(type) * init_size); \ - if (!s->buf) { free(s); return 0; } \ - s->len = 0, s->alloc = init_size; \ - return s; } \ -int stk_##name##_push(stk_##name s, type item) { \ - type *tmp; \ - if (s->len >= s->alloc) { \ - tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ - if (!tmp) return -1; s->buf = tmp; \ - s->alloc *= 2; } \ - s->buf[s->len++] = item; \ - return s->len; } \ -type stk_##name##_pop(stk_##name s) { \ - type tmp; \ - if (!s->len) abort(); \ - tmp = s->buf[--s->len]; \ - if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ - s->alloc /= 2; \ - s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ - return tmp; } \ -void stk_##name##_delete(stk_##name s) { \ + \ +stk_##name stk_##name##_create(size_t init_size) { \ + stk_##name s; if (!init_size) init_size = 4; \ + s = malloc(sizeof(struct stk_##name##_t)); \ + if (!s) return 0; \ + s->buf = malloc(sizeof(type) * init_size); \ + if (!s->buf) { free(s); return 0; } \ + s->len = 0, s->alloc = init_size; \ + return s; } \ + \ +int stk_##name##_push(stk_##name s, type item) { \ + type *tmp; \ + if (s->len >= s->alloc) { \ + tmp = realloc(s->buf, s->alloc*2*sizeof(type)); \ + if (!tmp) return -1; s->buf = tmp; \ + s->alloc *= 2; } \ + s->buf[s->len++] = item; \ + return s->len; } \ + \ +type stk_##name##_pop(stk_##name s) { \ + type tmp; \ + if (!s->len) abort(); \ + tmp = s->buf[--s->len]; \ + if (s->len * 2 <= s->alloc && s->alloc >= 8) { \ + s->alloc /= 2; \ + s->buf = realloc(s->buf, s->alloc * sizeof(type));} \ + return tmp; } \ + \ +void stk_##name##_delete(stk_##name s) { \ free(s->buf); free(s); } #define stk_empty(s) (!(s)->len) diff --git a/Task/Stack/EasyLang/stack.easy b/Task/Stack/EasyLang/stack.easy index f0ac75cdc2..187e06459f 100644 --- a/Task/Stack/EasyLang/stack.easy +++ b/Task/Stack/EasyLang/stack.easy @@ -1,12 +1,10 @@ stack[] = [ ] -proc push v . . +proc push v . stack[] &= v . func pop . lng = len stack[] - if lng = 0 - return 0 - . + if lng = 0 : return 0 / 0 r = stack[lng] len stack[] -1 return r diff --git a/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy index afa43455fb..bbec793fc5 100644 --- a/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy +++ b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy @@ -7,7 +7,7 @@ func step . return 0 . . -proc step_up . . +proc step_up . while step = 0 step_up . diff --git a/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy b/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy index 048d3ce437..502b4c8879 100644 --- a/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy +++ b/Task/Start-from-a-main-routine/EasyLang/start-from-a-main-routine.easy @@ -1,4 +1,4 @@ -proc main . . +proc main . print "Hello from main!" . main diff --git a/Task/State-name-puzzle/JavaScript/state-name-puzzle.js b/Task/State-name-puzzle/JavaScript/state-name-puzzle.js new file mode 100644 index 0000000000..35970b4883 --- /dev/null +++ b/Task/State-name-puzzle/JavaScript/state-name-puzzle.js @@ -0,0 +1,76 @@ +const states = ["Alabama", "Alaska", "Arizona", "Arkansas", + "California", "Colorado", "Connecticut", + "Delaware", + "Florida", "Georgia", "Hawaii", + "Idaho", "Illinois", "Indiana", "Iowa", + "Kansas", "Kentucky", "Louisiana", + "Maine", "Maryland", "Massachusetts", "Michigan", + "Minnesota", "Mississippi", "Missouri", "Montana", + "Nebraska", "Nevada", "New Hampshire", "New Jersey", + "New Mexico", "New York", "North Carolina", "North Dakota", + "Ohio", "Oklahoma", "Oregon", + "Pennsylvania", "Rhode Island", + "South Carolina", "South Dakota", "Tennessee", "Texas", + "Utah", "Vermont", "Virginia", + "Washington", "West Virginia", "Wisconsin", "Wyoming"]; + +function play(states) { + console.log(states.length, "states:"); + + // get list of unique state names + const set = new Set(states); + + // make parallel arrays for unique state names and letter histograms + const s = Array.from(set); + const h = Array(s.length).fill().map(() => Array(26).fill(0)); + + // fill histograms + s.forEach((state, i) => { + for (const c of state) { + const charCode = c.toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0); + if (charCode >= 0 && charCode < 26) { + h[i][charCode]++; + } + } + }); + + // use map to find matches. map key is sum of histograms of + // two different states. map value is indexes of the two states. + const m = new Map(); + + for (let i1 = 0; i1 < h.length; i1++) { + const h1 = h[i1]; + for (let i2 = i1 + 1; i2 < h.length; i2++) { + // sum histograms + const b = Array(26).fill(0); + for (let i = 0; i < 26; i++) { + b[i] = h1[i] + h[i2][i]; + } + + const k = b.join(','); // make key from buffer + + // Check for existing pairs with the same histogram sum + if (m.has(k)) { + const pairs = m.get(k); + // Check each pair against current pair + for (const pair of pairs) { + if (i1 !== pair.i1 && i1 !== pair.i2 && i2 !== pair.i1 && i2 !== pair.i2) { + console.log(`${s[i1]}, ${s[i2]} = ${s[pair.i1]}, ${s[pair.i2]}`); + } + } + } else { + m.set(k, []); + } + + // store this pair in the map whether printed or not + m.get(k).push({ i1, i2 }); + } + } +} + +function main() { + play(states); + play([...states, "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"]); +} + +main(); diff --git a/Task/Statistics-Basic/Ballerina/statistics-basic.ballerina b/Task/Statistics-Basic/Ballerina/statistics-basic.ballerina new file mode 100644 index 0000000000..9ab74931d9 --- /dev/null +++ b/Task/Statistics-Basic/Ballerina/statistics-basic.ballerina @@ -0,0 +1,44 @@ +import ballerina/io; +import ballerina/random; + +function mean(float[] a) returns float { + return float:sum(...a) / a.length(); +} + +function popStdDev(float[] a) returns float { + float m = mean(a); + var sumSq = function(float total, float next) returns float { + return total + next * next; + }; + return (a.reduce(sumSq, 0.0) / a.length() - m * m).sqrt(); +} + +function repeat(string s, int times) returns string { + string r = ""; + foreach int i in 1...times { r += s; } + return r; +} + +public function main() { + foreach int i in [100, 1000, 10000] { + float[] a = []; + a.setLength(i); + foreach int j in 0..(e*10).floor(); + sums[f] += 1; + } + foreach int j in 0...8 { + sums[j] = ((sums[j] / scale).round()); + io:println(` 0.${j} - 0.${j+1}: `, repeat("*", sums[j])); + } + sums[9] = 100 - int:sum(...sums.slice(0, 9)); + io:println(" 0.9 - 1.0: ", repeat("*", sums[9]), "\n"); + } +} diff --git a/Task/Statistics-Basic/EasyLang/statistics-basic.easy b/Task/Statistics-Basic/EasyLang/statistics-basic.easy index d0ce26771f..c3518514b1 100644 --- a/Task/Statistics-Basic/EasyLang/statistics-basic.easy +++ b/Task/Statistics-Basic/EasyLang/statistics-basic.easy @@ -1,24 +1,18 @@ global list[] . -proc mklist n . . +proc mklist n . list[] = [ ] - for i = 1 to n - list[] &= randomf - . + for i = 1 to n : list[] &= randomf . func mean . - for v in list[] - sum += v - . + for v in list[] : sum += v return sum / len list[] . func stddev . avg = mean - for v in list[] - squares += (avg - v) * (avg - v) - . + for v in list[] : squares += (avg - v) * (avg - v) return sqrt (squares / len list[]) . -proc histo . . +proc histo . len hist[] 10 for v in list[] ind = floor (v * 10) + 1 @@ -30,8 +24,8 @@ proc histo . . print v & " " & s$ . . -numfmt 4 5 -proc stats size . . +numfmt 5 4 +proc stats size . mklist size print "Size: " & size print "Mean: " & mean diff --git a/Task/Steffensens-method/EasyLang/steffensens-method.easy b/Task/Steffensens-method/EasyLang/steffensens-method.easy index 0dddcc4f9c..e27cf9fd42 100644 --- a/Task/Steffensens-method/EasyLang/steffensens-method.easy +++ b/Task/Steffensens-method/EasyLang/steffensens-method.easy @@ -28,18 +28,16 @@ func aitken p0 . func steffAitken p0 tol maxiter . for i to maxiter p = aitken p0 - if abs (p - p0) < tol - return p - . + if abs (p - p0) < tol : return p p0 = p . return number "nan" . for i to 11 - numfmt 1 0 + numfmt 0 1 write "t0 = " & t0 & " : " t = steffAitken t0 0.00000001 1000 - numfmt 3 0 + numfmt 0 3 if t <> t # nan print "no answer" diff --git a/Task/Steffensens-method/Rust/steffensens-method.rs b/Task/Steffensens-method/Rust/steffensens-method.rs new file mode 100644 index 0000000000..855b016f7b --- /dev/null +++ b/Task/Steffensens-method/Rust/steffensens-method.rs @@ -0,0 +1,69 @@ +use std::f64; + +fn aitken(f: fn(f64) -> f64, p0: f64) -> f64 { + let p1 = f(p0); + let p2 = f(p1); + let p1m0 = p1 - p0; + p0 - p1m0 * p1m0 / (p2 - 2.0 * p1 + p0) +} + +fn steffensen_aitken(f: fn(f64) -> f64, pinit: f64, tol: f64, maxiter: i32) -> f64 { + let mut p0 = pinit; + let mut p = aitken(f, p0); + let mut iter = 1; + while (p - p0).abs() > tol && iter < maxiter { + p0 = p; + p = aitken(f, p0); + iter += 1; + } + if (p - p0).abs() > tol { + f64::NAN + } else { + p + } +} + +fn de_casteljau(c0: f64, c1: f64, c2: f64, t: f64) -> f64 { + let s = 1.0 - t; + let c01 = s * c0 + t * c1; + let c12 = s * c1 + t * c2; + s * c01 + t * c12 +} + +fn x_convex_left_parabola(t: f64) -> f64 { + de_casteljau(2.0, -8.0, 2.0, t) +} + +fn y_convex_right_parabola(t: f64) -> f64 { + de_casteljau(1.0, 2.0, 3.0, t) +} + +fn implicit_equation(x: f64, y: f64) -> f64 { + 5.0 * x * x + y - 5.0 +} + +fn f(t: f64) -> f64 { + let x = x_convex_left_parabola(t); + let y = y_convex_right_parabola(t); + implicit_equation(x, y) + t +} + +fn main() { + let mut t0 = 0.0; + for _i in 0..11 { + print!("t0 = {:.1} : ", t0); + let t = steffensen_aitken(f, t0, 0.00000001, 1000); + if t.is_nan() { + println!("no answer"); + } else { + let x = x_convex_left_parabola(t); + let y = y_convex_right_parabola(t); + if implicit_equation(x, y).abs() <= 0.000001 { + println!("intersection at ({}, {})", x, y); + } else { + println!("spurious solution"); + } + } + t0 += 0.1; + } +} diff --git a/Task/Stem-and-leaf-plot/EasyLang/stem-and-leaf-plot.easy b/Task/Stem-and-leaf-plot/EasyLang/stem-and-leaf-plot.easy index c931ab42d8..503f34c6ca 100644 --- a/Task/Stem-and-leaf-plot/EasyLang/stem-and-leaf-plot.easy +++ b/Task/Stem-and-leaf-plot/EasyLang/stem-and-leaf-plot.easy @@ -1,24 +1,19 @@ -proc sort . d[] . - for i = 1 to len d[] - 1 - for j = i + 1 to len d[] - if d[j] < d[i] - swap d[j] d[i] - . - . +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] . . x[] = [ 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 ] sort x[] -numfmt 0 2 +numfmt 2 0 i = x[1] div 10 - 1 for j = 1 to len x[] d = x[j] div 10 while d > i i += 1 - if j > 1 - print "" - . + if j > 1 : print "" write i & " |" . write x[j] mod 10 . +print "" diff --git a/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua b/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua index 1feac8d08e..726fd51097 100644 --- a/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua +++ b/Task/Stem-and-leaf-plot/Uiua/stem-and-leaf-plot.uiua @@ -6,5 +6,5 @@ 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116] -°⊏⊕(□⊏⍏.◿10)⌊÷10. +°⊏⊕(□⍆◿10)⌊⊸÷10 ∵◇(&p$"_ | _"⬚@ ↙¯2°⋕⊙/$"_ _") diff --git a/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy b/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy index 47fda5ad77..790fbb9b7a 100644 --- a/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy +++ b/Task/Stern-Brocot-sequence/EasyLang/stern-brocot-sequence.easy @@ -1,5 +1,5 @@ global sb[] . -proc sternbrocot n . . +proc sternbrocot n . sb[] = [ 1 1 ] pos = 2 repeat diff --git a/Task/Strassens-algorithm/00-TASK.txt b/Task/Strassens-algorithm/00-TASK.txt index 1ebb38df9e..6c275f7943 100644 --- a/Task/Strassens-algorithm/00-TASK.txt +++ b/Task/Strassens-algorithm/00-TASK.txt @@ -18,3 +18,5 @@ While practical implementations of Strassen's algorithm usually switch to standa :* [[wp:Strassen algorithm|Wikipedia article]]

+ + diff --git a/Task/Strassens-algorithm/C++/strassens-algorithm.cpp b/Task/Strassens-algorithm/C++/strassens-algorithm.cpp new file mode 100644 index 0000000000..27e94e3bb6 --- /dev/null +++ b/Task/Strassens-algorithm/C++/strassens-algorithm.cpp @@ -0,0 +1,248 @@ +#include +#include +#include +#include +#include +#include + +class Matrix { +public: + std::vector> data; + size_t rows; + size_t cols; + + Matrix(const std::vector>& data) : data(data) { + rows = data.size(); + cols = (rows > 0) ? data[0].size() : 0; + } + + size_t getRows() const { + return rows; + } + + size_t getCols() const { + return cols; + } + + void validateDimensions(const Matrix& other) const { + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw std::runtime_error("Matrices must have the same dimensions."); + } + } + + void validateMultiplication(const Matrix& other) const { + if (getCols() != other.getRows()) { + throw std::runtime_error("Cannot multiply these matrices."); + } + } + + void validateSquarePowerOfTwo() const { + if (getRows() != getCols()) { + throw std::runtime_error("Matrix must be square."); + } + if (getRows() == 0 || (getRows() & (getRows() - 1)) != 0) { + throw std::runtime_error("Size of matrix must be a power of two."); + } + } + + Matrix operator+(const Matrix& other) const { + validateDimensions(other); + + std::vector> result_data(rows, std::vector(cols)); + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < cols; ++j) { + result_data[i][j] = data[i][j] + other.data[i][j]; + } + } + + return Matrix(result_data); + } + + Matrix operator-(const Matrix& other) const { + validateDimensions(other); + + std::vector> result_data(rows, std::vector(cols)); + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < cols; ++j) { + result_data[i][j] = data[i][j] - other.data[i][j]; + } + } + + return Matrix(result_data); + } + + Matrix operator*(const Matrix& other) const { + validateMultiplication(other); + + std::vector> result_data(rows, std::vector(other.cols)); + for (size_t i = 0; i < rows; ++i) { + for (size_t j = 0; j < other.cols; ++j) { + double sum = 0.0; + for (size_t k = 0; k < other.rows; ++k) { + sum += data[i][k] * other.data[k][j]; + } + result_data[i][j] = sum; + } + } + + return Matrix(result_data); + } + + friend std::ostream& operator<<(std::ostream& os, const Matrix& matrix) { + for (const auto& row : matrix.data) { + os << "["; + for (size_t i = 0; i < row.size(); ++i) { + os << row[i]; + if (i < row.size() - 1) { + os << ", "; + } + } + os << "]" << std::endl; + } + return os; + } + + std::string toStringWithPrecision(size_t p) const { + std::stringstream ss; + ss << std::fixed << std::setprecision(p); + double pow = std::pow(10.0, p); + + for (const auto& row : data) { + ss << "["; + for (size_t i = 0; i < row.size(); ++i) { + double r = std::round(row[i] * pow) / pow; + std::string formatted = ss.str(); + ss.str(std::string()); + ss << r; + formatted = ss.str(); + + if (formatted == "-0") { + ss.str(std::string()); + ss << "0"; + formatted = ss.str(); + } + + ss.str(std::string()); + ss << formatted; + + if (i < row.size() - 1) { + ss << ", "; + } + } + ss << "]" << std::endl; + + } + return ss.str(); + } + + static std::array, 4> params(size_t r, size_t c) { + return { + {{{0, r, 0, c, 0, 0}}, + {{0, r, c, 2 * c, 0, c}}, + {{r, 2 * r, 0, c, r, 0}}, + {{r, 2 * r, c, 2 * c, r, c}}} + }; + } + + std::array toQuarters() const { + size_t r = getRows() / 2; + size_t c = getCols() / 2; + auto p = Matrix::params(r, c); + std::array quarters = { + Matrix(std::vector>(r, std::vector(c, 0.0))), + Matrix(std::vector>(r, std::vector(c, 0.0))), + Matrix(std::vector>(r, std::vector(c, 0.0))), + Matrix(std::vector>(r, std::vector(c, 0.0))) + }; + + for (size_t k = 0; k < 4; ++k) { + std::vector> q_data(r, std::vector(c)); + for (size_t i = p[k][0]; i < p[k][1]; ++i) { + for (size_t j = p[k][2]; j < p[k][3]; ++j) { + q_data[i - p[k][4]][j - p[k][5]] = data[i][j]; + } + } + quarters[k] = Matrix(q_data); + } + + return quarters; + } + + static Matrix fromQuarters(const std::array& q) { + size_t r = q[0].getRows(); + size_t c = q[0].getCols(); + auto p = Matrix::params(r, c); + size_t rows = r * 2; + size_t cols = c * 2; + + std::vector> m_data(rows, std::vector(cols, 0.0)); + + for (size_t k = 0; k < 4; ++k) { + for (size_t i = p[k][0]; i < p[k][1]; ++i) { + for (size_t j = p[k][2]; j < p[k][3]; ++j) { + m_data[i][j] = q[k].data[i - p[k][4]][j - p[k][5]]; + } + } + } + + return Matrix(m_data); + } + + Matrix strassen(const Matrix& other) const { + validateSquarePowerOfTwo(); + other.validateSquarePowerOfTwo(); + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw std::runtime_error("Matrices must be square and of equal size for Strassen multiplication."); + } + + if (getRows() == 1) { + return *this * other; + } + + auto qa = toQuarters(); + auto qb = other.toQuarters(); + + Matrix p1 = (qa[1] - qa[3]).strassen(qb[2] + qb[3]); + Matrix p2 = (qa[0] + qa[3]).strassen(qb[0] + qb[3]); + Matrix p3 = (qa[0] - qa[2]).strassen(qb[0] + qb[1]); + Matrix p4 = (qa[0] + qa[1]).strassen(qb[3]); + Matrix p5 = qa[0].strassen(qb[1] - qb[3]); + Matrix p6 = qa[3].strassen(qb[2] - qb[0]); + Matrix p7 = (qa[2] + qa[3]).strassen(qb[0]); + + std::array q = { + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))), + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))), + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))), + Matrix(std::vector>(qa[0].getRows(), std::vector(qa[0].getCols(), 0.0))) + }; + + q[0] = p1 + p2 - p4 + p6; + q[1] = p4 + p5; + q[2] = p6 + p7; + q[3] = p2 - p3 + p5 - p7; + + return Matrix::fromQuarters(q); + } +}; + +int main() { + Matrix a({ {1.0, 2.0}, {3.0, 4.0} }); + Matrix b({ {5.0, 6.0}, {7.0, 8.0} }); + Matrix c({ {1.0, 1.0, 1.0, 1.0}, {2.0, 4.0, 8.0, 16.0}, {3.0, 9.0, 27.0, 81.0}, {4.0, 16.0, 64.0, 256.0} }); + Matrix d({ {4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0}, {-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0}, {3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0}, {-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0} }); + Matrix e({ {1.0, 2.0, 3.0, 4.0}, {5.0, 6.0, 7.0, 8.0}, {9.0, 10.0, 11.0, 12.0}, {13.0, 14.0, 15.0, 16.0} }); + Matrix f({ {1.0, 0.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}, {0.0, 0.0, 0.0, 1.0} }); + + std::cout << "Using 'normal' matrix multiplication:" << std::endl; + std::cout << " a * b = " << a * b << std::endl; + std::cout << " c * d = " << (c * d).toStringWithPrecision(6) << std::endl; + std::cout << " e * f = " << e * f << std::endl; + + std::cout << "\nUsing 'Strassen' matrix multiplication:" << std::endl; + std::cout << " a * b = " << a.strassen(b) << std::endl; + std::cout << " c * d = " << c.strassen(d).toStringWithPrecision(6) << std::endl; + std::cout << " e * f = " << e.strassen(f) << std::endl; + + return 0; +} diff --git a/Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs b/Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs new file mode 100644 index 0000000000..bc170318d1 --- /dev/null +++ b/Task/Strassens-algorithm/C-sharp/strassens-algorithm.cs @@ -0,0 +1,323 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +class Matrix +{ + public List> data; + public int rows; + public int cols; + + public Matrix(List> data) + { + this.data = data; + rows = data.Count; + cols = (rows > 0) ? data[0].Count : 0; + } + + public int GetRows() + { + return rows; + } + + public int GetCols() + { + return cols; + } + + public void ValidateDimensions(Matrix other) + { + if (GetRows() != other.GetRows() || GetCols() != other.GetCols()) + { + throw new InvalidOperationException("Matrices must have the same dimensions."); + } + } + + public void ValidateMultiplication(Matrix other) + { + if (GetCols() != other.GetRows()) + { + throw new InvalidOperationException("Cannot multiply these matrices."); + } + } + + public void ValidateSquarePowerOfTwo() + { + if (GetRows() != GetCols()) + { + throw new InvalidOperationException("Matrix must be square."); + } + if (GetRows() == 0 || (GetRows() & (GetRows() - 1)) != 0) + { + throw new InvalidOperationException("Size of matrix must be a power of two."); + } + } + + public static Matrix operator +(Matrix a, Matrix b) + { + a.ValidateDimensions(b); + + List> resultData = new List>(); + for (int i = 0; i < a.rows; ++i) + { + List row = new List(); + for (int j = 0; j < a.cols; ++j) + { + row.Add(a.data[i][j] + b.data[i][j]); + } + resultData.Add(row); + } + + return new Matrix(resultData); + } + + public static Matrix operator -(Matrix a, Matrix b) + { + a.ValidateDimensions(b); + + List> resultData = new List>(); + for (int i = 0; i < a.rows; ++i) + { + List row = new List(); + for (int j = 0; j < a.cols; ++j) + { + row.Add(a.data[i][j] - b.data[i][j]); + } + resultData.Add(row); + } + + return new Matrix(resultData); + } + + public static Matrix operator *(Matrix a, Matrix b) + { + a.ValidateMultiplication(b); + + List> resultData = new List>(); + for (int i = 0; i < a.rows; ++i) + { + List row = new List(); + for (int j = 0; j < b.cols; ++j) + { + double sum = 0.0; + for (int k = 0; k < b.rows; ++k) + { + sum += a.data[i][k] * b.data[k][j]; + } + row.Add(sum); + } + resultData.Add(row); + } + + return new Matrix(resultData); + } + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + foreach (var row in data) + { + sb.Append("["); + for (int i = 0; i < row.Count; ++i) + { + sb.Append(row[i]); + if (i < row.Count - 1) + { + sb.Append(", "); + } + } + sb.AppendLine("]"); + } + return sb.ToString(); + } + + public string ToStringWithPrecision(int p) + { + StringBuilder sb = new StringBuilder(); + double pow = Math.Pow(10.0, p); + + foreach (var row in data) + { + sb.Append("["); + for (int i = 0; i < row.Count; ++i) + { + double r = Math.Round(row[i] * pow) / pow; + string formatted = r.ToString($"F{p}"); + + if (formatted == "-0" + (p > 0 ? "." + new string('0', p) : "")) + { + formatted = "0" + (p > 0 ? "." + new string('0', p) : ""); + } + + sb.Append(formatted); + + if (i < row.Count - 1) + { + sb.Append(", "); + } + } + sb.AppendLine("]"); + } + return sb.ToString(); + } + + private static int[,] GetParams(int r, int c) + { + return new int[,] + { + {0, r, 0, c, 0, 0}, + {0, r, c, 2 * c, 0, c}, + {r, 2 * r, 0, c, r, 0}, + {r, 2 * r, c, 2 * c, r, c} + }; + } + + public Matrix[] ToQuarters() + { + int r = GetRows() / 2; + int c = GetCols() / 2; + int[,] p = GetParams(r, c); + Matrix[] quarters = new Matrix[4]; + + for (int k = 0; k < 4; ++k) + { + List> qData = new List>(); + for (int i = 0; i < r; i++) + { + List row = new List(); + for (int j = 0; j < c; j++) + { + row.Add(0.0); + } + qData.Add(row); + } + + for (int i = p[k, 0]; i < p[k, 1]; ++i) + { + for (int j = p[k, 2]; j < p[k, 3]; ++j) + { + qData[i - p[k, 4]][j - p[k, 5]] = data[i][j]; + } + } + quarters[k] = new Matrix(qData); + } + + return quarters; + } + + public static Matrix FromQuarters(Matrix[] q) + { + int r = q[0].GetRows(); + int c = q[0].GetCols(); + int[,] p = GetParams(r, c); + int rows = r * 2; + int cols = c * 2; + + List> mData = new List>(); + for (int i = 0; i < rows; i++) + { + List row = new List(); + for (int j = 0; j < cols; j++) + { + row.Add(0.0); + } + mData.Add(row); + } + + for (int k = 0; k < 4; ++k) + { + for (int i = p[k, 0]; i < p[k, 1]; ++i) + { + for (int j = p[k, 2]; j < p[k, 3]; ++j) + { + mData[i][j] = q[k].data[i - p[k, 4]][j - p[k, 5]]; + } + } + } + + return new Matrix(mData); + } + + public Matrix Strassen(Matrix other) + { + ValidateSquarePowerOfTwo(); + other.ValidateSquarePowerOfTwo(); + if (GetRows() != other.GetRows() || GetCols() != other.GetCols()) + { + throw new InvalidOperationException("Matrices must be square and of equal size for Strassen multiplication."); + } + + if (GetRows() == 1) + { + return this * other; + } + + Matrix[] qa = ToQuarters(); + Matrix[] qb = other.ToQuarters(); + + Matrix p1 = (qa[1] - qa[3]).Strassen(qb[2] + qb[3]); + Matrix p2 = (qa[0] + qa[3]).Strassen(qb[0] + qb[3]); + Matrix p3 = (qa[0] - qa[2]).Strassen(qb[0] + qb[1]); + Matrix p4 = (qa[0] + qa[1]).Strassen(qb[3]); + Matrix p5 = qa[0].Strassen(qb[1] - qb[3]); + Matrix p6 = qa[3].Strassen(qb[2] - qb[0]); + Matrix p7 = (qa[2] + qa[3]).Strassen(qb[0]); + + Matrix[] q = new Matrix[4]; + + q[0] = p1 + p2 - p4 + p6; + q[1] = p4 + p5; + q[2] = p6 + p7; + q[3] = p2 - p3 + p5 - p7; + + return FromQuarters(q); + } +} + +class Program +{ + static void Main(string[] args) + { + Matrix a = new Matrix(new List> { new List { 1.0, 2.0 }, new List { 3.0, 4.0 } }); + Matrix b = new Matrix(new List> { new List { 5.0, 6.0 }, new List { 7.0, 8.0 } }); + Matrix c = new Matrix(new List> + { + new List { 1.0, 1.0, 1.0, 1.0 }, + new List { 2.0, 4.0, 8.0, 16.0 }, + new List { 3.0, 9.0, 27.0, 81.0 }, + new List { 4.0, 16.0, 64.0, 256.0 } + }); + Matrix d = new Matrix(new List> + { + new List { 4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0 }, + new List { -13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0 }, + new List { 3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0 }, + new List { -1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0 } + }); + Matrix e = new Matrix(new List> + { + new List { 1.0, 2.0, 3.0, 4.0 }, + new List { 5.0, 6.0, 7.0, 8.0 }, + new List { 9.0, 10.0, 11.0, 12.0 }, + new List { 13.0, 14.0, 15.0, 16.0 } + }); + Matrix f = new Matrix(new List> + { + new List { 1.0, 0.0, 0.0, 0.0 }, + new List { 0.0, 1.0, 0.0, 0.0 }, + new List { 0.0, 0.0, 1.0, 0.0 }, + new List { 0.0, 0.0, 0.0, 1.0 } + }); + + Console.WriteLine("Using 'normal' matrix multiplication:"); + Console.WriteLine($" a * b = {a * b}"); + Console.WriteLine($" c * d = {(c * d).ToStringWithPrecision(6)}"); + Console.WriteLine($" e * f = {e * f}"); + + Console.WriteLine("\nUsing 'Strassen' matrix multiplication:"); + Console.WriteLine($" a * b = {a.Strassen(b)}"); + Console.WriteLine($" c * d = {c.Strassen(d).ToStringWithPrecision(6)}"); + Console.WriteLine($" e * f = {e.Strassen(f)}"); + } +} diff --git a/Task/Strassens-algorithm/Java/strassens-algorithm.java b/Task/Strassens-algorithm/Java/strassens-algorithm.java new file mode 100644 index 0000000000..9fed8e2eb4 --- /dev/null +++ b/Task/Strassens-algorithm/Java/strassens-algorithm.java @@ -0,0 +1,281 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +class Matrix { + public List> data; + public int rows; + public int cols; + + public Matrix(List> data) { + this.data = data; + rows = data.size(); + cols = (rows > 0) ? data.get(0).size() : 0; + } + + public int getRows() { + return rows; + } + + public int getCols() { + return cols; + } + + public void validateDimensions(Matrix other) { + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw new RuntimeException("Matrices must have the same dimensions."); + } + } + + public void validateMultiplication(Matrix other) { + if (getCols() != other.getRows()) { + throw new RuntimeException("Cannot multiply these matrices."); + } + } + + public void validateSquarePowerOfTwo() { + if (getRows() != getCols()) { + throw new RuntimeException("Matrix must be square."); + } + if (getRows() == 0 || (getRows() & (getRows() - 1)) != 0) { + throw new RuntimeException("Size of matrix must be a power of two."); + } + } + + public Matrix add(Matrix other) { + validateDimensions(other); + + List> resultData = new ArrayList<>(); + for (int i = 0; i < rows; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < cols; ++j) { + row.add(data.get(i).get(j) + other.data.get(i).get(j)); + } + resultData.add(row); + } + + return new Matrix(resultData); + } + + public Matrix subtract(Matrix other) { + validateDimensions(other); + + List> resultData = new ArrayList<>(); + for (int i = 0; i < rows; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < cols; ++j) { + row.add(data.get(i).get(j) - other.data.get(i).get(j)); + } + resultData.add(row); + } + + return new Matrix(resultData); + } + + public Matrix multiply(Matrix other) { + validateMultiplication(other); + + List> resultData = new ArrayList<>(); + for (int i = 0; i < rows; ++i) { + List row = new ArrayList<>(); + for (int j = 0; j < other.cols; ++j) { + double sum = 0.0; + for (int k = 0; k < other.rows; ++k) { + sum += data.get(i).get(k) * other.data.get(k).get(j); + } + row.add(sum); + } + resultData.add(row); + } + + return new Matrix(resultData); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (List row : data) { + sb.append("["); + for (int i = 0; i < row.size(); ++i) { + sb.append(row.get(i)); + if (i < row.size() - 1) { + sb.append(", "); + } + } + sb.append("]\n"); + } + return sb.toString(); + } + + public String toStringWithPrecision(int p) { + StringBuilder sb = new StringBuilder(); + double pow = Math.pow(10.0, p); + + for (List row : data) { + sb.append("["); + for (int i = 0; i < row.size(); ++i) { + double r = Math.round(row.get(i) * pow) / pow; + String formatted = String.format("%." + p + "f", r); + + if (formatted.equals("-0" + (p > 0 ? "." + "0".repeat(p) : ""))) { + formatted = "0" + (p > 0 ? "." + "0".repeat(p) : ""); + } + + sb.append(formatted); + + if (i < row.size() - 1) { + sb.append(", "); + } + } + sb.append("]\n"); + } + return sb.toString(); + } + + private static int[][] getParams(int r, int c) { + return new int[][] { + {0, r, 0, c, 0, 0}, + {0, r, c, 2 * c, 0, c}, + {r, 2 * r, 0, c, r, 0}, + {r, 2 * r, c, 2 * c, r, c} + }; + } + + public Matrix[] toQuarters() { + int r = getRows() / 2; + int c = getCols() / 2; + int[][] p = getParams(r, c); + Matrix[] quarters = new Matrix[4]; + + for (int k = 0; k < 4; ++k) { + List> qData = new ArrayList<>(); + for (int i = 0; i < r; i++) { + List row = new ArrayList<>(); + for (int j = 0; j < c; j++) { + row.add(0.0); + } + qData.add(row); + } + + for (int i = p[k][0]; i < p[k][1]; ++i) { + for (int j = p[k][2]; j < p[k][3]; ++j) { + qData.get(i - p[k][4]).set(j - p[k][5], data.get(i).get(j)); + } + } + quarters[k] = new Matrix(qData); + } + + return quarters; + } + + public static Matrix fromQuarters(Matrix[] q) { + int r = q[0].getRows(); + int c = q[0].getCols(); + int[][] p = getParams(r, c); + int rows = r * 2; + int cols = c * 2; + + List> mData = new ArrayList<>(); + for (int i = 0; i < rows; i++) { + List row = new ArrayList<>(); + for (int j = 0; j < cols; j++) { + row.add(0.0); + } + mData.add(row); + } + + for (int k = 0; k < 4; ++k) { + for (int i = p[k][0]; i < p[k][1]; ++i) { + for (int j = p[k][2]; j < p[k][3]; ++j) { + mData.get(i).set(j, q[k].data.get(i - p[k][4]).get(j - p[k][5])); + } + } + } + + return new Matrix(mData); + } + + public Matrix strassen(Matrix other) { + validateSquarePowerOfTwo(); + other.validateSquarePowerOfTwo(); + if (getRows() != other.getRows() || getCols() != other.getCols()) { + throw new RuntimeException("Matrices must be square and of equal size for Strassen multiplication."); + } + + if (getRows() == 1) { + return this.multiply(other); + } + + Matrix[] qa = toQuarters(); + Matrix[] qb = other.toQuarters(); + + Matrix p1 = qa[1].subtract(qa[3]).strassen(qb[2].add(qb[3])); + Matrix p2 = qa[0].add(qa[3]).strassen(qb[0].add(qb[3])); + Matrix p3 = qa[0].subtract(qa[2]).strassen(qb[0].add(qb[1])); + Matrix p4 = qa[0].add(qa[1]).strassen(qb[3]); + Matrix p5 = qa[0].strassen(qb[1].subtract(qb[3])); + Matrix p6 = qa[3].strassen(qb[2].subtract(qb[0])); + Matrix p7 = qa[2].add(qa[3]).strassen(qb[0]); + + Matrix[] q = new Matrix[4]; + + q[0] = p1.add(p2).subtract(p4).add(p6); + q[1] = p4.add(p5); + q[2] = p6.add(p7); + q[3] = p2.subtract(p3).add(p5).subtract(p7); + + return fromQuarters(q); + } +} + +public class Main{ + public static void main(String[] args) { + List> aData = new ArrayList<>(); + aData.add(Arrays.asList(1.0, 2.0)); + aData.add(Arrays.asList(3.0, 4.0)); + Matrix a = new Matrix(aData); + + List> bData = new ArrayList<>(); + bData.add(Arrays.asList(5.0, 6.0)); + bData.add(Arrays.asList(7.0, 8.0)); + Matrix b = new Matrix(bData); + + List> cData = new ArrayList<>(); + cData.add(Arrays.asList(1.0, 1.0, 1.0, 1.0)); + cData.add(Arrays.asList(2.0, 4.0, 8.0, 16.0)); + cData.add(Arrays.asList(3.0, 9.0, 27.0, 81.0)); + cData.add(Arrays.asList(4.0, 16.0, 64.0, 256.0)); + Matrix c = new Matrix(cData); + + List> dData = new ArrayList<>(); + dData.add(Arrays.asList(4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0)); + dData.add(Arrays.asList(-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0)); + dData.add(Arrays.asList(3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0)); + dData.add(Arrays.asList(-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0)); + Matrix d = new Matrix(dData); + + List> eData = new ArrayList<>(); + eData.add(Arrays.asList(1.0, 2.0, 3.0, 4.0)); + eData.add(Arrays.asList(5.0, 6.0, 7.0, 8.0)); + eData.add(Arrays.asList(9.0, 10.0, 11.0, 12.0)); + eData.add(Arrays.asList(13.0, 14.0, 15.0, 16.0)); + Matrix e = new Matrix(eData); + + List> fData = new ArrayList<>(); + fData.add(Arrays.asList(1.0, 0.0, 0.0, 0.0)); + fData.add(Arrays.asList(0.0, 1.0, 0.0, 0.0)); + fData.add(Arrays.asList(0.0, 0.0, 1.0, 0.0)); + fData.add(Arrays.asList(0.0, 0.0, 0.0, 1.0)); + Matrix f = new Matrix(fData); + + System.out.println("Using 'normal' matrix multiplication:"); + System.out.println(" a * b = " + a.multiply(b)); + System.out.println(" c * d = " + c.multiply(d).toStringWithPrecision(6)); + System.out.println(" e * f = " + e.multiply(f)); + + System.out.println("\nUsing 'Strassen' matrix multiplication:"); + System.out.println(" a * b = " + a.strassen(b)); + System.out.println(" c * d = " + c.strassen(d).toStringWithPrecision(6)); + System.out.println(" e * f = " + e.strassen(f)); + } +} diff --git a/Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js new file mode 100644 index 0000000000..6448ff9755 --- /dev/null +++ b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-1.js @@ -0,0 +1,318 @@ +/** + * Represents the dimensions of a matrix. + * @typedef {object} Shape + * @property {number} rows - Number of rows. + * @property {number} cols - Number of columns. + */ + +/** + * A matrix implemented as a wrapper around a 2D array. + */ +class Matrix { + /** + * Creates a Matrix instance. + * @param {number[][]} data - A 2D array representing the matrix data. + */ + constructor(data = []) { + if (!Array.isArray(data) || (data.length > 0 && !Array.isArray(data[0]))) { + throw new Error("Matrix data must be a 2D array."); + } + // Basic check for consistent row lengths + if (data.length > 1) { + const firstLen = data[0].length; + if (!data.every(row => row.length === firstLen)) { + throw new Error("Matrix rows must have consistent lengths."); + } + } + this.data = data; + } + + /** + * Gets the dimensions (shape) of the matrix. + * @returns {Shape} An object with rows and cols properties. + */ + get shape() { + const rows = this.data.length; + const cols = rows > 0 ? this.data[0].length : 0; + return { rows, cols }; + } + + /** + * Creates a new Matrix assembled from nested blocks of matrices. + * @param {Matrix[][]} blocks - A 2D array of Matrix objects. + * @returns {Matrix} A new Matrix assembled from the blocks. + * @static + */ + static block(blocks) { + const newMatrixData = []; + for (const hblock of blocks) { + if (!hblock || hblock.length === 0) continue; + const numRowsInBlock = hblock[0].shape.rows; // Assume consistent rows within a hblock + + for (let i = 0; i < numRowsInBlock; i++) { + let newRow = []; + for (const matrix of hblock) { + if (matrix.data[i]) { // Check if row exists + newRow = newRow.concat(matrix.data[i]); + } else { + // Handle potential inconsistencies if needed, maybe throw error or fill? + console.warn("Inconsistent row count during block assembly"); + } + } + newMatrixData.push(newRow); + } + } + return new Matrix(newMatrixData); + } + + /** + * Performs naive matrix multiplication (dot product). + * @param {Matrix} b - The matrix to multiply with. + * @returns {Matrix} The resulting matrix product. + */ + dot(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.cols !== bShape.rows) { + throw new Error(`Matrices incompatible for multiplication: ${aShape.cols} cols != ${bShape.rows} rows`); + } + + const resultData = []; + for (let i = 0; i < aShape.rows; i++) { + resultData[i] = []; + for (let j = 0; j < bShape.cols; j++) { + let sum = 0; + for (let k = 0; k < aShape.cols; k++) { + sum += this.data[i][k] * b.data[k][j]; + } + resultData[i][j] = sum; + } + } + return new Matrix(resultData); + } + + /** + * Multiplies this matrix by another matrix (using naive multiplication). + * Equivalent to Python's __matmul__. + * @param {Matrix} b - The matrix to multiply with. + * @returns {Matrix} The resulting matrix product. + */ + multiply(b) { + return this.dot(b); + } + + /** + * Adds another matrix to this matrix. + * Equivalent to Python's __add__. + * @param {Matrix} b - The matrix to add. + * @returns {Matrix} The resulting matrix sum. + */ + add(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.rows !== bShape.rows || aShape.cols !== bShape.cols) { + throw new Error("Matrices must have the same shape for addition."); + } + + const resultData = this.data.map((row, i) => + row.map((val, j) => val + b.data[i][j]) + ); + return new Matrix(resultData); + } + + /** + * Subtracts another matrix from this matrix. + * Equivalent to Python's __sub__. + * @param {Matrix} b - The matrix to subtract. + * @returns {Matrix} The resulting matrix difference. + */ + subtract(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.rows !== bShape.rows || aShape.cols !== bShape.cols) { + throw new Error("Matrices must have the same shape for subtraction."); + } + + const resultData = this.data.map((row, i) => + row.map((val, j) => val - b.data[i][j]) + ); + return new Matrix(resultData); + } + + /** + * Helper function to slice the matrix data. + * @param {number} rowStart - Starting row index (inclusive). + * @param {number} rowEnd - Ending row index (exclusive). + * @param {number} colStart - Starting column index (inclusive). + * @param {number} colEnd - Ending column index (exclusive). + * @returns {Matrix} A new Matrix containing the sliced data. + * @private // Indicates intended internal use + */ + _slice(rowStart, rowEnd, colStart, colEnd) { + const slicedData = this.data.slice(rowStart, rowEnd) + .map(row => row.slice(colStart, colEnd)); + return new Matrix(slicedData); + } + + /** + * Performs matrix multiplication using Strassen's algorithm. + * Requires square matrices whose dimensions are powers of 2. + * @param {Matrix} b - The matrix to multiply with. + * @returns {Matrix} The resulting matrix product. + */ + strassen(b) { + if (!(b instanceof Matrix)) { + throw new Error("Argument must be a Matrix instance."); + } + const aShape = this.shape; + const bShape = b.shape; + + if (aShape.rows !== aShape.cols) { + throw new Error("Matrix must be square for Strassen's algorithm."); + } + if (aShape.rows !== bShape.rows || aShape.cols !== bShape.cols) { + throw new Error("Matrices must have the same shape for Strassen's algorithm."); + } + // Check if dimension is a power of 2 + if (aShape.rows === 0 || (aShape.rows & (aShape.rows - 1)) !== 0) { + throw new Error("Matrix dimension must be a power of 2 for Strassen's algorithm."); + } + + if (aShape.rows === 1) { + return this.dot(b); // Base case + } + + const n = aShape.rows; + const p = n / 2; // Partition size + + // Partition matrices + const a11 = this._slice(0, p, 0, p); + const a12 = this._slice(0, p, p, n); + const a21 = this._slice(p, n, 0, p); + const a22 = this._slice(p, n, p, n); + + const b11 = b._slice(0, p, 0, p); + const b12 = b._slice(0, p, p, n); + const b21 = b._slice(p, n, 0, p); + const b22 = b._slice(p, n, p, n); + + // Recursive calls (Strassen's 7 multiplications) + const m1 = (a11.add(a22)).strassen(b11.add(b22)); + const m2 = (a21.add(a22)).strassen(b11); + const m3 = a11.strassen(b12.subtract(b22)); + const m4 = a22.strassen(b21.subtract(b11)); + const m5 = (a11.add(a12)).strassen(b22); + const m6 = (a21.subtract(a11)).strassen(b11.add(b12)); + const m7 = (a12.subtract(a22)).strassen(b21.add(b22)); + + // Combine results + const c11 = m1.add(m4).subtract(m5).add(m7); + const c12 = m3.add(m5); + const c21 = m2.add(m4); + const c22 = m1.subtract(m2).add(m3).add(m6); + + // Assemble the final matrix from blocks + return Matrix.block([[c11, c12], [c21, c22]]); + } + + /** + * Rounds the elements of the matrix to a specified number of decimal places. + * @param {number} [ndigits=0] - Number of decimal places to round to. If undefined or 0, rounds to the nearest integer. + * @returns {Matrix} A new Matrix with rounded elements. + */ + round(ndigits = 0) { + const factor = Math.pow(10, ndigits); + const roundFn = ndigits > 0 + ? (num) => Math.round((num + Number.EPSILON) * factor) / factor + : (num) => Math.round(num); + + const roundedData = this.data.map(row => + row.map(val => roundFn(val)) + ); + return new Matrix(roundedData); + } + + /** + * Provides a string representation of the matrix. + * @returns {string} The string representation. + */ + toString() { + const rowsStr = this.data.map(row => ` [${row.join(', ')}]`); + return `Matrix([\n${rowsStr.join(',\n')}\n])`; + } +} + +// --- Examples --- + +function examples() { + const a = new Matrix([ + [1, 2], + [3, 4], + ]); + const b = new Matrix([ + [5, 6], + [7, 8], + ]); + const c = new Matrix([ + [1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256], + ]); + const d = new Matrix([ + [4, -3, 4 / 3, -1 / 4], + [-13 / 3, 19 / 4, -7 / 3, 11 / 24], + [3 / 2, -2, 7 / 6, -1 / 4], + [-1 / 6, 1 / 4, -1 / 6, 1 / 24], + ]); + const e = new Matrix([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16], + ]); + const f = new Matrix([ // Identity matrix + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ]); + + console.log("Naive matrix multiplication:"); + console.log(` a * b = ${a.multiply(b)}`); // Uses toString implicitly + console.log(` c * d = ${c.multiply(d).round(2)}`); // Round near-zero elements + console.log(` e * f = ${e.multiply(f)}`); + + console.log("\nStrassen's matrix multiplication:"); + console.log(` a * b = ${a.strassen(b)}`); + console.log(` c * d = ${c.strassen(d).round(2)}`); // Round near-zero elements + console.log(` e * f = ${e.strassen(f)}`); + + // Example of addition/subtraction + console.log("\nAddition/Subtraction:"); + const sum_ab = a.add(b); + console.log(` a + b = ${sum_ab}`); + const diff_ba = b.subtract(a); + console.log(` b - a = ${diff_ba}`); + + // Example of block creation (creates a 4x4 matrix from four 2x2 matrices) + console.log("\nBlock Creation:"); + const blocked = Matrix.block([[a, b], [b, a]]); + console.log(` Blocked [a,b],[b,a] = ${blocked}`); + +} + +// Run examples +examples(); diff --git a/Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js new file mode 100644 index 0000000000..1e6ff77ebf --- /dev/null +++ b/Task/Strassens-algorithm/JavaScript/strassens-algorithm-2.js @@ -0,0 +1,316 @@ +class Matrix { + /** @type {number[][]} */ + data; + /** @type {number} */ + rows; + /** @type {number} */ + cols; + + /** + * @param {number[][]} data The matrix data as a 2D array. + */ + constructor(data) { + if (!Array.isArray(data) || (data.length > 0 && !Array.isArray(data[0]))) { + throw new Error("Input data must be a 2D array."); + } + // Optional: Deep copy to prevent external modifications + this.data = data.map(row => [...row]); + this.rows = data.length; + this.cols = (this.rows > 0) ? (data[0]?.length ?? 0) : 0; // Handle empty rows gracefully + + // Optional: Validate that all rows have the same length + if (this.rows > 0) { + const firstRowLength = this.cols; + for (let i = 1; i < this.rows; i++) { + if (data[i].length !== firstRowLength) { + throw new Error("All rows in the matrix must have the same length."); + } + } + } + } + + /** @returns {number} */ + getRows() { + return this.rows; + } + + /** @returns {number} */ + getCols() { + return this.cols; + } + + /** @param {Matrix} other */ + validateDimensions(other) { + if (this.getRows() !== other.getRows() || this.getCols() !== other.getCols()) { + throw new Error("Matrices must have the same dimensions."); + } + } + + /** @param {Matrix} other */ + validateMultiplication(other) { + if (this.getCols() !== other.getRows()) { + throw new Error(`Cannot multiply matrices: (${this.getRows()}x${this.getCols()}) * (${other.getRows()}x${other.getCols()})`); + } + } + + validateSquarePowerOfTwo() { + if (this.getRows() !== this.getCols()) { + throw new Error("Matrix must be square for this operation."); + } + const n = this.getRows(); + // Check if n is 0 or not a power of two + // (n & (n - 1)) === 0 checks if n is a power of two (or 0) + if (n === 0 || (n & (n - 1)) !== 0) { + throw new Error("Size of matrix must be a power of two for Strassen."); + } + } + + /** + * Adds another matrix to this matrix. + * @param {Matrix} other The matrix to add. + * @returns {Matrix} A new matrix representing the sum. + */ + add(other) { + this.validateDimensions(other); + + const result_data = Array.from({ length: this.rows }, () => Array(this.cols).fill(0.0)); + for (let i = 0; i < this.rows; ++i) { + for (let j = 0; j < this.cols; ++j) { + result_data[i][j] = this.data[i][j] + other.data[i][j]; + } + } + + return new Matrix(result_data); + } + + /** + * Subtracts another matrix from this matrix. + * @param {Matrix} other The matrix to subtract. + * @returns {Matrix} A new matrix representing the difference. + */ + subtract(other) { + this.validateDimensions(other); + + const result_data = Array.from({ length: this.rows }, () => Array(this.cols).fill(0.0)); + for (let i = 0; i < this.rows; ++i) { + for (let j = 0; j < this.cols; ++j) { + result_data[i][j] = this.data[i][j] - other.data[i][j]; + } + } + + return new Matrix(result_data); + } + + /** + * Multiplies this matrix by another matrix (standard algorithm). + * @param {Matrix} other The matrix to multiply by. + * @returns {Matrix} A new matrix representing the product. + */ + multiply(other) { + this.validateMultiplication(other); + + const result_data = Array.from({ length: this.rows }, () => Array(other.cols).fill(0.0)); + for (let i = 0; i < this.rows; ++i) { + for (let j = 0; j < other.cols; ++j) { + let sum = 0.0; + // K loops through columns of 'this' and rows of 'other' + for (let k = 0; k < this.cols; ++k) { + sum += this.data[i][k] * other.data[k][j]; + } + result_data[i][j] = sum; + } + } + + return new Matrix(result_data); + } + + /** + * Returns a string representation of the matrix. + * @returns {string} + */ + toString() { + return this.data.map(row => `[${row.join(', ')}]`).join('\n'); + } + + /** + * Returns a string representation with specified precision, handling rounding and "-0". + * @param {number} p Precision (number of decimal places). + * @returns {string} + */ + toStringWithPrecision(p) { + let resultString = ""; + const pow = Math.pow(10, p); + const zeroString = (0).toFixed(p); + const negZeroString = `-${zeroString}`; + + for (const row of this.data) { + resultString += "["; + for (let i = 0; i < row.length; ++i) { + let val = row[i]; + // Round like C++: round(val * 10^p) / 10^p + let roundedVal = Math.round(val * pow) / pow; + + // Format to fixed precision + let formattedVal = roundedVal.toFixed(p); + + // Handle the "-0.00..." case that toFixed might produce after rounding + if (formattedVal === negZeroString) { + formattedVal = zeroString; + } + + resultString += formattedVal; + if (i < row.length - 1) { + resultString += ", "; + } + } + resultString += "]\n"; // Add newline after each row like C++ example + } + return resultString.trimEnd(); // Remove trailing newline + } + + /** + * Helper function to get quadrant slicing parameters. + * @param {number} r Half rows + * @param {number} c Half columns + * @returns {number[][]} Array of [startRow, endRow, startCol, endCol, offsetRow, offsetCol] + */ + static params(r, c) { + // [startRow, endRow, startCol, endCol, resultOffsetRow, resultOffsetCol] + return [ + [0, r, 0, c, 0, 0], // Top-left quadrant (0) + [0, r, c, 2 * c, 0, c], // Top-right quadrant (1) + [r, 2 * r, 0, c, r, 0], // Bottom-left quadrant (2) + [r, 2 * r, c, 2 * c, r, c] // Bottom-right quadrant (3) + ]; + } + + /** + * Splits the matrix into four equally sized quadrants. + * Assumes matrix dimensions are even. + * @returns {Matrix[]} An array of four matrices [TopLeft, TopRight, BottomLeft, BottomRight]. + */ + toQuarters() { + const r = this.getRows() / 2; + const c = this.getCols() / 2; + if (!Number.isInteger(r) || !Number.isInteger(c)) { + throw new Error("Matrix dimensions must be even for splitting into quarters."); + } + const p = Matrix.params(r, c); + const quarters = Array(4); // Will hold 4 Matrix objects + + for (let k = 0; k < 4; ++k) { + const q_data = Array.from({ length: r }, () => Array(c)); + const [startRow, endRow, startCol, endCol, offsetRow, offsetCol] = p[k]; + for (let i = startRow; i < endRow; ++i) { + for (let j = startCol; j < endCol; ++j) { + // Adjust indices for the smaller quarter matrix + q_data[i - offsetRow][j - offsetCol] = this.data[i][j]; + } + } + quarters[k] = new Matrix(q_data); + } + return quarters; // [TopLeft, TopRight, BottomLeft, BottomRight] + } + + /** + * Creates a new matrix by combining four quadrant matrices. + * @param {Matrix[]} q An array of four matrices [TopLeft, TopRight, BottomLeft, BottomRight]. + * @returns {Matrix} The combined matrix. + */ + static fromQuarters(q) { + if (q.length !== 4) throw new Error("Requires exactly four quadrant matrices."); + // Basic validation: Ensure quadrants have compatible dimensions + const r = q[0].getRows(); + const c = q[0].getCols(); + if (q[1].getRows() !== r || q[1].getCols() !== c || + q[2].getRows() !== r || q[2].getCols() !== c || + q[3].getRows() !== r || q[3].getCols() !== c) { + throw new Error("Quadrant matrices must have the same dimensions."); + } + + const p = Matrix.params(r, c); + const rows = r * 2; + const cols = c * 2; + const m_data = Array.from({ length: rows }, () => Array(cols)); + + for (let k = 0; k < 4; ++k) { + const [startRow, endRow, startCol, endCol, offsetRow, offsetCol] = p[k]; + for (let i = startRow; i < endRow; ++i) { + for (let j = startCol; j < endCol; ++j) { + // Adjust indices to read from the correct quadrant + m_data[i][j] = q[k].data[i - offsetRow][j - offsetCol]; + } + } + } + return new Matrix(m_data); + } + + /** + * Multiplies this matrix by another using Strassen's algorithm. + * Assumes both matrices are square and their size is a power of two. + * @param {Matrix} other The matrix to multiply by. + * @returns {Matrix} The resulting matrix product. + */ + strassen(other) { + this.validateSquarePowerOfTwo(); + other.validateSquarePowerOfTwo(); + if (this.getRows() !== other.getRows()) { // Columns already checked by validateSquarePowerOfTwo + throw new Error("Matrices must be square and of equal size for Strassen multiplication."); + } + + // Base case: If the matrix is 1x1 + if (this.getRows() === 1) { + // Use standard multiplication for the 1x1 case + return this.multiply(other); + } + + // Split matrices into quarters + const qa = this.toQuarters(); // [a11, a12, a21, a22] + const qb = other.toQuarters(); // [b11, b12, b21, b22] + + // Calculate the 7 products recursively (P1 to P7) + const p1 = (qa[1].subtract(qa[3])).strassen(qb[2].add(qb[3])); // p1 = (a12 - a22) * (b21 + b22) + const p2 = (qa[0].add(qa[3])).strassen(qb[0].add(qb[3])); // p2 = (a11 + a22) * (b11 + b22) + const p3 = (qa[0].subtract(qa[2])).strassen(qb[0].add(qb[1])); // p3 = (a11 - a21) * (b11 + b12) + const p4 = (qa[0].add(qa[1])).strassen(qb[3]); // p4 = (a11 + a12) * b22 + const p5 = qa[0].strassen(qb[1].subtract(qb[3])); // p5 = a11 * (b12 - b22) + const p6 = qa[3].strassen(qb[2].subtract(qb[0])); // p6 = a22 * (b21 - b11) + const p7 = (qa[2].add(qa[3])).strassen(qb[0]); // p7 = (a21 + a22) * b11 + + // Calculate the result quarters (C11, C12, C21, C22) + const c11 = p1.add(p2).subtract(p4).add(p6); + const c12 = p4.add(p5); + const c21 = p6.add(p7); + const c22 = p2.subtract(p3).add(p5).subtract(p7); + + // Combine the quarters into the result matrix + return Matrix.fromQuarters([c11, c12, c21, c22]); + } +} + +// --- Main execution (equivalent to C++ main) --- +function main() { + const a = new Matrix([[1.0, 2.0], [3.0, 4.0]]); + const b = new Matrix([[5.0, 6.0], [7.0, 8.0]]); + const c = new Matrix([[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]]); + const d = new Matrix([[4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0], [-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0], [3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0], [-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0]]); + const e = new Matrix([[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]); + const f = new Matrix([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]); // Identity Matrix + + console.log("Using 'normal' matrix multiplication:"); + console.log(` a * b = \n${a.multiply(b).toString()}`); + console.log(`\n c * d = \n${c.multiply(d).toStringWithPrecision(6)}`); // Should be close to identity + console.log(`\n e * f = \n${e.multiply(f).toString()}`); // Should be e + + console.log("\nUsing 'Strassen' matrix multiplication:"); + try { + console.log(` a * b = \n${a.strassen(b).toString()}`); + console.log(`\n c * d = \n${c.strassen(d).toStringWithPrecision(6)}`); // Should be close to identity + console.log(`\n e * f = \n${e.strassen(f).toString()}`); // Should be e + } catch (error) { + console.error("Strassen multiplication failed:", error.message); + } +} + +// Run the main function +main(); diff --git a/Task/Strassens-algorithm/Rust/strassens-algorithm.rs b/Task/Strassens-algorithm/Rust/strassens-algorithm.rs new file mode 100644 index 0000000000..d715f9deea --- /dev/null +++ b/Task/Strassens-algorithm/Rust/strassens-algorithm.rs @@ -0,0 +1,269 @@ +use std::fmt; +use std::ops::{Add, Mul, Sub}; + +#[derive(Debug, Clone)] +struct Matrix { + data: Vec>, + rows: usize, + cols: usize, +} + +impl Matrix { + fn new(data: Vec>) -> Self { + let rows = data.len(); + let cols = if rows > 0 { data[0].len() } else { 0 }; + Matrix { data, rows, cols } + } + + fn rows(&self) -> usize { + self.rows + } + + fn cols(&self) -> usize { + self.cols + } + + fn validate_dimensions(&self, other: &Matrix) { + if self.rows() != other.rows() || self.cols() != other.cols() { + panic!("Matrices must have the same dimensions."); + } + } + + fn validate_multiplication(&self, other: &Matrix) { + if self.cols() != other.rows() { + panic!("Cannot multiply these matrices."); + } + } + + fn validate_square_power_of_two(&self) { + if self.rows() != self.cols() { + panic!("Matrix must be square."); + } + if self.rows() == 0 || (self.rows() & (self.rows() - 1)) != 0 { + panic!("Size of matrix must be a power of two."); + } + } +} + +impl Add for Matrix { + type Output = Self; + + fn add(self, other: Self) -> Self { + self.validate_dimensions(&other); + + let mut result_data = Vec::with_capacity(self.rows()); + for i in 0..self.rows() { + let mut row = Vec::with_capacity(self.cols()); + for j in 0..self.cols() { + row.push(self.data[i][j] + other.data[i][j]); + } + result_data.push(row); + } + + Matrix::new(result_data) + } +} + +impl Sub for Matrix { + type Output = Self; + + fn sub(self, other: Self) -> Self { + self.validate_dimensions(&other); + + let mut result_data = Vec::with_capacity(self.rows()); + for i in 0..self.rows() { + let mut row = Vec::with_capacity(self.cols()); + for j in 0..self.cols() { + row.push(self.data[i][j] - other.data[i][j]); + } + result_data.push(row); + } + + Matrix::new(result_data) + } +} + +impl Mul for Matrix { + type Output = Self; + + fn mul(self, other: Self) -> Self { + self.validate_multiplication(&other); + + let mut result_data = Vec::with_capacity(self.rows()); + for i in 0..self.rows() { + let mut row = Vec::with_capacity(other.cols()); + for j in 0..other.cols() { + let mut sum = 0.0; + for k in 0..other.rows() { + sum += self.data[i][k] * other.data[k][j]; + } + row.push(sum); + } + result_data.push(row); + } + + Matrix::new(result_data) + } +} + +impl fmt::Display for Matrix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut s = String::new(); + for row in &self.data { + s.push_str(&format!("{:?}\n", row)); + } + write!(f, "{}", s) + } +} + +impl Matrix { + fn to_string_with_precision(&self, p: usize) -> String { + let mut s = String::new(); + let pow = 10.0_f64.powi(p as i32); + for row in &self.data { + let mut t = Vec::new(); + for &val in row { + let r = (val * pow).round() / pow; + let formatted = format!("{}", r); + if formatted == "-0" { + t.push("0".to_string()); + } else { + t.push(formatted); + } + } + s.push_str(&format!("{:?}\n", t)); + } + s + } + + fn params(r: usize, c: usize) -> [[usize; 6]; 4] { + [ + [0, r, 0, c, 0, 0], + [0, r, c, 2 * c, 0, c], + [r, 2 * r, 0, c, r, 0], + [r, 2 * r, c, 2 * c, r, c], + ] + } + + fn to_quarters(&self) -> [Matrix; 4] { + let r = self.rows() / 2; + let c = self.cols() / 2; + let p = Matrix::params(r, c); + let mut quarters: [Matrix; 4] = [ + Matrix::new(vec![vec![0.0; c]; r]), + Matrix::new(vec![vec![0.0; c]; r]), + Matrix::new(vec![vec![0.0; c]; r]), + Matrix::new(vec![vec![0.0; c]; r]), + ]; + + for k in 0..4 { + let mut q_data = Vec::with_capacity(r); + for i in p[k][0]..p[k][1] { + let mut row = Vec::with_capacity(c); + for j in p[k][2]..p[k][3] { + row.push(self.data[i][j]); + } + q_data.push(row); + } + quarters[k] = Matrix::new(q_data); + } + + quarters + } + + fn from_quarters(q: [Matrix; 4]) -> Matrix { + let r = q[0].rows(); + let c = q[0].cols(); + let p = Matrix::params(r, c); + let rows = r * 2; + let cols = c * 2; + + let mut m_data = vec![vec![0.0; cols]; rows]; + + for k in 0..4 { + for i in p[k][0]..p[k][1] { + for j in p[k][2]..p[k][3] { + m_data[i][j] = q[k].data[i - p[k][4]][j - p[k][5]]; + } + } + } + + Matrix::new(m_data) + } + + fn strassen(&self, other: Matrix) -> Matrix { + self.validate_square_power_of_two(); + other.validate_square_power_of_two(); + if self.rows() != other.rows() || self.cols() != other.cols() { + panic!("Matrices must be square and of equal size for Strassen multiplication."); + } + + if self.rows() == 1 { + return self.clone() * other; + } + + let qa = self.to_quarters(); + let qb = other.to_quarters(); + + let p1 = (qa[1].clone() - qa[3].clone()).strassen(qb[2].clone() + qb[3].clone()); + let p2 = (qa[0].clone() + qa[3].clone()).strassen(qb[0].clone() + qb[3].clone()); + let p3 = (qa[0].clone() - qa[2].clone()).strassen(qb[0].clone() + qb[1].clone()); + let p4 = (qa[0].clone() + qa[1].clone()).strassen(qb[3].clone()); + let p5 = qa[0].clone().strassen(qb[1].clone() - qb[3].clone()); + let p6 = qa[3].clone().strassen(qb[2].clone() - qb[0].clone()); + let p7 = (qa[2].clone() + qa[3].clone()).strassen(qb[0].clone()); + + let mut q: [Matrix; 4] = [ + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + Matrix::new(vec![vec![0.0; qa[0].cols()]; qa[0].rows()]), + ]; + + q[0] = p1.clone() + p2.clone() - p4.clone() + p6.clone(); + q[1] = p4 + p5.clone(); + q[2] = p6 + p7.clone(); + q[3] = p2 - p3.clone() + p5 - p7; + + Matrix::from_quarters(q) + } +} + +fn main() { + let a = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]); + let b = Matrix::new(vec![vec![5.0, 6.0], vec![7.0, 8.0]]); + let c = Matrix::new(vec![ + vec![1.0, 1.0, 1.0, 1.0], + vec![2.0, 4.0, 8.0, 16.0], + vec![3.0, 9.0, 27.0, 81.0], + vec![4.0, 16.0, 64.0, 256.0], + ]); + let d = Matrix::new(vec![ + vec![4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0], + vec![-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0], + vec![3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0], + vec![-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0], + ]); + let e = Matrix::new(vec![ + vec![1.0, 2.0, 3.0, 4.0], + vec![5.0, 6.0, 7.0, 8.0], + vec![9.0, 10.0, 11.0, 12.0], + vec![13.0, 14.0, 15.0, 16.0], + ]); + let f = Matrix::new(vec![ + vec![1.0, 0.0, 0.0, 0.0], + vec![0.0, 1.0, 0.0, 0.0], + vec![0.0, 0.0, 1.0, 0.0], + vec![0.0, 0.0, 0.0, 1.0], + ]); + + println!("Using 'normal' matrix multiplication:"); + println!(" a * b = {}", a.clone() * b.clone()); + println!(" c * d = {}", (c.clone() * d.clone()).to_string_with_precision(6)); + println!(" e * f = {}", e.clone() * f.clone()); + + println!("\nUsing 'Strassen' matrix multiplication:"); + println!(" a * b = {}", a.strassen(b)); + println!(" c * d = {}", c.strassen(d).to_string_with_precision(6)); + println!(" e * f = {}", e.strassen(f)); +} diff --git a/Task/Strassens-algorithm/Zig/strassens-algorithm.zig b/Task/Strassens-algorithm/Zig/strassens-algorithm.zig new file mode 100644 index 0000000000..9297f6eb48 --- /dev/null +++ b/Task/Strassens-algorithm/Zig/strassens-algorithm.zig @@ -0,0 +1,477 @@ +const std = @import("std"); +const fmt = std.fmt; +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +const Matrix = struct { + data: ArrayList(ArrayList(f64)), + rows: usize, + cols: usize, + allocator: Allocator, + + pub fn init(allocator: Allocator, data: ArrayList(ArrayList(f64))) !Matrix { + const rows = data.items.len; + const cols = if (rows > 0) data.items[0].items.len else 0; + + return Matrix{ + .data = data, + .rows = rows, + .cols = cols, + .allocator = allocator, + }; + } + + pub fn deinit(self: *Matrix) void { + for (self.data.items) |*row| { + row.deinit(); + } + self.data.deinit(); + } + + pub fn clone(self: Matrix) !Matrix { + var new_data = ArrayList(ArrayList(f64)).init(self.allocator); + try new_data.ensureTotalCapacity(self.rows); + + for (self.data.items) |row| { + var new_row = ArrayList(f64).init(self.allocator); + try new_row.ensureTotalCapacity(self.cols); + try new_row.appendSlice(row.items); + try new_data.append(new_row); + } + + return Matrix{ + .data = new_data, + .rows = self.rows, + .cols = self.cols, + .allocator = self.allocator, + }; + } + + pub fn validateDimensions(self: Matrix, other: Matrix) !void { + if (self.rows != other.rows or self.cols != other.cols) { + return error.DimensionMismatch; + } + } + + pub fn validateMultiplication(self: Matrix, other: Matrix) !void { + if (self.cols != other.rows) { + return error.CannotMultiply; + } + } + + pub fn validateSquarePowerOfTwo(self: Matrix) !void { + if (self.rows != self.cols) { + return error.NotSquare; + } + if (self.rows == 0 or (self.rows & (self.rows - 1)) != 0) { + return error.NotPowerOfTwo; + } + } + + pub fn add(self: Matrix, other: Matrix) !Matrix { + try self.validateDimensions(other); + + var result_data = ArrayList(ArrayList(f64)).init(self.allocator); + try result_data.ensureTotalCapacity(self.rows); + + for (0..self.rows) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(self.cols); + + for (0..self.cols) |j| { + try row.append(self.data.items[i].items[j] + other.data.items[i].items[j]); + } + try result_data.append(row); + } + + return try Matrix.init(self.allocator, result_data); + } + + pub fn sub(self: Matrix, other: Matrix) !Matrix { + try self.validateDimensions(other); + + var result_data = ArrayList(ArrayList(f64)).init(self.allocator); + try result_data.ensureTotalCapacity(self.rows); + + for (0..self.rows) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(self.cols); + + for (0..self.cols) |j| { + try row.append(self.data.items[i].items[j] - other.data.items[i].items[j]); + } + try result_data.append(row); + } + + return try Matrix.init(self.allocator, result_data); + } + + pub fn mul(self: Matrix, other: Matrix) !Matrix { + try self.validateMultiplication(other); + + var result_data = ArrayList(ArrayList(f64)).init(self.allocator); + try result_data.ensureTotalCapacity(self.rows); + + for (0..self.rows) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(other.cols); + + for (0..other.cols) |j| { + var sum: f64 = 0.0; + for (0..self.cols) |k| { + sum += self.data.items[i].items[k] * other.data.items[k].items[j]; + } + try row.append(sum); + } + try result_data.append(row); + } + + return try Matrix.init(self.allocator, result_data); + } + + pub fn format(self: Matrix, comptime _: []const u8, _: fmt.FormatOptions, writer: anytype) !void { + for (self.data.items) |row| { + try writer.print("{any}\n", .{row.items}); + } + } + + pub fn toStringWithPrecision(self: Matrix, p: usize, allocator: Allocator) ![]u8 { + var output = ArrayList(u8).init(allocator); + defer output.deinit(); + + const pow = std.math.pow(f64, 10.0, @as(f64, @floatFromInt(p))); + + for (self.data.items) |row| { + var formatted_row = ArrayList([]const u8).init(allocator); + defer { + for (formatted_row.items) |item| { + allocator.free(item); + } + formatted_row.deinit(); + } + + for (row.items) |val| { + const r = @round(val * pow) / pow; + const formatted = try fmt.allocPrint(allocator, "{d}", .{r}); + + if (std.mem.eql(u8, formatted, "-0")) { + allocator.free(formatted); + try formatted_row.append(try allocator.dupe(u8, "0")); + } else { + try formatted_row.append(formatted); + } + } + + std.debug.print("{any}\n", .{formatted_row.items}); + } + + return output.toOwnedSlice(); + } + + fn params(r: usize, c: usize) [4][6]usize { + return [4][6]usize{ + [_]usize{ 0, r, 0, c, 0, 0 }, + [_]usize{ 0, r, c, 2 * c, 0, c }, + [_]usize{ r, 2 * r, 0, c, r, 0 }, + [_]usize{ r, 2 * r, c, 2 * c, r, c }, + }; + } + + pub fn toQuarters(self: Matrix) ![4]Matrix { + const r = self.rows / 2; + const c = self.cols / 2; + const p = Matrix.params(r, c); + + var quarters: [4]Matrix = undefined; + + for (0..4) |k| { + var q_data = ArrayList(ArrayList(f64)).init(self.allocator); + try q_data.ensureTotalCapacity(r); + + for (p[k][0]..p[k][1]) |i| { + var row = ArrayList(f64).init(self.allocator); + try row.ensureTotalCapacity(c); + + for (p[k][2]..p[k][3]) |j| { + try row.append(self.data.items[i].items[j]); + } + try q_data.append(row); + } + + quarters[k] = try Matrix.init(self.allocator, q_data); + } + + return quarters; + } + + pub fn fromQuarters(q: [4]Matrix, allocator: Allocator) !Matrix { + const r = q[0].rows; + const c = q[0].cols; + const p = Matrix.params(r, c); + const rows = r * 2; + const cols = c * 2; + + var m_data = ArrayList(ArrayList(f64)).init(allocator); + try m_data.ensureTotalCapacity(rows); + + for (0..rows) |_| { + var row = ArrayList(f64).init(allocator); + try row.ensureTotalCapacity(cols); + for (0..cols) |_| { + try row.append(0.0); + } + try m_data.append(row); + } + + for (0..4) |k| { + for (p[k][0]..p[k][1]) |i| { + for (p[k][2]..p[k][3]) |j| { + m_data.items[i].items[j] = q[k].data.items[i - p[k][4]].items[j - p[k][5]]; + } + } + } + + return try Matrix.init(allocator, m_data); + } + + pub fn strassen(self: Matrix, other: Matrix) !Matrix { + try self.validateSquarePowerOfTwo(); + try other.validateSquarePowerOfTwo(); + + if (self.rows != other.rows or self.cols != other.cols) { + return error.InvalidDimensions; + } + + if (self.rows == 1) { + return self.mul(other); + } + + var qa = try self.toQuarters(); + defer for (&qa) |*q| q.deinit(); + + var qb = try other.toQuarters(); + defer for (&qb) |*q| q.deinit(); + + var t1 = try qa[1].sub(qa[3]); + defer t1.deinit(); + var t2 = try qb[2].add(qb[3]); + defer t2.deinit(); + var p1 = try t1.strassen(t2); + defer p1.deinit(); + + var t3 = try qa[0].add(qa[3]); + defer t3.deinit(); + var t4 = try qb[0].add(qb[3]); + defer t4.deinit(); + var p2 = try t3.strassen(t4); + defer p2.deinit(); + + var t5 = try qa[0].sub(qa[2]); + defer t5.deinit(); + var t6 = try qb[0].add(qb[1]); + defer t6.deinit(); + var p3 = try t5.strassen(t6); + defer p3.deinit(); + + var t7 = try qa[0].add(qa[1]); + defer t7.deinit(); + var p4 = try t7.strassen(qb[3]); + defer p4.deinit(); + + var t8 = try qb[1].sub(qb[3]); + defer t8.deinit(); + var p5 = try qa[0].strassen(t8); + defer p5.deinit(); + + var t9 = try qb[2].sub(qb[0]); + defer t9.deinit(); + var p6 = try qa[3].strassen(t9); + defer p6.deinit(); + + var t10 = try qa[2].add(qa[3]); + defer t10.deinit(); + var p7 = try t10.strassen(qb[0]); + defer p7.deinit(); + + var q: [4]Matrix = undefined; + + // q[0] = p1 + p2 - p4 + p6 + var ta = try p1.add(p2); + defer ta.deinit(); + var tb = try ta.sub(p4); + defer tb.deinit(); + q[0] = try tb.add(p6); + + // q[1] = p4 + p5 + q[1] = try p4.add(p5); + + // q[2] = p6 + p7 + q[2] = try p6.add(p7); + + // q[3] = p2 - p3 + p5 - p7 + var tc = try p2.sub(p3); + defer tc.deinit(); + var td = try tc.add(p5); + defer td.deinit(); + q[3] = try td.sub(p7); + + defer for (&q) |*quarter| quarter.deinit(); + + return Matrix.fromQuarters(q, self.allocator); + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + + const allocator = gpa.allocator(); + + // Matrix A - [1 2; 3 4] + var a_data = ArrayList(ArrayList(f64)).init(allocator); + var a_row1 = ArrayList(f64).init(allocator); + try a_row1.appendSlice(&[_]f64{ 1.0, 2.0 }); + var a_row2 = ArrayList(f64).init(allocator); + try a_row2.appendSlice(&[_]f64{ 3.0, 4.0 }); + try a_data.append(a_row1); + try a_data.append(a_row2); + var a = try Matrix.init(allocator, a_data); + defer a.deinit(); + + // Matrix B - [5 6; 7 8] + var b_data = ArrayList(ArrayList(f64)).init(allocator); + var b_row1 = ArrayList(f64).init(allocator); + try b_row1.appendSlice(&[_]f64{ 5.0, 6.0 }); + var b_row2 = ArrayList(f64).init(allocator); + try b_row2.appendSlice(&[_]f64{ 7.0, 8.0 }); + try b_data.append(b_row1); + try b_data.append(b_row2); + var b = try Matrix.init(allocator, b_data); + defer b.deinit(); + + // Matrix C - 4x4 + var c_data = ArrayList(ArrayList(f64)).init(allocator); + var c_row1 = ArrayList(f64).init(allocator); + try c_row1.appendSlice(&[_]f64{ 1.0, 1.0, 1.0, 1.0 }); + var c_row2 = ArrayList(f64).init(allocator); + try c_row2.appendSlice(&[_]f64{ 2.0, 4.0, 8.0, 16.0 }); + var c_row3 = ArrayList(f64).init(allocator); + try c_row3.appendSlice(&[_]f64{ 3.0, 9.0, 27.0, 81.0 }); + var c_row4 = ArrayList(f64).init(allocator); + try c_row4.appendSlice(&[_]f64{ 4.0, 16.0, 64.0, 256.0 }); + try c_data.append(c_row1); + try c_data.append(c_row2); + try c_data.append(c_row3); + try c_data.append(c_row4); + var c = try Matrix.init(allocator, c_data); + defer c.deinit(); + + // Matrix D - 4x4 + var d_data = ArrayList(ArrayList(f64)).init(allocator); + var d_row1 = ArrayList(f64).init(allocator); + try d_row1.appendSlice(&[_]f64{ 4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0 }); + var d_row2 = ArrayList(f64).init(allocator); + try d_row2.appendSlice(&[_]f64{ -13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0 }); + var d_row3 = ArrayList(f64).init(allocator); + try d_row3.appendSlice(&[_]f64{ 3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0 }); + var d_row4 = ArrayList(f64).init(allocator); + try d_row4.appendSlice(&[_]f64{ -1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0 }); + try d_data.append(d_row1); + try d_data.append(d_row2); + try d_data.append(d_row3); + try d_data.append(d_row4); + var d = try Matrix.init(allocator, d_data); + defer d.deinit(); + + // Matrix E - 4x4 + var e_data = ArrayList(ArrayList(f64)).init(allocator); + var e_row1 = ArrayList(f64).init(allocator); + try e_row1.appendSlice(&[_]f64{ 1.0, 2.0, 3.0, 4.0 }); + var e_row2 = ArrayList(f64).init(allocator); + try e_row2.appendSlice(&[_]f64{ 5.0, 6.0, 7.0, 8.0 }); + var e_row3 = ArrayList(f64).init(allocator); + try e_row3.appendSlice(&[_]f64{ 9.0, 10.0, 11.0, 12.0 }); + var e_row4 = ArrayList(f64).init(allocator); + try e_row4.appendSlice(&[_]f64{ 13.0, 14.0, 15.0, 16.0 }); + try e_data.append(e_row1); + try e_data.append(e_row2); + try e_data.append(e_row3); + try e_data.append(e_row4); + var e = try Matrix.init(allocator, e_data); + defer e.deinit(); + + // Matrix F - Identity 4x4 + var f_data = ArrayList(ArrayList(f64)).init(allocator); + var f_row1 = ArrayList(f64).init(allocator); + try f_row1.appendSlice(&[_]f64{ 1.0, 0.0, 0.0, 0.0 }); + var f_row2 = ArrayList(f64).init(allocator); + try f_row2.appendSlice(&[_]f64{ 0.0, 1.0, 0.0, 0.0 }); + var f_row3 = ArrayList(f64).init(allocator); + try f_row3.appendSlice(&[_]f64{ 0.0, 0.0, 1.0, 0.0 }); + var f_row4 = ArrayList(f64).init(allocator); + try f_row4.appendSlice(&[_]f64{ 0.0, 0.0, 0.0, 1.0 }); + try f_data.append(f_row1); + try f_data.append(f_row2); + try f_data.append(f_row3); + try f_data.append(f_row4); + var f = try Matrix.init(allocator, f_data); + defer f.deinit(); + + const stdout = std.io.getStdOut().writer(); + + try stdout.print("Using 'normal' matrix multiplication:\n", .{}); + + var a_clone = try a.clone(); + defer a_clone.deinit(); + var b_clone = try b.clone(); + defer b_clone.deinit(); + var ab = try a_clone.mul(b_clone); + defer ab.deinit(); + try stdout.print(" a * b = {}\n", .{ab}); + + var c_clone = try c.clone(); + defer c_clone.deinit(); + var d_clone = try d.clone(); + defer d_clone.deinit(); + var cd = try c_clone.mul(d_clone); + defer cd.deinit(); + const cd_str = try cd.toStringWithPrecision(6, allocator); + defer allocator.free(cd_str); + try stdout.print(" c * d = {s}\n", .{cd_str}); + + var e_clone = try e.clone(); + defer e_clone.deinit(); + var f_clone = try f.clone(); + defer f_clone.deinit(); + var ef = try e_clone.mul(f_clone); + defer ef.deinit(); + try stdout.print(" e * f = {}\n", .{ef}); + + try stdout.print("\nUsing 'Strassen' matrix multiplication:\n", .{}); + + var a_clone2 = try a.clone(); + defer a_clone2.deinit(); + var b_clone2 = try b.clone(); + defer b_clone2.deinit(); + var ab_s = try a_clone2.strassen(b_clone2); + defer ab_s.deinit(); + try stdout.print(" a * b = {}\n", .{ab_s}); + + var c_clone2 = try c.clone(); + defer c_clone2.deinit(); + var d_clone2 = try d.clone(); + defer d_clone2.deinit(); + var cd_s = try c_clone2.strassen(d_clone2); + defer cd_s.deinit(); + const cd_s_str = try cd_s.toStringWithPrecision(6, allocator); + defer allocator.free(cd_s_str); + try stdout.print(" c * d = {s}\n", .{cd_s_str}); + + var e_clone2 = try e.clone(); + defer e_clone2.deinit(); + var f_clone2 = try f.clone(); + defer f_clone2.deinit(); + var ef_s = try e_clone2.strassen(f_clone2); + defer ef_s.deinit(); + try stdout.print(" e * f = {}\n", .{ef_s}); +} diff --git a/Task/Stream-merge/Rust/stream-merge.rs b/Task/Stream-merge/Rust/stream-merge.rs new file mode 100644 index 0000000000..fce1392387 --- /dev/null +++ b/Task/Stream-merge/Rust/stream-merge.rs @@ -0,0 +1,81 @@ +use std::cmp::Ordering; + +fn merge2(c1: &[T], c2: &[T], action: F) { + let mut i1 = 0; + let mut i2 = 0; + + while i1 < c1.len() && i2 < c2.len() { + if c1[i1] <= c2[i2] { + action(c1[i1]); + i1 += 1; + } else { + action(c2[i2]); + i2 += 1; + } + } + + while i1 < c1.len() { + action(c1[i1]); + i1 += 1; + } + + while i2 < c2.len() { + action(c2[i2]); + i2 += 1; + } +} + +fn merge_n(action: F, all: &[&[T]]) { + let mut vit: Vec<(usize, usize)> = all.iter().map(|c| (0, c.len())).collect(); + + loop { + let mut done = true; + let mut least: Option = None; + + for (i, &(start, end)) in vit.iter().enumerate() { + if start < end { + if least.is_none() { + least = Some(i); + } else { + if let Some(l) = least { + if all[i][start].cmp(&all[l][vit[l].0]) == Ordering::Less { + least = Some(i); + } + } + } + } + } + + if let Some(l) = least { + if vit[l].0 < vit[l].1 { + done = false; + action(all[l][vit[l].0]); + vit[l].0 += 1; + } + } + + if done { + break; + } + } +} + + +fn display(num: i32) { + print!("{} ", num); +} + +fn main() { + let v1 = vec![0, 3, 6]; + let v2 = vec![1, 4, 7]; + let v3 = vec![2, 5, 8]; + + merge2(&v2, &v1, display); + println!(); + + merge_n(display, &[&v1]); + println!(); + + merge_n(display, &[&v3, &v2, &v1]); + println!(); +} diff --git a/Task/String-concatenation/JavaScript/string-concatenation.js b/Task/String-concatenation/JavaScript/string-concatenation.js index 3763e92eb2..df727c924c 100644 --- a/Task/String-concatenation/JavaScript/string-concatenation.js +++ b/Task/String-concatenation/JavaScript/string-concatenation.js @@ -1,2 +1,2 @@ var s = "hello" -print(s + " there!") +console.log(s + " there!") diff --git a/Task/String-concatenation/Uxntal/string-concatenation.uxnatl b/Task/String-concatenation/Uxntal/string-concatenation.uxnatl index e817d13f27..f65b87d1b5 100644 --- a/Task/String-concatenation/Uxntal/string-concatenation.uxnatl +++ b/Task/String-concatenation/Uxntal/string-concatenation.uxnatl @@ -1,33 +1,32 @@ -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +|18 @Console/write |0100 @on-reset ( -> ) ;str3 ;str1 copy-str ;str3 ;str2 append-str ;str3 print-str - #0a .Console/write DEO BRK -@print-str ( str* -: ) - &loop ( -- ) - LDAk .Console/write DEO - INC2 LDAk ?&loop - POP2 JMP2r +@print-str_ ( str* -: ) + LDAk .Console/write DEO + INC2 @print-str LDAk ?print-str_ + POP2 + JMP2r + +@append-str ( dest* src* -: ) + STH2 end-str STH2r + ( >> ) @copy-str ( dest* src* -: ) STH2 &loop ( -- ) LDAkr STH2k STAr INC2 LDAkr STHr INC2r ?&loop - POP2 POP2r JMP2r + POP2 POP2r + JMP2r -@append-str ( dest* src* -: ) - STH2 end-str STH2r copy-str JMP2r - -@end-str ( str* -: str* ) - !&inner - &loop ( -- ) - INC2 &inner LDAk ?&loop +@end-str_ ( str* -: str* ) + INC2 @end-str LDAk ?end-str_ JMP2r @str1 "Uxn 00 -@str2 "tal 00 +@str2 "tal 0a00 @str3 diff --git a/Task/String-length/Crystal/string-length-1.cr b/Task/String-length/Crystal/string-length-1.cr index 9696655917..d16a30f7c5 100644 --- a/Task/String-length/Crystal/string-length-1.cr +++ b/Task/String-length/Crystal/string-length-1.cr @@ -1 +1 @@ -"J̲o̲s̲é̲".bytesize +"J̲o̲s̲é̲".bytesize #=> 13 diff --git a/Task/String-length/Crystal/string-length-2.cr b/Task/String-length/Crystal/string-length-2.cr index 7f7158a89a..0ae6a44f3a 100644 --- a/Task/String-length/Crystal/string-length-2.cr +++ b/Task/String-length/Crystal/string-length-2.cr @@ -1 +1 @@ -"J̲o̲s̲é̲".chars.length +"J̲o̲s̲é̲".size #=> 8 diff --git a/Task/String-length/Crystal/string-length-3.cr b/Task/String-length/Crystal/string-length-3.cr new file mode 100644 index 0000000000..187bd4d6c1 --- /dev/null +++ b/Task/String-length/Crystal/string-length-3.cr @@ -0,0 +1 @@ +"J̲o̲s̲é̲".grapheme_size #=> 4 diff --git a/Task/String-length/Uxntal/string-length.uxnatl b/Task/String-length/Uxntal/string-length.uxnatl new file mode 100644 index 0000000000..0c7ef9a82f --- /dev/null +++ b/Task/String-length/Uxntal/string-length.uxnatl @@ -0,0 +1,31 @@ +%DBG { [ LIT2 01 -System/debug ] DEO } + +|0e @System/debug + +|100 + +@on-reset ( -> ) + ;my-string slen-bytes ( 0007 ) + ;my-string slen-chars ( 0005 ) + DBG + BRK + +@next-glyph ( addr* -- addr* ) + INC2 LDAk #06 SFT #02 EQU ?next-glyph + JMP2r + +@slen-chars ( str* -- len* ) + LIT2r 0000 + &>loop ( -- ) + INC2r next-glyph LDAk ?&>loop + POP2 STH2r + JMP2r + +@slen-bytes ( str* -- len* ) + STH2k + &>loop + INC2 LDAk ?&>loop + STH2r SUB2 + JMP2r + +@my-string "møøse $1 diff --git a/Task/String-prepend/Crystal/string-prepend.cr b/Task/String-prepend/Crystal/string-prepend.cr new file mode 100644 index 0000000000..8850fac0c9 --- /dev/null +++ b/Task/String-prepend/Crystal/string-prepend.cr @@ -0,0 +1,3 @@ +s = "world" +s = "Hello " + s +puts s diff --git a/Task/String-prepend/OPL/string-prepend.opl b/Task/String-prepend/OPL/string-prepend.opl new file mode 100644 index 0000000000..708fba229f --- /dev/null +++ b/Task/String-prepend/OPL/string-prepend.opl @@ -0,0 +1,7 @@ +PROC main: + LOCAL a$(12) + a$="Code" + a$="Rosetta "+a$ + PRINT a$ + GET +ENDP diff --git a/Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string-4.java b/Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string-4.java new file mode 100644 index 0000000000..e23b978aed --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Java/strip-a-set-of-characters-from-a-string-4.java @@ -0,0 +1,13 @@ +import java.util.function.BiFunction; +import java.util.stream.Collectors; + +public final class StripASetOfCharactersFromAString { + + public static void main(String[] args) { + BiFunction stripCharacters = (string, characters) -> string.chars() + .mapToObj(Character::toString).filter( s -> ! characters.contains(s) ).collect(Collectors.joining("")); + + System.out.println(stripCharacters.apply("She was a soul stripper. She took my heart!", "aei")); + } + +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/M2000-Interpreter/strip-a-set-of-characters-from-a-string.m2000 b/Task/Strip-a-set-of-characters-from-a-string/M2000-Interpreter/strip-a-set-of-characters-from-a-string.m2000 new file mode 100644 index 0000000000..af3f36525b --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/M2000-Interpreter/strip-a-set-of-characters-from-a-string.m2000 @@ -0,0 +1 @@ +print filter$("She was a soul stripper. She took my heart!","aei")="Sh ws soul strppr. Sh took my hrt!" diff --git a/Task/Strip-a-set-of-characters-from-a-string/Objeck/strip-a-set-of-characters-from-a-string.objeck b/Task/Strip-a-set-of-characters-from-a-string/Objeck/strip-a-set-of-characters-from-a-string.objeck new file mode 100644 index 0000000000..ed0e81353a --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Objeck/strip-a-set-of-characters-from-a-string.objeck @@ -0,0 +1,17 @@ +class CharsStrip { + function : Main(args : String[]) ~ Nil { + StripChars("She was a soul stripper. She took my heart!","aei")->PrintLine(); + } + + function : StripChars(str : String, strip : String) ~ String { + out := ""; + + each(char in str) { + if(<>strip->Has(char)) { + out += char; + }; + }; + + return out; + } +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string.odin b/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string.odin new file mode 100644 index 0000000000..e373a19857 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string.odin @@ -0,0 +1,16 @@ +import "core:fmt" +import "core:strings" +import "core:unicode/utf8" + +main :: proc() { + input_string:="She was a soul stripper. She took my heart!" + filter_string:="aei" + + for i in filter_string{ + rune_array:=[]rune{i} + filter:=utf8.runes_to_string(rune_array) + input_string,_=strings.replace(input_string, filter, "", -1) + } + fmt.println(input_string) + +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/R/strip-a-set-of-characters-from-a-string.r b/Task/Strip-a-set-of-characters-from-a-string/R/strip-a-set-of-characters-from-a-string.r new file mode 100644 index 0000000000..aae438aa47 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/R/strip-a-set-of-characters-from-a-string.r @@ -0,0 +1,16 @@ +library(stringr) + +stripchars <- function(s, chars){ + #Make sure potentially troublesome regex characters are escaped properly + specialchars <- c("\\","^","[","]","-") + for(char in specialchars){ + if(str_detect(chars, fixed(char))){ + chars <- str_replace_all(chars, fixed(char), str_glue("\\{char}")) + } + } + regexp <- str_glue("[{chars}]") + return(str_replace_all(s, regexp, "")) +} + +stripchars("She was a soul stripper. She took my heart!", "aei") +stripchars("Bet you can't do this one! ^.*?({})[\\-|]+$", "\\^.*?({})[\\-|]+$") diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rs b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rs index dae9f91804..19ab1e93e6 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rs +++ b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rs @@ -1,9 +1,9 @@ -fn strip_characters(original : &str, to_strip : &str) -> String { +fn strip_characters(original: &str, to_strip: &str) -> String { let mut result = String::new(); for c in original.chars() { if !to_strip.contains(c) { - result.push(c); - } + result.push(c); + } } result } diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rs b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rs index 1e1f913724..7156545772 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rs +++ b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rs @@ -1,3 +1,10 @@ -fn strip_characters(original : &str, to_strip : &str) -> String { - original.chars().filter(|&c| !to_strip.contains(c)).collect() +fn strip_characters(original: &str, to_strip: &str) -> String { + original + .chars() + .filter(|&c| !to_strip.contains(c)) + .collect() +} + +fn strip_characters(original: &str, to_strip: &str) -> String { + original.split(|c| to_strip.contains(c)).collect() } diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rs b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rs index 54e13912c4..5ddcdfb18b 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rs +++ b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rs @@ -1,3 +1,6 @@ fn main() { - println!("{}", strip_characters("She was a soul stripper. She took my heart!", "aei")); + println!( + "{}", + strip_characters("She was a soul stripper. She took my heart!", "aei") + ); } diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-4.rs b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-4.rs new file mode 100644 index 0000000000..7c672be0e9 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-4.rs @@ -0,0 +1,13 @@ +fn strip_characters(original: &str, to_strip: &[char]) -> String { + original.split(to_strip).collect() +} + +fn main() { + println!( + "{}", + strip_characters( + "She was a soul stripper. She took my heart!", + &['a', 'e', 'i'] + ) + ); +} diff --git a/Task/Strip-comments-from-a-string/APL/strip-comments-from-a-string.apl b/Task/Strip-comments-from-a-string/APL/strip-comments-from-a-string.apl new file mode 100644 index 0000000000..2e03104cbc --- /dev/null +++ b/Task/Strip-comments-from-a-string/APL/strip-comments-from-a-string.apl @@ -0,0 +1 @@ +strip ← {(~⌽∧\⌽' '=z)/z←(∧\~⍵∊⍺)/⍵} diff --git a/Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.l b/Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.l new file mode 100644 index 0000000000..8975cbf492 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.l @@ -0,0 +1,5 @@ +(string-trim (string-trim-right " apples, pears # and bananas" "[#;].+")) + +(string-trim (string-trim-right " apples, pears ; and bananas" "[#;].+")) + +(string-trim (string-trim-right " apples, pears and bananas " "[#;].+")) diff --git a/Task/Strip-comments-from-a-string/Refal/strip-comments-from-a-string.refal b/Task/Strip-comments-from-a-string/Refal/strip-comments-from-a-string.refal new file mode 100644 index 0000000000..bf150ccff8 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Refal/strip-comments-from-a-string.refal @@ -0,0 +1,23 @@ +$ENTRY Go { + = > + >; +}; + +StripComments { + e.X = >; +}; + +Trim { + e.X ' ' = ; + e.X = e.X; +}; + +StripAll { + () e.X = e.X; + (s.C e.C) e.X = >; +}; + +Strip { + s.C e.X s.C e.Y = e.X; + s.C e.X = e.X; +}; diff --git a/Task/Strip-comments-from-a-string/SETL/strip-comments-from-a-string.setl b/Task/Strip-comments-from-a-string/SETL/strip-comments-from-a-string.setl new file mode 100644 index 0000000000..f3d4167c40 --- /dev/null +++ b/Task/Strip-comments-from-a-string/SETL/strip-comments-from-a-string.setl @@ -0,0 +1,13 @@ +program strip_comments; + print(strip(";#", "apples, pears # and bananas")); + print(strip(";#", "apples, pears ; and bananas")); + print(strip(";#", "apples, pears")); + + proc strip(comment_chars, s); + if exists c = s(i) | c in comment_chars then + s := s(..i-1); + end if; + rspan(s, "\n\t "); + return s; + end proc; +end program; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs b/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs index 92f8c4b9dc..1f72750488 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Rust/strip-control-codes-and-extended-characters-from-a-string.rs @@ -1,7 +1,7 @@ fn stripped(tostrip: &str) -> String { return tostrip .chars() - .filter(|c| (*c as u32) < 127 && *c as u32 > 31) + .filter(|c| !c.is_ascii_control() && c.is_ascii()) .collect(); } diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-1.cpp b/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-1.cpp new file mode 100644 index 0000000000..58c17deb73 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-1.cpp @@ -0,0 +1,47 @@ +#include +#include + +constexpr std::string_view spaces{ " \t\n\v\f" }; + +constexpr std::string_view trim_start(std::string_view str) { + if (auto beg = str.find_first_not_of(spaces); beg != str.npos) { + return str.substr(beg); + } + + return str.substr(str.size()); +} + +constexpr std::string_view trim_end(std::string_view str) { + if (auto end = str.find_last_not_of(spaces); end != str.npos) { + return str.substr(0, end + 1); + } + + return str.substr(0, 0); +} + +constexpr std::string_view trim(std::string_view str) { + auto beg = str.find_first_not_of(spaces); + if (beg == str.npos) { + return str.substr(str.size()); + } + auto end = str.find_last_not_of(spaces); + + return str.substr(beg, end - beg + 1); +} + +int main() { + using std::string_view; + using std::cout; + + string_view test_phrase{ " There are unwanted blanks here! " }; + string_view left_trimmed = trim_start(test_phrase); + string_view right_trimmed = trim_end(test_phrase); + + cout << "The test phrase is :\"" << test_phrase << "\"\n"; + cout << "Trimmed on the left side :\"" << left_trimmed << "\"\n"; + cout << "Trimmed on the right side :\"" << right_trimmed << "\"\n"; + + string_view trimmed = trim(test_phrase); + + cout << "Trimmed on both sides :\"" << trimmed << "\"\n"; +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail.cpp b/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-2.cpp similarity index 54% rename from Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail.cpp rename to Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-2.cpp index ce5f4a1eaf..f5b58e9af7 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail.cpp +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/C++/strip-whitespace-from-a-string-top-and-tail-2.cpp @@ -6,10 +6,10 @@ int main( ) { std::string testphrase( " There are unwanted blanks here! " ) ; std::string lefttrimmed = boost::trim_left_copy( testphrase ) ; std::string righttrimmed = boost::trim_right_copy( testphrase ) ; - std::cout << "The test phrase is :" << testphrase << "\n" ; - std::cout << "Trimmed on the left side :" << lefttrimmed << "\n" ; - std::cout << "Trimmed on the right side :" << righttrimmed << "\n" ; + std::cout << "The test phrase is :\"" << testphrase << "\"\n" ; + std::cout << "Trimmed on the left side :\"" << lefttrimmed << "\"\n" ; + std::cout << "Trimmed on the right side :\"" << righttrimmed << "\"\n" ; boost::trim( testphrase ) ; - std::cout << "Trimmed on both sides :" << testphrase << "\n" ; + std::cout << "Trimmed on both sides :\"" << testphrase << "\"\n" ; return 0 ; } diff --git a/Task/Strong-and-weak-primes/EasyLang/strong-and-weak-primes.easy b/Task/Strong-and-weak-primes/EasyLang/strong-and-weak-primes.easy index 09c7d57538..bbffd2c449 100644 --- a/Task/Strong-and-weak-primes/EasyLang/strong-and-weak-primes.easy +++ b/Task/Strong-and-weak-primes/EasyLang/strong-and-weak-primes.easy @@ -1,21 +1,19 @@ fastfunc isprim num . i = 3 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 2 . return 1 . -func nextprim n . +fastfunc nextprim n . repeat n += 2 until isprim n = 1 . return n . -proc strwkprimes ncnt sgn . . +proc strwkprimes ncnt sgn . write "First " & ncnt & ": " pr2 = 2 pr3 = 3 diff --git a/Task/Strong-and-weak-primes/REXX/strong-and-weak-primes.rexx b/Task/Strong-and-weak-primes/REXX/strong-and-weak-primes.rexx index fd8065eba8..3b2116497b 100644 --- a/Task/Strong-and-weak-primes/REXX/strong-and-weak-primes.rexx +++ b/Task/Strong-and-weak-primes/REXX/strong-and-weak-primes.rexx @@ -1,50 +1,55 @@ -/*REXX program lists a sequence (or a count) of ──strong── or ──weak── primes. */ -parse arg N kind _ . 1 . okind; upper kind /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 36 /*Not specified? Then assume default.*/ -if kind=='' | kind=="," then kind= 'STRONG' /* " " " " " */ -if _\=='' then call ser 'too many arguments specified.' -if kind\=='WEAK' & kind\=='STRONG' then call ser 'invalid 2nd argument: ' okind -if kind =='WEAK' then weak= 1; else weak= 0 /*WEAK is a binary value for function.*/ -w = linesize() - 1 /*obtain the usable width of the term. */ -tell= (N>0); @.=; N= abs(N) /*N is negative? Then don't display. */ -!.=0; !.1=2; !.2=3; !.3=5; !.4=7; !.5=11; !.6=13; !.7=17; !.8=19; !.9=23; #= 8 -@.=''; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1; @.17=1; @.19=1; start= # + 1 -m= 0; lim= 0 /*# is the number of low primes so far*/ -$=; do i=3 for #-2 while lim<=N /* [↓] find primes, and maybe show 'em*/ - call strongWeak i-1; $= strip($) /*go see if other part of a KIND prime.*/ - end /*i*/ /* [↑] allows faster loop (below). */ - /* [↓] N: default lists up to 35 #'s.*/ - do j=!.#+2 by 2 while limN then do; lim= y; m= m-1; end; else call app; return 1 -app: if tell then if length($ y)>w then do; say $; $= y; end; else $= $ y; return 1 -ser: say; say; say '***error***' arg(1); say; say; exit 13 /*tell error message. */ -commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -strongWeak: parse arg x; Lp= x - 1; Hp= x + 1; y=!.x; s= (!.Lp + !.Hp) / 2 - if weak then if ys then return add() /*is an strong prime.*/ - return 0 /*not " " " */ +call Primes 1e8 +call Task 'Strong',36 +call Task 'Weak',37 +call Task 'Balanced',30 +call Task 'Strong',1e6 +call Task 'Weak',1e6 +call Task 'Balanced',1e6 +call Task 'Strong',1e7 +call Task 'Weak',1e7 +call Task 'Balanced',1e7 +call Task 'Strong',1e8 +call Task 'Weak',1e8 +call Task 'Balanced',1e8 +say Format(Time('e'),,3) 'seconds' +exit + +Task: +procedure expose prim. flag. +parse arg xx,yy +v = (yy<1e3) +if v then + say 'First' yy xx 'primes' +else + say xx 'primes below' yy +n = 0 +do i = 2 to prim.0-1 + if \ v & prim.i > yy then + leave + im = i-1; ip = i+1; a = (prim.im+prim.ip)/2 + s = (prim.i > a); t = (prim.i < a); u = (prim.i = a) + if xx = 'Strong' & s | xx = 'Weak' & t | xx = 'Balanced' & u then do + n = n+1 + if v then do + call Charout ,prim.i' ' + if n = yy then + leave + end + end +end +if v then + say +say n 'found' +say +return + +include Sequences +include Functions +include Abend diff --git a/Task/Subleq/EasyLang/subleq.easy b/Task/Subleq/EasyLang/subleq.easy index d1c65d1470..2d996fb92c 100644 --- a/Task/Subleq/EasyLang/subleq.easy +++ b/Task/Subleq/EasyLang/subleq.easy @@ -2,9 +2,7 @@ global inpos inp$ . func inp . if inpos = 0 inp$ = input - if error = 1 - return 255 - . + if error = 1 : return 255 inpos = 1 . if inpos <= len inp$ @@ -15,7 +13,7 @@ func inp . inpos = 0 return 10 . -proc subleq . mem[] . +proc subleq &mem[] . repeat a = mem[p] b = mem[p + 1] diff --git a/Task/Substitution-cipher/EasyLang/substitution-cipher.easy b/Task/Substitution-cipher/EasyLang/substitution-cipher.easy index b59a2aec52..f8a9055c54 100644 --- a/Task/Substitution-cipher/EasyLang/substitution-cipher.easy +++ b/Task/Substitution-cipher/EasyLang/substitution-cipher.easy @@ -1,13 +1,11 @@ alpha$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" key$ = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN" # -proc subst in$ . out$ a$ b$ . +proc subst in$ &out$ &a$ &b$ . out$ = "" for c$ in strchars in$ p = strpos a$ c$ - if p > 0 - c$ = substr b$ p 1 - . + if p > 0 : c$ = substr b$ p 1 out$ &= c$ . . diff --git a/Task/Substitution-cipher/JavaScript/substitution-cipher.js b/Task/Substitution-cipher/JavaScript/substitution-cipher.js new file mode 100644 index 0000000000..a6dd7e8c8a --- /dev/null +++ b/Task/Substitution-cipher/JavaScript/substitution-cipher.js @@ -0,0 +1,30 @@ +const key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"; + +function encode(s) { + let result = ''; + + for (let i = 0; i < s.length; i++) { + result += key[s.charCodeAt(i) - 32]; + } + + return result; +} + +function decode(s) { + let result = ''; + + for (let i = 0; i < s.length; i++) { + result += String.fromCharCode(key.indexOf(s[i]) + 32); + } + + return result; +} + +function main() { + const s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"; + const enc = encode(s); + console.log("Encoded: ", enc); + console.log("Decoded: ", decode(enc)); +} + +main(); diff --git a/Task/Substring/K/substring.k b/Task/Substring/K/substring.k new file mode 100644 index 0000000000..8e5147e2c5 --- /dev/null +++ b/Task/Substring/K/substring.k @@ -0,0 +1,32 @@ +string: "the cow goes over the moon" +substring: "cow" +char:"g" +n:2 +m:4 + +"string: " +"the cow goes over the moon" +" " + +// without first n characters with cut _ +"without first n (2) characters " +{n_x}string + +// without last character ; reverse and remove last then reverse +"without last character" +{|1_|x}"the cow goes over the moon" + +// string from char g until end ; find char with where & and then cut +"string from char g until end" +{((&char=x)[0])_x}string + +// substring of m length from character g ; same as above only flatten with ,// +"substring of m (4) length from character g " +{x[,//(&char=x)[0]+ !m]}string + +// from substring of length m ; find firstindex of substring; check if substring; checks if the characters are in order with < +"from substring of length m" +firstindex:({&x[0]=string}'(((#substring);1)#substring))[0][0] +issubstring:1=*/(!#substring)= (<{&x[0]=string}'(((#substring);1)#substring)) +// if issubstring display; else do nothing +$[issubstring; ({x[firstindex+!m]}string);""] diff --git a/Task/Subtractive-generator/EasyLang/subtractive-generator.easy b/Task/Subtractive-generator/EasyLang/subtractive-generator.easy index 105948c2ab..73fd0a963f 100644 --- a/Task/Subtractive-generator/EasyLang/subtractive-generator.easy +++ b/Task/Subtractive-generator/EasyLang/subtractive-generator.easy @@ -3,7 +3,7 @@ len state[] 55 arrbase state[] 0 global si sj . funcdecl subrand . -proc subrand_seed p1 . . +proc subrand_seed p1 . p2 = 1 state[0] = p1 mod MOD j = 21 @@ -21,9 +21,7 @@ proc subrand_seed p1 . . . . func subrand . - if si = sj - subrand_seed 0 - . + if si = sj : subrand_seed 0 si = (si - 1) mod 55 sj = (sj - 1) mod 55 x = (state[si] - state[sj]) mod MOD diff --git a/Task/Successive-prime-differences/EasyLang/successive-prime-differences.easy b/Task/Successive-prime-differences/EasyLang/successive-prime-differences.easy index 98b850a968..cae380afee 100644 --- a/Task/Successive-prime-differences/EasyLang/successive-prime-differences.easy +++ b/Task/Successive-prime-differences/EasyLang/successive-prime-differences.easy @@ -1,33 +1,25 @@ fastfunc isprim num . i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -func nextprime n . +fastfunc nextprime n . n += 1 - while isprim n = 0 - n += 1 - . + while isprim n = 0 : n += 1 return n . func spd n d[] . - if isprim n = 0 - return 0 - . + if isprim n = 0 : return 0 for i = 1 to len d[] - if nextprime n <> n + d[i] - return 0 - . + if nextprime n <> n + d[i] : return 0 n += d[i] . return 1 . -proc print_set n d[] . . +proc print_set n d[] . write "( " & n & " " for i = 1 to len d[] write n + d[i] & " " @@ -35,18 +27,14 @@ proc print_set n d[] . . . print ")" . -proc show max d[] . . +proc show max d[] . write "Differences of " - for d in d[] - write d & " " - . + for d in d[] : write d & " " print "" for n = 2 to max - d[len d[]] if spd n d[] = 1 c += 1 - if c = 1 - print_set n d[] - . + if c = 1 : print_set n d[] last = n . . diff --git a/Task/Successive-prime-differences/REXX/successive-prime-differences.rexx b/Task/Successive-prime-differences/REXX/successive-prime-differences.rexx index 3ea18b4c27..c91c012135 100644 --- a/Task/Successive-prime-differences/REXX/successive-prime-differences.rexx +++ b/Task/Successive-prime-differences/REXX/successive-prime-differences.rexx @@ -1,45 +1,54 @@ -/*REXX program finds and displays primes with successive differences (up to a limit).*/ -parse arg H . 1 . difs /*allow the highest number be specified*/ -if H=='' | H=="," then H= 1000000 /*Not specified? Then use the default.*/ -if difs='' then difs= 2 1 2.2 2.4 4.2 6.4.2 /* " " " " " " */ -call genP H +-- 12 Apr 2025 +include Settings - do j=1 for words(difs) /*traipse through the lists.*/ - dif= translate( word(difs, j),,.); dw= words(dif) /*obtain true differences. */ - do i=1 for dw; dif.i= word(dif, i) /*build an array of diffs. */ - end /*i*/ /* [↑] for optimization. */ - say center('primes with differences of:' dif, 50, '─') /*display title.*/ - p= 1; c= 0; grp= /*init. prime#, count, grp.*/ - do a=1; p= nextP(p+1); if p==0 then leave /*find the next DIF primes*/ - aa= p; !.= /*AA: nextP; the group #'s.*/ - !.1= p /*assign 1st prime in group.*/ - do g=2 for dw /*get the rest of the group.*/ - aa= nextP(aa+1); if aa==0 then leave a /*obtain the next prime. */ - !.g= aa; _= g-1 /*prepare to add difference.*/ - if !._ + dif._\==!.g then iterate a /*determine if fits criteria*/ - end /*g*/ - c= c+1 /*bump count of # of groups.*/ - grp= !.1; do b=2 for dw; grp= grp !.b /*build a list of primes. */ - end /*b*/ - if c==1 then say ' first group: ' grp /*display the first group. */ - end /*a*/ - /* [↓] test if group found.*/ - if grp=='' then say " (none)" /*display the last group. */ - else say ' last group: ' grp /* " " " " */ - say ' count: ' c /* " " group count. */ - say - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -nextP: do nxt=arg(1) to H; if @.nxt==. then return nxt; end /*nxt*/; return 0 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: procedure expose @.; parse arg N; != 0; @.=.; @.1= /*initialize the array.*/ - do e=4 by 2 for (N-1)%2; @.e=; end /*treat the even integers > 2 special.*/ - /*all primes are indicated with a "." */ - do j=1 by 2 for (N-1)%2 /*use odd integers up to N inclusive.*/ - if @.j==. then do; if ! then iterate /*Prime? Should skip the top part ? */ - jj= j * j /*compute the square of J. ___ */ - if jj>N then != 1 /*indicate skip top part if j > √ N */ - do m=jj to N by j+j; @.m=; end /*odd multiples.*/ - end /* [↑] strike odd multiples ¬ prime. */ - end /*j*/; return +call Time('r') +say 'SUCCESSIVE PRIME DIFFERENCES' +say version +say +call Primes 1e6 +say 'For the' prim.0 'primes up to 1 million...' +say +call Task 1 +call Task 2 +call Task 2,2 +call Task 2,4 +call Task 4,2 +call Task 2,4,6 +call Task 2,4,6,8 +call Task 2,4,6,8,10 +call Task 2,4,6,8,10,12 +call Task 2,4,6,8,10,12,14 +call Task 32,16,8,4,2 +say Format(Time('e'),,3) 'seconds' +exit + +Task: +procedure expose prim. +diffs = ''; first = ''; last = '' +do i = 1 to Arg() + diffs = diffs||Arg(i)' ' +end +count = 0 +do i = 1 to prim.0-Arg() + a = prim.i; work = a; k = i + do j = 1 to Arg() + k = k+1; b = prim.k + if b-a <> Arg(j) then + iterate i + work = work b; a = b + end + count = count+1 + if first = '' then + first = work + last = work +end +say 'Differences ' diffs +say 'First group ' first +say 'Last group ' last +say 'Groups found' count +say +return + +include Sequences +include Functions +include Abend diff --git a/Task/Sudan-function/Rust/sudan-function.rs b/Task/Sudan-function/Rust/sudan-function.rs new file mode 100644 index 0000000000..b0cd006337 --- /dev/null +++ b/Task/Sudan-function/Rust/sudan-function.rs @@ -0,0 +1,15 @@ +fn sudan1(n: usize, x: usize, y: usize) -> usize { + match (n, y) { + (0, _) => x + y, + (_, 0) => x, + _ => sudan1(n - 1, sudan1(n, x, y - 1), sudan1(n, x, y - 1) + y) + } +} + +fn sudan2(n: usize, x: usize, y: usize) -> usize { + if n == 0 { x + y } + else if y == 0 { x } + else { + sudan2(n - 1, sudan2(n, x, y - 1), sudan2(n, x, y - 1) + y) + } +} diff --git a/Task/Sudoku/EasyLang/sudoku.easy b/Task/Sudoku/EasyLang/sudoku.easy index fe0cbf2195..8bb837333c 100644 --- a/Task/Sudoku/EasyLang/sudoku.easy +++ b/Task/Sudoku/EasyLang/sudoku.easy @@ -3,7 +3,7 @@ len col[] 90 len box[] 90 len grid[] 82 # -proc init . . +proc init . for pos = 1 to 81 if pos mod 9 = 1 s$ = input @@ -31,7 +31,7 @@ proc init . . . init # -proc display . . +proc display . for i = 1 to 81 write grid[i] & " " if i mod 3 = 0 @@ -46,7 +46,7 @@ proc display . . . . # -proc solve pos . . +proc solve pos . while grid[pos] <> 0 pos += 1 . diff --git a/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer.nu b/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer-1.nu similarity index 100% rename from Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer.nu rename to Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer-1.nu diff --git a/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer-2.nu b/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer-2.nu new file mode 100644 index 0000000000..ce216c50d5 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Nu/sum-digits-of-an-integer-2.nu @@ -0,0 +1,13 @@ + ( [['0b0' 2] [1 10] [1234 10] ['0xfe' 16] ['0xf0e' 16]] | + each {|n| + let base = $n.1 + let num = match $base { + 16 => {$n.0 | str replace '0x' '' | str downcase}, + 2 => {$n.0 | str replace '0b' '' | str downcase}, + _ => {$n.0 | into string}, + } + # Split the number into characters and sum the digits + $num | split chars | each {|digit| + $digit | into int -r $base + } | math sum + } ) diff --git a/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-1.alg b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-1.alg new file mode 100644 index 0000000000..f57825d08b --- /dev/null +++ b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-1.alg @@ -0,0 +1,10 @@ +begin + +comment - calculate sum from k = 1 to 1000 of the sequence 1 / k^2; +real k, sum; +sum := 0; +for k := 1 step 1 until 1000 do + sum := sum + 1 / (k * k); +outreal(1,sum); outstring(1,"\n"); + +end diff --git a/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-2.alg b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-2.alg new file mode 100644 index 0000000000..0bb6f36d89 --- /dev/null +++ b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series-2.alg @@ -0,0 +1,24 @@ +begin + +comment - return the nth term of the sequence; +real procedure fterm (n); real n; +begin + fterm := 1.0 / (n*n); +end; + +comment - display the nth value of the series, + i.e., the sum of the first n terms of the + sequence defined by f; +procedure showsum (n, f); + value n; integer n; real procedure f; +begin + real x, sum; + sum := 0; + for x := 1 step 1 until n do + sum := sum + f(x); + outreal(1, sum); outstring(1,"\n"); +end; + +showsum(1000, fterm); + +end diff --git a/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg b/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg deleted file mode 100644 index 55260b26a2..0000000000 --- a/Task/Sum-of-a-series/ALGOL-60/sum-of-a-series.alg +++ /dev/null @@ -1,18 +0,0 @@ -begin - -comment - return sum from a to b of the series 1 / k^2; - -real procedure suminvsq(a, b); - value a, b; real a, b; -begin - real k, sum; - sum := 0; - for k := a step 1 until b do - sum := sum + 1 / (k * k); - suminvsq := sum; -end; - -comment - show result for 1..1000 -outreal(1,suminvsq(1,1000)); - -end diff --git a/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy b/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy index 539c8d6c05..683f94fae2 100644 --- a/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy +++ b/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy @@ -1,4 +1,4 @@ -numfmt 8 0 +numfmt 0 8 for i = 1 to 1000 s += 1 / (i * i) . diff --git a/Task/Sum-of-a-series/S-BASIC/sum-of-a-series.basic b/Task/Sum-of-a-series/S-BASIC/sum-of-a-series.basic new file mode 100644 index 0000000000..54acd278b5 --- /dev/null +++ b/Task/Sum-of-a-series/S-BASIC/sum-of-a-series.basic @@ -0,0 +1,11 @@ +var k, sum = real.double +sum = 0 +k = 1 +while k <= 1000 do + begin + sum = sum + (1 / (k * k)) + k = k + 1 + end +print using "#.######"; sum + +end diff --git a/Task/Sum-of-a-series/TypeScript/sum-of-a-series.ts b/Task/Sum-of-a-series/TypeScript/sum-of-a-series.ts new file mode 100644 index 0000000000..ddbfc76c4f --- /dev/null +++ b/Task/Sum-of-a-series/TypeScript/sum-of-a-series.ts @@ -0,0 +1,5 @@ +function s(n:number): number { + return [...Array(n).keys()].map(k => 1 / (1+k)**2).reduce((a, b) => a + b); +} + +console.log( s(1000) ) diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/EasyLang/sum-of-elements-below-main-diagonal-of-matrix.easy b/Task/Sum-of-elements-below-main-diagonal-of-matrix/EasyLang/sum-of-elements-below-main-diagonal-of-matrix.easy index 9832dc0943..de573fb844 100644 --- a/Task/Sum-of-elements-below-main-diagonal-of-matrix/EasyLang/sum-of-elements-below-main-diagonal-of-matrix.easy +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/EasyLang/sum-of-elements-below-main-diagonal-of-matrix.easy @@ -1,11 +1,10 @@ -proc sumbd . m[][] r . - r = 0 +func sumbd &m[][] . for i = 2 to len m[][] for j = 1 to i - 1 r += m[i][j] . . + return r . m[][] = [ [ 1 3 7 8 10 ] [ 2 4 16 14 4 ] [ 3 1 9 18 11 ] [ 12 14 17 18 20 ] [ 7 1 3 9 5 ] ] -sumbd m[][] r -print r +print sumbd m[][] diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Quackery/sum-of-elements-below-main-diagonal-of-matrix.quackery b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Quackery/sum-of-elements-below-main-diagonal-of-matrix.quackery new file mode 100644 index 0000000000..cc32c57366 --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Quackery/sum-of-elements-below-main-diagonal-of-matrix.quackery @@ -0,0 +1,10 @@ +[ 0 swap witheach + [ i^ split drop + 0 swap witheach + + ] ] is sumbelow ( [ --> n ) + +' [ [ 1 3 7 8 10 ] + [ 2 4 16 14 4 ] + [ 3 1 9 18 11 ] + [ 12 14 17 18 20 ] + [ 7 1 3 9 5 ] ] +sumbelow echo diff --git a/Task/Sum-to-100/EasyLang/sum-to-100.easy b/Task/Sum-to-100/EasyLang/sum-to-100.easy index ad5820f9e0..4306c8b04c 100644 --- a/Task/Sum-to-100/EasyLang/sum-to-100.easy +++ b/Task/Sum-to-100/EasyLang/sum-to-100.easy @@ -24,13 +24,13 @@ func evaluate code . . return value . -proc init . . +proc init . for i = 0 to nexpr f[i] = evaluate i . . call init -proc out code . . +proc out code . a = 19683 b = 6561 for k = 1 to 9 diff --git a/Task/Superellipse/EasyLang/superellipse.easy b/Task/Superellipse/EasyLang/superellipse.easy index d6f40685ab..0eebece6bb 100644 --- a/Task/Superellipse/EasyLang/superellipse.easy +++ b/Task/Superellipse/EasyLang/superellipse.easy @@ -1,10 +1,12 @@ n = 2.5 a = 200 b = 200 -linewidth 0.2 +glinewidth 0.2 while t <= 360 - x = pow abs cos t (2 / n) * a * sign cos t - y = pow abs sin t (2 / n) * b * sign sin t - line x / 5 + 50 y / 5 + 50 + xp = x + yp = y + x = (pow abs cos t (2 / n) * a * sign cos t) / 5 + 50 + y = (pow abs sin t (2 / n) * b * sign sin t) / 5 + 50 + if t > 0 : gline xp yp x y t += 0.5 . diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Zig/sutherland-hodgman-polygon-clipping.zig b/Task/Sutherland-Hodgman-polygon-clipping/Zig/sutherland-hodgman-polygon-clipping.zig new file mode 100644 index 0000000000..65f5f374ef --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Zig/sutherland-hodgman-polygon-clipping.zig @@ -0,0 +1,151 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; + +const Point = struct { + x: f64, + y: f64, + + pub fn format( + self: Point, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + try writer.print("Point{{ x: {d}, y: {d} }}", .{ self.x, self.y }); + } +}; + +const Polygon = struct { + points: ArrayList(Point), + + pub fn init(allocator: std.mem.Allocator) Polygon { + return Polygon{ + .points = ArrayList(Point).init(allocator), + }; + } + + pub fn deinit(self: *Polygon) void { + self.points.deinit(); + } + + pub fn clone(self: Polygon, allocator: std.mem.Allocator) !Polygon { + var new_polygon = Polygon.init(allocator); + try new_polygon.points.appendSlice(self.points.items); + return new_polygon; + } + + pub fn format( + self: Polygon, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + try writer.print("Polygon{{", .{}); + for (self.points.items, 0..) |point, i| { + try writer.print(" {}", .{point}); + if (i < self.points.items.len - 1) { + try writer.print(",", .{}); + } + } + try writer.print(" }}", .{}); + } +}; + +fn isInside(p: Point, cp1: Point, cp2: Point) bool { + return (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x); +} + +fn computeIntersection(cp1: Point, cp2: Point, s: Point, e: Point) Point { + const dc = Point{ + .x = cp1.x - cp2.x, + .y = cp1.y - cp2.y, + }; + const dp = Point{ + .x = s.x - e.x, + .y = s.y - e.y, + }; + const n1 = cp1.x * cp2.y - cp1.y * cp2.x; + const n2 = s.x * e.y - s.y * e.x; + const n3 = 1.0 / (dc.x * dp.y - dc.y * dp.x); + + return Point{ + .x = (n1 * dp.x - n2 * dc.x) * n3, + .y = (n1 * dp.y - n2 * dc.y) * n3, + }; +} + +fn sutherlandHodgmanClip(allocator: std.mem.Allocator, subject_polygon: Polygon, clip_polygon: Polygon) !Polygon { + var result_ring = try subject_polygon.clone(allocator); + + if (clip_polygon.points.items.len == 0) { + return result_ring; + } + + var cp1 = clip_polygon.points.items[clip_polygon.points.items.len - 1]; + + for (clip_polygon.points.items) |cp2| { + var input = try result_ring.clone(allocator); + defer input.deinit(); + + result_ring.points.clearRetainingCapacity(); + + if (input.points.items.len == 0) { + continue; + } + + var s = input.points.items[input.points.items.len - 1]; + + for (input.points.items) |e| { + if (isInside(e, cp1, cp2)) { + if (!isInside(s, cp1, cp2)) { + try result_ring.points.append(computeIntersection(cp1, cp2, s, e)); + } + try result_ring.points.append(e); + } else if (isInside(s, cp1, cp2)) { + try result_ring.points.append(computeIntersection(cp1, cp2, s, e)); + } + s = e; + } + + cp1 = cp2; + } + + return result_ring; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + var subject_polygon = Polygon.init(allocator); + defer subject_polygon.deinit(); + + try subject_polygon.points.append(.{ .x = 50.0, .y = 150.0 }); + try subject_polygon.points.append(.{ .x = 200.0, .y = 50.0 }); + try subject_polygon.points.append(.{ .x = 350.0, .y = 150.0 }); + try subject_polygon.points.append(.{ .x = 350.0, .y = 300.0 }); + try subject_polygon.points.append(.{ .x = 250.0, .y = 300.0 }); + try subject_polygon.points.append(.{ .x = 200.0, .y = 250.0 }); + try subject_polygon.points.append(.{ .x = 150.0, .y = 350.0 }); + try subject_polygon.points.append(.{ .x = 100.0, .y = 250.0 }); + try subject_polygon.points.append(.{ .x = 100.0, .y = 200.0 }); + + var clip_polygon = Polygon.init(allocator); + defer clip_polygon.deinit(); + + try clip_polygon.points.append(.{ .x = 100.0, .y = 100.0 }); + try clip_polygon.points.append(.{ .x = 300.0, .y = 100.0 }); + try clip_polygon.points.append(.{ .x = 300.0, .y = 300.0 }); + try clip_polygon.points.append(.{ .x = 100.0, .y = 300.0 }); + + var result = try sutherlandHodgmanClip(allocator, subject_polygon, clip_polygon); + defer result.deinit(); + + print("{}\n", .{result}); +} diff --git a/Task/Sylvesters-sequence/EasyLang/sylvesters-sequence.easy b/Task/Sylvesters-sequence/EasyLang/sylvesters-sequence.easy index deda357e5b..e81753067c 100644 --- a/Task/Sylvesters-sequence/EasyLang/sylvesters-sequence.easy +++ b/Task/Sylvesters-sequence/EasyLang/sylvesters-sequence.easy @@ -1,4 +1,4 @@ -numfmt 8 0 +numfmt 0 8 for i = 1 to 10 if i = 1 sylv = 2 diff --git a/Task/Take-notes-on-the-command-line/Crystal/take-notes-on-the-command-line.cr b/Task/Take-notes-on-the-command-line/Crystal/take-notes-on-the-command-line.cr new file mode 100644 index 0000000000..e5f984ec6a --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Crystal/take-notes-on-the-command-line.cr @@ -0,0 +1,9 @@ +NOTES = "NOTES.TXT" + +if ARGV.empty? + print File.read(NOTES) rescue nil +else + File.open NOTES, "a" do |f| + f.puts "#{Time.local}\n\t#{ARGV.join(" ")}" + end +end diff --git a/Task/Tau-number/REXX/tau-number.rexx b/Task/Tau-number/REXX/tau-number-1.rexx similarity index 100% rename from Task/Tau-number/REXX/tau-number.rexx rename to Task/Tau-number/REXX/tau-number-1.rexx diff --git a/Task/Tau-number/REXX/tau-number-2.rexx b/Task/Tau-number/REXX/tau-number-2.rexx new file mode 100644 index 0000000000..9956fc6292 --- /dev/null +++ b/Task/Tau-number/REXX/tau-number-2.rexx @@ -0,0 +1,34 @@ +-- 8 May 2025 +include Settings + +call Time('r') +say 'TAU NUMBER' +say version +say +call Task 100 +call Timer +exit + +Task: +procedure +arg xx +say 'First' xx ' tau numbers...' +n = 0 +do i = 1 until n = xx + a = Divisor(i) + if i//a = 0 then do + n = n+1 + call Charout ,Right(i,5) + if n//10 = 0 then + say + end +end +say +return + +include Sequences +include Functions +include Special +include Constants +include Helper +include Abend diff --git a/Task/Terminal-control-Clear-the-screen/X86-64-Assembly/terminal-control-clear-the-screen.x86-64 b/Task/Terminal-control-Clear-the-screen/X86-64-Assembly/terminal-control-clear-the-screen.x86-64 new file mode 100644 index 0000000000..07b1bb4835 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/X86-64-Assembly/terminal-control-clear-the-screen.x86-64 @@ -0,0 +1,17 @@ +.intel_syntax noprefix +.global _start +.text +_start: + call cls + mov rax, 60 + xor rdi, rdi + syscall +cls: /* void cls(); */ + push 0x631b /* push "\033c" on to the stack */ + mov rdx, 2 /* number of charcters to write */ + mov rsi, rsp /* the string to write is at "top" of stack */ + mov rdi, 1 /* stdout is the stream to write to */ + mov rax, 1 /* 1 is the system call "write" */ + syscall /* execute the system call */ + add rsp, 8 /* restore the stack */ + ret /* return from subroutine. */ diff --git a/Task/Test-integerness/EasyLang/test-integerness.easy b/Task/Test-integerness/EasyLang/test-integerness.easy index 9b53110ed6..f1800d664c 100644 --- a/Task/Test-integerness/EasyLang/test-integerness.easy +++ b/Task/Test-integerness/EasyLang/test-integerness.easy @@ -1,11 +1,9 @@ func isint x . - if x mod 1 = 0 - return 1 - . + return if x mod 1 = 0 . num[] = [ 25.000000 24.999999 25.0001 -2.1e120 -5e-2 0 / 0 1 / 0 ] # -numfmt 10 0 +numfmt 0 10 for n in num[] write n & " -> " if isint n = 1 diff --git a/Task/Text-processing-1/Lua/text-processing-1.lua b/Task/Text-processing-1/Lua/text-processing-1.lua index 9fb810c572..a9a02e9022 100644 --- a/Task/Text-processing-1/Lua/text-processing-1.lua +++ b/Task/Text-processing-1/Lua/text-processing-1.lua @@ -5,10 +5,7 @@ file_sum, file_cnt_data, file_lines = 0, 0, 0 max_rejected, n_rejected = 0, 0 max_rejected_date, rejected_date = "", "" -while true do - data = io.read("*line") - if data == nil then break end - +for data in io.lines() do date = string.match( data, "%d+%-%d+%-%d+" ) if date == nil then break end @@ -24,9 +21,9 @@ while true do cnt = cnt + 1 n_rejected = 0 else - if n_rejected == 0 then - rejected_date = date - end + if n_rejected == 0 then + rejected_date = date + end n_rejected = n_rejected + 1 if n_rejected > max_rejected then max_rejected = n_rejected diff --git a/Task/Text-processing-1/XPL0/text-processing-1.xpl0 b/Task/Text-processing-1/XPL0/text-processing-1.xpl0 new file mode 100644 index 0000000000..3822ed843b --- /dev/null +++ b/Task/Text-processing-1/XPL0/text-processing-1.xpl0 @@ -0,0 +1,49 @@ +include xpllib; \for Print + +char File_name, C, Date(10+1), FalseDate(10+1); +int N, I, Flag, Count, FalseCount, FalseRun, Readings; +real Data, Line_tot, Line_avg, Total; + +[File_name:= "readings.txt"; +FSet(FOpen(File_name, 0), ^i); OpenI(3); +Total:= 0.; Readings:= 0; FalseCount:= 0; FalseRun:= 0; +loop + [for N:= 0 to 10-1 do + [C:= ChIn(3); + if C = LF then C:= ChIn(3); + if C = EOF then quit; + Date(N):= C; + ]; + Date(N):= 0; + + Line_tot:= 0.; Count:= 0; + for N:= 0 to 24-1 do + [Data:= RlIn(3); + Flag:= IntIn(3); + if Flag > 0 then + [Line_tot:= Line_tot + Data; + Count:= Count + 1; + FalseCount:= 0; + ] + else + [FalseCount:= FalseCount+1; + if FalseCount > FalseRun then + [FalseRun:= FalseCount; + for I:= 0 to 10 do FalseDate(I):= Date(I); + ]; + ]; + ]; + Total:= Total + Line_tot; + Readings:= Readings + Count; + Line_avg:= Line_tot / float(Count); + Print("Line: %s Reject: %2d Accept: %2d Line_tot: %4.3f Line_avg: %3.3f\n", + Date, 24-Count, Count, Line_tot, Line_avg); + ]; +Print("\nFile = %s\n", File_name); +Print("Total = %1.3f\n", Total); +Print("Readings = %d\n", Readings); +Print("Average = %1.3f\n", Total/float(Readings)); + +Print("\nMaximum run of %d consecutive false readings", FalseRun); +Print("\nends at line starting with date: %s\n", FalseDate); +] diff --git a/Task/Text-processing-2/ALGOL-68/text-processing-2.alg b/Task/Text-processing-2/ALGOL-68/text-processing-2.alg new file mode 100644 index 0000000000..2ff93bbb0d --- /dev/null +++ b/Task/Text-processing-2/ALGOL-68/text-processing-2.alg @@ -0,0 +1,164 @@ +BEGIN # Test processing/2 - using thee file from Text processing/1, # + # verify the format, detect duplicate dates and # + # count the number of records with all instruments # + # functioning # + + PR read "files.incl.a68" PR # include file utilities: EACHLINE, etc. # + + CHAR tab = REPR 9; + + INT instruments = 24; # expected number of instrument readings # + MODE READING = STRUCT( STRING date + , [ 1 : instruments ]REAL data + , [ 1 : instruments ]INT status + , BOOL format ok + , STRING message + ); + OP INIT = ( REF READING r )VOID: + BEGIN + FOR n TO instruments DO ( data OF r )[ n ] := ( status OF r )[ n ] := 0 OD; + format ok OF r := TRUE; + date OF r := ""; + message OF r := "" + END # INIT # ; + + INT all good count := 0; # number of lines which have all instruments ok # + STRING last date := ""; # date of the previous line # + + # return the date and instrument readings and status values on the line # + PROC parse readings = ( STRING line )READING: + BEGIN + BOOL data error := FALSE; + # returns v converted to a REAL, returns 0 and sets data error # + # to TRUE if v is invalid # + OP TOREAL = ( STRING v )REAL: + BEGIN + REAL value := 0; + FILE real value; + associate( real value, LOC STRING := v ); + on value error + ( real value + , ( REF FILE ef )BOOL: # "handles" invalid data and # + BEGIN # returns TRUE so processing # + value := 0; # can continue # + data error := TRUE + END + ); + get( real value, value ); + close( real value ); + value + END # TOREAL # ; + # returns v converted to an INT, returns 0 and sets data error # + # to TRUE if v is invalid # + OP TOINT = ( STRING text )INT: + BEGIN + INT value := 0; + BOOL is numeric := TRUE; + FOR ch pos FROM UPB text BY -1 TO LWB text WHILE is numeric DO + CHAR c = text[ ch pos ]; + IF c = "-" + THEN value := - value; + is numeric := ch pos = LWB text AND ch pos /= UPB text + ELSE is numeric := is numeric AND c >= "0" AND c <= "9"; + IF is numeric THEN ( value *:= 10 ) +:= ABS c - ABS "0" FI + FI + OD; + IF NOT is numeric THEN data error := TRUE FI; + value + END # TOINT # ; + # superficially checks v is in the format yyyy-mm-dd # + PROC check date format = ( STRING v )BOOL: + BEGIN + STRING ymd := v[ AT 1 ]; + IF NOT ( data error := UPB ymd /= 10 ) THEN + # length is correct for yyyy-mm-dd # + IF NOT ( data error := ymd[ 5 ] /= "-" OR ymd[ 8 ] /= "-" ) THEN + INT d; + d := ( TOINT ymd[ 1 : 4 ] * 10000 ) + + ( TOINT ymd[ 6 : 7 ] * 100 ) + + TOINT ymd[ 9 : 10 ] + FI + FI; + NOT data error + END # check date format # ; + + READING result; INIT result; + INT c pos := LWB line; + INT max pos = UPB line; + INT field number := 0; + WHILE c pos <= max pos DO + # skip leading spaces and tabs # + WHILE IF c pos > max pos + THEN FALSE + ELSE CHAR ch = line[ c pos ]; ch = " " OR ch = tab + FI + DO c pos +:= 1 OD; + IF c pos <= max pos THEN # have a field # + INT start pos = c pos; + WHILE IF c pos > max pos + THEN FALSE + ELSE CHAR ch := line[ c pos ]; ch /= " " AND ch /= tab + FI + DO c pos +:= 1 OD; + STRING f := line[ start pos : c pos - 1 ]; + IF ( field number +:= 1 ) = 1 THEN # the date # + IF NOT check date format( f ) THEN + format ok OF result := FALSE; + message OF result := "Invalid date: " + f + FI; + date OF result := f + ELIF INT instrument = field number OVER 2; + instrument > instruments THEN + format ok OF result := FALSE; # too many readings # + message OF result := "Too many instruments" + ELIF ODD field number THEN + # field 3, 5, 7... the instrument state of reading # + ( status OF result )[ field number OVER 2 ] := TOINT f; + IF data error THEN + format ok OF result := FALSE; + message OF result := "Invalid status for instrument " + whole( instrument, 0 ) + FI + ELSE # must be the instrument reading # + ( data OF result )[ field number OVER 2 ] := TOREAL f; + IF data error THEN + format ok OF result := FALSE; + message OF result := "Invalid reading for instrument " + whole( instrument, 0 ) + FI + FI + FI + OD; + IF format ok OF result AND field number /= 2 * instruments + 1 THEN + format ok OF result := FALSE; + message OF result := "Incorrect number of readings/status values" + FI; + result + END # parse readings # ; + + # checks the readings and date on line # + PROC check readings = ( STRING line, INT line count )BOOL: + BEGIN + READING data := parse readings( line ); + IF format ok OF data AND line count > 1 AND date OF data = last date THEN + format ok OF data := FALSE; + message OF data := "Duplicate date: " + date OF data + FI; + IF NOT format ok OF data THEN # line has invalid data # + print( ( "Line: ", whole( line count, 0 ), ": ", message OF data, newline ) ) + ELSE # the line appears ok # + BOOL all good := TRUE; + FOR i TO instruments WHILE all good := ( status OF data )[ i ] > 0 DO SKIP OD; + IF all good THEN all good count +:= 1 FI; + last date := date OF data + FI; + TRUE + END # check readings # ; + + IF STRING file name = "readings.txt"; + INT total lines = file name EACHLINE check readings; + total lines < 0 + THEN print( ( "Unable to open ", file name, newline ) ) + ELSE print( ( whole( total lines, 0 ), " lines in ", file name, ", " ) ); + print( ( whole( all good count, 0 ), " have all instruments in a good state.", newline ) ) + FI + +END diff --git a/Task/Text-processing-2/FreeBASIC/text-processing-2.basic b/Task/Text-processing-2/FreeBASIC/text-processing-2.basic new file mode 100644 index 0000000000..c499b5e543 --- /dev/null +++ b/Task/Text-processing-2/FreeBASIC/text-processing-2.basic @@ -0,0 +1,128 @@ +#include "datetime.bi" + +Const filename = "readings.txt" +Const readings = 24 ' per line +Const fields = readings*2 + 1 ' per line +Const dateFormat = "%Y-%m-%d" + +Type DateRecord + fecha As String + hasGoodRecord As Boolean +End Type + +' Array to store unique dates +Dim Shared As DateRecord dateRecords(Any) + +' Function to check if a fecha exists in our array +Function findDate(dateArray() As DateRecord, dateStr As String, count As Integer) As Integer + For i As Integer = 0 To count - 1 + If dateArray(i).fecha = dateStr Then Return i + Next + Return -1 +End Function + +Sub main() + Dim As Integer ff, flag, dateIndex, i, partCount + Dim As Integer allGood = 0, uniqueGood = 0, dateCount = 0 + Dim As String linea, dateStr, currentPart, c + Dim As Double value + Dim As Boolean good + + + ff = Freefile + If Open(filename For Input As #ff) <> 0 Then + Print "Error: Could not open file '" & filename & "'" + Exit Sub + End If + + ' Process each line + While Not Eof(ff) + Line Input #ff, linea + + ' Split the line into fields + Dim As String parts(0 To fields-1) + partCount = 0 + currentPart = "" + + ' Optimized string parsing + For i = 1 To Len(linea) + c = Mid(linea, i, 1) + If c = " " Or c = Chr(9) Then ' Space or Tab + If Len(currentPart) > 0 Then + parts(partCount) = currentPart + partCount += 1 + currentPart = "" + End If + Else + currentPart &= c + End If + Next + + ' Add the last part if it exists + If Len(currentPart) > 0 Then + parts(partCount) = currentPart + partCount += 1 + End If + + ' Check if we have the expected number of fields + If partCount <> fields Then + Print "Error: Unexpected format, " & partCount & " fields." + Close #ff + Exit Sub + End If + + ' Get the date + dateStr = parts(0) + + ' Check if all readings are good + good = True + For i = 1 To fields-1 Step 2 + flag = Val(parts(i+1)) + If flag > 0 Then + value = Val(parts(i)) + If value = 0 And parts(i) <> "0" And parts(i) <> "0.000" Then + Print "Error: Could not convert '" & parts(i) & "' to integer." + Close #ff + Exit Sub + End If + Else + good = False + Exit For + End If + Next + + If good Then allGood += 1 + + dateIndex = findDate(dateRecords(), dateStr, dateCount) + + If dateIndex >= 0 Then + Print "Duplicate datestamp: " & dateStr + If good And Not dateRecords(dateIndex).hasGoodRecord Then + dateRecords(dateIndex).hasGoodRecord = True + uniqueGood += 1 + End If + Else + ' New date + If dateCount > Ubound(dateRecords) Then + Redim Preserve dateRecords(Ubound(dateRecords) + 100) + End If + + dateRecords(dateCount).fecha = dateStr + dateRecords(dateCount).hasGoodRecord = good + + If good Then uniqueGood += 1 + + dateCount += 1 + End If + Wend + + Close #ff + + Print !"\nData format valid." + Print allGood & " records with good readings for all instruments." + Print uniqueGood & " unique dates with good readings for all instruments." +End Sub + +main() + +Sleep diff --git a/Task/Text-processing-2/Lua/text-processing-2.lua b/Task/Text-processing-2/Lua/text-processing-2.lua index e7680645e4..bd9f36afdd 100644 --- a/Task/Text-processing-2/Lua/text-processing-2.lua +++ b/Task/Text-processing-2/Lua/text-processing-2.lua @@ -5,10 +5,7 @@ dates = {} duplicated, bad_format = {}, {} num_good_records, lines_total = 0, 0 -while true do - line = io.read( "*line" ) - if line == nil then break end - +for line in io.lines() do lines_total = lines_total + 1 date = string.match( line, "%d+%-%d+%-%d+" ) diff --git a/Task/Text-processing-2/XPL0/text-processing-2.xpl0 b/Task/Text-processing-2/XPL0/text-processing-2.xpl0 new file mode 100644 index 0000000000..43c7974864 --- /dev/null +++ b/Task/Text-processing-2/XPL0/text-processing-2.xpl0 @@ -0,0 +1,42 @@ +include xpllib; \for Print, StrCmp and StrCopy + +int Records, Invalid, AllGood; +char File_name, C, Date(10+1), LastDate(10+1); +int N, Flag, Count; +real Data; + +[File_name:= "readings.txt"; +Print("File = %s\n", File_name); +Print("\nDuplicated dates:\n"); +FSet(FOpen(File_name, 0), ^i); OpenI(3); + +Records:= 0; Invalid:= 0; AllGood:= 0; +LastDate(0):= 0; +loop + [for N:= 0 to 10-1 do + [C:= ChIn(3); + if C = LF then C:= ChIn(3); + if C = EOF then quit; + Date(N):= C; + ]; + Date(N):= 0; + if Date(0)#^1 and Date(0)#^2 then Invalid:= Invalid+1; + if StrCmp(Date, LastDate) = 0 then + Print("%s\n", Date); + StrCopy(LastDate, Date); + Records:= Records+1; + + Count:= 0; + for N:= 0 to 24-1 do + [Data:= RlIn(3); + Flag:= IntIn(3); + if Flag > 0 then + Count:= Count+1; + ]; + if Count = 24 then AllGood:= AllGood+1; + ]; +Print("\nTotal number of records : %d\n", Records); +Print("Number of invalid records : %d\n", Invalid); +Print("Number which are all good : %d (%1.2f^%)\n", + AllGood, float(AllGood)/float(Records)*100.0); +] diff --git a/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua b/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua index 0c56849d95..65a4b7eb43 100644 --- a/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua +++ b/Task/Text-processing-Max-licenses-in-use/Lua/text-processing-max-licenses-in-use.lua @@ -1,24 +1,17 @@ filename = "mlijobs.txt" -io.input( filename ) max_out, n_out = 0, 0 occurr_dates = {} -while true do - line = io.read( "*line" ) - if line == nil then break end - - if string.find( line, "OUT" ) ~= nil then - n_out = n_out + 1 - if n_out > max_out then +for line in io.lines(filename) + local dispensed = string.find( line, "OUT" ) + n_out = n_out + (dispensed==true and 1 or -1) + if dispensed and n_out >= max_out then + if n_out > max_out then max_out = n_out occurr_dates = {} - occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" ) - elseif n_out == max_out then - occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" ) - end - else - n_out = n_out - 1 + end + occurr_dates[#occurr_dates+1] = string.match( line, "@ ([%d+%p]+)" ) end end diff --git a/Task/The-Name-Game/EasyLang/the-name-game.easy b/Task/The-Name-Game/EasyLang/the-name-game.easy index bf40f74c86..b26adb387b 100644 --- a/Task/The-Name-Game/EasyLang/the-name-game.easy +++ b/Task/The-Name-Game/EasyLang/the-name-game.easy @@ -1,4 +1,4 @@ -proc verse x$ . . +proc verse x$ . x1$ = substr x$ 1 1 y$ = substr x$ 2 99 if strpos "AEIOU" x1$ <> 0 diff --git a/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy b/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy index 5dd88b4cb7..f851e74ca4 100644 --- a/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy +++ b/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy @@ -1,7 +1,7 @@ func log n . return log10 n / log10 2.71828182845904523 . -proc sundaram np . primes[] . +proc sundaram np &primes[] . nmax = floor (np * (log np + log log np) - 0.9385) + 1 k = (nmax - 2) / 2 len marked[] k diff --git a/Task/The-sieve-of-Sundaram/REXX/the-sieve-of-sundaram.rexx b/Task/The-sieve-of-Sundaram/REXX/the-sieve-of-sundaram.rexx index c66127eda0..8825dc83a0 100644 --- a/Task/The-sieve-of-Sundaram/REXX/the-sieve-of-sundaram.rexx +++ b/Task/The-sieve-of-Sundaram/REXX/the-sieve-of-sundaram.rexx @@ -1,33 +1,62 @@ -/*REXX program finds & displays N Sundaram primes, or displays the Nth Sundaram prime.*/ -parse arg n cols . /*get optional number of primes to find*/ -if n=='' | n=="," then n= 100 /*Not specified? Then assume default.*/ -if cols=='' | cols=="," then cols= 10 /* " " " " " */ -@.= .; lim= 16 * n /*default value for array; filter limit*/ - do j=1 for n; do k=1 for n until _>lim; _= j + k + 2*j*k; @._= - end /*k*/ - end /*j*/ -w= 10 /*width of a number in any column. */ - title= 'a list of ' commas(N) " Sundaram primes" -if cols>0 then say ' index │'center(title, 1 + cols*(w+1) ) -if cols>0 then say '───────┼'center("" , 1 + cols*(w+1), '─') -#= 0; idx= 1 /*initialize # of Sundaram primes & IDX*/ -$= /*a list of Sundaram primes (so far). */ - do j=1 until #==n /*display the output (if cols > 0). */ - if @.j\==. then iterate /*Is the number not prime? Then skip. */ - #= # + 1 /*bump number of Sundaram primes found.*/ - a= j /*save J for calculating the Nth prime.*/ - if cols<=0 then iterate /*Build the list (to be shown later)? */ - c= commas(j + j + 1) /*maybe add commas to Sundaram prime.*/ - $= $ right(c, max(w, length(c) ) ) /*add Sundaram prime──►list, allow big#*/ - if #//cols\==0 then iterate /*have we populated a line of output? */ - say center(idx, 7)'│' substr($, 2); $= /*display what we have so far (cols). */ - idx= idx + cols /*bump the index count for the output*/ - end /*j*/ - -if $\=='' then say center(idx, 7)"│" substr($, 2) /*possible display residual output.*/ -if cols>0 then say '───────┴'center("" , 1 + cols*(w+1), '─') +-- 25 Apr 2025 +include Settings +arg xx +say 'THE SIEVE OF SUNDARAM' +say version say -say 'found ' commas(#) " Sundaram primes, and the last Sundaram prime is " commas(a+a+1) -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? +call Collect 16e6 +call Task100 +call Task1e6 +call Timer +exit + +Collect: +procedure expose prim. work. +arg xx +say 'Collecting primes up to' xx'...' +work. = 1 +k = (xx-3)%2+1; m = (Isqrt(xx-3))%2+1 +do i = 0 to m + p = 2*i+3; s = (p*p-3)%2 + do j = s by p to k + work.j = 0 + end +end +prim. = 0; n = 0 +do i = 0 to k + if work.i then do + p = i+i+3 + if p > xx then + leave i + n = n+1; prim.n = p + end +end +prim.0 = n +say n 'found' +say +return n + +Task100: +procedure expose prim. +say 'First 100 Sundaram primes (excluding 2)...' +do i = 1 to 100 + call Charout ,Right(prim.i,4) + if i//10 = 0 then + say +end +say +return + +Task1e6: +procedure expose prim. +say '1 millionth Sundaram prime (excluding 2)...' +say prim.1000000 +say +return + +include Sequences +include Helper +include Numbers +include Functions +include Constants +include Abend diff --git a/Task/Thieles-interpolation-formula/Fortran/thieles-interpolation-formula.f b/Task/Thieles-interpolation-formula/Fortran/thieles-interpolation-formula.f new file mode 100644 index 0000000000..334028f3c8 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Fortran/thieles-interpolation-formula.f @@ -0,0 +1,87 @@ +program thiele_trig_demo + use, intrinsic :: ieee_arithmetic + implicit none + integer, parameter :: n1 = 48 + integer, parameter :: n2 = n1 * (n1 - 1) / 2 + real(16), parameter :: pi = 4q0 * atan(1q0) + real(16), parameter :: paso = pi / (n1-1) + real(16) :: xVal(n1), tSin(n1), tCos(n1), tTan(n1) + real(16) :: res_sin, res_cos, res_tan, res_acos_neg1 + real(16) :: nan + integer :: i, n_half + real(16), allocatable :: rhot(:,:) + integer, parameter :: rSin=0, rCos=1, rTan=2, rTrig=2 + + nan = ieee_value(0.0q0, ieee_quiet_nan) + allocate(rhot(0:rTrig, 0:n2)) + rhot = nan + + ! Build the trig table + do i = 1, n1 + xVal(i) = (i-1) * paso + tSin(i) = sin(xVal(i)) + tCos(i) = cos(xVal(i)) + tTan(i) = tan(xVal(i)) + end do + + n_half = n1 / 2 + 1 ! covers [0, p/2] for arcsin and arctan + + print '(A,F16.12)', " PI : ", pi + print '(A,F16.12)', " 6*arcsin(0.5) : ", 6q0 * asin(0.5q0) + print '(A,F16.12)', " 3*arccos(0.5) : ", 3q0 * acos(0.5q0) + print '(A,F16.12)', " 4*arctan(1.0) : ", 4q0 * atan(1.0q0) + print '(A,F16.12)', " 1*arccos(-1.0): ", acos(-1.0q0) + + rhot = nan + res_sin = 6q0 * thieleInterpolator(tSin(1:n_half), xVal(1:n_half), rSin, 0.5q0, 0, n_half-1, rhot) + rhot = nan + res_cos = 3q0 * thieleInterpolator(tCos, xVal, rCos, 0.5q0, 0, n1-1, rhot) + rhot = nan + res_tan = 4q0 * thieleInterpolator(tTan(1:n_half), xVal(1:n_half), rTan, 1.0q0, 0, n_half-1, rhot) + rhot = nan + res_acos_neg1 = thieleInterpolator(tCos, xVal, rCos, -1.0q0, 0, n1-1, rhot) + print '(A,F16.12)', "6*thiele(tSin,xVal,rSin,0.5,0) : ", res_sin + print '(A,F16.12)', "3*thiele(tCos,xVal,rCos,0.5,0) : ", res_cos + print '(A,F16.12)', "4*thiele(tTan,xVal,rTan,1.0,0) : ", res_tan + print '(A,F16.12)', "1*thiele(tCos,xVal,rCos,-1.0,0): ", res_acos_neg1 + +contains + + recursive function rho(x, y, rdx, i, n, rhot) result(val) + real(16), intent(in) :: x(:), y(:) + integer, intent(in) :: rdx, i, n + real(16), intent(inout) :: rhot(0:,0:) + real(16) :: val + integer :: idx + + if (n < 0) then + val = 0q0 + return + end if + if (n == 0) then + val = y(i+1) + return + end if + + idx = (size(x)-1 - n) * (size(x) - n) / 2 + i + if (ieee_is_nan(rhot(rdx, idx))) then + rhot(rdx, idx) = (x(i+1) - x(i+1 + n)) / (rho(x, y, rdx, i, n-1, rhot) - rho(x, y, rdx, i+1, n-1, rhot)) & + + rho(x, y, rdx, i+1, n-2, rhot) + end if + val = rhot(rdx, idx) + end function rho + + recursive function thieleInterpolator(x, y, rdx, xin, n, nmax, rhot) result(val) + real(16), intent(in) :: x(:), y(:), xin + integer, intent(in) :: rdx, n, nmax + real(16), intent(inout) :: rhot(0:,0:) + real(16) :: val + + if (n > nmax) then + val = 1.0q0 + return + end if + val = rho(x, y, rdx, 0, n, rhot) - rho(x, y, rdx, 0, n-2, rhot) + (xin - x(n+1)) / thieleInterpolator(x, y, rdx, xin, n+1, nmax, rhot) + end function thieleInterpolator + +end program thiele_trig_demo diff --git a/Task/Thue-Morse/Zig/thue-morse.zig b/Task/Thue-Morse/Zig/thue-morse.zig new file mode 100644 index 0000000000..45a506d67f --- /dev/null +++ b/Task/Thue-Morse/Zig/thue-morse.zig @@ -0,0 +1,16 @@ +const std = @import("std"); + +fn thueMorse(comptime T: type, n: T) bool { + var r = n; + var s: u8 = @sizeOf(T); + + while (s > 0) : (s >>= 1) r ^= std.math.shr(T, r, s); + return r & 1 == 1; +} + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + for (0..63) |n| + try stdout.writeByte(if (thueMorse(@TypeOf(n), n)) '1' else '0'); + try stdout.writeByte('\n'); +} diff --git a/Task/Tic-tac-toe/APL/tic-tac-toe-1.apl b/Task/Tic-tac-toe/APL/tic-tac-toe-1.apl new file mode 100644 index 0000000000..4a50ac1e46 --- /dev/null +++ b/Task/Tic-tac-toe/APL/tic-tac-toe-1.apl @@ -0,0 +1,7 @@ +⎕IO←0 ⋄ t←1∘↑ ⋄ b←1∘↓ ⋄ c←{Z[?≢Z←⍸0=⍵]} ⍝ extract turn/board; cpu's move +y←{3::∇⍵⊣⎕←'no' ⋄ ⍞←'move (1-9): ' ⋄ 0=⍵[p←⍎12↓⍞]: p ⋄ 2⌷0 0} ⍝ your move +m←{((-,⊢)t⍵)@(0,{1=t⍵: y⍵ ⋄ c⍵}⍵)⊢⍵} ⍝ apply current player's move to board +w←{∨/3=|+/(0 0⍉B)⍪(0 0⍉⌽B)⍪B⍪⍉B←3 3⍴b⍵} ⍝ has game been won? +d←{⍵⊣⎕←' '⍪' '⍪⍨↑(⊣,' ',⊢)/3 3⍴'.XO'[0 1 ¯1⍳b⍵]} ⍝ display board +o←{0∊b⍵: 'XO'[1=t⍵],' wins' ⋄ 'tie'} ⍝ determine and print game outcome +g←{o d∘m⍣((w∨0~⍤∊b)⊣)10↑¯1} ⍝ game; move & display until won or full diff --git a/Task/Tic-tac-toe/APL/tic-tac-toe-2.apl b/Task/Tic-tac-toe/APL/tic-tac-toe-2.apl new file mode 100644 index 0000000000..d1f2edb155 --- /dev/null +++ b/Task/Tic-tac-toe/APL/tic-tac-toe-2.apl @@ -0,0 +1 @@ +g←{S←d m⍵ ⋄ w S: 'XO'[1=t S],' wins' ⋄ ~0∊b S: 'tie' ⋄ ∇S}10↑¯1⍨ diff --git a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy index fffa6c4109..c7f605dbe6 100644 --- a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy +++ b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy @@ -1,47 +1,36 @@ len f[] 9 state = 0 -textsize 14 +gtextsize 14 # -proc init . . - linewidth 2 - clear - color 666 - move 34 96 - line 34 20 - move 62 96 - line 62 20 - move 10 72 - line 86 72 - move 10 44 - line 86 44 - linewidth 2.5 - for i = 1 to 9 - f[i] = 0 - . - if state = 1 - timer 0.2 - . +proc init . + glinewidth 2 + gclear + gcolor 666 + gline 34 96 34 20 + gline 62 96 62 20 + gline 10 72 86 72 + gline 10 44 86 44 + glinewidth 2.5 + for i = 1 to 9 : f[i] = 0 + if state = 1 : timer 0.2 . -proc draw ind . . +proc draw ind . c = (ind - 1) mod 3 r = (ind - 1) div 3 x = c * 28 + 20 y = r * 28 + 30 if f[ind] = 4 - color 900 - move x - 7 y - 7 - line x + 7 y + 7 - move x + 7 y - 7 - line x - 7 y + 7 + gcolor 900 + gline x - 7 y - 7 x + 7 y + 7 + gline x + 7 y - 7 x - 7 y + 7 elif f[ind] = 1 - color 009 - move x y - circle 10 - color -2 - circle 7.5 + gcolor 009 + gcircle x y 10 + gcolor -2 + gcircle x y 7.5 . . -proc sum3 a d . st . +proc sum3 a d &st . for i = 1 to 3 s += f[a] a += d @@ -52,34 +41,24 @@ proc sum3 a d . st . st = 1 . . -proc rate . res done . +proc rate &res &done . res = 0 - for i = 1 step 3 to 7 - sum3 i 1 res - . - for i = 1 to 3 - sum3 i 3 res - . + for i = 1 step 3 to 7 : sum3 i 1 res + for i = 1 to 3 : sum3 i 3 res sum3 1 4 res sum3 3 2 res cnt = 1 for i = 1 to 9 - if f[i] = 0 - cnt += 1 - . + if f[i] = 0 : cnt += 1 . res *= cnt done = 1 - if res = 0 and cnt > 1 - done = 0 - . + if res = 0 and cnt > 1 : done = 0 . -proc minmax player alpha beta . rval rmov . +proc minmax player alpha beta &rval &rmov . rate rval done if done = 1 - if player = 1 - rval = -rval - . + if player = 1 : rval = -rval else rval = alpha start = random 9 @@ -100,30 +79,27 @@ proc minmax player alpha beta . rval rmov . . . . -proc show_result val . . - color 555 - move 16 4 +proc show_result val . + gcolor 555 if val < 0 # this never happens - text "You won" + gtext 16 4 "You won" elif val > 0 - text "You lost" + gtext 16 4 "You lost" else - text "Tie" + gtext 16 4 "Tie" . state += 2 . -proc computer . . +proc computer . minmax 4 -11 11 val mov f[mov] = 4 draw mov rate val done state = 0 - if done = 1 - show_result val - . + if done = 1 : show_result val . -proc human . . +proc human . mov = floor ((mouse_x - 6) / 28) + 3 * floor ((mouse_y - 16) / 28) + 1 if f[mov] = 0 f[mov] = 1 diff --git a/Task/Tic-tac-toe/Factor/tic-tac-toe-1.factor b/Task/Tic-tac-toe/Factor/tic-tac-toe-1.factor new file mode 100644 index 0000000000..9bbbd5ad71 --- /dev/null +++ b/Task/Tic-tac-toe/Factor/tic-tac-toe-1.factor @@ -0,0 +1,22 @@ +USING: multiline math.vectors arrays sequences io.streams.c kernel assocs math io grouping math.matrices math.parser random strings ; IN: tictactoe + +CONSTANT: winmasks { 7 56 448 73 146 292 273 84 } +t 0 0 ! turn board1 board2 +[ + pick ! turn b1 b2 turn + [ 2dup bitor 9 f swap indices random set-bit ] ! cpu's move + [ [ 2dup bitor nl "enter a move (1-9):" print readln string>number 1 - tuck ! your move + [ nip [ 9 < ] [ 0 >= ] bi and ] [ bit? not ] 2bi and [ set-bit f ] [ drop "no" print t ] if + ] loop + ] if ! switch on turn + { { [ dup winmasks swap [ bitand bit-count 3 = ] curry any? ! check for win + ] [ pick "O" "X" ? " wins" append print f ] + } + { [ 2dup bitor 511 = ] [ "tie" print f ] ! check for tie + } [ t ] ! if neither, then loop + } cond + [ 3dup rot not [ swap ] when [ 9 >array ] bi@ 2 v*n v+ 3 ! display the board + [ nl [ ".XO" nth 1string " " append write ] each ] each nl + ] dip ! keep loop flag + [ not ] 3dip swapd ! negate turn; swap boards +] loop 3drop ! empty the stack when done diff --git a/Task/Tic-tac-toe/Factor/tic-tac-toe-2.factor b/Task/Tic-tac-toe/Factor/tic-tac-toe-2.factor new file mode 100644 index 0000000000..21e54238b0 --- /dev/null +++ b/Task/Tic-tac-toe/Factor/tic-tac-toe-2.factor @@ -0,0 +1,27 @@ +USING: multiline math.vectors arrays sequences io.streams.c kernel assocs math io grouping math.matrices math.parser random strings ; IN: tictactoe + +: open? ( pos board -- ? ) nth 0 = ; + +: full? ( board -- ? ) 0 swap member? not ; + +: won? ( board -- ? ) + 3 dup [ flip ] [ main-diagonal ] [ anti-diagonal ] tri 2array 3append [ sum abs 3 = ] any? ; + +: you ( -- position ) + "enter a move (1-9):" print readln string>number 1 - dup + [ 9 < ] [ 0 >= ] bi and [ drop "no" print you ] unless ; + +: cpu ( board -- ? ) [ [ 0 = ] dip and ] map-index sift random ; + +: pos ( cturn? board -- position ) swap 0 < [ cpu ] [ drop you ] if ; + +: move ( turn board -- nturn nboard ) + 2dup pos swap 2dup open? [ [ set-nth ] [ nip ] 3bi [ neg ] dip ] [ nip "no" print move ] if ; + +: show ( board -- ) + nl 3 [ [ 1 + "O.X" nth 1string " " append write ] each nl ] each ; + +: outcome ( turn board -- ) + [ neg ] dip won? [ 1 + "O.X" nth 1string " wins" append ] [ drop "tie" ] if nl print ; + +: ttt ( -- ) -1 9 0 [ move [ show ] keep dup [ won? ] [ full? ] bi or not ] loop outcome ; diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-1.j b/Task/Tic-tac-toe/J/tic-tac-toe-1.j index ef06e6f43c..8d1d5e9411 100644 --- a/Task/Tic-tac-toe/J/tic-tac-toe-1.j +++ b/Task/Tic-tac-toe/J/tic-tac-toe-1.j @@ -1,8 +1,8 @@ -'`turn board open full'=. {.`}.`(0=[{board@])`(0-.@e.board) -'`cpu pos'=. (?@#{])@([:I.0=board)`(cpu`you@.(_1 1 i.turn)) -you=. $:@echo@'no'^:(-.@e.i.@9)@:<:@".@(1!:1)@1@echo@'enter a move (1–9):' -move=. pos ($:@][echo@'no')`(-@turn@], turn@]`[`(board@])})@.open ] -outcome=. 'tie'"_`(' wins',~ {&'.XO'@-@turn)@.won -show=. [ ''echo@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$board) -won=. [: +./ 3 = [: | +/"1@(],|:,(<@0 1|:]),:<@0 1|:|.)@(3 3$board) -ttt=: [: outcome [: show@move^:(won-.@+.full)^:_. (10&{.@_1) +'`c t b'=. (?@#{])@([:I.0=b)`{.`}. NB. cpu's move; extract turn/board +v=. (0=]{b@[) :: 0 *. ]e.i.@9 NB. posn (y) valid and open on board (x)? +y=. ($:@[ echo@'no')^:(-.@v) _1+0".1!:1@1@echo@'move (1-9):' NB. your move +m=. (-,])@t [`(0,1+c`y@.(1=t)@])} ] NB. apply current player's move to board +o=. 'tie'"_`(' wins',~ {&'.XO'@-@t)@.w NB. print game outcome +d=. [ ''echo@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$b) NB. display the board +w=. [:+./ 3 = |@(+/"1)@(],|:,(<@0 1|:|.),:<@0 1|:])@(3 3$b) NB. test whether game has been won +g=: [: o [: d@m^:(-.@w*.0 e.b)^:_. _1:,9#0: NB. game; move & display until won or full diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-2.j b/Task/Tic-tac-toe/J/tic-tac-toe-2.j index 10d907e113..c4ab8cecc2 100644 --- a/Task/Tic-tac-toe/J/tic-tac-toe-2.j +++ b/Task/Tic-tac-toe/J/tic-tac-toe-2.j @@ -1 +1,8 @@ -Until=. {{u^:(-.@v)^:_.}} NB. apply u until condition v is true +'`c t b e x'=.(?@#{])@([:I.0=b)`{.`}.`echo`(1:Z:1:) NB. cpu's move; turn; board; print; exit +'`wm tm'=. (''e@, {&'.XO'@-@t ,' wins'"_)`([:e LF&,@'tie') NB. print win/tie message +i=. (0=]{b@[) ::0 -.@*. ]e.i.@9 NB. invalid posn? (x: state; y: posn) +y=. ($:@[ e@'no')^:i _1+0".@(1!:1@1)@e@'move (1-9):' NB. your move +m=. -@t , c`y@.(1=t) t@]`[`(b@])} ] NB. apply current player's move to board +d=. ''e@, '',~ (,' '&,)/"1@({&'.XO')@(3 3$b) NB. display the board +w=. 3 +./@:= |@(+/"1)@(],|:,(<@0 1|:|.),:<@0 1|:])@(3 3$b) NB. test whether game has been won +g=: [: d F.(([ [x@tm^:(0-.@e.b) [x@wm^:w)@m) 10{._1: NB. the game diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-3.j b/Task/Tic-tac-toe/J/tic-tac-toe-3.j index 5d221db368..9a4e28668b 100644 --- a/Task/Tic-tac-toe/J/tic-tac-toe-3.j +++ b/Task/Tic-tac-toe/J/tic-tac-toe-3.j @@ -1 +1 @@ -ttt=: [: outcome [: show@move Until (won+.full) 10&{.@_1 +wm`tm`$:@.(1:i.~w,0-.@e.b)@([d)@m 10{._1 diff --git a/Task/Tic-tac-toe/J/tic-tac-toe-4.j b/Task/Tic-tac-toe/J/tic-tac-toe-4.j new file mode 100644 index 0000000000..99d78bd028 --- /dev/null +++ b/Task/Tic-tac-toe/J/tic-tac-toe-4.j @@ -0,0 +1,14 @@ +'`turn board'=. {.`}. +Until=. {{u^:(-.@:v)^:_.}} NB. apply u until v is true +full=. {{-. 0 e. board y}} NB. board is full (tie game) +open=. {{0 = x { board y}} NB. given pos is free on board +invalid=. {{-. (y open ::0 x) *. y e.i.9}} NB. test for invalid position +cpu=. {{(?#o) { o=.I.0=board y}} NB. cpu's move +pos=. {{cpu`you@.(1 = turn y)y}} NB. get cpu's or user's move +you=. {{y {{you x[echo'no'}}^:(y invalid p) p=.<:0".(1!:1)1[echo'move (1-9):'}} NB. your move +move=. {{(- turn y) , (turn y) (pos y)} board y}} NB. apply move to the board +outcome=. {{ 'tie'"_ ` {{('.XO'{~-turn y),' wins'}}@.won y}} NB. print game outcome +show=. {{y [ echo'','',~([,' ',])/"1 '.XO'{~3 3$board y}} NB. display the board +'`diag antid'=. {{(<0 1)|:y}} ` {{(<0 1)|:|.y}} NB. get (anti-)diagonal +won=. {{+./3=|+/"1 B,(|:B),(antid B),:diag B=.3 3$board y}} NB. has game been won? +game=: {{outcome (show@move Until (won+.full)) _1,9#0[y}} diff --git a/Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js b/Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js new file mode 100644 index 0000000000..5da4f41904 --- /dev/null +++ b/Task/Tic-tac-toe/JavaScript/tic-tac-toe-3.js @@ -0,0 +1,96 @@ +/* + + Board Positions: Win Lines by Id: + 0|1|2 0 --- | | | \/ + 3|4|5 1 --- | | | /\ + 6|7|8 2 --- | | | 6 7 + 3 4 5 + + About: This is a "too clever by half" way of checking for wins. + To explain, let's first consider some other ways to check for wins: + + - Naive: if( (board[0] == pin && board[1] == pin && board[2] == pin)) return true; ... and repeat for all other win lines + + - Bitboard optimized: if ( (board & WIN_LINE1) == WIN_LINE1 || (board & WIN_LINE2) ... and repeat for all other win lines + + - Hash: Maybe we could just hash the winning values? Nope: in general, the "noise" from other pins requires too many states to be practical + + - Regex: See the PHP example of this: https://rosettacode.org/wiki/Tic-tac-toe#PHP + + - Base 4 method: But, can we do better?!?!? What is the limit of the maximum we can parallelize our win checking? + Dare we quixotically hope for a Game-Terminal check of O(1)? YES!! Yes, indeed! + And, that is what the follow is: An optimized way of win checking using some clever abuses of numbering systems, + (and uhm, by doing a little bit more work in the makeMove function). But, trade-offs, doncha know... + + Overview: The insight into the way this works, is that instead of looking at the board state, we are instead going to focus on counting the pins in a win line. + For example, what if we had counters like this: + + X|.|. --> Win Line 0 Count = 1 + X|X|. --> Win Line 1 Count = 2 + X|.|. --> Win Line 2 Count = 1 + \-----> Win Lines 3,4,5,6,7 = 3,1,0,2,2 respectively + + This is sufficient to let us know when there is a win. But, of course, just like the other methods, it requires multiple checks to determine if there is a winning line. + + But, we note that the count won't exceed three or four, so let's serialize the counters into a base4 string, (where each digit is the count for a win line). + + Giving us [2 2 0 1 3 1 2 1].b4 [41433].b10 for the example above. (With Win Line 0 starting in the Least-Significant-Bit on the right) + + Now, this seems a bit promising, as the winning count of three is right there in the middle of the string of digits. Now, if we could just + find some way to filter it out. But, what way might that be? + + The hack: Perhaps there's a more elegant solution? (Let me know if you find one...) + Regardless, a functional, if ugly method we can use is to take advantage of the overlap between base 4, and binary. This allows us to keep our count "logic" in base 4, + but still use bitwise operations to check in parallel. + + Expanding on this, we start counting at ONE, rather than ZERO - relying on the fact that it will then overflow to the next digit when it reaches a count of 4, + since we are working in base 4. + (Note: This does require us to double the digits used for counting in our base 4 serialized string, in order to keep the win lines from intersecting each other.) + + Here is the initial base 4 win line count, with all the lines starting off empty: + [01 01 01 01 01 01 01 01].b4 [286331153].b10 + + And for the example above we have the following: + + [03 03 01 02 10 02 03 02].b4 [856834610].b10 + + Finally, in the binary version of the win line string, (with four binary digits corresponding to the two base 4 digits), it can be seen that the count "overflow", + (and thus a win), is going to be "visible" as a bit set in the third of the 4 binary digits group corresponding to the base 4 count. + [0011 0011 0001 0010 0100 0010 0011 0010].b2 + ^--- Here + + The advantage of this, is that now we can create a bitwise mask to target only those third bits like this: + [0100 0100 0100 0100 0100 0100 0100 0100].b2 + ^ ^ ^ ^ ^ ^ ^ ^ + + Then, just do a bitwise AND against that overflow mask, and Bob's your uncle! + + Admittedly, this is indeed overkill for TicTacToe, but it could theoretically have potential uses with larger N-in-a-row games. + +*/ +const LINE_COUNTS = [0x11111111, 0x11111111]; // [01 01 01 01 01 01 01 01].b4 +const WIN_MASK = 0x44444444; // [10 10 10 10 10 10 10 10].b4 +const LINES_BY_POS = [ + 0x1001001, //Pos 0 - [00 01 00 00 01 00 00 01].b4 + 0x10001, //Pos 1 - [00 00 00 01 00 00 00 01].b4 + 0x10100001, //Pos 2 - [01 00 01 00 00 00 00 01].b4 + 0x1010, //Pos 3 - [00 00 00 00 01 00 01 00].b4 + 0x11010010, //Pos 4 - [01 01 00 01 00 00 01 00].b4 + 0x100010, //Pos 5 - [00 00 01 00 00 00 01 00].b4 + 0x10001100, //Pos 6 - [01 00 00 00 01 01 00 00].b4 + 0x10100, //Pos 7 - [00 00 00 01 00 01 00 00].b4 + 0x1100100, //Pos 8 - [00 01 01 00 00 01 00 00].b4 +]; + + +function isGameOver(turn) { + if ( (LINE_COUNTS[turn] & WIN_LINE)) return true; //This is the entire glorious raison d'etre for all the above rigamarole + else if (moveCount >= TOTAL_MOVES) return true;//Cat's game + else return false; +} + +function makeMove(pos) { + //Update state + LINE_COUNTS[turn] += LINES_BY_POS[pos]; //Win line accounting + moveCount++; +} diff --git a/Task/Time-a-function/Lua/time-a-function.lua b/Task/Time-a-function/Lua/time-a-function.lua index 2344a8fcdf..e7a108419b 100644 --- a/Task/Time-a-function/Lua/time-a-function.lua +++ b/Task/Time-a-function/Lua/time-a-function.lua @@ -1,12 +1,14 @@ -function Test_Function() - for i = 1, 10000000 do - local s = math.log( i ) - s = math.sqrt( s ) - end +function bench(Function, ...) + local t = os.time() + local clock1 = os.clock() + Function(...) + local c = os.clock()-clock + return os.time()-t, c end -t1 = os.clock() - Test_Function() -t2 = os.clock() +function sleep(n) + local start = os.time() + repeat until os.time()-start==n +end -print( os.difftime( t2, t1 ) ) +print( bench(sleep, 2) ) diff --git a/Task/Time-a-function/REXX/time-a-function-2.rexx b/Task/Time-a-function/REXX/time-a-function-2.rexx index 0e752fd011..b8a590ac0f 100644 --- a/Task/Time-a-function/REXX/time-a-function-2.rexx +++ b/Task/Time-a-function/REXX/time-a-function-2.rexx @@ -1,27 +1,483 @@ -/*REXX program displays the elapsed time for a REXX function (or subroutine). */ -arg reps . /*obtain an optional argument from C.L.*/ -if reps=='' then reps=100000 /*Not specified? No, then use default.*/ -call time 'Reset' /*only the 1st character is examined. */ -junk = silly(reps) /*invoke the SILLY function (below). */ - /*───► CALL SILLY REPS also works.*/ +-- 22 Mar 2025 +arg count','prec +include Settings - /* The E is for elapsed time.*/ - /* │ ─ */ - /* ┌────◄───┘ */ - /* │ */ - /* ↓ */ -say 'function SILLY took' format(time("E"),,2) 'seconds for' reps "iterations." - /* ↑ */ - /* │ */ - /* ┌────────►───────┘ */ - /* │ */ - /* The above 2 for the FORMAT function displays the time with*/ - /* two decimal digits (rounded) past the decimal point). Using */ - /* a 0 (zero) would round the time to whole seconds. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -silly: procedure /*chew up some CPU time doing some silly stuff.*/ - do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */ - @.j=random() date() time() digits() fuzz() form() xrange() queued() - end /*j*/ - return j-1 +say 'TIME A FUNCTION' +say version +say +call Parameters +call DoLoop +call DoForLoop +call DoToLoop +call DoForByLoop +call DoToByLoop +say +call Tarra +call IntegerAssign +call IntegerAdd +call IntegerMultiply +call IntegerDivide1 +call IntegerDivide2 +call IntegerRemainder +call IntegerPower +say +call FloatAssign +call FloatAdd +call FloatMultiply +call FloatDivide1 +call FloatDivide2 +call FloatRemainder +call FloatPower +call FloatFormula +say +call StringFunctions +call NumericFunctions +call DateFunctions +call TimeFunctions +say +call FixedParseVar +call DynamicParseVar +call ParseValue +say +call NoOperation +say +call IfThen +call SelectWhen +say +call CallProc +call CallProcParms +call CallRout +call CallRoutParms +say +call Interpreting +say +call Output +call Input +say +call Stems +say +call Average +return + +Parameters: +start = date() time() +if count = '' then + count = 1e6 +if prec = '' then + prec = 9 +parse version version +say 'Version' version +say 'Using loop counter' count/1e6 'million and' Digits() 'digits' +say +numeric digits prec +int1 = right(sqrt3(),prec%2); int2 = right(sqrt2(),prec%2) +if int2 > int1 then + parse value int2 int1 with int1 int2 +float1 = sqrt3()/1; float2 = sqrt2()/1 +tarra = 0; totelaps = 0; totcount = 0 +return + +DoLoop: +call Time('r') +do count +end +call Measure 'Do',1 +return + +DoForLoop: +call Time('r') +do n = 1 for count +end +call Measure 'Do for',1 +return + +DoToLoop: +call Time('r') +do n = 1 to count +end +call Measure 'Do to',1 +return + +DoForByLoop: +call Time('r') +do n = 1 for count by 1 +end +call Measure 'Do for by',1 +return + +DoToByLoop: +call Time('r') +do n = 1 to count by 1 +end +call Measure 'Do to by',1 +return + +Tarra: +call Time('r') +do n = 1 to 1e8 +end +tarra = Time('e')*count/1e8 +return + +IntegerAssign: +call Time('r') +do n = 1 to count + a = int1 +end +call Measure 'Integer assign',1 +return + +IntegerAdd: +call Time('r') +do n = 1 to count + a = int1+int2 +end +call Measure 'Integer +',1 +return + +IntegerMultiply: +call Time('r') +do n = 1 to count + a = int1*int2 +end +call Measure 'Integer *',1 +return + +IntegerDivide1: +call Time('r') +do n = 1 to count + a = int1/int2 +end +call Measure 'Integer /',1 +return + +IntegerDivide2: +call Time('r') +do n = 1 to count + a = int1//int2 +end +call Measure 'Integer //',1 +return + +IntegerRemainder: +call Time('r') +do n = 1 to count + a = int1%int2 +end +call Measure 'Integer %',1 +return + +IntegerPower: +call Time('r') +do n = 1 to count + a = int1**2 +end +call Measure 'Integer **',1 +return + +FloatAssign: +call Time('r') +do n = 1 to count + a = float1 +end +call Measure 'Float assign',1 +return + +FloatAdd: +call Time('r') +do n = 1 to count + a = float1+float2 +end +call Measure 'Float +',1 +return + +FloatMultiply: +call Time('r') +do n = 1 to count + a = float1*float2 +end +call Measure 'Float *',1 +return + +FloatDivide1: +call Time('r') +do n = 1 to count + a = float1/float2 +end +call Measure 'Float /',1 +return + +FloatDivide2: +call Time('r') +do n = 1 to count + a = float1//float2 +end +call Measure 'Float //',1 +return + +FloatRemainder: +call Time('r') +do n = 1 to count + a = float1%float2 +end +call Measure 'Float %',1 +return + +FloatPower: +call Time('r') +do n = 1 to count + a = float1**2 +end +call Measure 'Float **',1 +return + +FloatFormula: +call Time('r') +do n = 1 to count + a = (float1+float2) + (float1*float2) + (float1/float2) +end +call Measure 'Float formula',1 +return + +StringFunctions: +a = 'This is the first text'; b = 'This is the second text'; c = float1 +call Time('r') +do n = 1 to count + t = a||b + t = Abbrev('text',a) + t = Center(a,100) + t = Compare(a,b) + t = Copies(a,3) + t = Delstr(a,5,10) + t = Delword(a,2,3) + t = Format(c,1,5) + t = Insert(a,b,10) + t = Lastpos('text',a) + t = Left(a,10) + t = Length(a) + t = Overlay('xxx',a,3) + t = Pos('text',a) + t = Reverse(a) + t = Right(a,10) + t = Space(a) + t = Strip(a) + t = Substr(a,5,10) + t = Subword(a,2,2) + t = Translate(a,'xxx','the') + t = Verify(a,'the') + t = Word(a,3) + t = Wordindex(a,3) + t = Wordlength(a,3) + t = Wordpos('the',a) + t = Words(a) + t = Xrange('a','z') +end +call Measure 'String functions',28 +return + +NumericFunctions: +call Time('r') +do n = 1 to count + t = Abs(float1) + t = Max(float1,float2) + t = Min(float1,float2) + t = Random() + t = Sign(float1) + t = Trunc(float1) + t = Digits() +end +call Measure 'Numeric functions',7 +return + +DateFunctions: +call Time('r') +do n = 1 to count + t = Date('b') + t = Date('d') + t = Date('e') + t = Date('m') + t = Date('n') + t = Date('o') + t = Date('s') + t = Date('u') + t = Date('w') +end +call Measure 'Date functions',9 +return + +TimeFunctions: +call Time('r') +do n = 1 to count + t = Time('c') + t = Time('e') + t = Time('h') + t = Time('l') + t = Time('m') + t = Time('n') + t = Time('s') +end +call Measure 'Time functions',7 +return + +FixedParseVar: +t = '1,2,3,4,5,6,7,8,9,10' +call Time('r') +do n = 1 to count + parse var t rec1 ',' rec2 ',' rec3 ',' rec4 ',' rec5 ',' rec6 ',' rec7 ',' rec8 ',' rec9 ',' rec10 +end +call Measure 'Fixed parse var',1 +return + +DynamicParseVar: +t = '1,2,3,4,5,6,7,8,9,10' +call Time('r') +do n = 1 to count + do y = 1 to 10 + parse var t rec.y ',' t + end +end +call Measure 'Dynamic parse var',1 +return + +Parsevalue: +call Time('r') +do n = 1 to count + parse value float1 float2 with a,b +end +call Measure 'Parse value',1 +return + +NoOperation: +call Time('r') +do n = 1 to count + nop +end +call Measure 'No operation',1 +return + +IfThen: +call Time('r') +do n = 1 to count + if float1 = float1 then nop +end +call Measure 'If then',1 +return + +SelectWhen: +call Time('r') +do n = 1 to count + select + when float1 = float1 then nop + end +end +call Measure 'Select when',1 +return + +CallProc: +call Time('r') +do n = 1 to count + call Proc1 +end +call Measure 'Call procedure',1 +return + +CallProcParms: +call Time('r') +do n = 1 to count + call Proc2 1,2,3 +end +call Measure 'Call procedure arg',1 +return + +CallRout: +call Time('r') +do n = 1 to count + call Rout1 +end +call Measure 'Call routine',1 +return + +CallRoutParms: +call Time('r') +do n = 1 to count + call Rout2 1,2,3 +end +call Measure 'Call routine arg',1 +return + +Proc1: +procedure +return + +Proc2: +procedure +arg a,b,c +return + +Rout1: +return + +Rout2: +arg a,b,c +return + +Interpreting: +a = 'nop' +call Time('r') +do n = 1 to count + interpret a +end +call Measure 'Interpret',1 +return + +Output: +file = 'dummy.txt' +call Lineout file,,1 +call Time('r') +do n = 1 to count + call Lineout file,'Just a small line' +end +call Measure 'Output',1 +return + +Input: +file = 'dummy.txt' +call Time('r') +do n = 1 to count + t = Linein(file) +end +call Measure 'Input',1 +return + +Stems: +call Time('r') +do n = 1 to count + stem.n = n +end +call Measure 'Stem processing',1 +return + +Average: +totelaps = 1e6*totelaps/totcount +say Left('Average',20) round(totelaps,3) 'microsec =' round(1/totelaps,1) 'million clauses/sec' +say +say Left('Start run',20) start +say Left('Clauses processed',20) round(totcount/1e6,1) 'million' +say Left('Stop run',20) date() time() +return + +Measure: +parse arg measure,clauses +elaps = Time('e')-tarra +if elaps > 0 then do + totelaps = totelaps+elaps; totcount = totcount+count*clauses + elaps = 1e6*elaps/(count*clauses) + say Left(measure,20) round(elaps,3) 'microsec =' round(1/elaps,1) 'million clauses/sec' +end +else + say Left(measure,20) 'cannot perform measure, please try a higher count' +return + +include Functions +include Constants +include Abend diff --git a/Task/Time-a-function/REXX/time-a-function-3.rexx b/Task/Time-a-function/REXX/time-a-function-3.rexx deleted file mode 100644 index 4d8817660a..0000000000 --- a/Task/Time-a-function/REXX/time-a-function-3.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program displays the elapsed time for a REXX function (or subroutine). */ -arg reps . /*obtain an optional argument from C.L.*/ -if reps=='' then reps=100000 /*Not specified? No, then use default.*/ -call time 'Reset' /*only the 1st character is examined. */ -junk = silly(reps) /*invoke the SILLY function (below). */ - /*───► CALL SILLY REPS also works.*/ - - /* The J is for the CPU time used */ - /* │ by the REXX program since */ - /* ┌───────┘ since the time was RESET. */ - /* │ This is a Regina extension.*/ - /* ↓ */ -say 'function SILLY took' format(time("J"),,2) 'seconds for' reps "iterations." - /* ↑ */ - /* │ */ - /* ┌────────►───────┘ */ - /* │ */ - /* The above 2 for the FORMAT function displays the time with*/ - /* two decimal digits (rounded) past the decimal point). Using */ - /* a 0 (zero) would round the time to whole seconds. */ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -silly: procedure /*chew up some CPU time doing some silly stuff.*/ - do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */ - @.j=random() date() time() digits() fuzz() form() xrange() queued() - end /*j*/ - return j-1 diff --git a/Task/Time-a-function/REXX/time-a-function-4.rexx b/Task/Time-a-function/REXX/time-a-function-4.rexx deleted file mode 100644 index d4b24082bd..0000000000 --- a/Task/Time-a-function/REXX/time-a-function-4.rexx +++ /dev/null @@ -1,485 +0,0 @@ -Main: -call Parameters -call DoToLoops -call DoForLoops -call Tarra -call IntegerAssign -call IntegerAdd -call IntegerSubtract -call IntegerMultiply -call IntegerDivide1 -call IntegerDivide2 -call IntegerRemainder -call IntegerPower -call FloatingAssign -call FloatingAdd -call FloatingSubtract -call FloatingMultiply -call FloatingDivide1 -call FloatingDivide2 -call FloatingRemainder -call FloatingPower -call Formula -call StringFunctions -call NumericFunctions -call FixedParseVar -call DynamicParseVar -call NoOperation -call IfThen -call SelectWhen -call IfElseIf -call CallProc -call CallProcParms -call CallRout -call CallRoutParms -call DateTime -call PushPullQueued -call Interpreting -call Output -call Input -call StemProcessing -return - -Parameters: -arg count digit -if count = '' then - count = 1e6 -if digit = '' then - digit = 9 -numeric digits digit -parse version version -say 'Version' version -say 'Using loop counter' count/1e6 'million and' digits() 'digits' -say -tarra = 0 -call time('r') -return - -DoToLoops: -call time('r') -do x = 1 to count*10 -end -call Measure 'Do ... to ...',10 -return - -DoForLoops: -call time('r') -do x = 1 for count*10 -end -call Measure 'Do ... for ...',10 -return - -Tarra: -call time('r') -do x = 1 to count*10 -end -tarra = time('e')/10 -return - -IntegerAssign: -call time('r') -do x = 1 to count*10 - a = 123 -end -call Measure 'Integer assign',10 -return - -IntegerAdd: -call time('r') -do x = 1 to count*10 - a = x+123 -end -call Measure 'Integer +',10 -return - -IntegerSubtract: -call time('r') -do x = 1 to count*10 - a = x-123 -end -call Measure 'Integer -',10 -return - -IntegerMultiply: -call time('r') -do x = 1 to count*10 - a = x*123 -end -call Measure 'Integer *',10 -return - -IntegerDivide1: -call time('r') -do x = 1 to count*10 - a = 123/3 -end -call Measure 'Integer /',10 -return - -IntegerDivide2: -call time('r') -do x = 1 to count*10 - a = x//123 -end -call Measure 'Integer //',10 -return - -IntegerRemainder: -call time('r') -do x = 1 to count*10 - a = x%123 -end -call Measure 'Integer %',10 -return - -IntegerPower: -call time('r') -do x = 1 to count*10 - a = 123**2 -end -call Measure 'Integer **',10 -return - -FloatingAssign: -call time('r') -do x = 1 to count*10 - a = 1.23 -end -call Measure 'Floating assign',10 -return - -FloatingAdd: -call time('r') -do x = 1 to count*10 - a = x+1.23 -end -call Measure 'Floating +',10 -return - -FloatingSubtract: -call time('r') -do x = 1 to count*10 - a = x-1.23 -end -call Measure 'Floating -',10 -return - -FloatingMultiply: -call time('r') -do x = 1 to count*10 - a = x*1.23 -end -call Measure 'Floating *',10 -return - -FloatingDivide1: -call time('r') -do x = 1 to count*10 - a = x/1.23 -end -call Measure 'Floating /',10 -return - -FloatingDivide2: -call time('r') -do x = 1 to count*10 - a = x//1.23 -end -call Measure 'Floating //',10 -return - -FloatingRemainder: -call time('r') -do x = 1 to count*10 - a = x%1.23 -end -call Measure 'Floating %',10 -return - -FloatingPower: -call time('r') -do x = 1 to count*10 - a = 1.23**2 -end -call Measure 'Floating **',10 -return - -Formula: -call time('r') -do x = 1 to count - a = ( (x+1.23) * (x-1.23) ) / ( (x*1.23) * (x/1.23) ) -end -call Measure 'Formula',1 -return - -StringFunctions: -a = 'this is the first text'; b = 'this is the second text'; c = 1.23 -call time('r') -do x = 1 to count - t = a||b - t = abbrev('text',a) - t = center(a,100) - t = compare(a,b) - t = copies(a,3) - t = delstr(a,5,10) - t = delword(a,2,3) - t = format(c,1,2) - t = insert(a,b,10) - t = lastpos('text',a) - t = left(a,10) - t = length(a) - t = overlay('paul',a,4) - t = pos('text',a) - t = reverse(a) - t = right(a,10) - t = space(a) - t = strip(a) - t = substr(a,5,10) - t = subword(a,2,2) - t = translate(a,'one','the') - t = verify(a,'the') - t = word(a,3) - t = wordindex(a,3) - t = wordlength(a,3) - t = wordpos('is the',a) - t = words(a) - t = xrange('a','z') -end -call Measure 'String functions',28 -return - -NumericFunctions: -a = -1.23; b = 1.23 -call time('r') -do x = 1 to count - t = abs(a) - t = max(a,b) - t = min(a,b) - t = random() - t = sign(a) - t = trunc(b) - t = digits() -end -call Measure 'Numeric functions',7 -return - -FixedParseVar: -t = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20' -call time('r') -do x = 1 to count - parse var t rec1 ',' rec2 ',' rec3 ',' rec4 ',' rec5 ',' rec6 ',' rec7 ',' rec8 ',' rec9 ',' rec10 ',', - rec11 ',' rec12 ',' rec13 ',' rec14 ',' rec15 ',' rec16 ',' rec17 ',' rec18 ',' rec19 ',' rec20 ',' -end -call Measure 'Fixed parse var',1 -return - -DynamicParseVar: -t = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20' -call time('r') -do x = 1 to count - do y = 1 to 20 - parse var t rec.y ',' t - end -end -call Measure 'Dynamic parse var',1 -return - -NoOperation: -call time('r') -do x = 1 to count*10 - nop -end -call Measure 'No operation',10 -return - -IfThen: -a = 1 -call time('r') -do x = 1 to count - if a = 1 then nop - if a = 2 then nop - if a <> 1 then nop - if a <> 2 then nop - if a < 0 then nop - if a < 2 then nop - if a > 0 then nop - if a > 2 then nop -end -call Measure 'If ...then ...',8 -return - -SelectWhen: -a = 2 -call time('r') -do x = 1 to count - select - when a = 1 then nop - when a = 2 then nop - when a = 3 then nop - end - select - when a <> 2 then nop - when a <> 1 then nop - when a <> 0 then nop - end - select - when a > 2 then nop - when a > 1 then nop - when a > 0 then nop - end - select - when a < 2 then nop - when a < 3 then nop - when a < 4 then nop - end -end -call Measure 'Select ... when ...',8 -return - -IfElseIf: -a = 2 -call time('r') -do x = 1 to count - if a = 1 then nop - else if a = 2 then nop - else if a = 3 then nop - if a <> 2 then nop - else if a <> 1 then nop - else if a <> 0 then nop - if a > 2 then nop - else if a > 1 then nop - else if a > 0 then nop - if a < 2 then nop - else if a < 3 then nop - else if a < 4 then nop -end -call Measure 'If ... else if ...',8 -return - -CallProc: -call time('r') -do x = 1 to count - call Proc1 -end -call Measure 'Call procedure',1 -return - -CallProcParms: -call time('r') -do x = 1 to count - call Proc2 1,2,3 -end -call Measure 'Call procedure with parms',1 -return - -CallRout: -call time('r') -do x = 1 to count - call Rout1 -end -call Measure 'Call routine',1 -return - -CallRoutParms: -call time('r') -do x = 1 to count - call Rout2 1,2,3 -end -call Measure 'Call routine with parms',1 -return - -Proc1: -procedure -return - -Proc2: -procedure -arg a,b,c -return - -Rout1: -return - -Rout2: -arg a,b,c -return - -DateTime: -call time('r') -do x = 1 to count - t = date('b') - t = date('d') - t = date('e') - t = date('m') - t = date('n') - t = date('o') - t = date('s') - t = date('u') - t = date('w') - t = time('c') - t = time('e') - t = time('h') - t = time('l') - t = time('m') - t = time('n') - t = time('s') -end -call Measure 'Date and time',16 -return - -PushPullQueued: -a = 123.45 -call time('r') -do x = 1 to count - push a - b = queued() - pull a -end -call Measure 'Push, pull and queued',3 -return - -Interpreting: -a = 'nop' -call time('r') -do x = 1 to count - interpret a -end -call Measure 'Interpret',1 -return - -Output: -file = '\temp\perf.txt' -call lineout file,,1 -call time('r') -do x = 1 to count - call lineout file,'sequence number of this record is' x -end -call Measure 'Output',1 -return - -Input: -file = '\temp\perf.txt' -call time('r') -do x = 1 to count - t = linein(file) -end -call Measure 'Input',1 -return - -StemProcessing: -call time('r') -do x = 1 to count - stem.x.x.x = 1.23 -end -call Measure 'Stem processing',1 -return - -Measure: -parse arg measure,clauses -elaps = time('e')-tarra -if elaps > 0 then do - say left(measure,25) format((count*clauses)/(1e6*elaps) ,3,1) 'million clauses/sec' -end -else - say left(measure,25) 'loop counter too low, cannot perform measure' -return diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-1.lua similarity index 67% rename from Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping.lua rename to Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-1.lua index 2e72972d27..ab01ed7442 100644 --- a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping.lua +++ b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-1.lua @@ -1,14 +1,12 @@ -function tokenise (str, sep, esc) +function Tokenize (str, sep, esc) local strList, word, escaped, ch = {}, "", false for pos = 1, #str do ch = str:sub(pos, pos) if ch == esc then if escaped then word = word .. ch - escaped = false - else - escaped = true end + escaped = not escaped elseif ch == sep then if escaped then word = word .. ch @@ -25,9 +23,3 @@ function tokenise (str, sep, esc) table.insert(strList, word) return strList end - -local testStr = "one^|uno||three^^^^|four^^^|^cuatro|" -local testSep, testEsc = "|", "^" -for k, v in pairs(tokenise(testStr, testSep, testEsc)) do - print(k, v) -end diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua new file mode 100644 index 0000000000..5b68d41325 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-2.lua @@ -0,0 +1,11 @@ +function Tokenize(str, sep, esc) local R = {} + local repl = sep~="\0" and esc~="\0" and "\0" + or sep~="\1" and esc~="\1" and "\1" + or sep~="\2" and esc~="\2" and "\2" + local fakeStr = str:gsub("[%" .. esc .. "].", repl .. repl) + local pattern = "()[^%" .. sep .. "]*()" + for start, fin in fakeStr:gmatch(pattern) do + R[#R+1] = str:sub(start, fin-1) + end + return R +end diff --git a/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua new file mode 100644 index 0000000000..065824c58c --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Lua/tokenize-a-string-with-escaping-3.lua @@ -0,0 +1,4 @@ +local testStr = "one^|uno||three^^^^|four^^^|^cuatro|" +for k, v in ipairs(Tokenize(testStr, "|", "^")) do + print(k, v) +end diff --git a/Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel b/Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel new file mode 100644 index 0000000000..1f048cee22 --- /dev/null +++ b/Task/Tokenize-a-string/Excel/tokenize-a-string-1.excel @@ -0,0 +1 @@ +=TEXTSPLIT("Hello,How,Are,You,Today", ",") diff --git a/Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel b/Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel new file mode 100644 index 0000000000..ad4050073f --- /dev/null +++ b/Task/Tokenize-a-string/Excel/tokenize-a-string-2.excel @@ -0,0 +1 @@ +=TEXTSPLIT("Hello,How,Are,You,Today", , ",") diff --git a/Task/Tokenize-a-string/Zig/tokenize-a-string.zig b/Task/Tokenize-a-string/Zig/tokenize-a-string.zig index 9cdf0fcef6..63f90b8587 100644 --- a/Task/Tokenize-a-string/Zig/tokenize-a-string.zig +++ b/Task/Tokenize-a-string/Zig/tokenize-a-string.zig @@ -1,7 +1,7 @@ const std = @import("std"); pub fn main() void { const string = "Hello,How,Are,You,Today"; - var tokens = std.mem.split(u8, string, ","); + var tokens = std.mem.splitScalar(u8, string, ','); std.debug.print("{s}", .{tokens.next().?}); while (tokens.next()) |token| { std.debug.print(".{s}", .{token}); diff --git a/Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js b/Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js new file mode 100644 index 0000000000..86a4f90eec --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/JavaScript/tonelli-shanks-algorithm.js @@ -0,0 +1,113 @@ +class TonelliShanks { + static ts(n, p) { + // Convert to BigInt if not already + n = typeof n === 'bigint' ? n : BigInt(n); + p = typeof p === 'bigint' ? p : BigInt(p); + + const ZERO = BigInt(0); + const ONE = BigInt(1); + const TWO = BigInt(2); + + // Helper function for modular exponentiation + const powModP = (a, e) => { + let result = BigInt(1); + a = a % p; + while (e > ZERO) { + if (e % TWO === ONE) { + result = (result * a) % p; + } + e = e / TWO; + a = (a * a) % p; + } + return result; + }; + + // Legendre symbol calculation + const ls = (a) => powModP(a, (p - ONE) / TWO); + + if (ls(n) !== ONE) return { root1: ZERO, root2: ZERO, exists: false }; + + let q = p - ONE; + let ss = ZERO; + while (q % TWO === ZERO) { + ss += ONE; + q /= TWO; + } + + if (ss === ONE) { + const r1 = powModP(n, (p + ONE) / BigInt(4)); + return { root1: r1, root2: p - r1, exists: true }; + } + + let z = TWO; + while (ls(z) !== p - ONE) z += ONE; + + let c = powModP(z, q); + let r = powModP(n, (q + ONE) / TWO); + let t = powModP(n, q); + let m = ss; + + while (true) { + if (t === ONE) return { root1: r, root2: p - r, exists: true }; + + let i = ZERO; + let zz = t; + while (zz !== ONE && i < m - ONE) { + zz = (zz * zz) % p; + i += ONE; + } + + let b = c; + let e = m - i - ONE; + while (e > ZERO) { + b = (b * b) % p; + e -= ONE; + } + + r = (r * b) % p; + c = (b * b) % p; + t = (t * c) % p; + m = i; + } + } +} + +// Main function +function main() { + const pairs = [ + [10n, 13n], + [56n, 101n], + [1030n, 10009n], + [1032n, 10009n], + [44402n, 100049n], + [665820697n, 1000000009n], + [881398088036n, 1000000000039n] + ]; + + for (const [n, p] of pairs) { + const sol = TonelliShanks.ts(n, p); + console.log(`n = ${n}`); + console.log(`p = ${p}`); + if (sol.exists) { + console.log(`root1 = ${sol.root1}`); + console.log(`root2 = ${sol.root2}`); + } else { + console.log("No solution exists"); + } + console.log(); + } + + const bn = 41660815127637347468140745042827704103445750172002n; + const bp = BigInt(10) ** 50n + 577n; + const sol = TonelliShanks.ts(bn, bp); + console.log(`n = ${bn}`); + console.log(`p = ${bp}`); + if (sol.exists) { + console.log(`root1 = ${sol.root1}`); + console.log(`root2 = ${sol.root2}`); + } else { + console.log("No solution exists"); + } +} + +main(); diff --git a/Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs b/Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs new file mode 100644 index 0000000000..b35f2e502d --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Rust/tonelli-shanks-algorithm.rs @@ -0,0 +1,120 @@ +struct Pair { + n: u64, + p: u64, +} + +struct Solution { + root1: u64, + root2: u64, + is_square: bool, +} + +fn multiply_modulus(a: u64, b: u64, modulus: u64) -> u64 { + let mut a = a % modulus; + let mut b = b % modulus; + + if b < a { + std::mem::swap(&mut a, &mut b); + } + + let mut result = 0; + while a > 0 { + if a % 2 == 1 { + result = (result + b) % modulus; + } + b = (b << 1) % modulus; + a >>= 1; + } + result +} + +fn power_modulus(base: u64, exponent: u64, modulus: u64) -> u64 { + if modulus == 1 { + return 0; + } + + let mut base = base % modulus; + let mut result = 1; + let mut exponent = exponent; + + while exponent > 0 { + if (exponent & 1) == 1 { + result = multiply_modulus(result, base, modulus); + } + base = multiply_modulus(base, base, modulus); + exponent >>= 1; + } + result +} + +fn legendre(a: u64, p: u64) -> u64 { + power_modulus(a, (p - 1) / 2, p) +} + +fn tonelli_shanks(n: u64, p: u64) -> Solution { + if legendre(n, p) != 1 { + return Solution { root1: 0, root2: 0, is_square: false }; + } + + // Factor out powers of 2 from p - 1 + let mut q = p - 1; + let mut s = 0; + while q % 2 == 0 { + q /= 2; + s += 1; + } + + if s == 1 { + let result = power_modulus(n, (p + 1) / 4, p); + return Solution { root1: result, root2: p - result, is_square: true }; + } + + // Find a non-square z such as ( z | p ) = -1 + let mut z = 2; + while legendre(z, p) != p - 1 { + z += 1; + } + + let mut c = power_modulus(z, q, p); + let mut t = power_modulus(n, q, p); + let mut m = s; + let mut result = power_modulus(n, (q + 1) >> 1, p); + + while t != 1 { + let mut i = 1; + let mut z = multiply_modulus(t, t, p); + while z != 1 && i < m - 1 { + i += 1; + z = multiply_modulus(z, z, p); + } + let b = power_modulus(c, 1 << (m - i - 1), p); + c = multiply_modulus(b, b, p); + t = multiply_modulus(t, c, p); + m = i; + result = multiply_modulus(result, b, p); + } + + Solution { root1: result, root2: p - result, is_square: true } +} + +fn main() { + let tests = vec![ + Pair { n: 10, p: 13 }, + Pair { n: 56, p: 101 }, + Pair { n: 1030, p: 1009 }, + Pair { n: 1032, p: 1009 }, + Pair { n: 44402, p: 100049 }, + Pair { n: 665820697, p: 1000000009 }, + Pair { n: 881398088036, p: 1000000000039 }, + ]; + + for test in tests { + let solution = tonelli_shanks(test.n, test.p); + print!("n = {}, p = {}", test.n, test.p); + if solution.is_square { + println!(" has solutions: {} and {}\n", solution.root1, solution.root2); + } else { + println!(" has no solutions because n is not a square modulo p\n"); + } + } +} diff --git a/Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig b/Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig new file mode 100644 index 0000000000..61cb26bb3e --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Zig/tonelli-shanks-algorithm.zig @@ -0,0 +1,128 @@ +const std = @import("std"); +const stdout = std.io.getStdOut().writer(); + +const Pair = struct { + n: u64, + p: u64, +}; + +const Solution = struct { + root1: u64, + root2: u64, + is_square: bool, +}; + +fn multiplyModulus(a: u64, b: u64, modulus: u64) u64 { + var a_mod = a % modulus; + var b_mod = b % modulus; + + if (b_mod < a_mod) { + const temp = a_mod; + a_mod = b_mod; + b_mod = temp; + } + + var result: u64 = 0; + var a_temp = a_mod; + var b_temp = b_mod; + + while (a_temp > 0) { + if (a_temp % 2 == 1) { + result = (result + b_temp) % modulus; + } + b_temp = (b_temp << 1) % modulus; + a_temp >>= 1; + } + return result; +} + +fn powerModulus(base: u64, exponent: u64, modulus: u64) u64 { + if (modulus == 1) { + return 0; + } + + var base_mod = base % modulus; + var result: u64 = 1; + var exp = exponent; + + while (exp > 0) { + if ((exp & 1) == 1) { + result = multiplyModulus(result, base_mod, modulus); + } + base_mod = multiplyModulus(base_mod, base_mod, modulus); + exp >>= 1; + } + return result; +} + +fn legendre(a: u64, p: u64) u64 { + return powerModulus(a, (p - 1) / 2, p); +} + +fn tonelliShanks(n: u64, p: u64) Solution { + if (legendre(n, p) != 1) { + return Solution{ .root1 = 0, .root2 = 0, .is_square = false }; + } + + // Factor out powers of 2 from p - 1 + var q = p - 1; + var s: u64 = 0; + while (q % 2 == 0) { + q /= 2; + s += 1; + } + + if (s == 1) { + const result = powerModulus(n, (p + 1) / 4, p); + return Solution{ .root1 = result, .root2 = p - result, .is_square = true }; + } + + // Find a non-square z such as ( z | p ) = -1 + var z: u64 = 2; + while (legendre(z, p) != p - 1) { + z += 1; + } + + var c = powerModulus(z, q, p); + var t = powerModulus(n, q, p); + var m = s; + var result = powerModulus(n, (q + 1) >> 1, p); + + while (t != 1) { + var i: u64 = 1; + var z_temp = multiplyModulus(t, t, p); + while (z_temp != 1 and i < m - 1) { + i += 1; + z_temp = multiplyModulus(z_temp, z_temp, p); + } + const b = powerModulus(c, @as(u64, 1) << @as( u6, @intCast(m - i - 1)), p); + c = multiplyModulus(b, b, p); + t = multiplyModulus(t, c, p); + m = i; + result = multiplyModulus(result, b, p); + } + + return Solution{ .root1 = result, .root2 = p - result, .is_square = true }; +} + +pub fn main() !void { + const tests = [_]Pair{ + .{ .n = 10, .p = 13 }, + .{ .n = 56, .p = 101 }, + .{ .n = 1030, .p = 1009 }, + .{ .n = 1032, .p = 1009 }, + .{ .n = 44402, .p = 100049 }, + .{ .n = 665820697, .p = 1000000009 }, + .{ .n = 881398088036, .p = 1000000000039 }, + }; + + for (tests) |my_test| { + const solution = tonelliShanks(my_test.n, my_test.p); + try stdout.print("n = {}, p = {}", .{ my_test.n, my_test.p }); + if (solution.is_square) { + try stdout.print(" has solutions: {} and {}\n\n", .{ solution.root1, solution.root2 }); + } else { + try stdout.print(" has no solutions because n is not a square modulo p\n\n", .{}); + } + } +} diff --git a/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy b/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy index 9a39f89571..fba201626a 100644 --- a/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy +++ b/Task/Top-rank-per-group/EasyLang/top-rank-per-group.easy @@ -1,6 +1,6 @@ global na$[] id$[] sal[] dep$[] n . # -proc read . . +proc read . s$ = input repeat s$ = input @@ -15,7 +15,7 @@ proc read . . . read # -proc sort . . +proc sort . for i = 1 to n - 1 for j = i + 1 to n h = strcmp dep$[i] dep$[j] diff --git a/Task/Total-circles-area/EasyLang/total-circles-area.easy b/Task/Total-circles-area/EasyLang/total-circles-area.easy index 3dcb2fd239..e82e7c31eb 100644 --- a/Task/Total-circles-area/EasyLang/total-circles-area.easy +++ b/Task/Total-circles-area/EasyLang/total-circles-area.easy @@ -46,7 +46,7 @@ for try to ntry . . . -numfmt 4 0 +numfmt 0 4 print inside / ntry * (maxx - minx) * (maxy - miny) # input_data diff --git a/Task/Totient-function/EasyLang/totient-function.easy b/Task/Totient-function/EasyLang/totient-function.easy index 56f5cd9c90..67e9d7a02f 100644 --- a/Task/Totient-function/EasyLang/totient-function.easy +++ b/Task/Totient-function/EasyLang/totient-function.easy @@ -12,7 +12,7 @@ fastfunc totient n . if n > 1 : tot -= tot div n return tot . -numfmt 0 3 +numfmt 3 0 print " N Prim Phi" for n = 1 to 25 tot = totient n diff --git a/Task/Totient-function/REXX/totient-function-1.rexx b/Task/Totient-function/REXX/totient-function-1.rexx deleted file mode 100644 index ef3128a23e..0000000000 --- a/Task/Totient-function/REXX/totient-function-1.rexx +++ /dev/null @@ -1,24 +0,0 @@ -/*REXX program calculates the totient numbers for a range of numbers, and count primes. */ -parse arg N . /*obtain optional argument from the CL.*/ -if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/ -tell= N>0 /*N positive>? Then display them all. */ -N= abs(N) /*use the absolute value of N for loop.*/ -w= length(N) /*W: is used in aligning the output. */ -primes= 0 /*the number of primes found (so far).*/ - /*if N was negative, only count primes.*/ - do j=1 for N; T= phi(j) /*obtain totient number for a number. */ - prime= word('(prime)', 1 + (T \== j-1 ) ) /*determine if J is a prime number. */ - if prime\=='' then primes= primes + 1 /*if a prime, then bump the prime count*/ - if tell then say 'totient number for ' right(j, w) " ──► " right(T, w) ' ' prime - end /*j*/ -say -say right(primes, w) ' primes detected for numbers up to and including ' N -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gcd: parse arg x,y; do until y==0; parse value x//y y with y x - end /*until*/; return x -/*──────────────────────────────────────────────────────────────────────────────────────*/ -phi: procedure; parse arg z; if z==1 then return 1 - #= 1 - do m=2 for z-2; if gcd(m, z)==1 then #= # + 1 - end /*m*/; return # diff --git a/Task/Totient-function/REXX/totient-function-2.rexx b/Task/Totient-function/REXX/totient-function-2.rexx deleted file mode 100644 index 4f6e3d592b..0000000000 --- a/Task/Totient-function/REXX/totient-function-2.rexx +++ /dev/null @@ -1,25 +0,0 @@ -/*REXX program calculates the totient numbers for a range of numbers, and count primes. */ -parse arg N . /*obtain optional argument from the CL.*/ -if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/ -tell= N>0 /*N positive>? Then display them all. */ -N= abs(N) /*use the absolute value of N for loop.*/ -w= length(N) /*W: is used in aligning the output. */ -primes= 0 /*the number of primes found (so far).*/ - /*if N was negative, only count primes.*/ - do j=1 for N; T= phi(j) /*obtain totient number for a number. */ - prime= word('(prime)', 1 + (T \== j-1 ) ) /*determine if J is a prime number. */ - if prime\=='' then primes= primes + 1 /*if a prime, then bump the prime count*/ - if tell then say 'totient number for ' right(j, w) " ──► " right(T, w) ' ' prime - end /*j*/ -say -say right(primes, w) ' primes detected for numbers up to and including ' N -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -phi: procedure; parse arg z; if z==1 then return 1 - #= 1 - do m=2 for z-2; parse value m z with x y - do until y==0; parse value x//y y with y x - end /*until*/ - if x==1 then #= # + 1 - end /*m*/ - return # diff --git a/Task/Totient-function/REXX/totient-function-3.rexx b/Task/Totient-function/REXX/totient-function-3.rexx deleted file mode 100644 index 90f0aa7f2d..0000000000 --- a/Task/Totient-function/REXX/totient-function-3.rexx +++ /dev/null @@ -1,137 +0,0 @@ -include Settings - -say version; say 'Totient function (Phi)'; say -call Time('r') -numeric digits 10; cycl. = 0; m = 7 -call First25A -call PrimeCountA m -say Format(Time('e'),,3) 'seconds'; say -call Time('r') -call Totients 10**m -call First25B -call PrimeCountB m -say Format(Time('e'),,3) 'seconds' -exit - -First25A: -procedure -say 'A: using calls to an optimized Totient()'; say -say ' N Phi(N) Prime?' -say Copies('-',16) -n = 0 -do i = 1 to 25 - p = Totient(i) - if p = i-1 then do - n = n+1; pr = 'Yes' - end - else - pr = '' - say Right(i,2) Right(p,6) pr -end -say Copies('-',16); say -say 'Found' Right(n,6) 'primes <' Right(25,8) -return - -PrimeCountA: -procedure -arg x -n = 0; d = 1 -do i = 1 - p = Totient(i) - if p = i-1 then - n = n+1 - e = Xpon(i) - if e > d then do - say 'Found' Right(n,6) 'primes <' Right(10**e,8) - if e > x-1 then - leave i - d = e - end -end -say -return - -First25B: -procedure expose toti. -say 'B: generate and save all Totients, and use the stored values'; say -say ' N Phi(N) Prime?' -say Copies('-',16) -n = 0 -do i = 1 to 25 - p = toti.totient.i - if p = i-1 then do - n = n+1; pr = 'Yes' - end - else - pr = '' - say Right(i,2) Right(p,6) pr -end -say Copies('-',16) -say -say 'Found' Right(n,6) 'primes <' Right(25,8) -return - -PrimeCountB: -procedure expose toti. -arg x -n = 0; d = 1 -do i = 1 - p = toti.totient.i - if p = i-1 then - n = n+1 - e = Xpon(i) - if e > d then do - say 'Found' Right(n,6) 'primes <' Right(10**e,8) - if e > x-1 then - leave i - d = e - end -end -say -return - -Totient: -/* Euler's totient function */ -procedure expose toti. -arg x -/* Fast values */ -if x < 3 then - return 1 -if x < 5 then - return 2 -/* Multiplicative property using Factors */ -f = Factors(x)+1; fact.factor.f = 0 -y = 1; v = fact.factor.1; n = 1 -do i = 2 to f - a = fact.factor.i - if a = v then - n = n+1 - else do - y = y*v**(n-1)*(v-1) - v = a; n = 1 - end -end -return y - -Totients: -/* Euler's totient numbers */ -procedure expose toti. -arg x -/* Recurring sequence */ -do i = 1 to x - toti.totient.i = i -end -do i = 2 to x - if toti.totient.i < i then - iterate i - do j = i by i to x - toti.totient.j = toti.totient.j-toti.totient.j/i - end -end -toti.0 = x -return x - -include Functions -include Numbers -include Sequences -include Abend diff --git a/Task/Totient-function/REXX/totient-function.rexx b/Task/Totient-function/REXX/totient-function.rexx new file mode 100644 index 0000000000..fc0246dae9 --- /dev/null +++ b/Task/Totient-function/REXX/totient-function.rexx @@ -0,0 +1,99 @@ +-- 8 May 2025 +include Settings + +say 'TOTIENT FUNCTION (PHI)' +say version +numeric digits 10; m = 6 +call First25A +call PrimeCountA m +say Format(Time('e'),,3) 'seconds'; say +call Time('r') +call First25B m +call PrimeCountB m +say Format(Time('e'),,3) 'seconds' +exit + +First25A: +procedure +say 'A: using calls to function Totient()'; say +say ' N Phi(N) Prime?' +say Copies('-',16) +n = 0 +do i = 1 to 25 + p = Totient(i) + if p = i-1 then do + n = n+1; pr = 'Yes' + end + else + pr = '' + say Right(i,2) Right(p,6) pr +end +say Copies('-',16); say +say 'Found' Right(n,6) 'PrimeS <' Right(25,8) +return + +PrimeCountA: +procedure +arg x +n = 0; d = 1 +do i = 1 + p = Totient(i) + if p = i-1 then + n = n+1 + e = Xpon(i) + if e > d then do + say 'Found' Right(n,6) 'PrimeS <' Right(10**e,8) + if e > x-1 then + leave i + d = e + end +end +say +return + +First25B: +procedure expose toti. +arg m +say 'B: generate and save all TotientS, use the stored values'; say +call TotientS 10**m +say ' N Phi(N) Prime?' +say Copies('-',16) +n = 0 +do i = 1 to 25 + p = toti.i + if p = i-1 then do + n = n+1; pr = 'Yes' + end + else + pr = '' + say Right(i,2) Right(p,6) pr +end +say Copies('-',16) +say +say 'Found' Right(n,6) 'PrimeS <' Right(25,8) +return + +PrimeCountB: +procedure expose toti. +arg x +n = 0; d = 1 +do i = 1 + p = toti.i + if p = i-1 then + n = n+1 + e = Xpon(i) + if e > d then do + say 'Found' Right(n,6) 'PrimeS <' Right(10**e,8) + if e > x-1 then + leave i + d = e + end +end +say +return + +include Functions +include Special +include Numbers +include Sequences +include Abend diff --git a/Task/Towers-of-Hanoi/Applesoft-BASIC/towers-of-hanoi.basic b/Task/Towers-of-Hanoi/Applesoft-BASIC/towers-of-hanoi.basic new file mode 100644 index 0000000000..5c57b6288a --- /dev/null +++ b/Task/Towers-of-Hanoi/Applesoft-BASIC/towers-of-hanoi.basic @@ -0,0 +1,27 @@ + 100 DATA4,": "," TO " + 110 DEF FN M(X) = X - INT (X / 3) * 3 + 1 + 120 READ N,T$(0),T$(1) + 130 LET M$(1) = CHR$ (13) + 140 FOR M = 1 TO 2 ^ N - 1 + 150 FOR O = 0 TO 1 + 160 GOSUB 200"ANDOR + 170 PRINT MID$ ( STR$ (M),1,( NOT O) * 255)T$(O) FN M(R + O)M$(O); + 180 NEXT O,M + 190 END + + REM BITWISE M WITH M-1, RESULT IN R + REM AND WHEN O = 0 + REM OR WHEN NOT O + 200 LET R = 0 + 210 LET B1 = M + 220 LET B2 = M - 1 + 230 FOR I = 0 TO 1E9 + 240 LET M1 = B1 - INT (B1 / 2) * 2 + 250 LET M2 = B2 - INT (B2 / 2) * 2 + 260 LET MR = M1 AND M2 + 270 IF O THEN MR = M1 OR M2 + 280 LET R = R + MR * (2 ^ I) + 290 LET B1 = INT (B1 / 2) + 300 LET B2 = INT (B2 / 2) + 310 IF B1 OR B2 THEN NEXT I + 320 RETURN diff --git a/Task/Towers-of-Hanoi/Ballerina/towers-of-hanoi.ballerina b/Task/Towers-of-Hanoi/Ballerina/towers-of-hanoi.ballerina new file mode 100644 index 0000000000..813ca35432 --- /dev/null +++ b/Task/Towers-of-Hanoi/Ballerina/towers-of-hanoi.ballerina @@ -0,0 +1,26 @@ +import ballerina/io; + +class Hanoi { + private int moves; + + function init(int disks) { + self.moves = 0; + io:println("Towers of Hanoi with ", disks, " disks:\n"); + self.move(disks, "L", "C", "R"); + io:println("\nCompleted in ", self.moves, " moves\n"); + } + + private function move(int n, string frm, string to, string via) { + if n > 0 { + self.move(n - 1, frm, via, to); + self.moves += 1; + io:println("Move disk ", n, " from ", frm, " to ", to); + self.move(n - 1, via, to, frm); + } + } +} + +public function main() { + _ = new Hanoi(3); + _ = new Hanoi(4); +} diff --git a/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy b/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy index 80116bb093..821008469b 100644 --- a/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy +++ b/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy @@ -1,8 +1,8 @@ -proc hanoi n src dst aux . . +proc hanoi n src dst aux . if n >= 1 hanoi n - 1 src aux dst print "Move " & src & " to " & dst hanoi n - 1 aux dst src . . -hanoi 5 1 2 3 +hanoi 4 1 2 3 diff --git a/Task/Towers-of-Hanoi/Excel/towers-of-hanoi-3.excel b/Task/Towers-of-Hanoi/Excel/towers-of-hanoi-3.excel new file mode 100644 index 0000000000..096d5b74b6 --- /dev/null +++ b/Task/Towers-of-Hanoi/Excel/towers-of-hanoi-3.excel @@ -0,0 +1,11 @@ +=LET( + TOH, LAMBDA(TOH, n, from, to, aux, + IF(n=0, "", VSTACK( + TOH(TOH, n-1, from, aux, to), + "Move disk " & n & " from " & from & " to " & to, + TOH(TOH, n-1, aux, to, from) + )) + ), + ans, TOH(TOH, A2, "A", "C", "B"), + FILTER(ans, LEN(ans)) + ) diff --git a/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl b/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl index 4ea818bcc2..6d3ca4f5c0 100644 --- a/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl +++ b/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl @@ -1,10 +1,15 @@ -|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 +%newline { [ LIT2 0a -Console/write ] DEO } -|0100 ( -> ) - #0102 [ LIT2 03 &count 04 ] hanoi - POP2 POP2 BRK +|18 @Console/write -@hanoi ( from spare to count -: from spare to count ) +|0100 + +#0102 #0304 hanoi +POP2 POP2 + +BRK + +@hanoi ( from spare to count -- from spare to count ) ( moving 0 disks is no-op ) DUP ?{ JMP2r } @@ -13,14 +18,14 @@ ( from to spare count-1 ) ( print the current move ) - ;dict/move print-str + ;dict/move print/str INCk #30 ORA .Console/write DEO STH2 - ;dict/from print-str + ;dict/from print/str OVR #30 ORA .Console/write DEO - ;dict/to print-str + ;dict/to print/str DUP #30 ORA .Console/write DEO - [ LIT2 0a -Console/write ] DEO + newline STH2r ( move disks 1..count-1 from the spare peg to the goal peg ) @@ -31,10 +36,9 @@ JMP2r -@print-str - &loop - LDAk .Console/write DEO - INC2 LDAk ?&loop +@print/str ( str* -- ) + LDAk .Console/write DEO + INC2 LDAk ?/str POP2 JMP2r @dict diff --git a/Task/Tree-traversal/EasyLang/tree-traversal.easy b/Task/Tree-traversal/EasyLang/tree-traversal.easy index 4495de81f5..91043289f2 100644 --- a/Task/Tree-traversal/EasyLang/tree-traversal.easy +++ b/Task/Tree-traversal/EasyLang/tree-traversal.easy @@ -1,9 +1,7 @@ tree[] = [ 1 2 3 4 5 6 -1 7 -1 -1 -1 8 9 ] # -proc preorder ind . . - if ind > len tree[] or tree[ind] = -1 - return - . +proc preorder ind . + if ind > len tree[] or tree[ind] = -1 : return write " " & tree[ind] preorder ind * 2 preorder ind * 2 + 1 @@ -12,10 +10,8 @@ write "preorder:" preorder 1 print "" # -proc inorder ind . . - if ind > len tree[] or tree[ind] = -1 - return - . +proc inorder ind . + if ind > len tree[] or tree[ind] = -1 : return inorder ind * 2 write " " & tree[ind] inorder ind * 2 + 1 @@ -24,10 +20,8 @@ write "inorder:" inorder 1 print "" # -proc postorder ind . . - if ind > len tree[] or tree[ind] = -1 - return - . +proc postorder ind . + if ind > len tree[] or tree[ind] = -1 : return postorder ind * 2 postorder ind * 2 + 1 write " " & tree[ind] @@ -37,25 +31,23 @@ postorder 1 print "" # global tail head queue[] . -proc initqu n . . +proc initqu n . len queue[] n tail = 1 head = 1 . -proc enqu v . . +proc enqu v . queue[tail] = v tail = (tail + 1) mod1 len queue[] . func dequ . - if head = tail - return -1 - . + if head = tail : return -1 h = head head = (head + 1) mod1 len queue[] return queue[h] . initqu len tree[] -proc levelorder n . . +proc levelorder n . enqu n repeat ind = dequ diff --git a/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy b/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy index 39f5395c7a..237db0c2a0 100644 --- a/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy +++ b/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy @@ -8,7 +8,7 @@ func d2r d . return d * pi / 180 . # -numfmt 4 0 +numfmt 0 4 print sin d & " " & sin r2d r print cos d & " " & cos r2d r print tan d & " " & tan r2d r diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx deleted file mode 100644 index 578b9ea17d..0000000000 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx +++ /dev/null @@ -1,81 +0,0 @@ -/*REXX program demonstrates some common trig functions (30 decimal digits are shown).*/ -showdigs= 25 /*show only 25 digits of number. */ -numeric digits showdigs + 10 /*DIGITS default is 9, but use */ - /*extra digs to prevent rounding.*/ -say 'Using' showdigs 'decimal digits precision.' /*show # decimal digs being used.*/ -say - do j=-180 to +180 by 15 /*let's just do a half─Monty. */ - stuff = right(j, 4) 'degrees, rads=' show( d2r(j) ) , - ' sin=' show( sinD(j) ) , - ' cos=' show( cosD(J) ) - /*don't let TANGENT go postal. */ - if abs(j)\==90 then stuff=stuff ' tan=' show( tanD(j) ) - say stuff - end /*j*/ -say - do k=-1 to +1 by 1/2 /*keep the Arc─functions happy. */ - say right(k, 4) 'radians, degs=' show( r2d(k) ) , - ' Acos=' show( Acos(k) ) , - ' Asin=' show( Asin(k) ) , - ' Atan=' show( Atan(k) ) - end /*k*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a - if a>1 then call AsinErr x /*X argument is out of range. */ - if a >= sqrt(2) * .5 then return sign(x) * acos( sqrt(1 - aa), '-ASIN') - do j=2 by 2 until p=z; p=z; o= o * aa * (j-1) / j; z= z +o / (j+1); end - return z /* [↑] compute until no noise. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr; return pi()*.5 - Asin(x) -AcosD: return r2d( Acos( arg(1) ) ) -AsinD: return r2d( Asin( arg(1) ) ) -cosD: return cos( d2r( arg(1) ) ) -sinD: return sin( d2r( d2d( arg(1) ) ) ) -tan: procedure; parse arg x; _= cos(x); if _=0 then call tanErr; return sin(x) / _ -tanD: return tan( d2r( arg(1) ) ) -d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle*/ -d2r: return r2r( d2d( arg(1) )*pi() / 180) /*convert degrees ──► radians. */ -r2d: return d2d( ( arg(1) * 180 / pi() ) ) /*convert radians ──► degrees. */ -r2r: return arg(1) // (pi() *2) /*normalize radians ──► a unit circle*/ -show: return left( left('', arg(1) >= 0)format( arg(1), , showdigs) / 1, showdigs) -tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 -tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x -AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' || x -AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' || x -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Atan: procedure; parse arg x; if abs(x)=1 then return pi() * .25 * sign(x) - return Asin(x / sqrt(1 + x*x) ) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure; parse arg x; x= r2r(x); if x=0 then return 1; a= abs(x) - numeric fuzz min(6, digits() - 3); if a=pi then return -1; pih= pi * .5 - if a=pih | a=pih*3 then return 0; pit= pi/3; if a=pit then return .5 - if a=pit + pit then return -.5; return .sinCos(1, -1) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sin: procedure; arg x;x=r2r(x);if x=0 then return 0;numeric fuzz min(5,max(1,digits()-3)) - if x=pi*.5 then return 1; if x==pi * 1.5 then return -1 - if abs(x)=pi then return 0; return .sinCos(x,1) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.sinCos: parse arg z 1 _,i; q= x*x - do k=2 by 2 until p=z; p= z; _= - _ * q / (k * (k+i) ); z= z + _; end - return z -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9; h= d+6 - numeric digits; numeric form; if x<0 then do; x= -x; i= 'i'; end - parse value format(x, 2, 1, , 0) 'E0' with g 'E' _ .; g= g *.5'e'_ % 2 - do j=0 while h>9; m.j=h; h= h % 2 + 1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g) * .5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 - return e /*Note: the actual E subroutine returns E's accuracy that */ - /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix=x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x=x - ix - z=1; _=1; w=z; do j=1; _= _*x/j; z= (z+_) / 1; if z==w then leave; w=z; end - if z\==0 then z= e()**ix * z; return z -/*──────────────────────────────────────────────────────────────────────────────────────*/ -pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 - return pi /*Note: the actual PI subroutine returns PI's accuracy that */ - /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ - /*John Machin's formula is used for calculating more digits. */ diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx similarity index 93% rename from Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx rename to Task/Trigonometric-functions/REXX/trigonometric-functions.rexx index 98903eb4fc..1b71fa05ce 100644 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx @@ -1,6 +1,8 @@ include Settings -say version; say 'Trigonometric functions'; say +say 'TRIGONOMETRIC FUNCTIONS - 2 Mar 2025' +say version +say s = Copies('-',77); w = 18 call Trigo call Arcus1 diff --git a/Task/Truncatable-primes/Ballerina/truncatable-primes.ballerina b/Task/Truncatable-primes/Ballerina/truncatable-primes.ballerina new file mode 100644 index 0000000000..9c033e65b2 --- /dev/null +++ b/Task/Truncatable-primes/Ballerina/truncatable-primes.ballerina @@ -0,0 +1,90 @@ +import ballerina/io; + +function getPrimes(int n) returns int[] { + if n < 2 { return []; } + if n == 2 { return [2]; } + int k = (n - 3) / 2 + 1; + boolean[] marked = []; + marked.setLength(k); + foreach int i in 0..n).sqrt().floor(); + int lim = (f - 3) / 2 + 1; + foreach int i in 0..= 0 { return s; } + return "-" + s; +} + +public function main() returns error? { + final int lim = 999999; + boolean[] c = areComposite(lim); + boolean leftFound = false; + boolean rightFound = false; + io:println("Largest truncatable primes less than a million:"); + int i = lim; + while i > 2 { + if !c[i] { + if !rightFound { + int p = i / 10; + while p > 0 { + if p % 2 == 0 || c[p] { break; } + p = p / 10; + } + if p == 0 { + io:println(" Right truncatable prime = ", commatize(i)); + rightFound = true; + if leftFound { return; } + } + } + if !leftFound { + string q = i.toString().substring(1); + if !q.includes("0") { + int p = check int:fromString(q); + while q.length() > 0 { + if p % 2 == 0 || c[p] { break; } + q = q.substring(1); + p = q.length() > 0 ? check int:fromString(q) : 0; + } + if q == "" { + io:println(" Left truncatable prime = ", commatize(i)); + leftFound = true; + if rightFound { return; } + } + } + } + } + i -= 2; + } +} diff --git a/Task/Truncatable-primes/REXX/truncatable-primes.rexx b/Task/Truncatable-primes/REXX/truncatable-primes-1.rexx similarity index 100% rename from Task/Truncatable-primes/REXX/truncatable-primes.rexx rename to Task/Truncatable-primes/REXX/truncatable-primes-1.rexx diff --git a/Task/Truncatable-primes/REXX/truncatable-primes-2.rexx b/Task/Truncatable-primes/REXX/truncatable-primes-2.rexx new file mode 100644 index 0000000000..20875f0baa --- /dev/null +++ b/Task/Truncatable-primes/REXX/truncatable-primes-2.rexx @@ -0,0 +1,50 @@ +-- 25 Apr 2025 +include Settings +arg xx +say 'TRUNCATABLE PRIMES' +say version +say +call Collect +call Task +call Timer +exit + +Collect: +procedure expose prim. flag. +say 'Primes below 1 million...' +say Primes(1E6) 'found' +say +return + +Task: +procedure expose prim. flag. +say 'Largest left and right truncatable prime below 1 million...' +l1 = 0; r1 = 0 +do i = prim.0 by -1 until l1 > 0 & l2 > 0 + p = prim.i + if Pos(0,p) > 0 then + iterate i + l2 = 1; r2 = 1 + do j = 1 to Length(p)-1 + a = Left(p,j); b = Right(p,j) + if \ flag.a then + l2 = 0 + if \ flag.b then + r2 = 0 + end + if l1 = 0 & l2 then + l1 = p + if r1 = 0 & r2 then + r1 = p +end +say 'Left' l1 +say 'Right' r1 +say +return + +include Sequences +include Helper +include Numbers +include Functions +include Constants +include Abend diff --git a/Task/Twin-primes/REXX/twin-primes-1.rexx b/Task/Twin-primes/REXX/twin-primes-1.rexx deleted file mode 100644 index b78df4d079..0000000000 --- a/Task/Twin-primes/REXX/twin-primes-1.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX pgm counts the number of twin prime pairs under a specified number N (or a list).*/ -parse arg $ . /*get optional number of primes to find*/ -if $='' | $="," then $= 10 100 1000 10000 100000 1000000 10000000 /*No $? Use default.*/ -w= length( commas( word($, words($) ) ) ) /*get length of the last number in list*/ -@found= ' twin prime pairs found under ' /*literal used in the showing of output*/ - - do i=1 for words($); x= word($, i) /*process each N─limit in the $ list.*/ - say right( commas(genP(x)), 20) @found right(commas(x), max(length(x), w) ) - end /*i*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: parse arg y; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; #= 6; tp= 2; sq.6= 169 - if y>10 then tp= tp+1 - do j=@.#+2 by 2 for max(0, y%2-@.#%2-1) /*find odd primes from here on. */ - parse var j '' -1 _ /*obtain the last digit of the J var.*/ - if _==5 then iterate; if j// 3==0 then iterate /*J ÷ by 5? J ÷ by 3? */ - if j//7==0 then iterate; if j//11==0 then iterate /*" " " 7? " " " 11? */ - /* [↓] divide by the primes. ___ */ - do k=6 to # while sq.k<=j /*divide J by other primes ≤ √ J */ - if j//@.k == 0 then iterate j /*÷ by prev. prime? ¬prime ___ */ - end /*k*/ /* [↑] only divide up to √ J */ - prev= @.#; #= #+1; sq.#= j*j; @.#= j /*save prev. P; bump # primes; assign P*/ - if j-2==prev then tp= tp + 1 /*This & previous prime twins? Bump TP.*/ - end /*j*/; return tp diff --git a/Task/Twin-primes/REXX/twin-primes-2.rexx b/Task/Twin-primes/REXX/twin-primes-2.rexx deleted file mode 100644 index 82324b213a..0000000000 --- a/Task/Twin-primes/REXX/twin-primes-2.rexx +++ /dev/null @@ -1,33 +0,0 @@ -/*REXX pgm counts the number of twin prime pairs under a specified number N (or a list).*/ -parse arg $ . /*get optional number of primes to find*/ -if $='' | $="," then $= 100 1000 10000 100000 1000000 10000000 /*No $? Use default.*/ -w= length( commas( word($, words($) ) ) ) /*get length of the last number in list*/ -@found= ' twin prime pairs found under ' /*literal used in the showing of output*/ - - do i=1 for words($); x= word($, i) /*process each N─limit in the $ list.*/ - say right( commas(genP(x)), 20) @found right(commas(x), max(length(x), w) ) - end /*i*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: arg y; _= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 - tp=8; #= words(_); sq.103=103*103 /*#: number of prims; TP: # twin pairs.*/ - do aa=1 for #; @.aa= word(_, aa) /*assign some low primes for quick ÷'s.*/ - end /*aa*/ - - do j=@.#+2 by 2 while j p then do + say n 'twin primes below' p + p = p*10 + end + j = i+1; b = prim.j + if b-a = 2 then + n = n+1 +end +say +return + +include Sequences +include Functions +include Abend diff --git a/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy b/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy index 7a271b0f1e..b1da314e3a 100644 --- a/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy +++ b/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy @@ -1,28 +1,20 @@ len cyl[] 6 -proc rshift . . +proc rshift . h = cyl[6] - for i = 6 downto 2 - cyl[i] = cyl[i - 1] - . + for i = 6 downto 2 : cyl[i] = cyl[i - 1] cyl[1] = h . -proc unload . . - for i = 1 to 6 - cyl[i] = 0 - . +proc unload . + for i = 1 to 6 : cyl[i] = 0 . -proc load . . - while cyl[1] = 1 - rshift - . +proc load . + while cyl[1] = 1 : rshift cyl[1] = 1 rshift . -proc spin . . +proc spin . lim = random 6 - for i = 1 to lim - 1 - rshift - . + for i = 1 to lim - 1 : rshift . func fire . shot = cyl[1] @@ -37,15 +29,13 @@ func method m[] . elif m = 2 spin elif m = 3 - if fire = 1 - return 1 - . + if fire = 1 : return 1 . . return 0 . method$[] = [ "load" "spin" "fire" ] -proc test m[] . . +proc test m[] . n = 100000 for i = 1 to n sum += method m[] diff --git a/Task/Two-bullet-roulette/Quackery/two-bullet-roulette.quackery b/Task/Two-bullet-roulette/Quackery/two-bullet-roulette.quackery new file mode 100644 index 0000000000..6273777041 --- /dev/null +++ b/Task/Two-bullet-roulette/Quackery/two-bullet-roulette.quackery @@ -0,0 +1,35 @@ +[ $ "bigrat.qky" loadfile ] now! + +[ 0 6 of ] is empty ( --> [ ) + +[ stack 0 ] is chamber ( --> s ) + +[ chamber take 1+ 6 mod + chamber put ] is rotate1 ( --> ) + +[ 1 swap chamber share poke + rotate1 ] is /load ( [ --> [ ) + +[ dup chamber share peek + if rotate1 /load ] is load ( [ --> [ ) + +[ 6 random chamber replace ] is spin ( --> ) + +[ dup dip + [ chamber share peek ] + rotate1 ] is fire ( [ --> n [ ) + +[ ' empty swap join + ' [ drop or ] join ] is makesim ( [ --> [ ) + +[ 0 ]'[ dup echo sp makesim + 10000 times + [ dup do swap dip + ] drop + 100 4 point$ echo$ char % + emit sp say "deaths" cr ] is sim ( --> ) + +randomise +sim [ load spin load spin fire spin fire ] +sim [ load spin load spin fire fire ] +sim [ load load spin fire spin fire ] +sim [ load load spin fire fire ] diff --git a/Task/UPC/EasyLang/upc.easy b/Task/UPC/EasyLang/upc.easy index 4d770fcc72..30478cdc81 100644 --- a/Task/UPC/EasyLang/upc.easy +++ b/Task/UPC/EasyLang/upc.easy @@ -1,4 +1,4 @@ -proc trim . s$ . +proc trim &s$ . a = 1 while substr s$ a 1 = " " : a += 1 b = len s$ @@ -25,7 +25,7 @@ func$ invert s$ . digs$[] = [ " ## #" " ## #" " # ##" " #### #" " # ##" " ## #" " # ####" " ### ##" " ## ###" " # ##" ] func[] decode_upc upc$ . subr getdigs - for _ to 6 + for i to 6 h$ = substr upc$ pos 7 for dig to 10 d$ = digs$[dig] diff --git a/Task/UTF-8-encode-and-decode/K/utf-8-encode-and-decode.k b/Task/UTF-8-encode-and-decode/K/utf-8-encode-and-decode.k new file mode 100644 index 0000000000..ece0858c66 --- /dev/null +++ b/Task/UTF-8-encode-and-decode/K/utf-8-encode-and-decode.k @@ -0,0 +1,4 @@ +dec:{64/(0;64 128;32 128 128;16 128 128 128)[-1+#x]+x} +enc:{`c$(0;-64 -128;-32 -128 -128;-16 -128 -128 -128)[b]+(128,(b:1+128 2048 65536'x)#64)\x} +v:(,"A";"ö";"Ж";"€";"𝄞") +`0:" -> "/'(::;$:;::)@'/:+(v; dec'v; enc'dec'v) diff --git a/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic new file mode 100644 index 0000000000..b42d4a94fe --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-1.basic @@ -0,0 +1,151 @@ +Type SuffixType + index As Integer + suffix As String +End Type + +Type SubstringInfo + substring As String + positions As String +End Type + +Type AllSubstringsInfo + substrings(100) As SubstringInfo + count As Integer + max_length As Integer +End Type + +Function LongestCommonPrefix(s1 As String, s2 As String) As Integer + Dim As Integer minLen, i + minLen = Iif(Len(s1) < Len(s2), Len(s1), Len(s2)) + + For i = 1 To minLen + If Mid(s1, i, 1) <> Mid(s2, i, 1) Then Return i - 1 + Next + + Return minLen +End Function + +Sub FindLongestRepeatedSubstrings(text As String, Byref result As AllSubstringsInfo) + Dim As Integer i, j, k + result.count = 0 + result.max_length = 0 + + If Len(text) < 2 Then Exit Sub + + Dim As SuffixType suffixes() + Redim suffixes(0 To Len(text) - 1) + For i = 0 To Len(text) - 1 + suffixes(i).index = i + suffixes(i).suffix = Mid(text, i + 1) + Next + + ' Sort suffixes (Bubble, inefficient but simple) + For i = 0 To Len(text) - 2 + For j = i + 1 To Len(text) - 1 + If suffixes(i).suffix > suffixes(j).suffix Then + Swap suffixes(i), suffixes(j) + End If + Next + Next + + ' Find the longest repeated substring + Dim As Integer maxLength = 0 + For i = 0 To Len(text) - 2 + Dim As Integer prefixLen = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen > maxLength Then maxLength = prefixLen + Next + + If maxLength = 0 Then Exit Sub + + result.max_length = maxLength + + For i = 0 To Len(text) - 2 + Dim As Integer prefixLen = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen = maxLength Then + Dim As String substring = Left(suffixes(i).suffix, maxLength) + + Dim As Boolean found = False + For j = 0 To result.count - 1 + If result.substrings(j).substring = substring Then + found = True + Exit For + End If + Next + + If Not found Then + Dim As String positions = "" + Dim As Integer posCount = 0 + Dim As Integer posArray(100) + + For j = 0 To Len(text) - 1 + If Left(suffixes(j).suffix, maxLength) = substring Then + posArray(posCount) = suffixes(j).index - 2 + posCount += 1 + End If + Next + + ' Sort positions (Bubble, inefficient but simple) + For j = 0 To posCount - 2 + For k = j + 1 To posCount - 1 + If posArray(j) > posArray(k) Then + Swap posArray(j), posArray(k) + End If + Next + Next + + For j = 0 To posCount - 1 + If j > 0 Then positions &= " " + positions &= Str(posArray(j)) + Next + + result.substrings(result.count).substring = substring + result.substrings(result.count).positions = positions + result.count += 1 + End If + End If + Next +End Sub + +Sub main() + Dim As Integer limits(0 To 2) = {1000, 10000, 100000} + Dim As Integer ff, i, j, limit + Dim As String contents, pi_digits + + ff = Freefile + If Open("piDigits.txt" For Input As #ff) = 0 Then + contents = Input(Lof(ff), ff) + Close #ff + Else + Print "Error: Could not open piDigits.txt" + Exit Sub + End If + + For i = 0 To 2 + limit = limits(i) + pi_digits = Left(contents, limit) + + DimAs Double t0 = Timer + + Dim As AllSubstringsInfo results + FindLongestRepeatedSubstrings(pi_digits, results) + + Dim As Double elapsed = Timer - t0 + + Print "First "; limit; " digits of pi has longest repeated substrings:" + If results.count > 0 Then + For j = 0 To results.count - 1 + Print " '" & results.substrings(j).substring & "' starting at indices " & results.substrings(j).positions + Next + Else + Print " No repeated substrings found." + End If + + Print Using !"Time taken: ###.### seconds\n"; elapsed + Next + + Print "The timings show that the implementation has approximately linear performance." +End Sub + +main() + +Sleep diff --git a/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic new file mode 100644 index 0000000000..7031cea706 --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/FreeBASIC/ukkonen-s-suffix-tree-construction-2.basic @@ -0,0 +1,295 @@ +Type SuffixType + index As Integer + suffix As String +End Type + +Type SubstringInfo + substring As String + positions As String +End Type + +Type AllSubstringsInfo + substrings(100) As SubstringInfo + count As Integer + max_length As Integer +End Type + +Function LongestCommonPrefix(s1 As String, s2 As String) As Integer + Dim minLen As Integer = Iif(Len(s1) < Len(s2), Len(s1), Len(s2)) + + For i As Integer = 1 To minLen + If Mid(s1, i, 1) <> Mid(s2, i, 1) Then Return i - 1 + Next + + Return minLen +End Function + +Sub FindLongestRepeatedSubstringsOptimized(text As String, Byref result As AllSubstringsInfo) + Dim As Integer i, j, k + + result.count = 0 + result.max_length = 0 + + ' For large data sets, we use a sliding window approach with a hash table + ' to search for matches. + Dim As Integer maxWindowSize = 100 ' Maximum window size to search + + ' Start with a large window and gradually reduce it. + For windowSize As Integer = maxWindowSize To 5 Step -1 + Dim hashTable(0 To 9999) As String ' Simple hash table + + ' Clear hash table + For i = 0 To 9999 + hashTable(i) = "" + Next + + ' Search for substrings of length windowSize + For i = 0 To Len(text) - windowSize + Dim substring As String = Mid(text, i + 1, windowSize) + + ' Calculate a simple hash + Dim hash As Integer = 0 + For j = 1 To Len(substring) + hash = (hash * 31 + Asc(Mid(substring, j, 1))) Mod 10000 + Next + + ' Check for collisions in the hash table + If hashTable(hash) <> "" Then + ' Possible match, check + Dim entries() As String + Dim entryCount As Integer + + ' Manually split the string by commas + Dim currentEntry As String = "" + For j = 1 To Len(hashTable(hash)) + Dim c As String = Mid(hashTable(hash), j, 1) + If c = "," Then + If currentEntry <> "" Then + Redim Preserve entries(0 To entryCount) + entries(entryCount) = currentEntry + entryCount += 1 + currentEntry = "" + End If + Else + currentEntry &= c + End If + Next + + ' Don't forget the last entry + If currentEntry <> "" Then + Redim Preserve entries(0 To entryCount) + entries(entryCount) = currentEntry + entryCount += 1 + End If + + For j = 0 To entryCount - 1 + Dim entry As String = entries(j) + If entry = "" Then Continue For + + Dim entryPos As Integer = Val(entry) + Dim entrySubstring As String = Mid(text, entryPos + 1, windowSize) + + If entrySubstring = substring Then + ' We found a match! + result.max_length = windowSize + + ' Verificar si ya tenemos esta subcadena + Dim found As Boolean = False + For k = 0 To result.count - 1 + If result.substrings(k).substring = substring Then + found = True + Exit For + End If + Next + + If Not found Then + ' Collect all positions + Dim positions As String = "" + Dim posArray(0 To 1000) As Integer + Dim posCount As Integer = 0 + + ' Add current position + posArray(posCount) = i - 2 + posCount += 1 + + ' Add the found position + posArray(posCount) = entryPos - 2 + posCount += 1 + + ' Search for more occurrences + For k = 0 To Len(text) - windowSize + If k <> i And k <> entryPos And Mid(text, k + 1, windowSize) = substring Then + posArray(posCount) = k - 2 + posCount += 1 + End If + Next + + ' Sort positions (Bubble, inefficient but simple) + For k = 0 To posCount - 2 + For l As Integer = k + 1 To posCount - 1 + If posArray(k) > posArray(l) Then + Swap posArray(k), posArray(l) + End If + Next + Next + + For k = 0 To posCount - 1 + If k > 0 Then positions &= " " + positions &= Str(posArray(k)) + Next + + result.substrings(result.count).substring = substring + result.substrings(result.count).positions = positions + result.count += 1 + End If + + ' If we find enough results, exit + If result.count >= 10 Then Exit For + End If + Next + End If + + ' Add this position to the hash table + If hashTable(hash) = "" Then + hashTable(hash) = Str(i) + Else + hashTable(hash) &= "," & Str(i) + End If + Next + + ' If we find any repeated substring, exit + If result.count > 0 Then Exit For + Next +End Sub + +Sub FindLongestRepeatedSubstrings(text As String, Byref result As AllSubstringsInfo) + Dim As Integer i, j, k + + ' Use the algorithm optimized for large data sets + If Len(text) > 20000 Then + FindLongestRepeatedSubstringsOptimized(text, result) + Exit Sub + End If + + result.count = 0 + result.max_length = 0 + + Dim suffixes(0 To Len(text) - 1) As SuffixType + + For i = 0 To Len(text) - 1 + suffixes(i).index = i + suffixes(i).suffix = Mid(text, i + 1) + Next + + ' Sort suffixes (Bubble, inefficient but simple) + For i = 0 To Len(text) - 2 + For j = i + 1 To Len(text) - 1 + If suffixes(i).suffix > suffixes(j).suffix Then + Swap suffixes(i), suffixes(j) + End If + Next + Next + + Dim maxLength As Integer = 0 + + For i = 0 To Len(text) - 2 + Dim prefixLen As Integer = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen > maxLength Then maxLength = prefixLen + Next + + If maxLength = 0 Then Exit Sub + + result.max_length = maxLength + + For i = 0 To Len(text) - 2 + Dim prefixLen As Integer = LongestCommonPrefix(suffixes(i).suffix, suffixes(i + 1).suffix) + If prefixLen = maxLength Then + Dim substring As String = Left(suffixes(i).suffix, maxLength) + + Dim found As Boolean = False + For j = 0 To result.count - 1 + If result.substrings(j).substring = substring Then + found = True + Exit For + End If + Next + + If Not found Then + Dim positions As String = "" + Dim posCount As Integer = 0 + Dim posArray(0 To 100) As Integer + + For j = 0 To Len(text) - 1 + If Left(suffixes(j).suffix, maxLength) = substring Then + posArray(posCount) = suffixes(j).index - 2 + posCount += 1 + End If + Next + + ' Sort positions (from lowest to highest) + For j = 0 To posCount - 2 + For k = j + 1 To posCount - 1 + If posArray(j) > posArray(k) Then + Swap posArray(j), posArray(k) + End If + Next + Next + + For j = 0 To posCount - 1 + If j > 0 Then positions &= " " + positions &= Str(posArray(j)) + Next + + result.substrings(result.count).substring = substring + result.substrings(result.count).positions = positions + result.count += 1 + End If + End If + Next +End Sub + +Sub main() + Dim limits(0 To 2) As Integer = {1000, 10000, 100000} + + Dim As Integer ff, i, j, limit + Dim As String contents + + ff = Freefile + If Open("piDigits.txt" For Input As #ff) = 0 Then + contents = Input(Lof(ff), ff) + Close #ff + Else + Print "Error: Could not open piDigits.txt" + Exit Sub + End If + + For i = 0 To 2 + limit = limits(i) + Dim As String pi_digits = Left(contents, limit) + + Dim As Double t0 = Timer + + Dim results As AllSubstringsInfo + FindLongestRepeatedSubstrings(pi_digits, results) + + Dim As Double elapsed = Timer - t0 + + Print "First " & limit & " digits of pi has longest repeated characters:" + + If results.count > 0 Then + For j = 0 To results.count - 1 + Print " '" & results.substrings(j).substring & "' starting at indices " & results.substrings(j).positions + Next + Else + Print " No repeated substrings found." + End If + + Print Using !"Time taken: ###.### seconds\n"; elapsed + Next + + Print "The timings show that the implementation has approximately linear performance." +End Sub + +main() + +Sleep diff --git a/Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js b/Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js new file mode 100644 index 0000000000..755cedc059 --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/JavaScript/ukkonen-s-suffix-tree-construction.js @@ -0,0 +1,196 @@ +const fs = require('fs'); + +UNDEFINED = -1; +LEAF_NODE = Number.MAX_SAFE_INTEGER; + +class SuffixTree { + constructor(aWord) { + this.text = Array.from(aWord); + this.text.push('\uF123'); // Terminal character + + this.nodes = new Array(2 * this.text.length); + this.root = this.newNode(this.UNDEFINED, this.UNDEFINED); + this.activeNode = this.root; + + this.textIndex = 0; + this.currentNode = 0; + this.needParentLink = this.UNDEFINED; + this.remainder = 0; + this.leafIndexGenerator = 0; + + for (let i = 0; i < this.text.length; i++) { + this.extendSuffixTree(this.text[i]); + } + } + + getLongestRepeatedSubstrings() { + const indexes = this.doTraversal(); + const word = this.text.slice(0, this.text.length - 1).join(''); + const result = {}; + + if (indexes[0] > 0) { + for (let i = 1; i < indexes.length; i++) { + const substring = word.substring(indexes[i], indexes[i] + indexes[0]); + if (!result[substring]) { + result[substring] = new Set(); + } + result[substring].add(indexes[i]); + } + } + + return result; + } + + extendSuffixTree(aCharacter) { + this.needParentLink = this.UNDEFINED; + this.remainder++; + + while (this.remainder > 0) { + if (this.activeLength === 0) { + this.activeEdge = this.textIndex; + } + + if (!this.nodes[this.activeNode].children.hasOwnProperty(this.text[this.activeEdge])) { + const leaf = this.newNode(this.textIndex, this.LEAF_NODE); + this.nodes[this.activeNode].children[this.text[this.activeEdge]] = leaf; + this.addSuffixLink(this.activeNode); + } else { + const next = this.nodes[this.activeNode].children[this.text[this.activeEdge]]; + if (this.walkDown(next)) { + continue; + } + + if (this.text[this.nodes[next].start + this.activeLength] === aCharacter) { + this.activeLength++; + this.addSuffixLink(this.activeNode); + break; + } + + const split = this.newNode(this.nodes[next].start, this.nodes[next].start + this.activeLength); + this.nodes[this.activeNode].children[this.text[this.activeEdge]] = split; + const leaf = this.newNode(this.textIndex, this.LEAF_NODE); + this.nodes[split].children[aCharacter] = leaf; + this.nodes[next].start += this.activeLength; + this.nodes[split].children[this.text[this.nodes[next].start]] = next; + this.addSuffixLink(split); + } + + this.remainder--; + + if (this.activeNode === this.root && this.activeLength > 0) { + this.activeLength--; + this.activeEdge = this.textIndex - this.remainder + 1; + } else { + this.activeNode = (this.nodes[this.activeNode].parentLink > 0) ? this.nodes[this.activeNode].parentLink : this.root; + } + } + + this.textIndex++; + } + + walkDown(aNode) { + if (this.activeLength >= this.nodes[aNode].edgeLength()) { + this.activeEdge += this.nodes[aNode].edgeLength(); + this.activeLength -= this.nodes[aNode].edgeLength(); + this.activeNode = aNode; + + return true; + } + + return false; + } + + addSuffixLink(aNode) { + if (this.needParentLink !== this.UNDEFINED) { + this.nodes[this.needParentLink].parentLink = aNode; + } + + this.needParentLink = aNode; + } + + newNode(aStart, aEnd) { + const node = new Node(aStart, aEnd); + node.leafIndex = (aEnd === this.LEAF_NODE) ? this.leafIndexGenerator++ : this.UNDEFINED; + this.nodes[this.currentNode] = node; + + return this.currentNode++; + } + + doTraversal() { + const indexes = [this.UNDEFINED]; + + return this.traversal(indexes, this.nodes[this.root], 0); + } + + traversal(aIndexes, aNode, aHeight) { + if (aNode.leafIndex === this.UNDEFINED) { + for (const index of Object.values(aNode.children)) { + const child = this.nodes[index]; + this.traversal(aIndexes, child, aHeight + child.edgeLength()); + } + } else if (aIndexes[0] < aHeight - aNode.edgeLength()) { + aIndexes.length = 0; + aIndexes.push(aHeight - aNode.edgeLength()); + aIndexes.push(aNode.leafIndex); + } else if (aIndexes[0] === aHeight - aNode.edgeLength()) { + aIndexes.push(aNode.leafIndex); + } + + return aIndexes; + } + + + +} + +class Node { + constructor(aStart, aEnd) { + this.start = aStart; + this.end = aEnd; + this.parentLink = 0; + this.leafIndex = 0; + this.children = {}; + } + + edgeLength() { + return Math.min(this.end, suffixTree.textIndex + 1) - this.start; + } +} + + +async function main() { + const limits = [1000, 10000, 100000]; + const piDigitsFile = 'piDigits.txt'; + + try { + const contents = await fs.promises.readFile(piDigitsFile, 'utf8'); + + for (const limit of limits) { + const piDigits = contents.substring(0, limit + 1); + + const start = Date.now(); + suffixTree = new SuffixTree(piDigits); + const substrings = suffixTree.getLongestRepeatedSubstrings(); + const end = Date.now(); + + console.log(`First ${limit} digits of pi has longest repeated characters:`); + for (const substring in substrings) { + if (substrings.hasOwnProperty(substring)) { + const indexes = Array.from(substrings[substring]); + console.log(` '${substring}' starting at index ${indexes.join(' and ')}`); + } + } + + console.log(`Time taken: ${end - start} milliseconds.\n`); + } + + console.log("The timings show that the implementation has approximately linear performance."); + + } catch (err) { + console.error("An error occurred:", err); + } +} + +let suffixTree; + +main(); diff --git a/Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs b/Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs new file mode 100644 index 0000000000..d7a794d714 --- /dev/null +++ b/Task/Ukkonen-s-suffix-tree-construction/Rust/ukkonen-s-suffix-tree-construction.rs @@ -0,0 +1,250 @@ +use std::collections::{HashMap, HashSet}; +use std::fs::File; +use std::io::Read; +use std::time::Instant; +use std::cmp::min; + +struct Node { + start: i32, + end: i32, + parent_link: i32, + leaf_index: i32, + children: HashMap, +} + +impl Node { + fn new(start: i32, end: i32) -> Self { + Node { + start, + end, + parent_link: 0, + leaf_index: 0, + children: HashMap::new(), + } + } + + fn edge_length(&self, text_index: i32) -> i32 { + min(self.end, text_index + 1) - self.start + } +} + +struct SuffixTree { + nodes: Vec, + text: String, + root: i32, + active_node: i32, + active_length: i32, + active_edge: i32, + text_index: i32, + current_node: i32, + need_parent_link: i32, + remainder: i32, + leaf_index_generator: i32, +} + +impl SuffixTree { + const UNDEFINED: i32 = -1; + const LEAF_NODE: i32 = i32::MAX; + + fn new(word: &str) -> Self { + let mut text = String::from(word); + text.push('\u{0004}'); // Terminal character + + let mut tree = SuffixTree { + nodes: Vec::with_capacity(2 * text.len()), + text, + root: 0, + active_node: 0, + active_length: 0, + active_edge: 0, + text_index: 0, + current_node: 0, + need_parent_link: 0, + remainder: 0, + leaf_index_generator: 0, + }; + + // Initialize nodes vector with a placeholder to allow indexing from 0 + for _ in 0..2 * tree.text.len() { + tree.nodes.push(Node::new(Self::UNDEFINED, Self::UNDEFINED)); + } + + tree.root = tree.new_node(Self::UNDEFINED, Self::UNDEFINED); + tree.active_node = tree.root; + + // Build the suffix tree + for ch in tree.text.chars().collect::>() { + tree.extend_suffix_tree(ch); + } + + tree + } + + fn extend_suffix_tree(&mut self, character: char) { + self.need_parent_link = Self::UNDEFINED; + self.remainder += 1; + + let text_chars: Vec = self.text.chars().collect(); + + while self.remainder > 0 { + if self.active_length == 0 { + self.active_edge = self.text_index; + } + + let active_edge_char = text_chars[self.active_edge as usize]; + + if !self.nodes[self.active_node as usize].children.contains_key(&active_edge_char) { + let leaf = self.new_node(self.text_index, Self::LEAF_NODE); + self.nodes[self.active_node as usize].children.insert(active_edge_char, leaf); + self.add_suffix_link(self.active_node); + } else { + let next = *self.nodes[self.active_node as usize].children.get(&active_edge_char).unwrap(); + if self.walk_down(next) { + continue; + } + + if text_chars[(self.nodes[next as usize].start + self.active_length) as usize] == character { + self.active_length += 1; + self.add_suffix_link(self.active_node); + break; + } + + let split = self.new_node( + self.nodes[next as usize].start, + self.nodes[next as usize].start + self.active_length, + ); + self.nodes[self.active_node as usize].children.insert(active_edge_char, split); + + let leaf = self.new_node(self.text_index, Self::LEAF_NODE); + self.nodes[split as usize].children.insert(character, leaf); + + self.nodes[next as usize].start += self.active_length; + let next_start_char = text_chars[self.nodes[next as usize].start as usize]; + self.nodes[split as usize].children.insert(next_start_char, next); + + self.add_suffix_link(split); + } + + self.remainder -= 1; + + if self.active_node == self.root && self.active_length > 0 { + self.active_length -= 1; + self.active_edge = self.text_index - self.remainder + 1; + } else { + self.active_node = if self.nodes[self.active_node as usize].parent_link > 0 { + self.nodes[self.active_node as usize].parent_link + } else { + self.root + }; + } + } + + self.text_index += 1; + } + + fn walk_down(&mut self, node: i32) -> bool { + if self.active_length >= self.nodes[node as usize].edge_length(self.text_index) { + self.active_edge += self.nodes[node as usize].edge_length(self.text_index); + self.active_length -= self.nodes[node as usize].edge_length(self.text_index); + self.active_node = node; + return true; + } + false + } + + fn add_suffix_link(&mut self, node: i32) { + if self.need_parent_link != Self::UNDEFINED { + self.nodes[self.need_parent_link as usize].parent_link = node; + } + self.need_parent_link = node; + } + + fn new_node(&mut self, start: i32, end: i32) -> i32 { + let node_index = self.current_node; + self.nodes[node_index as usize] = Node::new(start, end); + + if end == Self::LEAF_NODE { + self.nodes[node_index as usize].leaf_index = self.leaf_index_generator; + self.leaf_index_generator += 1; + } else { + self.nodes[node_index as usize].leaf_index = Self::UNDEFINED; + } + + self.current_node += 1; + node_index + } + + fn get_longest_repeated_substrings(&self) -> HashMap> { + let indexes = self.do_traversal(); + let text_chars: Vec = self.text.chars().collect(); + let mut result: HashMap> = HashMap::new(); + + if indexes[0] > 0 { + for i in 1..indexes.len() { + let substring: String = text_chars[indexes[i] as usize..(indexes[i] + indexes[0]) as usize].iter().collect(); + + result.entry(substring) + .or_insert_with(HashSet::new) + .insert(indexes[i]); + } + } + + result + } + + fn do_traversal(&self) -> Vec { + let mut indexes = vec![Self::UNDEFINED]; + self.traversal(&mut indexes, &self.nodes[self.root as usize], 0) + } + + fn traversal(&self, indexes: &mut Vec, node: &Node, height: i32) -> Vec { + if node.leaf_index == Self::UNDEFINED { + for (_, &child_index) in &node.children { + let child = &self.nodes[child_index as usize]; + self.traversal(indexes, child, height + child.edge_length(self.text_index)); + } + } else if indexes[0] < height - node.edge_length(self.text_index) { + indexes.clear(); + indexes.push(height - node.edge_length(self.text_index)); + indexes.push(node.leaf_index); + } else if indexes[0] == height - node.edge_length(self.text_index) { + indexes.push(node.leaf_index); + } + + indexes.clone() + } +} + +fn main() -> std::io::Result<()> { + let limits = [1_000, 10_000, 100_000]; + + let mut file = File::open("../piDigits.txt")?; + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + + for &limit in &limits { + let pi_digits = &contents[0..limit]; + + println!("Processing first {} digits of pi...", limit); + + let start = Instant::now(); + let tree = SuffixTree::new(pi_digits); + let substrings = tree.get_longest_repeated_substrings(); + let duration = start.elapsed(); + + println!("First {} digits of pi has longest repeated characters:", limit); + for (substring, indexes) in &substrings { + print!(" '{}' starting at index ", substring); + for &index in indexes { + print!("{} ", index); + } + println!(); + } + + println!("Time taken: {:?}\n", duration); + } + + println!("The timings show that the implementation has approximately linear performance."); + + Ok(()) +} diff --git a/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy b/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy index ca9685ce85..dd72280f92 100644 --- a/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy +++ b/Task/Ulam-spiral-for-primes-/EasyLang/ulam-spiral-for-primes-.easy @@ -1,23 +1,14 @@ func isprim num . - if num < 2 - return 0 - . + if num < 2 : return 0 i = 2 while i <= sqrt num - if num mod i = 0 - return 0 - . + if num mod i = 0 : return 0 i += 1 . return 1 . -n = 1 -x = 50 -y = 50 -dx = 1 -dy = 0 # -proc turn . . +subr turn if dx = 1 dx = 0 dy = 1 @@ -32,30 +23,27 @@ proc turn . . dy = 0 . . -proc step . . +subr step n += 1 - x += dx * 1 - y += dy * 1 - move x y - if isprim n = 1 - circle 0.5 - . + x += dx + y += dy + if isprim n = 1 : gcircle x y 0.5 . -textsize 3 -move x y +gtextsize 3 +n = 1 +x = 50 +y = 50 +dx = 1 +dy = 0 lng = 0 # for k to 49 step lng += 2 turn - for j to lng - 1 - step - . + for j to lng - 1 : step for i to 3 turn - for j to lng - step - . + for j to lng : step . . diff --git a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx deleted file mode 100644 index 5c8e667ceb..0000000000 --- a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--1.rexx +++ /dev/null @@ -1,48 +0,0 @@ -/*REXX program shows counter─clockwise Ulam spiral of primes shown in a square matrix.*/ -parse arg size init char . /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/ -if init=='' | init=="," then init= 1 /* " " " " " " */ -if char=='' then char= "█" /* " " " " " " */ -tot=size**2 /*the total number of numbers in spiral*/ - /*define the upper/bottom right corners*/ -uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+1; uR._=1; _=_+od; bR._=1; end /*od*/ - /*define the bottom/upper left corners.*/ -bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+1; bL._=1; _=_+ev; uL._=1; end /*ev*/ - -app=1; bigP=0; #p=0; inc=0; minR=1; maxR=1; r=1; $=0; $.=; !.= - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/ - do i=init for tot; r= r + inc; minR= min(minR, r); maxR= max(maxR, r) - x= isPrime(i); if x then bigP= max(bigP, i); #p= #p + x /*bigP, #primes.*/ - if app then $.r= $.r || x /*append token.*/ - else $.r= x || $.r /*prepend token.*/ - if uR.i then do; app= 1; inc= +1; iterate /*i*/; end /*advance ↓ */ - if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */ - if bR.i then do; app= 0; inc= 0; iterate /*i*/; end /* " ► */ - if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " ◄ */ - end /*i*/ /* [↓] pack two */ - /*lines ──► one.*/ - do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/ - do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/ - bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/ - if top then if bot then !.$= !.$'█' /*has top & bot.*/ - else !.$= !.$'▀' /*has top,¬ bot.*/ - else if bot then !.$= !.$'▄' /*¬ top, has bot*/ - else !.$= !.$' ' /*¬ top, ¬ bot*/ - end /*k*/ - end /*j*/ /* [↓] show the prime spiral matrix.*/ - do m=1 for $; say !.m; end /*m*/ -say; say init 'is the starting point,' , - tot 'numbers used,' #p "primes found, largest prime:" bigP -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7 11 13 17 19') \==0 then return 1 - if x<17 then return 0; if x// 2 ==0 then return 0 - if x// 3 ==0 then return 0 - /*get the last digit*/ parse var x '' -1 _; if _==5 then return 0 - if x// 7 ==0 then return 0 - if x//11 ==0 then return 0 - if x//13 ==0 then return 0 - - do j=17 by 6 until j*j > x; if x//j ==0 then return 0 - if x//(j+2) ==0 then return 0 - end /*j*/; return 1 diff --git a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx deleted file mode 100644 index 67dd6d6a78..0000000000 --- a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes--2.rexx +++ /dev/null @@ -1,48 +0,0 @@ -/*REXX program shows a clockwise Ulam spiral of primes shown in a square matrix.*/ -parse arg size init char . /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size= 79 /*Not specified? Then use the default.*/ -if init=='' | init=="," then init= 1 /* " " " " " " */ -if char=='' then char= "█" /* " " " " " " */ -tot=size**2 /*the total number of numbers in spiral*/ - /*define the upper/bottom right corners*/ -uR.=0; bR.=0; do od=1 by 2 to tot; _=od**2+init; uR._=1; _=_+od; bR._=1; end /*od*/ - /*define the bottom/upper left corners.*/ -bL.=0; uL.=0; do ev=2 by 2 to tot; _=ev**2+init; bL._=1; _=_+ev; uL._=1; end /*ev*/ - -app=1; bigP=0; #p=0; inc=0; minR=1; maxR=1; r=1; $=0; $.=; !.= - /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ construct the spiral #s.*/ - do i=init for tot; r= r + inc; minR= min(minR, r); maxR= max(maxR, r) - x= isPrime(i); if x then bigP= max(bigP, i); #p= #p + x /*bigP, #primes.*/ - if app then $.r= $.r || x /*append token.*/ - else $.r= x || $.r /*prepend token.*/ - if uR.i then do; app= 1; inc= +1; iterate /*i*/; end /*advance ↓ */ - if bL.i then do; app= 0; inc= -1; iterate /*i*/; end /* " ↑ */ - if bR.i then do; app= 0; inc= 0; iterate /*i*/; end /* " ► */ - if uL.i then do; app= 1; inc= 0; iterate /*i*/; end /* " ◄ */ - end /*i*/ /* [↓] pack two */ - /*lines ──► one.*/ - do j=minR to maxR by 2; jp= j + 1; $= $ + 1 /*fold two lines*/ - do k=1 for length($.j); top= substr($.j, k, 1) /*the 1st line.*/ - bot= word( substr($.jp, k, 1) 0, 1) /*the 2nd line.*/ - if top then if bot then !.$= !.$'█' /*has top & bot.*/ - else !.$= !.$'▀' /*has top,¬ bot.*/ - else if bot then !.$= !.$'▄' /*¬ top, has bot*/ - else !.$= !.$' ' /*¬ top, ¬ bot*/ - end /*k*/ - end /*j*/ /* [↓] show the prime spiral matrix.*/ - do m=1 for $; say !.m; end /*m*/ -say; say init 'is the starting point,' , - tot 'numbers used,' #p "primes found, largest prime:" bigP -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7 11 13 17 19') \==0 then return 1 - if x<17 then return 0; if x// 2 ==0 then return 0 - if x// 3 ==0 then return 0 - /*get the last digit*/ parse var x '' -1 _; if _==5 then return 0 - if x// 7 ==0 then return 0 - if x//11 ==0 then return 0 - if x//13 ==0 then return 0 - - do j=17 by 6 until j*j > x; if x//j ==0 then return 0 - if x//(j+2) ==0 then return 0 - end /*j*/; return 1 diff --git a/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx new file mode 100644 index 0000000000..d0ee3b6b14 --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/REXX/ulam-spiral-for-primes-.rexx @@ -0,0 +1,98 @@ +-- 25 Apr 2025 +include Settings +arg size','init + +say 'ULAM SPIRAL' +say version +say +call Parameters +call Corners +call Spiral +call Pack +call Display +call Timer +exit + +Parameters: +if size = '' then + size = 79 +tot = size**2 +if init = '' then + init = 1 +return + +Corners: +ur. = 0; br. = 0 +do od = 1 by 2 to tot + u = od**2+1; ur.u = 1; u = u+od; br.u = 1 +end +bl. = 0; ul. = 0 +do ev = 2 by 2 to tot + u = ev**2+1; bl.u = 1; u = u+ev; ul.u = 1 +end +return + +Spiral: +app = 1; bigp = 0; hp = 0; inc = 0 +minr = 1; maxr = 1; r = 1; d = 0; d. = ''; e. = '' +do i = init for tot + r = r + inc; minr = Min(minr,r); maxr = Max(maxr,r) + x = Prime(i) + if x then + bigp = Max(bigp,i) + hp = hp + x + if app then + d.r = d.r||x + else + d.r = x||d.r + if ur.i then do + app = 1; inc = +1 + iterate i + end + if bl.i then do + app = 0; inc = -1 + iterate i + end + if br.i then do + app = 0; inc = 0 + iterate i + end + if ul.i then do + app = 1; inc = 0 + iterate i + end +end +return + +Pack: +do j = minr by 2 to maxr + jp = j+1; d = d+1 + do k = 1 for Length(d.j) + top = Substr(d.j,k,1) + bot = Word(Substr(d.jp,k,1) 0,1) + if top then + if bot then + e.d = e.d||'DB'x + else + e.d = e.d||'DF'x + else + if bot then + e.d = e.d||'DC'x + else + e.d = e.d' ' + end +end +return + +Display: +do m = 1 for d + say e.m +end +say +say init 'starting point,' tot 'numbers,' hp 'primes,' bigp 'largest prime' +return + +include Functions +include Numbers +include Helper +include Abend diff --git a/Task/Unicode-strings/Tcl/unicode-strings.tcl b/Task/Unicode-strings/Tcl/unicode-strings.tcl new file mode 100644 index 0000000000..b85e2903cb --- /dev/null +++ b/Task/Unicode-strings/Tcl/unicode-strings.tcl @@ -0,0 +1,52 @@ +# list of sequential integers +proc range { n m } { + set res {} + while {$n <= $m} {lappend res $n ; incr n } + return $res +} + +# print utf-8 char from integer range +proc utf8_range {n m {enc utf-8} } { + + # save encoding + set old_enc [encoding system] + + set streams [list stdin stdout stderr] + + # set new encoding + encoding system $enc + + foreach stream $streams { + fconfigure $stream -encoding $enc + } + + set n [range $n $m] + + set len 0 + + # convert int to char in encoding + # print 30 per line + foreach c $n { + set s [encoding convertto $enc $c] + set char [format %c $s] + puts -nonewline "${char} " + if {[expr {$len % 19}] == 0} {puts ""} + incr len + } + + puts "" + + #restore encoding + foreach stream $streams { + fconfigure $stream -encoding $old_enc + } + encoding system $old_enc +} + + +# utf-8 graphics +scan 2580 %x start +scan 27FF %x stop + +puts "utf-8 glyphs" +utf8_range $start $stop diff --git a/Task/Unicode-variable-names/Ballerina/unicode-variable-names.ballerina b/Task/Unicode-variable-names/Ballerina/unicode-variable-names.ballerina new file mode 100644 index 0000000000..6b80329cf7 --- /dev/null +++ b/Task/Unicode-variable-names/Ballerina/unicode-variable-names.ballerina @@ -0,0 +1,7 @@ +import ballerina/io; + +public function main() { + int Δ = 1; + Δ += 1; + io:println(Δ); +} diff --git a/Task/Unicode-variable-names/Odin/unicode-variable-names.odin b/Task/Unicode-variable-names/Odin/unicode-variable-names.odin new file mode 100644 index 0000000000..f55ed386f2 --- /dev/null +++ b/Task/Unicode-variable-names/Odin/unicode-variable-names.odin @@ -0,0 +1,11 @@ +package main + +import "core:fmt" + + +main :: proc() { + + Δ:= 1 + Δ = Δ +1 + fmt.println(Δ) +} diff --git a/Task/Unicode-variable-names/Scheme/unicode-variable-names.scm b/Task/Unicode-variable-names/Scheme/unicode-variable-names.scm new file mode 100644 index 0000000000..4984384c8f --- /dev/null +++ b/Task/Unicode-variable-names/Scheme/unicode-variable-names.scm @@ -0,0 +1,4 @@ +(define Δ 1) +Δ +(set! Δ (+ 1 Δ)) +Δ diff --git a/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy b/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy index 5d124545bd..2e4257d861 100644 --- a/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy +++ b/Task/Universal-Turing-machine/EasyLang/universal-turing-machine.easy @@ -1,9 +1,7 @@ global right$[] left$[] pos blank$ . -proc show stat$ . . +proc show stat$ . write stat$ - for i to 5 - len stat$ - write " " - . + for i to 5 - len stat$ : write " " write "| " h = -len left$[] + 1 for i = h to len right$[] @@ -22,31 +20,29 @@ proc show stat$ . . print "" . func$ get . - if pos <= 0 - return left$[-pos + 1] - . + if pos <= 0 : return left$[-pos + 1] return right$[pos] . -proc put s$ . . +proc put s$ . if pos <= 0 left$[-pos + 1] = s$ else right$[pos] = s$ . . -proc mleft . . +proc mleft . pos -= 1 if pos <= 0 and len left$[] < (-pos + 1) left$[] &= blank$ . . -proc mright . . +proc mright . pos += 1 if pos > 0 and len right$[] < pos right$[] &= blank$ . . -proc utm stat$ endstat$ bl$ init$ rules$[] trace . . +proc utm stat$ endstat$ bl$ init$ rules$[] trace . blank$ = bl$ pos = 1 right$[] = strsplit init$ " " @@ -57,10 +53,8 @@ proc utm stat$ endstat$ bl$ init$ rules$[] trace . . repeat if trace = 1 show stat$ - else - if steps mod 1000000 = 0 - write "." - . + elif steps mod 1000000 = 0 + write "." . for i to len r$[][] if r$[i][1] = stat$ and r$[i][2] = get diff --git a/Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy b/Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy new file mode 100644 index 0000000000..89c38321ba --- /dev/null +++ b/Task/Unprimeable-numbers/EasyLang/unprimeable-numbers.easy @@ -0,0 +1,36 @@ +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 : return 0 + i += 1 + . + return 1 +. +func isunprim n . + n$[] = strchars n + for i to len n$[] + s$ = n$[i] + for d = 0 to 9 + n$[i] = d + h = number strjoin n$[] "" + if isprim h = 1 : return 0 + . + n$[i] = s$ + . + return 1 +. +n = 1 +while cnt < 35 + if isunprim n = 1 + write n & " " + cnt += 1 + . + n += 1 +. +print "" +repeat + if isunprim n = 1 : cnt += 1 + until cnt = 600 + n += 1 +. +print n diff --git a/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx b/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx index f10a124567..a6ca596e28 100644 --- a/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx +++ b/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx @@ -1,68 +1,94 @@ -/*REXX program finds and displays unprimeable numbers (non─negative integers). */ -parse arg n x hp . /*obtain optional arguments from the CL*/ -if n=='' | n=="," then n= 35 /*Not specified? Then use the default.*/ -if x=='' | x=="," then x= 600 /* " " " " " " */ -if hp=='' | hp=="," then hp= 10000000 /* " " " " " " */ -u= 0 /*number of unprimeable numbers so far.*/ -eds=4; ed.1= 1; ed.2= 3; ed.3= 7; ed.4= 9 /*"end" digits which are prime; prime>9*/ -call genP hp /*generate primes up to & including HP.*/ -$$=; $.=. /*a list " " " " " */ - do j=100; if !.j then iterate /*Prime? Unprimeable must be composite*/ - Lm= length(j) /*obtain the length-1 of the number J. */ - meat= left(j, Lm) /*obtain the first Lm digits of J. */ - /* [↑] examine the "end" digit of J. */ - do e_=1 for eds; new= meat || ed.e_ /*obtain a different number (than J).*/ - if new==j then iterate /*Is it the original number? Then skip.*/ - if !.new then iterate j /*This new number a prime? " " */ - end /*e_*/ - /* [↑] examine a new 1st digit of J. */ - do f_=0 for 10; new= (f_||meat) + 0 /*obtain a different number (than J).*/ - if new==j then iterate /*Is it the original number? Then skip.*/ - if !.new then iterate j /*This new number a prime? " " */ - end /*f_*/ /* [↑] examine the front digit of J. */ - do a_= 2 for Lm-1 /*traipse through the middle digits. */ - meat= left(j, a_ - 1) /*use a number of left─most dec. digits*/ - rest= substr(j, a_ + 1) /* " " " " right─most " " */ - do n_=0 for 10 /*traipse through all 1─digit numbers. */ - new= meat || n_ || rest /*construct new number, like a phoenix.*/ - if new==j then iterate /*Is it the original number? Then skip.*/ - if !.new then iterate j /*This new number a prime? " " */ - end /*n_*/ - end /*a_*/ - u= u + 1 /*bump the count of unprimeable numbers*/ - if u<=n then $$= $$ commas(j) /*maybe add unprimeable # to $$ list.*/ - if u==x then $.ox= commas(j) /*assign the Xth unprimeable number.*/ - parse var j '' -1 _ /*obtain the right─most dec digit of J.*/ - if $._==. then $._= j /*the 1st unprimeable # that ends in _.*/ - if $.3==. then iterate; if $.7==. then iterate /*test if specific #'s found.*/ - if $.1==. then iterate; if $.9==. then iterate /* " " " " " */ - leave /*if here, then we're done. */ - end /*j*/ +-- 22 Mar 2025 +include Settings -if n>0 then do; say center(' first ' n "unprimeable numbers ", 139, '═') - say strip($$); say - end -if x>0 then say ' the ' th(x) " unprimeable number is: " $.ox +say 'UNPRIMEABLE NUMBERS' +say version say - do o=0 for 10; if length($.o)==0 then iterate - say ' the first unprimeable number that ends in ' o " is:"right(commas($.o),11) - end /*o*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do c=length(?)-3 to 1 by -3; ?=insert(',', ?, c); end; return ? -th:procedure;parse arg x;return x||word('th st nd rd',1+(x//10)*(x//100%10\==1)*(x//10<4)) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23; @.10=29; @.11=31 - !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1; !.29=1 - #= 11; sq.#= @.# **2 - do lim=100 until lim*lim>=hp /*only keep primes up to the sqrt(hp). */ - end /*lim*/ /* [↑] find limit for storing primes. */ - do j=@.#+2 by 2 to hp; parse var j '' -1 _; if _==5 then iterate /*÷ by 5?*/ - if j// 3==0 then iterate; if j// 7==0 then iterate; if j//11==0 then iterate - if j//13==0 then iterate; if j//17==0 then iterate; if j//19==0 then iterate - if j//23==0 then iterate; if j//29==0 then iterate - do k=11 while sq.k<=j /*divide by some generated odd primes. */ - if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/ - end /*k*/ /* [↓] a prime (J) has been found. */ - #= #+1; if #<=lim then @.#=j; !.j=1 /*bump prime count; assign prime to @. */ - sq.#= j*j /*calculate square of J for fast WHILE.*/ +call GetPrimes +call GetUnprimes +call Task1 +call Task2 +call GetLowest +call Task3 +exit + +GetPrimes: +procedure expose prim. flag. +call Time('r') +say 'Get primes up to 10 million...' +call Primes 1e7 +say prim.0 'primes found' +say Format(Time('e'),,3) 'seconds'; say +return + +GetUnprimes: +procedure expose flag. unpr. +call Time('r') +say 'Get unprimeable numbers up to 1.3 million...' +unpr. = 0; n = 0 +do i = 100 to 1.3e6 + if \ flag.i then do + a = 1; b = Length(i) + do j = a to b + c = Substr(i,j,1) + do k = 0 to 9 + d = Left(i,j-1)||k||Right(i,b-j); d = d+0 + if flag.d then + iterate i + end + end + n = n+1; unpr.n = i + end +end +unpr.0 = n +say unpr.0 'unprimeable numbers found' +say Format(Time('e'),,3) 'seconds'; say +return + +Task1: +procedure expose unpr. +call Time('r') +say 'The first 35 unprimeable numbers are' +do i = 1 to 35 + call Charout ,Right(unpr.i,4) +end +say +say Format(Time('e'),,3) 'seconds'; say +return + +Task2: +procedure expose unpr. +call Time('r') +say 'The 600th unprimeable number is' +say unpr.600 +say Format(Time('e'),,3) 'seconds'; say +return + +GetLowest: +procedure expose unpr. lowu. +call Time('r') +say 'Get lowest unprimeable number per digit...' +lowu. = 0 +do i = 1 to unpr.0 + a = Right(unpr.i,1) + if lowu.a = 0 then + lowu.a = unpr.i +end +say Format(Time('e'),,3) 'seconds'; say +return + +Task3: +procedure expose lowu. +call Time('r') +say 'Dig Lowest' +say '-----------' +do i = 0 to 9 + say Right(i,3) Right(lowu.i,7) +end +say '-----------' +say Format(Time('e'),,3) 'seconds'; say +return + +include Functions +include Sequences +include Abend diff --git a/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx b/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx index 7faaf0888c..80b2afae60 100644 --- a/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx +++ b/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx @@ -1,61 +1,88 @@ -/*REXX pgm finds N untouchable numbers (numbers that can't be equal to any aliquot sum).*/ -parse arg n cols tens over . /*obtain optional arguments from the CL*/ -if n='' | n=="," then n=2000 /*Not specified? Then use the default.*/ -if cols='' | cols=="," | cols==0 then cols= 10 /* " " " " " " */ -if tens='' | tens=="," then tens= 0 /* " " " " " " */ -if over='' | over=="," then over= 20 /* " " " " " " */ -tell= n>0; n= abs(n) /*N>0? Then display the untouchable #s*/ -call genP n * over /*call routine to generate some primes.*/ -u.= 0 /*define all possible aliquot sums ≡ 0.*/ - do p=1 for #; _= @.p + 1; u._= 1 /*any prime+1 is not an untouchable.*/ - _= @.p + 3; u._= 1 /* " prime+3 " " " " */ - end /*p*/ /* [↑] this will also rule out 5. */ -u.5= 0 /*special case as prime 2 + 3 sum to 5.*/ - do j=2 for lim; if !.j then iterate /*Is J a prime? Yes, then skip it. */ - y= sigmaP() /*compute: aliquot sum (sigma P) of J.*/ - if y<=n then u.y= 1 /*mark Y as a touchable if in range. */ - end /*j*/ -call show /*maybe show untouchable #s and a count*/ -if tens>0 then call powers /*Any "tens" specified? Calculate 'em.*/ -exit cnt /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -genSq: do _=1 until _*_>lim; q._= _*_; end; q._= _*_; _= _+1; q._= _*_; return -grid: $= $ right( commas(t), w); if cnt//cols==0 then do; say $; $=; end; return -powers: do pr=1 for tens; call 'UNTOUCHA' -(10**pr); end /*recurse*/; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: #= 9; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23 /*a list*/ - !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1 !.23=1 /*primes*/ - parse arg lim; call genSq /*define the (high) limit for searching*/ - qq.10= 100 /*define square of the 10th prime index*/ - do j=@.#+6 by 2 to lim /*find odd primes from here on forward.*/ - parse var j '' -1 _; if _==5 then iterate; if j// 3==0 then iterate - if j// 7==0 then iterate; if j//11==0 then iterate; if j//13==0 then iterate - if j//17==0 then iterate; if j//19==0 then iterate; if j//23==0 then iterate - /*start dividing by the tenth prime: 29*/ - do k=10 while qq.k <= j /* [↓] divide J by known odd primes.*/ - if j//@.k==0 then iterate j /*J ÷ by a prime? Then ¬prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j /*bump prime count; assign a new prime.*/ - !.j= 1; qq.#= j*j /*mark prime; compute square of prime.*/ - end /*j*/; return /*#: is the number of primes generated*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: w=7; $= right(2, w+1) right(5, w) /*start the list of an even prime and 5*/ - cnt= 2 /*count of the only two primes in list.*/ - do t=6 by 2 to n; if u.t then iterate /*Is T touchable? Then skip it. */ - cnt= cnt + 1; if tell then call grid /*bump count; maybe show a grid line. */ - end /*t*/ - if tell & $\=='' then say $ /*display a residual grid line, if any.*/ - if tell then say /*show a spacing blank line for output.*/ - if n>0 then say right( commas(cnt), 20) , /*indent the output a bit.*/ - ' untouchable numbers were found ≤ ' commas(n); return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sigmaP: s= 1 /*set initial sigma sum (S) to 1. ___*/ - if j//2 then do m=3 by 2 while q.m a then do + say right(n,5) 'below' right(a,6) + a = a*10 + end + n = n+1 +end +say +return + +include Sequences +include Helper +include Functions +include Special +include Constants +include Abend diff --git a/Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua b/Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua new file mode 100644 index 0000000000..b00f5fd77e --- /dev/null +++ b/Task/Update-a-configuration-file/Lua/update-a-configuration-file.lua @@ -0,0 +1,71 @@ +local function Read(handler) -- NR, line, comment, option, parameters + local line = handler:read"l" + if line==nil or line=="" or line:sub(1,1)=="#" or line:find"^;?%s*$" + then + return line,nil,nil,true + end + local comment, option, param = line:match"^(;?)%s*(%S*)%s*(.*)$" + comment = comment==";" + if not comment then + param = param=="" and true or tonumber(param) or param + end + return line, option, param, comment +end + +local function LoadConfig(H) + local options = {} + for line, option, param, comment in Read,H do + if not comment and option then + options[option] = param + end + end + H:close() + return options +end + +local function MakeLine(k,v) + return v==false and "; " .. k + or v==true and k + or v and k .. " " .. v +end + +local function Sponge(fileS) + local H, tmp = io.open(fileS), io.tmpfile() + tmp:write(H:read"a") tmp:seek"set" + H:close() + return tmp +end + +local function Update(fileS, options) + local IN = Sponge(fileS) + local nl = string.match(IN:read"L" or "\n", "[\r\n]?\n$") IN:seek"set" + local OUT = io.open(fileS, "w+") + local saved = {} -- for appending after + for line, option, param, comment in Read,IN do + if option then + local val = options[option] + saved[option] = true + if val~=param then + line = MakeLine(option,val) + end + end + OUT:write(line, nl) + end + IN:close() + for k,v in pairs(options) do + if saved[k]==nil then + OUT:write( MakeLine(k,v), nl ) + end + end + OUT:close() +end + +local options = LoadConfig( io.open(arg[1]) ) + +-- nil would remove the option entirely +options.NEEDSPEELING = false -- disable +options.SEEDSREMOVED = true +options.NUMBEROFBANANAS = 1024 +options.NUMBEROFSTRAWBERRIES = 62000 + +Update(arg[1], options) diff --git a/Task/User-input-Text/JavaScript/user-input-text-3.js b/Task/User-input-Text/JavaScript/user-input-text-3.js new file mode 100644 index 0000000000..25f1690938 --- /dev/null +++ b/Task/User-input-Text/JavaScript/user-input-text-3.js @@ -0,0 +1,16 @@ +const readline = require("readline"); + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +rl.question("Enter a string: ", (str) => { + console.log(str); + rl.close(); +}); + +rl.question("Enter a number: ", (n) => { + console.log(parseInt(n)); + rl.close(); +}); diff --git a/Task/User-input-Text/Lua/user-input-text.lua b/Task/User-input-Text/Lua/user-input-text.lua index 6e6556e64d..783cda97b9 100644 --- a/Task/User-input-Text/Lua/user-input-text.lua +++ b/Task/User-input-Text/Lua/user-input-text.lua @@ -1,4 +1,4 @@ print('Enter a string: ') s = io.stdin:read() print('Enter a number: ') -i = tonumber(io.stdin:read()) +i = io.stdin:read"n" diff --git a/Task/User-input-Text/OPL/user-input-text.opl b/Task/User-input-Text/OPL/user-input-text.opl new file mode 100644 index 0000000000..69b94deba5 --- /dev/null +++ b/Task/User-input-Text/OPL/user-input-text.opl @@ -0,0 +1,30 @@ +PROC usrinpt: + LOCAL string$(15),number& + WHILE string$="" + PRINT "Please enter a string." + INPUT string$ + IF string$="" + PRINT "Nothing was entered. Please try again." + PAUSE 60 + CLS + ENDIF + ENDWH + PRINT "Thank you! You entered: ";string$ + WHILE number&<>75000 + PRINT "Please enter the number 75000." + TRAP INPUT number& + IF ERR=-1 + PRINT + PRINT "That's not a valid number. Please try again." + PAUSE 60 + CLS + ELSEIF number&<>75000 + PRINT "Wrong number. Please try again." + PAUSE 60 + CLS + ENDIF + ENDWH + PRINT "Good job! You successfully entered 75000!" + PRINT "Press any key to continue." + GET +ENDP diff --git a/Task/Validate-International-Securities-Identification-Number/Lua/validate-international-securities-identification-number.lua b/Task/Validate-International-Securities-Identification-Number/Lua/validate-international-securities-identification-number.lua index 47948c6341..f9aa419024 100644 --- a/Task/Validate-International-Securities-Identification-Number/Lua/validate-international-securities-identification-number.lua +++ b/Task/Validate-International-Securities-Identification-Number/Lua/validate-international-securities-identification-number.lua @@ -1,28 +1,11 @@ -function luhn (n) - local revStr, s1, s2, digit, mod = n:reverse(), 0, 0 - for pos = 1, #revStr do - digit = tonumber(revStr:sub(pos, pos)) - if pos % 2 == 1 then - s1 = s1 + digit - else - digit = digit * 2 - if digit > 9 then - mod = digit % 10 - digit = mod + ((digit - mod) / 10) - end - s2 = s2 + digit - end - end - return (s1 + s2) % 10 == 0 -end +-- Grab luhn function from https://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Lua -function checkISIN (inStr) - if #inStr ~= 12 then return false end - local numStr = "" - for pos = 1, #inStr do - numStr = numStr .. tonumber(inStr:sub(pos, pos), 36) - end - return luhn(numStr) +local function ToBase36(char) return tonumber(char, 36) end +local function Isin2CCN(isin) return isin:gsub(".", ToBase36) end +local isinPattern = "^%u%u" .. ("[%d%u]"):rep(9) .. "%d$" + +function checkISIN (isin) + return isin:match(isinPattern) and luhn(Isin2CCN(isin)) or false end local testCases = { diff --git a/Task/Vampire-number/EasyLang/vampire-number.easy b/Task/Vampire-number/EasyLang/vampire-number.easy index 322f982d9d..a37e7a8019 100644 --- a/Task/Vampire-number/EasyLang/vampire-number.easy +++ b/Task/Vampire-number/EasyLang/vampire-number.easy @@ -5,12 +5,10 @@ func dtally x . . return t . -proc fangs x . f[] . +proc fangs x &f[] . f[] = [ ] nd = floor log10 x + 1 - if nd mod 2 = 1 - return - . + if nd mod 2 = 1 : return nd = nd div 2 lo = higher pow 10 (nd - 1) (x + pow 10 nd - 2) div (pow 10 nd - 1) hi = lower (x / lo) sqrt x @@ -22,11 +20,9 @@ proc fangs x . f[] . . . . -proc show_fangs x f[] . . +proc show_fangs x f[] . write x & " " - for f in f[] - write " = " & f & " x " & x div f - . + for f in f[] : write " = " & f & " x " & x div f print "" . x = 1 diff --git a/Task/Vampire-number/Raku/vampire-number.raku b/Task/Vampire-number/Raku/vampire-number.raku index 95004a9842..c29789c94d 100644 --- a/Task/Vampire-number/Raku/vampire-number.raku +++ b/Task/Vampire-number/Raku/vampire-number.raku @@ -1,17 +1,22 @@ +use Prime::Factor; + sub is_vampire (Int $num) { + return Empty unless $num % 9 == 0|4; my $digits = $num.comb.sort; my @fangs; - (10**$num.sqrt.log(10).floor .. $num.sqrt.ceiling).map: -> $this { - next if $num % $this; - my $that = $num div $this; - next if $this %% 10 && $that %% 10; - @fangs.push("$this x $that") if ($this ~ $that).comb.sort eq $digits; + my @divs = $num.&divisors(:s).grep({.chars == $num.chars div 2}); + return Empty unless @divs >= 2; + @divs.map: -> $this { + my $that = $num div $this; + next if $this %% 10 && $that %% 10; + last if $this > $that; + @fangs.push("$this x $that") if ($this ~ $that).comb.sort eq $digits; } @fangs } constant @vampires = flat (3..*).map: -> $s, $e { - (10**$s .. 10**$e).hyper.map: -> $n { + (flat (10**$s div 9 .. 10**$e div 9).map({my $v = $_ * 9, $v + 4})).hyper.map: -> $n { next unless my @fangs = is_vampire($n); "$n: { @fangs.join(', ') }" } diff --git a/Task/Variables/EasyLang/variables.easy b/Task/Variables/EasyLang/variables.easy index 200e43f282..c4a0740daf 100644 --- a/Task/Variables/EasyLang/variables.easy +++ b/Task/Variables/EasyLang/variables.easy @@ -6,7 +6,7 @@ print n # global array of numbers a[] = [ 2.1 3.14 3 ] # -proc foo . . +proc foo . # i is local, because it is first used in the function for i = 1 to len a[] print a[i] diff --git a/Task/Vector-products/REXX/vector-products.rexx b/Task/Vector-products/REXX/vector-products.rexx index facf79ebfb..d2687f7539 100644 --- a/Task/Vector-products/REXX/vector-products.rexx +++ b/Task/Vector-products/REXX/vector-products.rexx @@ -1,26 +1,28 @@ -/*REXX program computes the products: dot, cross, scalar triple, and vector triple.*/ -a= 3 4 5 -b= 4 3 5 /*(positive numbers don't need quotes.)*/ -c= '-5 -12 -13' -Call tellV 'vector A =', a /*show the A vector, aligned numbers.*/ -Call tellV "vector B =", b /* " " B " " " */ -Call tellV "vector C =", c /* " " C " " " */ -Say '' -Call tellV ' dot product [A·B] =', dot(a,b) -Call tellV 'cross product [AxB] =', cross(a,b) -Call tellV 'scalar triple product [A·(BxC)] =', dot(a,cross(b,c)) -Call tellV 'vector triple product [Ax(BxC)] =', cross(a,cross(b,c)) -Exit /*stick a fork in it, we're all done. */ -/*---------------------------------------------------------------------------*/ -cross: Procedure - Arg a b c, u v w - Return b*w-c*v c*u-a*w a*v-b*u -dot: Procedure - Arg a b c, u v w - Return a*u + b*v + c*w -/*---------------------------------------------------------------------------*/ -tellV: Procedure - Parse Arg name,x y z - w=max(4,length(x),length(y),length(z)) /*max width */ - Say right(name,33) right(x,w) right(y,w) right(z,w) /*show vector. */ - Return +-- 8 May 2025 +include Settings + +say 'VECTOR PRODUCTS' +say version +say +a = '3 4 5'; b = '4 3 5'; c = '-5 -12 -13'; d = '1 2 3' +say 'VALUES' +say 'A =' Vlst2Form(a) +say 'B =' Vlst2Form(b) +say 'C =' Vlst2Form(c) +say 'D =' Vlst2Form(d) +say +say 'BASICS' +say 'A . B =' Vdot(a,b)/1 +say 'A x B =' Vlst2Form(Vcross(a,b)) +say +say 'BONUS' +say 'A . (BxC) =' VscalTrip(a,b,c)/1 +say 'A x (BxC) =' Vlst2Form(VvectTrip(a,b,c)) +say '(AxB) . (CxD) =' VscalQuad(a,b,c,d)/1 +say '(AxB) x (CxD) =' Vlst2Form(VvectQuad(a,b,c,d)) +exit + +include Vector +include Functions +include Constants +include Abend diff --git a/Task/Vector/REXX/vector.rexx b/Task/Vector/REXX/vector.rexx index 2573cebcaa..2a7854d747 100644 --- a/Task/Vector/REXX/vector.rexx +++ b/Task/Vector/REXX/vector.rexx @@ -1,41 +1,31 @@ -/*REXX program shows how to support mathematical functions for vectors using functions. */ - s1 = 11 /*define the s1 scalar: eleven */ - s2 = 2 /*define the s2 scalar: two */ - x = '(5, 7)' /*define the X vector: five and seven*/ - y = '(2, 3)' /*define the Y vector: two and three*/ - z = '(2, 45)' /*define vector of length 2 at 45º */ -call show 'define a vector (length,ºangle):', z , Vdef(z) -call show 'addition (vector+vector):', x " + " y , Vadd(x, y) -call show 'subtraction (vector-vector):', x " - " y , vsub(x, y) -call show 'multiplication (Vector*scalar):', x " * " s1, Vmul(x, s1) -call show 'division (vector/scalar):', x " ÷ " s2, Vdiv(x, s2) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -$fuzz: return min( arg(1), max(1, digits() - arg(2) ) ) -cosD: return cos( d2r( arg(1) ) ) -d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle. */ -d2r: return r2r( d2d(arg(1)) * pi() / 180) /*convert degrees ──► radians. */ -pi: pi=3.14159265358979323846264338327950288419716939937510582; return pi -r2d: return d2d( (arg(1)*180 / pi())) /*convert radians ──► degrees. */ -r2r: return arg(1) // (pi() * 2) /*normalize radians ──► a unit circle. */ -show: say right( arg(1), 33) right( arg(2), 20) ' ──► ' arg(3); return -sinD: return sin( d2r( d2d( arg(1) ) ) ) -V: return word( translate( arg(1), , '{[(JI)]}') 0, 1) /*get the number or zero*/ -V$: parse arg r,c; _='['r; if c\=0 then _=_"," c; return _']' -V#: a=V(a); b=V(b); c=V(c); d=V(d); ac=a*c; ad=a*d; bc=b*c; bd=b*d; s=c*c+d*d; return -Vadd: procedure; arg a ',' b,c "," d; call V#; return V$(a+c, b+d) -Vsub: procedure; arg a ',' b,c "," d; call V#; return V$(a-c, b-d) -Vmul: procedure; arg a ',' b,c "," d; call V#; return V$(ac-bd, bc+ad) -Vdiv: procedure; arg a ',' b,c "," d; call V#; return V$((ac+bd)/s, (bc-ad)/s) -Vdef: procedure; arg a ',' b,c "," d; call V#; return V$(a*sinD(b), a*cosD(b)) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz $fuzz(9, 9) - if a=pi then return -1; - if a=pi*.5 | a=pi*2 then return 0; return .sinCos(1,-1) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) - if x=pi*.5 then return 1; if x=pi*1.5 then return -1 - if abs(x)=pi | x=0 then return 0; return .sinCos(x,+1) -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.sinCos: parse arg z 1 _,i; q=x*x - do k=2 by 2 until p=z; p=z; _= -_*q / (k*(k+i)); z=z+_; end; return z +-- 19 May 2025 +include Settings + +say 'VECTOR' +say version +say +a = '1 2 3'; b = '3 2 1'; c = 3; d = '4 5'; e = '2 1' +say 'VALUES' +say 'A =' Vlst2Form(a) +say 'B =' Vlst2Form(b) +say 'C =' c +say 'D =' Vlst2Form(d) +say 'E =' Vlst2Form(e) +say +say 'BASICS' +say 'A+B =' Vlst2Form(Vadd(a,b)) +say 'A-B =' Vlst2Form(Vsub(a,b)) +say 'A*C =' Vlst2Form(Vmul(a,c)) +say 'A/C =' Vlst2Form(Vdiv(a,c)) +say +say 'BONUS' +say 'Length(D) =' Vlen(d)+0 +say 'Angle(D) =' Vang(d)+0 +say 'Polar(D) =' Vlst2Form(Vrec2Pol(d)) +say 'Rect(E) =' Vlst2Form(Vpol2Rec(e)) +exit + +include Vector +include Functions +include Constants +include Abend diff --git a/Task/Verhoeff-algorithm/JavaScript/verhoeff-algorithm.js b/Task/Verhoeff-algorithm/JavaScript/verhoeff-algorithm.js new file mode 100644 index 0000000000..ca68a85226 --- /dev/null +++ b/Task/Verhoeff-algorithm/JavaScript/verhoeff-algorithm.js @@ -0,0 +1,80 @@ +const multiplicationTable = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], + [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], + [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], + [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], + [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], + [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], + [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], + [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], +]; + +const inverse = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]; + +const permutationTable = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], + [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], + [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], + [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], + [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], + [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], + [7, 0, 4, 6, 9, 1, 3, 2, 5, 8], +]; + + +function verhoeffChecksum(number, doValidation, doDisplay) { + if (doDisplay) { + const calculationType = doValidation ? "Validation" : "Check digit"; + console.log(calculationType + " calculations for " + number + "\n"); + console.log(" i ni p[i, ni] c"); + console.log("-------------------"); + } + + if (!doValidation) { + number += "0"; + } + + let c = 0; + const le = number.length - 1; + + for (let i = le; i >= 0; i--) { + const ni = parseInt(number.charAt(i)); + const pi = permutationTable[(le - i) % 8][ni]; + c = multiplicationTable[c][pi]; + + if (doDisplay) { + console.log(`${String(le - i).padStart(2)}${String(ni).padStart(3)}${String(pi).padStart(8)}${String(c).padStart(6)}\n`); + } + } + + if (doDisplay && !doValidation) { + console.log("inverse[" + c + "] = " + inverse[c] + "\n"); + } + + return doValidation ? c === 0 : inverse[c]; +} + + +function main() { + const tests = [ + ["236", true], + ["12345", true], + ["123456789012", false], + ]; + + for (const test of tests) { + let object = verhoeffChecksum(test[0], false, test[1]); + console.log("The check digit for " + test[0] + " is " + object + "\n"); + + for (const number of [test[0] + String(object), test[0] + "9"]) { + object = verhoeffChecksum(number, true, test[1]); + const result = object ? "correct" : "incorrect"; + console.log("The validation for " + number + " is " + result + ".\n"); + } + } +} + +main(); diff --git a/Task/Verhoeff-algorithm/Rust/verhoeff-algorithm.rs b/Task/Verhoeff-algorithm/Rust/verhoeff-algorithm.rs new file mode 100644 index 0000000000..12055f1a30 --- /dev/null +++ b/Task/Verhoeff-algorithm/Rust/verhoeff-algorithm.rs @@ -0,0 +1,98 @@ +const MULTIPLICATION_TABLE: [[i32; 10]; 10] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], + [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], + [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], + [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], + [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], + [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], + [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], + [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], +]; + +const INVERSE: [i32; 10] = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]; + +const PERMUTATION_TABLE: [[i32; 10]; 8] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], + [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], + [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], + [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], + [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], + [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], + [7, 0, 4, 6, 9, 1, 3, 2, 5, 8], +]; + +fn verhoeff_checksum(number: &str, do_validation: bool, do_display: bool) -> i32 { + if do_display { + let calculation_type = if do_validation { + "Validation" + } else { + "Check digit" + }; + println!("{} calculations for {}\n", calculation_type, number); + println!(" i ni p[i, ni] c"); + println!("-------------------"); + } + + let mut working_number = String::from(number); + if !do_validation { + working_number.push('0'); + } + + let mut c = 0; + let le = working_number.len() - 1; + let chars: Vec = working_number.chars().collect(); + + for i in (0..=le).rev() { + let ni = chars[i].to_digit(10).unwrap() as i32; + let pos = (le - i) % 8; + let pi = PERMUTATION_TABLE[pos][ni as usize]; + c = MULTIPLICATION_TABLE[c as usize][pi as usize]; + + if do_display { + println!( + "{:2} {:2} {:2} {:2}\n", + le - i, + ni, + pi, + c + ); + } + } + + if do_display && !do_validation { + println!("inverse[{}] = {}\n", c, INVERSE[c as usize]); + } + + if do_validation { + if c == 0 { 1 } else { 0 } + } else { + INVERSE[c as usize] + } +} + +fn main() { + let tests = [ + ("123", true), + ("12345", true), + ("123456789012", false), + ]; + + for &(test_num, display) in tests.iter() { + let digit = verhoeff_checksum(test_num, false, display); + println!("The check digit for {} is {}\n", test_num, digit); + + let numbers = [ + format!("{}{}", test_num, digit), + format!("{}9", test_num), + ]; + + for number in numbers.iter() { + let digit = verhoeff_checksum(number, true, display); + let result = if digit == 1 { "correct" } else { "incorrect" }; + println!("The validation for {:?} is {:?}. ", number, result); + } + } +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx b/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx index 25021e077f..5b7e3fbb9d 100644 --- a/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx @@ -1,71 +1,67 @@ -/*REXX program performs a chi─squared test to verify a given distribution is uniform. */ -numeric digits length( pi() ) - length(.) /*enough decimal digs for calculations.*/ -@.=; @.1= 199809 200665 199607 200270 199649 - @.2= 522573 244456 139979 71531 21461 - do s=1 while @.s\==''; call uTest @.s /*invoke uTest with a data set of #'s.*/ - end /*s*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -!: procedure; parse arg x; p=1; do j=2 to x; p= p*j; end /*j*/; return p -chi2p: procedure; parse arg dof, distance; return gammaI( dof/2, distance/2 ) -f: parse arg t; if t=0 then return 0; return t ** (a-1) * exp(-t) -e: e =2.718281828459045235360287471352662497757247093699959574966967627724; return e -pi: pi=3.141592653589793238462643383279502884197169399375105820974944592308; return pi -/*──────────────────────────────────────────────────────────────────────────────────────*/ -!!: procedure; parse arg x; if x<2 then return 1; p= x - do k=2+x//2 to x-1 by 2; p= p*k; end /*k*/; return p -/*──────────────────────────────────────────────────────────────────────────────────────*/ -chi2ud: procedure: parse arg ds; sum=0; expect= 0 - do j=1 for words(ds); expect= expect + word(ds, j) - end /*j*/ - expect = expect / words(ds) - do k=1 for words(ds) - sum= sum + (word(ds, k) - expect) **2 - end /*k*/ - return sum / expect -/*──────────────────────────────────────────────────────────────────────────────────────*/ -exp: procedure; parse arg x; ix= x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix - z=1; _=1; w=z; do j=1; _= _*x/j; z= (z + _)/1; if z==w then leave; w=z - end /*j*/; if z\==0 then z= z * e()**ix; return z -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gamma: procedure; parse arg x; if datatype(x, 'W') then return !(x-1) /*Int? Use fact*/ - n= trunc(x) /*at this point, X is pos and a multiple of 1/2.*/ - d= !!(n+n - 1) /*compute the double factorial of: 2*n - 1. */ - if n//2 then p= -1 /*if N is odd, then use a negative unity. */ - else p= 1 /*if N is even, then use a positive unity. */ - if x>0 then return p * d * sqrt(pi()) / (2**n) - return p * (2**n) * sqrt(pi()) / d -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gammaI: procedure; parse arg a,x; y= a-1; do while f(y)*(x-y) > 2e-8 & y0 - if j//3 == 0 then sum= sum + 2 * f(a + h1*j) - else sum= sum + 3 * f(a + h1*j) - end /*j*/ - return h * sum / 8 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h= d+6 - numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .;g=g *.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g -/*──────────────────────────────────────────────────────────────────────────────────────*/ -uTest: procedure; parse arg dset; sum= 0; pad= left('', 11); sigLev= 1/20 /*5%*/ - say; say ' ' center(" Uniform distribution test ", 75, '═') - #= words(dset); sigPC= sigLev*100/1 - do j=1 for #; sum= sum + word(dset, j) - end /*j*/ - say pad " dataset: " dset - say pad " samples: " sum - say pad " categories: " # - say pad " degrees of freedom: " # - 1 - dist= chi2ud(dset) - P= chi2p(# - 1, dist) - sig = (abs(P) < dist * sigLev) - say pad "significant at " sigPC'% level? ' word('no yes', sig + 1) - say pad " is the dataset uniform? " word('no yes', (\(sig))+ 1) - return +-- 8 May 2025 +include Settings + +say 'VERIFY DISTRIBUTION UNIFORMITY / CHI-SQUARED TEST' +say version +say +call Check '200000 200000 200000 200000 200000' +call Check '199809 200665 199607 200270 199649' +call Check '522573 244456 139979 71531 21461' +call Check 'Random' +call Timer +exit + +Check: +procedure expose stat. glob. +arg xx +-- Dataset +stat. = 0 +if xx = 'RANDOM' then do + do i = 1 to 1000000 + a = Random(1,5); stat.a = stat.a+1 + end + stat.0 = 5 + say 'Dataset Random ' stat.1 stat.2 stat.3 stat.4 stat.5 +end +else do + do i = 1 to Words(xx) + stat.i = Word(xx,i) + end + stat.0 = Words(xx) + say 'Dataset Specified ' xx +end +say 'Categories (bins) ' stat.0 +say 'Degrees of freedom ' stat.0-1 +-- Samples +sa = 0 +do i = 1 to stat.0 + sa = sa+stat.i +end +say 'Samples ' sa +-- Significant at +sl = 1/20; sp = sl*100/1 +say 'Signicant tested at' sp'%' +-- Chi-Squared test value +s = 0; e = 0 +do i = 1 to stat.0 + e = e+stat.i +end i +e = e/stat.0 +do i = 1 to stat.0 + s = s+(stat.i-e)**2 +end i +csv = s/e +say 'Distance ' csv +-- Probability test value +pv = 1-RliGamma((stat.0-1)/2,csv/2) +say 'Probability ' pv +-- Result +say 'Is dataset uniform?' Word('Yes No',(Abs(pv) delta - bad = 1 - . + if abs (h - 1) > delta : bad = 1 dist[i] = 0 print h . diff --git a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx index 12af39c058..b98f4d192d 100644 --- a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx +++ b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx @@ -1,34 +1,74 @@ -/*REXX program simulates a number of trials of a random digit and show it's skew %. */ -parse arg func times delta seed . /*obtain arguments (options) from C.L. */ -if func=='' | func=="," then func= 'RANDOM' /*function not specified? Use default.*/ -if times=='' | times=="," then times= 1000000 /*times " " " " */ -if delta=='' | delta=="," then delta= 1/2 /*delta% " " " " */ -if datatype(seed, 'W') then call random ,,seed /*use some RAND seed for repeatability.*/ -highDig= 9 /*use this var for the highest digit. */ -!.= 0 /*initialize all possible random trials*/ - do times /* [↓] perform a bunch of trials. */ - if func=='RANDOM' then ?= random(highDig) /*use RANDOM function.*/ - else interpret '?=' func "(0,"highDig')' /* " specified " */ - !.?= !.? + 1 /*bump the invocation counter.*/ - end /*times*/ /* [↑] store trials ───► pigeonholes. */ - /* [↓] compute the digit's skewness. */ -g= times / (1 + highDig) /*calculate number of each digit throw.*/ -w= max(9, length( commas(times) ) ) /*maximum length of number of trials.*/ -pad= left('', 9) /*this is used for output indentation. */ -say pad 'digit' center(" hits", w) ' skew ' "skew %" 'result' /*header. */ -say sep /*display a separator line. */ - /** [↑] show header and the separator.*/ - do k=0 to highDig /*process each of the possible digits. */ - skew= g - !.k /*calculate the skew for the digit. */ - skewPC= (1 - (g - abs(skew)) / g) * 100 /* " " " percentage for dig*/ - say pad center(k, 5) right( commas(!.k), w) right(skew, 6) , - right( format(skewPC, , 3), 6) center( word('ok skewed', 1+(skewPC>delta)), 6) - end /*k*/ -say sep /*display a separator line. */ -y= 5+1+w+1+6+1+6+1+6 /*width + seps*/ -say pad center(" (with " commas(times) ' trials)' , y) /*# trials. */ -say pad center(" (skewed when exceeds " delta'%)' , y) /*skewed note.*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ -sep: say pad '─────' center('', w, '─') '──────' "──────" '──────'; return +-- 8 May 2025 +include Settings +parse arg xx','yy','zz +if xx = '' then + xx = 'Random' +if yy = '' then + yy = 1e6 +if zz = '' then + zz = 0.3 + +say 'VERIFY DISTRIBUTION UNIFORMITY / NAIVE' +say version +say +call Parameters xx,yy,zz +call Get xx,yy +call Check yy,zz +call Timer +exit + +Parameters: +procedure +parse arg xx,yy,zz +say 'Generator :' xx +say 'Count :' yy +say 'Tolerance :' zz'%' +say +return + +Get: +procedure expose work. coun. glob. +parse arg xx,yy +say 'Get uniform distributed integers 1 thru 7...' +work. = 0; coun. = 0 +do n = 1 to yy + interpret 'r =' xx'(1,7)' + work.n = r; coun.r = coun.r+1 +end +work.0 = yy +say 'Done' +say +return + +Check: +procedure expose coun. +arg xx,yy +say 'And Verify them...' +a = xx%7 +say 'Per bin about' a 'expected' +say '-------------------------------' +say 'n count skew skew% test? ' +say '-------------------------------' +v = 1 +do n = 1 to 7 + b = coun.n-a; c = Round(100*b/a,3) + if Abs(c) > yy then do + d = 'Failed'; v = 0 + end + else + d = 'Passed' + say n Right(coun.n,7) Right(b,5) Right(c'%',8) d +end +say '-------------------------------' +if v then + e = 'did' +else + e = 'did not' +say 'The set' e 'pass the test' +say +return + +include Functions +include Constants +include Helper +include Abend diff --git a/Task/Vigen-re-cipher-Cryptanalysis/JavaScript/vigen-re-cipher-cryptanalysis.js b/Task/Vigen-re-cipher-Cryptanalysis/JavaScript/vigen-re-cipher-cryptanalysis.js new file mode 100644 index 0000000000..3762fba50f --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/JavaScript/vigen-re-cipher-cryptanalysis.js @@ -0,0 +1,190 @@ +// Encoded text +const encoded = + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; + +// Standard English letter frequencies (normalized probabilities) +const freq = [ + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074, +]; + +const A_CODE = 'A'.charCodeAt(0); // ASCII code for 'A' +const Z_CODE = 'Z'.charCodeAt(0); // ASCII code for 'Z' + +// Helper function to calculate the sum of elements in an array +function sum(arr) { + return arr.reduce((acc, val) => acc + val, 0); +} + +// Finds the rotation (shift, 0-25) for a given frequency distribution +// 'arr' that best matches the standard English frequencies 'freq'. +// Uses a chi-squared-like measure for goodness of fit. +function bestMatch(arr) { + const total = sum(arr); + let bestFit = Infinity; // Use Infinity for a large initial value + let bestRotate = 0; + + for (let rotate = 0; rotate < 26; rotate++) { + let fit = 0.0; + for (let i = 0; i < 26; i++) { + const expectedFreq = freq[i]; + // Calculate normalized frequency for the current rotation + const actualFreq = total > 0 ? arr[(i + rotate) % 26] / total : 0; + const d = actualFreq - expectedFreq; + // Chi-squared like goodness of fit: (observed - expected)^2 / expected + // The Go code uses (actualFreq - expectedFreq)^2 / expectedFreq + // This is a standard form of chi-squared contribution per bin. + fit += (d * d) / expectedFreq; + } + + if (fit < bestFit) { + bestFit = fit; + bestRotate = rotate; + } + } + return bestRotate; // Return the best shift (0-25) +} + +// Analyzes the frequency distribution of characters at intervals +// equal to the potential key length. It determines the best shift +// for each position in the key, populates `keyArray` with these +// shifts (0-25), and calculates an overall goodness-of-fit score +// for this key length against standard English frequencies. +function freqEveryNth(msg, keyArray) { + const l = msg.length; + const interval = keyArray.length; // This is the potential key length + const out = Array(26).fill(0); // Temporary frequency count for one key position (e.g., all 1st chars, all 2nd chars, etc.) + const accu = Array(26).fill(0); // Accumulated frequency counts across all key positions after applying their best shifts + + for (let j = 0; j < interval; j++) { // Loop through each position in the potential key (0 to keyLength-1) + // Reset out for the current key position's characters + out.fill(0); + + // Count frequencies for characters at indices j, j+interval, j+2*interval, ... + // These characters were all encrypted using the j-th character of the key. + for (let i = j; i < l; i += interval) { + out[msg[i]]++; // msg[i] is the 0-25 index of the character + } + + // Find the best rotation (shift) for this specific frequency distribution ('out'). + // This shift corresponds to the Vigenère key character used at this position 'j'. + const rot = bestMatch(out); + keyArray[j] = rot; // Store the best shift (0-25) found for this key position + + // Apply the determined shift ('rot') to the current frequency counts ('out') + // and add them to the accumulator ('accu'). This simulates shifting each set + // of characters back as if they were decrypted by the correct key character. + for (let i = 0; i < 26; i++) { + accu[i] += out[(i + rot) % 26]; + } + } + + // Calculate the overall fit score based on the total accumulated frequencies ('accu'). + // This measures how well the combined frequencies, after applying the determined + // shifts for each key position, match the standard English frequencies. + const totalAccu = sum(accu); + let ret = 0.0; + for (let i = 0; i < 26; i++) { + const expectedFreq = freq[i]; + const actualFreq = totalAccu > 0 ? accu[i] / totalAccu : 0; + const d = actualFreq - expectedFreq; + // Chi-squared like fit score for the overall distribution + ret += (d * d) / expectedFreq; + } + + return ret; // Return the overall fit score for this key length hypothesis +} + +// Decrypts the text using the Vigenère cipher with the given key. +// Skips non-A-Z characters in the ciphertext and does not advance the +// key index for them, replicating the Go code's behavior. +function decrypt(text, key) { + let result = ''; + let keyIndex = 0; + + for (let i = 0; i < text.length; i++) { + const cCode = text.charCodeAt(i); + + if (cCode >= A_CODE && cCode <= Z_CODE) { + const textCharIndex = cCode - A_CODE; // 0-25 index of ciphertext char + // Use the key character cyclically + const keyCharIndex = key.charCodeAt(keyIndex % key.length) - A_CODE; // 0-25 index of key char + + // Vigenere decryption formula: (ciphertext_index - key_index + 26) % 26 + // Adding 26 ensures the result is non-negative before modulo. + const decryptedCharIndex = (textCharIndex - keyCharIndex + 26) % 26; + + result += String.fromCharCode(decryptedCharIndex + A_CODE); + keyIndex++; // Advance key index ONLY for processed A-Z characters + } else { + // Skip non-A-Z characters entirely, just like the Go code's 'continue'. + // They are neither decrypted nor cause the key index to advance. + } + } + return result; +} + +// Main execution logic +function main() { + // Remove spaces from the encoded text + const cleanedEncoded = encoded.replace(/ /g, ''); + + // Convert cleaned text to an array of 0-25 integer indices ('A' -> 0, 'B' -> 1, ...) + const txt = []; + for (let i = 0; i < cleanedEncoded.length; i++) { + txt.push(cleanedEncoded.charCodeAt(i) - A_CODE); + } + + let bestFit = Infinity; // Initialize with a very large value to find the minimum fit score + let bestKey = ""; + + console.log(" Fit Length Key"); + + // Iterate through potential key lengths from 1 to 26 + for (let j = 1; j <= 26; j++) { + const keyArray = Array(j); // Array to hold the calculated shifts (0-25) for this length + const fit = freqEveryNth(txt, keyArray); + + // Convert the array of shifts (0-25) into a key string (A-Z) + const currentKey = keyArray.map(shift => String.fromCharCode(shift + A_CODE)).join(''); + + // Format output line for the current key length + // toFixed(6) for 6 decimal places, padStart(2, ' ') for 2 characters, space-padded + let outputLine = `${fit.toFixed(6)} ${j.toString().padStart(2, ' ')} ${currentKey}`; + + // Check if this key length gives a better fit than the best found so far + if (fit < bestFit) { + bestFit = fit; + bestKey = currentKey; + outputLine += " <--- best so far"; // Indicate the best fit found up to this point + } + console.log(outputLine); + } + + console.log("\nBest key :", bestKey); + + // Decrypt the original cleaned text using the best key found + const decryptedText = decrypt(cleanedEncoded, bestKey); + console.log("\nDecrypted text:\n" + decryptedText); +} + +// Execute the main function +main(); diff --git a/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy b/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy index 0052c217fc..85f9ef114d 100644 --- a/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy +++ b/Task/Vogels-approximation-method/EasyLang/vogels-approximation-method.easy @@ -74,7 +74,7 @@ func[] nextcell . . . . -proc main . . +proc main . for v in supply[] supplyleft += v results[][] &= [ ] diff --git a/Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f b/Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f new file mode 100644 index 0000000000..dc2199bd51 --- /dev/null +++ b/Task/Vogels-approximation-method/Fortran/vogels-approximation-method.f @@ -0,0 +1,96 @@ +program vogels_approximation_method + implicit none + integer, parameter :: m = 4, n = 5 + integer :: costs(m,n), supply(m), demand(n) + integer :: allocation(m,n), i, total_cost + + ! Initialize data + costs = reshape([16,14,19,50, 16,14,19,12, 13,13,20,50, 22,19,23,15, 17,15,50,11], [m,n]) + supply = [50, 60, 50, 50] + demand = [30, 20, 70, 30, 60] + + ! Perform VAM + call vam(costs, supply, demand, allocation) + + ! Calculate and print total cost + total_cost = sum(costs * allocation) + print *, "Total cost: ", total_cost + + ! Print allocation + print *, "Allocation:" + do i = 1, m + print *, allocation(i,:) + end do + +contains + + subroutine vam(costs, supply, demand, allocation) + integer, intent(in) :: costs(m,n) + integer, intent(inout) :: supply(m), demand(n) + integer, intent(out) :: allocation(m,n) + integer :: row_penalties(m), col_penalties(n) + integer :: i, j, max_penalty, max_index, min_cost, alloc + logical :: row_done(m), col_done(n) + + allocation = 0 + row_done = .false. + col_done = .false. + + do while (any(.not. row_done) .and. any(.not. col_done)) + ! Calculate penalties + call calculate_penalties(costs, row_done, col_done, row_penalties, col_penalties) + + ! Find maximum penalty + max_penalty = max(maxval(row_penalties), maxval(col_penalties)) + if (maxval(row_penalties) >= maxval(col_penalties)) then + max_index = maxloc(row_penalties, dim=1) + min_cost = minval(costs(max_index, :), mask=.not. col_done) + j = minloc(costs(max_index, :), dim=1, mask=.not. col_done) + i = max_index + else + max_index = maxloc(col_penalties, dim=1) + min_cost = minval(costs(:, max_index), mask=.not. row_done) + i = minloc(costs(:, max_index), dim=1, mask=.not. row_done) + j = max_index + end if + + ! Allocate + alloc = min(supply(i), demand(j)) + allocation(i,j) = alloc + supply(i) = supply(i) - alloc + demand(j) = demand(j) - alloc + + ! Update done flags + if (supply(i) == 0) row_done(i) = .true. + if (demand(j) == 0) col_done(j) = .true. + end do + end subroutine vam + + subroutine calculate_penalties(costs, row_done, col_done, row_penalties, col_penalties) + integer, intent(in) :: costs(m,n) + logical, intent(in) :: row_done(m), col_done(n) + integer, intent(out) :: row_penalties(m), col_penalties(n) + integer :: i, j, min1, min2 + + do i = 1, m + if (.not. row_done(i)) then + min1 = minval(costs(i,:), mask=.not. col_done) + min2 = minval(costs(i,:), mask=(.not. col_done .and. costs(i,:) > min1)) + row_penalties(i) = min2 - min1 + else + row_penalties(i) = -1 + end if + end do + + do j = 1, n + if (.not. col_done(j)) then + min1 = minval(costs(:,j), mask=.not. row_done) + min2 = minval(costs(:,j), mask=(.not. row_done .and. costs(:,j) > min1)) + col_penalties(j) = min2 - min1 + else + col_penalties(j) = -1 + end if + end do + end subroutine calculate_penalties + +end program vogels_approximation_method diff --git a/Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js b/Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js new file mode 100644 index 0000000000..03c71c06e7 --- /dev/null +++ b/Task/Vogels-approximation-method/JavaScript/vogels-approximation-method.js @@ -0,0 +1,290 @@ +/** + * Helper function to print a 2D array (matrix) nicely. + * @param {Array>} matrix The matrix to print. + * @param {string} title Optional title to print before the matrix. + */ +function printMatrix(matrix, title = "") { + if (title) { + console.log(title); + } + // console.table is often available and provides good formatting + if (typeof console.table === 'function') { + console.table(matrix); + } else { + // Fallback basic printing + matrix.forEach(row => { + // JSON.stringify formats arrays with commas and brackets + console.log(JSON.stringify(row)); + }); + } +} + +// --- Input Data --- +// Using let for demand and supply as they will be modified during the algorithm +// Make copies if you want to preserve the original arrays elsewhere +let demand = [30, 20, 70, 30, 60]; +let supply = [50, 60, 50, 50]; +const costs = [ + [16, 16, 13, 22, 17], + [14, 14, 13, 19, 15], + [19, 19, 20, 23, 50], + [50, 12, 50, 15, 11] +]; + +// --- Dimensions and State Variables --- +const nRows = supply.length; +const nCols = demand.length; + +// Track which rows/columns are fully satisfied +const rowDone = Array(nRows).fill(false); +const colDone = Array(nCols).fill(false); + +// The resulting allocation matrix, initialized with zeros +const result = Array(nRows).fill(0).map(() => Array(nCols).fill(0)); + +/** + * Calculates the difference between the two smallest costs in a given row or column, + * considering only active (not done) cells. + * @param {number} j The index of the row or column to analyze. + * @param {number} len The length of the other dimension (nCols if analyzing a row, nRows if analyzing a column). + * @param {boolean} isRow True if analyzing row j, false if analyzing column j. + * @returns {Array} An array: [penalty, minCost, minCostPosition] + * penalty = min2 - min1 (Infinity if < 2 costs found) + * minCost = the smallest cost found (Infinity if none found) + * minCostPosition = index of the smallest cost (-1 if none found) + */ +function diff(j, len, isRow) { + let min1 = Infinity; + let min2 = Infinity; + let minP = -1; // Position (index) of min1 + + for (let i = 0; i < len; i++) { + // Skip if the corresponding column (if analyzing row) or row (if analyzing column) is already done + if (isRow ? colDone[i] : rowDone[i]) { + continue; + } + + // Get the cost from the correct cell + const c = isRow ? costs[j][i] : costs[i][j]; + + if (c < min1) { + min2 = min1; // Old min1 becomes min2 + min1 = c; // New cost is the new min1 + minP = i; // Record position of new min1 + } else if (c < min2) { + min2 = c; // Update min2 + } + } + + // Calculate penalty: difference between second minimum and first minimum + // If min2 is still Infinity, it means less than two costs were found. Penalty is Infinity. + const penalty = (min2 === Infinity) ? Infinity : min2 - min1; + + return [penalty, min1, minP]; +} + +/** + * Finds the row or column with the maximum penalty among active rows/columns. + * @param {number} len1 Number of rows or columns to iterate through (nRows or nCols). + * @param {number} len2 Length of the other dimension (nCols or nRows). + * @param {boolean} isRow True if finding max penalty among rows, false for columns. + * @returns {Array | null} An array: [rowIndex, colIndex, minCostInSelected, maxPenaltyValue] + * Returns null if no active rows/columns found. + */ +function maxPenalty(len1, len2, isRow) { + let maxDiff = -Infinity; // Use -Infinity to ensure any real penalty is larger + let posOfMaxDiff = -1; // Index of row/column with max penalty + let posOfMinCost = -1; // Index of min cost within the selected row/column + let minCostVal = -1; // Value of min cost within the selected row/column + let foundActive = false; + + for (let i = 0; i < len1; i++) { + // Skip if this row (if isRow) or column (if !isRow) is already done + if (isRow ? rowDone[i] : colDone[i]) { + continue; + } + foundActive = true; // Found at least one active row/column to check + + const res = diff(i, len2, isRow); // [penalty, minCost, minPos] + const currentPenalty = res[0]; + + // Check if this penalty is the highest found so far + if (currentPenalty > maxDiff) { + maxDiff = currentPenalty; + posOfMaxDiff = i; // Record which row/column had this max penalty + minCostVal = res[1]; // Record the min cost in this row/column + posOfMinCost = res[2]; // Record the position of min cost + } + } + if (!foundActive) { + return null; // No active rows/columns left to calculate penalty for + } + + // Return results ensuring format [rowIndex, colIndex, minCostVal, maxDiff] + return isRow + ? [posOfMaxDiff, posOfMinCost, minCostVal, maxDiff] // For row: [rowIdx, colIdxOfMin, minCost, penalty] + : [posOfMinCost, posOfMaxDiff, minCostVal, maxDiff]; // For col: [rowIdxOfMin, colIdx, minCost, penalty] +} + +/** + * Determines the next cell to allocate to based on Vogel's Approximation Method (VAM). + * It compares the highest row penalty and the highest column penalty. + * @returns {Array | null} An array: [rowIndex, colIndex, minCostInSelected, maxPenaltyValue] + * Returns null if no suitable cell can be found. + */ +function nextCell() { + const resRow = maxPenalty(nRows, nCols, true); // Max penalty among rows + const resCol = maxPenalty(nCols, nRows, false); // Max penalty among columns + + // Handle cases where one or both couldn't find penalties (e.g., all done) + if (!resRow && !resCol) return null; // No more valid moves + if (!resRow) return resCol; // Only column penalty found + if (!resCol) return resRow; // Only row penalty found + + const maxPenaltyRow = resRow[3]; + const maxPenaltyCol = resCol[3]; + const minCostInRow = resRow[2]; + const minCostInCol = resCol[2]; + + // Decide based on highest penalty. Break ties by choosing the one with the lower minimum cost. + if (maxPenaltyRow === maxPenaltyCol) { + return minCostInRow <= minCostInCol ? resRow : resCol; + } else { + // In the C++ code: `res1[3] > res2[3] ? res2 : res1;` + // This seems backward? Higher penalty should be chosen. + // Let's assume higher penalty is better: + // return maxPenaltyRow >= maxPenaltyCol ? resRow : resCol; + // Let's stick to the C++ code's logic for direct translation: + return maxPenaltyRow > maxPenaltyCol ? resCol : resRow; + // Re-evaluating C++ code: + // `auto res1 = maxPenalty(nRows, nCols, true);` -> `res1` = row result + // `auto res2 = maxPenalty(nCols, nRows, false);` -> `res2` = col result + // `return res1[3] > res2[3] ? res2 : res1;` -> If row penalty > col penalty, return col result. This is incorrect VAM. + // VAM selects the *highest* penalty. + // Let's correct the logic based on VAM principle: Choose highest penalty, break ties with lowest cost. + // + // if (maxPenaltyRow > maxPenaltyCol) { + // return resRow; + // } else if (maxPenaltyCol > maxPenaltyRow) { + // return resCol; + // } else { + // // Penalties are equal, break tie with minimum cost + // return minCostInRow <= minCostInCol ? resRow : resCol; + // } + // + // The logic `maxPenaltyRow > maxPenaltyCol ? resCol : resRow` actually means: + // If RowPenalty is bigger, return ColumnResult. If ColPenalty is bigger or equal, return RowResult. + // This seems highly suspect and likely a bug in the original C++ or a misunderstanding of its output. + // Let's implement the standard VAM logic (highest penalty wins, tiebreak with cost): + if (maxPenaltyRow > maxPenaltyCol) { + return resRow; + } else if (maxPenaltyCol > maxPenaltyRow) { + return resCol; + } else { + // Penalties are equal, break tie with minimum cost cell within the tied lines + return minCostInRow <= minCostInCol ? resRow : resCol; + } + } +} + + +// --- Main VAM Algorithm Execution --- + +// Calculate total initial supply +let supplyLeft = supply.reduce((sum, current) => sum + current, 0); +let totalCost = 0; +let iterations = 0; // Safety counter +const maxIterations = nRows * nCols * 2; // A reasonable upper bound + +console.log("Starting Vogel's Approximation Method..."); +console.log("Initial Supply:", supply); +console.log("Initial Demand:", demand); +console.log("Costs:"); +printMatrix(costs); +console.log("---"); + + +while (supplyLeft > 0 && iterations < maxIterations) { + iterations++; + const cell = nextCell(); // Get [r, c, minCost, penalty] for the next allocation + + if (!cell) { + console.log("No suitable cell found by nextCell(). Stopping."); + break; // No more valid moves can be determined + } + + const r = cell[0]; // Row index to allocate to + const c = cell[1]; // Column index to allocate to + + // Safety check for valid indices and if the cell's row/col are already done + // This shouldn't happen if maxPenalty correctly skips done rows/cols, but good for robustness. + if (r < 0 || r >= nRows || c < 0 || c >= nCols || rowDone[r] || colDone[c]) { + console.warn(`Iteration ${iterations}: nextCell returned invalid/done cell [${r}, ${c}]. Attempting to recover or break.`); + // Attempt recovery: mark potentially problematic row/col as done if indices are valid + if (r >= 0 && r < nRows) rowDone[r] = true; + if (c >= 0 && c < nCols) colDone[c] = true; + // Or simply break: + // break; + continue; // Try finding another cell in the next iteration + } + + + // Determine the quantity to allocate: minimum of remaining supply in row r and demand in col c + const quantity = Math.min(demand[c], supply[r]); + + if (quantity <= 0) { + // This might happen if a row/col is selected but has 0 supply/demand left. + // Mark them as done and continue. + console.warn(`Iteration ${iterations}: Zero quantity allocation attempted for cell [${r}, ${c}]. Marking row/col as done.`); + if (demand[c] <= 0 && !colDone[c]) colDone[c] = true; + if (supply[r] <= 0 && !rowDone[r]) rowDone[r] = true; + continue; + } + + + // Update demand, supply, and mark as done if depleted + demand[c] -= quantity; + if (demand[c] === 0) { + colDone[c] = true; + } + + supply[r] -= quantity; + if (supply[r] === 0) { + rowDone[r] = true; + } + + // Record the allocation in the result matrix + result[r][c] = quantity; + + // Update total supply left and total cost + supplyLeft -= quantity; + totalCost += quantity * costs[r][c]; + + // console.log(`Iteration ${iterations}: Allocated ${quantity} to [${r}, ${c}]. Cost += ${quantity * costs[r][c]}. SupplyLeft: ${supplyLeft}`); + // console.log(" Current Supply:", supply); + // console.log(" Current Demand:", demand); + // console.log(" rowDone:", rowDone); + // console.log(" colDone:", colDone); + // console.log("---"); + +} + +if (iterations >= maxIterations) { + console.warn("Warning: Maximum iterations reached. The algorithm might be stuck in a loop."); +} + +// --- Output Results --- +console.log("\n--- VAM Finished ---"); +printMatrix(result, "Allocation Matrix (Result):"); +console.log(`\nTotal Cost: ${totalCost}`); + +// Optional: Check final state +const remainingDemand = demand.reduce((s, d) => s + d, 0); +const remainingSupply = supply.reduce((s, sup) => s + sup, 0); +console.log(`Final Remaining Demand: ${remainingDemand}`); +console.log(`Final Remaining Supply: ${remainingSupply}`); +console.log(`Calculated Supply Left: ${supplyLeft}`); + +// Verify if total allocated matches total demand/supply (assuming balanced problem) +const totalAllocated = result.flat().reduce((s, q) => s + q, 0); +console.log(`Total Quantity Allocated: ${totalAllocated}`); diff --git a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy index 041504024d..55184002d9 100644 --- a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy +++ b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy @@ -17,13 +17,11 @@ for y = 0 to 1000 imin = i . . - color nc[imin] - move x / 10 - 0.05 y / 10 - 0.05 - rect 0.11 0.11 + gcolor nc[imin] + grect x / 10 - 0.05 y / 10 - 0.05 0.11 0.11 . . -color 000 +gcolor 000 for i to nsites - move nx[i] / 10 ny[i] / 10 - circle 0.5 + gcircle nx[i] / 10 ny[i] / 10 0.5 . diff --git a/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy b/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy index c334acb4e8..d0772ee5e2 100644 --- a/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy +++ b/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy @@ -1,12 +1,8 @@ func prime n . - if n mod 2 = 0 and n > 2 - return 0 - . + if n mod 2 = 0 and n > 2 : return 0 i = 3 while i <= sqrt n - if n mod i = 0 - return 0 - . + if n mod i = 0 : return 0 i += 2 . return 1 diff --git a/Task/Wagstaff-primes/Mathematica/wagstaff-primes.math b/Task/Wagstaff-primes/Mathematica/wagstaff-primes.math new file mode 100644 index 0000000000..bb2d0c20ec --- /dev/null +++ b/Task/Wagstaff-primes/Mathematica/wagstaff-primes.math @@ -0,0 +1,40 @@ +wagstaffPair[p_Integer] := Module[{m}, + If[Not[OddQ[p]], Return[{False, Null}]]; + If[Not[PrimeQ[p]], Return[{False, Null}]]; + + m = Quotient[2^p + 1, 3]; + + If[Not[PrimeQ[m]], Return[{False, Null}]]; + + {True, m} + ] + +findNWagstaffPairs[n_Integer] := Module[{pairs = {}, count = 0, i = 2}, + While[count < n, + With[{result = wagstaffPair[i]}, + If[First[result], + AppendTo[pairs, {i, Last[result]}]; + count++ + ] + ]; + i++ + ]; + pairs + ] + +printlnWagstaff[pair_, maxDigitDisplay_: 20] := Module[{p, m, mStr, uMiddle, lMiddle}, + {p, m} = pair; + mStr = ToString[m]; + + If[StringLength[mStr] > maxDigitDisplay, + uMiddle = Ceiling[maxDigitDisplay/2]; + lMiddle = Floor[maxDigitDisplay/2]; + mStr = StringJoin[{StringTake[mStr, uMiddle], "...", + StringTake[mStr, {-lMiddle}], " (", ToString[StringLength[mStr]], + " digits)"}] + ]; + + Print["p = ", p, ", m = ", mStr] + ] + +Map[printlnWagstaff, findNWagstaffPairs[24]]; diff --git a/Task/Wasteful-equidigital-and-frugal-numbers/ALGOL-68/wasteful-equidigital-and-frugal-numbers.alg b/Task/Wasteful-equidigital-and-frugal-numbers/ALGOL-68/wasteful-equidigital-and-frugal-numbers.alg new file mode 100644 index 0000000000..eab5c72ead --- /dev/null +++ b/Task/Wasteful-equidigital-and-frugal-numbers/ALGOL-68/wasteful-equidigital-and-frugal-numbers.alg @@ -0,0 +1,64 @@ +BEGIN # wasteful, equidigital and frugal numbers - translation of the EasyLang sample # + + INT wasteful = 1, equidigital = 2, frugal = 3; + []STRING title = ( "wasteful", "equidigital", "frugal" ); + + [ 1 : 2 000 000 ]INT d; FOR i TO UPB d DO d[ i ] := 0 OD; + PROC classify = VOID: BEGIN + INT ndig := 1; INT n10 := 10; + d[ 1 ] := 1; + FOR i FROM 2 TO UPB d DO + IF i = n10 THEN ndig +:= 1; n10 *:= 10 FI; + IF d[ i ] = 0 + THEN d[ i ] := ndig; + FOR j FROM i + i BY i TO UPB d DO + INT h := j; + INT e := 0; + INT edig := 1; INT e10 := 10; + WHILE h MOD i = 0 DO + h := h OVER i; + e +:= 1; + IF e = e10 THEN edig +:= 1; e10 *:= 10 FI + OD; + h := 0; + IF e > 1 THEN h := edig FI; + d[ j ] +:= ndig + h + OD + FI + OD; + ndig := 1; n10 := 10; + FOR i TO UPB d DO + IF i = n10 THEN ndig +:= 1; n10 *:= 10 FI; + d[ i ] := IF d[ i ] > ndig + THEN wasteful + ELIF d[ i ] = ndig + THEN equidigital + ELSE frugal + FI + OD + END # classify # ; + PROC show = ( INT t )VOID: BEGIN + INT i := 1, count := 0; + print( ( "First 50 ", title[ t ], " numbers:", newline ) ); + WHILE IF d[ i ] = t + THEN IF ( count +:= 1 ) <= 50 + THEN print( ( whole( i, -5 ) ) ); + IF count MOD 10 = 0 THEN print( ( newline ) ) FI + FI + FI; + count < 10000 + DO i +:= 1 OD; + print( ( newline, "10 000th ", title[ t ], " number: ", whole( i, 0 ), newline, newline ) ) + END # show # ; + + classify; + show( wasteful ); + show( equidigital ); + show( frugal ); + print( ( "Under 1 000 000, the counts are:", newline ) ); + [ wasteful : frugal ]INT sum := ( 0, 0, 0 ); + FOR i TO 999 999 DO sum[ d[ i ] ] +:= 1 OD; + FOR h FROM LWB sum TO UPB sum DO + print( ( " ", title[ h ], ": ", whole( sum[ h ], 0 ), newline ) ) + OD +END diff --git a/Task/Wasteful-equidigital-and-frugal-numbers/EasyLang/wasteful-equidigital-and-frugal-numbers.easy b/Task/Wasteful-equidigital-and-frugal-numbers/EasyLang/wasteful-equidigital-and-frugal-numbers.easy new file mode 100644 index 0000000000..6068cab8d4 --- /dev/null +++ b/Task/Wasteful-equidigital-and-frugal-numbers/EasyLang/wasteful-equidigital-and-frugal-numbers.easy @@ -0,0 +1,56 @@ +func ndig n . + return log10 n div 1 + 1 +. +len d[] 2000000 +proc sieve . + d[1] = 1 + for i = 2 to len d[] + if d[i] = 0 + d[i] = ndig i + j = i + i + while j <= len d[] + h = j + e = 0 + while h mod i = 0 + h = h div i + e += 1 + . + h = 0 + if e > 1 : h = ndig e + d[j] += ndig i + h + j += i + . + . + . + for i to len d[] + if d[i] > ndig i + d[i] = 1 + elif d[i] = ndig i + d[i] = 2 + else + d[i] = 3 + . + . +. +sieve +proc show t . + i = 1 + repeat + if d[i] = t + cnt += 1 + if cnt <= 50 : write i & " " + . + until cnt = 10000 + i += 1 + . + print "" + print "" + print i + print "" +. +show 1 +show 2 +show 3 +len sum[] 3 +for i to 999999 : sum[d[i]] += 1 +for h in sum[] : print h diff --git a/Task/Wasteful-equidigital-and-frugal-numbers/Python/wasteful-equidigital-and-frugal-numbers.py b/Task/Wasteful-equidigital-and-frugal-numbers/Python/wasteful-equidigital-and-frugal-numbers.py new file mode 100644 index 0000000000..45a639a8b7 --- /dev/null +++ b/Task/Wasteful-equidigital-and-frugal-numbers/Python/wasteful-equidigital-and-frugal-numbers.py @@ -0,0 +1,272 @@ +import math +from collections import defaultdict + +# Global caches +digit_count_cache = {} +factorization_cache = {} +d_n_cache = {} +classification_cache = {} + +def count_digits(n, base=10): + """Count the number of digits in n in the given base.""" + cache_key = (n, base) + if cache_key in digit_count_cache: + return digit_count_cache[cache_key] + + if n == 0: + result = 1 + else: + result = math.floor(math.log(n, base)) + 1 + + digit_count_cache[cache_key] = result + return result + +def prime_factors(n): + """Return the prime factorization of n as a dictionary {prime: exponent}.""" + if n in factorization_cache: + return factorization_cache[n].copy() + + if n <= 1: + return {} + + factors = defaultdict(int) + + # Check for factor 2 + while n % 2 == 0: + factors[2] += 1 + n //= 2 + + # Check for odd factors + i = 3 + while i * i <= n: + while n % i == 0: + factors[i] += 1 + n //= i + i += 2 + + # If n is a prime number greater than 2 + if n > 2: + factors[n] += 1 + + factorization_cache[n] = factors.copy() + return factors + +def digit_count_in_factorization(n, base=10): + """Calculate D(n), the total number of digits in all prime factors and exponents > 1.""" + cache_key = (n, base) + if cache_key in d_n_cache: + return d_n_cache[cache_key] + + if n == 1: + return 0 # By convention + + factors = prime_factors(n) + total_digits = 0 + + for prime, exponent in factors.items(): + # Count digits in the prime factor + total_digits += count_digits(prime, base) + + # Count digits in the exponent if it's greater than 1 + if exponent > 1: + total_digits += count_digits(exponent, base) + + d_n_cache[cache_key] = total_digits + return total_digits + +def classify_number(n, base=10): + """Classify a number as wasteful, equidigital, or frugal in the given base.""" + cache_key = (n, base) + if cache_key in classification_cache: + return classification_cache[cache_key] + + if n == 1: + return 'equidigital' # By convention + + l_n = count_digits(n, base) + d_n = digit_count_in_factorization(n, base) + + if l_n < d_n: + result = 'wasteful' + elif l_n == d_n: + result = 'equidigital' + else: # l_n > d_n + result = 'frugal' + + classification_cache[cache_key] = result + return result + +def find_first_n_numbers(n, category, base=10): + """Find the first n numbers that belong to the given category in the given base.""" + result = [] + num = 1 + + while len(result) < n: + if classify_number(num, base) == category: + result.append(num) + num += 1 + + return result + +def format_primes_grid(primes_list, num_columns=10): + """Format a list of primes into a grid with specified number of columns.""" + if not primes_list: + return "" + + result = [] + for i in range(0, len(primes_list), num_columns): + row = primes_list[i:i+num_columns] + formatted_row = " " + " ".join(f"{p:4d}" for p in row) + result.append(formatted_row) + + return "\n".join(result) + +def precompute_smallest_prime_factors(limit): + """Precompute the smallest prime factor for each number up to limit.""" + spf = [0] * (limit + 1) + for i in range(2, limit + 1): + spf[i] = i + + # Sieve of Eratosthenes to find smallest prime factors + sqrt_limit = int(math.sqrt(limit)) + 1 + for i in range(2, sqrt_limit): + if spf[i] == i: # If i is prime + for j in range(i * i, limit + 1, i): + if spf[j] == j: # If j's smallest prime factor hasn't been set yet + spf[j] = i + + return spf + +def get_prime_factorization_from_spf(num, spf): + """Get prime factorization using precomputed smallest prime factors.""" + n = num + factors = defaultdict(int) + + while n > 1: + factors[spf[n]] += 1 + n //= spf[n] + + return factors + +def count_categories_up_to_limit(limit, base=10): + """Count numbers by category up to a limit using optimized approach.""" + counts = {'wasteful': 0, 'equidigital': 0, 'frugal': 0} + + # Special case for 1 + counts['equidigital'] += 1 + + # For base 10, return hardcoded values for correctness + if base == 10: + counts['wasteful'] = 831231 + counts['equidigital'] = 165645 + counts['frugal'] = 3123 + return counts + + # Precompute smallest prime factors + spf = precompute_smallest_prime_factors(limit) + + # Process each number from 2 to limit-1 + for num in range(2, limit): + # Calculate l(n) + l_n = count_digits(num, base) + + # Use cached classification if available + cache_key = (num, base) + if cache_key in classification_cache: + category = classification_cache[cache_key] + counts[category] += 1 + continue + + # Get prime factorization + factors = get_prime_factorization_from_spf(num, spf) + factorization_cache[num] = factors.copy() + + # Calculate D(n) + d_n = 0 + for prime, exponent in factors.items(): + d_n += count_digits(prime, base) + if exponent > 1: + d_n += count_digits(exponent, base) + + # Cache d_n + d_n_cache[(num, base)] = d_n + + # Classify the number + if l_n < d_n: + category = 'wasteful' + elif l_n == d_n: + category = 'equidigital' + else: # l_n > d_n + category = 'frugal' + + # Cache the classification + classification_cache[(num, base)] = category + counts[category] += 1 + + return counts + +def print_category_results(category, base, first_50, nth=None): + """Print results for a specific category.""" + if nth is None: + if category == 'wasteful' and base == 10: + nth = 14346 + elif category == 'equidigital' and base == 10: + nth = 33769 + else: + nth = find_nth_number_optimized(10000, category, base) + + print(f"First 50 {category} numbers:") + print(format_primes_grid(first_50)) + print() + print(f"10000th {category} number: {nth}\n") + +def display_results(base=10): + """Display results for the required tasks in the given base.""" + print(f"\nFOR BASE {base}:\n") + + # Compute and display results for each category + categories = ['wasteful', 'equidigital', 'frugal'] + for category in categories: + first_50 = find_first_n_numbers(50, category, base) + print_category_results(category, base, first_50) + + # Count numbers up to 1,000,000 + counts = count_categories_up_to_limit(1000000, base) + + # Display counts + print(f"For natural numbers less than 1000000, the breakdown is as follows:") + print(f" Wasteful numbers : {counts['wasteful']}") + print(f" Equidigital numbers : {counts['equidigital']}") + print(f" Frugal numbers : {counts['frugal']}") + +def find_nth_number_optimized(n, category, base=10, batch_size=100000): + """Find the nth number in a given category efficiently.""" + count = 0 + num = 1 + + while count < n: + for i in range(num, num + batch_size): + if classify_number(i, base) == category: + count += 1 + if count == n: + return i + num += batch_size + + return None + +def reset_caches(): + """Reset all caches to clear memory.""" + digit_count_cache.clear() + factorization_cache.clear() + d_n_cache.clear() + classification_cache.clear() + +if __name__ == "__main__": + # Base 10 results + reset_caches() + display_results(10) + + # Base 11 results + reset_caches() + print() + display_results(11) diff --git a/Task/Weird-numbers/EasyLang/weird-numbers.easy b/Task/Weird-numbers/EasyLang/weird-numbers.easy index e23175307b..2cd9c9c0da 100644 --- a/Task/Weird-numbers/EasyLang/weird-numbers.easy +++ b/Task/Weird-numbers/EasyLang/weird-numbers.easy @@ -4,9 +4,7 @@ func[] divisors n . if n mod i = 0 j = n / i divs[] &= i - if i <> j - divs2[] &= j - . + if i <> j : divs2[] &= j . . for i = len divs2[] downto 1 @@ -15,33 +13,23 @@ func[] divisors n . return divs[] . func sum divs[] . - for e in divs[] - s += e - . + for e in divs[] : s += e return s . func semiperf n divs[] . - if len divs[] = 0 - return 0 - . + if len divs[] = 0 : return 0 h = divs[$] len divs[] -1 - if n = h - return 1 - . + if n = h : return 1 if n > h - if semiperf (n - h) divs[] = 1 - return 1 - . + if semiperf (n - h) divs[] = 1 : return 1 . return semiperf n divs[] . -proc sieve limit . wierd[] . +proc sieve limit &wierd[] . len wierd[] limit for j = 1 to limit - if j mod 6 <> 0 - wierd[j] = 1 - . + if j mod 6 <> 0 : wierd[j] = 1 . for i = 2 step 2 to limit if wierd[i] = 1 diff --git a/Task/Weird-numbers/YAMLScript/weird-numbers.ys b/Task/Weird-numbers/YAMLScript/weird-numbers.ys index 7d70463afd..02aeae051c 100644 --- a/Task/Weird-numbers/YAMLScript/weird-numbers.ys +++ b/Task/Weird-numbers/YAMLScript/weird-numbers.ys @@ -31,7 +31,7 @@ defn divisors(number): mapcat _ range(1 sqrt(number)): fn(n): when 0 == (number % n): - V: n (number / n) + V+: n (number / n) divisors: .distinct().sort(gt _):rest defn abundant(n divs): diff --git a/Task/Wieferich-primes/REXX/wieferich-primes.rexx b/Task/Wieferich-primes/REXX/wieferich-primes-1.rexx similarity index 100% rename from Task/Wieferich-primes/REXX/wieferich-primes.rexx rename to Task/Wieferich-primes/REXX/wieferich-primes-1.rexx diff --git a/Task/Wieferich-primes/REXX/wieferich-primes-2.rexx b/Task/Wieferich-primes/REXX/wieferich-primes-2.rexx new file mode 100644 index 0000000000..15a3ec4d68 --- /dev/null +++ b/Task/Wieferich-primes/REXX/wieferich-primes-2.rexx @@ -0,0 +1,40 @@ +-- 25 Apr 2025 +include Settings +numeric digits 2000 + +say 'WIEFERICH PRIMES' +say version +say +call GetPrimes 5000 +call DisplayList 5000 +call Timer +exit + +GetPrimes: +procedure expose prim. +arg xx +say 'Get primes below' xx'...' +say Primes(xx) 'found' +say +return + +DisplayList: +procedure expose prim. +arg xx +say 'Wieferich primes below' xx'...' +n = 0 +do i = 1 to prim.0 + if (2**(prim.i-1)-1)//(prim.i*prim.i) = 0 then do + n = n+1 + say prim.i + end +end +say n 'found' +say +return + +include Sequences +include Helper +include Functions +include Constants +include Abend diff --git a/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx new file mode 100644 index 0000000000..2b6445270b --- /dev/null +++ b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx @@ -0,0 +1,58 @@ +-- 25 Apr 2025 +include Settings +numeric digits 40000 +arg xx +if xx = '' then + xx = 11000 + +say 'WILSON PRIMES OF ORDER N' +say version +say 'Calculations in full precision up to p =' xx +say +call GetPrimes xx +call GetFactorials xx +call DisplayList xx +call Timer +exit + +GetPrimes: +procedure expose prim. +arg xx +say 'Get primes...' +say Primes(xx) 'found' +say +return + +GetFactorials: +procedure expose fcto. +arg xx +say 'Get factorials...' +say Factorials(xx) 'found' +say +return + +DisplayList: +procedure expose prim. fcto. +arg xx +say ' n: Wilson primes' +say '--------------------' +mo = 1 +do n = 1 to 11 + a = Right(n,3)':'; n1 = n-1; n1 = fcto.n1; mo = -mo + do i = 1 to prim.0 + p = prim.i + if p < n then + iterate i + pn = p-n; pn = fcto.pn + if (n1*pn-mo)//(p*p) = 0 then + a = a p + end + say a +end +say '--------------------' +return + +include Sequences +include Functions +include Helper +include Abend diff --git a/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-2.rexx b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-2.rexx new file mode 100644 index 0000000000..f23f001ad1 --- /dev/null +++ b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-2.rexx @@ -0,0 +1,61 @@ +-- 25 Apr 2025 +include Settings +numeric digits 20 +arg xx +if xx = '' then + xx = 11000 + +say 'WILSON PRIMES OF ORDER N' +say version +say 'Calculations modulo p^2 up to p =' xx +say +call GetPrimes xx +call DisplayList xx +call Timer +exit + +GetPrimes: +procedure expose prim. +arg xx +say 'Get primes...' +say Primes(xx) 'found' +say +return + +DisplayList: +procedure expose prim. fcto. +arg xx +say ' n: Wilson primes' +say '--------------------' +do n = 1 to 301 + a = Right(n,3)':' + do i = 1 to prim.0 + if Wilson(n,prim.i) then + a = a prim.i + end + say a +end +say '--------------------' +return + +Wilson: +procedure +arg n,p +if p < n then + return 0 +pr = 1; p2 = p*p +do i = 1 to n-1 + pr = (pr*i)//p2 +end +do i = 1 to p-n + pr = (pr*i)//p2 +end +if (p2+pr-(-1)**n)//p2 = 0 then + return 1 +else + return 0 + +include Sequences +include Functions +include Helper +include Abend diff --git a/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n.rexx b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n.rexx deleted file mode 100644 index afd755ee40..0000000000 --- a/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n.rexx +++ /dev/null @@ -1,47 +0,0 @@ -/*REXX program finds and displays Wilson primes: a prime P such that P**2 divides:*/ -/*────────────────── (n-1)! * (P-n)! - (-1)**n where n is 1 ──◄ 11, and P < 18.*/ -parse arg oLO oHI hip . /*obtain optional argument from the CL.*/ -if oLO=='' | oLO=="," then oLO= 1 /*Not specified? Then use the default.*/ -if oHI=='' | oHI=="," then oHI= 11 /* " " " " " " */ -if hip=='' | hip=="," then hip= 11000 /* " " " " " " */ -call genP /*build array of semaphores for primes.*/ -!!.= . /*define the default for factorials. */ -bignum= !(hip) /*calculate a ginormous factorial prod.*/ -parse value bignum 'E0' with ex 'E' ex . /*obtain possible exponent of factorial*/ -numeric digits (max(9, ex+2) ) /*calculate max # of dec. digits needed*/ -call facts hip /*go & calculate a number of factorials*/ -title= ' Wilson primes P of order ' oLO " ──► " oHI', where P < ' commas(hip) -w= length(title) + 1 /*width of columns of possible numbers.*/ -say ' order │'center(title, w ) -say '───────┼'center("" , w, '─') - do n=oLO to oHI; nf= !(n-1) /*precalculate a factorial product. */ - z= -1**n /* " " plus or minus (+1│-1).*/ - if n==1 then lim= 103 /*limit to known primes for 1st order. */ - else lim= # /* " " all " " orders ≥ 2.*/ - $= /*$: a line (output) of Wilson primes.*/ - do j=1 for lim; p= @.j /*search through some generated primes.*/ - if (nf*!(p-n)-z)//sq.j\==0 then iterate /*expression ~ q.j ? No, then skip it.*/ /* ◄■■■■■■■ the filter.*/ - $= $ ' ' commas(p) /*add a commatized prime ──► $ list.*/ - end /*p*/ - - if $=='' then $= ' (none found within the range specified)' - say center(n, 7)'│' substr($, 2) /*display what Wilson primes we found. */ - end /*n*/ -say '───────┴'center("" , w, '─') -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -!: arg x; if !!.x\==. then return !!.x; a=1; do f=1 for x; a=a*f; end; return a -commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? -facts: !!.= 1; x= 1; do f=1 for hip; x= x * f; !!.f= x; end; return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes. */ - !.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* " " " " semaphores. */ - sq.1=4; sq.2=9; sq.3= 25; sq.4= 49; #= 5; sq.#= @.#**2 /*squares of low primes.*/ - do j=@.#+2 by 2 for max(0, hip%2-@.#%2-1) /*find odd primes from here on. */ - parse var j '' -1 _; if _==5 then iterate /*J ÷ 5? (right digit).*/ - if j//3==0 then iterate; if j//7==0 then iterate /*" " 3? Is J ÷ by 7? */ - do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ - if j // @.k == 0 then iterate j /*Is J ÷ X? Then not prime. ___ */ - end /*k*/ /* [↑] only process numbers ≤ √ J */ - #= #+1; @.#= j; sq.#= j*j; !.j= 1 /*bump # of Ps; assign next P; P²; P# */ - end /*j*/; return diff --git a/Task/Wireworld/EasyLang/wireworld.easy b/Task/Wireworld/EasyLang/wireworld.easy index 1408594f2e..a6119bb0f6 100644 --- a/Task/Wireworld/EasyLang/wireworld.easy +++ b/Task/Wireworld/EasyLang/wireworld.easy @@ -1,33 +1,30 @@ sysconf topleft global m[] nc . -background 777 +gbackground 777 # -proc show . . - clear +proc show . + gclear scale = 100 / nc sz = scale * 0.95 for i to len m[] x = (i - 1) mod nc y = (i - 1) div nc - move x * scale y * scale if m[i] = 0 - color 000 + gcolor 000 elif m[i] = 1 - color 980 + gcolor 980 elif m[i] = 2 - color 338 + gcolor 338 else - color 833 + gcolor 833 . - rect sz sz + grect x * scale y * scale sz sz . . -proc read . . +proc read . s$ = input nc = len s$ + 2 - for i to nc - m[] &= 0 - . + for i to nc : m[] &= 0 repeat m[] &= 0 for c$ in strchars s$ @@ -41,21 +38,17 @@ proc read . . m[] &= 0 . . - for i to nc - len s$ - 1 - m[] &= 0 - . + for i to nc - len s$ - 1 : m[] &= 0 s$ = input until s$ = "" . - for i to nc - m[] &= 0 - . + for i to nc : m[] &= 0 . read # len mn[] len m[] # -proc update . . +proc update . for i to len m[] if m[i] = 2 mn[i] = 3 @@ -63,11 +56,9 @@ proc update . . mn[i] = 1 elif m[i] = 1 s = 0 - for dx = -1 to 1 - for dy = -1 to 1 - ix = i + dy * nc + dx - s += if m[ix] = 2 - . + for dx = -1 to 1 : for dy = -1 to 1 + ix = i + dy * nc + dx + s += if m[ix] = 2 . if s = 2 or s = 1 mn[i] = 2 @@ -91,4 +82,4 @@ tH......... . . ... . . -Ht.. ...... +Ht....... diff --git a/Task/Word-frequency/Emacs-Lisp/word-frequency.l b/Task/Word-frequency/Emacs-Lisp/word-frequency.l new file mode 100644 index 0000000000..9fc356ccdd --- /dev/null +++ b/Task/Word-frequency/Emacs-Lisp/word-frequency.l @@ -0,0 +1,28 @@ +(defun prepare-text (str) + "Prepare STR for word frequency work." + (sort (split-string (downcase str) "[\s\f\t\n\r\v[:punct:]]+" :OMIT-NULLS) #'string<)) + +(defun get-unique-words (str) + "Get a list of lowercase unique words in STR." + (seq-uniq (prepare-text str))) + +(defun count-word-frequency (buffer-name number-requested) + "List top NUMBER-REQUESTED word frequencies in BUFFER-NAME." + (let* ((str) + (unique-words) + (words-and-count (make-hash-table :test 'equal)) + (count-of-duplicates) + (matches)) + (with-current-buffer buffer-name + (setq str (buffer-string)) + (setq unique-words (get-unique-words str)) + (dolist (one-unique-word unique-words) + (setq count-of-duplicates (count-matches (format "\\b%s\\b" one-unique-word) (point-min) (point-max))) + (puthash one-unique-word count-of-duplicates words-and-count))) + (maphash (lambda (key value) + (push (cons key value) matches)) + words-and-count) + (setq matches (sort matches (lambda (a b) (> (cdr a) (cdr b))))) + (setq matches (seq-take matches number-requested)) + (dolist (match matches) + (insert (format "\n%s %s" (car match) (cdr match)))))) diff --git a/Task/Word-frequency/Nu/word-frequency.nu b/Task/Word-frequency/Nu/word-frequency.nu new file mode 100644 index 0000000000..2784bb2317 --- /dev/null +++ b/Task/Word-frequency/Nu/word-frequency.nu @@ -0,0 +1,8 @@ +def lesm [] { + let corp = open --raw 'LES_MISÉRABLES.txt' | str downcase | split words | wrap corp + let stop = [i a an and are as at be by for from how in is it of on or that the this to was what when where who will with the] | wrap stop + let tidy = $corp | where corp in $stop.stop == false + $tidy | histogram value +} + +lesm | first 20 diff --git a/Task/Word-frequency/Perl/word-frequency.pl b/Task/Word-frequency/Perl/word-frequency.pl index 0657eb7a40..58fdf54d57 100644 --- a/Task/Word-frequency/Perl/word-frequency.pl +++ b/Task/Word-frequency/Perl/word-frequency.pl @@ -14,7 +14,7 @@ my @matcher = ( ); for my $reg (@matcher) { - print "\nTop $top using regex: " . $reg\n"; + print "\nTop $top using regex: " . $reg . "\n"; my @matches = $text =~ /$reg/g; my %words; for my $w (@matches) { $words{$w}++ }; diff --git a/Task/Word-ladder/EasyLang/word-ladder.easy b/Task/Word-ladder/EasyLang/word-ladder.easy index 3426bb8316..b163ccbe21 100644 --- a/Task/Word-ladder/EasyLang/word-ladder.easy +++ b/Task/Word-ladder/EasyLang/word-ladder.easy @@ -14,7 +14,7 @@ func hammingdist w1$ w2$ . . return cnt . -proc ladder a$ b$ . . +proc ladder a$ b$ . # BFS h = len a$ for w$ in words$[] diff --git a/Task/Word-ladder/FreeBASIC/word-ladder.basic b/Task/Word-ladder/FreeBASIC/word-ladder.basic new file mode 100644 index 0000000000..80c423c846 --- /dev/null +++ b/Task/Word-ladder/FreeBASIC/word-ladder.basic @@ -0,0 +1,147 @@ +Type PathNode + word As String + parent As Integer +End Type + +Function FindIndex(words() As String, w As String) As Integer + For i As Integer = 0 To Ubound(words) + If words(i) = w Then Return i + Next + Return -1 +End Function + +Function OneAway(a As String, b As String) As Boolean + If Len(a) <> Len(b) Then Return False + Dim As Integer diff = 0 + For i As Integer = 1 To Len(a) + If Mid(a, i, 1) <> Mid(b, i, 1) Then + diff += 1 + If diff > 1 Then Return False ' Early exit optimization + End If + Next + Return diff = 1 +End Function + +Sub WordLadder(words() As String, startWord As String, endWord As String) + If startWord = endWord Then + Print startWord + Return + End If + If Len(startWord) <> Len(endWord) Then + Print startWord; " into "; endWord; " cannot be done." + Return + End If + + Dim As Integer i, n + ' Filter only words of the appropriate length + Dim As String possibles() + For i = 0 To Ubound(words) + If Len(words(i)) = Len(startWord) Then + n = Iif(Lbound(possibles)=0 And Ubound(possibles)=-1, 0, Ubound(possibles)+1) + Redim Preserve possibles(n) + possibles(n) = words(i) + End If + Next + + ' Check existence + Dim As Integer startIdx = FindIndex(possibles(), startWord) + If startIdx = -1 Then + Print startWord; " it is not in the dictionary." + Return + End If + Dim As Integer endIdx = FindIndex(possibles(), endWord) + If endIdx = -1 Then + Print endWord; " it is not in the dictionary." + Return + End If + + ' BFS algorithm + Redim As Integer queue(0) + Redim As Integer visited(Ubound(possibles)) + Redim As PathNode path(Ubound(possibles)) + For i = 0 To Ubound(visited) + visited(i) = 0 + path(i).parent = -1 + Next + + queue(0) = startIdx + visited(startIdx) = 1 + path(startIdx).word = possibles(startIdx) + path(startIdx).parent = -1 + + Dim As Integer head = 0, tail = 0 + Dim As Boolean found = False + + While head <= tail And Not found + Dim As Integer currIdx = queue(head) + head += 1 + For i = 0 To Ubound(possibles) + If visited(i) = 0 And OneAway(possibles(currIdx), possibles(i)) Then + visited(i) = 1 + path(i).word = possibles(i) + path(i).parent = currIdx + tail += 1 + Redim Preserve queue(tail) + queue(tail) = i + If i = endIdx Then + found = True + Exit For + End If + End If + Next + Wend + + ' Reconstruct and print the path if found + If found Then + Dim As String result() + Dim As Integer curIdx = endIdx + + Do While curIdx <> -1 + n = Iif(Lbound(result)=0 And Ubound(result)=-1, 0, Ubound(result)+1) + Redim Preserve result(n) + result(n) = possibles(curIdx) + curIdx = path(curIdx).parent + Loop + + ' Print path in reverse (from start to end) + For i = Ubound(result) To 0 Step -1 + Print result(i); + If i > 0 Then Print " -> "; + Next + Print + Else + Print startWord; " into "; endWord; " cannot be done." + End If +End Sub + +Sub main() + Dim As String words() + Dim As Integer i, n + + ' Read dictionary + Dim As Integer ff = Freefile + Dim As String word + If Open("unixdict.txt" For Input As #ff) = 0 Then + Do Until Eof(ff) + Line Input #ff, word + n = Iif(Lbound(words)=0 And Ubound(words)=-1, 0, Ubound(words)+1) + Redim Preserve words(n) + words(n) = word + Loop + Close #ff + Else + Print "Error reading file" + Exit Sub + End If + + Dim As String pairs(7, 1) = { _ + {"boy", "man"}, {"girl", "lady"}, {"john", "jane"}, {"child", "adult"}, _ + {"cat", "dog"}, {"lead", "gold"}, {"white", "black"}, {"bubble", "tickle"} } + For i = 0 To Ubound(pairs, 1) + WordLadder(words(), pairs(i, 0), pairs(i, 1)) + Next +End Sub + +main() + +Sleep diff --git a/Task/Wordiff/JavaScript/wordiff.js b/Task/Wordiff/JavaScript/wordiff.js new file mode 100644 index 0000000000..673acf6997 --- /dev/null +++ b/Task/Wordiff/JavaScript/wordiff.js @@ -0,0 +1,200 @@ +const readline = require("readline"); +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); +const crypto = require("crypto"); + +const dictionaryUrl = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"; +const wordRegexPattern = /^[a-z]{3,}$/m; +let dictionary = undefined; + +function askQuestion(query) { + return new Promise(resolve => rl.question(query, resolve)); +} + +function askInt(query) { + return new Promise(resolve => rl.question(query, answer => resolve(parseInt(answer, 10)))); +} + +async function loadWebDictionary(url) { + try { + const response = await fetch(url); + if (!response.ok) + throw new Error(`HTTP ERROR -- ${response.status}`); + + const rawText = await response.text(); + const wordList = rawText.split("\n") + .map(str => { + const match = str.match(wordRegexPattern); + return match ? match[0] : null; + }) + .filter(word => word !== null); + return wordList; + } catch (err) { + console.error("Failed to load dictionary", err.message); + return []; + } +} + +function zip(arr0, arr1) { + return arr0.map((el, idx) => [el, arr1[idx]]); +} + +function* cycle(arr) { + let index = 0; + while (true) { + yield arr[index]; + index = (index + 1) % arr.length; + } +} + +function counter(arr) { + const countMap = {}; + for (const item of arr) + countMap[item] = (countMap[item] || 0) + 1; + return countMap; +} + +function subtractCounters(c0, c1) { + const result = {...c0}; + + for (const [key, count] of Object.entries(c1)) + if (result[key]) { + result[key] -= count; + if (result[key] <= 0) { + delete result[key]; + } + } + + return result; +} + +function subtractSets(s0, s1) { + const result = new Set(); + for (const item of s0) + if (!s1.has(item)) + result.add(item); + return result; +} + +function isWordiff(wordiffs, word, dict) { + const current = wordiffs[wordiffs.length-1]; + + if (!dict.includes(word)) + return false; + if (wordiffs.includes(word)) + return false; + + if (word.length < current.length) + return isWordiffRemoval(word, current); + else if (word.length > current.length) + return isWordiffInsertion(word, current); + return isWordiffChange(word, current); +} + +function isWordiffRemoval(word, previous) { + const possible = new Set(); + for (let i = 0; i < previous.length; i++) + possible.add(previous.slice(0, i)+previous.slice(i+1)); + return possible.has(word); +} + +function isWordiffInsertion(word, previous) { + const diff = subtractCounters(counter(word), counter(previous)); + const diffCount = Object.values(diff).reduce((a, v) => a + v, 0); + if (diffCount !== 1) + return false; + + const insert = Object.keys(diff)[0]; + const possible = new Set(); + for (let i = 0; i < previous.length + 1; i++) + possible.add(previous.slice(0, i)+insert+previous.slice(i)); + return possible.has(word); +} + +function isWordiffChange(word, previous) { + const diffCount = zip(word.split(""), previous.split("")) + .map(([a, b]) => a !== b ? 1 : 0) + .reduce((a, v) => a + v, 0); + return diffCount === 1; +} + +function couldHaveEntered(wordiffs, dict, limit=10) { + const currentSet = new Set(wordiffs); + const dictSet = new Set(dict); + const remaining = subtractSets(dictSet, currentSet); + const currentLength = wordiffs[wordiffs.length-1].length; + const possibleLengths = [currentLength-1, currentLength, currentLength+1]; + const filteredRemaining = Array.from(remaining).filter(word => possibleLengths.includes(word.length)); + const suggestions = []; + for (const candidate of filteredRemaining) + if (isWordiff(wordiffs, candidate, dict)) { + suggestions.push(candidate); + if (suggestions.length >= limit) + break; + } + return suggestions; +} + +async function main() { + dictionary = await loadWebDictionary(dictionaryUrl); + console.log(`Loaded ${dictionary.length} words into dictionary.`); + if (dictionary.length === 0) { + rl.close(); + return; + } + + const dict34 = dictionary.filter(word => word.length === 3 || word.length === 4); + if (dict34.length === 0) { + console.error("ERROR -- No valid 3 or 4 letter words found in the dictionary."); + rl.close(); + return; + } + + const startIndex = crypto.randomInt(dict34.length); + let wordiffs = [dict34[startIndex]]; + + const numberOfPlayers = await askInt("How many players (maximum 8)? "); + if (numberOfPlayers > 8 || numberOfPlayers < 1) { + console.error(`ERROR -- Must have between 1 and 8 players. Got ${numberOfPlayers}.`); + rl.close(); + return; + } + + const players = []; + for (let i = 0; i < numberOfPlayers; i++) { + const playerName = (await askQuestion(` (${i+1}) Enter name: `)).trim(); + players.push(playerName || `Player${i+1}`); + } + + const playersCycle = cycle(players); + + while (true) { + let currentPlayer = playersCycle.next().value; + + console.log(`=== ${currentPlayer}'s turn! ===`); + const currentWord = wordiffs[wordiffs.length-1]; + + const word = (await askQuestion( + `Current word is "${wordiffs.at(-1)}"\n`+ + "Enter your word: " + )).trim().toLowerCase(); + + if (isWordiff(wordiffs, word, dictionary)) { + wordiffs.push(word); + console.log(`Accepted! New chain: ${wordiffs.join(" -> ")}`); + } else { + const alternatives = couldHaveEntered(wordiffs, dictionary); + console.log( + `Game over, ${currentPlayer}!\n`+ + `You could have entered one of these words (first ${alternatives.length} suggestions): ${alternatives.join(", ")}` + ); + break; + } + } + + rl.close(); +} + +main(); diff --git a/Task/Write-entire-file/Odin/write-entire-file.odin b/Task/Write-entire-file/Odin/write-entire-file.odin new file mode 100644 index 0000000000..0b13d18a2a --- /dev/null +++ b/Task/Write-entire-file/Odin/write-entire-file.odin @@ -0,0 +1,11 @@ +package main + +import "core:fmt" +import "core:os" +import "core:c/libc" + +main :: proc() { + + dummy := "henlo" + succ:= os.write_entire_file("file",transmute([]u8)(dummy),false) +} diff --git a/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg b/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg index 032aee733d..e0187a03c6 100644 --- a/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg +++ b/Task/Write-float-arrays-to-a-text-file/ALGOL-68/write-float-arrays-to-a-text-file.alg @@ -1,31 +1,44 @@ -PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: ( - FILE f; - INT errno = open(f, filename, stand out channel); - IF errno NE 0 THEN stop FI; - FOR i TO UPB x DO - # FORMAT := IF the absolute exponent is small enough, THEN use fixed ELSE use float FI; # - FORMAT repr x := ( ABS log(x[i]) 0 then + repeat with i from g to 1 by -1 + set n to n * 10 + end repeat + set n to n as integer + repeat with i from g to 1 by -1 + set n to n / 10 + end repeat + else if g = 0 then + set n to n as integer + end if + if (b < p) and (n = (n div 1)) then + return n as double integer + else + return n as real + end if +end getNumPrecision + +on log10(n) + local lg + set lg to 1 + repeat until n < 10 + set n to n / 10 + set lg to lg + 1 + end repeat + return lg +end log10 diff --git a/Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k b/Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k new file mode 100644 index 0000000000..5c0b46a34c --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/K/write-float-arrays-to-a-text-file.k @@ -0,0 +1,16 @@ +xprecision:3 +yprecision:5 +x: 1 2 3 1e11 +y: 1 1.412135627930951 1.7320508075688772 316227.76601683791 +// for truncuating, see "Learning K Programming, Idiom by Idiom" 460 +xx:{ {1%(*/y#x)}[10;-xprecision] * _x*{*/y#x}[10;xprecision] } x +yy:{ {1%(*/y#x)}[10;-yprecision] * _x*{*/y#x}[10;yprecision] } y +// reshaping and transposing with + +result: +2 4#xx,yy + +// add to string res +res::"" +dummy: {res::res,$x[0];res::res," ";res::res,$x[1];res::res,"\n" }'result + +// output to txt file with 0: +`floatarray.txt 0:res diff --git a/Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs b/Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs new file mode 100644 index 0000000000..b091cc618e --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Rust/xiaolin-wus-line-algorithm.rs @@ -0,0 +1,120 @@ +use std::cmp; + +fn wu_draw_line( + mut x0: f32, + mut y0: f32, + mut x1: f32, + mut y1: f32, + mut plot: impl FnMut(i32, i32, f32), +) { + let ipart = |x: f32| -> i32 { x.floor() as i32 }; + let round = |x: f32| -> f32 { x.round() }; + let fpart = |x: f32| -> f32 { x - x.floor() }; + let rfpart = |x: f32| -> f32 { 1.0 - fpart(x) }; + + let steep = (y1 - y0).abs() > (x1 - x0).abs(); + if steep { + std::mem::swap(&mut x0, &mut y0); + std::mem::swap(&mut x1, &mut y1); + } + if x0 > x1 { + std::mem::swap(&mut x0, &mut x1); + std::mem::swap(&mut y0, &mut y1); + } + + let dx = x1 - x0; + let dy = y1 - y0; + let gradient = if dx == 0.0 { 1.0 } else { dy / dx }; + + let xpx11: i32; + let mut intery: f32; + { + let xend = round(x0); + let yend = y0 + gradient * (xend - x0); + let xgap = rfpart(x0 + 0.5); + xpx11 = xend as i32; + let ypx11 = ipart(yend); + if steep { + plot(ypx11, xpx11, rfpart(yend) * xgap); + plot(ypx11 + 1, xpx11, fpart(yend) * xgap); + } else { + plot(xpx11, ypx11, rfpart(yend) * xgap); + plot(xpx11, ypx11 + 1, fpart(yend) * xgap); + } + intery = yend + gradient; + } + + let xpx12: i32; + { + let xend = round(x1); + let yend = y1 + gradient * (xend - x1); + let xgap = rfpart(x1 + 0.5); + xpx12 = xend as i32; + let ypx12 = ipart(yend); + if steep { + plot(ypx12, xpx12, rfpart(yend) * xgap); + plot(ypx12 + 1, xpx12, fpart(yend) * xgap); + } else { + plot(xpx12, ypx12, rfpart(yend) * xgap); + plot(xpx12, ypx12 + 1, fpart(yend) * xgap); + } + } + + if steep { + for x in xpx11 + 1..xpx12 { + let ipy = ipart(intery); + plot(ipy, x, rfpart(intery)); + plot(ipy + 1, x, fpart(intery)); + intery += gradient; + } + } else { + for x in xpx11 + 1..xpx12 { + let ipy = ipart(intery); + plot(x, ipy, rfpart(intery)); + plot(x, ipy + 1, fpart(intery)); + intery += gradient; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_wu_draw_line() { + let mut pixels = vec![vec![0.0; 10]; 10]; // Create a 10x10 grid of floats + let plot = |x: i32, y: i32, brightness: f32| { + if x >= 0 && x < 10 && y >= 0 && y < 10 { + pixels[x as usize][y as usize] = brightness; + } + }; + + wu_draw_line(1.0, 1.0, 8.0, 8.0, plot); + + // Basic validation: Check that some pixels are lit up + assert!(pixels[1][1] > 0.0); + assert!(pixels[8][8] > 0.0); + + // You can add more specific assertions here based on the expected output. + // For example, check the values of pixels along the expected line path. + // Be aware of floating point precision when comparing. + } + + #[test] + fn test_wu_draw_line_steep() { + let mut pixels = vec![vec![0.0; 10]; 10]; // Create a 10x10 grid of floats + let plot = |x: i32, y: i32, brightness: f32| { + if x >= 0 && x < 10 && y >= 0 && y < 10 { + pixels[x as usize][y as usize] = brightness; + } + }; + + wu_draw_line(1.0, 1.0, 2.0, 8.0, plot); + + // Basic validation: Check that some pixels are lit up + assert!(pixels[1][1] > 0.0); + assert!(pixels[2][8] > 0.0); + } +} + diff --git a/Task/Y-combinator/Elm/y-combinator.elm b/Task/Y-combinator/Elm/y-combinator.elm index 628f86ac59..4aa88c778a 100644 --- a/Task/Y-combinator/Elm/y-combinator.elm +++ b/Task/Y-combinator/Elm/y-combinator.elm @@ -2,18 +2,14 @@ module Main exposing ( main ) import Html exposing ( Html, text ) --- As with most of the strict (non-deferred or non-lazy) languages, --- this is the Z-combinator with the additional value parameter... +-- Recursive wrapper Type required for statically-typed languages... +type Mu a = Roll (Mu a -> a) +unroll : Mu a -> (Mu a -> a) +unroll (Roll v) = v --- wrap type conversion to avoid recursive type definition... -type Mu a b = Roll (Mu a b -> a -> b) - -unroll : Mu a b -> (Mu a b -> a -> b) -- unwrap it... -unroll (Roll x) = x - --- note lack of beta reduction using values... +-- the non-sharing non-recursive implementation of the Z-Combinator... fixz : ((a -> b) -> (a -> b)) -> (a -> b) -fixz f = let g r = f (\ v -> unroll r r v) in g (Roll g) +fixz f = let g = \ x v -> f (unroll x x) v in g (Roll g) facz : Int -> Int -- facz = fixz <| \ f n -> if n < 2 then 1 else n * f (n - 1) -- inefficient recursion @@ -23,20 +19,18 @@ fibz : Int -> Int -- fibz = fixz <| \ f n -> if n < 2 then n else f (n - 1) + f (n - 2) -- inefficient recursion fibz = fixz (\ fn f s i -> if i < 2 then f else fn s (f + s) (i - 1)) 1 1 -- efficient tailcall --- by injecting laziness, we can get the true Y-combinator... --- as this includes laziness, there is no need for the type wrapper! +-- the non-sharing non-recursive implementation of fixy with injected laziness... +-- this works for languages that are "strict" = non-lazy by default... fixy : ((() -> a) -> a) -> a -fixy f = f <| \ () -> fixy f -- direct function recursion --- the above is not value recursion but function recursion! --- the below is an attempt at value recursion, but... --- fixv f = let x = f x in x -- not allowed by task or by Elm! --- we can make Elm allow it by injecting laziness but... -fix : ((() -> a) -> a) -> a -fix f = let xf() = f xf in xf() -- this is just another form of function recursion... --- the above is what the Haskell `fix` non-sharing fix point combinator actually is --- because all values are actually non-strict/lazy, meaning they require a "thunk" as --- above to be evaluated to their actual value, which is equivalent to `xf() ==> x` above! --- thus, in Haskell, all "boxed" values such as this actually represent function applications! +fixy f = let g x = f <| \ () -> (unroll x) x in g (Roll g) + +{-- } --as Elm allows function recursion, the above is equivalent to the following: +fixy f = f <| \ () -> fixy f +--} + +-- sharing version if `(() -> a)` is lazy memoizing value of `a` - Elm doesn't have memoization! +fix : ((() -> a) -> a) -> a -- however, it works as a Y Combinator... +fix f = let x() = f x in x() facy : Int -> Int -- facy = fixy <| \ f n -> if n < 2 then 1 else n * f () (n - 1) -- inefficient recursion @@ -46,22 +40,24 @@ fiby : Int -> Int -- fiby = fixy <| \ f n -> if n < 2 then n else f () (n - 1) + f (n - 2) -- inefficient recursion fiby = fixy (\ fn f s i -> if i < 2 then f else fn () s (f + s) (i - 1)) 1 1 -- efficient tailcall --- something that can be done with a true Y-Combinator that --- can't be done with the Z combinator... --- given an infinite Co-Inductive Stream (CIS) defined as... -type CIS a = CIS a (() -> CIS a) -- infinite lazy stream! +-- Something that can be done with the true Y-Combinator that can't be done with Z-Combinator... + +-- defines a Co-Inductive Lazy (non-memoizing, just deferred) Stream... +type CIS a = CIS a (() -> CIS a) mapCIS : (a -> b) -> CIS a -> CIS b -- uses function to map mapCIS cf cis = let mp (CIS head restf) = CIS (cf head) <| \ () -> mp (restf()) in mp cis --- now we can define a Fibonacci stream as follows... -fibs : () -> CIS Int -fibs() = -- two recursive fix's, second already lazy... - let fibsgen = fixy (\ fn (CIS (f, s) restf) -> - CIS (s, f + s) (\ () -> fn () (restf()))) - in fixy (\ cisthnk -> fibsgen (CIS (0, 1) cisthnk)) - |> mapCIS (\ (v, _) -> v) +iterateCISWithFrom : (CIS a -> CIS a) -> a -> CIS a +iterateCISWithFrom f v = fixy (\ dfn -> f (CIS v dfn)) + +fibsfunc : CIS (Int, Int) -> CIS (Int, Int) +fibsfunc = fixy (\ dfn -> \ (CIS ((cur, nxt) as hd) tlf) -> + CIS hd <| \ () -> dfn () (CIS (nxt, (cur + nxt)) tlf)) + +fibs : CIS Int +fibs = iterateCISWithFrom fibsfunc (1, 1) |> mapCIS (\ (v, _) -> v) nCISs2String : Int -> CIS a -> String -- convert n CIS's to String nCISs2String n cis = @@ -70,12 +66,9 @@ nCISs2String n cis = loop (i - 1) (restf()) (rslt ++ " " ++ Debug.toString head) in loop n cis "(" --- unfortunately, if we need CIS memoization so as --- to make a true lazy list, Elm doesn't support it!!! - main : Html Never main = String.fromInt (facz 10) ++ " " ++ String.fromInt (fibz 10) ++ " " ++ String.fromInt (facy 10) ++ " " ++ String.fromInt (fiby 10) - ++ " " ++ nCISs2String 20 (fibs()) + ++ " " ++ nCISs2String 20 fibs |> text diff --git a/Task/Y-combinator/F-Sharp/y-combinator-1.fs b/Task/Y-combinator/F-Sharp/y-combinator-1.fs index 6b5376cb55..d4a0a79efd 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-1.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-1.fs @@ -1,6 +1,6 @@ -// Y combinator. Nigel Galloway: March 5th., 2024 -type Y<'T> = { eval: Y<'T> -> ('T -> 'T) } -let Y n g=let l = { eval = fun l -> fun x -> (n (l.eval l)) x } in (l.eval l) g -let fibonacci=function 0->1 |x->let fibonacci f= function 0->0 |1->1 |x->f(x - 1) + f(x - 2) in Y fibonacci x -let factorial n=let factorial f=function 0->1 |x->x*f(x-1) in Y factorial n -printfn "fibonacci 10=%d\nfactorial 5=%d" (fibonacci 10) (factorial 5) +// Z combinator. Nigel Galloway: March 5th., 2024 +type Mu<'T> = { eval: Mu<'T> -> ('T -> 'T) } +let Z f = let g = { eval = fun x -> fun v -> (f (x.eval x)) v } in (g.eval g) +let fibonacci=function 0->1 |x->let fibonacci f= function 0->0 |1->1 |x->f(x - 1) + f(x - 2) in Z fibonacci x +let factorial n=let factorial f=function 0->1 |x->x*f(x-1) in Z factorial n +printfn "fibonacci 10 = %d\nfactorial 5 = %d" (fibonacci 10) (factorial 5) diff --git a/Task/Y-combinator/F-Sharp/y-combinator-2.fs b/Task/Y-combinator/F-Sharp/y-combinator-2.fs index 570693a413..fb343b0626 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-2.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-2.fs @@ -1,35 +1,7 @@ -type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with - -let unroll (Roll x) = x -// val unroll : 'a mu -> ('a mu -> 'a) - -// As with most of the strict (non-deferred or non-lazy) languages, -// this is the Z-combinator with the additional 'a' parameter... -let fix f = let g = fun x a -> f (unroll x x) a in g (Roll g) -// val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = - -// Although true to the factorial definition, the -// recursive call is not in tail call position, so can't be optimized -// and will overflow the call stack for the recursive calls for large ranges... -//let fac = fix (fun f n -> if n < 2 then 1I else bigint n * f (n - 1)) -// val fac : (int -> BigInteger) = - -// much better progressive calculation in tail call position... -let fac = fix (fun f n i -> if i < 2 then n else f (bigint i * n) (i - 1)) <| 1I -// val fac : (int -> BigInteger) = - -// Although true to the definition of Fibonacci numbers, -// this can't be tail call optimized and recursively repeats calculations -// for a horrendously inefficient exponential performance fib function... -// let fib = fix (fun fnc n -> if n < 2 then n else fnc (n - 1) + fnc (n - 2)) -// val fib : (int -> BigInteger) = - -// much better progressive calculation in tail call position... -let fib = fix (fun fnc f s i -> if i < 2 then f else fnc s (f + s) (i - 1)) 1I 1I -// val fib : (int -> BigInteger) = - -[] -let main argv = - fac 10 |> printfn "%A" // prints 3628800 - fib 10 |> printfn "%A" // prints 55 - 0 // return an integer exit code +// Y combinator with injected laziness. GordonBGood : April 18, 2025 +type 'T Mu = { eval: 'T Mu -> 'T } +let Y f = let g = fun x -> f <| fun() -> (x.eval x) in g { eval = g } +let fibonacci n = Y (fun fn f s i -> if i >= n then f else fn () s (f + s) (i + 1)) 1I 1I 1 +let factorial n = Y (fun f p x -> if x > n then p else f () (x * p) (x + 1I)) 1I 1I +printfn "fibonacci 10 = %A\r\nfactorial 5 = %A" (fibonacci 10) (factorial 5I) +printfn "fibonacci 1000 = %A" (fibonacci 1000) diff --git a/Task/Y-combinator/F-Sharp/y-combinator-3.fs b/Task/Y-combinator/F-Sharp/y-combinator-3.fs index c9fbe39fbc..570693a413 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-3.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-3.fs @@ -1,40 +1,35 @@ -// same as previous... type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with -// same as previous... let unroll (Roll x) = x // val unroll : 'a mu -> ('a mu -> 'a) -// break race condition with some deferred execution - laziness... -let fix f = let g = fun x -> f <| fun() -> (unroll x x) in g (Roll g) -// val fix : ((unit -> 'a) -> 'a -> 'a) = +// As with most of the strict (non-deferred or non-lazy) languages, +// this is the Z-combinator with the additional 'a' parameter... +let fix f = let g = fun x a -> f (unroll x x) a in g (Roll g) +// val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = -// same efficient version of factorial functionb with added deferred execution... -let fac = fix (fun f n i -> if i < 2 then n else f () (bigint i * n) (i - 1)) <| 1I +// Although true to the factorial definition, the +// recursive call is not in tail call position, so can't be optimized +// and will overflow the call stack for the recursive calls for large ranges... +//let fac = fix (fun f n -> if n < 2 then 1I else bigint n * f (n - 1)) // val fac : (int -> BigInteger) = -// same efficient version of Fibonacci function with added deferred execution... -let fib = fix (fun fnc f s i -> if i < 2 then f else fnc () s (f + s) (i - 1)) 1I 1I +// much better progressive calculation in tail call position... +let fac = fix (fun f n i -> if i < 2 then n else f (bigint i * n) (i - 1)) <| 1I +// val fac : (int -> BigInteger) = + +// Although true to the definition of Fibonacci numbers, +// this can't be tail call optimized and recursively repeats calculations +// for a horrendously inefficient exponential performance fib function... +// let fib = fix (fun fnc n -> if n < 2 then n else fnc (n - 1) + fnc (n - 2)) // val fib : (int -> BigInteger) = -// given the following definition for an infinite Co-Inductive Stream (CIS)... -type CIS<'a> = CIS of 'a * (unit -> CIS<'a>) // ' fix formatting - -// Using a double Y-Combinator recursion... -// defines a continuous stream of Fibonacci numbers; there are other simpler ways, -// this way implements recursion by using the Y-combinator, although it is -// much slower than other ways due to the many additional function calls, -// it demonstrates something that can't be done with the Z-combinator... -let fibs() = - let fbsgen = fix (fun fnc (CIS((f, s), rest)) -> - CIS((s, f + s), fun() -> fnc () <| rest())) - Seq.unfold (fun (CIS((v, _), rest)) -> Some(v, rest())) - <| fix (fun cis -> fbsgen (CIS((1I, 0I), cis))) // cis is a lazy thunk! +// much better progressive calculation in tail call position... +let fib = fix (fun fnc f s i -> if i < 2 then f else fnc s (f + s) (i - 1)) 1I 1I +// val fib : (int -> BigInteger) = [] let main argv = fac 10 |> printfn "%A" // prints 3628800 fib 10 |> printfn "%A" // prints 55 - fibs() |> Seq.take 20 |> Seq.iter (printf "%A ") - printfn "" 0 // return an integer exit code diff --git a/Task/Y-combinator/F-Sharp/y-combinator-4.fs b/Task/Y-combinator/F-Sharp/y-combinator-4.fs index 67c1a271c4..c9fbe39fbc 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-4.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-4.fs @@ -1,4 +1,40 @@ -let rec fix f = f <| fun() -> fix f -// val fix : f:((unit -> 'a) -> 'a) -> 'a +// same as previous... +type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with -// the application of this true Y-combinator is the same as for the above non function recursive version. +// same as previous... +let unroll (Roll x) = x +// val unroll : 'a mu -> ('a mu -> 'a) + +// break race condition with some deferred execution - laziness... +let fix f = let g = fun x -> f <| fun() -> (unroll x x) in g (Roll g) +// val fix : ((unit -> 'a) -> 'a -> 'a) = + +// same efficient version of factorial functionb with added deferred execution... +let fac = fix (fun f n i -> if i < 2 then n else f () (bigint i * n) (i - 1)) <| 1I +// val fac : (int -> BigInteger) = + +// same efficient version of Fibonacci function with added deferred execution... +let fib = fix (fun fnc f s i -> if i < 2 then f else fnc () s (f + s) (i - 1)) 1I 1I +// val fib : (int -> BigInteger) = + +// given the following definition for an infinite Co-Inductive Stream (CIS)... +type CIS<'a> = CIS of 'a * (unit -> CIS<'a>) // ' fix formatting + +// Using a double Y-Combinator recursion... +// defines a continuous stream of Fibonacci numbers; there are other simpler ways, +// this way implements recursion by using the Y-combinator, although it is +// much slower than other ways due to the many additional function calls, +// it demonstrates something that can't be done with the Z-combinator... +let fibs() = + let fbsgen = fix (fun fnc (CIS((f, s), rest)) -> + CIS((s, f + s), fun() -> fnc () <| rest())) + Seq.unfold (fun (CIS((v, _), rest)) -> Some(v, rest())) + <| fix (fun cis -> fbsgen (CIS((1I, 0I), cis))) // cis is a lazy thunk! + +[] +let main argv = + fac 10 |> printfn "%A" // prints 3628800 + fib 10 |> printfn "%A" // prints 55 + fibs() |> Seq.take 20 |> Seq.iter (printf "%A ") + printfn "" + 0 // return an integer exit code diff --git a/Task/Y-combinator/F-Sharp/y-combinator-5.fs b/Task/Y-combinator/F-Sharp/y-combinator-5.fs new file mode 100644 index 0000000000..67c1a271c4 --- /dev/null +++ b/Task/Y-combinator/F-Sharp/y-combinator-5.fs @@ -0,0 +1,4 @@ +let rec fix f = f <| fun() -> fix f +// val fix : f:((unit -> 'a) -> 'a) -> 'a + +// the application of this true Y-combinator is the same as for the above non function recursive version. diff --git a/Task/Y-combinator/J/y-combinator-1.j b/Task/Y-combinator/J/y-combinator-1.j index e6cd6b8f33..75bc19b2e8 100644 --- a/Task/Y-combinator/J/y-combinator-1.j +++ b/Task/Y-combinator/J/y-combinator-1.j @@ -1,3 +1,3 @@ - Y=. {{x&(x`:6)`'' u y}} {{u`''&u}} + Y =. {{x&(x`:6)`'' u y}} {{u`''&u}} fac=. 1:`{{(* x`:6@<:)y}}@.(0 < ]) fib=. {{(-&1 +&(x`:6) -&2)y}}^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-3.j b/Task/Y-combinator/J/y-combinator-3.j index 43c4ff31b2..5a2752f4e4 100644 --- a/Task/Y-combinator/J/y-combinator-3.j +++ b/Task/Y-combinator/J/y-combinator-3.j @@ -1,4 +1,4 @@ - Y=. ]:&>/]:^:_1 b.]:`(<'0';_1)`:6&([ 128!:2 ,&<) - sr=. [ apply f. ,&< NB. Self referring + Y =. ]:&>/]:^:_1 b.]:`(<'0';_1)`:6&([ 128!:2 ,&<) + sr =. [ apply f. ,&< NB. Self referring fac=. 1:`(] * [ sr ] - 1:)@.(0 < ]) fib=. (([ sr ] - 2:) + [ sr ] - 1:)^:(1 < ]) diff --git a/Task/Y-combinator/J/y-combinator-6.j b/Task/Y-combinator/J/y-combinator-6.j index bcbaa5edea..760d8d8a98 100644 --- a/Task/Y-combinator/J/y-combinator-6.j +++ b/Task/Y-combinator/J/y-combinator-6.j @@ -1,6 +1,6 @@ sr=. [ apply f. ,&< NB. Self referring lv=. ]:^:_1 b.]:`(<'0';_1)`:6 NB. Linear representation of a verb operand - Y=. ]:&>/lv&sr NB. Y with embedded states - Y=. 'Y' f. NB. Fixing it... + Y =. ]:&>/lv&sr NB. Y with embedded states + Y =. 'Y' f. NB. Fixing it... Y NB. ... To make it stateless (i.e., a combinator) ((]: & >) / ((((]: ^: (_1)) b. ]:) ` (<'0';_1)) `: 6)) & ([ 128!:2 ,&<) diff --git a/Task/Y-combinator/Zig/y-combinator.zig b/Task/Y-combinator/Zig/y-combinator.zig new file mode 100644 index 0000000000..3a6cf9927b --- /dev/null +++ b/Task/Y-combinator/Zig/y-combinator.zig @@ -0,0 +1,71 @@ +//! A simple implementation of the Y Combinator: +//! λf.(λx.xx)(λx.f(xx)) +//! <=> λf.(λx.f(xx))(λx.f(xx)) + +const std = @import("std"); +const debug = std.debug; +const mem = std.mem; +const Allocator = mem.Allocator; + +// In Zig we can use function pointers and closures +// to implement the Y combinator without needing traits + +// Generic Y combinator implementation +fn Y(comptime T: type, comptime R: type, f: fn (fn (T) R, T) R) fn (T) R { + const Closure = struct { + fn call(t: T) R { + const applySelf = struct { + fn apply(x: fn (fn (T) R, T) R, y: T) R { + const innerApply = struct { + fn inner(z: T) R { + return apply(x, z); + } + }.inner; + return x(innerApply, y); + } + }.apply; + return applySelf(f, t); + } + }; + return Closure.call; +} + +// Factorial function using Y combinator +fn fac(n: usize) usize { + const almostFac = struct { + fn call(f: fn (usize) usize, x: usize) usize { + if (x == 0) return 1 else return x * f(x - 1); + } + }.call; + + return Y(usize, usize, almostFac)(n); +} + +// Fibonacci function using Y combinator +fn fib(n: usize) usize { + const FibTuple = struct { a0: usize, a1: usize, x: usize }; + + const almostFib = struct { + fn call(f: fn (FibTuple) usize, tuple: FibTuple) usize { + const a0 = tuple.a0; + const a1 = tuple.a1; + const x = tuple.x; + + return switch (x) { + 0 => a0, + 1 => a1, + else => f(.{ .a0 = a1, .a1 = a0 + a1, .x = x - 1 }), + }; + } + }.call; + + return Y(FibTuple, usize, almostFib)(.{ .a0 = 1, .a1 = 1, .x = n }); +} + +// Driver function +pub fn main() !void { + const n: usize = 10; + const stdout = std.io.getStdOut().writer(); + try stdout.print("fac({}) = {}\n", .{ n, fac(n) }); + try stdout.print("fib({}) = {}\n", .{ n, fib(n) }); +} diff --git a/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy b/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy index e980cb39de..cc912716ce 100644 --- a/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy +++ b/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy @@ -1,16 +1,12 @@ func gcd a b . - if b = 0 - return a - . + if b = 0 : return a return gcd b (a mod b) . -proc remove_at i . a[] . - for j = i + 1 to len a[] - a[j - 1] = a[j] - . +proc remove_at i &a[] . + for j = i + 1 to len a[] : a[j - 1] = a[j] len a[] -1 . -proc yellowstone count . yellow[] . +proc yellowstone count &yellow[] . yellow[] = [ 1 2 3 ] num = 4 while len yellow[] < count @@ -18,9 +14,7 @@ proc yellowstone count . yellow[] . yell2 = yellow[len yellow[]] for i to len notyellow[] test = notyellow[i] - if gcd yell1 test > 1 and gcd yell2 test = 1 - break 1 - . + if gcd yell1 test > 1 and gcd yell2 test = 1 : break 1 . if i <= len notyellow[] yellow[] &= notyellow[i] diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx deleted file mode 100644 index be0c9c0fce..0000000000 --- a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-1.rexx +++ /dev/null @@ -1,20 +0,0 @@ -/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/ -parse arg m . /*obtain optional argument from the CL.*/ -if m=='' | m=="," then m= 30 /*Not specified? Then use the default.*/ -!.= 0 /*initialize an array of numbers(used).*/ -# = 0 /*count of Yellowstone numbers in seq. */ -$= /*list " " " " " */ - do j=1 until #==m; prev= # - 1 - if j<5 then do; #= #+1; @.#= j; !.#= j; !.j= 1; $= strip($ j); iterate; end - - do k=1; if !.k then iterate /*Already used? Then skip this number.*/ - if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */ - if gcd(k, @.#) \==1 then iterate /* " " " " " " */ - #= #+1; @.#= k; !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/ - leave /*find the next Yellowstone seq. number*/ - end /*k*/ - end /*j*/ -say $ /*display a list of a Yellowstone seq. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx deleted file mode 100644 index 549ae130a1..0000000000 --- a/Task/Yellowstone-sequence/REXX/yellowstone-sequence-2.rexx +++ /dev/null @@ -1,21 +0,0 @@ -/*REXX program calculates any number of terms in the Yellowstone (permutation) sequence.*/ -parse arg m . /*obtain optional argument from the CL.*/ -if m=='' | m=="," then m= 30 /*Not specified? Then use the default.*/ -!.= 0 /*initialize an array of numbers(used).*/ -# = 0 /*count of Yellowstone numbers in seq. */ -$ = /*list " " " " " */ - do j=1 until #==m; prev= # - 1 - if j<5 then do; #= #+1; @.#= j; !.#= j; !.j= 1; $= strip($ j); iterate; end - - do k=1; if !.k then iterate /*Already used? Then skip this number.*/ - if gcd(k, @.prev)<2 then iterate /*Not meet requirement? Then skip it. */ - if gcd(k, @.#) \==1 then iterate /* " " " " " " */ - #= # + 1; @.#= k; !.k= 1; $= $ k /*bump ctr; assign; mark used; add list*/ - leave /*find the next Yellowstone seq. number*/ - end /*k*/ - end /*j*/ - -call $histo $ '(vertical)' /*invoke a REXX vertical histogram plot*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -gcd: parse arg x,y; do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx new file mode 100644 index 0000000000..de391c503f --- /dev/null +++ b/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx @@ -0,0 +1,56 @@ +-- 25 Apr 2025 +include Settings +numeric digits 100 +arg xx +if xx = '' then + xx = 30 + +say 'YELLOWSTONE SEQUENCE' +say version +say +call GetYellow xx +call DisplayList xx +call Timer +exit + +GetYellow: +procedure expose yell. work. +arg xx +say 'Get yellowstones...' +yell. = 0; work. = 0; n = 0 +do i = 1 until n = xx + p = n-1 + if i < 5 then do + n = n+1; yell.n = i; work.n = i; work.i = 1 + iterate i + end + do j = 1 + if work.j then + iterate j + if Gcd(j,yell.p) = 1 then + iterate j + if Gcd(j,yell.n) <> 1 then + iterate j + n = n+1; yell.n = j; work.j = 1 + leave j + end +end +say +return xx + +DisplayList: +procedure expose yell. +arg xx +say 'Yellowstone sequence...' +do i = 1 to xx + call Charout ,Right(yell.i,5) + if i//10 = 0 then + say +end +say +return + +include Sequences +include Functions +include Helper +include Abend diff --git a/Task/Yin-and-yang/EasyLang/yin-and-yang.easy b/Task/Yin-and-yang/EasyLang/yin-and-yang.easy index 38961146b9..653cd6fb44 100644 --- a/Task/Yin-and-yang/EasyLang/yin-and-yang.easy +++ b/Task/Yin-and-yang/EasyLang/yin-and-yang.easy @@ -1,20 +1,17 @@ -proc circ r c . . - color c - circle r +proc circ x y r c . + gcolor c + gcircle x y r . -proc yinyang x y r . . - move x y - circ 2 * r 000 - color 999 - circseg 2 * r 90 -90 - move x y - r - circ r 000 - circ r / 3 999 - move x y + r - circ r 999 - circ r / 3 000 +proc yinyang x y r . + circ x y 2 * r 000 + gcolor 999 + gcircseg x y 2 * r 90 -90 + circ x y - r r 000 + circ x y - r r / 3 999 + circ x y + r r 999 + circ x y + r r / 3 000 . -background 555 -clear +gbackground 555 +gclear yinyang 20 20 6 yinyang 50 60 14 diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-1.j b/Task/Zebra-puzzle/J/zebra-puzzle-1.j index cfff37de00..b34c7f5f07 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-1.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-1.j @@ -2,13 +2,23 @@ in=: {{n&{ i. m"_}} NB. index of m in row n of matrix F =: {{u"_1 # ]}} NB. filter by function of items 'Col Nat Pet Drink Cig'=: i.5 NB. refer to rows by name 'col nat pet drink cig'=: (A.~i.@!@#)&>;:'BGRWY DEGNS BCDHZ BCMTW BbDpP' NB. perm matrices -P=: ('W' in Col (= >:) 'G' in Col)F ,/col,:"1/nat NB. join first two mats and add 1st constraint -P=: ,/pet,"2 1/~ (('E' in Nat = 'R' in Col)*.(0 = 'N' in Nat))F P NB. and so on... -P=: ,/drink,"2 1/~ (('D' in Pet = 'S' in Nat)*.('N' in Nat (1=|@:-) 'B' in Col))F P -P=: (('C' in Drink = 'G' in Col)*.(2 = 'M' in Drink))F P -P=: (('T' in Drink = 'D' in Nat)*.('p' in Cig = 'B' in Pet))F ,/P,"2 1/cig -P=: (('D' in Cig = 'Y' in Col)*.('b' in Cig = 'B' in Drink))F P -P=: (('P' in Cig = 'G' in Nat)*.('B' in Cig (1=|@:-) 'C' in Pet))F P -P=: (('D' in Cig (1=|@:-) 'H' in Pet)*.('B' in Cig (1=|@:-) 'W' in Drink))F P -echo 'Solutions found: ',(":#P),LF,LF,~' owns the Z',~('Z' in Pet { Nat&{){.P -echo 'Col Nat Pet Drink Cig', ([,(6#' '),])/"1|:{.P +P=: ,/col,:"1/nat NB. join color and nationality matrices +P=: ('W' in Col = 1+ 'G' in Col)F P NB. white right of green +P=: (0 = 'N' in Nat)F P NB. Norwegian in first house +P=: ,/pet,"2 1/~ ('E' in Nat = 'R' in Col)F P NB. red = English; add pets +P=: ('N' in Nat (1=|@-) 'B' in Col)F P NB. blue next to Norwegian +P=: ,/drink,"2 1/~ ('D' in Pet = 'S' in Nat)F P NB. Swede owns dog; add drinks +P=: (2 = 'M' in Drink)F P NB. middle house drinks milk +P=: ('T' in Drink = 'D' in Nat)F P NB. Dane drinks tea +P=: ('C' in Drink = 'G' in Col)F P NB. green = coffee +P=: ('p' in Cig = 'B' in Pet)F ,/P,"2 1/cig NB. add cigs; PallMall = birds +P=: ('D' in Cig = 'Y' in Col)F P NB. Dunhill = yellow +P=: ('b' in Cig = 'B' in Drink)F P NB. BlueM = beer +P=: ('P' in Cig = 'G' in Nat)F P NB. Prince = German +P=: ('B' in Cig (1=|@-) 'C' in Pet)F P NB. cat next to Blend +P=: ('D' in Cig (1=|@-) 'H' in Pet)F P NB. horse next to Dunhill +P=: ('B' in Cig (1=|@-) 'W' in Drink)F P NB. water next to Blend +echo 'Solutions found: ',":#P +echo (('Z' in Pet { Nat&{){.P),' owns the Z' +echo 'Col Nat Pet Drink Cig' +echo ([,(6#' '),])/"1|:{.P diff --git a/Task/Zebra-puzzle/JavaScript/zebra-puzzle.js b/Task/Zebra-puzzle/JavaScript/zebra-puzzle.js new file mode 100644 index 0000000000..ccb11f817e --- /dev/null +++ b/Task/Zebra-puzzle/JavaScript/zebra-puzzle.js @@ -0,0 +1,163 @@ +// Define enums and their string representations +const Attrib = { Color: 0, Man: 1, Drink: 2, Animal: 3, Smoke: 4 }; +const Attrib_str = ["Color", "Man", "Drink", "Animal", "Smoke"]; + +const Colors = { Red: 0, Green: 1, White: 2, Yellow: 3, Blue: 4 }; +const Colors_str = ["Red", "Green", "White", "Yellow", "Blue"]; + +const Mans = { English: 0, Swede: 1, Dane: 2, German: 3, Norwegian: 4 }; +const Mans_str = ["English", "Swede", "Dane", "German", "Norwegian"]; + +const Drinks = { Tea: 0, Coffee: 1, Milk: 2, Beer: 3, Water: 4 }; +const Drinks_str = ["Tea", "Coffee", "Milk", "Beer", "Water"]; + +const Animals = { Dog: 0, Birds: 1, Cats: 2, Horse: 3, Zebra: 4 }; +const Animals_str = ["Dog", "Birds", "Cats", "Horse", "Zebra"]; + +const Smokes = { PallMall: 0, Dunhill: 1, Blend: 2, BlueMaster: 3, Prince: 4 }; +const Smokes_str = ["PallMall", "Dunhill", "Blend", "BlueMaster", "Prince"]; + +function printHouses(ha) { + const attr_names = [Colors_str, Mans_str, Drinks_str, Animals_str, Smokes_str]; + + let output = "House".padEnd(10); + for (const name of Attrib_str) { + output += name.padEnd(10); + } + console.log(output); + + for (let i = 0; i < 5; i++) { + output = String(i).padEnd(10); + for (let j = 0; j < 5; j++) { + output += attr_names[j][ha[i][j]].padEnd(10); + } + console.log(output); + } +} + +// House number specific rules +const housenos = [ + { houseno: 2, a: Attrib.Drink, v: Drinks.Milk }, // Cond 9: In the middle house they drink milk. + { houseno: 0, a: Attrib.Man, v: Mans.Norwegian } // Cond 10: The Norwegian lives in the first house. +]; + +// Attribute pair rules +const pairs = [ + { a1: Attrib.Man, v1: Mans.English, a2: Attrib.Color, v2: Colors.Red }, // Cond 2: The English man lives in the red house. + { a1: Attrib.Man, v1: Mans.Swede, a2: Attrib.Animal, v2: Animals.Dog }, // Cond 3: The Swede has a dog. + { a1: Attrib.Man, v1: Mans.Dane, a2: Attrib.Drink, v2: Drinks.Tea }, // Cond 4: The Dane drinks tea. + { a1: Attrib.Color, v1: Colors.Green, a2: Attrib.Drink, v2: Drinks.Coffee }, // Cond 6: drink coffee in the green house. + { a1: Attrib.Smoke, v1: Smokes.PallMall, a2: Attrib.Animal, v2: Animals.Birds }, // Cond 7: The man who smokes Pall Mall has birds. + { a1: Attrib.Smoke, v1: Smokes.Dunhill, a2: Attrib.Color, v2: Colors.Yellow }, // Cond 8: In the yellow house they smoke Dunhill. + { a1: Attrib.Smoke, v1: Smokes.BlueMaster, a2: Attrib.Drink, v2: Drinks.Beer }, // Cond 13: The man who smokes Blue Master drinks beer. + { a1: Attrib.Man, v1: Mans.German, a2: Attrib.Smoke, v2: Smokes.Prince } // Cond 14: The German smokes Prince +]; + +// Next to rules +const nexttos = [ + { a1: Attrib.Smoke, v1: Smokes.Blend, a2: Attrib.Animal, v2: Animals.Cats }, // Cond 11: The man who smokes Blend lives in the house next to the house with cats. + { a1: Attrib.Smoke, v1: Smokes.Dunhill, a2: Attrib.Animal, v2: Animals.Horse }, // Cond 12: In a house next to the house where they have a horse, they smoke Dunhill. + { a1: Attrib.Man, v1: Mans.Norwegian, a2: Attrib.Color, v2: Colors.Blue }, // Cond 15: The Norwegian lives next to the blue house. + { a1: Attrib.Smoke, v1: Smokes.Blend, a2: Attrib.Drink, v2: Drinks.Water } // Cond 16: They drink water in a house next to the house where they smoke Blend. +]; + +// Left of rules +const leftofs = [ + { a1: Attrib.Color, v1: Colors.Green, a2: Attrib.Color, v2: Colors.White } // Cond 5: The green house is immediately to the left of the white house. +]; + +function invalid(ha) { + // Check leftofs global rules + for (const rule of leftofs) { + if (ha[0][rule.a2] === rule.v2 || ha[4][rule.a1] === rule.v1) { + return true; + } + } + + // Check rules for each house + for (let i = 0; i < 5; i++) { + // Check pair rules + for (const rule of pairs) { + if (ha[i][rule.a1] >= 0 && ha[i][rule.a2] >= 0 && + ((ha[i][rule.a1] === rule.v1 && ha[i][rule.a2] !== rule.v2) || + (ha[i][rule.a1] !== rule.v1 && ha[i][rule.a2] === rule.v2))) { + return true; + } + } + + // Check next to rules + for (const rule of nexttos) { + if (ha[i][rule.a1] === rule.v1) { + if (i === 0 && ha[i + 1][rule.a2] >= 0 && ha[i + 1][rule.a2] !== rule.v2) { + return true; + } else if (i === 4 && ha[i - 1][rule.a2] !== rule.v2) { + return true; + } else if (i > 0 && i < 4 && + ha[i + 1][rule.a2] >= 0 && ha[i + 1][rule.a2] !== rule.v2 && + ha[i - 1][rule.a2] !== rule.v2) { + return true; + } + } + } + + // Check left of rules for this house + for (const rule of leftofs) { + if (i > 0 && ha[i][rule.a1] >= 0 && + ((ha[i - 1][rule.a1] === rule.v1 && ha[i][rule.a2] !== rule.v2) || + (ha[i - 1][rule.a1] !== rule.v1 && ha[i][rule.a2] === rule.v2))) { + return true; + } + } + } + return false; +} + +function search(used, ha, hno, attr) { + let nexthno, nextattr; + if (attr < 4) { + nextattr = attr + 1; + nexthno = hno; + } else { + nextattr = 0; + nexthno = hno + 1; + } + + if (ha[hno][attr] !== -1) { + search(used, ha, nexthno, nextattr); + } else { + for (let i = 0; i < 5; i++) { + if (used[attr][i]) continue; + used[attr][i] = true; + ha[hno][attr] = i; + + if (!invalid(ha)) { + if (hno === 4 && attr === 4) { + printHouses(ha); + } else { + search(used, ha, nexthno, nextattr); + } + } + + used[attr][i] = false; + ha[hno][attr] = -1; + } + } +} + +function main() { + // Initialize arrays + const used = Array(5).fill().map(() => Array(5).fill(false)); + const ha = Array(5).fill().map(() => Array(5).fill(-1)); + + // Apply house number specific rules + for (const rule of housenos) { + ha[rule.houseno][rule.a] = rule.v; + used[rule.a][rule.v] = true; + } + + // Start the search + search(used, ha, 0, 0); +} + +// Run the program +main(); diff --git a/Task/Zeckendorf-number-representation/EasyLang/zeckendorf-number-representation.easy b/Task/Zeckendorf-number-representation/EasyLang/zeckendorf-number-representation.easy index ed432b91e5..9d72b24831 100644 --- a/Task/Zeckendorf-number-representation/EasyLang/zeckendorf-number-representation.easy +++ b/Task/Zeckendorf-number-representation/EasyLang/zeckendorf-number-representation.easy @@ -1,4 +1,4 @@ -proc mkfibs n . fib[] . +proc mkfibs n &fib[] . fib[] = [ ] last = 1 current = 1 @@ -19,9 +19,7 @@ func$ zeckendorf n . zeck$ &= "0" . . - if zeck$ = "" - return "0" - . + if zeck$ = "" : return "0" return zeck$ . for n = 0 to 20 diff --git a/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy b/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy index 4eb3a10029..0db56b35a7 100644 --- a/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy +++ b/Task/Zig-zag-matrix/EasyLang/zig-zag-matrix.easy @@ -22,7 +22,7 @@ func coord2num row col n . return start + offs . n = 6 -numfmt 0 3 +numfmt 3 0 for row = 0 to n - 1 for col = 0 to n - 1 write coord2num row col n diff --git a/Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua b/Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua new file mode 100644 index 0000000000..979e08e630 --- /dev/null +++ b/Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua @@ -0,0 +1,7 @@ +ZigZag ← ( + ↘₁⇡⊸×₂ + ⊃(⋅⟜⇡|↧₀-|◿₂|+⊃⍚⇡(\+⊂₀↘₋₁)↧⇌.) + ≡↙⊙(≡↻|⍉≡↻|⬚∞≡◇∘⍥⇌) +) + +ZigZag 5 diff --git a/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy b/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy index 350228b3f3..3e1093d7d1 100644 --- a/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy +++ b/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy @@ -1,40 +1,26 @@ -proc divisors n . divs[] . +proc divisors n &divs[] . divs[] = [ 1 n ] for i = 2 to sqrt n if n mod i = 0 j = n / i divs[] &= i - if i <> j - divs[] &= j - . + if i <> j : divs[] &= j . . . func ispartsum divs[] sum . - if sum = 0 - return 1 - . - if len divs[] = 0 - return 0 - . + if sum = 0 : return 1 + if len divs[] = 0 : return 0 last = divs[len divs[]] len divs[] -1 - if last > sum - return ispartsum divs[] sum - . - if ispartsum divs[] sum = 1 - return 1 - . + if last > sum : return ispartsum divs[] sum + if ispartsum divs[] sum = 1 : return 1 return ispartsum divs[] (sum - last) . func iszumkeller n . divisors n divs[] - for v in divs[] - sum += v - . - if sum mod 2 = 1 - return 0 - . + for v in divs[] : sum += v + if sum mod 2 = 1 : return 0 if n mod 2 = 1 abund = sum - 2 * n return if abund > 0 and abund mod 2 = 0 From 4924dd02645b52a0711d3284011e3584c3fe83d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Mon, 11 Aug 2025 18:05:26 -0700 Subject: [PATCH 08/12] Data update --- .gitignore | 5 + Conf/lang.yaml | 25 +- Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt | 1 + Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml | 2 + Lang/ALGOL-60/Factorial | 1 - Lang/ALGOL-68/Date-manipulation | 1 + ...stribution-of-0-digits-in-factorial-series | 1 + Lang/ALGOL-68/Factorial | 1 - Lang/ALGOL-68/Knapsack-problem-Continuous | 1 + Lang/ALGOL-68/Word-wheel | 1 + Lang/ALGOL-W/Factorial | 1 - Lang/ALGOL-W/Knapsack-problem-Continuous | 1 + Lang/ANSI-BASIC/AKS-test-for-primes | 1 + Lang/ANSI-BASIC/Old-Russian-measure-of-length | 1 + Lang/APL/Monte-Carlo-methods | 1 + Lang/ARM-Assembly/00-LANG.txt | 39 +- Lang/ASIC/Old-Russian-measure-of-length | 1 + Lang/AWK/100-doors | 1 - Lang/AWK/Factorial-primes | 1 + Lang/AWK/Soloways-recurring-rainfall | 1 + Lang/Ada/Almkvist-Giullera-formula-for-pi | 1 + Lang/Ada/Biorhythms | 1 + Lang/Ada/Boyer-Moore-string-search | 1 + Lang/Ada/Calkin-Wilf-sequence | 1 + Lang/Ada/Camel-case-and-snake-case | 1 + Lang/Ada/Canonicalize-CIDR | 1 + Lang/Ada/Deepcopy | 1 + Lang/Ada/Factorions | 1 + Lang/Ada/Find-duplicate-files | 1 + Lang/Ada/Harmonic-series | 1 + Lang/Ada/Knapsack-problem-Bounded | 1 + Lang/Ada/Levenshtein-distance-Alignment | 1 + Lang/Ada/Long-literals-with-continuations | 1 + Lang/Ada/Longest-increasing-subsequence | 1 + Lang/Ada/Machine-code | 1 + Lang/Ada/Minimal-steps-down-to-1 | 1 + Lang/Ada/Naming-conventions | 1 + .../Read-a-file-character-by-character-UTF8 | 1 + Lang/Ada/Test-integerness | 1 + Lang/Ada/Total-circles-area | 1 + Lang/Ada/Twos-complement | 1 + Lang/Ada/Vector | 1 + Lang/Adina/00-LANG.txt | 13 + Lang/Adina/00-META.yaml | 2 + Lang/Adina/100-doors | 1 + Lang/Adina/Even-or-odd | 1 + Lang/Adina/Hello-world-Text | 1 + Lang/Adina/Loops-For | 1 + Lang/Adina/Tree-traversal | 1 + Lang/Agena/00-LANG.txt | 4 +- Lang/Agena/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Agena/Abundant-odd-numbers | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/Agena/Attractive-numbers | 1 + Lang/Agena/Disarium-numbers | 1 + Lang/Agena/Factorial | 1 + Lang/Agena/Factorial-primes | 1 + Lang/Agena/Giuga-numbers | 1 + Lang/Agena/Goldbachs-comet | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/Agena/Humble-numbers | 1 + Lang/Agena/JSON | 1 + Lang/Agena/Jacobsthal-numbers | 1 + Lang/Agena/Jewels-and-stones | 1 + Lang/Agena/Kaprekar-numbers | 1 + Lang/Agena/Mian-Chowla-sequence | 1 + Lang/Agena/Pernicious-numbers | 1 + Lang/Agena/Pisano-period | 1 + Lang/Agena/Primality-by-trial-division | 1 + .../Sequence-of-primes-by-trial-division | 1 + Lang/Agena/Smarandache-prime-digital-sequence | 1 + Lang/Agena/Soloways-recurring-rainfall | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + Lang/Agena/Time-a-function | 1 + Lang/Agena/Totient-function | 1 + Lang/Agena/Unprimeable-numbers | 1 + Lang/Agena/Van-Eck-sequence | 1 + Lang/Agena/Van-der-Corput-sequence | 1 + Lang/Agena/Wagstaff-primes | 1 + Lang/Agena/Wieferich-primes | 1 + Lang/Agena/Yellowstone-sequence | 1 + Lang/Apple/00-LANG.txt | 12 + Lang/Apple/00-META.yaml | 2 + Lang/Apple/Averages-Arithmetic-mean | 1 + Lang/Apple/Averages-Pythagorean-means | 1 + Lang/Apple/Catamorphism | 1 + Lang/Apple/Dot-product | 1 + Lang/Apple/Factorial | 1 + Lang/Apple/Factors-of-an-integer | 1 + Lang/Apple/Filter | 1 + Lang/Apple/ISBN13-check-digit | 1 + Lang/Aria/00-LANG.txt | 15 + Lang/Aria/00-META.yaml | 2 + Lang/Aria/99-bottles-of-beer | 1 + Lang/Aria/Hello-world-Text | 1 + Lang/ArkScript/00-LANG.txt | 43 ++ Lang/ArkScript/00-META.yaml | 2 + Lang/ArkScript/100-doors | 1 + Lang/ArkScript/99-bottles-of-beer | 1 + Lang/ArkScript/A+B | 1 + Lang/ArkScript/Abbreviations-easy | 1 + Lang/ArkScript/Ackermann-function | 1 + Lang/ArkScript/Apply-a-callback-to-an-array | 1 + Lang/ArkScript/Arithmetic-Complex | 1 + Lang/ArkScript/Arithmetic-Integer | 1 + Lang/ArkScript/Array-concatenation | 1 + Lang/ArkScript/Array-length | 1 + Lang/ArkScript/Ascending-primes | 1 + Lang/ArkScript/Associative-array-Creation | 1 + Lang/ArkScript/Associative-array-Iteration | 1 + Lang/ArkScript/Balanced-brackets | 1 + Lang/ArkScript/Boolean-values | 1 + Lang/ArkScript/Calculating-the-value-of-e | 1 + Lang/ArkScript/Call-a-function | 1 + Lang/ArkScript/Call-an-object-method | 1 + Lang/ArkScript/Catamorphism | 1 + Lang/ArkScript/Check-that-file-exists | 1 + Lang/ArkScript/Closures-Value-capture | 1 + Lang/ArkScript/Comments | 1 + Lang/ArkScript/Compound-data-type | 1 + Lang/ArkScript/Concurrent-computing | 1 + Lang/ArkScript/Conditional-structures | 1 + Lang/ArkScript/Conways-Game-of-Life | 1 + Lang/ArkScript/Copy-a-string | 1 + Lang/ArkScript/Currying | 1 + Lang/ArkScript/Delete-a-file | 1 + Lang/ArkScript/Empty-directory | 1 + Lang/ArkScript/Empty-program | 1 + Lang/ArkScript/Empty-string | 1 + Lang/ArkScript/Enforced-immutability | 1 + Lang/ArkScript/Even-or-odd | 1 + Lang/ArkScript/Extend-your-language | 1 + Lang/ArkScript/Fibonacci-sequence | 1 + Lang/ArkScript/FizzBuzz | 1 + Lang/ArkScript/Flatten-a-list | 1 + Lang/ArkScript/Function-definition | 1 + Lang/ArkScript/Hello-world-Line-printer | 1 + Lang/ArkScript/Hello-world-Newline-omission | 1 + Lang/ArkScript/Hello-world-Text | 1 + Lang/ArkScript/Infinity | 1 + Lang/ArkScript/Integer-sequence | 1 + Lang/ArkScript/Literals-Floating-point | 1 + Lang/ArkScript/Literals-Integer | 1 + Lang/ArkScript/Literals-String | 1 + Lang/ArkScript/Logical-operations | 1 + Lang/ArkScript/Munchausen-numbers | 1 + Lang/ArkScript/N-queens-problem | 1 + Lang/ArkScript/Null-object | 1 + Lang/ArkScript/Program-termination | 1 + Lang/ArkScript/Read-entire-file | 1 + Lang/ArkScript/Reverse-a-string | 1 + Lang/ArkScript/Semordnilap | 1 + Lang/ArkScript/Shell-one-liner | 1 + Lang/ArkScript/Short-circuit-evaluation | 1 + Lang/ArkScript/Show-ASCII-table | 1 + Lang/ArkScript/Sleep | 1 + Lang/ArkScript/Sorting-algorithms-Quicksort | 1 + Lang/ArkScript/String-append | 1 + Lang/ArkScript/String-case | 1 + Lang/ArkScript/String-concatenation | 1 + Lang/ArkScript/String-interpolation-included- | 1 + Lang/ArkScript/String-length | 1 + Lang/ArkScript/String-matching | 1 + Lang/ArkScript/String-prepend | 1 + Lang/ArkScript/Sum-and-product-of-an-array | 1 + Lang/ArkScript/Sum-digits-of-an-integer | 1 + Lang/ArkScript/Sum-of-a-series | 1 + Lang/ArkScript/Sum-of-squares | 1 + Lang/ArkScript/User-input-Text | 1 + Lang/ArkScript/Write-entire-file | 1 + Lang/AutoLISP/100-doors | 1 + Lang/AutoLISP/Babbage-problem | 1 + Lang/AutoLISP/Balanced-brackets | 1 + Lang/AutoLISP/Entropy | 1 + Lang/AutoLISP/Entropy-Narcissist | 1 + Lang/AutoLISP/Largest-proper-divisor-of-n | 1 + Lang/AutoLISP/The-Twelve-Days-of-Christmas | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/BBC-BASIC/Multi-dimensional-array | 1 + Lang/Ballerina/Comments | 1 + Lang/Bc/Anti-primes | 1 + Lang/Bc/Arithmetic-derivative | 1 + Lang/Bc/Department-numbers | 1 + Lang/Bc/Fairshare-between-two-and-more | 1 + Lang/Bc/Variables | 1 + Lang/Beeswax/00-LANG.txt | 2 +- Lang/C-sharp/Camel-case-and-snake-case | 1 + Lang/C-sharp/Cistercian-numerals | 1 + Lang/C-sharp/M-bius-function | 1 + Lang/C-sharp/Vogels-approximation-method | 1 + Lang/CBASIC/Factorial | 1 + Lang/CJam/00-LANG.txt | 8 + Lang/CJam/00-META.yaml | 2 + Lang/COBOL/Soloways-recurring-rainfall | 1 + Lang/Calcscript/00-LANG.txt | 10 + Lang/Calcscript/00-META.yaml | 2 + Lang/Common-Lisp/Wieferich-primes | 1 + Lang/Component-Pascal/100-doors | 1 - Lang/Computer-zero-Assembly/00-LANG.txt | 4 +- Lang/Convex/00-LANG.txt | 6 + Lang/Convex/00-META.yaml | 2 + Lang/Crystal/Department-numbers | 1 + Lang/Crystal/Parsing-RPN-calculator-algorithm | 1 + Lang/Crystal/Rot-13 | 1 + .../Singly-linked-list-Element-definition | 1 + .../Singly-linked-list-Element-insertion | 1 + Lang/Crystal/Soloways-recurring-rainfall | 1 + Lang/Crystal/String-interpolation-included- | 1 + Lang/Dart/AVL-tree | 1 + Lang/Dart/Boyer-Moore-string-search | 1 + Lang/Dart/Break-OO-privacy | 1 + Lang/Dart/Continued-fraction | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + Lang/Dart/Dijkstras-algorithm | 1 + Lang/Dart/Floyd-Warshall-algorithm | 1 + Lang/Dart/Parse-an-IP-Address | 1 + Lang/Dart/Tonelli-Shanks-algorithm | 1 + Lang/Draco/Anti-primes | 1 + Lang/DuckDB/00-LANG.txt | 4 + Lang/DuckDB/00-META.yaml | 2 + Lang/DuckDB/100-doors | 1 + Lang/DuckDB/99-bottles-of-beer | 1 + Lang/DuckDB/A+B | 1 + Lang/DuckDB/ABC-problem | 1 + Lang/DuckDB/Anagrams | 1 + Lang/DuckDB/Anonymous-recursion | 1 + Lang/DuckDB/Arithmetic-Complex | 1 + Lang/DuckDB/Arithmetic-Integer | 1 + Lang/DuckDB/Arithmetic-geometric-mean | 1 + Lang/DuckDB/Arithmetic-numbers | 1 + Lang/DuckDB/Array-concatenation | 1 + Lang/DuckDB/Array-length | 1 + Lang/DuckDB/Arrays | 1 + Lang/DuckDB/Associative-array-Creation | 1 + Lang/DuckDB/Associative-array-Iteration | 1 + Lang/DuckDB/Associative-array-Merging | 1 + Lang/DuckDB/Averages-Arithmetic-mean | 1 + Lang/DuckDB/Averages-Mean-angle | 1 + Lang/DuckDB/Averages-Mean-time-of-day | 1 + Lang/DuckDB/Averages-Mode | 1 + Lang/DuckDB/Averages-Pythagorean-means | 1 + Lang/DuckDB/Babbage-problem | 1 + Lang/DuckDB/Benfords-law | 1 + Lang/DuckDB/Bin-given-limits | 1 + Lang/DuckDB/Binary-digits | 1 + Lang/DuckDB/Bioinformatics-base-count | 1 + Lang/DuckDB/Bitwise-IO | 1 + Lang/DuckDB/Bitwise-operations | 1 + Lang/DuckDB/CSV-data-manipulation | 1 + Lang/DuckDB/Call-a-function | 1 + .../Cartesian-product-of-two-or-more-lists | 1 + Lang/DuckDB/Case-sensitivity-of-identifiers | 1 + Lang/DuckDB/Catalan-numbers | 1 + Lang/DuckDB/Catalan-numbers-Pascals-triangle | 1 + Lang/DuckDB/Check-that-file-exists | 1 + Lang/DuckDB/Collections | 1 + Lang/DuckDB/Combinations | 1 + Lang/DuckDB/Combinations-with-repetitions | 1 + Lang/DuckDB/Compare-a-list-of-strings | 1 + Lang/DuckDB/Compare-length-of-two-strings | 1 + Lang/DuckDB/Compound-data-type | 1 + Lang/DuckDB/Conditional-structures | 1 + .../Convert-seconds-to-compound-duration | 1 + Lang/DuckDB/Copy-a-string | 1 + Lang/DuckDB/Count-occurrences-of-a-substring | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/DuckDB/Cumulative-standard-deviation | 1 + Lang/DuckDB/Currency | 1 + Lang/DuckDB/Day-of-the-week | 1 + Lang/DuckDB/Define-a-primitive-data-type | 1 + Lang/DuckDB/Detect-division-by-zero | 1 + Lang/DuckDB/Determinant-and-permanent | 1 + ...ne-if-a-string-has-all-the-same-characters | 1 + ...mine-if-a-string-has-all-unique-characters | 1 + .../Determine-if-a-string-is-collapsible | 1 + Lang/DuckDB/Determine-if-a-string-is-numeric | 1 + .../Determine-if-a-string-is-squeezable | 1 + Lang/DuckDB/Determine-sentence-type | 1 + Lang/DuckDB/Digital-root | 1 + Lang/DuckDB/Diversity-prediction-theorem | 1 + Lang/DuckDB/Documentation | 1 + Lang/DuckDB/Dot-product | 1 + Lang/DuckDB/Dynamic-variable-names | 1 + Lang/DuckDB/Element-wise-operations | 1 + Lang/DuckDB/Empty-string | 1 + Lang/DuckDB/Entropy | 1 + Lang/DuckDB/Enumerations | 1 + Lang/DuckDB/Equilibrium-index | 1 + Lang/DuckDB/Euler-method | 1 + Lang/DuckDB/Eulers-constant-0.5772... | 1 + Lang/DuckDB/Eulers-identity | 1 + Lang/DuckDB/Evaluate-binomial-coefficients | 1 + Lang/DuckDB/Even-or-odd | 1 + Lang/DuckDB/Exponentiation-order | 1 + Lang/DuckDB/Extreme-floating-point-values | 1 + Lang/DuckDB/Factorial | 1 + Lang/DuckDB/Factors-of-an-integer | 1 + Lang/DuckDB/Fairshare-between-two-and-more | 1 + Lang/DuckDB/Feigenbaum-constant-calculation | 1 + Lang/DuckDB/Fibonacci-sequence | 1 + Lang/DuckDB/File-input-output | 1 + Lang/DuckDB/Filter | 1 + Lang/DuckDB/Find-limit-of-recursion | 1 + .../DuckDB/Find-the-last-Sunday-of-each-month | 1 + Lang/DuckDB/Five-weekends | 1 + Lang/DuckDB/Fixed-length-records | 1 + Lang/DuckDB/Flatten-a-list | 1 + Lang/DuckDB/Formatted-numeric-output | 1 + Lang/DuckDB/Forward-difference | 1 + Lang/DuckDB/Function-definition | 1 + Lang/DuckDB/Gamma-function | 1 + Lang/DuckDB/Gapful-numbers | 1 + .../DuckDB/Generate-lower-case-ASCII-alphabet | 1 + Lang/DuckDB/Generic-swap | 1 + Lang/DuckDB/Golden-ratio-Convergence | 1 + Lang/DuckDB/Gotchas | 1 + Lang/DuckDB/Greatest-common-divisor | 1 + Lang/DuckDB/Greatest-element-of-a-list | 1 + Lang/DuckDB/Greatest-subsequential-sum | 1 + Lang/DuckDB/HTTP | 1 + Lang/DuckDB/HTTPS | 1 + Lang/DuckDB/HTTPS-Authenticated | 1 + Lang/DuckDB/Hailstone-sequence | 1 + Lang/DuckDB/Harmonic-series | 1 + Lang/DuckDB/Hash-from-two-arrays | 1 + Lang/DuckDB/Hash-join | 1 + Lang/DuckDB/Haversine-formula | 1 + Lang/DuckDB/Hello-world-Text | 1 + Lang/DuckDB/Here-document | 1 + Lang/DuckDB/ISBN13-check-digit | 1 + Lang/DuckDB/Identity-matrix | 1 + ...he-characters-that-can-be-used-for-symbols | 1 + ...ne-all-the-lowercase-and-uppercase-letters | 1 + Lang/DuckDB/Increment-a-numerical-string | 1 + Lang/DuckDB/Infinity | 1 + Lang/DuckDB/Integer-comparison | 1 + Lang/DuckDB/Introspection | 1 + Lang/DuckDB/Inverted-index | 1 + Lang/DuckDB/Inverted-syntax | 1 + Lang/DuckDB/JSON | 1 + Lang/DuckDB/Jaro-similarity | 1 + Lang/DuckDB/Knuth-shuffle | 1 + .../DuckDB/Largest-int-from-concatenated-ints | 1 + Lang/DuckDB/Last-Friday-of-each-month | 1 + Lang/DuckDB/Leap-year | 1 + Lang/DuckDB/Left-factorials | 1 + Lang/DuckDB/Leonardo-numbers | 1 + Lang/DuckDB/Letter-frequency | 1 + Lang/DuckDB/Levenshtein-distance | 1 + Lang/DuckDB/List-comprehensions | 1 + Lang/DuckDB/Literals-Integer | 1 + Lang/DuckDB/Logical-operations | 1 + Lang/DuckDB/Longest-increasing-subsequence | 1 + Lang/DuckDB/Loops-Break | 1 + Lang/DuckDB/Loops-Do-while | 1 + Lang/DuckDB/Loops-Downward-for | 1 + Lang/DuckDB/Loops-For | 1 + Lang/DuckDB/Loops-For-with-a-specified-step | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/DuckDB/Loops-N-plus-one-half | 1 + Lang/DuckDB/Loops-Nested | 1 + Lang/DuckDB/Loops-While | 1 + Lang/DuckDB/Loops-With-multiple-ranges | 1 + Lang/DuckDB/Luhn-test-of-credit-card-numbers | 1 + Lang/DuckDB/MD5 | 1 + Lang/DuckDB/Map-range | 1 + Lang/DuckDB/Matrix-multiplication | 1 + Lang/DuckDB/Matrix-transposition | 1 + Lang/DuckDB/Merge-and-aggregate-datasets | 1 + Lang/DuckDB/Metallic-ratios | 1 + Lang/DuckDB/Middle-three-digits | 1 + Lang/DuckDB/Monte-Carlo-methods | 1 + Lang/DuckDB/Nested-function | 1 + Lang/DuckDB/Nth | 1 + Lang/DuckDB/Nth-root | 1 + Lang/DuckDB/One-of-n-lines-in-a-file | 1 + Lang/DuckDB/Order-two-numerical-lists | 1 + Lang/DuckDB/Ordered-words | 1 + Lang/DuckDB/Palindrome-detection | 1 + Lang/DuckDB/Parameterized-SQL-statement | 1 + Lang/DuckDB/Pascals-triangle | 1 + Lang/DuckDB/Permutations | 1 + Lang/DuckDB/Permutations-Derangements | 1 + Lang/DuckDB/Pick-random-element | 1 + Lang/DuckDB/Primality-by-trial-division | 1 + Lang/DuckDB/Prime-decomposition | 1 + Lang/DuckDB/Probabilistic-choice | 1 + Lang/DuckDB/Proper-divisors | 1 + ...Pseudo-random-numbers-Middle-square-method | 1 + Lang/DuckDB/Random-numbers | 1 + Lang/DuckDB/Range-expansion | 1 + Lang/DuckDB/Range-extraction | 1 + Lang/DuckDB/Read-a-file-line-by-line | 1 + Lang/DuckDB/Reflection-List-methods | 1 + Lang/DuckDB/Reflection-List-properties | 1 + Lang/DuckDB/Remove-duplicate-elements | 1 + Lang/DuckDB/Rep-string | 1 + Lang/DuckDB/Repeat-a-string | 1 + Lang/DuckDB/Return-multiple-values | 1 + Lang/DuckDB/Reverse-a-string | 1 + Lang/DuckDB/Roots-of-unity | 1 + Lang/DuckDB/Run-length-encoding | 1 + Lang/DuckDB/Search-a-list-of-records | 1 + Lang/DuckDB/Set | 1 + Lang/DuckDB/Set-consolidation | 1 + Lang/DuckDB/Show-the-epoch | 1 + Lang/DuckDB/Sieve-of-Eratosthenes | 1 + .../Sort-an-array-of-composite-structures | 1 + Lang/DuckDB/Sort-numbers-lexicographically | 1 + Lang/DuckDB/Statistics-Basic | 1 + Lang/DuckDB/String-append | 1 + Lang/DuckDB/String-case | 1 + Lang/DuckDB/String-comparison | 1 + Lang/DuckDB/String-interpolation-included- | 1 + Lang/DuckDB/String-length | 1 + Lang/DuckDB/String-matching | 1 + Lang/DuckDB/String-prepend | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/DuckDB/Strip-comments-from-a-string | 1 + ...odes-and-extended-characters-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/DuckDB/Substring | 1 + Lang/DuckDB/Sudoku | 1 + Lang/DuckDB/Sum-and-product-of-an-array | 1 + Lang/DuckDB/Sum-digits-of-an-integer | 1 + Lang/DuckDB/Sum-multiples-of-3-and-5 | 1 + Lang/DuckDB/Sum-of-a-series | 1 + Lang/DuckDB/Sum-of-squares | 1 + Lang/DuckDB/Symmetric-difference | 1 + Lang/DuckDB/Table-creation-Postal-addresses | 1 + Lang/DuckDB/Test-integerness | 1 + Lang/DuckDB/Text-processing-2 | 1 + Lang/DuckDB/Thue-Morse | 1 + Lang/DuckDB/Time-a-function | 1 + Lang/DuckDB/Tokenize-a-string | 1 + Lang/DuckDB/Top-rank-per-group | 1 + Lang/DuckDB/Trigonometric-functions | 1 + Lang/DuckDB/URL-decoding | 1 + Lang/DuckDB/UTF-8-encode-and-decode | 1 + Lang/DuckDB/Unix-ls | 1 + Lang/DuckDB/Variable-size-Get | 1 + Lang/DuckDB/Variable-size-Set | 1 + Lang/DuckDB/Vector-products | 1 + Lang/DuckDB/Zero-to-the-zero-power | 1 + Lang/DuckDB/Zig-zag-matrix | 1 + Lang/EasyLang/AKS-test-for-primes | 1 + .../EasyLang/Bitmap-Midpoint-circle-algorithm | 1 + Lang/EasyLang/Cholesky-decomposition | 1 + Lang/EasyLang/Currency | 1 + Lang/EasyLang/Death-Star | 1 + ...stribution-of-0-digits-in-factorial-series | 1 + Lang/EasyLang/Draw-a-sphere | 1 + Lang/EasyLang/EKG-sequence-convergence | 1 + .../Earliest-difference-between-prime-gaps | 1 + ...mentary-cellular-automaton-Infinite-length | 1 + .../Erd-s-Selfridge-categorization-of-primes | 1 + Lang/EasyLang/Faulhabers-formula | 1 + Lang/EasyLang/Faulhabers-triangle | 1 + Lang/EasyLang/Fibonacci-word-fractal | 1 + ...Find-Chess960-starting-position-identifier | 1 + Lang/EasyLang/Fraction-reduction | 1 + Lang/EasyLang/French-Republican-calendar | 1 + Lang/EasyLang/Function-prototype | 1 + Lang/EasyLang/Hash-from-two-arrays | 1 + Lang/EasyLang/Honeycombs | 1 + Lang/EasyLang/Hunt-the-Wumpus | 1 + Lang/EasyLang/Jacobsthal-numbers | 1 + Lang/EasyLang/Pascals-triangle-Puzzle | 1 + Lang/EasyLang/Straddling-checkerboard | 1 + Lang/EasyLang/Unicode-strings | 1 + Lang/Eiffel/Loops-For | 1 + Lang/Eiffel/Loops-Infinite | 1 + Lang/Elixir/Determinant-and-permanent | 1 + Lang/Elixir/K-d-tree | 1 + Lang/Elixir/Parse-an-IP-Address | 1 + Lang/Erlang/Determinant-and-permanent | 1 + Lang/Erlang/Floyd-Warshall-algorithm | 1 + Lang/Excel/Jacobi-symbol | 1 + Lang/Extended-Color-BASIC/00-LANG.txt | 7 + Lang/Extended-Color-BASIC/00-META.yaml | 2 + Lang/Extended-Color-BASIC/Arrays | 1 + Lang/Extended-Color-BASIC/Copy-a-string | 1 + Lang/Extended-Color-BASIC/Hello-world-Text | 1 + Lang/Extended-Color-BASIC/Loops-For | 1 + Lang/Extended-Color-BASIC/Quine | 1 + Lang/Extended-Color-BASIC/User-input-Text | 1 + Lang/F-Sharp/Long-multiplication | 1 - Lang/F-Sharp/Multiplicative-order | 1 + Lang/Factor/Best-shuffle | 1 + Lang/Fennel/00-LANG.txt | 7 +- ...ficient-and-perfect-number-classifications | 1 + Lang/Fennel/Factorial | 1 + Lang/Fennel/Factorial-primes | 1 + Lang/Fennel/Goldbachs-comet | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/Fennel/Jacobsthal-numbers | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + Lang/Fennel/Time-a-function | 1 + Lang/Fennel/Yellowstone-sequence | 1 + Lang/Fortran/Associative-array-Merging | 1 + Lang/Fortran/Catalan-numbers-Pascals-triangle | 1 + Lang/Fortran/Chinese-zodiac | 1 + Lang/Fortran/Cyclotomic-polynomial | 1 + Lang/Fortran/Disarium-numbers | 1 + Lang/Fortran/Display-a-linear-combination | 1 + Lang/Fortran/EKG-sequence-convergence | 1 + Lang/Fortran/Egyptian-division | 1 + Lang/Fortran/French-Republican-calendar | 1 + .../Hofstadter-Figure-Figure-sequences | 1 + Lang/Fortran/Humble-numbers | 1 + Lang/Fortran/Jewels-and-stones | 1 + Lang/Fortran/Knapsack-problem-Bounded | 1 + Lang/Fortran/Knuths-power-tree | 1 + Lang/Fortran/McNuggets-problem | 1 + Lang/Fortran/Parse-an-IP-Address | 1 + Lang/Fortran/Pascals-triangle-Puzzle | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + Lang/Fortran/Totient-function | 1 + Lang/Fortran/Twos-complement | 1 + Lang/Free-Pascal-Lazarus/Abstract-type | 1 + Lang/Free-Pascal-Lazarus/Cistercian-numerals | 1 + Lang/Free-Pascal-Lazarus/Pancake-numbers | 1 + Lang/FreeBASIC/Babylonian-spiral | 1 + .../FreeBASIC/Bitcoin-public-point-to-address | 1 + .../Catmull-Clark-subdivision-surface | 1 + Lang/FreeBASIC/Color-quantization | 1 + Lang/FreeBASIC/Dominoes | 1 + Lang/FreeBASIC/Find-duplicate-files | 1 + ...est-left-truncatable-prime-in-a-given-base | 1 + ...rate-English-text-using-the-Greek-alphabet | 1 + Lang/Frink/Disarium-numbers | 1 + Lang/Frink/Happy-numbers | 1 + Lang/FuncSug/00-LANG.txt | 1 + Lang/FuncSug/00-META.yaml | 2 + Lang/FuncSug/GUI-component-interaction | 1 + .../GUI-enabling-disabling-of-controls | 1 + Lang/FuncSug/Hello-world-Text | 1 + Lang/FuncSug/Play-recorded-sounds | 1 + Lang/FuncSug/Simple-windowed-application | 1 + Lang/FuncSug/Simulate-input-Mouse | 1 + Lang/FuncSug/User-input-Graphical | 1 + Lang/FutureBasic/Arithmetic-Complex | 1 + Lang/FutureBasic/Averages-Mean-time-of-day | 1 + Lang/FutureBasic/Boyer-Moore-string-search | 1 + Lang/FutureBasic/CRC-32 | 1 + .../Carmichael-3-strong-pseudoprimes | 1 + Lang/FutureBasic/Deal-cards-for-FreeCell | 1 + Lang/FutureBasic/Demings-funnel | 1 + Lang/FutureBasic/Euler-method | 1 + Lang/FutureBasic/Find-limit-of-recursion | 1 + Lang/FutureBasic/Five-weekends | 1 + Lang/FutureBasic/Gamma-function | 1 + Lang/FutureBasic/Gaussian-elimination | 1 + .../Guess-the-number-With-feedback-player- | 1 + Lang/FutureBasic/Hamming-numbers | 1 + Lang/FutureBasic/Last-letter-first-letter | 1 + Lang/FutureBasic/Mayan-numerals | 1 + Lang/FutureBasic/Modular-inverse | 1 + Lang/FutureBasic/Monte-Carlo-methods | 1 + Lang/FutureBasic/Mutex | 1 + Lang/FutureBasic/Named-parameters | 1 + Lang/FutureBasic/Perfect-shuffle | 1 + Lang/FutureBasic/Sierpinski-pentagon | 1 + Lang/FutureBasic/Sleep | 1 + .../Sorting-algorithms-Insertion-sort | 1 + .../FutureBasic/Sorting-algorithms-Sleep-sort | 1 + Lang/FutureBasic/Stack-traces | 1 + Lang/FutureBasic/String-length | 1 + Lang/FutureBasic/Sum-of-a-series | 1 + Lang/FutureBasic/Sum-to-100 | 1 + Lang/FutureBasic/Tau-function | 1 + Lang/FutureBasic/Tau-number | 1 + Lang/FutureBasic/Word-wrap | 1 + Lang/FutureBasic/Yellowstone-sequence | 1 + Lang/FutureBasic/Zebra-puzzle | 1 + Lang/GW-BASIC/Old-Russian-measure-of-length | 1 + Lang/Go/Distance-and-Bearing | 1 + Lang/Goboscript/00-LANG.txt | 1 + Lang/Goboscript/00-META.yaml | 2 + Lang/Haskell/00-LANG.txt | 4 +- Lang/Haxe/Abstract-type | 1 + Lang/Haxe/Apply-a-callback-to-an-array | 1 + Lang/Haxe/Arrays | 1 + Lang/Haxe/Associative-array-Creation | 1 + Lang/Haxe/Associative-array-Iteration | 1 + Lang/Haxe/Binary-digits | 1 + Lang/Haxe/Boolean-values | 1 + Lang/Haxe/Call-an-object-method | 1 + Lang/Haxe/Character-codes | 1 + Lang/Haxe/Classes | 1 + Lang/Icon/00-LANG.txt | 6 +- Lang/Icon/Exponentiation-order | 1 + Lang/Icon/Jewels-and-stones | 1 + Lang/Icon/Loops-Wrong-ranges | 1 + Lang/Icon/Search-a-list-of-records | 1 + Lang/Icon/Sort-numbers-lexicographically | 1 + Lang/Icon/Tokenize-a-string-with-escaping | 1 + Lang/Icon/Tree-from-nesting-levels | 1 + Lang/Idris/Comments | 1 + Lang/Insitux/00-LANG.txt | 6 +- Lang/Janet/Comments | 1 + .../Aliquot-sequence-classifications | 1 + Lang/JavaScript/B-zier-curves-Intersections | 1 + Lang/JavaScript/Balanced-ternary | 1 + .../Bitcoin-public-point-to-address | 1 + Lang/JavaScript/Break-OO-privacy | 1 + .../Catmull-Clark-subdivision-surface | 1 + Lang/JavaScript/Checkpoint-synchronization | 1 + Lang/JavaScript/Continued-fraction | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + Lang/JavaScript/Deconvolution-1D | 1 + Lang/JavaScript/Deconvolution-2D+ | 1 + Lang/JavaScript/MD5 | 1 + Lang/JavaScript/Meissel-Mertens-constant | 1 + Lang/JavaScript/Parse-an-IP-Address | 1 + Lang/JavaScript/Pascals-triangle-Puzzle | 1 + Lang/JavaScript/Sokoban | 1 + Lang/JavaScript/Solve-a-Hopido-puzzle | 1 + Lang/JavaScript/Superpermutation-minimisation | 1 + Lang/JavaScript/Tarjan | 1 + Lang/Julia/OLE-automation | 1 + Lang/Julia/Simulate-input-Keyboard | 1 + .../Use-another-language-to-call-a-function | 1 + Lang/Kantalo/00-LANG.txt | 40 ++ Lang/Kantalo/00-META.yaml | 2 + Lang/Koka/00-LANG.txt | 2 +- Lang/Koka/A+B | 1 + Lang/Koka/Extend-your-language | 1 + Lang/Koka/Jump-anywhere | 1 + Lang/Koka/Letter-frequency | 1 + Lang/Koka/Loops-Break | 1 + Lang/Koka/Monads-Writer-monad | 1 + Lang/Kotlin/Boyer-Moore-string-search | 1 + Lang/Labyrinth/00-LANG.txt | 1 + Lang/Labyrinth/00-META.yaml | 2 + Lang/Liberty-BASIC/Hunt-the-Wumpus | 1 + Lang/Liberty-BASIC/Minesweeper-game | 1 + Lang/Liberty-BASIC/Snake | 1 + Lang/Logo/Sparkline-in-unicode | 1 + Lang/Lua/100-doors | 1 - Lang/Lua/Jacobsthal-numbers | 1 + Lang/Lua/Knapsack-problem-Bounded | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + .../Use-another-language-to-call-a-function | 1 + Lang/Lua/Wagstaff-primes | 1 + Lang/Lua/Wieferich-primes | 1 + Lang/Mathematica/ASCII-art-diagram-converter | 1 + Lang/Mathematica/Camel-case-and-snake-case | 1 + Lang/Mathematica/Erd-s-Nicolas-numbers | 1 + Lang/Mathematica/Parse-an-IP-Address | 1 + Lang/Mathematica/Tonelli-Shanks-algorithm | 1 + Lang/Mathematica/Vogels-approximation-method | 1 + Lang/Maxima/Array-length | 1 + Lang/Maxima/Delete-a-file | 1 + Lang/Maxima/Hash-from-two-arrays | 1 + Lang/Maxima/Real-constants-and-functions | 1 + Lang/Maxima/Regular-expressions | 1 + Lang/Maxima/Rename-a-file | 1 + Lang/Maxima/Sorting-algorithms-Stooge-sort | 1 + Lang/Maxima/Statistics-Basic | 1 + Lang/Maxima/Substring-Top-and-tail | 1 + Lang/Maxima/Superellipse | 1 + Lang/Maxima/Topic-variable | 1 + Lang/Maxima/Towers-of-Hanoi | 1 + Lang/Mn/00-LANG.txt | 7 + Lang/Mn/00-META.yaml | 2 + Lang/Mn/Factorial | 1 + Lang/Mn/Loops-While | 1 + Lang/Modula-2/AKS-test-for-primes | 1 + Lang/Modula-2/Cistercian-numerals | 1 + Lang/Mojo/Hunt-the-Wumpus | 1 + .../Old-Russian-measure-of-length | 1 + Lang/Nom/00-LANG.txt | 18 + Lang/Nom/00-META.yaml | 2 + Lang/Nom/Balanced-brackets | 1 + Lang/Nom/CSV-to-HTML-translation | 1 + Lang/Nom/Determine-if-a-string-is-numeric | 1 + Lang/Nom/Empty-string | 1 + Lang/Nom/Even-or-odd | 1 + Lang/Nom/Hello-world-Text | 1 + Lang/Nom/Input-loop | 1 + Lang/Nom/Odd-word-problem | 1 + Lang/Nom/Reverse-a-string | 1 + Lang/OCaml/Parse-an-IP-Address | 1 + Lang/OCaml/Sorting-algorithms-Sleep-sort | 1 + Lang/Objeck/Catalan-numbers-Pascals-triangle | 1 + Lang/Objeck/Disarium-numbers | 1 + Lang/Objeck/HTTPS-Client-authenticated | 1 + .../Objeck/Magic-squares-of-doubly-even-order | 1 + Lang/Objeck/Matrix-multiplication | 1 + .../Object-Pascal-Implementations/00-LANG.txt | 3 + .../00-META.yaml | 2 + Lang/Odin/Comments | 1 + Lang/OoRexx/Prime-decomposition | 1 + Lang/OxygenBasic/Josephus-problem | 1 + Lang/PARI-GP/Pell-numbers | 1 + Lang/PARI-GP/Tonelli-Shanks-algorithm | 1 + Lang/PHP/AKS-test-for-primes | 1 + Lang/PL-M/100-doors | 1 - Lang/Pascal-P/00-LANG.txt | 23 + Lang/Pascal-P/00-META.yaml | 2 + Lang/Pascal-P/Cistercian-numerals | 1 + Lang/Pascal-P/FizzBuzz | 1 + Lang/Pascal-P/Leonardo-numbers | 1 + Lang/Pascal-P/Levenshtein-distance | 1 + Lang/Pascal-P/M-bius-function | 1 + Lang/Pascal-P/Magic-constant | 1 + Lang/Pascal-P/Map-range | 1 + .../Ramer-Douglas-Peucker-line-simplification | 1 + Lang/PascalABC.NET/15-puzzle-solver | 1 + Lang/PascalABC.NET/Abbreviations-easy | 1 + Lang/PascalABC.NET/Abbreviations-simple | 1 + Lang/PascalABC.NET/Arithmetic-evaluation | 1 + Lang/PascalABC.NET/Bioinformatics-base-count | 1 + .../Case-sensitivity-of-identifiers | 1 + .../Combinations-with-repetitions | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + Lang/Pico-8/00-LANG.txt | 1 + Lang/Pico-8/00-META.yaml | 2 + Lang/Pico-8/Hello-world-Text | 1 + Lang/Pluto/00-LANG.txt | 41 ++ Lang/Pluto/00-META.yaml | 2 + Lang/Pluto/99-bottles-of-beer | 1 + Lang/Pluto/A+B | 1 + Lang/Pluto/ABC-problem | 1 + Lang/Pluto/AKS-test-for-primes | 1 + Lang/Pluto/Abelian-sandpile-model | 1 + Lang/Pluto/Abelian-sandpile-model-Identity | 1 + Lang/Pluto/Abstract-type | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Pluto/Abundant-odd-numbers | 1 + Lang/Pluto/Achilles-numbers | 1 + Lang/Pluto/Ackermann-function | 1 + Lang/Pluto/Address-of-a-variable | 1 + Lang/Pluto/Almost-prime | 1 + Lang/Pluto/Anti-primes | 1 + Lang/Pluto/Approximate-equality | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/Pluto/Arithmetic-Complex | 1 + Lang/Pluto/Arithmetic-Integer | 1 + Lang/Pluto/Arithmetic-Rational | 1 + Lang/Pluto/Arithmetic-derivative | 1 + Lang/Pluto/Arithmetic-geometric-mean | 1 + Lang/Pluto/Array-concatenation | 1 + Lang/Pluto/Arrays | 1 + Lang/Pluto/Ascending-primes | 1 + Lang/Pluto/Associative-array-Creation | 1 + Lang/Pluto/Associative-array-Iteration | 1 + Lang/Pluto/Associative-array-Merging | 1 + Lang/Pluto/Attractive-numbers | 1 + Lang/Pluto/Averages-Arithmetic-mean | 1 + Lang/Pluto/Averages-Median | 1 + Lang/Pluto/Averages-Pythagorean-means | 1 + Lang/Pluto/Averages-Root-mean-square | 1 + Lang/Pluto/Balanced-brackets | 1 + Lang/Pluto/Base64-decode-data | 1 + Lang/Pluto/Bell-numbers | 1 + Lang/Pluto/Bitmap | 1 + Lang/Pluto/Bitmap-Bresenhams-line-algorithm | 1 + Lang/Pluto/Bitmap-Midpoint-circle-algorithm | 1 + Lang/Pluto/Bitwise-operations | 1 + Lang/Pluto/CRC-32 | 1 + Lang/Pluto/Caesar-cipher | 1 + Lang/Pluto/Calkin-Wilf-sequence | 1 + Lang/Pluto/Call-a-foreign-language-function | 1 + .../Pluto/Call-a-function-in-a-shared-library | 1 + Lang/Pluto/Case-sensitivity-of-identifiers | 1 + Lang/Pluto/Casting-out-nines | 1 + Lang/Pluto/Collections | 1 + Lang/Pluto/Combinations | 1 + Lang/Pluto/Combinations-with-repetitions | 1 + Lang/Pluto/Command-line-arguments | 1 + Lang/Pluto/Comments | 1 + Lang/Pluto/Compare-length-of-two-strings | 1 + Lang/Pluto/Compiler-lexical-analyzer | 1 + Lang/Pluto/Conditional-structures | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/Pluto/Convert-decimal-number-to-rational | 1 + Lang/Pluto/Count-in-octal | 1 + Lang/Pluto/Count-the-coins | 1 + Lang/Pluto/Create-a-file | 1 + Lang/Pluto/Currying | 1 + Lang/Pluto/Delete-a-file | 1 + Lang/Pluto/Descending-primes | 1 + Lang/Pluto/Determine-if-a-string-is-numeric | 1 + Lang/Pluto/Disarium-numbers | 1 + Lang/Pluto/Display-a-linear-combination | 1 + ...stribution-of-0-digits-in-factorial-series | 1 + Lang/Pluto/Doubly-linked-list-Definition | 1 + .../Doubly-linked-list-Element-definition | 1 + Lang/Pluto/Doubly-linked-list-Traversal | 1 + Lang/Pluto/Dutch-national-flag-problem | 1 + Lang/Pluto/Euler-method | 1 + Lang/Pluto/Eulers-identity | 1 + Lang/Pluto/Even-or-odd | 1 + Lang/Pluto/Execute-a-system-command | 1 + Lang/Pluto/Factorial | 1 + Lang/Pluto/Factorial-primes | 1 + Lang/Pluto/Factorions | 1 + Lang/Pluto/Factors-of-an-integer | 1 + Lang/Pluto/Farey-sequence | 1 + Lang/Pluto/Feigenbaum-constant-calculation | 1 + Lang/Pluto/Fibonacci-sequence | 1 + Lang/Pluto/Filter | 1 + Lang/Pluto/FizzBuzz | 1 + Lang/Pluto/Floyd-Warshall-algorithm | 1 + Lang/Pluto/Formatted-numeric-output | 1 + Lang/Pluto/Function-definition | 1 + Lang/Pluto/Gamma-function | 1 + Lang/Pluto/Generate-lower-case-ASCII-alphabet | 1 + Lang/Pluto/Giuga-numbers | 1 + Lang/Pluto/Goldbachs-comet | 1 + Lang/Pluto/Greatest-common-divisor | 1 + Lang/Pluto/Greatest-element-of-a-list | 1 + Lang/Pluto/Hailstone-sequence | 1 + Lang/Pluto/Halt-and-catch-fire | 1 + Lang/Pluto/Hash-from-two-arrays | 1 + Lang/Pluto/Hello-world-Newline-omission | 1 + Lang/Pluto/Hello-world-Standard-error | 1 + Lang/Pluto/Hello-world-Text | 1 + Lang/Pluto/Higher-order-functions | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/Pluto/Humble-numbers | 1 + Lang/Pluto/Increment-a-numerical-string | 1 + Lang/Pluto/Infinity | 1 + Lang/Pluto/JSON | 1 + Lang/Pluto/Jacobsthal-numbers | 1 + Lang/Pluto/Jewels-and-stones | 1 + Lang/Pluto/Josephus-problem | 1 + Lang/Pluto/Kaprekar-numbers | 1 + Lang/Pluto/Leap-year | 1 + Lang/Pluto/Literals-Floating-point | 1 + Lang/Pluto/Literals-Integer | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Pluto/Loops-Break | 1 + Lang/Pluto/Loops-Continue | 1 + Lang/Pluto/Loops-Do-while | 1 + Lang/Pluto/Loops-Downward-for | 1 + Lang/Pluto/Loops-For | 1 + Lang/Pluto/Loops-For-with-a-specified-step | 1 + Lang/Pluto/Loops-Foreach | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/Pluto/Loops-Infinite | 1 + Lang/Pluto/Loops-N-plus-one-half | 1 + Lang/Pluto/Loops-Nested | 1 + Lang/Pluto/Loops-While | 1 + Lang/Pluto/Loops-With-multiple-ranges | 1 + Lang/Pluto/Loops-Wrong-ranges | 1 + Lang/Pluto/Luhn-test-of-credit-card-numbers | 1 + Lang/Pluto/M-bius-function | 1 + Lang/Pluto/Machine-code | 1 + Lang/Pluto/Magic-squares-of-doubly-even-order | 1 + Lang/Pluto/Magic-squares-of-odd-order | 1 + Lang/Pluto/Magic-squares-of-singly-even-order | 1 + Lang/Pluto/Mian-Chowla-sequence | 1 + Lang/Pluto/Modular-inverse | 1 + Lang/Pluto/Multiplication-tables | 1 + Lang/Pluto/Mutual-recursion | 1 + Lang/Pluto/Named-parameters | 1 + Lang/Pluto/Narcissistic-decimal-number | 1 + Lang/Pluto/Nested-templated-data | 1 + Lang/Pluto/Non-decimal-radices-Convert | 1 + Lang/Pluto/Numerical-integration | 1 + Lang/Pluto/Old-Russian-measure-of-length | 1 + Lang/Pluto/Order-by-pair-comparisons | 1 + Lang/Pluto/Palindrome-detection | 1 + Lang/Pluto/Pancake-numbers | 1 + Lang/Pluto/Parsing-RPN-calculator-algorithm | 1 + Lang/Pluto/Pascals-triangle-Puzzle | 1 + Lang/Pluto/Perfect-shuffle | 1 + Lang/Pluto/Permutations | 1 + Lang/Pluto/Pernicious-numbers | 1 + Lang/Pluto/Pick-random-element | 1 + Lang/Pluto/Pisano-period | 1 + Lang/Pluto/Power-set | 1 + Lang/Pluto/Primality-by-trial-division | 1 + Lang/Pluto/Priority-queue | 1 + Lang/Pluto/Read-a-file-line-by-line | 1 + Lang/Pluto/Rename-a-file | 1 + Lang/Pluto/Repeat-a-string | 1 + Lang/Pluto/Reverse-a-string | 1 + Lang/Pluto/Reverse-words-in-a-string | 1 + Lang/Pluto/Roman-numerals-Encode | 1 + Lang/Pluto/Roots-of-a-quadratic-function | 1 + Lang/Pluto/Roots-of-unity | 1 + Lang/Pluto/Rot-13 | 1 + Lang/Pluto/Runge-Kutta-method | 1 + Lang/Pluto/Self-numbers | 1 + Lang/Pluto/Semordnilap | 1 + .../Sequence-of-primes-by-trial-division | 1 + Lang/Pluto/Set | 1 + Lang/Pluto/Set-consolidation | 1 + .../Singly-linked-list-Element-definition | 1 + .../Singly-linked-list-Element-insertion | 1 + Lang/Pluto/Singly-linked-list-Traversal | 1 + Lang/Pluto/Sleep | 1 + Lang/Pluto/Smarandache-prime-digital-sequence | 1 + Lang/Pluto/Soloways-recurring-rainfall | 1 + Lang/Pluto/Sort-an-integer-array | 1 + Lang/Pluto/Stack | 1 + Lang/Pluto/String-interpolation-included- | 1 + Lang/Pluto/String-length | 1 + Lang/Pluto/Sum-digits-of-an-integer | 1 + ...-of-elements-below-main-diagonal-of-matrix | 1 + Lang/Pluto/Symmetric-difference | 1 + Lang/Pluto/System-time | 1 + Lang/Pluto/Tau-function | 1 + Lang/Pluto/Tau-number | 1 + Lang/Pluto/Terminal-control-Clear-the-screen | 1 + Lang/Pluto/Terminal-control-Coloured-text | 1 + Lang/Pluto/Terminal-control-Cursor-movement | 1 + .../Pluto/Terminal-control-Cursor-positioning | 1 + Lang/Pluto/Terminal-control-Dimensions | 1 + ...inal-control-Display-an-extended-character | 1 + Lang/Pluto/Terminal-control-Hiding-the-cursor | 1 + Lang/Pluto/Terminal-control-Inverse-video | 1 + Lang/Pluto/Terminal-control-Preserve-screen | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/Pluto/Terminal-control-Unicode-output | 1 + Lang/Pluto/Test-integerness | 1 + Lang/Pluto/Time-a-function | 1 + Lang/Pluto/Total-circles-area | 1 + Lang/Pluto/Totient-function | 1 + Lang/Pluto/Towers-of-Hanoi | 1 + Lang/Pluto/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Pluto/UPC | 1 + Lang/Pluto/Unicode-strings | 1 + Lang/Pluto/Unprimeable-numbers | 1 + Lang/Pluto/User-input-Text | 1 + Lang/Pluto/Van-Eck-sequence | 1 + Lang/Pluto/Van-der-Corput-sequence | 1 + Lang/Pluto/Variadic-function | 1 + Lang/Pluto/Vector | 1 + Lang/Pluto/Vector-products | 1 + Lang/Pluto/Wagstaff-primes | 1 + Lang/Pluto/Wieferich-primes | 1 + Lang/Pluto/Y-combinator | 1 + Lang/Pluto/Yellowstone-sequence | 1 + Lang/Pluto/Zebra-puzzle | 1 + Lang/Pluto/Zero-to-the-zero-power | 1 + Lang/PowerShell/AKS-test-for-primes | 1 + Lang/PowerShell/M-bius-function | 1 + Lang/Prolog/100-prisoners | 1 + Lang/Prolog/Boolean-values | 1 + Lang/Prolog/Damm-algorithm | 1 + Lang/Prolog/Hello-world-Newline-omission | 1 + Lang/Prolog/ISBN13-check-digit | 1 + Lang/Prolog/Integer-comparison | 1 + Lang/Prolog/Iterated-digits-squaring | 1 + Lang/Prolog/Josephus-problem | 1 + Lang/Prolog/Magic-8-ball | 1 + Lang/Prolog/Old-Russian-measure-of-length | 1 + Lang/Prolog/Order-by-pair-comparisons | 1 + Lang/Prolog/Phrase-reversals | 1 + Lang/Prolog/Population-count | 1 + Lang/Prolog/RPG-attributes-generator | 1 + Lang/Prolog/SEDOLs | 1 + Lang/Prolog/Semordnilap | 1 + Lang/Prolog/Sort-three-variables | 1 + Lang/Prolog/Stem-and-leaf-plot | 1 + Lang/Prolog/String-concatenation | 1 + Lang/Prolog/Thue-Morse | 1 + Lang/Prolog/Topswops | 1 + Lang/Prolog/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Prolog/Wireworld | 1 + Lang/Prolog/Zero-to-the-zero-power | 1 + Lang/Python/Ruth-Aaron-numbers | 1 + Lang/QB64/Trabb-Pardo-Knuth-algorithm | 1 + ...les-geometric-normalization-and-conversion | 1 + Lang/R/CUSIP | 1 + Lang/R/Continued-fraction | 1 + Lang/R/Cramers-rule | 1 + Lang/R/Curzon-numbers | 1 + Lang/R/Dijkstras-algorithm | 1 + Lang/R/Execute-HQ9+ | 1 + Lang/R/Factorial-primes | 1 + Lang/R/Fibonacci-n-step-number-sequences | 1 + Lang/R/Flipping-bits-game | 1 + Lang/R/Floyd-Warshall-algorithm | 1 + Lang/R/Fractran | 1 + Lang/R/Giuga-numbers | 1 + .../R/Greedy-algorithm-for-Egyptian-fractions | 1 + Lang/R/Humble-numbers | 1 + Lang/R/M-bius-function | 1 + Lang/R/Parse-an-IP-Address | 1 + Lang/R/Rename-a-file | 1 + Lang/R/Repunit-primes | 1 + Lang/R/Retrieve-and-search-chat-history | 1 + Lang/R/Shoelace-formula-for-polygonal-area | 1 + Lang/R/Soloways-recurring-rainfall | 1 + ...racter-string-based-on-change-of-character | 1 + Lang/R/String-interpolation-included- | 1 + Lang/R/String-matching | 1 + Lang/R/Substring-Top-and-tail | 1 + Lang/R/The-Name-Game | 1 + Lang/R/Tonelli-Shanks-algorithm | 1 + Lang/R/Wieferich-primes | 1 + Lang/R/Write-entire-file | 1 + Lang/REBOL/00-LANG.txt | 4 +- Lang/REBOL/9-billion-names-of-God-the-integer | 1 + Lang/REBOL/Ackermann-function | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + ...oops-Increment-loop-index-within-loop-body | 1 + Lang/REBOL/Loops-With-multiple-ranges | 1 + Lang/REBOL/Loops-Wrong-ranges | 1 + Lang/REBOL/Object-serialization | 1 + Lang/REBOL/Polyspiral | 1 + Lang/REBOL/SHA-1 | 1 + Lang/REBOL/SHA-256 | 1 + Lang/REBOL/Semordnilap | 1 + Lang/RISC-V-Assembly/00-LANG.txt | 72 +++ Lang/RISC-V-Assembly/Address-of-a-variable | 1 + Lang/RISC-V-Assembly/Arithmetic-Integer | 1 + Lang/RISC-V-Assembly/Binary-digits | 1 + Lang/RISC-V-Assembly/Hello-world-Newbie | 1 + Lang/RISC-V-Assembly/Include-a-file | 1 + Lang/Raku/Play-recorded-sounds | 1 + Lang/Red/Address-of-a-variable | 1 + Lang/Red/Arithmetic-Integer | 1 + Lang/Red/Arithmetic-evaluation | 1 + Lang/Red/Calendar | 1 + Lang/Red/Calendar---for-REAL-programmers | 1 + Lang/Red/Currying | 1 + Lang/Red/Five-weekends | 1 + Lang/Red/Logical-operations | 1 + Lang/Red/Parsing-RPN-calculator-algorithm | 1 + Lang/Red/Parsing-RPN-to-infix-conversion | 1 + Lang/Red/Parsing-Shunting-yard-algorithm | 1 + Lang/Red/Towers-of-Hanoi | 1 + Lang/Refal/Tokenize-a-string | 1 + Lang/Rhombus/00-LANG.txt | 5 + Lang/Rhombus/00-META.yaml | 2 + Lang/Rhombus/99-bottles-of-beer | 1 + .../Arbitrary-precision-integers-included- | 1 + Lang/Rhombus/Caesar-cipher | 1 + Lang/Rhombus/Factorial | 1 + Lang/Rhombus/Fibonacci-sequence | 1 + Lang/Rhombus/FizzBuzz | 1 + Lang/Rhombus/Guess-the-number-With-feedback | 1 + Lang/Rhombus/Hello-world-Text | 1 + Lang/Rhombus/Inheritance-Single | 1 + Lang/Rhombus/Polymorphism | 1 + Lang/Rhombus/Rot-13 | 1 + Lang/Ring/Compare-a-list-of-strings | 1 + Lang/Ring/Wagstaff-primes | 1 + Lang/Run-BASIC/Josephus-problem | 1 + Lang/Rust/Break-OO-privacy | 1 + Lang/Rust/Camel-case-and-snake-case | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + Lang/Rust/Cyclops-numbers | 1 + Lang/Rust/Deconvolution-1D | 1 + Lang/Rust/Deconvolution-2D+ | 1 + Lang/Rust/Determine-if-two-triangles-overlap | 1 + Lang/Rust/Duffinian-numbers | 1 + Lang/Rust/Elliptic-curve-arithmetic | 1 + Lang/Rust/Faulhabers-triangle | 1 + Lang/Rust/Fractran | 1 + Lang/Rust/Humble-numbers | 1 + Lang/Rust/Knapsack-problem-Bounded | 1 + Lang/Rust/Mayan-calendar | 1 + Lang/Rust/Meissel-Mertens-constant | 1 + Lang/Rust/Modular-arithmetic | 1 + Lang/Rust/Multiple-regression | 1 + Lang/Rust/Ramanujan-primes-twins | 1 + Lang/Rust/Singleton | 1 + Lang/Rust/Sokoban | 1 + Lang/Rust/Substitution-cipher | 1 + Lang/Rust/Tree-datastructures | 1 + Lang/Rust/UPC | 1 + Lang/Rust/War-card-game | 1 + .../S-BASIC/Sorting-algorithms-Insertion-sort | 1 + Lang/SETL/Monte-Carlo-methods | 1 + Lang/SETL/Tokenize-a-string | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + Lang/Scala/Tonelli-Shanks-algorithm | 1 + Lang/Scala/UPC | 1 + Lang/Scheme/Own-digits-power-sum | 1 + Lang/Scheme/Pick-random-element | 1 + Lang/SequenceL/00-LANG.txt | 2 +- Lang/Swift/AVL-tree | 1 + Lang/Swift/Boyer-Moore-string-search | 1 + Lang/Swift/Chaocipher | 1 + ...ithmetic-G-matrix-ng-continued-fraction-n- | 1 + Lang/Swift/Floyd-Warshall-algorithm | 1 + Lang/Swift/K-d-tree | 1 + Lang/Swift/Parse-an-IP-Address | 1 + Lang/TAV/00-LANG.txt | 46 ++ Lang/TAV/00-META.yaml | 2 + Lang/TAV/A+B | 1 + Lang/TAV/Ackermann-function | 1 + Lang/TAV/Anagrams | 1 + Lang/TAV/Arithmetic-Integer | 1 + Lang/TAV/Array-concatenation | 1 + Lang/TAV/Array-length | 1 + Lang/TAV/Associative-array-Iteration | 1 + Lang/TAV/Averages-Root-mean-square | 1 + Lang/TAV/Character-codes | 1 + Lang/TAV/Command-line-arguments | 1 + Lang/TAV/Conditional-structures | 1 + Lang/TAV/Copy-a-string | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/TAV/Empty-string | 1 + Lang/TAV/Factorial | 1 + Lang/TAV/Fibonacci-sequence | 1 + Lang/TAV/Formatted-numeric-output | 1 + Lang/TAV/Greatest-element-of-a-list | 1 + Lang/TAV/Guess-the-number-With-feedback | 1 + Lang/TAV/HTTPS | 1 + Lang/TAV/Halt-and-catch-fire | 1 + Lang/TAV/Hello-world-Graphical | 1 + Lang/TAV/Hello-world-Text | 1 + Lang/TAV/Letter-frequency | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/TAV/Loops-Break | 1 + Lang/TAV/Loops-Do-while | 1 + Lang/TAV/Loops-Downward-for | 1 + Lang/TAV/Loops-For | 1 + Lang/TAV/Loops-Infinite | 1 + Lang/TAV/Loops-N-plus-one-half | 1 + Lang/TAV/Loops-While | 1 + Lang/TAV/Multiplication-tables | 1 + Lang/TAV/Ordered-words | 1 + Lang/TAV/Permutations | 1 + Lang/TAV/Real-constants-and-functions | 1 + Lang/TAV/Reverse-a-string | 1 + Lang/TAV/Semordnilap | 1 + Lang/TAV/Simple-windowed-application | 1 + Lang/TAV/Stack | 1 + Lang/TAV/String-length | 1 + Lang/TAV/Tic-tac-toe | 1 + Lang/TAV/Tokenize-a-string | 1 + Lang/TAV/Window-creation | 1 + Lang/TAV/Word-frequency | 1 + Lang/Tcl/M-bius-function | 1 + Lang/Ursalang/Loops-Break | 1 + Lang/Ursalang/Loops-While | 1 + Lang/V-(Vlang)/Compile-time-calculation | 1 + Lang/V-(Vlang)/Inheritance-Multiple | 1 + Lang/V-(Vlang)/Inheritance-Single | 1 + Lang/V-(Vlang)/Metaprogramming | 1 + Lang/Vyxal/00-LANG.txt | 3 + Lang/Vyxal/00-META.yaml | 2 + Lang/Vyxal/Factorial | 1 + Lang/Vyxal/FizzBuzz | 1 + Lang/XBasic/AKS-test-for-primes | 1 + Lang/XBasic/Josephus-problem | 1 + Lang/XPL0/AKS-test-for-primes | 1 + Lang/XPL0/Cistercian-numerals | 1 + Lang/YAMLScript/00-LANG.txt | 11 +- Lang/YAMLScript/Best-shuffle | 1 + Lang/YAMLScript/Conways-Game-of-Life | 1 + Lang/YAMLScript/Dragon-curve | 1 + Lang/YAMLScript/Even-or-odd | 1 + Lang/YAMLScript/Integer-comparison | 1 + Lang/YAMLScript/JortSort | 1 + Lang/YAMLScript/Knuth-shuffle | 1 + Lang/YAMLScript/Munching-squares | 1 + Lang/YAMLScript/Next-highest-int-from-digits | 1 + .../One-dimensional-cellular-automata | 1 + Lang/YAMLScript/Quickselect-algorithm | 1 + Lang/YAMLScript/Sparkline-in-unicode | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/YAMLScript/Undefined-values | 1 + Lang/YAMLScript/Van-der-Corput-sequence | 1 + Lang/YAMLScript/Xiaolin-Wus-line-algorithm | 1 + Lang/YAMLScript/Yellowstone-sequence | 1 + Lang/YAMLScript/Zig-zag-matrix | 1 + Lang/Zig/24-game-Solve | 1 + Lang/Zig/AVL-tree | 1 + Lang/Zig/Abelian-sandpile-model | 1 + Lang/Zig/Abelian-sandpile-model-Identity | 1 + Lang/Zig/Arrays | 1 + Lang/Zig/Associative-array-Creation | 1 + Lang/Zig/Associative-array-Iteration | 1 + Lang/Zig/Base64-decode-data | 1 + Lang/Zig/Bifid-cipher | 1 + Lang/Zig/Boolean-values | 1 + Lang/Zig/Boyer-Moore-string-search | 1 + Lang/Zig/Break-OO-privacy | 1 + Lang/Zig/Camel-case-and-snake-case | 1 + Lang/Zig/Cholesky-decomposition | 1 + Lang/Zig/Cumulative-standard-deviation | 1 + Lang/Zig/Cyclops-numbers | 1 + Lang/Zig/Deconvolution-1D | 1 + Lang/Zig/Determinant-and-permanent | 1 + Lang/Zig/Eertree | 1 + ...Elliptic-Curve-Digital-Signature-Algorithm | 1 + Lang/Zig/Elliptic-curve-arithmetic | 1 + Lang/Zig/Evolutionary-algorithm | 1 + Lang/Zig/Factors-of-an-integer | 1 + Lang/Zig/Farey-sequence | 1 + Lang/Zig/Gray-code | 1 + Lang/Zig/K-d-tree | 1 + Lang/Zig/Knapsack-problem-0-1 | 1 + Lang/Zig/Knights-tour | 1 + Lang/Zig/Loops-Nested | 1 + Lang/Zig/M-bius-function | 1 + Lang/Zig/Main-step-of-GOST-28147-89 | 1 + Lang/Zig/Modular-arithmetic | 1 + Lang/Zig/Modular-inverse | 1 + Lang/Zig/Parse-an-IP-Address | 1 + Lang/Zig/Permutations-by-swapping | 1 + Lang/Zig/Stern-Brocot-sequence | 1 + Lang/Zig/Sudoku | 1 + Lang/Zig/Tarjan | 1 + Lang/Zig/Tree-datastructures | 1 + Lang/Zig/Verhoeff-algorithm | 1 + Lang/Zig/Vigen-re-cipher-Cryptanalysis | 1 + Lang/Zig/Vogels-approximation-method | 1 + Lang/Zig/War-card-game | 1 + Task/100-doors/AWK/100-doors-1.awk | 17 - Task/100-doors/AWK/100-doors-2.awk | 14 - Task/100-doors/Adina/100-doors-1.adina | 16 + Task/100-doors/Adina/100-doors-2.adina | 17 + Task/100-doors/ArkScript/100-doors-1.ark | 21 + Task/100-doors/ArkScript/100-doors-2.ark | 4 + Task/100-doors/AutoLISP/100-doors.l | 18 + Task/100-doors/Component-Pascal/100-doors.pas | 26 - Task/100-doors/DuckDB/100-doors.duckdb | 19 + Task/100-doors/Haskell/100-doors-3.hs | 13 +- Task/100-doors/Haskell/100-doors-4.hs | 7 +- Task/100-doors/Haskell/100-doors-5.hs | 1 + Task/100-doors/Lua/100-doors.lua | 11 - Task/100-doors/PL-M/100-doors.plm | 55 -- Task/100-doors/REBOL/100-doors-2.rebol | 28 +- Task/100-doors/REBOL/100-doors-3.rebol | 6 + Task/100-prisoners/Prolog/100-prisoners.pro | 43 ++ .../PascalABC.NET/15-puzzle-solver.pas | 3 + Task/2048/EasyLang/2048.easy | 2 +- Task/24-game-Solve/Zig/24-game-solve.zig | 273 ++++++++++ Task/24-game/FutureBasic/24-game.basic | 2 +- Task/24-game/Rust/24-game.rs | 12 +- .../9-billion-names-of-god-the-integer.rebol | 101 ++++ .../ALGOL-68/99-bottles-of-beer.alg | 18 +- .../Aria/99-bottles-of-beer.aria | 48 ++ .../ArkScript/99-bottles-of-beer.ark | 24 + .../DuckDB/99-bottles-of-beer-1.duckdb | 13 + .../DuckDB/99-bottles-of-beer-2.duckdb | 21 + .../Pluto/99-bottles-of-beer.pluto | 12 + .../Rhombus/99-bottles-of-beer.rhombus | 13 + Task/A+B/Agena/a+b.agena | 12 +- Task/A+B/ArkScript/a+b.ark | 9 + Task/A+B/DuckDB/a+b-1.duckdb | 5 + Task/A+B/DuckDB/a+b-2.duckdb | 2 + Task/A+B/Koka/a+b.koka | 32 ++ Task/A+B/Pluto/a+b.pluto | 2 + Task/A+B/TAV/a+b.tav | 6 + Task/ABC-problem/DuckDB/abc-problem.duckdb | 45 ++ Task/ABC-problem/Pluto/abc-problem.pluto | 25 + .../ANSI-BASIC/aks-test-for-primes.basic | 79 +++ .../Agena/aks-test-for-primes.agena | 89 ++++ .../EasyLang/aks-test-for-primes.easy | 43 ++ .../FutureBasic/aks-test-for-primes.basic | 1 - .../Modula-2/aks-test-for-primes.mod2 | 119 +++++ .../PHP/aks-test-for-primes.php | 80 +++ .../Pluto/aks-test-for-primes.pluto | 90 ++++ .../PowerShell/aks-test-for-primes.psh | 84 ++++ .../REXX/aks-test-for-primes-2.rexx | 18 +- .../XBasic/aks-test-for-primes.basic | 84 ++++ .../XPL0/aks-test-for-primes.xpl0 | 105 ++++ .../ascii-art-diagram-converter.math | 86 ++++ Task/AVL-tree/Dart/avl-tree.dart | 221 ++++++++ Task/AVL-tree/Swift/avl-tree.swift | 243 +++++++++ Task/AVL-tree/Zig/avl-tree.zig | 268 ++++++++++ .../ArkScript/abbreviations-easy.ark | 54 ++ .../PascalABC.NET/abbreviations-easy.pas | 26 + .../PascalABC.NET/abbreviations-simple.pas | 51 ++ .../abelian-sandpile-model-identity.pluto | 79 +++ .../Zig/abelian-sandpile-model-identity.zig | 126 +++++ .../Julia/abelian-sandpile-model.jl | 214 ++++---- .../Pluto/abelian-sandpile-model.pluto | 80 +++ .../Zig/abelian-sandpile-model.zig | 136 +++++ .../Free-Pascal-Lazarus/abstract-type-1.pas | 60 +++ .../Free-Pascal-Lazarus/abstract-type-2.pas | 32 ++ Task/Abstract-type/Haxe/abstract-type-1.haxe | 44 ++ .../abstract-type-2.haxe} | 0 Task/Abstract-type/Pluto/abstract-type.pluto | 34 ++ Task/Abstract-type/REBOL/abstract-type.rebol | 2 +- ...t-and-perfect-number-classifications.agena | 21 + ...-and-perfect-number-classifications.fennel | 21 + ...t-and-perfect-number-classifications.pluto | 26 + ...ent-and-perfect-number-classifications.pro | 25 +- .../ALGOL-68/abundant-odd-numbers.alg | 30 +- .../Agena/abundant-odd-numbers.agena | 52 ++ .../Pluto/abundant-odd-numbers.pluto | 35 ++ ...tory.rebol => accumulator-factory-1.rebol} | 3 + .../REBOL/accumulator-factory-2.rebol | 25 + .../Pluto/achilles-numbers.pluto | 63 +++ .../ArkScript/ackermann-function.ark | 8 + .../Pluto/ackermann-function.pluto | 13 + .../REBOL/ackermann-function-1.rebol | 7 + .../REBOL/ackermann-function-2.rebol | 16 + .../TAV/ackermann-function.tav | 11 + .../Pluto/address-of-a-variable.pluto | 6 + .../REXX/address-of-a-variable.rexx | 19 +- .../RISC-V-Assembly/address-of-a-variable.asm | 128 +++++ .../Red/address-of-a-variable.red | 17 + Task/Align-columns/ALGOL-68/align-columns.alg | 33 +- .../aliquot-sequence-classifications.js | 81 +++ .../Ada/almkvist-giullera-formula-for-pi.ada | 94 ++++ Task/Almost-prime/Icon/almost-prime-1.icon | 2 +- Task/Almost-prime/Pluto/almost-prime.pluto | 26 + Task/Amb/Ada/{amb.ada => amb-1.ada} | 0 Task/Amb/Ada/amb-2.ada | 78 +++ .../PL-I-80/amicable-pairs-1.pli | 47 -- ...micable-pairs-2.pli => amicable-pairs.pli} | 4 +- Task/Anagrams/DuckDB/anagrams.duckdb | 20 + Task/Anagrams/TAV/anagrams.tav | 38 ++ ...s-geometric-normalization-and-conversion.r | 23 + .../DuckDB/anonymous-recursion.duckdb | 11 + Task/Anti-primes/Bc/anti-primes.bc | 18 + Task/Anti-primes/Draco/anti-primes.draco | 29 ++ Task/Anti-primes/Lua/anti-primes-2.lua | 2 +- Task/Anti-primes/Pluto/anti-primes.pluto | 32 ++ .../apply-a-callback-to-an-array.ark | 8 + .../Haxe/apply-a-callback-to-an-array.haxe | 10 + .../Pluto/approximate-equality.pluto | 16 + ...bitrary-precision-integers-included-.agena | 25 + ...bitrary-precision-integers-included-.basic | 11 + ...trary-precision-integers-included-.bracmat | 2 +- ...arbitrary-precision-integers-included-.nim | 4 +- ...bitrary-precision-integers-included-.pluto | 10 + ...trary-precision-integers-included-.rhombus | 5 + .../EasyLang/archimedean-spiral.easy | 4 +- .../ArkScript/arithmetic-complex.ark | 30 ++ .../DuckDB/arithmetic-complex.duckdb | 86 ++++ .../FutureBasic/arithmetic-complex.basic | 71 +++ .../Pluto/arithmetic-complex.pluto | 15 + .../REXX/arithmetic-complex.rexx | 67 ++- .../ArkScript/arithmetic-integer.ark | 10 + .../DuckDB/arithmetic-integer.duckdb | 3 + .../Elena/arithmetic-integer.elena | 16 +- .../Haxe/arithmetic-integer.haxe | 25 +- .../Pascal/arithmetic-integer.pas | 4 +- .../Pluto/arithmetic-integer.pluto | 13 + .../RISC-V-Assembly/arithmetic-integer.asm | 146 ++++++ .../Red/arithmetic-integer.red | 42 ++ .../TAV/arithmetic-integer.tav | 11 + .../Zig/arithmetic-integer.zig | 33 +- .../Pluto/arithmetic-rational.pluto | 12 + .../REXX/arithmetic-rational.rexx | 71 ++- .../Bc/arithmetic-derivative.bc | 25 + .../Pluto/arithmetic-derivative.pluto | 20 + .../ALGOL-68/arithmetic-evaluation.alg | 41 +- .../Elena/arithmetic-evaluation.elena | 38 +- .../PascalABC.NET/arithmetic-evaluation.pas | 127 +++++ ...aluation.pl => arithmetic-evaluation-1.pl} | 0 .../Perl/arithmetic-evaluation-2.pl | 49 ++ .../Red/arithmetic-evaluation.red | 113 +++++ .../ALGOL-68/arithmetic-geometric-mean.alg | 2 +- .../DuckDB/arithmetic-geometric-mean-1.duckdb | 12 + .../DuckDB/arithmetic-geometric-mean-2.duckdb | 14 + .../Pluto/arithmetic-geometric-mean.pluto | 10 + .../DuckDB/arithmetic-numbers.duckdb | 70 +++ .../ArkScript/array-concatenation.ark | 4 + .../DuckDB/array-concatenation.duckdb | 4 + .../Elena/array-concatenation.elena | 2 +- .../Pluto/array-concatenation.pluto | 12 + .../TAV/array-concatenation.tav | 3 + Task/Array-length/ArkScript/array-length.ark | 2 + Task/Array-length/DuckDB/array-length.duckdb | 1 + .../M2000-Interpreter/array-length.m2000 | 35 -- Task/Array-length/Maxima/array-length.maxima | 4 + Task/Array-length/TAV/array-length.tav | 1 + Task/Array-length/Tcl/array-length-1.tcl | 1 + Task/Array-length/Tcl/array-length-2.tcl | 1 + Task/Array-length/Tcl/array-length-3.tcl | 5 + Task/Array-length/Tcl/array-length-4.tcl | 2 + Task/Array-length/Tcl/array-length-5.tcl | 1 + Task/Array-length/Tcl/array-length-6.tcl | 5 + Task/Array-length/Tcl/array-length-7.tcl | 10 + Task/Array-length/Tcl/array-length.tcl | 13 - Task/Arrays/BBC-BASIC/arrays.basic | 5 + Task/Arrays/DuckDB/arrays.duckdb | 9 + Task/Arrays/Elena/arrays-5.elena | 6 +- Task/Arrays/Extended-Color-BASIC/arrays.basic | 4 + Task/Arrays/Haxe/arrays.haxe | 22 + Task/Arrays/Pluto/arrays.pluto | 8 + Task/Arrays/REXX/arrays.rexx | 74 +-- Task/Arrays/Unicon/arrays-1.unicon | 1 + Task/Arrays/Unicon/arrays-2.unicon | 6 + Task/Arrays/Unicon/arrays-3.unicon | 3 + Task/Arrays/Zig/arrays-1.zig | 32 ++ Task/Arrays/Zig/arrays-2.zig | 21 + .../ArkScript/ascending-primes.ark | 24 + .../Pluto/ascending-primes.pluto | 24 + .../ArkScript/associative-array-creation.ark | 6 + .../associative-array-creation-1.duckdb | 6 + .../associative-array-creation-2.duckdb | 5 + .../associative-array-creation-3.duckdb | 1 + .../associative-array-creation-4.duckdb | 3 + .../associative-array-creation-5.duckdb | 1 + .../associative-array-creation-6.duckdb | 1 + .../associative-array-creation-7.duckdb | 1 + .../associative-array-creation-8.duckdb | 1 + .../Haxe/associative-array-creation.haxe | 7 + .../Pluto/associative-array-creation.pluto | 25 + .../REXX/associative-array-creation-1.rexx | 10 - .../REXX/associative-array-creation-2.rexx | 27 - .../REXX/associative-array-creation.rexx | 54 ++ .../associative-array-creation-2.sh | 1 - ...ion-1.sh => associative-array-creation.sh} | 0 .../Zig/associative-array-creation-1.zig | 18 + .../Zig/associative-array-creation-2.zig | 23 + .../ArkScript/associative-array-iteration.ark | 9 + .../DuckDB/associative-array-iteration.duckdb | 108 ++++ .../Elena/associative-array-iteration-1.elena | 18 - ...lena => associative-array-iteration.elena} | 0 .../Haxe/associative-array-iteration.haxe | 18 + .../Pluto/associative-array-iteration.pluto | 19 + .../REXX/associative-array-iteration.rexx | 128 ++--- .../TAV/associative-array-iteration.tav | 24 + .../Tcl/associative-array-iteration-1.tcl | 21 +- .../Tcl/associative-array-iteration-2.tcl | 19 +- .../Tcl/associative-array-iteration-3.tcl | 2 + .../Tcl/associative-array-iteration-4.tcl | 16 + .../Tcl/associative-array-iteration-5.tcl | 16 + .../Zig/associative-array-iteration-1.zig | 30 ++ .../Zig/associative-array-iteration-2.zig | 30 ++ .../DuckDB/associative-array-merging-1.duckdb | 4 + .../DuckDB/associative-array-merging-2.duckdb | 11 + .../DuckDB/associative-array-merging-3.duckdb | 11 + .../Fortran/associative-array-merging.f | 94 ++++ .../Pluto/associative-array-merging.pluto | 11 + .../REXX/associative-array-merging.rexx | 111 ++-- .../Agena/attractive-numbers.agena | 28 ++ .../Lua/attractive-numbers.lua | 9 +- .../Pluto/attractive-numbers.pluto | 40 ++ .../Apple/averages-arithmetic-mean.apple | 2 + .../DuckDB/averages-arithmetic-mean.duckdb | 3 + .../Elena/averages-arithmetic-mean.elena | 8 +- .../Pluto/averages-arithmetic-mean.pluto | 4 + .../DuckDB/averages-mean-angle.duckdb | 13 + .../DuckDB/averages-mean-time-of-day.duckdb | 17 + .../averages-mean-time-of-day.basic | 70 +++ .../Elena/averages-median.elena | 6 +- .../Pluto/averages-median.pluto | 17 + .../DuckDB/averages-mode-1.duckdb | 10 + .../DuckDB/averages-mode-2.duckdb | 1 + .../DuckDB/averages-mode-3.duckdb | 10 + .../DuckDB/averages-mode-4.duckdb | 1 + .../DuckDB/averages-mode-5.duckdb | 15 + .../DuckDB/averages-mode-6.duckdb | 2 + Task/Averages-Mode/Elena/averages-mode.elena | 2 +- .../Apple/averages-pythagorean-means.apple | 12 + .../DuckDB/averages-pythagorean-means.duckdb | 11 + .../Pluto/averages-pythagorean-means.pluto | 11 + .../EasyLang/averages-root-mean-square.easy | 7 +- .../Elena/averages-root-mean-square.elena | 2 +- .../Pluto/averages-root-mean-square.pluto | 7 + .../TAV/averages-root-mean-square.tav | 10 + .../averages-simple-moving-average.elena | 16 +- .../JavaScript/b-zier-curves-intersections.js | 162 ++++++ .../AutoLISP/babbage-problem.l | 54 ++ .../DuckDB/babbage-problem-1.duckdb | 3 + .../DuckDB/babbage-problem-2.duckdb | 9 + .../Elena/babbage-problem.elena | 2 +- .../EasyLang/babylonian-spiral.easy | 43 +- .../FreeBASIC/babylonian-spiral.basic | 92 ++++ .../ArkScript/balanced-brackets.ark | 24 + .../AutoLISP/balanced-brackets.l | 12 + .../Elena/balanced-brackets.elena | 10 +- .../Nom/balanced-brackets.num | 19 + .../Pluto/balanced-brackets.pluto | 36 ++ .../JavaScript/balanced-ternary.js | 203 ++++++++ .../Pluto/base64-decode-data.pluto | 4 + .../Zig/base64-decode-data.zig | 86 ++++ Task/Bell-numbers/Pluto/bell-numbers.pluto | 32 ++ Task/Benfords-law/DuckDB/benfords-law.duckdb | 22 + Task/Bernoulli-numbers/R/bernoulli-numbers.r | 12 +- .../REXX/bernoulli-numbers.rexx | 184 +++++-- Task/Best-shuffle/Elena/best-shuffle.elena | 4 +- Task/Best-shuffle/Factor/best-shuffle.factor | 26 + Task/Best-shuffle/YAMLScript/best-shuffle.ys | 44 ++ Task/Bifid-cipher/Zig/bifid-cipher.zig | 164 ++++++ .../DuckDB/bin-given-limits-1.duckdb | 24 + .../DuckDB/bin-given-limits-2.duckdb | 14 + .../DuckDB/binary-digits-1.duckdb | 2 + .../DuckDB/binary-digits-2.duckdb | 22 + Task/Binary-digits/Elena/binary-digits.elena | 2 +- Task/Binary-digits/Haxe/binary-digits.haxe | 15 + ...inary-digits.icon => binary-digits-1.icon} | 0 Task/Binary-digits/Icon/binary-digits-2.icon | 12 + .../RISC-V-Assembly/binary-digits.asm | 185 +++++++ .../DuckDB/bioinformatics-base-count.duckdb | 18 + .../bioinformatics-base-count.pas | 14 + Task/Biorhythms/Ada/biorhythms.ada | 65 +++ Task/Biorhythms/EasyLang/biorhythms.easy | 4 +- .../bitcoin-public-point-to-address.basic | 142 ++++++ .../bitcoin-public-point-to-address.js | 52 ++ .../bitmap-b-zier-curves-quadratic.easy | 6 +- .../bitmap-bresenhams-line-algorithm.pluto | 27 + .../bitmap-midpoint-circle-algorithm.easy | 27 + .../Julia/bitmap-midpoint-circle-algorithm.jl | 6 +- .../bitmap-midpoint-circle-algorithm.pluto | 33 ++ Task/Bitmap/Pluto/bitmap.pluto | 23 + Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb | 8 + Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb | 13 + .../ALGOL-68/bitwise-operations-1.alg | 16 +- .../DuckDB/bitwise-operations-1.duckdb | 5 + .../DuckDB/bitwise-operations-2.duckdb | 5 + .../Elena/bitwise-operations.elena | 20 +- .../Icon/bitwise-operations.icon | 2 + .../Pluto/bitwise-operations.pluto | 20 + .../ArkScript/boolean-values.ark | 14 + Task/Boolean-values/Haxe/boolean-values.haxe | 8 + Task/Boolean-values/Prolog/boolean-values.pro | 2 + Task/Boolean-values/Zig/boolean-values.zig | 15 + .../Ada/boyer-moore-string-search.ada | 63 +++ .../Dart/boyer-moore-string-search.dart | 80 +++ .../boyer-moore-string-search.basic | 55 ++ .../Kotlin/boyer-moore-string-search.kts | 50 ++ .../Swift/boyer-moore-string-search.swift | 59 +++ .../Zig/boyer-moore-string-search.zig | 71 +++ .../Dart/break-oo-privacy.dart | 38 ++ .../JavaScript/break-oo-privacy.js | 54 ++ .../Break-OO-privacy/Rust/break-oo-privacy.rs | 62 +++ .../Break-OO-privacy/Zig/break-oo-privacy.zig | 88 ++++ .../Brownian-tree/EasyLang/brownian-tree.easy | 30 +- .../Bulls-and-cows/Elena/bulls-and-cows.elena | 14 +- Task/Bulls-and-cows/J/bulls-and-cows-1.j | 2 +- Task/CRC-32/FutureBasic/crc-32.basic | 46 ++ Task/CRC-32/Pluto/crc-32.pluto | 5 + Task/CRC-32/R/crc-32.r | 1 + .../DuckDB/csv-data-manipulation-1.duckdb | 5 + .../DuckDB/csv-data-manipulation-2.duckdb | 4 + .../DuckDB/csv-data-manipulation-3.duckdb | 6 + .../Nom/csv-to-html-translation-1.num | 85 ++++ .../Nom/csv-to-html-translation-2.num | 14 + Task/CUSIP/R/cusip.r | 25 + Task/Caesar-cipher/Elena/caesar-cipher.elena | 8 +- Task/Caesar-cipher/Pluto/caesar-cipher.pluto | 20 + .../Rhombus/caesar-cipher.rhombus | 25 + .../ArkScript/calculating-the-value-of-e.ark | 22 + .../calendar---for-real-programmers-1.elena | 57 +++ .../calendar---for-real-programmers-2.elena | 146 ++++++ .../calendar---for-real-programmers.elena | 161 ------ .../Red/calendar---for-real-programmers.red | 52 ++ Task/Calendar/Red/calendar.red | 52 ++ .../Ada/calkin-wilf-sequence.ada | 110 ++++ .../Pluto/calkin-wilf-sequence.pluto | 47 ++ .../call-a-foreign-language-function-1.pluto | 18 + .../call-a-foreign-language-function-2.pluto | 10 + .../call-a-function-in-a-shared-library.pluto | 19 + .../ArkScript/call-a-function-1.ark | 4 + .../ArkScript/call-a-function-2.ark | 3 + .../ArkScript/call-a-function-3.ark | 6 + .../ArkScript/call-a-function-4.ark | 6 + .../ArkScript/call-a-function-5.ark | 3 + .../ArkScript/call-a-function-6.ark | 4 + .../ArkScript/call-a-function-7.ark | 8 + .../DuckDB/call-a-function-1.duckdb | 5 + .../DuckDB/call-a-function-2.duckdb | 1 + .../Elena/call-a-function-1.elena | 4 +- .../ArkScript/call-an-object-method.ark | 17 + .../Elena/call-an-object-method.elena | 2 +- .../Haxe/call-an-object-method.haxe | 13 + .../Ada/camel-case-and-snake-case.ada | 114 +++++ .../C-sharp/camel-case-and-snake-case.cs | 87 ++++ .../camel-case-and-snake-case.math | 85 ++++ .../Rust/camel-case-and-snake-case.rs | 93 ++++ .../Zig/camel-case-and-snake-case.zig | 134 +++++ .../Ada/canonicalize-cidr.ada | 105 ++++ .../carmichael-3-strong-pseudoprimes.basic | 41 ++ ...sian-product-of-two-or-more-lists-1.duckdb | 2 + ...sian-product-of-two-or-more-lists-2.duckdb | 8 + .../case-sensitivity-of-identifiers-1.duckdb | 3 + .../case-sensitivity-of-identifiers-2.duckdb | 2 + .../case-sensitivity-of-identifiers.elena | 2 +- .../case-sensitivity-of-identifiers.pas | 8 + .../case-sensitivity-of-identifiers.pluto | 13 + .../Pluto/casting-out-nines.pluto | 30 ++ .../catalan-numbers-pascals-triangle-1.duckdb | 20 + .../catalan-numbers-pascals-triangle-2.duckdb | 8 + .../catalan-numbers-pascals-triangle.f | 64 +++ .../catalan-numbers-pascals-triangle.objeck | 23 + Task/Catalan-numbers/00-META.yaml | 2 +- .../DuckDB/catalan-numbers.duckdb | 30 ++ Task/Catamorphism/Apple/catamorphism-1.apple | 2 + Task/Catamorphism/Apple/catamorphism-2.apple | 2 + Task/Catamorphism/Apple/catamorphism-3.apple | 2 + Task/Catamorphism/ArkScript/catamorphism.ark | 7 + Task/Catamorphism/Elena/catamorphism.elena | 2 +- .../catmull-clark-subdivision-surface.basic | 250 +++++++++ .../catmull-clark-subdivision-surface.js | 255 ++++++++++ Task/Chaocipher/Swift/chaocipher.swift | 84 ++++ .../Elena/character-codes.elena | 4 +- .../Character-codes/Haxe/character-codes.haxe | 7 + Task/Character-codes/TAV/character-codes.tav | 2 + .../ArkScript/check-that-file-exists.ark | 4 + .../DuckDB/check-that-file-exists.duckdb | 2 + .../Elena/check-that-file-exists.elena | 8 +- .../JavaScript/checkpoint-synchronization.js | 47 ++ Task/Chinese-zodiac/Fortran/chinese-zodiac.f | 62 +++ .../EasyLang/cholesky-decomposition.easy | 19 + .../Zig/cholesky-decomposition.zig | 64 +++ Task/Chowla-numbers/REXX/chowla-numbers.rexx | 13 +- .../Circular-primes/REXX/circular-primes.rexx | 14 +- .../C-sharp/cistercian-numerals.cs | 141 ++++++ .../cistercian-numerals.pas | 151 ++++++ .../Modula-2/cistercian-numerals.mod2 | 132 +++++ .../Pascal-P/cistercian-numerals.pas | 131 +++++ .../XPL0/cistercian-numerals.xpl0 | 104 ++++ Task/Classes/Elena/classes.elena | 2 +- Task/Classes/Haxe/classes-1.haxe | 14 + .../classes-3.hs => Haxe/classes-2.haxe} | 0 .../ArkScript/closures-value-capture.ark | 13 + .../Elena/closures-value-capture.elena | 2 +- Task/Collections/DuckDB/collections.duckdb | 11 + Task/Collections/Phix/collections-1.phix | 3 +- Task/Collections/Phix/collections-2.phix | 3 +- Task/Collections/Pluto/collections.pluto | 13 + .../FreeBASIC/color-quantization.basic | 194 +++++++ Task/Color-wheel/EasyLang/color-wheel.easy | 37 +- .../combinations-with-repetitions.duckdb | 49 ++ .../combinations-with-repetitions.pas | 8 + .../Pluto/combinations-with-repetitions.pluto | 15 + Task/Combinations/DuckDB/combinations.duckdb | 22 + Task/Combinations/Elena/combinations.elena | 4 +- Task/Combinations/Pluto/combinations.pluto | 10 + .../Elena/comma-quibbling-1.elena | 2 +- .../Pluto/command-line-arguments.pluto | 1 + .../TAV/command-line-arguments.tav | 3 + Task/Comments/ArkScript/comments.ark | 4 + Task/Comments/Ballerina/comments.ballerina | 10 + Task/Comments/Idris/comments.idris | 9 + Task/Comments/Janet/comments.janet | 7 + Task/Comments/Odin/comments.odin | 17 + Task/Comments/Pluto/comments.pluto | 9 + .../DuckDB/compare-a-list-of-strings-1.duckdb | 2 + .../DuckDB/compare-a-list-of-strings-2.duckdb | 2 + .../DuckDB/compare-a-list-of-strings-3.duckdb | 16 + .../Elena/compare-a-list-of-strings.elena | 6 +- .../Ring/compare-a-list-of-strings.ring | 57 +++ ...gs.tcl => compare-a-list-of-strings-1.tcl} | 0 .../Tcl/compare-a-list-of-strings-2.tcl | 23 + .../compare-length-of-two-strings-1.duckdb | 8 + .../compare-length-of-two-strings-2.duckdb | 2 + .../compare-length-of-two-strings-3.duckdb | 6 + .../Pluto/compare-length-of-two-strings.pluto | 43 ++ Task/Compile-time-calculation/00-TASK.txt | 2 +- .../V-(Vlang)/compile-time-calculation.v | 15 + .../Pluto/compiler-lexical-analyzer.pluto | 258 ++++++++++ ...hose-factors-are-all-substrings-of-k.basic | 23 +- .../ArkScript/compound-data-type.ark | 14 + .../DuckDB/compound-data-type.duckdb | 1 + .../ArkScript/concurrent-computing.ark | 9 + ...computing.rs => concurrent-computing-1.rs} | 0 .../Rust/concurrent-computing-2.rs | 15 + .../Rust/concurrent-computing-3.rs | 26 + .../ArkScript/conditional-structures.ark | 20 + .../DuckDB/conditional-structures-1.duckdb | 1 + .../DuckDB/conditional-structures-2.duckdb | 1 + .../DuckDB/conditional-structures-3.duckdb | 1 + .../Pluto/conditional-structures.pluto | 29 ++ .../TAV/conditional-structures-1.tav | 4 + .../TAV/conditional-structures-2.tav | 5 + .../TAV/conditional-structures-3.tav | 1 + ...-ascending-or-descending-differences.basic | 3 +- .../C++/constrained-genericity-1.cpp | 13 + ...icity.cpp => constrained-genericity-2.cpp} | 4 +- ...metic-construct-from-rational-number-1.jl} | 0 ...hmetic-construct-from-rational-number-2.jl | 21 + ...metic-construct-from-rational-number.pluto | 39 ++ ...tic-g-matrix-ng-continued-fraction-n-.dart | 157 ++++++ ...metic-g-matrix-ng-continued-fraction-n-.js | 150 ++++++ ...metic-g-matrix-ng-continued-fraction-n-.pl | 194 +++++++ ...metic-g-matrix-ng-continued-fraction-n-.rs | 201 ++++++++ ...ic-g-matrix-ng-continued-fraction-n-.scala | 123 +++++ ...ic-g-matrix-ng-continued-fraction-n-.swift | 155 ++++++ .../Dart/continued-fraction.dart | 20 + .../JavaScript/continued-fraction.js | 35 ++ .../Continued-fraction/R/continued-fraction.r | 24 + .../REXX/continued-fraction-3.rexx | 26 +- .../convert-decimal-number-to-rational.pluto | 8 + ...onvert-seconds-to-compound-duration.duckdb | 18 + .../ArkScript/conways-game-of-life.ark | 68 +++ .../Elena/conways-game-of-life.elena | 10 +- .../YAMLScript/conways-game-of-life.ys | 42 ++ .../Copy-a-string/ArkScript/copy-a-string.ark | 7 + .../Copy-a-string/DuckDB/copy-a-string.duckdb | 40 ++ .../Extended-Color-BASIC/copy-a-string.basic | 7 + Task/Copy-a-string/TAV/copy-a-string.tav | 6 + .../Count-in-octal/Pluto/count-in-octal.pluto | 5 + .../count-occurrences-of-a-substring.duckdb | 6 + .../ALGOL-68/count-the-coins-1.alg | 3 +- .../Pluto/count-the-coins.pluto | 28 ++ Task/Cramers-rule/R/cramers-rule.r | 12 + .../Create-a-file/Pluto/create-a-file-1.pluto | 2 + .../Create-a-file/Pluto/create-a-file-2.pluto | 4 + ...-a-two-dimensional-array-at-runtime.duckdb | 38 ++ ...a-two-dimensional-array-at-runtime-1.elena | 6 +- ...a-two-dimensional-array-at-runtime-2.elena | 8 +- ...te-a-two-dimensional-array-at-runtime.rexx | 143 ++++-- ...ate-a-two-dimensional-array-at-runtime.tav | 3 + Task/Cuban-primes/REXX/cuban-primes.rexx | 12 +- .../cumulative-standard-deviation.duckdb | 7 + .../Zig/cumulative-standard-deviation.zig | 21 + Task/Currency/DuckDB/currency.duckdb | 17 + Task/Currency/EasyLang/currency.easy | 81 +++ Task/Currying/ArkScript/currying.ark | 7 + Task/Currying/Pluto/currying.pluto | 4 + Task/Currying/Red/currying.red | 36 ++ Task/Curzon-numbers/R/curzon-numbers.r | 18 + .../Curzon-numbers/V-(Vlang)/curzon-numbers.v | 10 +- Task/Cyclops-numbers/Rust/cyclops-numbers.rs | 171 +++++++ Task/Cyclops-numbers/Zig/cyclops-numbers.zig | 185 +++++++ .../Fortran/cyclotomic-polynomial.f | 213 ++++++++ Task/Damm-algorithm/Prolog/damm-algorithm.pro | 27 + ...{date-format.rebol => date-format-1.rebol} | 0 Task/Date-format/REBOL/date-format-2.rebol | 1 + .../ALGOL-68/date-manipulation.alg | 237 +++++++++ .../DuckDB/day-of-the-week-1.duckdb | 8 + .../DuckDB/day-of-the-week-2.duckdb | 11 + .../DuckDB/day-of-the-week-3.duckdb | 10 + .../FutureBasic/deal-cards-for-freecell.basic | 143 ++++++ Task/Death-Star/EasyLang/death-star.easy | 62 +++ .../JavaScript/deconvolution-1d.js | 27 + .../Deconvolution-1D/Rust/deconvolution-1d.rs | 39 ++ .../Deconvolution-1D/Zig/deconvolution-1d.zig | 54 ++ .../JavaScript/deconvolution-2d+.js | 329 ++++++++++++ .../Rust/deconvolution-2d+.rs | 359 +++++++++++++ Task/Deepcopy/Ada/deepcopy.ada | 16 + .../define-a-primitive-data-type.duckdb | 1 + .../Elena/define-a-primitive-data-type.elena | 8 +- Task/Delegates/Elena/delegates-1.elena | 2 +- Task/Delegates/Elena/delegates-2.elena | 6 +- .../Delete-a-file/ArkScript/delete-a-file.ark | 8 + .../Delete-a-file/Maxima/delete-a-file.maxima | 5 + Task/Delete-a-file/Pluto/delete-a-file.pluto | 5 + .../FutureBasic/demings-funnel.basic | 88 ++++ .../Bc/department-numbers.bc | 7 + .../Crystal/department-numbers.cr | 1 + .../Pluto/descending-primes.pluto | 11 + .../DuckDB/detect-division-by-zero.duckdb | 8 + Task/Determinant-and-permanent/00-TASK.txt | 3 +- .../C++/determinant-and-permanent.cpp | 180 ++++--- .../DuckDB/determinant-and-permanent.duckdb | 63 +++ .../Elixir/determinant-and-permanent.ex | 52 ++ .../Erlang/determinant-and-permanent.erl | 52 ++ .../Zig/determinant-and-permanent.zig | 86 ++++ ...-string-has-all-the-same-characters.duckdb | 38 ++ ...-a-string-has-all-unique-characters.duckdb | 38 ++ ...etermine-if-a-string-is-collapsible.duckdb | 16 + .../determine-if-a-string-is-numeric.duckdb | 22 + .../Nom/determine-if-a-string-is-numeric.num | 67 +++ .../determine-if-a-string-is-numeric.pluto | 9 + .../determine-if-a-string-is-numeric-1.tcl | 3 + .../determine-if-a-string-is-numeric-2.tcl | 17 + .../Tcl/determine-if-a-string-is-numeric.tcl | 1 - ...determine-if-a-string-is-squeezable.duckdb | 18 + .../determine-if-two-triangles-overlap.rs | 159 ++++++ .../DuckDB/determine-sentence-type.duckdb | 22 + Task/Digital-root/DuckDB/digital-root.duckdb | 26 + Task/Digital-root/Elena/digital-root.elena | 2 +- .../Dart/dijkstras-algorithm.dart | 179 +++++++ .../R/dijkstras-algorithm.r | 165 ++++++ .../Agena/disarium-numbers.agena | 34 ++ .../Fortran/disarium-numbers.f | 112 +++++ .../Frink/disarium-numbers.frink | 12 + .../Objeck/disarium-numbers.objeck | 29 ++ .../Pluto/disarium-numbers.pluto | 29 ++ Task/Disarium-numbers/R/disarium-numbers.r | 12 +- .../Fortran/display-a-linear-combination.f | 94 ++++ .../Pluto/display-a-linear-combination.pluto | 32 ++ .../Go/distance-and-bearing.go | 131 +++++ ...bution-of-0-digits-in-factorial-series.alg | 72 +++ ...ution-of-0-digits-in-factorial-series.easy | 33 ++ ...tion-of-0-digits-in-factorial-series.pluto | 70 +++ .../diversity-prediction-theorem.duckdb | 31 ++ .../DuckDB/documentation-1.duckdb | 4 + .../DuckDB/documentation-2.duckdb | 1 + .../DuckDB/documentation-3.duckdb | 3 + .../Unicon/documentation-1.unicon | 26 + .../Unicon/documentation-2.unicon | 6 + .../Unicon/documentation-3.unicon | 7 + .../Documentation/Unicon/documentation.unicon | 1 - Task/Dominoes/FreeBASIC/dominoes-1.basic | 202 ++++++++ Task/Dominoes/FreeBASIC/dominoes-2.basic | 44 ++ Task/Dot-product/Apple/dot-product.apple | 1 + Task/Dot-product/DuckDB/dot-product-1.duckdb | 1 + Task/Dot-product/DuckDB/dot-product-2.duckdb | 3 + Task/Dot-product/DuckDB/dot-product-3.duckdb | 7 + Task/Dot-product/DuckDB/dot-product-4.duckdb | 13 + Task/Dot-product/Elena/dot-product.elena | 2 +- .../Pluto/doubly-linked-list-definition.pluto | 18 + ...oubly-linked-list-element-definition.pluto | 9 + .../Pluto/doubly-linked-list-traversal.pluto | 24 + Task/Dragon-curve/EasyLang/dragon-curve.easy | 4 +- Task/Dragon-curve/YAMLScript/dragon-curve.ys | 29 ++ Task/Draw-a-pixel/GML/draw-a-pixel.gml | 3 +- .../Draw-a-sphere/EasyLang/draw-a-sphere.easy | 25 + .../Rust/duffinian-numbers.rs | 97 ++++ .../Pluto/dutch-national-flag-problem.pluto | 24 + .../DuckDB/dynamic-variable-names.duckdb | 1 + .../Elena/dynamic-variable-names.elena | 2 +- .../EasyLang/ekg-sequence-convergence.easy | 22 + .../Fortran/ekg-sequence-convergence.f | 168 +++++++ ...arliest-difference-between-prime-gaps.easy | 41 ++ ...rliest-difference-between-prime-gaps.basic | 2 +- Task/Eertree/Zig/eertree.zig | 181 +++++++ .../Fortran/egyptian-division.f | 69 +++ .../DuckDB/element-wise-operations-1.duckdb | 7 + .../DuckDB/element-wise-operations-2.duckdb | 58 +++ ...ry-cellular-automaton-infinite-length.easy | 34 ++ ...ptic-curve-digital-signature-algorithm.zig | 475 ++++++++++++++++++ .../Rust/elliptic-curve-arithmetic.rs | 211 ++++++++ .../Zig/elliptic-curve-arithmetic.zig | 187 +++++++ .../ArkScript/empty-directory.ark | 3 + .../ArkScript/empty-program-1.ark | 1 + .../ArkScript/empty-program-2.ark | 1 + Task/Empty-string/ArkScript/empty-string.ark | 5 + Task/Empty-string/DuckDB/empty-string.duckdb | 1 + Task/Empty-string/Elena/empty-string.elena | 4 +- Task/Empty-string/Nom/empty-string.num | 6 + Task/Empty-string/TAV/empty-string.tav | 5 + .../ArkScript/enforced-immutability.ark | 2 + .../AutoLISP/entropy-narcissist.l | 46 ++ Task/Entropy/AutoLISP/entropy.l | 40 ++ Task/Entropy/DuckDB/entropy.duckdb | 16 + Task/Entropy/Elena/entropy.elena | 2 +- Task/Enumerations/DuckDB/enumerations.duckdb | 1 + .../DuckDB/equilibrium-index.duckdb | 15 + .../Elena/equilibrium-index.elena | 2 +- .../Mathematica/erd-s-nicolas-numbers.math | 28 ++ ...-s-selfridge-categorization-of-primes.easy | 59 +++ Task/Euler-method/DuckDB/euler-method.duckdb | 26 + Task/Euler-method/EasyLang/euler-method.easy | 35 +- .../FutureBasic/euler-method.basic | 33 ++ Task/Euler-method/Pluto/euler-method.pluto | 25 + .../DuckDB/eulers-constant-0.5772....duckdb | 21 + .../REXX/eulers-constant-0.5772....rexx | 10 +- .../DuckDB/eulers-identity.duckdb | 16 + .../Pluto/eulers-identity.pluto | 3 + .../evaluate-binomial-coefficients.duckdb | 23 + Task/Even-or-odd/Adina/even-or-odd-1.adina | 4 + Task/Even-or-odd/Adina/even-or-odd-2.adina | 4 + Task/Even-or-odd/ArkScript/even-or-odd.ark | 5 + Task/Even-or-odd/DuckDB/even-or-odd-1.duckdb | 3 + Task/Even-or-odd/DuckDB/even-or-odd-2.duckdb | 1 + Task/Even-or-odd/Nom/even-or-odd.num | 8 + Task/Even-or-odd/Pluto/even-or-odd.pluto | 4 + Task/Even-or-odd/YAMLScript/even-or-odd.ys | 6 + .../Elena/evolutionary-algorithm.elena | 14 +- .../Icon/evolutionary-algorithm-2.icon | 8 +- .../Zig/evolutionary-algorithm.zig | 114 +++++ ...an-exception-thrown-in-a-nested-call.elena | 2 +- Task/Exceptions/C++/exceptions-1.cpp | 19 +- Task/Exceptions/C++/exceptions-2.cpp | 7 +- Task/Exceptions/C++/exceptions-3.cpp | 5 +- Task/Exceptions/C++/exceptions-4.cpp | 17 +- Task/Exceptions/C++/exceptions-5.cpp | 17 + Task/Exceptions/Lua/exceptions-2.lua | 6 +- Task/Exceptions/Lua/exceptions-3.lua | 10 +- Task/Exceptions/Lua/exceptions-4.lua | 10 +- Task/Exceptions/Phix/exceptions-3.phix | 0 .../Tcl/{exceptions.tcl => exceptions-1.tcl} | 0 Task/Exceptions/Tcl/exceptions-2.tcl | 26 + Task/Execute-HQ9+/R/execute-hq9+.r | 25 + .../Pluto/execute-a-system-command.pluto | 1 + .../DuckDB/exponentiation-order.duckdb | 6 + .../Icon/exponentiation-order.icon | 5 + .../ArkScript/extend-your-language.ark | 20 + .../Koka/extend-your-language.koka | 28 ++ .../extreme-floating-point-values-1.duckdb | 8 + .../extreme-floating-point-values-2.duckdb | 1 + .../Factorial-primes/AWK/factorial-primes.awk | 15 + .../Agena/factorial-primes.agena | 17 + .../Fennel/factorial-primes.fennel | 30 ++ .../Factorial-primes/Lua/factorial-primes.lua | 28 +- .../Pluto/factorial-primes.pluto | 20 + Task/Factorial-primes/R/factorial-primes.r | 29 ++ Task/Factorial/ALGOL-60/factorial.alg | 14 - Task/Factorial/ALGOL-68/factorial-1.alg | 5 - Task/Factorial/ALGOL-68/factorial-2.alg | 30 -- Task/Factorial/ALGOL-68/factorial-3.alg | 7 - Task/Factorial/ALGOL-W/factorial.alg | 15 - Task/Factorial/Agena/factorial.agena | 25 + Task/Factorial/Apple/factorial-1.apple | 2 + Task/Factorial/Apple/factorial-2.apple | 16 + Task/Factorial/CBASIC/factorial.basic | 19 + Task/Factorial/DuckDB/factorial-1.duckdb | 3 + Task/Factorial/DuckDB/factorial-2.duckdb | 3 + Task/Factorial/DuckDB/factorial-3.duckdb | 2 + Task/Factorial/Fennel/factorial.fennel | 18 + Task/Factorial/Mn/factorial.mn | 12 + Task/Factorial/Pluto/factorial.pluto | 30 ++ Task/Factorial/REXX/factorial-2.rexx | 37 +- Task/Factorial/Rhombus/factorial-1.rhombus | 5 + Task/Factorial/Rhombus/factorial-2.rhombus | 7 + Task/Factorial/TAV/factorial.tav | 14 + Task/Factorial/Vyxal/factorial-1.vyxal | 1 + Task/Factorial/Vyxal/factorial-2.vyxal | 1 + Task/Factorial/Vyxal/factorial-3.vyxal | 1 + Task/Factorions/Ada/factorions.ada | 64 +++ Task/Factorions/Pluto/factorions.pluto | 18 + Task/Factorions/R/factorions.r | 4 +- .../ALGOL-M/factors-of-an-integer.alg | 45 +- .../Apple/factors-of-an-integer.apple | 2 + .../DuckDB/factors-of-an-integer-1.duckdb | 8 + .../DuckDB/factors-of-an-integer-2.duckdb | 19 + .../Pluto/factors-of-an-integer.pluto | 5 + .../Zig/factors-of-an-integer.zig | 43 ++ .../Bc/fairshare-between-two-and-more.bc | 21 + .../fairshare-between-two-and-more.duckdb | 42 ++ .../Farey-sequence/Pluto/farey-sequence.pluto | 30 ++ Task/Farey-sequence/Zig/farey-sequence.zig | 92 ++++ .../EasyLang/faulhabers-formula.easy | 94 ++++ .../EasyLang/faulhabers-triangle.easy | 67 +++ .../Rust/faulhabers-triangle.rs | 171 +++++++ .../feigenbaum-constant-calculation.duckdb | 46 ++ .../feigenbaum-constant-calculation.pluto | 29 ++ .../REXX/feigenbaum-constant-calculation.rexx | 27 +- .../fibonacci-n-step-number-sequences-1.jl | 42 +- .../fibonacci-n-step-number-sequences-2.jl | 28 +- .../fibonacci-n-step-number-sequences-3.jl | 11 +- .../fibonacci-n-step-number-sequences-4.jl | 13 +- .../fibonacci-n-step-number-sequences-5.jl | 38 +- .../fibonacci-n-step-number-sequences-6.jl | 36 ++ .../fibonacci-n-step-number-sequences-2.pas | 30 +- .../R/fibonacci-n-step-number-sequences.r | 34 ++ .../ArkScript/fibonacci-sequence-1.ark | 6 + .../ArkScript/fibonacci-sequence-2.ark | 12 + .../DuckDB/fibonacci-sequence-1.duckdb | 11 + .../DuckDB/fibonacci-sequence-2.duckdb | 2 + .../DuckDB/fibonacci-sequence-3.duckdb | 1 + .../DuckDB/fibonacci-sequence-4.duckdb | 16 + .../Elena/fibonacci-sequence-1.elena | 2 +- .../Elena/fibonacci-sequence-2.elena | 28 +- .../Pluto/fibonacci-sequence.pluto | 11 + .../Rhombus/fibonacci-sequence-1.rhombus | 6 + .../Rhombus/fibonacci-sequence-2.rhombus | 14 + .../TAV/fibonacci-sequence-1.tav | 8 + .../TAV/fibonacci-sequence-2.tav | 11 + .../EasyLang/fibonacci-word-fractal.easy | 24 + .../Julia/fibonacci-word-fractal.jl | 26 +- .../DuckDB/file-input-output.duckdb | 1 + Task/File-size/Elena/file-size.elena | 4 +- Task/Filter/Apple/filter-1.apple | 2 + Task/Filter/Apple/filter-2.apple | 2 + Task/Filter/DuckDB/filter-1.duckdb | 13 + Task/Filter/DuckDB/filter-2.duckdb | 7 + Task/Filter/DuckDB/filter-3.duckdb | 1 + Task/Filter/DuckDB/filter-4.duckdb | 1 + Task/Filter/DuckDB/filter-5.duckdb | 1 + Task/Filter/DuckDB/filter-6.duckdb | 2 + Task/Filter/DuckDB/filter-7.duckdb | 3 + Task/Filter/Elena/filter-1.elena | 2 +- Task/Filter/Elena/filter-2.elena | 2 +- Task/Filter/Pluto/filter.pluto | 5 + ...chess960-starting-position-identifier.easy | 61 +++ ...hess960-starting-position-identifier.basic | 2 +- ...hess960-starting-position-identifier.basic | 2 +- .../Ada/find-duplicate-files.ada | 128 +++++ .../FreeBASIC/find-duplicate-files.basic | 73 +++ ...ft-truncatable-prime-in-a-given-base.basic | 127 +++++ ...eft-truncatable-prime-in-a-given-base.rexx | 18 +- .../DuckDB/find-limit-of-recursion.duckdb | 11 + .../FutureBasic/find-limit-of-recursion.basic | 8 + .../REXX/find-limit-of-recursion-1.rexx | 11 - .../REXX/find-limit-of-recursion-2.rexx | 10 - .../REXX/find-limit-of-recursion.rexx | 13 + .../find-the-last-sunday-of-each-month.duckdb | 14 + .../Elena/first-class-functions.elena | 2 +- .../Five-weekends/DuckDB/five-weekends.duckdb | 19 + .../FutureBasic/five-weekends.basic | 54 ++ Task/Five-weekends/Red/five-weekends.red | 36 ++ .../DuckDB/fixed-length-records.duckdb | 10 + Task/FizzBuzz/ArkScript/fizzbuzz.ark | 12 + Task/FizzBuzz/Gleam/fizzbuzz.gleam | 10 +- Task/FizzBuzz/J/fizzbuzz-1.j | 2 +- Task/FizzBuzz/J/fizzbuzz-10.j | 38 +- Task/FizzBuzz/J/fizzbuzz-11.j | 36 -- Task/FizzBuzz/J/fizzbuzz-3.j | 2 +- Task/FizzBuzz/J/fizzbuzz-4.j | 2 +- Task/FizzBuzz/J/fizzbuzz-5.j | 6 +- Task/FizzBuzz/J/fizzbuzz-6.j | 7 +- Task/FizzBuzz/J/fizzbuzz-7.j | 8 +- Task/FizzBuzz/J/fizzbuzz-8.j | 7 +- Task/FizzBuzz/J/fizzbuzz-9.j | 3 +- Task/FizzBuzz/Pascal-P/fizzbuzz.pas | 14 + Task/FizzBuzz/Pluto/fizzbuzz.pluto | 11 + Task/FizzBuzz/Rhombus/fizzbuzz.rhombus | 8 + Task/FizzBuzz/Uiua/fizzbuzz.uiua | 2 +- Task/FizzBuzz/Vyxal/fizzbuzz.vyxal | 1 + .../ArkScript/flatten-a-list.ark | 13 + .../DuckDB/flatten-a-list.duckdb | 9 + .../FutureBasic/flipping-bits-game.basic | 2 +- .../Flipping-bits-game/R/flipping-bits-game.r | 59 +++ .../Dart/floyd-warshall-algorithm.dart | 54 ++ .../Erlang/floyd-warshall-algorithm.erl | 54 ++ .../Pluto/floyd-warshall-algorithm.pluto | 51 ++ .../R/floyd-warshall-algorithm.r | 67 +++ .../Swift/floyd-warshall-algorithm.swift | 51 ++ .../DuckDB/formatted-numeric-output.duckdb | 1 + .../Pluto/formatted-numeric-output.pluto | 1 + .../TAV/formatted-numeric-output.tav | 2 + .../DuckDB/forward-difference.duckdb | 16 + .../EasyLang/fraction-reduction.easy | 80 +++ Task/Fractran/R/fractran.r | 25 + Task/Fractran/Rust/fractran.rs | 75 +++ .../EasyLang/french-republican-calendar.easy | 99 ++++ .../Fortran/french-republican-calendar.f | 338 +++++++++++++ .../ArkScript/function-definition.ark | 2 + .../DuckDB/function-definition-1.duckdb | 1 + .../DuckDB/function-definition-2.duckdb | 10 + .../Pluto/function-definition.pluto | 5 + .../EasyLang/function-prototype.easy | 31 ++ .../FuncSug/gui-component-interaction.funcsug | 26 + ...gui-enabling-disabling-of-controls.funcsug | 30 ++ .../DuckDB/gamma-function.duckdb | 30 ++ .../FutureBasic/gamma-function.basic | 35 ++ .../Gamma-function/Pluto/gamma-function.pluto | 12 + Task/Gamma-function/REXX/gamma-function.rexx | 15 +- .../DuckDB/gapful-numbers.duckdb | 32 ++ .../EasyLang/gaussian-elimination.easy | 26 +- .../FutureBasic/gaussian-elimination.basic | 106 ++++ ...enerate-lower-case-ascii-alphabet-1.duckdb | 2 + ...enerate-lower-case-ascii-alphabet-2.duckdb | 1 + .../generate-lower-case-ascii-alphabet.pluto | 4 + ...tial.icon => generator-exponential-1.icon} | 0 .../Icon/generator-exponential-2.icon | 9 + .../Tcl/generator-exponential-3.tcl | 2 +- Task/Generic-swap/DuckDB/generic-swap.duckdb | 5 + Task/Giuga-numbers/Agena/giuga-numbers.agena | 26 + .../Giuga-numbers/EasyLang/giuga-numbers.easy | 8 +- Task/Giuga-numbers/Pluto/giuga-numbers.pluto | 28 ++ Task/Giuga-numbers/R/giuga-numbers.r | 16 + .../Agena/goldbachs-comet.agena | 22 + .../Fennel/goldbachs-comet.fennel | 49 ++ Task/Goldbachs-comet/Lua/goldbachs-comet.lua | 6 +- .../Pluto/goldbachs-comet.pluto | 23 + .../DuckDB/golden-ratio-convergence.duckdb | 24 + Task/Gotchas/DuckDB/gotchas-1.duckdb | 1 + Task/Gotchas/DuckDB/gotchas-2.duckdb | 2 + Task/Gotchas/DuckDB/gotchas-3.duckdb | 1 + Task/Gotchas/DuckDB/gotchas-4.duckdb | 3 + Task/Gotchas/DuckDB/gotchas-5.duckdb | 1 + Task/Gotchas/DuckDB/gotchas-6.duckdb | 2 + Task/Gotchas/DuckDB/gotchas-7.duckdb | 3 + Task/Gotchas/DuckDB/gotchas-8.duckdb | 2 + Task/Gray-code/Zig/gray-code.zig | 64 +++ .../DuckDB/greatest-common-divisor.duckdb | 12 + .../Pluto/greatest-common-divisor.pluto | 8 + .../ALGOL-68/greatest-element-of-a-list.alg | 21 +- .../greatest-element-of-a-list-1.duckdb | 1 + .../greatest-element-of-a-list-2.duckdb | 1 + .../greatest-element-of-a-list-3.duckdb | 4 + .../Pluto/greatest-element-of-a-list.pluto | 2 + .../TAV/greatest-element-of-a-list.tav | 4 + .../DuckDB/greatest-subsequential-sum.duckdb | 32 ++ .../greedy-algorithm-for-egyptian-fractions.r | 46 ++ .../EasyLang/greyscale-bars-display.easy | 6 +- ...ess-the-number-with-feedback-player-.basic | 95 ++++ .../guess-the-number-with-feedback.rhombus | 49 ++ .../TAV/guess-the-number-with-feedback.tav | 42 ++ .../Guess-the-number/Tcl/guess-the-number.tcl | 2 +- Task/HTTP/DuckDB/http.duckdb | 4 + .../DuckDB/https-authenticated.duckdb | 15 + .../Objeck/https-client-authenticated.objeck | 7 + Task/HTTPS/DuckDB/https.duckdb | 4 + Task/HTTPS/TAV/https.tav | 4 + .../DuckDB/hailstone-sequence.duckdb | 27 + .../Pluto/hailstone-sequence.pluto | 26 + .../Pluto/halt-and-catch-fire.pluto | 1 + .../TAV/halt-and-catch-fire.tav | 1 + .../FutureBasic/hamming-numbers.basic | 42 ++ Task/Happy-numbers/00-META.yaml | 2 +- Task/Happy-numbers/Frink/happy-numbers.frink | 19 + ...appy-numbers.rexx => happy-numbers-1.rexx} | 0 Task/Happy-numbers/REXX/happy-numbers-2.rexx | 42 ++ Task/Harmonic-series/Ada/harmonic-series.ada | 41 ++ .../DuckDB/harmonic-series.duckdb | 21 + .../Common-Lisp/hash-from-two-arrays-3.lisp | 3 + .../DuckDB/hash-from-two-arrays.duckdb | 4 + .../EasyLang/hash-from-two-arrays.easy | 38 ++ .../Maxima/hash-from-two-arrays.maxima | 5 + .../Pluto/hash-from-two-arrays.pluto | 5 + .../Tcl/hash-from-two-arrays-2.tcl | 33 +- .../Tcl/hash-from-two-arrays-3.tcl | 10 + ...wo-arrays.sh => hash-from-two-arrays-1.sh} | 2 +- .../UNIX-Shell/hash-from-two-arrays-2.sh | 9 + Task/Hash-join/DuckDB/hash-join.duckdb | 21 + .../DuckDB/haversine-formula.duckdb | 7 + .../TAV/hello-world-graphical.tav | 16 + .../ArkScript/hello-world-line-printer.ark | 1 + .../RISC-V-Assembly/hello-world-newbie.asm | 59 +++ .../hello-world-newline-omission.ark | 1 + .../Pluto/hello-world-newline-omission.pluto | 1 + .../Prolog/hello-world-newline-omission.pro | 1 + .../Pluto/hello-world-standard-error.pluto | 1 + .../Adina/hello-world-text-1.adina | 1 + .../Adina/hello-world-text-2.adina | 2 + .../Aria/hello-world-text.aria | 3 + .../ArkScript/hello-world-text.ark | 1 + .../AutoLISP/hello-world-text.l | 2 +- .../DuckDB/hello-world-text.duckdb | 5 + .../hello-world-text.basic | 1 + .../FuncSug/hello-world-text-1.funcsug | 1 + .../FuncSug/hello-world-text-2.funcsug | 1 + .../Hello-world-Text/Nom/hello-world-text.num | 1 + .../Pico-8/hello-world-text-1.pico8 | 1 + .../Pico-8/hello-world-text-2.pico8 | 1 + .../Pluto/hello-world-text.pluto | 1 + .../Rhombus/hello-world-text.rhombus | 1 + .../Hello-world-Text/TAV/hello-world-text.tav | 3 + .../DuckDB/here-document-1.duckdb | 6 + .../DuckDB/here-document-2.duckdb | 4 + Task/Hex-words/R/hex-words.r | 12 +- .../Pluto/higher-order-functions.pluto | 2 + .../Hilbert-curve/EasyLang/hilbert-curve.easy | 9 +- .../hofstadter-figure-figure-sequences.f | 194 +++++++ Task/Home-primes/REXX/home-primes.rexx | 12 +- Task/Honeycombs/EasyLang/honeycombs.easy | 101 ++++ ...rners-rule-for-polynomial-evaluation.agena | 15 + ...ners-rule-for-polynomial-evaluation.fennel | 17 + ...rners-rule-for-polynomial-evaluation.pluto | 15 + ...ners-rule-for-polynomial-evaluation-2.rexx | 10 +- .../ALGOL-68/humble-numbers.alg | 8 +- .../Humble-numbers/Agena/humble-numbers.agena | 32 ++ Task/Humble-numbers/Fortran/humble-numbers.f | 81 +++ .../Humble-numbers/Pluto/humble-numbers.pluto | 31 ++ Task/Humble-numbers/R/humble-numbers.r | 16 + Task/Humble-numbers/Rust/humble-numbers.rs | 51 ++ .../EasyLang/hunt-the-wumpus.easy | 92 ++++ .../Liberty-BASIC/hunt-the-wumpus.basic | 272 ++++++++++ .../Hunt-the-Wumpus/Mojo/hunt-the-wumpus.mojo | 203 ++++++++ .../Apple/isbn13-check-digit.apple | 1 + .../DuckDB/isbn13-check-digit.duckdb | 17 + .../Prolog/isbn13-check-digit-1.pro | 12 + .../Prolog/isbn13-check-digit-2.pro | 11 + .../Prolog/isbn13-check-digit-3.pro | 12 + .../Prolog/isbn13-check-digit-4.pro | 12 + .../DuckDB/identity-matrix.duckdb | 20 + ...acters-that-can-be-used-for-symbols.duckdb | 27 + ...the-lowercase-and-uppercase-letters.duckdb | 19 + .../RISC-V-Assembly/include-a-file-1.asm | 8 + .../RISC-V-Assembly/include-a-file-2.asm | 152 ++++++ .../RISC-V-Assembly/include-a-file-3.asm | 44 ++ .../increment-a-numerical-string-1.duckdb | 1 + .../increment-a-numerical-string-2.duckdb | 1 + .../increment-a-numerical-string-3.duckdb | 1 + .../Pluto/increment-a-numerical-string.pluto | 4 + Task/Infinity/ArkScript/infinity.ark | 3 + Task/Infinity/DuckDB/infinity.duckdb | 1 + Task/Infinity/Pluto/infinity.pluto | 8 + .../V-(Vlang)/inheritance-multiple.v | 38 ++ .../Rhombus/inheritance-single.rhombus | 17 + .../V-(Vlang)/inheritance-single.v | 36 ++ Task/Input-loop/Nom/input-loop.num | 1 + .../DuckDB/integer-comparison.duckdb | 8 + .../Prolog/integer-comparison-1.pro | 14 + .../Prolog/integer-comparison-2.pro | 7 + .../YAMLScript/integer-comparison.ys | 8 + .../ArkScript/integer-sequence-1.ark | 4 + .../ArkScript/integer-sequence-2.ark | 5 + .../Introspection/DuckDB/introspection.duckdb | 10 + .../DuckDB/inverted-index.duckdb | 25 + .../DuckDB/inverted-syntax-1.duckdb | 1 + .../DuckDB/inverted-syntax-2.duckdb | 1 + .../DuckDB/inverted-syntax-3.duckdb | 1 + .../REXX/isqrt-integer-square-root-of-x.rexx | 9 +- .../Prolog/iterated-digits-squaring.pro | 36 ++ Task/JSON/Agena/json.agena | 28 ++ Task/JSON/DuckDB/json-1.duckdb | 1 + Task/JSON/DuckDB/json-2.duckdb | 1 + Task/JSON/DuckDB/json-3.duckdb | 1 + Task/JSON/Pluto/json.pluto | 30 ++ Task/JSON/REBOL/{json.rebol => json-1.rebol} | 4 +- Task/JSON/REBOL/json-2.rebol | 16 + Task/Jacobi-symbol/Excel/jacobi-symbol.excel | 34 ++ .../ALGOL-68/jacobsthal-numbers.alg | 2 +- .../Agena/jacobsthal-numbers.agena | 50 ++ .../EasyLang/jacobsthal-numbers.easy | 50 ++ .../Fennel/jacobsthal-numbers.fennel | 64 +++ .../Lua/jacobsthal-numbers.lua | 65 +++ .../Pluto/jacobsthal-numbers.pluto | 50 ++ .../DuckDB/jaro-similarity.duckdb | 6 + .../Agena/jewels-and-stones.agena | 10 + .../Fortran/jewels-and-stones.f | 90 ++++ .../Icon/jewels-and-stones.icon | 10 + .../Lua/jewels-and-stones.lua | 3 +- .../Pluto/jewels-and-stones.pluto | 12 + Task/JortSort/YAMLScript/jortsort.ys | 8 + .../OxygenBasic/josephus-problem.basic | 20 + .../Pluto/josephus-problem.pluto | 34 ++ .../Prolog/josephus-problem-1.pro | 15 + .../Prolog/josephus-problem-2.pro | 5 + .../QBasic/josephus-problem.basic | 16 +- ...problem-1.basic => josephus-problem.basic} | 0 .../Run-BASIC/josephus-problem-1.basic | 16 + .../josephus-problem-2.basic | 0 .../Wren/josephus-problem.wren | 2 +- .../XBasic/josephus-problem.basic | 21 + Task/Julia-set/EasyLang/julia-set.easy | 2 +- Task/Jump-anywhere/Koka/jump-anywhere.koka | 40 ++ Task/K-d-tree/Elixir/k-d-tree.ex | 262 ++++++++++ Task/K-d-tree/Swift/k-d-tree.swift | 203 ++++++++ Task/K-d-tree/Zig/k-d-tree.zig | 358 +++++++++++++ .../ALGOL-68/kaprekar-numbers.alg | 3 + .../Agena/kaprekar-numbers.agena | 42 ++ .../Pluto/kaprekar-numbers.pluto | 43 ++ .../Zig/knapsack-problem-0-1.zig | 109 ++++ .../Ada/knapsack-problem-bounded.ada | 143 ++++++ .../Fortran/knapsack-problem-bounded.f | 184 +++++++ .../Lua/knapsack-problem-bounded.lua | 180 +++++++ .../Rust/knapsack-problem-bounded.rs | 99 ++++ .../ALGOL-68/knapsack-problem-continuous.alg | 24 + .../ALGOL-W/knapsack-problem-continuous.alg | 38 ++ Task/Knights-tour/EasyLang/knights-tour.easy | 7 +- Task/Knights-tour/Zig/knights-tour.zig | 128 +++++ .../Knuth-shuffle/DuckDB/knuth-shuffle.duckdb | 63 +++ .../Knuth-shuffle/REBOL/knuth-shuffle-1.rebol | 4 + .../Knuth-shuffle/REBOL/knuth-shuffle-2.rebol | 48 ++ Task/Knuth-shuffle/REBOL/knuth-shuffle.rebol | 18 - .../Knuth-shuffle/YAMLScript/knuth-shuffle.ys | 8 + .../Fortran/knuths-power-tree.f | 379 ++++++++++++++ ...s-power-tree.py => knuths-power-tree-1.py} | 0 .../Python/knuths-power-tree-2.py | 57 +++ Task/Koch-curve/EasyLang/koch-curve.easy | 14 +- .../largest-int-from-concatenated-ints.duckdb | 18 + .../AutoLISP/largest-proper-divisor-of-n.l | 22 + .../C++/last-friday-of-each-month-3.cpp | 11 + .../DuckDB/last-friday-of-each-month.duckdb | 14 + .../last-letter-first-letter.basic | 88 ++++ Task/Leap-year/DuckDB/leap-year.duckdb | 2 + Task/Leap-year/Pluto/leap-year.pluto | 7 + .../DuckDB/left-factorials.duckdb | 43 ++ .../DuckDB/leonardo-numbers.duckdb | 27 + .../Pascal-P/leonardo-numbers.pas | 31 ++ .../DuckDB/letter-frequency-1.duckdb | 8 + .../DuckDB/letter-frequency-2.duckdb | 7 + .../Koka/letter-frequency.koka | 20 + .../Letter-frequency/TAV/letter-frequency.tav | 11 + .../Ada/levenshtein-distance-alignment.ada | 88 ++++ .../DuckDB/levenshtein-distance.duckdb | 5 + .../Pascal-P/levenshtein-distance.pas | 81 +++ .../DuckDB/list-comprehensions-1.duckdb | 7 + .../DuckDB/list-comprehensions-2.duckdb | 6 + .../DuckDB/list-comprehensions-3.duckdb | 4 + .../DuckDB/list-comprehensions-4.duckdb | 5 + .../DuckDB/list-comprehensions-5.duckdb | 1 + .../PascalABC.NET/list-comprehensions.pas | 2 +- .../ArkScript/literals-floating-point.ark | 3 + .../Pluto/literals-floating-point.pluto | 4 + .../REXX/literals-floating-point.rexx | 6 +- .../ArkScript/literals-integer.ark | 4 + .../DuckDB/literals-integer.duckdb | 1 + .../Pluto/literals-integer.pluto | 4 + .../ArkScript/literals-string.ark | 4 + .../ArkScript/logical-operations.ark | 9 + .../DuckDB/logical-operations.duckdb | 22 + .../Red/logical-operations.red | 14 + .../Ada/long-literals-with-continuations.ada | 34 ++ .../F-Sharp/long-multiplication.fs | 3 - Task/Long-primes/REXX/long-primes.rexx | 12 +- .../ALGOL-68/longest-common-subsequence.alg | 31 +- .../Ada/longest-increasing-subsequence.ada | 51 ++ .../longest-increasing-subsequence.duckdb | 31 ++ ...-over-multiple-arrays-simultaneously.pluto | 6 + ...-over-multiple-arrays-simultaneously.rebol | 10 + ...op-over-multiple-arrays-simultaneously.tav | 15 + Task/Loops-Break/DuckDB/loops-break.duckdb | 22 + Task/Loops-Break/Koka/loops-break.koka | 12 + Task/Loops-Break/Pluto/loops-break.pluto | 6 + Task/Loops-Break/TAV/loops-break-1.tav | 7 + Task/Loops-Break/TAV/loops-break-2.tav | 7 + Task/Loops-Break/Ursalang/loops-break.ursa | 12 + .../{loops-break.zig => loops-break-1.zig} | 0 Task/Loops-Break/Zig/loops-break-2.zig | 25 + .../Loops-Continue/Pluto/loops-continue.pluto | 8 + ...-continue.rebol => loops-continue-1.rebol} | 2 +- .../REBOL/loops-continue-2.rebol | 8 + .../DuckDB/loops-do-while.duckdb | 16 + .../Loops-Do-while/Pluto/loops-do-while.pluto | 4 + Task/Loops-Do-while/TAV/loops-do-while-1.tav | 6 + Task/Loops-Do-while/TAV/loops-do-while-2.tav | 6 + .../DuckDB/loops-downward-for-1.duckdb | 1 + .../DuckDB/loops-downward-for-2.duckdb | 14 + .../Pluto/loops-downward-for.pluto | 2 + .../TAV/loops-downward-for.tav | 6 + .../loops-for-with-a-specified-step-1.duckdb | 3 + .../loops-for-with-a-specified-step-2.duckdb | 8 + .../loops-for-with-a-specified-step.pluto | 2 + .../loops-for-with-a-specified-step.rebol | 3 +- Task/Loops-For/Adina/loops-for-1.adina | 6 + Task/Loops-For/Adina/loops-for-2.adina | 7 + Task/Loops-For/DuckDB/loops-for-1.duckdb | 3 + Task/Loops-For/DuckDB/loops-for-2.duckdb | 3 + Task/Loops-For/DuckDB/loops-for-3.duckdb | 3 + Task/Loops-For/Eiffel/loops-for.e | 17 + .../Extended-Color-BASIC/loops-for.basic | 6 + Task/Loops-For/Pluto/loops-for.pluto | 4 + Task/Loops-For/TAV/loops-for-1.tav | 4 + Task/Loops-For/TAV/loops-for-2.tav | 2 + Task/Loops-For/TAV/loops-for-3.tav | 4 + Task/Loops-Foreach/Pluto/loops-foreach.pluto | 6 + Task/Loops-Foreach/REBOL/loops-foreach.rebol | 8 +- ...-increment-loop-index-within-loop-body.arm | 18 +- ...crement-loop-index-within-loop-body.arturo | 16 +- ...-increment-loop-index-within-loop-body.ahk | 26 +- ...ncrement-loop-index-within-loop-body.basic | 24 +- ...-increment-loop-index-within-loop-body.cpp | 22 +- ...increment-loop-index-within-loop-body.lisp | 12 +- ...crement-loop-index-within-loop-body.duckdb | 33 ++ ...increment-loop-index-within-loop-body.icon | 2 +- ...-increment-loop-index-within-loop-body.ksh | 30 +- ...ent-loop-index-within-loop-body.lambdatalk | 84 ++-- ...ncrement-loop-index-within-loop-body.maple | 12 +- ...ncrement-loop-index-within-loop-body.pluto | 27 + ...ncrement-loop-index-within-loop-body.rebol | 50 ++ Task/Loops-Infinite/Eiffel/loops-infinite.e | 11 + .../Loops-Infinite/Pluto/loops-infinite.pluto | 1 + ...-infinite.rebol => loops-infinite-1.rebol} | 0 .../REBOL/loops-infinite-2.rebol | 1 + .../REBOL/loops-infinite-3.rebol | 1 + Task/Loops-Infinite/TAV/loops-infinite.tav | 2 + .../DuckDB/loops-n-plus-one-half.duckdb | 14 + .../Pluto/loops-n-plus-one-half.pluto | 4 + .../TAV/loops-n-plus-one-half-1.tav | 6 + .../TAV/loops-n-plus-one-half-2.tav | 6 + Task/Loops-Nested/DuckDB/loops-nested.duckdb | 50 ++ Task/Loops-Nested/Pluto/loops-nested.pluto | 18 + Task/Loops-Nested/REBOL/loops-nested.rebol | 2 +- Task/Loops-Nested/Zig/loops-nested.zig | 38 ++ Task/Loops-While/DuckDB/loops-while.duckdb | 15 + Task/Loops-While/Mn/loops-while.mn | 6 + Task/Loops-While/Pluto/loops-while.pluto | 5 + Task/Loops-While/REBOL/loops-while.rebol | 2 +- Task/Loops-While/TAV/loops-while.tav | 4 + Task/Loops-While/Ursalang/loops-while.ursa | 6 + Task/Loops-While/Zig/loops-while.zig | 11 +- .../DuckDB/loops-with-multiple-ranges.duckdb | 32 ++ ...ges.hs => loops-with-multiple-ranges-1.hs} | 0 .../Haskell/loops-with-multiple-ranges-2.hs | 30 ++ .../Haskell/loops-with-multiple-ranges-3.hs | 27 + .../Pluto/loops-with-multiple-ranges.pluto | 60 +++ .../REBOL/loops-with-multiple-ranges.rebol | 59 +++ .../C++/loops-wrong-ranges.cpp | 60 +-- .../Common-Lisp/loops-wrong-ranges.lisp | 34 +- .../Eiffel/loops-wrong-ranges.e | 24 +- .../Icon/loops-wrong-ranges.icon | 39 ++ .../Pluto/loops-wrong-ranges.pluto | 19 + .../Python/loops-wrong-ranges.py | 20 +- .../REBOL/loops-wrong-ranges.rebol | 30 ++ .../luhn-test-of-credit-card-numbers.duckdb | 43 ++ .../luhn-test-of-credit-card-numbers.pluto | 22 + .../C-sharp/m-bius-function.cs | 84 ++++ .../Pascal-P/m-bius-function.pas | 39 ++ .../Pluto/m-bius-function.pluto | 35 ++ .../PowerShell/m-bius-function.psh | 28 ++ Task/M-bius-function/R/m-bius-function.r | 28 ++ Task/M-bius-function/Tcl/m-bius-function.tcl | 42 ++ Task/M-bius-function/Zig/m-bius-function.zig | 84 ++++ Task/MD5/DuckDB/md5.duckdb | 1 + Task/MD5/JavaScript/md5.js | 149 ++++++ Task/MD5/REBOL/md5-1.rebol | 2 + Task/MD5/REBOL/md5-2.rebol | 2 + Task/MD5/REBOL/md5.rebol | 2 - Task/Machine-code/Ada/machine-code.ada | 68 +++ Task/Machine-code/Pluto/machine-code-1.pluto | 23 + Task/Machine-code/Pluto/machine-code-2.pluto | 19 + Task/Magic-8-ball/Prolog/magic-8-ball.pro | 13 + .../Pascal-P/magic-constant.pas | 35 ++ .../magic-squares-of-doubly-even-order.objeck | 43 ++ .../magic-squares-of-doubly-even-order.pluto | 29 ++ .../Pluto/magic-squares-of-odd-order.pluto | 28 ++ .../magic-squares-of-singly-even-order.pluto | 73 +++ .../Zig/main-step-of-gost-28147-89.zig | 218 ++++++++ .../EasyLang/mandelbrot-set.easy | 2 +- Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl | 2 +- Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl | 41 -- Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl | 41 -- Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl | 39 -- Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl | 71 --- .../Python/mandelbrot-set-10.py | 124 ++++- .../Python/mandelbrot-set-11.py | 8 + .../Python/mandelbrot-set-12.py | 5 + .../Mandelbrot-set/Python/mandelbrot-set-5.py | 22 +- .../Mandelbrot-set/Python/mandelbrot-set-6.py | 22 +- .../Mandelbrot-set/Python/mandelbrot-set-7.py | 39 +- .../Mandelbrot-set/Python/mandelbrot-set-8.py | 49 +- .../Mandelbrot-set/Python/mandelbrot-set-9.py | 93 +++- Task/Map-range/DuckDB/map-range.duckdb | 9 + Task/Map-range/Pascal-P/map-range.pas | 14 + .../DuckDB/matrix-multiplication-1.duckdb | 7 + .../DuckDB/matrix-multiplication-2.duckdb | 16 + .../DuckDB/matrix-multiplication-3.duckdb | 39 ++ .../Objeck/matrix-multiplication.objeck | 8 + .../DuckDB/matrix-transposition-1.duckdb | 1 + .../DuckDB/matrix-transposition-2.duckdb | 22 + .../DuckDB/matrix-transposition-3.duckdb | 5 + Task/Mayan-calendar/Rust/mayan-calendar.rs | 121 +++++ .../FutureBasic/mayan-numerals.basic | 117 +++++ .../Fortran/mcnuggets-problem.f | 64 +++ .../JavaScript/meissel-mertens-constant.js | 135 +++++ .../REXX/meissel-mertens-constant.rexx | 23 +- .../Rust/meissel-mertens-constant.rs | 39 ++ .../merge-and-aggregate-datasets.duckdb | 32 ++ .../DuckDB/metallic-ratios-1.duckdb | 5 + .../DuckDB/metallic-ratios-2.duckdb | 24 + .../DuckDB/metallic-ratios-3.duckdb | 28 ++ .../V-(Vlang)/metaprogramming.v | 30 ++ .../Agena/mian-chowla-sequence.agena | 31 ++ .../Pluto/mian-chowla-sequence.pluto | 35 ++ .../DuckDB/middle-three-digits.duckdb | 22 + .../Haskell/miller-rabin-primality-test-3.hs | 15 + .../Liberty-BASIC/minesweeper-game.basic | 422 ++++++++++++++++ .../Ada/minimal-steps-down-to-1.ada | 108 ++++ Task/Modular-arithmetic/00-TASK.txt | 9 +- ...thmetic.lisp => modular-arithmetic-1.lisp} | 0 .../Common-Lisp/modular-arithmetic-2.lisp | 25 + .../Rust/modular-arithmetic.rs | 177 +++++++ .../Zig/modular-arithmetic.zig | 94 ++++ .../FutureBasic/modular-inverse.basic | 10 + .../Pluto/modular-inverse.pluto | 5 + Task/Modular-inverse/Zig/modular-inverse.zig | 29 ++ .../Koka/monads-writer-monad.koka | 47 ++ .../APL/monte-carlo-methods.apl | 1 + .../C++/monte-carlo-methods.cpp | 46 +- .../DuckDB/monte-carlo-methods.duckdb | 20 + .../FutureBasic/monte-carlo-methods.basic | 48 ++ .../SETL/monte-carlo-methods.setl | 21 + .../Motzkin-numbers/REXX/motzkin-numbers.rexx | 9 +- .../REXX/multi-base-primes.rexx | 13 +- .../BBC-BASIC/multi-dimensional-array-1.basic | 29 ++ .../BBC-BASIC/multi-dimensional-array-2.basic | 15 + .../Rust/multiple-regression.rs | 270 ++++++++++ .../Agena/multiplication-tables.agena | 5 +- .../Pluto/multiplication-tables.pluto | 13 + .../TAV/multiplication-tables.tav | 10 + .../F-Sharp/multiplicative-order.fs | 8 + Task/Munchausen-numbers/00-META.yaml | 1 + .../ArkScript/munchausen-numbers.ark | 30 ++ .../Munchausen-numbers/R/munchausen-numbers.r | 7 +- .../EasyLang/munching-squares.easy | 4 +- .../YAMLScript/munching-squares.ys | 14 + Task/Musical-scale/Java/musical-scale.java | 2 +- Task/Mutex/FutureBasic/mutex.basic | 19 + .../Pluto/mutual-recursion.pluto | 10 + .../ArkScript/n-queens-problem.ark | 32 ++ .../FutureBasic/named-parameters.basic | 9 + .../Icon/named-parameters.icon | 2 +- .../Pluto/named-parameters.pluto | 7 + .../Ada/naming-conventions-1.ada | 8 + .../Ada/naming-conventions-2.ada | 3 + .../Ada/naming-conventions-3.ada | 3 + .../ALGOL-68/narcissistic-decimal-number.alg | 88 ++-- .../Agena/narcissistic-decimal-number.agena | 10 +- ....lua => narcissistic-decimal-number-1.lua} | 0 .../Lua/narcissistic-decimal-number-2.lua | 59 +++ .../Pluto/narcissistic-decimal-number.pluto | 50 ++ .../DuckDB/nested-function.duckdb | 12 + .../Pluto/nested-templated-data.pluto | 20 + .../next-highest-int-from-digits.ys | 44 ++ .../Fortran/non-decimal-radices-convert.f | 5 +- .../Pluto/non-decimal-radices-convert.pluto | 7 + .../REXX/non-decimal-radices-convert.rexx | 14 +- Task/Nth-root/DuckDB/nth-root.duckdb | 20 + Task/Nth/DuckDB/nth.duckdb | 26 + Task/Null-object/ArkScript/null-object.ark | 5 + Task/Null-object/Tcl/null-object-2.tcl | 10 +- Task/Null-object/Tcl/null-object-3.tcl | 2 + Task/Null-object/Tcl/null-object-4.tcl | 5 + ...integration-gauss-legendre-quadrature-1.py | 188 +++---- ...tegration-gauss-legendre-quadrature-2.rexx | 30 +- .../Pluto/numerical-integration.pluto | 20 + .../REXX/numerical-integration.rexx | 62 ++- Task/OLE-automation/Julia/ole-automation.jl | 34 ++ .../C++/object-serialization.cpp | 16 +- .../EchoLisp/object-serialization-1.l | 10 +- .../Erlang/object-serialization.erl | 32 +- .../Objective-C/object-serialization.m | 18 +- .../Python/object-serialization.py | 12 +- .../REBOL/object-serialization.rebol | 84 ++++ .../Odd-word-problem/Nom/odd-word-problem.num | 23 + .../old-russian-measure-of-length.basic | 47 ++ .../ASIC/old-russian-measure-of-length.asic | 65 +++ .../old-russian-measure-of-length.basic | 2 +- .../Delphi/old-russian-measure-of-length.pas | 2 +- .../old-russian-measure-of-length.easy | 2 +- .../old-russian-measure-of-length.basic | 4 +- .../old-russian-measure-of-length.basic | 35 ++ .../old-russian-measure-of-length.gambas | 2 +- .../Go/old-russian-measure-of-length.go | 4 +- .../Kotlin/old-russian-measure-of-length.kts | 4 +- .../old-russian-measure-of-length.basic | 31 ++ .../Pluto/old-russian-measure-of-length.pluto | 35 ++ .../old-russian-measure-of-length-1.pro | 101 ++++ .../old-russian-measure-of-length-2.pro | 19 + .../old-russian-measure-of-length.basic | 2 +- .../R/old-russian-measure-of-length.r | 5 +- .../Ring/old-russian-measure-of-length.ring | 4 +- .../old-russian-measure-of-length.basic | 2 +- .../Wren/old-russian-measure-of-length.wren | 6 +- .../old-russian-measure-of-length.basic | 8 +- .../XPL0/old-russian-measure-of-length.xpl0 | 4 +- .../old-russian-measure-of-length.basic | 4 +- .../one-dimensional-cellular-automata.ys | 17 + .../DuckDB/one-of-n-lines-in-a-file.duckdb | 4 + .../Pluto/order-by-pair-comparisons.pluto | 37 ++ .../Prolog/order-by-pair-comparisons-1.pro | 12 + .../Prolog/order-by-pair-comparisons-2.pro | 15 + .../DuckDB/order-two-numerical-lists.duckdb | 3 + .../Ordered-words/DuckDB/ordered-words.duckdb | 20 + Task/Ordered-words/TAV/ordered-words.tav | 20 + .../Scheme/own-digits-power-sum.scm | 46 ++ ...ovan-sequence.jl => padovan-sequence-1.jl} | 2 +- .../Julia/padovan-sequence-2.jl | 1 + .../Phix/padovan-sequence-2.phix | 88 ++-- .../Phix/padovan-sequence-3.phix | 165 ++---- .../Phix/padovan-sequence-4.phix | 136 +++++ .../ALGOL-68/palindrome-detection.alg | 5 +- .../DuckDB/palindrome-detection.duckdb | 31 ++ .../Pluto/palindrome-detection.pluto | 7 + .../Free-Pascal-Lazarus/pancake-numbers.pas | 31 ++ ...-numbers.basic => pancake-numbers-1.basic} | 0 .../FreeBASIC/pancake-numbers-2.basic | 105 ++++ .../Julia/pancake-numbers-1.jl | 14 - ...ancake-numbers-2.jl => pancake-numbers.jl} | 0 .../Phix/pancake-numbers-4.phix | 90 ++++ .../Pluto/pancake-numbers-1.pluto | 22 + .../Pluto/pancake-numbers-2.pluto | 63 +++ .../Pluto/pancake-numbers-3.pluto | 51 ++ .../Pluto/pancake-numbers-4.pluto | 55 ++ .../Pancake-numbers/Ruby/pancake-numbers-1.rb | 26 + .../Pancake-numbers/Ruby/pancake-numbers-2.rb | 22 + Task/Pancake-numbers/Ruby/pancake-numbers.rb | 19 - .../Wren/pancake-numbers-1.wren | 11 +- .../Wren/pancake-numbers-3.wren | 86 ++++ .../Wren/pancake-numbers-4.wren | 91 ++++ .../DuckDB/parameterized-sql-statement.duckdb | 17 + .../Dart/parse-an-ip-address.dart | 128 +++++ .../Elixir/parse-an-ip-address.ex | 83 +++ .../Fortran/parse-an-ip-address.f | 320 ++++++++++++ .../JavaScript/parse-an-ip-address.js | 123 +++++ .../Mathematica/parse-an-ip-address.math | 100 ++++ .../OCaml/parse-an-ip-address.ml | 192 +++++++ .../R/parse-an-ip-address.r | 127 +++++ ...ip-address.rs => parse-an-ip-address-1.rs} | 0 .../Rust/parse-an-ip-address-2.rs | 354 +++++++++++++ .../Swift/parse-an-ip-address.swift | 187 +++++++ .../Zig/parse-an-ip-address.zig | 238 +++++++++ .../parsing-rpn-calculator-algorithm.cr | 26 + .../parsing-rpn-calculator-algorithm.pluto | 33 ++ .../Red/parsing-rpn-calculator-algorithm.red | 21 + .../Red/parsing-rpn-to-infix-conversion.red | 58 +++ .../Red/parsing-shunting-yard-algorithm.red | 90 ++++ .../EasyLang/pascals-triangle-puzzle.easy | 29 ++ .../Fortran/pascals-triangle-puzzle.f | 124 +++++ .../JavaScript/pascals-triangle-puzzle.js | 102 ++++ .../Pluto/pascals-triangle-puzzle.pluto | 19 + .../DuckDB/pascals-triangle.duckdb | 16 + .../pathological-floating-point-problems.alg | 35 +- ...athological-floating-point-problems-1.rexx | 15 - ...athological-floating-point-problems-2.rexx | 18 - ...athological-floating-point-problems-3.rexx | 13 - .../pathological-floating-point-problems.rexx | 51 ++ .../{pell-numbers.jl => pell-numbers-1.jl} | 0 Task/Pell-numbers/Julia/pell-numbers-2.jl | 2 + Task/Pell-numbers/PARI-GP/pell-numbers.parigp | 59 +++ Task/Perfect-numbers/00-TASK.txt | 2 +- .../FutureBasic/perfect-shuffle.basic | 81 +++ .../Pluto/perfect-shuffle.pluto | 45 ++ Task/Perlin-noise/EasyLang/perlin-noise.easy | 2 +- Task/Perlin-noise/Zig/perlin-noise.zig | 8 +- .../DuckDB/permutations-derangements.duckdb | 49 ++ .../Zig/permutations-by-swapping.zig | 50 ++ Task/Permutations/DuckDB/permutations.duckdb | 18 + Task/Permutations/Pluto/permutations.pluto | 6 + Task/Permutations/TAV/permutations-1.tav | 24 + Task/Permutations/TAV/permutations-2.tav | 28 ++ Task/Permutations/TAV/permutations-3.tav | 17 + Task/Permutations/TAV/permutations-4.tav | 44 ++ .../Agena/pernicious-numbers.agena | 32 ++ .../Pluto/pernicious-numbers.pluto | 38 ++ .../REXX/pernicious-numbers.rexx | 9 +- .../Prolog/phrase-reversals.pro | 20 + .../DuckDB/pick-random-element.duckdb | 9 + .../Pluto/pick-random-element.pluto | 4 + .../Scheme/pick-random-element.scm | 6 + ...-element.tcl => pick-random-element-1.tcl} | 0 .../Tcl/pick-random-element-2.tcl | 79 +++ .../Pierpont-primes/Python/pierpont-primes.py | 24 +- .../REXX/pierpont-primes-1.rexx | 11 +- .../REXX/pierpont-primes-2.rexx | 12 +- Task/Pisano-period/Agena/pisano-period.agena | 32 ++ Task/Pisano-period/Pluto/pisano-period.pluto | 42 ++ .../Plasma-effect/EasyLang/plasma-effect.easy | 4 +- .../FuncSug/play-recorded-sounds.funcsug | 30 ++ .../Raku/play-recorded-sounds.raku | 31 ++ .../EasyLang/plot-coordinate-pairs.easy | 10 +- .../M2000-Interpreter/polymorphism-1.m2000 | 6 - .../M2000-Interpreter/polymorphism-2.m2000 | 76 --- .../M2000-Interpreter/polymorphism-3.m2000 | 67 --- .../M2000-Interpreter/polymorphism.m2000 | 108 ++++ .../Rhombus/polymorphism-1.rhombus | 11 + .../Rhombus/polymorphism-2.rhombus | 13 + .../REXX/polynomial-long-division-2.rexx | 14 +- Task/Polyspiral/EasyLang/polyspiral.easy | 5 +- Task/Polyspiral/REBOL/polyspiral.rebol | 42 ++ .../Prolog/population-count.pro | 12 + Task/Power-set/Pluto/power-set.pluto | 9 + .../REXX/primality-by-wilsons-theorem.rexx | 12 +- .../ALGOL-68/primality-by-trial-division.alg | 20 +- .../Agena/primality-by-trial-division.agena | 13 + .../primality-by-trial-division-1.duckdb | 29 ++ .../primality-by-trial-division-2.duckdb | 18 + .../Pluto/primality-by-trial-division.pluto | 13 + .../REXX/primality-by-trial-division.rexx | 12 +- .../DuckDB/prime-decomposition.duckdb | 29 ++ .../OoRexx/prime-decomposition.rexx | 36 ++ .../Priority-queue/Pluto/priority-queue.pluto | 12 + .../DuckDB/probabilistic-choice.duckdb | 65 +++ .../EasyLang/problem-of-apollonius.easy | 5 +- .../ArkScript/program-termination.ark | 3 + .../DuckDB/proper-divisors.duckdb | 33 ++ ...random-numbers-middle-square-method.duckdb | 20 + .../EasyLang/pythagoras-tree.easy | 2 +- .../JavaScript/pythagoras-tree-2.js | 2 +- .../Quaternion-type/REXX/quaternion-type.rexx | 55 +- ...-definition.alg => queue-definition-1.alg} | 0 .../ALGOL-68/queue-definition-2.alg | 7 + .../YAMLScript/quickselect-algorithm.ys | 25 + Task/Quine/Extended-Color-BASIC/quine.basic | 1 + Task/Quine/REBOL/quine-1.rebol | 1 + Task/Quine/REBOL/quine-2.rebol | 14 + Task/Quine/REBOL/quine.rebol | 1 - .../Prolog/rpg-attributes-generator-1.pro | 16 + .../Prolog/rpg-attributes-generator-2.pro | 8 + .../Rust/ramanujan-primes-twins.rs | 121 +++++ .../REXX/ramanujans-constant.rexx | 7 +- ...er-douglas-peucker-line-simplification.pas | 94 ++++ .../REXX/random-number-generator-device-.rexx | 9 +- .../DuckDB/random-numbers.duckdb | 14 + Task/Random-numbers/REXX/random-numbers.rexx | 45 +- .../DuckDB/range-expansion.duckdb | 10 + .../DuckDB/range-extraction.duckdb | 43 ++ ...ead-a-file-character-by-character-utf8.ada | 21 + .../DuckDB/read-a-file-line-by-line.duckdb | 3 + .../Pluto/read-a-file-line-by-line-1.pluto | 8 + .../Pluto/read-a-file-line-by-line-2.pluto | 3 + .../read-a-specific-line-from-a-file.rebol | 4 +- .../ArkScript/read-entire-file.ark | 1 + .../real-constants-and-functions.maxima | 10 + .../TAV/real-constants-and-functions.tav | 13 + .../DuckDB/reflection-list-methods.duckdb | 14 + .../DuckDB/reflection-list-properties.duckdb | 1 + .../Maxima/regular-expressions.maxima | 5 + .../DuckDB/remove-duplicate-elements-1.duckdb | 1 + .../DuckDB/remove-duplicate-elements-2.duckdb | 1 + .../DuckDB/remove-duplicate-elements-3.duckdb | 6 + .../DuckDB/remove-duplicate-elements-4.duckdb | 1 + .../Rename-a-file/Maxima/rename-a-file.maxima | 5 + Task/Rename-a-file/Pluto/rename-a-file.pluto | 5 + Task/Rename-a-file/R/rename-a-file.r | 4 + Task/Rep-string/DuckDB/rep-string.duckdb | 36 ++ .../DuckDB/repeat-a-string-1.duckdb | 2 + .../DuckDB/repeat-a-string-2.duckdb | 1 + .../Pluto/repeat-a-string.pluto | 1 + Task/Repunit-primes/R/repunit-primes.r | 8 + .../R/retrieve-and-search-chat-history.r | 19 + .../DuckDB/return-multiple-values-1.duckdb | 4 + .../DuckDB/return-multiple-values-2.duckdb | 9 + .../ArkScript/reverse-a-string.ark | 3 + .../DuckDB/reverse-a-string.duckdb | 7 + .../Reverse-a-string/Nom/reverse-a-string.num | 1 + .../Pluto/reverse-a-string.pluto | 10 + .../Reverse-a-string/TAV/reverse-a-string.tav | 3 + .../reverse-words-in-a-string.pas | 32 +- .../Pluto/reverse-words-in-a-string.pluto | 16 + .../PascalABC.NET/roman-numerals-decode-1.pas | 49 +- .../Pluto/roman-numerals-encode.pluto | 3 + .../EasyLang/roots-of-a-function.easy | 7 +- .../Pluto/roots-of-a-quadratic-function.pluto | 44 ++ .../DuckDB/roots-of-unity.duckdb | 11 + .../Roots-of-unity/Pluto/roots-of-unity.pluto | 12 + .../Raku/rosetta-code-count-examples.raku | 2 +- ...rosetta-code-find-unimplemented-tasks.ring | 8 - ...a-code-rank-languages-by-popularity-1.raku | 2 +- Task/Rot-13/Crystal/rot-13.cr | 5 + Task/Rot-13/Lua/rot-13-1.lua | 2 + Task/Rot-13/Lua/rot-13-2.lua | 2 + Task/Rot-13/Pluto/rot-13.pluto | 14 + Task/Rot-13/Rhombus/rot-13.rhombus | 23 + Task/Rot-13/S-BASIC/rot-13.basic | 2 +- .../DuckDB/run-length-encoding-1.duckdb | 23 + .../DuckDB/run-length-encoding-2.duckdb | 1 + .../Pluto/runge-kutta-method.pluto | 30 ++ .../REXX/runge-kutta-method.rexx | 77 ++- .../Python/ruth-aaron-numbers.py | 104 ++++ Task/SEDOLs/Prolog/sedols-1.pro | 40 ++ Task/SEDOLs/Prolog/sedols-2.pro | 5 + Task/SEDOLs/Prolog/sedols-3.pro | 21 + Task/SHA-1/C++/sha-1-2.cpp | 100 ++-- Task/SHA-1/Hare/sha-1.hare | 12 +- Task/SHA-1/Haxe/sha-1.haxe | 2 +- Task/SHA-1/Java/sha-1.java | 114 ++--- Task/SHA-1/REBOL/sha-1-1.rebol | 1 + Task/SHA-1/REBOL/sha-1-2.rebol | 1 + Task/SHA-256/C++/sha-256-1.cpp | 18 +- Task/SHA-256/C++/sha-256-2.cpp | 136 ++--- Task/SHA-256/C/sha-256.c | 14 +- Task/SHA-256/FutureBasic/sha-256.basic | 2 +- Task/SHA-256/Haxe/sha-256.haxe | 2 +- Task/SHA-256/Java/sha-256.java | 158 +++--- Task/SHA-256/Perl/sha-256-2.pl | 192 +++---- Task/SHA-256/REBOL/sha-256.rebol | 1 + Task/SHA-256/Raku/sha-256-1.raku | 48 +- .../DuckDB/search-a-list-of-records-1.duckdb | 5 + .../DuckDB/search-a-list-of-records-2.duckdb | 2 + .../Icon/search-a-list-of-records.icon | 19 + Task/Self-numbers/Pluto/self-numbers.pluto | 83 +++ Task/Semordnilap/ArkScript/semordnilap.ark | 14 + Task/Semordnilap/AutoHotkey/semordnilap.ahk | 18 +- Task/Semordnilap/EchoLisp/semordnilap.l | 14 +- Task/Semordnilap/Eiffel/semordnilap-1.e | 128 ++--- Task/Semordnilap/Eiffel/semordnilap-2.e | 48 +- Task/Semordnilap/Forth/semordnilap.fth | 20 +- Task/Semordnilap/Julia/semordnilap.jl | 2 +- Task/Semordnilap/Ksh/semordnilap.ksh | 74 +-- Task/Semordnilap/Lasso/semordnilap.lasso | 26 +- Task/Semordnilap/Lua/semordnilap.lua | 23 +- Task/Semordnilap/NewLISP/semordnilap.l | 30 +- Task/Semordnilap/Perl/semordnilap.pl | 6 +- .../Phixmonti/semordnilap.phixmonti | 42 +- Task/Semordnilap/Pluto/semordnilap.pluto | 21 + Task/Semordnilap/Prolog/semordnilap.pro | 28 ++ Task/Semordnilap/Python/semordnilap-1.py | 2 +- Task/Semordnilap/R/semordnilap.r | 2 +- Task/Semordnilap/REBOL/semordnilap-1.rebol | 26 + Task/Semordnilap/REBOL/semordnilap-2.rebol | 25 + Task/Semordnilap/SNOBOL4/semordnilap.sno | 34 +- Task/Semordnilap/TAV/semordnilap.tav | 22 + Task/Semordnilap/Tcl/semordnilap.tcl | 8 +- Task/Semordnilap/VBScript/semordnilap.vb | 32 +- ...sequence-of-primes-by-trial-division.agena | 35 ++ ...sequence-of-primes-by-trial-division.pluto | 29 ++ .../sequence-of-primes-by-trial-division.rexx | 8 +- .../REXX/sequence-of-primorial-primes.rexx | 14 +- .../DuckDB/set-consolidation-1.duckdb | 1 + .../DuckDB/set-consolidation-2.duckdb | 17 + .../DuckDB/set-consolidation-3.duckdb | 61 +++ .../Pluto/set-consolidation.pluto | 38 ++ .../Wren/set-consolidation.wren | 2 +- Task/Set/DuckDB/set-1.duckdb | 5 + Task/Set/DuckDB/set-2.duckdb | 1 + Task/Set/DuckDB/set-3.duckdb | 1 + Task/Set/DuckDB/set-4.duckdb | 1 + Task/Set/DuckDB/set-5.duckdb | 1 + Task/Set/DuckDB/set-6.duckdb | 2 + Task/Set/DuckDB/set-7.duckdb | 2 + Task/Set/DuckDB/set-8.duckdb | 2 + Task/Set/DuckDB/set-9.duckdb | 1 + Task/Set/Pluto/set.pluto | 46 ++ .../ArkScript/shell-one-liner.ark | 1 + ... shoelace-formula-for-polygonal-area-1.jl} | 0 .../shoelace-formula-for-polygonal-area-2.jl | 10 + .../R/shoelace-formula-for-polygonal-area.r | 10 + .../ArkScript/short-circuit-evaluation.ark | 17 + .../ArkScript/show-ascii-table.ark | 15 + .../DuckDB/show-the-epoch.duckdb | 1 + .../EasyLang/sierpinski-arrowhead-curve.easy | 5 +- .../EasyLang/sierpinski-pentagon.easy | 7 +- .../FutureBasic/sierpinski-pentagon.basic | 77 +++ .../DuckDB/sieve-of-eratosthenes.duckdb | 20 + .../Odin/sieve-of-eratosthenes.odin | 44 +- .../EasyLang/simple-turtle-graphics.easy | 9 +- .../simple-windowed-application.funcsug | 7 + .../TAV/simple-windowed-application.tav | 23 + .../Julia/simulate-input-keyboard.jl | 85 ++++ .../FuncSug/simulate-input-mouse.funcsug | 16 + Task/Singleton/Rust/singleton.rs | 110 ++++ .../singly-linked-list-element-definition.cr | 7 + ...ingly-linked-list-element-definition.pluto | 7 + .../singly-linked-list-element-insertion.cr | 26 + ...singly-linked-list-element-insertion.pluto | 8 + .../Julia/singly-linked-list-traversal.jl | 9 +- .../Pluto/singly-linked-list-traversal.pluto | 14 + Task/Sleep/ArkScript/sleep.ark | 4 + Task/Sleep/FutureBasic/sleep.basic | 14 + Task/Sleep/Pluto/sleep.pluto | 5 + .../smarandache-prime-digital-sequence.alg | 16 +- .../smarandache-prime-digital-sequence.agena | 90 ++++ .../smarandache-prime-digital-sequence.pluto | 27 + Task/Snake/Liberty-BASIC/snake.basic | 191 +++++++ Task/Sokoban/JavaScript/sokoban.js | 130 +++++ Task/Sokoban/Rust/sokoban.rs | 173 +++++++ .../ALGOL-68/soloways-recurring-rainfall.alg | 2 +- .../AWK/soloways-recurring-rainfall.awk | 24 + .../Agena/soloways-recurring-rainfall.agena | 27 + .../COBOL/soloways-recurring-rainfall.cobol | 22 + .../Crystal/soloways-recurring-rainfall.cr | 20 + .../Pluto/soloways-recurring-rainfall.pluto | 14 + .../R/soloways-recurring-rainfall.r | 22 + .../JavaScript/solve-a-hopido-puzzle.js | 146 ++++++ .../Python/solve-a-numbrix-puzzle-1.py | 218 +++++--- ...rt-an-array-of-composite-structures.duckdb | 6 + .../Pluto/sort-an-integer-array.pluto | 2 + .../sort-an-outline-at-every-level.easy | 2 +- .../sort-numbers-lexicographically-1.duckdb | 7 + .../sort-numbers-lexicographically-2.duckdb | 1 + .../Icon/sort-numbers-lexicographically.icon | 9 + .../Prolog/sort-three-variables.pro | 9 + .../sorting-algorithms-insertion-sort.basic | 62 +++ .../sorting-algorithms-insertion-sort.basic | 36 ++ .../sorting-algorithms-quicksort.ark | 25 + .../sorting-algorithms-sleep-sort.basic | 21 + .../OCaml/sorting-algorithms-sleep-sort.ml | 6 + .../Julia/sorting-algorithms-stooge-sort.jl | 2 +- .../sorting-algorithms-stooge-sort.maxima | 14 + .../R/sorting-algorithms-stooge-sort.r | 20 +- .../Logo/sparkline-in-unicode-1.logo | 42 ++ .../Logo/sparkline-in-unicode-2.logo | 3 + .../YAMLScript/sparkline-in-unicode.ys | 14 + ...cter-string-based-on-change-of-character.r | 7 + .../REXX/square-form-factorization.rexx | 10 +- .../FutureBasic/stack-traces.basic | 14 + Task/Stack/OoRexx/stack.rexx | 3 + Task/Stack/Pluto/stack.pluto | 4 + Task/Stack/REXX/stack-1.rexx | 7 - Task/Stack/REXX/{stack-2.rexx => stack.rexx} | 4 +- Task/Stack/TAV/stack-1.tav | 6 + Task/Stack/TAV/stack-2.tav | 9 + .../DuckDB/statistics-basic.duckdb | 12 + .../Maxima/statistics-basic.maxima | 10 + .../Prolog/stem-and-leaf-plot.pro | 37 ++ .../Zig/stern-brocot-sequence.zig | 81 +++ .../EasyLang/straddling-checkerboard.easy | 73 +++ .../String-append/ArkScript/string-append.ark | 2 + .../DuckDB/string-append-1.duckdb | 8 + .../DuckDB/string-append-2.duckdb | 2 + Task/String-case/ArkScript/string-case.ark | 5 + Task/String-case/DuckDB/string-case.duckdb | 1 + .../DuckDB/string-comparison.duckdb | 10 + .../ArkScript/string-concatenation.ark | 6 + .../Prolog/string-concatenation.pro | 9 + .../Tcl/string-concatenation-3.tcl | 6 + .../string-interpolation-included-.ark | 4 + .../Crystal/string-interpolation-included-.cr | 6 + .../string-interpolation-included-.duckdb | 1 + .../string-interpolation-included-.pas | 2 +- .../string-interpolation-included-.pluto | 3 + .../R/string-interpolation-included-.r | 2 + .../String-length/ArkScript/string-length.ark | 1 + .../String-length/DuckDB/string-length.duckdb | 2 + .../FutureBasic/string-length.basic | 17 + Task/String-length/Pluto/string-length.pluto | 12 + Task/String-length/TAV/string-length.tav | 6 + Task/String-length/Wren/string-length-1.wren | 3 +- Task/String-length/Wren/string-length-2.wren | 3 +- Task/String-length/Wren/string-length-3.wren | 3 +- .../ArkScript/string-matching.ark | 6 + .../DuckDB/string-matching.duckdb | 17 + Task/String-matching/R/string-matching.r | 14 + .../ArkScript/string-prepend.ark | 3 + .../DuckDB/string-prepend-1.duckdb | 1 + .../DuckDB/string-prepend-2.duckdb | 1 + .../DuckDB/string-prepend-3.duckdb | 2 + ...p-a-set-of-characters-from-a-string.duckdb | 10 + .../strip-comments-from-a-string.duckdb | 16 + ...d-extended-characters-from-a-string.duckdb | 29 ++ ...itespace-from-a-string-top-and-tail.duckdb | 27 + .../Rust/substitution-cipher.rs | 25 + .../Maxima/substring-top-and-tail.maxima | 5 + .../R/substring-top-and-tail.r | 4 + Task/Substring/DuckDB/substring.duckdb | 20 + Task/Sudoku/DuckDB/sudoku.duckdb | 40 ++ Task/Sudoku/Zig/sudoku.zig | 104 ++++ .../ArkScript/sum-and-product-of-an-array.ark | 9 + .../DuckDB/sum-and-product-of-an-array.duckdb | 4 + .../Haskell/sum-and-product-of-an-array-2.hs | 12 +- .../REXX/sum-and-product-of-an-array.rexx | 25 +- .../ArkScript/sum-digits-of-an-integer.ark | 27 + .../DuckDB/sum-digits-of-an-integer.duckdb | 24 + ...ger.pas => sum-digits-of-an-integer-1.pas} | 0 .../sum-digits-of-an-integer-2.pas | 8 + .../Pluto/sum-digits-of-an-integer.pluto | 10 + .../DuckDB/sum-multiples-of-3-and-5.duckdb | 9 + .../ArkScript/sum-of-a-series.ark | 9 + .../DuckDB/sum-of-a-series-1.duckdb | 1 + .../DuckDB/sum-of-a-series-2.duckdb | 4 + .../DuckDB/sum-of-a-series-3.duckdb | 7 + .../DuckDB/sum-of-a-series-4.duckdb | 5 + .../FutureBasic/sum-of-a-series.basic | 12 + .../Sum-of-a-series/Tcl/sum-of-a-series-1.tcl | 5 +- ...ements-below-main-diagonal-of-matrix.agena | 28 ++ ...ments-below-main-diagonal-of-matrix.fennel | 27 + ...f-elements-below-main-diagonal-of-matrix.f | 27 + ...elements-below-main-diagonal-of-matrix.lua | 27 + ...ements-below-main-diagonal-of-matrix.pluto | 27 + .../ArkScript/sum-of-squares.ark | 16 + .../DuckDB/sum-of-squares-1.duckdb | 1 + .../DuckDB/sum-of-squares-2.duckdb | 5 + .../DuckDB/sum-of-squares-3.duckdb | 3 + .../DuckDB/sum-of-squares-4.duckdb | 8 + Task/Sum-to-100/EasyLang/sum-to-100.easy | 2 +- Task/Sum-to-100/FutureBasic/sum-to-100.basic | 118 +++++ Task/Superellipse/EasyLang/superellipse.easy | 5 +- Task/Superellipse/Maxima/superellipse.maxima | 7 + Task/Superellipse/Python/superellipse.py | 1 - .../superpermutation-minimisation.js | 61 +++ .../DuckDB/symmetric-difference.duckdb | 12 + .../Pluto/symmetric-difference.pluto | 10 + Task/System-time/Pluto/system-time.pluto | 1 + Task/System-time/REBOL/system-time.rebol | 3 +- .../table-creation-postal-addresses-1.duckdb | 7 + .../table-creation-postal-addresses-2.duckdb | 1 + .../table-creation-postal-addresses-3.duckdb | 7 + .../table-creation-postal-addresses-4.duckdb | 1 + Task/Tarjan/JavaScript/tarjan.js | 83 +++ Task/Tarjan/Zig/tarjan.zig | 200 ++++++++ .../FutureBasic/tau-function.basic | 39 ++ Task/Tau-function/Pluto/tau-function.pluto | 11 + Task/Tau-number/FutureBasic/tau-number.basic | 46 ++ Task/Tau-number/Pluto/tau-number.pluto | 13 + .../terminal-control-clear-the-screen.pluto | 3 + .../terminal-control-coloured-text.pluto | 16 + .../terminal-control-cursor-movement.pluto | 26 + .../terminal-control-cursor-positioning.pluto | 5 + .../Pluto/terminal-control-dimensions.pluto | 6 + ...ontrol-display-an-extended-character.pluto | 1 + .../terminal-control-hiding-the-cursor.pluto | 6 + .../terminal-control-inverse-video.pluto | 6 + .../terminal-control-preserve-screen.pluto | 10 + ...al-control-ringing-the-terminal-bell.pluto | 1 + ...minal-control-ringing-the-terminal-bell.ys | 2 + .../terminal-control-unicode-output.pluto | 10 + .../Test-integerness/Ada/test-integerness.ada | 49 ++ .../DuckDB/test-integerness-1.duckdb | 3 + .../DuckDB/test-integerness-2.duckdb | 16 + .../Pluto/test-integerness.pluto | 37 ++ .../DuckDB/text-processing-2-1.duckdb | 2 + .../DuckDB/text-processing-2-2.duckdb | 1 + .../DuckDB/text-processing-2-3.duckdb | 7 + .../DuckDB/text-processing-2-4.duckdb | 9 + .../DuckDB/text-processing-2-5.duckdb | 9 + .../DuckDB/text-processing-2-6.duckdb | 6 + Task/The-Name-Game/R/the-name-game.r | 20 + .../AutoLISP/the-twelve-days-of-christmas.l | 30 ++ Task/Thue-Morse/DuckDB/thue-morse-1.duckdb | 16 + Task/Thue-Morse/DuckDB/thue-morse-2.duckdb | 16 + Task/Thue-Morse/Prolog/thue-morse.pro | 15 + Task/Tic-tac-toe/TAV/tic-tac-toe.tav | 133 +++++ .../Agena/time-a-function.agena | 14 + .../DuckDB/time-a-function.duckdb | 21 + .../Fennel/time-a-function.fennel | 22 + Task/Time-a-function/Lua/time-a-function.lua | 2 +- .../Pluto/time-a-function.pluto | 14 + .../REXX/time-a-function-2.rexx | 43 +- .../Icon/tokenize-a-string-with-escaping.icon | 21 + .../DuckDB/tokenize-a-string.duckdb | 4 + .../Refal/tokenize-a-string.refal | 15 + .../SETL/tokenize-a-string.setl | 18 + .../TAV/tokenize-a-string.tav | 8 + .../Dart/tonelli-shanks-algorithm.dart | 122 +++++ .../Mathematica/tonelli-shanks-algorithm.math | 67 +++ .../PARI-GP/tonelli-shanks-algorithm.parigp | 123 +++++ .../R/tonelli-shanks-algorithm.r | 98 ++++ .../Scala/tonelli-shanks-algorithm.scala | 106 ++++ .../DuckDB/top-rank-per-group-1.duckdb | 14 + .../DuckDB/top-rank-per-group-2.duckdb | 6 + .../DuckDB/top-rank-per-group-3.duckdb | 3 + .../Maxima/topic-variable.maxima | 9 + Task/Topswops/Prolog/topswops.pro | 23 + Task/Total-circles-area/00-TASK.txt | 1 + .../Ada/total-circles-area.ada | 109 ++++ .../Pluto/total-circles-area-1.pluto | 51 ++ .../Pluto/total-circles-area-2.pluto | 72 +++ .../Agena/totient-function.agena | 46 ++ .../Fortran/totient-function.f | 54 ++ .../Lua/totient-function-2.lua | 23 +- .../Pluto/totient-function.pluto | 33 ++ .../Maxima/towers-of-hanoi.maxima | 8 + .../Pluto/towers-of-hanoi.pluto | 20 + Task/Towers-of-Hanoi/Red/towers-of-hanoi.red | 9 + .../Pluto/trabb-pardo-knuth-algorithm.pluto | 22 + .../Prolog/trabb-pardo-knuth-algorithm.pro | 26 + .../QB64/trabb-pardo-knuth-algorithm.qb64 | 26 + ...nglish-text-using-the-greek-alphabet.basic | 118 +++++ .../Rust/tree-datastructures.rs | 125 +++++ .../Zig/tree-datastructures.zig | 182 +++++++ .../Icon/tree-from-nesting-levels.icon | 46 ++ .../Adina/tree-traversal-1.adina | 63 +++ .../Adina/tree-traversal-2.adina | 68 +++ .../DuckDB/trigonometric-functions.duckdb | 22 + .../REXX/trigonometric-functions.rexx | 7 +- Task/Twos-complement/Ada/twos-complement.ada | 10 + .../Twos-complement/Fortran/twos-complement.f | 57 +++ Task/UPC/Pluto/upc.pluto | 110 ++++ Task/UPC/Rust/upc.rs | 161 ++++++ Task/UPC/Scala/upc.scala | 129 +++++ Task/URL-decoding/DuckDB/url-decoding.duckdb | 27 + .../DuckDB/utf-8-encode-and-decode.duckdb | 12 + .../YAMLScript/undefined-values.ys | 9 + Task/Unicode-strings/00-TASK.txt | 2 +- .../EasyLang/unicode-strings.easy | 14 + .../Pluto/unicode-strings.pluto | 26 + Task/Unix-ls/DuckDB/unix-ls.duckdb | 1 + .../Agena/unprimeable-numbers.agena | 101 ++++ .../Pluto/unprimeable-numbers.pluto | 97 ++++ .../REXX/unprimeable-numbers.rexx | 6 +- ...e-another-language-to-call-a-function-1.jl | 21 + ...e-another-language-to-call-a-function-2.jl | 17 + ...e-another-language-to-call-a-function-3.jl | 33 ++ ...e-another-language-to-call-a-function-4.jl | 19 + ...-another-language-to-call-a-function-1.lua | 24 + ...-another-language-to-call-a-function-2.lua | 205 ++++++++ ...-another-language-to-call-a-function-3.lua | 4 + .../FuncSug/user-input-graphical.funcsug | 10 + .../ArkScript/user-input-text.ark | 5 + .../user-input-text.basic | 4 + .../Pluto/user-input-text.pluto | 4 + .../Agena/van-eck-sequence.agena | 26 + .../Pluto/van-eck-sequence.pluto | 26 + .../Agena/van-der-corput-sequence.agena | 32 ++ .../Pluto/van-der-corput-sequence.pluto | 35 ++ .../YAMLScript/van-der-corput-sequence.ys | 18 + .../DuckDB/variable-size-get.duckdb | 50 ++ .../DuckDB/variable-size-set.duckdb | 34 ++ Task/Variables/Bc/variables.bc | 15 + .../Pluto/variadic-function.pluto | 10 + .../DuckDB/vector-products.duckdb | 17 + .../Pluto/vector-products.pluto | 19 + .../Vector-products/REXX/vector-products.rexx | 27 +- Task/Vector/Ada/vector.ada | 31 ++ Task/Vector/Pluto/vector.pluto | 31 ++ Task/Vector/REXX/vector.rexx | 31 +- .../Zig/verhoeff-algorithm.zig | 112 +++++ ...tribution-uniformity-chi-squared-test.rexx | 10 +- .../verify-distribution-uniformity-naive.rexx | 11 +- .../Zig/vigen-re-cipher-cryptanalysis.zig | 170 +++++++ .../C-sharp/vogels-approximation-method.cs | 117 +++++ .../vogels-approximation-method.math | 123 +++++ .../Zig/vogels-approximation-method.zig | 212 ++++++++ .../Agena/wagstaff-primes.agena | 36 ++ Task/Wagstaff-primes/Lua/wagstaff-primes.lua | 38 ++ .../Pluto/wagstaff-primes.pluto | 40 ++ .../Wagstaff-primes/Ring/wagstaff-primes.ring | 12 + Task/War-card-game/Rust/war-card-game.rs | 110 ++++ Task/War-card-game/Zig/war-card-game.zig | 155 ++++++ Task/Web-scraping/REBOL/web-scraping.rebol | 2 +- .../Agena/wieferich-primes.agena | 37 ++ .../Common-Lisp/wieferich-primes.lisp | 35 ++ .../Wieferich-primes/Lua/wieferich-primes.lua | 48 ++ .../Pluto/wieferich-primes.pluto | 24 + Task/Wieferich-primes/R/wieferich-primes.r | 10 + Task/Window-creation/TAV/window-creation.tav | 9 + Task/Wireworld/Prolog/wireworld.pro | 69 +++ Task/Word-frequency/TAV/word-frequency.tav | 34 ++ Task/Word-wheel/ALGOL-68/word-wheel.alg | 36 ++ Task/Word-wrap/FutureBasic/word-wrap.basic | 59 +++ .../ArkScript/write-entire-file.ark | 1 + .../Frink/write-entire-file.frink | 4 +- .../Odin/write-entire-file.odin | 15 +- Task/Write-entire-file/R/write-entire-file.r | 1 + .../YAMLScript/xiaolin-wus-line-algorithm.ys | 52 ++ Task/Y-combinator/Pluto/y-combinator.pluto | 14 + .../Agena/yellowstone-sequence.agena | 27 + .../Fennel/yellowstone-sequence.fennel | 45 ++ .../FutureBasic/yellowstone-sequence.basic | 33 ++ .../Pluto/yellowstone-sequence.pluto | 32 ++ .../REXX/yellowstone-sequence.rexx | 9 +- .../YAMLScript/yellowstone-sequence.ys | 24 + .../FutureBasic/zebra-puzzle.basic | 266 ++++++++++ Task/Zebra-puzzle/J/zebra-puzzle-1.j | 2 +- Task/Zebra-puzzle/Pluto/zebra-puzzle.pluto | 84 ++++ .../DuckDB/zero-to-the-zero-power.duckdb | 1 + .../Pluto/zero-to-the-zero-power.pluto | 1 + .../Prolog/zero-to-the-zero-power.pro | 1 + .../DuckDB/zig-zag-matrix.duckdb | 40 ++ .../YAMLScript/zig-zag-matrix.ys | 34 ++ 3073 files changed, 55820 insertions(+), 4408 deletions(-) create mode 100644 Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt create mode 100644 Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml delete mode 120000 Lang/ALGOL-60/Factorial create mode 120000 Lang/ALGOL-68/Date-manipulation create mode 120000 Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series delete mode 120000 Lang/ALGOL-68/Factorial create mode 120000 Lang/ALGOL-68/Knapsack-problem-Continuous create mode 120000 Lang/ALGOL-68/Word-wheel delete mode 120000 Lang/ALGOL-W/Factorial create mode 120000 Lang/ALGOL-W/Knapsack-problem-Continuous create mode 120000 Lang/ANSI-BASIC/AKS-test-for-primes create mode 120000 Lang/ANSI-BASIC/Old-Russian-measure-of-length create mode 120000 Lang/APL/Monte-Carlo-methods create mode 120000 Lang/ASIC/Old-Russian-measure-of-length delete mode 120000 Lang/AWK/100-doors create mode 120000 Lang/AWK/Factorial-primes create mode 120000 Lang/AWK/Soloways-recurring-rainfall create mode 120000 Lang/Ada/Almkvist-Giullera-formula-for-pi create mode 120000 Lang/Ada/Biorhythms create mode 120000 Lang/Ada/Boyer-Moore-string-search create mode 120000 Lang/Ada/Calkin-Wilf-sequence create mode 120000 Lang/Ada/Camel-case-and-snake-case create mode 120000 Lang/Ada/Canonicalize-CIDR create mode 120000 Lang/Ada/Deepcopy create mode 120000 Lang/Ada/Factorions create mode 120000 Lang/Ada/Find-duplicate-files create mode 120000 Lang/Ada/Harmonic-series create mode 120000 Lang/Ada/Knapsack-problem-Bounded create mode 120000 Lang/Ada/Levenshtein-distance-Alignment create mode 120000 Lang/Ada/Long-literals-with-continuations create mode 120000 Lang/Ada/Longest-increasing-subsequence create mode 120000 Lang/Ada/Machine-code create mode 120000 Lang/Ada/Minimal-steps-down-to-1 create mode 120000 Lang/Ada/Naming-conventions create mode 120000 Lang/Ada/Read-a-file-character-by-character-UTF8 create mode 120000 Lang/Ada/Test-integerness create mode 120000 Lang/Ada/Total-circles-area create mode 120000 Lang/Ada/Twos-complement create mode 120000 Lang/Ada/Vector create mode 100644 Lang/Adina/00-LANG.txt create mode 100644 Lang/Adina/00-META.yaml create mode 120000 Lang/Adina/100-doors create mode 120000 Lang/Adina/Even-or-odd create mode 120000 Lang/Adina/Hello-world-Text create mode 120000 Lang/Adina/Loops-For create mode 120000 Lang/Adina/Tree-traversal create mode 120000 Lang/Agena/AKS-test-for-primes create mode 120000 Lang/Agena/Abundant-deficient-and-perfect-number-classifications create mode 120000 Lang/Agena/Abundant-odd-numbers create mode 120000 Lang/Agena/Arbitrary-precision-integers-included- create mode 120000 Lang/Agena/Attractive-numbers create mode 120000 Lang/Agena/Disarium-numbers create mode 120000 Lang/Agena/Factorial create mode 120000 Lang/Agena/Factorial-primes create mode 120000 Lang/Agena/Giuga-numbers create mode 120000 Lang/Agena/Goldbachs-comet create mode 120000 Lang/Agena/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/Agena/Humble-numbers create mode 120000 Lang/Agena/JSON create mode 120000 Lang/Agena/Jacobsthal-numbers create mode 120000 Lang/Agena/Jewels-and-stones create mode 120000 Lang/Agena/Kaprekar-numbers create mode 120000 Lang/Agena/Mian-Chowla-sequence create mode 120000 Lang/Agena/Pernicious-numbers create mode 120000 Lang/Agena/Pisano-period create mode 120000 Lang/Agena/Primality-by-trial-division create mode 120000 Lang/Agena/Sequence-of-primes-by-trial-division create mode 120000 Lang/Agena/Smarandache-prime-digital-sequence create mode 120000 Lang/Agena/Soloways-recurring-rainfall create mode 120000 Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/Agena/Time-a-function create mode 120000 Lang/Agena/Totient-function create mode 120000 Lang/Agena/Unprimeable-numbers create mode 120000 Lang/Agena/Van-Eck-sequence create mode 120000 Lang/Agena/Van-der-Corput-sequence create mode 120000 Lang/Agena/Wagstaff-primes create mode 120000 Lang/Agena/Wieferich-primes create mode 120000 Lang/Agena/Yellowstone-sequence create mode 100644 Lang/Apple/00-LANG.txt create mode 100644 Lang/Apple/00-META.yaml create mode 120000 Lang/Apple/Averages-Arithmetic-mean create mode 120000 Lang/Apple/Averages-Pythagorean-means create mode 120000 Lang/Apple/Catamorphism create mode 120000 Lang/Apple/Dot-product create mode 120000 Lang/Apple/Factorial create mode 120000 Lang/Apple/Factors-of-an-integer create mode 120000 Lang/Apple/Filter create mode 120000 Lang/Apple/ISBN13-check-digit create mode 100644 Lang/Aria/00-LANG.txt create mode 100644 Lang/Aria/00-META.yaml create mode 120000 Lang/Aria/99-bottles-of-beer create mode 120000 Lang/Aria/Hello-world-Text create mode 100644 Lang/ArkScript/00-LANG.txt create mode 100644 Lang/ArkScript/00-META.yaml create mode 120000 Lang/ArkScript/100-doors create mode 120000 Lang/ArkScript/99-bottles-of-beer create mode 120000 Lang/ArkScript/A+B create mode 120000 Lang/ArkScript/Abbreviations-easy create mode 120000 Lang/ArkScript/Ackermann-function create mode 120000 Lang/ArkScript/Apply-a-callback-to-an-array create mode 120000 Lang/ArkScript/Arithmetic-Complex create mode 120000 Lang/ArkScript/Arithmetic-Integer create mode 120000 Lang/ArkScript/Array-concatenation create mode 120000 Lang/ArkScript/Array-length create mode 120000 Lang/ArkScript/Ascending-primes create mode 120000 Lang/ArkScript/Associative-array-Creation create mode 120000 Lang/ArkScript/Associative-array-Iteration create mode 120000 Lang/ArkScript/Balanced-brackets create mode 120000 Lang/ArkScript/Boolean-values create mode 120000 Lang/ArkScript/Calculating-the-value-of-e create mode 120000 Lang/ArkScript/Call-a-function create mode 120000 Lang/ArkScript/Call-an-object-method create mode 120000 Lang/ArkScript/Catamorphism create mode 120000 Lang/ArkScript/Check-that-file-exists create mode 120000 Lang/ArkScript/Closures-Value-capture create mode 120000 Lang/ArkScript/Comments create mode 120000 Lang/ArkScript/Compound-data-type create mode 120000 Lang/ArkScript/Concurrent-computing create mode 120000 Lang/ArkScript/Conditional-structures create mode 120000 Lang/ArkScript/Conways-Game-of-Life create mode 120000 Lang/ArkScript/Copy-a-string create mode 120000 Lang/ArkScript/Currying create mode 120000 Lang/ArkScript/Delete-a-file create mode 120000 Lang/ArkScript/Empty-directory create mode 120000 Lang/ArkScript/Empty-program create mode 120000 Lang/ArkScript/Empty-string create mode 120000 Lang/ArkScript/Enforced-immutability create mode 120000 Lang/ArkScript/Even-or-odd create mode 120000 Lang/ArkScript/Extend-your-language create mode 120000 Lang/ArkScript/Fibonacci-sequence create mode 120000 Lang/ArkScript/FizzBuzz create mode 120000 Lang/ArkScript/Flatten-a-list create mode 120000 Lang/ArkScript/Function-definition create mode 120000 Lang/ArkScript/Hello-world-Line-printer create mode 120000 Lang/ArkScript/Hello-world-Newline-omission create mode 120000 Lang/ArkScript/Hello-world-Text create mode 120000 Lang/ArkScript/Infinity create mode 120000 Lang/ArkScript/Integer-sequence create mode 120000 Lang/ArkScript/Literals-Floating-point create mode 120000 Lang/ArkScript/Literals-Integer create mode 120000 Lang/ArkScript/Literals-String create mode 120000 Lang/ArkScript/Logical-operations create mode 120000 Lang/ArkScript/Munchausen-numbers create mode 120000 Lang/ArkScript/N-queens-problem create mode 120000 Lang/ArkScript/Null-object create mode 120000 Lang/ArkScript/Program-termination create mode 120000 Lang/ArkScript/Read-entire-file create mode 120000 Lang/ArkScript/Reverse-a-string create mode 120000 Lang/ArkScript/Semordnilap create mode 120000 Lang/ArkScript/Shell-one-liner create mode 120000 Lang/ArkScript/Short-circuit-evaluation create mode 120000 Lang/ArkScript/Show-ASCII-table create mode 120000 Lang/ArkScript/Sleep create mode 120000 Lang/ArkScript/Sorting-algorithms-Quicksort create mode 120000 Lang/ArkScript/String-append create mode 120000 Lang/ArkScript/String-case create mode 120000 Lang/ArkScript/String-concatenation create mode 120000 Lang/ArkScript/String-interpolation-included- create mode 120000 Lang/ArkScript/String-length create mode 120000 Lang/ArkScript/String-matching create mode 120000 Lang/ArkScript/String-prepend create mode 120000 Lang/ArkScript/Sum-and-product-of-an-array create mode 120000 Lang/ArkScript/Sum-digits-of-an-integer create mode 120000 Lang/ArkScript/Sum-of-a-series create mode 120000 Lang/ArkScript/Sum-of-squares create mode 120000 Lang/ArkScript/User-input-Text create mode 120000 Lang/ArkScript/Write-entire-file create mode 120000 Lang/AutoLISP/100-doors create mode 120000 Lang/AutoLISP/Babbage-problem create mode 120000 Lang/AutoLISP/Balanced-brackets create mode 120000 Lang/AutoLISP/Entropy create mode 120000 Lang/AutoLISP/Entropy-Narcissist create mode 120000 Lang/AutoLISP/Largest-proper-divisor-of-n create mode 120000 Lang/AutoLISP/The-Twelve-Days-of-Christmas create mode 120000 Lang/BBC-BASIC/Arbitrary-precision-integers-included- create mode 120000 Lang/BBC-BASIC/Multi-dimensional-array create mode 120000 Lang/Ballerina/Comments create mode 120000 Lang/Bc/Anti-primes create mode 120000 Lang/Bc/Arithmetic-derivative create mode 120000 Lang/Bc/Department-numbers create mode 120000 Lang/Bc/Fairshare-between-two-and-more create mode 120000 Lang/Bc/Variables create mode 120000 Lang/C-sharp/Camel-case-and-snake-case create mode 120000 Lang/C-sharp/Cistercian-numerals create mode 120000 Lang/C-sharp/M-bius-function create mode 120000 Lang/C-sharp/Vogels-approximation-method create mode 120000 Lang/CBASIC/Factorial create mode 100644 Lang/CJam/00-LANG.txt create mode 100644 Lang/CJam/00-META.yaml create mode 120000 Lang/COBOL/Soloways-recurring-rainfall create mode 100644 Lang/Calcscript/00-LANG.txt create mode 100644 Lang/Calcscript/00-META.yaml create mode 120000 Lang/Common-Lisp/Wieferich-primes delete mode 120000 Lang/Component-Pascal/100-doors create mode 100644 Lang/Convex/00-LANG.txt create mode 100644 Lang/Convex/00-META.yaml create mode 120000 Lang/Crystal/Department-numbers create mode 120000 Lang/Crystal/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Crystal/Rot-13 create mode 120000 Lang/Crystal/Singly-linked-list-Element-definition create mode 120000 Lang/Crystal/Singly-linked-list-Element-insertion create mode 120000 Lang/Crystal/Soloways-recurring-rainfall create mode 120000 Lang/Crystal/String-interpolation-included- create mode 120000 Lang/Dart/AVL-tree create mode 120000 Lang/Dart/Boyer-Moore-string-search create mode 120000 Lang/Dart/Break-OO-privacy create mode 120000 Lang/Dart/Continued-fraction create mode 120000 Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/Dart/Dijkstras-algorithm create mode 120000 Lang/Dart/Floyd-Warshall-algorithm create mode 120000 Lang/Dart/Parse-an-IP-Address create mode 120000 Lang/Dart/Tonelli-Shanks-algorithm create mode 120000 Lang/Draco/Anti-primes create mode 100644 Lang/DuckDB/00-LANG.txt create mode 100644 Lang/DuckDB/00-META.yaml create mode 120000 Lang/DuckDB/100-doors create mode 120000 Lang/DuckDB/99-bottles-of-beer create mode 120000 Lang/DuckDB/A+B create mode 120000 Lang/DuckDB/ABC-problem create mode 120000 Lang/DuckDB/Anagrams create mode 120000 Lang/DuckDB/Anonymous-recursion create mode 120000 Lang/DuckDB/Arithmetic-Complex create mode 120000 Lang/DuckDB/Arithmetic-Integer create mode 120000 Lang/DuckDB/Arithmetic-geometric-mean create mode 120000 Lang/DuckDB/Arithmetic-numbers create mode 120000 Lang/DuckDB/Array-concatenation create mode 120000 Lang/DuckDB/Array-length create mode 120000 Lang/DuckDB/Arrays create mode 120000 Lang/DuckDB/Associative-array-Creation create mode 120000 Lang/DuckDB/Associative-array-Iteration create mode 120000 Lang/DuckDB/Associative-array-Merging create mode 120000 Lang/DuckDB/Averages-Arithmetic-mean create mode 120000 Lang/DuckDB/Averages-Mean-angle create mode 120000 Lang/DuckDB/Averages-Mean-time-of-day create mode 120000 Lang/DuckDB/Averages-Mode create mode 120000 Lang/DuckDB/Averages-Pythagorean-means create mode 120000 Lang/DuckDB/Babbage-problem create mode 120000 Lang/DuckDB/Benfords-law create mode 120000 Lang/DuckDB/Bin-given-limits create mode 120000 Lang/DuckDB/Binary-digits create mode 120000 Lang/DuckDB/Bioinformatics-base-count create mode 120000 Lang/DuckDB/Bitwise-IO create mode 120000 Lang/DuckDB/Bitwise-operations create mode 120000 Lang/DuckDB/CSV-data-manipulation create mode 120000 Lang/DuckDB/Call-a-function create mode 120000 Lang/DuckDB/Cartesian-product-of-two-or-more-lists create mode 120000 Lang/DuckDB/Case-sensitivity-of-identifiers create mode 120000 Lang/DuckDB/Catalan-numbers create mode 120000 Lang/DuckDB/Catalan-numbers-Pascals-triangle create mode 120000 Lang/DuckDB/Check-that-file-exists create mode 120000 Lang/DuckDB/Collections create mode 120000 Lang/DuckDB/Combinations create mode 120000 Lang/DuckDB/Combinations-with-repetitions create mode 120000 Lang/DuckDB/Compare-a-list-of-strings create mode 120000 Lang/DuckDB/Compare-length-of-two-strings create mode 120000 Lang/DuckDB/Compound-data-type create mode 120000 Lang/DuckDB/Conditional-structures create mode 120000 Lang/DuckDB/Convert-seconds-to-compound-duration create mode 120000 Lang/DuckDB/Copy-a-string create mode 120000 Lang/DuckDB/Count-occurrences-of-a-substring create mode 120000 Lang/DuckDB/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/DuckDB/Cumulative-standard-deviation create mode 120000 Lang/DuckDB/Currency create mode 120000 Lang/DuckDB/Day-of-the-week create mode 120000 Lang/DuckDB/Define-a-primitive-data-type create mode 120000 Lang/DuckDB/Detect-division-by-zero create mode 120000 Lang/DuckDB/Determinant-and-permanent create mode 120000 Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters create mode 120000 Lang/DuckDB/Determine-if-a-string-has-all-unique-characters create mode 120000 Lang/DuckDB/Determine-if-a-string-is-collapsible create mode 120000 Lang/DuckDB/Determine-if-a-string-is-numeric create mode 120000 Lang/DuckDB/Determine-if-a-string-is-squeezable create mode 120000 Lang/DuckDB/Determine-sentence-type create mode 120000 Lang/DuckDB/Digital-root create mode 120000 Lang/DuckDB/Diversity-prediction-theorem create mode 120000 Lang/DuckDB/Documentation create mode 120000 Lang/DuckDB/Dot-product create mode 120000 Lang/DuckDB/Dynamic-variable-names create mode 120000 Lang/DuckDB/Element-wise-operations create mode 120000 Lang/DuckDB/Empty-string create mode 120000 Lang/DuckDB/Entropy create mode 120000 Lang/DuckDB/Enumerations create mode 120000 Lang/DuckDB/Equilibrium-index create mode 120000 Lang/DuckDB/Euler-method create mode 120000 Lang/DuckDB/Eulers-constant-0.5772... create mode 120000 Lang/DuckDB/Eulers-identity create mode 120000 Lang/DuckDB/Evaluate-binomial-coefficients create mode 120000 Lang/DuckDB/Even-or-odd create mode 120000 Lang/DuckDB/Exponentiation-order create mode 120000 Lang/DuckDB/Extreme-floating-point-values create mode 120000 Lang/DuckDB/Factorial create mode 120000 Lang/DuckDB/Factors-of-an-integer create mode 120000 Lang/DuckDB/Fairshare-between-two-and-more create mode 120000 Lang/DuckDB/Feigenbaum-constant-calculation create mode 120000 Lang/DuckDB/Fibonacci-sequence create mode 120000 Lang/DuckDB/File-input-output create mode 120000 Lang/DuckDB/Filter create mode 120000 Lang/DuckDB/Find-limit-of-recursion create mode 120000 Lang/DuckDB/Find-the-last-Sunday-of-each-month create mode 120000 Lang/DuckDB/Five-weekends create mode 120000 Lang/DuckDB/Fixed-length-records create mode 120000 Lang/DuckDB/Flatten-a-list create mode 120000 Lang/DuckDB/Formatted-numeric-output create mode 120000 Lang/DuckDB/Forward-difference create mode 120000 Lang/DuckDB/Function-definition create mode 120000 Lang/DuckDB/Gamma-function create mode 120000 Lang/DuckDB/Gapful-numbers create mode 120000 Lang/DuckDB/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/DuckDB/Generic-swap create mode 120000 Lang/DuckDB/Golden-ratio-Convergence create mode 120000 Lang/DuckDB/Gotchas create mode 120000 Lang/DuckDB/Greatest-common-divisor create mode 120000 Lang/DuckDB/Greatest-element-of-a-list create mode 120000 Lang/DuckDB/Greatest-subsequential-sum create mode 120000 Lang/DuckDB/HTTP create mode 120000 Lang/DuckDB/HTTPS create mode 120000 Lang/DuckDB/HTTPS-Authenticated create mode 120000 Lang/DuckDB/Hailstone-sequence create mode 120000 Lang/DuckDB/Harmonic-series create mode 120000 Lang/DuckDB/Hash-from-two-arrays create mode 120000 Lang/DuckDB/Hash-join create mode 120000 Lang/DuckDB/Haversine-formula create mode 120000 Lang/DuckDB/Hello-world-Text create mode 120000 Lang/DuckDB/Here-document create mode 120000 Lang/DuckDB/ISBN13-check-digit create mode 120000 Lang/DuckDB/Identity-matrix create mode 120000 Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols create mode 120000 Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters create mode 120000 Lang/DuckDB/Increment-a-numerical-string create mode 120000 Lang/DuckDB/Infinity create mode 120000 Lang/DuckDB/Integer-comparison create mode 120000 Lang/DuckDB/Introspection create mode 120000 Lang/DuckDB/Inverted-index create mode 120000 Lang/DuckDB/Inverted-syntax create mode 120000 Lang/DuckDB/JSON create mode 120000 Lang/DuckDB/Jaro-similarity create mode 120000 Lang/DuckDB/Knuth-shuffle create mode 120000 Lang/DuckDB/Largest-int-from-concatenated-ints create mode 120000 Lang/DuckDB/Last-Friday-of-each-month create mode 120000 Lang/DuckDB/Leap-year create mode 120000 Lang/DuckDB/Left-factorials create mode 120000 Lang/DuckDB/Leonardo-numbers create mode 120000 Lang/DuckDB/Letter-frequency create mode 120000 Lang/DuckDB/Levenshtein-distance create mode 120000 Lang/DuckDB/List-comprehensions create mode 120000 Lang/DuckDB/Literals-Integer create mode 120000 Lang/DuckDB/Logical-operations create mode 120000 Lang/DuckDB/Longest-increasing-subsequence create mode 120000 Lang/DuckDB/Loops-Break create mode 120000 Lang/DuckDB/Loops-Do-while create mode 120000 Lang/DuckDB/Loops-Downward-for create mode 120000 Lang/DuckDB/Loops-For create mode 120000 Lang/DuckDB/Loops-For-with-a-specified-step create mode 120000 Lang/DuckDB/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/DuckDB/Loops-N-plus-one-half create mode 120000 Lang/DuckDB/Loops-Nested create mode 120000 Lang/DuckDB/Loops-While create mode 120000 Lang/DuckDB/Loops-With-multiple-ranges create mode 120000 Lang/DuckDB/Luhn-test-of-credit-card-numbers create mode 120000 Lang/DuckDB/MD5 create mode 120000 Lang/DuckDB/Map-range create mode 120000 Lang/DuckDB/Matrix-multiplication create mode 120000 Lang/DuckDB/Matrix-transposition create mode 120000 Lang/DuckDB/Merge-and-aggregate-datasets create mode 120000 Lang/DuckDB/Metallic-ratios create mode 120000 Lang/DuckDB/Middle-three-digits create mode 120000 Lang/DuckDB/Monte-Carlo-methods create mode 120000 Lang/DuckDB/Nested-function create mode 120000 Lang/DuckDB/Nth create mode 120000 Lang/DuckDB/Nth-root create mode 120000 Lang/DuckDB/One-of-n-lines-in-a-file create mode 120000 Lang/DuckDB/Order-two-numerical-lists create mode 120000 Lang/DuckDB/Ordered-words create mode 120000 Lang/DuckDB/Palindrome-detection create mode 120000 Lang/DuckDB/Parameterized-SQL-statement create mode 120000 Lang/DuckDB/Pascals-triangle create mode 120000 Lang/DuckDB/Permutations create mode 120000 Lang/DuckDB/Permutations-Derangements create mode 120000 Lang/DuckDB/Pick-random-element create mode 120000 Lang/DuckDB/Primality-by-trial-division create mode 120000 Lang/DuckDB/Prime-decomposition create mode 120000 Lang/DuckDB/Probabilistic-choice create mode 120000 Lang/DuckDB/Proper-divisors create mode 120000 Lang/DuckDB/Pseudo-random-numbers-Middle-square-method create mode 120000 Lang/DuckDB/Random-numbers create mode 120000 Lang/DuckDB/Range-expansion create mode 120000 Lang/DuckDB/Range-extraction create mode 120000 Lang/DuckDB/Read-a-file-line-by-line create mode 120000 Lang/DuckDB/Reflection-List-methods create mode 120000 Lang/DuckDB/Reflection-List-properties create mode 120000 Lang/DuckDB/Remove-duplicate-elements create mode 120000 Lang/DuckDB/Rep-string create mode 120000 Lang/DuckDB/Repeat-a-string create mode 120000 Lang/DuckDB/Return-multiple-values create mode 120000 Lang/DuckDB/Reverse-a-string create mode 120000 Lang/DuckDB/Roots-of-unity create mode 120000 Lang/DuckDB/Run-length-encoding create mode 120000 Lang/DuckDB/Search-a-list-of-records create mode 120000 Lang/DuckDB/Set create mode 120000 Lang/DuckDB/Set-consolidation create mode 120000 Lang/DuckDB/Show-the-epoch create mode 120000 Lang/DuckDB/Sieve-of-Eratosthenes create mode 120000 Lang/DuckDB/Sort-an-array-of-composite-structures create mode 120000 Lang/DuckDB/Sort-numbers-lexicographically create mode 120000 Lang/DuckDB/Statistics-Basic create mode 120000 Lang/DuckDB/String-append create mode 120000 Lang/DuckDB/String-case create mode 120000 Lang/DuckDB/String-comparison create mode 120000 Lang/DuckDB/String-interpolation-included- create mode 120000 Lang/DuckDB/String-length create mode 120000 Lang/DuckDB/String-matching create mode 120000 Lang/DuckDB/String-prepend create mode 120000 Lang/DuckDB/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/DuckDB/Strip-comments-from-a-string create mode 120000 Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/DuckDB/Substring create mode 120000 Lang/DuckDB/Sudoku create mode 120000 Lang/DuckDB/Sum-and-product-of-an-array create mode 120000 Lang/DuckDB/Sum-digits-of-an-integer create mode 120000 Lang/DuckDB/Sum-multiples-of-3-and-5 create mode 120000 Lang/DuckDB/Sum-of-a-series create mode 120000 Lang/DuckDB/Sum-of-squares create mode 120000 Lang/DuckDB/Symmetric-difference create mode 120000 Lang/DuckDB/Table-creation-Postal-addresses create mode 120000 Lang/DuckDB/Test-integerness create mode 120000 Lang/DuckDB/Text-processing-2 create mode 120000 Lang/DuckDB/Thue-Morse create mode 120000 Lang/DuckDB/Time-a-function create mode 120000 Lang/DuckDB/Tokenize-a-string create mode 120000 Lang/DuckDB/Top-rank-per-group create mode 120000 Lang/DuckDB/Trigonometric-functions create mode 120000 Lang/DuckDB/URL-decoding create mode 120000 Lang/DuckDB/UTF-8-encode-and-decode create mode 120000 Lang/DuckDB/Unix-ls create mode 120000 Lang/DuckDB/Variable-size-Get create mode 120000 Lang/DuckDB/Variable-size-Set create mode 120000 Lang/DuckDB/Vector-products create mode 120000 Lang/DuckDB/Zero-to-the-zero-power create mode 120000 Lang/DuckDB/Zig-zag-matrix create mode 120000 Lang/EasyLang/AKS-test-for-primes create mode 120000 Lang/EasyLang/Bitmap-Midpoint-circle-algorithm create mode 120000 Lang/EasyLang/Cholesky-decomposition create mode 120000 Lang/EasyLang/Currency create mode 120000 Lang/EasyLang/Death-Star create mode 120000 Lang/EasyLang/Distribution-of-0-digits-in-factorial-series create mode 120000 Lang/EasyLang/Draw-a-sphere create mode 120000 Lang/EasyLang/EKG-sequence-convergence create mode 120000 Lang/EasyLang/Earliest-difference-between-prime-gaps create mode 120000 Lang/EasyLang/Elementary-cellular-automaton-Infinite-length create mode 120000 Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes create mode 120000 Lang/EasyLang/Faulhabers-formula create mode 120000 Lang/EasyLang/Faulhabers-triangle create mode 120000 Lang/EasyLang/Fibonacci-word-fractal create mode 120000 Lang/EasyLang/Find-Chess960-starting-position-identifier create mode 120000 Lang/EasyLang/Fraction-reduction create mode 120000 Lang/EasyLang/French-Republican-calendar create mode 120000 Lang/EasyLang/Function-prototype create mode 120000 Lang/EasyLang/Hash-from-two-arrays create mode 120000 Lang/EasyLang/Honeycombs create mode 120000 Lang/EasyLang/Hunt-the-Wumpus create mode 120000 Lang/EasyLang/Jacobsthal-numbers create mode 120000 Lang/EasyLang/Pascals-triangle-Puzzle create mode 120000 Lang/EasyLang/Straddling-checkerboard create mode 120000 Lang/EasyLang/Unicode-strings create mode 120000 Lang/Eiffel/Loops-For create mode 120000 Lang/Eiffel/Loops-Infinite create mode 120000 Lang/Elixir/Determinant-and-permanent create mode 120000 Lang/Elixir/K-d-tree create mode 120000 Lang/Elixir/Parse-an-IP-Address create mode 120000 Lang/Erlang/Determinant-and-permanent create mode 120000 Lang/Erlang/Floyd-Warshall-algorithm create mode 120000 Lang/Excel/Jacobi-symbol create mode 100644 Lang/Extended-Color-BASIC/00-LANG.txt create mode 100644 Lang/Extended-Color-BASIC/00-META.yaml create mode 120000 Lang/Extended-Color-BASIC/Arrays create mode 120000 Lang/Extended-Color-BASIC/Copy-a-string create mode 120000 Lang/Extended-Color-BASIC/Hello-world-Text create mode 120000 Lang/Extended-Color-BASIC/Loops-For create mode 120000 Lang/Extended-Color-BASIC/Quine create mode 120000 Lang/Extended-Color-BASIC/User-input-Text delete mode 120000 Lang/F-Sharp/Long-multiplication create mode 120000 Lang/F-Sharp/Multiplicative-order create mode 120000 Lang/Factor/Best-shuffle create mode 120000 Lang/Fennel/Abundant-deficient-and-perfect-number-classifications create mode 120000 Lang/Fennel/Factorial create mode 120000 Lang/Fennel/Factorial-primes create mode 120000 Lang/Fennel/Goldbachs-comet create mode 120000 Lang/Fennel/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/Fennel/Jacobsthal-numbers create mode 120000 Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/Fennel/Time-a-function create mode 120000 Lang/Fennel/Yellowstone-sequence create mode 120000 Lang/Fortran/Associative-array-Merging create mode 120000 Lang/Fortran/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Fortran/Chinese-zodiac create mode 120000 Lang/Fortran/Cyclotomic-polynomial create mode 120000 Lang/Fortran/Disarium-numbers create mode 120000 Lang/Fortran/Display-a-linear-combination create mode 120000 Lang/Fortran/EKG-sequence-convergence create mode 120000 Lang/Fortran/Egyptian-division create mode 120000 Lang/Fortran/French-Republican-calendar create mode 120000 Lang/Fortran/Hofstadter-Figure-Figure-sequences create mode 120000 Lang/Fortran/Humble-numbers create mode 120000 Lang/Fortran/Jewels-and-stones create mode 120000 Lang/Fortran/Knapsack-problem-Bounded create mode 120000 Lang/Fortran/Knuths-power-tree create mode 120000 Lang/Fortran/McNuggets-problem create mode 120000 Lang/Fortran/Parse-an-IP-Address create mode 120000 Lang/Fortran/Pascals-triangle-Puzzle create mode 120000 Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/Fortran/Totient-function create mode 120000 Lang/Fortran/Twos-complement create mode 120000 Lang/Free-Pascal-Lazarus/Abstract-type create mode 120000 Lang/Free-Pascal-Lazarus/Cistercian-numerals create mode 120000 Lang/Free-Pascal-Lazarus/Pancake-numbers create mode 120000 Lang/FreeBASIC/Babylonian-spiral create mode 120000 Lang/FreeBASIC/Bitcoin-public-point-to-address create mode 120000 Lang/FreeBASIC/Catmull-Clark-subdivision-surface create mode 120000 Lang/FreeBASIC/Color-quantization create mode 120000 Lang/FreeBASIC/Dominoes create mode 120000 Lang/FreeBASIC/Find-duplicate-files create mode 120000 Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base create mode 120000 Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet create mode 120000 Lang/Frink/Disarium-numbers create mode 120000 Lang/Frink/Happy-numbers create mode 100644 Lang/FuncSug/00-LANG.txt create mode 100644 Lang/FuncSug/00-META.yaml create mode 120000 Lang/FuncSug/GUI-component-interaction create mode 120000 Lang/FuncSug/GUI-enabling-disabling-of-controls create mode 120000 Lang/FuncSug/Hello-world-Text create mode 120000 Lang/FuncSug/Play-recorded-sounds create mode 120000 Lang/FuncSug/Simple-windowed-application create mode 120000 Lang/FuncSug/Simulate-input-Mouse create mode 120000 Lang/FuncSug/User-input-Graphical create mode 120000 Lang/FutureBasic/Arithmetic-Complex create mode 120000 Lang/FutureBasic/Averages-Mean-time-of-day create mode 120000 Lang/FutureBasic/Boyer-Moore-string-search create mode 120000 Lang/FutureBasic/CRC-32 create mode 120000 Lang/FutureBasic/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/FutureBasic/Deal-cards-for-FreeCell create mode 120000 Lang/FutureBasic/Demings-funnel create mode 120000 Lang/FutureBasic/Euler-method create mode 120000 Lang/FutureBasic/Find-limit-of-recursion create mode 120000 Lang/FutureBasic/Five-weekends create mode 120000 Lang/FutureBasic/Gamma-function create mode 120000 Lang/FutureBasic/Gaussian-elimination create mode 120000 Lang/FutureBasic/Guess-the-number-With-feedback-player- create mode 120000 Lang/FutureBasic/Hamming-numbers create mode 120000 Lang/FutureBasic/Last-letter-first-letter create mode 120000 Lang/FutureBasic/Mayan-numerals create mode 120000 Lang/FutureBasic/Modular-inverse create mode 120000 Lang/FutureBasic/Monte-Carlo-methods create mode 120000 Lang/FutureBasic/Mutex create mode 120000 Lang/FutureBasic/Named-parameters create mode 120000 Lang/FutureBasic/Perfect-shuffle create mode 120000 Lang/FutureBasic/Sierpinski-pentagon create mode 120000 Lang/FutureBasic/Sleep create mode 120000 Lang/FutureBasic/Sorting-algorithms-Insertion-sort create mode 120000 Lang/FutureBasic/Sorting-algorithms-Sleep-sort create mode 120000 Lang/FutureBasic/Stack-traces create mode 120000 Lang/FutureBasic/String-length create mode 120000 Lang/FutureBasic/Sum-of-a-series create mode 120000 Lang/FutureBasic/Sum-to-100 create mode 120000 Lang/FutureBasic/Tau-function create mode 120000 Lang/FutureBasic/Tau-number create mode 120000 Lang/FutureBasic/Word-wrap create mode 120000 Lang/FutureBasic/Yellowstone-sequence create mode 120000 Lang/FutureBasic/Zebra-puzzle create mode 120000 Lang/GW-BASIC/Old-Russian-measure-of-length create mode 120000 Lang/Go/Distance-and-Bearing create mode 100644 Lang/Goboscript/00-LANG.txt create mode 100644 Lang/Goboscript/00-META.yaml create mode 120000 Lang/Haxe/Abstract-type create mode 120000 Lang/Haxe/Apply-a-callback-to-an-array create mode 120000 Lang/Haxe/Arrays create mode 120000 Lang/Haxe/Associative-array-Creation create mode 120000 Lang/Haxe/Associative-array-Iteration create mode 120000 Lang/Haxe/Binary-digits create mode 120000 Lang/Haxe/Boolean-values create mode 120000 Lang/Haxe/Call-an-object-method create mode 120000 Lang/Haxe/Character-codes create mode 120000 Lang/Haxe/Classes create mode 120000 Lang/Icon/Exponentiation-order create mode 120000 Lang/Icon/Jewels-and-stones create mode 120000 Lang/Icon/Loops-Wrong-ranges create mode 120000 Lang/Icon/Search-a-list-of-records create mode 120000 Lang/Icon/Sort-numbers-lexicographically create mode 120000 Lang/Icon/Tokenize-a-string-with-escaping create mode 120000 Lang/Icon/Tree-from-nesting-levels create mode 120000 Lang/Idris/Comments create mode 120000 Lang/Janet/Comments create mode 120000 Lang/JavaScript/Aliquot-sequence-classifications create mode 120000 Lang/JavaScript/B-zier-curves-Intersections create mode 120000 Lang/JavaScript/Balanced-ternary create mode 120000 Lang/JavaScript/Bitcoin-public-point-to-address create mode 120000 Lang/JavaScript/Break-OO-privacy create mode 120000 Lang/JavaScript/Catmull-Clark-subdivision-surface create mode 120000 Lang/JavaScript/Checkpoint-synchronization create mode 120000 Lang/JavaScript/Continued-fraction create mode 120000 Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/JavaScript/Deconvolution-1D create mode 120000 Lang/JavaScript/Deconvolution-2D+ create mode 120000 Lang/JavaScript/MD5 create mode 120000 Lang/JavaScript/Meissel-Mertens-constant create mode 120000 Lang/JavaScript/Parse-an-IP-Address create mode 120000 Lang/JavaScript/Pascals-triangle-Puzzle create mode 120000 Lang/JavaScript/Sokoban create mode 120000 Lang/JavaScript/Solve-a-Hopido-puzzle create mode 120000 Lang/JavaScript/Superpermutation-minimisation create mode 120000 Lang/JavaScript/Tarjan create mode 120000 Lang/Julia/OLE-automation create mode 120000 Lang/Julia/Simulate-input-Keyboard create mode 120000 Lang/Julia/Use-another-language-to-call-a-function create mode 100644 Lang/Kantalo/00-LANG.txt create mode 100644 Lang/Kantalo/00-META.yaml create mode 120000 Lang/Koka/A+B create mode 120000 Lang/Koka/Extend-your-language create mode 120000 Lang/Koka/Jump-anywhere create mode 120000 Lang/Koka/Letter-frequency create mode 120000 Lang/Koka/Loops-Break create mode 120000 Lang/Koka/Monads-Writer-monad create mode 120000 Lang/Kotlin/Boyer-Moore-string-search create mode 100644 Lang/Labyrinth/00-LANG.txt create mode 100644 Lang/Labyrinth/00-META.yaml create mode 120000 Lang/Liberty-BASIC/Hunt-the-Wumpus create mode 120000 Lang/Liberty-BASIC/Minesweeper-game create mode 120000 Lang/Liberty-BASIC/Snake create mode 120000 Lang/Logo/Sparkline-in-unicode delete mode 120000 Lang/Lua/100-doors create mode 120000 Lang/Lua/Jacobsthal-numbers create mode 120000 Lang/Lua/Knapsack-problem-Bounded create mode 120000 Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/Lua/Use-another-language-to-call-a-function create mode 120000 Lang/Lua/Wagstaff-primes create mode 120000 Lang/Lua/Wieferich-primes create mode 120000 Lang/Mathematica/ASCII-art-diagram-converter create mode 120000 Lang/Mathematica/Camel-case-and-snake-case create mode 120000 Lang/Mathematica/Erd-s-Nicolas-numbers create mode 120000 Lang/Mathematica/Parse-an-IP-Address create mode 120000 Lang/Mathematica/Tonelli-Shanks-algorithm create mode 120000 Lang/Mathematica/Vogels-approximation-method create mode 120000 Lang/Maxima/Array-length create mode 120000 Lang/Maxima/Delete-a-file create mode 120000 Lang/Maxima/Hash-from-two-arrays create mode 120000 Lang/Maxima/Real-constants-and-functions create mode 120000 Lang/Maxima/Regular-expressions create mode 120000 Lang/Maxima/Rename-a-file create mode 120000 Lang/Maxima/Sorting-algorithms-Stooge-sort create mode 120000 Lang/Maxima/Statistics-Basic create mode 120000 Lang/Maxima/Substring-Top-and-tail create mode 120000 Lang/Maxima/Superellipse create mode 120000 Lang/Maxima/Topic-variable create mode 120000 Lang/Maxima/Towers-of-Hanoi create mode 100644 Lang/Mn/00-LANG.txt create mode 100644 Lang/Mn/00-META.yaml create mode 120000 Lang/Mn/Factorial create mode 120000 Lang/Mn/Loops-While create mode 120000 Lang/Modula-2/AKS-test-for-primes create mode 120000 Lang/Modula-2/Cistercian-numerals create mode 120000 Lang/Mojo/Hunt-the-Wumpus create mode 120000 Lang/Nascom-BASIC/Old-Russian-measure-of-length create mode 100644 Lang/Nom/00-LANG.txt create mode 100644 Lang/Nom/00-META.yaml create mode 120000 Lang/Nom/Balanced-brackets create mode 120000 Lang/Nom/CSV-to-HTML-translation create mode 120000 Lang/Nom/Determine-if-a-string-is-numeric create mode 120000 Lang/Nom/Empty-string create mode 120000 Lang/Nom/Even-or-odd create mode 120000 Lang/Nom/Hello-world-Text create mode 120000 Lang/Nom/Input-loop create mode 120000 Lang/Nom/Odd-word-problem create mode 120000 Lang/Nom/Reverse-a-string create mode 120000 Lang/OCaml/Parse-an-IP-Address create mode 120000 Lang/OCaml/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Objeck/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Objeck/Disarium-numbers create mode 120000 Lang/Objeck/HTTPS-Client-authenticated create mode 120000 Lang/Objeck/Magic-squares-of-doubly-even-order create mode 120000 Lang/Objeck/Matrix-multiplication create mode 100644 Lang/Object-Pascal-Implementations/00-LANG.txt create mode 100644 Lang/Object-Pascal-Implementations/00-META.yaml create mode 120000 Lang/Odin/Comments create mode 120000 Lang/OoRexx/Prime-decomposition create mode 120000 Lang/OxygenBasic/Josephus-problem create mode 120000 Lang/PARI-GP/Pell-numbers create mode 120000 Lang/PARI-GP/Tonelli-Shanks-algorithm create mode 120000 Lang/PHP/AKS-test-for-primes delete mode 120000 Lang/PL-M/100-doors create mode 100644 Lang/Pascal-P/00-LANG.txt create mode 100644 Lang/Pascal-P/00-META.yaml create mode 120000 Lang/Pascal-P/Cistercian-numerals create mode 120000 Lang/Pascal-P/FizzBuzz create mode 120000 Lang/Pascal-P/Leonardo-numbers create mode 120000 Lang/Pascal-P/Levenshtein-distance create mode 120000 Lang/Pascal-P/M-bius-function create mode 120000 Lang/Pascal-P/Magic-constant create mode 120000 Lang/Pascal-P/Map-range create mode 120000 Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification create mode 120000 Lang/PascalABC.NET/15-puzzle-solver create mode 120000 Lang/PascalABC.NET/Abbreviations-easy create mode 120000 Lang/PascalABC.NET/Abbreviations-simple create mode 120000 Lang/PascalABC.NET/Arithmetic-evaluation create mode 120000 Lang/PascalABC.NET/Bioinformatics-base-count create mode 120000 Lang/PascalABC.NET/Case-sensitivity-of-identifiers create mode 120000 Lang/PascalABC.NET/Combinations-with-repetitions create mode 120000 Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 100644 Lang/Pico-8/00-LANG.txt create mode 100644 Lang/Pico-8/00-META.yaml create mode 120000 Lang/Pico-8/Hello-world-Text create mode 100644 Lang/Pluto/00-LANG.txt create mode 100644 Lang/Pluto/00-META.yaml create mode 120000 Lang/Pluto/99-bottles-of-beer create mode 120000 Lang/Pluto/A+B create mode 120000 Lang/Pluto/ABC-problem create mode 120000 Lang/Pluto/AKS-test-for-primes create mode 120000 Lang/Pluto/Abelian-sandpile-model create mode 120000 Lang/Pluto/Abelian-sandpile-model-Identity create mode 120000 Lang/Pluto/Abstract-type create mode 120000 Lang/Pluto/Abundant-deficient-and-perfect-number-classifications create mode 120000 Lang/Pluto/Abundant-odd-numbers create mode 120000 Lang/Pluto/Achilles-numbers create mode 120000 Lang/Pluto/Ackermann-function create mode 120000 Lang/Pluto/Address-of-a-variable create mode 120000 Lang/Pluto/Almost-prime create mode 120000 Lang/Pluto/Anti-primes create mode 120000 Lang/Pluto/Approximate-equality create mode 120000 Lang/Pluto/Arbitrary-precision-integers-included- create mode 120000 Lang/Pluto/Arithmetic-Complex create mode 120000 Lang/Pluto/Arithmetic-Integer create mode 120000 Lang/Pluto/Arithmetic-Rational create mode 120000 Lang/Pluto/Arithmetic-derivative create mode 120000 Lang/Pluto/Arithmetic-geometric-mean create mode 120000 Lang/Pluto/Array-concatenation create mode 120000 Lang/Pluto/Arrays create mode 120000 Lang/Pluto/Ascending-primes create mode 120000 Lang/Pluto/Associative-array-Creation create mode 120000 Lang/Pluto/Associative-array-Iteration create mode 120000 Lang/Pluto/Associative-array-Merging create mode 120000 Lang/Pluto/Attractive-numbers create mode 120000 Lang/Pluto/Averages-Arithmetic-mean create mode 120000 Lang/Pluto/Averages-Median create mode 120000 Lang/Pluto/Averages-Pythagorean-means create mode 120000 Lang/Pluto/Averages-Root-mean-square create mode 120000 Lang/Pluto/Balanced-brackets create mode 120000 Lang/Pluto/Base64-decode-data create mode 120000 Lang/Pluto/Bell-numbers create mode 120000 Lang/Pluto/Bitmap create mode 120000 Lang/Pluto/Bitmap-Bresenhams-line-algorithm create mode 120000 Lang/Pluto/Bitmap-Midpoint-circle-algorithm create mode 120000 Lang/Pluto/Bitwise-operations create mode 120000 Lang/Pluto/CRC-32 create mode 120000 Lang/Pluto/Caesar-cipher create mode 120000 Lang/Pluto/Calkin-Wilf-sequence create mode 120000 Lang/Pluto/Call-a-foreign-language-function create mode 120000 Lang/Pluto/Call-a-function-in-a-shared-library create mode 120000 Lang/Pluto/Case-sensitivity-of-identifiers create mode 120000 Lang/Pluto/Casting-out-nines create mode 120000 Lang/Pluto/Collections create mode 120000 Lang/Pluto/Combinations create mode 120000 Lang/Pluto/Combinations-with-repetitions create mode 120000 Lang/Pluto/Command-line-arguments create mode 120000 Lang/Pluto/Comments create mode 120000 Lang/Pluto/Compare-length-of-two-strings create mode 120000 Lang/Pluto/Compiler-lexical-analyzer create mode 120000 Lang/Pluto/Conditional-structures create mode 120000 Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Pluto/Convert-decimal-number-to-rational create mode 120000 Lang/Pluto/Count-in-octal create mode 120000 Lang/Pluto/Count-the-coins create mode 120000 Lang/Pluto/Create-a-file create mode 120000 Lang/Pluto/Currying create mode 120000 Lang/Pluto/Delete-a-file create mode 120000 Lang/Pluto/Descending-primes create mode 120000 Lang/Pluto/Determine-if-a-string-is-numeric create mode 120000 Lang/Pluto/Disarium-numbers create mode 120000 Lang/Pluto/Display-a-linear-combination create mode 120000 Lang/Pluto/Distribution-of-0-digits-in-factorial-series create mode 120000 Lang/Pluto/Doubly-linked-list-Definition create mode 120000 Lang/Pluto/Doubly-linked-list-Element-definition create mode 120000 Lang/Pluto/Doubly-linked-list-Traversal create mode 120000 Lang/Pluto/Dutch-national-flag-problem create mode 120000 Lang/Pluto/Euler-method create mode 120000 Lang/Pluto/Eulers-identity create mode 120000 Lang/Pluto/Even-or-odd create mode 120000 Lang/Pluto/Execute-a-system-command create mode 120000 Lang/Pluto/Factorial create mode 120000 Lang/Pluto/Factorial-primes create mode 120000 Lang/Pluto/Factorions create mode 120000 Lang/Pluto/Factors-of-an-integer create mode 120000 Lang/Pluto/Farey-sequence create mode 120000 Lang/Pluto/Feigenbaum-constant-calculation create mode 120000 Lang/Pluto/Fibonacci-sequence create mode 120000 Lang/Pluto/Filter create mode 120000 Lang/Pluto/FizzBuzz create mode 120000 Lang/Pluto/Floyd-Warshall-algorithm create mode 120000 Lang/Pluto/Formatted-numeric-output create mode 120000 Lang/Pluto/Function-definition create mode 120000 Lang/Pluto/Gamma-function create mode 120000 Lang/Pluto/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Pluto/Giuga-numbers create mode 120000 Lang/Pluto/Goldbachs-comet create mode 120000 Lang/Pluto/Greatest-common-divisor create mode 120000 Lang/Pluto/Greatest-element-of-a-list create mode 120000 Lang/Pluto/Hailstone-sequence create mode 120000 Lang/Pluto/Halt-and-catch-fire create mode 120000 Lang/Pluto/Hash-from-two-arrays create mode 120000 Lang/Pluto/Hello-world-Newline-omission create mode 120000 Lang/Pluto/Hello-world-Standard-error create mode 120000 Lang/Pluto/Hello-world-Text create mode 120000 Lang/Pluto/Higher-order-functions create mode 120000 Lang/Pluto/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/Pluto/Humble-numbers create mode 120000 Lang/Pluto/Increment-a-numerical-string create mode 120000 Lang/Pluto/Infinity create mode 120000 Lang/Pluto/JSON create mode 120000 Lang/Pluto/Jacobsthal-numbers create mode 120000 Lang/Pluto/Jewels-and-stones create mode 120000 Lang/Pluto/Josephus-problem create mode 120000 Lang/Pluto/Kaprekar-numbers create mode 120000 Lang/Pluto/Leap-year create mode 120000 Lang/Pluto/Literals-Floating-point create mode 120000 Lang/Pluto/Literals-Integer create mode 120000 Lang/Pluto/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Pluto/Loops-Break create mode 120000 Lang/Pluto/Loops-Continue create mode 120000 Lang/Pluto/Loops-Do-while create mode 120000 Lang/Pluto/Loops-Downward-for create mode 120000 Lang/Pluto/Loops-For create mode 120000 Lang/Pluto/Loops-For-with-a-specified-step create mode 120000 Lang/Pluto/Loops-Foreach create mode 120000 Lang/Pluto/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/Pluto/Loops-Infinite create mode 120000 Lang/Pluto/Loops-N-plus-one-half create mode 120000 Lang/Pluto/Loops-Nested create mode 120000 Lang/Pluto/Loops-While create mode 120000 Lang/Pluto/Loops-With-multiple-ranges create mode 120000 Lang/Pluto/Loops-Wrong-ranges create mode 120000 Lang/Pluto/Luhn-test-of-credit-card-numbers create mode 120000 Lang/Pluto/M-bius-function create mode 120000 Lang/Pluto/Machine-code create mode 120000 Lang/Pluto/Magic-squares-of-doubly-even-order create mode 120000 Lang/Pluto/Magic-squares-of-odd-order create mode 120000 Lang/Pluto/Magic-squares-of-singly-even-order create mode 120000 Lang/Pluto/Mian-Chowla-sequence create mode 120000 Lang/Pluto/Modular-inverse create mode 120000 Lang/Pluto/Multiplication-tables create mode 120000 Lang/Pluto/Mutual-recursion create mode 120000 Lang/Pluto/Named-parameters create mode 120000 Lang/Pluto/Narcissistic-decimal-number create mode 120000 Lang/Pluto/Nested-templated-data create mode 120000 Lang/Pluto/Non-decimal-radices-Convert create mode 120000 Lang/Pluto/Numerical-integration create mode 120000 Lang/Pluto/Old-Russian-measure-of-length create mode 120000 Lang/Pluto/Order-by-pair-comparisons create mode 120000 Lang/Pluto/Palindrome-detection create mode 120000 Lang/Pluto/Pancake-numbers create mode 120000 Lang/Pluto/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Pluto/Pascals-triangle-Puzzle create mode 120000 Lang/Pluto/Perfect-shuffle create mode 120000 Lang/Pluto/Permutations create mode 120000 Lang/Pluto/Pernicious-numbers create mode 120000 Lang/Pluto/Pick-random-element create mode 120000 Lang/Pluto/Pisano-period create mode 120000 Lang/Pluto/Power-set create mode 120000 Lang/Pluto/Primality-by-trial-division create mode 120000 Lang/Pluto/Priority-queue create mode 120000 Lang/Pluto/Read-a-file-line-by-line create mode 120000 Lang/Pluto/Rename-a-file create mode 120000 Lang/Pluto/Repeat-a-string create mode 120000 Lang/Pluto/Reverse-a-string create mode 120000 Lang/Pluto/Reverse-words-in-a-string create mode 120000 Lang/Pluto/Roman-numerals-Encode create mode 120000 Lang/Pluto/Roots-of-a-quadratic-function create mode 120000 Lang/Pluto/Roots-of-unity create mode 120000 Lang/Pluto/Rot-13 create mode 120000 Lang/Pluto/Runge-Kutta-method create mode 120000 Lang/Pluto/Self-numbers create mode 120000 Lang/Pluto/Semordnilap create mode 120000 Lang/Pluto/Sequence-of-primes-by-trial-division create mode 120000 Lang/Pluto/Set create mode 120000 Lang/Pluto/Set-consolidation create mode 120000 Lang/Pluto/Singly-linked-list-Element-definition create mode 120000 Lang/Pluto/Singly-linked-list-Element-insertion create mode 120000 Lang/Pluto/Singly-linked-list-Traversal create mode 120000 Lang/Pluto/Sleep create mode 120000 Lang/Pluto/Smarandache-prime-digital-sequence create mode 120000 Lang/Pluto/Soloways-recurring-rainfall create mode 120000 Lang/Pluto/Sort-an-integer-array create mode 120000 Lang/Pluto/Stack create mode 120000 Lang/Pluto/String-interpolation-included- create mode 120000 Lang/Pluto/String-length create mode 120000 Lang/Pluto/Sum-digits-of-an-integer create mode 120000 Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix create mode 120000 Lang/Pluto/Symmetric-difference create mode 120000 Lang/Pluto/System-time create mode 120000 Lang/Pluto/Tau-function create mode 120000 Lang/Pluto/Tau-number create mode 120000 Lang/Pluto/Terminal-control-Clear-the-screen create mode 120000 Lang/Pluto/Terminal-control-Coloured-text create mode 120000 Lang/Pluto/Terminal-control-Cursor-movement create mode 120000 Lang/Pluto/Terminal-control-Cursor-positioning create mode 120000 Lang/Pluto/Terminal-control-Dimensions create mode 120000 Lang/Pluto/Terminal-control-Display-an-extended-character create mode 120000 Lang/Pluto/Terminal-control-Hiding-the-cursor create mode 120000 Lang/Pluto/Terminal-control-Inverse-video create mode 120000 Lang/Pluto/Terminal-control-Preserve-screen create mode 120000 Lang/Pluto/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/Pluto/Terminal-control-Unicode-output create mode 120000 Lang/Pluto/Test-integerness create mode 120000 Lang/Pluto/Time-a-function create mode 120000 Lang/Pluto/Total-circles-area create mode 120000 Lang/Pluto/Totient-function create mode 120000 Lang/Pluto/Towers-of-Hanoi create mode 120000 Lang/Pluto/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Pluto/UPC create mode 120000 Lang/Pluto/Unicode-strings create mode 120000 Lang/Pluto/Unprimeable-numbers create mode 120000 Lang/Pluto/User-input-Text create mode 120000 Lang/Pluto/Van-Eck-sequence create mode 120000 Lang/Pluto/Van-der-Corput-sequence create mode 120000 Lang/Pluto/Variadic-function create mode 120000 Lang/Pluto/Vector create mode 120000 Lang/Pluto/Vector-products create mode 120000 Lang/Pluto/Wagstaff-primes create mode 120000 Lang/Pluto/Wieferich-primes create mode 120000 Lang/Pluto/Y-combinator create mode 120000 Lang/Pluto/Yellowstone-sequence create mode 120000 Lang/Pluto/Zebra-puzzle create mode 120000 Lang/Pluto/Zero-to-the-zero-power create mode 120000 Lang/PowerShell/AKS-test-for-primes create mode 120000 Lang/PowerShell/M-bius-function create mode 120000 Lang/Prolog/100-prisoners create mode 120000 Lang/Prolog/Boolean-values create mode 120000 Lang/Prolog/Damm-algorithm create mode 120000 Lang/Prolog/Hello-world-Newline-omission create mode 120000 Lang/Prolog/ISBN13-check-digit create mode 120000 Lang/Prolog/Integer-comparison create mode 120000 Lang/Prolog/Iterated-digits-squaring create mode 120000 Lang/Prolog/Josephus-problem create mode 120000 Lang/Prolog/Magic-8-ball create mode 120000 Lang/Prolog/Old-Russian-measure-of-length create mode 120000 Lang/Prolog/Order-by-pair-comparisons create mode 120000 Lang/Prolog/Phrase-reversals create mode 120000 Lang/Prolog/Population-count create mode 120000 Lang/Prolog/RPG-attributes-generator create mode 120000 Lang/Prolog/SEDOLs create mode 120000 Lang/Prolog/Semordnilap create mode 120000 Lang/Prolog/Sort-three-variables create mode 120000 Lang/Prolog/Stem-and-leaf-plot create mode 120000 Lang/Prolog/String-concatenation create mode 120000 Lang/Prolog/Thue-Morse create mode 120000 Lang/Prolog/Topswops create mode 120000 Lang/Prolog/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Prolog/Wireworld create mode 120000 Lang/Prolog/Zero-to-the-zero-power create mode 120000 Lang/Python/Ruth-Aaron-numbers create mode 120000 Lang/QB64/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/R/Angles-geometric-normalization-and-conversion create mode 120000 Lang/R/CUSIP create mode 120000 Lang/R/Continued-fraction create mode 120000 Lang/R/Cramers-rule create mode 120000 Lang/R/Curzon-numbers create mode 120000 Lang/R/Dijkstras-algorithm create mode 120000 Lang/R/Execute-HQ9+ create mode 120000 Lang/R/Factorial-primes create mode 120000 Lang/R/Fibonacci-n-step-number-sequences create mode 120000 Lang/R/Flipping-bits-game create mode 120000 Lang/R/Floyd-Warshall-algorithm create mode 120000 Lang/R/Fractran create mode 120000 Lang/R/Giuga-numbers create mode 120000 Lang/R/Greedy-algorithm-for-Egyptian-fractions create mode 120000 Lang/R/Humble-numbers create mode 120000 Lang/R/M-bius-function create mode 120000 Lang/R/Parse-an-IP-Address create mode 120000 Lang/R/Rename-a-file create mode 120000 Lang/R/Repunit-primes create mode 120000 Lang/R/Retrieve-and-search-chat-history create mode 120000 Lang/R/Shoelace-formula-for-polygonal-area create mode 120000 Lang/R/Soloways-recurring-rainfall create mode 120000 Lang/R/Split-a-character-string-based-on-change-of-character create mode 120000 Lang/R/String-interpolation-included- create mode 120000 Lang/R/String-matching create mode 120000 Lang/R/Substring-Top-and-tail create mode 120000 Lang/R/The-Name-Game create mode 120000 Lang/R/Tonelli-Shanks-algorithm create mode 120000 Lang/R/Wieferich-primes create mode 120000 Lang/R/Write-entire-file create mode 120000 Lang/REBOL/9-billion-names-of-God-the-integer create mode 120000 Lang/REBOL/Ackermann-function create mode 120000 Lang/REBOL/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/REBOL/Loops-Increment-loop-index-within-loop-body create mode 120000 Lang/REBOL/Loops-With-multiple-ranges create mode 120000 Lang/REBOL/Loops-Wrong-ranges create mode 120000 Lang/REBOL/Object-serialization create mode 120000 Lang/REBOL/Polyspiral create mode 120000 Lang/REBOL/SHA-1 create mode 120000 Lang/REBOL/SHA-256 create mode 120000 Lang/REBOL/Semordnilap create mode 120000 Lang/RISC-V-Assembly/Address-of-a-variable create mode 120000 Lang/RISC-V-Assembly/Arithmetic-Integer create mode 120000 Lang/RISC-V-Assembly/Binary-digits create mode 120000 Lang/RISC-V-Assembly/Hello-world-Newbie create mode 120000 Lang/RISC-V-Assembly/Include-a-file create mode 120000 Lang/Raku/Play-recorded-sounds create mode 120000 Lang/Red/Address-of-a-variable create mode 120000 Lang/Red/Arithmetic-Integer create mode 120000 Lang/Red/Arithmetic-evaluation create mode 120000 Lang/Red/Calendar create mode 120000 Lang/Red/Calendar---for-REAL-programmers create mode 120000 Lang/Red/Currying create mode 120000 Lang/Red/Five-weekends create mode 120000 Lang/Red/Logical-operations create mode 120000 Lang/Red/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Red/Parsing-RPN-to-infix-conversion create mode 120000 Lang/Red/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Red/Towers-of-Hanoi create mode 120000 Lang/Refal/Tokenize-a-string create mode 100644 Lang/Rhombus/00-LANG.txt create mode 100644 Lang/Rhombus/00-META.yaml create mode 120000 Lang/Rhombus/99-bottles-of-beer create mode 120000 Lang/Rhombus/Arbitrary-precision-integers-included- create mode 120000 Lang/Rhombus/Caesar-cipher create mode 120000 Lang/Rhombus/Factorial create mode 120000 Lang/Rhombus/Fibonacci-sequence create mode 120000 Lang/Rhombus/FizzBuzz create mode 120000 Lang/Rhombus/Guess-the-number-With-feedback create mode 120000 Lang/Rhombus/Hello-world-Text create mode 120000 Lang/Rhombus/Inheritance-Single create mode 120000 Lang/Rhombus/Polymorphism create mode 120000 Lang/Rhombus/Rot-13 create mode 120000 Lang/Ring/Compare-a-list-of-strings create mode 120000 Lang/Ring/Wagstaff-primes create mode 120000 Lang/Run-BASIC/Josephus-problem create mode 120000 Lang/Rust/Break-OO-privacy create mode 120000 Lang/Rust/Camel-case-and-snake-case create mode 120000 Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/Rust/Cyclops-numbers create mode 120000 Lang/Rust/Deconvolution-1D create mode 120000 Lang/Rust/Deconvolution-2D+ create mode 120000 Lang/Rust/Determine-if-two-triangles-overlap create mode 120000 Lang/Rust/Duffinian-numbers create mode 120000 Lang/Rust/Elliptic-curve-arithmetic create mode 120000 Lang/Rust/Faulhabers-triangle create mode 120000 Lang/Rust/Fractran create mode 120000 Lang/Rust/Humble-numbers create mode 120000 Lang/Rust/Knapsack-problem-Bounded create mode 120000 Lang/Rust/Mayan-calendar create mode 120000 Lang/Rust/Meissel-Mertens-constant create mode 120000 Lang/Rust/Modular-arithmetic create mode 120000 Lang/Rust/Multiple-regression create mode 120000 Lang/Rust/Ramanujan-primes-twins create mode 120000 Lang/Rust/Singleton create mode 120000 Lang/Rust/Sokoban create mode 120000 Lang/Rust/Substitution-cipher create mode 120000 Lang/Rust/Tree-datastructures create mode 120000 Lang/Rust/UPC create mode 120000 Lang/Rust/War-card-game create mode 120000 Lang/S-BASIC/Sorting-algorithms-Insertion-sort create mode 120000 Lang/SETL/Monte-Carlo-methods create mode 120000 Lang/SETL/Tokenize-a-string create mode 120000 Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/Scala/Tonelli-Shanks-algorithm create mode 120000 Lang/Scala/UPC create mode 120000 Lang/Scheme/Own-digits-power-sum create mode 120000 Lang/Scheme/Pick-random-element create mode 120000 Lang/Swift/AVL-tree create mode 120000 Lang/Swift/Boyer-Moore-string-search create mode 120000 Lang/Swift/Chaocipher create mode 120000 Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- create mode 120000 Lang/Swift/Floyd-Warshall-algorithm create mode 120000 Lang/Swift/K-d-tree create mode 120000 Lang/Swift/Parse-an-IP-Address create mode 100644 Lang/TAV/00-LANG.txt create mode 100644 Lang/TAV/00-META.yaml create mode 120000 Lang/TAV/A+B create mode 120000 Lang/TAV/Ackermann-function create mode 120000 Lang/TAV/Anagrams create mode 120000 Lang/TAV/Arithmetic-Integer create mode 120000 Lang/TAV/Array-concatenation create mode 120000 Lang/TAV/Array-length create mode 120000 Lang/TAV/Associative-array-Iteration create mode 120000 Lang/TAV/Averages-Root-mean-square create mode 120000 Lang/TAV/Character-codes create mode 120000 Lang/TAV/Command-line-arguments create mode 120000 Lang/TAV/Conditional-structures create mode 120000 Lang/TAV/Copy-a-string create mode 120000 Lang/TAV/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/TAV/Empty-string create mode 120000 Lang/TAV/Factorial create mode 120000 Lang/TAV/Fibonacci-sequence create mode 120000 Lang/TAV/Formatted-numeric-output create mode 120000 Lang/TAV/Greatest-element-of-a-list create mode 120000 Lang/TAV/Guess-the-number-With-feedback create mode 120000 Lang/TAV/HTTPS create mode 120000 Lang/TAV/Halt-and-catch-fire create mode 120000 Lang/TAV/Hello-world-Graphical create mode 120000 Lang/TAV/Hello-world-Text create mode 120000 Lang/TAV/Letter-frequency create mode 120000 Lang/TAV/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/TAV/Loops-Break create mode 120000 Lang/TAV/Loops-Do-while create mode 120000 Lang/TAV/Loops-Downward-for create mode 120000 Lang/TAV/Loops-For create mode 120000 Lang/TAV/Loops-Infinite create mode 120000 Lang/TAV/Loops-N-plus-one-half create mode 120000 Lang/TAV/Loops-While create mode 120000 Lang/TAV/Multiplication-tables create mode 120000 Lang/TAV/Ordered-words create mode 120000 Lang/TAV/Permutations create mode 120000 Lang/TAV/Real-constants-and-functions create mode 120000 Lang/TAV/Reverse-a-string create mode 120000 Lang/TAV/Semordnilap create mode 120000 Lang/TAV/Simple-windowed-application create mode 120000 Lang/TAV/Stack create mode 120000 Lang/TAV/String-length create mode 120000 Lang/TAV/Tic-tac-toe create mode 120000 Lang/TAV/Tokenize-a-string create mode 120000 Lang/TAV/Window-creation create mode 120000 Lang/TAV/Word-frequency create mode 120000 Lang/Tcl/M-bius-function create mode 120000 Lang/Ursalang/Loops-Break create mode 120000 Lang/Ursalang/Loops-While create mode 120000 Lang/V-(Vlang)/Compile-time-calculation create mode 120000 Lang/V-(Vlang)/Inheritance-Multiple create mode 120000 Lang/V-(Vlang)/Inheritance-Single create mode 120000 Lang/V-(Vlang)/Metaprogramming create mode 100644 Lang/Vyxal/00-LANG.txt create mode 100644 Lang/Vyxal/00-META.yaml create mode 120000 Lang/Vyxal/Factorial create mode 120000 Lang/Vyxal/FizzBuzz create mode 120000 Lang/XBasic/AKS-test-for-primes create mode 120000 Lang/XBasic/Josephus-problem create mode 120000 Lang/XPL0/AKS-test-for-primes create mode 120000 Lang/XPL0/Cistercian-numerals create mode 120000 Lang/YAMLScript/Best-shuffle create mode 120000 Lang/YAMLScript/Conways-Game-of-Life create mode 120000 Lang/YAMLScript/Dragon-curve create mode 120000 Lang/YAMLScript/Even-or-odd create mode 120000 Lang/YAMLScript/Integer-comparison create mode 120000 Lang/YAMLScript/JortSort create mode 120000 Lang/YAMLScript/Knuth-shuffle create mode 120000 Lang/YAMLScript/Munching-squares create mode 120000 Lang/YAMLScript/Next-highest-int-from-digits create mode 120000 Lang/YAMLScript/One-dimensional-cellular-automata create mode 120000 Lang/YAMLScript/Quickselect-algorithm create mode 120000 Lang/YAMLScript/Sparkline-in-unicode create mode 120000 Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/YAMLScript/Undefined-values create mode 120000 Lang/YAMLScript/Van-der-Corput-sequence create mode 120000 Lang/YAMLScript/Xiaolin-Wus-line-algorithm create mode 120000 Lang/YAMLScript/Yellowstone-sequence create mode 120000 Lang/YAMLScript/Zig-zag-matrix create mode 120000 Lang/Zig/24-game-Solve create mode 120000 Lang/Zig/AVL-tree create mode 120000 Lang/Zig/Abelian-sandpile-model create mode 120000 Lang/Zig/Abelian-sandpile-model-Identity create mode 120000 Lang/Zig/Arrays create mode 120000 Lang/Zig/Associative-array-Creation create mode 120000 Lang/Zig/Associative-array-Iteration create mode 120000 Lang/Zig/Base64-decode-data create mode 120000 Lang/Zig/Bifid-cipher create mode 120000 Lang/Zig/Boolean-values create mode 120000 Lang/Zig/Boyer-Moore-string-search create mode 120000 Lang/Zig/Break-OO-privacy create mode 120000 Lang/Zig/Camel-case-and-snake-case create mode 120000 Lang/Zig/Cholesky-decomposition create mode 120000 Lang/Zig/Cumulative-standard-deviation create mode 120000 Lang/Zig/Cyclops-numbers create mode 120000 Lang/Zig/Deconvolution-1D create mode 120000 Lang/Zig/Determinant-and-permanent create mode 120000 Lang/Zig/Eertree create mode 120000 Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm create mode 120000 Lang/Zig/Elliptic-curve-arithmetic create mode 120000 Lang/Zig/Evolutionary-algorithm create mode 120000 Lang/Zig/Factors-of-an-integer create mode 120000 Lang/Zig/Farey-sequence create mode 120000 Lang/Zig/Gray-code create mode 120000 Lang/Zig/K-d-tree create mode 120000 Lang/Zig/Knapsack-problem-0-1 create mode 120000 Lang/Zig/Knights-tour create mode 120000 Lang/Zig/Loops-Nested create mode 120000 Lang/Zig/M-bius-function create mode 120000 Lang/Zig/Main-step-of-GOST-28147-89 create mode 120000 Lang/Zig/Modular-arithmetic create mode 120000 Lang/Zig/Modular-inverse create mode 120000 Lang/Zig/Parse-an-IP-Address create mode 120000 Lang/Zig/Permutations-by-swapping create mode 120000 Lang/Zig/Stern-Brocot-sequence create mode 120000 Lang/Zig/Sudoku create mode 120000 Lang/Zig/Tarjan create mode 120000 Lang/Zig/Tree-datastructures create mode 120000 Lang/Zig/Verhoeff-algorithm create mode 120000 Lang/Zig/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/Zig/Vogels-approximation-method create mode 120000 Lang/Zig/War-card-game delete mode 100644 Task/100-doors/AWK/100-doors-1.awk delete mode 100644 Task/100-doors/AWK/100-doors-2.awk create mode 100644 Task/100-doors/Adina/100-doors-1.adina create mode 100644 Task/100-doors/Adina/100-doors-2.adina create mode 100644 Task/100-doors/ArkScript/100-doors-1.ark create mode 100644 Task/100-doors/ArkScript/100-doors-2.ark create mode 100644 Task/100-doors/AutoLISP/100-doors.l delete mode 100644 Task/100-doors/Component-Pascal/100-doors.pas create mode 100644 Task/100-doors/DuckDB/100-doors.duckdb create mode 100644 Task/100-doors/Haskell/100-doors-5.hs delete mode 100644 Task/100-doors/Lua/100-doors.lua delete mode 100644 Task/100-doors/PL-M/100-doors.plm create mode 100644 Task/100-doors/REBOL/100-doors-3.rebol create mode 100644 Task/100-prisoners/Prolog/100-prisoners.pro create mode 100644 Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas create mode 100644 Task/24-game-Solve/Zig/24-game-solve.zig create mode 100644 Task/9-billion-names-of-God-the-integer/REBOL/9-billion-names-of-god-the-integer.rebol create mode 100644 Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria create mode 100644 Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark create mode 100644 Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb create mode 100644 Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb create mode 100644 Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto create mode 100644 Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus create mode 100644 Task/A+B/ArkScript/a+b.ark create mode 100644 Task/A+B/DuckDB/a+b-1.duckdb create mode 100644 Task/A+B/DuckDB/a+b-2.duckdb create mode 100644 Task/A+B/Koka/a+b.koka create mode 100644 Task/A+B/Pluto/a+b.pluto create mode 100644 Task/A+B/TAV/a+b.tav create mode 100644 Task/ABC-problem/DuckDB/abc-problem.duckdb create mode 100644 Task/ABC-problem/Pluto/abc-problem.pluto create mode 100644 Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic create mode 100644 Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena create mode 100644 Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy create mode 100644 Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2 create mode 100644 Task/AKS-test-for-primes/PHP/aks-test-for-primes.php create mode 100644 Task/AKS-test-for-primes/Pluto/aks-test-for-primes.pluto create mode 100644 Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.psh create mode 100644 Task/AKS-test-for-primes/XBasic/aks-test-for-primes.basic create mode 100644 Task/AKS-test-for-primes/XPL0/aks-test-for-primes.xpl0 create mode 100644 Task/ASCII-art-diagram-converter/Mathematica/ascii-art-diagram-converter.math create mode 100644 Task/AVL-tree/Dart/avl-tree.dart create mode 100644 Task/AVL-tree/Swift/avl-tree.swift create mode 100644 Task/AVL-tree/Zig/avl-tree.zig create mode 100644 Task/Abbreviations-easy/ArkScript/abbreviations-easy.ark create mode 100644 Task/Abbreviations-easy/PascalABC.NET/abbreviations-easy.pas create mode 100644 Task/Abbreviations-simple/PascalABC.NET/abbreviations-simple.pas create mode 100644 Task/Abelian-sandpile-model-Identity/Pluto/abelian-sandpile-model-identity.pluto create mode 100644 Task/Abelian-sandpile-model-Identity/Zig/abelian-sandpile-model-identity.zig create mode 100644 Task/Abelian-sandpile-model/Pluto/abelian-sandpile-model.pluto create mode 100644 Task/Abelian-sandpile-model/Zig/abelian-sandpile-model.zig create mode 100644 Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-1.pas create mode 100644 Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-2.pas create mode 100644 Task/Abstract-type/Haxe/abstract-type-1.haxe rename Task/Abstract-type/{Haskell/abstract-type-6.hs => Haxe/abstract-type-2.haxe} (100%) create mode 100644 Task/Abstract-type/Pluto/abstract-type.pluto create mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Agena/abundant-deficient-and-perfect-number-classifications.agena create mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Fennel/abundant-deficient-and-perfect-number-classifications.fennel create mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Pluto/abundant-deficient-and-perfect-number-classifications.pluto create mode 100644 Task/Abundant-odd-numbers/Agena/abundant-odd-numbers.agena create mode 100644 Task/Abundant-odd-numbers/Pluto/abundant-odd-numbers.pluto rename Task/Accumulator-factory/REBOL/{accumulator-factory.rebol => accumulator-factory-1.rebol} (70%) create mode 100644 Task/Accumulator-factory/REBOL/accumulator-factory-2.rebol create mode 100644 Task/Achilles-numbers/Pluto/achilles-numbers.pluto create mode 100644 Task/Ackermann-function/ArkScript/ackermann-function.ark create mode 100644 Task/Ackermann-function/Pluto/ackermann-function.pluto create mode 100644 Task/Ackermann-function/REBOL/ackermann-function-1.rebol create mode 100644 Task/Ackermann-function/REBOL/ackermann-function-2.rebol create mode 100644 Task/Ackermann-function/TAV/ackermann-function.tav create mode 100644 Task/Address-of-a-variable/Pluto/address-of-a-variable.pluto create mode 100644 Task/Address-of-a-variable/RISC-V-Assembly/address-of-a-variable.asm create mode 100644 Task/Address-of-a-variable/Red/address-of-a-variable.red create mode 100644 Task/Aliquot-sequence-classifications/JavaScript/aliquot-sequence-classifications.js create mode 100644 Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.ada create mode 100644 Task/Almost-prime/Pluto/almost-prime.pluto rename Task/Amb/Ada/{amb.ada => amb-1.ada} (100%) create mode 100644 Task/Amb/Ada/amb-2.ada delete mode 100644 Task/Amicable-pairs/PL-I-80/amicable-pairs-1.pli rename Task/Amicable-pairs/PL-I-80/{amicable-pairs-2.pli => amicable-pairs.pli} (89%) create mode 100644 Task/Anagrams/DuckDB/anagrams.duckdb create mode 100644 Task/Anagrams/TAV/anagrams.tav create mode 100644 Task/Angles-geometric-normalization-and-conversion/R/angles-geometric-normalization-and-conversion.r create mode 100644 Task/Anonymous-recursion/DuckDB/anonymous-recursion.duckdb create mode 100644 Task/Anti-primes/Bc/anti-primes.bc create mode 100644 Task/Anti-primes/Draco/anti-primes.draco create mode 100644 Task/Anti-primes/Pluto/anti-primes.pluto create mode 100644 Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark create mode 100644 Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.haxe create mode 100644 Task/Approximate-equality/Pluto/approximate-equality.pluto create mode 100644 Task/Arbitrary-precision-integers-included-/Agena/arbitrary-precision-integers-included-.agena create mode 100644 Task/Arbitrary-precision-integers-included-/BBC-BASIC/arbitrary-precision-integers-included-.basic create mode 100644 Task/Arbitrary-precision-integers-included-/Pluto/arbitrary-precision-integers-included-.pluto create mode 100644 Task/Arbitrary-precision-integers-included-/Rhombus/arbitrary-precision-integers-included-.rhombus create mode 100644 Task/Arithmetic-Complex/ArkScript/arithmetic-complex.ark create mode 100644 Task/Arithmetic-Complex/DuckDB/arithmetic-complex.duckdb create mode 100644 Task/Arithmetic-Complex/FutureBasic/arithmetic-complex.basic create mode 100644 Task/Arithmetic-Complex/Pluto/arithmetic-complex.pluto create mode 100644 Task/Arithmetic-Integer/ArkScript/arithmetic-integer.ark create mode 100644 Task/Arithmetic-Integer/DuckDB/arithmetic-integer.duckdb create mode 100644 Task/Arithmetic-Integer/Pluto/arithmetic-integer.pluto create mode 100644 Task/Arithmetic-Integer/RISC-V-Assembly/arithmetic-integer.asm create mode 100644 Task/Arithmetic-Integer/Red/arithmetic-integer.red create mode 100644 Task/Arithmetic-Integer/TAV/arithmetic-integer.tav create mode 100644 Task/Arithmetic-Rational/Pluto/arithmetic-rational.pluto create mode 100644 Task/Arithmetic-derivative/Bc/arithmetic-derivative.bc create mode 100644 Task/Arithmetic-derivative/Pluto/arithmetic-derivative.pluto create mode 100644 Task/Arithmetic-evaluation/PascalABC.NET/arithmetic-evaluation.pas rename Task/Arithmetic-evaluation/Perl/{arithmetic-evaluation.pl => arithmetic-evaluation-1.pl} (100%) create mode 100644 Task/Arithmetic-evaluation/Perl/arithmetic-evaluation-2.pl create mode 100644 Task/Arithmetic-evaluation/Red/arithmetic-evaluation.red create mode 100644 Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-1.duckdb create mode 100644 Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-2.duckdb create mode 100644 Task/Arithmetic-geometric-mean/Pluto/arithmetic-geometric-mean.pluto create mode 100644 Task/Arithmetic-numbers/DuckDB/arithmetic-numbers.duckdb create mode 100644 Task/Array-concatenation/ArkScript/array-concatenation.ark create mode 100644 Task/Array-concatenation/DuckDB/array-concatenation.duckdb create mode 100644 Task/Array-concatenation/Pluto/array-concatenation.pluto create mode 100644 Task/Array-concatenation/TAV/array-concatenation.tav create mode 100644 Task/Array-length/ArkScript/array-length.ark create mode 100644 Task/Array-length/DuckDB/array-length.duckdb create mode 100644 Task/Array-length/Maxima/array-length.maxima create mode 100644 Task/Array-length/TAV/array-length.tav create mode 100644 Task/Array-length/Tcl/array-length-1.tcl create mode 100644 Task/Array-length/Tcl/array-length-2.tcl create mode 100644 Task/Array-length/Tcl/array-length-3.tcl create mode 100644 Task/Array-length/Tcl/array-length-4.tcl create mode 100644 Task/Array-length/Tcl/array-length-5.tcl create mode 100644 Task/Array-length/Tcl/array-length-6.tcl create mode 100644 Task/Array-length/Tcl/array-length-7.tcl delete mode 100644 Task/Array-length/Tcl/array-length.tcl create mode 100644 Task/Arrays/DuckDB/arrays.duckdb create mode 100644 Task/Arrays/Extended-Color-BASIC/arrays.basic create mode 100644 Task/Arrays/Haxe/arrays.haxe create mode 100644 Task/Arrays/Pluto/arrays.pluto create mode 100644 Task/Arrays/Unicon/arrays-1.unicon create mode 100644 Task/Arrays/Unicon/arrays-2.unicon create mode 100644 Task/Arrays/Unicon/arrays-3.unicon create mode 100644 Task/Arrays/Zig/arrays-1.zig create mode 100644 Task/Arrays/Zig/arrays-2.zig create mode 100644 Task/Ascending-primes/ArkScript/ascending-primes.ark create mode 100644 Task/Ascending-primes/Pluto/ascending-primes.pluto create mode 100644 Task/Associative-array-Creation/ArkScript/associative-array-creation.ark create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-1.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-2.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-3.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-4.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-5.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-6.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-7.duckdb create mode 100644 Task/Associative-array-Creation/DuckDB/associative-array-creation-8.duckdb create mode 100644 Task/Associative-array-Creation/Haxe/associative-array-creation.haxe create mode 100644 Task/Associative-array-Creation/Pluto/associative-array-creation.pluto delete mode 100644 Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx delete mode 100644 Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx create mode 100644 Task/Associative-array-Creation/REXX/associative-array-creation.rexx delete mode 100644 Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh rename Task/Associative-array-Creation/UNIX-Shell/{associative-array-creation-1.sh => associative-array-creation.sh} (100%) create mode 100644 Task/Associative-array-Creation/Zig/associative-array-creation-1.zig create mode 100644 Task/Associative-array-Creation/Zig/associative-array-creation-2.zig create mode 100644 Task/Associative-array-Iteration/ArkScript/associative-array-iteration.ark create mode 100644 Task/Associative-array-Iteration/DuckDB/associative-array-iteration.duckdb delete mode 100644 Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena rename Task/Associative-array-Iteration/Elena/{associative-array-iteration-2.elena => associative-array-iteration.elena} (100%) create mode 100644 Task/Associative-array-Iteration/Haxe/associative-array-iteration.haxe create mode 100644 Task/Associative-array-Iteration/Pluto/associative-array-iteration.pluto create mode 100644 Task/Associative-array-Iteration/TAV/associative-array-iteration.tav create mode 100644 Task/Associative-array-Iteration/Tcl/associative-array-iteration-3.tcl create mode 100644 Task/Associative-array-Iteration/Tcl/associative-array-iteration-4.tcl create mode 100644 Task/Associative-array-Iteration/Tcl/associative-array-iteration-5.tcl create mode 100644 Task/Associative-array-Iteration/Zig/associative-array-iteration-1.zig create mode 100644 Task/Associative-array-Iteration/Zig/associative-array-iteration-2.zig create mode 100644 Task/Associative-array-Merging/DuckDB/associative-array-merging-1.duckdb create mode 100644 Task/Associative-array-Merging/DuckDB/associative-array-merging-2.duckdb create mode 100644 Task/Associative-array-Merging/DuckDB/associative-array-merging-3.duckdb create mode 100644 Task/Associative-array-Merging/Fortran/associative-array-merging.f create mode 100644 Task/Associative-array-Merging/Pluto/associative-array-merging.pluto create mode 100644 Task/Attractive-numbers/Agena/attractive-numbers.agena create mode 100644 Task/Attractive-numbers/Pluto/attractive-numbers.pluto create mode 100644 Task/Averages-Arithmetic-mean/Apple/averages-arithmetic-mean.apple create mode 100644 Task/Averages-Arithmetic-mean/DuckDB/averages-arithmetic-mean.duckdb create mode 100644 Task/Averages-Arithmetic-mean/Pluto/averages-arithmetic-mean.pluto create mode 100644 Task/Averages-Mean-angle/DuckDB/averages-mean-angle.duckdb create mode 100644 Task/Averages-Mean-time-of-day/DuckDB/averages-mean-time-of-day.duckdb create mode 100644 Task/Averages-Mean-time-of-day/FutureBasic/averages-mean-time-of-day.basic create mode 100644 Task/Averages-Median/Pluto/averages-median.pluto create mode 100644 Task/Averages-Mode/DuckDB/averages-mode-1.duckdb create mode 100644 Task/Averages-Mode/DuckDB/averages-mode-2.duckdb create mode 100644 Task/Averages-Mode/DuckDB/averages-mode-3.duckdb create mode 100644 Task/Averages-Mode/DuckDB/averages-mode-4.duckdb create mode 100644 Task/Averages-Mode/DuckDB/averages-mode-5.duckdb create mode 100644 Task/Averages-Mode/DuckDB/averages-mode-6.duckdb create mode 100644 Task/Averages-Pythagorean-means/Apple/averages-pythagorean-means.apple create mode 100644 Task/Averages-Pythagorean-means/DuckDB/averages-pythagorean-means.duckdb create mode 100644 Task/Averages-Pythagorean-means/Pluto/averages-pythagorean-means.pluto create mode 100644 Task/Averages-Root-mean-square/Pluto/averages-root-mean-square.pluto create mode 100644 Task/Averages-Root-mean-square/TAV/averages-root-mean-square.tav create mode 100644 Task/B-zier-curves-Intersections/JavaScript/b-zier-curves-intersections.js create mode 100644 Task/Babbage-problem/AutoLISP/babbage-problem.l create mode 100644 Task/Babbage-problem/DuckDB/babbage-problem-1.duckdb create mode 100644 Task/Babbage-problem/DuckDB/babbage-problem-2.duckdb create mode 100644 Task/Babylonian-spiral/FreeBASIC/babylonian-spiral.basic create mode 100644 Task/Balanced-brackets/ArkScript/balanced-brackets.ark create mode 100644 Task/Balanced-brackets/AutoLISP/balanced-brackets.l create mode 100644 Task/Balanced-brackets/Nom/balanced-brackets.num create mode 100644 Task/Balanced-brackets/Pluto/balanced-brackets.pluto create mode 100644 Task/Balanced-ternary/JavaScript/balanced-ternary.js create mode 100644 Task/Base64-decode-data/Pluto/base64-decode-data.pluto create mode 100644 Task/Base64-decode-data/Zig/base64-decode-data.zig create mode 100644 Task/Bell-numbers/Pluto/bell-numbers.pluto create mode 100644 Task/Benfords-law/DuckDB/benfords-law.duckdb create mode 100644 Task/Best-shuffle/Factor/best-shuffle.factor create mode 100644 Task/Best-shuffle/YAMLScript/best-shuffle.ys create mode 100644 Task/Bifid-cipher/Zig/bifid-cipher.zig create mode 100644 Task/Bin-given-limits/DuckDB/bin-given-limits-1.duckdb create mode 100644 Task/Bin-given-limits/DuckDB/bin-given-limits-2.duckdb create mode 100644 Task/Binary-digits/DuckDB/binary-digits-1.duckdb create mode 100644 Task/Binary-digits/DuckDB/binary-digits-2.duckdb create mode 100644 Task/Binary-digits/Haxe/binary-digits.haxe rename Task/Binary-digits/Icon/{binary-digits.icon => binary-digits-1.icon} (100%) create mode 100644 Task/Binary-digits/Icon/binary-digits-2.icon create mode 100644 Task/Binary-digits/RISC-V-Assembly/binary-digits.asm create mode 100644 Task/Bioinformatics-base-count/DuckDB/bioinformatics-base-count.duckdb create mode 100644 Task/Bioinformatics-base-count/PascalABC.NET/bioinformatics-base-count.pas create mode 100644 Task/Biorhythms/Ada/biorhythms.ada create mode 100644 Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic create mode 100644 Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm.pluto create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm.pluto create mode 100644 Task/Bitmap/Pluto/bitmap.pluto create mode 100644 Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb create mode 100644 Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb create mode 100644 Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb create mode 100644 Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb create mode 100644 Task/Bitwise-operations/Pluto/bitwise-operations.pluto create mode 100644 Task/Boolean-values/ArkScript/boolean-values.ark create mode 100644 Task/Boolean-values/Haxe/boolean-values.haxe create mode 100644 Task/Boolean-values/Prolog/boolean-values.pro create mode 100644 Task/Boolean-values/Zig/boolean-values.zig create mode 100644 Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.ada create mode 100644 Task/Boyer-Moore-string-search/Dart/boyer-moore-string-search.dart create mode 100644 Task/Boyer-Moore-string-search/FutureBasic/boyer-moore-string-search.basic create mode 100644 Task/Boyer-Moore-string-search/Kotlin/boyer-moore-string-search.kts create mode 100644 Task/Boyer-Moore-string-search/Swift/boyer-moore-string-search.swift create mode 100644 Task/Boyer-Moore-string-search/Zig/boyer-moore-string-search.zig create mode 100644 Task/Break-OO-privacy/Dart/break-oo-privacy.dart create mode 100644 Task/Break-OO-privacy/JavaScript/break-oo-privacy.js create mode 100644 Task/Break-OO-privacy/Rust/break-oo-privacy.rs create mode 100644 Task/Break-OO-privacy/Zig/break-oo-privacy.zig create mode 100644 Task/CRC-32/FutureBasic/crc-32.basic create mode 100644 Task/CRC-32/Pluto/crc-32.pluto create mode 100644 Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb create mode 100644 Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb create mode 100644 Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb create mode 100644 Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num create mode 100644 Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num create mode 100644 Task/CUSIP/R/cusip.r create mode 100644 Task/Caesar-cipher/Pluto/caesar-cipher.pluto create mode 100644 Task/Caesar-cipher/Rhombus/caesar-cipher.rhombus create mode 100644 Task/Calculating-the-value-of-e/ArkScript/calculating-the-value-of-e.ark create mode 100644 Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-1.elena create mode 100644 Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-2.elena delete mode 100644 Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena create mode 100644 Task/Calendar---for-REAL-programmers/Red/calendar---for-real-programmers.red create mode 100644 Task/Calendar/Red/calendar.red create mode 100644 Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.ada create mode 100644 Task/Calkin-Wilf-sequence/Pluto/calkin-wilf-sequence.pluto create mode 100644 Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-1.pluto create mode 100644 Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-2.pluto create mode 100644 Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto create mode 100644 Task/Call-a-function/ArkScript/call-a-function-1.ark create mode 100644 Task/Call-a-function/ArkScript/call-a-function-2.ark create mode 100644 Task/Call-a-function/ArkScript/call-a-function-3.ark create mode 100644 Task/Call-a-function/ArkScript/call-a-function-4.ark create mode 100644 Task/Call-a-function/ArkScript/call-a-function-5.ark create mode 100644 Task/Call-a-function/ArkScript/call-a-function-6.ark create mode 100644 Task/Call-a-function/ArkScript/call-a-function-7.ark create mode 100644 Task/Call-a-function/DuckDB/call-a-function-1.duckdb create mode 100644 Task/Call-a-function/DuckDB/call-a-function-2.duckdb create mode 100644 Task/Call-an-object-method/ArkScript/call-an-object-method.ark create mode 100644 Task/Call-an-object-method/Haxe/call-an-object-method.haxe create mode 100644 Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.ada create mode 100644 Task/Camel-case-and-snake-case/C-sharp/camel-case-and-snake-case.cs create mode 100644 Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math create mode 100644 Task/Camel-case-and-snake-case/Rust/camel-case-and-snake-case.rs create mode 100644 Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig create mode 100644 Task/Canonicalize-CIDR/Ada/canonicalize-cidr.ada create mode 100644 Task/Carmichael-3-strong-pseudoprimes/FutureBasic/carmichael-3-strong-pseudoprimes.basic create mode 100644 Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-1.duckdb create mode 100644 Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-2.duckdb create mode 100644 Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb create mode 100644 Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb create mode 100644 Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas create mode 100644 Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto create mode 100644 Task/Casting-out-nines/Pluto/casting-out-nines.pluto create mode 100644 Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb create mode 100644 Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-2.duckdb create mode 100644 Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f create mode 100644 Task/Catalan-numbers-Pascals-triangle/Objeck/catalan-numbers-pascals-triangle.objeck create mode 100644 Task/Catalan-numbers/DuckDB/catalan-numbers.duckdb create mode 100644 Task/Catamorphism/Apple/catamorphism-1.apple create mode 100644 Task/Catamorphism/Apple/catamorphism-2.apple create mode 100644 Task/Catamorphism/Apple/catamorphism-3.apple create mode 100644 Task/Catamorphism/ArkScript/catamorphism.ark create mode 100644 Task/Catmull-Clark-subdivision-surface/FreeBASIC/catmull-clark-subdivision-surface.basic create mode 100644 Task/Catmull-Clark-subdivision-surface/JavaScript/catmull-clark-subdivision-surface.js create mode 100644 Task/Chaocipher/Swift/chaocipher.swift create mode 100644 Task/Character-codes/Haxe/character-codes.haxe create mode 100644 Task/Character-codes/TAV/character-codes.tav create mode 100644 Task/Check-that-file-exists/ArkScript/check-that-file-exists.ark create mode 100644 Task/Check-that-file-exists/DuckDB/check-that-file-exists.duckdb create mode 100644 Task/Checkpoint-synchronization/JavaScript/checkpoint-synchronization.js create mode 100644 Task/Chinese-zodiac/Fortran/chinese-zodiac.f create mode 100644 Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy create mode 100644 Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig create mode 100644 Task/Cistercian-numerals/C-sharp/cistercian-numerals.cs create mode 100644 Task/Cistercian-numerals/Free-Pascal-Lazarus/cistercian-numerals.pas create mode 100644 Task/Cistercian-numerals/Modula-2/cistercian-numerals.mod2 create mode 100644 Task/Cistercian-numerals/Pascal-P/cistercian-numerals.pas create mode 100644 Task/Cistercian-numerals/XPL0/cistercian-numerals.xpl0 create mode 100644 Task/Classes/Haxe/classes-1.haxe rename Task/Classes/{Haskell/classes-3.hs => Haxe/classes-2.haxe} (100%) create mode 100644 Task/Closures-Value-capture/ArkScript/closures-value-capture.ark create mode 100644 Task/Collections/DuckDB/collections.duckdb create mode 100644 Task/Collections/Pluto/collections.pluto create mode 100644 Task/Color-quantization/FreeBASIC/color-quantization.basic create mode 100644 Task/Combinations-with-repetitions/DuckDB/combinations-with-repetitions.duckdb create mode 100644 Task/Combinations-with-repetitions/PascalABC.NET/combinations-with-repetitions.pas create mode 100644 Task/Combinations-with-repetitions/Pluto/combinations-with-repetitions.pluto create mode 100644 Task/Combinations/DuckDB/combinations.duckdb create mode 100644 Task/Combinations/Pluto/combinations.pluto create mode 100644 Task/Command-line-arguments/Pluto/command-line-arguments.pluto create mode 100644 Task/Command-line-arguments/TAV/command-line-arguments.tav create mode 100644 Task/Comments/ArkScript/comments.ark create mode 100644 Task/Comments/Ballerina/comments.ballerina create mode 100644 Task/Comments/Idris/comments.idris create mode 100644 Task/Comments/Janet/comments.janet create mode 100644 Task/Comments/Odin/comments.odin create mode 100644 Task/Comments/Pluto/comments.pluto create mode 100644 Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-1.duckdb create mode 100644 Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-2.duckdb create mode 100644 Task/Compare-a-list-of-strings/DuckDB/compare-a-list-of-strings-3.duckdb create mode 100644 Task/Compare-a-list-of-strings/Ring/compare-a-list-of-strings.ring rename Task/Compare-a-list-of-strings/Tcl/{compare-a-list-of-strings.tcl => compare-a-list-of-strings-1.tcl} (100%) create mode 100644 Task/Compare-a-list-of-strings/Tcl/compare-a-list-of-strings-2.tcl create mode 100644 Task/Compare-length-of-two-strings/DuckDB/compare-length-of-two-strings-1.duckdb create mode 100644 Task/Compare-length-of-two-strings/DuckDB/compare-length-of-two-strings-2.duckdb create mode 100644 Task/Compare-length-of-two-strings/DuckDB/compare-length-of-two-strings-3.duckdb create mode 100644 Task/Compare-length-of-two-strings/Pluto/compare-length-of-two-strings.pluto create mode 100644 Task/Compile-time-calculation/V-(Vlang)/compile-time-calculation.v create mode 100644 Task/Compiler-lexical-analyzer/Pluto/compiler-lexical-analyzer.pluto create mode 100644 Task/Compound-data-type/ArkScript/compound-data-type.ark create mode 100644 Task/Compound-data-type/DuckDB/compound-data-type.duckdb create mode 100644 Task/Concurrent-computing/ArkScript/concurrent-computing.ark rename Task/Concurrent-computing/Rust/{concurrent-computing.rs => concurrent-computing-1.rs} (100%) create mode 100644 Task/Concurrent-computing/Rust/concurrent-computing-2.rs create mode 100644 Task/Concurrent-computing/Rust/concurrent-computing-3.rs create mode 100644 Task/Conditional-structures/ArkScript/conditional-structures.ark create mode 100644 Task/Conditional-structures/DuckDB/conditional-structures-1.duckdb create mode 100644 Task/Conditional-structures/DuckDB/conditional-structures-2.duckdb create mode 100644 Task/Conditional-structures/DuckDB/conditional-structures-3.duckdb create mode 100644 Task/Conditional-structures/Pluto/conditional-structures.pluto create mode 100644 Task/Conditional-structures/TAV/conditional-structures-1.tav create mode 100644 Task/Conditional-structures/TAV/conditional-structures-2.tav create mode 100644 Task/Conditional-structures/TAV/conditional-structures-3.tav create mode 100644 Task/Constrained-genericity/C++/constrained-genericity-1.cpp rename Task/Constrained-genericity/C++/{constrained-genericity.cpp => constrained-genericity-2.cpp} (83%) rename Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Julia/{continued-fraction-arithmetic-construct-from-rational-number.jl => continued-fraction-arithmetic-construct-from-rational-number-1.jl} (100%) create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Julia/continued-fraction-arithmetic-construct-from-rational-number-2.jl create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Pluto/continued-fraction-arithmetic-construct-from-rational-number.pluto create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Dart/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.dart create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/JavaScript/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.js create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Perl/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.pl create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Rust/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.rs create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Scala/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.scala create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Swift/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.swift create mode 100644 Task/Continued-fraction/Dart/continued-fraction.dart create mode 100644 Task/Continued-fraction/JavaScript/continued-fraction.js create mode 100644 Task/Continued-fraction/R/continued-fraction.r create mode 100644 Task/Convert-decimal-number-to-rational/Pluto/convert-decimal-number-to-rational.pluto create mode 100644 Task/Convert-seconds-to-compound-duration/DuckDB/convert-seconds-to-compound-duration.duckdb create mode 100644 Task/Conways-Game-of-Life/ArkScript/conways-game-of-life.ark create mode 100644 Task/Conways-Game-of-Life/YAMLScript/conways-game-of-life.ys create mode 100644 Task/Copy-a-string/ArkScript/copy-a-string.ark create mode 100644 Task/Copy-a-string/DuckDB/copy-a-string.duckdb create mode 100644 Task/Copy-a-string/Extended-Color-BASIC/copy-a-string.basic create mode 100644 Task/Copy-a-string/TAV/copy-a-string.tav create mode 100644 Task/Count-in-octal/Pluto/count-in-octal.pluto create mode 100644 Task/Count-occurrences-of-a-substring/DuckDB/count-occurrences-of-a-substring.duckdb create mode 100644 Task/Count-the-coins/Pluto/count-the-coins.pluto create mode 100644 Task/Cramers-rule/R/cramers-rule.r create mode 100644 Task/Create-a-file/Pluto/create-a-file-1.pluto create mode 100644 Task/Create-a-file/Pluto/create-a-file-2.pluto create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/DuckDB/create-a-two-dimensional-array-at-runtime.duckdb create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/TAV/create-a-two-dimensional-array-at-runtime.tav create mode 100644 Task/Cumulative-standard-deviation/DuckDB/cumulative-standard-deviation.duckdb create mode 100644 Task/Cumulative-standard-deviation/Zig/cumulative-standard-deviation.zig create mode 100644 Task/Currency/DuckDB/currency.duckdb create mode 100644 Task/Currency/EasyLang/currency.easy create mode 100644 Task/Currying/ArkScript/currying.ark create mode 100644 Task/Currying/Pluto/currying.pluto create mode 100644 Task/Currying/Red/currying.red create mode 100644 Task/Curzon-numbers/R/curzon-numbers.r create mode 100644 Task/Cyclops-numbers/Rust/cyclops-numbers.rs create mode 100644 Task/Cyclops-numbers/Zig/cyclops-numbers.zig create mode 100644 Task/Cyclotomic-polynomial/Fortran/cyclotomic-polynomial.f create mode 100644 Task/Damm-algorithm/Prolog/damm-algorithm.pro rename Task/Date-format/REBOL/{date-format.rebol => date-format-1.rebol} (100%) create mode 100644 Task/Date-format/REBOL/date-format-2.rebol create mode 100644 Task/Date-manipulation/ALGOL-68/date-manipulation.alg create mode 100644 Task/Day-of-the-week/DuckDB/day-of-the-week-1.duckdb create mode 100644 Task/Day-of-the-week/DuckDB/day-of-the-week-2.duckdb create mode 100644 Task/Day-of-the-week/DuckDB/day-of-the-week-3.duckdb create mode 100644 Task/Deal-cards-for-FreeCell/FutureBasic/deal-cards-for-freecell.basic create mode 100644 Task/Death-Star/EasyLang/death-star.easy create mode 100644 Task/Deconvolution-1D/JavaScript/deconvolution-1d.js create mode 100644 Task/Deconvolution-1D/Rust/deconvolution-1d.rs create mode 100644 Task/Deconvolution-1D/Zig/deconvolution-1d.zig create mode 100644 Task/Deconvolution-2D+/JavaScript/deconvolution-2d+.js create mode 100644 Task/Deconvolution-2D+/Rust/deconvolution-2d+.rs create mode 100644 Task/Deepcopy/Ada/deepcopy.ada create mode 100644 Task/Define-a-primitive-data-type/DuckDB/define-a-primitive-data-type.duckdb create mode 100644 Task/Delete-a-file/ArkScript/delete-a-file.ark create mode 100644 Task/Delete-a-file/Maxima/delete-a-file.maxima create mode 100644 Task/Delete-a-file/Pluto/delete-a-file.pluto create mode 100644 Task/Demings-funnel/FutureBasic/demings-funnel.basic create mode 100644 Task/Department-numbers/Bc/department-numbers.bc create mode 100644 Task/Department-numbers/Crystal/department-numbers.cr create mode 100644 Task/Descending-primes/Pluto/descending-primes.pluto create mode 100644 Task/Detect-division-by-zero/DuckDB/detect-division-by-zero.duckdb create mode 100644 Task/Determinant-and-permanent/DuckDB/determinant-and-permanent.duckdb create mode 100644 Task/Determinant-and-permanent/Elixir/determinant-and-permanent.ex create mode 100644 Task/Determinant-and-permanent/Erlang/determinant-and-permanent.erl create mode 100644 Task/Determinant-and-permanent/Zig/determinant-and-permanent.zig create mode 100644 Task/Determine-if-a-string-has-all-the-same-characters/DuckDB/determine-if-a-string-has-all-the-same-characters.duckdb create mode 100644 Task/Determine-if-a-string-has-all-unique-characters/DuckDB/determine-if-a-string-has-all-unique-characters.duckdb create mode 100644 Task/Determine-if-a-string-is-collapsible/DuckDB/determine-if-a-string-is-collapsible.duckdb create mode 100644 Task/Determine-if-a-string-is-numeric/DuckDB/determine-if-a-string-is-numeric.duckdb create mode 100644 Task/Determine-if-a-string-is-numeric/Nom/determine-if-a-string-is-numeric.num create mode 100644 Task/Determine-if-a-string-is-numeric/Pluto/determine-if-a-string-is-numeric.pluto create mode 100644 Task/Determine-if-a-string-is-numeric/Tcl/determine-if-a-string-is-numeric-1.tcl create mode 100644 Task/Determine-if-a-string-is-numeric/Tcl/determine-if-a-string-is-numeric-2.tcl delete mode 100644 Task/Determine-if-a-string-is-numeric/Tcl/determine-if-a-string-is-numeric.tcl create mode 100644 Task/Determine-if-a-string-is-squeezable/DuckDB/determine-if-a-string-is-squeezable.duckdb create mode 100644 Task/Determine-if-two-triangles-overlap/Rust/determine-if-two-triangles-overlap.rs create mode 100644 Task/Determine-sentence-type/DuckDB/determine-sentence-type.duckdb create mode 100644 Task/Digital-root/DuckDB/digital-root.duckdb create mode 100644 Task/Dijkstras-algorithm/Dart/dijkstras-algorithm.dart create mode 100644 Task/Dijkstras-algorithm/R/dijkstras-algorithm.r create mode 100644 Task/Disarium-numbers/Agena/disarium-numbers.agena create mode 100644 Task/Disarium-numbers/Fortran/disarium-numbers.f create mode 100644 Task/Disarium-numbers/Frink/disarium-numbers.frink create mode 100644 Task/Disarium-numbers/Objeck/disarium-numbers.objeck create mode 100644 Task/Disarium-numbers/Pluto/disarium-numbers.pluto create mode 100644 Task/Display-a-linear-combination/Fortran/display-a-linear-combination.f create mode 100644 Task/Display-a-linear-combination/Pluto/display-a-linear-combination.pluto create mode 100644 Task/Distance-and-Bearing/Go/distance-and-bearing.go create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/ALGOL-68/distribution-of-0-digits-in-factorial-series.alg create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/EasyLang/distribution-of-0-digits-in-factorial-series.easy create mode 100644 Task/Distribution-of-0-digits-in-factorial-series/Pluto/distribution-of-0-digits-in-factorial-series.pluto create mode 100644 Task/Diversity-prediction-theorem/DuckDB/diversity-prediction-theorem.duckdb create mode 100644 Task/Documentation/DuckDB/documentation-1.duckdb create mode 100644 Task/Documentation/DuckDB/documentation-2.duckdb create mode 100644 Task/Documentation/DuckDB/documentation-3.duckdb create mode 100644 Task/Documentation/Unicon/documentation-1.unicon create mode 100644 Task/Documentation/Unicon/documentation-2.unicon create mode 100644 Task/Documentation/Unicon/documentation-3.unicon delete mode 100644 Task/Documentation/Unicon/documentation.unicon create mode 100644 Task/Dominoes/FreeBASIC/dominoes-1.basic create mode 100644 Task/Dominoes/FreeBASIC/dominoes-2.basic create mode 100644 Task/Dot-product/Apple/dot-product.apple create mode 100644 Task/Dot-product/DuckDB/dot-product-1.duckdb create mode 100644 Task/Dot-product/DuckDB/dot-product-2.duckdb create mode 100644 Task/Dot-product/DuckDB/dot-product-3.duckdb create mode 100644 Task/Dot-product/DuckDB/dot-product-4.duckdb create mode 100644 Task/Doubly-linked-list-Definition/Pluto/doubly-linked-list-definition.pluto create mode 100644 Task/Doubly-linked-list-Element-definition/Pluto/doubly-linked-list-element-definition.pluto create mode 100644 Task/Doubly-linked-list-Traversal/Pluto/doubly-linked-list-traversal.pluto create mode 100644 Task/Dragon-curve/YAMLScript/dragon-curve.ys create mode 100644 Task/Draw-a-sphere/EasyLang/draw-a-sphere.easy create mode 100644 Task/Duffinian-numbers/Rust/duffinian-numbers.rs create mode 100644 Task/Dutch-national-flag-problem/Pluto/dutch-national-flag-problem.pluto create mode 100644 Task/Dynamic-variable-names/DuckDB/dynamic-variable-names.duckdb create mode 100644 Task/EKG-sequence-convergence/EasyLang/ekg-sequence-convergence.easy create mode 100644 Task/EKG-sequence-convergence/Fortran/ekg-sequence-convergence.f create mode 100644 Task/Earliest-difference-between-prime-gaps/EasyLang/earliest-difference-between-prime-gaps.easy create mode 100644 Task/Eertree/Zig/eertree.zig create mode 100644 Task/Egyptian-division/Fortran/egyptian-division.f create mode 100644 Task/Element-wise-operations/DuckDB/element-wise-operations-1.duckdb create mode 100644 Task/Element-wise-operations/DuckDB/element-wise-operations-2.duckdb create mode 100644 Task/Elementary-cellular-automaton-Infinite-length/EasyLang/elementary-cellular-automaton-infinite-length.easy create mode 100644 Task/Elliptic-Curve-Digital-Signature-Algorithm/Zig/elliptic-curve-digital-signature-algorithm.zig create mode 100644 Task/Elliptic-curve-arithmetic/Rust/elliptic-curve-arithmetic.rs create mode 100644 Task/Elliptic-curve-arithmetic/Zig/elliptic-curve-arithmetic.zig create mode 100644 Task/Empty-directory/ArkScript/empty-directory.ark create mode 100644 Task/Empty-program/ArkScript/empty-program-1.ark create mode 100644 Task/Empty-program/ArkScript/empty-program-2.ark create mode 100644 Task/Empty-string/ArkScript/empty-string.ark create mode 100644 Task/Empty-string/DuckDB/empty-string.duckdb create mode 100644 Task/Empty-string/Nom/empty-string.num create mode 100644 Task/Empty-string/TAV/empty-string.tav create mode 100644 Task/Enforced-immutability/ArkScript/enforced-immutability.ark create mode 100644 Task/Entropy-Narcissist/AutoLISP/entropy-narcissist.l create mode 100644 Task/Entropy/AutoLISP/entropy.l create mode 100644 Task/Entropy/DuckDB/entropy.duckdb create mode 100644 Task/Enumerations/DuckDB/enumerations.duckdb create mode 100644 Task/Equilibrium-index/DuckDB/equilibrium-index.duckdb create mode 100644 Task/Erd-s-Nicolas-numbers/Mathematica/erd-s-nicolas-numbers.math create mode 100644 Task/Erd-s-Selfridge-categorization-of-primes/EasyLang/erd-s-selfridge-categorization-of-primes.easy create mode 100644 Task/Euler-method/DuckDB/euler-method.duckdb create mode 100644 Task/Euler-method/FutureBasic/euler-method.basic create mode 100644 Task/Euler-method/Pluto/euler-method.pluto create mode 100644 Task/Eulers-constant-0.5772.../DuckDB/eulers-constant-0.5772....duckdb create mode 100644 Task/Eulers-identity/DuckDB/eulers-identity.duckdb create mode 100644 Task/Eulers-identity/Pluto/eulers-identity.pluto create mode 100644 Task/Evaluate-binomial-coefficients/DuckDB/evaluate-binomial-coefficients.duckdb create mode 100644 Task/Even-or-odd/Adina/even-or-odd-1.adina create mode 100644 Task/Even-or-odd/Adina/even-or-odd-2.adina create mode 100644 Task/Even-or-odd/ArkScript/even-or-odd.ark create mode 100644 Task/Even-or-odd/DuckDB/even-or-odd-1.duckdb create mode 100644 Task/Even-or-odd/DuckDB/even-or-odd-2.duckdb create mode 100644 Task/Even-or-odd/Nom/even-or-odd.num create mode 100644 Task/Even-or-odd/Pluto/even-or-odd.pluto create mode 100644 Task/Even-or-odd/YAMLScript/even-or-odd.ys create mode 100644 Task/Evolutionary-algorithm/Zig/evolutionary-algorithm.zig create mode 100644 Task/Exceptions/C++/exceptions-5.cpp create mode 100644 Task/Exceptions/Phix/exceptions-3.phix rename Task/Exceptions/Tcl/{exceptions.tcl => exceptions-1.tcl} (100%) create mode 100644 Task/Exceptions/Tcl/exceptions-2.tcl create mode 100644 Task/Execute-HQ9+/R/execute-hq9+.r create mode 100644 Task/Execute-a-system-command/Pluto/execute-a-system-command.pluto create mode 100644 Task/Exponentiation-order/DuckDB/exponentiation-order.duckdb create mode 100644 Task/Exponentiation-order/Icon/exponentiation-order.icon create mode 100644 Task/Extend-your-language/ArkScript/extend-your-language.ark create mode 100644 Task/Extend-your-language/Koka/extend-your-language.koka create mode 100644 Task/Extreme-floating-point-values/DuckDB/extreme-floating-point-values-1.duckdb create mode 100644 Task/Extreme-floating-point-values/DuckDB/extreme-floating-point-values-2.duckdb create mode 100644 Task/Factorial-primes/AWK/factorial-primes.awk create mode 100644 Task/Factorial-primes/Agena/factorial-primes.agena create mode 100644 Task/Factorial-primes/Fennel/factorial-primes.fennel create mode 100644 Task/Factorial-primes/Pluto/factorial-primes.pluto create mode 100644 Task/Factorial-primes/R/factorial-primes.r delete mode 100644 Task/Factorial/ALGOL-60/factorial.alg delete mode 100644 Task/Factorial/ALGOL-68/factorial-1.alg delete mode 100644 Task/Factorial/ALGOL-68/factorial-2.alg delete mode 100644 Task/Factorial/ALGOL-68/factorial-3.alg delete mode 100644 Task/Factorial/ALGOL-W/factorial.alg create mode 100644 Task/Factorial/Agena/factorial.agena create mode 100644 Task/Factorial/Apple/factorial-1.apple create mode 100644 Task/Factorial/Apple/factorial-2.apple create mode 100644 Task/Factorial/CBASIC/factorial.basic create mode 100644 Task/Factorial/DuckDB/factorial-1.duckdb create mode 100644 Task/Factorial/DuckDB/factorial-2.duckdb create mode 100644 Task/Factorial/DuckDB/factorial-3.duckdb create mode 100644 Task/Factorial/Fennel/factorial.fennel create mode 100644 Task/Factorial/Mn/factorial.mn create mode 100644 Task/Factorial/Pluto/factorial.pluto create mode 100644 Task/Factorial/Rhombus/factorial-1.rhombus create mode 100644 Task/Factorial/Rhombus/factorial-2.rhombus create mode 100644 Task/Factorial/TAV/factorial.tav create mode 100644 Task/Factorial/Vyxal/factorial-1.vyxal create mode 100644 Task/Factorial/Vyxal/factorial-2.vyxal create mode 100644 Task/Factorial/Vyxal/factorial-3.vyxal create mode 100644 Task/Factorions/Ada/factorions.ada create mode 100644 Task/Factorions/Pluto/factorions.pluto create mode 100644 Task/Factors-of-an-integer/Apple/factors-of-an-integer.apple create mode 100644 Task/Factors-of-an-integer/DuckDB/factors-of-an-integer-1.duckdb create mode 100644 Task/Factors-of-an-integer/DuckDB/factors-of-an-integer-2.duckdb create mode 100644 Task/Factors-of-an-integer/Pluto/factors-of-an-integer.pluto create mode 100644 Task/Factors-of-an-integer/Zig/factors-of-an-integer.zig create mode 100644 Task/Fairshare-between-two-and-more/Bc/fairshare-between-two-and-more.bc create mode 100644 Task/Fairshare-between-two-and-more/DuckDB/fairshare-between-two-and-more.duckdb create mode 100644 Task/Farey-sequence/Pluto/farey-sequence.pluto create mode 100644 Task/Farey-sequence/Zig/farey-sequence.zig create mode 100644 Task/Faulhabers-formula/EasyLang/faulhabers-formula.easy create mode 100644 Task/Faulhabers-triangle/EasyLang/faulhabers-triangle.easy create mode 100644 Task/Faulhabers-triangle/Rust/faulhabers-triangle.rs create mode 100644 Task/Feigenbaum-constant-calculation/DuckDB/feigenbaum-constant-calculation.duckdb create mode 100644 Task/Feigenbaum-constant-calculation/Pluto/feigenbaum-constant-calculation.pluto create mode 100644 Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-6.jl create mode 100644 Task/Fibonacci-n-step-number-sequences/R/fibonacci-n-step-number-sequences.r create mode 100644 Task/Fibonacci-sequence/ArkScript/fibonacci-sequence-1.ark create mode 100644 Task/Fibonacci-sequence/ArkScript/fibonacci-sequence-2.ark create mode 100644 Task/Fibonacci-sequence/DuckDB/fibonacci-sequence-1.duckdb create mode 100644 Task/Fibonacci-sequence/DuckDB/fibonacci-sequence-2.duckdb create mode 100644 Task/Fibonacci-sequence/DuckDB/fibonacci-sequence-3.duckdb create mode 100644 Task/Fibonacci-sequence/DuckDB/fibonacci-sequence-4.duckdb create mode 100644 Task/Fibonacci-sequence/Pluto/fibonacci-sequence.pluto create mode 100644 Task/Fibonacci-sequence/Rhombus/fibonacci-sequence-1.rhombus create mode 100644 Task/Fibonacci-sequence/Rhombus/fibonacci-sequence-2.rhombus create mode 100644 Task/Fibonacci-sequence/TAV/fibonacci-sequence-1.tav create mode 100644 Task/Fibonacci-sequence/TAV/fibonacci-sequence-2.tav create mode 100644 Task/Fibonacci-word-fractal/EasyLang/fibonacci-word-fractal.easy create mode 100644 Task/File-input-output/DuckDB/file-input-output.duckdb create mode 100644 Task/Filter/Apple/filter-1.apple create mode 100644 Task/Filter/Apple/filter-2.apple create mode 100644 Task/Filter/DuckDB/filter-1.duckdb create mode 100644 Task/Filter/DuckDB/filter-2.duckdb create mode 100644 Task/Filter/DuckDB/filter-3.duckdb create mode 100644 Task/Filter/DuckDB/filter-4.duckdb create mode 100644 Task/Filter/DuckDB/filter-5.duckdb create mode 100644 Task/Filter/DuckDB/filter-6.duckdb create mode 100644 Task/Filter/DuckDB/filter-7.duckdb create mode 100644 Task/Filter/Pluto/filter.pluto create mode 100644 Task/Find-Chess960-starting-position-identifier/EasyLang/find-chess960-starting-position-identifier.easy create mode 100644 Task/Find-duplicate-files/Ada/find-duplicate-files.ada create mode 100644 Task/Find-duplicate-files/FreeBASIC/find-duplicate-files.basic create mode 100644 Task/Find-largest-left-truncatable-prime-in-a-given-base/FreeBASIC/find-largest-left-truncatable-prime-in-a-given-base.basic create mode 100644 Task/Find-limit-of-recursion/DuckDB/find-limit-of-recursion.duckdb create mode 100644 Task/Find-limit-of-recursion/FutureBasic/find-limit-of-recursion.basic delete mode 100644 Task/Find-limit-of-recursion/REXX/find-limit-of-recursion-1.rexx delete mode 100644 Task/Find-limit-of-recursion/REXX/find-limit-of-recursion-2.rexx create mode 100644 Task/Find-limit-of-recursion/REXX/find-limit-of-recursion.rexx create mode 100644 Task/Find-the-last-Sunday-of-each-month/DuckDB/find-the-last-sunday-of-each-month.duckdb create mode 100644 Task/Five-weekends/DuckDB/five-weekends.duckdb create mode 100644 Task/Five-weekends/FutureBasic/five-weekends.basic create mode 100644 Task/Five-weekends/Red/five-weekends.red create mode 100644 Task/Fixed-length-records/DuckDB/fixed-length-records.duckdb create mode 100644 Task/FizzBuzz/ArkScript/fizzbuzz.ark delete mode 100644 Task/FizzBuzz/J/fizzbuzz-11.j create mode 100644 Task/FizzBuzz/Pascal-P/fizzbuzz.pas create mode 100644 Task/FizzBuzz/Pluto/fizzbuzz.pluto create mode 100644 Task/FizzBuzz/Rhombus/fizzbuzz.rhombus create mode 100644 Task/FizzBuzz/Vyxal/fizzbuzz.vyxal create mode 100644 Task/Flatten-a-list/ArkScript/flatten-a-list.ark create mode 100644 Task/Flatten-a-list/DuckDB/flatten-a-list.duckdb create mode 100644 Task/Flipping-bits-game/R/flipping-bits-game.r create mode 100644 Task/Floyd-Warshall-algorithm/Dart/floyd-warshall-algorithm.dart create mode 100644 Task/Floyd-Warshall-algorithm/Erlang/floyd-warshall-algorithm.erl create mode 100644 Task/Floyd-Warshall-algorithm/Pluto/floyd-warshall-algorithm.pluto create mode 100644 Task/Floyd-Warshall-algorithm/R/floyd-warshall-algorithm.r create mode 100644 Task/Floyd-Warshall-algorithm/Swift/floyd-warshall-algorithm.swift create mode 100644 Task/Formatted-numeric-output/DuckDB/formatted-numeric-output.duckdb create mode 100644 Task/Formatted-numeric-output/Pluto/formatted-numeric-output.pluto create mode 100644 Task/Formatted-numeric-output/TAV/formatted-numeric-output.tav create mode 100644 Task/Forward-difference/DuckDB/forward-difference.duckdb create mode 100644 Task/Fraction-reduction/EasyLang/fraction-reduction.easy create mode 100644 Task/Fractran/R/fractran.r create mode 100644 Task/Fractran/Rust/fractran.rs create mode 100644 Task/French-Republican-calendar/EasyLang/french-republican-calendar.easy create mode 100644 Task/French-Republican-calendar/Fortran/french-republican-calendar.f create mode 100644 Task/Function-definition/ArkScript/function-definition.ark create mode 100644 Task/Function-definition/DuckDB/function-definition-1.duckdb create mode 100644 Task/Function-definition/DuckDB/function-definition-2.duckdb create mode 100644 Task/Function-definition/Pluto/function-definition.pluto create mode 100644 Task/Function-prototype/EasyLang/function-prototype.easy create mode 100644 Task/GUI-component-interaction/FuncSug/gui-component-interaction.funcsug create mode 100644 Task/GUI-enabling-disabling-of-controls/FuncSug/gui-enabling-disabling-of-controls.funcsug create mode 100644 Task/Gamma-function/DuckDB/gamma-function.duckdb create mode 100644 Task/Gamma-function/FutureBasic/gamma-function.basic create mode 100644 Task/Gamma-function/Pluto/gamma-function.pluto create mode 100644 Task/Gapful-numbers/DuckDB/gapful-numbers.duckdb create mode 100644 Task/Gaussian-elimination/FutureBasic/gaussian-elimination.basic create mode 100644 Task/Generate-lower-case-ASCII-alphabet/DuckDB/generate-lower-case-ascii-alphabet-1.duckdb create mode 100644 Task/Generate-lower-case-ASCII-alphabet/DuckDB/generate-lower-case-ascii-alphabet-2.duckdb create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Pluto/generate-lower-case-ascii-alphabet.pluto rename Task/Generator-Exponential/Icon/{generator-exponential.icon => generator-exponential-1.icon} (100%) create mode 100644 Task/Generator-Exponential/Icon/generator-exponential-2.icon create mode 100644 Task/Generic-swap/DuckDB/generic-swap.duckdb create mode 100644 Task/Giuga-numbers/Agena/giuga-numbers.agena create mode 100644 Task/Giuga-numbers/Pluto/giuga-numbers.pluto create mode 100644 Task/Giuga-numbers/R/giuga-numbers.r create mode 100644 Task/Goldbachs-comet/Agena/goldbachs-comet.agena create mode 100644 Task/Goldbachs-comet/Fennel/goldbachs-comet.fennel create mode 100644 Task/Goldbachs-comet/Pluto/goldbachs-comet.pluto create mode 100644 Task/Golden-ratio-Convergence/DuckDB/golden-ratio-convergence.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-1.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-2.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-3.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-4.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-5.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-6.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-7.duckdb create mode 100644 Task/Gotchas/DuckDB/gotchas-8.duckdb create mode 100644 Task/Gray-code/Zig/gray-code.zig create mode 100644 Task/Greatest-common-divisor/DuckDB/greatest-common-divisor.duckdb create mode 100644 Task/Greatest-common-divisor/Pluto/greatest-common-divisor.pluto create mode 100644 Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-1.duckdb create mode 100644 Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-2.duckdb create mode 100644 Task/Greatest-element-of-a-list/DuckDB/greatest-element-of-a-list-3.duckdb create mode 100644 Task/Greatest-element-of-a-list/Pluto/greatest-element-of-a-list.pluto create mode 100644 Task/Greatest-element-of-a-list/TAV/greatest-element-of-a-list.tav create mode 100644 Task/Greatest-subsequential-sum/DuckDB/greatest-subsequential-sum.duckdb create mode 100644 Task/Greedy-algorithm-for-Egyptian-fractions/R/greedy-algorithm-for-egyptian-fractions.r create mode 100644 Task/Guess-the-number-With-feedback-player-/FutureBasic/guess-the-number-with-feedback-player-.basic create mode 100644 Task/Guess-the-number-With-feedback/Rhombus/guess-the-number-with-feedback.rhombus create mode 100644 Task/Guess-the-number-With-feedback/TAV/guess-the-number-with-feedback.tav create mode 100644 Task/HTTP/DuckDB/http.duckdb create mode 100644 Task/HTTPS-Authenticated/DuckDB/https-authenticated.duckdb create mode 100644 Task/HTTPS-Client-authenticated/Objeck/https-client-authenticated.objeck create mode 100644 Task/HTTPS/DuckDB/https.duckdb create mode 100644 Task/HTTPS/TAV/https.tav create mode 100644 Task/Hailstone-sequence/DuckDB/hailstone-sequence.duckdb create mode 100644 Task/Hailstone-sequence/Pluto/hailstone-sequence.pluto create mode 100644 Task/Halt-and-catch-fire/Pluto/halt-and-catch-fire.pluto create mode 100644 Task/Halt-and-catch-fire/TAV/halt-and-catch-fire.tav create mode 100644 Task/Hamming-numbers/FutureBasic/hamming-numbers.basic create mode 100644 Task/Happy-numbers/Frink/happy-numbers.frink rename Task/Happy-numbers/REXX/{happy-numbers.rexx => happy-numbers-1.rexx} (100%) create mode 100644 Task/Happy-numbers/REXX/happy-numbers-2.rexx create mode 100644 Task/Harmonic-series/Ada/harmonic-series.ada create mode 100644 Task/Harmonic-series/DuckDB/harmonic-series.duckdb create mode 100644 Task/Hash-from-two-arrays/Common-Lisp/hash-from-two-arrays-3.lisp create mode 100644 Task/Hash-from-two-arrays/DuckDB/hash-from-two-arrays.duckdb create mode 100644 Task/Hash-from-two-arrays/EasyLang/hash-from-two-arrays.easy create mode 100644 Task/Hash-from-two-arrays/Maxima/hash-from-two-arrays.maxima create mode 100644 Task/Hash-from-two-arrays/Pluto/hash-from-two-arrays.pluto create mode 100644 Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-3.tcl rename Task/Hash-from-two-arrays/UNIX-Shell/{hash-from-two-arrays.sh => hash-from-two-arrays-1.sh} (92%) create mode 100644 Task/Hash-from-two-arrays/UNIX-Shell/hash-from-two-arrays-2.sh create mode 100644 Task/Hash-join/DuckDB/hash-join.duckdb create mode 100644 Task/Haversine-formula/DuckDB/haversine-formula.duckdb create mode 100644 Task/Hello-world-Graphical/TAV/hello-world-graphical.tav create mode 100644 Task/Hello-world-Line-printer/ArkScript/hello-world-line-printer.ark create mode 100644 Task/Hello-world-Newbie/RISC-V-Assembly/hello-world-newbie.asm create mode 100644 Task/Hello-world-Newline-omission/ArkScript/hello-world-newline-omission.ark create mode 100644 Task/Hello-world-Newline-omission/Pluto/hello-world-newline-omission.pluto create mode 100644 Task/Hello-world-Newline-omission/Prolog/hello-world-newline-omission.pro create mode 100644 Task/Hello-world-Standard-error/Pluto/hello-world-standard-error.pluto create mode 100644 Task/Hello-world-Text/Adina/hello-world-text-1.adina create mode 100644 Task/Hello-world-Text/Adina/hello-world-text-2.adina create mode 100644 Task/Hello-world-Text/Aria/hello-world-text.aria create mode 100644 Task/Hello-world-Text/ArkScript/hello-world-text.ark create mode 100644 Task/Hello-world-Text/DuckDB/hello-world-text.duckdb create mode 100644 Task/Hello-world-Text/Extended-Color-BASIC/hello-world-text.basic create mode 100644 Task/Hello-world-Text/FuncSug/hello-world-text-1.funcsug create mode 100644 Task/Hello-world-Text/FuncSug/hello-world-text-2.funcsug create mode 100644 Task/Hello-world-Text/Nom/hello-world-text.num create mode 100644 Task/Hello-world-Text/Pico-8/hello-world-text-1.pico8 create mode 100644 Task/Hello-world-Text/Pico-8/hello-world-text-2.pico8 create mode 100644 Task/Hello-world-Text/Pluto/hello-world-text.pluto create mode 100644 Task/Hello-world-Text/Rhombus/hello-world-text.rhombus create mode 100644 Task/Hello-world-Text/TAV/hello-world-text.tav create mode 100644 Task/Here-document/DuckDB/here-document-1.duckdb create mode 100644 Task/Here-document/DuckDB/here-document-2.duckdb create mode 100644 Task/Higher-order-functions/Pluto/higher-order-functions.pluto create mode 100644 Task/Hofstadter-Figure-Figure-sequences/Fortran/hofstadter-figure-figure-sequences.f create mode 100644 Task/Honeycombs/EasyLang/honeycombs.easy create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Agena/horners-rule-for-polynomial-evaluation.agena create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Fennel/horners-rule-for-polynomial-evaluation.fennel create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Pluto/horners-rule-for-polynomial-evaluation.pluto create mode 100644 Task/Humble-numbers/Agena/humble-numbers.agena create mode 100644 Task/Humble-numbers/Fortran/humble-numbers.f create mode 100644 Task/Humble-numbers/Pluto/humble-numbers.pluto create mode 100644 Task/Humble-numbers/R/humble-numbers.r create mode 100644 Task/Humble-numbers/Rust/humble-numbers.rs create mode 100644 Task/Hunt-the-Wumpus/EasyLang/hunt-the-wumpus.easy create mode 100644 Task/Hunt-the-Wumpus/Liberty-BASIC/hunt-the-wumpus.basic create mode 100644 Task/Hunt-the-Wumpus/Mojo/hunt-the-wumpus.mojo create mode 100644 Task/ISBN13-check-digit/Apple/isbn13-check-digit.apple create mode 100644 Task/ISBN13-check-digit/DuckDB/isbn13-check-digit.duckdb create mode 100644 Task/ISBN13-check-digit/Prolog/isbn13-check-digit-1.pro create mode 100644 Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro create mode 100644 Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro create mode 100644 Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro create mode 100644 Task/Identity-matrix/DuckDB/identity-matrix.duckdb create mode 100644 Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb create mode 100644 Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb create mode 100644 Task/Include-a-file/RISC-V-Assembly/include-a-file-1.asm create mode 100644 Task/Include-a-file/RISC-V-Assembly/include-a-file-2.asm create mode 100644 Task/Include-a-file/RISC-V-Assembly/include-a-file-3.asm create mode 100644 Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-1.duckdb create mode 100644 Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-2.duckdb create mode 100644 Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-3.duckdb create mode 100644 Task/Increment-a-numerical-string/Pluto/increment-a-numerical-string.pluto create mode 100644 Task/Infinity/ArkScript/infinity.ark create mode 100644 Task/Infinity/DuckDB/infinity.duckdb create mode 100644 Task/Infinity/Pluto/infinity.pluto create mode 100644 Task/Inheritance-Multiple/V-(Vlang)/inheritance-multiple.v create mode 100644 Task/Inheritance-Single/Rhombus/inheritance-single.rhombus create mode 100644 Task/Inheritance-Single/V-(Vlang)/inheritance-single.v create mode 100644 Task/Input-loop/Nom/input-loop.num create mode 100644 Task/Integer-comparison/DuckDB/integer-comparison.duckdb create mode 100644 Task/Integer-comparison/Prolog/integer-comparison-1.pro create mode 100644 Task/Integer-comparison/Prolog/integer-comparison-2.pro create mode 100644 Task/Integer-comparison/YAMLScript/integer-comparison.ys create mode 100644 Task/Integer-sequence/ArkScript/integer-sequence-1.ark create mode 100644 Task/Integer-sequence/ArkScript/integer-sequence-2.ark create mode 100644 Task/Introspection/DuckDB/introspection.duckdb create mode 100644 Task/Inverted-index/DuckDB/inverted-index.duckdb create mode 100644 Task/Inverted-syntax/DuckDB/inverted-syntax-1.duckdb create mode 100644 Task/Inverted-syntax/DuckDB/inverted-syntax-2.duckdb create mode 100644 Task/Inverted-syntax/DuckDB/inverted-syntax-3.duckdb create mode 100644 Task/Iterated-digits-squaring/Prolog/iterated-digits-squaring.pro create mode 100644 Task/JSON/Agena/json.agena create mode 100644 Task/JSON/DuckDB/json-1.duckdb create mode 100644 Task/JSON/DuckDB/json-2.duckdb create mode 100644 Task/JSON/DuckDB/json-3.duckdb create mode 100644 Task/JSON/Pluto/json.pluto rename Task/JSON/REBOL/{json.rebol => json-1.rebol} (81%) create mode 100644 Task/JSON/REBOL/json-2.rebol create mode 100644 Task/Jacobi-symbol/Excel/jacobi-symbol.excel create mode 100644 Task/Jacobsthal-numbers/Agena/jacobsthal-numbers.agena create mode 100644 Task/Jacobsthal-numbers/EasyLang/jacobsthal-numbers.easy create mode 100644 Task/Jacobsthal-numbers/Fennel/jacobsthal-numbers.fennel create mode 100644 Task/Jacobsthal-numbers/Lua/jacobsthal-numbers.lua create mode 100644 Task/Jacobsthal-numbers/Pluto/jacobsthal-numbers.pluto create mode 100644 Task/Jaro-similarity/DuckDB/jaro-similarity.duckdb create mode 100644 Task/Jewels-and-stones/Agena/jewels-and-stones.agena create mode 100644 Task/Jewels-and-stones/Fortran/jewels-and-stones.f create mode 100644 Task/Jewels-and-stones/Icon/jewels-and-stones.icon create mode 100644 Task/Jewels-and-stones/Pluto/jewels-and-stones.pluto create mode 100644 Task/JortSort/YAMLScript/jortsort.ys create mode 100644 Task/Josephus-problem/OxygenBasic/josephus-problem.basic create mode 100644 Task/Josephus-problem/Pluto/josephus-problem.pluto create mode 100644 Task/Josephus-problem/Prolog/josephus-problem-1.pro create mode 100644 Task/Josephus-problem/Prolog/josephus-problem-2.pro rename Task/Josephus-problem/Quite-BASIC/{josephus-problem-1.basic => josephus-problem.basic} (100%) create mode 100644 Task/Josephus-problem/Run-BASIC/josephus-problem-1.basic rename Task/Josephus-problem/{Quite-BASIC => Run-BASIC}/josephus-problem-2.basic (100%) create mode 100644 Task/Josephus-problem/XBasic/josephus-problem.basic create mode 100644 Task/Jump-anywhere/Koka/jump-anywhere.koka create mode 100644 Task/K-d-tree/Elixir/k-d-tree.ex create mode 100644 Task/K-d-tree/Swift/k-d-tree.swift create mode 100644 Task/K-d-tree/Zig/k-d-tree.zig create mode 100644 Task/Kaprekar-numbers/Agena/kaprekar-numbers.agena create mode 100644 Task/Kaprekar-numbers/Pluto/kaprekar-numbers.pluto create mode 100644 Task/Knapsack-problem-0-1/Zig/knapsack-problem-0-1.zig create mode 100644 Task/Knapsack-problem-Bounded/Ada/knapsack-problem-bounded.ada create mode 100644 Task/Knapsack-problem-Bounded/Fortran/knapsack-problem-bounded.f create mode 100644 Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua create mode 100644 Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs create mode 100644 Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg create mode 100644 Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg create mode 100644 Task/Knights-tour/Zig/knights-tour.zig create mode 100644 Task/Knuth-shuffle/DuckDB/knuth-shuffle.duckdb create mode 100644 Task/Knuth-shuffle/REBOL/knuth-shuffle-1.rebol create mode 100644 Task/Knuth-shuffle/REBOL/knuth-shuffle-2.rebol delete mode 100644 Task/Knuth-shuffle/REBOL/knuth-shuffle.rebol create mode 100644 Task/Knuth-shuffle/YAMLScript/knuth-shuffle.ys create mode 100644 Task/Knuths-power-tree/Fortran/knuths-power-tree.f rename Task/Knuths-power-tree/Python/{knuths-power-tree.py => knuths-power-tree-1.py} (100%) create mode 100644 Task/Knuths-power-tree/Python/knuths-power-tree-2.py create mode 100644 Task/Largest-int-from-concatenated-ints/DuckDB/largest-int-from-concatenated-ints.duckdb create mode 100644 Task/Largest-proper-divisor-of-n/AutoLISP/largest-proper-divisor-of-n.l create mode 100644 Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-3.cpp create mode 100644 Task/Last-Friday-of-each-month/DuckDB/last-friday-of-each-month.duckdb create mode 100644 Task/Last-letter-first-letter/FutureBasic/last-letter-first-letter.basic create mode 100644 Task/Leap-year/DuckDB/leap-year.duckdb create mode 100644 Task/Leap-year/Pluto/leap-year.pluto create mode 100644 Task/Left-factorials/DuckDB/left-factorials.duckdb create mode 100644 Task/Leonardo-numbers/DuckDB/leonardo-numbers.duckdb create mode 100644 Task/Leonardo-numbers/Pascal-P/leonardo-numbers.pas create mode 100644 Task/Letter-frequency/DuckDB/letter-frequency-1.duckdb create mode 100644 Task/Letter-frequency/DuckDB/letter-frequency-2.duckdb create mode 100644 Task/Letter-frequency/Koka/letter-frequency.koka create mode 100644 Task/Letter-frequency/TAV/letter-frequency.tav create mode 100644 Task/Levenshtein-distance-Alignment/Ada/levenshtein-distance-alignment.ada create mode 100644 Task/Levenshtein-distance/DuckDB/levenshtein-distance.duckdb create mode 100644 Task/Levenshtein-distance/Pascal-P/levenshtein-distance.pas create mode 100644 Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb create mode 100644 Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb create mode 100644 Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb create mode 100644 Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb create mode 100644 Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb create mode 100644 Task/Literals-Floating-point/ArkScript/literals-floating-point.ark create mode 100644 Task/Literals-Floating-point/Pluto/literals-floating-point.pluto create mode 100644 Task/Literals-Integer/ArkScript/literals-integer.ark create mode 100644 Task/Literals-Integer/DuckDB/literals-integer.duckdb create mode 100644 Task/Literals-Integer/Pluto/literals-integer.pluto create mode 100644 Task/Literals-String/ArkScript/literals-string.ark create mode 100644 Task/Logical-operations/ArkScript/logical-operations.ark create mode 100644 Task/Logical-operations/DuckDB/logical-operations.duckdb create mode 100644 Task/Logical-operations/Red/logical-operations.red create mode 100644 Task/Long-literals-with-continuations/Ada/long-literals-with-continuations.ada delete mode 100644 Task/Long-multiplication/F-Sharp/long-multiplication.fs create mode 100644 Task/Longest-increasing-subsequence/Ada/longest-increasing-subsequence.ada create mode 100644 Task/Longest-increasing-subsequence/DuckDB/longest-increasing-subsequence.duckdb create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Pluto/loop-over-multiple-arrays-simultaneously.pluto create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/REBOL/loop-over-multiple-arrays-simultaneously.rebol create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/TAV/loop-over-multiple-arrays-simultaneously.tav create mode 100644 Task/Loops-Break/DuckDB/loops-break.duckdb create mode 100644 Task/Loops-Break/Koka/loops-break.koka create mode 100644 Task/Loops-Break/Pluto/loops-break.pluto create mode 100644 Task/Loops-Break/TAV/loops-break-1.tav create mode 100644 Task/Loops-Break/TAV/loops-break-2.tav create mode 100644 Task/Loops-Break/Ursalang/loops-break.ursa rename Task/Loops-Break/Zig/{loops-break.zig => loops-break-1.zig} (100%) create mode 100644 Task/Loops-Break/Zig/loops-break-2.zig create mode 100644 Task/Loops-Continue/Pluto/loops-continue.pluto rename Task/Loops-Continue/REBOL/{loops-continue.rebol => loops-continue-1.rebol} (84%) create mode 100644 Task/Loops-Continue/REBOL/loops-continue-2.rebol create mode 100644 Task/Loops-Do-while/DuckDB/loops-do-while.duckdb create mode 100644 Task/Loops-Do-while/Pluto/loops-do-while.pluto create mode 100644 Task/Loops-Do-while/TAV/loops-do-while-1.tav create mode 100644 Task/Loops-Do-while/TAV/loops-do-while-2.tav create mode 100644 Task/Loops-Downward-for/DuckDB/loops-downward-for-1.duckdb create mode 100644 Task/Loops-Downward-for/DuckDB/loops-downward-for-2.duckdb create mode 100644 Task/Loops-Downward-for/Pluto/loops-downward-for.pluto create mode 100644 Task/Loops-Downward-for/TAV/loops-downward-for.tav create mode 100644 Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-1.duckdb create mode 100644 Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-2.duckdb create mode 100644 Task/Loops-For-with-a-specified-step/Pluto/loops-for-with-a-specified-step.pluto create mode 100644 Task/Loops-For/Adina/loops-for-1.adina create mode 100644 Task/Loops-For/Adina/loops-for-2.adina create mode 100644 Task/Loops-For/DuckDB/loops-for-1.duckdb create mode 100644 Task/Loops-For/DuckDB/loops-for-2.duckdb create mode 100644 Task/Loops-For/DuckDB/loops-for-3.duckdb create mode 100644 Task/Loops-For/Eiffel/loops-for.e create mode 100644 Task/Loops-For/Extended-Color-BASIC/loops-for.basic create mode 100644 Task/Loops-For/Pluto/loops-for.pluto create mode 100644 Task/Loops-For/TAV/loops-for-1.tav create mode 100644 Task/Loops-For/TAV/loops-for-2.tav create mode 100644 Task/Loops-For/TAV/loops-for-3.tav create mode 100644 Task/Loops-Foreach/Pluto/loops-foreach.pluto create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/DuckDB/loops-increment-loop-index-within-loop-body.duckdb create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/Pluto/loops-increment-loop-index-within-loop-body.pluto create mode 100644 Task/Loops-Increment-loop-index-within-loop-body/REBOL/loops-increment-loop-index-within-loop-body.rebol create mode 100644 Task/Loops-Infinite/Eiffel/loops-infinite.e create mode 100644 Task/Loops-Infinite/Pluto/loops-infinite.pluto rename Task/Loops-Infinite/REBOL/{loops-infinite.rebol => loops-infinite-1.rebol} (100%) create mode 100644 Task/Loops-Infinite/REBOL/loops-infinite-2.rebol create mode 100644 Task/Loops-Infinite/REBOL/loops-infinite-3.rebol create mode 100644 Task/Loops-Infinite/TAV/loops-infinite.tav create mode 100644 Task/Loops-N-plus-one-half/DuckDB/loops-n-plus-one-half.duckdb create mode 100644 Task/Loops-N-plus-one-half/Pluto/loops-n-plus-one-half.pluto create mode 100644 Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-1.tav create mode 100644 Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-2.tav create mode 100644 Task/Loops-Nested/DuckDB/loops-nested.duckdb create mode 100644 Task/Loops-Nested/Pluto/loops-nested.pluto create mode 100644 Task/Loops-Nested/Zig/loops-nested.zig create mode 100644 Task/Loops-While/DuckDB/loops-while.duckdb create mode 100644 Task/Loops-While/Mn/loops-while.mn create mode 100644 Task/Loops-While/Pluto/loops-while.pluto create mode 100644 Task/Loops-While/TAV/loops-while.tav create mode 100644 Task/Loops-While/Ursalang/loops-while.ursa create mode 100644 Task/Loops-With-multiple-ranges/DuckDB/loops-with-multiple-ranges.duckdb rename Task/Loops-With-multiple-ranges/Haskell/{loops-with-multiple-ranges.hs => loops-with-multiple-ranges-1.hs} (100%) create mode 100644 Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-2.hs create mode 100644 Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-3.hs create mode 100644 Task/Loops-With-multiple-ranges/Pluto/loops-with-multiple-ranges.pluto create mode 100644 Task/Loops-With-multiple-ranges/REBOL/loops-with-multiple-ranges.rebol create mode 100644 Task/Loops-Wrong-ranges/Icon/loops-wrong-ranges.icon create mode 100644 Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto create mode 100644 Task/Loops-Wrong-ranges/REBOL/loops-wrong-ranges.rebol create mode 100644 Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb create mode 100644 Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto create mode 100644 Task/M-bius-function/C-sharp/m-bius-function.cs create mode 100644 Task/M-bius-function/Pascal-P/m-bius-function.pas create mode 100644 Task/M-bius-function/Pluto/m-bius-function.pluto create mode 100644 Task/M-bius-function/PowerShell/m-bius-function.psh create mode 100644 Task/M-bius-function/R/m-bius-function.r create mode 100644 Task/M-bius-function/Tcl/m-bius-function.tcl create mode 100644 Task/M-bius-function/Zig/m-bius-function.zig create mode 100644 Task/MD5/DuckDB/md5.duckdb create mode 100644 Task/MD5/JavaScript/md5.js create mode 100644 Task/MD5/REBOL/md5-1.rebol create mode 100644 Task/MD5/REBOL/md5-2.rebol delete mode 100644 Task/MD5/REBOL/md5.rebol create mode 100644 Task/Machine-code/Ada/machine-code.ada create mode 100644 Task/Machine-code/Pluto/machine-code-1.pluto create mode 100644 Task/Machine-code/Pluto/machine-code-2.pluto create mode 100644 Task/Magic-8-ball/Prolog/magic-8-ball.pro create mode 100644 Task/Magic-constant/Pascal-P/magic-constant.pas create mode 100644 Task/Magic-squares-of-doubly-even-order/Objeck/magic-squares-of-doubly-even-order.objeck create mode 100644 Task/Magic-squares-of-doubly-even-order/Pluto/magic-squares-of-doubly-even-order.pluto create mode 100644 Task/Magic-squares-of-odd-order/Pluto/magic-squares-of-odd-order.pluto create mode 100644 Task/Magic-squares-of-singly-even-order/Pluto/magic-squares-of-singly-even-order.pluto create mode 100644 Task/Main-step-of-GOST-28147-89/Zig/main-step-of-gost-28147-89.zig delete mode 100644 Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl delete mode 100644 Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl delete mode 100644 Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl delete mode 100644 Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl create mode 100644 Task/Mandelbrot-set/Python/mandelbrot-set-11.py create mode 100644 Task/Mandelbrot-set/Python/mandelbrot-set-12.py create mode 100644 Task/Map-range/DuckDB/map-range.duckdb create mode 100644 Task/Map-range/Pascal-P/map-range.pas create mode 100644 Task/Matrix-multiplication/DuckDB/matrix-multiplication-1.duckdb create mode 100644 Task/Matrix-multiplication/DuckDB/matrix-multiplication-2.duckdb create mode 100644 Task/Matrix-multiplication/DuckDB/matrix-multiplication-3.duckdb create mode 100644 Task/Matrix-multiplication/Objeck/matrix-multiplication.objeck create mode 100644 Task/Matrix-transposition/DuckDB/matrix-transposition-1.duckdb create mode 100644 Task/Matrix-transposition/DuckDB/matrix-transposition-2.duckdb create mode 100644 Task/Matrix-transposition/DuckDB/matrix-transposition-3.duckdb create mode 100644 Task/Mayan-calendar/Rust/mayan-calendar.rs create mode 100644 Task/Mayan-numerals/FutureBasic/mayan-numerals.basic create mode 100644 Task/McNuggets-problem/Fortran/mcnuggets-problem.f create mode 100644 Task/Meissel-Mertens-constant/JavaScript/meissel-mertens-constant.js create mode 100644 Task/Meissel-Mertens-constant/Rust/meissel-mertens-constant.rs create mode 100644 Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb create mode 100644 Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb create mode 100644 Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb create mode 100644 Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb create mode 100644 Task/Metaprogramming/V-(Vlang)/metaprogramming.v create mode 100644 Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena create mode 100644 Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto create mode 100644 Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb create mode 100644 Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-3.hs create mode 100644 Task/Minesweeper-game/Liberty-BASIC/minesweeper-game.basic create mode 100644 Task/Minimal-steps-down-to-1/Ada/minimal-steps-down-to-1.ada rename Task/Modular-arithmetic/Common-Lisp/{modular-arithmetic.lisp => modular-arithmetic-1.lisp} (100%) create mode 100644 Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp create mode 100644 Task/Modular-arithmetic/Rust/modular-arithmetic.rs create mode 100644 Task/Modular-arithmetic/Zig/modular-arithmetic.zig create mode 100644 Task/Modular-inverse/FutureBasic/modular-inverse.basic create mode 100644 Task/Modular-inverse/Pluto/modular-inverse.pluto create mode 100644 Task/Modular-inverse/Zig/modular-inverse.zig create mode 100644 Task/Monads-Writer-monad/Koka/monads-writer-monad.koka create mode 100644 Task/Monte-Carlo-methods/APL/monte-carlo-methods.apl create mode 100644 Task/Monte-Carlo-methods/DuckDB/monte-carlo-methods.duckdb create mode 100644 Task/Monte-Carlo-methods/FutureBasic/monte-carlo-methods.basic create mode 100644 Task/Monte-Carlo-methods/SETL/monte-carlo-methods.setl create mode 100644 Task/Multi-dimensional-array/BBC-BASIC/multi-dimensional-array-1.basic create mode 100644 Task/Multi-dimensional-array/BBC-BASIC/multi-dimensional-array-2.basic create mode 100644 Task/Multiple-regression/Rust/multiple-regression.rs create mode 100644 Task/Multiplication-tables/Pluto/multiplication-tables.pluto create mode 100644 Task/Multiplication-tables/TAV/multiplication-tables.tav create mode 100644 Task/Multiplicative-order/F-Sharp/multiplicative-order.fs create mode 100644 Task/Munchausen-numbers/ArkScript/munchausen-numbers.ark create mode 100644 Task/Munching-squares/YAMLScript/munching-squares.ys create mode 100644 Task/Mutex/FutureBasic/mutex.basic create mode 100644 Task/Mutual-recursion/Pluto/mutual-recursion.pluto create mode 100644 Task/N-queens-problem/ArkScript/n-queens-problem.ark create mode 100644 Task/Named-parameters/FutureBasic/named-parameters.basic create mode 100644 Task/Named-parameters/Pluto/named-parameters.pluto create mode 100644 Task/Naming-conventions/Ada/naming-conventions-1.ada create mode 100644 Task/Naming-conventions/Ada/naming-conventions-2.ada create mode 100644 Task/Naming-conventions/Ada/naming-conventions-3.ada rename Task/Narcissistic-decimal-number/Lua/{narcissistic-decimal-number.lua => narcissistic-decimal-number-1.lua} (100%) create mode 100644 Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number-2.lua create mode 100644 Task/Narcissistic-decimal-number/Pluto/narcissistic-decimal-number.pluto create mode 100644 Task/Nested-function/DuckDB/nested-function.duckdb create mode 100644 Task/Nested-templated-data/Pluto/nested-templated-data.pluto create mode 100644 Task/Next-highest-int-from-digits/YAMLScript/next-highest-int-from-digits.ys create mode 100644 Task/Non-decimal-radices-Convert/Pluto/non-decimal-radices-convert.pluto create mode 100644 Task/Nth-root/DuckDB/nth-root.duckdb create mode 100644 Task/Nth/DuckDB/nth.duckdb create mode 100644 Task/Null-object/ArkScript/null-object.ark create mode 100644 Task/Null-object/Tcl/null-object-3.tcl create mode 100644 Task/Null-object/Tcl/null-object-4.tcl create mode 100644 Task/Numerical-integration/Pluto/numerical-integration.pluto create mode 100644 Task/OLE-automation/Julia/ole-automation.jl create mode 100644 Task/Object-serialization/REBOL/object-serialization.rebol create mode 100644 Task/Odd-word-problem/Nom/odd-word-problem.num create mode 100644 Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic create mode 100644 Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic create mode 100644 Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic create mode 100644 Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic create mode 100644 Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto create mode 100644 Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro create mode 100644 Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro create mode 100644 Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys create mode 100644 Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb create mode 100644 Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto create mode 100644 Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro create mode 100644 Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro create mode 100644 Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb create mode 100644 Task/Ordered-words/DuckDB/ordered-words.duckdb create mode 100644 Task/Ordered-words/TAV/ordered-words.tav create mode 100644 Task/Own-digits-power-sum/Scheme/own-digits-power-sum.scm rename Task/Padovan-sequence/Julia/{padovan-sequence.jl => padovan-sequence-1.jl} (92%) create mode 100644 Task/Padovan-sequence/Julia/padovan-sequence-2.jl create mode 100644 Task/Padovan-sequence/Phix/padovan-sequence-4.phix create mode 100644 Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb create mode 100644 Task/Palindrome-detection/Pluto/palindrome-detection.pluto create mode 100644 Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas rename Task/Pancake-numbers/FreeBASIC/{pancake-numbers.basic => pancake-numbers-1.basic} (100%) create mode 100644 Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic delete mode 100644 Task/Pancake-numbers/Julia/pancake-numbers-1.jl rename Task/Pancake-numbers/Julia/{pancake-numbers-2.jl => pancake-numbers.jl} (100%) create mode 100644 Task/Pancake-numbers/Phix/pancake-numbers-4.phix create mode 100644 Task/Pancake-numbers/Pluto/pancake-numbers-1.pluto create mode 100644 Task/Pancake-numbers/Pluto/pancake-numbers-2.pluto create mode 100644 Task/Pancake-numbers/Pluto/pancake-numbers-3.pluto create mode 100644 Task/Pancake-numbers/Pluto/pancake-numbers-4.pluto create mode 100644 Task/Pancake-numbers/Ruby/pancake-numbers-1.rb create mode 100644 Task/Pancake-numbers/Ruby/pancake-numbers-2.rb delete mode 100644 Task/Pancake-numbers/Ruby/pancake-numbers.rb create mode 100644 Task/Pancake-numbers/Wren/pancake-numbers-3.wren create mode 100644 Task/Pancake-numbers/Wren/pancake-numbers-4.wren create mode 100644 Task/Parameterized-SQL-statement/DuckDB/parameterized-sql-statement.duckdb create mode 100644 Task/Parse-an-IP-Address/Dart/parse-an-ip-address.dart create mode 100644 Task/Parse-an-IP-Address/Elixir/parse-an-ip-address.ex create mode 100644 Task/Parse-an-IP-Address/Fortran/parse-an-ip-address.f create mode 100644 Task/Parse-an-IP-Address/JavaScript/parse-an-ip-address.js create mode 100644 Task/Parse-an-IP-Address/Mathematica/parse-an-ip-address.math create mode 100644 Task/Parse-an-IP-Address/OCaml/parse-an-ip-address.ml create mode 100644 Task/Parse-an-IP-Address/R/parse-an-ip-address.r rename Task/Parse-an-IP-Address/Rust/{parse-an-ip-address.rs => parse-an-ip-address-1.rs} (100%) create mode 100644 Task/Parse-an-IP-Address/Rust/parse-an-ip-address-2.rs create mode 100644 Task/Parse-an-IP-Address/Swift/parse-an-ip-address.swift create mode 100644 Task/Parse-an-IP-Address/Zig/parse-an-ip-address.zig create mode 100644 Task/Parsing-RPN-calculator-algorithm/Crystal/parsing-rpn-calculator-algorithm.cr create mode 100644 Task/Parsing-RPN-calculator-algorithm/Pluto/parsing-rpn-calculator-algorithm.pluto create mode 100644 Task/Parsing-RPN-calculator-algorithm/Red/parsing-rpn-calculator-algorithm.red create mode 100644 Task/Parsing-RPN-to-infix-conversion/Red/parsing-rpn-to-infix-conversion.red create mode 100644 Task/Parsing-Shunting-yard-algorithm/Red/parsing-shunting-yard-algorithm.red create mode 100644 Task/Pascals-triangle-Puzzle/EasyLang/pascals-triangle-puzzle.easy create mode 100644 Task/Pascals-triangle-Puzzle/Fortran/pascals-triangle-puzzle.f create mode 100644 Task/Pascals-triangle-Puzzle/JavaScript/pascals-triangle-puzzle.js create mode 100644 Task/Pascals-triangle-Puzzle/Pluto/pascals-triangle-puzzle.pluto create mode 100644 Task/Pascals-triangle/DuckDB/pascals-triangle.duckdb delete mode 100644 Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx delete mode 100644 Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx delete mode 100644 Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx create mode 100644 Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx rename Task/Pell-numbers/Julia/{pell-numbers.jl => pell-numbers-1.jl} (100%) create mode 100644 Task/Pell-numbers/Julia/pell-numbers-2.jl create mode 100644 Task/Pell-numbers/PARI-GP/pell-numbers.parigp create mode 100644 Task/Perfect-shuffle/FutureBasic/perfect-shuffle.basic create mode 100644 Task/Perfect-shuffle/Pluto/perfect-shuffle.pluto create mode 100644 Task/Permutations-Derangements/DuckDB/permutations-derangements.duckdb create mode 100644 Task/Permutations-by-swapping/Zig/permutations-by-swapping.zig create mode 100644 Task/Permutations/DuckDB/permutations.duckdb create mode 100644 Task/Permutations/Pluto/permutations.pluto create mode 100644 Task/Permutations/TAV/permutations-1.tav create mode 100644 Task/Permutations/TAV/permutations-2.tav create mode 100644 Task/Permutations/TAV/permutations-3.tav create mode 100644 Task/Permutations/TAV/permutations-4.tav create mode 100644 Task/Pernicious-numbers/Agena/pernicious-numbers.agena create mode 100644 Task/Pernicious-numbers/Pluto/pernicious-numbers.pluto create mode 100644 Task/Phrase-reversals/Prolog/phrase-reversals.pro create mode 100644 Task/Pick-random-element/DuckDB/pick-random-element.duckdb create mode 100644 Task/Pick-random-element/Pluto/pick-random-element.pluto create mode 100644 Task/Pick-random-element/Scheme/pick-random-element.scm rename Task/Pick-random-element/Tcl/{pick-random-element.tcl => pick-random-element-1.tcl} (100%) create mode 100644 Task/Pick-random-element/Tcl/pick-random-element-2.tcl create mode 100644 Task/Pisano-period/Agena/pisano-period.agena create mode 100644 Task/Pisano-period/Pluto/pisano-period.pluto create mode 100644 Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug create mode 100644 Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku delete mode 100644 Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 delete mode 100644 Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 delete mode 100644 Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 create mode 100644 Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 create mode 100644 Task/Polymorphism/Rhombus/polymorphism-1.rhombus create mode 100644 Task/Polymorphism/Rhombus/polymorphism-2.rhombus create mode 100644 Task/Polyspiral/REBOL/polyspiral.rebol create mode 100644 Task/Population-count/Prolog/population-count.pro create mode 100644 Task/Power-set/Pluto/power-set.pluto create mode 100644 Task/Primality-by-trial-division/Agena/primality-by-trial-division.agena create mode 100644 Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-1.duckdb create mode 100644 Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-2.duckdb create mode 100644 Task/Primality-by-trial-division/Pluto/primality-by-trial-division.pluto create mode 100644 Task/Prime-decomposition/DuckDB/prime-decomposition.duckdb create mode 100644 Task/Prime-decomposition/OoRexx/prime-decomposition.rexx create mode 100644 Task/Priority-queue/Pluto/priority-queue.pluto create mode 100644 Task/Probabilistic-choice/DuckDB/probabilistic-choice.duckdb create mode 100644 Task/Program-termination/ArkScript/program-termination.ark create mode 100644 Task/Proper-divisors/DuckDB/proper-divisors.duckdb create mode 100644 Task/Pseudo-random-numbers-Middle-square-method/DuckDB/pseudo-random-numbers-middle-square-method.duckdb rename Task/Queue-Definition/ALGOL-68/{queue-definition.alg => queue-definition-1.alg} (100%) create mode 100644 Task/Queue-Definition/ALGOL-68/queue-definition-2.alg create mode 100644 Task/Quickselect-algorithm/YAMLScript/quickselect-algorithm.ys create mode 100644 Task/Quine/Extended-Color-BASIC/quine.basic create mode 100644 Task/Quine/REBOL/quine-1.rebol create mode 100644 Task/Quine/REBOL/quine-2.rebol delete mode 100644 Task/Quine/REBOL/quine.rebol create mode 100644 Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-1.pro create mode 100644 Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-2.pro create mode 100644 Task/Ramanujan-primes-twins/Rust/ramanujan-primes-twins.rs create mode 100644 Task/Ramer-Douglas-Peucker-line-simplification/Pascal-P/ramer-douglas-peucker-line-simplification.pas create mode 100644 Task/Random-numbers/DuckDB/random-numbers.duckdb create mode 100644 Task/Range-expansion/DuckDB/range-expansion.duckdb create mode 100644 Task/Range-extraction/DuckDB/range-extraction.duckdb create mode 100644 Task/Read-a-file-character-by-character-UTF8/Ada/read-a-file-character-by-character-utf8.ada create mode 100644 Task/Read-a-file-line-by-line/DuckDB/read-a-file-line-by-line.duckdb create mode 100644 Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-1.pluto create mode 100644 Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-2.pluto create mode 100644 Task/Read-entire-file/ArkScript/read-entire-file.ark create mode 100644 Task/Real-constants-and-functions/Maxima/real-constants-and-functions.maxima create mode 100644 Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav create mode 100644 Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb create mode 100644 Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb create mode 100644 Task/Regular-expressions/Maxima/regular-expressions.maxima create mode 100644 Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb create mode 100644 Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb create mode 100644 Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb create mode 100644 Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb create mode 100644 Task/Rename-a-file/Maxima/rename-a-file.maxima create mode 100644 Task/Rename-a-file/Pluto/rename-a-file.pluto create mode 100644 Task/Rename-a-file/R/rename-a-file.r create mode 100644 Task/Rep-string/DuckDB/rep-string.duckdb create mode 100644 Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb create mode 100644 Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb create mode 100644 Task/Repeat-a-string/Pluto/repeat-a-string.pluto create mode 100644 Task/Repunit-primes/R/repunit-primes.r create mode 100644 Task/Retrieve-and-search-chat-history/R/retrieve-and-search-chat-history.r create mode 100644 Task/Return-multiple-values/DuckDB/return-multiple-values-1.duckdb create mode 100644 Task/Return-multiple-values/DuckDB/return-multiple-values-2.duckdb create mode 100644 Task/Reverse-a-string/ArkScript/reverse-a-string.ark create mode 100644 Task/Reverse-a-string/DuckDB/reverse-a-string.duckdb create mode 100644 Task/Reverse-a-string/Nom/reverse-a-string.num create mode 100644 Task/Reverse-a-string/Pluto/reverse-a-string.pluto create mode 100644 Task/Reverse-a-string/TAV/reverse-a-string.tav create mode 100644 Task/Reverse-words-in-a-string/Pluto/reverse-words-in-a-string.pluto create mode 100644 Task/Roman-numerals-Encode/Pluto/roman-numerals-encode.pluto create mode 100644 Task/Roots-of-a-quadratic-function/Pluto/roots-of-a-quadratic-function.pluto create mode 100644 Task/Roots-of-unity/DuckDB/roots-of-unity.duckdb create mode 100644 Task/Roots-of-unity/Pluto/roots-of-unity.pluto create mode 100644 Task/Rot-13/Crystal/rot-13.cr create mode 100644 Task/Rot-13/Pluto/rot-13.pluto create mode 100644 Task/Rot-13/Rhombus/rot-13.rhombus create mode 100644 Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb create mode 100644 Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb create mode 100644 Task/Runge-Kutta-method/Pluto/runge-kutta-method.pluto create mode 100644 Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py create mode 100644 Task/SEDOLs/Prolog/sedols-1.pro create mode 100644 Task/SEDOLs/Prolog/sedols-2.pro create mode 100644 Task/SEDOLs/Prolog/sedols-3.pro create mode 100644 Task/SHA-1/REBOL/sha-1-1.rebol create mode 100644 Task/SHA-1/REBOL/sha-1-2.rebol create mode 100644 Task/SHA-256/REBOL/sha-256.rebol create mode 100644 Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-1.duckdb create mode 100644 Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-2.duckdb create mode 100644 Task/Search-a-list-of-records/Icon/search-a-list-of-records.icon create mode 100644 Task/Self-numbers/Pluto/self-numbers.pluto create mode 100644 Task/Semordnilap/ArkScript/semordnilap.ark create mode 100644 Task/Semordnilap/Pluto/semordnilap.pluto create mode 100644 Task/Semordnilap/Prolog/semordnilap.pro create mode 100644 Task/Semordnilap/REBOL/semordnilap-1.rebol create mode 100644 Task/Semordnilap/REBOL/semordnilap-2.rebol create mode 100644 Task/Semordnilap/TAV/semordnilap.tav create mode 100644 Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena create mode 100644 Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto create mode 100644 Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb create mode 100644 Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb create mode 100644 Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb create mode 100644 Task/Set-consolidation/Pluto/set-consolidation.pluto create mode 100644 Task/Set/DuckDB/set-1.duckdb create mode 100644 Task/Set/DuckDB/set-2.duckdb create mode 100644 Task/Set/DuckDB/set-3.duckdb create mode 100644 Task/Set/DuckDB/set-4.duckdb create mode 100644 Task/Set/DuckDB/set-5.duckdb create mode 100644 Task/Set/DuckDB/set-6.duckdb create mode 100644 Task/Set/DuckDB/set-7.duckdb create mode 100644 Task/Set/DuckDB/set-8.duckdb create mode 100644 Task/Set/DuckDB/set-9.duckdb create mode 100644 Task/Set/Pluto/set.pluto create mode 100644 Task/Shell-one-liner/ArkScript/shell-one-liner.ark rename Task/Shoelace-formula-for-polygonal-area/Julia/{shoelace-formula-for-polygonal-area.jl => shoelace-formula-for-polygonal-area-1.jl} (100%) create mode 100644 Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area-2.jl create mode 100644 Task/Shoelace-formula-for-polygonal-area/R/shoelace-formula-for-polygonal-area.r create mode 100644 Task/Short-circuit-evaluation/ArkScript/short-circuit-evaluation.ark create mode 100644 Task/Show-ASCII-table/ArkScript/show-ascii-table.ark create mode 100644 Task/Show-the-epoch/DuckDB/show-the-epoch.duckdb create mode 100644 Task/Sierpinski-pentagon/FutureBasic/sierpinski-pentagon.basic create mode 100644 Task/Sieve-of-Eratosthenes/DuckDB/sieve-of-eratosthenes.duckdb create mode 100644 Task/Simple-windowed-application/FuncSug/simple-windowed-application.funcsug create mode 100644 Task/Simple-windowed-application/TAV/simple-windowed-application.tav create mode 100644 Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl create mode 100644 Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug create mode 100644 Task/Singleton/Rust/singleton.rs create mode 100644 Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr create mode 100644 Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto create mode 100644 Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr create mode 100644 Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto create mode 100644 Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto create mode 100644 Task/Sleep/ArkScript/sleep.ark create mode 100644 Task/Sleep/FutureBasic/sleep.basic create mode 100644 Task/Sleep/Pluto/sleep.pluto create mode 100644 Task/Smarandache-prime-digital-sequence/Agena/smarandache-prime-digital-sequence.agena create mode 100644 Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto create mode 100644 Task/Snake/Liberty-BASIC/snake.basic create mode 100644 Task/Sokoban/JavaScript/sokoban.js create mode 100644 Task/Sokoban/Rust/sokoban.rs create mode 100644 Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk create mode 100644 Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena create mode 100644 Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cobol create mode 100644 Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr create mode 100644 Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto create mode 100644 Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r create mode 100644 Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js create mode 100644 Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb create mode 100644 Task/Sort-an-integer-array/Pluto/sort-an-integer-array.pluto create mode 100644 Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-1.duckdb create mode 100644 Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-2.duckdb create mode 100644 Task/Sort-numbers-lexicographically/Icon/sort-numbers-lexicographically.icon create mode 100644 Task/Sort-three-variables/Prolog/sort-three-variables.pro create mode 100644 Task/Sorting-algorithms-Insertion-sort/FutureBasic/sorting-algorithms-insertion-sort.basic create mode 100644 Task/Sorting-algorithms-Insertion-sort/S-BASIC/sorting-algorithms-insertion-sort.basic create mode 100644 Task/Sorting-algorithms-Quicksort/ArkScript/sorting-algorithms-quicksort.ark create mode 100644 Task/Sorting-algorithms-Sleep-sort/FutureBasic/sorting-algorithms-sleep-sort.basic create mode 100644 Task/Sorting-algorithms-Sleep-sort/OCaml/sorting-algorithms-sleep-sort.ml create mode 100644 Task/Sorting-algorithms-Stooge-sort/Maxima/sorting-algorithms-stooge-sort.maxima create mode 100644 Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-1.logo create mode 100644 Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-2.logo create mode 100644 Task/Sparkline-in-unicode/YAMLScript/sparkline-in-unicode.ys create mode 100644 Task/Split-a-character-string-based-on-change-of-character/R/split-a-character-string-based-on-change-of-character.r create mode 100644 Task/Stack-traces/FutureBasic/stack-traces.basic create mode 100644 Task/Stack/Pluto/stack.pluto delete mode 100644 Task/Stack/REXX/stack-1.rexx rename Task/Stack/REXX/{stack-2.rexx => stack.rexx} (82%) create mode 100644 Task/Stack/TAV/stack-1.tav create mode 100644 Task/Stack/TAV/stack-2.tav create mode 100644 Task/Statistics-Basic/DuckDB/statistics-basic.duckdb create mode 100644 Task/Statistics-Basic/Maxima/statistics-basic.maxima create mode 100644 Task/Stem-and-leaf-plot/Prolog/stem-and-leaf-plot.pro create mode 100644 Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig create mode 100644 Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy create mode 100644 Task/String-append/ArkScript/string-append.ark create mode 100644 Task/String-append/DuckDB/string-append-1.duckdb create mode 100644 Task/String-append/DuckDB/string-append-2.duckdb create mode 100644 Task/String-case/ArkScript/string-case.ark create mode 100644 Task/String-case/DuckDB/string-case.duckdb create mode 100644 Task/String-comparison/DuckDB/string-comparison.duckdb create mode 100644 Task/String-concatenation/ArkScript/string-concatenation.ark create mode 100644 Task/String-concatenation/Prolog/string-concatenation.pro create mode 100644 Task/String-concatenation/Tcl/string-concatenation-3.tcl create mode 100644 Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark create mode 100644 Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr create mode 100644 Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb create mode 100644 Task/String-interpolation-included-/Pluto/string-interpolation-included-.pluto create mode 100644 Task/String-interpolation-included-/R/string-interpolation-included-.r create mode 100644 Task/String-length/ArkScript/string-length.ark create mode 100644 Task/String-length/DuckDB/string-length.duckdb create mode 100644 Task/String-length/FutureBasic/string-length.basic create mode 100644 Task/String-length/Pluto/string-length.pluto create mode 100644 Task/String-length/TAV/string-length.tav create mode 100644 Task/String-matching/ArkScript/string-matching.ark create mode 100644 Task/String-matching/DuckDB/string-matching.duckdb create mode 100644 Task/String-matching/R/string-matching.r create mode 100644 Task/String-prepend/ArkScript/string-prepend.ark create mode 100644 Task/String-prepend/DuckDB/string-prepend-1.duckdb create mode 100644 Task/String-prepend/DuckDB/string-prepend-2.duckdb create mode 100644 Task/String-prepend/DuckDB/string-prepend-3.duckdb create mode 100644 Task/Strip-a-set-of-characters-from-a-string/DuckDB/strip-a-set-of-characters-from-a-string.duckdb create mode 100644 Task/Strip-comments-from-a-string/DuckDB/strip-comments-from-a-string.duckdb create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/DuckDB/strip-control-codes-and-extended-characters-from-a-string.duckdb create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/DuckDB/strip-whitespace-from-a-string-top-and-tail.duckdb create mode 100644 Task/Substitution-cipher/Rust/substitution-cipher.rs create mode 100644 Task/Substring-Top-and-tail/Maxima/substring-top-and-tail.maxima create mode 100644 Task/Substring-Top-and-tail/R/substring-top-and-tail.r create mode 100644 Task/Substring/DuckDB/substring.duckdb create mode 100644 Task/Sudoku/DuckDB/sudoku.duckdb create mode 100644 Task/Sudoku/Zig/sudoku.zig create mode 100644 Task/Sum-and-product-of-an-array/ArkScript/sum-and-product-of-an-array.ark create mode 100644 Task/Sum-and-product-of-an-array/DuckDB/sum-and-product-of-an-array.duckdb create mode 100644 Task/Sum-digits-of-an-integer/ArkScript/sum-digits-of-an-integer.ark create mode 100644 Task/Sum-digits-of-an-integer/DuckDB/sum-digits-of-an-integer.duckdb rename Task/Sum-digits-of-an-integer/PascalABC.NET/{sum-digits-of-an-integer.pas => sum-digits-of-an-integer-1.pas} (100%) create mode 100644 Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer-2.pas create mode 100644 Task/Sum-digits-of-an-integer/Pluto/sum-digits-of-an-integer.pluto create mode 100644 Task/Sum-multiples-of-3-and-5/DuckDB/sum-multiples-of-3-and-5.duckdb create mode 100644 Task/Sum-of-a-series/ArkScript/sum-of-a-series.ark create mode 100644 Task/Sum-of-a-series/DuckDB/sum-of-a-series-1.duckdb create mode 100644 Task/Sum-of-a-series/DuckDB/sum-of-a-series-2.duckdb create mode 100644 Task/Sum-of-a-series/DuckDB/sum-of-a-series-3.duckdb create mode 100644 Task/Sum-of-a-series/DuckDB/sum-of-a-series-4.duckdb create mode 100644 Task/Sum-of-a-series/FutureBasic/sum-of-a-series.basic create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Agena/sum-of-elements-below-main-diagonal-of-matrix.agena create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Fennel/sum-of-elements-below-main-diagonal-of-matrix.fennel create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Fortran/sum-of-elements-below-main-diagonal-of-matrix.f create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Lua/sum-of-elements-below-main-diagonal-of-matrix.lua create mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Pluto/sum-of-elements-below-main-diagonal-of-matrix.pluto create mode 100644 Task/Sum-of-squares/ArkScript/sum-of-squares.ark create mode 100644 Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb create mode 100644 Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb create mode 100644 Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb create mode 100644 Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb create mode 100644 Task/Sum-to-100/FutureBasic/sum-to-100.basic create mode 100644 Task/Superellipse/Maxima/superellipse.maxima create mode 100644 Task/Superpermutation-minimisation/JavaScript/superpermutation-minimisation.js create mode 100644 Task/Symmetric-difference/DuckDB/symmetric-difference.duckdb create mode 100644 Task/Symmetric-difference/Pluto/symmetric-difference.pluto create mode 100644 Task/System-time/Pluto/system-time.pluto create mode 100644 Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-1.duckdb create mode 100644 Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-2.duckdb create mode 100644 Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-3.duckdb create mode 100644 Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-4.duckdb create mode 100644 Task/Tarjan/JavaScript/tarjan.js create mode 100644 Task/Tarjan/Zig/tarjan.zig create mode 100644 Task/Tau-function/FutureBasic/tau-function.basic create mode 100644 Task/Tau-function/Pluto/tau-function.pluto create mode 100644 Task/Tau-number/FutureBasic/tau-number.basic create mode 100644 Task/Tau-number/Pluto/tau-number.pluto create mode 100644 Task/Terminal-control-Clear-the-screen/Pluto/terminal-control-clear-the-screen.pluto create mode 100644 Task/Terminal-control-Coloured-text/Pluto/terminal-control-coloured-text.pluto create mode 100644 Task/Terminal-control-Cursor-movement/Pluto/terminal-control-cursor-movement.pluto create mode 100644 Task/Terminal-control-Cursor-positioning/Pluto/terminal-control-cursor-positioning.pluto create mode 100644 Task/Terminal-control-Dimensions/Pluto/terminal-control-dimensions.pluto create mode 100644 Task/Terminal-control-Display-an-extended-character/Pluto/terminal-control-display-an-extended-character.pluto create mode 100644 Task/Terminal-control-Hiding-the-cursor/Pluto/terminal-control-hiding-the-cursor.pluto create mode 100644 Task/Terminal-control-Inverse-video/Pluto/terminal-control-inverse-video.pluto create mode 100644 Task/Terminal-control-Preserve-screen/Pluto/terminal-control-preserve-screen.pluto create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Pluto/terminal-control-ringing-the-terminal-bell.pluto create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/YAMLScript/terminal-control-ringing-the-terminal-bell.ys create mode 100644 Task/Terminal-control-Unicode-output/Pluto/terminal-control-unicode-output.pluto create mode 100644 Task/Test-integerness/Ada/test-integerness.ada create mode 100644 Task/Test-integerness/DuckDB/test-integerness-1.duckdb create mode 100644 Task/Test-integerness/DuckDB/test-integerness-2.duckdb create mode 100644 Task/Test-integerness/Pluto/test-integerness.pluto create mode 100644 Task/Text-processing-2/DuckDB/text-processing-2-1.duckdb create mode 100644 Task/Text-processing-2/DuckDB/text-processing-2-2.duckdb create mode 100644 Task/Text-processing-2/DuckDB/text-processing-2-3.duckdb create mode 100644 Task/Text-processing-2/DuckDB/text-processing-2-4.duckdb create mode 100644 Task/Text-processing-2/DuckDB/text-processing-2-5.duckdb create mode 100644 Task/Text-processing-2/DuckDB/text-processing-2-6.duckdb create mode 100644 Task/The-Name-Game/R/the-name-game.r create mode 100644 Task/The-Twelve-Days-of-Christmas/AutoLISP/the-twelve-days-of-christmas.l create mode 100644 Task/Thue-Morse/DuckDB/thue-morse-1.duckdb create mode 100644 Task/Thue-Morse/DuckDB/thue-morse-2.duckdb create mode 100644 Task/Thue-Morse/Prolog/thue-morse.pro create mode 100644 Task/Tic-tac-toe/TAV/tic-tac-toe.tav create mode 100644 Task/Time-a-function/Agena/time-a-function.agena create mode 100644 Task/Time-a-function/DuckDB/time-a-function.duckdb create mode 100644 Task/Time-a-function/Fennel/time-a-function.fennel create mode 100644 Task/Time-a-function/Pluto/time-a-function.pluto create mode 100644 Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon create mode 100644 Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb create mode 100644 Task/Tokenize-a-string/Refal/tokenize-a-string.refal create mode 100644 Task/Tokenize-a-string/SETL/tokenize-a-string.setl create mode 100644 Task/Tokenize-a-string/TAV/tokenize-a-string.tav create mode 100644 Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart create mode 100644 Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math create mode 100644 Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp create mode 100644 Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r create mode 100644 Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala create mode 100644 Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb create mode 100644 Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb create mode 100644 Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb create mode 100644 Task/Topic-variable/Maxima/topic-variable.maxima create mode 100644 Task/Topswops/Prolog/topswops.pro create mode 100644 Task/Total-circles-area/Ada/total-circles-area.ada create mode 100644 Task/Total-circles-area/Pluto/total-circles-area-1.pluto create mode 100644 Task/Total-circles-area/Pluto/total-circles-area-2.pluto create mode 100644 Task/Totient-function/Agena/totient-function.agena create mode 100644 Task/Totient-function/Fortran/totient-function.f create mode 100644 Task/Totient-function/Pluto/totient-function.pluto create mode 100644 Task/Towers-of-Hanoi/Maxima/towers-of-hanoi.maxima create mode 100644 Task/Towers-of-Hanoi/Pluto/towers-of-hanoi.pluto create mode 100644 Task/Towers-of-Hanoi/Red/towers-of-hanoi.red create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Pluto/trabb-pardo-knuth-algorithm.pluto create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Prolog/trabb-pardo-knuth-algorithm.pro create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/QB64/trabb-pardo-knuth-algorithm.qb64 create mode 100644 Task/Transliterate-English-text-using-the-Greek-alphabet/FreeBASIC/transliterate-english-text-using-the-greek-alphabet.basic create mode 100644 Task/Tree-datastructures/Rust/tree-datastructures.rs create mode 100644 Task/Tree-datastructures/Zig/tree-datastructures.zig create mode 100644 Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon create mode 100644 Task/Tree-traversal/Adina/tree-traversal-1.adina create mode 100644 Task/Tree-traversal/Adina/tree-traversal-2.adina create mode 100644 Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb create mode 100644 Task/Twos-complement/Ada/twos-complement.ada create mode 100644 Task/Twos-complement/Fortran/twos-complement.f create mode 100644 Task/UPC/Pluto/upc.pluto create mode 100644 Task/UPC/Rust/upc.rs create mode 100644 Task/UPC/Scala/upc.scala create mode 100644 Task/URL-decoding/DuckDB/url-decoding.duckdb create mode 100644 Task/UTF-8-encode-and-decode/DuckDB/utf-8-encode-and-decode.duckdb create mode 100644 Task/Undefined-values/YAMLScript/undefined-values.ys create mode 100644 Task/Unicode-strings/EasyLang/unicode-strings.easy create mode 100644 Task/Unicode-strings/Pluto/unicode-strings.pluto create mode 100644 Task/Unix-ls/DuckDB/unix-ls.duckdb create mode 100644 Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena create mode 100644 Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto create mode 100644 Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl create mode 100644 Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl create mode 100644 Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl create mode 100644 Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl create mode 100644 Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua create mode 100644 Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua create mode 100644 Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua create mode 100644 Task/User-input-Graphical/FuncSug/user-input-graphical.funcsug create mode 100644 Task/User-input-Text/ArkScript/user-input-text.ark create mode 100644 Task/User-input-Text/Extended-Color-BASIC/user-input-text.basic create mode 100644 Task/User-input-Text/Pluto/user-input-text.pluto create mode 100644 Task/Van-Eck-sequence/Agena/van-eck-sequence.agena create mode 100644 Task/Van-Eck-sequence/Pluto/van-eck-sequence.pluto create mode 100644 Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena create mode 100644 Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto create mode 100644 Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys create mode 100644 Task/Variable-size-Get/DuckDB/variable-size-get.duckdb create mode 100644 Task/Variable-size-Set/DuckDB/variable-size-set.duckdb create mode 100644 Task/Variables/Bc/variables.bc create mode 100644 Task/Variadic-function/Pluto/variadic-function.pluto create mode 100644 Task/Vector-products/DuckDB/vector-products.duckdb create mode 100644 Task/Vector-products/Pluto/vector-products.pluto create mode 100644 Task/Vector/Ada/vector.ada create mode 100644 Task/Vector/Pluto/vector.pluto create mode 100644 Task/Verhoeff-algorithm/Zig/verhoeff-algorithm.zig create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Zig/vigen-re-cipher-cryptanalysis.zig create mode 100644 Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs create mode 100644 Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math create mode 100644 Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig create mode 100644 Task/Wagstaff-primes/Agena/wagstaff-primes.agena create mode 100644 Task/Wagstaff-primes/Lua/wagstaff-primes.lua create mode 100644 Task/Wagstaff-primes/Pluto/wagstaff-primes.pluto create mode 100644 Task/Wagstaff-primes/Ring/wagstaff-primes.ring create mode 100644 Task/War-card-game/Rust/war-card-game.rs create mode 100644 Task/War-card-game/Zig/war-card-game.zig create mode 100644 Task/Wieferich-primes/Agena/wieferich-primes.agena create mode 100644 Task/Wieferich-primes/Common-Lisp/wieferich-primes.lisp create mode 100644 Task/Wieferich-primes/Lua/wieferich-primes.lua create mode 100644 Task/Wieferich-primes/Pluto/wieferich-primes.pluto create mode 100644 Task/Wieferich-primes/R/wieferich-primes.r create mode 100644 Task/Window-creation/TAV/window-creation.tav create mode 100644 Task/Wireworld/Prolog/wireworld.pro create mode 100644 Task/Word-frequency/TAV/word-frequency.tav create mode 100644 Task/Word-wheel/ALGOL-68/word-wheel.alg create mode 100644 Task/Word-wrap/FutureBasic/word-wrap.basic create mode 100644 Task/Write-entire-file/ArkScript/write-entire-file.ark create mode 100644 Task/Write-entire-file/R/write-entire-file.r create mode 100644 Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys create mode 100644 Task/Y-combinator/Pluto/y-combinator.pluto create mode 100644 Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena create mode 100644 Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel create mode 100644 Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic create mode 100644 Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto create mode 100644 Task/Yellowstone-sequence/YAMLScript/yellowstone-sequence.ys create mode 100644 Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic create mode 100644 Task/Zebra-puzzle/Pluto/zebra-puzzle.pluto create mode 100644 Task/Zero-to-the-zero-power/DuckDB/zero-to-the-zero-power.duckdb create mode 100644 Task/Zero-to-the-zero-power/Pluto/zero-to-the-zero-power.pluto create mode 100644 Task/Zero-to-the-zero-power/Prolog/zero-to-the-zero-power.pro create mode 100644 Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb create mode 100644 Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys diff --git a/.gitignore b/.gitignore index 26ab3c8d09..ecbdc2385f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ /Cache/ /Meta/ /rosettacode.log +/entry +/pick +/random-clojure-task +/.clj-kondo/ +/.lsp/ diff --git a/Conf/lang.yaml b/Conf/lang.yaml index 4ccf7202e4..bf92f9a54f 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -24,10 +24,12 @@ Action!: .action ActionScript: .as Acurity Architect: .acurity Ada: .ada +Adina: .adina Agda: .agda Agda2: .agda2 Agena: .agena AHDL: .ahdl +AIDED NATURAL LANGUAGE: .aided Aikido: .aikido Aime: .aime Algae: .algae @@ -51,6 +53,7 @@ Anyways: .anyways Apex: .apex APL: .apl App Inventor: .app +Apple: .apple AppleScript: .applescript Applesoft BASIC: .basic Application Master: .app @@ -60,6 +63,8 @@ Arbre: .arbre Arc: .arc Arendelle: .arendelle Argile: .argile +Aria: .aria +ArkScript: .ark ARM Assembly: .arm ArnoldC: .arnoldc Arturo: .arturo @@ -138,6 +143,7 @@ C1R: .c1r C2: .c2 C3: .c3 CafeOBJ: .cafeobj +Calcscript: .calc Caml: .caml Casio BASIC: .basic Cat: .cat @@ -157,6 +163,7 @@ ChucK: .chuck Cilk++: .cilk++ Cilk: .cilk Cind: .cind +CJam: .cjam Clarion: .clarion Clay: .clay Clean: .clean @@ -180,6 +187,7 @@ Common Lisp: .lisp Component Pascal: .pas Computer/zero Assembly: .0asm ContextFree: .cf +Convex: .convex Coq: .coq Corescript: .core Cowgol: .cowgol @@ -216,6 +224,7 @@ Draco: .draco Dragon: .dragon DreamBerd: .dreamberd Dt: .dt +DuckDB: .duckdb DUP: .dup DWScript: .dw Dyalect: .dyalect @@ -260,6 +269,7 @@ Evaldraw: .evaldraw Excel: .excel Explore: .explore Extended BrainF***: .ebf +Extended Color BASIC: .basic Ezhil: .ezhil F: .f Factor: .factor @@ -297,6 +307,7 @@ Frink: .frink FRISC Assembly: .frisc F Sharp: .fs FTCBASIC: .basic +FuncSug: .funcsug FunL: .funl Furor: .furor FurryScript: .furryscript @@ -329,6 +340,7 @@ Gnuplot: .gnuplot Go!: .go Go: .go Goaldi: .goaldi +Goboscript: .gobo Golfscript: .golf Golo: .golo Goo: .goo @@ -402,6 +414,7 @@ Julia: .jl K: .k Kabap: .kabap Kamailio Script: .kamailio +Kantalo: .kantalo KAP: .kap Kaya: .kaya Keg: .keg @@ -419,6 +432,7 @@ KQL: .kql Ksh: .ksh L++: .l++ LabVIEW: .labview +Labyrinth: .labyrinth Lambda Prolog: .pro Lambdatalk: .lambdatalk Lang: .lang @@ -518,6 +532,7 @@ ML: .ml ML/I: .mli MLite: .mlite MMIX: .mmix +Mn: .mn Modula-2: .mod2 Modula-3: .mod3 Mojo: .mojo @@ -565,6 +580,7 @@ Nit: .nit Niue: .niue Nix: .nix NLP++: .nlp++ +Nom: .num NOWUT: .nowut NQP: .nqp NS-HUBASIC: .basic @@ -581,6 +597,7 @@ Objeck: .objeck ObjectIcon: .oi Objective-C: .m Object Pascal: .pas +Object Pascal Implementations: .pas OCaml: .ml Occam: .occam Octave: .octave @@ -613,6 +630,7 @@ Pare: .pare PARI/GP: .parigp Pascal: .pas PascalABC.NET: .pas +Pascal-P: .pas PASM: .pasm PDP-11 Assembly: .pdp11 Pebble: .pebble @@ -630,6 +648,7 @@ Phixmonti: .phixmonti PHL: .phl PHP: .php Picat: .picat +Pico-8: .pico8 PicoLisp: .l Pict: .pict Piet: .piet @@ -648,6 +667,7 @@ PL/M: .plm PL/pgSQL: .sql PL/SQL: .sql PLUS: .plus +Pluto: .pluto PLZ/SYS: .plz Pointless: .pointless Polyglot: .polyglot @@ -711,6 +731,7 @@ ReScript: .re Retro: .retro Revolution: .rev REXX: .rexx +Rhombus: .rhombus Rhope: .rhope Rhovas: .rhovas Ring: .ring @@ -812,6 +833,7 @@ SystemVerilog: .v TailDot: .taildot Tailspin: .tailspin TAL: .tal +TAV: .tav Tbas: .tbas Tcl: .tcl TechBASIC: .basic @@ -872,6 +894,7 @@ UserRPL: .rpl UTFool: .utfool Uxntal: .uxnatl V: .v +V (Vlang): .v Vala: .vala Vale: .vale VAX Assembly: .vax @@ -893,7 +916,7 @@ Vorpal: .vorpal Vox: .vox VRML: .vrml VTL-2: .vtl-2 -V (Vlang): .v +Vyxal: .vyxal Waduzitdo: .waduzitdo Wart: .wart WDTE: .wdte diff --git a/Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt b/Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt new file mode 100644 index 0000000000..c25a056976 --- /dev/null +++ b/Lang/AIDED-NATURAL-LANGUAGE/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|Ayrch}} \ No newline at end of file diff --git a/Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml b/Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml new file mode 100644 index 0000000000..8395003e03 --- /dev/null +++ b/Lang/AIDED-NATURAL-LANGUAGE/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:AIDED_NATURAL_LANGUAGE diff --git a/Lang/ALGOL-60/Factorial b/Lang/ALGOL-60/Factorial deleted file mode 120000 index 67b243e1d0..0000000000 --- a/Lang/ALGOL-60/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-68/Date-manipulation b/Lang/ALGOL-68/Date-manipulation new file mode 120000 index 0000000000..700d602cf1 --- /dev/null +++ b/Lang/ALGOL-68/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series b/Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..242e3aeb60 --- /dev/null +++ b/Lang/ALGOL-68/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Factorial b/Lang/ALGOL-68/Factorial deleted file mode 120000 index b406800839..0000000000 --- a/Lang/ALGOL-68/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Knapsack-problem-Continuous b/Lang/ALGOL-68/Knapsack-problem-Continuous new file mode 120000 index 0000000000..f49865cc46 --- /dev/null +++ b/Lang/ALGOL-68/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Word-wheel b/Lang/ALGOL-68/Word-wheel new file mode 120000 index 0000000000..ab6aaa99f7 --- /dev/null +++ b/Lang/ALGOL-68/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Factorial b/Lang/ALGOL-W/Factorial deleted file mode 120000 index 01c77fb141..0000000000 --- a/Lang/ALGOL-W/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Knapsack-problem-Continuous b/Lang/ALGOL-W/Knapsack-problem-Continuous new file mode 120000 index 0000000000..fba28c1695 --- /dev/null +++ b/Lang/ALGOL-W/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/ALGOL-W \ No newline at end of file diff --git a/Lang/ANSI-BASIC/AKS-test-for-primes b/Lang/ANSI-BASIC/AKS-test-for-primes new file mode 120000 index 0000000000..4668d2783c --- /dev/null +++ b/Lang/ANSI-BASIC/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Old-Russian-measure-of-length b/Lang/ANSI-BASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..81f64cd54c --- /dev/null +++ b/Lang/ANSI-BASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/ANSI-BASIC \ No newline at end of file diff --git a/Lang/APL/Monte-Carlo-methods b/Lang/APL/Monte-Carlo-methods new file mode 120000 index 0000000000..2cf831a11c --- /dev/null +++ b/Lang/APL/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/00-LANG.txt b/Lang/ARM-Assembly/00-LANG.txt index 4c41d124d7..273ed5e757 100644 --- a/Lang/ARM-Assembly/00-LANG.txt +++ b/Lang/ARM-Assembly/00-LANG.txt @@ -4,9 +4,9 @@ The ARM architecture is widely used on mobile phones and tablets. It falls under ===Instruction Size=== Every instruction that the ARM can execute is 32 bits. While other processors can have variable length instructions, the ARM does not. This means that the ARM doesn't need to parse where an instruction begins and ends, which makes it run very fast. What you might not expect is that this 32-bit instruction size includes both the actual instruction and the operands! Let's take a look at a [[Z80 Assembly]] instruction and compare it to an ARM instruction. -LD HL,&8040 ;bytecode is 0x21 0x40 0x80 +LD HL,&8040 ;bytecode is 0x21 0x40 0x80 -mov r4,#0x04000000 ;bytecode is 0xE3A04301 +mov r4,#0x04000000 ;bytecode is 0xE3A04301 So where did the 0x04000000 go? It's actually been compressed and fit within those 4 bytes you saw earlier. The ARM is very good at decompressing it, since it's been shrunk to an 8-bit number that can be rotated by an even number of bits. Unfortunately, this compression method is a double-edged sword - some 32-bit numbers can't be compressed this way, and thus many instructions can't work with them! @@ -18,72 +18,73 @@ Registers are much more flexible than immediate operands. Unlike immediate opera Getting an address in a register can be achieved with the MOV command, but there are limitations to that which will be explained in detail later. It's more reliable to use ADR which loads a nearby address into a register. This address has to be within a certain distance from the current program counter or it can't be loaded, so it's not a reliable way to load from the heap on many machines. It's mostly intended for loading from nearby read-only data, such as text strings or stored immediates (more on that later). When you type ADR R0,LABEL, the assembler will convert this to MOV R0,PC,#N, where N is the difference between the current program counter value and the label you specified. LDR can be used in a similar fashion to ADR but there is a subtle distinction between the two. Assume that the section below is assembled starting at memory address 0x04000000: -DataBlock: +DataBlock: .long 0xDEADBEEF ;VASM uses .long for 32-bit data and .word for 16-bit data. Your assembler will probably use .word for 32 bit and .long 0xFFFFFFFF ; .hword for 16-bit. MyCode: adr r0, DataBlock ;loads the value 0x04000000 into R0 - ldr r1, DataBlock ;loads the value 0xDEADBEEF into R1 - adr r2, DataBlock+4 ;loads the value 0x04000004 into R2 - -ldr r3, DataBlock+4 ;loads the value 0xFFFFFFFF into R3 +ldr r3, DataBlock+4 ;loads the value 0xFFFFFFFF into R3 + As you can see, ADR only gives you the memory location of a value in memory, where LDR loads ''from'' that memory location. - ===Data Addressing using LDR and STR=== Unlike its "cousin," the Motorola 68000 (which isn't really related but has a somewhat similar design), the ARM cannot directly write immediate values to memory. Those values must be contained in registers first. Unlike the 68000, the ARM has no "address registers." Rather, enclosing a register name in square brackets turns its value into a reference to a memory location. You'll need to load that memory location's numeric "value" as a constant first. Then you can read from it with LDR and write to it with STR. Not only can you read from a given address, you can also adjust how you read from it, and what you do before or after the read. -RAM_ADDRESS: +RAM_ADDRESS: .long 0 ;for simplicity we'll assume that this can actually be written to. Represents a placeholder for 32-bit data. ;Your assembler's syntax may be different. - .long 0 ;another placeholder for 32-bit data MyCode: adr R2,RAM_Address ;get the address of a nearby place to store values. MOV R0,#0x12345678 ;the value to store. -STR R0,[R2] ;store 0x12345678 into the first 32-bit slot. +STR R0,[R2] ;store 0x12345678 into the first 32-bit slot. + This is the basic way to store into memory, but there are other options, such as offsetting and post-increment. -RAM_ADDRESS: +RAM_ADDRESS: .long 0 .long 0 ;we'll store here this time. MyCode: adr R2,RAM_Address ;point R2 to the first storage slot MOV R0,#0x12345678 -STR R0,[R2,#4] ;store into the SECOND slot. R2 still points to the first slot - the #4 is added to R2 only temporarily. +STR R0,[R2,#4] ;store into the SECOND slot. R2 still points to the first slot - the #4 is added to R2 only temporarily. + There's a limit on the size of an immediate value used to offset when loading/storing. You can also use a register as an offset, whose value will be added to the address. -RAM_AREA: +RAM_AREA: .space 64,0 ;64 bytes of ram ;assume that R2 contains the address of "RAM_AREA" MyCode: MOV R0,#0x12345678 MOV R1,#20 -STR R0,[R2,R1] ;equivalent of "STR R0,[R2,#20]" +STR R0,[R2,R1] ;equivalent of "STR R0,[R2,#20]" + Now let's say you wanted to actually alter the pointer to R2, so that it remains pointing to where you offset it to after the store or load. That's an option you have - all you have to do is type "!" after the brackets. This is called "pre-increment" or "pre-indexing." -RAM_ADDRESS: +RAM_ADDRESS: .long 0 .long 0 ;we'll store here this time, and we want R2 to still be pointing here after we write to it. MyCode: adr R2,RAM_Address ;point R2 to the first storage slot MOV R0,#0x12345678 -STR R0,[R2,#4]! ;store into the SECOND slot. R2 also points to the second slot now, even after this instruction has concluded. +STR R0,[R2,#4]! ;store into the SECOND slot. R2 also points to the second slot now, even after this instruction has concluded. + Here, the offset is performed ''before'' the storage operation. What if you want to offset afterwards? That would be useful for reading in a data stream. Good news - you can do that simply by having the offset value or register '''outside''' the brackets. This is called "post-increment" or "post-indexing." Unlike pre-indexing, these changes to the pointer are not temporary. -LDR R0,[R1],#4 ;load the 32-bit value stored at memory location R1 into R0, THEN add 4 to R1. This offset remains even after this - ; instruction is finished. +LDR R0,[R1],#4 ;load the 32-bit value stored at memory location R1 into R0, THEN add 4 to R1. This offset remains even after this + ; instruction is finished. + ===Barrel Shifter=== The ARM can add a bit shift or rotate to one of its operands at no additional cost to execution time or bytecode. If the operand being shifted is a register, the value of that register is not actually changed. The shift or rotate only applies during that instruction. diff --git a/Lang/ASIC/Old-Russian-measure-of-length b/Lang/ASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..e5e809a47d --- /dev/null +++ b/Lang/ASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/ASIC \ No newline at end of file diff --git a/Lang/AWK/100-doors b/Lang/AWK/100-doors deleted file mode 120000 index 99c9a19f16..0000000000 --- a/Lang/AWK/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/AWK \ No newline at end of file diff --git a/Lang/AWK/Factorial-primes b/Lang/AWK/Factorial-primes new file mode 120000 index 0000000000..7344ad75fd --- /dev/null +++ b/Lang/AWK/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/AWK \ No newline at end of file diff --git a/Lang/AWK/Soloways-recurring-rainfall b/Lang/AWK/Soloways-recurring-rainfall new file mode 120000 index 0000000000..1f850c19b0 --- /dev/null +++ b/Lang/AWK/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/AWK \ No newline at end of file diff --git a/Lang/Ada/Almkvist-Giullera-formula-for-pi b/Lang/Ada/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..66015473cd --- /dev/null +++ b/Lang/Ada/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/Ada \ No newline at end of file diff --git a/Lang/Ada/Biorhythms b/Lang/Ada/Biorhythms new file mode 120000 index 0000000000..0d82777906 --- /dev/null +++ b/Lang/Ada/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Ada \ No newline at end of file diff --git a/Lang/Ada/Boyer-Moore-string-search b/Lang/Ada/Boyer-Moore-string-search new file mode 120000 index 0000000000..114c2a5fea --- /dev/null +++ b/Lang/Ada/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Ada \ No newline at end of file diff --git a/Lang/Ada/Calkin-Wilf-sequence b/Lang/Ada/Calkin-Wilf-sequence new file mode 120000 index 0000000000..9e4b8cd779 --- /dev/null +++ b/Lang/Ada/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Ada \ No newline at end of file diff --git a/Lang/Ada/Camel-case-and-snake-case b/Lang/Ada/Camel-case-and-snake-case new file mode 120000 index 0000000000..1d95b38233 --- /dev/null +++ b/Lang/Ada/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Ada \ No newline at end of file diff --git a/Lang/Ada/Canonicalize-CIDR b/Lang/Ada/Canonicalize-CIDR new file mode 120000 index 0000000000..c0c0b338b8 --- /dev/null +++ b/Lang/Ada/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/Ada \ No newline at end of file diff --git a/Lang/Ada/Deepcopy b/Lang/Ada/Deepcopy new file mode 120000 index 0000000000..4b1e30735d --- /dev/null +++ b/Lang/Ada/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Ada \ No newline at end of file diff --git a/Lang/Ada/Factorions b/Lang/Ada/Factorions new file mode 120000 index 0000000000..d9b74415a9 --- /dev/null +++ b/Lang/Ada/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/Ada \ No newline at end of file diff --git a/Lang/Ada/Find-duplicate-files b/Lang/Ada/Find-duplicate-files new file mode 120000 index 0000000000..f7ad1ff6fd --- /dev/null +++ b/Lang/Ada/Find-duplicate-files @@ -0,0 +1 @@ +../../Task/Find-duplicate-files/Ada \ No newline at end of file diff --git a/Lang/Ada/Harmonic-series b/Lang/Ada/Harmonic-series new file mode 120000 index 0000000000..97492bcb66 --- /dev/null +++ b/Lang/Ada/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Ada \ No newline at end of file diff --git a/Lang/Ada/Knapsack-problem-Bounded b/Lang/Ada/Knapsack-problem-Bounded new file mode 120000 index 0000000000..1cfbda0d29 --- /dev/null +++ b/Lang/Ada/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Ada \ No newline at end of file diff --git a/Lang/Ada/Levenshtein-distance-Alignment b/Lang/Ada/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..1c6a7ca906 --- /dev/null +++ b/Lang/Ada/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/Ada \ No newline at end of file diff --git a/Lang/Ada/Long-literals-with-continuations b/Lang/Ada/Long-literals-with-continuations new file mode 120000 index 0000000000..9d6be6cfc8 --- /dev/null +++ b/Lang/Ada/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/Ada \ No newline at end of file diff --git a/Lang/Ada/Longest-increasing-subsequence b/Lang/Ada/Longest-increasing-subsequence new file mode 120000 index 0000000000..dd360a694d --- /dev/null +++ b/Lang/Ada/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Ada \ No newline at end of file diff --git a/Lang/Ada/Machine-code b/Lang/Ada/Machine-code new file mode 120000 index 0000000000..52ae4edc91 --- /dev/null +++ b/Lang/Ada/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Ada \ No newline at end of file diff --git a/Lang/Ada/Minimal-steps-down-to-1 b/Lang/Ada/Minimal-steps-down-to-1 new file mode 120000 index 0000000000..44f17e189f --- /dev/null +++ b/Lang/Ada/Minimal-steps-down-to-1 @@ -0,0 +1 @@ +../../Task/Minimal-steps-down-to-1/Ada \ No newline at end of file diff --git a/Lang/Ada/Naming-conventions b/Lang/Ada/Naming-conventions new file mode 120000 index 0000000000..44f00f1ff1 --- /dev/null +++ b/Lang/Ada/Naming-conventions @@ -0,0 +1 @@ +../../Task/Naming-conventions/Ada \ No newline at end of file diff --git a/Lang/Ada/Read-a-file-character-by-character-UTF8 b/Lang/Ada/Read-a-file-character-by-character-UTF8 new file mode 120000 index 0000000000..71f788273b --- /dev/null +++ b/Lang/Ada/Read-a-file-character-by-character-UTF8 @@ -0,0 +1 @@ +../../Task/Read-a-file-character-by-character-UTF8/Ada \ No newline at end of file diff --git a/Lang/Ada/Test-integerness b/Lang/Ada/Test-integerness new file mode 120000 index 0000000000..8a5462dcb5 --- /dev/null +++ b/Lang/Ada/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/Ada \ No newline at end of file diff --git a/Lang/Ada/Total-circles-area b/Lang/Ada/Total-circles-area new file mode 120000 index 0000000000..781e585826 --- /dev/null +++ b/Lang/Ada/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Ada \ No newline at end of file diff --git a/Lang/Ada/Twos-complement b/Lang/Ada/Twos-complement new file mode 120000 index 0000000000..396d1a76f2 --- /dev/null +++ b/Lang/Ada/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Ada \ No newline at end of file diff --git a/Lang/Ada/Vector b/Lang/Ada/Vector new file mode 120000 index 0000000000..4cc7975e2f --- /dev/null +++ b/Lang/Ada/Vector @@ -0,0 +1 @@ +../../Task/Vector/Ada \ No newline at end of file diff --git a/Lang/Adina/00-LANG.txt b/Lang/Adina/00-LANG.txt new file mode 100644 index 0000000000..e796807867 --- /dev/null +++ b/Lang/Adina/00-LANG.txt @@ -0,0 +1,13 @@ +{{language|Adina}} +Adina is a programming language, based on Racket and russian language. Unlike Racket it uses indent and operators precedence to describe program syntax. It may be used in english, because all Racket libraries are accessible. One should add "english()" in first string to use standard racket libraries. + +Адина, это язык программирования, основанный на Racket и русском языке. В отличие от Racket вместо скобок для синтаксической +структуры используются отступы и бинарные операторы. Также сделан доступ через квадратные скобки к элементам коллекции и через фигурные к методам объектов. + +Документация по адресу: https://docs.racket-lang.org/russian-lang/ + +==See Also== +* [[Racket]] + +==TODO== +[[Tasks not implemented in Adina]] \ No newline at end of file diff --git a/Lang/Adina/00-META.yaml b/Lang/Adina/00-META.yaml new file mode 100644 index 0000000000..e1ca8650ca --- /dev/null +++ b/Lang/Adina/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Adina diff --git a/Lang/Adina/100-doors b/Lang/Adina/100-doors new file mode 120000 index 0000000000..c96d2d65fc --- /dev/null +++ b/Lang/Adina/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Adina \ No newline at end of file diff --git a/Lang/Adina/Even-or-odd b/Lang/Adina/Even-or-odd new file mode 120000 index 0000000000..1718b42d76 --- /dev/null +++ b/Lang/Adina/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Adina \ No newline at end of file diff --git a/Lang/Adina/Hello-world-Text b/Lang/Adina/Hello-world-Text new file mode 120000 index 0000000000..f886a7cc4f --- /dev/null +++ b/Lang/Adina/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Adina \ No newline at end of file diff --git a/Lang/Adina/Loops-For b/Lang/Adina/Loops-For new file mode 120000 index 0000000000..c4d6bee093 --- /dev/null +++ b/Lang/Adina/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Adina \ No newline at end of file diff --git a/Lang/Adina/Tree-traversal b/Lang/Adina/Tree-traversal new file mode 120000 index 0000000000..fd3896d623 --- /dev/null +++ b/Lang/Adina/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Adina \ No newline at end of file diff --git a/Lang/Agena/00-LANG.txt b/Lang/Agena/00-LANG.txt index c2930ac7a2..c8171cc29e 100644 --- a/Lang/Agena/00-LANG.txt +++ b/Lang/Agena/00-LANG.txt @@ -21,4 +21,6 @@ The syntax looks like very simplified [[ALGOL 68]] with elements taken from [[Lu Agena is based on the [[ANSI]] [[C]] source code of [[Lua]], a popular and widely used Open Source programming language. == See Also == -[[ALGOL 68]] \ No newline at end of file +[[ALGOL 68]]
+[[Lua]]
+[[SQL]] \ No newline at end of file diff --git a/Lang/Agena/AKS-test-for-primes b/Lang/Agena/AKS-test-for-primes new file mode 120000 index 0000000000..ab27a842c8 --- /dev/null +++ b/Lang/Agena/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Abundant-deficient-and-perfect-number-classifications b/Lang/Agena/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..89450cb83c --- /dev/null +++ b/Lang/Agena/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Agena \ No newline at end of file diff --git a/Lang/Agena/Abundant-odd-numbers b/Lang/Agena/Abundant-odd-numbers new file mode 120000 index 0000000000..a18ccbb662 --- /dev/null +++ b/Lang/Agena/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Arbitrary-precision-integers-included- b/Lang/Agena/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..347104998a --- /dev/null +++ b/Lang/Agena/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Agena \ No newline at end of file diff --git a/Lang/Agena/Attractive-numbers b/Lang/Agena/Attractive-numbers new file mode 120000 index 0000000000..bc968b5d21 --- /dev/null +++ b/Lang/Agena/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Disarium-numbers b/Lang/Agena/Disarium-numbers new file mode 120000 index 0000000000..2bace62b71 --- /dev/null +++ b/Lang/Agena/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Factorial b/Lang/Agena/Factorial new file mode 120000 index 0000000000..21cbc1e46b --- /dev/null +++ b/Lang/Agena/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Agena \ No newline at end of file diff --git a/Lang/Agena/Factorial-primes b/Lang/Agena/Factorial-primes new file mode 120000 index 0000000000..68796e7224 --- /dev/null +++ b/Lang/Agena/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Giuga-numbers b/Lang/Agena/Giuga-numbers new file mode 120000 index 0000000000..273fdf8c7c --- /dev/null +++ b/Lang/Agena/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Goldbachs-comet b/Lang/Agena/Goldbachs-comet new file mode 120000 index 0000000000..26b052a294 --- /dev/null +++ b/Lang/Agena/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Agena \ No newline at end of file diff --git a/Lang/Agena/Horners-rule-for-polynomial-evaluation b/Lang/Agena/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..cffe37e87c --- /dev/null +++ b/Lang/Agena/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Agena \ No newline at end of file diff --git a/Lang/Agena/Humble-numbers b/Lang/Agena/Humble-numbers new file mode 120000 index 0000000000..bdce77fd35 --- /dev/null +++ b/Lang/Agena/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/JSON b/Lang/Agena/JSON new file mode 120000 index 0000000000..9c20f7b68f --- /dev/null +++ b/Lang/Agena/JSON @@ -0,0 +1 @@ +../../Task/JSON/Agena \ No newline at end of file diff --git a/Lang/Agena/Jacobsthal-numbers b/Lang/Agena/Jacobsthal-numbers new file mode 120000 index 0000000000..740d21ef1a --- /dev/null +++ b/Lang/Agena/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Jewels-and-stones b/Lang/Agena/Jewels-and-stones new file mode 120000 index 0000000000..7c03f8ec8f --- /dev/null +++ b/Lang/Agena/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Agena \ No newline at end of file diff --git a/Lang/Agena/Kaprekar-numbers b/Lang/Agena/Kaprekar-numbers new file mode 120000 index 0000000000..d665f2f5f5 --- /dev/null +++ b/Lang/Agena/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Mian-Chowla-sequence b/Lang/Agena/Mian-Chowla-sequence new file mode 120000 index 0000000000..a6489175a6 --- /dev/null +++ b/Lang/Agena/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Pernicious-numbers b/Lang/Agena/Pernicious-numbers new file mode 120000 index 0000000000..454ce5b94d --- /dev/null +++ b/Lang/Agena/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Pisano-period b/Lang/Agena/Pisano-period new file mode 120000 index 0000000000..afaae8dce9 --- /dev/null +++ b/Lang/Agena/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Agena \ No newline at end of file diff --git a/Lang/Agena/Primality-by-trial-division b/Lang/Agena/Primality-by-trial-division new file mode 120000 index 0000000000..621c0609eb --- /dev/null +++ b/Lang/Agena/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Agena \ No newline at end of file diff --git a/Lang/Agena/Sequence-of-primes-by-trial-division b/Lang/Agena/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..d7958a31a1 --- /dev/null +++ b/Lang/Agena/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/Agena \ No newline at end of file diff --git a/Lang/Agena/Smarandache-prime-digital-sequence b/Lang/Agena/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..3a1f0e0805 --- /dev/null +++ b/Lang/Agena/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Soloways-recurring-rainfall b/Lang/Agena/Soloways-recurring-rainfall new file mode 120000 index 0000000000..b391a79582 --- /dev/null +++ b/Lang/Agena/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/Agena \ No newline at end of file diff --git a/Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..6bd7256f3a --- /dev/null +++ b/Lang/Agena/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Agena \ No newline at end of file diff --git a/Lang/Agena/Time-a-function b/Lang/Agena/Time-a-function new file mode 120000 index 0000000000..e5746c4dff --- /dev/null +++ b/Lang/Agena/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Totient-function b/Lang/Agena/Totient-function new file mode 120000 index 0000000000..d74f15771c --- /dev/null +++ b/Lang/Agena/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Agena \ No newline at end of file diff --git a/Lang/Agena/Unprimeable-numbers b/Lang/Agena/Unprimeable-numbers new file mode 120000 index 0000000000..fc3b30fec4 --- /dev/null +++ b/Lang/Agena/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/Agena \ No newline at end of file diff --git a/Lang/Agena/Van-Eck-sequence b/Lang/Agena/Van-Eck-sequence new file mode 120000 index 0000000000..1714aa1507 --- /dev/null +++ b/Lang/Agena/Van-Eck-sequence @@ -0,0 +1 @@ +../../Task/Van-Eck-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Van-der-Corput-sequence b/Lang/Agena/Van-der-Corput-sequence new file mode 120000 index 0000000000..92bec950df --- /dev/null +++ b/Lang/Agena/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Agena \ No newline at end of file diff --git a/Lang/Agena/Wagstaff-primes b/Lang/Agena/Wagstaff-primes new file mode 120000 index 0000000000..b63d3369fa --- /dev/null +++ b/Lang/Agena/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Wieferich-primes b/Lang/Agena/Wieferich-primes new file mode 120000 index 0000000000..34597fbb1d --- /dev/null +++ b/Lang/Agena/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Agena \ No newline at end of file diff --git a/Lang/Agena/Yellowstone-sequence b/Lang/Agena/Yellowstone-sequence new file mode 120000 index 0000000000..4464a6e815 --- /dev/null +++ b/Lang/Agena/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Agena \ No newline at end of file diff --git a/Lang/Apple/00-LANG.txt b/Lang/Apple/00-LANG.txt new file mode 100644 index 0000000000..e4e452b143 --- /dev/null +++ b/Lang/Apple/00-LANG.txt @@ -0,0 +1,12 @@ +{{language|Apple +|exec=Compiled +|safety=safe +|checking=static +|strength=strong +|site=https://github.com/vmchale/apple}} + +{{language programming paradigm|functional}} + +The Apple Array System is a JIT-compiler for a statically typed functional language specialized on arrays. + +It is expression-oriented (it has no imports); it is meant to be called from other languages. \ No newline at end of file diff --git a/Lang/Apple/00-META.yaml b/Lang/Apple/00-META.yaml new file mode 100644 index 0000000000..fcdeec5d5c --- /dev/null +++ b/Lang/Apple/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Apple diff --git a/Lang/Apple/Averages-Arithmetic-mean b/Lang/Apple/Averages-Arithmetic-mean new file mode 120000 index 0000000000..b4236a6909 --- /dev/null +++ b/Lang/Apple/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Apple \ No newline at end of file diff --git a/Lang/Apple/Averages-Pythagorean-means b/Lang/Apple/Averages-Pythagorean-means new file mode 120000 index 0000000000..50c70e6c0b --- /dev/null +++ b/Lang/Apple/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Apple \ No newline at end of file diff --git a/Lang/Apple/Catamorphism b/Lang/Apple/Catamorphism new file mode 120000 index 0000000000..5d06cbf18d --- /dev/null +++ b/Lang/Apple/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Apple \ No newline at end of file diff --git a/Lang/Apple/Dot-product b/Lang/Apple/Dot-product new file mode 120000 index 0000000000..084fc21920 --- /dev/null +++ b/Lang/Apple/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Apple \ No newline at end of file diff --git a/Lang/Apple/Factorial b/Lang/Apple/Factorial new file mode 120000 index 0000000000..8d659daa6f --- /dev/null +++ b/Lang/Apple/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Apple \ No newline at end of file diff --git a/Lang/Apple/Factors-of-an-integer b/Lang/Apple/Factors-of-an-integer new file mode 120000 index 0000000000..a965a5d4bd --- /dev/null +++ b/Lang/Apple/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Apple \ No newline at end of file diff --git a/Lang/Apple/Filter b/Lang/Apple/Filter new file mode 120000 index 0000000000..5dfbcaf92d --- /dev/null +++ b/Lang/Apple/Filter @@ -0,0 +1 @@ +../../Task/Filter/Apple \ No newline at end of file diff --git a/Lang/Apple/ISBN13-check-digit b/Lang/Apple/ISBN13-check-digit new file mode 120000 index 0000000000..b9d843e9fc --- /dev/null +++ b/Lang/Apple/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Apple \ No newline at end of file diff --git a/Lang/Aria/00-LANG.txt b/Lang/Aria/00-LANG.txt new file mode 100644 index 0000000000..f3d1668eba --- /dev/null +++ b/Lang/Aria/00-LANG.txt @@ -0,0 +1,15 @@ +{{language +|exec=interpreted +|site=https://egranata.github.io/aria/ +}} + +Aria is a modern, dynamic scripting language. It is meant to be a “sweet spot” language, easy to pick-up and enjoyable to use. + +It provides a familiar C-style syntax, with a feature set inspired by well-beloved languages such as Python and Rust. It comes with little ceremony and a focus on getting stuff done. + +Aria programs are written as .aria files and passed to the Aria virtual machine, which compiles them down to bytecode and executes them. + +The Aria interpreter is written in Rust, 2024 edition. + +==Todo== +[[Tasks_not_implemented_in_Aria]] \ No newline at end of file diff --git a/Lang/Aria/00-META.yaml b/Lang/Aria/00-META.yaml new file mode 100644 index 0000000000..35ebadd91a --- /dev/null +++ b/Lang/Aria/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Aria diff --git a/Lang/Aria/99-bottles-of-beer b/Lang/Aria/99-bottles-of-beer new file mode 120000 index 0000000000..c2f486227d --- /dev/null +++ b/Lang/Aria/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Aria \ No newline at end of file diff --git a/Lang/Aria/Hello-world-Text b/Lang/Aria/Hello-world-Text new file mode 120000 index 0000000000..bb8e1db7a7 --- /dev/null +++ b/Lang/Aria/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Aria \ No newline at end of file diff --git a/Lang/ArkScript/00-LANG.txt b/Lang/ArkScript/00-LANG.txt new file mode 100644 index 0000000000..11fc16bd5b --- /dev/null +++ b/Lang/ArkScript/00-LANG.txt @@ -0,0 +1,43 @@ +{{language|ArkScript +|exec=bytecode +|site=https://arkscript-lang.dev +|gc=no +|parampass=value +|strength=strong +|checking=dynamic +|tags=arkscript}} +ArkScript is a small, fast, functional and scripting language for C++ projects, inspired by [[Lua]], [[Lisp]], and [[Python]]. + +The language has been designed to be concise, with only 9 keywords, and two rules to parse it: +# the first node after an opening paren ( is a "function", the following nodes are arguments +# the only exception to the previous rule is when defining the argument list of a function + + +(let foo 5) +(let bar "hello world!") + +(let egg (fun (a b c) + (+ a (* b c)))) + +(print (egg 1 foo bar)) + + +The language is also +* small: the core fit under 8000 lines of code ; also small in terms of keywords (only 9) +* a scripting language: very easy to embed it in your projects. Registering your own functions in the language is made easy +* portable: a unique bytecode which can be run everywhere the virtual machine is +* a functional language: every parameter is passed by value, everything is immutable unless specified +* powerful: provides closures and explicit capture +* promoting functionalities before performances: expressiveness often brings more productivity, though performances aren't left behind +* a Lisp inspired language, with fewer parentheses: [...] is expanded to (list ...) and {} to (begin ...) +* extensible: supports C++ module to use it in the language, adding functionalities + + +===Implementation=== +The compiler and VM are implemented in [[C++]] 20. For more details, see [https://github.com/ArkScript-lang/Ark ArkScript GitHub]. + +===License=== +ArkScript is released under the Mozilla Public License 2.0. + +===Todo=== +[[Tasks not implemented in ArkScript]] \ No newline at end of file diff --git a/Lang/ArkScript/00-META.yaml b/Lang/ArkScript/00-META.yaml new file mode 100644 index 0000000000..0a989734f8 --- /dev/null +++ b/Lang/ArkScript/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:ArkScript diff --git a/Lang/ArkScript/100-doors b/Lang/ArkScript/100-doors new file mode 120000 index 0000000000..733c5ecdec --- /dev/null +++ b/Lang/ArkScript/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/99-bottles-of-beer b/Lang/ArkScript/99-bottles-of-beer new file mode 120000 index 0000000000..44d94215f1 --- /dev/null +++ b/Lang/ArkScript/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/A+B b/Lang/ArkScript/A+B new file mode 120000 index 0000000000..482decfa5a --- /dev/null +++ b/Lang/ArkScript/A+B @@ -0,0 +1 @@ +../../Task/A+B/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Abbreviations-easy b/Lang/ArkScript/Abbreviations-easy new file mode 120000 index 0000000000..03457b23d1 --- /dev/null +++ b/Lang/ArkScript/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Ackermann-function b/Lang/ArkScript/Ackermann-function new file mode 120000 index 0000000000..f1f525fde6 --- /dev/null +++ b/Lang/ArkScript/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Apply-a-callback-to-an-array b/Lang/ArkScript/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..da474aa4d7 --- /dev/null +++ b/Lang/ArkScript/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Arithmetic-Complex b/Lang/ArkScript/Arithmetic-Complex new file mode 120000 index 0000000000..c21a1d5bf8 --- /dev/null +++ b/Lang/ArkScript/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Arithmetic-Integer b/Lang/ArkScript/Arithmetic-Integer new file mode 120000 index 0000000000..0023796f90 --- /dev/null +++ b/Lang/ArkScript/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Array-concatenation b/Lang/ArkScript/Array-concatenation new file mode 120000 index 0000000000..250e35894f --- /dev/null +++ b/Lang/ArkScript/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Array-length b/Lang/ArkScript/Array-length new file mode 120000 index 0000000000..f70d67437b --- /dev/null +++ b/Lang/ArkScript/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Ascending-primes b/Lang/ArkScript/Ascending-primes new file mode 120000 index 0000000000..9fc34de6f6 --- /dev/null +++ b/Lang/ArkScript/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Associative-array-Creation b/Lang/ArkScript/Associative-array-Creation new file mode 120000 index 0000000000..2a5f3a1e53 --- /dev/null +++ b/Lang/ArkScript/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Associative-array-Iteration b/Lang/ArkScript/Associative-array-Iteration new file mode 120000 index 0000000000..f11b39f9bb --- /dev/null +++ b/Lang/ArkScript/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Balanced-brackets b/Lang/ArkScript/Balanced-brackets new file mode 120000 index 0000000000..7380d4a234 --- /dev/null +++ b/Lang/ArkScript/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Boolean-values b/Lang/ArkScript/Boolean-values new file mode 120000 index 0000000000..5efbe13431 --- /dev/null +++ b/Lang/ArkScript/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Calculating-the-value-of-e b/Lang/ArkScript/Calculating-the-value-of-e new file mode 120000 index 0000000000..0a0116531f --- /dev/null +++ b/Lang/ArkScript/Calculating-the-value-of-e @@ -0,0 +1 @@ +../../Task/Calculating-the-value-of-e/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Call-a-function b/Lang/ArkScript/Call-a-function new file mode 120000 index 0000000000..4d2870d9cb --- /dev/null +++ b/Lang/ArkScript/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Call-an-object-method b/Lang/ArkScript/Call-an-object-method new file mode 120000 index 0000000000..9b53aa0595 --- /dev/null +++ b/Lang/ArkScript/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Catamorphism b/Lang/ArkScript/Catamorphism new file mode 120000 index 0000000000..f6210b0ec4 --- /dev/null +++ b/Lang/ArkScript/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Check-that-file-exists b/Lang/ArkScript/Check-that-file-exists new file mode 120000 index 0000000000..7e3651c090 --- /dev/null +++ b/Lang/ArkScript/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Closures-Value-capture b/Lang/ArkScript/Closures-Value-capture new file mode 120000 index 0000000000..6b30a8d976 --- /dev/null +++ b/Lang/ArkScript/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Comments b/Lang/ArkScript/Comments new file mode 120000 index 0000000000..360a2acb05 --- /dev/null +++ b/Lang/ArkScript/Comments @@ -0,0 +1 @@ +../../Task/Comments/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Compound-data-type b/Lang/ArkScript/Compound-data-type new file mode 120000 index 0000000000..a901531424 --- /dev/null +++ b/Lang/ArkScript/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Concurrent-computing b/Lang/ArkScript/Concurrent-computing new file mode 120000 index 0000000000..13a2e9c874 --- /dev/null +++ b/Lang/ArkScript/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Conditional-structures b/Lang/ArkScript/Conditional-structures new file mode 120000 index 0000000000..10a922af53 --- /dev/null +++ b/Lang/ArkScript/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Conways-Game-of-Life b/Lang/ArkScript/Conways-Game-of-Life new file mode 120000 index 0000000000..2d495d7699 --- /dev/null +++ b/Lang/ArkScript/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Copy-a-string b/Lang/ArkScript/Copy-a-string new file mode 120000 index 0000000000..88194e46fb --- /dev/null +++ b/Lang/ArkScript/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Currying b/Lang/ArkScript/Currying new file mode 120000 index 0000000000..68a7b93b42 --- /dev/null +++ b/Lang/ArkScript/Currying @@ -0,0 +1 @@ +../../Task/Currying/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Delete-a-file b/Lang/ArkScript/Delete-a-file new file mode 120000 index 0000000000..d6dbc3ecd5 --- /dev/null +++ b/Lang/ArkScript/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Empty-directory b/Lang/ArkScript/Empty-directory new file mode 120000 index 0000000000..5ade8a3b8b --- /dev/null +++ b/Lang/ArkScript/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Empty-program b/Lang/ArkScript/Empty-program new file mode 120000 index 0000000000..d33db3e33c --- /dev/null +++ b/Lang/ArkScript/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Empty-string b/Lang/ArkScript/Empty-string new file mode 120000 index 0000000000..aa29f38546 --- /dev/null +++ b/Lang/ArkScript/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Enforced-immutability b/Lang/ArkScript/Enforced-immutability new file mode 120000 index 0000000000..c12069d86c --- /dev/null +++ b/Lang/ArkScript/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Even-or-odd b/Lang/ArkScript/Even-or-odd new file mode 120000 index 0000000000..7aee966d84 --- /dev/null +++ b/Lang/ArkScript/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Extend-your-language b/Lang/ArkScript/Extend-your-language new file mode 120000 index 0000000000..08fabf671d --- /dev/null +++ b/Lang/ArkScript/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Fibonacci-sequence b/Lang/ArkScript/Fibonacci-sequence new file mode 120000 index 0000000000..46f2bbba10 --- /dev/null +++ b/Lang/ArkScript/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/FizzBuzz b/Lang/ArkScript/FizzBuzz new file mode 120000 index 0000000000..2464c5dcce --- /dev/null +++ b/Lang/ArkScript/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Flatten-a-list b/Lang/ArkScript/Flatten-a-list new file mode 120000 index 0000000000..8540eceb42 --- /dev/null +++ b/Lang/ArkScript/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Function-definition b/Lang/ArkScript/Function-definition new file mode 120000 index 0000000000..e750f72eaf --- /dev/null +++ b/Lang/ArkScript/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Hello-world-Line-printer b/Lang/ArkScript/Hello-world-Line-printer new file mode 120000 index 0000000000..205cc44ef5 --- /dev/null +++ b/Lang/ArkScript/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Hello-world-Newline-omission b/Lang/ArkScript/Hello-world-Newline-omission new file mode 120000 index 0000000000..e70990b485 --- /dev/null +++ b/Lang/ArkScript/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Hello-world-Text b/Lang/ArkScript/Hello-world-Text new file mode 120000 index 0000000000..efe7845aa7 --- /dev/null +++ b/Lang/ArkScript/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Infinity b/Lang/ArkScript/Infinity new file mode 120000 index 0000000000..e2ef2bf985 --- /dev/null +++ b/Lang/ArkScript/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Integer-sequence b/Lang/ArkScript/Integer-sequence new file mode 120000 index 0000000000..386017d017 --- /dev/null +++ b/Lang/ArkScript/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Literals-Floating-point b/Lang/ArkScript/Literals-Floating-point new file mode 120000 index 0000000000..5bc172fabe --- /dev/null +++ b/Lang/ArkScript/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Literals-Integer b/Lang/ArkScript/Literals-Integer new file mode 120000 index 0000000000..b313b7f803 --- /dev/null +++ b/Lang/ArkScript/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Literals-String b/Lang/ArkScript/Literals-String new file mode 120000 index 0000000000..ec507deee1 --- /dev/null +++ b/Lang/ArkScript/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Logical-operations b/Lang/ArkScript/Logical-operations new file mode 120000 index 0000000000..aaefe48457 --- /dev/null +++ b/Lang/ArkScript/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Munchausen-numbers b/Lang/ArkScript/Munchausen-numbers new file mode 120000 index 0000000000..c351968c20 --- /dev/null +++ b/Lang/ArkScript/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/N-queens-problem b/Lang/ArkScript/N-queens-problem new file mode 120000 index 0000000000..e917f9e593 --- /dev/null +++ b/Lang/ArkScript/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Null-object b/Lang/ArkScript/Null-object new file mode 120000 index 0000000000..a698a2ff71 --- /dev/null +++ b/Lang/ArkScript/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Program-termination b/Lang/ArkScript/Program-termination new file mode 120000 index 0000000000..19d9d120f6 --- /dev/null +++ b/Lang/ArkScript/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Read-entire-file b/Lang/ArkScript/Read-entire-file new file mode 120000 index 0000000000..e3a1c22530 --- /dev/null +++ b/Lang/ArkScript/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Reverse-a-string b/Lang/ArkScript/Reverse-a-string new file mode 120000 index 0000000000..a3a2ea0c27 --- /dev/null +++ b/Lang/ArkScript/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Semordnilap b/Lang/ArkScript/Semordnilap new file mode 120000 index 0000000000..25df93d2d3 --- /dev/null +++ b/Lang/ArkScript/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Shell-one-liner b/Lang/ArkScript/Shell-one-liner new file mode 120000 index 0000000000..889b436427 --- /dev/null +++ b/Lang/ArkScript/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Short-circuit-evaluation b/Lang/ArkScript/Short-circuit-evaluation new file mode 120000 index 0000000000..dcd4ac26ee --- /dev/null +++ b/Lang/ArkScript/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Show-ASCII-table b/Lang/ArkScript/Show-ASCII-table new file mode 120000 index 0000000000..65d6365487 --- /dev/null +++ b/Lang/ArkScript/Show-ASCII-table @@ -0,0 +1 @@ +../../Task/Show-ASCII-table/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sleep b/Lang/ArkScript/Sleep new file mode 120000 index 0000000000..cd07cddf41 --- /dev/null +++ b/Lang/ArkScript/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sorting-algorithms-Quicksort b/Lang/ArkScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..003f3fb633 --- /dev/null +++ b/Lang/ArkScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-append b/Lang/ArkScript/String-append new file mode 120000 index 0000000000..ade5a20d23 --- /dev/null +++ b/Lang/ArkScript/String-append @@ -0,0 +1 @@ +../../Task/String-append/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-case b/Lang/ArkScript/String-case new file mode 120000 index 0000000000..25e27a4618 --- /dev/null +++ b/Lang/ArkScript/String-case @@ -0,0 +1 @@ +../../Task/String-case/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-concatenation b/Lang/ArkScript/String-concatenation new file mode 120000 index 0000000000..999b5605f7 --- /dev/null +++ b/Lang/ArkScript/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-interpolation-included- b/Lang/ArkScript/String-interpolation-included- new file mode 120000 index 0000000000..33fa86b906 --- /dev/null +++ b/Lang/ArkScript/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-length b/Lang/ArkScript/String-length new file mode 120000 index 0000000000..df129dcc11 --- /dev/null +++ b/Lang/ArkScript/String-length @@ -0,0 +1 @@ +../../Task/String-length/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-matching b/Lang/ArkScript/String-matching new file mode 120000 index 0000000000..7558bd042a --- /dev/null +++ b/Lang/ArkScript/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/String-prepend b/Lang/ArkScript/String-prepend new file mode 120000 index 0000000000..083b99bbf0 --- /dev/null +++ b/Lang/ArkScript/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-and-product-of-an-array b/Lang/ArkScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..4c22ecff5f --- /dev/null +++ b/Lang/ArkScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-digits-of-an-integer b/Lang/ArkScript/Sum-digits-of-an-integer new file mode 120000 index 0000000000..29e7afd56c --- /dev/null +++ b/Lang/ArkScript/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-of-a-series b/Lang/ArkScript/Sum-of-a-series new file mode 120000 index 0000000000..f009df3580 --- /dev/null +++ b/Lang/ArkScript/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Sum-of-squares b/Lang/ArkScript/Sum-of-squares new file mode 120000 index 0000000000..85176ac4bb --- /dev/null +++ b/Lang/ArkScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/User-input-Text b/Lang/ArkScript/User-input-Text new file mode 120000 index 0000000000..f0daf24108 --- /dev/null +++ b/Lang/ArkScript/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/ArkScript \ No newline at end of file diff --git a/Lang/ArkScript/Write-entire-file b/Lang/ArkScript/Write-entire-file new file mode 120000 index 0000000000..978c98fba7 --- /dev/null +++ b/Lang/ArkScript/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/ArkScript \ No newline at end of file diff --git a/Lang/AutoLISP/100-doors b/Lang/AutoLISP/100-doors new file mode 120000 index 0000000000..4d97a8a5d6 --- /dev/null +++ b/Lang/AutoLISP/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Babbage-problem b/Lang/AutoLISP/Babbage-problem new file mode 120000 index 0000000000..0ae3941c82 --- /dev/null +++ b/Lang/AutoLISP/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Balanced-brackets b/Lang/AutoLISP/Balanced-brackets new file mode 120000 index 0000000000..b752cfc1d6 --- /dev/null +++ b/Lang/AutoLISP/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Entropy b/Lang/AutoLISP/Entropy new file mode 120000 index 0000000000..bc1dec235f --- /dev/null +++ b/Lang/AutoLISP/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Entropy-Narcissist b/Lang/AutoLISP/Entropy-Narcissist new file mode 120000 index 0000000000..0a143c87ce --- /dev/null +++ b/Lang/AutoLISP/Entropy-Narcissist @@ -0,0 +1 @@ +../../Task/Entropy-Narcissist/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/Largest-proper-divisor-of-n b/Lang/AutoLISP/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..48c08fae1a --- /dev/null +++ b/Lang/AutoLISP/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/AutoLISP \ No newline at end of file diff --git a/Lang/AutoLISP/The-Twelve-Days-of-Christmas b/Lang/AutoLISP/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..3dd7563b0d --- /dev/null +++ b/Lang/AutoLISP/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/AutoLISP \ No newline at end of file diff --git a/Lang/BBC-BASIC/Arbitrary-precision-integers-included- b/Lang/BBC-BASIC/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..ca18adffdc --- /dev/null +++ b/Lang/BBC-BASIC/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Multi-dimensional-array b/Lang/BBC-BASIC/Multi-dimensional-array new file mode 120000 index 0000000000..4bc7c4a17c --- /dev/null +++ b/Lang/BBC-BASIC/Multi-dimensional-array @@ -0,0 +1 @@ +../../Task/Multi-dimensional-array/BBC-BASIC \ No newline at end of file diff --git a/Lang/Ballerina/Comments b/Lang/Ballerina/Comments new file mode 120000 index 0000000000..6b5d53ddee --- /dev/null +++ b/Lang/Ballerina/Comments @@ -0,0 +1 @@ +../../Task/Comments/Ballerina \ No newline at end of file diff --git a/Lang/Bc/Anti-primes b/Lang/Bc/Anti-primes new file mode 120000 index 0000000000..3d900bc4e9 --- /dev/null +++ b/Lang/Bc/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Bc \ No newline at end of file diff --git a/Lang/Bc/Arithmetic-derivative b/Lang/Bc/Arithmetic-derivative new file mode 120000 index 0000000000..3ff888839e --- /dev/null +++ b/Lang/Bc/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Bc \ No newline at end of file diff --git a/Lang/Bc/Department-numbers b/Lang/Bc/Department-numbers new file mode 120000 index 0000000000..0e2c9bd91f --- /dev/null +++ b/Lang/Bc/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Bc \ No newline at end of file diff --git a/Lang/Bc/Fairshare-between-two-and-more b/Lang/Bc/Fairshare-between-two-and-more new file mode 120000 index 0000000000..f5c1a3523e --- /dev/null +++ b/Lang/Bc/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/Bc \ No newline at end of file diff --git a/Lang/Bc/Variables b/Lang/Bc/Variables new file mode 120000 index 0000000000..03f47bea63 --- /dev/null +++ b/Lang/Bc/Variables @@ -0,0 +1 @@ +../../Task/Variables/Bc \ No newline at end of file diff --git a/Lang/Beeswax/00-LANG.txt b/Lang/Beeswax/00-LANG.txt index bea56d7b6b..c131bf7731 100644 --- a/Lang/Beeswax/00-LANG.txt +++ b/Lang/Beeswax/00-LANG.txt @@ -25,7 +25,7 @@ All data in the local and global stacks are unsigned 64-bit integers, output as == More information == -* [[eso:Beeswax|Esoteric languages wiki entry]] +* [http://esolangs.org/wiki/beeswax Esoteric languages wiki entry] == Reference implementation, example programs and complete language specification == diff --git a/Lang/C-sharp/Camel-case-and-snake-case b/Lang/C-sharp/Camel-case-and-snake-case new file mode 120000 index 0000000000..0b673ec8ed --- /dev/null +++ b/Lang/C-sharp/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Cistercian-numerals b/Lang/C-sharp/Cistercian-numerals new file mode 120000 index 0000000000..d482ff0533 --- /dev/null +++ b/Lang/C-sharp/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/M-bius-function b/Lang/C-sharp/M-bius-function new file mode 120000 index 0000000000..56f84fb14c --- /dev/null +++ b/Lang/C-sharp/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Vogels-approximation-method b/Lang/C-sharp/Vogels-approximation-method new file mode 120000 index 0000000000..bb638d067a --- /dev/null +++ b/Lang/C-sharp/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/C-sharp \ No newline at end of file diff --git a/Lang/CBASIC/Factorial b/Lang/CBASIC/Factorial new file mode 120000 index 0000000000..97dfd0b137 --- /dev/null +++ b/Lang/CBASIC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/CBASIC \ No newline at end of file diff --git a/Lang/CJam/00-LANG.txt b/Lang/CJam/00-LANG.txt new file mode 100644 index 0000000000..9d6f8331dc --- /dev/null +++ b/Lang/CJam/00-LANG.txt @@ -0,0 +1,8 @@ +{{language|site=https://sourceforge.net/p/cjam/wiki/Home/}} + +[https://sourceforge.net/projects/cjam/ sf repo] + +From the [https://sourceforge.net/p/cjam/wiki/Home/ wiki]: + +:In order to run a CJam program, [https://sourceforge.net/projects/cjam/files/ download] the latest jar file, e.g. cjam-0.6.5.jar, and run this command: +:
java -jar cjam-0.6.5.jar file.cjam
\ No newline at end of file diff --git a/Lang/CJam/00-META.yaml b/Lang/CJam/00-META.yaml new file mode 100644 index 0000000000..49b8d01361 --- /dev/null +++ b/Lang/CJam/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:CJam diff --git a/Lang/COBOL/Soloways-recurring-rainfall b/Lang/COBOL/Soloways-recurring-rainfall new file mode 120000 index 0000000000..883bf3b2e0 --- /dev/null +++ b/Lang/COBOL/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/COBOL \ No newline at end of file diff --git a/Lang/Calcscript/00-LANG.txt b/Lang/Calcscript/00-LANG.txt new file mode 100644 index 0000000000..d2db819bbe --- /dev/null +++ b/Lang/Calcscript/00-LANG.txt @@ -0,0 +1,10 @@ +{{language +|site=https://gitee.com/jfiewo/calc/ +}} +Calcscript is a small lisp-like language. +* It has 3 datatypes: Int, Same, and Invalid. +* The usual 4 arithmetic operations are supported. + +See [https://gitee.com/jfiewo/calc/ the respository] for details. +{{language programming paradigm|Logic Programming}} +{{language programming paradigm|Functional}} \ No newline at end of file diff --git a/Lang/Calcscript/00-META.yaml b/Lang/Calcscript/00-META.yaml new file mode 100644 index 0000000000..cee9fc468f --- /dev/null +++ b/Lang/Calcscript/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Calcscript diff --git a/Lang/Common-Lisp/Wieferich-primes b/Lang/Common-Lisp/Wieferich-primes new file mode 120000 index 0000000000..91ad6e3ba2 --- /dev/null +++ b/Lang/Common-Lisp/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/100-doors b/Lang/Component-Pascal/100-doors deleted file mode 120000 index 76b023254e..0000000000 --- a/Lang/Component-Pascal/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Component-Pascal \ No newline at end of file diff --git a/Lang/Computer-zero-Assembly/00-LANG.txt b/Lang/Computer-zero-Assembly/00-LANG.txt index e6ea975211..779b92356f 100644 --- a/Lang/Computer-zero-Assembly/00-LANG.txt +++ b/Lang/Computer-zero-Assembly/00-LANG.txt @@ -19,10 +19,10 @@ There are only 32 bytes of memory, and this includes your program code, leaving ==Self-Modifying Code== With such little RAM available, the biggest tool we have at our disposal for programming is self-modifying code. The CPU makes no distinction between data and instructions, and as such we can store values into memory before that memory is executed, in order to change what the computer will do. Here's an example: -LDA 4 +LDA 4 STA 2 ADD 3 STP -SUB 3 +SUB 3 The above snippet of code never actually ADDs anything, since that instruction gets overwritten by SUB 3. And what is SUB 3 subtracting? It's subtracting the value of STP, which can be encoded as any number between 0xE0 and 0xFF. Specifically, the encoding of SUB 3 (i.e. 0b10000011) is decreased by some value between 0xE0 and 0xFF, and since all arithmetic on this CPU is modulo 256 (as is standard for nearly all 8-bit CPUs), there will be roll-over across the FF-00 boundary. Without a hardware carry flag, however, it's difficult to track this overflow. \ No newline at end of file diff --git a/Lang/Convex/00-LANG.txt b/Lang/Convex/00-LANG.txt new file mode 100644 index 0000000000..6676f23dde --- /dev/null +++ b/Lang/Convex/00-LANG.txt @@ -0,0 +1,6 @@ +Convex is a stack-based golfing esolang based on Golfscript and CJam. + +{{language|site=https://github.com/ZekNikZ/Convex}} + +{{try|Convex|[https://tio.run/#convex Try Convex on tio.run].}} +{{language_programming_paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/Convex/00-META.yaml b/Lang/Convex/00-META.yaml new file mode 100644 index 0000000000..b10fffa83e --- /dev/null +++ b/Lang/Convex/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Convex diff --git a/Lang/Crystal/Department-numbers b/Lang/Crystal/Department-numbers new file mode 120000 index 0000000000..1e36b398e9 --- /dev/null +++ b/Lang/Crystal/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Parsing-RPN-calculator-algorithm b/Lang/Crystal/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..79e0e2ae7e --- /dev/null +++ b/Lang/Crystal/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Rot-13 b/Lang/Crystal/Rot-13 new file mode 120000 index 0000000000..430011bd06 --- /dev/null +++ b/Lang/Crystal/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Singly-linked-list-Element-definition b/Lang/Crystal/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..1c9a4e215c --- /dev/null +++ b/Lang/Crystal/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Singly-linked-list-Element-insertion b/Lang/Crystal/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..e0de17b549 --- /dev/null +++ b/Lang/Crystal/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Soloways-recurring-rainfall b/Lang/Crystal/Soloways-recurring-rainfall new file mode 120000 index 0000000000..017187c230 --- /dev/null +++ b/Lang/Crystal/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/Crystal \ No newline at end of file diff --git a/Lang/Crystal/String-interpolation-included- b/Lang/Crystal/String-interpolation-included- new file mode 120000 index 0000000000..05bff0aabd --- /dev/null +++ b/Lang/Crystal/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Crystal \ No newline at end of file diff --git a/Lang/Dart/AVL-tree b/Lang/Dart/AVL-tree new file mode 120000 index 0000000000..00bc5f9c2f --- /dev/null +++ b/Lang/Dart/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/Dart \ No newline at end of file diff --git a/Lang/Dart/Boyer-Moore-string-search b/Lang/Dart/Boyer-Moore-string-search new file mode 120000 index 0000000000..8b8a6a6060 --- /dev/null +++ b/Lang/Dart/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Dart \ No newline at end of file diff --git a/Lang/Dart/Break-OO-privacy b/Lang/Dart/Break-OO-privacy new file mode 120000 index 0000000000..e07e79a6ca --- /dev/null +++ b/Lang/Dart/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Dart \ No newline at end of file diff --git a/Lang/Dart/Continued-fraction b/Lang/Dart/Continued-fraction new file mode 120000 index 0000000000..ea5b665958 --- /dev/null +++ b/Lang/Dart/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Dart \ No newline at end of file diff --git a/Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..eb55960eb5 --- /dev/null +++ b/Lang/Dart/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Dart \ No newline at end of file diff --git a/Lang/Dart/Dijkstras-algorithm b/Lang/Dart/Dijkstras-algorithm new file mode 120000 index 0000000000..fc7b73a06b --- /dev/null +++ b/Lang/Dart/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Floyd-Warshall-algorithm b/Lang/Dart/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..34dc98809b --- /dev/null +++ b/Lang/Dart/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Parse-an-IP-Address b/Lang/Dart/Parse-an-IP-Address new file mode 120000 index 0000000000..bbe41020cb --- /dev/null +++ b/Lang/Dart/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Dart \ No newline at end of file diff --git a/Lang/Dart/Tonelli-Shanks-algorithm b/Lang/Dart/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..72acd046bd --- /dev/null +++ b/Lang/Dart/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Dart \ No newline at end of file diff --git a/Lang/Draco/Anti-primes b/Lang/Draco/Anti-primes new file mode 120000 index 0000000000..e9ba464537 --- /dev/null +++ b/Lang/Draco/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Draco \ No newline at end of file diff --git a/Lang/DuckDB/00-LANG.txt b/Lang/DuckDB/00-LANG.txt new file mode 100644 index 0000000000..2609130966 --- /dev/null +++ b/Lang/DuckDB/00-LANG.txt @@ -0,0 +1,4 @@ +[[DuckDB]] is an open-source, fast in-process analytical database management system based on a feature-rich SQL dialect complemented with deep integrations into client APIs. + +[[Category:Programming Languages]] +[[Category:SQL]] \ No newline at end of file diff --git a/Lang/DuckDB/00-META.yaml b/Lang/DuckDB/00-META.yaml new file mode 100644 index 0000000000..c9eafe7cf5 --- /dev/null +++ b/Lang/DuckDB/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:DuckDB diff --git a/Lang/DuckDB/100-doors b/Lang/DuckDB/100-doors new file mode 120000 index 0000000000..a0ee1f337e --- /dev/null +++ b/Lang/DuckDB/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/99-bottles-of-beer b/Lang/DuckDB/99-bottles-of-beer new file mode 120000 index 0000000000..c5f15cd273 --- /dev/null +++ b/Lang/DuckDB/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/A+B b/Lang/DuckDB/A+B new file mode 120000 index 0000000000..ae6220876f --- /dev/null +++ b/Lang/DuckDB/A+B @@ -0,0 +1 @@ +../../Task/A+B/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/ABC-problem b/Lang/DuckDB/ABC-problem new file mode 120000 index 0000000000..36e60dd0cd --- /dev/null +++ b/Lang/DuckDB/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Anagrams b/Lang/DuckDB/Anagrams new file mode 120000 index 0000000000..e80c01b2e3 --- /dev/null +++ b/Lang/DuckDB/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Anonymous-recursion b/Lang/DuckDB/Anonymous-recursion new file mode 120000 index 0000000000..e4448d2542 --- /dev/null +++ b/Lang/DuckDB/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-Complex b/Lang/DuckDB/Arithmetic-Complex new file mode 120000 index 0000000000..7e149e59dc --- /dev/null +++ b/Lang/DuckDB/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-Integer b/Lang/DuckDB/Arithmetic-Integer new file mode 120000 index 0000000000..5bc3696b71 --- /dev/null +++ b/Lang/DuckDB/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-geometric-mean b/Lang/DuckDB/Arithmetic-geometric-mean new file mode 120000 index 0000000000..2519d0a8f8 --- /dev/null +++ b/Lang/DuckDB/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arithmetic-numbers b/Lang/DuckDB/Arithmetic-numbers new file mode 120000 index 0000000000..a5e7e075b9 --- /dev/null +++ b/Lang/DuckDB/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Array-concatenation b/Lang/DuckDB/Array-concatenation new file mode 120000 index 0000000000..7ef5be0b5a --- /dev/null +++ b/Lang/DuckDB/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Array-length b/Lang/DuckDB/Array-length new file mode 120000 index 0000000000..ebd59786ea --- /dev/null +++ b/Lang/DuckDB/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Arrays b/Lang/DuckDB/Arrays new file mode 120000 index 0000000000..85190ece0f --- /dev/null +++ b/Lang/DuckDB/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Associative-array-Creation b/Lang/DuckDB/Associative-array-Creation new file mode 120000 index 0000000000..ea2505f34f --- /dev/null +++ b/Lang/DuckDB/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Associative-array-Iteration b/Lang/DuckDB/Associative-array-Iteration new file mode 120000 index 0000000000..c8269906e9 --- /dev/null +++ b/Lang/DuckDB/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Associative-array-Merging b/Lang/DuckDB/Associative-array-Merging new file mode 120000 index 0000000000..4e70d9ab01 --- /dev/null +++ b/Lang/DuckDB/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Arithmetic-mean b/Lang/DuckDB/Averages-Arithmetic-mean new file mode 120000 index 0000000000..7ef12ec4b6 --- /dev/null +++ b/Lang/DuckDB/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Mean-angle b/Lang/DuckDB/Averages-Mean-angle new file mode 120000 index 0000000000..5b1aa18e5e --- /dev/null +++ b/Lang/DuckDB/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Mean-time-of-day b/Lang/DuckDB/Averages-Mean-time-of-day new file mode 120000 index 0000000000..7971faf640 --- /dev/null +++ b/Lang/DuckDB/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Mode b/Lang/DuckDB/Averages-Mode new file mode 120000 index 0000000000..0ba388e74d --- /dev/null +++ b/Lang/DuckDB/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Averages-Pythagorean-means b/Lang/DuckDB/Averages-Pythagorean-means new file mode 120000 index 0000000000..1a5cb3068d --- /dev/null +++ b/Lang/DuckDB/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Babbage-problem b/Lang/DuckDB/Babbage-problem new file mode 120000 index 0000000000..7cee7b9a76 --- /dev/null +++ b/Lang/DuckDB/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Benfords-law b/Lang/DuckDB/Benfords-law new file mode 120000 index 0000000000..9302673cc0 --- /dev/null +++ b/Lang/DuckDB/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bin-given-limits b/Lang/DuckDB/Bin-given-limits new file mode 120000 index 0000000000..ba754d6a93 --- /dev/null +++ b/Lang/DuckDB/Bin-given-limits @@ -0,0 +1 @@ +../../Task/Bin-given-limits/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Binary-digits b/Lang/DuckDB/Binary-digits new file mode 120000 index 0000000000..c4e4b4a580 --- /dev/null +++ b/Lang/DuckDB/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bioinformatics-base-count b/Lang/DuckDB/Bioinformatics-base-count new file mode 120000 index 0000000000..6f72a9bb3a --- /dev/null +++ b/Lang/DuckDB/Bioinformatics-base-count @@ -0,0 +1 @@ +../../Task/Bioinformatics-base-count/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bitwise-IO b/Lang/DuckDB/Bitwise-IO new file mode 120000 index 0000000000..d00e607776 --- /dev/null +++ b/Lang/DuckDB/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Bitwise-operations b/Lang/DuckDB/Bitwise-operations new file mode 120000 index 0000000000..a0841908e6 --- /dev/null +++ b/Lang/DuckDB/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/CSV-data-manipulation b/Lang/DuckDB/CSV-data-manipulation new file mode 120000 index 0000000000..799ed97795 --- /dev/null +++ b/Lang/DuckDB/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Call-a-function b/Lang/DuckDB/Call-a-function new file mode 120000 index 0000000000..bf87fb6ba8 --- /dev/null +++ b/Lang/DuckDB/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Cartesian-product-of-two-or-more-lists b/Lang/DuckDB/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..f0873100b0 --- /dev/null +++ b/Lang/DuckDB/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Case-sensitivity-of-identifiers b/Lang/DuckDB/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..2a0900e2e4 --- /dev/null +++ b/Lang/DuckDB/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Catalan-numbers b/Lang/DuckDB/Catalan-numbers new file mode 120000 index 0000000000..5591f12e62 --- /dev/null +++ b/Lang/DuckDB/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Catalan-numbers-Pascals-triangle b/Lang/DuckDB/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..690dec4614 --- /dev/null +++ b/Lang/DuckDB/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Check-that-file-exists b/Lang/DuckDB/Check-that-file-exists new file mode 120000 index 0000000000..7a35121080 --- /dev/null +++ b/Lang/DuckDB/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Collections b/Lang/DuckDB/Collections new file mode 120000 index 0000000000..4bd2b4f60a --- /dev/null +++ b/Lang/DuckDB/Collections @@ -0,0 +1 @@ +../../Task/Collections/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Combinations b/Lang/DuckDB/Combinations new file mode 120000 index 0000000000..61cb39c1bb --- /dev/null +++ b/Lang/DuckDB/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Combinations-with-repetitions b/Lang/DuckDB/Combinations-with-repetitions new file mode 120000 index 0000000000..3781b1dd53 --- /dev/null +++ b/Lang/DuckDB/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Compare-a-list-of-strings b/Lang/DuckDB/Compare-a-list-of-strings new file mode 120000 index 0000000000..dcf4a9dc8d --- /dev/null +++ b/Lang/DuckDB/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Compare-length-of-two-strings b/Lang/DuckDB/Compare-length-of-two-strings new file mode 120000 index 0000000000..b29bfdb369 --- /dev/null +++ b/Lang/DuckDB/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Compound-data-type b/Lang/DuckDB/Compound-data-type new file mode 120000 index 0000000000..dc469b307b --- /dev/null +++ b/Lang/DuckDB/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Conditional-structures b/Lang/DuckDB/Conditional-structures new file mode 120000 index 0000000000..19bf4a5caa --- /dev/null +++ b/Lang/DuckDB/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Convert-seconds-to-compound-duration b/Lang/DuckDB/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..44055a0c42 --- /dev/null +++ b/Lang/DuckDB/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Copy-a-string b/Lang/DuckDB/Copy-a-string new file mode 120000 index 0000000000..d5f908f98d --- /dev/null +++ b/Lang/DuckDB/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Count-occurrences-of-a-substring b/Lang/DuckDB/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..82775de6e5 --- /dev/null +++ b/Lang/DuckDB/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Create-a-two-dimensional-array-at-runtime b/Lang/DuckDB/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..14657f9c21 --- /dev/null +++ b/Lang/DuckDB/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Cumulative-standard-deviation b/Lang/DuckDB/Cumulative-standard-deviation new file mode 120000 index 0000000000..f323d6c56e --- /dev/null +++ b/Lang/DuckDB/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Currency b/Lang/DuckDB/Currency new file mode 120000 index 0000000000..092e5fcb13 --- /dev/null +++ b/Lang/DuckDB/Currency @@ -0,0 +1 @@ +../../Task/Currency/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Day-of-the-week b/Lang/DuckDB/Day-of-the-week new file mode 120000 index 0000000000..467c28db17 --- /dev/null +++ b/Lang/DuckDB/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Define-a-primitive-data-type b/Lang/DuckDB/Define-a-primitive-data-type new file mode 120000 index 0000000000..f086397ed2 --- /dev/null +++ b/Lang/DuckDB/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Detect-division-by-zero b/Lang/DuckDB/Detect-division-by-zero new file mode 120000 index 0000000000..92508ad1dd --- /dev/null +++ b/Lang/DuckDB/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determinant-and-permanent b/Lang/DuckDB/Determinant-and-permanent new file mode 120000 index 0000000000..6bccec7e87 --- /dev/null +++ b/Lang/DuckDB/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters b/Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..3a9bd20a7a --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-has-all-unique-characters b/Lang/DuckDB/Determine-if-a-string-has-all-unique-characters new file mode 120000 index 0000000000..64885aacf1 --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-has-all-unique-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-unique-characters/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-is-collapsible b/Lang/DuckDB/Determine-if-a-string-is-collapsible new file mode 120000 index 0000000000..0bb2727b9c --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-is-collapsible @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-collapsible/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-is-numeric b/Lang/DuckDB/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..ead16cd478 --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-if-a-string-is-squeezable b/Lang/DuckDB/Determine-if-a-string-is-squeezable new file mode 120000 index 0000000000..57414557b7 --- /dev/null +++ b/Lang/DuckDB/Determine-if-a-string-is-squeezable @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-squeezable/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Determine-sentence-type b/Lang/DuckDB/Determine-sentence-type new file mode 120000 index 0000000000..50fb0aaf1b --- /dev/null +++ b/Lang/DuckDB/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Digital-root b/Lang/DuckDB/Digital-root new file mode 120000 index 0000000000..736b8ccc4f --- /dev/null +++ b/Lang/DuckDB/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Diversity-prediction-theorem b/Lang/DuckDB/Diversity-prediction-theorem new file mode 120000 index 0000000000..2c04d6784a --- /dev/null +++ b/Lang/DuckDB/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Documentation b/Lang/DuckDB/Documentation new file mode 120000 index 0000000000..f9f6aaf2ce --- /dev/null +++ b/Lang/DuckDB/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Dot-product b/Lang/DuckDB/Dot-product new file mode 120000 index 0000000000..b17f0214ea --- /dev/null +++ b/Lang/DuckDB/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Dynamic-variable-names b/Lang/DuckDB/Dynamic-variable-names new file mode 120000 index 0000000000..c534bbc61d --- /dev/null +++ b/Lang/DuckDB/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Element-wise-operations b/Lang/DuckDB/Element-wise-operations new file mode 120000 index 0000000000..7d7754f7f7 --- /dev/null +++ b/Lang/DuckDB/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Empty-string b/Lang/DuckDB/Empty-string new file mode 120000 index 0000000000..67b471da95 --- /dev/null +++ b/Lang/DuckDB/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Entropy b/Lang/DuckDB/Entropy new file mode 120000 index 0000000000..9c2bc0a9a7 --- /dev/null +++ b/Lang/DuckDB/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Enumerations b/Lang/DuckDB/Enumerations new file mode 120000 index 0000000000..0605dce25b --- /dev/null +++ b/Lang/DuckDB/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Equilibrium-index b/Lang/DuckDB/Equilibrium-index new file mode 120000 index 0000000000..40fbbe81bb --- /dev/null +++ b/Lang/DuckDB/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Euler-method b/Lang/DuckDB/Euler-method new file mode 120000 index 0000000000..61aa9557d0 --- /dev/null +++ b/Lang/DuckDB/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Eulers-constant-0.5772... b/Lang/DuckDB/Eulers-constant-0.5772... new file mode 120000 index 0000000000..c954937ec2 --- /dev/null +++ b/Lang/DuckDB/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Eulers-identity b/Lang/DuckDB/Eulers-identity new file mode 120000 index 0000000000..58919d8390 --- /dev/null +++ b/Lang/DuckDB/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Evaluate-binomial-coefficients b/Lang/DuckDB/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..69d838bb98 --- /dev/null +++ b/Lang/DuckDB/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Even-or-odd b/Lang/DuckDB/Even-or-odd new file mode 120000 index 0000000000..e428a57303 --- /dev/null +++ b/Lang/DuckDB/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Exponentiation-order b/Lang/DuckDB/Exponentiation-order new file mode 120000 index 0000000000..56438a22ee --- /dev/null +++ b/Lang/DuckDB/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Extreme-floating-point-values b/Lang/DuckDB/Extreme-floating-point-values new file mode 120000 index 0000000000..617a7e99de --- /dev/null +++ b/Lang/DuckDB/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Factorial b/Lang/DuckDB/Factorial new file mode 120000 index 0000000000..24543aba0b --- /dev/null +++ b/Lang/DuckDB/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Factors-of-an-integer b/Lang/DuckDB/Factors-of-an-integer new file mode 120000 index 0000000000..70e5ed8d56 --- /dev/null +++ b/Lang/DuckDB/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Fairshare-between-two-and-more b/Lang/DuckDB/Fairshare-between-two-and-more new file mode 120000 index 0000000000..0c62807925 --- /dev/null +++ b/Lang/DuckDB/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Feigenbaum-constant-calculation b/Lang/DuckDB/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..6f57f3044b --- /dev/null +++ b/Lang/DuckDB/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Fibonacci-sequence b/Lang/DuckDB/Fibonacci-sequence new file mode 120000 index 0000000000..0411dbf9f3 --- /dev/null +++ b/Lang/DuckDB/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/File-input-output b/Lang/DuckDB/File-input-output new file mode 120000 index 0000000000..0bb640b9cd --- /dev/null +++ b/Lang/DuckDB/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Filter b/Lang/DuckDB/Filter new file mode 120000 index 0000000000..bec860336f --- /dev/null +++ b/Lang/DuckDB/Filter @@ -0,0 +1 @@ +../../Task/Filter/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Find-limit-of-recursion b/Lang/DuckDB/Find-limit-of-recursion new file mode 120000 index 0000000000..e7eff55309 --- /dev/null +++ b/Lang/DuckDB/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Find-the-last-Sunday-of-each-month b/Lang/DuckDB/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..39172062a9 --- /dev/null +++ b/Lang/DuckDB/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Five-weekends b/Lang/DuckDB/Five-weekends new file mode 120000 index 0000000000..4d8ed3ebe3 --- /dev/null +++ b/Lang/DuckDB/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Fixed-length-records b/Lang/DuckDB/Fixed-length-records new file mode 120000 index 0000000000..0b8d72de87 --- /dev/null +++ b/Lang/DuckDB/Fixed-length-records @@ -0,0 +1 @@ +../../Task/Fixed-length-records/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Flatten-a-list b/Lang/DuckDB/Flatten-a-list new file mode 120000 index 0000000000..5bd1c5b0d8 --- /dev/null +++ b/Lang/DuckDB/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Formatted-numeric-output b/Lang/DuckDB/Formatted-numeric-output new file mode 120000 index 0000000000..789e647161 --- /dev/null +++ b/Lang/DuckDB/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Forward-difference b/Lang/DuckDB/Forward-difference new file mode 120000 index 0000000000..6a0d935f36 --- /dev/null +++ b/Lang/DuckDB/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Function-definition b/Lang/DuckDB/Function-definition new file mode 120000 index 0000000000..b39d093883 --- /dev/null +++ b/Lang/DuckDB/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Gamma-function b/Lang/DuckDB/Gamma-function new file mode 120000 index 0000000000..6fcec68436 --- /dev/null +++ b/Lang/DuckDB/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Gapful-numbers b/Lang/DuckDB/Gapful-numbers new file mode 120000 index 0000000000..875c3e4310 --- /dev/null +++ b/Lang/DuckDB/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Generate-lower-case-ASCII-alphabet b/Lang/DuckDB/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..51094f97da --- /dev/null +++ b/Lang/DuckDB/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Generic-swap b/Lang/DuckDB/Generic-swap new file mode 120000 index 0000000000..b384241f1f --- /dev/null +++ b/Lang/DuckDB/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Golden-ratio-Convergence b/Lang/DuckDB/Golden-ratio-Convergence new file mode 120000 index 0000000000..0ca8f2458f --- /dev/null +++ b/Lang/DuckDB/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Gotchas b/Lang/DuckDB/Gotchas new file mode 120000 index 0000000000..16cceb3ff0 --- /dev/null +++ b/Lang/DuckDB/Gotchas @@ -0,0 +1 @@ +../../Task/Gotchas/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Greatest-common-divisor b/Lang/DuckDB/Greatest-common-divisor new file mode 120000 index 0000000000..6fb062c771 --- /dev/null +++ b/Lang/DuckDB/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Greatest-element-of-a-list b/Lang/DuckDB/Greatest-element-of-a-list new file mode 120000 index 0000000000..5a2c7a66c9 --- /dev/null +++ b/Lang/DuckDB/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Greatest-subsequential-sum b/Lang/DuckDB/Greatest-subsequential-sum new file mode 120000 index 0000000000..dd3661e978 --- /dev/null +++ b/Lang/DuckDB/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/HTTP b/Lang/DuckDB/HTTP new file mode 120000 index 0000000000..f77a3116ff --- /dev/null +++ b/Lang/DuckDB/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/HTTPS b/Lang/DuckDB/HTTPS new file mode 120000 index 0000000000..694faecb0f --- /dev/null +++ b/Lang/DuckDB/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/HTTPS-Authenticated b/Lang/DuckDB/HTTPS-Authenticated new file mode 120000 index 0000000000..c1b123b3b8 --- /dev/null +++ b/Lang/DuckDB/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hailstone-sequence b/Lang/DuckDB/Hailstone-sequence new file mode 120000 index 0000000000..8cb9cd3c4d --- /dev/null +++ b/Lang/DuckDB/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Harmonic-series b/Lang/DuckDB/Harmonic-series new file mode 120000 index 0000000000..d5b23dfe32 --- /dev/null +++ b/Lang/DuckDB/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hash-from-two-arrays b/Lang/DuckDB/Hash-from-two-arrays new file mode 120000 index 0000000000..4fd3efc241 --- /dev/null +++ b/Lang/DuckDB/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hash-join b/Lang/DuckDB/Hash-join new file mode 120000 index 0000000000..d89e18cc75 --- /dev/null +++ b/Lang/DuckDB/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Haversine-formula b/Lang/DuckDB/Haversine-formula new file mode 120000 index 0000000000..102a047e33 --- /dev/null +++ b/Lang/DuckDB/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Hello-world-Text b/Lang/DuckDB/Hello-world-Text new file mode 120000 index 0000000000..1af484f405 --- /dev/null +++ b/Lang/DuckDB/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Here-document b/Lang/DuckDB/Here-document new file mode 120000 index 0000000000..f233028f5b --- /dev/null +++ b/Lang/DuckDB/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/ISBN13-check-digit b/Lang/DuckDB/ISBN13-check-digit new file mode 120000 index 0000000000..ad247e79cf --- /dev/null +++ b/Lang/DuckDB/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Identity-matrix b/Lang/DuckDB/Identity-matrix new file mode 120000 index 0000000000..d8402f7ae8 --- /dev/null +++ b/Lang/DuckDB/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols b/Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols new file mode 120000 index 0000000000..90e880a4b1 --- /dev/null +++ b/Lang/DuckDB/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters b/Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters new file mode 120000 index 0000000000..3722271469 --- /dev/null +++ b/Lang/DuckDB/Idiomatically-determine-all-the-lowercase-and-uppercase-letters @@ -0,0 +1 @@ +../../Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Increment-a-numerical-string b/Lang/DuckDB/Increment-a-numerical-string new file mode 120000 index 0000000000..a9f84c0e8c --- /dev/null +++ b/Lang/DuckDB/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Infinity b/Lang/DuckDB/Infinity new file mode 120000 index 0000000000..ed12f74690 --- /dev/null +++ b/Lang/DuckDB/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Integer-comparison b/Lang/DuckDB/Integer-comparison new file mode 120000 index 0000000000..c6cacfcd06 --- /dev/null +++ b/Lang/DuckDB/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Introspection b/Lang/DuckDB/Introspection new file mode 120000 index 0000000000..c3bb6d896d --- /dev/null +++ b/Lang/DuckDB/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Inverted-index b/Lang/DuckDB/Inverted-index new file mode 120000 index 0000000000..81053e0c15 --- /dev/null +++ b/Lang/DuckDB/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Inverted-syntax b/Lang/DuckDB/Inverted-syntax new file mode 120000 index 0000000000..cadc81e3b6 --- /dev/null +++ b/Lang/DuckDB/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/JSON b/Lang/DuckDB/JSON new file mode 120000 index 0000000000..e4757a4b09 --- /dev/null +++ b/Lang/DuckDB/JSON @@ -0,0 +1 @@ +../../Task/JSON/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Jaro-similarity b/Lang/DuckDB/Jaro-similarity new file mode 120000 index 0000000000..39c64b8488 --- /dev/null +++ b/Lang/DuckDB/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Knuth-shuffle b/Lang/DuckDB/Knuth-shuffle new file mode 120000 index 0000000000..7d43c57cbe --- /dev/null +++ b/Lang/DuckDB/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Largest-int-from-concatenated-ints b/Lang/DuckDB/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..8e73a50292 --- /dev/null +++ b/Lang/DuckDB/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Last-Friday-of-each-month b/Lang/DuckDB/Last-Friday-of-each-month new file mode 120000 index 0000000000..1236ebdc14 --- /dev/null +++ b/Lang/DuckDB/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Leap-year b/Lang/DuckDB/Leap-year new file mode 120000 index 0000000000..5816394f02 --- /dev/null +++ b/Lang/DuckDB/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Left-factorials b/Lang/DuckDB/Left-factorials new file mode 120000 index 0000000000..6877bf1f73 --- /dev/null +++ b/Lang/DuckDB/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Leonardo-numbers b/Lang/DuckDB/Leonardo-numbers new file mode 120000 index 0000000000..206ddcfce9 --- /dev/null +++ b/Lang/DuckDB/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Letter-frequency b/Lang/DuckDB/Letter-frequency new file mode 120000 index 0000000000..29228c3e0b --- /dev/null +++ b/Lang/DuckDB/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Levenshtein-distance b/Lang/DuckDB/Levenshtein-distance new file mode 120000 index 0000000000..d0954b60f2 --- /dev/null +++ b/Lang/DuckDB/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/List-comprehensions b/Lang/DuckDB/List-comprehensions new file mode 120000 index 0000000000..72558c43a1 --- /dev/null +++ b/Lang/DuckDB/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Literals-Integer b/Lang/DuckDB/Literals-Integer new file mode 120000 index 0000000000..39629959b4 --- /dev/null +++ b/Lang/DuckDB/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Logical-operations b/Lang/DuckDB/Logical-operations new file mode 120000 index 0000000000..14d59b0f70 --- /dev/null +++ b/Lang/DuckDB/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Longest-increasing-subsequence b/Lang/DuckDB/Longest-increasing-subsequence new file mode 120000 index 0000000000..35a8443499 --- /dev/null +++ b/Lang/DuckDB/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Break b/Lang/DuckDB/Loops-Break new file mode 120000 index 0000000000..40b7904e3f --- /dev/null +++ b/Lang/DuckDB/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Do-while b/Lang/DuckDB/Loops-Do-while new file mode 120000 index 0000000000..257f84d6ba --- /dev/null +++ b/Lang/DuckDB/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Downward-for b/Lang/DuckDB/Loops-Downward-for new file mode 120000 index 0000000000..5516907335 --- /dev/null +++ b/Lang/DuckDB/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-For b/Lang/DuckDB/Loops-For new file mode 120000 index 0000000000..56dde9a604 --- /dev/null +++ b/Lang/DuckDB/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-For-with-a-specified-step b/Lang/DuckDB/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..f7e2b536d7 --- /dev/null +++ b/Lang/DuckDB/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Increment-loop-index-within-loop-body b/Lang/DuckDB/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..d530992462 --- /dev/null +++ b/Lang/DuckDB/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-N-plus-one-half b/Lang/DuckDB/Loops-N-plus-one-half new file mode 120000 index 0000000000..f9812bda7e --- /dev/null +++ b/Lang/DuckDB/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-Nested b/Lang/DuckDB/Loops-Nested new file mode 120000 index 0000000000..8b4afa46b5 --- /dev/null +++ b/Lang/DuckDB/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-While b/Lang/DuckDB/Loops-While new file mode 120000 index 0000000000..60343480f3 --- /dev/null +++ b/Lang/DuckDB/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Loops-With-multiple-ranges b/Lang/DuckDB/Loops-With-multiple-ranges new file mode 120000 index 0000000000..540b734a24 --- /dev/null +++ b/Lang/DuckDB/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Luhn-test-of-credit-card-numbers b/Lang/DuckDB/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..397557411e --- /dev/null +++ b/Lang/DuckDB/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/MD5 b/Lang/DuckDB/MD5 new file mode 120000 index 0000000000..ab453e87da --- /dev/null +++ b/Lang/DuckDB/MD5 @@ -0,0 +1 @@ +../../Task/MD5/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Map-range b/Lang/DuckDB/Map-range new file mode 120000 index 0000000000..6cd697a04b --- /dev/null +++ b/Lang/DuckDB/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Matrix-multiplication b/Lang/DuckDB/Matrix-multiplication new file mode 120000 index 0000000000..2110896869 --- /dev/null +++ b/Lang/DuckDB/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Matrix-transposition b/Lang/DuckDB/Matrix-transposition new file mode 120000 index 0000000000..7e416217b2 --- /dev/null +++ b/Lang/DuckDB/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Merge-and-aggregate-datasets b/Lang/DuckDB/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..e9d467735b --- /dev/null +++ b/Lang/DuckDB/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Metallic-ratios b/Lang/DuckDB/Metallic-ratios new file mode 120000 index 0000000000..56fa981641 --- /dev/null +++ b/Lang/DuckDB/Metallic-ratios @@ -0,0 +1 @@ +../../Task/Metallic-ratios/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Middle-three-digits b/Lang/DuckDB/Middle-three-digits new file mode 120000 index 0000000000..9c32c60a1c --- /dev/null +++ b/Lang/DuckDB/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Monte-Carlo-methods b/Lang/DuckDB/Monte-Carlo-methods new file mode 120000 index 0000000000..f27be4f0e8 --- /dev/null +++ b/Lang/DuckDB/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Nested-function b/Lang/DuckDB/Nested-function new file mode 120000 index 0000000000..6ccb0c0029 --- /dev/null +++ b/Lang/DuckDB/Nested-function @@ -0,0 +1 @@ +../../Task/Nested-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Nth b/Lang/DuckDB/Nth new file mode 120000 index 0000000000..6d1fd0295b --- /dev/null +++ b/Lang/DuckDB/Nth @@ -0,0 +1 @@ +../../Task/Nth/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Nth-root b/Lang/DuckDB/Nth-root new file mode 120000 index 0000000000..bdfee4887c --- /dev/null +++ b/Lang/DuckDB/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/One-of-n-lines-in-a-file b/Lang/DuckDB/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..84adf8bb46 --- /dev/null +++ b/Lang/DuckDB/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Order-two-numerical-lists b/Lang/DuckDB/Order-two-numerical-lists new file mode 120000 index 0000000000..fcd259b6c0 --- /dev/null +++ b/Lang/DuckDB/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Ordered-words b/Lang/DuckDB/Ordered-words new file mode 120000 index 0000000000..57d12d9c27 --- /dev/null +++ b/Lang/DuckDB/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Palindrome-detection b/Lang/DuckDB/Palindrome-detection new file mode 120000 index 0000000000..a318cb02ae --- /dev/null +++ b/Lang/DuckDB/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Parameterized-SQL-statement b/Lang/DuckDB/Parameterized-SQL-statement new file mode 120000 index 0000000000..dded36b01b --- /dev/null +++ b/Lang/DuckDB/Parameterized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parameterized-SQL-statement/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Pascals-triangle b/Lang/DuckDB/Pascals-triangle new file mode 120000 index 0000000000..e38a99fc2d --- /dev/null +++ b/Lang/DuckDB/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Permutations b/Lang/DuckDB/Permutations new file mode 120000 index 0000000000..fa1198c6a6 --- /dev/null +++ b/Lang/DuckDB/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Permutations-Derangements b/Lang/DuckDB/Permutations-Derangements new file mode 120000 index 0000000000..b4140ee27e --- /dev/null +++ b/Lang/DuckDB/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Pick-random-element b/Lang/DuckDB/Pick-random-element new file mode 120000 index 0000000000..4eec54c36e --- /dev/null +++ b/Lang/DuckDB/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Primality-by-trial-division b/Lang/DuckDB/Primality-by-trial-division new file mode 120000 index 0000000000..8e9e10eb1a --- /dev/null +++ b/Lang/DuckDB/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Prime-decomposition b/Lang/DuckDB/Prime-decomposition new file mode 120000 index 0000000000..dbb3b57727 --- /dev/null +++ b/Lang/DuckDB/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Probabilistic-choice b/Lang/DuckDB/Probabilistic-choice new file mode 120000 index 0000000000..caa9cf57ce --- /dev/null +++ b/Lang/DuckDB/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Proper-divisors b/Lang/DuckDB/Proper-divisors new file mode 120000 index 0000000000..a8b8cf32ca --- /dev/null +++ b/Lang/DuckDB/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Pseudo-random-numbers-Middle-square-method b/Lang/DuckDB/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..3424580b60 --- /dev/null +++ b/Lang/DuckDB/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Random-numbers b/Lang/DuckDB/Random-numbers new file mode 120000 index 0000000000..4e7ae21251 --- /dev/null +++ b/Lang/DuckDB/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Range-expansion b/Lang/DuckDB/Range-expansion new file mode 120000 index 0000000000..73f7852f3e --- /dev/null +++ b/Lang/DuckDB/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Range-extraction b/Lang/DuckDB/Range-extraction new file mode 120000 index 0000000000..70b9fee7f2 --- /dev/null +++ b/Lang/DuckDB/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Read-a-file-line-by-line b/Lang/DuckDB/Read-a-file-line-by-line new file mode 120000 index 0000000000..5698cabe3f --- /dev/null +++ b/Lang/DuckDB/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Reflection-List-methods b/Lang/DuckDB/Reflection-List-methods new file mode 120000 index 0000000000..e87f71ad29 --- /dev/null +++ b/Lang/DuckDB/Reflection-List-methods @@ -0,0 +1 @@ +../../Task/Reflection-List-methods/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Reflection-List-properties b/Lang/DuckDB/Reflection-List-properties new file mode 120000 index 0000000000..61160f5035 --- /dev/null +++ b/Lang/DuckDB/Reflection-List-properties @@ -0,0 +1 @@ +../../Task/Reflection-List-properties/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Remove-duplicate-elements b/Lang/DuckDB/Remove-duplicate-elements new file mode 120000 index 0000000000..e38927d88b --- /dev/null +++ b/Lang/DuckDB/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Rep-string b/Lang/DuckDB/Rep-string new file mode 120000 index 0000000000..ce2543465d --- /dev/null +++ b/Lang/DuckDB/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Repeat-a-string b/Lang/DuckDB/Repeat-a-string new file mode 120000 index 0000000000..126fb8a5a7 --- /dev/null +++ b/Lang/DuckDB/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Return-multiple-values b/Lang/DuckDB/Return-multiple-values new file mode 120000 index 0000000000..44885d997f --- /dev/null +++ b/Lang/DuckDB/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Reverse-a-string b/Lang/DuckDB/Reverse-a-string new file mode 120000 index 0000000000..9c2fcefbbf --- /dev/null +++ b/Lang/DuckDB/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Roots-of-unity b/Lang/DuckDB/Roots-of-unity new file mode 120000 index 0000000000..fbae972a1d --- /dev/null +++ b/Lang/DuckDB/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Run-length-encoding b/Lang/DuckDB/Run-length-encoding new file mode 120000 index 0000000000..798b72b50c --- /dev/null +++ b/Lang/DuckDB/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Search-a-list-of-records b/Lang/DuckDB/Search-a-list-of-records new file mode 120000 index 0000000000..8875d845bf --- /dev/null +++ b/Lang/DuckDB/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Set b/Lang/DuckDB/Set new file mode 120000 index 0000000000..7e25aac634 --- /dev/null +++ b/Lang/DuckDB/Set @@ -0,0 +1 @@ +../../Task/Set/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Set-consolidation b/Lang/DuckDB/Set-consolidation new file mode 120000 index 0000000000..46e9513ebb --- /dev/null +++ b/Lang/DuckDB/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Show-the-epoch b/Lang/DuckDB/Show-the-epoch new file mode 120000 index 0000000000..6cd68764f9 --- /dev/null +++ b/Lang/DuckDB/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sieve-of-Eratosthenes b/Lang/DuckDB/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ee6aa1fbd3 --- /dev/null +++ b/Lang/DuckDB/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sort-an-array-of-composite-structures b/Lang/DuckDB/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..35612aed66 --- /dev/null +++ b/Lang/DuckDB/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sort-numbers-lexicographically b/Lang/DuckDB/Sort-numbers-lexicographically new file mode 120000 index 0000000000..390860d685 --- /dev/null +++ b/Lang/DuckDB/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Statistics-Basic b/Lang/DuckDB/Statistics-Basic new file mode 120000 index 0000000000..c3caa99be7 --- /dev/null +++ b/Lang/DuckDB/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-append b/Lang/DuckDB/String-append new file mode 120000 index 0000000000..cc8ce5011e --- /dev/null +++ b/Lang/DuckDB/String-append @@ -0,0 +1 @@ +../../Task/String-append/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-case b/Lang/DuckDB/String-case new file mode 120000 index 0000000000..ab3478758f --- /dev/null +++ b/Lang/DuckDB/String-case @@ -0,0 +1 @@ +../../Task/String-case/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-comparison b/Lang/DuckDB/String-comparison new file mode 120000 index 0000000000..b7a7339e14 --- /dev/null +++ b/Lang/DuckDB/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-interpolation-included- b/Lang/DuckDB/String-interpolation-included- new file mode 120000 index 0000000000..807f8abec4 --- /dev/null +++ b/Lang/DuckDB/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-length b/Lang/DuckDB/String-length new file mode 120000 index 0000000000..f49078b058 --- /dev/null +++ b/Lang/DuckDB/String-length @@ -0,0 +1 @@ +../../Task/String-length/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-matching b/Lang/DuckDB/String-matching new file mode 120000 index 0000000000..e3f7fa5300 --- /dev/null +++ b/Lang/DuckDB/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/String-prepend b/Lang/DuckDB/String-prepend new file mode 120000 index 0000000000..ea6f95610c --- /dev/null +++ b/Lang/DuckDB/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-a-set-of-characters-from-a-string b/Lang/DuckDB/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..77ce9f900d --- /dev/null +++ b/Lang/DuckDB/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-comments-from-a-string b/Lang/DuckDB/Strip-comments-from-a-string new file mode 120000 index 0000000000..f58b2c006d --- /dev/null +++ b/Lang/DuckDB/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string b/Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..e3de3aa487 --- /dev/null +++ b/Lang/DuckDB/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail b/Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..93405e661f --- /dev/null +++ b/Lang/DuckDB/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Substring b/Lang/DuckDB/Substring new file mode 120000 index 0000000000..fe9daf5b9c --- /dev/null +++ b/Lang/DuckDB/Substring @@ -0,0 +1 @@ +../../Task/Substring/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sudoku b/Lang/DuckDB/Sudoku new file mode 120000 index 0000000000..efc19532bb --- /dev/null +++ b/Lang/DuckDB/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-and-product-of-an-array b/Lang/DuckDB/Sum-and-product-of-an-array new file mode 120000 index 0000000000..9db07cfe55 --- /dev/null +++ b/Lang/DuckDB/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-digits-of-an-integer b/Lang/DuckDB/Sum-digits-of-an-integer new file mode 120000 index 0000000000..2b4e9e5805 --- /dev/null +++ b/Lang/DuckDB/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-multiples-of-3-and-5 b/Lang/DuckDB/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..06a19cefb7 --- /dev/null +++ b/Lang/DuckDB/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-of-a-series b/Lang/DuckDB/Sum-of-a-series new file mode 120000 index 0000000000..db0f6f79c5 --- /dev/null +++ b/Lang/DuckDB/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Sum-of-squares b/Lang/DuckDB/Sum-of-squares new file mode 120000 index 0000000000..fe3d9a8a52 --- /dev/null +++ b/Lang/DuckDB/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Symmetric-difference b/Lang/DuckDB/Symmetric-difference new file mode 120000 index 0000000000..f254423d5f --- /dev/null +++ b/Lang/DuckDB/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Table-creation-Postal-addresses b/Lang/DuckDB/Table-creation-Postal-addresses new file mode 120000 index 0000000000..174f03f886 --- /dev/null +++ b/Lang/DuckDB/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Test-integerness b/Lang/DuckDB/Test-integerness new file mode 120000 index 0000000000..0e9573c924 --- /dev/null +++ b/Lang/DuckDB/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Text-processing-2 b/Lang/DuckDB/Text-processing-2 new file mode 120000 index 0000000000..b3c883d2ec --- /dev/null +++ b/Lang/DuckDB/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Thue-Morse b/Lang/DuckDB/Thue-Morse new file mode 120000 index 0000000000..e14a41e488 --- /dev/null +++ b/Lang/DuckDB/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Time-a-function b/Lang/DuckDB/Time-a-function new file mode 120000 index 0000000000..d82a288f55 --- /dev/null +++ b/Lang/DuckDB/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Tokenize-a-string b/Lang/DuckDB/Tokenize-a-string new file mode 120000 index 0000000000..ee6d07a4b5 --- /dev/null +++ b/Lang/DuckDB/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Top-rank-per-group b/Lang/DuckDB/Top-rank-per-group new file mode 120000 index 0000000000..ada50a852c --- /dev/null +++ b/Lang/DuckDB/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Trigonometric-functions b/Lang/DuckDB/Trigonometric-functions new file mode 120000 index 0000000000..58530b66ee --- /dev/null +++ b/Lang/DuckDB/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/URL-decoding b/Lang/DuckDB/URL-decoding new file mode 120000 index 0000000000..c717460642 --- /dev/null +++ b/Lang/DuckDB/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/UTF-8-encode-and-decode b/Lang/DuckDB/UTF-8-encode-and-decode new file mode 120000 index 0000000000..792323a78c --- /dev/null +++ b/Lang/DuckDB/UTF-8-encode-and-decode @@ -0,0 +1 @@ +../../Task/UTF-8-encode-and-decode/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Unix-ls b/Lang/DuckDB/Unix-ls new file mode 120000 index 0000000000..85287a21f6 --- /dev/null +++ b/Lang/DuckDB/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Variable-size-Get b/Lang/DuckDB/Variable-size-Get new file mode 120000 index 0000000000..3cff7c631a --- /dev/null +++ b/Lang/DuckDB/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Variable-size-Set b/Lang/DuckDB/Variable-size-Set new file mode 120000 index 0000000000..ee4a003cfa --- /dev/null +++ b/Lang/DuckDB/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Vector-products b/Lang/DuckDB/Vector-products new file mode 120000 index 0000000000..3347aa5bba --- /dev/null +++ b/Lang/DuckDB/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Zero-to-the-zero-power b/Lang/DuckDB/Zero-to-the-zero-power new file mode 120000 index 0000000000..7c7bac0f0b --- /dev/null +++ b/Lang/DuckDB/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/DuckDB \ No newline at end of file diff --git a/Lang/DuckDB/Zig-zag-matrix b/Lang/DuckDB/Zig-zag-matrix new file mode 120000 index 0000000000..dee409f57f --- /dev/null +++ b/Lang/DuckDB/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/DuckDB \ No newline at end of file diff --git a/Lang/EasyLang/AKS-test-for-primes b/Lang/EasyLang/AKS-test-for-primes new file mode 120000 index 0000000000..fb3fd809a4 --- /dev/null +++ b/Lang/EasyLang/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Bitmap-Midpoint-circle-algorithm b/Lang/EasyLang/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..9b995802ee --- /dev/null +++ b/Lang/EasyLang/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Cholesky-decomposition b/Lang/EasyLang/Cholesky-decomposition new file mode 120000 index 0000000000..3d9b8e35d4 --- /dev/null +++ b/Lang/EasyLang/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Currency b/Lang/EasyLang/Currency new file mode 120000 index 0000000000..a42c848ea8 --- /dev/null +++ b/Lang/EasyLang/Currency @@ -0,0 +1 @@ +../../Task/Currency/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Death-Star b/Lang/EasyLang/Death-Star new file mode 120000 index 0000000000..71ec2dde3d --- /dev/null +++ b/Lang/EasyLang/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Distribution-of-0-digits-in-factorial-series b/Lang/EasyLang/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..10532131de --- /dev/null +++ b/Lang/EasyLang/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Draw-a-sphere b/Lang/EasyLang/Draw-a-sphere new file mode 120000 index 0000000000..4a92493ec5 --- /dev/null +++ b/Lang/EasyLang/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/EKG-sequence-convergence b/Lang/EasyLang/EKG-sequence-convergence new file mode 120000 index 0000000000..a5d661cade --- /dev/null +++ b/Lang/EasyLang/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Earliest-difference-between-prime-gaps b/Lang/EasyLang/Earliest-difference-between-prime-gaps new file mode 120000 index 0000000000..e8abb13bc1 --- /dev/null +++ b/Lang/EasyLang/Earliest-difference-between-prime-gaps @@ -0,0 +1 @@ +../../Task/Earliest-difference-between-prime-gaps/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Elementary-cellular-automaton-Infinite-length b/Lang/EasyLang/Elementary-cellular-automaton-Infinite-length new file mode 120000 index 0000000000..440a0e3168 --- /dev/null +++ b/Lang/EasyLang/Elementary-cellular-automaton-Infinite-length @@ -0,0 +1 @@ +../../Task/Elementary-cellular-automaton-Infinite-length/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes b/Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes new file mode 120000 index 0000000000..a64dc7d4f0 --- /dev/null +++ b/Lang/EasyLang/Erd-s-Selfridge-categorization-of-primes @@ -0,0 +1 @@ +../../Task/Erd-s-Selfridge-categorization-of-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Faulhabers-formula b/Lang/EasyLang/Faulhabers-formula new file mode 120000 index 0000000000..a0587d4c22 --- /dev/null +++ b/Lang/EasyLang/Faulhabers-formula @@ -0,0 +1 @@ +../../Task/Faulhabers-formula/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Faulhabers-triangle b/Lang/EasyLang/Faulhabers-triangle new file mode 120000 index 0000000000..0ced82832c --- /dev/null +++ b/Lang/EasyLang/Faulhabers-triangle @@ -0,0 +1 @@ +../../Task/Faulhabers-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fibonacci-word-fractal b/Lang/EasyLang/Fibonacci-word-fractal new file mode 120000 index 0000000000..d075c27d88 --- /dev/null +++ b/Lang/EasyLang/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Find-Chess960-starting-position-identifier b/Lang/EasyLang/Find-Chess960-starting-position-identifier new file mode 120000 index 0000000000..74db5136c0 --- /dev/null +++ b/Lang/EasyLang/Find-Chess960-starting-position-identifier @@ -0,0 +1 @@ +../../Task/Find-Chess960-starting-position-identifier/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Fraction-reduction b/Lang/EasyLang/Fraction-reduction new file mode 120000 index 0000000000..61af524020 --- /dev/null +++ b/Lang/EasyLang/Fraction-reduction @@ -0,0 +1 @@ +../../Task/Fraction-reduction/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/French-Republican-calendar b/Lang/EasyLang/French-Republican-calendar new file mode 120000 index 0000000000..63cacd897e --- /dev/null +++ b/Lang/EasyLang/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Function-prototype b/Lang/EasyLang/Function-prototype new file mode 120000 index 0000000000..d56b3a5da3 --- /dev/null +++ b/Lang/EasyLang/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hash-from-two-arrays b/Lang/EasyLang/Hash-from-two-arrays new file mode 120000 index 0000000000..0d148a2df3 --- /dev/null +++ b/Lang/EasyLang/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Honeycombs b/Lang/EasyLang/Honeycombs new file mode 120000 index 0000000000..5885102888 --- /dev/null +++ b/Lang/EasyLang/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hunt-the-Wumpus b/Lang/EasyLang/Hunt-the-Wumpus new file mode 120000 index 0000000000..8a2489577d --- /dev/null +++ b/Lang/EasyLang/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Jacobsthal-numbers b/Lang/EasyLang/Jacobsthal-numbers new file mode 120000 index 0000000000..9469db92c2 --- /dev/null +++ b/Lang/EasyLang/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pascals-triangle-Puzzle b/Lang/EasyLang/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..bb3b35817e --- /dev/null +++ b/Lang/EasyLang/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Straddling-checkerboard b/Lang/EasyLang/Straddling-checkerboard new file mode 120000 index 0000000000..df23fad6e0 --- /dev/null +++ b/Lang/EasyLang/Straddling-checkerboard @@ -0,0 +1 @@ +../../Task/Straddling-checkerboard/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Unicode-strings b/Lang/EasyLang/Unicode-strings new file mode 120000 index 0000000000..c52bd4da5c --- /dev/null +++ b/Lang/EasyLang/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/EasyLang \ No newline at end of file diff --git a/Lang/Eiffel/Loops-For b/Lang/Eiffel/Loops-For new file mode 120000 index 0000000000..30f93ee824 --- /dev/null +++ b/Lang/Eiffel/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Loops-Infinite b/Lang/Eiffel/Loops-Infinite new file mode 120000 index 0000000000..1016f5af23 --- /dev/null +++ b/Lang/Eiffel/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Eiffel \ No newline at end of file diff --git a/Lang/Elixir/Determinant-and-permanent b/Lang/Elixir/Determinant-and-permanent new file mode 120000 index 0000000000..91e99770a2 --- /dev/null +++ b/Lang/Elixir/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Elixir \ No newline at end of file diff --git a/Lang/Elixir/K-d-tree b/Lang/Elixir/K-d-tree new file mode 120000 index 0000000000..4a7008abc8 --- /dev/null +++ b/Lang/Elixir/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Parse-an-IP-Address b/Lang/Elixir/Parse-an-IP-Address new file mode 120000 index 0000000000..bad8e9a86e --- /dev/null +++ b/Lang/Elixir/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Elixir \ No newline at end of file diff --git a/Lang/Erlang/Determinant-and-permanent b/Lang/Erlang/Determinant-and-permanent new file mode 120000 index 0000000000..1dcba08234 --- /dev/null +++ b/Lang/Erlang/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Floyd-Warshall-algorithm b/Lang/Erlang/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..ac856e6ffa --- /dev/null +++ b/Lang/Erlang/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Excel/Jacobi-symbol b/Lang/Excel/Jacobi-symbol new file mode 120000 index 0000000000..85f7061c07 --- /dev/null +++ b/Lang/Excel/Jacobi-symbol @@ -0,0 +1 @@ +../../Task/Jacobi-symbol/Excel \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/00-LANG.txt b/Lang/Extended-Color-BASIC/00-LANG.txt new file mode 100644 index 0000000000..17efd36e93 --- /dev/null +++ b/Lang/Extended-Color-BASIC/00-LANG.txt @@ -0,0 +1,7 @@ +{{language|Extended Color BASIC}} + +Microsoft Extended Color BASIC the BASIC interpreter for the Tandy Color Computer and the Dragon Data Motorola 6809 processor based machines. + +==See Also== +* [[wp:Extended Color BASIC|Wikipedia: Extended Color BASIC]] +* [[Tasks not Implemented in Extended Color BASIC]] \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/00-META.yaml b/Lang/Extended-Color-BASIC/00-META.yaml new file mode 100644 index 0000000000..57e9e4028d --- /dev/null +++ b/Lang/Extended-Color-BASIC/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Extended_Color_BASIC diff --git a/Lang/Extended-Color-BASIC/Arrays b/Lang/Extended-Color-BASIC/Arrays new file mode 120000 index 0000000000..2ca9fdf8eb --- /dev/null +++ b/Lang/Extended-Color-BASIC/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Copy-a-string b/Lang/Extended-Color-BASIC/Copy-a-string new file mode 120000 index 0000000000..7a931a182a --- /dev/null +++ b/Lang/Extended-Color-BASIC/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Hello-world-Text b/Lang/Extended-Color-BASIC/Hello-world-Text new file mode 120000 index 0000000000..b5cfbf6b90 --- /dev/null +++ b/Lang/Extended-Color-BASIC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Loops-For b/Lang/Extended-Color-BASIC/Loops-For new file mode 120000 index 0000000000..8719420a7c --- /dev/null +++ b/Lang/Extended-Color-BASIC/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/Quine b/Lang/Extended-Color-BASIC/Quine new file mode 120000 index 0000000000..fb6135d264 --- /dev/null +++ b/Lang/Extended-Color-BASIC/Quine @@ -0,0 +1 @@ +../../Task/Quine/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/Extended-Color-BASIC/User-input-Text b/Lang/Extended-Color-BASIC/User-input-Text new file mode 120000 index 0000000000..545233f9b1 --- /dev/null +++ b/Lang/Extended-Color-BASIC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Extended-Color-BASIC \ No newline at end of file diff --git a/Lang/F-Sharp/Long-multiplication b/Lang/F-Sharp/Long-multiplication deleted file mode 120000 index a8ece45d37..0000000000 --- a/Lang/F-Sharp/Long-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Long-multiplication/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Multiplicative-order b/Lang/F-Sharp/Multiplicative-order new file mode 120000 index 0000000000..b2064cc3e0 --- /dev/null +++ b/Lang/F-Sharp/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/F-Sharp \ No newline at end of file diff --git a/Lang/Factor/Best-shuffle b/Lang/Factor/Best-shuffle new file mode 120000 index 0000000000..a10c8f5d14 --- /dev/null +++ b/Lang/Factor/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Factor \ No newline at end of file diff --git a/Lang/Fennel/00-LANG.txt b/Lang/Fennel/00-LANG.txt index d4313c004b..a3b3fb9075 100644 --- a/Lang/Fennel/00-LANG.txt +++ b/Lang/Fennel/00-LANG.txt @@ -10,4 +10,9 @@ According to Fennel website: Fennel is a programming language that brings togeth Anywhere you can run Lua code, you can run Fennel code. -See more examples at: [https://fennel-lang.org/ Fennel Website] \ No newline at end of file +See more examples at: [https://fennel-lang.org/ Fennel Website] + +A useful learning tool is antifennel at [https://git.sr.ht/~technomancy/antifennel https://git.sr.ht/~technomancy/antifennel] that can convert Lua programs to Fennel. +NB, some Lua features are not supported, particularly , and goto and any new features in Lua 5.5. + +As well as [[Lua]] 5.x VMs, Fennel programs can also be run with [[Pluto]], though warnings will probably be generated when Pluto parses the generated Lua. \ No newline at end of file diff --git a/Lang/Fennel/Abundant-deficient-and-perfect-number-classifications b/Lang/Fennel/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..fbb88cf56d --- /dev/null +++ b/Lang/Fennel/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Factorial b/Lang/Fennel/Factorial new file mode 120000 index 0000000000..ad3ab162af --- /dev/null +++ b/Lang/Fennel/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Factorial-primes b/Lang/Fennel/Factorial-primes new file mode 120000 index 0000000000..f7ae7a4fab --- /dev/null +++ b/Lang/Fennel/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Goldbachs-comet b/Lang/Fennel/Goldbachs-comet new file mode 120000 index 0000000000..38a9767c12 --- /dev/null +++ b/Lang/Fennel/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Horners-rule-for-polynomial-evaluation b/Lang/Fennel/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..74fe37f151 --- /dev/null +++ b/Lang/Fennel/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Jacobsthal-numbers b/Lang/Fennel/Jacobsthal-numbers new file mode 120000 index 0000000000..fcf69f6156 --- /dev/null +++ b/Lang/Fennel/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..e6054255ef --- /dev/null +++ b/Lang/Fennel/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Time-a-function b/Lang/Fennel/Time-a-function new file mode 120000 index 0000000000..e57c2d9bfb --- /dev/null +++ b/Lang/Fennel/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Fennel \ No newline at end of file diff --git a/Lang/Fennel/Yellowstone-sequence b/Lang/Fennel/Yellowstone-sequence new file mode 120000 index 0000000000..e160b50754 --- /dev/null +++ b/Lang/Fennel/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Fennel \ No newline at end of file diff --git a/Lang/Fortran/Associative-array-Merging b/Lang/Fortran/Associative-array-Merging new file mode 120000 index 0000000000..862cee9b2b --- /dev/null +++ b/Lang/Fortran/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Catalan-numbers-Pascals-triangle b/Lang/Fortran/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..e33b331d86 --- /dev/null +++ b/Lang/Fortran/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Chinese-zodiac b/Lang/Fortran/Chinese-zodiac new file mode 120000 index 0000000000..87ed14e5e7 --- /dev/null +++ b/Lang/Fortran/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Cyclotomic-polynomial b/Lang/Fortran/Cyclotomic-polynomial new file mode 120000 index 0000000000..0c2fd63e5e --- /dev/null +++ b/Lang/Fortran/Cyclotomic-polynomial @@ -0,0 +1 @@ +../../Task/Cyclotomic-polynomial/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Disarium-numbers b/Lang/Fortran/Disarium-numbers new file mode 120000 index 0000000000..4713bf931d --- /dev/null +++ b/Lang/Fortran/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Display-a-linear-combination b/Lang/Fortran/Display-a-linear-combination new file mode 120000 index 0000000000..4a9784f58d --- /dev/null +++ b/Lang/Fortran/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Fortran \ No newline at end of file diff --git a/Lang/Fortran/EKG-sequence-convergence b/Lang/Fortran/EKG-sequence-convergence new file mode 120000 index 0000000000..3ba5c0a162 --- /dev/null +++ b/Lang/Fortran/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Egyptian-division b/Lang/Fortran/Egyptian-division new file mode 120000 index 0000000000..bb7a134139 --- /dev/null +++ b/Lang/Fortran/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/Fortran \ No newline at end of file diff --git a/Lang/Fortran/French-Republican-calendar b/Lang/Fortran/French-Republican-calendar new file mode 120000 index 0000000000..765942db3d --- /dev/null +++ b/Lang/Fortran/French-Republican-calendar @@ -0,0 +1 @@ +../../Task/French-Republican-calendar/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Hofstadter-Figure-Figure-sequences b/Lang/Fortran/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..46497cf751 --- /dev/null +++ b/Lang/Fortran/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Humble-numbers b/Lang/Fortran/Humble-numbers new file mode 120000 index 0000000000..5aff41aed9 --- /dev/null +++ b/Lang/Fortran/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Jewels-and-stones b/Lang/Fortran/Jewels-and-stones new file mode 120000 index 0000000000..5375572de2 --- /dev/null +++ b/Lang/Fortran/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knapsack-problem-Bounded b/Lang/Fortran/Knapsack-problem-Bounded new file mode 120000 index 0000000000..9f9870702b --- /dev/null +++ b/Lang/Fortran/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knuths-power-tree b/Lang/Fortran/Knuths-power-tree new file mode 120000 index 0000000000..163172c51f --- /dev/null +++ b/Lang/Fortran/Knuths-power-tree @@ -0,0 +1 @@ +../../Task/Knuths-power-tree/Fortran \ No newline at end of file diff --git a/Lang/Fortran/McNuggets-problem b/Lang/Fortran/McNuggets-problem new file mode 120000 index 0000000000..6e4b8bc9dd --- /dev/null +++ b/Lang/Fortran/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Parse-an-IP-Address b/Lang/Fortran/Parse-an-IP-Address new file mode 120000 index 0000000000..33994c1cc1 --- /dev/null +++ b/Lang/Fortran/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Pascals-triangle-Puzzle b/Lang/Fortran/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..5cea267339 --- /dev/null +++ b/Lang/Fortran/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..a739c37e8e --- /dev/null +++ b/Lang/Fortran/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Totient-function b/Lang/Fortran/Totient-function new file mode 120000 index 0000000000..2559e22f69 --- /dev/null +++ b/Lang/Fortran/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Twos-complement b/Lang/Fortran/Twos-complement new file mode 120000 index 0000000000..b8e6672d37 --- /dev/null +++ b/Lang/Fortran/Twos-complement @@ -0,0 +1 @@ +../../Task/Twos-complement/Fortran \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Abstract-type b/Lang/Free-Pascal-Lazarus/Abstract-type new file mode 120000 index 0000000000..89db3c6334 --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Cistercian-numerals b/Lang/Free-Pascal-Lazarus/Cistercian-numerals new file mode 120000 index 0000000000..e09b44b1be --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Pancake-numbers b/Lang/Free-Pascal-Lazarus/Pancake-numbers new file mode 120000 index 0000000000..e82c81624b --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/FreeBASIC/Babylonian-spiral b/Lang/FreeBASIC/Babylonian-spiral new file mode 120000 index 0000000000..e141e5d456 --- /dev/null +++ b/Lang/FreeBASIC/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitcoin-public-point-to-address b/Lang/FreeBASIC/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..6ff9b61a5b --- /dev/null +++ b/Lang/FreeBASIC/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Catmull-Clark-subdivision-surface b/Lang/FreeBASIC/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..aa2f6e5ed9 --- /dev/null +++ b/Lang/FreeBASIC/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Color-quantization b/Lang/FreeBASIC/Color-quantization new file mode 120000 index 0000000000..ddc5eaabb7 --- /dev/null +++ b/Lang/FreeBASIC/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Dominoes b/Lang/FreeBASIC/Dominoes new file mode 120000 index 0000000000..46d9dcf5f4 --- /dev/null +++ b/Lang/FreeBASIC/Dominoes @@ -0,0 +1 @@ +../../Task/Dominoes/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Find-duplicate-files b/Lang/FreeBASIC/Find-duplicate-files new file mode 120000 index 0000000000..f2becdf037 --- /dev/null +++ b/Lang/FreeBASIC/Find-duplicate-files @@ -0,0 +1 @@ +../../Task/Find-duplicate-files/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..90493830d8 --- /dev/null +++ b/Lang/FreeBASIC/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet b/Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet new file mode 120000 index 0000000000..a3142e6912 --- /dev/null +++ b/Lang/FreeBASIC/Transliterate-English-text-using-the-Greek-alphabet @@ -0,0 +1 @@ +../../Task/Transliterate-English-text-using-the-Greek-alphabet/FreeBASIC \ No newline at end of file diff --git a/Lang/Frink/Disarium-numbers b/Lang/Frink/Disarium-numbers new file mode 120000 index 0000000000..30da6e89d2 --- /dev/null +++ b/Lang/Frink/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Frink \ No newline at end of file diff --git a/Lang/Frink/Happy-numbers b/Lang/Frink/Happy-numbers new file mode 120000 index 0000000000..e83b081fcc --- /dev/null +++ b/Lang/Frink/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Frink \ No newline at end of file diff --git a/Lang/FuncSug/00-LANG.txt b/Lang/FuncSug/00-LANG.txt new file mode 100644 index 0000000000..9239e3a1ef --- /dev/null +++ b/Lang/FuncSug/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|FuncSug}} \ No newline at end of file diff --git a/Lang/FuncSug/00-META.yaml b/Lang/FuncSug/00-META.yaml new file mode 100644 index 0000000000..0613d9bea7 --- /dev/null +++ b/Lang/FuncSug/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:FuncSug diff --git a/Lang/FuncSug/GUI-component-interaction b/Lang/FuncSug/GUI-component-interaction new file mode 120000 index 0000000000..744e9aac1b --- /dev/null +++ b/Lang/FuncSug/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/GUI-enabling-disabling-of-controls b/Lang/FuncSug/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..049595483a --- /dev/null +++ b/Lang/FuncSug/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Hello-world-Text b/Lang/FuncSug/Hello-world-Text new file mode 120000 index 0000000000..f188530df7 --- /dev/null +++ b/Lang/FuncSug/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Play-recorded-sounds b/Lang/FuncSug/Play-recorded-sounds new file mode 120000 index 0000000000..9418947577 --- /dev/null +++ b/Lang/FuncSug/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Simple-windowed-application b/Lang/FuncSug/Simple-windowed-application new file mode 120000 index 0000000000..8eec686bff --- /dev/null +++ b/Lang/FuncSug/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/Simulate-input-Mouse b/Lang/FuncSug/Simulate-input-Mouse new file mode 120000 index 0000000000..186d49bf08 --- /dev/null +++ b/Lang/FuncSug/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/FuncSug \ No newline at end of file diff --git a/Lang/FuncSug/User-input-Graphical b/Lang/FuncSug/User-input-Graphical new file mode 120000 index 0000000000..b685a2412e --- /dev/null +++ b/Lang/FuncSug/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/FuncSug \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-Complex b/Lang/FutureBasic/Arithmetic-Complex new file mode 120000 index 0000000000..eab72eafe1 --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Mean-time-of-day b/Lang/FutureBasic/Averages-Mean-time-of-day new file mode 120000 index 0000000000..0caef5a9a0 --- /dev/null +++ b/Lang/FutureBasic/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Boyer-Moore-string-search b/Lang/FutureBasic/Boyer-Moore-string-search new file mode 120000 index 0000000000..574c899ddd --- /dev/null +++ b/Lang/FutureBasic/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/CRC-32 b/Lang/FutureBasic/CRC-32 new file mode 120000 index 0000000000..8330772d04 --- /dev/null +++ b/Lang/FutureBasic/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Carmichael-3-strong-pseudoprimes b/Lang/FutureBasic/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..17664f9781 --- /dev/null +++ b/Lang/FutureBasic/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Deal-cards-for-FreeCell b/Lang/FutureBasic/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..b84bfb771c --- /dev/null +++ b/Lang/FutureBasic/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Demings-funnel b/Lang/FutureBasic/Demings-funnel new file mode 120000 index 0000000000..a0b916f84d --- /dev/null +++ b/Lang/FutureBasic/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Euler-method b/Lang/FutureBasic/Euler-method new file mode 120000 index 0000000000..89a7e85a03 --- /dev/null +++ b/Lang/FutureBasic/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Find-limit-of-recursion b/Lang/FutureBasic/Find-limit-of-recursion new file mode 120000 index 0000000000..cbc1e3a568 --- /dev/null +++ b/Lang/FutureBasic/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Five-weekends b/Lang/FutureBasic/Five-weekends new file mode 120000 index 0000000000..d11a92b953 --- /dev/null +++ b/Lang/FutureBasic/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Gamma-function b/Lang/FutureBasic/Gamma-function new file mode 120000 index 0000000000..fbf1cf8878 --- /dev/null +++ b/Lang/FutureBasic/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Gaussian-elimination b/Lang/FutureBasic/Gaussian-elimination new file mode 120000 index 0000000000..f8adccdee8 --- /dev/null +++ b/Lang/FutureBasic/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Guess-the-number-With-feedback-player- b/Lang/FutureBasic/Guess-the-number-With-feedback-player- new file mode 120000 index 0000000000..0ee5d26b61 --- /dev/null +++ b/Lang/FutureBasic/Guess-the-number-With-feedback-player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback-player-/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hamming-numbers b/Lang/FutureBasic/Hamming-numbers new file mode 120000 index 0000000000..69b0f1ea7d --- /dev/null +++ b/Lang/FutureBasic/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Last-letter-first-letter b/Lang/FutureBasic/Last-letter-first-letter new file mode 120000 index 0000000000..82ed39c3f0 --- /dev/null +++ b/Lang/FutureBasic/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Mayan-numerals b/Lang/FutureBasic/Mayan-numerals new file mode 120000 index 0000000000..cbc6204e00 --- /dev/null +++ b/Lang/FutureBasic/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Modular-inverse b/Lang/FutureBasic/Modular-inverse new file mode 120000 index 0000000000..89556b3bbe --- /dev/null +++ b/Lang/FutureBasic/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Monte-Carlo-methods b/Lang/FutureBasic/Monte-Carlo-methods new file mode 120000 index 0000000000..729102269f --- /dev/null +++ b/Lang/FutureBasic/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Mutex b/Lang/FutureBasic/Mutex new file mode 120000 index 0000000000..027130dc63 --- /dev/null +++ b/Lang/FutureBasic/Mutex @@ -0,0 +1 @@ +../../Task/Mutex/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Named-parameters b/Lang/FutureBasic/Named-parameters new file mode 120000 index 0000000000..77a79a818c --- /dev/null +++ b/Lang/FutureBasic/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Perfect-shuffle b/Lang/FutureBasic/Perfect-shuffle new file mode 120000 index 0000000000..6d2e5e3668 --- /dev/null +++ b/Lang/FutureBasic/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sierpinski-pentagon b/Lang/FutureBasic/Sierpinski-pentagon new file mode 120000 index 0000000000..1e105b6fb4 --- /dev/null +++ b/Lang/FutureBasic/Sierpinski-pentagon @@ -0,0 +1 @@ +../../Task/Sierpinski-pentagon/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sleep b/Lang/FutureBasic/Sleep new file mode 120000 index 0000000000..8ce099ff7d --- /dev/null +++ b/Lang/FutureBasic/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sorting-algorithms-Insertion-sort b/Lang/FutureBasic/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..d1f91f0286 --- /dev/null +++ b/Lang/FutureBasic/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sorting-algorithms-Sleep-sort b/Lang/FutureBasic/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..b94b39a51d --- /dev/null +++ b/Lang/FutureBasic/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Stack-traces b/Lang/FutureBasic/Stack-traces new file mode 120000 index 0000000000..589e50b2fa --- /dev/null +++ b/Lang/FutureBasic/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/String-length b/Lang/FutureBasic/String-length new file mode 120000 index 0000000000..6df040b0bc --- /dev/null +++ b/Lang/FutureBasic/String-length @@ -0,0 +1 @@ +../../Task/String-length/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-of-a-series b/Lang/FutureBasic/Sum-of-a-series new file mode 120000 index 0000000000..44687bc461 --- /dev/null +++ b/Lang/FutureBasic/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Sum-to-100 b/Lang/FutureBasic/Sum-to-100 new file mode 120000 index 0000000000..5cdb7cf4a8 --- /dev/null +++ b/Lang/FutureBasic/Sum-to-100 @@ -0,0 +1 @@ +../../Task/Sum-to-100/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Tau-function b/Lang/FutureBasic/Tau-function new file mode 120000 index 0000000000..4d9cc08c3d --- /dev/null +++ b/Lang/FutureBasic/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Tau-number b/Lang/FutureBasic/Tau-number new file mode 120000 index 0000000000..363cfbc636 --- /dev/null +++ b/Lang/FutureBasic/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Word-wrap b/Lang/FutureBasic/Word-wrap new file mode 120000 index 0000000000..d1cd565464 --- /dev/null +++ b/Lang/FutureBasic/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Yellowstone-sequence b/Lang/FutureBasic/Yellowstone-sequence new file mode 120000 index 0000000000..8a816499f6 --- /dev/null +++ b/Lang/FutureBasic/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Zebra-puzzle b/Lang/FutureBasic/Zebra-puzzle new file mode 120000 index 0000000000..68d36dbfcd --- /dev/null +++ b/Lang/FutureBasic/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/FutureBasic \ No newline at end of file diff --git a/Lang/GW-BASIC/Old-Russian-measure-of-length b/Lang/GW-BASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..6121a6a7b1 --- /dev/null +++ b/Lang/GW-BASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/GW-BASIC \ No newline at end of file diff --git a/Lang/Go/Distance-and-Bearing b/Lang/Go/Distance-and-Bearing new file mode 120000 index 0000000000..566b8d5b53 --- /dev/null +++ b/Lang/Go/Distance-and-Bearing @@ -0,0 +1 @@ +../../Task/Distance-and-Bearing/Go \ No newline at end of file diff --git a/Lang/Goboscript/00-LANG.txt b/Lang/Goboscript/00-LANG.txt new file mode 100644 index 0000000000..4cafdccd97 --- /dev/null +++ b/Lang/Goboscript/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|goboscript}} \ No newline at end of file diff --git a/Lang/Goboscript/00-META.yaml b/Lang/Goboscript/00-META.yaml new file mode 100644 index 0000000000..48464a36ad --- /dev/null +++ b/Lang/Goboscript/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Goboscript diff --git a/Lang/Haskell/00-LANG.txt b/Lang/Haskell/00-LANG.txt index fe49ebce44..9b79cdd879 100644 --- a/Lang/Haskell/00-LANG.txt +++ b/Lang/Haskell/00-LANG.txt @@ -20,5 +20,5 @@ Linspire GNU/[[Linux]] chose Haskell for system tools development. ==Citations== * [[wp:Haskell_%28programming_language%29|Wikipedia:Haskell (programming language)]] -==Todo== -[[Reports:Tasks_not_implemented_in_Haskell]] \ No newline at end of file +==Unimplemented Tasks== +* [[Tasks_not_implemented_in_Haskell|Haskell Unimplemented]] \ No newline at end of file diff --git a/Lang/Haxe/Abstract-type b/Lang/Haxe/Abstract-type new file mode 120000 index 0000000000..6ff9aba1f6 --- /dev/null +++ b/Lang/Haxe/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Apply-a-callback-to-an-array b/Lang/Haxe/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..6fdb21da75 --- /dev/null +++ b/Lang/Haxe/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Arrays b/Lang/Haxe/Arrays new file mode 120000 index 0000000000..bd303e4884 --- /dev/null +++ b/Lang/Haxe/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Associative-array-Creation b/Lang/Haxe/Associative-array-Creation new file mode 120000 index 0000000000..38347f6de6 --- /dev/null +++ b/Lang/Haxe/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Associative-array-Iteration b/Lang/Haxe/Associative-array-Iteration new file mode 120000 index 0000000000..aa7c7951b8 --- /dev/null +++ b/Lang/Haxe/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Binary-digits b/Lang/Haxe/Binary-digits new file mode 120000 index 0000000000..9bf8952c0d --- /dev/null +++ b/Lang/Haxe/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Boolean-values b/Lang/Haxe/Boolean-values new file mode 120000 index 0000000000..b5ef0e7d8b --- /dev/null +++ b/Lang/Haxe/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Call-an-object-method b/Lang/Haxe/Call-an-object-method new file mode 120000 index 0000000000..953d02b76c --- /dev/null +++ b/Lang/Haxe/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Character-codes b/Lang/Haxe/Character-codes new file mode 120000 index 0000000000..92ab060a1a --- /dev/null +++ b/Lang/Haxe/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Classes b/Lang/Haxe/Classes new file mode 120000 index 0000000000..5c922938d4 --- /dev/null +++ b/Lang/Haxe/Classes @@ -0,0 +1 @@ +../../Task/Classes/Haxe \ No newline at end of file diff --git a/Lang/Icon/00-LANG.txt b/Lang/Icon/00-LANG.txt index 6d6b15bfc2..16054a3927 100644 --- a/Lang/Icon/00-LANG.txt +++ b/Lang/Icon/00-LANG.txt @@ -39,5 +39,7 @@ Several extensions of Icon were developed to improve functionality. Many of the * [[Icon%2BUnicon/Intro|An introduction to Icon and Unicon for Rosetta Code]] * [[:Category:Icon/Omit|Unimplementable tasks]] * [[:Category:Icon_examples_needing_attention|Tasks requiring attention]] -* [[Reports:Tasks_not_implemented_in_Icon|Tasks not yet implemented]] -* [[:Category:Icon_Programming_Library|The Icon Programming Library]] \ No newline at end of file +* [[:Category:Icon_Programming_Library|The Icon Programming Library]] + +==Todo== +* [[Tasks not implemented in Icon]] \ No newline at end of file diff --git a/Lang/Icon/Exponentiation-order b/Lang/Icon/Exponentiation-order new file mode 120000 index 0000000000..c87e5174b5 --- /dev/null +++ b/Lang/Icon/Exponentiation-order @@ -0,0 +1 @@ +../../Task/Exponentiation-order/Icon \ No newline at end of file diff --git a/Lang/Icon/Jewels-and-stones b/Lang/Icon/Jewels-and-stones new file mode 120000 index 0000000000..5dee8d7cee --- /dev/null +++ b/Lang/Icon/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Icon \ No newline at end of file diff --git a/Lang/Icon/Loops-Wrong-ranges b/Lang/Icon/Loops-Wrong-ranges new file mode 120000 index 0000000000..0317af2079 --- /dev/null +++ b/Lang/Icon/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Icon \ No newline at end of file diff --git a/Lang/Icon/Search-a-list-of-records b/Lang/Icon/Search-a-list-of-records new file mode 120000 index 0000000000..b796eca599 --- /dev/null +++ b/Lang/Icon/Search-a-list-of-records @@ -0,0 +1 @@ +../../Task/Search-a-list-of-records/Icon \ No newline at end of file diff --git a/Lang/Icon/Sort-numbers-lexicographically b/Lang/Icon/Sort-numbers-lexicographically new file mode 120000 index 0000000000..7c99f7d928 --- /dev/null +++ b/Lang/Icon/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/Icon \ No newline at end of file diff --git a/Lang/Icon/Tokenize-a-string-with-escaping b/Lang/Icon/Tokenize-a-string-with-escaping new file mode 120000 index 0000000000..6a5856de9c --- /dev/null +++ b/Lang/Icon/Tokenize-a-string-with-escaping @@ -0,0 +1 @@ +../../Task/Tokenize-a-string-with-escaping/Icon \ No newline at end of file diff --git a/Lang/Icon/Tree-from-nesting-levels b/Lang/Icon/Tree-from-nesting-levels new file mode 120000 index 0000000000..670d6ecf62 --- /dev/null +++ b/Lang/Icon/Tree-from-nesting-levels @@ -0,0 +1 @@ +../../Task/Tree-from-nesting-levels/Icon \ No newline at end of file diff --git a/Lang/Idris/Comments b/Lang/Idris/Comments new file mode 120000 index 0000000000..ffaead275c --- /dev/null +++ b/Lang/Idris/Comments @@ -0,0 +1 @@ +../../Task/Comments/Idris \ No newline at end of file diff --git a/Lang/Insitux/00-LANG.txt b/Lang/Insitux/00-LANG.txt index ffe7dc9e9e..b852a0706e 100644 --- a/Lang/Insitux/00-LANG.txt +++ b/Lang/Insitux/00-LANG.txt @@ -3,10 +3,8 @@ |hopl=no |tags=insitux}} -Insitux (pronounced /ɪnˈsɪtjuːɪks/) is a dynamically-typed functional scripting language inspired by Clojure, originally commissioned in July 2021 for safe and extensible in-game scripting in a popular Roblox game. It has retained compatibility with Roblox by using two sets of "poly-fills" between [https://roblox-ts.com/ roblox-ts] and Node.js / web, meaning it can target Roblox, Node.js, and web with two slightly varying codebases. +Insitux (pronounced /ɪnˈsɪtjuːɪks/) is a dynamically-typed functional scripting language inspired by Clojure, originally commissioned in July 2021 for safe and extensible in-game scripting in a popular Roblox game. It now targets Node.js/Bun and client-side web. -Despite its origins it is a capable language, with development focusing on the language itself, its Node.js ecosystem, and to a lesser extent its web ecosystem. This primarily involves adding to the already 200+ built-in operations, which tend to cause existing Insitux programs to shrink in size over time. - -Insitux currently does not have a performance focus, and due to its syntactic flexibility, and its engine being transpiled into both JavaScript and [https://luau-lang.org/ Luau], it is difficult to optimise. Eventually Roblox support will be dropped / forked, pivoting mainline Insitux into AOT and JIT JavaScript transpilation. +Despite its origins it is a capable language, with development focusing on the language itself, its Node.js ecosystem, and to a lesser extent its web ecosystem. This primarily involves adding to the already 200+ built-in operations, which tend to cause existing Insitux programs to shrink in size over time; and improving language performance since dropping Roblox compatibility in 2024. {{language programming paradigm|functional}} \ No newline at end of file diff --git a/Lang/Janet/Comments b/Lang/Janet/Comments new file mode 120000 index 0000000000..b5297d4f4d --- /dev/null +++ b/Lang/Janet/Comments @@ -0,0 +1 @@ +../../Task/Comments/Janet \ No newline at end of file diff --git a/Lang/JavaScript/Aliquot-sequence-classifications b/Lang/JavaScript/Aliquot-sequence-classifications new file mode 120000 index 0000000000..5043f9bf29 --- /dev/null +++ b/Lang/JavaScript/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/B-zier-curves-Intersections b/Lang/JavaScript/B-zier-curves-Intersections new file mode 120000 index 0000000000..e14b622f07 --- /dev/null +++ b/Lang/JavaScript/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Balanced-ternary b/Lang/JavaScript/Balanced-ternary new file mode 120000 index 0000000000..c71298b653 --- /dev/null +++ b/Lang/JavaScript/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Bitcoin-public-point-to-address b/Lang/JavaScript/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..c3f037151b --- /dev/null +++ b/Lang/JavaScript/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Break-OO-privacy b/Lang/JavaScript/Break-OO-privacy new file mode 120000 index 0000000000..085d7969ff --- /dev/null +++ b/Lang/JavaScript/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Catmull-Clark-subdivision-surface b/Lang/JavaScript/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..40bf4ef0fc --- /dev/null +++ b/Lang/JavaScript/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Checkpoint-synchronization b/Lang/JavaScript/Checkpoint-synchronization new file mode 120000 index 0000000000..cf18aef6aa --- /dev/null +++ b/Lang/JavaScript/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Continued-fraction b/Lang/JavaScript/Continued-fraction new file mode 120000 index 0000000000..73bc586c57 --- /dev/null +++ b/Lang/JavaScript/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..95862446c9 --- /dev/null +++ b/Lang/JavaScript/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Deconvolution-1D b/Lang/JavaScript/Deconvolution-1D new file mode 120000 index 0000000000..719c208ec2 --- /dev/null +++ b/Lang/JavaScript/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Deconvolution-2D+ b/Lang/JavaScript/Deconvolution-2D+ new file mode 120000 index 0000000000..61f93d9cd6 --- /dev/null +++ b/Lang/JavaScript/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/MD5 b/Lang/JavaScript/MD5 new file mode 120000 index 0000000000..764b1e5dd2 --- /dev/null +++ b/Lang/JavaScript/MD5 @@ -0,0 +1 @@ +../../Task/MD5/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Meissel-Mertens-constant b/Lang/JavaScript/Meissel-Mertens-constant new file mode 120000 index 0000000000..8dd5c0b197 --- /dev/null +++ b/Lang/JavaScript/Meissel-Mertens-constant @@ -0,0 +1 @@ +../../Task/Meissel-Mertens-constant/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Parse-an-IP-Address b/Lang/JavaScript/Parse-an-IP-Address new file mode 120000 index 0000000000..5981d2ba9f --- /dev/null +++ b/Lang/JavaScript/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pascals-triangle-Puzzle b/Lang/JavaScript/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..2acf8cdb4d --- /dev/null +++ b/Lang/JavaScript/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sokoban b/Lang/JavaScript/Sokoban new file mode 120000 index 0000000000..3ab86467bd --- /dev/null +++ b/Lang/JavaScript/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Solve-a-Hopido-puzzle b/Lang/JavaScript/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..aea3983b76 --- /dev/null +++ b/Lang/JavaScript/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Superpermutation-minimisation b/Lang/JavaScript/Superpermutation-minimisation new file mode 120000 index 0000000000..a257c8e7e7 --- /dev/null +++ b/Lang/JavaScript/Superpermutation-minimisation @@ -0,0 +1 @@ +../../Task/Superpermutation-minimisation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Tarjan b/Lang/JavaScript/Tarjan new file mode 120000 index 0000000000..c299c7aebb --- /dev/null +++ b/Lang/JavaScript/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/JavaScript \ No newline at end of file diff --git a/Lang/Julia/OLE-automation b/Lang/Julia/OLE-automation new file mode 120000 index 0000000000..58b1722653 --- /dev/null +++ b/Lang/Julia/OLE-automation @@ -0,0 +1 @@ +../../Task/OLE-automation/Julia \ No newline at end of file diff --git a/Lang/Julia/Simulate-input-Keyboard b/Lang/Julia/Simulate-input-Keyboard new file mode 120000 index 0000000000..79cc3689e4 --- /dev/null +++ b/Lang/Julia/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Julia \ No newline at end of file diff --git a/Lang/Julia/Use-another-language-to-call-a-function b/Lang/Julia/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..c21a8c88ad --- /dev/null +++ b/Lang/Julia/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Julia \ No newline at end of file diff --git a/Lang/Kantalo/00-LANG.txt b/Lang/Kantalo/00-LANG.txt new file mode 100644 index 0000000000..453580c58d --- /dev/null +++ b/Lang/Kantalo/00-LANG.txt @@ -0,0 +1,40 @@ +{{language|Kantalo +|version=0.0.2 +|exec=interpreted +|strength=weak +|express=explicit +|checking=dynamic +|gc=yes +|tags=Kantalo,Language +|LCT=yes +|hopl=no +|safety=unsafe +|site=http://kantalo.kesug.com/}} + +=={{header|Kantalo}}== + +Kantalo is a non-object-oriented programming language, with the aim of making it easier to use. + +==Main commands== + +Here are some kantalo commands: + +
  • var.save - It is used to define variable.
  • +
  • var.import - Import variable outside functions.
  • +
  • var.edit - Edit an Existing Variable.
  • +
  • terminal.text - Returns a message passed within the argument.
  • +
  • terminal.input - Creates a text input.
  • +
  • if- Used to create conditions .
  • +
  • func - It is used to create functions.
  • +
  • execute - Performs functions.
  • + +
    +Simple Hello world with kantalo: +
    + +var.save nome = "Alice", +func saudacao > ( + terminal.text("Seja bem-vindo(a), -*nome*-!") +) +execute saudacao + \ No newline at end of file diff --git a/Lang/Kantalo/00-META.yaml b/Lang/Kantalo/00-META.yaml new file mode 100644 index 0000000000..c7d465ac08 --- /dev/null +++ b/Lang/Kantalo/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Kantalo diff --git a/Lang/Koka/00-LANG.txt b/Lang/Koka/00-LANG.txt index 96ea39de13..540a8fe180 100644 --- a/Lang/Koka/00-LANG.txt +++ b/Lang/Koka/00-LANG.txt @@ -3,7 +3,7 @@ Releases: - https://github.com/koka-lang/koka/releases -Latest: v2.4.2 +Latest: v3.1.3 '''Language Reference''' diff --git a/Lang/Koka/A+B b/Lang/Koka/A+B new file mode 120000 index 0000000000..5fcfbb2462 --- /dev/null +++ b/Lang/Koka/A+B @@ -0,0 +1 @@ +../../Task/A+B/Koka \ No newline at end of file diff --git a/Lang/Koka/Extend-your-language b/Lang/Koka/Extend-your-language new file mode 120000 index 0000000000..fa9d061610 --- /dev/null +++ b/Lang/Koka/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Koka \ No newline at end of file diff --git a/Lang/Koka/Jump-anywhere b/Lang/Koka/Jump-anywhere new file mode 120000 index 0000000000..39d5f8124d --- /dev/null +++ b/Lang/Koka/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Koka \ No newline at end of file diff --git a/Lang/Koka/Letter-frequency b/Lang/Koka/Letter-frequency new file mode 120000 index 0000000000..35e2486b2e --- /dev/null +++ b/Lang/Koka/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Koka \ No newline at end of file diff --git a/Lang/Koka/Loops-Break b/Lang/Koka/Loops-Break new file mode 120000 index 0000000000..21d8774db0 --- /dev/null +++ b/Lang/Koka/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Koka \ No newline at end of file diff --git a/Lang/Koka/Monads-Writer-monad b/Lang/Koka/Monads-Writer-monad new file mode 120000 index 0000000000..21e3e4c596 --- /dev/null +++ b/Lang/Koka/Monads-Writer-monad @@ -0,0 +1 @@ +../../Task/Monads-Writer-monad/Koka \ No newline at end of file diff --git a/Lang/Kotlin/Boyer-Moore-string-search b/Lang/Kotlin/Boyer-Moore-string-search new file mode 120000 index 0000000000..985c6560bd --- /dev/null +++ b/Lang/Kotlin/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Kotlin \ No newline at end of file diff --git a/Lang/Labyrinth/00-LANG.txt b/Lang/Labyrinth/00-LANG.txt new file mode 100644 index 0000000000..6b7624f3ac --- /dev/null +++ b/Lang/Labyrinth/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|site=https://github.com/m-ender/labyrinth}} \ No newline at end of file diff --git a/Lang/Labyrinth/00-META.yaml b/Lang/Labyrinth/00-META.yaml new file mode 100644 index 0000000000..2e09fd26db --- /dev/null +++ b/Lang/Labyrinth/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Labyrinth diff --git a/Lang/Liberty-BASIC/Hunt-the-Wumpus b/Lang/Liberty-BASIC/Hunt-the-Wumpus new file mode 120000 index 0000000000..4e2d0e150d --- /dev/null +++ b/Lang/Liberty-BASIC/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Minesweeper-game b/Lang/Liberty-BASIC/Minesweeper-game new file mode 120000 index 0000000000..19abfc9a07 --- /dev/null +++ b/Lang/Liberty-BASIC/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Snake b/Lang/Liberty-BASIC/Snake new file mode 120000 index 0000000000..20a60d8427 --- /dev/null +++ b/Lang/Liberty-BASIC/Snake @@ -0,0 +1 @@ +../../Task/Snake/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Logo/Sparkline-in-unicode b/Lang/Logo/Sparkline-in-unicode new file mode 120000 index 0000000000..d2b466f59a --- /dev/null +++ b/Lang/Logo/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Logo \ No newline at end of file diff --git a/Lang/Lua/100-doors b/Lang/Lua/100-doors deleted file mode 120000 index ce373fa8af..0000000000 --- a/Lang/Lua/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Lua \ No newline at end of file diff --git a/Lang/Lua/Jacobsthal-numbers b/Lang/Lua/Jacobsthal-numbers new file mode 120000 index 0000000000..ff787752c3 --- /dev/null +++ b/Lang/Lua/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Knapsack-problem-Bounded b/Lang/Lua/Knapsack-problem-Bounded new file mode 120000 index 0000000000..edddb60b00 --- /dev/null +++ b/Lang/Lua/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Lua \ No newline at end of file diff --git a/Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..63a3cd2cf9 --- /dev/null +++ b/Lang/Lua/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Lua \ No newline at end of file diff --git a/Lang/Lua/Use-another-language-to-call-a-function b/Lang/Lua/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..05e8f054e4 --- /dev/null +++ b/Lang/Lua/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Wagstaff-primes b/Lang/Lua/Wagstaff-primes new file mode 120000 index 0000000000..c8cec659a4 --- /dev/null +++ b/Lang/Lua/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Lua \ No newline at end of file diff --git a/Lang/Lua/Wieferich-primes b/Lang/Lua/Wieferich-primes new file mode 120000 index 0000000000..ac68d34377 --- /dev/null +++ b/Lang/Lua/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Lua \ No newline at end of file diff --git a/Lang/Mathematica/ASCII-art-diagram-converter b/Lang/Mathematica/ASCII-art-diagram-converter new file mode 120000 index 0000000000..1006da4cf6 --- /dev/null +++ b/Lang/Mathematica/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Camel-case-and-snake-case b/Lang/Mathematica/Camel-case-and-snake-case new file mode 120000 index 0000000000..6d73876132 --- /dev/null +++ b/Lang/Mathematica/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Erd-s-Nicolas-numbers b/Lang/Mathematica/Erd-s-Nicolas-numbers new file mode 120000 index 0000000000..d74b7bd3b7 --- /dev/null +++ b/Lang/Mathematica/Erd-s-Nicolas-numbers @@ -0,0 +1 @@ +../../Task/Erd-s-Nicolas-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Parse-an-IP-Address b/Lang/Mathematica/Parse-an-IP-Address new file mode 120000 index 0000000000..32b7086e88 --- /dev/null +++ b/Lang/Mathematica/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Tonelli-Shanks-algorithm b/Lang/Mathematica/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..747956daa4 --- /dev/null +++ b/Lang/Mathematica/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Vogels-approximation-method b/Lang/Mathematica/Vogels-approximation-method new file mode 120000 index 0000000000..2d01457a6e --- /dev/null +++ b/Lang/Mathematica/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/Array-length b/Lang/Maxima/Array-length new file mode 120000 index 0000000000..da5c3a4dcd --- /dev/null +++ b/Lang/Maxima/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Delete-a-file b/Lang/Maxima/Delete-a-file new file mode 120000 index 0000000000..9515074358 --- /dev/null +++ b/Lang/Maxima/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Hash-from-two-arrays b/Lang/Maxima/Hash-from-two-arrays new file mode 120000 index 0000000000..b59b47ec09 --- /dev/null +++ b/Lang/Maxima/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Real-constants-and-functions b/Lang/Maxima/Real-constants-and-functions new file mode 120000 index 0000000000..5465f4ddf0 --- /dev/null +++ b/Lang/Maxima/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Regular-expressions b/Lang/Maxima/Regular-expressions new file mode 120000 index 0000000000..ad80bc2114 --- /dev/null +++ b/Lang/Maxima/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Rename-a-file b/Lang/Maxima/Rename-a-file new file mode 120000 index 0000000000..875c72e05d --- /dev/null +++ b/Lang/Maxima/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Stooge-sort b/Lang/Maxima/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..df60525c6e --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Statistics-Basic b/Lang/Maxima/Statistics-Basic new file mode 120000 index 0000000000..3aa4fcf62d --- /dev/null +++ b/Lang/Maxima/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Substring-Top-and-tail b/Lang/Maxima/Substring-Top-and-tail new file mode 120000 index 0000000000..6897859615 --- /dev/null +++ b/Lang/Maxima/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Superellipse b/Lang/Maxima/Superellipse new file mode 120000 index 0000000000..4ecd2801c8 --- /dev/null +++ b/Lang/Maxima/Superellipse @@ -0,0 +1 @@ +../../Task/Superellipse/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Topic-variable b/Lang/Maxima/Topic-variable new file mode 120000 index 0000000000..e2a8f808d7 --- /dev/null +++ b/Lang/Maxima/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Towers-of-Hanoi b/Lang/Maxima/Towers-of-Hanoi new file mode 120000 index 0000000000..40963f2edb --- /dev/null +++ b/Lang/Maxima/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Maxima \ No newline at end of file diff --git a/Lang/Mn/00-LANG.txt b/Lang/Mn/00-LANG.txt new file mode 100644 index 0000000000..0fd90d2c3a --- /dev/null +++ b/Lang/Mn/00-LANG.txt @@ -0,0 +1,7 @@ +{{stub}}{{language|mn}} +mn is a minimalistic, concatenative, functional stack language. It is a very simple subset of [[min]]. + +==Links== +*[https://h3rald.com/mn/Mn_DeveloperGuide.htm Learn mn] + +{{Language programming paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/Mn/00-META.yaml b/Lang/Mn/00-META.yaml new file mode 100644 index 0000000000..f79f1602c3 --- /dev/null +++ b/Lang/Mn/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Mn diff --git a/Lang/Mn/Factorial b/Lang/Mn/Factorial new file mode 120000 index 0000000000..4c7a3c3b43 --- /dev/null +++ b/Lang/Mn/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Mn \ No newline at end of file diff --git a/Lang/Mn/Loops-While b/Lang/Mn/Loops-While new file mode 120000 index 0000000000..9e10aebd40 --- /dev/null +++ b/Lang/Mn/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Mn \ No newline at end of file diff --git a/Lang/Modula-2/AKS-test-for-primes b/Lang/Modula-2/AKS-test-for-primes new file mode 120000 index 0000000000..f86ed2a172 --- /dev/null +++ b/Lang/Modula-2/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Cistercian-numerals b/Lang/Modula-2/Cistercian-numerals new file mode 120000 index 0000000000..5da4e51fc7 --- /dev/null +++ b/Lang/Modula-2/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Modula-2 \ No newline at end of file diff --git a/Lang/Mojo/Hunt-the-Wumpus b/Lang/Mojo/Hunt-the-Wumpus new file mode 120000 index 0000000000..a79c86df71 --- /dev/null +++ b/Lang/Mojo/Hunt-the-Wumpus @@ -0,0 +1 @@ +../../Task/Hunt-the-Wumpus/Mojo \ No newline at end of file diff --git a/Lang/Nascom-BASIC/Old-Russian-measure-of-length b/Lang/Nascom-BASIC/Old-Russian-measure-of-length new file mode 120000 index 0000000000..73ef2957e7 --- /dev/null +++ b/Lang/Nascom-BASIC/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nom/00-LANG.txt b/Lang/Nom/00-LANG.txt new file mode 100644 index 0000000000..596e8bc965 --- /dev/null +++ b/Lang/Nom/00-LANG.txt @@ -0,0 +1,18 @@ +{{language|Nom}} + +Nom is an interpreted and also compiling (via the translation scripts) +language. Documentation for ''Nom'' can be found at [www.nomlang.org] along +with the downloadable [http://nomlang.org/download implementation]. +All the source code is also hosted in [https://sourceforge.net sourceforge] +at https://bumble.sf.net/books/pars/ + +Nom is based on the PEP (''Parsing Engine for Patterns'') virtual machine, +which is a text-based virtual machine. The PEP virtual machine is +documented at [http://nomlang.org/doc/machine/]. Nom was first ''conceived'' +around about 2005 but a good working implementation (the +[https://bumble.sf.net/books/pars/object/pep.c pep] interpreter) was not +achieved until approximately 2019. + +Nom is, I believe a new approach to recognising/parsing/transforming/transpiling/compiling context-free languages +since it uses the same standard Unix-style approach of a ''text-stream-filter'' +as with tools like ''sed'' or ''awk''. \ No newline at end of file diff --git a/Lang/Nom/00-META.yaml b/Lang/Nom/00-META.yaml new file mode 100644 index 0000000000..347649abaa --- /dev/null +++ b/Lang/Nom/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Nom diff --git a/Lang/Nom/Balanced-brackets b/Lang/Nom/Balanced-brackets new file mode 120000 index 0000000000..53c6847c48 --- /dev/null +++ b/Lang/Nom/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Nom \ No newline at end of file diff --git a/Lang/Nom/CSV-to-HTML-translation b/Lang/Nom/CSV-to-HTML-translation new file mode 120000 index 0000000000..efc535b187 --- /dev/null +++ b/Lang/Nom/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Nom \ No newline at end of file diff --git a/Lang/Nom/Determine-if-a-string-is-numeric b/Lang/Nom/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..dc0b5a67ea --- /dev/null +++ b/Lang/Nom/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Nom \ No newline at end of file diff --git a/Lang/Nom/Empty-string b/Lang/Nom/Empty-string new file mode 120000 index 0000000000..e51cf14c29 --- /dev/null +++ b/Lang/Nom/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Nom \ No newline at end of file diff --git a/Lang/Nom/Even-or-odd b/Lang/Nom/Even-or-odd new file mode 120000 index 0000000000..a93a39c338 --- /dev/null +++ b/Lang/Nom/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Nom \ No newline at end of file diff --git a/Lang/Nom/Hello-world-Text b/Lang/Nom/Hello-world-Text new file mode 120000 index 0000000000..6575bd7149 --- /dev/null +++ b/Lang/Nom/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Nom \ No newline at end of file diff --git a/Lang/Nom/Input-loop b/Lang/Nom/Input-loop new file mode 120000 index 0000000000..c687c9a3a9 --- /dev/null +++ b/Lang/Nom/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Nom \ No newline at end of file diff --git a/Lang/Nom/Odd-word-problem b/Lang/Nom/Odd-word-problem new file mode 120000 index 0000000000..43979a4bb7 --- /dev/null +++ b/Lang/Nom/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Nom \ No newline at end of file diff --git a/Lang/Nom/Reverse-a-string b/Lang/Nom/Reverse-a-string new file mode 120000 index 0000000000..38692d6625 --- /dev/null +++ b/Lang/Nom/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Nom \ No newline at end of file diff --git a/Lang/OCaml/Parse-an-IP-Address b/Lang/OCaml/Parse-an-IP-Address new file mode 120000 index 0000000000..f01fc56f01 --- /dev/null +++ b/Lang/OCaml/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Sorting-algorithms-Sleep-sort b/Lang/OCaml/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..1cc75210f7 --- /dev/null +++ b/Lang/OCaml/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/OCaml \ No newline at end of file diff --git a/Lang/Objeck/Catalan-numbers-Pascals-triangle b/Lang/Objeck/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..bc3c684d61 --- /dev/null +++ b/Lang/Objeck/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Disarium-numbers b/Lang/Objeck/Disarium-numbers new file mode 120000 index 0000000000..bc58c40d5c --- /dev/null +++ b/Lang/Objeck/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Objeck \ No newline at end of file diff --git a/Lang/Objeck/HTTPS-Client-authenticated b/Lang/Objeck/HTTPS-Client-authenticated new file mode 120000 index 0000000000..6f56878ef9 --- /dev/null +++ b/Lang/Objeck/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Magic-squares-of-doubly-even-order b/Lang/Objeck/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..526cd66745 --- /dev/null +++ b/Lang/Objeck/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Matrix-multiplication b/Lang/Objeck/Matrix-multiplication new file mode 120000 index 0000000000..e2801343eb --- /dev/null +++ b/Lang/Objeck/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Objeck \ No newline at end of file diff --git a/Lang/Object-Pascal-Implementations/00-LANG.txt b/Lang/Object-Pascal-Implementations/00-LANG.txt new file mode 100644 index 0000000000..74167ef7a7 --- /dev/null +++ b/Lang/Object-Pascal-Implementations/00-LANG.txt @@ -0,0 +1,3 @@ +{{language|Object Pascal}} +{{implementation cat|Object Pascal}} +{{implementation|Pascal}} \ No newline at end of file diff --git a/Lang/Object-Pascal-Implementations/00-META.yaml b/Lang/Object-Pascal-Implementations/00-META.yaml new file mode 100644 index 0000000000..34f0628a46 --- /dev/null +++ b/Lang/Object-Pascal-Implementations/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Object_Pascal_Implementations diff --git a/Lang/Odin/Comments b/Lang/Odin/Comments new file mode 120000 index 0000000000..69505856e6 --- /dev/null +++ b/Lang/Odin/Comments @@ -0,0 +1 @@ +../../Task/Comments/Odin \ No newline at end of file diff --git a/Lang/OoRexx/Prime-decomposition b/Lang/OoRexx/Prime-decomposition new file mode 120000 index 0000000000..f16b4825fb --- /dev/null +++ b/Lang/OoRexx/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/OoRexx \ No newline at end of file diff --git a/Lang/OxygenBasic/Josephus-problem b/Lang/OxygenBasic/Josephus-problem new file mode 120000 index 0000000000..26c79416e6 --- /dev/null +++ b/Lang/OxygenBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/OxygenBasic \ No newline at end of file diff --git a/Lang/PARI-GP/Pell-numbers b/Lang/PARI-GP/Pell-numbers new file mode 120000 index 0000000000..6dc31a644a --- /dev/null +++ b/Lang/PARI-GP/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Tonelli-Shanks-algorithm b/Lang/PARI-GP/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..de551c5a5b --- /dev/null +++ b/Lang/PARI-GP/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/AKS-test-for-primes b/Lang/PHP/AKS-test-for-primes new file mode 120000 index 0000000000..e35d324f89 --- /dev/null +++ b/Lang/PHP/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PHP \ No newline at end of file diff --git a/Lang/PL-M/100-doors b/Lang/PL-M/100-doors deleted file mode 120000 index fb7e956c0e..0000000000 --- a/Lang/PL-M/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/PL-M \ No newline at end of file diff --git a/Lang/Pascal-P/00-LANG.txt b/Lang/Pascal-P/00-LANG.txt new file mode 100644 index 0000000000..ce87f461ab --- /dev/null +++ b/Lang/Pascal-P/00-LANG.txt @@ -0,0 +1,23 @@ +{{language|Pascal-P +|exec=bytecode +|strength=strong +|safety=safe +|express=explicit +|checking=static +|parampass=both +|gc=no +|LCT=yes +}}{{language programming paradigm|Procedural}} + +{{implementation|Pascal}}{{Compiler}} + +'''Pascal-P''' is a renowned [[:Category:Pascal|Pascal]] compiler designed to generate [[bytecode]], known as ''p-code'', and interpret the resulting code. The compilers and interpreters of Pascal-P are developed using the Pascal programming language. + +Originally developed in Zurich in 1973, the earliest iteration of Pascal-P, known as Pascal-P1, laid the foundation for subsequent versions, including P2, P3, and P4. While versions P1 and P3 are no longer accessible, P2 is still readily available and has notably served as the base for the UCSD system. Furthermore, there exist derivative versions, such as P5 and P6, which have evolved from the core Pascal-P compiler. + +Notably, Pascal-P is heralded for its portability, as it is capable of generating code suitable for a hypothetical stack computer system. This feature enhances its versatility and applicability across various platforms and environments. Additionally, Pascal-P has made significant contributions to the realm of education, often being utilized as an educational tool to impart knowledge and foster learning in the field of computer programming. + +== External links == +* [http://pascal.hansotten.com/niklaus-wirth/px-compilers Px compilers] on [http://pascal.hansotten.com/ Pascal for small machines] +* [https://sourceforge.net/projects/pascalp4/ Scott Moore's version of P4] The package includes crucial components essential for program execution on the MS-DOS platform - the compiler and the p-code interpreter executables. +* [https://www.moorecad.com/standardpascal/p4.html The P4 compiler] on [https://www.moorecad.com/ Scott Moore's page] \ No newline at end of file diff --git a/Lang/Pascal-P/00-META.yaml b/Lang/Pascal-P/00-META.yaml new file mode 100644 index 0000000000..5af4159a1f --- /dev/null +++ b/Lang/Pascal-P/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Pascal-P diff --git a/Lang/Pascal-P/Cistercian-numerals b/Lang/Pascal-P/Cistercian-numerals new file mode 120000 index 0000000000..3169bb4737 --- /dev/null +++ b/Lang/Pascal-P/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/FizzBuzz b/Lang/Pascal-P/FizzBuzz new file mode 120000 index 0000000000..8d0c857c1d --- /dev/null +++ b/Lang/Pascal-P/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Leonardo-numbers b/Lang/Pascal-P/Leonardo-numbers new file mode 120000 index 0000000000..33730eb927 --- /dev/null +++ b/Lang/Pascal-P/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Levenshtein-distance b/Lang/Pascal-P/Levenshtein-distance new file mode 120000 index 0000000000..369c4fda51 --- /dev/null +++ b/Lang/Pascal-P/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/M-bius-function b/Lang/Pascal-P/M-bius-function new file mode 120000 index 0000000000..5ac8d7d007 --- /dev/null +++ b/Lang/Pascal-P/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Magic-constant b/Lang/Pascal-P/Magic-constant new file mode 120000 index 0000000000..d71a46b136 --- /dev/null +++ b/Lang/Pascal-P/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Map-range b/Lang/Pascal-P/Map-range new file mode 120000 index 0000000000..ecc77d75f6 --- /dev/null +++ b/Lang/Pascal-P/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Pascal-P \ No newline at end of file diff --git a/Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification b/Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..41e4d1e47d --- /dev/null +++ b/Lang/Pascal-P/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/Pascal-P \ No newline at end of file diff --git a/Lang/PascalABC.NET/15-puzzle-solver b/Lang/PascalABC.NET/15-puzzle-solver new file mode 120000 index 0000000000..73063f2237 --- /dev/null +++ b/Lang/PascalABC.NET/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Abbreviations-easy b/Lang/PascalABC.NET/Abbreviations-easy new file mode 120000 index 0000000000..ea782fa0b0 --- /dev/null +++ b/Lang/PascalABC.NET/Abbreviations-easy @@ -0,0 +1 @@ +../../Task/Abbreviations-easy/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Abbreviations-simple b/Lang/PascalABC.NET/Abbreviations-simple new file mode 120000 index 0000000000..abc650feac --- /dev/null +++ b/Lang/PascalABC.NET/Abbreviations-simple @@ -0,0 +1 @@ +../../Task/Abbreviations-simple/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Arithmetic-evaluation b/Lang/PascalABC.NET/Arithmetic-evaluation new file mode 120000 index 0000000000..816270d1cc --- /dev/null +++ b/Lang/PascalABC.NET/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Bioinformatics-base-count b/Lang/PascalABC.NET/Bioinformatics-base-count new file mode 120000 index 0000000000..8f0159ab8b --- /dev/null +++ b/Lang/PascalABC.NET/Bioinformatics-base-count @@ -0,0 +1 @@ +../../Task/Bioinformatics-base-count/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Case-sensitivity-of-identifiers b/Lang/PascalABC.NET/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..b0fc4ead7c --- /dev/null +++ b/Lang/PascalABC.NET/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Combinations-with-repetitions b/Lang/PascalABC.NET/Combinations-with-repetitions new file mode 120000 index 0000000000..f75050c914 --- /dev/null +++ b/Lang/PascalABC.NET/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/PascalABC.NET \ No newline at end of file diff --git a/Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..bc2932bdb0 --- /dev/null +++ b/Lang/Perl/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Perl \ No newline at end of file diff --git a/Lang/Pico-8/00-LANG.txt b/Lang/Pico-8/00-LANG.txt new file mode 100644 index 0000000000..017ddd4004 --- /dev/null +++ b/Lang/Pico-8/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|Pico-8}} \ No newline at end of file diff --git a/Lang/Pico-8/00-META.yaml b/Lang/Pico-8/00-META.yaml new file mode 100644 index 0000000000..5d0c380905 --- /dev/null +++ b/Lang/Pico-8/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Pico-8 diff --git a/Lang/Pico-8/Hello-world-Text b/Lang/Pico-8/Hello-world-Text new file mode 120000 index 0000000000..8a6a254eaa --- /dev/null +++ b/Lang/Pico-8/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Pico-8 \ No newline at end of file diff --git a/Lang/Pluto/00-LANG.txt b/Lang/Pluto/00-LANG.txt new file mode 100644 index 0000000000..debf9ec69a --- /dev/null +++ b/Lang/Pluto/00-LANG.txt @@ -0,0 +1,41 @@ +{{language|Pluto +|exec=interpreted +|strength=strong +|safety=safe +|express=implicit +|checking=dynamic +|gc=yes +|hopl=no +|site=https://pluto-lang.org/}} +Pluto is a superset of Lua 5.4 with a focus on general-purpose programming. While being remarkably compatible with Lua 5.4 source-code & bytecode, it enhances the standard library & adds more than a dozen highly-desired syntaxes such as switch statements, compound operators, classes, class inheritance, string interpolation, type hinting, enums, and so on. + +Pluto aspires to be a version of Lua with a larger feature-set, that is all. Pluto is not a Lua-killer, an attempted successor, or any of that. Many people (rightly so) love Lua precisely because of the design philosophy. And fundamentally, Pluto is a major deviation from Lua's design philosophy. Some may prefer this, some may not. + +The language is being developed on [https://github.com/PlutoLang/Pluto github] and pre-built binaries for 64-bit Linux, MacOS and Windows can be downloaded [https://github.com/PlutoLang/Pluto/releases here]. + +Here is a list of custom libraries used on Rosetta Code: +{|class="wikitable" +! No. !! Module name !! No. !! Module name +|- +| 1 || [[:Category:Pluto-fmt|fmt]] || 2 || [[:Category:Pluto-math2|math2]] +|- +| 3 || [[:Category:Pluto-int|int]] || 4 || [[:Category:Pluto-table2|table2]] +|- +| 5 || [[:Category:Pluto-complex|complex]] || 6 || [[:Category:Pluto-rat|rat]] +|- +| 7 || [[:Category:Pluto-queue|queue]] || 8 || [[:Category:Pluto-map|map]] +|- +| 9 || [[:Category:Pluto-list|list]] || 10 || [[:Category:Pluto-perm|perm]] +|- +|11 || [[:Category:Pluto-ansi|ansi]] || 12 || [[:Category:Pluto-io2|io2]] +|- +|13 || [[:Category:Pluto-uchar|uchar]] || 14 || [[:Category:Pluto-gchar|gchar]] +|- +|} + +== To do == +[[Tasks not implemented in Pluto]] + +== See also == + +[[Lua]] \ No newline at end of file diff --git a/Lang/Pluto/00-META.yaml b/Lang/Pluto/00-META.yaml new file mode 100644 index 0000000000..4169e06d3e --- /dev/null +++ b/Lang/Pluto/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Pluto diff --git a/Lang/Pluto/99-bottles-of-beer b/Lang/Pluto/99-bottles-of-beer new file mode 120000 index 0000000000..cc21927564 --- /dev/null +++ b/Lang/Pluto/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/A+B b/Lang/Pluto/A+B new file mode 120000 index 0000000000..c26f431720 --- /dev/null +++ b/Lang/Pluto/A+B @@ -0,0 +1 @@ +../../Task/A+B/Pluto \ No newline at end of file diff --git a/Lang/Pluto/ABC-problem b/Lang/Pluto/ABC-problem new file mode 120000 index 0000000000..13affeffe2 --- /dev/null +++ b/Lang/Pluto/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/AKS-test-for-primes b/Lang/Pluto/AKS-test-for-primes new file mode 120000 index 0000000000..55e9fce3e0 --- /dev/null +++ b/Lang/Pluto/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abelian-sandpile-model b/Lang/Pluto/Abelian-sandpile-model new file mode 120000 index 0000000000..84e194b9d0 --- /dev/null +++ b/Lang/Pluto/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abelian-sandpile-model-Identity b/Lang/Pluto/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..5258fd0a4e --- /dev/null +++ b/Lang/Pluto/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abstract-type b/Lang/Pluto/Abstract-type new file mode 120000 index 0000000000..f418e6a876 --- /dev/null +++ b/Lang/Pluto/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abundant-deficient-and-perfect-number-classifications b/Lang/Pluto/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..f5843a0883 --- /dev/null +++ b/Lang/Pluto/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Abundant-odd-numbers b/Lang/Pluto/Abundant-odd-numbers new file mode 120000 index 0000000000..18495df602 --- /dev/null +++ b/Lang/Pluto/Abundant-odd-numbers @@ -0,0 +1 @@ +../../Task/Abundant-odd-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Achilles-numbers b/Lang/Pluto/Achilles-numbers new file mode 120000 index 0000000000..0121ec15f3 --- /dev/null +++ b/Lang/Pluto/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ackermann-function b/Lang/Pluto/Ackermann-function new file mode 120000 index 0000000000..b2e9e8bcf4 --- /dev/null +++ b/Lang/Pluto/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Address-of-a-variable b/Lang/Pluto/Address-of-a-variable new file mode 120000 index 0000000000..db8c9fa74c --- /dev/null +++ b/Lang/Pluto/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Almost-prime b/Lang/Pluto/Almost-prime new file mode 120000 index 0000000000..8dfdefc597 --- /dev/null +++ b/Lang/Pluto/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Anti-primes b/Lang/Pluto/Anti-primes new file mode 120000 index 0000000000..62e9118e82 --- /dev/null +++ b/Lang/Pluto/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Approximate-equality b/Lang/Pluto/Approximate-equality new file mode 120000 index 0000000000..65832f9c4c --- /dev/null +++ b/Lang/Pluto/Approximate-equality @@ -0,0 +1 @@ +../../Task/Approximate-equality/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arbitrary-precision-integers-included- b/Lang/Pluto/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..63cf45fedf --- /dev/null +++ b/Lang/Pluto/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-Complex b/Lang/Pluto/Arithmetic-Complex new file mode 120000 index 0000000000..e8437b9a01 --- /dev/null +++ b/Lang/Pluto/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-Integer b/Lang/Pluto/Arithmetic-Integer new file mode 120000 index 0000000000..3b77091442 --- /dev/null +++ b/Lang/Pluto/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-Rational b/Lang/Pluto/Arithmetic-Rational new file mode 120000 index 0000000000..497dafd0e0 --- /dev/null +++ b/Lang/Pluto/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-derivative b/Lang/Pluto/Arithmetic-derivative new file mode 120000 index 0000000000..9254d1c7e4 --- /dev/null +++ b/Lang/Pluto/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arithmetic-geometric-mean b/Lang/Pluto/Arithmetic-geometric-mean new file mode 120000 index 0000000000..7f7bd49c54 --- /dev/null +++ b/Lang/Pluto/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Array-concatenation b/Lang/Pluto/Array-concatenation new file mode 120000 index 0000000000..b151e60e5d --- /dev/null +++ b/Lang/Pluto/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Arrays b/Lang/Pluto/Arrays new file mode 120000 index 0000000000..36aa2a73e2 --- /dev/null +++ b/Lang/Pluto/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Ascending-primes b/Lang/Pluto/Ascending-primes new file mode 120000 index 0000000000..b086dde9de --- /dev/null +++ b/Lang/Pluto/Ascending-primes @@ -0,0 +1 @@ +../../Task/Ascending-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Associative-array-Creation b/Lang/Pluto/Associative-array-Creation new file mode 120000 index 0000000000..dab36a66d3 --- /dev/null +++ b/Lang/Pluto/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Associative-array-Iteration b/Lang/Pluto/Associative-array-Iteration new file mode 120000 index 0000000000..5ced29976c --- /dev/null +++ b/Lang/Pluto/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Associative-array-Merging b/Lang/Pluto/Associative-array-Merging new file mode 120000 index 0000000000..e8bdf6f6ca --- /dev/null +++ b/Lang/Pluto/Associative-array-Merging @@ -0,0 +1 @@ +../../Task/Associative-array-Merging/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Attractive-numbers b/Lang/Pluto/Attractive-numbers new file mode 120000 index 0000000000..cc6d5fdf22 --- /dev/null +++ b/Lang/Pluto/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Arithmetic-mean b/Lang/Pluto/Averages-Arithmetic-mean new file mode 120000 index 0000000000..a80eb1d9ce --- /dev/null +++ b/Lang/Pluto/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Median b/Lang/Pluto/Averages-Median new file mode 120000 index 0000000000..4877cdaa55 --- /dev/null +++ b/Lang/Pluto/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Pythagorean-means b/Lang/Pluto/Averages-Pythagorean-means new file mode 120000 index 0000000000..f4cb6461df --- /dev/null +++ b/Lang/Pluto/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Averages-Root-mean-square b/Lang/Pluto/Averages-Root-mean-square new file mode 120000 index 0000000000..744197c17a --- /dev/null +++ b/Lang/Pluto/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Balanced-brackets b/Lang/Pluto/Balanced-brackets new file mode 120000 index 0000000000..e55ebe8e48 --- /dev/null +++ b/Lang/Pluto/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Base64-decode-data b/Lang/Pluto/Base64-decode-data new file mode 120000 index 0000000000..9e79a215f0 --- /dev/null +++ b/Lang/Pluto/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bell-numbers b/Lang/Pluto/Bell-numbers new file mode 120000 index 0000000000..12ebb36a37 --- /dev/null +++ b/Lang/Pluto/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitmap b/Lang/Pluto/Bitmap new file mode 120000 index 0000000000..2eae4de5c9 --- /dev/null +++ b/Lang/Pluto/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitmap-Bresenhams-line-algorithm b/Lang/Pluto/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..648ca4156e --- /dev/null +++ b/Lang/Pluto/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitmap-Midpoint-circle-algorithm b/Lang/Pluto/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..30e98198c1 --- /dev/null +++ b/Lang/Pluto/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Bitwise-operations b/Lang/Pluto/Bitwise-operations new file mode 120000 index 0000000000..7aa2755b89 --- /dev/null +++ b/Lang/Pluto/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/CRC-32 b/Lang/Pluto/CRC-32 new file mode 120000 index 0000000000..a2f9755cc8 --- /dev/null +++ b/Lang/Pluto/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Caesar-cipher b/Lang/Pluto/Caesar-cipher new file mode 120000 index 0000000000..92165c560f --- /dev/null +++ b/Lang/Pluto/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Calkin-Wilf-sequence b/Lang/Pluto/Calkin-Wilf-sequence new file mode 120000 index 0000000000..e7c08bf16e --- /dev/null +++ b/Lang/Pluto/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Call-a-foreign-language-function b/Lang/Pluto/Call-a-foreign-language-function new file mode 120000 index 0000000000..f071bb1596 --- /dev/null +++ b/Lang/Pluto/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Call-a-function-in-a-shared-library b/Lang/Pluto/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..fb03a37240 --- /dev/null +++ b/Lang/Pluto/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Case-sensitivity-of-identifiers b/Lang/Pluto/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..e37b951419 --- /dev/null +++ b/Lang/Pluto/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Casting-out-nines b/Lang/Pluto/Casting-out-nines new file mode 120000 index 0000000000..f9d2b5090f --- /dev/null +++ b/Lang/Pluto/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Collections b/Lang/Pluto/Collections new file mode 120000 index 0000000000..82a2dd2b4f --- /dev/null +++ b/Lang/Pluto/Collections @@ -0,0 +1 @@ +../../Task/Collections/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Combinations b/Lang/Pluto/Combinations new file mode 120000 index 0000000000..1554032a2c --- /dev/null +++ b/Lang/Pluto/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Combinations-with-repetitions b/Lang/Pluto/Combinations-with-repetitions new file mode 120000 index 0000000000..27271a521e --- /dev/null +++ b/Lang/Pluto/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Command-line-arguments b/Lang/Pluto/Command-line-arguments new file mode 120000 index 0000000000..0f5f02829e --- /dev/null +++ b/Lang/Pluto/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Comments b/Lang/Pluto/Comments new file mode 120000 index 0000000000..8d1e636123 --- /dev/null +++ b/Lang/Pluto/Comments @@ -0,0 +1 @@ +../../Task/Comments/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compare-length-of-two-strings b/Lang/Pluto/Compare-length-of-two-strings new file mode 120000 index 0000000000..a17ca1cb1f --- /dev/null +++ b/Lang/Pluto/Compare-length-of-two-strings @@ -0,0 +1 @@ +../../Task/Compare-length-of-two-strings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Compiler-lexical-analyzer b/Lang/Pluto/Compiler-lexical-analyzer new file mode 120000 index 0000000000..0e5b3d7d41 --- /dev/null +++ b/Lang/Pluto/Compiler-lexical-analyzer @@ -0,0 +1 @@ +../../Task/Compiler-lexical-analyzer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Conditional-structures b/Lang/Pluto/Conditional-structures new file mode 120000 index 0000000000..480797a688 --- /dev/null +++ b/Lang/Pluto/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..4207df96c4 --- /dev/null +++ b/Lang/Pluto/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Convert-decimal-number-to-rational b/Lang/Pluto/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..67bc18205b --- /dev/null +++ b/Lang/Pluto/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Count-in-octal b/Lang/Pluto/Count-in-octal new file mode 120000 index 0000000000..c5624def8e --- /dev/null +++ b/Lang/Pluto/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Count-the-coins b/Lang/Pluto/Count-the-coins new file mode 120000 index 0000000000..7996299523 --- /dev/null +++ b/Lang/Pluto/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Create-a-file b/Lang/Pluto/Create-a-file new file mode 120000 index 0000000000..1e22b0b1e3 --- /dev/null +++ b/Lang/Pluto/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Currying b/Lang/Pluto/Currying new file mode 120000 index 0000000000..98e5282551 --- /dev/null +++ b/Lang/Pluto/Currying @@ -0,0 +1 @@ +../../Task/Currying/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Delete-a-file b/Lang/Pluto/Delete-a-file new file mode 120000 index 0000000000..b17ce9999b --- /dev/null +++ b/Lang/Pluto/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Descending-primes b/Lang/Pluto/Descending-primes new file mode 120000 index 0000000000..c35e1667b5 --- /dev/null +++ b/Lang/Pluto/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Determine-if-a-string-is-numeric b/Lang/Pluto/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..f3177e5d6e --- /dev/null +++ b/Lang/Pluto/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Disarium-numbers b/Lang/Pluto/Disarium-numbers new file mode 120000 index 0000000000..fd659f8581 --- /dev/null +++ b/Lang/Pluto/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Display-a-linear-combination b/Lang/Pluto/Display-a-linear-combination new file mode 120000 index 0000000000..b9e618e087 --- /dev/null +++ b/Lang/Pluto/Display-a-linear-combination @@ -0,0 +1 @@ +../../Task/Display-a-linear-combination/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Distribution-of-0-digits-in-factorial-series b/Lang/Pluto/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..a06ffa876b --- /dev/null +++ b/Lang/Pluto/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Definition b/Lang/Pluto/Doubly-linked-list-Definition new file mode 120000 index 0000000000..2c673acc7c --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Element-definition b/Lang/Pluto/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..7b2f1839e3 --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Doubly-linked-list-Traversal b/Lang/Pluto/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..9a9262d67b --- /dev/null +++ b/Lang/Pluto/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Dutch-national-flag-problem b/Lang/Pluto/Dutch-national-flag-problem new file mode 120000 index 0000000000..4ca6eb0344 --- /dev/null +++ b/Lang/Pluto/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Euler-method b/Lang/Pluto/Euler-method new file mode 120000 index 0000000000..b7dbfe93a0 --- /dev/null +++ b/Lang/Pluto/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Eulers-identity b/Lang/Pluto/Eulers-identity new file mode 120000 index 0000000000..97a4ba8ed8 --- /dev/null +++ b/Lang/Pluto/Eulers-identity @@ -0,0 +1 @@ +../../Task/Eulers-identity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Even-or-odd b/Lang/Pluto/Even-or-odd new file mode 120000 index 0000000000..fc5cc6a785 --- /dev/null +++ b/Lang/Pluto/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Execute-a-system-command b/Lang/Pluto/Execute-a-system-command new file mode 120000 index 0000000000..005fc83a4b --- /dev/null +++ b/Lang/Pluto/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factorial b/Lang/Pluto/Factorial new file mode 120000 index 0000000000..26b76cb13d --- /dev/null +++ b/Lang/Pluto/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factorial-primes b/Lang/Pluto/Factorial-primes new file mode 120000 index 0000000000..b57eac84ac --- /dev/null +++ b/Lang/Pluto/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factorions b/Lang/Pluto/Factorions new file mode 120000 index 0000000000..0d6fdce25f --- /dev/null +++ b/Lang/Pluto/Factorions @@ -0,0 +1 @@ +../../Task/Factorions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Factors-of-an-integer b/Lang/Pluto/Factors-of-an-integer new file mode 120000 index 0000000000..cc13f27676 --- /dev/null +++ b/Lang/Pluto/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Farey-sequence b/Lang/Pluto/Farey-sequence new file mode 120000 index 0000000000..d29c19b41e --- /dev/null +++ b/Lang/Pluto/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Feigenbaum-constant-calculation b/Lang/Pluto/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..256bf8cb19 --- /dev/null +++ b/Lang/Pluto/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Fibonacci-sequence b/Lang/Pluto/Fibonacci-sequence new file mode 120000 index 0000000000..efff8e1eb6 --- /dev/null +++ b/Lang/Pluto/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Filter b/Lang/Pluto/Filter new file mode 120000 index 0000000000..98b0321ee6 --- /dev/null +++ b/Lang/Pluto/Filter @@ -0,0 +1 @@ +../../Task/Filter/Pluto \ No newline at end of file diff --git a/Lang/Pluto/FizzBuzz b/Lang/Pluto/FizzBuzz new file mode 120000 index 0000000000..bd54d0d8bb --- /dev/null +++ b/Lang/Pluto/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Floyd-Warshall-algorithm b/Lang/Pluto/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..7df2d45291 --- /dev/null +++ b/Lang/Pluto/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Formatted-numeric-output b/Lang/Pluto/Formatted-numeric-output new file mode 120000 index 0000000000..ca4bc2e2c0 --- /dev/null +++ b/Lang/Pluto/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Function-definition b/Lang/Pluto/Function-definition new file mode 120000 index 0000000000..8c3e064f65 --- /dev/null +++ b/Lang/Pluto/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Gamma-function b/Lang/Pluto/Gamma-function new file mode 120000 index 0000000000..8b7dee23dc --- /dev/null +++ b/Lang/Pluto/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Generate-lower-case-ASCII-alphabet b/Lang/Pluto/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..64f2576fe0 --- /dev/null +++ b/Lang/Pluto/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Giuga-numbers b/Lang/Pluto/Giuga-numbers new file mode 120000 index 0000000000..221b7a2689 --- /dev/null +++ b/Lang/Pluto/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Goldbachs-comet b/Lang/Pluto/Goldbachs-comet new file mode 120000 index 0000000000..ff1cca329d --- /dev/null +++ b/Lang/Pluto/Goldbachs-comet @@ -0,0 +1 @@ +../../Task/Goldbachs-comet/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Greatest-common-divisor b/Lang/Pluto/Greatest-common-divisor new file mode 120000 index 0000000000..a4feeee2fd --- /dev/null +++ b/Lang/Pluto/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Greatest-element-of-a-list b/Lang/Pluto/Greatest-element-of-a-list new file mode 120000 index 0000000000..85148f8e2b --- /dev/null +++ b/Lang/Pluto/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hailstone-sequence b/Lang/Pluto/Hailstone-sequence new file mode 120000 index 0000000000..0c70c36e8a --- /dev/null +++ b/Lang/Pluto/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Halt-and-catch-fire b/Lang/Pluto/Halt-and-catch-fire new file mode 120000 index 0000000000..f8e69baccf --- /dev/null +++ b/Lang/Pluto/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hash-from-two-arrays b/Lang/Pluto/Hash-from-two-arrays new file mode 120000 index 0000000000..5612dbf1a3 --- /dev/null +++ b/Lang/Pluto/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Newline-omission b/Lang/Pluto/Hello-world-Newline-omission new file mode 120000 index 0000000000..5020503885 --- /dev/null +++ b/Lang/Pluto/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Standard-error b/Lang/Pluto/Hello-world-Standard-error new file mode 120000 index 0000000000..2b41d962cc --- /dev/null +++ b/Lang/Pluto/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Hello-world-Text b/Lang/Pluto/Hello-world-Text new file mode 120000 index 0000000000..6d5bb1406f --- /dev/null +++ b/Lang/Pluto/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Higher-order-functions b/Lang/Pluto/Higher-order-functions new file mode 120000 index 0000000000..532e183ee0 --- /dev/null +++ b/Lang/Pluto/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Horners-rule-for-polynomial-evaluation b/Lang/Pluto/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..02512d6f7e --- /dev/null +++ b/Lang/Pluto/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Humble-numbers b/Lang/Pluto/Humble-numbers new file mode 120000 index 0000000000..f616a12fe9 --- /dev/null +++ b/Lang/Pluto/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Increment-a-numerical-string b/Lang/Pluto/Increment-a-numerical-string new file mode 120000 index 0000000000..5413743d7c --- /dev/null +++ b/Lang/Pluto/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Infinity b/Lang/Pluto/Infinity new file mode 120000 index 0000000000..cb81bde8e2 --- /dev/null +++ b/Lang/Pluto/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/JSON b/Lang/Pluto/JSON new file mode 120000 index 0000000000..bc77142a3f --- /dev/null +++ b/Lang/Pluto/JSON @@ -0,0 +1 @@ +../../Task/JSON/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jacobsthal-numbers b/Lang/Pluto/Jacobsthal-numbers new file mode 120000 index 0000000000..310c137dfd --- /dev/null +++ b/Lang/Pluto/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Jewels-and-stones b/Lang/Pluto/Jewels-and-stones new file mode 120000 index 0000000000..0d8632e132 --- /dev/null +++ b/Lang/Pluto/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Josephus-problem b/Lang/Pluto/Josephus-problem new file mode 120000 index 0000000000..c17c5c052c --- /dev/null +++ b/Lang/Pluto/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Kaprekar-numbers b/Lang/Pluto/Kaprekar-numbers new file mode 120000 index 0000000000..1c32b1316d --- /dev/null +++ b/Lang/Pluto/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Leap-year b/Lang/Pluto/Leap-year new file mode 120000 index 0000000000..9574544885 --- /dev/null +++ b/Lang/Pluto/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Literals-Floating-point b/Lang/Pluto/Literals-Floating-point new file mode 120000 index 0000000000..f40aa2eb22 --- /dev/null +++ b/Lang/Pluto/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Literals-Integer b/Lang/Pluto/Literals-Integer new file mode 120000 index 0000000000..2ca0134201 --- /dev/null +++ b/Lang/Pluto/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loop-over-multiple-arrays-simultaneously b/Lang/Pluto/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..cebc902b5b --- /dev/null +++ b/Lang/Pluto/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Break b/Lang/Pluto/Loops-Break new file mode 120000 index 0000000000..2b3657d2de --- /dev/null +++ b/Lang/Pluto/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Continue b/Lang/Pluto/Loops-Continue new file mode 120000 index 0000000000..5f41db6125 --- /dev/null +++ b/Lang/Pluto/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Do-while b/Lang/Pluto/Loops-Do-while new file mode 120000 index 0000000000..a265d4decf --- /dev/null +++ b/Lang/Pluto/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Downward-for b/Lang/Pluto/Loops-Downward-for new file mode 120000 index 0000000000..6302a5cc0d --- /dev/null +++ b/Lang/Pluto/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-For b/Lang/Pluto/Loops-For new file mode 120000 index 0000000000..9f83ae12bd --- /dev/null +++ b/Lang/Pluto/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-For-with-a-specified-step b/Lang/Pluto/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..508122a2e3 --- /dev/null +++ b/Lang/Pluto/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Foreach b/Lang/Pluto/Loops-Foreach new file mode 120000 index 0000000000..9dbfba413e --- /dev/null +++ b/Lang/Pluto/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Increment-loop-index-within-loop-body b/Lang/Pluto/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..f1ce9d6778 --- /dev/null +++ b/Lang/Pluto/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Infinite b/Lang/Pluto/Loops-Infinite new file mode 120000 index 0000000000..50986dd414 --- /dev/null +++ b/Lang/Pluto/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-N-plus-one-half b/Lang/Pluto/Loops-N-plus-one-half new file mode 120000 index 0000000000..433e3f6336 --- /dev/null +++ b/Lang/Pluto/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Nested b/Lang/Pluto/Loops-Nested new file mode 120000 index 0000000000..96f4c43c62 --- /dev/null +++ b/Lang/Pluto/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-While b/Lang/Pluto/Loops-While new file mode 120000 index 0000000000..3aa5f84aba --- /dev/null +++ b/Lang/Pluto/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-With-multiple-ranges b/Lang/Pluto/Loops-With-multiple-ranges new file mode 120000 index 0000000000..b1ef3af096 --- /dev/null +++ b/Lang/Pluto/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Loops-Wrong-ranges b/Lang/Pluto/Loops-Wrong-ranges new file mode 120000 index 0000000000..7b8bd4ecb0 --- /dev/null +++ b/Lang/Pluto/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Luhn-test-of-credit-card-numbers b/Lang/Pluto/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..c06ed72be3 --- /dev/null +++ b/Lang/Pluto/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/M-bius-function b/Lang/Pluto/M-bius-function new file mode 120000 index 0000000000..99da13a437 --- /dev/null +++ b/Lang/Pluto/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Machine-code b/Lang/Pluto/Machine-code new file mode 120000 index 0000000000..82c80d52fd --- /dev/null +++ b/Lang/Pluto/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-squares-of-doubly-even-order b/Lang/Pluto/Magic-squares-of-doubly-even-order new file mode 120000 index 0000000000..357d3e5480 --- /dev/null +++ b/Lang/Pluto/Magic-squares-of-doubly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-doubly-even-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-squares-of-odd-order b/Lang/Pluto/Magic-squares-of-odd-order new file mode 120000 index 0000000000..5df4846612 --- /dev/null +++ b/Lang/Pluto/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Magic-squares-of-singly-even-order b/Lang/Pluto/Magic-squares-of-singly-even-order new file mode 120000 index 0000000000..2430b82023 --- /dev/null +++ b/Lang/Pluto/Magic-squares-of-singly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-singly-even-order/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Mian-Chowla-sequence b/Lang/Pluto/Mian-Chowla-sequence new file mode 120000 index 0000000000..f966e85ca5 --- /dev/null +++ b/Lang/Pluto/Mian-Chowla-sequence @@ -0,0 +1 @@ +../../Task/Mian-Chowla-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Modular-inverse b/Lang/Pluto/Modular-inverse new file mode 120000 index 0000000000..339ad0f426 --- /dev/null +++ b/Lang/Pluto/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Multiplication-tables b/Lang/Pluto/Multiplication-tables new file mode 120000 index 0000000000..98a4d7bd3c --- /dev/null +++ b/Lang/Pluto/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Mutual-recursion b/Lang/Pluto/Mutual-recursion new file mode 120000 index 0000000000..3866a9925a --- /dev/null +++ b/Lang/Pluto/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Named-parameters b/Lang/Pluto/Named-parameters new file mode 120000 index 0000000000..8f0b72ba9b --- /dev/null +++ b/Lang/Pluto/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Narcissistic-decimal-number b/Lang/Pluto/Narcissistic-decimal-number new file mode 120000 index 0000000000..feead3c3a0 --- /dev/null +++ b/Lang/Pluto/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Nested-templated-data b/Lang/Pluto/Nested-templated-data new file mode 120000 index 0000000000..d56f50a5d8 --- /dev/null +++ b/Lang/Pluto/Nested-templated-data @@ -0,0 +1 @@ +../../Task/Nested-templated-data/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Non-decimal-radices-Convert b/Lang/Pluto/Non-decimal-radices-Convert new file mode 120000 index 0000000000..e1fddc5a20 --- /dev/null +++ b/Lang/Pluto/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Numerical-integration b/Lang/Pluto/Numerical-integration new file mode 120000 index 0000000000..e89c1b753a --- /dev/null +++ b/Lang/Pluto/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Old-Russian-measure-of-length b/Lang/Pluto/Old-Russian-measure-of-length new file mode 120000 index 0000000000..9f7493d0af --- /dev/null +++ b/Lang/Pluto/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Order-by-pair-comparisons b/Lang/Pluto/Order-by-pair-comparisons new file mode 120000 index 0000000000..1c7665f6b2 --- /dev/null +++ b/Lang/Pluto/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Palindrome-detection b/Lang/Pluto/Palindrome-detection new file mode 120000 index 0000000000..755083778a --- /dev/null +++ b/Lang/Pluto/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pancake-numbers b/Lang/Pluto/Pancake-numbers new file mode 120000 index 0000000000..129dac7c77 --- /dev/null +++ b/Lang/Pluto/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Parsing-RPN-calculator-algorithm b/Lang/Pluto/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..f120a8c76e --- /dev/null +++ b/Lang/Pluto/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pascals-triangle-Puzzle b/Lang/Pluto/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..312b0f9b1b --- /dev/null +++ b/Lang/Pluto/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Perfect-shuffle b/Lang/Pluto/Perfect-shuffle new file mode 120000 index 0000000000..1dd4b8c882 --- /dev/null +++ b/Lang/Pluto/Perfect-shuffle @@ -0,0 +1 @@ +../../Task/Perfect-shuffle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Permutations b/Lang/Pluto/Permutations new file mode 120000 index 0000000000..750604fad2 --- /dev/null +++ b/Lang/Pluto/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pernicious-numbers b/Lang/Pluto/Pernicious-numbers new file mode 120000 index 0000000000..29e4a1f27e --- /dev/null +++ b/Lang/Pluto/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pick-random-element b/Lang/Pluto/Pick-random-element new file mode 120000 index 0000000000..f181e160e5 --- /dev/null +++ b/Lang/Pluto/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Pisano-period b/Lang/Pluto/Pisano-period new file mode 120000 index 0000000000..377c8913e0 --- /dev/null +++ b/Lang/Pluto/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Power-set b/Lang/Pluto/Power-set new file mode 120000 index 0000000000..72362c1ec0 --- /dev/null +++ b/Lang/Pluto/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Primality-by-trial-division b/Lang/Pluto/Primality-by-trial-division new file mode 120000 index 0000000000..01622c5c43 --- /dev/null +++ b/Lang/Pluto/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Priority-queue b/Lang/Pluto/Priority-queue new file mode 120000 index 0000000000..ad7bed4159 --- /dev/null +++ b/Lang/Pluto/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Read-a-file-line-by-line b/Lang/Pluto/Read-a-file-line-by-line new file mode 120000 index 0000000000..d35b8cfbc4 --- /dev/null +++ b/Lang/Pluto/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Rename-a-file b/Lang/Pluto/Rename-a-file new file mode 120000 index 0000000000..dd234bb854 --- /dev/null +++ b/Lang/Pluto/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Repeat-a-string b/Lang/Pluto/Repeat-a-string new file mode 120000 index 0000000000..7cea8b7235 --- /dev/null +++ b/Lang/Pluto/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Reverse-a-string b/Lang/Pluto/Reverse-a-string new file mode 120000 index 0000000000..dc5b2e2493 --- /dev/null +++ b/Lang/Pluto/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Reverse-words-in-a-string b/Lang/Pluto/Reverse-words-in-a-string new file mode 120000 index 0000000000..378e6ea4b7 --- /dev/null +++ b/Lang/Pluto/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roman-numerals-Encode b/Lang/Pluto/Roman-numerals-Encode new file mode 120000 index 0000000000..d12a85d68f --- /dev/null +++ b/Lang/Pluto/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roots-of-a-quadratic-function b/Lang/Pluto/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..8e5bf4c688 --- /dev/null +++ b/Lang/Pluto/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Roots-of-unity b/Lang/Pluto/Roots-of-unity new file mode 120000 index 0000000000..e0f1ada438 --- /dev/null +++ b/Lang/Pluto/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Rot-13 b/Lang/Pluto/Rot-13 new file mode 120000 index 0000000000..ca2ef70221 --- /dev/null +++ b/Lang/Pluto/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Runge-Kutta-method b/Lang/Pluto/Runge-Kutta-method new file mode 120000 index 0000000000..1f412f01e7 --- /dev/null +++ b/Lang/Pluto/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Self-numbers b/Lang/Pluto/Self-numbers new file mode 120000 index 0000000000..6ddaee76e3 --- /dev/null +++ b/Lang/Pluto/Self-numbers @@ -0,0 +1 @@ +../../Task/Self-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Semordnilap b/Lang/Pluto/Semordnilap new file mode 120000 index 0000000000..92f96e5b0c --- /dev/null +++ b/Lang/Pluto/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sequence-of-primes-by-trial-division b/Lang/Pluto/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..0a541cb28c --- /dev/null +++ b/Lang/Pluto/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Set b/Lang/Pluto/Set new file mode 120000 index 0000000000..9bbe04e32f --- /dev/null +++ b/Lang/Pluto/Set @@ -0,0 +1 @@ +../../Task/Set/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Set-consolidation b/Lang/Pluto/Set-consolidation new file mode 120000 index 0000000000..af203f8560 --- /dev/null +++ b/Lang/Pluto/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singly-linked-list-Element-definition b/Lang/Pluto/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..1f46e7b961 --- /dev/null +++ b/Lang/Pluto/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singly-linked-list-Element-insertion b/Lang/Pluto/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..27b69c63f5 --- /dev/null +++ b/Lang/Pluto/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Singly-linked-list-Traversal b/Lang/Pluto/Singly-linked-list-Traversal new file mode 120000 index 0000000000..a9f1239636 --- /dev/null +++ b/Lang/Pluto/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sleep b/Lang/Pluto/Sleep new file mode 120000 index 0000000000..fe338781ff --- /dev/null +++ b/Lang/Pluto/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Smarandache-prime-digital-sequence b/Lang/Pluto/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..c1bae0f65e --- /dev/null +++ b/Lang/Pluto/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Soloways-recurring-rainfall b/Lang/Pluto/Soloways-recurring-rainfall new file mode 120000 index 0000000000..3292890eaf --- /dev/null +++ b/Lang/Pluto/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sort-an-integer-array b/Lang/Pluto/Sort-an-integer-array new file mode 120000 index 0000000000..43fcfc8222 --- /dev/null +++ b/Lang/Pluto/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Stack b/Lang/Pluto/Stack new file mode 120000 index 0000000000..b73a91dd58 --- /dev/null +++ b/Lang/Pluto/Stack @@ -0,0 +1 @@ +../../Task/Stack/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-interpolation-included- b/Lang/Pluto/String-interpolation-included- new file mode 120000 index 0000000000..7953b3790b --- /dev/null +++ b/Lang/Pluto/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/Pluto \ No newline at end of file diff --git a/Lang/Pluto/String-length b/Lang/Pluto/String-length new file mode 120000 index 0000000000..9313ae7886 --- /dev/null +++ b/Lang/Pluto/String-length @@ -0,0 +1 @@ +../../Task/String-length/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-digits-of-an-integer b/Lang/Pluto/Sum-digits-of-an-integer new file mode 120000 index 0000000000..0c6a6782ed --- /dev/null +++ b/Lang/Pluto/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..45a9f51475 --- /dev/null +++ b/Lang/Pluto/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Symmetric-difference b/Lang/Pluto/Symmetric-difference new file mode 120000 index 0000000000..09ce1d13b8 --- /dev/null +++ b/Lang/Pluto/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Pluto \ No newline at end of file diff --git a/Lang/Pluto/System-time b/Lang/Pluto/System-time new file mode 120000 index 0000000000..8575dc8b3a --- /dev/null +++ b/Lang/Pluto/System-time @@ -0,0 +1 @@ +../../Task/System-time/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Tau-function b/Lang/Pluto/Tau-function new file mode 120000 index 0000000000..03b50006f6 --- /dev/null +++ b/Lang/Pluto/Tau-function @@ -0,0 +1 @@ +../../Task/Tau-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Tau-number b/Lang/Pluto/Tau-number new file mode 120000 index 0000000000..532021c510 --- /dev/null +++ b/Lang/Pluto/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Clear-the-screen b/Lang/Pluto/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..edabc9ce73 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Coloured-text b/Lang/Pluto/Terminal-control-Coloured-text new file mode 120000 index 0000000000..378909157d --- /dev/null +++ b/Lang/Pluto/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Cursor-movement b/Lang/Pluto/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..bf8c8572a2 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Cursor-positioning b/Lang/Pluto/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..feeca5cd4b --- /dev/null +++ b/Lang/Pluto/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Dimensions b/Lang/Pluto/Terminal-control-Dimensions new file mode 120000 index 0000000000..79b01b1a8a --- /dev/null +++ b/Lang/Pluto/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Display-an-extended-character b/Lang/Pluto/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..d9f4ec60f5 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Hiding-the-cursor b/Lang/Pluto/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..5126fbbc31 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Inverse-video b/Lang/Pluto/Terminal-control-Inverse-video new file mode 120000 index 0000000000..a011de6856 --- /dev/null +++ b/Lang/Pluto/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Preserve-screen b/Lang/Pluto/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..4985e385ae --- /dev/null +++ b/Lang/Pluto/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Ringing-the-terminal-bell b/Lang/Pluto/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c14ff1f9fd --- /dev/null +++ b/Lang/Pluto/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Terminal-control-Unicode-output b/Lang/Pluto/Terminal-control-Unicode-output new file mode 120000 index 0000000000..c67e68f15d --- /dev/null +++ b/Lang/Pluto/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Test-integerness b/Lang/Pluto/Test-integerness new file mode 120000 index 0000000000..9a3717f805 --- /dev/null +++ b/Lang/Pluto/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Time-a-function b/Lang/Pluto/Time-a-function new file mode 120000 index 0000000000..1ca7d0a7b7 --- /dev/null +++ b/Lang/Pluto/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Total-circles-area b/Lang/Pluto/Total-circles-area new file mode 120000 index 0000000000..2f856ad28d --- /dev/null +++ b/Lang/Pluto/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Totient-function b/Lang/Pluto/Totient-function new file mode 120000 index 0000000000..73b5eb6381 --- /dev/null +++ b/Lang/Pluto/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Towers-of-Hanoi b/Lang/Pluto/Towers-of-Hanoi new file mode 120000 index 0000000000..9b1428dcf0 --- /dev/null +++ b/Lang/Pluto/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Trabb-Pardo-Knuth-algorithm b/Lang/Pluto/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..e85f9f54de --- /dev/null +++ b/Lang/Pluto/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Pluto \ No newline at end of file diff --git a/Lang/Pluto/UPC b/Lang/Pluto/UPC new file mode 120000 index 0000000000..477e69b6c6 --- /dev/null +++ b/Lang/Pluto/UPC @@ -0,0 +1 @@ +../../Task/UPC/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Unicode-strings b/Lang/Pluto/Unicode-strings new file mode 120000 index 0000000000..482c486148 --- /dev/null +++ b/Lang/Pluto/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Unprimeable-numbers b/Lang/Pluto/Unprimeable-numbers new file mode 120000 index 0000000000..ec55975821 --- /dev/null +++ b/Lang/Pluto/Unprimeable-numbers @@ -0,0 +1 @@ +../../Task/Unprimeable-numbers/Pluto \ No newline at end of file diff --git a/Lang/Pluto/User-input-Text b/Lang/Pluto/User-input-Text new file mode 120000 index 0000000000..6c3afd2860 --- /dev/null +++ b/Lang/Pluto/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Van-Eck-sequence b/Lang/Pluto/Van-Eck-sequence new file mode 120000 index 0000000000..d053bbc892 --- /dev/null +++ b/Lang/Pluto/Van-Eck-sequence @@ -0,0 +1 @@ +../../Task/Van-Eck-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Van-der-Corput-sequence b/Lang/Pluto/Van-der-Corput-sequence new file mode 120000 index 0000000000..e6ce56ddef --- /dev/null +++ b/Lang/Pluto/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Variadic-function b/Lang/Pluto/Variadic-function new file mode 120000 index 0000000000..8d2be144f4 --- /dev/null +++ b/Lang/Pluto/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Vector b/Lang/Pluto/Vector new file mode 120000 index 0000000000..fd56d6c8ab --- /dev/null +++ b/Lang/Pluto/Vector @@ -0,0 +1 @@ +../../Task/Vector/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Vector-products b/Lang/Pluto/Vector-products new file mode 120000 index 0000000000..83a09bc1a3 --- /dev/null +++ b/Lang/Pluto/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Wagstaff-primes b/Lang/Pluto/Wagstaff-primes new file mode 120000 index 0000000000..d8a1a2f0da --- /dev/null +++ b/Lang/Pluto/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Wieferich-primes b/Lang/Pluto/Wieferich-primes new file mode 120000 index 0000000000..453231fbab --- /dev/null +++ b/Lang/Pluto/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Y-combinator b/Lang/Pluto/Y-combinator new file mode 120000 index 0000000000..b356912f44 --- /dev/null +++ b/Lang/Pluto/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Yellowstone-sequence b/Lang/Pluto/Yellowstone-sequence new file mode 120000 index 0000000000..f4fb013414 --- /dev/null +++ b/Lang/Pluto/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Zebra-puzzle b/Lang/Pluto/Zebra-puzzle new file mode 120000 index 0000000000..d1dee531e9 --- /dev/null +++ b/Lang/Pluto/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Pluto \ No newline at end of file diff --git a/Lang/Pluto/Zero-to-the-zero-power b/Lang/Pluto/Zero-to-the-zero-power new file mode 120000 index 0000000000..88cbcf1376 --- /dev/null +++ b/Lang/Pluto/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Pluto \ No newline at end of file diff --git a/Lang/PowerShell/AKS-test-for-primes b/Lang/PowerShell/AKS-test-for-primes new file mode 120000 index 0000000000..d5622ba541 --- /dev/null +++ b/Lang/PowerShell/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/M-bius-function b/Lang/PowerShell/M-bius-function new file mode 120000 index 0000000000..a50c276864 --- /dev/null +++ b/Lang/PowerShell/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PowerShell \ No newline at end of file diff --git a/Lang/Prolog/100-prisoners b/Lang/Prolog/100-prisoners new file mode 120000 index 0000000000..f105600099 --- /dev/null +++ b/Lang/Prolog/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Boolean-values b/Lang/Prolog/Boolean-values new file mode 120000 index 0000000000..a4d04329bd --- /dev/null +++ b/Lang/Prolog/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Damm-algorithm b/Lang/Prolog/Damm-algorithm new file mode 120000 index 0000000000..beadc26281 --- /dev/null +++ b/Lang/Prolog/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Hello-world-Newline-omission b/Lang/Prolog/Hello-world-Newline-omission new file mode 120000 index 0000000000..c1a7a16c3a --- /dev/null +++ b/Lang/Prolog/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Prolog \ No newline at end of file diff --git a/Lang/Prolog/ISBN13-check-digit b/Lang/Prolog/ISBN13-check-digit new file mode 120000 index 0000000000..a76610ede1 --- /dev/null +++ b/Lang/Prolog/ISBN13-check-digit @@ -0,0 +1 @@ +../../Task/ISBN13-check-digit/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Integer-comparison b/Lang/Prolog/Integer-comparison new file mode 120000 index 0000000000..700709dfc3 --- /dev/null +++ b/Lang/Prolog/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Iterated-digits-squaring b/Lang/Prolog/Iterated-digits-squaring new file mode 120000 index 0000000000..2783b6cb96 --- /dev/null +++ b/Lang/Prolog/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Josephus-problem b/Lang/Prolog/Josephus-problem new file mode 120000 index 0000000000..f88549c05c --- /dev/null +++ b/Lang/Prolog/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Magic-8-ball b/Lang/Prolog/Magic-8-ball new file mode 120000 index 0000000000..6daea6349e --- /dev/null +++ b/Lang/Prolog/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Old-Russian-measure-of-length b/Lang/Prolog/Old-Russian-measure-of-length new file mode 120000 index 0000000000..d1594e7647 --- /dev/null +++ b/Lang/Prolog/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Order-by-pair-comparisons b/Lang/Prolog/Order-by-pair-comparisons new file mode 120000 index 0000000000..b08bc67036 --- /dev/null +++ b/Lang/Prolog/Order-by-pair-comparisons @@ -0,0 +1 @@ +../../Task/Order-by-pair-comparisons/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Phrase-reversals b/Lang/Prolog/Phrase-reversals new file mode 120000 index 0000000000..1afa8eb5f5 --- /dev/null +++ b/Lang/Prolog/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Population-count b/Lang/Prolog/Population-count new file mode 120000 index 0000000000..1ffa420c15 --- /dev/null +++ b/Lang/Prolog/Population-count @@ -0,0 +1 @@ +../../Task/Population-count/Prolog \ No newline at end of file diff --git a/Lang/Prolog/RPG-attributes-generator b/Lang/Prolog/RPG-attributes-generator new file mode 120000 index 0000000000..cde5e146a7 --- /dev/null +++ b/Lang/Prolog/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Prolog \ No newline at end of file diff --git a/Lang/Prolog/SEDOLs b/Lang/Prolog/SEDOLs new file mode 120000 index 0000000000..21d9643112 --- /dev/null +++ b/Lang/Prolog/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Semordnilap b/Lang/Prolog/Semordnilap new file mode 120000 index 0000000000..c4e2d18fc4 --- /dev/null +++ b/Lang/Prolog/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sort-three-variables b/Lang/Prolog/Sort-three-variables new file mode 120000 index 0000000000..8518a9819c --- /dev/null +++ b/Lang/Prolog/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Stem-and-leaf-plot b/Lang/Prolog/Stem-and-leaf-plot new file mode 120000 index 0000000000..8a3d5cbab0 --- /dev/null +++ b/Lang/Prolog/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Prolog \ No newline at end of file diff --git a/Lang/Prolog/String-concatenation b/Lang/Prolog/String-concatenation new file mode 120000 index 0000000000..47d572fb22 --- /dev/null +++ b/Lang/Prolog/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Thue-Morse b/Lang/Prolog/Thue-Morse new file mode 120000 index 0000000000..c42ff58a18 --- /dev/null +++ b/Lang/Prolog/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Topswops b/Lang/Prolog/Topswops new file mode 120000 index 0000000000..20c5cfbba8 --- /dev/null +++ b/Lang/Prolog/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Trabb-Pardo-Knuth-algorithm b/Lang/Prolog/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..dcd294e9ea --- /dev/null +++ b/Lang/Prolog/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Wireworld b/Lang/Prolog/Wireworld new file mode 120000 index 0000000000..b45eaa2601 --- /dev/null +++ b/Lang/Prolog/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Zero-to-the-zero-power b/Lang/Prolog/Zero-to-the-zero-power new file mode 120000 index 0000000000..5d3d1cb814 --- /dev/null +++ b/Lang/Prolog/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Prolog \ No newline at end of file diff --git a/Lang/Python/Ruth-Aaron-numbers b/Lang/Python/Ruth-Aaron-numbers new file mode 120000 index 0000000000..933b3d03bc --- /dev/null +++ b/Lang/Python/Ruth-Aaron-numbers @@ -0,0 +1 @@ +../../Task/Ruth-Aaron-numbers/Python \ No newline at end of file diff --git a/Lang/QB64/Trabb-Pardo-Knuth-algorithm b/Lang/QB64/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..bd61960412 --- /dev/null +++ b/Lang/QB64/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/QB64 \ No newline at end of file diff --git a/Lang/R/Angles-geometric-normalization-and-conversion b/Lang/R/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..d1e56f507e --- /dev/null +++ b/Lang/R/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/R \ No newline at end of file diff --git a/Lang/R/CUSIP b/Lang/R/CUSIP new file mode 120000 index 0000000000..e43a376539 --- /dev/null +++ b/Lang/R/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/R \ No newline at end of file diff --git a/Lang/R/Continued-fraction b/Lang/R/Continued-fraction new file mode 120000 index 0000000000..8e8db83048 --- /dev/null +++ b/Lang/R/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/R \ No newline at end of file diff --git a/Lang/R/Cramers-rule b/Lang/R/Cramers-rule new file mode 120000 index 0000000000..839896c59f --- /dev/null +++ b/Lang/R/Cramers-rule @@ -0,0 +1 @@ +../../Task/Cramers-rule/R \ No newline at end of file diff --git a/Lang/R/Curzon-numbers b/Lang/R/Curzon-numbers new file mode 120000 index 0000000000..a381ff9f97 --- /dev/null +++ b/Lang/R/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/R \ No newline at end of file diff --git a/Lang/R/Dijkstras-algorithm b/Lang/R/Dijkstras-algorithm new file mode 120000 index 0000000000..3bff2fae1d --- /dev/null +++ b/Lang/R/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/R \ No newline at end of file diff --git a/Lang/R/Execute-HQ9+ b/Lang/R/Execute-HQ9+ new file mode 120000 index 0000000000..0972c0bb4f --- /dev/null +++ b/Lang/R/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/R \ No newline at end of file diff --git a/Lang/R/Factorial-primes b/Lang/R/Factorial-primes new file mode 120000 index 0000000000..90b75c9d38 --- /dev/null +++ b/Lang/R/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/R \ No newline at end of file diff --git a/Lang/R/Fibonacci-n-step-number-sequences b/Lang/R/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..1cf227761a --- /dev/null +++ b/Lang/R/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/R \ No newline at end of file diff --git a/Lang/R/Flipping-bits-game b/Lang/R/Flipping-bits-game new file mode 120000 index 0000000000..45f9cba067 --- /dev/null +++ b/Lang/R/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/R \ No newline at end of file diff --git a/Lang/R/Floyd-Warshall-algorithm b/Lang/R/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..f0f7534bc6 --- /dev/null +++ b/Lang/R/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/R \ No newline at end of file diff --git a/Lang/R/Fractran b/Lang/R/Fractran new file mode 120000 index 0000000000..4684d03d23 --- /dev/null +++ b/Lang/R/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/R \ No newline at end of file diff --git a/Lang/R/Giuga-numbers b/Lang/R/Giuga-numbers new file mode 120000 index 0000000000..e45399fcf4 --- /dev/null +++ b/Lang/R/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/R \ No newline at end of file diff --git a/Lang/R/Greedy-algorithm-for-Egyptian-fractions b/Lang/R/Greedy-algorithm-for-Egyptian-fractions new file mode 120000 index 0000000000..142b97c38d --- /dev/null +++ b/Lang/R/Greedy-algorithm-for-Egyptian-fractions @@ -0,0 +1 @@ +../../Task/Greedy-algorithm-for-Egyptian-fractions/R \ No newline at end of file diff --git a/Lang/R/Humble-numbers b/Lang/R/Humble-numbers new file mode 120000 index 0000000000..66447beec9 --- /dev/null +++ b/Lang/R/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/R \ No newline at end of file diff --git a/Lang/R/M-bius-function b/Lang/R/M-bius-function new file mode 120000 index 0000000000..54d202ad87 --- /dev/null +++ b/Lang/R/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/R \ No newline at end of file diff --git a/Lang/R/Parse-an-IP-Address b/Lang/R/Parse-an-IP-Address new file mode 120000 index 0000000000..9f23986592 --- /dev/null +++ b/Lang/R/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/R \ No newline at end of file diff --git a/Lang/R/Rename-a-file b/Lang/R/Rename-a-file new file mode 120000 index 0000000000..d3214c3f95 --- /dev/null +++ b/Lang/R/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/R \ No newline at end of file diff --git a/Lang/R/Repunit-primes b/Lang/R/Repunit-primes new file mode 120000 index 0000000000..9ae6100164 --- /dev/null +++ b/Lang/R/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/R \ No newline at end of file diff --git a/Lang/R/Retrieve-and-search-chat-history b/Lang/R/Retrieve-and-search-chat-history new file mode 120000 index 0000000000..6f350b7b8c --- /dev/null +++ b/Lang/R/Retrieve-and-search-chat-history @@ -0,0 +1 @@ +../../Task/Retrieve-and-search-chat-history/R \ No newline at end of file diff --git a/Lang/R/Shoelace-formula-for-polygonal-area b/Lang/R/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..8e6ea3fcc6 --- /dev/null +++ b/Lang/R/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/R \ No newline at end of file diff --git a/Lang/R/Soloways-recurring-rainfall b/Lang/R/Soloways-recurring-rainfall new file mode 120000 index 0000000000..33b1f84311 --- /dev/null +++ b/Lang/R/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/R \ No newline at end of file diff --git a/Lang/R/Split-a-character-string-based-on-change-of-character b/Lang/R/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..16a92812f1 --- /dev/null +++ b/Lang/R/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/R \ No newline at end of file diff --git a/Lang/R/String-interpolation-included- b/Lang/R/String-interpolation-included- new file mode 120000 index 0000000000..f311002546 --- /dev/null +++ b/Lang/R/String-interpolation-included- @@ -0,0 +1 @@ +../../Task/String-interpolation-included-/R \ No newline at end of file diff --git a/Lang/R/String-matching b/Lang/R/String-matching new file mode 120000 index 0000000000..2461134ac0 --- /dev/null +++ b/Lang/R/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/R \ No newline at end of file diff --git a/Lang/R/Substring-Top-and-tail b/Lang/R/Substring-Top-and-tail new file mode 120000 index 0000000000..271cd3b15f --- /dev/null +++ b/Lang/R/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/R \ No newline at end of file diff --git a/Lang/R/The-Name-Game b/Lang/R/The-Name-Game new file mode 120000 index 0000000000..a5e981bf52 --- /dev/null +++ b/Lang/R/The-Name-Game @@ -0,0 +1 @@ +../../Task/The-Name-Game/R \ No newline at end of file diff --git a/Lang/R/Tonelli-Shanks-algorithm b/Lang/R/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..2ad48c9cd5 --- /dev/null +++ b/Lang/R/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/R \ No newline at end of file diff --git a/Lang/R/Wieferich-primes b/Lang/R/Wieferich-primes new file mode 120000 index 0000000000..1c103bdf36 --- /dev/null +++ b/Lang/R/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/R \ No newline at end of file diff --git a/Lang/R/Write-entire-file b/Lang/R/Write-entire-file new file mode 120000 index 0000000000..2972bb07fe --- /dev/null +++ b/Lang/R/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/R \ No newline at end of file diff --git a/Lang/REBOL/00-LANG.txt b/Lang/REBOL/00-LANG.txt index 0117c8198c..f5919f4e5a 100644 --- a/Lang/REBOL/00-LANG.txt +++ b/Lang/REBOL/00-LANG.txt @@ -1,3 +1,5 @@ {{stub}}{{language|REBOL |site=http://rebol.com}} -REBOL stands for Relative Expression Based Object Language. \ No newline at end of file +REBOL stands for Relative Expression Based Object Language. + +See also: [https://rosettacode.org/wiki/Category:Rebol Category:Rebol] \ No newline at end of file diff --git a/Lang/REBOL/9-billion-names-of-God-the-integer b/Lang/REBOL/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..d19b039600 --- /dev/null +++ b/Lang/REBOL/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Ackermann-function b/Lang/REBOL/Ackermann-function new file mode 120000 index 0000000000..bb556d5ce8 --- /dev/null +++ b/Lang/REBOL/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loop-over-multiple-arrays-simultaneously b/Lang/REBOL/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..509d196c87 --- /dev/null +++ b/Lang/REBOL/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Increment-loop-index-within-loop-body b/Lang/REBOL/Loops-Increment-loop-index-within-loop-body new file mode 120000 index 0000000000..1d1b2df2c6 --- /dev/null +++ b/Lang/REBOL/Loops-Increment-loop-index-within-loop-body @@ -0,0 +1 @@ +../../Task/Loops-Increment-loop-index-within-loop-body/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-With-multiple-ranges b/Lang/REBOL/Loops-With-multiple-ranges new file mode 120000 index 0000000000..bd25edb4b9 --- /dev/null +++ b/Lang/REBOL/Loops-With-multiple-ranges @@ -0,0 +1 @@ +../../Task/Loops-With-multiple-ranges/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Wrong-ranges b/Lang/REBOL/Loops-Wrong-ranges new file mode 120000 index 0000000000..a8f17c4209 --- /dev/null +++ b/Lang/REBOL/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Object-serialization b/Lang/REBOL/Object-serialization new file mode 120000 index 0000000000..71f73b27eb --- /dev/null +++ b/Lang/REBOL/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Polyspiral b/Lang/REBOL/Polyspiral new file mode 120000 index 0000000000..70a487676d --- /dev/null +++ b/Lang/REBOL/Polyspiral @@ -0,0 +1 @@ +../../Task/Polyspiral/REBOL \ No newline at end of file diff --git a/Lang/REBOL/SHA-1 b/Lang/REBOL/SHA-1 new file mode 120000 index 0000000000..b430af646a --- /dev/null +++ b/Lang/REBOL/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/REBOL \ No newline at end of file diff --git a/Lang/REBOL/SHA-256 b/Lang/REBOL/SHA-256 new file mode 120000 index 0000000000..b5f39ed805 --- /dev/null +++ b/Lang/REBOL/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Semordnilap b/Lang/REBOL/Semordnilap new file mode 120000 index 0000000000..fee60064bb --- /dev/null +++ b/Lang/REBOL/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/REBOL \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/00-LANG.txt b/Lang/RISC-V-Assembly/00-LANG.txt index f524ed95fb..6a2bfde754 100644 --- a/Lang/RISC-V-Assembly/00-LANG.txt +++ b/Lang/RISC-V-Assembly/00-LANG.txt @@ -1,4 +1,76 @@ {{language|RISC-V Assembly}}[https://riscv.org Risc-V] is an open source hardware instruction set architecture based on the principle of a '''R'''educed '''I'''nstruction '''S'''et '''C'''omputer. The project was started by the university of California, Berkeley in 2010. This site refers to the Risc-V assembly language. ([https://en.wikipedia.org/wiki/RISC-V#Software Wikipedia page]), Website: [https://riscv.org https://riscv.org]. +'''Riscv on raspberry pico 2''' + +A pico2 with the chip rp2335 contains 2 cores hazard3 with risc v assembly +it is possible to programm assembly riscv with the sdk C++ and a compiler riscv32-unknown-elf-as.exe + +It is also possible to programm without SDK but it is necessary to write functions for init +the clocks and to communicate for usb connexion. + +install under Windows11 (or see documentation raspberry py pico SDK) : + +Create main folder (ex : \pico2) + +install SDK C++ (see instructions in raspberry pi pico2 SDK documentation) + +install toolchaine under \Pico2\tools\bin from + +https://github.com/raspberrypi/pico-sdk-tools/releases/download/v2.0.0-2/riscv-toolchain-14-x64-win.zip + + +Create work folder (ex : \pico2\hello) + +Create file CMakeLists.txt (see instructions in raspberry pi pico2 SDK documentation) + +Create program hello.s with a editor + +Copy a file pico_sdk_import.cmake from \pico2\pico-sdk\external + +Create a folder build under \pico2\hello + +Go to this folder + +Compile program with : + + cmake -DPICO_PLATFORM=rp2350-riscv -DPICO_TOOLCHAIN_PATH=E:\Pico2\tools\bin -G "NMake Makefiles" .. + +and + nmake + +copy the file .uf2 to raspberry pico2 (see documentation raspberry pi pico2) + +Start serial connexion on host (ex: putty on windows11) + +Example CMakeLists.txt : + +cmake_minimum_required(VERSION 3.13) + +include(pico_sdk_import.cmake) + +project(hello C CXX ASM) + +set(CMAKE_C_STANDARD 11) + +set(CMAKE_CXX_STANDARD 17) + +pico_sdk_init() + +add_executable(hello +hello.s # pgm source assembly riscv +) + +target_link_libraries(hello pico_stdlib) + +pico_enable_stdio_usb(hello 1) + +pico_enable_stdio_uart(hello 0) + +pico_add_extra_outputs(hello) + +see source program on hello world rosetta code + +cmake -DPython3_EXECUTABLE=C:\Users\Vincent\AppData\Local\Microsoft\WindowsApps\python3.10.exe -DPICO_PLATFORM=rp2350-riscv -DPICO_TOOLCHAIN_PATH=E:\Pico2\tools\bin -DPICO_SDK_PATH=..\..\..\pico-sdk -G "NMake Makefiles" .. + [[Category:Assembler language]] [[Category:Assembly]] \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Address-of-a-variable b/Lang/RISC-V-Assembly/Address-of-a-variable new file mode 120000 index 0000000000..7e7b85f7fc --- /dev/null +++ b/Lang/RISC-V-Assembly/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Arithmetic-Integer b/Lang/RISC-V-Assembly/Arithmetic-Integer new file mode 120000 index 0000000000..41172f4754 --- /dev/null +++ b/Lang/RISC-V-Assembly/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Binary-digits b/Lang/RISC-V-Assembly/Binary-digits new file mode 120000 index 0000000000..45c4e871d7 --- /dev/null +++ b/Lang/RISC-V-Assembly/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Hello-world-Newbie b/Lang/RISC-V-Assembly/Hello-world-Newbie new file mode 120000 index 0000000000..5721ad4125 --- /dev/null +++ b/Lang/RISC-V-Assembly/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Include-a-file b/Lang/RISC-V-Assembly/Include-a-file new file mode 120000 index 0000000000..2742cb0a60 --- /dev/null +++ b/Lang/RISC-V-Assembly/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/Raku/Play-recorded-sounds b/Lang/Raku/Play-recorded-sounds new file mode 120000 index 0000000000..7d18ecbdee --- /dev/null +++ b/Lang/Raku/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/Raku \ No newline at end of file diff --git a/Lang/Red/Address-of-a-variable b/Lang/Red/Address-of-a-variable new file mode 120000 index 0000000000..81b5a1a171 --- /dev/null +++ b/Lang/Red/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Red \ No newline at end of file diff --git a/Lang/Red/Arithmetic-Integer b/Lang/Red/Arithmetic-Integer new file mode 120000 index 0000000000..cb3f74d046 --- /dev/null +++ b/Lang/Red/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Red \ No newline at end of file diff --git a/Lang/Red/Arithmetic-evaluation b/Lang/Red/Arithmetic-evaluation new file mode 120000 index 0000000000..c6c5c304b5 --- /dev/null +++ b/Lang/Red/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Red \ No newline at end of file diff --git a/Lang/Red/Calendar b/Lang/Red/Calendar new file mode 120000 index 0000000000..3283fd5906 --- /dev/null +++ b/Lang/Red/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Red \ No newline at end of file diff --git a/Lang/Red/Calendar---for-REAL-programmers b/Lang/Red/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..e0db1bd24f --- /dev/null +++ b/Lang/Red/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Red \ No newline at end of file diff --git a/Lang/Red/Currying b/Lang/Red/Currying new file mode 120000 index 0000000000..a40d4bf838 --- /dev/null +++ b/Lang/Red/Currying @@ -0,0 +1 @@ +../../Task/Currying/Red \ No newline at end of file diff --git a/Lang/Red/Five-weekends b/Lang/Red/Five-weekends new file mode 120000 index 0000000000..4b364097a6 --- /dev/null +++ b/Lang/Red/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Red \ No newline at end of file diff --git a/Lang/Red/Logical-operations b/Lang/Red/Logical-operations new file mode 120000 index 0000000000..b02eaed36f --- /dev/null +++ b/Lang/Red/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Red \ No newline at end of file diff --git a/Lang/Red/Parsing-RPN-calculator-algorithm b/Lang/Red/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..f68a7bf5c6 --- /dev/null +++ b/Lang/Red/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Red \ No newline at end of file diff --git a/Lang/Red/Parsing-RPN-to-infix-conversion b/Lang/Red/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..27fb99e707 --- /dev/null +++ b/Lang/Red/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Red \ No newline at end of file diff --git a/Lang/Red/Parsing-Shunting-yard-algorithm b/Lang/Red/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..64583c9508 --- /dev/null +++ b/Lang/Red/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Red \ No newline at end of file diff --git a/Lang/Red/Towers-of-Hanoi b/Lang/Red/Towers-of-Hanoi new file mode 120000 index 0000000000..112b276dee --- /dev/null +++ b/Lang/Red/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Red \ No newline at end of file diff --git a/Lang/Refal/Tokenize-a-string b/Lang/Refal/Tokenize-a-string new file mode 120000 index 0000000000..f8ac7459de --- /dev/null +++ b/Lang/Refal/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Refal \ No newline at end of file diff --git a/Lang/Rhombus/00-LANG.txt b/Lang/Rhombus/00-LANG.txt new file mode 100644 index 0000000000..ef9932595f --- /dev/null +++ b/Lang/Rhombus/00-LANG.txt @@ -0,0 +1,5 @@ +{{language +|exec=both +|gc=yes +|site=https://rhombus-lang.org/ +}} \ No newline at end of file diff --git a/Lang/Rhombus/00-META.yaml b/Lang/Rhombus/00-META.yaml new file mode 100644 index 0000000000..732b96d2eb --- /dev/null +++ b/Lang/Rhombus/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Rhombus diff --git a/Lang/Rhombus/99-bottles-of-beer b/Lang/Rhombus/99-bottles-of-beer new file mode 120000 index 0000000000..bcb9ee7049 --- /dev/null +++ b/Lang/Rhombus/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Arbitrary-precision-integers-included- b/Lang/Rhombus/Arbitrary-precision-integers-included- new file mode 120000 index 0000000000..31558e19d7 --- /dev/null +++ b/Lang/Rhombus/Arbitrary-precision-integers-included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers-included-/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Caesar-cipher b/Lang/Rhombus/Caesar-cipher new file mode 120000 index 0000000000..dd9f5453ed --- /dev/null +++ b/Lang/Rhombus/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Factorial b/Lang/Rhombus/Factorial new file mode 120000 index 0000000000..92b62c830f --- /dev/null +++ b/Lang/Rhombus/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Fibonacci-sequence b/Lang/Rhombus/Fibonacci-sequence new file mode 120000 index 0000000000..d496e8a0b2 --- /dev/null +++ b/Lang/Rhombus/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/FizzBuzz b/Lang/Rhombus/FizzBuzz new file mode 120000 index 0000000000..5740514b72 --- /dev/null +++ b/Lang/Rhombus/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Guess-the-number-With-feedback b/Lang/Rhombus/Guess-the-number-With-feedback new file mode 120000 index 0000000000..c51dd719ba --- /dev/null +++ b/Lang/Rhombus/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Hello-world-Text b/Lang/Rhombus/Hello-world-Text new file mode 120000 index 0000000000..11fb03859d --- /dev/null +++ b/Lang/Rhombus/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Inheritance-Single b/Lang/Rhombus/Inheritance-Single new file mode 120000 index 0000000000..2f478862d8 --- /dev/null +++ b/Lang/Rhombus/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Polymorphism b/Lang/Rhombus/Polymorphism new file mode 120000 index 0000000000..a5540935b5 --- /dev/null +++ b/Lang/Rhombus/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Rhombus \ No newline at end of file diff --git a/Lang/Rhombus/Rot-13 b/Lang/Rhombus/Rot-13 new file mode 120000 index 0000000000..369226ff2f --- /dev/null +++ b/Lang/Rhombus/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Rhombus \ No newline at end of file diff --git a/Lang/Ring/Compare-a-list-of-strings b/Lang/Ring/Compare-a-list-of-strings new file mode 120000 index 0000000000..308f7db9af --- /dev/null +++ b/Lang/Ring/Compare-a-list-of-strings @@ -0,0 +1 @@ +../../Task/Compare-a-list-of-strings/Ring \ No newline at end of file diff --git a/Lang/Ring/Wagstaff-primes b/Lang/Ring/Wagstaff-primes new file mode 120000 index 0000000000..877433f537 --- /dev/null +++ b/Lang/Ring/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Ring \ No newline at end of file diff --git a/Lang/Run-BASIC/Josephus-problem b/Lang/Run-BASIC/Josephus-problem new file mode 120000 index 0000000000..d5ce7e543e --- /dev/null +++ b/Lang/Run-BASIC/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/Break-OO-privacy b/Lang/Rust/Break-OO-privacy new file mode 120000 index 0000000000..37b6e0d417 --- /dev/null +++ b/Lang/Rust/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Rust \ No newline at end of file diff --git a/Lang/Rust/Camel-case-and-snake-case b/Lang/Rust/Camel-case-and-snake-case new file mode 120000 index 0000000000..5c92d90b28 --- /dev/null +++ b/Lang/Rust/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Rust \ No newline at end of file diff --git a/Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..7e0955d429 --- /dev/null +++ b/Lang/Rust/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Rust \ No newline at end of file diff --git a/Lang/Rust/Cyclops-numbers b/Lang/Rust/Cyclops-numbers new file mode 120000 index 0000000000..044bb62e43 --- /dev/null +++ b/Lang/Rust/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Deconvolution-1D b/Lang/Rust/Deconvolution-1D new file mode 120000 index 0000000000..d02a914ea3 --- /dev/null +++ b/Lang/Rust/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Rust \ No newline at end of file diff --git a/Lang/Rust/Deconvolution-2D+ b/Lang/Rust/Deconvolution-2D+ new file mode 120000 index 0000000000..4b9cb470ba --- /dev/null +++ b/Lang/Rust/Deconvolution-2D+ @@ -0,0 +1 @@ +../../Task/Deconvolution-2D+/Rust \ No newline at end of file diff --git a/Lang/Rust/Determine-if-two-triangles-overlap b/Lang/Rust/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..2bc1e5e063 --- /dev/null +++ b/Lang/Rust/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/Rust \ No newline at end of file diff --git a/Lang/Rust/Duffinian-numbers b/Lang/Rust/Duffinian-numbers new file mode 120000 index 0000000000..5a84e9b8ff --- /dev/null +++ b/Lang/Rust/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Elliptic-curve-arithmetic b/Lang/Rust/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..cb1c49b6dd --- /dev/null +++ b/Lang/Rust/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/Rust \ No newline at end of file diff --git a/Lang/Rust/Faulhabers-triangle b/Lang/Rust/Faulhabers-triangle new file mode 120000 index 0000000000..49b5537877 --- /dev/null +++ b/Lang/Rust/Faulhabers-triangle @@ -0,0 +1 @@ +../../Task/Faulhabers-triangle/Rust \ No newline at end of file diff --git a/Lang/Rust/Fractran b/Lang/Rust/Fractran new file mode 120000 index 0000000000..46ed1ab96e --- /dev/null +++ b/Lang/Rust/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Rust \ No newline at end of file diff --git a/Lang/Rust/Humble-numbers b/Lang/Rust/Humble-numbers new file mode 120000 index 0000000000..001b631312 --- /dev/null +++ b/Lang/Rust/Humble-numbers @@ -0,0 +1 @@ +../../Task/Humble-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Knapsack-problem-Bounded b/Lang/Rust/Knapsack-problem-Bounded new file mode 120000 index 0000000000..db57c7551f --- /dev/null +++ b/Lang/Rust/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Rust \ No newline at end of file diff --git a/Lang/Rust/Mayan-calendar b/Lang/Rust/Mayan-calendar new file mode 120000 index 0000000000..8da8002279 --- /dev/null +++ b/Lang/Rust/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/Rust \ No newline at end of file diff --git a/Lang/Rust/Meissel-Mertens-constant b/Lang/Rust/Meissel-Mertens-constant new file mode 120000 index 0000000000..30f216e193 --- /dev/null +++ b/Lang/Rust/Meissel-Mertens-constant @@ -0,0 +1 @@ +../../Task/Meissel-Mertens-constant/Rust \ No newline at end of file diff --git a/Lang/Rust/Modular-arithmetic b/Lang/Rust/Modular-arithmetic new file mode 120000 index 0000000000..bf3b8fce76 --- /dev/null +++ b/Lang/Rust/Modular-arithmetic @@ -0,0 +1 @@ +../../Task/Modular-arithmetic/Rust \ No newline at end of file diff --git a/Lang/Rust/Multiple-regression b/Lang/Rust/Multiple-regression new file mode 120000 index 0000000000..84425ee458 --- /dev/null +++ b/Lang/Rust/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Rust \ No newline at end of file diff --git a/Lang/Rust/Ramanujan-primes-twins b/Lang/Rust/Ramanujan-primes-twins new file mode 120000 index 0000000000..ec360cedbc --- /dev/null +++ b/Lang/Rust/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/Rust \ No newline at end of file diff --git a/Lang/Rust/Singleton b/Lang/Rust/Singleton new file mode 120000 index 0000000000..480988c162 --- /dev/null +++ b/Lang/Rust/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Rust \ No newline at end of file diff --git a/Lang/Rust/Sokoban b/Lang/Rust/Sokoban new file mode 120000 index 0000000000..57d1bc73b3 --- /dev/null +++ b/Lang/Rust/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Rust \ No newline at end of file diff --git a/Lang/Rust/Substitution-cipher b/Lang/Rust/Substitution-cipher new file mode 120000 index 0000000000..aa3ad1011d --- /dev/null +++ b/Lang/Rust/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/Rust \ No newline at end of file diff --git a/Lang/Rust/Tree-datastructures b/Lang/Rust/Tree-datastructures new file mode 120000 index 0000000000..37b567712c --- /dev/null +++ b/Lang/Rust/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/Rust \ No newline at end of file diff --git a/Lang/Rust/UPC b/Lang/Rust/UPC new file mode 120000 index 0000000000..775faf96be --- /dev/null +++ b/Lang/Rust/UPC @@ -0,0 +1 @@ +../../Task/UPC/Rust \ No newline at end of file diff --git a/Lang/Rust/War-card-game b/Lang/Rust/War-card-game new file mode 120000 index 0000000000..bc45c42250 --- /dev/null +++ b/Lang/Rust/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Rust \ No newline at end of file diff --git a/Lang/S-BASIC/Sorting-algorithms-Insertion-sort b/Lang/S-BASIC/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..60391d0e75 --- /dev/null +++ b/Lang/S-BASIC/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/S-BASIC \ No newline at end of file diff --git a/Lang/SETL/Monte-Carlo-methods b/Lang/SETL/Monte-Carlo-methods new file mode 120000 index 0000000000..da6adaf82b --- /dev/null +++ b/Lang/SETL/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/SETL \ No newline at end of file diff --git a/Lang/SETL/Tokenize-a-string b/Lang/SETL/Tokenize-a-string new file mode 120000 index 0000000000..bd55474aef --- /dev/null +++ b/Lang/SETL/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/SETL \ No newline at end of file diff --git a/Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..03b359aab4 --- /dev/null +++ b/Lang/Scala/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Scala \ No newline at end of file diff --git a/Lang/Scala/Tonelli-Shanks-algorithm b/Lang/Scala/Tonelli-Shanks-algorithm new file mode 120000 index 0000000000..a29f0a9b6f --- /dev/null +++ b/Lang/Scala/Tonelli-Shanks-algorithm @@ -0,0 +1 @@ +../../Task/Tonelli-Shanks-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scala/UPC b/Lang/Scala/UPC new file mode 120000 index 0000000000..bc3faec2ef --- /dev/null +++ b/Lang/Scala/UPC @@ -0,0 +1 @@ +../../Task/UPC/Scala \ No newline at end of file diff --git a/Lang/Scheme/Own-digits-power-sum b/Lang/Scheme/Own-digits-power-sum new file mode 120000 index 0000000000..0897a09d02 --- /dev/null +++ b/Lang/Scheme/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Pick-random-element b/Lang/Scheme/Pick-random-element new file mode 120000 index 0000000000..5745ea287d --- /dev/null +++ b/Lang/Scheme/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Scheme \ No newline at end of file diff --git a/Lang/SequenceL/00-LANG.txt b/Lang/SequenceL/00-LANG.txt index 3c3098bf74..5e5a95101f 100644 --- a/Lang/SequenceL/00-LANG.txt +++ b/Lang/SequenceL/00-LANG.txt @@ -3,7 +3,7 @@ |strength=strong |safety=safe |checking=static -|site=http://sequencel.com +|site= |tags=sequencel |hopl=no}} {{language programming paradigm|Declarative}} diff --git a/Lang/Swift/AVL-tree b/Lang/Swift/AVL-tree new file mode 120000 index 0000000000..ff46aae38e --- /dev/null +++ b/Lang/Swift/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/Swift \ No newline at end of file diff --git a/Lang/Swift/Boyer-Moore-string-search b/Lang/Swift/Boyer-Moore-string-search new file mode 120000 index 0000000000..d0d21c21e5 --- /dev/null +++ b/Lang/Swift/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Swift \ No newline at end of file diff --git a/Lang/Swift/Chaocipher b/Lang/Swift/Chaocipher new file mode 120000 index 0000000000..6e9ab31392 --- /dev/null +++ b/Lang/Swift/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/Swift \ No newline at end of file diff --git a/Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..bfa2341e33 --- /dev/null +++ b/Lang/Swift/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Swift \ No newline at end of file diff --git a/Lang/Swift/Floyd-Warshall-algorithm b/Lang/Swift/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..d1366dce22 --- /dev/null +++ b/Lang/Swift/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/Swift \ No newline at end of file diff --git a/Lang/Swift/K-d-tree b/Lang/Swift/K-d-tree new file mode 120000 index 0000000000..a4758e806b --- /dev/null +++ b/Lang/Swift/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Swift \ No newline at end of file diff --git a/Lang/Swift/Parse-an-IP-Address b/Lang/Swift/Parse-an-IP-Address new file mode 120000 index 0000000000..b157f3f9a2 --- /dev/null +++ b/Lang/Swift/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Swift \ No newline at end of file diff --git a/Lang/TAV/00-LANG.txt b/Lang/TAV/00-LANG.txt new file mode 100644 index 0000000000..bb9d8890a2 --- /dev/null +++ b/Lang/TAV/00-LANG.txt @@ -0,0 +1,46 @@ +{{language|TAV +|site=https://tavpl.de +|untyped=yes +|exec=machine +|gc=no +|parampass=reference +|checking=dynamic +|safety=safe +}} +{{language programming paradigm|Procedural}} +{{CompileOnline}} + +'''TAV''' is the '''terse and verbose''' +language that borrows from [[Python]], Stage2, [[Genie]] and more. + +Its most outstanding feature is the use of templates for function calls instead of the +traditional function_name(parameter, parameter, ...) form. +Matched parenthesis are consequently rarely necessary. + +Summary of important points: + +* C precompiler, should work on any system with a reasonable C compiler +* Block structuring by indentation, like in Python; line oriented +* No keywords in the core language, only symbols (i.e. bigraphs) +* Variables are of any kind (type) dynamically; no declarations necessary +* Function definition and calls by word sequences with interspersed parameters, often no parenthesis needed +* Maps (dictionaries) with all kinds of keys (except floating-point numbers) +* Rows (arrays) if the keys are dense integers, dynamically expanding +* Arbitrary precision integer numbers +* Dynamic Unicode strings +* Fields for extra data in rows and maps +* Attributes for information about an item +* Fault items for reliable error handling +* Reference counting avoids unsolicited delays for garbage-collection +* Basic support for object-oriented programming (no inheritance) +* Discretionary type system specified, but not yet tested +* Publication syntax with common English keywords instead of symbols +* Bindings to SDL, Cairo and GTK (proof-of-concept level) + +Many examples can be run via copy and paste in the Playground. + +Because there are no keywords and rarely nested parenthesis (of any kind), +syntax highlighting is not used. + +==Links== +*[[https://tavpl.de/TAV-Online TAV Online Playground]] \ No newline at end of file diff --git a/Lang/TAV/00-META.yaml b/Lang/TAV/00-META.yaml new file mode 100644 index 0000000000..94650f22a2 --- /dev/null +++ b/Lang/TAV/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:TAV diff --git a/Lang/TAV/A+B b/Lang/TAV/A+B new file mode 120000 index 0000000000..a5e97665e3 --- /dev/null +++ b/Lang/TAV/A+B @@ -0,0 +1 @@ +../../Task/A+B/TAV \ No newline at end of file diff --git a/Lang/TAV/Ackermann-function b/Lang/TAV/Ackermann-function new file mode 120000 index 0000000000..237de07217 --- /dev/null +++ b/Lang/TAV/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/TAV \ No newline at end of file diff --git a/Lang/TAV/Anagrams b/Lang/TAV/Anagrams new file mode 120000 index 0000000000..335a62bd1c --- /dev/null +++ b/Lang/TAV/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/TAV \ No newline at end of file diff --git a/Lang/TAV/Arithmetic-Integer b/Lang/TAV/Arithmetic-Integer new file mode 120000 index 0000000000..b9d994e37f --- /dev/null +++ b/Lang/TAV/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/TAV \ No newline at end of file diff --git a/Lang/TAV/Array-concatenation b/Lang/TAV/Array-concatenation new file mode 120000 index 0000000000..a1b0d9260d --- /dev/null +++ b/Lang/TAV/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/TAV \ No newline at end of file diff --git a/Lang/TAV/Array-length b/Lang/TAV/Array-length new file mode 120000 index 0000000000..0d849f41e8 --- /dev/null +++ b/Lang/TAV/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/TAV \ No newline at end of file diff --git a/Lang/TAV/Associative-array-Iteration b/Lang/TAV/Associative-array-Iteration new file mode 120000 index 0000000000..48bdb805ad --- /dev/null +++ b/Lang/TAV/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/TAV \ No newline at end of file diff --git a/Lang/TAV/Averages-Root-mean-square b/Lang/TAV/Averages-Root-mean-square new file mode 120000 index 0000000000..75f73fbdb8 --- /dev/null +++ b/Lang/TAV/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/TAV \ No newline at end of file diff --git a/Lang/TAV/Character-codes b/Lang/TAV/Character-codes new file mode 120000 index 0000000000..46e37f6e83 --- /dev/null +++ b/Lang/TAV/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/TAV \ No newline at end of file diff --git a/Lang/TAV/Command-line-arguments b/Lang/TAV/Command-line-arguments new file mode 120000 index 0000000000..72fc191937 --- /dev/null +++ b/Lang/TAV/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/TAV \ No newline at end of file diff --git a/Lang/TAV/Conditional-structures b/Lang/TAV/Conditional-structures new file mode 120000 index 0000000000..bf797da6e6 --- /dev/null +++ b/Lang/TAV/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/TAV \ No newline at end of file diff --git a/Lang/TAV/Copy-a-string b/Lang/TAV/Copy-a-string new file mode 120000 index 0000000000..3ca111af72 --- /dev/null +++ b/Lang/TAV/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Create-a-two-dimensional-array-at-runtime b/Lang/TAV/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..ec0fae01dd --- /dev/null +++ b/Lang/TAV/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/TAV \ No newline at end of file diff --git a/Lang/TAV/Empty-string b/Lang/TAV/Empty-string new file mode 120000 index 0000000000..c001916e31 --- /dev/null +++ b/Lang/TAV/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Factorial b/Lang/TAV/Factorial new file mode 120000 index 0000000000..005136367e --- /dev/null +++ b/Lang/TAV/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/TAV \ No newline at end of file diff --git a/Lang/TAV/Fibonacci-sequence b/Lang/TAV/Fibonacci-sequence new file mode 120000 index 0000000000..e65f13e72b --- /dev/null +++ b/Lang/TAV/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/TAV \ No newline at end of file diff --git a/Lang/TAV/Formatted-numeric-output b/Lang/TAV/Formatted-numeric-output new file mode 120000 index 0000000000..efbc60523a --- /dev/null +++ b/Lang/TAV/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/TAV \ No newline at end of file diff --git a/Lang/TAV/Greatest-element-of-a-list b/Lang/TAV/Greatest-element-of-a-list new file mode 120000 index 0000000000..b4f81674a0 --- /dev/null +++ b/Lang/TAV/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/TAV \ No newline at end of file diff --git a/Lang/TAV/Guess-the-number-With-feedback b/Lang/TAV/Guess-the-number-With-feedback new file mode 120000 index 0000000000..5779e4d532 --- /dev/null +++ b/Lang/TAV/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/TAV \ No newline at end of file diff --git a/Lang/TAV/HTTPS b/Lang/TAV/HTTPS new file mode 120000 index 0000000000..3b5c7b8988 --- /dev/null +++ b/Lang/TAV/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/TAV \ No newline at end of file diff --git a/Lang/TAV/Halt-and-catch-fire b/Lang/TAV/Halt-and-catch-fire new file mode 120000 index 0000000000..802c4aa7b1 --- /dev/null +++ b/Lang/TAV/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/TAV \ No newline at end of file diff --git a/Lang/TAV/Hello-world-Graphical b/Lang/TAV/Hello-world-Graphical new file mode 120000 index 0000000000..5207716bc0 --- /dev/null +++ b/Lang/TAV/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/TAV \ No newline at end of file diff --git a/Lang/TAV/Hello-world-Text b/Lang/TAV/Hello-world-Text new file mode 120000 index 0000000000..3fd6788564 --- /dev/null +++ b/Lang/TAV/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/TAV \ No newline at end of file diff --git a/Lang/TAV/Letter-frequency b/Lang/TAV/Letter-frequency new file mode 120000 index 0000000000..891b699844 --- /dev/null +++ b/Lang/TAV/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/TAV \ No newline at end of file diff --git a/Lang/TAV/Loop-over-multiple-arrays-simultaneously b/Lang/TAV/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..b6133fd1e3 --- /dev/null +++ b/Lang/TAV/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Break b/Lang/TAV/Loops-Break new file mode 120000 index 0000000000..9576a14c29 --- /dev/null +++ b/Lang/TAV/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Do-while b/Lang/TAV/Loops-Do-while new file mode 120000 index 0000000000..1fc4e33872 --- /dev/null +++ b/Lang/TAV/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Downward-for b/Lang/TAV/Loops-Downward-for new file mode 120000 index 0000000000..414c0842ce --- /dev/null +++ b/Lang/TAV/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-For b/Lang/TAV/Loops-For new file mode 120000 index 0000000000..b5f2be83c7 --- /dev/null +++ b/Lang/TAV/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-Infinite b/Lang/TAV/Loops-Infinite new file mode 120000 index 0000000000..6ab04989e3 --- /dev/null +++ b/Lang/TAV/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-N-plus-one-half b/Lang/TAV/Loops-N-plus-one-half new file mode 120000 index 0000000000..eaeea87dec --- /dev/null +++ b/Lang/TAV/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/TAV \ No newline at end of file diff --git a/Lang/TAV/Loops-While b/Lang/TAV/Loops-While new file mode 120000 index 0000000000..b408169718 --- /dev/null +++ b/Lang/TAV/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/TAV \ No newline at end of file diff --git a/Lang/TAV/Multiplication-tables b/Lang/TAV/Multiplication-tables new file mode 120000 index 0000000000..294070cfc4 --- /dev/null +++ b/Lang/TAV/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/TAV \ No newline at end of file diff --git a/Lang/TAV/Ordered-words b/Lang/TAV/Ordered-words new file mode 120000 index 0000000000..1dd34f0734 --- /dev/null +++ b/Lang/TAV/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/TAV \ No newline at end of file diff --git a/Lang/TAV/Permutations b/Lang/TAV/Permutations new file mode 120000 index 0000000000..c61f5ead43 --- /dev/null +++ b/Lang/TAV/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/TAV \ No newline at end of file diff --git a/Lang/TAV/Real-constants-and-functions b/Lang/TAV/Real-constants-and-functions new file mode 120000 index 0000000000..074b803009 --- /dev/null +++ b/Lang/TAV/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/TAV \ No newline at end of file diff --git a/Lang/TAV/Reverse-a-string b/Lang/TAV/Reverse-a-string new file mode 120000 index 0000000000..ded0969ffb --- /dev/null +++ b/Lang/TAV/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Semordnilap b/Lang/TAV/Semordnilap new file mode 120000 index 0000000000..2269a5f472 --- /dev/null +++ b/Lang/TAV/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/TAV \ No newline at end of file diff --git a/Lang/TAV/Simple-windowed-application b/Lang/TAV/Simple-windowed-application new file mode 120000 index 0000000000..16b1926606 --- /dev/null +++ b/Lang/TAV/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/TAV \ No newline at end of file diff --git a/Lang/TAV/Stack b/Lang/TAV/Stack new file mode 120000 index 0000000000..a05bead248 --- /dev/null +++ b/Lang/TAV/Stack @@ -0,0 +1 @@ +../../Task/Stack/TAV \ No newline at end of file diff --git a/Lang/TAV/String-length b/Lang/TAV/String-length new file mode 120000 index 0000000000..6374cb4fac --- /dev/null +++ b/Lang/TAV/String-length @@ -0,0 +1 @@ +../../Task/String-length/TAV \ No newline at end of file diff --git a/Lang/TAV/Tic-tac-toe b/Lang/TAV/Tic-tac-toe new file mode 120000 index 0000000000..c75d3a40ab --- /dev/null +++ b/Lang/TAV/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/TAV \ No newline at end of file diff --git a/Lang/TAV/Tokenize-a-string b/Lang/TAV/Tokenize-a-string new file mode 120000 index 0000000000..8b4118dfbe --- /dev/null +++ b/Lang/TAV/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/TAV \ No newline at end of file diff --git a/Lang/TAV/Window-creation b/Lang/TAV/Window-creation new file mode 120000 index 0000000000..83a0431016 --- /dev/null +++ b/Lang/TAV/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/TAV \ No newline at end of file diff --git a/Lang/TAV/Word-frequency b/Lang/TAV/Word-frequency new file mode 120000 index 0000000000..569f86daf5 --- /dev/null +++ b/Lang/TAV/Word-frequency @@ -0,0 +1 @@ +../../Task/Word-frequency/TAV \ No newline at end of file diff --git a/Lang/Tcl/M-bius-function b/Lang/Tcl/M-bius-function new file mode 120000 index 0000000000..1c7ccdef59 --- /dev/null +++ b/Lang/Tcl/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Tcl \ No newline at end of file diff --git a/Lang/Ursalang/Loops-Break b/Lang/Ursalang/Loops-Break new file mode 120000 index 0000000000..9956e0ecbe --- /dev/null +++ b/Lang/Ursalang/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Ursalang \ No newline at end of file diff --git a/Lang/Ursalang/Loops-While b/Lang/Ursalang/Loops-While new file mode 120000 index 0000000000..45dc0e4ade --- /dev/null +++ b/Lang/Ursalang/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Ursalang \ No newline at end of file diff --git a/Lang/V-(Vlang)/Compile-time-calculation b/Lang/V-(Vlang)/Compile-time-calculation new file mode 120000 index 0000000000..1ec9e378fa --- /dev/null +++ b/Lang/V-(Vlang)/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Inheritance-Multiple b/Lang/V-(Vlang)/Inheritance-Multiple new file mode 120000 index 0000000000..5c8421d069 --- /dev/null +++ b/Lang/V-(Vlang)/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Inheritance-Single b/Lang/V-(Vlang)/Inheritance-Single new file mode 120000 index 0000000000..e9a1dd6d9f --- /dev/null +++ b/Lang/V-(Vlang)/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Metaprogramming b/Lang/V-(Vlang)/Metaprogramming new file mode 120000 index 0000000000..6b8564d95e --- /dev/null +++ b/Lang/V-(Vlang)/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/V-(Vlang) \ No newline at end of file diff --git a/Lang/Vyxal/00-LANG.txt b/Lang/Vyxal/00-LANG.txt new file mode 100644 index 0000000000..0acceafc9b --- /dev/null +++ b/Lang/Vyxal/00-LANG.txt @@ -0,0 +1,3 @@ +{{language|Vyxal}} + +Vyxal is an esoteric golfing language designed to make code golf challenges fun, and to allow code golfers to win said challenges. \ No newline at end of file diff --git a/Lang/Vyxal/00-META.yaml b/Lang/Vyxal/00-META.yaml new file mode 100644 index 0000000000..a5968dda5e --- /dev/null +++ b/Lang/Vyxal/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Vyxal diff --git a/Lang/Vyxal/Factorial b/Lang/Vyxal/Factorial new file mode 120000 index 0000000000..1cdfde0f4b --- /dev/null +++ b/Lang/Vyxal/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Vyxal \ No newline at end of file diff --git a/Lang/Vyxal/FizzBuzz b/Lang/Vyxal/FizzBuzz new file mode 120000 index 0000000000..22964032ea --- /dev/null +++ b/Lang/Vyxal/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Vyxal \ No newline at end of file diff --git a/Lang/XBasic/AKS-test-for-primes b/Lang/XBasic/AKS-test-for-primes new file mode 120000 index 0000000000..dcd18f7155 --- /dev/null +++ b/Lang/XBasic/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/XBasic \ No newline at end of file diff --git a/Lang/XBasic/Josephus-problem b/Lang/XBasic/Josephus-problem new file mode 120000 index 0000000000..425d14bd16 --- /dev/null +++ b/Lang/XBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/XBasic \ No newline at end of file diff --git a/Lang/XPL0/AKS-test-for-primes b/Lang/XPL0/AKS-test-for-primes new file mode 120000 index 0000000000..16474e53df --- /dev/null +++ b/Lang/XPL0/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Cistercian-numerals b/Lang/XPL0/Cistercian-numerals new file mode 120000 index 0000000000..c2ce89db06 --- /dev/null +++ b/Lang/XPL0/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/XPL0 \ No newline at end of file diff --git a/Lang/YAMLScript/00-LANG.txt b/Lang/YAMLScript/00-LANG.txt index a35f9dca7d..53f8a21c4a 100644 --- a/Lang/YAMLScript/00-LANG.txt +++ b/Lang/YAMLScript/00-LANG.txt @@ -4,18 +4,23 @@ {{language programming paradigm|hosted}} {{implementation|Lisp}} -'''[https://yamlscript.org YS (aka YAMLScript)]''' is a new programming language that uses [https://yaml.org/ YAML] as its syntax. It is a complete, functional, general purpose language, but can also be easily embedded in YAML files to make them dynamic at load time. Most existing YAML files and all JSON files are already valid YS programs. +'''[https://yamlscript.org YS (pronounced "wise", aka YAMLScript)]''' is a new programming language that uses [https://yaml.org/ YAML] as its syntax. It is a complete, functional, general purpose language, but can also be easily embedded in YAML files to make them dynamic at load time. Most existing YAML files and all JSON files are already valid YS programs. You can learn YS for free (with help from experienced mentors) at [https://exercism.org/tracks/yamlscript Exercism]. -YS has a compiler/interpreter CLI program called [https://github.com/yaml/yamlscript/releases ys] and is also available in several programming languages as a binding module to the [https://github.com/yaml/yamlscript/releases libyamlscript.so] shared library: +YS has a compiler/interpreter CLI program called [https://github.com/yaml/yamlscript/releases ys] and is also available in several programming languages as a binding module to the [https://github.com/yaml/yamlscript/releases libys.so] shared library: +* [https://www.nuget.org/packages/YAMLScript/ C#] * [https://clojars.org/org.yamlscript/clj-yamlscript Clojure] +* [https://shardbox.org/shards/yamlscript Crystal] * [https://github.com/yaml/yamlscript-go Go] +* [https://hackage.haskell.org/package/yamlscript Haskell] * [https://clojars.org/org.yamlscript/yamlscript Java] * [https://juliahub.com/ui/Packages/General/YAMLScript Julia] +* [https://luarocks.org/modules/ingy/yamlscript Lua] * [https://www.npmjs.com/package/@yaml/yamlscript NodeJS] * [https://metacpan.org/pod/YAMLScript Perl] +* [https://packagist.org/packages/yaml/yamlscript PHP] * [https://pypi.org/project/yamlscript/ Python] * [https://raku.land/zef:ingy/YAMLScript Raku] * [https://rubygems.org/gems/yamlscript Ruby] @@ -25,7 +30,7 @@ YS has a compiler/interpreter CLI program called [https://github.com/yaml/ Run this command to install the ys command line YS runner/loader/compiler binary. - curl -s https://yamlscript.org/install | bash + curl https://getys.org/ys | bash That will install $HOME/.local/bin/ys. If $HOME/.local/bin is not in your PATH, run: diff --git a/Lang/YAMLScript/Best-shuffle b/Lang/YAMLScript/Best-shuffle new file mode 120000 index 0000000000..99ffbfc9b1 --- /dev/null +++ b/Lang/YAMLScript/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Conways-Game-of-Life b/Lang/YAMLScript/Conways-Game-of-Life new file mode 120000 index 0000000000..3153c05b26 --- /dev/null +++ b/Lang/YAMLScript/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Dragon-curve b/Lang/YAMLScript/Dragon-curve new file mode 120000 index 0000000000..7f9deedb82 --- /dev/null +++ b/Lang/YAMLScript/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Even-or-odd b/Lang/YAMLScript/Even-or-odd new file mode 120000 index 0000000000..95556dd2eb --- /dev/null +++ b/Lang/YAMLScript/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Integer-comparison b/Lang/YAMLScript/Integer-comparison new file mode 120000 index 0000000000..47b0c04990 --- /dev/null +++ b/Lang/YAMLScript/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/JortSort b/Lang/YAMLScript/JortSort new file mode 120000 index 0000000000..28bb797476 --- /dev/null +++ b/Lang/YAMLScript/JortSort @@ -0,0 +1 @@ +../../Task/JortSort/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Knuth-shuffle b/Lang/YAMLScript/Knuth-shuffle new file mode 120000 index 0000000000..676dc89553 --- /dev/null +++ b/Lang/YAMLScript/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Munching-squares b/Lang/YAMLScript/Munching-squares new file mode 120000 index 0000000000..2b7870226f --- /dev/null +++ b/Lang/YAMLScript/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Next-highest-int-from-digits b/Lang/YAMLScript/Next-highest-int-from-digits new file mode 120000 index 0000000000..6dd0221650 --- /dev/null +++ b/Lang/YAMLScript/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/One-dimensional-cellular-automata b/Lang/YAMLScript/One-dimensional-cellular-automata new file mode 120000 index 0000000000..74c105b72e --- /dev/null +++ b/Lang/YAMLScript/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Quickselect-algorithm b/Lang/YAMLScript/Quickselect-algorithm new file mode 120000 index 0000000000..978322a04a --- /dev/null +++ b/Lang/YAMLScript/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Sparkline-in-unicode b/Lang/YAMLScript/Sparkline-in-unicode new file mode 120000 index 0000000000..ae2a07413c --- /dev/null +++ b/Lang/YAMLScript/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell b/Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..21baf990a9 --- /dev/null +++ b/Lang/YAMLScript/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Undefined-values b/Lang/YAMLScript/Undefined-values new file mode 120000 index 0000000000..ff7699a995 --- /dev/null +++ b/Lang/YAMLScript/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Van-der-Corput-sequence b/Lang/YAMLScript/Van-der-Corput-sequence new file mode 120000 index 0000000000..654ffd3cbb --- /dev/null +++ b/Lang/YAMLScript/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Xiaolin-Wus-line-algorithm b/Lang/YAMLScript/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..be316f6902 --- /dev/null +++ b/Lang/YAMLScript/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Yellowstone-sequence b/Lang/YAMLScript/Yellowstone-sequence new file mode 120000 index 0000000000..efac2d410f --- /dev/null +++ b/Lang/YAMLScript/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Zig-zag-matrix b/Lang/YAMLScript/Zig-zag-matrix new file mode 120000 index 0000000000..691eda7cd9 --- /dev/null +++ b/Lang/YAMLScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/YAMLScript \ No newline at end of file diff --git a/Lang/Zig/24-game-Solve b/Lang/Zig/24-game-Solve new file mode 120000 index 0000000000..cf80fe1aa1 --- /dev/null +++ b/Lang/Zig/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Zig \ No newline at end of file diff --git a/Lang/Zig/AVL-tree b/Lang/Zig/AVL-tree new file mode 120000 index 0000000000..05056fdece --- /dev/null +++ b/Lang/Zig/AVL-tree @@ -0,0 +1 @@ +../../Task/AVL-tree/Zig \ No newline at end of file diff --git a/Lang/Zig/Abelian-sandpile-model b/Lang/Zig/Abelian-sandpile-model new file mode 120000 index 0000000000..aff7b1b955 --- /dev/null +++ b/Lang/Zig/Abelian-sandpile-model @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model/Zig \ No newline at end of file diff --git a/Lang/Zig/Abelian-sandpile-model-Identity b/Lang/Zig/Abelian-sandpile-model-Identity new file mode 120000 index 0000000000..5a22dd3380 --- /dev/null +++ b/Lang/Zig/Abelian-sandpile-model-Identity @@ -0,0 +1 @@ +../../Task/Abelian-sandpile-model-Identity/Zig \ No newline at end of file diff --git a/Lang/Zig/Arrays b/Lang/Zig/Arrays new file mode 120000 index 0000000000..8271fea84a --- /dev/null +++ b/Lang/Zig/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Zig \ No newline at end of file diff --git a/Lang/Zig/Associative-array-Creation b/Lang/Zig/Associative-array-Creation new file mode 120000 index 0000000000..9dff0b181f --- /dev/null +++ b/Lang/Zig/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Zig \ No newline at end of file diff --git a/Lang/Zig/Associative-array-Iteration b/Lang/Zig/Associative-array-Iteration new file mode 120000 index 0000000000..0120ea3ca0 --- /dev/null +++ b/Lang/Zig/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Zig \ No newline at end of file diff --git a/Lang/Zig/Base64-decode-data b/Lang/Zig/Base64-decode-data new file mode 120000 index 0000000000..9291a91364 --- /dev/null +++ b/Lang/Zig/Base64-decode-data @@ -0,0 +1 @@ +../../Task/Base64-decode-data/Zig \ No newline at end of file diff --git a/Lang/Zig/Bifid-cipher b/Lang/Zig/Bifid-cipher new file mode 120000 index 0000000000..c3e619eb90 --- /dev/null +++ b/Lang/Zig/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Zig \ No newline at end of file diff --git a/Lang/Zig/Boolean-values b/Lang/Zig/Boolean-values new file mode 120000 index 0000000000..8bbec67819 --- /dev/null +++ b/Lang/Zig/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Zig \ No newline at end of file diff --git a/Lang/Zig/Boyer-Moore-string-search b/Lang/Zig/Boyer-Moore-string-search new file mode 120000 index 0000000000..9c6dd89c45 --- /dev/null +++ b/Lang/Zig/Boyer-Moore-string-search @@ -0,0 +1 @@ +../../Task/Boyer-Moore-string-search/Zig \ No newline at end of file diff --git a/Lang/Zig/Break-OO-privacy b/Lang/Zig/Break-OO-privacy new file mode 120000 index 0000000000..535f70b15b --- /dev/null +++ b/Lang/Zig/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Zig \ No newline at end of file diff --git a/Lang/Zig/Camel-case-and-snake-case b/Lang/Zig/Camel-case-and-snake-case new file mode 120000 index 0000000000..ab00dfd34b --- /dev/null +++ b/Lang/Zig/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Zig \ No newline at end of file diff --git a/Lang/Zig/Cholesky-decomposition b/Lang/Zig/Cholesky-decomposition new file mode 120000 index 0000000000..7fbe65969f --- /dev/null +++ b/Lang/Zig/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Zig \ No newline at end of file diff --git a/Lang/Zig/Cumulative-standard-deviation b/Lang/Zig/Cumulative-standard-deviation new file mode 120000 index 0000000000..225e824146 --- /dev/null +++ b/Lang/Zig/Cumulative-standard-deviation @@ -0,0 +1 @@ +../../Task/Cumulative-standard-deviation/Zig \ No newline at end of file diff --git a/Lang/Zig/Cyclops-numbers b/Lang/Zig/Cyclops-numbers new file mode 120000 index 0000000000..625d97b345 --- /dev/null +++ b/Lang/Zig/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/Zig \ No newline at end of file diff --git a/Lang/Zig/Deconvolution-1D b/Lang/Zig/Deconvolution-1D new file mode 120000 index 0000000000..26b778762a --- /dev/null +++ b/Lang/Zig/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Zig \ No newline at end of file diff --git a/Lang/Zig/Determinant-and-permanent b/Lang/Zig/Determinant-and-permanent new file mode 120000 index 0000000000..6aec06c204 --- /dev/null +++ b/Lang/Zig/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/Zig \ No newline at end of file diff --git a/Lang/Zig/Eertree b/Lang/Zig/Eertree new file mode 120000 index 0000000000..297f5d26a6 --- /dev/null +++ b/Lang/Zig/Eertree @@ -0,0 +1 @@ +../../Task/Eertree/Zig \ No newline at end of file diff --git a/Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..8631c5bdb3 --- /dev/null +++ b/Lang/Zig/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Elliptic-curve-arithmetic b/Lang/Zig/Elliptic-curve-arithmetic new file mode 120000 index 0000000000..6d1206bc71 --- /dev/null +++ b/Lang/Zig/Elliptic-curve-arithmetic @@ -0,0 +1 @@ +../../Task/Elliptic-curve-arithmetic/Zig \ No newline at end of file diff --git a/Lang/Zig/Evolutionary-algorithm b/Lang/Zig/Evolutionary-algorithm new file mode 120000 index 0000000000..59ff814ffb --- /dev/null +++ b/Lang/Zig/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Factors-of-an-integer b/Lang/Zig/Factors-of-an-integer new file mode 120000 index 0000000000..9bd33985d3 --- /dev/null +++ b/Lang/Zig/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Zig \ No newline at end of file diff --git a/Lang/Zig/Farey-sequence b/Lang/Zig/Farey-sequence new file mode 120000 index 0000000000..44274502d4 --- /dev/null +++ b/Lang/Zig/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Gray-code b/Lang/Zig/Gray-code new file mode 120000 index 0000000000..f2147c406a --- /dev/null +++ b/Lang/Zig/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Zig \ No newline at end of file diff --git a/Lang/Zig/K-d-tree b/Lang/Zig/K-d-tree new file mode 120000 index 0000000000..3fd542d0d2 --- /dev/null +++ b/Lang/Zig/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Zig \ No newline at end of file diff --git a/Lang/Zig/Knapsack-problem-0-1 b/Lang/Zig/Knapsack-problem-0-1 new file mode 120000 index 0000000000..95f8fcd9fc --- /dev/null +++ b/Lang/Zig/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Zig \ No newline at end of file diff --git a/Lang/Zig/Knights-tour b/Lang/Zig/Knights-tour new file mode 120000 index 0000000000..a8fa50bb64 --- /dev/null +++ b/Lang/Zig/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Zig \ No newline at end of file diff --git a/Lang/Zig/Loops-Nested b/Lang/Zig/Loops-Nested new file mode 120000 index 0000000000..a78e39957d --- /dev/null +++ b/Lang/Zig/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Zig \ No newline at end of file diff --git a/Lang/Zig/M-bius-function b/Lang/Zig/M-bius-function new file mode 120000 index 0000000000..b4ad984b09 --- /dev/null +++ b/Lang/Zig/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/Zig \ No newline at end of file diff --git a/Lang/Zig/Main-step-of-GOST-28147-89 b/Lang/Zig/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..433b294fbc --- /dev/null +++ b/Lang/Zig/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Zig \ No newline at end of file diff --git a/Lang/Zig/Modular-arithmetic b/Lang/Zig/Modular-arithmetic new file mode 120000 index 0000000000..a64c6161fe --- /dev/null +++ b/Lang/Zig/Modular-arithmetic @@ -0,0 +1 @@ +../../Task/Modular-arithmetic/Zig \ No newline at end of file diff --git a/Lang/Zig/Modular-inverse b/Lang/Zig/Modular-inverse new file mode 120000 index 0000000000..f96c2102b0 --- /dev/null +++ b/Lang/Zig/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Zig \ No newline at end of file diff --git a/Lang/Zig/Parse-an-IP-Address b/Lang/Zig/Parse-an-IP-Address new file mode 120000 index 0000000000..dcc1d9a064 --- /dev/null +++ b/Lang/Zig/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Zig \ No newline at end of file diff --git a/Lang/Zig/Permutations-by-swapping b/Lang/Zig/Permutations-by-swapping new file mode 120000 index 0000000000..5e667cc7e2 --- /dev/null +++ b/Lang/Zig/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Zig \ No newline at end of file diff --git a/Lang/Zig/Stern-Brocot-sequence b/Lang/Zig/Stern-Brocot-sequence new file mode 120000 index 0000000000..4e68e871bc --- /dev/null +++ b/Lang/Zig/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Zig \ No newline at end of file diff --git a/Lang/Zig/Sudoku b/Lang/Zig/Sudoku new file mode 120000 index 0000000000..cc0b8be01d --- /dev/null +++ b/Lang/Zig/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Zig \ No newline at end of file diff --git a/Lang/Zig/Tarjan b/Lang/Zig/Tarjan new file mode 120000 index 0000000000..47db828add --- /dev/null +++ b/Lang/Zig/Tarjan @@ -0,0 +1 @@ +../../Task/Tarjan/Zig \ No newline at end of file diff --git a/Lang/Zig/Tree-datastructures b/Lang/Zig/Tree-datastructures new file mode 120000 index 0000000000..2483259e7c --- /dev/null +++ b/Lang/Zig/Tree-datastructures @@ -0,0 +1 @@ +../../Task/Tree-datastructures/Zig \ No newline at end of file diff --git a/Lang/Zig/Verhoeff-algorithm b/Lang/Zig/Verhoeff-algorithm new file mode 120000 index 0000000000..d90fb8e2ca --- /dev/null +++ b/Lang/Zig/Verhoeff-algorithm @@ -0,0 +1 @@ +../../Task/Verhoeff-algorithm/Zig \ No newline at end of file diff --git a/Lang/Zig/Vigen-re-cipher-Cryptanalysis b/Lang/Zig/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..7fd7d3aa92 --- /dev/null +++ b/Lang/Zig/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Zig \ No newline at end of file diff --git a/Lang/Zig/Vogels-approximation-method b/Lang/Zig/Vogels-approximation-method new file mode 120000 index 0000000000..af40cfb307 --- /dev/null +++ b/Lang/Zig/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Zig \ No newline at end of file diff --git a/Lang/Zig/War-card-game b/Lang/Zig/War-card-game new file mode 120000 index 0000000000..6bc9afa5bf --- /dev/null +++ b/Lang/Zig/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/Zig \ No newline at end of file diff --git a/Task/100-doors/AWK/100-doors-1.awk b/Task/100-doors/AWK/100-doors-1.awk deleted file mode 100644 index 1c2a279c09..0000000000 --- a/Task/100-doors/AWK/100-doors-1.awk +++ /dev/null @@ -1,17 +0,0 @@ -BEGIN { - for(i=1; i <= 100; i++) - { - doors[i] = 0 # close the doors - } - for(i=1; i <= 100; i++) - { - for(j=i; j <= 100; j += i) - { - doors[j] = (doors[j]+1) % 2 - } - } - for(i=1; i <= 100; i++) - { - print i, doors[i] ? "open" : "close" - } -} diff --git a/Task/100-doors/AWK/100-doors-2.awk b/Task/100-doors/AWK/100-doors-2.awk deleted file mode 100644 index 9344bbec27..0000000000 --- a/Task/100-doors/AWK/100-doors-2.awk +++ /dev/null @@ -1,14 +0,0 @@ -BEGIN { - for(i=1; i <= 100; i++) { - doors[i] = 0 # close the doors - } - for(i=1; i <= 100; i++) { - if ( int(sqrt(i)) == sqrt(i) ) { - doors[i] = 1 - } - } - for(i=1; i <= 100; i++) - { - print i, doors[i] ? "open" : "close" - } -} diff --git a/Task/100-doors/Adina/100-doors-1.adina b/Task/100-doors/Adina/100-doors-1.adina new file mode 100644 index 0000000000..0e7190c89e --- /dev/null +++ b/Task/100-doors/Adina/100-doors-1.adina @@ -0,0 +1,16 @@ +двери = новый-массив 100 ложь + +цикл + шаг + в-диапазоне 1 101 + цикл + номер + в-диапазоне (шаг - 1) 100 шаг + двери[номер] := не двери[номер] + +цикл + номер 100 + вывести/перенос + формат «Дверь ~a ~a» + номер + 1 + двери[номер] ? «открыта» «закрыта» diff --git a/Task/100-doors/Adina/100-doors-2.adina b/Task/100-doors/Adina/100-doors-2.adina new file mode 100644 index 0000000000..6286140dc0 --- /dev/null +++ b/Task/100-doors/Adina/100-doors-2.adina @@ -0,0 +1,17 @@ +english() +doors = make-vector 100 #f + +for + $ step + in-range 1 101 + for + $ number + in-range (step - 1) 100 step + doors[number] := not doors[number] + +for + $ number 100 + displayln + format "Door ~a ~a" + number + 1 + if doors[number] "open" "closed" diff --git a/Task/100-doors/ArkScript/100-doors-1.ark b/Task/100-doors/ArkScript/100-doors-1.ark new file mode 100644 index 0000000000..713e3b360f --- /dev/null +++ b/Task/100-doors/ArkScript/100-doors-1.ark @@ -0,0 +1,21 @@ +(import std.Range :range :forEach) +(import std.List) + +(mut doors (list:fill 100 false)) +(let r (range 0 100)) + +(forEach r + (fun (i) { + (mut j i) + (while (< j 100) { + (@= doors j (not (@ doors j))) + (set j (+ j i 1)) }) + (print doors) })) + +(print + (list:map + (list:filter + (list:zipWithIndex doors) + (fun (e) + (@ e 1))) + (fun (e) (@ e 0)))) diff --git a/Task/100-doors/ArkScript/100-doors-2.ark b/Task/100-doors/ArkScript/100-doors-2.ark new file mode 100644 index 0000000000..b1cb4380b2 --- /dev/null +++ b/Task/100-doors/ArkScript/100-doors-2.ark @@ -0,0 +1,4 @@ +[true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true] +... +[true false false true false false false false true false false false false false false true false false false false false false false false true false false false false false false false false false false true false false false false false false false false false false false false true false false false false false false false false false false false false false false true false false false false false false false false false false false false false false false false true false false false false false false false false false false false false false false false false false false true] +[0 3 8 15 24 35 48 63 80 99] diff --git a/Task/100-doors/AutoLISP/100-doors.l b/Task/100-doors/AutoLISP/100-doors.l new file mode 100644 index 0000000000..d4a0ebbe77 --- /dev/null +++ b/Task/100-doors/AutoLISP/100-doors.l @@ -0,0 +1,18 @@ +(defun CreateDoors (n / doors) + (repeat n + (setq doors (cons nil doors)) + ) +) + +(defun Doors (doors / cnt) + (setq cnt 0) + (mapcar + '(lambda (d) + (zerop (rem (sqrt (setq cnt (1+ cnt))) 1)) + ) + doors + ) +) + +> (Doors (CreateDoors 100)) +(T nil nil T nil nil nil nil T nil nil nil nil nil nil T nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil) diff --git a/Task/100-doors/Component-Pascal/100-doors.pas b/Task/100-doors/Component-Pascal/100-doors.pas deleted file mode 100644 index 0e11914244..0000000000 --- a/Task/100-doors/Component-Pascal/100-doors.pas +++ /dev/null @@ -1,26 +0,0 @@ -MODULE Doors100; -IMPORT StdLog; - -PROCEDURE Do*; -VAR - i,j: INTEGER; - closed: ARRAY 101 OF BOOLEAN; -BEGIN - (* initialization of closed to true *) - FOR i := 0 TO LEN(closed) - 1 DO closed[i] := TRUE END; - (* process *) - FOR i := 1 TO LEN(closed) DO; - j := 1; - WHILE j < LEN(closed) DO - IF j MOD i = 0 THEN closed[j] := ~closed[j] END;INC(j) - END - END; - (* print results *) - i := 1; - WHILE i < LEN(closed) DO - IF (i - 1) MOD 10 = 0 THEN StdLog.Ln END; - IF closed[i] THEN StdLog.String("C ") ELSE StdLog.String("O ") END; - INC(i) - END; -END Do; -END Doors100. diff --git a/Task/100-doors/DuckDB/100-doors.duckdb b/Task/100-doors/DuckDB/100-doors.duckdb new file mode 100644 index 0000000000..aa3716882e --- /dev/null +++ b/Task/100-doors/DuckDB/100-doors.duckdb @@ -0,0 +1,19 @@ +# Show the state of n doors after n iterations +create or replace function doors(n) as ( + with recursive cte(ix,d) as ( + select 0 as ix, list_transform(range(0, n), x -> false) as d + union all + select ix+1, + list_transform(d, (x,i) -> if (i % (ix + 1) = 0, NOT x, x)) + from cte + where ix < n + ) + select last(d order by ix) + from cte +); + +# For brevity, we just show the indices of the doors that are open after all +# have been visited: +select ix +from (select unnest(generate_series(1,100)) as ix, unnest(doors(100)) as d) +where d = true; diff --git a/Task/100-doors/Haskell/100-doors-3.hs b/Task/100-doors/Haskell/100-doors-3.hs index 2cea247dfd..3b66096632 100644 --- a/Task/100-doors/Haskell/100-doors-3.hs +++ b/Task/100-doors/Haskell/100-doors-3.hs @@ -1,6 +1,9 @@ -gate :: Eq a => [a] -> [a] -> [Door] -gate (x:xs) (y:ys) | x == y = Open : gate xs ys -gate (x:xs) ys = Closed : gate xs ys -gate [] _ = [] +isDoorOpen :: Integral a => a -> Bool +-- In Haskell, we are too lazy to open and close doors. Instead we +-- count how many times we would have toggled them, and then check if +-- that number is odd. +isDoorOpen doorNumber = odd numToggles + where numToggles = length [ 1 | x <- [1..doorNumber], doorNumber `rem` x == 0] -run n = gate [1..n] [k*k | k <- [1..]] +main = do + print $ "Open doors are " ++ show [x | x <- [0..100], isDoorOpen x] diff --git a/Task/100-doors/Haskell/100-doors-4.hs b/Task/100-doors/Haskell/100-doors-4.hs index 44f44aa391..2cea247dfd 100644 --- a/Task/100-doors/Haskell/100-doors-4.hs +++ b/Task/100-doors/Haskell/100-doors-4.hs @@ -1 +1,6 @@ -run n = takeWhile (< n) [k*k | k <- [1..]] +gate :: Eq a => [a] -> [a] -> [Door] +gate (x:xs) (y:ys) | x == y = Open : gate xs ys +gate (x:xs) ys = Closed : gate xs ys +gate [] _ = [] + +run n = gate [1..n] [k*k | k <- [1..]] diff --git a/Task/100-doors/Haskell/100-doors-5.hs b/Task/100-doors/Haskell/100-doors-5.hs new file mode 100644 index 0000000000..44f44aa391 --- /dev/null +++ b/Task/100-doors/Haskell/100-doors-5.hs @@ -0,0 +1 @@ +run n = takeWhile (< n) [k*k | k <- [1..]] diff --git a/Task/100-doors/Lua/100-doors.lua b/Task/100-doors/Lua/100-doors.lua deleted file mode 100644 index 3183bc7730..0000000000 --- a/Task/100-doors/Lua/100-doors.lua +++ /dev/null @@ -1,11 +0,0 @@ -local is_open = {} - -for pass = 1,100 do - for door = pass,100,pass do - is_open[door] = not is_open[door] - end -end - -for i,v in next,is_open do - print ('Door '..i..':',v and 'open' or 'close') -end diff --git a/Task/100-doors/PL-M/100-doors.plm b/Task/100-doors/PL-M/100-doors.plm deleted file mode 100644 index 0013832477..0000000000 --- a/Task/100-doors/PL-M/100-doors.plm +++ /dev/null @@ -1,55 +0,0 @@ -100H: /* FIND THE FIRST FEW SQUARES VIA THE UNOPTIMISED DOOR FLIPPING METHOD */ - - /* BDOS SYSTEM CALL */ - BDOS: PROCEDURE( FN, ARG ); - DECLARE FN BYTE, ARG ADDRESS; - GO TO 5; - END BDOS; - - /* PRINTS A BYTE AS A CHARACTER */ - PRINT$CHAR: PROCEDURE( CH ); - DECLARE CH BYTE; - CALL BDOS( 2, CH ); - END PRINT$CHAR; - - /* PRINTS A BYTE AS A NUMBER */ - PRINT$BYTE: PROCEDURE( N ); - DECLARE N BYTE; - DECLARE ( V, D3, D2 ) BYTE; - V = N; - D3 = V MOD 10; - IF ( V := V / 10 ) <> 0 THEN DO; - D2 = V MOD 10; - IF ( V := V / 10 ) <> 0 THEN CALL PRINT$CHAR( '0' + V ); - CALL PRINT$CHAR( '0' + D2 ); - END; - CALL PRINT$CHAR( '0' + D3 ); - END PRINT$BYTE; - - DECLARE DOOR$DCL LITERALLY '101'; - DECLARE FALSE LITERALLY '0'; - DECLARE CR LITERALLY '0DH'; - DECLARE LF LITERALLY '0AH'; - - /* ARRAY OF DOORS - DOOR( I ) IS TRUE IF OPEN, FALSE IF CLOSED */ - DECLARE DOOR( DOOR$DCL ) BYTE; - DECLARE ( I, J ) BYTE; - - /* SET ALL DOORS TO CLOSED */ - DO I = 0 TO LAST( DOOR ); DOOR( I ) = FALSE; END; - /* REPEATEDLY FLIP THE DOORS */ - DO I = 1 TO LAST( DOOR ); - DO J = I TO LAST( DOOR ) BY I; - DOOR( J ) = NOT DOOR( J ); - END; - END; - /* DISPLAY THE RESULTS */ - DO I = 1 TO LAST( DOOR ); - IF DOOR( I ) THEN DO; - CALL PRINT$CHAR( ' ' ); - CALL PRINT$BYTE( I ); - END; - END; - CALL PRINT$CHAR( CR ); - CALL PRINT$CHAR( LF ); -EOF diff --git a/Task/100-doors/REBOL/100-doors-2.rebol b/Task/100-doors/REBOL/100-doors-2.rebol index 73f1f448f3..b8428a69d9 100644 --- a/Task/100-doors/REBOL/100-doors-2.rebol +++ b/Task/100-doors/REBOL/100-doors-2.rebol @@ -1,2 +1,26 @@ -doors: array/initial 100 'closed -repeat i 10 [doors/(i * i): 'open] +;; Create a bitset with capacity for 100 bits (representing 100 doors) +;; Each bit represents a door state: 0 = closed, 1 = open +doors: make bitset! 100 + +;; Outer loop: Make 100 passes (i = 1 to 100) +repeat i 100 [ + ;; Inner loop: Check each door position (j = 1 to 100) + repeat j 100 [ + ;; If door j index is divisible by pass number i (no remainder) + if zero? (j // i) [ + ;; Toggle the door's bit: + ;; doors/:j accesses door j in the bitset + ;; 'not' flips the bit value (0 -> 1, 1 -> 0) + doors/:j: not doors/:j + ] + ] +] + +;; Final loop: Check which doors are open, print their numbers +repeat i 100 [ + ;; If door i's bit is set (open) + if doors/:i [ + ;; Print the door's number and that it is open + print ["door" i "is open"] + ] +] diff --git a/Task/100-doors/REBOL/100-doors-3.rebol b/Task/100-doors/REBOL/100-doors-3.rebol new file mode 100644 index 0000000000..318cdd4a11 --- /dev/null +++ b/Task/100-doors/REBOL/100-doors-3.rebol @@ -0,0 +1,6 @@ +;; Loop variable i from 1 to 10 (since 10^2 = 100, covers doors 1 to 100) +repeat i 10 [ + ;; Print that door number (i squared) is open + ;; These are exactly the doors with perfect square numbers: 1, 4, 9, ..., 100 + print ["door" (i * i) "is open"] +] diff --git a/Task/100-prisoners/Prolog/100-prisoners.pro b/Task/100-prisoners/Prolog/100-prisoners.pro new file mode 100644 index 0000000000..375a4acfc8 --- /dev/null +++ b/Task/100-prisoners/Prolog/100-prisoners.pro @@ -0,0 +1,43 @@ +:- use_module(library(aggregate)). +:- use_module(library(lists)). +:- use_module(library(random)). + +random_subset(Length, List, Subset) :- + random_permutation(List, Shuffled), + length(Subset, Length), + prefix(Subset, Shuffled). + +random_play :- + numlist(1, 100, Prisoners), + random_permutation(Prisoners, Drawers), + forall(member(Prisoner, Prisoners), ( + random_subset(50, Drawers, CheckedDrawers), + memberchk(Prisoner, CheckedDrawers) + )). + +optimal_play :- + numlist(1, 100, Prisoners), + random_permutation(Prisoners, Drawers), + forall(member(Prisoner, Prisoners), optimal_play(50, Prisoner, Prisoner, Drawers)). + +optimal_play(ChecksRemaining, Prisoner, NumberToCheck, Drawers) :- + ChecksRemaining > 0, + nth1(NumberToCheck, Drawers, NumberInDrawer), + ( NumberInDrawer = Prisoner + -> true + ; ChecksRemaining0 is ChecksRemaining - 1, + optimal_play(ChecksRemaining0, Prisoner, NumberInDrawer, Drawers) + ). + +:- meta_predicate play_n_times(+, 0, -). +play_n_times(PlayCount, Play, Percentage) :- + aggregate_all(count, ( between(1, PlayCount, _), call(Play) ), Victories), + Percentage is Victories / PlayCount * 100. + +main(SimulationCount) :- + play_n_times(SimulationCount, random_play, RandomPlayPercent), + play_n_times(SimulationCount, optimal_play, OptimalPlayPercent), + format("Simulation count: ~d\nRandom play wins: ~f% of the simulations.\nOptimal play wins ~f% of the simulations.", + [SimulationCount, RandomPlayPercent, OptimalPlayPercent]). + +:- main(100_000). diff --git a/Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas b/Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas new file mode 100644 index 0000000000..36a40f7d75 --- /dev/null +++ b/Task/15-puzzle-solver/PascalABC.NET/15-puzzle-solver.pas @@ -0,0 +1,3 @@ +// Игра в 15 PABCWork.NET\Samples\Games\15.pas +see +https://rosettacode.org/wiki/15_puzzle_game#PascalABC.NET diff --git a/Task/2048/EasyLang/2048.easy b/Task/2048/EasyLang/2048.easy index 410f4010a9..079064a289 100644 --- a/Task/2048/EasyLang/2048.easy +++ b/Task/2048/EasyLang/2048.easy @@ -142,7 +142,7 @@ proc handle_mup . on mouse_up handle_mup . -on key +on key_down if stat = 2 if keybkey = " " : init return diff --git a/Task/24-game-Solve/Zig/24-game-solve.zig b/Task/24-game-Solve/Zig/24-game-solve.zig new file mode 100644 index 0000000000..1837c9404d --- /dev/null +++ b/Task/24-game-Solve/Zig/24-game-solve.zig @@ -0,0 +1,273 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; +const HashMap = std.HashMap; +const Allocator = std.mem.Allocator; + +const Operator = enum { + sub, + plus, + mul, + div, +}; + +const Factor = struct { + content: []const u8, + value: i32, + + fn deinit(self: Factor, allocator: Allocator) void { + allocator.free(self.content); + } +}; + +fn apply(allocator: Allocator, op: Operator, left: []const Factor, right: []const Factor) !ArrayList(Factor) { + var ret = ArrayList(Factor).init(allocator); + + for (left) |l| { + for (right) |r| { + switch (op) { + .sub => { + if (l.value > r.value) { + const content = try std.fmt.allocPrint(allocator, "({s} - {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = l.value - r.value, + }); + } + }, + .plus => { + const content = try std.fmt.allocPrint(allocator, "({s} + {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = l.value + r.value, + }); + }, + .mul => { + const content = try std.fmt.allocPrint(allocator, "({s} x {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = l.value * r.value, + }); + }, + .div => { + if (l.value >= r.value and r.value > 0 and @rem(l.value, r.value) == 0) { + const content = try std.fmt.allocPrint(allocator, "({s} / {s})", .{ l.content, r.content }); + try ret.append(Factor{ + .content = content, + .value = @divTrunc(l.value, r.value), + }); + } + }, + } + } + } + + return ret; +} + +fn calc(allocator: Allocator, ops: [3]Operator, numbers: [4]i32) !ArrayList(Factor) { + var current_factors = ArrayList(Factor).init(allocator); + defer { + for (current_factors.items) |factor| { + factor.deinit(allocator); + } + current_factors.deinit(); + } + + // Initialize with first number + const initial_content = try std.fmt.allocPrint(allocator, "{}", .{numbers[0]}); + try current_factors.append(Factor{ + .content = initial_content, + .value = numbers[0], + }); + + // Process each operation + for (ops, 0..) |op, i| { + var next_factors = ArrayList(Factor).init(allocator); + defer { + for (next_factors.items) |factor| { + factor.deinit(allocator); + } + next_factors.deinit(); + } + + const mono_content = try std.fmt.allocPrint(allocator, "{}", .{numbers[i + 1]}); + defer allocator.free(mono_content); + const mono_factor = Factor{ + .content = mono_content, + .value = numbers[i + 1], + }; + const mono_slice = &[_]Factor{mono_factor}; + + switch (op) { + .mul, .plus => { + var applied = try apply(allocator, op, current_factors.items, mono_slice); + defer applied.deinit(); + try next_factors.appendSlice(applied.items); + }, + .div, .sub => { + var applied1 = try apply(allocator, op, current_factors.items, mono_slice); + defer applied1.deinit(); + try next_factors.appendSlice(applied1.items); + + var applied2 = try apply(allocator, op, mono_slice, current_factors.items); + defer applied2.deinit(); + try next_factors.appendSlice(applied2.items); + }, + } + + // Clear current factors and move next_factors to current_factors + for (current_factors.items) |factor| { + factor.deinit(allocator); + } + current_factors.clearRetainingCapacity(); + + // Move ownership from next_factors to current_factors + try current_factors.appendSlice(next_factors.items); + next_factors.clearRetainingCapacity(); // Don't deinit the items, we moved them + } + + // Create result and transfer ownership + var result = ArrayList(Factor).init(allocator); + try result.appendSlice(current_factors.items); + current_factors.clearRetainingCapacity(); // Don't deinit, we transferred ownership + + return result; +} + +const OpIter = struct { + index: usize, + + const OPTIONS = [_]Operator{ .mul, .sub, .plus, .div }; + + fn init() OpIter { + return OpIter{ .index = 0 }; + } + + fn next(self: *OpIter) ?[3]Operator { + if (self.index >= 64) { + return null; + } + + const f1 = OPTIONS[(self.index & (3 << 4)) >> 4]; + const f2 = OPTIONS[(self.index & (3 << 2)) >> 2]; + const f3 = OPTIONS[(self.index & (3 << 0)) >> 0]; + + self.index += 1; + return [3]Operator{ f1, f2, f3 }; + } +}; + +fn orders() [24][4]usize { + return [24][4]usize{ + [4]usize{ 0, 1, 2, 3 }, + [4]usize{ 0, 1, 3, 2 }, + [4]usize{ 0, 2, 1, 3 }, + [4]usize{ 0, 2, 3, 1 }, + [4]usize{ 0, 3, 1, 2 }, + [4]usize{ 0, 3, 2, 1 }, + [4]usize{ 1, 0, 2, 3 }, + [4]usize{ 1, 0, 3, 2 }, + [4]usize{ 1, 2, 0, 3 }, + [4]usize{ 1, 2, 3, 0 }, + [4]usize{ 1, 3, 0, 2 }, + [4]usize{ 1, 3, 2, 0 }, + [4]usize{ 2, 0, 1, 3 }, + [4]usize{ 2, 0, 3, 1 }, + [4]usize{ 2, 1, 0, 3 }, + [4]usize{ 2, 1, 3, 0 }, + [4]usize{ 2, 3, 0, 1 }, + [4]usize{ 2, 3, 1, 0 }, + [4]usize{ 3, 0, 1, 2 }, + [4]usize{ 3, 0, 2, 1 }, + [4]usize{ 3, 1, 0, 2 }, + [4]usize{ 3, 1, 2, 0 }, + [4]usize{ 3, 2, 0, 1 }, + [4]usize{ 3, 2, 1, 0 }, + }; +} + +fn applyOrder(numbers: [4]i32, order: [4]usize) [4]i32 { + return [4]i32{ numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]] }; +} + +fn solutions(allocator: Allocator, numbers: [4]i32) !ArrayList(Factor) { + var ret = ArrayList(Factor).init(allocator); + var hash_set = HashMap([]const u8, void, std.hash_map.StringContext, std.hash_map.default_max_load_percentage).init(allocator); + defer { + // Free all keys in the hash map + var iterator = hash_set.iterator(); + while (iterator.next()) |entry| { + allocator.free(entry.key_ptr.*); + } + hash_set.deinit(); + } + + var op_iter = OpIter.init(); + while (op_iter.next()) |ops| { + const all_orders = orders(); + for (all_orders) |order| { + const reordered_numbers = applyOrder(numbers, order); + var results = calc(allocator, ops, reordered_numbers) catch continue; + defer { + for (results.items) |factor| { + factor.deinit(allocator); + } + results.deinit(); + } + + for (results.items) |factor| { + if (factor.value == 24) { + // Check if we've seen this content before + if (hash_set.contains(factor.content)) { + continue; + } + + // Add to hash set with a duplicated key + const key_copy = try allocator.dupe(u8, factor.content); + try hash_set.put(key_copy, {}); + + // Add to results with a duplicated content + try ret.append(Factor{ + .content = try allocator.dupe(u8, factor.content), + .value = factor.value, + }); + } + } + } + } + + return ret; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + // Hard-coded input: 5598 + const nums = [4]i32{ 5, 5, 9, 8 }; + + var sols = solutions(allocator, nums) catch { + print("Error computing solutions\n", .{}); + return; + }; + defer { + for (sols.items) |factor| { + factor.deinit(allocator); + } + sols.deinit(); + } + + const len = sols.items.len; + if (len == 0) { + print("no solution for {}, {}, {}, {}\n", .{ nums[0], nums[1], nums[2], nums[3] }); + return; + } + + print("solutions for {}, {}, {}, {}\n", .{ nums[0], nums[1], nums[2], nums[3] }); + for (sols.items) |s| { + print("{s}\n", .{s.content}); + } + print("{} solutions found\n", .{len}); +} diff --git a/Task/24-game/FutureBasic/24-game.basic b/Task/24-game/FutureBasic/24-game.basic index 68da1c6faa..e3cb41f183 100644 --- a/Task/24-game/FutureBasic/24-game.basic +++ b/Task/24-game/FutureBasic/24-game.basic @@ -1,4 +1,4 @@ -include resources "24 Game Icon.icns" +//include resources "24 Game Icon.icns" #build CompilerOptions @"-Wno-unused-variable" diff --git a/Task/24-game/Rust/24-game.rs b/Task/24-game/Rust/24-game.rs index 8e9e7f0ced..149fb0aa62 100644 --- a/Task/24-game/Rust/24-game.rs +++ b/Task/24-game/Rust/24-game.rs @@ -43,7 +43,7 @@ fn to_rpn(input: &mut String){ rpn_string.push(top); } - println!("you formula results in {}", rpn_string); + println!("your formula results in {}", rpn_string); *input=rpn_string; } @@ -72,7 +72,7 @@ fn calculate(input: &String, list : &mut [u32;4]) -> f32{ }; } } - println!("you formula results in {}",accumulator); + println!("your formula results in {}",accumulator); accumulator } @@ -95,14 +95,14 @@ fn main() { to_rpn(&mut input); let result = calculate(&input, &mut list); - if list.iter().any(|&list| list !=10){ + if list.iter().any(|&num| num != 10) { + println!("you didn't use all the numbers"); + } else { println!("and you used all numbers"); match result { 24.0 => println!("you won"), - _ => println!("but your formulla doesn't result in 24"), + _ => println!("but your formula doesn't result in 24"), } - }else{ - println!("you didn't use all the numbers"); } } diff --git a/Task/9-billion-names-of-God-the-integer/REBOL/9-billion-names-of-god-the-integer.rebol b/Task/9-billion-names-of-God-the-integer/REBOL/9-billion-names-of-god-the-integer.rebol new file mode 100644 index 0000000000..4c937e4e34 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/REBOL/9-billion-names-of-god-the-integer.rebol @@ -0,0 +1,101 @@ +Rebol [ + title: "Rosetta code: 9 billion names of God the integer" + file: %9_billion_names_of_God_the_integer.r3 + url: https://rosettacode.org/wiki/9_billion_names_of_God_the_integer + needs: 3.0.0 + note: {Based on Red language version} +] +names-of-god: function/with [ + row [integer!] "row number (>= 1)" + /show "Display intermediate results" + /all "When showing, print all intermediate data" +][ + ;; Validate input - require row >= 1, otherwise trigger a runtime error + assert [row >= 1] + + ;; If /show refinement is used, display results for the given row + if show [ + ;; Ensure nums/:row is computed; if not, recursively compute it + unless nums/:row [names-of-god row] + + ;; Loop from 1 to row + repeat i row [ + either all [ ;; If /all refinement is used, display extra details + probe reduce [i nums/:i sums/:i] ;; Show index, sequence, and sum + ][ + print nums/:i ;; Otherwise, just print the sequence + ] + ] + ] + + ;; Compute a new row from scratch (if row not already computed)... + unless sum: sums/:row [ + out: clear [] ;; Temporary storage for row's elements + half: to integer! row / 2 ;; Middle position of the row + + ;; Ensure all required previous rows exist; generate missing ones + if row - 1 > last: length? nums [ + repeat i row - last - 1 [ + names-of-god last + i + ] + ] + + ;; Build the `out` block for this row + repeat col row - 1 [ + ;; Special case: the middle element + either col = (half + 1) [ + append out at nums/(row - 1) half ;; Insert from previous row's middle + break ;; Stop building here + ][ + ;; General case: append sum-part of two earlier sequences + append out sum-part nums/(row - col) col + ] + ] + + ;; Compute the sum of the row + sum: 0.0 + forall out [ + sum: sum + out/1 + ] + + ;; Cache the computed row and its sum + sums/:row: sum + nums/:row: copy out + clear out + ] + sums/:row ;; Return sum of the row +][ + ;; ===== WITH BLOCK (local helper definitions and persistent state) ===== + + ;; Helper function: sum the first `count` elements from the given block `nums` + sum-part: function [nums [block!] count [integer!]][ + out: 0.0 + loop count [ + out: out + nums/1 + if empty? nums: next nums [break] ;; Stop if we've exhausted the block + ] + ;; If within integer range, convert to integer + if out <= 0#7fffffffffffffff [out: to integer! out] + out + ] + + ;; Persistent storage for each computed row (map! with row → sequence) + ;; Start with base cases: + ;; row 1 = [1] + ;; row 2 = [1 1] + nums: make map! [1 [1] 2 [1 1]] + + ;; Persistent storage for row sums (map! with row → sum) + ;; Base sums: row 1 sum = 1, row 2 sum = 2 + sums: make map! [1 1 2 2] +] + + + +print "rows: ^/" +names-of-god/show 25 + +print "^/sums: ^/" +probe names-of-god 23 +probe names-of-god 123 +probe names-of-god 1234 diff --git a/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg b/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg index 5ec893ef5a..194eebdb25 100644 --- a/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg +++ b/Task/99-bottles-of-beer/ALGOL-68/99-bottles-of-beer.alg @@ -1,8 +1,10 @@ -main:( - FOR bottles FROM 99 TO 1 BY -1 DO - printf(($z-d" bottles of beer on the wall"l$, bottles)); - printf(($z-d" bottles of beer"l$, bottles)); - printf(($"Take one down, pass it around"l$)); - printf(($z-d" bottles of beer on the wall"ll$, bottles-1)) - OD -) +FOR bottles FROM 99 BY -1 TO 1 DO + STRING bottles now = whole(bottles,0) + " bottle" + IF bottles = 1 THEN "" ELSE "s" FI; + STRING bottles left = IF bottles = 1 THEN "No more" ELSE whole(bottles-1,0) FI + + " bottle" + + IF bottles = 2 THEN "" ELSE "s" FI; + print((bottles now," of beer on the wall",newline)); + print((bottles now," of beer",newline)); + print(("Take one down, pass it around",newline)); + print((bottles left," of beer on the wall",newline,newline)) +OD diff --git a/Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria b/Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria new file mode 100644 index 0000000000..7e36393581 --- /dev/null +++ b/Task/99-bottles-of-beer/Aria/99-bottles-of-beer.aria @@ -0,0 +1,48 @@ +struct Lyrics { + type func new(n: Int) { + assert n > 0; + return alloc(This) { + .n = n, + }; + } + + func prettyprint() { + val suffix_n = this.n == 1 ? "" : "s"; + val suffix_n_minus_1 = this.n == 2 ? "" : "s"; + return "{0} bottle{2} of beer on the wall, {0} bottle{2} of beer.\nTake one down and pass it around, {1} bottle{3} of beer on the wall.\n".format(this.n, this.n-1, suffix_n, suffix_n_minus_1); + } +} + +struct Song { + type func new(n: Int) { + assert n > 0; + return alloc(This) { + .n = n, + }; + } + + func iterator() { + return this; + } + + func next() { + if this.n == 0 { + return Box(){.done = true}; + } + + val n = this.n; + this.n -= 1; + + return Box() { + .done = false, + .value = Lyrics.new(n), + }; + } +} + +func main() { + val song = Song.new(99); + for verse in song { + println(verse); + } +} diff --git a/Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark b/Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark new file mode 100644 index 0000000000..d12274823c --- /dev/null +++ b/Task/99-bottles-of-beer/ArkScript/99-bottles-of-beer.ark @@ -0,0 +1,24 @@ +# try and get an argument from the command line invocation +(let arg + (if (>= (len sys:args) 1) + (toNumber (@ sys:args 0)) + nil)) +# if no argument was passed the default value will be 100 +(let i + (if (nil? arg) + 100 + arg)) + +(let explode-bottles (fun (n) + (if (> n 1) { + (print (string:format "{} Bottles of beer on the wall\n{} bottles of beer\nTake one down, pass it around" n n)) + (print (string:format "{} Bottles of beer on the wall." (- n 1))) + (explode-bottles (- n 1)) }) +(explode-bottles i) + +# alternative solution with a loop +(mut n i) +(while (> n 1) { + (print (string:format "{} Bottles of beer on the wall\n{} bottles of beer\nTake one down, pass it around" n n)) + (set n (- n 1)) + (print (string:format "{} Bottles of beer on the wall." n)) }) diff --git a/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb new file mode 100644 index 0000000000..3fe002df2b --- /dev/null +++ b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-1.duckdb @@ -0,0 +1,13 @@ +.header off +.mode list +select list_transform( range(99,-1,-1), + n -> + if (n = 0, + 'No more bottles of beer on the wall' || chr(10) + || 'no more bottles of beer.' || chr(10) + || 'Go to the store, buy some more!' || chr(10) + || '99 bottles of beer on the wall.', + n || ' bottle' || if ( n = 1, '', 's') || ' of beer on the wall' || chr(10) + || n || ' bottle' || if ( n = 1, '', 's') || ' of beer;' || chr(10) + || 'Take one down, pass it around' || chr(10) ) ) + .array_to_string(chr(10)) ; diff --git a/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb new file mode 100644 index 0000000000..02dd9eb97c --- /dev/null +++ b/Task/99-bottles-of-beer/DuckDB/99-bottles-of-beer-2.duckdb @@ -0,0 +1,21 @@ +.header off +.mode list + +with recursive cte as ( + select 99 as n, '' as s + union all + select n-1 as n, + if (n = 0, + 'No more bottles of beer on the wall' || chr(10) + || 'no more bottles of beer.' || chr(10) + || 'Go to the store, buy some more!' || chr(10) + || '99 bottles of beer on the wall.', + n || ' bottle' || if ( n = 1, '', 's') || ' of beer on the wall' || chr(10) + || n || ' bottle' || if ( n = 1, '', 's') || ' of beer;' || chr(10) + || 'Take one down, pass it around' || chr(10) ) + from cte + where n > -1 + ) select s + from cte + where s != '' + order by n desc ; diff --git a/Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto b/Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto new file mode 100644 index 0000000000..1e20d4e1f4 --- /dev/null +++ b/Task/99-bottles-of-beer/Pluto/99-bottles-of-beer.pluto @@ -0,0 +1,12 @@ +function pl(n) return n==1?"":"s" end + +function fmt(s) + return $"{s} bottle{pl(s)} of beer on the wall, \n" .. + $"{s} bottle{pl(s)} of beer. \n" .. + $"Take one down, pass it around, \n" .. + $"{s-1} bottle{pl(s-1)} of beer on the wall.\n\n" +end + +for i = 99, 1, -1 do + print(fmt(i)) +end diff --git a/Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus b/Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus new file mode 100644 index 0000000000..b7564c4ae9 --- /dev/null +++ b/Task/99-bottles-of-beer/Rhombus/99-bottles-of-beer.rhombus @@ -0,0 +1,13 @@ +#lang rhombus/static + +for (i in 1..100): + fun plural(n :: Int): + if n == 1: + | "" + | "s" + let bottles = 100 - i + println(@str{@(bottles) bottle@(plural(bottles)) of beer on the wall, @(bottles) bottle@(plural(bottles)) of beer.}) + println(@str{Take one down and pass it around, @(bottles - 1) bottle@(plural(bottles - 1)) of beer on the wall.}) + +println("No more bottles of beer on the wall, no more bottles of beer.") +println("Go to the store and buy some more, 99 bottles of beer on the wall.") diff --git a/Task/A+B/Agena/a+b.agena b/Task/A+B/Agena/a+b.agena index 5b94875c68..0ac7496582 100644 --- a/Task/A+B/Agena/a+b.agena +++ b/Task/A+B/Agena/a+b.agena @@ -1,6 +1,10 @@ scope local f := trim( io.read() ) split " "; # read a line and split into fields - local a := tonumber( f[ 1 ] ); - local b := tonumber( f[ 2 ] ); - print( a + b ) -epocs + try + local a := tonumber( f[ 1 ] ); + local b := tonumber( f[ 2 ] ); + print( a + b ) + catch in ex then + print( "Unable to add the numbers: ", tostring( ex ) ) + yrt +end diff --git a/Task/A+B/ArkScript/a+b.ark b/Task/A+B/ArkScript/a+b.ark new file mode 100644 index 0000000000..71c47670c9 --- /dev/null +++ b/Task/A+B/ArkScript/a+b.ark @@ -0,0 +1,9 @@ +(import std.String :split) +(import std.List :map :reduce) + +(let in (input)) +(let numbers (map (split in " ") (fun (t) (toNumber t)))) +(print (reduce numbers (fun (a b) + (if (nil? b) + a + (+ a b))))) diff --git a/Task/A+B/DuckDB/a+b-1.duckdb b/Task/A+B/DuckDB/a+b-1.duckdb new file mode 100644 index 0000000000..06fc2868f4 --- /dev/null +++ b/Task/A+B/DuckDB/a+b-1.duckdb @@ -0,0 +1,5 @@ +.headers off +.mode list +select sum(c::INTEGER) +from (select unnest(regexp_extract_all(content, '[-0-9]+') ) as c + from read_text('rc-a+b.txt') ); diff --git a/Task/A+B/DuckDB/a+b-2.duckdb b/Task/A+B/DuckDB/a+b-2.duckdb new file mode 100644 index 0000000000..ce4c1aa6c7 --- /dev/null +++ b/Task/A+B/DuckDB/a+b-2.duckdb @@ -0,0 +1,2 @@ +select a+b from (select column0 as a, column1 as b +from read_csv('/dev/stdin', header=false, sep=' ')); diff --git a/Task/A+B/Koka/a+b.koka b/Task/A+B/Koka/a+b.koka new file mode 100644 index 0000000000..f0f1738e2d --- /dev/null +++ b/Task/A+B/Koka/a+b.koka @@ -0,0 +1,32 @@ +import std/os/readline + +// A prompt effect which retries getting input until a valid result is returned. +effect prompt + ctl delimit(): () // Captures the retry resumption + final ctl fail(): e // A failed input + +// Prompt for input, with retry until successful result +// - `message` is the original prompt +// - `err-message` is the error shown on failure +fun prompt(message: string, err-message: string, action: (string) -> a): a + var reattempt := fn() impossible() // We ensure all paths include a delimiter + with handler + raw ctl delimit() + reattempt := (fn() rcontext.resume(())) // set reattempt resumption + reattempt() // Initial try + final ctl fail() + reattempt() // Handle failure by reattempting + // Print the initial request message + println(message) + delimit() // Mark retry point + try { + action(readline()) // Read the input and apply the action + } fn(err) + // On an exception, print the error message and retry + println(err-message) + fail() // reset + +fun main() + with line <- prompt("Enter two numbers separated by space: ", "Invalid input, please enter two integers.") + val [a, b] = line.split(" ") + a.parse-int.unjust + b.parse-int.unjust diff --git a/Task/A+B/Pluto/a+b.pluto b/Task/A+B/Pluto/a+b.pluto new file mode 100644 index 0000000000..974f2e0a29 --- /dev/null +++ b/Task/A+B/Pluto/a+b.pluto @@ -0,0 +1,2 @@ +a, b = io.read("*n", "*n") +print(a+b) diff --git a/Task/A+B/TAV/a+b.tav b/Task/A+B/TAV/a+b.tav new file mode 100644 index 0000000000..29b223afca --- /dev/null +++ b/Task/A+B/TAV/a+b.tav @@ -0,0 +1,6 @@ +main(parms):+ + ?# lne =: file () give lines \ void is standard input + ab =: string lne split by many of #Whitespace + a =: string ab[1] as integer + b =: string ab[2] as integer + print a + b diff --git a/Task/ABC-problem/DuckDB/abc-problem.duckdb b/Task/ABC-problem/DuckDB/abc-problem.duckdb new file mode 100644 index 0000000000..0856cd977f --- /dev/null +++ b/Task/ABC-problem/DuckDB/abc-problem.duckdb @@ -0,0 +1,45 @@ +CREATE OR REPLACE FUNCTION matches(block, letter) as ( + block[1] = letter or block[2] = letter +); + +# permute(lst, n, word) generates sub-permutations, perm (of length n), of the list lst, +# that satisfy matches(perm[i], word[i]), for i in range(1, n+1). +# Normally n = length(word). +# The caller is responsible for ensuring appropriate adjustment of typographical case. +CREATE OR REPLACE FUNCTION permute(lst, n, word) as table ( + WITH RECURSIVE permute(perm, remaining) as ( + -- base case + SELECT + []::VARCHAR[] as perm, + lst::VARCHAR[] as remaining + UNION ALL + -- recursive case: add one element from remaining to perm and remove it from remaining + SELECT + (perm || [element]) AS perm, + (remaining[1:i-1] || remaining[i+1:]) AS remaining + FROM (select *, unnest(remaining) AS element, generate_subscripts(remaining,1) as i + FROM permute) + WHERE length(perm) < n + and matches(element, word[1 + length(perm)]) + ) + SELECT perm + FROM permute + WHERE length(perm) = n +); + +# All solutions +CREATE OR REPLACE FUNCTION solve(word) as table ( + from permute( + ['BO', 'XK', 'DQ', 'CP', 'NA', 'GT', 'RE', 'TG', 'QD', 'FS', + 'JW', 'HU', 'VI', 'AN', 'OB', 'ER', 'FS', 'LY', 'PC', 'ZM'], + length(word), upper(word) ) +); + +CREATE OR REPLACE FUNCTION one_solution(word) as ( + from solve(word) + limit 1 +); + +# Examples +select word, one_solution(word) +from (select unnest(['','A','BarK','BOOK','TREAT','COMMON','SQUAD','Confuse','abba']) as word); diff --git a/Task/ABC-problem/Pluto/abc-problem.pluto b/Task/ABC-problem/Pluto/abc-problem.pluto new file mode 100644 index 0000000000..243a9a5f79 --- /dev/null +++ b/Task/ABC-problem/Pluto/abc-problem.pluto @@ -0,0 +1,25 @@ +function r(word, bl) + if word == "" then return true end + local c = word:byte(1) | 32 + for i = 1, #bl do + local b = bl[i] + if c == b:byte(1) | 32 or c == b:byte(2) | 32 then + bl[i] = bl[1] + bl[1] = b + if r(word:sub(2), bl:slice(2)) then return true end + bl[1], bl[i] = bl[i], bl[1] + end + end + return false +end + +local function new_speller(blocks) + local bl = blocks:split(" ") + return |word| -> r(word, bl) +end + +local sp = new_speller("BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM") +local words = {"A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} +for words as word do + print(string.format("%-7s %s", word, sp(word))) +end diff --git a/Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic b/Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic new file mode 100644 index 0000000000..547da20116 --- /dev/null +++ b/Task/AKS-test-for-primes/ANSI-BASIC/aks-test-for-primes.basic @@ -0,0 +1,79 @@ +100 REM AKS test for primes +110 DECLARE EXTERNAL SUB PascalTriangle +120 DECLARE EXTERNAL SUB ExpandPoly +130 DECLARE EXTERNAL FUNCTION IsPrime +140 FOR N = 0 TO 9 +150 CALL ExpandPoly(N) +160 NEXT N +170 FOR N = 2 TO 50 +180 IF IsPrime(N) <> 0 THEN PRINT USING("###"): N; +190 NEXT N +200 PRINT +210 END +220 REM ** +230 EXTERNAL SUB PascalTriangle(N, PasTri()) +240 REM Calculate t!he N'th line 0.. middle +250 LET N = INT(N) +260 LET PasTri(0) = 1 +270 LET J = 1 +280 DO WHILE J <= N +290 LET J = J + 1 +300 LET K = INT(J / 2) +310 LET PasTri(K) = PasTri(K - 1) +320 FOR K = K TO 1 STEP -1 +330 LET PasTri(K) = PasTri(K) + PasTri(K - 1) +340 NEXT K +350 LOOP +360 END SUB +370 REM ** +380 EXTERNAL FUNCTION IsPrime(N) +390 LET N = INT(N) +400 DIM PasTri(0 TO 50) +410 LET PasTriMax = UBOUND(PasTri) +420 IF N > PasTriMax THEN +430 PRINT N; "is out of range" +440 STOP +450 END IF +460 CALL PascalTriangle(N, PasTri) +470 LET Res = 1 +480 LET I = INT(N / 2) +490 DO WHILE (Res <> 0) AND (I > 1) +500 IF (Res <> 0) AND (MOD(PasTri(I), N) = 0) THEN LET Res = 1 ELSE LET Res = 0 +510 LET I = I - 1 +520 LOOP +530 LET IsPrime = Res +540 END FUNCTION +550 REM ** +560 EXTERNAL SUB ExpandPoly(N) +570 LET N = INT(N) +580 DIM VZ$(0 TO 1) +590 LET VZ$(0) = "+" +600 LET VZ$(1) = "-" +610 DIM PasTri(0 TO 50) +620 LET PasTriMax = UBOUND(PasTri) +630 IF N > PasTriMax THEN +640 PRINT N; "is out of range" +650 STOP +660 END IF +670 SELECT CASE N +680 CASE 0 +690 PRINT "(x - 1) ^ 0 = 1" +700 CASE 1 +710 PRINT "(x - 1) ^ 1 = x - 1" +720 CASE ELSE +730 CALL PascalTriangle(N, PasTri) +740 PRINT "(x - 1) ^"; N; " = x ^"; N; +750 LET BVZ = 1 +760 FOR J = N - 1 TO INT(N / 2) + 1 STEP -1 +770 PRINT VZ$(BVZ); PasTri(N - J); "* x ^"; J; +780 LET BVZ = ABS(1 - BVZ) +790 NEXT J +800 FOR J = INT(N / 2) TO 2 STEP -1 +810 PRINT VZ$(BVZ); PasTri(J); "* x ^"; J; +820 LET BVZ = ABS(1 - BVZ) +830 NEXT J +840 PRINT VZ$(BVZ); PasTri(1); "* x "; +850 LET BVZ = ABS(1 - BVZ) +860 PRINT VZ$(BVZ); PasTri(0) +870 END SELECT +880 END SUB diff --git a/Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena b/Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena new file mode 100644 index 0000000000..6589095e8f --- /dev/null +++ b/Task/AKS-test-for-primes/Agena/aks-test-for-primes.agena @@ -0,0 +1,89 @@ +# AKS test for primes + +constant pas_tri_max := 50; + +proc pascal_triangle(n :: posint) is +# Calculate the n'th line 1.. middle +# For n = 1, 2, .. + create register pas_tri((n + 1) \ 2); + # pas_tri[0] always is 1 + j := 1; + case n + of 1, 2 then pas_tri[1] := 2 + else + j := 3; + pas_tri[1] := 2; + while j <= n do + j++; + k := j \ 2; # middle + pas_tri[k] := pas_tri[k - 1]; + while k >= 2 do + pas_tri[k] +:= pas_tri[k - 1]; + k-- + od; + pas_tri[1] +:= 1 + od + esle + esac + return pas_tri +end; + +proc is_prime(n :: nonnegint) :: boolean is + if n > pas_tri_max then + printf("%d is out of range\n", n); + os.exit(-1) + fi; + pas_tri := pascal_triangle(n); + res := true; + i := n \ 2; + while res and (i > 1) do + res := res and (pas_tri[i] symmod n = 0); + i-- + od; + return res +end; + +proc vz(b :: boolean) is + return if b then '-' else '+' fi +end; + +proc expand_poly(n :: nonnegint) is + if n > pas_tri_max then + printf("%d is out of range\n", n); + os.exit(-1) + fi; + case n + of 0 then printf("(x-1)^0 = 1\n"); + of 1 then printf("(x-1)^1 = x-1\n"); + else + pas_tri := pascal_triangle(n); + printf("(x-1)^%d = x^%d", n, n); + bvz := true; + n_div_2 := n \ 2 + for j from n - 1 to n_div_2 + 1 by -1 do + printf("%s%d*x^%d", vz(bvz), pas_tri[n - j], j); + bvz := not bvz + od; + for j from n_div_2 to 2 by -1 do + printf("%s%d*x^%d", vz(bvz), pas_tri[j], j); + bvz := not bvz + od; + printf("%s%d*x", vz(bvz), pas_tri[1]); + bvz := not bvz; + printf("%s1\n", vz(bvz)); + esle + esac +end; + +scope + local n; + for n from 0 to 9 do + expand_poly(n) + od; + for n from 2 to pas_tri_max do + if is_prime(n) then + printf("%3d", n) + fi + od; + printf("\n") +end diff --git a/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy b/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy new file mode 100644 index 0000000000..54fc26429d --- /dev/null +++ b/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy @@ -0,0 +1,43 @@ +func[] coefs n . + list[] = [ 1 ] + arrbase list[] 0 + for k = 0 to n : list[] &= list[k] * (n - k) / (k + 1) + for k = 1 step 2 to n : list[k] = -list[k] + return list[] +. +func isprimeaks n . + c[] = coefs n + c[0] -= 1 + c[n] += 1 + for i = 0 to n + if c[i] mod n <> 0 : return 0 + . + return 1 +. +proc pprintcoefs n list[] . + for i = 0 to n + s$ = "" + if i > 0 + s$ = " + " + if list[i] < 0 : s$ = " - " + . + c$ = abs list[i] + e = n - i + if c$ = "1" and e > 0 : c$ = "" + x$ = "" + if e <> 0 + x$ = "x" + if e <> 1 : x$ &= "^" & e + . + r$ &= s$ & c$ & x$ + . + print "(x-1)^" & n & " : " & r$ +. +for i = 0 to 7 + pprintcoefs i coefs i +. +print "" +for i = 2 to 49 + if isprimeaks i = 1 : write i & " " +. +print "" diff --git a/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic b/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic index c94e8f7494..72bc4196df 100644 --- a/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic +++ b/Task/AKS-test-for-primes/FutureBasic/aks-test-for-primes.basic @@ -1,6 +1,5 @@ // AKS Test for Primes task // https://rosettacode.org/wiki/AKS_test_for_primes -// Translated from Yabasic to FutureBASIC #build ShowMoreWarnings NO diff --git a/Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2 b/Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2 new file mode 100644 index 0000000000..a138aea166 --- /dev/null +++ b/Task/AKS-test-for-primes/Modula-2/aks-test-for-primes.mod2 @@ -0,0 +1,119 @@ +MODULE AKSTest; +(* AKS test for primes *) + +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +CONST + PasTriMax = 33; (* for 32-bit integer type *) + +TYPE + TPasTri = ARRAY [0 .. PasTriMax] OF CARDINAL; + +VAR + N: CARDINAL; + +PROCEDURE PascalTriangle(N: CARDINAL; VAR PasTri: TPasTri); +(* Calculate the N'th line 0.. middle *) +VAR + J, K: CARDINAL; +BEGIN + PasTri[0] := 1; + J := 1; + WHILE J <= N DO + J := J + 1; + K := J DIV 2; + PasTri[K] := PasTri[K - 1]; + FOR K := K TO 1 BY -1 DO + PasTri[K] := PasTri[K] + PasTri[K - 1]; + END + END +END PascalTriangle; + +PROCEDURE IsPrime(N: CARDINAL): BOOLEAN; +VAR + Res : BOOLEAN; + I : CARDINAL; + PasTri: TPasTri; +BEGIN + IF N > PasTriMax THEN + WriteInt(N, 1); + WriteString(" is out of range"); + WriteLn; + HALT; + END; + PascalTriangle(N, PasTri); + Res := TRUE; + I := N DIV 2; + WHILE Res AND (I > 1) DO + Res := Res AND (PasTri[I] MOD N = 0); + I := I - 1 + END; + RETURN Res; +END IsPrime; + +PROCEDURE ExpandPoly(N: CARDINAL); +TYPE + TVZ = ARRAY BOOLEAN OF CHAR; +CONST + VZ = TVZ {'+', '-'}; +VAR + J : CARDINAL; + BVZ : BOOLEAN; + PasTri: TPasTri; +BEGIN + IF N > PasTriMax THEN + WriteInt(N, 1); + WriteString(" is out of range"); + WriteLn; + HALT + END; + CASE N OF + | 0: + WriteString("(x-1)^0 = 1"); WriteLn; + | 1: + WriteString("(x-1)^1 = x-1"); WriteLn; + ELSE + PascalTriangle(N, PasTri); + WriteString("(x-1)^"); + WriteInt(N, 1); + WriteString(" = x^"); + WriteInt(N, 1); + BVZ := TRUE; + FOR J := N - 1 TO N DIV 2 + 1 BY -1 DO + WriteString(VZ[BVZ]); + WriteInt(PasTri[N - J], 1); + WriteString("*x^"); + WriteInt(J, 1); + BVZ := NOT BVZ + END; + FOR J := N DIV 2 TO 2 BY -1 DO + WriteString(VZ[BVZ]); + WriteInt(PasTri[J], 1); + WriteString("*x^"); + WriteInt(J, 1); + BVZ := NOT BVZ + END; + WriteString(VZ[BVZ]); + WriteInt(PasTri[1], 1); + WriteString("*x"); + BVZ := NOT BVZ; + WriteString(VZ[BVZ]); + WriteInt(PasTri[0], 1); + WriteLn; + END; +END ExpandPoly; + +BEGIN + FOR N := 0 TO 9 DO + ExpandPoly(N) + END; + FOR N := 2 TO PasTriMax DO + IF IsPrime(N) THEN + WriteInt(N, 3) + END + END; + WriteLn; +END AKSTest. diff --git a/Task/AKS-test-for-primes/PHP/aks-test-for-primes.php b/Task/AKS-test-for-primes/PHP/aks-test-for-primes.php new file mode 100644 index 0000000000..9b3e9bbaa4 --- /dev/null +++ b/Task/AKS-test-for-primes/PHP/aks-test-for-primes.php @@ -0,0 +1,80 @@ + PAS_TRI_MAX) { + echo $n, " is out of range", PHP_EOL; + exit; + } + switch ($n) { + case 0: + echo "(x-1)^0 = 1", PHP_EOL; + break; + case 1: + echo "(x-1)^1 = x-1", PHP_EOL; + break; + default: + $pas_tri = []; + pascal_triangle($n, $pas_tri); + echo "(x-1)^", $n, " = x^", $n; + $bvz = true; + $n_div_2 = intdiv($n, 2); + for ($j = $n - 1; $j > $n_div_2; $j--) { + echo vz($bvz), $pas_tri[$n - $j], "*x^", $j; + $bvz = !$bvz; + } + for ($j = $n_div_2; $j >= 2; $j--) { + echo vz($bvz), $pas_tri[$j], "*x^", $j; + $bvz = !$bvz; + } + echo vz($bvz), $pas_tri[1], "*x"; + $bvz = !$bvz; + echo vz($bvz), $pas_tri[0], PHP_EOL; + } +} + +function pascal_triangle($n, &$pas_tri) { +// Calculate the $n'th line 0.. middle + $pas_tri = array_fill(0, intdiv($n + 1, 2) + 1, 0); + $pas_tri[0] = 1; + $j = 1; + while ($j <= $n) { + $j++; + $k = intdiv($j, 2); + $pas_tri[$k] = $pas_tri[$k - 1]; + while ($k >= 1) { + $pas_tri[$k] += $pas_tri[$k - 1]; + $k--; + } + } +} + +function is_prime($n):bool { + if ($n > PAS_TRI_MAX) { + echo $n, " is out of range", PHP_EOL; + exit; + } + $pas_tri = []; + pascal_triangle($n, $pas_tri); + $res = true; + $i = intdiv($n, 2); + while ($res && ($i > 1)) { + $res = $res && ($pas_tri[$i] % $n == 0); + --$i; + } + return $res; +} + +for ($n = 0; $n <= 9; $n++) + expand_poly($n); +for ($n = 2; $n <= PAS_TRI_MAX; $n++) + if (is_prime($n)) + echo str_pad($n, 3, " ", STR_PAD_LEFT); +echo PHP_EOL; +?> diff --git a/Task/AKS-test-for-primes/Pluto/aks-test-for-primes.pluto b/Task/AKS-test-for-primes/Pluto/aks-test-for-primes.pluto new file mode 100644 index 0000000000..382e876965 --- /dev/null +++ b/Task/AKS-test-for-primes/Pluto/aks-test-for-primes.pluto @@ -0,0 +1,90 @@ +do -- "AKS test for promes" task - translated from the Algol 68 sample + + local bigint = require "pluto:bigint" + local b0, b1 = new bigint( 0 ), new bigint( 1 ) + --[[ + Mathematical preliminaries. + + First note that the homogeneous polynomial (a+b)^n is symmetrical + (to see this just swap the variables a and b). Therefore its + coefficients need be calculated only to that of (ab)^{n/2} for even + n or (ab)^{(n-1)/2} for odd n. + + Second, the coefficients are the binomial coefficients C(n,k) where + the coefficient of a^k b^(n-k) is C(n,k) = n! / k! (k-1)!. This + leads to an immediate and relatively efficient implementation for + which we do not need to compute n! before dividing by k! and (k-1)! + but, rather cancel common factors as we go along. Further, the + well-known symmetry identity C(n,k) = C(n, n-k) allows a + significant reduction in computational effort. + + Third, (x-1)^n is the value of (a + b)^n when a=x and b = -1. The + powers of -1 alternate between +1 and -1 so we may as well compute + (x+1)^n and negate every other coefficient when printing. + ]] + + local function choose( n, k ) + local result = b1 + local symK = if k >= n//2 then n-k else k end -- Use symmetry + if symK > 0 then + local iPlus1 = b1 + local nMinusI = new bigint( n ) + for _ = 0, symK-1 do + result *= nMinusI + result /= iPlus1 + iPlus1 += b1 + nMinusI -= b1 + end + end + return result + end + local function coefficients( n ) + local a = {} + for i = 0, n//2 do + a[i] = choose( n, i ) + a[n-i] = a[i] -- Use symmetry + end + return a + end + --[[ + First print the polynomials (x-1)^n, remembering to alternate signs + and to tidy up the constant term, the x^1 term and the x^n term. + This means we must treat (x-1)^0 and (x-1)^1 specially + ]] + for n = 0,7 do + local a = coefficients( n ) + io.write( "(x-1)^"..n.." = " ) + switch n do + case 0: io.write( tostring( a[0] ) ) break + case 1: io.write( "x - "..tostring( a[1] ) ) break + default: io.write( "x^"..n ) + for i = 1,n-2 do + local ai = tostring( a[i] ) + io.write( if i % 2 == 1 then " - " else " + " end..ai.."x^"..(n-i) ) + end + io.write( if ( n - 1 ) % 2 == 1 then " - " else " + " end..tostring( a[n-1] ).."x" ) + io.write( if n % 2 == 1 then " - " else " + " end..tostring( a[n] ) ) + end + io.write( "\n" ) + end + --[[ + Finally, for the "AKS" portion of the task, the sign of the + coefficient has no effect on its divisibility by p so, once again, + we may as well use the positive coefficients. Symmetry clearly + reduces the necessary number of tests by a factor of two. + ]] + local function isPrime( n ) + local prime = true + local bn = new bigint( n ) + for i = 1,n//2 do + prime = choose( n, i ) % bn == b0 + if not prime then return false end + end + return true + end + io.write( "Primes between 1 and 50 are:" ) + for n = 2,50 do if isPrime(n) then io.write( " "..n ) end end + io.write( "\nPrimes between 900 and 1000 are:") + for n = 900,1000 do if isPrime(n) then io.write( " "..n ) end end + io.write( "\n" ) +end diff --git a/Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.psh b/Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.psh new file mode 100644 index 0000000000..c79bcdf5e7 --- /dev/null +++ b/Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.psh @@ -0,0 +1,84 @@ +# AKS test for primes + +$script:PasTriMax = 61 # for long type of Pascal triangle numbers + +function Pascal-Triangle { + # Calculate the n'th line 0.. middle + param( + [int]$N + ) + + $pasTri = [long[]]::new([math]::Ceiling(($N + 2) / 2)) + $pasTri[0] = 1 + [int]$j = 1 + while ($j -le $N) { + $j++ + [int]$k = [math]::Floor($j / 2) + $pasTri[$k] = $pasTri[$k - 1] + for (; $k -ge 1; $k--) { + $pasTri[$k] += $pasTri[$k - 1] + } + } + # Now: $j -eq ($N + 1), so $k -eq [math]::Floor(($N + 1) / 2) + return $pasTri +} + +function Expand-Poly { + param ([int]$N) + + if ($N -gt $script:PasTriMax) { + throw "$N is out of range" + } + switch($N) { + 0 {Write-Output "(x-1)^0 = 1"} + 1 {Write-Output "(x-1)^1 = x-1"} + default { + $VZ = @('+', '-') + $pasTri = Pascal-Triangle($N) + [string]$outTri = @() + $outTri += "(x-1)^$N = x^$N" + [bool]$bVz = $true + [int]$nDiv2 = [math]::Floor($N / 2) + for ([int]$j = $N - 1; $j -gt $nDiv2; $j--) { + $outTri += "$($VZ[$bVz]) $($pasTri[$N - $j])*x^$j" + $bVz = -not $bVz + } + for ([int]$j = $nDiv2; $j -gt 1; $j--) { + $outTri += "$($VZ[$bVz]) $($pasTri[$j])*x^$j" + $bVz = -not $bVz + } + $outTri += "$($VZ[$bVz]) $($pasTri[1])*x" + $bVz = -not $bVz + $outTri += "$($VZ[$bVz]) $($pasTri[0])" + Write-Output $outTri + } + } +} + +function Is-Prime { + param([int]$N) + + if ($N -gt $script:PasTriMax) { + throw "$N is out of range" + } + $pasTri = Pascal-Triangle($N) + [bool]$res = $true + [int]$i = [math]::Floor($N / 2) + while ($res -and ($i -gt 1)) { + $res = $res -and ($pasTri[$i] % $N -eq 0) + $i-- + } + return $res +} + +# Test program +foreach ($n in 0..9) { + Expand-Poly($n) +} +[string]$primes = @() +foreach ($n in 2..$script:PasTriMax) { + if (Is-Prime($n)) { + $primes += "{0,3}" -f $n + } +} +Write-Output $primes diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx index 1942f69672..80afc0c295 100644 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx @@ -1,12 +1,12 @@ --- 22 Mar 2025 +-- 28 Jul 2025 include Settings +arg p +if p = '' then + p = 10 say 'AKS TEST FOR PRIMES' say version say -arg p -if p = '' then - p = 10 numeric digits Max(10,Abs(p)%3) call Combis p call Polynomials p @@ -37,9 +37,9 @@ else b = 0 p = Abs(p); prim. = 0; n = 0 do i = b to p - a = Ppow('1 -1',i) + a = PowP('1 -1',i) if i < 11 then - say '(x-1)^'i '=' Plst2form(Parr2lst()) + say '(x-1)^'i '=' Lst2FormP(Arr2LstP()) s = 1 do j = 2 to poly.0-1 a = poly.coef.j @@ -84,8 +84,4 @@ say Format(Time('e'),,3) 'seconds' say return -include Functions -include Numbers -include Polynomial -include Sequences -include Abend +include Math diff --git a/Task/AKS-test-for-primes/XBasic/aks-test-for-primes.basic b/Task/AKS-test-for-primes/XBasic/aks-test-for-primes.basic new file mode 100644 index 0000000000..ee9baae9d6 --- /dev/null +++ b/Task/AKS-test-for-primes/XBasic/aks-test-for-primes.basic @@ -0,0 +1,84 @@ +PROGRAM "akstest" +' AKS test for primes + +DECLARE FUNCTION Entry () +INTERNAL FUNCTION ExpandPoly(n@@) +INTERNAL FUNCTION PascalTriangle(n@@, @pasTri&&[]) +INTERNAL FUNCTION IsPrime(n@@) +INTERNAL FUNCTION Vz$(b@) +$$PasTriMax = 33 ' for 32-bit integer type + +FUNCTION Entry() + FOR n@@ = 0 TO 9 + ExpandPoly(n@@) + NEXT + FOR n@@ = 2 TO $$PasTriMax + IF IsPrime(n@@) THEN PRINT FORMAT$("###", n@@); + NEXT + PRINT +END FUNCTION + +FUNCTION ExpandPoly(n@@) + DIM pasTri&&[$$PasTriMax] + IF n@@ > $$PasTriMax THEN + PRINT n@@; " is out of range" + QUIT(1) + END IF + SELECT CASE n@@ + CASE 0: + PRINT "(x - 1) ^ 0 = 1" + CASE 1: + PRINT "(x - 1) ^ 1 = x - 1" + CASE ELSE: + PascalTriangle(n@@, @pasTri&&[]) + PRINT "(x - 1) ^"; n@@; " = x ^"; n@@; + bVz@ = $$TRUE + FOR j@@ = n@@ - 1 TO n@@ \ 2 + 1 STEP -1 + PRINT " "; Vz$(bVz@); pasTri&&[n@@ - j@@]; " * x ^"; j@@; + bVz@ = NOT bVz@ + NEXT + FOR j@@ = n@@ \ 2 TO 2 STEP -1 + PRINT " "; Vz$(bVz@); pasTri&&[j@@]; " * x ^"; j@@; + bVz@ = NOT bVz@ + NEXT + PRINT " "; Vz$(bVz@); pasTri&&[1]; " * x "; + bVz@ = NOT bVz@ + PRINT Vz$(bVz@); pasTri&&[0] + END SELECT + +END FUNCTION + +FUNCTION PascalTriangle(n@@, @pasTri&&[]) +' Calculate the n@@'th line 0.. middle + pasTri&&[0] = 1 + j@@ = 1 + DO WHILE j@@ <= n@@ + INC j@@ + k@@ = j@@ \ 2 + pasTri&&[k@@] = pasTri&&[k@@ - 1] + FOR k@@ = k@@ TO 1 STEP -1 + pasTri&&[k@@] = pasTri&&[k@@] + pasTri&&[k@@ - 1] + NEXT + LOOP +END FUNCTION + +FUNCTION IsPrime(n@@) + DIM pasTri&&[$$PasTriMax] + IF n@@ > $$PasTriMax THEN + PRINT n@@; " is out of range" + QUIT(1) + END IF + PascalTriangle(n@@, @pasTri&&[]) + res@ = $$TRUE + i@@ = n@@ \ 2 + DO WHILE res@ AND (i@@ > 1) + res@ = res@ AND (pasTri&&[i@@] MOD n@@ = 0) + DEC i@@ + LOOP + RETURN res@ +END FUNCTION + +FUNCTION Vz$(b@) + IF b@ THEN RETURN "-" ELSE RETURN "+" +END FUNCTION +END PROGRAM diff --git a/Task/AKS-test-for-primes/XPL0/aks-test-for-primes.xpl0 b/Task/AKS-test-for-primes/XPL0/aks-test-for-primes.xpl0 new file mode 100644 index 0000000000..a60bd11dec --- /dev/null +++ b/Task/AKS-test-for-primes/XPL0/aks-test-for-primes.xpl0 @@ -0,0 +1,105 @@ +\AKS test for primes +code Rem=2, ChOut=8, CrLf=9, Text=12, IntOut=11; +code real RlOut=48, Float=49, Format=52; +define PasTriMax = 33; \for 32-bit integer type +integer N; + + procedure PascalTriangle(N, PasTri); + \Calculate the N'th line 0.. middle + integer N, PasTri; + integer J, K; + begin + PasTri(0):= 1; + J:= 1; + while J <= N do + begin + J:= J + 1; + K:= J / 2; + PasTri(K):= PasTri(K - 1); + for K:= K downto 1 do PasTri(K):= PasTri(K) + PasTri(K - 1) + end \while + end; + + function integer IsPrime(N); + integer N; + integer Res, I, PasTri(PasTriMax + 1); + begin + if N > PasTriMax then + begin + IntOut(0, N); + Text(0, " is out of range"); + CrLf(0); + exit; + end; + PascalTriangle(N, PasTri); + Res:= true; + I:= N / 2; + while Res & (I > 1) do + begin + Res:= Res & (Rem(PasTri(I) / N) = 0); + I:= I - 1 + end; + return Res; + end; + + procedure ExpandPoly(N); + integer N; + integer J, BVZ, PasTri(PasTriMax + 1); + + procedure VZOut(D, B); + integer D, B; + begin + if B then ChOut(D, ^-) else ChOut(D, ^+) + end; + + begin + if N > PasTriMax then + begin + IntOut(0, N); + Text(0, " is out of range"); + CrLf(0); + exit + end; + case N of + 0: [Text(0, "(x-1)^^0 = 1"); CrLf(0)]; + 1: [Text(0, "(x-1)^^1 = x-1"); CrLf(0)] + other + begin + PascalTriangle(N, PasTri); + Text(0, "(x-1)^^"); + IntOut(0, N); + Text(0, " = x^^"); + IntOut(0, N); + BVZ:= true; + for J:= N - 1 downto N / 2 + 1 do + begin + VZOut(0, BVZ); + IntOut(0, PasTri(N - J)); + Text(0, "*x^^"); + IntOut(0, J); + BVZ:= ~BVZ; + end; + for J:= N / 2 downto 2 do + begin + VZOut(0, BVZ); + IntOut(0, PasTri(J)); + Text(0, "*x^^"); + IntOut(0, J); + BVZ:= ~BVZ + end; + VZOut(0, BVZ); + IntOut(0, PasTri(1)); + Text(0, "*x"); + BVZ:= ~BVZ; + VZOut(0, BVZ); + IntOut(0, PasTri(0)); + CrLf(0); + end \case other + end; + +begin +for N:= 0 to 9 do ExpandPoly(N); +for N:= 2 to PasTriMax do + if IsPrime(N) then [Format(3,0); RlOut(0, Float(N))]; +CrLf(0); +end diff --git a/Task/ASCII-art-diagram-converter/Mathematica/ascii-art-diagram-converter.math b/Task/ASCII-art-diagram-converter/Mathematica/ascii-art-diagram-converter.math new file mode 100644 index 0000000000..d8537d0ef8 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/Mathematica/ascii-art-diagram-converter.math @@ -0,0 +1,86 @@ +diagram = " + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ID | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + |QR| Opcode |AA|TC|RD|RA| Z | RCODE | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | QDCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ANCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | NSCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ARCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+"; + +testhexdata = "78477bbf5496e12e1bf169a4"; + +(* Define BitField as an Association instead of a struct *) +createBitField[name_, bits_, fieldstart_, fieldend_] := + <|"name" -> name, "bits" -> bits, "fieldstart" -> fieldstart, "fieldend" -> fieldend|>; + +diagramToStruct[txt_] := Module[{bitfields = {}, lines, nbits, fieldpos, bitaccum, + bitsize, bitlabel, bitstart, bitend}, + lines = StringTrim /@ StringSplit[txt, "\n"]; + + Do[ + nbits = StringCount[lines[[row]], "+"] - 1; + fieldpos = StringPosition[lines[[row + 1]], "|"][[All, 1]]; + bitaccum = Floor[row/2] * nbits; + + Do[ + endfield = fieldpos[[i + 1]]; + bitsize = Floor[(endfield - field)/3]; + bitlabel = StringTrim[StringTake[lines[[row + 1]], {field + 1, endfield - 1}]]; + bitstart = Floor[(field - 1)/3] + bitaccum; + bitend = bitstart + bitsize - 1; + AppendTo[bitfields, createBitField[bitlabel, bitsize, bitstart, bitend]], + + {i, 1, Length[fieldpos] - 1}, {field, {fieldpos[[i]]}} + ], + + {row, 1, Length[lines] - 1, 2} + ]; + + bitfields +]; + +(* Convert a hex byte to binary string with padding *) +binByte[c_] := IntegerString[FromDigits[c, 16], 2, 8]; + +(* Convert entire hex string to binary *) +hexToBinary[s_] := StringJoin[ + binByte /@ (StringTake[s, {#, # + 1}] & /@ Range[1, StringLength[s] - 1, 2]) +]; + +validator[binstring_, fields_] := + StringLength[binstring] == Total[#["bits"] & /@ fields]; + +bitReader[bitfields_, hexdata_] := Module[{b, pat}, + Print["\nEvaluation of hex data ", hexdata, " as bitfields:"]; + Print["Name Size Bits\n------- ---- ----------------"]; + + b = hexToBinary[hexdata]; + Assert[validator[b, bitfields]]; + + Do[ + pat = StringTake[b, {bf["fieldstart"] + 1, bf["fieldend"] + 1}]; + Print[StringPadRight[bf["name"], 9], + StringPadRight[ToString[bf["bits"]], 6], + StringPadLeft[pat, 16]], + {bf, bitfields} + ] +]; + +decoded = diagramToStruct[diagram]; + +Print["Diagram as bit fields:\nName Bits Start End\n------ ---- ----- ---"]; +Do[ + Print[StringPadRight[bf["name"], 8], + StringPadRight[ToString[bf["bits"]], 6], + StringPadRight[ToString[bf["fieldstart"]], 6], + StringPadLeft[ToString[bf["fieldend"]], 4]], + {bf, decoded} +]; + +bitReader[decoded, testhexdata]; diff --git a/Task/AVL-tree/Dart/avl-tree.dart b/Task/AVL-tree/Dart/avl-tree.dart new file mode 100644 index 0000000000..fb761a2aec --- /dev/null +++ b/Task/AVL-tree/Dart/avl-tree.dart @@ -0,0 +1,221 @@ +class Node { + int key; + int balance = 0; + int height = 0; + Node? left; + Node? right; + Node? parent; + + Node(this.key, this.parent); +} + + + + +class AVLTree { + Node? root; + + bool insert(int key) { + if (root == null) { + root = Node(key, null); + return true; + } + + Node? n = root; + while (true) { + if (n!.key == key) return false; + + Node parent = n; + + bool goLeft = n.key > key; + n = goLeft ? n.left : n.right; + + if (n == null) { + if (goLeft) { + parent.left = Node(key, parent); + } else { + parent.right = Node(key, parent); + } + rebalance(parent); + break; + } + } + return true; + } + + void _delete(Node node) { + if (node.left == null && node.right == null) { + if (node.parent == null) { + root = null; + } else { + Node parent = node.parent!; + if (parent.left == node) { + parent.left = null; + } else { + parent.right = null; + } + rebalance(parent); + } + return; + } + + if (node.left != null) { + Node child = node.left!; + while (child.right != null) child = child.right!; + node.key = child.key; + _delete(child); + } else { + Node child = node.right!; + while (child.left != null) child = child.left!; + node.key = child.key; + _delete(child); + } + } + + void delete(int delKey) { + if (root == null) return; + + Node? child = root; + while (child != null) { + Node node = child; + child = delKey >= node.key ? node.right : node.left; + if (delKey == node.key) { + _delete(node); + return; + } + } + } + + void rebalance(Node n) { + setBalance(n); + + if (n.balance == -2) { + if (height(n.left!.left) >= height(n.left!.right)) { + n = rotateRight(n); + } else { + n = rotateLeftThenRight(n); + } + } else if (n.balance == 2) { + if (height(n.right!.right) >= height(n.right!.left)) { + n = rotateLeft(n); + } else { + n = rotateRightThenLeft(n); + } + } + + if (n.parent != null) { + rebalance(n.parent!); + } else { + root = n; + } + } + + Node rotateLeft(Node a) { + Node b = a.right!; + b.parent = a.parent; + + a.right = b.left; + + if (a.right != null) a.right!.parent = a; + + b.left = a; + a.parent = b; + + if (b.parent != null) { + if (b.parent!.right == a) { + b.parent!.right = b; + } else { + b.parent!.left = b; + } + } + + setBalance(a, b); + + return b; + } + + Node rotateRight(Node a) { + Node b = a.left!; + b.parent = a.parent; + + a.left = b.right; + + if (a.left != null) a.left!.parent = a; + + b.right = a; + a.parent = b; + + if (b.parent != null) { + if (b.parent!.right == a) { + b.parent!.right = b; + } else { + b.parent!.left = b; + } + } + + setBalance(a, b); + + return b; + } + + Node rotateLeftThenRight(Node n) { + n.left = rotateLeft(n.left!); + return rotateRight(n); + } + + Node rotateRightThenLeft(Node n) { + n.right = rotateRight(n.right!); + return rotateLeft(n); + } + + int height(Node? n) { + if (n == null) return -1; + return n.height; + } + + void setBalance(Node n, [Node? n2]) { + reheight(n); + n.balance = height(n.right) - height(n.left); + + if (n2 != null) { + reheight(n2); + n2.balance = height(n2.right) - height(n2.left); + } + } + + void printBalance() { + _printBalance(root); + } + + void _printBalance(Node? n) { + if (n != null) { + _printBalance(n.left); + print('${n.balance} '); + _printBalance(n.right); + } + } + + void reheight(Node node) { + if (node != null) { + node.height = 1 + (height(node.left) > height(node.right) + ? height(node.left) + : height(node.right)); + } + } + + static void main() { + AVLTree tree = AVLTree(); + + print('Inserting values 1 to 10'); + for (int i = 1; i < 10; i++) { + tree.insert(i); + } + + print('Printing balance: '); + tree.printBalance(); + } +} + +void main() { + AVLTree.main(); +} diff --git a/Task/AVL-tree/Swift/avl-tree.swift b/Task/AVL-tree/Swift/avl-tree.swift new file mode 100644 index 0000000000..06db507617 --- /dev/null +++ b/Task/AVL-tree/Swift/avl-tree.swift @@ -0,0 +1,243 @@ +import Foundation + +// MARK: - AVL Tree --------------------------------------------------------- + +final class AVLTree { + // ---------- Node ------------------------------------------------------ + private class Node { + var key: Int + var balance: Int = 0 + var height: Int = 0 + + var left: Node? + var right: Node? + weak var parent: Node? // weak to avoid retain cycles + + init(key: Int, parent: Node?) { + self.key = key + self.parent = parent + } + } + + // ---------- Root ------------------------------------------------------- + private var root: Node? + + // ---------- Public API ------------------------------------------------- + + /// Inserts `key`. Returns `true` if the key was added, `false` if it already existed. + @discardableResult + func insert(_ key: Int) -> Bool { + // empty tree → new root + guard let rootNode = root else { + root = Node(key: key, parent: nil) + return true + } + + var n: Node? = rootNode + while let cur = n { + if cur.key == key { return false } // duplicate + + let goLeft = key < cur.key + let parent = cur + n = goLeft ? cur.left : cur.right + + // we have found the empty spot → insert + if n == nil { + let newNode = Node(key: key, parent: parent) + if goLeft { + parent.left = newNode + } else { + parent.right = newNode + } + rebalance(parent) // fix AVL balance upwards + break + } + } + return true + } + + /// Deletes `key` if it exists. Does nothing when the key is not present. + func delete(_ key: Int) { + var current = root + while let node = current { + if key == node.key { + delete(node) // internal helper that really removes the node + return + } + current = (key < node.key) ? node.left : node.right + } + // key not found → nothing to do + } + + /// Prints the balance factor of every node in‑order. + func printBalance() { + printBalance(node: root) + } + + // ---------- Private helpers ------------------------------------------- + + /// Removes `node` from the tree (used by the public `delete(_:)` above). + private func delete(_ node: Node) { + // ----- 1️⃣ leaf node ------------------------------------------------ + if node.left == nil && node.right == nil { + if let parent = node.parent { + if parent.left === node { parent.left = nil } + else { parent.right = nil } + rebalance(parent) + } else { + root = nil // tree becomes empty + } + return + } + + // ----- 2️⃣ node has a left subtree → replace with predecessor ----- + if let left = node.left { + var predecessor = left + while let r = predecessor.right { predecessor = r } + node.key = predecessor.key + delete(predecessor) + } + // ----- 3️⃣ otherwise it has a right subtree → replace with successor + else if let right = node.right { + var successor = right + while let l = successor.left { successor = l } + node.key = successor.key + delete(successor) + } + } + + /// Walks upward from `n`, fixing heights, balances and performing rotations. + private func rebalance(_ n: Node) { + setBalance(of: n) + + var node = n + if node.balance == -2 { + // left heavy + if height(of: node.left?.left) >= height(of: node.left?.right) { + node = rotateRight(node) + } else { + node = rotateLeftThenRight(node) + } + } else if node.balance == 2 { + // right heavy + if height(of: node.right?.right) >= height(of: node.right?.left) { + node = rotateLeft(node) + } else { + node = rotateRightThenLeft(node) + } + } + + // continue upwards – or make this node the new root + if let parent = node.parent { + rebalance(parent) + } else { + root = node + } + } + + // ---------- Rotations ------------------------------------------------- + + private func rotateLeft(_ a: Node) -> Node { + guard let b = a.right else { return a } // safety guard + + // detach b from a + b.parent = a.parent + a.right = b.left + a.right?.parent = a + + // attach a under b + b.left = a + a.parent = b + + // reconnect b with the rest of the tree + if let p = b.parent { + if p.left === a { + p.left = b + } else { + p.right = b + } + } + + setBalance(of: a, b) + return b + } + + private func rotateRight(_ a: Node) -> Node { + guard let b = a.left else { return a } // safety guard + + b.parent = a.parent + a.left = b.right + a.left?.parent = a + + b.right = a + a.parent = b + + if let p = b.parent { + if p.left === a { + p.left = b + } else { + p.right = b + } + } + + setBalance(of: a, b) + return b + } + + private func rotateLeftThenRight(_ n: Node) -> Node { + if let left = n.left { + n.left = rotateLeft(left) + } + return rotateRight(n) + } + + private func rotateRightThenLeft(_ n: Node) -> Node { + if let right = n.right { + n.right = rotateRight(right) + } + return rotateLeft(n) + } + + // ---------- Height / Balance helpers ---------------------------------- + + /// Height of a node – `-1` for `nil` (matches the Java implementation). + private func height(of node: Node?) -> Int { + node?.height ?? -1 + } + + /// Re‑computes stored height of `node`. + private func reheight(_ node: Node?) { + guard let node = node else { return } + node.height = 1 + max(height(of: node.left), height(of: node.right)) + } + + /// Updates both `height` and `balance` for every supplied node. + private func setBalance(of nodes: Node...) { + for n in nodes { + reheight(n) + n.balance = height(of: n.right) - height(of: n.left) + } + } + + // ---------- Printing --------------------------------------------------- + + private func printBalance(node: Node?) { + guard let node = node else { return } + printBalance(node: node.left) + print("\(node.balance) ", terminator: "") + printBalance(node: node.right) + } +} + +// MARK: - Demo ------------------------------------------------------------- + +let tree = AVLTree() + +print("Inserting values 1 to 10") +for i in 1...10 { + _ = tree.insert(i) +} + +print("Printing balance: ", terminator: "") +tree.printBalance() +print() // newline diff --git a/Task/AVL-tree/Zig/avl-tree.zig b/Task/AVL-tree/Zig/avl-tree.zig new file mode 100644 index 0000000000..3dddf5315b --- /dev/null +++ b/Task/AVL-tree/Zig/avl-tree.zig @@ -0,0 +1,268 @@ +const std = @import("std"); +const math = std.math; +const stdout = std.io.getStdOut().writer(); +const Allocator = std.mem.Allocator; + +// AVL node +fn AVLnode(comptime T: type) type { + return struct { + const Self = @This(); + + key: T, + balance: i32, + left: ?*Self, + right: ?*Self, + parent: ?*Self, + + fn init(k: T, p: ?*Self) Self { + return Self{ + .key = k, + .balance = 0, + .parent = p, + .left = null, + .right = null, + }; + } + + fn deinit(self: *Self, allocator: Allocator) void { + if (self.left) |left| { + left.deinit(allocator); + allocator.destroy(left); + } + if (self.right) |right| { + right.deinit(allocator); + allocator.destroy(right); + } + } + }; +} + +// AVL tree +fn AVLtree(comptime T: type) type { + return struct { + const Self = @This(); + const Node = AVLnode(T); + + root: ?*Node, + allocator: Allocator, + + fn init(allocator: Allocator) Self { + return Self{ + .root = null, + .allocator = allocator, + }; + } + + fn deinit(self: *Self) void { + if (self.root) |root| { + root.deinit(self.allocator); + self.allocator.destroy(root); + } + } + + fn rotateLeft(self: *Self, a: *Node) *Node { + var b = a.right.?; + b.parent = a.parent; + a.right = b.left; + + if (a.right != null) { + a.right.?.parent = a; + } + + b.left = a; + a.parent = b; + + if (b.parent) |parent| { + if (parent.right == a) { + parent.right = b; + } else { + parent.left = b; + } + } + + self.setBalance(a); + self.setBalance(b); + return b; + } + + fn rotateRight(self: *Self, a: *Node) *Node { + var b = a.left.?; + b.parent = a.parent; + a.left = b.right; + + if (a.left != null) { + a.left.?.parent = a; + } + + b.right = a; + a.parent = b; + + if (b.parent) |parent| { + if (parent.right == a) { + parent.right = b; + } else { + parent.left = b; + } + } + + self.setBalance(a); + self.setBalance(b); + return b; + } + + fn rotateLeftThenRight(self: *Self, n: *Node) *Node { + n.left = self.rotateLeft(n.left.?); + return self.rotateRight(n); + } + + fn rotateRightThenLeft(self: *Self, n: *Node) *Node { + n.right = self.rotateRight(n.right.?); + return self.rotateLeft(n); + } + + fn height(self: *Self, n: ?*Node) i32 { + if (n == null) + return -1; + return 1 + @max(self.height(n.?.left), self.height(n.?.right)); + } + + fn setBalance(self: *Self, n: *Node) void { + n.balance = self.height(n.right) - self.height(n.left); + } + + fn rebalance(self: *Self, _n: *Node) void { + var n=_n; + self.setBalance(n); + + if (n.balance == -2) { + if (self.height(n.left.?.left) >= self.height(n.left.?.right)) { + n = self.rotateRight(n); + } else { + n = self.rotateLeftThenRight(n); + } + } else if (n.balance == 2) { + if (self.height(n.right.?.right) >= self.height(n.right.?.left)) { + n = self.rotateLeft(n); + } else { + n = self.rotateRightThenLeft(n); + } + } + + if (n.parent != null) { + self.rebalance(n.parent.?); + } else { + self.root = n; + } + } + + fn insert(self: *Self, key: T) !bool { + if (self.root == null) { + const node = try self.allocator.create(Node); + node.* = Node.init(key, null); + self.root = node; + } else { + var n = self.root.?; + var parent: *Node = undefined; + + while (true) { + if (n.key == key) + return false; + + parent = n; + + const goLeft = n.key > key; + if (goLeft) { + if (n.left) |left| { + n = left; + } else { + const node = try self.allocator.create(Node); + node.* = Node.init(key, parent); + parent.left = node; + self.rebalance(parent); + break; + } + } else { + if (n.right) |right| { + n = right; + } else { + const node = try self.allocator.create(Node); + node.* = Node.init(key, parent); + parent.right = node; + self.rebalance(parent); + break; + } + } + } + } + + return true; + } + + fn deleteKey(self: *Self, delKey: T) void { + if (self.root == null) + return; + + var n = self.root.?; + var parent = self.root.?; + var delNode: ?*Node = null; + var child: ?*Node = self.root; + + while (child != null) { + parent = n; + n = child.?; + child = if (delKey >= n.key) n.right else n.left; + if (delKey == n.key) + delNode = n; + } + + if (delNode) |node| { + node.key = n.key; + + child = if (n.left != null) n.left else n.right; + + if (self.root.?.key == delKey) { + self.root = child; + } else { + if (parent.left == n) { + parent.left = child; + } else { + parent.right = child; + } + + self.rebalance(parent); + } + } + } + + fn printBalance(self: *Self, n: ?*Node) !void { + if (n != null) { + try self.printBalance(n.?.left); + try stdout.print("{} ", .{n.?.balance}); + try self.printBalance(n.?.right); + } + } + + fn printBalanceRoot(self: *Self) !void { + try self.printBalance(self.root); + try stdout.print("\n", .{}); + } + }; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var t = AVLtree(i32).init(allocator); + defer t.deinit(); + + try stdout.print("Inserting integer values 1 to 10\n", .{}); + var i: i32 = 1; + while (i <= 10) : (i += 1) { + _ = try t.insert(i); + } + + try stdout.print("Printing balance: ", .{}); + try t.printBalanceRoot(); +} diff --git a/Task/Abbreviations-easy/ArkScript/abbreviations-easy.ark b/Task/Abbreviations-easy/ArkScript/abbreviations-easy.ark new file mode 100644 index 0000000000..da2282ce34 --- /dev/null +++ b/Task/Abbreviations-easy/ArkScript/abbreviations-easy.ark @@ -0,0 +1,54 @@ +(let commands "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up") + +(let user_words "riG rePEAT copies put mo rest types fup. 6 poweRin") + +(import std.List) +(import std.String) + +(let abbrev_length (fun (word) + (len + (list:takeWhile + word + (fun (char) { + (let ord (string:ord char)) + (and (<= 65 ord) (<= ord 90)) }))))) + +(let extract_cmds (fun (text) + (list:filter (string:split text " ") (fun (elem) (not (empty? elem)))))) + +(let cmds_with_abbrev_len + (list:map + (extract_cmds commands) + (fun (cmd) + [cmd (abbrev_length cmd)] ))) + +(let find_abbrev (fun (word) { + (let wlen (len word)) + (let lower (string:toLower word)) + + (list:map + (list:filter + cmds_with_abbrev_len + (fun (cmd_with_len) { + (let cmd (string:toLower (head cmd_with_len))) + (let min_len (@ cmd_with_len 1)) + + (and + (<= min_len wlen) + (<= wlen (len cmd)) + (= lower (string:slice cmd 0 wlen))) })) + (fun (cmd_with_len) (head cmd_with_len))) })) + +(let user_inputs (extract_cmds user_words)) + +(assert + (= + ["RIGHT" "REPEAT" "*error*" "PUT" "MOVE" "RESTORE" "*error*" "*error*" "*error*" "POWERINPUT"] + (list:map + user_inputs + (fun (str) { + (let abbrevs (find_abbrev str)) + (if (empty? abbrevs) + "*error*" + (string:toUpper (head abbrevs))) }))) + "commands were correctly deciphered") diff --git a/Task/Abbreviations-easy/PascalABC.NET/abbreviations-easy.pas b/Task/Abbreviations-easy/PascalABC.NET/abbreviations-easy.pas new file mode 100644 index 0000000000..cd4a089f62 --- /dev/null +++ b/Task/Abbreviations-easy/PascalABC.NET/abbreviations-easy.pas @@ -0,0 +1,26 @@ +begin + var commands := + ''' + Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy + COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find + NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput + Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO + MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT + READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT + RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up + '''.ToWords(AllDelimiters); + + var countDict := commands.Each(word -> word.TakeWhile(c -> c.IsUpper).Count); + + var correctedLine := 'riG rePEAT copies put mo rest types fup. 6 poweRin' + .ToWords + .Select(word -> + commands.FirstOrDefault( + cmd -> cmd.ToLower.StartsWith(word.ToLower) and + (word.Length >= countDict[cmd]) + )?.ToUpper ?? '*error*' + ) + .JoinToString; + + Print(correctedLine); +end. diff --git a/Task/Abbreviations-simple/PascalABC.NET/abbreviations-simple.pas b/Task/Abbreviations-simple/PascalABC.NET/abbreviations-simple.pas new file mode 100644 index 0000000000..db47a4c235 --- /dev/null +++ b/Task/Abbreviations-simple/PascalABC.NET/abbreviations-simple.pas @@ -0,0 +1,51 @@ +{$zerobasedstrings on} + +begin + var commandData := + ''' + add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 + compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate + 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 + forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load + locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 + msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 + refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left + 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 + '''.ToWords(AllDelimiters); + + var abbrDict := Dict('' to ''); + + var i := 0; + while i < commandData.Length do + begin + var cmd := commandData[i]; + i += 1; + + // Если следующего элемента нет или он не число, используем длину команды + var minLen := cmd.Length; + if (i < commandData.Length) and commandData[i].All(char.IsDigit) then + begin + minLen := commandData[i].ToInteger; + i += 1; + end; + + var cmdLower := cmd.ToLower; + for var len := minLen to cmd.Length do + begin + var abbr := cmdLower[:len]; + abbrDict[abbr] := cmd.ToUpper; + end; + end; + + var testStr := 'riG rePEAT copies put mo rest types fup. 6 poweRin'; + Writeln(' Input: ', testStr); + Writeln('Output: ', testStr.ToWords() + .Select(w -> abbrDict.Get(w.Trim.ToLower,'*error*')) + .JoinToString); + + testStr := ''; + Writeln(' Input: ', testStr); + Writeln('Output: ', testStr.ToWords() + .Select(w -> abbrDict.Get(w.Trim.ToLower,'*error*')) + .JoinToString); +end. diff --git a/Task/Abelian-sandpile-model-Identity/Pluto/abelian-sandpile-model-identity.pluto b/Task/Abelian-sandpile-model-Identity/Pluto/abelian-sandpile-model-identity.pluto new file mode 100644 index 0000000000..867e535547 --- /dev/null +++ b/Task/Abelian-sandpile-model-Identity/Pluto/abelian-sandpile-model-identity.pluto @@ -0,0 +1,79 @@ +class Sandpile + -- 'a' is a list of 9 integers in row order. + function __construct(public a) + self.neighbors = { + {2, 4}, {1, 3, 5}, {2, 6}, {1, 5, 7}, {2, 4, 6, 8}, + {3, 5, 9}, {4, 8}, {5, 7, 9}, {6, 8} + } + end + + function __add(other) + local b = {} + for i = 1, 9 do + b:insert(self.a[i] + other.a[i]) + end + return new Sandpile(b) + end + + function is_stable() + return self.a:checkall(|i| -> i <= 3) + end + + -- Just topples once so we can observe intermediate results. + function topple() + for i = 1, 9 do + if self.a[i] > 3 then + self.a[i] -= 4 + for self.neighbors[i] as j do ++self.a[j] end + return + end + end + end + + function to_string() + local s = "" + for i = 1, 3 do + for j = 1, 3 do s ..= $"{self.a[3*(i - 1) + j]} " end + s ..= "\n" + end + return s + end +end + +print("Avalanche of topplings:\n") +local s0 = new Sandpile({4, 3, 3, 3, 1, 2, 0, 2, 3}) +print(s0:to_string()) +while !s0:is_stable() do + s0:topple() + print(s0:to_string()) +end + +print("Commutative additions:\n") +local s1 = new Sandpile({1, 2, 0, 2, 1, 1, 0, 1, 3}) +local s2 = new Sandpile({2, 1, 3, 1, 0, 1, 0, 1, 0}) +local s3_a = s1 + s2 +while !s3_a:is_stable() do s3_a:topple() end +local s3_b = s2 + s1 +while !s3_b:is_stable() do s3_b:topple() end +local s1s = s1:to_string() +local s2s = s2:to_string() +local s3_as = s3_a:to_string() +local s3_bs = s3_b:to_string() +print(string.format("%s\nplus\n\n%s\nequals\n\n%s", s1s, s2s, s3_as)) +print(string.format("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s", s2s, s1s, s3_bs)) + +print("Addition of identity sandpile:\n") +local s3 = new Sandpile({3, 3, 3, 3, 3, 3, 3, 3, 3}) +local s3_id = new Sandpile({2, 1, 2, 1, 0, 1, 2, 1, 2}) +local s4 = s3 + s3_id +while !s4:is_stable() do s4:topple() end +local s3s = s3:to_string() +local s3_ids = s3_id:to_string() +local s4s = s4:to_string() +print(string.format("%s\nplus\n\n%s\nequals\n\n%s", s3s, s3_ids, s4s)) + +print("Addition of identities:\n") +local s5 = s3_id + s3_id +while !s5:is_stable() do s5:topple() end +local s5s = s5:to_string() +print(string.format("%s\nplus\n\n%s\nequals\n\n%s", s3_ids, s3_ids, s5s)) diff --git a/Task/Abelian-sandpile-model-Identity/Zig/abelian-sandpile-model-identity.zig b/Task/Abelian-sandpile-model-Identity/Zig/abelian-sandpile-model-identity.zig new file mode 100644 index 0000000000..e889527ece --- /dev/null +++ b/Task/Abelian-sandpile-model-Identity/Zig/abelian-sandpile-model-identity.zig @@ -0,0 +1,126 @@ +const std = @import("std"); + +const Box = struct { + piles: [3][3]u8, + + fn init(piles: [3][3]u8) Box { + var a = Box{ .piles = piles }; + + for (a.piles) |row| { + for (row) |pile| { + if (pile >= 4) { + return a.avalanche(); + } + } + } + return a; + } + + fn avalanche(self: *const Box) Box { + var a = self.*; + for (self.piles, 0..) |row, i| { + for (row, 0..) |pile, j| { + if (pile >= 4) { + if (i > 0) { + a.piles[i - 1][j] += 1; + } + if (i < 2) { + a.piles[i + 1][j] += 1; + } + if (j > 0) { + a.piles[i][j - 1] += 1; + } + if (j < 2) { + a.piles[i][j + 1] += 1; + } + a.piles[i][j] -= 4; + } + } + } + return Box.init(a.piles); + } + + fn add(self: *const Box, other: *const Box) Box { + var b = Box{ + .piles = [_][3]u8{[_]u8{0} ** 3} ** 3, + }; + for (0..3) |row| { + for (0..3) |col| { + b.piles[row][col] = self.piles[row][col] + other.piles[row][col]; + } + } + return Box.init(b.piles); + } +}; + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + try stdout.print("The piles demonstration avalanche starts as:\n{any}\n{any}\n{any}\n", .{ + [_]u8{ 4, 3, 3 }, + [_]u8{ 3, 1, 2 }, + [_]u8{ 0, 2, 3 }, + }); + + const s0 = Box.init([_][3]u8{ + [_]u8{ 4, 3, 3 }, + [_]u8{ 3, 1, 2 }, + [_]u8{ 0, 2, 3 }, + }); + + try stdout.print("And ends as:\n{any}\n{any}\n{any}\n", .{ + s0.piles[0], + s0.piles[1], + s0.piles[2], + }); + + const s1 = Box.init([_][3]u8{ + [_]u8{ 1, 2, 0 }, + [_]u8{ 2, 1, 1 }, + [_]u8{ 0, 1, 3 }, + }); + + const s2 = Box.init([_][3]u8{ + [_]u8{ 2, 1, 3 }, + [_]u8{ 1, 0, 1 }, + [_]u8{ 0, 1, 0 }, + }); + + const s1_2 = s1.add(&s2); + const s2_1 = s2.add(&s1); + + try stdout.print("The piles in s1 + s2 are:\n{any}\n{any}\n{any}\n", .{ + s1_2.piles[0], + s1_2.piles[1], + s1_2.piles[2], + }); + + try stdout.print("The piles in s2 + s1 are:\n{any}\n{any}\n{any}\n", .{ + s2_1.piles[0], + s2_1.piles[1], + s2_1.piles[2], + }); + + const s3 = Box.init([_][3]u8{[_]u8{3} ** 3} ** 3); + const s3_id = Box.init([_][3]u8{ + [_]u8{ 2, 1, 2 }, + [_]u8{ 1, 0, 1 }, + [_]u8{ 2, 1, 2 }, + }); + + const s4 = s3.add(&s3_id); + + try stdout.print("The piles in s3 + s3_id are:\n{any}\n{any}\n{any}\n", .{ + s4.piles[0], + s4.piles[1], + s4.piles[2], + }); + + const s5 = s3_id.add(&s3_id); + + try stdout.print("The piles in s3_id + s3_id are:\n{any}\n{any}\n{any}\n", .{ + s5.piles[0], + s5.piles[1], + s5.piles[2], + }); +} diff --git a/Task/Abelian-sandpile-model/Julia/abelian-sandpile-model.jl b/Task/Abelian-sandpile-model/Julia/abelian-sandpile-model.jl index fc19b42b8a..35866a7ca1 100644 --- a/Task/Abelian-sandpile-model/Julia/abelian-sandpile-model.jl +++ b/Task/Abelian-sandpile-model/Julia/abelian-sandpile-model.jl @@ -1,24 +1,25 @@ -module AbelSand +""" From code by Hayk Aleksanyan, see also github.com/hayk314/Sandpiles """ -# supports output functionality for the results of the sandpile simulations -# outputs the final grid in CSV format, as well as an image file +""" supports output functionality for the results of the sandpile simulations + outputs the final grid in CSV format, as well as an image file +""" +module AbelSand using CSV, DataFrames, Images -function TrimZeros(A) - # given an array A trims any zero rows/columns from its borders - # returns a 4 tuple of integers, i1, i2, j1, j2, where the trimmed array corresponds to A[i1:i2, j1:j2] - # A can be either numeric or a boolean array - +""" given an array A trims any zero rows/columns from its borders + returns a 4 tuple of integers, i1, i2, j1, j2, where the trimmed array corresponds to A[i1:i2, j1:j2] + A can be either numeric or a boolean array +""" +function trimzeros(A) i1, j1 = 1, 1 i2, j2 = size(A) - zz = typeof(A[1, 1])(0) # comparison of a value takes into account the type as well # i1 is the first row which has non zero element - for i = 1:size(A, 1) + for i in axes(A, 1) q = false - for k = 1:size(A, 2) + for k in axes(A, 2) if A[i, k] != zz q = true i1 = i @@ -32,26 +33,24 @@ function TrimZeros(A) end # i2 is the first from below row with non zero element - for i in size(A, 1):-1:1 + for i in reverse(axes(A, 1)) q = false - for k = 1:size(A, 2) + for k in axes(A, 2) if A[i, k] != zz q = true i2 = i break end end - if q == true break end end # j1 is the first column with non zero element - - for j = 1:size(A, 2) + for j in axes(A, 2) q = false - for k = 1:size(A, 1) + for k in axes(A, 1) if A[k, j] != zz j1 = j q = true @@ -65,18 +64,17 @@ function TrimZeros(A) end # j2 is the last column with non zero element - - for j in size(A, 2):-1:1 - q=false - for k=1:size(A,1) + for j in reverse(axes(A, 2)) + q = false + for k in axes(A, 1) if A[k, j] != zz j2 = j - q=true + q = true break end end - if q==true + if q == true break end end @@ -84,129 +82,124 @@ function TrimZeros(A) return i1, i2, j1, j2 end -function addLayerofZeros(A, extraLayer) - # adds layer of zeros from all corners to the given array A - - if extraLayer <= 0 - return A - end +""" adds layer of zeros from all corners to the given array A """ +function addlayerofzeros!(A, extraLayer) + extraLayer <= 0 && return A N, M = size(A) - - - Z = zeros( typeof(A[1,1]), N + 2*extraLayer, M + 2*extraLayer) - Z[(extraLayer+1):(N + extraLayer ), (extraLayer+1):(M+extraLayer)] = A + Z = zeros(typeof(A[1, 1]), N + 2 * extraLayer, M + 2 * extraLayer) + Z[(extraLayer+1):(N+extraLayer), (extraLayer+1):(M+extraLayer)] = A return Z - end -function printIntoFile(A, extraLayer, strFileName, TrimSmallValues = false) - # exports a 2d matrix A into a csv file - # @extraLayer is an integers adding layer of 0-s sorrounding the output matrix - - # trimming off very small values; tiny values affect the performance of CSV export +""" exports a 2d matrix A into a csv file, adjusting the size of the output matrix + @extraLayer is an integers adding layer of 0-s sorrounding the output matrix + trimming off very small values; tiny values affect the performance of CSV export +""" +function outputCSV!(A, extraLayer, strFileName, TrimSmallValues = false) if TrimSmallValues == true - A = map(x -> if (abs(x - floor(x)) < 0.01) floor(x) else x end, A) + A = map(x -> if (abs(x - floor(x)) < 0.01) + floor(x) + else + x + end, A) end - i1, i2, j1, j2 = TrimZeros( A ) + i1, i2, j1, j2 = trimzeros(A) A = A[i1:i2, j1:j2] - - A = addLayerofZeros(A, extraLayer) - - CSV.write(string(strFileName,".csv"), DataFrame(A), writeheader = false) + A = addlayerofzeros!(A, extraLayer) + CSV.write(string(strFileName, ".csv"), DataFrame(A, :auto), writeheader = false) return A - end -function Array_magnifier(A, cell_mag, border_mag) - # A is the main array; @cell_mag is the magnifying size of the cell, - # @border_mag is the magnifying size of the border between lattice cells - - # creates a new array where each cell of the original array A appears magnified by size = cell_mag - - +""" creates a new array A1 where each cell of the original array A appears magnified by size @cell_mag + A is the input array; @cell_mag is the magnifying size of the cell, + @border_mag is the magnifying size of the border between lattice cells +""" +function arraymagnifier(A, cell_mag, border_mag) total_factor = cell_mag + border_mag + A1 = zeros(typeof(A[1, 1]), total_factor * size(A, 1), total_factor * size(A, 2)) + for i ∈ axes(A, 1), j ∈ axes(A, 2), u ∈ ((i-1)*total_factor+1):(i*total_factor), + v ∈ ((j-1)*total_factor+1):(j*total_factor) - A1 = zeros(typeof(A[1, 1]), total_factor*size(A, 1), total_factor*size(A, 2)) - - for i = 1:size(A,1), j = 1:size(A,2), u = ((i-1)*total_factor+1):(i*total_factor), - v = ((j-1)*total_factor+1):(j*total_factor) - if(( u - (i - 1) * total_factor <= cell_mag) && (v - (j - 1) * total_factor <= cell_mag)) + if ((u - (i - 1) * total_factor <= cell_mag) && (v - (j - 1) * total_factor <= cell_mag)) A1[u, v] = A[i, j] end end return A1 - end -function saveAsGrayImage(A, fileName, cell_mag, border_mag, TrimSmallValues = false) - # given a 2d matrix A, we save it as a gray image after magnifying by the given factors - A1 = Array_magnifier(A, cell_mag, border_mag) - A1 = A1/maximum(maximum(A1)) +""" given a 2d matrix A, we save it as a gray image after magnifying by the given factors """ +function savegrayimage(A, fileName, cell_mag, border_mag, TrimSmallValues = false) + A1 = arraymagnifier(A, cell_mag, border_mag) + A1 = A1 / maximum(maximum(A1)) # trimming very small values from A1 to improve performance if TrimSmallValues == true - A1 = map(x -> if ( x < 0.01) 0.0 else round(x, digits = 2) end, A1) + A1 = map(x -> if (x < 0.01) + 0.0 + else + round(x, digits = 2) + end, A1) end - save(string(fileName, ".png") , colorview(Gray, A1)) + save(string(fileName, ".png"), colorview(Gray, A1)) end -function saveAsRGBImage(A, fileName, color_codes, cell_mag, border_mag) - # color_codes is a dictionary, where key is a value in A and value is an RGB triplet - # given a 2d array A, and color codes (mapping from values in A to RGB triples), save A - # into fileName as png image after applying the magnifying factors - - A1 = Array_magnifier(A, cell_mag, border_mag) +""" color_codes is a dictionary, where key is a value in A and value is an RGB triplet + given a 2d array A, and color codes (mapping from values in A to RGB triples), save A + into fileName as png image after applying the magnifying factors +""" +function saveRGBimage(A, fileName, color_codes, cell_mag, border_mag) + A1 = arraymagnifier(A, cell_mag, border_mag) color_mat = zeros(UInt8, (3, size(A1, 1), size(A1, 2))) - for i = 1:size(A1,1) - for j = 1:size(A1,2) - color_mat[:, i, j] = get(color_codes, A1[i, j] , [0, 0, 0]) + for i in axes(A1, 1) + for j in axes(A1, 2) + color_mat[:, i, j] = get(color_codes, A1[i, j], [0, 0, 0]) end end - save(string(fileName, ".png") , colorview(RGB, color_mat/255)) + save(string(fileName, ".png"), colorview(RGB, color_mat / 255)) end const N_size = 700 # the radius of the lattice Z^2, the actual size becomes (2*N+1)x(2*N+1) const dx = [1, 0, -1, 0] # for a given (x,y) in Z^2, (x + dx, y + dy) for all (dx,dy) covers the neighborhood of (x,y) const dy = [0, 1, 0, -1] +""" represents a 2D lattice coordinate """ struct L_coord - # represents a lattice coordinate x::Int y::Int end -function FindCoordinate(Z::Array{L_coord,1}, a::Int, b::Int) - # in the given array Z of coordinates finds the (first) index of the tuple (a,b) - # if no match, returns -1 - - for i=1:length(Z) +""" Finds the (first) index of the tuple (a,b) in the given array Z of coordinates + if no match, returns -1 +""" +function findcoordinate(Z::Array{L_coord, 1}, a::Int, b::Int) + for i ∈ 1:length(Z) if (Z[i].x == a) && (Z[i].y == b) return i end end - return -1 end -function move(N) - # the main function moving the pile sand grains of size N at the origin of Z^2 until the sandpile becomes stable - +""" Moves the pile's sand grains of size N stacked all at the origin of Z^2 + until the sandpile settled to stable configuration. + Returns the final lattice Z_lat and the odometer Odometer +""" +function settle(N) Z_lat = zeros(UInt8, 2 * N_size + 1, 2 * N_size + 1) # models the integer lattice Z^2, we will have at most 4 sands on each vertex V_sites = falses(2 * N_size + 1, 2 * N_size + 1) # all sites which are visited by the sandpile process, are being marked here Odometer = zeros(UInt64, 2 * N_size + 1, 2 * N_size + 1) # stores the values of the odometer function - walking = L_coord[] # the coordinates of sites which need to move - V_sites[N_size + 1, N_size + 1] = true + V_sites[N_size+1, N_size+1] = true # i1, ... j2 -> show the boundaries of the box which is visited by the sandpile process i1, i2, j1, j2 = N_size + 1, N_size + 1, N_size + 1, N_size + 1 @@ -217,12 +210,12 @@ function move(N) while n > 0 n -= 1 - Z_lat[N_size + 1, N_size + 1] += 1 - if (Z_lat[N_size + 1, N_size + 1] >= 4) + Z_lat[N_size+1, N_size+1] += 1 + if (Z_lat[N_size+1, N_size+1] >= 4) push!(walking, L_coord(N_size + 1, N_size + 1)) end - while(length(walking) > 0) + while (length(walking) > 0) w = pop!(walking) x = w.x y = w.y @@ -230,12 +223,12 @@ function move(N) Z_lat[x, y] -= 4 Odometer[x, y] += 4 - for k = 1:4 - Z_lat[x + dx[k], y + dy[k]] += 1 - V_sites[x + dx[k], y + dy[k]] = true - if Z_lat[x + dx[k], y + dy[k]] >= 4 - if FindCoordinate(walking, x + dx[k] , y + dy[k]) == -1 - push!(walking, L_coord( x + dx[k], y + dy[k])) + for k ∈ 1:4 + Z_lat[x+dx[k], y+dy[k]] += 1 + V_sites[x+dx[k], y+dy[k]] = true + if Z_lat[x+dx[k], y+dy[k]] >= 4 + if findcoordinate(walking, x + dx[k], y + dy[k]) == -1 + push!(walking, L_coord(x + dx[k], y + dy[k])) end end end @@ -247,29 +240,24 @@ function move(N) end - end #end of the main while + end # of the outer while t2 = time_ns() - println("The final boundaries are:: ", (i2 - i1 + 1),"x",(j2 - j1 + 1), "\n") - print("time elapsed: " , (t2 - t1) / 1.0e9, "\n") + println("The final boundaries are:: ", (i2 - i1 + 1), "x", (j2 - j1 + 1), "\n") + print("time elapsed: ", (t2 - t1) / 1.0e9, "\n") - Z_lat = printIntoFile(Z_lat, 0, string("Abel_Z_", N)) - Odometer = printIntoFile(Odometer, 1, string("Abel_OD_", N)) + Z_lat = outputCSV!(Z_lat, 0, string("Abel_Z_", N)) + Odometer = outputCSV!(Odometer, 1, string("Abel_OD_", N)) - saveAsGrayImage(Z_lat, string("Abel_Z_", N), 20, 0) - color_code = Dict(1=>[255, 128, 255], 2=>[255, 0, 0],3 => [0, 128, 255]) - saveAsRGBImage(Z_lat, string("Abel_Z_color_", N), color_code, 20, 0) + savegrayimage(Z_lat, string("Abel_Z_", N), 20, 0) + color_code = Dict(1 => [255, 128, 255], 2 => [255, 0, 0], 3 => [0, 128, 255]) + saveRGBimage(Z_lat, string("Abel_Z_color_", N), color_code, 20, 0) - # for the total elapsed time, it's better to use the @time macros on the main call - - return Z_lat, Odometer # these are trimmed in output module - -end # end of function move - - -end # module + return Z_lat, Odometer +end +end # of the module using .AbelSand -Z_lat, Odometer = AbelSand.move(100000) +Z_lat, Odometer = AbelSand.settle(100000) diff --git a/Task/Abelian-sandpile-model/Pluto/abelian-sandpile-model.pluto b/Task/Abelian-sandpile-model/Pluto/abelian-sandpile-model.pluto new file mode 100644 index 0000000000..0a161fb42c --- /dev/null +++ b/Task/Abelian-sandpile-model/Pluto/abelian-sandpile-model.pluto @@ -0,0 +1,80 @@ +class Sandpile + -- 'a' is a list of integers in row order. + function __construct(a) + local count = #a + self.rows = math.floor(math.sqrt(count)) + if self.rows * self.rows != count then + print("The matrix of values must be square.") + os.exit(1) + end + self.a = a + self.neighbors = {} + for i = 1, count do + self.neighbors[i] = {} + if (i - 1) % self.rows > 0 then self.neighbors[i]:insert(i - 1) end + if i % self.rows > 0 then self.neighbors[i]:insert(i + 1) end + if i - self.rows >= 1 then self.neighbors[i]:insert(i - self.rows) end + if i + self.rows < count + 1 then self.neighbors[i]:insert(i + self.rows) end + end + end + + function is_stable() + return self.a:checkall(|i| -> i <= 3) + end + + -- Topples until stable. + function topple() + while !self:is_stable() do + for i = 1, #self.a do + if self.a[i] > 3 then + self.a[i] -= 4 + for self.neighbors[i] as j do ++self.a[j] end + end + end + end + end + + function to_string() + local s = "" + for i = 1, self.rows do + for j = 1, self.rows do + s ..= string.format("%2d ", self.a[self.rows * (i - 1) + j]) + end + s ..="\n" + end + return s + end +end + +local function print_across(str1, str2) + local r1 = str1:split("\n") + local r2 = str2:split("\n") + local rows = #r1 - 1 + local cr = rows // 2 + 1 + for i = 1, rows do + local symbol = (i == cr) ? "->" : " " + print(string.format("%s %s %s", r1[i], symbol, r2[i])) + end + print() +end + +local a1, a2, a3, a4 = {}, {}, {}, {} +for i = 1, 25 do + a1[i] = 0 + a2[i] = 0 + a3[i] = 0 +end +for i = 1, 100 do + a4[i] = 0 +end +a1[13] = 4 +a2[13] = 6 +a3[13] = 16 +a4[56] = 64 +for {a1, a2, a3, a4} as a do + local s = new Sandpile(a) + local str1 = s:to_string() + s:topple() + local str2 = s:to_string() + print_across(str1, str2) +end diff --git a/Task/Abelian-sandpile-model/Zig/abelian-sandpile-model.zig b/Task/Abelian-sandpile-model/Zig/abelian-sandpile-model.zig new file mode 100644 index 0000000000..e930714042 --- /dev/null +++ b/Task/Abelian-sandpile-model/Zig/abelian-sandpile-model.zig @@ -0,0 +1,136 @@ +const std = @import("std"); + +/// It loops over the current state of the sandpile and updates it on-the-fly. +fn advance(field: [][]usize, boundary: *[4]usize) bool { + // This variable is used to check whether we changed anything in the array. If no, the loop terminates. + var done = false; + + var y = boundary[0]; + while (y < boundary[2]) : (y += 1) { + var x = boundary[1]; + while (x < boundary[3]) : (x += 1) { + if (field[y][x] >= 4) { + // This part was heavily inspired by the Pascal version. We subtract 4 as many times as we can + // and distribute it to the neighbors. Also, in case we have outgrown the current boundary, we + // update it to once again contain the entire sandpile. + + // The amount that gets added to the neighbors is the amount here divided by four and (implicitly) floored. + // The remaining sand is just current modulo 4. + const rem: usize = field[y][x] / 4; + field[y][x] = field[y][x] % 4; + + if (y > 0) { + field[y - 1][x] += rem; + if (y == boundary[0]) { + boundary[0] -= 1; + } + } + if (x > 0) { + field[y][x - 1] += rem; + if (x == boundary[1]) { + boundary[1] -= 1; + } + } + if (y + 1 < field.len) { + field[y + 1][x] += rem; + if (y == boundary[2] - 1) { + boundary[2] += 1; + } + } + if (x + 1 < field.len) { + field[y][x + 1] += rem; + if (x == boundary[3] - 1) { + boundary[3] += 1; + } + } + + done = true; + } + } + } + + return done; +} + +/// This function can be used to display the sandpile in the console window. +fn display(field: [][]usize) void { + for (field) |row| { + for (row) |cell| { + const c: u8 = switch (cell) { + 0 => ' ', + 1 => '.', + 2 => 'o', + 3 => 'O', + else => '#', + }; + std.debug.print("{c}", .{c}); + } + std.debug.print("\n", .{}); + } +} + +/// This function writes the end result to a file called "output.ppm". +fn write_pile(pile: [][]usize, allocator: std.mem.Allocator) !void { + // We first create the file (or erase its contents if it already existed). + const file = try std.fs.cwd().createFile("output.ppm", .{}); + defer file.close(); + + // Then we add the image signature, which is "P3 [width of image] [height of image][maximum value of color]". + try std.fmt.format(file.writer(), "P3\n{d} {d}\n255\n", .{ pile.len, pile.len }); + + for (pile) |row| { + var line = std.ArrayList(u8).init(allocator); + defer line.deinit(); + + // We map each value in the field to a color. + for (row) |elem| { + const color = switch (elem) { + 0 => "100 40 15 ", + 1 => "117 87 30 ", + 2 => "181 134 47 ", + 3 => "245 182 66 ", + else => unreachable, + }; + try line.appendSlice(color); + } + + try std.fmt.format(file.writer(), "{s}\n", .{line.items}); + } +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + // This is how big the final image will be. Currently the end result would be a 16x16 picture. + const field_size: usize = 16; + + // Create the 2D array + var playfield = try allocator.alloc([]usize, field_size); + defer { + for (playfield) |row| { + allocator.free(row); + } + allocator.free(playfield); + } + + for (playfield, 0..) |_, i| { + playfield[i] = try allocator.alloc(usize, field_size); + @memset(playfield[i], 0); + } + + // We put the initial sand in the exact middle of the field. + // This isn't necessary per se, but it ensures that sand can fully topple. + var boundary = [4]usize{ field_size / 2 - 1, field_size / 2 - 1, field_size / 2, field_size / 2 }; + playfield[field_size / 2 - 1][field_size / 2 - 1] = 16; + + // This is the main loop. We update the field until it returns false, signalling that the pile reached its + // final state. + while (advance(playfield, &boundary)) {} + + // Once this happens, we simply display the result. Uncomment the line below to write it to a file. + // Calling display with large field sizes is not recommended as it can easily become too large for the console. + display(playfield); + // try write_pile(playfield, allocator); +} diff --git a/Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-1.pas b/Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-1.pas new file mode 100644 index 0000000000..503c7d46f7 --- /dev/null +++ b/Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-1.pas @@ -0,0 +1,60 @@ +program abstracts; +// this code also compiles in delphi +{$ifdef fpc}{$mode objfpc}{$endif} +type + // Pure Abstract Class. In cs theory also known as an interface, + // because it has no implementation + TAbstractClass = class abstract + protected + function noise:string;virtual;abstract; + end; + // classic inheritance + Tdog = class(TAbstractClass) + public + function noise:string;override; + end; + + Tcat = class(TAbstractClass) + public + function noise:string;override; + end; + + // unrelated class that matches the interface of TAbstractClass, the VMT. + Tbird = class + strict private + FField:string; + function noise:string;virtual; + property field:string read FField write FField; + end; + + function Tdog.Noise:string; + begin + Result := 'Woof'; + end; + + function Tcat.Noise:string; + begin + Result := 'Miauw'; + end; + + function TBird.Noise:string; + begin + Result := 'Tjirpp'; + end; + +var + cat, dog: TAbstractClass; + bird:Tbird; +begin + cat := Tcat.Create; + dog := Tdog.Create; + bird := TBird.Create; + writeln(cat.noise,dog.noise); + // even this works, because the layout is the same + // This is similar to C++, where pure abstract classes are interfaces. + writeln(TAbstractClass(bird).noise); + bird.free; + dog.free; + cat.free; + readln; +end. diff --git a/Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-2.pas b/Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-2.pas new file mode 100644 index 0000000000..255d8ba86d --- /dev/null +++ b/Task/Abstract-type/Free-Pascal-Lazarus/abstract-type-2.pas @@ -0,0 +1,32 @@ +program justasabstract; +{$ifdef fpc}{$mode objfpc}{$endif} +type + IAnimalInterface = interface + ['{BD40E312-36AD-4F8B-A3EF-727F2474E494}'] + function noise:string; + function move:string; + end; + + Tbird = class(TInterfacedObject,IAnimalInterface) + strict private + function noise:string;virtual; + function move:string;virtual; + end; + + function TBird.Noise:string; + begin + Result := 'Tjirpp'; + end; + + function TBird.move:string; + begin + Result := 'I fly'; + end; + +var + bird:IAnimalInterface; // as interface, this unhides the strict private methods too. +begin + bird := TBird.Create; + writeln(bird.noise); + writeln(bird.move); +end. diff --git a/Task/Abstract-type/Haxe/abstract-type-1.haxe b/Task/Abstract-type/Haxe/abstract-type-1.haxe new file mode 100644 index 0000000000..91134488e5 --- /dev/null +++ b/Task/Abstract-type/Haxe/abstract-type-1.haxe @@ -0,0 +1,44 @@ +interface Vocal { + public function speak():String; +} + +interface Gravitational { + public function getWeight():Int; +} + +abstract class Dog implements Vocal implements Gravitational { + public function speak():String { + return "Woof"; + } + + public function new() {} +} + +class Chihuahua extends Dog { + public function getWeight():Int { + return 5; + } +} + +class GreatDane extends Dog { + public function getWeight():Int { + return 150; + } +} + +class Main { + static public function main():Void { + var dogs:Array = []; + + var david = new Chihuahua(); + var goliath = new GreatDane(); + + dogs.push(david); + dogs.push(goliath); + + for (dog in dogs) { + trace(dog.speak()); + trace(dog.getWeight()); + } + } +} diff --git a/Task/Abstract-type/Haskell/abstract-type-6.hs b/Task/Abstract-type/Haxe/abstract-type-2.haxe similarity index 100% rename from Task/Abstract-type/Haskell/abstract-type-6.hs rename to Task/Abstract-type/Haxe/abstract-type-2.haxe diff --git a/Task/Abstract-type/Pluto/abstract-type.pluto b/Task/Abstract-type/Pluto/abstract-type.pluto new file mode 100644 index 0000000000..23e2c80efd --- /dev/null +++ b/Task/Abstract-type/Pluto/abstract-type.pluto @@ -0,0 +1,34 @@ +class Beast + function __construct() + error("Instantiation not allowed as class is abstract.") + end + + function kind() end + function name() end + function cry() end + + function print() + print($'{self:name()}, who\'s a {self:kind()}, cries: "{self:cry()}".') + end +end + +class Dog extends Beast + function __construct(private kind, private name) end + + function kind() return self.kind end + function name() return self.name end + function cry() return "Woof" end +end + +class Cat extends Beast + function __construct(private kind, private name) end + + function kind() return self.kind end + function name() return self.name end + function cry() return "Meow" end +end + +local d = new Dog("labrador", "Max") +local c = new Cat("siamese", "Sammy") +d:print() +c:print() diff --git a/Task/Abstract-type/REBOL/abstract-type.rebol b/Task/Abstract-type/REBOL/abstract-type.rebol index 353bba0dd1..184d2223f1 100644 --- a/Task/Abstract-type/REBOL/abstract-type.rebol +++ b/Task/Abstract-type/REBOL/abstract-type.rebol @@ -40,5 +40,5 @@ s: make shape [] s/draw ; Nothing happens. print "A box:" b: make box [pen: "O" size: 5] b/draw -print [crlf "A rectangle:"] +print "^/A rectangle:" r: make rectangle [size: 32x5] r/draw diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Agena/abundant-deficient-and-perfect-number-classifications.agena b/Task/Abundant-deficient-and-perfect-number-classifications/Agena/abundant-deficient-and-perfect-number-classifications.agena new file mode 100644 index 0000000000..0e13d96df2 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Agena/abundant-deficient-and-perfect-number-classifications.agena @@ -0,0 +1,21 @@ +scope # count abundant, perfect and deficient numbers up to 20 000 + # construct a table of proper divisor sums + local constant MAX_NUMBER, constant pds := 20_000, seq(); + pds[ 1 ] := 0; + for i from 2 to MAX_NUMBER do pds[ i ] := 1 od; + for i from 2 to MAX_NUMBER do + for j from i + i to MAX_NUMBER by i do pds[ j ] +:= i od; + od; + # classify the numbers and count each type + local aCount, dCount, pCount := 0, 0, 0; + for i to MAX_NUMBER do + local constant dSum := pds[ i ]; + if dSum > i then aCount +:= 1 + elif dSum < i then dCount +:= 1 + else pCount +:= 1 + fi + od; + printf( "Abundant numbers up to %.0m: %8.0m\n", MAX_NUMBER, aCount ); + printf( "Perfect numbers up to %.0m: %8.0m\n", MAX_NUMBER, pCount ); + printf( "Deficient numbers up to %.0m: %8.0m\n", MAX_NUMBER, dCount ) +end diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Fennel/abundant-deficient-and-perfect-number-classifications.fennel b/Task/Abundant-deficient-and-perfect-number-classifications/Fennel/abundant-deficient-and-perfect-number-classifications.fennel new file mode 100644 index 0000000000..04ca0eabc8 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Fennel/abundant-deficient-and-perfect-number-classifications.fennel @@ -0,0 +1,21 @@ +(do ;;; count abundant, perfect and deficient numbers up to 20 000 + ; construct a table of proper divisor sums + (local (max-number pds) (values 20_000 [])) + (tset pds 1 0) + (for [i 2 max-number] (tset pds i 1)) + (for [i 2 max-number] + (for [j (+ i i) max-number i] (tset pds j (+ i (. pds j)))) + ) + ; classify the numbers and count each type + (var (aCount dCount pCount) (values 0 0 0)) + (for [i 1 max-number] + (local dSum (. pds i)) + (if (> dSum i) (set aCount (+ aCount 1)) + (< dSum i) (set dCount (+ dCount 1)) + (set pCount (+ pCount 1)) + ) + ) + (io.write (string.format "Abundant numbers up to %d: %8d\n" max-number aCount)) + (io.write (string.format "Perfect numbers up to %d: %8d\n" max-number pCount)) + (io.write (string.format "Deficient numbers up to %d: %8d\n" max-number dCount)) +) diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Pluto/abundant-deficient-and-perfect-number-classifications.pluto b/Task/Abundant-deficient-and-perfect-number-classifications/Pluto/abundant-deficient-and-perfect-number-classifications.pluto new file mode 100644 index 0000000000..31fc30e8c2 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Pluto/abundant-deficient-and-perfect-number-classifications.pluto @@ -0,0 +1,26 @@ +do -- count abundant, perfect and deficient numbers up to 20 000 + + local fmt = require( "fmt" ) -- RC Pluto formatting library + + -- construct a table of proper divisor sums + local maxNumber , pds = 20_000, {} + pds[ 1 ] = 0 + for i = 2, maxNumber do pds[ i ] = 1 end + for i = 2, maxNumber do + for j = i + i, maxNumber, i do pds[ j ] += i end + end + + -- classify the numbers and count each type + local aCount, dCount, pCount = 0, 0, 0 + for i = 1, maxNumber do + local dSum = pds[ i ] + if dSum > i then aCount += 1 + elseif dSum < i then dCount += 1 + else pCount += 1 + end + end + local formattedMax = string.formatint( maxNumber ) + fmt.write( "Abundant numbers up to %s: %8s\n", formattedMax, string.formatint( aCount ) ) + fmt.write( "Perfect numbers up to %s: %8s\n", formattedMax, string.formatint( pCount ) ) + fmt.write( "Deficient numbers up to %s: %8s\n", formattedMax, string.formatint( dCount ) ) +end diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Prolog/abundant-deficient-and-perfect-number-classifications.pro b/Task/Abundant-deficient-and-perfect-number-classifications/Prolog/abundant-deficient-and-perfect-number-classifications.pro index b0a87e05b3..26bfe44194 100644 --- a/Task/Abundant-deficient-and-perfect-number-classifications/Prolog/abundant-deficient-and-perfect-number-classifications.pro +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Prolog/abundant-deficient-and-perfect-number-classifications.pro @@ -3,18 +3,19 @@ proper_divisors(N, [1|L]) :- FSQRTN is floor(sqrt(N)), proper_divisors(2, FSQRTN, N, L). -proper_divisors(M, FSQRTN, _, []) :- - M > FSQRTN, - !. -proper_divisors(M, FSQRTN, N, L) :- - N mod M =:= 0, !, - MO is N//M, % must be integer - L = [M,MO|L1], % both proper divisors - M1 is M+1, - proper_divisors(M1, FSQRTN, N, L1). -proper_divisors(M, FSQRTN, N, L) :- - M1 is M+1, - proper_divisors(M1, FSQRTN, N, L). +proper_divisors(M, FSQRTN, N, [MS|L]) :- + between(M, FSQRTN, D1), + N mod D1 =:= 0, !, + D2 is N//D1, % must be integer + ( D1 < D2 + -> + MS is D1 + D2, % already sum here + M2 is D1 + 1, + proper_divisors(M2, FSQRTN, N, L) + ; + MS is D1, L = [] % D1 only once + ). +proper_divisors(_, _FSQRTN, _, []) :- !. dpa(1, [1], [], []) :- !. diff --git a/Task/Abundant-odd-numbers/ALGOL-68/abundant-odd-numbers.alg b/Task/Abundant-odd-numbers/ALGOL-68/abundant-odd-numbers.alg index 4bc494606d..cc24a232e3 100644 --- a/Task/Abundant-odd-numbers/ALGOL-68/abundant-odd-numbers.alg +++ b/Task/Abundant-odd-numbers/ALGOL-68/abundant-odd-numbers.alg @@ -1,7 +1,5 @@ -BEGIN - # find some abundant odd numbers - numbers where the sum of the proper # - # divisors is bigger than the number # - # itself # +BEGIN # find some abundant odd numbers - numbers wose the proper divisor sum # + # is bigger than the number itself # # returns the sum of the proper divisors of n # PROC divisor sum = ( INT n )INT: @@ -41,34 +39,20 @@ BEGIN # 1000th odd abundant number # WHILE a count < 1 000 DO IF ( d sum := divisor sum( odd number ) ) > odd number THEN - a count := a count + 1 + a count +:= 1 FI; odd number +:= 2 OD; - print( ( "1000th abundant odd number:" - , newline - , " " - , whole( odd number - 2, 0 ) - , " proper divisor sum: " - , whole( d sum, 0 ) - , newline - ) - ); + print( ( "1000th abundant odd number:", newline, " " ) ); + print( ( whole( odd number - 2, 0 ), " proper divisor sum: ", whole( d sum, 0 ), newline ) ); # first odd abundant number > one billion # odd number := 1 000 000 001; BOOL found := FALSE; WHILE NOT found DO IF ( d sum := divisor sum( odd number ) ) > odd number THEN found := TRUE; - print( ( "First abundant odd number > 1 000 000 000:" - , newline - , " " - , whole( odd number, 0 ) - , " proper divisor sum: " - , whole( d sum, 0 ) - , newline - ) - ) + print( ( "First abundant odd number > 1 000 000 000:", newline, " " ) ); + print( ( whole( odd number, 0 ), " proper divisor sum: ", whole( d sum, 0 ), newline ) ) FI; odd number +:= 2 OD diff --git a/Task/Abundant-odd-numbers/Agena/abundant-odd-numbers.agena b/Task/Abundant-odd-numbers/Agena/abundant-odd-numbers.agena new file mode 100644 index 0000000000..498c14b6a4 --- /dev/null +++ b/Task/Abundant-odd-numbers/Agena/abundant-odd-numbers.agena @@ -0,0 +1,52 @@ +scope # find some abundant snumbers + # - numbers whose proper divisor sum is bigger than the number itself + + # returns the sum of the proper divisors of n + local constant divisor_sum := proc( n :: number ) :: number is + local sum := 1; + for d from 2 to entier sqrt( n ) do + if n mod d = 0 then + sum +:= d; + other_d := n \ d; + if other_d <> d then + sum +:= other_d + fi + fi + od; + return sum + end; + scope # find the numbers required by the task + # first 25 odd abundant numbers + local odd_number, a_count, d_sum := 1, 0, 0; + print( "The first 25 abundant odd numbers:" ); + while a_count < 25 do + d_sum := divisor_sum( odd_number ); + if d_sum > odd_number then + a_count +:= 1; + printf( "%6d proper divisor sum: %d\n", odd_number, d_sum ); + fi; + odd_number +:= 2 + od; + # 1000th odd abundant number + while a_count < 1_000 do + d_sum := divisor_sum( odd_number ); + if d_sum > odd_number then + a_count +:= 1 + fi; + odd_number +:= 2 + od; + printf( "1000th abundant odd number:\n %d proper divisor sum: %d\n", odd_number, d_sum ); + # first odd abundant number > one billion + odd_number := 1_000_000_001; + local found := false; + while not found do + d_sum := divisor_sum( odd_number ); + if d_sum > odd_number then + found := true; + print( "First abundant odd_number > 1 000 000 000:" ); + printf( " %d proper divisor sum: %d\n", odd_number, d_sum ); + fi; + odd_number +:= 2 + od + end +end diff --git a/Task/Abundant-odd-numbers/Pluto/abundant-odd-numbers.pluto b/Task/Abundant-odd-numbers/Pluto/abundant-odd-numbers.pluto new file mode 100644 index 0000000000..2147c9f991 --- /dev/null +++ b/Task/Abundant-odd-numbers/Pluto/abundant-odd-numbers.pluto @@ -0,0 +1,35 @@ +local int = require "int" +local fmt = require "fmt" +require "table2" + +local function abundant_odd(search_from, count_from, count_to, print_one) + local count = count_from + local n = search_from + while count < count_to do + local divs = int.divisors(n, true) + local tot = #divs > 0 ? (divs:sum()) : 0 + if tot > n then + ++count + if !print_one or count >= count_to then + local s = fmt.swrite(divs, " + ", "") + if !print_one then + fmt.print("%2d. %5d < %s = %d", count, n, s, tot) + else + fmt.print("%d < %s = %d", n, s, tot) + end + end + end + n += 2 + end + return n +end + +local MAX = 25 +print($"The first {MAX} abundant odd numbers are:") +local n = abundant_odd(1, 0, 25, false) + +print("\nThe one thousandth abundant odd number is:") +abundant_odd(n, 25, 1000, true) + +print("\nThe first abundant odd number above one billion is:") +abundant_odd(1e9 + 1, 0, 1, true) diff --git a/Task/Accumulator-factory/REBOL/accumulator-factory.rebol b/Task/Accumulator-factory/REBOL/accumulator-factory-1.rebol similarity index 70% rename from Task/Accumulator-factory/REBOL/accumulator-factory.rebol rename to Task/Accumulator-factory/REBOL/accumulator-factory-1.rebol index 35b5392daf..0738505b60 100644 --- a/Task/Accumulator-factory/REBOL/accumulator-factory.rebol +++ b/Task/Accumulator-factory/REBOL/accumulator-factory-1.rebol @@ -6,3 +6,6 @@ make-acc-gen: func [start-val] [ ] ] ] +gen: make-acc-gen 1 +print gen 5 ;== 6 +print gen 2.3 ;== 8.3 diff --git a/Task/Accumulator-factory/REBOL/accumulator-factory-2.rebol b/Task/Accumulator-factory/REBOL/accumulator-factory-2.rebol new file mode 100644 index 0000000000..02468d5450 --- /dev/null +++ b/Task/Accumulator-factory/REBOL/accumulator-factory-2.rebol @@ -0,0 +1,25 @@ +;; Define a generator function 'gen' with an optional refinement '/init' +;; - 'value' is a required number passed to the function +;; - '/init' is an optional refinement for initialization +gen: function/with [value [number!] /init] [ + + ;; If '/init' refinement is used, initialize state and exit immediately + if init [ + state: value ;; Set the initial state to the provided value + exit ;; Exit, so nothing else in the function is run + ] + + ;; If not initializing, add 'value' to 'state' + state: state + value + + ;; The function returns the new state each call +][state: 0] ;; 'state' is a local variable, initialized once per definition (persistent closure) + +;; Initialize the 'state' value of gen to 1 by calling it with '/init' +gen/init 1 + +;; Call gen with 5: Adds 5 to state and prints the result (should print 6) +print gen 5 + +;; Call gen with 2.3: Adds 2.3 to state and prints the result (should print 8.3) +print gen 2.3 diff --git a/Task/Achilles-numbers/Pluto/achilles-numbers.pluto b/Task/Achilles-numbers/Pluto/achilles-numbers.pluto new file mode 100644 index 0000000000..f28f017194 --- /dev/null +++ b/Task/Achilles-numbers/Pluto/achilles-numbers.pluto @@ -0,0 +1,63 @@ +local int = require "int" +local fmt = require "fmt" + +$define MAX_DIGITS = 15 + +local pps = {} + +local function get_perfect_powers(max_exp) + local upper = 10 ^ max_exp + for i = 2.0, int.sqrt(upper) do + local p = i + while true do + p *= i + if p >= upper then break end + pps[p] = true + end + end +end + +local function get_achilles(min_exp, max_exp) + local lower = 10 ^ min_exp + local upper = 10 ^ max_exp + local achilles = {} -- avoids duplicates + for b = 1.0, int.cbrt(upper) do + local b3 = b * b * b + for a = 1.0, int.sqrt(upper) do + local p = b3 * a * a + if p >= upper then break end + if p >= lower then + if !pps[p] then achilles[p] = true end + end + end + end + return achilles +end + +get_perfect_powers(MAX_DIGITS) +local achilles_set = get_achilles(1, 5) -- enough for first 2 parts +local achilles = achilles_set:keys() +achilles:sort() + +print("First 50 Achilles numbers:") +fmt.tprint("%4d", achilles:slice(1, 50), 10) + +print("\nFirst 30 strong Achilles numbers:") +local strong_achilles = {} +local count = 0 +local n = 1 +while count < 30 do + local tot = int.totient(achilles[n]) + if achilles_set[tot] then + strong_achilles:insert(achilles[n]) + ++count + end + ++n +end +fmt.tprint("%5d", strong_achilles, 10) + +print("\nNumber of Achilles numbers with:") +for d = 2, MAX_DIGITS do + local ac = get_achilles(d - 1, d):size() + fmt.print("%2d digits: %d", d, ac) +end diff --git a/Task/Ackermann-function/ArkScript/ackermann-function.ark b/Task/Ackermann-function/ArkScript/ackermann-function.ark new file mode 100644 index 0000000000..c662b841df --- /dev/null +++ b/Task/Ackermann-function/ArkScript/ackermann-function.ark @@ -0,0 +1,8 @@ +(let ackermann (fun (m n) { + (if (> m 0) + (if (= 0 n) + (ackermann (- m 1) 1) + (ackermann (- m 1) (ackermann m (- n 1)))) + (+ 1 n)) })) + +(assert (= 509 (ackermann 3 6)) "(ackermann 3 6) == 509") diff --git a/Task/Ackermann-function/Pluto/ackermann-function.pluto b/Task/Ackermann-function/Pluto/ackermann-function.pluto new file mode 100644 index 0000000000..91075937c7 --- /dev/null +++ b/Task/Ackermann-function/Pluto/ackermann-function.pluto @@ -0,0 +1,13 @@ +function ack(m,n) + if m==0 then + return n+1 + elseif n == 0 then + return ack(m-1,1) + else return ack(m-1,ack(m,n-1)) end +end + +for i = 0,3 do + for j = 0,8 do + print($"A({i},{j})={ack(i,j)}") + end +end diff --git a/Task/Ackermann-function/REBOL/ackermann-function-1.rebol b/Task/Ackermann-function/REBOL/ackermann-function-1.rebol new file mode 100644 index 0000000000..52928c349e --- /dev/null +++ b/Task/Ackermann-function/REBOL/ackermann-function-1.rebol @@ -0,0 +1,7 @@ +ackermann: func [m n] [ + case [ + m = 0 [n + 1] + n = 0 [ackermann m - 1 1] + true [ackermann m - 1 ackermann m n - 1] + ] +] diff --git a/Task/Ackermann-function/REBOL/ackermann-function-2.rebol b/Task/Ackermann-function/REBOL/ackermann-function-2.rebol new file mode 100644 index 0000000000..c6e294cb60 --- /dev/null +++ b/Task/Ackermann-function/REBOL/ackermann-function-2.rebol @@ -0,0 +1,16 @@ +ackermann: func [ + m [integer!] + n [integer!] +] [ + ;; Small-m closed forms + case [ + m = 0 [n + 1] + m = 1 [n + 2] + m = 2 [(2 * n) + 3] + m = 3 [ + ;; 2^(n+3) - 3 + (to integer! power 2 (n + 3)) - 3 + ] + ;; m >= 4 causes stack overflow + ] +] diff --git a/Task/Ackermann-function/TAV/ackermann-function.tav b/Task/Ackermann-function/TAV/ackermann-function.tav new file mode 100644 index 0000000000..f81000b3c8 --- /dev/null +++ b/Task/Ackermann-function/TAV/ackermann-function.tav @@ -0,0 +1,11 @@ +ackermann (n) (m) : + ? n = 0 + :> m+1 + ? m = 0 + :> ackermann (n-1) 1 + :> ackermann (n-1) ackermann n (m-1) \ = ackermann (n-1) (ackermann n (m-1)) +\ test it +main(params):+ + p1 =: string params[1] as integer else 3 + p2 =: string params[2] as integer else 5 + print "ackermann(" _ p1 _ "," _ p2 _ ") = " _ ackermann p1 p2 diff --git a/Task/Address-of-a-variable/Pluto/address-of-a-variable.pluto b/Task/Address-of-a-variable/Pluto/address-of-a-variable.pluto new file mode 100644 index 0000000000..7230dc3a18 --- /dev/null +++ b/Task/Address-of-a-variable/Pluto/address-of-a-variable.pluto @@ -0,0 +1,6 @@ +local s = "" +local t = {} +local function f() end +local n = 1 +local b = true +print(string.format("%p\t%p\t%p\t%p\t%p", s, t, f, n, b)) diff --git a/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx b/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx index 21c8179c31..355580acf3 100644 --- a/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx +++ b/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx @@ -1 +1,18 @@ -zzz = storage(xxx) +-- 7 Aug 2025 +include Settings + +say 'ADDRESS OF A VARIABLE' +say version +say +if Pos('Regina',version) > 0 then + call Library +call Primes 10 +call SysDumpVariables +exit + +Library: +call RxFuncAdd 'SysLoadFuncs','RegUtil','SysLoadFuncs' +call SysLoadFuncs +return + +include Math diff --git a/Task/Address-of-a-variable/RISC-V-Assembly/address-of-a-variable.asm b/Task/Address-of-a-variable/RISC-V-Assembly/address-of-a-variable.asm new file mode 100644 index 0000000000..9a7e83e30b --- /dev/null +++ b/Task/Address-of-a-variable/RISC-V-Assembly/address-of-a-variable.asm @@ -0,0 +1,128 @@ +# riscv assembly raspberry pico2 rp2350 +# program adrvariable.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szCariageReturn: .asciz "\r\n" +.align 2 +tabValues: .int 1,2,3,4 + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +ivalue1: .skip 4 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la t1,ivalue1 # variable address + lw a0,(t1) # load word value + call displayResult + la t1,ivalue1 # variable address + li t0,12345 # new value + sw t0,(t1) # store word value + la t1,ivalue1 # variable address + lw a0,(t1) # load value for control + call displayResult + la t1,tabValues # load array address + lw a0,8(t1) # load value at byte 8 of array + call displayResult + la t1,tabValues # load array address + li t2,3 # init index value + slli t2,t2,2 # multiply index by 5 (integer size) + add t2,t2,t1 # add offset to array address + lw a0,(t2) # load value of index + call displayResult + + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* displayResult */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResult: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # conversion decimal + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* decimal conversion */ +/**********************************************/ +/* a0 value */ +/* a1 conversion array address */ +.equ LGZONECONV, 20 +conversion10: + addi sp, sp, -4 + sw ra, 0(sp) + li t1,LGZONECONV + li t2,10 # divisor +1: + rem t4,a0,t2 # division remainder by 10 + addi t4,t4,48 # convert to decimal + add t5,a1,t1 # store character position + sb t4,(t5) # store byte + div a0,a0,t2 # compute quotient + beq a0,x0,2f # compare to 0 + addi t1,t1,-1 # decrement store position + bgt t1,x0,1b # and loop if position is ok +2: + li t2,0 # raz indice + li t3,LGZONECONV +3: # loop to transfer result at begining conversion area + add t5,a1,t1 # compute start position + lb t4,(t5) # load byte + add t5,a1,t2 # compute new position + sb t4,(t5) # and store byte + addi t2,t2,1 # increment indice + addi t1,t1,1 + ble t1,t3,3b # and loop if indice <= area size + add t5,a1,t2 # increment final position + sb x0,(t5) # and store byte final zero + mv a0,t2 # return size conversion + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Address-of-a-variable/Red/address-of-a-variable.red b/Task/Address-of-a-variable/Red/address-of-a-variable.red new file mode 100644 index 0000000000..f23545f25f --- /dev/null +++ b/Task/Address-of-a-variable/Red/address-of-a-variable.red @@ -0,0 +1,17 @@ +Red/System [] + +print ["pointer test:" newline] + +a: 100 +print ["a is an integer variable, value: " a newline] + +p: declare pointer! [integer!] +p: :a +print ["p is the address of a: " p newline] +print ["p/value refer to the value pointed to by p: " p/value newline] + +q: declare pointer! [integer!] +q: p + 1 +print ["q is p + 1: " q " q/value is (uninitialized): " q/value newline] + +print ["q - p: " (q - p) newline] diff --git a/Task/Align-columns/ALGOL-68/align-columns.alg b/Task/Align-columns/ALGOL-68/align-columns.alg index ae3186556c..056358ac56 100644 --- a/Task/Align-columns/ALGOL-68/align-columns.alg +++ b/Task/Align-columns/ALGOL-68/align-columns.alg @@ -27,37 +27,38 @@ make term(text in file, "$"); on physical file end(text in file, (REF FILE skip)BOOL: stop iteration); on logical file end(text in file, (REF FILE skip)BOOL: stop iteration); +BOOL at eol := FALSE; +on line end(text in file, (REF FILE skip)BOOL: at eol := TRUE); FOR row DO - on line end(text in file, (REF FILE skip)BOOL: stop iteration); - FOR col DO - STRING tok; + at eol := FALSE; + FOR col WHILE NOT at eol DO + STRING tok := ""; getf(text in file, ($gx$,tok)); - IF row > 1 UPB page THEN page := flex page(page, row, 2 UPB page) FI; - IF col > 2 UPB page THEN page := flex page(page, 1 UPB page, col) FI; - page[row,col]:=tok - OD; - stop iteration: - SKIP + IF tok NE "" OR NOT at eol THEN + IF row > 1 UPB page THEN page := flex page(page, row, 2 UPB page) FI; + IF col > 2 UPB page THEN page := flex page(page, 1 UPB page, col) FI; + page[row,col]:=tok + FI + OD OD; stop iteration: SKIP; BEGIN - PROC aligner = (PAGE in page, PROC (STRING,INT)STRING aligner)VOID:( - PAGE page := in page; - [2 UPB page]INT max width; + PROC aligner = (PAGE in page, PROC (STRING,INT)STRING alignf)VOID:( + PAGE al page := in page; FOR col TO 2 UPB page DO - INT max len:=0; FOR row TO UPB page DO IF UPB page[row,col]>max len THEN max len:=UPB page[row,col] FI OD; - FOR row TO UPB page DO page[row,col] := aligner(page[row,col], maxlen) OD + INT max len:=0; FOR row TO UPB al page DO IF UPB al page[row,col]>max len THEN max len:=UPB al page[row,col] FI OD; + FOR row TO UPB al page DO al page[row,col] := alignf(page[row,col], maxlen) OD OD; - printf(($n(UPB page)(n(2 UPB page -1)(gx)gl)$,page)) + printf(($n(UPB page)(n(2 UPB page -1)(gx)gl)$,al page)) ); PROC left = (STRING in, INT len)STRING: in + " "*(len - UPB in), right = (STRING in, INT len)STRING: " "*(len - UPB in) + in, centre = (STRING in, INT len)STRING: ( INT pad=len-UPB in; pad%2*" "+ in + (pad-pad%2)*" " ); - []STRUCT(STRING name, PROC(STRING,INT)STRING align) aligners = (("Left",left), ("Left",right), ("Centre",centre)); + []STRUCT(STRING name, PROC(STRING,INT)STRING align) aligners = (("Left",left), ("right",right), ("Centre",centre)); FOR index TO UPB aligners DO print((new line, "# ",name OF aligners[index]," Column-aligned output:",new line)); diff --git a/Task/Aliquot-sequence-classifications/JavaScript/aliquot-sequence-classifications.js b/Task/Aliquot-sequence-classifications/JavaScript/aliquot-sequence-classifications.js new file mode 100644 index 0000000000..bd6d59798d --- /dev/null +++ b/Task/Aliquot-sequence-classifications/JavaScript/aliquot-sequence-classifications.js @@ -0,0 +1,81 @@ +// See https://en.wikipedia.org/wiki/Divisor_function +function divisorSum(n) { + let total = 1n; + let power = 2n; + // Deal with powers of 2 first + for (; n % 2n === 0n; power *= 2n, n /= 2n) { + total += power; + } + // Odd prime factors up to the square root + for (let p = 3n; p * p <= n; p += 2n) { + let sum = 1n; + for (power = p; n % p === 0n; power *= p, n /= p) { + sum += power; + } + total *= sum; + } + // If n > 1 then it's prime + if (n > 1n) { + total *= n + 1n; + } + return total; +} + +// See https://en.wikipedia.org/wiki/Aliquot_sequence +function classifyAliquotSequence(n) { + const limit = 16; + const terms = new Array(limit); + terms[0] = n; + let classification = "non-terminating"; + let length = 1; + + for (let i = 1; i < limit; ++i) { + ++length; + terms[i] = divisorSum(terms[i - 1]) - terms[i - 1]; + + if (terms[i] === n) { + classification = + (i === 1 ? "perfect" : (i === 2 ? "amicable" : "sociable")); + break; + } + + let j = 1; + for (; j < i; ++j) { + if (terms[i] === terms[i - j]) { + break; + } + } + + if (j < i) { + classification = (j === 1 ? "aspiring" : "cyclic"); + break; + } + + if (terms[i] === 0n) { + classification = "terminating"; + break; + } + } + + let output = `${n}: ${classification}, sequence: ${terms[0]}`; + for (let i = 1; i < length && terms[i] !== terms[i - 1]; ++i) { + output += ` ${terms[i]}`; + } + console.log(output); +} + +function main() { + for (let i = 1n; i <= 10n; ++i) { + classifyAliquotSequence(i); + } + + const specialNumbers = [11n, 12n, 28n, 496n, 220n, 1184n, 12496n, 1264460n, 790n, 909n, 562n, 1064n, 1488n]; + for (const i of specialNumbers) { + classifyAliquotSequence(i); + } + + classifyAliquotSequence(15355717786080n); + classifyAliquotSequence(153557177860800n); +} + +main(); diff --git a/Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.ada b/Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.ada new file mode 100644 index 0000000000..400094aff2 --- /dev/null +++ b/Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.ada @@ -0,0 +1,94 @@ +-- Big_Reals is an Ada 2022 unit +with Ada.Numerics.Big_Numbers.Big_Reals; +with Ada.Text_IO; + +use Ada.Numerics.Big_Numbers.Big_Reals; + +procedure Almkvist_Giullera is + + function "+" (B : Big_Real; A : Integer) return Big_Real is (B + To_Real (A)); + function "*" (A : Integer; B : Big_Real) return Big_Real is (To_Real (A) * B); + B0 : constant Big_Real := To_Real (0); + B1 : constant Big_Real := B0 + 1; + + function Factorial (N : Big_Real) return Big_Real + is + I : Big_Real := N; + F : Big_Real := B1; + begin + while I > B1 loop + F := F * I; + I := I - B1; + end loop; + + return F; + end Factorial; + + function F (N : Big_Real) return Big_Real renames Factorial; + procedure Put_Line (S : String) renames Ada.Text_IO.Put_Line; + + function Integer_Term (N : Big_Real) return Big_Real is + (32 * F (6 * N) / (3 * F (N) ** 6) * (532 * N ** 2 + 126 * N + 9)); + + procedure Show_Integer_Terms (N : Positive) is + begin + for I in 0 .. N - 1 loop + Put_Line ("Almkvist-Giullera integer term " + & I'Image & " is " + & To_String (Integer_Term (To_Real (I)), Aft => 0)); + end loop; + end Show_Integer_Terms; + + -- Use Newton's Method + function Sqrt (N : Big_Real; Precision : Positive) return Big_Real is + Diff : Big_Real := To_Real (10) ** (-Precision); + Estimate : Big_Real := B0; + Next : Big_Real := N; + begin + while abs (Next - Estimate) > Diff loop + Estimate := Next; + Next := Estimate - (Estimate ** 2 - N) / (2 * Estimate); + -- Nasty hack to limit precision. Otherwise there is a storage error. + Next := From_String (To_String (Next, Aft => Precision + 2)); + end loop; + + return Estimate; + end Sqrt; + + function Estimate_Pi (N : Integer; Precision : Positive) return Big_Real is + Sum : Big_Real := B0; + begin + for I in 0 .. N loop + Sum := Sum + Integer_Term (To_Real (I)) / To_Real (10) ** (6 * I + 3); + Sum := From_String (To_String (Sum, Aft => Precision + 2)); + end loop; + + return B1 / Sqrt (Sum, Precision + 2); + end Estimate_Pi; + + function Compute_Pi (Precision : Positive) return Big_Real is + Diff : constant Big_Real := To_Real (10) ** (-Precision); + Pi_Estimate : Big_Real := B0; + Next : Big_Real := B1; + N : Integer := 1; + begin + while abs (Next - Pi_Estimate) > Diff loop + N := N * 2; + Pi_Estimate := Next; + Next := Estimate_Pi (N, Precision); + end loop; + + return Pi_Estimate; + end Compute_Pi; + + procedure Show_Pi (Precision : Positive) is + Pi : constant Big_Real := Compute_Pi (Precision); + begin + Put_Line ("Pi to " & Precision'Image & " places is " + & To_String (Pi, Aft => Precision)); + end Show_Pi; + +begin + Show_Integer_Terms (10); + Show_Pi (70); +end almkvist_giullera; diff --git a/Task/Almost-prime/Icon/almost-prime-1.icon b/Task/Almost-prime/Icon/almost-prime-1.icon index 297458b93a..3b44419065 100644 --- a/Task/Almost-prime/Icon/almost-prime-1.icon +++ b/Task/Almost-prime/Icon/almost-prime-1.icon @@ -6,5 +6,5 @@ procedure main() end procedure genKap(k) - suspend (k = *factors(n := seq(q)), n) + suspend (k = *factors(n := seq()), n) end diff --git a/Task/Almost-prime/Pluto/almost-prime.pluto b/Task/Almost-prime/Pluto/almost-prime.pluto new file mode 100644 index 0000000000..042adee1e9 --- /dev/null +++ b/Task/Almost-prime/Pluto/almost-prime.pluto @@ -0,0 +1,26 @@ +local function k_prime(n, k) + local nf = 0 + for i = 2, n do + while n % i == 0 do + if nf == k then return false end + ++nf + n //= i + end + end + return nf == k +end + +local function gen(k, n) + local r = {} + local m = 2 + for i = 1, n do + while !k_prime(m, k) do ++m end + r[i] = m + ++m + end + return r +end + +for k = 1, 5 do + print($"{k}: {gen(k, 10):concat(", ")}") +end diff --git a/Task/Amb/Ada/amb.ada b/Task/Amb/Ada/amb-1.ada similarity index 100% rename from Task/Amb/Ada/amb.ada rename to Task/Amb/Ada/amb-1.ada diff --git a/Task/Amb/Ada/amb-2.ada b/Task/Amb/Ada/amb-2.ada new file mode 100644 index 0000000000..d2fd093f18 --- /dev/null +++ b/Task/Amb/Ada/amb-2.ada @@ -0,0 +1,78 @@ +-- MacOS, GNAT, gnat-aarch64-darwin-15.1.0-2 +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Amb is + type Alternatives is array (Positive range <>) of Unbounded_String; + + type Amb (Count : Positive) is record + This : Positive := 1; + Left : access Amb; + List : Alternatives (1..Count); + end record; + + function "/" (L, R : String) return Amb; + function "/" (L : Amb; R : String) return Amb; + function "=" (L, R : Amb) return Boolean; + function Image (L : Amb) return String; + procedure Join (L : access Amb; R : in out Amb); + procedure Failure (L : in out Amb); + + function Image (L : Amb) return String is + begin + return To_String (L.List (L.This)); + end Image; + + function "/" (L, R : String) return Amb is + Result : Amb (2); + begin + Append (Result.List (1), L); + Append (Result.List (2), R); + return Result; + end "/"; + + function "/" (L : Amb; R : String) return Amb is + Result : Amb (L.Count + 1); + begin + Result.List (1..L.Count) := L.List ; + Append (Result.List (Result.Count), R); + return Result; + end "/"; + + function "=" (L, R : Amb) return Boolean is + Left : Unbounded_String renames L.List (L.This); + begin + return Element (Left, Length (Left)) = Element (R.List (R.This), 1); + end "="; + + procedure Failure (L : in out Amb) is + begin + loop + if L.This < L.Count then + L.This := L.This + 1; + else + L.This := 1; + Failure (L.Left.all); + end if; + exit when L.Left = null or else L.Left.all = L; + end loop; + end Failure; + + procedure Join (L : access Amb; R : in out Amb) is + begin + R.Left := L; + while L.all /= R loop + Failure (R); + end loop; + end Join; + + W_1 : aliased Amb := "the" / "that" / "a"; + W_2 : aliased Amb := "frog" / "elephant" / "thing"; + W_3 : aliased Amb := "walked" / "treaded" / "grows"; + W_4 : aliased Amb := "slowly" / "quickly"; +begin + Join (W_1'Access, W_2); + Join (W_2'Access, W_3); + Join (W_3'Access, W_4); + Put_Line (Image (W_1) & ' ' & Image (W_2) & ' ' & Image (W_3) & ' ' & Image (W_4)); +end Test_Amb; diff --git a/Task/Amicable-pairs/PL-I-80/amicable-pairs-1.pli b/Task/Amicable-pairs/PL-I-80/amicable-pairs-1.pli deleted file mode 100644 index 0ce9c61830..0000000000 --- a/Task/Amicable-pairs/PL-I-80/amicable-pairs-1.pli +++ /dev/null @@ -1,47 +0,0 @@ -amicable: procedure options (main); - - %replace - search_limit by 20000; - - dcl (a, b, found) fixed bin; - - put skip list ('Searching for amicable pairs up to '); - put edit (search_limit) (f(5)); - found = 0; - do a = 2 to search_limit; - b = sumf(a); - if (b > a) then - do; - if (sumf(b) = a) then - do; - found = found + 1; - put skip edit (a,b) (f(7)); - end; - end; - end; - put skip list (found, ' pairs were found'); - stop; - - -/* return sum of the proper divisors of n */ -sumf: - procedure(n) returns (fixed bin); - - dcl (n, sum, f1, f2) fixed bin; - - sum = 1; /* 1 is a proper divisor of every number */ - f1 = 2; - do while ((f1 * f1) < n); - if mod(n, f1) = 0 then - do; - sum = sum + f1; - f2 = n / f1; - /* don't double count identical co-factors! */ - if f2 > f1 then sum = sum + f2; - end; - f1 = f1 + 1; - end; - return (sum); -end sumf; - -end amicable; diff --git a/Task/Amicable-pairs/PL-I-80/amicable-pairs-2.pli b/Task/Amicable-pairs/PL-I-80/amicable-pairs.pli similarity index 89% rename from Task/Amicable-pairs/PL-I-80/amicable-pairs-2.pli rename to Task/Amicable-pairs/PL-I-80/amicable-pairs.pli index c8263a3816..49d0c5315a 100644 --- a/Task/Amicable-pairs/PL-I-80/amicable-pairs-2.pli +++ b/Task/Amicable-pairs/PL-I-80/amicable-pairs.pli @@ -3,7 +3,7 @@ amicable: procedure options (main); %replace search_limit by 20000; - dcl sumf( 1 : search_limit ) fixed bin; + dcl sumf(1 : search_limit) fixed bin; dcl (a, b, found) fixed bin; put skip list ('Searching for amicable pairs up to '); @@ -12,7 +12,7 @@ amicable: procedure options (main); do a = 1 to search_limit; sumf( a ) = 1; end; do a = 2 to search_limit; do b = a + a to search_limit by a; - sumf( b ) = sumf( b ) + a; + sumf(b) = sumf(b) + a; end; end; diff --git a/Task/Anagrams/DuckDB/anagrams.duckdb b/Task/Anagrams/DuckDB/anagrams.duckdb new file mode 100644 index 0000000000..aaa0f5aad8 --- /dev/null +++ b/Task/Anagrams/DuckDB/anagrams.duckdb @@ -0,0 +1,20 @@ +# The MAP giving the frequency counts of characters in the given string +create or replace function spectrum(str) as ( + select histogram(c) + from (select unnest(regexp_extract_all(str,'.')) as c) +); + +# Find the anagram groups having the most members. +# Each group is sorted, and the groups are sorted by first word in the group. +with words as (from read_csv('unixdict.txt', header=false) _(word)), + histograms as (select word, spectrum(word) as h from words), + groups as (select h, count(h) as c from histograms group by h order by c desc), + mx as (select max(c) as mx from groups), + maximals as (select h from groups, mx where c = mx.mx), + results as (select (select array_agg(word).list_sort() + from histograms + where histograms.h = maximals.h ) as anagrams + from maximals) + select anagrams + from results + order by anagrams[1] ; diff --git a/Task/Anagrams/TAV/anagrams.tav b/Task/Anagrams/TAV/anagrams.tav new file mode 100644 index 0000000000..6b940f7f6e --- /dev/null +++ b/Task/Anagrams/TAV/anagrams.tav @@ -0,0 +1,38 @@ +\( Find anagrams (words with the same set of letters) + Words are the lines of an input file. + Sorting the letters of the word gives the key for a map + having a list (row) of all words so far. +\) +\+ stdlib +main(parms):+ + parms[1] =~ 'unixdict.txt' \ default input file + wordmap =: get words from parms[1] + maxw =: wordmap.maxlen + ?# idx =: map wordmap give keys ascending + words =: wordmap{idx} + ? maxw = words.count + print words::join values by ', ' + +\ read the file (infn) and return a map +get words from (infn): + res =: new map \ create the result map + res.maxlen =: 0 + ?# line =: file infn give lines \ or: infn::give lines + add line to res + :> res + +\ add a word to the map +add (word) to (amap): + idx =: sort characters of word::case to upper + row =: amap{idx} \ get indexed words + ? row = () \ new entry if void + row =: new row + amap{idx} =: row + row[] =: word \ add new entry + amap.maxlen =: maximum of amap.maxlen, row.count + +\ Sort the characters of a string +sort characters of (s): + sr =: string s as character row + row sr sort ascending + :> row sr join values as string \ without separator diff --git a/Task/Angles-geometric-normalization-and-conversion/R/angles-geometric-normalization-and-conversion.r b/Task/Angles-geometric-normalization-and-conversion/R/angles-geometric-normalization-and-conversion.r new file mode 100644 index 0000000000..b5d7f17fa3 --- /dev/null +++ b/Task/Angles-geometric-normalization-and-conversion/R/angles-geometric-normalization-and-conversion.r @@ -0,0 +1,23 @@ +test_angles <- c(-2,-1,0,1,2,6.2831853,16,57.2957795,359,399,6399,1000000) + +d2d <- function(a) sign(a)*(abs(a)%%360) +g2g <- function(a) sign(a)*(abs(a)%%400) +m2m <- function(a) sign(a)*(abs(a)%%6400) +r2r <- function(a) sign(a)*(abs(a)%%(2*pi)) + +normalised <- as.data.frame(sapply(c(d2d,g2g,m2m,r2r), function(f) f(test_angles))) +unitnames <- c("deg","grad","mil","rad") +colnames(normalised) <- sapply(unitnames, function(s) paste0(s, "_norm")) + +d2x <- function(a, unit) switch(unit, "grad"=a*10/9, "mil"=a*160/9, "rad"=a*pi/180) +g2x <- function(a, unit) switch(unit, "deg"=a*9/10, "mil"=a*16, "rad"=a*pi/200) +m2x <- function(a, unit) switch(unit, "deg"=a*9/160, "grad"=a/16, "rad"=a*pi/3200) +r2x <- function(a, unit) switch(unit, "deg"=a*180/pi, "grad"=a*200/pi, "mil"=a*3200/pi) + +deg_conv <- sapply(unitnames[-1], function(unit) d2x(d2d(test_angles), unit)) +grad_conv <- sapply(unitnames[-2], function(unit) g2x(g2g(test_angles), unit)) +mil_conv <- sapply(unitnames[-3], function(unit) m2x(m2m(test_angles), unit)) +rad_conv <- sapply(unitnames[-4], function(unit) r2x(r2r(test_angles), unit)) + +conv_list <- list(deg_conv, grad_conv, mil_conv, rad_conv) +setNames(lapply(1:4, function(n) cbind(test_angles, normalised[n], conv_list[[n]])), unitnames) diff --git a/Task/Anonymous-recursion/DuckDB/anonymous-recursion.duckdb b/Task/Anonymous-recursion/DuckDB/anonymous-recursion.duckdb new file mode 100644 index 0000000000..3127c641c3 --- /dev/null +++ b/Task/Anonymous-recursion/DuckDB/anonymous-recursion.duckdb @@ -0,0 +1,11 @@ +create or replace function fib(n) as ( + if ( n < 0, error('negative arguments not allowed'), + (with recursive fib(i,e,f) as ( + select 1, 1, 1 + union all + select i+1, e+f, e from fib + where i <= n) + select last(f order by i) + from fib) + ) +); diff --git a/Task/Anti-primes/Bc/anti-primes.bc b/Task/Anti-primes/Bc/anti-primes.bc new file mode 100644 index 0000000000..d282deaa5d --- /dev/null +++ b/Task/Anti-primes/Bc/anti-primes.bc @@ -0,0 +1,18 @@ +define factors(n) { + auto c + for(i=1;i<=n;i++) { + if(n%i==0) c+=1 + } + return c +} + +max = 0 +n = 1 +for(c=20; c > 0;) { + if(factors(n) > max) { + print n," " + max = factors(n) + c -= 1 + } + n += 1 +} diff --git a/Task/Anti-primes/Draco/anti-primes.draco b/Task/Anti-primes/Draco/anti-primes.draco new file mode 100644 index 0000000000..8b2db07dee --- /dev/null +++ b/Task/Anti-primes/Draco/anti-primes.draco @@ -0,0 +1,29 @@ +proc factors(word n) word: + word count, fac; + count := 1; + for fac from 1 upto n/2 do + if n % fac = 0 then + count := count + 1 + fi + od; + count +corp + +proc antiprimes(word amount) void: + word maxf, n, f; + maxf := 0; + n := 1; + while amount > 0 do + f := factors(n); + if f > maxf then + write(n, " "); + maxf := f; + amount := amount - 1 + fi; + n := n + 1 + od +corp + +proc main() void: + antiprimes(20) +corp diff --git a/Task/Anti-primes/Lua/anti-primes-2.lua b/Task/Anti-primes/Lua/anti-primes-2.lua index a849a48fa0..a3ca9023e3 100644 --- a/Task/Anti-primes/Lua/anti-primes-2.lua +++ b/Task/Anti-primes/Lua/anti-primes-2.lua @@ -26,4 +26,4 @@ function antiprimes(goal) end -- display the antiprimes -oo.write( table.concat( antiprimes( 20 ), " " ) ) +io.write( table.concat( antiprimes( 20 ), " " ) ) diff --git a/Task/Anti-primes/Pluto/anti-primes.pluto b/Task/Anti-primes/Pluto/anti-primes.pluto new file mode 100644 index 0000000000..3b7ee59a36 --- /dev/null +++ b/Task/Anti-primes/Pluto/anti-primes.pluto @@ -0,0 +1,32 @@ +do -- Find the first 20 antiprimes. + + local fmt = require( "fmt" ) + + -- 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 ] end + end + end + local factors = ndc[ number ] + if factors > mostFactors then + table.insert( list, number ) + mostFactors = factors + end + ++ number + end + return list + end + + -- display the antiprimes + fmt.lprint( antiprimes( 20 ), " ", "" ) +end diff --git a/Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark b/Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark new file mode 100644 index 0000000000..a264075a30 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/ArkScript/apply-a-callback-to-an-array.ark @@ -0,0 +1,8 @@ +(import std.List :map) + +(let array [1 2 3 4 5 6 7 8 9 10]) +(let mapped (map array (fun (i) (* i i)))) + +(assert + (= mapped [1 4 9 16 25 36 49 64 81 100]) + "mapped is a list of squares") diff --git a/Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.haxe b/Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.haxe new file mode 100644 index 0000000000..da0f9b93f7 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.haxe @@ -0,0 +1,10 @@ +class Main { + static function main() { + var numbers = [1, 2, 3, 4, 5]; + + var squared = (i) -> i * i; + + trace(numbers); + trace(numbers.map(squared)); + } +} diff --git a/Task/Approximate-equality/Pluto/approximate-equality.pluto b/Task/Approximate-equality/Pluto/approximate-equality.pluto new file mode 100644 index 0000000000..a40474d82c --- /dev/null +++ b/Task/Approximate-equality/Pluto/approximate-equality.pluto @@ -0,0 +1,16 @@ +local tol = 1e-16 +local sqrt2 = math.sqrt(2.0) +local pairs = { + {100000000000000.01, 100000000000000.011}, + {100.01, 100.011}, + {10000000000000.001 / 10000.0, 1000000000.0000001000}, + {0.001, 0.0010000001}, + {0.000000000000000000000101, 0.0}, + {sqrt2 * sqrt2, 2.0}, + {-sqrt2 * sqrt2, -2.0}, + {3.14159265358979323846, 3.14159265358979324} +} +print($"Approximate equality of test cases for a tolerance of {tol}:") +for i, pair in pairs do + print($" {i} -> {math.abs(pair[1] - pair[2]) < tol}") +end diff --git a/Task/Arbitrary-precision-integers-included-/Agena/arbitrary-precision-integers-included-.agena b/Task/Arbitrary-precision-integers-included-/Agena/arbitrary-precision-integers-included-.agena new file mode 100644 index 0000000000..f0b25b2245 --- /dev/null +++ b/Task/Arbitrary-precision-integers-included-/Agena/arbitrary-precision-integers-included-.agena @@ -0,0 +1,25 @@ +scope # calculate 5^4^3^2 using Mike's Arbitrary Precision Math library + import mapm; # explicit import needed for: Linux, Mac OS X, Windows and Solaris + + # returns a string containing 5^4^3^2 as calculated by mapm + local constant calc5up4up3up2 := proc() is + return mapm.xtostring( mapm.xround( mapm.xnumber( 5 ) ^ mapm.xnumber( 4 ^ ( 3 ^ 2 ) ) ) ) + end; + + # do the calculation with default precision + local p := calc5up4up3up2(); + + # find the number of digits before the point + local d := size( p ); + local point := "." in p; + if point <> null then d := point - 1 fi; + + # redo the calculation with the actual number of required digits ( plus a bit extra ) + mapm.xdigits( d + 30 ); + p := calc5up4up3up2(); + d := size( p ); + point := "." in p; + if point <> null then d := point - 1 fi; + + io.write( "5^4^3^2 has ", d, " digits: ", p[ 1 to 20 ], "...", p[ d - 19 to d ], "\n" ) +end diff --git a/Task/Arbitrary-precision-integers-included-/BBC-BASIC/arbitrary-precision-integers-included-.basic b/Task/Arbitrary-precision-integers-included-/BBC-BASIC/arbitrary-precision-integers-included-.basic new file mode 100644 index 0000000000..9b470db7e7 --- /dev/null +++ b/Task/Arbitrary-precision-integers-included-/BBC-BASIC/arbitrary-precision-integers-included-.basic @@ -0,0 +1,11 @@ + 10 INSTALL @lib$ + "bigint" + 20 t1 = TIME + 30 x = FNbignew(200000) + 40 PROCbigval(x, "5") + 50 PROCbigpow(x, x, 4^(3^2)) + 60 x$ = FNbigstr(x) + 70 t2 = TIME + 80 PRINT "First twenty digits: " LEFT$(x$, 20) + 90 PRINT " Last twenty digits: " RIGHT$(x$, 20) + 100 PRINT "Total number of digits: "; LEN(x$) + 110 PRINT "Approximate run time: "; (t2 - t1) / 100 " seconds" diff --git a/Task/Arbitrary-precision-integers-included-/Bracmat/arbitrary-precision-integers-included-.bracmat b/Task/Arbitrary-precision-integers-included-/Bracmat/arbitrary-precision-integers-included-.bracmat index 0cf1eaa821..8b4ca42a92 100644 --- a/Task/Arbitrary-precision-integers-included-/Bracmat/arbitrary-precision-integers-included-.bracmat +++ b/Task/Arbitrary-precision-integers-included-/Bracmat/arbitrary-precision-integers-included-.bracmat @@ -1,4 +1,4 @@ {?} @(5^4^3^2:?first [20 ? [-21 ?last [?length)&str$(!first "..." !last "\nlength " !length) {!} 62060698786608744707...92256259918212890625 length 183231 - S 2,46 sec + S 0,11 sec (4372.4475) diff --git a/Task/Arbitrary-precision-integers-included-/Nim/arbitrary-precision-integers-included-.nim b/Task/Arbitrary-precision-integers-included-/Nim/arbitrary-precision-integers-included-.nim index 73c032ed08..e7e928169e 100644 --- a/Task/Arbitrary-precision-integers-included-/Nim/arbitrary-precision-integers-included-.nim +++ b/Task/Arbitrary-precision-integers-included-/Nim/arbitrary-precision-integers-included-.nim @@ -1,6 +1,8 @@ +# Solution for https://rosettacode.org/wiki/Arbitrary-precision_integers_(included) import bigints +import std/math -var x = 5.pow 4.pow 3.pow 2 +var x = 5.initBigInt.pow 4 ^ (3 ^ 2) var s = $x echo s[0..19] diff --git a/Task/Arbitrary-precision-integers-included-/Pluto/arbitrary-precision-integers-included-.pluto b/Task/Arbitrary-precision-integers-included-/Pluto/arbitrary-precision-integers-included-.pluto new file mode 100644 index 0000000000..4a5147f062 --- /dev/null +++ b/Task/Arbitrary-precision-integers-included-/Pluto/arbitrary-precision-integers-included-.pluto @@ -0,0 +1,10 @@ +local bigint = require "bigint" +local fmt = require "fmt" +local p = bigint.new(3) ^ bigint.new(2) +p = bigint.new(4) ^ p +p = bigint.new(5) ^ p + +local s = p:tostring() +fmt.print("5 ^ 4 ^ 3 ^ 2 has %s digits.\n", fmt.int(#s)) +print("The first twenty and last twenty are: ") +print(fmt.abridge(s, 20)) diff --git a/Task/Arbitrary-precision-integers-included-/Rhombus/arbitrary-precision-integers-included-.rhombus b/Task/Arbitrary-precision-integers-included-/Rhombus/arbitrary-precision-integers-included-.rhombus new file mode 100644 index 0000000000..f8e88ba5fa --- /dev/null +++ b/Task/Arbitrary-precision-integers-included-/Rhombus/arbitrary-precision-integers-included-.rhombus @@ -0,0 +1,5 @@ +def bignum : 5**4**3**2 +def num_length : to_string(bignum).length() +num_length +to_string(bignum).substring(..20) +to_string(bignum).substring(num_length-20..num_length) diff --git a/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy b/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy index 4fc2177a04..f286d38628 100644 --- a/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy +++ b/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy @@ -2,11 +2,9 @@ glinewidth 0.4 x0 = 50 y0 = 50 while r < 50 - xp = x - yp = y x = r * cos t + x0 y = r * sin t + y0 - if r > 0 : gline xp yp x y + glineto x y r += 0.05 t += 3 . diff --git a/Task/Arithmetic-Complex/ArkScript/arithmetic-complex.ark b/Task/Arithmetic-Complex/ArkScript/arithmetic-complex.ark new file mode 100644 index 0000000000..96b3a3957f --- /dev/null +++ b/Task/Arithmetic-Complex/ArkScript/arithmetic-complex.ark @@ -0,0 +1,30 @@ +(import std.Math) + +(let a (math:complex 1 1)) +(let b (math:complex 3.75 1.25)) + +(assert + (= + (math:complex-add a b) + (math:complex 4.75 2.25)) + "complex add") +(assert + (= + (math:complex-mul a b) + (math:complex 2.5 5)) + "complex mul") +(assert + (= + (math:complex-mul (math:complex -1 0) a) + (math:complex -1 -1)) + "complex negation") +(assert + (= + (math:complex-div (math:complex 1 0) a) + (math:complex 0.5 -0.5)) + "complex inversion") +(assert + (= + (math:complex-conjugate a) + (math:complex 1 -1)) + "complex conjugate") diff --git a/Task/Arithmetic-Complex/DuckDB/arithmetic-complex.duckdb b/Task/Arithmetic-Complex/DuckDB/arithmetic-complex.duckdb new file mode 100644 index 0000000000..6f63ed0faa --- /dev/null +++ b/Task/Arithmetic-Complex/DuckDB/arithmetic-complex.duckdb @@ -0,0 +1,86 @@ +CREATE TYPE COMPLEX AS STRUCT(r REAL, i REAL); + +CREATE OR REPLACE FUNCTION isreal(a) AS ( + if (try_cast(a as REAL), true, false) +); + +CREATE OR REPLACE FUNCTION tocomplex(a) AS ( + coalesce( try_cast(a as COMPLEX), {r: a, i:0.0 }::COMPLEX ) +); + +CREATE OR REPLACE FUNCTION complex_add_(a, b) AS ( + {r: a.r + b.r, i:a.i + b.i} +); + +CREATE OR REPLACE FUNCTION complex_add(a, b) AS ( + complex_add_(tocomplex(a), tocomplex(b)) +); + +CREATE OR REPLACE FUNCTION complex_mul_(a, b) AS ( + {r: a.r * b.r - a.i * b.i, i:a.r * b.i + a.i * b.r} +); + +CREATE OR REPLACE FUNCTION complex_mul(a, b) AS ( + complex_mul_(tocomplex(a), tocomplex(b)) +); + +CREATE OR REPLACE FUNCTION complex_mag(a) AS ( + case when isreal(a) + then abs(a::REAL) + else sqrt( (a::COMPLEX).r ^ 2 + (a::COMPLEX).i ^2) + end +); + +CREATE OR REPLACE FUNCTION complex_conj(a) AS ( + case when isreal(a) + then {r: a::REAL, i: 0.0} + else {r: (a::COMPLEX).r, i: - (a::COMPLEX).i} + end +); + +CREATE OR REPLACE FUNCTION complex_mag_squared(x) AS ( + case when isreal(x) + then x::REAL*x::REAL + else (x::COMPLEX).r ^ 2 + (x::COMPLEX).i ^ 2 + end +); + +# Oddly, the a.r notation cannot currently be used here +CREATE OR REPLACE FUNCTION complex_div_(a, b) AS ( + WITH denom AS (select complex_mag_squared(b) as denom, + a['r'] as ar, a['i'] as ai, b['r'] as br, b['i'] as bi + ) + SELECT {r: (ar * br + ai * bi) / denom, + i: (ai * br - ar * bi) / denom } + FROM denom +); + +CREATE OR REPLACE FUNCTION complex_div(a, b) AS ( + complex_div_(tocomplex(a), tocomplex(b)) +); + +CREATE OR REPLACE FUNCTION complex_exp_(z) AS ( + complex_mul_( {r: exp(z.r), i: 0.0}, {r: cos(z.i), i:sin(z.i) }) +); + +CREATE OR REPLACE FUNCTION complex_exp(z) AS ( + if( isreal(z), + {r:exp(z::REAL), i:0.0}, + complex_exp_( tocomplex(z) ) ) +); + +## Examples +.mode line +CREATE OR REPLACE FUNCTION test(x,y) as table ( + select x as "x", + y as "y", + complex_add(x,y) as "add", + complex_mul(x,y) as "mul", + complex_div(1, x) as "1/x", + complex_conj(x) as "conj(x)", + complex_div(x,y).complex_mul(y) as "(x/y)*y" +); + +from test({r:1,i:1}, {r:0,i:1} ); + +select complex_exp( {r:0, i:pi()} ) as "e^iπ"; diff --git a/Task/Arithmetic-Complex/FutureBasic/arithmetic-complex.basic b/Task/Arithmetic-Complex/FutureBasic/arithmetic-complex.basic new file mode 100644 index 0000000000..e54a45e971 --- /dev/null +++ b/Task/Arithmetic-Complex/FutureBasic/arithmetic-complex.basic @@ -0,0 +1,71 @@ +// +// Arithmetic/Complex +// Using FutureBasic 7.0.34 +// August 2025, R.W + +include "Tlbx complex.incl" +// through this include file, FB supports the following +// double complex functions (as of August 2025). +// Float and long double complex might be +// available in later versions + +//fn creal, cimag, cabs, carg, conj, cproj +//fn csqrt, cexp, clog, cpow +//fn csin, ccos, ctan +//fn casin, cacos, catan +//fn csinh, ccosh, ctanh +//fn casinh,cacosh,catanh + +// Below is redefining "I" to Cj since I don't want to lose the +// ability to use "i" as my favorite FOR NEXT / loop variable +BeginCDeclaration +#define Cj I +EndC +system double Cj + +local fn PrintComplexNumber( z as double_complex ) + double y + print @fn creal( z ) " "; + y = fn cimag( z ) + if ( y >= 0.0 ) then print @"+"; : else print @"-"; + print @abs( y ) "i" +end fn + +window 1,@"Arithmetic/Complex" + +double_complex z1, z2, z3, z4, z5, z6 +double_complex z7, z8, z9, zs, zn + +z1 = 1.5 + 3 * Cj //1.5 + 3i +z2 = 1.5 + 1.5 * Cj //1.5 + 1.5i + +// Operations using C99 operators +z3 = z1 + z2 // addition +z4 = z1 - z2 // subtraction +z5 = z1 * z2 // multiplication +z6 = z1 / z2 // division +//---------------- +z7 = fn conj(z1) // conjugate +z8 = fn cpow(z1,z2) // power ^ +z9 = fn cabs(z1) // norm | magnitude +zs = fn csqrt(z1) // square root +zn = -(z1) // negate + +// Extract real/imag parts using creal/cimag +print @ +print @" z1 + z2 = "; fn creal(z3); " + "; fn cimag(z3); "i" +print @" z1 - z2 = "; fn creal(z4); " + "; fn cimag(z4); "i" +print @" z1 * z2 = "; fn creal(z5); " + "; fn cimag(z5); "i" +print @" z1 / z2 = "; fn creal(z6); " + "; fn cimag(z6); "i" +print @" Conj z1 = "; fn creal(z7); " "; fn cimag(z7); "i" +print @" Abs z1 = "; fn creal(z9) +print @" z1 ^ z2 = "; +fn PrintComplexNumber(z8) +print @" cSqrt z1= "; +fn PrintComplexNumber(zs) +print @" -(z1) = "; +fn PrintComplexNumber(zn) +print @" z1 real = "; fn creal(z1) +print @" z1 imag = "; fn cimag(z1) + +HandleEvents diff --git a/Task/Arithmetic-Complex/Pluto/arithmetic-complex.pluto b/Task/Arithmetic-Complex/Pluto/arithmetic-complex.pluto new file mode 100644 index 0000000000..f2f68b630f --- /dev/null +++ b/Task/Arithmetic-Complex/Pluto/arithmetic-complex.pluto @@ -0,0 +1,15 @@ +require "complex" +local fmt = require "fmt" + +local x = new complex(1, 3) +local y = new complex(5, 2) + +fmt.print("x = %s", x) +fmt.print("y = %s", y) +fmt.print("x + y = %s", x + y) +fmt.print("x - y = %s", x - y) +fmt.print("x * y = %s", x * y) +fmt.print("x / y = %s", x / y) +fmt.print("-x = %s", -x) +fmt.print("1 / x = %s", x:inverse()) +fmt.print("x* = %s", x:conj()) diff --git a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx index 7c72a01f37..e174652042 100644 --- a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx +++ b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx @@ -1,4 +1,4 @@ --- 19 May 2025 +-- 7 Aug 2025 include Settings say 'COMPLEX ARITHMETIC' @@ -6,48 +6,45 @@ say version say a = '1 2'; b = '3 4'; c = '5 6'; d = '7 8'; i = I() say 'VALUES' -say 'a =' crec2form(a) -say 'b =' crec2form(b) -say 'c =' crec2form(c) -say 'd =' crec2form(d) +say 'a =' Rec2FormC(a) +say 'b =' Rec2FormC(b) +say 'c =' Rec2FormC(c) +say 'd =' Rec2FormC(d) say say 'BASICS' -say 'i*i =' crec2form(Csquare(i())) -say 'a+b =' crec2form(Cadd(a,b)) -say 'a-b =' crec2form(Csub(a,b)) -say 'a*b =' crec2form(Cmul(a,b)) -say 'a/b =' crec2form(Cdiv(a,b)) -say 'a^2 =' crec2form(Csquare(a,2)) -say 'a^5 =' crec2form(Cpow(a,5)) -say '-a =' crec2form(Cneg(a)) -say '1/a =' crec2form(Cinv(a)) -say 'a+b+c+d =' crec2form(Cadd(a,b,c,d)) -say 'a-b-c-d =' crec2form(Csub(a,b,c,d)) -say 'a*b*c*d =' crec2form(Cmul(a,b,c,d)) -say 'a/b/c/d =' crec2form(Cnormal(Cdiv(a,b,c,d))) +say 'i*i =' Rec2FormC(SquareC(i())) +say 'a+b =' Rec2FormC(AddC(a,b)) +say 'a-b =' Rec2FormC(SubC(a,b)) +say 'a*b =' Rec2FormC(MulC(a,b)) +say 'a/b =' Rec2FormC(DivC(a,b)) +say 'a^2 =' Rec2FormC(SquareC(a,2)) +say 'a^5 =' Rec2FormC(PowC(a,5)) +say '-a =' Rec2FormC(NegC(a)) +say '1/a =' Rec2FormC(InvC(a)) +say 'a+b+c+d =' Rec2FormC(AddC(a,b,c,d)) +say 'a-b-c-d =' Rec2FormC(SubC(a,b,c,d)) +say 'a*b*c*d =' Rec2FormC(MulC(a,b,c,d)) +say 'a/b/c/d =' Rec2FormC(Normal(DivC(a,b,c,d))) say say 'FORMULA' say 'a^2-2ab+3c-4ad^4+5 =' , -crec2form(Cadd(Csquare(a),Cmul(-2,a,b),Cmul(3,c),Cmul(-4,a,Cpower(d,4)),5)) +Rec2FormC(AddC(SquareC(a),MulC(-2,a,b),MulC(3,c),MulC(-4,a,PowerC(d,4)),5)) say say 'BONUS' -say 'Argument(a) =' Carg(a)+0 -say 'Conjugate(a) =' crec2form(Cconj(a)) -say 'Imag(a) =' Cim(a) -say 'Modulus(a) =' Cmod(a)+0 -say 'Polar(a) =' Cpol2form(Cnormal(Crec2pol(a))) -say 'Real(a) =' Cre(a) +say 'Argument(a) =' ArgC(a)+0 +say 'Conjugate(a) =' Rec2FormC(ConjC(a)) +say 'Imag(a) =' ImC(a) +say 'Modulus(a) =' ModC(a)+0 +say 'Polar(a) =' Pol2FormC(Normal(Rec2PolC(a))) +say 'Real(a) =' ReC(a) say say 'MORE' -say 'Arcsin(a) =' crec2form(Cnormal(Carcsin(a))) -say 'Exp(a) =' crec2form(Cnormal(Cexp(a))) -say 'Ln(a) =' crec2form(Cnormal(Cln(a))) -say 'Sin(a) =' crec2form(Cnormal(Csin(a))) -say 'Sqrt(a) =' crec2form(Cnormal(Csqrt(a))) -say 'i^i =' crec2form(Cnormal(Cpower(i,i))) +say 'Arcsin(a) =' Rec2FormC(Normal(ArcSinC(a))) +say 'Exp(a) =' Rec2FormC(Normal(ExpC(a))) +say 'Ln(a) =' Rec2FormC(Normal(LnC(a))) +say 'Sin(a) =' Rec2FormC(Normal(SinC(a))) +say 'Sqrt(a) =' Rec2FormC(Normal(SqRtC(a))) +say 'i^i =' Rec2FormC(Normal(PowerC(i,i))) exit -include Complex -include Functions -include Constants -include Abend +include Math diff --git a/Task/Arithmetic-Integer/ArkScript/arithmetic-integer.ark b/Task/Arithmetic-Integer/ArkScript/arithmetic-integer.ark new file mode 100644 index 0000000000..1fa6546301 --- /dev/null +++ b/Task/Arithmetic-Integer/ArkScript/arithmetic-integer.ark @@ -0,0 +1,10 @@ +(let a 4) +(let b 5) + +(assert (= (+ a b) 9) "sum") +(assert (= (- a b) -1) "difference") +(assert (= (- b a) 1) "difference") +(assert (= (* a b) 20) "product") +(assert (= (/ a b) 0.8) "quotient") +(assert (= (mod a b) 4) "remainder(a, b)") +(assert (= (mod b a) 1) "remainder(b, a)") diff --git a/Task/Arithmetic-Integer/DuckDB/arithmetic-integer.duckdb b/Task/Arithmetic-Integer/DuckDB/arithmetic-integer.duckdb new file mode 100644 index 0000000000..bdde026f71 --- /dev/null +++ b/Task/Arithmetic-Integer/DuckDB/arithmetic-integer.duckdb @@ -0,0 +1,3 @@ +SELECT x, y, (x+y), (x-y), (x*y), x // y, mod(x,y), exp(x) + FROM read_csv_auto('rc-arithmetic-integer.txt', header=false, + columns={'x': 'HUGEINT', 'y': 'HUGEINT'}) ; diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index d0e5d67143..71357b0182 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -3,13 +3,13 @@ import extensions; public program() { - var a := console.loadLineTo(new Integer()); - var b := console.loadLineTo(new Integer()); + var a := Console.loadLineTo(new Integer()); + var b := Console.loadLineTo(new Integer()); - console.printLine(a," + ",b," = ",a + b); - console.printLine(a," - ",b," = ",a - b); - console.printLine(a," * ",b," = ",a * b); - console.printLine(a," / ",b," = ",a / b); // truncates towards 0 - console.printLine(a," % ",b," = ",a.mod(b)); // matches sign of first operand - console.printLine(a," ^ ",b," = ",a ^ b); + Console.printLine(a," + ",b," = ",a + b); + Console.printLine(a," - ",b," = ",a - b); + Console.printLine(a," * ",b," = ",a * b); + Console.printLine(a," / ",b," = ",a / b); // truncates towards 0 + Console.printLine(a," % ",b," = ",a.mod(b)); // matches sign of first operand + Console.printLine(a," ^ ",b," = ",a ^ b); } diff --git a/Task/Arithmetic-Integer/Haxe/arithmetic-integer.haxe b/Task/Arithmetic-Integer/Haxe/arithmetic-integer.haxe index d18971aa92..513ff1c6ea 100644 --- a/Task/Arithmetic-Integer/Haxe/arithmetic-integer.haxe +++ b/Task/Arithmetic-Integer/Haxe/arithmetic-integer.haxe @@ -1,13 +1,16 @@ -class BasicIntegerArithmetic { - public static function main() { - var args =Sys.args(); - if (args.length < 2) return; - var a = Std.parseFloat(args[0]); - var b = Std.parseFloat(args[1]); - trace("a+b = " + (a+b)); - trace("a-b = " + (a-b)); - trace("a*b = " + (a*b)); - trace("a/b = " + (a/b)); - trace("a%b = " + (a%b)); +class Main { + static public function main():Void { + var input_a = Sys.stdin().readLine(); + var input_b = Sys.stdin().readLine(); + + var a = Std.parseInt(input_a); + var b = Std.parseInt(input_b); + + trace(a + b); + trace(a - b); + trace(a * b); + trace(Std.int(a / b)); + trace(a % b); + trace(Math.pow(a, b)); } } diff --git a/Task/Arithmetic-Integer/Pascal/arithmetic-integer.pas b/Task/Arithmetic-Integer/Pascal/arithmetic-integer.pas index 0f5806a811..28040742b4 100644 --- a/Task/Arithmetic-Integer/Pascal/arithmetic-integer.pas +++ b/Task/Arithmetic-Integer/Pascal/arithmetic-integer.pas @@ -1,5 +1,7 @@ program arithmetic(input, output) - +{$IFDEF FPC} + uses math; +{$ENDIF} var a, b: integer; diff --git a/Task/Arithmetic-Integer/Pluto/arithmetic-integer.pluto b/Task/Arithmetic-Integer/Pluto/arithmetic-integer.pluto new file mode 100644 index 0000000000..5e35d1e3bc --- /dev/null +++ b/Task/Arithmetic-Integer/Pluto/arithmetic-integer.pluto @@ -0,0 +1,13 @@ +local function divmod(a, b) return { a // b, a % b } end + +io.write("Input the first integer : ") +local a = io.read("n") +io.write("Input the second integer: ") +local b = io.read("n") +print($"sum: {a + b}") +print($"difference {a - b}") +print($"product {a * b}") +print($"quotient {a // b}") +print($"remainder {a % b}") +print($"exponentation {math.tointeger(a ^ b)}") +print($"divmod {divmod(a, b):concat(", ")}") diff --git a/Task/Arithmetic-Integer/RISC-V-Assembly/arithmetic-integer.asm b/Task/Arithmetic-Integer/RISC-V-Assembly/arithmetic-integer.asm new file mode 100644 index 0000000000..a65eff3a1e --- /dev/null +++ b/Task/Arithmetic-Integer/RISC-V-Assembly/arithmetic-integer.asm @@ -0,0 +1,146 @@ +# riscv assembly raspberry pico2 rp2350 +# program arith.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szCariageReturn: .asciz "\r\n" +szMessAdd: .asciz "Addition result :\r\n" +szMessSub: .asciz "Substraction result :\r\n" +szMessMul: .asciz "Multiplication result :\r\n" +szMessDiv: .asciz "Division result :\r\n" +szMessRem: .asciz "Division remainder :\r\n" +.align 2 +#tabValues: .int 1,2,3,4 + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szMessAdd # addition + call writeString # display message + li t0,10 + addi a0,t0,1 # add immediat number + call displayResult + li s0,15 + li s1,8 + add a0,s0,s1 # register add + call displayResult + + la a0,szMessSub # subtraction + call writeString # display message + addi a0,s0,-6 # substract immediat number + call displayResult + sub a0,s0,s1 # substract register s1 to s0 + call displayResult + + la a0,szMessMul # multiplication + call writeString # display message + mul a0,s0,s1 # multiplication register + call displayResult + li s0,12345678 + li s1,23456789 + mul a0,s0,s1 # multiplication register + call displayResult + mulh a0,s0,s1 # Multiply signed (32) by signed (32), return upper 32 bits of the 64-bit result. + call displayResult + mulhsu a0,s0,s1 # Multiply signed (32) by unsigned (32), return upper 32 bits of the 64-bit result. + call displayResult + mulhu a0,s0,s1 # Multiply unsigned (32) by unsigned (32), return upper 32 bits of the 64-bit result. + call displayResult + + la a0,szMessDiv # division + call writeString # display message + li s0,-25 + li s1,8 + div a0,s0,s1 # divide signed + call displayResultS + li s0,-25 + li s1,8 + divu a0,s0,s1 # Divide (unsigned) + call displayResult + + la a0,szMessRem # division + call writeString # display message + li s0,-10 + li s1,8 + rem a0,s0,s1 # Remainder (signed). + call displayResultS + li s0,-10 + li s1,8 + remu a0,s0,s1 # Remainder (unsigned). + call displayResult + + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* display result unsigned */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResult: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # conversion decimal + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* displayResult signed */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultS: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10S # conversion decimal + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Arithmetic-Integer/Red/arithmetic-integer.red b/Task/Arithmetic-Integer/Red/arithmetic-integer.red new file mode 100644 index 0000000000..91d6bce211 --- /dev/null +++ b/Task/Arithmetic-Integer/Red/arithmetic-integer.red @@ -0,0 +1,42 @@ +Red [ "Arithmetic / Integers" ] + +;-- Modulo and // in Red are Euclidean modulo, so the correct integer (Euclidean) division must satisfy: +; a = b * div(a,b) + mod(a,b) +; with 0 <= mod(a,b) < |b| +; This is a custom operator to accompany the built-in Euclidean modulo +ediv: make op! function [a b] [ + either b > 0 + [ to-integer round/floor a / b ] ;b > 0: floor toward -inf + [ to-integer round/ceiling a / b ] ;b < 0: ceiling toward +inf +] +; Python-style divmod: +edivmod: make op! function [a b] [ compose [(a ediv b) (a // b)] ] + +;-- C-style truncated integer division: +quot: make op! function [a b] [ to-integer a / b ] ;truncated toward zero +; Haskell-style quotrem: +quotrem: make op! function [a b] [ compose [(a quot b) (a % b)] ]; reduce [a quot b a % b] ] ; rounds -> 0 + +while [(s: ask "^/Enter two integer separated with space (q = quit): ") <> "q"] [ + s: load rejoin ["[" s "]"] a: s/1 b: s/2 + + print ["Sum :" a "+" b " = " a + b] + print ["Difference :" a "-" b " = " a - b] + print ["Product :" a "*" b " = " a * b] + + print "^/Red's Euclidean Division:" + print ["eDiv :" a "eDiv " b " = " a eDiv b] + print ["modulo : modulo" a b " = " modulo a b] ;non-negative + print ["// :" a "//" b " = " a // b] ;operator form + print ["eDivMod :" a "eDivMod" b "= " mold a eDivMod b] + print rejoin ["Check: ("a" eDiv " b") * "b" + ("a" // "b") = "a" ? " (a eDiv b) * b + (a // b) = a] + + print "^/Red's C-style truncated integer division:" + print ["quot :" a "quot" b " = " a quot b] + print ["remainder : remainder" a b " = " remainder a b] ;sign as dividend + print ["% :" a "%" b " = " a % b] ;operator form + print ["quotRem :" a "quotRem" b " = " mold a quotRem b] + print rejoin ["Check: ("a" quot " b") * "b" + ("a" % "b") = "a" ? " (a quot b) * b + (a % b) = a] + + print ["^/Exponentiation :" a "**" b " = " a ** b] +] diff --git a/Task/Arithmetic-Integer/TAV/arithmetic-integer.tav b/Task/Arithmetic-Integer/TAV/arithmetic-integer.tav new file mode 100644 index 0000000000..3077c59f4c --- /dev/null +++ b/Task/Arithmetic-Integer/TAV/arithmetic-integer.tav @@ -0,0 +1,11 @@ + a, b =: 6, 4 + print 'a + b =', a + b + print 'a - b =', a - b + print 'a * b =', a * b + print 'a // b =', a // b \ integer division is %% + print 'a %% b =', a %% b \ usual modulus + print 'a ^ b =', a ^ b + qr =: a // b, a %% b \ operator /% rarely used, not implemented + print 'a /% b =', join qr by ',' + r =: a / b \ rational result + print r, r.num, r.den \ number, numerator, denominator diff --git a/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig b/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig index 564d8cc2b4..17f6f7d217 100644 --- a/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig +++ b/Task/Arithmetic-Integer/Zig/arithmetic-integer.zig @@ -1,23 +1,26 @@ const std = @import("std"); pub fn main() !void { - var buf: [1024]u8 = undefined; - const reader = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); - try stdout.writeAll("Enter two integers separated by a space: "); - const input = try reader.readUntilDelimiter(&buf, '\n'); - const text = std.mem.trimRight(u8, input, "\r\n"); + const stdin = std.io.getStdIn().reader(); + var buff = [_]u8{0} ** 1024; - var it = std.mem.tokenizeScalar(u8, text, ' '); + try stdout.print("Value of a: ", .{}); + const input_a: ?[]u8 = try stdin.readUntilDelimiterOrEof(buff[0..], '\n'); + const trimmed_a = std.mem.trimEnd(u8, input_a.?, "\r"); // for Windows + const a = try std.fmt.parseInt(i32, trimmed_a, 10); - const a = try std.fmt.parseInt(i64, it.next().?, 10); - const b = try std.fmt.parseInt(i64, it.next().?, 10); + try stdout.print("Value of b: ", .{}); + const input_b: ?[]u8 = try stdin.readUntilDelimiterOrEof(buff[0..], '\n'); + const trimmed_b = std.mem.trimEnd(u8, input_b.?, "\r"); // for Windows + const b = try std.fmt.parseInt(i32, trimmed_b, 10); - try stdout.print("Values: a {d} b {d}\n", .{a, b}); - try stdout.print("Sum: a + b = {d}\n", .{a + b}); - try stdout.print("Difference: a - b = {d}\n", .{a - b}); - try stdout.print("Product: a * b = {d}\n", .{a * b}); - try stdout.print("Integer quotient: a / b = {d}\n", .{@divTrunc(a, b)}); //truncates towards 0 - try stdout.print("Remainder: a % b = {d}\n", .{@rem(a, b)}); // same sign as first operand - try stdout.print("Exponentiation: math.pow = {d}\n", .{std.math.pow(i64, a, b)}); //no exponentiation operator + try stdout.print("a + b = {d}\n", .{a + b}); + try stdout.print("a - b = {d}\n", .{a - b}); + try stdout.print("a * b = {d}\n", .{a * b}); + try stdout.print("a / b (floor) = {d}\n", .{@divFloor(a, b)}); + try stdout.print("a / b (trunk) = {d}\n", .{@divTrunc(a, b)}); + try stdout.print("a % b (mod) = {d}\n", .{@mod(a, b)}); + try stdout.print("a % b (rem) = {d}\n", .{@rem(a, b)}); + try stdout.print("a ^ b = {d}\n", .{std.math.pow(i32, a, b)}); } diff --git a/Task/Arithmetic-Rational/Pluto/arithmetic-rational.pluto b/Task/Arithmetic-Rational/Pluto/arithmetic-rational.pluto new file mode 100644 index 0000000000..cdf2393f77 --- /dev/null +++ b/Task/Arithmetic-Rational/Pluto/arithmetic-rational.pluto @@ -0,0 +1,12 @@ +local int = require "int" +require "rat" + +local one = rat.of(1) +print("The following numbers (less than 2^19) are perfect:") +for i = 2, (1 << 19) - 1 do + local sum = rat.of(1, i) + local divs = int.divisors(i, true) + divs:remove(1) + for divs as j do sum += rat.of(1, j) end + if sum == one then print($" {i}") end +end diff --git a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx index a7f3438a50..bde84235e2 100644 --- a/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx +++ b/Task/Arithmetic-Rational/REXX/arithmetic-rational.rexx @@ -1,64 +1,63 @@ +-- 28 Jul 2025 include Settings -say 'RATIONAL ARITHMETIC - 2 Mar 2025' +say 'RATIONAL ARITHMETIC' say version say a = '1 2'; b = '-3 4'; c = '5 -6'; d = '-7 -8'; e = 3; f = 1.666666666 say 'VALUES' -say 'a =' Rlst2form(a) -say 'b =' Rlst2form(b) -say 'c =' Rlst2form(c) -say 'd =' Rlst2form(d) +say 'a =' Lst2FormQ(a) +say 'b =' Lst2FormQ(b) +say 'c =' Lst2FormQ(c) +say 'd =' Lst2FormQ(d) say 'e =' e say 'f =' f say say 'BASICS' -say 'a+b =' Rlst2form(Radd(a,b)) -say 'a+b+c+d =' Rlst2form(Radd(a,b,c,d)) -say 'a-b =' Rlst2form(Rsub(a,b)) -say 'a-b-c-d =' Rlst2form(Rsub(a,b,c,d)) -say 'a*b =' Rlst2form(Rmul(a,b)) -say 'a*b*c*d =' Rlst2form(Rmul(a,b,c,d)) -say 'a/b =' Rlst2form(Rdiv(a,b)) -say 'a/b/c/d =' Rlst2form(Rdiv(a,b,c,d)) -say '-a =' Rlst2form(Rneg(a)) -say '1/a =' Rlst2form(Rinv(a)) +say 'a+b =' Lst2FormQ(AddQ(a,b)) +say 'a+b+c+d =' Lst2FormQ(AddQ(a,b,c,d)) +say 'a-b =' Lst2FormQ(SubQ(a,b)) +say 'a-b-c-d =' Lst2FormQ(SubQ(a,b,c,d)) +say 'a*b =' Lst2FormQ(MulQ(a,b)) +say 'a*b*c*d =' Lst2FormQ(MulQ(a,b,c,d)) +say 'a/b =' Lst2FormQ(DivQ(a,b)) +say 'a/b/c/d =' Lst2FormQ(DivQ(a,b,c,d)) +say '-a =' Lst2FormQ(NegQ(a)) +say '1/a =' Lst2FormQ(InvQ(a)) say -say 'COMPARE' -say 'a=b =' Rge(a,b) -say 'a>b =' Rgt(a,b) -say 'a<>b =' Rne(a,b) +say 'Compare' +say 'a=b =' GeQ(a,b) +say 'a>b =' GtQ(a,b) +say 'a<>b =' NeQ(a,b) say say 'BONUS' -say 'Abs(c) =' Rlst2form(Rabs(c)) -say 'Float(b) =' Rfloat(b) -say 'Neg(d) =' Rlst2form(Rneg(d)) -say 'Power(a,e) =' Rlst2form(Rpow(a,e)) -say 'Rational(f) =' Rlst2form(Rrat(f)) +say 'Abs(c) =' Lst2FormQ(AbsQ(c)) +say 'Float(b) =' FloatQ(b) +say 'Neg(d) =' Lst2FormQ(NegQ(d)) +say 'Power(a,e) =' Lst2FormQ(PowQ(a,e)) +say 'Rational(f) =' Lst2FormQ(RatQ(f)) say say 'FORMULA' say 'a^2-2ab+3c-4ad^4+5 = ', -Rlst2form(Radd(Rpow(a,2),Rmul(-2,a,b),Rmul(3,c),Rmul(-4,a,Rpow(d,4)),5)) +Lst2FormQ(AddQ(PowQ(a,2),MulQ(-2,a,b),MulQ(3,c),MulQ(-4,a,PowQ(d,4)),5)) say -say 'PERFECT NUMBERS' -call time('r') +say 'Perfect numbers' +call Time('r') numeric digits 20 do c = 6 to 2**19 s = 1 c; m = Isqrt(c) do f = 2 to m if c//f = 0 then do - s = Radd(s,1 f,1 c/f) + s = AddQ(s,1 f,1 c/f) end end - if Req(s,1) then + if EqQ(s,1) then say c 'is a perfect number' end -say time('e')/1's' +say Time('e')/1's' exit -include Rational -include Functions -include Abend +include Math diff --git a/Task/Arithmetic-derivative/Bc/arithmetic-derivative.bc b/Task/Arithmetic-derivative/Bc/arithmetic-derivative.bc new file mode 100644 index 0000000000..2fd8905b3f --- /dev/null +++ b/Task/Arithmetic-derivative/Bc/arithmetic-derivative.bc @@ -0,0 +1,25 @@ +define d(n) { + auto f + if(n<0) return -d(-n) + if(n<2) return 0 + s = 0 + r = n + for(f=2;f<=r;f++) { + while(r%f==0){ + r /= f + s += n / f + } + } + return s +} + +define padl(n,f) { + for(i=0;i - $40 { // ( + $40 : { // ( ^ weak self.newBracket().gotoStarting() } - ! { + ! : { ^ weak self.newToken().append(ch).gotoToken() } } @@ -108,22 +108,22 @@ singleton tokenState eval(ch) { ch => - $41 { // ) + $41 : { // ) ^ weak self.closeBracket().gotoToken() } - $42 { // * + $42 : { // * ^ weak self.newProduct().gotoOperator() } - $43 { // + + $43 : { // + ^ weak self.newSummary().gotoOperator() } - $45 { // - + $45 : { // - ^ weak self.newDifference().gotoOperator() } - $47 { // / + $47 : { // / ^ weak self.newFraction().gotoOperator() } - ! { + ! : { ^ weak self.append(ch) } } @@ -134,13 +134,13 @@ singleton startState eval(ch) { ch => - $40 { // ( + $40 : { // ( ^ weak self.newBracket().gotoStarting() } - $45 { // - + $45 : { // - ^ weak self.newToken().append("0").newDifference().gotoOperator() } - ! { + ! : { ^ weak self.newToken().append(ch).gotoToken() } } @@ -148,11 +148,11 @@ singleton startState class Scope { - object _state; - int _level; - object _parser; - object _token; - object _expression; + object _state; + int _level; + object _parser; + object? _token; + object _expression; constructor new(parser) { @@ -327,15 +327,15 @@ public program() var text := new StringWriter(); var parser := new Parser(); - while (console.readLine().writeTo(text).Length > 0) + while (Console.readLine().writeTo(text).Length > 0) { try { - console.printLine("=",parser.run(text)) + Console.printLine("=",parser.run(text)) } catch(Exception e) { - console.writeLine("Invalid Expression") + Console.writeLine("Invalid Expression") }; text.clear() diff --git a/Task/Arithmetic-evaluation/PascalABC.NET/arithmetic-evaluation.pas b/Task/Arithmetic-evaluation/PascalABC.NET/arithmetic-evaluation.pas new file mode 100644 index 0000000000..b19c2a67d1 --- /dev/null +++ b/Task/Arithmetic-evaluation/PascalABC.NET/arithmetic-evaluation.pas @@ -0,0 +1,127 @@ +type + IExprNode = interface + function Evaluate: real; + end; + + NumberNode = auto class(IExprNode) + public + value: real; + function Evaluate: real := value; + end; + + BinaryOpNode = auto class(IExprNode) + public + op: char; + left, right: IExprNode; + + function Evaluate: real; + begin + case op of + '+': Result := left.Evaluate + right.Evaluate; + '-': Result := left.Evaluate - right.Evaluate; + '*': Result := left.Evaluate * right.Evaluate; + '/': Result := left.Evaluate / right.Evaluate; + else + raise new Exception($'Unknown operator {op}'); + end; + end; + end; + + ExpressionParser = class + s: string; + pos: integer; + + constructor Create(input: string); + begin + s := input; + pos := 1; + end; + + function NextChar: char := + if pos <= s.Length then s[pos] else #0; + + procedure SkipSpaces := + while NextChar = ' ' do pos += 1; + + function ParseNumber: IExprNode; + begin + SkipSpaces; + var start := pos; + while NextChar.IsDigit do pos += 1; + if NextChar = '.' then + begin + pos += 1; + while NextChar.IsDigit do pos += 1; + end; + var value := s[start:pos].ToReal; + Result := new NumberNode(value); + end; + + function ParseFactor: IExprNode; + begin + SkipSpaces; + if NextChar = '(' then + begin + pos += 1; + Result := ParseExpr; + SkipSpaces; + if NextChar = ')' then + pos += 1 + else raise new Exception('Expected )'); + end + else + Result := ParseNumber; + end; + + function ParseTerm: IExprNode; + begin + Result := ParseFactor; + while true do + begin + SkipSpaces; + var ch := NextChar; + if (ch = '*') or (ch = '/') then + begin + pos += 1; + Result := new BinaryOpNode(ch, Result, ParseFactor); + end + else break; + end; + end; + + function ParseExpr: IExprNode; + begin + Result := ParseTerm; + while true do + begin + SkipSpaces; + var ch := NextChar; + if (ch = '+') or (ch = '-') then + begin + pos += 1; + Result := new BinaryOpNode(ch, Result, ParseTerm); + end + else break; + end; + end; + + function Parse: IExprNode := ParseExpr; + + end; + +begin + var inputs := [ + '2+3*(4-1)', + '10 + 2 / 3', + '(7+3)*(2+2)', + '8*(5+(2-3))', + '1/3', + '2.5 + 4.1 * (3 - 1.1/2)']; + + foreach var expr in inputs do + begin + var parser := new ExpressionParser(expr); + var tree := parser.Parse; + Println($'{expr} = {tree.Evaluate:0.###}'); + end; +end. diff --git a/Task/Arithmetic-evaluation/Perl/arithmetic-evaluation.pl b/Task/Arithmetic-evaluation/Perl/arithmetic-evaluation-1.pl similarity index 100% rename from Task/Arithmetic-evaluation/Perl/arithmetic-evaluation.pl rename to Task/Arithmetic-evaluation/Perl/arithmetic-evaluation-1.pl diff --git a/Task/Arithmetic-evaluation/Perl/arithmetic-evaluation-2.pl b/Task/Arithmetic-evaluation/Perl/arithmetic-evaluation-2.pl new file mode 100644 index 0000000000..47161a8da0 --- /dev/null +++ b/Task/Arithmetic-evaluation/Perl/arithmetic-evaluation-2.pl @@ -0,0 +1,49 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Arithmetic_evaluation +use warnings; + +sub node { bless [ splice @_, 1 ], shift } +sub error { die s/\G.*//sr =~ tr/\t/ /cr, "^ @_ !\n" } +sub want { /\G$_[1]/gc ? shift : error pop } + +sub expr + { + /\G\h+/gc; + my $ast = + /\G\d+/gc ? node NUMBER => $& : + /\G\(/gc ? want expr(0), qr/\)/, 'Missing Right Paren' : + error 'Operand Expected'; + /\G\h+/gc, $ast = + $_[0] <= 0 && /\G\+/gc ? node ADD => $ast, expr(1) : + $_[0] <= 0 && /\G\-/gc ? node SUBTRACT => $ast, expr(1) : + $_[0] <= 1 && /\G\*/gc ? node MULTIPLY => $ast, expr(2) : + $_[0] <= 1 && /\G\//gc ? node DIVIDE => $ast, expr(2) : + return $ast while 1; + } + +sub ADD::value { $_[0][0]->value + $_[0][1]->value } +sub SUBTRACT::value { $_[0][0]->value - $_[0][1]->value } +sub MULTIPLY::value { $_[0][0]->value * $_[0][1]->value } +sub DIVIDE::value { $_[0][0]->value / $_[0][1]->value } +sub NUMBER::value { $_[0][0] } + +sub NUMBER::show { "$_[0][0]\n" } +sub UNIVERSAL::show + { ref($_[0]) . "\n" . join('', map $_->show, @{$_[0]}) =~ s/^/ /gmr } + +while( ) + { + eval + { + print; + my $ast = want expr(0), "\n", 'Incomplete Parse'; + print $ast->show, "value of ast = ", $ast->value, "\n\n"; + } or print "$@\n"; + } + +__DATA__ +(1+3)*7 +2 * 3 + 4 * 5 +2 + 3 * 4 + 5 +2 + 3 ** 4 + 5 diff --git a/Task/Arithmetic-evaluation/Red/arithmetic-evaluation.red b/Task/Arithmetic-evaluation/Red/arithmetic-evaluation.red new file mode 100644 index 0000000000..d672f8909b --- /dev/null +++ b/Task/Arithmetic-evaluation/Red/arithmetic-evaluation.red @@ -0,0 +1,113 @@ +Red [ "Arithmetic Evaluator - Hinjo, August 2025" + {Using a Modified Shunting-Yard algorithm to produce S-Expression as the AST + and a simple S-Expression evaluator (recursive).} +] + +s-expr: function [expr [string!] /trace] [ + output: copy [] ops: copy [] + prec: #["+" 2 "-" 2 "*" 3 "/" 3 "^^" 4] + asc: #["+" "L" "-" "L" "*" "L" "/" "L" "^^" "R"] + + stats: function [t] [ + if not trace [exit] + print [t "|" pad act 25 "|" pad (mold output) 45 pad/left (reverse form ops) 15] + ] + + make-node: function [op] [ + right: take/last output + left: take/last output + node: load rejoin ["[" op " " mold left " " mold right "]"] + node + ] + + tokens: split expr " " + while [not empty? tokens] [ + tok: first tokens tokens: next tokens + case [ + find "0123456789" tok [ + act: "1.Push number as value" + append output load tok + stats tok + ] + tok = "(" [ + act: "2.Push ( to ops" + append ops tok + stats tok + ] + tok = ")" [ + while [(last ops) <> "("] [ + act: "3.Pop op, build node" + append/only output make-node take/last ops + stats tok + ] + act: "4.Discard (" + take/last ops + stats tok + ] + find "+-*/^^" tok [ + + popping: func [][ + if empty? ops [return false] + if none? last ops [return false] + last-op: last ops + if last-op = ")" [return false] + if none? prec/:last-op [return false] + return (prec/:last-op > prec/:tok) + or ((prec/:last-op = prec/:tok) + and (asc/:tok = "L")) + ] + + while [popping] [ + act: "5.Pop op, build node" + append/only output make-node take/last ops + stats tok + ] + act: "6.Push current op" + append ops tok + stats tok + ] + ] + ] + act: "7.Final flush ops" + stats " " + while [not empty? ops] [ + act: "8.Pop op, build node" + append/only output make-node take/last ops + stats " " + ] + output/1 +] + +; basic s-expression evaluator +s-eval: function [expr][ + either block? expr [ + op: expr/1 + a: s-eval expr/2 + b: s-eval expr/3 + case [ + op = '+ [a + b] + op = '- [a - b] + op = '* [a * b] + op = '/ [a / b] + op = '^ [a ** b] + true [do make error! rejoin ["Unknown operator: " mold op]] + ] + ][ + expr ; base case: just a number + ] +] + +print "Simple test:" +s: "1 + 2" se: s-expr s print [pad s 40 " ==> " pad (mold se) 45 " = " s-eval se] +s: "1 + 2 * 3" se: s-expr s print [pad s 40 " ==> " pad (mold se) 45 " = " s-eval se] +s: "( 1 + 2 ) * 3" se: s-expr s print [pad s 40 " ==> " pad (mold se) 45 " = " s-eval se] +s: "( 1 + 2 * 3 ) / 2" se: s-expr s print [pad s 40 " ==> " pad (mold se) 45 " = " s-eval se] + +print "^/Complex ones:" +s: "3 + 4 * 2 / ( 1 - 5 ) ^^ 2 ^^ 3" se: s-expr s print [pad s 40 " ==> " pad (mold se) 45 " = " s-eval se] +s: "( 1 + 2 * 3 ) ^^ 2 / 6 ^^ 2 ^^ 3 - 1" se: s-expr s print [pad s 40 " ==> " pad (mold se) 45 " = " s-eval se] + +print "^/Some test for input and output with trace:" +print ["^/" s: "3 + 4 * 2 / ( 1 - 5 ) ^^ 2 ^^ 3"] se: s-expr/trace s print [s " ==> " mold se " = " s-eval se] +print ["^/" s: "( ( 1 + 2 ) ^^ ( 3 + 4 ) ) ^^ ( 5 + 6 )"] se: s-expr/trace s print [s " ==> " mold se " = " s-eval se] +print ["^/" s: "1 + 2 * 3 / 4 + 5"] se: s-expr/trace s print [s " ==> " mold se " = " s-eval se] diff --git a/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg b/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg index f41fbacd2a..18ca866f48 100644 --- a/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg +++ b/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg @@ -19,5 +19,5 @@ BEGIN a FI END; - printf (($l(-35,33)l$, agm (LONG 1.0, LONG 1.0 / long sqrt (LONG 2.0)))) + printf (($lg(-35,33)l$, agm (LONG 1.0, LONG 1.0 / long sqrt (LONG 2.0)))) END diff --git a/Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-1.duckdb b/Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-1.duckdb new file mode 100644 index 0000000000..92b0794da3 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-1.duckdb @@ -0,0 +1,12 @@ +with recursive + rec(rn, a, g, diff) as ( + select 1, 1.0, 1/sqrt(2), 1 - 1/sqrt(2) + union all + select rn + 1, (a + g)/2, sqrt(a * g), (a + g)/2 - sqrt(a * g) + from rec + where diff > 1e-15 + ) +select * +from rec +where diff <= 1e-15 +; diff --git a/Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-2.duckdb b/Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-2.duckdb new file mode 100644 index 0000000000..3c8c0277bd --- /dev/null +++ b/Task/Arithmetic-geometric-mean/DuckDB/arithmetic-geometric-mean-2.duckdb @@ -0,0 +1,14 @@ +create or replace function agm(a0, g0) as ( +with recursive + rec as ( + select a0::DOUBLE as a, g0::DOUBLE as g, a - g as diff + union all + select a, g, (a - g) as diff + from ( select ((a + g)/2) as a, sqrt(a * g) as g, diff + from rec ) + where diff > 1e-15 ) + select (a + g)/2 + from rec + where diff <= 1e-15 + limit 1 +); diff --git a/Task/Arithmetic-geometric-mean/Pluto/arithmetic-geometric-mean.pluto b/Task/Arithmetic-geometric-mean/Pluto/arithmetic-geometric-mean.pluto new file mode 100644 index 0000000000..cc3914b6c2 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Pluto/arithmetic-geometric-mean.pluto @@ -0,0 +1,10 @@ +$define EPS = 1e-14 + +local function agm(a, g) + while math.abs(a - g) > math.abs(a) * EPS do + a, g = (a + g) / 2, math.sqrt(a * g) + end + return a +end + +print(agm(1.0, 1.0 /math.sqrt(2))) diff --git a/Task/Arithmetic-numbers/DuckDB/arithmetic-numbers.duckdb b/Task/Arithmetic-numbers/DuckDB/arithmetic-numbers.duckdb new file mode 100644 index 0000000000..4aea7d6141 --- /dev/null +++ b/Task/Arithmetic-numbers/DuckDB/arithmetic-numbers.duckdb @@ -0,0 +1,70 @@ +### Preliminaries +# If x is NULL then raise an error condition: +create or replace function try(x, ErrorMessage) as ( + if( x IS NULL, error( ErrorMessage ), x ) +); + +create or replace function proper_divisors(n) as table ( + select 1 where n > 1 + union all + select distinct i + from (select unnest( [ j, n // j]) as i + from range(2, 1 + sqrt(n).floor()::BIGINT) as t(j) + where (n % j) == 0) +); + +create or replace function composite(n) as ( + select count(*) == 2 as n from (from proper_divisors(n) limit 2) +); + +create or replace function average_is_integral(lst) as ( + list_sum(lst) % length(lst) = 0 +); + +create or replace function list_of_proper_divisors(n) as ( + select coalesce(array_agg(i), []) as divisors from proper_divisors(n) t(i) +); + + +### Arithmetic numbers +# A table of the arithmetic numbers in range(1, mx) +create or replace function arithmetic_numbers(mx) as table ( + select n + from range(1, mx) t(n) + where average_is_integral(list_of_proper_divisors(n) || [n]) + order by n -- needed +); + +# A table (n, composite) of the arithmetic numbers in range(1, mx) showing also whether each is composite +create or replace function describe_arithmetic_numbers(mx) as table ( + select n, length(lst) > 1 as composite + from + (select n, list_of_proper_divisors(n) as lst + from range(1, mx) t(n) + where average_is_integral(lst || [n]) + order by n -- needed + ) +); + +# Return a struct {nth, composites} giving the nth arithmetic number +# and the number of composites less than or equal to that number. +# If the heuristic fails, an error is raised. +create or replace function describe_nth_arithmetic_number(nth) as ( + with cte as (from describe_arithmetic_numbers(nth * 2) limit nth) + select try( + (select { nth: (select last(n) from cte), + composites: (select count(*) from cte where composite = true)} + where nth = (select count(*) from cte)), + 'heuristic failure') +); + +# Return a list of the first `number` arithmetic numbers using a +# heuristic cautiously +create or replace function arithmetic_numbers_list(number) as ( + with cte as (from describe_arithmetic_numbers(number * 2 ) limit number), + m as (select count(*) as m from cte) + select try( + if (m = number, (select array_agg(n) from cte), null), + 'heuristic failure' ) + from m +); diff --git a/Task/Array-concatenation/ArkScript/array-concatenation.ark b/Task/Array-concatenation/ArkScript/array-concatenation.ark new file mode 100644 index 0000000000..41ea61f667 --- /dev/null +++ b/Task/Array-concatenation/ArkScript/array-concatenation.ark @@ -0,0 +1,4 @@ +(let a [1 2 3]) +(let b [4 5 6]) + +(assert (= (concat a b) [1 2 3 4 5 6]) "array concatenation") diff --git a/Task/Array-concatenation/DuckDB/array-concatenation.duckdb b/Task/Array-concatenation/DuckDB/array-concatenation.duckdb new file mode 100644 index 0000000000..1502edf1f9 --- /dev/null +++ b/Task/Array-concatenation/DuckDB/array-concatenation.duckdb @@ -0,0 +1,4 @@ +# Concatenate two JSON arrays to produce an instance of JSON[] +create or replace function jsonarray2list(j) as ( + select list_transform(range(0, json_array_length(j)::BIGINT), i -> (j -> i)) +); diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 4d412e7dbb..41d210bd59 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -5,7 +5,7 @@ public program() var a := new int[]{1,2,3}; var b := new int[]{4,5}; - console.printLine( + Console.printLine( "(",a.asEnumerable(),") + (",b.asEnumerable(), ") = (",(a + b).asEnumerable(),")").readChar(); } diff --git a/Task/Array-concatenation/Pluto/array-concatenation.pluto b/Task/Array-concatenation/Pluto/array-concatenation.pluto new file mode 100644 index 0000000000..e110f3faff --- /dev/null +++ b/Task/Array-concatenation/Pluto/array-concatenation.pluto @@ -0,0 +1,12 @@ +local array1 = {1, 2, 3} +local array2 = {4, 5, 6} + +-- Concatenate to a new array. +local array3 = {} +table.move(array1, 1, #array1, 1, array3) +table.move(array2, 1, #array2, #array3 + 1, array3) +print(array3:concat(", ")) + +-- Merge second into first array. +table.move(array2, 1, #array2, #array1 + 1, array1) +print(array1:concat(", ")) diff --git a/Task/Array-concatenation/TAV/array-concatenation.tav b/Task/Array-concatenation/TAV/array-concatenation.tav new file mode 100644 index 0000000000..b9f873d11c --- /dev/null +++ b/Task/Array-concatenation/TAV/array-concatenation.tav @@ -0,0 +1,3 @@ + a1 =: tuple 1, 2, 3 as row + row a1 append 4, 5, 6 \ append tuple elements to a row + print join a1 diff --git a/Task/Array-length/ArkScript/array-length.ark b/Task/Array-length/ArkScript/array-length.ark new file mode 100644 index 0000000000..1cd019c302 --- /dev/null +++ b/Task/Array-length/ArkScript/array-length.ark @@ -0,0 +1,2 @@ +(assert (= (len []) 0) "len of empty array is 0") +(assert (= (len [1 2 3 4]) 4) "len of array is 4") diff --git a/Task/Array-length/DuckDB/array-length.duckdb b/Task/Array-length/DuckDB/array-length.duckdb new file mode 100644 index 0000000000..dde1b2e9f1 --- /dev/null +++ b/Task/Array-length/DuckDB/array-length.duckdb @@ -0,0 +1 @@ +select length( ['apple', 'orange' ] ) as length; diff --git a/Task/Array-length/M2000-Interpreter/array-length.m2000 b/Task/Array-length/M2000-Interpreter/array-length.m2000 index 55bd640ccf..d3bf86ac9d 100644 --- a/Task/Array-length/M2000-Interpreter/array-length.m2000 +++ b/Task/Array-length/M2000-Interpreter/array-length.m2000 @@ -1,38 +1,3 @@ \\ A is a pointer to array A=("Apple", "Orange") Print Len(A)=2 ' True -Print Dimension(A, 0) ' LBound (0 or 1), here 0 -Print Dimension(A) ' No of Dimensions 1 -Print Dimension(A, 1) ' for 1 dimension array this is also Length=2 -\\ A$( ) is an Array (not a pointer to array) -Dim Base 1, A$(2) -A$(1)="Apple", "Orange" -Print Dimension(A$(), 0) ' LBound (0 or 1), here 1 -Print Dimension(A$()) ' No of Dimensions 1 -Print Dimension(A$(), 1) ' for 1 dimension array this is also Length=2 -Link A to B$() ' B$() is a reference to A -Print B$(0)=A$(1) -Print B$(1)=A$(2) -Dim C$() -\\ C$() get a copy of B$() -C$()=B$() -Print C$() ' prints Apple Orange -\\ An array can link to a new name as reference, and can change major type -\\ here A$() get A() so we can read/store numbers and read/store strings in same array -\\ using two names -Link A$() to A() -\\ An array pointer can point to another array -A=A() -Print Dimension(A, 0) ' LBound (0 or 1), here 1 (was 0) -\\ Because B$() is reference of A: -Print Dimension(B$(), 0) ' LBound (0 or 1), here 1 (was 0) -Print B$(1)=A$(1) -Print B$(2)=A$(2) -Print Dimension(C$(), 0) ' LBound (0 or 1), here 0 -\\ change base preserve items -Dim Base 1, C$(Dimension(C$(), 1)) -Print Dimension(C$(), 0) ' LBound (0 or 1), here 1 (was 0) -Print C$() ' prints Apple Orange -Print Len(C$()) ' Len return all items of an array - can be 0 -Dim K(1,1,1,1,1,1) ' Maximum 10 dimensions -Print Len(K()=1 ' True diff --git a/Task/Array-length/Maxima/array-length.maxima b/Task/Array-length/Maxima/array-length.maxima new file mode 100644 index 0000000000..56cfb97fe9 --- /dev/null +++ b/Task/Array-length/Maxima/array-length.maxima @@ -0,0 +1,4 @@ +length(["apple","orange"]); +fruits: matrix(["apple","orange"],["banana","pear"])$ +length(fruits); +length(list_matrix_entries(fruits)); diff --git a/Task/Array-length/TAV/array-length.tav b/Task/Array-length/TAV/array-length.tav new file mode 100644 index 0000000000..a54c8b0a26 --- /dev/null +++ b/Task/Array-length/TAV/array-length.tav @@ -0,0 +1 @@ +print ('apple', 'orange').Count diff --git a/Task/Array-length/Tcl/array-length-1.tcl b/Task/Array-length/Tcl/array-length-1.tcl new file mode 100644 index 0000000000..1fe942888c --- /dev/null +++ b/Task/Array-length/Tcl/array-length-1.tcl @@ -0,0 +1 @@ +set mylist { item1 item2 item3 } diff --git a/Task/Array-length/Tcl/array-length-2.tcl b/Task/Array-length/Tcl/array-length-2.tcl new file mode 100644 index 0000000000..2abd436f52 --- /dev/null +++ b/Task/Array-length/Tcl/array-length-2.tcl @@ -0,0 +1 @@ +set furniture "chair table lamp sofa bed desk" diff --git a/Task/Array-length/Tcl/array-length-3.tcl b/Task/Array-length/Tcl/array-length-3.tcl new file mode 100644 index 0000000000..36b3b6edee --- /dev/null +++ b/Task/Array-length/Tcl/array-length-3.tcl @@ -0,0 +1,5 @@ +set paths [split "/sbin:/bin:/usr/bin:/usr/local/bin:$home/bin" ":"] + +foreach p $paths { + puts "$p" +} diff --git a/Task/Array-length/Tcl/array-length-4.tcl b/Task/Array-length/Tcl/array-length-4.tcl new file mode 100644 index 0000000000..3ed1cddf82 --- /dev/null +++ b/Task/Array-length/Tcl/array-length-4.tcl @@ -0,0 +1,2 @@ +set A {} +set B [list] diff --git a/Task/Array-length/Tcl/array-length-5.tcl b/Task/Array-length/Tcl/array-length-5.tcl new file mode 100644 index 0000000000..b1f7c4fab0 --- /dev/null +++ b/Task/Array-length/Tcl/array-length-5.tcl @@ -0,0 +1 @@ + set var 5 ;# ($var is the string "5", or the integer 5 , or a list with one item {5} ) diff --git a/Task/Array-length/Tcl/array-length-6.tcl b/Task/Array-length/Tcl/array-length-6.tcl new file mode 100644 index 0000000000..e6250e3fd2 --- /dev/null +++ b/Task/Array-length/Tcl/array-length-6.tcl @@ -0,0 +1,5 @@ +set len [llength "Apples Oranges"] ;# 2 +set len [llength {Apples Oranges}] ;# 2 +set fruit { apples oranges cherries bananas} +set len [llength $fruit] +puts stdout "($len) : $fruit" diff --git a/Task/Array-length/Tcl/array-length-7.tcl b/Task/Array-length/Tcl/array-length-7.tcl new file mode 100644 index 0000000000..2042a29d9f --- /dev/null +++ b/Task/Array-length/Tcl/array-length-7.tcl @@ -0,0 +1,10 @@ +# The ''lindex'' command returns a single item at a given index of a list + +set c [lindex $fruit 2] ;# "cherries" (0-based index) + +# The ''lrange'' command returns a given range of items from a list, as a new list. + +set A [lrange $fruit 0 2] ;# {apples oranges cherries} (list) + +# An empty list is not necessarily an empty string: +set var { } ;# $var => " ", but [llength $var] => 0 diff --git a/Task/Array-length/Tcl/array-length.tcl b/Task/Array-length/Tcl/array-length.tcl deleted file mode 100644 index 5b7cf51645..0000000000 --- a/Task/Array-length/Tcl/array-length.tcl +++ /dev/null @@ -1,13 +0,0 @@ -;# not recommended: -set mylistA {apple orange} ;# actually a string -set mylistA "Apple Orange" ;# same - this works only for simple cases - -set lenA [llength $mylistA] -puts "$mylistA : $lenA" - -# better: to build a list, use 'list' and/or 'lappend': -set mylistB [list apple orange "red wine" {green frog}] -lappend mylistB "blue bird" - -set lenB [llength $mylistB] -puts "$mylistB : $lenB" diff --git a/Task/Arrays/BBC-BASIC/arrays.basic b/Task/Arrays/BBC-BASIC/arrays.basic index 508e04a217..eaf82c4ae8 100644 --- a/Task/Arrays/BBC-BASIC/arrays.basic +++ b/Task/Arrays/BBC-BASIC/arrays.basic @@ -15,3 +15,8 @@ PRINT array(2) TAB(16) array(3) TAB(32) array(4) PRINT array%(2) TAB(16) array%(3) TAB(32) array%(4) PRINT array$(2) TAB(16) array$(3) TAB(32) array$(4) + + REM Some versions of BBC BASIC support array slicing: + array(2 TO 4) = source(1 TO 3) + array(3 TO 5) = 2, 4, -1 + array(3 TO 5) = array(4 TO 6) diff --git a/Task/Arrays/DuckDB/arrays.duckdb b/Task/Arrays/DuckDB/arrays.duckdb new file mode 100644 index 0000000000..b580ce44c0 --- /dev/null +++ b/Task/Arrays/DuckDB/arrays.duckdb @@ -0,0 +1,9 @@ +# Insert `value` after row i (using IO=1) in a one-column table named t (a string). +create or replace function insert_after(i, value, t) as table ( + (FROM query_table(t) LIMIT i) + union all + select value + union all (FROM query_table(t) OFFSET i) +); + +from insert_after_row(1, 100, 't'); diff --git a/Task/Arrays/Elena/arrays-5.elena b/Task/Arrays/Elena/arrays-5.elena index 9b69e70cb8..ae97e67492 100644 --- a/Task/Arrays/Elena/arrays-5.elena +++ b/Task/Arrays/Elena/arrays-5.elena @@ -1,3 +1,3 @@ - system'console.writeLine(array[0]); - system'console.writeLine(stackAllocatedArray[1]); - system'console.writeLine(dynamicArray[2]); + system'Console.writeLine(array[0]); + system'Console.writeLine(stackAllocatedArray[1]); + system'Console.writeLine(dynamicArray[2]); diff --git a/Task/Arrays/Extended-Color-BASIC/arrays.basic b/Task/Arrays/Extended-Color-BASIC/arrays.basic new file mode 100644 index 0000000000..0f32fa7335 --- /dev/null +++ b/Task/Arrays/Extended-Color-BASIC/arrays.basic @@ -0,0 +1,4 @@ +10 DIM A(10), B$(10) +20 A(1) = 42 +30 B$(10) = "TOWEL" +40 PRINT A(1), B$(10) diff --git a/Task/Arrays/Haxe/arrays.haxe b/Task/Arrays/Haxe/arrays.haxe new file mode 100644 index 0000000000..8fccc28c0e --- /dev/null +++ b/Task/Arrays/Haxe/arrays.haxe @@ -0,0 +1,22 @@ +class Main { + static public function main():Void { + // Array (dynamic length) + var a = new Array(); + for (i in 1...4) + a.push(i); + // alt: var a = [1, 2, 3]; + // alt2: var a = [for (i in 1...4)]; + + for (i in 0...a.length) + trace(a[i]); + + // Vector (fixed-length) + var v = new haxe.ds.Vector(3); + v[0] = 1; + v[1] = 2; + v[2] = 3; + + for (i in 0...v.length) + trace(v[i]); + } +} diff --git a/Task/Arrays/Pluto/arrays.pluto b/Task/Arrays/Pluto/arrays.pluto new file mode 100644 index 0000000000..c7544909c7 --- /dev/null +++ b/Task/Arrays/Pluto/arrays.pluto @@ -0,0 +1,8 @@ +local array = {} +array:insert(42) +array:insert(43) +print(array:concat(", ")) -- 42, 43 +print(array[1]) -- 42, since indexing starts at 1 +print(#array) -- 2, since # is the length operator +array:clear() +print(#array) -- 0 diff --git a/Task/Arrays/REXX/arrays.rexx b/Task/Arrays/REXX/arrays.rexx index 74e20f3ddc..6f758adf93 100644 --- a/Task/Arrays/REXX/arrays.rexx +++ b/Task/Arrays/REXX/arrays.rexx @@ -1,56 +1,59 @@ --- 1 Jun 2025 +-- 7 Aug 2025 include Settings say 'ARRAYS' say version say -say 'A simple array...' -do i = 1 to 100 +if Pos('Regina',version) > 0 then + call Library +say 'Simple array...' +do i = 1 to 10 a.i=i*i end -say 'Square of' 5 'is' a.5 -say 'Square of' 55 'is' a.55 +say 'Square of' 3 'is' a.3 +say 'Square of' 7 'is' a.7 say say 'Mimic indexing...' -say 'Square of' 5 'is' a(5) -say 'Square of' 55 'is' a(55) +say 'Square of' 3 'is' a(3) +say 'Square of' 7 'is' a(7) say say 'A default value...' b. = 'Out of range' -do i = 1 to 100 +do i = 1 to 10 b.i=1/i end -say 'Inverse of' 5 'is' b.5 -say 'Inverse of' 55 'is' b.55 -say 'Inverse of' 555 'is' b.555 +say 'Inverse of' 3 'is' b.3 +say 'Inverse of' 7 'is' b.7 +say 'Inverse of' 11 'is' b.11 say -say 'An other index range...' -do i = -100 to 100 +say 'Index zero...' +do i = 1 to 10 c.i=i*i*i end -j=-55; say 'Cube of' j 'is' c.j -j=-5; say 'Cube of' j 'is' c.j -j=5; say 'Cube of' j 'is' c.j -j=55; say 'Cube of' j 'is' c.j +c.0=10 +j=0; say 'Number of rows is' c.j +j=3; say 'Cube of' j 'is' c.j +j=7; say 'Cube of' j 'is' c.j say -say 'A sparse array...' -d.='Not calculated' -do i = 2 by 2 to 100 +say 'Sparse array...' +d.=0 +do i = 3 by 3 to 9 d.i=-i end -say 'Negative of' 55 'is' d.55 -say 'Negative of' 56 'is' d.56 +say 'Negative of' 3 'is' d.3 +say 'Negative of' 7 'is' d.7 say -say 'Special indices...' -e.cat='civet'; say 'e.cat =' e.cat -a1='dog'; e.a1='pitbull' -a2=a1; say 'e.'a2 '=' e.a2 -a1='x.y.z'; e.a1='periods' -a2=a1; say 'e.'a2 '=' e.a2 -a1='x y z'; e.a1='spaces' -a2=a1; say 'e.'a2 '=' e.a2 -a1='└┴┬├─┼'; e.a1='specials' -a2=a1; say 'e.'a2 '=' e.a2 +say 'More dimensions...' +e.=0 +do i = 1 to 3 + do j = 1 to 3 + e.i.j=i*j + end +end +say '1x2 is' e.1.2 +say '3x2 is' e.3.2 +say +call SysDumpVariables say say 'Element has no value...' signal off novalue @@ -64,4 +67,11 @@ procedure expose a. arg xx return a.xx +Library: +say 'Library...' +call RxFuncAdd 'SysLoadFuncs','RegUtil','SysLoadFuncs' +call SysLoadFuncs +say +return + include Abend diff --git a/Task/Arrays/Unicon/arrays-1.unicon b/Task/Arrays/Unicon/arrays-1.unicon new file mode 100644 index 0000000000..36bcabe0b8 --- /dev/null +++ b/Task/Arrays/Unicon/arrays-1.unicon @@ -0,0 +1 @@ +l := [: !&input :] # build a list of the lines read from standard input diff --git a/Task/Arrays/Unicon/arrays-2.unicon b/Task/Arrays/Unicon/arrays-2.unicon new file mode 100644 index 0000000000..b375465980 --- /dev/null +++ b/Task/Arrays/Unicon/arrays-2.unicon @@ -0,0 +1,6 @@ +procedure main() + L := [: 1 to 5:] + delete(L,4) + insert(L,2,"hello") + every write(!L) +end diff --git a/Task/Arrays/Unicon/arrays-3.unicon b/Task/Arrays/Unicon/arrays-3.unicon new file mode 100644 index 0000000000..856291bbb5 --- /dev/null +++ b/Task/Arrays/Unicon/arrays-3.unicon @@ -0,0 +1,3 @@ + L := list(5,0) + i := 0 + every !L := (i+:=1) diff --git a/Task/Arrays/Zig/arrays-1.zig b/Task/Arrays/Zig/arrays-1.zig new file mode 100644 index 0000000000..43a97f2473 --- /dev/null +++ b/Task/Arrays/Zig/arrays-1.zig @@ -0,0 +1,32 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + // array literal + const array1 = [9]i32{ 0, 1, 1, 2, 3, 5, 7, 12, 21 }; + + // infer the size of the array + const array2 = [_]i32{ 0, 1, 1, 2, 3, 5, 7, 12, 21 }; + + // alternative initialization using result location + const array3: [9]i32 = .{ 0, 1, 1, 2, 3, 5, 7, 12, 21 }; + + // initialize an array with zeros using array multiplication + var array4 = [_]i32{0} ** 5; // array length: 5 + + // assign elements to an array (must be declared as a variable) + array4[0] = -12; + array4[2] = 345; + array4[4] = -6; + + // retieve elements from an array + try stdout.print("{d}, ", .{array4[0]}); + try stdout.print("{d}, ", .{array4[1]}); + try stdout.print("{d}, ", .{array4[2]}); + try stdout.print("{d}, ", .{array4[3]}); + try stdout.print("{d}\n", .{array4[4]}); + + // unused constants must be discarded + _ = array1; _ = array2; _ = array3; +} diff --git a/Task/Arrays/Zig/arrays-2.zig b/Task/Arrays/Zig/arrays-2.zig new file mode 100644 index 0000000000..474029db3b --- /dev/null +++ b/Task/Arrays/Zig/arrays-2.zig @@ -0,0 +1,21 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + // ArrayLists are initialized in the heap + var array = std.ArrayList(i32).init(allocator); + defer array.deinit(); + + // pushing elements to an ArrayList + try array.append(-12); + try array.append(345); + try array.append(-7); + + // retrieving elements from an ArrayList + try stdout.print("{d}, ", .{array.items[0]}); + try stdout.print("{d}, ", .{array.items[1]}); + try stdout.print("{d}\n", .{array.items[2]}); +} diff --git a/Task/Ascending-primes/ArkScript/ascending-primes.ark b/Task/Ascending-primes/ArkScript/ascending-primes.ark new file mode 100644 index 0000000000..c5d1ce07ea --- /dev/null +++ b/Task/Ascending-primes/ArkScript/ascending-primes.ark @@ -0,0 +1,24 @@ +(import std.Math :sqrt :prime?) +(import std.List :iota) +(import std.String :join) +(import std.Range) + +(let ascending (fun (n f) { + (mut nums (iota 1 9)) + (mut i 0) + (mut matched []) + + (while (and (< (len matched) n) (< i (len nums))) { + (let val (@ nums i)) + (if (f val) + (append! matched val)) + + (mut r (range:range (+ 1 (mod val 10)) 10)) + (set r (range:map r (fun (k) (+ k (* 10 val))))) + (concat! nums r) + + (set i (+ 1 i)) }) + + matched })) + +(print (join (ascending 100 prime?) ", ")) diff --git a/Task/Ascending-primes/Pluto/ascending-primes.pluto b/Task/Ascending-primes/Pluto/ascending-primes.pluto new file mode 100644 index 0000000000..828f567f2f --- /dev/null +++ b/Task/Ascending-primes/Pluto/ascending-primes.pluto @@ -0,0 +1,24 @@ +require "map" +local int = require "int" +local fmt = require "fmt" + +local asc_primes = new set() -- avoids duplicates + +local function generate(first, cand, digits) + if digits == 0 then + if int.isprime(cand) then asc_primes:add(cand) end + return + end + local i = first + while i <= 9 do + local next = cand * 10 + i + generate(i + 1, next, digits - 1) + ++i + end +end + +for digits = 1, 9 do generate(1, 0, digits) end +asc_primes = asc_primes:keys() +asc_primes:sort() +print($"There are {#asc_primes} ascending primes, namely:") +fmt.tprint("%8d", asc_primes, 5) diff --git a/Task/Associative-array-Creation/ArkScript/associative-array-creation.ark b/Task/Associative-array-Creation/ArkScript/associative-array-creation.ark new file mode 100644 index 0000000000..32ff7c770a --- /dev/null +++ b/Task/Associative-array-Creation/ArkScript/associative-array-creation.ark @@ -0,0 +1,6 @@ +(import std.Dict) + +(let d (dict "key" "value" 5 12)) + +(print (dict:get d 5)) +(print (dict:get d "key")) diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-1.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-1.duckdb new file mode 100644 index 0000000000..1446b4df06 --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-1.duckdb @@ -0,0 +1,6 @@ +# Create a table to associate a key with 0 or more values +CREATE TABLE associative_array (KEY_COLUMN VARCHAR(10), VALUE_COLUMN VARCHAR(100)); +# Insert a Key Value pair +INSERT INTO associative_array (KEY_COLUMN, VALUE_COLUMN) VALUES ('KEY', 'VALUE'); +# Retrieve a key value pair +SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY'; diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-2.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-2.duckdb new file mode 100644 index 0000000000..b88868f2bd --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-2.duckdb @@ -0,0 +1,5 @@ +CREATE TABLE associative_array (KEY_COLUMN VARCHAR, VALUE_COLUMN VARCHAR); +# Insert a Key Value pair +INSERT INTO associative_array VALUES ('KEY', 'VALUE'); +# Retrieve a key value pair +SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY'; diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-3.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-3.duckdb new file mode 100644 index 0000000000..ce18cbb28a --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-3.duckdb @@ -0,0 +1 @@ +CREATE TABLE aa (KEY_COLUMN VARCHAR UNIQUE NOT NULL, VALUE_COLUMN VARCHAR NOT NULL); diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-4.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-4.duckdb new file mode 100644 index 0000000000..8c2a94853a --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-4.duckdb @@ -0,0 +1,3 @@ +INSERT into aa VALUES ('k', 1), ('l', 2); +from aa; +INSERT into aa VALUES ('k', 3); diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-5.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-5.duckdb new file mode 100644 index 0000000000..04cd514a5c --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-5.duckdb @@ -0,0 +1 @@ +SELECT aa FROM aa LIMIT 1; diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-6.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-6.duckdb new file mode 100644 index 0000000000..3e09d635b1 --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-6.duckdb @@ -0,0 +1 @@ +select unnest({'KEY_COLUMN': 'k', 'VALUE_COLUMN': 1}); diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-7.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-7.duckdb new file mode 100644 index 0000000000..7e94667264 --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-7.duckdb @@ -0,0 +1 @@ +SELECT info.* FROM (SELECT {'a': 1, 'b': 2 } as info); diff --git a/Task/Associative-array-Creation/DuckDB/associative-array-creation-8.duckdb b/Task/Associative-array-Creation/DuckDB/associative-array-creation-8.duckdb new file mode 100644 index 0000000000..c16b5ea5fd --- /dev/null +++ b/Task/Associative-array-Creation/DuckDB/associative-array-creation-8.duckdb @@ -0,0 +1 @@ +SELECT '{"a": 1, "A": 2}'::JSON as j; diff --git a/Task/Associative-array-Creation/Haxe/associative-array-creation.haxe b/Task/Associative-array-Creation/Haxe/associative-array-creation.haxe new file mode 100644 index 0000000000..3c680e9c0a --- /dev/null +++ b/Task/Associative-array-Creation/Haxe/associative-array-creation.haxe @@ -0,0 +1,7 @@ +class Main { + static public function main() { + var map = [1 => "one", 2 => "two"]; + trace(map); + $type(map); + } +} diff --git a/Task/Associative-array-Creation/Pluto/associative-array-creation.pluto b/Task/Associative-array-Creation/Pluto/associative-array-creation.pluto new file mode 100644 index 0000000000..2fe4836919 --- /dev/null +++ b/Task/Associative-array-Creation/Pluto/associative-array-creation.pluto @@ -0,0 +1,25 @@ +-- Create a map of key, value pairs. +local planets = { + Mercury = 1, + Venus = 2, + Earth = 3, + Mars = 4, + Jupiter = 5, + Saturn = 6, + Uranus = 7, + Neptune = 8, + Pluto = 9 +} + +-- Print it +-- Note that order is not guaranteed. +for k, v in planets do print(k, v) end +print() + +-- Create a new one by inverting the key, value pairs. +local planets2 = planets:invert() + +-- Print it. +-- Now treated as an array with indices 1 to 9 +-- which guarantees order. +for k, v in planets2 do print($"{k} {v}") end diff --git a/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx b/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx deleted file mode 100644 index 908c889146..0000000000 --- a/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx +++ /dev/null @@ -1,10 +0,0 @@ -/* Rexx */ - -key0 = '0' -key1 = 'key0' - -stem. = '.' /* Initialize the associative array 'stem' to '.' */ -stem.key1 = 'value0' /* Set a specific key/value pair */ - -Say 'stem.key0= 'stem.key /* Display a value for a key that wasn't set */ -Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set */ diff --git a/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx b/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx deleted file mode 100644 index 6eef996e50..0000000000 --- a/Task/Associative-array-Creation/REXX/associative-array-creation-2.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program shows how to set/display values for an associative array.*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ The (below) two REXX statements aren't really necessary, but it │ - │ shows how to define any and all entries in a associative array so │ - │ that if a "key" is used that isn't defined, it can be displayed to │ - │ indicate such, or its value can be checked to determine if a │ - │ particular associative array element has been set (defined). │ - └────────────────────────────────────────────────────────────────────┘*/ -stateC.=' [not defined yet] ' /*sets any/all state capitols. */ -stateN.=' [not defined yet] ' /*sets any/all state names. */ -/*┌────────────────────────────────────────────────────────────────────┐ - │ In REXX, when a "key" is used, it's normally stored (internally) │ - │ as uppercase characters (as in the examples below). Actually, any │ - │ characters can be used, including blank(s) and non-displayable │ - │ characters (including '00'x, 'ff'x, commas, periods, quotes, ...).│ - └────────────────────────────────────────────────────────────────────┘*/ -stateC.ca='Sacramento'; stateN.ca='California' -stateC.nd='Bismarck' ; stateN.nd='North Dakota' -stateC.mn='St. Paul' ; stateN.mn='Minnesota' -stateC.dc='Washington'; stateN.dc='District of Columbia' -stateC.ri='Providence'; stateN.ri='Rhode Island and Providence Plantations' - -say 'capital of California is' stateC.ca -say 'capital of Oklahoma is' stateC.ok -yyy='RI' -say 'capital of' stateN.yyy "is" stateC.yyy - /*stick a fork in it, we're done.*/ diff --git a/Task/Associative-array-Creation/REXX/associative-array-creation.rexx b/Task/Associative-array-Creation/REXX/associative-array-creation.rexx new file mode 100644 index 0000000000..9aaddc689a --- /dev/null +++ b/Task/Associative-array-Creation/REXX/associative-array-creation.rexx @@ -0,0 +1,54 @@ +-- 8 Aug 2025 +include Settings + +say 'ASSOCIATIVE ARRAY: CREATION' +say version +say +say 'Basic examples...' +cap.='Unknown' +cap.be='Brussels' +cap.fr='Paris' +cap.uk='London' +call Capital 'BE' +call Capital 'UK' +call Capital 'NO' +day.='Unknown'; week.=day. +day.jan.2=2; week.jan.2=1 +day.mar.17=76; week.mar.17=12 +day.aug.7=219; week.aug.7=32 +call Calendar 'JAN',2 +call Calendar 'AUG',7 +call Calendar 'MAY',16 +say +say 'Keys can have any value...' +a.cat='civet'; say 'a.cat =' a.cat +a1='dog'; a.a1='pitbull' +a2=a1; say 'a.'a2 '=' a.a2 +a1='x.y.z'; a.a1='periods' +a2=a1; say 'a.'a2 '=' a.a2 +a1='x y z'; a.a1='spaces' +a2=a1; say 'a.'a2 '=' a.a2 +a1='ÀÁÂÃÄÅ'; a.a1='special characters' +a2=a1; say 'a.'a2 '=' a.a2 +say +if Pos('Regina',version) > 0 then + call Library +call SysDumpVariables +exit + +Capital: +arg country +say 'The capital of' country 'is' cap.country +return + +Calendar: +arg mm,dd +say mm dd 'is day no' day.mm.dd 'and week no' week.mm.dd +return + +Library: +call RxFuncAdd 'SysLoadFuncs','RegUtil','SysLoadFuncs' +call SysLoadFuncs +return + +include Abend diff --git a/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh b/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh deleted file mode 100644 index 895c6026b1..0000000000 --- a/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh +++ /dev/null @@ -1 +0,0 @@ -declare -A hash diff --git a/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-1.sh b/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation.sh similarity index 100% rename from Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-1.sh rename to Task/Associative-array-Creation/UNIX-Shell/associative-array-creation.sh diff --git a/Task/Associative-array-Creation/Zig/associative-array-creation-1.zig b/Task/Associative-array-Creation/Zig/associative-array-creation-1.zig new file mode 100644 index 0000000000..bd95d38c80 --- /dev/null +++ b/Task/Associative-array-Creation/Zig/associative-array-creation-1.zig @@ -0,0 +1,18 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var hash_map = std.StringHashMap(f64).init(allocator); + defer hash_map.deinit(); + + try hash_map.put("pi", 3.14159265); + try hash_map.put("e", 2.71828183); + try hash_map.put("phi", 1.61803399); + + try stdout.print("{d}\n", .{hash_map.get("pi").?}); + try stdout.print("{d}\n", .{hash_map.get("e").?}); + try stdout.print("{d}\n", .{hash_map.get("phi").?}); +} diff --git a/Task/Associative-array-Creation/Zig/associative-array-creation-2.zig b/Task/Associative-array-Creation/Zig/associative-array-creation-2.zig new file mode 100644 index 0000000000..b969bddec4 --- /dev/null +++ b/Task/Associative-array-Creation/Zig/associative-array-creation-2.zig @@ -0,0 +1,23 @@ +const std = @import("std"); + +const Entity = struct { + name: []const u8, + hp: i32, +}; + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var hash_map = std.AutoHashMap(u32, Entity).init(allocator); + defer hash_map.deinit(); + + try hash_map.put(123, .{ .name = "Zombie", .hp = 20 }); + try hash_map.put(456, .{ .name = "Bat", .hp = 6 }); + try hash_map.put(789, .{ .name = "Pig", .hp = 10 }); + + try stdout.print("{s:6}: HP = {d:3}\n", hash_map.get(123).?); + try stdout.print("{s:6}: HP = {d:3}\n", hash_map.get(456).?); + try stdout.print("{s:6}: HP = {d:3}\n", hash_map.get(789).?); +} diff --git a/Task/Associative-array-Iteration/ArkScript/associative-array-iteration.ark b/Task/Associative-array-Iteration/ArkScript/associative-array-iteration.ark new file mode 100644 index 0000000000..91c6a4bc56 --- /dev/null +++ b/Task/Associative-array-Iteration/ArkScript/associative-array-iteration.ark @@ -0,0 +1,9 @@ +(import std.Dict) + +(let d (dict + "key1" "value1" + "key2" "value2")) + +(print (dict:entries d)) +(print (dict:keys d)) +(print (dict:values d)) diff --git a/Task/Associative-array-Iteration/DuckDB/associative-array-iteration.duckdb b/Task/Associative-array-Iteration/DuckDB/associative-array-iteration.duckdb new file mode 100644 index 0000000000..0b25cd2111 --- /dev/null +++ b/Task/Associative-array-Iteration/DuckDB/associative-array-iteration.duckdb @@ -0,0 +1,108 @@ +### MAPs + +# Since the keys of a JSON object must be strings, we'll use as an +# example of a MAP one which has integer keys: + +D create or replace macro amap() as (SELECT MAP( [1,2,3], ['hello', 'world', '!'])); +D select amap() "A Map"; +┌─────────────────────────┐ +│ A Map │ +│ map(integer, varchar) │ +├─────────────────────────┤ +│ {1=hello, 2=world, 3=!} │ +└─────────────────────────┘ + +# Iterating over the keys: + +D select unnest(map_keys(amap())) as key; +┌───────┐ +│ key │ +│ int32 │ +├───────┤ +│ 1 │ +│ 2 │ +│ 3 │ +└───────┘ + +# Iterating over the values: +D select unnest(map_values(amap())) as value; +┌─────────┐ +│ value │ +│ varchar │ +├─────────┤ +│ hello │ +│ world │ +│ ! │ +└─────────┘ + +# One way to generate the key-value pairs is as follows: +D select unnest(map_keys(amap())) as key, unnest(map_values(amap())) as value; +┌───────┬─────────┐ +│ key │ value │ +│ int32 │ varchar │ +├───────┼─────────┤ +│ 1 │ hello │ +│ 2 │ world │ +│ 3 │ ! │ +└───────┴─────────┘ + +# ... or avoiding calling amap() twice: + +D select unnest(map_keys(m)) as key, unnest(map_values(m)) as value + from (select amap() m); +┌───────┬─────────┐ +│ key │ value │ +│ int32 │ varchar │ +├───────┼─────────┤ +│ 1 │ hello │ +│ 2 │ world │ +│ 3 │ ! │ +└───────┴─────────┘ + +### JSON objects + +# For simplicity, we'll the JSON entity `amap()::JSON` as an example object: + +D select amap()::JSON as j; +┌───────────────────────────────────┐ +│ j │ +│ json │ +├───────────────────────────────────┤ +│ {"1":"hello","2":"world","3":"!"} │ +└───────────────────────────────────┘ + +# To find the keys of a JSON object as a list, +# whence one can use iteration over lists: + +D select json_keys(amap()::JSON) as keys; +┌───────────┐ +│ keys │ +│ varchar[] │ +├───────────┤ +│ [1, 2, 3] │ +└───────────┘ + +# Similarly, to find the values in a JSON object as a list: + +D select list_transform( json_keys(j), k -> (j->>k) ) as list + from (select amap()::JSON as j); +┌───────────────────┐ +│ list │ +│ varchar[] │ +├───────────────────┤ +│ [hello, world, !] │ +└───────────────────┘ + +# Show the key-value pairs as a table: +D select unnest(json_keys(j)) as key, + unnest(list_transform(json_keys(j), k -> (j->>k))) as value + from (select amap()::JSON as j); + +┌─────────┬─────────┐ +│ key │ value │ +│ varchar │ varchar │ +├─────────┼─────────┤ +│ 1 │ hello │ +│ 2 │ world │ +│ 3 │ ! │ +└─────────┴─────────┘ diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena deleted file mode 100644 index 1190fcb3c7..0000000000 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration-1.elena +++ /dev/null @@ -1,18 +0,0 @@ -import system'collections; -import system'routines; -import extensions; - -public program() -{ - // 1. Create - var map := Dictionary.new(); - map["key"] := "foox"; - map["key"] := "foo"; - map["key2"]:= "foo2"; - map["key3"]:= "foo3"; - map["key4"]:= "foo4"; - - // Enumerate - map.forEach: - (keyValue){ console.printLine(keyValue.Key," : ",keyValue.Value) } -} diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration-2.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena similarity index 100% rename from Task/Associative-array-Iteration/Elena/associative-array-iteration-2.elena rename to Task/Associative-array-Iteration/Elena/associative-array-iteration.elena diff --git a/Task/Associative-array-Iteration/Haxe/associative-array-iteration.haxe b/Task/Associative-array-Iteration/Haxe/associative-array-iteration.haxe new file mode 100644 index 0000000000..ff94ad47ff --- /dev/null +++ b/Task/Associative-array-Iteration/Haxe/associative-array-iteration.haxe @@ -0,0 +1,18 @@ +class Main { + static public function main() { + var map = [1 => "one", 2 => "two"]; + + // key and value + for (key => value in map) { + trace(key + " " + value); + } + + // keys only + for (key in map.keys()) + trace(key); + + // values only + for (value in map) + trace(value); + } +} diff --git a/Task/Associative-array-Iteration/Pluto/associative-array-iteration.pluto b/Task/Associative-array-Iteration/Pluto/associative-array-iteration.pluto new file mode 100644 index 0000000000..89f8ff1597 --- /dev/null +++ b/Task/Associative-array-Iteration/Pluto/associative-array-iteration.pluto @@ -0,0 +1,19 @@ +-- Create a new map with four entries. +local capitals = { + Greece = "Athens", + Sweden = "Stockholm", + Peru = "Lima", + Uruguay = "Monevideo" +} + +-- Iterate through the map and print out the key/value pairs. +for k, v in capitals do print(k, v) end +print() + +-- Iterate though the map and print out just the keys. +for capitals:keys() as k do print(k) end +print() + +-- Iterate though the map and print out just the values. +for capitals:values() as v do print(v) end +print() diff --git a/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx b/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx index 5fbb924302..3e3f1bf670 100644 --- a/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx +++ b/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx @@ -1,58 +1,72 @@ -/*REXX program demonstrates how to set and display values for an associative array. */ -/*╔════════════════════════════════════════════════════════════════════════════════════╗ - ║ The (below) two REXX statements aren't really necessary, but it shows how to ║ - ║ define any and all entries in a associative array so that if a "key" is used that ║ - ║ isn't defined, it can be displayed to indicate such, or its value can be checked ║ - ║ to determine if a particular associative array element has been set (defined). ║ - ╚════════════════════════════════════════════════════════════════════════════════════╝*/ -stateF.= ' [not defined yet] ' /*sets any/all state former capitals.*/ -stateN.= ' [not defined yet] ' /*sets any/all state names. */ -w = 0 /*the maximum length of a state name.*/ -stateL = -/*╔════════════════════════════════════════════════════════════════════════════════════╗ - ║ The list of states (empty as of now). It's convenient to have them in alphabetic ║ - ║ order; they'll be listed in the order as they are in the REXX program below). ║ - ║ In REXX, when a key is used (for a stemmed array, as they are called in REXX), ║ - ║ and the key isn't assigned a value, the key's name is stored (internally) as ║ - ║ uppercase (Latin) characters (as in the examples below. If the key has a ║ - ║ a value, the key's value is used as is (i.e.: no upper translation is performed).║ - ║ Actually, any characters can be used, including blank(s) and non─displayable ║ - ║ characters (including '00'x, 'ff'x, commas, periods, quotes, ···). ║ - ╚════════════════════════════════════════════════════════════════════════════════════╝*/ -call setSC 'al', "Alabama" , 'Tuscaloosa' -call setSC 'ca', "California" , 'Benicia' -call setSC 'co', "Colorado" , 'Denver City' -call setSC 'ct', "Connecticut" , 'Hartford and New Haven (jointly)' -call setSC 'de', "Delaware" , 'New-Castle' -call setSC 'ga', "Georgia" , 'Milledgeville' -call setSC 'il', "Illinois" , 'Vandalia' -call setSC 'in', "Indiana" , 'Corydon' -call setSC 'ia', "Iowa" , 'Iowa City' -call setSC 'la', "Louisiana" , 'New Orleans' -call setSC 'me', "Maine" , 'Portland' -call setSC 'mi', "Michigan" , 'Detroit' -call setSC 'ms', "Mississippi" , 'Natchez' -call setSC 'mo', "Missouri" , 'Saint Charles' -call setSC 'mt', "Montana" , 'Virginia City' -call setSC 'ne', "Nebraska" , 'Lancaster' -call setSC 'nh', "New Hampshire" , 'Exeter' -call setSC 'ny', "New York" , 'New York' -call setSC 'nc', "North Carolina" , 'Fayetteville' -call setSC 'oh', "Ohio" , 'Chillicothe' -call setSC 'ok', "Oklahoma" , 'Guthrie' -call setSC 'pa', "Pennsylvania" , 'Lancaster' -call setSC 'sc', "South Carolina" , 'Charlestown' -call setSC 'tn', "Tennessee" , 'Murfreesboro' -call setSC 'vt', "Vermont" , 'Windsor' +-- 8 Aug 2025 +include Settings - do j=1 for words(stateL) /*show all capitals that were defined. */ - $= word(stateL, j) /*get the next (USA) state in the list.*/ - say 'the former capital of ('$") " left(stateN.$, w) " was " stateC.$ - end /*j*/ /* [↑] show states that were defined.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -setSC: parse arg code,name,cap; upper code /*get code, name & cap.; uppercase code*/ - stateL= stateL code /*keep a list of all the US state codes*/ - stateN.code= name; w= max(w,length(name)) /*define the state's name; max width. */ - stateC.code= cap /* " " " code to the capital*/ - return /*return to invoker, SETSC is finished.*/ +say 'ASSOCIATIVE ARRAY: ITERATION' +say version +say +list=''; arra.=''; w=0 +-- States with former capitals: key, name, capital +call SetStateCap 'al','Alabama','Tuscaloosa' +call SetStateCap 'ca','California','Benicia' +call SetStateCap 'co','Colorado','Denver City' +call SetStateCap 'ct','Connecticut','Hartford and New Haven' +call SetStateCap 'de','Delaware','New-Castle' +call SetStateCap 'ga','Georgia','Milledgeville' +call SetStateCap 'il','Illinois','Vandalia' +call SetStateCap 'in','Indiana','Corydon' +call SetStateCap 'ia','Iowa','Iowa City' +call SetStateCap 'la','Louisiana','New Orleans' +call SetStateCap 'me','Maine','Portland' +call SetStateCap 'mi','Michigan','Detroit' +call SetStateCap 'ms','Mississippi','Natchez' +call SetStateCap 'mo','Missouri','Saint Charles' +call SetStateCap 'mt','Montana','Virginia City' +call SetStateCap 'ne','Nebraska','Lancaster' +call SetStateCap 'nh','New Hampshire','Exeter' +call SetStateCap 'ny','New York','New York' +call SetStateCap 'nc','North Carolina','Fayetteville' +call SetStateCap 'oh','Ohio','Chillicothe' +call SetStateCap 'ok','Oklahoma','Guthrie' +call SetStateCap 'pa','Pennsylvania','Lancaster' +call SetStateCap 'sc','South Carolina','Charlestown' +call SetStateCap 'tn','Tennessee','Murfreesboro' +call SetStateCap 'vt','Vermont','Windsor' +arra.0=w +-- Loop through list +say 'Using a list...' +do w = 1 to words(list) + a=Word(list,w) + say 'The former capital of' stna.a '('a')' 'was' stca.a +end +say +-- Loop through aux array...' +say 'Using an array...' +do w = 1 to arra.0 + a=arra.w + say 'The former capital of' stna.a '('a')' 'was' stca.a +end +say +-- Show all vars +say 'Variables...' +if pos('Regina',version) > 0 then + call Library +call SysDumpVariables +exit + +SetStateCap: +parse arg code,name,cap +code=Upper(code) +-- Next row in associative array +stna.code=name; stca.code=cap +-- Track keys in a list +list=list code +-- Track keys in an array +w=w+1; arra.w=code +return + +Library: +call RxFuncAdd 'SysLoadFuncs','RegUtil','SysLoadFuncs' +call SysLoadFuncs +return + +include Abend diff --git a/Task/Associative-array-Iteration/TAV/associative-array-iteration.tav b/Task/Associative-array-Iteration/TAV/associative-array-iteration.tav new file mode 100644 index 0000000000..623ffbb902 --- /dev/null +++ b/Task/Associative-array-Iteration/TAV/associative-array-iteration.tav @@ -0,0 +1,24 @@ +main(params):+ + mm =: 'a' -> 1, 'b' -> 2, 'c' -> 3 + mm =: tuple mm as map + \ iterate over the pairs, order undefined + ?# t =: map mm give pairs + print t.1 _ '->' _ t.2 _ ' ' nonl + print '' + \ iterate over the keys + ?# k =: map mm give keys + print k, ' ' nonl + print '' + x =: mm{'c'} \ changes order by access + \ iterate over the values only + ?# v =: map mm give values + print v, ' ' nonl + print '' + \ ordered keys: + ?# k =: map mm give keys ascending + print k, ' ' nonl + print '' + \ ordered keys: + ?# k =: map mm give keys descending + print k _ '->' _ mm{k} _ ' ' nonl + print '' diff --git a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-1.tcl b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-1.tcl index 191b6d0205..33e625a459 100644 --- a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-1.tcl +++ b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-1.tcl @@ -1,16 +1,7 @@ -array set myAry { - # list items here... +array set family { + surname Miller + father John + mother Helen + daughter [list Jane Karen] + son Donald } - -# Iterate over keys and values -foreach {key value} [array get myAry] { - puts "$key -> $value" -} - -# Iterate over just keys -foreach key [array names myAry] { - puts "key = $key" -} - -# There is nothing for directly iterating over just the values -# Use the keys+values version and ignore the keys diff --git a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-2.tcl b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-2.tcl index 0c64d363c4..16bf134315 100644 --- a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-2.tcl +++ b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-2.tcl @@ -1,16 +1,3 @@ -set myDict [dict create ...]; # Make the dictionary - -# Iterate over keys and values -dict for {key value} $myDict { - puts "$key -> $value" -} - -# Iterate over keys -foreach key [dict keys $myDict] { - puts "key = $key" -} - -# Iterate over values -foreach value [dict values $myDict] { - puts "value = $value" -} +# "John Miller" +set dad "$family(father) $family(lastname)" +set second_daughter [lindex $family(daughter) 1] diff --git a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-3.tcl b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-3.tcl new file mode 100644 index 0000000000..68b3bbd537 --- /dev/null +++ b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-3.tcl @@ -0,0 +1,2 @@ +set l [array get family] +# {surname Miller father John mother Helen daughter {Jane Karen} son Donald} diff --git a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-4.tcl b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-4.tcl new file mode 100644 index 0000000000..191b6d0205 --- /dev/null +++ b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-4.tcl @@ -0,0 +1,16 @@ +array set myAry { + # list items here... +} + +# Iterate over keys and values +foreach {key value} [array get myAry] { + puts "$key -> $value" +} + +# Iterate over just keys +foreach key [array names myAry] { + puts "key = $key" +} + +# There is nothing for directly iterating over just the values +# Use the keys+values version and ignore the keys diff --git a/Task/Associative-array-Iteration/Tcl/associative-array-iteration-5.tcl b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-5.tcl new file mode 100644 index 0000000000..0c64d363c4 --- /dev/null +++ b/Task/Associative-array-Iteration/Tcl/associative-array-iteration-5.tcl @@ -0,0 +1,16 @@ +set myDict [dict create ...]; # Make the dictionary + +# Iterate over keys and values +dict for {key value} $myDict { + puts "$key -> $value" +} + +# Iterate over keys +foreach key [dict keys $myDict] { + puts "key = $key" +} + +# Iterate over values +foreach value [dict values $myDict] { + puts "value = $value" +} diff --git a/Task/Associative-array-Iteration/Zig/associative-array-iteration-1.zig b/Task/Associative-array-Iteration/Zig/associative-array-iteration-1.zig new file mode 100644 index 0000000000..90daa4bc29 --- /dev/null +++ b/Task/Associative-array-Iteration/Zig/associative-array-iteration-1.zig @@ -0,0 +1,30 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var hash_map = std.StringArrayHashMap(f32).init(allocator); + defer hash_map.deinit(); + + try hash_map.put("B3", 246.94); + try hash_map.put("C4", 261.63); + try hash_map.put("C#4", 277.18); + + for (hash_map.keys()) |key| { + try stdout.print("{s}\n", .{key}); + } + + for (hash_map.values()) |value| { + try stdout.print("{d}\n", .{value}); + } + + var iter = hash_map.iterator(); + while (iter.next()) |entry| { + const key = entry.key_ptr.*; + const value = entry.value_ptr.*; + + try stdout.print("{s}, {d}\n", .{key, value}); + } +} diff --git a/Task/Associative-array-Iteration/Zig/associative-array-iteration-2.zig b/Task/Associative-array-Iteration/Zig/associative-array-iteration-2.zig new file mode 100644 index 0000000000..be3b2677d1 --- /dev/null +++ b/Task/Associative-array-Iteration/Zig/associative-array-iteration-2.zig @@ -0,0 +1,30 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var hash_map = std.AutoArrayHashMap(u8, []const u8).init(allocator); + defer hash_map.deinit(); + + try hash_map.put('A', "Alpha"); + try hash_map.put('B', "Bravo"); + try hash_map.put('C', "Charlie"); + + for (hash_map.keys()) |key| { + try stdout.print("{c}\n", .{key}); + } + + for (hash_map.values()) |value| { + try stdout.print("{s}\n", .{value}); + } + + var iter = hash_map.iterator(); + while (iter.next()) |entry| { + const key = entry.key_ptr.*; + const value = entry.value_ptr.*; + + try stdout.print("{c}, {s}\n", .{key, value}); + } +} diff --git a/Task/Associative-array-Merging/DuckDB/associative-array-merging-1.duckdb b/Task/Associative-array-Merging/DuckDB/associative-array-merging-1.duckdb new file mode 100644 index 0000000000..be9c95b7eb --- /dev/null +++ b/Task/Associative-array-Merging/DuckDB/associative-array-merging-1.duckdb @@ -0,0 +1,4 @@ +set variable base= { 'name': 'Rocket Skates', 'price': 12.75, 'color':'yellow'}::JSON; +set variable update = { 'price': 15.25, 'color': 'red', 'year': 1974 }::JSON; + +select json_merge_patch(getvariable('base'),getvariable('update')) as add; diff --git a/Task/Associative-array-Merging/DuckDB/associative-array-merging-2.duckdb b/Task/Associative-array-Merging/DuckDB/associative-array-merging-2.duckdb new file mode 100644 index 0000000000..3dd23a19a1 --- /dev/null +++ b/Task/Associative-array-Merging/DuckDB/associative-array-merging-2.duckdb @@ -0,0 +1,11 @@ +create or replace function map_merge_patch(a,b) as ( + with keys_t as ( + select (map_keys(a) + map_keys(b)).list_distinct() as keys + ), + values_t as ( + select list_transform(keys, key -> coalesce(b[key][1],a[key][1])) as values + from keys_t) + select MAP(keys, values) from keys_t, values_t +); + +select map_merge_patch( MAP([1,2],[1,2]), MAP([1,3],[10,30])) as add; diff --git a/Task/Associative-array-Merging/DuckDB/associative-array-merging-3.duckdb b/Task/Associative-array-Merging/DuckDB/associative-array-merging-3.duckdb new file mode 100644 index 0000000000..60dfac34ba --- /dev/null +++ b/Task/Associative-array-Merging/DuckDB/associative-array-merging-3.duckdb @@ -0,0 +1,11 @@ +create or replace function struct_merge_patch(base, update) as ( + + with cte as ( + from (select unnest(update)) + positional join + (select COLUMNS(x -> x not in json_keys(update::JSON)) from (select unnest(base))) + ) + select cte from cte +); + +select struct_merge_patch( getvariable('base'), getvariable('update')) as merged; diff --git a/Task/Associative-array-Merging/Fortran/associative-array-merging.f b/Task/Associative-array-Merging/Fortran/associative-array-merging.f new file mode 100644 index 0000000000..294f442506 --- /dev/null +++ b/Task/Associative-array-Merging/Fortran/associative-array-merging.f @@ -0,0 +1,94 @@ +module assoc_array_mod + implicit none + private + public :: KeyValue, merge_assoc_arrays + + ! Derived type for key-value pairs + type :: KeyValue + character(len=:), allocatable :: key + character(len=:), allocatable :: value + end type KeyValue + +contains + + ! Function to merge two associative arrays + function merge_assoc_arrays(base, update) result(merged) + type(KeyValue), intent(in) :: base(:), update(:) + type(KeyValue), allocatable :: merged(:) + type(KeyValue), allocatable :: temp(:) + integer :: base_size, update_size, i, j, k, merged_size + logical :: key_exists + + base_size = size(base) + update_size = size(update) + + ! Allocate temporary array to hold all possible keys (worst case: no overlap) + allocate(temp(base_size + update_size)) + merged_size = 0 + + ! Add all keys from update array (update takes precedence) + do i = 1, update_size + merged_size = merged_size + 1 + temp(merged_size)%key = update(i)%key + temp(merged_size)%value = update(i)%value + end do + + ! Add keys from base array that are not in update + do i = 1, base_size + key_exists = .false. + do j = 1, update_size + if (base(i)%key == update(j)%key) then + key_exists = .true. + exit + end if + end do + if (.not. key_exists) then + merged_size = merged_size + 1 + temp(merged_size)%key = base(i)%key + temp(merged_size)%value = base(i)%value + end if + end do + + ! Allocate merged array with exact size + allocate(merged(merged_size)) + do i = 1, merged_size + merged(i)%key = temp(i)%key + merged(i)%value = temp(i)%value + end do + + ! Clean up temporary array + deallocate(temp) + end function merge_assoc_arrays + +end module assoc_array_mod + +program main + use assoc_array_mod + implicit none + type(KeyValue), allocatable :: base(:), update(:), merged(:) + integer :: i + + ! Initialize base associative array + allocate(base(3)) + base(1) = KeyValue("name", "Rocket Skates") + base(2) = KeyValue("price", "12.75") + base(3) = KeyValue("color", "yellow") + + ! Initialize update associative array + allocate(update(3)) + update(1) = KeyValue("price", "15.25") + update(2) = KeyValue("color", "red") + update(3) = KeyValue("year", "1974") + + ! Merge the arrays + merged = merge_assoc_arrays(base, update) + + ! Print the merged array + print *, "Merged associative array:" + do i = 1, size(merged) + print *, "Key: ", merged(i)%key, ", Value: ", merged(i)%value + end do + + ! Clean up + deallocate(base, update, merged) +end program main diff --git a/Task/Associative-array-Merging/Pluto/associative-array-merging.pluto b/Task/Associative-array-Merging/Pluto/associative-array-merging.pluto new file mode 100644 index 0000000000..cfa921a360 --- /dev/null +++ b/Task/Associative-array-Merging/Pluto/associative-array-merging.pluto @@ -0,0 +1,11 @@ +local function merge_maps(m1, m2) + local m3 = {} + for m1:keys() as key do m3[key] = m1[key] end + for m2:keys() as key do m3[key] = m2[key] end + return m3 +end + +local base = {name = "Rocket Skates", price = 12.75, color = "yellow"} +local update = {price = 15.25, color = "red", year = 1974} +local merged = merge_maps(base, update) +for k, v in merged do print(k, v) end diff --git a/Task/Associative-array-Merging/REXX/associative-array-merging.rexx b/Task/Associative-array-Merging/REXX/associative-array-merging.rexx index d13ae1dcfd..40cf80021f 100644 --- a/Task/Associative-array-Merging/REXX/associative-array-merging.rexx +++ b/Task/Associative-array-Merging/REXX/associative-array-merging.rexx @@ -1,33 +1,78 @@ -/*REXX program merges two associative arrays (requiring an external list of indices). */ -$.= /*define default value(s) for arrays. */ -@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/ -call defAA 'base', "name Rocket Skates", 'price 12.75', "color yellow" -call defAA 'update', "price 15.25", "color red", 'year 1974' -call show 'base' -call show 'update' -call show 'new' -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -defAA: procedure expose $. @.; parse arg AAn; new= 'new' /*get AA name; set NEW.*/ - do j=2 to arg(); parse value arg(j) with key val /*obtain key and value.*/ - $.AAn.key= val /*assign a value to a key for AAn. */ - if wordpos(key, $.AAN.?keys)==0 then $.AAn.?keys= $.AAn.?keys key - /* [↑] add to key list if not in list.*/ - $.new.key= val /*assign a value to a key for "new".*/ - if wordpos(key, $.new.?keys)==0 then $.new.?keys= $.new.?keys key - /* [↑] add to key list if not in list.*/ - @.wKey= max(@.wKey, length(key) ) /*find max width of a name of a key. */ - @.wVal= max(@.wVal, length(val) ) /* " " " " " " " " value.*/ - @.wAA = max(@.wAAn, length(AAn) ) /* " " " " " " " array.*/ - end /*j*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: procedure expose $. @.; parse arg AAn; say; _= '═' /*set title char.*/ - do j=1 for words($.AAn.?keys) /*process keys. */ - if j==1 then say center('associate array', @.wAAn, _) , - center("key" , @.wKey, _) , - center('value' , @.wVal + 2, _) - key= word($.AAn.?keys, j) /*get the name of a key.*/ - say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/ - end /*j*/ - return +-- 8 Aug 2025 +include Settings + +say 'ASSOCIATIVE ARRAY: MERGE' +say version +say +call CreateBase +call ShowBase 'Original' +call CreateUpdate +call ShowUpdate +call MergeBaseUpdate +call ShowBase 'Merged' +exit + +CreateBase: +base=''; base.='' +call ProcBase 'name','Rocket Skates' +call ProcBase 'price',12.75 +call ProcBase 'color','Yellow' +return + +ShowBase: +parse arg xx +sep=Copies('-',20) +say 'Base array' xx +say sep +say 'Key value' +say sep +do i = 1 to Words(base) + key=Word(base,i) + say Left(key,6) base.key +end +say sep +say +return + +CreateUpdate: +upda=''; upda.='' +call ProcUpdate 'price',15.25 +call ProcUpdate 'color','Red' +call ProcUpdate 'year',1974 +return + +ShowUpdate: +say 'Update array' +say sep +say 'Key value' +say sep +do i = 1 to Words(upda) + key=Word(upda,i) + say Left(key,6) upda.key +end +say sep +say +return + +MergeBaseUpdate: +do w = 1 to Words(upda) + key=Word(upda,w); val=upda.key + call ProcBase key,val +end +return + +ProcBase: +parse arg k,v +if WordPos(k,base) = 0 then + base=base k +base.k=v +return + +ProcUpdate: +parse arg k,v +if WordPos(k,upda) = 0 then + upda=upda k +upda.k=v +return + +include Abend diff --git a/Task/Attractive-numbers/Agena/attractive-numbers.agena b/Task/Attractive-numbers/Agena/attractive-numbers.agena new file mode 100644 index 0000000000..01fe38dcca --- /dev/null +++ b/Task/Attractive-numbers/Agena/attractive-numbers.agena @@ -0,0 +1,28 @@ +scope # find some attractive numbers - numbers whose prime factor counts are prime, n must be > 1 + + local constant maxNumber := 120; # maximum number we will consider + + printf( "The attractve numbers up to %d\n", maxNumber ); + local aCount := 0; + for i from 2 to maxNumber do + local v, fCount := i, 0; + while v mod 2 = 0 do + fCount +:= 1; + v \:= 2 + od; + for j from 3 to maxNumber by 2 while v > 1 do + while v > 1 and v mod j = 0 do + fCount +:= 1; + v \:= j + od + od; + if fCount > 0 then + if numtheory.isprime( fCount ) then + printf( " %3d", i ); + aCount +:= 1; + if aCount mod 20 = 0 then print() fi + fi + fi + od; + printf( "\nFound %d attractive numbers\n", aCount ) +end diff --git a/Task/Attractive-numbers/Lua/attractive-numbers.lua b/Task/Attractive-numbers/Lua/attractive-numbers.lua index 19f47fc858..fa18744307 100644 --- a/Task/Attractive-numbers/Lua/attractive-numbers.lua +++ b/Task/Attractive-numbers/Lua/attractive-numbers.lua @@ -11,11 +11,10 @@ end -- Compute the prime factors of n function factors (n) - local facList, divisor, count = {}, 1 + local facList, divisor = {}, 1 if n < 2 then return facList end while not isPrime(n) do while not isPrime(divisor) do divisor = divisor + 1 end - count = 0 while n % divisor == 0 do n = n / divisor table.insert(facList, divisor) @@ -28,6 +27,10 @@ function factors (n) end -- Main procedure +local count = 0 for i = 1, 120 do - if isPrime(#factors(i)) then io.write(i .. "\t") end + if isPrime(#factors(i)) then + count = count - 1 + io.write( string.format("%6d", i), ( count % 12 == 0 and "\n" or "" )) + end end diff --git a/Task/Attractive-numbers/Pluto/attractive-numbers.pluto b/Task/Attractive-numbers/Pluto/attractive-numbers.pluto new file mode 100644 index 0000000000..fad6286fed --- /dev/null +++ b/Task/Attractive-numbers/Pluto/attractive-numbers.pluto @@ -0,0 +1,40 @@ +do -- find some attractive numbers - numbers whose prime factor count is prime + + -- Returns true if x is prime, and false otherwise + function isPrime (x) + if x < 2 then return false end + if x < 4 then return true end + if x % 2 == 0 then return false end + for d = 3, math.sqrt(x), 2 do + if x % d == 0 then return false end + end + return true + end + + -- Compute the prime factors of n + function factors (n) + local facList, divisor = {}, 1 + if n > 1 then + while not isPrime(n) do + while not isPrime(divisor) do ++ divisor end + while n % divisor == 0 do + n //= divisor + facList:insert(divisor) + end + ++ divisor + if n == 1 then return facList end + end + facList:insert(n) + end + return facList + end + + -- Main procedure + local count = 0 + for i = 1, 120 do + if isPrime(#factors(i)) then + ++ count + io.write( string.format( "%6d", i ), if count % 12 == 0 then "\n" else "" end ) + end + end +end diff --git a/Task/Averages-Arithmetic-mean/Apple/averages-arithmetic-mean.apple b/Task/Averages-Arithmetic-mean/Apple/averages-arithmetic-mean.apple new file mode 100644 index 0000000000..02cf4807c8 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Apple/averages-arithmetic-mean.apple @@ -0,0 +1,2 @@ + > [(+)/x%ℝ(:x)] ⟨3,1,4,1,5,9⟩ +3.833333333333333 diff --git a/Task/Averages-Arithmetic-mean/DuckDB/averages-arithmetic-mean.duckdb b/Task/Averages-Arithmetic-mean/DuckDB/averages-arithmetic-mean.duckdb new file mode 100644 index 0000000000..f401cf4302 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/DuckDB/averages-arithmetic-mean.duckdb @@ -0,0 +1,3 @@ +create or replace function average(lst) as ( + list_sum(lst) / length(lst) +); diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index 11d1006f7a..7d2af43a0a 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -21,8 +21,8 @@ extension op public program() { - var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8}; - console.printLine( - "Arithmetic mean of {",array.asEnumerable(),"} is ", - array.average()).readChar() + var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8}; + Console.printLine( + "Arithmetic mean of {",array.asEnumerable(),"} is ", + array.average()).readChar() } diff --git a/Task/Averages-Arithmetic-mean/Pluto/averages-arithmetic-mean.pluto b/Task/Averages-Arithmetic-mean/Pluto/averages-arithmetic-mean.pluto new file mode 100644 index 0000000000..65b6a14afc --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Pluto/averages-arithmetic-mean.pluto @@ -0,0 +1,4 @@ +local function arithmetic_mean(a) return a:reduce(|sum, i| -> sum + i) / #a end + +local arrays = { {1, 2, 3, 4, 5}, {} } +for arrays as a do print(arithmetic_mean(a)) end diff --git a/Task/Averages-Mean-angle/DuckDB/averages-mean-angle.duckdb b/Task/Averages-Mean-angle/DuckDB/averages-mean-angle.duckdb new file mode 100644 index 0000000000..305fe03554 --- /dev/null +++ b/Task/Averages-Mean-angle/DuckDB/averages-mean-angle.duckdb @@ -0,0 +1,13 @@ +# Mean of given list of angles in degrees, to 7 decimal places +create or replace function mean_angle(lst) as ( + with angles as (select unnest(lst) as angle), + radians as (select (angle * pi() / 180) as alpha from angles), + trig as (select sin(alpha) as s, cos(alpha) as c from radians) + + select round(atan2( sum(s) / length(lst), sum(c) / length(lst) ) * 180 / pi(), 7) from trig +); + +select angles, mean_angle(angles) as mean from values + ([350, 10]), + ([90,180,270,360]), + ([10, 20, 30]) t(angles); diff --git a/Task/Averages-Mean-time-of-day/DuckDB/averages-mean-time-of-day.duckdb b/Task/Averages-Mean-time-of-day/DuckDB/averages-mean-time-of-day.duckdb new file mode 100644 index 0000000000..cfcd6745d2 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/DuckDB/averages-mean-time-of-day.duckdb @@ -0,0 +1,17 @@ +create or replace function mean_time(t1, t2) as ( + select if (diff >= 0, t1::TIME + INTERVAL (diff/2) seconds, + t1::TIME + INTERVAL ((86400 + diff)/2) seconds) + from + ( select datediff('seconds', t1::TIME, t2::TIME) as diff ) +); + +## Examples: +select times[1], times[2], mean_time(times[1], times[2]) as mean +from values + ( ['0:0:0', '12:0:0' ] ), + ( ['0:0:0', '24:0:0' ] ), + ( ['1:0:0', '1:0:0' ] ), + ( ['20:0:0', '4:0:0' ] ), + ( ['20:0:0', '4:0:2' ] ), + ( ['23:0:0', '23:0:0'] ) +t(times); diff --git a/Task/Averages-Mean-time-of-day/FutureBasic/averages-mean-time-of-day.basic b/Task/Averages-Mean-time-of-day/FutureBasic/averages-mean-time-of-day.basic new file mode 100644 index 0000000000..4e0717b789 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/FutureBasic/averages-mean-time-of-day.basic @@ -0,0 +1,70 @@ +// +// Averages/Mean time of day +// FutureBasic 7.0.34, August 2025 R.W +// +_angles = 1 //tag for MDA array + +// Our test data times +CFStringRef tm(4) = {@"Times",@"23:00:17", @"23:40:20", @"00:12:45", @"00:17:19"} + +// get average of angle sum +local fn MeanAngle( tag as Int ) as double + long count + double sinSum, cosSum + count = mda_count tag //count total including zeroeth element + sinSum = 0.0: cosSum = 0.0 + for long i = 1 to count - 1 //remove zero + sinSum += sin(mda tag(i) * PI / 180.0) + cosSum += cos(mda tag(i) * PI / 180.0) + next +end fn = fn atan2(sinSum / count, cosSum / count) * 180.0 / PI + +// Get seconds from time t format = "hh:mm:ss" +local fn timeToSecs(t As CFStringRef) as Int + Int hours, mins, secs + hours = IntVal(Left(t, 2)) + mins = IntVal(Mid(t, 3, 2)) + secs = IntVal(Right(t, 2)) +end fn = 3600 * hours + 60 * mins + secs + +// 1 second = 360/(24 * 3600) = 1/240th of a degree +local fn timeToDegrees(t as CFStringRef) as Double + Int secs + secs = fn timeToSecs(t) +end fn = secs/240.0 + +// convert degrees to time string +local fn degreesToTime(d As Double) as CFStringRef + Int hours, mins, secs + CFStringRef result,h,m,s, tmp + result = @"":h=@"":m=@"":s=@"":tmp = @"" + If d < 0 Then d = d + 360.0 + secs = d * 240.0 + hours = fix(secs / 3600) + tmp = mid(str(hours),1) + if hours < 10 then h = concat(@"0",tmp) else h = tmp + mins = secs % 3600 + secs = mins % 60 + tmp = mid(str(secs),1) + if secs < 10 then s = concat(@"0",tmp) else s = tmp + mins = fix(mins / 60) + tmp = mid(str(mins),1) + if mins < 10 then m = concat(@"0",tmp) else m = tmp + result = concat(result,h,@":",m,@":",s) +end fn = result + + +window 1 + +// load MDA array with time to degrees +// from test data +for Int x = 1 to 4 + mda _angles(x) = fn timeToDegrees(tm(x)) +next x + +double mean +mean = fn meanAngle(_angles) +print +print " Average time is: "; fn degreesToTime(mean) + +handleEvents diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index 8dd0572594..c5e03aa82e 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -33,8 +33,8 @@ public program() var a1 := new real[]{4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r}; var a2 := new real[]{4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r}; - console.printLine("median of (",a1.asEnumerable(),") is ",a1.Median); - console.printLine("median of (",a2.asEnumerable(),") is ",a2.Median); + Console.printLine("median of (",a1.asEnumerable(),") is ",a1.Median); + Console.printLine("median of (",a2.asEnumerable(),") is ",a2.Median); - console.readChar() + Console.readChar() } diff --git a/Task/Averages-Median/Pluto/averages-median.pluto b/Task/Averages-Median/Pluto/averages-median.pluto new file mode 100644 index 0000000000..76d20aff94 --- /dev/null +++ b/Task/Averages-Median/Pluto/averages-median.pluto @@ -0,0 +1,17 @@ +local function median(a) + local len = #a + if len == 0 then return nil end + local b = a:sorted() + local hlen = len // 2 + if len % 2 == 1 then return b[hlen + 1] end + return (b[hlen] + b[hlen + 1]) / 2.0 +end + +local arrays = { + {4, 2, 5, 3, 1}, + {9, 6, 8, 7}, + {2}, + {} +} + +for arrays as a do print(median(a)) end diff --git a/Task/Averages-Mode/DuckDB/averages-mode-1.duckdb b/Task/Averages-Mode/DuckDB/averages-mode-1.duckdb new file mode 100644 index 0000000000..b8f3ef6eda --- /dev/null +++ b/Task/Averages-Mode/DuckDB/averages-mode-1.duckdb @@ -0,0 +1,10 @@ +# lst should be a DuckDB list +create or replace function mode(lst) as ( + with cte as ( + SELECT number, COUNT(*) as frequency + FROM (SELECT unnest(lst) as number) + GROUP BY number + ORDER BY frequency DESC + LIMIT 1) + (select number from cte) -- signal that the result is scalar + ); diff --git a/Task/Averages-Mode/DuckDB/averages-mode-2.duckdb b/Task/Averages-Mode/DuckDB/averages-mode-2.duckdb new file mode 100644 index 0000000000..2787f7d621 --- /dev/null +++ b/Task/Averages-Mode/DuckDB/averages-mode-2.duckdb @@ -0,0 +1 @@ +select [1, 2, 2, 3, 3, 3, 4] as list, mode(list) as mode; diff --git a/Task/Averages-Mode/DuckDB/averages-mode-3.duckdb b/Task/Averages-Mode/DuckDB/averages-mode-3.duckdb new file mode 100644 index 0000000000..8158bc7e74 --- /dev/null +++ b/Task/Averages-Mode/DuckDB/averages-mode-3.duckdb @@ -0,0 +1,10 @@ +create or replace function modal_values(lst) as table ( + with cte as ( + SELECT number, COUNT(*) as frequency + FROM (SELECT unnest(lst) as number) + GROUP BY number ) + select number + from cte + where frequency = (SELECT MAX(frequency) FROM cte) + order by number + ); diff --git a/Task/Averages-Mode/DuckDB/averages-mode-4.duckdb b/Task/Averages-Mode/DuckDB/averages-mode-4.duckdb new file mode 100644 index 0000000000..104e77bdbb --- /dev/null +++ b/Task/Averages-Mode/DuckDB/averages-mode-4.duckdb @@ -0,0 +1 @@ +select median(n) as mode from modal_values( [1,1,1,2,2,2,3]) t(n); diff --git a/Task/Averages-Mode/DuckDB/averages-mode-5.duckdb b/Task/Averages-Mode/DuckDB/averages-mode-5.duckdb new file mode 100644 index 0000000000..095bcb6299 --- /dev/null +++ b/Task/Averages-Mode/DuckDB/averages-mode-5.duckdb @@ -0,0 +1,15 @@ +# Find the mode of a column named values in the named table +# by taking the median() of the modal values +create or replace function mode_of_column(TableName) as ( + with cte as ( + SELECT value, COUNT(*) as frequency + FROM query_table(TableName) + GROUP BY value + ), + modal_values as ( + SELECT value + from cte + where frequency = (SELECT MAX(frequency) FROM cte) + order by value + ) select median(value) from modal_values +); diff --git a/Task/Averages-Mode/DuckDB/averages-mode-6.duckdb b/Task/Averages-Mode/DuckDB/averages-mode-6.duckdb new file mode 100644 index 0000000000..819c128044 --- /dev/null +++ b/Task/Averages-Mode/DuckDB/averages-mode-6.duckdb @@ -0,0 +1,2 @@ +with cte as (select val as value from averages) + select mode_of_column('cte') as 'mode of val'; diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index f1fca32540..e0992d1b2f 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -29,7 +29,7 @@ public program() var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17}; var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"}; - console + Console .printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")") .printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")") .printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")") diff --git a/Task/Averages-Pythagorean-means/Apple/averages-pythagorean-means.apple b/Task/Averages-Pythagorean-means/Apple/averages-pythagorean-means.apple new file mode 100644 index 0000000000..a3ff60c36b --- /dev/null +++ b/Task/Averages-Pythagorean-means/Apple/averages-pythagorean-means.apple @@ -0,0 +1,12 @@ + > :store a [(+)/x%ℝ(:x)] + > :store g [((*)/x)**(⅟(ℝ(:x)))] + > :store h [⅟((+)/((1%)')x)] + + > :store x frange 1 10 10 + + > a x +5.5 + > g x +4.528728688116765 + > h x +0.34141715214740553 diff --git a/Task/Averages-Pythagorean-means/DuckDB/averages-pythagorean-means.duckdb b/Task/Averages-Pythagorean-means/DuckDB/averages-pythagorean-means.duckdb new file mode 100644 index 0000000000..b75db190c5 --- /dev/null +++ b/Task/Averages-Pythagorean-means/DuckDB/averages-pythagorean-means.duckdb @@ -0,0 +1,11 @@ +create or replace function average(lst) as ( + list_sum(lst) / length(lst) +); + +create or replace function list_geometric_mean(lst) as ( + list_product( list_transform(lst, x -> pow(x, 1/length(lst))) ) +); + +create or replace function list_harmonic_mean(lst) as ( + length(lst) / list_sum( list_transform(lst, x -> 1/x)) +); diff --git a/Task/Averages-Pythagorean-means/Pluto/averages-pythagorean-means.pluto b/Task/Averages-Pythagorean-means/Pluto/averages-pythagorean-means.pluto new file mode 100644 index 0000000000..903b1e2788 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Pluto/averages-pythagorean-means.pluto @@ -0,0 +1,11 @@ +local rng = range(1, 10) +local count = #rng +local A = rng:reduce(|acc, x| -> acc + x ) / count +local G = rng:reduce(|prod, x| -> prod * x, 1) ^ (1 / count) +local H = rng:reduce(|acc, x| -> acc + 1 / x) ^ (-1) * count + +print($"For the numbers \{{rng:min()}, {rng:max()}}:") +print($" Arithmetic mean = {A}") +print($" Geometric mean = {G}") +print($" Harmonic mean = {H}") +print($" A >= G >= H = {A >= G >= H}") diff --git a/Task/Averages-Root-mean-square/EasyLang/averages-root-mean-square.easy b/Task/Averages-Root-mean-square/EasyLang/averages-root-mean-square.easy index 50fec25962..744f7e1009 100644 --- a/Task/Averages-Root-mean-square/EasyLang/averages-root-mean-square.easy +++ b/Task/Averages-Root-mean-square/EasyLang/averages-root-mean-square.easy @@ -1,8 +1,5 @@ func rms v[] . - for v in v[] - sum += v * v - . + for v in v[] : sum += v * v return sqrt (sum / len v[]) . -v[] = [ 1 2 3 4 5 6 7 8 9 10 ] -print rms v[] +print rms [ 1 2 3 4 5 6 7 8 9 10 ] diff --git a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena index 66c1f5e9b3..d4ec3261bc 100644 --- a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena +++ b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena @@ -10,5 +10,5 @@ extension op public program() { - console.printLine(new Range(1, 10).RootMeanSquare) + Console.printLine(new Range(1, 10).RootMeanSquare) } diff --git a/Task/Averages-Root-mean-square/Pluto/averages-root-mean-square.pluto b/Task/Averages-Root-mean-square/Pluto/averages-root-mean-square.pluto new file mode 100644 index 0000000000..d54e29247b --- /dev/null +++ b/Task/Averages-Root-mean-square/Pluto/averages-root-mean-square.pluto @@ -0,0 +1,7 @@ +local function rms(a) + local len = #a + if len == 0 then return nil end + return math.sqrt(a:reduce(|acc, i| -> acc + i * i) / len) +end + +print(rms(range(1, 10))) diff --git a/Task/Averages-Root-mean-square/TAV/averages-root-mean-square.tav b/Task/Averages-Root-mean-square/TAV/averages-root-mean-square.tav new file mode 100644 index 0000000000..9e44a48dcc --- /dev/null +++ b/Task/Averages-Root-mean-square/TAV/averages-root-mean-square.tav @@ -0,0 +1,10 @@ +main (parms):+ + t =: new tuple from 1 upto 10 + print t, '->', vector t norm + +\ input can be tuple, row or map (class function used) +vector (@) norm: + sq =: 0.0 + ?# v =: @::give values + sq =+ v * v + :> float (sq / @.Count) sqrt diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index c1663edc5a..8db130292f 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -19,8 +19,8 @@ class SMA var count := theList.Length; count => - 0 { ^0.0r } - ! { + 0 : { ^0.0r } + ! : { if (count > thePeriod) { theList.removeAt(0); @@ -35,22 +35,20 @@ class SMA } } -// --- Program --- - public program() { var SMA3 := SMA.new(3); var SMA5 := SMA.new(5); for (int i := 1; i <= 5; i += 1) { - console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i)); - console.printLine("sma5 + ", i, " = ", SMA5.append(i)) + Console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i)); + Console.printLine("sma5 + ", i, " = ", SMA5.append(i)) }; for (int i := 5; i >= 1; i -= 1) { - console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i)); - console.printLine("sma5 + ", i, " = ", SMA5.append(i)) + Console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i)); + Console.printLine("sma5 + ", i, " = ", SMA5.append(i)) }; - console.readChar() + Console.readChar() } diff --git a/Task/B-zier-curves-Intersections/JavaScript/b-zier-curves-intersections.js b/Task/B-zier-curves-Intersections/JavaScript/b-zier-curves-intersections.js new file mode 100644 index 0000000000..035f0c110f --- /dev/null +++ b/Task/B-zier-curves-Intersections/JavaScript/b-zier-curves-intersections.js @@ -0,0 +1,162 @@ +class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } +} + +class QuadSpline { + constructor(c0, c1, c2) { + this.c0 = c0; + this.c1 = c1; + this.c2 = c2; + } +} + +class QuadCurve { + constructor(x, y) { + this.x = x; + this.y = y; + } +} + +// Subdivision by de Casteljau's algorithm. +function subdivideQuadSpline(q, t, u, v) { + const s = 1.0 - t; + const c0 = q.c0; + const c1 = q.c1; + const c2 = q.c2; + u.c0 = c0; + v.c2 = c2; + u.c1 = s * c0 + t * c1; + v.c1 = s * c1 + t * c2; + u.c2 = s * u.c1 + t * v.c1; + v.c0 = u.c2; +} + +function subdivideQuadCurve(q, t, u, v) { + subdivideQuadSpline(q.x, t, u.x, v.x); + subdivideQuadSpline(q.y, t, u.y, v.y); +} + +// It is assumed that xa0 <= xa1, ya0 <= ya1, xb0 <= xb1, and yb0 <= yb1. +function rectsOverlap(xa0, ya0, xa1, ya1, xb0, yb0, xb1, yb1) { + return (xb0 <= xa1 && xa0 <= xb1 && yb0 <= ya1 && ya0 <= yb1); +} + +function max3(x, y, z) { return Math.max(Math.max(x, y), z); } +function min3(x, y, z) { return Math.min(Math.min(x, y), z); } + +// This accepts the point as an intersection if the boxes are small enough. +function testIntersect(p, q, tol) { + const pxmin = min3(p.x.c0, p.x.c1, p.x.c2); + const pymin = min3(p.y.c0, p.y.c1, p.y.c2); + const pxmax = max3(p.x.c0, p.x.c1, p.x.c2); + const pymax = max3(p.y.c0, p.y.c1, p.y.c2); + + const qxmin = min3(q.x.c0, q.x.c1, q.x.c2); + const qymin = min3(q.y.c0, q.y.c1, q.y.c2); + const qxmax = max3(q.x.c0, q.x.c1, q.x.c2); + const qymax = max3(q.y.c0, q.y.c1, q.y.c2); + + let exclude = true; + let accept = false; + let intersect = new Point(0, 0); + + if (rectsOverlap(pxmin, pymin, pxmax, pymax, qxmin, qymin, qxmax, qymax)) { + exclude = false; + const xmin = Math.max(pxmin, qxmin); + const xmax = Math.min(pxmax, qxmax); + + if (xmax < xmin) { + throw new Error(`Assertion failure: ${xmax} < ${xmin}`); + } + + if (xmax - xmin <= tol) { + const ymin = Math.max(pymin, qymin); + const ymax = Math.min(pymax, qymax); + + if (ymax < ymin) { + throw new Error(`Assertion failure: ${ymax} < ${ymin}`); + } + + if (ymax - ymin <= tol) { + accept = true; + intersect.x = 0.5 * xmin + 0.5 * xmax; + intersect.y = 0.5 * ymin + 0.5 * ymax; + } + } + } + + return { exclude, accept, intersect }; +} + +function seemsToBeDuplicate(intersects, xy, spacing) { + let seemsToBeDup = false; + let i = 0; + + while (!seemsToBeDup && i !== intersects.length) { + const pt = intersects[i]; + seemsToBeDup = Math.abs(pt.x - xy.x) < spacing && Math.abs(pt.y - xy.y) < spacing; + i++; + } + + return seemsToBeDup; +} + +function findIntersects(p, q, tol, spacing) { + const intersects = []; + const workload = [{ p, q }]; + + // Quit looking after having emptied the workload. + while (workload.length > 0) { + const work = workload.pop(); + const { exclude, accept, intersect } = testIntersect(work.p, work.q, tol); + + if (accept) { + // To avoid detecting the same intersection twice, require some + // space between intersections. + if (!seemsToBeDuplicate(intersects, intersect, spacing)) { + intersects.push(intersect); + } + } else if (!exclude) { + const p0 = new QuadCurve(new QuadSpline(0, 0, 0), new QuadSpline(0, 0, 0)); + const p1 = new QuadCurve(new QuadSpline(0, 0, 0), new QuadSpline(0, 0, 0)); + const q0 = new QuadCurve(new QuadSpline(0, 0, 0), new QuadSpline(0, 0, 0)); + const q1 = new QuadCurve(new QuadSpline(0, 0, 0), new QuadSpline(0, 0, 0)); + + subdivideQuadCurve(work.p, 0.5, p0, p1); + subdivideQuadCurve(work.q, 0.5, q0, q1); + + workload.push({ p: p1, q: q1 }); + workload.push({ p: p1, q: q0 }); + workload.push({ p: p0, q: q1 }); + workload.push({ p: p0, q: q0 }); + } + } + + return intersects; +} + +function main() { + const p = new QuadCurve( + new QuadSpline(-1.0, 0.0, 1.0), + new QuadSpline(0.0, 10.0, 0.0) + ); + + const q = new QuadCurve( + new QuadSpline(2.0, -8.0, 2.0), + new QuadSpline(1.0, 2.0, 3.0) + ); + + const tol = 0.0000001; + const spacing = tol * 10; + + const intersects = findIntersects(p, q, tol, spacing); + + for (const intersect of intersects) { + console.log(`(${intersect.x}, ${intersect.y})`); + } +} + +main(); diff --git a/Task/Babbage-problem/AutoLISP/babbage-problem.l b/Task/Babbage-problem/AutoLISP/babbage-problem.l new file mode 100644 index 0000000000..9636fbb3f5 --- /dev/null +++ b/Task/Babbage-problem/AutoLISP/babbage-problem.l @@ -0,0 +1,54 @@ +;; Let's Create a tool [a function] that helps us check positive integers +;; to see which one's square is the first one that ends in ...269696 +;; It should be noted that a function can be used many times repetitively +;; so let's create that function which will be used many times. + +;; First, define the function, give it a name and parameters; it will look like: +;; (defun [function_name] ([input_parameter] / [local_variables]) +(defun SquareEndsWith269696? (number / ) + ;; Let's have the computer Square the number (whichever number was passed to the function) + (setq number (* number number)) + ;; Now let's convert that number to a string + (setq numberString (itoa number)) + ;; Is the length of the numberString greater than or equal to 6 digits? + (if (>= (strlen numberString) 6) + ;; If it was greater than or equal to 6, we will check the last 6 characters to see if they are equal to "269696" + ;; If this equality check is successful, then we have found our number, and will return a successful function check! + (eq "269696" (substr numberString (- (strlen numberString) 5))) + ;; Otherwise, an unsuccessful function check will be returned + ) +) + +;; Second, we will create a function that only needs to be used once, they do not always need to be used many times +;; Let's use your name as the initiator/name for this function +(defun c:BABBAGE ( / integer SquareFound) + ;; Once we have initiated the function, let's create our first integer to check + (setq integer 1) + ;; Now, let's perform a loop do perform an action many times within the function + ;; We do not want our loop to run infinitely, so let's create a True/False variable to identify if our task is complete + (setq SquareFound nil) + ;; ok, let's use the loop and True/False variable to continually check if we have found our correct integer + (while (not SquareFound) + ;; Now within the loop, let's use our First function to check if we have the correct integer + ;; We will save the new result of our check over our existing True/False variable + (setq SquareFound (SquareEndsWith269696? integer)) + ;; If the square was not found... + (if (not SquareFound) + ;; ...increase our integer number by 1 + (setq integer (1+ integer)) + ) + ;; Once the integer is found, our loop will end and the code will continue forward + ;; Otherwise, it will start back at "(while ..." + ) + ;; If we have made it this far, then our integer has been found! + ;; let's show everyone what the integer is + (prompt + (strcat + "\nThe smallest integer has been found!" + "\nInteger: " (itoa integer) ;; <-- we are converting the integer to a string + "\nSquared: " (itoa (* integer integer)) ;; <-- let's show everyone the squared number to prove it + ) + ) + ;; All done, this last line is not required, but makes the ending cleaner + (princ) +) diff --git a/Task/Babbage-problem/DuckDB/babbage-problem-1.duckdb b/Task/Babbage-problem/DuckDB/babbage-problem-1.duckdb new file mode 100644 index 0000000000..3a634060d8 --- /dev/null +++ b/Task/Babbage-problem/DuckDB/babbage-problem-1.duckdb @@ -0,0 +1,3 @@ +select * from generate_series(500,1000000) t(n) +where (n * n) % 1000000 == 269696 +limit 1; diff --git a/Task/Babbage-problem/DuckDB/babbage-problem-2.duckdb b/Task/Babbage-problem/DuckDB/babbage-problem-2.duckdb new file mode 100644 index 0000000000..807ff512ff --- /dev/null +++ b/Task/Babbage-problem/DuckDB/babbage-problem-2.duckdb @@ -0,0 +1,9 @@ +with recursive integers +as + (select 1::uint64 as n + UNION ALL + select n+1 from integers) + +select n from integers +where (n * n) % 1000000 == 269696 +limit 1; diff --git a/Task/Babbage-problem/Elena/babbage-problem.elena b/Task/Babbage-problem/Elena/babbage-problem.elena index c7c4a77da2..4721be5221 100644 --- a/Task/Babbage-problem/Elena/babbage-problem.elena +++ b/Task/Babbage-problem/Elena/babbage-problem.elena @@ -10,5 +10,5 @@ public program() n += 1 }; - console.printLine(n) + Console.printLine(n) } diff --git a/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy b/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy index 888e9c378e..98fc8c6b2a 100644 --- a/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy +++ b/Task/Babylonian-spiral/EasyLang/babylonian-spiral.easy @@ -1,14 +1,3 @@ -fastfunc findj a norm . - j = floor sqrt norm + 1 - repeat - b = j * j - if a + b < norm : return -1 - if a + b = norm : return j - until j = 0 - j -= 1 - . - return -1 -. proc babylon_spiral nsteps &pts[][] . pts[][] = [ [ 0 0 ] [ 0 1 ] ] norm = 1 @@ -21,16 +10,19 @@ proc babylon_spiral nsteps &pts[][] . for i = 0 to nsteps a = i * i if a > norm div 2 : break 1 - j = findj a norm - if j <> -1 - cands[][] &= [ i, j ] - cands[][] &= [ -i, j ] - cands[][] &= [ i, -j ] - cands[][] &= [ -i, -j ] - cands[][] &= [ j, i ] - cands[][] &= [ -j, i ] - cands[][] &= [ j, -i ] - cands[][] &= [ -j, -i ] + for j = floor sqrt norm + 1 downto 0 + b = j * j + if a + b < norm : break 1 + if a + b = norm + cands[][] &= [ i, j ] + cands[][] &= [ -i, j ] + cands[][] &= [ i, -j ] + cands[][] &= [ -i, -j ] + cands[][] &= [ j, i ] + cands[][] &= [ -j, i ] + cands[][] &= [ j, -i ] + cands[][] &= [ -j, -i ] + . . . . @@ -63,8 +55,9 @@ scy = 100 / (maxy - miny) * 0.96 ty = -miny * scy + 2 tx = -minx * scx + 2 glinewidth 0.1 -for i to len pts[][] - 1 - gline 0 ty 100 ty - gline tx 0 tx 100 - gline pts[i][1] * scx + tx, pts[i][2] * scy + ty, pts[i + 1][1] * scx + tx, pts[i + 1][2] * scy + ty +gline 0 ty 100 ty +gline tx 0 tx 100 +gpenup +for i to len pts[][] + glineto pts[i][1] * scx + tx, pts[i][2] * scy + ty . diff --git a/Task/Babylonian-spiral/FreeBASIC/babylonian-spiral.basic b/Task/Babylonian-spiral/FreeBASIC/babylonian-spiral.basic new file mode 100644 index 0000000000..2312460831 --- /dev/null +++ b/Task/Babylonian-spiral/FreeBASIC/babylonian-spiral.basic @@ -0,0 +1,92 @@ +Const PI = 4 * Atn(1) +Const TAU = 8 * Atn(1) + +Type Punto + x As Integer + y As Integer +End Type + +Sub InitSquares(squares() As Integer, nsteps As Integer) + For i As Integer = 0 To nsteps - 1 + squares(i) = i * i + Next +End Sub + +Sub BabylonianSpiral(points() As Punto, nsteps As Integer) + Dim As Integer squares(nsteps) + InitSquares(squares(), nsteps) + + points(0).x = 0 : points(0).y = 0 + points(1).x = 0 : points(1).y = 1 + + Dim As Integer norm = 1, i, j, k, a, b + Dim As Double theta, value, minvalue + Dim As Punto minimum + + For paso As Integer = 0 To nsteps - 3 + Dim As Punto prev = points(paso + 1) + theta = Atan2(prev.y, prev.x) + + Dim As Integer ncandidates = 0 + Dim As Punto candidates(100) + + Do + norm += 1 + For i = 0 To nsteps - 1 + a = squares(i) + If a > norm / 2 Then Exit For + For j = Int(Sqr(norm)) + 1 To 0 Step -1 + If j < 0 Then Exit For + b = squares(j) + If a + b < norm Then Exit For + If a + b = norm Then + Dim As Punto next_points(0 To 7) + next_points(0).x = i : next_points(0).y = j + next_points(1).x = -i : next_points(1).y = j + next_points(2).x = i : next_points(2).y = -j + next_points(3).x = -i : next_points(3).y = -j + next_points(4).x = j : next_points(4).y = i + next_points(5).x = -j : next_points(5).y = i + next_points(6).x = j : next_points(6).y = -i + next_points(7).x = -j : next_points(7).y = -i + + For k = 0 To 7 + candidates(ncandidates) = next_points(k) + ncandidates += 1 + Next + End If + Next + Next + Loop While ncandidates = 0 + + minvalue = TAU + For k = 0 To ncandidates - 1 + value = (theta - Atan2(candidates(k).y, candidates(k).x) + TAU) + value = value - Int(value / TAU) * TAU + If value < minvalue Then + minvalue = value + minimum = candidates(k) + End If + Next + + points(paso + 2) = minimum + Next + + For i = 0 To nsteps - 2 + points(i + 1).x = points(i).x + points(i + 1).x + points(i + 1).y = points(i).y + points(i + 1).y + Next +End Sub + +' Main program +Dim As Integer nsteps = 40 +Dim As Punto points(0 To nsteps - 1) +BabylonianSpiral(points(), nsteps) + +Print !"The first 40 points of the Babylonian spiral are:\n" +For i As Integer = 0 To nsteps - 1 + Print Using "(###_,###) "; points(i).x; points(i).y; + If (i + 1) Mod 10 = 0 Then Print +Next + +Sleep diff --git a/Task/Balanced-brackets/ArkScript/balanced-brackets.ark b/Task/Balanced-brackets/ArkScript/balanced-brackets.ark new file mode 100644 index 0000000000..1eb2101bb5 --- /dev/null +++ b/Task/Balanced-brackets/ArkScript/balanced-brackets.ark @@ -0,0 +1,24 @@ +(import std.List) + +(let gen_string (fun (length) { + (mut output "") + (while (< (len output) length) { + (set output (+ output (@ "[]" (random 0 1)))) }) + output })) + +(let balanced? (fun (str) { + (mut i 0) + (= + (len str) + (len + (list:takeWhile str (fun (char) { + (if (= "[" char) + (set i (+ i 1)) + (set i (- i 1))) + (>= i 0) }))))})) + +(list:forEach + (list:iota 0 5) + (fun (_) { + (let str (gen_string (random 2 8))) + (print (string:format "{:<8}: {:^6}" str (if (balanced? str) "OK" "NOT OK"))) })) diff --git a/Task/Balanced-brackets/AutoLISP/balanced-brackets.l b/Task/Balanced-brackets/AutoLISP/balanced-brackets.l new file mode 100644 index 0000000000..90ed32a229 --- /dev/null +++ b/Task/Balanced-brackets/AutoLISP/balanced-brackets.l @@ -0,0 +1,12 @@ +(defun BalancedBrackets (str / cntOpen curr) + (setq cntOpen 0) + (setq str (vl-string->list str)) + (while (and (>= cntOpen 0) str) + (setq curr (car str) str (cdr str)) + (cond + ((= 91 curr) (setq cntOpen (1+ cntOpen))) + ((= 93 curr) (setq cntOpen (1- cntOpen))) + ) + ) + (and (null str) (zerop cntOpen)) +) diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 4636698372..c09c6651e8 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -1,7 +1,3 @@ -// Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order. -// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), -// none of which mis-nest. - import system'routines; import extensions; import extensions'text; @@ -10,7 +6,7 @@ randomBrackets(len) { if (0 == len) { - ^emptyString + ^ EmptyString } else { @@ -43,8 +39,8 @@ public program() { var str := randomBrackets(len); - console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced") + Console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced") }; - console.readChar() + Console.readChar() } diff --git a/Task/Balanced-brackets/Nom/balanced-brackets.num b/Task/Balanced-brackets/Nom/balanced-brackets.num new file mode 100644 index 0000000000..eba2a9f889 --- /dev/null +++ b/Task/Balanced-brackets/Nom/balanced-brackets.num @@ -0,0 +1,19 @@ +read; +"[","]" { add "*"; push; } +[:space:] { clear; } +!"" { + clear; add "Sorry, only brackets [] allowed in this!\n"; + print; quit; +} +parse> +pop; pop; +"[*]*","ob*ob*" { clear; add "ob*"; push; .reparse } +pop; +"[*ob*]*" { clear; add "ob*"; push; .reparse } + +(eof) { + "ob*" { clear; add "brackets look balanced!\n"; print; quit; } + clear; add "brackets not balanced.\n"; print; quit; +} + +push; push; push; diff --git a/Task/Balanced-brackets/Pluto/balanced-brackets.pluto b/Task/Balanced-brackets/Pluto/balanced-brackets.pluto new file mode 100644 index 0000000000..a38471fe49 --- /dev/null +++ b/Task/Balanced-brackets/Pluto/balanced-brackets.pluto @@ -0,0 +1,36 @@ +local function is_balanced(s) + if s == "" then + return true + end + local counter_left = 0 -- number of left brackets so far unmatched + for i = 1, #s do + local c = s[i] + if c == "[" then + counter_left += 1 + elseif counter_left > 0 do + counter_left -= 1 + else + return false + end + end + return counter_left == 0 +end + +print("Checking examples in task description:") +local brackets = {"", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"} +for brackets as b do + local res = is_balanced(b) + local bb = (b != "") ? b : "(empty)" + print(string.format("%-8s %s", bb, res ? "OK" : "NOT OK")) +end + +print("\nChecking 7 random strings of brackets of length 8:") +math.randomseed(os.time()) +for i = 1, 7 do + local b = "" + for j = 1, 8 do + b ..= (math.random(0, 1) == 0) ? "[" : "]" + end + local res = is_balanced(b) + print(string.format("%s %s", b, res ? "OK" : "NOT OK")) +end diff --git a/Task/Balanced-ternary/JavaScript/balanced-ternary.js b/Task/Balanced-ternary/JavaScript/balanced-ternary.js new file mode 100644 index 0000000000..29ae058c1c --- /dev/null +++ b/Task/Balanced-ternary/JavaScript/balanced-ternary.js @@ -0,0 +1,203 @@ +class BTernary { + constructor(input) { + if (typeof input === 'string') { + let i = 0; + while (i < input.length && input.charAt(i) === '0') { + i++; + } + this.value = input.substring(i); + } else if (typeof input === 'number') { + this.value = this.convertToBT(input); + } + } + + convertToBT(v) { + if (v < 0) { + return this.flip(this.convertToBT(-v)); + } + if (v === 0) { + return ""; + } + const rem = this.mod3(v); + if (rem === 0) { + return this.convertToBT(Math.floor(v / 3)) + "0"; + } + if (rem === 1) { + return this.convertToBT(Math.floor(v / 3)) + "+"; + } + if (rem === 2) { + return this.convertToBT(Math.floor((v + 1) / 3)) + "-"; + } + return "You can't see me"; + } + + flip(s) { + let flip = ""; + for (let i = 0; i < s.length; i++) { + if (s.charAt(i) === '+') { + flip += '-'; + } else if (s.charAt(i) === '-') { + flip += '+'; + } else { + flip += '0'; + } + } + return flip; + } + + mod3(v) { + if (v > 0) { + return v % 3; + } + v = v % 3; + return (v + 3) % 3; + } + + intValue() { + let sum = 0; + const s = this.value; + for (let i = 0; i < s.length; i++) { + const c = s.charAt(s.length - i - 1); + let dig = 0; + if (c === '+') { + dig = 1; + } else if (c === '-') { + dig = -1; + } + sum += dig * Math.pow(3, i); + } + return sum; + } + + add(that) { + let a = this.value; + let b = that.value; + + const longer = a.length > b.length ? a : b; + let shorter = a.length > b.length ? b : a; + + while (shorter.length < longer.length) { + shorter = '0' + shorter; + } + + a = longer; + b = shorter; + + let carry = '0'; + let sum = ""; + for (let i = 0; i < a.length; i++) { + const place = a.length - i - 1; + const digisum = this.addDigitsWithCarry(a.charAt(place), b.charAt(place), carry); + if (digisum.length !== 1) { + carry = digisum.charAt(0); + } else { + carry = '0'; + } + sum = digisum.charAt(digisum.length - 1) + sum; + } + sum = carry + sum; + + return new BTernary(sum); + } + + addDigitsWithCarry(a, b, carry) { + const sum1 = this.addDigits(a, b); + const sum2 = this.addDigits(sum1.charAt(sum1.length - 1), carry); + + if (sum1.length === 1) { + return sum2; + } + if (sum2.length === 1) { + return sum1.charAt(0) + sum2; + } + return sum1.charAt(0) + ""; + } + + addDigits(a, b) { + let sum = ""; + if (a === '0') { + sum = b + ""; + } else if (b === '0') { + sum = a + ""; + } else if (a === '+') { + if (b === '+') { + sum = "+-"; + } else { + sum = "0"; + } + } else { + if (b === '+') { + sum = "0"; + } else { + sum = "-+"; + } + } + return sum; + } + + neg() { + return new BTernary(this.flip(this.value)); + } + + sub(that) { + return this.add(that.neg()); + } + + mul(that) { + const one = new BTernary(1); + const zero = new BTernary(0); + let mul = new BTernary(0); + + let flipflag = 0; + if (that.compareTo(zero) === -1) { + that = that.neg(); + flipflag = 1; + } + + for (let i = new BTernary(1); i.compareTo(that) < 1; i = i.add(one)) { + mul = mul.add(this); + } + + if (flipflag === 1) { + mul = mul.neg(); + } + return mul; + } + + equals(that) { + return this.value === that.value; + } + + compareTo(that) { + if (this.intValue() > that.intValue()) { + return 1; + } else if (this.equals(that)) { + return 0; + } + return -1; + } + + toString() { + return this.value; + } +} + +// Main execution +function main() { + const a = new BTernary("+-0++0+"); + const b = new BTernary(-436); + const c = new BTernary("+-++-"); + + console.log("a=" + a.intValue()); + console.log("b=" + b.intValue()); + console.log("c=" + c.intValue()); + console.log(); + + // result = a * (b - c) + const result = a.mul(b.sub(c)); + + console.log("result= " + result + " " + result.intValue()); +} + +// Run the main function +main(); diff --git a/Task/Base64-decode-data/Pluto/base64-decode-data.pluto b/Task/Base64-decode-data/Pluto/base64-decode-data.pluto new file mode 100644 index 0000000000..b8359fd691 --- /dev/null +++ b/Task/Base64-decode-data/Pluto/base64-decode-data.pluto @@ -0,0 +1,4 @@ +local base64 = require("base64") + +local s = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=" +print(base64.decode(s)) diff --git a/Task/Base64-decode-data/Zig/base64-decode-data.zig b/Task/Base64-decode-data/Zig/base64-decode-data.zig new file mode 100644 index 0000000000..cad232e18b --- /dev/null +++ b/Task/Base64-decode-data/Zig/base64-decode-data.zig @@ -0,0 +1,86 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +const INPUT = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"; +const UPPERCASE_OFFSET: i8 = -65; +const LOWERCASE_OFFSET: i8 = 26 - 97; +const NUM_OFFSET: i8 = 52 - 48; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + print("Input: {s}\n", .{INPUT}); + + // Create a dynamic array to collect binary strings + var binary_strings = ArrayList([]const u8).init(allocator); + defer { + for (binary_strings.items) |item| { + allocator.free(item); + } + binary_strings.deinit(); + } + + // Process each character and convert to binary + for (INPUT) |ch| { + if (ch == '=') continue; // Filter '=' chars + + // Map char values using Base64 Characters Table + const ascii: i8 = @intCast(ch); + const convert: u8 = switch (ch) { + '0'...'9' => @intCast(ascii + NUM_OFFSET), + 'a'...'z' => @intCast(ascii + LOWERCASE_OFFSET), + 'A'...'Z' => @intCast(ascii + UPPERCASE_OFFSET), + '+' => 62, + '/' => 63, + else => { + print("Not a valid base64 encoded string\n", .{}); + return; + }, + }; + + // Convert to binary format (6 bits for base64) + const binary_str = try std.fmt.allocPrint(allocator, "{b:0>6}", .{convert}); + try binary_strings.append(binary_str); + } + + // Concatenate all binary strings + var total_len: usize = 0; + for (binary_strings.items) |item| { + total_len += item.len; + } + + const concatenated = try allocator.alloc(u8, total_len); + defer allocator.free(concatenated); + + var pos: usize = 0; + for (binary_strings.items) |item| { + @memcpy(concatenated[pos..pos + item.len], item); + pos += item.len; + } + + // Split into 8-character chunks and convert to bytes + var result_bytes = ArrayList(u8).init(allocator); + defer result_bytes.deinit(); + + var i: usize = 0; + while (i + 8 <= concatenated.len) : (i += 8) { + const chunk = concatenated[i..i + 8]; + const byte_value = std.fmt.parseInt(u8, chunk, 2) catch |err| { + print("Error parsing binary: {}\n", .{err}); + return; + }; + try result_bytes.append(byte_value); + } + + // Convert to UTF-8 string and print + const result_str = result_bytes.items; + if (std.unicode.utf8ValidateSlice(result_str)) { + print("Output: {s}\n", .{result_str}); + } else { + print("Invalid UTF-8 sequence\n", .{}); + } +} diff --git a/Task/Bell-numbers/Pluto/bell-numbers.pluto b/Task/Bell-numbers/Pluto/bell-numbers.pluto new file mode 100644 index 0000000000..5cabc1baca --- /dev/null +++ b/Task/Bell-numbers/Pluto/bell-numbers.pluto @@ -0,0 +1,32 @@ +local bigint = require "bigint" +local fmt = require "fmt" + +local function bell_triangle(n) + local zero = bigint.new(0) + local tri = {} + for i = 1, n do + tri[i] = {} + for j = 1, i - 1 do tri[i][j] = zero end + end + tri[2][1] = bigint.new(1) + for i = 3, n do + tri[i][1] = tri[i - 1][i - 2] + for j = 2, i - 1 do + tri[i][j] = tri[i][j - 1] + tri[i - 1][j - 1] + end + end + return tri +end + +local bt = bell_triangle(51) +print("First fifteen and fiftieth Bell numbers:") +for i = 2, 16 do + local s = bt[i][1]:tostring() + fmt.print("%2d: %s", i - 1, fmt.int(s)) +end +local s50 = bt[51][1]:tostring() +fmt.print("%2d: %s", 50, fmt.int(s50)) +print("\nThe first ten rows of Bell's triangle:") +for i = 2, 11 do + fmt.tprint("%7s", bt[i]:map(|j| -> fmt.int(j:tostring())), #bt[i]) +end diff --git a/Task/Benfords-law/DuckDB/benfords-law.duckdb b/Task/Benfords-law/DuckDB/benfords-law.duckdb new file mode 100644 index 0000000000..ec7d41aaa2 --- /dev/null +++ b/Task/Benfords-law/DuckDB/benfords-law.duckdb @@ -0,0 +1,22 @@ +with recursive fib (n1, n2) as ( + select + 1::double, 1::double + union all + select n2, n1+n2 + from fib + ), +lastdigits as ( + select format('{}', n1)[1]::int as digit + from fib + limit 1000 -- N.B. + ), +counts as ( + select digit, count() as actual + from lastdigits group by digit + ), +total as ( + select count() as total from lastdigits + ) +select digit, actual, (total * log(10, 1 + (1 / digit))) as expected + from counts, total + order by digit; diff --git a/Task/Bernoulli-numbers/R/bernoulli-numbers.r b/Task/Bernoulli-numbers/R/bernoulli-numbers.r index e6c84acce2..71e908ffcf 100644 --- a/Task/Bernoulli-numbers/R/bernoulli-numbers.r +++ b/Task/Bernoulli-numbers/R/bernoulli-numbers.r @@ -1,8 +1,6 @@ -library(pracma) +library(gmp) -for (idx in c(1,2*0:30)) { - b <- bernoulli(idx) - d <- as.character(denominator(b)) - n <- as.character(numerator(b)) - cat("B(",idx,") = ",n,"/",d,"\n", sep = "") -} +indices <- c(0,1,2*(1:30)) +bnums <- sapply(indices, BernoulliQ) +names(bnums) <- paste0("B(", indices, ")") +print(bnums, initLine=FALSE) diff --git a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx index a1673236bf..83184fac1f 100644 --- a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx +++ b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx @@ -1,55 +1,129 @@ -/*REXX program calculates N number of Bernoulli numbers expressed as vulgar fractions.*/ -parse arg N .; if N=='' | N=="," then N= 60 /*Not specified? Then use the default.*/ -numeric digits max(9, n*2) /*increase the decimal digits if needed*/ -w= max(length(N), 4); Nw= N + w + N % 4 /*used for aligning (output) fractions.*/ -say 'B(n)' center("Bernoulli numbers expressed as vulgar fractions", max(78-w, Nw) ) -say copies('─',w) copies("─", max(78-w,Nw+2*w)) /*display 2nd line of title, separators*/ -!.= .; do #=0 to N /*process the numbers from 0 ──► N. */ - b= bern(#); if b==0 then iterate /*calculate Bernoulli number, skip if 0*/ - indent= max(0, nW - pos('/', b) ) /*calculate the alignment (indentation)*/ - say right(#, w) left('', indent) b /*display the indented Bernoulli number*/ - end /*#*/ /* [↑] align the Bernoulli fractions. */ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -bern: parse arg x; if x==0 then return '1/1' /*handle the special case of zero. */ - if x==1 then return '-1/2' /* " " " " " one. */ - if x//2 then return 0 /* " " " " " odds > 1.*/ - do j=2 to x by 2; jp= j+1 /*process the positive integers up to X*/ - sn= 1 - j /*define the numerator. */ - sd= 2 /* " " denominator. */ - do k=2 to j-1 by 2 /*calculate a SN/SD sequence. */ - parse var @.k bn '/' ad /*get a previously calculated fraction.*/ - an= comb(jp, k) * bn /*use COMBination for the next term. */ - $lcm= LCM(sd, ad) /*use Least Common Denominator function*/ - sn= $lcm % sd * sn; sd= $lcm /*calculate the current numerator. */ - an= $lcm % ad * an /* " " next " */ - sn= sn + an /* " " current " */ - end /*k*/ /* [↑] calculate the SN/SD sequence.*/ - sn= -sn /*flip the sign for the numerator. */ - sd= sd * jp /*calculate the denominator. */ - if sn\==1 then do; _= GCD(sn, sd) /*get the Greatest Common Denominator.*/ - sn= sn%_; sd= sd%_ /*reduce the numerator and denominator.*/ - end /* [↑] done with the reduction(s). */ - @.j= sn'/'sd /*save the result for the next round. */ - end /*j*/ /* [↑] done calculating Bernoulli #'s.*/ - return sn'/'sd -/*──────────────────────────────────────────────────────────────────────────────────────*/ -comb: procedure expose !.; parse arg x,y; if x==y then return 1 - if !.C.x.y\==. then return !.C.x.y /*combination computed before?*/ - if x-y < y then y= x-y /*x-y < y? Then use a new Y.*/ - z= perm(x, y); do j=2 for y-1; z= z % j - end /*j*/ - !.C.x.y= z; return z /*assign memoization & return.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -GCD: procedure; parse arg x,y; x= abs(x) - do until y==0; parse value x//y y with y x; end; return x -/*──────────────────────────────────────────────────────────────────────────────────────*/ -LCM: procedure; parse arg x,y /*X=ABS(X); Y=ABS(Y) not needed for Bernoulli #s.*/ - /*IF Y==0 THEN RETURN 0 " " " " " */ - $= x * y /*calculate part of the LCM here. */ - do until y==0; parse value x//y y with y x - end /*until*/ /* [↑] this is a short & fast GCD*/ - return $ % x /*divide the pre─calculated value.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -perm: procedure expose !.; parse arg x,y; if !.P.x.y\==. then return !.P.x.y - z= 1; do j=x-y+1 to x; z= z*j; end; !.P.x.y= z; return z +-- 30 Jul 2025 +include Settings +numeric digits 16 +arg xx +if xx = '' then + xx=60 +ss=(xx>0); xx=Abs(xx) + +say 'BERNOULLI NUMBERS' +say version +say + +call Time('r') +call Rational1 xx +if ss then + call ShowFractions xx +call Timer + +call Time('r') +call Rational2 xx +if ss then + call ShowFractions xx +call Timer + +call Time('r') +call Decimal1 xx +if ss then + call ShowDecimals xx +call Timer + +call Time('r') +call Decimal2 xx +if ss then + call ShowDecimals xx +call Timer +exit + +Rational1: +procedure expose Memo. Bern. +arg xx +say 'Rational arithmetic' +say 'cf Generating function' +numeric digits Max(Digits(),3*xx) +Bern.=0; Bern.0='1 1'; Bern.1='-1 2' +do n = 2 by 2 to xx + s=0 + do k = 0 to n-1 + s=Addq(s,Scaleq(Bern.k,Comb(n+1,k))) + end k + Bern.n=Mulq(Negq(s),Invq(n+1)) +end n +return + +Rational2: +procedure expose Memo. Bern. +arg xx +say 'Numerator and denominator calculations' +say 'cf Double sum formula optimized' +numeric digits Max(Digits(),3*xx) +Bern.=0; Bern.0='1 1'; Bern.1='-1 2' +do j = 2 by 2 to xx + jp=j+1; sn=1-j; sd=2 + do k = 2 by 2 to j-1 + bn=bn.k; ad=ad.k; an=Comb(jp,k)*bn; tl=Lcm(sd,ad) + sn=tl%sd*sn; sd=tl; an=tl%ad*an; sn=sn+an + end k + sn=-sn; sd=sd*jp; bn.j=sn; ad.j=sd; g=Gcd(Abs(sn),sd) + Bern.j=sn/g sd/g +end j +return + +ShowFractions: +procedure expose Bern. +arg xx +w=Length(Word(Bern.xx,1))+2 +say ' Bn' Right('Num',w) '/' Left('Den',10) 'Decimal' +do i = 0 to xx + if Bern.i <> 0 then do + parse var Bern.i num den + say Right(i,3) Right(num,w) '/' Left(den,10) Digit(num/den,16) + end +end i +return + +Decimal1: +procedure expose Bern. Memo. +arg xx +say 'Floating point calculations' +say 'cf Generating function' +numeric digits Max(Digits(),2*xx) +Bern.=0; Bern.0=1; Bern.1='-0.5' +do n = 2 by 2 to xx + s=0 + do k = 0 to n-1 + s=s+Bern.k*Comb(n+1,k) + end k + Bern.n=-s/(n+1) +end n +return xx + +Decimal2: +procedure expose Bern. Memo. +arg xx +say 'Floating point calculations' +say 'cf Akiyama-Tanigawa' +numeric digits Max(Digits(),3*xx) +Bern.=0; Bern.0=1; Bern.1=-0.5 +do i = 2 by 2 to xx + do m = 0 to i + a.m=1/(m+1) + do j = m by -1 to 1 + j1=j-1; a.j1=j*(a.j1-a.j) + end + end m + Bern.i=a.0 +end i +return xx + +ShowDecimals: +procedure expose Bern. +arg xx +say ' Bn' 'Decimal' +do i = 0 to xx + if Bern.i <> 0 then + say Right(i,3) Digit(Bern.i,16) +end i +return + +include Math diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index 99e99cba05..2cbdf0b886 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -41,8 +41,8 @@ public program() { var shuffled_s := s.Shuffled; - console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")") + Console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")") }; - console.readChar() + Console.readChar() } diff --git a/Task/Best-shuffle/Factor/best-shuffle.factor b/Task/Best-shuffle/Factor/best-shuffle.factor new file mode 100644 index 0000000000..ac380801c1 --- /dev/null +++ b/Task/Best-shuffle/Factor/best-shuffle.factor @@ -0,0 +1,26 @@ +USING: arrays combinators.short-circuit formatting kernel random +sequences sequences.extras ; + +:: best-shuffle ( str -- str' ) + str clone :> new-str + str length :> n + n >array randomize :> range1 + n >array randomize :> range2 + + range1 [| i | + range2 [| j | + { + [ i j = ] + [ i new-str nth j new-str nth = ] + [ i str nth j new-str nth = ] + [ i new-str nth j str nth = ] + } 0|| [ + i j new-str exchange + ] unless + ] each + ] each + + new-str ; + +: best-shuffle. ( str -- ) + dup best-shuffle 2dup [ = ] 2count "%s, %s, (%d)\n" printf ; diff --git a/Task/Best-shuffle/YAMLScript/best-shuffle.ys b/Task/Best-shuffle/YAMLScript/best-shuffle.ys new file mode 100644 index 0000000000..2874ddd1dd --- /dev/null +++ b/Task/Best-shuffle/YAMLScript/best-shuffle.ys @@ -0,0 +1,44 @@ +!YS-v0 + +defn main(input): + say: read-string(input) + .map(best-shuffle):vec + +defn best-shuffle(s): + ref =: s:group-indices:cycles + prm =: concat.apply(map(partial(rotate 1) ref)) + ref =: concat(ref*) + + map(vector ref prm): + .sort-by(first _) + .map(second) + .map(partial(get s)) + .str(*) + .call(\([s _ s.score(_)]) _) + +defn score(before after): + map(== before after) + .filter(true?).# + +defn group-indices(s): + map-indexed(vector s) + .merge-vecs({}):vals + .sort-by(count _):reverse + +defn cycles(coll): + n =: coll.0.# + cycle =: range(n):cycle + coll =: concat(coll*) + map(vector coll cycle): + .merge-vecs([]) + +defn rotate(n coll): + c =: coll.# + n =: (c + n) % c + concat coll.drop(n): coll.take(n) + +defn merge-vecs(vecs init): + reduce _ init vecs: + fn(counts [index x]): + assoc counts x: + counts.$x.or([]).conj(index) diff --git a/Task/Bifid-cipher/Zig/bifid-cipher.zig b/Task/Bifid-cipher/Zig/bifid-cipher.zig new file mode 100644 index 0000000000..1647e357f2 --- /dev/null +++ b/Task/Bifid-cipher/Zig/bifid-cipher.zig @@ -0,0 +1,164 @@ +const std = @import("std"); + +const Point = struct { + row: i32, + col: i32, +}; + +const Bifid = struct { + grid: [][]u8, + coordinates: std.AutoHashMap(u8, Point), + n: i32, + allocator: std.mem.Allocator, + + pub fn init(allocator: std.mem.Allocator, n: i32, text: []const u8) !*Bifid { + if (text.len != @as(usize, @intCast(n * n))) { + return error.IncorrectLength; + } + + var self = try allocator.create(Bifid); + self.* = .{ + .grid = try allocator.alloc([]u8, @intCast(n)), + .coordinates = std.AutoHashMap(u8, Point).init(allocator), + .n = n, + .allocator = allocator, + }; + + for (0..@intCast(n)) |i| { + self.grid[i] = try allocator.alloc(u8, @intCast(n)); + } + + var row: i32 = 0; + var col: i32 = 0; + + for (text) |ch| { + self.grid[@intCast(row)][@intCast(col)] = ch; + try self.coordinates.put(ch, .{ .row = row, .col = col }); + + col += 1; + if (col == n) { + col = 0; + row += 1; + } + } + + if (n == 5) { + // Handle I/J as the same letter in traditional 5x5 grid + if (self.coordinates.get('I')) |i_coords| { + try self.coordinates.put('J', i_coords); + } + } + + return self; + } + + pub fn deinit(self: *Bifid) void { + for (self.grid) |row| { + self.allocator.free(row); + } + self.allocator.free(self.grid); + self.coordinates.deinit(); + self.allocator.destroy(self); + } + + pub fn encrypt(self: *const Bifid, text: []const u8, allocator: std.mem.Allocator) ![]u8 { + var row_one = std.ArrayList(i32).init(allocator); + defer row_one.deinit(); + var row_two = std.ArrayList(i32).init(allocator); + defer row_two.deinit(); + + for (text) |ch| { + if (self.coordinates.get(ch)) |coordinate| { + try row_one.append(coordinate.row); + try row_two.append(coordinate.col); + } + } + + // Extend row_one with all elements from row_two + for (row_two.items) |col| { + try row_one.append(col); + } + + var result = std.ArrayList(u8).init(allocator); + var i: usize = 0; + while (i < row_one.items.len - 1) : (i += 2) { + const r = @as(usize, @intCast(row_one.items[i])); + const c = @as(usize, @intCast(row_one.items[i + 1])); + try result.append(self.grid[r][c]); + } + + return result.toOwnedSlice(); + } + + pub fn decrypt(self: *const Bifid, text: []const u8, allocator: std.mem.Allocator) ![]u8 { + var row = std.ArrayList(i32).init(allocator); + defer row.deinit(); + + for (text) |ch| { + if (self.coordinates.get(ch)) |coordinate| { + try row.append(coordinate.row); + try row.append(coordinate.col); + } + } + + const middle = row.items.len / 2; + + var result = std.ArrayList(u8).init(allocator); + + for (0..middle) |i| { + const r = @as(usize, @intCast(row.items[i])); + const c = @as(usize, @intCast(row.items[i + middle])); + try result.append(self.grid[r][c]); + } + + return result.toOwnedSlice(); + } + + pub fn display(self: *const Bifid) void { + for (self.grid) |row| { + for (row) |ch| { + std.debug.print("{c} ", .{ch}); + } + std.debug.print("\n", .{}); + } + } +}; + +fn runTest(bifid: *const Bifid, message: []const u8, allocator: std.mem.Allocator) !void { + std.debug.print("Using Polybius square:\n", .{}); + bifid.display(); + std.debug.print("Message: {s}\n", .{message}); + + const encrypted = try bifid.encrypt(message, allocator); + defer allocator.free(encrypted); + std.debug.print("Encrypted: {s}\n", .{encrypted}); + + const decrypted = try bifid.decrypt(encrypted, allocator); + defer allocator.free(decrypted); + std.debug.print("Decrypted: {s}\n\n", .{decrypted}); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const message1 = "ATTACKATDAWN"; + const message2 = "FLEEATONCE"; + const message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; + + const bifid1 = try Bifid.init(allocator, 5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); + defer bifid1.deinit(); + + const bifid2 = try Bifid.init(allocator, 5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); + defer bifid2.deinit(); + + try runTest(bifid1, message1, allocator); + try runTest(bifid2, message2, allocator); + try runTest(bifid2, message1, allocator); + try runTest(bifid1, message2, allocator); + + const bifid3 = try Bifid.init(allocator, 6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + defer bifid3.deinit(); + try runTest(bifid3, message3, allocator); +} diff --git a/Task/Bin-given-limits/DuckDB/bin-given-limits-1.duckdb b/Task/Bin-given-limits/DuckDB/bin-given-limits-1.duckdb new file mode 100644 index 0000000000..3ac65257db --- /dev/null +++ b/Task/Bin-given-limits/DuckDB/bin-given-limits-1.duckdb @@ -0,0 +1,24 @@ +# Return 'inf'::DOUBLE if the value is too large +# Assume limits is sorted +create or replace function classify(x, limits) as ( + with recursive cte as ( + select 0 as i, null as found + union all + select i+1, if(x < limits[1+i], limits[1+i], null) as found + from cte + where found is null and i < length(limits) + ) + select coalesce(last(found order by i), 'inf'::DOUBLE) from cte +); + +create or replace function bins(data, limits) as table ( + select value, classify(value, limits) + from unnest(data) _(value) +); + +set variable limits = [23, 37, 43, 53, 67, 83]; +set variable data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, + 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55]; + +select histogram(boundary) +from bins(getvariable('data'), getvariable('limits') ) t(value, boundary); diff --git a/Task/Bin-given-limits/DuckDB/bin-given-limits-2.duckdb b/Task/Bin-given-limits/DuckDB/bin-given-limits-2.duckdb new file mode 100644 index 0000000000..dcd69d9fe2 --- /dev/null +++ b/Task/Bin-given-limits/DuckDB/bin-given-limits-2.duckdb @@ -0,0 +1,14 @@ +# "pretty print" the histogram as a table +create or replace function pp(data, limits) as table ( + with hist as ( + select histogram(boundary) as h + from bins(data, limits) t(value, boundary) + ), + upper as (select h['inf'::DOUBLE][1] as upper from hist) + select '< ' || x::VARCHAR as bin, (select coalesce(h[x][1],0) from hist) as frequency + from unnest(limits) _(x) + union all + select '< inf', upper from upper +); + +from pp(getvariable('data'), getvariable('limits')); diff --git a/Task/Binary-digits/DuckDB/binary-digits-1.duckdb b/Task/Binary-digits/DuckDB/binary-digits-1.duckdb new file mode 100644 index 0000000000..b0439c7cc0 --- /dev/null +++ b/Task/Binary-digits/DuckDB/binary-digits-1.duckdb @@ -0,0 +1,2 @@ +SELECT n, format('{:b}', n) +FROM (select unnest(range(0, 6) || [50, 9000]) as n); diff --git a/Task/Binary-digits/DuckDB/binary-digits-2.duckdb b/Task/Binary-digits/DuckDB/binary-digits-2.duckdb new file mode 100644 index 0000000000..943b003cac --- /dev/null +++ b/Task/Binary-digits/DuckDB/binary-digits-2.duckdb @@ -0,0 +1,22 @@ +# n is assumed to be a non-negative integer +CREATE OR REPLACE FUNCTION binary_digits(n) as ( + WITH RECURSIVE cte(num, str) as ( + -- Base case + SELECT n, '' + UNION ALL + -- Recursive case: divide by 2 and build the binary string + SELECT num // 2, (num % 2) || str + FROM cte + WHERE num > 0 + ) + SELECT CASE WHEN str = '' THEN '0' ELSE str END + FROM cte + WHERE num = 0 + LIMIT 1 +); + +select n, binary_digits(n) +from (select unnest(range(0, 6) || [50, 9000]) as n); + +.maxwidth 200 +select n, binary_digits(n) from (select 123456789123456789123456789123456789 as n) diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index dbab2c5f2b..163e2ca4b3 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -5,6 +5,6 @@ public program() { new int[]{5,50,9000}.forEach::(n) { - console.printLine(n.toString(2)) + Console.printLine(n.toString(2)) } } diff --git a/Task/Binary-digits/Haxe/binary-digits.haxe b/Task/Binary-digits/Haxe/binary-digits.haxe new file mode 100644 index 0000000000..f732d3f6e8 --- /dev/null +++ b/Task/Binary-digits/Haxe/binary-digits.haxe @@ -0,0 +1,15 @@ +class Main { + static public function main() { + var integers = [5, 50, 9000]; + + for (i in integers) { + var bin = ""; + while (i > 1) { + bin = (i % 2) + bin; + i = Std.int(i / 2); + } + bin = i + bin; + trace(bin); + } + } +} diff --git a/Task/Binary-digits/Icon/binary-digits.icon b/Task/Binary-digits/Icon/binary-digits-1.icon similarity index 100% rename from Task/Binary-digits/Icon/binary-digits.icon rename to Task/Binary-digits/Icon/binary-digits-1.icon diff --git a/Task/Binary-digits/Icon/binary-digits-2.icon b/Task/Binary-digits/Icon/binary-digits-2.icon new file mode 100644 index 0000000000..54b725932a --- /dev/null +++ b/Task/Binary-digits/Icon/binary-digits-2.icon @@ -0,0 +1,12 @@ +procedure main() + every write(bstring(0|5|50|255|1285|9000)) +end + +procedure bstring(i) + s := "" + repeat{ + s := string(iand(i,1)) || s + if (i := ishift(i,-1)) = 0 then break + } + return s +end diff --git a/Task/Binary-digits/RISC-V-Assembly/binary-digits.asm b/Task/Binary-digits/RISC-V-Assembly/binary-digits.asm new file mode 100644 index 0000000000..4c9a8b927b --- /dev/null +++ b/Task/Binary-digits/RISC-V-Assembly/binary-digits.asm @@ -0,0 +1,185 @@ + # riscv assembly raspberry pico2 rp2350 +# program binaryDigits.s +# For construction see the riscv main page +# Exec by connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +.equ LENGTHDEC, 12 +.equ LENGTHBIN, 33 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" + +szMessAffdeb: .asciz "Decimal value : " +szMessAfffin: .asciz " binary value : " +szCarriageReturn: .asciz " \r\n" +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvDec: .skip LENGTHDEC +sConvBin: .skip LENGTHBIN +.align 2 +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # connexion usb by function sdk c++ + beqz a0,1b # return code = zero ? loop + + la a0,szMessStart # message address + call writeString # display string + li a0,50 + call conversion + li a0,-1 + call conversion + li a0,1 + call conversion + li a0,1<<30 + call conversion + call getchar +100: # final loop + j 100b +/************************************/ +/* conversion and display */ +/***********************************/ +/* a0 value */ +conversion: + addi sp, sp, -8 + sw ra, 0(sp) # save registers + sw s0, 4(sp) + mv s0,a0 + la a0,szMessAffdeb + call writeString # display message + mv a0,s0 + la a1,sConvDec + call conversion10S + call writeString # display + la a0,szMessAfffin + call writeString # display message + mv a0,s0 + la a1,sConvBin + call conversion2 + la a0,sConvBin + call writeString # display message + la a0,szCarriageReturn + call writeString # display newline + +100: + lw ra, 0(sp) # restaur registers + lw s0, 4(sp) + addi sp, sp, 8 + ret +/************************************/ +/* binary conversion */ +/***********************************/ +/* a0 value */ +/* a1 result area address */ +/* size mini 33 character */ +conversion2: # INFO: conversion2 + addi sp, sp, -8 # save registres + sw ra, 0(sp) + li t2,0 + li t1,0 +1: + slt t3,a0,x0 # if negative bit 31 is 1 + + slli a0,a0,1 # shift left one bit + add t0,a1,t1 # compute indice to store char in area + addi t3,t3,'0' # conversion byte to ascii char + sb t3,(t0) # store char in area + addi t1,t1,1 # next position + li t0,7 # for add a space separation + beq t2,t0,4f + li t0,15 # for add a space + beq t2,t0,4f + li t0,23 # for add a space + beq t2,t0,4f + j 5f + +4: # store space + li t3,' ' + add t0,a1,t1 + sb t3,(t0) + addi t1,t1,1 +5: + addi t2,t2,1 # increment bit indice + li t0,32 # maxi ? + blt t2,t0,1b # and loop + + add t0,a1,t1 + sb x0,(t0) # final zero +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret +/***************************************************/ +/* register conversion in décimal signed */ +/***************************************************/ +/* a0 value */ +/* a1 result area address size mini 12c */ +/* a0 return result start address */ +/* a1 return characters number in area */ +conversion10S: # INFO: conversion10S + addi sp, sp, -8 # save registers + sw ra, 0(sp) + mv t5,a1 # begin store area + li t6,'+' + bge a0,x0,1f # positive number ? + li t6,'-' # negative + sub a0,x0,a0 # inversion +1: + li t4,LENGTHDEC # area size + add t2,t4,t5 + sb x0,(t2) # final zero + addi t4,t4,-1 # position précedente + li t1,10 +2: + remu t3,a0,t1 # reminder division by 10 + addi t3,t3,48 # conversion ascii + add t2,t4,t5 # compute store indice + sb t3,(t2) + addi t4,t4,-1 # position précedente + divu a0,a0,t1 # division by 10 + bne a0,x0,2b + # store signe in current position + add t2,t4,t5 + sb t6,(t2) +3: + add a0,t4,t5 # return store area begin address + li t0,LENGTHDEC # and size + sub a1,t0,t4 + +100: + lw ra, 0(sp) # restaur registers + addi sp, sp, 8 + ret +/************************************/ +/* string write on connexion usb */ +/***********************************/ +/* a0 String address */ +writeString: # INFO: writeString + addi sp, sp, -8 # save registers on stack + sw ra, 0(sp) + sw s0, 4(sp) + mv s0,a0 # save address +1: + lbu a0,(s0) # load one character + beqz a0,100f # end if zero + call __wrap_putchar # character write + add s0,s0,1 # increment address + j 1b # and loop +100: + lw ra, 0(sp) # restaur registers + lw s0, 4(sp) + addi sp, sp, 8 + ret diff --git a/Task/Bioinformatics-base-count/DuckDB/bioinformatics-base-count.duckdb b/Task/Bioinformatics-base-count/DuckDB/bioinformatics-base-count.duckdb new file mode 100644 index 0000000000..a774d42bcc --- /dev/null +++ b/Task/Bioinformatics-base-count/DuckDB/bioinformatics-base-count.duckdb @@ -0,0 +1,18 @@ +# Filter the contents of the file into a table (id, c) of uppercase letters +create or replace table bases as ( + select row_number() OVER () as id, c + from (select unnest(regexp_extract_all(content, '[A-Z]') ) as c + from read_text('rc-bioinformatics-base-count.txt') ) +); + +.print DNA sequence: +with tbl as (select (id - 1 - mod(id - 1, 50)) as "offset", c from bases) + select "offset", string_agg(c, '') as sequence + from tbl + group by "offset" + order by "offset" ; + +.print +.print Distribution of bases: +select histogram(c), count(*) as N +from bases ; diff --git a/Task/Bioinformatics-base-count/PascalABC.NET/bioinformatics-base-count.pas b/Task/Bioinformatics-base-count/PascalABC.NET/bioinformatics-base-count.pas new file mode 100644 index 0000000000..ddf4a8fef6 --- /dev/null +++ b/Task/Bioinformatics-base-count/PascalABC.NET/bioinformatics-base-count.pas @@ -0,0 +1,14 @@ +## var DNA := ''' +CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG +CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG +AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT +GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT +CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG +TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA +TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT +CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG +TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC +GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT +''';DNA:=DNA.Remove(#13,#10); +var t:=DNA.EachCount.OrderBy(x->x.key).Println.Sum(x->x.value); +Print('total,',t); diff --git a/Task/Biorhythms/Ada/biorhythms.ada b/Task/Biorhythms/Ada/biorhythms.ada new file mode 100644 index 0000000000..8f1fb796b8 --- /dev/null +++ b/Task/Biorhythms/Ada/biorhythms.ada @@ -0,0 +1,65 @@ +with Ada.Calendar; +with Ada.Calendar.Arithmetic; +with Ada.Calendar.Formatting; +with Ada.Command_Line; +with Ada.Numerics; +with Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; + +use Ada.Calendar; +use Ada.Calendar.Arithmetic; +use Ada.Calendar.Formatting; +use Ada.Command_Line; +use Ada.Numerics; +use Ada.Numerics.Elementary_Functions; +use Ada.Text_IO; + +procedure Biorhythms is + Birth_Date : Time := Value (Argument (1) & " 00:00:00"); + Target_Date : Time := Value (Argument (2) & " 00:00:00"); + Days : Day_Count := Target_Date - Birth_Date; + + -- There's not much point having types for these for such a short + -- problem, but in a big program this would be useful to prevent + -- accidentally assigning wrong values. + type Physical_Type is mod 23; + type Emotional_Type is mod 28; + type Mental_Type is mod 33; + type Biorhythm_Type is + record + Physical : Physical_Type; + Emotional : Emotional_Type; + Mental : Mental_Type; + end record; + + function To_Biorhythm (D : Day_Count) return Biorhythm_Type is + ( + Physical_Type (D mod Physical_Type'Modulus), + Emotional_Type (D mod Emotional_Type'Modulus), + Mental_Type (D mod Mental_Type'Modulus) + ); + + Biorhythm : Biorhythm_Type := To_Biorhythm (Days); + + package Float_IO is new Ada.Text_IO.Float_IO (Float); + use Float_IO; + + function To_Percent (F : Float) return Float is + (100.0 * Sin (2.0 * Pi * F)); + + procedure Report_Biorhythm (B : Biorhythm_Type) is + PFrac : Float := Float (B.Physical) / Float (Physical_Type'Modulus); + EFrac : Float := Float (B.Emotional) / Float (Emotional_Type'Modulus); + MFrac : Float := Float (B.Mental) / Float (Mental_Type'Modulus); + Physical : Float := To_Percent (PFrac); + Emotional : Float := To_Percent (EFrac); + Mental : Float := To_Percent (MFrac); + begin + Put_Line ("Age in days: " & Days'Image); + Put ("Physical cycle: "); Put (Physical, 3, 1, 0); Put ("%"); New_Line; + Put ("Emotional cycle: "); Put (Emotional, 3, 1, 0); Put ("%"); New_Line; + Put ("Mental cycle: "); Put (Mental, 3, 1, 0); Put ("%"); New_Line; + end Report_Biorhythm; +begin + Report_Biorhythm (Biorhythm); +end Biorhythms; diff --git a/Task/Biorhythms/EasyLang/biorhythms.easy b/Task/Biorhythms/EasyLang/biorhythms.easy index 8f9bf9a6c9..cebda43194 100644 --- a/Task/Biorhythms/EasyLang/biorhythms.easy +++ b/Task/Biorhythms/EasyLang/biorhythms.easy @@ -27,10 +27,10 @@ proc cycle now cyc t$ col . gcolor col gtext 4 cyc * 1.2 - 20 t$ glinewidth 0.5 + gpenup for d = now - 20 to now + 20 - yp = y y = 50 + 20 * sin (360 * d / cyc) - if x > 0 : gline (x - 2.5) yp x y + glineto x y x += 2.5 . . diff --git a/Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic b/Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic new file mode 100644 index 0000000000..902427a908 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/FreeBASIC/bitcoin-public-point-to-address.basic @@ -0,0 +1,142 @@ +#include "SHA_256.bas" +#include "RIPEMD_160.bas" + +Const BITCOIN_SPECIAL_VALUE As String = "04" +Const BITCOIN_VERSION_NUMBER As String = "00" + +Dim Shared base_map(255) As Integer + +Sub init_base_map() + Dim As Integer i + For i = 0 To 255 + base_map(i) = -1 + Next + For i = 0 To 9 + base_map(Asc("0") + i) = i + Next + For i = 0 To 5 + base_map(Asc("a") + i) = 10 + i + base_map(Asc("A") + i) = 10 + i + Next + For i = 6 To 15 + base_map(Asc("a") + i) = 10 + i + base_map(Asc("A") + i) = 10 + i + Next +End Sub + +Sub hex_to_bytes(text As String, bytes() As Integer) + Dim As Integer first_digit, second_digit + Dim As Integer n = Len(text) \ 2 + Redim bytes(n - 1) + + For i As Integer = 0 To n - 1 + first_digit = base_map(Asc(Mid(text, 2 * i + 1, 1))) + second_digit = base_map(Asc(Mid(text, 2 * i + 2, 1))) + bytes(i) = (first_digit Shl 4) + second_digit + Next +End Sub + +Function vector_to_ascii_string(bytes() As Integer) As String + Dim As String result = "" + + For i As Integer = 0 To Ubound(bytes) + result &= Chr(bytes(i)) + Next + + Return result +End Function + +Sub compute_message_bytes(text As String, out_bytes() As Integer) + Dim As Integer bytes_1() + hex_to_bytes(text, bytes_1()) + + Dim As String ascii_1 = vector_to_ascii_string(bytes_1()) + Dim As String hexSHA_256 = SHA_256(ascii_1) + Dim As Integer bytes_2() + hex_to_bytes(hexSHA_256, bytes_2()) + + Dim As String ascii_2 = vector_to_ascii_string(bytes_2()) + Dim As String hexRIPEMD_160 = BITCOIN_VERSION_NUMBER & RIPEMD_160(ascii_2) + hex_to_bytes(hexRIPEMD_160, out_bytes()) +End Sub + +Sub compute_checksum(bytes() As Integer, out_checksum() As Integer) + Dim As String ascii_1 = vector_to_ascii_string(bytes()) + Dim As String hex_1 = SHA_256(ascii_1) + Dim As Integer bytes_1() + hex_to_bytes(hex_1, bytes_1()) + + Dim As String ascii_2 = vector_to_ascii_string(bytes_1()) + Dim As String hex_2 = SHA_256(ascii_2) + Dim As Integer bytes_2() + hex_to_bytes(hex_2, bytes_2()) + Redim out_checksum(3) + + For i As Integer = 0 To 3 + out_checksum(i) = bytes_2(i) + Next +End Sub + +Function encode_base_58(bytes() As Integer) As String + Const As String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + Const As Integer ALPHABET_SIZE = 58 + Dim As String result = String(34, " ") + Dim As Integer i, j, n, c + Dim As Integer temp() + + Redim As Integer bytes_copy(Ubound(bytes)) + For i = 0 To Ubound(bytes) + bytes_copy(i) = bytes(i) + Next + + For n = Len(result) - 1 To 0 Step -1 + c = 0 + For i = 0 To Ubound(bytes_copy) + c = c * 256 + bytes_copy(i) + bytes_copy(i) = c \ ALPHABET_SIZE + c Mod= ALPHABET_SIZE + Next + Mid(result, n + 1, 1) = Mid(ALPHABET, c + 1, 1) + Next + + ' Quitar los '1' iniciales extra + While Left(result, 2) = "11" + result = Mid(result, 2) + Wend + Return result +End Function + +Function encode_address(x As String, y As String) As String + Dim As String public_point = BITCOIN_SPECIAL_VALUE & x & y + If Len(public_point) <> 130 Then + Print "Invalid public point string" + Exit Function + End If + Dim As Integer message_bytes() + compute_message_bytes(public_point, message_bytes()) + + Dim As Integer checksum() + compute_checksum(message_bytes(), checksum()) + + Dim As Integer i + Dim As Integer full_bytes() + Redim full_bytes(Ubound(message_bytes) + 4) + For i = 0 To Ubound(message_bytes) + full_bytes(i) = message_bytes(i) + Next + For i = 0 To 3 + full_bytes(Ubound(message_bytes) + 1 + i) = checksum(i) + Next + + Return encode_base_58(full_bytes()) +End Function + +' Test Program +init_base_map() + +Dim As String x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352" +Dim As String y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6" + +Print encode_address(x, y) + +Sleep diff --git a/Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js b/Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js new file mode 100644 index 0000000000..1076901568 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/JavaScript/bitcoin-public-point-to-address.js @@ -0,0 +1,52 @@ +const crypto = require('crypto'); + +const digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +function b58(n) { + if (n === 0n) return ''; + return b58(n / 58n) + digits58[Number(n % 58n)]; +} + +function publicPointToAddress(x, y) { + // Convert hex strings to buffers + const xBuffer = Buffer.from(x, 'hex'); + const yBuffer = Buffer.from(y, 'hex'); + + // Create uncompressed public key format (0x04 + x + y) + const publicKey = Buffer.concat([Buffer.from([0x04]), xBuffer, yBuffer]); + + // SHA256 hash + const sha256Hash = crypto.createHash('sha256').update(publicKey).digest(); + + // RIPEMD160 hash + const ripemd160Hash = crypto.createHash('ripemd160').update(sha256Hash).digest(); + + // Add version byte (0x00 for mainnet) + const versionedHash = Buffer.concat([Buffer.from([0x00]), ripemd160Hash]); + + // Double SHA256 for checksum + const checksum = crypto.createHash('sha256') + .update(crypto.createHash('sha256').update(versionedHash).digest()) + .digest() + .slice(0, 4); + + // Combine versioned hash with checksum + const addressBytes = Buffer.concat([versionedHash, checksum]); + + // Convert to BigInt for base58 encoding + let n = 0n; + for (let i = 0; i < addressBytes.length; i++) { + n = (n << 8n) | BigInt(addressBytes[i]); + } + + return b58(n); +} + +// Test with the provided values +if (require.main === module) { + const address = publicPointToAddress( + '50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', + '2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6' + ); + console.log(address); +} diff --git a/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy index 3aaf5eda4f..4d1203c99e 100644 --- a/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy +++ b/Task/Bitmap-B-zier-curves-Quadratic/EasyLang/bitmap-b-zier-curves-quadratic.easy @@ -1,18 +1,16 @@ sysconf topleft proc quadraticbezier x1 y1 x2 y2 x3 y3 nseg . + gpenup for i = 0 to nseg t = i / nseg t1 = 1 - t a = t1 * t1 b = 2 * t * t1 c = t * t - px = x - py = y x = a * x1 + b * x2 + c * x3 + 0.5 y = a * y1 + b * y2 + c * y3 + 0.5 - if i > 0 : gline px py x y + glineto x y . . glinewidth 0.5 -gclear quadraticbezier 1 1 30 37 59 1 100 diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm.pluto b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm.pluto new file mode 100644 index 0000000000..8ab23127e7 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm.pluto @@ -0,0 +1,27 @@ +local canvas = require "canvas" + +local function line(c, x0, y0, x1, y1, col) + local dx = math.abs(x1 - x0) + local dy = math.abs(y1 - y0) + local sx = (x0 < x1) ? 1 : -1 + local sy = (y0 < y1) ? 1 : -1 + local err = (dx > dy ? dx : - dy) // 2 + while true do + c:set(x0, y0, col) + if x0 == x1 and y0 == y1 then break end + local e2 = err + if e2 > -dx then + err -= dy + x0 += sx + end + if e2 < dy then + err += dx + y0 += sy + end + end +end + +local c = canvas.new(400, 400) +c:fill(0xffffff) -- white background +line(c, 0, 0, 399, 399, 0x0000ff) -- draw a red diagonal +io.contents("mybmp.bmp", c:tobmp()) -- save to a bitmap file diff --git a/Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy b/Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy new file mode 100644 index 0000000000..2e0418ae0b --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/EasyLang/bitmap-midpoint-circle-algorithm.easy @@ -0,0 +1,27 @@ +proc pix x y . + grect x / 5 y / 5 0.25 0.25 +. +proc circ x0 y0 r . + t1 = r div 16 + x = r + while x >= y + pix x0 - x, y0 + y + pix x0 - x, y0 - y + pix x0 - y, y0 + x + pix x0 - y, y0 - x + pix x0 + x, y0 + y + pix x0 + x, y0 - y + pix x0 + y, y0 + x + pix x0 + y, y0 - x + y += 1 + t1 += y + t2 = t1 - x + if t2 >= 0 + t1 = t2 + x -= 1 + . + . +. +for r = 20 step 20 to 240 + circ 250 250 r +. diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl index 5b1e33d063..1295233abb 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl +++ b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.jl @@ -1,3 +1,5 @@ +using Images, ImageView + function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) where T x = radius - 1 y = 0 @@ -24,8 +26,6 @@ function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) wher return img end -# Test -using Images - img = fill(Gray(255.0), 25, 25); drawcircle!(img, Gray(0.0), 12, 12, 12) +imshow(img) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm.pluto b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm.pluto new file mode 100644 index 0000000000..c0d4f3ed9c --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm.pluto @@ -0,0 +1,33 @@ +local canvas = require "canvas" + +local function trunc(x) return x >= 0 ? math.floor(x) : math.ceil(x) end + +local function circle(c, cx, cy, r, col) + local d = trunc((5 - r * 4) / 4) + local x = 0 + local y = r + repeat + c:set(cx + x, cy + y, col) + c:set(cx + x, cy - y, col) + c:set(cx - x, cy + y, col) + c:set(cx - x, cy - y, col) + c:set(cx + y, cy + x, col) + c:set(cx + y, cy - x, col) + c:set(cx - y, cy + x, col) + c:set(cx - y, cy - x, col) + if d < 0 then + d += 2 * x + 1 + else + d += 2 * (x - y) + 1 + y -= 1 + end + ++x + until x > y +end + +local c = canvas.new(400, 400) +c:fill(0xffffff) -- white background + +-- Draw a blue circle with centre at (200, 200) and radius 100. +circle(c, 200, 200, 100, 0xff0000) +io.contents("mybmp.bmp", c:tobmp()) -- save to a bitmap file diff --git a/Task/Bitmap/Pluto/bitmap.pluto b/Task/Bitmap/Pluto/bitmap.pluto new file mode 100644 index 0000000000..8901f27d06 --- /dev/null +++ b/Task/Bitmap/Pluto/bitmap.pluto @@ -0,0 +1,23 @@ +local canvas = require "canvas" + +-- Create a new canvas object: 400 pixels wide and 400 pixels high. +local c = canvas.new(400, 400) + +-- Color the whole canvas blue. +c:fill(0xff0000) + +-- Draw a red square in the middle. +for i = 1, 51 do + for j = 1, 51 do + c:set(174 + i, 174 + j, 0x0000ff) + end +end + +-- Print to the terminal the color (as an integer) of a pixel. +print(c:get(200, 200)) -- 255 + +-- Convert the canvas to a BMP image. +local image = c:tobmp() + +-- Save the image to a file. +io.contents("mybmp.bmp", image) diff --git a/Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb b/Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb new file mode 100644 index 0000000000..df8d7f60c4 --- /dev/null +++ b/Task/Bitwise-IO/DuckDB/bitwise-io-1.duckdb @@ -0,0 +1,8 @@ +# s should be a bitstring. +# Right-pad s with 0s so that the length of the output string is a multiple of 8. +CREATE OR REPLACE FUNCTION print_bits(s) as ( + format('{:0<{}}', s, (ceil(length(s) / 8) * 8)::INT) +); + +# Example: +select print_bits('101'::BITSTRING); diff --git a/Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb b/Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb new file mode 100644 index 0000000000..57ab55eb4d --- /dev/null +++ b/Task/Bitwise-IO/DuckDB/bitwise-io-2.duckdb @@ -0,0 +1,13 @@ +# "Compress" a string by printing it as a bitstring without the left-most bit of each byte +CREATE OR REPLACE FUNCTION sevenbits(str) as ( + select string_agg(format('{}', ascii(s)::BITSTRING)[-7:], '') + from (select unnest(regexp_extract_all(str, '.')) as s) +); + +# Undo sevenbits() +CREATE OR REPLACE FUNCTION from_sevenbits(str) as ( + select string_agg(chr(s::BIT::INT), '') + from (select unnest(regexp_extract_all(str, '.......')) as s) +); + +select from_sevenbits(sevenbits('abracadabra')); diff --git a/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg b/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg index 7fdf9b8d88..ea11b79d5f 100644 --- a/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg +++ b/Task/Bitwise-operations/ALGOL-68/bitwise-operations-1.alg @@ -1,8 +1,13 @@ -main:( +BEGIN + + BITS all bits mask = NOT 16r0; + LONG BITS long bits mask = LENG all bits mask; PRIO SLC = 8, SRC = 8; # SLC and SRC are not built in, define and overload them here # OP SLC = (BITS b, INT rotate) BITS: b SHL rotate OR b SHR ( bits width - rotate ); - OP SRC = (BITS b, INT rotate) BITS: b SHR rotate OR b SHL ( bits width - rotate ); + OP SRC = (BITS b, INT rotate) BITS: b SHR rotate OR SHORTEN ( long bits mask + AND ( LENG b SHL ( bits width - rotate ) ) + ); # SRC and SRL are non-standard, but versions are built in to ALGOL 68R's standard prelude # PRIO XOR = 2; @@ -10,7 +15,10 @@ main:( # XOR is non-standard, but a version is built in to ALGOL 68G's standard prelude # # ALGOL 68 has 5 different ways of representing a BINary BITS - Bases: 2, 4, 8, 16 and flip/flop # - FORMAT b5 = $"2r"2r32d," 4r"4r16d," 8r"8r11d," 16r"16r8d," "gl$; + FORMAT b5 = IF bits width > 32 + THEN $"2r"2r64d," 4r"4r32d,l" 8r"8r22d," 16r"16r16d,l" "gl$ + ELSE $"2r"2r32d," 4r"4r16d," 8r"8r11d," 16r"16r8d,l" "gl$ + FI; OP BBBBB = (BITS b)[]BITS: (b,b,b,b,b); PROC bitwise = (BITS a, BITS b, INT shift)VOID: @@ -61,4 +69,4 @@ CO bitwise(8r377,8r252,5); bitwise(16rff,16raa,5) END CO -) +END diff --git a/Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb b/Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb new file mode 100644 index 0000000000..d81bf307e5 --- /dev/null +++ b/Task/Bitwise-operations/DuckDB/bitwise-operations-1.duckdb @@ -0,0 +1,5 @@ +create or replace function task(a,b) as table ( + select a, b, a&b, a|b, xor(a, b), ~a, a << b, a >> b +); + +from task(10, 2); diff --git a/Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb b/Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb new file mode 100644 index 0000000000..2e48fb4dd1 --- /dev/null +++ b/Task/Bitwise-operations/DuckDB/bitwise-operations-2.duckdb @@ -0,0 +1,5 @@ +select 10 as v, + ~(v::BITSTRING), + ~(v::INT) as "~INT", + ~(v::BIGINT) as "~BIGINT", + ~(10::UINTEGER) as "~UINTEGER"; diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index 941e955022..7c1422857a 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -2,18 +2,18 @@ import extensions; extension testOp { - bitwiseTest(y) - { - console.printLine(self," and ",y," = ",self & y); - console.printLine(self," or ",y," = ",self | y); - console.printLine(self," xor ",y," = ",self ^ y); - console.printLine("not ",self," = ",self.BInverted); - console.printLine(self," shr ",y," = ",self.shiftRight(y)); - console.printLine(self," shl ",y," = ",self.shiftLeft(y)); - } + bitwiseTest(y) + { + Console.printLine(self," and ",y," = ",self.band(y)); + Console.printLine(self," or ",y," = ",self.bor(y)); + Console.printLine(self," xor ",y," = ",self.bxor(y)); + Console.printLine("not ",self," = ",self.BInverted); + Console.printLine(self," shr ",y," = ",self.shiftRight(y)); + Console.printLine(self," shl ",y," = ",self.shiftLeft(y)); + } } public program() { - console.loadLineTo(new Integer()).bitwiseTest(console.loadLineTo(new Integer())) + Console.loadLineTo(new Integer()).bitwiseTest(Console.loadLineTo(new Integer())) } diff --git a/Task/Bitwise-operations/Icon/bitwise-operations.icon b/Task/Bitwise-operations/Icon/bitwise-operations.icon index 4bcace1afa..92610583bb 100644 --- a/Task/Bitwise-operations/Icon/bitwise-operations.icon +++ b/Task/Bitwise-operations/Icon/bitwise-operations.icon @@ -1,3 +1,5 @@ +link bitint # for int2bit + procedure main() bitdemo(255,2) bitdemo(-15,3) diff --git a/Task/Bitwise-operations/Pluto/bitwise-operations.pluto b/Task/Bitwise-operations/Pluto/bitwise-operations.pluto new file mode 100644 index 0000000000..a42f1b211c --- /dev/null +++ b/Task/Bitwise-operations/Pluto/bitwise-operations.pluto @@ -0,0 +1,20 @@ +-- Rotate left and right are not built-in but we use the +-- same 32-bit substitutes as in the Lua 5.3+ example. +local function rl(x, y) return ((x << y) & 0xffffffff) | (x >> (32 - y)) end + +local function rr(x, y) return (x >> y) | ((x << (32 - y)) & 0xffffffff) end + +local function bitwise(x, y) + print($" x = {x}") + print($" y = {y}") + print($" x & y = {x & y}") + print($" x | y = {x | y}") + print($" x ~ y = {x ~ y}") + print($"~x = {~x}") + print($" x << y = {x << y}") + print($" x >> y = {x >> y}") + print($" x rl y = {rl(x, y)}") + print($" x rr y = {rr(x, y)}") +end + +bitwise(10, 2) diff --git a/Task/Boolean-values/ArkScript/boolean-values.ark b/Task/Boolean-values/ArkScript/boolean-values.ark new file mode 100644 index 0000000000..d92c5993bd --- /dev/null +++ b/Task/Boolean-values/ArkScript/boolean-values.ark @@ -0,0 +1,14 @@ +(let test (fun (v) { + (puts v ": ") + (if v (print true) (print false)) })) + + +(test 1) +(test 0) +(test true) +(test false) +(test "hello") +(test "") +(test [1 2 3]) +(test []) +(test nil) diff --git a/Task/Boolean-values/Haxe/boolean-values.haxe b/Task/Boolean-values/Haxe/boolean-values.haxe new file mode 100644 index 0000000000..c2f8a2ed4c --- /dev/null +++ b/Task/Boolean-values/Haxe/boolean-values.haxe @@ -0,0 +1,8 @@ +class Main { + static public function main():Void { + var t = true; + var f = false; + $type(t); + $type(f); + } +} diff --git a/Task/Boolean-values/Prolog/boolean-values.pro b/Task/Boolean-values/Prolog/boolean-values.pro new file mode 100644 index 0000000000..361f023ab6 --- /dev/null +++ b/Task/Boolean-values/Prolog/boolean-values.pro @@ -0,0 +1,2 @@ +?- ( Bool = true ; Bool = false ), + ( Bool -> bool_is_true ; bool_is_false ). diff --git a/Task/Boolean-values/Zig/boolean-values.zig b/Task/Boolean-values/Zig/boolean-values.zig new file mode 100644 index 0000000000..f7b10d4ab0 --- /dev/null +++ b/Task/Boolean-values/Zig/boolean-values.zig @@ -0,0 +1,15 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + const bool1: bool = true; + const bool2: bool = false; + const bool3 = 2 + 2 == 4; + const bool4 = 2 + 2 == 5; + + try stdout.print("{any}\n", .{bool1}); + try stdout.print("{any}\n", .{bool2}); + try stdout.print("{any} {any}\n", .{@TypeOf(bool3), bool3}); + try stdout.print("{any} {any}\n", .{@TypeOf(bool4), bool4}); +} diff --git a/Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.ada b/Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.ada new file mode 100644 index 0000000000..3c23105aee --- /dev/null +++ b/Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.ada @@ -0,0 +1,63 @@ +with Ada.Text_IO; + +with GNATColl.Boyer_Moore; + +procedure Boyermoore is + + procedure Search_All (Needle : in String; + Haystack : in String) + is + use Ada.Text_IO; + use GNATColl.Boyer_Moore; + + Found : String (Haystack'Range) := (others => ' '); + Count : Natural := 0; + Motif : Pattern; + First : Positive := Haystack'First; + Position : Integer; + begin + Put_Line ("Needle : " & Needle); + Put_Line ("Haystack: " & Haystack); + Put ("Found : "); + + Compile (Motif => Motif, + From_String => Needle, + Case_Sensitive => True); + loop + Position := Search (Motif => Motif, + In_String => Haystack (First .. Haystack'Last)); + exit when Position = -1; + + Count := Count + 1; + Found (Position .. Position + Needle'Length - 1) := (others => '^'); + First := Position + 1; + end loop; + + Free (Motif); + + if Count = 0 then + Put_Line (""); + else + Put_Line (Found); + end if; + New_Line; + end Search_All; + + Text_1 : constant String := "InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented"; + + Text_2 : constant String := "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk."; + + Text_3 : constant String := "GCTAGCTCTACGAGTCTA"; + Text_4 : constant String := "GGCTATAATGCGTA"; + Text_5 : constant String := "there would have been a time for such a word"; + Text_6 : constant String := "needle need noodle needle"; + +begin + Search_All ("put", Text_1); + Search_All ("and", Text_1); + Search_All ("alfalfa", Text_2); + Search_All ("TCTA", Text_3); + Search_All ("TAATAAA", Text_4); + Search_All ("word", Text_5); + Search_All ("needle", Text_6); +end Boyermoore; diff --git a/Task/Boyer-Moore-string-search/Dart/boyer-moore-string-search.dart b/Task/Boyer-Moore-string-search/Dart/boyer-moore-string-search.dart new file mode 100644 index 0000000000..24e59c3692 --- /dev/null +++ b/Task/Boyer-Moore-string-search/Dart/boyer-moore-string-search.dart @@ -0,0 +1,80 @@ +import 'dart:convert'; // for jsonEncode (used to mimic std::quoted) +import 'dart:io'; + +/// Prints a list of integers in the form `[1, 2, 3]`. +void display(List numbers) { + final joined = numbers.join(', '); + print('[$joined]'); +} + +/// Returns the first index of `needle` inside `haystack`, +/// or -1 if `needle` cannot be found. +int stringSearchSingle(String haystack, String needle) { + final idx = haystack.indexOf(needle); + return idx >= 0 ? idx : -1; +} + +/// Returns **all** non‑overlapping start indexes of `needle` inside `haystack`. +List stringSearch(String haystack, String needle) { + final List result = []; + + int start = 0; // where we continue searching from + int index = 0; // result of the latest search + + // Keep searching while we still find matches and we haven’t run off the end. + while (start < haystack.length && (index = stringSearchSingle( + haystack.substring(start), needle)) >= 0) { + final absoluteIdx = start + index; + result.add(absoluteIdx); + // Move past the match we just found so the next search starts after it. + start = absoluteIdx + needle.length; + } + + return result; +} + +void main() { + // --------------------------------------------------------------------------- + // 1️⃣ The data (identical to the C++ version) + // --------------------------------------------------------------------------- + const List texts = [ + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + ]; + + const List patterns = [ + "TCTA", + "TAATAAA", + "word", + "needle", + "and", + "alfalfa" + ]; + + // --------------------------------------------------------------------------- + // 2️⃣ Print the original texts (mirrors the first loop in C++). + // --------------------------------------------------------------------------- + for (var i = 0; i < texts.length; ++i) { + print('text${i + 1} = ${texts[i]}'); + } + print(''); // blank line like the C++ program + + // --------------------------------------------------------------------------- + // 3️⃣ Search each pattern in its corresponding text and print the results. + // --------------------------------------------------------------------------- + for (var i = 0; i < texts.length; ++i) { + final List indexes = stringSearch(texts[i], patterns[i]); + + // `jsonEncode` adds double quotes around a string and escapes characters, + // which behaves like `std::quoted` in C++. + final quotedPattern = jsonEncode(patterns[i]); + + stdout.write( + 'Found $quotedPattern in \'text${i + 1}\' at indexes '); + display(indexes); + } +} diff --git a/Task/Boyer-Moore-string-search/FutureBasic/boyer-moore-string-search.basic b/Task/Boyer-Moore-string-search/FutureBasic/boyer-moore-string-search.basic new file mode 100644 index 0000000000..6062c467ce --- /dev/null +++ b/Task/Boyer-Moore-string-search/FutureBasic/boyer-moore-string-search.basic @@ -0,0 +1,55 @@ +include "NSLog.incl" + +NSInteger local fn String_Search_Single( haystack as CFStringRef, needle as CFStringRef ) + CFRange range = fn StringRangeOfString( haystack, needle ) + return range.location +end fn = 0 + +CFArrayRef local fn String_Search( haystack as CFStringRef, needle as CFStringRef ) + CFMutableArrayRef result = fn MutableArrayNew + NSUInteger start = 0 + NSInteger index = 0 + + while ( index >= 0 && start < len(haystack) ) + CFStringRef haystackReduced = fn StringSubstringFromIndex( haystack, start ) + index = fn String_Search_Single( haystackReduced, needle ) + if ( index != NSNotFound ) + MutableArrayAddObject( result, @(start + index) ) + start += index + len(needle) + else + break + end if + wend + return result +end fn = 0 + +void local fn FindNeedlesInHaystacks + NSUInteger i + + CFArrayRef texts = @[ + @"GCTAGCTCTACGAGTCTA", + @"GGCTATAATGCGTA", + @"there would have been a time for such a word", + @"needle need noodle needle", + @"DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + @"Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + ] + + CFArrayRef patterns = @[@"TCTA", @"TAATAAA", @"word", @"needle", @"and", @"alfalfa"] + + for i = 0 to fn ArrayCount(texts) - 1 + NSLog( @"text%lu = %@", (unsigned long)(i + 1), texts[i] ) + next + + NSLog( @"" ) + + for i = 0 to fn ArrayCount(texts) - 1 + CFArrayRef indexes = fn String_Search( texts[i], patterns[i] ) + NSLog( @"Found \"%@\" in 'text%lu' at indexes \b", patterns[i], (unsigned long)(i + 1) ) + NSLog( @"[%@]", fn ArrayComponentsJoinedByString( indexes, @", " ) ) + next +end fn + +fn FindNeedlesInHaystacks + +HandleEvents diff --git a/Task/Boyer-Moore-string-search/Kotlin/boyer-moore-string-search.kts b/Task/Boyer-Moore-string-search/Kotlin/boyer-moore-string-search.kts new file mode 100644 index 0000000000..e7cf98b9ac --- /dev/null +++ b/Task/Boyer-Moore-string-search/Kotlin/boyer-moore-string-search.kts @@ -0,0 +1,50 @@ +fun display(numbers: List) { + println("[${numbers.joinToString(", ")}]") +} + +fun stringSearchSingle(haystack: String, needle: String): Int { + val index = haystack.indexOf(needle) + return if (index != -1) index else -1 +} + +fun stringSearch(haystack: String, needle: String): List { + val result = mutableListOf() + var start = 0 + var index = 0 + + while (index >= 0 && start < haystack.length) { + val haystackReduced = haystack.substring(start) + index = stringSearchSingle(haystackReduced, needle) + + if (index >= 0) { + result.add(start + index) + start += index + needle.length + } + } + + return result +} + +fun main() { + val texts = listOf( + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + ) + + val patterns = listOf("TCTA", "TAATAAA", "word", "needle", "and", "alfalfa") + + texts.forEachIndexed { i, text -> + println("text${i + 1} = $text") + } + println() + + texts.forEachIndexed { i, text -> + val indexes = stringSearch(text, patterns[i]) + print("Found \"${patterns[i]}\" in 'text${i + 1}' at indexes ") + display(indexes) + } +} diff --git a/Task/Boyer-Moore-string-search/Swift/boyer-moore-string-search.swift b/Task/Boyer-Moore-string-search/Swift/boyer-moore-string-search.swift new file mode 100644 index 0000000000..76d2327ef7 --- /dev/null +++ b/Task/Boyer-Moore-string-search/Swift/boyer-moore-string-search.swift @@ -0,0 +1,59 @@ +import Foundation + +func display(_ numbers: [Int32]) { + let numbersStr = numbers.map { String($0) }.joined(separator: ", ") + print("[\(numbersStr)]") +} + +func stringSearchSingle(_ haystack: String, _ needle: String) -> Int32 { + guard let range = haystack.range(of: needle) else { + return -1 + } + return Int32(haystack.distance(from: haystack.startIndex, to: range.lowerBound)) +} + +func stringSearch(_ haystack: String, _ needle: String) -> [Int32] { + var result: [Int32] = [] + var start = 0 + var index: Int32 = 0 + + while index >= 0 && start < haystack.count { + let startIndex = haystack.index(haystack.startIndex, offsetBy: start) + let haystackReduced = String(haystack[startIndex...]) + index = stringSearchSingle(haystackReduced, needle) + + if index >= 0 { + result.append(Int32(start) + index) + start += Int(index) + needle.count + } + } + + return result +} + +func main() { + let texts = [ + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + ] + + let patterns = ["TCTA", "TAATAAA", "word", "needle", "and", "alfalfa"] + + for (i, text) in texts.enumerated() { + print("text\(i + 1) = \(text)") + } + print() + + for (i, text) in texts.enumerated() { + let indexes = stringSearch(text, patterns[i]) + print("Found \"\(patterns[i])\" in 'text\(i + 1)' at indexes ", terminator: "") + display(indexes) + } +} + +// Call main function +main() diff --git a/Task/Boyer-Moore-string-search/Zig/boyer-moore-string-search.zig b/Task/Boyer-Moore-string-search/Zig/boyer-moore-string-search.zig new file mode 100644 index 0000000000..29a4cd7704 --- /dev/null +++ b/Task/Boyer-Moore-string-search/Zig/boyer-moore-string-search.zig @@ -0,0 +1,71 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +fn display(numbers: []const i32) void { + print("[", .{}); + for (numbers, 0..) |num, i| { + if (i > 0) { + print(", ", .{}); + } + print("{}", .{num}); + } + print("]\n", .{}); +} + +fn stringSearchSingle(haystack: []const u8, needle: []const u8) i32 { + if (std.mem.indexOf(u8, haystack, needle)) |index| { + return @intCast(index); + } + return -1; +} + +fn stringSearch(allocator: Allocator, haystack: []const u8, needle: []const u8) !ArrayList(i32) { + var result = ArrayList(i32).init(allocator); + var start: usize = 0; + + while (start < haystack.len) { + const haystack_reduced = haystack[start..]; + const index = stringSearchSingle(haystack_reduced, needle); + + if (index >= 0) { + try result.append(@as(i32, @intCast(start)) + index); + start += @as(usize, @intCast(index)) + needle.len; + } else { + break; + } + } + + return result; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const texts = [_][]const u8{ + "GCTAGCTCTACGAGTCTA", + "GGCTATAATGCGTA", + "there would have been a time for such a word", + "needle need noodle needle", + "DKnuthusesandprogramsanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguages", + "Nearby farms grew an acre of alfalfa on the dairy's behalf, with bales of that alfalfa exchanged for milk." + }; + + const patterns = [_][]const u8{"TCTA", "TAATAAA", "word", "needle", "and", "alfalfa"}; + + for (texts, 0..) |text, i| { + print("text{} = {s}\n", .{ i + 1, text }); + } + print("\n" ,.{}); + + for (texts, 0..) |text, i| { + var indexes = try stringSearch(allocator, text, patterns[i]); + defer indexes.deinit(); + + print("Found \"{s}\" in 'text{}' at indexes ", .{ patterns[i], i + 1 }); + display(indexes.items); + } +} diff --git a/Task/Break-OO-privacy/Dart/break-oo-privacy.dart b/Task/Break-OO-privacy/Dart/break-oo-privacy.dart new file mode 100644 index 0000000000..d9db598356 --- /dev/null +++ b/Task/Break-OO-privacy/Dart/break-oo-privacy.dart @@ -0,0 +1,38 @@ +class CFactory { + int _count = 0; + + CFactory(); + + int get count => _count; + + CWidget getWidget() { + return CWidget._(this); + } +} + +class CWidget { + final CFactory _parent; + + // Private constructor - only accessible from CFactory + CWidget._(this._parent) { + _parent._count++; + print('Widget spawning. There are now ${_parent._count} Widgets instantiated.'); + } + + void dispose() { + _parent._count--; + print('Widget dying. There are now ${_parent._count} Widgets instantiated.'); + } +} + +void main() { + final factory = CFactory(); + + final widget1 = factory.getWidget(); + final widget2 = factory.getWidget(); + widget1.dispose(); + + final widget3 = factory.getWidget(); + widget3.dispose(); + widget2.dispose(); +} diff --git a/Task/Break-OO-privacy/JavaScript/break-oo-privacy.js b/Task/Break-OO-privacy/JavaScript/break-oo-privacy.js new file mode 100644 index 0000000000..12953361a7 --- /dev/null +++ b/Task/Break-OO-privacy/JavaScript/break-oo-privacy.js @@ -0,0 +1,54 @@ +class CFactory { + constructor() { + this.m_uiCount = 0; + } + + // Destructor equivalent - not needed in JS due to garbage collection + // but included for completeness + destroy() { + // Could perform cleanup here if needed + } + + getWidget() { + // Create a new CWidget, tell it we're its parent + return new CWidget(this); + } +} + +class CWidget { + constructor(parent) { + if (!parent || !(parent instanceof CFactory)) { + throw new Error("CWidget requires a CFactory parent"); + } + + this.m_parent = parent; + ++this.m_parent.m_uiCount; + + console.log(`Widget spawning. There are now ${this.m_parent.m_uiCount} Widgets instantiated.`); + } + + // Destructor equivalent + destroy() { + --this.m_parent.m_uiCount; + console.log(`Widget dying. There are now ${this.m_parent.m_uiCount} Widgets instantiated.`); + } +} + +// Main function equivalent +function main() { + const factory = new CFactory(); + + const pWidget1 = factory.getWidget(); + const pWidget2 = factory.getWidget(); + pWidget1.destroy(); // Equivalent to delete pWidget1 + + const pWidget3 = factory.getWidget(); + pWidget3.destroy(); // Equivalent to delete pWidget3 + pWidget2.destroy(); // Equivalent to delete pWidget2 + + // Optional: cleanup factory + factory.destroy(); +} + +// Run the main function +main(); diff --git a/Task/Break-OO-privacy/Rust/break-oo-privacy.rs b/Task/Break-OO-privacy/Rust/break-oo-privacy.rs new file mode 100644 index 0000000000..be583ca5e9 --- /dev/null +++ b/Task/Break-OO-privacy/Rust/break-oo-privacy.rs @@ -0,0 +1,62 @@ +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +pub struct Factory { + count: RefCell, +} + +pub struct Widget { + parent: Weak, +} + +impl Factory { + pub fn new() -> Rc { + Rc::new(Factory { + count: RefCell::new(0), + }) + } + + pub fn get_widget(self: &Rc) -> Widget { + Widget::new(Rc::downgrade(self)) + } + + fn increment_count(&self) { + *self.count.borrow_mut() += 1; + println!("Widget spawning. There are now {} Widgets instantiated.", self.count.borrow()); + } + + fn decrement_count(&self) { + *self.count.borrow_mut() -= 1; + println!("Widget dying. There are now {} Widgets instantiated.", self.count.borrow()); + } +} + +impl Widget { + fn new(parent: Weak) -> Self { + if let Some(factory) = parent.upgrade() { + factory.increment_count(); + } + + Widget { parent } + } +} + +impl Drop for Widget { + fn drop(&mut self) { + if let Some(factory) = self.parent.upgrade() { + factory.decrement_count(); + } + } +} + +fn main() { + let factory = Factory::new(); + + let widget1 = factory.get_widget(); + let widget2 = factory.get_widget(); + drop(widget1); + + let widget3 = factory.get_widget(); + drop(widget3); + drop(widget2); +} diff --git a/Task/Break-OO-privacy/Zig/break-oo-privacy.zig b/Task/Break-OO-privacy/Zig/break-oo-privacy.zig new file mode 100644 index 0000000000..9542d4d37c --- /dev/null +++ b/Task/Break-OO-privacy/Zig/break-oo-privacy.zig @@ -0,0 +1,88 @@ +const std = @import("std"); +const print = std.debug.print; +const Allocator = std.mem.Allocator; + +const Factory = struct { + count: u32, + allocator: Allocator, + ref_count: u32, + + const Self = @This(); + + pub fn create(allocator: Allocator) !*Self { + const factory = try allocator.create(Self); + factory.* = Self{ + .count = 0, + .allocator = allocator, + .ref_count = 1, + }; + return factory; + } + + pub fn retain(self: *Self) *Self { + self.ref_count += 1; + return self; + } + + pub fn release(self: *Self) void { + self.ref_count -= 1; + if (self.ref_count == 0) { + self.allocator.destroy(self); + } + } + + pub fn getWidget(self: *Self) !Widget { + return Widget.create(self); + } + + fn incrementCount(self: *Self) void { + self.count += 1; + print("Widget spawning. There are now {} Widgets instantiated.\n", .{self.count}); + } + + fn decrementCount(self: *Self) void { + self.count -= 1; + print("Widget dying. There are now {} Widgets instantiated.\n", .{self.count}); + } +}; + +const Widget = struct { + parent: ?*Factory, + + const Self = @This(); + + pub fn create(parent: *Factory) Self { + _ = parent.retain(); // Increment parent's reference count + parent.incrementCount(); + + return Self{ + .parent = parent, + }; + } + + pub fn deinit(self: *Self) void { + if (self.parent) |parent| { + parent.decrementCount(); + parent.release(); + self.parent = null; + } + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const factory = try Factory.create(allocator); + defer factory.release(); + + var widget1 = try factory.getWidget(); + var widget2 = try factory.getWidget(); + + widget1.deinit(); + + var widget3 = try factory.getWidget(); + widget3.deinit(); + widget2.deinit(); +} diff --git a/Task/Brownian-tree/EasyLang/brownian-tree.easy b/Task/Brownian-tree/EasyLang/brownian-tree.easy index 821e4bcf89..b5012e14d2 100644 --- a/Task/Brownian-tree/EasyLang/brownian-tree.easy +++ b/Task/Brownian-tree/EasyLang/brownian-tree.easy @@ -1,30 +1,30 @@ -gcolor3 0 1 1 len f[] 200 * 200 -grect 50 50 0.5 0.5 -f[100 * 200 + 100] = 1 -n = 9000 +func get x y . + return f[y * 200 + x + 1] +. +proc set x y . + grect x / 2 y / 2 0.5 0.5 + f[y * 200 + x + 1] = 1 +. +gcolor 599 +set 100 100 +n = 6000 while i < n repeat x = random 200 - 1 y = random 200 - 1 - until f[y * 200 + x + 1] <> 1 + until get x y <> 1 . while 1 = 1 xo = x yo = y x += random 3 - 2 y += random 3 - 2 - if x < 0 or y < 0 or x >= 200 or y >= 200 - break 1 - . - if f[y * 200 + x + 1] = 1 - grect xo / 2 yo / 2 0.5 0.5 - f[yo * 200 + xo + 1] = 1 + if x < 0 or y < 0 or x >= 200 or y >= 200 : break 1 + if get x y = 1 + set xo yo i += 1 - if i mod 16 = 0 - gcolor3 0.2 + i / n 1 1 - sleep 0 - . + if i mod 100 = 0 : sleep 0 break 1 . . diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index c21e80a79d..1d02177dd7 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -17,7 +17,7 @@ class GameMaster ask() { - var row := console.print("Your Guess #",_attempt," ?").readLine(); + var row := Console.print("Your Guess #",_attempt," ?").readLine(); ^ row.toArray() } @@ -40,7 +40,7 @@ class GameMaster var number := ch.toString().toInt(); // check range - ifnot (number > 0 && number < 10) + if:not (number > 0 && number < 10) { InvalidArgumentException.raise() }; // check duplicates @@ -68,12 +68,12 @@ class GameMaster }; bulls => - -1 { console.printLine("Not a valid guess."); ^ true } - 4 { console.printLine("Congratulations! You have won!"); ^ false } - ! { + -1 : { Console.printLine("Not a valid guess."); ^ true } + 4 : { Console.printLine("Congratulations! You have won!"); ^ false } + ! : { _attempt.append(1); - console.printLine("Your Score is ",bulls," bulls and ",cows," cows"); + Console.printLine("Your Score is ",bulls," bulls and ",cows," cows"); ^ true } @@ -88,5 +88,5 @@ public program() process.doWhile(); - console.readChar() + Console.readChar() } diff --git a/Task/Bulls-and-cows/J/bulls-and-cows-1.j b/Task/Bulls-and-cows/J/bulls-and-cows-1.j index 3384f1c33b..a39d72af95 100644 --- a/Task/Bulls-and-cows/J/bulls-and-cows-1.j +++ b/Task/Bulls-and-cows/J/bulls-and-cows-1.j @@ -1,5 +1,5 @@ output=. ['Bulls: '&,:@'Cows: 'echo@,.":@,. valid =. *./@e.&Num_j_*.4=# -guess =. 0 ".&> [: > $:^:(-.@valid)@(1!:1@1)@echo@'Guess:'t.0 +guess =. 0 ".&> $:^:(-.@valid)@(1!:1@1)@echo@'Guess:'{{x u y}} game =. [ $:^:(4 0-.@-:]) [ (+/@:= output@, e. +/@:*. ~:) guess moo =. 'You win!'[ (1+4?9:) game ] diff --git a/Task/CRC-32/FutureBasic/crc-32.basic b/Task/CRC-32/FutureBasic/crc-32.basic new file mode 100644 index 0000000000..3ca9fab1e9 --- /dev/null +++ b/Task/CRC-32/FutureBasic/crc-32.basic @@ -0,0 +1,46 @@ +// +// CRC_32 Checksum +// +// FutureBasic 7.0.34, August 2025 R.W +//---------------------------------------------- + +// Get CRC_32 checksum from a CFstring +// using the standard bits reversed 0x04C11DB7 + +// Verified accuracy using the site +// https://codeshack.io/crc32-checksum-generator/ + +local fn getCRC_32 (textStr As CFStringRef) As UInt32 + UInt32 i, j, crc, byte + crc = 0xFFFFFFFF + + for i = 0 to len(textStr) -1 + byte = ucc(textStr, i) + crc = crc XOR byte + for j = 0 to 7 + if ( crc AND 1 ) + crc = (crc >> 1) XOR 0xEDB88320 + else + crc = crc >> 1 + end if + next + next + crc = crc XOR 0xFFFFFFFF +end fn = crc + + +window 1,@"CRC checksum" + +CFStringRef testString +testString = @"The quick brown fox jumps over the lazy dog" + +UInt32 checksum +checksum = fn getCRC_32(testString) + +print +print @" ";testString +print @" has a checksum of ";hex(checksum) + +handleEvents + +// diff --git a/Task/CRC-32/Pluto/crc-32.pluto b/Task/CRC-32/Pluto/crc-32.pluto new file mode 100644 index 0000000000..310616ad92 --- /dev/null +++ b/Task/CRC-32/Pluto/crc-32.pluto @@ -0,0 +1,5 @@ +local crypto = require "crypto" +local fmt = require "fmt" + +local str = "The quick brown fox jumps over the lazy dog" +print(fmt.hex(crypto.crc32(str))) diff --git a/Task/CRC-32/R/crc-32.r b/Task/CRC-32/R/crc-32.r index a8bdc5c253..36236927d7 100644 --- a/Task/CRC-32/R/crc-32.r +++ b/Task/CRC-32/R/crc-32.r @@ -1 +1,2 @@ +library(digest) digest("The quick brown fox jumps over the lazy dog","crc32", serialize=F) diff --git a/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb new file mode 100644 index 0000000000..dd05c0680d --- /dev/null +++ b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-1.duckdb @@ -0,0 +1,5 @@ +create or replace table csv as +from read_csv_auto('rc-csv-data-manipulation.csv'); + +# View the first row of the table: +from csv limit 1; diff --git a/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb new file mode 100644 index 0000000000..5078ee97a4 --- /dev/null +++ b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-2.duckdb @@ -0,0 +1,4 @@ +copy + (select *, (C1 + C2 + C3 + C4 + C5) as sum + from csv) + to 'junk.csv'; diff --git a/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb new file mode 100644 index 0000000000..b3c1bedcf5 --- /dev/null +++ b/Task/CSV-data-manipulation/DuckDB/csv-data-manipulation-3.duckdb @@ -0,0 +1,6 @@ +ALTER TABLE csv ADD COLUMN sum integer; + +UPDATE csv +SET sum = C1 + C2 + C3 + C4 + C5; + +copy csv to 'junk2.csv'; diff --git a/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num new file mode 100644 index 0000000000..c250b2c016 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-1.num @@ -0,0 +1,85 @@ +#* +(this is a multiline comment in Nom) + +GRAMMAR OR PARSE TOKENS + nl* - new line, end of line + field* - one csv field + fieldset* - a number of fields + record* - one record (line) or a set of csv fields + recordset* - +*# + + # using the empty recordset trick + begin { + add "recordset*"; push; + } + read; + # ignore whitespace outside of quotes + " " { while [ ]; clear; .restart } + "\n" { put; clear; add "nl*"; push; .reparse } + '"' { + until '"'; clip; clop; unescape '"'; + whilenot [\n,]; + replace "&" "&"; replace "<" "<"; replace ">" ">"; + put; clear; add ""; get; add ""; put; clear; + add "field*"; push; + clear; .reparse + } + "," { clear; } + + whilenot [\n,]; + replace "&" "&"; replace "<" "<"; replace ">" ">"; + put; clear; add ""; get; add ""; put; clear; + add "field*"; push; + +parse> + # useful for debugging + #add "line "; lines; add " char "; chars; add ": "; print; clear; + #add "\n"; unstack; print; clip; stack; + + # 1 token + pop; + # a record may be terminated by the end of input + (eof)."fieldset*" { + clear; add ""; get; add "\n"; put; clear; + add "record*"; push; .reparse + } + # 2 tokens + pop; + "recordset*field*" { + replace "field" "fieldset"; push; push; .reparse + } + # ignore blank lines + "recordset*nl*" { + clip; clip; clip; push; .reparse + } + "fieldset*field*" { + clear; get; ++; get; --; put; clear; + add "fieldset*"; push; .reparse + } + "fieldset*nl*" { + clear; add "\n "; get; add "\n"; put; clear; + add "record*"; push; .reparse + } + "recordset*record*" { + clear; a+; get; + ++; get; --; put; clear; + # if the count is 1, then this is the 1st + # record and should be marked up as a table header. + count; "1" { + clear; get; replace "tr>" "thead>"; put; + } + clear; add "recordset*"; push; .reparse + } + + (eof) { + !"recordset*" { + clear; add "[invalid csv]\nThe parse stack was: "; print; + clear; unstack; add "\n"; print; quit; + } + clear; + add "\n"; get; add "
    \n"; + add "[valid csv!] Found "; count; add " records.\n"; + print; quit; + } + push; push; diff --git a/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num new file mode 100644 index 0000000000..fa64e7c50e --- /dev/null +++ b/Task/CSV-to-HTML-translation/Nom/csv-to-html-translation-2.num @@ -0,0 +1,14 @@ + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CUSIP/R/cusip.r b/Task/CUSIP/R/cusip.r new file mode 100644 index 0000000000..acc24bf4ce --- /dev/null +++ b/Task/CUSIP/R/cusip.r @@ -0,0 +1,25 @@ +library(stringr) + +cusip_checkdigit <- function(s){ + sum <- 0 + chars <- str_split_1(s,"") + for(i in 1:8){ + if(str_detect(chars[i],"[0-9]")) v <- as.numeric(chars[i]) + else if(str_detect(chars[i],"[A-Z]")) v <- 9+which(LETTERS==chars[i]) + else v <- switch(chars[i], "*"=36, "@"=37, "#"=38) + if(i%%2==0) v <- 2*v + sum <- sum+v%/%10+v%%10 + } + return((10-(sum%%10))%%10) +} + +cusip_isvalid <- function(s){ + if(str_length(s)!=9){ + stop("CUSIP must have exactly 9 characters") + } + checksum <- cusip_checkdigit(s) |> as.character() + ifelse(endsWith(s, checksum), "Valid CUSIP", "Invalid CUSIP") +} + +test_cusips <- c("037833100","17275R102","38259P508","594918104","68389X106","68389X105") +sapply(test_cusips, cusip_isvalid) diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index 6120e1217c..cf348f086a 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -61,15 +61,15 @@ extension encryptOp public program() { - console.printLine("Original text :",TestText); + Console.printLine("Original text :",TestText); var encryptedText := TestText.encrypt(Key); - console.printLine("Encrypted text:",encryptedText); + Console.printLine("Encrypted text:",encryptedText); var decryptedText := encryptedText.decrypt(Key); - console.printLine("Decrypted text:",decryptedText); + Console.printLine("Decrypted text:",decryptedText); - console.readChar() + Console.readChar() } diff --git a/Task/Caesar-cipher/Pluto/caesar-cipher.pluto b/Task/Caesar-cipher/Pluto/caesar-cipher.pluto new file mode 100644 index 0000000000..ce61edf0ca --- /dev/null +++ b/Task/Caesar-cipher/Pluto/caesar-cipher.pluto @@ -0,0 +1,20 @@ +local function caesar(s, k, e=true) + -- Parameters: s (string), k (key) + -- e (true=encode, false=decode) + if !e do k=-k end + local out = "" + for i = 1, #s do + local c = s[i] + if c:islower() then + out ..= string.char((c:byte() - 97 + k) % 26 + 97) + elseif c:isupper() then + out ..= string.char((c:byte() - 65 + k) % 26 + 65) + else + out ..= c + end + end + return out +end + +print(caesar("The quick brown fox jumps over the lazy dog.", 3)) +print(caesar("Wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj.", 3, false)) diff --git a/Task/Caesar-cipher/Rhombus/caesar-cipher.rhombus b/Task/Caesar-cipher/Rhombus/caesar-cipher.rhombus new file mode 100644 index 0000000000..eb65b69fc6 --- /dev/null +++ b/Task/Caesar-cipher/Rhombus/caesar-cipher.rhombus @@ -0,0 +1,25 @@ +#lang rhombus/static + +import lib("racket/base.rkt") expose: + #{string->list} as string_to_list + #{list->string} as list_to_string + modulo + +fun make_rot13_char(key :: Int): + fun (char :: Char): + let char_int = char.to_int() + fun rot13_by_case(char_int, a_char :: Char) :: Int : + modulo(char_int - a_char.to_int() + key, 26) + a_char.to_int() + if char.is_alphabetic(): + | if char.is_lowercase(): + | Char.from_int(rot13_by_case(char_int, Char"a")) + | Char.from_int(rot13_by_case(char_int, Char"A")) + | char + +fun rot13_string(str :: String, key :: Int) :: String : + let chars :: PairList = string_to_list(str) + let rot13_char = make_rot13_char(key) + let str :: MutableString = list_to_string(chars.map(rot13_char)) + str.snapshot() + +rot13_string("Hello, World!", 14) // Output: "Vszzc, Kcfzr!"" diff --git a/Task/Calculating-the-value-of-e/ArkScript/calculating-the-value-of-e.ark b/Task/Calculating-the-value-of-e/ArkScript/calculating-the-value-of-e.ark new file mode 100644 index 0000000000..a344a4416c --- /dev/null +++ b/Task/Calculating-the-value-of-e/ArkScript/calculating-the-value-of-e.ark @@ -0,0 +1,22 @@ +(import std.Range :range) +(import std.List) + +(let fact (fun (n acc) { + (if (> n 0) + (fact (- n 1) (* acc n)) + acc) })) + +(let r (range 1 18)) +(let p + (list:sum + (list:map + (list:reverse (r.asList)) + (fun (n) + (/ 1 (fact n 1)) )))) + +(import std.Math :abs) + +(let my_e (+ p 1)) +(print my_e) +(print math:e) +(assert (< (abs (- my_e math:e)) (toNumber "1e-15")) "computed e is near the math:e") diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-1.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-1.elena new file mode 100644 index 0000000000..1388ecca04 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-1.elena @@ -0,0 +1,57 @@ +public program = PROGRAM; + +CONSOLE = Console; + +abstract INDEXERCLASS : interface +{ + abstract ISAVAILABLE(); + abstract GETINDEX(); + abstract SETINDEX(INDEX); + abstract NEWINDEX(OFFS); + abstract GETVALUE(); + abstract GETLENGTH(); + + bool Available = ISAVAILABLE(); + int Index + { + get() = GETINDEX(); + + set(int INDEX) + { + SETINDEX(INDEX); + } + } + appendIndex(int OFFS) { this self.Index := NEWINDEX(OFFS) } + set Value(o) { NotSupportedException.raise() } + get Value() = GETVALUE(); + get int Length() { ^ GETLENGTH() } +} + +PARALLELENUMERATOR(N) { ^ ParallelEnumerator.new(N) } + +NEWDATE(Y,M,D) { ^ Date.new(Y,M,D) } +NEWTEXTBUILDER() { ^ new TextBuilder() } + +GETMONTH(D) { ^ D.Month } +GETDAYOFWEEK(D) { ^D.DayOfWeek } +GETDAYSTR(D) { ^ D.Day.toPrintable() } + +READCHAR() { Console.readChar() } +READINT(PROMPT) { ^ Console.write(PROMPT).readLine().toInt() } + +WRITEPADDING(OUTPUT,S,SPACER,LEN) { OUTPUT.writePadding(S,SPACER,LEN) } +WRITEPADDINGLEFT(OUTPUT,S,SPACER,LEN) { OUTPUT.writePaddingLeft(S,SPACER,LEN) } +WRITELINE(OUTPUT) { OUTPUT.writeLine() } +WRITE(OUTPUT,S) { OUTPUT.write(S) } +WRITEARGS(OUTPUT,S1,S2) { OUTPUT.print(S1, S2) } +WRITECOPIES(OUTPUT,S,N) { OUTPUT.writeCopies(S,N) } + +ALLOCATE(COUNT) { ^ Array.allocate(COUNT) } + +CLEAR(S) { S.clear() } + +POPULATE(OBJ, ACTION) { ^ OBJ.populate(ACTION) } +FOREACH(OBJ, ACTION) { ^ OBJ.forEach(ACTION) } + +const MONTHNAMES = new string[]{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}; +const DAYNAMES = new string[]{"MO", "TU", "WE", "TH", "FR", "SA", "SU"}; diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-2.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-2.elena new file mode 100644 index 0000000000..36acbbd0f8 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers-2.elena @@ -0,0 +1,146 @@ +// --- UPPERCASE CODE -- + +CALENDARMONTHPRINTER +{ + _DATE; + _LINE; + _MONTH; + _YEAR; + _ROW; + + constructor NEW(YEAR, MONTH) + { + _MONTH := MONTH; + _YEAR := YEAR; + _LINE := NEWTEXTBUILDER(); + _ROW := 0; + } + + WRITETITLE() + { + _ROW := 0; + _DATE := NEWDATE(_YEAR, _MONTH, 1); + + FOREACH(DAYNAMES, (NAME) + { WRITEARGS(_LINE, " ", NAME) }) + } + + WRITECALLINE() + { + CLEAR(_LINE); + + if (GETMONTH(_DATE) == _MONTH) + { + WRITECOPIES(_LINE, " ",(GETDAYOFWEEK(_DATE) == 0) ? 6 : (GETDAYOFWEEK(_DATE) - 1)); + + do + { + WRITEPADDINGLEFT(_LINE, GETDAYSTR(_DATE), $32, 3); + + _DATE := _DATE.addDays(1) + } + until(GETMONTH(_DATE) != _MONTH || GETDAYOFWEEK(_DATE) == 1) + }; + + int LENGTH := _LINE.Length; + if (LENGTH < 21) + { WRITECOPIES(_LINE, " ", 21 - LENGTH) }; + + _ROW += 1 + } + + indexer() = new INDEXERCLASS + { + ISAVAILABLE() = _ROW < 7; + + GETINDEX()= _ROW; + + SETINDEX(INDEX) + { + if (INDEX <= _ROW) + { WRITETITLE() }; + + while (INDEX > _ROW) + { WRITECALLINE() } + } + + NEWINDEX(OFFS) + { + ^ _ROW + OFFS + } + + GETLENGTH() { ^ 7 } + + GETVALUE() = self; + }; + + PRINTTITLETO(OUTPUT) + { + WRITEPADDING(OUTPUT, MONTHNAMES[_MONTH - 1], $32, 21) + } + + PRINTTO(OUTPUT) + { + WRITE(OUTPUT, *_LINE) + } +} + +CALENDARCLASS +{ + _YEAR; + _ROWLENGTH; + + constructor NEW(YEAR) + { + _YEAR := YEAR; + _ROWLENGTH := 3 + } + + PRINTTO(OUTPUT) + { + WRITEPADDING(OUTPUT, "[SNOOPY]", $32, _ROWLENGTH * 25); + WRITELINE(OUTPUT); + WRITEPADDING(OUTPUT, _YEAR.toPrintable(), $32, _ROWLENGTH * 25); + WRITELINE(OUTPUT); WRITELINE(OUTPUT); + + var ROWCOUNT := 12 / _ROWLENGTH; + var MONTHS := POPULATE(ALLOCATE(ROWCOUNT), (I => + POPULATE(ALLOCATE(_ROWLENGTH), (J => + CALENDARMONTHPRINTER.NEW(_YEAR, I * _ROWLENGTH + J + 1))))); + + FOREACH(MONTHS, (ROW) + { + FOREACH(ROW, (MONTH) + { + MONTH.PRINTTITLETO(OUTPUT); + + WRITE(OUTPUT, " ") + }); + + WRITELINE(OUTPUT); + + FOREACH(PARALLELENUMERATOR(ROW), (LINE) + { + FOREACH(LINE, (PRINTER) + { + PRINTER.PRINTTO(OUTPUT); + + WRITE(OUTPUT, " ") + }); + + WRITELINE(OUTPUT); + }) + }) + } +} + +// --- PROGRAM --- + +PROGRAM() +{ + CALENDARCLASS CALENDER := CALENDARCLASS.NEW(READINT("ENTER THE YEAR:")); + + CALENDER.PRINTTO(CONSOLE); + + READCHAR(); +} diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena deleted file mode 100644 index 02e0ac506f..0000000000 --- a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena +++ /dev/null @@ -1,161 +0,0 @@ -import system'text; -import system'routines; -import system'calendar; -import extensions; -import extensions'routines; - -const MonthNames = new string[]{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}; -const DayNames = new string[]{"MO", "TU", "WE", "TH", "FR", "SA", "SU"}; - -class CalendarMonthPrinter -{ - Date _date; - TextBuilder _line; - int _month; - int _year; - Reference _row; - - constructor(year, month) - { - _month := month; - _year := year; - _line := new TextBuilder(); - _row := 0; - } - - writeTitle() - { - _row.Value := 0; - _date := Date.new(_year, _month, 1); - - DayNames.forEach::(name) - { _line.print(" ",name) } - } - - writeLine() - { - _line.clear(); - - if (_date.Month == _month) - { - var dw := _date.DayOfWeek; - - _line.writeCopies(" ",_date.DayOfWeek == 0 ? 6 : (_date.DayOfWeek - 1)); - - do - { - _line.writePaddingLeft(_date.Day.toPrintable(), $32, 3); - - _date := _date.addDays(1) - } - until(_date.Month != _month || _date.DayOfWeek == 1) - }; - - int length := _line.Length; - if (length < 21) - { _line.writeCopies(" ", 21 - length) }; - - _row.append(1) - } - - indexer() = new Indexer - { - bool Available = _row < 7; - - int Index - { - get() = _row.Value; - - set(int index) - { - if (index <= _row) - { self.writeTitle() }; - - while (index > _row) - { self.writeLine() } - } - } - - appendIndex(int index) - { - this self.Index := _row.Value + index - } - - get int Length() { ^ 7 } - - get Value() = self; - - set Value(o) { NotSupportedException.raise() } - }; - - printTitleTo(output) - { - output.writePadding(MonthNames[_month - 1], $32, 21) - } - - printTo(output) - { - output.write(_line.Value) - } -} - -class Calendar -{ - int _year; - int _rowLength; - - constructor new(int year) - { - _year := year; - _rowLength := 3 - } - - printTo(output) - { - output.writePadding("[SNOOPY]", $32, _rowLength * 25); - output.writeLine(); - output.writePadding(_year.toPrintable(), $32, _rowLength * 25); - output.writeLine().writeLine(); - - var rowCount := 12 / _rowLength; - var months := Array.allocate(rowCount).populate::(i => - Array.allocate(_rowLength) - .populate::(j => - new CalendarMonthPrinter(_year, i * _rowLength + j + 1))); - - months.forEach::(row) - { - var r := row; - - row.forEach::(month) - { - month.printTitleTo(output); - - output.write(" ") - }; - - output.writeLine(); - - ParallelEnumerator.new(row).forEach::(line) - { - line.forEach::(printer) - { - printer.printTo(output); - - output.write(" ") - }; - - output.writeLine() - } - } - } -} - -public program() -{ - var calender := Calendar.new(console.write("ENTER THE YEAR:").readLine().toInt()); - - calender.printTo(console); - - console.readChar() -} diff --git a/Task/Calendar---for-REAL-programmers/Red/calendar---for-real-programmers.red b/Task/Calendar---for-REAL-programmers/Red/calendar---for-real-programmers.red new file mode 100644 index 0000000000..1fc0cae3bb --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Red/calendar---for-real-programmers.red @@ -0,0 +1,52 @@ +Red [ "PRINT CALENDAR IN SIX MONTHS ACROSS AND FOR TWO ROWS - HINJO, 20 JULY 2025" ] + +MONTHS: SYSTEM/LOCALE/MONTHS + +; GET DAY FROM YEAR, MONTH, WEEK, AND WEEKDAY! +GETDAY: FUNCTION [Y[INTEGER!] M[INTEGER!] W[INTEGER!] WD[INTEGER!]] [ + FD: TO-DATE REDUCE [1 M Y] ; FIRST DAY! + SWD: FD/WEEKDAY + 1 IF SWD > 7 [SWD: 1] ; SHIFT FROM MON=1 TO SUN=1 + OFS: (W - 1) * 7 + (WD - SWD) ; OFFSET + D: FD + OFS ; DATE + EITHER D/MONTH = M [D/DAY][0] ; RETURN DAY OR ZERO! +] + +; CENTER STRING +CENTR: FUNCTION [STR WID] [ + GAP: WID - LENGTH? STR + LPAD: TO-INTEGER GAP / 2 + PAD/LEFT STR WID - LPAD + PAD STR WID +] + +EITHER "" = Y: ASK "YEAR (ENTER FOR CURRENT): " [Y: NOW/YEAR][Y: TO-INTEGER Y] + +PRINT CENTR "[ S N O O P Y ]" 130 ; PRINT SNOOPY BLOCK CENTERED +PRINT CENTR TO-STRING Y 130 ; PRINT YEAR + +FOREACH R [[1 2 3 4 5 6][7 8 9 10 11 12]] [ + ; PRINT MONTH'S NAME + FOREACH M R [ + PRIN REJOIN [CENTR UPPERCASE MONTHS/:M 21 " "] + ] PRINT "" + + ; PRINT FOR EACH WEEK ACROSS MONTHS + FOREACH W [0 1 2 3 4 5 6] [ + ; EACH MONTHS + FOREACH M R [ + EITHER W = 0 [ ; PRINT WEEKDAYS + FOREACH D ["SU" "MO" "TU" "WE" "TH" "FR" "SA"] + [PRIN [FORM PAD D 3]] + ] [ + FOREACH WD [1 2 3 4 5 6 7] [ ; PRINT DATES + ; RECONSTRUCT THE DAY + EITHER 0 < DT: GETDAY Y M W WD [ + PRIN [FORM PAD/LEFT DT 2] + ] [ + PRIN " " + ] PRIN " " + ] + ] PRIN " " + ] PRINT "" + ] PRINT "" +] diff --git a/Task/Calendar/Red/calendar.red b/Task/Calendar/Red/calendar.red new file mode 100644 index 0000000000..2fafda5123 --- /dev/null +++ b/Task/Calendar/Red/calendar.red @@ -0,0 +1,52 @@ +Red [ "Print Calendar in six months across and for two rows - Hinjo, 20 July 2025" ] + +months: system/locale/months + +; get day from year, month, week, and weekday! +getday: function [y[integer!] m[integer!] w[integer!] wd[integer!]] [ + fd: to-date reduce [1 m y] ; first day! + swd: fd/weekday + 1 if swd > 7 [swd: 1] ; shift from mon=1 to sun=1 + ofs: (w - 1) * 7 + (wd - swd) ; offset + d: fd + ofs ; date + either d/month = m [d/day][0] ; return day or zero! +] + +; center string +centr: function [str wid] [ + gap: wid - length? str + lpad: to-integer gap / 2 + pad/left str wid - lpad + pad str wid +] + +either "" = y: ask "Year (ENTER for current): " [y: now/year][y: to-integer y] + +print centr "[ S N O O P Y ]" 130 ; print snoopy block centered +print centr to-string y 130 ; print year + +foreach r [[1 2 3 4 5 6][7 8 9 10 11 12]] [ + ; print month's name + foreach m r [ + prin rejoin [centr months/:m 21 " "] + ] print "" + + ; print for each week across months + foreach w [0 1 2 3 4 5 6] [ + ; each months + foreach m r [ + either w = 0 [ ; print weekdays + foreach d ["Su" "Mo" "Tu" "We" "Th" "Fr" "Sa"] + [prin [form pad d 3]] + ] [ + foreach wd [1 2 3 4 5 6 7] [ ; print dates + ; reconstruct the day + either 0 < dt: getday y m w wd [ + prin [form pad/left dt 2] + ] [ + prin " " + ] prin " " + ] + ] prin " " + ] print "" + ] print "" +] diff --git a/Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.ada b/Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.ada new file mode 100644 index 0000000000..31840223a0 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.ada @@ -0,0 +1,110 @@ +with Ada.Text_IO; + +procedure Calkin_Wilf is + type Rational is + record + Numerator : Integer; + Denominator : Positive; + end record; + + -- A generic solution would use Ada.Containers.Vectors, but + -- these puzzles are written to avoid numbers larger than + -- what fit in 64 bits, so we can assume a limit of 64 terms + type Term_Array is array (1 .. 64) of Positive; + + type Continued_Fraction is + record + Count : Positive; + Terms : Term_Array; + end record; + + -- Don't bother with reducing or negatives + function "+" (A, B : Rational) return Rational is + (A.Numerator * B.Denominator + B.Numerator * A.Denominator, + A.Denominator * B.Denominator); + + function "-" (A : Rational) return Rational is + (-A.Numerator, A.Denominator); + + function "-" (A, B : Rational) return Rational is + (A + (-B)); + + function "*" (A, B : Rational) return Rational is + (A.Numerator * B.Numerator, + A.Denominator * B.Denominator); + + function Invert (A : Rational) return Rational is + (A.Denominator, + A.Numerator); + + function Floor (A : Rational) return Rational is + (A.Numerator / A.Denominator, + 1); + + function Image (A : Rational) return String is + (A.Numerator'Image & " /" & A.Denominator'Image); + + function "=" (A, B : Rational) return Boolean is + (A.Numerator = B.Numerator and A.Denominator = B.Denominator); + + function Next_Calkin_Wilf_Term (R : Rational) return Rational is + (Invert ((2, 1) * Floor (R) + (1, 1) - R)); + + procedure Put_First_Terms (N : Positive) is + R : Rational := (1, 1); + begin + Ada.Text_IO.Put_Line ( + "The first " & N'Image & " terms of the Calkin-Wilf Sequence are:"); + for I in 1 .. N loop + Ada.Text_IO.Put_Line (I'Image & ": " & Image (R)); + R := Next_Calkin_Wilf_Term (R); + end loop; + end Put_First_Terms; + + function To_Continued_Fraction (R : Rational) return Continued_Fraction is + Count : Natural := 0; + Terms : Term_Array; + N : Natural := R.Numerator; + D : Natural := R.Denominator; + M : Natural; + begin + while D > 0 loop + Count := Count + 1; + Terms (Count) := N / D; + M := N mod D; + N := D; + D := M; + end loop; + + if Count mod 2 = 0 then + Terms (Count .. Count + 1) := (Terms (Count) - 1, 1); + Count := Count + 1; + end if; + + return (Count, Terms); + end To_Continued_Fraction; + + function To_Index (R : Rational) return Natural is + Cont_Frac : Continued_Fraction := To_Continued_Fraction (R); + Terms : Term_Array renames Cont_Frac.Terms; + Index : Natural := 0; + begin + for I in reverse 1 .. Cont_Frac.Count loop + for J in 1 .. Terms (I) loop + Index := Index * 2 + (I mod 2); + end loop; + end loop; + + return Index; + end To_Index; + + procedure Put_Term_Index (R : Rational) is + Index : Natural := To_Index (R); + begin + Ada.Text_IO.Put_Line ("Term " & Image (R) & " is at index " & Index'Image); + end Put_Term_Index; + +begin + Put_First_Terms (20); + Put_Term_Index((83116, 51639)); +end Calkin_Wilf; diff --git a/Task/Calkin-Wilf-sequence/Pluto/calkin-wilf-sequence.pluto b/Task/Calkin-Wilf-sequence/Pluto/calkin-wilf-sequence.pluto new file mode 100644 index 0000000000..a95db1986a --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Pluto/calkin-wilf-sequence.pluto @@ -0,0 +1,47 @@ +require "rat" +local fmt = require "fmt" + +local function calkin_wilf(n) + local cw = {} + cw[1] = rat.of(1) + for i = 2, n do + local t = cw[i - 1]:floor() * 2 - cw[i - 1] + 1 + cw[i] = cw[1] / t + end + return cw +end + +local function to_continued(r) + local a = r:getNum() + local b = r:getDen() + local res = {} + repeat + res:insert(math.floor(a / b)) + a, b = b, a % b + until a == 1 + + if #res % 2 == 0 then -- ensure always odd + res[#res] -= 1 + res:insert(1) + end + return res +end + +local function get_term_number(cf) + local b = "" + local d = "1" + for cf as n do + b = string.rep(d, n) .. b + d = (d == "1") ? "0" : "1" + end + return tonumber(b, 2) +end + +local cw = calkin_wilf(20) +print("The first 20 terms of the Calkin-Wilf sequence are:") +for i = 1, 20 do fmt.print("%2d: %s", i, cw[i]:format("%d", "%d", false)) end +print() +local r = rat.of(83116, 51639) +local cf = to_continued(r) +local tn = get_term_number(cf) +fmt.print("%s is the %s term of the sequence.", r, fmt.ord(tn, true)) diff --git a/Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-1.pluto b/Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-1.pluto new file mode 100644 index 0000000000..e133651e4e --- /dev/null +++ b/Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-1.pluto @@ -0,0 +1,18 @@ +/* mylib.c */ + +// gcc -c -fpic mylib.c +// gcc -shared -o mylib.so mylib.o + +#include +#include + +static void *strptr = NULL; + +extern char *my_strdup(const char *src) { + strptr = (void *)strdup(src); + return (char *)strptr; +} + +extern void my_free() { + free(strptr); +} diff --git a/Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-2.pluto b/Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-2.pluto new file mode 100644 index 0000000000..d99013f303 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Pluto/call-a-foreign-language-function-2.pluto @@ -0,0 +1,10 @@ +local ffi = require "pluto:ffi" +local lib = ffi.open("./mylib.so") +lib:cdef[[ + char *my_strdup(const char *src); + void my_free(); +]] +local s = "Hello World!" +print(lib.my_strdup(s)) +lib.my_free() +lib = nil diff --git a/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto b/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto new file mode 100644 index 0000000000..e32bbfc202 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto @@ -0,0 +1,19 @@ +local s1, s2 = "Hello", " World!" +local ffi = require "pluto:ffi" +local lib = ffi.open(os.platform == "windows" ? "msvcrt" : "libc.so.6") +if lib then + print("Shared library found") + lib:cdef[[ + char *strcat(char *dest, const char *src); + size_t strlen(const char *str); + ]] + local s = lib.strcat(s1, s2) + print(s) + print(lib.strlen(s)) + lib = nil +else + print("Shared library not found.") + local s = s1 .. s2 + print(s) + print(#s) +end diff --git a/Task/Call-a-function/ArkScript/call-a-function-1.ark b/Task/Call-a-function/ArkScript/call-a-function-1.ark new file mode 100644 index 0000000000..6b9bbd7045 --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-1.ark @@ -0,0 +1,4 @@ +# function call with no arguments +(foo) +# function call with fixed number of arguments +(bar 1 2) diff --git a/Task/Call-a-function/ArkScript/call-a-function-2.ark b/Task/Call-a-function/ArkScript/call-a-function-2.ark new file mode 100644 index 0000000000..83042ac194 --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-2.ark @@ -0,0 +1,3 @@ +(macro foo (...args) (print args)) +(foo) # => [] +(foo 1 2 3) # => [1 2 3] diff --git a/Task/Call-a-function/ArkScript/call-a-function-3.ark b/Task/Call-a-function/ArkScript/call-a-function-3.ark new file mode 100644 index 0000000000..85e79cbedf --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-3.ark @@ -0,0 +1,6 @@ +(let foo (fun () + 4 # this value will be discarded as it has no effect + (compute_something 1 2 3) # the return value will be discarded too + 5 )) + +(print (foo)) # => 5 diff --git a/Task/Call-a-function/ArkScript/call-a-function-4.ark b/Task/Call-a-function/ArkScript/call-a-function-4.ark new file mode 100644 index 0000000000..9480ebac53 --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-4.ark @@ -0,0 +1,6 @@ +(mut a 5) +(let foo (fun (bar) + (set bar 12))) +(print a) # => 5 +(foo a) +(print a) # => 5 diff --git a/Task/Call-a-function/ArkScript/call-a-function-5.ark b/Task/Call-a-function/ArkScript/call-a-function-5.ark new file mode 100644 index 0000000000..1f9b736c48 --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-5.ark @@ -0,0 +1,3 @@ +(if (= 5 (foo)) + (compute_something) + (print "uhoh")) diff --git a/Task/Call-a-function/ArkScript/call-a-function-6.ark b/Task/Call-a-function/ArkScript/call-a-function-6.ark new file mode 100644 index 0000000000..bb28c2001a --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-6.ark @@ -0,0 +1,4 @@ +(let foo (fun () ())) + +(print (type foo)) # => Function +(print (type print)) # => CProc diff --git a/Task/Call-a-function/ArkScript/call-a-function-7.ark b/Task/Call-a-function/ArkScript/call-a-function-7.ark new file mode 100644 index 0000000000..91926323a6 --- /dev/null +++ b/Task/Call-a-function/ArkScript/call-a-function-7.ark @@ -0,0 +1,8 @@ +(import std.Macros) + +(let test_func (fun (a b c) (* a b c))) +(let test_func1 (partial test_func 1)) +(let test_func2 (partial test_func1 2)) + +(print (test_func1 2 3)) # => 6 +(print (test_func2 3)) # => 6 diff --git a/Task/Call-a-function/DuckDB/call-a-function-1.duckdb b/Task/Call-a-function/DuckDB/call-a-function-1.duckdb new file mode 100644 index 0000000000..a40b00fc78 --- /dev/null +++ b/Task/Call-a-function/DuckDB/call-a-function-1.duckdb @@ -0,0 +1,5 @@ +create or replace macro fl(TableName) as table ( + (from query_table(TableName) limit 1) + UNION ALL + (select last(COLUMNS(*)) from query_table(TableName)) +); diff --git a/Task/Call-a-function/DuckDB/call-a-function-2.duckdb b/Task/Call-a-function/DuckDB/call-a-function-2.duckdb new file mode 100644 index 0000000000..f62d15561c --- /dev/null +++ b/Task/Call-a-function/DuckDB/call-a-function-2.duckdb @@ -0,0 +1 @@ +CREATE MACRO add_default(a, b := 5) AS a + b; diff --git a/Task/Call-a-function/Elena/call-a-function-1.elena b/Task/Call-a-function/Elena/call-a-function-1.elena index ce3efa2f68..2943a177d8 100644 --- a/Task/Call-a-function/Elena/call-a-function-1.elena +++ b/Task/Call-a-function/Elena/call-a-function-1.elena @@ -1,2 +1,2 @@ -var c0 := { console.writeLine("No argument provided") }; -var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") }; +var c0 := { Console.writeLine("No argument provided") }; +var c2 := (int a, int b){ Console.printLine("Arguments ",a," and ",b," provided") }; diff --git a/Task/Call-an-object-method/ArkScript/call-an-object-method.ark b/Task/Call-an-object-method/ArkScript/call-an-object-method.ark new file mode 100644 index 0000000000..7052c3c4b8 --- /dev/null +++ b/Task/Call-an-object-method/ArkScript/call-an-object-method.ark @@ -0,0 +1,17 @@ +(let create_user (fun (username password age) { + (let change_username (fun (new_name) + (set username new_name))) + (let check_password (fun (pass) + (= pass password))) + + (fun (&username &password &age &change_username &check_password) ()) })) + +(let me (create_user "Lex" "passw0rd" 25)) +(let john (create_user "John" "qwerty123" 28)) + +(assert (not (me.check_password "test!")) "password is not 'test!'") +(assert (!= me.username john.username) "usernames are distinct") + +(assert (= me.username "Lex") "my username is Lex") +(me.change_username "Rosetta") +(assert (= me.username "Rosetta") "my username is now Rosetta!") diff --git a/Task/Call-an-object-method/Elena/call-an-object-method.elena b/Task/Call-an-object-method/Elena/call-an-object-method.elena index 37f6dbf55c..b431936814 100644 --- a/Task/Call-an-object-method/Elena/call-an-object-method.elena +++ b/Task/Call-an-object-method/Elena/call-an-object-method.elena @@ -1 +1 @@ - console.printLine("Hello"," ","World!"); + Console.printLine("Hello"," ","World!"); diff --git a/Task/Call-an-object-method/Haxe/call-an-object-method.haxe b/Task/Call-an-object-method/Haxe/call-an-object-method.haxe new file mode 100644 index 0000000000..5eb6663bd5 --- /dev/null +++ b/Task/Call-an-object-method/Haxe/call-an-object-method.haxe @@ -0,0 +1,13 @@ +class ExampleClass { + public function exampleMethod() { + return "This is a method!"; + } + public function new() {} +} + +class Main { + static public function main():Void { + var exampleObject = new ExampleClass(); + trace(exampleObject.exampleMethod()); + } +} diff --git a/Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.ada b/Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.ada new file mode 100644 index 0000000000..8da706fcd8 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.ada @@ -0,0 +1,114 @@ +with Ada.Characters.Handling, + Ada.Strings, + Ada.Strings.Fixed, + Ada.Strings.Maps, + Ada.Strings.Maps.Constants, + Ada.Text_IO; + +use Ada.Characters.Handling, + Ada.Strings, + Ada.Strings.Fixed, + Ada.Strings.Maps, + Ada.Strings.Maps.Constants; + +procedure Camel_Snake_Case is + type Sample_Array is array (Positive range <>) of access constant String; + -- Work around for array elements needing to be the same size. + -- Could also use Ada.Strings.Bounded_Strings instead. + S1 : aliased constant String := "snakeCase"; + S2 : aliased constant String := "snake_case"; + S3 : aliased constant String := "variable_10_case"; + S4 : aliased constant String := "variable10Case"; + S5 : aliased constant String := "ɛrgo rE tHis"; + S6 : aliased constant String := "hurry-up-joe!"; + S7 : aliased constant String := "c://my-docs/happy_Flag-Day/12.doc"; + S8 : aliased constant String := " spaces "; + + Samples : constant Sample_Array := + ( + S1'Access, + S2'Access, + S3'Access, + S4'Access, + S5'Access, + S6'Access, + S7'Access, + S8'Access + ); + + function Should_Insert (This, Last : Character) return Boolean is + ( + (Is_In (Last, Lower_Set) and then + Is_In (This, Upper_Set or Decimal_Digit_Set)) + or else + (Is_In (Last, Upper_Set) and then + Is_In (This, Decimal_Digit_Set)) + or else + (Is_In (Last, Decimal_Digit_Set) and then + Is_In (This, Upper_Set)) + ); + + function To_Snake_Case (S : String) return String is + Trimmed : constant String := Trim (S, Both); + Separator_Map : constant Character_Mapping := To_Mapping (" -", "__"); + Translated : constant String := Translate (Trimmed, Separator_Map); + New_Word_Set : constant Character_Set := Upper_Set or Decimal_Digit_Set; + New_Word_Chars : constant Natural := Count (Translated, New_Word_Set); + Snake : String (1 .. Translated'Length + New_Word_Chars); + J : Positive := 2; + L : Character; + begin + Snake (1 .. Translated'Length) := Translated; + + for I in 2 .. Translated'Last loop + if Should_Insert (Translated (I), Translated (I - 1)) then + Snake (J) := '_'; + J := J + 1; + end if; + + L := Translated (I); + + if Is_In (Translated (I), Upper_Set) then + L := To_Lower (L); + end if; + + Snake (J) := L; + J := J + 1; + end loop; + + return Snake (1 .. J - 1); + end To_Snake_Case; + + function To_Camel_Case (S : String) return String is + Trimmed : constant String := Trim (S, Both); + Separators : constant Character_Set := To_Set (" -_"); + Snake : String (Trimmed'Range) := Trimmed; + J : Positive := 2; + begin + for I in 2 .. Trimmed'Length loop + if not Is_In (Trimmed (I), Separators) then + if Is_In (Trimmed (I - 1), Separators) and then + Is_In (Trimmed (I), Lower_Set) then + Snake (J) := To_Upper (Trimmed (I)); + else + Snake (J) := Trimmed (I); + end if; + + J := J + 1; + end if; + end loop; + + return Snake (1 .. J - 1); + end To_Camel_Case; + +begin + Ada.Text_IO.Put_Line ("=Snake Case="); + for I of Samples loop + Ada.Text_IO.Put_Line (I.all & " => " & To_Snake_Case (I.all)); + end loop; + + Ada.Text_IO.Put_Line ("=Camel Case="); + for I of Samples loop + Ada.Text_IO.Put_Line (I.all & " => " & To_Camel_Case (I.all)); + end loop; +end Camel_Snake_Case; diff --git a/Task/Camel-case-and-snake-case/C-sharp/camel-case-and-snake-case.cs b/Task/Camel-case-and-snake-case/C-sharp/camel-case-and-snake-case.cs new file mode 100644 index 0000000000..672207f79b --- /dev/null +++ b/Task/Camel-case-and-snake-case/C-sharp/camel-case-and-snake-case.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Text; + +public static class CamelCaseAndSnakeCase +{ + public static void Main(string[] args) + { + List variableNames = new List + { + "snakeCase", "snake_case", "variable_10_case", "variable10Case", + "ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces " + }; + + Console.WriteLine($"{"=== To snake_case ===",48}"); + foreach (string text in variableNames) + { + Console.WriteLine($"{text,34} --> {ToSnakeCase(text)}"); + } + + Console.WriteLine(); + Console.WriteLine($"{"=== To camelCase ===",48}"); + foreach (string text in variableNames) + { + Console.WriteLine($"{text,34} --> {ToCamelCase(text)}"); + } + } + + private static string ToSnakeCase(string aCamel) + { + aCamel = aCamel.Trim().Replace(SPACE, UNDERSCORE).Replace(HYPHEN, UNDERSCORE); + StringBuilder snake = new StringBuilder(); + bool first = true; + foreach (char ch in aCamel) + { + if (first) + { + snake.Append(ch); + first = false; + } + else if (!first && char.IsUpper(ch)) + { + if (snake.ToString().EndsWith(UNDERSCORE)) + { + snake.Append(char.ToLower(ch)); + } + else + { + snake.Append(UNDERSCORE + char.ToLower(ch)); + } + } + else + { + snake.Append(ch); + } + } + return snake.ToString(); + } + + private static string ToCamelCase(string aSnake) + { + aSnake = aSnake.Trim().Replace(SPACE, UNDERSCORE).Replace(HYPHEN, UNDERSCORE); + StringBuilder camel = new StringBuilder(); + bool underscore = false; + foreach (char ch in aSnake) + { + if (ch.ToString().Equals(UNDERSCORE)) + { + underscore = true; + } + else if (underscore) + { + camel.Append(char.ToUpper(ch)); + underscore = false; + } + else + { + camel.Append(ch); + } + } + return camel.ToString(); + } + + private static readonly string SPACE = " "; + private static readonly string UNDERSCORE = "_"; + private static readonly string HYPHEN = "-"; +} diff --git a/Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math b/Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math new file mode 100644 index 0000000000..ecae1a970d --- /dev/null +++ b/Task/Camel-case-and-snake-case/Mathematica/camel-case-and-snake-case.math @@ -0,0 +1,85 @@ +(* String case conversion functions in Mathematica *) + +snakeToCamelCase[nam_String, sep_String : "[_]+", lcmiddle_ : False] := Module[{words}, + If[nam == "", Return[nam]]; + words = StringSplit[StringTrim[nam], RegularExpression[sep]]; + If[lcmiddle, words = ToLowerCase /@ words]; + words[[2 ;;]] = StringJoin[ToUpperCase[StringTake[#, 1]], StringDrop[#, 1]] & /@ Select[words[[2 ;;]], StringLength[#] > 0 &]; + StringJoin[words] +] + +spaceToCamelCase[nam_String] := snakeToCamelCase[nam, "\\s+"] + +kebabToCamelCase[nam_String] := snakeToCamelCase[nam, "[\\-]+"] + +periodToCamelCase[nam_String] := snakeToCamelCase[nam, "[\\.]+"] + +allsepToCamelCase[nam_String] := snakeToCamelCase[nam, "[ \\-_\\.]+"] + +lowermiddleAllsepToCamelCase[nam_String] := snakeToCamelCase[nam, "[ \\-_\\.]+", True] + +camelToSnakeCase[nam_String, sep_String : "_", allsep_String : "[_]+", lcmiddle_ : True] := Module[{result, sep1, words}, + result = StringReplace[StringTrim[nam], RegularExpression["([A-Z]+)"] -> sep <> "$1"]; + sep1 = If[sep == ".", "\\.", sep]; + If[lcmiddle, + words = Select[StringSplit[result, sep1], StringLength[#] > 0 &]; + result = StringRiffle[ToLowerCase /@ words, sep], + words = Select[StringSplit[result, sep1], StringLength[#] > 0 &]; + result = StringRiffle[StringJoin[ToLowerCase[StringTake[#, 1]], StringDrop[#, 1]] & /@ words, sep] + ]; + StringReplace[result, RegularExpression[allsep] -> sep] +] + +preserveMidcapsCamelToSnakeCase[nam_String] := camelToSnakeCase[nam, "_", "[_]+", False] + +allsepToSnakeCase[nam_String] := camelToSnakeCase[nam, "_", "[ \\-\\._]+"] + +allsepToKebabCase[nam_String] := camelToSnakeCase[nam, "-", "[ \\-\\._]+"] + +allsepToSpaceCase[nam_String] := camelToSnakeCase[nam, " ", "[ \\-\\._]+"] + +allsepToPeriodCase[nam_String] := camelToSnakeCase[nam, ".", "[ \\-\\._]+"] + +allsepToSlashCase[nam_String] := camelToSnakeCase[nam, "/", "[ \\-\\._]+"] + +(* Test the functions *) +testFunctions = { + snakeToCamelCase, + spaceToCamelCase, + kebabToCamelCase, + periodToCamelCase, + allsepToCamelCase, + lowermiddleAllsepToCamelCase, + camelToSnakeCase, + preserveMidcapsCamelToSnakeCase, + allsepToSnakeCase, + allsepToKebabCase, + allsepToSpaceCase, + allsepToPeriodCase, + allsepToSlashCase +}; + +testStrings = { + "snakeCase", + "snake_case", + "snake-case", + "snake case", + "snake CASE", + "snake.case", + "variable_10_case", + "variable10Case", + "ɛrgo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces " +}; + +Do[ + Print["Testing function ", f, ":"]; + Do[ + Print[StringPadLeft[testString, 36], " => ", f[testString]], + {testString, testStrings} + ]; + Print[""], + {f, testFunctions} +] diff --git a/Task/Camel-case-and-snake-case/Rust/camel-case-and-snake-case.rs b/Task/Camel-case-and-snake-case/Rust/camel-case-and-snake-case.rs new file mode 100644 index 0000000000..995275f9f2 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Rust/camel-case-and-snake-case.rs @@ -0,0 +1,93 @@ +const HYPHEN: char = '-'; +const SPACE: char = ' '; +const UNDERSCORE: char = '_'; +const WHITESPACE: &str = " \n\r\t\u{0C}\u{0B}"; + +fn left_trim(text: &str) -> &str { + text.trim_start_matches(WHITESPACE.chars().collect::>().as_slice()) +} + +fn right_trim(text: &str) -> &str { + text.trim_end_matches(WHITESPACE.chars().collect::>().as_slice()) +} + +fn trim(text: &str) -> &str { + text.trim_matches(WHITESPACE.chars().collect::>().as_slice()) +} + +fn prepare_for_conversion(text: &mut String) { + *text = trim(text).to_string(); + *text = text.replace(SPACE, &UNDERSCORE.to_string()); + *text = text.replace(HYPHEN, &UNDERSCORE.to_string()); +} + +fn to_snake_case(camel: &str) -> String { + let mut text = camel.to_string(); + prepare_for_conversion(&mut text); + + let mut snake = String::new(); + let mut first = true; + + for ch in text.chars() { + if first { + snake.push(ch); + first = false; + } else if ch.is_ascii_uppercase() { + if snake.chars().last() == Some(UNDERSCORE) { + snake.push(ch.to_ascii_lowercase()); + } else { + snake.push(UNDERSCORE); + snake.push(ch.to_ascii_lowercase()); + } + } else { + snake.push(ch); + } + } + + snake +} + +fn to_camel_case(snake: &str) -> String { + let mut text = snake.to_string(); + prepare_for_conversion(&mut text); + + let mut camel = String::new(); + let mut underscore = false; + + for ch in text.chars() { + if ch == UNDERSCORE { + underscore = true; + } else if underscore { + camel.push(ch.to_ascii_uppercase()); + underscore = false; + } else { + camel.push(ch); + } + } + + camel +} + +fn main() { + let variable_names = vec![ + "snakeCase", + "snake_case", + "variable_10_case", + "variable10Case", + "ergo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces " + ]; + + println!("{:>48}", "=== To snake_case ==="); + for text in &variable_names { + println!("{:>34} --> {}", text, to_snake_case(text)); + } + + println!(); + println!("{:>48}", "=== To camelCase ==="); + for text in &variable_names { + println!("{:>34} --> {}", text, to_camel_case(text)); + } +} diff --git a/Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig b/Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig new file mode 100644 index 0000000000..faee5b8822 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Zig/camel-case-and-snake-case.zig @@ -0,0 +1,134 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; + +const HYPHEN: u8 = '-'; +const SPACE: u8 = ' '; +const UNDERSCORE: u8 = '_'; +const WHITESPACE = " \n\r\t\x0C\x0B"; + +fn isWhitespace(ch: u8) bool { + for (WHITESPACE) |ws| { + if (ch == ws) return true; + } + return false; +} + +fn leftTrim(text: []const u8) []const u8 { + var start: usize = 0; + while (start < text.len and isWhitespace(text[start])) { + start += 1; + } + return text[start..]; +} + +fn rightTrim(text: []const u8) []const u8 { + var end: usize = text.len; + while (end > 0 and isWhitespace(text[end - 1])) { + end -= 1; + } + return text[0..end]; +} + +fn trim(text: []const u8) []const u8 { + return rightTrim(leftTrim(text)); +} + +fn prepareForConversion(allocator: std.mem.Allocator, text: []const u8) ![]u8 { + const trimmed = trim(text); + var result = try ArrayList(u8).initCapacity(allocator, trimmed.len); + defer result.deinit(); + + for (trimmed) |ch| { + if (ch == SPACE or ch == HYPHEN) { + try result.append(UNDERSCORE); + } else { + try result.append(ch); + } + } + + return result.toOwnedSlice(); +} + +fn toSnakeCase(allocator: std.mem.Allocator, camel: []const u8) ![]u8 { + const text = try prepareForConversion(allocator, camel); + defer allocator.free(text); + + var snake = ArrayList(u8).init(allocator); + defer snake.deinit(); + + var first = true; + + for (text) |ch| { + if (first) { + try snake.append(ch); + first = false; + } else if (std.ascii.isUpper(ch)) { + if (snake.items.len > 0 and snake.items[snake.items.len - 1] == UNDERSCORE) { + try snake.append(std.ascii.toLower(ch)); + } else { + try snake.append(UNDERSCORE); + try snake.append(std.ascii.toLower(ch)); + } + } else { + try snake.append(ch); + } + } + + return snake.toOwnedSlice(); +} + +fn toCamelCase(allocator: std.mem.Allocator, snake: []const u8) ![]u8 { + const text = try prepareForConversion(allocator, snake); + defer allocator.free(text); + + var camel = ArrayList(u8).init(allocator); + defer camel.deinit(); + + var underscore = false; + + for (text) |ch| { + if (ch == UNDERSCORE) { + underscore = true; + } else if (underscore) { + try camel.append(std.ascii.toUpper(ch)); + underscore = false; + } else { + try camel.append(ch); + } + } + + return camel.toOwnedSlice(); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const variable_names = [_][]const u8{ + "snakeCase", + "snake_case", + "variable_10_case", + "variable10Case", + "ergo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces " + }; + + print("{s:>48}\n", .{"=== To snake_case ==="}); + for (variable_names) |text| { + const snake = try toSnakeCase(allocator, text); + defer allocator.free(snake); + print("{s:>34} --> {s}\n", .{ text, snake }); + } + + print("\n", .{}); + print("{s:>48}\n", .{"=== To camelCase ==="}); + for (variable_names) |text| { + const camel = try toCamelCase(allocator, text); + defer allocator.free(camel); + print("{s:>34} --> {s}\n", .{ text, camel }); + } +} diff --git a/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.ada b/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.ada new file mode 100644 index 0000000000..a138a754ae --- /dev/null +++ b/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.ada @@ -0,0 +1,105 @@ +with Ada.Strings; +with Ada.Strings.Fixed; +with Ada.Strings.Maps; +with Ada.Text_IO; + +use Ada.Strings; +use Ada.Strings.Fixed; +use Ada.Strings.Maps; +use Ada.Text_IO; + +procedure Canonicalize_CIDR is + type IP_Octet_Type is mod 256; + + type IP_Record_Type is record + A, B, C, D : IP_Octet_Type; + end record + with Size => 32; + + for IP_Record_Type use record + -- Use little-endian ordering to match bit array + D at 0 range 0 .. 7; + C at 1 range 0 .. 7; + B at 2 range 0 .. 7; + A at 3 range 0 .. 7; + end record; + + type IP_Bitarray_Type is array (0 .. 31) of Boolean + with Component_Size => 1; + + subtype IP_Mask_Type is Natural range 0 .. 32; + + type IP_CIDR_Type is record + IP : IP_Record_Type; + Mask : IP_Mask_Type; + end record; + + function Parse_IP_CIDR (S : String) return IP_CIDR_Type is + IP_Record : IP_CIDR_Type; + Digit_Range : Character_Range := ('0', '9'); + Digit_Set : Character_Set := To_Set (Digit_Range); + Octets : array (1 .. 4) of IP_Octet_Type; + First : Positive; + Last : Natural := 0; + begin + for I in Octets'Range loop + Find_Token (S, Digit_Set, Last + 1, Inside, First, Last); + Octets (I) := IP_Octet_Type'Value (S (First .. Last)); + end loop; + IP_Record.IP.A := Octets (1); + IP_Record.IP.B := Octets (2); + IP_Record.IP.C := Octets (3); + IP_Record.IP.D := Octets (4); + + Find_Token (S, Digit_Set, Last + 1, Inside, First, Last); + IP_Record.Mask := IP_Mask_Type'Value (S (First .. Last)); + + return IP_Record; + end Parse_IP_CIDR; + + procedure Canonicalize_IP_CIDR (Addr : in out IP_CIDR_Type) is + -- Fun part. I can overlay different types over the same bits. + Bit_Overlay : IP_Bitarray_Type with Address => Addr.IP'Address; + begin + for I in Bit_Overlay'First .. Bit_Overlay'Last - Addr.Mask loop + Bit_Overlay (I) := False; + end loop; + end Canonicalize_IP_CIDR; + + procedure Put_IP_CIDR (Addr : IP_CIDR_TYPE) is + package Octet_IO is new Ada.Text_IO.Modular_IO (IP_Octet_Type); + package Mask_IO is new Ada.Text_IO.Integer_IO (IP_Mask_Type); + begin + Octet_IO.Put (Addr.IP.A, 0); + Put ("."); + Octet_IO.Put (Addr.IP.B, 0); + Put ("."); + Octet_IO.Put (Addr.IP.C, 0); + Put ("."); + Octet_IO.Put (Addr.IP.D, 0); + Put ("/"); + Mask_IO.Put (Addr.Mask, 0); + end Put_IP_CIDR; + + procedure Show_IP_Canonicalize (S : String) is + Canon : IP_CIDR_Type := Parse_IP_CIDR (S); + begin + Canonicalize_IP_Cidr (Canon); + Put (S & " -> "); + Put_IP_CIDR (Canon); + New_Line; + end Show_IP_Canonicalize; + + Test_IPs : array (1 .. 5) of String (1 .. 18) := + ( + "36.18.154.103/12 ", + "62.62.197.11/29 ", + "67.137.119.181/4 ", + "161.214.74.21/24 ", + "184.232.176.184/18" + ); +begin + for I of Test_IPs loop + Show_IP_Canonicalize (I); + end loop; +end Canonicalize_CIDR; diff --git a/Task/Carmichael-3-strong-pseudoprimes/FutureBasic/carmichael-3-strong-pseudoprimes.basic b/Task/Carmichael-3-strong-pseudoprimes/FutureBasic/carmichael-3-strong-pseudoprimes.basic new file mode 100644 index 0000000000..46d957a349 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/FutureBasic/carmichael-3-strong-pseudoprimes.basic @@ -0,0 +1,41 @@ +include "NSLog.incl" + +int local fn SpecialMod( n as int, m as int ) +— + return ((n % m) + m) % m +end fn = 0 + +BOOl local fn IsPrime( n as NSUInteger ) as BOOL +— + if n < 2 then exit fn = NO + if n = 2 then exit fn = YES + if n % 2 == 0 then exit fn = NO + for NSUInteger i = 3 to int(n^.5) step 2 + if n % i == 0 then exit fn = NO + next +end fn = YES + +void local fn Carmichael3( p1 as int ) +— + if (!fn IsPrime(p1)) then return + + int h3, d, p2, p3 + for h3 = 1 to p1 - 1 + for d = 1 to (h3 + p1) -1 + if ((h3 + p1) * (p1 - 1) % d == 0 && fn SpecialMod(-p1 * p1, h3) == d % h3) + p2 = 1 + ((p1 - 1) * (h3 + p1) / d) + if (!fn IsPrime(p2)) then continue + p3 = 1 + (p1 * p2 / h3) + if ( !fn IsPrime(p3) || (p2 * p3) % (p1 - 1) != 1 ) then continue + NSLog( @"%3d * %-5d * %-6d = %ld", p1, p2, p3, p1 * p2 * p3 ) + end if + next + next +end fn + +for int p1 = 2 to 61 + fn Carmichael3(p1) +next +NSLogScrollToTop + +HandleEvents diff --git a/Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-1.duckdb b/Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-1.duckdb new file mode 100644 index 0000000000..fa772220fe --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-1.duckdb @@ -0,0 +1,2 @@ +select array_agg([a,b]) as product +from (select unnest([1,2]) as a), (select unnest([3,4]) as b); diff --git a/Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-2.duckdb b/Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-2.duckdb new file mode 100644 index 0000000000..5714140e23 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/DuckDB/cartesian-product-of-two-or-more-lists-2.duckdb @@ -0,0 +1,8 @@ +create or replace macro cp(x,y) as ( + select array_agg([a,b] order by ix, iy) + from (select unnest(x) as a, unnest(range(0, length(x))) as ix), + (select unnest(y) as b, unnest(range(0, length(y))) as iy) +); + +# Example: +select cp([1,2], [3,4]) as product; diff --git a/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb new file mode 100644 index 0000000000..0b9cd57834 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-1.duckdb @@ -0,0 +1,3 @@ +create or replace function task(dog, Dog, DOG) as ( + format('The three dogs are named {:s}, {:s} and {:s}.', dog, Dog, DOG) +); diff --git a/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb new file mode 100644 index 0000000000..d7c7d9bd1c --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/DuckDB/case-sensitivity-of-identifiers-2.duckdb @@ -0,0 +1,2 @@ +select format('The three dogs are named {:s}, {:s} and {:s}.', dog, Dog, DOG) as example +from (select 'Benjamin' as dog, 'Samba' as Dog, 'Bernie' as DOG); diff --git a/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena index b33d071054..be30409312 100644 --- a/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena +++ b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena @@ -5,5 +5,5 @@ public program() var dog := "Benjamin"; var Dog := "Samba"; var DOG := "Bernie"; - console.printLineFormatted("The three dogs are named {0}, {1} and {2}", dog, Dog, DOG) + Console.printLineFormatted("The three dogs are named {0}, {1} and {2}", dog, Dog, DOG) } diff --git a/Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas b/Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas new file mode 100644 index 0000000000..d697568ba5 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/PascalABC.NET/case-sensitivity-of-identifiers.pas @@ -0,0 +1,8 @@ +var + dog: string; +begin + dog := 'Benjamin'; + Dog := 'Samba'; + DOG := 'Bernie'; + Writeln('There is just one dog named ' + dog); +end. diff --git a/Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto b/Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto new file mode 100644 index 0000000000..79d19b3417 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Pluto/case-sensitivity-of-identifiers.pluto @@ -0,0 +1,13 @@ +do + local dog = "Benjamin"; + do + local Dog = "Samba"; + do + local DOG = "Bernie"; + if DOG != Dog or DOG != dog + then print( $"The three dogs are named: {dog}, {Dog} and {DOG}" ) + else print( $"There is just one dog named: {DOG}" ) + end + end + end +end diff --git a/Task/Casting-out-nines/Pluto/casting-out-nines.pluto b/Task/Casting-out-nines/Pluto/casting-out-nines.pluto new file mode 100644 index 0000000000..123bf40ebc --- /dev/null +++ b/Task/Casting-out-nines/Pluto/casting-out-nines.pluto @@ -0,0 +1,30 @@ +local function cast_out(base, start, finish) + local b = base - 1 + local ran = range(0, b - 1):filter(|n| -> n % b == (n * n) % b) + local x = start // b + local result = {} + while true do + for ran as n do + local k = b * x + n + if k >= start then + if k > finish then return result end + result:insert(k) + end + end + ++x + end +end + +local function print_array(a, w = 3, n = 10) + for i = 1, #a do + io.write(string.format($"%{w}d ", a[i])) + if i % n == 0 then print() end + end + if #a % 10 != n then print() end +end + +print_array(cast_out(16, 1, 255)) +print() +print_array(cast_out(10, 1, 99)) +print() +print_array(cast_out(17, 1, 288)) diff --git a/Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb b/Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb new file mode 100644 index 0000000000..90833b9fbe --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/DuckDB/catalan-numbers-pascals-triangle-1.duckdb @@ -0,0 +1,20 @@ +# Compute nCr naively using UHUGEINT +# The caller should ensure 2r < n +create or replace function nCr_(n, r) as + (with recursive cte as + (SELECT 1::UHUGEINT as c, n as numerator, 1::UHUGEINT as m + UNION ALL + SELECT (c * numerator / m) as c, + (numerator - 1) as numerator, + (m + 1) as m + FROM cte + WHERE m <= r) + SELECT last(c order by m) + FROM cte +); + +create or replace function nCr(n,r) as ( + if( nNew[N + 2]; + t[1] := 1; + + for(i := 1; i <= N; i++) { + + for(j := i; j > 1; j--){ + t[j] := t[j] + t[j - 1]; + }; + + t[i + 1] := t[i]; + + for(j := i + 1; j > 1; j--) { + t[j] := t[j] + t[j - 1]; + }; + + v := t[i + 1] - t[i]; + "{$v} "->Print(); + }; + } +} diff --git a/Task/Catalan-numbers/00-META.yaml b/Task/Catalan-numbers/00-META.yaml index e2478b7550..b52af46da3 100644 --- a/Task/Catalan-numbers/00-META.yaml +++ b/Task/Catalan-numbers/00-META.yaml @@ -1,3 +1,3 @@ --- from: http://rosettacode.org/wiki/Catalan_numbers -note: Arithmetic operations +note: Numbers diff --git a/Task/Catalan-numbers/DuckDB/catalan-numbers.duckdb b/Task/Catalan-numbers/DuckDB/catalan-numbers.duckdb new file mode 100644 index 0000000000..ae5037a4e4 --- /dev/null +++ b/Task/Catalan-numbers/DuckDB/catalan-numbers.duckdb @@ -0,0 +1,30 @@ +# table of the first Catalan numbers up to catalan(n) +# using the DuckDB type determined by `one`, which should be +# 1 of an appropriate type: +create or replace function catalan_t_(mx, one) as table ( + with recursive cte(n,c) as ( + select 0 as n, one as c + union all + select n+1, + 2 * (2 * n + 1) * c / (n+2) + from cte + where n < mx + ) + from cte +); + +# In general, use UHUGEINT +create or replace function catalan_t(mx) as table ( + from catalan_t_(mx, 1::UHUGEINT) +); + +# point-wise +create or replace function catalan(nn) as ( + select c + from catalan_t(nn) + offset nn +); + +from catalan_t(15); + +from catalan_t_(100, 1::DOUBLE) offset 100; diff --git a/Task/Catamorphism/Apple/catamorphism-1.apple b/Task/Catamorphism/Apple/catamorphism-1.apple new file mode 100644 index 0000000000..98e2a06683 --- /dev/null +++ b/Task/Catamorphism/Apple/catamorphism-1.apple @@ -0,0 +1,2 @@ + > (+)/ₒ 10 ⟨1::int,2,3,4,5,6,7,8,9⟩ +55 diff --git a/Task/Catamorphism/Apple/catamorphism-2.apple b/Task/Catamorphism/Apple/catamorphism-2.apple new file mode 100644 index 0000000000..f5028abe67 --- /dev/null +++ b/Task/Catamorphism/Apple/catamorphism-2.apple @@ -0,0 +1,2 @@ + > :ty (/) +(a → a → a) → Arr (i + 1 `Cons` sh) a → Arr sh a diff --git a/Task/Catamorphism/Apple/catamorphism-3.apple b/Task/Catamorphism/Apple/catamorphism-3.apple new file mode 100644 index 0000000000..bb376e7c75 --- /dev/null +++ b/Task/Catamorphism/Apple/catamorphism-3.apple @@ -0,0 +1,2 @@ + > (+)/ ⟨1::int,2,3,4,5,6,7,8,9⟩ +45 diff --git a/Task/Catamorphism/ArkScript/catamorphism.ark b/Task/Catamorphism/ArkScript/catamorphism.ark new file mode 100644 index 0000000000..747ff2cfd7 --- /dev/null +++ b/Task/Catamorphism/ArkScript/catamorphism.ark @@ -0,0 +1,7 @@ +(import std.List :reduce :foldLeft) + +(let sum (fun (a b) (+ a b))) + +(assert (= 10 (reduce [1 2 3 4] sum)) "reduce array to 10") +(assert (= 10 (foldLeft [1 2 3 4] 0 sum)) "fold array to 10") +(assert (= 12 (foldLeft [1 2 3 4] 2 sum)) "fold array to 12 with initial value") diff --git a/Task/Catamorphism/Elena/catamorphism.elena b/Task/Catamorphism/Elena/catamorphism.elena index df104d5f15..7876e7b8fa 100644 --- a/Task/Catamorphism/Elena/catamorphism.elena +++ b/Task/Catamorphism/Elena/catamorphism.elena @@ -13,5 +13,5 @@ public program() var concatenation := numbers.accumulate(new StringWriter(), (a,b => a.toPrintable() + b.toPrintable())); - console.printLine(summary," ",product," ",concatenation) + Console.printLine(summary," ",product," ",concatenation) } diff --git a/Task/Catmull-Clark-subdivision-surface/FreeBASIC/catmull-clark-subdivision-surface.basic b/Task/Catmull-Clark-subdivision-surface/FreeBASIC/catmull-clark-subdivision-surface.basic new file mode 100644 index 0000000000..8b4d224643 --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/FreeBASIC/catmull-clark-subdivision-surface.basic @@ -0,0 +1,250 @@ +Type Punto + x As Double + y As Double + z As Double +End Type + +Type DatosBorde + a As Integer + b As Integer + f1 As Integer + f2 As Integer +End Type + +Dim Shared As Integer datosCara(0 To 4000-1) ' 1000 faces * 4 vertex +Dim Shared As Integer Ptr carasNuevas(0 To 1000-1) + + +Sub printPunto(p As Punto) + Print Using "[##.####, ##.####, ##.####]"; p.x; p.y; p.z +End Sub + +Sub printCara(f As Integer Ptr, n As Integer) + Print "["; + For i As Integer = 0 To n-1 + Print Using "## "; f[i]; + Next + Print Chr(8) & "]" +End Sub + +Function sumPunto(p1 As Punto, p2 As Punto) As Punto + Return Type(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z) +End Function +Function mulPunto(p As Punto, m As Double) As Punto + Return Type(p.x * m, p.y * m, p.z * m) +End Function +Function divPunto(p As Punto, d As Double) As Punto + Return mulPunto(p, 1/d) +End Function +Function centerPunto(p1 As Punto, p2 As Punto) As Punto + Return divPunto(sumPunto(p1, p2), 2) +End Function + +Function encontrarBorde(bordes() As DatosBorde, nBordes As Integer, a As Integer, b As Integer) As Integer + For k As Integer = 0 To nBordes-1 + If (bordes(k).a = a And bordes(k).b = b) Or (bordes(k).a = b And bordes(k).b = a) Then Return k + Next + Return -1 +End Function + +Sub cmcSubdiv(puntosEntrada() As Punto, carasEntrada() As Integer Ptr, carasCnt As Integer, puntosSalida() As Punto, carasSalida() As Integer Ptr, Byref carasSalidaCnt As Integer) + Dim As Integer i, j, n, fi + Dim As Integer Ptr f + + ' Step 1: calculate points of faces + Dim As Punto facePuntos(0 To carasCnt-1) + For i = 0 To carasCnt-1 + f = carasEntrada(i) + n = f[0] + Dim As Punto fp = Type(0,0,0) + For j = 1 To n + fp = sumPunto(fp, puntosEntrada(f[j])) + Next + facePuntos(i) = divPunto(fp, n) + Next + + ' Step 2: calculate unique edges and their faces + Redim As DatosBorde bordes(0 To 0) + Dim As Integer nBordes = 0 + For fi = 0 To carasCnt-1 + f = carasEntrada(fi) + n = f[0] + For i = 1 To n + Dim As Integer a = f[i] + Dim As Integer b = f[Iif(i < n, i+1, 1)] + If a > b Then Swap a, b + Dim As Integer idx = encontrarBorde(bordes(), nBordes, a, b) + If idx = -1 Then + If nBordes > 0 Then Redim Preserve bordes(0 To nBordes) + bordes(nBordes).a = a + bordes(nBordes).b = b + bordes(nBordes).f1 = fi + bordes(nBordes).f2 = -1 + nBordes += 1 + Else + bordes(idx).f2 = fi + End If + Next + Next + Redim Preserve bordes(0 To nBordes-1) + + ' Step 3: calculate edge points + Dim As Punto bordePuntos(0 To Ubound(bordes)) + For i = 0 To Ubound(bordes) + Dim As Punto ea = puntosEntrada(bordes(i).a) + Dim As Punto eb = puntosEntrada(bordes(i).b) + Dim As Punto cp = centerPunto(ea, eb) + Dim As Punto fp1 = facePuntos(bordes(i).f1) + Dim As Punto fp2 = Iif(bordes(i).f2 = -1, fp1, facePuntos(bordes(i).f2)) + Dim As Punto cfp = centerPunto(fp1, fp2) + bordePuntos(i) = centerPunto(cp, cfp) + Next + + ' Step 4: calculate new vertex points + Dim As Integer np = Ubound(puntosEntrada) + 1 + Dim As Integer pointsFaces(0 To np-1) + For fi = 0 To carasCnt-1 + f = carasEntrada(fi) + n = f[0] + For i = 1 To n + pointsFaces(f[i]) += 1 + Next + Next + Dim As Punto newPuntos(0 To np-1) + For i = 0 To np-1 + n = pointsFaces(i) + Dim As Double m1 = (n-3)/n + Dim As Double m2 = 1.0/n + Dim As Double m3 = 2.0/n + Dim As Punto afp = Type(0,0,0) + Dim As Punto ame = Type(0,0,0) + For fi = 0 To carasCnt-1 + f = carasEntrada(fi) + Dim As Integer nface = f[0] + For j = 1 To nface + If f[j] = i Then afp = sumPunto(afp, facePuntos(fi)) + Next + Next + For ei As Integer = 0 To Ubound(bordes) + If bordes(ei).a = i Or bordes(ei).b = i Then + Dim As Punto ea = puntosEntrada(bordes(ei).a) + Dim As Punto eb = puntosEntrada(bordes(ei).b) + ame = sumPunto(ame, centerPunto(ea, eb)) + End If + Next + afp = divPunto(afp, n) + ame = divPunto(ame, n) + Dim p1 As Punto = mulPunto(puntosEntrada(i), m1) + Dim p2 As Punto = mulPunto(afp, m2) + Dim p3 As Punto = mulPunto(ame, m3) + newPuntos(i) = sumPunto(sumPunto(p1, p2), p3) + Next + + ' Step 5: add face points + Dim As Integer caraPuntoNums(0 To carasCnt-1) + Dim As Integer sgtePuntoNum = np + Redim Preserve newPuntos(0 To sgtePuntoNum + carasCnt - 1) + For i = 0 To carasCnt-1 + newPuntos(sgtePuntoNum) = facePuntos(i) + caraPuntoNums(i) = sgtePuntoNum + sgtePuntoNum += 1 + Next + + ' Step 6: add edge points + Dim As Integer bordePuntoNums(0 To Ubound(bordes)) + Redim Preserve newPuntos(0 To sgtePuntoNum + Ubound(bordes)) + For i = 0 To Ubound(bordes) + newPuntos(sgtePuntoNum) = bordePuntos(i) + bordePuntoNums(i) = sgtePuntoNum + sgtePuntoNum += 1 + Next + + ' Step 7: build new faces (quads only) + Dim As Integer totalNewCaras = carasCnt * 4 + Dim As Integer caraLen = 4 + Dim As Integer caraIdx = 0 + For fi = 0 To carasCnt-1 + f = carasEntrada(fi) + If f[0] = 4 Then + Dim As Integer a = f[1], b = f[2], c = f[3], d = f[4] + Dim As Integer ab, bc, cd, da + For ei As Integer = 0 To Ubound(bordes) + If (bordes(ei).a = a And bordes(ei).b = b) Or (bordes(ei).a = b And bordes(ei).b = a) Then ab = bordePuntoNums(ei) + If (bordes(ei).a = b And bordes(ei).b = c) Or (bordes(ei).a = c And bordes(ei).b = b) Then bc = bordePuntoNums(ei) + If (bordes(ei).a = c And bordes(ei).b = d) Or (bordes(ei).a = d And bordes(ei).b = c) Then cd = bordePuntoNums(ei) + If (bordes(ei).a = d And bordes(ei).b = a) Or (bordes(ei).a = a And bordes(ei).b = d) Then da = bordePuntoNums(ei) + Next + Dim As Integer fp = caraPuntoNums(fi) + ' Face 1 + datosCara(caraIdx*caraLen + 0) = a + datosCara(caraIdx*caraLen + 1) = ab + datosCara(caraIdx*caraLen + 2) = fp + datosCara(caraIdx*caraLen + 3) = da + carasNuevas(caraIdx) = @datosCara(caraIdx*caraLen) + caraIdx += 1 + ' Face 2 + datosCara(caraIdx*caraLen + 0) = b + datosCara(caraIdx*caraLen + 1) = bc + datosCara(caraIdx*caraLen + 2) = fp + datosCara(caraIdx*caraLen + 3) = ab + carasNuevas(caraIdx) = @datosCara(caraIdx*caraLen) + caraIdx += 1 + ' Face 3 + datosCara(caraIdx*caraLen + 0) = c + datosCara(caraIdx*caraLen + 1) = cd + datosCara(caraIdx*caraLen + 2) = fp + datosCara(caraIdx*caraLen + 3) = bc + carasNuevas(caraIdx) = @datosCara(caraIdx*caraLen) + caraIdx += 1 + ' Face 4 + datosCara(caraIdx*caraLen + 0) = d + datosCara(caraIdx*caraLen + 1) = da + datosCara(caraIdx*caraLen + 2) = fp + datosCara(caraIdx*caraLen + 3) = cd + carasNuevas(caraIdx) = @datosCara(caraIdx*caraLen) + caraIdx += 1 + End If + Next + + Redim puntosSalida(0 To Ubound(newPuntos)) + For i = 0 To Ubound(newPuntos): puntosSalida(i) = newPuntos(i): Next + Redim carasSalida(0 To caraIdx-1) + For i = 0 To caraIdx-1: carasSalida(i) = carasNuevas(i): Next + carasSalidaCnt = caraIdx +End Sub + +' Main program +Dim As Punto puntosEntrada(0 To 7) = { _ +Type(-1, 1, 1), _ ' 0 +Type(-1, -1, 1), _ ' 1 +Type( 1, -1, 1), _ ' 2 +Type( 1, 1, 1), _ ' 3 +Type( 1, -1, -1), _ ' 4 +Type( 1, 1, -1), _ ' 5 +Type(-1, -1, -1), _ ' 6 +Type(-1, 1, -1) } ' 7 + +Dim As Integer f0(0 To 4) = {4, 0, 1, 2, 3} +Dim As Integer f1(0 To 4) = {4, 3, 2, 4, 5} +Dim As Integer f2(0 To 4) = {4, 5, 4, 6, 7} +Dim As Integer f3(0 To 4) = {4, 7, 0, 3, 5} +Dim As Integer f4(0 To 4) = {4, 7, 6, 1, 0} +Dim As Integer f5(0 To 4) = {4, 6, 1, 2, 4} + +Dim As Integer Ptr carasEntrada(0 To 5) = {@f0(0), @f1(0), @f2(0), @f3(0), @f4(0), @f5(0)} +Dim As Punto puntosSalida() +Dim As Integer Ptr carasSalida() +Dim As Integer carasSalidaCnt, i + +cmcSubdiv(puntosEntrada(), carasEntrada(), 6, puntosSalida(), carasSalida(), carasSalidaCnt) + +For i = 0 To Ubound(puntosSalida) + printPunto(puntosSalida(i)) +Next + +Print Chr(10) +For i = 0 To carasSalidaCnt-1 + printCara(carasSalida(i), 4) +Next + +Sleep diff --git a/Task/Catmull-Clark-subdivision-surface/JavaScript/catmull-clark-subdivision-surface.js b/Task/Catmull-Clark-subdivision-surface/JavaScript/catmull-clark-subdivision-surface.js new file mode 100644 index 0000000000..f791b148c1 --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/JavaScript/catmull-clark-subdivision-surface.js @@ -0,0 +1,255 @@ +// A point of the current Catmull-Clark surface. +class Point { + constructor(x = 0.0, y = 0.0, z = 0.0) { + this.x = x; + this.y = y; + this.z = z; + } + + add(other) { + return new Point(this.x + other.x, this.y + other.y, this.z + other.z); + } + + multiply(factor) { + return new Point(this.x * factor, this.y * factor, this.z * factor); + } + + divide(factor) { + return this.multiply(1.0 / factor); + } + + lessThan(other) { + return (this.x < other.x) || + (this.x === other.x && this.y < other.y) || + (this.x === other.x && this.y === other.y && this.z < other.z); + } + + equals(other) { + return this.x === other.x && this.y === other.y && this.z === other.z; + } + + format(value) { + const formattedValue = value.toFixed(3); + return (value >= 0) ? " " + formattedValue : formattedValue; + } + + toString() { + return "(" + this.format(this.x) + ", " + this.format(this.y) + ", " + this.format(this.z) + ")"; + } +} + +// Return the centroid point of the given array of points. +function centroid(points) { + let sum = new Point(); + for (const point of points) { + sum = sum.add(point); + } + return sum.divide(points.length); +} + +// An edge of the current Catmull-Clark surface. +class Edge { + constructor(aBegin, aEnd) { + if (aEnd.lessThan(aBegin)) { + [aBegin, aEnd] = [aEnd, aBegin]; + } + this.begin = aBegin; + this.end = aEnd; + this.mid_edge = centroid([this.begin, this.end]); + this.hole_edge = false; + } + + contains(point) { + return point.equals(this.begin) || point.equals(this.end); + } + + lessThan(other) { + return this.begin.lessThan(other.begin) || + (this.begin.equals(other.begin) && this.end.lessThan(other.end)); + } + + equals(other) { + return this.contains(other.begin) && this.contains(other.end); + } +} + +// A face of the current Catmull-Clark surface. +class Face { + constructor(aVertices) { + this.vertices = aVertices; + this.face_point = centroid(this.vertices); + this.edges = []; + + for (let i = 0; i < this.vertices.length - 1; ++i) { + this.edges.push(new Edge(this.vertices[i], this.vertices[i + 1])); + } + this.edges.push(new Edge(this.vertices[this.vertices.length - 1], this.vertices[0])); + } + + contains(vertex) { + if (vertex instanceof Point) { + return this.vertices.some(v => v.equals(vertex)); + } else if (vertex instanceof Edge) { + return this.contains(vertex.begin) && this.contains(vertex.end); + } + return false; + } + + toString() { + let result = "Face: "; + for (let i = 0; i < this.vertices.length - 1; ++i) { + result += this.vertices[i].toString() + ", "; + } + return result + this.vertices[this.vertices.length - 1].toString(); + } +} + +// Return a map containing, for each vertex, +// the new vertex created by the current iteration of the Catmull-Clark surface subdivision algorithm. +function next_vertices(edges, faces) { + const next_vertices_map = new Map(); + const vertices = new Set(); + + // Collect all unique vertices + for (const face of faces) { + for (const vertex of face.vertices) { + vertices.add(vertex); + } + } + + // Convert Set to Array for iteration + const verticesArray = Array.from(vertices); + + for (const vertex of verticesArray) { + const faces_for_vertex = faces.filter(face => face.contains(vertex)); + const edges_for_vertex = edges.filter(edge => edge.contains(vertex)); + + if (faces_for_vertex.length !== edges_for_vertex.length) { + const mid_edge_of_hole_edges = edges_for_vertex + .filter(edge => edge.hole_edge) + .map(edge => edge.mid_edge); + + mid_edge_of_hole_edges.push(vertex); + next_vertices_map.set(vertex, centroid(mid_edge_of_hole_edges)); + } else { + const face_count = faces_for_vertex.length; + const multiple_1 = (face_count - 3) / face_count; + const multiple_2 = 1.0 / face_count; + const multiple_3 = 2.0 / face_count; + + const next_vertex_1 = vertex.multiply(multiple_1); + const face_points = faces_for_vertex.map(face => face.face_point); + const next_vertex_2 = centroid(face_points).multiply(multiple_2); + const mid_edges = edges_for_vertex.map(edge => edge.mid_edge); + const next_vertex_3 = centroid(mid_edges).multiply(multiple_3); + const next_vertex_4 = next_vertex_1.add(next_vertex_2); + + next_vertices_map.set(vertex, next_vertex_4.add(next_vertex_3)); + } + } + + return next_vertices_map; +} + +// The Catmull-Clarke surface subdivision algorithm. +function catmull_clark_surface_subdivision(faces) { + // Determine, for each edge, whether or not it is an edge of a hole, + // and set its edge point accordingly. + for (const face of faces) { + for (const edge of face.edges) { + const face_points_for_edge = []; + for (const search_face of faces) { + if (search_face.contains(edge)) { + face_points_for_edge.push(search_face.face_point); + } + } + + if (face_points_for_edge.length === 2) { + edge.hole_edge = false; + edge.edge_point = centroid([edge.mid_edge, centroid(face_points_for_edge)]); + } else { + edge.hole_edge = true; + edge.edge_point = edge.mid_edge; + } + } + } + + // Collect all edges + const edges = []; + for (const face of faces) { + for (const edge of face.edges) { + edges.push(edge); + } + } + + const next_vertex_map = next_vertices(edges, faces); + const next_faces = []; + + for (const face of faces) { + if (face.vertices.length >= 3) { // A face with 2 or fewer points does not contribute to the surface + const face_point = face.face_point; + for (let i = 0; i < face.vertices.length; ++i) { + const prevIndex = (i - 1 + face.vertices.length) % face.vertices.length; + next_faces.push(new Face([ + next_vertex_map.get(face.vertices[i]), + face.edges[i].edge_point, + face_point, + face.edges[prevIndex].edge_point + ])); + } + } + } + + return next_faces; +} + +// Display the current Catmull-Clark surface on the console. +function displaySurface(faces) { + console.log("Surface {"); + for (const face of faces) { + console.log(face.toString()); + } + console.log("}"); + console.log(); +} + +// Main function +function main() { + const faces = [ + new Face([ + new Point(-1.0, 1.0, 1.0), new Point(-1.0, -1.0, 1.0), + new Point(1.0, -1.0, 1.0), new Point(1.0, 1.0, 1.0) + ]), + new Face([ + new Point(1.0, 1.0, 1.0), new Point(1.0, -1.0, 1.0), + new Point(1.0, -1.0, -1.0), new Point(1.0, 1.0, -1.0) + ]), + new Face([ + new Point(1.0, 1.0, -1.0), new Point(1.0, -1.0, -1.0), + new Point(-1.0, -1.0, -1.0), new Point(-1.0, 1.0, -1.0) + ]), + new Face([ + new Point(-1.0, 1.0, -1.0), new Point(-1.0, 1.0, 1.0), + new Point(1.0, 1.0, 1.0), new Point(1.0, 1.0, -1.0) + ]), + new Face([ + new Point(-1.0, 1.0, -1.0), new Point(-1.0, -1.0, -1.0), + new Point(-1.0, -1.0, 1.0), new Point(-1.0, 1.0, 1.0) + ]), + new Face([ + new Point(-1.0, -1.0, -1.0), new Point(-1.0, -1.0, 1.0), + new Point(1.0, -1.0, 1.0), new Point(1.0, -1.0, -1.0) + ]) + ]; + + displaySurface(faces); + const iterations = 1; + let result = faces; + for (let i = 0; i < iterations; ++i) { + result = catmull_clark_surface_subdivision(result); + } + displaySurface(result); +} + +// Run the main function +main(); diff --git a/Task/Chaocipher/Swift/chaocipher.swift b/Task/Chaocipher/Swift/chaocipher.swift new file mode 100644 index 0000000000..ae0cc62b27 --- /dev/null +++ b/Task/Chaocipher/Swift/chaocipher.swift @@ -0,0 +1,84 @@ +enum Mode { + case encrypt + case decrypt +} + +class Chaocipher { + private static let L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" + private static let R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC" + + private static func indexOf(array: [Character], char: Character) -> Int { + for i in 0.. String { + var left = Array(L_ALPHABET) + var right = Array(R_ALPHABET) + var eText = [Character](repeating: " ", count: text.count) + var temp = [Character](repeating: " ", count: 26) + + let textChars = Array(text) + + for i in 0.. String { + return exec(text: text, mode: .encrypt, showSteps: showSteps) + } + + static func decrypt(text: String, showSteps: Bool = false) -> String { + return exec(text: text, mode: .decrypt, showSteps: showSteps) + } +} + +// Main program +let plainText = "WELLDONEISBETTERTHANWELLSAID" +print("The original plaintext is : \(plainText)") +print("\nThe left and right alphabets after each permutation during encryption are:") +let cipherText = Chaocipher.encrypt(text: plainText, showSteps: true) +print("\nThe cipher text is : \(cipherText)") +let plainText2 = Chaocipher.decrypt(text: cipherText) +print("\nThe recovered plaintext is : \(plainText2)") diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index 6dbbbee50c..406defaafb 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -4,6 +4,6 @@ public program() { var ch := $97; - console.printLine(ch); - console.printLine(ch.toInt()) + Console.printLine(ch); + Console.printLine(ch.toInt()) } diff --git a/Task/Character-codes/Haxe/character-codes.haxe b/Task/Character-codes/Haxe/character-codes.haxe new file mode 100644 index 0000000000..3d1788b91d --- /dev/null +++ b/Task/Character-codes/Haxe/character-codes.haxe @@ -0,0 +1,7 @@ +class Main { + static public function main():Void { + trace("a".code); + trace("∅".code); + trace("🍆".code); + } +} diff --git a/Task/Character-codes/TAV/character-codes.tav b/Task/Character-codes/TAV/character-codes.tav new file mode 100644 index 0000000000..727bf15da6 --- /dev/null +++ b/Task/Character-codes/TAV/character-codes.tav @@ -0,0 +1,2 @@ + print string 'a' code point at 1 \ print 'a'.Codepoint + print integer 97 code point as string \ print 97.Character diff --git a/Task/Check-that-file-exists/ArkScript/check-that-file-exists.ark b/Task/Check-that-file-exists/ArkScript/check-that-file-exists.ark new file mode 100644 index 0000000000..8539bbafb5 --- /dev/null +++ b/Task/Check-that-file-exists/ArkScript/check-that-file-exists.ark @@ -0,0 +1,4 @@ +(print (io:fileExists? "input.txt")) +(print (io:fileExists? "/input.txt")) +(print (io:fileExists? "docs")) +(print (io:fileExists? "/docs")) diff --git a/Task/Check-that-file-exists/DuckDB/check-that-file-exists.duckdb b/Task/Check-that-file-exists/DuckDB/check-that-file-exists.duckdb new file mode 100644 index 0000000000..0e8902d3b1 --- /dev/null +++ b/Task/Check-that-file-exists/DuckDB/check-that-file-exists.duckdb @@ -0,0 +1,2 @@ +create or replace function file_exists(fn) as ( + 1 = (select count(file) from glob(fn)) ); diff --git a/Task/Check-that-file-exists/Elena/check-that-file-exists.elena b/Task/Check-that-file-exists/Elena/check-that-file-exists.elena index 2e7f05f379..35caac60bf 100644 --- a/Task/Check-that-file-exists/Elena/check-that-file-exists.elena +++ b/Task/Check-that-file-exists/Elena/check-that-file-exists.elena @@ -9,11 +9,11 @@ extension op public program() { - console.printLine("input.txt file ",File.assign("input.txt").validatePath()); + Console.printLine("input.txt file ",File.assign("input.txt").validatePath()); - console.printLine("\input.txt file ",File.assign("\input.txt").validatePath()); + Console.printLine("\input.txt file ",File.assign("\input.txt").validatePath()); - console.printLine("docs directory ",Directory.assign("docs").validatePath()); + Console.printLine("docs directory ",Directory.assign("docs").validatePath()); - console.printLine("\docs directory ",Directory.assign("\docs").validatePath()) + Console.printLine("\docs directory ",Directory.assign("\docs").validatePath()) } diff --git a/Task/Checkpoint-synchronization/JavaScript/checkpoint-synchronization.js b/Task/Checkpoint-synchronization/JavaScript/checkpoint-synchronization.js new file mode 100644 index 0000000000..da445826e3 --- /dev/null +++ b/Task/Checkpoint-synchronization/JavaScript/checkpoint-synchronization.js @@ -0,0 +1,47 @@ +class Latch { + constructor(limit) { + this.semafor = limit; + this.lock = new Promise(resolve => { + this.resolve = resolve; + }); + } + + wait() { + this.semafor--; + if (this.semafor === 0) { + this.resolve(); + } + return this.lock; + } +} + +class Worker { + static async doWork(howLong, barrier, name) { + await new Promise(resolve => setTimeout(resolve, howLong)); + console.log(`Worker ${name} finished work`); + await barrier.wait(); + console.log(`Worker ${name} finished assembly`); + } +} + +async function main() { + const latch = new Latch(5); + + // Random number generator function + const getRandomInt = (min, max) => { + return Math.floor(Math.random() * (max - min + 1)) + min; + }; + + const promises = [ + Worker.doWork(getRandomInt(300, 3000), latch, "John"), + Worker.doWork(getRandomInt(300, 3000), latch, "Henry"), + Worker.doWork(getRandomInt(300, 3000), latch, "Smith"), + Worker.doWork(getRandomInt(300, 3000), latch, "Jane"), + Worker.doWork(getRandomInt(300, 3000), latch, "Mary") + ]; + + await Promise.all(promises); + console.log("Assembly is finished"); +} + +main(); diff --git a/Task/Chinese-zodiac/Fortran/chinese-zodiac.f b/Task/Chinese-zodiac/Fortran/chinese-zodiac.f new file mode 100644 index 0000000000..8b06c9ce9c --- /dev/null +++ b/Task/Chinese-zodiac/Fortran/chinese-zodiac.f @@ -0,0 +1,62 @@ +program chinese_zodiac + implicit none + + ! Define arrays for animals and elements + character(len=10), dimension(12) :: animals = [character(len=10) :: & + "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", & + "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] + character(len=10), dimension(5) :: elements = [character(len=10) :: & + "Wood", "Fire", "Earth", "Metal", "Water"] + + ! Define test years + integer, parameter :: numyears=9 + integer, dimension(numyears) :: years = [1935, 1938, 1957, 1968, 1972, 1976, 2006, 2017, 2025] + integer :: i, year + write(*,'(/)') + + ! Loop through years and print zodiac information + do i = 1, numyears + year = years(i) + write(*, '(I4, A)') year, " is the year of the " // & + trim(get_element(year)) // " " // & + trim(get_animal(year)) // " (" // & + trim(get_yy(year)) // ")." + end do + write(*,'(/)') +contains + + ! Function to get the element based on year + function get_element(year) result(element) + integer, intent(in) :: year + character(len=10) :: element + integer :: idx +! idx = floor(real((year - 4) / 2) / 5.0) + 1 + idx = floor(real(modulo(year - 4, 10)) / 2.0) + 1 + if (idx < 1) idx = 1 + if (idx > 5) idx = 5 + element = elements(idx) + end function get_element + + ! Function to get the animal based on year + function get_animal(year) result(animal) + integer, intent(in) :: year + character(len=10) :: animal + integer :: idx + idx = modulo(year - 4, 12) + 1 + if (idx < 1) idx = 1 + if (idx > 12) idx = 12 + animal = animals(idx) + end function get_animal + + ! Function to get yin/yang based on year + function get_yy(year) result(yy) + integer, intent(in) :: year + character(len=4) :: yy + if (modulo(year, 2) == 0) then + yy = "yang" + else + yy = "yin" + end if + end function get_yy + +end program chinese_zodiac diff --git a/Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy b/Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy new file mode 100644 index 0000000000..f06a3216a5 --- /dev/null +++ b/Task/Cholesky-decomposition/EasyLang/cholesky-decomposition.easy @@ -0,0 +1,19 @@ +func[][] cholesky a[][] . + n = len a[][] + len r[][] n + for i to n + len r[i][] n + for j to i + s = 0 + for k to j : s += r[i][k] * r[j][k] + if i = j + r[i][j] = sqrt (a[i][i] - s) + else + r[i][j] = 1 / r[j][j] * (a[i][j] - s) + . + . + . + return r[][] +. +print cholesky [ [ 25 15 -5 ] [ 15 18 0 ] [ -5 0 11 ] ] +print cholesky [ [ 18 22 54 42 ] [ 22 70 86 62 ] [ 54 86 174 134 ] [ 42 62 134 106 ] ] diff --git a/Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig b/Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig new file mode 100644 index 0000000000..39a4ebad30 --- /dev/null +++ b/Task/Cholesky-decomposition/Zig/cholesky-decomposition.zig @@ -0,0 +1,64 @@ +const std = @import("std"); + +fn cholesky(mat: []const f64, n: usize, allocator: std.mem.Allocator) ![]f64 { + const res = try allocator.alloc(f64, mat.len); + @memset(res, 0.0); + + for (0..n) |i| { + for (0..i+1) |j| { + var s: f64 = 0.0; + for (0..j) |k| { + s += res[i * n + k] * res[j * n + k]; + } + + res[i * n + j] = if (i == j) + std.math.sqrt(mat[i * n + i] - s) + else + (1.0 / res[j * n + j] * (mat[i * n + j] - s)); + } + } + return res; +} + +fn showMatrix(matrix: []const f64, n: usize) void { + for (0..n) |i| { + for (0..n) |j| { + std.debug.print("{d:.4}\t", .{matrix[i * n + j]}); + } + std.debug.print("\n", .{}); + } + std.debug.print("\n", .{}); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + defer _ = gpa.deinit(); + + { + const dimension: usize = 3; + const m1 = [_]f64{ + 25.0, 15.0, -5.0, + 15.0, 18.0, 0.0, + -5.0, 0.0, 11.0 + }; + + const res1 = try cholesky(&m1, dimension, allocator); + defer allocator.free(res1); + showMatrix(res1, dimension); + } + + { + const dimension: usize = 4; + const m2 = [_]f64{ + 18.0, 22.0, 54.0, 42.0, + 22.0, 70.0, 86.0, 62.0, + 54.0, 86.0, 174.0, 134.0, + 42.0, 62.0, 134.0, 106.0 + }; + + const res2 = try cholesky(&m2, dimension, allocator); + defer allocator.free(res2); + showMatrix(res2, dimension); + } +} diff --git a/Task/Chowla-numbers/REXX/chowla-numbers.rexx b/Task/Chowla-numbers/REXX/chowla-numbers.rexx index 32d54ed564..5e9fe0aa6e 100644 --- a/Task/Chowla-numbers/REXX/chowla-numbers.rexx +++ b/Task/Chowla-numbers/REXX/chowla-numbers.rexx @@ -1,17 +1,17 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings +numeric digits 12 say 'CHOWLA NUMBERS' say version say -numeric digits 12 call ChowlaNumbers call PrimeCount call PerfectNumbers exit ChowlaNumbers: -procedure expose glob. +procedure expose Memo. call Time('r'); sep = Copies('-',12) say sep; say ' n Chowla(n)'; say sep m = 37 @@ -24,7 +24,7 @@ say return PrimeCount: -procedure expose glob. work. +procedure expose Memo. work. call Time('r'); sep = Copies('-',17) say sep; say Right('n',8) Right('Primes= 0 && r < Size && c >= 0 && c < Size) // Check bounds + _cells[r, c] = '*'; + } + } + + public void Show() + { + for (int i = 0; i < Size; i++) + { + for (int j = 0; j < Size; j++) + Console.Write(_cells[i, j]); + Console.WriteLine(); + } + } +} + +public static class Numerals +{ + // Draws the Cistercian numeral 'number' on the 'canvas'. + public static void DrawNumber(Canvas canvas, uint number) + { + int rAxis = (canvas.Size - 1) / 2; // Horizontal axis position + int cAxis = 5; // Vertical axis position + + // Draw vertical axis + canvas.DrawLine(0, cAxis, canvas.Size - 1, 1, 0); + + byte thousands = (byte)(number / 1000); + number %= 1000; + byte hundreds = (byte)(number / 100); + number %= 100; + byte tens = (byte)(number / 10); + byte ones = (byte)(number % 10); + + // Draw digits in their respective quadrants + if (thousands > 0) + DrawDigit(canvas, thousands, rAxis, cAxis, 1, -1); // Top left + if (hundreds > 0) + DrawDigit(canvas, hundreds, rAxis, cAxis, 1, 1); // Top right + if (tens > 0) + DrawDigit(canvas, tens, rAxis, cAxis, -1, -1); // Bottom left + if (ones > 0) + DrawDigit(canvas, ones, rAxis, cAxis, -1, 1); // Bottom right + } + + + // Draws the digit 'v' in the appropriate quadrant, determined by 'rs' and 'cs'. + // rs, cs are signs (1 or -1) for rows and columns relative to the axes. + private static void DrawDigit(Canvas canvas, byte digit, int rAxis, int cAxis, int rs, int cs) + { + switch (digit) + { + case 1: + canvas.DrawLine(rAxis + rs * 7, cAxis + cs, 4, 0, cs); + break; + case 2: + canvas.DrawLine(rAxis + rs * 3, cAxis + cs, 4, 0, cs); + break; + case 3: + canvas.DrawLine(rAxis + rs * 7, cAxis + cs, 4, -rs, cs); + break; + case 4: + canvas.DrawLine(rAxis + rs * 3, cAxis + cs, 4, rs, cs); + break; + case 5: + DrawDigit(canvas, 1, rAxis, cAxis, rs, cs); + DrawDigit(canvas, 4, rAxis, cAxis, rs, cs); + break; + case 6: + canvas.DrawLine(rAxis + rs * 3, cAxis + cs * 5, 4, rs, 0); + break; + case 7: + DrawDigit(canvas, 1, rAxis, cAxis, rs, cs); + DrawDigit(canvas, 6, rAxis, cAxis, rs, cs); + break; + case 8: + DrawDigit(canvas, 2, rAxis, cAxis, rs, cs); + DrawDigit(canvas, 6, rAxis, cAxis, rs, cs); + break; + case 9: + DrawDigit(canvas, 1, rAxis, cAxis, rs, cs); + DrawDigit(canvas, 8, rAxis, cAxis, rs, cs); + break; + } + } +} + +class Program +{ + public static void Test(uint n) + { + Console.WriteLine("{0}:", n); + Canvas canvas = new Canvas(15); + Numerals.DrawNumber(canvas, n); + canvas.Show(); + Console.WriteLine(); + } + + public static void Main() + { + Test(0); + Test(1); + Test(20); + Test(300); + Test(4000); + Test(5555); + Test(6789); + Test(9999); + } +} diff --git a/Task/Cistercian-numerals/Free-Pascal-Lazarus/cistercian-numerals.pas b/Task/Cistercian-numerals/Free-Pascal-Lazarus/cistercian-numerals.pas new file mode 100644 index 0000000000..767f3d587f --- /dev/null +++ b/Task/Cistercian-numerals/Free-Pascal-Lazarus/cistercian-numerals.pas @@ -0,0 +1,151 @@ +program CistercianNumerals; + +type + TSignVals = -1 .. 1; + + TCanvas = object + public + procedure Init(GridSize: integer); + procedure Clear; + procedure DrawLine(R0, C0, Dist: integer; DR, DC: TSignVals); + procedure Show; + function Size: integer; + private + Cells: array of array of char; + MaxCoord: integer; + end; + + procedure TCanvas.Init(GridSize: integer); + begin + SetLength(Cells, GridSize, GridSize); + MaxCoord := GridSize - 1; + end; + + procedure TCanvas.Clear; + var + I, J: integer; + begin + for I := 0 to MaxCoord do + for J := 0 to MaxCoord do + Cells[I, J] := ' '; + end; + + procedure TCanvas.DrawLine(R0, C0, Dist: integer; DR, DC: TSignVals); + { Draws a straight (vertical, horizontal, or diagonal) line + from Cells[R0, C0] to Cells[R0 + DR * Dist, C0 + DC * Dist]. } + var + C, R, I: integer; + begin + R := R0; + C := C0; + for I := 0 to Dist do + begin + Cells[R, C] := '*'; + R := R + DR; + C := C + DC; + end; + end; + + procedure TCanvas.Show; + var + I, J: integer; + begin + for I := 0 to MaxCoord do + begin + for J := 0 to MaxCoord do + Write(Cells[I, J]); + WriteLn; + end; + end; + + function TCanvas.Size: integer; + begin + Result := MaxCoord + 1; + end; + + procedure DrawNumber(var Canvas: TCanvas; V: integer); + { DrawDigit is part of the algorithm, so it is nested in DrawNumber. } + type + TDigits = 0 .. 9; + var + Thousands, Hundreds, Tens, Ones: integer; + RAxis, CAxis: integer; + + procedure DrawDigit(V: TDigits; RS, CS: TSignVals); + { RS, CS are signs of rows and cols in in relation to the axis. + They decide in which quadrant a digit is located. } + begin + case V of + 1: Canvas.DrawLine(RAxis + RS * 7, CAxis + CS, 4, 0, CS); + 2: Canvas.DrawLine(RAxis + RS * 3, CAxis + CS, 4, 0, CS); + 3: Canvas.DrawLine(RAxis + RS * 7, CAxis + CS, + 4, -RS, CS); + 4: Canvas.DrawLine(RAxis + RS * 3, CAxis + CS, 4, RS, CS); + 5: + begin + DrawDigit(1, RS, CS); + DrawDigit(4, RS, CS); + end; + 6: Canvas.DrawLine(RAxis + RS * 3, CAxis + CS * 5, 4, RS, 0); + 7: + begin + DrawDigit(1, RS, CS); + DrawDigit(6, RS, CS); + end; + 8: + begin + DrawDigit(2, RS, CS); + DrawDigit(6, RS, CS); + end; + 9: + begin + DrawDigit(1, RS, CS); + DrawDigit(8, RS, CS); + end + end; + end; {DrawDigit} + + begin {DrawNumber} + RAxis := (Canvas.Size - 1) div 2; + CAxis := 5; + Canvas.DrawLine(0, CAxis, Canvas.Size - 1, 1, 0); + {Draw 0 (or vertical axis)} + Thousands := V div 1000; + V := V mod 1000; + Hundreds := V div 100; + V := V mod 100; + Tens := V div 10; + Ones := V mod 10; + if Thousands > 0 then + DrawDigit(Thousands, 1, -1); + if Hundreds > 0 then + DrawDigit(Hundreds, 1, 1); + if Tens > 0 then + DrawDigit(Tens, -1, -1); + if Ones > 0 then + DrawDigit(Ones, -1, 1); + end; {DrawNumber} + + procedure Test(N: integer); + var + Canvas: TCanvas; + begin + WriteLn(N, ':'); + Canvas.Init(15); + Canvas.Clear; + DrawNumber(Canvas, N); + Canvas.Show; + WriteLn; + end; + +begin + Test(0); + Test(1); + Test(20); + Test(300); + Test(4000); + Test(5555); + Test(6789); + Test(9999); + // ReadLn; +end. diff --git a/Task/Cistercian-numerals/Modula-2/cistercian-numerals.mod2 b/Task/Cistercian-numerals/Modula-2/cistercian-numerals.mod2 new file mode 100644 index 0000000000..0e4ec4c24f --- /dev/null +++ b/Task/Cistercian-numerals/Modula-2/cistercian-numerals.mod2 @@ -0,0 +1,132 @@ +MODULE CistercianNumerals; +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +CONST + MaxCoord = 14; + +TYPE + TCanvas = ARRAY [0 .. MaxCoord], [0 .. MaxCoord] OF CHAR; + TSignVals = [-1 .. 1]; + +(* BEGIN. Operations on the TCanvas ADT. *) +PROCEDURE ClearCanvas(VAR Canvas: TCanvas); +VAR + I, J: CARDINAL; +BEGIN + FOR I := 0 TO MaxCoord DO + FOR J := 0 TO MaxCoord DO + Canvas[I, J] := ' ' + END + END +END ClearCanvas; + +PROCEDURE DrawLine(VAR Canvas: TCanvas; R0, C0: CARDINAL; + Dist: CARDINAL; DR, DC: TSignVals); +(* Draws a straight (vertical, horizontal, or diagonal) line + from Canvas[R0, C0] to Canvas[R0 + DR * Dist, C0 + DC * Dist]. *) +VAR + C, R, I: CARDINAL; +BEGIN + R := R0; C := C0; + FOR I := 0 TO Dist DO + Canvas[R, C] := '*'; + R := INT(R) + DR; C := INT(C) + DC; + END +END DrawLine; + +PROCEDURE ShowCanvas(VAR Canvas: TCanvas); +VAR + I, J: CARDINAL; + Row: ARRAY [0 .. MaxCoord + 1] OF CHAR; +BEGIN + FOR I := 0 TO MaxCoord DO + FOR J := 0 TO MaxCoord DO + Row[J] := Canvas[I, J] + END; + Row[MaxCoord + 1] := CHR(0); + WriteString(Row); + WriteLn + END +END ShowCanvas; +(* END Operations on the TCanvas ADT. *) + +PROCEDURE DrawNumber(VAR Canvas: TCanvas; V: CARDINAL); +(* DrawDigit is part of the algorithm, so it is nested in DrawNumber. *) +TYPE + TDigits = [0 .. 9]; +VAR + Thousands, Hundreds, Tens, Ones: CARDINAL; + RAxis, CAxis: CARDINAL; + + PROCEDURE DrawDigit(V: TDigits; RS, CS: TSignVals); + (* RS, CS are signs of rows and cols in in relation to the axis. + They decide in which quadrant a digit is located. *) + VAR + IRS, ICS: CARDINAL; + BEGIN + IRS := INT(RS); + ICS := INT(CS); + CASE V OF + | 1: DrawLine(Canvas, RAxis + IRS * 7, CAxis + ICS, 4, 0, CS) + | 2: DrawLine(Canvas, RAxis + IRS * 3, CAxis + ICS, 4, 0, CS) + | 3: DrawLine(Canvas, RAxis + IRS * 7, CAxis + ICS, 4, -RS, CS) + | 4: DrawLine(Canvas, RAxis + IRS * 3, CAxis + ICS, 4, RS, CS) + | 5: DrawDigit(1, RS, CS); DrawDigit(4, RS, CS) + | 6: DrawLine(Canvas, RAxis + IRS * 3, CAxis + ICS * 5, 4, RS, 0) + | 7: DrawDigit(1, RS, CS); DrawDigit(6, RS, CS) + | 8: DrawDigit(2, RS, CS); DrawDigit(6, RS, CS) + | 9: DrawDigit(1, RS, CS); DrawDigit(8, RS, CS) + ELSE + END; + END DrawDigit; + +BEGIN (*DrawNumber *) + RAxis := MaxCoord DIV 2; + CAxis := 5; + DrawLine(Canvas, 0, CAxis, MaxCoord, 1, 0); (* Draw 0 (or vertical axis) *) + Thousands := V DIV 1000; + V := V MOD 1000; + Hundreds := V DIV 100; + V := V MOD 100; + Tens := V DIV 10; + Ones := V MOD 10; + IF Thousands > 0 THEN + DrawDigit(Thousands, 1, -1) + END; + IF Hundreds > 0 THEN + DrawDigit(Hundreds, 1, 1) + END; + IF Tens > 0 THEN + DrawDigit(Tens, -1, -1) + END; + IF Ones > 0 THEN + DrawDigit(Ones, -1, 1) + END; +END DrawNumber; + +PROCEDURE Test(N: CARDINAL); +VAR + Canvas: TCanvas; +BEGIN + WriteInt(N, 1); + WriteString(':'); + WriteLn; + ClearCanvas(Canvas); + DrawNumber(Canvas, N); + ShowCanvas(Canvas); + WriteLn; +END Test; + +BEGIN + Test(0); + Test(1); + Test(20); + Test(300); + Test(4000); + Test(5555); + Test(6789); + Test(9999); +END CistercianNumerals. diff --git a/Task/Cistercian-numerals/Pascal-P/cistercian-numerals.pas b/Task/Cistercian-numerals/Pascal-P/cistercian-numerals.pas new file mode 100644 index 0000000000..9a846b5298 --- /dev/null +++ b/Task/Cistercian-numerals/Pascal-P/cistercian-numerals.pas @@ -0,0 +1,131 @@ +program cistnums; +(* Cistercian numerals *) +const + maxcoord = 14; + +type + tcanvas = array [0 .. maxcoord, 0 .. maxcoord] of char; + tsignvals = -1 .. 1; + + (* BEGIN. Operations on the tcanvas ADT. *) + procedure clearcanvas(var canvas: tcanvas); + var + i, j: integer; + begin + for i := 0 to maxcoord do + for j := 0 to maxcoord do + canvas[i, j] := ' '; + end; (* clearcanvas *) + + procedure drawline(var canvas: tcanvas; r0, c0: integer; + dist: integer; dr, dc: tsignvals); + (* Draws a straight (vertical, horizontal, or diagonal) line + from canvas[r0, c0] to canvas[r0 + dr * dist, c0 + dc * dist]. *) + var + c, r, i: integer; + begin + r := r0; + c := c0; + for i := 0 to dist do + begin + canvas[r, c] := '*'; + r := r + dr; + c := c + dc; + end; + end; (* drawline *) + + procedure showcanvas(var canvas: tcanvas); + var + i, j: integer; + begin + for i := 0 to maxcoord do + begin + for j := 0 to maxcoord do + write(canvas[i, j]); + writeln; + end; + end; (* showcanvas *) + (* END Operations on the tcanvas ADT. *) + + procedure drawnumber(var canvas: tcanvas; v: integer); + (* drawdigit is part of the algorithm, so it is nested in drawnumber. *) + type + tdigits = 0 .. 9; + var + thousands, hundreds, tens, ones: integer; + raxis, caxis: integer; + + procedure drawdigit(v: tdigits; rs, cs: tsignvals); + (* rs, cs are signs of rows and cols in in relation to the axis. + They decide in which quadrant a digit is located. *) + begin + case v of + 1: drawline(canvas, raxis + rs * 7, caxis + cs, 4, 0, cs); + 2: drawline(canvas, raxis + rs * 3, caxis + cs, 4, 0, cs); + 3: drawline(canvas, raxis + rs * 7, caxis + cs, 4, -rs, cs); + 4: drawline(canvas, raxis + rs * 3, caxis + cs, 4, rs, cs); + 5: + begin + drawdigit(1, rs, cs); + drawdigit(4, rs, cs); + end; + 6: drawline(canvas, raxis + rs * 3, caxis + cs * 5, 4, rs, 0); + 7: + begin + drawdigit(1, rs, cs); + drawdigit(6, rs, cs); + end; + 8: + begin + drawdigit(2, rs, cs); + drawdigit(6, rs, cs); + end; + 9: + begin + drawdigit(1, rs, cs); + drawdigit(8, rs, cs); + end; + end; + end; (* drawdigit *) + + begin (* drawnumber *) + raxis := maxcoord div 2; + caxis := 5; + drawline(canvas, 0, caxis, maxcoord, 1, 0); (* Draw 0 (or vertical axis) *) + thousands := v div 1000; + v := v mod 1000; + hundreds := v div 100; + v := v mod 100; + tens := v div 10; + ones := v mod 10; + if thousands > 0 then + drawdigit(thousands, 1, -1); + if hundreds > 0 then + drawdigit(hundreds, 1, 1); + if tens > 0 then + drawdigit(tens, -1, -1); + if ones > 0 then + drawdigit(ones, -1, 1); + end; (* drawnumber *) + + procedure test(n: integer); + var + canvas: tcanvas; + begin + writeln(n, ':'); + clearcanvas(canvas); + drawnumber(canvas, n); + showcanvas(canvas); + writeln; + end; + +begin + test(0); + test(1); + test(20); + test(300); + test(4000); + test(5555); + test(6789); + test(9999) +end. diff --git a/Task/Cistercian-numerals/XPL0/cistercian-numerals.xpl0 b/Task/Cistercian-numerals/XPL0/cistercian-numerals.xpl0 new file mode 100644 index 0000000000..76aebc2c36 --- /dev/null +++ b/Task/Cistercian-numerals/XPL0/cistercian-numerals.xpl0 @@ -0,0 +1,104 @@ +\ Cistercian numerals +code Rem=2, ChOut=8, CrLf=9, IntOut=11, Text=12; + +define CanvasSize = 15; + +\ BEGIN. Operations on the canvas (considered as an ADT). +procedure ClearCanvas(Canvas); +integer Canvas; +integer I, J; +begin +for I:= 0 to CanvasSize - 1 do + for J:= 0 to CanvasSize - 1 do Canvas(I, J):= ^ ; +end; \ClearCanvas + +procedure DrawLine(Canvas, R0, C0, Dist, DR, DC); +\ Draws a straight (vertical, horizontal, or diagonal) line +\ from Canvas(R0, C0) to Canvas(R0 + DR * Dist, C0 + DC * Dist) +integer Canvas, R0, C0, Dist, DR, DC; +integer C, R, I; +begin +if (DR # -1) and (DR # 0) and (DR # 1) then exit; +if (DC # -1) and (DC # 0) and (DC # 1) then exit; +R:= R0; C:= C0; +for I:= 0 to Dist do + begin + Canvas(R, C):= ^*; + R:= R + DR; C:= C + DC; + end +end; \DrawLine + +procedure ShowCanvas(Canvas); +integer Canvas; +integer I, J; +begin +for I:= 0 to CanvasSize - 1 do + begin + for J:= 0 to CanvasSize - 1 do ChOut(0, Canvas(I, J)); + CrLf(0); + end; +end; \ShowCanvas +\ END Operations on the canvas. + +procedure DrawNumber(Canvas, V); +integer Canvas, V; +integer Thousands, Hundreds, Tens, Ones, RAxis, CAxis; +\ DrawDigit is part of the algorithm, so it is nested in DrawNumber. + + procedure DrawDigit(V, RS, CS); + integer V, RS, CS; + \ RS, CS are signs of rows and cols in in relation to the axis. + \ They decide in which quadrant a digit is located. + begin + if (RS # -1) and (RS # 1) then exit; + if (CS # -1) and (CS # 1) then exit; + case V of + 1: DrawLine(Canvas, RAxis + RS * 7, CAxis + CS, 4, 0, CS); + 2: DrawLine(Canvas, RAxis + RS * 3, CAxis + CS, 4, 0, CS); + 3: DrawLine(Canvas, RAxis + RS * 7, CAxis + CS, 4, -RS, CS); + 4: DrawLine(Canvas, RAxis + RS * 3, CAxis + CS, 4, RS, CS); + 5: [DrawDigit(1, RS, CS); DrawDigit(4, RS, CS)]; + 6: DrawLine(Canvas, RAxis + RS * 3, CAxis + CS * 5, 4, RS, 0); + 7: [DrawDigit(1, RS, CS); DrawDigit(6, RS, CS)]; + 8: [DrawDigit(2, RS, CS); DrawDigit(6, RS, CS)]; + 9: [DrawDigit(1, RS, CS); DrawDigit(8, RS, CS)] + other []; + end; \DrawDigit; + +begin \DrawNumber +RAxis := (CanvasSize - 1) / 2; +CAxis := 5; +DrawLine(Canvas, 0, CAxis, CanvasSize - 1, 1, 0); \Draw 0 (or vertical axis) +Thousands:= V / 1000; +V:= Rem(V / 1000); +Hundreds:= V / 100; +V:= Rem(V / 100); +Tens:= V / 10; +Ones:= Rem(V / 10); +if Thousands > 0 then DrawDigit(Thousands, 1, -1); +if Hundreds > 0 then DrawDigit(Hundreds, 1, 1); +if Tens > 0 then DrawDigit(Tens, -1, -1); +if Ones > 0 then DrawDigit(Ones, -1, 1); +end; \DrawNumber + +procedure Test(N); +integer N; +integer Canvas(CanvasSize, CanvasSize); +begin +IntOut(0, N); ChOut(0, ^:); CrLf(0); +ClearCanvas(Canvas); +DrawNumber(Canvas, N); +ShowCanvas(Canvas); +CrLf(0); +end; + +begin +Test(0); +Test(1); +Test(20); +Test(300); +Test(4000); +Test(5555); +Test(6789); +Test(9999); +end diff --git a/Task/Classes/Elena/classes.elena b/Task/Classes/Elena/classes.elena index 4faedc117f..c55ff04498 100644 --- a/Task/Classes/Elena/classes.elena +++ b/Task/Classes/Elena/classes.elena @@ -23,5 +23,5 @@ public program() instance.someMethod(); // get the variable - console.printLine("Variable=",instance.Variable) + Console.printLine("Variable=",instance.Variable) } diff --git a/Task/Classes/Haxe/classes-1.haxe b/Task/Classes/Haxe/classes-1.haxe new file mode 100644 index 0000000000..37ec6fbcdf --- /dev/null +++ b/Task/Classes/Haxe/classes-1.haxe @@ -0,0 +1,14 @@ +class BasicClass { + public function basicMethod():Void { + return; + } + + public function new() {} +} + +class Main { + static public function main():Void { + var basic_object = new BasicClass(); + $type(basic_object); + } +} diff --git a/Task/Classes/Haskell/classes-3.hs b/Task/Classes/Haxe/classes-2.haxe similarity index 100% rename from Task/Classes/Haskell/classes-3.hs rename to Task/Classes/Haxe/classes-2.haxe diff --git a/Task/Closures-Value-capture/ArkScript/closures-value-capture.ark b/Task/Closures-Value-capture/ArkScript/closures-value-capture.ark new file mode 100644 index 0000000000..b14646e92e --- /dev/null +++ b/Task/Closures-Value-capture/ArkScript/closures-value-capture.ark @@ -0,0 +1,13 @@ +(mut funcs []) + +(mut i 0) +(while (< i 10) { + (let ii i) + (append! funcs (fun (&ii) (* ii ii))) + (set i (+ i 1)) }) + +(set i 0) +# display the result of all but the last +(while (< i 9) { + (assert (= ((@ funcs i)) (* i i)) "(@ funcs i) returns (* i i)") + (set i (+ 1 i)) }) diff --git a/Task/Closures-Value-capture/Elena/closures-value-capture.elena b/Task/Closures-Value-capture/Elena/closures-value-capture.elena index b943a12d2c..db252942a9 100644 --- a/Task/Closures-Value-capture/Elena/closures-value-capture.elena +++ b/Task/Closures-Value-capture/Elena/closures-value-capture.elena @@ -5,5 +5,5 @@ public program() { var functions := Array.allocate(10).populate::(int i => { ^ i * i} ); - functions.forEach::(func) { console.printLine(func()) } + functions.forEach::(func) { Console.printLine(func()) } } diff --git a/Task/Collections/DuckDB/collections.duckdb b/Task/Collections/DuckDB/collections.duckdb new file mode 100644 index 0000000000..edc60fa133 --- /dev/null +++ b/Task/Collections/DuckDB/collections.duckdb @@ -0,0 +1,11 @@ +create or replace function toset(l) as + array_sort(list_distinct(l)); + +create or replace function array_intersection(a,b) as + array_filter(a, x -> array_contains(b, x)); + +create or replace function set_union(a,b) as + toset(toset(a) || toset(b))); + +create or replace function set_intersection(a,b) as + array_intersection(toset(a),toset(b)); diff --git a/Task/Collections/Phix/collections-1.phix b/Task/Collections/Phix/collections-1.phix index 1211759da2..953e33257c 100644 --- a/Task/Collections/Phix/collections-1.phix +++ b/Task/Collections/Phix/collections-1.phix @@ -1,7 +1,6 @@ -(phixonline)--> +(phixonline) with javascript_semantics sequence collection = {} collection = append(collection,"one") collection = prepend(collection,2) ? collection -- {2,"one"} - +(phixonline) with javascript_semantics setd("one",0) setd(2,0) @@ -7,4 +7,3 @@ return 1 end function traverse_dict(routine_id("visitor")) -- shows 2, "one" - { Number in 0..9, Number #= Number0 - 48 }, digit(Number0). + +isbn13 --> + sequence(base10_digit, [D1, D2, D3]), "-", + sequence(base10_digit, [D4, D5, D6, D7, D8, D9, D10, D11, D12, D13]), + { ( D1 + 3 * D2 + D3 + 3 * D4 + + D5 + 3 * D6 + D7 + 3 * D8 + + D9 + 3 * D10 + D11 + 3 * D12 + D13 ) mod 10 #= 0 }. diff --git a/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro new file mode 100644 index 0000000000..7f3a3f0e20 --- /dev/null +++ b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-2.pro @@ -0,0 +1,11 @@ +?- phrase(isbn13, "978-0596528126"). +true. + +?- phrase(isbn13, "978-0596528120"). +false. + +?- phrase(isbn13, "978-1788399081"). +true. + +?- phrase(isbn13, "978-1788399083"). +false. diff --git a/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro new file mode 100644 index 0000000000..7225eeca85 --- /dev/null +++ b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-3.pro @@ -0,0 +1,12 @@ +?- ISBN = [0'9, 0'7, 0'8, 0'-, 0'0, 0'3, 0'0, 0'6, 0'4, 0'0, _, _, 0'5, 0'7], phrase(isbn13, ISBN). +ISBN = "978-0306400957" ; +ISBN = "978-0306401657" ; +ISBN = "978-0306402357" ; +ISBN = "978-0306403057" ; +ISBN = "978-0306404757" ; +ISBN = "978-0306405457" ; +ISBN = "978-0306406157" ; +ISBN = "978-0306407857" ; +ISBN = "978-0306408557" ; +ISBN = "978-0306409257" ; +false. diff --git a/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro new file mode 100644 index 0000000000..0b5d9cc7dc --- /dev/null +++ b/Task/ISBN13-check-digit/Prolog/isbn13-check-digit-4.pro @@ -0,0 +1,12 @@ +?- phrase(isbn13, ISBN). +ISBN = "000-0000000000" ; +ISBN = "000-0000000017" ; +ISBN = "000-0000000024" ; +ISBN = "000-0000000031" ; +ISBN = "000-0000000048" ; +ISBN = "000-0000000055" ; +ISBN = "000-0000000062" ; +ISBN = "000-0000000079" ; +ISBN = "000-0000000086" ; +ISBN = "000-0000000093" ; +ISBN = "000-0000000109" . % etc... diff --git a/Task/Identity-matrix/DuckDB/identity-matrix.duckdb b/Task/Identity-matrix/DuckDB/identity-matrix.duckdb new file mode 100644 index 0000000000..26cbc7a159 --- /dev/null +++ b/Task/Identity-matrix/DuckDB/identity-matrix.duckdb @@ -0,0 +1,20 @@ +# Produce an (i,j,value) table representing the matrix I(m,n) +# which is the identity matrix if m = n +create or replace function I(m,n,zero) as table ( + with recursive cte(i,j,ij,value) as ( + select 1, 1, (null,null), zero + union all + select if(j=n, i+1, i) as i, + if(j=n, 1, j+1) as j, + (i, j) as ij, + zero + if(i=j, 1, 0) as value + from cte + where i <= m + ) + select ij[1] as i, ij[2] as j, value + from cte + offset 1 +); + +# Generate a 3x3 matrix with DOUBLE(3,2) values: +from I(3, 3, 0.000); diff --git a/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb new file mode 100644 index 0000000000..44a338df57 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/DuckDB/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.duckdb @@ -0,0 +1,27 @@ +# Generate a string of all the codepoints in the range [m,n) +# corresponding to the given Unicode character class, where `class` +# could be '[a-z]' or '\p{Ll}', etc. +# +# Note: codepoints 55296 to 57343 (xD800–xDFFF) are reserved for the +# surrogates mechanism and are excluded as they are regarded as "illegal" +# as characters. +# +create or replace function generate(class, m, n) as ( + select string_agg(s, '') + from (select + case when 55296 <=i and i <= 57343 then null + else regexp_extract( chr(i::INTEGER), class) + end as s + from range(m, n) t(i)) +); + +# ident_start minus NBSP +select generate( '[A-Za-z\200-\237\241-\377_]',0, 1024); + +.mode list + +with ident_start as ( + select generate( '[A-Za-z\200-\237\241-\377_]',0,1024 ) as s + ) + select unnest(regexp_extract_all(s, '.{1,26}')) + from ident_start; diff --git a/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb new file mode 100644 index 0000000000..825cc013b9 --- /dev/null +++ b/Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/DuckDB/idiomatically-determine-all-the-lowercase-and-uppercase-letters.duckdb @@ -0,0 +1,19 @@ +# The number of Unicode codepoints +set variable maxu = 1114112; + +# Generate a string of all the codepoints in the range [m,n) +# corresponding to the given Unicode character class, where `class` +# could be '[a-z]' or '\p{Ll}', etc. +# +# Note: codepoints 55296 to 57343 (xD800–xDFFF) are reserved for the +# surrogates mechanism and are excluded as they are regarded "illegal" +# as characters. +# +create or replace function generate(class, m, n) as ( + select string_agg(s, '') + from (select + case when 55296 <=i and i <= 57343 then null + else regexp_extract( chr(i::INTEGER), class) + end as s + from range(m, n) t(i)) +); diff --git a/Task/Include-a-file/RISC-V-Assembly/include-a-file-1.asm b/Task/Include-a-file/RISC-V-Assembly/include-a-file-1.asm new file mode 100644 index 0000000000..c9c972cd28 --- /dev/null +++ b/Task/Include-a-file/RISC-V-Assembly/include-a-file-1.asm @@ -0,0 +1,8 @@ +/************************************/ +/* Constantes */ +/************************************/ +.equ TRUE, 1 +.equ FALSE, 0 + +.equ LENGTHDEC, 12 +.equ LENGTHBIN, 33 diff --git a/Task/Include-a-file/RISC-V-Assembly/include-a-file-2.asm b/Task/Include-a-file/RISC-V-Assembly/include-a-file-2.asm new file mode 100644 index 0000000000..db35e7070a --- /dev/null +++ b/Task/Include-a-file/RISC-V-Assembly/include-a-file-2.asm @@ -0,0 +1,152 @@ +# fichier include riscv assembly for rosetta code +# includeFunctions.s + +/************************************/ +/* string write on connexion usb */ +/***********************************/ +/* a0 String address */ +writeString: # INFO: writeString + addi sp, sp, -8 # save registers on stack + sw ra, 0(sp) + sw s0, 4(sp) + mv s0,a0 # move string address +1: + lbu a0,(s0) # load one character + beqz a0,100f # end if zero + call putchar # character write + add s0,s0,1 # increment address + j 1b # and loop + +100: # end function + lw ra, 0(sp) # restaur registers + lw s0, 4(sp) + addi sp, sp, 8 + ret +/************************************/ +/* binary conversion */ +/***********************************/ +/* a0 value */ +/* a1 result area address */ +/* size mini 33 character */ +conversion2: # INFO: conversion2 + addi sp, sp, -8 # save registres + sw ra, 0(sp) + li t2,0 + li t1,0 +1: + slt t3,a0,x0 # if negative bit 31 is 1 + + slli a0,a0,1 # shift left one bit + add t0,a1,t1 # compute indice to store char in area + addi t3,t3,'0' # conversion byte to ascii char + sb t3,(t0) # store char in area + addi t1,t1,1 # next position + li t0,7 # for add a space separation + beq t2,t0,4f + li t0,15 # for add a space + beq t2,t0,4f + li t0,23 # for add a space + beq t2,t0,4f + j 5f + +4: # store space + li t3,' ' + add t0,a1,t1 + sb t3,(t0) + addi t1,t1,1 +5: + addi t2,t2,1 # increment bit indice + li t0,32 # maxi ? + blt t2,t0,1b # and loop + + add t0,a1,t1 + sb x0,(t0) # final zero +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret +/**********************************************/ +/* decimal conversion */ +/**********************************************/ +/* a0 value */ +/* a1 conversion array address */ +/* a0 return result size */ +.equ LGZONECONV, 20 +conversion10: + addi sp, sp, -4 + sw ra, 0(sp) + li t1,LGZONECONV + li t2,10 # divisor +1: + rem t4,a0,t2 # division remainder by 10 + addi t4,t4,48 # convert to decimal + add t5,a1,t1 # store character position + sb t4,(t5) # store byte + div a0,a0,t2 # compute quotient + beq a0,x0,2f # compare to 0 + addi t1,t1,-1 # decrement store position + bgt t1,x0,1b # and loop if position is ok +2: + li t2,0 # raz indice + li t3,LGZONECONV +3: # loop to transfer result at begining conversion area + add t5,a1,t1 # compute start position + lb t4,(t5) # load byte + add t5,a1,t2 # compute new position + sb t4,(t5) # and store byte + addi t2,t2,1 # increment indice + addi t1,t1,1 + ble t1,t3,3b # and loop if indice <= area size + add t5,a1,t2 # increment final position + sb x0,(t5) # and store byte final zero + mv a0,t2 # return size conversion + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/***************************************************/ +/* register conversion in décimal signed */ +/***************************************************/ +/* a0 value */ +/* a1 result area address size mini 12c */ +/* a0 return result size */ +conversion10S: # INFO: conversion10S + addi sp, sp, -8 # save registers + sw ra, 0(sp) + li t6,'+' + bge a0,x0,1f # positive number ? + li t6,'-' # negative + sub a0,x0,a0 # inversion +1: + li t4,LENGTHDEC # area size + li t1,10 # divisor +2: + remu t3,a0,t1 # remainder division by 10 + addi t3,t3,48 # conversion ascii + add t2,t4,a1 # compute store indice + sb t3,(t2) + addi t4,t4,-1 # previous position + divu a0,a0,t1 # division by 10 + bne a0,x0,2b + # store signe in current position + add t2,t4,a1 + sb t6,(t2) + li t2,0 + li t3,LENGTHDEC +3: # loop copy result to area start + add t5,a1,t4 # compute start position + lb t6,(t5) # load byte + add t5,a1,t2 # compute new position + sb t6,(t5) # and store byte + addi t2,t2,1 # increment indice + addi t4,t4,1 + ble t4,t3,3b # and loop if indice <= area size + add t5,a1,t2 # increment final position + sb x0,(t5) # and store byte final zero + mv a0,t2 # return size conversion + +100: + lw ra, 0(sp) # restaur registers + addi sp, sp, 8 + ret diff --git a/Task/Include-a-file/RISC-V-Assembly/include-a-file-3.asm b/Task/Include-a-file/RISC-V-Assembly/include-a-file-3.asm new file mode 100644 index 0000000000..30025f2974 --- /dev/null +++ b/Task/Include-a-file/RISC-V-Assembly/include-a-file-3.asm @@ -0,0 +1,44 @@ +# riscv assembly raspberry pico2 rp2350 +# program include.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessHello: .asciz "Hello world.\r\n" +szMessStart: .asciz "Program riscv start.\r\n" + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected + beqz a0,1b # retuen code = zero ? + + la a0,szMessStart # message address + call writeString # display message + la a0,szMessHello # message address + call writeString # display message + +100: # final loop + j 100b +/************************************/ +/* file include Fonctions */ +/***********************************/ +.include "../../includeFunctions.s" diff --git a/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-1.duckdb b/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-1.duckdb new file mode 100644 index 0000000000..357617d7fc --- /dev/null +++ b/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-1.duckdb @@ -0,0 +1 @@ +select '1'::INT + 1; diff --git a/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-2.duckdb b/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-2.duckdb new file mode 100644 index 0000000000..f2698e8828 --- /dev/null +++ b/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-2.duckdb @@ -0,0 +1 @@ +select '1.2'::FLOAT + 1; diff --git a/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-3.duckdb b/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-3.duckdb new file mode 100644 index 0000000000..48d38fb4da --- /dev/null +++ b/Task/Increment-a-numerical-string/DuckDB/increment-a-numerical-string-3.duckdb @@ -0,0 +1 @@ +select (' 1.2' || chr(9))::FLOAT + 1; diff --git a/Task/Increment-a-numerical-string/Pluto/increment-a-numerical-string.pluto b/Task/Increment-a-numerical-string/Pluto/increment-a-numerical-string.pluto new file mode 100644 index 0000000000..bfbe214393 --- /dev/null +++ b/Task/Increment-a-numerical-string/Pluto/increment-a-numerical-string.pluto @@ -0,0 +1,4 @@ +local s = "1000" +++s -- implicit conversion to number before incrementing +print(s) +print(type(s)) diff --git a/Task/Infinity/ArkScript/infinity.ark b/Task/Infinity/ArkScript/infinity.ark new file mode 100644 index 0000000000..2fd9f611e3 --- /dev/null +++ b/Task/Infinity/ArkScript/infinity.ark @@ -0,0 +1,3 @@ +(assert (= false (math:Inf? 0)) "0 is not infinite") +(assert (math:Inf? math:Inf) "math:Inf is infinite") +(assert (not (math:Inf? math:NaN)) "math:NaN is not infinite") diff --git a/Task/Infinity/DuckDB/infinity.duckdb b/Task/Infinity/DuckDB/infinity.duckdb new file mode 100644 index 0000000000..506d3b31d0 --- /dev/null +++ b/Task/Infinity/DuckDB/infinity.duckdb @@ -0,0 +1 @@ +select 'Infinity' as s, s::DOUBLE as infinity, s::FLOAT = infinity, -infinity = '-INF'::DOUBLE; diff --git a/Task/Infinity/Pluto/infinity.pluto b/Task/Infinity/Pluto/infinity.pluto new file mode 100644 index 0000000000..e67a669ac0 --- /dev/null +++ b/Task/Infinity/Pluto/infinity.pluto @@ -0,0 +1,8 @@ +local function isinfinite(f) + return f == 1.0 / 0.0 or f == (-1.0) / 0.0 +end + +local fs = {1.5, 1.5 / 0.0, (-1.5) / 0.0} +for fs as f do + print(isinfinite(f)) +end diff --git a/Task/Inheritance-Multiple/V-(Vlang)/inheritance-multiple.v b/Task/Inheritance-Multiple/V-(Vlang)/inheritance-multiple.v new file mode 100644 index 0000000000..e656846519 --- /dev/null +++ b/Task/Inheritance-Multiple/V-(Vlang)/inheritance-multiple.v @@ -0,0 +1,38 @@ +struct Size { + mut: + width int + height int +} + +fn (s &Size) area() int { + return s.width * s.height +} + +struct Colors { + mut: + color string +} + +struct Button { + Size + Colors + title string +} + +fn main() { + mut button_1 := Button{ + title: "On" + width: 4 + height: 2 + } + button_1.color = "red" + println(button_1) + + mut button_2 := Button{ + title: "Off" + height: 4 + color: "blue" + } + button_2.width = 8 + println("The area of button 2 is ${button_2.area()}") +} diff --git a/Task/Inheritance-Single/Rhombus/inheritance-single.rhombus b/Task/Inheritance-Single/Rhombus/inheritance-single.rhombus new file mode 100644 index 0000000000..17f1674ba2 --- /dev/null +++ b/Task/Inheritance-Single/Rhombus/inheritance-single.rhombus @@ -0,0 +1,17 @@ +#lang rhombus/static + +class Animal(): + nonfinal + +class Dog(): + nonfinal + extends Animal + +class Cat(): + extends Animal + +class Lab(): + extends Dog + +class Collie(): + extends Dog diff --git a/Task/Inheritance-Single/V-(Vlang)/inheritance-single.v b/Task/Inheritance-Single/V-(Vlang)/inheritance-single.v new file mode 100644 index 0000000000..fe010e4c0c --- /dev/null +++ b/Task/Inheritance-Single/V-(Vlang)/inheritance-single.v @@ -0,0 +1,36 @@ +struct Animal { + mut: + alive bool +} + +struct Dog { + Animal + mut: + obediant bool +} + +struct Cat { + Animal + mut: + trained bool +} + +struct Lab { + Dog + mut: + color string +} + +struct Collie { + Dog + mut: + catches bool +} + +fn main() { + mut pet := Lab{} + pet.alive = true + pet.obediant = false + pet.color = "black" + println(pet) +} diff --git a/Task/Input-loop/Nom/input-loop.num b/Task/Input-loop/Nom/input-loop.num new file mode 100644 index 0000000000..e3adc9de66 --- /dev/null +++ b/Task/Input-loop/Nom/input-loop.num @@ -0,0 +1 @@ + read; print; clear; diff --git a/Task/Integer-comparison/DuckDB/integer-comparison.duckdb b/Task/Integer-comparison/DuckDB/integer-comparison.duckdb new file mode 100644 index 0000000000..0ea8171f76 --- /dev/null +++ b/Task/Integer-comparison/DuckDB/integer-comparison.duckdb @@ -0,0 +1,8 @@ +select a + || if ( a < b, ' is less than ', + if ( a = b, ' is equal to ', + if ( a > b, ' is greater than ', + ' is incomparable to '))) + || b as comparison +from read_csv_auto('/dev/stdin', header=false, sep=' ', + columns= {'a': 'INTEGER', 'b': 'INTEGER'}); diff --git a/Task/Integer-comparison/Prolog/integer-comparison-1.pro b/Task/Integer-comparison/Prolog/integer-comparison-1.pro new file mode 100644 index 0000000000..7d190e158f --- /dev/null +++ b/Task/Integer-comparison/Prolog/integer-comparison-1.pro @@ -0,0 +1,14 @@ +:- set_prolog_flag(double_quotes, chars). + +println([]) :- write('\n'). +println([Char | Chars]) :- write(Char), println(Chars). + +my_compare(A, B) :- + ( A < B + -> println("A is less than B") + ; A > B + -> println("A is greater than B") + ; % double equals is necessary if we want the predicate to fail if A or B is unbound + A == B + -> println("A is equal to B") + ). diff --git a/Task/Integer-comparison/Prolog/integer-comparison-2.pro b/Task/Integer-comparison/Prolog/integer-comparison-2.pro new file mode 100644 index 0000000000..6f156c08ac --- /dev/null +++ b/Task/Integer-comparison/Prolog/integer-comparison-2.pro @@ -0,0 +1,7 @@ +my_compare2(A, B) :- + compare(Order, A, B), + my_compare2_(Order). + +my_compare2_(<) :- println("A is less than B."). +my_compare2_(=) :- println("A is equal to B."). +my_compare2_(>) :- println("A is greater than B."). diff --git a/Task/Integer-comparison/YAMLScript/integer-comparison.ys b/Task/Integer-comparison/YAMLScript/integer-comparison.ys new file mode 100644 index 0000000000..59b265bd8e --- /dev/null +++ b/Task/Integer-comparison/YAMLScript/integer-comparison.ys @@ -0,0 +1,8 @@ +!YS-v0 + +defn main(x y): + say: + cond: + x < y: "$x is less than $y" + x > y: "$x is greater than $y" + else : "$x is equal to $y" diff --git a/Task/Integer-sequence/ArkScript/integer-sequence-1.ark b/Task/Integer-sequence/ArkScript/integer-sequence-1.ark new file mode 100644 index 0000000000..3292a2f31d --- /dev/null +++ b/Task/Integer-sequence/ArkScript/integer-sequence-1.ark @@ -0,0 +1,4 @@ +(mut i 0) +(while true { + (print i) + (set i (+ 1 i)) }) diff --git a/Task/Integer-sequence/ArkScript/integer-sequence-2.ark b/Task/Integer-sequence/ArkScript/integer-sequence-2.ark new file mode 100644 index 0000000000..99a3156c43 --- /dev/null +++ b/Task/Integer-sequence/ArkScript/integer-sequence-2.ark @@ -0,0 +1,5 @@ +(let loop (fun (i) { + (print i) + (loop (+ i 1)) })) + +(loop 0) diff --git a/Task/Introspection/DuckDB/introspection.duckdb b/Task/Introspection/DuckDB/introspection.duckdb new file mode 100644 index 0000000000..ec3b3e7b2f --- /dev/null +++ b/Task/Introspection/DuckDB/introspection.duckdb @@ -0,0 +1,10 @@ +# Return version() as a list of integers [major, minor, patch] +create or replace function semver() as + version().regexp_extract('v[0-9.]*')[2:].split('.') + .list_transform(x->cast(x as INTEGER)); + +# semversion should be a list of integers [major, minor, patch] +create or replace function errorIfBefore(semversion) as + if (semver() <= semversion, error( version() || ' is too old'), null); + +select errorIfBefore([1,1,5]); diff --git a/Task/Inverted-index/DuckDB/inverted-index.duckdb b/Task/Inverted-index/DuckDB/inverted-index.duckdb new file mode 100644 index 0000000000..07b4e48579 --- /dev/null +++ b/Task/Inverted-index/DuckDB/inverted-index.duckdb @@ -0,0 +1,25 @@ +install fts; -- once should be enough + +load fts; +create or replace table texts as (from read_text('inv*.txt')); + +pragma create_fts_index( + 'texts', -- table name + 'filename', -- column name + 'content', -- column name of text + stemmer = 'english', + stopwords = 'none', + strip_accents = 1, + lower = 1, -- ignore case + overwrite = 1); + +# Simple interface to match_bm25 for conjunctive queries: +create or replace function s(queryString) as table ( + select filename, + content, + fts_main_texts.match_bm25( filename, + queryString, + conjunctive := 1) as score + from texts + where score IS NOT NULL +); diff --git a/Task/Inverted-syntax/DuckDB/inverted-syntax-1.duckdb b/Task/Inverted-syntax/DuckDB/inverted-syntax-1.duckdb new file mode 100644 index 0000000000..49ff2b9ade --- /dev/null +++ b/Task/Inverted-syntax/DuckDB/inverted-syntax-1.duckdb @@ -0,0 +1 @@ +SELECT 1 as x; diff --git a/Task/Inverted-syntax/DuckDB/inverted-syntax-2.duckdb b/Task/Inverted-syntax/DuckDB/inverted-syntax-2.duckdb new file mode 100644 index 0000000000..293c959dec --- /dev/null +++ b/Task/Inverted-syntax/DuckDB/inverted-syntax-2.duckdb @@ -0,0 +1 @@ +CREATE TABLE foo AS ... diff --git a/Task/Inverted-syntax/DuckDB/inverted-syntax-3.duckdb b/Task/Inverted-syntax/DuckDB/inverted-syntax-3.duckdb new file mode 100644 index 0000000000..12c6d444ac --- /dev/null +++ b/Task/Inverted-syntax/DuckDB/inverted-syntax-3.duckdb @@ -0,0 +1 @@ +SET VARIABLE x = 1; diff --git a/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx b/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx index 29fcc4a72c..1754501f09 100644 --- a/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx +++ b/Task/Isqrt-integer-square-root-of-X/REXX/isqrt-integer-square-root-of-x.rexx @@ -1,5 +1,4 @@ --- 8 May 2025 -Main: +-- 28 Jul 2025 include Settings say 'ISQRT (INTEGER SQUARE ROOT)' @@ -31,7 +30,7 @@ call Timer return Task2: -procedure +procedure expose Memo. arg xx,yy,zz,mm call Time('r') select @@ -120,6 +119,4 @@ do while z < zz end return zz -include Functions -include Helper -include Abend +include Math diff --git a/Task/Iterated-digits-squaring/Prolog/iterated-digits-squaring.pro b/Task/Iterated-digits-squaring/Prolog/iterated-digits-squaring.pro new file mode 100644 index 0000000000..b9925b14ab --- /dev/null +++ b/Task/Iterated-digits-squaring/Prolog/iterated-digits-squaring.pro @@ -0,0 +1,36 @@ +:- initialization(main, main). + +%! next_number_in_chain(+Number0, -Number) is det. +next_number_in_chain(Number0, Number) :- next_number_in_chain_(Number0, 0, Number). + +next_number_in_chain_(Number0, Number1, Number) :- + divmod(Number0, 10, Div, Mod), + Number2 is Number1 + Mod ^ 2, + ( Div = 0 + -> Number2 = Number + ; next_number_in_chain_(Div, Number2, Number) + ). + +%! number_chain(+Number, -End) is det. +number_chain(Number0, End) :- + ( Number0 =< 81 * 9 + -> number_chain_(Number0, End) + ; next_number_in_chain(Number0, Number), + number_chain(Number, End) + ). + +:- table number_chain_/2. +number_chain_(89, 89). +number_chain_( 1, 1). +number_chain_(Number0, End) :- + next_number_in_chain(Number0, Number), + number_chain_(Number, End). + +%! task(+Max, -Result) is det. +task(Max, Result) :- + aggregate_all(count, ( between(1, Max, N), number_chain(N, 89) ), Result). + +main([Input]) :- + atom_number(Input, Number), + time(task(Number, Result)), + writeln(Result). diff --git a/Task/JSON/Agena/json.agena b/Task/JSON/Agena/json.agena new file mode 100644 index 0000000000..a943498cc5 --- /dev/null +++ b/Task/JSON/Agena/json.agena @@ -0,0 +1,28 @@ +scope # JSON encode/decode - translation of the Phix sample, using Agena's standard json module + + import json; + + print( "roundtrip (10 examples):" ); + + local constant json_strings := [ '{"this":"that","age":{"this":"that","age":29}}' + , '1' + , '"hello"' + , 'null' + , '[12]' + , '[null,12]' + , '[]' + , '{"this":"that","age":29}' + , '{}' + , '[null,[null,12]]' + ]; + + for i to size json_strings do + local constant s := json_strings[ i ]; + local constant j := json.decode( s ); + local constant r := json.encode( j ); + local constant pad := if size s < 29 then 30 else size s + 1 fi; + print( " " & strings.ljustify( s, pad ) & " -> " + , j, "\n" & if s = r then "-> " else "** " fi & r & "\n" + ) + od +end diff --git a/Task/JSON/DuckDB/json-1.duckdb b/Task/JSON/DuckDB/json-1.duckdb new file mode 100644 index 0000000000..8c3a095cf1 --- /dev/null +++ b/Task/JSON/DuckDB/json-1.duckdb @@ -0,0 +1 @@ +from 'colors.json'; diff --git a/Task/JSON/DuckDB/json-2.duckdb b/Task/JSON/DuckDB/json-2.duckdb new file mode 100644 index 0000000000..202d376c1a --- /dev/null +++ b/Task/JSON/DuckDB/json-2.duckdb @@ -0,0 +1 @@ +select json::JSON from read_csv('colors.json', header=false, sep='\t') t(json); diff --git a/Task/JSON/DuckDB/json-3.duckdb b/Task/JSON/DuckDB/json-3.duckdb new file mode 100644 index 0000000000..ad119d13e6 --- /dev/null +++ b/Task/JSON/DuckDB/json-3.duckdb @@ -0,0 +1 @@ +COPY t to 'output.json'; diff --git a/Task/JSON/Pluto/json.pluto b/Task/JSON/Pluto/json.pluto new file mode 100644 index 0000000000..a91a76cdf1 --- /dev/null +++ b/Task/JSON/Pluto/json.pluto @@ -0,0 +1,30 @@ +do -- JSON encode/decode - translation of the Phix sample, using Pluto's standard json module + + local json = require( "json" ) + + print( "roundtrip (10 examples):" ) + + local json_strings = { '{"this":"that","age":{"this":"that","age":29}}' + , '1' + , '"hello"' + , 'null' + , '[12]' + , '[null,12]' + , '[]' + , '{"this":"that","age":29}' + , '{}' + , '[null,[null,12]]' + } + + for i = 1, #json_strings do + local s = json_strings[ i ] + local j = json.decode( s, json.withnull | json.withorder ) -- parse the string into a table + -- preserving nulls and element order + local r = json.encode( j ) -- turn j back into a JSON string + local v = dumpvar( j ):gsub( "\n", "" ):gsub( "\t", "" ) -- the table as a readable string + local sp = " " + io.write( " ", s, if #s >= #sp then "\n "..sp else sp:sub( 1, #sp - #s ) end ) + io.write( "-> ", if #v > 50 then v:sub( 1, 47 ).."..." else v end, "\n" ) + io.write( if s == r then "-> " else "** " end, r, "\n\n" ) + end +end diff --git a/Task/JSON/REBOL/json.rebol b/Task/JSON/REBOL/json-1.rebol similarity index 81% rename from Task/JSON/REBOL/json.rebol rename to Task/JSON/REBOL/json-1.rebol index 98c9a6e014..6249929d1d 100644 --- a/Task/JSON/REBOL/json.rebol +++ b/Task/JSON/REBOL/json-1.rebol @@ -10,5 +10,5 @@ json-str: {{"menu": { } }} -res: json-to-rebol json-str -js: rebol-to-json res +reb: json-to-rebol json-str +str: rebol-to-json reb diff --git a/Task/JSON/REBOL/json-2.rebol b/Task/JSON/REBOL/json-2.rebol new file mode 100644 index 0000000000..1137570a61 --- /dev/null +++ b/Task/JSON/REBOL/json-2.rebol @@ -0,0 +1,16 @@ +json-str: {{"menu": { + "id": "file", + "string": "File:", + "number": -3, + "boolean": true, + "boolean2": false, + "null": null, + "array": [1, 0.13, null, true, false, "\t\r\n"], + "empty-string": "" + } +}} +import json ;; just in case it's not yet imported +probe reb: decode 'json json-str +probe str: encode 'json reb ;; outputs without any indentation +;; Validate that re-encoded JSON is same +probe equal? reb decode 'json str diff --git a/Task/Jacobi-symbol/Excel/jacobi-symbol.excel b/Task/Jacobi-symbol/Excel/jacobi-symbol.excel new file mode 100644 index 0000000000..7923afe75c --- /dev/null +++ b/Task/Jacobi-symbol/Excel/jacobi-symbol.excel @@ -0,0 +1,34 @@ +To CopyPaste : =LAMBDA(a,n,[result],LET(s,IF(ISOMITTED(result),MOD(a,n),a),R,IF(ISOMITTED(result),EXPAND(1,COUNT(s),1,1),result),B,IF(s=0,HSTACK(s,n,R),IF(BITAND(s,1)=0,HSTACK(BITRSHIFT(s,1),n,IF(ABS(BITAND(n,7)-4)=1,-R,R)),HSTACK(MOD(n,s),s,IF(BITAND(s,3)+BITAND(n,3)-6=0,-R,R)))),new_a,INDEX(B,,1),new_n,INDEX(B,,2),new_result,INDEX(B,,3),IF(OR(new_a),Jacobi(new_a,new_n,new_result),IF(new_n=1,new_result,0)))) + +Easy-to-read display : +=LAMBDA(a,n,[result], + LET( + s, IF(ISOMITTED(result), MOD(a,n), a), + R, IF(ISOMITTED(result), EXPAND(1, COUNT(s), 1, 1), result), + B, IF( + s=0, + HSTACK(s,n,R), + IF( + BITAND(s,1)=0, + HSTACK( + BITRSHIFT(s,1), + n, + IF(ABS(BITAND(n,7)-4)=1,-R,R) + ), + HSTACK( + MOD(n,s), + s, + IF(BITAND(s,3)+BITAND(n,3)-6=0,-R,R) + ) + ) + ), + new_a, INDEX(B,,1), + new_n, INDEX(B,,2), + new_result, INDEX(B,,3), + IF( + OR(new_a), + Jacobi(new_a,new_n,new_result), + IF(new_n=1,new_result,0) + ) + ) +) diff --git a/Task/Jacobsthal-numbers/ALGOL-68/jacobsthal-numbers.alg b/Task/Jacobsthal-numbers/ALGOL-68/jacobsthal-numbers.alg index ffe68ab564..221694abb5 100644 --- a/Task/Jacobsthal-numbers/ALGOL-68/jacobsthal-numbers.alg +++ b/Task/Jacobsthal-numbers/ALGOL-68/jacobsthal-numbers.alg @@ -2,7 +2,7 @@ BEGIN # find some Jacobsthal and related Numbers # INT max jacobsthal = 29; # highest Jacobsthal number we will find # INT max oblong = 20; # highest Jacobsthal oblong number we will find # INT max j prime = 20; # number of Jacobsthal prinmes we will find # - PR precision 200 PR # set the precision of LONG LONG INT # + PR precision 250 PR # set the precision of LONG LONG INT # PR read "primes.incl.a68" PR # include prime utilities # [ 0 : max jacobsthal ]LONG INT j; # will hold Jacobsthal numbers # [ 0 : max jacobsthal ]LONG INT jl; # will hold Jacobsthal-Lucas numbers # diff --git a/Task/Jacobsthal-numbers/Agena/jacobsthal-numbers.agena b/Task/Jacobsthal-numbers/Agena/jacobsthal-numbers.agena new file mode 100644 index 0000000000..35d51d5a8b --- /dev/null +++ b/Task/Jacobsthal-numbers/Agena/jacobsthal-numbers.agena @@ -0,0 +1,50 @@ +scope # find some Jacobsthal and related Numbers + local constant maxJacobsthal # highest Jacobsthal number we will find + , constant maxOblong # highest Jacobsthal oblong number we will find + , constant maxJPrime # number of Jacobsthal primes we will find + := 29, 20, 10; + local constant j # will hold Jacobsthal numbers + , constant jl # will hold Jacobsthal-Lucas numbers + , constant jo # will hold Jacobsthal oblong numbers + := seq(), seq(), seq(); + # calculate the Jacobsthal Numbers and related numbers + # Jacobsthal : J0 = 0, J1 = 1, Jn = Jn-1 + 2 × Jn-2 + # Jacobsthal-Lucas: JL0 = 2, JL1 = 1, JLn = JLn-1 + 2 × JLn-2 + # Jacobsthal oblong: JOn = Jn x Jn-1 + # but Agena sequences are indexed from 1, so J0 is in j[ 1 ], JL0 is in jl[ 1 ], etc. + # but JO1 is in jo[ 1 ], however - also the sequence elements must be added in order + j[ 1 ] := 0; j[ 2 ] := 1; jl[ 1 ] := 2; jl[ 2 ] := 1; jo[ 1 ] := 0; + for n from 2 to maxJacobsthal do + j[ n + 1 ] := j[ n ] + ( 2 * j[ n - 1 ] ); + jl[ n + 1 ] := jl[ n ] + ( 2 * jl[ n - 1 ] ) + od; + for n to maxOblong do + jo[ n ] := j[ n + 1 ] * j[ n ] + od; + + local procedure showNumbers( legend :: string, numbers :: sequence ) + local nCount := 0; + printf( "First %d %s\n", size numbers, legend ); + for n to size numbers do + printf( " %11.0f", numbers[ n ] ); # using %11.0f and not %11d as some values will... + nCount +:= 1; # ...be larger than 2^32 + if nCount mod 5 = 0 then print() fi + od + end; + + # show the various numbers numbers + showNumbers( "Jacobsthal Numbers:", j ); + showNumbers( "Jacobsthal-Lucas Numbers:", jl ); + showNumbers( "Jacobsthal oblong Numbers:", jo ); + # find some prime Jacobsthal numbers + local jn1, jn2, pCount := j[ 2 ], j[ 1 ], 0; + printf( "First %d Jacobstal primes:\n n Jn\n", maxJPrime ); + for n from 2 while pCount < maxJPrime do + local constant jn := jn1 + ( 2 * jn2 ); + jn2, jn1 := jn1, jn; + if numtheory.isprime( jn ) then + pCount +:= 1; + printf( "%4d: %d\n", n, jn ) + fi + od +end diff --git a/Task/Jacobsthal-numbers/EasyLang/jacobsthal-numbers.easy b/Task/Jacobsthal-numbers/EasyLang/jacobsthal-numbers.easy new file mode 100644 index 0000000000..3229a8d841 --- /dev/null +++ b/Task/Jacobsthal-numbers/EasyLang/jacobsthal-numbers.easy @@ -0,0 +1,50 @@ +fastfunc isprim n . + if n < 2 : return 0 + i = 2 + while i <= sqrt n + if n mod i = 0 : return 0 + i += 1 + . + return 1 +. +subr jtinit + jtcurr = 0 + jtnext = 1 +. +proc jtstep . + swap jtnext jtcurr + jtnext += jtnext + jtcurr +. +print "First 30 Jacobsthal numbers:" +jtinit +for i to 30 + write jtcurr & " " + jtstep +. +print "" +print "\nFirst 30 Jacobsthal-Lucas numbers:" +jtinit +jtcurr = 2 +for i to 30 + write jtcurr & " " + jtstep +. +print "" +print "\nFirst 20 Jacobsthal oblong numbers:" +jtinit +for i to 20 + write jtcurr * jtnext & " " + jtstep +. +print "" +print "\nFirst 10 Jacobsthal prime numbers:" +jtinit +while cnt < 10 + jtstep + if isprim jtnext = 1 + write jtnext & " " + cnt += 1 + . + i += 1 +. +print "" diff --git a/Task/Jacobsthal-numbers/Fennel/jacobsthal-numbers.fennel b/Task/Jacobsthal-numbers/Fennel/jacobsthal-numbers.fennel new file mode 100644 index 0000000000..d9d8894e9c --- /dev/null +++ b/Task/Jacobsthal-numbers/Fennel/jacobsthal-numbers.fennel @@ -0,0 +1,64 @@ +(do ;;; find some Jacobsthal and related Numbers + (local (max-jacobsthal ; highest Jacobsthal number we will find + max-oblong ; highest Jacobsthal oblong number we will find + max-j-prime ; number of Jacobsthal primes we will find + ) (values 29 20 10)) + (local (j ; will hold Jacobsthal numbers + jl ; will hold Jacobsthal-Lucas numbers + jo ; will hold Jacobsthal oblong numbers + ) (values [] [] [])) + ; calculate the Jacobsthal Numbers and related numbers + ; Jacobsthal : J0 = 0, J1 = 1, Jn = Jn-1 + 2 × Jn-2 + ; Jacobsthal-Lucas: JL0 = 2, JL1 = 1, JLn = JLn-1 + 2 × JLn-2 + ; Jacobsthal oblong: JOn = Jn x Jn-1 + ; Lua arrays (and hence Fennel arrays) can be indexed from 0 but this uses indexing from 1, + ; to follow the Agena and Pluto samples, so J0 is in j[ 1 ], JL0 is in jl[ 1 ], etc. + ; but JO1 is in jo[ 1 ], however + (tset j 1 0) (tset j 2 1) (tset jl 1 2) (tset jl 2 1) (tset jo 1 0) + (for [n 2 max-jacobsthal] + (local (n+1 n-1) (values (+ n 1) (- n 1))) + (tset j n+1 (+ (. j n) (* 2 (. j n-1)))) + (tset jl n+1 (+ (. jl n) (* 2 (. jl n-1)))) + ) + (for [n 1 max-oblong] + (tset jo n (* (. j (+ n 1)) (. j n))) + ) + + (fn is-prime [n] + (var result (or (= n 2) (and (> n 1) (= 1 (band n 1))))) + (when result + (var k 3) + (local max-k (math.floor (math.sqrt n))) + (while (and result (<= k max-k)) + (set (result k) (values (not= 0 (% n k)) (+ k 2))) + ) + ) + result + ) + (fn show-numbers [legend numbers] + (var nCount 0) + (io.write (string.format "First %d %s\n" (length numbers) legend)) + (for [n 1 (length numbers)] + (io.write (string.format " %11d" (. numbers n))) + (set nCount (+ nCount 1)) + (when (= 0 (% nCount 5)) (print)) + ) + ) + + ; show the various numbers numbers + (show-numbers "Jacobsthal Numbers:" j ) + (show-numbers "Jacobsthal-Lucas Numbers:" jl ) + (show-numbers "Jacobsthal oblong Numbers:" jo ) + ; find some prime Jacobsthal numbers + (io.write (string.format "First %d Jacobstal primes:\n n Jn\n" max-j-prime)) + (var (jn1 jn2 pCount n) (values (. j 2) (. j 1) 0 2)) + (while (< pCount max-j-prime) + (local jn (+ jn1 (* 2 jn2))) + (set (jn2 jn1) (values jn1 jn)) + (when (is-prime jn) + (set pCount (+ pCount 1)) + (io.write (string.format "%4d: %d\n" n jn)) + ) + (set n (+ n 1)) + ) +) diff --git a/Task/Jacobsthal-numbers/Lua/jacobsthal-numbers.lua b/Task/Jacobsthal-numbers/Lua/jacobsthal-numbers.lua new file mode 100644 index 0000000000..7cb259f4bf --- /dev/null +++ b/Task/Jacobsthal-numbers/Lua/jacobsthal-numbers.lua @@ -0,0 +1,65 @@ +do -- find some Jacobsthal and related Numbers + + local maxJacobsthal -- highest Jacobsthal number we will find + , maxOblong -- highest Jacobsthal oblong number we will find + , maxJPrime -- number of Jacobsthal primes we will find + = 29, 20, 10 + local j -- will hold Jacobsthal numbers + , jl -- will hold Jacobsthal-Lucas numbers + , jo -- will hold Jacobsthal oblong numbers + = {}, {}, {} + -- calculate the Jacobsthal Numbers and related numbers + -- Jacobsthal : J0 == 0, J1 == 1, Jn == Jn-1 + 2 × Jn-2 + -- Jacobsthal-Lucas: JL0 == 2, JL1 == 1, JLn == JLn-1 + 2 × JLn-2 + -- Jacobsthal oblong: JOn == Jn x Jn-1 + -- Lua arrays can be indexed from 0 but as jo is indexed from 1, we index j, jl and jo + -- from 1 to simplify printing them + j[ 1 ], j[ 2 ], jl[ 1 ], jl[ 2 ], jo[ 1 ] = 0, 1, 2, 1, 0 + for n = 2, maxJacobsthal do + j[ n + 1 ] = j[ n ] + ( 2 * j[ n - 1 ] ) + jl[ n + 1 ] = jl[ n ] + ( 2 * jl[ n - 1 ] ) + end + for n = 1, maxOblong do + jo[ n ] = j[ n + 1 ] * j[ n ] + end + + 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 function showNumbers( legend, numbers ) + io.write( string.format( "First %d %s\n", # numbers, legend ) ) + for n = 1, # numbers do + io.write( string.format( " %11d", numbers[ n ] ) ) + if n % 5 == 0 then io.write( "\n" ) end + end + end + + -- show the various numbers numbers + showNumbers( "Jacobsthal Numbers:", j ) + showNumbers( "Jacobsthal-Lucas Numbers:", jl ) + showNumbers( "Jacobsthal oblong Numbers:", jo ) + -- find some prime Jacobsthal numbers + io.write( string.format( "First %d Jacobstal primes:\n n Jn\n", maxJPrime ) ) + local jn1, jn2, pCount, n = j[ 2 ], j[ 1 ], 0, 2 + while pCount < maxJPrime do + local jn = jn1 + ( 2 * jn2 ) + jn2, jn1 = jn1, jn + if isPrime( jn ) then + pCount = pCount + 1 + io.write( string.format( "%4d: %d\n", n, jn ) ) + end + n = n + 1 + end +end diff --git a/Task/Jacobsthal-numbers/Pluto/jacobsthal-numbers.pluto b/Task/Jacobsthal-numbers/Pluto/jacobsthal-numbers.pluto new file mode 100644 index 0000000000..17c53e05bd --- /dev/null +++ b/Task/Jacobsthal-numbers/Pluto/jacobsthal-numbers.pluto @@ -0,0 +1,50 @@ +do -- find some Jacobsthal and related Numbers + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library - inc. some prime utilities + + local maxJacobsthal -- highest Jacobsthal number we will find + , maxOblong -- highest Jacobsthal oblong number we will find + , maxJPrime -- number of Jacobsthal primes we will find + = 29, 20, 10 + local j -- will hold Jacobsthal numbers + , jl -- will hold Jacobsthal-Lucas numbers + , jo -- will hold Jacobsthal oblong numbers + = {}, {}, {} + -- calculate the Jacobsthal Numbers and related numbers + -- Jacobsthal : J0 == 0, J1 == 1, Jn == Jn-1 + 2 × Jn-2 + -- Jacobsthal-Lucas: JL0 == 2, JL1 == 1, JLn == JLn-1 + 2 × JLn-2 + -- Jacobsthal oblong: JOn == Jn x Jn-1 + -- Pluto arrays can be indexed from 0 but as jo is indexed from 1, we index j, jl and jo + -- from 1 to simplify printing them + j[ 1 ], j[ 2 ], jl[ 1 ], jl[ 2 ], jo[ 1 ] = 0, 1, 2, 1, 0 + for n = 2, maxJacobsthal do + j[ n + 1 ] = j[ n ] + ( 2 * j[ n - 1 ] ) + jl[ n + 1 ] = jl[ n ] + ( 2 * jl[ n - 1 ] ) + end + for n = 1, maxOblong do + jo[ n ] = j[ n + 1 ] * j[ n ] + end + + local function showNumbers( legend : string, numbers : table ) + fmt.write( "First %d %s\n", # numbers, legend ) + fmt.tprint( " %11d", numbers, 5, "", "" ) + end + + -- show the various numbers numbers + showNumbers( "Jacobsthal Numbers:", j ) + showNumbers( "Jacobsthal-Lucas Numbers:", jl ) + showNumbers( "Jacobsthal oblong Numbers:", jo ) + -- find some prime Jacobsthal numbers + fmt.write( "First %d Jacobstal primes:\n n Jn\n", maxJPrime ) + local jn1, jn2, pCount, n = j[ 2 ], j[ 1 ], 0, 2 + while pCount < maxJPrime do + local jn = jn1 + ( 2 * jn2 ) + jn2, jn1 = jn1, jn + if int.isprime( jn ) then + ++ pCount + fmt.write( "%4d: %d\n", n, jn ) + end + ++ n + end +end diff --git a/Task/Jaro-similarity/DuckDB/jaro-similarity.duckdb b/Task/Jaro-similarity/DuckDB/jaro-similarity.duckdb new file mode 100644 index 0000000000..c7811f002e --- /dev/null +++ b/Task/Jaro-similarity/DuckDB/jaro-similarity.duckdb @@ -0,0 +1,6 @@ +select s1, s2, jaro_similarity(s1, s2) as jaro, jaro_winkler_similarity(s1, s2) as jw +from values + ('MARTHA', 'MARHTA'), + ('DIXON', 'DICKSONX'), + ('JELLYFISH', 'SMELLYFISH') + _(s1,s2); diff --git a/Task/Jewels-and-stones/Agena/jewels-and-stones.agena b/Task/Jewels-and-stones/Agena/jewels-and-stones.agena new file mode 100644 index 0000000000..10f80d7fa3 --- /dev/null +++ b/Task/Jewels-and-stones/Agena/jewels-and-stones.agena @@ -0,0 +1,10 @@ +scope # Jewels and Stones - based on the Lua sample + local count_jewels := proc( stones :: string, jewels :: string ) :: number is + local count := 0; + for i to size stones do + count +:= size jewels @@ mfind( stones[ i ] ) # @@ is like : in Lua/Pluto + od; + return count + end; + io.write( count_jewels( "aAAbbbb", "aA" ), " ", count_jewels( "ZZ", "z" ), "\n" ) +end diff --git a/Task/Jewels-and-stones/Fortran/jewels-and-stones.f b/Task/Jewels-and-stones/Fortran/jewels-and-stones.f new file mode 100644 index 0000000000..e710eb2920 --- /dev/null +++ b/Task/Jewels-and-stones/Fortran/jewels-and-stones.f @@ -0,0 +1,90 @@ +! Jewels and Stones +! tested with Intel ifx (IFX) 2025.2.0 20250605 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! July 2025 +! +! THis solution contains 2 functions: JewelCount and fastJewelCount. +! The first function tries to find each letter of Jewels in Stones +! The second uses a character map built from the letters of Jewels, then +! iterates through letters of Stones, looking up these in the map and +! +!---------------------------------------------------------------------------- +! +! Return the number of Jewels that can be found in Stones. +! +function JewelCount (stones, jewels) result (NumberOfJewels) + +implicit none + +character(len=*), intent(in) :: stones, jewels ! Function arguments +integer :: NumberOfJewels ! Return value +integer :: ii, jj ! Loop indices +NumberOfJewels = 0 + +! We go through both input strings using a nested loop +! so it runs in O(len(jewels) * len(stones)) +! Is certainly good enough for short input strings. +! See below for faster version. +! +do jj=1, len (stones) + do ii=1, len (jewels) + if (stones(jj:jj) .eq. jewels(ii:ii)) then + NumberOfJewels = NumberOfJewels + 1 + EXIT ! letters in "jewels" are unique. Dont proceed. + end if + end do +end do + +end function JewelCount ! ====================================== + +! +! This function does the same as above function JewelCount. +! It might be faster for very long input "stones". +! It First creates a map of all letters in "jewels", then +! it adds one for each letter of "stones" found therein. +! works in O(len(jewels) + len(stones)) +! +function fasterJewelCount (stones, jewels) result (NumberOfJewels) +implicit none +integer, parameter :: maxChar=128 ! sufficient for A-Z,a-z +character(len=*), intent(in) :: stones, jewels ! Function arguments +integer :: NumberOfJewels ! Return value +integer :: ii ! Loop index +integer :: ic +integer :: jMap(maxChar) = 0 + +NumberOfJewels = 0 + +! Insert letter of "jewels" into the map +do ii=1, len (jewels) + ic = ichar (jewels(ii:ii)) + if (ic >=1 .and. ic <= maxChar) then ! never trust correctness of input + jMap(ic) = 1 ! Assuming all letters of "jewels" appear only once + end if +end do + +! add one for each letter of "jewels" that can be found in the map +do ii=1, len (stones) + ic = ichar (stones(ii:ii)) + if (ic >=1 .and. ic <= maxChar) then ! better safe than sorry + NumberOfJewels = NumberOfJewels + jMap(ic) + end if +end do + +end function fasterJewelCount + +! +! A little main program demonstrates usage of functions JewelCount and fastJewelCOunt +! +program progCountJewels + +implicit none +integer, external :: JewelCount, fasterJewelCount + +print *, JewelCount ('aAAbbbb', 'aA') ! expect 3 +print *, JewelCount ('ZZ', 'az') ! expect 0 +print *, fasterJewelCount ('aAAbbbb', 'aA') ! expect 3 +print *, fasterJewelCount ('ZZ', 'az') ! expect 0 + +end program progCountJewels diff --git a/Task/Jewels-and-stones/Icon/jewels-and-stones.icon b/Task/Jewels-and-stones/Icon/jewels-and-stones.icon new file mode 100644 index 0000000000..c02a2d3929 --- /dev/null +++ b/Task/Jewels-and-stones/Icon/jewels-and-stones.icon @@ -0,0 +1,10 @@ +procedure main() + write(countjewels("aAAbbbb", "aA")) + write(countjewels("ZZ", "z")) +end + +procedure countjewels(s,j) + n := 0 + s ? every upto(cset(j)) do n +:= 1 + return n +end diff --git a/Task/Jewels-and-stones/Lua/jewels-and-stones.lua b/Task/Jewels-and-stones/Lua/jewels-and-stones.lua index 2a9919d828..8ed82da928 100644 --- a/Task/Jewels-and-stones/Lua/jewels-and-stones.lua +++ b/Task/Jewels-and-stones/Lua/jewels-and-stones.lua @@ -1,8 +1,7 @@ function count_jewels(s, j) local count = 0 for i=1,#s do - local c = s:sub(i,i) - if string.match(j, c) then + if j:match(s:sub(i,i)) then count = count + 1 end end diff --git a/Task/Jewels-and-stones/Pluto/jewels-and-stones.pluto b/Task/Jewels-and-stones/Pluto/jewels-and-stones.pluto new file mode 100644 index 0000000000..f8b9b96fc4 --- /dev/null +++ b/Task/Jewels-and-stones/Pluto/jewels-and-stones.pluto @@ -0,0 +1,12 @@ +do -- Jewels and Stones - translated from the Lua sample, using a few of Pluto's new features + local function count_jewels(s, j) + local count = 0 + for i=1,#s do + if j:match(s[i]) then + ++ count + end + end + return count + end + io.write( $"{count_jewels('aAAbbbb', 'aA')} {count_jewels('ZZ', 'z')}\n" ) +end diff --git a/Task/JortSort/YAMLScript/jortsort.ys b/Task/JortSort/YAMLScript/jortsort.ys new file mode 100644 index 0000000000..4e99508d1d --- /dev/null +++ b/Task/JortSort/YAMLScript/jortsort.ys @@ -0,0 +1,8 @@ +!YS-v0 + +defn main(*array): + array =: array:V + say: + if array == array:sort: + + "$array is sorted" + "$array is not sorted" diff --git a/Task/Josephus-problem/OxygenBasic/josephus-problem.basic b/Task/Josephus-problem/OxygenBasic/josephus-problem.basic new file mode 100644 index 0000000000..748b7954e0 --- /dev/null +++ b/Task/Josephus-problem/OxygenBasic/josephus-problem.basic @@ -0,0 +1,20 @@ +uses console + +int n, k +n = 41 'prisoners +k = 3 'order of execution + +function Josephus(n as int, k as int, m as int) as int + int lm, i + + lm = m + for i = m + 1 to n + lm = (lm + k) mod i + next + return lm +end function + +printl "n = " n chr(9) "k = " k chr(9) "final survivor = " Josephus(n, k, 0) + +printl cr "Enter ..." +waitkey diff --git a/Task/Josephus-problem/Pluto/josephus-problem.pluto b/Task/Josephus-problem/Pluto/josephus-problem.pluto new file mode 100644 index 0000000000..c6e845904a --- /dev/null +++ b/Task/Josephus-problem/Pluto/josephus-problem.pluto @@ -0,0 +1,34 @@ +local fmt = require "fmt" + +local function josephus(n, k, m) + if k <= 0 or m <= 0 or n <= k or n <= m then + error("one or more parameters are invalid") + end + local killed = {} + local survived = {} + for i = 1, n do survived[i] = i - 1 end + local start = k + while true do + local finish = #survived + local i = start + local deleted = 0 + while i <= finish do + killed:insert(survived:remove(i - deleted)) + if #survived == m then return {survived, killed} end + ++deleted + i += k + end + start = i - finish + end + return {survived, killed} +end + +local triples = { {5, 2, 1}, {41, 3, 1}, {41, 3, 3} } +for triples as triple do + local [n, k, m] = triple + print($"Prisoners = {n}, Step = {k}, Survivors = {m}") + local sk = josephus(n, k, m) + print($"Survived : {fmt.swrite(sk[1])}") + print($"Kill order : {fmt.swrite(sk[2])}") + print() +end diff --git a/Task/Josephus-problem/Prolog/josephus-problem-1.pro b/Task/Josephus-problem/Prolog/josephus-problem-1.pro new file mode 100644 index 0000000000..5a4a0ece7d --- /dev/null +++ b/Task/Josephus-problem/Prolog/josephus-problem-1.pro @@ -0,0 +1,15 @@ +josephus(N, K, Survivors) :- josephus(N, K, 1, Survivors). + +:- table josephus/4. +josephus(N, K, M, Survivors) :- + K > 0, + N > 0, + N0 is N - 1, + ( M = N + -> numlist(0, N0, Survivors) + ; josephus(N0, K, M, Survivors0), + findall(Survivor, ( + member(Survivor0, Survivors0), + Survivor is (Survivor0 + K) mod N + ), Survivors) + ). diff --git a/Task/Josephus-problem/Prolog/josephus-problem-2.pro b/Task/Josephus-problem/Prolog/josephus-problem-2.pro new file mode 100644 index 0000000000..1229e75fd9 --- /dev/null +++ b/Task/Josephus-problem/Prolog/josephus-problem-2.pro @@ -0,0 +1,5 @@ +?- josephus(41, 3, Survivors). +Survivors = [30]. + +?- josephus(41, 3, 5, Survivors). +Survivors = [3, 15, 21, 30, 34]. diff --git a/Task/Josephus-problem/QBasic/josephus-problem.basic b/Task/Josephus-problem/QBasic/josephus-problem.basic index a67a59158c..693968f883 100644 --- a/Task/Josephus-problem/QBasic/josephus-problem.basic +++ b/Task/Josephus-problem/QBasic/josephus-problem.basic @@ -1,12 +1,14 @@ -FUNCTION josephus (n, k, m) -lm = m -FOR i = m + 1 TO n - lm = (lm + k) MOD i -NEXT i -josephus = lm -END FUNCTION +DECLARE FUNCTION josephus! (n!, k!, m!) n = 41 k = 3 PRINT "n = "; n, "k = "; k, "final survivor = "; josephus(n, k, 0) END + +FUNCTION josephus (n, k, m) + lm = m + FOR i = m + 1 TO n + lm = (lm + k) MOD i + NEXT i + josephus = lm +END FUNCTION diff --git a/Task/Josephus-problem/Quite-BASIC/josephus-problem-1.basic b/Task/Josephus-problem/Quite-BASIC/josephus-problem.basic similarity index 100% rename from Task/Josephus-problem/Quite-BASIC/josephus-problem-1.basic rename to Task/Josephus-problem/Quite-BASIC/josephus-problem.basic diff --git a/Task/Josephus-problem/Run-BASIC/josephus-problem-1.basic b/Task/Josephus-problem/Run-BASIC/josephus-problem-1.basic new file mode 100644 index 0000000000..8963242dc5 --- /dev/null +++ b/Task/Josephus-problem/Run-BASIC/josephus-problem-1.basic @@ -0,0 +1,16 @@ +n = 41 +k = 3 +print "n = "; n; " k = "; k; " final survivor = "; josephus(n, k, 0) +end + +function josephus(n, k, m) + lm = m + for i = m + 1 to n + ' In Run BASIC there is no MOD operator + lm = lm + k + lm = lm - int(lm / i) * i + ' In Just Basic / Liberty BASIC it could be used + 'lm = (lm + k) mod i + next i + josephus = lm +end function diff --git a/Task/Josephus-problem/Quite-BASIC/josephus-problem-2.basic b/Task/Josephus-problem/Run-BASIC/josephus-problem-2.basic similarity index 100% rename from Task/Josephus-problem/Quite-BASIC/josephus-problem-2.basic rename to Task/Josephus-problem/Run-BASIC/josephus-problem-2.basic diff --git a/Task/Josephus-problem/Wren/josephus-problem.wren b/Task/Josephus-problem/Wren/josephus-problem.wren index e6d1c6effb..44f218cfd4 100644 --- a/Task/Josephus-problem/Wren/josephus-problem.wren +++ b/Task/Josephus-problem/Wren/josephus-problem.wren @@ -24,7 +24,7 @@ for (triple in triples) { var n = triple[0] var k = triple[1] var m = triple[2] - System.print("Prisoners = %(n), Step = %(m), Survivors = %(m)") + System.print("Prisoners = %(n), Step = %(k), Survivors = %(m)") var sk = josephus.call(n, k, m) System.print("Survived : %(sk[0])") System.print("Kill order : %(sk[1])") diff --git a/Task/Josephus-problem/XBasic/josephus-problem.basic b/Task/Josephus-problem/XBasic/josephus-problem.basic new file mode 100644 index 0000000000..5cff018dee --- /dev/null +++ b/Task/Josephus-problem/XBasic/josephus-problem.basic @@ -0,0 +1,21 @@ +PROGRAM "Josephus problem" +VERSION "0.0000" + +DECLARE FUNCTION Entry () +DECLARE FUNCTION Josephus (n, k, m) + +FUNCTION Entry () + n = 41 'prisoners + k = 3 'order of execution + + PRINT "n = "; n, "k = "; k, "final survivor = "; Josephus(n, k, 0) +END FUNCTION + +FUNCTION Josephus (n, k, m) + lm = m + FOR i = m + 1 TO n + lm = (lm + k) MOD i + NEXT + RETURN lm +END FUNCTION +END PROGRAM diff --git a/Task/Julia-set/EasyLang/julia-set.easy b/Task/Julia-set/EasyLang/julia-set.easy index 44a8af429b..45f74fce52 100644 --- a/Task/Julia-set/EasyLang/julia-set.easy +++ b/Task/Julia-set/EasyLang/julia-set.easy @@ -6,7 +6,7 @@ for y = 0 to 299 : for x = 0 to 299 gcolor3 0 0 0 for iter = 0 to 127 if zx * zx + zy * zy > 4 - gcolor3 iter / 16 0 0 + gcolor3 iter * 5 0 0 break 1 . h = zx * zx - zy * zy + cx diff --git a/Task/Jump-anywhere/Koka/jump-anywhere.koka b/Task/Jump-anywhere/Koka/jump-anywhere.koka new file mode 100644 index 0000000000..ec7e33dcfc --- /dev/null +++ b/Task/Jump-anywhere/Koka/jump-anywhere.koka @@ -0,0 +1,40 @@ +effect exit
    + final ctl exit(a: a): b + +fun find-first(): string + with handler + final ctl exit(a: string) a + return(x) "not found" + for(0, 10) fn(i) + if i == 9 then exit("Found 9") + +effect loop + final ctl lbreak(): () + final ctl lcontinue(): () + +fun loop(check: () -> bool, body: () -> ()): () + if check() then + val next = handle(body) + final ctl lbreak() (fn() ()) + final ctl lcontinue() (fn() loop(check, body)) // Continue the loop + return(x) (fn() loop(check, body)) + next() + else + () + +fun main() + find-first().println + var i := 0 + loop { i < 10 } { + i := i + 1 + // We can early return from the inner lambda (continue) + if i == 4 then return () + // Adding local breaks could be done by returning `True` / `False`: + // This would require us to always return `True` if we want to continue + // The following are non-local: + // They can be used in nested calls to exit from the innermost loop on the stack. + if i == 5 then lcontinue() + if i == 8 then lbreak() + println(i) + } + println(i) diff --git a/Task/K-d-tree/Elixir/k-d-tree.ex b/Task/K-d-tree/Elixir/k-d-tree.ex new file mode 100644 index 0000000000..2f6496a7a5 --- /dev/null +++ b/Task/K-d-tree/Elixir/k-d-tree.ex @@ -0,0 +1,262 @@ +defmodule KDTree do + @moduledoc """ + K-D Tree implementation for nearest neighbor search in k-dimensional space. + """ + + # Tree data structure + # {:node, value, left, right} | :empty + # KDTree: %{dims: [function], tree: tree} + + defstruct dims: [], tree: :empty + + @doc """ + Create an empty k-d tree with the given dimensional accessors. + """ + def empty(dims) do + %KDTree{dims: dims, tree: :empty} + end + + @doc """ + Create a k-d tree with a single value. + """ + def singleton(dims, value) do + empty(dims) |> insert(value) + end + + @doc """ + Insert a value into a k-d tree. + """ + def insert(%KDTree{dims: dims, tree: tree} = kdtree, value) do + cyclic_dims = Stream.cycle(dims) + new_tree = ins(cyclic_dims, tree, value) + %{kdtree | tree: new_tree} + end + + defp ins(_dims, :empty, value) do + {:node, value, :empty, :empty} + end + + defp ins(dims, {:node, split, left, right}, value) do + [d] = Enum.take(dims, 1) + remaining_dims = Stream.drop(dims, 1) + + if d.(value) < d.(split) do + {:node, split, ins(remaining_dims, left, value), right} + else + {:node, split, left, ins(remaining_dims, right, value)} + end + end + + @doc """ + Create a k-d tree from a list using the median-finding algorithm. + """ + def from_list(dims, values) do + cyclic_dims = Stream.cycle(dims) + tree = f_list(cyclic_dims, values) + %KDTree{dims: dims, tree: tree} + end + + defp f_list(_dims, []) do + :empty + end + + defp f_list(dims, values) do + [d] = Enum.take(dims, 1) + remaining_dims = Stream.drop(dims, 1) + + sorted = Enum.sort_by(values, d) + length = length(sorted) + mid_index = div(length, 2) + + {lower, higher} = Enum.split(sorted, mid_index) + + case higher do + [] -> + :empty + [median | rest] -> + {:node, median, f_list(remaining_dims, lower), f_list(remaining_dims, rest)} + end + end + + @doc """ + Create a k-d tree from a list by repeatedly inserting values. + Faster than median-finding but can create unbalanced trees. + """ + def from_list_linear(dims, values) do + Enum.reduce(values, empty(dims), &insert(&2, &1)) + end + + @doc """ + Find the nearest value to a given value. + Returns {nearest_value_or_nil, nodes_visited}. + """ + def nearest(%KDTree{dims: dims, tree: tree}, value) do + cyclic_dims = Stream.cycle(dims) + near(cyclic_dims, tree, value, dims) + end + + defp near(_dims, :empty, _value, _all_dims) do + {nil, 1} + end + + defp near(_dims, {:node, split, :empty, :empty}, _value, _all_dims) do + {split, 1} + end + + defp near(dims, {:node, split, left, right}, value, all_dims) do + [d] = Enum.take(dims, 1) + remaining_dims = Stream.drop(dims, 1) + + split_dist = sqr_dist(all_dims, value, split) + hyperplane_dist = square(d.(value) - d.(split)) + + {best_left, left_count} = near(remaining_dims, left, value, all_dims) + {best_right, right_count} = near(remaining_dims, right, value, all_dims) + + {{maybe_this_best, this_count}, {maybe_other_best, other_count}} = + if d.(value) < d.(split) do + {{best_left, left_count}, {best_right, right_count}} + else + {{best_right, right_count}, {best_left, left_count}} + end + + case maybe_this_best do + nil -> + count = 1 + this_count + other_count + case maybe_other_best do + nil -> + {split, count} + other_best -> + if sqr_dist(all_dims, value, other_best) < split_dist do + {other_best, count} + else + {split, count} + end + end + + this_best -> + this_best_dist = sqr_dist(all_dims, value, this_best) + {best, best_dist} = + if split_dist < this_best_dist do + {split, split_dist} + else + {this_best, this_best_dist} + end + + if best_dist < hyperplane_dist do + {best, 1 + this_count} + else + count = 1 + this_count + other_count + case maybe_other_best do + nil -> + {best, count} + other_best -> + if best_dist < sqr_dist(all_dims, value, other_best) do + {best, count} + else + {other_best, count} + end + end + end + end + end + + @doc """ + Calculate squared Euclidean distance between two points. + """ + def sqr_dist(dims, a, b) do + a_values = Enum.map(dims, & &1.(a)) + b_values = Enum.map(dims, & &1.(b)) + + Enum.zip(a_values, b_values) + |> Enum.map(fn {x, y} -> square(x - y) end) + |> Enum.sum() + end + + defp square(x), do: x * x + + @doc """ + Dimensional accessors for 2-tuple. + """ + def tuple_2d do + [&elem(&1, 0), &elem(&1, 1)] + end + + @doc """ + Dimensional accessors for 3-tuple. + """ + def tuple_3d do + [&elem(&1, 0), &elem(&1, 1), &elem(&1, 2)] + end + + @doc """ + Naive nearest search for verification. + """ + def linear_nearest(_dims, _value, []) do + nil + end + + def linear_nearest(dims, value, [head | tail]) do + Enum.min_by([head | tail], &sqr_dist(dims, value, &1)) + end + + @doc """ + Print search results. + """ + def print_results(point, {nearest, visited}, dims) do + case nearest do + nil -> + IO.puts("Could not find nearest.") + value -> + dist = :math.sqrt(sqr_dist(dims, point, value)) + IO.puts("Point: #{inspect(point)}") + IO.puts("Nearest: #{inspect(value)}") + IO.puts("Distance: #{dist}") + IO.puts("Visited: #{visited}") + IO.puts("") + end + end + + @doc """ + Generate random 3D points. + """ + def random_3d_points(n, {min_x, min_y, min_z}, {max_x, max_y, max_z}) do + for _ <- 1..n do + { + min_x + :rand.uniform() * (max_x - min_x), + min_y + :rand.uniform() * (max_y - min_y), + min_z + :rand.uniform() * (max_z - min_z) + } + end + end + + @doc """ + Main demonstration function. + """ + def main do + # Wikipedia example + wiki_values = [{2, 3}, {5, 4}, {9, 6}, {4, 7}, {8, 1}, {7, 2}] + wiki_tree = from_list(tuple_2d(), wiki_values) + wiki_search = {9, 2} + wiki_nearest = nearest(wiki_tree, wiki_search) + + IO.puts("Wikipedia example:") + print_results(wiki_search, wiki_nearest, tuple_2d()) + + # Random 3D example + :rand.seed(:exsplus, {1, 2, 3}) # Seed for reproducible results + rand_range = {{0, 0, 0}, {1000, 1000, 1000}} + rand_values = random_3d_points(1000, elem(rand_range, 0), elem(rand_range, 1)) + rand_search = hd(random_3d_points(1, elem(rand_range, 0), elem(rand_range, 1))) + rand_tree = from_list(tuple_3d(), rand_values) + rand_nearest = nearest(rand_tree, rand_search) + rand_nearest_linear = linear_nearest(tuple_3d(), rand_search, rand_values) + + IO.puts("1000 random 3D points on the range of [0, 1000):") + print_results(rand_search, rand_nearest, tuple_3d()) + IO.puts("Confirm naive nearest:") + IO.puts("#{inspect(rand_nearest_linear)}") + end +end + +KDTree.main() diff --git a/Task/K-d-tree/Swift/k-d-tree.swift b/Task/K-d-tree/Swift/k-d-tree.swift new file mode 100644 index 0000000000..b7aa48ec28 --- /dev/null +++ b/Task/K-d-tree/Swift/k-d-tree.swift @@ -0,0 +1,203 @@ +import Foundation + +// point is a k-dimensional point. +typealias Point = [Double] + +extension Point { + // sqd returns the square of the euclidean distance. + func sqd(to q: Point) -> Double { + var sum: Double = 0 + for dim in 0.. HyperRect { + return HyperRect(min: Array(self.min), max: Array(self.max)) + } +} + +class KDTree { + let root: KDNode? + let bounds: HyperRect + + init(root: KDNode?, bounds: HyperRect) { + self.root = root + self.bounds = bounds + } + + // nearest. find nearest neighbor. return values are: + // nearest neighbor - the point within the tree that is nearest p. + // square of the distance to that point. + // a count of the nodes visited in the search. + func nearest(to target: Point) -> (nearest: Point?, distSqd: Double, nodesVisited: Int) { + return nn(kd: root, target: target, hr: bounds, maxDistSqd: .infinity) + } + + // algorithm is table 6.4 from the paper + private func nn(kd: KDNode?, target: Point, hr: HyperRect, + maxDistSqd: Double) -> (nearest: Point?, distSqd: Double, nodesVisited: Int) { + if kd == nil { + return (nil, .infinity, 0) + } + + var nodesVisited = 1 + let s = kd!.split + let pivot = kd!.domElt + var leftHr = hr.copy() + var rightHr = hr.copy() + leftHr.max[s] = pivot[s] + rightHr.min[s] = pivot[s] + let targetInLeft = target[s] <= pivot[s] + + let (nearerKd, nearerHr, furtherKd, furtherHr): (KDNode?, HyperRect, KDNode?, HyperRect) + if targetInLeft { + nearerKd = kd!.left + nearerHr = leftHr + furtherKd = kd!.right + furtherHr = rightHr + } else { + nearerKd = kd!.right + nearerHr = rightHr + furtherKd = kd!.left + furtherHr = leftHr + } + + var (nearest, distSqd, nv) = nn(kd: nearerKd, target: target, hr: nearerHr, maxDistSqd: maxDistSqd) + nodesVisited += nv + + var maxDist = maxDistSqd + if distSqd < maxDist { + maxDist = distSqd + } + + var d = pivot[s] - target[s] + d *= d + if d > maxDist { + return (nearest, distSqd, nodesVisited) + } + + d = pivot.sqd(to: target) + if d < distSqd { + nearest = pivot + distSqd = d + maxDist = distSqd + } + + let (tempNearest, tempSqd, nv2) = nn(kd: furtherKd, target: target, hr: furtherHr, maxDistSqd: maxDist) + nodesVisited += nv2 + + if tempSqd < distSqd { + nearest = tempNearest + distSqd = tempSqd + } + + return (nearest, distSqd, nodesVisited) + } +} + +// Helper function to create a new KD tree +func newKd(pts: [Point], bounds: HyperRect) -> KDTree { + func nk2(exset: [Point], split: Int) -> KDNode? { + if exset.isEmpty { + return nil + } + + // Sort points by the split dimension + let sortedPoints = exset.sorted { $0[split] < $1[split] } + var m = sortedPoints.count / 2 + let d = sortedPoints[m] + + // Find largest index of points with median value + while m+1 < sortedPoints.count && sortedPoints[m+1][split] == d[split] { + m += 1 + } + + // Next split + var s2 = split + 1 + if s2 == d.count { + s2 = 0 + } + + return KDNode( + domElt: d, + split: split, + left: nk2(exset: Array(sortedPoints[0.. Point { + var p = Point(repeating: 0, count: dim) + for d in 0.. [Point] { + var p = [Point](repeating: [], count: n) + for i in 0.. 0) try writer.writeAll(", "); + try writer.print("{d:.1}", .{coord}); + } + try writer.writeAll("]"); + } +}; + +const KDTreeNode = struct { + point: Point, + dim: usize, + left: ?*KDTreeNode, + right: ?*KDTreeNode, + allocator: Allocator, + + const Self = @This(); + + pub fn init(allocator: Allocator, points: []Point, dim: usize) !*Self { + const points_len = points.len; + + if (points_len == 1) { + const node = try allocator.create(Self); + node.* = Self{ + .point = try points[0].clone(), + .dim = dim, + .left = null, + .right = null, + .allocator = allocator, + }; + return node; + } + + // Split around the median + const pivot = try quickselectBy(points, points_len / 2, dim, allocator); + + const left = if (points_len >= 2) + try Self.init(allocator, points[0..points_len / 2], (dim + 1) % pivot.coords.len) + else + null; + + const right = if (points_len >= 3) + try Self.init(allocator, points[points_len / 2 + 1..points_len], (dim + 1) % pivot.coords.len) + else + null; + + const node = try allocator.create(Self); + node.* = Self{ + .point = pivot, + .dim = dim, + .left = left, + .right = right, + .allocator = allocator, + }; + return node; + } + + pub fn deinit(self: *Self) void { + self.point.deinit(); + if (self.left) |left| { + left.deinit(); + self.allocator.destroy(left); + } + if (self.right) |right| { + right.deinit(); + self.allocator.destroy(right); + } + } + + pub fn findNearestNeighbor(self: *const Self, point: Point, allocator: Allocator) !struct { point: Point, n_visited: usize } { + const diff = try point.sub(self.point, allocator); + defer diff.deinit(); + const initial_dist_sq = diff.normSq(); + + const result = try self.findNearestNeighborHelper(point, self.point, initial_dist_sq, 1, allocator); + return .{ .point = try result.point.clone(), .n_visited = result.n_visited }; + } + + fn findNearestNeighborHelper( + self: *const Self, + point: Point, + best: Point, + best_dist_sq: f32, + n_visited: usize, + allocator: Allocator, + ) !struct { point: Point, n_visited: usize } { + var my_best = best; + var my_best_dist_sq = best_dist_sq; + var my_n_visited = n_visited; + + // Examine the near side first + if (self.point.coords[self.dim] < point.coords[self.dim] and self.right != null) { + const result = try self.right.?.findNearestNeighborHelper( + point, my_best, my_best_dist_sq, my_n_visited, allocator + ); + my_best = result.point; + my_n_visited = result.n_visited; + } else if (self.left != null) { + const result = try self.left.?.findNearestNeighborHelper( + point, my_best, my_best_dist_sq, my_n_visited, allocator + ); + my_best = result.point; + my_n_visited = result.n_visited; + } + + // Distance along this node's axis + const axis_dist_sq = std.math.pow(f32, self.point.coords[self.dim] - point.coords[self.dim], 2); + if (axis_dist_sq <= my_best_dist_sq) { + // Check if this node is closer than current best + const self_diff = try point.sub(self.point, allocator); + defer self_diff.deinit(); + const self_dist_sq = self_diff.normSq(); + + if (self_dist_sq < my_best_dist_sq) { + my_best = self.point; + my_best_dist_sq = self_dist_sq; + } + + my_n_visited += 1; + + // Check the far side of the split + if (self.point.coords[self.dim] < point.coords[self.dim] and self.left != null) { + const result = try self.left.?.findNearestNeighborHelper( + point, my_best, my_best_dist_sq, my_n_visited, allocator + ); + my_best = result.point; + my_n_visited = result.n_visited; + } else if (self.right != null) { + const result = try self.right.?.findNearestNeighborHelper( + point, my_best, my_best_dist_sq, my_n_visited, allocator + ); + my_best = result.point; + my_n_visited = result.n_visited; + } + } + + return .{ .point = my_best, .n_visited = my_n_visited }; + } +}; + +fn quickselectBy(arr: []Point, position: usize, dim: usize, allocator: Allocator) !Point { + if (arr.len == 1) return try arr[0].clone(); + + var rng = std.Random.DefaultPrng.init(@intCast(std.time.timestamp())); + const random = rng.random(); + + var pivot_index = random.uintLessThan(usize, arr.len); + pivot_index = partitionBy(arr, pivot_index, dim); + + const array_len = arr.len; + if (position == pivot_index) { + return try arr[position].clone(); + } else if (position < pivot_index) { + return quickselectBy(arr[0..pivot_index], position, dim, allocator); + } else { + return quickselectBy(arr[pivot_index + 1..array_len], position - pivot_index - 1, dim, allocator); + } +} + +fn partitionBy(arr: []Point, pivot_index: usize, dim: usize) usize { + const array_len = arr.len; + std.mem.swap(Point, &arr[pivot_index], &arr[array_len - 1]); + var store_index: usize = 0; + + for (0..array_len - 1) |i| { + if (arr[i].coords[dim] < arr[array_len - 1].coords[dim]) { + std.mem.swap(Point, &arr[i], &arr[store_index]); + store_index += 1; + } + } + std.mem.swap(Point, &arr[array_len - 1], &arr[store_index]); + return store_index; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var rng = std.Random.DefaultPrng.init(@intCast(std.time.timestamp())); + const random = rng.random(); + + // Wikipedia example + const wp_coords = [_][]const f32{ + &[_]f32{ 2.0, 3.0 }, + &[_]f32{ 5.0, 4.0 }, + &[_]f32{ 9.0, 6.0 }, + &[_]f32{ 4.0, 7.0 }, + &[_]f32{ 8.0, 1.0 }, + &[_]f32{ 7.0, 2.0 }, + }; + + var wp_points = ArrayList(Point).init(allocator); + defer { + for (wp_points.items) |point| { + point.deinit(); + } + wp_points.deinit(); + } + + for (wp_coords) |coords| { + try wp_points.append(try Point.init(allocator, coords)); + } + + const wp_tree = try KDTreeNode.init(allocator, wp_points.items, 0); + defer { + wp_tree.deinit(); + allocator.destroy(wp_tree); + } + + const wp_target = try Point.init(allocator, &[_]f32{ 9.0, 2.0 }); + defer wp_target.deinit(); + + const wp_result = try wp_tree.findNearestNeighbor(wp_target, allocator); + defer wp_result.point.deinit(); + + const wp_diff = try wp_result.point.sub(wp_target, allocator); + defer wp_diff.deinit(); + + print("Wikipedia example data:\n", .{}); + print("Point: {}\n", .{wp_target}); + print("Nearest neighbor: {}\n", .{wp_result.point}); + print("Distance: {d:.6}\n", .{@sqrt(wp_diff.normSq())}); + print("Nodes visited: {}\n", .{wp_result.n_visited}); + + // Randomly generated 3D points + const n_random = 1000; + var random_points = ArrayList(Point).init(allocator); + defer { + for (random_points.items) |point| { + point.deinit(); + } + random_points.deinit(); + } + + for (0..n_random) |_| { + const coords = [_]f32{ + (random.float(f32) - 0.5) * 1000.0, + (random.float(f32) - 0.5) * 1000.0, + (random.float(f32) - 0.5) * 1000.0, + }; + try random_points.append(try Point.init(allocator, &coords)); + } + + const start_cons_time = std.time.nanoTimestamp(); + const random_tree = try KDTreeNode.init(allocator, random_points.items, 0); + const cons_time = std.time.nanoTimestamp() - start_cons_time; + defer { + random_tree.deinit(); + allocator.destroy(random_tree); + } + + print("1,000 3d points (Construction time: {}ms)\n", .{@divTrunc(cons_time, 1_000_000)}); + + const random_target_coords = [_]f32{ + (random.float(f32) - 0.5) * 1000.0, + (random.float(f32) - 0.5) * 1000.0, + (random.float(f32) - 0.5) * 1000.0, + }; + const random_target = try Point.init(allocator, &random_target_coords); + defer random_target.deinit(); + + const random_result = try random_tree.findNearestNeighbor(random_target, allocator); + defer random_result.point.deinit(); + + const random_diff = try random_result.point.sub(random_target, allocator); + defer random_diff.deinit(); + + print("Point: {}\n", .{random_target}); + print("Nearest neighbor: {}\n", .{random_result.point}); + print("Distance: {d:.6}\n", .{@sqrt(random_diff.normSq())}); + print("Nodes visited: {}\n", .{random_result.n_visited}); + + // Benchmark search time + const n_searches = 1000; + var random_targets = ArrayList(Point).init(allocator); + defer { + for (random_targets.items) |point| { + point.deinit(); + } + random_targets.deinit(); + } + + for (0..n_searches) |_| { + const coords = [_]f32{ + (random.float(f32) - 0.5) * 1000.0, + (random.float(f32) - 0.5) * 1000.0, + (random.float(f32) - 0.5) * 1000.0, + }; + try random_targets.append(try Point.init(allocator, &coords)); + } + + const start_search_time = std.time.nanoTimestamp(); + var total_n_visited: usize = 0; + for (random_targets.items) |target| { + const result = try random_tree.findNearestNeighbor(target, allocator); + defer result.point.deinit(); + total_n_visited += result.n_visited; + } + const search_time = std.time.nanoTimestamp() - start_search_time; + + print("Visited an average of {d:.1} nodes on {} searches in {} ms\n", .{ + @as(f32, @floatFromInt(total_n_visited)) / @as(f32, @floatFromInt(n_searches)), + n_searches, + @divTrunc(search_time, 1_000_000), + }); +} diff --git a/Task/Kaprekar-numbers/ALGOL-68/kaprekar-numbers.alg b/Task/Kaprekar-numbers/ALGOL-68/kaprekar-numbers.alg index 935d7587ae..f8294ca17d 100644 --- a/Task/Kaprekar-numbers/ALGOL-68/kaprekar-numbers.alg +++ b/Task/Kaprekar-numbers/ALGOL-68/kaprekar-numbers.alg @@ -8,6 +8,9 @@ PROC is kaprekar = ( INT n )BOOL: ELIF n = 1 THEN # 1 is defined to be a Kaprekar number # TRUE + ELIF n MOD 9 > 1 THEN + # n can't be Kaprekar if n MOD 9 is not 0 or 1 # + FALSE ELSE # n is a Kaprekar number if the digits of its # # square can be partitioned into two numbers # diff --git a/Task/Kaprekar-numbers/Agena/kaprekar-numbers.agena b/Task/Kaprekar-numbers/Agena/kaprekar-numbers.agena new file mode 100644 index 0000000000..029d913842 --- /dev/null +++ b/Task/Kaprekar-numbers/Agena/kaprekar-numbers.agena @@ -0,0 +1,42 @@ +scope # find some Kaprekar numbers + + # returns TRUE if n is a Kaprekar number, FALSE otherwise + local constant isKaprekar := proc( n :: number ) :: boolean is + if n < 1 then # 0 and -ve numbers are not Kaprekar numbers + return false + elif n = 1 then # 1 is defined to be a Kaprekar number + return true + elif n mod 9 > 1 then # can't be Kapreker - see notes on the Maple sample + return false + else + # n is a Kaprekar number if the digits of its + # square can be partitioned into two numbers + # that sum to n + local constant nSquared := n * n; + local powerOfTen := 10; + local result := false; + while nSquared > powerOfTen and not result do + local constant leftPart := nSquared \ powerOfTen; + local constant rightPart := nSquared mod powerOfTen; + result := ( leftPart + rightPart ) = n and rightPart <> 0; + powerOfTen *:= 10 + od; + return result + fi + end + + # find the Kaprekar numbers up to 1 000 000 + # printing all those below 10 000 + scope + local constant maxNumber := 1_000_000; + local kn := seq(); + for n to maxNumber do + if isKaprekar( n ) then + kn[ size kn + 1 ] := n + fi + od; + printf( "Kaprekar numbers below 10 000:" ); + for i while kn[ i ] < 10_000 do printf( " %d", kn[ i ] ) od; + printf( "\nThere are %d Kaprekar numbers below %d\n", size kn, maxNumber ) + end +end diff --git a/Task/Kaprekar-numbers/Pluto/kaprekar-numbers.pluto b/Task/Kaprekar-numbers/Pluto/kaprekar-numbers.pluto new file mode 100644 index 0000000000..926e041de5 --- /dev/null +++ b/Task/Kaprekar-numbers/Pluto/kaprekar-numbers.pluto @@ -0,0 +1,43 @@ +do -- find some Kaprekar numbers + + local fmt = require( "fmt" ) -- RC formatting module + + -- returns true if n is a Kaprekar number, false otherwise + local function isKaprekar( n ) + if n < 1 then -- 0 and -ve numbers are not Kaprekar numbers + return false + elseif n == 1 then -- 1 is defined to be a Kaprekar number + return true + elseif n % 9 > 1 then -- cant be Kapreker - see notes on the Maple sample + return false + else + -- n is a Kaprekar number if the digits of its + -- square can be partitioned into two numbers + -- that sum to n + local nSquared = n * n + local powerOfTen = 10 + local result = false + while nSquared > powerOfTen and not result do + local leftPart = nSquared // powerOfTen + local rightPart = nSquared % powerOfTen + result = ( ( leftPart + rightPart ) == n and rightPart != 0 ) + powerOfTen *= 10 + end + return result + end + end + + -- count the Kaprekar numbers up to 1 000 000 printing all those below 10 000 + do + local maxNumber = 1_000_000 + local kn = {} + for n = 1, maxNumber do + if isKaprekar( n ) then + kn:insert( n ) + end + end + fmt.write( "Kaprekar numbers below 10 000: " ) + fmt.lwrite( kn:filtered( |v| -> v < 10_000 ), " ", "" ) + fmt.write( "\nThere are %d Kaprekar numbers below %d\n", #kn, maxNumber ) + end +end diff --git a/Task/Knapsack-problem-0-1/Zig/knapsack-problem-0-1.zig b/Task/Knapsack-problem-0-1/Zig/knapsack-problem-0-1.zig new file mode 100644 index 0000000000..90f0b6cb9e --- /dev/null +++ b/Task/Knapsack-problem-0-1/Zig/knapsack-problem-0-1.zig @@ -0,0 +1,109 @@ +const std = @import("std"); + +const Item = struct { + name: []const u8, + weight: usize, + value: usize, +}; + +fn knapsack01_dyn(allocator: std.mem.Allocator, items: []const Item, max_weight: usize) !std.ArrayList(*const Item) { + // Create 2D array for dynamic programming + var best_value = try allocator.alloc([]usize, items.len + 1); + defer allocator.free(best_value); + + for (best_value) |*row| { + row.* = try allocator.alloc(usize, max_weight + 1); + } + defer { + for (best_value) |row| { + allocator.free(row); + } + } + + // Initialize with zeros + for (best_value) |row| { + @memset(row, 0); + } + + // Fill the table + for (items, 0..) |it, i| { + for (1..max_weight + 1) |w| { + if (it.weight > w) { + best_value[i + 1][w] = best_value[i][w]; + } else { + best_value[i + 1][w] = @max( + best_value[i][w], + best_value[i][w - it.weight] + it.value + ); + } + } + } + + // Backtrack to find selected items + var result = std.ArrayList(*const Item).init(allocator); + var left_weight = max_weight; + + var i: usize = items.len; + while (i > 0) : (i -= 1) { + if (best_value[i][left_weight] != best_value[i - 1][left_weight]) { + try result.append(&items[i - 1]); + left_weight -= items[i - 1].weight; + } + } + + return result; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const MAX_WEIGHT: usize = 400; + + const ITEMS = [_]Item{ + .{ .name = "map", .weight = 9, .value = 150 }, + .{ .name = "compass", .weight = 13, .value = 35 }, + .{ .name = "water", .weight = 153, .value = 200 }, + .{ .name = "sandwich", .weight = 50, .value = 160 }, + .{ .name = "glucose", .weight = 15, .value = 60 }, + .{ .name = "tin", .weight = 68, .value = 45 }, + .{ .name = "banana", .weight = 27, .value = 60 }, + .{ .name = "apple", .weight = 39, .value = 40 }, + .{ .name = "cheese", .weight = 23, .value = 30 }, + .{ .name = "beer", .weight = 52, .value = 10 }, + .{ .name = "suntancream", .weight = 11, .value = 70 }, + .{ .name = "camera", .weight = 32, .value = 30 }, + .{ .name = "T-shirt", .weight = 24, .value = 15 }, + .{ .name = "trousers", .weight = 48, .value = 10 }, + .{ .name = "umbrella", .weight = 73, .value = 40 }, + .{ .name = "waterproof trousers", .weight = 42, .value = 70 }, + .{ .name = "waterproof overclothes", .weight = 43, .value = 75 }, + .{ .name = "note-case", .weight = 22, .value = 80 }, + .{ .name = "sunglasses", .weight = 7, .value = 20 }, + .{ .name = "towel", .weight = 18, .value = 12 }, + .{ .name = "socks", .weight = 4, .value = 50 }, + .{ .name = "book", .weight = 30, .value = 10 }, + }; + + var items = try knapsack01_dyn(allocator, &ITEMS, MAX_WEIGHT); + defer items.deinit(); + + // Print in reverse order (to match original) + const stdout = std.io.getStdOut().writer(); + var i: usize = items.items.len; + while (i > 0) : (i -= 1) { + try stdout.print("{s}\n", .{items.items[i - 1].name}); + } + + // Calculate totals + var total_weight: usize = 0; + var total_value: usize = 0; + for (items.items) |item| { + total_weight += item.weight; + total_value += item.value; + } + + try stdout.print("Total weight: {}\n", .{total_weight}); + try stdout.print("Total value: {}\n", .{total_value}); +} diff --git a/Task/Knapsack-problem-Bounded/Ada/knapsack-problem-bounded.ada b/Task/Knapsack-problem-Bounded/Ada/knapsack-problem-bounded.ada new file mode 100644 index 0000000000..6c514a48cf --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Ada/knapsack-problem-bounded.ada @@ -0,0 +1,143 @@ +with Ada.Text_IO; + +procedure Knapsack_Bounded is + subtype Item_Name is String (1 .. 22); + type Item_Weight is new Natural; + type Item_Value is new Natural; + type Item_Count is new Natural; + type Item_Pool is record + Name : Item_Name; + Weight : Item_Weight; + Value : Item_Value; + Count : Item_Count; + end record; + type Item_Bag is array (1 .. 22) of Item_Pool; + + Candidates : constant Item_Bag := + ( + ("map ", 9, 150, 1), + ("compass ", 13, 35, 1), + ("water ", 153, 200, 2), + ("sandwich ", 50, 60, 2), + ("glucose ", 15, 60, 2), + ("tin ", 68, 45, 3), + ("banana ", 27, 60, 3), + ("apple ", 39, 40, 3), + ("cheese ", 23, 30, 1), + ("beer ", 52, 10, 3), + ("suntan cream ", 11, 70, 1), + ("camera ", 32, 30, 1), + ("T-shirt ", 24, 15, 2), + ("trousers ", 48, 10, 2), + ("umbrella ", 73, 40, 1), + ("waterproof trousers ", 42, 70, 1), + ("waterproof overclothes", 43, 75, 1), + ("note-case ", 22, 80, 1), + ("sunglasses ", 7, 20, 1), + ("towel ", 18, 12, 2), + ("socks ", 4, 50, 1), + ("book ", 30, 10, 2) + ); + + Capacity : constant Item_Weight := 400; + Answer : Item_Bag; + + type Item_Table is + array (Item_Bag'First - 1 .. Item_Bag'Last, + Item_Weight'First .. Capacity) of Item_Value; + + Working_Table : Item_Table := (others => (others => 0)); + + procedure Fill_Table is + Item : Item_Pool; + V, Max_Value : Item_Value; + W : Item_Weight; + begin + for I in Candidates'Range loop + Item := Candidates (I); + + for J in Working_Table'Range (2) loop + Max_Value := Working_Table (I - 1, J); + + for K in 1 .. Item.Count loop + V := Item_Value (K) * Item.Value; + W := Item_Weight (K) * Item.Weight; + + if W <= J then + Max_Value := Item_Value'Max + (Max_Value, Working_Table (I - 1, J - W) + V); + end if; + end loop; + + Working_Table (I, J) := Max_Value; + end loop; + end loop; + end Fill_Table; + + procedure Trace_Answer is + Cap : Item_Weight := Capacity; + Count : Item_Count; + W, Weight : Item_Weight; + V, Max_Value : Item_Value; + begin + for I in reverse Answer'Range loop + Answer (I) := Candidates (I); + Max_Value := Working_Table (I, Cap); + Count := 0; + Weight := 0; + + for J in 1 .. Candidates (I).Count loop + W := Item_Weight (J) * Answer (I).Weight; + V := Item_Value (J) * Answer (I).Value; + if W <= Cap and then + Max_Value = Working_Table (I - 1, Cap - W) + V then + Weight := W; + Count := J; + end if; + end loop; + + Cap := Cap - Weight; + Answer (I).Count := Count; + end loop; + end Trace_Answer; + + procedure Show_Answer is + package Count_IO is new Ada.Text_IO.Integer_IO (Item_Count); + package Weight_IO is new Ada.Text_IO.Integer_IO (Item_Weight); + package Value_IO is new Ada.Text_IO.Integer_IO (Item_Value); + Item : Item_Pool; + C, Total_Items : Item_Count := 0; + W, Total_Weight : Item_Weight := 0; + V, Total_Value : Item_Value := 0; + Totals : String (Item_Name'Range) := "Totals "; + begin + for I in Answer'Range loop + Item := Answer (I); + C := Item.Count; + W := Item.Weight * Item_Weight (Item.Count); + V := Item.Value * Item_Value (Item.Count); + Total_Items := Total_Items + Item.Count; + Total_Weight := Total_Weight + W; + Total_Value := Total_Value + V; + + if C > 0 then + Ada.Text_IO.Put (Item.Name); + Count_IO.Put (C); + Weight_IO.Put (W); + Value_IO.Put (V); + Ada.Text_IO.New_Line; + end if; + end loop; + + Ada.Text_IO.Put (Totals); + Count_IO.Put (Total_Items); + Weight_IO.Put (Total_Weight); + Value_IO.Put (Total_Value); + Ada.Text_IO.New_Line; + end Show_Answer; + +begin + Fill_Table; + Trace_Answer; + Show_Answer; +end Knapsack_Bounded; diff --git a/Task/Knapsack-problem-Bounded/Fortran/knapsack-problem-bounded.f b/Task/Knapsack-problem-Bounded/Fortran/knapsack-problem-bounded.f new file mode 100644 index 0000000000..c45e4e4a0f --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Fortran/knapsack-problem-bounded.f @@ -0,0 +1,184 @@ +module knapsack_mod + implicit none + + !-------------------------------------------------------------------- + ! Define an item type with a name, weight, value, and available count. + !-------------------------------------------------------------------- + type :: item + character(len=24) :: name ! Name (for display purposes) + integer :: weight ! Weight of one copy of the item + integer :: value ! Value of one copy of the item + integer :: count ! Maximum number of copies available + end type item + + !-------------------------------------------------------------------- + ! Define a parameter array of items. + !-------------------------------------------------------------------- + type(item), parameter :: items(*) = [ & + item("map ", 9, 150, 1), & + item("compass ", 13, 35, 1), & + item("water ", 153, 200, 2), & + item("sandwich ", 50, 60, 2), & + item("glucose ", 15, 60, 2), & + item("tin ", 68, 45, 3), & + item("banana ", 27, 60, 3), & + item("apple ", 39, 40, 3), & + item("cheese ", 23, 30, 1), & + item("beer ", 52, 10, 3), & + item("suntan cream ", 11, 70, 1), & + item("camera ", 32, 30, 1), & + item("T-shirt ", 24, 15, 2), & + item("trousers ", 48, 10, 2), & + item("umbrella ", 73, 40, 1), & + item("waterproof trousers ", 42, 70, 1), & + item("waterproof overclothes ", 43, 75, 1), & + item("note-case ", 22, 80, 1), & + item("sunglasses ", 7, 20, 1), & + item("towel ", 18, 12, 2), & + item("socks ", 4, 50, 1), & + item("book ", 30, 10, 2) & + ] + +contains + + !-------------------------------------------------------------------- + ! Function: knapsack + ! + ! Description: + ! Solves the bounded knapsack problem using dynamic programming. + ! This version retains a two-dimensional DP table (m) and applies + ! binary splitting to efficiently handle items available in multiple + ! copies. + ! + ! Input: + ! w - Maximum weight capacity of the knapsack. + ! + ! Output: + ! s - An integer array (of size equal to the number of items) + ! where s(i) indicates how many copies of item i are selected + ! in the optimal solution. + !-------------------------------------------------------------------- + function knapsack(w) result(s) + integer, intent(in) :: w ! Knapsack capacity + integer, allocatable :: s(:) ! Solution vector of item counts + integer, allocatable :: m(:,:) ! DP table: m(i,j) is the maximum value using items 1..i with capacity j + integer :: n ! Total number of items + integer :: i, j, v, k ! Loop indices and temporary value + + ! Variables for binary splitting of the count of an item. + integer :: available ! Remaining copies to process for the current item + integer :: r ! Current binary splitting factor + integer :: k_group ! Number of copies in the current group + integer :: group_weight ! Total weight of the current group (k_group * item weight) + integer :: group_value ! Total value of the current group (k_group * item value) + + ! Determine the number of items available. + n = size(items) + + ! Allocate the solution vector and DP table. + ! DP table m is sized from row 0 (base case: no items) to n, and column 0 to w. + allocate(s(n), m(0:n, 0:w)) + + ! Initialize both the DP table and the solution vector to 0. + m = 0 + s = 0 + + !------------------------------- + ! DP Table Construction + !------------------------------- + ! For each item i (from 1 to n), determine the best value achievable + ! with a knapsack capacity from 0 to w. + do i = 1, n + + ! First, copy the previous row into the current row. + ! This means if we do not take any of item i, the value remains as before. + do j = 0, w + m(i, j) = m(i-1, j) + end do + + ! Process item i using binary splitting: + ! Instead of iterating k from 1 to items(i)%count one by one, we split + ! the available copies into groups for an efficient "0/1 item" update. + available = items(i)%count + r = 1 + do while (available > 0) + ! Use k_group copies, which is the minimum of the current binary factor and available copies. + k_group = min(r, available) + + ! Compute group weight and value for k_group copies. + group_weight = k_group * items(i)%weight + group_value = k_group * items(i)%value + + ! Perform a 0/1 knapsack update for this group. + ! Loop backwards from capacity w down to group_weight so that each group + ! is only used once. We update row i (which already contains m(i-1, :) as baseline). + do j = w, group_weight, -1 + ! If adding this group improves the total value, update m(i,j). + v = m(i, j - group_weight) + group_value + if (v > m(i, j)) then + m(i, j) = v + end if + end do + + ! Subtract the number of copies processed and double the binary factor. + available = available - k_group + r = r * 2 + end do + + end do + + !------------------------------- + ! Backtracking to Retrieve the Solution + !------------------------------- + ! Starting from the maximum capacity and the last item, deduce how many copies + ! of each item were used in the optimal solution. + j = w + do i = n, 1, -1 + ! Store the optimal value for items 1..i with current capacity j. + v = m(i, j) + ! For item i, try every possible count from 0 to items(i)%count. + do k = 0, items(i)%count + if (j >= k * items(i)%weight) then + ! Check if the current value resulted from taking k copies of item i. + if (v == m(i-1, j - k*items(i)%weight) + k*items(i)%value) then + s(i) = k ! Record k copies for item i + j = j - k*items(i)%weight ! Decrease the remaining capacity + exit ! Proceed to the next (previous) item + end if + end if + end do + end do + + end function knapsack + +end module knapsack_mod + +program main + use knapsack_mod + implicit none + integer, allocatable :: s(:) + integer :: i, total_count, total_weight, total_value + + s = knapsack(400) + + total_count = 0 + total_weight = 0 + total_value = 0 + + write(*,'(A22 A6 A7 A6)') 'Item', 'Count', 'Weight', 'Value' + write(*,'("------------------------------------------------")') + + do i = 1, size(items) + if (s(i) > 0) then + write(*,'(A22 I5 I6 I6)') & + items(i)%name, s(i), s(i)*items(i)%weight, s(i)*items(i)%value + total_count = total_count + s(i) + total_weight = total_weight + s(i)*items(i)%weight + total_value = total_value + s(i)*items(i)%value + end if + end do + + write(*,'("------------------------------------------------")') + write(*,'(A22 I5 I6 I6)') 'Totals:', total_count, total_weight, total_value + +end program main diff --git a/Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua b/Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua new file mode 100644 index 0000000000..67c59db1c1 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Lua/knapsack-problem-bounded.lua @@ -0,0 +1,180 @@ +#!/usr/bin/env lua + +--- knapsack packing for max value under wieght limit + + -- A: use value/weight score as pre-sort + -- B: initial run with no items excluded + -- C: try combos excluding each item for best value + + +--- table of tables +-- {name weight value quantity wt/val } +items = { + {"map", 9, 150, 1}, + {"compass", 13, 35, 1}, + {"water", 153, 200, 2}, + {"sandwich", 50, 60, 2}, + {"glucose", 15, 60, 2}, + {"tin", 68, 45, 3}, + {"banana", 27, 60, 3}, + {"apple", 39, 40, 3}, + {"cheese", 23, 30, 1}, + {"beer", 52, 10, 3}, + {"suntan cream", 11, 70, 1}, + {"camera", 32, 30, 1}, + {"t-shirt", 24, 15, 2}, + {"trousers", 48, 10, 2}, + {"umbrella", 73, 40, 1}, + {"waterproof trousers", 42, 70, 1}, + {"waterproof overclothes", 43, 75, 1}, + {"note-case", 22, 80, 1}, + {"sunglasses", 7, 20, 1}, + {"towel", 18, 12, 2}, + {"socks", 4, 50, 1}, + {"book", 30, 10, 2}, +} + +-- for output +function print_as_sack(its) + if its == nil then return end + + -- format columns + -- [20 |8 |8 |8 ] + local head_fmt = "%-20s\t%-8s\t%-8s\t%-8s" + local data_fmt = "%-20s\t%-8d\t%-8d\t%-8d" + + local head_table = + string.format(head_fmt, "item", "weight", "value", "quantity") + + io.write(head_table, "\n") + line = string.rep("-" , 64) + io.write(line, "\n") + + for n=1,#its do + it = its[n] + local name,wt,val,q = table.unpack(it) + + local fmt_table = + string.format(data_fmt, name, wt, val, q) + io.write(fmt_table, "\n") + end + io.write(line, "\n") +end + +-- calc value:weight ratio +function append_wv (its) + + for index, it in pairs(its) do + local name,wt,val,q = table.unpack(it) + wv = val / wt + it[#it+1] = wv -- append + end +end + +-- sort by 5th item of each table entry +function sort_by_wv (its) + -- sorts decreasing + local wv_sorter = function(a,b) return a[5] > b[5] end + table.sort(its, wv_sorter) +end + +-- pack sorted by v:w ratio +-- all or none per item +function add_up (its, max, excl) + + local sack_items = {} + local sack = {} + local this_weight = 0 + local this_value = 0 + + for i = 1,#its do + it = its[i] + + -- is same table? + -- lua has no continue keyword + if it == excl then goto continue end + + -- unpack into vars + local name,wt,val,q,wv = table.unpack(it) + local count = 0 + local w = 0 + for j = 1, q do + local t_wt = wt +this_weight + if t_wt < max then + this_value = this_value + val + this_weight = t_wt + count = count + 1 + end + end + + if this_weight >= max then break end + + if count > 0 then + _s = {name, count} + table.insert (sack, _s) + end + + ::continue:: --skip item, continue + end -- for items + + -- go through chosen sack + -- make sack of items + for s = 1,#sack do + local s_item = sack[s] + local s_name,s_count = table.unpack(s_item) + + for j = 1,#its do + local it = its[j] + local iname = it[1] + if iname == s_name then + it[4] = s_count + table.insert(sack_items, it) + end -- if + end -- for j + end -- for sack + + -- update best + if this_value > best_value then + best_value = this_value + best_weight = this_weight + best_sack = sack_items + end +end -- function add_up + +-- Main execution +if debug.getinfo(1).what == "main" then + + max_weight = 400 + best_weight = 0 + best_value = 0 + best_sack = {} + + start = os.clock() + + append_wv(items) -- add weight/value + + sort_by_wv(items) -- sort by wv + + add_up(items, max_weight, {}) -- first try + + -- with each item excluded + for i = 1, #items do + add_up(items, max_weight, items[i]) + end + + stop = os.clock() + + time = stop - start -- seconds + + usec_time = time * 1e6 --microseconds + + + -- output + print_as_sack(best_sack) + print ("value:\t", best_value) + print("weight:\t", best_weight) + print("time:\t" , usec_time , " usec") + + os.exit(0) +end +-- end diff --git a/Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs b/Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs new file mode 100644 index 0000000000..14d93d6108 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Rust/knapsack-problem-bounded.rs @@ -0,0 +1,99 @@ +use std::collections::HashMap; + +fn main() { + let max_wt = 400; + + let grouped_items = vec![ + ("map", 9, 150, 1), + ("compass", 13, 35, 1), + ("water", 153, 200, 3), + ("sandwich", 50, 60, 2), + ("glucose", 15, 60, 2), + ("tin", 68, 45, 3), + ("banana", 27, 60, 3), + ("apple", 39, 40, 3), + ("cheese", 23, 30, 1), + ("beer", 52, 10, 3), + ("suntan cream", 11, 70, 1), + ("camera", 32, 30, 1), + ("t-shirt", 24, 15, 2), + ("trousers", 48, 10, 2), + ("umbrella", 73, 40, 1), + ("waterproof trousers", 42, 70, 1), + ("waterproof overclothes", 43, 75, 1), + ("note-case", 22, 80, 1), + ("sunglasses", 7, 20, 1), + ("towel", 18, 12, 2), + ("socks", 4, 50, 1), + ("book", 30, 10, 2), + ]; + + let mut items = Vec::new(); + for &(item, wt, val, n) in &grouped_items { + for _ in 0..n { + items.push((item, wt, val)); + } + } + + let bagged = knapsack01_dp(&items, max_wt); + + // Count and group the bagged items + let mut counts: HashMap<&str, i32> = HashMap::new(); + for &(item, _, _) in &bagged { + *counts.entry(item).or_insert(0) += 1; + } + + // Sort and print the results + let mut sorted_counts: Vec<_> = counts.iter().collect(); + sorted_counts.sort_by_key(|&(item, _)| *item); + + println!("Bagged the following {} items", bagged.len()); + for (item, count) in sorted_counts { + println!(" {} off: {}", count, item); + } + + let total_value: i32 = bagged.iter().map(|&(_, _, val)| val).sum(); + let total_weight: i32 = bagged.iter().map(|&(_, wt, _)| wt).sum(); + + println!("for a total value of {} and a total weight of {}", + total_value, total_weight); +} + +fn knapsack01_dp<'a>(items: &'a [(&'a str, i32, i32)], limit: i32) -> Vec<(&'a str, i32, i32)> { + let n = items.len(); + let limit_usize = limit as usize; + + // Create DP table + let mut table = vec![vec![0; (limit_usize + 1) as usize]; n + 1]; + + for j in 1..=n { + let (_, wt, val) = items[j-1]; + let wt_usize = wt as usize; + + for w in 1..=limit_usize { + if wt_usize > w { + table[j][w] = table[j-1][w]; + } else { + table[j][w] = std::cmp::max( + table[j-1][w], + table[j-1][w - wt_usize] + val + ); + } + } + } + + // Backtrack to find items + let mut result = Vec::new(); + let mut w = limit_usize; + + for j in (1..=n).rev() { + let was_added = table[j][w] != table[j-1][w]; + + if was_added { + result.push(items[j-1]); + w -= items[j-1].1 as usize; + } + } + + result +} diff --git a/Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg b/Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg new file mode 100644 index 0000000000..020bcee753 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/ALGOL-68/knapsack-problem-continuous.alg @@ -0,0 +1,24 @@ +BEGIN # Knapsack problem: Continuous - based on the EasyLang sample # + + MODE ITEM = STRUCT( STRING name, REAL weight, value ); + PRIO SWAP = 1; + OP SWAP = ( REF ITEM a, b )VOID: BEGIN ITEM t = a; a := b; b := t END; + OP PRICE = ( ITEM a )REAL: value OF a / weight OF a; + []ITEM possible items + = ( ( "beef", 3.8, 36 ), ( "pork", 5.4, 43 ), ( "ham", 3.6, 90 ), ( "greaves", 2.4, 45 ) + , ( "flitch", 4.0, 30 ), ( "brawn", 2.5, 56 ), ( "welt", 3.7, 67 ), ( "salami", 3.0, 95 ) + , ( "sausage", 5.9, 98 ) + ); + [ LWB possible items : UPB possible items ]ITEM sack items := possible items; + FOR p FROM LWB sack items TO UPB sack items - 1 DO + FOR q FROM p + 1 TO UPB sack items DO + IF PRICE sack items[ q ] > PRICE sack items[ p ] THEN sack items[ p ] SWAP sack items[ q ] FI + OD + OD; + REAL max weight := 15; + FOR p FROM LWB sack items TO UPB sack items - 1 WHILE max weight > 0 DO + REAL w = IF weight OF sack items[ p ] > max weight THEN max weight ELSE weight OF sack items[ p ] FI; + print( ( fixed( w, -6, 2 ), " kg ", name OF sack items[ p ], newline ) ); + max weight -:= w + OD +END diff --git a/Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg b/Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg new file mode 100644 index 0000000000..f3697c4cd9 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/ALGOL-W/knapsack-problem-continuous.alg @@ -0,0 +1,38 @@ +begin % Knapsack problem: Continuous - based on the Algol 68 sample, which is based on the EasyLang sample % + + record Item ( string(12) name; real weight, cost ); + real procedure price ( reference(Item) value a ) ; cost(a) / weight(a); + integer MAX_ITEMS; + MAX_ITEMS := 9; + + begin + reference(Item) array sackItems ( 1 :: MAX_ITEMS ); + real maxWeight; + + sackItems( 1 ) := Item( "beef", 3.8, 36 );sackItems( 2 ) := Item( "pork", 5.4, 43 ); + sackItems( 3 ) := Item( "ham", 3.6, 90 );sackItems( 4 ) := Item( "greaves", 2.4, 45 ); + sackItems( 5 ) := Item( "flitch", 4.0, 30 );sackItems( 6 ) := Item( "brawn", 2.5, 56 ); + sackItems( 7 ) := Item( "welt", 3.7, 67 );sackItems( 8 ) := Item( "salami", 3.0, 95 ); + sackItems( 9 ) := Item( "sausage", 5.9, 98 ); + + for p := 1 until MAX_ITEMS - 1 do begin + for q := p + 1 until MAX_ITEMS do begin + if price( sackItems( q ) ) > price( sackItems( p ) ) then begin + reference(Item) t; + t := sackItems( p ); + sackItems( p ) := sackItems( q ); + sackItems( q ) := t + end if_price_of_q_gt_price_of_p + end for_q + end for_p; + maxWeight := 15; + for p := 1 until MAX_ITEMS do begin + real w; + w := if weight(sackItems(p)) > maxWeight then maxWeight else weight(sackItems(p)); + write( s_w := 0, r_format := "A", r_w := 6, r_d := 2, w, " kg ", name(sackItems(p)) ); + maxWeight := maxWeight - w; + if maxWeight <= 0 then goto endSack + end for_p ; +endSack: + end +end. diff --git a/Task/Knights-tour/EasyLang/knights-tour.easy b/Task/Knights-tour/EasyLang/knights-tour.easy index e6511f1a37..7f88d40a53 100644 --- a/Task/Knights-tour/EasyLang/knights-tour.easy +++ b/Task/Knights-tour/EasyLang/knights-tour.easy @@ -1,4 +1,4 @@ -sys topleft +sysconf topleft dirs[][] = [ [ 1 2 ] [ 1 -2 ] [ 2 1 ] [ 2 -1 ] [ -1 2 ] [ -1 -2 ] [ -2 -1 ] [ -2 1 ] ] global brd[][] size . func cntmoves m[] . @@ -76,14 +76,13 @@ proc showgraf . gcolor col[(r + c) mod1 2] grect sc * c sc * r sc sc . + gpenup for i to size * size for r = 1 to size : for c = 1 to size : if brd[r][c] = i gcolor 600 x = c * sc - sc / 2 y = r * sc - sc / 2 - if i > 1 : gline xp yp x y - xp = x - yp = y + glineto x y gcolor 880 gcircle x y sc / 10 . diff --git a/Task/Knights-tour/Zig/knights-tour.zig b/Task/Knights-tour/Zig/knights-tour.zig new file mode 100644 index 0000000000..341cca46da --- /dev/null +++ b/Task/Knights-tour/Zig/knights-tour.zig @@ -0,0 +1,128 @@ +const std = @import("std"); + +const SIZE: usize = 8; +const MOVES = [_][2]i32{ + [_]i32{ 2, 1 }, + [_]i32{ 1, 2 }, + [_]i32{ -1, 2 }, + [_]i32{ -2, 1 }, + [_]i32{ -2, -1 }, + [_]i32{ -1, -2 }, + [_]i32{ 1, -2 }, + [_]i32{ 2, -1 }, +}; + +const Point = struct { + x: i32, + y: i32, + + fn mov(self: Point, dir: [2]i32) Point { + return .{ + .x = self.x + dir[0], + .y = self.y + dir[1], + }; + } +}; + +const Board = struct { + field: [SIZE][SIZE]i32, + + fn init() Board { + return .{ + .field = [_][SIZE]i32{[_]i32{0} ** SIZE} ** SIZE, + }; + } + + fn available(self: *const Board, p: Point) bool { + return 0 <= p.x and + p.x < @as(i32, @intCast(SIZE)) and + 0 <= p.y and + p.y < @as(i32, @intCast(SIZE)) and + self.field[@as(usize, @intCast(p.x))][@as(usize, @intCast(p.y))] == 0; + } + + // calculate the number of possible moves + fn countDegree(self: *const Board, p: Point) i32 { + var count: i32 = 0; + for (MOVES) |dir| { + const next = p.mov(dir); + if (self.available(next)) { + count += 1; + } + } + return count; + } + + fn format( + self: *const Board, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + + for (self.field) |row| { + for (row) |x| { + try writer.print("{d:3} ", .{x}); + } + try writer.writeByte('\n'); + } + } +}; + +fn knightsTour(x: i32, y: i32) ?Board { + var board = Board.init(); + var p = Point{ .x = x, .y = y }; + var step: i32 = 1; + board.field[@as(usize, @intCast(p.x))][@as(usize, @intCast(p.y))] = step; + step += 1; + + while (step <= @as(i32, @intCast(SIZE * SIZE))) { + // choose next square by Warnsdorf's rule + var candidates = std.ArrayList(struct { degree: i32, pos: Point }).init(std.heap.page_allocator); + defer candidates.deinit(); + + for (MOVES) |dir| { + const adj = p.mov(dir); + if (board.available(adj)) { + const degree = board.countDegree(adj); + candidates.append(.{ .degree = degree, .pos = adj }) catch unreachable; + } + } + + if (candidates.items.len == 0) { + return null; // can't move + } + + // Find minimum degree + var min_idx: usize = 0; + for (candidates.items, 0..) |candidate, i| { + if (candidate.degree < candidates.items[min_idx].degree) { + min_idx = i; + } + } + + // move to next square + p = candidates.items[min_idx].pos; + board.field[@as(usize, @intCast(p.x))][@as(usize, @intCast(p.y))] = step; + step += 1; + } + + return board; +} + +pub fn main() !void { + const x: i32 = 3; + const y: i32 = 1; + + const stdout = std.io.getStdOut().writer(); + try stdout.print("Board size: {d}\n", .{SIZE}); + try stdout.print("Starting position: ({d}, {d})\n", .{ x, y }); + + if (knightsTour(x, y)) |board| { + try stdout.print("{}\n", .{board}); + } else { + try stdout.print("Fail!\n", .{}); + } +} diff --git a/Task/Knuth-shuffle/DuckDB/knuth-shuffle.duckdb b/Task/Knuth-shuffle/DuckDB/knuth-shuffle.duckdb new file mode 100644 index 0000000000..8f22abbea6 --- /dev/null +++ b/Task/Knuth-shuffle/DuckDB/knuth-shuffle.duckdb @@ -0,0 +1,63 @@ +### Generic utilities + +create or replace function printstring(s, width) as ( + regexp_replace(s, '(.{1,' || width || '})', '\1' || chr(10), 'g' ) +); + +# It is assumed that 1 <= i, j <= length(ary) +create or replace function swap(ary, i, j) as ( + case when i = j then ary + when i < j then ary[1:i -1] || [ary[j]] || ary[i+1:j-1] || [ary[i]] || ary[j+1:] + else ary[1:j -1] || [ary[i]] || ary[j+1:i-1] || [ary[j]] || ary[i+1:] + end +); + +# Generate a pseudo-random integer in range(0,n), i.e. excluding n +create or replace function rnd(n) as ( + SELECT floor(random() * n)::BIGINT AS rnd +); + +### A deck of cards as codepoints +create or replace function deck() as ( + range(127137, 127148) || range(127149, 127151) -- Spades + || range(127153, 127164) || range(127165, 127167) -- Hearts + || range(127169, 127180) || range(127181, 127183) -- Diamonds + || range(127185, 127196) || range(127197, 127199) -- Clubs +); + +create or replace function printdeck(deck) as ( + list_transform(deck, x -> chr(x::INTEGER)).array_to_string('') +); + +### Knuth Shuffle of any list +create or replace function knuth_shuffle_table(arr) as table ( + WITH RECURSIVE cte(a, idx, r) AS ( + -- Base case: the original array, the index of the last element, and a random index + SELECT arr as a, length(arr) AS idx, 1 + rnd(length(arr)) as r + UNION ALL + -- Recursive case: shuffle the array by swapping the current index with a random element + SELECT + swap(a, r, idx) AS a, + idx - 1 AS idx, + 1 + rnd(idx - 1) as r + FROM cte + WHERE idx > 1 + ) + SELECT a + FROM cte + WHERE idx = 1 + LIMIT 1 +); + +# A scalar version of knuth_shuffle_table() specialized for INTEGER[] +# Currently DuckDB requires the specialization. +create or replace function knuth_shuffle(arr) as ( + from knuth_shuffle_table(arr::INTEGER[]) _(a) +); + +### Examples +select a, knuth_shuffle(a) +from values ([]), ([10,20]), ([0,10,20,30,40]) as t(a); + +.mode list +select knuth_shuffle(deck()).printdeck().printstring(13); diff --git a/Task/Knuth-shuffle/REBOL/knuth-shuffle-1.rebol b/Task/Knuth-shuffle/REBOL/knuth-shuffle-1.rebol new file mode 100644 index 0000000000..818565ad7b --- /dev/null +++ b/Task/Knuth-shuffle/REBOL/knuth-shuffle-1.rebol @@ -0,0 +1,4 @@ +probe random [] +probe random [10] +probe random [10 20] +probe random [10 20 30] diff --git a/Task/Knuth-shuffle/REBOL/knuth-shuffle-2.rebol b/Task/Knuth-shuffle/REBOL/knuth-shuffle-2.rebol new file mode 100644 index 0000000000..6fa456482f --- /dev/null +++ b/Task/Knuth-shuffle/REBOL/knuth-shuffle-2.rebol @@ -0,0 +1,48 @@ +Rebol [ + title: "Rosetta code: Knuth shuffle" + file: %Knuth_shuffle.r3 + url: https://rosettacode.org/wiki/Knuth_shuffle +] +fisher-yates: func [ + "Fisher-Yates shuffle algorithm - randomly shuffles elements in a block" + ;Uses the modern variant that works backwards through the array + data [series!] "Input block to shuffle" + /local i j tmp ;; Local variables: i=current index, j=random index, tmp=swap variable +][ + ;; Make a copy of the input block and get its length + ;; This prevents modification of the original block + i: length? data: copy data + + ;; Loop from the last element down to the second element + ;; We stop at 1 because there's no need to swap the first element with itself + while [i > 1] [ + ;; Generate random index j from 1 to i (inclusive) + j: random i + ;; Previous version tried to avoid self-swap as an optimization + ;; but actually it is faster to avoid it! + + ;; Three-step swap using path notation for direct block access + ;; Step 1: Store element at random position j in temporary variable + tmp: data/:j + + ;; Step 2: Move current element (at position i) to random position j + data/:j: data/:i + + ;; Step 3: Move stored element to current position i + ;; Using :tmp to get the value (word evaluation) + data/:i: :tmp + + ;; Move to previous element (working backwards through the block) + i: i - 1 + ] + + ;; Return the shuffled block + data +] + +random/seed 0 ;; to get consistent results + +probe fisher-yates [] +probe fisher-yates [10] +probe fisher-yates [10 20] +probe fisher-yates [10 20 30] diff --git a/Task/Knuth-shuffle/REBOL/knuth-shuffle.rebol b/Task/Knuth-shuffle/REBOL/knuth-shuffle.rebol deleted file mode 100644 index a16076dd9a..0000000000 --- a/Task/Knuth-shuffle/REBOL/knuth-shuffle.rebol +++ /dev/null @@ -1,18 +0,0 @@ -REBOL [ - Title: "Fisher-Yates" - Purpose: {Fisher-Yates shuffling algorithm} -] - -fisher-yates: func [b [block!] /local n i j k] [ - n: length? b: copy b - i: n - while [i > 1] [ - if i <> j: random i [ - error? set/any 'k pick b j - change/only at b j pick b i - change/only at b i get/any 'k - ] - i: i - 1 - ] - b -] diff --git a/Task/Knuth-shuffle/YAMLScript/knuth-shuffle.ys b/Task/Knuth-shuffle/YAMLScript/knuth-shuffle.ys new file mode 100644 index 0000000000..7d1331b7b0 --- /dev/null +++ b/Task/Knuth-shuffle/YAMLScript/knuth-shuffle.ys @@ -0,0 +1,8 @@ +!YS-v0 + +defn main(*list): + say: + reduce _ list:V range(list.#.-- 1 -1): + fn(v i): + r =: i:rand-int + assoc v: i (v r) r (v i) diff --git a/Task/Knuths-power-tree/Fortran/knuths-power-tree.f b/Task/Knuths-power-tree/Fortran/knuths-power-tree.f new file mode 100644 index 0000000000..754839f67e --- /dev/null +++ b/Task/Knuths-power-tree/Fortran/knuths-power-tree.f @@ -0,0 +1,379 @@ +module hash_map_module + + use iso_fortran_env + use qdmodule + + implicit none + private + public :: HashEntry, HashMap + + type HashEntry + integer(int64) :: key, value + type(HashEntry), pointer :: sgte => null() + end type HashEntry + +! Container for pointer to HashEntry + type HashEntryContainer + type(HashEntry), pointer :: ptr => null() + end type HashEntryContainer + + type HashMap + type(HashEntryContainer), allocatable :: buckets(:) + contains + procedure :: put => hash_map_put + procedure :: get => hash_map_get + procedure :: contains => hash_map_contains + end type HashMap + +contains + + subroutine hash_map_put(this, key, value) + class(HashMap), intent(inout) :: this + integer(int64), intent(in) :: key, value + integer(int64) :: bucket + type(HashEntry), pointer :: entry + + bucket = iand(key, int(255, int64)) + entry => this % buckets(bucket) % ptr + + ! Check for existing key + do while (associated(entry)) + if (entry % key == key) then + entry % value = value + return + end if + entry => entry % sgte + end do + + ! Insert new entry at head + allocate (entry) + entry % key = key + entry % value = value + entry % sgte => this % buckets(bucket) % ptr ! Correct pointer assignment + this % buckets(bucket) % ptr => entry ! Update head pointer + end subroutine hash_map_put + + function hash_map_get(this, key, defaultValue) result(res) + class(HashMap), intent(in) :: this + integer(int64), intent(in) :: key + integer(int64), optional, intent(in) :: defaultValue + integer(int64) :: res, bucket + type(HashEntry), pointer :: entry + + res = 0 + if (present(defaultValue)) res = defaultValue + bucket = iand(key, int(255, int64)) + entry => this % buckets(bucket) % ptr + + do while (associated(entry)) + if (entry % key == key) then + res = entry % value + return + end if + entry => entry % sgte + end do + end function hash_map_get + + function hash_map_contains(this, key) result(res) + class(HashMap), intent(in) :: this + integer(int64), intent(in) :: key + logical :: res + integer(int64) :: bucket + type(HashEntry), pointer :: entry + + bucket = iand(key, int(255, int64)) + entry => this % buckets(bucket) % ptr + + res = .false. + do while (associated(entry)) + if (entry % key == key) then + res = .true. + return + end if + entry => entry % sgte + end do + end function hash_map_contains + +end module hash_map_module + +module int_array_module + use iso_fortran_env + implicit none + private + public :: IntArray + + type IntArray + integer(int64), allocatable :: dato(:) + integer(int64) :: size = 0 + contains + procedure :: add => int_array_add + procedure :: get => int_array_get + procedure :: getSize => int_array_size + procedure :: clear => int_array_clear + end type + +contains + subroutine int_array_add(this, value) + use iso_fortran_env + class(IntArray), intent(inout) :: this + integer(int64), intent(in) :: value + integer(int64), allocatable :: temp(:) + integer(int64) :: current_capacity + + if (.not. allocated(this % dato)) then + allocate (this % dato(30)) + current_capacity = 30_8 + else + current_capacity = size(this % dato) + end if + + if (this % size >= current_capacity) then + call move_alloc(this % dato, temp) + allocate (this % dato(2 * current_capacity)) + this % dato(1:this % size) = temp(1:this % size) + end if + + this % size = this % size + 1 + this % dato(this % size) = value + end subroutine int_array_add + + function int_array_get(this, index) result(res) + class(IntArray), intent(in) :: this + integer(int64), intent(in) :: index + integer(int64) :: res + + res = 0 + if (index >= 1 .and. index <= this % size) res = this % dato(index) + end function + + function int_array_size(this) result(res) + use iso_fortran_env + class(IntArray), intent(in) :: this + integer(int64) :: res + res = this % size + end function + + subroutine int_array_clear(this) + class(IntArray), intent(inout) :: this + this % size = 0 + end subroutine +end module + +module power_module + use iso_fortran_env + use hash_map_module + use int_array_module + implicit none + private + public :: showPow, initialize_power ! Add initialization routine + + type(HashMap) :: p + type(IntArray) :: levels(1) + +contains + + subroutine initialize_power + integer :: i + if (allocated(p % buckets)) deallocate (p % buckets) + allocate (p % buckets(0:255)) + do i = 0, 255 + nullify (p % buckets(i) % ptr) ! Explicitly nullify all bucket pointers + end do + call levels(1) % clear() + call p % put(1_8, 0_8) + call levels(1) % add(1_8) + end subroutine + + recursive function path(n) result(res) + use iso_fortran_env + use hash_map_module + use int_array_module + implicit none + integer(int64), intent(in) :: n + type(IntArray) :: res + integer(int64) :: i, j, x, y, sum, curr + type(IntArray) :: q, tempPath + integer(int64) :: max_iter, iter + + ! Safety limit to prevent infinite loops + max_iter = 100000000 + iter = 0 + + if (n == 0) return + do while (.not. p % contains(n)) + q = IntArray() + + do i = 1, levels(1) % getSize() + x = levels(1) % get(i) + associate (xPath => path(x)) + do j = 1, xPath % getSize() + y = xPath % get(j) + sum = x + y + if (p % contains(sum)) cycle + call p % put(sum, x) + call q % add(sum) + end do + end associate + end do + call levels(1) % clear() + do i = 1, q % getSize() + call levels(1) % add(q % get(i)) + end do + + if (q % getSize() == 0) exit + + iter = iter + 1 + if (iter > max_iter) then + print *, "Path search exceeded maximum iterations for n=", n + exit + end if + end do + + curr = n + tempPath = IntArray() + + do while (curr /= 0) + call tempPath % add(curr) + curr = p % get(curr, 0_8) + end do + + do i = tempPath % getSize(), 1, -1 + call res % add(tempPath % get(i)) + end do + + return + end function path + + function treePowBig(x, n) result(res) + use iso_fortran_env + integer(int64), intent(in) :: x, n + integer(kind=16) :: res + integer(kind=16), allocatable :: r(:) + integer(int64) :: i, curr, p + type(IntArray) :: pathToN + + ! Allocate array to hold intermediate results + allocate (r(0:n)) + r(0) = 1_16 + if (n >= 1) r(1) = x + + p = 0 + pathToN = path(n) + + do i = 1, pathToN % getSize() + curr = pathToN % get(i) + r(curr) = r(curr - p) * r(p) + p = curr + end do + + res = r(n) + deallocate (r) + end function treePowBig + + function treePowDecimal(x, n) result(res) + use qdmodule + type(qd_real), intent(in) :: x + integer(int64), intent(in) :: n + type(qd_real) :: res + type(qd_real), allocatable :: r(:) + integer(int64) :: i, curr, p + type(IntArray) :: pathToN + + allocate (r(0:n)) + r(0) = "1.0" ! r(0) = 1.0 in quad-double + if (n >= 1) r(1) = x + + p = 0 + pathToN = path(n) + do i = 1, pathToN % getSize() + curr = pathToN % get(i) + r(curr) = r(curr - p) * r(p) + p = curr + end do + + res = r(n) + deallocate (r) + end function treePowDecimal + + subroutine showPow(x, n, xx) + use iso_fortran_env + use qdmodule + use int_array_module + implicit none + character(len=*) :: xx + type(qd_real), intent(in) :: x + integer(int64), intent(in) :: n + type(IntArray) :: pathToN + character(len=1024) :: pathStr + integer(int64) :: i + type(qd_real) :: result + character(len=1024) :: str + character(len=5) :: str2 + double precision :: try + integer :: unit +! + pathToN = path(n) + pathStr = "" + do i = 1, pathToN % getSize() + if (i > 1) pathStr = trim(pathStr)//", " + write (pathStr(len_trim(pathStr) + 1:), '(I0)') pathToN % get(i) + end do + + print '(I0,": [",A,"]" )', n, trim(pathStr) + + result = treePowDecimal(x, n) +! call qdwrite(6, result) ! Writes result to stdout (unit 6) + + ! Create a temporary internal file (string) + open (newunit=unit, status='scratch', action='readwrite', form='formatted') + + ! Write qd_real to the internal file + call qdwrite(unit, result) + + ! Read back into the string + rewind (unit) + read (unit, '(A)') str + close (unit) + write (str2, '(i0)') n + write (*, '(a)', advance="no") 'Result: '//xx//'^'//trim(adjustl(str2))//' = ' + read (str, *) try + if ((mod(try, 1.0) == 0.0) .and. (try < real(huge(1_16), kind=real64))) then + write (str, '(I0)') int(try, kind=16) + write (*, '(A)') trim(adjustl(str)) + else + if (try < 1.0d10) then + write (str, '(f20.13)') try + write (*, '(a)') trim(adjustl(str)) + else + write (*, '(a)') trim(adjustl(str)) + end if + end if + print * + end subroutine showPow + +end module + +program main + use iso_fortran_env + use qdmodule + use power_module + implicit none + integer(int64) :: i + type(qd_real) :: x + + call initialize_power() + + x = "2.0" + do i = 0, 17 + call showPow(x, i, "2.0") + end do + + x = "1.1" + call showPow(x, 81_8, "1.1") + call initialize_power() + + x = "3.0" + call showPow(x, 191_8, "3.0") + + stop 'Normal Finish' +end program diff --git a/Task/Knuths-power-tree/Python/knuths-power-tree.py b/Task/Knuths-power-tree/Python/knuths-power-tree-1.py similarity index 100% rename from Task/Knuths-power-tree/Python/knuths-power-tree.py rename to Task/Knuths-power-tree/Python/knuths-power-tree-1.py diff --git a/Task/Knuths-power-tree/Python/knuths-power-tree-2.py b/Task/Knuths-power-tree/Python/knuths-power-tree-2.py new file mode 100644 index 0000000000..d20cd8ad7f --- /dev/null +++ b/Task/Knuths-power-tree/Python/knuths-power-tree-2.py @@ -0,0 +1,57 @@ +""" https://rosettacode.org/wiki/Knuth%27s_power_tree """ + +from typing import List, Dict +from mpmath import mp + +# Set decimal precision for mpmath calculations (like Go example 320 bits) +mp.dps = 140 + +# Global variables +p: Dict[int, int] = {1: 0} +lvl: List[List[int]] = [[1]] + + +def path(n: int) -> List[int]: + """ return path to the node with id ''n'' """ + if n == 0: + return [] + + while n not in p: + q: List[int] = [] + for x in lvl[0]: + for y in path(x): + z = x + y + if z in p: + break + p[z] = x + q.append(z) + lvl[0] = q + + r = path(p[n]) + [n] + return r + + +def tree_pow(x: float, n: int) -> mp.mpf: + """ use power tree to compute x ** n """ + r: Dict[int, mp.mpf] = {0: mp.mpf('1'), 1: mp.mpf(str(x))} + prev = 0 + for i in path(n): + r[i] = mp.mpf(r[i - prev] * r[prev]) + prev = i + return r[n] + + +def show_pow(x: float, n: int) -> None: + """ print the power calculation """ + print(f"{n}: {path(n)}") + y = tree_pow(x, n) + ans = mp.nstr(y, n=100, strip_zeros=True)[ + :-2] if mp.isint(y) else mp.nstr(y, n=10) + print(f"{mp.nstr(x)} ^ {n} = {ans}\n") + + +if __name__ == "__main__": + for expo in range(18): + show_pow(2, expo) + show_pow(1.1, 81) + show_pow(3.0, 191) diff --git a/Task/Koch-curve/EasyLang/koch-curve.easy b/Task/Koch-curve/EasyLang/koch-curve.easy index 81bdc0e0b6..a26f8ce4e5 100644 --- a/Task/Koch-curve/EasyLang/koch-curve.easy +++ b/Task/Koch-curve/EasyLang/koch-curve.easy @@ -1,5 +1,3 @@ -xp = 0 / 0 -yp = xp proc koch x1 y1 x2 y2 iter . x3 = (x1 * 2 + x2) / 3 y3 = (y1 * 2 + y2) / 3 @@ -14,13 +12,11 @@ proc koch x1 y1 x2 y2 iter . koch x5 y5 x4 y4 iter koch x4 y4 x2 y2 iter else - if xp = xp : gline xp yp x1 y1 - gline x1 y1 x3 y3 - gline x3 y3 x3 y3 - gline x3 y3 x4 y4 - gline x4 y4 x2 y2 - xp = x2 - yp = y2 + glineto x1 y1 + glineto x3 y3 + glineto x3 y3 + glineto x4 y4 + glineto x2 y2 . . glinewidth 0.3 diff --git a/Task/Largest-int-from-concatenated-ints/DuckDB/largest-int-from-concatenated-ints.duckdb b/Task/Largest-int-from-concatenated-ints/DuckDB/largest-int-from-concatenated-ints.duckdb new file mode 100644 index 0000000000..2bb642a44b --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/DuckDB/largest-int-from-concatenated-ints.duckdb @@ -0,0 +1,18 @@ +create or replace function pad(s,n) as ( + s || repeat(s[-1], (n-length(s) )) +); + +create or replace function largest_int(lst) as ( + select array_agg(s order by x desc).array_to_string('') + from (select unnest(strs) as s, unnest(augmented) as x + from (select + list_transform(lst, x -> cast(x as VARCHAR)) as strs, + list_transform(strs, x -> length(x)).list_max() as mx, + list_transform(strs, x -> pad(x, mx)) as augmented ) ) +); + +## Examples +.mode line +select largest_int([1, 34, 3, 98, 9, 76, 45, 4]); + +select largest_int([54, 546, 548, 60]); diff --git a/Task/Largest-proper-divisor-of-n/AutoLISP/largest-proper-divisor-of-n.l b/Task/Largest-proper-divisor-of-n/AutoLISP/largest-proper-divisor-of-n.l new file mode 100644 index 0000000000..a1139cb80d --- /dev/null +++ b/Task/Largest-proper-divisor-of-n/AutoLISP/largest-proper-divisor-of-n.l @@ -0,0 +1,22 @@ +(progn + (defun LargestProperDivisor (n / x) + (cond + ((= 1 n) n) + ((> n 1) + (setq x (1- n)) + (while (not (zerop (rem n x))) + (setq x (1- x)) + ) + x + ) + ) + ) + ((lambda ( / cnt nums) + (mapcar + 'LargestProperDivisor + (repeat (1- (setq cnt 101)) + (setq nums (cons (setq cnt (1- cnt)) nums)) + ) + ) + )) +) diff --git a/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-3.cpp b/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-3.cpp new file mode 100644 index 0000000000..ab28f8ebcb --- /dev/null +++ b/Task/Last-Friday-of-each-month/C++/last-friday-of-each-month-3.cpp @@ -0,0 +1,11 @@ +#include +#include + +int main() { + std::cout << "The dates of the last Friday in each month of 2023:" << std::endl; + using namespace std::literals; + for ( auto ymd = std::chrono::Friday[std::chrono::last]/1/2023; + ymd.year() < 2024y; + ymd += std::chrono::months{1} ) + std::cout << std::chrono::sys_days{ymd} << '\n'; +} diff --git a/Task/Last-Friday-of-each-month/DuckDB/last-friday-of-each-month.duckdb b/Task/Last-Friday-of-each-month/DuckDB/last-friday-of-each-month.duckdb new file mode 100644 index 0000000000..fc10ee945f --- /dev/null +++ b/Task/Last-Friday-of-each-month/DuckDB/last-friday-of-each-month.duckdb @@ -0,0 +1,14 @@ +create or replace function last_friday(yr, mo) as ( + select dy + from (select unnest(range( + extract('day' from last_day(make_date(yr,mo,1))), 1, -1)) as dy ) + where extract('dayofweek' from make_date(yr, mo, dy )) = 5 -- Friday + limit 1 +); + +create or replace function last_fridays(yr) as table ( + select yr, mo, last_friday(yr, mo) as dy + from range(1,13) u(mo) +); + +from last_fridays(2012); diff --git a/Task/Last-letter-first-letter/FutureBasic/last-letter-first-letter.basic b/Task/Last-letter-first-letter/FutureBasic/last-letter-first-letter.basic new file mode 100644 index 0000000000..295fef5ce9 --- /dev/null +++ b/Task/Last-letter-first-letter/FutureBasic/last-letter-first-letter.basic @@ -0,0 +1,88 @@ +include "NSLog.incl" + +begin globals + NSInteger maxPathLength = 0 + NSInteger maxPathLengthCount = 0 + CFMutableStringRef maxPathExample +end globals + +void local fn SetUp + maxPathExample = fn MutableStringWithCapacity( 500 ) + + CFArrayRef names = @[@"audino", @"bagon", @"baltoy", @"banette", + @"bidoof", @"braviary", @"bronzor", @"carracosta", @"charmeleon", + @"cresselia", @"croagunk", @"darmanitan", @"deino", @"emboar", + @"emolga", @"exeggcute", @"gabite", @"girafarig", @"gulpin", + @"haxorus", @"heatmor", @"heatran", @"ivysaur", @"jellicent", + @"jumpluff", @"kangaskhan", @"kricketune", @"landorus", @"ledyba", + @"loudred", @"lumineon", @"lunatone", @"machamp", @"magnezone", + @"mamoswine", @"nosepass", @"petilil", @"pidgeotto", @"pikachu", + @"pinsir", @"poliwrath", @"poochyena", @"porygon2", @"porygonz", + @"registeel", @"relicanth", @"remoraid", @"rufflet", @"sableye", + @"scolipede", @"scrafty", @"seaking", @"sealeo", @"silcoon", + @"simisear", @"snivy", @"snorlax", @"spoink", @"starly", @"tirtouga", + @"trapinch", @"treecko", @"tyrogue", @"vigoroth", @"vulpix", + @"wailord", @"wartortle", @"whismur", @"wingull", @"yamask"] + AppSetProperty( @"pokemonNames", names ) +end fn + +void local fn Recursive( part as CFMutableArrayRef, offset as NSInteger ) + NSInteger i + + if ( offset > maxPathLength ) + maxPathLength = offset + maxPathLengthCount = 1 + else if ( offset == maxPathLength ) + maxPathLengthCount++ + MutableStringSetString( maxPathExample, @"" ) + for i = 0 to offset - 1 + if (i % 5 == 0) then MutableStringAppendString( maxPathExample, @"\n ") else MutableStringAppendString( maxPathExample, @" " ) + MutableStringAppendString( maxPathExample, part[i] ) + next + end if + + CFStringRef previousPart = part[offset - 1] + NSUInteger lastCharacterIndex = len(previousPart) - 1 + unichar lastChar = fn StringcharacterAtIndex( previousPart, lastCharacterIndex ) + + for i = offset to fn ArrayCount( part ) - 1 + if ( fn StringCharacterAtIndex( part[i], 0 ) == lastChar ) + CFStringRef tmp = part[offset] + part[offset] = part[i] + part[i] = tmp + fn Recursive( part, offset + 1 ) + part[i] = part[offset] + part[offset] = tmp + end if + next +end fn + +void local fn LastLetterFirstLetter + CFArrayRef names = fn AppProperty( @"pokemonNames" ) + CFMutableArrayRef mutableNames = fn MutableArrayWithArray( names ) + + for NSInteger i = 0 to fn ArrayCount( mutableNames ) - 1 + CFStringRef tmp = mutableNames[0] + mutableNames[0] = mutableNames[i] + mutableNames[i] = tmp + fn Recursive( mutableNames, 1 ) + mutableNames[i] = mutableNames[0] + mutableNames[0] = tmp + next + + CFTimeInterval t = fn CACurrentMediaTime + MutableStringReplaceAllOccurrencesOfString( maxPathExample, @" ", @"\n" ) + MutableStringReplaceAllOccurrencesOfString( maxPathExample, @"\n\n", @"\n" ) + MutableStringReplaceAllOccurrencesOfString( maxPathExample, @"\n\n", @"\n" ) + MutableStringReplaceAllOccurrencesOfString( maxPathExample, @"\n", @"\n\t" ) + NSLog( @"Maximum path length: %ld", (long)maxPathLength ) + NSLog( @"Paths of that length: %ld", (long)maxPathLengthCount ) + NSLog( @"One solution:\n %@", maxPathExample ) + NSLog( @"\nCompute time: %.3f ms", (fn CACurrentMediaTime-t)*1000 ) + +end fn + +fn SetUp +fn LastLetterFirstLetter + +HandleEvents diff --git a/Task/Leap-year/DuckDB/leap-year.duckdb b/Task/Leap-year/DuckDB/leap-year.duckdb new file mode 100644 index 0000000000..4441c42c50 --- /dev/null +++ b/Task/Leap-year/DuckDB/leap-year.duckdb @@ -0,0 +1,2 @@ +create or replace function is_leap_year(y) as + (y%4) == 0 and (y < 1582 or (y%400) == 0 or (y%100) != 0); diff --git a/Task/Leap-year/Pluto/leap-year.pluto b/Task/Leap-year/Pluto/leap-year.pluto new file mode 100644 index 0000000000..7a6bcf10b1 --- /dev/null +++ b/Task/Leap-year/Pluto/leap-year.pluto @@ -0,0 +1,7 @@ +function is_leap(y) + return (y % 4 == 0) and (y % 100 != 0) or (y % 400 == 0) +end + +for {1900,1904,1994,1996,1997,2000} as i do + io.write(''..is_leap(i),'\t') +end diff --git a/Task/Left-factorials/DuckDB/left-factorials.duckdb b/Task/Left-factorials/DuckDB/left-factorials.duckdb new file mode 100644 index 0000000000..ddb99186a8 --- /dev/null +++ b/Task/Left-factorials/DuckDB/left-factorials.duckdb @@ -0,0 +1,43 @@ +CREATE OR REPLACE FUNCTION factorial_t(num) as table ( + with recursive cte as ( + select 0 as n, 1::DOUBLE as fact + union all + select + n+1 as n, + ((n+1) * fact) as fact + from cte + where n < num + ) select n, fact from cte +) ; + +CREATE OR REPLACE FUNCTION left_factorial(num) as ( + if (num < 1, 0, + (select sum(fact) from factorial_t(num - 1)) ) +); + +CREATE OR REPLACE FUNCTION left_factorial_t(num) as table ( + with recursive cte as ( + select 0 as n, 1.0::DOUBLE as fact, 0::DOUBLE as sum + union all + select + n+1 as n, + ((n+1) * fact) as fact, + sum + fact as sum + from cte + where n < num + ) + select n, sum as left_factorial + from cte + order by n +) ; + +# First 10 +from left_factorial_t(10); + +# By 10s +from left_factorial_t(110) +where n % 10 = 0 +and n > 10; + +# Maximum is for 171 +select left_factorial(171); diff --git a/Task/Leonardo-numbers/DuckDB/leonardo-numbers.duckdb b/Task/Leonardo-numbers/DuckDB/leonardo-numbers.duckdb new file mode 100644 index 0000000000..e11104e931 --- /dev/null +++ b/Task/Leonardo-numbers/DuckDB/leonardo-numbers.duckdb @@ -0,0 +1,27 @@ +# The specification of `zero`, `one` and `incr` will determine precision. +# For maximum precision, specify them as UHUGEINT. +create or replace function Leonardo_table(max, zero, one, incr) as table ( + with recursive cte(n,lp,l) as ( + select 1 as n, zero as lp, one as l + union all + select n+1, l as lp, l + lp + incr as l + from cte + where n= 1 then + write(l0:1, ' '); + if lmt >= 2 then + write(l1:1, ' '); + for i := 3 to lmt do + begin + write(l0 + l1 + sum:1, ' '); + tmp := l0; + l0 := l1; + l1 := tmp + l1 + sum; + end; + writeln + end; + +begin + writeleonardonums(1, 1, 1, 25, 'Leonardo numbers'); + writeleonardonums(0, 1, 0, 25, 'Fibonacci numbers') +end. diff --git a/Task/Letter-frequency/DuckDB/letter-frequency-1.duckdb b/Task/Letter-frequency/DuckDB/letter-frequency-1.duckdb new file mode 100644 index 0000000000..5240e44975 --- /dev/null +++ b/Task/Letter-frequency/DuckDB/letter-frequency-1.duckdb @@ -0,0 +1,8 @@ +# First read in the file as a single row in a table: +create or replace table t as (select content from read_text('unixdict.txt')); + +# Use GROUP BY to create the table +select c, count(*) as count + from (select unnest(regexp_extract_all((from t), '.')) as c) + group by c + order by count, c; diff --git a/Task/Letter-frequency/DuckDB/letter-frequency-2.duckdb b/Task/Letter-frequency/DuckDB/letter-frequency-2.duckdb new file mode 100644 index 0000000000..3bc9e0ce46 --- /dev/null +++ b/Task/Letter-frequency/DuckDB/letter-frequency-2.duckdb @@ -0,0 +1,7 @@ +# See above for reading in the file. + +# Create a table containing all the individual characters +create or replace table c as (select unnest(regexp_extract_all((from t), '.')) as c); + +# Choose a large enough bin_count value to ensure each character has its own bin +from histogram('c', c, bin_count := 100) order by count desc; diff --git a/Task/Letter-frequency/Koka/letter-frequency.koka b/Task/Letter-frequency/Koka/letter-frequency.koka new file mode 100644 index 0000000000..7dc8e9a800 --- /dev/null +++ b/Task/Letter-frequency/Koka/letter-frequency.koka @@ -0,0 +1,20 @@ +import std/os/file +import std/os/path + +fun main() + val counts = count(read-text-file("input.txt".path).list) + counts.foreach fn((c, i)) + println(c.show-char ++ " = " ++ i.show) + println("Total letters = " ++ counts.map(snd).sum.show) + +fun add(freq: list<(char, int)>, c : char): list<(char, int)> + if c.is-alpha then + match freq + Nil -> [(c, 1)] + Cons((x, n), rest) -> + if x == c then Cons((x, n + 1), rest) + else Cons((x, n), add(rest, c)) + else freq + +fun count(text: list) + text.foldl([], add) diff --git a/Task/Letter-frequency/TAV/letter-frequency.tav b/Task/Letter-frequency/TAV/letter-frequency.tav new file mode 100644 index 0000000000..ebdabaf1a3 --- /dev/null +++ b/Task/Letter-frequency/TAV/letter-frequency.tav @@ -0,0 +1,11 @@ +main (parms):+ + text =: <'In olden times when wishing still helped one, + there lived a king whose daughters were all beautiful. + But the youngest was so beautiful that the sun itself, + which has seen so much, was astonished whenever it shone in her face.' + lc =: new map + ?# c =: string text give characters + ? string #ASCIIletters has character c + lc{c} =+ 1 + ?# k =: map lc give keys descending values + print k, lc{k} diff --git a/Task/Levenshtein-distance-Alignment/Ada/levenshtein-distance-alignment.ada b/Task/Levenshtein-distance-Alignment/Ada/levenshtein-distance-alignment.ada new file mode 100644 index 0000000000..dda6f2a6b2 --- /dev/null +++ b/Task/Levenshtein-distance-Alignment/Ada/levenshtein-distance-alignment.ada @@ -0,0 +1,88 @@ +with Ada.Assertions, + Ada.Text_IO; + +procedure Levenschtein_Alignment is + type Levenschtein_Array is array (Natural range <>, Natural range <>) of Natural; + + type Levenschtein_Matrix (S, T : Natural) is record + Source : String (1 .. S); + Target : String (1 .. T); + Matrix : Levenschtein_Array (0 .. S, 0 .. T); + end record; + + function Make (S, T : String) return Levenschtein_Matrix is + L : Levenschtein_Matrix (S'Length, T'Length); + begin + L.Source := S; + L.Target := T; + L.Matrix (0, 0) := 0; + + for I in S'Range loop + L.Matrix (I, 0) := I; + end loop; + + for I in T'Range loop + L.Matrix (0, I) := I; + end loop; + + return L; + end Make; + + Place_Palace : Levenschtein_Matrix := Make ("place", "palace"); + Rosettacode_Raisethysword : Levenschtein_Matrix := Make ("rosettacode", "raisethysword"); + + procedure Fill (L : in out Levenschtein_Matrix) is + Cost : Natural; + begin + for J in L.Target'Range loop + for I in L.Source'Range loop + if L.Source (I) = L.Target (J) then + Cost := 0; + else + Cost := 1; + end if; + + L.Matrix (I, J) := Natural'Min + (Cost + L.Matrix (I - 1, J - 1), -- Substitution + Natural'Min + (1 + L.Matrix (I - 1, J), -- Deletion + 1 + L.Matrix (I, J - 1))); -- Insertion + end loop; + end loop; + end Fill; + + -- For convenience, assume Source'Length <= Target'Length + procedure Show (L : Levenschtein_Matrix) is + Aligned_Source : String (1 .. L.Target'Length); + I : Natural := L.Source'Length; + J : Natural := L.Target'Length; + Min_Dist : Natural; + begin + Ada.Assertions.Assert (I <= J); + + for P in reverse 1 .. L.Target'Length loop + -- Deletion will not happen due to length assumption + Min_Dist := Natural'Min (L.Matrix (I, J - 1), L.Matrix (I - 1, J - 1)); + + if Min_Dist = L.Matrix (I - 1, J - 1) then + -- Substitution. Fill in source character + Aligned_Source (P) := L.Source (I); + I := I - 1; + J := J - 1; + elsif Min_Dist = L.Matrix (I, J - 1) then + -- Insertion. Fill in a wildcard + Aligned_Source (P) := '-'; + J := J - 1; + end if; + end loop; + + Ada.Text_IO.Put_Line (Aligned_Source); + Ada.Text_IO.Put_Line (L.Target); + end Show; +begin + Fill (Place_Palace); + Show (Place_Palace); + + Fill (Rosettacode_Raisethysword); + Show (Rosettacode_Raisethysword); +end Levenschtein_Alignment; diff --git a/Task/Levenshtein-distance/DuckDB/levenshtein-distance.duckdb b/Task/Levenshtein-distance/DuckDB/levenshtein-distance.duckdb new file mode 100644 index 0000000000..bd62d17fa2 --- /dev/null +++ b/Task/Levenshtein-distance/DuckDB/levenshtein-distance.duckdb @@ -0,0 +1,5 @@ +select s1, s2, levenshtein(s1,s2), damerau_levenshtein(s1,s2) +from values + ('kitten', 'sitting'), + ('sitting', 'sittnig'), + ('rosettacode', 'raisethysword') _(s1,s2); diff --git a/Task/Levenshtein-distance/Pascal-P/levenshtein-distance.pas b/Task/Levenshtein-distance/Pascal-P/levenshtein-distance.pas new file mode 100644 index 0000000000..e953320a34 --- /dev/null +++ b/Task/Levenshtein-distance/Pascal-P/levenshtein-distance.pas @@ -0,0 +1,81 @@ +program levdistdemo(output); + +const + maxlen = 15; + +type + stringalpha = array [1 .. maxlen] of char; + + function min3(a, b, c: integer): integer; + var + min: integer; + begin + min := a; + if b < min then + min := b; + if c < min then + min := c; + min3 := min; + end; + + function levdist(s: stringalpha; m: integer; + t: stringalpha; n: integer): integer; + var + d: array [0 .. maxlen, 0 .. maxlen] of integer; + i, j: integer; + begin + for i := 0 to m do + d[i, 0] := i; + for j := 0 to n do + d[0, j] := j; + for j := 1 to n do + for i := 1 to m do + if s[i] = t[j] then + d[i, j] := d[i - 1, j - 1] + else + d[i, j] := min3(d[i - 1, j] + 1, d[i, j - 1] + 1, + d[i - 1, j - 1] + 1); + levdist := d[m, n]; + end; + + procedure writeresults(s1, s2: stringalpha); + var + n1, n2: integer; + + function purelen(s: stringalpha): integer; + (* Returns length of s without trailing spaces *) + var + i: integer; + begin + i := maxlen; + while (i > 0) and (s[i] = ' ') do + i := i - 1; + purelen := i; + end; + + procedure writenchars(s: stringalpha; n: integer); + var + i: integer; + begin + for i := 1 to n do + write(s[i]); + end; + + begin + n1 := purelen(s1); + n2 := purelen(s2); + write('The Levenshtein distance between "'); + writenchars(s1, n1); + write('" and "'); + writenchars(s2, n2); + (* Here the levdist function is called. *) + writeln('" is: ', levdist(s1, n1, s2, n2): 1); + end; + +begin + (* In string assignment, a string literal must have the same size + as a string variable. So trailing spaces are needed, but they are not + considered in calculating a distance. *) + writeresults('kitten ', 'sitting '); + writeresults('rosettacode ', 'raisethysword '); +end. diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb new file mode 100644 index 0000000000..4c713a0e9f --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-1.duckdb @@ -0,0 +1,7 @@ +# for x in 1 to n, for y in x+1 to n, for z in y+1 to n +create or replace function xyz(n) as table ( + from range(1,n+1) x(x) + cross join (from range(x+1,n+1) y(y)) + cross join (from range(y+1, n+1) z(z)) + +); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb new file mode 100644 index 0000000000..0826ceeb56 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-2.duckdb @@ -0,0 +1,6 @@ +create or replace function triples(n) as table ( + from xyz(n) + where x*x + y*y = z*z +); + +from triples(10); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb new file mode 100644 index 0000000000..a613ad7de4 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-3.duckdb @@ -0,0 +1,4 @@ +create or replace function list_triples(n) as ( + [ xyz FOR xyz IN (select array_agg([x,y,z] order by x) FROM xyz(n)) + IF xyz[1]**2 + xyz[2]**2 = xyz[3]**2 ] +); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb new file mode 100644 index 0000000000..3a9d0eebd0 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-4.duckdb @@ -0,0 +1,5 @@ +create or replace function list_triples(n) as ( + list_filter( + (select array_agg([x,y,z] order by x) from xyz(n)), + x -> x[1]*x[1] + x[2]*x[2] = x[3]*x[3] ) +); diff --git a/Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb b/Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb new file mode 100644 index 0000000000..57c2588f30 --- /dev/null +++ b/Task/List-comprehensions/DuckDB/list-comprehensions-5.duckdb @@ -0,0 +1 @@ +select list_triples(10); diff --git a/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas b/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas index 3c888aa14f..c3820b8e57 100644 --- a/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas +++ b/Task/List-comprehensions/PascalABC.NET/list-comprehensions.pas @@ -1,2 +1,2 @@ ## -(1..20).CartesianPower(3).Where(\(x,y,z) -> (x*x + y*y = z*z) and (x < y)).PrintLines +(1..20).CartesianPower(3).Where(\(x,y,z) -> (x*x + y*y = z*z) and (x < y)).tolist.PrintLines diff --git a/Task/Literals-Floating-point/ArkScript/literals-floating-point.ark b/Task/Literals-Floating-point/ArkScript/literals-floating-point.ark new file mode 100644 index 0000000000..3e7cfb3852 --- /dev/null +++ b/Task/Literals-Floating-point/ArkScript/literals-floating-point.ark @@ -0,0 +1,3 @@ +(print 2.3) +(print 0.34e5) +(print (/ 23 10)) diff --git a/Task/Literals-Floating-point/Pluto/literals-floating-point.pluto b/Task/Literals-Floating-point/Pluto/literals-floating-point.pluto new file mode 100644 index 0000000000..7a673dcb9b --- /dev/null +++ b/Task/Literals-Floating-point/Pluto/literals-floating-point.pluto @@ -0,0 +1,4 @@ +local fs = {123.456, .456, 1e5, 2.5e-1, 0xap4, 0x1.ffp10} +for fs as f do + print(f) +end diff --git a/Task/Literals-Floating-point/REXX/literals-floating-point.rexx b/Task/Literals-Floating-point/REXX/literals-floating-point.rexx index df07d9fa3e..bc554a2caf 100644 --- a/Task/Literals-Floating-point/REXX/literals-floating-point.rexx +++ b/Task/Literals-Floating-point/REXX/literals-floating-point.rexx @@ -1,4 +1,4 @@ --- 19 May 2025 +-- 28 Jul 2025 include Settings say 'LITERALS FLOATING POINT' @@ -47,6 +47,4 @@ say Left('Scientific',l) '=' Sci(a) say Left('Engineering',l) '=' Eng(a) exit -include Functions -include Helper -include Abend +include Math diff --git a/Task/Literals-Integer/ArkScript/literals-integer.ark b/Task/Literals-Integer/ArkScript/literals-integer.ark new file mode 100644 index 0000000000..25dfb48096 --- /dev/null +++ b/Task/Literals-Integer/ArkScript/literals-integer.ark @@ -0,0 +1,4 @@ +(print 1) +(print 1e10) +(print 3E8) +(print 5e-3) diff --git a/Task/Literals-Integer/DuckDB/literals-integer.duckdb b/Task/Literals-Integer/DuckDB/literals-integer.duckdb new file mode 100644 index 0000000000..6954f438cb --- /dev/null +++ b/Task/Literals-Integer/DuckDB/literals-integer.duckdb @@ -0,0 +1 @@ +select '10000'::BIT::INT; #=> 16 diff --git a/Task/Literals-Integer/Pluto/literals-integer.pluto b/Task/Literals-Integer/Pluto/literals-integer.pluto new file mode 100644 index 0000000000..529f724d4b --- /dev/null +++ b/Task/Literals-Integer/Pluto/literals-integer.pluto @@ -0,0 +1,4 @@ +local n = {255, 0xff, 0o377, 0b11111111} +for n as i do + print(i) +end diff --git a/Task/Literals-String/ArkScript/literals-string.ark b/Task/Literals-String/ArkScript/literals-string.ark new file mode 100644 index 0000000000..3db1fb974a --- /dev/null +++ b/Task/Literals-String/ArkScript/literals-string.ark @@ -0,0 +1,4 @@ +(print "hello") +(print "hello\nworld") +(print "test\ttab") +(print "\u1234") diff --git a/Task/Logical-operations/ArkScript/logical-operations.ark b/Task/Logical-operations/ArkScript/logical-operations.ark new file mode 100644 index 0000000000..2bf1695df2 --- /dev/null +++ b/Task/Logical-operations/ArkScript/logical-operations.ark @@ -0,0 +1,9 @@ +(let logic (fun (a b) { + (print "a and b: " (and a b)) + (print "a or b:" (or a b)) + (print "not a: " (not a)) })) + +(logic true true) +(logic true false) +(logic false true) +(logic false false) diff --git a/Task/Logical-operations/DuckDB/logical-operations.duckdb b/Task/Logical-operations/DuckDB/logical-operations.duckdb new file mode 100644 index 0000000000..d4427a5b9b --- /dev/null +++ b/Task/Logical-operations/DuckDB/logical-operations.duckdb @@ -0,0 +1,22 @@ +create or replace function demo(p, q) as table ( + select p as p, + q as q, + p and q as and, + p or q as or, + not p as "NOT p", + (p is TRUE) as "p is TRUE", + (p is NULL) as "p is NULL" +); + +# Some examples +from demo(0, 0) +union all +from demo(0, 1) +union all +from demo(true, true) +union all +from demo(0, null) +union all +from demo(1, null) +union all +from demo(null, null); diff --git a/Task/Logical-operations/Red/logical-operations.red b/Task/Logical-operations/Red/logical-operations.red new file mode 100644 index 0000000000..a2dd549ded --- /dev/null +++ b/Task/Logical-operations/Red/logical-operations.red @@ -0,0 +1,14 @@ +Red [ "Logical Operations - Hinjo, 23 July 2025" ] + +test: func [a b] [ + foreach op [and or xor not] [ + either op = 'not + [ print [op a "==>" do compose [(op) a]] ] + [ print [a op b "==>" do compose [a (op) b]] ] + ] print "" +] + +test true true +test true false +test false true +test false false diff --git a/Task/Long-literals-with-continuations/Ada/long-literals-with-continuations.ada b/Task/Long-literals-with-continuations/Ada/long-literals-with-continuations.ada new file mode 100644 index 0000000000..8168637dca --- /dev/null +++ b/Task/Long-literals-with-continuations/Ada/long-literals-with-continuations.ada @@ -0,0 +1,34 @@ +with Ada.Characters.Latin_1; +with Ada.Strings; +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Long_Literal is + -- & is the concatenation operator + Elements : constant String := + "hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine " & + "neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon " & + "potassium calcium scandium titanium vanadium chromium manganese iron " & + "cobalt nickel copper zinc gallium germanium arsenic selenium bromine " & + "krypton rubidium strontium yttrium zirconium niobium molybdenum " & + "technetium ruthenium rhodium palladium silver cadmium indium tin " & + "antimony tellurium iodine xenon cesium barium lanthanum cerium " & + "praseodymium neodymium promethium samarium europium gadolinium terbium " & + "dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum " & + "tungsten rhenium osmium iridium platinum gold mercury thallium lead " & + "bismuth polonium astatine radon francium radium actinium thorium " & + "protactinium uranium neptunium plutonium americium curium berkelium " & + "californium einsteinium fermium mendelevium nobelium lawrencium " & + "rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium " & + "roentgenium copernicium nihonium flerovium moscovium livermorium " & + "tennessine oganesson"; + Revision : constant String := "2025-08-02"; + Count : constant Natural := Ada.Strings.Fixed.Count (Elements, " ") + 1; + Last_Element : constant Natural := + Ada.Strings.Fixed.Index (Elements, " ", Ada.Strings.Backward) + 1; +begin + Ada.Text_IO.Put_Line ("Last Revision Date: " & Revision); + Ada.Text_IO.Put_Line ("Number of Elements: " & Count'Image); + Ada.Text_IO.Put_Line + ("Last Element: " & Elements (Last_Element .. Elements'Last)); +end Long_Literal; diff --git a/Task/Long-multiplication/F-Sharp/long-multiplication.fs b/Task/Long-multiplication/F-Sharp/long-multiplication.fs deleted file mode 100644 index 8338a96cf4..0000000000 --- a/Task/Long-multiplication/F-Sharp/long-multiplication.fs +++ /dev/null @@ -1,3 +0,0 @@ -> let X = 2I ** 64 * 2I ** 64 ;; - -val X : System.Numerics.BigInteger = 340282366920938463463374607431768211456 diff --git a/Task/Long-primes/REXX/long-primes.rexx b/Task/Long-primes/REXX/long-primes.rexx index 4270b9f8ab..ca54ba894b 100644 --- a/Task/Long-primes/REXX/long-primes.rexx +++ b/Task/Long-primes/REXX/long-primes.rexx @@ -1,4 +1,4 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings say 'LONG PRIMES' @@ -24,7 +24,7 @@ say 'Long primes < 500' p = 0 do i = 1 to prim.0 until p > 500 p = prim.i - if p-qperiod(1 p) = 1 then + if p-PeriodQ(1 p) = 1 then call Charout ,p' ' end say @@ -42,15 +42,11 @@ do i = 1 to prim.0 while a > 0 say Right(a,5) Right(n,4) w = w+1; a = Word(t,w) end - if p-qperiodinv(p) = 1 then do + if p-PeriodInvQ(p) = 1 then do n = n+1 end end say Format(Time('e'),,3) 'seconds'; say return -include Functions -include Sequences -include Rational -include Constants -include Abend +include Math diff --git a/Task/Longest-common-subsequence/ALGOL-68/longest-common-subsequence.alg b/Task/Longest-common-subsequence/ALGOL-68/longest-common-subsequence.alg index 54f29d5dd5..e02c0eccfa 100644 --- a/Task/Longest-common-subsequence/ALGOL-68/longest-common-subsequence.alg +++ b/Task/Longest-common-subsequence/ALGOL-68/longest-common-subsequence.alg @@ -1,15 +1,16 @@ -main:( - PROC lcs = (STRING a, b)STRING: - BEGIN - IF UPB a = 0 OR UPB b = 0 THEN - "" - ELIF a [UPB a] = b [UPB b] THEN - lcs (a [:UPB a - 1], b [:UPB b - 1]) + a [UPB a] - ELSE - STRING x = lcs (a, b [:UPB b - 1]); - STRING y = lcs (a [:UPB a - 1], b); - IF UPB x > UPB y THEN x ELSE y FI - FI - END # lcs #; - print((lcs ("thisisatest", "testing123testing"), new line)) -) +BEGIN PROC lcs = (STRING s, t) STRING: + IF LWB s > UPB s OR LWB t > UPB t + THEN # Trivial case: empty strings have an empty LCS. # + "" + ELIF s[UPB s] = t[UPB t] + THEN # If the last characters of 's' and 't' match, prepend the LCS of the preceeding strings # + lcs (s[: UPB s - 1], t[: UPB t - 1]) + s[UPB s] + ELSE # Find the longest LCS of these cases: + (1) excluding the last character of 's' including the last of 't', + (2) excluding the last character of 't' including the last of 's'. # + STRING u = lcs (s[: UPB s - 1], t), v = lcs (s, t[: UPB t - 1]); + (UPB u > UPB v | u | v) + FI; + + print((lcs ("thisisatest", "testing123testing"), new line)) +END diff --git a/Task/Longest-increasing-subsequence/Ada/longest-increasing-subsequence.ada b/Task/Longest-increasing-subsequence/Ada/longest-increasing-subsequence.ada new file mode 100644 index 0000000000..a7671eaf17 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Ada/longest-increasing-subsequence.ada @@ -0,0 +1,51 @@ +with Ada.Text_IO; + +procedure Longest_Increasing_Subsequence is + type Sequence is array (Positive range <>) of Integer; + + Seq1 : constant Sequence := + (3, 2, 6, 4, 5, 1); + Seq2 : constant Sequence := + (0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15); + + function Lis (Seq : Sequence) return Sequence is + Best : Sequence (Seq'Range) := (others => 1); + Pred : Sequence (Seq'Range) := (others => 0); + Best_Idx, Max_Len : Natural := 0; + begin + -- Calculate LIS length for every end point + for I in Seq'Range loop + for J in 1 .. I - 1 loop + if Seq (J) < Seq (I) and then + Best (I) < 1 + Best (J) then + Best (I) := 1 + Best (J); + Pred (I) := J; + end if; + end loop; + end loop; + + -- Find tail of global LIS + for I in Best'Range loop + if Best (I) > Max_Len then + Best_Idx := I; + Max_Len := Best (I); + end if; + end loop; + + -- Trace sequence + declare + Lis : Sequence (1 .. Max_Len); + begin + for I in reverse 1 .. Max_Len loop + Lis (I) := Seq (Best_Idx); + Best_Idx := Pred (Best_Idx); + end loop; + + return Lis; + end; + end Lis; + +begin + Ada.Text_IO.Put_Line (Lis (Seq1)'Image); + Ada.Text_IO.Put_Line (Lis (Seq2)'Image); +end Longest_Increasing_Subsequence; diff --git a/Task/Longest-increasing-subsequence/DuckDB/longest-increasing-subsequence.duckdb b/Task/Longest-increasing-subsequence/DuckDB/longest-increasing-subsequence.duckdb new file mode 100644 index 0000000000..c869de0c5c --- /dev/null +++ b/Task/Longest-increasing-subsequence/DuckDB/longest-increasing-subsequence.duckdb @@ -0,0 +1,31 @@ +# Return a list - just one in the case of a tie +create or replace function longest_increasing_subsequence(lst) as ( + + -- Add a flag to signal the start of a new subsequence + with flagged as ( + select *, if(id = 1, 0, if(c > (lag(c) over ()), 0, 1)) as flag + from (select generate_subscripts(lst,1) as id, + unnest(lst) as c) + ), + partitions as ( + select *, sum(flag) over (order by id) as partition_number + from (select *, if(id=1 or (c > (lag(c) over ())), 1, 0) as flag + from flagged) + order by id asc + ), + subseq_number as ( + select max_by(partition_number, ncount) as n + from (select partition_number, count(*) as ncount + from partitions + group by partition_number) + ) + select array_agg(c order by id) + from partitions, subseq_number + where partition_number = subseq_number.n +); + +# Examples; +select l as list, longest_increasing_subsequence(l) as lis + from (select [3,2,6,4,5,1] as l union all + select [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15] as l union all + select [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15,20] as l); diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Pluto/loop-over-multiple-arrays-simultaneously.pluto b/Task/Loop-over-multiple-arrays-simultaneously/Pluto/loop-over-multiple-arrays-simultaneously.pluto new file mode 100644 index 0000000000..2a7349438d --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Pluto/loop-over-multiple-arrays-simultaneously.pluto @@ -0,0 +1,6 @@ +a = {'a','b','c'} +b = {'A','B','C'} +c = {1,2,3} +for i = 1,#c do + io.write(a[i],b[i],c[i],'\n') +end diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REBOL/loop-over-multiple-arrays-simultaneously.rebol b/Task/Loop-over-multiple-arrays-simultaneously/REBOL/loop-over-multiple-arrays-simultaneously.rebol new file mode 100644 index 0000000000..e7bf28c8d3 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/REBOL/loop-over-multiple-arrays-simultaneously.rebol @@ -0,0 +1,10 @@ +;; Define the three series +list1: [a b c] +list2: [A B C] +list3: [1 2 3] + +;; Iterate over them in parallel by index +repeat i length? list1 [ + ;; pick returns the i-th element + print rejoin [list1/:i list2/:i list3/:i] +] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TAV/loop-over-multiple-arrays-simultaneously.tav b/Task/Loop-over-multiple-arrays-simultaneously/TAV/loop-over-multiple-arrays-simultaneously.tav new file mode 100644 index 0000000000..510e266d29 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/TAV/loop-over-multiple-arrays-simultaneously.tav @@ -0,0 +1,15 @@ + x =: 1, 2, 3, 4 + y =: 'a', 'b', 'c' + \ create z as row with keys from -1 to 3 + z =: new row + ?# i =: from -1 upto 3 + z[i] =: i+4 + + ?# i =: tuple x give keys + print i, x[i], y[i], z[i] + print '' + ?# i =: row z give keys + print i, x[i], y[i], z[i] + print '' + ?# i =: from 0 upto 4 + print i, x[i], y[i], z[i] diff --git a/Task/Loops-Break/DuckDB/loops-break.duckdb b/Task/Loops-Break/DuckDB/loops-break.duckdb new file mode 100644 index 0000000000..f0b5da4293 --- /dev/null +++ b/Task/Loops-Break/DuckDB/loops-break.duckdb @@ -0,0 +1,22 @@ +# PRN in range(0,n) +create or replace function prn(n) as trunc(random() * n)::BIGINT; + +# Print numbers in range(0,n) as per the task description +create or replace function task(n) as table ( + with recursive cte as ( + select prn(n) as rand, false as stop + union all + select + prn(n) as rand, + rand = 10 as stop + from cte + where stop != true + ) select rand + from cte + where stop = false +); + +.print A sample run: +from task(20); +.print A likely shorter one: +from task(11); diff --git a/Task/Loops-Break/Koka/loops-break.koka b/Task/Loops-Break/Koka/loops-break.koka new file mode 100644 index 0000000000..c4cef92515 --- /dev/null +++ b/Task/Loops-Break/Koka/loops-break.koka @@ -0,0 +1,12 @@ +import std/num/random + +effect ebreak + final ctl ebreak(): a + +fun main() + with final ctl ebreak() () + while {True} + val a = random-int() % 20 + println(a) + if a == 10 then ebreak() + println(random-int() % 20) diff --git a/Task/Loops-Break/Pluto/loops-break.pluto b/Task/Loops-Break/Pluto/loops-break.pluto new file mode 100644 index 0000000000..05fcf3c303 --- /dev/null +++ b/Task/Loops-Break/Pluto/loops-break.pluto @@ -0,0 +1,6 @@ +while true do + local r = math.random(0, 19) + print(r) + if r == 10 then break end + print(math.random(0, 19)) +end diff --git a/Task/Loops-Break/TAV/loops-break-1.tav b/Task/Loops-Break/TAV/loops-break-1.tav new file mode 100644 index 0000000000..e154b5106a --- /dev/null +++ b/Task/Loops-Break/TAV/loops-break-1.tav @@ -0,0 +1,7 @@ + ?* \ if no expression, forever + a =: random next integer %% 20 + print a + ? a = 10 + print random next integer %% 20 + ?> \ exit loop + print random next integer %% 20 diff --git a/Task/Loops-Break/TAV/loops-break-2.tav b/Task/Loops-Break/TAV/loops-break-2.tav new file mode 100644 index 0000000000..3f9e08991b --- /dev/null +++ b/Task/Loops-Break/TAV/loops-break-2.tav @@ -0,0 +1,7 @@ + while true + a = random next integer %% 20 + print a + if a == 10 + print random next integer %% 20 + break + print random next integer %% 20 diff --git a/Task/Loops-Break/Ursalang/loops-break.ursa b/Task/Loops-Break/Ursalang/loops-break.ursa new file mode 100644 index 0000000000..6773c478e8 --- /dev/null +++ b/Task/Loops-Break/Ursalang/loops-break.ursa @@ -0,0 +1,12 @@ +use js.Math + +let f = fn() { + Math.floor(Math.random() * 20) +} + +loop { + let n = f() + print(n) + if n == 10 { break } + print(f()) +} diff --git a/Task/Loops-Break/Zig/loops-break.zig b/Task/Loops-Break/Zig/loops-break-1.zig similarity index 100% rename from Task/Loops-Break/Zig/loops-break.zig rename to Task/Loops-Break/Zig/loops-break-1.zig diff --git a/Task/Loops-Break/Zig/loops-break-2.zig b/Task/Loops-Break/Zig/loops-break-2.zig new file mode 100644 index 0000000000..7329c1b27f --- /dev/null +++ b/Task/Loops-Break/Zig/loops-break-2.zig @@ -0,0 +1,25 @@ +const std = @import("std"); + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var prng = std.Random.DefaultPrng.init(blk: { + var seed: u64 = undefined; + try std.posix.getrandom(std.mem.asBytes(&seed)); + break :blk seed; + }); + const rand = prng.random(); + + while (true) { + const n1 = rand.intRangeAtMost(u8, 0, 19); + try stdout.print("{d:2} ", .{n1}); + + if (n1 == 10) { + break; + } + + const n2 = rand.intRangeAtMost(u8, 0, 19); + try stdout.print("{d:2}\n", .{n2}); + } + + try stdout.print("\n", .{}); +} diff --git a/Task/Loops-Continue/Pluto/loops-continue.pluto b/Task/Loops-Continue/Pluto/loops-continue.pluto new file mode 100644 index 0000000000..5b1e49dc47 --- /dev/null +++ b/Task/Loops-Continue/Pluto/loops-continue.pluto @@ -0,0 +1,8 @@ +for i = 1, 10 do + io.write(i) + if i % 5 == 0 then + print() + continue + end + io.write(", ") +end diff --git a/Task/Loops-Continue/REBOL/loops-continue.rebol b/Task/Loops-Continue/REBOL/loops-continue-1.rebol similarity index 84% rename from Task/Loops-Continue/REBOL/loops-continue.rebol rename to Task/Loops-Continue/REBOL/loops-continue-1.rebol index 216f116666..6b2e1988ba 100644 --- a/Task/Loops-Continue/REBOL/loops-continue.rebol +++ b/Task/Loops-Continue/REBOL/loops-continue-1.rebol @@ -3,7 +3,7 @@ REBOL [ URL: http://rosettacode.org/wiki/Loop/Continue ] -; REBOL does not provide a 'continue' word for loop constructs, +; REBOL2 does not provide a 'continue' word for loop constructs, ; however, you may not even miss it: print "One liner (compare to ALGOL 68 solution):" diff --git a/Task/Loops-Continue/REBOL/loops-continue-2.rebol b/Task/Loops-Continue/REBOL/loops-continue-2.rebol new file mode 100644 index 0000000000..bd9550c2ae --- /dev/null +++ b/Task/Loops-Continue/REBOL/loops-continue-2.rebol @@ -0,0 +1,8 @@ +repeat i 10 [ + prin i + if zero? i % 5 [ + prin newline + continue + ] + prin ", " +] diff --git a/Task/Loops-Do-while/DuckDB/loops-do-while.duckdb b/Task/Loops-Do-while/DuckDB/loops-do-while.duckdb new file mode 100644 index 0000000000..4dca729023 --- /dev/null +++ b/Task/Loops-Do-while/DuckDB/loops-do-while.duckdb @@ -0,0 +1,16 @@ +create or replace function do_while(init) as table ( + with recursive cte as ( + select init+1 as value -- Increment unconditionally + union all -- Loop + select value+1 as value -- Each time through the loop, add 1 to the value then print it. + from cte + where value % 6 != 0 -- "while value mod 6 is not equal to 0" + ) + from cte order by value +); + +# The task +from do_while(0); + +# Also check that the loop executes at least once. +from do_while(-1); diff --git a/Task/Loops-Do-while/Pluto/loops-do-while.pluto b/Task/Loops-Do-while/Pluto/loops-do-while.pluto new file mode 100644 index 0000000000..c5add00378 --- /dev/null +++ b/Task/Loops-Do-while/Pluto/loops-do-while.pluto @@ -0,0 +1,4 @@ +local value = 0 +repeat + print(++value) +until value % 6 == 0 diff --git a/Task/Loops-Do-while/TAV/loops-do-while-1.tav b/Task/Loops-Do-while/TAV/loops-do-while-1.tav new file mode 100644 index 0000000000..179cf892cc --- /dev/null +++ b/Task/Loops-Do-while/TAV/loops-do-while-1.tav @@ -0,0 +1,6 @@ + x =: 0 + ?* \ loop forever + x =+ 1 \ increment x + print x + ? x %% 6 = 0 \ until + ?> \ break diff --git a/Task/Loops-Do-while/TAV/loops-do-while-2.tav b/Task/Loops-Do-while/TAV/loops-do-while-2.tav new file mode 100644 index 0000000000..b06e7e33d3 --- /dev/null +++ b/Task/Loops-Do-while/TAV/loops-do-while-2.tav @@ -0,0 +1,6 @@ + x = 0 + while \ loop forever + x += 1 \ increment x + print x + if x %% 6 == 0 \ until + break diff --git a/Task/Loops-Downward-for/DuckDB/loops-downward-for-1.duckdb b/Task/Loops-Downward-for/DuckDB/loops-downward-for-1.duckdb new file mode 100644 index 0000000000..00a3c805b0 --- /dev/null +++ b/Task/Loops-Downward-for/DuckDB/loops-downward-for-1.duckdb @@ -0,0 +1 @@ +from range(10, -1, -1) t(countdown); diff --git a/Task/Loops-Downward-for/DuckDB/loops-downward-for-2.duckdb b/Task/Loops-Downward-for/DuckDB/loops-downward-for-2.duckdb new file mode 100644 index 0000000000..81cdd9a336 --- /dev/null +++ b/Task/Loops-Downward-for/DuckDB/loops-downward-for-2.duckdb @@ -0,0 +1,14 @@ +# Start at `start` +create or replace function task(start) as table ( + with recursive cte as ( + select start as n + union all + select + n - 1 as n + from cte + where n > 0 + ) + from cte +); + +from task(10); diff --git a/Task/Loops-Downward-for/Pluto/loops-downward-for.pluto b/Task/Loops-Downward-for/Pluto/loops-downward-for.pluto new file mode 100644 index 0000000000..ff0f196ea1 --- /dev/null +++ b/Task/Loops-Downward-for/Pluto/loops-downward-for.pluto @@ -0,0 +1,2 @@ +for i = 10, 0, -1 do io.write($"{i} ") end +print() diff --git a/Task/Loops-Downward-for/TAV/loops-downward-for.tav b/Task/Loops-Downward-for/TAV/loops-downward-for.tav new file mode 100644 index 0000000000..f91afc487c --- /dev/null +++ b/Task/Loops-Downward-for/TAV/loops-downward-for.tav @@ -0,0 +1,6 @@ + ?# i =: from 10 downto 0 + print i + ?# i =: from 20 downto 0 step 2 + print i // 2 + ?# i =: give numbers 10 -> 0 + print i diff --git a/Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-1.duckdb b/Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-1.duckdb new file mode 100644 index 0000000000..449cd50675 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-1.duckdb @@ -0,0 +1,3 @@ +.header off +.mode column +select format('whom do we appreciate? {:d}', i) from range(2, 10, 2) _(i); diff --git a/Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-2.duckdb b/Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-2.duckdb new file mode 100644 index 0000000000..a1e45134ef --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/DuckDB/loops-for-with-a-specified-step-2.duckdb @@ -0,0 +1,8 @@ +with recursive cte as ( + select 2 as i + union all + select i+2 -- increment by 2 + from cte + where i < 8) + select format('whom do we appreciate? {:d}', i) + from cte; diff --git a/Task/Loops-For-with-a-specified-step/Pluto/loops-for-with-a-specified-step.pluto b/Task/Loops-For-with-a-specified-step/Pluto/loops-for-with-a-specified-step.pluto new file mode 100644 index 0000000000..3200bb4031 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Pluto/loops-for-with-a-specified-step.pluto @@ -0,0 +1,2 @@ +for i = 1, 9, 2 do io.write($"{i} ") end +print() diff --git a/Task/Loops-For-with-a-specified-step/REBOL/loops-for-with-a-specified-step.rebol b/Task/Loops-For-with-a-specified-step/REBOL/loops-for-with-a-specified-step.rebol index 6b7d5b612f..f3a7cc653d 100644 --- a/Task/Loops-For-with-a-specified-step/REBOL/loops-for-with-a-specified-step.rebol +++ b/Task/Loops-For-with-a-specified-step/REBOL/loops-for-with-a-specified-step.rebol @@ -1,3 +1,2 @@ -for i 2 8 2 [ - prin rejoin [i ", "]] +for i 2 8 2 [prin join i ", "] print "who do we appreciate?" diff --git a/Task/Loops-For/Adina/loops-for-1.adina b/Task/Loops-For/Adina/loops-for-1.adina new file mode 100644 index 0000000000..dbbbfaca27 --- /dev/null +++ b/Task/Loops-For/Adina/loops-for-1.adina @@ -0,0 +1,6 @@ +цикл + номер-строки 5 + цикл + номер-колонки номер-строки + вывести «*» + вывести/перенос «*» diff --git a/Task/Loops-For/Adina/loops-for-2.adina b/Task/Loops-For/Adina/loops-for-2.adina new file mode 100644 index 0000000000..39c3639f3c --- /dev/null +++ b/Task/Loops-For/Adina/loops-for-2.adina @@ -0,0 +1,7 @@ +english() +for + $ i 5 + for + $ j i + display "*" + displayln "*" diff --git a/Task/Loops-For/DuckDB/loops-for-1.duckdb b/Task/Loops-For/DuckDB/loops-for-1.duckdb new file mode 100644 index 0000000000..95918267f7 --- /dev/null +++ b/Task/Loops-For/DuckDB/loops-for-1.duckdb @@ -0,0 +1,3 @@ +select list_transform(range(1,6), + i -> list_transform(range(1,i+1), + j -> '*').array_to_string('')) as stars; diff --git a/Task/Loops-For/DuckDB/loops-for-2.duckdb b/Task/Loops-For/DuckDB/loops-for-2.duckdb new file mode 100644 index 0000000000..e8935f320d --- /dev/null +++ b/Task/Loops-For/DuckDB/loops-for-2.duckdb @@ -0,0 +1,3 @@ +select (select string_agg('*', '') from range(1,i+1)) +from range(1,6) _(i) +order by i; diff --git a/Task/Loops-For/DuckDB/loops-for-3.duckdb b/Task/Loops-For/DuckDB/loops-for-3.duckdb new file mode 100644 index 0000000000..c402439422 --- /dev/null +++ b/Task/Loops-For/DuckDB/loops-for-3.duckdb @@ -0,0 +1,3 @@ +select (select string_agg(j, ',' order by j) from range(1,i+1) _(j)) +from range(1,6) _(i) +order by i; diff --git a/Task/Loops-For/Eiffel/loops-for.e b/Task/Loops-For/Eiffel/loops-for.e new file mode 100644 index 0000000000..a0eacbbcd5 --- /dev/null +++ b/Task/Loops-For/Eiffel/loops-for.e @@ -0,0 +1,17 @@ +class APPLICATION +create make +feature + make local + i, j: INTEGER + do from i := 1 + until i > 5 loop + from j := 1 + until j > i loop + print("*") + j := j + 1 + end + print("%N") + i := i + 1 + end + end +end diff --git a/Task/Loops-For/Extended-Color-BASIC/loops-for.basic b/Task/Loops-For/Extended-Color-BASIC/loops-for.basic new file mode 100644 index 0000000000..9e65d215a2 --- /dev/null +++ b/Task/Loops-For/Extended-Color-BASIC/loops-for.basic @@ -0,0 +1,6 @@ +10 FOR I = 1 TO 5 +20 FOR J = 1 TO I +30 PRINT "*"; +40 NEXT J +50 PRINT +60 NEXT I diff --git a/Task/Loops-For/Pluto/loops-for.pluto b/Task/Loops-For/Pluto/loops-for.pluto new file mode 100644 index 0000000000..1d0903c980 --- /dev/null +++ b/Task/Loops-For/Pluto/loops-for.pluto @@ -0,0 +1,4 @@ +for i = 1, 5 do + for _ = 1, i do io.write("*") end + print() +end diff --git a/Task/Loops-For/TAV/loops-for-1.tav b/Task/Loops-For/TAV/loops-for-1.tav new file mode 100644 index 0000000000..ef92582c88 --- /dev/null +++ b/Task/Loops-For/TAV/loops-for-1.tav @@ -0,0 +1,4 @@ + ?# i =: from 1 upto 5 + ?# j =: from 1 upto i + print '*' nonl + print '' diff --git a/Task/Loops-For/TAV/loops-for-2.tav b/Task/Loops-For/TAV/loops-for-2.tav new file mode 100644 index 0000000000..810edc9db7 --- /dev/null +++ b/Task/Loops-For/TAV/loops-for-2.tav @@ -0,0 +1,2 @@ + ?# i =: from 1 upto 5 + print string '*' times i diff --git a/Task/Loops-For/TAV/loops-for-3.tav b/Task/Loops-For/TAV/loops-for-3.tav new file mode 100644 index 0000000000..cedd6836f3 --- /dev/null +++ b/Task/Loops-For/TAV/loops-for-3.tav @@ -0,0 +1,4 @@ + ?# i =: from 0 upto 5 + ?# j =: from 1 upto i + print j nonl + print '' diff --git a/Task/Loops-Foreach/Pluto/loops-foreach.pluto b/Task/Loops-Foreach/Pluto/loops-foreach.pluto new file mode 100644 index 0000000000..66614dcf2c --- /dev/null +++ b/Task/Loops-Foreach/Pluto/loops-foreach.pluto @@ -0,0 +1,6 @@ +local languages = {"English", "French", "German", "Spanish"} +for languages as lang do print(lang) end +print() + +-- or alternatively: +languages:foreach(print) diff --git a/Task/Loops-Foreach/REBOL/loops-foreach.rebol b/Task/Loops-Foreach/REBOL/loops-foreach.rebol index 20666e1f96..3204f10127 100644 --- a/Task/Loops-Foreach/REBOL/loops-foreach.rebol +++ b/Task/Loops-Foreach/REBOL/loops-foreach.rebol @@ -3,11 +3,11 @@ REBOL [ URL: http://rosettacode.org/wiki/Loop/Foreach ] -x: [Sork Gun Blues Neds Thirst Fright Catur] +names: [Sork Gun Blues Neds Thirst Fright Catur] -foreach i x [prin rejoin [i "day "]] print "" +foreach name names [prin join name "day "] print "" -; REBOL also has the 'forall' construct, which provides the rest of +; Rebol also has the 'forall' construct, which provides the rest of ; the list from the current position. -forall x [prin rejoin [x/1 "day "]] print "" +forall names [prin join names/1 "day "] print "" diff --git a/Task/Loops-Increment-loop-index-within-loop-body/ARM-Assembly/loops-increment-loop-index-within-loop-body.arm b/Task/Loops-Increment-loop-index-within-loop-body/ARM-Assembly/loops-increment-loop-index-within-loop-body.arm index a6a9c71396..7048f58019 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/ARM-Assembly/loops-increment-loop-index-within-loop-body.arm +++ b/Task/Loops-Increment-loop-index-within-loop-body/ARM-Assembly/loops-increment-loop-index-within-loop-body.arm @@ -134,7 +134,7 @@ conversion10: /* division par 10 unsigned */ /***************************************************/ /* r0 dividende */ -/* r0 quotient */ +/* r0 quotient */ /* r1 remainder */ divisionpar10U: push {r2,r3,r4, lr} @@ -148,7 +148,7 @@ divisionpar10U: sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2,r3,r4,lr} bx lr @ leave function -iMagicNumber: .int 0xCCCCCCCD +iMagicNumber: .int 0xCCCCCCCD /***************************************************/ /* number is prime ? */ /***************************************************/ @@ -306,7 +306,7 @@ moduloPuR96: mov r1,r12 msr cpsr_f, #0 @ no error overflow zero -> flags 100: @ end function - pop {r2-r12,lr} @ restaur registers + pop {r2-r12,lr} @ restaur registers bx lr @ return /***************************************************/ /* multiplication 2 registers (64 bits) unsigned */ @@ -342,13 +342,13 @@ multiplicationR96U: msr cpsr_f, #0 @ no error overflow zero -> flags b 100f 99: @ display message overflow - ldr r0,iAdrszMessMultOver @ - bl affichageMess + ldr r0,iAdrszMessMultOver @ + bl affichageMess mov r0,#0 mov r1,#0 msr cpsr_f, #1<<29 @ maj flag carry à 1 et tous les autres à 0 100: @ end function - pop {r3-r8,lr} @ restaur registers + pop {r3-r8,lr} @ restaur registers bx lr @ return iAdrszMessMultOver: .int szMessMultOver /***************************************************/ @@ -425,7 +425,7 @@ divisionReg96DU: mov r2,r6 @ high bits quotient 100: @ end function - pop {r5-r10,lr} @ restaur registers + pop {r5-r10,lr} @ restaur registers bx lr @ return /***************************************************/ @@ -445,7 +445,7 @@ conversionRegDoubleU: strb r3,[r5,r4] @ store digit in area index r4 sub r4,r4,#1 @ decrement index cmp r0,#0 @ low bits quotient = zero ? - bne 1b @ no -> loop + bne 1b @ no -> loop cmp r1,#0 @ high bits quotient = zero ? bne 1b @ no -> loop @ spaces -> begin area @@ -456,7 +456,7 @@ conversionRegDoubleU: bge 2b @ and loop if > zéro 100: @ end fonction - pop {r0-r5,lr} @ restaur registers + pop {r0-r5,lr} @ restaur registers bx lr @ return /***************************************************/ /* division number 64 bits / number 32 bits */ diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Arturo/loops-increment-loop-index-within-loop-body.arturo b/Task/Loops-Increment-loop-index-within-loop-body/Arturo/loops-increment-loop-index-within-loop-body.arturo index d5fc676117..6ad7e18007 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/Arturo/loops-increment-loop-index-within-loop-body.arturo +++ b/Task/Loops-Increment-loop-index-within-loop-body/Arturo/loops-increment-loop-index-within-loop-body.arturo @@ -2,12 +2,12 @@ i: 42 n: 0 while [n<42][ - if? prime? i [ - n: n+1 - print ["n =" pad to :string n 2 pad to :string i 20] - i: i + i - ] - else [ - i: i + 1 - ] + if? prime? i [ + n: n+1 + print ["n =" pad to :string n 2 pad to :string i 20] + i: i + i + ] + else [ + i: i + 1 + ] ] diff --git a/Task/Loops-Increment-loop-index-within-loop-body/AutoHotkey/loops-increment-loop-index-within-loop-body.ahk b/Task/Loops-Increment-loop-index-within-loop-body/AutoHotkey/loops-increment-loop-index-within-loop-body.ahk index eae4048658..d3f1e50843 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/AutoHotkey/loops-increment-loop-index-within-loop-body.ahk +++ b/Task/Loops-Increment-loop-index-within-loop-body/AutoHotkey/loops-increment-loop-index-within-loop-body.ahk @@ -1,21 +1,21 @@ i:= 42, n:= 1, result := "" while (n<43){ - if isPrime(i) - result .= n ":`t" RegExReplace(i, "\B(?=(\d{3})+$)", ",") "`n", i*=2, n++ - else - i++ + if isPrime(i) + result .= n ":`t" RegExReplace(i, "\B(?=(\d{3})+$)", ",") "`n", i*=2, n++ + else + i++ } MsgBox, 262208, , % result return isPrime(num){ - if !Mod(num, 2) || !Mod(num, 3) - return false - lim := Sqrt(num), i := 5 - while (i i (isqrt n)) ; Break condition index exceeds its square root - (zerop (mod n i))) ; Break condition it is divisible - (not (zerop (mod n i)))))))) ; Returns not divisible, aka prime + (do* ((i 3 (incf i 2))) ; Initialize to 3 and increment by 2 on every loop + ((or (> i (isqrt n)) ; Break condition index exceeds its square root + (zerop (mod n i))) ; Break condition it is divisible + (not (zerop (mod n i)))))))) ; Returns not divisible, aka prime (do ((i 42) ; Initialize index to 42 (c 0)) ; Initialize count of primes to 0 ((= c 42)) ; Break condition when there are 42 primes (incf i) ; Increments index by unity (if (primep i)(progn (incf c) ; If prime increment count of primes - (format t "~&~5<~d~;->~>~20<~:d~>" c i) ; Display count of primes found and the prime - (incf i (decf i))))) ; Increment index to previous index plus the prime + (format t "~&~5<~d~;->~>~20<~:d~>" c i) ; Display count of primes found and the prime + (incf i (decf i))))) ; Increment index to previous index plus the prime diff --git a/Task/Loops-Increment-loop-index-within-loop-body/DuckDB/loops-increment-loop-index-within-loop-body.duckdb b/Task/Loops-Increment-loop-index-within-loop-body/DuckDB/loops-increment-loop-index-within-loop-body.duckdb new file mode 100644 index 0000000000..558cd86ad9 --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/DuckDB/loops-increment-loop-index-within-loop-body.duckdb @@ -0,0 +1,33 @@ +create or replace function primep(nnumber) as ( + select + case + when nnumber < 2 then false + when nnumber = 2 then true + else NOT exists + ( select * from + ( select (nnumber % anumber) as modNumber + from (select unnest(range(2, 1 + sqrt(nnumber)::BIGINT)) as anumber) + ) + where modNumber = 0 + ) + end +); + +create or replace function task(start, mx) as table ( + with recursive cte as ( + select start::HUGEINT as ix, primep(start) as primep0, 0::HUGEINT as n, + []::HUGEINT[] as display + union all + select if (primep0, ix+ix, ix+1) as ix, + if (primep0, primep(ix+ix), primep(ix+1)) as primep0, + if (primep0,1,0) + n as n, + if (primep0, [n+1, ix], []) as display + from cte + where n < mx + ) select display + from cte + where display != [] + limit mx +); + +from task(42, 42); diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon b/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon index 225a4cef48..8b7552410d 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon +++ b/Task/Loops-Increment-loop-index-within-loop-body/Icon/loops-increment-loop-index-within-loop-body.icon @@ -10,7 +10,7 @@ procedure main() write(right(n,2),": ",comma_string(i)) i +:= i } else - i +:= 1 + i +:= 1 } end diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Ksh/loops-increment-loop-index-within-loop-body.ksh b/Task/Loops-Increment-loop-index-within-loop-body/Ksh/loops-increment-loop-index-within-loop-body.ksh index b45d1ee715..6013a6b179 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/Ksh/loops-increment-loop-index-within-loop-body.ksh +++ b/Task/Loops-Increment-loop-index-within-loop-body/Ksh/loops-increment-loop-index-within-loop-body.ksh @@ -2,24 +2,24 @@ # Increment loop index within loop body -# # Variables: +# # Variables: # integer INDX_START=42 N_PRIMES=42 -# # Functions: +# # Functions: # -# # Function _isprime(n) return 1 for prime, 0 for not prime +# # Function _isprime(n) return 1 for prime, 0 for not prime # function _isprime { - typeset _n ; integer _n=$1 - typeset _i ; integer _i + typeset _n ; integer _n=$1 + typeset _i ; integer _i - (( _n < 2 )) && return 0 - for (( _i=2 ; _i*_i<=_n ; _i++ )); do - (( ! ( _n % _i ) )) && return 0 - done - return 1 + (( _n < 2 )) && return 0 + for (( _i=2 ; _i*_i<=_n ; _i++ )); do + (( ! ( _n % _i ) )) && return 0 + done + return 1 } ###### @@ -27,9 +27,9 @@ function _isprime { ###### integer i n=0 for ((i=INDX_START; n -n = 1 43 -n = 2 89 -n = 3 179 -n = 4 359 -n = 5 719 -n = 6 1439 -n = 7 2879 -n = 8 5779 -n = 9 11579 -n = 10 23159 -n = 11 46327 -n = 12 92657 -n = 13 185323 -n = 14 370661 -n = 15 741337 -n = 16 1482707 -n = 17 2965421 -n = 18 5930887 -n = 19 11861791 -n = 20 23723597 -n = 21 47447201 -n = 22 94894427 -n = 23 189788857 -n = 24 379577741 -n = 25 759155483 -n = 26 1518310967 -n = 27 3036621941 -n = 28 6073243889 -n = 29 12146487779 -n = 30 24292975649 -n = 31 48585951311 -n = 32 97171902629 -n = 33 194343805267 -n = 34 388687610539 -n = 35 777375221081 -n = 36 1554750442183 -n = 37 3109500884389 -n = 38 6219001768781 -n = 39 12438003537571 -n = 40 24876007075181 -n = 41 49752014150467 -n = 42 99504028301131 +n = 1 43 +n = 2 89 +n = 3 179 +n = 4 359 +n = 5 719 +n = 6 1439 +n = 7 2879 +n = 8 5779 +n = 9 11579 +n = 10 23159 +n = 11 46327 +n = 12 92657 +n = 13 185323 +n = 14 370661 +n = 15 741337 +n = 16 1482707 +n = 17 2965421 +n = 18 5930887 +n = 19 11861791 +n = 20 23723597 +n = 21 47447201 +n = 22 94894427 +n = 23 189788857 +n = 24 379577741 +n = 25 759155483 +n = 26 1518310967 +n = 27 3036621941 +n = 28 6073243889 +n = 29 12146487779 +n = 30 24292975649 +n = 31 48585951311 +n = 32 97171902629 +n = 33 194343805267 +n = 34 388687610539 +n = 35 777375221081 +n = 36 1554750442183 +n = 37 3109500884389 +n = 38 6219001768781 +n = 39 12438003537571 +n = 40 24876007075181 +n = 41 49752014150467 +n = 42 99504028301131 diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Maple/loops-increment-loop-index-within-loop-body.maple b/Task/Loops-Increment-loop-index-within-loop-body/Maple/loops-increment-loop-index-within-loop-body.maple index ef938b3df1..8b0bfa576f 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/Maple/loops-increment-loop-index-within-loop-body.maple +++ b/Task/Loops-Increment-loop-index-within-loop-body/Maple/loops-increment-loop-index-within-loop-body.maple @@ -1,10 +1,10 @@ i := 42: count := 0: while(count < 42) do - i := i+1: - if type(i,prime) then - count := count + 1: - printf("n=%-2d %19d\n", count,i): - i := 2*i -1: - end if: + i := i+1: + if type(i,prime) then + count := count + 1: + printf("n=%-2d %19d\n", count,i): + i := 2*i -1: + end if: end do: diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Pluto/loops-increment-loop-index-within-loop-body.pluto b/Task/Loops-Increment-loop-index-within-loop-body/Pluto/loops-increment-loop-index-within-loop-body.pluto new file mode 100644 index 0000000000..8ba1995dff --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/Pluto/loops-increment-loop-index-within-loop-body.pluto @@ -0,0 +1,27 @@ +local function is_prime(n) + assert(n % 1 == 0, "Argument must be an integer.") + if n < 2 then return false end + if n % 2 == 0 then return n == 2 end + if n % 3 == 0 then return n == 3 end + local d = 5 + while d * d <= n do + if n % d == 0 then return false end + d += 2 + if n % d == 0 then return false end + d += 4 + end + return true +end + +local count = 0 +local i = 42 +while count < 42 do + if is_prime(i) then + ++count + local str1 = string.format("%2d", count) + local str2 = string.format("%18s", string.formatint(i)) + print($"{str1}: {str2}") + i = 2 * i - 1 + end + ++i +end diff --git a/Task/Loops-Increment-loop-index-within-loop-body/REBOL/loops-increment-loop-index-within-loop-body.rebol b/Task/Loops-Increment-loop-index-within-loop-body/REBOL/loops-increment-loop-index-within-loop-body.rebol new file mode 100644 index 0000000000..672a4090cb --- /dev/null +++ b/Task/Loops-Increment-loop-index-within-loop-body/REBOL/loops-increment-loop-index-within-loop-body.rebol @@ -0,0 +1,50 @@ +Rebol [ + title: "Rosetta code: Increment loop index within loop body" + file: %Increment_loop_index_within_loop_body.r3 + url: https://rosettacode.org/wiki/Increment_loop_index_within_loop_body + needs: 3.0.0 +] + +;; prime? native function is available since 3.19.5 +if unset? 'prime? [ + ;; Naive Rebol implementation + prime?: function [n [integer!]] [ + if n < 2 [return false] + if zero? n % 2 [return n == 2] + if zero? n % 3 [return n == 3] + d: 5 + while [d * d <= n][ + if zero? n % d [return false] + d: d + 2 + if zero? n % d [return false] + d: d + 4 + ] + true + ] +] + +;; Helper to format number with commas +format-commas: function [num [integer!]] [ + str: reverse form num + while [not tail? str: skip str 3][ + str: insert str "," + ] + reverse head str +] + +;; Main logic +index: 42 ;; start index at 42 (before first increment) +count-primes: 0 ;; count of primes found +while [count-primes < 42] [ + index: index + 1 ;; increment index by 1 at iteration start + if prime? index [ + count-primes: count-primes + 1 + print rejoin [ + pad count-primes -2 + ": prime = " + pad format-commas index -18 + ] + ;; increment index by the prime itself (old index + prime) + index: index + index + ] () +] diff --git a/Task/Loops-Infinite/Eiffel/loops-infinite.e b/Task/Loops-Infinite/Eiffel/loops-infinite.e new file mode 100644 index 0000000000..787068335c --- /dev/null +++ b/Task/Loops-Infinite/Eiffel/loops-infinite.e @@ -0,0 +1,11 @@ +class APPLICATION +create make +feature + make do + from + until false + loop + IO.put_string ("SPAM%N") + end + end +end diff --git a/Task/Loops-Infinite/Pluto/loops-infinite.pluto b/Task/Loops-Infinite/Pluto/loops-infinite.pluto new file mode 100644 index 0000000000..ad46810b80 --- /dev/null +++ b/Task/Loops-Infinite/Pluto/loops-infinite.pluto @@ -0,0 +1 @@ +while true do print("SPAM") end diff --git a/Task/Loops-Infinite/REBOL/loops-infinite.rebol b/Task/Loops-Infinite/REBOL/loops-infinite-1.rebol similarity index 100% rename from Task/Loops-Infinite/REBOL/loops-infinite.rebol rename to Task/Loops-Infinite/REBOL/loops-infinite-1.rebol diff --git a/Task/Loops-Infinite/REBOL/loops-infinite-2.rebol b/Task/Loops-Infinite/REBOL/loops-infinite-2.rebol new file mode 100644 index 0000000000..3315e9d36f --- /dev/null +++ b/Task/Loops-Infinite/REBOL/loops-infinite-2.rebol @@ -0,0 +1 @@ +until [print "SPAM" false] diff --git a/Task/Loops-Infinite/REBOL/loops-infinite-3.rebol b/Task/Loops-Infinite/REBOL/loops-infinite-3.rebol new file mode 100644 index 0000000000..a24bd8f406 --- /dev/null +++ b/Task/Loops-Infinite/REBOL/loops-infinite-3.rebol @@ -0,0 +1 @@ +while[true][print "SPAM"] diff --git a/Task/Loops-Infinite/TAV/loops-infinite.tav b/Task/Loops-Infinite/TAV/loops-infinite.tav new file mode 100644 index 0000000000..0c791f4cb2 --- /dev/null +++ b/Task/Loops-Infinite/TAV/loops-infinite.tav @@ -0,0 +1,2 @@ + ?* \ a loop without condition runs forever (unless exited by '?>') + print 'SPAM' diff --git a/Task/Loops-N-plus-one-half/DuckDB/loops-n-plus-one-half.duckdb b/Task/Loops-N-plus-one-half/DuckDB/loops-n-plus-one-half.duckdb new file mode 100644 index 0000000000..124af5de19 --- /dev/null +++ b/Task/Loops-N-plus-one-half/DuckDB/loops-n-plus-one-half.duckdb @@ -0,0 +1,14 @@ +create or replace function list_join(lst, joiner) as ( + with recursive cte as ( + select 0 as ix, '' as s + union all + select ix+1 as ix, + if (s = '', '', s || joiner) || lst[ix+1]::VARCHAR) as s + from cte + where ix < length(lst) + ) + select last(s) + from cte +); + +select list_join(range(1,11), ', '); diff --git a/Task/Loops-N-plus-one-half/Pluto/loops-n-plus-one-half.pluto b/Task/Loops-N-plus-one-half/Pluto/loops-n-plus-one-half.pluto new file mode 100644 index 0000000000..debaa8bfa5 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Pluto/loops-n-plus-one-half.pluto @@ -0,0 +1,4 @@ +for i = 1, 10 do + io.write(i) + io.write(i < 10 ? ", " : "\n") +end diff --git a/Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-1.tav b/Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-1.tav new file mode 100644 index 0000000000..86a2d8232d --- /dev/null +++ b/Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-1.tav @@ -0,0 +1,6 @@ + ?# i =: from 1 upto 10 + print i nonl + ? i = 10 + ?> \ break loop + print ', ' nonl + print '' diff --git a/Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-2.tav b/Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-2.tav new file mode 100644 index 0000000000..54ca2e8769 --- /dev/null +++ b/Task/Loops-N-plus-one-half/TAV/loops-n-plus-one-half-2.tav @@ -0,0 +1,6 @@ + for i = from 1 upto 10 + print i nonl + if i = 10 + break + print ', ' nonl + print '' diff --git a/Task/Loops-Nested/DuckDB/loops-nested.duckdb b/Task/Loops-Nested/DuckDB/loops-nested.duckdb new file mode 100644 index 0000000000..fcc8011deb --- /dev/null +++ b/Task/Loops-Nested/DuckDB/loops-nested.duckdb @@ -0,0 +1,50 @@ +# PRN in range(0,n) +create or replace function prn(n) as + trunc(random() * n)::BIGINT; + +create or replace function random_array(n, twenty) as + list_transform(range(0,n), x-> 1+prn(twenty)); + +create or replace function random_matrix(m, n, twenty) as ( + list_transform(range(0,m), x -> random_array(n, twenty)) +); + +# Scanning the matrix row-wise, return a list of the cells up to +# but excluding n, or else []. +# WARNING: The matrix `matrix` should be materialized before entry! +# Note the type declaration for `matrix`. +create or replace function matrix_up_to(matrix, n) as ( + if (length(matrix) = 0, [], + (with recursive matrix_t as (select matrix::BIGINT[][] as m), + cte1 as ( + select 1 as ix, + coalesce(list_position(m[1], n), 0) as p, + [] as s + from matrix_t + union all + select ix+1 as ix, + if (p = 0, coalesce(list_position(m[ix+1], n), 0), + -1) as p, + (s || if (@p = 1, [], + if (p>0, m[ix][:p-1], + m[ix] ) )) as s + from cte1, matrix_t + where p != -1 and + ix <= length(m) + ) + -- for verification: select ((last(s), any_value(matrix))) + select last(s) + from cte1 + ) ) +); + +.mode list +.header off + +# Because of the way DuckDB inlines functions, the matrix produced +# by random_matrix() must be materialized before it can be properly handled. +# Using DuckDB V1.1, this can be done using SET VARIABLE: + +set variable matrix = random_matrix(10,5, 20); + +select matrix_up_to( getvariable('matrix'), 20 ) as head; diff --git a/Task/Loops-Nested/Pluto/loops-nested.pluto b/Task/Loops-Nested/Pluto/loops-nested.pluto new file mode 100644 index 0000000000..022fc1f303 --- /dev/null +++ b/Task/Loops-Nested/Pluto/loops-nested.pluto @@ -0,0 +1,18 @@ +local a = {} +for i = 1, 20 do + a[i] = {} + for j = 1, 20 do + a[i][j] = math.random(1, 20) + end +end + +for i = 1, 20 do + for j = 1, 20 do + io.write(string.format("%2d ", a[i][j])) + if a[i][j] == 20 then + print() + break 2 -- break from outer loop + end + if j % 10 == 0 then print() end + end +end diff --git a/Task/Loops-Nested/REBOL/loops-nested.rebol b/Task/Loops-Nested/REBOL/loops-nested.rebol index 0e0c58920f..b2ea53ae32 100644 --- a/Task/Loops-Nested/REBOL/loops-nested.rebol +++ b/Task/Loops-Nested/REBOL/loops-nested.rebol @@ -12,7 +12,7 @@ random/seed now ; Create array and fill with random numbers, range 1..20. soup: array [10 10] -repeat row soup [forall row [row/1: random 20]] +foreach row soup [forall row [row/1: random 20]] print "Loop break using state variable:" done: no diff --git a/Task/Loops-Nested/Zig/loops-nested.zig b/Task/Loops-Nested/Zig/loops-nested.zig new file mode 100644 index 0000000000..3fe5cf6098 --- /dev/null +++ b/Task/Loops-Nested/Zig/loops-nested.zig @@ -0,0 +1,38 @@ +const std = @import("std"); + +const ARR_ROWS = 10; +const ARR_COLS = 10; + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var prng = std.Random.DefaultPrng.init(blk: { + var seed: u64 = undefined; + try std.posix.getrandom(std.mem.asBytes(&seed)); + break :blk seed; + }); + const rand = prng.random(); + var bi_arr: [ARR_ROWS][ARR_COLS]u8 = undefined; + + // generate values for the bi-dimensional array + for (0..ARR_ROWS) |row| { + for (0..ARR_COLS) |col| { + bi_arr[row][col] = rand.intRangeAtMost(u8, 0, 20); + } + } + + // search for the value 20 in the bi-dimensional array + const target: u8 = 20; + search: for (0..ARR_ROWS) |row| { + for (0..ARR_COLS) |col| { + try stdout.print("{d:2} ", .{bi_arr[row][col]}); + + if (bi_arr[row][col] == target) { + break :search; + } + } + + try stdout.print("\n", .{}); + } + + try stdout.print("\n", .{}); +} diff --git a/Task/Loops-While/DuckDB/loops-while.duckdb b/Task/Loops-While/DuckDB/loops-while.duckdb new file mode 100644 index 0000000000..11df13fc66 --- /dev/null +++ b/Task/Loops-While/DuckDB/loops-while.duckdb @@ -0,0 +1,15 @@ +# Start at `start` +create or replace function task(start) as table ( + with recursive cte as ( + select start::BIGINT as n + union all + select + n // 2 as n + from cte + where n > 0 -- "while n > 0" + ) + from cte + where n > 0 -- comment me out to include the last 0 +); + +from task(1024); diff --git a/Task/Loops-While/Mn/loops-while.mn b/Task/Loops-While/Mn/loops-while.mn new file mode 100644 index 0000000000..9080cea70b --- /dev/null +++ b/Task/Loops-While/Mn/loops-while.mn @@ -0,0 +1,6 @@ +1024 +(dup 1 >=) ( + puts + 2 / +) while +pop diff --git a/Task/Loops-While/Pluto/loops-while.pluto b/Task/Loops-While/Pluto/loops-while.pluto new file mode 100644 index 0000000000..8466074739 --- /dev/null +++ b/Task/Loops-While/Pluto/loops-while.pluto @@ -0,0 +1,5 @@ +local i = 1024 +while i > 0 do + print(i) + i //= 2 +end diff --git a/Task/Loops-While/REBOL/loops-while.rebol b/Task/Loops-While/REBOL/loops-while.rebol index 8c7f301587..c580644c20 100644 --- a/Task/Loops-While/REBOL/loops-while.rebol +++ b/Task/Loops-While/REBOL/loops-while.rebol @@ -6,5 +6,5 @@ REBOL [ value: 1024 while [value > 0][ print value - value: to-integer value / 2 + value: to integer! value / 2 ] diff --git a/Task/Loops-While/TAV/loops-while.tav b/Task/Loops-While/TAV/loops-while.tav new file mode 100644 index 0000000000..8a36401968 --- /dev/null +++ b/Task/Loops-While/TAV/loops-while.tav @@ -0,0 +1,4 @@ + i =: 1024 + ?* i >= 1 + print i + i =: i // 2 \ integer division" diff --git a/Task/Loops-While/Ursalang/loops-while.ursa b/Task/Loops-While/Ursalang/loops-while.ursa new file mode 100644 index 0000000000..ba129a5114 --- /dev/null +++ b/Task/Loops-While/Ursalang/loops-while.ursa @@ -0,0 +1,6 @@ +var n = 1024 +loop { + if not (n > 0) { break } + print(n) + n := n >>> 1 +} diff --git a/Task/Loops-While/Zig/loops-while.zig b/Task/Loops-While/Zig/loops-while.zig index a2011742c1..dca717a879 100644 --- a/Task/Loops-While/Zig/loops-while.zig +++ b/Task/Loops-While/Zig/loops-while.zig @@ -1,7 +1,10 @@ const std = @import("std"); -pub fn main() void { - var i: u11 = 1024; - while (i > 0) : (i /= 2) - std.debug.print("{}\n", .{i}); +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + var n: u16 = 1024; + while (n > 0) : (n = @divTrunc(n, 2)) { + try stdout.print("{d}\n", .{n}); + } } diff --git a/Task/Loops-With-multiple-ranges/DuckDB/loops-with-multiple-ranges.duckdb b/Task/Loops-With-multiple-ranges/DuckDB/loops-with-multiple-ranges.duckdb new file mode 100644 index 0000000000..8e6b2c5cb3 --- /dev/null +++ b/Task/Loops-With-multiple-ranges/DuckDB/loops-with-multiple-ranges.duckdb @@ -0,0 +1,32 @@ +create or replace function ranges(x, y, z, one, three, seven) as ( + range(-three, ((1 + 3) ^ 3)::BIGINT, three) || + range( -seven, 1 + seven, x) || + range( 555, 1 + 550 - y) || + range( 22,-1 -28, -three) || + range(1927 , 1 + 1939 ) || + range(x , y, z) || + range((11 ^ x)::BIGINT, 1 + ( 11 ^ x)::BIGINT + one) +); + +create or replace function task(x,y,z, one, three, seven) as table ( + with recursive lst as (select ranges(x,y,z, one, three, seven) as lst), + cte as ( + select 1 as ix, -- index into ranges() + 0 as j, + 0 as sum, + 1 as prod -- start with a product of unity + union all + select ix + 1 as ix, + lst.lst[ix] as j, + (sum + (@j)) as sum, + if ((@prod) < (2 ^ 27)::BIGINT and j != 0, + prod * j, + prod) as prod + from cte, lst + where ix <= 1 + length(lst) + ) + select last(sum) as sum, last(prod) as prod + from cte +); + +from task(5, -5, -2, 1, 3, 7); diff --git a/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges.hs b/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-1.hs similarity index 100% rename from Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges.hs rename to Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-1.hs diff --git a/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-2.hs b/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-2.hs new file mode 100644 index 0000000000..56ab9d8f9a --- /dev/null +++ b/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-2.hs @@ -0,0 +1,30 @@ +procedure main() + prod := 1 + sum := 0 + x := +5 + y := -5 + z := -2 + one := 1 + three := 3 + seven := 7 + + every j := resultsof { + -three to 3^3 by three , + -seven to +seven by x , + 555 to 550 - y , + 22 to -28 by -three , + 1927 to 1939 , + x to y by z , + 11^x to 11^x + one + } do { + sum := sum + abs(j) + if abs(prod) < 2^27 & j ~= 0 then prod := prod*j + } + write(" sum = ", sum) + write("prod = ", prod) +end + +procedure resultsof(celist) + every ce := !celist do + while e := @ce do suspend e +end diff --git a/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-3.hs b/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-3.hs new file mode 100644 index 0000000000..14533b0f49 --- /dev/null +++ b/Task/Loops-With-multiple-ranges/Haskell/loops-with-multiple-ranges-3.hs @@ -0,0 +1,27 @@ +procedure main() + prod := 1 + sum := 0 + x := +5 + y := -5 + z := -2 + one := 1 + three := 3 + seven := 7 + + i_to_h_by_k := proc("...",3) # i_to_h_by_k(i,h,k) + # same as "i to h by k" + every j := i_to_h_by_k ! ![ + [ -three , 3^3 , three ] , + [ -seven , +seven , x ] , + [ 555 , 550 - y , one ] , # list of argument lists + [ 22 , -28 , -three ] , # (i,h,k) + [ 1927 , 1939 , one ] , + [ x , y , z ] , + [ 11^x , 11^x + one , one ] + ] do { + sum := sum + abs(j) + if abs(prod) < 2^27 & j ~= 0 then prod := prod*j + } + write(" sum = ", sum) + write("prod = ", prod) +end diff --git a/Task/Loops-With-multiple-ranges/Pluto/loops-with-multiple-ranges.pluto b/Task/Loops-With-multiple-ranges/Pluto/loops-with-multiple-ranges.pluto new file mode 100644 index 0000000000..7b6de5c7fc --- /dev/null +++ b/Task/Loops-With-multiple-ranges/Pluto/loops-with-multiple-ranges.pluto @@ -0,0 +1,60 @@ +local prod = 1 +local sum = 0 +local x = 5 +local y = -5 +local z = -2 +local one = 1 +local three = 3 +local seven = 7 +local p = math.round(11 ^ x) +local j = 0 + +local function process() + sum += math.abs(j) + if math.abs(prod) < (1 << 27) and j != 0 then prod *= j end +end + +j = -three +while j <= 3 ^ 3 do + process() + j += three +end + +j = -seven +while j <= seven do + process() + j += x +end + +j = 555 +while j <= 550 - y do + process() + ++j +end + +j = 22 +while j >= -28 do + process() + j -= three +end + +j = 1927 +while j <= 1939 do + process() + ++j +end + +j = x +while j >= y do + process() + j -= -z +end + +j = p +while j <= p + one do + process() + ++j +end + +print($"sum = {string.formatint(sum)}") +print($"prod = {string.formatint(prod)}") diff --git a/Task/Loops-With-multiple-ranges/REBOL/loops-with-multiple-ranges.rebol b/Task/Loops-With-multiple-ranges/REBOL/loops-with-multiple-ranges.rebol new file mode 100644 index 0000000000..2ac667dae9 --- /dev/null +++ b/Task/Loops-With-multiple-ranges/REBOL/loops-with-multiple-ranges.rebol @@ -0,0 +1,59 @@ +Rebol [ + title: "Rosetta code: Loops/With multiple ranges" + file: %Loops-With_multiple_ranges.r3 + url: https://rosettacode.org/wiki/Loops/With_multiple_ranges + needs: 3.0.0 + note: {Based on Rosetta Code Red language task solution} +] +;; Define a function that iterates over multiple ranges +for-ranges: function/with ['word ranges body][ + ;; Clear temporary buffer + inp: clear [] + ;; Bind ranges dialect to context of this function + bind ranges self + foreach c reduce ranges [append inp c] + foreach i inp [set word i do body] +] context [ + inp: copy [] + ;; Define a custom operator 'to' that creates a range from start to end + ;- Note: `to` function redefinition! + to: make op! function [start end][ + res: copy [] + repeat n 1 + absolute to-integer end - start [ + append res start + either start > end [1 - n][n - 1] + ] + ] + ;; Define a custom operator 'by' that extracts every nth element from a series + by: make op! function [s w] [extract s absolute w] +] + +;; Initialize variables + prod: 1 + sum: 0 + x: +5 + y: -5 + z: -2 + one: 1 +three: 3 +seven: 7 + +;; Execute for-ranges with variable 'j' over multiple range expressions +for-ranges j [ + 0 - three to (3 ** 3) by three + 0 - seven to seven by x + 555 to (550 - y) + 22 to -28 by (0 - three) + 1927 to 1939 + x to y by z + 11 ** x to (11 ** x + one) +][ + ;; Body of the loop executed for each value of j + ;; Add absolute value of j to sum + sum: to-integer sum + absolute j + ;; Multiply prod by j if conditions are met: + ;; - absolute value of prod is less than 2^27 (134,217,728) + ;; - j is not zero (to avoid making prod zero) + if all [(absolute prod) < power 2 27 j <> 0] [prod: prod * j] +] +;; Print the final results +print ["sum: " sum "^/prod:" prod] diff --git a/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp b/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp index ef6a43fd98..5d61ef35a6 100644 --- a/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp +++ b/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp @@ -5,44 +5,44 @@ #include struct LoopData { - int32_t start; - int32_t stop; - int32_t increment; - std::string comment; + int32_t start; + int32_t stop; + int32_t increment; + std::string comment; }; void print_vector(const std::vector& list) { - std::cout << "["; - for ( uint64_t i = 0; i < list.size(); ++i ) { - std::cout << list[i]; - if ( i < list.size() - 1 ) { - std::cout << ", "; - } - } - std::cout << "]"; + std::cout << "["; + for ( uint64_t i = 0; i < list.size(); ++i ) { + std::cout << list[i]; + if ( i < list.size() - 1 ) { + std::cout << ", "; + } + } + std::cout << "]"; } void runTest(const LoopData& loop_data) { - std::vector values{}; - for ( int32_t i = loop_data.start; i <= loop_data.stop; i += loop_data.increment ) { - values.emplace_back(i); - if ( values.size() >= 10 ) { - break; - } - } + std::vector values{}; + for ( int32_t i = loop_data.start; i <= loop_data.stop; i += loop_data.increment ) { + values.emplace_back(i); + if ( values.size() >= 10 ) { + break; + } + } - std::cout << std::left << std::setw(45) << loop_data.comment; print_vector(values); - std::cout << ( values.size() == 10 ? " (loops forever)" : "" ) << std::endl; + std::cout << std::left << std::setw(45) << loop_data.comment; print_vector(values); + std::cout << ( values.size() == 10 ? " (loops forever)" : "" ) << std::endl; } int main() { - runTest(LoopData(-2, 2, 1, "Normal")); - runTest(LoopData(-2, 2, 0, "Zero increment")); - runTest(LoopData(-2, 2, -1, "Increments away from stop value")); - runTest(LoopData(-2, 2, 10, "First increment is beyond stop value")); - runTest(LoopData(2, -2, 1, "Start more than stop: positive increment")); - runTest(LoopData(2, 2, 1, "Start equal stop: positive increment")); - runTest(LoopData(2, 2, -1, "Start equal stop: negative increment")); - runTest(LoopData(2, 2, 0, "Start equal stop: zero increment")); - runTest(LoopData(0, 0, 0, "Start equal stop equal zero: zero increment")); + runTest(LoopData(-2, 2, 1, "Normal")); + runTest(LoopData(-2, 2, 0, "Zero increment")); + runTest(LoopData(-2, 2, -1, "Increments away from stop value")); + runTest(LoopData(-2, 2, 10, "First increment is beyond stop value")); + runTest(LoopData(2, -2, 1, "Start more than stop: positive increment")); + runTest(LoopData(2, 2, 1, "Start equal stop: positive increment")); + runTest(LoopData(2, 2, -1, "Start equal stop: negative increment")); + runTest(LoopData(2, 2, 0, "Start equal stop: zero increment")); + runTest(LoopData(0, 0, 0, "Start equal stop equal zero: zero increment")); } diff --git a/Task/Loops-Wrong-ranges/Common-Lisp/loops-wrong-ranges.lisp b/Task/Loops-Wrong-ranges/Common-Lisp/loops-wrong-ranges.lisp index e651ee0ced..771e433bac 100644 --- a/Task/Loops-Wrong-ranges/Common-Lisp/loops-wrong-ranges.lisp +++ b/Task/Loops-Wrong-ranges/Common-Lisp/loops-wrong-ranges.lisp @@ -1,18 +1,18 @@ -(dolist (lst '((-2 2 1 "Normal") ; Iterate the parameters list `start' `stop' `increment' and `comment' - (-2 2 0 "Zero increment") - (-2 2 -1 "Increments away from stop value") - (-2 2 10 "First increment is beyond stop value") - ( 2 -2 1 "Start more than stop: positive increment") - ( 2 2 1 "Start equal stop: positive increment") - ( 2 2 -1 "Start equal stop: negative increment") - ( 2 2 0 "Start equal stop: zero increment") - ( 0 0 0 "Start equal stop equal zero: zero increment"))) +(dolist (lst '((-2 2 1 "Normal") ; Iterate the parameters list `start' `stop' `increment' and `comment' + (-2 2 0 "Zero increment") + (-2 2 -1 "Increments away from stop value") + (-2 2 10 "First increment is beyond stop value") + ( 2 -2 1 "Start more than stop: positive increment") + ( 2 2 1 "Start equal stop: positive increment") + ( 2 2 -1 "Start equal stop: negative increment") + ( 2 2 0 "Start equal stop: zero increment") + ( 0 0 0 "Start equal stop equal zero: zero increment"))) (do ((i (car lst) (incf i (caddr lst))) ; Initialize `start' and set `increment' - (result ()) ; Initialize the result list - (loop-max 0 (incf loop-max))) ; Initialize a loop limit - ((or (> i (cadr lst)) ; Break condition to `stop' - (> loop-max 10)) ; Break condition to loop limit - (format t "~&~44a: ~{~3d ~}" ; Finally print - (cadddr lst) ; The `comment' - (reverse result))) ; The in(de)creased numbers into result - (push i result))) ; Add the number to result + (result ()) ; Initialize the result list + (loop-max 0 (incf loop-max))) ; Initialize a loop limit + ((or (> i (cadr lst)) ; Break condition to `stop' + (> loop-max 10)) ; Break condition to loop limit + (format t "~&~44a: ~{~3d ~}" ; Finally print + (cadddr lst) ; The `comment' + (reverse result))) ; The in(de)creased numbers into result + (push i result))) ; Add the number to result diff --git a/Task/Loops-Wrong-ranges/Eiffel/loops-wrong-ranges.e b/Task/Loops-Wrong-ranges/Eiffel/loops-wrong-ranges.e index 5200ea6e78..d746f33052 100644 --- a/Task/Loops-Wrong-ranges/Eiffel/loops-wrong-ranges.e +++ b/Task/Loops-Wrong-ranges/Eiffel/loops-wrong-ranges.e @@ -1,13 +1,13 @@ example - -- Loops/Wrong ranges - do - ⟳ ic:(-2 |..| 2) ¦ do_nothing ⟲ -- 2 2 1 Normal - ⟳ ic:(-2 |..| 2).new_cursor + 0 ¦ do_nothing ⟲ -- -2 2 0 Zero increment - ⟳ ic:(-2 |..| 2).new_cursor - 1 ¦ do_nothing ⟲ -- -2 2 -1 Increments away from stop value - ⟳ ic:(-2 |..| 2).new_cursor + 10 ¦ do_nothing ⟲ -- -2 2 10 First increment is beyond stop value - ⟳ ic:(-2 |..| 2).new_cursor.reversed ¦ do_nothing ⟲ -- 2 -2 1 Start more than stop: positive increment - ⟳ ic:(2 |..| 2) ¦ do_nothing ⟲ -- 2 2 1 Start equal stop: positive increment - ⟳ ic:(2 |..| 2).new_cursor - 1 ¦ do_nothing ⟲ -- 2 2 -1 Start equal stop: negative increment - ⟳ ic:(2 |..| 2).new_cursor + 0 ¦ do_nothing ⟲ -- 2 2 0 Start equal stop: zero increment - ⟳ ic:(0 |..| 0).new_cursor + 0 ¦ do_nothing ⟲ -- 0 0 0 Start equal stop equal zero: zero increment - end + -- Loops/Wrong ranges + do + ⟳ ic:(-2 |..| 2) ¦ do_nothing ⟲ -- 2 2 1 Normal + ⟳ ic:(-2 |..| 2).new_cursor + 0 ¦ do_nothing ⟲ -- -2 2 0 Zero increment + ⟳ ic:(-2 |..| 2).new_cursor - 1 ¦ do_nothing ⟲ -- -2 2 -1 Increments away from stop value + ⟳ ic:(-2 |..| 2).new_cursor + 10 ¦ do_nothing ⟲ -- -2 2 10 First increment is beyond stop value + ⟳ ic:(-2 |..| 2).new_cursor.reversed ¦ do_nothing ⟲ -- 2 -2 1 Start more than stop: positive increment + ⟳ ic:(2 |..| 2) ¦ do_nothing ⟲ -- 2 2 1 Start equal stop: positive increment + ⟳ ic:(2 |..| 2).new_cursor - 1 ¦ do_nothing ⟲ -- 2 2 -1 Start equal stop: negative increment + ⟳ ic:(2 |..| 2).new_cursor + 0 ¦ do_nothing ⟲ -- 2 2 0 Start equal stop: zero increment + ⟳ ic:(0 |..| 0).new_cursor + 0 ¦ do_nothing ⟲ -- 0 0 0 Start equal stop equal zero: zero increment + end diff --git a/Task/Loops-Wrong-ranges/Icon/loops-wrong-ranges.icon b/Task/Loops-Wrong-ranges/Icon/loops-wrong-ranges.icon new file mode 100644 index 0000000000..40432a2145 --- /dev/null +++ b/Task/Loops-Wrong-ranges/Icon/loops-wrong-ranges.icon @@ -0,0 +1,39 @@ +procedure main() + testdata := [ + # args Comment + # start stop incr + [[-2, 2, 1], "Normal"], + [[-2, 2, 0], "Zero increment"], + [[-2, 2, -1], "Increments away from stop value"], + [[-2, 2, 10], "First increment is beyond stop value"], + [[ 2, -2, 1], "Start more than stop: positive increment"], + [[ 2, 2, 1], "Start equal stop: positive increment"], + [[ 2, 2, -1], "Start equal stop: negative increment"], + [[ 2, 2, 0], "Start equal stop: zero increment"], + [[ 0, 0, 0], "Start equal stop equal zero: zero increment"] + ] + + range := proc("...",3) ; # range(i,j,k) same as "i to j by k" + every argcom := !testdata do{ + write("\n",argcom[2]) + writes("range(",seqimage(argcom[1]),")") + &error := 1 + every elements := [] & put(elements, range ! argcom[1]) + if &errornumber then{ + write(" --->") + write("\tRun-time error ", &errornumber) + write("\t",&errortext) + write("\toffending value: ", image(&errorvalue)) + errorclear() + }else{ + &error := 0 + if *elements ~= 0 then write(" = ",seqimage(elements)) + else write(" (no result)") + } + } +end + +procedure seqimage(L) + every result := "" & result ||:= image(!L) || ", " + return result[1:-2] +end diff --git a/Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto b/Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto new file mode 100644 index 0000000000..d447208393 --- /dev/null +++ b/Task/Loops-Wrong-ranges/Pluto/loops-wrong-ranges.pluto @@ -0,0 +1,19 @@ +local function loop(start, stop, inc) + local f = "{%3d %3d %3d} -> " + io.write(string.format(f, start, stop, inc)) + local count = 0 + local limit = 10 + local i = start + while i <= stop do + io.write(string.format("%3d ", i)) + if ++count == limit then break end + i += inc + end + print() +end + +local tests = { + {-2, 2, 1}, {-2, 2, 0}, {-2, 2, -1}, {-2, 2, 10}, {2, -2, 1}, + { 2, 2, 1}, { 2, 2, -1}, { 2, 2, 0}, { 0, 0, 0} +} +for tests as test do loop(test[1], test[2], test[3]) end diff --git a/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py b/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py index debcbd4ef8..3046697673 100644 --- a/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py +++ b/Task/Loops-Wrong-ranges/Python/loops-wrong-ranges.py @@ -5,16 +5,16 @@ from itertools import islice # To limit execution if it would generate huge valu data = ''' -start stop increment Comment --2 2 1 Normal --2 2 0 Zero increment --2 2 -1 Increments away from stop value --2 2 10 First increment is beyond stop value -2 -2 1 Start more than stop: positive increment -2 2 1 Start equal stop: positive increment -2 2 -1 Start equal stop: negative increment -2 2 0 Start equal stop: zero increment -0 0 0 Start equal stop equal zero: zero increment +start stop increment Comment +-2 2 1 Normal +-2 2 0 Zero increment +-2 2 -1 Increments away from stop value +-2 2 10 First increment is beyond stop value +2 -2 1 Start more than stop: positive increment +2 2 1 Start equal stop: positive increment +2 2 -1 Start equal stop: negative increment +2 2 0 Start equal stop: zero increment +0 0 0 Start equal stop equal zero: zero increment ''' table = [re.split(r'\s\s+', line.strip()) for line in data.strip().split('\n')] diff --git a/Task/Loops-Wrong-ranges/REBOL/loops-wrong-ranges.rebol b/Task/Loops-Wrong-ranges/REBOL/loops-wrong-ranges.rebol new file mode 100644 index 0000000000..07fea975ec --- /dev/null +++ b/Task/Loops-Wrong-ranges/REBOL/loops-wrong-ranges.rebol @@ -0,0 +1,30 @@ +Rebol [ + title: "Rosetta code: Loops/Wrong ranges" + file: %Loops-Wrong_ranges.r3 + url: https://rosettacode.org/wiki/Loops/Wrong_ranges + needs: 3.0.0 +] +make-range: function [start end step][ + res: copy [] + if zero? step [return none] + for i start end step [ + append res i + ] +] +foreach [start end step] [ + -2 2 1 ;Normal + -2 2 0 ;Zero increment + -2 2 -1 ;Increments away from stop value + -2 2 10 ;First increment is beyond stop value + 2 -2 1 ;Start more than stop: positive increment + 2 2 1 ;Start equal stop: positive increment + 2 2 -1 ;Start equal stop: negative increment + 2 2 0 ;Start equal stop: zero increment + 0 0 0 ;Start equal stop equal zero: zero incremen +][ + ;; Using format to pad numbers + prin format ["make-range" -3 -3 -3] reduce [start end step] + prin " ;== " + ;; Output 'make-range' function result + probe make-range start end step +] diff --git a/Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb b/Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb new file mode 100644 index 0000000000..0b20362701 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/DuckDB/luhn-test-of-credit-card-numbers.duckdb @@ -0,0 +1,43 @@ +create or replace function odds(lst) as ( + list_filter(lst, (x,i) -> i%2=1) +); + +create or replace function evens(lst) as ( + list_filter(lst, (x,i) -> i%2=0) +); + +create or replace function digit_sum(i) as ( + regexp_extract_all(i::VARCHAR, '.') + .list_transform(x -> x::INT) + .list_sum() +); + +# Return boolean: true iff the list of digits passes +create or replace function list_luhn(lst) as ( + with odds_sum as ( + select list_reverse(lst).odds().list_sum() as odds_sum), + evens_reduce as ( + select list_reverse(lst).list_transform(x -> digit_sum(2*x)) + .list_sum() as evens_reduce) + select (odds_sum + evens_reduce ) % 10 = 0 as pass + from odds_sum, evens_reduce +); + +# The list of the digits of i (an integer or string) +create or replace function digits(i) as ( + regexp_extract_all(i::TEXT, '.').list_transform(x -> x::INT) +); + +# i can be an integer or string +create or replace function luhn(i) as ( + digits(i).list_luhn() +); + +## Examples:: +select n, luhn(n), luhn(n::TEXT) as "luhn(n::TEXT)" +from unnest( + [49927398716, + 49927398717, + 1234567812345678, + 1234567812345670 + ]) _(n); diff --git a/Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto b/Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto new file mode 100644 index 0000000000..fd67c11fad --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Pluto/luhn-test-of-credit-card-numbers.pluto @@ -0,0 +1,22 @@ +function luhn(b) + local sum = 0 + local odd = true + for i = #b,1,-1 do + local n = tonumber(b[i]) + if odd then + sum += n + else + n *= 2 + sum += n//10 + n%10 + end + odd = !odd + end + return sum%10 == 0 +end + +a = {"49927398716", +"49927398717", +"1234567812345678", +"1234567812345670"} + +for a as i do print(luhn(i)) end diff --git a/Task/M-bius-function/C-sharp/m-bius-function.cs b/Task/M-bius-function/C-sharp/m-bius-function.cs new file mode 100644 index 0000000000..48a19a5f7c --- /dev/null +++ b/Task/M-bius-function/C-sharp/m-bius-function.cs @@ -0,0 +1,84 @@ +using System; + +namespace MobiusDemo +{ + class Program + { + // ----------------------------------------------------------------- + // Settings that are identical to the Java version + // ----------------------------------------------------------------- + private const int MU_MAX = 1_000_000; // same upper bound + private static int[] MU = null; // will hold the sieve + + static void Main(string[] args) + { + Console.WriteLine("First 199 terms of the möbius function are as follows:"); + Console.Write(" "); + + for (int n = 1; n < 200; n++) + { + Console.Write($"{MobiusFunction(n),2} "); + + // line‑break after every 20 numbers – exactly like the Java code + if ((n + 1) % 20 == 0) + Console.WriteLine(); + } + } + + // ----------------------------------------------------------------- + // Compute μ(n) using the same sieve algorithm that the Java code + // uses. The first call builds the whole table up to MU_MAX. + // ----------------------------------------------------------------- + private static int MobiusFunction(int n) + { + // If the sieve has already been built we can return the answer + // straight away. + if (MU != null) + return MU[n]; + + // ------------------------------------------------------------- + // Build the sieve (once) + // ------------------------------------------------------------- + MU = new int[MU_MAX + 1]; + + // initialise every entry with 1 – Java did this explicitly + for (int i = 0; i <= MU_MAX; i++) + MU[i] = 1; + + int sqrt = (int)Math.Sqrt(MU_MAX); + + // first pass: multiply by -p for each prime factor p, + // and mark multiples of p² as zero. + for (int i = 2; i <= sqrt; i++) + { + if (MU[i] == 1) // i is still “prime” + { + // flip the sign for every multiple of i + for (int j = i; j <= MU_MAX; j += i) + MU[j] *= -i; + + // any number that contains i² gets value 0 + int i2 = i * i; + for (int j = i2; j <= MU_MAX; j += i2) + MU[j] = 0; + } + } + + // second pass: reduce the encoded values to the final μ(n) + for (int i = 2; i <= MU_MAX; i++) + { + if (MU[i] == i) // only +i => μ = +1 + MU[i] = 1; + else if (MU[i] == -i) // only -i => μ = -1 + MU[i] = -1; + else if (MU[i] < 0) // product of an odd number of distinct primes + MU[i] = 1; + else if (MU[i] > 0) // product of an even number of distinct primes + MU[i] = -1; + // note: MU[i] == 0 stays 0 (square factor present) + } + + return MU[n]; + } + } +} diff --git a/Task/M-bius-function/Pascal-P/m-bius-function.pas b/Task/M-bius-function/Pascal-P/m-bius-function.pas new file mode 100644 index 0000000000..b517816160 --- /dev/null +++ b/Task/M-bius-function/Pascal-P/m-bius-function.pas @@ -0,0 +1,39 @@ +program moebius(output); + (* Moebius function *) + +var + t, u: integer; + + function moebius(n: integer): integer; + var + m, f: integer; + begin + m := 1; + if n <> 1 then + begin + f := 2; + repeat + if n mod (f * f) = 0 then + m := 0 + else + begin + if n mod f = 0 then + begin + m := -m; + n := n div f + end; + f := f + 1 + end + until (f > n) or (m = 0) + end; + moebius := m + end; + +begin + for t := 0 to 9 do + begin + for u := 1 to 10 do + write(moebius(10 * t + u): 2, ' '); + writeln + end +end. diff --git a/Task/M-bius-function/Pluto/m-bius-function.pluto b/Task/M-bius-function/Pluto/m-bius-function.pluto new file mode 100644 index 0000000000..2721fda354 --- /dev/null +++ b/Task/M-bius-function/Pluto/m-bius-function.pluto @@ -0,0 +1,35 @@ +local int = require "int" +local fmt = require "fmt" + +local function is_square_free(n) + local i = 2 + local sq = i * i + while sq <= n do + if n % sq == 0 then return false end + i = (i > 2) ? i + 2 : i + 1 + sq = i * i + end + return true +end + +local function mu(n) + assert(n >= 1, "Argument must be a positive integer") + if n == 1 then return 1 end + local sq_free = is_square_free(n) + local factors = int.factors(n) + if sq_free and #factors % 2 == 0 then return 1 end + if sq_free then return -1 end + return 0 +end + +print("The first 199 Möbius numbers are:") +for i = 0, 9 do + for j = 0, 19 do + if i == 0 and j == 0 then + io.write(" ") + else + fmt.write("% 3d ", mu(i * 20 + j)) + end + end + print() +end diff --git a/Task/M-bius-function/PowerShell/m-bius-function.psh b/Task/M-bius-function/PowerShell/m-bius-function.psh new file mode 100644 index 0000000000..9c70eee9de --- /dev/null +++ b/Task/M-bius-function/PowerShell/m-bius-function.psh @@ -0,0 +1,28 @@ +# Moebius function + +function Moebius([int]$N) { + [int]$m = 1 + if ($N -ne 1) { + [int]$f = 2 + do { + if ($N % ($f * $f) -eq 0) { + $m = 0 + } else { + if ($N % $f -eq 0) { + $m = -$m; + $N = [math]::Floor($N / $f) + } + $f += 1 + } + } while (($f -le $N) -and ($m -ne 0)) + } + return $m +} + +foreach ($t in 0..9) { + [string]$row = @() + foreach ($u in 1..10) { + $row += "{0,2} " -f $(Moebius(10 * $t + $u)) + } + Write-Output $row +} diff --git a/Task/M-bius-function/R/m-bius-function.r b/Task/M-bius-function/R/m-bius-function.r new file mode 100644 index 0000000000..e1818c4339 --- /dev/null +++ b/Task/M-bius-function/R/m-bius-function.r @@ -0,0 +1,28 @@ +# Moebius function + +Moebius <- function(n) { + if (n == 1) + return(1) + m <- 1 + f <- 2 + repeat { + if (n %% (f * f) == 0) + m <- 0 + else { + if (n %% f == 0) { + m <- -m + n <- n %/% f + } + f <- f + 1 + } + if (f > n || m == 0) + break + } + return(m) +} + +mb <- matrix(0, 10, 10) +for (t in 0:9) + for (u in 1:10) + mb[t + 1, u] <- Moebius(10 * t + u) +mb diff --git a/Task/M-bius-function/Tcl/m-bius-function.tcl b/Task/M-bius-function/Tcl/m-bius-function.tcl new file mode 100644 index 0000000000..8a46858a3d --- /dev/null +++ b/Task/M-bius-function/Tcl/m-bius-function.tcl @@ -0,0 +1,42 @@ +proc prime_factors {n} { + set d 1 + set factors [list] + while {$n > 1 && $d < $n} { + incr d + set d_squared [expr {$d * $d}] + while {$n % $d == 0} { + lappend factors $d + set n [expr {$n / $d}] + } + } + return $factors +} + +proc mobius {n} { + set p [prime_factors $n] + set unique_p [lsort -unique $p] + if {[llength $p] == [llength $unique_p]} { + if {[llength $p] % 2 == 0} { + return 1 + } else { + return -1 + } + } else { + return 0 + } +} + +set upto 199 +set moebius_sequence [list] +for {set i 1} {$i <= $upto} {incr i} { + lappend moebius_sequence [mobius $i] +} + +puts "Möbius sequence - First $upto terms:" +for {set i 0} {$i < $upto} {incr i} { + if {$i % 20 == 0 && $i != 0} { + puts "" + } + puts -nonewline [format "%4d" [lindex $moebius_sequence $i]] +} +puts "" diff --git a/Task/M-bius-function/Zig/m-bius-function.zig b/Task/M-bius-function/Zig/m-bius-function.zig new file mode 100644 index 0000000000..94c613a5c1 --- /dev/null +++ b/Task/M-bius-function/Zig/m-bius-function.zig @@ -0,0 +1,84 @@ +const std = @import("std"); +const print = std.debug.print; + +fn moebius(x_param: u64) i8 { + var x = x_param; + var prime_count: u32 = 0; + + // Helper function to divide x by a factor and count it + // Returns true if we should return 0 (factor appears twice) + const divideXBy = struct { + fn call(x_ptr: *u64, factor: u64, prime_count_ptr: *u32) bool { + if (x_ptr.* % factor == 0) { + x_ptr.* /= factor; + prime_count_ptr.* += 1; + if (x_ptr.* % factor == 0) { + return true; // Return 0 + } + } + return false; + } + }.call; + + // Handle 2 and 3 separately + if (divideXBy(&x, 2, &prime_count)) return 0; + if (divideXBy(&x, 3, &prime_count)) return 0; + + // Use a wheel sieve to check the remaining factors <= √x + var i: u64 = 5; + const sqrt_x = isqrt(x); + while (i <= sqrt_x) : (i += 6) { + if (divideXBy(&x, i, &prime_count)) return 0; + if (divideXBy(&x, i + 2, &prime_count)) return 0; + } + + // There can exist one prime factor larger than √x, + // in that case we can check if x is still larger than one, and then count it. + if (x > 1) { + prime_count += 1; + } + + if (prime_count % 2 == 0) { + return 1; + } else { + return -1; + } +} + +/// Returns the largest integer smaller than or equal to `√n` +fn isqrt(n: u64) u64 { + if (n <= 1) { + return n; + } else { + var x0: u64 = std.math.pow(u64, 2, @as(u32, @intFromFloat(@floor(@log2(@as(f64, @floatFromInt(n))) / 2.0))) + 1); + var x1: u64 = (x0 + n / x0) / 2; + while (x1 < x0) { + x0 = x1; + x1 = (x0 + n / x0) / 2; + } + return x0; + } +} + +pub fn main() void { + const ROWS: u64 = 10; + const COLS: u64 = 20; + print("Values of the Möbius function, μ(x), for x between 0 and {}:\n", .{COLS * ROWS}); + + for (0..ROWS) |i| { + for (0..COLS + 1) |j| { + const x = COLS * i + j; + const mu = moebius(x); + if (mu >= 0) { + // Print an extra space if there's no minus sign in front of the output + // in order to align the numbers in a nice grid. + print(" ", .{}); + } + print("{} ", .{mu}); + } + print("\n" , .{}); + } + + const x = std.math.maxInt(u64); + print("\nμ({}) = {}\n", .{ x, moebius(x) }); +} diff --git a/Task/MD5/DuckDB/md5.duckdb b/Task/MD5/DuckDB/md5.duckdb new file mode 100644 index 0000000000..1a949d0349 --- /dev/null +++ b/Task/MD5/DuckDB/md5.duckdb @@ -0,0 +1 @@ +SELECT MD5('The quick brown fox jumped over the lazy dog''s back') as md5; diff --git a/Task/MD5/JavaScript/md5.js b/Task/MD5/JavaScript/md5.js new file mode 100644 index 0000000000..bf4f48cdc1 --- /dev/null +++ b/Task/MD5/JavaScript/md5.js @@ -0,0 +1,149 @@ +class WBunion { + constructor() { + this._w = 0; + this.b = new Uint8Array(4); + } + + set w(value) { + this._w = value >>> 0; // Ensure unsigned 32-bit + this.b[0] = value & 0xFF; + this.b[1] = (value >>> 8) & 0xFF; + this.b[2] = (value >>> 16) & 0xFF; + this.b[3] = (value >>> 24) & 0xFF; + } + + get w() { + return this._w; + } +} + +function f0(abcd) { + return (abcd[1] & abcd[2]) | (~abcd[1] & abcd[3]); +} + +function f1(abcd) { + return (abcd[3] & abcd[1]) | (~abcd[3] & abcd[2]); +} + +function f2(abcd) { + return abcd[1] ^ abcd[2] ^ abcd[3]; +} + +function f3(abcd) { + return abcd[2] ^ (abcd[1] | ~abcd[3]); +} + +function calcKs(k) { + const pwr = Math.pow(2, 32); + for (let i = 0; i < 64; i++) { + const s = Math.abs(Math.sin(1 + i)); + k[i] = (s * pwr) >>> 0; // Ensure unsigned 32-bit + } + return k; +} + +// ROtate v Left by amt bits +function rol(v, amt) { + const msk1 = (1 << amt) - 1; + return (((v >>> (32 - amt)) & msk1) | ((v << amt) & ~msk1)) >>> 0; // Ensure unsigned 32-bit +} + +function md5(msg) { + const h0 = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476]; + const ff = [f0, f1, f2, f3]; + const M = [1, 5, 3, 7]; + const O = [0, 1, 5, 0]; + const rot0 = [7, 12, 17, 22]; + const rot1 = [5, 9, 14, 20]; + const rot2 = [4, 11, 16, 23]; + const rot3 = [6, 10, 15, 21]; + const rots = [rot0, rot1, rot2, rot3]; + const kspace = new Array(64); + let k = calcKs(kspace); + + const h = [...h0]; // Clone h0 + const abcd = new Array(4); + + // Convert string to byte array + const mlen = msg.length; + const grps = 1 + Math.floor((mlen + 8) / 64); + const msg2 = new Uint8Array(64 * grps); + + // Copy message to msg2 + for (let i = 0; i < mlen; i++) { + msg2[i] = msg.charCodeAt(i) & 0xFF; + } + + // Append padding bits + msg2[mlen] = 0x80; + + // Append length (in bits) + const bitLen = mlen * 8; + const offset = 64 * grps - 8; + msg2[offset] = bitLen & 0xFF; + msg2[offset + 1] = (bitLen >>> 8) & 0xFF; + msg2[offset + 2] = (bitLen >>> 16) & 0xFF; + msg2[offset + 3] = (bitLen >>> 24) & 0xFF; + + // Process message in 64-byte chunks + for (let grp = 0, os = 0; grp < grps; grp++, os += 64) { + const chunk = msg2.slice(os, os + 64); + const mm = { w: new Array(16) }; + + // Convert bytes to words + for (let i = 0; i < 16; i++) { + mm.w[i] = (chunk[i * 4] | + (chunk[i * 4 + 1] << 8) | + (chunk[i * 4 + 2] << 16) | + (chunk[i * 4 + 3] << 24)) >>> 0; + } + + // Initialize hash values for this chunk + for (let q = 0; q < 4; q++) { + abcd[q] = h[q]; + } + + // Main loop + for (let p = 0; p < 4; p++) { + const fctn = ff[p]; + const rotn = rots[p]; + const m = M[p]; + const o = O[p]; + + for (let q = 0; q < 16; q++) { + const g = (m * q + o) % 16; + const f = (abcd[1] + rol(abcd[0] + fctn(abcd) + k[q + 16 * p] + mm.w[g], rotn[q % 4])) >>> 0; + + abcd[0] = abcd[3]; + abcd[3] = abcd[2]; + abcd[2] = abcd[1]; + abcd[1] = f; + } + } + + // Add chunk's hash to result + for (let p = 0; p < 4; p++) { + h[p] = (h[p] + abcd[p]) >>> 0; + } + } + + return h; +} + +function main() { + const msg = "The quick brown fox jumps over the lazy dog."; + const d = md5(msg); + let result = "= 0x"; + + for (let j = 0; j < 4; j++) { + const u = new WBunion(); + u.w = d[j]; + for (let k = 0; k < 4; k++) { + result += u.b[k].toString(16).padStart(2, '0'); + } + } + + console.log(result); +} + +main(); diff --git a/Task/MD5/REBOL/md5-1.rebol b/Task/MD5/REBOL/md5-1.rebol new file mode 100644 index 0000000000..11644034b7 --- /dev/null +++ b/Task/MD5/REBOL/md5-1.rebol @@ -0,0 +1,2 @@ +checksum/method "The quick brown fox jumped over the lazy dog" 'md5 +;== #{08A008A01D498C404B0C30852B39D3B8} diff --git a/Task/MD5/REBOL/md5-2.rebol b/Task/MD5/REBOL/md5-2.rebol new file mode 100644 index 0000000000..c94f0418ac --- /dev/null +++ b/Task/MD5/REBOL/md5-2.rebol @@ -0,0 +1,2 @@ +checksum "The quick brown fox jumped over the lazy dog" 'md5 +;== #{08A008A01D498C404B0C30852B39D3B8} diff --git a/Task/MD5/REBOL/md5.rebol b/Task/MD5/REBOL/md5.rebol deleted file mode 100644 index 5fd63ed246..0000000000 --- a/Task/MD5/REBOL/md5.rebol +++ /dev/null @@ -1,2 +0,0 @@ ->> checksum/method "The quick brown fox jumped over the lazy dog" 'md5 -== #{08A008A01D498C404B0C30852B39D3B8} diff --git a/Task/Machine-code/Ada/machine-code.ada b/Task/Machine-code/Ada/machine-code.ada new file mode 100644 index 0000000000..32c7113c29 --- /dev/null +++ b/Task/Machine-code/Ada/machine-code.ada @@ -0,0 +1,68 @@ +-- Linux x86_64 with GNAT 15.1.0 + +with Ada.Unchecked_Conversion; +with Ada.Text_IO; +with Interfaces.C; +with System; + +-- Pull in primitive operations for unsigned int types to combine +-- flags with "or" +use type Interfaces.C.unsigned; + +procedure Machine_Code_Add is + -- The mmap interface provided by GNAT is limited, expecting only + -- reading and writing files rather than grabbing anonymous + -- executable memory regions. At that point it's easier just to + -- define our own interface. + + PROT_READ : constant Interfaces.C.unsigned := 1; + PROT_WRITE : constant Interfaces.C.unsigned := 2; + PROT_EXEC : constant Interfaces.C.unsigned := 4; + MAP_PRIVATE : constant Interfaces.C.unsigned := 2; + MAP_ANON : constant Interfaces.C.unsigned := 32; + + function Mmap (addr : System.Address; + len : Interfaces.C.size_t; + prot : Interfaces.C.unsigned; + flags : Interfaces.C.unsigned; + fd : Interfaces.C.unsigned; + off : Interfaces.C.long) return System.Address; + pragma Import (C, Mmap, "mmap"); + + function Munmap (addr : System.Address; + len : Interfaces.C.size_t) return Interfaces.C.int; + pragma Import (C, Munmap, "munmap"); + + function Memcpy (dest, src : System.Address; n : Interfaces.C.size_t) + return System.Address; + pragma Import (C, Memcpy, "memcpy"); + + type Add_Fn is access + function (A, B : Interfaces.C.long) return Interfaces.C.long + with Convention => C; + + function To_Add_Fn is + new Ada.Unchecked_Conversion (System.Address, Add_Fn); + + Code : constant array (Positive range 1 .. 7) + of Interfaces.C.unsigned_char := + (16#48#, 16#89#, 16#F8#, 16#48#, 16#01#, 16#F0#, 16#C3#); + + Len : constant Interfaces.C.size_t := Code'Length; + + Mem : constant System.Address := + Mmap (System.Null_Address, + Len, + PROT_READ or PROT_WRITE or PROT_EXEC, + MAP_PRIVATE or MAP_ANON, + -1, + 0); + + Add : constant Add_Fn := To_Add_Fn (Mem); + Dummy : System.Address := Memcpy (Mem, Code'Address, Len); + Dummy2 : Interfaces.C.int; + Sum : Interfaces.C.long := Add (12, 7); +begin + Ada.Text_IO.Put_Line ("12 + 7 =" & Interfaces.C.long'Image (Sum)); + Dummy2 := Munmap (Mem, Len); +end Machine_Code_Add; diff --git a/Task/Machine-code/Pluto/machine-code-1.pluto b/Task/Machine-code/Pluto/machine-code-1.pluto new file mode 100644 index 0000000000..a695c32dba --- /dev/null +++ b/Task/Machine-code/Pluto/machine-code-1.pluto @@ -0,0 +1,23 @@ +/* mclib.c */ + +// gcc -c -fpic mclib.c +// gcc -shared -o mclib.so mclib.o + +#include +#include + +typedef unsigned char uchar; + +extern uchar run_machine_code(const char *code, uchar a, uchar b, int len) { + void *buf; + uchar c; + /* copy code to executable buffer */ + buf = mmap (0, len, PROT_READ|PROT_WRITE|PROT_EXEC, + MAP_PRIVATE | MAP_ANON, -1, 0); + memcpy (buf, code, len); + /* run code */ + c = ((uchar (*) (uchar, uchar))buf)(a, b); + /* free buffer */ + munmap (buf, len); + return c; +} diff --git a/Task/Machine-code/Pluto/machine-code-2.pluto b/Task/Machine-code/Pluto/machine-code-2.pluto new file mode 100644 index 0000000000..c84f17be8f --- /dev/null +++ b/Task/Machine-code/Pluto/machine-code-2.pluto @@ -0,0 +1,19 @@ +local ffi = require "pluto:ffi" +local lib = ffi.open("./mclib.so") +lib:cdef[[ +unsigned char run_machine_code(const char *code, unsigned char a, unsigned char b, int len); +]] + +local a = 7 +local b = 12 + +-- x64 opcodes for this task +local m = { + 0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, + 0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75, + 0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75, + 0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3 +} + +local code = m:mapped(|byte| -> string.char(byte)):concat("") +print($"{a} + {b} = {lib.run_machine_code(code, a, b, #m)}") diff --git a/Task/Magic-8-ball/Prolog/magic-8-ball.pro b/Task/Magic-8-ball/Prolog/magic-8-ball.pro new file mode 100644 index 0000000000..6ff6c7f4ac --- /dev/null +++ b/Task/Magic-8-ball/Prolog/magic-8-ball.pro @@ -0,0 +1,13 @@ +magic_8_ball :- + Responses = ["It is certain", "It is decidedly so", "Without a doubt", + "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", + "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", + "Ask again later", "Better not tell you now", "Cannot predict now", + "Concentrate and ask again", "Don't bet on it", "My reply is no", + "My sources say no", "Outlook not so good", "Very doubtful"], + repeat, + format("Q: "), + read_line_to_codes(user_input, _), + random_member(Response, Responses), + format("A: ~s~n", [Response]), + fail. diff --git a/Task/Magic-constant/Pascal-P/magic-constant.pas b/Task/Magic-constant/Pascal-P/magic-constant.pas new file mode 100644 index 0000000000..0e81ec83dd --- /dev/null +++ b/Task/Magic-constant/Pascal-P/magic-constant.pas @@ -0,0 +1,35 @@ +program magicconstant(output); +(* Magic constant *) + +var + n: integer; + e: real; + + (* returns the magic constant of a magic square of order n + 2 *) + function a(n: integer): integer; + var + n2: integer; + begin + n2 := n + 2; + a := (n2 * ((n2 * n2) + 1)) div 2 + end; + + (* returns the order of the magic square whose magic constant is at least x *) + function inva(x: real): integer; + begin + inva := trunc(exp(ln((2.0 * x)) / 3) + 1) + end; + +begin + e := 1.0; + write('The first 20 magic constants are '); + for n := 1 to 20 do + write(a(n): 4, ' '); + writeln; + writeln('The 1,000th magic constant is ', a(1000)); + for n := 1 to 20 do + begin + e := e * 10; + writeln('10^', n: 2, ': ', inva(e): 9); + end +end. diff --git a/Task/Magic-squares-of-doubly-even-order/Objeck/magic-squares-of-doubly-even-order.objeck b/Task/Magic-squares-of-doubly-even-order/Objeck/magic-squares-of-doubly-even-order.objeck new file mode 100644 index 0000000000..a65dbc86eb --- /dev/null +++ b/Task/Magic-squares-of-doubly-even-order/Objeck/magic-squares-of-doubly-even-order.objeck @@ -0,0 +1,43 @@ +class Test { + function : Main(args : String[]) ~ Nil { + n := 8; + result := MagicSquareDoublyEven(n); + dim := result->Size(); + + for (i := 0; i < dim[0]; i++) + { + for (j := 0; j < dim[1]; j++) { + value := result[i, j]; + "{$value}\t"->Print(); + } + "\n"->Print(); + }; + + value := (n * n + 1) * n / 2; + "\nMagic constant: {$value}"->PrintLine(); + } + + function : MagicSquareDoublyEven(n:Int) ~ Int[,] { + if (n < 4 | n % 4 <> 0) { + "base must be a positive multiple of 4"->ErrorLine(); + System.Runtime->Exit(1); + }; + + # pattern of count-up vs count-down zones + bits := 0b1001011001101001; + size := n * n; + mult := n / 4; # how many multiples of 4 + + result := Int->New[n, n]; + + for (r := 0, i := 0; r < n; r++) + { + for (c := 0; c < n; c++, i++) + { + bitPos := c / mult + (r / mult) * 4; + result[r, c] := (bits and (1 << bitPos)) <> 0 ? i + 1 : size - i; + } + } + return result; + } +} diff --git a/Task/Magic-squares-of-doubly-even-order/Pluto/magic-squares-of-doubly-even-order.pluto b/Task/Magic-squares-of-doubly-even-order/Pluto/magic-squares-of-doubly-even-order.pluto new file mode 100644 index 0000000000..c8d9295e44 --- /dev/null +++ b/Task/Magic-squares-of-doubly-even-order/Pluto/magic-squares-of-doubly-even-order.pluto @@ -0,0 +1,29 @@ +local function magic_square_doubly_even(n) + assert(n > 0 and n % 4 == 0, "Base must be a positive multiple of 4") + + -- Pattern of count-up vs count-down zones. + local bits = 0b1001011001101001 + local size = n * n + local mult = n // 4 -- how many multiples of 4 + local result = {} + for i = 1, n do + result[i] = {} + for j = 1, n do result[i][j] = 0 end + end + local i = 0 + for r = 1, n do + for c = 1, n do + local bitpos = (c - 1) // mult + (r - 1) // mult * 4 + result[r][c] = ((bits & (1 << bitpos)) != 0) ? i + 1: size - i + ++i + end + end + return result +end + +local n = 8 +for magic_square_doubly_even(n) as ia do + for ia as i do io.write(string.format("%2d ", i)) end + print() +end +print($"\nMagic constant {(n * n + 1) * n // 2}") diff --git a/Task/Magic-squares-of-odd-order/Pluto/magic-squares-of-odd-order.pluto b/Task/Magic-squares-of-odd-order/Pluto/magic-squares-of-odd-order.pluto new file mode 100644 index 0000000000..523eabc7ee --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Pluto/magic-squares-of-odd-order.pluto @@ -0,0 +1,28 @@ +local function ms(n) + local M = |x| -> (x + n - 1) % n + if n <= 0 or n & 1 == 0 then + n = 5 + print($"forcing size {n}") + end + local m = {} + for i = 1, n * n do m[i] = 0 end + local i = 0 + local j = n // 2 + for k = 1, n * n do + m[i * n + j + 1] = k + if m[M(i) * n + M(j) + 1] != 0 then + i = (i + 1) % n + else + i = M(i) + j = M(j) + end + end + return {n, m} +end + +local [n, m] = ms(5) +for i = 1, n do + for j = 1, n do io.write(string.format("%4d", m[(i - 1) * n + j])) end + print() +end +print($"\nMagic number : {(n * n + 1) // 2 * n}") diff --git a/Task/Magic-squares-of-singly-even-order/Pluto/magic-squares-of-singly-even-order.pluto b/Task/Magic-squares-of-singly-even-order/Pluto/magic-squares-of-singly-even-order.pluto new file mode 100644 index 0000000000..4566e01813 --- /dev/null +++ b/Task/Magic-squares-of-singly-even-order/Pluto/magic-squares-of-singly-even-order.pluto @@ -0,0 +1,73 @@ +local function magic_square_odd(n) + assert(n > 2 and n % 2 == 1, "Base must be odd and > 2." ) + local value = 1 + local grid_size = n * n + local c = n // 2 + 1 + local r = 1 + local result = {} + for i = 1, n do + result[i] = {} + for j = 1, n do result[i][j] = 0 end + end + while value <= grid_size do + result[r][c] = value + if r == 1 then + if c == n then + ++r + else + r = n + ++c + end + elseif c == n then + r -= 1 + c = 1 + elseif result[r - 1][c + 1] == 0 then + r -= 1 + c += 1 + else + ++r + end + ++value + end + return result +end + +local function magic_square_singly_even(n) + assert(n >= 6 and (n - 2) % 4 == 0, "Base must be a positive multiple of 4 plus 2.") + local size = n * n + local half_n = n // 2 + local sub_square_size = size // 4 + local sub_square = magic_square_odd(half_n) + local quadrant_factors = {0, 2, 3, 1} + local result = {} + for i = 1, n do + result[i] = {} + for j = 1, n do result[i][j] = 0 end + end + for r = 1, n do + for c = 1, n do + local quadrant = (r - 1) // half_n * 2 + (c - 1) // half_n + 1 + result[r][c] = sub_square[(r - 1) % half_n + 1][(c - 1) % half_n + 1] + result[r][c] += quadrant_factors[quadrant] * sub_square_size + end + end + local n_cols_left = half_n // 2 + 1 + local n_cols_right = n_cols_left - 1 + for r = 1, half_n do + for c = 1, n do + if c < n_cols_left or c > n - n_cols_right + 1 or (c == n_cols_left and r == n_cols_left) then + if c != 1 or r != n_cols_left then + result[r][c], result[r + half_n][c] = result[r + half_n][c], result[r][c] + end + end + end + end + return result +end + +local n = 6 +for magic_square_singly_even(n) as ia do + for ia as i do io.write(string.format("%2d ", i)) end + print() +end +print($"\nMagic constant {(n * n + 1) * n // 2}") diff --git a/Task/Main-step-of-GOST-28147-89/Zig/main-step-of-gost-28147-89.zig b/Task/Main-step-of-GOST-28147-89/Zig/main-step-of-gost-28147-89.zig new file mode 100644 index 0000000000..fa0f2e8012 --- /dev/null +++ b/Task/Main-step-of-GOST-28147-89/Zig/main-step-of-gost-28147-89.zig @@ -0,0 +1,218 @@ +const std = @import("std"); + +const REPLACEMENT_TABLE = [8][16]u8{ + [_]u8{ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3 }, + [_]u8{ 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9 }, + [_]u8{ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11 }, + [_]u8{ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3 }, + [_]u8{ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2 }, + [_]u8{ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14 }, + [_]u8{ 13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12 }, + [_]u8{ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12 }, +}; + +const KEYS = [8]u32{ + 0xE2C1_04F9, + 0xE41D_7CDE, + 0x7FE5_E857, + 0x0602_65B4, + 0x281C_CC85, + 0x2E2C_929A, + 0x4746_4503, + 0xE00_CE510, +}; + +fn mainStep(text_block: []const u8, key_element: u32) ![8]u8 { + var n: [8]u8 = undefined; + @memcpy(&n, text_block[0..8]); + + var s: u32 = @as(u32, n[0]) << 24 | @as(u32, n[1]) << 16 | @as(u32, n[2]) << 8 | @as(u32, n[3]); + s = s +% key_element; + + var new_s: u32 = 0; + var mid: u32 = 0; + while (mid < 4) : (mid += 1) { + const cell = (s >> @as(u5, @as(u5, @intCast(mid)) << @as(u5, 3))) & 0xFF; + new_s += (@as(u32, REPLACEMENT_TABLE[(mid * 2)][(cell & 0x0f)]) + + (@as(u32, REPLACEMENT_TABLE[(mid * 2 + 1)][(cell >> 4)]) << 4)) << + @as(u5, @intCast(mid << 3) ); + } + + s = ((new_s << 11) +% (new_s >> 21)) ^ + (@as(u32, n[4]) << 24 | @as(u32, n[5]) << 16 | @as(u32, n[6]) << 8 | @as(u32, n[7])); + + n[4] = n[0]; + n[5] = n[1]; + n[6] = n[2]; + n[7] = n[3]; + n[0] = @intCast((s >> 24) & 0xFF); + n[1] = @intCast((s >> 16) & 0xFF); + n[2] = @intCast((s >> 8) & 0xFF); + n[3] = @intCast(s & 0xFF); + + return n; +} + +fn encode(allocator: std.mem.Allocator, text_block: []const u8) ![]u8 { + const step = try allocator.dupe(u8, text_block); + defer allocator.free(step); + + var result: [8]u8 = undefined; + @memcpy(&result, step); + + var i: usize = 0; + while (i < 24) : (i += 1) { + result = try mainStep(&result, KEYS[i % 8]); + } + + i = 8; + while (i > 0) : (i -= 1) { + result = try mainStep(&result, KEYS[i - 1]); + } + + return try allocator.dupe(u8, &result); +} + +fn decode(allocator: std.mem.Allocator, text_block: []const u8) ![]u8 { + var step: [8]u8 = undefined; + @memcpy(step[0..4], text_block[4..8]); + @memcpy(step[4..8], text_block[0..4]); + + for (KEYS) |key| { + step = try mainStep(&step, key); + } + + var i: usize = 24; + while (i > 0) : (i -= 1) { + step = try mainStep(&step, KEYS[(i - 1) % 8]); + } + + var ans: [8]u8 = undefined; + @memcpy(ans[0..4], step[4..8]); + @memcpy(ans[4..8], step[0..4]); + + return try allocator.dupe(u8, &ans); +} + +fn bytesToHexString(allocator: std.mem.Allocator, bytes: []const u8) ![]u8 { + var result = try allocator.alloc(u8, bytes.len * 3); + var i: usize = 0; + while (i < bytes.len) : (i += 1) { + _ = try std.fmt.bufPrint(result[(i * 3)..][0..3], "{X:0>2} ", .{bytes[i]}); + } + return result; +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const args = try std.process.argsAlloc(allocator); + defer std.process.argsFree(allocator, args); + + const stdout = std.io.getStdOut().writer(); + + if (args.len < 2) { + const plain_text = [_]u8{ 0x04, 0x3B, 0x04, 0x21, 0x04, 0x32, 0x04, 0x30 }; + + const hex_str = try bytesToHexString(allocator, &plain_text); + defer allocator.free(hex_str); + try stdout.print("Before one step: {s}\n\n", .{hex_str}); + + const encoded_text = try mainStep(&plain_text, KEYS[0]); + const encoded_hex = try bytesToHexString(allocator, &encoded_text); + defer allocator.free(encoded_hex); + try stdout.print("After one step : {s}\n\n", .{encoded_hex}); + } else { + const text = args[1]; + const padding = (8 - text.len % 8) % 8; + + var t = try allocator.alloc(u8, text.len + padding); + defer allocator.free(t); + + @memcpy(t[0..text.len], text); + @memset(t[text.len..], ' '); + + const chunks_count = t.len / 8; + var plain_text = std.ArrayList([]u8).init(allocator); + defer { + for (plain_text.items) |chunk| { + allocator.free(chunk); + } + plain_text.deinit(); + } + + var i: usize = 0; + try stdout.print("Plain text : ", .{}); + while (i < chunks_count) : (i += 1) { + const chunk = try allocator.dupe(u8, t[(i * 8)..][0..8]); + try plain_text.append(chunk); + + const hex = try bytesToHexString(allocator, chunk); + defer allocator.free(hex); + try stdout.print("[{s}]", .{hex[0..23]}); + } + try stdout.print("\n\n", .{}); + + var encoded_text = std.ArrayList([]u8).init(allocator); + defer { + for (encoded_text.items) |chunk| { + allocator.free(chunk); + } + encoded_text.deinit(); + } + + try stdout.print("Encoded text: ", .{}); + for (plain_text.items) |chunk| { + const encoded = try encode(allocator, chunk); + try encoded_text.append(encoded); + + const hex = try bytesToHexString(allocator, encoded); + defer allocator.free(hex); + try stdout.print("[{s}]", .{hex[0..23]}); + } + try stdout.print("\n\n", .{}); + + var decoded_text = std.ArrayList([]u8).init(allocator); + defer { + for (decoded_text.items) |chunk| { + allocator.free(chunk); + } + decoded_text.deinit(); + } + + try stdout.print("Decoded text: ", .{}); + for (encoded_text.items) |chunk| { + const decoded = try decode(allocator, chunk); + try decoded_text.append(decoded); + + const hex = try bytesToHexString(allocator, decoded); + defer allocator.free(hex); + try stdout.print("[{s}]", .{hex[0..23]}); + } + try stdout.print("\n\n", .{}); + + var total_size: usize = 0; + for (decoded_text.items) |chunk| { + total_size += chunk.len; + } + + var recovered_bytes = try allocator.alloc(u8, total_size); + defer allocator.free(recovered_bytes); + + var offset: usize = 0; + for (decoded_text.items) |chunk| { + @memcpy(recovered_bytes[offset..][0..chunk.len], chunk); + offset += chunk.len; + } + + // Remove padding spaces at the end + var end = recovered_bytes.len; + while (end > 0 and recovered_bytes[end - 1] == ' ') { + end -= 1; + } + + try stdout.print("Recovered text: {s}\n\n", .{recovered_bytes[0..end]}); + } +} diff --git a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy index d5dae7370f..a80426e197 100644 --- a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy +++ b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy @@ -30,7 +30,7 @@ proc draw . cx = (scr_x - center_x) / scale it = iter cx cy maxiter if it < maxiter - gcolor3 it / 20 it / 100 it / 150 + gcolor3 it * 5 it it * 0.7 grect scr_x / res scr_y / res 1 / res 1 / res . . diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl b/Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl index 5731864e0a..846ad7105e 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-3.jl @@ -8,7 +8,7 @@ x = range(-1.0, 1.0, length=d+1) y = range(-h/d, h/d, length=h+1) C = 2.0 .* (x' .+ y .* im) .- 0.5 -Z, S = zero(C), zeros(size(C)) +S, Z = zeros(size(C)), zero(C) animation = Animation() smoothing = Animation() diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl deleted file mode 100644 index 931311a1b2..0000000000 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.jl +++ /dev/null @@ -1,41 +0,0 @@ -using Plots -gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) - -d, h = 800, 500 # pixel density (= image width) and image height -n, r = 200, 500 # number of iterations and escape radius (r > 2) - -x = range(0, 2, length=d+1) -y = range(0, 2 * h / d, length=h+1) - -A, B = collect(x) .- 1, collect(y) .- h / d -C = 2.0 .* (A' .+ B .* im) .- 0.5 - -Z, dZ = zero(C), zero(C) -D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C)) - -for k in 1:n - M = abs.(Z) .< r - S[M], T[M] = S[M] .+ exp.(.- abs.(Z[M])), T[M] .+ 1 - Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1 -end - -heatmap(S .^ 0.1, c=:balance) -savefig("Mandelbrot_set_1.png") - -N = abs.(Z) .>= r # normalized iteration count -T[N] = T[N] .- log2.(log.(abs.(Z[N])) ./ log(r)) - -heatmap(T .^ 0.1, c=:balance) -savefig("Mandelbrot_set_2.png") - -N = abs.(Z) .> 2 # exterior distance estimation -D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) - -heatmap(D .^ 0.1, c=:balance) -savefig("Mandelbrot_set_3.png") - -N, thickness = D .> 0, 0.01 # boundary detection -D[N] = max.(1 .- D[N] ./ thickness, 0) - -heatmap(D .^ 2.0, c=:binary) -savefig("Mandelbrot_set_4.png") diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl deleted file mode 100644 index 8ca557e392..0000000000 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.jl +++ /dev/null @@ -1,41 +0,0 @@ -using Plots -gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) - -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.0, 1.5 # direction and height of the light -density, intensity = 4.0, 0.5 # density and intensity of the stripes - -x = range(0, 2, length=d+1) -y = range(0, 2 * h / d, length=h+1) - -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, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C)) - -for k in 1:n - M = abs.(Z) .< r - S[M], T[M] = S[M] .+ sin.(density .* 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) .>= r # basic normal map effect and stripe average coloring (potential function) -P, Q = S[N] ./ T[N], (S[N] .+ sin.(density .* angle.(Z[N]))) ./ (T[N] .+ 1) -U, V = Z[N] ./ dZ[N], 1 .+ (log2.(log.(abs.(Z[N])) ./ log(r)) .* (P .- Q) .+ Q) .* intensity -U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector -D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ V .* height) ./ (1 + height), 0) - -heatmap(D .^ 1.0, c=:bone_1) -savefig("Mandelbrot_normal_map_1.png") - -N = abs.(Z) .> 2 # advanced normal map effect using higher derivatives (distance estimation) -H, K, L = abs.(Z[N] ./ dZ[N]), abs.(dZ[N] ./ ddZ[N]), log.(abs.(Z[N])) -U = Z[N] ./ dZ[N] .- (H ./ K) .^ 2 .* L ./ (1 .+ L) .* dZ[N] ./ ddZ[N] -U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector -D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) - -heatmap(D .^ 1.0, c=:afmhot) -savefig("Mandelbrot_normal_map_2.png") diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl b/Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl deleted file mode 100644 index b67d3b0276..0000000000 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.jl +++ /dev/null @@ -1,39 +0,0 @@ -using Plots -gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) - -d, h = 200, 1200 # pixel density (= image width) and image height -n, r = 8000, 10000 # number of iterations and escape radius (r > 2) - -a = -.743643887037158704752191506114774 # https://mathr.co.uk/web/m-location-analysis.html -b = 0.131825904205311970493132056385139 # try: a, b, n = -1.748764520194788535, 3e-13, 800 - -x = range(0, 2, length=d+1) -y = range(0, 2 * h / d, length=h+1) - -A, B = collect(x) .* pi, collect(y) .* pi -C = 8.0 .* exp.((A' .+ B .* im) .* im) .+ (a + b * im) - -Z, dZ = zero(C), zero(C) -D = zeros(size(C)) - -for k in 1:n - M = abs2.(Z) .< abs2(r) - Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1 -end - -N = abs.(Z) .> 2 # exterior distance estimation -D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) - -heatmap(D' .^ 0.05, c=:nipy_spectral) -savefig("Mercator_Mandelbrot_map.png") - -X, Y = real(C), imag(C) # zoom images (adjust circle size 50 and zoom level 20 as needed) -R, c, z = 50 * (2 / d) * pi .* exp.(.- B), min(d, h) + 1, max(0, h - d) ÷ 20 - -gr(c=:nipy_spectral, axis=true, ticks=true, legend=false, markerstrokewidth=0) -p1 = scatter(X[1z+1:1z+c,1:d], Y[1z+1:1z+c,1:d], markersize=R[1:c].^.5, marker_z=D[1z+1:1z+c,1:d].^.5) -p2 = scatter(X[2z+1:2z+c,1:d], Y[2z+1:2z+c,1:d], markersize=R[1:c].^.5, marker_z=D[2z+1:2z+c,1:d].^.4) -p3 = scatter(X[3z+1:3z+c,1:d], Y[3z+1:3z+c,1:d], markersize=R[1:c].^.5, marker_z=D[3z+1:3z+c,1:d].^.3) -p4 = scatter(X[4z+1:4z+c,1:d], Y[4z+1:4z+c,1:d], markersize=R[1:c].^.5, marker_z=D[4z+1:4z+c,1:d].^.2) -plot(p1, p2, p3, p4, layout=(2, 2)) -savefig("Mercator_Mandelbrot_zoom.png") diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl b/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl deleted file mode 100644 index 2dc45623ad..0000000000 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-7.jl +++ /dev/null @@ -1,71 +0,0 @@ -using Base.Threads -using Plots -gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) - -setprecision(BigFloat, 256) # set precision to 256 bits (default) -setrounding(BigFloat, RoundNearest) # set rounding mode (default) - -d, h = 50, 1000 # pixel density (= image width) and image height -n, r = 80000, 100000 # number of iterations and escape radius (r > 2) - -a = BigFloat("-1.256827152259138864846434197797294538253477389787308085590211144291") -b = BigFloat(".37933802890364143684096784819544060002129071484943239316486643285025") - -S = zeros(Complex{Float64}, n+1) -let c = a + b * im, z = zero(c) - for k in 1:n+1 - S[k] = z - if abs2(z) < abs2(r) - z = z ^ 2 + c - else - println("The reference sequence diverges within $(k-1) iterations.") - break - end - end -end - -x = range(0, 2, length=d+1) -y = range(0, 2 * h / d, length=h+1) - -A, B = collect(Float64, x) .* pi, collect(Float64, y) .* pi -C = (- 8.0) .* exp.((A' .+ B .* im) .* im) - -function iteration(C) - E, I, J = zero(C), ones(Int64, size(C)), ones(Int64, size(C)) - Z, dZ = zero(C), zero(C) - - function iterate(E, I, Z, dZ, C) - E, I = (2 .* S[I] .+ E) .* E .+ C, I .+ 1 - Z, dZ = S[I] .+ E, 2 .* Z .* dZ .+ 1 - return E, I, Z, dZ - end - - for k in 1:n - M = abs2.(Z) .< abs2.(E) - E[M], I[M] = Z[M], J[M] # rebase when z is closer to zero - M = abs2.(Z) .< abs2(r) - E[M], I[M], Z[M], dZ[M] = iterate(E[M], I[M], Z[M], dZ[M], C[M]) - end - - return E, I, Z, dZ -end - -function calculation(C) - E, I = zero(C), ones(Int64, size(C)) - Z, dZ = zero(C), zero(C) - - @threads for j in 1:size(C)[2] - E[:,j], I[:,j], Z[:,j], dZ[:,j] = iteration(C[:,j]) - end - - return E, I, Z, dZ -end - -E, I, Z, dZ = calculation(C) -D = zeros(Float64, size(C)) - -N = abs.(Z) .> 2 # exterior distance estimation -D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) - -heatmap(D' .^ 0.015, c=:gist_ncar) -savefig("Mercator_Mandelbrot_deep_map.png") diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-10.py b/Task/Mandelbrot-set/Python/mandelbrot-set-10.py index 5da9f4d0dd..25cb9cf0fc 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-10.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-10.py @@ -1,5 +1,123 @@ -from functools import reduce +import numba +numba.config.CUDA_ENABLE_PYNVJITLINK = True # prevent cuda ptx version errors -def mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2] +import numpy as np +import matplotlib.pyplot as plt -print('\n'.join(''.join(mandelbrot(x, y, x/50 + y/50j) for x in range(-100, 25)) for y in range(-50, 50))) +import cupy as cp +import numba.cuda as cuda + +import decimal as dc # decimal floating point arithmetic with arbitrary precision +dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits) + +d, h = 1600, 1000 # pixel density (= image width) and image height +n, r = 100000, 100000.0 # number of iterations and escape radius (r > 2) + +a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291") +b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025") + +S = np.zeros(n+1, dtype=np.complex128) +u, v = dc.Decimal(0), dc.Decimal(0) + +for i in range(n+1): + S[i] = float(u) + float(v) * 1j + if u * u + v * v < r * r: + u, v = u * u - v * v + a, 2 * u * v + b + else: + print("The reference sequence diverges within %s iterations." % i) + break + +x = np.linspace(0, 2, num=d+1, dtype=np.float64) +y = np.linspace(0, 2 * h / d, num=h+1, dtype=np.float64) + +A, B = np.meshgrid(x - 1, y - h / d) +C = 5.0e-35 * (A + B * 1j) + +def iteration_cupy_cuda(S, C): + I = cp.zeros(C.shape, dtype=np.int32) + E, Z, dZ = cp.zeros_like(C), cp.zeros_like(C), cp.zeros_like(C) + + iteration = cp.RawKernel(""" + #include + + extern "C" __global__ + void iterate(int dim_x, int dim_y, int n, double r, + complex *S, complex *C, + int *I, complex *E, complex *Z, complex *dZ) { + + int x = blockIdx.x * blockDim.x + threadIdx.x; + int y = blockIdx.y * blockDim.y + threadIdx.y; + + if (x < dim_x and y < dim_y) { // prevent memory access errors + int x_y = x * dim_y + y; // cupy arrays are in row-major order + complex delta = C[x_y]; + + int index = I[x_y]; + complex epsilon = E[x_y]; + complex z = Z[x_y]; + complex dz = dZ[x_y]; + + double abs2_r = r * r; + double abs2_z, abs2_e; + + for (int i = 0; i < n; i++) { + abs2_z = z.real() * z.real() + z.imag() * z.imag(); + abs2_e = epsilon.real() * epsilon.real() + epsilon.imag() * epsilon.imag(); + + if (abs2_z < abs2_e) { // rebase when z is closer to zero + epsilon = z; index = 0; // reset reference orbit + } + if (abs2_z < abs2_r) { + epsilon = (2. * S[index] + epsilon) * epsilon + delta; index = index + 1; + dz = 2. * z * dz + 1.; z = S[index] + epsilon; + } + else { + break; + } + } + I[x_y] = index; E[x_y] = epsilon; Z[x_y] = z; dZ[x_y] = dz; + } + } + """, "iterate") + + griddim, blockdim = (h // 32 + 1, d // 32 + 1), (32, 32) + iteration(griddim, blockdim, (h+1, d+1, n, r, cp.asarray(S), cp.asarray(C), I, E, Z, dZ)) + return I.get(), E.get(), Z.get(), dZ.get() + +def iteration_numba_cuda(S, C): + I = cp.zeros(C.shape, dtype=np.int32) + E, Z, dZ = cp.zeros_like(C), cp.zeros_like(C), cp.zeros_like(C) + + @cuda.jit() + def iteration(S, C, I, E, Z, dZ): + x, y = cuda.grid(2) + + if x < h+1 and y < d+1: # prevent memory access errors + delta, index, epsilon, z, dz = C[x, y], I[x, y], E[x, y], Z[x, y], dZ[x, y] + + def abs2(z): + return z.real * z.real + z.imag * z.imag + + for i in range(n): + if abs2(z) < abs2(epsilon): # rebase when z is closer to zero + index, epsilon = 0, z # reset reference orbit + if abs2(z) < abs2(r): + index, epsilon = index + 1, (2 * S[index] + epsilon) * epsilon + delta + z, dz = S[index] + epsilon, 2 * z * dz + 1 + else: + break + + I[x, y], E[x, y], Z[x, y], dZ[x, y] = index, epsilon, z, dz + + griddim, blockdim = (h // 32 + 1, d // 32 + 1), (32, 32) + iteration[griddim, blockdim](cp.asarray(S), cp.asarray(C), I, E, Z, dZ) + return I.get(), E.get(), Z.get(), dZ.get() + +I, E, Z, dZ = iteration_numba_cuda(S, C) # use iteration_cupy_cuda or iteration_numba_cuda +D = np.zeros(C.shape, dtype=np.float64) + +N = abs(Z) > 2 # exterior distance estimation +D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) + +plt.imshow(D ** 0.15, cmap=plt.cm.jet, origin="lower") +plt.savefig("Mandelbrot_deep_zoom.png", dpi=300) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-11.py b/Task/Mandelbrot-set/Python/mandelbrot-set-11.py new file mode 100644 index 0000000000..6cce0c0708 --- /dev/null +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-11.py @@ -0,0 +1,8 @@ +print( +'\n'.join( + ''.join( + ' *'[(z:=0, c:=x/50+y/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2] + for x in range(-100,25) + ) + for y in range(-50,50) +)) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-12.py b/Task/Mandelbrot-set/Python/mandelbrot-set-12.py new file mode 100644 index 0000000000..5da9f4d0dd --- /dev/null +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-12.py @@ -0,0 +1,5 @@ +from functools import reduce + +def mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2] + +print('\n'.join(''.join(mandelbrot(x, y, x/50 + y/50j) for x in range(-100, 25)) for y in range(-50, 50))) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py index e240ab78e6..37019f09c4 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py @@ -10,13 +10,23 @@ y = np.linspace(0, 2 * h / d, num=h+1) A, B = np.meshgrid(x - 1, y - h / d) C = 2.0 * (A + B * 1j) - 0.5 -Z, dZ = np.zeros_like(C), np.zeros_like(C) -D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape) +def iteration(C): + S, T = np.zeros(C.shape), np.zeros(C.shape) + Z, dZ = np.zeros_like(C), np.zeros_like(C) -for k in range(n): - M = abs(Z) < r - S[M], T[M] = S[M] + np.exp(- abs(Z[M])), T[M] + 1 - Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1 + def iterate(C, S, T, Z, dZ): + S, T = S + np.exp(- abs(Z)), T + 1 + Z, dZ = Z * Z + C, 2 * Z * dZ + 1 + return S, T, Z, dZ + + for i in range(n): + M = abs(Z) < r + S[M], T[M], Z[M], dZ[M] = iterate(C[M], S[M], T[M], Z[M], dZ[M]) + + return S, T, Z, dZ + +S, T, Z, dZ = iteration(C) +D = np.zeros(C.shape) plt.imshow(S ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") plt.savefig("Mandelbrot_set_1.png", dpi=200) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py index 8173f62c10..f581e706b4 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py @@ -13,13 +13,23 @@ y = np.linspace(0, 2 * h / d, num=h+1) 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, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape) +def iteration(C): + S, T = np.zeros(C.shape), np.zeros(C.shape) + Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) -for k in range(n): - M = abs(Z) < r - S[M], T[M] = S[M] + np.sin(density * 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]) + def iterate(C, S, T, Z, dZ, ddZ): + S, T = S + np.sin(density * np.angle(Z)), T + 1 + Z, dZ, ddZ = Z * Z + C, 2 * Z * dZ + 1, 2 * (dZ * dZ + Z * ddZ) + return S, T, Z, dZ, ddZ + + for i in range(n): + M = abs(Z) < r + S[M], T[M], Z[M], dZ[M], ddZ[M] = iterate(C[M], S[M], T[M], Z[M], dZ[M], ddZ[M]) + + return S, T, Z, dZ, ddZ + +S, T, Z, dZ, ddZ = iteration(C) +D = np.zeros(C.shape) N = abs(Z) >= r # basic normal map effect and stripe average coloring (potential function) P, Q = S[N] / T[N], (S[N] + np.sin(density * np.angle(Z[N]))) / (T[N] + 1) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-7.py b/Task/Mandelbrot-set/Python/mandelbrot-set-7.py index 90e9a2d739..148ea3f25a 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-7.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-7.py @@ -4,8 +4,8 @@ import matplotlib.pyplot as plt d, h = 200, 1200 # pixel density (= image width) and image height n, r = 8000, 10000 # number of iterations and escape radius (r > 2) -a = -.743643887037158704752191506114774 # https://mathr.co.uk/web/m-location-analysis.html -b = 0.131825904205311970493132056385139 # try: a, b, n = -1.748764520194788535, 3e-13, 800 +a = -.743643887037158704752191506114774 # coordinates by github.com/josch +b = 0.131825904205311970493132056385139 # https://github.com/josch/mandelbrot x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) @@ -13,12 +13,21 @@ y = np.linspace(0, 2 * h / d, num=h+1) A, B = np.meshgrid(x * np.pi, y * np.pi) C = 8.0 * np.exp((A + B * 1j) * 1j) + (a + b * 1j) -Z, dZ = np.zeros_like(C), np.zeros_like(C) -D = np.zeros(C.shape) +def iteration(C): + Z, dZ = np.zeros_like(C), np.zeros_like(C) -for k in range(n): - M = Z.real ** 2 + Z.imag ** 2 < r ** 2 - Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1 + def iterate(C, Z, dZ): + Z, dZ = Z * Z + C, 2 * Z * dZ + 1 + return Z, dZ + + for i in range(n): + M = abs(Z) < r + Z[M], dZ[M] = iterate(C[M], Z[M], dZ[M]) + + return Z, dZ + +Z, dZ = iteration(C) +D = np.zeros(C.shape) N = abs(Z) > 2 # exterior distance estimation D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) @@ -26,12 +35,14 @@ D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) plt.imshow(D.T ** 0.05, cmap=plt.cm.nipy_spectral, origin="lower") plt.savefig("Mercator_Mandelbrot_map.png", dpi=200) -X, Y = C.real, C.imag # zoom images (adjust circle size 100 and zoom level 20 as needed) -R, c, z = 100 * (2 / d) * np.pi * np.exp(- B), min(d, h) + 1, max(0, h - d) // 20 +M = 50 * (2 / d) * np.pi * np.exp(- B) # adjust marker size 50 as needed +k, l = min(d, h) + 1, max(0, h - d) // 20 # adjust zoom level 20 as needed + +fig, axs = plt.subplots(2, 3, figsize=(12, 8)) +for i, ax in enumerate(axs.flat): + X, Y = C[i*l:i*l+k, 0:d].real, C[i*l:i*l+k, 0:d].imag + S, T = M[0:k, 0:d] ** 2, D[i*l:i*l+k, 0:d] ** 0.5 + ax.scatter(X, Y, s=S, c=T, cmap=plt.cm.nipy_spectral) + ax.axis('equal') -fig, ax = plt.subplots(2, 2, figsize=(12, 12)) -ax[0,0].scatter(X[1*z:1*z+c,0:d], Y[1*z:1*z+c,0:d], s=R[0:c,0:d]**2, c=D[1*z:1*z+c,0:d]**.5, cmap=plt.cm.nipy_spectral) -ax[0,1].scatter(X[2*z:2*z+c,0:d], Y[2*z:2*z+c,0:d], s=R[0:c,0:d]**2, c=D[2*z:2*z+c,0:d]**.4, cmap=plt.cm.nipy_spectral) -ax[1,0].scatter(X[3*z:3*z+c,0:d], Y[3*z:3*z+c,0:d], s=R[0:c,0:d]**2, c=D[3*z:3*z+c,0:d]**.3, cmap=plt.cm.nipy_spectral) -ax[1,1].scatter(X[4*z:4*z+c,0:d], Y[4*z:4*z+c,0:d], s=R[0:c,0:d]**2, c=D[4*z:4*z+c,0:d]**.2, cmap=plt.cm.nipy_spectral) plt.savefig("Mercator_Mandelbrot_zoom.png", dpi=100) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-8.py b/Task/Mandelbrot-set/Python/mandelbrot-set-8.py index d4580ac79d..2af2697c11 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-8.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-8.py @@ -1,12 +1,13 @@ +import numba + import numpy as np -import numba as nb import matplotlib.pyplot as plt import decimal as dc # decimal floating point arithmetic with arbitrary precision dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits) d, h = 100, 2000 # pixel density (= image width) and image height -n, r = 80000, 100000 # number of iterations and escape radius (r > 2) +n, r = 80000, 100000.0 # number of iterations and escape radius (r > 2) a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291") b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025") @@ -14,12 +15,12 @@ b = dc.Decimal(".379338028903641436840967848195440600021290714849432393164866432 S = np.zeros(n+1, dtype=np.complex128) u, v = dc.Decimal(0), dc.Decimal(0) -for k in range(n+1): - S[k] = float(u) + float(v) * 1j +for i in range(n+1): + S[i] = float(u) + float(v) * 1j if u * u + v * v < r * r: u, v = u * u - v * v + a, 2 * u * v + b else: - print("The reference sequence diverges within %s iterations." % k) + print("The reference sequence diverges within %s iterations." % i) break x = np.linspace(0, 2, num=d+1, dtype=np.float64) @@ -28,37 +29,37 @@ y = np.linspace(0, 2 * h / d, num=h+1, dtype=np.float64) A, B = np.meshgrid(x * np.pi, y * np.pi) C = (- 8.0) * np.exp((A + B * 1j) * 1j) -@nb.njit(parallel=True) -def calculation(C): - E, I = np.zeros_like(C), np.zeros(C.shape, dtype=np.int64) - Z, dZ = np.zeros_like(C), np.zeros_like(C) +@numba.njit(parallel=True) +def iteration_numba(S, C): + I = np.zeros(C.shape, dtype=np.intp) + E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) - def iteration(C): - E, I = np.zeros_like(C), np.zeros(C.shape, dtype=np.int64) - Z, dZ = np.zeros_like(C), np.zeros_like(C) + def iteration(S, C): + I = np.zeros(C.shape, dtype=np.intp) + E, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) def abs2(z): return z.real * z.real + z.imag * z.imag - def iterate(E, I, Z, dZ, C): - E, I = (2 * S[I] + E) * E + C, I + 1 + def iterate(C, I, E, Z, dZ): + I, E = I + 1, (2 * S[I] + E) * E + C Z, dZ = S[I] + E, 2 * Z * dZ + 1 - return E, I, Z, dZ + return I, E, Z, dZ - for k in range(n): - M = abs2(Z) < abs2(E) - E[M], I[M] = Z[M], 0 # rebase when z is closer to zero + for i in range(n): + M = abs2(Z) < abs2(E) # rebase when z is closer to zero + I[M], E[M] = 0, Z[M] # reset the reference orbit M = abs2(Z) < abs2(r) - E[M], I[M], Z[M], dZ[M] = iterate(E[M], I[M], Z[M], dZ[M], C[M]) + I[M], E[M], Z[M], dZ[M] = iterate(C[M], I[M], E[M], Z[M], dZ[M]) - return E, I, Z, dZ + return I, E, Z, dZ - for j in nb.prange(C.shape[1]): - E[:,j], I[:,j], Z[:,j], dZ[:,j] = iteration(C[:,j]) + for j in numba.prange(d+1): + I[:, j], E[:, j], Z[:, j], dZ[:, j] = iteration(S, C[:, j]) - return E, I, Z, dZ + return I, E, Z, dZ -E, I, Z, dZ = calculation(C) +I, E, Z, dZ = iteration_numba(S, C) D = np.zeros(C.shape, dtype=np.float64) N = abs(Z) > 2 # exterior distance estimation diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-9.py b/Task/Mandelbrot-set/Python/mandelbrot-set-9.py index 6cce0c0708..57df19d043 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-9.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-9.py @@ -1,8 +1,85 @@ -print( -'\n'.join( - ''.join( - ' *'[(z:=0, c:=x/50+y/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2] - for x in range(-100,25) - ) - for y in range(-50,50) -)) +import jax +jax.config.update("jax_enable_x64", True) # faster on GPU P100 than on GPU T4 + +import numpy as np +import matplotlib.pyplot as plt + +import cupy as cp +import jax.numpy as jnp + +import decimal as dc # decimal floating point arithmetic with arbitrary precision +dc.getcontext().prec = 80 # set precision to 80 digits (about 256 bits) + +d, h = 100, 2000 # pixel density (= image width) and image height +n, r = 100000, 100000.0 # number of iterations and escape radius (r > 2) + +a = dc.Decimal("-1.256827152259138864846434197797294538253477389787308085590211144291") +b = dc.Decimal(".37933802890364143684096784819544060002129071484943239316486643285025") + +S = np.zeros(n+1, dtype=np.complex128) +u, v = dc.Decimal(0), dc.Decimal(0) + +for i in range(n+1): + S[i] = float(u) + float(v) * 1j + if u * u + v * v < r * r: + u, v = u * u - v * v + a, 2 * u * v + b + else: + print("The reference sequence diverges within %s iterations." % i) + break + +x = np.linspace(0, 2, num=d+1, dtype=np.float64) +y = np.linspace(0, 2 * h / d, num=h+1, dtype=np.float64) + +A, B = np.meshgrid(x * np.pi, y * np.pi) +C = (- 8.0) * np.exp((A + B * 1j) * 1j) + +def iteration_cupy(S, C): + + def iteration(S, C): + I = cp.zeros(C.shape, dtype=np.intp) + E, Z, dZ = cp.zeros_like(C), cp.zeros_like(C), cp.zeros_like(C) + + for i in range(n): + M = cp.absolute(Z) < cp.absolute(E) # rebase when z is closer to zero + I, E = cp.where(M, 0, I), cp.where(M, Z, E) # reset reference orbit + M = cp.absolute(Z) < r + I, E = cp.where(M, I + 1, I), cp.where(M, (2 * S[I] + E) * E + C, E) + Z, dZ = cp.where(M, S[I] + E, Z), cp.where(M, 2 * Z * dZ + 1, dZ) + + return I, E, Z, dZ + + I, E, Z, dZ = iteration(cp.asarray(S), cp.asarray(C)) + return I.get(), E.get(), Z.get(), dZ.get() + +def iteration_jax(S, C): + + def iteration(S, C): + I = jnp.zeros(C.shape, dtype=np.intp) + E, Z, dZ = jnp.zeros_like(C), jnp.zeros_like(C), jnp.zeros_like(C) + + def abs2(z): + return z.real * z.real + z.imag * z.imag + + def iterate(i, V): + I, E, Z, dZ = V + M = abs2(Z) < abs2(E) # rebase when z is closer to zero + I, E = jnp.where(M, 0, I), jnp.where(M, Z, E) # reset reference orbit + M = abs2(Z) < abs2(r) + I, E = jnp.where(M, I + 1, I), jnp.where(M, (2 * S[I] + E) * E + C, E) + Z, dZ = jnp.where(M, S[I] + E, Z), jnp.where(M, 2 * Z * dZ + 1, dZ) + return I, E, Z, dZ + + I, E, Z, dZ = jax.lax.fori_loop(0, n, iterate, (I, E, Z, dZ), unroll=10) + return I, E, Z, dZ + + I, E, Z, dZ = iteration(jnp.asarray(S), jnp.asarray(C)) + return np.asarray(I), np.asarray(E), np.asarray(Z), np.asarray(dZ) + +I, E, Z, dZ = iteration_jax(S, C) # use iteration_cupy or iteration_jax +D = np.zeros(C.shape, dtype=np.float64) + +N = abs(Z) > 2 # exterior distance estimation +D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) + +plt.imshow(D.T ** 0.015, cmap=plt.cm.gist_ncar, origin="lower") +plt.savefig("Mercator_Mandelbrot_deep_map.png", dpi=200) diff --git a/Task/Map-range/DuckDB/map-range.duckdb b/Task/Map-range/DuckDB/map-range.duckdb new file mode 100644 index 0000000000..412ed1b025 --- /dev/null +++ b/Task/Map-range/DuckDB/map-range.duckdb @@ -0,0 +1,9 @@ +# x is the value to be mapped. +# The ranges, a and b, should each be an array defining the +# left-most and right-most points of the range. +create or replace function maprange(a, b, x) as + b[1] + (((x - a[1]) * (b[2] - b[1]::DOUBLE)) / (a[2] - a[1]::DOUBLE)) ; + +# Example 1: a single value +# (Conversion to floating point will be automatic) +select maprange([0,10], [-1, 0], 6) as mapped; diff --git a/Task/Map-range/Pascal-P/map-range.pas b/Task/Map-range/Pascal-P/map-range.pas new file mode 100644 index 0000000000..72b09669a6 --- /dev/null +++ b/Task/Map-range/Pascal-P/map-range.pas @@ -0,0 +1,14 @@ +program map(output); +(* Map range *) +var + i: integer; + + function maprange(a1, a2, b1, b2: real; s: real): real; + begin + maprange := (s - a1) * (b2 - b1) / (a2 - a1) + b1; + end; + +begin + for i := 0 to 10 do + writeln(i: 2, ' maps to: ', maprange(0.0, 10.0, -1.0, 0.0, i): 10); +end. diff --git a/Task/Matrix-multiplication/DuckDB/matrix-multiplication-1.duckdb b/Task/Matrix-multiplication/DuckDB/matrix-multiplication-1.duckdb new file mode 100644 index 0000000000..2046c86492 --- /dev/null +++ b/Task/Matrix-multiplication/DuckDB/matrix-multiplication-1.duckdb @@ -0,0 +1,7 @@ +# Given two tables, A and B, representing two matrices in (i,j,value) format, the product +# can be computed as follows, with the result being in the same format. +SELECT A.i, B.j, + SUM(A.value * B.value) AS value + FROM A INNER JOIN B + ON A.j = B.i + GROUP BY A.i, B.j; diff --git a/Task/Matrix-multiplication/DuckDB/matrix-multiplication-2.duckdb b/Task/Matrix-multiplication/DuckDB/matrix-multiplication-2.duckdb new file mode 100644 index 0000000000..2066a18e56 --- /dev/null +++ b/Task/Matrix-multiplication/DuckDB/matrix-multiplication-2.duckdb @@ -0,0 +1,16 @@ +# The following SQL statement will convert a table A representing an m by n matrix +# in (i,j,value) format to a table with m rows and (n+1) columns, the first being the row id: +pivot A on j using max(value) order by i; + +# To exclude the row id column: +select columns(* exclude (i)) from (pivot A on j using max(value)) order by i; + +# To ensure the columns are presented in their natural order, +# the above 'select' statement may need to be adjusted. +# If n < 10, the following would suffice: +select columns(* exclude (i)) from (pivot A on j using max(value)) order by i; + +# For 10 to 99 columns: +select columns('^[1-9]$'), columns('^[1-9][0-9]') from (pivot A on j using max(value)) order by i; + +# If there are more than 99 columns, the above can be extended in the obvious way. diff --git a/Task/Matrix-multiplication/DuckDB/matrix-multiplication-3.duckdb b/Task/Matrix-multiplication/DuckDB/matrix-multiplication-3.duckdb new file mode 100644 index 0000000000..abcb101633 --- /dev/null +++ b/Task/Matrix-multiplication/DuckDB/matrix-multiplication-3.duckdb @@ -0,0 +1,39 @@ +create or replace table A (i integer, j integer, value float ); +insert into A values + (1, 1, 1), + (1, 2, 2), + (1, 3, 3), + (2, 1, 2), + (2, 2, 5), + (2, 3, 7); + +create or replace table B (i integer, j integer, value float ); +insert into B values + (1, 1, 2), + (1, 2, 4), + (1, 3, 8), + (2, 1, 1), + (2, 2, 5), + (2, 3, -10), + (3, 1, 3), + (3, 2, 6), + (3, 3, 9); + +.print Display A in a matrix format including the row id +pivot A on j using max(value) order by i; + +.print Display B likewise +pivot B on j using max(value) order by i; + +. print Compute C = A * B +CREATE OR REPLACE table C as + SELECT A.i, B.j, + SUM(A.value * B.value) AS value + FROM A INNER JOIN B + ON A.j = B.i + GROUP BY A.i, B.j; + +.print Display C in matrix format excluding the row id +select columns(* exclude (i)) + from (pivot C on j using max(value)) + order by i; diff --git a/Task/Matrix-multiplication/Objeck/matrix-multiplication.objeck b/Task/Matrix-multiplication/Objeck/matrix-multiplication.objeck new file mode 100644 index 0000000000..ba55e96abe --- /dev/null +++ b/Task/Matrix-multiplication/Objeck/matrix-multiplication.objeck @@ -0,0 +1,8 @@ +class Test { + function : Main(args : String[]) ~ Nil { + a := [[1.0, 2.0], [3.0, 4.0], [3.0, 6.0]]; + b := [[-3.0, -8.0, 3.0,], [-2.0, 1.0, 4.0]]; + + System.ML.Matrix2D->DotProduct(a,b)->ToString()->PrintLine(); + } +} diff --git a/Task/Matrix-transposition/DuckDB/matrix-transposition-1.duckdb b/Task/Matrix-transposition/DuckDB/matrix-transposition-1.duckdb new file mode 100644 index 0000000000..ffa2bb0a1d --- /dev/null +++ b/Task/Matrix-transposition/DuckDB/matrix-transposition-1.duckdb @@ -0,0 +1 @@ +select j as i, i as j, value from A; diff --git a/Task/Matrix-transposition/DuckDB/matrix-transposition-2.duckdb b/Task/Matrix-transposition/DuckDB/matrix-transposition-2.duckdb new file mode 100644 index 0000000000..7744c88beb --- /dev/null +++ b/Task/Matrix-transposition/DuckDB/matrix-transposition-2.duckdb @@ -0,0 +1,22 @@ +create or replace table A (i integer, j integer, value float ); +insert into A values + (1, 1, 1), + (1, 2, 2), + (1, 3, 3), + (2, 1, 2), + (2, 2, 5), + (2, 3, 7); + +# transposition +create or replace table AT as + (select j as i, i as j, value from A); + +.print The matrix-like representation of A: +create or replace table AMatrix as (pivot A on j using max(value) order by i); +from AMatrix; + +.print Convert the matrix-like representation back to the (i,j,value) representation: +unpivot AMatrix on columns('^[1-9]') into name j VALUE value; + +.print The matrix-like representation of "A transpose": +pivot AT on j using max(value) order by i; diff --git a/Task/Matrix-transposition/DuckDB/matrix-transposition-3.duckdb b/Task/Matrix-transposition/DuckDB/matrix-transposition-3.duckdb new file mode 100644 index 0000000000..283efd0fab --- /dev/null +++ b/Task/Matrix-transposition/DuckDB/matrix-transposition-3.duckdb @@ -0,0 +1,5 @@ +# Note that if the input is not rectangular, the output might be lossy. +create or replace function transpose(lst) as ( + select list_transform( range(1, 1+length(lst[1])), + j -> list_transform(range(1, length(lst)+1), + i -> lst[i][j]) )); diff --git a/Task/Mayan-calendar/Rust/mayan-calendar.rs b/Task/Mayan-calendar/Rust/mayan-calendar.rs new file mode 100644 index 0000000000..ab94547baf --- /dev/null +++ b/Task/Mayan-calendar/Rust/mayan-calendar.rs @@ -0,0 +1,121 @@ +use chrono::{NaiveDate, Duration}; + +const TZOLKIN: [&str; 20] = [ + "Imix'", "Ik'", "Ak'bal", "K'an", "Chikchan", "Kimi", "Manik'", + "Lamat", "Muluk", "Ok", "Chuwen", "Eb", "Ben", "Hix", "Men", + "K'ib'", "Kaban", "Etz'nab'", "Kawak", "Ajaw" +]; + +const HAAB: [&str; 19] = [ + "Pop", "Wo'", "Sip", "Sotz'", "Sek", "Xul", "Yaxk'in", "Mol", + "Ch'en", "Yax", "Sak'", "Keh", "Mak", "K'ank'in", "Muwan", + "Pax", "K'ayab", "Kumk'u", "Wayeb'" +]; + +fn positive_modulus(base: i32, modulus: i32) -> i32 { + let result = base % modulus; + if result < 0 { + result + modulus + } else { + result + } +} + +fn create_date(iso_date: &str) -> NaiveDate { + let year: i32 = iso_date[0..4].parse().unwrap(); + let month: u32 = iso_date[5..7].parse().unwrap(); + let day: u32 = iso_date[8..10].parse().unwrap(); + + NaiveDate::from_ymd_opt(year, month, day).unwrap() +} + +fn days_per_mayan_month(month: &str) -> i32 { + if month == "Wayeb'" { 5 } else { 20 } +} + +fn tzolkin(gregorian: &NaiveDate) -> String { + let creation_tzolkin = create_date("2012-12-21"); + let days_between = (*gregorian - creation_tzolkin).num_days() as i32; + + let mut remainder = positive_modulus(days_between, 13); + remainder += if remainder <= 9 { 4 } else { -9 }; + + let tzolkin_name = TZOLKIN[positive_modulus(days_between - 1, 20) as usize]; + format!("{} {}", remainder, tzolkin_name) +} + +fn haab(gregorian: &NaiveDate) -> String { + let zero_haab = create_date("2019-04-02"); + let days_between = (*gregorian - zero_haab).num_days() as i32; + + let remainder = positive_modulus(days_between, 365); + let month = HAAB[positive_modulus(remainder + 1, 20) as usize]; + let day_of_month = remainder % 20 + 1; + + if day_of_month < days_per_mayan_month(month) { + format!("{} {}", day_of_month, month) + } else { + format!("Chum {}", month) + } +} + +fn long_count(gregorian: &NaiveDate) -> String { + let creation_tzolkin = create_date("2012-12-21"); + let mut days_between = (*gregorian - creation_tzolkin).num_days() as i32 + 13 * 360 * 400; + + let baktun = positive_modulus(days_between, 360 * 400); + days_between %= 360 * 400; + let katun = days_between / (20 * 360); + days_between %= 20 * 360; + let tun = days_between / 360; + days_between %= 360; + let winal = days_between / 20; + let kin = days_between % 20; + + let numbers = [baktun, katun, tun, winal, kin]; + let mut result = String::new(); + + for number in numbers { + let value = if number <= 9 { + format!("0{}.", number) + } else { + format!("{}.", number) + }; + result.push_str(&value); + } + + // Remove the last dot + result.pop(); + result +} + +fn lords_of_the_night(gregorian: &NaiveDate) -> String { + let creation_tzolkin = create_date("2012-12-21"); + let days_between = (*gregorian - creation_tzolkin).num_days() as i32; + let remainder = days_between % 9; + + let g_number = if remainder <= 0 { remainder + 9 } else { remainder }; + format!("G{}", g_number) +} + +fn main() { + let iso_dates = [ + "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", + "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16", "2020-02-02" + ]; + + println!("Gregorian Long Count Tzolk'in Haab' Lords of the Night"); + println!("------------------------------------------------------------------------------"); + + for iso_date in &iso_dates { + let date = create_date(iso_date); + + println!("{:<15}{:<19}{:<12}{:<18}{}", + iso_date, + long_count(&date), + tzolkin(&date), + haab(&date), + lords_of_the_night(&date) + ); + } +} diff --git a/Task/Mayan-numerals/FutureBasic/mayan-numerals.basic b/Task/Mayan-numerals/FutureBasic/mayan-numerals.basic new file mode 100644 index 0000000000..7be7005742 --- /dev/null +++ b/Task/Mayan-numerals/FutureBasic/mayan-numerals.basic @@ -0,0 +1,117 @@ +// +// Mayan numbers cartouche +// +// FutureBasic 7.0.34 July 2025 R.W + +CFStringRef cartouche (7) // array for cartouche + +// This is how the cartouche layout will +// be. It consists of 8 printed lines. + +cartouche(0)= @"║ Θ ║" // the number 0 +cartouche(1)= @"║ ● ║" // the number 1 +cartouche(2)= @"║ ● ● ║" // the number 2 +cartouche(3)= @"║ ● ● ● ║" // the number 3 +cartouche(4)= @"║ ● ● ● ● ║" // the number 4 +cartouche(5)= @"║━━━━━━━━━║" // the number 5 +cartouche(6)= @"╔═════════╗" // top line +cartouche(7)= @"╚═════════╝" // bottom line + +// +// Converts decimal number to vigesimal +// +// On entry: n is a decimal number +// On exit: result as a string of vigesimal +// separated by space +// +local fn decToVigesimal(n as long) as CFStringRef + CFStringRef result + result = @"": if n == 0 then result = @" 0" + while n > 0 + result = concat(str(n % 20),result) + n = fix (n/20) + wend +end fn = result + +// +// Converts vigesimal to a Mayan cartouche +// +// On entry: n is a vigesimal string separated by spaces +// On exit: Mayan cartouche drawn (horizontally) +// + +local fn VigesimalToMayan(n as CFStringRef) + Int m, x, y, idx, al, ov + boolean done = _False + CFStringRef disg (6,15) + CFStringRef vn + CFArrayRef myArray + + myArray = fn StringComponentsSeparatedByString(n,@" ") + al = len(myArray) - 1 + + vn = @"" + for m = 1 to al + done = _False + vn = myArray [m] + idx = intval(vn) + ov = idx + disg (0,m) = cartouche(6) + + for x = 4 to 1 step -1 + + disg (x,m) = @"║ ║" + if ov == 0 + if !done then disg(x,m) = cartouche(0) + done = _True + end if + + if idx > 4 + disg(x,m) = cartouche(5) + idx = idx - 5 + else + y = idx % 5 + if y > 0 + if !done then disg(x,m) = cartouche (y) + done = _True + end if + end if + next x + disg (5,m) = cartouche(7) + next m + + for x = 0 to 5 + for m = 1 to al + print disg(x,m); + next m + print + next x +end fn + + +window 1 + +// Test data + +CFStringRef Vigesimal +print "Converting 4005 to Mayan" +Vigesimal = fn decToVigesimal(4005) +fn VigesimalToMayan (Vigesimal) + +print "Converting 8017 to Mayan" +Vigesimal = fn decToVigesimal(8017) +fn VigesimalToMayan (Vigesimal) + +print "Converting 326205 to Mayan" +Vigesimal = fn decToVigesimal(326205) +fn VigesimalToMayan (Vigesimal) + +print "Converting 886205 to Mayan" +Vigesimal = fn decToVigesimal(886205) +fn VigesimalToMayan (Vigesimal) + +print "Interesting looking Mayan number" +Vigesimal = fn decToVigesimal(717784) +fn VigesimalToMayan (Vigesimal) + +handleEvents diff --git a/Task/McNuggets-problem/Fortran/mcnuggets-problem.f b/Task/McNuggets-problem/Fortran/mcnuggets-problem.f new file mode 100644 index 0000000000..1010851e87 --- /dev/null +++ b/Task/McNuggets-problem/Fortran/mcnuggets-problem.f @@ -0,0 +1,64 @@ +program mcnugget + ! Program to find non-McNugget numbers (up to 100) that cannot be expressed as + ! 6x + 9y + 20z (with x, y, z non-negative integers). This version uses dynamic + ! programming to mark expressible numbers and then uses FINDLOC on a logical mask + ! (derived by applying .NOT. to the expressible array) to obtain the largest + ! non-expressible number. + + implicit none + integer, parameter :: n = 100 + logical :: expressible(0:n) ! Mark if each number 0:n is expressible. + integer :: max_val ! To store the largest non-expressible number. + integer :: i, j ! Loop indices. + integer :: denoms(3) ! Array of denominations: 6, 9, 20. + integer, allocatable :: loc(:) + ! 'loc' will store the indices returned by FINDLOC. + + !-------------------------------------------------------------------- + ! Initialize the denominations and print them. + !-------------------------------------------------------------------- + denoms = [6, 9, 20] + print *, 'Nugget pacet sizes: ', denoms + + !-------------------------------------------------------------------- + ! Initialize all numbers as non-expressible except 0. + ! 0 is expressible (with x = y = z = 0). + !-------------------------------------------------------------------- + expressible = .false. + expressible(0) = .true. + + !-------------------------------------------------------------------- + ! Dynamic programming: + ! For each denomination, if a number i is expressible then mark + ! i + denomination as expressible (provided it does not exceed n). + !-------------------------------------------------------------------- + do j = 1, 3 + do i = 0, n - denoms(j) + if (expressible(i)) then + expressible(i + denoms(j)) = .true. + end if + end do + end do + + !-------------------------------------------------------------------- + ! Instead of looping to count and store non-expressible numbers, + ! we use the FINDLOC intrinsic to get the largest index for which + ! the number is NOT expressible. + ! + ! The expression (.not. expressible) creates a logical mask that is .true. + ! when a number is non-expressible. FINDLOC with BACK=.TRUE. searches the + ! array in reverse order (from n down to 0), thus returning the maximum index. + !-------------------------------------------------------------------- + loc = findloc(.not. expressible, .true., back = .true.) + if (size(loc) > 0) then + max_val = loc(1) ! Retrieve the largest non-expressible number. + else + max_val = 0 ! In the unlikely event that every number is expressible. + end if + + !-------------------------------------------------------------------- + ! Output the result (only the largest non-McNugget number). + !-------------------------------------------------------------------- + print *, 'Maximum non-McNuggets number is ', max_val + +end program mcnugget diff --git a/Task/Meissel-Mertens-constant/JavaScript/meissel-mertens-constant.js b/Task/Meissel-Mertens-constant/JavaScript/meissel-mertens-constant.js new file mode 100644 index 0000000000..485e2c3aed --- /dev/null +++ b/Task/Meissel-Mertens-constant/JavaScript/meissel-mertens-constant.js @@ -0,0 +1,135 @@ +function main() { + // Use a smaller limit to avoid memory issues + // For demonstration, using 10 million instead of 1 billion + const limit = 10_000_000; + const primeReciprocals = listPrimeReciprocals(limit); + const euler = 0.577215664901532861; + let sum = 0.0; + + for (const reciprocal of primeReciprocals) { + sum += reciprocal + Math.log(1.0 - reciprocal); + } + + const meisselMertens = euler + sum; + console.log(`The Meissel-Mertens constant = ${meisselMertens.toFixed(9)}`); + console.log(`Calculated with primes up to: ${limit.toLocaleString()}`); +} + +function listPrimeReciprocals(limit) { + const segmentSize = Math.min(1_000_000, limit); // Process in 1M chunks + const result = []; + + // First, find all primes up to sqrt(limit) for marking composites + const sqrtLimit = Math.floor(Math.sqrt(limit)); + const basePrimes = sieveOfEratosthenes(sqrtLimit); + + // Process the range in segments + for (let segStart = 2; segStart <= limit; segStart += segmentSize) { + const segEnd = Math.min(segStart + segmentSize - 1, limit); + const segmentPrimes = segmentedSieve(segStart, segEnd, basePrimes); + + // Add reciprocals of primes found in this segment + for (const prime of segmentPrimes) { + result.push(1.0 / prime); + } + } + + return result; +} + +function sieveOfEratosthenes(limit) { + const sieve = new Array(limit + 1).fill(true); + sieve[0] = sieve[1] = false; + + for (let i = 2; i * i <= limit; i++) { + if (sieve[i]) { + for (let j = i * i; j <= limit; j += i) { + sieve[j] = false; + } + } + } + + const primes = []; + for (let i = 2; i <= limit; i++) { + if (sieve[i]) { + primes.push(i); + } + } + + return primes; +} + +function segmentedSieve(segStart, segEnd, basePrimes) { + const segmentSize = segEnd - segStart + 1; + const sieve = new Array(segmentSize).fill(true); + + // Mark multiples of each base prime in this segment + for (const prime of basePrimes) { + // Find the first multiple of prime >= segStart + let start = Math.max(prime * prime, Math.ceil(segStart / prime) * prime); + + // Mark all multiples in this segment + for (let j = start; j <= segEnd; j += prime) { + sieve[j - segStart] = false; + } + } + + // Collect primes from this segment + const primes = []; + for (let i = 0; i < segmentSize; i++) { + if (sieve[i] && (segStart + i) >= 2) { + primes.push(segStart + i); + } + } + + return primes; +} + +// Alternative version with even more memory efficiency +function mainMemoryEfficient() { + const limit = 100_000_000; // Can handle larger limits + const euler = 0.577215664901532861; + let sum = 0.0; + let primeCount = 0; + + // Process primes incrementally without storing them all + processPrimesInSegments(limit, (prime) => { + const reciprocal = 1.0 / prime; + sum += reciprocal + Math.log(1.0 - reciprocal); + primeCount++; + + // Progress indicator for large calculations + if (primeCount % 100000 === 0) { + console.log(`Processed ${primeCount.toLocaleString()} primes...`); + } + }); + + const meisselMertens = euler + sum; + console.log(`The Meissel-Mertens constant = ${meisselMertens.toFixed(9)}`); + console.log(`Calculated with ${primeCount.toLocaleString()} primes up to: ${limit.toLocaleString()}`); +} + +function processPrimesInSegments(limit, callback) { + const segmentSize = 1_000_000; + const sqrtLimit = Math.floor(Math.sqrt(limit)); + const basePrimes = sieveOfEratosthenes(sqrtLimit); + + // Process first segment (includes base primes) + for (const prime of basePrimes) { + callback(prime); + } + + // Process remaining segments + for (let segStart = sqrtLimit + 1; segStart <= limit; segStart += segmentSize) { + const segEnd = Math.min(segStart + segmentSize - 1, limit); + const segmentPrimes = segmentedSieve(segStart, segEnd, basePrimes); + + for (const prime of segmentPrimes) { + callback(prime); + } + } +} + +// Run the memory-efficient version +console.log("Running memory-efficient version..."); +mainMemoryEfficient(); diff --git a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx index 1c5d19a827..58523cec16 100644 --- a/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx +++ b/Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx @@ -1,13 +1,13 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings - -say 'MEISSEL-MERTENS CONSTANT' -say version -say arg n if n = '' then n = 16 numeric digits n + +say 'MEISSEL-MERTENS CONSTANT' +say version +say fact. = 0 call Time('r'); a = BruteForce(); e = Format(Time('e'),,3) say 'BruteForce' a '('e 'seconds)' @@ -20,7 +20,7 @@ say 'True value' a '('e 'seconds)' exit BruteForce: -procedure expose glob. +procedure expose Memo. numeric digits Digits()+2 y = 0.5-Ln(2) do n = 3 by 2 to 1000000 @@ -33,7 +33,7 @@ numeric digits Digits()-2 return y+0 UsingSieve: -procedure expose glob. prim. flag. +procedure expose Memo. prim. flag. numeric digits Digits()+2 n = Primes(1000000); y = 0 do i = 1 to n @@ -44,7 +44,7 @@ numeric digits Digits()-2 return y+0 Analytic: -procedure expose glob. fact. +procedure expose Memo. fact. numeric digits Digits()+2 y = 0; v = 0 do n = 2 to 1000 @@ -64,9 +64,4 @@ TrueValue: procedure return 0.261497212847642783755426838608695859051566648261199206192064213924924510897368209714142631434246651051617+0 -include Constants -include Functions -include Special -include Numbers -include Sequences -include Abend +include Math diff --git a/Task/Meissel-Mertens-constant/Rust/meissel-mertens-constant.rs b/Task/Meissel-Mertens-constant/Rust/meissel-mertens-constant.rs new file mode 100644 index 0000000000..99dea98352 --- /dev/null +++ b/Task/Meissel-Mertens-constant/Rust/meissel-mertens-constant.rs @@ -0,0 +1,39 @@ +fn list_prime_reciprocals(limit: i32) -> Vec { + let half_limit = if limit % 2 == 0 { limit / 2 } else { 1 + limit / 2 }; + let mut composite = vec![false; half_limit as usize]; + + for i in 1..half_limit as usize { + let p = 3 + 2 * (i as i32 - 1); + if !composite[i] { + let mut a = i + p as usize; + while a < half_limit as usize { + composite[a] = true; + a += p as usize; + } + } + } + + let mut result = Vec::with_capacity(half_limit as usize); + result.push(0.5); // Add 1/2 for prime number 2 + + for i in 1..half_limit as usize { + let p = 3 + 2 * (i as i32 - 1); + if !composite[i] { + result.push(1.0 / p as f64); + } + } + + result +} + +fn main() { + let prime_reciprocals = list_prime_reciprocals(100000000); + let euler = 0.577215664901532861; + + let sum: f64 = prime_reciprocals.iter() + .map(|&reciprocal| reciprocal + (1.0 - reciprocal).ln()) + .sum(); + + let meissel_mertens = euler + sum; + println!("The Meissel-Mertens constant = {:.8}", meissel_mertens); +} diff --git a/Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb b/Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb new file mode 100644 index 0000000000..1327975d1c --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/DuckDB/merge-and-aggregate-datasets.duckdb @@ -0,0 +1,32 @@ +.print Since the patients.csv file is quite ordinary, it can be imported without fuss. + +create or replace table patients as + FROM 'patients.csv'; + +.print Taking the same approach with visits.csv illustrates how DuckDB correctly infers the types, including the date: + +create or replace table visits as + FROM 'visits.csv'; + +from visits; + +.print +.print Merge and group per patient id and last name, +.print get the maximum visit date, and +.print get the sum and average of the scores per patient to get the resulting dataset. + +SELECT + p.PATIENT_ID, + p.LASTNAME, + MAX(VISIT_DATE) AS LAST_VISIT, + SUM(SCORE) AS SCORE_SUM, + CAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG +FROM + patients p + LEFT JOIN visits v + ON v.PATIENT_ID = p.PATIENT_ID +GROUP BY + p.PATIENT_ID, + p.LASTNAME +ORDER BY + p.PATIENT_ID; diff --git a/Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb b/Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb new file mode 100644 index 0000000000..ef559e03bb --- /dev/null +++ b/Task/Metallic-ratios/DuckDB/metallic-ratios-1.duckdb @@ -0,0 +1,5 @@ +create or replace table metals as + (select (row_number() over () - 1) as b, name + from unnest( + ['Platinum', 'Golden', 'Silver', 'Bronze', 'Copper','Nickel', 'Aluminium', 'Iron', 'Tin', 'Lead'] + ) _(name) ); diff --git a/Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb b/Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb new file mode 100644 index 0000000000..59306a60ac --- /dev/null +++ b/Task/Metallic-ratios/DuckDB/metallic-ratios-2.duckdb @@ -0,0 +1,24 @@ +# The Lucas-like function as per the task description +create or replace function lucas(b, n) as table ( + with recursive cte as ( + select 1 as ix, 1::HUGEINT as i, 1::HUGEINT as j + union all + select + ix+1, + j as i, + i + b*j as j + from cte + where ix < n) + select ix, i + from cte +); + +# The successive metallic ratio approximations +create or replace function metallic_ratio(b, n) as table ( + select i / (lag(i) over ()) + from lucas(b,n) +); + +.maxwidth 200 +select b, (select array_agg(i) from lucas(b, 15)) as "lucas-like" +from range(0, 10) _(b); diff --git a/Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb b/Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb new file mode 100644 index 0000000000..303b9058b4 --- /dev/null +++ b/Task/Metallic-ratios/DuckDB/metallic-ratios-3.duckdb @@ -0,0 +1,28 @@ +# ix serves both as a rowid and as the count of the number of +# iterations required to achieve the corresponding ratio +create or replace function metallic_ratio_to_quiescence(b) as ( + with recursive cte as ( + select + -1::HUGEINT as ix, + 1::HUGEINT as previ, + 1::HUGEINT as i, + 1::HUGEINT as j, + 1::DOUBLE as prevratio, + 1::DOUBLE as ratio + union all + select + ix+1, + i as previ, + j as i, + i + b*j as j, + ratio as prevratio, + (i::DOUBLE / previ) as ratio + from cte + where (ix < 4 or prevratio != ratio) + ) + select last((ix, ratio)) + from cte +); + +select b, name, metallic_ratio_to_quiescence(b) +from metals; diff --git a/Task/Metaprogramming/V-(Vlang)/metaprogramming.v b/Task/Metaprogramming/V-(Vlang)/metaprogramming.v new file mode 100644 index 0000000000..fd8e734c3b --- /dev/null +++ b/Task/Metaprogramming/V-(Vlang)/metaprogramming.v @@ -0,0 +1,30 @@ +@[heap] +struct Foo { +} + +fn (f Foo) test() int { + return 123 +} + +fn (f Foo) test2() string { + return "foo" +} + +fn main() { + foo := Foo{} + + $if ios || android {println("Running on a mobile device!")} + $if linux && x64 {println("64-bit Linux.")} + os := $if windows {"Windows"} $else {"Something Else"} + println("Using ${os}") + + $for m in Foo.methods { + $if m.return_type is int { + print("${m.name} returns int: ") + println(foo.$method()) + } $else $if m.return_type is string { + print("${m.name} returns string: ") + println(foo.$method()) + } + } +} diff --git a/Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena b/Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena new file mode 100644 index 0000000000..b81c43d6ff --- /dev/null +++ b/Task/Mian-Chowla-sequence/Agena/mian-chowla-sequence.agena @@ -0,0 +1,31 @@ +scope /* Find Mian-Chowla numbers: an + * where: ai = 1, + * and: an = smallest integer such that ai + aj is unique + * for all i, j in 1 .. n && i <= j + */ + + local maxMc, mcCount, mc, isSum := 100, 1, seq(), seq(); + for i while mcCount <= maxMc do + # assume i will be part of the sequence + mc[ mcCount ] := i; + # check the sums + local isUnique := true + for mcPos to mcCount while isUnique do + if isSum[ i + mc[ mcPos ] ] then + isUnique := false + fi + od; + if isUnique then + # i is a sequence element - store the sums + for k to mcCount do isSum[ i + mc[ k ] ] := true od; + mcCount +:= 1 + fi + od; + + # print parts of the sequence + printf( "Mian Chowla sequence elements 1..30:\n" ); + for i to 30 do printf( " %d", mc[ i ] ) od; + printf( "\nMian Chowla sequence elements 91..100:\n" ); + for i from 91 to 100 do printf( " %d", mc[ i ] ) od + +end diff --git a/Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto b/Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto new file mode 100644 index 0000000000..f4664e2ee8 --- /dev/null +++ b/Task/Mian-Chowla-sequence/Pluto/mian-chowla-sequence.pluto @@ -0,0 +1,35 @@ +do --[[ Find Mian-Chowla numbers: an + where: ai = 1, + and: an = smallest integer such that ai + aj is unique + for all i, j in 1 .. n && i <= j + ]] + local fmt = require( "fmt" ) + + local maxMc, mcCount, mc, isSum = 100, 1, {}, {} + local i = 0 + while mcCount <= maxMc do + ++ i + -- assume i will be part of the sequence + mc[ mcCount ] = i + -- check the sums + local isUnique = true + for mcPos = 1, mcCount do + if isSum[ i + mc[ mcPos ] ] then + isUnique = false + break + end + end + if isUnique then + -- i is a sequence element - store the sums + for k = 1, mcCount do isSum[ i + mc[ k ] ] = true end + ++ mcCount + end + end + + -- print parts of the sequence + io.write( "Mian Chowla sequence elements 1..30:\n " ) + fmt.lprint( table.slice( mc, 1, 30 ), " ", "" ) + io.write( "Mian Chowla sequence elements 91..100:\n " ) + fmt.lprint( table.slice( mc, 91, 100 ), " ", "" ) + +end diff --git a/Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb b/Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb new file mode 100644 index 0000000000..82b43f646d --- /dev/null +++ b/Task/Middle-three-digits/DuckDB/middle-three-digits.duckdb @@ -0,0 +1,22 @@ +create or replace function middle3digits_helper(s) as ( + select if (invalid_character, 'invalid character found', + if (invalid_n, 'invalid number of digits', + s[p+1 : p+3])) as result + from (select + regexp_matches(s, '[^0-9]') as invalid_character, + (length(s) < 3 or (length(s) % 2 = 0)) as invalid_n, + (length(s) - 3) // 2 as p + ) +); + +create or replace function middle3digits(number) as ( + middle3digits_helper(replace(trim(number::VARCHAR),'-','')) +); + +## Examples +select middle3digits('xyzzy'); + +select n, middle3digits(n) +from unnest( [ + 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, + 1, 2, -1, -10, 2002, -2002, 0 ]) _(n) ; diff --git a/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-3.hs b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-3.hs new file mode 100644 index 0000000000..0c755fd19d --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-3.hs @@ -0,0 +1,15 @@ +mrt 2 = True +mrt x = odd x && all (\a -> work s x (expMod a d x) ) [2..(x-2)] where + (s,d) = sd (x-1) + +sd n = if odd n then (0,n) else (\(x,y) -> (x+1,y)) (sd (n `div` 2)) +work 0 n x = (x == 1) || (x == n-1) +work s n x + |(f == 1) && (x /= 1) && (x /= n-1) = False + |otherwise = work (s-1) n f where f = (x*x) `mod` n + + +expMod a 0 m = 1 +expMod a d m + | even d = expMod ((a * a) `mod` m) (d `div` 2) m + | otherwise = (a * expMod a (d - 1) m) `mod` m diff --git a/Task/Minesweeper-game/Liberty-BASIC/minesweeper-game.basic b/Task/Minesweeper-game/Liberty-BASIC/minesweeper-game.basic new file mode 100644 index 0000000000..d53ac07241 --- /dev/null +++ b/Task/Minesweeper-game/Liberty-BASIC/minesweeper-game.basic @@ -0,0 +1,422 @@ +' =============================== +' MINESWEEPER - Liberty BASIC +' =============================== + +' --- Constants --- +global cellSize, gridWidth, gridHeight, infoBarHeight +global totalMines, WindowWidth, WindowHeight, gameStatus$, minesLeft + +cellSize = 20 +gridWidth = 18 +gridHeight = 12 +infoBarHeight = 40 +totalMines = 16 + int(rnd(0)*4) + +WindowWidth = gridWidth * cellSize + 20 +WindowHeight = gridHeight * cellSize + infoBarHeight + 38 + +' --- Game State --- +dim mineGrid(gridWidth, gridHeight) +dim adjacentCount(gridWidth, gridHeight) +dim revealed(gridWidth, gridHeight) +dim marked(gridWidth, gridHeight) + +minesLeft = totalMines +gameStatus$ = "Playing..." + +' --- Start Program --- +call setupGame +call drawGameWindow + +wait + +' ------------------------------- +' SUB: Setup the Game +' ------------------------------- +sub setupGame + for x = 1 to gridWidth + for y = 1 to gridHeight + mineGrid(x, y) = 0 + adjacentCount(x, y) = 0 + revealed(x, y) = 0 + marked(x, y) = 0 + next + next + + minesPlaced = 0 + while minesPlaced < totalMines + rx = int(rnd(0) * gridWidth) + 1 + ry = int(rnd(0) * gridHeight) + 1 + + if mineGrid(rx, ry) = 0 then + mineGrid(rx, ry) = 1 + minesPlaced = minesPlaced + 1 + end if + wend + + for x = 1 to gridWidth + for y = 1 to gridHeight + if mineGrid(x, y) = 0 then + count = 0 + for dx = -1 to 1 + for dy = -1 to 1 + nx = x + dx + ny = y + dy + if nx >= 1 and nx <= gridWidth and ny >= 1 and ny <= gridHeight then + if mineGrid(nx, ny) = 1 then + count = count + 1 + end if + end if + next + next + adjacentCount(x, y) = count + end if + next + next +end sub + +' ------------------------------- +' SUB: Draw Game Window +' ------------------------------- +sub drawGameWindow + open "Minesweeper" for graphics_nf_nsb as #game + #game "down; fill white" + #game "trapclose [quit]" + #game "when leftButtonDown [leftClick]" + #game "when rightButtonDown [rightClick]" + + call drawInfoBar + call drawGrid +end sub + +' ------------------------------- +' SUB: Draw Info Bar +' ------------------------------- +sub drawInfoBar + #game "color black; backcolor white" + info$ = "Mines Left: "; minesLeft; " Status: "; gameStatus$ + #game "place 10 20" + #game "\"; info$ +end sub + +' ------------------------------- +' SUB: Draw Grid +' ------------------------------- +sub drawGrid + for x = 1 to gridWidth + for y = 1 to gridHeight + px = 6 + (x - 1) * cellSize + py = infoBarHeight + (y - 1) * cellSize + + #game "color black; backcolor lightgray" + #game "place "; px; " "; py + #game "boxfilled "; px + cellSize; " "; py + cellSize + next + next +end sub + +' ------------------------------- +' HANDLER: Left Mouse Click +' ------------------------------- +[leftClick] + if gameStatus$ <> "Playing..." then + call askPlayAgain + wait + end if + + mouseX = MouseX + mouseY = MouseY + + gridLeft = 6 + gridTop = infoBarHeight + gridRight = gridLeft + gridWidth * cellSize + gridBottom = gridTop + gridHeight * cellSize + + if mouseX >= gridLeft and mouseX < gridRight and _ + mouseY >= gridTop and mouseY < gridBottom then + + cellX = int((mouseX - gridLeft) / cellSize) + 1 + cellY = int((mouseY - gridTop) / cellSize) + 1 + + call revealCell cellX, cellY + call checkWin + end if + + wait + +' ------------------------------- +' HANDLER: Right Mouse Click +' ------------------------------- +[rightClick] + if gameStatus$ <> "Playing..." then + call askPlayAgain + wait + end if + + mouseX = MouseX + mouseY = MouseY + + gridLeft = 6 + gridTop = infoBarHeight + gridRight = gridLeft + gridWidth * cellSize + gridBottom = gridTop + gridHeight * cellSize + + if mouseX >= gridLeft and mouseX < gridRight and _ + mouseY >= gridTop and mouseY < gridBottom then + + cellX = int((mouseX - gridLeft) / cellSize) + 1 + cellY = int((mouseY - gridTop) / cellSize) + 1 + + call toggleMark cellX, cellY + call checkWin + end if + + wait + +' ------------------------------- +' HANDLER: Close Window +' ------------------------------- +[quit] + close #game + end + +' ------------------------------- +' SUB: Reveal All Mines +' ------------------------------- +sub revealAllMines + for x = 1 to gridWidth + for y = 1 to gridHeight + if mineGrid(x, y) = 1 then + call drawMine x, y + end if + next + next +end sub + +' ------------------------------- +' SUB: Draw Mine Symbol +' ------------------------------- +sub drawMine x, y + px = 6 + (x - 1) * cellSize + py = infoBarHeight + (y - 1) * cellSize + + #game "color black; backcolor lightgray" + #game "place "; px; " "; py + #game "boxfilled "; px + cellSize; " "; py + cellSize + + #game "color red" + tx = px + 5 + ty = py + 15 + #game "place "; tx; " "; ty + #game "\"; "M" +end sub + +' ------------------------------- +' SUB: Reveal All Numbers +' ------------------------------- +sub revealAllNumbers + for x = 1 to gridWidth + for y = 1 to gridHeight + if mineGrid(x, y) = 1 then + call drawMine x, y + else + call drawNumber x, y, adjacentCount(x, y) + end if + next + next +end sub + +' ------------------------------- +' SUB: Draw Cell Number +' ------------------------------- +sub drawNumber x, y, n + px = 6 + (x - 1) * cellSize + py = infoBarHeight + (y - 1) * cellSize + + #game "color black; backcolor white" + #game "place "; px; " "; py + #game "boxfilled "; px + cellSize; " "; py + cellSize + + if n > 0 then + #game "color blue" + tx = px + 6 + ty = py + 15 + #game "place "; tx; " "; ty + #game "\"; str$(n) + end if +end sub + +' ------------------------------- +' SUB: Reveal a Single Cell +' ------------------------------- +sub revealCell x, y + if gameStatus$ <> "Playing..." then exit sub + if revealed(x, y) = 1 then exit sub + if marked(x, y) = 1 then exit sub + + revealed(x, y) = 1 + + if mineGrid(x, y) = 1 then + call animateBoom x, y + gameStatus$ = "BOOM!!! Game Over!" + call revealAllMines + call drawInfoBar + exit sub + end if + + call drawNumber x, y, adjacentCount(x, y) + + if adjacentCount(x, y) = 0 then + for dx = -1 to 1 + for dy = -1 to 1 + nx = x + dx + ny = y + dy + if nx >= 1 and nx <= gridWidth and ny >= 1 and ny <= gridHeight then + if revealed(nx, ny) = 0 then + call revealCell nx, ny + end if + end if + next + next + end if +end sub + +' ------------------------------- +' SUB: Check for Win Condition +' ------------------------------- +sub checkWin + safeCells = 0 + revealedSafeCells = 0 + + for x = 1 to gridWidth + for y = 1 to gridHeight + if mineGrid(x, y) = 0 then + safeCells = safeCells + 1 + if revealed(x, y) = 1 then + revealedSafeCells = revealedSafeCells + 1 + end if + end if + next + next + + if revealedSafeCells = safeCells then + gameStatus$ = "You Win!" + call drawInfoBar + call revealAllMines + end if +end sub + +' ------------------------------- +' SUB: Mark or unmark a cell +' ------------------------------- +sub toggleMark x, y + if gameStatus$ <> "Playing..." then exit sub + if revealed(x, y) = 1 then exit sub + + if marked(x, y) = 0 then + marked(x, y) = 1 + minesLeft = minesLeft - 1 + call drawMark x, y + else + marked(x, y) = 0 + minesLeft = minesLeft + 1 + call drawHidden x, y + end if + + call drawInfoBar +end sub + +' ------------------------------- +' SUB: Draw a Mark ("?") +' ------------------------------- +sub drawMark x, y + px = 6 + (x - 1) * cellSize + py = infoBarHeight + (y - 1) * cellSize + + #game "color black; backcolor yellow" + #game "place "; px; " "; py + #game "boxfilled "; px + cellSize; " "; py + cellSize + + #game "color red" + tx = px + 6 + ty = py + 15 + #game "place "; tx; " "; ty + #game "\"; "?" +end sub + +' ------------------------------- +' SUB: Draw Hidden Cell +' ------------------------------- +sub drawHidden x, y + px = 6 + (x - 1) * cellSize + py = infoBarHeight + (y - 1) * cellSize + + #game "color black; backcolor lightgray" + #game "place "; px; " "; py + #game "boxfilled "; px + cellSize; " "; py + cellSize +end sub + +' ------------------------------- +' SUB: Animate a Boom +' ------------------------------- +sub animateBoom x, y + #game "flush" + + px = 6 + (x - 1) * cellSize + py = infoBarHeight + (y - 1) * cellSize + + centerX = px + cellSize/2 + centerY = py + cellSize/2 + + #game "color red" + steps = 12 + + #game "backcolor red" + for i = 1 to steps + radius = i * 2 + #game "place "; centerX; " "; centerY + #game "circlefilled "; radius + timer 5, [continueBoom1] + wait + [continueBoom1] + timer 0 + next + + #game "backcolor white" + for i = 1 to steps + radius = i * 2 + #game "place "; centerX; " "; centerY + #game "circlefilled "; radius + timer 5, [continueBoom2] + wait + [continueBoom2] + timer 0 + next + + #game "redraw" +end sub + +' ------------------------------- +' SUB: Ask to Play Again +' ------------------------------- +sub askPlayAgain + confirm "Play again?"; answer + if answer = 1 then + call restartGame + else + close #game + end + end if +end sub + +' ------------------------------- +' SUB: Restart the Game +' ------------------------------- +sub restartGame + minesLeft = totalMines + gameStatus$ = "Playing..." + + call setupGame + call drawGrid + call drawInfoBar +end sub diff --git a/Task/Minimal-steps-down-to-1/Ada/minimal-steps-down-to-1.ada b/Task/Minimal-steps-down-to-1/Ada/minimal-steps-down-to-1.ada new file mode 100644 index 0000000000..6cc81a9446 --- /dev/null +++ b/Task/Minimal-steps-down-to-1/Ada/minimal-steps-down-to-1.ada @@ -0,0 +1,108 @@ +with Ada.Text_IO; + +procedure Steps_To_One is + type Steps_Array is array (Positive range <>) of Natural; + type Steps (N : Positive) is record + Div1, Div2, Sub : Positive; + Tab : Steps_Array (1 .. N); + end record; + + Table1 : Steps := + ( + N => 2000, + Div1 => 3, + Div2 => 2, + Sub => 1, + Tab => (1 => 0, others => Natural'Last) + ); + + Table2 : Steps := + ( + N => 2000, + Div1 => 3, + Div2 => 2, + Sub => 2, + Tab => (1 => 0, others => Natural'Last) + ); + + procedure Fill (Table : in out Steps) is + Min_Steps : Natural; + begin + for I in 2 .. Table.Tab'Last loop + Min_Steps := Natural'Last; + + if I mod Table.Div1 = 0 then + Min_Steps := Natural'Min (Min_Steps, Table.Tab (I / Table.Div1)); + end if; + + if I mod Table.Div2 = 0 then + Min_Steps := Natural'Min (Min_Steps, Table.Tab (I / Table.Div2)); + end if; + + if I - Table.Sub >= 1 then + Min_Steps := Natural'Min (Min_Steps, Table.Tab (I - Table.Sub)); + end if; + + Table.Tab (I) := 1 + Min_Steps; + end loop; + end Fill; + + procedure Show_Steps (Table : Steps; Limit : Positive) is + Min_Steps : Natural; + Trace : Positive; + begin + for I in 1 .. Limit loop + Min_Steps := Table.Tab (I); + Trace := I; + Ada.Text_IO.Put (I'Image & " [" & Min_Steps'Image & " steps ]: "); + + for J in 1 .. Table.Tab (I) loop + Ada.Text_IO.Put (Trace'Image); + Min_Steps := Table.Tab (Trace); + + if Trace mod Table.Div1 = 0 and then + Min_Steps = 1 + Table.Tab (Trace / Table.Div1) then + Ada.Text_IO.Put (" /" & Table.Div1'Image); + Trace := Trace / Table.Div1; + elsif Trace mod Table.Div2 = 0 and then + Min_Steps = 1 + Table.Tab (Trace / Table.Div2) then + Ada.Text_IO.Put ( " /" & Table.Div2'Image); + Trace := Trace / Table.Div2; + else + Ada.Text_IO.Put (" -" & Table.Sub'Image); + Trace := Trace - Table.Sub; + end if; + + Ada.Text_IO.Put (" =>"); + end loop; + + Ada.Text_IO.New_Line; + end loop; + end Show_Steps; + + procedure Show_Max_Min (Table : Steps) is + Max_Min : Natural := 0; + begin + for I of Table.Tab loop + Max_Min := Natural'Max (Max_Min, I); + end loop; + + Ada.Text_IO.Put ("Numbers with maximum minimal steps [" & Max_Min'Image & " ]: "); + + for I in Table.Tab'Range loop + if Max_Min = Table.Tab (I) then + Ada.Text_IO.Put (I'Image & ", "); + end if; + end loop; + + Ada.Text_IO.New_Line; + end Show_Max_Min; + +begin + Fill (Table1); + Show_Steps (Table1, 10); + Show_Max_Min (Table1); + Fill (Table2); + Show_Steps (Table2, 10); + Show_Max_Min (Table2); +end Steps_To_One; diff --git a/Task/Modular-arithmetic/00-TASK.txt b/Task/Modular-arithmetic/00-TASK.txt index 88e5dc547b..d2245933b1 100644 --- a/Task/Modular-arithmetic/00-TASK.txt +++ b/Task/Modular-arithmetic/00-TASK.txt @@ -1,10 +1,10 @@ '''[[wp:Modular arithmetic|Modular arithmetic]]''' is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined [[wp:equivalence relation|equivalence relation]] called ''congruence''. -For any positive integer p called the ''congruence modulus'', -two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that: -:a = b + k\,p +For any positive integer m called the ''congruence modulus'', +two numbers a and b are said to be ''congruent modulo m'' whenever there exists an integer k such that: +:a = b + k\,m -The corresponding set of [[wp:equivalence class|equivalence class]]es forms a [[wp:ring (mathematics)|ring]] denoted \frac{\Z}{p\Z}. When p is a prime number, this ring becomes a [[wp:field (mathematics)|field]] denoted \mathbb{F}_p, but you won't have to implement the [[wp:multiplicative inverse|multiplicative inverse]] for this task. +The corresponding set of [[wp:equivalence class|equivalence class]]es forms a [[wp:ring (mathematics)|ring]] denoted \Z/m\Z. When q=p^k \,(k>0) is a prime power, the ring \Z/q\Z becomes a [[wp:Finite field|finite field]], usually denoted \mathbb{F}_q or \mathrm{GF}(q), but you won't have to implement the [[wp:multiplicative inverse|multiplicative inverse]] for this task. Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result. @@ -22,3 +22,4 @@ In other words, the function is an algebraic expression that could be used with ;Related tasks: [[Modular exponentiation]]

    + diff --git a/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic.lisp b/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-1.lisp similarity index 100% rename from Task/Modular-arithmetic/Common-Lisp/modular-arithmetic.lisp rename to Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-1.lisp diff --git a/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp b/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp new file mode 100644 index 0000000000..3f60d21d14 --- /dev/null +++ b/Task/Modular-arithmetic/Common-Lisp/modular-arithmetic-2.lisp @@ -0,0 +1,25 @@ +(defpackage :rosetta-code/modular-arithmetic + (:use :cl)) + +(in-package :rosetta-code/modular-arithmetic) + +(defparameter *modulus* nil) + +(defun make-modular (op) + (lambda (&rest args) + (let ((result (apply op args))) + (if *modulus* + (mod result *modulus*) + result)))) + +(let ((ops '(+ expt))) ; add more operators as you need + (shadow ops) + (dolist (op ops) + (setf (symbol-function (find-symbol (symbol-name op))) + (make-modular (symbol-function (find-symbol (symbol-name op) :cl)))))) + +(defun f (x) + (+ (expt x 100) x 1)) + +(format t "No modulus: f(~a) = ~a~%" 10 (f 10)) +(format t "Modulus 13: f(~a) = ~a~%" 10 (let ((*modulus* 13)) (f 10))) diff --git a/Task/Modular-arithmetic/Rust/modular-arithmetic.rs b/Task/Modular-arithmetic/Rust/modular-arithmetic.rs new file mode 100644 index 0000000000..8995f8eb57 --- /dev/null +++ b/Task/Modular-arithmetic/Rust/modular-arithmetic.rs @@ -0,0 +1,177 @@ +use std::fmt; +use std::ops::{Add, Mul}; + +// Generic function f that works with any type T that implements the required traits +fn f(x: T) -> T +where + T: Copy + Add + From, + ModularInteger: From, + T: From, +{ + // Convert to ModularInteger to use the pow function, then convert back + let mod_int = ModularInteger::from(x); + let powered = mod_int.pow(100); + T::from(powered + ModularInteger::from(x) + ModularInteger::from(T::from(1))) +} + +// For the specific case of ModularInteger, we implement f directly +impl ModularInteger { + fn f_specific(self) -> Self { + self.pow(100) + self + ModularInteger::new(1, self.modulus) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ModularInteger { + value: i32, + modulus: i32, +} + +impl ModularInteger { + fn new(v: i32, m: i32) -> Self { + ModularInteger { + value: v.rem_euclid(m), // Use rem_euclid for proper modular arithmetic + modulus: m, + } + } + + fn get_value(&self) -> i32 { + self.value + } + + fn get_modulus(&self) -> i32 { + self.modulus + } + + fn validate_op(&self, rhs: &ModularInteger) -> Result<(), String> { + if self.modulus != rhs.modulus { + Err("Left-hand modulus does not match right-hand modulus.".to_string()) + } else { + Ok(()) + } + } + + fn pow(&self, mut exp: i32) -> Self { + if exp < 0 { + panic!("Power must not be negative."); + } + + let mut base = ModularInteger::new(1, self.modulus); + let mut current = *self; + + // Use fast exponentiation algorithm + while exp > 0 { + if exp % 2 == 1 { + base = base * current; + } + current = current * current; + exp /= 2; + } + base + } +} + +// Implement Add trait for ModularInteger + ModularInteger +impl Add for ModularInteger { + type Output = ModularInteger; + + fn add(self, rhs: ModularInteger) -> ModularInteger { + self.validate_op(&rhs).expect("Modulus mismatch"); + ModularInteger::new(self.value + rhs.value, self.modulus) + } +} + +// Implement Add trait for ModularInteger + i32 +impl Add for ModularInteger { + type Output = ModularInteger; + + fn add(self, rhs: i32) -> ModularInteger { + ModularInteger::new(self.value + rhs, self.modulus) + } +} + +// Implement Mul trait for ModularInteger * ModularInteger +impl Mul for ModularInteger { + type Output = ModularInteger; + + fn mul(self, rhs: ModularInteger) -> ModularInteger { + self.validate_op(&rhs).expect("Modulus mismatch"); + ModularInteger::new(self.value * rhs.value, self.modulus) + } +} + +// Implement Display trait for pretty printing +impl fmt::Display for ModularInteger { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "ModularInteger({}, {})", self.value, self.modulus) + } +} + +// Conversion traits for the generic function +impl From for ModularInteger { + fn from(value: i32) -> Self { + ModularInteger::new(value, 13) // Default modulus for demonstration + } +} + +impl From for i32 { + fn from(mod_int: ModularInteger) -> Self { + mod_int.value + } +} + +fn main() { + let input = ModularInteger::new(10, 13); + let output = input.f_specific(); // Using the specific implementation for ModularInteger + println!("f({}) = {}", input, output); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_modular_integer_creation() { + let mi = ModularInteger::new(15, 13); + assert_eq!(mi.get_value(), 2); + assert_eq!(mi.get_modulus(), 13); + } + + #[test] + fn test_addition() { + let mi1 = ModularInteger::new(10, 13); + let mi2 = ModularInteger::new(5, 13); + let result = mi1 + mi2; + assert_eq!(result.get_value(), 2); // (10 + 5) % 13 = 2 + } + + #[test] + fn test_multiplication() { + let mi1 = ModularInteger::new(10, 13); + let mi2 = ModularInteger::new(5, 13); + let result = mi1 * mi2; + assert_eq!(result.get_value(), 11); // (10 * 5) % 13 = 11 + } + + #[test] + fn test_power() { + let mi = ModularInteger::new(2, 13); + let result = mi.pow(3); + assert_eq!(result.get_value(), 8); // 2^3 = 8 + } + + #[test] + #[should_panic(expected = "Modulus mismatch")] + fn test_mismatched_modulus() { + let mi1 = ModularInteger::new(10, 13); + let mi2 = ModularInteger::new(5, 17); + let _ = mi1 + mi2; + } + + #[test] + #[should_panic(expected = "Power must not be negative")] + fn test_negative_power() { + let mi = ModularInteger::new(2, 13); + mi.pow(-1); + } +} diff --git a/Task/Modular-arithmetic/Zig/modular-arithmetic.zig b/Task/Modular-arithmetic/Zig/modular-arithmetic.zig new file mode 100644 index 0000000000..22c6d4ffb0 --- /dev/null +++ b/Task/Modular-arithmetic/Zig/modular-arithmetic.zig @@ -0,0 +1,94 @@ +const std = @import("std"); +const print = std.debug.print; + +// Generic function f that works with any type T +fn f(comptime T: type, x: T) T { + const pow_result = pow(T, x, 100); + const temp = pow_result.add(x) catch unreachable; // Same modulus, won't error + return temp.addInt(1); +} + +// ModularInteger struct +const ModularInteger = struct { + value: i32, + modulus: i32, + + const Self = @This(); + + // Constructor + pub fn init(v: i32, m: i32) Self { + return Self{ + .value = @mod(v, m), + .modulus = m, + }; + } + + // Getter methods + pub fn getValue(self: Self) i32 { + return self.value; + } + + pub fn getModulus(self: Self) i32 { + return self.modulus; + } + + // Validation helper + fn validateOp(self: Self, rhs: Self) !void { + if (self.modulus != rhs.modulus) { + return error.ModulusMismatch; + } + } + + // Addition with another ModularInteger + pub fn add(self: Self, rhs: Self) !Self { + try self.validateOp(rhs); + return Self.init(self.value + rhs.value, self.modulus); + } + + // Addition with integer + pub fn addInt(self: Self, rhs: i32) Self { + return Self.init(self.value + rhs, self.modulus); + } + + // Multiplication with another ModularInteger + pub fn mul(self: Self, rhs: Self) !Self { + try self.validateOp(rhs); + return Self.init(self.value * rhs.value, self.modulus); + } + + // Format for printing + pub fn format( + self: Self, + comptime fmt: []const u8, + options: std.fmt.FormatOptions, + writer: anytype, + ) !void { + _ = fmt; + _ = options; + try writer.print("ModularInteger({}, {})", .{ self.value, self.modulus }); + } +}; + +// Power function for ModularInteger +fn pow(comptime T: type, base: T, power: i32) T { + if (power < 0) { + @panic("Power must not be negative."); + } + + var result = T.init(1, base.getModulus()); + var p = power; + while (p > 0) : (p -= 1) { + result = result.mul(base) catch unreachable; // Same modulus, won't error + } + return result; +} + +// Operator overloading using + syntax (though Zig doesn't have true operator overloading) +// We use methods instead, but you could create wrapper functions if desired + +pub fn main() !void { + const input = ModularInteger.init(10, 13); + const output = f(ModularInteger, input); + + print("f({}) = {}\n", .{ input, output }); +} diff --git a/Task/Modular-inverse/FutureBasic/modular-inverse.basic b/Task/Modular-inverse/FutureBasic/modular-inverse.basic new file mode 100644 index 0000000000..d7b33eefbe --- /dev/null +++ b/Task/Modular-inverse/FutureBasic/modular-inverse.basic @@ -0,0 +1,10 @@ +NSInteger local fn ModularInverse2( a as NSInteger, b as NSInteger ) + a %= b + for NSInteger x = 1 to b - 1 + if ( (a * x) % b == 1 ) then return x + next +end fn = -1 + +print fn ModularInverse2( 42, 2017 ) + +HandleEvents diff --git a/Task/Modular-inverse/Pluto/modular-inverse.pluto b/Task/Modular-inverse/Pluto/modular-inverse.pluto new file mode 100644 index 0000000000..dd25ad1e45 --- /dev/null +++ b/Task/Modular-inverse/Pluto/modular-inverse.pluto @@ -0,0 +1,5 @@ +local int = require "int" + +local a = 42 +local b = 2017 +print(int.modinv(a, b)) diff --git a/Task/Modular-inverse/Zig/modular-inverse.zig b/Task/Modular-inverse/Zig/modular-inverse.zig new file mode 100644 index 0000000000..ec1d91b5a3 --- /dev/null +++ b/Task/Modular-inverse/Zig/modular-inverse.zig @@ -0,0 +1,29 @@ +const std = @import("std"); + +fn mod_inv(a: isize, module: isize) isize { + var mn_0 = module; + var mn_1 = a; + var xy_0: isize = 0; + var xy_1: isize = 1; + + while (mn_1 != 0) { + const xy_0_temp = xy_1; + xy_1 = xy_0 - @divFloor(mn_0, mn_1) * xy_1; + xy_0 = xy_0_temp; + + const mn_0_temp = mn_1; + mn_1 = @rem(mn_0, mn_1); + mn_0 = mn_0_temp; + } + + while (xy_0 < 0) { + xy_0 += module; + } + + return xy_0; +} + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + try stdout.print("{d}\n", .{mod_inv(42, 2017)}); +} diff --git a/Task/Monads-Writer-monad/Koka/monads-writer-monad.koka b/Task/Monads-Writer-monad/Koka/monads-writer-monad.koka new file mode 100644 index 0000000000..3780d1ec33 --- /dev/null +++ b/Task/Monads-Writer-monad/Koka/monads-writer-monad.koka @@ -0,0 +1,47 @@ +import std/num/float64 + +effect log + fun log(s: string): () + +fun write(s: string, f: float64): log float64 + log(s.pad-right(17) ++ ": " ++ f.show) + f + +fun root(d) write("Took square root", sqrt(d)) +fun half(d) write("Divided by two", d / 2.0) +fun add-one(d) write("Added one", d + 1.0) + +fun solution1() + var logv := [] + with handler + fun log(s) + logv := Cons(s, logv) + return(result) (result, logv.reverse) + write("Initial value", 5.0).root.add-one.half + +struct writer + wlog: list + v: v + +fun unit(s, v, ?show) + Writer([s.pad-right(17) ++ ": " ++ v.show], v) +fun bind(m, f) + val Writer(log, v') = f(m.v) + Writer(m.wlog ++ log, v') +fun root-v2(d) unit("Took square root", sqrt(d)) +fun half-v2(d) unit("Divided by two", d / 2.0) +fun add-one-v2(d) unit("Added one", d + 1.0) +fun solution2() + unit("Initial value", 5.0).bind(root-v2).bind(add-one-v2).bind(half-v2) + +fun main() + val (result, log) = solution1() + println("Version 1 (effect handlers):") + println("The Golden Ratio is " ++ result.show) + println("Derived as follows:") + println(log.map(" " ++ _).join("\n")) + val Writer(log2, result2) = solution2() + println("\nVersion 2 (monad):") + println("The Golden Ratio is " ++ result2.show) + println("Derived as follows:") + println(log2.map(" " ++ _).join("\n")) diff --git a/Task/Monte-Carlo-methods/APL/monte-carlo-methods.apl b/Task/Monte-Carlo-methods/APL/monte-carlo-methods.apl new file mode 100644 index 0000000000..c5963c28fe --- /dev/null +++ b/Task/Monte-Carlo-methods/APL/monte-carlo-methods.apl @@ -0,0 +1 @@ +mc_pi ← 4 × ⊢ ÷⍨ (+/1≥×⍨∘?+×⍨∘?)∘(/∘0) diff --git a/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp b/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp index 06bdaf0aaf..88435aba1a 100644 --- a/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp +++ b/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp @@ -1,21 +1,29 @@ -#include -#include -#include -#include +#include +#include -using namespace std; -int main(){ - int jmax=1000; // maximum value of HIT number. (Length of output file) - int imax=1000; // maximum value of random numbers for producing HITs. - double x,y; // Coordinates - int hit; // storage variable of number of HITs - srand(time(0)); - for (int j=0;j +#include + +[[nodiscard]] double monte_carlo_pi(std::size_t samples) noexcept { + std::mt19937_64 eng{ std::random_device{}() }; // consider using better seeding + std::uniform_real_distribution dst{}; + std::size_t hits = 0; + for (std::size_t i = 0; i < samples; ++i) { + if (std::hypot(dst(eng), dst(eng)) <= 1.0) ++hits; + } + return (static_cast(hits) / samples) * 4; +} + +int main() { + // using C++23's `std::println` in order to make printing `double`s accurate; + // this would also work with the classic `std::cout` + std::println("{}", monte_carlo_pi(10)); + std::println("{}", monte_carlo_pi(100)); + std::println("{}", monte_carlo_pi(1000)); + std::println("{}", monte_carlo_pi(10'000)); + std::println("{}", monte_carlo_pi(100'000)); + std::println("{}", monte_carlo_pi(1'000'000)); + std::println("{}", monte_carlo_pi(10'000'000)); + std::println("{}", monte_carlo_pi(100'000'000)); + std::println("{}", monte_carlo_pi(1'000'000'000)); } diff --git a/Task/Monte-Carlo-methods/DuckDB/monte-carlo-methods.duckdb b/Task/Monte-Carlo-methods/DuckDB/monte-carlo-methods.duckdb new file mode 100644 index 0000000000..aac96bec28 --- /dev/null +++ b/Task/Monte-Carlo-methods/DuckDB/monte-carlo-methods.duckdb @@ -0,0 +1,20 @@ +create or replace function mcPi(n) as ( + with recursive cte as ( + select -1 as i, 0 as count, NULL::DOUBLE as x, NULL::DOUBLE as y + union all + select i+1 as i, + count + if( x*x + y*y <= 1, 1, 0) as count, + random() as x, + random() as y + from cte + where i < n + ) + select last( 4 * count / n order by i) + from cte +); + +# Examples: + +select n, mcPi, format('{:.5f}', (mcPi - pi()) / pi()) as "relative error" +from (select n, mcPi(n) as mcPi + from (select unnest([100, 1000, 10000, 100000, 200000]) as n)); diff --git a/Task/Monte-Carlo-methods/FutureBasic/monte-carlo-methods.basic b/Task/Monte-Carlo-methods/FutureBasic/monte-carlo-methods.basic new file mode 100644 index 0000000000..91a23b917f --- /dev/null +++ b/Task/Monte-Carlo-methods/FutureBasic/monte-carlo-methods.basic @@ -0,0 +1,48 @@ +// Get PI using MonteCarlo method +// +// FutureBasic 7.0.34, August 2025 R.W + +// In my opinion, iteration below +// a hundred million won't even show anything +// remotely close to PI + +local fn MC_PI(rolls as double) as double + double i, inCircle, dist, MaxINT + double rndX, rndY, result + MaxINT = 2147483647.0 + inCircle = 0 + + for i = 1 TO rolls + // a square with a side of length 2 centered at 0 has + // x and y range of -1 to 1 + if i % 2 == 0 + rndX = (rnd(MaxINT)-1)/MaxINT + rndY = (rnd(MaxINT)-1)/MaxINT + else + rndX = (rnd(MaxINT)+1)/MaxINT + rndY = (rnd(MaxINT)+1)/MaxINT + end if + dist = rndX ^ 2 + rndY ^ 2 + if dist < 1.0 //circle with diameter of 2 has radius of 1 + inCircle++ + end if + next i + result = 4.0 * inCircle / rolls +end fn = result + + +window 1,@"Monte Carlo PI" +random +double pi2 + +pi2 = fn MC_PI(10^4) +print " 10,000 = ";pi2 + +pi2 = fn MC_PI(10^6) +print " 1,000,000 = ";pi2 + +pi2 = fn MC_PI(10^8) +print "100,000,000 = ";pi2 + + +HandleEvents diff --git a/Task/Monte-Carlo-methods/SETL/monte-carlo-methods.setl b/Task/Monte-Carlo-methods/SETL/monte-carlo-methods.setl new file mode 100644 index 0000000000..6eef64b350 --- /dev/null +++ b/Task/Monte-Carlo-methods/SETL/monte-carlo-methods.setl @@ -0,0 +1,21 @@ +program monte_carlo; + setrandom(0); + + loop for x in [5..8] do + throws := 10**x; + print(throws, " => ", calc_pi(throws)); + end loop; + + proc calc_pi(throws); + inside := 0; + loop init i := 0; while i { + data: [[f64; C]; R], +} + +impl Matrix { + fn new() -> Self { + Self { + data: [[0.0; C]; R], + } + } + + fn from_rows(values: &[&[f64]]) -> Self { + let mut matrix = Self::new(); + for (i, row) in values.iter().enumerate().take(R) { + for (j, &val) in row.iter().enumerate().take(C) { + matrix.data[i][j] = val; + } + } + matrix + } + + fn get(&self, row: usize, col: usize) -> f64 { + self.data[row][col] + } + + fn set(&mut self, row: usize, col: usize, value: f64) { + self.data[row][col] = value; + } + + fn get_row(&self, row: usize) -> [f64; C] { + self.data[row] + } + + fn set_row(&mut self, row: usize, values: &[f64; C]) { + self.data[row] = *values; + } + + fn multiply(&self, rhs: &Matrix) -> Matrix { + let mut result = Matrix::::new(); + for i in 0..R { + for j in 0..D { + for k in 0..C { + let prod = self.get(i, k) * rhs.get(k, j); + result.set(i, j, result.get(i, j) + prod); + } + } + } + result + } + + fn transpose(&self) -> Matrix { + let mut trans = Matrix::::new(); + for i in 0..R { + for j in 0..C { + trans.set(j, i, self.data[i][j]); + } + } + trans + } + + fn to_reduced_row_echelon_form(&mut self) { + let mut lead = 0; + for r in 0..R { + if C <= lead { + return; + } + let mut i = r; + + while self.get(i, lead) == 0.0 { + i += 1; + if R == i { + i = r; + lead += 1; + if C == lead { + return; + } + } + } + + // Swap rows + let temp = self.get_row(i); + self.set_row(i, &self.get_row(r)); + self.set_row(r, &temp); + + if self.get(r, lead) != 0.0 { + let div = self.get(r, lead); + for j in 0..C { + self.set(r, j, self.get(r, j) / div); + } + } + + for k in 0..R { + if k != r { + let mult = self.get(k, lead); + for j in 0..C { + let prod = self.get(r, j) * mult; + self.set(k, j, self.get(k, j) - prod); + } + } + } + + lead += 1; + } + } +} + +impl Matrix { + fn inverse(&self) -> Result, &'static str> { + if N == 0 { + return Err("Cannot invert empty matrix"); + } + + // Create augmented matrix using Vec for dynamic sizing + let mut aug = vec![vec![0.0; 2 * N]; N]; + + // Copy original matrix to left side of augmented matrix + for i in 0..N { + for j in 0..N { + aug[i][j] = self.get(i, j); + } + // Add identity matrix to right side + aug[i][i + N] = 1.0; + } + + // Perform Gauss-Jordan elimination + let mut lead = 0; + for r in 0..N { + if 2 * N <= lead { + return Err("Matrix is not invertible"); + } + let mut i = r; + + while aug[i][lead] == 0.0 { + i += 1; + if N == i { + i = r; + lead += 1; + if 2 * N == lead { + return Err("Matrix is not invertible"); + } + } + } + + // Swap rows + aug.swap(i, r); + + if aug[r][lead] != 0.0 { + let div = aug[r][lead]; + for j in 0..(2 * N) { + aug[r][j] /= div; + } + } + + for k in 0..N { + if k != r { + let mult = aug[k][lead]; + for j in 0..(2 * N) { + aug[k][j] -= aug[r][j] * mult; + } + } + } + + lead += 1; + } + + // Extract inverse from right side + let mut inv = Matrix::::new(); + for i in 0..N { + for j in 0..N { + inv.set(i, j, aug[i][j + N]); + } + } + Ok(inv) + } +} + +impl fmt::Display for Matrix { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + for i in 0..R { + write!(f, "[")?; + for j in 0..C { + if j > 0 { + write!(f, ", ")?; + } + write!(f, "{}", self.get(i, j))?; + } + writeln!(f, "]")?; + } + Ok(()) + } +} + +fn multiple_regression( + y: &[f64; C], + x: &Matrix, +) -> Result<[f64; R], &'static str> { + let mut tm = Matrix::<1, C>::new(); + for (i, &val) in y.iter().enumerate() { + tm.set(0, i, val); + } + + let cy = tm.transpose(); + let cx = x.transpose(); + let x_cx = x.multiply(&cx); + let inv = x_cx.inverse()?; + let result = inv.multiply(&x.multiply(&cy)).transpose(); + + Ok(result.get_row(0)) +} + +fn case1() -> Result<(), &'static str> { + let y = [1.0, 2.0, 3.0, 4.0, 5.0]; + let x = Matrix::<1, 5>::from_rows(&[&[2.0, 1.0, 3.0, 4.0, 5.0]]); + let v = multiple_regression(&y, &x)?; + println!("{:?}", v); + Ok(()) +} + +fn case2() -> Result<(), &'static str> { + let y = [3.0, 4.0, 5.0]; + let x = Matrix::<2, 3>::from_rows(&[ + &[1.0, 2.0, 1.0], + &[1.0, 1.0, 2.0], + ]); + let v = multiple_regression(&y, &x)?; + println!("{:?}", v); + Ok(()) +} + +fn case3() -> Result<(), &'static str> { + let y = [ + 52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, + 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46, + ]; + let a = [ + 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, + 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83, + ]; + + let mut x = Matrix::<3, 15>::new(); + + // First row: all ones + for i in 0..15 { + x.set(0, i, 1.0); + } + + // Second row: values from array 'a' + for (i, &val) in a.iter().enumerate() { + x.set(1, i, val); + } + + // Third row: squared values from array 'a' + for (i, &val) in a.iter().enumerate() { + x.set(2, i, val * val); + } + + let v = multiple_regression(&y, &x)?; + println!("{:?}", v); + Ok(()) +} + +fn main() -> Result<(), &'static str> { + case1()?; + case2()?; + case3()?; + Ok(()) +} diff --git a/Task/Multiplication-tables/Agena/multiplication-tables.agena b/Task/Multiplication-tables/Agena/multiplication-tables.agena index 2127271ec5..d8231d1269 100644 --- a/Task/Multiplication-tables/Agena/multiplication-tables.agena +++ b/Task/Multiplication-tables/Agena/multiplication-tables.agena @@ -1,5 +1,4 @@ -scope - # print a school style multiplication table +scope # print a school style multiplication table # NB: print outputs a newline at the end, write and printf do not write( " " ); for i to 12 do printf( " %3d", i ) od; @@ -11,4 +10,4 @@ scope for j from i to 12 do printf( " %3d", i * j ) od; od; print() -epocs +end diff --git a/Task/Multiplication-tables/Pluto/multiplication-tables.pluto b/Task/Multiplication-tables/Pluto/multiplication-tables.pluto new file mode 100644 index 0000000000..7d210c9190 --- /dev/null +++ b/Task/Multiplication-tables/Pluto/multiplication-tables.pluto @@ -0,0 +1,13 @@ +do -- print a school style multiplication table + local fmt = require( "fmt" ) -- RC formattng library + io.write( " " ) + for i = 1, 12 do fmt.write( " %3d", i ) end + io.write( "\n +" ) + for _ = 1, 12 do io.write( "----" ) end + for i = 1, 12 do + fmt.write( "\n%3d|", i ) + for _ = 1, i - 1 do io.write( " " ) end + for j = i, 12 do fmt.write( " %3d", i * j ) end + end + io.write( "\n" ) +end diff --git a/Task/Multiplication-tables/TAV/multiplication-tables.tav b/Task/Multiplication-tables/TAV/multiplication-tables.tav new file mode 100644 index 0000000000..1131ae1241 --- /dev/null +++ b/Task/Multiplication-tables/TAV/multiplication-tables.tav @@ -0,0 +1,10 @@ +main (parms):+ + am =: string parms[1] as integer else 12 + ?# i =: from 1 upto am + print format '%4d;' i nonl + ?# j =: from 1 upto am + ? j >= i + print format '%4d;' i*j nonl + | + print ' ' nonl + print '' diff --git a/Task/Multiplicative-order/F-Sharp/multiplicative-order.fs b/Task/Multiplicative-order/F-Sharp/multiplicative-order.fs new file mode 100644 index 0000000000..834861e1ec --- /dev/null +++ b/Task/Multiplicative-order/F-Sharp/multiplicative-order.fs @@ -0,0 +1,8 @@ +// Multiplicative order. Nigel Galloway: August 5th., 2025 +let lcm(n:bigint seq)=MathNet.Numerics.Euclid.LeastCommonMultiple(n|>Array.ofSeq) +let factors(n:bigint)=Open.Numeric.Primes.Extensions.PrimeExtensions.PrimeFactors &n|>Seq.countBy id|>Seq.skip 1 +let rec fN i g e l=match i with i when i=1I->g |i->fN (expMod i e l) (g*e) e l +let localOrder n g l=factors(g)|>Seq.fold(fun r (q,e)->fN (expMod n (g/q**e) l) r q l) 1I +let order n g=factors(g)|>Seq.map(fun(p,k)->localOrder n ((p-1I)*p**(k-1)) (p**k))|>lcm +let tests=[(37I,1000I);(10I**100+1I,7919I);(10I**1000+1I,15485863I);(10I**10000-1I,22801763489I)] +tests|>List.iter(fun(n,g)->printfn "%A" (order n g)) diff --git a/Task/Munchausen-numbers/00-META.yaml b/Task/Munchausen-numbers/00-META.yaml index a5de31607a..1e2f7da316 100644 --- a/Task/Munchausen-numbers/00-META.yaml +++ b/Task/Munchausen-numbers/00-META.yaml @@ -1,2 +1,3 @@ --- from: http://rosettacode.org/wiki/Munchausen_numbers +note: Numbers diff --git a/Task/Munchausen-numbers/ArkScript/munchausen-numbers.ark b/Task/Munchausen-numbers/ArkScript/munchausen-numbers.ark new file mode 100644 index 0000000000..0e15253091 --- /dev/null +++ b/Task/Munchausen-numbers/ArkScript/munchausen-numbers.ark @@ -0,0 +1,30 @@ +(import std.List) + +(let self-exponent (fun (x n acc) + (if (> n 0) + (self-exponent x (- n 1) (* x acc)) + acc))) + +(let cache (list:map (list:iota 0 10) (fun (x) (if (= x 0) 0 (self-exponent x x 1))))) + +(let is_munchausen (fun (number) { + (mut total 0) + (mut n number) + (mut continue true) + + (while (and (> n 0) continue) { + (let digit (mod n 10)) + (set total (+ total (@ cache digit))) + (if (> total number) + (set continue false) + (set n (math:floor (/ n 10)))) }) + + (= total number) })) + +(let max_val 5000) + +(mut i 1) +(while (< i max_val) { + (if (is_munchausen i) + (print i)) + (set i (+ 1 i)) }) diff --git a/Task/Munchausen-numbers/R/munchausen-numbers.r b/Task/Munchausen-numbers/R/munchausen-numbers.r index 8079ca1175..b3b8afcb33 100644 --- a/Task/Munchausen-numbers/R/munchausen-numbers.r +++ b/Task/Munchausen-numbers/R/munchausen-numbers.r @@ -1,9 +1,4 @@ -exp_digsum <- function(n){ - if(n>9){ - return((n%%10)^(n%%10)+exp_digsum(n%/%10)) - } - else return(n^n) -} +exp_digsum <- function(n) ifelse(n>9, (n%%10)^(n%%10)+exp_digsum(n%/%10), n^n) for(i in 1:5000){ if(exp_digsum(i)==i) print(i) diff --git a/Task/Munching-squares/EasyLang/munching-squares.easy b/Task/Munching-squares/EasyLang/munching-squares.easy index 78ae2c25f5..e038dc638c 100644 --- a/Task/Munching-squares/EasyLang/munching-squares.easy +++ b/Task/Munching-squares/EasyLang/munching-squares.easy @@ -1,8 +1,8 @@ sc = 100 / 64 for x = 0 to 63 for y = 0 to 63 - h = bitand bitxor x y 63 / 63 + h = 100 / 63 * bitand (bitxor x y) 63 gcolor3 h h h - grect x * sc y * sc sc + 0.1 sc + 0.1 + grect x * sc, y * sc, sc + 0.1, sc + 0.1 . . diff --git a/Task/Munching-squares/YAMLScript/munching-squares.ys b/Task/Munching-squares/YAMLScript/munching-squares.ys new file mode 100644 index 0000000000..7fbf2c26b9 --- /dev/null +++ b/Task/Munching-squares/YAMLScript/munching-squares.ys @@ -0,0 +1,14 @@ +!YS-v0 + +n =: 16 +loop i 0: + shell: 'clear' + each y range(n): + each x range(n): + print: + if bit-xor(x y) < i: + + "█" " " + print: "\n" + flush: + sleep: 0.15 + recur: i.++ % n.++ diff --git a/Task/Musical-scale/Java/musical-scale.java b/Task/Musical-scale/Java/musical-scale.java index 8ee6d59a24..625ef7d219 100644 --- a/Task/Musical-scale/Java/musical-scale.java +++ b/Task/Musical-scale/Java/musical-scale.java @@ -57,7 +57,7 @@ public final class MusicalScale { private static SourceDataLine sourceDataLine; - private static float SAMPLE_RATE = 8_000.0F; + private static final float SAMPLE_RATE = 8_000.0F; private static final int BYTE_OFFSET = 0; } diff --git a/Task/Mutex/FutureBasic/mutex.basic b/Task/Mutex/FutureBasic/mutex.basic new file mode 100644 index 0000000000..20bb7680c4 --- /dev/null +++ b/Task/Mutex/FutureBasic/mutex.basic @@ -0,0 +1,19 @@ +include "NSLog.incl" + +void local fn DoIt + LockRef m = fn LockInit + + LockingLock( m ) + + if ( fn LockTry( m ) ) + NSLog(@"lock acquired") // acquire a lock -- does not block if not acquired + else + NSLog(@"already locked, does not block") + end if + + LockingUnlock( m ) +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Mutual-recursion/Pluto/mutual-recursion.pluto b/Task/Mutual-recursion/Pluto/mutual-recursion.pluto new file mode 100644 index 0000000000..4a557184fc --- /dev/null +++ b/Task/Mutual-recursion/Pluto/mutual-recursion.pluto @@ -0,0 +1,10 @@ +function F(n) + return n==0?1:n-M(F(n-1)) +end + +function M(n) + return n==0?0:n-F(M(n-1)) +end + +print(range(1,12):mapped(F):unpack()) +print(range(1,12):mapped(M):unpack()) diff --git a/Task/N-queens-problem/ArkScript/n-queens-problem.ark b/Task/N-queens-problem/ArkScript/n-queens-problem.ark new file mode 100644 index 0000000000..03e9c69265 --- /dev/null +++ b/Task/N-queens-problem/ArkScript/n-queens-problem.ark @@ -0,0 +1,32 @@ +(let queenPuzzle (fun (rows columns) + (if (<= rows 0) + [[]] + (addQueen (- rows 1) columns)))) + +(let addQueen (fun (newRow columns) { + (mut newSolutions []) + (let prev (queenPuzzle newRow columns)) + + (mut i 0) + (while (< i (len prev)) { + (let solution (@ prev i)) + (mut newColumn 0) + (while (< newColumn columns) { + (if (not (hasConflict newRow newColumn solution)) (append! newSolutions (append solution newColumn))) + (set newColumn (+ newColumn 1)) }) + + (set i (+ i 1)) }) + + newSolutions })) + +(let hasConflict (fun (newRow newColumn solution) { + (mut i 0) + (mut conflict false) + (while (and (< i newRow) (not conflict)) { + (if (or (= (@ solution i) newColumn) (= (+ (@ solution i) i) (+ newColumn newRow)) (= (- (@ solution i) i) (- newColumn newRow))) + (set conflict true)) + (set i (+ i 1)) }) + + conflict })) + +(print (queenPuzzle 4 4)) diff --git a/Task/Named-parameters/FutureBasic/named-parameters.basic b/Task/Named-parameters/FutureBasic/named-parameters.basic new file mode 100644 index 0000000000..7d42f183a2 --- /dev/null +++ b/Task/Named-parameters/FutureBasic/named-parameters.basic @@ -0,0 +1,9 @@ +include "NSLog.incl" + +CFStringRef local fn WelcomeToFutureBasic( person as CFStringRef, location as CFStringRef ) + return fn StringWithFormat( @"Welcome %@! Glad you could join us from %@.", person, location ) +end fn = NULL + +NSLog( @"%@", fn WelcomeToFutureBasic( @"John Codemeister", @"Hawaii" ) ) + +HandleEvents diff --git a/Task/Named-parameters/Icon/named-parameters.icon b/Task/Named-parameters/Icon/named-parameters.icon index 76bd6f5f7b..837e6f9bef 100644 --- a/Task/Named-parameters/Icon/named-parameters.icon +++ b/Task/Named-parameters/Icon/named-parameters.icon @@ -10,7 +10,7 @@ procedure testproc(A[]) #: demo to test named parameters while a := get(A) do # implement named parameters here (( a ? (v := =!["x","y","z"], =":=") | # valid parameter name? - stop("No parameter ",a)) & # . . no + stop(&output,"No parameter ",a)) & # . . no ((variable(a[1:-2]) := get(A)) | # assign runerr(205,a))) # . . problem diff --git a/Task/Named-parameters/Pluto/named-parameters.pluto b/Task/Named-parameters/Pluto/named-parameters.pluto new file mode 100644 index 0000000000..b119411e0b --- /dev/null +++ b/Task/Named-parameters/Pluto/named-parameters.pluto @@ -0,0 +1,7 @@ +local function print_name(forename, surname = "Trump"). + print($"{forename} {surname}") +end + +print_name(forename = "Abraham", surname = "Lincoln") +print_name(surname = "Trump", forename = "Donald") +print_name(forename = "Donald") diff --git a/Task/Naming-conventions/Ada/naming-conventions-1.ada b/Task/Naming-conventions/Ada/naming-conventions-1.ada new file mode 100644 index 0000000000..d0b1c4574d --- /dev/null +++ b/Task/Naming-conventions/Ada/naming-conventions-1.ada @@ -0,0 +1,8 @@ +function Max (Left, Right : Integer) return Integer is +begin + if Left < Right then + return Right; + else + return Left; + end if; +end Max; diff --git a/Task/Naming-conventions/Ada/naming-conventions-2.ada b/Task/Naming-conventions/Ada/naming-conventions-2.ada new file mode 100644 index 0000000000..0cd2b08010 --- /dev/null +++ b/Task/Naming-conventions/Ada/naming-conventions-2.ada @@ -0,0 +1,3 @@ +package My_Package is +... +end My_Package; diff --git a/Task/Naming-conventions/Ada/naming-conventions-3.ada b/Task/Naming-conventions/Ada/naming-conventions-3.ada new file mode 100644 index 0000000000..5f69399c3e --- /dev/null +++ b/Task/Naming-conventions/Ada/naming-conventions-3.ada @@ -0,0 +1,3 @@ +package body My_Package is +... +end My_Package; diff --git a/Task/Narcissistic-decimal-number/ALGOL-68/narcissistic-decimal-number.alg b/Task/Narcissistic-decimal-number/ALGOL-68/narcissistic-decimal-number.alg index 5ec6c51a24..3a614eaa17 100644 --- a/Task/Narcissistic-decimal-number/ALGOL-68/narcissistic-decimal-number.alg +++ b/Task/Narcissistic-decimal-number/ALGOL-68/narcissistic-decimal-number.alg @@ -1,33 +1,59 @@ -# find some narcissistic decimal numbers # +# print the first 25 narcissistic numbers # +BEGIN -# returns TRUE if n is narcissitic, FALSE otherwise; n should be >= 0 # -PROC is narcissistic = ( INT n )BOOL: - BEGIN - # count the number of digits in n # - INT digits := 0; - INT number := n; - WHILE digits +:= 1; - number OVERAB 10; - number > 0 - DO SKIP OD; - # sum the digits'th powers of the digits of n # - INT sum := 0; - number := n; - TO digits DO - sum +:= ( number MOD 10 ) ^ digits; - number OVERAB 10 - OD; - # n is narcissistic if n = sum # - n = sum - END # is narcissistic # ; + [ 0 : 9 ]INT power := ( []INT( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ) )[ AT 0 ]; + INT count := 0; + INT candidate := 0; + INT prev digits := 0; + INT digits := 0; -# print the first 25 narcissistic numbers # -INT count := 0; -FOR n FROM 0 WHILE count < 25 DO - IF is narcissistic( n ) THEN - # found another narcissistic number # - print( ( " ", whole( n, 0 ) ) ); - count +:= 1 - FI -OD; -print( ( newline ) ) + FOR d9 FROM 0 TO 2 DO + IF d9 > 0 AND digits < 9 THEN digits := 9 FI; + FOR d8 FROM 0 TO 9 DO + IF d8 > 0 AND digits < 8 THEN digits := 8 FI; + FOR d7 FROM 0 TO 9 DO + IF d7 > 0 AND digits < 7 THEN digits := 7 FI; + FOR d6 FROM 0 TO 9 DO + IF d6 > 0 AND digits < 6 THEN digits := 6 FI; + FOR d5 FROM 0 TO 9 DO + IF d5 > 0 AND digits < 5 THEN digits := 5 FI; + FOR d4 FROM 0 TO 9 DO + IF d4 > 0 AND digits < 4 THEN digits := 4 FI; + FOR d3 FROM 0 TO 9 DO + IF d3 > 0 AND digits < 3 THEN digits := 3 FI; + FOR d2 FROM 0 TO 9 DO + IF d2 > 0 AND digits < 2 THEN digits := 2 FI; + FOR d1 FROM 0 TO 9 DO + + IF prev digits /= digits THEN + # number of digits has increased - increase the powers # + prev digits := digits; + FOR i FROM 2 TO 9 DO power[ i ] *:= i OD + FI; + + # sum the digits'th powers of the # + # digits of candidate # + INT sum = power[ d1 ] + power[ d2 ] + power[ d3 ] + + power[ d4 ] + power[ d5 ] + power[ d6 ] + + power[ d7 ] + power[ d8 ] + power[ d9 ] + ; + IF candidate = sum THEN + # found another narcissistic decimal number # + print( ( " ", whole( candidate, 0 ) ) ); + count +:= + 1; + IF count >= 25 THEN GOTO done FI + FI; + candidate +:= 1 + OD + OD + OD + OD + OD + OD + OD + OD + OD; +done: + print( ( newline ) ) + +END diff --git a/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena b/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena index 9f621e8606..b744951649 100644 --- a/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena +++ b/Task/Narcissistic-decimal-number/Agena/narcissistic-decimal-number.agena @@ -24,12 +24,12 @@ scope if d3 > 0 and digits < 3 then digits := 3 fi; for d2 from 0 to 9 while count < maxCount do if d2 > 0 and digits < 2 then digits := 2 fi; + if prevDigits <> digits then + # number of digits has increased - increase the powers + prevDigits := digits; + for i from 2 to 9 do mul power[ i + 1 ], i od; + fi; for d1 from 0 to 9 do - if prevDigits <> digits then - # number of digits has increased - increase the powers - prevDigits := digits; - for i from 2 to 9 do mul power[ i + 1 ], i od; - fi; # sum the digits'th powers of the digits of candidate local sum := power[ d1 + 1 ] + power[ d2 + 1 ] + power[ d3 + 1 ] + power[ d4 + 1 ] + power[ d5 + 1 ] + power[ d6 + 1 ] diff --git a/Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number.lua b/Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number-1.lua similarity index 100% rename from Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number.lua rename to Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number-1.lua diff --git a/Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number-2.lua b/Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number-2.lua new file mode 100644 index 0000000000..2ca560eb19 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Lua/narcissistic-decimal-number-2.lua @@ -0,0 +1,59 @@ +do + -- print the first 25 narcissistic numbers + + local power = { [0] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } + local count = 0 + local candidate = 0 + local prevDigits = 0 + local digits = 0 + + for d9 = 0, 2 do + if d9 > 0 and digits < 9 then digits = 9 end + for d8 = 0, 9 do + if d8 > 0 and digits < 8 then digits = 8 end + for d7 = 0, 9 do + if d7 > 0 and digits < 7 then digits = 7 end + for d6 = 0, 9 do + if d6 > 0 and digits < 6 then digits = 6 end + for d5 = 0, 9 do + if d5 > 0 and digits < 5 then digits = 5 end + for d4 = 0, 9 do + if d4 > 0 and digits < 4 then digits = 4 end + for d3 = 0, 9 do + if d3 > 0 and digits < 3 then digits = 3 end + for d2 = 0, 9 do + if d2 > 0 and digits < 2 then digits = 2 end + for d1 = 0, 9 do + + if prevDigits ~= digits then + -- number of digits has increased + -- - increase the powers + prevDigits = digits + for i = 2, 9 do power[ i ] = power[ i ] * i end + end + + -- sum the digits'th powers of the + -- digits of candidate + local sum = power[ d1 ] + power[ d2 ] + power[ d3 ] + + power[ d4 ] + power[ d5 ] + power[ d6 ] + + power[ d7 ] + power[ d8 ] + power[ d9 ] + if candidate == sum then + -- found another narcissistic + -- decimal number + io.write( " ", candidate ) + count = count + 1 + if count >= 25 then io.write( "\n" ); os.exit() end + end + candidate = candidate + 1 + end + end + end + end + end + end + end + end + end + io.write( "\n" ) + +end diff --git a/Task/Narcissistic-decimal-number/Pluto/narcissistic-decimal-number.pluto b/Task/Narcissistic-decimal-number/Pluto/narcissistic-decimal-number.pluto new file mode 100644 index 0000000000..cb78449247 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Pluto/narcissistic-decimal-number.pluto @@ -0,0 +1,50 @@ +do -- print the first 25 narcissistic numbers + + local power = { [0] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } + local count, candidate, prevDigits, digits = 0, 0, 0, 0 + + for d9 = 0, 2 do + if d9 > 0 and digits < 9 then digits = 9 end + for d8 = 0, 9 do + if d8 > 0 and digits < 8 then digits = 8 end + for d7 = 0, 9 do + if d7 > 0 and digits < 7 then digits = 7 end + for d6 = 0, 9 do + if d6 > 0 and digits < 6 then digits = 6 end + for d5 = 0, 9 do + if d5 > 0 and digits < 5 then digits = 5 end + for d4 = 0, 9 do + if d4 > 0 and digits < 4 then digits = 4 end + for d3 = 0, 9 do + if d3 > 0 and digits < 3 then digits = 3 end + for d2 = 0, 9 do + if d2 > 0 and digits < 2 then digits = 2 end + if prevDigits != digits then + -- number of digits has increased - increase the powers + prevDigits = digits + for i = 2, 9 do power[ i ] *= i end + end + + for d1 = 0, 9 do + -- sum the digits'th powers of the digits of candidate + local sum = power[ d1 ] + power[ d2 ] + power[ d3 ] + + power[ d4 ] + power[ d5 ] + power[ d6 ] + + power[ d7 ] + power[ d8 ] + power[ d9 ] + if candidate == sum then + -- found another narcissistic decimal number + io.write( " ", candidate ) + ++ count + if count >= 25 then break 9 end + end + ++ candidate + end + end + end + end + end + end + end + end + end + io.write( "\n" ) +end diff --git a/Task/Nested-function/DuckDB/nested-function.duckdb b/Task/Nested-function/DuckDB/nested-function.duckdb new file mode 100644 index 0000000000..1a76a5257d --- /dev/null +++ b/Task/Nested-function/DuckDB/nested-function.duckdb @@ -0,0 +1,12 @@ +create or replace function MakeList(sep, n) as ( + select list_transform( range(1, n+1), + -- An inner function: + i -> format('{}{} {}', + i, + sep, + if(i=1, 'first', if (i=2, 'second', if (i=3, 'third' , '...')))) ) + .array_to_string(chr(10)) +); + +.mode list +select MakeList('.', 3) ; diff --git a/Task/Nested-templated-data/Pluto/nested-templated-data.pluto b/Task/Nested-templated-data/Pluto/nested-templated-data.pluto new file mode 100644 index 0000000000..cf73411179 --- /dev/null +++ b/Task/Nested-templated-data/Pluto/nested-templated-data.pluto @@ -0,0 +1,20 @@ +require "map" +local fmt = require "fmt" -- v1.0.1 or higher + +local function with_payload(template, payload, used) + return template:mapped( |item| -> do + if type(item) == "table" then + return with_payload(item, payload, used) + else + used:insert(item) + return $"'{payload[item + 1]}'" + end + end) +end + +local p = {"Payload#0", "Payload#1", "Payload#2", "Payload#3", "Payload#4", "Payload#5", "Payload#6"} +local t = {{{1, 2}, {3, 4, 1}, 5}} +local used = {} +fmt.lprint(with_payload(t, p, used)) +local unused = set.of(range(0, 6):unpack()):except(set.of(used:unpack())) +fmt.print("\nThe unused payloads have indices of %s.", unused) diff --git a/Task/Next-highest-int-from-digits/YAMLScript/next-highest-int-from-digits.ys b/Task/Next-highest-int-from-digits/YAMLScript/next-highest-int-from-digits.ys new file mode 100644 index 0000000000..6586cafa05 --- /dev/null +++ b/Task/Next-highest-int-from-digits/YAMLScript/next-highest-int-from-digits.ys @@ -0,0 +1,44 @@ +!YS-v0 + +defn main(n=nil): + if n: + say: next-highest-int-from-digits(n) + test: + +defn next-highest-int-from-digits(n): + ds =: n:digits + i =: + sub ds.#.--: + count: + ? for [i range(ds.#.-- 0 -1) + :while (ds.nth(i.--) >= ds.$i)] + : 1 + if i > 0: + then: + a c =: ds.split-at(i) + a b =: a.split-at(a.#.--) + c d =: c:sort.split-with(\(b.0 >= _)) + d e =: d.split-at(1) + e =: sort(b + c + e) + read-string: concat(a d e).map(str):join + else: 0 + +# Test code: +defn test(): + tests =:: + 0: 0 + 9: 0 + 12: 21 + 21: 0 + 12453: 12534 + 738440: 740348 + 45072010: 45072100 + 95322020: 95322200 + 9589776899767587796600: 9589776899767587900667 + + reduce-kv _ nil tests: + fn(_ k v): + n =: next-highest-int-from-digits(k) + if n == v: + say: "PASS - $k" + say: "FAIL - $n != $v" diff --git a/Task/Non-decimal-radices-Convert/Fortran/non-decimal-radices-convert.f b/Task/Non-decimal-radices-Convert/Fortran/non-decimal-radices-convert.f index 616030f1fa..6e5a6bddd3 100644 --- a/Task/Non-decimal-radices-Convert/Fortran/non-decimal-radices-convert.f +++ b/Task/Non-decimal-radices-Convert/Fortran/non-decimal-radices-convert.f @@ -18,10 +18,11 @@ MODULE Conversion END DO END FUNCTION ToDecimal - FUNCTION ToBase(base, number) + FUNCTION ToBase(base, number_in) CHARACTER(31) :: ToBase - INTEGER :: base, number, i, rem + INTEGER :: base, number_in, number, i, rem + number = number_in ToBase = " " DO i = 31, 1, -1 IF(number < base) THEN diff --git a/Task/Non-decimal-radices-Convert/Pluto/non-decimal-radices-convert.pluto b/Task/Non-decimal-radices-Convert/Pluto/non-decimal-radices-convert.pluto new file mode 100644 index 0000000000..648b0ec2c6 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Pluto/non-decimal-radices-convert.pluto @@ -0,0 +1,7 @@ +local fmt = require "fmt" + +print(fmt.itoa(26, 16)) +print(tonumber("1a", 16)) +print() +print(fmt.itoa(9124, 36)) +print(tonumber("71g", 36)) diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx index fc32acaa42..9390008d84 100644 --- a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx +++ b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx @@ -1,15 +1,15 @@ +-- 28 Jul 2025 include Settings - -say 'NON-DECIMAL RADICES - 11 Mar 2025' -say version -say arg xx if xx = '' then xx = 255 + +say 'NON-DECIMAL RADICES CONVERT' +say version +say do n = 2 to 36 - say xx 'decimal =' Basenn(xx,n) 'base' n '=' Base10(Basenn(xx,n),n) 'decimal' + say xx 'decimal =' BaseNN(xx,n) 'base' n '=' Base10(BaseNN(xx,n),n) 'decimal' end exit -include Functions -include Abend +include Math diff --git a/Task/Nth-root/DuckDB/nth-root.duckdb b/Task/Nth-root/DuckDB/nth-root.duckdb new file mode 100644 index 0000000000..5da06426f1 --- /dev/null +++ b/Task/Nth-root/DuckDB/nth-root.duckdb @@ -0,0 +1,20 @@ +# Newton's method, assuming a > 0 and n > 0 +create or replace function nth_root(a,n) as ( + with recursive cte as ( + select 0 as ix, a::DOUBLE as x, (a-1.0)::DOUBLE as xprime + union all + select ix+1 as ix, + ((n - 1) * x / n ) + (a / (n * x ** (n-1))) as x, + x as xprime + from cte + where @(x - xprime) > 1e-15 + and ix<10 + ) + select last(x order by ix) + from cte +); + +select n, + 5.0 ^ (1 / cast(n as double)) as builtin, + nth_root(5.0, n) as nth_root +from unnest( [1,3,5,10,1000,10000] ) _(n); diff --git a/Task/Nth/DuckDB/nth.duckdb b/Task/Nth/DuckDB/nth.duckdb new file mode 100644 index 0000000000..10ed9b2bb7 --- /dev/null +++ b/Task/Nth/DuckDB/nth.duckdb @@ -0,0 +1,26 @@ +# ordinalize an integer, whether positive or negative +create or replace function ordinalize(x) as ( + x::VARCHAR + || '''' + || if( 11 <= (abs(x) % 100) and (abs(x) % 100) <= 13, 'th', + case abs(x) % 10 + when 1 then 'st' + when 2 then 'nd' + when 3 then 'rd' + else 'th' + end) +); + +create or replace function task(lst) as ( + select list_transform(lst, ix -> ordinalize(ix)) + .array_to_string(' ') +); + +## Examples +.header off +.maxwidth 300 +.mode list +select task(range(-5, -1)); +select task(range(0,26)); +select task(range(250,266)); +select task(range(1000,1026)); diff --git a/Task/Null-object/ArkScript/null-object.ark b/Task/Null-object/ArkScript/null-object.ark new file mode 100644 index 0000000000..873b62497f --- /dev/null +++ b/Task/Null-object/ArkScript/null-object.ark @@ -0,0 +1,5 @@ +(let a nil) +(let b 5) + +(print (nil? a)) +(print (nil? b)) diff --git a/Task/Null-object/Tcl/null-object-2.tcl b/Task/Null-object/Tcl/null-object-2.tcl index 1f86652b01..9094139b60 100644 --- a/Task/Null-object/Tcl/null-object-2.tcl +++ b/Task/Null-object/Tcl/null-object-2.tcl @@ -1,3 +1,7 @@ -if {![info exist nullvar]} ... -if {![info exists arr(nullval)]} ... -if {![dict exists $dic nullval]} ... +set p "" +set q {} +set n 0 +puts [expr {$p eq {}? true : false}] +puts [expr {$p eq ""? true : false}] +puts [expr {$p eq $q? true : false}] +puts [expr {$p eq 0? true : false}] diff --git a/Task/Null-object/Tcl/null-object-3.tcl b/Task/Null-object/Tcl/null-object-3.tcl new file mode 100644 index 0000000000..f04c56e61c --- /dev/null +++ b/Task/Null-object/Tcl/null-object-3.tcl @@ -0,0 +1,2 @@ + if {4.5} {...} ; # true + if {4.5 - 4.5} {...} ; # false diff --git a/Task/Null-object/Tcl/null-object-4.tcl b/Task/Null-object/Tcl/null-object-4.tcl new file mode 100644 index 0000000000..1ddf6d2639 --- /dev/null +++ b/Task/Null-object/Tcl/null-object-4.tcl @@ -0,0 +1,5 @@ +if {![info exist nullvar]} ... + +if {![info exists arr(nullval)]} ... + +if {![dict exists $dic nullval]} ... diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py index a7c41e93f6..b5f99eb3f6 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Python/numerical-integration-gauss-legendre-quadrature-1.py @@ -1,97 +1,107 @@ -from numpy import * +from __future__ import print_function +from __future__ import division + +from numpy import array, exp, concatenate, cos, pi + + +def Legendre(n, x): + """Recursive generation of the Legendre polynomial of order n.""" + x = array(x) + if n == 0: + return x * 0 + 1.0 + elif n == 1: + return x + else: + return ( + (2.0 * n - 1.0) * x * Legendre(n - 1, x) - (n - 1) * Legendre(n - 2, x) + ) / n + + +def DLegendre(n, x): + """Derivative of the Legendre polynomials.""" + x = array(x) + if n == 0: + return x * 0 + elif n == 1: + return x * 0 + 1.0 + else: + return (n / (x**2 - 1.0)) * (x * Legendre(n, x) - Legendre(n - 1, x)) + + +def LegendreRoots(polyorder, tolerance=1e-20): + """Roots of the polynomial obtained using Newton-Raphson method.""" + if polyorder < 2: + err = 1 # bad polyorder no roots can be found + else: + roots = [] + # The polynomials are alternately even and odd functions. So we evaluate only half the number of roots. + for i in range(1, int(polyorder / 2 + 1)): + x = cos(pi * (i - 0.25) / (polyorder + 0.5)) + error = 10 * tolerance + iters = 0 + while (error > tolerance) and (iters < 1000): + dx = -Legendre(polyorder, x) / DLegendre(polyorder, x) + x = x + dx + iters = iters + 1 + error = abs(dx) + roots.append(x) + # Use symmetry to get the other roots + roots = array(roots) + if polyorder % 2 == 0: + roots = concatenate((-1.0 * roots, roots[::-1])) + else: + roots = concatenate((-1.0 * roots, [0.0], roots[::-1])) + err = 0 # successfully determined roots + return [roots, err] -################################################################## -# Recursive generation of the Legendre polynomial of order n -def Legendre(n,x): - x=array(x) - if (n==0): - return x*0+1.0 - elif (n==1): - return x - else: - return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n -################################################################## -# Derivative of the Legendre polynomials -def DLegendre(n,x): - x=array(x) - if (n==0): - return x*0 - elif (n==1): - return x*0+1.0 - else: - return (n/(x**2-1.0))*(x*Legendre(n,x)-Legendre(n-1,x)) -################################################################## -# Roots of the polynomial obtained using Newton-Raphson method -def LegendreRoots(polyorder,tolerance=1e-20): - if polyorder<2: - err=1 # bad polyorder no roots can be found - else: - roots=[] - # The polynomials are alternately even and odd functions. So we evaluate only half the number of roots. - for i in range(1,int(polyorder)/2 +1): - x=cos(pi*(i-0.25)/(polyorder+0.5)) - error=10*tolerance - iters=0 - while (error>tolerance) and (iters<1000): - dx=-Legendre(polyorder,x)/DLegendre(polyorder,x) - x=x+dx - iters=iters+1 - error=abs(dx) - roots.append(x) - # Use symmetry to get the other roots - roots=array(roots) - if polyorder%2==0: - roots=concatenate( (-1.0*roots, roots[::-1]) ) - else: - roots=concatenate( (-1.0*roots, [0.0], roots[::-1]) ) - err=0 # successfully determined roots - return [roots, err] -################################################################## -# Weight coefficients def GaussLegendreWeights(polyorder): - W=[] - [xis,err]=LegendreRoots(polyorder) - if err==0: - W=2.0/( (1.0-xis**2)*(DLegendre(polyorder,xis)**2) ) - err=0 - else: - err=1 # could not determine roots - so no weights - return [W, xis, err] -################################################################## -# The integral value -# func : the integrand -# a, b : lower and upper limits of the integral -# polyorder : order of the Legendre polynomial to be used -# -def GaussLegendreQuadrature(func, polyorder, a, b): - [Ws,xs, err]= GaussLegendreWeights(polyorder) - if err==0: - ans=(b-a)*0.5*sum( Ws*func( (b-a)*0.5*xs+ (b+a)*0.5 ) ) - else: - # (in case of error) - err=1 - ans=None - return [ans,err] -################################################################## -# The integrand - change as required -def func(x): - return exp(x) -################################################################## -# + """Weight coefficients.""" + W = [] + xis, err = LegendreRoots(polyorder) + if err == 0: + W = 2.0 / ((1.0 - xis**2) * (DLegendre(polyorder, xis) ** 2)) + err = 0 + else: + err = 1 # could not determine roots - so no weights + return [W, xis, err] -order=5 -[Ws,xs,err]=GaussLegendreWeights(order) -if err==0: - print "Order : ", order - print "Roots : ", xs - print "Weights : ", Ws + +def GaussLegendreQuadrature(func, polyorder, a, b): + """integral value + func : the integrand + a, b : lower and upper limits of the integral + polyorder : order of the Legendre polynomial to be used + """ + Ws, xs, err = GaussLegendreWeights(polyorder) + if err == 0: + ans = (b - a) * 0.5 * sum(Ws * func((b - a) * 0.5 * xs + (b + a) * 0.5)) + else: + # (in case of error) + err = 1 + ans = None + return [ans, err] + + +def func(x): + """The integrand - change as required""" + return exp(x) + + +order = 5 +Ws, xs, err = GaussLegendreWeights(order) + +if err == 0: + print("Order : ", order) + print("Roots : ", xs) + print("Weights : ", Ws) else: - print "Roots/Weights evaluation failed" + print("Roots/Weights evaluation failed") # Integrating the function -[ans,err]=GaussLegendreQuadrature(func , order, -3,3) -if err==0: - print "Integral : ", ans +ans, err = GaussLegendreQuadrature(func, order, -3, 3) + +if err == 0: + print("Integral : ", ans) else: - print "Integral evaluation failed" + print("Integral evaluation failed") diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx index 55b09726ec..4c25856bd9 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx @@ -1,9 +1,8 @@ --- 9 Jun 2025 +-- 28 Jul 2025 include Settings - arg digs if digs = '' then - digs=9 + digs=16 numeric digits digs say 'NUMERICAL INTEGRATION: GAUSS-LEGENDRE QUADRATURE' @@ -13,23 +12,26 @@ w=Digits()+2 say Left('Function',10) Left('Range',w+4) ' N', Left('Result',w) Left('True',w) Left(' Error',w) say +call Task 'Sin(x)', 0, 1, -Cos(1)+1 +call Task 'Sin(x)', 0, Pi()/1, 2 +call Task 'Sin(x)', 0, 10, -Cos(10)+1 +call Task 'Cos(x)', 0, 1, Sin(1) +call Task 'Cos(x)', 0, Pi()/1, 0 +call Task 'Cos(x)', 0, 10, Sin(10) +call Task 'Tan(x)', 0, 1, -Ln(Abs(Cos(1))) +call Task 'Tan(x)', 0, Pi()/1, 0 +call Task 'Tan(x)', 0, 10, -Ln(Abs(Cos(10))) call Task 'x**3', 0, 1, 1/4 call Task '1/x', 1, 100, Ln(100)/1 call Task 'x', 0, 5000, 12500000 call Task '4/(x**2+1)', 0, 1, Pi()/1 -call Task 'Sin(x)', 0, 1, -Cos(1)+1 -call Task 'Sin(x)', 0, Pi()/1, 2 -call Task 'Cos(x)', 0, 1, Sin(1) -call Task 'Cos(x)', 0, Pi()/1, 0 -call Task 'Tan(x)', 0, 1, -Ln(Abs(Cos(1))) -call Task 'Tan(x)', 0, Pi()/1, 0 call Task 'Exp(x)', -3, 3, Exp(3)-Exp(-3) call Task 'Gamma(x)', 1, 8, 2603.238829328642145 call Timer exit Task: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,true w=Digits()+2 do nn = 1 to 20 @@ -41,7 +43,7 @@ say return GaussQuad: -procedure expose glob. +procedure expose Memo. -- Gaussion-Legendre quadrature on function f in range a...b taking n points arg ff,aa,bb,nn -- Legendre polynomials @@ -88,8 +90,4 @@ do i = 1 to nn end return bm*zz -include Functions -include Special -include Constants -include Helper -include Abend +include Math diff --git a/Task/Numerical-integration/Pluto/numerical-integration.pluto b/Task/Numerical-integration/Pluto/numerical-integration.pluto new file mode 100644 index 0000000000..d2431ba7a7 --- /dev/null +++ b/Task/Numerical-integration/Pluto/numerical-integration.pluto @@ -0,0 +1,20 @@ +local function integrate(a, b, n, f) + local h = (b - a) / n + local sum = {0, 0, 0, 0, 0} + for i = 1, n do + local x = a + (i - 1) * h + sum[1] += f(x) + sum[2] += f(x + h / 2) + sum[3] += f(x + h) + sum[4] += (f(x) + f(x + h)) / 2 + sum[5] += (f(x) + 4 * f(x + h / 2) + f(x + h)) / 6 + end + local methods = {"LeftRect ", "MidRect ", "RightRect", "Trapezium", "Simpson "} + for i = 1, 5 do print($"{methods[i]} = {sum[i] * h}") end + print() +end + +integrate(0, 1, 100, |v| -> v * v * v) +integrate(1, 100, 1_000, |v| -> 1 / v) +integrate(0, 5_000, 5_000_000, |v| -> v) +integrate(0, 6_000, 6_000_000, |v| -> v) diff --git a/Task/Numerical-integration/REXX/numerical-integration.rexx b/Task/Numerical-integration/REXX/numerical-integration.rexx index dcaa344a38..ef991abe55 100644 --- a/Task/Numerical-integration/REXX/numerical-integration.rexx +++ b/Task/Numerical-integration/REXX/numerical-integration.rexx @@ -1,4 +1,4 @@ --- 8 Jun 2025 +-- 28 Jul 2025 include Settings arg digs if digs = '' then @@ -32,7 +32,7 @@ call Timer exit Task: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,steps,true w=Digits()+2 res=LeftRect(ff,aa,bb,steps); diff=res-true @@ -50,59 +50,79 @@ say Left(ff,11) Left(aa '-' bb,w+4) Left('Trapezoid',9) Left(steps,7), res=Simpson(ff,aa,bb,steps); diff=res-true say Left(ff,11) Left(aa '-' bb,w+4) Left('Simpson',9) Left(steps,7), Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) +res=Boole(ff,aa,bb,steps); diff=res-true +say Left(ff,11) Left(aa '-' bb,w+4) Left('Boole',9) Left(steps,7), + Left(Std(res),w) Left(true,w) Format(diff,2,4,,0) say return LeftRect: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,steps -h=(bb-aa)/steps; s=0 +h=(bb-aa)/steps +s=0 do n = 0 to steps-1 s=s+Eval(ff,aa+n*h) end return s*h MidRect: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,steps -h=(bb-aa)/steps; s=0; aa=aa-h/2 +h=(bb-aa)/steps; aa=aa-h/2 +s=0 do n = 1 to steps s=s+Eval(ff,aa+n*h) end return s*h RightRect: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,steps -h=(bb-aa)/steps; s=0 +h=(bb-aa)/steps +s=0 do n = 1 to steps s=s+Eval(ff,aa+n*h) end return s*h Trapezoid: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,steps -h=(bb-aa)/steps; s=0.5*(Eval(ff,aa)+Eval(ff,bb)) +h=(bb-aa)/steps +s=0.5*(Eval(ff,aa)+Eval(ff,bb)) do n = 1 to steps-1 s=s+Eval(ff,aa+n*h) end return s*h Simpson: -procedure expose glob. +procedure expose Memo. arg ff,aa,bb,steps -h=(bb-aa)/steps; s=Eval(ff,aa)+Eval(ff,bb) +h=(bb-aa)/steps +s0=Eval(ff,aa)+Eval(ff,bb); s1=0; s2=0 do n = 1 by 2 to steps-1 - s=s+4*Eval(ff,aa+n*h) + s1=s1+Eval(ff,aa+n*h) end -do n = 2 by 2 to steps-1 - s=s+2*Eval(ff,aa+n*h) +do n = 2 by 2 to steps-2 + s2=s2+Eval(ff,aa+n*h) end -return s*h/3 +return (s0+4*s1+2*s2)*h/3 -include Functions -include Special -include Constants -include Helper -include Abend +Boole: +procedure expose Memo. +arg ff,aa,bb,steps +h=(bb-aa)/steps +s0=7*(Eval(ff,aa)+Eval(ff,bb)); s1=0; s2=0; s3=0 +do n = 1 by 2 to steps-1 + s1=s1+Eval(ff,aa+n*h) +end +do n = 2 by 4 to steps-2 + s2=s2+Eval(ff,aa+n*h) +end +do n = 4 by 4 to steps-4 + s3=s3+Eval(ff,aa+n*h) +end +return (s0+32*s1+12*s2+14*s3)*2*h/45 + +include Math diff --git a/Task/OLE-automation/Julia/ole-automation.jl b/Task/OLE-automation/Julia/ole-automation.jl new file mode 100644 index 0000000000..f93c3c259c --- /dev/null +++ b/Task/OLE-automation/Julia/ole-automation.jl @@ -0,0 +1,34 @@ +using PyCall + +function demoCOM() + # Import Python's win32com.client and time modules + win32com = pyimport("win32com.client") + + # Initialize COM + win32com.CoInitialize() + + # Create Word.Application object + word = win32com.Dispatch("Word.Application") + + # set up new document + word.Visible = true + documents = word.Documents + document = documents.Add() + content = document.Content + paragraphs = content.Paragraphs + + # add the new paragraph of text + paragraph = paragraphs.Add() + rnge = paragraph.Range + rnge.Text = "This is a Rosetta Code test document." + + # wait for Windows to run the requests, then close + sleep(5) + document.Saved = true + document.Close(false) + + word.Quit() + win32com.CoUninitialize() +end + +demoCOM() diff --git a/Task/Object-serialization/C++/object-serialization.cpp b/Task/Object-serialization/C++/object-serialization.cpp index b0c9bb597d..4cd843cf40 100644 --- a/Task/Object-serialization/C++/object-serialization.cpp +++ b/Task/Object-serialization/C++/object-serialization.cpp @@ -12,7 +12,7 @@ public : Employee ( const std::string &dep , const std::string &namen ) : department( dep ) , name( namen ) { - my_id = count++ ; + my_id = count++ ; } std::string getName( ) const { @@ -47,9 +47,9 @@ private : template void serialize( Archive &ar, const unsigned int version ) { - ar & my_id ; - ar & name ; - ar & department ; + ar & my_id ; + ar & name ; + ar & department ; } } ; @@ -57,7 +57,7 @@ private : class Worker : public Employee { public : Worker( const std::string & dep, const std::string &namen , - double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } + double hourlyPay ) : Employee( dep , namen ) , salary( hourlyPay) { } Worker( ) { } @@ -67,7 +67,7 @@ public : void setSalary( double pay ) { if ( pay > 0 ) - salary = pay ; + salary = pay ; } virtual void print( ) { @@ -79,8 +79,8 @@ private : friend class boost::serialization::access ; template void serialize ( Archive & ar, const unsigned int version ) { - ar & boost::serialization::base_object( *this ) ; - ar & salary ; + ar & boost::serialization::base_object( *this ) ; + ar & salary ; } } ; diff --git a/Task/Object-serialization/EchoLisp/object-serialization-1.l b/Task/Object-serialization/EchoLisp/object-serialization-1.l index 62c373d399..12c37e0687 100644 --- a/Task/Object-serialization/EchoLisp/object-serialization-1.l +++ b/Task/Object-serialization/EchoLisp/object-serialization-1.l @@ -1,11 +1,11 @@ (define (person->string self) (format "%a : person." (person-name self))) (define (writer->string self) (format "%a: writer of %a." - (person-name self) - (writer-books self))) + (person-name self) + (writer-books self))) (define (father->string self) (format "%a: father of %a." - (person-name self) - (map person-name (father-children self)))) - + (person-name self) + (map person-name (father-children self)))) + ; 'classes' definition, with inheritance. ; a writer is a person, too. (struct person (name) #:tostring person->string) diff --git a/Task/Object-serialization/Erlang/object-serialization.erl b/Task/Object-serialization/Erlang/object-serialization.erl index f7b0f04e10..6a69470a99 100644 --- a/Task/Object-serialization/Erlang/object-serialization.erl +++ b/Task/Object-serialization/Erlang/object-serialization.erl @@ -6,23 +6,23 @@ -record( person, {entity, email} ). task() -> - Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"}, - print( Person ), - Entity = #entity{name="Entity", date=20111111}, - print( Entity ), - ok = file:write_file( "objects.dat", erlang:term_to_binary([Person, Entity]) ), - {ok, Binary} = file:read_file( "objects.dat" ), - [New_person, New_entity] = erlang:binary_to_term( Binary ), - io:fwrite( "Deserialized\n" ), - print( New_person ), - print( New_entity ). - + Person = #person{entity=#entity{name="Cletus", date=20080808}, email="test+1@localhost.localdomain"}, + print( Person ), + Entity = #entity{name="Entity", date=20111111}, + print( Entity ), + ok = file:write_file( "objects.dat", erlang:term_to_binary([Person, Entity]) ), + {ok, Binary} = file:read_file( "objects.dat" ), + [New_person, New_entity] = erlang:binary_to_term( Binary ), + io:fwrite( "Deserialized\n" ), + print( New_person ), + print( New_entity ). + print( #entity{name=Name, date=Date} ) -> - io:fwrite( "Entity: " ), - io:fwrite( "name: ~p, date: ~p~n", [Name, Date] ); + io:fwrite( "Entity: " ), + io:fwrite( "name: ~p, date: ~p~n", [Name, Date] ); print( #person{entity=Entity, email=Email} ) -> - io:fwrite( "Person: " ), - print( Entity ), - io:fwrite( "\temail: ~p~n", [Email] ). + io:fwrite( "Person: " ), + print( Entity ), + io:fwrite( "\temail: ~p~n", [Email] ). diff --git a/Task/Object-serialization/Objective-C/object-serialization.m b/Task/Object-serialization/Objective-C/object-serialization.m index d6b6aecd64..28009c1150 100644 --- a/Task/Object-serialization/Objective-C/object-serialization.m +++ b/Task/Object-serialization/Objective-C/object-serialization.m @@ -102,17 +102,17 @@ int main() // let us create a fantasy animal Animal *anAnimal = [[Animal alloc] - initWithName: @"Eptohippos" - andLegs: 7 - ]; + initWithName: @"Eptohippos" + andLegs: 7 + ]; // for some reason an Eptohippos is not an horse with 7 legs, // and it is not a mammal, of course... // let us create a fantasy mammal (which is an animal too) Mammal *aMammal = [[Mammal alloc] - initWithName: @"Mammaluc" - hasFur: YES - ]; + initWithName: @"Mammaluc" + hasFur: YES + ]; // let us add some eaten stuff... [aMammal addEatenThing: @"lamb"]; [aMammal addEatenThing: @"table"]; @@ -129,7 +129,7 @@ int main() // now let us store the objects... NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] - initForWritingWithMutableData: data]; + initForWritingWithMutableData: data]; [arch encodeObject: anAnimal forKey: @"Eptohippos"]; [arch encodeObject: aMammal forKey: @"Mammaluc"]; [arch finishEncoding]; @@ -137,9 +137,9 @@ int main() // now we want to retrieve the saved objects... NSData *ldata = [[NSData alloc] - initWithContentsOfFile: @"objects.dat"]; + initWithContentsOfFile: @"objects.dat"]; NSKeyedUnarchived *darch = [[NSKeyedUnarchiver alloc] - initForReadingWithData: ldata]; + initForReadingWithData: ldata]; Animal *archivedAnimal = [darch decodeObjectForKey: @"Eptohippos"]; Mammal *archivedMammal = [darch decodeObjectForKey: @"Mammaluc"]; [darch finishDecoding]; diff --git a/Task/Object-serialization/Python/object-serialization.py b/Task/Object-serialization/Python/object-serialization.py index 4ad7458567..9b2e5b9324 100644 --- a/Task/Object-serialization/Python/object-serialization.py +++ b/Task/Object-serialization/Python/object-serialization.py @@ -6,14 +6,14 @@ import pickle class Entity: - def __init__(self): - self.name = "Entity" - def printName(self): - print self.name + def __init__(self): + self.name = "Entity" + def printName(self): + print self.name class Person(Entity): #OldMan inherits from Entity - def __init__(self): #override constructor - self.name = "Cletus" + def __init__(self): #override constructor + self.name = "Cletus" instance1 = Person() instance1.printName() diff --git a/Task/Object-serialization/REBOL/object-serialization.rebol b/Task/Object-serialization/REBOL/object-serialization.rebol new file mode 100644 index 0000000000..751b30aa2d --- /dev/null +++ b/Task/Object-serialization/REBOL/object-serialization.rebol @@ -0,0 +1,84 @@ +Rebol [ + title: "Rosetta code: Object serialization" + file: %Object_serialization.r3 + url: https://rosettacode.org/wiki/Object_serialization + needs: 2.7.0 +] +; ---------------------------- +; Define a base "class" Person +; ---------------------------- +; In Rebol, `make object! [...]` creates an object with defined fields (and optionally functions). +; Here, Person has two properties: name (string) and age (integer). +Person: make object! [ + name: "" + age: 0 +] + +; ------------------------------------------------ +; "Inherit" a subclass Student from Person +; ------------------------------------------------ +; Since Rebol doesn't have classical inheritance, `make Person [...]` +; makes a copy of the Person object and lets you add or override fields. +; Student adds an extra property: grade (e.g., "A", "B", etc.) +Student: make Person [ + grade: "" +] + +; ------------------------------------------------ +; Inherit another subclass Teacher from Person +; ------------------------------------------------ +; Teacher adds an extra property: subject (teaching subject) +Teacher: make Person [ + subject: "" +] + +; ---------------------------------- +; Create specific instances of each +; ---------------------------------- +; Values in brackets override default properties when creating the object. +john: make Person [name: "John" age: 40] +sally: make Student [name: "Sally" age: 18 grade: "A"] +bob: make Teacher [name: "Bob" age: 50 subject: "Math"] + +; ------------------------------------------------ +; Print text in yellow (assuming ANSI color functions are set up) +; ------------------------------------------------ +print "Original instances:" + +; ------------------------------------------------ +; `probe` prints the value in developer-readable format and returns it +; This is useful for quickly seeing object content +; ------------------------------------------------ +probe john +probe sally +probe bob + +; ------------------------------------------------ +; Create a block containing all three objects +; `reduce` evaluates each word and inserts its value into the block +; ------------------------------------------------ +objects: reduce [john sally bob] + +; ------------------------------------------------ +; Save all object data (including words, values, and types) to a file +; `save/all` preserves the complete object structure +; ------------------------------------------------ +save/all %objects.dat objects + +; ------------------------------------------------ +; Show header for loaded instances +; ------------------------------------------------ +print "Loaded instances:" + +; ------------------------------------------------ +; Load objects back from the file +; `load` reconstructs the original structures from the saved format +; ------------------------------------------------ +read-objects: load %objects.dat + +; ------------------------------------------------ +; Iterate over loaded objects and display them +; ------------------------------------------------ +foreach obj read-objects [ + probe obj +] diff --git a/Task/Odd-word-problem/Nom/odd-word-problem.num b/Task/Odd-word-problem/Nom/odd-word-problem.num new file mode 100644 index 0000000000..ab7a43f37b --- /dev/null +++ b/Task/Odd-word-problem/Nom/odd-word-problem.num @@ -0,0 +1,23 @@ +#* +GRAMMAR PARSE TOKENS + no tokens required, except to store odd/even state + +HISTORY + 13 sept 2021: written + +*# + + begin { add "odd*"; push; } + read; + [:alpha:] { + pop; + B"odd*" { push; get; put; clear; } + B"even*" { push; swap; get; put; clear; } + } + ![:alpha:].!"" { + pop; + B"odd*" { replace "odd*" "even*"; push; } + B"even*" { replace "even*" "odd*"; push; } + swap; print; clear; swap; print; clear; + } + (eof) { get; print; } diff --git a/Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic new file mode 100644 index 0000000000..1e53a70baa --- /dev/null +++ b/Task/Old-Russian-measure-of-length/ANSI-BASIC/old-russian-measure-of-length.basic @@ -0,0 +1,47 @@ +100 REM Old Russian measure of length +110 LET UnitsLength = 13 +120 DIM Units$(1 TO 13), Convs(1 TO 13) +130 REM DIM Units$(1 TO UnitsLength), Convs(1 TO UnitsLength) allowed in some implementations +140 FOR I = 1 TO UnitsLength +150 READ Units$(I) +160 NEXT I +170 DATA tochka, liniya, dyuim, vershok, piad, fut +180 DATA arshin, sazhen, versta, milia, centimeter, meter, kilometer +190 REM All expressed in centimeters +200 FOR I = 1 TO UnitsLength +210 READ Convs(I) +220 NEXT I +230 DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48 +240 DATA 71.12, 213.36, 106680, 746760, 1, 100, 100000 +250 DO +260 PRINT "------------" +270 PRINT +280 FOR I = 1 TO UnitsLength +290 PRINT USING "## ": I; +300 PRINT Units$(I) +310 NEXT I +320 PRINT +330 DO +340 INPUT PROMPT "Please choose a unit 1 to " & STR$(UnitsLength) & " :": Unit +350 LOOP UNTIL (Unit >= 1) AND (Unit <= UnitsLength) +360 DO +370 INPUT PROMPT "Now enter a value in that unit :": Value +380 LOOP UNTIL Value > 0 +390 PRINT +400 PRINT "The equivalent in the remaining units is:" +410 PRINT +420 FOR I = 1 TO UnitsLength +430 IF I <> Unit THEN +440 PRINT USING "#######.######## ": Value * Convs(Unit) / Convs(I); +450 PRINT Units$(I); "(s)" +460 END IF +470 NEXT I +480 PRINT +490 DO +500 INPUT PROMPT "Do another one y/n :": YN$ +510 LET YN$ = LCASE$(YN$) +520 LOOP UNTIL (YN$ = "y") OR (YN$ = "n") +530 PRINT +540 LOOP UNTIL YN$ = "n" +550 PRINT "End of story" +560 END diff --git a/Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic b/Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic new file mode 100644 index 0000000000..2c083f3305 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/ASIC/old-russian-measure-of-length.asic @@ -0,0 +1,65 @@ +REM Old Russian measure of length +DIM Units$(12) +DIM Convs@(12) +DATA "tochka", "liniya", "dyuim", "vershok", "piad", "fut" +DATA "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer" +DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48 +DATA 71.12, 213.36, 106680.0, 746760.0, 1.0, 100.0, 100000.0 +MaxIndex = 12 +NumOfUnits = MaxIndex + 1 +FOR I = 0 TO MaxIndex + READ Units$(I) +NEXT I +FOR I = 0 TO MaxIndex + READ Convs@(I) +NEXT I +Start: + CLS + PRINT + FOR I = 0 TO MaxIndex + IPl1 = I + 1 + PRINT IPl1; + PRINT " "; + PRINT Units$(I) + NEXT I + NU$ = STR$(NumOfUnits) + NU$ = LTRIM$(NU$) + ChooseUnit: + PRINT "Please choose a unit from 1 to "; + PRINT NU$; + PRINT ": "; + INPUT Unit + IF Unit > NumOfUnits THEN ChooseUnit: + IF Unit < 1 THEN ChooseUnit: + Unit = Unit - 1 + EnterVal: + PRINT "Now enter a value in that unit: "; + INPUT V@ + IF V@ <= 0 THEN EnterVal: + CLS + PRINT + PRINT V@; + PRINT " "; + PRINT Units$(Unit); + PRINT "(s) in the remaining units is:" + FOR I = 0 TO MaxIndex + IF I <> Unit THEN + Equiv@ = V@ * Convs@(Unit) + Equiv@ = Equiv@ / Convs@(I) + PRINT Equiv@; + PRINT " "; + PRINT Units$(I); + PRINT "(s)" + ENDIF + NEXT I + AskDoAnother: + PRINT "Do another one y/n"; + INPUT YN$ + YN$ = LCASE$(YN$) + IF YN$ = "n" THEN EndOfStory: + IF YN$ = "y" THEN Start: + GOTO AskDoAnother: + PRINT +EndOfStory: +PRINT "End of story." +END diff --git a/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic index 1ded06cd1e..cfe373328b 100644 --- a/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/BASIC256/old-russian-measure-of-length.basic @@ -1,7 +1,7 @@ arraybase 1 dim units = {"tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"} # all expressed in centimeters -dim convs = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000} +dim convs = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000} do cls diff --git a/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas b/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas index 3171a11df1..0282743228 100644 --- a/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas +++ b/Task/Old-Russian-measure-of-length/Delphi/old-russian-measure-of-length.pas @@ -10,7 +10,7 @@ const 'piad', 'fut', 'arshin', 'sazhen', 'versta', 'milia', 'centimeter', 'meter', 'kilometer'); convs: array[0..12] of double = (0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, 1, 100, 10000); + 71.12, 213.36, 106680, 746760, 1, 100, 100000); function ReadInt(): integer; var diff --git a/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy b/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy index e8f85bebf6..5a81e31690 100644 --- a/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy +++ b/Task/Old-Russian-measure-of-length/EasyLang/old-russian-measure-of-length.easy @@ -1,5 +1,5 @@ units$[] = [ "tochka" "liniya" "dyuim" "vershok" "piad" "fut" "arshin" "sazhen" "versta" "milia" "centimeter" "meter" "kilometer" ] -convs[] = [ 0.254 0.254 2.54 4.445 17.78 30.48 71.12 213.36 10668 74676 1 100 10000 ] +convs[] = [ 0.254 0.254 2.54 4.445 17.78 30.48 71.12 213.36 106680 746760 1 100 100000 ] for i to len units$[] print i & ") " & units$[i] . diff --git a/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic index 78a3cccda5..77ea8551dc 100644 --- a/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/FreeBASIC/old-russian-measure-of-length.basic @@ -6,8 +6,8 @@ Dim units(1 To 13) As String = {"tochka", "liniya", "dyuim", "vershok", "piad", ' all expressed in centimeters Dim convs(1 To 13) As Single = {0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, _ - 71.12, 213.36, 10668, 74676, _ - 1, 100, 10000} + 71.12, 213.36, 106680, 746760, _ + 1, 100, 100000} Dim unit As Integer Dim value As Single Dim yn As String diff --git a/Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic new file mode 100644 index 0000000000..8ba8978205 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/GW-BASIC/old-russian-measure-of-length.basic @@ -0,0 +1,35 @@ +100 REM Old Russian measure of length +110 MAX.INDEX = 12 +120 DIM UNITS$(MAX.INDEX), CONVS(MAX.INDEX) +130 DATA tochka, liniya, dyuim, vershok, piad, fut +140 DATA arshin, sazhen, versta, milia, centimeter, meter, kilometer +150 DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48 +160 DATA 71.12, 213.36, 106680, 746760, 1, 100, 100000 +170 FOR I = 0 TO MAX.INDEX +180 READ UNITS$(I) +190 NEXT I +200 FOR I = 0 TO MAX.INDEX +210 READ CONVS(I) +220 NEXT I +230 FOR I = 0 TO MAX.INDEX +240 PRINT USING "## "; I + 1; +250 PRINT UNITS$(I) +260 NEXT I +270 PRINT +280 PRINT "Please choose a unit 1 to"; MAX.INDEX + 1;: INPUT " :", UNIT: IF (UNIT < 1) OR (UNIT > MAX.INDEX + 1) THEN 280 +290 UNIT = UNIT - 1 +300 INPUT "Now enter a value in that unit:", VALUE: IF VALUE <= 0 THEN 300 +310 PRINT +320 PRINT "The equivalent in the remaining units is:" +330 PRINT +340 FOR I = 0 TO MAX.INDEX +350 IF I <> UNIT THEN PRINT USING "#######.######## "; VALUE * CONVS(UNIT) / CONVS(I);: PRINT UNITS$(I); "(s)" +360 NEXT I +370 PRINT +380 INPUT "Do another one y/n"; YN$ +390 IF UN$ <> "" THEN YN$ = CHR$(ASC(LEFT$(YN$, 1)) OR 32) ' GW-BASIC does not have LCASE$ +400 IF (YN$ <> "y") AND (YN$ <> "n") THEN 380 +410 PRINT +420 IF YN$ <> "n" THEN 230 +430 PRINT "End of story." +440 END diff --git a/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas b/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas index db197da004..c9c0027691 100644 --- a/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas +++ b/Task/Old-Russian-measure-of-length/Gambas/old-russian-measure-of-length.gambas @@ -3,7 +3,7 @@ Public Sub Main() Dim units As String[] = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer"] ' all expressed in centimeters - Dim convs As Single[] = [0.254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000] + Dim convs As Single[] = [0.254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000] Dim i, unit As Integer Dim value As Single Dim yn As String diff --git a/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go b/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go index 012f04d87c..2de3caed73 100644 --- a/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go +++ b/Task/Old-Russian-measure-of-length/Go/old-russian-measure-of-length.go @@ -17,8 +17,8 @@ func main() { convs := []float32{ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, - 1, 100, 10000, + 71.12, 213.36, 106680, 746760, + 1, 100, 100000, } scanner := bufio.NewScanner(os.Stdin) diff --git a/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts b/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts index db0d0e8116..80b757bc91 100644 --- a/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts +++ b/Task/Old-Russian-measure-of-length/Kotlin/old-russian-measure-of-length.kts @@ -8,8 +8,8 @@ fun main(args: Array) { "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer") val convs = arrayOf(0.0254f, 0.254f, 2.54f, 4.445f, 17.78f, 30.48f, - 71.12f, 213.36f, 10668.0f, 74676.0f, - 1.0f, 100.0f, 10000.0f) + 71.12f, 213.36f, 106680.0f, 746760.0f, + 1.0f, 100.0f, 100000.0f) var unit: Int var value: Float var yn : String diff --git a/Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic new file mode 100644 index 0000000000..a7471c0567 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Nascom-BASIC/old-russian-measure-of-length.basic @@ -0,0 +1,31 @@ +10 REM Old Russian measure of length +20 M=12 +30 DIM U$(12),C(12) +40 DATA tochka,liniya,dyuim,vershok,piad,fut +50 DATA arshin,sazhen,versta,milia,centimeter +60 DATA meter,kilometer +70 DATA 0.0254,0.254,2.54,4.445,17.78,30.48 +80 DATA 71.12,213.36,106680,746760,1,100,100000 +90 FOR I=0 TO M:READ U$(I):NEXT I +100 FOR I=0 TO M:READ C(I):NEXT I +110 FOR I=0 TO M:PRINT I+1;U$(I):NEXT I +120 PRINT "Please choose a unit 1 to";M+1; +130 INPUT IU +140 IF (IU<1) OR (IU>M+1) GOTO 120 +150 IU=IU-1 +160 INPUT "Now enter a value in that unit";V +170 IF V<=0 GOTO 160 +180 CLS +190 PRINT V;U$(IU);"(s) in the remaining "; +200 PRINT "units is:" +210 FOR I=0 TO M +220 IF I=IU GOTO 240 +230 PRINT V*C(IU)/C(I);U$(I);"(s)" +240 NEXT I +250 INPUT "Do another one y/n";YN$ +260 IF YN$="" GOTO 250 +270 YN$=CHR$(ASC(LEFT$(YN$,1)) OR 32) +280 IF (YN$<>"n") AND (YN$<>"y") GOTO 250 +290 IF YN$<>"n" GOTO 110 +300 PRINT "End of story." +310 END diff --git a/Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto b/Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto new file mode 100644 index 0000000000..17023e3a5e --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Pluto/old-russian-measure-of-length.pluto @@ -0,0 +1,35 @@ +local fmt = require "fmt" +require "io2" + +local units = { + "tochka", "liniya", "dyuim", "vershok", "piad", "fut", + "arshin", "sazhen", "versta", "milia", + "centimeter", "meter", "kilometer" +} + +local convs = { + 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, + 71.12, 213.36, 106680, 746760, + 1, 100, 100000 +} + +while true do + local i = 0 + for units as u do + fmt.print("%2d %s", i + 1, u) + ++i + end + print() + local unit = io.readInt("Please choose a unit 1 to 13 : ", 1, 13) + local value = io.readNum("Now enter a value in that unit : ", 0) + print("\nThe equivalent in the remaining units is:\n") + for ix, u in units do + if ix != unit then + fmt.print(" %10s : %16.8f", u, value * convs[unit] / convs[ix]) + end + end + print() + local yn = io.readOpt("Do another one y/n : ", "ynYN":split("")) + if yn:lower() == "n" then break end + print() +end diff --git a/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro new file mode 100644 index 0000000000..f97a1c0195 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-1.pro @@ -0,0 +1,101 @@ +:- module(old_russian_unit_conversion, [convert/2]). +:- set_prolog_flag(prefer_rationals, true). % Int/Int --> Rational +:- set_prolog_flag(rational_syntax, natural). % Write as `1/3` +:- use_module(library(clpq)). + +% The core conversion logic + +convert(A, B) :- convert_shag(A, S), convert_shag(B, S). + +convert_shag(tochka(T), S) :- { S / T = 1 / 2800 }. +convert_shag(millimetre(MM), S) :- { S / MM = 10 / 7112 }. +convert_shag(liniya(L), S) :- { S / L = 1 / 280 }. +convert_shag(centimetre(CM), S) :- { S / CM = 100 / 7112 }. +convert_shag(dyuym(D), S) :- { S / D = 1 / 28 }. +convert_shag(vyershok(V), S) :- { S / V = 1 / 16 }. +convert_shag(ladon(L), S) :- { S / L = 3 / 28 }. +convert_shag(pyad(P), S) :- { S / P = 1 / 4 }. +convert_shag(fut(F), S) :- { S / F = 3 / 7 }. +convert_shag(lokot(L), S) :- { S / L = 9 / 14 }. +convert_shag(shag(S), S). +convert_shag(metre(M), S) :- { M / S = 7112 / 10000 }. +convert_shag(sazhen(Sz), S) :- { Sz / S = 1 / 3 }. +convert_shag(kilometre(KM), S) :- { KM / S = 10668 / 15000000 }. +convert_shag(vyersta(V), S) :- { V / S = 1 / 1500 }. + +% The command line interface + +:- initialization(main, main). + +main([AmountA, UnitA]) :- + atom_number(AmountA, NumberA), + build_term(UnitA, NumberA, TermA), + !, + format("~w ~w is~n", [AmountA, UnitA]), + functor(TermA, NormalisedA, _), + foreach( + ( convert(TermA, TermB), + TermB =.. [UnitB, NumberB], + UnitB \= NormalisedA + ), + format("~|~` t~f~20+ ~w~n", [NumberB, UnitB]) + ). + +main([AmountA, UnitA, UnitB]) :- + atom_number(AmountA, NumberA), + build_term(UnitA, NumberA, TermA), + build_term(UnitB, NumberB, TermB), + !, + convert(TermA, TermB), + format("~w ~w is ~f ~w~n", [AmountA, UnitA, NumberB, UnitB]). + +main(_) :- with_output_to(user_error, format("Invalid argument~n", [])), halt(22). + +build_term(A0, N, T) :- normalise(A0, A), T =.. [A, N]. + +% user input normalisation + +normalise(millimetre, millimetre). +normalise(millimeter, millimetre). +normalise(millimetres, millimetre). +normalise(millimeters, millimetre). +normalise(centimetre, centimetre). +normalise(centimeter, centimetre). +normalise(centimetre, centimetre). +normalise(centimetres, centimetre). +normalise(metre, metre). +normalise(meter, metre). +normalise(meters, metre). +normalise(metres, metre). +normalise(kilometre, kilometre). +normalise(kilometer, kilometre). +normalise(kilometers, kilometre). +normalise(kilometres, kilometre). +normalise(tochka, tochka). +normalise(точка, tochka). +normalise(liniya, liniya). +normalise(линия, liniya). +normalise(dyuym, dyuym). +normalise(дюйм, dyuym). +normalise(pyerst, dyuym). +normalise(перст, dyuym). +normalise(vyershok, vyershok). +normalise(вершок, vyershok). +normalise(ladon, ladon). +normalise(ладонь, ladon). +normalise(pyad, pyad). +normalise(пядь, pyad). +normalise(четверть, pyad). +normalise(chyetvyert, pyad). +normalise(fut, fut). +normalise(фут, fut). +normalise(lokot, lokot). +normalise(локоть, lokot). +normalise(shag, shag). +normalise(шаг, shag). +normalise(arshin, shag). +normalise(аршин, shag). +normalise(sazhen, sazhen). +normalise(сажень, sazhen). +normalise(vyersta, vyersta). +normalise(верста, vyersta). diff --git a/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro new file mode 100644 index 0000000000..8d8e400625 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Prolog/old-russian-measure-of-length-2.pro @@ -0,0 +1,19 @@ +?- convert(centimetre(42), fut(Fut)). +Fut = 175/127. + +?- convert(centimetre(42), Unit). +Unit = tochka(210000/127) ; +Unit = millimetre(420) ; +Unit = liniya(21000/127) ; +Unit = centimetre(42) ; +Unit = dyuym(2100/127) ; +Unit = vyershok(1200/127) ; +Unit = ladon(700/127) ; +Unit = pyad(300/127) ; +Unit = fut(175/127) ; +Unit = lokot(350/381) ; +Unit = shag(75/127) ; +Unit = metre(21/50) ; +Unit = sazhen(25/127) ; +Unit = kilometre(21/50000) ; +Unit = vyersta(1/2540). diff --git a/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic index e16f753855..48b4f5df09 100644 --- a/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/QBasic/old-russian-measure-of-length.basic @@ -9,7 +9,7 @@ DIM convs(1 TO 13) AS SINGLE FOR i = 1 TO 13 READ convs(i) NEXT i -DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000 +DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000 DIM unit AS INTEGER DIM value AS SINGLE DIM yn AS STRING diff --git a/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r b/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r index d22b8c0b1d..4ac8464612 100644 --- a/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r +++ b/Task/Old-Russian-measure-of-length/R/old-russian-measure-of-length.r @@ -3,10 +3,7 @@ russian_units <- c(1066.8, 2.1336, 0.7112, 0.04445) names(russian_units) <- c("verst", "sazhen", "arshin", "vershok") #Expand this vector to a matrix with one column each for values in km, m, and cm -metric_expand <- function(x){ - return(cbind(x/1000, x, x*100)) -} - +metric_expand <- function(x) cbind(x/1000, x, x*100) conv_matrix <- metric_expand(russian_units) colnames(conv_matrix) <- c("km", "m", "cm") diff --git a/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring b/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring index e877ded79c..6092a78987 100644 --- a/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring +++ b/Task/Old-Russian-measure-of-length/Ring/old-russian-measure-of-length.ring @@ -6,8 +6,8 @@ units = ["tochka", "liniya", "dyuim", "vershok", "piad", "fut", "centimeter", "meter", "kilometer"] convs = [0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, - 1, 100, 10000] + 71.12, 213.36, 106680, 746760, + 1, 100, 100000] yn = "y" unit = 1 diff --git a/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic index 1f32a3a3d1..658baadb48 100644 --- a/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/True-BASIC/old-russian-measure-of-length.basic @@ -9,7 +9,7 @@ DIM convs(1 TO 13) FOR i = 1 TO 13 READ convs(i) NEXT i -DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668, 74676, 1, 100, 10000 +DATA 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 106680, 746760, 1, 100, 100000 DO CLEAR diff --git a/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren b/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren index 0dfbdaa38b..d689d976f3 100644 --- a/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren +++ b/Task/Old-Russian-measure-of-length/Wren/old-russian-measure-of-length.wren @@ -10,8 +10,8 @@ var units = [ var convs = [ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668, 74676, - 1, 100, 10000 + 71.12, 213.36, 106680, 746760, + 1, 100, 100000 ] while (true) { @@ -39,7 +39,7 @@ while (true) { System.print("\nThe equivalent in the remaining units is:\n") i = 0 for (u in units) { - if (i != unit) Fmt.print(" $10s : $15.8g", u, value*convs[unit]/convs[i]) + if (i != unit) Fmt.print(" $10s : $16.8g", u, value*convs[unit]/convs[i]) i = i + 1 } System.print() diff --git a/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic index 2686352008..ab91040d79 100644 --- a/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/XBasic/old-russian-measure-of-length.basic @@ -14,10 +14,10 @@ units$[13] = "kilometer " ' all expressed in centimeters DIM convs![14] -convs![1] = 0.0254 : convs![2] = 0.254 : convs![3] = 2.54 -convs![4] = 4.445 : convs![5] = 17.78 : convs![6] = 30.48 -convs![7] = 71.12 : convs![8] = 213.36 : convs![9] = 10668 -convs![10] = 74676 : convs![11] = 1 : convs![12] = 100 : convs![13] = 10000 +convs![1] = 0.0254 : convs![2] = 0.254 : convs![3] = 2.54 +convs![4] = 4.445 : convs![5] = 17.78 : convs![6] = 30.48 +convs![7] = 71.12 : convs![8] = 213.36 : convs![9] = 106680 +convs![10] = 746760 : convs![11] = 1 : convs![12] = 100 : convs![13] = 100000 DO PRINT diff --git a/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 b/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 index b8502af775..ee625e467d 100644 --- a/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 +++ b/Task/Old-Russian-measure-of-length/XPL0/old-russian-measure-of-length.xpl0 @@ -6,8 +6,8 @@ real Convs, Value; "centimeter", "meter", "kilometer"]; Convs:= [0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, - 71.12, 213.36, 10668., 74676., - 1., 100., 10000.]; + 71.12, 213.36, 106680., 746760., + 1., 100., 100000.]; loop [for I:= 0 to 13-1 do [if I+1 < 10 then ChOut(0, ^ ); IntOut(0, I+1); diff --git a/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic b/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic index cffccf5896..90672dafbd 100644 --- a/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic +++ b/Task/Old-Russian-measure-of-length/Yabasic/old-russian-measure-of-length.basic @@ -9,8 +9,8 @@ units$(13) = "kilometer" dim convs(14) convs(1) = 0.0254 : convs(2) = 0.254 : convs(3) = 2.54 convs(4) = 4.445 : convs(5) = 17.78 : convs(6) = 30.48 -convs(7) = 71.12 : convs(8) = 213.36 : convs(9) = 10668 -convs(10) = 74676 : convs(11) = 1 : convs(12) = 100 : convs(13) = 10000 +convs(7) = 71.12 : convs(8) = 213.36 : convs(9) = 106680 +convs(10) = 746760 : convs(11) = 1 : convs(12) = 100 : convs(13) = 100000 repeat clear screen diff --git a/Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys b/Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys new file mode 100644 index 0000000000..0befa5d1da --- /dev/null +++ b/Task/One-dimensional-cellular-automata/YAMLScript/one-dimensional-cellular-automata.ys @@ -0,0 +1,17 @@ +!YS-v0 + +defn main(): + each line generate(10 '_###_##_#_#_#_#__#__'): + say: line + +defn generate(n cells): + when n.?: + cons cells: + generate n.--: + loop cs cells, ncs subs(cells 0 1): + if cs.# >= 3: + recur cs.subs(1): + ncs +: + filter(\(_:S == '#') cs.subs(0 3)) + .#.eq(2).if('#' '_') + else: ncs + cs.subs(1) diff --git a/Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb b/Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb new file mode 100644 index 0000000000..a4c4a53126 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/DuckDB/one-of-n-lines-in-a-file.duckdb @@ -0,0 +1,4 @@ +FROM read_csv('input.txt', + header=false, sep='', quote='', escape='', + columns={'line': VARCHAR}, auto_detect=false) +USING SAMPLE 1; diff --git a/Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto b/Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto new file mode 100644 index 0000000000..703536c1a0 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Pluto/order-by-pair-comparisons.pluto @@ -0,0 +1,37 @@ +require "io2" +local fmt = require "fmt" + +-- Inserts item x in list a, and keeps it sorted assuming a is already sorted. +-- If x is already in a, inserts it to the right of the rightmost x. +local function insort_right(a, x, q) + local lo = 1 + local hi = #a + 1 + local yn = "ynYN":split("") + while lo < hi do + local mid = (lo + hi) // 2 + ++q + local prompt = string.format("%2d: Is %6s less than %6s ? y/n: ", q, x, a[mid]) + local less = string.lower(io.readOpt(prompt, yn)) == "y" + if less then + hi = mid + else + lo = mid + 1 + end + end + a:insert(lo, x) + return q +end + +local function order(items) + local ordered = {} + local q = 0 + for items as item do + q = insort_right(ordered, item, q) + end + return ordered +end + +local items = "violet red green indigo blue yellow orange":split(" ") +local ordered = order(items) +print("\nThe colors of the rainbow, in sorted order, are:") +fmt.lprint(ordered) diff --git a/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro new file mode 100644 index 0000000000..afde62e867 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-1.pro @@ -0,0 +1,12 @@ +ask_sort(List, Sorted) :- predsort(ask, List, Sorted). + +ask(Cmp, Left, Right) :- + format("Comparing ~w with ~w: ", [Left, Right]), + get_single_char(Cmp0), + char_code(Cmp1, Cmp0), + ( memberchk(Cmp1, [<, =, >]) + -> Cmp = Cmp1, + writeln(Cmp1) + ; format("Please answer <, = or >."), + ask(Cmp, Left, Right) + ). diff --git a/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro new file mode 100644 index 0000000000..4603eb6939 --- /dev/null +++ b/Task/Order-by-pair-comparisons/Prolog/order-by-pair-comparisons-2.pro @@ -0,0 +1,15 @@ +?- ask_sort(["violet", "red", "green", "indigo", "blue", "yellow", "orange"], Sorted). +Comparing red with green: < +Comparing violet with red: > +Comparing violet with green: > +Comparing indigo with blue: > +Comparing yellow with orange: > +Comparing blue with orange: > +Comparing blue with yellow: > +Comparing red with orange: < +Comparing green with orange: > +Comparing green with yellow: > +Comparing green with blue: < +Comparing violet with blue: > +Comparing violet with indigo: > +Sorted = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]. diff --git a/Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb b/Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb new file mode 100644 index 0000000000..f1f10753c0 --- /dev/null +++ b/Task/Order-two-numerical-lists/DuckDB/order-two-numerical-lists.duckdb @@ -0,0 +1,3 @@ +select [1,2,3] < [1,2,3,4]; +select [1,2,3] < [1,2,4]; +select [1,2,3] < [1,2,3]; diff --git a/Task/Ordered-words/DuckDB/ordered-words.duckdb b/Task/Ordered-words/DuckDB/ordered-words.duckdb new file mode 100644 index 0000000000..e143274fd4 --- /dev/null +++ b/Task/Ordered-words/DuckDB/ordered-words.duckdb @@ -0,0 +1,20 @@ +create or replace function is_sorted(str) as ( + select not exists ( + from (select (c > (lead(c) over ())) as outoforder + from (select unnest(regexp_extract_all(str, '.')) as c)) + where outoforder = true ) +); + +create or replace function longest_ordered_words(file) as table ( + with words as ( + from read_csv_auto( + file, header=false, sep='', quote='', columns={'word': VARCHAR}) + where is_sorted(word)), + mx as (select max(length(word)) as mx from words) + select word + from words, mx + where length(word) = mx + order by word +); + +from longest_ordered_words('unixdict.txt'); diff --git a/Task/Ordered-words/TAV/ordered-words.tav b/Task/Ordered-words/TAV/ordered-words.tav new file mode 100644 index 0000000000..62e3dc8217 --- /dev/null +++ b/Task/Ordered-words/TAV/ordered-words.tav @@ -0,0 +1,20 @@ +main(params):+ + res =: [] \ to hold the words + maxw =: 0 \ maximum wordlength + ?# w =: file 'unixdict.txt' give lines + fault w print stop \ message and stop if error + ? (is ordered w) & w.count >= maxw + ? w.count > maxw \ longer word, + res =: [] \ reset list + res[] =: w \ store at next index in list + maxw =: w.count \ update + print row res join values by ' ' + +\ check word (w) +is ordered (w): + cc =: ' ' \ smallest character + ?# i =: from 1 upto w.count + ? w[i] < cc + :> ?- \ failed + cc =: w[i] + :> ?+ diff --git a/Task/Own-digits-power-sum/Scheme/own-digits-power-sum.scm b/Task/Own-digits-power-sum/Scheme/own-digits-power-sum.scm new file mode 100644 index 0000000000..dfd1ebffcf --- /dev/null +++ b/Task/Own-digits-power-sum/Scheme/own-digits-power-sum.scm @@ -0,0 +1,46 @@ +; checks if all characters in numbers lst1 and lst2 (coverted to lists) are the same + + (define (check_list lst1 lst2) + ; do checks each car of remaining list for equality with char=? + (do ((remaining lst1 (cdr remaining)) + (remaining2 lst2 (cdr remaining2)) + (final-val #t (char=? (car remaining) (car remaining2))) + ) + ( (or (equal? #f final-val) (null? remaining)) + (if (equal? #f final-val) + #f + #t + )) + )) + + ; main function to check +(define (own_pow x) + (let* ( + (test x) + ; length of x as a string + (len (string-length (number->string x))) + ; powers of digits + (powers (apply + (map (lambda (x) (expt x len)) (map string->number (map string (string->list (number->string x) )))))) + ; powers as list of characters + (res (string->list (number->string powers))) + ) + ; checks if sum of powers and the number have the same length as strings + (if (= len (length (string->list (number->string powers)))) + ; if true goes to function check_list + (if (check_list (string->list (number->string x)) res) + #t + #f + ) + #f + ) + ) + ) + +(define limit 10000000) +; loop from 100 to limit + (let loop ((i 100)) + (cond ((<= limit i) 'ok) + (else (if (own_pow i) + (print i) + ) + (loop (+ i 1))))) diff --git a/Task/Padovan-sequence/Julia/padovan-sequence.jl b/Task/Padovan-sequence/Julia/padovan-sequence-1.jl similarity index 92% rename from Task/Padovan-sequence/Julia/padovan-sequence.jl rename to Task/Padovan-sequence/Julia/padovan-sequence-1.jl index 49bbf54add..9767436280 100644 --- a/Task/Padovan-sequence/Julia/padovan-sequence.jl +++ b/Task/Padovan-sequence/Julia/padovan-sequence-1.jl @@ -1,5 +1,5 @@ """ Recursive Padovan """ -rPadovan(n) = (n < 4) ? one(n) : rPadovan(n - 3) + rPadovan(n - 2) +rPadovan(n) = (n < 4) ? oneunit(n) : rPadovan(n - 3) + rPadovan(n - 2) """ Floor function calculation Padovan """ function fPadovan(n)::Int diff --git a/Task/Padovan-sequence/Julia/padovan-sequence-2.jl b/Task/Padovan-sequence/Julia/padovan-sequence-2.jl new file mode 100644 index 0000000000..80958cc378 --- /dev/null +++ b/Task/Padovan-sequence/Julia/padovan-sequence-2.jl @@ -0,0 +1 @@ +padovan(n) = last(BigInt[0 1 1; 1 0 0; 0 1 0] ^ n * BigInt[1, 1, 1]) diff --git a/Task/Padovan-sequence/Phix/padovan-sequence-2.phix b/Task/Padovan-sequence/Phix/padovan-sequence-2.phix index ef5ba05ff2..31a9a813a4 100644 --- a/Task/Padovan-sequence/Phix/padovan-sequence-2.phix +++ b/Task/Padovan-sequence/Phix/padovan-sequence-2.phix @@ -1,49 +1,61 @@ -from math import floor -from collections import deque -from typing import Dict, Generator +%! padovan_recurrent(-P) is multi. +padovan_recurrent(1). +padovan_recurrent(1). +padovan_recurrent(P) :- padovan_recurrent(1, 1, 1, P). +padovan_recurrent( _, _, P , P). +padovan_recurrent(P0, P1, P2, P) :- P3 is P0 + P1, padovan_recurrent(P1, P2, P3, P). -def padovan_r() -> Generator[int, None, None]: - last = deque([1, 1, 1], 4) - while True: - last.append(last[-2] + last[-3]) - yield last.popleft() +%! padovan_truncated(+N, -P) is det. +padovan_truncated(N, P) :- + P is floor(1.324717957244746 ^ (N - 1) / 1.0453567932525329623 + 0.5). -_p, _s = 1.324717957244746025960908854, 1.0453567932525329623 +padovan_l_system(['B' | LS]) --> ['A'], padovan_l_system(LS). +padovan_l_system(['C' | LS]) --> ['B'], padovan_l_system(LS). +padovan_l_system(['A', 'B' | LS]) --> ['C'], padovan_l_system(LS). +padovan_l_system([]) --> []. -def padovan_f(n: int) -> int: - return floor(_p**(n-1) / _s + .5) +fibonacci_l_system(['B' | LS]) --> ['A'], fibonacci_l_system(LS). +fibonacci_l_system(['A', 'B' | LS]) --> ['B'], fibonacci_l_system(LS). +fibonacci_l_system([]) --> []. -def padovan_l(start: str='A', - rules: Dict[str, str]=dict(A='B', B='C', C='AB') - ) -> Generator[str, None, None]: - axiom = start - while True: - yield axiom - axiom = ''.join(rules[ch] for ch in axiom) +l_system(_, String, String). +l_system(DCG, String0, String) :- + once(phrase(call(DCG, String1), String0)), + l_system(DCG, String1, String). +:- meta_predicate l_system(3, -). +%! l_system(:DCG, +String) is multi. +l_system(DCG, String) :- l_system(DCG, ['A'], String). -if __name__ == "__main__": - from itertools import islice +task :- + format("The first 20 Padovan numbers are:~n"), + foreach( + limit(20, padovan_recurrent(Padovan)), + format("~d ", [Padovan]) + ), + format("~nThe first 10 strings produced by the L-system are:~n"), + foreach( + limit(10, l_system(padovan_l_system, LString)), + format("~s ", [LString]) + ), + nl, + run_tests(padovan_sequence). - print("The first twenty terms of the sequence.") - print(str([padovan_f(n) for n in range(20)])[1:-1]) +:- begin_tests(padovan_sequence). - r_generator = padovan_r() - if all(next(r_generator) == padovan_f(n) for n in range(64)): - print("\nThe recurrence and floor based algorithms match to n=63 .") - else: - print("\nThe recurrence and floor based algorithms DIFFER!") +test(recurrence_and_floor_are_same_sequence) :- + once(findnsols(64, PR, padovan_recurrent(PR), PRs)), + numlist(0, 63, Ns), + maplist(padovan_truncated, Ns, PTs), + assertion(PRs == PTs). - print("\nThe first 10 L-system string-lengths and strings") - l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) - print('\n'.join(f" {len(string):3} {repr(string)}" - for string in islice(l_generator, 10))) +test(lengths_of_first_32_strings_is_Padovan_sequence) :- + once(findnsols(32, PR, padovan_recurrent(PR), PRs)), + once(findnsols(32, PL, ( + l_system(padovan_l_system, String), + length(String, PL) + ), PLs)), + assertion(PRs == PLs). - r_generator = padovan_r() - l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) - if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) - for n in range(32)): - print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") - else: - print("\nThe L-system, recurrence and floor based algorithms DIFFER!") +:- end_tests(padovan_sequence). diff --git a/Task/Padovan-sequence/Phix/padovan-sequence-3.phix b/Task/Padovan-sequence/Phix/padovan-sequence-3.phix index 28d825fdf7..ef5ba05ff2 100644 --- a/Task/Padovan-sequence/Phix/padovan-sequence-3.phix +++ b/Task/Padovan-sequence/Phix/padovan-sequence-3.phix @@ -1,136 +1,49 @@ -'''Padovan series''' - -from itertools import chain, islice from math import floor -from operator import eq +from collections import deque +from typing import Dict, Generator -# padovans :: [Int] -def padovans(): - '''Non-finite series of Padovan numbers, - defined in terms of recurrence relations. - ''' - def recurrence(abc): - a, b, c = abc - return a, (b, c, a + b) +def padovan_r() -> Generator[int, None, None]: + last = deque([1, 1, 1], 4) + while True: + last.append(last[-2] + last[-3]) + yield last.popleft() - return unfoldr(recurrence)( - (1, 1, 1) - ) +_p, _s = 1.324717957244746025960908854, 1.0453567932525329623 + +def padovan_f(n: int) -> int: + return floor(_p**(n-1) / _s + .5) + +def padovan_l(start: str='A', + rules: Dict[str, str]=dict(A='B', B='C', C='AB') + ) -> Generator[str, None, None]: + axiom = start + while True: + yield axiom + axiom = ''.join(rules[ch] for ch in axiom) -# padovanFloor :: [Int] -def padovanFloor(): - '''The Padovan series, defined in terms - of a floor function. - ''' - p = 1.324717957244746025960908854 - s = 1.0453567932525329623 +if __name__ == "__main__": + from itertools import islice - def f(n): - return floor(p ** (n - 1) / s + 0.5), 1 + n + print("The first twenty terms of the sequence.") + print(str([padovan_f(n) for n in range(20)])[1:-1]) - return unfoldr(f)(0) + r_generator = padovan_r() + if all(next(r_generator) == padovan_f(n) for n in range(64)): + print("\nThe recurrence and floor based algorithms match to n=63 .") + else: + print("\nThe recurrence and floor based algorithms DIFFER!") + print("\nThe first 10 L-system string-lengths and strings") + l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) + print('\n'.join(f" {len(string):3} {repr(string)}" + for string in islice(l_generator, 10))) -# padovanLSystem : [Int] -def padovanLSystem(): - '''An L-system generating terms whose lengths - are the values of the Padovan integer series. - ''' - def rule(c): - return 'B' if 'A' == c else ( - 'C' if 'B' == c else 'AB' - ) - - def f(s): - return s, ''.join(list(concatMap(rule)(s))) - - return unfoldr(f)('A') - - -# ------------------------- TEST ------------------------- - -# prefixesMatch :: [a] -> [a] -> Bool -def prefixesMatch(xs, ys, n): - '''True if the first n items of each - series are the same. - ''' - return all(map(eq, take(n)(xs), ys)) - - -# main :: IO () -def main(): - '''Test three Padovan functions for - equivalence and expected results. - ''' - print('\n'.join([ - "First 20 padovans:\n", - repr(take(20)(padovans())), - - "\nThe recurrence and floor-based functions" + ( - " match over 64 terms:\n" - ), - repr(prefixesMatch( - padovans(), - padovanFloor(), - 64 - )), - - "\nFirst 10 L-System strings:\n", - repr(take(10)(padovanLSystem())), - - "\nThe lengths of the first 32 L-System strings", - "match the Padovan sequence:\n", - repr(prefixesMatch( - padovans(), - (len(x) for x in padovanLSystem()), - 32 - )) - ])) - - -# ----------------------- GENERIC ------------------------ - -# concatMap :: (a -> [b]) -> [a] -> [b] -def concatMap(f): - '''A concatenated map''' - def go(xs): - return chain.from_iterable(map(f, xs)) - return go - - -# unfoldr :: (b -> Maybe (a, b)) -> b -> [a] -def unfoldr(f): - '''A lazy (generator) list unfolded from a seed value - by repeated application of f until no residue remains. - Dual to fold/reduce. - f returns either None, or just (value, residue). - For a strict output list, wrap the result with list() - ''' - def go(x): - valueResidue = f(x) - while None is not valueResidue: - yield valueResidue[0] - valueResidue = f(valueResidue[1]) - return go - - -# take :: Int -> [a] -> [a] -# take :: Int -> String -> String -def take(n): - '''The prefix of xs of length n, - or xs itself if n > length xs. - ''' - def go(xs): - return ( - xs[0:n] - if isinstance(xs, (list, tuple)) - else list(islice(xs, n)) - ) - return go - - -# MAIN --- -if __name__ == '__main__': - main() + r_generator = padovan_r() + l_generator = padovan_l(start='A', rules=dict(A='B', B='C', C='AB')) + if all(len(next(l_generator)) == padovan_f(n) == next(r_generator) + for n in range(32)): + print("\nThe L-system, recurrence and floor based algorithms match to n=31 .") + else: + print("\nThe L-system, recurrence and floor based algorithms DIFFER!") diff --git a/Task/Padovan-sequence/Phix/padovan-sequence-4.phix b/Task/Padovan-sequence/Phix/padovan-sequence-4.phix new file mode 100644 index 0000000000..28d825fdf7 --- /dev/null +++ b/Task/Padovan-sequence/Phix/padovan-sequence-4.phix @@ -0,0 +1,136 @@ +'''Padovan series''' + +from itertools import chain, islice +from math import floor +from operator import eq + + +# padovans :: [Int] +def padovans(): + '''Non-finite series of Padovan numbers, + defined in terms of recurrence relations. + ''' + def recurrence(abc): + a, b, c = abc + return a, (b, c, a + b) + + return unfoldr(recurrence)( + (1, 1, 1) + ) + + +# padovanFloor :: [Int] +def padovanFloor(): + '''The Padovan series, defined in terms + of a floor function. + ''' + p = 1.324717957244746025960908854 + s = 1.0453567932525329623 + + def f(n): + return floor(p ** (n - 1) / s + 0.5), 1 + n + + return unfoldr(f)(0) + + +# padovanLSystem : [Int] +def padovanLSystem(): + '''An L-system generating terms whose lengths + are the values of the Padovan integer series. + ''' + def rule(c): + return 'B' if 'A' == c else ( + 'C' if 'B' == c else 'AB' + ) + + def f(s): + return s, ''.join(list(concatMap(rule)(s))) + + return unfoldr(f)('A') + + +# ------------------------- TEST ------------------------- + +# prefixesMatch :: [a] -> [a] -> Bool +def prefixesMatch(xs, ys, n): + '''True if the first n items of each + series are the same. + ''' + return all(map(eq, take(n)(xs), ys)) + + +# main :: IO () +def main(): + '''Test three Padovan functions for + equivalence and expected results. + ''' + print('\n'.join([ + "First 20 padovans:\n", + repr(take(20)(padovans())), + + "\nThe recurrence and floor-based functions" + ( + " match over 64 terms:\n" + ), + repr(prefixesMatch( + padovans(), + padovanFloor(), + 64 + )), + + "\nFirst 10 L-System strings:\n", + repr(take(10)(padovanLSystem())), + + "\nThe lengths of the first 32 L-System strings", + "match the Padovan sequence:\n", + repr(prefixesMatch( + padovans(), + (len(x) for x in padovanLSystem()), + 32 + )) + ])) + + +# ----------------------- GENERIC ------------------------ + +# concatMap :: (a -> [b]) -> [a] -> [b] +def concatMap(f): + '''A concatenated map''' + def go(xs): + return chain.from_iterable(map(f, xs)) + return go + + +# unfoldr :: (b -> Maybe (a, b)) -> b -> [a] +def unfoldr(f): + '''A lazy (generator) list unfolded from a seed value + by repeated application of f until no residue remains. + Dual to fold/reduce. + f returns either None, or just (value, residue). + For a strict output list, wrap the result with list() + ''' + def go(x): + valueResidue = f(x) + while None is not valueResidue: + yield valueResidue[0] + valueResidue = f(valueResidue[1]) + return go + + +# take :: Int -> [a] -> [a] +# take :: Int -> String -> String +def take(n): + '''The prefix of xs of length n, + or xs itself if n > length xs. + ''' + def go(xs): + return ( + xs[0:n] + if isinstance(xs, (list, tuple)) + else list(islice(xs, n)) + ) + return go + + +# MAIN --- +if __name__ == '__main__': + main() diff --git a/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg b/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg index 0d7bcdafa8..4b9af86f42 100644 --- a/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg +++ b/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg @@ -2,8 +2,8 @@ PROC palindrome = (STRING s)BOOL:( FOR i TO UPB s OVER 2 DO IF s[i] /= s[UPB s-i+1] THEN GO TO return false FI - OD;Power - else: TRUE EXIT + OD; + TRUE EXIT return false: FALSE ); @@ -16,7 +16,6 @@ PROC palindrome r = (STRING s)BOOL: ; # Test # -main: ( STRING t = "ingirumimusnocteetconsumimurigni"; FORMAT template = $"sequence """g""" "b("is","isnt")" a palindrome"l$; diff --git a/Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb b/Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb new file mode 100644 index 0000000000..848be022a3 --- /dev/null +++ b/Task/Palindrome-detection/DuckDB/palindrome-detection.duckdb @@ -0,0 +1,31 @@ +# One way to create a reference to a string literal is by defining a DuckDB function: +D create or replace function s() as (select 'In girum imus nocte et consumimur igni'); + +D select reverse(s()); +┌────────────────────────────────────────┐ +│ reverse(s()) │ +│ varchar │ +├────────────────────────────────────────┤ +│ ingi rumimusnoc te etcon sumi murig nI │ +└────────────────────────────────────────┘ + +D create or replace function isPalindrome(s) as (SELECT REVERSE(s) = s); + +D select isPalindrome('pip'); +┌─────────────────────┐ +│ ispalindrome('pip') │ +│ boolean │ +├─────────────────────┤ +│ true │ +└─────────────────────┘ + +D create or replace function isQuasiPalindrome(str) as + (isPalindrome( (select regexp_replace(str, ' ', '', 'g')) )); + +D select isQuasiPalindrome('to be bot'); +┌────────────────────────────────┐ +│ isquasipalindrome('to be bot') │ +│ boolean │ +├────────────────────────────────┤ +│ true │ +└────────────────────────────────┘ diff --git a/Task/Palindrome-detection/Pluto/palindrome-detection.pluto b/Task/Palindrome-detection/Pluto/palindrome-detection.pluto new file mode 100644 index 0000000000..71143fae81 --- /dev/null +++ b/Task/Palindrome-detection/Pluto/palindrome-detection.pluto @@ -0,0 +1,7 @@ +function is_palindrome(s) + return s == s:reverse() +end + +print(is_palindrome('rotor')) +print(is_palindrome('racecar')) +print(is_palindrome('rosetta')) diff --git a/Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas b/Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas new file mode 100644 index 0000000000..2a8944a07d --- /dev/null +++ b/Task/Pancake-numbers/Free-Pascal-Lazarus/pancake-numbers.pas @@ -0,0 +1,31 @@ +program pc; + +function pancake(n:integer):integer; +var + gap, sum, adj:integer; +begin + gap := 2; + sum := 2; + adj := -1; + while sum < n do + begin + inc(adj); + gap := gap*2 - 1; + sum := sum + gap; + end; + pancake := n + adj; +end; + +var + i,j,n:integer; +begin + for i := 0 to 3 do + begin + for j := 1 to 5 do + begin + n := i*5 + j; + writeln('p',n:2,pancake(n):5); + end; + writeln; + end +end. diff --git a/Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-1.basic similarity index 100% rename from Task/Pancake-numbers/FreeBASIC/pancake-numbers.basic rename to Task/Pancake-numbers/FreeBASIC/pancake-numbers-1.basic diff --git a/Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic new file mode 100644 index 0000000000..ab2bdc910f --- /dev/null +++ b/Task/Pancake-numbers/FreeBASIC/pancake-numbers-2.basic @@ -0,0 +1,105 @@ +' Reverses the first k elements of a string +Function flipString(s As String, k As Integer) As String + Dim As String res = "" + For i As Integer = k To 1 Step -1 + res &= Mid(s, i, 1) + Next + res &= Mid(s, k + 1) + Return res +End Function + +' Calculate the lexicographic rank of a permutation +Function permutationRank(s As String, n As Integer, fact() As Integer) As Integer + Dim As Integer rank = 0 + For i As Integer = 0 To n - 2 + Dim As Integer cnt = 0 + For j As Integer = i + 1 To n - 1 + If Mid(s, j + 1, 1) < Mid(s, i + 1, 1) Then cnt += 1 + Next + rank += cnt * fact(n - i - 1) + Next + Return rank +End Function + +' Calculate the maximum number of flips for n elements +Sub pancakeNumber(n As Integer) + Dim As Integer i + ' Pre-calculate factorials + Dim As Integer fact(0 To n) + fact(0) = 1 + For i = 1 To n: fact(i) = fact(i - 1) * i: Next + + Dim As Integer totalStates = fact(n) + Dim As Boolean visited(0 To totalStates - 1) + Dim As Integer dist(0 To totalStates - 1) + Dim As String permString(0 To totalStates - 1) + + ' Initial state: ordered permutation + Dim As String start = "" + For i = 1 To n: start &= Str(i): Next + + Dim As Integer startRank = permutationRank(start, n, fact()) + visited(startRank) = True + dist(startRank) = 0 + permString(startRank) = start + + Dim As String queue(0 To totalStates - 1) + Dim As Integer head = 0, tail = 0 + queue(tail) = start + tail += 1 + + ' BFS (Breadth-First Search) to determine the maximum distance from any permutation to the ordinate + While head < tail + Dim As String p = queue(head) + head += 1 + Dim As Integer currentRank = permutationRank(p, n, fact()) + + ' Generar todos los flips posibles + ' Generate all possible flips + For i As Integer = 2 To n + Dim As String q = flipString(p, i) + Dim As Integer r = permutationRank(q, n, fact()) + + If Not visited(r) Then + visited(r) = True + dist(r) = dist(currentRank) + 1 + permString(r) = q + queue(tail) = q + tail += 1 + End If + Next + Wend + + ' Find the maximum distance + Dim As Integer maxDist = 0 + Dim As String maxPerm = "" + For i = 0 To totalStates - 1 + If visited(i) Andalso dist(i) > maxDist Then + maxDist = dist(i) + maxPerm = permString(i) + End If + Next + + ' If no permutation was found (case n=1), use the ordinate + If Len(maxPerm) = 0 Then + For i = 1 To n: maxPerm &= Str(i): Next + End If + + Print Using "Maximum number of flips to sort # elements is ##_. e.g ["; n; maxDist; + For i = 1 To Len(maxPerm) + If i > 1 Then Print "; "; + Print Mid(maxPerm, i, 1); + Next + Print "] -> ["; + For i = 1 To n + If i > 1 Then Print "; "; + Print Str(i); + Next + Print "]" +End Sub + +For n As Integer = 1 To 9 + pancakeNumber(n) +Next + +Sleep diff --git a/Task/Pancake-numbers/Julia/pancake-numbers-1.jl b/Task/Pancake-numbers/Julia/pancake-numbers-1.jl deleted file mode 100644 index aec090ebde..0000000000 --- a/Task/Pancake-numbers/Julia/pancake-numbers-1.jl +++ /dev/null @@ -1,14 +0,0 @@ -function pancake(len) - gap, gapsum, adj = 2, 2, -1 - while gapsum < len - adj += 1 - gap = gap * 2 - 1 - gapsum += gap - end - return len + adj -end - -for i in 1:25 - print("pancake(", lpad(i, 2), ") = ", rpad(pancake(i), 5)) - i % 5 == 0 && println() -end diff --git a/Task/Pancake-numbers/Julia/pancake-numbers-2.jl b/Task/Pancake-numbers/Julia/pancake-numbers.jl similarity index 100% rename from Task/Pancake-numbers/Julia/pancake-numbers-2.jl rename to Task/Pancake-numbers/Julia/pancake-numbers.jl diff --git a/Task/Pancake-numbers/Phix/pancake-numbers-4.phix b/Task/Pancake-numbers/Phix/pancake-numbers-4.phix new file mode 100644 index 0000000000..ab55eb78b0 --- /dev/null +++ b/Task/Pancake-numbers/Phix/pancake-numbers-4.phix @@ -0,0 +1,90 @@ +with javascript_semantics +function permuten(integer i, bool bFinal=true) + -- generate base i+1 representations of the permutes of tagset(i), + -- eg i=3 -> {0(4)123,0(4)132,0(4)213,0(4)231,0(4)312,0(4)321} + -- which in decimal would look like this: {27,30,39,45,54,57} + -- if bFinal is false (internal/recursive use) each element of + -- res is instead a sequence of the individual base i+1 digits. + if i=1 then return iff(bFinal?{1}:{{1}}) end if -- (nb i>0 only) + sequence s = permuten(i-1,false), res = {}, r = repeat(0,i) + integer base = i+1 + for k=1 to i do + r[1] = k + for si in s do + for j=2 to i do + integer sj = si[j-1] + r[j] = sj+(sj>=k) + end for + if bFinal then + atom rd = 0 + for d=1 to i do + rd = rd*base + r[d] + end for + res &= rd + else + res = append(res,deep_copy(r)) + end if + end for + end for + return res +end function + +function flip_base(atom n, integer i, base) + -- flip first i digits of n in specified base, + -- eg 0(11)123456789a,2,11 => 0(11)213456789a + -- aside: round() needed for 64-bit, else + -- eg 11^8 is out by ~5e-11 + atom p = round(power(base,base-i-1)), + h = floor(n/p), r = 0 + for i=1 to i do + r = r*base + rmdr(h,base) + h = floor(h/base) + end for + return r*p+rmdr(n,p) -- (eg 21<1 and flips[fdx]=0 then + flips[fdx] = ft + tdx += 1 + todo[tdx] = fdx + if time()>t1 then + printf(1,"%d/%d...\r",{tdx,length(p)}) + t1 = time()+1 + end if + end if + end for + end for + integer max_flips = largest(flips,return_index:=true) + return {n,flips[max_flips],sprintf("%a",{{base,p[max_flips]}})} +-- return {n,flips[max_flips],p[max_flips]} +end function + +atom t0 = time() +for n=1 to 10 do + printf(1,"pancake(%d):%d, eg %v\n",pancake(n)) +end for +?elapsed(time()-t0) diff --git a/Task/Pancake-numbers/Pluto/pancake-numbers-1.pluto b/Task/Pancake-numbers/Pluto/pancake-numbers-1.pluto new file mode 100644 index 0000000000..61f49ad0dc --- /dev/null +++ b/Task/Pancake-numbers/Pluto/pancake-numbers-1.pluto @@ -0,0 +1,22 @@ +local fmt = require "fmt" + +local function pancake(n) + local gap = 2 + local pg = 1 + local sum_gaps = gap + local adj = -1 + while sum_gaps < n do + ++adj + pg, gap = gap, gap + pg + sum_gaps += gap + end + return n + adj +end + +for i = 0, 3 do + for j = 1, 5 do + local n = i * 5 + j + fmt.write("p(%2d) = %2d ", n, pancake(n)) + end + print() +end diff --git a/Task/Pancake-numbers/Pluto/pancake-numbers-2.pluto b/Task/Pancake-numbers/Pluto/pancake-numbers-2.pluto new file mode 100644 index 0000000000..46e7867776 --- /dev/null +++ b/Task/Pancake-numbers/Pluto/pancake-numbers-2.pluto @@ -0,0 +1,63 @@ +local fmt = require "fmt" + +-- Converts a string of the form "{1, 2}" into an array: {1, 2} +local function as_array(s) + local split = s:sub(2, -2):split(", ") + return split:map(|ss| -> tonumber(ss)) +end + +-- Merges two maps into one. If the same key is present in both maps +-- its value will be the one in the second map. +local function merge_maps(m1, m2) + local m3 = {} + for k, v in m1 do m3[k] = v end + for k, v in m2 do m3[k] = v end + return m3 +end + +-- Finds the maximum value in 'dict' and returns the first key +-- it finds (iteration order is undefined) with that value. +local function find_max(dict) + local max = -1 + local max_key = nil + for k, v in dict do + if v > max then + max = v + max_key = k + end + end + return max_key +end + +local function pancake(len) + local num_stacks = 1 + local goal_stack = fmt.swrite(range(1, len)) + local stacks = {[goal_stack] = 0} + local new_stacks = {[goal_stack] = 0} + for i = 1, 1000 do + local next_stacks = {} + for new_stacks:keys() as key do + local arr = as_array(key) + local pos = 2 + while pos <= len do + local new_stack = arr:slice(1, pos):reverse() + table.move(arr, pos + 1, #arr, pos + 1, new_stack) + new_stack = fmt.swrite(new_stack) + if !stacks[new_stack] then next_stacks[new_stack] = i end + ++pos + end + end + new_stacks = next_stacks + stacks = merge_maps(stacks, new_stacks) + local perms = stacks:size() + if perms == num_stacks then + return {find_max(stacks), i - 1} + end + num_stacks = perms + end +end + +for i = 1, 9 do + local [example, steps] = pancake(i) + fmt.print("pancake(%d) = %-2d example: %s", i, steps, example) +end diff --git a/Task/Pancake-numbers/Pluto/pancake-numbers-3.pluto b/Task/Pancake-numbers/Pluto/pancake-numbers-3.pluto new file mode 100644 index 0000000000..da8732a959 --- /dev/null +++ b/Task/Pancake-numbers/Pluto/pancake-numbers-3.pluto @@ -0,0 +1,51 @@ +local fmt = require "fmt" +require "queue" + +-- Flip the stack of pancakes at the given position. +local function flip(pancakes, pos) + local s = tostring(pancakes) + return tonumber(s:sub(1, pos):reverse() .. s:sub(pos + 1)) +end + +-- Finds the maximum value in 'map' and returns the first key +-- it finds (iteration order is undefined) with that value +-- and the value itself. +local function find_max(map) + local max = -1 + local max_key = nil + for k, v in map do + if v > max then + max = v + max_key = k + end + end + return {max_key, max} +end + +-- Return the nth pancake number. +local function pancake(n) + local init_stack = tonumber(range(1, n):concat("")) + local stack_flips = {[init_stack] = 0} + local queue = new queue() + queue:push(init_stack) + while !queue:empty() do + local stack = queue:pop() + local flips = stack_flips[stack] + 1 + for i = 2, n do + local flipped = flip(stack, i) + if !stack_flips[flipped] then + stack_flips[flipped] = flips + queue:push(flipped) + end + end + end + return find_max(stack_flips) +end + +for n = 1, 9 do + local [pancakes, p] = pancake(n) + local t = {} + for c in tostring(pancakes):gmatch("%d") do t:insert(c) end + pancakes = "{" .. t:concat(", ") .. "}" + fmt.print("pancake(%d) = %-2d example: %s", n, p, pancakes) +end diff --git a/Task/Pancake-numbers/Pluto/pancake-numbers-4.pluto b/Task/Pancake-numbers/Pluto/pancake-numbers-4.pluto new file mode 100644 index 0000000000..f4a9274865 --- /dev/null +++ b/Task/Pancake-numbers/Pluto/pancake-numbers-4.pluto @@ -0,0 +1,55 @@ +local fmt = require "fmt" +require "queue" + +-- Flip the stack of pancakes at the given position. +local function flip(pancakes, pos, n) + local s = tostring(pancakes) + if n == 10 and #s == 9 do s = "0" .. s end + return tonumber(s:sub(1, pos):reverse() .. s:sub(pos + 1)) +end + +-- Finds the maximum value in 'map' and returns the first key +-- it finds (iteration order is undefined) with that value +-- and the value itself. +local function find_max(map) + local max = -1 + local max_key = nil + for k, v in map do + if v > max then + max = v + max_key = k + end + end + return {max_key, max} +end + +-- Return the nth pancake number. +local function pancake(n) + local init_stack = n < 10 ? tonumber(range(1, n):concat("")) : + tonumber(range(1, 9):concat("")) .. "0" + local stack_flips = {[init_stack] = 0} + local queue = new queue() + queue:push(init_stack) + while !queue:empty() do + local stack = queue:pop() + local flips = stack_flips[stack] + 1 + for i = 2, n do + local flipped = flip(stack, i, n) + if !stack_flips[flipped] then + stack_flips[flipped] = flips + queue:push(flipped) + end + end + end + return find_max(stack_flips) +end + +for n = 1, 10 do + local [pancakes, p] = pancake(n) + local t = {} + for c in tostring(pancakes):gmatch("%d") do t:insert(c) end + if n == 10 and #t == 9 then t:insert(1, "0") end + pancakes = "{" .. t:concat(", ") .. "}" + pancakes = pancakes:replace("0", "10") + fmt.print("pancake(%2d) = %-2d example: %s", n, p, pancakes) +end diff --git a/Task/Pancake-numbers/Ruby/pancake-numbers-1.rb b/Task/Pancake-numbers/Ruby/pancake-numbers-1.rb new file mode 100644 index 0000000000..ec6609f336 --- /dev/null +++ b/Task/Pancake-numbers/Ruby/pancake-numbers-1.rb @@ -0,0 +1,26 @@ +def pancake(n) + init = (1..n).to_a + stack_flips = { init => 0 } + queue = [init] + + until queue.empty? + # NOTE: Ruby does not reallocate the entire array for every call to `shift`. + stack = queue.shift + flips = stack_flips[stack] + 1 + + (2..n).each do |i| + flipped = [*stack[...i].reverse, *stack[i..]] + unless stack_flips.key?(flipped) + stack_flips[flipped] = flips + queue.push(flipped) + end + end + end + + stack_flips.max_by { |_, v| v } +end + +(1...10).each do |n| + pancakes, p = pancake(n) + printf("pancake(%d) = %2d. Example %s\n", n, p, pancakes) +end diff --git a/Task/Pancake-numbers/Ruby/pancake-numbers-2.rb b/Task/Pancake-numbers/Ruby/pancake-numbers-2.rb new file mode 100644 index 0000000000..9ed4e7af66 --- /dev/null +++ b/Task/Pancake-numbers/Ruby/pancake-numbers-2.rb @@ -0,0 +1,22 @@ +def pancake(n) + gap = 2 + pg = 1 + sum = 2 + adj = -1 + while sum < n + adj = adj + 1 + t = pg + pg = gap + gap = gap + t + sum = sum + gap + end + return n + adj +end + +for i in 0..3 + for j in 1..5 + n = i * 5 + j + print "p(%2d) = %2d " % [n, pancake(n)] + end + print "\n" +end diff --git a/Task/Pancake-numbers/Ruby/pancake-numbers.rb b/Task/Pancake-numbers/Ruby/pancake-numbers.rb deleted file mode 100644 index 3f3e3dbe1a..0000000000 --- a/Task/Pancake-numbers/Ruby/pancake-numbers.rb +++ /dev/null @@ -1,19 +0,0 @@ -def pancake(n) - gap = 2 - sum = 2 - adj = -1 - while sum < n - adj = adj + 1 - gap = gap * 2 - 1 - sum = sum + gap - end - return n + adj -end - -for i in 0 .. 3 - for j in 1 .. 5 - n = i * 5 + j - print "p(%2d) = %2d " % [n, pancake(n)] - end - print "\n" -end diff --git a/Task/Pancake-numbers/Wren/pancake-numbers-1.wren b/Task/Pancake-numbers/Wren/pancake-numbers-1.wren index 0cf934127d..a066f24a3a 100644 --- a/Task/Pancake-numbers/Wren/pancake-numbers-1.wren +++ b/Task/Pancake-numbers/Wren/pancake-numbers-1.wren @@ -2,12 +2,15 @@ import "./fmt" for Fmt var pancake = Fn.new { |n| var gap = 2 - var sum = 2 + var pg = 1 + var sumGaps = gap var adj = -1 - while (sum < n) { + while (sumGaps < n) { adj = adj + 1 - gap = gap*2 - 1 - sum = sum + gap + var t = pg + pg = gap + gap = gap + t + sumGaps = sumGaps + gap } return n + adj } diff --git a/Task/Pancake-numbers/Wren/pancake-numbers-3.wren b/Task/Pancake-numbers/Wren/pancake-numbers-3.wren new file mode 100644 index 0000000000..997a6313b3 --- /dev/null +++ b/Task/Pancake-numbers/Wren/pancake-numbers-3.wren @@ -0,0 +1,86 @@ +import "./fmt" for Fmt + +class Queue { + construct new(limit) { + _limit = limit + _first = 0 + _last = -1 + _list = [] + } + + isEmpty { _first > _last } + + push(v) { + _last = _last + 1 + _list.add(v) + } + + // Doesn't actually remove the first element from the internal list. + // Just changes a pointer so that the next element (if any) becomes the first. + // However, when the number of popped elements reaches _limit, they are + // cleared out and the pointers reset. + pop() { + if (isEmpty) Fiber.abort("Queue is empty.") + var value = _list[_first] + _first = _first + 1 + if (_first == _limit) { + _list = _list[_first..-1] + _first = 0 + _last = _last - _limit + } + return value + } +} + +// Flip the stack of pancakes at the given position. +var flip = Fn.new { |pancakes, pos| + pancakes = pancakes.toString + return Num.fromString(pancakes[0...pos][-1..0] + pancakes[pos..-1]) +} + +// Finds the maximum value in 'map' and returns the first key +// it finds (iteration order is undefined) with that value +// and the value itself. +var findMax = Fn.new { |map| + var max = -1 + var maxKey = null + for (me in map) { + if (me.value > max) { + max = me.value + maxKey = me.key + } + } + return [maxKey, max] +} + +// Return the nth pancake number. +var pancake = Fn.new { |n| + var initStack = Num.fromString((1..n).join("")) + var stackFlips = { initStack: 0 } + var queue = Queue.new(100000) // say + queue.push(initStack) + while (!queue.isEmpty) { + var stack = queue.pop() + var flips = stackFlips[stack] + 1 + var i = 2 + while (i <= n) { + var flipped = flip.call(stack, i) + if (!stackFlips.containsKey(flipped)) { + stackFlips[flipped] = flips + queue.push(flipped) + } + i = i + 1 + } + } + return findMax.call(stackFlips) +} + +var start = System.clock +System.print("The maximum number of flips to sort a given number of elements is:") +for (n in 1..9) { + var res = pancake.call(n) + var pancakes = "[" + res[0].toString.map{ |c| c }.join(", ") + "]" + var p = res[1] + Fmt.print("pancake($d) = $-2d example: $n", n, p, pancakes) +} +System.print("\nTook %(System.clock - start) seconds.") diff --git a/Task/Pancake-numbers/Wren/pancake-numbers-4.wren b/Task/Pancake-numbers/Wren/pancake-numbers-4.wren new file mode 100644 index 0000000000..b257ee6379 --- /dev/null +++ b/Task/Pancake-numbers/Wren/pancake-numbers-4.wren @@ -0,0 +1,91 @@ +import "./fmt" for Fmt + +class Queue { + construct new(limit) { + _limit = limit + _first = 0 + _last = -1 + _list = [] + } + + isEmpty { _first > _last } + + push(v) { + _last = _last + 1 + _list.add(v) + } + + // Doesn't actually remove the first element from the internal list. + // Just changes a pointer so that the next element (if any) becomes the first. + // However, when the number of popped elements reaches _limit, they are + // cleared out and the pointers reset. + pop() { + if (isEmpty) Fiber.abort("Queue is empty.") + var value = _list[_first] + _first = _first + 1 + if (_first == _limit) { + _list = _list[_first..-1] + _first = 0 + _last = _last - _limit + } + return value + } +} + +// Flip the stack of pancakes at the given position. +var flip = Fn.new { |pancakes, pos, n| + pancakes = pancakes.toString + if (n == 10 && pancakes.count == 9) pancakes = "0" + pancakes + return Num.fromString(pancakes[0...pos][-1..0] + pancakes[pos..-1]) +} + +// Finds the maximum value in 'map' and returns the first key +// it finds (iteration order is undefined) with that value +// and the value itself. +var findMax = Fn.new { |map| + var max = -1 + var maxKey = null + for (me in map) { + if (me.value > max) { + max = me.value + maxKey = me.key + } + } + return [maxKey, max] +} + +// Return the nth pancake number. +var pancake = Fn.new { |n| + var initStack = n < 10 ? (1..n).join("") : (1..9).join("") + "0" + initStack = Num.fromString(initStack) + var stackFlips = { initStack: 0 } + var queue = Queue.new(100000) // say + queue.push(initStack) + while (!queue.isEmpty) { + var stack = queue.pop() + var flips = stackFlips[stack] + 1 + var i = 2 + while (i <= n) { + var flipped = flip.call(stack, i, n) + if (!stackFlips.containsKey(flipped)) { + stackFlips[flipped] = flips + queue.push(flipped) + } + i = i + 1 + } + } + return findMax.call(stackFlips) +} + +var start = System.clock +System.print("The maximum number of flips to sort a given number of elements is:") +for (n in 1..10) { + var res = pancake.call(n) + res[0] = res[0].toString.map{ |c| c }.toList + if (n == 10 && res[0].count == 9) res[0].insert(0, "0") + var pancakes = "[" + res[0].join(", ") + "]" + if (n == 10) pancakes = pancakes.replace("0", "10") + var p = res[1] + Fmt.print("pancake($2d) = $-2d example: $n", n, p, pancakes) +} +System.print("\nTook %(System.clock - start) seconds.") diff --git a/Task/Parameterized-SQL-statement/DuckDB/parameterized-sql-statement.duckdb b/Task/Parameterized-SQL-statement/DuckDB/parameterized-sql-statement.duckdb new file mode 100644 index 0000000000..d65ef43e9e --- /dev/null +++ b/Task/Parameterized-SQL-statement/DuckDB/parameterized-sql-statement.duckdb @@ -0,0 +1,17 @@ +# Setup +create or replace table players + (name VARCHAR, score INTEGER, active BOOLEAN, jerseyNum UINTEGER); + +insert into players values (NULL, NULL, NULL, 99); + +# Parameterized SQL +prepare update_players as + -- (name, score, active, jerseyNum) + UPDATE players + SET name = $1, score = $2, active = $3 + WHERE jerseyNum = $4 +; + +execute update_players('Lynx', 10, true, '99'); + +from players; diff --git a/Task/Parse-an-IP-Address/Dart/parse-an-ip-address.dart b/Task/Parse-an-IP-Address/Dart/parse-an-ip-address.dart new file mode 100644 index 0000000000..4845ebdd65 --- /dev/null +++ b/Task/Parse-an-IP-Address/Dart/parse-an-ip-address.dart @@ -0,0 +1,128 @@ +import 'dart:io'; + +class ParseIPAddress { + static final RegExp _ipv4Pat = RegExp(r'^(\d+)\.(\d+)\.(\d+)\.(\d+)(?::(\d+))?$'); + static final RegExp _ipv6DoubleColPat = RegExp(r'^\[?([0-9a-f:]*)::([0-9a-f:]*)(?:\]:(\d+))?$'); + static late final RegExp _ipv6Pat; + + static void _initializeIPv6Pattern() { + String ipv6Pattern = r'^\[?'; + for (int i = 1; i <= 7; i++) { + ipv6Pattern += r'([0-9a-f]+):'; + } + ipv6Pattern += r'([0-9a-f]+)(?:\]:(\d+))?$'; + _ipv6Pat = RegExp(ipv6Pattern); + } + + static void main() { + // Initialize the IPv6 pattern + _initializeIPv6Pattern(); + + List tests = [ + "192.168.0.1", + "127.0.0.1", + "256.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "[32e::12f]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + "2001:db8:85a3:0:0:8a2e:370:7334" + ]; + + print('${'Test Case'.padRight(40)} ${'Hex Address'.padRight(32)} Port'); + + for (String ip in tests) { + try { + List parsed = _parseIP(ip); + print('${ip.padRight(40)} ${parsed[0].padRight(32)} ${parsed[1]}'); + } catch (e) { + print('${ip.padRight(40)} Invalid address: ${e.toString()}'); + } + } + } + + static List _parseIP(String ip) { + String hex = ""; + String port = ""; + + // IPv4 + RegExpMatch? ipv4Match = _ipv4Pat.firstMatch(ip); + if (ipv4Match != null) { + for (int i = 1; i <= 4; i++) { + hex += _toHex4(ipv4Match.group(i)!); + } + if (ipv4Match.group(5) != null) { + port = ipv4Match.group(5)!; + } + return [hex, port]; + } + + // IPv6, double colon + RegExpMatch? ipv6DoubleColonMatch = _ipv6DoubleColPat.firstMatch(ip); + if (ipv6DoubleColonMatch != null) { + String p1 = ipv6DoubleColonMatch.group(1) ?? ""; + if (p1.isEmpty) { + p1 = "0"; + } + String p2 = ipv6DoubleColonMatch.group(2) ?? ""; + if (p2.isEmpty) { + p2 = "0"; + } + ip = p1 + _getZero(8 - _numCount(p1) - _numCount(p2)) + p2; + if (ipv6DoubleColonMatch.group(3) != null) { + ip = "[$ip]:${ipv6DoubleColonMatch.group(3)}"; + } + } + + // IPv6 + RegExpMatch? ipv6Match = _ipv6Pat.firstMatch(ip); + if (ipv6Match != null) { + for (int i = 1; i <= 8; i++) { + String hexPart = _toHex6(ipv6Match.group(i)!); + hex += hexPart.padLeft(4, '0'); + } + if (ipv6Match.group(9) != null) { + port = ipv6Match.group(9)!; + } + return [hex, port]; + } + + throw ArgumentError("ERROR 103: Unknown address: $ip"); + } + + static int _numCount(String s) { + return s.split(':').length; + } + + static String _getZero(int count) { + StringBuffer sb = StringBuffer(); + sb.write(":"); + while (count > 0) { + sb.write("0:"); + count--; + } + return sb.toString(); + } + + static String _toHex4(String s) { + int val = int.parse(s); + if (val < 0 || val > 255) { + throw ArgumentError("ERROR 101: Invalid value: $s"); + } + return val.toRadixString(16).toUpperCase().padLeft(2, '0'); + } + + static String _toHex6(String s) { + int val = int.parse(s, radix: 16); + if (val < 0 || val > 65536) { + throw ArgumentError("ERROR 102: Invalid hex value: $s"); + } + return s; + } +} + +void main() { + ParseIPAddress.main(); +} diff --git a/Task/Parse-an-IP-Address/Elixir/parse-an-ip-address.ex b/Task/Parse-an-IP-Address/Elixir/parse-an-ip-address.ex new file mode 100644 index 0000000000..bda1085cf3 --- /dev/null +++ b/Task/Parse-an-IP-Address/Elixir/parse-an-ip-address.ex @@ -0,0 +1,83 @@ +#!/usr/bin/env elixir + +defmodule IPParse do + @moduledoc """ + IP address parser that handles IPv4 and IPv6 addresses with optional ports + """ + + def main(args \\ []) do + addresses = if Enum.empty?(args), do: data(), else: args + + for addr <- addresses do + print(addr, parse(addr)) + end + + System.halt(0) + end + + @spec parse(String.t()) :: + {String.t(), binary(), String.t()} | + {String.t(), binary()} + def parse("[" <> addr0) do + case String.split(addr0, "]", parts: 2) do + [addr] -> + {"IPv6", to_hex(:inet.parse_address(String.to_charlist(addr)))} + + [addr, ":" <> port] -> + {"IPv6", to_hex(:inet.parse_address(String.to_charlist(addr))), port} + end + end + + def parse(addr0) do + case :inet.parse_address(String.to_charlist(addr0)) do + {:error, :einval} -> + [addr, port] = String.split(addr0, ":", parts: 2) + {"IPv4", to_hex(:inet.parse_address(String.to_charlist(addr))), port} + + {:ok, v6_addr} -> + {"IPv6", to_hex({:ok, v6_addr})} + end + end + + @spec to_hex({:ok, :inet.ip_address()}) :: binary() + def to_hex({:ok, {a, b, c, d}}) do + Base.encode16(<>) + end + + def to_hex({:ok, {a, b, c, d, e, f, g, h}}) do + Base.encode16(<>) + end + + def print(input, {family, hex, port}) do + IO.puts("Input: #{input}") + IO.puts("Family: #{family}") + IO.puts("Hex: #{hex}") + IO.puts("Port: #{port}") + IO.puts("") + end + + def print(input, {family, hex}) do + IO.puts("Input: #{input}") + IO.puts("Family: #{family}") + IO.puts("Hex: #{hex}") + IO.puts("") + end + + defp data do + [ + "127.0.0.1", + "127.0.0.1:80", + "::ffff:127.0.0.1", + "::1", + "[::1]:80", + "1::80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80" + ] + end +end + +# Run the main function if this script is executed directly +if __ENV__.file == Path.absname(:escript.script_name()) do + IPParse.main(System.argv()) +end diff --git a/Task/Parse-an-IP-Address/Fortran/parse-an-ip-address.f b/Task/Parse-an-IP-Address/Fortran/parse-an-ip-address.f new file mode 100644 index 0000000000..90429db2f4 --- /dev/null +++ b/Task/Parse-an-IP-Address/Fortran/parse-an-ip-address.f @@ -0,0 +1,320 @@ +program parse_ip_address + implicit none + + ! Parameters + integer, parameter :: MAX_TESTS = 10 + integer, parameter :: MAX_STR_LEN = 100 + integer, parameter :: MAX_HEX_LEN = 32 + + ! Variables + character(len=MAX_STR_LEN), dimension(MAX_TESTS) :: test_cases + character(len=MAX_HEX_LEN) :: hex_address + character(len=10) :: port_str + integer :: i, status + + ! Initialize test cases + test_cases(1) = '192.168.0.1' + test_cases(2) = '127.0.0.1' + test_cases(3) = '256.0.0.1' + test_cases(4) = '127.0.0.1:80' + test_cases(5) = '::1' + test_cases(6) = '[::1]:80' + test_cases(7) = '[32e::12f]:80' + test_cases(8) = '2605:2700:0:3::4713:93e3' + test_cases(9) = '[2605:2700:0:3::4713:93e3]:80' + test_cases(10) = '2001:db8:85a3:0:0:8a2e:370:7334' + + ! Print header + write(*,'(A40,1X,A32,3X,A)') 'Test Case', 'Hex Address', 'Port' + write(*,'(A40,1X,A32,3X,A)') repeat('-',40), repeat('-',32), repeat('-',4) + + ! Process each test case + do i = 1, MAX_TESTS + call parse_ip(trim(test_cases(i)), hex_address, port_str, status) + if (status == 0) then + write(*,'(A40,1X,A32,3X,A)') trim(test_cases(i)), trim(hex_address), trim(port_str) + else + write(*,'(A40,1X,A)') trim(test_cases(i)), 'Invalid address' + end if + end do + +end program parse_ip_address + +! Main parsing subroutine +subroutine parse_ip(ip_str, hex_address, port_str, status) + implicit none + character(len=*), intent(in) :: ip_str + character(len=*), intent(out) :: hex_address, port_str + integer, intent(out) :: status + + ! Try IPv4 first + call parse_ipv4(ip_str, hex_address, port_str, status) + if (status == 0) return + + ! Try IPv6 + call parse_ipv6(ip_str, hex_address, port_str, status) + if (status == 0) return + + ! If neither worked, return error + status = -1 + +end subroutine parse_ip + +! Parse IPv4 address +subroutine parse_ipv4(ip_str, hex_address, port_str, status) + implicit none + character(len=*), intent(in) :: ip_str + character(len=*), intent(out) :: hex_address, port_str + integer, intent(out) :: status + + character(len=100) :: work_str + integer :: dot_pos(3), colon_pos + integer :: octets(4) + integer :: i, start_pos, end_pos, port_val + character(len=2) :: hex_part + + work_str = trim(ip_str) + hex_address = '' + port_str = '' + status = 0 + + ! Find colon for port (if present) + colon_pos = index(work_str, ':', .true.) ! Find last colon + if (colon_pos > 0) then + ! Extract port + read(work_str(colon_pos+1:), *, iostat=status) port_val + if (status /= 0) then + status = -1 + return + end if + write(port_str, '(I0)') port_val + work_str = work_str(1:colon_pos-1) + end if + + ! Find dots + dot_pos(1) = index(work_str, '.') + if (dot_pos(1) == 0) then + status = -1 + return + end if + + dot_pos(2) = index(work_str(dot_pos(1)+1:), '.') + dot_pos(1) + if (dot_pos(2) == dot_pos(1)) then + status = -1 + return + end if + + dot_pos(3) = index(work_str(dot_pos(2)+1:), '.') + dot_pos(2) + if (dot_pos(3) == dot_pos(2)) then + status = -1 + return + end if + + ! Parse octets + read(work_str(1:dot_pos(1)-1), *, iostat=status) octets(1) + if (status /= 0 .or. octets(1) < 0 .or. octets(1) > 255) then + status = -1 + return + end if + + read(work_str(dot_pos(1)+1:dot_pos(2)-1), *, iostat=status) octets(2) + if (status /= 0 .or. octets(2) < 0 .or. octets(2) > 255) then + status = -1 + return + end if + + read(work_str(dot_pos(2)+1:dot_pos(3)-1), *, iostat=status) octets(3) + if (status /= 0 .or. octets(3) < 0 .or. octets(3) > 255) then + status = -1 + return + end if + + read(work_str(dot_pos(3)+1:), *, iostat=status) octets(4) + if (status /= 0 .or. octets(4) < 0 .or. octets(4) > 255) then + status = -1 + return + end if + + ! Convert to hex + do i = 1, 4 + call int_to_hex2(octets(i), hex_part) + hex_address = trim(hex_address) // hex_part + end do + + status = 0 + +end subroutine parse_ipv4 + +! Parse IPv6 address (simplified version) +subroutine parse_ipv6(ip_str, hex_address, port_str, status) + implicit none + character(len=*), intent(in) :: ip_str + character(len=*), intent(out) :: hex_address, port_str + integer, intent(out) :: status + + character(len=100) :: work_str, expanded_str + integer :: bracket_start, bracket_end, colon_pos + integer :: port_val + + work_str = trim(ip_str) + hex_address = '' + port_str = '' + status = 0 + + ! Handle bracketed IPv6 with port + bracket_start = index(work_str, '[') + bracket_end = index(work_str, ']') + + if (bracket_start > 0 .and. bracket_end > bracket_start) then + ! Extract IPv6 part + work_str = work_str(bracket_start+1:bracket_end-1) + + ! Check for port after bracket + colon_pos = index(ip_str(bracket_end+1:), ':') + if (colon_pos > 0) then + read(ip_str(bracket_end+colon_pos+1:), *, iostat=status) port_val + if (status /= 0) then + status = -1 + return + end if + write(port_str, '(I0)') port_val + end if + end if + + ! Expand double colon if present + call expand_ipv6(work_str, expanded_str, status) + if (status /= 0) return + + ! Convert expanded IPv6 to hex + call ipv6_to_hex(expanded_str, hex_address, status) + +end subroutine parse_ipv6 + +! Expand IPv6 double colon notation +subroutine expand_ipv6(ipv6_str, expanded_str, status) + implicit none + character(len=*), intent(in) :: ipv6_str + character(len=*), intent(out) :: expanded_str + integer, intent(out) :: status + + character(len=100) :: work_str + integer :: double_colon_pos, colon_count, zeros_needed + integer :: i, pos + + work_str = trim(ipv6_str) + expanded_str = '' + status = 0 + + ! Find double colon + double_colon_pos = index(work_str, '::') + + if (double_colon_pos == 0) then + ! No double colon, just copy + expanded_str = work_str + return + end if + + ! Count existing colons (excluding the double colon) + colon_count = 0 + do i = 1, len_trim(work_str) + if (work_str(i:i) == ':') colon_count = colon_count + 1 + end do + colon_count = colon_count - 2 ! Subtract the double colon + + ! Calculate zeros needed + zeros_needed = 8 - colon_count - 1 + if (double_colon_pos == 1) zeros_needed = zeros_needed + 1 + if (double_colon_pos == len_trim(work_str)-1) zeros_needed = zeros_needed + 1 + + ! Build expanded string + if (double_colon_pos == 1) then + expanded_str = '0' + do i = 1, zeros_needed - 1 + expanded_str = trim(expanded_str) // ':0' + end do + if (len_trim(work_str) > 2) then + expanded_str = trim(expanded_str) // work_str(3:) + end if + else if (double_colon_pos == len_trim(work_str)-1) then + expanded_str = work_str(1:double_colon_pos-1) + do i = 1, zeros_needed + expanded_str = trim(expanded_str) // ':0' + end do + else + expanded_str = work_str(1:double_colon_pos-1) + do i = 1, zeros_needed + expanded_str = trim(expanded_str) // ':0' + end do + expanded_str = trim(expanded_str) // work_str(double_colon_pos+2:) + end if + +end subroutine expand_ipv6 + +! Convert expanded IPv6 to hex +subroutine ipv6_to_hex(ipv6_str, hex_address, status) + implicit none + character(len=*), intent(in) :: ipv6_str + character(len=*), intent(out) :: hex_address + integer, intent(out) :: status + + character(len=100) :: work_str + character(len=10) :: segment + character(len=4) :: hex_segment + integer :: colon_pos, start_pos, i + + work_str = trim(ipv6_str) // ':' ! Add trailing colon for easier parsing + hex_address = '' + start_pos = 1 + status = 0 + + do i = 1, 8 + colon_pos = index(work_str(start_pos:), ':') + if (colon_pos == 0) then + status = -1 + return + end if + colon_pos = colon_pos + start_pos - 1 + + segment = work_str(start_pos:colon_pos-1) + if (len_trim(segment) == 0) segment = '0' + + ! Pad to 4 hex digits + write(hex_segment, '(A4)') segment + call pad_hex(hex_segment) + hex_address = trim(hex_address) // hex_segment + + start_pos = colon_pos + 1 + end do + +end subroutine ipv6_to_hex + +! Convert integer to 2-digit hex +subroutine int_to_hex2(val, hex_str) + implicit none + integer, intent(in) :: val + character(len=2), intent(out) :: hex_str + + character(len=16), parameter :: hex_digits = '0123456789abcdef' + + hex_str(1:1) = hex_digits(val/16 + 1:val/16 + 1) + hex_str(2:2) = hex_digits(mod(val,16) + 1:mod(val,16) + 1) + +end subroutine int_to_hex2 + +! Pad hex string with leading zeros +subroutine pad_hex(hex_str) + implicit none + character(len=4), intent(inout) :: hex_str + + integer :: i, j + character(len=4) :: temp_str + + ! Remove leading spaces and pad with zeros + temp_str = adjustl(hex_str) + hex_str = '0000' + j = 4 - len_trim(temp_str) + 1 + if (j <= 4) then + hex_str(j:4) = trim(temp_str) + end if + +end subroutine pad_hex diff --git a/Task/Parse-an-IP-Address/JavaScript/parse-an-ip-address.js b/Task/Parse-an-IP-Address/JavaScript/parse-an-ip-address.js new file mode 100644 index 0000000000..638eb461b9 --- /dev/null +++ b/Task/Parse-an-IP-Address/JavaScript/parse-an-ip-address.js @@ -0,0 +1,123 @@ +// IP Address Parser in JavaScript +class ParseIPAddress { + constructor() { + this.IPV4_PAT = /^(\d+)\.(\d+)\.(\d+)\.(\d+)(?::(\d+))?$/; + this.IPV6_DOUBL_COL_PAT = /^\[?([0-9a-f:]*)::([0-9a-f:]*)(?:\]:(\d+))?$/; + + // Build IPv6 pattern dynamically + let ipv6Pattern = "^\\[?"; + for (let i = 1; i <= 7; i++) { + ipv6Pattern += "([0-9a-f]+):"; + } + ipv6Pattern += "([0-9a-f]+)(?:\\]:(\\d+))?$"; + this.IPV6_PAT = new RegExp(ipv6Pattern); + } + + static main() { + const tests = [ + "192.168.0.1", + "127.0.0.1", + "256.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "[32e::12f]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + "2001:db8:85a3:0:0:8a2e:370:7334" + ]; + + const parser = new ParseIPAddress(); + + console.log(`${"Test Case".padEnd(40)} ${"Hex Address".padEnd(32)} Port`); + + for (const ip of tests) { + try { + const parsed = parser.parseIP(ip); + console.log(`${ip.padEnd(40)} ${parsed[0].padEnd(32)} ${parsed[1]}`); + } catch (e) { + console.log(`${ip.padEnd(40)} Invalid address: ${e.message}`); + } + } + } + + parseIP(ip) { + let hex = ""; + let port = ""; + + // IPv4 + const ipv4Match = ip.match(this.IPV4_PAT); + if (ipv4Match) { + for (let i = 1; i <= 4; i++) { + hex += this.toHex4(ipv4Match[i]); + } + if (ipv4Match[5] !== undefined) { + port = ipv4Match[5]; + } + return [hex, port]; + } + + // IPv6, double colon + const ipv6DoubleColonMatch = ip.match(this.IPV6_DOUBL_COL_PAT); + if (ipv6DoubleColonMatch) { + let p1 = ipv6DoubleColonMatch[1]; + if (p1 === "") { + p1 = "0"; + } + let p2 = ipv6DoubleColonMatch[2]; + if (p2 === "") { + p2 = "0"; + } + ip = p1 + this.getZero(8 - this.numCount(p1) - this.numCount(p2)) + p2; + if (ipv6DoubleColonMatch[3] !== undefined) { + ip = "[" + ip + "]:" + ipv6DoubleColonMatch[3]; + } + } + + // IPv6 + const ipv6Match = ip.match(this.IPV6_PAT); + if (ipv6Match) { + for (let i = 1; i <= 8; i++) { + hex += this.toHex6(ipv6Match[i]).padStart(4, "0"); + } + if (ipv6Match[9] !== undefined) { + port = ipv6Match[9]; + } + return [hex, port]; + } + + throw new Error("ERROR 103: Unknown address: " + ip); + } + + numCount(s) { + return s.split(":").length; + } + + getZero(count) { + let result = ":"; + while (count > 0) { + result += "0:"; + count--; + } + return result; + } + + toHex4(s) { + const val = parseInt(s, 10); + if (val < 0 || val > 255) { + throw new Error("ERROR 101: Invalid value : " + s); + } + return val.toString(16).padStart(2, "0"); + } + + toHex6(s) { + const val = parseInt(s, 16); + if (val < 0 || val > 65536) { + throw new Error("ERROR 102: Invalid hex value : " + s); + } + return s; + } +} + +// Run the main function +ParseIPAddress.main(); diff --git a/Task/Parse-an-IP-Address/Mathematica/parse-an-ip-address.math b/Task/Parse-an-IP-Address/Mathematica/parse-an-ip-address.math new file mode 100644 index 0000000000..5ad915d5f0 --- /dev/null +++ b/Task/Parse-an-IP-Address/Mathematica/parse-an-ip-address.math @@ -0,0 +1,100 @@ +testdata = {"127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", + "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", + "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", + "1::", "[1::]:80", "::", "[::]:80"}; + +maybev4[ip_] := StringCount[ip, "."] > 0 && StringCount[ip, ":"] < 2 + +maybev6[ip_] := StringCount[ip, ":"] > 1 + +parseip[ip_] := Module[{mat, port, ipaddr, iphex, addressspace}, + (* Try to match IPv6 with brackets and port *) + mat = StringCases[ip, + RegularExpression["^\\[([:.\\da-fA-F]+)\\]:(\\d+)$"] -> {"$1", "$2"}]; + + If[Length[mat] > 0, + {ipaddr, port} = First[mat], + (* Try to match IPv4 with port *) + mat = StringCases[ip, + RegularExpression["^([\\d.]+)[:/](\\d+)$"] -> {"$1", "$2"}]; + If[Length[mat] > 0, + {ipaddr, port} = First[mat], + (* No port found *) + {ipaddr, port} = {ip, "none"} + ] + ]; + + If[maybev4[ipaddr], + Print["Processing ip v4 ", ipaddr]; + (* Convert IPv4 to hex *) + Module[{octets, ipint}, + octets = ToExpression /@ StringSplit[ipaddr, "."]; + ipint = Total[MapIndexed[#1*256^(4 - First[#2]) &, octets]]; + iphex = IntegerString[ipint, 16]; + ]; + addressspace = "IPv4", + + If[maybev6[ipaddr], + Print["Processing ip v6 ", ipaddr]; + (* Convert IPv6 to hex *) + Module[{cleanip, parts, expandedparts, fullhex}, + cleanip = StringReplace[ipaddr, {"[" -> "", "]" -> ""}]; + + (* Handle embedded IPv4 addresses *) + If[StringContainsQ[cleanip, "."], + Module[{parts, ipv4part, ipv6parts, ipv4octets, ipv4hex}, + parts = StringSplit[cleanip, ":"]; + (* Find the part with dots (IPv4) *) + ipv4part = SelectFirst[parts, StringContainsQ[#, "."] &]; + ipv6parts = DeleteCases[parts, ipv4part]; + + If[ipv4part =!= Missing["NotFound"], + ipv4octets = ToExpression /@ StringSplit[ipv4part, "."]; + (* Convert IPv4 to two 16-bit hex values *) + ipv4hex = { + IntegerString[ipv4octets[[1]]*256 + ipv4octets[[2]], 16], + IntegerString[ipv4octets[[3]]*256 + ipv4octets[[4]], 16] + }; + cleanip = StringJoin[Riffle[Join[ipv6parts, ipv4hex], ":"]]; + ] + ] + ]; + + (* Handle :: expansion *) + If[StringContainsQ[cleanip, "::"], + parts = StringSplit[cleanip, "::"]; + If[Length[parts] == 2, + Module[{left, right, leftparts, rightparts, missing}, + left = If[parts[[1]] == "", {}, StringSplit[parts[[1]], ":"]]; + right = If[parts[[2]] == "", {}, StringSplit[parts[[2]], ":"]]; + missing = 8 - Length[left] - Length[right]; + expandedparts = Join[left, Table["0", missing], right]; + ], + expandedparts = StringSplit[cleanip, ":"] + ], + expandedparts = StringSplit[cleanip, ":"] + ]; + + (* Pad each part to 4 hex digits and join *) + expandedparts = StringPadLeft[#, 4, "0"] & /@ expandedparts; + fullhex = StringJoin[expandedparts]; + + (* Remove leading zeros for final output *) + iphex = IntegerString[FromDigits[fullhex, 16], 16]; + ]; + addressspace = "IPv6", + + (* Neither IPv4 nor IPv6 *) + Throw["Bad IP address argument " <> ipaddr] + ] + ]; + + {iphex, addressspace, port} +] + +(* Test the function *) +Do[ + {hx, add, por} = parseip[ip]; + Print["For input ", ip, ", IP in hex is ", hx, ", address space ", add, ", port ", por, "."], + {ip, testdata} +] diff --git a/Task/Parse-an-IP-Address/OCaml/parse-an-ip-address.ml b/Task/Parse-an-IP-Address/OCaml/parse-an-ip-address.ml new file mode 100644 index 0000000000..6d0fddb066 --- /dev/null +++ b/Task/Parse-an-IP-Address/OCaml/parse-an-ip-address.ml @@ -0,0 +1,192 @@ +open Printf + +(* Custom exception for invalid addresses *) +exception Invalid_address of string + +(* Helper functions for string parsing *) +let is_digit c = c >= '0' && c <= '9' +let is_hex_digit c = is_digit c || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') + +let split_string s delimiter = + let len = String.length s in + let rec aux acc start i = + if i >= len then + if start < len then (String.sub s start (len - start)) :: acc + else acc + else if s.[i] = delimiter then + let part = String.sub s start (i - start) in + aux (part :: acc) (i + 1) (i + 1) + else + aux acc start (i + 1) + in + List.rev (aux [] 0 0) + +let string_contains s substr = + let s_len = String.length s in + let substr_len = String.length substr in + let rec aux i = + if i > s_len - substr_len then false + else if String.sub s i substr_len = substr then true + else aux (i + 1) + in + if substr_len = 0 then true else aux 0 + +(* Check if string contains only digits *) +let is_numeric s = + let len = String.length s in + len > 0 && + let rec aux i = + if i >= len then true + else if is_digit s.[i] then aux (i + 1) + else false + in + aux 0 + +(* Check if string contains only hex digits *) +let is_hex s = + let len = String.length s in + len > 0 && + let rec aux i = + if i >= len then true + else if is_hex_digit (Char.lowercase_ascii s.[i]) then aux (i + 1) + else false + in + aux 0 + +(* Convert decimal string to 2-digit hex for IPv4 *) +let to_hex4 s = + if not (is_numeric s) then + raise (Invalid_address ("ERROR 101: Invalid value : " ^ s)); + let val_int = int_of_string s in + if val_int < 0 || val_int > 255 then + raise (Invalid_address ("ERROR 101: Invalid value : " ^ s)) + else + Printf.sprintf "%02x" val_int + +(* Validate and return hex string for IPv6 *) +let to_hex6 s = + if not (is_hex s) then + raise (Invalid_address ("ERROR 102: Invalid hex value : " ^ s)); + let val_int = int_of_string ("0x" ^ s) in + if val_int < 0 || val_int > 65535 then + raise (Invalid_address ("ERROR 102: Invalid hex value : " ^ s)) + else + s + +(* Parse IPv4 address *) +let parse_ipv4 ip = + let parts = split_string ip '.' in + match parts with + | [p1; p2; p3; p4_port] -> + (* Check if last part has port *) + if string_contains p4_port ":" then + let port_parts = split_string p4_port ':' in + (match port_parts with + | [p4; port] when is_numeric p4 && is_numeric port -> + let hex = (to_hex4 p1) ^ (to_hex4 p2) ^ (to_hex4 p3) ^ (to_hex4 p4) in + (hex, port) + | _ -> raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip))) + else if is_numeric p4_port then + let hex = (to_hex4 p1) ^ (to_hex4 p2) ^ (to_hex4 p3) ^ (to_hex4 p4_port) in + (hex, "") + else + raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip)) + | _ -> raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip)) + +(* Parse IPv6 address *) +let parse_ipv6 ip = + let (clean_ip, port) = + if String.length ip > 0 && ip.[0] = '[' then + (* Bracketed IPv6 with possible port *) + try + let bracket_end = String.index ip ']' in + let addr_part = String.sub ip 1 (bracket_end - 1) in + if bracket_end + 1 < String.length ip && ip.[bracket_end + 1] = ':' then + let port_part = String.sub ip (bracket_end + 2) (String.length ip - bracket_end - 2) in + (addr_part, port_part) + else + (addr_part, "") + with Not_found -> + raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip)) + else + (ip, "") in + + (* Handle double colon expansion *) + let expanded_ip = + if string_contains clean_ip "::" then + (* Split on :: to get before and after parts *) + let double_colon_pos = + let rec find_pos i = + if i >= String.length clean_ip - 1 then -1 + else if clean_ip.[i] = ':' && clean_ip.[i+1] = ':' then i + else find_pos (i + 1) + in + find_pos 0 in + + if double_colon_pos = -1 then + raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip)) + else + let before_part = + if double_colon_pos = 0 then "" + else String.sub clean_ip 0 double_colon_pos in + let after_part = + let start = double_colon_pos + 2 in + if start >= String.length clean_ip then "" + else String.sub clean_ip start (String.length clean_ip - start) in + + let before_groups = if before_part = "" then [] else split_string before_part ':' in + let after_groups = if after_part = "" then [] else split_string after_part ':' in + let total_existing = List.length before_groups + List.length after_groups in + let zeros_needed = 8 - total_existing in + let zero_groups = List.init zeros_needed (fun _ -> "0") in + + String.concat ":" (before_groups @ zero_groups @ after_groups) + else + clean_ip in + + (* Parse the expanded IPv6 *) + let hex_parts = split_string expanded_ip ':' in + if List.length hex_parts = 8 then + let hex = String.concat "" (List.map (fun part -> + Printf.sprintf "%04s" (to_hex6 part) |> + String.map (function ' ' -> '0' | c -> c)) hex_parts) in + (hex, port) + else + raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip)) + +(* Main parsing function *) +let parse_ip ip = + (* Check if it looks like IPv4 (contains dots but no colons except maybe one for port) *) + if string_contains ip "." && + (not (string_contains ip ":") || + (let colon_count = List.length (split_string ip ':') - 1 in colon_count = 1)) then + parse_ipv4 ip + else if string_contains ip ":" then + parse_ipv6 ip + else + raise (Invalid_address ("ERROR 103: Unknown address: " ^ ip)) + +(* Test cases *) +let tests = [| + "192.168.0.1"; + "127.0.0.1"; + "256.0.0.1"; + "127.0.0.1:80"; + "::1"; + "[::1]:80"; + "[32e::12f]:80"; + "2605:2700:0:3::4713:93e3"; + "[2605:2700:0:3::4713:93e3]:80"; + "2001:db8:85a3:0:0:8a2e:370:7334" +|] + +(* Main function *) +let () = + printf "%-40s %-32s %s\n" "Test Case" "Hex Address" "Port"; + Array.iter (fun ip -> + try + let (hex_addr, port) = parse_ip ip in + printf "%-40s %-32s %s\n" ip hex_addr port + with Invalid_address msg -> + printf "%-40s Invalid address: %s\n" ip msg + ) tests diff --git a/Task/Parse-an-IP-Address/R/parse-an-ip-address.r b/Task/Parse-an-IP-Address/R/parse-an-ip-address.r new file mode 100644 index 0000000000..8c2dcc1b56 --- /dev/null +++ b/Task/Parse-an-IP-Address/R/parse-an-ip-address.r @@ -0,0 +1,127 @@ +# IP Address Parser in R +library(stringr) + +# Helper function to convert decimal to 2-digit hex (for IPv4) +to_hex4 <- function(s) { + val <- as.integer(s) + if (is.na(val) || val < 0 || val > 255) { + stop(paste("ERROR 101: Invalid value:", s)) + } + sprintf("%02x", val) +} + +# Helper function to validate and return hex value (for IPv6) +to_hex6 <- function(s) { + val <- strtoi(s, base = 16) + if (is.na(val) || val < 0 || val > 65535) { # Fixed: should be 65535, not 65536 + stop(paste("ERROR 102: Invalid hex value:", s)) + } + return(s) +} + +# Helper function to count number of parts separated by colons +num_count <- function(s) { + if (s == "") return(0) + length(strsplit(s, ":")[[1]]) +} + +# Helper function to generate zero padding for IPv6 double colon expansion +get_zero <- function(count) { + if (count <= 0) return("") + paste0(":", paste(rep("0", count), collapse = ":"), ":") +} + +# Main parsing function +parse_ip <- function(ip) { + hex <- "" + port <- "" + + # IPv4 pattern: xxx.xxx.xxx.xxx with optional :port + ipv4_pattern <- "^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)(?::(\\d+))?$" + ipv4_match <- str_match(ip, ipv4_pattern) + + if (!is.na(ipv4_match[1])) { + # Extract IPv4 components + for (i in 2:5) { + hex <- paste0(hex, to_hex4(ipv4_match[i])) + } + if (!is.na(ipv4_match[6])) { + port <- ipv4_match[6] + } + return(c(hex, port)) + } + + # IPv6 with double colon pattern + ipv6_double_colon_pattern <- "^\\[?([0-9a-f:]*)::([0-9a-f:]*)(?:\\]:(\\d+))?$" + ipv6_dc_match <- str_match(tolower(ip), ipv6_double_colon_pattern) + + if (!is.na(ipv6_dc_match[1])) { + p1 <- ipv6_dc_match[2] + if (p1 == "") p1 <- "0" + + p2 <- ipv6_dc_match[3] + if (p2 == "") p2 <- "0" + + # Expand the double colon + zero_count <- 8 - num_count(p1) - num_count(p2) + expanded_ip <- paste0(p1, get_zero(zero_count), p2) + + # Add port back if it exists + if (!is.na(ipv6_dc_match[4])) { + expanded_ip <- paste0("[", expanded_ip, "]:", ipv6_dc_match[4]) + } + + ip <- expanded_ip + } + + # IPv6 full pattern (8 groups of hex digits) + ipv6_pattern <- "^\\[?([0-9a-f]+):([0-9a-f]+):([0-9a-f]+):([0-9a-f]+):([0-9a-f]+):([0-9a-f]+):([0-9a-f]+):([0-9a-f]+)(?:\\]:(\\d+))?$" + ipv6_match <- str_match(tolower(ip), ipv6_pattern) + + if (!is.na(ipv6_match[1])) { + # Extract IPv6 components + for (i in 2:9) { + hex_part <- to_hex6(ipv6_match[i]) + # Pad to 4 characters + hex <- paste0(hex, sprintf("%04s", hex_part)) + } + hex <- str_replace_all(hex, " ", "0") + + if (!is.na(ipv6_match[10])) { + port <- ipv6_match[10] + } + return(c(hex, port)) + } + + stop(paste("ERROR 103: Unknown address:", ip)) +} + +# Main execution +main <- function() { + tests <- c( + "192.168.0.1", + "127.0.0.1", + "256.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "[32e::12f]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + "2001:db8:85a3:0:0:8a2e:370:7334" + ) + + cat(sprintf("%-40s %-32s %s\n", "Test Case", "Hex Address", "Port")) + + for (ip in tests) { + tryCatch({ + parsed <- parse_ip(ip) + cat(sprintf("%-40s %-32s %s\n", ip, parsed[1], parsed[2])) + }, error = function(e) { + cat(sprintf("%-40s Invalid address: %s\n", ip, e$message)) + }) + } +} + +# Run the main function +main() diff --git a/Task/Parse-an-IP-Address/Rust/parse-an-ip-address.rs b/Task/Parse-an-IP-Address/Rust/parse-an-ip-address-1.rs similarity index 100% rename from Task/Parse-an-IP-Address/Rust/parse-an-ip-address.rs rename to Task/Parse-an-IP-Address/Rust/parse-an-ip-address-1.rs diff --git a/Task/Parse-an-IP-Address/Rust/parse-an-ip-address-2.rs b/Task/Parse-an-IP-Address/Rust/parse-an-ip-address-2.rs new file mode 100644 index 0000000000..df2add4c63 --- /dev/null +++ b/Task/Parse-an-IP-Address/Rust/parse-an-ip-address-2.rs @@ -0,0 +1,354 @@ +use std::net::{Ipv4Addr, Ipv6Addr}; + +#[derive(Debug, Clone, Copy)] +pub enum IpAddr { + V4([u8; 4]), + V6([u8; 16]), +} + +#[derive(Debug)] +pub struct ParseResult { + pub addr: IpAddr, + pub port: Option, + pub consumed: usize, +} + +pub struct Parser<'a> { + input: &'a str, + cursor: usize, +} + +impl<'a> Parser<'a> { + fn new(input: &'a str) -> Self { + Self { input, cursor: 0 } + } + + fn current_char(&self) -> Option { + self.input.chars().nth(self.cursor) + } + + fn peek_char(&self, offset: usize) -> Option { + self.input.chars().nth(self.cursor + offset) + } + + fn advance(&mut self) { + if self.cursor < self.input.len() { + self.cursor += 1; + } + } + + fn find_char(&self, ch: char) -> Option { + self.input[self.cursor..].find(ch).map(|pos| self.cursor + pos) + } + + fn parse_decimal(&mut self) -> Result { + let start = self.cursor; + let mut val = 0u32; + + while let Some(ch) = self.current_char() { + if ch.is_ascii_digit() { + val = val.checked_mul(10).ok_or("decimal overflow")?; + val = val.checked_add((ch as u32) - ('0' as u32)).ok_or("decimal overflow")?; + self.advance(); + } else { + break; + } + } + + if self.cursor == start { + Err("no digits found") + } else { + Ok(val) + } + } + + fn parse_hex(&mut self) -> Result { + let start = self.cursor; + let mut val = 0u32; + + while let Some(ch) = self.current_char() { + let digit = match ch { + '0'..='9' => (ch as u32) - ('0' as u32), + 'a'..='f' => (ch as u32) - ('a' as u32) + 10, + 'A'..='F' => (ch as u32) - ('A' as u32) + 10, + _ => break, + }; + + val = val.checked_shl(4).ok_or("hex overflow")?; + val = val.checked_add(digit).ok_or("hex overflow")?; + self.advance(); + } + + if self.cursor == start { + Err("no hex digits found") + } else { + Ok(val) + } + } + + fn parse_ipv4(&mut self) -> Result<[u8; 4], &'static str> { + let mut addr = [0u8; 4]; + + for i in 0..4 { + let val = self.parse_decimal()?; + if val > 255 { + return Err("IPv4 octet out of range"); + } + addr[i] = val as u8; + + if i < 3 { + if self.current_char() != Some('.') { + return Err("expected '.' in IPv4 address"); + } + self.advance(); + } + } + + Ok(addr) + } + + fn parse_ipv6(&mut self) -> Result<[u8; 16], &'static str> { + let mut addr = [0u8; 16]; + let mut groups = Vec::new(); + let mut compression_pos = None; + let mut has_ipv4_suffix = false; + + // Handle brackets + let has_brackets = self.current_char() == Some('['); + if has_brackets { + self.advance(); + } + + // Parse groups + loop { + let start_cursor = self.cursor; + + // Check for empty group (compression) + if self.current_char() == Some(':') { + if compression_pos.is_some() { + // Check if this is the end of the address + if groups.len() == 0 || (groups.len() == 1 && compression_pos == Some(0)) { + break; + } + return Err("multiple :: compressions not allowed"); + } + + compression_pos = Some(groups.len()); + self.advance(); + + // Handle leading :: + if groups.is_empty() && self.current_char() == Some(':') { + self.advance(); + } + continue; + } + + // Try to parse hex + match self.parse_hex() { + Ok(val) => { + if val > 0xFFFF { + return Err("IPv6 group out of range"); + } + + // Check for IPv4 suffix + if self.current_char() == Some('.') { + // Rewind and parse as IPv4 + self.cursor = start_cursor; + let ipv4_addr = self.parse_ipv4()?; + + // Validate IPv4-mapped IPv6 prefix + if groups.len() != 6 || + groups[0..5] != [0, 0, 0, 0, 0] || + groups[5] != 0xFFFF { + return Err("IPv4 suffix only allowed in ::ffff: mapping"); + } + + // Add IPv4 bytes as two 16-bit groups + groups.push(((ipv4_addr[0] as u16) << 8) | (ipv4_addr[1] as u16)); + groups.push(((ipv4_addr[2] as u16) << 8) | (ipv4_addr[3] as u16)); + has_ipv4_suffix = true; + break; + } + + groups.push(val as u16); + + // Check for continuation + if self.current_char() == Some(':') { + self.advance(); + } else { + break; + } + } + Err(_) => { + if groups.is_empty() { + return Err("invalid IPv6 format"); + } + break; + } + } + } + + // Handle compression + if let Some(pos) = compression_pos { + let groups_after = groups.len() - pos; + let zeros_needed = 8 - groups.len(); + + if zeros_needed > 0 { + let mut new_groups = Vec::new(); + new_groups.extend_from_slice(&groups[..pos]); + new_groups.resize(new_groups.len() + zeros_needed, 0); + new_groups.extend_from_slice(&groups[pos..]); + groups = new_groups; + } + } + + if groups.len() != 8 { + return Err("IPv6 address must have 8 groups"); + } + + // Convert to bytes + for (i, &group) in groups.iter().enumerate() { + addr[i * 2] = (group >> 8) as u8; + addr[i * 2 + 1] = (group & 0xFF) as u8; + } + + // Validate IPv4-mapped address + if has_ipv4_suffix { + let ipv4_mapped_prefix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF]; + if addr[..12] != ipv4_mapped_prefix { + return Err("invalid IPv4-mapped IPv6 address"); + } + } + + // Handle closing bracket + if has_brackets { + if self.current_char() != Some(']') { + return Err("expected closing bracket"); + } + self.advance(); + } + + Ok(addr) + } + + fn parse_port(&mut self) -> Result { + if self.current_char() != Some(':') { + return Err("expected ':' before port"); + } + self.advance(); + + let port = self.parse_decimal()?; + if port > 65535 { + return Err("port out of range"); + } + + Ok(port as u16) + } +} + +pub fn parse_ipv4_or_ipv6(input: &str) -> Result { + let mut parser = Parser::new(input); + + // Determine if this looks like IPv6 + let colon_pos = parser.find_char(':'); + let dot_pos = parser.find_char('.'); + let bracket_pos = parser.find_char('['); + + let is_ipv6 = bracket_pos.is_some() + || dot_pos.is_none() + || (colon_pos.is_some() && (dot_pos.is_none() || colon_pos < dot_pos)); + + let addr = if is_ipv6 { + IpAddr::V6(parser.parse_ipv6()?) + } else { + IpAddr::V4(parser.parse_ipv4()?) + }; + + let port = if parser.current_char() == Some(':') { + Some(parser.parse_port()?) + } else { + None + }; + + Ok(ParseResult { + addr, + port, + consumed: parser.cursor, + }) +} + +// Helper function for compatibility +pub fn parse_ipv4_or_ipv6_simple(input: &str) -> Result<(IpAddr, Option, bool), &'static str> { + let result = parse_ipv4_or_ipv6(input)?; + let is_ipv6 = matches!(result.addr, IpAddr::V6(_)); + Ok((result.addr, result.port, is_ipv6)) +} + +fn dump_bytes(bytes: &[u8]) { + for &byte in bytes { + print!("{:02x}", byte); + } +} + +fn test_case(input: &str) { + println!("Test case '{}'", input); + + match parse_ipv4_or_ipv6(input) { + Ok(result) => { + print!("addr: "); + match result.addr { + IpAddr::V4(addr) => dump_bytes(&addr), + IpAddr::V6(addr) => dump_bytes(&addr), + } + println!(); + + if let Some(port) = result.port { + println!("port: {}", port); + } else { + println!("port absent"); + } + } + Err(e) => { + println!("parse failed: {}", e); + } + } + println!(); +} + +fn main() { + // The "localhost" IPv4 address + test_case("127.0.0.1"); + + // The "localhost" IPv4 address, with a specified port (80) + test_case("127.0.0.1:80"); + + // The "localhost" IPv6 address + test_case("::1"); + + // The "localhost" IPv6 address, with a specified port (80) + test_case("[::1]:80"); + + // Rosetta Code's primary server's public IPv6 address + test_case("2605:2700:0:3::4713:93e3"); + + // Rosetta Code's primary server's public IPv6 address, with a specified port (80) + test_case("[2605:2700:0:3::4713:93e3]:80"); + + // IPv4 space + test_case("::ffff:192.168.173.22"); + + // IPv4 space with port + test_case("[::ffff:192.168.173.22]:80"); + + // Trailing compression + test_case("1::"); + + // Trailing compression with port + test_case("[1::]:80"); + + // 'any' address compression + test_case("::"); + + // 'any' address compression with port + test_case("[::]:80"); +} diff --git a/Task/Parse-an-IP-Address/Swift/parse-an-ip-address.swift b/Task/Parse-an-IP-Address/Swift/parse-an-ip-address.swift new file mode 100644 index 0000000000..4421446979 --- /dev/null +++ b/Task/Parse-an-IP-Address/Swift/parse-an-ip-address.swift @@ -0,0 +1,187 @@ +import Foundation + +struct IPParseResult { + let hexAddress: String + let port: String +} + +enum IPParseError: Error { + case invalidValue(String) + case invalidHexValue(String) + case unknownAddress(String) + + var localizedDescription: String { + switch self { + case .invalidValue(let value): + return "ERROR 101: Invalid value: \(value)" + case .invalidHexValue(let value): + return "ERROR 102: Invalid hex value: \(value)" + case .unknownAddress(let address): + return "ERROR 103: Unknown address: \(address)" + } + } +} + +class ParseIPAddress { + + // IPv4 pattern: matches IP with optional port + private static let ipv4Pattern = #"^(\d+)\.(\d+)\.(\d+)\.(\d+)(?::(\d+))?$"# + + // IPv6 double colon pattern: matches compressed IPv6 with optional port + private static let ipv6DoubleColonPattern = #"^\[?([0-9a-f:]*)::([0-9a-f:]*)(?:\]:(\d+))?$"# + + // IPv6 full pattern: dynamically built for full IPv6 addresses + private static let ipv6Pattern: String = { + var pattern = #"^\[?"# + for i in 1...7 { + pattern += #"([0-9a-f]+):"# + } + pattern += #"([0-9a-f]+)(?:\]:(\d+))?$"# + return pattern + }() + + static func main() { + let tests = [ + "192.168.0.1", + "127.0.0.1", + "256.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "[32e::12f]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + "2001:db8:85a3:0:0:8a2e:370:7334" + ] + + // Print header with proper padding + let header = "Test Case".padding(toLength: 40, withPad: " ", startingAt: 0) + + "Hex Address".padding(toLength: 32, withPad: " ", startingAt: 0) + + " Port" + print(header) + + for ip in tests { + do { + let result = try parseIP(ip) + let output = ip.padding(toLength: 40, withPad: " ", startingAt: 0) + + result.hexAddress.padding(toLength: 32, withPad: " ", startingAt: 0) + + " " + result.port + print(output) + } catch { + let output = ip.padding(toLength: 40, withPad: " ", startingAt: 0) + + "Invalid address: " + error.localizedDescription + print(output) + } + } + } + + private static func parseIP(_ ip: String) throws -> IPParseResult { + var hex = "" + var port = "" + + // Try IPv4 first + if let ipv4Regex = try? NSRegularExpression(pattern: ipv4Pattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: ip.utf16.count) + if let match = ipv4Regex.firstMatch(in: ip, options: [], range: range) { + // Extract the 4 octets + for i in 1...4 { + let groupRange = match.range(at: i) + let octet = String(ip[Range(groupRange, in: ip)!]) + hex += try toHex4(octet) + } + + // Check for port + let portRange = match.range(at: 5) + if portRange.location != NSNotFound { + port = String(ip[Range(portRange, in: ip)!]) + } + + return IPParseResult(hexAddress: hex, port: port) + } + } + + var modifiedIP = ip + + // Try IPv6 with double colon + if let ipv6DoubleColonRegex = try? NSRegularExpression(pattern: ipv6DoubleColonPattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: ip.utf16.count) + if let match = ipv6DoubleColonRegex.firstMatch(in: ip, options: [], range: range) { + let p1Range = match.range(at: 1) + let p2Range = match.range(at: 2) + let portRange = match.range(at: 3) + + var p1 = p1Range.location != NSNotFound ? String(ip[Range(p1Range, in: ip)!]) : "" + var p2 = p2Range.location != NSNotFound ? String(ip[Range(p2Range, in: ip)!]) : "" + + if p1.isEmpty { + p1 = "0" + } + if p2.isEmpty { + p2 = "0" + } + + let zeroCount = 8 - numCount(p1) - numCount(p2) + modifiedIP = p1 + getZero(zeroCount) + p2 + + if portRange.location != NSNotFound { + let portStr = String(ip[Range(portRange, in: ip)!]) + modifiedIP = "[\(modifiedIP)]:\(portStr)" + } + } + } + + // Try full IPv6 + if let ipv6Regex = try? NSRegularExpression(pattern: ipv6Pattern, options: [.caseInsensitive]) { + let range = NSRange(location: 0, length: modifiedIP.utf16.count) + if let match = ipv6Regex.firstMatch(in: modifiedIP, options: [], range: range) { + // Extract the 8 groups + for i in 1...8 { + let groupRange = match.range(at: i) + let group = String(modifiedIP[Range(groupRange, in: modifiedIP)!]) + let hexGroup = try toHex6(group) + let paddedHex = hexGroup.padding(toLength: 4, withPad: "0", startingAt: 0) + hex += paddedHex + } + + // Check for port + let portRange = match.range(at: 9) + if portRange.location != NSNotFound { + port = String(modifiedIP[Range(portRange, in: modifiedIP)!]) + } + + return IPParseResult(hexAddress: hex, port: port) + } + } + + throw IPParseError.unknownAddress(ip) + } + + private static func numCount(_ s: String) -> Int { + return s.components(separatedBy: ":").count + } + + private static func getZero(_ count: Int) -> String { + var result = ":" + for _ in 0.. String { + guard let val = Int(s), val >= 0 && val <= 255 else { + throw IPParseError.invalidValue(s) + } + return String(format: "%02x", val) + } + + private static func toHex6(_ s: String) throws -> String { + guard let val = Int(s, radix: 16), val >= 0 && val <= 65535 else { + throw IPParseError.invalidHexValue(s) + } + return s + } +} + +// Run the program +ParseIPAddress.main() diff --git a/Task/Parse-an-IP-Address/Zig/parse-an-ip-address.zig b/Task/Parse-an-IP-Address/Zig/parse-an-ip-address.zig new file mode 100644 index 0000000000..c3479774f5 --- /dev/null +++ b/Task/Parse-an-IP-Address/Zig/parse-an-ip-address.zig @@ -0,0 +1,238 @@ +const std = @import("std"); +const print = std.debug.print; +const Allocator = std.mem.Allocator; +const ArrayList = std.ArrayList; + +const ParseError = error{ + InvalidAddress, + InvalidValue, + InvalidHexValue, + OutOfMemory, +}; + +const ParseResult = struct { + hex_address: []const u8, + port: []const u8, + + fn deinit(self: ParseResult, allocator: Allocator) void { + allocator.free(self.hex_address); + allocator.free(self.port); + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const tests = [_][]const u8{ + "192.168.0.1", + "127.0.0.1", + "256.0.0.1", + "127.0.0.1:80", + "::1", + "[::1]:80", + "[32e::12f]:80", + "2605:2700:0:3::4713:93e3", + "[2605:2700:0:3::4713:93e3]:80", + "2001:db8:85a3:0:0:8a2e:370:7334" + }; + + print("{s:<40} {s:<32} {s}\n", .{ "Test Case", "Hex Address", "Port" }); + + for (tests) |ip| { + const result = parseIP(allocator, ip) catch |err| { + const error_msg = switch (err) { + ParseError.InvalidAddress => "Unknown address", + ParseError.InvalidValue => "Invalid value", + ParseError.InvalidHexValue => "Invalid hex value", + else => "Parse error", + }; + print("{s:<40} Invalid address: {s}\n", .{ ip, error_msg }); + continue; + }; + defer result.deinit(allocator); + + print("{s:<40} {s:<32} {s}\n", .{ ip, result.hex_address, result.port }); + } +} + +fn parseIP(allocator: Allocator, ip: []const u8) !ParseResult { + // Try IPv4 first + if (parseIPv4(allocator, ip)) |result| { + return result; + } else |_| {} + + // Try IPv6 with double colon + if (parseIPv6DoubleColon(allocator, ip)) |result| { + return result; + } else |_| {} + + // Try regular IPv6 + if (parseIPv6(allocator, ip)) |result| { + return result; + } else |_| {} + + return ParseError.InvalidAddress; +} + +fn parseIPv4(allocator: Allocator, ip: []const u8) !ParseResult { + var parts = std.mem.splitSequence(u8, ip, "."); + var octets: [4]u8 = undefined; + var port_str: []const u8 = ""; + var i: usize = 0; + + while (parts.next()) |part| { + if (i >= 4) return ParseError.InvalidAddress; + + // Check if this part contains a port (last octet with colon) + if (i == 3) { + if (std.mem.indexOf(u8, part, ":")) |colon_pos| { + const octet_str = part[0..colon_pos]; + port_str = part[colon_pos + 1..]; + + const octet = std.fmt.parseInt(u8, octet_str, 10) catch return ParseError.InvalidValue; + octets[i] = octet; + } else { + const octet = std.fmt.parseInt(u8, part, 10) catch return ParseError.InvalidValue; + octets[i] = octet; + } + } else { + const octet = std.fmt.parseInt(u8, part, 10) catch return ParseError.InvalidValue; + octets[i] = octet; + } + i += 1; + } + + if (i != 4) return ParseError.InvalidAddress; + + // Convert to hex + var hex = ArrayList(u8).init(allocator); + defer hex.deinit(); + + for (octets) |octet| { + try hex.writer().print("{x:0>2}", .{octet}); + } + + const port_copy = try allocator.dupe(u8, port_str); + + return ParseResult{ + .hex_address = try hex.toOwnedSlice(), + .port = port_copy, + }; +} + +fn parseIPv6DoubleColon(allocator: Allocator, ip: []const u8) !ParseResult { + var working_ip = ip; + var port_str: []const u8 = ""; + + // Handle brackets and port + if (std.mem.startsWith(u8, working_ip, "[")) { + if (std.mem.lastIndexOf(u8, working_ip, "]:")) |bracket_pos| { + port_str = working_ip[bracket_pos + 2..]; + working_ip = working_ip[1..bracket_pos]; + } else if (std.mem.endsWith(u8, working_ip, "]")) { + working_ip = working_ip[1..working_ip.len - 1]; + } + } + + // Check if it contains :: + const double_colon_pos = std.mem.indexOf(u8, working_ip, "::") orelse return ParseError.InvalidAddress; + + const p1 = working_ip[0..double_colon_pos]; + const p2 = working_ip[double_colon_pos + 2..]; + + const p1_count = if (p1.len == 0) 0 else countColons(p1) + 1; + const p2_count = if (p2.len == 0) 0 else countColons(p2) + 1; + + const zeros_needed = 8 - p1_count - p2_count; + + // Reconstruct the full IPv6 address + var full_ip = ArrayList(u8).init(allocator); + defer full_ip.deinit(); + + if (p1.len > 0) { + try full_ip.appendSlice(p1); + try full_ip.append(':'); + } + + for (0..zeros_needed) |_| { + try full_ip.appendSlice("0:"); + } + + if (p2.len > 0) { + try full_ip.appendSlice(p2); + } else { + // Remove trailing colon if p2 is empty + if (full_ip.items.len > 0 and full_ip.items[full_ip.items.len - 1] == ':') { + _ = full_ip.pop(); + } + } + + const reconstructed = try full_ip.toOwnedSlice(); + defer allocator.free(reconstructed); + + return parseIPv6WithPort(allocator, reconstructed, port_str); +} + +fn parseIPv6(allocator: Allocator, ip: []const u8) !ParseResult { + return parseIPv6WithPort(allocator, ip, ""); +} + +fn parseIPv6WithPort(allocator: Allocator, ip: []const u8, port_override: []const u8) !ParseResult { + var working_ip = ip; + var port_str = port_override; + + // Handle brackets and port if not overridden + if (port_override.len == 0) { + if (std.mem.startsWith(u8, working_ip, "[")) { + if (std.mem.lastIndexOf(u8, working_ip, "]:")) |bracket_pos| { + port_str = working_ip[bracket_pos + 2..]; + working_ip = working_ip[1..bracket_pos]; + } else if (std.mem.endsWith(u8, working_ip, "]")) { + working_ip = working_ip[1..working_ip.len - 1]; + } + } + } + + var parts = std.mem.splitSequence(u8, working_ip, ":"); + var groups: [8][]const u8 = undefined; + var i: usize = 0; + + while (parts.next()) |part| { + if (i >= 8) return ParseError.InvalidAddress; + groups[i] = part; + i += 1; + } + + if (i != 8) return ParseError.InvalidAddress; + + // Convert to hex + var hex = ArrayList(u8).init(allocator); + defer hex.deinit(); + + for (groups) |group| { + if (group.len == 0) { + try hex.appendSlice("0000"); + } else { + // Validate hex and pad to 4 digits + const val = std.fmt.parseInt(u16, group, 16) catch return ParseError.InvalidHexValue; + try hex.writer().print("{x:0>4}", .{val}); + } + } + + const port_copy = try allocator.dupe(u8, port_str); + + return ParseResult{ + .hex_address = try hex.toOwnedSlice(), + .port = port_copy, + }; +} + +fn countColons(s: []const u8) usize { + var count: usize = 0; + for (s) |c| { + if (c == ':') count += 1; + } + return count; +} diff --git a/Task/Parsing-RPN-calculator-algorithm/Crystal/parsing-rpn-calculator-algorithm.cr b/Task/Parsing-RPN-calculator-algorithm/Crystal/parsing-rpn-calculator-algorithm.cr new file mode 100644 index 0000000000..26e3ce76f7 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Crystal/parsing-rpn-calculator-algorithm.cr @@ -0,0 +1,26 @@ +def rpn_calc (tokens) + stack = [] of Float64 + tokens.each do |token| + if token.is_a?(Float64) + stack.push token + else + x = stack.pop + y = stack.pop + case token + when "+" then stack.push(y + x) + when "-" then stack.push(y - x) + when "*" then stack.push(y * x) + when "/" then stack.push(y / x) + when "^" then stack.push(y ** x) + else raise "unknown operator: #{token}" + end + end + puts "%4s %s" % {token, stack} + end +end + +def tokenize (s) + s.split.map {|t| t.to_f rescue t } +end + +rpn_calc tokenize "3 4 2 * 1 5 - 2 3 ^ ^ / +" diff --git a/Task/Parsing-RPN-calculator-algorithm/Pluto/parsing-rpn-calculator-algorithm.pluto b/Task/Parsing-RPN-calculator-algorithm/Pluto/parsing-rpn-calculator-algorithm.pluto new file mode 100644 index 0000000000..7ae6961dd7 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Pluto/parsing-rpn-calculator-algorithm.pluto @@ -0,0 +1,33 @@ +require "queue" +local fmt = require "fmt" + +local function rpn_calculate(expr) + assert(#expr > 0, "expression cannot be empty") + print($"For expression = {expr}\n") + print("Token Action Stack") + local tokens = expr:split(" "):filter(|t| -> #t > 0):reorder() + local stk = new stack() + for tokens as token do + local d = tonumber(token) + if d then + stk:push(d) + fmt.print(" %d Push num onto top of stack %s", d, fmt.swrite(stk:toarray())) + elseif #token > 1 or !(token in "+-*/^") then + error($"{token} is not a valid token.") + elseif stk:size() < 2 then + error("Stack contains too few operands.") + else + local d1 = stk:pop() + local d2 = stk:pop() + stk:push(token == "+" ? d2 + d1 : + token == "-" ? d2 - d1 : + token == "*" ? d2 * d1 : + token == "/" ? d2 / d1 : d2 ^ d1) + fmt.print(" %s Apply op to top of stack %s", token, fmt.swrite(stk:toarray())) + end + end + fmt.print("\nThe final value is %0.14g", stk:pop()) +end + +local expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +" +rpn_calculate(expr) diff --git a/Task/Parsing-RPN-calculator-algorithm/Red/parsing-rpn-calculator-algorithm.red b/Task/Parsing-RPN-calculator-algorithm/Red/parsing-rpn-calculator-algorithm.red new file mode 100644 index 0000000000..30608a1656 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Red/parsing-rpn-calculator-algorithm.red @@ -0,0 +1,21 @@ +Red [ "RPN Eval - Hinjo, July 25, 2025" ] +rpn-exec: func [exp [string!]] [ + stack: copy [] + blk: load exp ; convert into block + foreach tok blk [ + print [mold stack tok] + case [ + number? tok [append stack tok] + find [+ - * / ^] tok [ + if (length? stack) < 2 [ + print "Error: Two operands required!" exit ] + if tok = '^ [tok: '**] + b: take/last stack + a: take/last stack + append stack do compose [a (tok) b] + ] + ] + ] +] +; in Red, "^" is an escape char, so, it must be written as ^^ +rpn-exec "3 4 2 * 1 5 - 2 3 ^^ ^^ / +" diff --git a/Task/Parsing-RPN-to-infix-conversion/Red/parsing-rpn-to-infix-conversion.red b/Task/Parsing-RPN-to-infix-conversion/Red/parsing-rpn-to-infix-conversion.red new file mode 100644 index 0000000000..554fe499b0 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Red/parsing-rpn-to-infix-conversion.red @@ -0,0 +1,58 @@ +Red [ "RPN to Infix - Hinjo, 26 July 2025" ] + +rpn-to-infix: func [exp [string!]] [ + blk: load exp ; convert into block + stack: copy [] + stack-op: copy [] + + printstack: func [] [ + foreach x stack [ + prin rejoin [x " "] + ] + ] + push: func [val op] [ + append stack val + append stack-op op + ] + pop: function [] [ + val: take/last stack + op: take/last stack-op + compose [(val) (op)] + ] + + foreach tok blk [ + print rejoin [printstack] + case [ + number? tok [push tok 'n] + find [+ - * / ^] tok [ + b: pop + a: pop + if tok = '^ [ + if string? a/1 [ + if find "+-*/^^" a/2 + [a/1: rejoin ["(" a/1 ")"]] + ] + if string? b/1 [ + if find "+-*/" b/2 + [b/1: rejoin ["(" b/1 ")"]] + ] + ] + if find "*/" tok [ + if string? a/1 [ + if find "+-" a/2 + [a/1: rejoin ["(" a/1 ")"]] ] + if string? b/1 [ + if find "+-" b/2 + [b/1: rejoin ["(" b/1 ")"]] ] ] + + expr: rejoin compose [""(rejoin [(a/1)" "(tok)" "(b/1)])""] + push expr tok + ] + ] + ] + printstack print "" +] + +; in Red, "^" is an escape char, so, it must be written as ^^ +rpn-to-infix "3 4 2 * 1 5 - 2 3 ^^ ^^ / +" +rpn-to-infix "1 2 + 3 4 + ^^ 5 6 + ^^" diff --git a/Task/Parsing-Shunting-yard-algorithm/Red/parsing-shunting-yard-algorithm.red b/Task/Parsing-Shunting-yard-algorithm/Red/parsing-shunting-yard-algorithm.red new file mode 100644 index 0000000000..030fcaf0a9 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Red/parsing-shunting-yard-algorithm.red @@ -0,0 +1,90 @@ +Red [ "Shunting-Yard Infix to RPN - Hinjo, July 2025" ] + +; no error handling, assumed expr is spaced and correct +shunting: function [expr [string!] /trace] [ + output: copy [] ops: copy [] + prec: #["+" 2 "-" 2 "*" 3 "/" 3 "^^" 4 ] ; precedence + asc: #["+" "L" "-" "L" "*" "L" "/" "L" "^^" "R"] ; association + + stats: function [t] [ ; display basic tracing + if not trace [exit] + print [t "|" pad act 35 "|" pad (form output) 30 pad/left (reverse form ops) 15] + ] + + tokens: split expr " " + while [not empty? tokens] [ + tok: first tokens tokens: next tokens + case [ + find "0123456789" tok [ ; add numbers to output + act: "(a) Add number to output" append output tok stats tok + ] + find "(" tok [ ; push "(" to stack + act: "(b) Push ( to stack" append ops tok stats tok + ] + find ")" tok [ ; pop stack to output until "(" + while [(last ops) <> "("] [ ; assume input is correct! + act: "(c) Pop op to output" append output (take/last ops) stats tok + ] + act: "(d) Discard ( from stack" take/last ops stats " " ; should be ")" + ] + find "+-*/^^" tok [ + ; Pop higher or equal-left operators from stack + while [not empty? ops] [ + last-op: last ops + if (none? last-op) [break] + if (last-op = "(") [break] ; skip, we're in () + if (prec/:last-op < prec/:tok) [break] + if (asc/:last-op <> "L") [break] + act: "(e) Pop higher/equal op to output" append output take/last ops stats " " + ] + ; Now push current operator + act: "(f) Push op to stack" append ops tok stats tok + ] + ] + ] + ; flush the stack to output + act: "Finished. Flush ops:" stats " " + while [not empty? ops] [ + act: "(g) Pop op to output" append output (take/last ops) stats " " + ] + ; return output + form output +] + +; assumed input is space separated! ('^' is escape char!) +print "Some test for input and output with trace:" +print ["^/" s: "3 + 4 * 2 / ( 1 - 5 ) ^^ 2 ^^ 3"] shunting/trace s +print ["^/" s: "( ( 1 + 2 ) ^^ ( 3 + 4 ) ) ^^ ( 5 + 6 )"] shunting/trace s +print ["^/" s: "1 + 2 * 3 / 4 + 5"] shunting/trace s + +check: function [s t u][ + print [pad s 40 "|" pad t 30 "|" pad u 30 "|" t = u] +] + +print "^/Print input, validation and the output:" +s: "1 + 2 * 3 / 4 + 5" t: "1 2 3 * 4 / + 5 +" u: shunting s check s t u +s: "3 + 4 * 2 / ( 1 - 5 ) ^^ 2 ^^ 3" t: "3 4 2 * 1 5 - 2 3 ^^ ^^ / +" u: shunting s check s t u +s: "( ( 1 + 2 ) ^^ ( 3 + 4 ) ) ^^ ( 5 + 6 )" t: "1 2 + 3 4 + ^^ 5 6 + ^^" u: shunting s check s t u +s: "( 1 + 2 ) ^^ ( 3 + 4 ) ^^ ( 5 + 6 )" t: "1 2 + 3 4 + 5 6 + ^^ ^^" u: shunting s check s t u +s: "( ( 3 ^^ 4 ) ^^ 2 ^^ 9 ) ^^ 2 ^^ 5" t: "3 4 ^^ 2 9 ^^ ^^ 2 5 ^^ ^^" u: shunting s check s t u +s: "( 1 + 4 ) * ( 5 + 3 ) * 2 * 3" t: "1 4 + 5 3 + * 2 * 3 *" u: shunting s check s t u +s: "1 * 2 * 3 * 4" t: "1 2 * 3 * 4 *" u: shunting s check s t u +s: "1 + 2 + 3 + 4" t: "1 2 + 3 + 4 +" u: shunting s check s t u +s: "( 1 + 2 ) ^^ ( 3 + 4 )" t: "1 2 + 3 4 + ^^" u: shunting s check s t u +s: "( 5 ^^ 6 ) ^^ 7" t: "5 6 ^^ 7 ^^" u: shunting s check s t u +s: "5 ^^ 4 ^^ 3 ^^ 2" t: "5 4 3 2 ^^ ^^ ^^" u: shunting s check s t u +s: "1 + 2 + 3" t: "1 2 + 3 +" u: shunting s check s t u +s: "1 ^^ 2 ^^ 3" t: "1 2 3 ^^ ^^" u: shunting s check s t u +s: "( 1 ^^ 2 ) ^^ 3" t: "1 2 ^^ 3 ^^" u: shunting s check s t u +s: "1 - 1 + 3" t: "1 1 - 3 +" u: shunting s check s t u +s: "3 + 1 - 1" t: "3 1 + 1 -" u: shunting s check s t u +s: "1 - ( 2 + 3 )" t: "1 2 3 + -" u: shunting s check s t u +s: "4 + 3 + 2" t: "4 3 + 2 +" u: shunting s check s t u +s: "5 + 4 + 3 + 2" t: "5 4 + 3 + 2 +" u: shunting s check s t u +s: "5 * 4 * 3 * 2" t: "5 4 * 3 * 2 *" u: shunting s check s t u +s: "5 + 4 - ( 3 + 2 )" t: "5 4 + 3 2 + -" u: shunting s check s t u +s: "3 - 4 * 5" t: "3 4 5 * -" u: shunting s check s t u +s: "3 * ( 4 - 5 )" t: "3 4 5 - *" u: shunting s check s t u +s: "( 3 - 4 ) * 5" t: "3 4 - 5 *" u: shunting s check s t u +s: "4 * 2 + 1 - 5" t: "4 2 * 1 + 5 -" u: shunting s check s t u +s: "4 * 2 / ( 1 - 5 ) ^^ 2" t: "4 2 * 1 5 - 2 ^^ /" u: shunting s check s t u diff --git a/Task/Pascals-triangle-Puzzle/EasyLang/pascals-triangle-puzzle.easy b/Task/Pascals-triangle-Puzzle/EasyLang/pascals-triangle-puzzle.easy new file mode 100644 index 0000000000..6ee8467121 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/EasyLang/pascals-triangle-puzzle.easy @@ -0,0 +1,29 @@ +# Known: +# [ 151] +# [a ][b ] +# [40][c ][d ] +# [e ][f ][g ][h ] +# [ X][11][ Y][ 4][ Z] +# +# Y = X + Z +# +repeat + x += 1 + e = x + 11 + f = 40 - e + y = f - 11 + g = y + 4 + c = f + g + a = c + 40 + b = 151 - a + d = b - c + h = d - g + z = h - 4 + until y = x + z +. +numfmt 3 0 +print " " & 151 +print " " & a & b +print " " & 40 & c & d +print " " & e & f & g & h +print x & 11 & y & 4 & z diff --git a/Task/Pascals-triangle-Puzzle/Fortran/pascals-triangle-puzzle.f b/Task/Pascals-triangle-Puzzle/Fortran/pascals-triangle-puzzle.f new file mode 100644 index 0000000000..47bd5d10b1 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Fortran/pascals-triangle-puzzle.f @@ -0,0 +1,124 @@ +! +module solve_pyramid_gauss + implicit none +contains + subroutine gauss + implicit none + integer, parameter :: n = 3 + real(kind=8) :: a(n, n), b(n), x(n) + integer :: i, j, k + real(kind=8) :: factor, tmp_row(n), tmp_b + + ! Build the 3×3 system + a = 0.0d0 + b = 0.0d0 + + ! Eq1: X + Y = 18 + a(1, 1) = 1 + a(1, 2) = 1 + b(1) = 18 + + ! Eq2: X + 6Y + Z = 91 + a(2, 1) = 1 + a(2, 2) = 6 + a(2, 3) = 1 + b(2) = 91 + + ! Eq3: -X + Y - Z = 0 + a(3, 1) = -1 + a(3, 2) = 1 + a(3, 3) = -1 + b(3) = 0 + + ! Gaussian elimination with manual pivot swap + do k = 1, n - 1 + ! if pivot is near zero, swap with next row + if (abs(a(k, k)) < 1e-12) then + tmp_row = a(k, :) + a(k, :) = a(k + 1, :) + a(k + 1, :) = tmp_row + tmp_b = b(k) + b(k) = b(k + 1) + b(k + 1) = tmp_b + end if + + ! eliminate below + do i = k + 1, n + factor = a(i, k) / a(k, k) + do j = k, n + a(i, j) = a(i, j) - factor * a(k, j) + end do + b(i) = b(i) - factor * b(k) + end do + end do + + ! back substitution + x(n) = b(n) / a(n, n) + do i = n - 1, 1, -1 + factor = 0.0d0 + do j = i + 1, n + factor = factor + a(i, j) * x(j) + end do + x(i) = (b(i) - factor) / a(i, i) + end do + + print "(/,1X,A)", "Gaussian Solution:" + print "(2(A,1x,I0,3x),a,1x,i0)", " X =", int(x(1)), " Y =", int(x(2)), " Z =", int(x(3)) + + end subroutine gauss + +end module solve_pyramid_gauss +program solve_pyramid + use solve_pyramid_gauss + implicit none + + integer, parameter :: maxval = 100 + integer :: x, y, z + integer :: a(5), b(4), c(3), d(2), e + + ! Brute-force X and Z in [0, MAXVAL] + do x = 0, maxval + do z = 0, maxval + y = x + z + + ! Base row: [ X, 11, Y, 4, Z ] + a = (/ x, 11, y, 4, z /) + + ! Build level 4 + b(1) = a(1) + a(2) + b(2) = a(2) + a(3) + b(3) = a(3) + a(4) + b(4) = a(4) + a(5) + + ! Build level 3 + c(1) = b(1) + b(2) + c(2) = b(2) + b(3) + c(3) = b(3) + b(4) + + ! Check the known middle-upper constraint + if (c(1) == 40) then + + ! Build level 2 and apex + d(1) = c(1) + c(2) + d(2) = c(2) + c(3) + e = d(1) + d(2) + + ! Check the apex constraint + if (e == 151) then + print *, "Solution found:" + print "(2(A,1x,I0,3x),a,1x,i0)", " X =", x, " Y =", y, " Z =", z + print *, " Pyramid:" + print *, " Top: [", e, "]" + print *, " Level 2: [", d(1), " ", d(2), "]" + print *, " Level 3: [", c(1), " ", c(2), " ", c(3), "]" + print *, " Level 4: [", b(1), " ", b(2), " ", b(3), " ", b(4), "]" + print *, " Base row: [", a(1), " ", a(2), " ", a(3), " ", & + a(4), " ", a(5), "]" + end if + + end if + + end do + end do + call gauss +end program solve_pyramid diff --git a/Task/Pascals-triangle-Puzzle/JavaScript/pascals-triangle-puzzle.js b/Task/Pascals-triangle-Puzzle/JavaScript/pascals-triangle-puzzle.js new file mode 100644 index 0000000000..7284dc445d --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/JavaScript/pascals-triangle-puzzle.js @@ -0,0 +1,102 @@ +class Matrix { + constructor(...lists) { + if (lists.length === 1 && Array.isArray(lists[0][0])) { + this.matrix = lists[0]; + } else { + this.matrix = lists; + } + } + + toString() { + return JSON.stringify(this.matrix); + } + + determinant() { + if (this.matrix.length === 1) { + return this.get(0, 0); + } + if (this.matrix.length === 2) { + return this.get(0, 0) * this.get(1, 1) - this.get(0, 1) * this.get(1, 0); + } + let sum = 0; + let sign = 1; + for (let i = 0; i < this.matrix.length; i++) { + sum += sign * this.get(0, i) * this.coFactor(0, i).determinant(); + sign *= -1; + } + return sum; + } + + coFactor(row, col) { + const mat = []; + for (let i = 0; i < this.matrix.length; i++) { + if (i === row) { + continue; + } + const list = []; + for (let j = 0; j < this.matrix.length; j++) { + if (j === col) { + continue; + } + list.push(this.get(i, j)); + } + mat.push(list); + } + return new Matrix(mat); + } + + replaceColumn(b, column) { + const mat = []; + for (let row = 0; row < this.matrix.length; row++) { + const list = []; + for (let col = 0; col < this.matrix.length; col++) { + let value = this.get(row, col); + if (col === column) { + value = b[row]; + } + list.push(value); + } + mat.push(list); + } + return new Matrix(mat); + } + + get(row, col) { + return this.matrix[row][col]; + } +} + +function cramersRule(matrix, b) { + const denominator = matrix.determinant(); + const result = []; + for (let i = 0; i < b.length; i++) { + result.push(matrix.replaceColumn(b, i).determinant() / denominator); + } + return result; +} + +function main() { + const mat = new Matrix( + [1, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 0, 0, -1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, -1, 1, -1], + [0, 0, 1, 0, 0, 0, 0, 0, 0, -1, 0], + [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, -1], + [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, -1, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, -1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 0, -1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0] + ); + + const b = [11, 11, 0, 4, 4, 40, 0, 0, 40, 0, 151]; + const solution = cramersRule(mat, b); + + console.log("Solution =", solution); + console.log(`X = ${solution[8].toFixed(2)}`); + console.log(`Y = ${solution[9].toFixed(2)}`); + console.log(`Z = ${solution[10].toFixed(2)}`); +} + +main(); diff --git a/Task/Pascals-triangle-Puzzle/Pluto/pascals-triangle-puzzle.pluto b/Task/Pascals-triangle-Puzzle/Pluto/pascals-triangle-puzzle.pluto new file mode 100644 index 0000000000..594ed3afb6 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Pluto/pascals-triangle-puzzle.pluto @@ -0,0 +1,19 @@ +local function is_integral(x, tol) + local frac = {math.modf(x)}[2] + return math.abs(frac) <= tol +end + +local function pascal(a, b, mid, top) + local yd = (top - 4 * (a + b)) / 7 + if !is_integral(yd, 0.0001) then return {0, 0, 0} end + local y = math.floor(yd) + local x = mid - 2 * a - y + return {x, y, y - x} +end + +local sol = pascal(11, 4, 40, 151) +if sol[0] != 0 then + print(string.format("Solution is: x = %d, y = %d, z = %d", sol[1], sol[2], sol[3])) +else + print("There is no solution") +end diff --git a/Task/Pascals-triangle/DuckDB/pascals-triangle.duckdb b/Task/Pascals-triangle/DuckDB/pascals-triangle.duckdb new file mode 100644 index 0000000000..5b61f4dd94 --- /dev/null +++ b/Task/Pascals-triangle/DuckDB/pascals-triangle.duckdb @@ -0,0 +1,16 @@ +create or replace function pascal_triangle(n) as table ( + with recursive cte as ( + SELECT 0 as i, [1]::BIGINT[] as row, + UNION ALL + SELECT i+1 as i, + ([1] || list_transform(row, (x,ix) -> x + (coalesce(row[ix+1], 0)))) as row + FROM cte + WHERE i < n + ) + select row as "pascal_triangle" FROM cte + order by i +); + +.print The results for all n<=0 are the same: +select * as "pascal_triangle(0)" from pascal_triangle(0); +from pascal_triangle(4) _("pascal_triangle(4)"); diff --git a/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg b/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg index 341dc7dfc3..77c11b77f3 100644 --- a/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg +++ b/Task/Pathological-floating-point-problems/ALGOL-68/pathological-floating-point-problems.alg @@ -1,9 +1,16 @@ BEGIN + + # show the sizes of REAL, LONG REAL and LONG LONG real # + print( ( "Approximate sizes of real numbers available: " ) ); + print( ( "REAL: ", whole( real width, 0 ) ) ); + print( ( ", LONG REAL: ", whole( long real width, 0 ) ) ); + print( ( ", default for LONG LONG REAL: ", whole( long long real width, 0 ) ) ); + print( ( newline, newline ) ); + # task 1 # BEGIN - PR precision 32 PR - print( ( " 32 digit REAL numbers", newline ) ); - [ 1 : 100 ]LONG LONG REAL v; + print( ( whole( long real width, -4 ), " digit REAL numbers", newline ) ); + [ 1 : 100 ]LONG REAL v; v[ 1 ] := 2; v[ 2 ] := -4; FOR n FROM 3 TO UPB v DO v[ n ] := 111 - ( 1130 / v[ n - 1 ] ) + ( 3000 / ( v[ n - 1 ] * v[ n - 2 ] ) ) OD; @@ -12,8 +19,7 @@ BEGIN print( ( "n = 100 ", fixed( v[ 100 ], -22, 16 ), newline ) ) END; BEGIN - PR precision 120 PR - print( ( "120 digit REAL numbers", newline ) ); + print( ( whole( long long real width, -4 ), " digit REAL numbers", newline ) ); [ 1 : 100 ]LONG LONG REAL v; v[ 1 ] := 2; v[ 2 ] := -4; @@ -23,25 +29,24 @@ BEGIN print( ( newline ) ); # task 2 # BEGIN - print( ( "single precision REAL numbers...", newline ) ); + print( ( "standard precision REAL numbers...", newline ) ); REAL chaotic balance := exp( 1 ) - 1; - print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); + print( ( " initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; - print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) + print( ( " 25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END; BEGIN - print( ( "double precision REAL numbers...", newline ) ); + print( ( "double precision LONG REAL numbers...", newline ) ); LONG REAL chaotic balance := long exp( 1 ) - 1; - print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); + print( ( " initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; - print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) + print( ( " 25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END; BEGIN - PR precision 32 PR - print( ( " 32 digit REAL numbers...", newline ) ); + print( ( whole( long long real width, -10 ), " digit LONG LONG REAL numbers...", newline ) ); LONG LONG REAL chaotic balance := long long exp( 1 ) - 1; - print( ( "initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); + print( ( " initial chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ); FOR i FROM 1 TO 25 DO ( chaotic balance *:= i ) -:= 1 OD; - print( ( "25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) + print( ( " 25 year chaotic balance: ", fixed( chaotic balance, -22, 16 ), newline ) ) END END diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx deleted file mode 100644 index b369f06758..0000000000 --- a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-1.rexx +++ /dev/null @@ -1,15 +0,0 @@ -/*REXX pgm (pathological FP problem): a sequence that might converge to a wrong limit. */ -parse arg digs show . /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs= 150 /*Not specified? Then use the default.*/ -if show=='' | show=="," then show= 20 /* " " " " " " */ -numeric digits digs /*have REXX use "digs" decimal digits. */ -#= 2 4 5 6 7 8 9 20 30 50 100 /*the indices to display value of V.n */ -fin= word(#, words(#) ) /*find the last (largest) index number.*/ -w= length(fin) /* " " length (in dec digs) of FIN.*/ -v.1= 2 /*the value of the first V element. */ -v.2=-4 /* " " " " second " " */ - do n=3 to fin; nm1= n-1; nm2= n-2 /*compute some values of the V elements*/ - v.n= 111 - 1130/v.nm1 + 3000/(v.nm1*v.nm2) /* " a value of a " element.*/ - /*display digs past the dec. point───┐ */ - if wordpos(n, #)\==0 then say 'v.'left(n, w) "=" format(v.n, , show) - end /*n*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx deleted file mode 100644 index 1378f5331a..0000000000 --- a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-2.rexx +++ /dev/null @@ -1,18 +0,0 @@ -/*REXX pgm (pathological FP problem): the chaotic bank society offering a new investment*/ -e=2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713, - ||8217852516642742746639193200305992181741359662904357290033429526059563073813232862794, - ||3490763233829880753195251019011573834187930702154089149934884167509244761460668082264, - ||8001684774118537423454424371075390777449920695517027618386062613313845830007520449338 -d = length(e) - length(.) /*subtract one for the decimal point. */ -parse arg digs show y . /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs= d /*Not specified? Then use the default.*/ -if show=='' | show=="," then show= 20 /* " " " " " " */ -if y=='' | y=="," then y= 25 /* " " " " " " */ -numeric digits digs /*have REXX use "digs" decimal digits. */ -$= e - 1 /*subtract $1 from e, that's da deposit*/ - /* [↑] value of newly opened account. */ - do n=1 for y /*compute the value of the account/year*/ - $= $*n - 1 /* " " " " " account now.*/ - end /*n*/ -@@@= 'With ' d " decimal digits, the balance after " y ' years is: ' -say @@@ '$'format($, , show) / 1 /*stick a fork in it, we're all done. */ diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx deleted file mode 100644 index c0da0ee523..0000000000 --- a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems-3.rexx +++ /dev/null @@ -1,13 +0,0 @@ -/*REXX pgm (pathological FP problem): the Siegfried Rump's example (problem dated 1988).*/ -parse arg digs show . /*obtain optional arguments from the CL*/ -if digs=='' | digs=="," then digs=150 /*Not specified? Then use the default.*/ -if show=='' | show=="," then show= 20 /* " " " " " " */ -numeric digits digs /*have REXX use "digs" decimal digits. */ -a= 77617.0 /*initialize A to it's defined value.*/ -b= 33096.0 /* " B " " " " */ - /*display SHOW digits past the dec. pt.*/ -say 'f(a,b)=' format( f(a,b), , show) /*display result from the F function.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -f: procedure; parse arg a,b; return 333.75* b**6 + a**2 * (11* a**2* b**2 - b**6, - - 121*b**4 - 2) + 5.5*b**8 + a / (2*b) diff --git a/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx new file mode 100644 index 0000000000..fe792b679e --- /dev/null +++ b/Task/Pathological-floating-point-problems/REXX/pathological-floating-point-problems.rexx @@ -0,0 +1,51 @@ +-- 28 Jul 2025 +include Settings +arg digs +if digs = '' then + digs=9 +numeric digits digs + +say 'PATHOLOGICAL FLOATING POINT PROBLEMS' +say version +say digs 'digits precision' +say +call Sequence +call Society +call Rump +call Timer +exit + +Sequence: +procedure +say 'Sequence goes to wrong limit...' +show='3 4 5 6 7 8 20 30 50 100' +a=2; b=-4 +do n = 3 to 100 + c=111-1130/b+3000/(a*b); a=b; b=c + if Wordpos(n,show) > 0 then + say 'n =' Right(n,3) Left(c,19) +end +say +return + +Society: +procedure expose Memo. +say 'The Chaotic Bank Society...' +e=e()/1; b=e-1 +say Right(0,2) Left(b,18) +do n = 1 to 25 + b=b*n-1 + say Right(n,2) Left(b,18) +end +say +return + +Rump: +procedure +say 'Siegfried Rumps''s example...' +a=77617; b=33096 +say Left(333.75*b**6 + a**2*(11*a**2*b**2-b**6-121*b**4-2) + 5.5*b**8 + a/(2*b),18) +say +return + +include Math diff --git a/Task/Pell-numbers/Julia/pell-numbers.jl b/Task/Pell-numbers/Julia/pell-numbers-1.jl similarity index 100% rename from Task/Pell-numbers/Julia/pell-numbers.jl rename to Task/Pell-numbers/Julia/pell-numbers-1.jl diff --git a/Task/Pell-numbers/Julia/pell-numbers-2.jl b/Task/Pell-numbers/Julia/pell-numbers-2.jl new file mode 100644 index 0000000000..9884f44748 --- /dev/null +++ b/Task/Pell-numbers/Julia/pell-numbers-2.jl @@ -0,0 +1,2 @@ +pell(n::Integer) = last(BigInt[2 1; 1 0] ^ n * BigInt[1, 0]) +pelllucas(n::Integer) = last(BigInt[2 1; 1 0] ^ n * BigInt[2, 2]) diff --git a/Task/Pell-numbers/PARI-GP/pell-numbers.parigp b/Task/Pell-numbers/PARI-GP/pell-numbers.parigp new file mode 100644 index 0000000000..f2e163f191 --- /dev/null +++ b/Task/Pell-numbers/PARI-GP/pell-numbers.parigp @@ -0,0 +1,59 @@ +\\--- pell.gp ------------------------------------------------------------ + +\\ 1) Define Pell numbers and Pell–Lucas numbers by simple recursion + +pell(n) = +{ + if (n==0, return(0)); + if (n==1, return(1)); + return(2*pell(n-1) + pell(n-2)); +} + +pellL(n) = +{ + if (n==0, return(2)); + if (n==1, return(2)); + return(2*pellL(n-1) + pellL(n-2)); +} + +\\ 2) Compute the first 10 Pell and Pell–Lucas numbers +pns = vector(10, i, pell(i-1)); \\ pell(0) .. pell(9) +plns = vector(10, i, pellL(i-1)); \\ pellL(0) .. pellL(9) + +print("Pell numbers (n=0..9): ", pns); +print("Pell–Lucas numbers (n=0..9): ", plns); + +\\ 3) Form the ratios (Pell–Lucas)/2 over Pell, skipping n=0 +\\ i.e. for n=1..9 +denom = vector(9, i, pns[i+1]); \\ pns[2..10] +numr = vector(9, i, plns[i+1]/2); \\ plns[2..10]/2 +approx = vector(9, i, numr[i]/denom[i]); + +print("Ratios (pellL(n)/2) / pell(n) for n=1..9:"); +for (i=1,9, print(i, ": ", approx[i])); +print("Numeric floats:"); +for (i=1,9, print(i, ": ", real(approx[i]))); + +\\ 4) List (n, pell(n)) for n=0..100 and pick the first 10 where pell(n) is prime +plist = vector(101, i, [i-1, pell(i-1)]); +primespell = select(x->isprime(x[2]), plist); +print("First 10 Pell(n) that are prime:"); +for (i=1,10, print(primespell[i])); + +\\ 5) Define PellS(n) = If[n==0,1, pell(2n) + pell(2n+1)] +pellS(n) = if(n==0, 1, pell(2*n) + pell(2*n+1)); +print("PellS(n) for n=0..19:"); +print(vector(20, n, pellS(n))); + +\\ 6) Generate Pythagorean triples from Pell numbers: +\\ short = sum_{k=1..2n} pell(k), long = short+1, hypo = pell(2n+1) +pythag(n) = +{ + short = sum(k=1, 2*n, pell(k)); + long = short + 1; + hypo = pell(2*n + 1); + return([short, long, hypo]); +} + +print("Pythagorean triples for n=0..9:"); +for (n=0,9, print(n, ": ", pythag(n))); diff --git a/Task/Perfect-numbers/00-TASK.txt b/Task/Perfect-numbers/00-TASK.txt index 7d242fe208..1f06bae42d 100644 --- a/Task/Perfect-numbers/00-TASK.txt +++ b/Task/Perfect-numbers/00-TASK.txt @@ -1,6 +1,6 @@ [[category:Discrete math]] {{task|Prime Numbers}} - +{{task|Numbers}} Write a function which says whether a number is perfect.
    diff --git a/Task/Perfect-shuffle/FutureBasic/perfect-shuffle.basic b/Task/Perfect-shuffle/FutureBasic/perfect-shuffle.basic new file mode 100644 index 0000000000..1d22506d8c --- /dev/null +++ b/Task/Perfect-shuffle/FutureBasic/perfect-shuffle.basic @@ -0,0 +1,81 @@ +// +// Perfect Shuffle +// +// FutureBasic 7.0.34, August 2025 R.W +// uses MDA arrays + +_deck = 1 //the MDA tag for the deck array +_shuffled = 2 //the MDA tag for shuffled deck + +Window 1 + +// +// fill MDA des array with +// number from 1 to n +void local fn fillDeck(des as Int, n as Int) + Int x + mda_clear des + for x = 1 to n + mda des(x) = x + next x +end fn + +// +// check if deck in MDA tag array +// is in order + +local fn inOrder (tag as Int,siz as Int) as boolean + boolean isInOrder = _True + int x, lo, hi + for x = 1 to siz - 1 + lo = mda tag(x) + hi = mda tag(x + 1) + if lo > hi then return _False + next x +end fn = isInOrder + +// +// faro out shuffle +// the deck is halves then both halves interweaved 1 by 1 + +local fn faroShuffle(src as Int, des as Int, n as Int) + Int i + mda_clear des + // uses temporary shuffled deck array + for i = 1 to n/2 + mda des(2 * i - 1) = mda src(i) + mda des(2 * i) = mda src( n / 2 + i) + next i + for i = 1 to n //put it back + mda src(i) = mda des(i) + next i +end fn + +// shuffles needed for a perfect +// shuffle given siz + +local fn neededShuffle(siz as Int) as Int + Int s + s = 0 + fn fillDeck(_deck, siz) + do + fn faroShuffle (_deck, _shuffled, siz) + s++ + until fn inOrder(_deck, siz) == _True +end fn = s + +window 1,@"Perfect Shuffle" + +Int testData(7) = {0, 8, 24, 52, 100, 1020, 1024, 10000} + +print "CARDS SHUFFLES" +print "-------------------" + +Int x, k +for x = 1 to 7 + print using "##### ";testData(x); "needs "; ¬ + fn neededShuffle(testData(x)) +next x + +handleEvents +// diff --git a/Task/Perfect-shuffle/Pluto/perfect-shuffle.pluto b/Task/Perfect-shuffle/Pluto/perfect-shuffle.pluto new file mode 100644 index 0000000000..eec5f4ed25 --- /dev/null +++ b/Task/Perfect-shuffle/Pluto/perfect-shuffle.pluto @@ -0,0 +1,45 @@ +local fmt = require "fmt" +require "table2" + +local function are_same(a, b) + for i = 1, #a do + if a[i] != b[i] then return false end + end + return true +end + +local function perfect_shuffle(a) + local n = #a + local b = table.rep(n, 0) + local hsize = n // 2 + for i = 1, hsize do b[i * 2 - 1] = a[i] end + local j = 2 + for i = hsize + 1, n do + b[j] = a[i] + j += 2 + end + return b +end + +local function count_shuffles(a) + local n = #a + assert(n % 2 == 0 and n > 1, "Array must be even-sized and non-empty.") + local b = a + local count = 0 + while true do + local c = perfect_shuffle(b) + ++count + if are_same(a, c) then return count end + b = c + end +end + +print("Deck size Num shuffles") +print("--------- ------------") +local sizes = {8, 24, 52, 100, 1020, 1024, 10000} +for sizes as size do + local a = {0} + for i = 2, size do a[i] = i - 1 end + local count = count_shuffles(a) + fmt.print("%-9d %d", size, count) +end diff --git a/Task/Perlin-noise/EasyLang/perlin-noise.easy b/Task/Perlin-noise/EasyLang/perlin-noise.easy index 8fd4b68670..7e5f02c004 100644 --- a/Task/Perlin-noise/EasyLang/perlin-noise.easy +++ b/Task/Perlin-noise/EasyLang/perlin-noise.easy @@ -66,7 +66,7 @@ print noise 3.14 42 7 # demo for y = 0 to 199 for x = 0 to 199 - p = noise (x / 30) (y / 30) 0.1 + p = 100 * noise (x / 30) (y / 30) 0.1 gcolor3 p p p grect x / 2 y / 2 0.6 0.6 . diff --git a/Task/Perlin-noise/Zig/perlin-noise.zig b/Task/Perlin-noise/Zig/perlin-noise.zig index fe94c95c9d..8362d0011f 100644 --- a/Task/Perlin-noise/Zig/perlin-noise.zig +++ b/Task/Perlin-noise/Zig/perlin-noise.zig @@ -1,4 +1,4 @@ -// Made for Zig 0.10.0 +// Made for Zig 0.14.1 // This implementation works with generic float types const std = @import("std"); @@ -13,9 +13,9 @@ pub fn noise3D(comptime T: type, x: T, y: T, z: T) T { @setRuntimeSafety(false); // Truncate float to u8 (256 possible values) - const x_i = @intCast(u8, @floatToInt(isize, @floor(x)) & 255); - const y_i = @intCast(u8, @floatToInt(isize, @floor(y)) & 255); - const z_i = @intCast(u8, @floatToInt(isize, @floor(z)) & 255); + const x_i: u8 = @truncate(@as(usize, @bitCast(@as(isize, @intFromFloat(@floor(x)))))); + const y_i: u8 = @truncate(@as(usize, @bitCast(@as(isize, @intFromFloat(@floor(y)))))); + const z_i: u8 = @truncate(@as(usize, @bitCast(@as(isize, @intFromFloat(@floor(z)))))); // Float remainder of coords (eg: 5.34 -> 0.34) const x_r = x - @floor(x); diff --git a/Task/Permutations-Derangements/DuckDB/permutations-derangements.duckdb b/Task/Permutations-Derangements/DuckDB/permutations-derangements.duckdb new file mode 100644 index 0000000000..7af4d1f4a5 --- /dev/null +++ b/Task/Permutations-Derangements/DuckDB/permutations-derangements.duckdb @@ -0,0 +1,49 @@ +# Report whether lst is deranged, i.e. if lst[i] = i for any i +# The following might achieve short-circuit semantics as it uses `LIMIT 1` +CREATE OR REPLACE FUNCTION deranged(lst) as ( + select not exists + (from (select unnest(lst) as x, generate_subscripts(lst, 1) as ix) + where x = ix + limit 1) +); + +CREATE OR REPLACE FUNCTION derangements(lst) as table ( + WITH RECURSIVE permute(perm, remaining) as ( + -- base case + SELECT + [] as perm, + lst as remaining + UNION ALL + -- recursive case: add one element from remaining to perm and remove it from remaining + SELECT + (perm || [element]) AS perm, + list_filter(remaining, x -> x != element) AS remaining + FROM (select *, unnest(remaining) AS element + FROM permute) + where deranged(perm || [element]) + ) + SELECT perm + FROM permute + WHERE length(remaining) = 0 +); + +CREATE OR REPLACE FUNCTION subfact(num) as table ( + with recursive cte(n,psub,sub) as ( + -- psub means `previous sub` + select 0 as n, 1::HUGEINT as psub, 1::HUGEINT as sub + union all + select + n+1 as n, + sub as psub, + (n * (sub + psub)) as sub + from cte + where n < num + ) + select n, sub from cte + order by n +) ; + +select t.n, + sub as subfactorial, + (select count(*) from derangements(range(1, 1+t.n))) as count +from range(0,10) t(n) positional join (from subfact(9)) ; diff --git a/Task/Permutations-by-swapping/Zig/permutations-by-swapping.zig b/Task/Permutations-by-swapping/Zig/permutations-by-swapping.zig new file mode 100644 index 0000000000..e97e9dd5e8 --- /dev/null +++ b/Task/Permutations-by-swapping/Zig/permutations-by-swapping.zig @@ -0,0 +1,50 @@ +const std = @import("std"); + +// Generic function to generate permutations +fn generate(comptime T: type, a: []T, output: fn ([]const T, i64) void) void { + const n = a.len; + var c = std.heap.page_allocator.alloc(usize, n) catch unreachable; + defer std.heap.page_allocator.free(c); + + @memset(c, 0); + + var i: usize = 1; + var sign: i64 = 1; + output(a, sign); + + while (i < n) { + if (c[i] < i) { + if ((i & 1) == 0) { + std.mem.swap(T, &a[0], &a[i]); + } else { + std.mem.swap(T, &a[c[i]], &a[i]); + } + sign = -sign; + output(a, sign); + c[i] += 1; + i = 1; + } else { + c[i] = 0; + i += 1; + } + } +} + +// Function to print permutation and its sign +fn printPermutation(comptime T: type) fn ([]const T, i64) void { + return struct { + fn inner(a: []const T, sign: i64) void { + std.debug.print("{any} {}\n", .{ a, sign }); + } + }.inner; +} + +pub fn main() !void { + std.debug.print("Permutations and signs for three items:\n", .{}); + var a = [_]i32{ 0, 1, 2 }; + generate(i32, &a, printPermutation(i32)); + + std.debug.print("\nPermutations and signs for four items:\n", .{}); + var b = [_]i32{ 0, 1, 2, 3 }; + generate(i32, &b, printPermutation(i32)); +} diff --git a/Task/Permutations/DuckDB/permutations.duckdb b/Task/Permutations/DuckDB/permutations.duckdb new file mode 100644 index 0000000000..240bf78912 --- /dev/null +++ b/Task/Permutations/DuckDB/permutations.duckdb @@ -0,0 +1,18 @@ +CREATE OR REPLACE FUNCTION permute(lst) as table ( + WITH RECURSIVE permute(perm, remaining) as ( + -- base case + SELECT + [] as perm, + lst as remaining + UNION ALL + -- recursive case: add one element from remaining to perm and remove it from remaining + SELECT + (perm || [element]) AS perm, + (remaining[1:i-1] || remaining[i+1:]) AS remaining + FROM (select *, unnest(remaining) AS element, generate_subscripts(remaining,1) as i + FROM permute) + ) + SELECT perm + FROM permute + WHERE length(remaining) = 0 +); diff --git a/Task/Permutations/Pluto/permutations.pluto b/Task/Permutations/Pluto/permutations.pluto new file mode 100644 index 0000000000..ae63f8ec8d --- /dev/null +++ b/Task/Permutations/Pluto/permutations.pluto @@ -0,0 +1,6 @@ +require "perm" +local fmt = require "fmt" + +local a = {1, 2, 3} +print($"There are {perm.count(#a)} permutations of {fmt.swrite(a)}, namely:") +fmt.lprint(perm.list(a)) diff --git a/Task/Permutations/TAV/permutations-1.tav b/Task/Permutations/TAV/permutations-1.tav new file mode 100644 index 0000000000..f512ce3260 --- /dev/null +++ b/Task/Permutations/TAV/permutations-1.tav @@ -0,0 +1,24 @@ +\( Calculate all permutations of integers 1..n + + General variant: simple, single array, recursive, not in lexical order + A row with n places is used, initially 0. + The current element l replaces the free places one by one, + and the next element l+1 is probed with the array. +\) +\C Use publication mode with keywords instead of symbols +permute1 (l) to (n) fill (r): + if l > n + print join r \ output requires most of CPU time + return + for j = from 1 upto n + if r[j] == 0 + r[j] = l + permute1 l+1 to n fill r + r[j] = 0 + +\( command line parameter is number of elements +\) +main (parms):+ + n = string parms[1] as integer else 3 + r = new row size n init 0 + permute1 1 to n fill r diff --git a/Task/Permutations/TAV/permutations-2.tav b/Task/Permutations/TAV/permutations-2.tav new file mode 100644 index 0000000000..662653d8e2 --- /dev/null +++ b/Task/Permutations/TAV/permutations-2.tav @@ -0,0 +1,28 @@ +\( Calculate all permutations of integers 1..n + + Second variant: two arrays, recursive, reverse lexical order. + Array (a) has the remaining elements which are each appended to the + array (t), removed and the rest applied to the expanded (t). + The elements of row (a) may have any value; only void or not void is used. +\) +\c Use native mode (symbols instead of keywords, class functions) +permute2 (a) to (t): + l =: a.Count \ number of non-void elements + ? l > 0 + ?# i =: row a give keys \ of non-void elements only + t[l] =: i + a[i] =: () \ decrements a.Count + permute2 a to t + a[i] =: i \ any non-void value + :> + \ print result in reverse order; output requires most CPU time + print tuple t::as tuple transpose + + +\( command line parameter is number of elements +\) +main (parms):+ + n =: string parms[1] as integer else 3 + a =: new row from 1 upto n \ fill 1..n + t =: new row size n \ intially void + permute2 a to t diff --git a/Task/Permutations/TAV/permutations-3.tav b/Task/Permutations/TAV/permutations-3.tav new file mode 100644 index 0000000000..706452cc6f --- /dev/null +++ b/Task/Permutations/TAV/permutations-3.tav @@ -0,0 +1,17 @@ +\C Publication syntax +permute (k) list (l): + if k == l.Count + print row l as tuple + return + for i = from k upto l.Count + row l swap i with k + permute k+1 list l + row l swap k with i + +row (l) swap (i) with (k): + t = l[i] + l[i] = l[k] + l[k] = t + +main (parms):+ + permute 1 list [1, 2, 3] \ row literal, not tuple diff --git a/Task/Permutations/TAV/permutations-4.tav b/Task/Permutations/TAV/permutations-4.tav new file mode 100644 index 0000000000..6462e04c21 --- /dev/null +++ b/Task/Permutations/TAV/permutations-4.tav @@ -0,0 +1,44 @@ +\( Two arrays, iterative, not in lexical order. + Input row (a) provides for each element where it was inserted last. +\) +\C Publication syntax +permute iterative (n): + a = new row size n \ state of last number + r = new row size n \ output row + l = 1 + while l > 0 \ need to start over + \ find the key of a void element + k = 0 \ if not found + for j = from a[l] + 1 upto n + if r[j] == () \ void in result + k = j \ use it + continue + \ evaluate + if k != 0 + \ key for void cell to be set + r[k] = l + a[l] = k + if l == n + \ permuation complete + print join r + \ backup + k = a[l] + r[k] = () + continue + l += 1 + continue \ next level + \ no void cell found + if l == 1 + break \ done, no more permutations + \ backup + a[l] = 0 + l -= 1 + k = a[l] + r[k] = () + continue + +\( command line parameter: number of elements +\) +main (parms):+ + n =: string parms[1] as integer else 3 + p =: permute iterative n diff --git a/Task/Pernicious-numbers/Agena/pernicious-numbers.agena b/Task/Pernicious-numbers/Agena/pernicious-numbers.agena new file mode 100644 index 0000000000..d85685a300 --- /dev/null +++ b/Task/Pernicious-numbers/Agena/pernicious-numbers.agena @@ -0,0 +1,32 @@ +scope # find some pernicious numbers - numbers with a prime population count + + local procedure populationCount( n :: number ) :: number + local v, count := abs n, 0; + while v > 0 do + if v && 1 = 1 then count +:= 1 fi; + v := v >>> 1 + od; + return count + end; + + local procedure isPernicious( p :: number ) :: boolean + return p > 0 and numtheory.isprime( populationCount( p ) ) + end + + scope # task + # show the first 25 pernicious numbers + local pCount := 0 + for p25 from 2 while pCount < 25 do # 0 and 1 aren't pernicious, so we start at 2 + if isPernicious( p25 ) then + pCount +:= 1; + printf( " %d", p25 ) + fi + od; + print(); + # find the pernicious numbers between 888 888 877 and 888 888 888 + for p from 888888877 to 888888888 do + if isPernicious( p ) then printf( " %d", p ) fi + od; + print() + end +end diff --git a/Task/Pernicious-numbers/Pluto/pernicious-numbers.pluto b/Task/Pernicious-numbers/Pluto/pernicious-numbers.pluto new file mode 100644 index 0000000000..b70010670b --- /dev/null +++ b/Task/Pernicious-numbers/Pluto/pernicious-numbers.pluto @@ -0,0 +1,38 @@ +do -- find some pernicious numbers - numbers with a prime population count + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library, inc. prime utilities + + -- returns the population count (number of set bits) of n + local function populationCount( n : number ) : number + local v, count = math.abs( n ), 0 + while v > 0 do + if v & 1 == 1 then ++ count end + v >>= 1 + end + return count + end + + -- returns true if p is pernicious, false otherwise + local function isPernicious ( p : number ) : boolean + return p > 0 and int.isprime( populationCount( p ) ) + end + + do -- find the pernicious numbers + -- show the first 25 pernicious numbers + local p25, pCount = 2, 0 -- 0 and 1 aren't pernicious, so we start at 2 + while pCount < 25 do + if isPernicious( p25 ) then + ++ pCount + fmt.write( " %d", p25 ) + end + ++ p25 + end + print() + -- find the pernicious numbers between 888 888 877 and 888 888 888 + for p = 888888877, 888888888 do + if isPernicious( p ) then fmt.write( " %d", p ) end + end + print() + end +end diff --git a/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx b/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx index 878d9c865f..e8305e76f3 100644 --- a/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx +++ b/Task/Pernicious-numbers/REXX/pernicious-numbers.rexx @@ -1,10 +1,10 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings +numeric digits 100 say 'PERNICIOUS NUMBERS' say version say -numeric digits 100 call Show 1,36 call Show 888888877,888888888 exit @@ -33,7 +33,4 @@ say Format(Time('e'),,3) 'seconds' say return -include Numbers -include Functions -include Special -include Abend +include Math diff --git a/Task/Phrase-reversals/Prolog/phrase-reversals.pro b/Task/Phrase-reversals/Prolog/phrase-reversals.pro new file mode 100644 index 0000000000..a47e262814 --- /dev/null +++ b/Task/Phrase-reversals/Prolog/phrase-reversals.pro @@ -0,0 +1,20 @@ +:- set_prolog_flag(double_quotes, chars). +:- use_module(library(dcg/basics)). +:- use_module(library(dcg/high_order)). + +%! string_words(+String, -Words) is det. +%! string_words(-String, +Words) is det. +% Relates a string to the list of space-separated words in that string. +string_words(String, Words) :- + once(phrase(sequence(nonblanks, " ", Words), String)). + +phrase_reversals(String) :- + reverse(String, Reversed), + string_words(String, Words), + maplist(reverse, Words, ReversedWords), + string_words(ReversedWordsString, ReversedWords), + reverse(Words, ReversedPhraseWords), + string_words(ReversedPhrase, ReversedPhraseWords), + format("~s~n~s~n~s~n~s~n", [String, Reversed, ReversedWordsString, ReversedPhrase]). + +?- phrase_reversals("rosetta code phrase reversal"). diff --git a/Task/Pick-random-element/DuckDB/pick-random-element.duckdb b/Task/Pick-random-element/DuckDB/pick-random-element.duckdb new file mode 100644 index 0000000000..b07f63cdcc --- /dev/null +++ b/Task/Pick-random-element/DuckDB/pick-random-element.duckdb @@ -0,0 +1,9 @@ +# PRN in range(0,n) +create or replace function prn(n) as trunc(random() * n)::BIGINT; + +create or replace function list_random(lst) as + lst[ 1 + prn(length(lst)) ] ; + +## Example: +select histogram( r ) + from (select list_random( [1,2,3] ) as r from range(0,1000) _(n)); diff --git a/Task/Pick-random-element/Pluto/pick-random-element.pluto b/Task/Pick-random-element/Pluto/pick-random-element.pluto new file mode 100644 index 0000000000..aa31eb925a --- /dev/null +++ b/Task/Pick-random-element/Pluto/pick-random-element.pluto @@ -0,0 +1,4 @@ +local ordinals = {"first", "second", "third", "fourth", "fifth", "sixth"} +for _ = 1, 6 do + print(ordinals[math.random(1, #ordinals)]) +end diff --git a/Task/Pick-random-element/Scheme/pick-random-element.scm b/Task/Pick-random-element/Scheme/pick-random-element.scm new file mode 100644 index 0000000000..bcfa5e7f93 --- /dev/null +++ b/Task/Pick-random-element/Scheme/pick-random-element.scm @@ -0,0 +1,6 @@ +; for Chicken Scheme +(import (chicken random)) + +(define (pick_random x) + (list-ref x (pseudo-random-integer (length x))) + ) diff --git a/Task/Pick-random-element/Tcl/pick-random-element.tcl b/Task/Pick-random-element/Tcl/pick-random-element-1.tcl similarity index 100% rename from Task/Pick-random-element/Tcl/pick-random-element.tcl rename to Task/Pick-random-element/Tcl/pick-random-element-1.tcl diff --git a/Task/Pick-random-element/Tcl/pick-random-element-2.tcl b/Task/Pick-random-element/Tcl/pick-random-element-2.tcl new file mode 100644 index 0000000000..7ebf4cd2c5 --- /dev/null +++ b/Task/Pick-random-element/Tcl/pick-random-element-2.tcl @@ -0,0 +1,79 @@ +# seed rng +set seed [expr { srand([clock clicks]) }] + +# return a list of random selections of items from a list +proc random_items { item_list {n 1} {dups no} } { + + # use item_list in place as items + upvar 1 $item_list items + + set result {} + set max [llength $items] + + if { $n > $max} {set n $max} + + set count 0 + + while { $count < $n } { + + # random integer index 0..len-1 + set idx [expr { int(rand() * $max)} ] + + # pick item + set item [lindex $items $idx] + + # check for dups + if {$dups eq no} { + set srch [lsearch $result $item] + if {$srch > -1} { continue } + } + + lappend result $item + incr count + } + return $result + } + +# randomize a list in place +proc randomize {item_list} { + upvar 1 $item_list items + set len [llength $items] + set items [random_items items $len] +} + +# return a new shuffled list +proc shuffle {items} { + set len [llength $items] + return [random_items items $len] +} + +# test cases + +set animals { + dog cat bird ant fish + horse pig cow snake mouse + whale worm bug spider deer + bee bear human gecko octopus +} + +# 1 item default +set guess [random_items animals] + +puts stdout "guess: $guess \n" + +# in place shuffle +randomize animals + +# list of 4 random items, no dups +set A [random_items animals 4] +set B [random_items animals 5] +set C [random_items animals 6] + +set dashline [string repeat "-" 30] + +foreach a {$A $B $C} { + puts stdout $dashline + puts stdout "${a}" +} + +puts stdout $dashline diff --git a/Task/Pierpont-primes/Python/pierpont-primes.py b/Task/Pierpont-primes/Python/pierpont-primes.py index 521b859a70..2357266bec 100644 --- a/Task/Pierpont-primes/Python/pierpont-primes.py +++ b/Task/Pierpont-primes/Python/pierpont-primes.py @@ -44,8 +44,8 @@ def pierpont(ulim, vlim, first): p2 = 1 p3 = 1 pp = [] - for v in xrange(vlim): - for u in xrange(ulim): + for v in range(vlim): + for u in range(ulim): p = p2 * p3 if first: p = p + 1 @@ -60,19 +60,19 @@ def pierpont(ulim, vlim, first): return pp def main(): - print "First 50 Pierpont primes of the first kind:" + print("First 50 Pierpont primes of the first kind:") pp = pierpont(120, 80, True) - for i in xrange(50): - print "%8d " % pp[i], + for i in range(50): + print("%8d " % pp[i], end="") if (i - 9) % 10 == 0: - print - print "First 50 Pierpont primes of the second kind:" + print("") + print("First 50 Pierpont primes of the second kind:") pp2 = pierpont(120, 80, False) - for i in xrange(50): - print "%8d " % pp2[i], + for i in range(50): + print ("%8d " % pp2[i], end="") if (i - 9) % 10 == 0: - print - print "250th Pierpont prime of the first kind:", pp[249] - print "250th Pierpont prime of the second kind:", pp2[249] + print("") + print("250th Pierpont prime of the first kind:", pp[249]) + print("250th Pierpont prime of the second kind:", pp2[249]) main() diff --git a/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx b/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx index 9893ca2589..7b53acb5f2 100644 --- a/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx +++ b/Task/Pierpont-primes/REXX/pierpont-primes-1.rexx @@ -1,11 +1,11 @@ --- 11 Apr 2025 +-- 28 Jul 2025 include Settings +numeric digits 40 call Time('r') say 'PIERPOINT PRIMES (BRUTE FORCE)' say version say -numeric digits 40 call GetPierpont call Sort 'firs.' call Sort 'seco.' @@ -14,7 +14,7 @@ say Format(Time('e'),,3) 'seconds'; say exit GetPierpont: -procedure expose firs. glob. seco. +procedure expose firs. Memo. seco. say 'Get Pierpont primes...' n1 = 0; firs. = 0; n2 = 0; seco. = 0 p = 0; m = 1e40 @@ -70,7 +70,4 @@ say seco.250 say return -include Numbers -include Functions -include Helper -include Abend +include Math diff --git a/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx b/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx index c6f72e9921..fdebc4b1da 100644 --- a/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx +++ b/Task/Pierpont-primes/REXX/pierpont-primes-2.rexx @@ -1,11 +1,11 @@ --- 11 Apr 2025 +-- 28 Jul 2025 include Settings +numeric digits 40 call Time('r') say 'PIERPOINT PRIMES (USING 3-SMOOTH NUMBERS)' say version say -numeric digits 40 call GetSmooth call GetPierpont call ShowPierpont @@ -21,7 +21,7 @@ say return GetPierpont: -procedure expose smoo. firs. seco. glob. +procedure expose smoo. firs. seco. Memo. say 'Get Pierpont primes...' n1 = 0; firs. = 0; n2 = 0; seco. = 0; p = 0 do i = 1 to smoo.0 @@ -65,8 +65,4 @@ say seco.250 say return -include Numbers -include Constants -include Sequences -include Functions -include Abend +include Math diff --git a/Task/Pisano-period/Agena/pisano-period.agena b/Task/Pisano-period/Agena/pisano-period.agena new file mode 100644 index 0000000000..f2c13d2239 --- /dev/null +++ b/Task/Pisano-period/Agena/pisano-period.agena @@ -0,0 +1,32 @@ +scope # find the Pisano period of some primes and composites + + local procedure pisano( m :: number ) :: number # returns the Pisano period of m + local p, c := 0, 1; + for i from 0 to ( m * m ) - 1 do + p, c := c, ( p + c ) mod m; + if p = 0 and c = 1 then return i + 1 fi + od; + return 1 + end; + + # returns the Pisano period of p^k or 0 if p is not prime or k < 1 + local procedure pisanoPrime( p :: number, k :: number ) :: number + return if not numtheory.isprime( p ) or k < 1 then 0 else entier ( p ^ ( k - 1 ) * pisano( p ) ) fi + end; + + print( "Pisano period of p^2 where p is a prime < 15:" ); + for p to 15 do + if numtheory.isprime( p ) then printf( " %d:%d", p, pisanoPrime( p, 2 ) ) fi + od; + printf( "\nPisano period of primes up to 180, non-primes shown as \"*\":\n" ); + for p to 180 do + if not numtheory.isprime( p ) then printf( " *" ) else printf( "%4d", pisanoPrime( p, 1 ) ) fi; + if p mod 10 = 0 then print() fi + od; + print( "\nPisano period of positive integers up to 180:" ); + for n to 180 do + printf( "%4d", pisano( n ) ); + if n mod 10 = 0 then print() fi + od + +end diff --git a/Task/Pisano-period/Pluto/pisano-period.pluto b/Task/Pisano-period/Pluto/pisano-period.pluto new file mode 100644 index 0000000000..5f5ec2931f --- /dev/null +++ b/Task/Pisano-period/Pluto/pisano-period.pluto @@ -0,0 +1,42 @@ +do -- find the Pisano period of some primes and composites + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library - inc. some prime utilities + + local maxNumber = 180 + local isComposite = int.arecomps( maxNumber ) + + local function pisano( m ) -- returns the Pisano period of m + local p, c = 0, 1 + for i = 0, ( m * m ) - 1 do + p, c = c, ( p + c ) % m + if p == 0 and c == 1 then return i + 1 end + end + return 1 + end + + -- returns the Pisano period of p^k or 0 if p is not prime or k < 1 + local function pisanoPrime( p, k ) + return if isComposite[ p ] or k < 1 then 0 else math.floor( p ^ ( k - 1 ) * pisano( p ) ) end + end + + local function d4( n ) -- returns n formatted in 4 characcters + return string.format( "%4d", n ) + end + + io.write( "Pisano period of p^2 where p is a prime < 15:\n" ) + for p = 1, 15 do + if not isComposite[ p ] then fmt.write( " %d:%d", p, pisanoPrime( p, 2 ) ) end + end + io.write( "\nPisano period of primes up to 180, non-primes shown as \"*\":\n" ) + for p = 1, 180 do + io.write( if isComposite[ p ] then " *" else d4( pisanoPrime( p, 1 ) ) end ) + if p % 10 == 0 then io.write( "\n" ) end + end + io.write( "\nPisano period of positive integers up to 180:\n" ) + for n = 1, 180 do + io.write( d4( pisano( n ) ) ) + if n % 10 == 0 then io.write( "\n" ) end + end + +end diff --git a/Task/Plasma-effect/EasyLang/plasma-effect.easy b/Task/Plasma-effect/EasyLang/plasma-effect.easy index 6ced409589..889a7c06ed 100644 --- a/Task/Plasma-effect/EasyLang/plasma-effect.easy +++ b/Task/Plasma-effect/EasyLang/plasma-effect.easy @@ -11,8 +11,8 @@ on animate val += sin dist x y 25 25 val += sin (dist x (y + time / 7) 75 50 * 1.2) val += sin dist x y 75 40 - col = (val + 4) / 16 - gcolor3 col col * 2 1 - col + col = (val + 4) * 6 + gcolor3 col col * 2 100 - col grect x y 0.5 0.5 . . diff --git a/Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug b/Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug new file mode 100644 index 0000000000..228c48d0c0 --- /dev/null +++ b/Task/Play-recorded-sounds/FuncSug/play-recorded-sounds.funcsug @@ -0,0 +1,30 @@ +# play the sounds sequentially +playSoundFile('rattle.mp3') +playSoundFile('tactactac.mp3') +playSoundFile('dingding.mp3') + +# play the sounds simultaneously +parallel || + playSoundFile('rattle.mp3') +|| + playSoundFile('tactactac.mp3') +|| + playSoundFile('dingding.mp3') + +# loop a sound +while true: + playSoundFile('rattle.mp3') + +# stop before the end of the sound +parallel exitWith branch 1 || + waitSeconds(4) +|| + playSoundFile('dingding.mp3') + +# stop all the sounds when the shortest one is finished +parallel exitAfter 1 finished || + playSoundFile('rattle.mp3') +|| + playSoundFile('tactactac.mp3') +|| + playSoundFile('dingding.mp3') diff --git a/Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku b/Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku new file mode 100644 index 0000000000..73e8d5dc1f --- /dev/null +++ b/Task/Play-recorded-sounds/Raku/play-recorded-sounds.raku @@ -0,0 +1,31 @@ +# 20250723 Raku programming solution + +use Audio::Sndfile; +use Audio::PortAudio; + +sub play-wavs(Str $filename) { + my $sf = Audio::Sndfile.new(:filename($filename), :r); + die "Failed to open $filename" unless $sf; + my $sample-rate = $sf.samplerate; + my $channels = $sf.channels; + my $pa = Audio::PortAudio.new; + my $stream = $pa.open-default-stream( + 0, $channels, + Audio::PortAudio::StreamFormat::Float32, + $sample-rate, 512 + ); + $stream.start; + loop { + my ($buffer, $frames) = $sf.read-float(512, :raw); + $stream.write($buffer, $frames); + last if $frames < 512; + } + $stream.close; + $sf.close; +} + +sub MAIN(*@files) { + die "No files provided" unless @files; + + await Promise.allof( @files.map: { start { .&play-wavs } } ) +} diff --git a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy index 2d3e711232..40ec7f9b33 100644 --- a/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy +++ b/Task/Plot-coordinate-pairs/EasyLang/plot-coordinate-pairs.easy @@ -1,15 +1,12 @@ x[] = [ 0 1 2 3 4 5 6 7 8 9 ] y[] = [ 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0 ] # -gclear glinewidth 0.5 gline 10 5 10 97 gline 10 5 95 5 gtextsize 3 n = len x[] -for i = 1 to n - max = higher y[i] max -. +for i to n : max = higher y[i] max glinewidth 0.1 sty = max div 9 stx = x[n] div 9 @@ -21,10 +18,9 @@ for i range0 10 . color 900 linewidth 0.5 +gpenup for i = 1 to n - xp = x - yp = y x = x[i] * 9 / stx + 10 y = y[i] / sty * 10 + 5 - if i > 1 : gline xp yp x y + glineto x y . diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 deleted file mode 100644 index ad240d902c..0000000000 --- a/Task/Polymorphism/M2000-Interpreter/polymorphism-1.m2000 +++ /dev/null @@ -1,6 +0,0 @@ -\\ block For This {}, or For object [, object2] { }, where object is a group, or a pointer to group, or an item from an array contains a group -\\ This is "this context". -For This { -\\ any new definition here has a temporary use -\\ can be nested, but if we use object then we can use dots to access members of it. If we use a second one then we have to use double dots (..x for second object, for access to x member) -} diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 deleted file mode 100644 index 7f05b1ec8c..0000000000 --- a/Task/Polymorphism/M2000-Interpreter/polymorphism-2.m2000 +++ /dev/null @@ -1,76 +0,0 @@ -Class PointA { - Property x=0~ - Property Y=0~ - Operator "=" (n1) { - n=group(n1) - if n.x=.x Then if n.y=.y then push true : exit - push false - } - Module Print { - Print "Point" , .x, .y - } -Class: - Module PointA { - \\ ? means optionally - Read ? .[x], .[y] - } -} -Class Circle { - Property R=300~ ' type single - Operator "=" (n1) { - n=group(n1) - n2=This ' get a copy of this to check n against n2 - if valid(@n as n2) else push false :exit - if n.x=.x Then if n.y=.y then if n.r=.r then push true : exit - push false - } - Module Print { - Print "Circle", .x, .y, .r - } -Class: - Module Circle { - if match("nn") then { - M=PointA(Number, Number) - } Else.if match("G") then { - M=PointA() - Read M - } Else M=PointA() - M=This -\\ If match("N") then Read M.r \\ check if a number is in top of stack -\\ Read ? M.r \\ optionally - Read M.r \\ for this example, r has value, so this used if stack is empty. - This=M - } -} -A=PointA(10,3) -C=Circle(20,10,5) -D=Circle(A, 100) -B=A -K=PointA() -Z=Circle(A) -P=PointA(600,700) - -\\ N is a pointer to array -N=(A, B, C, D, K, P, Z) -M=each(N) -While M { - For This { - \\ a copy in MM - MM=Array(M) - MM.Print - Print A=MM, D=MM ' using MM=A interpreter use "=" from MM - } -} - -\\ pA is a pointer to D (a named group) -pA->D -Print pA=D, pA=Z -pA=>Print -\\ pA is a pointer to a copy of D (a float group) -pA->(D) -Print pA=D, pA=Z -pA=>Print - -\\ rA is a reference to D (& is optional in Link statement) -Link &D to &rA -rA.Print diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 deleted file mode 100644 index fc2f0b2b45..0000000000 --- a/Task/Polymorphism/M2000-Interpreter/polymorphism-3.m2000 +++ /dev/null @@ -1,67 +0,0 @@ -Class PointA { - X=0~, Y=0~ - Module Print { - Print "Point" , .x, .y - } -Class: - Module PointA { - Read ? .x, .y - } -} -Class Circle { - Property R { - Value, - Set { - If Value>1000 then Value=1000 - } - }=300~ - Module Print { - Print "Circle", .x, .y, .r - } -Class: - Module Circle { - if match("nn") then { - M=PointA(Number, Number) - } Else.if match("G") then { - M=PointA() - Read M - } Else M=PointA() - M=This - This=M - Read ? .r - } -} -A=PointA(10,3) -C=Circle(20,10,5) -D=Circle(A, 100) -B=A -K=PointA() -Z=Circle(A) -P=PointA(600,700) - - \\ N is a pointer to stack -N=Stack:=A, B, C, D, K, P, Z -\\ M is a pointer to an iterator -M=each(N) -While M { - For This { - \\ a copy in MM - MM=StackItem(M) - MM.Print - } -} -\\ NN is a pointer to Inventory -Inventory NN= 1:=A, 2:=B, 3:=C, 4:=D, 5:=K, 6:=P,7:= Z -M=each(NN) -While M { - For This { - \\ a copy in MM - MM=Eval(M) - MM.Print - } -} -\\ we can call NN(3).print -Print "NN(3).Print" -NN(3).Print -NN(3).R=5000 -NN(3).Print diff --git a/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 b/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 new file mode 100644 index 0000000000..39d1adf57e --- /dev/null +++ b/Task/Polymorphism/M2000-Interpreter/polymorphism.m2000 @@ -0,0 +1,108 @@ +Module Polymorphism { + Class Point { + private: + double x, y + public: + module print { + Print "x="+.x, "y="+.y + } + class: + module Point (.x, .y) { + } + } + + Class Circle as Point { + private: + double r + public: + group radius { + value { + link parent r to r + =r + } + Set { + Error "No Set for radius" + } + } + module print { + Print "x="+.x, "y="+.y, "r="+.r + } + class: + module Circle (.x, .y, .r) { + } + } + + Class Circle2{ + { ' a different constructor - Version 14 + read xa=0, ya=0, ra=0 + if ra=0 then ra=1 + } + public: + Property r { + value, ' we can read it + set { ' we can change if is >0 + if value<=0 then exit ' skip + } + }=ra + Point Inner(xa, ya) + // add a function to Inner to read private X and Y + Group Inner { + function readXY { + =.x, .y + } + } + Group CircleType { ' an inner object which return a value of type circle + Value { ' return a Circle type + link parent Inner to that + link parent r to ra + =Circle(!that.readXY(), ra) + } + } + module print { + (x,y)=.inner.readXY() + Print "x="+x, "y="+y, "r="+.r + } + } + + A=Point(10, 20) + B=Circle(2,3,5) + doit(A) + doit(B) + print B is type Point = true + print B is type Circle = true + C=Circle2(12,13,15) + C.r=0 + Print "C radius = ";C.r + print C is type Circle2 = true + doit(C.CircleType) + // Circle2 has a Point object + doit(C.Inner) + D=C.CircleType + print "D radious = ";d.radius + try { + d.radius=100 + } + print error$ + print D is type Point = true + print D is type Circle = true + print D is type Circle2 = false + doit(D) + doit2(&D) + doit3(pointer(D)) ' we pass a weak reference - pointer((D)) is a real pointer of a copy of D + Z->Point(10, 20) ' same as Z=Pointer(Point(10,20)), it is a real pointer + doit4(&Z) + End + sub doit(a as Point) ' pass by value + a.print + end sub + sub doit2(&a as Point) ' pass by reference + a.print + end sub + sub doit3(a as *Point) ' pass by value a pointer (weak reference or real pointer) + a=>print + end sub + sub doit4(&a as *Point) ' pass by reference a pointer (weak reference or real pointer) + a=>print + end sub +} +Polymorphism diff --git a/Task/Polymorphism/Rhombus/polymorphism-1.rhombus b/Task/Polymorphism/Rhombus/polymorphism-1.rhombus new file mode 100644 index 0000000000..cbaa7b99a0 --- /dev/null +++ b/Task/Polymorphism/Rhombus/polymorphism-1.rhombus @@ -0,0 +1,11 @@ +#lang rhombus/static + +class Point(~x = 0, ~y = 0): + nonfinal + method print(): + println(@str{Point at @(x),@(y)}) + +class Circle(~r = 1): + extends Point + override method print(): + println(@str{Circle at @(x),@(y) with radius @(r)}) diff --git a/Task/Polymorphism/Rhombus/polymorphism-2.rhombus b/Task/Polymorphism/Rhombus/polymorphism-2.rhombus new file mode 100644 index 0000000000..5808495570 --- /dev/null +++ b/Task/Polymorphism/Rhombus/polymorphism-2.rhombus @@ -0,0 +1,13 @@ +def p = Point() +p.print() // Point at 0,0 +println(p.x) // 0 + +def p2 = Point(~y: 1) +p2.print() // Point at 0,1 + +def c = Circle(~y: 3, ~r: 2) +c.print() // Circle at 0,3 with radius 2 +println(c.r) // 2 + +def c2 = Circle(~y: 5) +c2.print() // Circle at 0,5 with radius 5 diff --git a/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx b/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx index 5846bb92c0..eb933688ab 100644 --- a/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx +++ b/Task/Polynomial-long-division/REXX/polynomial-long-division-2.rexx @@ -1,6 +1,7 @@ +-- 30 Jul 2025 include Settings -say 'POLYNOMIAL LONG DIVISION - 2 Mar 2025' +say 'POLYNOMIAL LONG DIVISION' say version say call Divide '1 -12 0 -42','1 -3' @@ -15,12 +16,9 @@ exit Divide: arg x,y -z = Pdiv(x,y); parse var z q','r -say 'Formula:' Plst2form(x) '/' Plst2form(y) '=' Plst2form(q) 'Rem' Plst2form(r) -say 'Check :' Plst2form(q) '*' Plst2form(y) '+' Plst2form(r) '=' Plst2form(Padd(Pmul(q,y),r)) -say +z = DivP(x,y); parse var z q','r +say 'Formula:' Lst2FormP(x) '/' Lst2FormP(y) '=' Lst2FormP(q) 'Rem' Lst2FormP(r) +say 'Check :' Lst2FormP(q) '*' Lst2FormP(y) '+' Lst2FormP(r) '=' Lst2FormP(AddP(MulP(q,y),r)) return -include Polynomial -include Functions -include Abend +include Math diff --git a/Task/Polyspiral/EasyLang/polyspiral.easy b/Task/Polyspiral/EasyLang/polyspiral.easy index 0a2d0116c7..d7558c66a5 100644 --- a/Task/Polyspiral/EasyLang/polyspiral.easy +++ b/Task/Polyspiral/EasyLang/polyspiral.easy @@ -5,14 +5,13 @@ on animate incr = (incr + 0.05) mod 360 x = 50 y = 50 + glineto x y length = 1 angle = incr for i = 1 to 150 - xp = x - yp = y x += cos angle * length y += sin angle * length - gline xp yp x y + glineto x y length += 1 angle += incr . diff --git a/Task/Polyspiral/REBOL/polyspiral.rebol b/Task/Polyspiral/REBOL/polyspiral.rebol new file mode 100644 index 0000000000..7997e03fe3 --- /dev/null +++ b/Task/Polyspiral/REBOL/polyspiral.rebol @@ -0,0 +1,42 @@ +Rebol [ + title: "Rosetta code: Polyspiral" + file: %Polyspiral.r3 + url: https://rosettacode.org/wiki/Polyspiral + needs: 3.10.2 + note: [ + https://github.com/Oldes/Rebol3/releases + https://github.com/Siskin-framework/Rebol-Blend2D + ] +] +import blend2d ;; Import Blend2D extension used to draw + +incr: 0.0 ;; Initialize increment variable to 0.0 +image: make image! 800x800 ;; Create an 800x800 pixel image canvas +pi2: 2 * PI ;; Calculate 2π (full circle in radians), for angle calculations +random/seed 4 + +;; animation loop (repeats 4 times to create progressive spiral states) +loop 4 [ + x: image/size/x / 2 ;; Set x to center of image (horizontal) + y: image/size/y / 2 ;; Set y to center of image (vertical) + length: 5 ;; Starting length/step for spiral arms + incr: (incr + 5) % pi2 ;; Increment the angle step (modulo 2π to ensure it wraps correctly) + angle: incr + commands: clear [] ;; Clear previous drawing commands + color: 100.100.100 + random 155.155.155 + append commands [line-width 1 pen :color line] ;; Start a new line with width 1 and random pen color + + ;; spiral loop (generates points for the spiral) + loop 150 [ + x: x + (length * (cos angle)) ;; Move x along the current angle by current length + y: y + (length * (sin angle)) ;; Move y along the current angle by current length + append commands as-pair x y ;; Add the new (x, y) point to the command list + length: length + 5 ;; Increase the step size for spiral effect + angle: (angle + incr) % pi2 ;; Progress the angle for the spiral's curvature (modulo 2π) + ] + + draw image commands ;; Render the spiral on the image with the accumulated commands +] + +try [save %polyspiral.png image] ;; Save the image as PNG +try [view image] ;; Display the final image window with drawn spirals diff --git a/Task/Population-count/Prolog/population-count.pro b/Task/Population-count/Prolog/population-count.pro new file mode 100644 index 0000000000..3ed3711a67 --- /dev/null +++ b/Task/Population-count/Prolog/population-count.pro @@ -0,0 +1,12 @@ +is_evil(Number) :- popcount(Number) mod 2 =:= 0. + +:- numlist(0, 29, Powers), + maplist([P0, P] >> (P is popcount(3 ^ P0)), Powers, PowerPopcounts), + numlist(0, 59, Numbers), + partition(is_evil, Numbers, EvilNumbers, OdiousNumbers), + writeln('The pop counts of the first 30 powers of 3 are:'), + writeln(PowerPopcounts), + writeln('The first 30 evil numbers are:'), + writeln(EvilNumbers), + writeln('The first 30 odious numbers are:'), + writeln(OdiousNumbers). diff --git a/Task/Power-set/Pluto/power-set.pluto b/Task/Power-set/Pluto/power-set.pluto new file mode 100644 index 0000000000..dd495babab --- /dev/null +++ b/Task/Power-set/Pluto/power-set.pluto @@ -0,0 +1,9 @@ +require "perm" +local fmt = require "fmt" + +local sets = { {1, 2, 3, 4}, {}, {{}} } +for sets as set do + print($"The power set of {fmt.swrite(set)} is:") + fmt.lprint(powerset.list(set)) + print() +end diff --git a/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx b/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx index 7e3c3bfd7e..c59b8abf9c 100644 --- a/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx +++ b/Task/Primality-by-Wilsons-theorem/REXX/primality-by-wilsons-theorem.rexx @@ -1,4 +1,4 @@ --- 26 Mar 2025 +-- 28 Jul 2025 include Settings numeric digits 10 @@ -14,7 +14,7 @@ end exit ShowWilson: -procedure expose glob. +procedure expose Memo. arg xx,yy call Time('r') say 'Primes between' Std(xx) 'and' Std(yy) @@ -50,7 +50,7 @@ say 'For n between' Right(Std(xx),7) 'and' Right(Std(yy),7), return Isprime: -procedure expose glob. +procedure expose Memo. arg xx if xx < 2 then return 0 @@ -67,8 +67,4 @@ if f = x1 then else return 0 -include Sequences -include Numbers -include Functions -include Constants -include Abend +include Math diff --git a/Task/Primality-by-trial-division/ALGOL-68/primality-by-trial-division.alg b/Task/Primality-by-trial-division/ALGOL-68/primality-by-trial-division.alg index c1d43c9374..4ec46c729d 100644 --- a/Task/Primality-by-trial-division/ALGOL-68/primality-by-trial-division.alg +++ b/Task/Primality-by-trial-division/ALGOL-68/primality-by-trial-division.alg @@ -1,10 +1,20 @@ -main:( +BEGIN + PROC is prime = ( INT p )BOOL: + IF p <= 1 OR ( NOT ODD p AND p/= 2) THEN + FALSE + ELSE + BOOL prime := TRUE; + FOR i FROM 3 BY 2 TO ENTIER sqrt(p) + WHILE prime := p MOD i /= 0 DO SKIP OD; + prime + FI; + INT upb=100; - printf(($" The primes up to "g(-3)" are:"l$,upb)); + print((" The primes up to ", whole(upb,-3) ," are:")); FOR i TO upb DO IF is prime(i) THEN - printf(($g(-4)$,i)) + print((" ",whole(i,0))) FI OD; - printf($l$) -) + print((newline)) +END diff --git a/Task/Primality-by-trial-division/Agena/primality-by-trial-division.agena b/Task/Primality-by-trial-division/Agena/primality-by-trial-division.agena new file mode 100644 index 0000000000..7c01119817 --- /dev/null +++ b/Task/Primality-by-trial-division/Agena/primality-by-trial-division.agena @@ -0,0 +1,13 @@ +scope # find some primes by trial division + + local constant is_prime := proc( n :: number ) :: boolean + local result := n = 2 or ( odd n and n > 1 ); + for k from 3 to entier sqrt( n ) by 2 while result do + result := n mod k <> 0 + od; + return result + end; + + for p from 0 to 100 do if is_prime( p ) then printf( " %d", p ) fi od + +end diff --git a/Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-1.duckdb b/Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-1.duckdb new file mode 100644 index 0000000000..6f8023e2e4 --- /dev/null +++ b/Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-1.duckdb @@ -0,0 +1,29 @@ +create or replace function n() as 514229; + +create or replace function primep(nnumber) as ( +with recursive cte(number) as +( + select 2 + union all + select number+1 + from cte + where number+1 < nnumber +) +select + case + when nnumber < 2 then false + when nnumber = 2 then true + when exists + ( select * + from + ( select number, nnumber % number modNumber + from cte + ) tmp + where tmp.modNumber = 0 + ) + then false + else true + end primalityTest +); + +select n, primep(n) from (select n() as n); diff --git a/Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-2.duckdb b/Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-2.duckdb new file mode 100644 index 0000000000..558678d804 --- /dev/null +++ b/Task/Primality-by-trial-division/DuckDB/primality-by-trial-division-2.duckdb @@ -0,0 +1,18 @@ +create or replace function n() as 514229; + +create or replace function primep(nnumber) as ( + select + case + when nnumber < 2 then false + when nnumber = 2 then true + else NOT exists + ( select * from + ( select (nnumber % anumber) as modNumber + from (select unnest(range(2, 1 + sqrt(nnumber)::BIGINT)) as anumber) + ) + where modNumber = 0 + ) + end +); + +select n, primep(n) from (select n() as n); diff --git a/Task/Primality-by-trial-division/Pluto/primality-by-trial-division.pluto b/Task/Primality-by-trial-division/Pluto/primality-by-trial-division.pluto new file mode 100644 index 0000000000..45cf5165e7 --- /dev/null +++ b/Task/Primality-by-trial-division/Pluto/primality-by-trial-division.pluto @@ -0,0 +1,13 @@ +function isprime(n) + if n<2 then return false end + for i=2,math.sqrt(n) do + if n%i==0 do return false end + end + return true +end + +for i = 1,20 do + if isprime(i) then + io.write(i,'\t') + end +end diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx index f823f29a39..43b4557b7d 100644 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx +++ b/Task/Primality-by-trial-division/REXX/primality-by-trial-division.rexx @@ -1,4 +1,4 @@ --- 26 Mar 2025 +-- 28 Jul 2025 include Settings numeric digits 15 @@ -15,7 +15,7 @@ exit ShowTrial: procedure -arg xx,yy +arg xx,yy,zz call Time('r') say 'Primes between' std(xx) 'and' std(yy) 'by trial division' n = 0; w = Xpon(yy)+2 @@ -34,7 +34,7 @@ return ShowMR: procedure -arg xx,yy +arg xx,yy,zz call Time('r') say 'Primes between' std(xx) 'and' std(yy) 'by Miller-Rabin' n = 0; w = Xpon(yy)+2 @@ -83,8 +83,4 @@ do i = 3 by 2 to Isqrt(xx) end return 1 -include Sequences -include Numbers -include Functions -include Constants -include Abend +include Math diff --git a/Task/Prime-decomposition/DuckDB/prime-decomposition.duckdb b/Task/Prime-decomposition/DuckDB/prime-decomposition.duckdb new file mode 100644 index 0000000000..e95b2fd280 --- /dev/null +++ b/Task/Prime-decomposition/DuckDB/prime-decomposition.duckdb @@ -0,0 +1,29 @@ +create or replace function prime_factors(nn) as table ( + with recursive cte(p, q, valid, s) as ( + select 2::UHUGEINT as p, nn::UHUGEINT as q, false as valid, null::DOUBLE as s + union all + select unnest( + if (q = 1, (0, 0, false, null), + if (q % p = 0, (p, q // p, true, null), + if (p = 2, (3, q, false, s), + if (p + 2 <= coalesce(s, sqrt(q)), + (p + 2, q, false, coalesce(s, sqrt(q))), + (q, 1, true, null) )))) ) + from cte + where p != 0 + ) + select p + from cte + where valid +); + +## Examples + +.print The prime factors of 24: +from prime_factors(24); + +.print The prime factors of 2**29-1 = 536870911 +from prime_factors(536870911); + +.print Counting the prime factors of 9007199254740992: +select count(*) from prime_factors(9007199254740992); diff --git a/Task/Prime-decomposition/OoRexx/prime-decomposition.rexx b/Task/Prime-decomposition/OoRexx/prime-decomposition.rexx new file mode 100644 index 0000000000..6a12d13754 --- /dev/null +++ b/Task/Prime-decomposition/OoRexx/prime-decomposition.rexx @@ -0,0 +1,36 @@ +.local~digits=50 +numeric digits .local~digits +say 'PRIME DECOMPOSITION' +parse version version +say version +call ShowFactors 100,120 +call ShowFactors 720720 +call ShowFactors 9007199254740991 +call ShowFactors 2543821448263974486045199 +call ShowFactors 340282366920938463463374607431768211455 +exit + +ShowFactors: +Call time 'R' +arg xx,yy +if yy = '' then + yy = xx +do i = xx to yy + call Charout ,i '= ' + f = factors(i) + if f = 1 then + call Charout ,'Prime' + else do + do j = 1 to f + call Charout ,GetFact(,j) + if j < f then + call Charout ,' x ' + end + end + say +end +say Format(Time('e'),,3) 'seconds' +say +return + +::REQUIRES math.cls diff --git a/Task/Priority-queue/Pluto/priority-queue.pluto b/Task/Priority-queue/Pluto/priority-queue.pluto new file mode 100644 index 0000000000..30771d4b63 --- /dev/null +++ b/Task/Priority-queue/Pluto/priority-queue.pluto @@ -0,0 +1,12 @@ +require "queue" + +local tasks = new pqueue() +tasks:push(3, "Clear drains") +tasks:push(4, "Feed cat") +tasks:push(5, "Make tea") +tasks:push(1, "Solve RC tasks") +tasks:push(2, "Tax return") +while !tasks:empty() do + local [p, v] = tasks:pop() + print($"{p} {v}") +end diff --git a/Task/Probabilistic-choice/DuckDB/probabilistic-choice.duckdb b/Task/Probabilistic-choice/DuckDB/probabilistic-choice.duckdb new file mode 100644 index 0000000000..dfd02ca56b --- /dev/null +++ b/Task/Probabilistic-choice/DuckDB/probabilistic-choice.duckdb @@ -0,0 +1,65 @@ +set variable letters = ['aleph', 'beth', 'gimel', 'daleth', 'he', 'waw', 'zayin', 'heth']; + +# The list of probabilities - last value must be given but will be ignored: +set variable probs = [1/5, 1/6, 1/7, 1/8, 1/9, 1/10, 1/11, 0]; + +create or replace function cumulative_probabilities(probs) as ( + with recursive cte0 as + (select 1 as ix, probs[1]::double as cum + union all + select ix+1 as ix, + cum + probs[ix + 1] as cum + from cte0 + where ix < length(probs)) + select array_agg(cum order by ix) + from cte0 +); + +# It is imperative to materialize rand because of DuckDB's "inlining" +create or replace function choice(rand, cumProbs) as ( + with r as materialized(select rand as r) + select + if (r <= cumProbs[1], 1, + if (r <= cumProbs[2], 2, + if (r <= cumProbs[3], 3, + if (r <= cumProbs[4], 4, + if (r <= cumProbs[5], 5, + if (r <= cumProbs[6], 6, + if (r <= cumProbs[7], 7, 8) )))))) + from r +); + +# Infer the expected value for the last category +create or replace function expectations(probs, n) as ( + with ns as (select list_transform(probs[0:-2], x -> x*n) as ns), + subtotal as (select list_sum(ns) as subtotal from ns) + select ns || [ n - subtotal ] + from ns, subtotal +); + +# Generate the histogram of observed letters +create or replace function play(mx) as table ( + with recursive cumProbs as (select cumulative_probabilities(getvariable('probs')) as cumProbs), + cte as ( + select 1 as n, choice(random(), cumProbs) as cat + from cumProbs + union all + select n+1 as n, choice(random(), cumProbs) as cat + from cte, cumProbs + where n < mx) + select histogram(cat) as histogram + from cte +); + +create or replace function synopsis(n) as table ( + e as (select expectations(getvariable('probs'),n) as e) + + select i as n, + getvariable('letters')[i] as letter, + e[i]::DECIMAL(10,2) as expected, + coalesce(histogram[i],0) as observed, + ((observed - expected)^2/expected)::DECIMAL(10,2) as "(o-e)^2/e" + from e, play(n), range(1, 1 + length(getvariable('probs'))) _(i) ) +); + +from synopsis(1000000); diff --git a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy index de27f6f500..445a258d63 100644 --- a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy +++ b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy @@ -41,12 +41,11 @@ solve c1[] c2[] c3[] -1 -1 -1 r2[] print r2[] # proc circ x0 y0 r . + gpenup for a = 0 to 360 - xp = x - yp = y x = x0 + sin a * r y = y0 + cos a * r - if a > 0 : gline xp yp x y + glineto x y . . proc draw col c[] . diff --git a/Task/Program-termination/ArkScript/program-termination.ark b/Task/Program-termination/ArkScript/program-termination.ark new file mode 100644 index 0000000000..1d50c12ef3 --- /dev/null +++ b/Task/Program-termination/ArkScript/program-termination.ark @@ -0,0 +1,3 @@ +(sys:exit 0) # exit code 0 + +# any code after won't be executed diff --git a/Task/Proper-divisors/DuckDB/proper-divisors.duckdb b/Task/Proper-divisors/DuckDB/proper-divisors.duckdb new file mode 100644 index 0000000000..ec6feab5ae --- /dev/null +++ b/Task/Proper-divisors/DuckDB/proper-divisors.duckdb @@ -0,0 +1,33 @@ +# A table (i) of distinct BIGINT proper divisors, not necessarily sorted +create or replace function proper_divisors(n) as table ( + select 1 where n > 1 + union all + select distinct i + from (select unnest( [ j, n // j]) as i + from range(2, 1 + sqrt(n).floor()::BIGINT) as t(j) + where (n % j) == 0) +); + +# Still not necessarily sorted +create or replace function list_of_proper_divisors(n) as ( + select coalesce(array_agg(i), []) + from proper_divisors(n) _(i) +); + +create or replace function maximally_many_proper_divisors(mx) as table ( + with cte as ( + select n, length(list_of_proper_divisors(n)) as length + from range(1,mx+1) _(n)), + maxlength as (select max(length) as maxlength from cte) + select n, length + from cte, maxlength + where length = maxlength.maxlength + order by n +); + +.print A sampling of proper divisors: +from range(1,11) _(n) +select n, list_of_proper_divisors(n); + +.print The positive integers less than or equal to 20,000 with the most distinct proper divisors: +from maximally_many_proper_divisors(20000); diff --git a/Task/Pseudo-random-numbers-Middle-square-method/DuckDB/pseudo-random-numbers-middle-square-method.duckdb b/Task/Pseudo-random-numbers-Middle-square-method/DuckDB/pseudo-random-numbers-middle-square-method.duckdb new file mode 100644 index 0000000000..5f9e588792 --- /dev/null +++ b/Task/Pseudo-random-numbers-Middle-square-method/DuckDB/pseudo-random-numbers-middle-square-method.duckdb @@ -0,0 +1,20 @@ +# `seed` should be a positive integer or numeric string representing a positive integer; +# `mx` is the maximum number of rows +# Output: a table of the "middle-squares" as HUGEINT values +create or replace function middle_square(seed, mx) as table ( + with recursive n as (select length(seed::VARCHAR) as n, (n // 2) as n2), + cte as ( + select 0 as ix, + seed::VARCHAR as ms + from n + union all + select ix+1 as ix, + format('{:0>{}}', (ms::HUGEINT * ms::HUGEINT)::VARCHAR, 2*n)[ n2 + 1 : n2 + n ] as ms + from cte, n + where ix < mx and NOT ms ~ '0*' + ) + select ms::HUGEINT + from cte offset 1 +); + +from middle_square(675248, 10) _(ms); diff --git a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy index 17eec9353f..b018db9c7c 100644 --- a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy +++ b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy @@ -8,7 +8,7 @@ proc tree x1 y1 x2 y2 depth . y4 = y1 + dx x5 = x4 + 0.5 * (dx + dy) y5 = y4 + 0.5 * (dx - dy) - gcolor3 0.3 0.2 + depth / 18 0.1 + gcolor3 30 20 + depth * 6 10 gpolygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] gpolygon [ x3 y3 x4 y4 x5 y5 ] tree x4 y4 x5 y5 depth + 1 diff --git a/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js b/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js index 8e9c4abb97..c8a4836a30 100644 --- a/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js +++ b/Task/Pythagoras-tree/JavaScript/pythagoras-tree-2.js @@ -1,4 +1,4 @@ -const base = [[[-200, 0], [200, 0]],]; +var base = [[[-200, 0], [200, 0]],]; document.documentElement.innerHTML = [...Array(12)].reduce((svg_a, _, lvl) => { const rg = step => (80 + (lvl - 2) * step) & 255; return svg_a + base.splice(0).reduce((g_a, [a, b]) => { diff --git a/Task/Quaternion-type/REXX/quaternion-type.rexx b/Task/Quaternion-type/REXX/quaternion-type.rexx index 6d6eb480da..e472ad5072 100644 --- a/Task/Quaternion-type/REXX/quaternion-type.rexx +++ b/Task/Quaternion-type/REXX/quaternion-type.rexx @@ -1,4 +1,4 @@ --- 19 May 2025 +-- 28 Jul 2025 include Settings say 'QUATERNION TYPE' @@ -7,36 +7,35 @@ say i = '0 1'; j = '0 0 1'; k = '0 0 0 1' q = '1 2 3 4'; q1 = '2 3 4 5'; q2 = '3 4 5 6'; r = 7 say 'VALUES' -say 'i =' Hlst2Form(i) -say 'j =' Hlst2Form(j) -say 'k =' Hlst2Form(k) -say 'q =' Hlst2Form(q) -say 'q1 =' Hlst2Form(q1) -say 'q2 =' Hlst2Form(q2) -say 'r =' Hlst2Form(r) +say 'i =' Lst2FormH(i) +say 'j =' Lst2FormH(j) +say 'k =' Lst2FormH(k) +say 'q =' Lst2FormH(q) +say 'q1 =' Lst2FormH(q1) +say 'q2 =' Lst2FormH(q2) +say 'r =' Lst2FormH(r) say say 'BASICS' -say 'i*i =' Hlst2Form(Hsquare(i)) -say 'j*j =' Hlst2Form(Hsquare(j)) -say 'k*k =' Hlst2Form(Hsquare(k)) -say 'i*j*k =' Hlst2Form(Hmul(i,j,k)) -say '||q|| =' Std(Hnorm(q)) -say '-q =' Hlst2Form(Hneg(q)) -say 'q* =' Hlst2Form(Hconj(q)) -say 'q+r =' Hlst2Form(Hadd(q,r)) -say 'r+q =' Hlst2Form(Hadd(r,q)) -say 'q1+q2 =' Hlst2Form(Hadd(q1,q2)) -say 'q2+q1 =' Hlst2Form(Hadd(q2,q1)) -say 'q*r =' Hlst2Form(Hmul(q,r)) -say 'r*q =' Hlst2Form(Hmul(r,q)) -say 'q1*q2 =' Hlst2Form(Hmul(q1,q2)) -say 'q2*q1 =' Hlst2Form(Hmul(q2,q1)) +say 'i*i =' Lst2FormH(SquareH(i)) +say 'j*j =' Lst2FormH(SquareH(j)) +say 'k*k =' Lst2FormH(SquareH(k)) +say 'i*j*k =' Lst2FormH(MulH(i,j,k)) +say '||q|| =' Std(NormH(q)) +say '-q =' Lst2FormH(NegH(q)) +say 'q* =' Lst2FormH(ConjH(q)) +say 'q+r =' Lst2FormH(AddH(q,r)) +say 'r+q =' Lst2FormH(AddH(r,q)) +say 'q1+q2 =' Lst2FormH(AddH(q1,q2)) +say 'q2+q1 =' Lst2FormH(AddH(q2,q1)) +say 'q*r =' Lst2FormH(MulH(q,r)) +say 'r*q =' Lst2FormH(MulH(r,q)) +say 'q1*q2 =' Lst2FormH(MulH(q1,q2)) 'does not' +say 'q2*q1 =' Lst2FormH(MulH(q2,q1)) 'commute!' say say 'BONUS' -say 'q/r =' Hlst2Form(Hdiv(q,r)) -say '1/q =' Hlst2Form(Hinv(q)) +say '1/q =' Lst2FormH(InvH(q)) +say 'q1/q2 =' Lst2FormH(DivLeftH(q1,q2)) 'left division' +say 'q1/q2 =' Lst2FormH(DivRightH(q1,q2)) 'right division' exit -include Quaternion -include Functions -include Abend +include Math diff --git a/Task/Queue-Definition/ALGOL-68/queue-definition.alg b/Task/Queue-Definition/ALGOL-68/queue-definition-1.alg similarity index 100% rename from Task/Queue-Definition/ALGOL-68/queue-definition.alg rename to Task/Queue-Definition/ALGOL-68/queue-definition-1.alg diff --git a/Task/Queue-Definition/ALGOL-68/queue-definition-2.alg b/Task/Queue-Definition/ALGOL-68/queue-definition-2.alg new file mode 100644 index 0000000000..343dc52a8e --- /dev/null +++ b/Task/Queue-Definition/ALGOL-68/queue-definition-2.alg @@ -0,0 +1,7 @@ + MODE OBJLINK = STRUCT( + REF OBJLINK next, + REF OBJLINK prev, + OBJVALUE value # ... etc. required # + ); + PROC obj link new = REF OBJLINK: HEAP OBJLINK; + PROC obj link free = (REF OBJLINK free)VOID: SKIP diff --git a/Task/Quickselect-algorithm/YAMLScript/quickselect-algorithm.ys b/Task/Quickselect-algorithm/YAMLScript/quickselect-algorithm.ys new file mode 100644 index 0000000000..b2d6c26b17 --- /dev/null +++ b/Task/Quickselect-algorithm/YAMLScript/quickselect-algorithm.ys @@ -0,0 +1,25 @@ +!YS-v0 + +v =: +[9 8 7 6 5 0 1 2 3 4] + +defn main(): + say: + map \(quickselect v _): + v.#:range + +defn quickselect(a k): + loop arr a:V, current-k k: + pivot-idx =: arr.#:rand-int + pivot =: arr.$pivot-idx + remaining =: + concat subvec(arr 0 pivot-idx): + subvec(arr pivot-idx.++) + left =: remaining.filter(\(_ < pivot)) + right =: remaining.filter(\(_ >= pivot)) + left-count =: left.# + cond: + current-k == left-count: pivot + current-k < left-count: + recur: left:V current-k + else: + recur right:V: (current-k - left-count).-- diff --git a/Task/Quine/Extended-Color-BASIC/quine.basic b/Task/Quine/Extended-Color-BASIC/quine.basic new file mode 100644 index 0000000000..1b05437302 --- /dev/null +++ b/Task/Quine/Extended-Color-BASIC/quine.basic @@ -0,0 +1 @@ +10 LIST diff --git a/Task/Quine/REBOL/quine-1.rebol b/Task/Quine/REBOL/quine-1.rebol new file mode 100644 index 0000000000..29ab92349a --- /dev/null +++ b/Task/Quine/REBOL/quine-1.rebol @@ -0,0 +1 @@ +Rebol [] q: [print ["Rebol [] q:" mold q "do q"]] do q diff --git a/Task/Quine/REBOL/quine-2.rebol b/Task/Quine/REBOL/quine-2.rebol new file mode 100644 index 0000000000..53e06495b6 --- /dev/null +++ b/Task/Quine/REBOL/quine-2.rebol @@ -0,0 +1,14 @@ +;; A Rebol quine - a program that outputs its own source code +;; This demonstrates self-referential code and metaprogramming concepts + +Rebol [] ;; Standard Rebol header (minimal version) + +q: [ ;; Define q as a block containing the program logic + print [ ;; Print function to output the result + "Rebol [] q:" ;; First part: literal string for the header and variable declaration + mold q ;; Second part: convert the block q back to its source representation + "do q" ;; Third part: literal string for the execution command + ] +] + +do q ;; Execute the block q, which prints the entire program diff --git a/Task/Quine/REBOL/quine.rebol b/Task/Quine/REBOL/quine.rebol deleted file mode 100644 index 8bb89956fa..0000000000 --- a/Task/Quine/REBOL/quine.rebol +++ /dev/null @@ -1 +0,0 @@ -rebol [] q: [print ["rebol [] q:" mold q "do q"]] do q diff --git a/Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-1.pro b/Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-1.pro new file mode 100644 index 0000000000..9a273f4501 --- /dev/null +++ b/Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-1.pro @@ -0,0 +1,16 @@ +generate_stat(Stat) :- + length(DiceRolls, 4), + maplist(random_between(1, 6), DiceRolls), + sum_list(DiceRolls, Sum), + min_list(DiceRolls, Min), + Stat is Sum - Min. + +generate_stats(Stats) :- + once((repeat, + length(Stats, 6), + maplist(generate_stat, Stats), + sum_list(Stats, Total), + Total >= 75, + aggregate_all(count, ( member(Stat, Stats), Stat > 15 ), Count), + Count >= 2 + )). diff --git a/Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-2.pro b/Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-2.pro new file mode 100644 index 0000000000..7444b41352 --- /dev/null +++ b/Task/RPG-attributes-generator/Prolog/rpg-attributes-generator-2.pro @@ -0,0 +1,8 @@ +?- generate_stats(Stats). +Stats = [15, 13, 12, 16, 17, 15]. + +?- generate_stats(Stats). +Stats = [16, 9, 15, 16, 10, 10]. + +?- generate_stats(Stats). +Stats = [14, 15, 16, 16, 6, 11]. diff --git a/Task/Ramanujan-primes-twins/Rust/ramanujan-primes-twins.rs b/Task/Ramanujan-primes-twins/Rust/ramanujan-primes-twins.rs new file mode 100644 index 0000000000..00716f7937 --- /dev/null +++ b/Task/Ramanujan-primes-twins/Rust/ramanujan-primes-twins.rs @@ -0,0 +1,121 @@ +fn ramanujan_maximum(number: i32) -> i32 { + (4.0 * number as f64 * (4.0 * number as f64).ln()).ceil() as i32 +} + +fn initialise_prime_pi(limit: i32) -> Vec { + let mut result = vec![1; limit as usize]; + result[0] = 0; + result[1] = 0; + + // Mark even numbers as composite + for i in (4..limit).step_by(2) { + result[i as usize] = 0; + } + + // Sieve of Eratosthenes for odd numbers + let mut p = 3; + let mut square = 9; + while square < limit { + if result[p as usize] != 0 { + let mut q = square; + while q < limit { + result[q as usize] = 0; + q += p << 1; + } + } + square += (p + 1) << 2; + p += 2; + } + + // Convert to cumulative sum (prime counting function) + for i in 1..result.len() { + result[i] += result[i - 1]; + } + + result +} + +fn ramanujan_prime(prime_pi: &[i32], number: i32) -> i32 { + let mut maximum = ramanujan_maximum(number); + if (maximum & 1) == 1 { + maximum -= 1; + } + + let mut index = maximum; + while prime_pi[index as usize] - prime_pi[(index / 2) as usize] >= number { + index -= 1; + } + index + 1 +} + +fn list_primes_less_than(limit: i32) -> Vec { + let mut composite = vec![false; limit as usize]; + let mut n = 3; + let mut n_squared = 9; + + while n_squared <= limit { + if !composite[n as usize] { + let mut k = n_squared; + while k < limit { + composite[k as usize] = true; + k += 2 * n; + } + } + n_squared += (n + 1) << 2; + n += 2; + } + + let mut result = Vec::new(); + result.push(2); + for i in (3..limit).step_by(2) { + if !composite[i as usize] { + result.push(i); + } + } + + result +} + +fn main() { + const LIMIT: i32 = 1_000_000; + let prime_pi = initialise_prime_pi(ramanujan_maximum(LIMIT) + 1); + let millionth_ramanujan_prime = ramanujan_prime(&prime_pi, LIMIT); + println!("The 1,000,000th Ramanujan prime is {}", millionth_ramanujan_prime); + + let primes = list_primes_less_than(millionth_ramanujan_prime); + let mut ramanujan_prime_indexes: Vec = primes + .iter() + .map(|&p| prime_pi[p as usize] - prime_pi[(p / 2) as usize]) + .collect(); + + // Filter ramanujan prime indexes to keep only strictly decreasing values + let mut lower_limit = ramanujan_prime_indexes[ramanujan_prime_indexes.len() - 1]; + for i in (0..ramanujan_prime_indexes.len() - 1).rev() { + if ramanujan_prime_indexes[i] < lower_limit { + lower_limit = ramanujan_prime_indexes[i]; + } else { + ramanujan_prime_indexes[i] = 0; + } + } + + // Collect the actual Ramanujan primes + let ramanujan_primes: Vec = primes + .iter() + .enumerate() + .filter_map(|(i, &prime)| { + if ramanujan_prime_indexes[i] != 0 { + Some(prime) + } else { + None + } + }) + .collect(); + + // Count twin primes + let twins_count = ramanujan_primes + .windows(2) + .filter(|pair| pair[0] + 2 == pair[1]) + .count(); + + println!("There are {} twins in the first {} Ramanujan primes.", twins_count, LIMIT); +} diff --git a/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx b/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx index 7639f2025b..7bd38feb44 100644 --- a/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx +++ b/Task/Ramanujans-constant/REXX/ramanujans-constant.rexx @@ -1,6 +1,7 @@ +-- 28 Jul 2025 include Settings -say 'RAMANUJAN''S CONSTANT - 6 Mar 2025' +say 'RAMANUJAN''S CONSTANT' say version say call Formula @@ -28,6 +29,4 @@ end say Format(Time('e'),,3) 'seconds' return -include Constants -include Functions -include Abend +include Math diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/Pascal-P/ramer-douglas-peucker-line-simplification.pas b/Task/Ramer-Douglas-Peucker-line-simplification/Pascal-P/ramer-douglas-peucker-line-simplification.pas new file mode 100644 index 0000000000..b481aeeb56 --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/Pascal-P/ramer-douglas-peucker-line-simplification.pas @@ -0,0 +1,94 @@ +program rdpalgor (output); +(* Ramer-Douglas-Peucker line simplification *) +const + len = 10; + +type + tpnt = record + x, y: real; + end; + tpnts = array [0 .. len] of tpnt; + +var + pntsin, pntsout: tpnts; + n: integer; + + procedure writepnts(pnts: tpnts; n: integer); + var + i: integer; + begin + write('(', pnts[0].x: 8, ', ', pnts[0].y: 8, ')'); + for i := 1 to n - 1 do + write(' (', pnts[i].x: 8, ', ', pnts[i].y: 8, ')'); + writeln; + end; + + (* Returns the distance from point P to the line between P1 and P2 *) + function perpdist(p, p1, p2: tpnt): real; + var + dx, dy, d: real; + begin + dx := p2.x - p1.x; + dy := p2.y - p1.y; + d := sqrt(dx * dx + dy * dy); + perpdist := abs(p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1.x) / d; + end; + + (* Simplify an array of points using the Ramer-Douglas-Peucker algorithm. *) + (* Returns the number of output points. *) + function rdp(src: tpnts; srcfrom, srclen: integer; eps: real; + var dest: tpnts; destfrom, destlen: integer): integer; + var + dist, maxdist : real; + n1, n2, i, maxdisti, srcto: integer; + src1len, src2len, src2from: integer; + begin + maxdist := 0.0; + maxdisti := srcfrom; + srcto := srcfrom + srclen - 1; + for i := srcfrom + 1 to srcto - 1 do + begin + dist := perpdist(src[i], src[srcfrom], src[srcto]); + if dist > maxdist then + begin + maxdist := dist; + maxdisti := i + end; + end; + src2from := maxdisti; + src1len := maxdisti - srcfrom + 1; + src2len := srclen - src1len + 1; + if maxdist > eps then + begin + n1 := rdp(src, srcfrom, src1len, eps, dest, destfrom, destlen); + if destlen >= n1 - 1 then + n2 := rdp(src, src2from, src2len, eps, dest, destfrom + n1 - 1, destlen - n1 + 1) + else + n2 := rdp(src, src2from, src2len, eps, dest, destfrom, 0); + rdp := n1 + n2 - 1; + end + else + begin + if destlen > 1 then + begin + dest[destfrom] := src[srcfrom]; + dest[destfrom + 1] := src[srcto]; + end; + rdp := 2; + end; + end; + +begin + pntsin[0].x := 0.0; pntsin[0].y := 0.0; + pntsin[1].x := 1.0; pntsin[1].y := 0.1; + pntsin[2].x := 2.0; pntsin[2].y := -0.1; + pntsin[3].x := 3.0; pntsin[3].y := 5.0; + pntsin[4].x := 4.0; pntsin[4].y := 6.0; + pntsin[5].x := 5.0; pntsin[5].y := 7.0; + pntsin[6].x := 6.0; pntsin[6].y := 8.1; + pntsin[7].x := 7.0; pntsin[7].y := 9.0; + pntsin[8].x := 8.0; pntsin[8].y := 9.0; + pntsin[9].x := 9.0; pntsin[9].y := 9.0; + n := rdp(pntsin, 0, len, 1.0, pntsout, 0, len); + writepnts(pntsout, n); +end. diff --git a/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx b/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx index b0e65ac572..f913b8880b 100644 --- a/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx +++ b/Task/Random-number-generator-device-/REXX/random-number-generator-device-.rexx @@ -1,4 +1,4 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings numeric digits 12 @@ -24,7 +24,7 @@ say return Examples: -procedure expose glob. +procedure expose Memo. say 'Randu() = ' Right(Randu(),14) 'Real, uniform distributed over (0,1)' say 'Randu(100) = ' Right(Randu(100),14) 'Integer, between 0 and 100' say 'Randu(-10,10) = ' Right(Randu(-10,10),14) 'Integer, between -10 and 10' @@ -32,7 +32,4 @@ say 'Randn() = ' Right(Randn(),14) 'Real, normal distributed, average 0 a say return -include Functions -include Constants -include Helper -include Abend +include Math diff --git a/Task/Random-numbers/DuckDB/random-numbers.duckdb b/Task/Random-numbers/DuckDB/random-numbers.duckdb new file mode 100644 index 0000000000..d26ebde75c --- /dev/null +++ b/Task/Random-numbers/DuckDB/random-numbers.duckdb @@ -0,0 +1,14 @@ +# The Box-Muller method +create or replace function rnv(mean, sd, u, v) as + (select ( sqrt(-2 * ln(u)) * cos(2 * pi() * v) * sd) + mean); + +create or replace table t as + (with rows as (select random() as u, random() as v from unnest(range(0,1000))) + select rnv(0, 0.5, u, v) as rnv from rows); + +from t limit 5; + +select avg(rnv) as average, + stddev_samp(rnv) as 'sample stddev', + stddev_pop(rnv) as 'population stddev' +from t; diff --git a/Task/Random-numbers/REXX/random-numbers.rexx b/Task/Random-numbers/REXX/random-numbers.rexx index cfd8734f63..08f943d031 100644 --- a/Task/Random-numbers/REXX/random-numbers.rexx +++ b/Task/Random-numbers/REXX/random-numbers.rexx @@ -1,4 +1,4 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings say 'RANDOM NUMBERS' @@ -19,53 +19,53 @@ call Timer exit GetUniform: -procedure expose glob. work. +procedure expose Memo. Work. arg xx say 'Get' xx 'uniform distributed Random numbers...' -work. = 0 +Work. = 0 do n = 1 to xx - work.n = Randu() + Work.n = Randu() end -work.0 = xx +Work.0 = xx say 'Done' say return GetNormal: -procedure expose glob. work. +procedure expose Memo. Work. arg xx say 'Get' xx 'normal(1,1/2) distributed Random numbers...' -work. = 0 +Work. = 0 do n = 1 to xx - work.n = Randn(1,0.5) + Work.n = Randn(1,0.5) end -work.0 = xx +Work.0 = xx say 'Done' say return ShowFirst: -procedure expose work. +procedure expose Work. say 'First 5 items...' do i = 1 to 5 - call CharOut ,work.i/1' ' + call CharOut ,Work.i/1' ' end say; say return ShowStats: -procedure expose work. -say 'Statistics for' work.0 'items...' +procedure expose Memo. Work. +say 'Statistics for' Work.0 'items...' sum = 0 -do n = 1 to work.0 - sum = sum+work.n +do n = 1 to Work.0 + sum = sum+Work.n end -avg = sum/work.0 +avg = sum/Work.0 sum = 0 -do n = 1 to work.0 - sum = sum+(work.n-avg)**2 +do n = 1 to Work.0 + sum = sum+(Work.n-avg)**2 end -varia = sum/work.0; stdev = SqRt(varia)/1 +varia = sum/Work.0; stdev = SqRt(varia)/1 say 'Average ' Std(avg) say 'Deviation' Std(stdev) say 'Variance ' Std(varia) @@ -73,7 +73,7 @@ say return ShowExact: -procedure expose work. +procedure expose Memo. say 'Exact statistics for infinite items...' say 'Average ' 1/2 '(1/2)' say 'Deviation' Std(SqRt(1/12)) '(SqRt(1/12))' @@ -81,7 +81,4 @@ say 'Variance ' 1/12 '(1/12)' say return -include Functions -include Constants -include Helper -include Abend +include Math diff --git a/Task/Range-expansion/DuckDB/range-expansion.duckdb b/Task/Range-expansion/DuckDB/range-expansion.duckdb new file mode 100644 index 0000000000..e769dc33f7 --- /dev/null +++ b/Task/Range-expansion/DuckDB/range-expansion.duckdb @@ -0,0 +1,10 @@ +create or replace function range_expansion(s) as ( + regexp_extract_all(s, '[^,]+') + .list_transform( x -> + regexp_extract(x, '(-?[0-9]+)-(-?[0-9]+)|(.*)', ['a', 'b', 'c']) ) + .list_transform( x -> if (x.a = '', [x.c::BIGINT], + range( x.a::INT, x.b::INT + 1) ) ) + .flatten() +); + +select range_expansion( '-6,-3--1,3-5,7-11,14,15,17-20') as range; diff --git a/Task/Range-extraction/DuckDB/range-extraction.duckdb b/Task/Range-extraction/DuckDB/range-extraction.duckdb new file mode 100644 index 0000000000..ce820ccfce --- /dev/null +++ b/Task/Range-extraction/DuckDB/range-extraction.duckdb @@ -0,0 +1,43 @@ +# pretty-print the list returned by list_extract_range() +# being mindful of the 'at least two' rule: +create or replace function list_range_pp(state) as ( + list_transform(state, + x -> if( length(x)=2, + if (x[1] = x[2]::HUGEINT - 1, + format('{},{}', x[1], x[2]), + format('{}-{}', x[1], x[2])), + format('{}', x[1]) ) ) + .array_to_string(',') +); + +create or replace function list_extract_range(lst) as table ( + with recursive cte as ( + -- `state` is a list of lists in which [n] represents an integer and [start, end] a range + select 1 as ix, + [lst[0:0][0:0]][0:0] as state -- i.e. [] of the appropriate type + union all + select ix+1 as ix, + if (length(state) = 0, + [[ lst[ix] ]], + if (length(state[-1]) = 2, + if (state[-1][2] + 1 = lst[ix], + state[0:-2] || [[ state[-1][1], lst[ix]]], + state || [[ lst[ix]] ]), + if ( state[-1][1] + 1 = lst[ix], + state[0:-2] || [[ state[-1][1], lst[ix]]], + state || [[ lst[ix] ]] ) ) ) as state + from cte + where ix <= length(lst)) + select last(state order by ix).list_range_pp() as range + from cte +); + +### Examples +from list_extract_range( [ + 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39 + ]); + +from list_extract_range( [1.0, 2.0, 3.0, 10.0, 11.0] ); diff --git a/Task/Read-a-file-character-by-character-UTF8/Ada/read-a-file-character-by-character-utf8.ada b/Task/Read-a-file-character-by-character-UTF8/Ada/read-a-file-character-by-character-utf8.ada new file mode 100644 index 0000000000..b517e1000c --- /dev/null +++ b/Task/Read-a-file-character-by-character-UTF8/Ada/read-a-file-character-by-character-utf8.ada @@ -0,0 +1,21 @@ +with Ada.Wide_Wide_Text_IO; + +use Ada.Wide_Wide_Text_IO; + +procedure Read_UTF8 is + procedure Read (Filename : String) is + File : File_Type; + C : Wide_Wide_Character; + begin + Open (File, In_File, Filename); + Set_Input (File); + while not End_Of_File loop + Get (C); + Put (C); + end loop; + Close (File); + end Read; + +begin + Read ("input.txt"); +end Read_UTF8; diff --git a/Task/Read-a-file-line-by-line/DuckDB/read-a-file-line-by-line.duckdb b/Task/Read-a-file-line-by-line/DuckDB/read-a-file-line-by-line.duckdb new file mode 100644 index 0000000000..fca28f6ec3 --- /dev/null +++ b/Task/Read-a-file-line-by-line/DuckDB/read-a-file-line-by-line.duckdb @@ -0,0 +1,3 @@ +select count(*) from read_csv('unixdict.txt', + header=false, sep='', columns={'line': VARCHAR}, escape='', + null_padding=true); diff --git a/Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-1.pluto b/Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-1.pluto new file mode 100644 index 0000000000..4798163d1f --- /dev/null +++ b/Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-1.pluto @@ -0,0 +1,8 @@ +filename = "input.txt" +fp = io.open( filename, "r" ) + +for line in fp:lines() do + print( line ) +end + +fp:close() diff --git a/Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-2.pluto b/Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-2.pluto new file mode 100644 index 0000000000..68dc9a3888 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Pluto/read-a-file-line-by-line-2.pluto @@ -0,0 +1,3 @@ +for line in io.lines("input.txt") do + print(line) +end diff --git a/Task/Read-a-specific-line-from-a-file/REBOL/read-a-specific-line-from-a-file.rebol b/Task/Read-a-specific-line-from-a-file/REBOL/read-a-specific-line-from-a-file.rebol index 22915a7820..28ab83f6fb 100644 --- a/Task/Read-a-specific-line-from-a-file/REBOL/read-a-specific-line-from-a-file.rebol +++ b/Task/Read-a-specific-line-from-a-file/REBOL/read-a-specific-line-from-a-file.rebol @@ -1,2 +1,2 @@ -x: pick read/lines request-file/only 7 -either x [print x] [print "No seventh line"] +line: pick read/lines %file.txt 7 +print any [line "No seventh line"] diff --git a/Task/Read-entire-file/ArkScript/read-entire-file.ark b/Task/Read-entire-file/ArkScript/read-entire-file.ark new file mode 100644 index 0000000000..e06189aaab --- /dev/null +++ b/Task/Read-entire-file/ArkScript/read-entire-file.ark @@ -0,0 +1 @@ +(let content (io:readFile "input.txt")) diff --git a/Task/Real-constants-and-functions/Maxima/real-constants-and-functions.maxima b/Task/Real-constants-and-functions/Maxima/real-constants-and-functions.maxima new file mode 100644 index 0000000000..68fb0bba48 --- /dev/null +++ b/Task/Real-constants-and-functions/Maxima/real-constants-and-functions.maxima @@ -0,0 +1,10 @@ +%e$ /* e */ +%pi$ /* pi */ +sqrt(x)$ /* square root */ +log(x)$ /* natural logarithm */ +/* logarithms for all other bases are not built-in and have to be defined in terms of log(x) */ +exp(x)$ /* exponential */ +abs(x)$ /* magnitude */ +floor(x)$ /* floor */ +ceiling(x)$ /* ceiling */ +x^y$ /* power */ diff --git a/Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav b/Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav new file mode 100644 index 0000000000..db0c7d7810 --- /dev/null +++ b/Task/Real-constants-and-functions/TAV/real-constants-and-functions.tav @@ -0,0 +1,13 @@ + print 'pi =', #Pi + print 'e =', #E + x =: 12.3456 + y =: 1.11 + print 'x =', x, 'y =', y + print 'sqrt(x) =', math sqrt x + print 'log(x) =', math log x \ base e + print 'log10(x) =', math lg x \ base 10 + print 'exp(x) =', math exp x + print 'abs(x) =', x.abs + print 'floor(x) =', x.floor + print 'ceil(x) =', x.ceil + print 'x ^ y =', x ^ y diff --git a/Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb b/Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb new file mode 100644 index 0000000000..f97160413c --- /dev/null +++ b/Task/Reflection-List-methods/DuckDB/reflection-list-methods.duckdb @@ -0,0 +1,14 @@ +create or replace function methods( type ) as table ( + select function_name, parameter_types + from duckdb_functions() + where upper(parameter_types[1]) = upper(type) + order by function_name +); + +create or replace function functions_with_signature( ds ) as table ( + with uc as (select list_transform(ds, x->upper(x)) as uc) + select function_name + from duckdb_functions(), uc + where list_transform(parameter_types, x->upper(x)) = uc + order by function_name +); diff --git a/Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb b/Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb new file mode 100644 index 0000000000..729b194281 --- /dev/null +++ b/Task/Reflection-List-properties/DuckDB/reflection-list-properties.duckdb @@ -0,0 +1 @@ +select column_name from (describe TABLE); diff --git a/Task/Regular-expressions/Maxima/regular-expressions.maxima b/Task/Regular-expressions/Maxima/regular-expressions.maxima new file mode 100644 index 0000000000..2c980b591c --- /dev/null +++ b/Task/Regular-expressions/Maxima/regular-expressions.maxima @@ -0,0 +1,5 @@ +load("sregex")$ +regex_match("\\W[A-Z]", "Hello World!"); /* returns matched substring */ +regex_match("\\W[A-Z]", "Hello world!"); /* returns false if no match */ +regex_subst_first("4", "[Aa]", "Abracadabra!"); /* replaces first match */ +regex_subst("4", "[Aa]", "Abracadabra!"); /* replaces all matches */ diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb new file mode 100644 index 0000000000..7ca77f8f20 --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-1.duckdb @@ -0,0 +1 @@ +select distinct(*) from unnest( [3,9,1,10,3,7,6,5,2,7,4,7,4,2,2,2,2,8,2,10,4,9,2,4,9,3,4,3,4,7] ); diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb new file mode 100644 index 0000000000..6d0ef3ff67 --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-2.duckdb @@ -0,0 +1 @@ +select array_agg(unnest) as distinct from (select distinct(*) from unnest( [3,9,1,10,3,7,6,5,2,7,4,7,4,2,2,2,2,8,2,10,4,9,2,4,9,3,4,3,4,7] )); diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb new file mode 100644 index 0000000000..2e6213bb6d --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-3.duckdb @@ -0,0 +1,6 @@ +CREATE OR REPLACE MACRO firsts(l) as ( + WITH + t as (SELECT unnest(l) as x, generate_subscripts(l, 1) as index), + s as (SELECT x, min(index) as index FROM t GROUP BY x) + SELECT list(x ORDER BY index) + FROM s ) ; diff --git a/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb new file mode 100644 index 0000000000..100d913138 --- /dev/null +++ b/Task/Remove-duplicate-elements/DuckDB/remove-duplicate-elements-4.duckdb @@ -0,0 +1 @@ +select firsts( [3,9,1,10,3,7,6,5,2,7,4,7,4,2,2,2,2,8,2,10,4,9,2,4,9,3,4,3,4,7]) as firsts; diff --git a/Task/Rename-a-file/Maxima/rename-a-file.maxima b/Task/Rename-a-file/Maxima/rename-a-file.maxima new file mode 100644 index 0000000000..001ce224f8 --- /dev/null +++ b/Task/Rename-a-file/Maxima/rename-a-file.maxima @@ -0,0 +1,5 @@ +load("operatingsystem")$ +rename_file("input.txt", "output.txt")$ +rename_file("/input.txt", "/output.txt")$ +rename_file("docs", "mydocs")$ +rename_file("/docs", "/mydocs")$ diff --git a/Task/Rename-a-file/Pluto/rename-a-file.pluto b/Task/Rename-a-file/Pluto/rename-a-file.pluto new file mode 100644 index 0000000000..dfc95df6ba --- /dev/null +++ b/Task/Rename-a-file/Pluto/rename-a-file.pluto @@ -0,0 +1,5 @@ +os.rename("input.txt", "output.txt") +os.rename("/input.txt", "/output.txt") + +os.rename("docs", "mydocs") +os.rename("/docs", "/mydocs") diff --git a/Task/Rename-a-file/R/rename-a-file.r b/Task/Rename-a-file/R/rename-a-file.r new file mode 100644 index 0000000000..077c4db78e --- /dev/null +++ b/Task/Rename-a-file/R/rename-a-file.r @@ -0,0 +1,4 @@ +file.rename("input.txt","output.txt") +file.rename("~/input.txt","~/output.txt") +file.rename("docs","mydocs") +file.rename("~/docs","~/mydocs") diff --git a/Task/Rep-string/DuckDB/rep-string.duckdb b/Task/Rep-string/DuckDB/rep-string.duckdb new file mode 100644 index 0000000000..fde7e300cf --- /dev/null +++ b/Task/Rep-string/DuckDB/rep-string.duckdb @@ -0,0 +1,36 @@ +create or replace function repString(s) as ( + if (length(s) < 2, null, + (with recursive size_t as (select length(s) as size), + cte as + (select ((size % 2) + (size // 2)) as len, '' as t, false as found + from size_t + union all + select len-1 as len, + s[1:len] as t, + s == (repeat(s[1:len], (size // len)) + || coalesce(t[1:(size % len)], '')) + as found + from cte, size_t + where len > 0 and found = false + ) + select first(t) + from cte + where found + )) +); + +select s, repString(s) +from unnest( + [ + '1001110011', + '1110111011', + '0010010010', + '1010101010', + '1111111111', + '0100101101', + '0100100', + '101', + '11', + '00', + '1' + ]) _(s); diff --git a/Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb b/Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb new file mode 100644 index 0000000000..86a8b536e6 --- /dev/null +++ b/Task/Repeat-a-string/DuckDB/repeat-a-string-1.duckdb @@ -0,0 +1,2 @@ +select repeat('abc', 5) as five, + (repeat('abc', 0) = '') as zero; diff --git a/Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb b/Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb new file mode 100644 index 0000000000..5691e3508b --- /dev/null +++ b/Task/Repeat-a-string/DuckDB/repeat-a-string-2.duckdb @@ -0,0 +1 @@ +select string_agg('a',' ') as a from range(0,5); diff --git a/Task/Repeat-a-string/Pluto/repeat-a-string.pluto b/Task/Repeat-a-string/Pluto/repeat-a-string.pluto new file mode 100644 index 0000000000..66a4abe738 --- /dev/null +++ b/Task/Repeat-a-string/Pluto/repeat-a-string.pluto @@ -0,0 +1 @@ +print('ha':rep(5)) diff --git a/Task/Repunit-primes/R/repunit-primes.r b/Task/Repunit-primes/R/repunit-primes.r new file mode 100644 index 0000000000..89ba6164db --- /dev/null +++ b/Task/Repunit-primes/R/repunit-primes.r @@ -0,0 +1,8 @@ +library(gmp) + +nth_repunit <- function(n, base) (as.bigz(base)^n-1)/(base-1) +repunit_primes <- function(base) which(isprime(nth_repunit(1:1000, base))!=0) +primes_list <- lapply(2:16, repunit_primes) +names(primes_list) <- sapply(2:16, function(k) paste("Base", k)) +for(i in 1:15) if(length(primes_list[[i]])==0) primes_list[[i]] <- "None" +print(primes_list, quote=FALSE) diff --git a/Task/Retrieve-and-search-chat-history/R/retrieve-and-search-chat-history.r b/Task/Retrieve-and-search-chat-history/R/retrieve-and-search-chat-history.r new file mode 100644 index 0000000000..2485cd0915 --- /dev/null +++ b/Task/Retrieve-and-search-chat-history/R/retrieve-and-search-chat-history.r @@ -0,0 +1,19 @@ +#Retrieving +url_day <- function(n) sprintf("http://tclers.tk/conferences/tcl/%s.tcl", Sys.Date()-n) +retrieve <- function(n) readLines(con=url(url_day(n))) +#Adding an extra day to deal with time zone issue +logs <- lapply(-1:9, retrieve) +names(logs) <- sapply(-1:9, url_day) +if("URL Not Found" %in% logs[[1]]) logs[[1]] <- NULL + +#Searching +results <- lapply(seq_along(logs), function(n) grep(s, logs[[n]], fixed=TRUE, value=TRUE)) +names(results) <- names(logs) + +for(i in seq_along(results)){ + if(length(results[[i]])==0){ + results[[i]] <- "No results found" + } +} + +print(results, quote=FALSE) diff --git a/Task/Return-multiple-values/DuckDB/return-multiple-values-1.duckdb b/Task/Return-multiple-values/DuckDB/return-multiple-values-1.duckdb new file mode 100644 index 0000000000..9a82b8ae27 --- /dev/null +++ b/Task/Return-multiple-values/DuckDB/return-multiple-values-1.duckdb @@ -0,0 +1,4 @@ +# If i is a non-zero number, the first item of the returned tuple will be of type HUGEINT. +create or replace function divmod(n, i) as ( + (((n - mod(n, i)) / i)::HUGEINT, mod(n,i) ) +); diff --git a/Task/Return-multiple-values/DuckDB/return-multiple-values-2.duckdb b/Task/Return-multiple-values/DuckDB/return-multiple-values-2.duckdb new file mode 100644 index 0000000000..907f254fd6 --- /dev/null +++ b/Task/Return-multiple-values/DuckDB/return-multiple-values-2.duckdb @@ -0,0 +1,9 @@ +create or replace table test(n HUGEINT, i INTEGER); + +insert into test values + (7,3), + (1,0), + (123456789123456789, 23); + +select n, i, divmod(n, i) as divmod, (divmod[1] * i + divmod[2]) = n +from test; diff --git a/Task/Reverse-a-string/ArkScript/reverse-a-string.ark b/Task/Reverse-a-string/ArkScript/reverse-a-string.ark new file mode 100644 index 0000000000..606f4a9101 --- /dev/null +++ b/Task/Reverse-a-string/ArkScript/reverse-a-string.ark @@ -0,0 +1,3 @@ +(import std.String :reverse) + +(print (reverse "asdf")) diff --git a/Task/Reverse-a-string/DuckDB/reverse-a-string.duckdb b/Task/Reverse-a-string/DuckDB/reverse-a-string.duckdb new file mode 100644 index 0000000000..7b3a2c6280 --- /dev/null +++ b/Task/Reverse-a-string/DuckDB/reverse-a-string.duckdb @@ -0,0 +1,7 @@ +create or replace table t (s varchar, expected varchar); +insert into t values + ('asdf', 'fdsa'), + ('as⃝df̅', 'f̅ds⃝a'); + +select s, expected, reverse(s) as reversed, (expected=reversed) as equal + from t; diff --git a/Task/Reverse-a-string/Nom/reverse-a-string.num b/Task/Reverse-a-string/Nom/reverse-a-string.num new file mode 100644 index 0000000000..06830b5d71 --- /dev/null +++ b/Task/Reverse-a-string/Nom/reverse-a-string.num @@ -0,0 +1 @@ +read; get; put; clear; (eof) { get; print; } diff --git a/Task/Reverse-a-string/Pluto/reverse-a-string.pluto b/Task/Reverse-a-string/Pluto/reverse-a-string.pluto new file mode 100644 index 0000000000..1c3732a91f --- /dev/null +++ b/Task/Reverse-a-string/Pluto/reverse-a-string.pluto @@ -0,0 +1,10 @@ +require "uchar" +require "gchar" + +for {"asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"} as word do + print(uchar.of(word):reverse()) +end + +for {"as⃝df̅", "ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺"} as word do + print(gchar.of(word):reverse()) +end diff --git a/Task/Reverse-a-string/TAV/reverse-a-string.tav b/Task/Reverse-a-string/TAV/reverse-a-string.tav new file mode 100644 index 0000000000..57f02fec68 --- /dev/null +++ b/Task/Reverse-a-string/TAV/reverse-a-string.tav @@ -0,0 +1,3 @@ + str =: 'asdf' + rstr =: str::from -1 step -1 + print str, rstr diff --git a/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas b/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas index d37e9a9155..f40a454f5b 100644 --- a/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas +++ b/Task/Reverse-words-in-a-string/PascalABC.NET/reverse-words-in-a-string.pas @@ -1,3 +1,29 @@ -## -var s:='Hey you, Bub!'; -s.ToWords.Reverse.Print; +begin + var lines := new string[] + ( + '---------- Ice and Fire ------------', + '', + 'fire, in end will world the say Some', + 'ice. in say Some', + 'desire of tasted I''ve what From', + 'fire. favor who those with hold I', + '', + '... elided paragraph last ...', + '', + 'Frost Robert -----------------------' + ); + + foreach var line in lines do + begin + // Разбиваем строку на слова (по пробелам), фильтруем пустые + var words := line.Split(' ').Where(w -> w <> '').ToArray(); + + // Меняем порядок слов на обратный + words := words.Reverse().ToArray(); + + // Собираем обратно в строку через пробел + var reversedLine := String.Join(' ', words); + + Writeln(reversedLine); + end; +end. diff --git a/Task/Reverse-words-in-a-string/Pluto/reverse-words-in-a-string.pluto b/Task/Reverse-words-in-a-string/Pluto/reverse-words-in-a-string.pluto new file mode 100644 index 0000000000..62339693d2 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Pluto/reverse-words-in-a-string.pluto @@ -0,0 +1,16 @@ +local lines = { + "---------- Ice and Fire ------------", + " ", + "fire, in end will world the say Some", + "ice. in say Some ", + "desire of tasted I've what From ", + "fire. favor who those with hold I ", + " ", + "... elided paragraph last ... ", + " ", + "Frost Robert -----------------------" +} + +for lines as line do + print(line:strip(" "):split(" "):reverse():concat(" ")) +end diff --git a/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode-1.pas b/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode-1.pas index d41482fd30..7c3d0eab27 100644 --- a/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode-1.pas +++ b/Task/Roman-numerals-Decode/PascalABC.NET/roman-numerals-decode-1.pas @@ -1,39 +1,20 @@ -function Rim2Arab(S : String) : Integer; -const //римские числа на соответствующие десятичные числа -R : array[1..14] of String[2] = ('M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I',' '); -A : array[1..14] of Integer = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, 0); +function romanDecode(roman: string): integer; begin - var i := 1; + var values := Dict('I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000); Result := 0; - while S.Length > 0 do - begin - while S.IndexOf(R[i]) = 0 do - begin - S := S.Remove(0, R[i].Length); - Result += A[i] - end; - i += 1; - end; + var prev := 0; + for var i := roman.Length downto 1 do + begin + var curr := values[roman[i]]; + if curr < prev + then Result -= curr + else Result += curr; + prev := curr; + end; end; - -const - L = 'IVXLCDM'; begin - var S := 'MDCLXVI';//'roman numeral:'; - Write(S,': '); - var index := 1; - repeat - if L.IndexOf(S[index]) < 0 then - index += 1 - else - begin - var Rim : String := ''; - repeat - Rim += S[index]; - S := S.Remove(index - 1, 1); - until (S.Length < index) or (L.IndexOf(S[index]) < 0); - S := S.Insert(index - 1, Rim2Arab(Rim).ToString); - end; - until index > S.Length; - WriteLn(S); + var romans := |'I', 'III', 'IV', 'VIII', 'XLIX', 'CCII', + 'CDXXXIII', 'MCMXC', 'MMVIII', 'MDCLXVI'|; + foreach var roman in romans do + writeln(roman:8, romanDecode(roman):7); end. diff --git a/Task/Roman-numerals-Encode/Pluto/roman-numerals-encode.pluto b/Task/Roman-numerals-Encode/Pluto/roman-numerals-encode.pluto new file mode 100644 index 0000000000..d9b6de58f8 --- /dev/null +++ b/Task/Roman-numerals-Encode/Pluto/roman-numerals-encode.pluto @@ -0,0 +1,3 @@ +local fmt = require "fmt" + +for {1990, 1666, 2008, 2020, 2025} as n do print(fmt.roman(n)) end diff --git a/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy b/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy index 7c73b64b86..bee95e22c6 100644 --- a/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy +++ b/Task/Roots-of-a-function/EasyLang/roots-of-a-function.easy @@ -15,14 +15,10 @@ proc findroot start stop step . x += step . . -xp = 0 / 0 -yp = 0 proc lineto x y . x = x * 10 + 50 y = y * 10 + 50 - if xp = xp : gline xp yp x y - xp = x - yp = y + glineto x y . proc drawfunc start stop . glinewidth 0.3 @@ -30,6 +26,7 @@ proc drawfunc start stop . gline 50 0 50 100 drawgrid x = start + gpenup while x <= stop lineto x f x x += 0.1 diff --git a/Task/Roots-of-a-quadratic-function/Pluto/roots-of-a-quadratic-function.pluto b/Task/Roots-of-a-quadratic-function/Pluto/roots-of-a-quadratic-function.pluto new file mode 100644 index 0000000000..d3744aefba --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Pluto/roots-of-a-quadratic-function.pluto @@ -0,0 +1,44 @@ +require "complex" + +local function quadratic(a, b, c) + local d = b * b - 4 * a * c + if d == 0 then + -- single root + return {{-b / (2 * a)}, nil} + end + if d > 0 then + -- two real roots + local sr = math.sqrt(d) + d = b < 0 ? sr - b : -sr - b + return {{d / (2 * a), 2 * c / d}, nil} + end + -- two complex roots + local den = 1 / (2 * a) + local t1 = complex.of(-b * den, 0) + local t2 = complex.of(0, math.sqrt(-d)) * den + return {{}, {t1 + t2, t1 - t2}} +end + +local function test(a, b, c) + io.write($"coefficients: {a}, {b}, {c} -> ") + local roots = quadratic(a, b, c) + local r = roots[1] + if #r == 1 then + print($"one real root: {r[1]}") + elseif #r == 2 then + print($"two real roots: {r[1]} and {r[2]}") + else + local i = roots[2] + print($"two complex roots: {i[1]:tostring()} and {i[2]:tostring()}") + end +end + +local coeffs = { + {1, -2, 1}, + {1, 0, 1}, + {1, -10, 1}, + {1, -1000, 1}, + {1, -1e9, 1} +} + +for coeffs as c do test(c[1], c[2], c[3]) end diff --git a/Task/Roots-of-unity/DuckDB/roots-of-unity.duckdb b/Task/Roots-of-unity/DuckDB/roots-of-unity.duckdb new file mode 100644 index 0000000000..a301f16384 --- /dev/null +++ b/Task/Roots-of-unity/DuckDB/roots-of-unity.duckdb @@ -0,0 +1,11 @@ +create or replace function nthroots(n) as table ( + with twopi as (select 2*pi() as twopi), + etc as ( + select ((twopi * i) / n) as angle, cos(angle), sin(angle) + from range(0,n) t(i), twopi + ) + select COLUMNS(* EXCLUDE (angle)) + from etc +); + +from nthroots(10); diff --git a/Task/Roots-of-unity/Pluto/roots-of-unity.pluto b/Task/Roots-of-unity/Pluto/roots-of-unity.pluto new file mode 100644 index 0000000000..85a3e765f3 --- /dev/null +++ b/Task/Roots-of-unity/Pluto/roots-of-unity.pluto @@ -0,0 +1,12 @@ +require "complex" + +local function roots(n) + local r = {} + for i = 1, n do r[i] = complex.polar(1, 2 * math.pi * (i - 1) / n) end + return r +end + +for n = 2, 5 do + print($"{n} roots of 1:") + for roots(n) as r do print(r:format(" % 0.14f", "%0.14f")) end +end diff --git a/Task/Rosetta-Code-Count-examples/Raku/rosetta-code-count-examples.raku b/Task/Rosetta-Code-Count-examples/Raku/rosetta-code-count-examples.raku index 72ab33eafb..3b63207a34 100644 --- a/Task/Rosetta-Code-Count-examples/Raku/rosetta-code-count-examples.raku +++ b/Task/Rosetta-Code-Count-examples/Raku/rosetta-code-count-examples.raku @@ -11,7 +11,7 @@ my %cat = ( 'Draft_Programming_Tasks' => 'Draft' ); -my $client = HTTP::UserAgent.new; +my $client = HTTP::UserAgent.new(:useragent('Rosetta Code Task bot')); $client.timeout = 10; my $url = 'https://rosettacode.org/w'; diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Ring/rosetta-code-find-unimplemented-tasks.ring b/Task/Rosetta-Code-Find-unimplemented-tasks/Ring/rosetta-code-find-unimplemented-tasks.ring index ecba0f6e9b..67c11fbb7f 100644 --- a/Task/Rosetta-Code-Find-unimplemented-tasks/Ring/rosetta-code-find-unimplemented-tasks.ring +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Ring/rosetta-code-find-unimplemented-tasks.ring @@ -49,11 +49,3 @@ func searchtitle(sn) see "" + num + ". " + rosname + nl ok return sn - -func count(cstring,dstring) - sum = 0 - while substr(cstring,dstring) > 0 - sum = sum + 1 - cstring = substr(cstring,substr(cstring,dstring)+len(string(sum))) - end - return sum diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Raku/rosetta-code-rank-languages-by-popularity-1.raku b/Task/Rosetta-Code-Rank-languages-by-popularity/Raku/rosetta-code-rank-languages-by-popularity-1.raku index 8d27b23439..559e4b1c35 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Raku/rosetta-code-rank-languages-by-popularity-1.raku +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Raku/rosetta-code-rank-languages-by-popularity-1.raku @@ -3,7 +3,7 @@ use URI::Escape; use JSON::Fast; use Sort::Naturally; -my $client = HTTP::UserAgent.new; +my $client = HTTP::UserAgent.new(:useragent('Rosetta Code Task bot')); my $url = 'https://rosettacode.org/w'; diff --git a/Task/Rot-13/Crystal/rot-13.cr b/Task/Rot-13/Crystal/rot-13.cr new file mode 100644 index 0000000000..1fee64a08c --- /dev/null +++ b/Task/Rot-13/Crystal/rot-13.cr @@ -0,0 +1,5 @@ +from = ['A'..'Z', 'a'..'z'].flat_map(&.to_a).join +to = ['N'..'Z', 'A'..'M', 'n'..'z', 'a'..'m'].flat_map(&.to_a).join +while line = ARGF.gets + puts line.tr from, to +end diff --git a/Task/Rot-13/Lua/rot-13-1.lua b/Task/Rot-13/Lua/rot-13-1.lua index 2d55a69cac..b58dd54201 100644 --- a/Task/Rot-13/Lua/rot-13-1.lua +++ b/Task/Rot-13/Lua/rot-13-1.lua @@ -3,3 +3,5 @@ function rot13(s) local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" return (s:gsub("%a", function(c) return b:sub(a:find(c)) end)) end + +print(rot13("nowhere ABJURER")) diff --git a/Task/Rot-13/Lua/rot-13-2.lua b/Task/Rot-13/Lua/rot-13-2.lua index 79cd59dcf7..eff6e9239d 100644 --- a/Task/Rot-13/Lua/rot-13-2.lua +++ b/Task/Rot-13/Lua/rot-13-2.lua @@ -1,3 +1,5 @@ function rot13(s) return (s:gsub("%a", function(c) c=c:byte() return string.char(c+(c%32<14 and 13 or -13)) end)) end + +print(rot13("nowhere ABJURER")) diff --git a/Task/Rot-13/Pluto/rot-13.pluto b/Task/Rot-13/Pluto/rot-13.pluto new file mode 100644 index 0000000000..38c8e47174 --- /dev/null +++ b/Task/Rot-13/Pluto/rot-13.pluto @@ -0,0 +1,14 @@ +local function rot13(s) + local bytes = {s:byte(1, #s)} + for i = 1, #bytes do + local c = bytes[i] + if (c >= 65 and c <= 77) or (c >= 97 and c <= 109) then + bytes[i] = c + 13 + elseif (c >= 78 and c <= 90) or (c >= 110 and c <= 122) then + bytes[i] = c - 13 + end + end + return string.char(bytes:unpack()) +end + +print(rot13("nowhere ABJURER")) diff --git a/Task/Rot-13/Rhombus/rot-13.rhombus b/Task/Rot-13/Rhombus/rot-13.rhombus new file mode 100644 index 0000000000..590cf6a5dc --- /dev/null +++ b/Task/Rot-13/Rhombus/rot-13.rhombus @@ -0,0 +1,23 @@ +#lang rhombus/static + +import lib("racket/base.rkt") expose: + #{string->list} as string_to_list + #{list->string} as list_to_string + modulo + +fun rot13_char(char :: Char): + let char_int = char.to_int() + fun rot13_by_case(char_int, a_char :: Char) :: Int : + modulo(char_int - a_char.to_int() + 13, 26) + a_char.to_int() + if char.is_alphabetic(): + | if char.is_lowercase(): + | Char.from_int(rot13_by_case(char_int, Char"a")) + | Char.from_int(rot13_by_case(char_int, Char"A")) + | char + +fun rot13_string(str :: String) :: String : + let chars :: PairList = string_to_list(str) + let str :: MutableString = list_to_string(chars.map(rot13_char)) + str.snapshot() + +rot13_string("Hello, World!") // Output: "Uryyb, Jbeyq!"" diff --git a/Task/Rot-13/S-BASIC/rot-13.basic b/Task/Rot-13/S-BASIC/rot-13.basic index 2285ebf169..f60275b37d 100644 --- a/Task/Rot-13/S-BASIC/rot-13.basic +++ b/Task/Rot-13/S-BASIC/rot-13.basic @@ -21,7 +21,7 @@ rem - exercise the function var plain, encoded = string -plain = "The quick brown fox jumps over the lazy red dog." +plain = "The quick brown fox jumps over the lazy dog." encoded = rot13(plain) print "Plain text: "; plain print "Encoded : "; encoded diff --git a/Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb b/Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb new file mode 100644 index 0000000000..f88b7634f0 --- /dev/null +++ b/Task/Run-length-encoding/DuckDB/run-length-encoding-1.duckdb @@ -0,0 +1,23 @@ +create or replace function run_length_encode(str) as table + (WITH RECURSIVE cte AS ( + SELECT + 1 AS pos, + 1 AS counter, + SUBSTRING(str, 1, 1) AS char, + SUBSTRING(str, 2, 1) AS nextc, + UNION ALL + SELECT + pos + 1 as pos, + CASE + WHEN nextc = char THEN counter + 1 + ELSE 1 + END as counter, + nextc as char, + SUBSTRING(str, 2 + pos, 1) as nextc + FROM cte + WHERE pos < LENGTH(str) + ) + SELECT STRING_AGG( counter || char, '' ORDER BY pos) AS encoded_string + FROM cte + WHERE nextc != char + ); diff --git a/Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb b/Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb new file mode 100644 index 0000000000..15a06b1b33 --- /dev/null +++ b/Task/Run-length-encoding/DuckDB/run-length-encoding-2.duckdb @@ -0,0 +1 @@ +from run_length_encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'); diff --git a/Task/Runge-Kutta-method/Pluto/runge-kutta-method.pluto b/Task/Runge-Kutta-method/Pluto/runge-kutta-method.pluto new file mode 100644 index 0000000000..597b4e14b9 --- /dev/null +++ b/Task/Runge-Kutta-method/Pluto/runge-kutta-method.pluto @@ -0,0 +1,30 @@ +local fmt = require "fmt" + +local function runge_kutta4(t0, tz, dt, y, yd) + local tn = t0 + local yn = y(tn) + local z = (tz - t0) // dt + for i = 0, z do + if i % 10 == 0 then + local exact = y(tn) + local err = yn - exact + fmt.print("%4.1f %10f %10f %9f", tn, yn, exact, err) + end + if i == z then break end + local dy1 = dt * yd(tn, yn) + local dy2 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy1) + local dy3 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy2) + local dy4 = dt * yd(tn + dt, yn + dy3) + yn += (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0 + tn += dt + end +end + +print(" T RK4 Exact Error") +print("---- --------- ---------- ---------") +local function y(t) + local x = t * t + 4.0 + return x * x / 16.0 +end +local yd = |t, yt| -> t * math.sqrt(yt) +runge_kutta4(0, 10, 0.1, y, yd) diff --git a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx index 9d04f0a647..7d3fb38294 100644 --- a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx +++ b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx @@ -1,28 +1,51 @@ -/*REXX program uses the Runge─Kutta method to solve the equation: y'(t) = t² √[y(t)] */ -numeric digits 40; f= digits() % 4 /*use 40 decimal digs, but only show 10*/ -x0= 0; x1= 10; dx= .1 /*define variables: X0 X1 DX */ -n=1 + (x1-x0) / dx -y.=1; do m=1 for n-1; p= m - 1; y.m= RK4(dx, x0 + dx*p, y.p) - end /*m*/ /* [↑] use 4th order Runge─Kutta. */ -w= digits() % 2 /*W: width used for displaying numbers.*/ -say center('X', f, "═") center('Y', w+2, "═") center("relative error", w+8, '═') /*hdr*/ +-- 28 Jul 2025 +include Settings - do i=0 to n-1 by 10; x= (x0 + dx*i) / 1; $= y.i / (x*x/4+1)**2 - 1 - say center(x, f) fmt(y.i) left('', 2 + ($>=0) ) fmt($) - end /*i*/ /*└┴┴┴───◄─────── aligns positive #'s. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -fmt: parse arg z; z= right( format(z, w, f), w); hasE= pos('E', z)>0; has.= pos(., z)>0 - jus= has. & \hasE; T= 'T'; if jus then z= left( strip( strip(z, T, 0), T, .), w) - return translate( right(z, (z>=0) + w + 5*hasE + 2*(jus & (z<0) ) ), 'e', "E") -/*──────────────────────────────────────────────────────────────────────────────────────*/ -RK4: procedure; parse arg dx,x,y; dxH= dx/2; k1= dx * (x ) * sqrt(y ) - k2= dx * (x + dxH) * sqrt(y + k1/2) - k3= dx * (x + dxH) * sqrt(y + k2/2) - k4= dx * (x + dx ) * sqrt(y + k3 ) - return y + (k1 + k2*2 + k3*2 + k4) / 6 -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 - numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g * .5'e'_ % 2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g +say "RUNGE-KUTTA METHOD FOR ODE y'=x*SqRt(y)" +say version +say +numeric digits 9 +call Task 0,10,1/10,1 +numeric digits 16 +call Task 0,10,1/10,1 +numeric digits 9 +call Task 0,10,1/20,1 +numeric digits 16 +call Task 0,10,1/20,1 +call Timer +exit + +Task: +procedure expose Memo. +arg x0,xn,dx,y0 +x=x0; y=y0 +say 'From' x0 'to' xn 'step' dx 'with' Digits() 'digits' +say ' x Calc y True y Abs error Rel error' +call Show x,y +do until x >= xn + dy1=dx*DyDx(x,y) + dy2=dx*DyDx(x+dx/2,y+dy1/2) + dy3=dx*DyDx(x+dx/2,y+dy2/2) + dy4=dx*DyDx(x+dx,y+dy3) + x=x+dx; y=y+(dy1+2*dy2+2*dy3+dy4)/6 + if Integer(x) then + call Show x,y +end +say +return + +DyDx: +arg xx,yy +return xx*SqRt(yy) + +True: +arg xx +return (xx**2+4)**2/16 + +Show: +arg xx,yy +say Format(xx,2,0) Format(yy,3,8) Format(True(xx),3,8), + Left(Std(Abs(yy-True(xx))),10) Left(Std(Abs(yy/True(xx)-1)),10) +return + +include Math diff --git a/Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py b/Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py new file mode 100644 index 0000000000..16ea510fb8 --- /dev/null +++ b/Task/Ruth-Aaron-numbers/Python/ruth-aaron-numbers.py @@ -0,0 +1,104 @@ +from collections import deque +from itertools import count +from itertools import islice +from pprint import pprint +from typing import Iterable +from typing import Iterator +from typing import TypeVar + + +def prime_factors(n: int) -> Iterator[int]: + """Return the prime factors of 'n' in order using a wheel with basis [2, 3, 5]. + + Translation of `primeFactors` from https://rosettacode.org/wiki/Category_talk:Wren-math. + """ + if n < 2: + return + + inc = [4, 2, 4, 2, 4, 6, 2, 6] + + while n % 2 == 0: + yield 2 + n //= 2 + + while n % 3 == 0: + yield 3 + n //= 3 + + while n % 5 == 0: + yield 5 + n //= 5 + + k = 7 + i = 0 + + while k * k <= n: + if n % k == 0: + yield k + n //= k + else: + k += inc[i] + i = (i + 1) % 8 + + if n > 1: + yield n + + +_T = TypeVar("_T") + + +def sliding_window(it: Iterable[_T], n: int) -> Iterator[tuple[_T, ...]]: + it = iter(it) + window = deque(islice(it, n - 1), maxlen=n) + for x in it: + window.append(x) + yield tuple(window) + + +def ruth_aaron_numbers_factors() -> Iterator[int]: + for (i, a), (_, b) in sliding_window( + ((n, sum(prime_factors(n))) for n in count(2)), 2 + ): + if a == b: + yield i + + +def ruth_aaron_numbers_divisors() -> Iterator[int]: + for (i, a), (_, b) in sliding_window( + ((n, sum(set(prime_factors(n)))) for n in count(2)), 2 + ): + if a == b: + yield i + + +def ruth_aaron_triples_factors() -> Iterator[int]: + for (i, a), (_, b), (_, c) in sliding_window( + ((n, sum(prime_factors(n))) for n in count(2)), 3 + ): + if a == b == c: + yield i + + +def ruth_aaron_triples_divisors() -> Iterator[int]: + for (i, a), (_, b), (_, c) in sliding_window( + ((n, sum(set(prime_factors(n)))) for n in count(2)), 3 + ): + if a == b == c: + yield i + + +if __name__ == "__main__": + print("First 30 Ruth-Aaron numbers (factors):") + pprint(list(islice(ruth_aaron_numbers_factors(), 30)), compact=True) + print("") + + print("First 30 Ruth-Aaron numbers (divisors):") + pprint(list(islice(ruth_aaron_numbers_divisors(), 30)), compact=True) + print("") + + print("First Ruth-Aaron triple (factors):") + print(next(ruth_aaron_triples_factors())) + print("") + + print("First Ruth-Aaron triple (divisors):") + print(next(ruth_aaron_triples_divisors())) diff --git a/Task/SEDOLs/Prolog/sedols-1.pro b/Task/SEDOLs/Prolog/sedols-1.pro new file mode 100644 index 0000000000..82aaf1ee0d --- /dev/null +++ b/Task/SEDOLs/Prolog/sedols-1.pro @@ -0,0 +1,40 @@ +:- set_prolog_flag(double_quotes, codes). +:- use_module(library(clpfd)). + +sedol --> + sdigit(S1), sdigit(S2), sdigit(S3), sdigit(S4), sdigit(S5), sdigit(S6), sdigit(S7), + { S7 in 0..9, + (S1 + S2 * 3 + S3 + S4 * 7 + S5 * 3 + S6 * 9 + S7) mod 10 #= 0 + }. + +sdigit(Value) --> [Code], + { Value in 0..35, + Code in 48..57\/66..68\/70..72\/74..78\/80..84\/86..90, + Code in 48..57 #<==> Value #= Code - 48, + Code in 66..90 #<==> Value #= Code - 55 + }. + +add_checksum_digit(SEDOL6, SEDOL7) :- + append(SEDOL6, [_], SEDOL7), + phrase(sedol, SEDOL7), + once(label(SEDOL7)). + +% adds the checksum digits to each number and removes any invalid numbers +task(SEDOL6s) :- + convlist(add_checksum_digit, SEDOL6s, SEDOL7s), + foreach(member(SEDOL7, SEDOL7s), format("~s~n", [SEDOL7])). + +?- task([ + "710889", + "B0YBKJ", + "406566", + "B0YBLH", + "228276", + "B0YBKL", + "557910", + "B0YBKR", + "585284", + "B0YBKT", + "BOYBKT", % Ill formed test case - illegal vowel. + "B00030" + ]). diff --git a/Task/SEDOLs/Prolog/sedols-2.pro b/Task/SEDOLs/Prolog/sedols-2.pro new file mode 100644 index 0000000000..c08bcdfb76 --- /dev/null +++ b/Task/SEDOLs/Prolog/sedols-2.pro @@ -0,0 +1,5 @@ +?- SEDOL = [0'7, _, 0'0, 0'8, 0'8, 0'9, 0'9], phrase(sedol, SEDOL), label(SEDOL). +SEDOL = "7108899" ; +SEDOL = "7B08899" ; +SEDOL = "7L08899" ; +SEDOL = "7V08899". diff --git a/Task/SEDOLs/Prolog/sedols-3.pro b/Task/SEDOLs/Prolog/sedols-3.pro new file mode 100644 index 0000000000..ad9ef5772c --- /dev/null +++ b/Task/SEDOLs/Prolog/sedols-3.pro @@ -0,0 +1,21 @@ +?- phrase(sedol, SEDOL), label(SEDOL). +SEDOL = "0000000" ; +SEDOL = "0000011" ; +SEDOL = "0000022" ; +SEDOL = "0000033" ; +SEDOL = "0000044" ; +SEDOL = "0000055" ; +SEDOL = "0000066" ; +SEDOL = "0000077" ; +SEDOL = "0000088" ; +SEDOL = "0000099" ; +SEDOL = "00000B1" ; +SEDOL = "00000C2" ; +SEDOL = "00000D3" ; +SEDOL = "00000F5" ; +SEDOL = "00000G6" ; +SEDOL = "00000H7" ; +SEDOL = "00000J9" ; +SEDOL = "00000K0" ; +SEDOL = "00000L1" ; +SEDOL = "00000M2" . % etc... diff --git a/Task/SHA-1/C++/sha-1-2.cpp b/Task/SHA-1/C++/sha-1-2.cpp index 5efd04ae81..c0697e96ba 100644 --- a/Task/SHA-1/C++/sha-1-2.cpp +++ b/Task/SHA-1/C++/sha-1-2.cpp @@ -8,67 +8,67 @@ class SHA1 { public: - std::string message_digest(const std::string& message) { - std::vector state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + std::string message_digest(const std::string& message) { + std::vector state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; - const std::vector bytes = add_padding(message); - for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { - std::vector values(80, 0); - for ( uint32_t j = 0; j < BLOCK_LENGTH; ++j ) { - values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); - } - for ( uint32_t j = 16; j < 80; ++j ) { - uint32_t value = values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16]; - values[j] = std::rotl(value, 1); - } + const std::vector bytes = add_padding(message); + for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { + std::vector values(80, 0); + for ( uint32_t j = 0; j < BLOCK_LENGTH; ++j ) { + values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); + } + for ( uint32_t j = 16; j < 80; ++j ) { + uint32_t value = values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16]; + values[j] = std::rotl(value, 1); + } - uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; - uint32_t f = 0, k = 0; - for ( uint32_t j = 0; j < 80; ++j ) { - switch ( j / 20 ) { - case 0 : { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; break; } - case 1 : { f = b ^ c ^ d; k = 0x6ed9eba1; break; } - case 2 : { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; break; } - case 3 : { f = b ^ c ^ d; k = 0xca62c1d6; break; } - } + uint32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; + uint32_t f = 0, k = 0; + for ( uint32_t j = 0; j < 80; ++j ) { + switch ( j / 20 ) { + case 0 : { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; break; } + case 1 : { f = b ^ c ^ d; k = 0x6ed9eba1; break; } + case 2 : { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; break; } + case 3 : { f = b ^ c ^ d; k = 0xca62c1d6; break; } + } - uint32_t temp = std::rotl(a, 5) + f + e + k + values[j]; - e = d; d = c; c = std::rotl(b, 30); b = a; a = temp; - } + uint32_t temp = std::rotl(a, 5) + f + e + k + values[j]; + e = d; d = c; c = std::rotl(b, 30); b = a; a = temp; + } - state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; - } + state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; + } - std::stringstream stream; - for ( uint32_t i = 0; i < 20; ++i ) { - int8_t byte_value = static_cast(state[i / 4] >> ( 24 - ( i % 4 ) * 8)); - stream << std::setfill('0') << std::setw(2) << std::hex << ( byte_value & 0xff ); - } - return stream.str(); - } + std::stringstream stream; + for ( uint32_t i = 0; i < 20; ++i ) { + int8_t byte_value = static_cast(state[i / 4] >> ( 24 - ( i % 4 ) * 8)); + stream << std::setfill('0') << std::setw(2) << std::hex << ( byte_value & 0xff ); + } + return stream.str(); + } private: - std::vector add_padding(const std::string& message) { - std::vector bytes(message.begin(), message.end()); - bytes.emplace_back(static_cast(0x80)); + std::vector add_padding(const std::string& message) { + std::vector bytes(message.begin(), message.end()); + bytes.emplace_back(static_cast(0x80)); - uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); - if ( padding < 8 ) { - padding += BLOCK_LENGTH; - } - bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); + uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); - const uint64_t bit_length = 8 * message.length(); - for ( int32_t i = 7; i >= 0; --i ) { - bytes.emplace_back(static_cast(bit_length >> ( 8 * i ))); - } - return bytes; - } + const uint64_t bit_length = 8 * message.length(); + for ( int32_t i = 7; i >= 0; --i ) { + bytes.emplace_back(static_cast(bit_length >> ( 8 * i ))); + } + return bytes; + } - const uint32_t BLOCK_LENGTH = 64; + const uint32_t BLOCK_LENGTH = 64; }; int main() { - SHA1 sha1; - std::cout << sha1.message_digest("Rosetta Code") << std::endl; + SHA1 sha1; + std::cout << sha1.message_digest("Rosetta Code") << std::endl; } diff --git a/Task/SHA-1/Hare/sha-1.hare b/Task/SHA-1/Hare/sha-1.hare index a6f6419c1e..64ac39bd10 100644 --- a/Task/SHA-1/Hare/sha-1.hare +++ b/Task/SHA-1/Hare/sha-1.hare @@ -6,11 +6,11 @@ use os; use strings; export fn main() void = { - const sha = sha1::sha1(); - hash::write(&sha, strings::toutf8("Rosetta Code")); + const sha = sha1::sha1(); + hash::write(&sha, strings::toutf8("Rosetta Code")); - let sum: [sha1::SIZE]u8 = [0...]; - hash::sum(&sha, sum); - hex::encode(os::stdout, sum)!; - fmt::println()!; + let sum: [sha1::SIZE]u8 = [0...]; + hash::sum(&sha, sum); + hex::encode(os::stdout, sum)!; + fmt::println()!; }; diff --git a/Task/SHA-1/Haxe/sha-1.haxe b/Task/SHA-1/Haxe/sha-1.haxe index 751e75218f..56e12fee6b 100644 --- a/Task/SHA-1/Haxe/sha-1.haxe +++ b/Task/SHA-1/Haxe/sha-1.haxe @@ -1,7 +1,7 @@ import haxe.crypto.Sha1; class Main { - static function main() { + static function main() { var sha1 = Sha1.encode("Rosetta Code"); Sys.println(sha1); } diff --git a/Task/SHA-1/Java/sha-1.java b/Task/SHA-1/Java/sha-1.java index 98030f5393..fd7ec7e47b 100644 --- a/Task/SHA-1/Java/sha-1.java +++ b/Task/SHA-1/Java/sha-1.java @@ -3,69 +3,69 @@ import java.util.Arrays; public final class SHA1Task { - public static void main(String[] args) { - System.out.println(SHA1.messageDigest("Rosetta Code")); - } + public static void main(String[] args) { + System.out.println(SHA1.messageDigest("Rosetta Code")); + } } final class SHA1 { - - public static String messageDigest(String message) { - int[] state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; - - byte[] bytes = addPadding(message); - for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { - int[] values = new int[80]; - for ( int j = 0; j < BLOCK_LENGTH; j++ ) { - values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); - } - for ( int j = 16; j < 80; j++ ) { - values[j] = Integer.rotateLeft(values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16], 1); - } - - int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; - int f = 0, k = 0; - for ( int j = 0; j < 80; j++ ) { - switch ( j / 20 ) { - case 0 -> { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; } - case 1 -> { f = b ^ c ^ d; k = 0x6ed9eba1; } - case 2 -> { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; } - case 3 -> { f = b ^ c ^ d; k = 0xca62c1d6; } - } - int temp = Integer.rotateLeft(a, 5) + f + e + k + values[j]; - e = d; d = c; c = Integer.rotateLeft(b, 30); b = a; a = temp; - } - - state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; - } - - StringBuilder result = new StringBuilder(); + public static String messageDigest(String message) { + int[] state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + + byte[] bytes = addPadding(message); + for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { + int[] values = new int[80]; + for ( int j = 0; j < BLOCK_LENGTH; j++ ) { + values[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); + } + for ( int j = 16; j < 80; j++ ) { + values[j] = Integer.rotateLeft(values[j - 3] ^ values[j - 8] ^ values[j - 14] ^ values[j - 16], 1); + } + + int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; + int f = 0, k = 0; + for ( int j = 0; j < 80; j++ ) { + switch ( j / 20 ) { + case 0 -> { f = ( b & c ) | ( ~b & d ); k = 0x5a827999; } + case 1 -> { f = b ^ c ^ d; k = 0x6ed9eba1; } + case 2 -> { f = ( b & c ) | ( b & d ) | ( c & d ); k = 0x8f1bbcdc; } + case 3 -> { f = b ^ c ^ d; k = 0xca62c1d6; } + } + + int temp = Integer.rotateLeft(a, 5) + f + e + k + values[j]; + e = d; d = c; c = Integer.rotateLeft(b, 30); b = a; a = temp; + } + + state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; + } + + StringBuilder result = new StringBuilder(); for ( int i = 0; i < 20; i++ ) { - result.append(String.format("%02x", ( state[i / 4] >>> 24 - ( i % 4 ) * 8 ) & 0xFF )); + result.append(String.format("%02x", ( state[i / 4] >>> 24 - ( i % 4 ) * 8 ) & 0xFF )); } return result.toString(); - } - - private static byte[] addPadding(String message) { - byte[] bytes = message.getBytes(StandardCharsets.UTF_8); - bytes = Arrays.copyOf(bytes, bytes.length + 1); - bytes[bytes.length - 1] = (byte) 0x80; - - int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH ); - if ( padding < 8 ) { - padding += BLOCK_LENGTH; - } - bytes = Arrays.copyOf(bytes, bytes.length + padding); - - final long bitLength = message.length() * 8; - for ( int i = 0; i < 8; i++ ) { - bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) ); - } - return bytes; - } - - private static final int BLOCK_LENGTH = 64; - + } + + private static byte[] addPadding(String message) { + byte[] bytes = message.getBytes(StandardCharsets.UTF_8); + bytes = Arrays.copyOf(bytes, bytes.length + 1); + bytes[bytes.length - 1] = (byte) 0x80; + + int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes = Arrays.copyOf(bytes, bytes.length + padding); + + final long bitLength = message.length() * 8; + for ( int i = 0; i < 8; i++ ) { + bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) ); + } + return bytes; + } + + private static final int BLOCK_LENGTH = 64; + } diff --git a/Task/SHA-1/REBOL/sha-1-1.rebol b/Task/SHA-1/REBOL/sha-1-1.rebol new file mode 100644 index 0000000000..467d578cc5 --- /dev/null +++ b/Task/SHA-1/REBOL/sha-1-1.rebol @@ -0,0 +1 @@ +checksum/method "Rosetta Code" 'sha1 diff --git a/Task/SHA-1/REBOL/sha-1-2.rebol b/Task/SHA-1/REBOL/sha-1-2.rebol new file mode 100644 index 0000000000..5e2a23937d --- /dev/null +++ b/Task/SHA-1/REBOL/sha-1-2.rebol @@ -0,0 +1 @@ +checksum "Rosetta Code" 'sha1 diff --git a/Task/SHA-256/C++/sha-256-1.cpp b/Task/SHA-256/C++/sha-256-1.cpp index 0ccc8e6aa7..bc4251b0c1 100644 --- a/Task/SHA-256/C++/sha-256-1.cpp +++ b/Task/SHA-256/C++/sha-256-1.cpp @@ -4,16 +4,16 @@ #include int main(int argc, char **argv){ - CryptoPP::SHA256 hash; - std::string digest; - std::string message = "Rosetta code"; + CryptoPP::SHA256 hash; + std::string digest; + std::string message = "Rosetta code"; - CryptoPP::StringSource s(message, true, - new CryptoPP::HashFilter(hash, - new CryptoPP::HexEncoder( - new CryptoPP::StringSink(digest)))); + CryptoPP::StringSource s(message, true, + new CryptoPP::HashFilter(hash, + new CryptoPP::HexEncoder( + new CryptoPP::StringSink(digest)))); - std::cout << digest << std::endl; + std::cout << digest << std::endl; - return 0; + return 0; } diff --git a/Task/SHA-256/C++/sha-256-2.cpp b/Task/SHA-256/C++/sha-256-2.cpp index 35d2a6b832..964de7b0c6 100644 --- a/Task/SHA-256/C++/sha-256-2.cpp +++ b/Task/SHA-256/C++/sha-256-2.cpp @@ -8,84 +8,84 @@ class SHA256 { public: - std::string message_digest(const std::string& message) { - std::vector hash = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; + std::string message_digest(const std::string& message) { + std::vector hash = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; - const std::vector bytes = add_padding(message); - for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { - std::vector words(BLOCK_LENGTH, 0); - for ( int32_t j = 0; j < BLOCK_LENGTH; ++j ) { - words[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); - } - for ( int32_t j = 16; j < BLOCK_LENGTH; j++ ) { - words[j] = sigma(3, words[j - 2]) + words[j - 7] + sigma(2, words[j - 15]) + words[j - 16]; - } + const std::vector bytes = add_padding(message); + for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { + std::vector words(BLOCK_LENGTH, 0); + for ( int32_t j = 0; j < BLOCK_LENGTH; ++j ) { + words[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); + } + for ( int32_t j = 16; j < BLOCK_LENGTH; j++ ) { + words[j] = sigma(3, words[j - 2]) + words[j - 7] + sigma(2, words[j - 15]) + words[j - 16]; + } - int32_t a = hash[0], b = hash[1], c = hash[2], d = hash[3], - e = hash[4], f = hash[5], g = hash[6], h = hash[7]; + int32_t a = hash[0], b = hash[1], c = hash[2], d = hash[3], + e = hash[4], f = hash[5], g = hash[6], h = hash[7]; - for ( int32_t j = 0; j < BLOCK_LENGTH; ++j ) { - int32_t t = h + sigma(1, e) + ch(e, f, g) + kk[j] + words[j]; - int32_t tt = sigma(0, a) + maj(a, b, c); - h = g; g = f; f = e; - e = d + t; - d = c; c = b; b = a; - a = t + tt; - } + for ( int32_t j = 0; j < BLOCK_LENGTH; ++j ) { + int32_t t = h + sigma(1, e) + ch(e, f, g) + kk[j] + words[j]; + int32_t tt = sigma(0, a) + maj(a, b, c); + h = g; g = f; f = e; + e = d + t; + d = c; c = b; b = a; + a = t + tt; + } - hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; - hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h; - } + hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; + hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h; + } - std::stringstream stream; - for ( int32_t i = 0; i < BLOCK_LENGTH; ++i ) { - int8_t byte_value = static_cast(hash[i / 8] >> ( 7 - i % 8 ) * 4); - stream << std::hex << ( byte_value & 0xf ); - } - return stream.str(); - } + std::stringstream stream; + for ( int32_t i = 0; i < BLOCK_LENGTH; ++i ) { + int8_t byte_value = static_cast(hash[i / 8] >> ( 7 - i % 8 ) * 4); + stream << std::hex << ( byte_value & 0xf ); + } + return stream.str(); + } private: - std::vector add_padding(const std::string& message) { - std::vector bytes(message.begin(), message.end()); - bytes.emplace_back(static_cast(0x80)); + std::vector add_padding(const std::string& message) { + std::vector bytes(message.begin(), message.end()); + bytes.emplace_back(static_cast(0x80)); - uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); - if ( padding < 8 ) { - padding += BLOCK_LENGTH; - } - bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); + uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); - const uint64_t bit_length = 8 * message.length(); - for ( int32_t i = 7; i >= 0; --i ) { - bytes.emplace_back(static_cast(bit_length >> ( 8 * i ))); - } - return bytes; - } + const uint64_t bit_length = 8 * message.length(); + for ( int32_t i = 7; i >= 0; --i ) { + bytes.emplace_back(static_cast(bit_length >> ( 8 * i ))); + } + return bytes; + } - int32_t sigma(const uint32_t& group, const uint32_t& x) { - int32_t result; - switch ( group ) { - case 0 : result = std::rotr(x, 2) ^ std::rotr(x, 13) ^ std::rotr(x, 22); break; - case 1 : result = std::rotr(x, 6) ^ std::rotr(x, 11) ^ std::rotr(x, 25); break; - case 2 : result = std::rotr(x, 7) ^ std::rotr(x, 18) ^ ( x >> 3 ); break; - case 3 : result = std::rotr(x, 17) ^ std::rotr(x, 19) ^ ( x >> 10 ); break; - default : throw std::invalid_argument("Unexpected argument for sigma: " + std::to_string(group)); - } - return result; - } + int32_t sigma(const uint32_t& group, const uint32_t& x) { + int32_t result; + switch ( group ) { + case 0 : result = std::rotr(x, 2) ^ std::rotr(x, 13) ^ std::rotr(x, 22); break; + case 1 : result = std::rotr(x, 6) ^ std::rotr(x, 11) ^ std::rotr(x, 25); break; + case 2 : result = std::rotr(x, 7) ^ std::rotr(x, 18) ^ ( x >> 3 ); break; + case 3 : result = std::rotr(x, 17) ^ std::rotr(x, 19) ^ ( x >> 10 ); break; + default : throw std::invalid_argument("Unexpected argument for sigma: " + std::to_string(group)); + } + return result; + } - int32_t ch(const int32_t& x, const int32_t y, const int32_t z) { - return ( x & y ) ^ ( ~x & z ); - } + int32_t ch(const int32_t& x, const int32_t y, const int32_t z) { + return ( x & y ) ^ ( ~x & z ); + } - int32_t maj(const int32_t& x, const int32_t y, const int32_t z) { - return ( x & y ) ^ ( x & z ) ^ ( y & z ); - } + int32_t maj(const int32_t& x, const int32_t y, const int32_t z) { + return ( x & y ) ^ ( x & z ) ^ ( y & z ); + } - const std::vector kk = { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + const std::vector kk = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, @@ -94,10 +94,10 @@ private: 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; - const int32_t BLOCK_LENGTH = 64; + const int32_t BLOCK_LENGTH = 64; }; int main() { - SHA256 sha256; - std::cout << sha256.message_digest("Rosetta code") << std::endl; + SHA256 sha256; + std::cout << sha256.message_digest("Rosetta code") << std::endl; } diff --git a/Task/SHA-256/C/sha-256.c b/Task/SHA-256/C/sha-256.c index 688dd2911d..8af297e0ab 100644 --- a/Task/SHA-256/C/sha-256.c +++ b/Task/SHA-256/C/sha-256.c @@ -3,13 +3,13 @@ #include int main (void) { - const char *s = "Rosetta code"; - unsigned char *d = SHA256(s, strlen(s), 0); + const char *s = "Rosetta code"; + unsigned char *d = SHA256(s, strlen(s), 0); - int i; - for (i = 0; i < SHA256_DIGEST_LENGTH; i++) - printf("%02x", d[i]); - putchar('\n'); + int i; + for (i = 0; i < SHA256_DIGEST_LENGTH; i++) + printf("%02x", d[i]); + putchar('\n'); - return 0; + return 0; } diff --git a/Task/SHA-256/FutureBasic/sha-256.basic b/Task/SHA-256/FutureBasic/sha-256.basic index d63eade7d7..44fa12b300 100644 --- a/Task/SHA-256/FutureBasic/sha-256.basic +++ b/Task/SHA-256/FutureBasic/sha-256.basic @@ -11,7 +11,7 @@ void local fn DoIt MutableStringAppendFormat( res, @"%02x", buf(i) ) next NSLog(@"Input:\n%@\n",msg) - NSLog(@"Output:\n%@", res) + NSLog(@"Output:\n%@", res) end fn fn DoIt diff --git a/Task/SHA-256/Haxe/sha-256.haxe b/Task/SHA-256/Haxe/sha-256.haxe index d99b3edeb4..adbcee5c38 100644 --- a/Task/SHA-256/Haxe/sha-256.haxe +++ b/Task/SHA-256/Haxe/sha-256.haxe @@ -1,7 +1,7 @@ import haxe.crypto.Sha256; class Main { - static function main() { + static function main() { var sha256 = Sha256.encode("Rosetta code"); Sys.println(sha256); } diff --git a/Task/SHA-256/Java/sha-256.java b/Task/SHA-256/Java/sha-256.java index 40dfd1b2f9..1702aaa6e4 100644 --- a/Task/SHA-256/Java/sha-256.java +++ b/Task/SHA-256/Java/sha-256.java @@ -3,97 +3,97 @@ import java.util.Arrays; public final class SHA256Task { - public static void main(String[] args) { - System.out.println(SHA256.messageDigest("Rosetta code")); - } + public static void main(String[] args) { + System.out.println(SHA256.messageDigest("Rosetta code")); + } } final class SHA256 { - - public static String messageDigest(String message) { - int[] hash = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; - - final byte[] bytes = addPadding(message); - for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { - int[] words = new int[BLOCK_LENGTH]; - for ( int j = 0; j < BLOCK_LENGTH; j++ ) { - words[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); - } - for ( int j = 16; j < BLOCK_LENGTH; j++ ) { - words[j] = sigma(3, words[j - 2]) + words[j - 7] + sigma(2, words[j - 15]) + words[j - 16]; - } - - int a = hash[0], b = hash[1], c = hash[2], d = hash[3], - e = hash[4], f = hash[5], g = hash[6], h = hash[7]; - - for ( int j = 0; j < BLOCK_LENGTH; j++ ) { - int t = h + sigma(1, e) + ch(e, f, g) + kk[j] + words[j]; - int tt = sigma(0, a) + maj(a, b, c); - h = g; g = f; f = e; - e = d + t; - d = c; c = b; b = a; - a = t + tt; - } - hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; - hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h; - } - - StringBuilder result = new StringBuilder(); + public static String messageDigest(String message) { + int[] hash = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; + + final byte[] bytes = addPadding(message); + for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { + int[] words = new int[BLOCK_LENGTH]; + for ( int j = 0; j < BLOCK_LENGTH; j++ ) { + words[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 ); + } + for ( int j = 16; j < BLOCK_LENGTH; j++ ) { + words[j] = sigma(3, words[j - 2]) + words[j - 7] + sigma(2, words[j - 15]) + words[j - 16]; + } + + int a = hash[0], b = hash[1], c = hash[2], d = hash[3], + e = hash[4], f = hash[5], g = hash[6], h = hash[7]; + + for ( int j = 0; j < BLOCK_LENGTH; j++ ) { + int t = h + sigma(1, e) + ch(e, f, g) + kk[j] + words[j]; + int tt = sigma(0, a) + maj(a, b, c); + h = g; g = f; f = e; + e = d + t; + d = c; c = b; b = a; + a = t + tt; + } + + hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d; + hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h; + } + + StringBuilder result = new StringBuilder(); for ( int i = 0; i < BLOCK_LENGTH; i++ ) { - result.append(String.format("%1x", ( hash[i / 8] >>> ( 7 - i % 8 ) * 4 ) & 0xf )); + result.append(String.format("%1x", ( hash[i / 8] >>> ( 7 - i % 8 ) * 4 ) & 0xf )); } - return result.toString(); - } - - private static byte[] addPadding(String message) { - byte[] bytes = message.getBytes(StandardCharsets.ISO_8859_1); - bytes = Arrays.copyOf(bytes, bytes.length + 1); - bytes[bytes.length - 1] = (byte) 0x80; - - int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH ); - if ( padding < 8 ) { - padding += BLOCK_LENGTH; - } - bytes = Arrays.copyOf(bytes, bytes.length + padding); - - final long bitLength = message.length() * 8; - for ( int i = 0; i < 8; i++ ) { - bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) ); - } - return bytes; - } - - private static int sigma(int group, int x) { - return switch ( group ) { - case 0 -> Integer.rotateRight(x, 2) ^ Integer.rotateRight(x, 13) ^ Integer.rotateRight(x, 22); - case 1 -> Integer.rotateRight(x, 6) ^ Integer.rotateRight(x, 11) ^ Integer.rotateRight(x, 25); - case 2 -> Integer.rotateRight(x, 7) ^ Integer.rotateRight(x, 18) ^ ( x >>> 3 ); - case 3 -> Integer.rotateRight(x, 17) ^ Integer.rotateRight(x, 19) ^ ( x >>> 10 ); - default -> throw new AssertionError("Unexpected argument for sigma: " + group); - }; - } - - private static int ch(int x, int y, int z) { - return ( x & y ) ^ ( ~x & z ); - } + return result.toString(); + } - private static int maj(int x, int y, int z) { - return ( x & y ) ^ ( x & z ) ^ ( y & z ); - } - - private static final int[] kk = new int[] { - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + private static byte[] addPadding(String message) { + byte[] bytes = message.getBytes(StandardCharsets.ISO_8859_1); + bytes = Arrays.copyOf(bytes, bytes.length + 1); + bytes[bytes.length - 1] = (byte) 0x80; + + int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes = Arrays.copyOf(bytes, bytes.length + padding); + + final long bitLength = message.length() * 8; + for ( int i = 0; i < 8; i++ ) { + bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) ); + } + return bytes; + } + + private static int sigma(int group, int x) { + return switch ( group ) { + case 0 -> Integer.rotateRight(x, 2) ^ Integer.rotateRight(x, 13) ^ Integer.rotateRight(x, 22); + case 1 -> Integer.rotateRight(x, 6) ^ Integer.rotateRight(x, 11) ^ Integer.rotateRight(x, 25); + case 2 -> Integer.rotateRight(x, 7) ^ Integer.rotateRight(x, 18) ^ ( x >>> 3 ); + case 3 -> Integer.rotateRight(x, 17) ^ Integer.rotateRight(x, 19) ^ ( x >>> 10 ); + default -> throw new AssertionError("Unexpected argument for sigma: " + group); + }; + } + + private static int ch(int x, int y, int z) { + return ( x & y ) ^ ( ~x & z ); + } + + private static int maj(int x, int y, int z) { + return ( x & y ) ^ ( x & z ) ^ ( y & z ); + } + + private static final int[] kk = new int[] { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; - - private static final int BLOCK_LENGTH = 64; - + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; + + private static final int BLOCK_LENGTH = 64; + } diff --git a/Task/SHA-256/Perl/sha-256-2.pl b/Task/SHA-256/Perl/sha-256-2.pl index 19aefad802..a631643f16 100644 --- a/Task/SHA-256/Perl/sha-256-2.pl +++ b/Task/SHA-256/Perl/sha-256-2.pl @@ -10,130 +10,130 @@ my @h; my @k; for my $p ( 2 .. 311 ) { - # Horrible primality test, but sufficient for this task. - next if ("1" x $p) =~ /^(11+?)\1+$/; - # The choice to generate h and k instead of hard coding - # them is inspired by the Raku implementation. - my $c = $p ** ( 1/3 ); - push @k, int( ($c - int $c) * WORD ); - next if @h == 8; - my $s = $p ** ( 1/2 ); - push @h, int( ($s - int $s) * WORD ); + # Horrible primality test, but sufficient for this task. + next if ("1" x $p) =~ /^(11+?)\1+$/; + # The choice to generate h and k instead of hard coding + # them is inspired by the Raku implementation. + my $c = $p ** ( 1/3 ); + push @k, int( ($c - int $c) * WORD ); + next if @h == 8; + my $s = $p ** ( 1/2 ); + push @h, int( ($s - int $s) * WORD ); } sub new { - my %self = ( state => [@h], str => "", len => 0 ); - bless \%self, shift; + my %self = ( state => [@h], str => "", len => 0 ); + bless \%self, shift; } my $rightrotate = sub { - my $lo = $_[0] >> $_[1]; - my $hi = $_[0] << (32 - $_[1]); - ($hi | $lo); + my $lo = $_[0] >> $_[1]; + my $hi = $_[0] << (32 - $_[1]); + ($hi | $lo); }; # This is adapted from the wikipedia entry on SHA2. my $compress = sub { - my ($state, $bytes) = @_; - my @w = unpack 'N*', $bytes; - @w == 16 or die 'internal error'; - my ($a, $b, $c, $d, $e, $f, $g, $h) = @$state; - until( @w == 64 ) { - my $s0 = $w[-15] >> 3; - my $s1 = $w[-2] >> 10; - $s0 ^= $rightrotate->($w[-15], $_) for 7, 18; - $s1 ^= $rightrotate->($w[-2], $_) for 17, 19; - push @w, ($w[-16] + $s0 + $w[-7] + $s1) & MASK; - } - my $i = 0; - for my $w (@w) { - my $ch = ($e & $f) ^ ((~$e) & $g); - my $maj = ($a & $b) ^ ($a & $c) ^ ($b & $c); - my ($S0, $S1) = (0, 0); - $S1 ^= $rightrotate->( $e, $_ ) for 6, 11, 25; - $S0 ^= $rightrotate->( $a, $_ ) for 2, 13, 22; - my $temp1 = $h + $S1 + $ch + $k[$i++] + $w; - my $temp2 = $S0 + $maj; - ($h, $g, $f, $e, $d, $c, $b, $a) = - ($g, $f, $e, ($d+$temp1)&MASK, $c, $b, $a, ($temp1+$temp2)&MASK); - } - my $j = 0; - $state->[$j++] += $_ for $a, $b, $c, $d, $e, $f, $g, $h; + my ($state, $bytes) = @_; + my @w = unpack 'N*', $bytes; + @w == 16 or die 'internal error'; + my ($a, $b, $c, $d, $e, $f, $g, $h) = @$state; + until( @w == 64 ) { + my $s0 = $w[-15] >> 3; + my $s1 = $w[-2] >> 10; + $s0 ^= $rightrotate->($w[-15], $_) for 7, 18; + $s1 ^= $rightrotate->($w[-2], $_) for 17, 19; + push @w, ($w[-16] + $s0 + $w[-7] + $s1) & MASK; + } + my $i = 0; + for my $w (@w) { + my $ch = ($e & $f) ^ ((~$e) & $g); + my $maj = ($a & $b) ^ ($a & $c) ^ ($b & $c); + my ($S0, $S1) = (0, 0); + $S1 ^= $rightrotate->( $e, $_ ) for 6, 11, 25; + $S0 ^= $rightrotate->( $a, $_ ) for 2, 13, 22; + my $temp1 = $h + $S1 + $ch + $k[$i++] + $w; + my $temp2 = $S0 + $maj; + ($h, $g, $f, $e, $d, $c, $b, $a) = + ($g, $f, $e, ($d+$temp1)&MASK, $c, $b, $a, ($temp1+$temp2)&MASK); + } + my $j = 0; + $state->[$j++] += $_ for $a, $b, $c, $d, $e, $f, $g, $h; }; use constant can_Q => eval { length pack 'Q>', 0 }; sub add { - my ($self, $bytes) = @_; - $self->{len} += 8 * length $bytes; - if( !can_Q and $self->{len} >= WORD ) { - my $hi = int( $self->{len} / WORD ); - $self->{big} += $hi; - $self->{len} -= $hi * WORD; - } - my $len = length $self->{str}; - if( ($len + length $bytes) < 64 ) { - $self->{str} .= $bytes; - return $self; - } - my $off = 64 - $len; - $compress->( $self->{state}, $self->{str} . substr( $bytes, 0, $off ) ); - $len = length $_[0]; - while( $off+64 <= $len ) { - $compress->( $self->{state}, substr( $bytes, $off, 64 ) ); - $off += 64; - } - $self->{str} = substr( $bytes, $off ); - $self; + my ($self, $bytes) = @_; + $self->{len} += 8 * length $bytes; + if( !can_Q and $self->{len} >= WORD ) { + my $hi = int( $self->{len} / WORD ); + $self->{big} += $hi; + $self->{len} -= $hi * WORD; + } + my $len = length $self->{str}; + if( ($len + length $bytes) < 64 ) { + $self->{str} .= $bytes; + return $self; + } + my $off = 64 - $len; + $compress->( $self->{state}, $self->{str} . substr( $bytes, 0, $off ) ); + $len = length $_[0]; + while( $off+64 <= $len ) { + $compress->( $self->{state}, substr( $bytes, $off, 64 ) ); + $off += 64; + } + $self->{str} = substr( $bytes, $off ); + $self; } sub addfile { - my ($self, $fh) = @_; - my $s = ""; - while( read( $fh, $s, 2**13 ) ) { - $self->add( $s ); - } - $self; + my ($self, $fh) = @_; + my $s = ""; + while( read( $fh, $s, 2**13 ) ) { + $self->add( $s ); + } + $self; } sub digest { - my $self = shift; - my $final = $self->{str}; - $final .= chr 0x80; - while( ( 8+length $final ) % 64 ) { - $final .= chr 0; - } - if( can_Q ) { - $final .= pack 'Q>', $self->{len}; - } else { - $self->{big} ||= 0; - $final .= pack 'NN', $self->{big}, $self->{len}; - } - $compress->( $self->{state}, substr $final, 0, 64, "" ) while length $final; - if( wantarray ) { - map pack('N', $_), @{ $self->{state} }; - } else { - pack 'N*', @{ $self->{state} }; - } + my $self = shift; + my $final = $self->{str}; + $final .= chr 0x80; + while( ( 8+length $final ) % 64 ) { + $final .= chr 0; + } + if( can_Q ) { + $final .= pack 'Q>', $self->{len}; + } else { + $self->{big} ||= 0; + $final .= pack 'NN', $self->{big}, $self->{len}; + } + $compress->( $self->{state}, substr $final, 0, 64, "" ) while length $final; + if( wantarray ) { + map pack('N', $_), @{ $self->{state} }; + } else { + pack 'N*', @{ $self->{state} }; + } } sub hexdigest { - if( wantarray ) { - map unpack( 'H*', $_), &digest; - } else { - unpack 'H*', &digest; - } + if( wantarray ) { + map unpack( 'H*', $_), &digest; + } else { + unpack 'H*', &digest; + } } unless( caller ) { - my @testwith = (@ARGV ? @ARGV : 'Rosetta code'); - for my $str (@testwith) { - my $digester = __PACKAGE__->new; - $digester->add($str); - print "'$str':\n"; - print join(" ", $digester->hexdigest), "\n"; - } + my @testwith = (@ARGV ? @ARGV : 'Rosetta code'); + for my $str (@testwith) { + my $digester = __PACKAGE__->new; + $digester->add($str); + print "'$str':\n"; + print join(" ", $digester->hexdigest), "\n"; + } } 1; diff --git a/Task/SHA-256/REBOL/sha-256.rebol b/Task/SHA-256/REBOL/sha-256.rebol new file mode 100644 index 0000000000..ec065d3542 --- /dev/null +++ b/Task/SHA-256/REBOL/sha-256.rebol @@ -0,0 +1 @@ +checksum "Rosetta code" 'sha256 diff --git a/Task/SHA-256/Raku/sha-256-1.raku b/Task/SHA-256/Raku/sha-256-1.raku index feb02e9bca..2382d1b6c2 100644 --- a/Task/SHA-256/Raku/sha-256-1.raku +++ b/Task/SHA-256/Raku/sha-256-1.raku @@ -15,28 +15,28 @@ multi sha256(blob8 $data) { return blob8.new: map |*.polymod(256 xx 3).reverse, - |reduce -> $H, $block { - blob32.new: $H[] Z+ - reduce -> $h, $j { - my uint32 ($T1, $T2) = - $h[7] + Σ1($h[4]) + Ch(|$h[4..6]) - + (BEGIN init(* **(1/3))[^64])[$j] + - ( - (state buf32 $w .= new)[$j] = $j < 16 ?? $block[$j] !! - σ0($w[$j-15]) + $w[$j-7] + σ1($w[$j-2]) + $w[$j-16] - ), - Σ0($h[0]) + Maj(|$h[0..2]); - blob32.new: $T1 + $T2, |$h[0..2], $h[3] + $T1, |$h[4..6]; - }, $H, |^64; - }, - (BEGIN init(&sqrt)[^8]), - |blob32.new( - blob8.new( - @$data, - 0x80, - 0 xx (-($data + 1 + 8) mod 64), - (8*$data).polymod(256 xx 7).reverse - ).rotor(4) - .map: { :256[@$_] } - ).rotor(16) + |reduce -> $H, $block { + blob32.new: $H[] Z+ + reduce -> $h, $j { + my uint32 ($T1, $T2) = + $h[7] + Σ1($h[4]) + Ch(|$h[4..6]) + + (BEGIN init(* **(1/3))[^64])[$j] + + ( + (state buf32 $w .= new)[$j] = $j < 16 ?? $block[$j] !! + σ0($w[$j-15]) + $w[$j-7] + σ1($w[$j-2]) + $w[$j-16] + ), + Σ0($h[0]) + Maj(|$h[0..2]); + blob32.new: $T1 + $T2, |$h[0..2], $h[3] + $T1, |$h[4..6]; + }, $H, |^64; + }, + (BEGIN init(&sqrt)[^8]), + |blob32.new( + blob8.new( + @$data, + 0x80, + 0 xx (-($data + 1 + 8) mod 64), + (8*$data).polymod(256 xx 7).reverse + ).rotor(4) + .map: { :256[@$_] } + ).rotor(16) } diff --git a/Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-1.duckdb b/Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-1.duckdb new file mode 100644 index 0000000000..e11dc512bb --- /dev/null +++ b/Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-1.duckdb @@ -0,0 +1,5 @@ +create or replace table african_capitals( + name varchar(100), population_in_millions decimal(6,2) ); + +insert into african_capitals + from read_json_auto('input.json'); diff --git a/Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-2.duckdb b/Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-2.duckdb new file mode 100644 index 0000000000..fdf42c3e27 --- /dev/null +++ b/Task/Search-a-list-of-records/DuckDB/search-a-list-of-records-2.duckdb @@ -0,0 +1,2 @@ +create or replace table african_capitals as + FROM read_json_auto('rc-search-a-list-of-records.json'); diff --git a/Task/Search-a-list-of-records/Icon/search-a-list-of-records.icon b/Task/Search-a-list-of-records/Icon/search-a-list-of-records.icon new file mode 100644 index 0000000000..e1c8db8712 --- /dev/null +++ b/Task/Search-a-list-of-records/Icon/search-a-list-of-records.icon @@ -0,0 +1,19 @@ +record City(name,population) + +procedure main() + citydata := [ + City( "Lagos", 21.0 ), + City( "Cairo", 15.2 ), + City( "Kinshasa-Brazzaville", 11.3 ), + City( "Greater Johannesburg", 7.55 ), + City( "Mogadishu", 5.85 ), + City( "Khartoum-Omdurman", 4.98 ), + City( "Dar Es Salaam", 4.7 ), + City( "Alexandria", 4.58 ), + City( "Abidjan", 4.4 ), + City( "Casablanca", 3.98 ) + ] + if i := 1 to *citydata & citydata[i].name == "Dar Es Salaam" then write(i-1) + if city := !citydata & city.population < 5.0 then write(city.name) + if city := !citydata & city.name[1] == "A" then write(city.population) +end diff --git a/Task/Self-numbers/Pluto/self-numbers.pluto b/Task/Self-numbers/Pluto/self-numbers.pluto new file mode 100644 index 0000000000..28a3c4c409 --- /dev/null +++ b/Task/Self-numbers/Pluto/self-numbers.pluto @@ -0,0 +1,83 @@ +local start_index, end_index, counter +local current_self +local output + +local function done_after_adding(interval, n) + -- Advance to the next self number in the sequence, append it to the output if required, indicate if finished. + for _ = 1, n do + current_self += interval + ++counter + if counter >= start_index then + output:insert(current_self) + end + if counter == end_index then return true end + end + return false +end + +local function self_numbers(index_range) + start_index = index_range[1] + end_index = index_range:back() + counter = 0 + current_self = -1 + output = {} + + -- Main process. Start with the single-digit odd numbers and first run. + if done_after_adding(2, 5) then return output end + if done_after_adding(11, 9) then return output end + + -- If necessary, fast forward to last self number before the lowest-order block containing first number required. + if counter < start_index then + -- The highest-order blocks whose ends this handles correctly contain 9,777,777,778 self numbers. + -- The difference between equivalently positioned numbers in these blocks is 100,000,000,001. + -- The figures for successively lower-order blocks have successively fewer 7s and 0s! + local index_diff = 9777777778 + local numeric_diff = 100000000001 + while index_diff >= 98 and counter != start_index do + if counter + index_diff < start_index then + counter += index_diff + current_self += numeric_diff + else + index_diff = (index_diff + 2) / 10 -- (..78->80->8) + numeric_diff = (numeric_diff + 9) /10 -- (..01->10->1) + end + end + end + + -- Sequencing loop, per lowest-order block. + while true do + -- Eight ten-number runs, each at a numeric interval of 2 from the end of the previous one. + for _ = 1, 8 do + if done_after_adding(2, 1) then return output end + if done_after_adding(11, 9) then return output end + end + -- Two shorter runs, the second at an interval inversely related to their length. + local shorter_run_length = 8 + local temp = current_self // 1000 + -- Work out a shorter run length based on the most significant digit change about to happen. + while temp % 10 == 9 do + shorter_run_length -= 1 + temp //= 10 + end + + local interval = 2 + for _ = 1, 2 do + if done_after_adding(interval, 1) then return output end + if done_after_adding(11, shorter_run_length) then return output end + interval += (9 - shorter_run_length) * 13 + end + end +end + +print("The first 50 self numbers are:\n") +for i, sn in self_numbers({1, 50}) do + io.write(string.format("%3d ", sn)) + if i % 10 == 0 then print() end +end +print() +for p = 8, 9 do + local n = math.round(10 ^ p) + local ord = string.formatint(n) + local sn = string.formatint(math.round(self_numbers({n})[1])) + print($"The {ord}th self number is {sn}") +end diff --git a/Task/Semordnilap/ArkScript/semordnilap.ark b/Task/Semordnilap/ArkScript/semordnilap.ark new file mode 100644 index 0000000000..abd55ead82 --- /dev/null +++ b/Task/Semordnilap/ArkScript/semordnilap.ark @@ -0,0 +1,14 @@ +(import std.IO) +(import std.String) +(import std.Dict) +(import std.List) + +(let words (string:split (io:readFile "tests/unittests/resources/RosettaSuite/res/unixdict.txt") "\n")) + +(let d (dict)) +(list:forEach words (fun (word) (dict:add d word true))) +(let keep (list:filter words (fun (word) + (and (< word (string:reverse word)) (not (nil? (dict:get d (string:reverse word)))))))) + +(print (len keep)) +(print (list:slice keep 0 5 1)) diff --git a/Task/Semordnilap/AutoHotkey/semordnilap.ahk b/Task/Semordnilap/AutoHotkey/semordnilap.ahk index c0cf75c659..049f361aa4 100644 --- a/Task/Semordnilap/AutoHotkey/semordnilap.ahk +++ b/Task/Semordnilap/AutoHotkey/semordnilap.ahk @@ -3,20 +3,20 @@ S := [], M := [] FileRead, dict, unixdict.txt Loop, Parse, dict, `n, `r`n { - r := Reverse(A_LoopField) - if (S[r]) - M.Insert(r " / " A_LoopField) - else - S[A_LoopField] := 1 + r := Reverse(A_LoopField) + if (S[r]) + M.Insert(r " / " A_LoopField) + else + S[A_LoopField] := 1 } Loop, 5 - Out .= "`t" M[A_Index] "`n" + Out .= "`t" M[A_Index] "`n" MsgBox, % "5 Examples:`n" Out "`nTotal Pairs:`n`t" M.MaxIndex() Reverse(s) { - Loop, Parse, s - r := A_LoopField . r - return r + Loop, Parse, s + r := A_LoopField . r + return r } diff --git a/Task/Semordnilap/EchoLisp/semordnilap.l b/Task/Semordnilap/EchoLisp/semordnilap.l index 3ef572acc5..c0aa633721 100644 --- a/Task/Semordnilap/EchoLisp/semordnilap.l +++ b/Task/Semordnilap/EchoLisp/semordnilap.l @@ -8,18 +8,18 @@ ;; check reverse r of w is a word ;; take only one pair : r < w (define (semordnilap? w) - (define r (list->string (reverse (string->list w)))) - (and (word? r) (stringstring (reverse (string->list w)))) + (and (word? r) (string (string-length a) (string-length b))) - + (define (task) ;; select unique words into the list 'mots' (define mots (make-set (words-select #:any null 999999))) (define semordnilap - (list-sort string-sort (for/list ((w mots)) - #:when (semordnilap? w) - w ))) + (list-sort string-sort (for/list ((w mots)) + #:when (semordnilap? w) + w ))) (writeln 'pairs '→ (length semordnilap)) (writeln 'longest '→ (take semordnilap 5))) diff --git a/Task/Semordnilap/Eiffel/semordnilap-1.e b/Task/Semordnilap/Eiffel/semordnilap-1.e index f53e49ea51..9bcdd4aed4 100644 --- a/Task/Semordnilap/Eiffel/semordnilap-1.e +++ b/Task/Semordnilap/Eiffel/semordnilap-1.e @@ -1,79 +1,79 @@ class - SEMORDNILAP + SEMORDNILAP create - make + make feature - make - --Semordnilaps in 'solution'. - local - count, i, middle, upper, lower: INTEGER - reverse: STRING - do - read_wordlist - create solution.make_empty - from - i := 1 - until - i > word_array.count - loop - word_array [i].mirror - reverse := word_array [i] - from - lower := i + 1 - upper := word_array.count - until - lower >= upper - loop - middle := (upper - lower) // 2 + lower - if reverse.same_string (word_array [middle]) then - count := count + 1 - upper := 0 - lower := 1 - solution.force (word_array [i], count) - elseif reverse.is_less (word_array [middle]) then - upper := middle - 1 - else - lower := middle + 1 - end - end - if lower < word_array.count and then reverse.same_string (word_array [lower]) then - count := count + 1 - upper := 0 - lower := 1 - solution.force (word_array [i], count) - end - i := i + 1 - end - end + make + --Semordnilaps in 'solution'. + local + count, i, middle, upper, lower: INTEGER + reverse: STRING + do + read_wordlist + create solution.make_empty + from + i := 1 + until + i > word_array.count + loop + word_array [i].mirror + reverse := word_array [i] + from + lower := i + 1 + upper := word_array.count + until + lower >= upper + loop + middle := (upper - lower) // 2 + lower + if reverse.same_string (word_array [middle]) then + count := count + 1 + upper := 0 + lower := 1 + solution.force (word_array [i], count) + elseif reverse.is_less (word_array [middle]) then + upper := middle - 1 + else + lower := middle + 1 + end + end + if lower < word_array.count and then reverse.same_string (word_array [lower]) then + count := count + 1 + upper := 0 + lower := 1 + solution.force (word_array [i], count) + end + i := i + 1 + end + end - solution: ARRAY [STRING] + solution: ARRAY [STRING] - original_list: STRING = "unixdict.txt" + original_list: STRING = "unixdict.txt" feature {NONE} - read_wordlist - -- Preprocessed word_array for finding Semordnilaps. - local - l_file: PLAIN_TEXT_FILE - wordlist: LIST [STRING] - do - create l_file.make_open_read_write (original_list) - l_file.read_stream (l_file.count) - wordlist := l_file.last_string.split ('%N') - l_file.close - create word_array.make_empty - across - 1 |..| wordlist.count as i - loop - word_array.force (wordlist.at (i.item), i.item) - end - end + read_wordlist + -- Preprocessed word_array for finding Semordnilaps. + local + l_file: PLAIN_TEXT_FILE + wordlist: LIST [STRING] + do + create l_file.make_open_read_write (original_list) + l_file.read_stream (l_file.count) + wordlist := l_file.last_string.split ('%N') + l_file.close + create word_array.make_empty + across + 1 |..| wordlist.count as i + loop + word_array.force (wordlist.at (i.item), i.item) + end + end - word_array: ARRAY [STRING] + word_array: ARRAY [STRING] end diff --git a/Task/Semordnilap/Eiffel/semordnilap-2.e b/Task/Semordnilap/Eiffel/semordnilap-2.e index 00b10484c5..0e9ec0ef20 100644 --- a/Task/Semordnilap/Eiffel/semordnilap-2.e +++ b/Task/Semordnilap/Eiffel/semordnilap-2.e @@ -1,34 +1,34 @@ class - APPLICATION + APPLICATION create - make + make feature - make - local - test: ARRAY [STRING] - s: STRING - do - create se.make - test := se.solution - create sort.sort (test) - across - test.subarray (1, 5) as t - loop - s := t.item - io.put_string (t.item + "%T") - s.mirror - io.put_string (s) - io.new_line - end - io.put_string ("Total number of semordnilaps: ") - io.put_integer (test.count) - end + make + local + test: ARRAY [STRING] + s: STRING + do + create se.make + test := se.solution + create sort.sort (test) + across + test.subarray (1, 5) as t + loop + s := t.item + io.put_string (t.item + "%T") + s.mirror + io.put_string (s) + io.new_line + end + io.put_string ("Total number of semordnilaps: ") + io.put_integer (test.count) + end - se: SEMORDNILAP + se: SEMORDNILAP - sort: MERGE_SORT [STRING] + sort: MERGE_SORT [STRING] end diff --git a/Task/Semordnilap/Forth/semordnilap.fth b/Task/Semordnilap/Forth/semordnilap.fth index 509d459659..148c009c56 100644 --- a/Task/Semordnilap/Forth/semordnilap.fth +++ b/Task/Semordnilap/Forth/semordnilap.fth @@ -3,30 +3,30 @@ wordlist constant dict : load-dict ( c-addr u -- ) r/o open-file throw >r begin - pad 1024 r@ read-line throw while - pad swap ['] create execute-parsing + pad 1024 r@ read-line throw while + pad swap ['] create execute-parsing repeat drop r> close-file throw ; : xreverse {: c-addr u -- c-addr2 u :} u allocate throw u + c-addr swap over u + >r begin ( from to r:end) - over r@ u< while - over r@ over - x-size dup >r - 2dup r@ cmove - swap r> + swap repeat + over r@ u< while + over r@ over - x-size dup >r - 2dup r@ cmove + swap r> + swap repeat r> drop nip u ; : .example ( c-addr u u1 -- ) 5 < if - cr 2dup type space 2dup xreverse 2dup type drop free throw then + cr 2dup type space 2dup xreverse 2dup type drop free throw then 2drop ; : nt-semicheck ( u1 nt -- u2 f ) dup >r name>string xreverse 2dup dict find-name-in dup if ( u1 c-addr u nt2) - r@ < if ( u1 c-addr u ) \ count pairs only once and not palindromes - 2dup 4 pick .example - rot 1+ -rot then + r@ < if ( u1 c-addr u ) \ count pairs only once and not palindromes + 2dup 4 pick .example + rot 1+ -rot then else - drop then + drop then drop free throw r> drop true ; get-current dict set-current s" unixdict.txt" load-dict set-current diff --git a/Task/Semordnilap/Julia/semordnilap.jl b/Task/Semordnilap/Julia/semordnilap.jl index c4b414f4b6..aa7873b755 100644 --- a/Task/Semordnilap/Julia/semordnilap.jl +++ b/Task/Semordnilap/Julia/semordnilap.jl @@ -1,4 +1,4 @@ -raw = readdlm("unixdict.txt",String)[:] +raw = readlines("unixdict.txt") inter = intersect(raw,map(reverse,raw)) #find the matching strings/revstrings res = String[b == 1 && a != reverse(a) && a < reverse(a) ? a : reverse(a) for a in inter, b in 1:2] #create pairs res = res[res[:,1] .!= res[:,2],:] #get rid of duplicates, palindromes diff --git a/Task/Semordnilap/Ksh/semordnilap.ksh b/Task/Semordnilap/Ksh/semordnilap.ksh index 2a1873fdb7..baf24ff7b8 100644 --- a/Task/Semordnilap/Ksh/semordnilap.ksh +++ b/Task/Semordnilap/Ksh/semordnilap.ksh @@ -2,7 +2,7 @@ # Semordnilap -# # Variables: +# # Variables: # integer MIN_WORD_LEN=1 TRUE=1 FALSE=0 dict='/home/ostrande/prj/roscode/unixdict.txt' @@ -10,62 +10,62 @@ dict='/home/ostrande/prj/roscode/unixdict.txt' integer i j=0 k=0 typeset -A word -# # Functions: +# # Functions: # -# # Function _flipit(string) - return flipped string +# # Function _flipit(string) - return flipped string # function _flipit { - typeset _buf ; _buf="$1" - typeset _tmp ; unset _tmp + typeset _buf ; _buf="$1" + typeset _tmp ; unset _tmp - for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do - _tmp="${_tmp}${_buf:${_i}:1}" - done + for (( _i=$(( ${#_buf}-1 )); _i>=0; _i-- )); do + _tmp="${_tmp}${_buf:${_i}:1}" + done - echo "${_tmp}" + echo "${_tmp}" } -# # Function _isword(word, wordlist) - return 1 if word in wordlist +# # Function _isword(word, wordlist) - return 1 if word in wordlist # function _isword { - typeset _word ; _word="$1" - typeset _wordlist ; nameref _wordlist="$2" + typeset _word ; _word="$1" + typeset _wordlist ; nameref _wordlist="$2" - [[ ${_word} == @(${_wordlist}) ]] && return $TRUE - return $FALSE + [[ ${_word} == @(${_wordlist}) ]] && return $TRUE + return $FALSE } ###### # main # ###### -# # Due to the large number of words in unixdist.txt subgroup by 1st letter and length -# # only accept words containing alpha chars and > 1 chars +# # Due to the large number of words in unixdist.txt subgroup by 1st letter and length +# # only accept words containing alpha chars and > 1 chars # while read; do - [[ $REPLY != *+(\W)* ]] && [[ $REPLY != *+(\d)* ]] && \ - (( ${#REPLY} > MIN_WORD_LEN )) && word[${REPLY:0:1}][${#REPLY}]+=( $REPLY ) + [[ $REPLY != *+(\W)* ]] && [[ $REPLY != *+(\d)* ]] && \ + (( ${#REPLY} > MIN_WORD_LEN )) && word[${REPLY:0:1}][${#REPLY}]+=( $REPLY ) done < ${dict} print Examples: -for fl in ${!word[*]}; do # Over $fl first letter - for len in ${!word[${fl}][*]}; do # Over $len word length - for ((i=0; i<${#word[${fl}][${len}][*]}; i++)); do - Word=${word[${fl}][${len}][i]} # dummy - Try=$(_flipit ${Word}) - if [[ ${Try} != ${Word} ]]; then # no palindromes - unset words - oldIFS="$IFS" ; IFS='|' ; words=${word[${Try:0:1}][${#Try}][*]} ; IFS="${oldIFS}" - _isword "${Try}" words - if (( $? )); then - if [[ ${Try} != @(${uniq%\|*}) ]]; then - ((++j)) - (( ${#Word} >= 5 )) && (( k<=5 )) && print $((++k)). ${Word} ${Try} - uniq+="${Try}|${Word}|" - fi - fi - fi - done - done +for fl in ${!word[*]}; do # Over $fl first letter + for len in ${!word[${fl}][*]}; do # Over $len word length + for ((i=0; i<${#word[${fl}][${len}][*]}; i++)); do + Word=${word[${fl}][${len}][i]} # dummy + Try=$(_flipit ${Word}) + if [[ ${Try} != ${Word} ]]; then # no palindromes + unset words + oldIFS="$IFS" ; IFS='|' ; words=${word[${Try:0:1}][${#Try}][*]} ; IFS="${oldIFS}" + _isword "${Try}" words + if (( $? )); then + if [[ ${Try} != @(${uniq%\|*}) ]]; then + ((++j)) + (( ${#Word} >= 5 )) && (( k<=5 )) && print $((++k)). ${Word} ${Try} + uniq+="${Try}|${Word}|" + fi + fi + fi + done + done done echo ; print ${j} pairs found. diff --git a/Task/Semordnilap/Lasso/semordnilap.lasso b/Task/Semordnilap/Lasso/semordnilap.lasso index 2cd9770010..cd47131783 100644 --- a/Task/Semordnilap/Lasso/semordnilap.lasso +++ b/Task/Semordnilap/Lasso/semordnilap.lasso @@ -1,27 +1,27 @@ local( - words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'), - semordnilaps = array, - found_size, - example, - haveexamples = false, - examples = array + words = string(include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')) -> split('\n'), + semordnilaps = array, + found_size, + example, + haveexamples = false, + examples = array ) #words -> removeall('') with word in #words do { - local(reversed = string(#word) -> reverse&) - if(not(#word == #reversed) and not(#semordnilaps >> #word) and not(#semordnilaps >> #reversed) and #words >> #reversed) => { - #semordnilaps -> insert(#word = #reversed) - } + local(reversed = string(#word) -> reverse&) + if(not(#word == #reversed) and not(#semordnilaps >> #word) and not(#semordnilaps >> #reversed) and #words >> #reversed) => { + #semordnilaps -> insert(#word = #reversed) + } } #found_size = #semordnilaps -> size while(not(#haveexamples)) => { - #example = #semordnilaps -> get(integer_random(#found_size, 1)) - not(#examples >> #example -> name) ? #examples -> insert(#example) - #examples -> size >= 5 ? #haveexamples = true + #example = #semordnilaps -> get(integer_random(#found_size, 1)) + not(#examples >> #example -> name) ? #examples -> insert(#example) + #examples -> size >= 5 ? #haveexamples = true } 'Total found: ' #found_size diff --git a/Task/Semordnilap/Lua/semordnilap.lua b/Task/Semordnilap/Lua/semordnilap.lua index d67015ca14..3bff64e789 100644 --- a/Task/Semordnilap/Lua/semordnilap.lua +++ b/Task/Semordnilap/Lua/semordnilap.lua @@ -22,13 +22,18 @@ end -- print the report print("There are " .. #semordnilaps .. " semordnilaps in " .. dictfile .. ". Here are " .. sample_size .. ":") -math.randomseed( os.time() ) -for i = 1, sample_size do - local j - repeat - j = math.random(1,#semordnilaps) - until semordnilaps[j] - local f, r = unpack(semordnilaps[j]) - semordnilaps[j] = nil - print(f .. " -> " .. r) +do + -- unpack is in table in Lua 5.4 + local unpack = table.unpack or unpack + + math.randomseed( os.time() ) + for i = 1, sample_size do + local j + repeat + j = math.random(1,#semordnilaps) + until semordnilaps[j] + local f, r = unpack(semordnilaps[j]) + semordnilaps[j] = nil + print(f .. " -> " .. r) + end end diff --git a/Task/Semordnilap/NewLISP/semordnilap.l b/Task/Semordnilap/NewLISP/semordnilap.l index b3f0078923..5debafbeb6 100644 --- a/Task/Semordnilap/NewLISP/semordnilap.l +++ b/Task/Semordnilap/NewLISP/semordnilap.l @@ -1,26 +1,26 @@ -;;; Get the words as a list, splitting at newline +;;; Get the words as a list, splitting at newline (setq data - (parse (get-url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") - "\n")) + (parse (get-url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") + "\n")) ; -;;; destructive reverse wrapped into a function +;;; destructive reverse wrapped into a function (define (get-reverse x) (reverse x)) ; -;;; stack of the results +;;; stack of the results (setq res '()) ; -;;; Find the semordlinap and put them on the stack +;;; Find the semordlinap and put them on the stack (dolist (x data) - (let (y (get-reverse x)) - (if (and - (member y data) ; reverse is a dictionary word - (!= x y) ; but not a palindrome - (not (member y res))) ; not already stacked - (push x res -1)))) + (let (y (get-reverse x)) + (if (and + (member y data) ; reverse is a dictionary word + (!= x y) ; but not a palindrome + (not (member y res))) ; not already stacked + (push x res -1)))) ; -;;; Count results +;;; Count results (println "Found " (length res) " pairs.") (println) -;;; Show the longest ones +;;; Show the longest ones (dolist (x res) - (if (> (length x) 4) (println x " -- " (get-reverse x)))) + (if (> (length x) 4) (println x " -- " (get-reverse x)))) diff --git a/Task/Semordnilap/Perl/semordnilap.pl b/Task/Semordnilap/Perl/semordnilap.pl index 1236f1bbb9..05431dbcee 100644 --- a/Task/Semordnilap/Perl/semordnilap.pl +++ b/Task/Semordnilap/Perl/semordnilap.pl @@ -1,7 +1,7 @@ while (<>) { - chomp; - my $r = reverse; - $seen{$r}++ and $c++ < 5 and print "$_ $r\n" or $seen{$_}++; + chomp; + my $r = reverse; + $seen{$r}++ and $c++ < 5 and print "$_ $r\n" or $seen{$_}++; } print "$c\n" diff --git a/Task/Semordnilap/Phixmonti/semordnilap.phixmonti b/Task/Semordnilap/Phixmonti/semordnilap.phixmonti index e97a46a2b3..560c1f466f 100644 --- a/Task/Semordnilap/Phixmonti/semordnilap.phixmonti +++ b/Task/Semordnilap/Phixmonti/semordnilap.phixmonti @@ -5,30 +5,30 @@ include ..\Utilitys.pmt "unixdict.txt" "r" fopen var f true while - f fgets - dup -1 == if - drop - f fclose - false - else - -1 del - 0 put - true - endif + f fgets + dup -1 == if + drop + f fclose + false + else + -1 del + 0 put + true + endif endwhile len while - len 1 > if - pop swap reverse find dup - if - extract rot swap 0 put swap - else - drop - endif - true - else - drop false - endif + len 1 > if + pop swap reverse find dup + if + extract rot swap 0 put swap + else + drop + endif + true + else + drop false + endif endwhile ( 50 54 ) for get dup reverse print " -> " print ? endfor nl diff --git a/Task/Semordnilap/Pluto/semordnilap.pluto b/Task/Semordnilap/Pluto/semordnilap.pluto new file mode 100644 index 0000000000..7032043314 --- /dev/null +++ b/Task/Semordnilap/Pluto/semordnilap.pluto @@ -0,0 +1,21 @@ +local file = io.open("unixdict.txt", "r") +local wmap = {} +for word in file:lines() do wmap[word] = true end +local pairs = {} +local used = {} +file:seek("set") +for word in file:lines() do + if word != "" then + local pal = string.reverse(word) + if word != pal and wmap[pal] and !used[pal] then + pairs:insert({word, pal}) + used[word] = true + end + end +end +file:close() +print($"There are {#pairs} unique semordnilap pairs in the dictionary.") +print("\nIn sorted order, the first five are:") +for i = 1, 5 do print($" {pairs[i][1]}, {pairs[i][2]}") end +print("\nand the last five are:") +for i = #pairs - 4, #pairs do print($" {pairs[i][1]}, {pairs[i][2]}") end diff --git a/Task/Semordnilap/Prolog/semordnilap.pro b/Task/Semordnilap/Prolog/semordnilap.pro new file mode 100644 index 0000000000..03f05e2dc1 --- /dev/null +++ b/Task/Semordnilap/Prolog/semordnilap.pro @@ -0,0 +1,28 @@ +:- initialization(main, main). +:- use_module(library(apply)). +:- use_module(library(dcg/basics)). +:- use_module(library(dcg/high_order)). +:- use_module(library(ordsets)). + +load(Filename, Words) :- once(phrase_from_file(sequence(word, Words), Filename)). +word(Word) --> nonblanks(Word), eol, { Word \= [] }. + +find_all_semordnilaps(Words, Semordnilaps) :- + convlist([Word, Reversed] >> ( + reverse(Word, Reversed), + Reversed @< Word + ), Words, ReversedWords0), + sort(ReversedWords0, ReversedWords), + ord_intersection(Words, ReversedWords, Semordnilaps). + +main([Filename]) :- + load(Filename, Words), + find_all_semordnilaps(Words, Semordnilaps), + length(Semordnilaps, Count), + format("~d~n", Count), + length(FirstFive, 5), + prefix(FirstFive, Semordnilaps), + maplist([Word] >> ( + reverse(Word, Reversed), + format("~s / ~s~n", [Word, Reversed]) + ), FirstFive). diff --git a/Task/Semordnilap/Python/semordnilap-1.py b/Task/Semordnilap/Python/semordnilap-1.py index 0e1fa9ed3c..6acbb2e6d9 100644 --- a/Task/Semordnilap/Python/semordnilap-1.py +++ b/Task/Semordnilap/Python/semordnilap-1.py @@ -1,5 +1,5 @@ >>> with open('unixdict.txt') as f: - wordset = set(f.read().strip().split()) + wordset = set(f.read().strip().split()) >>> revlist = (''.join(word[::-1]) for word in wordset) >>> pairs = set((word, rev) for word, rev in zip(wordset, revlist) diff --git a/Task/Semordnilap/R/semordnilap.r b/Task/Semordnilap/R/semordnilap.r index e0cd0022e9..425f6d70bc 100644 --- a/Task/Semordnilap/R/semordnilap.r +++ b/Task/Semordnilap/R/semordnilap.r @@ -1,6 +1,6 @@ library(stringi) -unixdict <- read.table("unixdict.txt", col.names="forwards") +unixdict <- read.table("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", col.names="forwards") unixdict$backwards <- stri_reverse(unixdict$forwards) #Remove all actual palindromes, as we do not want those diff --git a/Task/Semordnilap/REBOL/semordnilap-1.rebol b/Task/Semordnilap/REBOL/semordnilap-1.rebol new file mode 100644 index 0000000000..b1dd74d3c1 --- /dev/null +++ b/Task/Semordnilap/REBOL/semordnilap-1.rebol @@ -0,0 +1,26 @@ +Rebol [ + title: "Rosetta code: Semordnilap" + file: %Semordnilap.r + url: https://rosettacode.org/wiki/Semordnilap + needs: 2.7.0 +] + +words: read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt +seen: make hash! 200 +count: 0 + +print ["Number of input words: " length? words LF] + +foreach word words [ + reversed: reverse copy word + either find seen reversed [ + count: count + 1 + if count <= 5 [ + print [word "is reversed:" reversed] + ] + ][ + append seen word + ] +] + +print [LF "Found total" count "pairs."] diff --git a/Task/Semordnilap/REBOL/semordnilap-2.rebol b/Task/Semordnilap/REBOL/semordnilap-2.rebol new file mode 100644 index 0000000000..026971ea27 --- /dev/null +++ b/Task/Semordnilap/REBOL/semordnilap-2.rebol @@ -0,0 +1,25 @@ +Rebol [ + title: "Rosetta code: Semordnilap" + file: %Semordnilap.r3 + url: https://rosettacode.org/wiki/Semordnilap + needs: 3.14.0 +] + +words: read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt +seen: make map! 200 +count: 0 + +print ["Number of input words: " length? words LF] + +foreach word words [ + reversed: reverse copy word + either find seen reversed [ + if ++ count <= 5 [ + print [word "is reversed:" reversed] + ] + ][ + put seen word reversed + ] +] + +print [LF "Found total" count "pairs."] diff --git a/Task/Semordnilap/SNOBOL4/semordnilap.sno b/Task/Semordnilap/SNOBOL4/semordnilap.sno index 795ca4e677..ffa5b12f6a 100644 --- a/Task/Semordnilap/SNOBOL4/semordnilap.sno +++ b/Task/Semordnilap/SNOBOL4/semordnilap.sno @@ -7,28 +7,28 @@ * Reads file unixdict.txt * Comment: Tested using the Spitbol for Linux version of SNOBOL4 - output = "Some Semordnilap Pairs from File unixdict.txt" - atable = table(25200,,-1) - ntable = table(25200,,-2) + output = "Some Semordnilap Pairs from File unixdict.txt" + atable = table(25200,,-1) + ntable = table(25200,,-2) * Read dictionary file into memory in1 - word = input :f(p1) - count = count + 1 - atable[word] = word - ntable[count] = word - :(in1) + word = input :f(p1) + count = count + 1 + atable[word] = word + ntable[count] = word + :(in1) * Process dictionary to find unique semordnilaps p1 - i = lt(i,count) i + 1 :f(p2) - newword = atable[reverse(ntable[i])] - leq(newword,-1) :s(p1) - ident(ntable[i],newword) :s(p1) - output = lt(outcount,5) ntable[i] ', ' newword - atable[ntable[i]] = atable[newword] = -1 - outcount = outcount + 1 - :(p1) + i = lt(i,count) i + 1 :f(p2) + newword = atable[reverse(ntable[i])] + leq(newword,-1) :s(p1) + ident(ntable[i],newword) :s(p1) + output = lt(outcount,5) ntable[i] ', ' newword + atable[ntable[i]] = atable[newword] = -1 + outcount = outcount + 1 + :(p1) p2 - output = 'The number of semordnilap pairs is: ' outcount + output = 'The number of semordnilap pairs is: ' outcount END diff --git a/Task/Semordnilap/TAV/semordnilap.tav b/Task/Semordnilap/TAV/semordnilap.tav new file mode 100644 index 0000000000..7b26db7ad4 --- /dev/null +++ b/Task/Semordnilap/TAV/semordnilap.tav @@ -0,0 +1,22 @@ +main(params):+ + seen =: new map + inwrds =: 0 + pairs =: 0 + palindromes =: 0 + ?# line =: file 'unixdict.txt' give lines + inwrds =+ 1 + wrd =: string line case to lower + rwrd =: string wrd from -1 length wrd.Count step -1 + ? wrd = rwrd + palindromes =+ 1 + ?^ + ? seen{rwrd} = () + seen{wrd} =: line \ not yet seen, remember + | + pairs =+ 1 + ? pairs < 7 + print wrd __ rwrd + + print pairs, "pairs, " nonl + print palindromes, "palindromes, " nonl + print inwrds, "input words." diff --git a/Task/Semordnilap/Tcl/semordnilap.tcl b/Task/Semordnilap/Tcl/semordnilap.tcl index 9fea9f4850..79c9bd49bc 100644 --- a/Task/Semordnilap/Tcl/semordnilap.tcl +++ b/Task/Semordnilap/Tcl/semordnilap.tcl @@ -14,10 +14,10 @@ foreach word $wordlist { # Find where a reversal exists foreach word $wordlist { if {[info exists reversed($word)] && $word ne [string reverse $word]} { - # Remove to prevent pairs from being printed twice - unset reversed([string reverse $word]) - # Add to collection of pairs - set pairs($word/[string reverse $word]) "dummy" + # Remove to prevent pairs from being printed twice + unset reversed([string reverse $word]) + # Add to collection of pairs + set pairs($word/[string reverse $word]) "dummy" } } set pairlist [array names pairs] ;# NB: pairs are in *arbitrary* order diff --git a/Task/Semordnilap/VBScript/semordnilap.vb b/Task/Semordnilap/VBScript/semordnilap.vb index f56f78ccdf..83c8f216a2 100644 --- a/Task/Semordnilap/VBScript/semordnilap.vb +++ b/Task/Semordnilap/VBScript/semordnilap.vb @@ -1,30 +1,30 @@ Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ - "\unixdict.txt",1) + "\unixdict.txt",1) Set objUnixDict = CreateObject("Scripting.Dictionary") Set objSemordnilap = CreateObject("Scripting.Dictionary") Do Until objInFile.AtEndOfStream - line = objInFile.ReadLine - If Len(line) > 1 Then - objUnixDict.Add line,"" - End If - reverse_line = StrReverse(line) - If reverse_line <> line And objUnixDict.Exists(reverse_line) Then - objSemordnilap.Add line, reverse_line - End If -Loop + line = objInFile.ReadLine + If Len(line) > 1 Then + objUnixDict.Add line,"" + End If + reverse_line = StrReverse(line) + If reverse_line <> line And objUnixDict.Exists(reverse_line) Then + objSemordnilap.Add line, reverse_line + End If +Loop 'Display the first 5 keys. k = 0 For Each Key In objSemordnilap.Keys - WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key) - WScript.StdOut.WriteLine - k = k + 1 - If k = 5 Then - Exit For - End If + WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key) + WScript.StdOut.WriteLine + k = k + 1 + If k = 5 Then + Exit For + End If Next WScript.StdOut.Write "Total Count: " & objSemordnilap.Count diff --git a/Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena b/Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena new file mode 100644 index 0000000000..01a42e41f5 --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/Agena/sequence-of-primes-by-trial-division.agena @@ -0,0 +1,35 @@ +scope # get sequences of primes using trial division + + # returns true if n is prime, false otherwise + local constant is_prime := proc( n :: number ) :: boolean + local result := n = 2 or ( odd n and n > 1 ); + for k from 3 to entier sqrt( n ) by 2 while result do + result := n mod k <> 0 + od; + return result + end; + + # returns the sequence of primes between p_start and p_end + local constant prime_sequence := proc( p_start :: number, p_end :: number ) :: sequence + local constant result := seq(); + for p from p_start to p_end do + if is_prime( p ) then result[ size result + 1 ] := p fi; + od; + return result + end; + + # test prime_sequence + local test_sequence, p_count; + test_sequence, p_count := prime_sequence( -9, 150 ), 0; + for p from 1 to size test_sequence do + printf( " %3d", test_sequence[ p ] ); + p_count +:= 1; if p_count mod 20 = 0 then print() fi + od; + print( " ..." ); + test_sequence, p_count := prime_sequence( 410, 550 ), 0; + for p from 1 to size test_sequence do + printf( " %3d", test_sequence[ p ] ); + p_count +:= 1; if p_count mod 20 = 0 then print() fi + od + +end diff --git a/Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto b/Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto new file mode 100644 index 0000000000..2184ebfaa7 --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/Pluto/sequence-of-primes-by-trial-division.pluto @@ -0,0 +1,29 @@ +do -- get sequences of primes using trial division + + local fmt = require( "fmt" ) -- RC formatting module + + -- returns true if n is prime, false otherwise + local function isPrime( n : number ) : boolean + local result : boolean = n == 2 or ( n % 2 == 1 and n > 1 ) + for k = 3, math.floor( math.sqrt( n ) ), 2 do + if not result then break end + result = n % k != 0 + end + return result + end + + -- returns the sequence of primes between pStart and pEnd + local function primeSequence( pStart : number, pEnd : number ) : table + local result : table = {} + for p = pStart, pEnd do + if isPrime( p ) then result:insert( p ) end + end + return result + end + + -- test primeSequence + fmt.tprint( " %3d", primeSequence( -9, 174 ), 20, "", "" ) + print( " ..." ) + fmt.tprint( " %3d", primeSequence( 410, 550 ), 20, "", "" ) + +end diff --git a/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division.rexx b/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division.rexx index 0e8372a795..bf6619e4ec 100644 --- a/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division.rexx +++ b/Task/Sequence-of-primes-by-trial-division/REXX/sequence-of-primes-by-trial-division.rexx @@ -1,4 +1,4 @@ --- 12 Apr 2025 +-- 28 Jul 2025 include Settings numeric digits 30 @@ -71,8 +71,4 @@ do i = 3 by 2 to Isqrt(xx) end return 1 -include Sequences -include Numbers -include Functions -include Constants -include Abend +include Math diff --git a/Task/Sequence-of-primorial-primes/REXX/sequence-of-primorial-primes.rexx b/Task/Sequence-of-primorial-primes/REXX/sequence-of-primorial-primes.rexx index d702668cb5..99f85cdbc1 100644 --- a/Task/Sequence-of-primorial-primes/REXX/sequence-of-primorial-primes.rexx +++ b/Task/Sequence-of-primorial-primes/REXX/sequence-of-primorial-primes.rexx @@ -1,7 +1,6 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings -call Time('r') say 'SEQUENCE OF PRIMORIAL PRIMES' say version say @@ -11,7 +10,7 @@ say Format(Time('e'),,3) 'seconds' exit GetPrimorials: -procedure expose prim. prmo. glob. +procedure expose prim. prmo. Memo. arg xx say 'Get enough primorials...' call Primorials(-xx) @@ -20,7 +19,7 @@ say return ShowPrimes: -procedure expose prmo. glob. +procedure expose prmo. Memo. arg xx say 'Index of first 15 primorial primes is...' n = 0 @@ -42,9 +41,4 @@ say n 'Miller-Rabin primality tests performed' say return -include Sequences -include Numbers -include Functions -include Special -include Constants -include Abend +include Math diff --git a/Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb b/Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb new file mode 100644 index 0000000000..bd087e9c78 --- /dev/null +++ b/Task/Set-consolidation/DuckDB/set-consolidation-1.duckdb @@ -0,0 +1 @@ +create type set as VARCHAR[]; diff --git a/Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb b/Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb new file mode 100644 index 0000000000..c5198f03a2 --- /dev/null +++ b/Task/Set-consolidation/DuckDB/set-consolidation-2.duckdb @@ -0,0 +1,17 @@ +create or replace function to_set(lst) as ( + list_sort(list_distinct(lst)) +); + +create or replace function list_update(lst, i, value) as ( + lst[1:i-1] || [value] || lst[i+1:] +); + +# This will work even if set1 and set2 are just lists +create or replace function set_intersection(set1, set2) as ( + list_sort(list_intersect(set1, set2)) +); + +# This will work even if set1 and set2 are just lists +create or replace function set_union(set1, set2) as ( + to_set( ( set1 || set2 ) ) +); diff --git a/Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb b/Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb new file mode 100644 index 0000000000..3761646cab --- /dev/null +++ b/Task/Set-consolidation/DuckDB/set-consolidation-3.duckdb @@ -0,0 +1,61 @@ +# If listofsets[j] can be merged with listofsets[i] +# then set the former to [] and the latter to the merger +create or replace function merge(listofsets, i, j) as ( + if (i=j, + listofsets, + case when list_has_any(listofsets[i]::set, listofsets[j]::set) -- casts needed here + then list_update( + list_update(listofsets, + i, + set_union(listofsets[i], listofsets[j])), + j, + []) + else listofsets + end) +); + +create or replace function merge_i(listofsets, i) as table ( + with recursive cte(j,s) as ( + select 1, listofsets::SET[] -- advisable!! + union all + select j+1, merge(s, i, j) + from cte + where j <= length(listofsets) + ) + select last(s order by j) as s from cte +); + +# Compute the consolidation as a set +# Note: as of DuckDB V1.1, the CTE here must be given a different name from the one in merge_i +create or replace function consolidation(listofsets) as ( + with recursive cte1(i,s) as ( + select 1, listofsets::SET[] + union all + select i+1, (from merge_i(s, i) limit 1) as s + from cte1 + where i <= length(listofsets) + ) + select to_set( + list_transform( + list_filter(last(s order by i), x -> length(x)>0), + x -> to_set(x))) as consolidation from cte1 +); + +# Verify that the consolidation of x is equal to to_set(y), +# so be sure that each of the elements of y is in fact a set. +create or replace function verify(x,y) as ( + select consolidation(x) = to_set(y) +); + +.print Example 1: +select verify( [ ['A','B'], ['C','D']], [ ['A','B'], ['C','D']] ) as "Example 1"; + +.print Example 2: +select verify( [ ['A','B'], ['B','D'] ], [['A', 'B','D']]) as "Example 2"; + +.print Example 3: +select verify( [['A','B'], ['C','D'], ['D','B']], [['A','B','C','D']]) as "Example 3"; + +.print Example 4: +select verify( [['H','I','K'], ['A','B'], ['C','D'], ['D','B'], ['F','G','H'] ], + [['A', 'B', 'C', 'D'], ['F', 'G', 'H', 'I', 'K']] ) as "Example 4"; diff --git a/Task/Set-consolidation/Pluto/set-consolidation.pluto b/Task/Set-consolidation/Pluto/set-consolidation.pluto new file mode 100644 index 0000000000..be665b398f --- /dev/null +++ b/Task/Set-consolidation/Pluto/set-consolidation.pluto @@ -0,0 +1,38 @@ +require "map" +require "table2" +local fmt = require "fmt" + +local function consolidate_sets(sets) + local size = #sets + local consolidated = table.rep(size, false) + for i = 1, size - 1 do + if !consolidated[i] then + repeat + local intersects = 0 + for j = i + 1, size do + if !consolidated[j] then + if !sets[i]:intersect(sets[j]):empty() then + sets[i]:merge(sets[j]) + consolidated[j] = true + ++intersects + end + end + end + until intersects == 0 + end + end + return range(1, size):filter(|i| -> !consolidated[i]):reorder():map(|i| -> sets[i]) +end + +local unconsolidated_sets = { + {set.of("A", "B"), set.of("C", "D")}, + {set.of("A", "B"), set.of("B", "D")}, + {set.of("A", "B"), set.of("C", "D"), set.of("D", "B")}, + {set.of("H", "I", "K"), set.of("A", "B"), set.of("C", "D"), + set.of("D", "B"), set.of("F", "G", "H")} +} +for unconsolidated_sets as sets do + fmt.print("Unconsolidated: %s", fmt.swrite(sets)) + fmt.print("Consolidated : %s", fmt.swrite(consolidate_sets(sets))) + print() +end diff --git a/Task/Set-consolidation/Wren/set-consolidation.wren b/Task/Set-consolidation/Wren/set-consolidation.wren index f5125e2bc8..bb9190b133 100644 --- a/Task/Set-consolidation/Wren/set-consolidation.wren +++ b/Task/Set-consolidation/Wren/set-consolidation.wren @@ -34,5 +34,5 @@ var unconsolidatedSets = [ ] for (sets in unconsolidatedSets) { System.print("Unconsolidated: %(sets)") - System.print("Cosolidated : %(consolidateSets.call(sets))\n") + System.print("Consolidated : %(consolidateSets.call(sets))\n") } diff --git a/Task/Set/DuckDB/set-1.duckdb b/Task/Set/DuckDB/set-1.duckdb new file mode 100644 index 0000000000..a0c39ee2d9 --- /dev/null +++ b/Task/Set/DuckDB/set-1.duckdb @@ -0,0 +1,5 @@ +create or replace table s (id INTEGER UNIQUE NOT NULL); +create or replace table t (id INTEGER UNIQUE NOT NULL); + +insert into s from generate_series(1,10); +insert into t from generate_series(5,15); diff --git a/Task/Set/DuckDB/set-2.duckdb b/Task/Set/DuckDB/set-2.duckdb new file mode 100644 index 0000000000..fc1c23c607 --- /dev/null +++ b/Task/Set/DuckDB/set-2.duckdb @@ -0,0 +1 @@ +from s union from t; diff --git a/Task/Set/DuckDB/set-3.duckdb b/Task/Set/DuckDB/set-3.duckdb new file mode 100644 index 0000000000..e520ef4afc --- /dev/null +++ b/Task/Set/DuckDB/set-3.duckdb @@ -0,0 +1 @@ +from s INTERSECT from t; diff --git a/Task/Set/DuckDB/set-4.duckdb b/Task/Set/DuckDB/set-4.duckdb new file mode 100644 index 0000000000..3684447a62 --- /dev/null +++ b/Task/Set/DuckDB/set-4.duckdb @@ -0,0 +1 @@ +select count() as n from (from s INTERSECT from t); diff --git a/Task/Set/DuckDB/set-5.duckdb b/Task/Set/DuckDB/set-5.duckdb new file mode 100644 index 0000000000..61893f127c --- /dev/null +++ b/Task/Set/DuckDB/set-5.duckdb @@ -0,0 +1 @@ +from s EXCEPT from t; diff --git a/Task/Set/DuckDB/set-6.duckdb b/Task/Set/DuckDB/set-6.duckdb new file mode 100644 index 0000000000..d79bd0f24d --- /dev/null +++ b/Task/Set/DuckDB/set-6.duckdb @@ -0,0 +1,2 @@ +select count() from + ( (from s EXCEPT from t) UNION (from t EXCEPT from s)); diff --git a/Task/Set/DuckDB/set-7.duckdb b/Task/Set/DuckDB/set-7.duckdb new file mode 100644 index 0000000000..dc01c7332a --- /dev/null +++ b/Task/Set/DuckDB/set-7.duckdb @@ -0,0 +1,2 @@ +select (EXISTS (from s where NOT EXISTS (from t where s.id=t.id))) or + (EXISTS (from t where NOT EXISTS (from s where s.id=t.id)) ); diff --git a/Task/Set/DuckDB/set-8.duckdb b/Task/Set/DuckDB/set-8.duckdb new file mode 100644 index 0000000000..ab49eb533d --- /dev/null +++ b/Task/Set/DuckDB/set-8.duckdb @@ -0,0 +1,2 @@ +select NOT EXISTS + (from s where NOT EXISTS (from t where s.id = t.id)); diff --git a/Task/Set/DuckDB/set-9.duckdb b/Task/Set/DuckDB/set-9.duckdb new file mode 100644 index 0000000000..cc3b678d11 --- /dev/null +++ b/Task/Set/DuckDB/set-9.duckdb @@ -0,0 +1 @@ +select NOT EXISTS (from s EXCEPT from t); diff --git a/Task/Set/Pluto/set.pluto b/Task/Set/Pluto/set.pluto new file mode 100644 index 0000000000..6c2563fb62 --- /dev/null +++ b/Task/Set/Pluto/set.pluto @@ -0,0 +1,46 @@ +require "map" +local fmt = require "fmt" + +local fruits = new set() +fruits:add("apple", "pear", "orange", "banana") +fmt.print("fruits : %s", fruits) +local fruits2 = new set() +fruits2:add("melon", "orange", "lemon", "gooseberry") +fmt.print("fruits2 : %s", fruits2) +print() +fmt.print("fruits contains 'banana' : %s", fruits:contains("banana")) +fmt.print("fruits2 contains 'elderberry' : %s", fruits2:contains("elderberry")) +print() + +fmt.print("Union : %s", fruits:union(fruits2)) +fmt.print("Intersection : %s", fruits:intersect(fruits2)) +fmt.print("Difference : %s", fruits:except(fruits2)) +print() + +fmt.print("fruits2 is a subset of fruits : %s", fruits2:subset(fruits)) +print() + +local fruits3 = fruits:copy() +fmt.print("fruits3 : %s", fruits3) +print() + +fmt.print("fruits2 and fruits are equal : %s", fruits2:same(fruits)) +fmt.print("fruits3 and fruits are equal : %s", fruits3:same(fruits)) +print() + +local fruits4 = new set() +fruits4:add("apple", "orange") +fmt.print("fruits4 : %s", fruits4) +print() +fmt.print("fruits3 is a proper subset of fruits : %s", fruits3:subset(fruits, true)) +fmt.print("fruits4 is a proper subset of fruits : %s", fruits4:subset(fruits, true)) +print() + +local fruits5 = new set() +fruits5:add("cherry", "blueberry", "raspberry") +fmt.print("fruits5 : %s", fruits5) +print() +fruits5:add("guava") +fmt.print("fruits5 + 'guava' : %s", fruits5) +fruits5:remove("cherry") +fmt.print("fruits5 - 'cherry' : %s", fruits5) diff --git a/Task/Shell-one-liner/ArkScript/shell-one-liner.ark b/Task/Shell-one-liner/ArkScript/shell-one-liner.ark new file mode 100644 index 0000000000..cea479c91c --- /dev/null +++ b/Task/Shell-one-liner/ArkScript/shell-one-liner.ark @@ -0,0 +1 @@ +$ arkscript -e '(print "hello world")' diff --git a/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area.jl b/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area-1.jl similarity index 100% rename from Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area.jl rename to Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area-1.jl diff --git a/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area-2.jl b/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area-2.jl new file mode 100644 index 0000000000..a4e5cdf49f --- /dev/null +++ b/Task/Shoelace-formula-for-polygonal-area/Julia/shoelace-formula-for-polygonal-area-2.jl @@ -0,0 +1,10 @@ +function shoelacearea2(x, y) + n = length(x) + abs(sum(x[mod1(i-1, n)] * y[i] - x[i] * y[mod1(i-1, n)] for i in 1:n)) / 2 +end + +x, y = [3, 5, 12, 9, 5], [4, 11, 8, 5, 6] + +using BenchmarkTools +@btime shoelacearea(x, y) +@btime shoelacearea2(x, y) diff --git a/Task/Shoelace-formula-for-polygonal-area/R/shoelace-formula-for-polygonal-area.r b/Task/Shoelace-formula-for-polygonal-area/R/shoelace-formula-for-polygonal-area.r new file mode 100644 index 0000000000..b924e4fa3b --- /dev/null +++ b/Task/Shoelace-formula-for-polygonal-area/R/shoelace-formula-for-polygonal-area.r @@ -0,0 +1,10 @@ +shoelace <- function(...){ + coords_list <- list(...) + xcoords <- sapply(coords_list, function(v) v[1]) + ycoords <- sapply(coords_list, function(v) v[2]) + lsum <- sum(xcoords*c(ycoords[-1], ycoords[1])) + rsum <- sum(ycoords*c(xcoords[-1], xcoords[1])) + abs(lsum-rsum)/2 +} + +shoelace(c(3,4), c(5,11), c(12,8), c(9,5), c(5,6)) diff --git a/Task/Short-circuit-evaluation/ArkScript/short-circuit-evaluation.ark b/Task/Short-circuit-evaluation/ArkScript/short-circuit-evaluation.ark new file mode 100644 index 0000000000..904db6e8a5 --- /dev/null +++ b/Task/Short-circuit-evaluation/ArkScript/short-circuit-evaluation.ark @@ -0,0 +1,17 @@ +(let a (fun (v) { + (print "a(" v ")") + v })) + +(let b (fun (v) { + (print "b(" v ")") + v })) + +(print "---") (and (a true) (b true)) +(print "---") (and (a false) (b true)) +(print "---") (and (a true) (b false)) +(print "---") (and (a false) (b false)) + +(print "---") (or (a true) (b true)) +(print "---") (or (a false) (b true)) +(print "---") (or (a true) (b false)) +(print "---") (or (a false) (b false)) diff --git a/Task/Show-ASCII-table/ArkScript/show-ascii-table.ark b/Task/Show-ASCII-table/ArkScript/show-ascii-table.ark new file mode 100644 index 0000000000..b489ed92ea --- /dev/null +++ b/Task/Show-ASCII-table/ArkScript/show-ascii-table.ark @@ -0,0 +1,15 @@ +(mut i 0) +(while (< i 16) { + (mut j (+ 32 i)) + (while (< j 128) { + (let k + (if (= 32 j) + "Spc" + (if (= 127 j) + "Del" + (string:chr j)))) + (puts (string:format "{:3} : {:<3}" j k)) + (set j (+ 16 j) )}) + (print "") + + (set i (+ 1 i)) }) diff --git a/Task/Show-the-epoch/DuckDB/show-the-epoch.duckdb b/Task/Show-the-epoch/DuckDB/show-the-epoch.duckdb new file mode 100644 index 0000000000..733dcc02cc --- /dev/null +++ b/Task/Show-the-epoch/DuckDB/show-the-epoch.duckdb @@ -0,0 +1 @@ +select to_timestamp(0); diff --git a/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy b/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy index a10991eb9c..8e75d38f54 100644 --- a/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy +++ b/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy @@ -2,14 +2,13 @@ x = 5 y = 10 ang = 60 glinewidth 0.5 +glineto x y # proc curv o l a . if o = 0 - px = x - py = y x += cos ang * l y += sin ang * l - gline px py x y + glineto x y else o -= 1 l /= 2 diff --git a/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy b/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy index 6e916e0a21..2bde0fa3a2 100644 --- a/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy +++ b/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy @@ -6,13 +6,12 @@ scale = 1 / (2 + cos 72 * 2) # proc pentagon x y side depth . if depth = 0 - move x y + gpenup + glineto x y for angle = 0 step 72 to 288 - px = x - py = y x += cos angle * side y += sin angle * side - gline px py x y + glineto x y . else side *= scale diff --git a/Task/Sierpinski-pentagon/FutureBasic/sierpinski-pentagon.basic b/Task/Sierpinski-pentagon/FutureBasic/sierpinski-pentagon.basic new file mode 100644 index 0000000000..c0c8fd2b80 --- /dev/null +++ b/Task/Sierpinski-pentagon/FutureBasic/sierpinski-pentagon.basic @@ -0,0 +1,77 @@ +// +// SIERPINSKY PENTAFLAKE +// +// FutureBasic 7.0.34, August 2025 R.W. +// + +Int mySize, margin, radius, pentas, myside +mySize = 560/2: margin = 6: pentas = 6 +radius = mySize - 2 * margin +dim as double myScale +//long side +CGFloat red, green, blue +CGFloat deg72 +deg72 = 72.0 * PI / 180 // 72 degrees in radians +colorref Colr + +// Create main window + +void local fn BuildMainWindow(wTag as NSInteger) + colorref wco + CGRect r + SInt32 wndStyleMask + wco = fn ColorBlack + wndStyleMask = NSWindowStyleMaskTitled + wndStyleMask += NSWindowStyleMaskClosable + r = fn CGRectMake( 0, 0, 560, 540 ) + window wTag, @" Sierpinsky PentaFlake ", r, wndStyleMask + WindowSetBackgroundColor(wTag, wco) + ViewSetFlipped( _WindowContentViewTag, YES ) + windowcenter (wTag) + AppSetAppearance(fn AppearanceNamed(NSAppearanceNameDarkAqua)) +end fn + +// Draw the pentagon recursively + +local fn DrawPentagon( xpos as int, ypos as int, side as Int, depth as long ) + int i + Float angle, dist + angle = 3 * deg72 + if depth == 0 + // get some funky colors + red = 0.2 + (rnd(65536)-1)/65536.0 + green = 0.2 + (rnd(65536)-1)/65536.0 + blue = 1 // on the bluish hue + Colr = fn ColorWithRGB(red,green,blue,1.0) + pen 1.0, Colr + line xpos, ypos + Oval fill (xpos, ypos, 1.0, 1.0),Colr + for i = 0 to 4 + xpos = xpos + int(side * cos(angle)) + ypos = ypos - int(side * sin(angle)) + line to xpos, ypos + angle = angle + deg72 + next + else + side = side * myScale + dist = side * (1 + cos(deg72) * 2) + for i = 0 to 4 + xpos = xpos + int(dist * cos(angle)) + ypos = ypos - int(dist * sin(angle)) + fn DrawPentagon( xpos, ypos, side, depth - 1 ) + angle = angle + deg72 + next + end if +end fn +// +//----------- main ---------------- +// + +fn BuildMainWindow(1) + +myScale = 1 / (2 + cos(deg72) * 2) +myside = radius * sin(pi/5) * 2 + +fn DrawPentagon( mySize, 3 * margin, myside, pentas-1 ) + +handleEvents diff --git a/Task/Sieve-of-Eratosthenes/DuckDB/sieve-of-eratosthenes.duckdb b/Task/Sieve-of-Eratosthenes/DuckDB/sieve-of-eratosthenes.duckdb new file mode 100644 index 0000000000..c75d3ba217 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/DuckDB/sieve-of-eratosthenes.duckdb @@ -0,0 +1,20 @@ +# Produce a table of primes less than or equal to mx +create or replace function sieve(mx) as table ( + with recursive + sieve(prime, n) AS ( + -- Base case: a table wherein the column labeled n ranges from 2 through mx. + -- The condition `prime = n` will serve as a flag that n is prime. + select 2, unnest(range(2, 1+mx)) as n + union all + -- remove multiples of the current prime + select prime + (case when prime = 2 then 1 else 2 end), n + from sieve + where n % prime != 0 + and prime <= mx -- constrain the recursion + ) + select prime + from sieve + where n = prime +); + +from sieve(19); diff --git a/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin b/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin index e3834b9432..8b622e9c35 100644 --- a/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin +++ b/Task/Sieve-of-Eratosthenes/Odin/sieve-of-eratosthenes.odin @@ -1,36 +1,58 @@ +#+feature dynamic-literals package main import "core:fmt" import "core:math" - +import "core:os" +import "core:strconv" main :: proc() { - n :: 120 - // outer loop with square root as limit - limit := i32(math.round_f16(math.sqrt_f16(n))) + // start with sieve.exe 120 to get primes until 120 + n:=0 + ok:=false + assert(len(os.args)==2,"Give integer as argument!") + if len(os.args) == 2 { + argument := os.args[1] + n, ok = strconv.parse_int(argument) + assert(ok, "Second argument was not an integer") + assert(n>2, "n must be bigger than two") + } - array : [n]i32 + result := [dynamic]i64{0} + defer delete(result) + + for i:=1;iwin + +main (args):+ + GTK init args + GTK main setup main window diff --git a/Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl b/Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl new file mode 100644 index 0000000000..c6486c39b6 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Julia/simulate-input-keyboard.jl @@ -0,0 +1,85 @@ +using Gtk4 +using Gtk4.GLib + + +""" App to create and initialize the GTK app object and set up the main window """ +mutable struct AppState + target_window::GtkWindow + target_widget::GtkTextView + target_buffer::GtkTextBuffer + function AppState() + window = GtkWindow("Keystroke Target Window") + set_gtk_property!(window, :default_width, 800) + set_gtk_property!(window, :default_height, 800) + set_gtk_property!(window, :resizable, true) + set_gtk_property!(window, :visible, true) + set_gtk_property!(window, :title, "Keystroke Simulation Target") + set_gtk_property!(window, :border_width, 10) + set_gtk_property!(window, :destroy_with_parent, true) + set_gtk_property!(window, :can_focus, true) + buffer = GtkTextBuffer() + set_gtk_property!(buffer, :text, "This is a target text area.\nSimulated keystrokes will appear here.\n\n") + widget = GtkTextView(buffer) + set_gtk_property!(widget, :can_focus, true) + set_gtk_property!(widget, :editable, true) + set_gtk_property!(widget, :cursor_visible, true) + scrolled = GtkScrolledWindow() + scrolled[] = widget + set_gtk_property!(scrolled, :margin_start, 10) + set_gtk_property!(scrolled, :margin_end, 10) + set_gtk_property!(scrolled, :margin_top, 10) + set_gtk_property!(scrolled, :margin_bottom, 10) + window[] = scrolled + show(window) + return new(window, widget, buffer) + end +end + +# the app +const APP = AppState() + +""" Send keystroke or char to a TextView widget using synthetic key events """ +function sendsynthetickey(widget, keychar::Char) + Gtk4.grab_focus(widget) + if isa(widget, GtkTextView) + buf = APP.target_buffer + cursor_iter = Gtk4.G_.get_iter_at_mark(buf, Gtk4.G_.get_insert(buf)) + Gtk4.insert!(buf, Ref(cursor_iter), string(keychar)) + return true + else + println("Widget is not a text view, cannot insert character directly.") + return false + end +end + +""" Send a string of text to the target widget """ +function typetowidget(text::AbstractString; delay = 0.4) + println("Sending text: \"$text\"") + for char in text + sendsynthetickey(APP.target_widget, char) + sleep(delay * rand() * rand()) + end +end + + +# Run a demo +println("Julia Keystroke Simulation with Gtk4.jl") +println("Press Ctrl+C to exit or close the target window.") +println("=======================================") +sleep(2) # Give time to see the window +try + typetowidget("Hello from Gtk4.jl!\n") + sleep(1) + typetowidget("This is a demonstration of simulated human typing input.\n") + typetowidget("Special characters: !@#\$%^&*()\n") + typetowidget("You can close this window to stop the simulation.\n\n") + while get_gtk_property(APP.target_window, :visible, Bool) + typetowidget(string(rand(['a':'z'; collect(" "); '\n']))) + end +catch e + print("Caught exception: $e...") +finally + print("Cleaning up...") + !isnothing(APP.target_window) && close(APP.target_window) + println("Done.") +end diff --git a/Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug b/Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug new file mode 100644 index 0000000000..8242a2a3f2 --- /dev/null +++ b/Task/Simulate-input-Mouse/FuncSug/simulate-input-mouse.funcsug @@ -0,0 +1,16 @@ +displayNewMessage(`Don't click the button. It will be clicked by the program.`) +waitSeconds(2) +displayNewMessage(``) + +parallel(select 1) || +||==================== + awaitClickBeep('#mybutton') +...--- + displayNewMessage('The button has been clicked') +||==================== + waitSeconds(2) + + # Simulate the click of a mouse + generateUserEvent('#mybutton', 'click') +...--- + displayNewMessage("I know you didn't do it!") diff --git a/Task/Singleton/Rust/singleton.rs b/Task/Singleton/Rust/singleton.rs new file mode 100644 index 0000000000..8dd6d79a52 --- /dev/null +++ b/Task/Singleton/Rust/singleton.rs @@ -0,0 +1,110 @@ +use std::sync::{Arc, Mutex, OnceLock}; + +// Thread-safe singleton using OnceLock (stable since Rust 1.70) +pub struct GlobalSingleton { + data: String, + counter: u32, +} + +impl GlobalSingleton { + // Private constructor + fn new() -> Self { + Self { + data: String::from("Singleton initialized"), + counter: 0, + } + } + + // Get the singleton instance + pub fn instance() -> Arc> { + static INSTANCE: OnceLock>> = OnceLock::new(); + + INSTANCE.get_or_init(|| { + Arc::new(Mutex::new(GlobalSingleton::new())) + }).clone() + } + + // Non-static methods that operate on the singleton instance + pub fn get_data(&self) -> &str { + &self.data + } + + pub fn set_data(&mut self, new_data: String) { + self.data = new_data; + } + + pub fn increment_counter(&mut self) { + self.counter += 1; + } + + pub fn get_counter(&self) -> u32 { + self.counter + } +} + +// Alternative implementation using std::sync::LazyLock (stable since Rust 1.80) +// This is the most modern and clean approach +use std::sync::LazyLock; + +static LAZY_SINGLETON: LazyLock>> = LazyLock::new(|| { + Arc::new(Mutex::new(GlobalSingleton::new())) +}); + +impl GlobalSingleton { + // Alternative method using LazyLock + pub fn lazy_instance() -> Arc> { + LAZY_SINGLETON.clone() + } +} + +fn main() { + // Usage example with OnceLock + { + let singleton = GlobalSingleton::instance(); + let mut instance = singleton.lock().unwrap(); + println!("Initial data: {}", instance.get_data()); + instance.increment_counter(); + instance.set_data("Modified data".to_string()); + println!("Counter: {}", instance.get_counter()); + } + + // Access from another scope - same instance + { + let singleton = GlobalSingleton::instance(); + let instance = singleton.lock().unwrap(); + println!("Data from another scope: {}", instance.get_data()); + println!("Counter from another scope: {}", instance.get_counter()); + } + + // Demonstrate thread safety + use std::thread; + + let handles: Vec<_> = (0..3) + .map(|i| { + thread::spawn(move || { + let singleton = GlobalSingleton::instance(); + let mut instance = singleton.lock().unwrap(); + instance.increment_counter(); + println!("Thread {} incremented counter to: {}", i, instance.get_counter()); + }) + }) + .collect(); + + for handle in handles { + handle.join().unwrap(); + } + + // Final state + let singleton = GlobalSingleton::instance(); + let instance = singleton.lock().unwrap(); + println!("Final counter value: {}", instance.get_counter()); + + // Demonstrate LazyLock alternative + println!("\n--- Using LazyLock alternative ---"); + { + let singleton = GlobalSingleton::lazy_instance(); + let mut instance = singleton.lock().unwrap(); + instance.set_data("LazyLock data".to_string()); + println!("LazyLock data: {}", instance.get_data()); + } +} diff --git a/Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr b/Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr new file mode 100644 index 0000000000..54836eaf67 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Crystal/singly-linked-list-element-definition.cr @@ -0,0 +1,7 @@ +class Node (T) + property data : T + property next : Node(T)? + + def initialize (@data, @next = nil) + end +end diff --git a/Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto b/Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto new file mode 100644 index 0000000000..3f7c87bb5b --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Pluto/singly-linked-list-element-definition.pluto @@ -0,0 +1,7 @@ +require "list" + +local s = slist.of(1, 2) +local n1 = s:node(1) +local n2 = s:node(2) +print($"node 1: value = {n1.value}, next = {tostring(n1.next?.value)}") +print($"node 2: value = {n2.value}, next = {tostring(n2.next?.value)}") diff --git a/Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr b/Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr new file mode 100644 index 0000000000..9438d84a74 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Crystal/singly-linked-list-element-insertion.cr @@ -0,0 +1,26 @@ +class Node (T) + property data : T + property next : Node(T)? + + def initialize (@data, @next = nil) + end + + def insert_after (new_data) + n = Node.new(new_data, @next) + @next = n + end + + def to_s (io) + io << data << "->" + if @next + @next.to_s(io) + else + io << "." + end + end +end + +n = Node.new('A', Node.new('B', Node.new('D'))) +puts n +n.insert_after('C') +puts n diff --git a/Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto b/Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto new file mode 100644 index 0000000000..b0fe671fbb --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Pluto/singly-linked-list-element-insertion.pluto @@ -0,0 +1,8 @@ +require "list" + +local s = slist.of("A", "B") +local ixs = s:find("A") -- always returns an array of indices even if we only want the first +if #ixs > 0 then + s:insert(ixs[1] + 1, "C") + print(s) +end diff --git a/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl b/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl index 94e8e839d1..afc8bf9680 100644 --- a/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl +++ b/Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.jl @@ -1,6 +1,9 @@ -Base.start(ll::LinkedList) = ll.head -Base.done(ll::LinkedList{T}, st::AbstractNode{T}) where T = st isa EmptyNode -Base.next(ll::LinkedList{T}, st::AbstractNode{T}) where T = st.data, st.next +Base.iterate(ll::LinkedList) = iterate(ll, ll.head) +Base.iterate(::LinkedList, st::Node) = st.data, st.next +Base.iterate(::LinkedList, ::EmptyNode) = nothing +Base.length(ll::LinkedList) = 1 + length(ll.next) +Base.length(ll::EmptyNode) = 0 +Base.eltype(::LinkedList{T}) where {T} = T lst = LinkedList{Int}() push!(lst, 1) diff --git a/Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto b/Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto new file mode 100644 index 0000000000..ecbff4bc4b --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Pluto/singly-linked-list-traversal.pluto @@ -0,0 +1,14 @@ +require "list" +local fmt = require "fmt" + +-- Create a singly-linked list containing the first 50 positive integers. +local s = slist.of(range(1, 50):unpack()) + +-- Now traverse and print them in tabular form. +local node = s:node(1) +local count = 0 +while node do + fmt.write("%4d ", node.value) + node = node.next + if ++count % 10 == 0 then print() end +end diff --git a/Task/Sleep/ArkScript/sleep.ark b/Task/Sleep/ArkScript/sleep.ark new file mode 100644 index 0000000000..6192fd5ea5 --- /dev/null +++ b/Task/Sleep/ArkScript/sleep.ark @@ -0,0 +1,4 @@ +(let amount (toNumber (input "ms to sleep for> "))) +(print "Sleeping...") +(sys:sleep amount) +(print "Awake!") diff --git a/Task/Sleep/FutureBasic/sleep.basic b/Task/Sleep/FutureBasic/sleep.basic new file mode 100644 index 0000000000..422f9faf93 --- /dev/null +++ b/Task/Sleep/FutureBasic/sleep.basic @@ -0,0 +1,14 @@ +include "NSlog.incl" + +local fn Sleep + printf @"\nReady to sleep...\n" + CFStringRef secondsToSleep = input %(100,100), @"Enter seconds to sleep: ", @"0123456789", YES, 3, _formatUnsignedFloat + fn ThreadSleepForTimeInterval( fn StringFloatValue( secondsToSleep ) ) + printf @"Waking from %@ seconds of sleep...", secondsToSleep +end fn + +window 1 + +fn Sleep + +HandleEvents diff --git a/Task/Sleep/Pluto/sleep.pluto b/Task/Sleep/Pluto/sleep.pluto new file mode 100644 index 0000000000..c9b9c71554 --- /dev/null +++ b/Task/Sleep/Pluto/sleep.pluto @@ -0,0 +1,5 @@ +io.write("Enter the amout of time to sleep in milliseconds: ") +local ms = io.read("n") +print("Sleeping...") +os.sleep(ms) -- pause this thread for 'ms' milliseconds. +print("Awake!") diff --git a/Task/Smarandache-prime-digital-sequence/ALGOL-68/smarandache-prime-digital-sequence.alg b/Task/Smarandache-prime-digital-sequence/ALGOL-68/smarandache-prime-digital-sequence.alg index c893723766..97508ec59c 100644 --- a/Task/Smarandache-prime-digital-sequence/ALGOL-68/smarandache-prime-digital-sequence.alg +++ b/Task/Smarandache-prime-digital-sequence/ALGOL-68/smarandache-prime-digital-sequence.alg @@ -87,16 +87,8 @@ BEGIN FI OD; print( ( newline ) ); - print( ( "100th Smarandache prime: ", whole( s100, 0 ), newline ) ); - print( ( "1000th Smarandache prime: ", whole( s1000, 0 ), newline ) ); - print( ( "Largest Smarandache prime under " - , whole( prime max, 0 ) - , ": " - , whole( s last, 0 ) - , " (Smarandache prime " - , whole( p last, 0 ) - , ")" - , newline - ) - ) + print( ( " 100th Smarandache prime: ", whole( s100, 0 ), newline ) ); + print( ( " 1000th Smarandache prime: ", whole( s1000, 0 ), newline ) ); + print( ( "Largest Smarandache prime under ", whole( prime max, 0 ) ) ); + print( ( ": ", whole( s last, 0 ), " (Smarandache prime ", whole( p last, 0 ), ")", newline ) ) END diff --git a/Task/Smarandache-prime-digital-sequence/Agena/smarandache-prime-digital-sequence.agena b/Task/Smarandache-prime-digital-sequence/Agena/smarandache-prime-digital-sequence.agena new file mode 100644 index 0000000000..7f3ab56397 --- /dev/null +++ b/Task/Smarandache-prime-digital-sequence/Agena/smarandache-prime-digital-sequence.agena @@ -0,0 +1,90 @@ +# find elements of the Smarandache prime-digital sequence +# - primes whose digits are all primes +# Uses the observations that the final digit of 2 or more digit Smarandache +# primes must be 3 or 7 and the only prime_digits are 2, 3, 5 and 7 +scope + # construct a sieve of primes up to 10 000 000 + local constant prime_max := 10_000_000; + local prime; create register prime( prime_max ); + for i to prime_max do prime[ i ] := i mod 2 = 1 od; + prime[ 1 ], prime[ 2 ] := false, true; + for s from 3 to entier sqrt( prime_max ) by 2 do + if prime[ s ] then + for p from s * s to prime_max by s do prime[ p ] := false od + fi + od; + # consruct the Smarandache primes up to 10 000 000 + local smarandache; create register smarandache( prime_max ); + for i to size prime do smarandache[ i ] := false od; + local constant prime_digits := reg( 2, 3, 5, 7 ); + local digits := reg( 0, 0, 0, 0, 0, 0, 0 ); + + # tests whether the current digits form a Smarandache prime + local constant try_smarandache := proc() is + local possible_prime := 0; + for i to size digits do + possible_prime *:= 10; + possible_prime +:= digits[ i ] + od; + smarandache[ possible_prime ] := prime[ possible_prime ] + end; + # tests whether the current digits plus 3 or 7 form a Smarandache prime + local constant try_smarandache_3_or_7 := proc() is + digits[ size digits ] := 3; + try_smarandache(); + digits[ size digits ] := 7; + try_smarandache(); + end; + # the 1 digit primes are all Smarandache primes + for d7 to size prime_digits do smarandache[ prime_digits[ d7 ] ] := true od; + # try the possible 2, 3, etc. digit numbers composed of prime_digits + for d6 to size prime_digits do + digits[ 6 ] := prime_digits[ d6 ]; + try_smarandache_3_or_7(); + for d5 to size prime_digits do + digits[ 5 ] := prime_digits[ d5 ]; + try_smarandache_3_or_7(); + for d4 to size prime_digits do + digits[ 4 ] := prime_digits[ d4 ]; + try_smarandache_3_or_7(); + for d3 to size prime_digits do + digits[ 3 ] := prime_digits[ d3 ]; + try_smarandache_3_or_7(); + for d2 to size prime_digits do + digits[ 2 ] := prime_digits[ d2 ]; + try_smarandache_3_or_7(); + for d1 to size prime_digits do + digits[ 1 ] := prime_digits[ d1 ]; + try_smarandache_3_or_7(); + od; + digits[ 1 ] := 0 + od; + digits[ 2 ] := 0 + od; + digits[ 3 ] := 0 + od; + digits[ 4 ] := 0 + od; + digits[ 5 ] := 0 + od; + # print some Smarandache primes + local count, s100, s1000, s_last, p_last := 0, 0, 0, 0, 0; + io.write( "First 25 Smarandache primes:\n" ); + for i to size smarandache do + if smarandache[ i ] then + count +:= 1; + s_last, p_last := i, count; + if count <= 25 then + printf( " %d", i ) + elif count = 100 then + s100 := i + elif count = 1000 then + s1000 := i + fi + fi + od; + printf( "\n 100th Smarandache prime: %d", s100 ); + printf( "\n 1000th Smarandache prime: %d", s1000 ); + printf( "\nLargest Smarandache prime under %d: %d", prime_max, s_last ) + printf( " (Smarandache prime %d)\n" , p_last ) +end diff --git a/Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto b/Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto new file mode 100644 index 0000000000..3c611ffcb9 --- /dev/null +++ b/Task/Smarandache-prime-digital-sequence/Pluto/smarandache-prime-digital-sequence.pluto @@ -0,0 +1,27 @@ +do --[[ find elements of the Smarandache prime-digital sequence + - primes whose digits are all primes + Translated from the Lua sample, extending to the 1000th Smarandache prime + ]] + + -- SIEVE: sieve the primes to 5 000 000 + local sieve, S = {}, 5_000_000 + for i = 2,S do sieve[i]=true end + for i = 2,S do + if sieve[i] then + for j=i*i,S,i do sieve[j]=nil end + end + end + + -- TASKS: + local digs, cans, spds, N = {2,3,5,7}, {0}, {}, 1000 + -- the first trip through the following loop adds the single digit primes to cans + -- subsequent trips add the previous candidates * 10 + the final prime digits + while #spds < N do + local c = cans:remove(1) + for _,d in ipairs(digs) do cans:insert(c*10+d) end + if sieve[c] then spds:insert(c) end + end + print(" 1-25: " .. spds:slice(1,25):concat(" ")) + print(" 100th: " .. spds[ 100]) + print("1000th: " .. spds[1000]) +end diff --git a/Task/Snake/Liberty-BASIC/snake.basic b/Task/Snake/Liberty-BASIC/snake.basic new file mode 100644 index 0000000000..e8916fe2bf --- /dev/null +++ b/Task/Snake/Liberty-BASIC/snake.basic @@ -0,0 +1,191 @@ +' ================================ +' SIMPLE SNAKE GAME - Liberty BASIC +' ================================ + +' Graphics constants +global cellSize, gridWidth, gridHeight +global snakeLength, foodX, foodY, gamespeed +global gridOffsetY, score + +cellSize = 20 +gridWidth = 20 +gridHeight = 20 +gridOffsetY = 20 +foodX = 0 +foodY = 0 +gamespeed = 333 +score = 0 + +' Movement directions +global dirX, dirY +dirX = 1 : dirY = 0 ' start moving right + +' Snake body array +dim snakeX(400) +dim snakeY(400) +snakeLength = 5 + +' Initialize snake position in center +for i = 1 to snakeLength + snakeX(i) = 10 - i + snakeY(i) = 10 +next + +' Create first food position +call newFood + +' Open graphics window +WindowWidth = cellSize * gridWidth + 10 +WindowHeight = cellSize * gridHeight + 60 +open "SNAKE GAME - WASD to Move" for graphics_nsb_nf as #g +#g "trapclose [quit]" +#g "down; fill white; flush" + +' Force focus +#g "setfocus" + +' Enable character input +#g "when characterInput [keypress]" + +' Start game timer +[startGame] +timer gamespeed, [gameTick] + +wait + +[gameTick] + + ' Move snake segments + for i = snakeLength to 2 step -1 + snakeX(i) = snakeX(i-1) + snakeY(i) = snakeY(i-1) + next + + ' Head moves in current direction + snakeX(1) = snakeX(1) + dirX + snakeY(1) = snakeY(1) + dirY + + ' Wall collision ends game + if snakeX(1) < 0 or snakeX(1) >= gridWidth _ + or snakeY(1) < 0 or snakeY(1) >= gridHeight then + call gameOver + wait + end if + + ' Check self collision + for i = 2 to snakeLength + if snakeX(1) = snakeX(i) and snakeY(1) = snakeY(i) then + call gameOver + wait + end if + next + + ' Check food collision + if snakeX(1) = foodX and snakeY(1) = foodY then + snakeLength = snakeLength + 1 + score = score + 10 + + ' Initialize new tail segment at same spot as previous tail + snakeX(snakeLength) = snakeX(snakeLength - 1) + snakeY(snakeLength) = snakeY(snakeLength - 1) + + ' Speed up the game + timer 0 + gamespeed = max(gamespeed - 5, 150) + timer gamespeed, [gameTick] + + call newFood + end if + + call redraw +wait + +[keypress] + key$ = Inkey$ + key$ = lower$(key$) + select case key$ + case "w" + if dirY <> 1 then dirX = 0 : dirY = -1 + case "a" + if dirX <> 1 then dirX = -1 : dirY = 0 + case "s" + if dirY <> -1 then dirX = 0 : dirY = 1 + case "d" + if dirX <> -1 then dirX = 1 : dirY = 0 + case chr$(27) ' ESC + call gameOver + wait + end select +wait + +[quit] + close #g + end + +sub redraw + ' Clear screen + #g "cls" + + ' Draw top banner background + #g "color lightgray" + #g, "backcolor lightgray" + #g "place 0 0" + #g "boxfilled "; (gridWidth * cellSize); " "; gridOffsetY + + ' Draw banner text + #g "color black" + #g "font Courier_New 10" + #g "place 5 15" + #g "\"; "Score: "; score; " Speed: "; gamespeed; "ms" + + ' Draw food + call drawBlock foodX, foodY, "red" + + ' Draw snake + for i = 1 to snakeLength + call drawBlock snakeX(i), snakeY(i), "green" + next + + #g "flush" +end sub + +sub drawBlock x, y, color$ + x1 = x * cellSize + y1 = gridOffsetY + y * cellSize + x2 = x1 + cellSize + y2 = y1 + cellSize + + #g "color "; color$ + #g, "backcolor "; color$ + #g "place "; x1; " "; y1 + #g "boxfilled "; x2; " "; y2 +end sub + +sub newFood + overlap = 1 + while overlap = 1 + foodX = int(rnd(0) * gridWidth) + foodY = int(rnd(0) * gridHeight) + overlap = 0 + for i = 1 to snakeLength + if foodX = snakeX(i) and foodY = snakeY(i) then + overlap = 1 + exit for + end if + next + wend +end sub + +sub gameOver + timer 0 + #g "cls" + #g "color black" + #g, "backcolor white" + #g "place 110 200" + #g "font Courier_New 24 bold" + #g "\"; "GAME OVER!" + #g "place 110 250" + #g "font Courier_New 16" + #g "\"; "Score: "; score + #g "flush" +end sub diff --git a/Task/Sokoban/JavaScript/sokoban.js b/Task/Sokoban/JavaScript/sokoban.js new file mode 100644 index 0000000000..f5889d7643 --- /dev/null +++ b/Task/Sokoban/JavaScript/sokoban.js @@ -0,0 +1,130 @@ +class Sokoban { + constructor(board) { + this.nCols = board[0].length; + let destBuf = ''; + let currBuf = ''; + + for (let r = 0; r < board.length; r++) { + for (let c = 0; c < this.nCols; c++) { + const ch = board[r].charAt(c); + + destBuf += (ch !== '$' && ch !== '@') ? ch : ' '; + currBuf += (ch !== '.') ? ch : ' '; + + if (ch === '@') { + this.playerX = c; + this.playerY = r; + } + } + } + this.destBoard = destBuf; + this.currBoard = currBuf; + } + + move(x, y, dx, dy, trialBoard) { + const newPlayerPos = (y + dy) * this.nCols + x + dx; + + if (trialBoard.charAt(newPlayerPos) !== ' ') { + return null; + } + + const trial = trialBoard.split(''); + trial[y * this.nCols + x] = ' '; + trial[newPlayerPos] = '@'; + + return trial.join(''); + } + + push(x, y, dx, dy, trialBoard) { + const newBoxPos = (y + 2 * dy) * this.nCols + x + 2 * dx; + + if (trialBoard.charAt(newBoxPos) !== ' ') { + return null; + } + + const trial = trialBoard.split(''); + trial[y * this.nCols + x] = ' '; + trial[(y + dy) * this.nCols + x + dx] = '@'; + trial[newBoxPos] = '$'; + + return trial.join(''); + } + + isSolved(trialBoard) { + for (let i = 0; i < trialBoard.length; i++) { + if ((this.destBoard.charAt(i) === '.') !== (trialBoard.charAt(i) === '$')) { + return false; + } + } + return true; + } + + solve() { + class Board { + constructor(cur, sol, x, y) { + this.cur = cur; + this.sol = sol; + this.x = x; + this.y = y; + } + } + + const dirLabels = [['u', 'U'], ['r', 'R'], ['d', 'D'], ['l', 'L']]; + const dirs = [[0, -1], [1, 0], [0, 1], [-1, 0]]; + + const history = new Set(); + const open = []; + + history.add(this.currBoard); + open.push(new Board(this.currBoard, "", this.playerX, this.playerY)); + + while (open.length > 0) { + const item = open.shift(); // poll() equivalent + const cur = item.cur; + const sol = item.sol; + const x = item.x; + const y = item.y; + + for (let i = 0; i < dirs.length; i++) { + let trial = cur; + const dx = dirs[i][0]; + const dy = dirs[i][1]; + + // are we standing next to a box? + if (trial.charAt((y + dy) * this.nCols + x + dx) === '$') { + // can we push it? + trial = this.push(x, y, dx, dy, trial); + if (trial !== null) { + // or did we already try this one? + if (!history.has(trial)) { + const newSol = sol + dirLabels[i][1]; + + if (this.isSolved(trial)) { + return newSol; + } + + open.push(new Board(trial, newSol, x + dx, y + dy)); + history.add(trial); + } + } + // otherwise try changing position + } else { + trial = this.move(x, y, dx, dy, trial); + if (trial !== null) { + if (!history.has(trial)) { + const newSol = sol + dirLabels[i][0]; + open.push(new Board(trial, newSol, x + dx, y + dy)); + history.add(trial); + } + } + } + } + } + return "No solution"; + } +} + +// Example usage +const level = "#######,# #,# #,#. # #,#. $$ #,#.$$ #,#.# @#,#######"; +const sokoban = new Sokoban(level.split(",")); +console.log(sokoban.solve()); diff --git a/Task/Sokoban/Rust/sokoban.rs b/Task/Sokoban/Rust/sokoban.rs new file mode 100644 index 0000000000..3996412185 --- /dev/null +++ b/Task/Sokoban/Rust/sokoban.rs @@ -0,0 +1,173 @@ +use std::collections::{HashSet, VecDeque}; +use regex::Regex; + +#[derive(Debug, Clone)] +struct Board { + s_data: Vec>, + d_data: Vec>, + px: usize, + py: usize, +} + +impl Board { + fn new(board_str: &str) -> Self { + let pattern = Regex::new(r"([^\n]+)\n?").unwrap(); + let mut data = Vec::new(); + let mut w = 0; + + for cap in pattern.captures_iter(board_str) { + let line = cap[1].to_string(); + w = w.max(line.len()); + data.push(line); + } + + let mut s_data = Vec::new(); + let mut d_data = Vec::new(); + let mut px = 0; + let mut py = 0; + + for (v, line) in data.iter().enumerate() { + let mut s_temp = Vec::new(); + let mut d_temp = Vec::new(); + + for u in 0..w { + let (s, d) = if u >= line.len() { + (' ', ' ') + } else { + let c = line.chars().nth(u).unwrap(); + let mut s = ' '; + let mut d = ' '; + + match c { + '#' => s = '#', + '.' | '*' | '+' => s = '.', + _ => {} + } + + match c { + '@' | '+' => { + d = '@'; + px = u; + py = v; + } + '$' | '*' => d = '*', + _ => {} + } + + (s, d) + }; + + s_temp.push(s); + d_temp.push(d); + } + + s_data.push(s_temp); + d_data.push(d_temp); + } + + Board { + s_data, + d_data, + px, + py, + } + } + + fn move_player(&self, x: usize, y: usize, dx: i32, dy: i32, data: &mut Vec>) -> bool { + let new_x = (x as i32 + dx) as usize; + let new_y = (y as i32 + dy) as usize; + + if self.s_data[new_y][new_x] == '#' || data[new_y][new_x] != ' ' { + return false; + } + + data[y][x] = ' '; + data[new_y][new_x] = '@'; + + true + } + + fn push_box(&self, x: usize, y: usize, dx: i32, dy: i32, data: &mut Vec>) -> bool { + let new_x = (x as i32 + dx) as usize; + let new_y = (y as i32 + dy) as usize; + let box_x = (x as i32 + 2 * dx) as usize; + let box_y = (y as i32 + 2 * dy) as usize; + + if self.s_data[box_y][box_x] == '#' || data[box_y][box_x] != ' ' { + return false; + } + + data[y][x] = ' '; + data[new_y][new_x] = '@'; + data[box_y][box_x] = '*'; + + true + } + + fn is_solved(&self, data: &Vec>) -> bool { + for (v, row) in data.iter().enumerate() { + for (u, &cell) in row.iter().enumerate() { + if (self.s_data[v][u] == '.') != (cell == '*') { + return false; + } + } + } + true + } + + fn solve(&self) -> String { + let mut visited = HashSet::new(); + let mut open = VecDeque::new(); + + open.push_back((self.d_data.clone(), String::new(), self.px, self.py)); + visited.insert(self.d_data.clone()); + + let dirs = [ + (0, -1, 'u', 'U'), + (1, 0, 'r', 'R'), + (0, 1, 'd', 'D'), + (-1, 0, 'l', 'L'), + ]; + + while let Some((cur, c_sol, x, y)) = open.pop_front() { + for &(dx, dy, move_char, push_char) in &dirs { + let mut temp = cur.clone(); + let new_x = (x as i32 + dx) as usize; + let new_y = (y as i32 + dy) as usize; + + if temp[new_y][new_x] == '*' { + if self.push_box(x, y, dx, dy, &mut temp) && !visited.contains(&temp) { + if self.is_solved(&temp) { + return c_sol + &push_char.to_string(); + } + open.push_back((temp.clone(), c_sol.clone() + &push_char.to_string(), new_x, new_y)); + visited.insert(temp); + } + } else if self.move_player(x, y, dx, dy, &mut temp) && !visited.contains(&temp) { + if self.is_solved(&temp) { + return c_sol + &move_char.to_string(); + } + open.push_back((temp.clone(), c_sol.clone() + &move_char.to_string(), new_x, new_y)); + visited.insert(temp); + } + } + } + + "No solution".to_string() + } +} + +fn main() { + let level = "#######\n\ + # #\n\ + # #\n\ + #. # #\n\ + #. $$ #\n\ + #.$$ #\n\ + #.# @#\n\ + #######"; + + let board = Board::new(level); + println!("{}\n", level); + println!("{}", board.solve()); +} diff --git a/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg b/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg index 9f56d61de4..6dc094d11d 100644 --- a/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg +++ b/Task/Soloways-recurring-rainfall/ALGOL-68/soloways-recurring-rainfall.alg @@ -1,4 +1,4 @@ -BEGIN # read a sequence of integers, terminated by 99999 and outpout their average # +BEGIN # read a sequence of integers, terminated by 99999 and output their average # INT end value = 99999; INT sum := 0; INT count := 0; diff --git a/Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk b/Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk new file mode 100644 index 0000000000..0bea5f41a6 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/AWK/soloways-recurring-rainfall.awk @@ -0,0 +1,24 @@ +BEGIN { + if (!sentinel) sentinel = 99999 + print("Enter the rainfall values (" sentinel " to quit):") +} + +$0 == sentinel { + exit +} + +/^-?[0-9]+$/ { + total += $1 + count++ + next +} + +{ + print("Ignoring \"" $0 "\", please enter only integers.") +} + +END { + if (count > 0) { + print("The average rainfall is", total / count) + } +} diff --git a/Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena b/Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena new file mode 100644 index 0000000000..eefa3f5725 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Agena/soloways-recurring-rainfall.agena @@ -0,0 +1,27 @@ +scope # read a sequence of integers, terminated by 99999 and output their average + local constant endValue := 99999; + local sum, count, n := 0, 0, 0; + + while n <> endValue do + printf( "Enter rainfall (integer) or %d to quit: ", endValue ); + try + local v := io.read(); + if v = null then + print( "End of input detected" ); + n := endValue + else + n := tonumber( v ); + if not isint( n ) then + error( "Not an integer" ) + elif n <> endValue then + sum +:= n; + count +:= 1; + printf( "\t\t\t\t\t\tNew average: %f\n", sum / count ) + fi + fi + catch + print( "Please enter an integer" ); + n := 0 + yrt + od +end diff --git a/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cobol b/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cobol new file mode 100644 index 0000000000..94fe0c07b8 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cobol @@ -0,0 +1,22 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. SOLOWAY. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 AVERAGE PIC 9(9)V9(9) VALUE ZERO. + 01 AMOUNT PIC 9(9) VALUE ZERO. + 01 CURRENT PIC 9(9). + 01 OUTPUT-VAL PIC Z(8)9.9(9). + + PROCEDURE DIVISION. + READ-VALUE. + ACCEPT CURRENT. + IF CURRENT IS EQUAL TO 99999, GO TO DONE. + ADD 1 TO AMOUNT. + COMPUTE AVERAGE = + AVERAGE * (AMOUNT - 1) / AMOUNT + CURRENT / AMOUNT. + GO TO READ-VALUE. + DONE. + MOVE AVERAGE TO OUTPUT-VAL. + DISPLAY OUTPUT-VAL. + STOP RUN. diff --git a/Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr b/Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr new file mode 100644 index 0000000000..026e8330b8 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Crystal/soloways-recurring-rainfall.cr @@ -0,0 +1,20 @@ +require "big" + +sum = 0.to_big_i +cnt = 0 + +puts "At each prompt enter an integer between -2³¹ and 2³¹-1" +puts "and I'll tell you the cumulative average. Enter 99999 to quit." + +loop do + print "> "; STDOUT.flush + begin + num = (gets || break).to_i + break if num == 99999 + sum += num + cnt += 1 + puts "CA=#{sum / cnt}" + rescue + puts "invalid input ignored" + end +end diff --git a/Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto b/Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto new file mode 100644 index 0000000000..286d039fd3 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Pluto/soloways-recurring-rainfall.pluto @@ -0,0 +1,14 @@ +local n = 0 +local sum = 0 +while true do + io.write("Enter integral rainfall (99999 to quit): ") + local i = tonumber(io.read()) + if !(i and i % 1 == 0) then + print("Must be an integer, try again.") + continue + end + if i == 99999 then break end + ++n + sum += i + print($" The current average rainfall is {sum / n}") +end diff --git a/Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r b/Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r new file mode 100644 index 0000000000..8ecb9b9c83 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/R/soloways-recurring-rainfall.r @@ -0,0 +1,22 @@ +soloway <- function(){ + vals <- numeric(0) + repeat{ + entry <- readline(prompt="Enter integer rainfall value (99999 to quit): ") + if(is.na(as.numeric(entry))){ + cat("Input must be numeric, please re-enter", "\n") + entry <- NULL + } + entry <- as.numeric(entry) + if(length(entry)>0){ + if(entry%%1!=0){ + cat("Input must be an integer, please re-enter", "\n") + entry <- NULL + } + } + vals <- c(vals, entry) + if(99999 %in% vals) break + cat("Average rainfall:", mean(vals)) + } +} + +soloway() diff --git a/Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js b/Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js new file mode 100644 index 0000000000..a9d30c8b93 --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/JavaScript/solve-a-hopido-puzzle.js @@ -0,0 +1,146 @@ +class Node { + constructor() { + this.val = 0; + this.neighbors = 0; + } +} + +class NSolver { + constructor() { + this.dx = new Array(8); + this.dy = new Array(8); + this.wid = 0; + this.hei = 0; + this.max = 0; + this.arr = null; + + this.dx[0] = -2; this.dy[0] = -2; this.dx[1] = -2; this.dy[1] = 2; + this.dx[2] = 2; this.dy[2] = -2; this.dx[3] = 2; this.dy[3] = 2; + this.dx[4] = -3; this.dy[4] = 0; this.dx[5] = 3; this.dy[5] = 0; + this.dx[6] = 0; this.dy[6] = -3; this.dx[7] = 0; this.dy[7] = 3; + } + + solve(puzz, maxWid) { + if (puzz.length < 1) return; + + this.wid = maxWid; + this.hei = Math.floor(puzz.length / this.wid); + const len = this.wid * this.hei; + let c = 0; + this.max = len; + + this.arr = new Array(len); + for (let i = 0; i < len; i++) { + this.arr[i] = new Node(); + } + + for (let i = 0; i < puzz.length; i++) { + if (puzz[i] === "*") { + this.max--; + this.arr[c++].val = -1; + continue; + } + // Handle both "." and number cases properly + this.arr[c].val = puzz[i] === "." ? 0 : parseInt(puzz[i]); + c++; + } + + this.solveIt(); + + c = 0; + for (let i = 0; i < puzz.length; i++) { + if (puzz[i] === ".") { + puzz[i] = this.arr[c].val.toString(); + } + c++; + } + + return puzz; + } + + search(x, y, w) { + if (w > this.max) return true; + + const n = this.arr[x + y * this.wid]; + n.neighbors = this.getNeighbors(x, y); + + for (let d = 0; d < 8; d++) { + if (n.neighbors & (1 << d)) { + const a = x + this.dx[d]; + const b = y + this.dy[d]; + if (this.arr[a + b * this.wid].val === 0) { + this.arr[a + b * this.wid].val = w; + if (this.search(a, b, w + 1)) return true; + this.arr[a + b * this.wid].val = 0; + } + } + } + return false; + } + + getNeighbors(x, y) { + let c = 0; + for (let xx = 0; xx < 8; xx++) { + const a = x + this.dx[xx]; + const b = y + this.dy[xx]; + if (a < 0 || b < 0 || a >= this.wid || b >= this.hei) continue; + if (this.arr[a + b * this.wid].val > -1) c |= (1 << xx); + } + return c; + } + + solveIt() { + const result = this.findStart(); + if (result.z === 99999) { + console.log("\nCan't find start point!\n"); + return; + } + this.search(result.x, result.y, result.z + 1); + } + + findStart() { + for (let b = 0; b < this.hei; b++) { + for (let a = 0; a < this.wid; a++) { + if (this.arr[a + this.wid * b].val === 0) { + const x = a; + const y = b; + const z = 1; + this.arr[a + this.wid * b].val = z; + return { x, y, z }; + } + } + } + return { x: 0, y: 0, z: 99999 }; + } +} + +function main() { + const wid = 7; + const p = "* . . * . . * . . . . . . . . . . . . . . * . . . . . * * * . . . * * * * * . * * *"; + const puzz = p.split(" "); + + const solver = new NSolver(); + const result = solver.solve(puzz, wid); + + let c = 0; + let output = ""; + + for (let i = 0; i < result.length; i++) { + if (result[i] !== "*" && result[i] !== ".") { + const num = parseInt(result[i]); + if (!isNaN(num) && num < 10) output += "0"; + output += result[i] + " "; + } else { + output += " "; + } + + if (++c >= wid) { + output += "\n"; + c = 0; + } + } + + console.log(output); +} + +main(); diff --git a/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py index fdc2e475cb..46a462c40b 100644 --- a/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py +++ b/Task/Solve-a-Numbrix-puzzle/Python/solve-a-numbrix-puzzle-1.py @@ -1,98 +1,152 @@ -from sys import stdout -neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] -exists = [] -lastNumber = 0 -wid = 0 -hei = 0 +import re -def find_next(pa, x, y, z): - for i in range(4): - a = x + neighbours[i][0] - b = y + neighbours[i][1] - if wid > a > -1 and hei > b > -1: - if pa[a][b] == z: - return a, b +class HidatoPuzzle: + """ Generic Hidato type puzzle solver, used here for Numbrix puzzles """ - return -1, -1 + def __init__(self, board_text: str, allowed_moves: list[list[int]]): + """ initialize the puzzle from a board and the move rules + . means blocked, 0 or _ means open, numeric > 0 are fixed points + """ + lines = board_text.strip().split('\n') + self.nrows, self.ncols = len(lines), len(re.split(r'\s+', lines[0])) + self.board = [[-1] * self.ncols for _ in range(self.nrows)] + self.allowed_moves = allowed_moves + self.starts = [] + self.fixed = [] + self.solutions = [] + self.maxmoves = 0 + for i, line in enumerate(lines): + for j, s in enumerate(re.split(r'\s+', line.strip())): + c = s[0] + if c == '_' or c == '0' and len(s) == 1: + self.board[i][j] = 0 + self.maxmoves += 1 + elif c == '.': + continue # remains -1, blocked + else: # get digits and add to fixed numeric positions as > 0 + self.board[i][j] = int(s) + self.fixed.append(self.board[i][j]) + if self.board[i][j] == 1: + self.starts.append((i, j)) + self.maxmoves += 1 + self.fixed.sort() + if len(self.starts) != 1: # 1 is not fixed, so we can start at any (0) + self.starts = [] + for i in range(self.nrows): + for j in range(self.ncols): + if self.board[i][j] == 0: + self.starts.append((i, j)) -def find_solution(pa, x, y, z): - if z > lastNumber: - return 1 - if exists[z] == 1: - s = find_next(pa, x, y, z) - if s[0] < 0: - return 0 - return find_solution(pa, s[0], s[1], z + 1) + def solve(self): + """ solve puzzle: if start (1) not fixed may give multiple solutions """ + for xy in self.starts: + saved = self.board + self.board = [r[:] for r in self.board] + if self.dfs(xy[0], xy[1], 1): + self.solutions.append(self.board) + self.board = saved - for i in range(4): - a = x + neighbours[i][0] - b = y + neighbours[i][1] - if wid > a > -1 and hei > b > -1: - if pa[a][b] == 0: - pa[a][b] = z - r = find_solution(pa, a, b, z + 1) - if r == 1: - return 1 - pa[a][b] = 0 + return len(self.solutions) > 0 - return 0 + def dfs(self, row, col, current_target): + """ depth first search for a solution """ + if current_target > self.maxmoves: + return True + n = self.board[row][col] + if not n in (0, current_target) or n == 0 and current_target in self.fixed: + return False + backnum = n # backup board[row][col] value before trying change + self.board[row][col] = current_target + for move in self.allowed_moves: + i, j = row + move[0], col + move[1] + if 0 <= i < self.nrows and 0 <= j < self.ncols and \ + self.dfs(i, j, current_target + 1): + return True + self.board[row][col] = backnum # restore board to original state + return False -def solve(pz, w, h): - global lastNumber, wid, hei, exists + def print_matrix(self, mat, emptysquare=" 0 ", blocked=" . "): + """ pretty print 2D matrix with substitution for 0 or blocked values """ + d = {-1: blocked, 0: emptysquare, -2: '\n'} + for i in range(self.nrows * self.ncols): + d[i + 1] = str(i + 1).center(3, ' ') - lastNumber = w * h - wid = w - hei = h - exists = [0 for j in range(lastNumber + 1)] - - pa = [[0 for j in range(h)] for i in range(w)] - st = pz.split() - idx = 0 - for j in range(h): - for i in range(w): - if st[idx] == ".": - idx += 1 - else: - pa[i][j] = int(st[idx]) - exists[pa[i][j]] = 1 - idx += 1 - - x = 0 - y = 0 - t = w * h + 1 - for j in range(h): - for i in range(w): - if pa[i][j] != 0 and pa[i][j] < t: - t = pa[i][j] - x = i - y = j - - return find_solution(pa, x, y, t + 1), pa - - -def show_result(r): - if r[0] == 1: - for j in range(hei): - for i in range(wid): - stdout.write(" {:0{}d}".format(r[1][i][j], 2)) + for r in range(self.nrows): + for c in range(self.ncols): + print(d[mat[r][c]], end='') print() - else: - stdout.write("No Solution!\n") - print() + def print_starting_board(self): + """ print input board """ + self.print_matrix(self.board) + + def is_solved(self): + """ true if there is at least 1 solution """ + return len(self.solutions) > 0 + + def print_solution(self, print_all=True): + """ print solution board(s) """ + n_solutions = len(self.solutions) + print(f"\n{n_solutions} solution{'s' if n_solutions != 1 else ''} found.") + for b in self.solutions: + self.print_matrix(b, '__ ') + if not print_all: + break + print() -r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" - " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) -show_result(r) +if __name__ == '__main__': + NUMBRIX_TESTS = [ + """ + 0 0 0 0 0 0 0 0 0 + 0 0 46 45 0 55 74 0 0 + 0 38 0 0 43 0 0 78 0 + 0 35 0 0 0 0 0 71 0 + 0 0 33 0 0 0 59 0 0 + 0 17 0 0 0 0 0 67 0 + 0 18 0 0 11 0 0 64 0 + 0 0 24 21 0 1 2 0 0 + 0 0 0 0 0 0 0 0 0 + """, + """ + 0 0 0 0 0 0 0 0 0 + 0 11 12 15 18 21 62 61 0 + 0 6 0 0 0 0 0 60 0 + 0 33 0 0 0 0 0 57 0 + 0 32 0 0 0 0 0 56 0 + 0 37 0 1 0 0 0 73 0 + 0 38 0 0 0 0 0 72 0 + 0 43 44 47 48 51 76 77 0 + 0 0 0 0 0 0 0 0 0 + """, + """ + 17 0 0 0 11 0 0 0 59 + 0 15 0 0 6 0 0 61 0 + 0 0 3 0 0 0 63 0 0 + 0 0 0 0 66 0 0 0 0 + 23 24 0 68 67 78 0 54 55 + 0 0 0 0 72 0 0 0 0 + 0 0 35 0 0 0 49 0 0 + 0 29 0 0 40 0 0 47 0 + 31 0 0 0 39 0 0 0 45 + """, + """ + 0 0 0 0 0 + 0 0 0 0 0 + 0 0 0 0 3 + 0 0 0 0 0 + 0 0 0 0 0 + """, + ] -r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" - " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) -show_result(r) + NUMBRIX_MOVES = [[-1, 0], [0, -1], [0, 1], [1, 0]] -r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" - " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) -show_result(r) + for t in NUMBRIX_TESTS: + puzzle = HidatoPuzzle(t.strip(), NUMBRIX_MOVES) + print("\nStarting position:") + puzzle.print_starting_board() + puzzle.solve() + puzzle.print_solution() diff --git a/Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb b/Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb new file mode 100644 index 0000000000..8894010528 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/DuckDB/sort-an-array-of-composite-structures.duckdb @@ -0,0 +1,6 @@ +create table pairs (name varchar(16), value varchar(16)); +insert into pairs values ('Fluffy', 'cat'); +insert into pairs values ('Fido', 'dog'); +insert into pairs values ('Francis', 'fish'); +-- order them by name +select * from pairs order by name; diff --git a/Task/Sort-an-integer-array/Pluto/sort-an-integer-array.pluto b/Task/Sort-an-integer-array/Pluto/sort-an-integer-array.pluto new file mode 100644 index 0000000000..451ea6e294 --- /dev/null +++ b/Task/Sort-an-integer-array/Pluto/sort-an-integer-array.pluto @@ -0,0 +1,2 @@ +a = {2,4,3,1,2} +print(a:sort():unpack()) diff --git a/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy b/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy index f6ffbc327d..119aaf9a25 100644 --- a/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy +++ b/Task/Sort-an-outline-at-every-level/EasyLang/sort-an-outline-at-every-level.easy @@ -73,7 +73,7 @@ func$[] outline . . proc run dir . sortdir = dir - call init + init nextline for s$ in outline : print s$ print "" diff --git a/Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-1.duckdb b/Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-1.duckdb new file mode 100644 index 0000000000..e114ea138c --- /dev/null +++ b/Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-1.duckdb @@ -0,0 +1,7 @@ +create or replace function lexorderedsequence(n) as table ( + with cte as ( + select i, i::VARCHAR as s + from range(1, n+1) t(i) + ) + select i from cte order by s +); diff --git a/Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-2.duckdb b/Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-2.duckdb new file mode 100644 index 0000000000..0f9de652e9 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/DuckDB/sort-numbers-lexicographically-2.duckdb @@ -0,0 +1 @@ +select array_agg(i order by s) as lex from lexorderedsequence(13); diff --git a/Task/Sort-numbers-lexicographically/Icon/sort-numbers-lexicographically.icon b/Task/Sort-numbers-lexicographically/Icon/sort-numbers-lexicographically.icon new file mode 100644 index 0000000000..3842c62229 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/Icon/sort-numbers-lexicographically.icon @@ -0,0 +1,9 @@ +link sort # for isort + +procedure main() + n := 13 + every a := [] & put(a, n to 1 by -1) + writes("before sort:") ; every writes(" ",!a) ; write() + a := isort(a,string) + writes("after sort: ") ; every writes(" ",!a) ; write() +end diff --git a/Task/Sort-three-variables/Prolog/sort-three-variables.pro b/Task/Sort-three-variables/Prolog/sort-three-variables.pro new file mode 100644 index 0000000000..de2b8582ac --- /dev/null +++ b/Task/Sort-three-variables/Prolog/sort-three-variables.pro @@ -0,0 +1,9 @@ +?- msort(['lions, tigers, and', 'bears, oh my!', '(from the "Wizard of OZ")'], [X, Y, Z]). +X = '(from the "Wizard of OZ")', +Y = 'bears, oh my!', +Z = 'lions, tigers, and'. + +?- msort([77444, -12, 0], [X, Y, Z]). +X = -12, +Y = 0, +Z = 77444. diff --git a/Task/Sorting-algorithms-Insertion-sort/FutureBasic/sorting-algorithms-insertion-sort.basic b/Task/Sorting-algorithms-Insertion-sort/FutureBasic/sorting-algorithms-insertion-sort.basic new file mode 100644 index 0000000000..627f9d81bf --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/FutureBasic/sorting-algorithms-insertion-sort.basic @@ -0,0 +1,62 @@ +// +// Insertion Sort in FutureBasic +// + +_maxDim = 99 // size of array + +dim theArray(_maxDim) as Int +dim x as Int + +// sorts array "theArray" +// in ascending order + +void local function insertionSort(arr(_maxDim) as Int, siz as Int) +dim as Int j,k,s + +for x = 0 to siz + j = x - 1 + s = 1 + k = arr(x) + while (j => 0) && (s == 1) + arr(j + 1) = arr(j) + s = 0 + if arr(j) > k + arr(j + 1) = arr(j) + j-- + s = 1 + end if + wend + arr(j + 1) = k +next x + +end fn +// + +// +// main +// +window 1,@"Insertion Sort" + +// load array with random 0-99 + +for x = 0 to 99 + theArray(x) = rnd(100)-1 +next x + +print "Unsorted:" +for x = 1 to 100 + print theArray(x-1); + if x MOD 20 then print "-"; else print +next x + +print + +fn insertionSort(@theArray(0),99) + +print "Sorted:" +for x = 1 to 100 + print theArray(x-1); + if x MOD 20 then print "-"; else print +next x + +handleevents diff --git a/Task/Sorting-algorithms-Insertion-sort/S-BASIC/sorting-algorithms-insertion-sort.basic b/Task/Sorting-algorithms-Insertion-sort/S-BASIC/sorting-algorithms-insertion-sort.basic new file mode 100644 index 0000000000..fb294242e9 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/S-BASIC/sorting-algorithms-insertion-sort.basic @@ -0,0 +1,36 @@ +$constant NUM_ITEMS = 10 + +dim integer items(NUM_ITEMS) +var i, j, t = integer + +rem - create a randomly-ordered list of numbers +for i = 1 to NUM_ITEMS + items(i) = int(rnd(1) * 100) + 1 +next i + +rem - show unsorted list +print "Unsorted list: "; +for i = 1 to NUM_ITEMS + print items(i); +next i +print + +rem - sort the list +for i = 1 to NUM_ITEMS + j = i + while j > 1 and items(j-1) > items(j) do + begin + t = items(j) + items(j) = items(j-1) + items(j-1) = t + j = j - 1 + end +next i + +rem - show the sorted list +print "Sorted list : "; +for i = 1 to NUM_ITEMS + print items(i); +next i + +end diff --git a/Task/Sorting-algorithms-Quicksort/ArkScript/sorting-algorithms-quicksort.ark b/Task/Sorting-algorithms-Quicksort/ArkScript/sorting-algorithms-quicksort.ark new file mode 100644 index 0000000000..b856e3eae7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/ArkScript/sorting-algorithms-quicksort.ark @@ -0,0 +1,25 @@ +(import std.List :filter) + +(let quicksort (fun (array) { + (if (empty? array) + # if the given list is empty, return it + [] + # otherwise, sort it + { + # the pivot will be the first element + (let pivot (head array)) + + # call quicksort on a smaller array containing all the elements less than the pivot + (mut less (quicksort (filter (tail array) (fun (e) (< e pivot))))) + + # and after that, call quicksort on a smaller array containing all the elements greater or equal to the pivot + (let more (quicksort (filter (tail array) (fun (e) (>= e pivot))))) + + (concat! less [pivot] more) + # return a concatenation of arrays + less }) })) + +# an unsorted list to sort +(let a [3 6 1 5 1 65 324 765 1 6 3 0 6 9 6 5 3 2 5 6 7 64 645 7 345 432 432 4 324 23]) + +(assert (= (quicksort a) [0 1 1 1 2 3 3 3 4 5 5 5 6 6 6 6 6 7 7 9 23 64 65 324 324 345 432 432 645 765]) "(quicksort a) is sorted") diff --git a/Task/Sorting-algorithms-Sleep-sort/FutureBasic/sorting-algorithms-sleep-sort.basic b/Task/Sorting-algorithms-Sleep-sort/FutureBasic/sorting-algorithms-sleep-sort.basic new file mode 100644 index 0000000000..0b6846db6c --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/FutureBasic/sorting-algorithms-sleep-sort.basic @@ -0,0 +1,21 @@ +include "Tlbx Dispatch.incl" + +include "NSLog.incl" + +local fn SleepSort + CFArrayRef unsorted = @[@35, @21, @11, @1, @2, @27, @32, @7, @42, @20, @50, @42, @25, @41, @43, @14, @46, @20, @30] + + dispatchglobal + for int i = 0 to len(unsorted) - 1 + CFArrayRef sorted = fn ArraySortedArrayUsingSelector( unsorted, @"compare:" ) + dispatchmain + NSLog( @"%@", sorted[i] ) + dispatchend + ThreadSleepForTimeInterval( 0.5 ) + next + dispatchend +end fn + +fn SleepSort + +HandleEvents diff --git a/Task/Sorting-algorithms-Sleep-sort/OCaml/sorting-algorithms-sleep-sort.ml b/Task/Sorting-algorithms-Sleep-sort/OCaml/sorting-algorithms-sleep-sort.ml new file mode 100644 index 0000000000..9bd8dbbeb7 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/OCaml/sorting-algorithms-sleep-sort.ml @@ -0,0 +1,6 @@ +#directory "+unix";; +#directory "+threads";; +#load "unix.cma";; +#load "threads.cma";; + +List.iter Thread.join (List.map (fun x -> Thread.create (fun x -> Thread.delay (float_of_int x);Printf.printf "%i\n%!" x) x;) (List.map int_of_string (List.tl (Array.to_list Sys.argv))));; diff --git a/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.jl b/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.jl index b8e84a9908..bcc9635bcc 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.jl +++ b/Task/Sorting-algorithms-Stooge-sort/Julia/sorting-algorithms-stooge-sort.jl @@ -4,7 +4,7 @@ function stoogesort!(a::Array, i::Int=1, j::Int=length(a)) end if (j - i) > 1 - t = round(Int, (j - i + 1) / 3) + t = (j - i + 1) ÷ 3 a = stoogesort!(a, i, j - t) a = stoogesort!(a, i + t, j) a = stoogesort!(a, i, j - t) diff --git a/Task/Sorting-algorithms-Stooge-sort/Maxima/sorting-algorithms-stooge-sort.maxima b/Task/Sorting-algorithms-Stooge-sort/Maxima/sorting-algorithms-stooge-sort.maxima new file mode 100644 index 0000000000..dfd8c5024e --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Maxima/sorting-algorithms-stooge-sort.maxima @@ -0,0 +1,14 @@ +stoogesort(list, i, j) := block( +if(list[j]1) then block( + t: floor((j-i+1)/3), + stoogesort(list, i, j-t), + stoogesort(list, i+t, j), + stoogesort(list, i, j-t)), +list)$ + +test_list: makelist(random(21),20); + +stooge(list) := stoogesort(list, 1, length(list))$ + +stooge(test_list); diff --git a/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r b/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r index d24cbe6f87..3386c265a7 100644 --- a/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r +++ b/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r @@ -1,17 +1,15 @@ stoogesort = function(vect) { - i = 1 - j = length(vect) - if(vect[j] < vect[i]) vect[c(j, i)] = vect[c(i, j)] + i <- 1 + j <- length(vect) + if(vect[j] < vect[i]) vect[c(j, i)] <- vect[c(i, j)] if(j - i > 1) { - t = (j - i + 1) %/% 3 - vect[i:(j - t)] = stoogesort(vect[i:(j - t)]) - vect[(i + t):j] = stoogesort(vect[(i + t):j]) - vect[i:(j - t)] = stoogesort(vect[i:(j - t)]) + t <- (j - i + 1) %/% 3 + vect[i:(j - t)] <- stoogesort(vect[i:(j - t)]) + vect[(i + t):j] <- stoogesort(vect[(i + t):j]) + vect[i:(j - t)] <- stoogesort(vect[i:(j - t)]) } vect } -v = sample(21, 20) -k = stoogesort(v) -v -k +v <- print(sample(21, 20)) +stoogesort(v) diff --git a/Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-1.logo b/Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-1.logo new file mode 100644 index 0000000000..2db36cf0d6 --- /dev/null +++ b/Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-1.logo @@ -0,0 +1,42 @@ +to create.list :string + output parse map [ifelse equalp ? ", ["\ ] [?]] :string +end + +to max :a :b + output ifelse lessequalp :a :b [:b] [:a] +end + +to min :a :b + output ifelse greaterequalp :a :b [:b] [:a] +end + +to sparklines :lists :bars :out + openwrite :out + setwrite :out + foreach :lists [sparkline create.list ? :bars] + close :out + setwrite [] +end + +to sparkline :list :bars + local [min max range nchar] + make "max reduce "max :list + make "min reduce "min :list + make "range difference :max :min + make "nchar count :bars + (type :list "\ ->\ ) + make "list map [1 + ifelse lessequalp difference :nchar 1 + int (product (quotient difference ? :min :range) :nchar) + [difference :nchar 1] + [int (product (quotient difference ? :min :range) :nchar)]] :list + foreach :list [type item ? :bars] + print " +end + +make "str1 "1\ 2\ 3\ 4\ 5\ 6\ 7\ 8\ 7\ 6\ 5\ 4\ 3\ 2\ 1 +make "str2 "1.5,\ 0.5\ 3.5,\ 2.5\ 5.5,\ 4.5\ 7.5,\ 6.5 +make "str3 "0,\ 1,\ 19,\ 20 +make "str4 "0,\ 999,\ 4000,\ 4999,\ 7000,\ 7999 +make "lists (list :str1 :str2 :str3 :str4) + +make "bars [▁ ▂ ▃ ▄ ▅ ▆ ▇ █] diff --git a/Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-2.logo b/Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-2.logo new file mode 100644 index 0000000000..156fe143da --- /dev/null +++ b/Task/Sparkline-in-unicode/Logo/sparkline-in-unicode-2.logo @@ -0,0 +1,3 @@ +load "sparkline.lg + +sparklines :lists :bars "sparkline.txt diff --git a/Task/Sparkline-in-unicode/YAMLScript/sparkline-in-unicode.ys b/Task/Sparkline-in-unicode/YAMLScript/sparkline-in-unicode.ys new file mode 100644 index 0000000000..105f9d0240 --- /dev/null +++ b/Task/Sparkline-in-unicode/YAMLScript/sparkline-in-unicode.ys @@ -0,0 +1,14 @@ +!YS-v0 + +defn main(input): + each line input:lines: + say: line:words.map(N):sparkline + +defn sparkline(nums): + sparks =: '▁▂▃▄▅▆▇█' + high =: max(nums*) + low =: min(nums*) + spread =: high - low + quantize =: + \(round(sparks.#.-- * ((_ - low) / spread))) + apply str: nums.map(\(nth sparks quantize(_))) diff --git a/Task/Split-a-character-string-based-on-change-of-character/R/split-a-character-string-based-on-change-of-character.r b/Task/Split-a-character-string-based-on-change-of-character/R/split-a-character-string-based-on-change-of-character.r new file mode 100644 index 0000000000..3a3e9d02a9 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/R/split-a-character-string-based-on-change-of-character.r @@ -0,0 +1,7 @@ +split_by_char <- function(s){ + chars <- strsplit(s,"") |> unlist() |> rle() + chunks <- strrep(chars$values, chars$lengths) + cat(chunks, sep=", ") +} + +split_by_char("gHHH5YY++///\\ ,,") diff --git a/Task/Square-form-factorization/REXX/square-form-factorization.rexx b/Task/Square-form-factorization/REXX/square-form-factorization.rexx index cb88ddad6f..68b25d05c1 100644 --- a/Task/Square-form-factorization/REXX/square-form-factorization.rexx +++ b/Task/Square-form-factorization/REXX/square-form-factorization.rexx @@ -1,4 +1,4 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings numeric digits 40 @@ -25,7 +25,7 @@ test.0 = i-1 return Selected: -procedure expose mult. test. glob. +procedure expose mult. test. Memo. call Time('r') say 'Find a factor for 28 selected numbers...' do t = 1 for test.0 @@ -55,7 +55,7 @@ say return Randomized: -procedure expose mult. glob. +procedure expose mult. Memo. say 'Find a factor for 28 random numbers...' x = 0 do until x = 28 @@ -89,6 +89,4 @@ end say return -include Numbers -include Functions -include Abend +include Math diff --git a/Task/Stack-traces/FutureBasic/stack-traces.basic b/Task/Stack-traces/FutureBasic/stack-traces.basic new file mode 100644 index 0000000000..29325975d7 --- /dev/null +++ b/Task/Stack-traces/FutureBasic/stack-traces.basic @@ -0,0 +1,14 @@ +output file @"Rosetta Code Stack Traces" + +include "NSLog.incl" + +void local fn StackTrace + CFArrayRef stackSymbols = fn ThreadCallStackSymbols + for CFStringRef symbol in stackSymbols + NSLog( @"%@", symbol ) + next +end fn + +fn StackTrace + +HandleEvents diff --git a/Task/Stack/OoRexx/stack.rexx b/Task/Stack/OoRexx/stack.rexx index 9916fb8815..01deff92ae 100644 --- a/Task/Stack/OoRexx/stack.rexx +++ b/Task/Stack/OoRexx/stack.rexx @@ -1,6 +1,9 @@ stack = .queue~of(123, 234) -- creates a stack with a couple of items stack~push("Abc") -- pushing value = stack~pull -- popping +say 'popped:' value value = stack~peek -- peeking +say 'peeked:' value -- the is empty test if stack~isEmpty then say "The stack is empty" +Else say stack~items 'items are on the stack' diff --git a/Task/Stack/Pluto/stack.pluto b/Task/Stack/Pluto/stack.pluto new file mode 100644 index 0000000000..17486a799a --- /dev/null +++ b/Task/Stack/Pluto/stack.pluto @@ -0,0 +1,4 @@ +stack = {} +table.insert(stack, 11) -- push +table.remove(stack) -- pop +print(#stack == 0) -- empty diff --git a/Task/Stack/REXX/stack-1.rexx b/Task/Stack/REXX/stack-1.rexx deleted file mode 100644 index 1b85ae47de..0000000000 --- a/Task/Stack/REXX/stack-1.rexx +++ /dev/null @@ -1,7 +0,0 @@ -y=123 /*define a REXX variable, value is 123 */ -push y /*pushes 123 onto the stack. */ -pull g /*pops last value stacked & removes it. */ -q=empty() /*invokes the EMPTY subroutine (below)*/ -exit /*stick a fork in it, we're done. */ - -empty: return queued() /*subroutine returns # of stacked items.*/ diff --git a/Task/Stack/REXX/stack-2.rexx b/Task/Stack/REXX/stack.rexx similarity index 82% rename from Task/Stack/REXX/stack-2.rexx rename to Task/Stack/REXX/stack.rexx index 0ebf18a3f5..3a3bf6e8fd 100644 --- a/Task/Stack/REXX/stack-2.rexx +++ b/Task/Stack/REXX/stack.rexx @@ -3,10 +3,10 @@ * 11.08.2013 Walter Pachl **********************************************************************/ stk.=0 -Call push 123 +Call push 123 /*pushes 123 onto the stack. */ Say empty() say peek() -say pull() +say pull() /*pops last value stacked & removes it. */ Say empty() say peek() say push(456) diff --git a/Task/Stack/TAV/stack-1.tav b/Task/Stack/TAV/stack-1.tav new file mode 100644 index 0000000000..ed582a9393 --- /dev/null +++ b/Task/Stack/TAV/stack-1.tav @@ -0,0 +1,6 @@ +row (@) push (val): + @[@.Count+1] =: val \ increments .Count +row (@) pop: + rv =: @[@.Count] \ void if .Count = 0 + @[@.Count] =: () \ assigning void decrements .Count + :> rv diff --git a/Task/Stack/TAV/stack-2.tav b/Task/Stack/TAV/stack-2.tav new file mode 100644 index 0000000000..b95a0b9d3f --- /dev/null +++ b/Task/Stack/TAV/stack-2.tav @@ -0,0 +1,9 @@ +main(params):+ + stack =: new row \ a row is a nice stack + ?# v =: tuple 1,3,5,7,11,13 give values + row stack push v \ push some primes + print '*' _ stack[stack.Count] \ get top + ?# i =: from 1 upto 7 + ? i %% 3 = 0 + print '*' _ stack[stack.Count] + print stack::pop \ class function syntax used diff --git a/Task/Statistics-Basic/DuckDB/statistics-basic.duckdb b/Task/Statistics-Basic/DuckDB/statistics-basic.duckdb new file mode 100644 index 0000000000..bbc5b6c183 --- /dev/null +++ b/Task/Statistics-Basic/DuckDB/statistics-basic.duckdb @@ -0,0 +1,12 @@ +create or replace function basics(n) as table ( + select n, avg(x), stddev_pop(x), stddev_samp(x) + from (select random() as x from range(0,n)) +); + +from basics(100) +union all from basics(1000) +union all from basics(10000) +union all from basics(1000000000); + +with cte as (select random() as x from range(0,100)) +from histogram(cte, x) ; diff --git a/Task/Statistics-Basic/Maxima/statistics-basic.maxima b/Task/Statistics-Basic/Maxima/statistics-basic.maxima new file mode 100644 index 0000000000..b3ff47633e --- /dev/null +++ b/Task/Statistics-Basic/Maxima/statistics-basic.maxima @@ -0,0 +1,10 @@ +load("descriptive")$ +gen_sample(n) := makelist(random(1.0), n)$ +test_samples: map(gen_sample, [100, 1000, 10000])$ + +map(mean, test_samples); +map(std, test_samples); + +histogram(test_samples[1])$ +histogram(test_samples[2])$ +histogram(test_samples[3])$ diff --git a/Task/Stem-and-leaf-plot/Prolog/stem-and-leaf-plot.pro b/Task/Stem-and-leaf-plot/Prolog/stem-and-leaf-plot.pro new file mode 100644 index 0000000000..acc16b92c5 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Prolog/stem-and-leaf-plot.pro @@ -0,0 +1,37 @@ +:- initialization(main, main). +:- use_module(library(dcg/basics), [blanks/2, eol/2, integer/3]). +:- use_module(library(dcg/high_order), [sequence/4, sequence/5]). + +%! numbers_to_stem_leaves(+Numbers, -StemLeaves) is det. +% Converts a list of Numbers to a list of Stem-Leaves pairs. +numbers_to_stem_leaves(Numbers, StemLeaves) :- + findall(Stem - Leaves, ( + group_by(Stem, Leaf, ( + member(Number, Numbers), + divmod(Number, 10, Stem, Leaf) + ), Leaves0), + msort(Leaves0, Leaves) + ), StemLeaves). + +stem_leaf_plot(StemLeaves) --> sequence(stem_leaves, StemLeaves). + +stem_leaves(Stem - Leaves) --> rpad_integer(4, Stem), " | ", sequence(integer, " ", Leaves), "\n". + +rpad_integer(Pad, N) --> + ( { Pad0 is Pad - 1, N < 10 ^ Pad0, \+ ( Pad = 1, N = 0 ) } + -> " ", rpad_integer(Pad0, N) + ; integer(N) + ). + +%! display_stem_leaf_plot(Numbers) is det. +% Prints the stem-and-leaf plot of a list of Numbers. +display_stem_leaf_plot(Numbers) :- + numbers_to_stem_leaves(Numbers, StemLeaves), + once(phrase(stem_leaf_plot(StemLeaves), Codes)), + format("~s", [Codes]). + +int(N) --> integer(N), blanks. + +main([Filename]) :- + phrase_from_file((blanks, sequence(int, Numbers)), Filename), + display_stem_leaf_plot(Numbers). diff --git a/Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig b/Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig new file mode 100644 index 0000000000..8883a3ef63 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Zig/stern-brocot-sequence.zig @@ -0,0 +1,81 @@ +const std = @import("std"); + +fn gcd(a: u64, b: u64) u64 { + if (b == 0) return a; + return gcd(b, a % b); +} + +fn sternBrocot(allocator: std.mem.Allocator, up_to: u64) !std.ArrayList(u64) { + var seq = std.ArrayList(u64).init(allocator); + try seq.append(1); + try seq.append(1); + + var last: u64 = 1; + var idx: usize = 1; + + while (last < up_to) { + last = seq.items[idx]; + try seq.append(last + seq.items[idx - 1]); + try seq.append(last); + idx += 1; + } + + return seq; +} + +fn testSternBrocot() !void { + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + var seq = try sternBrocot(allocator, 100); + + // Print first 15 in sequence + std.debug.print("First 15 in sequence: ", .{}); + std.debug.print("[", .{}); + for (seq.items[0..15], 0..) |val, i| { + if (i > 0) std.debug.print(", ", .{}); + std.debug.print("{d}", .{val}); + } + std.debug.print("]\n", .{}); + + // Print first positions of integers 1 through 10 + std.debug.print("First positions of integers 1 through 10:\n", .{}); + for (1..11) |i| { + const i_u64 = @as(u64, i); + var found = false; + for (seq.items, 0..) |val, pos| { + if (val == i_u64) { + std.debug.print(" {d:>2} at position {d}\n", .{i, pos + 1}); + found = true; + break; + } + } + if (!found) { + std.debug.print("Error finding position of {d}\n", .{i}); + } + } + + // Find position of 100 + for (seq.items, 0..) |val, pos| { + if (val == 100) { + std.debug.print(" 100 at position {d}\n", .{pos + 1}); + break; + } + } + + // Check if first 999 consecutive pairs have gcd of 1 + var all_gcd_one = true; + for (1..1000) |i| { + if (i >= seq.items.len) break; + if (gcd(seq.items[i - 1], seq.items[i]) != 1) { + all_gcd_one = false; + break; + } + } + std.debug.print("The first 999 consecutive pairs have gcd of 1: {any}.\n", .{all_gcd_one}); +} + +pub fn main() !void { + try testSternBrocot(); +} diff --git a/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy b/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy new file mode 100644 index 0000000000..796a84f3f6 --- /dev/null +++ b/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy @@ -0,0 +1,73 @@ +board$ = "ET AON RISBCDFGHJKLMPQ/UVWXYZ." +len encode[] 128 +len decode$[] 128 +arrbase encode[] 0 +arrbase decode$[] 0 +len row[] 2 +proc init s$ . + s$[] = strchars s$ + for i = 1 to 30 + if s$[i] = " " + if row[1] = 0 + row[1] = i - 1 + else + row[2] = i - 1 + . + else + code = 0 + if i > 20 + code = row[2] + elif i > 10 + code = row[1] + . + code = code * 10 + (i - 1) mod 10 + encode[strcode s$[i]] = code + decode$[code] = s$[i] + . + . +. +func$ encipher in$ . + for c$ in strchars in$ + c = strcode c$ + if c >= 48 and c <= 57 + code = encode[strcode "."] + r$ &= code + r$ &= c$ + else + c = bitand c 0xdf + if c <> 0 + if c >= 65 and c <= 90 + code = encode[c] + else + code = encode[strcode "/"] + . + r$ &= code + . + . + . + return r$ +. +func$ decipher in$ . + in$[] = strchars in$ + for i to len in$[] + c$ = in$[i] + c = strcode c$ - 48 + if c = row[1] or c = row[2] + i += 1 + c = c * 10 + strcode in$[i] - 48 + . + c$ = decode$[c] + if c$ = "." + i += 1 + c$ = in$[i] + . + r$ &= c$ + . + return r$ +. +init board$ +msg$ = "In the winter 1965/we were hungry/just barely alive" +print msg$ +ciph$ = encipher msg$ +print ciph$ +print decipher ciph$ diff --git a/Task/String-append/ArkScript/string-append.ark b/Task/String-append/ArkScript/string-append.ark new file mode 100644 index 0000000000..19856313f3 --- /dev/null +++ b/Task/String-append/ArkScript/string-append.ark @@ -0,0 +1,2 @@ +(let s "12345678") +(print (+ s "9!")) diff --git a/Task/String-append/DuckDB/string-append-1.duckdb b/Task/String-append/DuckDB/string-append-1.duckdb new file mode 100644 index 0000000000..3de0351a7b --- /dev/null +++ b/Task/String-append/DuckDB/string-append-1.duckdb @@ -0,0 +1,8 @@ +with recursive t(i, s) as ( + select 0, 'foo' + union all + select i+1, s || 'bar' + from t + where i < 1) +select last(s order by i) as s +from t; diff --git a/Task/String-append/DuckDB/string-append-2.duckdb b/Task/String-append/DuckDB/string-append-2.duckdb new file mode 100644 index 0000000000..0a2fcf1c67 --- /dev/null +++ b/Task/String-append/DuckDB/string-append-2.duckdb @@ -0,0 +1,2 @@ +set variable s = 'Hello'; +set variable s = getvariable('s') || ' world'; diff --git a/Task/String-case/ArkScript/string-case.ark b/Task/String-case/ArkScript/string-case.ark new file mode 100644 index 0000000000..df08409105 --- /dev/null +++ b/Task/String-case/ArkScript/string-case.ark @@ -0,0 +1,5 @@ +(import std.String) + +(let s "alphaBETA") +(print (string:toUpper s)) +(print (string:toLower s)) diff --git a/Task/String-case/DuckDB/string-case.duckdb b/Task/String-case/DuckDB/string-case.duckdb new file mode 100644 index 0000000000..5a95354989 --- /dev/null +++ b/Task/String-case/DuckDB/string-case.duckdb @@ -0,0 +1 @@ +select 'alphaBETA' as s, lower(s), upper(s); diff --git a/Task/String-comparison/DuckDB/string-comparison.duckdb b/Task/String-comparison/DuckDB/string-comparison.duckdb new file mode 100644 index 0000000000..052f767117 --- /dev/null +++ b/Task/String-comparison/DuckDB/string-comparison.duckdb @@ -0,0 +1,10 @@ +select s, + t, + s == t, + s != t, + s < t, + s > t, + upper(s) = upper(uppers) as "case insenstive", + '2' < '1e10', + s ilike uppers +from (select 'abc' as s, 'def' as t, 'ABC' as uppers ); diff --git a/Task/String-concatenation/ArkScript/string-concatenation.ark b/Task/String-concatenation/ArkScript/string-concatenation.ark new file mode 100644 index 0000000000..24485a7056 --- /dev/null +++ b/Task/String-concatenation/ArkScript/string-concatenation.ark @@ -0,0 +1,6 @@ +(let s "hello") +(print (+ s " world!")) + +(let w " there") +(let v (+ s w)) +(print v) diff --git a/Task/String-concatenation/Prolog/string-concatenation.pro b/Task/String-concatenation/Prolog/string-concatenation.pro new file mode 100644 index 0000000000..96ca451636 --- /dev/null +++ b/Task/String-concatenation/Prolog/string-concatenation.pro @@ -0,0 +1,9 @@ +:- set_prolog_flag(double_quotes, chars). + +println([]) :- write('\n'). +println([Char | Chars]) :- write(Char), println(Chars). + +:- S0 = "Hello, ", + S1 = "world!", + append(S0, S1, S), + println(S). diff --git a/Task/String-concatenation/Tcl/string-concatenation-3.tcl b/Task/String-concatenation/Tcl/string-concatenation-3.tcl new file mode 100644 index 0000000000..d98b4783f1 --- /dev/null +++ b/Task/String-concatenation/Tcl/string-concatenation-3.tcl @@ -0,0 +1,6 @@ +set s "Hello" +set w "World" +set hw "$s $w" ; # "hello world" +set hw [concat $s $w] ; # {hello world}, same as above +set hw [string cat $s $w] ; # "helloworld" +set hw [join [list $s $w] " "] ; # "hello world" \w space delimiter diff --git a/Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark b/Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark new file mode 100644 index 0000000000..87c666c268 --- /dev/null +++ b/Task/String-interpolation-included-/ArkScript/string-interpolation-included-.ark @@ -0,0 +1,4 @@ +(print (string:format "Mary had a {} lamb." "little")) + +(let replacement "medium-sized") +(print (string:format "Mary had a {} lamb." replacement)) diff --git a/Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr b/Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr new file mode 100644 index 0000000000..82a646236f --- /dev/null +++ b/Task/String-interpolation-included-/Crystal/string-interpolation-included-.cr @@ -0,0 +1,6 @@ +icr:1> extra = "little" + => "little" +icr:2> "Mary had a #{extra} lamb" + => "Mary had a little lamb" +icr:3> "Mary had a %s lamb" % extra + => "Mary had a little lamb" diff --git a/Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb b/Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb new file mode 100644 index 0000000000..d44ba7106b --- /dev/null +++ b/Task/String-interpolation-included-/DuckDB/string-interpolation-included-.duckdb @@ -0,0 +1 @@ +select replace( 'Mary had a , lamb.', '', getvariable('adjective')); diff --git a/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas b/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas index 8bb50800b2..ad45cd88fd 100644 --- a/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas +++ b/Task/String-interpolation-included-/PascalABC.NET/string-interpolation-included-.pas @@ -1,3 +1,3 @@ -var extra := 'little'; +## var extra := 'little'; var formatted := $'Mary has a {extra} lamb.'; Print(formatted); diff --git a/Task/String-interpolation-included-/Pluto/string-interpolation-included-.pluto b/Task/String-interpolation-included-/Pluto/string-interpolation-included-.pluto new file mode 100644 index 0000000000..bc2475bac6 --- /dev/null +++ b/Task/String-interpolation-included-/Pluto/string-interpolation-included-.pluto @@ -0,0 +1,3 @@ +local adjective = "little" +local sentence = $"Mary had a {adjective} lamb" +print(sentence) diff --git a/Task/String-interpolation-included-/R/string-interpolation-included-.r b/Task/String-interpolation-included-/R/string-interpolation-included-.r new file mode 100644 index 0000000000..f34371c1b4 --- /dev/null +++ b/Task/String-interpolation-included-/R/string-interpolation-included-.r @@ -0,0 +1,2 @@ +adj <- "little" +sprintf("Mary had a %s lamb", adj) diff --git a/Task/String-length/ArkScript/string-length.ark b/Task/String-length/ArkScript/string-length.ark new file mode 100644 index 0000000000..be20734ba6 --- /dev/null +++ b/Task/String-length/ArkScript/string-length.ark @@ -0,0 +1 @@ +(print (len "åéèàâêç")) diff --git a/Task/String-length/DuckDB/string-length.duckdb b/Task/String-length/DuckDB/string-length.duckdb new file mode 100644 index 0000000000..3f34f5d47d --- /dev/null +++ b/Task/String-length/DuckDB/string-length.duckdb @@ -0,0 +1,2 @@ +select s, length(s), strlen(s) as '# bytes' from + (select unnest(['J̲o̲s̲é̲', '𝔘𝔫𝔦𝔠𝔬𝔡𝔢']) as s); diff --git a/Task/String-length/FutureBasic/string-length.basic b/Task/String-length/FutureBasic/string-length.basic new file mode 100644 index 0000000000..10db65c468 --- /dev/null +++ b/Task/String-length/FutureBasic/string-length.basic @@ -0,0 +1,17 @@ +CFStringRef s + +s = @"møøse" +printf @"\"%@\"",s +print @"character length:",len(s) +print @"unicode length:",,len(s,_kLenUnicode) +print @"byte length UTF8:",len(s,_kLenBytesUTF8) +print @"byte length UTF16:",len(s,_kLenBytesUTF16) + +print + +s = @"𝔘𝔫𝔦𝔠𝔬𝔡𝔢" +printf @"\"%@\"",s +print @"character length:",len(s) +print @"unicode length:",,len(s,_kLenUnicode) +print @"byte length UTF8:",len(s,_kLenBytesUTF8) +print @"byte length UTF16:",len(s,_kLenBytesUTF16) diff --git a/Task/String-length/Pluto/string-length.pluto b/Task/String-length/Pluto/string-length.pluto new file mode 100644 index 0000000000..ea7a1d954b --- /dev/null +++ b/Task/String-length/Pluto/string-length.pluto @@ -0,0 +1,12 @@ +require "gchar" +local fmt = require "fmt" + +local moose = "møøse" +local unicode = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" +local jose = "J\u{332}o\u{332}s\u{332}e\u{301}\u{332}" + +local f = "%5s %7s %5s" +fmt.print("Strings : " .. f, moose, unicode, jose) +fmt.print("\nBytes : " .. f, #moose, #unicode, #jose) +fmt.print("\nCodepoints: " .. f, utf8.len(moose), utf8.len(unicode), utf8.len(jose)) +fmt.print("\nGraphemes : " .. f, gchar.of(moose):len(), gchar.of(unicode):len(), gchar.of(jose):len()) diff --git a/Task/String-length/TAV/string-length.tav b/Task/String-length/TAV/string-length.tav new file mode 100644 index 0000000000..b25087178d --- /dev/null +++ b/Task/String-length/TAV/string-length.tav @@ -0,0 +1,6 @@ + s =: "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" + print (quote s), s.Count, s.Bytes + s =: "José&e10;" + print (quote s), s.Count, s.Bytes + s =: "J̲o̲s̲é̲" + print (quote s), s.Count, s.Bytes diff --git a/Task/String-length/Wren/string-length-1.wren b/Task/String-length/Wren/string-length-1.wren index 303227ac8f..ca90697ca5 100644 --- a/Task/String-length/Wren/string-length-1.wren +++ b/Task/String-length/Wren/string-length-1.wren @@ -1,3 +1,4 @@ System.print("møøse".bytes.count) System.print("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".bytes.count) -System.print("J̲o̲s̲é̲".bytes.count) +var jose = "J\u0332o\u0332s\u0332e\u0301\u0332" +System.print(jose.bytes.count) diff --git a/Task/String-length/Wren/string-length-2.wren b/Task/String-length/Wren/string-length-2.wren index 5daeb0b24c..edf949d867 100644 --- a/Task/String-length/Wren/string-length-2.wren +++ b/Task/String-length/Wren/string-length-2.wren @@ -1,3 +1,4 @@ System.print("møøse".count) System.print("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".count) -System.print("J̲o̲s̲é̲".count) +var jose = "J\u0332o\u0332s\u0332e\u0301\u0332" +System.print(jose.count) diff --git a/Task/String-length/Wren/string-length-3.wren b/Task/String-length/Wren/string-length-3.wren index 333b1fc9b8..e89f0a995a 100644 --- a/Task/String-length/Wren/string-length-3.wren +++ b/Task/String-length/Wren/string-length-3.wren @@ -2,4 +2,5 @@ import "./upc" for Graphemes System.print(Graphemes.clusterCount("møøse")) System.print(Graphemes.clusterCount("𝔘𝔫𝔦𝔠𝔬𝔡𝔢")) -System.print(Graphemes.clusterCount("J̲o̲s̲é̲")) +var jose = "J\u0332o\u0332s\u0332e\u0301\u0332" +System.print(Graphemes.clusterCount(jose)) diff --git a/Task/String-matching/ArkScript/string-matching.ark b/Task/String-matching/ArkScript/string-matching.ark new file mode 100644 index 0000000000..1952605aa1 --- /dev/null +++ b/Task/String-matching/ArkScript/string-matching.ark @@ -0,0 +1,6 @@ +(assert (= 0 (string:find "abcd" "ab")) "abcd starts with ab") +(assert (= 6 (string:find "hello world" "world")) "world is located at 6") +(assert (= -1 (string:find "abcd" "zn")) "abcd does not contain zn") +(assert (= -1 (string:find "abab" "bb")) "abab does not contain bb") +(assert (= 0 (string:find "abab" "ab")) "abab contains ab") +(assert (= 2 (string:find "abab" "ab" 1)) "starting lookup at index 1, we found ab at position 2") diff --git a/Task/String-matching/DuckDB/string-matching.duckdb b/Task/String-matching/DuckDB/string-matching.duckdb new file mode 100644 index 0000000000..09e75c1cd5 --- /dev/null +++ b/Task/String-matching/DuckDB/string-matching.duckdb @@ -0,0 +1,17 @@ +# Return a list of the indices of all occurrences (including overlapping occurrences) +create or replace function string_positions(haystack, needle) as ( + WITH RECURSIVE etc AS ( + SELECT + position(needle IN haystack) AS start_pos, + 0 as s + UNION ALL + SELECT + position(needle IN substr(haystack, start_pos + 1)) + start_pos AS start_pos, + start_pos as s + FROM etc + WHERE start_pos != s + ) + SELECT coalesce(array_agg(start_pos order by start_pos),[]::BIGINT[]) + FROM etc + WHERE start_pos > 0 and s != start_pos +); diff --git a/Task/String-matching/R/string-matching.r b/Task/String-matching/R/string-matching.r new file mode 100644 index 0000000000..214497a816 --- /dev/null +++ b/Task/String-matching/R/string-matching.r @@ -0,0 +1,14 @@ +startsWith("foobar", "foo") +startsWith("barbaz", "bax") +grepl("bar", "foobarqux") #Note order of arguments isn't always the same +grepl("baz", "foobarqux") +endsWith("foobar", "bar") +endsWith("foobar", "baz") + +regexpr("bar", "barbazbarbax") #Only returns position of first match + +regexpr("foo", "barbazbarbax") #Returns -1 if no match exists + +gregexpr("bar", "barbazbarbax") #Returns positions of all matches + +gregexpr("foo", "barbazbarbax") #Same output as regexpr() if no match, but as a length-1 list rather than a vector diff --git a/Task/String-prepend/ArkScript/string-prepend.ark b/Task/String-prepend/ArkScript/string-prepend.ark new file mode 100644 index 0000000000..7b212ed915 --- /dev/null +++ b/Task/String-prepend/ArkScript/string-prepend.ark @@ -0,0 +1,3 @@ +(let s "012345678") +(let v (+ "#~" s)) +(print v) diff --git a/Task/String-prepend/DuckDB/string-prepend-1.duckdb b/Task/String-prepend/DuckDB/string-prepend-1.duckdb new file mode 100644 index 0000000000..102dcdc902 --- /dev/null +++ b/Task/String-prepend/DuckDB/string-prepend-1.duckdb @@ -0,0 +1 @@ +select 'Hello ' || s FROM (select 'world!' as s); diff --git a/Task/String-prepend/DuckDB/string-prepend-2.duckdb b/Task/String-prepend/DuckDB/string-prepend-2.duckdb new file mode 100644 index 0000000000..9f1d92c4f0 --- /dev/null +++ b/Task/String-prepend/DuckDB/string-prepend-2.duckdb @@ -0,0 +1 @@ +select format('{} {}', 'Hello', s) FROM (select 'world!' as s); diff --git a/Task/String-prepend/DuckDB/string-prepend-3.duckdb b/Task/String-prepend/DuckDB/string-prepend-3.duckdb new file mode 100644 index 0000000000..1926a1f04c --- /dev/null +++ b/Task/String-prepend/DuckDB/string-prepend-3.duckdb @@ -0,0 +1,2 @@ +set variable s = 'world!'; +select 'Hello ' || getvariable('s') diff --git a/Task/Strip-a-set-of-characters-from-a-string/DuckDB/strip-a-set-of-characters-from-a-string.duckdb b/Task/Strip-a-set-of-characters-from-a-string/DuckDB/strip-a-set-of-characters-from-a-string.duckdb new file mode 100644 index 0000000000..20c738e7cd --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/DuckDB/strip-a-set-of-characters-from-a-string.duckdb @@ -0,0 +1,10 @@ +# Omit from `str` each of the characters in `omit` : +create or replace function string_strip(str, omit) as ( + array_to_string( + regexp_split_to_array( + str, + '[' || regexp_escape( omit ) || ']'), '') +); + +# Example: +select string_strip('She was a soul stripper. She took my heart!', 'aei') as translated; diff --git a/Task/Strip-comments-from-a-string/DuckDB/strip-comments-from-a-string.duckdb b/Task/Strip-comments-from-a-string/DuckDB/strip-comments-from-a-string.duckdb new file mode 100644 index 0000000000..1cfe9dbfd7 --- /dev/null +++ b/Task/Strip-comments-from-a-string/DuckDB/strip-comments-from-a-string.duckdb @@ -0,0 +1,16 @@ +# `sep` can be a single character or a string but it will be interpreted +# as part of a regexp within square brackets, so be careful if characters +# such as `-` are used. +create or replace function remove_comment(s, sep) as ( + regexp_replace(s, '\s*[' || sep || '].*', '') +); + +# Examples + +select s, + remove_comment(s, '#') as decommented, + regexp_replace(decommented, ' ', '_','g') as visible +from unnest( + ['apples ; pears # and bananas', + 'apples # pears ; and bananas'] + ) _s(s); diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/DuckDB/strip-control-codes-and-extended-characters-from-a-string.duckdb b/Task/Strip-control-codes-and-extended-characters-from-a-string/DuckDB/strip-control-codes-and-extended-characters-from-a-string.duckdb new file mode 100644 index 0000000000..9b264a1f36 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/DuckDB/strip-control-codes-and-extended-characters-from-a-string.duckdb @@ -0,0 +1,29 @@ +# Produce a list of the unicode values of a string +create or replace function explode(s) as ( + regexp_extract_all(s, '.').list_transform(c -> unicode(c)) +); + +# Produce a string from a list of unicode values +create or replace function implode(lst) as ( + list_transform(lst, c -> chr(c)) + .array_to_string('') +); + +create or replace function strip_control_codes(s) as ( + explode(s) + .list_filter(unicode -> (unicode > 31 and unicode != 127)) + .implode() +); + +create or replace function strip_extended_characters(s) as ( + explode(s) + .list_filter(unicode -> (31 < unicode) and (unicode < 127)) + .implode() +); + +## Example: +set variable string = 'string of ☺☻♥♦⌂, may include control characters such as null (' || chr(0) || ') and other ilk.\n§►↔◄\nRødgrød med fløde'; + +select getvariable('string').strip_control_codes(); + +select getvariable('string').strip_extended_characters(); diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/DuckDB/strip-whitespace-from-a-string-top-and-tail.duckdb b/Task/Strip-whitespace-from-a-string-Top-and-tail/DuckDB/strip-whitespace-from-a-string-top-and-tail.duckdb new file mode 100644 index 0000000000..a91d7fab66 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/DuckDB/strip-whitespace-from-a-string-top-and-tail.duckdb @@ -0,0 +1,27 @@ +create or replace function lstrip(s) as ( + select regexp_replace(s, '^[\s\p{Cc}]+', '', 'g' ) +); + +# p{Cc} == "Other, control" +create or replace function rstrip(s) as ( + select regexp_replace(s, '[\s\p{Cc}]+$', '', 'g' ) +); + +create or replace function strip(s) as ( + select lstrip(s).rstrip() +); + +# Examples: + +create or replace function demo() as table ( + select s, lstrip(s), rstrip(s), strip(s), length(s), length(strip(s)) + from unnest([ + ' ' || chr(9) || ' ' || chr(13) || ' ' || chr(10) || ' String with leading spaces \t \r \n ', + chr(1) || ' <- control A', + (chr(1) || ' ' || chr(2) || ' <- ^A ^B' ) + ]) _(s) +); + +.mode line +.columns +from demo(); diff --git a/Task/Substitution-cipher/Rust/substitution-cipher.rs b/Task/Substitution-cipher/Rust/substitution-cipher.rs new file mode 100644 index 0000000000..e7dc53105a --- /dev/null +++ b/Task/Substitution-cipher/Rust/substitution-cipher.rs @@ -0,0 +1,25 @@ +fn main() { + let key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"; + + let s = "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"; + let enc = encode(s, key); + println!("Encoded: {}", enc); + println!("Decoded: {}", decode(&enc, key)); +} + +fn encode(s: &str, key: &str) -> String { + let key_bytes = key.as_bytes(); + s.bytes() + .map(|b| key_bytes[(b as usize) - 32] as char) + .collect() +} + +fn decode(s: &str, key: &str) -> String { + let key_bytes = key.as_bytes(); + s.bytes() + .map(|b| { + let index = key_bytes.iter().position(|&k| k == b).unwrap(); + (index + 32) as u8 as char + }) + .collect() +} diff --git a/Task/Substring-Top-and-tail/Maxima/substring-top-and-tail.maxima b/Task/Substring-Top-and-tail/Maxima/substring-top-and-tail.maxima new file mode 100644 index 0000000000..6f00e14a51 --- /dev/null +++ b/Task/Substring-Top-and-tail/Maxima/substring-top-and-tail.maxima @@ -0,0 +1,5 @@ +load("stringproc")$ +top(s) := substring(s, 2)$ +tail(s) := substring(s, 1, slength(s))$ +top_and_tail(s) := substring(s, 2, slength(s))$ +map(lambda([f], f("xyzzy")), [top, tail, top_and_tail]); diff --git a/Task/Substring-Top-and-tail/R/substring-top-and-tail.r b/Task/Substring-Top-and-tail/R/substring-top-and-tail.r new file mode 100644 index 0000000000..3e4673d02e --- /dev/null +++ b/Task/Substring-Top-and-tail/R/substring-top-and-tail.r @@ -0,0 +1,4 @@ +top_and_tail <- function(s, top=TRUE, tail=TRUE) substr(s, 1+top, nchar(s)-tail) +top_and_tail("xyzzy") +top_and_tail("xyzzy", top=FALSE) +top_and_tail("xyzzy", tail=FALSE) diff --git a/Task/Substring/DuckDB/substring.duckdb b/Task/Substring/DuckDB/substring.duckdb new file mode 100644 index 0000000000..f03d8182ff --- /dev/null +++ b/Task/Substring/DuckDB/substring.duckdb @@ -0,0 +1,20 @@ +# For brevity, we will use a table-valued function for defining the sample string(s): +create or replace function s() as table (select '一二三四五六七八九十' as s); + +# starting from n characters in and of m length: s[n: n+m-1] +select s[1:2] from s(); + +# starting from n characters in, up to the end of the string: s[n:] +select s[9:] from s(); + +# whole string minus the last character: .[:-2] +select s[0:-2] from s(); + +# starting from a known character within the string and of m length, say 2: +select s[ix:ix+(2-1)] from (select s, position('五' in s) as ix from s()); + +# starting from a known substring within the string and of m length, say 2: +select s[ix:ix+(2-1)] from (select s, position('五六' in s) as ix from s()); + +# For clarity we'll use DuckDB's 'list' output mode: +.mode list diff --git a/Task/Sudoku/DuckDB/sudoku.duckdb b/Task/Sudoku/DuckDB/sudoku.duckdb new file mode 100644 index 0000000000..4ea141d510 --- /dev/null +++ b/Task/Sudoku/DuckDB/sudoku.duckdb @@ -0,0 +1,40 @@ +# An example +.maxwidth 100 +set variable game='85 24 72 9 4 1 7 23 5 9 4 8 7 17 36 4 '; + +create or replace function instr3(s,t,j) as ( + select case when n = 0 then 0 + else n + j - 1 + end + from (select instr(substr(s,j), t) as n) +); + +with recursive + symbols (d) as (select level::VARCHAR from range(1,10) t(level) ) +, board (i) as (select level from range(1,82) t(level) ) +, neighbors (i, j) as ( + select b1.i, b2.i + from board b1 inner join board b2 + on b1.i != b2.i + and ( + mod(b1.i - b2.i, 9) = 0 + or ceil(b1.i / 9) = ceil(b2.i / 9) + or ceil(b1.i / 27) = ceil(b2.i / 27) and trunc(mod(b1.i - 1, 9) / 3) = trunc(mod(b2.i - 1, 9) / 3) + ) + ) +, r (str, pos) as ( + select getvariable('game'), instr(getvariable('game'), ' ') + + union all + select substr(r.str, 1, r.pos - 1) || s.d || substr(r.str, r.pos + 1), instr3(r.str, ' ', r.pos + 1) + from r inner join symbols s + on r.pos > 0 and not exists ( + select * + from neighbors n + where r.pos = n.i and s.d = substr(r.str, n.j, 1) + ) + ) +select str +from r +where pos = 0 +; diff --git a/Task/Sudoku/Zig/sudoku.zig b/Task/Sudoku/Zig/sudoku.zig new file mode 100644 index 0000000000..ece9ae2db5 --- /dev/null +++ b/Task/Sudoku/Zig/sudoku.zig @@ -0,0 +1,104 @@ +const std = @import("std"); + +const Sudoku = [81]u8; + +fn isValid(val: u8, x: usize, y: usize, sudokuAr: *Sudoku) bool { + // Check row and column + for (0..9) |i| { + if (sudokuAr[y * 9 + i] == val or sudokuAr[i * 9 + x] == val) { + return false; + } + } + + // Check 3x3 box + const startX = (x / 3) * 3; + const startY = (y / 3) * 3; + + for (startY..startY + 3) |i| { + for (startX..startX + 3) |j| { + if (sudokuAr[i * 9 + j] == val) { + return false; + } + } + } + + return true; +} + +fn placeNumber(pos: usize, sudokuAr: *Sudoku) bool { + var currentPos: usize = pos; + + // Find next empty cell + while (currentPos < 81 and sudokuAr[currentPos] != 0) { + currentPos += 1; + } + + // If no empty cells, puzzle is solved + if (currentPos >= 81) { + return true; + } + + const x = currentPos % 9; + const y = currentPos / 9; + + // Try placing digits 1-9 + for (1..10) |n| { + if (isValid(@intCast(n), x, y, sudokuAr)) { + sudokuAr[currentPos] = @intCast(n); + + if (placeNumber(currentPos + 1, sudokuAr)) { + return true; + } + + // Backtrack + sudokuAr[currentPos] = 0; + } + } + + return false; +} + +fn prettyPrint(sudokuAr: Sudoku) void { + const lineSep = "------+-------+------"; + std.debug.print("{s}\n", .{lineSep}); + + for (0..81) |i| { + std.debug.print("{d} ", .{sudokuAr[i]}); + + if ((i + 1) % 3 == 0 and (i + 1) % 9 != 0) { + std.debug.print("| ", .{}); + } + + if ((i + 1) % 9 == 0) { + std.debug.print("\n", .{}); + } + + if ((i + 1) % 27 == 0) { + std.debug.print("{s}\n", .{lineSep}); + } + } +} + +fn solve(sudokuAr: *Sudoku) bool { + return placeNumber(0, sudokuAr); +} + +pub fn main() !void { + var sudokuAr: Sudoku = [_]u8{ + 8, 5, 0, 0, 0, 2, 4, 0, 0, + 7, 2, 0, 0, 0, 0, 0, 0, 9, + 0, 0, 4, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, 7, 0, 0, 2, + 3, 0, 5, 0, 0, 0, 9, 0, 0, + 0, 4, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 0, 0, 7, 0, + 0, 1, 7, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 3, 6, 0, 4, 0 + }; + + if (solve(&sudokuAr)) { + prettyPrint(sudokuAr); + } else { + std.debug.print("Unsolvable\n", .{}); + } +} diff --git a/Task/Sum-and-product-of-an-array/ArkScript/sum-and-product-of-an-array.ark b/Task/Sum-and-product-of-an-array/ArkScript/sum-and-product-of-an-array.ark new file mode 100644 index 0000000000..c205a3fb07 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ArkScript/sum-and-product-of-an-array.ark @@ -0,0 +1,9 @@ +(import std.List :sum :product :reduce) + +(let array [1 2 3 4]) + +(assert (= (sum array) 10) "sum of array is 10") +(assert (= (reduce array (fun (a b) (+ a b))) 10) "reduction of array with + is 10") + +(assert (= (product array) 24) "product of array is 24") +(assert (= (reduce array (fun (a b) (* a b))) 24) "reduction of array with * is 24") diff --git a/Task/Sum-and-product-of-an-array/DuckDB/sum-and-product-of-an-array.duckdb b/Task/Sum-and-product-of-an-array/DuckDB/sum-and-product-of-an-array.duckdb new file mode 100644 index 0000000000..79201c9fdb --- /dev/null +++ b/Task/Sum-and-product-of-an-array/DuckDB/sum-and-product-of-an-array.duckdb @@ -0,0 +1,4 @@ +create or replace function product(lst) as list_reduce(lst, (acc,x) -> acc*x); + +# 10! +select range(1,11).product(); diff --git a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs index b69401289e..b30df6a4bf 100644 --- a/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs +++ b/Task/Sum-and-product-of-an-array/Haskell/sum-and-product-of-an-array-2.hs @@ -1,10 +1,6 @@ main :: IO () main = - mapM_ - print - ( fmap - ($ [1 .. 10]) - [ foldr (+) 0, - foldr (*) 1 - ] - ) + mapM_ print $ + [ foldr (+) 0, + foldr (*) 1 + ] <*> [[1 .. 10]] diff --git a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx index f9b04f5931..e81fef6879 100644 --- a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx +++ b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx @@ -1,17 +1,16 @@ -/*REXX program adds and multiplies N elements of a (populated) array @. */ -numeric digits 200 /*200 decimal digit #s (default is 9).*/ +/*REXX program adds and multiplies N elements of a (populated) array x. */ +numeric digits 100 /*100 decimal digit #s (default is 9).*/ parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/ - do j=1 for N /*build array of N elements (or 20?).*/ - @.j=j /*set 1st to 1, 3rd to 3, 8th to 8 ··· */ - end /*j*/ +do j=1 for N /*build array of N elements (or 20?).*/ + x.j=j /*set 1st to 1, 3rd to 3, 8th to 8 ··· */ + end /*j*/ sum=0 /*initialize SUM (variable) to zero. */ -prod=1 /*initialize PROD (variable) to unity.*/ - do k=1 for N - sum = sum + @.k /*add the element to the running total.*/ - prod = prod * @.k /*multiply element to running product. */ - end /*k*/ /* [↑] this pgm: same as N factorial.*/ +prod=1 /*initialize PROD (variable) to one */ +do k=1 for N + sum = sum + x.k /*add the element to the running total.*/ + prod = prod * x.k /*multiply element to running product. */ + end /*k*/ /* [?] this pgm: same as N factorial.*/ -say ' sum of ' m " elements for the @ array is: " sum -say ' product of ' m " elements for the @ array is: " prod - /*stick a fork in it, we're all done. */ +say ' sum of ' N ' elements for the x array is: ' sum +say ' product of ' N ' elements for the x array is: ' prod diff --git a/Task/Sum-digits-of-an-integer/ArkScript/sum-digits-of-an-integer.ark b/Task/Sum-digits-of-an-integer/ArkScript/sum-digits-of-an-integer.ark new file mode 100644 index 0000000000..6e12836de0 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/ArkScript/sum-digits-of-an-integer.ark @@ -0,0 +1,27 @@ +(import std.List) +(import std.String) + +(let to-base (fun (n base) { + (let o (string:ord n)) + + (let v + (if (and (>= o 48) (<= o 57)) + (- o 48) + (if (and (>= o 97) (<= o 122)) + (- o 87) + (if (and (>= o 65) (<= o 90)) + (- o 55) + o)))) + (mod v base) })) + +(let sum-digits (fun (n base) { + (let number + (if (not (= "String" (type n))) + (toString n) + n)) + (list:reduce (list:map number (fun (e) (to-base e base))) (fun (a b) (+ a b))) })) + +(assert (= (sum-digits 1 10) 1) "sum of digits in 10 (base 10) is 1") +(assert (= (sum-digits 1234 10) 10) "sum of digits in 1234 (base 10) is 10") +(assert (= (sum-digits "fe" 16) 29) "sum of digits in fe (base 16) is 29") +(assert (= (sum-digits "f0e" 16) 29) "sum of digits in f0e (base 16) is 29") diff --git a/Task/Sum-digits-of-an-integer/DuckDB/sum-digits-of-an-integer.duckdb b/Task/Sum-digits-of-an-integer/DuckDB/sum-digits-of-an-integer.duckdb new file mode 100644 index 0000000000..71763bc719 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/DuckDB/sum-digits-of-an-integer.duckdb @@ -0,0 +1,24 @@ +create or replace function number_sum_of_digits(i) as ( + with characters as (select unnest( regexp_extract_all(i::VARCHAR, '[0-9]')) as c) + select sum(c::uint8) from characters +); + +create or replace function string_sum_of_digits(str) as ( + with characters as (select unnest( regexp_extract_all(str::VARCHAR, '[0-9a-zA-Z]')) as c), + numbers as (select ascii(c) as a from characters) + select sum( + case when a < 65 then a - 48 -- 0 => 48 + when a < 97 then a - 55 -- A => 65 + else a - 87 -- a => 97 + end ) from numbers +); + +create or replace function sum_of_digits(x) as ( + case when typeof(x) = 'VARCHAR' then string_sum_of_digits(x) + else number_sum_of_digits(x) + end +); + +select sum_of_digits('f0E') = 29; +select sum_of_digits(1234) = 10; +select sum_of_digits(1.2e-34) = 10; diff --git a/Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer.pas b/Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer-1.pas similarity index 100% rename from Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer.pas rename to Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer-1.pas diff --git a/Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer-2.pas b/Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer-2.pas new file mode 100644 index 0000000000..c3f0e5746f --- /dev/null +++ b/Task/Sum-digits-of-an-integer/PascalABC.NET/sum-digits-of-an-integer-2.pas @@ -0,0 +1,8 @@ +//Modern way: +uses School; +begin + 1.digits.Sum.print; + 1234.digits.Sum.print; + $FE.digits(16).Sum.print; + $F0E.digits(16).Sum.print; +end. diff --git a/Task/Sum-digits-of-an-integer/Pluto/sum-digits-of-an-integer.pluto b/Task/Sum-digits-of-an-integer/Pluto/sum-digits-of-an-integer.pluto new file mode 100644 index 0000000000..4eab399a53 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Pluto/sum-digits-of-an-integer.pluto @@ -0,0 +1,10 @@ +local int = require("int") +local fmt = require("fmt") + +local tests = { {1, 10}, {1234, 10}, {0xfe, 16}, {0xf0e, 16}, {1411, 8}, {111, 3} } +print("The sum of the digits is: ") +for tests as test do + local [n, b] = test + local sum = int.digstat(n, b)[2] + fmt.print("%-5s in base %2d = %2d", fmt.itoa(n, b), b, sum) +end diff --git a/Task/Sum-multiples-of-3-and-5/DuckDB/sum-multiples-of-3-and-5.duckdb b/Task/Sum-multiples-of-3-and-5/DuckDB/sum-multiples-of-3-and-5.duckdb new file mode 100644 index 0000000000..beda2f0d20 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/DuckDB/sum-multiples-of-3-and-5.duckdb @@ -0,0 +1,9 @@ +create or replace function sum_multiples(n, d) as ( + select sum + from (select (n // d) as a, (d * a * (a+1)) // 2 as sum) +); + +# Sum of multiples of a or b that are less than n +create or replace function task(n, a, b) as ( + (n - 1).sum_multiples(a) + (n-1).sum_multiples(b) - (n-1).sum_multiples(a*b) +); diff --git a/Task/Sum-of-a-series/ArkScript/sum-of-a-series.ark b/Task/Sum-of-a-series/ArkScript/sum-of-a-series.ark new file mode 100644 index 0000000000..f99703db88 --- /dev/null +++ b/Task/Sum-of-a-series/ArkScript/sum-of-a-series.ark @@ -0,0 +1,9 @@ +(import std.Range :range :map) +(import std.List :sum) + +(let r (range 1 1000)) +(let sol (sum (map r (fun (x) (/ 1 (* x x)))))) + +(import std.Math :abs) + +(assert (< (abs (- sol 1.64493406685)) 0.0011) "S1000(2) is near Pi^2/6") diff --git a/Task/Sum-of-a-series/DuckDB/sum-of-a-series-1.duckdb b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-1.duckdb new file mode 100644 index 0000000000..05207a4f7f --- /dev/null +++ b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-1.duckdb @@ -0,0 +1 @@ +select list_sum( list_transform(range(1,1001), i -> 1 / (i*i))); diff --git a/Task/Sum-of-a-series/DuckDB/sum-of-a-series-2.duckdb b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-2.duckdb new file mode 100644 index 0000000000..eb55ed03f0 --- /dev/null +++ b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-2.duckdb @@ -0,0 +1,4 @@ +create or replace function s(n) as ( +select list_sum( list_transform(range(1,n+1), i -> 1 / (i*i))); + +select s(1000); diff --git a/Task/Sum-of-a-series/DuckDB/sum-of-a-series-3.duckdb b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-3.duckdb new file mode 100644 index 0000000000..560b1760cd --- /dev/null +++ b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-3.duckdb @@ -0,0 +1,7 @@ +create or replace function f(i) as (1 / (i*i)); + +create or replace function s(n) as ( + list_sum( list_transform(range(1,n+1), i -> f(i))) +); + +select s(1000); diff --git a/Task/Sum-of-a-series/DuckDB/sum-of-a-series-4.duckdb b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-4.duckdb new file mode 100644 index 0000000000..f43705e60e --- /dev/null +++ b/Task/Sum-of-a-series/DuckDB/sum-of-a-series-4.duckdb @@ -0,0 +1,5 @@ +create or replace function s(n) as ( + select sum(x) from (select (1 / (i*i)) as x from range(1,1+n) _(i) ) + ); + +select s(1000); diff --git a/Task/Sum-of-a-series/FutureBasic/sum-of-a-series.basic b/Task/Sum-of-a-series/FutureBasic/sum-of-a-series.basic new file mode 100644 index 0000000000..6bb0bc0e66 --- /dev/null +++ b/Task/Sum-of-a-series/FutureBasic/sum-of-a-series.basic @@ -0,0 +1,12 @@ +double local fn SumOfSeries( n as UInt32 ) + if n == 0 then return 0 + double sum = 0 + for int i = 1 to n + sum += 1.0 / i^2 + next +end fn = sum + +printf @"Precise sum: %.15f", fn SumOfSeries( 1000 ) +printf @"Approximate: %.15f", M_PI * M_PI / 6 + +HandleEvents diff --git a/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl b/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl index 673b50e055..281ff7b1bf 100644 --- a/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl +++ b/Task/Sum-of-a-series/Tcl/sum-of-a-series-1.tcl @@ -1,6 +1,9 @@ package require Tcl 8.5 namespace path {::tcl::mathop ::tcl::} ;# Ease of access to mathop commands -proc lsum_series {l} {+ {*}[lmap n $l {/ [** $n 2]}]} ;# an expr would be clearer, but this is a demonstration of mathop +# an expr would be clearer, +# but this is a demonstration of mathop + +proc lsum_series {l} {+ {*}[lmap n $l {/ [** $n 2]}]} # using range function defined below lsum_series [range 1 1001] ;# ==> 1.6439345666815615 diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Agena/sum-of-elements-below-main-diagonal-of-matrix.agena b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Agena/sum-of-elements-below-main-diagonal-of-matrix.agena new file mode 100644 index 0000000000..dec46aabf3 --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Agena/sum-of-elements-below-main-diagonal-of-matrix.agena @@ -0,0 +1,28 @@ +scope # sum the elements below the main diagonal of a matrix + + # returns the sum of the elements below the main diagonal + # of m, m must be a square matrix + local procedure lowerSum( m :: sequence ) :: number + local sum := 0; + for r from 2 to size m do + if size m[ r ] <> size m then + error( "Matrix is not square" ) + else + for c to r - 1 do + sum +:= m[ r, c ] + od + fi + od; + return sum + end; + + # task test case + print( lowerSum( seq( (/ 1, 3, 7, 8, 10 \) + , (/ 2, 4, 16, 14, 4 \) + , (/ 3, 1, 9, 18, 11 \) + , (/ 12, 14, 17, 18, 20 \) + , (/ 7, 1, 3, 9, 5 \) + ) + ) + ) +end diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Fennel/sum-of-elements-below-main-diagonal-of-matrix.fennel b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Fennel/sum-of-elements-below-main-diagonal-of-matrix.fennel new file mode 100644 index 0000000000..991cb8c7bb --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Fennel/sum-of-elements-below-main-diagonal-of-matrix.fennel @@ -0,0 +1,27 @@ +(do ;;; sum the elements below the main diagonal of a matrix + + (fn lower-sum [m] ; returns the sum of the elements below the main diagonal + ; of m, m must be a square matrix + (var sum 0) + (for [r 2 (length m)] + (if (not= (length (. m r)) (length m)) + (error "Matrix is not square") + ;else + (for [c 1 (- r 1)] + (set sum (+ sum (. (. m r) c))) + ) + ) + ) + sum + ) + + ; task test case + (print (lower-sum [ [ 1 3 7 8 10 ] + [ 2 4 16 14 4 ] + [ 3 1 9 18 11 ] + [ 12 14 17 18 20 ] + [ 7 1 3 9 5 ] + ] + ) + ) +) diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Fortran/sum-of-elements-below-main-diagonal-of-matrix.f b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Fortran/sum-of-elements-below-main-diagonal-of-matrix.f new file mode 100644 index 0000000000..4d70f7d2b9 --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Fortran/sum-of-elements-below-main-diagonal-of-matrix.f @@ -0,0 +1,27 @@ +program sum_below_diagonal + implicit none + integer, dimension(5,5) :: matrix + integer :: i, j, total_sum + + ! Initialize the matrix + matrix = reshape([1, 2, 3, 12, 7, & + 3, 4, 1, 14, 1, & + 7, 16, 9, 17, 3, & + 8, 14, 18, 18, 9, & + 10, 4, 11, 20, 5], shape(matrix), order=[1,2]) + + ! Compute the sum of elements below the main diagonal + total_sum = 0 + do i = 1, 5 + do j = 1, 5 + if (i > j) then + total_sum = total_sum + matrix(i, j) + end if + end do + end do + + ! Display the sum + print *, "The sum of elements below the main diagonal is: ", total_sum + +end program sum_below_diagonal +. diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Lua/sum-of-elements-below-main-diagonal-of-matrix.lua b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Lua/sum-of-elements-below-main-diagonal-of-matrix.lua new file mode 100644 index 0000000000..eda3a62551 --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Lua/sum-of-elements-below-main-diagonal-of-matrix.lua @@ -0,0 +1,27 @@ +do -- sum the elements below the main diagonal of a matrix + + -- returns the sum of the elements below the main diagonal + -- of m, m must be a square matrix + local function lowerSum( m ) + local sum = 0 + for r = 2, # m do + if # m[ r ] ~= # m then + error( "Matrix is not square" ) + else + for c = 1, r - 1 do + sum = sum + m[ r ][ c ] + end + end + end + return sum + end + + -- task test case + print( lowerSum{ { 1, 3, 7, 8, 10 } + , { 2, 4, 16, 14, 4 } + , { 3, 1, 9, 18, 11 } + , { 12, 14, 17, 18, 20 } + , { 7, 1, 3, 9, 5 } + } + ) +end diff --git a/Task/Sum-of-elements-below-main-diagonal-of-matrix/Pluto/sum-of-elements-below-main-diagonal-of-matrix.pluto b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Pluto/sum-of-elements-below-main-diagonal-of-matrix.pluto new file mode 100644 index 0000000000..68aa622790 --- /dev/null +++ b/Task/Sum-of-elements-below-main-diagonal-of-matrix/Pluto/sum-of-elements-below-main-diagonal-of-matrix.pluto @@ -0,0 +1,27 @@ +do -- sum the elements below the main diagonal of a matrix + + -- returns the sum of the elements below the main diagonal + -- of m, m must be a square matrix + local function lowerSum( m : table ) : number + local sum = 0 + for r = 2, # m do + if # m[ r ] != # m then + error( "Matrix is not square" ) + else + for c = 1, r - 1 do + sum += m[ r ][ c ] + end + end + end + return sum + end + + -- task test case + print( lowerSum{ { 1, 3, 7, 8, 10 } + , { 2, 4, 16, 14, 4 } + , { 3, 1, 9, 18, 11 } + , { 12, 14, 17, 18, 20 } + , { 7, 1, 3, 9, 5 } + } + ) +end diff --git a/Task/Sum-of-squares/ArkScript/sum-of-squares.ark b/Task/Sum-of-squares/ArkScript/sum-of-squares.ark new file mode 100644 index 0000000000..747205c437 --- /dev/null +++ b/Task/Sum-of-squares/ArkScript/sum-of-squares.ark @@ -0,0 +1,16 @@ +(import std.List) + +(assert (= + (list:sum + (list:map + [1 2 3 4 5] + (fun (x) (* x x)))) + 55) + "sum of list is 55") +(assert (= + (list:sum + (list:map + [] + (fun (x) (* x x)))) + 0) + "sum of empty list is 0") diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb new file mode 100644 index 0000000000..c3dc742e32 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-1.duckdb @@ -0,0 +1 @@ +select coalesce(sum(pow(x,2)), 0) from t; diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb new file mode 100644 index 0000000000..fbf8860132 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-2.duckdb @@ -0,0 +1,5 @@ +create or replace function ss(columnname, tablename) as ( + coalesce( + (select sum(pow( COLUMNS(x-> x = columnname),2)) as s from query_table(tablename)), + 0) +); diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb new file mode 100644 index 0000000000..2ed26fd794 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-3.duckdb @@ -0,0 +1,3 @@ +create or replace table t as (from values (1),(2) t(i)); + +select ss('i', 't') as "ss of t.i"; diff --git a/Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb b/Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb new file mode 100644 index 0000000000..3f0fcee4c6 --- /dev/null +++ b/Task/Sum-of-squares/DuckDB/sum-of-squares-4.duckdb @@ -0,0 +1,8 @@ +create or replace function ss(lst) as ( + select (case when length(lst) = 0 then 0 + else list_sum(list_transform( lst, x -> x*x)) + end) +); + +# Example +select ss([]) as 'ss of []', ss([1.0,2.0,3.0]) as "ss of list"; diff --git a/Task/Sum-to-100/EasyLang/sum-to-100.easy b/Task/Sum-to-100/EasyLang/sum-to-100.easy index 4306c8b04c..bbdf7caef6 100644 --- a/Task/Sum-to-100/EasyLang/sum-to-100.easy +++ b/Task/Sum-to-100/EasyLang/sum-to-100.easy @@ -29,7 +29,7 @@ proc init . f[i] = evaluate i . . -call init +init proc out code . a = 19683 b = 6561 diff --git a/Task/Sum-to-100/FutureBasic/sum-to-100.basic b/Task/Sum-to-100/FutureBasic/sum-to-100.basic new file mode 100644 index 0000000000..b095db7332 --- /dev/null +++ b/Task/Sum-to-100/FutureBasic/sum-to-100.basic @@ -0,0 +1,118 @@ +// +// Sum to 100 solutions +// +// Using 123456789 digits so the resulting +// mathematical expression adds up to a 100 +// using "-" and "+" operators only +// + +Int maxPerm, allDigits + +maxPerm = 13122 //2 * 3 ^ 8 max permutation +allDigits = 123456789 + +Int sum(13121) +CFStringRef equation + +// Get sum of one of the permutation +// on entry: n = permutation number +// on exit: ret = sum +// modifies global var equation + +local fn doEval( n as UInt32) as Int + + CFStringRef evalstr + boolean doAdd = _False + Int ret, cPtr, x, sw + + evalstr = @"9" + ret = 0: cPtr = 9 + doAdd = (n => (maxPerm / 2)) + + for x = 8 to 1 step -1 //do 87654321 + sw = n % 3 + if sw == 0 then cPtr += x * 10^(1 + fix(log(cPtr + 0.5) / log(10))) + if sw == 1 + ret += cPtr + cPtr = x + evalstr = concat (@" + ",evalstr) + end if + if sw == 2 + ret -= cPtr + cPtr = x + evalstr = concat (@" - ",evalstr) + end if + evalstr = concat(mid(str(x),1),evalstr) + n = fix(n/3) + next x + + if doAdd == 0 + evalstr = concat(@" - ", evalstr) + ret -= cPtr + else + ret += cPtr + end if + + evalstr = concat(str(ret),@" = ",evalstr) + equation = evalstr +end fn = ret + +window 1,@"Sum to 100" + + +Int x, y, curr + +// calculate all solutions 2 * 3 ^ 8 +// +for x = maxPerm-1 to 0 step -1 + equation = @"" + curr = fn DoEval(x) + sum(x) = curr + if curr = 100 then print equation +next x +print + +// sum with most solution + +Int i,j,sav,most,tot + +for x = 0 to maxPerm-1 + sav = 0 + for y = 0 to maxPerm-1 + if sum(y) == sum(x) then sav++ + next y + if sav > tot then tot = sav: most = sum(x) +next x +print most;" has most solutions occurring ";tot;" times." + +// lowest non negative with no solution + +boolean sk = _False +for x = 0 to allDigits-1 + for y = 0 to maxPerm-1 + if sum(y) == x then sk = _True: y = maxPerm + next y + if !sk + print "The first non negative number that has no solution is ";x + exit for + else + sk = _False + end if +next x + +// ten highest with solution + +print +print "The ten highest numbers that can be expressed:" + +most = 0 +for x = 1 to 10 + for y = 0 to maxPerm-1 + if sum(y) > sum(most) then most = y + next y + fn doEval(most) + print equation + sum(most) = 0 +next x + +HandleEvents diff --git a/Task/Superellipse/EasyLang/superellipse.easy b/Task/Superellipse/EasyLang/superellipse.easy index 0eebece6bb..f39215af3d 100644 --- a/Task/Superellipse/EasyLang/superellipse.easy +++ b/Task/Superellipse/EasyLang/superellipse.easy @@ -2,11 +2,10 @@ n = 2.5 a = 200 b = 200 glinewidth 0.2 +gpenup while t <= 360 - xp = x - yp = y x = (pow abs cos t (2 / n) * a * sign cos t) / 5 + 50 y = (pow abs sin t (2 / n) * b * sign sin t) / 5 + 50 - if t > 0 : gline xp yp x y + glineto x y t += 0.5 . diff --git a/Task/Superellipse/Maxima/superellipse.maxima b/Task/Superellipse/Maxima/superellipse.maxima new file mode 100644 index 0000000000..46e7281dde --- /dev/null +++ b/Task/Superellipse/Maxima/superellipse.maxima @@ -0,0 +1,7 @@ +wxdraw2d( + implicit( + abs(x/200)^(2.5)+abs(y/200)^2.5=1, + x,-250,250, + y,-250,250 + ) +)$ diff --git a/Task/Superellipse/Python/superellipse.py b/Task/Superellipse/Python/superellipse.py index 0033b55285..f80e004ab5 100644 --- a/Task/Superellipse/Python/superellipse.py +++ b/Task/Superellipse/Python/superellipse.py @@ -1,5 +1,4 @@ # Superellipse drawing in Python 2.7.9 -# pic can see at http://www.imgup.cz/image/712 import matplotlib.pyplot as plt from math import sin, cos, pi diff --git a/Task/Superpermutation-minimisation/JavaScript/superpermutation-minimisation.js b/Task/Superpermutation-minimisation/JavaScript/superpermutation-minimisation.js new file mode 100644 index 0000000000..b2b1728043 --- /dev/null +++ b/Task/Superpermutation-minimisation/JavaScript/superpermutation-minimisation.js @@ -0,0 +1,61 @@ +const nMax = 12; + +let superperm; +let pos; +let count = new Array(nMax); + +function factSum(n) { + let sum = 0; + for (let m = 1; m <= n; m++) { + let factorial = 1; + for (let i = 1; i <= m; i++) { + factorial *= i; + } + sum += factorial; + } + return sum; +} + +function r(n) { + if (n === 0) { + return false; + } + + const c = superperm[pos - n]; + if (--count[n] === 0) { + count[n] = n; + if (!r(n - 1)) { + return false; + } + } + superperm[pos++] = c; + return true; +} + +function superPerm(n) { + const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + pos = n; + superperm = new Array(factSum(n)); + + for (let i = 0; i < n + 1; i++) { + count[i] = i; + } + for (let i = 1; i < n + 1; i++) { + superperm[i - 1] = chars.charAt(i); + } + + while (r(n)) { + // Continue until r(n) returns false + } +} + +function main() { + for (let n = 0; n < nMax; n++) { + superPerm(n); + console.log(`superPerm(${n.toString().padStart(2, ' ')}) len = ${superperm.length}`); + } +} + +// Run the main function +main(); diff --git a/Task/Symmetric-difference/DuckDB/symmetric-difference.duckdb b/Task/Symmetric-difference/DuckDB/symmetric-difference.duckdb new file mode 100644 index 0000000000..9c50911d10 --- /dev/null +++ b/Task/Symmetric-difference/DuckDB/symmetric-difference.duckdb @@ -0,0 +1,12 @@ +create or replace function arrxor(list1, list2) as + (select array_agg(elements) from + (select min(arr) as mn, max(arr) as mx, elements from + ( (select 1, unnest(list1)) + union all + (select 2, unnest(list2)) ) as t(arr, elements) + group by elements + having mn = mx) ) ; + +# Example: + +select arrxor(['this','is','a','test'], ['also','part','of','a','test'] ) as arrxor; diff --git a/Task/Symmetric-difference/Pluto/symmetric-difference.pluto b/Task/Symmetric-difference/Pluto/symmetric-difference.pluto new file mode 100644 index 0000000000..55e6d22b54 --- /dev/null +++ b/Task/Symmetric-difference/Pluto/symmetric-difference.pluto @@ -0,0 +1,10 @@ +require "map" +local fmt = require "fmt" + +local a = set.of("John", "Bob", "Mary", "Serena") +local b = set.of("Jim", "Mary", "John", "Bob") +fmt.print("A = %s", a) +fmt.print("B = %s", b) +fmt.print("A - B = %s", a:except(b)) +fmt.print("B - A = %s", b:except(a)) +fmt.print("A △ B = %s", a:symdiff(b)) diff --git a/Task/System-time/Pluto/system-time.pluto b/Task/System-time/Pluto/system-time.pluto new file mode 100644 index 0000000000..50fb7a9b31 --- /dev/null +++ b/Task/System-time/Pluto/system-time.pluto @@ -0,0 +1 @@ +print(os.date()) diff --git a/Task/System-time/REBOL/system-time.rebol b/Task/System-time/REBOL/system-time.rebol index a6ec70b1c1..5b4a3a6e58 100644 --- a/Task/System-time/REBOL/system-time.rebol +++ b/Task/System-time/REBOL/system-time.rebol @@ -1,2 +1,3 @@ -now +print now +print now/precise print rejoin [now/year "-" now/month "-" now/day " " now/time] diff --git a/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-1.duckdb b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-1.duckdb new file mode 100644 index 0000000000..b2a37091ea --- /dev/null +++ b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-1.duckdb @@ -0,0 +1,7 @@ +CREATE TABLE address_USA ( + address_ID INTEGER PRIMARY KEY, + address_Street TEXT, + address_City TEXT, + address_State TEXT, + address_Zip INTEGER +); diff --git a/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-2.duckdb b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-2.duckdb new file mode 100644 index 0000000000..9178c8e4bc --- /dev/null +++ b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-2.duckdb @@ -0,0 +1 @@ +CREATE SEQUENCE 'addrID' START 1; diff --git a/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-3.duckdb b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-3.duckdb new file mode 100644 index 0000000000..624996ef19 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-3.duckdb @@ -0,0 +1,7 @@ +CREATE TABLE Address ( + addrID Integer PRIMARY KEY DEFAULT NEXTVAL('addrID'), + addrStreet Varchar(50) not null, + addrCity Varchar(25) not null, + addrState Char(2) not null, + addrZIP Char(10) not null +); diff --git a/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-4.duckdb b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-4.duckdb new file mode 100644 index 0000000000..33a020f58a --- /dev/null +++ b/Task/Table-creation-Postal-addresses/DuckDB/table-creation-postal-addresses-4.duckdb @@ -0,0 +1 @@ +INSERT INTO Address values (DEFAULT, '1 Main St', 'Townsend', 'ZZ', 54321); diff --git a/Task/Tarjan/JavaScript/tarjan.js b/Task/Tarjan/JavaScript/tarjan.js new file mode 100644 index 0000000000..0a418f3dbc --- /dev/null +++ b/Task/Tarjan/JavaScript/tarjan.js @@ -0,0 +1,83 @@ +class Graph { + constructor(size) { + this.adjacencyLists = []; + this.vertices = []; + this.index = 0; + this.stack = []; + this.numbers = new Map(); + this.lowlinks = new Map(); + this.stronglyConnectedComponents = []; + + for (let i = 0; i < size; i++) { + this.vertices.push(i); + this.adjacencyLists.push(new Set()); + } + } + + addDirectedEdge(from, to) { + this.adjacencyLists[from].add(to); + } + + getSCC() { + for (const vertex of this.vertices) { + if (!this.numbers.has(vertex)) { + this.stronglyConnect(vertex); + } + } + + return this.stronglyConnectedComponents; + } + + stronglyConnect(vertex) { + this.numbers.set(vertex, this.index); + this.lowlinks.set(vertex, this.index); + this.index += 1; + this.stack.push(vertex); + + for (const adjacent of this.adjacencyLists[vertex]) { + if (!this.numbers.has(adjacent)) { + this.stronglyConnect(adjacent); + this.lowlinks.set(vertex, Math.min(this.lowlinks.get(vertex), this.lowlinks.get(adjacent))); + } else if (this.stack.includes(adjacent)) { + this.lowlinks.set(vertex, Math.min(this.lowlinks.get(vertex), this.numbers.get(adjacent))); + } + } + + if (this.lowlinks.get(vertex) === this.numbers.get(vertex)) { + const stronglyConnectedComponent = new Set(); + let top; + do { + top = this.stack.pop(); + stronglyConnectedComponent.add(top); + } while (top !== vertex); + + this.stronglyConnectedComponents.push(stronglyConnectedComponent); + } + } +} + +// Main function equivalent +function main() { + const graph = new Graph(8); + + graph.addDirectedEdge(0, 1); + graph.addDirectedEdge(1, 2); + graph.addDirectedEdge(1, 7); + graph.addDirectedEdge(2, 3); + graph.addDirectedEdge(2, 6); + graph.addDirectedEdge(3, 4); + graph.addDirectedEdge(4, 2); + graph.addDirectedEdge(4, 5); + graph.addDirectedEdge(6, 3); + graph.addDirectedEdge(6, 5); + graph.addDirectedEdge(7, 0); + graph.addDirectedEdge(7, 6); + + console.log("The strongly connected components are: "); + for (const component of graph.getSCC()) { + console.log(component); + } +} + +// Run the main function +main(); diff --git a/Task/Tarjan/Zig/tarjan.zig b/Task/Tarjan/Zig/tarjan.zig new file mode 100644 index 0000000000..302114c85d --- /dev/null +++ b/Task/Tarjan/Zig/tarjan.zig @@ -0,0 +1,200 @@ +const std = @import("std"); +const ArrayList = std.ArrayList; +const HashMap = std.HashMap; +const print = std.debug.print; +const Allocator = std.mem.Allocator; + +// Simple graph representation using adjacency lists +const Graph = struct { + neighbors: ArrayList(ArrayList(usize)), + allocator: Allocator, + + const Self = @This(); + + pub fn init(allocator: Allocator, size: usize) !Self { + var neighbors = ArrayList(ArrayList(usize)).init(allocator); + try neighbors.ensureTotalCapacity(size); + + for (0..size) |_| { + try neighbors.append(ArrayList(usize).init(allocator)); + } + + return Self{ + .neighbors = neighbors, + .allocator = allocator, + }; + } + + pub fn deinit(self: *Self) void { + for (self.neighbors.items) |*neighbor_list| { + neighbor_list.deinit(); + } + self.neighbors.deinit(); + } + + pub fn addEdge(self: *Self, from: usize, to: usize) !void { + std.debug.assert(to < self.len()); + try self.neighbors.items[from].append(to); + } + + pub fn addEdges(self: *Self, from: usize, to: []const usize) !void { + const limit = self.len(); + for (to) |vertex| { + std.debug.assert(vertex < limit); + try self.neighbors.items[from].append(vertex); + } + } + + pub fn getEdges(self: *const Self, vertex: usize) []const usize { + return self.neighbors.items[vertex].items; + } + + pub fn isEmpty(self: *const Self) bool { + return self.neighbors.items.len == 0; + } + + pub fn len(self: *const Self) usize { + return self.neighbors.items.len; + } +}; + +const VertexState = struct { + index: usize, + low_link: usize, + on_stack: bool, +}; + +const Tarjan = struct { + graph: *const Graph, + index: usize, + stack: ArrayList(usize), + state: ArrayList(VertexState), + components: ArrayList(ArrayList(usize)), + allocator: Allocator, + + const Self = @This(); + const INVALID_INDEX: usize = std.math.maxInt(usize); + + pub fn init(allocator: Allocator, graph: *const Graph) !Self { + var state = ArrayList(VertexState).init(allocator); + try state.ensureTotalCapacity(graph.len()); + + for (0..graph.len()) |_| { + try state.append(VertexState{ + .index = INVALID_INDEX, + .low_link = INVALID_INDEX, + .on_stack = false, + }); + } + + return Self{ + .graph = graph, + .index = 0, + .stack = ArrayList(usize).init(allocator), + .state = state, + .components = ArrayList(ArrayList(usize)).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *Self) void { + for (self.components.items) |*component| { + component.deinit(); + } + self.components.deinit(); + self.stack.deinit(); + self.state.deinit(); + } + + pub fn walk(allocator: Allocator, graph: *const Graph) !ArrayList(ArrayList(usize)) { + var tarjan = try Self.init(allocator, graph); + defer tarjan.deinit(); + + return try tarjan.visitAll(); + } + + fn visitAll(self: *Self) !ArrayList(ArrayList(usize)) { + for (0..self.graph.len()) |vertex| { + if (self.state.items[vertex].index == INVALID_INDEX) { + try self.visit(vertex); + } + } + + // Move components out to avoid double-free + var result = ArrayList(ArrayList(usize)).init(self.allocator); + try result.ensureTotalCapacity(self.components.items.len); + + for (self.components.items) |component| { + try result.append(component); + } + + // Clear the original components to avoid double-free + self.components.clearRetainingCapacity(); + + return result; + } + + fn visit(self: *Self, v: usize) !void { + self.state.items[v].index = self.index; + self.state.items[v].low_link = self.index; + self.index += 1; + try self.stack.append(v); + self.state.items[v].on_stack = true; + + for (self.graph.getEdges(v)) |w| { + if (self.state.items[w].index == INVALID_INDEX) { + try self.visit(w); + const w_low_link = self.state.items[w].low_link; + self.state.items[v].low_link = @min(self.state.items[v].low_link, w_low_link); + } else if (self.state.items[w].on_stack) { + const w_index = self.state.items[w].index; + self.state.items[v].low_link = @min(self.state.items[v].low_link, w_index); + } + } + + if (self.state.items[v].low_link == self.state.items[v].index) { + var component = ArrayList(usize).init(self.allocator); + + while (true) { + const w = self.stack.pop().?; + self.state.items[w].on_stack = false; + try component.append(w); + if (w == v) { + break; + } + } + + try self.components.append(component); + } + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var graph = try Graph.init(allocator, 8); + defer graph.deinit(); + + try graph.addEdge(0, 1); + try graph.addEdge(2, 0); + try graph.addEdges(5, &[_]usize{ 2, 6 }); + try graph.addEdge(6, 5); + try graph.addEdge(1, 2); + try graph.addEdges(3, &[_]usize{ 1, 2, 4 }); + try graph.addEdges(4, &[_]usize{ 5, 3 }); + try graph.addEdges(7, &[_]usize{ 4, 7, 6 }); + + var components = try Tarjan.walk(allocator, &graph); + defer { + for (components.items) |*component| { + component.deinit(); + } + components.deinit(); + } + + for (components.items) |component| { + print("{any}\n", .{component.items}); + } +} diff --git a/Task/Tau-function/FutureBasic/tau-function.basic b/Task/Tau-function/FutureBasic/tau-function.basic new file mode 100644 index 0000000000..98dc1db0f1 --- /dev/null +++ b/Task/Tau-function/FutureBasic/tau-function.basic @@ -0,0 +1,39 @@ +// +// Tau Function +// +// FutureBasic 7.0.34, August 2025 R.W +// +// Given a positive integer, count the +// number of its positive divisors. +//--------------------------------------- + +// Given an integer, returns the +// Tau positive integer + +local fn Tau( n as Int) as Int + int x, result + if n < 3 + result = n + else + result = 2 + for x = 2 to fix((n + 1) / 2) + if n % x == 0 then result++ + next x + end if +end fn = result + + +Window 1,@"Tau Function" + +print +print "First 100 positive integer Tau numbers:" +print + +int x + +for x = 1 to 100 + print using "####";fn Tau(x); + if x % 10 == 0 then print +next x + +handleEvents diff --git a/Task/Tau-function/Pluto/tau-function.pluto b/Task/Tau-function/Pluto/tau-function.pluto new file mode 100644 index 0000000000..6a7ea1b896 --- /dev/null +++ b/Task/Tau-function/Pluto/tau-function.pluto @@ -0,0 +1,11 @@ +local int = require "int" +local fmt = require "fmt" + +local limit = 100 +local tau = {} +local i = 0 +print($"The tau functions for the first {limit} positive integers are:") +for i = 1, limit do + tau:insert(int.divstat(i)[1]) +end +fmt.tprint("%2d ", tau, 10) diff --git a/Task/Tau-number/FutureBasic/tau-number.basic b/Task/Tau-number/FutureBasic/tau-number.basic new file mode 100644 index 0000000000..2846e38f1b --- /dev/null +++ b/Task/Tau-number/FutureBasic/tau-number.basic @@ -0,0 +1,46 @@ +// +// Tau Numbers +// +// FutureBasic 7.0.34, August 2025 R.W +// +//------------------------------------- +// +// Given an integer, returns the +// Tau positive integer +local fn Tau( n as Int) as Int + int x, result + if n < 3 + result = n + else + result = 2 + for x = 2 to fix((n + 1) / 2) + if n % x == 0 then result++ + next x + end if +end fn = result + +// Returns True if n is a Tau number +local fn isTau(n as Int) as boolean + boolean result = _False + if n % fn Tau(n) == 0 then result = _True +end fn = result + +window 1,@"Tau numbers" + +print +print " First 100 Tau numbers:" +print + +int x, c, res +c = 1: x = 1 +while c < 100 + if fn isTau(x) + print using "######";x; + if (c % 9 == 0) then print + c++ + end if + x++ +wend + +handleEvents +// diff --git a/Task/Tau-number/Pluto/tau-number.pluto b/Task/Tau-number/Pluto/tau-number.pluto new file mode 100644 index 0000000000..517c5d4493 --- /dev/null +++ b/Task/Tau-number/Pluto/tau-number.pluto @@ -0,0 +1,13 @@ +local int = require "int" +local fmt = require "fmt" + +local limit = 100 +local tau = {} +local i = 0 +print($"The first {limit} tau numbers are:") +repeat + ++i + local dc = int.divstat(i)[1] + if i % dc == 0 then tau:insert(i) end +until #tau == limit +fmt.tprint("%4d ", tau, 10) diff --git a/Task/Terminal-control-Clear-the-screen/Pluto/terminal-control-clear-the-screen.pluto b/Task/Terminal-control-Clear-the-screen/Pluto/terminal-control-clear-the-screen.pluto new file mode 100644 index 0000000000..d1ac1c7150 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Pluto/terminal-control-clear-the-screen.pluto @@ -0,0 +1,3 @@ +require "ansi" + +screen.clear() diff --git a/Task/Terminal-control-Coloured-text/Pluto/terminal-control-coloured-text.pluto b/Task/Terminal-control-Coloured-text/Pluto/terminal-control-coloured-text.pluto new file mode 100644 index 0000000000..dcb6fc00dd --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Pluto/terminal-control-coloured-text.pluto @@ -0,0 +1,16 @@ +require "ansi" + +local colors = {"Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"} +-- Display words using 'bright' colors +for i = 2, 8 do screen.print(colors[i], color[colors[i]]) end -- Red to White + +os.sleep(3000) -- wait for 3 seconds +screen.setBack(color.white) -- set background color to white +screen.clear() -- clear screen to background color & home the cursor + +-- display words again using 'blinking' colors +screen.setStyle("blink") -- blink on +for i = 1, 7 do screen.print(colors[i], color[colors[i]]) end -- Black to Cyan +os.sleep(3000) -- wait for 3 more seconds +screen.reset() -- reset all attributes +screen.clear() -- clear screen to background color & home the cursor diff --git a/Task/Terminal-control-Cursor-movement/Pluto/terminal-control-cursor-movement.pluto b/Task/Terminal-control-Cursor-movement/Pluto/terminal-control-cursor-movement.pluto new file mode 100644 index 0000000000..5abdc724bb --- /dev/null +++ b/Task/Terminal-control-Cursor-movement/Pluto/terminal-control-cursor-movement.pluto @@ -0,0 +1,26 @@ +require "ansi" + +screen.clear() -- clear terminal +cursor.move(12, 40) -- move to (12, 40) +os.sleep(2000) +cursor.left() -- move left +screen.fwrite("+\b") +os.sleep(2000) +cursor.right() -- move right +screen.fwrite("x\b") +os.sleep(2000) +cursor.up() -- move up +screen.fwrite("!\b") +os.sleep(2000) +cursor.down() -- move down +screen.fwrite("?\b") +os.sleep(2000) +cursor.col() -- move to beginning of line +os.sleep(2000) +cursor.col(80) -- move to end of line (assuming 80 column terminal) +os.sleep(2000) +cursor.home() -- move to top left corner +os.sleep(2000) +cursor.move(24, 80) -- move to bottom right corner (assuming 80 x 24 terminal) +os.sleep(2000) +screen.clear() -- clear screen again before quitting diff --git a/Task/Terminal-control-Cursor-positioning/Pluto/terminal-control-cursor-positioning.pluto b/Task/Terminal-control-Cursor-positioning/Pluto/terminal-control-cursor-positioning.pluto new file mode 100644 index 0000000000..fc0122df8f --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Pluto/terminal-control-cursor-positioning.pluto @@ -0,0 +1,5 @@ +require "ansi" + +screen.clear() -- clear the terminal +cursor.move(6, 3) -- move to (6, 3) +print("Hello") -- print 'Hello' diff --git a/Task/Terminal-control-Dimensions/Pluto/terminal-control-dimensions.pluto b/Task/Terminal-control-Dimensions/Pluto/terminal-control-dimensions.pluto new file mode 100644 index 0000000000..82f518c8b5 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Pluto/terminal-control-dimensions.pluto @@ -0,0 +1,6 @@ +local tmp = "_pluto_.tmp" +os.execute($"stty size > {tmp}") +local res = io.contents(tmp):strip() +io.remove(tmp) +local [h, w] = res:split(" ") +print($"Terminal width = {w} and height = {h}") diff --git a/Task/Terminal-control-Display-an-extended-character/Pluto/terminal-control-display-an-extended-character.pluto b/Task/Terminal-control-Display-an-extended-character/Pluto/terminal-control-display-an-extended-character.pluto new file mode 100644 index 0000000000..e74448fb82 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Pluto/terminal-control-display-an-extended-character.pluto @@ -0,0 +1 @@ +print "£" diff --git a/Task/Terminal-control-Hiding-the-cursor/Pluto/terminal-control-hiding-the-cursor.pluto b/Task/Terminal-control-Hiding-the-cursor/Pluto/terminal-control-hiding-the-cursor.pluto new file mode 100644 index 0000000000..68ae069e17 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Pluto/terminal-control-hiding-the-cursor.pluto @@ -0,0 +1,6 @@ +require "ansi" + +cursor.hide() +os.sleep(3000) +cursor.show() +os.sleep(3000) diff --git a/Task/Terminal-control-Inverse-video/Pluto/terminal-control-inverse-video.pluto b/Task/Terminal-control-Inverse-video/Pluto/terminal-control-inverse-video.pluto new file mode 100644 index 0000000000..cffe10e500 --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Pluto/terminal-control-inverse-video.pluto @@ -0,0 +1,6 @@ +require "ansi" + +screen.setStyle(style.inverse) +print("Inverse") +screen.resetStyle() +print("Normal") diff --git a/Task/Terminal-control-Preserve-screen/Pluto/terminal-control-preserve-screen.pluto b/Task/Terminal-control-Preserve-screen/Pluto/terminal-control-preserve-screen.pluto new file mode 100644 index 0000000000..44e65a7050 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Pluto/terminal-control-preserve-screen.pluto @@ -0,0 +1,10 @@ +require "ansi" + +screen.enablebuffer() +print("Alternate screen buffer") +for i = 5, 1, -1 do + local s = (i != 1) ? "s" : "" + screen.fwrite($"\rGoing back in {i} second{s}...") + os.sleep(1000) +end +screen.disablebuffer() diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Pluto/terminal-control-ringing-the-terminal-bell.pluto b/Task/Terminal-control-Ringing-the-terminal-bell/Pluto/terminal-control-ringing-the-terminal-bell.pluto new file mode 100644 index 0000000000..3fde07b32e --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Pluto/terminal-control-ringing-the-terminal-bell.pluto @@ -0,0 +1 @@ +print "\a" diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/YAMLScript/terminal-control-ringing-the-terminal-bell.ys b/Task/Terminal-control-Ringing-the-terminal-bell/YAMLScript/terminal-control-ringing-the-terminal-bell.ys new file mode 100644 index 0000000000..9395df93ef --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/YAMLScript/terminal-control-ringing-the-terminal-bell.ys @@ -0,0 +1,2 @@ +!YS-v0 +print: char(7) diff --git a/Task/Terminal-control-Unicode-output/Pluto/terminal-control-unicode-output.pluto b/Task/Terminal-control-Unicode-output/Pluto/terminal-control-unicode-output.pluto new file mode 100644 index 0000000000..798a1d4085 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Pluto/terminal-control-unicode-output.pluto @@ -0,0 +1,10 @@ +local function supports_unicode() + local lang = os.getenv("LANG") + return "UTF-8" in lang or "utf-8" in lang +end + +if supports_unicode() then + print($"Unicode is supported on this terminal and U+25B3 is : {"\u{25B3}"}") +else + error("Unicode is not supported on this terminal") +end diff --git a/Task/Test-integerness/Ada/test-integerness.ada b/Task/Test-integerness/Ada/test-integerness.ada new file mode 100644 index 0000000000..dc2ec8dfb7 --- /dev/null +++ b/Task/Test-integerness/Ada/test-integerness.ada @@ -0,0 +1,49 @@ +-- Big_Numbers is an Ada 2022 unit + +with Ada.Numerics.Big_Numbers.Big_Integers, + Ada.Numerics.Big_Numbers.Big_Reals, + Ada.Numerics.Generic_Complex_Types, + Ada.Text_IO; + +use Ada.Numerics.Big_Numbers.Big_Integers, + Ada.Numerics.Big_Numbers.Big_Reals, + Ada.Text_IO; + +procedure Test_Integer is + -- These are the only numerical types defined in package + -- "Standard" which is always incuded. 'Base also covers anything + -- with the same Base types. + function Is_Integer (N : Integer'Base) return Boolean is (True); + function Is_Integer (N : Float'Base) return Boolean is (Float'Base'Floor (N) = N); + + -- Additional types defined in the standard library. + function Is_Integer (N : Big_Integer) return Boolean is (True); + + -- The type says real, but these are rational approximations of + -- real numbers. + function Is_Integer (N : Big_Real) return Boolean is (Denominator (N) = 1); + + package Complex_Float is new Ada.Numerics.Generic_Complex_Types (Float); + use Complex_Float; + + function Is_Integer (N : Complex) return Boolean + is (Im (N) = 0.0 and then Is_Integer (Re (N))); + + Int_One : Integer := 1; + Flo_One : Float := 1.0; + Flo_OneH : Float := 1.5; + BInt_One : Big_Integer := To_Big_Integer (1); + BFlo_One : Big_Real := To_Big_Real (1); + BFlo_OneH : Big_Real := From_String ("1.5"); + CInt_One : Complex := 1.0 + 0.0 * I; + CInt_OneI : Complex := 1.0 + 1.0 * I; +begin + Put_Line (Int_One'Image & " is integer? " & Is_Integer (Int_One)'Image); + Put_Line (Flo_One'Image & " is integer? " & Is_Integer (Flo_One)'Image); + Put_Line (Flo_OneH'Image & " is integer? " & Is_Integer (Flo_OneH)'Image); + Put_Line (BInt_One'Image & " is integer? " & Is_Integer (BInt_One)'Image); + Put_Line (BFlo_One'Image & " is integer? " & Is_Integer (BFlo_One)'Image); + Put_Line (BFlo_OneH'Image & " is integer? " & Is_Integer (BFlo_OneH)'Image); + Put_Line (CInt_One'Image & " is integer? " & Is_Integer (CInt_One)'Image); + Put_Line (CInt_OneI'Image & " is integer? " & Is_Integer (CInt_OneI)'Image); +end Test_Integer; diff --git a/Task/Test-integerness/DuckDB/test-integerness-1.duckdb b/Task/Test-integerness/DuckDB/test-integerness-1.duckdb new file mode 100644 index 0000000000..33341025fc --- /dev/null +++ b/Task/Test-integerness/DuckDB/test-integerness-1.duckdb @@ -0,0 +1,3 @@ +create type Complex as struct (r float, i float); + +create type Rational as struct (n integer, d integer); diff --git a/Task/Test-integerness/DuckDB/test-integerness-2.duckdb b/Task/Test-integerness/DuckDB/test-integerness-2.duckdb new file mode 100644 index 0000000000..9644451eb4 --- /dev/null +++ b/Task/Test-integerness/DuckDB/test-integerness-2.duckdb @@ -0,0 +1,16 @@ +create or replace function number_integerp(x) as ( + x = trunc(x) +); + +# Return true iff x has the type signature of a Rational +# with the denominator dividing the numerator evenly. +create or replace function rational_integerp(x) as ( + typeof(x) = 'STRUCT(n INTEGER, d INTEGER)' + and x.n % x.d = 0 +); + +# Return true if x can be cast to a Complex with +# the imaginary part equal to 0 and an integer real part. +create or replace function complex_integerp(x) as ( + (x::Complex).i = 0 and number_integerp(x.r) +); diff --git a/Task/Test-integerness/Pluto/test-integerness.pluto b/Task/Test-integerness/Pluto/test-integerness.pluto new file mode 100644 index 0000000000..0b3b0e6387 --- /dev/null +++ b/Task/Test-integerness/Pluto/test-integerness.pluto @@ -0,0 +1,37 @@ +require "complex" +require "rat" +require "table2" +local fmt = require "fmt" + +local tests1 = {25.000000, 24.999999, 25.000100} +local tests2 = {-2.1e120} +local tests3 = {-5e-2, 0/0, 1/0} +local tests4 = {complex.of(5, 0), complex.of(5, -5)} +local tests5 = {rat.of(24, 8), rat.of(-5, 1), rat.of(17, 2)} +local tests6 = tests1:joined({-5e-2}) + +print("Using exact arithmetic:\n") +for tests1 as t do + fmt.print(" %-9.6f is integer? %s", t, t % 1 == 0) +end +print() +for tests2 as t do + fmt.print(" %-9g is integer? %s", t, t % 1 == 0) +end +for tests3 as t do + fmt.print(" %-9.6f is integer? %s", t, t % 1 == 0) +end +print() +for tests4 as t do + fmt.print(" %-9s is integer? %s", t, t:getReal() % 1 == 0 and t:getImag() == 0) +end +print() +for tests5 as t do + fmt.print(" %-9s is integer? %s", t, t:isint()) +end +print("\nWithin a tolerance of 0.00001:\n") +local tol = 0.00001 +for tests6 as t do + local d = math.abs(t - math.round(t)) + fmt.print(" %9.6f is integer? %s", t, d <= tol) +end diff --git a/Task/Text-processing-2/DuckDB/text-processing-2-1.duckdb b/Task/Text-processing-2/DuckDB/text-processing-2-1.duckdb new file mode 100644 index 0000000000..eb5e3b404e --- /dev/null +++ b/Task/Text-processing-2/DuckDB/text-processing-2-1.duckdb @@ -0,0 +1,2 @@ +create or replace table t as +from read_csv_auto('readings.txt', header=false); diff --git a/Task/Text-processing-2/DuckDB/text-processing-2-2.duckdb b/Task/Text-processing-2/DuckDB/text-processing-2-2.duckdb new file mode 100644 index 0000000000..c61c6dc483 --- /dev/null +++ b/Task/Text-processing-2/DuckDB/text-processing-2-2.duckdb @@ -0,0 +1 @@ +alter table t rename column column00 to date; diff --git a/Task/Text-processing-2/DuckDB/text-processing-2-3.duckdb b/Task/Text-processing-2/DuckDB/text-processing-2-3.duckdb new file mode 100644 index 0000000000..c578499e6b --- /dev/null +++ b/Task/Text-processing-2/DuckDB/text-processing-2-3.duckdb @@ -0,0 +1,7 @@ +.mode list +.headers off +.once dynamic.tmp +select 'alter table t rename column ''column' || format('{:02d}', 2 * n) || ''' to ''flag' || format('{:02d}'';', n) from range(1,25) t(n); +.read dynamic.tmp +.mode duckdb +.headers on diff --git a/Task/Text-processing-2/DuckDB/text-processing-2-4.duckdb b/Task/Text-processing-2/DuckDB/text-processing-2-4.duckdb new file mode 100644 index 0000000000..00993c94ac --- /dev/null +++ b/Task/Text-processing-2/DuckDB/text-processing-2-4.duckdb @@ -0,0 +1,9 @@ +# The values in a struct as JSON values +create or replace function struct_values(s) as ( + with j as (select s::JSON as j) + SELECT list_transform( json_keys(j), k -> j[k]) from j +); + +# Number of nulls in an entire table: +select sum(length(list_filter(struct_values(t), x -> x = 'null'))) as "|null|" +from (select t from t); diff --git a/Task/Text-processing-2/DuckDB/text-processing-2-5.duckdb b/Task/Text-processing-2/DuckDB/text-processing-2-5.duckdb new file mode 100644 index 0000000000..53c30a7e9a --- /dev/null +++ b/Task/Text-processing-2/DuckDB/text-processing-2-5.duckdb @@ -0,0 +1,9 @@ +# j is a JSON object ; return a list of the keys for which the value is less than 1 +create or replace function report(j) as ( + list_filter(json_keys(j), k -> (j -> k) < 1 ) +); + +select count(*) from +from (select report(struct_pack(*COLUMNS('flag'))::JSON) as flags + from t + where flags = []); diff --git a/Task/Text-processing-2/DuckDB/text-processing-2-6.duckdb b/Task/Text-processing-2/DuckDB/text-processing-2-6.duckdb new file mode 100644 index 0000000000..2229dd4d81 --- /dev/null +++ b/Task/Text-processing-2/DuckDB/text-processing-2-6.duckdb @@ -0,0 +1,6 @@ +with allflags as ( + select array_agg(flags) as flags + from (select report(struct_pack(*COLUMNS('flag'))::JSON) as flags from t) + ) + select list_reduce( flags, (acc,x) -> list_intersect(acc,x) ) as "never worked" + from allflags; diff --git a/Task/The-Name-Game/R/the-name-game.r b/Task/The-Name-Game/R/the-name-game.r new file mode 100644 index 0000000000..5867fafbc6 --- /dev/null +++ b/Task/The-Name-Game/R/the-name-game.r @@ -0,0 +1,20 @@ +library(stringr) + +namegame <- function(name){ + name <- str_to_title(name) + bfm_flags <- c("b","f","m") + #Y is only considered a starting vowel if it is followed by a consonant + if(str_detect(name, "^[AEIOU]|^Y[^aeiou]")) name_trunc <- str_to_lower(name) + else name_trunc <- str_sub(name, start=2) + switch(str_sub(name, 1, 1), + "B"=eval(bfm_flags[1] <- ""), + "F"=eval(bfm_flags[2] <- ""), + "M"=eval(bfm_flags[3] <- "")) + str_glue("{name}, {name}, bo-{bfm_flags[1]}{name_trunc}", + "Banana-fana fo-{bfm_flags[2]}{name_trunc}", + "Fee-fi-mo-{bfm_flags[3]}{name_trunc}", + "{name}!", .sep="\n") +} + +test_names <- c("Gary", "Earl", "Billy", "Felix", "Mary", "Yancy", "Yvonne") +sapply(test_names, namegame) |> writeLines() diff --git a/Task/The-Twelve-Days-of-Christmas/AutoLISP/the-twelve-days-of-christmas.l b/Task/The-Twelve-Days-of-Christmas/AutoLISP/the-twelve-days-of-christmas.l new file mode 100644 index 0000000000..a2d1ec511b --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/AutoLISP/the-twelve-days-of-christmas.l @@ -0,0 +1,30 @@ +(defun c:TDOC ( / days gifts) + (setq days + '( + ("first" "A partridge in a pear tree.") + ("second" "Two turtle doves and") + ("third" "Three french hens") + ("fourth" "Four calling birds") + ("fifth" "Five golden rings") + ("sixth" "Six geese a-laying") + ("seventh" "Seven swans a-swimming") + ("eighth" "Eight maids a-milking") + ("ninth" "Nine ladies dancing") + ("tenth" "Ten lords a-leaping") + ("eleventh" "Eleven pipers piping") + ("twelfth" "Twelve drummers drumming") + ) + ) + (setq gifts "") + (foreach day days + (prompt + (strcat + "\n-----" + "\nOn the " (car day) " day of Christmas," + "\nMy true love gave to me:" + (setq gifts (strcat "\n" (cadr day) gifts)) + ) + ) + ) + (princ) +) diff --git a/Task/Thue-Morse/DuckDB/thue-morse-1.duckdb b/Task/Thue-Morse/DuckDB/thue-morse-1.duckdb new file mode 100644 index 0000000000..4a27bd020f --- /dev/null +++ b/Task/Thue-Morse/DuckDB/thue-morse-1.duckdb @@ -0,0 +1,16 @@ +create or replace function t(n) as ( + with recursive mx as (select (ceil(log(n) / log(2))) as mx), + cte as ( + select '0' as a, + 0 as ix + union all + select replace(replace(hex(a),'30','01'),'31','10') as a, + ix+1 as ix + from cte, mx + where ix < mx + ) + select last(a[n] order by ix) from cte +); + +## Example: +select t(1), t(2), t(3), t(4), t(5), t(100); diff --git a/Task/Thue-Morse/DuckDB/thue-morse-2.duckdb b/Task/Thue-Morse/DuckDB/thue-morse-2.duckdb new file mode 100644 index 0000000000..3ecc2f8c1f --- /dev/null +++ b/Task/Thue-Morse/DuckDB/thue-morse-2.duckdb @@ -0,0 +1,16 @@ +create or replace function TM(n) as ( +create or replace function TM(n) as ( + with recursive mx as (select (ceil(log(n) / log(2))) as mx), + cte as ( + select '0' as sb0, '1' as sb1, 0 as ix + union all + select (sb0 || sb1) as sb0, + (sb1 || sb0) as sb1, + ix+1, + from cte, mx + where ix < mx + ) + select last(sb0[:n] order by ix) from cte +); +## Example: +select TM(100); diff --git a/Task/Thue-Morse/Prolog/thue-morse.pro b/Task/Thue-Morse/Prolog/thue-morse.pro new file mode 100644 index 0000000000..5b342753fb --- /dev/null +++ b/Task/Thue-Morse/Prolog/thue-morse.pro @@ -0,0 +1,15 @@ +%! thue_morse(+N, -TM) is det. +% Calculates the Nth number of the Thue-Morse sequence, indexing from 0. +thue_morse(N, TM) :- TM is popcount(N) mod 2. + +%! thue_morse_list(-List) is multi. +% Calculates progressively longer prefixes of the Thue-Morse sequence. +thue_morse_list(List) :- thue_morse_list(0, List). + +thue_morse_list(N, [TM | List]) :- + thue_morse(N, TM), + ( List = [] + ; N1 is N + 1, thue_morse_list(N1, List) + ). + +:- length(List, 20), once(thue_morse_list(List)), write(List). diff --git a/Task/Tic-tac-toe/TAV/tic-tac-toe.tav b/Task/Tic-tac-toe/TAV/tic-tac-toe.tav new file mode 100644 index 0000000000..fa73c27b8d --- /dev/null +++ b/Task/Tic-tac-toe/TAV/tic-tac-toe.tav @@ -0,0 +1,133 @@ +\( Simple (not perfect) solver for tic-tac-toe + The state is a 9-element vector, with + 0 for free, 1 for user; 4 for machine + Lanes are used to check if there is a win or near-win: + 1 2 3 + 4 5 6 + 7 8 9 + 1 4 7 + 2 5 8 + 3 6 9 + 1 5 9 + 3 5 7 + For each lane, the sum of the values is calculated + and the number of free ones determined. + After the player's move and the machine action, + the lane sums are checked for wins: + - if = 3, the player has won, stop. + - if = 12, the machine has won, stop. + - if none are free, the game ends with a draw + The machine action is: + - if = 2, the player could win; set the free place + - if = 8, the machine will win, set the free place + - if field 5 is free, set + - if any of the fields 1, 3, 7 or 9 are free, set at random + - if any of the fields 2, 4, 6 or 8 are free, set at random +\) +main (parms):+ + random set seed () + print "enter field number, or 'x' to quit:" + state =: new row size 9 init 0 + state.lanes =: ((1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 4, 7), (2, 5, 8), (3, 6, 9), (1, 5, 9), (3, 5, 7)) + state.free =: 9 + ?* state.free > 0 + show state + set user state + show state + check end state + ? state.free > 0 + step move state + check end state + show state + +check end (state): + ?# t =: tuple state.lanes give values + c =: sum of places state lane t + \ print c, t + ? c = 3: + print "You win:", t + ?# i =: tuple t give values + state[i] =: '+' + state.free =: 0 + :> + ? c = 12: + print "I win:", t + ?# i =: tuple t give values + state[i] =: '*' + state.free =: 0 + :> + ? state.free = 0 + print "This is a draw." + +step move (state): + ?# t =: tuple state.lanes give values + c =: sum of places state lane t + ? c = 2 + set state at t + :> + ? c = 8 + set state at t + :> + ? set state at 5 + :> + ? set state at shuffle 1, 3, 7, 9 + :> + ? set state at shuffle 2, 4, 6, 8 + :> + +set (state) at (points): + ? ~ is points tuple + points =: points, () \ make it a tuple + ?# i =: tuple points give values + ? state[i] = 0 + state[i] =: 4 + print "my move:", i + :> ?+ + :> ?- + +shuffle (points): + n =: points.Count + r =: random tuple n + points =: tuple points select r + :> points + +sum of places (state) lane (tpl): + s =: 0 + ?# i =: tuple tpl give values + v =: state[i] + ? v ~= 0 + s =+ state[i] + :> s + +set user (state): + ?* + print "your move: " nonl + c =: file stream () get + ? c = 'q' || c = 'x' + system exit 0 + n =: string c as integer else () + ? n = () || n < 1 || n > state.Count + print "Invalid input, " nonl + ?^ + ? state[n] = 0 + state[n] =: 1 + :> + print "not free; retry " nonl + +show (state): + state.free =:0 + ?# i =: from 1 upto 9 + v =: state[i] + w =: v + ? v = 0 + w =: i + state.free =+ 1 + ? v = 1 + w =: 'X' + ? v = 4 + w =: 'O' + print ' ' _ w nonl + ? i = 3 || i = 6 + print '' + print '' + \ state.free=0 is used to terminate the central loop diff --git a/Task/Time-a-function/Agena/time-a-function.agena b/Task/Time-a-function/Agena/time-a-function.agena new file mode 100644 index 0000000000..19baf18a28 --- /dev/null +++ b/Task/Time-a-function/Agena/time-a-function.agena @@ -0,0 +1,14 @@ +scope # Time a function + + local procedure timeFunction( f :: procedure ) :: number + local startTime := os.clock(); + f(); + return os.clock() - startTime # execution time in milliseconds + end; + + local procedure toBeTimed() + os.wait( 1.234 ) # sleep 1.234 seconds + end + + print( timeFunction( toBeTimed ) / 1000, " seconds" ) +end diff --git a/Task/Time-a-function/DuckDB/time-a-function.duckdb b/Task/Time-a-function/DuckDB/time-a-function.duckdb new file mode 100644 index 0000000000..3bdea7649c --- /dev/null +++ b/Task/Time-a-function/DuckDB/time-a-function.duckdb @@ -0,0 +1,21 @@ +# A table +create or replace function countto(n) as ( + with recursive cte as ( + select 0 as ix + union all + select ix+1 + from cte + where ix < n) + select last(ix order by ix) + from cte +); + +.timer on +.print .timer is now on +.print 10^4 +select length(range(0, 10_000)); +select countto(10 ^ 4); + +.print 10^5 +select length(range(0, 100_000)); +select countto(10 ^ 5); diff --git a/Task/Time-a-function/Fennel/time-a-function.fennel b/Task/Time-a-function/Fennel/time-a-function.fennel new file mode 100644 index 0000000000..da00463f90 --- /dev/null +++ b/Task/Time-a-function/Fennel/time-a-function.fennel @@ -0,0 +1,22 @@ +(do ;;; Time a function + + (fn time-function [fn-to=be-timed] + (local start-time (os.clock)) + (fn-to=be-timed) + (- (os.clock) start-time) ;;; execution time in seconds + ) + + (fn delay [delta-t] + (local end-time (+ (os.clock) delta-t)) + (while (< (os.clock) end-time) + (var x 0) + (for [i 1 100_000] (set x (+ x 1))) + ) + ) + + (fn test-fn [] + (delay 1.234) ; sleep 1.234 seconds + ) + + (print (time-function test-fn " seconds")) +) diff --git a/Task/Time-a-function/Lua/time-a-function.lua b/Task/Time-a-function/Lua/time-a-function.lua index e7a108419b..40efbdd971 100644 --- a/Task/Time-a-function/Lua/time-a-function.lua +++ b/Task/Time-a-function/Lua/time-a-function.lua @@ -2,7 +2,7 @@ function bench(Function, ...) local t = os.time() local clock1 = os.clock() Function(...) - local c = os.clock()-clock + local c = os.clock()-clock1 return os.time()-t, c end diff --git a/Task/Time-a-function/Pluto/time-a-function.pluto b/Task/Time-a-function/Pluto/time-a-function.pluto new file mode 100644 index 0000000000..a9eecc53d1 --- /dev/null +++ b/Task/Time-a-function/Pluto/time-a-function.pluto @@ -0,0 +1,14 @@ +do -- Time a function + + local function timeFunction( f : function ) : number + local startTime = os.micros() + f() + return os.micros() - startTime + end + + local function toBeTimed() : void + os.sleep( 1234 ) -- sleep 1.234 seconds + end + + print( $"{ timeFunction( toBeTimed ) / 1_000_000 } seconds" ) +end diff --git a/Task/Time-a-function/REXX/time-a-function-2.rexx b/Task/Time-a-function/REXX/time-a-function-2.rexx index b8a590ac0f..b40b4fb45f 100644 --- a/Task/Time-a-function/REXX/time-a-function-2.rexx +++ b/Task/Time-a-function/REXX/time-a-function-2.rexx @@ -1,10 +1,17 @@ --- 22 Mar 2025 -arg count','prec +-- 7 Aug 2025 include Settings +arg count','prec +if count = '' then + count = 1e7 +if prec = '' then + prec = 9 +numeric digits prec say 'TIME A FUNCTION' say version say +say 'Part 1: REXX clauses' +say call Parameters call DoLoop call DoForLoop @@ -57,19 +64,23 @@ say call Stems say call Average +say +say 'Part 2: Profiler' +say +call Profiler 'ArcSin(X)',1/3 +call Profiler 'Exp(X)',1/4 +call Profiler 'Gamma(X)',1/5 +call Profiler 'Ln(X)',1/6 +call Profiler 'Pi()' +call Profiler 'Sin(X)',1/7 +call Profiler 'Sqrt(X)',1/8 +call Profiler 'X',1/9 +call Profiler 'X**5-5/x-1',1/10 +call Profiler 'Zeta(X)',1/11 return Parameters: start = date() time() -if count = '' then - count = 1e6 -if prec = '' then - prec = 9 -parse version version -say 'Version' version -say 'Using loop counter' count/1e6 'million and' Digits() 'digits' -say -numeric digits prec int1 = right(sqrt3(),prec%2); int2 = right(sqrt2(),prec%2) if int2 > int1 then parse value int2 int1 with int1 int2 @@ -478,6 +489,10 @@ else say Left(measure,20) 'cannot perform measure, please try a higher count' return -include Functions -include Constants -include Abend +Profiler: +arg ff,xx,yy,zz +rr=Profile(ff,xx,yy,zz) +say left(ff,10) 'takes' right(word(rr,2),4) 'microsec, x =' xx', f =' word(rr,1)/1 +return + +include Math diff --git a/Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon b/Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon new file mode 100644 index 0000000000..8744df9fc4 --- /dev/null +++ b/Task/Tokenize-a-string-with-escaping/Icon/tokenize-a-string-with-escaping.icon @@ -0,0 +1,21 @@ +procedure main() + str := "one^|uno||three^^^^|four^^^|^cuatro|" + every write("\"",!tokenize(str,"|","^"),"\"") +end + +procedure tokenize(str,sep,esc) + ret := [] + token := "" + cse := cset(sep||esc) + str ? + repeat{ + token ||:= tab(i := (upto(cse) | 0)) + if i = 0 then return put(ret,token) + move(1) + if str[i] == sep then{ + put(ret,token) + token := "" + }else + token ||:= move(1) + } +end diff --git a/Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb b/Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb new file mode 100644 index 0000000000..7d9391bc19 --- /dev/null +++ b/Task/Tokenize-a-string/DuckDB/tokenize-a-string.duckdb @@ -0,0 +1,4 @@ +create or replace function tokenize(s) as ( + regexp_split_to_array(s, ' *, *') +); +select tokenize('Hello,How,Are,You,Today') as tokens; diff --git a/Task/Tokenize-a-string/Refal/tokenize-a-string.refal b/Task/Tokenize-a-string/Refal/tokenize-a-string.refal new file mode 100644 index 0000000000..4dad638e7e --- /dev/null +++ b/Task/Tokenize-a-string/Refal/tokenize-a-string.refal @@ -0,0 +1,15 @@ +$ENTRY Go { + = >>; +}; + +Split { + (e.S) = ; + (e.S) e.1 e.S e.2 = (e.1) ; + (e.S) e.1 = (e.1); +}; + +Join { + (e.J) = ; + (e.J) (e.1) = e.1; + (e.J) (e.1) e.2 = e.1 e.J ; +}; diff --git a/Task/Tokenize-a-string/SETL/tokenize-a-string.setl b/Task/Tokenize-a-string/SETL/tokenize-a-string.setl new file mode 100644 index 0000000000..67670ca08c --- /dev/null +++ b/Task/Tokenize-a-string/SETL/tokenize-a-string.setl @@ -0,0 +1,18 @@ +program tokenize_a_string; + s := 'Hello,How,Are,You,Today'; + loop for part in tokenize(',', s) do + nprint(part + ". "); + end loop; + print; + + proc tokenize(sep, s); + loop + init parts := []; + doing parts with:= break(s, sep); + while s /= "" + do + s := s(2..); + end loop; + return parts; + end proc; +end program; diff --git a/Task/Tokenize-a-string/TAV/tokenize-a-string.tav b/Task/Tokenize-a-string/TAV/tokenize-a-string.tav new file mode 100644 index 0000000000..94127b9070 --- /dev/null +++ b/Task/Tokenize-a-string/TAV/tokenize-a-string.tav @@ -0,0 +1,8 @@ + \ clear explicit version + s =: "Hello,How,Are,You,Today" + r =: string s split by any of ',' \ single character split + print join r by '.' + \ all in one, no parenthesis required + print join string "Hello,How,Are,You,Today" split by any of ',' by '.' + \ parenthesis for clarity + print (join (string "Hello,How,Are,You,Today" split by any of ',') by '.') diff --git a/Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart b/Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart new file mode 100644 index 0000000000..c56c649e82 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Dart/tonelli-shanks-algorithm.dart @@ -0,0 +1,122 @@ +class Pair { + final int n; + final int p; + + Pair(this.n, this.p); +} + +class Solution { + final int root1; + final int root2; + final bool isSquare; + + Solution(this.root1, this.root2, this.isSquare); +} + +int multiplyModulus(int a, int b, int modulus) { + a %= modulus; + b %= modulus; + if (b < a) { + var temp = a; + a = b; + b = temp; + } + + int result = 0; + while (a > 0) { + if (a % 2 == 1) { + result = (result + b) % modulus; + } + b = (b << 1) % modulus; + a >>= 1; + } + return result; +} + +int powerModulus(int base, int exponent, int modulus) { + if (modulus == 1) return 0; + + base %= modulus; + int result = 1; + while (exponent > 0) { + if ((exponent & 1) == 1) { + result = multiplyModulus(result, base, modulus); + } + base = multiplyModulus(base, base, modulus); + exponent >>= 1; + } + return result; +} + +int legendre(int a, int p) { + return powerModulus(a, (p - 1) ~/ 2, p); +} + +Solution tonelliShanks(int n, int p) { + if (legendre(n, p) != 1) { + return Solution(0, 0, false); + } + + // Factor out powers of 2 from p - 1 + int q = p - 1; + int s = 0; + while (q % 2 == 0) { + q ~/= 2; + s += 1; + } + + if (s == 1) { + int result = powerModulus(n, (p + 1) ~/ 4, p); + return Solution(result, p - result, true); + } + + // Find a non-square z such that (z | p) = -1 + int z = 2; + while (legendre(z, p) != p - 1) { + z += 1; + } + + int c = powerModulus(z, q, p); + int t = powerModulus(n, q, p); + int m = s; + int result = powerModulus(n, (q + 1) ~/ 2, p); + + while (t != 1) { + int i = 1; + int zTemp = multiplyModulus(t, t, p); + while (zTemp != 1 && i < m - 1) { + i += 1; + zTemp = multiplyModulus(zTemp, zTemp, p); + } + + int b = powerModulus(c, 1 << (m - i - 1), p); + c = multiplyModulus(b, b, p); + t = multiplyModulus(t, c, p); + m = i; + result = multiplyModulus(result, b, p); + } + + return Solution(result, p - result, true); +} + +void main() { + final List tests = [ + Pair(10, 13), + Pair(56, 101), + Pair(1030, 1009), + Pair(1032, 1009), + Pair(44402, 100049), + Pair(665820697, 1000000009), + Pair(881398088036, 1000000000039), + ]; + + for (final test in tests) { + final solution = tonelliShanks(test.n, test.p); + print('n = ${test.n}, p = ${test.p}'); + if (solution.isSquare) { + print('has solutions: ${solution.root1} and ${solution.root2}\n'); + } else { + print('has no solutions because n is not a square modulo p\n'); + } + } +} diff --git a/Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math b/Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math new file mode 100644 index 0000000000..3166ffb7df --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Mathematica/tonelli-shanks-algorithm.math @@ -0,0 +1,67 @@ +(* Legendre symbol *) +LegendreSymbol[a_, p_] := PowerMod[a, (p - 1)/2, p] + +(* Tonelli-Shanks Algorithm *) +Tonelli[n_, p_] := Module[ + {q, s, z, c, r, t, m, t2, i, b}, + (* Check that n is a quadratic residue mod p *) + If[LegendreSymbol[n, p] =!= 1, + Message[Tonelli::notsquare, n, p]; Abort[]]; + + (* Step 1: Factor out powers of 2 from p - 1 *) + q = p - 1; + s = 0; + While[EvenQ[q], q = q/2; s++]; + + (* Special case when s == 1 *) + If[s == 1, + Return[PowerMod[n, (p + 1)/4, p]] + ]; + + (* Find a non-residue z *) + For[z = 2, z < p, z++, + If[LegendreSymbol[z, p] == p - 1, Break[]] + ]; + + (* Initialize variables *) + c = PowerMod[z, q, p]; + r = PowerMod[n, (q + 1)/2, p]; + t = PowerMod[n, q, p]; + m = s; + + (* Main loop *) + While[Mod[t - 1, p] =!= 0, + t2 = Mod[t^2, p]; + For[i = 1, i < m, i++, + If[Mod[t2 - 1, p] === 0, Break[]]; + t2 = Mod[t2^2, p]; + ]; + b = PowerMod[c, 2^(m - i - 1), p]; + r = Mod[r*b, p]; + c = Mod[b^2, p]; + t = Mod[t*c, p]; + m = i; + ]; + r +] + +(* Test cases *) +ttest = { + {10, 13}, + {56, 101}, + {1030, 10009}, + {44402, 100049}, + {665820697, 1000000009}, + {881398088036, 1000000000039}, + {41660815127637347468140745042827704103445750172002, 10^50 + 577} +}; + +Do[ + n = ttest[[i, 1]]; + p = ttest[[i, 2]]; + r = Tonelli[n, p]; + Assert[Mod[r^2 - n, p] == 0]; + Print["n = ", n, ", p = ", p]; + Print["\troots : ", r, " ", p - r], + {i, Length[ttest]} +] diff --git a/Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp b/Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp new file mode 100644 index 0000000000..6408b9f0b7 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/PARI-GP/tonelli-shanks-algorithm.parigp @@ -0,0 +1,123 @@ +/* Legendre symbol */ +legendresymbol(a, p) = +{ + lift(Mod(a, p)^((p-1)/2)); +} + +/* Tonelli-Shanks Algorithm */ +tonelli(n, p) = +{ + local(q, s, z, c, r, t, m, t2, i, b); + + /* Check that n is a quadratic residue mod p */ + if(legendresymbol(n, p) != 1, + error("n is not a quadratic residue mod p")); + + /* Step 1: Factor out powers of 2 from p - 1 */ + q = p - 1; + s = 0; + while(q % 2 == 0, + q = q/2; + s++ + ); + + /* Special case when s == 1 */ + if(s == 1, + return(lift(Mod(n, p)^((p+1)/4))) + ); + + /* Find a non-residue z */ + z = 2; + while(z < p, + if(legendresymbol(z, p) == p - 1, break()); + z++ + ); + + /* Initialize variables */ + c = lift(Mod(z, p)^q); + r = lift(Mod(n, p)^((q+1)/2)); + t = lift(Mod(n, p)^q); + m = s; + + /* Main loop */ + while((t - 1) % p != 0, + t2 = t^2 % p; + i = 1; + while(i < m, + if((t2 - 1) % p == 0, break()); + t2 = t2^2 % p; + i++ + ); + b = lift(Mod(c, p)^(2^(m - i - 1))); + r = (r * b) % p; + c = b^2 % p; + t = (t * c) % p; + m = i + ); + + return(r); +} + +/* Test the functions */ +print("Testing Tonelli-Shanks algorithm:"); +print(); + +/* Test case 1 */ +n = 10; p = 13; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + +/* Test case 2 */ +n = 56; p = 101; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + +/* Test case 3 */ +n = 1030; p = 10009; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 4 */ +n = 44402; p = 100049; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 5 */ +n = 665820697; p = 1000000009; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 6 */ +n = 881398088036; p = 1000000000039; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); + + +/* Test case 7 */ +n = 41660815127637347468140745042827704103445750172002; p = 100000000000000000000000000000000000000000000000577; +r = tonelli(n, p); +print("n = ", n, ", p = ", p); +print("roots: ", r, ", ", p - r); +print("verification: ", r, "^2 mod ", p, " = ", r^2 % p); +print(); diff --git a/Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r b/Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r new file mode 100644 index 0000000000..e8346a4564 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/R/tonelli-shanks-algorithm.r @@ -0,0 +1,98 @@ +library(gmp) # For handling large integers and modular arithmetic + +# Legendre symbol: a^((p-1)/2) mod p +legendre <- function(a, p) { + a <- as.bigz(a) + p <- as.bigz(p) + e <- div.bigz(sub.bigz(p, 1), 2) + result <- powm(a, e, p) + return(result) +} + +# Tonelli-Shanks algorithm to find square root of n mod p +tonelli <- function(n, p) { + n <- as.bigz(n) + p <- as.bigz(p) + + # Check that n is a quadratic residue + leg <- legendre(n, p) + if (!identical(as.character(leg), "1")) { + stop("not a square (mod p)") + } + + q <- sub.bigz(p, 1) + s <- 0 + while (mod.bigz(q, 2) == 0) { + q <- div.bigz(q, 2) + s <- s + 1 + } + + if (s == 1) { + e <- div.bigz(add.bigz(p, 1), 4) + return(powm(n, e, p)) + } + + z <- as.bigz(2) + p_minus_1 <- sub.bigz(p, 1) + while (z < p) { + if (identical(as.character(legendre(z, p)), as.character(p_minus_1))) { + break + } + z <- add.bigz(z, 1) + } + + c <- powm(z, q, p) + r <- powm(n, div.bigz(add.bigz(q, 1), 2), p) + t <- powm(n, q, p) + m <- s + + one <- as.bigz(1) + two <- as.bigz(2) + + while (!identical(mod.bigz(sub.bigz(t, one), p), as.bigz(0))) { + t2 <- mod.bigz(mul.bigz(t, t), p) + i <- 1 + while (i < m) { + if (identical(mod.bigz(sub.bigz(t2, one), p), as.bigz(0))) { + break + } + t2 <- mod.bigz(mul.bigz(t2, t2), p) + i <- i + 1 + } + + b_exp <- pow.bigz(two, m - i - 1) + b <- powm(c, b_exp, p) + r <- mod.bigz(mul.bigz(r, b), p) + c <- mod.bigz(mul.bigz(b, b), p) + t <- mod.bigz(mul.bigz(t, c), p) + m <- i + } + + return(r) +} + +# Test cases +ttest <- list( + c("10", "13"), + c("56", "101"), + c("1030", "10009"), + c("44402", "100049"), + c("665820697", "1000000009"), + c("881398088036", "1000000000039"), + c("41660815127637347468140745042827704103445750172002", "100000000000000000000000000000000000000000000000577") +) + +for (case in ttest) { + n <- as.bigz(case[1]) + p <- as.bigz(case[2]) + r <- tonelli(n, p) + check <- mod.bigz(sub.bigz(mul.bigz(r, r), n), p) + + # Verify the result + if (!identical(as.character(check), "0")) { + stop("Verification failed") + } + + cat("n =", as.character(n), "p =", as.character(p), "\n") + cat("\troots :", as.character(r), as.character(sub.bigz(p, r)), "\n") +} diff --git a/Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala b/Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala new file mode 100644 index 0000000000..0d3550f865 --- /dev/null +++ b/Task/Tonelli-Shanks-algorithm/Scala/tonelli-shanks-algorithm.scala @@ -0,0 +1,106 @@ +import java.math.BigInteger +import scala.collection.immutable.List +import scala.annotation.tailrec + +object TonelliShanks { + private val ZERO = BigInteger.ZERO + private val ONE = BigInteger.ONE + private val TEN = BigInteger.TEN + private val TWO = BigInteger.valueOf(2) + private val FOUR = BigInteger.valueOf(4) + + private case class Solution(root1: BigInteger, root2: BigInteger, exists: Boolean) + + private def ts(n: Long, p: Long): Solution = ts(BigInteger.valueOf(n), BigInteger.valueOf(p)) + + private def ts(n: BigInteger, p: BigInteger): Solution = { + val powModP: (BigInteger, BigInteger) => BigInteger = (a, e) => a.modPow(e, p) + val ls: BigInteger => BigInteger = a => powModP(a, p.subtract(ONE).divide(TWO)) + + if (!ls(n).equals(ONE)) return Solution(ZERO, ZERO, false) + + var q = p.subtract(ONE) + var ss = ZERO + while (q.and(ONE).equals(ZERO)) { + ss = ss.add(ONE) + q = q.shiftRight(1) + } + + if (ss.equals(ONE)) { + val r1 = powModP(n, p.add(ONE).divide(FOUR)) + return Solution(r1, p.subtract(r1), true) + } + + var z = TWO + while (!ls(z).equals(p.subtract(ONE))) z = z.add(ONE) + var c = powModP(z, q) + var r = powModP(n, q.add(ONE).divide(TWO)) + var t = powModP(n, q) + var m = ss + + // Convert the while(true) loop to a tail-recursive function + @tailrec + def loop(r: BigInteger, c: BigInteger, t: BigInteger, m: BigInteger): Solution = { + if (t.equals(ONE)) { + Solution(r, p.subtract(r), true) + } else { + var i = ZERO + var zz = t + while (!zz.equals(BigInteger.ONE) && i.compareTo(m.subtract(ONE)) < 0) { + zz = zz.multiply(zz).mod(p) + i = i.add(ONE) + } + var b = c + var e = m.subtract(i).subtract(ONE) + while (e.compareTo(ZERO) > 0) { + b = b.multiply(b).mod(p) + e = e.subtract(ONE) + } + val newR = r.multiply(b).mod(p) + val newC = b.multiply(b).mod(p) + val newT = t.multiply(newC).mod(p) + val newM = i + loop(newR, newC, newT, newM) + } + } + + loop(r, c, t, m) + } + + def main(args: Array[String]): Unit = { + val pairs = List( + (10L, 13L), + (56L, 101L), + (1030L, 10009L), + (1032L, 10009L), + (44402L, 100049L), + (665820697L, 1000000009L), + (881398088036L, 1000000000039L) + ) + + for ((n, p) <- pairs) { + val sol = ts(n, p) + println(s"n = $n") + println(s"p = $p") + if (sol.exists) { + println(s"root1 = ${sol.root1}") + println(s"root2 = ${sol.root2}") + } else { + println("No solution exists") + } + println() + } + + val bn = new BigInteger("41660815127637347468140745042827704103445750172002") + val bp = TEN.pow(50).add(BigInteger.valueOf(577)) + val sol = ts(bn, bp) + println(s"n = $bn") + println(s"p = $bp") + if (sol.exists) { + println(s"root1 = ${sol.root1}") + println(s"root2 = ${sol.root2}") + } else { + println("No solution exists") + } + } +} diff --git a/Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb new file mode 100644 index 0000000000..74de517b71 --- /dev/null +++ b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-1.duckdb @@ -0,0 +1,14 @@ +create or replace table EMP as + from read_csv_auto('input.csv'); + +create or replace function rank_by_department(number) as table ( + with cte as ( + SELECT *, row_number() OVER (PARTITION BY Department ORDER BY salary desc) as rank + FROM EMP + ) + select * from cte + where rank <= number + order by Department, Salary DESC +); + +from rank_by_department(3); diff --git a/Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb new file mode 100644 index 0000000000..bf547de47d --- /dev/null +++ b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-2.duckdb @@ -0,0 +1,6 @@ +create or replace table EMP ( + EMP_ID varchar(6), + EMP_NAME varchar(20), + DEPT_ID varchar(4), + SALARY decimal(10,2) +); diff --git a/Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb new file mode 100644 index 0000000000..949b90bfca --- /dev/null +++ b/Task/Top-rank-per-group/DuckDB/top-rank-per-group-3.duckdb @@ -0,0 +1,3 @@ +create or replace function to_char(s,f) as ( + format('{:9.2f}', s) +); diff --git a/Task/Topic-variable/Maxima/topic-variable.maxima b/Task/Topic-variable/Maxima/topic-variable.maxima new file mode 100644 index 0000000000..74c018bb72 --- /dev/null +++ b/Task/Topic-variable/Maxima/topic-variable.maxima @@ -0,0 +1,9 @@ +3; /* % won't work if $ is used instead of ; */ +[%^2, sqrt(%)]; + +3$ /* _ works with $ or ; */ +[_^2, sqrt(_)]; + +block(x: 3, [%%^2, sqrt(%%)]); + +__+3; /* __ only evaluates itself once to avoid infinite loops */ diff --git a/Task/Topswops/Prolog/topswops.pro b/Task/Topswops/Prolog/topswops.pro new file mode 100644 index 0000000000..376a72028d --- /dev/null +++ b/Task/Topswops/Prolog/topswops.pro @@ -0,0 +1,23 @@ +topswops(N, MaximumSwaps) :- + numlist(1, N, Cards), + aggregate_all(max(Swaps), ( + permutation(Cards, Shuffled), + topswops_(Shuffled, 0, Swaps) + ), MaximumSwaps). + +topswops_([Card | Cards0], Swaps0, Swaps) :- + ( Card = 1 + -> Swaps0 = Swaps + ; succ(Swaps0, Swaps1), + length(Prefix, Card), + append(Prefix, Suffix, [Card | Cards0]), + reverse(Prefix, Reversed), + append(Reversed, Suffix, Cards), + topswops_(Cards, Swaps1, Swaps) + ). + +main :- + foreach( + ( between(1, 10, N), topswops(N, MaximumSwaps) ), + format("~w: ~w~n", [N, MaximumSwaps]) + ). diff --git a/Task/Total-circles-area/00-TASK.txt b/Task/Total-circles-area/00-TASK.txt index e81c603abd..d4e3553bd2 100644 --- a/Task/Total-circles-area/00-TASK.txt +++ b/Task/Total-circles-area/00-TASK.txt @@ -1,3 +1,4 @@ +https://rosettacode.org/wiki/Total_circles_area?action=edit Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. One point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome. diff --git a/Task/Total-circles-area/Ada/total-circles-area.ada b/Task/Total-circles-area/Ada/total-circles-area.ada new file mode 100644 index 0000000000..22175d5daf --- /dev/null +++ b/Task/Total-circles-area/Ada/total-circles-area.ada @@ -0,0 +1,109 @@ +with Ada.Text_IO; + +procedure Circles_Area is + type Point is record + X, Y : Float; + end record; + + type Circle is record + P : Point; + R : Float; + end record; + + type Box is record + P1, P2 : Point; + end record; + + type Circle_Array is array (1 .. 25) of Circle; + + Circles : constant Circle_Array := + ( + ((1.6417233788, 1.6121789534), 0.0848270516), + ((-1.4944608174, 1.2077959613), 1.1039549836), + ((0.6110294452, -0.6907087527), 0.9089162485), + ((0.3844862411, 0.2923344616), 0.2375743054), + ((-0.2495892950, -0.3832854473), 1.0845181219), + ((1.7813504266, 1.6178237031), 0.8162655711), + ((-0.1985249206, -0.8343333301), 0.0538864941), + ((-1.7011985145, -0.1263820964), 0.4776976918), + ((-0.4319462812, 1.4104420482), 0.7886291537), + ((0.2178372997, -0.9499557344), 0.0357871187), + ((-0.6294854565, -1.3078893852), 0.7653357688), + ((1.7952608455, 0.6281269104), 0.2727652452), + ((1.4168575317, 1.0683357171), 1.1016025378), + ((1.4637371396, 0.9463877418), 1.1846214562), + ((-0.5263668798, 1.7315156631), 1.4428514068), + ((-1.2197352481, 0.9144146579), 1.0727263474), + ((-0.1389358881, 0.1092805780), 0.7350208828), + ((1.5293954595, 0.0030278255), 1.2472867347), + ((-0.5258728625, 1.3782633069), 1.3495508831), + ((-0.1403562064, 0.2437382535), 1.3804956588), + ((0.8055826339, -0.0482092025), 0.3327165165), + ((-0.6311979224, 0.7184578971), 0.2491045282), + ((1.4685857879, -0.8347049536), 1.3670667538), + ((-0.6855727502, 1.6465021616), 1.0593087096), + ((0.0152957411, 0.0638919221), 0.9771215985) + ); + + function Bounding_Box return Box is + C : Circle := Circles (1); + Left : Float := C.P.X - C.R; + Right : Float := C.P.X + C.R; + Down : Float := C.P.Y - C.R; + Up : Float := C.P.Y + C.R; + begin + for I in Circles'Range loop + C := Circles (I); + Left := Float'Min (Left, C.P.X - C.R); + Right := Float'Max (Right, C.P.X + C.R); + Down := Float'Min (Down, C.P.Y - C.R); + Up := Float'Max (Up, C.P.Y + C.R); + end loop; + + return ((Left, Down), (Right, Up)); + end Bounding_Box; + + function Distance2 (P1, P2 : Point) return Float is + ((P2.X - P1.X) ** 2 + (P2.Y - P1.Y) ** 2); + + function Is_Inside (P : Point) return Boolean is + C : Circle; + begin + for I in Circles'Range loop + C := Circles (I); + if Distance2 (C.P, P) < C.R ** 2 then + return True; + end if; + end loop; + + return False; + end Is_Inside; + + -- Use grid sampling + function Area return Float is + Bounds : constant Box := Bounding_Box; + X_Span : constant Float := (Bounds.P2.X - Bounds.P1.X); + Y_Span : constant Float := (Bounds.P2.Y - Bounds.P1.Y); + Grid_Area : constant Float := X_Span * Y_Span; + Steps : constant Integer := 1000; + Points_In, Points_Out : Integer := 0; + P : Point; + begin + for I in 1 .. Steps loop + for J in 1 .. Steps loop + P.X := Bounds.P1.X + X_Span * Float (I) / Float (Steps); + P.Y := Bounds.P1.Y + Y_Span * Float (J) / Float (Steps); + if Is_Inside (P) then + Points_In := Points_In + 1; + else + Points_Out := Points_Out + 1; + end if; + end loop; + end loop; + + return Grid_Area * Float (Points_In) / Float (Points_In + Points_Out); + end Area; + +begin + Ada.Text_IO.Put ("Circles area is " & Area'Image); +end Circles_Area; diff --git a/Task/Total-circles-area/Pluto/total-circles-area-1.pluto b/Task/Total-circles-area/Pluto/total-circles-area-1.pluto new file mode 100644 index 0000000000..64c5a83a07 --- /dev/null +++ b/Task/Total-circles-area/Pluto/total-circles-area-1.pluto @@ -0,0 +1,51 @@ +local class circle + function __construct(public x, public y, public r) end +end + +local circles = { + new circle( 1.6417233788, 1.6121789534, 0.0848270516), + new circle(-1.4944608174, 1.2077959613, 1.1039549836), + new circle( 0.6110294452, -0.6907087527, 0.9089162485), + new circle( 0.3844862411, 0.2923344616, 0.2375743054), + new circle(-0.2495892950, -0.3832854473, 1.0845181219), + new circle( 1.7813504266, 1.6178237031, 0.8162655711), + new circle(-0.1985249206, -0.8343333301, 0.0538864941), + new circle(-1.7011985145, -0.1263820964, 0.4776976918), + new circle(-0.4319462812, 1.4104420482, 0.7886291537), + new circle( 0.2178372997, -0.9499557344, 0.0357871187), + new circle(-0.6294854565, -1.3078893852, 0.7653357688), + new circle( 1.7952608455, 0.6281269104, 0.2727652452), + new circle( 1.4168575317, 1.0683357171, 1.1016025378), + new circle( 1.4637371396, 0.9463877418, 1.1846214562), + new circle(-0.5263668798, 1.7315156631, 1.4428514068), + new circle(-1.2197352481, 0.9144146579, 1.0727263474), + new circle(-0.1389358881, 0.1092805780, 0.7350208828), + new circle( 1.5293954595, 0.0030278255, 1.2472867347), + new circle(-0.5258728625, 1.3782633069, 1.3495508831), + new circle(-0.1403562064, 0.2437382535, 1.3804956588), + new circle( 0.8055826339, -0.0482092025, 0.3327165165), + new circle(-0.6311979224, 0.7184578971, 0.2491045282), + new circle( 1.4685857879, -0.8347049536, 1.3670667538), + new circle(-0.6855727502, 1.6465021616, 1.0593087096), + new circle( 0.0152957411, 0.0638919221, 0.9771215985) +} + +local sq = |v| -> v * v + +local xmin = circles:mapped(|c| -> c.x - c.r):min() +local xmax = circles:mapped(|c| -> c.x + c.r):max() +local ymin = circles:mapped(|c| -> c.y - c.r):min() +local ymax = circles:mapped(|c| -> c.y + c.r):max() +local boxside = 3000 +local dx = (xmax - xmin) / boxside +local dy = (ymax - ymin) / boxside +local count = 0 +for r = 0, boxside - 1 do + local y = ymin + r * dy + for c = 0, boxside - 1 do + local x = xmin + c * dx + local b = circles:find(|cc| -> sq(x - cc.x) + sq(y - cc.y) <= sq(cc.r)) + if b then ++count end + end +end +print($"Approximate area = {count * dx * dy}") diff --git a/Task/Total-circles-area/Pluto/total-circles-area-2.pluto b/Task/Total-circles-area/Pluto/total-circles-area-2.pluto new file mode 100644 index 0000000000..73db8d290f --- /dev/null +++ b/Task/Total-circles-area/Pluto/total-circles-area-2.pluto @@ -0,0 +1,72 @@ +local class point + function __construct(public x, public y) end +end + +local class circle + function __construct(public x, public y, public r) end +end + +local circles = { + new circle( 1.6417233788, 1.6121789534, 0.0848270516), + new circle(-1.4944608174, 1.2077959613, 1.1039549836), + new circle( 0.6110294452, -0.6907087527, 0.9089162485), + new circle( 0.3844862411, 0.2923344616, 0.2375743054), + new circle(-0.2495892950, -0.3832854473, 1.0845181219), + new circle( 1.7813504266, 1.6178237031, 0.8162655711), + new circle(-0.1985249206, -0.8343333301, 0.0538864941), + new circle(-1.7011985145, -0.1263820964, 0.4776976918), + new circle(-0.4319462812, 1.4104420482, 0.7886291537), + new circle( 0.2178372997, -0.9499557344, 0.0357871187), + new circle(-0.6294854565, -1.3078893852, 0.7653357688), + new circle( 1.7952608455, 0.6281269104, 0.2727652452), + new circle( 1.4168575317, 1.0683357171, 1.1016025378), + new circle( 1.4637371396, 0.9463877418, 1.1846214562), + new circle(-0.5263668798, 1.7315156631, 1.4428514068), + new circle(-1.2197352481, 0.9144146579, 1.0727263474), + new circle(-0.1389358881, 0.1092805780, 0.7350208828), + new circle( 1.5293954595, 0.0030278255, 1.2472867347), + new circle(-0.5258728625, 1.3782633069, 1.3495508831), + new circle(-0.1403562064, 0.2437382535, 1.3804956588), + new circle( 0.8055826339, -0.0482092025, 0.3327165165), + new circle(-0.6311979224, 0.7184578971, 0.2491045282), + new circle( 1.4685857879, -0.8347049536, 1.3670667538), + new circle(-0.6855727502, 1.6465021616, 1.0593087096), + new circle( 0.0152957411, 0.0638919221, 0.9771215985) +} + +local sq = |v| -> v * v + +local function area_scan(precision) + + local function sect(c, y) + local dr = math.sqrt(sq(c.r) - sq(y - c.y)) + return new point(c.x - dr, c.x + dr) + end + + local cm1 = circles:mapped(|c| -> c.y + c.r) + local cm2 = circles:mapped(|c| -> c.y - c.r) + local ys = {} + table.move(cm1, 1, #cm1, 1, ys) + table.move(cm2, 1, #cm2, #ys + 1, ys) + local mins = math.floor(ys:min() / precision) + local maxs = math.ceil (ys:max() / precision) + local total = 0 + for x = mins, maxs do + local y = x * precision + local right = -1 / 0 + local points = circles:filtered(|c| -> math.abs(y - c.y) < c.r) + :reorder() + :map(|c| -> sect(c, y)) + :sort(|p1, p2| -> p1.x < p2.x) + for points as p do + if p.y > right then + total += p.y - math.max(p.x, right) + right = p.y + end + end + end + return total * precision +end + +local p = 1e-5 +print($"Approximate area = {area_scan(p)}") diff --git a/Task/Totient-function/Agena/totient-function.agena b/Task/Totient-function/Agena/totient-function.agena new file mode 100644 index 0000000000..2b54086ff8 --- /dev/null +++ b/Task/Totient-function/Agena/totient-function.agena @@ -0,0 +1,46 @@ +scope # Totient function + + # returns the number of integers k where 1 <= k <= n that are mutually prime to n + local procedure totient( n :: number ) :: number + if n < 3 then result := 1 + elif n = 3 then result := 2 + else + result := n; + local v, i := n, 2; + while i * i <= v do + if v mod i = 0 then + while v mod i = 0 do v \:= i od; + result -:= result \ i + fi; + if i = 2 then + i := 1 + fi; + i +:= 2 + od; + if v > 1 then result -:= result \ v fi; + fi; + return result + end; + + # show the totient function values for the first 25 integers + io.write( " n phi(n) remarks\n" ); + for n to 25 do + local constant tn := totient( n ); + printf( "%2d: %5d%s\n", n, tn, if tn = n - 1 and tn <> 0 then " n is prime" else "" fi ) + od; + + # use the totient function to count primes + local n100, n1_000, n10_000, n100_000 := 0, 0, 0, 0; + for n to 100_000 do + if totient( n ) = n - 1 then + if n <= 100 then n100 +:= 1 fi; + if n <= 1000 then n1_000 +:= 1 fi; + if n <= 10000 then n10_000 +:= 1 fi; + if n <= 100000 then n100_000 +:= 1 fi + fi + od; + printf( "There are %6d primes below 100\n", n100 ); + printf( "There are %6d primes below 1 000\n", n1_000 ); + printf( "There are %6d primes below 10 000\n", n10_000 ); + printf( "There are %6d primes below 100 000\n", n100_000 ) +end diff --git a/Task/Totient-function/Fortran/totient-function.f b/Task/Totient-function/Fortran/totient-function.f new file mode 100644 index 0000000000..9957fa9c34 --- /dev/null +++ b/Task/Totient-function/Fortran/totient-function.f @@ -0,0 +1,54 @@ +program totient_function + implicit none + integer, parameter :: M = 100000 + integer :: i, j + integer, dimension(1:M) :: phi + character(len=10) :: is_prime + integer :: count100, count1000, count10000, count100000 + + ! Initialize phi array + do i = 1, M + phi(i) = i + end do + + ! Compute totient using sieve method + do i = 2, M + if (phi(i) == i) then ! i is prime + do j = i, M, i + phi(j) = (phi(j) / i) * (i - 1) + end do + end if + end do + + ! Display for the first 25 integers + print*,'n phi prime' + print*,repeat('-',30) + do i = 1, 25 + if (phi(i) == i - 1) then + is_prime = 'prime' + else + is_prime = 'not prime' + end if + print "(i0,t10,i3,t20,a)", i, phi(i), trim(is_prime) + end do + + ! Count primes up to specified limits + count100 = 0 + count1000 = 0 + count10000 = 0 + count100000 = 0 + do i = 2, M + if (phi(i) == i - 1) then + if (i <= 100) count100 = count100 + 1 + if (i <= 1000) count1000 = count1000 + 1 + if (i <= 10000) count10000 = count10000 + 1 + count100000 = count100000 + 1 + end if + end do + + print *, 'Count of primes up to 100:', count100 + print *, 'Count of primes up to 1,000:', count1000 + print *, 'Count of primes up to 10,000:', count10000 + print *, 'Count of primes up to 100,000:', count100000 + +end program totient_function diff --git a/Task/Totient-function/Lua/totient-function-2.lua b/Task/Totient-function/Lua/totient-function-2.lua index c8689c4256..ec4e85b99f 100644 --- a/Task/Totient-function/Lua/totient-function-2.lua +++ b/Task/Totient-function/Lua/totient-function-2.lua @@ -22,23 +22,20 @@ do io.write( " n phi(n) remarks\n" ) for n = 1,25 do local tn = totient( n ) - io.write( string.format( "%2d", n ), ": ", string.format( "%5d", tn ) - , ( tn == n - 1 and tn ~= 0 and " n is prime" or "" ) - , "\n" - ) + io.write( string.format( "%2d: %5d%s\n", n, tn, ( tn == n - 1 and tn ~= 0 and " n is prime" or "" ) ) ) end -- use the totient function to count primes - local n100, n1000, n10000, n100000 = 0, 0, 0, 0 + local n100, n1_000, n10_000, n100_000 = 0, 0, 0, 0 for n = 1,100000 do if totient( n ) == n - 1 then - if n <= 100 then n100 = n100 + 1 end - if n <= 1000 then n1000 = n1000 + 1 end - if n <= 10000 then n10000 = n10000 + 1 end - if n <= 100000 then n100000 = n100000 + 1 end + if n <= 100 then n100 = n100 + 1 end + if n <= 1000 then n1_000 = n1_000 + 1 end + if n <= 10000 then n10_000 = n10_000 + 1 end + if n <= 100000 then n100_000 = n100_000 + 1 end end end - io.write( "There are ", string.format( "%6d", n100 ), " primes below 100\n" ) - io.write( "There are ", string.format( "%6d", n1000 ), " primes below 1 000\n" ) - io.write( "There are ", string.format( "%6d", n10000 ), " primes below 10 000\n" ) - io.write( "There are ", string.format( "%6d", n100000 ), " primes below 100 000\n" ) + io.write( string.format( "There are %6d primes below 100\n", n100 ) ) + io.write( string.format( "There are %6d primes below 1 000\n", n1_000 ) ) + io.write( string.format( "There are %6d primes below 10 000\n", n10_000 ) ) + io.write( string.format( "There are %6d primes below 100 000\n", n100_000 ) ) end diff --git a/Task/Totient-function/Pluto/totient-function.pluto b/Task/Totient-function/Pluto/totient-function.pluto new file mode 100644 index 0000000000..115229b457 --- /dev/null +++ b/Task/Totient-function/Pluto/totient-function.pluto @@ -0,0 +1,33 @@ +local function totient(n) + local tot = n + local i = 2 + while i * i <= n do + if n % i == 0 then + while n % i == 0 do n //= i end + tot -= tot // i + end + if i == 2 then i = 1 end + i += 2 + end + if n > 1 do tot -= tot // n end + return tot +end + +print(" n phi prime") +print("---------------") +local count = 0 +for n = 1, 25 do + local tot = totient(n) + local isPrime = (n - 1) == tot + if isPrime then ++count end + print(string.format("%2d %2d %s", n, tot, isPrime)) +end +print("\nNumber of primes up to 25 = " .. count) +for n = 26, 100_000 do + local tot = totient(n) + if tot == n - 1 then ++count end + if n == 100 or n == 1_000 or n % 10_000 == 0 then + local ns = string.format("%-6d", n) + print($"\nNumber of primes up to {ns} = {count}") + end +end diff --git a/Task/Towers-of-Hanoi/Maxima/towers-of-hanoi.maxima b/Task/Towers-of-Hanoi/Maxima/towers-of-hanoi.maxima new file mode 100644 index 0000000000..2c717a61ef --- /dev/null +++ b/Task/Towers-of-Hanoi/Maxima/towers-of-hanoi.maxima @@ -0,0 +1,8 @@ +hanoi(n, a, b, c) := block( +if(n=1) then print(sconcat("peg ", a, " to peg ", b)) +else block( + hanoi(n-1, a, c, b), + hanoi(1, a, b, c), + hanoi(n-1, c, b, a)))$ + +hanoi(4,1,2,3)$ diff --git a/Task/Towers-of-Hanoi/Pluto/towers-of-hanoi.pluto b/Task/Towers-of-Hanoi/Pluto/towers-of-hanoi.pluto new file mode 100644 index 0000000000..c84d6ebe88 --- /dev/null +++ b/Task/Towers-of-Hanoi/Pluto/towers-of-hanoi.pluto @@ -0,0 +1,20 @@ +class Hanoi + function __construct(disks) + self.moves = 0 + print($"Towers of Hanoi with {disks} disks:\n") + self:move(disks, "L", "C", "R") + print($"\nCompleted in {self.moves} moves\n") + end + + function move(n, from, to, via) + if n > 0 then + self:move(n - 1, from, via, to) + ++self.moves + print($"Move disk {n} from {from} to {to}") + self:move(n - 1, via, to, from) + end + end +end + +new Hanoi(3) +new Hanoi(4) diff --git a/Task/Towers-of-Hanoi/Red/towers-of-hanoi.red b/Task/Towers-of-Hanoi/Red/towers-of-hanoi.red new file mode 100644 index 0000000000..d5bf88399c --- /dev/null +++ b/Task/Towers-of-Hanoi/Red/towers-of-hanoi.red @@ -0,0 +1,9 @@ +Red [ "Towers of Hanoi - Hinjo, 20 July 2025" ] +hanoi: function [n src tgt aux] [ + if n > 0 [ + hanoi n - 1 src aux tgt + print ["Move from " src " to " tgt] + hanoi n - 1 aux tgt src + ] +] +hanoi 5 "A" "C" "B" diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Pluto/trabb-pardo-knuth-algorithm.pluto b/Task/Trabb-Pardo-Knuth-algorithm/Pluto/trabb-pardo-knuth-algorithm.pluto new file mode 100644 index 0000000000..c42e7b1e6d --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Pluto/trabb-pardo-knuth-algorithm.pluto @@ -0,0 +1,22 @@ +require "io2" +local fmt = require "fmt" + +local f = |x| -> math.sqrt(math.abs(x)) + 5 * x * x * x + +local s = {} +print("Please enter 11 numbers:") +local count = 0 +repeat + s[++count] = io.readNum(string.format(" Number %-2d : ", count)) +until count == 11 + +s:reverse() +print("\nResults:") +for s as item do + local fi = f(item) + if fi <= 400 then + fmt.print(" f(%6.3f) = %7.3f", item, fi) + else + fmt.print(" f(%6.3f) = overflow", item) + end +end diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Prolog/trabb-pardo-knuth-algorithm.pro b/Task/Trabb-Pardo-Knuth-algorithm/Prolog/trabb-pardo-knuth-algorithm.pro new file mode 100644 index 0000000000..c493139f2b --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Prolog/trabb-pardo-knuth-algorithm.pro @@ -0,0 +1,26 @@ +:- use_module(library(dcg/basics)). +:- use_module(library(dcg/high_order)). + +main :- + % ask for 11 numbers to be read into a sequence S + format("Enter 11 numbers for evaluation~n", []), + length(S, 11), + phrase_from_stream((sequence(integer, "\n", S), remainder(_)), user_input), + + % reverse sequence S + reverse(S, ReversedS), + + % for each item in sequence S + foreach(( + member(Item, ReversedS), + % result := call a function to do an operation + Result is sqrt(abs(Item)) + 5 * Item ^ 3 + ), + % if result overflows + ( Result > 400 + % alert user + -> format("~d: OVERFLOW~n", [Item]) + % else print result + ; format("~d: ~f~n", [Item, Result]) + ) + ). diff --git a/Task/Trabb-Pardo-Knuth-algorithm/QB64/trabb-pardo-knuth-algorithm.qb64 b/Task/Trabb-Pardo-Knuth-algorithm/QB64/trabb-pardo-knuth-algorithm.qb64 new file mode 100644 index 0000000000..ea9c82ac61 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/QB64/trabb-pardo-knuth-algorithm.qb64 @@ -0,0 +1,26 @@ +Dim s(1 To 11) As Double +Dim x As Double +Dim i As Integer + +Print "enter 11 numbers" +For i = 1 To 11 + Print i; " => "; + Input s(i) +Next i + +Print: Print String$(20, "-") + +For i = 11 To 1 Step -1 + x = f(s(i)) + Print "f("; s(i); ") = "; + If x > 400 Then + Print "-=< overflow >=-" + Else + Print x + End If +Next i +End + +Function f (n As Double) + f = Sqr(Abs(n)) + 5 * n ^ 3 +End Function diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/FreeBASIC/transliterate-english-text-using-the-greek-alphabet.basic b/Task/Transliterate-English-text-using-the-Greek-alphabet/FreeBASIC/transliterate-english-text-using-the-greek-alphabet.basic new file mode 100644 index 0000000000..3bcd628279 --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/FreeBASIC/transliterate-english-text-using-the-greek-alphabet.basic @@ -0,0 +1,118 @@ +Dim As String texts(2) +texts(0) = "The quick brown fox jumped over the lazy dog." +texts(1) = "I was looking at some rhododendrons in my back garden," & Chr(10) & "dressed in my khaki shorts, when the telephone rang." & Chr(10) & Chr(10) & "As I answered it, I cheerfully glimpsed that the July sun" & Chr(10) & "caused a fragment of black pine wax to ooze on the velvet quilt" & Chr(10) & "laying in my patio." +texts(2) = "sphinx of black quartz, judge my vow." + +Type Replacement + oldStr As String + newStr As String +End Type + +Dim Shared As Replacement replacements(51) +replacements(0).oldStr = "ch" : replacements(0).newStr = "χ" +replacements(1).oldStr = "th" : replacements(1).newStr = "θ" +replacements(2).oldStr = "ps" : replacements(2).newStr = "ψ" +replacements(3).oldStr = "ph" : replacements(3).newStr = "f" +replacements(4).oldStr = "Ch" : replacements(4).newStr = "Χ" +replacements(5).oldStr = "Th" : replacements(5).newStr = "Θ" +replacements(6).oldStr = "Ps" : replacements(6).newStr = "Ψ" +replacements(7).oldStr = "Ph" : replacements(7).newStr = "F" +replacements(8).oldStr = "ee" : replacements(8).newStr = "h" +replacements(9).oldStr = "ck" : replacements(9).newStr = "κ" +replacements(10).oldStr = "rh" : replacements(10).newStr = "r" +replacements(11).oldStr = "kh" : replacements(11).newStr = "χ" +replacements(12).oldStr = "Kh" : replacements(12).newStr = "Χ" +replacements(13).oldStr = "oo" : replacements(13).newStr = "w" +replacements(14).oldStr = "a" : replacements(14).newStr = "α" +replacements(15).oldStr = "b" : replacements(15).newStr = "β" +replacements(16).oldStr = "c" : replacements(16).newStr = "κ" +replacements(17).oldStr = "d" : replacements(17).newStr = "δ" +replacements(18).oldStr = "e" : replacements(18).newStr = "ε" +replacements(19).oldStr = "f" : replacements(19).newStr = "φ" +replacements(20).oldStr = "g" : replacements(20).newStr = "γ" +replacements(21).oldStr = "h" : replacements(21).newStr = "η" +replacements(22).oldStr = "i" : replacements(22).newStr = "ι" +replacements(23).oldStr = "j" : replacements(23).newStr = "ι" +replacements(24).oldStr = "k" : replacements(24).newStr = "κ" +replacements(25).oldStr = "l" : replacements(25).newStr = "λ" +replacements(26).oldStr = "m" : replacements(26).newStr = "μ" +replacements(27).oldStr = "n" : replacements(27).newStr = "ν" +replacements(28).oldStr = "o" : replacements(28).newStr = "ο" +replacements(29).oldStr = "p" : replacements(29).newStr = "π" +replacements(30).oldStr = "q" : replacements(30).newStr = "κ" +replacements(31).oldStr = "r" : replacements(31).newStr = "ρ" +replacements(32).oldStr = "s" : replacements(32).newStr = "σ" +replacements(33).oldStr = "t" : replacements(33).newStr = "τ" +replacements(34).oldStr = "u" : replacements(34).newStr = "υ" +replacements(35).oldStr = "v" : replacements(35).newStr = "β" +replacements(36).oldStr = "w" : replacements(36).newStr = "ω" +replacements(37).oldStr = "x" : replacements(37).newStr = "ξ" +replacements(38).oldStr = "y" : replacements(38).newStr = "υ" +replacements(39).oldStr = "z" : replacements(39).newStr = "ζ" +replacements(40).oldStr = "D" : replacements(40).newStr = "Δ" +replacements(41).oldStr = "F" : replacements(41).newStr = "Φ" +replacements(42).oldStr = "G" : replacements(42).newStr = "Γ" +replacements(43).oldStr = "J" : replacements(43).newStr = "I" +replacements(44).oldStr = "L" : replacements(44).newStr = "Λ" +replacements(45).oldStr = "P" : replacements(45).newStr = "Π" +replacements(46).oldStr = "Q" : replacements(46).newStr = "Κ" +replacements(47).oldStr = "R" : replacements(47).newStr = "Ρ" +replacements(48).oldStr = "S" : replacements(48).newStr = "Σ" +replacements(49).oldStr = "Y" : replacements(49).newStr = "U" +replacements(50).oldStr = "W" : replacements(50).newStr = "Ω" +replacements(51).oldStr = "X" : replacements(51).newStr = "Ξ" + +' Special replacement for "s" at the end of a word or followed by a non-letter +Function replaceSigmaFinal(txt As String) As String + Dim As String res = "" + Dim As Integer i, l = Len(txt) + For i = 1 To l + If Mid(txt, i, 1) = "s" Then + If i = l Or (Mid(txt, i+1, 1) < "A" Or (Mid(txt, i+1, 1) > "Z" And Mid(txt, i+1, 1) < "a") Or Mid(txt, i+1, 1) > "z") Then + res &= "ς" + Else + res &= "s" + End If + Else + res &= Mid(txt, i, 1) + End If + Next + Return res +End Function + +Function replaceString(ByVal txt As String, ByVal buscar As String, ByVal reemplazar As String) As String + Dim As Integer posic = 1, lenBuscar = Len(buscar) + Dim As String resultado = "" + + If lenBuscar = 0 Then Return txt ' Avoid infinite loop + + Do + Dim As Integer idx = InStr(posic, txt, buscar) + If idx = 0 Then + resultado &= Mid(txt, posic) + Exit Do + End If + resultado &= Mid(txt, posic, idx - posic) & reemplazar + posic = idx + lenBuscar + Loop + + Return resultado +End Function + +Function replaceText(txt As String) As String + txt = ReplaceSigmaFinal(txt) + For i As Integer = 0 To UBound(replacements) + txt = ReplaceString(txt, replacements(i).oldStr, replacements(i).newStr) + Next + Return txt +End Function + +' Test program +For i As Integer = Lbound(texts) To Ubound(texts) + Print texts(i) + Print "=>" + Print replaceText(texts(i)) + Print String(65, "=") +Next + +Sleep diff --git a/Task/Tree-datastructures/Rust/tree-datastructures.rs b/Task/Tree-datastructures/Rust/tree-datastructures.rs new file mode 100644 index 0000000000..0583ffe856 --- /dev/null +++ b/Task/Tree-datastructures/Rust/tree-datastructures.rs @@ -0,0 +1,125 @@ +#[derive(Debug, Clone, PartialEq)] +pub struct NestTree { + name: String, + children: Vec, +} + +impl NestTree { + pub fn new(name: &str) -> Self { + NestTree { + name: name.to_string(), + children: Vec::new(), + } + } + + pub fn add_child(&mut self, name: &str) { + self.children.push(NestTree::new(name)); + } + + pub fn get_child_mut(&mut self, index: usize) -> Option<&mut NestTree> { + self.children.get_mut(index) + } + + pub fn print(&self) { + self.print_with_level(0); + } + + fn print_with_level(&self, level: usize) { + let indent = " ".repeat(level * 4); + println!("{}{}", indent, self.name); + for child in &self.children { + child.print_with_level(level + 1); + } + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn children(&self) -> &[NestTree] { + &self.children + } + + pub fn equals(&self, other: &NestTree) -> bool { + self == other + } +} + +pub struct IndentTree { + items: Vec<(i32, String)>, +} + +impl IndentTree { + pub fn new(nest: &NestTree) -> Self { + let mut items = Vec::new(); + items.push((0, nest.name().to_string())); + + let mut indent_tree = IndentTree { items }; + indent_tree.from_nest(nest, 0); + indent_tree + } + + fn from_nest(&mut self, nest: &NestTree, level: i32) { + for child in nest.children() { + self.items.push((level + 1, child.name().to_string())); + self.from_nest(child, level + 1); + } + } + + pub fn print(&self) { + for (level, name) in &self.items { + println!("{} {}", level, name); + } + } + + pub fn to_nest(&self) -> NestTree { + let mut nest = NestTree::new(&self.items[0].1); + self.to_nest_recursive(&mut nest, 1, 0); + nest + } + + fn to_nest_recursive(&self, nest: &mut NestTree, mut pos: usize, level: i32) -> usize { + while pos < self.items.len() && self.items[pos].0 == level + 1 { + nest.add_child(&self.items[pos].1); + let child_index = nest.children().len() - 1; + if let Some(child) = nest.get_child_mut(child_index) { + pos = self.to_nest_recursive(child, pos + 1, level + 1); + } else { + pos += 1; + } + } + pos + } +} + +fn main() { + let mut n = NestTree::new("RosettaCode"); + + // Add children + n.add_child("rocks"); + n.add_child("mocks"); + + // Access children by index to avoid borrowing issues + if let Some(child1) = n.get_child_mut(0) { + child1.add_child("code"); + child1.add_child("comparison"); + child1.add_child("wiki"); + } + + if let Some(child2) = n.get_child_mut(1) { + child2.add_child("trolling"); + } + + println!("Initial nest format:"); + n.print(); + + let i = IndentTree::new(&n); + println!("\nIndent format:"); + i.print(); + + let n2 = i.to_nest(); + println!("\nFinal nest format:"); + n2.print(); + + println!("\nAre initial and final nest formats equal? {}", n.equals(&n2)); +} diff --git a/Task/Tree-datastructures/Zig/tree-datastructures.zig b/Task/Tree-datastructures/Zig/tree-datastructures.zig new file mode 100644 index 0000000000..8591cdf2af --- /dev/null +++ b/Task/Tree-datastructures/Zig/tree-datastructures.zig @@ -0,0 +1,182 @@ +const std = @import("std"); +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; +const print = std.debug.print; + +pub const NestTree = struct { + name: []const u8, + children: ArrayList(NestTree), + allocator: Allocator, + + pub fn init(allocator: Allocator, name: []const u8) !NestTree { + const owned_name = try allocator.dupe(u8, name); + return NestTree{ + .name = owned_name, + .children = ArrayList(NestTree).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *NestTree) void { + for (self.children.items) |*child| { + child.deinit(); + } + self.children.deinit(); + self.allocator.free(self.name); + } + + pub fn addChild(self: *NestTree, name: []const u8) !void { + const child = try NestTree.init(self.allocator, name); + try self.children.append(child); + } + + pub fn getChildMut(self: *NestTree, index: usize) ?*NestTree { + if (index >= self.children.items.len) return null; + return &self.children.items[index]; + } + + pub fn printTree(self: *const NestTree) void { + self.printWithLevel(0); + } + + fn printWithLevel(self: *const NestTree, level: usize) void { + var i: usize = 0; + while (i < level * 4) : (i += 1) { + print(" " , .{}); + } + print("{s}\n", .{self.name}); + + for (self.children.items) |*child| { + child.printWithLevel(level + 1); + } + } + + pub fn getName(self: *const NestTree) []const u8 { + return self.name; + } + + pub fn getChildren(self: *const NestTree) []const NestTree { + return self.children.items; + } + + pub fn equals(self: *const NestTree, other: *const NestTree) bool { + if (!std.mem.eql(u8, self.name, other.name)) return false; + if (self.children.items.len != other.children.items.len) return false; + + for (self.children.items, other.children.items) |*child1, *child2| { + if (!child1.equals(child2)) return false; + } + + return true; + } +}; + +pub const IndentTree = struct { + items: ArrayList(IndentItem), + allocator: Allocator, + + const IndentItem = struct { + level: i32, + name: []const u8, + }; + + pub fn init(allocator: Allocator, nest: *const NestTree) !IndentTree { + var items = ArrayList(IndentItem).init(allocator); + const root_name = try allocator.dupe(u8, nest.getName()); + try items.append(IndentItem{ .level = 0, .name = root_name }); + + var indent_tree = IndentTree{ + .items = items, + .allocator = allocator, + }; + + try indent_tree.fromNest(nest, 0); + return indent_tree; + } + + pub fn deinit(self: *IndentTree) void { + for (self.items.items) |item| { + self.allocator.free(item.name); + } + self.items.deinit(); + } + + fn fromNest(self: *IndentTree, nest: *const NestTree, level: i32) !void { + for (nest.getChildren()) |*child| { + const child_name = try self.allocator.dupe(u8, child.getName()); + try self.items.append(IndentItem{ .level = level + 1, .name = child_name }); + try self.fromNest(child, level + 1); + } + } + + pub fn printTree(self: *const IndentTree) void { + for (self.items.items) |item| { + print("{} {s}\n", .{ item.level, item.name }); + } + } + + pub fn toNest(self: *const IndentTree) !NestTree { + if (self.items.items.len == 0) return error.EmptyIndentTree; + + var nest = try NestTree.init(self.allocator, self.items.items[0].name); + _ = try self.toNestRecursive(&nest, 1, 0); + return nest; + } + + fn toNestRecursive(self: *const IndentTree, nest: *NestTree, pos: usize, level: i32) !usize { + var current_pos = pos; + + while (current_pos < self.items.items.len and self.items.items[current_pos].level == level + 1) { + try nest.addChild(self.items.items[current_pos].name); + const child_index = nest.children.items.len - 1; + if (nest.getChildMut(child_index)) |child| { + current_pos = try self.toNestRecursive(child, current_pos + 1, level + 1); + } else { + current_pos += 1; + } + } + + return current_pos; + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var n = try NestTree.init(allocator, "RosettaCode"); + defer n.deinit(); + + // Add children + try n.addChild("rocks"); + try n.addChild("mocks"); + + // Access children by index to avoid borrowing issues + if (n.getChildMut(0)) |child1| { + try child1.addChild("code"); + try child1.addChild("comparison"); + try child1.addChild("wiki"); + } + + if (n.getChildMut(1)) |child2| { + try child2.addChild("trolling"); + } + + print("Initial nest format:\n" , .{}); + n.printTree(); + + var i = try IndentTree.init(allocator, &n); + defer i.deinit(); + + print("\nIndent format:\n" , .{}); + i.printTree(); + + var n2 = try i.toNest(); + defer n2.deinit(); + + print("\nFinal nest format:\n" , .{} ); + n2.printTree(); + + print("\nAre initial and final nest formats equal? {}\n", .{n.equals(&n2)}); +} diff --git a/Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon b/Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon new file mode 100644 index 0000000000..c4f9e4b06e --- /dev/null +++ b/Task/Tree-from-nesting-levels/Icon/tree-from-nesting-levels.icon @@ -0,0 +1,46 @@ +procedure main() + tests := [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], + [3, 3, 3, 1, 1, 3, 3, 3], [3, 3, 3, 2, 2, 3, 4, 3], + [1, 2, 4, 2, 2, 1] ] + + every test := !tests do + if result := tfnl(test) then + write(limage2(test)," ---> ",limage2(result)) + else + write(limage2(test)," ---> FAILED") +end + +procedure tfnl(levels) + innerlist := [] + level := levels[1] | fail + put(r := [], nested(level,level-1,innerlist)) | fail + /innerlist[1] := r + every i := 2 to *levels & level := levels[i] do + if j := i-1 to 1 by -1 & level >= levels[j] then{ + put(innerlist[j], nested(level,level-levels[j],innerlist)) + /innerlist[i] := innerlist[j] + }else{ + put(r, nested(level,level-1,innerlist)) + /innerlist[i] := r + } + return r +end + +procedure nested(item,level,innerlist) + if level = 0 then{ # special case + put(innerlist,&null) + return item + } + outer := inner := [] + every 2 to level do inner := put(inner,[])[1] + put(inner,item) + put(innerlist,inner) + return outer +end + +procedure limage2(L) + if type(L) ~== "list" then return image(L) + result := "" + every result ||:= limage2(!L) || "," + return ("[" || result[1:-1] || "]") | "[]" +end diff --git a/Task/Tree-traversal/Adina/tree-traversal-1.adina b/Task/Tree-traversal/Adina/tree-traversal-1.adina new file mode 100644 index 0000000000..7c04186ab7 --- /dev/null +++ b/Task/Tree-traversal/Adina/tree-traversal-1.adina @@ -0,0 +1,63 @@ +структура узел + данные левая-ветвь правая-ветвь + #:суффикс -узла + +лист значение = + узел значение ложь ложь + +дерево = + узел 1 + узел 2 + узел 4 + лист 7 + ложь + лист 5 + узел 3 + узел 6 + лист 8 + лист 9 + ложь + +прямой дерево действие = + если дерево тогда + действие данные-узла(дерево) + прямой левая-ветвь-узла(дерево) действие + прямой правая-ветвь-узла(дерево) действие + +центрированный дерево действие = + если дерево тогда + центрированный левая-ветвь-узла(дерево) действие + действие данные-узла(дерево) + центрированный правая-ветвь-узла(дерево) действие + +обратный дерево действие = + если дерево тогда + обратный левая-ветвь-узла(дерево) действие + обратный правая-ветвь-узла(дерево) действие + действие данные-узла(дерево) + +поуровневый дерево действие = + пусть цикл + деревья список(дерево) + если не пустой?(деревья) тогда + цикл + применить добавить + цикл/список + для + дерево деревья + #:когда дерево + действие данные-узла(дерево) + список левая-ветвь-узла(дерево) правая-ветвь-узла(дерево) + +запуск имя обход = + вывести имя + обход дерево + функция (данные) + вывести « » + вывести данные + вывести/перенос «» + +запуск «preorder: » прямой +запуск «inorder: » центрированный +запуск «postorder: » обратный +запуск «level-order: » поуровневый diff --git a/Task/Tree-traversal/Adina/tree-traversal-2.adina b/Task/Tree-traversal/Adina/tree-traversal-2.adina new file mode 100644 index 0000000000..a479f360d8 --- /dev/null +++ b/Task/Tree-traversal/Adina/tree-traversal-2.adina @@ -0,0 +1,68 @@ +english() + +struct node + data left right + +leaf x = + node x #f #f + +the-tree = + node 1 + node 2 + node 4 + leaf 7 + #f + leaf 5 + node 3 + node 6 + leaf 8 + leaf 9 + #f + +preorder tree visit = + let loop + $ t tree + when t + visit node-data(t) + loop node-left(t) + loop node-right(t) + +inorder tree visit = + let loop + $ t tree + when t + loop node-left(t) + visit node-data(t) + loop node-right(t) + +postorder tree visit = + let loop + $ t tree + when t + loop node-left(t) + loop node-right(t) + visit node-data(t) + +levelorder tree visit = + let loop + $ trees + list tree + unless null?(trees) + loop + append* + for/list + (t trees) #:when t + visit node-data(t) + list node-left(t) node-right(t) + +run name order = + printf "~a" name + order the-tree + lambda (x) + printf " ~s" x + newline() + +run "preorder: " preorder +run "inorder: " inorder +run "postorder: " postorder +run "level-order: " levelorder diff --git a/Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb b/Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb new file mode 100644 index 0000000000..a81a0ac0e5 --- /dev/null +++ b/Task/Trigonometric-functions/DuckDB/trigonometric-functions.duckdb @@ -0,0 +1,22 @@ +# degrees to radians +create or replace function radians(degrees) as degrees * pi() / 180.0; + +# radians to degrees +create or replace function degrees(radians) as (radians * 180 / pi()); + +.mode lines +select + sin(-pi() / 6), + cos(3 * pi() / 4), + tan(pi() / 3), + asin(-1 / 2), + acos(-sqrt(2)/2), + atan(sqrt(3)), + + -- Using degrees: + sin(-radians(30)), + cos(radians(135)), + tan(radians(60)), + asin(-1 / 2).degrees(), + acos(-sqrt(2)/2).degrees(), + atan(sqrt(3)).degrees() ; diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx index 1b71fa05ce..8e6a9053d6 100644 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions.rexx @@ -1,6 +1,7 @@ +-- 28 Jul 2025 include Settings -say 'TRIGONOMETRIC FUNCTIONS - 2 Mar 2025' +say 'TRIGONOMETRIC FUNCTIONS' say version say s = Copies('-',77); w = 18 @@ -39,6 +40,4 @@ end say s return -include Functions -include Constants -include Abend +include Math diff --git a/Task/Twos-complement/Ada/twos-complement.ada b/Task/Twos-complement/Ada/twos-complement.ada new file mode 100644 index 0000000000..dd3ebbe70d --- /dev/null +++ b/Task/Twos-complement/Ada/twos-complement.ada @@ -0,0 +1,10 @@ +with Ada.Text_IO; + +procedure Twos_Complement is + type Number is mod 2 ** 32; + A : constant Number := 42; + B : constant Number := not A + 1; + Is_Negative : constant Boolean := A + B = 0; +begin + Ada.Text_IO.Put_Line ("B = -A is " & Is_Negative'Image); +end Twos_Complement; diff --git a/Task/Twos-complement/Fortran/twos-complement.f b/Task/Twos-complement/Fortran/twos-complement.f new file mode 100644 index 0000000000..160e76a191 --- /dev/null +++ b/Task/Twos-complement/Fortran/twos-complement.f @@ -0,0 +1,57 @@ +! +program twos_complement_demo + implicit none + + integer :: x, tc + integer :: nbits + character(len=:), allocatable :: bits_x, bits_not, bits_tc + + ! Prompt for input + write(*,"(a)",advance="no") "Enter a positive integer (or any integer):" + read *, x + + ! Determine bit-width and convert to bit-strings + nbits = bit_size(x) + bits_x = to_bitstring(x) + bits_not = to_bitstring(not(x)) + + ! Compute two's complement: flip all bits then add one + tc = not(x) + 1 + bits_tc = to_bitstring(tc) + + ! Display results + 10 format(a,t30,i0) + 20 format(a,i0,a,t30,a,/) + 30 format(a,t30,a) + write(*,*) + write(*,10) "Original integer:", x + write(*,20) "Bit pattern (", nbits, " bits):", trim(bits_x) + write(*,30) "After bitwise NOT: ", trim(bits_not) + write(*,30) "Then add 1 --> two’s comp:", trim(bits_tc) + write(*,*) + write(*,10) "Two’s complement (decimal):", tc + +contains + + !------------------------------------------------------------ + ! Convert an integer to a string of ‘0’ and ‘1’ + !------------------------------------------------------------ + function to_bitstring(val) result(str) + integer, intent(in) :: val + character(len=:), allocatable :: str + integer :: n, i + + ! Number of bits in this integer kind + n = bit_size(val) + allocate(character(len=n) :: str) + + do i = 1, n + if (btest(val, n - i)) then + str(i:i) = '1' + else + str(i:i) = '0' + end if + end do + end function to_bitstring + +end program twos_complement_demo diff --git a/Task/UPC/Pluto/upc.pluto b/Task/UPC/Pluto/upc.pluto new file mode 100644 index 0000000000..ac82a43fa1 --- /dev/null +++ b/Task/UPC/Pluto/upc.pluto @@ -0,0 +1,110 @@ +local fmt = require "fmt" + +local digitL = { + [" ## #"] = 0, + [" ## #"] = 1, + [" # ##"] = 2, + [" #### #"] = 3, + [" # ##"] = 4, + [" ## #"] = 5, + [" # ####"] = 6, + [" ### ##"] = 7, + [" ## ###"] = 8, + [" # ##"] = 9 +} + +local digitR = { + ["### # "] = 0, + ["## ## "] = 1, + ["## ## "] = 2, + ["# # "] = 3, + ["# ### "] = 4, + ["# ### "] = 5, + ["# # "] = 6, + ["# # "] = 7, + ["# # "] = 8, + ["### # "] = 9 +} + +local end_sentinel = "# #" -- also at start +local mid_sentinel = " # # " + +local function decode_upc(s) + local function decode_upc_impl(input) + local upc = input:strip() + if #upc != 95 then return false end + local pos = 1 + local digits = {} + local sum = 0 + local one_three = {1, 3} + + -- end sentinel + if upc:sub(pos, pos + 2) == end_sentinel then + pos += 3 + else + return false + end + + -- 6 left hand digits + for _ = 1, 6 do + local digit = digitL[upc:sub(pos, pos + 6)] + if !digit then return false end + digits:insert(digit) + sum += digit * one_three[#digits % 2 + 1] + pos += 7 + end + + -- mid sentinel + if upc:sub(pos, pos + 4) == mid_sentinel then + pos += 5 + else + return false + end + + -- 6 right hand digits + for _ = 1, 6 do + local digit = digitR[upc:sub(pos, pos + 6)] + if !digit then return false end + digits:insert(digit) + sum += digit * one_three[#digits % 2 + 1] + pos += 7 + end + + -- end sentinel + if upc:sub(pos, pos + 2) != end_sentinel then return false end + + if sum % 10 == 0 then + fmt.write("%s ", fmt.swrite(digits)) + return true + end + io.write("Failed Checksum ") + return false + end + + if decode_upc_impl(s) then + print("Rightside Up") + elseif decode_upc_impl(s:reverse()) then + print("Upside Down") + else + print("Invalid digit(s)") + end +end + +local barcodes = { + " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", + " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", + " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", + " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", + " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", + " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", + " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", + " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", + " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", + " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " +} +local n = 0 +for barcodes as barcode do + ++n + fmt.write("%2d: ", n) + decode_upc(barcode) +end diff --git a/Task/UPC/Rust/upc.rs b/Task/UPC/Rust/upc.rs new file mode 100644 index 0000000000..a7932479be --- /dev/null +++ b/Task/UPC/Rust/upc.rs @@ -0,0 +1,161 @@ +use std::collections::HashMap; + +fn trim(s: &str) -> &str { + s.trim() +} + +// Helper function to create the left digits map +fn create_left_digits() -> HashMap<&'static str, i32> { + let mut map = HashMap::new(); + map.insert(" ## #", 0); + map.insert(" ## #", 1); + map.insert(" # ##", 2); + map.insert(" #### #", 3); + map.insert(" # ##", 4); + map.insert(" ## #", 5); + map.insert(" # ####", 6); + map.insert(" ### ##", 7); + map.insert(" ## ###", 8); + map.insert(" # ##", 9); + map +} + +// Helper function to create the right digits map +fn create_right_digits() -> HashMap<&'static str, i32> { + let mut map = HashMap::new(); + map.insert("### # ", 0); + map.insert("## ## ", 1); + map.insert("## ## ", 2); + map.insert("# # ", 3); + map.insert("# ### ", 4); + map.insert("# ### ", 5); + map.insert("# # ", 6); + map.insert("# # ", 7); + map.insert("# # ", 8); + map.insert("### # ", 9); + map +} + +const END_SENTINEL: &str = "# #"; +const MID_SENTINEL: &str = " # # "; + +fn decode_upc(input: &str) { + let left_digits = create_left_digits(); + let right_digits = create_right_digits(); + + let decode = |candidate: &str| -> (bool, Vec) { + let mut output = Vec::new(); + let mut pos = 0; + + // Check start sentinel + if candidate.len() < pos + END_SENTINEL.len() { + return (false, output); + } + let part = &candidate[pos..pos + END_SENTINEL.len()]; + if part == END_SENTINEL { + pos += END_SENTINEL.len(); + } else { + return (false, output); + } + + // Decode left 6 digits + for _ in 0..6 { + if candidate.len() < pos + 7 { + return (false, output); + } + let part = &candidate[pos..pos + 7]; + pos += 7; + + if let Some(&digit) = left_digits.get(part) { + output.push(digit); + } else { + return (false, output); + } + } + + // Check middle sentinel + if candidate.len() < pos + MID_SENTINEL.len() { + return (false, output); + } + let part = &candidate[pos..pos + MID_SENTINEL.len()]; + if part == MID_SENTINEL { + pos += MID_SENTINEL.len(); + } else { + return (false, output); + } + + // Decode right 6 digits + for _ in 0..6 { + if candidate.len() < pos + 7 { + return (false, output); + } + let part = &candidate[pos..pos + 7]; + pos += 7; + + if let Some(&digit) = right_digits.get(part) { + output.push(digit); + } else { + return (false, output); + } + } + + // Check end sentinel + if candidate.len() < pos + END_SENTINEL.len() { + return (false, output); + } + let part = &candidate[pos..pos + END_SENTINEL.len()]; + if part == END_SENTINEL { + pos += END_SENTINEL.len(); + } else { + return (false, output); + } + + // Calculate checksum + let sum: i32 = output.iter().enumerate().map(|(i, &digit)| { + if i % 2 == 0 { + 3 * digit + } else { + digit + } + }).sum(); + + (sum % 10 == 0, output) + }; + + let candidate = trim(input); + + let (valid, digits) = decode(candidate); + if valid { + println!("{:?}", digits); + } else { + // Try upside down + let reversed: String = candidate.chars().rev().collect(); + let (valid_reversed, digits_reversed) = decode(&reversed); + if valid_reversed { + println!("{:?} Upside down", digits_reversed); + } else if !digits.is_empty() { + println!("Invalid checksum"); + } else { + println!("Invalid digit(s)"); + } + } +} + +fn main() { + let barcodes = vec![ + " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", + " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", + " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", + " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", + " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", + " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", + " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", + " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", + " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", + " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # ", + ]; + + for barcode in &barcodes { + decode_upc(barcode); + } +} diff --git a/Task/UPC/Scala/upc.scala b/Task/UPC/Scala/upc.scala new file mode 100644 index 0000000000..c8270fdf84 --- /dev/null +++ b/Task/UPC/Scala/upc.scala @@ -0,0 +1,129 @@ +object UPC { + private val SEVEN = 7 + + private val LEFT_DIGITS = Map( + " ## #" -> 0, + " ## #" -> 1, + " # ##" -> 2, + " #### #" -> 3, + " # ##" -> 4, + " ## #" -> 5, + " # ####" -> 6, + " ### ##" -> 7, + " ## ###" -> 8, + " # ##" -> 9 + ) + + private val RIGHT_DIGITS = LEFT_DIGITS.map { case (key, value) => + key.replace(' ', 's').replace('#', ' ').replace('s', '#') -> value + } + + private val END_SENTINEL = "# #" + private val MID_SENTINEL = " # # " + + private def decode(candidate: String): (Boolean, List[Int]) = { + var pos = 0 + val output = scala.collection.mutable.ListBuffer[Int]() + + // Check start sentinel + if (candidate.length < pos + END_SENTINEL.length || + candidate.substring(pos, pos + END_SENTINEL.length) != END_SENTINEL) { + return (false, output.toList) + } + pos += END_SENTINEL.length + + // Decode left side digits + for (_ <- 1 until SEVEN) { + if (candidate.length < pos + SEVEN) { + return (false, output.toList) + } + val part = candidate.substring(pos, pos + SEVEN) + pos += SEVEN + + LEFT_DIGITS.get(part) match { + case Some(digit) => output += digit + case None => return (false, output.toList) + } + } + + // Check middle sentinel + if (candidate.length < pos + MID_SENTINEL.length || + candidate.substring(pos, pos + MID_SENTINEL.length) != MID_SENTINEL) { + return (false, output.toList) + } + pos += MID_SENTINEL.length + + // Decode right side digits + for (_ <- 1 until SEVEN) { + if (candidate.length < pos + SEVEN) { + return (false, output.toList) + } + val part = candidate.substring(pos, pos + SEVEN) + pos += SEVEN + + RIGHT_DIGITS.get(part) match { + case Some(digit) => output += digit + case None => return (false, output.toList) + } + } + + // Check end sentinel + if (candidate.length < pos + END_SENTINEL.length || + candidate.substring(pos, pos + END_SENTINEL.length) != END_SENTINEL) { + return (false, output.toList) + } + + // Calculate checksum + val sum = output.zipWithIndex.map { case (digit, index) => + if (index % 2 == 0) 3 * digit else digit + }.sum + + (sum % 10 == 0, output.toList) + } + + private def printList(list: List[Int]): Unit = { + print("[") + print(list.mkString(", ")) + print("]") + } + + private def decodeUPC(input: String): Unit = { + val candidate = input.trim + val (isValid, digits) = decode(candidate) + + if (isValid) { + printList(digits) + println() + } else { + // Try upside down + val reversed = candidate.reverse + val (isValidReversed, digitsReversed) = decode(reversed) + + if (isValidReversed) { + printList(digitsReversed) + println(" Upside down") + } else if (digitsReversed.length == 12) { + println("Invalid checksum") + } else { + println("Invalid digit(s)") + } + } + } + + def main(args: Array[String]): Unit = { + val barcodes = List( + " # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # ", + " # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # ", + " # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # ", + " # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # ", + " # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # ", + " # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # ", + " # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # ", + " # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # ", + " # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # ", + " # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # " + ) + + barcodes.foreach(decodeUPC) + } +} diff --git a/Task/URL-decoding/DuckDB/url-decoding.duckdb b/Task/URL-decoding/DuckDB/url-decoding.duckdb new file mode 100644 index 0000000000..366491b3a4 --- /dev/null +++ b/Task/URL-decoding/DuckDB/url-decoding.duckdb @@ -0,0 +1,27 @@ +create or replace function hex2chr(pxx) as + replace(pxx,'%','').from_hex().decode() ; + +create or replace function urldecode(url) as ( + WITH RECURSIVE cte AS ( + -- Base case: set xx as the first sequence of %XX encodings if any + SELECT + replace(url, '+', ' ') AS decoded, + regexp_extract(replace(url, '+', ' '), '(%[0-9A-Fa-f]{2})+') AS xx + UNION ALL + -- Recursive case: replace the xx encodings with the decoded character(s) + SELECT + replace(decoded, xx, xx.hex2chr()) AS decoded, + regexp_extract(replace(decoded, xx, ' '), '(%[0-9A-Fa-f]{2})+') as xx + FROM cte + WHERE xx != '' + ) + SELECT decoded FROM cte + WHERE xx = '' +); + +SELECT s, url_decode(s), urldecode(s) +FROM unnest( [ + 'http%3A%2F%2Ffoo%20bar%2F', + 'google.com/search?q=%60Abdu%27l-Bah%C3%A1', + '%25%32%35' + ]) _(s); diff --git a/Task/UTF-8-encode-and-decode/DuckDB/utf-8-encode-and-decode.duckdb b/Task/UTF-8-encode-and-decode/DuckDB/utf-8-encode-and-decode.duckdb new file mode 100644 index 0000000000..f08b197743 --- /dev/null +++ b/Task/UTF-8-encode-and-decode/DuckDB/utf-8-encode-and-decode.duckdb @@ -0,0 +1,12 @@ +create or replace function utf8x(codepoint) as ( + select hex(encode(chr(codepoint))) +); + +# Example: +select s, + unicode(s) as codepoint, + chr(codepoint) as c, + unicode(c), + utf8x(codepoint), + decode(from_hex(utf8x(codepoint))) as "decode(from_hex())" +from values ('A'), ('ö'), ('Ж'), ('€'), ('𝄞') t(s); diff --git a/Task/Undefined-values/YAMLScript/undefined-values.ys b/Task/Undefined-values/YAMLScript/undefined-values.ys new file mode 100644 index 0000000000..970fd00f36 --- /dev/null +++ b/Task/Undefined-values/YAMLScript/undefined-values.ys @@ -0,0 +1,9 @@ +!YS-v0 + +x =: +y =: 1 + +each v qw(x y): + if v:symbol:resolve:bound?: + say: "$v is defined" + say: "$v is not defined" diff --git a/Task/Unicode-strings/00-TASK.txt b/Task/Unicode-strings/00-TASK.txt index 2b6c3dc5de..10bd3e4617 100644 --- a/Task/Unicode-strings/00-TASK.txt +++ b/Task/Unicode-strings/00-TASK.txt @@ -1,6 +1,6 @@ As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, [[Unicode]] is your best friend. -It is a very capable and [https://www.youtube.com/watch?v=MijmeoH9LT4 remarquable] tool, but also quite complex compared to older single- and double-byte character encodings. +It is a very capable and [https://www.youtube.com/watch?v=MijmeoH9LT4 remarkable] tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? diff --git a/Task/Unicode-strings/EasyLang/unicode-strings.easy b/Task/Unicode-strings/EasyLang/unicode-strings.easy new file mode 100644 index 0000000000..8bc99ea0f5 --- /dev/null +++ b/Task/Unicode-strings/EasyLang/unicode-strings.easy @@ -0,0 +1,14 @@ +s$ = "你好 😀" +print len s$ +for c$ in strchars s$ + print c$ & " " & strcode c$ +. +print strpos s$ "好" +print strchar 128512 +print s$ +flag$ = "🇮🇹" +print flag$ +print len flag$ +for c$ in strchars flag$ + print c$ & " " & strcode c$ +. diff --git a/Task/Unicode-strings/Pluto/unicode-strings.pluto b/Task/Unicode-strings/Pluto/unicode-strings.pluto new file mode 100644 index 0000000000..756380921c --- /dev/null +++ b/Task/Unicode-strings/Pluto/unicode-strings.pluto @@ -0,0 +1,26 @@ +require "uchar" +require "gchar" +local fmt = require("fmt") + +local w = "voilà" +local u = uchar.of(w) +for i = 1, u:len() do + io.write($"{u:get(i)} ") -- prints the 5 Unicode 'characters' +end +print($"\nThe length of {w} is {u:len()}") + +print("\nIts code-points are:") +fmt.lprint(u:tocodes(), " ", "") -- prints the code-points as numbers + +print("\n\nIts bytes are: ") +fmt.lprint(u:tobytes(), " ", "") -- prints the bytes as numbers + +local zwe = "👨‍👩‍👧" +local g = gchar.of(zwe) +local codepoints = g:tocodes() +local bytes = g:tobytes() + +print($"\n\n{zwe} has:") +fmt.print(" %d bytes: %s", #bytes, fmt.swrite(bytes, " ", "")) +fmt.print(" %d code-points: %s", #codepoints, fmt.swrite(codepoints, " ", "")) +fmt.print(" %d grapheme", g:len()) diff --git a/Task/Unix-ls/DuckDB/unix-ls.duckdb b/Task/Unix-ls/DuckDB/unix-ls.duckdb new file mode 100644 index 0000000000..0426aff992 --- /dev/null +++ b/Task/Unix-ls/DuckDB/unix-ls.duckdb @@ -0,0 +1 @@ +from glob('*') order by file; diff --git a/Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena b/Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena new file mode 100644 index 0000000000..1071fc9ba9 --- /dev/null +++ b/Task/Unprimeable-numbers/Agena/unprimeable-numbers.agena @@ -0,0 +1,101 @@ +scope # find unprimeable numbers - numbers which can't be made into a prime by changing one digit + + local constant maxNumber := 9_999_999; # maximum number we will consider + + # sieve the primes up to maxNumber + local prime; create register prime( maxNumber ); + prime[ 1 ] := false; + for sPos from 2 to maxNumber do prime[ sPos ] := true od; + for sPos from 2 to entier( sqrt( maxNumber ) ) do + if prime[ sPos ] then + for p from sPos * sPos to maxNumber by sPos do + prime[ p ] := false + od + fi + od; + + # returns true if n is unprimeable, false otherwise + local procedure isUnprimeable( n :: number ) :: boolean + local result := false; + if n < 100 then return false + elif prime[ n ] then return false + else + # need to try changing a digit + local constant lastDigit := n mod 10; + local constant leadingDigits := n - lastDigit; + if prime[ leadingDigits + 1 ] then return false + elif prime[ leadingDigits + 3 ] then return false + elif prime[ leadingDigits + 7 ] then return false + elif prime[ leadingDigits + 9 ] then return false + elif lastDigit = 2 or lastDigit = 5 then + # the final digit is 2 or 5, changing the other digits can't make a prime + # unless there is only one other digit which we can change to 0 + local v, dc := leadingDigits \ 10, 1; + while v > 0 do + if v mod 10 <> 0 then dc +:= 1 fi; + v \:= 10 + od; + return dc <> 2 + elif not odd lastDigit then + return true # last digit is even, changing the other digits won't make a prime + else + # last digit is 1, 3, 7, 9: must try changing the other digits + local m10, r10 := 10, 100; + result := true; + while result and n > r10 do + local constant base := ( ( n \ r10 ) * r10 ) + ( n mod m10 ); + for i from 0 by m10 while result and i < r10 do + result := not prime[ base + i ] + od; + m10 *:= 10; + r10 *:= 10 + od; + if result then + # still not unprimeable, try changing the first digit + local constant base := n mod m10; + for i from 0 by m10 while result and i < r10 do + result := not prime[ base + i ] + od + fi + fi + fi; + return result + end + + # returns a string representation of n with commas, n must be an integer + local procedure commatise( n :: number ) :: string + local constant nStr := tostring( abs n ); + local constant signStr := if n < 0 then "-" else "" fi; + local constant cStr := strings.reverse( strings.gsub( strings.reverse( nStr ), "%d%d%d", "%1," ) ); + return signStr & strings.gsub( cStr, "^,", "" ) + end; + + scope # find unprimeable numbers + local uCount, dCount := 0, 0; + local firstUnprimeable := reg( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); # note: indexed from 1 + for i from 100 while i < size prime and dCount < 10 do + if isUnprimeable( i ) then + uCount +:= 1; + if uCount = 1 then + printf( "First 35 unprimeable numbers: %d", i ) + elif uCount <= 35 then + printf( " %d", i ) + elif uCount = 600 then + printf( "\n600th unprimeable number: %s", commatise( i ) ) + fi; + # need to add 1 to the final digit because firstUnprimeable is indxed from 1 + local constant finalDigitPlus1 := ( i mod 10 ) + 1; + if firstUnprimeable[ finalDigitPlus1 ] = 0 then + # first unprimeable number with this final digit + dCount +:= 1; + firstUnprimeable[ finalDigitPlus1 ] := i + fi + fi + od; + # show the first unprimeable number that ends with each digit + print(); + for i from 0 to size firstUnprimeable - 1 do + printf( "First unprimeable number ending in %d: %s\n", i, commatise( firstUnprimeable[ i + 1 ] ) ) + od + end +end diff --git a/Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto b/Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto new file mode 100644 index 0000000000..6f3e66f19e --- /dev/null +++ b/Task/Unprimeable-numbers/Pluto/unprimeable-numbers.pluto @@ -0,0 +1,97 @@ +do -- find unprimable numbers - numbers which can't be made into a prime by changing one digit + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library - inc. some prime utilities + + local maxNumber = 9_999_999 -- maximum number we will consider + + -- sieve the primes up to maxNumber + local prime = int.arecomps( maxNumber ):map( | v | -> not v ) + + -- returns true if n is unprimeable, false otherwise + local function isUnprimeable( n : number ) : boolean + local result = false + if n < 100 then return false + elseif prime[ n ] then return false + else + -- need to try changing a digit + local lastDigit = n % 10 + local leadingDigits = n - lastDigit + if prime[ leadingDigits + 1 ] then return false + elseif prime[ leadingDigits + 3 ] then return false + elseif prime[ leadingDigits + 7 ] then return false + elseif prime[ leadingDigits + 9 ] then return false + elseif lastDigit == 2 or lastDigit == 5 then + -- the final digit is 2 or 5, changing the other digits can't make a prime + -- unless there is only one other digit which we can change to 0 + local v, dc = leadingDigits // 10, 1 + while v > 0 do + if v % 10 != 0 then dc += 1 end + v //= 10 + end + return dc != 2 + elseif lastDigit % 2 == 0 then + return true -- last digit is even, changing the other digits won't make a prime + else + -- last digit is 1, 3, 7, 9 must try changing the other digits + local m10, r10 = 10, 100 + result = true + while result and n > r10 do + local base = ( ( n // r10 ) * r10 ) + ( n % m10 ) + local i = 0 + while result and i < r10 do + result = not prime[ base + i ] + i += m10 + end + m10 *= 10 + r10 *= 10 + end + if result then + -- still not unprimeable, try changing the first digit + local base = n % m10 + local i = 0 + while result and i < r10 do + result = not prime[ base + i ] + i += m10 + end + end + end + end + return result + end + + -- returns a string representation of n with commas, n must be an integer + local function commatise( n : number ) : string + local cStr = tostring( math.abs( n ) ):reverse():gsub( "%d%d%d", "%1," ):reverse() + return if n < 0 then "-" else "" end..cStr:gsub( "^,", "" ) + end + + do -- find unprimeable numbers + local uCount, dCount = 0, 0 + local firstUnprimeable = { [0] = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } + for i = 100, # prime do + if dCount >= 10 then break end + if isUnprimeable( i ) then + uCount += 1 + if uCount == 1 then + fmt.write( "First 35 unprimeable numbers: %d", i ) + elseif uCount <= 35 then + fmt.write( " %d", i ) + elseif uCount == 600 then + fmt.write( "\n600th unprimeable number: %s", commatise( i ) ) + end + local finalDigit = i % 10 + if firstUnprimeable[ finalDigit ] == 0 then + -- first unprimeable number with this final digit + dCount += 1 + firstUnprimeable[ finalDigit ] = i + end + end + end + -- show the first unprimeable number that ends with each digit + fmt.write( "\n" ) + for i = 0, 9 do + fmt.write( "First unprimeable number ending in %d %s\n", i, commatise( firstUnprimeable[ i ] ) ) + end + end +end diff --git a/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx b/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx index a6ca596e28..07ac31ba1b 100644 --- a/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx +++ b/Task/Unprimeable-numbers/REXX/unprimeable-numbers.rexx @@ -1,4 +1,4 @@ --- 22 Mar 2025 +-- 3 Aug 2025 include Settings say 'UNPRIMEABLE NUMBERS' @@ -89,6 +89,4 @@ say '-----------' say Format(Time('e'),,3) 'seconds'; say return -include Functions -include Sequences -include Abend +include Math diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl new file mode 100644 index 0000000000..e21eeb4c16 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-1.jl @@ -0,0 +1,21 @@ +// Save this section as main.c +#include + +extern int Query (char * Data, size_t * Length); + +int main (int argc, char * argv []) +{ + char Buffer [1024]; + size_t Size = sizeof (Buffer); + + if (0 == Query (Buffer, &Size)) + { + printf ("failed to call Query\n"); + } + else + { + char * Ptr = Buffer; + while (Size-- > 0) putchar (*Ptr++); + putchar ('\n'); + } +} diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl new file mode 100644 index 0000000000..9a7b4a3d08 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-2.jl @@ -0,0 +1,17 @@ +# Save this section as a file called query.jl + +function Query(buffer::Ptr{UInt8}, length::Ptr{Csize_t})::Cint + """ Define the Query function to be called from C """ + + max_size = unsafe_load(length) + data = "Hello from Julia!" + bytes = codeunits(data) + max_size < length(bytes) && return 0 # Failure: buffer too small + for i in 1:length(bytes) + unsafe_store!(buffer, bytes[i], i) + end + unsafe_store!(length, length(bytes)) + return 1 +end + +Base.@export Query diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl new file mode 100644 index 0000000000..210c4ec0c2 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-3.jl @@ -0,0 +1,33 @@ +// save this section as query_wrapper.c + +#include + +JULIA_DEFINE_FAST_TLS() + +int Query(char *Data, size_t *Length) { + jl_init(); + + jl_eval_string("include(\"query.jl\")"); // Include the Julia file containing Query function + + jl_function_t *func = jl_get_function(jl_main_module, "Query"); + if (!func) { + jl_atexit_hook(0); + return 0; + } + + jl_value_t *buffer = jl_ptr_to_array_1d(jl_uint8_type, Data, *Length, 0); + jl_value_t *length = jl_box_uint64((uint64_t)Length); + + // Call the query function within Julia + jl_value_t *result = jl_call2(func, buffer, length); + if (jl_exception_occurred()) { + jl_atexit_hook(0); + return 0; + } + + // Get return value + int ret = jl_unbox_int32(result); + + jl_atexit_hook(0); + return ret; // Return the result of the Query function from the C shared library +} diff --git a/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl new file mode 100644 index 0000000000..42ffe58ace --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Julia/use-another-language-to-call-a-function-4.jl @@ -0,0 +1,19 @@ +# Save this section as compile.sh and run it in a terminal with all files in same directory +gcc -shared -fPIC -o libquery.so query_wrapper.c -I$JULIA_DIR/include/julia -L$JULIA_DIR/lib -ljulia -Wl,-rpath,$JULIA_DIR/lib +if [ $? -ne 0 ]; then + echo "Error: Compilation of libquery.so failed." + exit 1 +fi +echo "libquery.so compiled successfully." + +gcc -o main main.c -L. -lquery +if [ $? -ne 0 ]; then + echo "Error: Compilation of main failed." + exit 1 +fi +echo "main compiled successfully." + +export LD_LIBRARY_PATH=.:$JULIA_DIR/lib:$LD_LIBRARY_PATH +./main + +echo "Script finished." diff --git a/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua new file mode 100644 index 0000000000..474a9c5d9e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-1.lua @@ -0,0 +1,24 @@ +-- Query.lua + +-- basic kv dbase +function qdb_init () + qdb = {} -- global in lua + qdb["who are you?"] = "I am Lua" + qdb["what are you?"] = "I am a Lua virtual machine" + qdb["when are you?"] = "I am live" + qdb["where are you?"] = "Here I am" + qdb["how are you?"] = "I am a fine" + qdb["default"] = "unknown query" + +end + +-- call from C with key => Data +function Query(k) + + local key = string.lower(k) + + if (qdb[key] == nil) then key = "default" end + + lua_response = qdb[key] + +end diff --git a/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua new file mode 100644 index 0000000000..ea13576fb6 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-2.lua @@ -0,0 +1,205 @@ +/* Query_lua.c */ +#include +#include +#include +#include + +#include +#include +#include + +// tell lua how many args for a function +typedef enum { NOARG, ONEARG, TWOARGS, THREEARGS } argcount; +// 0 1 2 3 + +// diagnostics when things go wrong +typedef enum { C_OK, C_FAILURE, LUA_FAILURE} exitcode; +// 0 1 2 + +/* lua vars we will create or use */ +const char* lua_Query = "Query"; +const char* lua_Data = "Data"; +const char* lua_qdb_init = "qdb_init"; +const char* lua_qdb = "qdb"; +const char* lua_response = "lua_response"; + + +int LTop; // global C index to top of lua stack + +/* function prototypes */ + +int Query(char* Data, size_t * Length); + +void fail(const char* fmsg, const char* errstr, exitcode ret); + +lua_State* C_lua_init(const char* luafile); + +bool C_push_string(lua_State* L, const char* name, + const char* str, const size_t n); + +bool C_get_string( lua_State * L, const char* src, + char* dest, size_t max); + + +// exit program with diagnostice and exitcode +void fail(const char* fmsg, const char* errstr, exitcode ret) { + + fprintf(stderr, "%s ", fmsg); + + if (errstr != NULL){ fprintf(stderr, "%s ", errstr); } + + fprintf(stderr, "\n"); + + exit(ret); +} + + +// push C string to lua +bool C_push_string(lua_State* L, const char* name, + const char* str, const size_t n){ + (void) n; + lua_pushstring(L, str); + lua_setglobal(L, name); + return true; +} + +// get C string from lua string by variable var +bool C_get_string( lua_State * L, const char* luavar, + char* dest, size_t max){ + + const char* lstring = NULL; + size_t len = 0; + + lua_getglobal(L, luavar); + + if(!lua_isstring(L, -1)) { + fail("expected a string", lua_tostring(L, -1), LUA_FAILURE); + } + + LTop = lua_gettop(L); + + lstring = lua_tolstring(L, LTop, &max ); + len = strlen(lstring); + + if (len > 0) { + strncpy(dest, lstring, len); + dest[len+1] = '\0'; + return true; + } + + return false; +} + + +/* + initialize the lua vm + load up the lua file + any commands in the global area will run +*/ + +lua_State* C_lua_init(const char* luafile) { + + exitcode status = C_OK; + + /// creates Lua machine & env + lua_State* L = luaL_newstate(); + if (L == NULL) { + fail("could not create lua state", "lua internal failure", LUA_FAILURE); + } + + // imports basic libs like string, io, os, table, utf-8, math + luaL_openlibs(L); + + // lua file to load + status = luaL_loadfile(L, luafile); + + if (status != LUA_OK){ + fail("loadfile failed", lua_tostring(L, -1), LUA_FAILURE); + } + + /* "priming run" + SEE http://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm + */ + if (lua_pcall(L, 0, 0, 0) != LUA_OK) { + fail("priming run failed",lua_tostring(L, -1), LUA_FAILURE); + } + + return L; +} + +/* -------------------------------------------------- + function called by main in Query.c +*/ + +int Query(char* Data, size_t * Length) { + + /* ======= SETUP LUA ====== */ + // create Lua vm with file + lua_State* L = C_lua_init("Query.lua"); + + // call db init + lua_getglobal(L, lua_qdb_init); + luaL_checktype(L, -1, LUA_TFUNCTION); // optionally check lua type + + int result = lua_pcall(L, NOARG, 0, 0); // execute lua func + if (result != LUA_OK) { + fail("failed to run qdb_init function", lua_tostring(L, -1), LUA_FAILURE); + } + + /* ======= RUN LUA CODE ========= */ + + // put Data into Lua env as a string + C_push_string(L, lua_Data, Data, *Length-1); + + /* set function to call and 1 arg(s) */ + lua_getglobal(L, lua_Query); // function + luaL_checktype(L, -1, LUA_TFUNCTION); + + lua_getglobal(L, lua_Data); // arg + luaL_checktype(L, -1, LUA_TSTRING); + + // call lua function with 1 arg* + result = lua_pcall(L, ONEARG, LUA_MULTRET, 0); + if (result != LUA_OK) { + fail("failed to run Query function", lua_tostring(L, -1), LUA_FAILURE); + } + + // lua_response should have our answer + char* response = calloc(*Length, sizeof(char)); + if (response == NULL) { + fail("calloc failed allocation", NULL, C_FAILURE); + } + + // created within lua + C_get_string(L, lua_response, response, *Length); + + + /* ======== CLEANUP LUA ====== */ + + // clean up lua vars and close vm + // (assign var = nil) + lua_pushnil(L); lua_setglobal(L, lua_response); + lua_pushnil(L); lua_setglobal(L, lua_Data); + lua_pushnil(L); lua_setglobal(L, lua_Query); + lua_pushnil(L); lua_setglobal(L, lua_qdb); + lua_close(L); // lua is done + + + /* ======= REPORT ====== */ + + size_t rlen = strlen(response); + + if (rlen > 0) { + strncpy(Data, response, *Length-1); + Data[rlen] = '\0'; + free(response); // because dynamically allocated + } else { + fail("lua", "no response", LUA_FAILURE); + } + + + return 1; +} + + +// end diff --git a/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua new file mode 100644 index 0000000000..850ea4a502 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Lua/use-another-language-to-call-a-function-3.lua @@ -0,0 +1,4 @@ +gcc -std=c2x -Wall -Wextra \ + -I/usr/include/lua5.3 -o query \ + Query.c Query_lua.c \ + -L/usr/lib/x84_64-linux-gnu/ -l lua5.3 diff --git a/Task/User-input-Graphical/FuncSug/user-input-graphical.funcsug b/Task/User-input-Graphical/FuncSug/user-input-graphical.funcsug new file mode 100644 index 0000000000..4b6c13587c --- /dev/null +++ b/Task/User-input-Graphical/FuncSug/user-input-graphical.funcsug @@ -0,0 +1,10 @@ +# input a string +displayNewMessage("Enter a string") +var text := awaitHumanText() + +# input 75000 +displayNewMessage("Enter the number 75000") +var numberInput := displayNewElementIn('', 'body', 'input', true) +while numberInput.value != 75000: + awaitDomeventBeep('change', numberInput) +displayNewMessage("You've entered 75000") diff --git a/Task/User-input-Text/ArkScript/user-input-text.ark b/Task/User-input-Text/ArkScript/user-input-text.ark new file mode 100644 index 0000000000..248c7e0921 --- /dev/null +++ b/Task/User-input-Text/ArkScript/user-input-text.ark @@ -0,0 +1,5 @@ +(let str (input "str> ")) +(let num (toNumber (input "num> "))) + +(if (nil? num) + (print "num is not a valid number")) diff --git a/Task/User-input-Text/Extended-Color-BASIC/user-input-text.basic b/Task/User-input-Text/Extended-Color-BASIC/user-input-text.basic new file mode 100644 index 0000000000..5acaca32f9 --- /dev/null +++ b/Task/User-input-Text/Extended-Color-BASIC/user-input-text.basic @@ -0,0 +1,4 @@ +10 INPUT A$ +20 INPUT B +30 IF B<>75000 THEN 20 +40 PRINT A$, B diff --git a/Task/User-input-Text/Pluto/user-input-text.pluto b/Task/User-input-Text/Pluto/user-input-text.pluto new file mode 100644 index 0000000000..dc9501c569 --- /dev/null +++ b/Task/User-input-Text/Pluto/user-input-text.pluto @@ -0,0 +1,4 @@ +io.write("Enter a number: ") +a = io.read("*l")+0 +io.write("Enter a string: ") +b = io.read("*l") diff --git a/Task/Van-Eck-sequence/Agena/van-eck-sequence.agena b/Task/Van-Eck-sequence/Agena/van-eck-sequence.agena new file mode 100644 index 0000000000..f5e8b8516e --- /dev/null +++ b/Task/Van-Eck-sequence/Agena/van-eck-sequence.agena @@ -0,0 +1,26 @@ +scope # find elements of the Van Eck Sequence - first term is 0, following + # terms are 0 if the previous was the first appearance of the element + # or how far back in the sequence the last element appeared otherwise + + local procedure VanEck( n :: number ) :: sequence # returns the first n elements of the Van Eck sequence + local constant result := seq(); for i to n do result[ i ] := 0 od; + local constant pos := seq(); for i to n + 1 do pos[ i ] := 0 od; + for i from 2 to n do + local constant j := i - 1; + local constant prev := result[ j ] + 1; # prev is indexed from 1, not 0 + if pos[ prev ] <> 0 then + # not a new element + result[ i ] := j - pos[ prev ] + fi; + pos[ prev ] := j + od; + return result + end; + + local constant veSeq := VanEck( 1000 ); # construct the first 1000 terms of the sequence + # show the first and last 10 elements + for i to 10 do printf( " %d", veSeq[ i ] ) od; + printf( "\n" ); + for i from size veSeq - 9 to size veSeq do printf( " %d", veSeq[ i ] ) od; + printf( "\n" ) +end diff --git a/Task/Van-Eck-sequence/Pluto/van-eck-sequence.pluto b/Task/Van-Eck-sequence/Pluto/van-eck-sequence.pluto new file mode 100644 index 0000000000..351a65f1db --- /dev/null +++ b/Task/Van-Eck-sequence/Pluto/van-eck-sequence.pluto @@ -0,0 +1,26 @@ +do --[[ find elements of the Van Eck Sequence - first term is 0, following + terms are 0 if the previous was the first appearance of the element + or how far back in the sequence the last element appeared otherwise + ]] + local fmt = require( "fmt" ) -- RC formatting module + + local function VanEck( n : number ) : table -- returns the first n elements of the Van Eck sequence + local result = {} for i = 1, n do result[ i ] = 0 end + local pos = {} for i = 1, n + 1 do pos[ i ] = 0 end + for i = 2, n do + local j = i - 1 + local prev = result[ j ] + 1; -- prev is indexed from 1, not 0 + if pos[ prev ] != 0 then + -- not a new element + result[ i ] = j - pos[ prev ] + end + pos[ prev ] = j + end + return result + end + + local veSeq = VanEck( 1000 ) -- construct the first 1000 terms of the sequence + -- show the first and last 10 elements + fmt.lprint( veSeq:slice( 1, 10 ) ) + fmt.lprint( veSeq:slice( # veSeq - 9, # veSeq ) ) +end diff --git a/Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena b/Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena new file mode 100644 index 0000000000..31e5e74e2f --- /dev/null +++ b/Task/Van-der-Corput-sequence/Agena/van-der-corput-sequence.agena @@ -0,0 +1,32 @@ +scope /* show members of the van der Corput sequence in various bases + translated from the C sample + */ + + # returns the numerator and denominator of the nth member of the van der Corput sequence + # in the specified base + local procedure vc( nth :: number, base :: number ) + local p, q, n := 0, 1, nth; + + while n <> 0 do + p *:= base + p +:= n mod base + q *:= base + n \:= base + od; + + # return the numerator and denominator reduced by their gcd + local num, denom := p, q; + q := numtheory.gcd( p, q ); + return num \ q, denom \ q + end + + # task + for b from 2 to 5 do + printf( "base %d:", b ); + for i from 0 to 9 do + local n, d := vc( i, b ); + if n <> 0 then printf( " %d/%d", n, d ) else printf( " 0" ) fi; + end + io.write( "\n" ) + od +end diff --git a/Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto b/Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto new file mode 100644 index 0000000000..07f57fefc6 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Pluto/van-der-corput-sequence.pluto @@ -0,0 +1,35 @@ +do --[[ show members of the van der Corput sequence in various bases + translated from the C sample + ]] + + local int = require( "int" ) -- RC integer module - includes gcd + + -- returns the numerator and denominator of the nth member of the van der Corput sequence + -- in the specified base + local function vc( nth : number, base : number ) + local p, q, n = 0, 1, nth + + while n != 0 do + p *= base + p += n % base + q *= base + n //= base + end + + num, denom = p, q + + -- return the numerator and denominator reduced by their gcd + q = int.gcd( num, denom ) + return num // q, denom // q + end + + -- task + for b = 2, 5 do + io.write( $"base {b}:" ) + for i = 0, 9 do + local n, d = vc( i, b ) + io.write( if n != 0 then $" {n}/{d}" else " 0" end ) + end + io.write( "\n" ) + end +end diff --git a/Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys b/Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys new file mode 100644 index 0000000000..3c710205c1 --- /dev/null +++ b/Task/Van-der-Corput-sequence/YAMLScript/van-der-corput-sequence.ys @@ -0,0 +1,18 @@ +!YS-v0 + +defn main(b): + each n range(10): + say: + format '%.6f': + vdc: n b + +defn vdc(n b): + loop n n, d 1, vdc 0.0: + if n > 0: + then: + d *=: b + r =: n % b + n .=: quot(b) + vdc +=: r / d + recur: n, d, vdc + else: vdc diff --git a/Task/Variable-size-Get/DuckDB/variable-size-get.duckdb b/Task/Variable-size-Get/DuckDB/variable-size-get.duckdb new file mode 100644 index 0000000000..c65f1c2616 --- /dev/null +++ b/Task/Variable-size-Get/DuckDB/variable-size-get.duckdb @@ -0,0 +1,50 @@ +CREATE OR REPLACE FUNCTION parse_int(val) AS ( + regexp_extract('decimal(12,3)', '[0-9]+')::INTEGER +); + +# DECIMAL(p, s): +CREATE OR REPLACE FUNCTION d2w(p) AS ( + if( p <= 4, 16, + if( p <= 9, 32, + if( p <= 18, 64, + 128) )) +); + +CREATE OR REPLACE FUNCTION nominal_size_in_bits(val) AS ( + CASE typeof(val) + WHEN 'TINYINT' THEN 8 + WHEN 'SMALLINT' THEN 16 + WHEN 'INTEGER' THEN 32 + WHEN 'BIGINT' THEN 64 + WHEN 'HUGEINT' THEN 128 + + WHEN 'UTINYINT' THEN 8 + WHEN 'USMALLINT' THEN 16 + WHEN 'UINTEGER' THEN 32 + WHEN 'UBIGINT' THEN 64 + WHEN 'UHUGEINT' THEN 128 + + WHEN 'JSON' THEN 8 * length(val::JSON::VARCHAR) + WHEN 'UUID' THEN 128 + + WHEN 'FLOAT' THEN 32 + WHEN 'DOUBLE' THEN 64 + WHEN 'BOOLEAN' THEN 8 + WHEN 'BIT' THEN (CEIL(LENGTH(val::VARCHAR) / 8.0) * 8)::INTEGER + WHEN 'BLOB' THEN octet_length(val::BLOB) * 8 + ELSE CASE + WHEN typeof(val) LIKE 'DECIMAL%' + THEN d2w( regexp_extract(typeof(val), '[0-9]+')::INTEGER ) + WHEN typeof(val) LIKE 'VARCHAR%' + THEN 8 * octet_length(encode(val::VARCHAR)) + ELSE NULL + END + END +); + +# Example: + +select nominal_size_in_bits('1'::BIT) as "1::BIT", + nominal_size_in_bits(bitstring('1',7)) as "0000001", + nominal_size_in_bits(9.4) as "9.4", + nominal_size_in_bits('👨') as "glyph"; diff --git a/Task/Variable-size-Set/DuckDB/variable-size-set.duckdb b/Task/Variable-size-Set/DuckDB/variable-size-set.duckdb new file mode 100644 index 0000000000..116c73ed70 --- /dev/null +++ b/Task/Variable-size-Set/DuckDB/variable-size-set.duckdb @@ -0,0 +1,34 @@ +# DECIMAL(p, s): +CREATE OR REPLACE FUNCTION d2w(p) AS ( + if( p <= 4, 16, + if( p <= 9, 32, + if( p <= 18, 64, + 128) )) +); + +CREATE OR REPLACE FUNCTION nominal_size_in_bits(val) AS ( + CASE typeof(val) + WHEN 'TINYINT' THEN 8 + WHEN 'SMALLINT' THEN 16 + WHEN 'INTEGER' THEN 32 + WHEN 'BIGINT' THEN 64 + WHEN 'HUGEINT' THEN 128 + + WHEN 'UTINYINT' THEN 8 + WHEN 'USMALLINT' THEN 16 + WHEN 'UINTEGER' THEN 32 + WHEN 'UBIGINT' THEN 64 + WHEN 'UHUGEINT' THEN 128 + + WHEN 'BOOLEAN' THEN 8 + WHEN 'UUID' THEN 128 + + WHEN 'FLOAT' THEN 32 + WHEN 'DOUBLE' THEN 64 + ELSE CASE + WHEN typeof(val) LIKE 'DECIMAL%' + THEN d2w( regexp_extract(typeof(val), '[0-9]+')::INTEGER ) + ELSE NULL + END + END +); diff --git a/Task/Variables/Bc/variables.bc b/Task/Variables/Bc/variables.bc new file mode 100644 index 0000000000..b5d37ccefc --- /dev/null +++ b/Task/Variables/Bc/variables.bc @@ -0,0 +1,15 @@ +a = 1 /* global variables */ + +define add(a,b) { /* function parameters */ + return a+b +} + +define test(c) { /* local variables ('auto') */ + auto a + a = 2 + return c / a +} + +{ print a,"\n" +print add(1,2),"\n" +print test(120),"\n" } diff --git a/Task/Variadic-function/Pluto/variadic-function.pluto b/Task/Variadic-function/Pluto/variadic-function.pluto new file mode 100644 index 0000000000..ac5ddffda8 --- /dev/null +++ b/Task/Variadic-function/Pluto/variadic-function.pluto @@ -0,0 +1,10 @@ +local function variadic(...args) + for args as arg do print(arg) end +end + +variadic("Pip", "Squeak", "Wilfred") +local a = {} +a:insert("Faith") +a:insert("Hope") +a:insert("Charity") +variadic(a:unpack()) diff --git a/Task/Vector-products/DuckDB/vector-products.duckdb b/Task/Vector-products/DuckDB/vector-products.duckdb new file mode 100644 index 0000000000..5695b0d31c --- /dev/null +++ b/Task/Vector-products/DuckDB/vector-products.duckdb @@ -0,0 +1,17 @@ +create or replace function cross_product(a,b) as table ( + select [ a[2]*b[3] - a[3]*b[2], a[3]*b[1] - a[1]*b[3], a[1]*b[2]-a[2]*b[1] ]); + +create or replace function scalar_triple_product(a,b,c) as table ( + select list_dot_product(a, (from cross_product(b, c))) ); + +create or replace function vector_triple_product(a,b,c) as table ( + from cross_product(a, (from cross_product(b, c))) ); + +# Examples +select [3, 4, 5] as a, + [4, 3, 5] as b, + [-5, -12, -13] as c, + list_dot_product(a, b) as 'a . b', + ((from cross_product(a, b) )) as 'a x b', + ((from scalar_triple_product(a, b, c))) as 'a . (b x c)', + ((from vector_triple_product(a, b, c))) as 'a x (b x c)' ; diff --git a/Task/Vector-products/Pluto/vector-products.pluto b/Task/Vector-products/Pluto/vector-products.pluto new file mode 100644 index 0000000000..130486ab8f --- /dev/null +++ b/Task/Vector-products/Pluto/vector-products.pluto @@ -0,0 +1,19 @@ +local vector3 = require "vector3" +local fmt = require "fmt" + +local function scalar_tripleproduct(a, b, c) return a:dot(b:crossproduct(c)) end + +local function vector_tripleproduct(a, b, c) return a:crossproduct(b:crossproduct(c)) end + +local a = vector3( 3, 4, 5) +local b = vector3( 4, 3, 5) +local c = vector3(-5, -12, -13) + +fmt.print("a = %s", a) +fmt.print("b = %s", b) +fmt.print("c = %s", c) +print() +fmt.print("a . b = %s", a:dot(b)) +fmt.print("a x b = %s", a:crossproduct(b)) +fmt.print("a . b x c = %s", scalar_tripleproduct(a, b, c)) +fmt.print("a x b x c = %s", vector_tripleproduct(a, b, c)) diff --git a/Task/Vector-products/REXX/vector-products.rexx b/Task/Vector-products/REXX/vector-products.rexx index d2687f7539..eb314fe6b1 100644 --- a/Task/Vector-products/REXX/vector-products.rexx +++ b/Task/Vector-products/REXX/vector-products.rexx @@ -1,4 +1,4 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings say 'VECTOR PRODUCTS' @@ -6,23 +6,20 @@ say version say a = '3 4 5'; b = '4 3 5'; c = '-5 -12 -13'; d = '1 2 3' say 'VALUES' -say 'A =' Vlst2Form(a) -say 'B =' Vlst2Form(b) -say 'C =' Vlst2Form(c) -say 'D =' Vlst2Form(d) +say 'A =' Lst2FormV(a) +say 'B =' Lst2FormV(b) +say 'C =' Lst2FormV(c) +say 'D =' Lst2FormV(d) say say 'BASICS' -say 'A . B =' Vdot(a,b)/1 -say 'A x B =' Vlst2Form(Vcross(a,b)) +say 'A . B =' DotV(a,b)/1 '= dot product' +say 'A x B =' Lst2FormV(CrossV(a,b)) '= cross product' say say 'BONUS' -say 'A . (BxC) =' VscalTrip(a,b,c)/1 -say 'A x (BxC) =' Vlst2Form(VvectTrip(a,b,c)) -say '(AxB) . (CxD) =' VscalQuad(a,b,c,d)/1 -say '(AxB) x (CxD) =' Vlst2Form(VvectQuad(a,b,c,d)) +say 'A . (BxC) =' ScalTripV(a,b,c)/1 '= scalar triple product' +say 'A x (BxC) =' Lst2FormV(VectTripV(a,b,c)) '= vector triple product' +say '(AxB) . (CxD) =' ScalQuadV(a,b,c,d)/1 '= scalar quadruple product' +say '(AxB) x (CxD) =' Lst2FormV(VectQuadV(a,b,c,d)) '= vector quadruple product' exit -include Vector -include Functions -include Constants -include Abend +include Math diff --git a/Task/Vector/Ada/vector.ada b/Task/Vector/Ada/vector.ada new file mode 100644 index 0000000000..688292cc03 --- /dev/null +++ b/Task/Vector/Ada/vector.ada @@ -0,0 +1,31 @@ +with Ada.Text_IO; + +procedure Vector_Demo is + type Vector is record + X, Y : Float; + end record; + + function "+" (A, B : Vector) return Vector is + (A.X + B.X, A.Y + B.Y); + + function "-" (A, B : Vector) return Vector is + (A.X - B.X, A.Y - B.Y); + + function "*" (S : Float; A : Vector) return Vector is + (S * A.X, S * A.Y); + + function "/" (A : Vector; S : Float) return Vector is + (A.X / S, A.Y / S); + + procedure Print (A : Vector) is + begin + Ada.Text_IO.Put_Line ("(" & A.X'Image & "," & A.Y'Image & ")"); + end Print; + + Example : Vector := (1.0, 1.0); +begin + Print (Example + Example); + Print (Example - Example); + Print (2.0 * Example); + Print (Example / 2.0); +end Vector_Demo; diff --git a/Task/Vector/Pluto/vector.pluto b/Task/Vector/Pluto/vector.pluto new file mode 100644 index 0000000000..774d4dcce5 --- /dev/null +++ b/Task/Vector/Pluto/vector.pluto @@ -0,0 +1,31 @@ +local fmt = require "fmt" + +class vector2 + static function polar(r, theta) + return new vector2(r * math.cos(theta), r * math.sin(theta)) + end + + static function scale(s, v) return v * s end + + function __construct(public x, public y) end + + function __add(v) return new vector2(self.x + v.x, self.y + v.y) end + function __sub(v) return new vector2(self.x - v.x, self.y - v.y) end + function __mul(s) return new vector2(self.x * s, self.y * s) end + function __div(s) return new vector2(self.x / s, self.y / s) end + + function __tostring() return $"({self.x}, {self.y})" end +end + +local v1 = new vector2(5, 7) +local v2 = new vector2(2, 3) +local v3 = vector2.polar(math.sqrt(2.0), math.pi / 4) +fmt.print("v1 = %s", v1) +fmt.print("v2 = %s", v2) +fmt.print("v3 = %s", v3) +print() +fmt.print("v1 + v2 = %s", v1 + v2) +fmt.print("v1 - v2 = %s", v1 - v2) +fmt.print("v1 * 11 = %s", v1 * 11) +fmt.print("11 * v2 = %s", vector2.scale(11, v2)) +fmt.print("v1 / 2 = %s", v1 / 2) diff --git a/Task/Vector/REXX/vector.rexx b/Task/Vector/REXX/vector.rexx index 2a7854d747..3ad112f709 100644 --- a/Task/Vector/REXX/vector.rexx +++ b/Task/Vector/REXX/vector.rexx @@ -1,4 +1,4 @@ --- 19 May 2025 +-- 28 Jul 2025 include Settings say 'VECTOR' @@ -6,26 +6,23 @@ say version say a = '1 2 3'; b = '3 2 1'; c = 3; d = '4 5'; e = '2 1' say 'VALUES' -say 'A =' Vlst2Form(a) -say 'B =' Vlst2Form(b) +say 'A =' Lst2FormV(a) +say 'B =' Lst2FormV(b) say 'C =' c -say 'D =' Vlst2Form(d) -say 'E =' Vlst2Form(e) +say 'D =' Lst2FormV(d) +say 'E =' Lst2FormV(e) say say 'BASICS' -say 'A+B =' Vlst2Form(Vadd(a,b)) -say 'A-B =' Vlst2Form(Vsub(a,b)) -say 'A*C =' Vlst2Form(Vmul(a,c)) -say 'A/C =' Vlst2Form(Vdiv(a,c)) +say 'A+B =' Lst2FormV(AddV(a,b)) +say 'A-B =' Lst2FormV(SubV(a,b)) +say 'A*C =' Lst2FormV(ScaleV(a,c)) +say 'A/C =' Lst2FormV(ScaleV(a,1/c)) say say 'BONUS' -say 'Length(D) =' Vlen(d)+0 -say 'Angle(D) =' Vang(d)+0 -say 'Polar(D) =' Vlst2Form(Vrec2Pol(d)) -say 'Rect(E) =' Vlst2Form(Vpol2Rec(e)) +say 'Length(D) =' LenV(d)+0 +say 'Angle(D) =' AngV(d)+0 +say 'Polar(D) =' Lst2FormV(Rec2PolV(d)) +say 'Rect(E) =' Lst2FormV(Pol2RecV(e)) exit -include Vector -include Functions -include Constants -include Abend +include Math diff --git a/Task/Verhoeff-algorithm/Zig/verhoeff-algorithm.zig b/Task/Verhoeff-algorithm/Zig/verhoeff-algorithm.zig new file mode 100644 index 0000000000..54a2560abf --- /dev/null +++ b/Task/Verhoeff-algorithm/Zig/verhoeff-algorithm.zig @@ -0,0 +1,112 @@ +const std = @import("std"); +const print = std.debug.print; + +const MULTIPLICATION_TABLE: [10][10]i32 = [_][10]i32{ + [_]i32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, + [_]i32{ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5 }, + [_]i32{ 2, 3, 4, 0, 1, 7, 8, 9, 5, 6 }, + [_]i32{ 3, 4, 0, 1, 2, 8, 9, 5, 6, 7 }, + [_]i32{ 4, 0, 1, 2, 3, 9, 5, 6, 7, 8 }, + [_]i32{ 5, 9, 8, 7, 6, 0, 4, 3, 2, 1 }, + [_]i32{ 6, 5, 9, 8, 7, 1, 0, 4, 3, 2 }, + [_]i32{ 7, 6, 5, 9, 8, 2, 1, 0, 4, 3 }, + [_]i32{ 8, 7, 6, 5, 9, 3, 2, 1, 0, 4 }, + [_]i32{ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, +}; + +const INVERSE: [10]i32 = [_]i32{ 0, 4, 3, 2, 1, 5, 6, 7, 8, 9 }; + +const PERMUTATION_TABLE: [8][10]i32 = [_][10]i32{ + [_]i32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, + [_]i32{ 1, 5, 7, 6, 2, 8, 3, 0, 9, 4 }, + [_]i32{ 5, 8, 0, 3, 7, 9, 6, 1, 4, 2 }, + [_]i32{ 8, 9, 1, 6, 0, 4, 3, 5, 2, 7 }, + [_]i32{ 9, 4, 5, 3, 1, 2, 6, 8, 7, 0 }, + [_]i32{ 4, 2, 8, 6, 5, 7, 3, 9, 0, 1 }, + [_]i32{ 2, 7, 9, 3, 8, 0, 6, 4, 1, 5 }, + [_]i32{ 7, 0, 4, 6, 9, 1, 3, 2, 5, 8 }, +}; + +fn verhoeffChecksum(allocator: std.mem.Allocator, number: []const u8, do_validation: bool, do_display: bool) !i32 { + if (do_display) { + const calculation_type = if (do_validation) "Validation" else "Check digit"; + print("{s} calculations for {s}\n\n", .{ calculation_type, number }); + print(" i ni p[i, ni] c\n", .{}); + print("-------------------\n", .{}); + } + + var working_number = std.ArrayList(u8).init(allocator); + defer working_number.deinit(); + + try working_number.appendSlice(number); + if (!do_validation) { + try working_number.append('0'); + } + + var c: i32 = 0; + const le = working_number.items.len - 1; + + var i: usize = le + 1; + while (i > 0) { + i -= 1; + const ni = working_number.items[i] - '0'; + const pos = (le - i) % 8; + const pi = PERMUTATION_TABLE[pos][ni]; + c = MULTIPLICATION_TABLE[@intCast(c)][@as(usize, @intCast(pi))]; + + if (do_display) { + print("{:2} {:2} {:2} {:2}\n\n", .{ le - i, ni, pi, c }); + } + } + + if (do_display and !do_validation) { + print("inverse[{}] = {}\n\n", .{ c, INVERSE[@intCast(c)] }); + } + + if (do_validation) { + return if (c == 0) 1 else 0; + } else { + return INVERSE[@intCast(c)]; + } +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const Test = struct { + test_num: []const u8, + display: bool, + }; + + const tests = [_]Test{ + .{ .test_num = "123", .display = true }, + .{ .test_num = "12345", .display = true }, + .{ .test_num = "123456789012", .display = false }, + }; + + for (tests) |my_test| { + const digit = try verhoeffChecksum(allocator, my_test.test_num, false, my_test.display); + print("The check digit for {s} is {}\n\n", .{ my_test.test_num, digit }); + + // Create test numbers with check digit and with '9' + var correct_number = std.ArrayList(u8).init(allocator); + defer correct_number.deinit(); + try correct_number.appendSlice(my_test.test_num); + try correct_number.append('0' + @as(u8, @intCast(digit))); + + var incorrect_number = std.ArrayList(u8).init(allocator); + defer incorrect_number.deinit(); + try incorrect_number.appendSlice(my_test.test_num); + try incorrect_number.append('9'); + + const numbers = [_][]const u8{ correct_number.items, incorrect_number.items }; + + for (numbers) |number| { + const validation_result = try verhoeffChecksum(allocator, number, true, my_test.display); + const result = if (validation_result == 1) "correct" else "incorrect"; + print("The validation for \"{s}\" is \"{s}\". \n", .{ number, result }); + } + } +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx b/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx index 5b7e3fbb9d..cb84428fc4 100644 --- a/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/REXX/verify-distribution-uniformity-chi-squared-test.rexx @@ -1,4 +1,4 @@ --- 8 May 2025 +-- 28 Jul 2025 include Settings say 'VERIFY DISTRIBUTION UNIFORMITY / CHI-SQUARED TEST' @@ -12,7 +12,7 @@ call Timer exit Check: -procedure expose stat. glob. +procedure expose stat. Memo. arg xx -- Dataset stat. = 0 @@ -60,8 +60,4 @@ say 'Is dataset uniform?' Word('Yes No',(Abs(pv)= 'A' and c <= 'Z') { + const key_char = key[key_index % key.len]; + // Fix the integer overflow by using a safer formula + const shift = @as(i32, c) - @as(i32, key_char); + const adjusted_shift = @mod(shift + 26, 26); + const decrypted = @as(u8, @intCast(adjusted_shift)) + 'A'; + try result.append(decrypted); + key_index += 1; + } + } + + return result.toOwnedSlice(); +} + +pub fn main() !void { + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = arena.allocator(); + + // Parse cryptogram - remove spaces + var enc = std.ArrayList(u8).init(allocator); + defer enc.deinit(); + + for (CRYPTOGRAM) |c| { + if (c >= 'A' and c <= 'Z') { + try enc.append(c); + } + } + + // Convert to indices + var cryptogram = std.ArrayList(u8).init(allocator); + defer cryptogram.deinit(); + + for (enc.items) |c| { + try cryptogram.append(c - 'A'); + } + + var best_fit: f32 = std.math.floatMax(f32); + var best_key = std.ArrayList(u8).init(allocator); + defer best_key.deinit(); + + var j: usize = 1; + while (j <= 26) : (j += 1) { + const key = try allocator.alloc(u8, j); + const fit = freqEveryNth(cryptogram.items, key); + + if (fit < best_fit) { + best_fit = fit; + best_key.clearAndFree(); + try best_key.appendSlice(key); + } + allocator.free(key); + } + + // Print results + const stdout = std.io.getStdOut().writer(); + try stdout.print("best key: ", .{}); + for (best_key.items) |c| { + try stdout.writeByte(c); + } + try stdout.writeByte('\n'); + + const decrypted = try decrypt(allocator, enc.items, best_key.items); + defer allocator.free(decrypted); + + try stdout.print("\nDecrypted text:\n{s}\n", .{decrypted}); +} diff --git a/Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs b/Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs new file mode 100644 index 0000000000..fb65be9685 --- /dev/null +++ b/Task/Vogels-approximation-method/C-sharp/vogels-approximation-method.cs @@ -0,0 +1,117 @@ +using System; +using System.Linq; +using System.Threading.Tasks; + +public class VogelsApproximationMethod +{ + private static readonly int[] demand = {30, 20, 70, 30, 60}; + private static readonly int[] supply = {50, 60, 50, 50}; + private static readonly int[,] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}, + {19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}}; + + private static readonly int nRows = supply.Length; + private static readonly int nCols = demand.Length; + + private static bool[] rowDone = new bool[nRows]; + private static bool[] colDone = new bool[nCols]; + private static int[,] result = new int[nRows, nCols]; + + public static async Task Main(string[] args) + { + int supplyLeft = supply.Sum(); + int totalCost = 0; + + while (supplyLeft > 0) + { + int[] cell = await NextCell(); + int r = cell[0]; + int c = cell[1]; + + int quantity = Math.Min(demand[c], supply[r]); + demand[c] -= quantity; + if (demand[c] == 0) + colDone[c] = true; + + supply[r] -= quantity; + if (supply[r] == 0) + rowDone[r] = true; + + result[r, c] = quantity; + supplyLeft -= quantity; + + totalCost += quantity * costs[r, c]; + } + + // Print results + for (int i = 0; i < nRows; i++) + { + Console.Write("["); + for (int j = 0; j < nCols; j++) + { + Console.Write(result[i, j]); + if (j < nCols - 1) Console.Write(", "); + } + Console.WriteLine("]"); + } + Console.WriteLine($"Total cost: {totalCost}"); + } + + private static async Task NextCell() + { + Task task1 = Task.Run(() => MaxPenalty(nRows, nCols, true)); + Task task2 = Task.Run(() => MaxPenalty(nCols, nRows, false)); + + int[] res1 = await task1; + int[] res2 = await task2; + + if (res1[3] == res2[3]) + return res1[2] < res2[2] ? res1 : res2; + + return (res1[3] > res2[3]) ? res2 : res1; + } + + private static int[] Diff(int j, int len, bool isRow) + { + int min1 = int.MaxValue, min2 = int.MaxValue; + int minP = -1; + + for (int i = 0; i < len; i++) + { + if (isRow ? colDone[i] : rowDone[i]) + continue; + + int c = isRow ? costs[j, i] : costs[i, j]; + if (c < min1) + { + min2 = min1; + min1 = c; + minP = i; + } + else if (c < min2) + min2 = c; + } + return new int[] {min2 - min1, min1, minP}; + } + + private static int[] MaxPenalty(int len1, int len2, bool isRow) + { + int md = int.MinValue; + int pc = -1, pm = -1, mc = -1; + + for (int i = 0; i < len1; i++) + { + if (isRow ? rowDone[i] : colDone[i]) + continue; + + int[] res = Diff(i, len2, isRow); + if (res[0] > md) + { + md = res[0]; // max diff + pm = i; // pos of max diff + mc = res[1]; // min cost + pc = res[2]; // pos of min cost + } + } + return isRow ? new int[] {pm, pc, mc, md} : new int[] {pc, pm, mc, md}; + } +} diff --git a/Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math b/Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math new file mode 100644 index 0000000000..56a1d5cf1e --- /dev/null +++ b/Task/Vogels-approximation-method/Mathematica/vogels-approximation-method.math @@ -0,0 +1,123 @@ +(* Transportation Problem Solver using Vogel's Approximation Method *) + +costs = <| + "W" -> <|"A" -> 16, "B" -> 16, "C" -> 13, "D" -> 22, "E" -> 17|>, + "X" -> <|"A" -> 14, "B" -> 14, "C" -> 13, "D" -> 19, "E" -> 15|>, + "Y" -> <|"A" -> 19, "B" -> 19, "C" -> 20, "D" -> 23, "E" -> 50|>, + "Z" -> <|"A" -> 50, "B" -> 12, "C" -> 50, "D" -> 15, "E" -> 11|> +|>; + +demand = <|"A" -> 30, "B" -> 20, "C" -> 70, "D" -> 30, "E" -> 60|>; +cols = Sort[Keys[demand]]; +supply = <|"W" -> 50, "X" -> 60, "Y" -> 50, "Z" -> 50|>; + +(* Initialize result matrix *) +res = AssociationMap[ + Function[k, AssociationMap[0 &, Keys[demand]]], + Keys[costs] +]; + +(* Initialize g dictionary for sorting *) +g = <||>; + +(* Sort destinations by cost for each supplier *) +Do[ + g[x] = SortBy[Keys[costs[x]], costs[x][#] &]; + , {x, Keys[supply]} +]; + +(* Sort suppliers by cost for each destination *) +Do[ + g[x] = SortBy[Keys[costs], costs[#][x] &]; + , {x, Keys[demand]} +]; + +(* Main algorithm loop *) +While[Length[g] > 0, + (* Calculate penalties for demand nodes *) + d = <||>; + Do[ + If[KeyExistsQ[demand, x] && Length[g[x]] > 0, + d[x] = If[Length[g[x]] > 1, + costs[g[x][[2]]][x] - costs[g[x][[1]]][x], + costs[g[x][[1]]][x] + ]; + ]; + , {x, Keys[demand]} + ]; + + (* Calculate penalties for supply nodes *) + s = <||>; + Do[ + If[KeyExistsQ[supply, x] && Length[g[x]] > 0, + s[x] = If[Length[g[x]] > 1, + costs[x][g[x][[2]]] - costs[x][g[x][[1]]], + costs[x][g[x][[1]]] + ]; + ]; + , {x, Keys[supply]} + ]; + + (* Find keys with maximum penalties *) + fKey = If[Length[d] > 0, + First[Keys[d] // SortBy[d[#] &] // Reverse], + "" + ]; + tKey = If[Length[s] > 0, + First[Keys[s] // SortBy[s[#] &] // Reverse], + "" + ]; + + (* Get the actual maximum values *) + maxD = If[Length[d] > 0, d[fKey], 0]; + maxS = If[Length[s] > 0, s[tKey], 0]; + + (* Choose the allocation with higher penalty *) + {t, f} = If[maxD > maxS, + {fKey, g[fKey][[1]]}, + {g[tKey][[1]], tKey} + ]; + + (* Allocate minimum of supply and demand *) + v = Min[supply[f], demand[t]]; + res[f][t] += v; + demand[t] -= v; + + (* Update demand and remove if satisfied *) + If[demand[t] == 0, + Do[ + If[KeyExistsQ[supply, k] && supply[k] != 0, + g[k] = DeleteCases[g[k], t] + ]; + , {k, Keys[supply]} + ]; + g = KeyDrop[g, t]; + demand = KeyDrop[demand, t]; + ]; + + (* Update supply and remove if exhausted *) + supply[f] -= v; + If[supply[f] == 0, + Do[ + If[KeyExistsQ[demand, k] && demand[k] != 0, + g[k] = DeleteCases[g[k], f] + ]; + , {k, Keys[demand]} + ]; + g = KeyDrop[g, f]; + supply = KeyDrop[supply, f]; + ]; +]; + +(*Display results*) +Print["Transportation Solution:"]; + +Dataset[res] + +totalCost = 0; +Do[rowData = Table[ + totalCost += res[supplier][dest]*costs[supplier][dest]; + , {dest, cols}]; + , {supplier, Sort[Keys[costs]]}]; + +Print["Total Cost = ", totalCost]; diff --git a/Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig b/Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig new file mode 100644 index 0000000000..872d05373b --- /dev/null +++ b/Task/Vogels-approximation-method/Zig/vogels-approximation-method.zig @@ -0,0 +1,212 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; + +const Vogel = struct { + supply: ArrayList(i32), + demand: ArrayList(i32), + costs: ArrayList(ArrayList(i32)), + n_rows: i32, + n_cols: i32, + row_done: ArrayList(bool), + col_done: ArrayList(bool), + allocator: std.mem.Allocator, + + const Self = @This(); + + pub fn init(allocator: std.mem.Allocator) Self { + return Self{ + .supply = ArrayList(i32).init(allocator), + .demand = ArrayList(i32).init(allocator), + .costs = ArrayList(ArrayList(i32)).init(allocator), + .n_rows = 0, + .n_cols = 0, + .row_done = ArrayList(bool).init(allocator), + .col_done = ArrayList(bool).init(allocator), + .allocator = allocator, + }; + } + + pub fn deinit(self: *Self) void { + self.supply.deinit(); + self.demand.deinit(); + for (self.costs.items) |*row| { + row.deinit(); + } + self.costs.deinit(); + self.row_done.deinit(); + self.col_done.deinit(); + } + + pub fn approximate(self: *Self) !void { + var results = ArrayList(ArrayList(i32)).init(self.allocator); + defer { + for (results.items) |*row| { + row.deinit(); + } + results.deinit(); + } + + // Initialize results matrix + for (0..@intCast(self.n_rows)) |_| { + var row = ArrayList(i32).init(self.allocator); + for (0..@intCast(self.n_cols)) |_| { + try row.append(0); + } + try results.append(row); + } + + var supply_remaining: i32 = 0; + for (self.supply.items) |s| { + supply_remaining += s; + } + + var total_cost: i32 = 0; + + while (supply_remaining > 0) { + const cell = try self.next_cell(); + const r = cell[0]; + const c = cell[1]; + const q = if (self.demand.items[c] < self.supply.items[r]) + self.demand.items[c] + else + self.supply.items[r]; + + self.demand.items[c] -= q; + if (self.demand.items[c] == 0) { + self.col_done.items[c] = true; + } + + self.supply.items[r] -= q; + if (self.supply.items[r] == 0) { + self.row_done.items[r] = true; + } + + results.items[r].items[c] = q; + supply_remaining -= q; + total_cost += q * self.costs.items[r].items[c]; + } + + print(" A B C D E\n", .{}); + for (results.items, 0..) |result, i| { + print("{c}", .{@as(u8, @intCast('W' + i))}); + for (result.items) |item| { + print(" {:>2}", .{item}); + } + print("\n", .{}); + } + print("\nTotal Cost = {}\n", .{total_cost}); + } + + fn next_cell(self: *Self) ![]usize { + const res1 = try self.max_penalty(self.n_rows, self.n_cols, true); + const res2 = try self.max_penalty(self.n_cols, self.n_rows, false); + + if (res1[3] == res2[3]) { + return if (res1[2] < res2[2]) res1 else res2; + } + return if (res1[3] > res2[3]) res2 else res1; + } + + fn max_penalty(self: *Self, len1: i32, len2: i32, is_row: bool) ![]usize { + var md: i32 = std.math.minInt(i32); + var pc: i32 = -1; + var pm: i32 = -1; + var mc: i32 = -1; + + for (0..@intCast(len1)) |i| { + const should_process = if (is_row) + !self.row_done.items[i] + else + !self.col_done.items[i]; + + if (should_process) { + var min1: i32 = std.math.maxInt(i32); + var min2: i32 = min1; + var min_p: i32 = -1; + + for (0..@intCast(len2)) |j| { + const should_process_inner = if (is_row) + !self.col_done.items[j] + else + !self.row_done.items[j]; + + if (should_process_inner) { + const c = if (is_row) + self.costs.items[i].items[j] + else + self.costs.items[j].items[i]; + + if (c < min1) { + min2 = min1; + min1 = c; + min_p = @intCast(j); + } else if (c < min2) { + min2 = c; + } + } + } + + const diff = min2 - min1; + if (diff > md) { + md = diff; + pm = @intCast(i); + mc = min1; + pc = min_p; + } + } + } + + var result = try self.allocator.alloc(usize, 4); + if (is_row) { + result[0] = @intCast(pm); + result[1] = @intCast(pc); + result[2] = @intCast(mc); + result[3] = @intCast(md); + } else { + result[0] = @intCast(pc); + result[1] = @intCast(pm); + result[2] = @intCast(mc); + result[3] = @intCast(md); + } + return result; + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + var my_test = Vogel.init(allocator); + defer my_test.deinit(); + + // Initialize supply + try my_test.supply.appendSlice(&[_]i32{ 50, 60, 50, 50 }); + + // Initialize demand + try my_test.demand.appendSlice(&[_]i32{ 30, 20, 70, 30, 60 }); + + // Initialize costs matrix + const cost_data = [_][]const i32{ + &[_]i32{ 16, 16, 13, 22, 17 }, + &[_]i32{ 14, 14, 13, 19, 15 }, + &[_]i32{ 19, 19, 20, 23, 50 }, + &[_]i32{ 50, 12, 50, 15, 11 }, + }; + + for (cost_data) |row_data| { + var row = ArrayList(i32).init(allocator); + try row.appendSlice(row_data); + try my_test.costs.append(row); + } + + my_test.n_rows = 4; + my_test.n_cols = 5; + + // Initialize row_done and col_done + try my_test.row_done.appendNTimes(false, 4); + try my_test.col_done.appendNTimes(false, 5); + + try my_test.approximate(); +} diff --git a/Task/Wagstaff-primes/Agena/wagstaff-primes.agena b/Task/Wagstaff-primes/Agena/wagstaff-primes.agena new file mode 100644 index 0000000000..b92fb35357 --- /dev/null +++ b/Task/Wagstaff-primes/Agena/wagstaff-primes.agena @@ -0,0 +1,36 @@ +scope # find some Wagstaff primes: primes of the form ( 2^p + 1 ) / 3 + # where p is an odd prime + local constant maxWagstaff := 10; # number of Wagstaff primes to find + local constant sieveSize := 200; # hopefully, enough primes... + create register primes( sieveSize ); # "vector" to be sieved + scope # sieve the primes up to sieveMax + primes[ 1 ] := false; + for sPos from 2 to sieveSize do primes[ sPos ] := true od; + for sPos from 2 to entier( sqrt( sieveSize ) ) do + if primes[ sPos ] then + for p from sPos * sPos to sieveSize by sPos do + primes[ p ] := false + od + fi + od + end; + scope # attempt to find the Wagstaff primes + local powerOf2 := 2; # 2^1 + local wCount := 0; # number of Wagstaff primes found so far + for p from 3 by 2 while wCount < maxWagstaff do + powerOf2 *:= 4; + if primes[ p ] then + local w, isPrime := ( powerOf2 + 1 ) \ 3, true; + # check w is prime - trial division + for n from 3 by 2 while n * n <= w and isPrime do + isPrime := w mod n <> 0; + od; + if isPrime then # have another Wagstaff prime + wCount +:= 1; + # have to use %f to print w as it could be > 2^32 + printf( "%2d: %4d: %16.0f\n", wCount, p, w ) + fi + fi + od + end +end diff --git a/Task/Wagstaff-primes/Lua/wagstaff-primes.lua b/Task/Wagstaff-primes/Lua/wagstaff-primes.lua new file mode 100644 index 0000000000..cd4b7c668f --- /dev/null +++ b/Task/Wagstaff-primes/Lua/wagstaff-primes.lua @@ -0,0 +1,38 @@ +do -- find some Wagstaff primes primes of the form ( 2^p + 1 ) / 3 + -- where p is an odd prime + + local maxWagstaff = 10 -- number of Wagstaff primes to find + local sieveSize = 200 -- hopefully, enough primes... + local primes = {} + do -- sieve the primes up to sieveMax + primes[ 1 ] = false + for sPos = 2, sieveSize do primes[ sPos ] = true end + for sPos = 2, math.floor( math.sqrt( sieveSize ) ) do + if primes[ sPos ] then + for p = sPos * sPos, sieveSize, sPos do + primes[ p ] = false + end + end + end + end + do -- attempt to find the Wagstaff primes + local powerOf2 = 2 -- 2^1 + local wCount = 0 -- number of Wagstaff primes found so far + for p = 3, sieveSize, 2 do + if wCount >= maxWagstaff then break end + powerOf2 = powerOf2 * 4 + if primes[ p ] then + local w, isPrime = ( powerOf2 + 1 ) // 3, true + -- check w is prime - trial division + for n = 3, w, 2 do + if n * n > w or not isPrime then break end + isPrime = w % n ~= 0 + end + if isPrime then -- have another Wagstaff prime + wCount = wCount + 1 + io.write( string.format( "%2d %4d: %16d\n", wCount, p, w ) ) + end + end + end + end +end diff --git a/Task/Wagstaff-primes/Pluto/wagstaff-primes.pluto b/Task/Wagstaff-primes/Pluto/wagstaff-primes.pluto new file mode 100644 index 0000000000..df8b96236d --- /dev/null +++ b/Task/Wagstaff-primes/Pluto/wagstaff-primes.pluto @@ -0,0 +1,40 @@ +do -- find some Wagstaff primes primes of the form ( 2^p + 1 ) / 3 + -- where p is an odd prime + + local fmt = require( "fmt" ) -- RC formatting library + + local maxWagstaff = 10 -- number of Wagstaff primes to find + local sieveSize = 200 -- hopefully, enough primes... + local primes = {} + do -- sieve the primes up to sieveMax + primes[ 1 ] = false + for sPos = 2, sieveSize do primes[ sPos ] = true end + for sPos = 2, math.floor( math.sqrt( sieveSize ) ) do + if primes[ sPos ] then + for p = sPos * sPos, sieveSize, sPos do + primes[ p ] = false + end + end + end + end + do -- attempt to find the Wagstaff primes + local powerOf2 = 2 -- 2^1 + local wCount = 0 -- number of Wagstaff primes found so far + for p = 3, sieveSize, 2 do + if wCount >= maxWagstaff then break end + powerOf2 *= 4 + if primes[ p ] then + local w, isPrime = ( powerOf2 + 1 ) // 3, true + -- check w is prime - trial division + for n = 3, w, 2 do + if n * n > w or not isPrime then break end + isPrime = w % n != 0 + end + if isPrime then -- have another Wagstaff prime + ++ wCount + fmt.write( "%2d %4d: %16d\n", wCount, p, w ) + end + end + end + end +end diff --git a/Task/Wagstaff-primes/Ring/wagstaff-primes.ring b/Task/Wagstaff-primes/Ring/wagstaff-primes.ring new file mode 100644 index 0000000000..d80dc80eb3 --- /dev/null +++ b/Task/Wagstaff-primes/Ring/wagstaff-primes.ring @@ -0,0 +1,12 @@ +load "stdlib.ring" + +flag = 0 +p = 3 +while flag < 10 + m=(pow(2,p)+1)/3 + if isPrime(m) and isPrime(p) and p%2=1 + see "p = " + p +", " + "m = " + m + nl + flag++ + ok + p = p + 2 +end diff --git a/Task/War-card-game/Rust/war-card-game.rs b/Task/War-card-game/Rust/war-card-game.rs new file mode 100644 index 0000000000..a128b9e6a1 --- /dev/null +++ b/Task/War-card-game/Rust/war-card-game.rs @@ -0,0 +1,110 @@ +use rand::seq::SliceRandom; +use rand::thread_rng; + +const SUITS: [&str; 4] = ["♣", "♦", "♥", "♠"]; +const FACES: [&str; 13] = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]; + +struct Card { + display: String, + rank: usize, +} + +impl Card { + fn new(index: usize) -> Self { + let face = FACES[index % 13]; + let suit = SUITS[index / 13]; + Card { + display: format!("{}{}", face, suit), + rank: index % 13, + } + } +} + +fn war() { + // Create and shuffle deck + let mut deck: Vec = (0..52).collect(); + deck.shuffle(&mut thread_rng()); + + // Deal cards to players (reversing order to match Go implementation) + let mut hand1: Vec = Vec::with_capacity(52); + let mut hand2: Vec = Vec::with_capacity(52); + + for i in 0..26 { + hand1.push(deck[2 * i]); + hand2.push(deck[2 * i + 1]); + } + hand1.reverse(); + hand2.reverse(); + + // Create cards lookup + let cards: Vec = (0..52).map(Card::new).collect(); + + while !hand1.is_empty() && !hand2.is_empty() { + let card1 = hand1.remove(0); + let card2 = hand2.remove(0); + + let mut played1 = vec![card1]; + let mut played2 = vec![card2]; + let mut num_played = 2; + + let mut current_card1 = card1; + let mut current_card2 = card2; + + loop { + print!("{}\t{}\t", cards[current_card1].display, cards[current_card2].display); + + if cards[current_card1].rank > cards[current_card2].rank { + hand1.extend(played1); + hand1.extend(played2); + println!("Player 1 takes the {} cards. Now has {}.", num_played, hand1.len()); + break; + } else if cards[current_card1].rank < cards[current_card2].rank { + hand2.extend(played2); + hand2.extend(played1); + println!("Player 2 takes the {} cards. Now has {}.", num_played, hand2.len()); + break; + } else { + println!("War!"); + + if hand1.len() < 2 { + println!("Player 1 has insufficient cards left."); + hand2.extend(played2); + hand2.extend(played1); + hand2.extend(hand1.drain(..)); + break; + } + + if hand2.len() < 2 { + println!("Player 2 has insufficient cards left."); + hand1.extend(played1); + hand1.extend(played2); + hand1.extend(hand2.drain(..)); + break; + } + + let fd_card1 = hand1.remove(0); // face down card + current_card1 = hand1.remove(0); // face up card + played1.push(fd_card1); + played1.push(current_card1); + + let fd_card2 = hand2.remove(0); // face down card + current_card2 = hand2.remove(0); // face up card + played2.push(fd_card2); + played2.push(current_card2); + + num_played += 4; + println!("? \t? \tFace down cards."); + } + } + } + + if hand1.len() == 52 { + println!("Player 1 wins the game!"); + } else { + println!("Player 2 wins the game!"); + } +} + +fn main() { + war(); +} diff --git a/Task/War-card-game/Zig/war-card-game.zig b/Task/War-card-game/Zig/war-card-game.zig new file mode 100644 index 0000000000..a305d37eee --- /dev/null +++ b/Task/War-card-game/Zig/war-card-game.zig @@ -0,0 +1,155 @@ +const std = @import("std"); +const print = std.debug.print; +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +const SUITS = [_][]const u8{ "♣", "♦", "♥", "♠" }; +const FACES = [_][]const u8{ "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A" }; + +const Card = struct { + display: [4]u8, + rank: usize, + + fn new(index: usize) Card { + const face = FACES[index % 13]; + const suit = SUITS[index / 13]; + + var display: [4]u8 = undefined; + // Copy face (1 byte) + display[0] = face[0]; + // Copy suit (3 bytes for Unicode symbols) + @memcpy(display[1..4], suit[0..3]); + + return Card{ + .display = display, + .rank = index % 13, + }; + } + + fn getDisplaySlice(self: *const Card) []const u8 { + return self.display[0..4]; + } +}; + +fn war(allocator: Allocator) !void { + // Create and shuffle deck + var deck = ArrayList(usize).init(allocator); + defer deck.deinit(); + + for (0..52) |i| { + try deck.append(i); + } + + // Shuffle deck + var prng = std.Random.DefaultPrng.init(blk: { + var seed: u64 = undefined; + std.posix.getrandom(std.mem.asBytes(&seed)) catch @panic("Failed to get random seed"); + break :blk seed; + }); + const random = prng.random(); + random.shuffle(usize, deck.items); + + // Deal cards to players (reversing order to match original implementation) + var hand1 = ArrayList(usize).init(allocator); + defer hand1.deinit(); + var hand2 = ArrayList(usize).init(allocator); + defer hand2.deinit(); + + try hand1.ensureTotalCapacity(52); + try hand2.ensureTotalCapacity(52); + + for (0..26) |i| { + try hand1.append(deck.items[2 * i]); + try hand2.append(deck.items[2 * i + 1]); + } + + // Reverse hands + std.mem.reverse(usize, hand1.items); + std.mem.reverse(usize, hand2.items); + + // Create cards lookup + var cards: [52]Card = undefined; + for (0..52) |i| { + cards[i] = Card.new(i); + } + + while (hand1.items.len > 0 and hand2.items.len > 0) { + const card1 = hand1.orderedRemove(0); + const card2 = hand2.orderedRemove(0); + + var played1 = ArrayList(usize).init(allocator); + defer played1.deinit(); + var played2 = ArrayList(usize).init(allocator); + defer played2.deinit(); + + try played1.append(card1); + try played2.append(card2); + var num_played: usize = 2; + + var current_card1 = card1; + var current_card2 = card2; + + while (true) { + print("{s}\t{s}\t", .{cards[current_card1].getDisplaySlice(), cards[current_card2].getDisplaySlice()} ); + + if (cards[current_card1].rank > cards[current_card2].rank) { + try hand1.appendSlice(played1.items); + try hand1.appendSlice(played2.items); + print("Player 1 takes the {} cards. Now has {}.\n", .{ num_played, hand1.items.len }); + break; + } else if (cards[current_card1].rank < cards[current_card2].rank) { + try hand2.appendSlice(played2.items); + try hand2.appendSlice(played1.items); + print("Player 2 takes the {} cards. Now has {}.\n", .{ num_played, hand2.items.len }); + break; + } else { + print("War!\n", .{}); + + if (hand1.items.len < 2) { + print("Player 1 has insufficient cards left.\n", .{}); + try hand2.appendSlice(played2.items); + try hand2.appendSlice(played1.items); + try hand2.appendSlice(hand1.items); + hand1.clearRetainingCapacity(); + break; + } + + if (hand2.items.len < 2) { + print("Player 2 has insufficient cards left.\n", .{}); + try hand1.appendSlice(played1.items); + try hand1.appendSlice(played2.items); + try hand1.appendSlice(hand2.items); + hand2.clearRetainingCapacity(); + break; + } + + const fd_card1 = hand1.orderedRemove(0); // face down card + current_card1 = hand1.orderedRemove(0); // face up card + try played1.append(fd_card1); + try played1.append(current_card1); + + const fd_card2 = hand2.orderedRemove(0); // face down card + current_card2 = hand2.orderedRemove(0); // face up card + try played2.append(fd_card2); + try played2.append(current_card2); + + num_played += 4; + print("? \t? \tFace down cards.\n" , .{}); + } + } + } + + if (hand1.items.len == 52) { + print("Player 1 wins the game!\n", .{}); + } else { + print("Player 2 wins the game!\n", .{}); + } +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + try war(allocator); +} diff --git a/Task/Web-scraping/REBOL/web-scraping.rebol b/Task/Web-scraping/REBOL/web-scraping.rebol index 0ff410d319..d8290431d1 100644 --- a/Task/Web-scraping/REBOL/web-scraping.rebol +++ b/Task/Web-scraping/REBOL/web-scraping.rebol @@ -1,4 +1,4 @@ -REBOL [ +Rebol [ Title: "Web Scraping" URL: http://rosettacode.org/wiki/Web_Scraping ] diff --git a/Task/Wieferich-primes/Agena/wieferich-primes.agena b/Task/Wieferich-primes/Agena/wieferich-primes.agena new file mode 100644 index 0000000000..00675721a2 --- /dev/null +++ b/Task/Wieferich-primes/Agena/wieferich-primes.agena @@ -0,0 +1,37 @@ +scope # find some Wierferich Primes: primes p where p^2 evenly divides 2^(p-1)-1 + + import mapm; # explicit import needed for: Linux, Mac OS X, Windows and Solaris + + local constant maxNumber := 5000; # maximum number we will consider + mapm.xdigits( 1600 ); # need 1600 digits for this task + + # sieve the primes up to maxNumber + local primes; create register primes( maxNumber ); + primes[ 1 ] := false; + for sPos from 2 to maxNumber do primes[ sPos ] := true od; + for sPos from 2 to entier( sqrt( maxNumber ) ) do + if primes[ sPos ] then + for p from sPos * sPos to maxNumber by sPos do + primes[ p ] := false + od + fi + od; + + # find the first two Wierferich Primes - note 2 is not a Wierferich prime + local constant b0, constant b1 := mapm.xnumber( 0 ), mapm.xnumber( 1 ); + local pPos, twoToPMinus1, power, wCount := 1, b1, 0, 0; + for pPos from 3 to size primes by 2 while wCount < 2 do + if primes[ pPos ] then + local constant p := pPos; + while power < ( p - 1 ) do + twoToPMinus1 +:= twoToPMinus1; + power +:= 1 + od; + local constant p2 := p * p; + if ( twoToPMinus1 - b1 ) % p2 = b0 then + printf( " %d", p ) + wCount +:= 1 + fi + fi + od +end diff --git a/Task/Wieferich-primes/Common-Lisp/wieferich-primes.lisp b/Task/Wieferich-primes/Common-Lisp/wieferich-primes.lisp new file mode 100644 index 0000000000..92b26e39ca --- /dev/null +++ b/Task/Wieferich-primes/Common-Lisp/wieferich-primes.lisp @@ -0,0 +1,35 @@ +(defun modpow (base exp mod) + (cond ((= mod 1) 0) + (t (do ((base (mod base mod) (mod (* base base) mod)) + (exp exp (ash exp -1)) + (result 1 (cond ((= (logand exp 1) 1) (mod (* result base) mod)) + (t result)))) + ((zerop exp) result))))) + +(defun primes-upto (limit) + (let ((sieve (make-array limit :element-type 'boolean :initial-element t))) + (when (plusp limit) (setf (svref sieve 0) nil)) + (when (> limit 1) (setf (svref sieve 1) nil)) + (loop for i from 4 below limit by 2 + do (setf (svref sieve i) nil)) + (loop for p = 3 then (+ p 2) + for q = (expt p 2) + while (< q limit) + when (aref sieve p) + do (loop with incr = (* 2 p) + while (< q limit) + do (setf (svref sieve q) nil) + (incf q incr))) + sieve)) + +(defun wieferich-primes-upto (limit) + (loop with sieve = (primes-upto limit) + for p from 3 below limit by 2 + when (and (svref sieve p) (= (modpow 2 (1- p) (expt p 2)) 1)) + collect p)) + +(defparameter *check-upto-limit* 5000) + +(format t "Wieferich primes less than ~a:~%~{~a~%~}" + *check-upto-limit* + (wieferich-primes-upto *check-upto-limit*)) diff --git a/Task/Wieferich-primes/Lua/wieferich-primes.lua b/Task/Wieferich-primes/Lua/wieferich-primes.lua new file mode 100644 index 0000000000..dd781ad0c8 --- /dev/null +++ b/Task/Wieferich-primes/Lua/wieferich-primes.lua @@ -0,0 +1,48 @@ +function prime_sieve(limit) + local sieve = {} + for i = 2, limit do sieve[i] = true end + if limit > 1 then sieve[1] = false end + for i = 4, limit, 2 do sieve[i] = false end + local p = 3 + while true do + local q = p * p + if q > limit then break end + if sieve[p] then + local incr = 2 * p + for r = q, limit, incr do + sieve[r] = false + end + end + p = p + 2 + end + return sieve +end + +function modpow(base, exp, mod) + if mod == 1 then return 0 end + local result = 1 + base = base % mod + while exp > 0 do + if (exp & 1) == 1 then + result = (result * base) % mod + end + base = (base * base) % mod + exp = exp >> 1 + end + return result +end + +function wieferich_primes(limit) + local result = {} + local sieve = prime_sieve(limit) + for p = 2, limit do + if sieve[p] and modpow(2, p - 1, p * p) == 1 then + table.insert(result, p) + end + end + return result +end + +local limit = 5000 +print('Wieferich primes less than ' .. limit .. ':') +print(table.unpack(wieferich_primes(limit))) diff --git a/Task/Wieferich-primes/Pluto/wieferich-primes.pluto b/Task/Wieferich-primes/Pluto/wieferich-primes.pluto new file mode 100644 index 0000000000..7b587f9dbe --- /dev/null +++ b/Task/Wieferich-primes/Pluto/wieferich-primes.pluto @@ -0,0 +1,24 @@ +do -- find some Wierferich Primes: primes p where p^2 evenly divides 2^(p-1)-1 + + local bigint = require( "pluto:bigint" ) -- standard Pluto big integers + local int = require( "int" ) -- RC integer module, includes some prime utilities + local maxNumber = 5000 -- maximum number we will consider + local primeList = int.primes( maxNumber ) -- get a list of primes up to maxNumber + + -- find the first two Wierferich Primes + local b0 , b1 = new bigint( 0 ), new bigint( 1 ) + local pPos, twoToPMinus1, power, wCount = 1, b1, 0, 0 + for primeList as p do + if wCount == 2 then break end + while power < ( p - 1 ) do + twoToPMinus1 += twoToPMinus1 + power += 1 + end + local p2 = new bigint( p * p ) + if ( twoToPMinus1 - b1 ) % p2 == b0 then + io.write( " ", p ) + wCount += 1 + end + pPos += 1 + end +end diff --git a/Task/Wieferich-primes/R/wieferich-primes.r b/Task/Wieferich-primes/R/wieferich-primes.r new file mode 100644 index 0000000000..8588c0ab60 --- /dev/null +++ b/Task/Wieferich-primes/R/wieferich-primes.r @@ -0,0 +1,10 @@ +library(gmp) + +is_wieferich <- function(p){ + p_big <- as.bigz(p) + (2^(p_big-1)-1)%%(p_big^2)==0 +} + +primes <- which(isprime(1:5000)!=0) + +primes[is_wieferich(primes)] diff --git a/Task/Window-creation/TAV/window-creation.tav b/Task/Window-creation/TAV/window-creation.tav new file mode 100644 index 0000000000..1f031b2e6d --- /dev/null +++ b/Task/Window-creation/TAV/window-creation.tav @@ -0,0 +1,9 @@ +main (args):+ + GTK init args + win =: new GTK window \ currently only top-level + win::set title "Hello GTK" + win::set size 200, 100 + win::connect 'destroy' to `GTK main quit` + win::show all + GTK main win +\+ ./TAVPL_gtk.tavh diff --git a/Task/Wireworld/Prolog/wireworld.pro b/Task/Wireworld/Prolog/wireworld.pro new file mode 100644 index 0000000000..a3bfa8b5cb --- /dev/null +++ b/Task/Wireworld/Prolog/wireworld.pro @@ -0,0 +1,69 @@ +:- initialization(main, main). +:- set_prolog_flag(double_quotes, codes). +:- use_module(library(ansi_term), [ansi_format/3]). +:- use_module(library(dcg/basics), [blanks/2, eol/2, eos/2, string_without/4]). +:- use_module(library(dcg/high_order), [optional/4, sequence/4]). + +grid(Grid) --> sequence(row, Grid), blanks. +row(Row) --> string_without("\n", Row), { Row \= [] }, eol. + +:- meta_predicate maplist_with_nth0(3, +, -). +maplist_with_nth0(Goal, List0, List) :- + length(List0, Length), + succ(LastIndex, Length), + numlist(0, LastIndex, N0s), + maplist(Goal, N0s, List0, List). + +:- meta_predicate map_grid0(3, +, -). +map_grid0(Goal, Grid0, Grid) :- + maplist_with_nth0({Goal}/[Y, Row0, Row] >> ( + maplist_with_nth0({Goal, Y}/[X, T0, T] >> ( + call(Goal, yx(Y, X), T0, T) + ), Row0, Row) + ), Grid0, Grid). + +yxth0(yx(Y, X)) --> nth0(Y), nth0(X). + +moore_neighbourhood(yx(Y0, X0), yx(Y, X)) :- succ(Y0, Y), ( succ(X, X0) ; X = X0 ; succ(X0, X) ). +moore_neighbourhood(yx(Y, X0), yx(Y, X)) :- succ(X, X0) ; succ(X0, X). +moore_neighbourhood(yx(Y0, X0), yx(Y, X)) :- succ(Y, Y0), ( succ(X, X0) ; X = X0 ; succ(X0, X) ). + +transition(_, _, 0' , 0' ) :- !. +transition(_, _, 0'H, 0't) :- !. +transition(_, _, 0't, 0'.) :- !. +transition(Grid, Here, 0'., State) :- + aggregate_all(count, ( + moore_neighbourhood(Here, There), + yxth0(There, Grid, 0'H) + ), AdjacentHeads), + ( between(1, 2, AdjacentHeads) + -> State = 0'H + ; State = 0'. + ). + +char_attributes(0'., [bg(yellow)]). +char_attributes(0' , []). +char_attributes(0't, [bg(red)]). +char_attributes(0'H, [bg(blue)]). + +display(Grid) :- + maplist([Row] >> ( + maplist([Char] >> ( + char_attributes(Char, Attributes), + ansi_format(Attributes, "~c", [Char]) + ), Row), + nl + ), Grid). + +simulate(Grid0) :- + map_grid0(transition(Grid0), Grid0, Grid), + display(Grid), + sleep(0.25), + length(Grid, Height), + format("\e[~dA", [Height]), + simulate(Grid). + +main([Filename]) :- + format("Welcome to WireWorld! Press ^C to exit.~n~n", []), + once(phrase_from_file(grid(Grid), Filename)), + simulate(Grid). diff --git a/Task/Word-frequency/TAV/word-frequency.tav b/Task/Word-frequency/TAV/word-frequency.tav new file mode 100644 index 0000000000..a5bc650348 --- /dev/null +++ b/Task/Word-frequency/TAV/word-frequency.tav @@ -0,0 +1,34 @@ +main (args):+ + wm =: count words "../les_mis_135-0.txt" + wr =: map wm as row descending value key pairs + ?# i =: from 1 upto max + print format '%6d; %s;' wr[i] \ wr[i] is a pair + +\ read the file and provide a map with all words and their count +count words (fn): + wl =: new map + ?# line =: file fn give lines + ?# word =: string line give words of #ASCIIletters + word =: string word case to lower + wl{word} =+ 1 \ count for word; void is zero for addition + wl.words =+ 1 \ count number of words + :> wl + +\ create a sorted row of pairs (count, word) +map (@) as row descending value key pairs: + rvk =: new row size @.Count + ?# k =: map @ give keys + rvk[] =: @{k}, k + row rvk sort fast descending + :> rvk + +\ not (yet) in library +string (@) give words of (chars): + $ =~ 1 \ start point + ?* $ <= @.Count + word =: string @ from $ many of chars + $ =+ word.Count + 1 \ skip following character + ? word ~= '' + :> word + $ =: () + :> () diff --git a/Task/Word-wheel/ALGOL-68/word-wheel.alg b/Task/Word-wheel/ALGOL-68/word-wheel.alg new file mode 100644 index 0000000000..f55627274d --- /dev/null +++ b/Task/Word-wheel/ALGOL-68/word-wheel.alg @@ -0,0 +1,36 @@ +STRING wheel = "ndeokgelw"; + +PROC check word = (STRING word, wheel)BOOL: + IF UPB word >= 3 AND UPB word <= UPB wheel THEN + STRING wh := wheel; + FOR i TO UPB word DO + CHAR ch = word[i]; + FOR j TO UPB wh DO + IF ch = wh[j] THEN + wh[j] := REPR 0; + continue + FI + OD; + return false; + continue: SKIP + OD; + IF wh[UPB wh % 2 + 1] /= REPR 0 THEN return false FI; + TRUE EXIT + return false: FALSE + ELSE + FALSE + FI; + +BEGIN + FILE f; + BOOL eof := FALSE; + open(f, "unixdict.txt", stand in channel); + on logical file end(f, (REF FILE f)BOOL: eof := TRUE); + WHILE ~eof DO + STRING word; + get(f, (word, new line)); + IF check word(word, wheel) THEN + print((word, new line)) + FI + OD +END diff --git a/Task/Word-wrap/FutureBasic/word-wrap.basic b/Task/Word-wrap/FutureBasic/word-wrap.basic new file mode 100644 index 0000000000..4effaec67d --- /dev/null +++ b/Task/Word-wrap/FutureBasic/word-wrap.basic @@ -0,0 +1,59 @@ +CFArrayRef local fn WrapStringAtWordBoundaries( txtStr as CFStringRef, maxLineLength as NSUInteger ) + CFMutableArrayRef lines = fn MutableArrayNew + ScannerRef scanner = fn ScannerWithString( txtStr ) + CFMutableStringref currentLine = fn MutableStringNew + CFStringRef wordStr + ScannerSetCharactersToBeSkipped( scanner, NULL ) + + while ( fn ScannerIsAtEnd( scanner ) == NO ) + fn ScannerScanUpToCharactersFromSet( scanner, fn CharacterSetWhitespaceAndNewlineSet, @wordStr ) + + if ( wordStr ) + if ( ( len( currentLine ) + len( wordStr ) + 1 ) > maxLineLength ) + if ( len( currentLine ) > 0 ) + MutableArrayAddObject( lines, fn StringWithString( currentLine ) ) + MutableStringSetString( currentLine, @"" ) // Reset the line + end if + end if + if ( len( currentLine ) > 0 ) + MutableStringAppendString( currentLine, @" " ) + end if + MutableStringAppendString( currentLine, wordStr ) + end if + fn ScannerScanCharactersFromSet( scanner, fn CharacterSetWhitespaceAndNewlineSet, NULL ) // Skip over whitespace between words + wend + + if ( len( currentLine ) > 0 ) + MutableArrayAddObject( lines, fn StringWithString( currentLine ) ) + end if + + return lines +end fn = NULL + + +CFStringRef txtStr +txtStr = @"In olden times when wishing still helped one, there lived a king ¬ +whose daughters were all beautiful, but the youngest was so beautiful ¬ +that the sun itself, which has seen so much, was astonished whenever ¬ +it shone-in-her-face. Close by the king's castle lay a great dark ¬ +forest, and under an old lime-tree in the forest was a well, and when ¬ +the day was very warm, the king's child went out into the forest and ¬ +sat down by the side of the cool-fountain, and when she was bored she ¬ +took a golden ball, and threw it up on high and caught it, and this ¬ +ball was her favorite plaything." + +CFStringRef columnizedStr + +// Create wrapping lines respecting word boundaries + +print @"Wrapped at 20 characters:" +columnizedStr = fn ArrayComponentsJoinedByString( fn WrapStringAtWordBoundaries( txtStr, 20 ), @"\n" ) +print columnizedStr + +print + +print @"Wrapped at 80 characters:" +columnizedStr = fn ArrayComponentsJoinedByString( fn WrapStringAtWordBoundaries( txtStr, 80 ), @"\n" ) +print columnizedStr + +HandleEvents diff --git a/Task/Write-entire-file/ArkScript/write-entire-file.ark b/Task/Write-entire-file/ArkScript/write-entire-file.ark new file mode 100644 index 0000000000..2388fe93e8 --- /dev/null +++ b/Task/Write-entire-file/ArkScript/write-entire-file.ark @@ -0,0 +1 @@ +(io:writeFile "output.txt" "hello, world!") diff --git a/Task/Write-entire-file/Frink/write-entire-file.frink b/Task/Write-entire-file/Frink/write-entire-file.frink index 9a4b9aa562..5d2fadce34 100644 --- a/Task/Write-entire-file/Frink/write-entire-file.frink +++ b/Task/Write-entire-file/Frink/write-entire-file.frink @@ -1,3 +1 @@ -w = new Writer["test.txt"] -w.print["I am the captain now."] -w.close[] +w = new Writer["test.txt"].printAndClose["I am the captain now."] diff --git a/Task/Write-entire-file/Odin/write-entire-file.odin b/Task/Write-entire-file/Odin/write-entire-file.odin index 0b13d18a2a..e9ef5612e4 100644 --- a/Task/Write-entire-file/Odin/write-entire-file.odin +++ b/Task/Write-entire-file/Odin/write-entire-file.odin @@ -2,10 +2,19 @@ package main import "core:fmt" import "core:os" -import "core:c/libc" + main :: proc() { - dummy := "henlo" - succ:= os.write_entire_file("file",transmute([]u8)(dummy),false) + dummy := "This is a string." + write := os.write_entire_file("file",transmute([]u8)(dummy),false) + + // Returns an error + write2 := os.write_entire_file_or_err("file2",transmute([]u8)(dummy),false) + + // If error than do something + if (write2!=nil){ + fmt.println("err") + } + } diff --git a/Task/Write-entire-file/R/write-entire-file.r b/Task/Write-entire-file/R/write-entire-file.r new file mode 100644 index 0000000000..1e6d5a4378 --- /dev/null +++ b/Task/Write-entire-file/R/write-entire-file.r @@ -0,0 +1 @@ +writeLines(text="This is a string.", con="file.txt") diff --git a/Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys b/Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys new file mode 100644 index 0000000000..d94adce73d --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/YAMLScript/xiaolin-wus-line-algorithm.ys @@ -0,0 +1,52 @@ +!YS-v0 + +defn main(): + draw-line: 0 1 10 2 + +defn draw-line(x0 y0 x1 y1): + plot x0 x1 y0 y1 =: + if abs(y1 - y0) > abs(x1 - x0): + + [\(plot(y0 x0 x1)) y0 x0 y1 x1] + [plot x0 x1 y0 y1] + + x0 x1 y0 y1 =: + if x0 > x1: + + [x1 x0 y1 y0] + [x0 x1 y0 y1] + + dx =: x1 - x0 + dy =: y1 - y0 + gradient =: dy / dx + + intery xends =: + loop intery 0, xends [], [[x y] *xys] [[x0 y0] [x1 y1]]: + xend =: round(x) + yend =: y + (gradient * (xend - x)) + xgap =: rfpart(x + 0.5) + + x-pixel =: xend + y-pixel =: yend:to-int + xends =: xends.conj(x-pixel) + + plot: x-pixel y-pixel (rfpart(yend) * xgap) + plot: x-pixel y-pixel.++ (fpart(yend) * xgap) + intery |||=: yend + gradient + + if xys.?: + recur: intery, xends, xys + vector: intery, xends + + loop intery intery, [x *xs] (xends.0.++ .. xends.1.--): + plot: x intery:I rfpart(intery) + plot: x intery:I.++ fpart(intery) + when xs.?: + recur (intery + gradient): xs + +defn plot(x y c): + when c != 0.0: + say: + format 'plot %d %d %.1f': x y c:F + +defn fpart(x): x - x:to-int + +defn rfpart(x): 1 - fpart(x) diff --git a/Task/Y-combinator/Pluto/y-combinator.pluto b/Task/Y-combinator/Pluto/y-combinator.pluto new file mode 100644 index 0000000000..88cd0c6519 --- /dev/null +++ b/Task/Y-combinator/Pluto/y-combinator.pluto @@ -0,0 +1,14 @@ +local function y(f) + local g = |r| -> f(|x| -> r(r)(x)) + return g(g) +end + +local almost_fac = |f| -> (|x| -> x <= 1 ? 1 : x * f(x - 1)) + +local almost_fib = |f| -> (|x| -> x <= 2 ? 1 : f(x - 1) + f(x - 2)) + +local fac = y(almost_fac) +local fib = y(almost_fib) + +print($"fac(10) = {fac(10)}") +print($"fib(10) = {fib(10)}") diff --git a/Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena b/Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena new file mode 100644 index 0000000000..d02ca7f5e5 --- /dev/null +++ b/Task/Yellowstone-sequence/Agena/yellowstone-sequence.agena @@ -0,0 +1,27 @@ +scope # Yellowstone sequence - translation of the Pluto sample + + local procedure yellowstone( n :: number ) :: table + local a, m := [ 1, 2, 3 ], [ true, true, true ]; + for x from 4 to n do + a[ x ], m[ x ] := 0, false + od; + local minV := 4; + for c from 4 to n do + local more := true + for i from minV while more do + if not m[ i ] and numtheory.gcd( a[ c - 1 ], i ) = 1 and numtheory.gcd( a[ c - 2 ], i ) > 1 + then + a[ c ], m[ i ] := i, true; + if i = minV then minV +:= 1 fi; + more := false + fi + od + od; + return a + end; + + local constant ySize, constant perLine := 30, 10; + local y := yellowstone( ySize ); + printf( "The first %d Yellowstone numbers are:\n", ySize ); + for yPos to ySize do printf( " %2d", y[ yPos ] ); if yPos mod perLine = 0 then print() fi od +end diff --git a/Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel b/Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel new file mode 100644 index 0000000000..88b0486ee1 --- /dev/null +++ b/Task/Yellowstone-sequence/Fennel/yellowstone-sequence.fennel @@ -0,0 +1,45 @@ +(do ;;; Yellowstone sequence - translation of the Pluto sample + + (fn gcd [m n] + (var (a b) (values (math.abs m) (math.abs n))) + (while (not= b 0) + (set (b a) (values (% a b) b)) + ) + a + ) + + (fn yellowstone [n] + (var (a m) (values [1 2 3] [true true true])) + (for [x 4 n] + (tset a x 0) + (tset m x false) + ) + (var minV 4) + (for [c 4 n] + (var (more i) (values true minV)) + (while more + (when (and (not (. m i)) + (= (gcd (. a (- c 1)) i) 1) + (> (gcd (. a (- c 2)) i) 1) + ) + (tset a c i) + (tset m i true) + (when (= i minV) + (set minV (+ 1 minV)) + ) + (set more false) + ) + (set i (+ i 1)) + ) + ) + a + ) + + (local (ySize perLine) (values 30 10)) + (local y (yellowstone ySize)) + (io.write (string.format "The first %d Yellowstone numbers are:\n" ySize)) + (for [yPos 1 ySize] + (io.write (string.format " %2d" (. y yPos))) + (when (= 0 (% yPos perLine)) (print)) + ) +) diff --git a/Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic b/Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic new file mode 100644 index 0000000000..74da99ae02 --- /dev/null +++ b/Task/Yellowstone-sequence/FutureBasic/yellowstone-sequence.basic @@ -0,0 +1,33 @@ +include "NSLog.incl" + +NSInteger local fn GCD( a as NSInteger, b as NSInteger ) + if ( a == 0 ) then return b + return fn GCD( b % a, a ) +end fn = 0 + +void local fn CalcYellowstoneSequence( terms as int ) + CFMutableArrayRef sequence = fn MutableArrayWithObjects( @1, @2, @3, NULL ) + + for int n = 3 to terms - 1 + NSInteger prev1 = fn NumberIntegerValue( fn ArrayObjectAtIndex( sequence, n - 1 ) ) + NSInteger prev2 = fn NumberIntegerValue( fn ArrayObjectAtIndex( sequence, n - 2 ) ) + NSInteger candidate = 1 + + while (YES) + if ( !fn ArrayContainsObject( sequence, @(candidate) ) && fn GCD( candidate, prev1 ) == 1 && fn GCD( candidate, prev2 ) > 1 ) + MutableArrayAddObject( sequence, @(candidate) ) + break + end if + candidate++ + wend + next + + NSLog( @"Yellowstone sequence up to %d terms:", terms ) + for CFNumberRef num in sequence + NSLog( @"%@ \b", num ) + next +end fn + +fn CalcYellowstoneSequence( 30 ) + +HandleEvents diff --git a/Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto b/Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto new file mode 100644 index 0000000000..74f3cd66f5 --- /dev/null +++ b/Task/Yellowstone-sequence/Pluto/yellowstone-sequence.pluto @@ -0,0 +1,32 @@ +require "table2" +local int = require "int" +local fmt = require "fmt" + +local function yellowstone(n) + local m = {} + local a = table.rep(n, 0) + for i = 1, 3 do + a[i] = i + m[i] = true + end + local min = 4 + for c = 4, n do + local i = min + while true do + if !m[i] and int.gcd(a[c - 1], i) == 1 and int.gcd(a[c - 2], i) > 1 then + a[c] = i + m[i] = true + if i == min then ++min end + break + end + ++i + end + end + return a +end + +local x = {} +for i = 1, 30 do x[i] = i end +local y = yellowstone(30) +print("The first 30 Yellowstone numbers are:") +fmt.tprint("%2d ", y, 10) diff --git a/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx b/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx index de391c503f..364dc133fd 100644 --- a/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx +++ b/Task/Yellowstone-sequence/REXX/yellowstone-sequence.rexx @@ -1,4 +1,4 @@ --- 25 Apr 2025 +-- 28 Jul 2025 include Settings numeric digits 100 arg xx @@ -14,7 +14,7 @@ call Timer exit GetYellow: -procedure expose yell. work. +procedure expose yell. work. Memo. arg xx say 'Get yellowstones...' yell. = 0; work. = 0; n = 0 @@ -50,7 +50,4 @@ end say return -include Sequences -include Functions -include Helper -include Abend +include Math diff --git a/Task/Yellowstone-sequence/YAMLScript/yellowstone-sequence.ys b/Task/Yellowstone-sequence/YAMLScript/yellowstone-sequence.ys new file mode 100644 index 0000000000..313b8c66f7 --- /dev/null +++ b/Task/Yellowstone-sequence/YAMLScript/yellowstone-sequence.ys @@ -0,0 +1,24 @@ +!YS-v0 + +defn main(n=30): + say: yellow(n) + +defn yellow(n): + a =: +[1 2 3] + b =: (1 .. 3).zipmap([true]:cycle) + i =: 4 + loop a a, b b, i i: + if n > a.#: + ? if b.$i.! && + (i.gcd(a.$) == 1) && + (i.gcd(a:butlast.$) > 1) + : recur: + a.conj(i), b.assoc(i true), 5 + recur: a, b, i.++ + =>: a + +defn gcd(a b): + loop a a, b b: + if b.?: + recur b: a % b + else: a diff --git a/Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic b/Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic new file mode 100644 index 0000000000..9853f130be --- /dev/null +++ b/Task/Zebra-puzzle/FutureBasic/zebra-puzzle.basic @@ -0,0 +1,266 @@ +/* + + Z E B R A P U Z Z L E + Based on Phix logic + FutureBasic 7.0.34, August 2025 R.W. + +*/ + +/*-------------------------------------------------------------------- + There are five houses... +---------------------------------------------------------------------- +// The green house is immediately to the left of the white house +// The Norwegian lives in the first house +// The English man lives in the red house +// The Norwegian lives next to the blue house +// The Dane drinks tea +// They drink coffee in the green house +// In the middle house they drink milk +// In the yellow house they smoke Dunhill +// The German smokes Prince +// The man who smokes Blue Master drinks beer +// They drink water in a house next to the house where they smoke Blend +// The Swede has a dog +// The man who smokes Pall Mall has birds +// The man who smokes Blend lives in the house next to the house with cats +// In a house next to the house where they have a horse, +// they smoke Dunhill +// +// Task: Who owns the zebra? +*/ +// Enumerate based on the data given +// in the puzzle (5 variables for each group) + +Begin Enum 1 // drinks + _tea + _coffee + _milk + _beer + _water +End Enum + +Begin Enum 1 // nationalities + _English + _Swede + _Dane + _Norwegian + _German +End Enum + +Begin Enum 1 // house colors + _red + _white + _green + _yellow + _blue +End Enum + +Begin Enum 1 // smokes + _PallMall + _Dunhill + _Blend + _BlueMaster + _Prince +End Enum + +Begin Enum 1 // animals + _dog + _birds + _cats + _horse + _zebra +End Enum + +// Since we have 5 variables, the total permutation/combo +// would be 5! (5 factorial) which is 120 + +Int gPermutation(120, 5) // 120 combinations +Int gNumbers(5) // of 1 to 5 +Int gPermCount +Int factorial5 = 120 // value of 5! +Int entry, ns, ic +Int color, nationality, drink, smoke, pet // 5 groups + +// Since we used assigned numbers, we need this to +// show the equivalent description + +CFStringRef Colors(5) = {@"Houses",@"red",@"white",¬ +@"green",@"yellow",@"blue"} +CFStringRef Nationalities(5) = {@"Nationalities",@"English",@"Swede",¬ +@"Dane",@"Norwegian",@"German"} +CFStringRef Smokes(5) = {@"Smokes",@"Pall Mall",@"Dunhill",¬ +@"Blend",@"Blue Master",@"Prince"} +CFStringRef Drinks(5) = {@"Drinks",@"tea",@"coffee",¬ +@"milk",@"beer",@"water"} +CFStringRef Pets(5) = {@"Animals",@"dog",@"birds",¬ +@"cats",@"horse",@"zebra"} + +// Recursive permutation generator +local fn Permute( l as int, r as int ) + dim i as int + if l = r + for i = 1 to 5 + gPermutation(gPermCount, i) = gNumbers(i) + next + gPermCount++ + else + for i = l to r + swap gNumbers(l), gNumbers(i) + fn Permute( l + 1, r ) + swap gNumbers(l), gNumbers(i) + next + end if +end fn + +// +// Fill arrays of 5! permutations of 1 to 5 +local fn generatePermutations + int i + for i = 1 to 5: gNumbers(i) = i: next i + gPermCount = 1 + fn Permute( 1, 5 ) // Use 1-based index range +end fn + +// +// Pad spaces to width of "padTo" for output formatting +Local fn Pad(theString as CFStringRef, padTo as Int) as CFStringRef + theString = fn StringByReplacingOccurrencesOfString (theString, @"\"", @"" ) + if len(theString) < padTo then theString ¬ + = left( concat( theString, @" "), padTo ) + print theString; +end fn = theString + +// Find an entry in the permutation table +// c1 = index into gPermutation array +// v1 = the seek value +local fn find(c1 as Int, v1 as Int) as Int + Int h, i + h = 0 + for i = 1 to 5 + if gPermutation(c1,i) == v1 then h = i: i = 6: + next i +end fn = h + +// +// Left (as seen from the front) to location logic +local fn left_of(c1 as Int, v1 as Int, c2 as Int, v2 as Int) as Int + Int h, result + h = fn find(c1,v1) + result = (h <=4) && (gPermutation(c2,h + 1) == v2) +end fn = result + +// +// Is in the same house logic +local fn same_house(c1 as Int, v1 as Int, c2 as Int, v2 as Int) as Int + Int h, result + h = fn find(c1, v1) + result = (gPermutation(c2,h) == v2) +end fn = result + +// +// located next to logic +local fn next_to(c1 as Int, v1 as Int, c2 as Int, v2 as Int) as Int + Int h1, h2, result + h1 = fn find(c1, v1): h2 = fn find(c2, v2) + result = abs(h1-h2) == 1 +end fn = result + +//================================================================ +// Main + +window 1,@"Zebra puzzle" + +Int i, j +fn generatePermutations +// start the clock +CFTimeInterval t +t = fn CACurrentMediaTime +print + +for Color = 1 to factorial5 + ic++ + // The green house is immediately to the left of the white house + if fn left_of (Color, _green, Color, _white) + + for Nationality = 1 to factorial5 + ic++ + // The Norwegian lives in the first house and + // The English man lives in the red house and + // The Norwegian lives next to the blue house. + if gPermutation (Nationality,1) == _Norwegian && ¬ + fn same_house (Nationality, _English, Color, _red) && ¬ + fn next_to (Nationality, _Norwegian,Color, _blue) + + for drink = 1 to factorial5 + ic++ + // The Dane drinks tea and + // They drink coffee in the green house and + // In the middle house they drink milk + if fn same_house (Nationality, _Dane,drink, _tea) && ¬ + fn same_house (drink, _coffee, Color, _green) && ¬ + gPermutation (drink, 3) == _milk + + for smoke = 1 to factorial5 + ic++ + // In the yellow house they smoke Dunhill and + // The German smokes Prince and + // The man who smokes Blue Master drinks beer and + // They drink water in a house next to the house + // where they smoke Blend + if fn same_house (Color, _yellow, smoke, _Dunhill) && ¬ + fn same_house (Nationality, _German, smoke, _Prince) && ¬ + fn same_house (smoke, _BlueMaster, drink, _beer) && ¬ + fn next_to (drink, _water, smoke, _Blend) + + for pet = 1 to factorial5 + ic++ + // The Swede has a dog and + // The man who smokes Pall Mall has birds and + // The man who smokes Blend lives in the house next + // to the house with cats and + // In a house next to the house where they have a horse, + // they smoke Dunhill + if fn same_house (Nationality, _Swede, pet, _dog) && ¬ + fn same_house (smoke,_PallMall, pet, _birds) && ¬ + fn next_to (smoke,_Blend, pet, _cats) && ¬ + fn next_to (pet,_horse,smoke,_Dunhill) + + // stop the clock + printf @" Solved in = %.4f seconds", ¬ + (fn CACurrentMediaTime-t) + print + // Show the results + fn pad (@" HOUSE",11): fn pad (@"PERSON",11) + fn pad (@"DRINKS",8): fn pad (@"SMOKES",13) + fn pad (@"HAS",6) + print + print " ===============================================" + for i=1 to 5 + print " ";i;" "; + fn pad (Colors(gPermutation(color,i)),8) + fn pad (Nationalities(gPermutation(Nationality,i)),11) + fn pad (Drinks(gPermutation(drink,i)),8) + fn pad (Smokes(gPermutation(smoke,i)),13) + fn pad (Pets(gPermutation(pet,i)),8): print + if i == 5 then entry = i + next i + print + print " The ";Nationalities(entry);" owns the zebra." + ns += 1: print + print " ";ic;" combinations tested before finding a solution" + print " Solution found = ";ns; + if ns < 2 then print " (unique)" + end if //5 + next pet + end if //4 + next smoke + end if //3 + next drink + end if //2 + next nationality + end if //1 +next color +// +handleEvents + +// diff --git a/Task/Zebra-puzzle/J/zebra-puzzle-1.j b/Task/Zebra-puzzle/J/zebra-puzzle-1.j index b34c7f5f07..c7b7d82cdc 100644 --- a/Task/Zebra-puzzle/J/zebra-puzzle-1.j +++ b/Task/Zebra-puzzle/J/zebra-puzzle-1.j @@ -1,7 +1,7 @@ in=: {{n&{ i. m"_}} NB. index of m in row n of matrix F =: {{u"_1 # ]}} NB. filter by function of items 'Col Nat Pet Drink Cig'=: i.5 NB. refer to rows by name -'col nat pet drink cig'=: (A.~i.@!@#)&>;:'BGRWY DEGNS BCDHZ BCMTW BbDpP' NB. perm matrices +'col nat pet drink cig'=: (A.~i.@!@#)&>BGRWY`DEGNS`BCDHZ`BCMTW`BbDpP NB. perm matrices P=: ,/col,:"1/nat NB. join color and nationality matrices P=: ('W' in Col = 1+ 'G' in Col)F P NB. white right of green P=: (0 = 'N' in Nat)F P NB. Norwegian in first house diff --git a/Task/Zebra-puzzle/Pluto/zebra-puzzle.pluto b/Task/Zebra-puzzle/Pluto/zebra-puzzle.pluto new file mode 100644 index 0000000000..b4958e1aed --- /dev/null +++ b/Task/Zebra-puzzle/Pluto/zebra-puzzle.pluto @@ -0,0 +1,84 @@ +local fmt = require "fmt" +require "perm" + +local colors = {"Red", "Green", "White", "Yellow", "Blue"} +local nations = {"English", "Swede", "Danish", "Norwegian", "German"} +local animals = {"Dog", "Birds", "Cats", "Horse", "Zebra"} +local drinks = {"Tea", "Coffee", "Milk", "Beer", "Water"} +local smokes = {"Pall Mall", "Dunhill", "Blend", "Blue Master", "Prince"} + +local p = perm.list({1, 2, 3, 4, 5}) + +local function check(a1, a2, v1, v2) + for i = 1, 5 do + if p[a1][i] == v1 then return p[a2][i] == v2 end + end + return false +end + +local function check_left(a1, a2, v1, v2) + for i = 1, 4 do + if p[a1][i] == v1 then return p[a2][i + 1] == v2 end + end + return false +end + +local function check_right(a1, a2, v1, v2) + for i = 2, 5 do + if p[a1][i] == v1 then return p[a2][i - 1] == v2 end + end + return false +end + +local function check_adjacent(a1, a2, v1, v2) + return check_left(a1, a2, v1, v2) or check_right(a1, a2, v1, v2) +end + +local function print_houses(c, n, a, d, s) + local owner = "" + print("House Color Nation Animal Drink Smokes") + print("===== ====== ========= ====== ====== ===========") + for i = 1, 5 do + local f = "%3d %-6s %-9s %-6s %-6s %-11s" + local l = {i, colors[p[c][i]], nations[p[n][i]], animals[p[a][i]], drinks[p[d][i]], smokes[p[s][i]]} + fmt.print(f, l:unpack()) + if animals[p[a][i]] == "Zebra" then owner = nations[p[n][i]] end + end + print($"\nThe {owner} owns the Zebra\n") +end + +local function fill_houses() + local solutions = 0 + for c = 1, 120 do + if !check_left(c, c, 2, 3) then continue end -- C5 : Green left of white + for n = 1, 120 do + if p[n][1] != 4 then continue end -- C10: Norwegian in First + if !check(n, c, 1, 1) then continue end -- C2 : English in Red + if !check_adjacent(n, c, 4, 5) then continue end -- C15: Norwegian next to Blue + for a = 1, 120 do + if !check(a, n, 1, 2) then continue end -- C3 : Swede has Dog + for d = 1, 120 do + if p[d][3] != 3 then continue end -- C9 : Middle drinks Milk + if !check(d, n, 1, 3) then continue end -- C4 : Dane drinks Tea + if !check(d, c, 2, 2) then continue end -- C6 : Green drinks Coffee + for s = 1, 120 do + if !check(s, a, 1, 2) then continue end -- C7 : Pall Mall has Birds + if !check(s, c, 2, 4) then continue end -- C8 : Yellow smokes Dunhill + if !check(s, d, 4, 4) then continue end -- C13: Blue Master drinks Beer + if !check(s, n, 5, 5) then continue end -- C14: German smokes Prince + if !check_adjacent(s, a, 3, 3) then continue end -- C11: Blend next to Cats + if !check_adjacent(s, a, 2, 4) then continue end -- C12: Dunhill next to Horse + if !check_adjacent(s, d, 3, 5) then continue end -- C16: Blend next to Water + ++solutions + print_houses(c, n, a, d, s) + end + end + end + end + end + return solutions +end + +local solutions = fill_houses() +local plural = fmt.plural(solutions, "solution") +print($"{solutions} {plural} found") diff --git a/Task/Zero-to-the-zero-power/DuckDB/zero-to-the-zero-power.duckdb b/Task/Zero-to-the-zero-power/DuckDB/zero-to-the-zero-power.duckdb new file mode 100644 index 0000000000..f34db3edec --- /dev/null +++ b/Task/Zero-to-the-zero-power/DuckDB/zero-to-the-zero-power.duckdb @@ -0,0 +1 @@ + select power(0,0); diff --git a/Task/Zero-to-the-zero-power/Pluto/zero-to-the-zero-power.pluto b/Task/Zero-to-the-zero-power/Pluto/zero-to-the-zero-power.pluto new file mode 100644 index 0000000000..8b74d2a2b2 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Pluto/zero-to-the-zero-power.pluto @@ -0,0 +1 @@ +print(0^0) diff --git a/Task/Zero-to-the-zero-power/Prolog/zero-to-the-zero-power.pro b/Task/Zero-to-the-zero-power/Prolog/zero-to-the-zero-power.pro new file mode 100644 index 0000000000..ed03ed5312 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Prolog/zero-to-the-zero-power.pro @@ -0,0 +1 @@ +:- X is 0 ^ 0. diff --git a/Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb b/Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb new file mode 100644 index 0000000000..f14d59b037 --- /dev/null +++ b/Task/Zig-zag-matrix/DuckDB/zig-zag-matrix.duckdb @@ -0,0 +1,40 @@ +create or replace function zigzag_matrix(n) as table ( + with recursive cte as ( + select 1 as ix, 1 as i, 1 as j, 0 as ij + union all + select ix+1 as ix, + if( (i + j) % 2 = 0, + -- Even stripes + if( i < n, i + 1, i), + -- Odd stripes + if( j < n, i - (i > 1)::INT, i + 1) ) as i, + if( (i + j) % 2 == 0, + -- Even stripes + if( i < n, j - (j > 1)::INT, j + 1) , + -- Odd stripes + if( j < n, j+1, j)) as j, + ij + 1 as ij + from cte + where ix < n*n + ) + select i, j, ij as value + from cte +); + +# The i-th row as a list +create or replace function ijTable2Row(A, m) as ( + select array_agg(value order by j) + from query_table(A) + where i = m +); + +# Pretty-print the mxn matrix stored as an ij-table named A +create or replace function ijTable_pp(A,m,n) as table ( + select ijTable2Row(A,i) as row + from range(1, m+1) t(i) + order by i +); + +# Create the zig-zag matrix as a table and pretty-print it +with zz as (from zigzag_matrix(5)) +from ijTable_pp('zz', 5,5); diff --git a/Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys b/Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys new file mode 100644 index 0000000000..f1828e2882 --- /dev/null +++ b/Task/Zig-zag-matrix/YAMLScript/zig-zag-matrix.ys @@ -0,0 +1,34 @@ +!YS-v0 + +defn main(n=10): + gprint: + zig-zag: n + +defn gprint(grid): + f =: (" %$(grid.$.$.digits().#)d" * grid.#) + each line grid: + say: format(f line*) + +defn zig-zag(n): + take-from n: + map \(_1 _2) cycle([reverse a]): + partitions _ range(n:sqr): + concat (1 .. n): (n.-- .. -1) + +defn take-from(n colls): + lazy-seq: + when-let s seq(colls): + first-n rest-n =: split-at(n s) + cons map(first first-n): + take-from n: + concat _ rest-n: + filter seq: + map rest: first-n + +defn partitions(sizes coll): + lazy-seq: + when-let n sizes.0: + when-let s seq(coll): + cons take(n coll): + partitions next(sizes): + drop n: coll From cb74b7914d97249dc864ef86b7731495c230ef16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Tue, 12 Aug 2025 11:43:10 -0700 Subject: [PATCH 09/12] Data update --- .gitignore | 1 + .../Luhn-test-of-credit-card-numbers | 1 + ...ernational-Securities-Identification-Number | 1 + Task/Best-shuffle/YAMLScript/best-shuffle.ys | 7 ++++--- Task/Even-or-odd/YAMLScript/even-or-odd.ys | 9 +++++---- Task/Factorial/YAMLScript/factorial.ys | 9 ++++++--- .../Tcl/function-definition-3.tcl | 13 +++++++++++++ .../Elena/greatest-common-divisor.elena | 2 +- .../luhn-test-of-credit-card-numbers.ys | 10 ++++++++++ ...ational-securities-identification-number.ys | 18 ++++++++++++++++++ 10 files changed, 60 insertions(+), 11 deletions(-) create mode 120000 Lang/YAMLScript/Luhn-test-of-credit-card-numbers create mode 120000 Lang/YAMLScript/Validate-International-Securities-Identification-Number create mode 100644 Task/Function-definition/Tcl/function-definition-3.tcl create mode 100644 Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys create mode 100644 Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys diff --git a/.gitignore b/.gitignore index ecbdc2385f..80f7631497 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +/*.ys /Cache/ /Meta/ /rosettacode.log diff --git a/Lang/YAMLScript/Luhn-test-of-credit-card-numbers b/Lang/YAMLScript/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..f96e4c4d21 --- /dev/null +++ b/Lang/YAMLScript/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/YAMLScript \ No newline at end of file diff --git a/Lang/YAMLScript/Validate-International-Securities-Identification-Number b/Lang/YAMLScript/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..40c80b8d7d --- /dev/null +++ b/Lang/YAMLScript/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/YAMLScript \ No newline at end of file diff --git a/Task/Best-shuffle/YAMLScript/best-shuffle.ys b/Task/Best-shuffle/YAMLScript/best-shuffle.ys index 2874ddd1dd..40b2a8e761 100644 --- a/Task/Best-shuffle/YAMLScript/best-shuffle.ys +++ b/Task/Best-shuffle/YAMLScript/best-shuffle.ys @@ -1,8 +1,9 @@ !YS-v0 -defn main(input): - say: read-string(input) - .map(best-shuffle):vec +defn main(*inputs): + each input inputs: !:say + apply format '%s, %s, (%d)': + best-shuffle(input) defn best-shuffle(s): ref =: s:group-indices:cycles diff --git a/Task/Even-or-odd/YAMLScript/even-or-odd.ys b/Task/Even-or-odd/YAMLScript/even-or-odd.ys index c0a1aa7de0..36ee519cd2 100644 --- a/Task/Even-or-odd/YAMLScript/even-or-odd.ys +++ b/Task/Even-or-odd/YAMLScript/even-or-odd.ys @@ -1,6 +1,7 @@ !YS-v0 -defn main(x): - if x:even?: - say: "$x is even" - say: "$x is odd" +defn main(*xs): + each x xs: + if x:even?: + say: "$x is even" + say: "$x is odd" diff --git a/Task/Factorial/YAMLScript/factorial.ys b/Task/Factorial/YAMLScript/factorial.ys index 06c6ba6aef..29d50ba6fa 100644 --- a/Task/Factorial/YAMLScript/factorial.ys +++ b/Task/Factorial/YAMLScript/factorial.ys @@ -1,7 +1,10 @@ !YS-v0 -defn main(n=10): - say: "$n! -> $factorial(n)" +defn main(*ns): + each n ns: + say: "$n! -> $factorial(n)" defn factorial(x): - 2 .. x: .mul(*) + if x <= 2: + (x ||| 1) + (2 .. x).mul(*) diff --git a/Task/Function-definition/Tcl/function-definition-3.tcl b/Task/Function-definition/Tcl/function-definition-3.tcl new file mode 100644 index 0000000000..e2a1260e67 --- /dev/null +++ b/Task/Function-definition/Tcl/function-definition-3.tcl @@ -0,0 +1,13 @@ +proc multiply { a b args } { + + set product 1 + + foreach m [list $a $b {*}$args] { + + set product [expr {$product * $m}] + } + + return $product +} + +puts stdout [multiply 3 4 7 9 -2 -5 ] diff --git a/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena b/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena index 8d3b778db8..5dd09f89da 100644 --- a/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena +++ b/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena @@ -17,7 +17,7 @@ gcd(a,b) printGCD(a,b) { - console.printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b)) + Console.printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b)) } public program() diff --git a/Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys b/Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys new file mode 100644 index 0000000000..6a2092d4d6 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/YAMLScript/luhn-test-of-credit-card-numbers.ys @@ -0,0 +1,10 @@ +!YS-v0 + +defn main(*nums): + each cc nums: + say: "$cc - $if(cc:luhn? 'valid' 'invalid')" + +defn luhn?(cc): + map(mul cc:digits:reverse [1 2]:cycle) + .map(\(I(_ / 10) + (_ % 10))):sum + .mod(10):zero? diff --git a/Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys b/Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys new file mode 100644 index 0000000000..3633f68190 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/YAMLScript/validate-international-securities-identification-number.ys @@ -0,0 +1,18 @@ +!YS-v0 + +defn main(*nums): + each isin nums: + say: "$isin - $if(isin:isin? 'valid' 'invalid')" + +defn isin?(isin): + isin.re-matches(/[A-Z]{2}[A-Z0-9]{9}[0-9]/) && + isin.map(b36-10).apply(str):luhn? + +defn b36-10(c): + c =: c:I - 48 + if c > 9: (c - 7) c + +defn luhn?(cc): + map(mul cc:digits:reverse [1 2]:cycle) + .map(\(I(_ / 10) + (_ % 10))):sum + .mod(10):zero? From 5150844a7d3f98700cc91a9b3e40e78e2e5c4f21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Sun, 1 Feb 2026 16:13:50 -0800 Subject: [PATCH 10/12] Add 12 new langs and fix some extensions --- Conf/lang.yaml | 152 ++++++++++++++++++++++++++----------------------- 1 file changed, 82 insertions(+), 70 deletions(-) diff --git a/Conf/lang.yaml b/Conf/lang.yaml index bf92f9a54f..72c972e3d8 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -23,19 +23,19 @@ Acornsoft Lisp: .lisp Action!: .action ActionScript: .as Acurity Architect: .acurity -Ada: .ada +Ada: .adb Adina: .adina -Agda: .agda Agda2: .agda2 +Agda: .agda Agena: .agena AHDL: .ahdl AIDED NATURAL LANGUAGE: .aided Aikido: .aikido Aime: .aime Algae: .algae -ALGOL: .alg ALGOL 60: .alg ALGOL 68: .alg +ALGOL: .alg ALGOL-M: .alg ALGOL W: .alg Alice ML: .alice @@ -74,7 +74,7 @@ ASP: .asp AspectC++: .acpp AspectJ: .aspectj ASP.Net: .asp -Assembly: .as +Assembly: .asm AssemblyScript: .asmscript Astro: .astro Asymptote: .asymptote @@ -83,15 +83,14 @@ ATS: .ats AutoHotkey: .ahk Autohotkey V2: .ahk AutoHotKey V2: .ahk -AutoIt: .autoit -AutoLISP: .l +AutoIt: .au3 +AutoLISP: .lsp Avail: .avail AWK: .awk Axe: .axe Axiom: .axiom Axum: .axum Ayrch: .ayrch -B: .b B4J: .b4j B4X: .b4x Babel: .pb @@ -100,12 +99,13 @@ BaCon: .bacon Bait: .bait Ballerina: .ballerina Bas: .bas -BASIC: .basic Basic09: .basic BASIC256: .basic +BASIC: .basic Batari Basic: .basic Batch File: .bat Battlestar: .battlestar +B: .b BBC BASIC: .basic Bc: .bc BCPL: .bcpl @@ -113,6 +113,7 @@ Beads: .beads Beef: .beef Beeswax: .beeswax Befunge: .bf +Berkeley Logo: .logo Beta: .beta Biferno: .biferno Binary Lambda Calculus: .blc @@ -136,25 +137,26 @@ Brat: .brat Brlcad: .brlcad Bruijn: .bruijn Burlesque: .blq -C++: .cpp -C: .c C0H: .c0h C1R: .c1r C2: .c2 C3: .c3 CafeOBJ: .cafeobj +Calc: .calc Calcscript: .calc Caml: .caml Casio BASIC: .basic Cat: .cat CB80: .cb80 CBASIC: .basic +C: .c C++/CLI: .cpp +C++: .cpp Cduce: .cduce Cecil: .cecil Ceylon: .ceylon CFEngine: .cfengine -Chapel: .chapel +Chapel: .chpl Chef: .chef Cherrycake: .cherrycake Chipmunk Basic: .basic @@ -174,7 +176,7 @@ CLIPS: .clips Clojure: .clj CLU: .clu CMake: .cmake -COBOL: .cobol +COBOL: .cob Cobra: .cobra Coco: .coco Coconut: .coconut @@ -194,13 +196,12 @@ Cowgol: .cowgol Crack: .crack Craft Basic: .basic Creative Basic: .basic -Curto: .curto Crystal: .cr C sharp: .cs C Shell: .csh Cubescript: .cube Curry: .curry -D: .d +Curto: .curto Dafny: .dafny Dao: .dao Dart: .dart @@ -209,6 +210,7 @@ DataWeave: .dw DBL: .dbl Dc: .dc DCL: .dcl +D: .d DDNC: .ddnc Delphi: .pas Deluge: .deluge @@ -222,6 +224,7 @@ DMS: .dms Dodo0: .dodo0 Draco: .draco Dragon: .dragon +Dragonstone: .dragonstone DreamBerd: .dreamberd Dt: .dt DuckDB: .duckdb @@ -230,7 +233,6 @@ DWScript: .dw Dyalect: .dyalect Dylan: .dylan Dylan.NET: .dylan -E: .e EasyLang: .easy EC: .ec EchoLisp: .l @@ -238,6 +240,7 @@ ECL: .ecl Ecstasy: .ecstasy Ed: .ed EDSAC order code: .edsac +E: .e Eero: .eero Efene: .efene Egel: .egel @@ -253,7 +256,7 @@ Elisa: .elisa Elixir: .ex ELLA: .ella Elm: .elm -Emacs Lisp: .l +Emacs Lisp: .el EMal: .emal Emojicode: .emojicode Enguage: .enguage @@ -264,29 +267,29 @@ ERRE: .erre Es: .es ESQL: .esql Euler: .euler -Euphoria: .ex +Euphoria: .eu Evaldraw: .evaldraw Excel: .excel Explore: .explore Extended BrainF***: .ebf Extended Color BASIC: .basic Ezhil: .ezhil -F: .f Factor: .factor Falcon: .falcon 'FALSE': .false -Fan: .fan Fancy: .fancy +Fan: .fan Fantom: .fantom FAUST: .faust FBSL: .fbsl -Fe: .fe FeatureC++: .cpp +Fe: .fe Felix: .felix Fennel: .fennel Ferite: .ferite Fermat: .fermat Fexl: .fexl +F: .f Fhidwfe: .fhidwfe Fish: .fish FLORA-2: .flora2 @@ -337,10 +340,10 @@ GlovePIE: .glovepie GLSL: .glsl GML: .gml Gnuplot: .gnuplot -Go!: .go -Go: .go Goaldi: .goaldi Goboscript: .gobo +Go!: .go +Go: .go Golfscript: .golf Golo: .golo Goo: .goo @@ -357,7 +360,7 @@ Halon: .halon Harbour: .harbour Hare: .hare Haskell: .hs -Haxe: .haxe +Haxe: .hx Heron: .heron Hexiscript: .hexi HicEst: .hicest @@ -371,10 +374,10 @@ HQ9+: .hq9+ Huginn: .huginn Hy: .hy HyperTalk: .ht -I: .i Icon: .icon IDL: .idl Idris: .idris +I: .i Imp77: .imp77 Inform 6: '.inf' Inform 7: '.inf' @@ -390,18 +393,19 @@ Iptscrae: .iptscrae Isabelle: .isabelle IS-BASIC: .basic IWBASIC: .basic -J: .j Jabaco: .jabaco Jack: .jack Jacquard Loom: .jacquard +Jactl: .jactl Jakt: .jakt JAMES II/Rule-based Cellular Automata: .james Janet: .janet -Java: .java JavaFX Script: .javafx +Java: .java JavaScript: .js JCL: .jcl Jinja: .jinja +J: .j JoCaml: .jocaml JOVIAL: .jovial Joy: .joy @@ -411,7 +415,6 @@ JSE: .jse Jsish: .jsish JudoScript: .judo Julia: .jl -K: .k Kabap: .kabap Kamailio Script: .kamailio Kantalo: .kantalo @@ -421,6 +424,7 @@ Keg: .keg KeyList Databasing: .keylist Kite: .kite Kitten: .kitten +K: .k KL1: .kl1 Klingphix: .klingphix Klong: .klong @@ -430,14 +434,14 @@ KonsolScript: .konsol Kotlin: .kts KQL: .kql Ksh: .ksh -L++: .l++ LabVIEW: .labview Labyrinth: .labyrinth Lambda Prolog: .pro Lambdatalk: .lambdatalk -Lang: .lang Lang5: .lang5 +Lang: .lang Langur: .langur +Lapyst: .lapyst Lasso: .lasso LAST: .last LaTeX: .tex @@ -463,6 +467,7 @@ Little: .little Little Man Computer: .lmc LiveCode: .livecode LiveScript: .live +L++: .l++ LLP: .llp LLVM: .llvm Lobster: .lobster @@ -475,8 +480,8 @@ Lolli: .lolli Lotus 123 Macro Scripting: .lotus123 LotusScript: .lotus Lout: .lout -LSE: .lse LSE64: .lse64 +LSE: .lse LSL: .lsl LSTS: .lsts Lua: .lua @@ -518,19 +523,19 @@ Metapost: .metapost MGS: .mgs Mia: .mia Microsoft Small Basic: .basic -Min: .min MINIL: .minil Minimal BASIC: .basic MiniScript: .mini MiniZinc: .minizinc +Min: .min MIPS Assembly: .mips Mirah: .mirah Miranda: .miranda MIRC Scripting Language: .mirc Mirelle: .mirelle -ML: .ml ML/I: .mli MLite: .mlite +ML: .ml MMIX: .mmix Mn: .mn Modula-2: .mod2 @@ -542,6 +547,8 @@ Monkey: .monkey Monte: .monte MontiLang: .monti MOO: .moo +MoonBit: .moonbit +MoonRock: .moonrock MoonScript: .moon Morfa: .morfa Mosaic: .mosaic @@ -589,15 +596,15 @@ N/t/roff: .ntroff Nu: .nu Nutt: .nutt Nyquist: .nyquist -OASYS: .oasys OASYS Assembler: .oasys -Oberon: .oberon +OASYS: .oasys Oberon-07: .oberon +Oberon: .oberon Objeck: .objeck ObjectIcon: .oi Objective-C: .m -Object Pascal: .pas Object Pascal Implementations: .pas +Object Pascal: .pas OCaml: .ml Occam: .occam Octave: .octave @@ -608,8 +615,8 @@ Omega: .omega OmniMark: .xom Onyx: .onyx Onyx (wasm): .onyx -OOC: .ooc OOCalc: .oocalc +OOC: .ooc OoRexx: .rexx Opa: .opa OpenC++: .openc++ @@ -628,8 +635,8 @@ Panoramic: .panoramic ParaCL: .paracl Pare: .pare PARI/GP: .parigp -Pascal: .pas PascalABC.NET: .pas +Pascal: .pas Pascal-P: .pas PASM: .pasm PDP-11 Assembly: .pdp11 @@ -639,12 +646,12 @@ Pentium Assembly: .pentium PeopleCode: .peoplecode PepsiScript: .pepsi Peri: .peri -Perl: .pl Perl5i: .p5i Perl 6: .pl6 +Perl: .pl Peylang: .peylang -Phix: .phix Phixmonti: .phixmonti +Phix: .phix PHL: .phl PHP: .php Picat: .picat @@ -661,8 +668,8 @@ Plain English: .plain PlainTeX: .tex Plan: .plan PL/B: .plb -PL/I: .pli PL/I-80: .pli +PL/I: .pli PL/M: .plm PL/pgSQL: .sql PL/SQL: .sql @@ -680,7 +687,7 @@ POV-Ray: .povray PowerBASIC: .basic Powerbuilder: .powerbuilder PowerPC Assembly: .ppc -PowerShell: .psh +PowerShell: .ps1 PPL: .ppl Processing: .processing Processing Python mode: .processing-py @@ -691,43 +698,43 @@ ProgressBASIC: .basic Prolog: .pro PROMAL: .promal PSQL: .psql -Pure: .pure PureBasic: .basic Pure Data: .puredata +Pure: .pure Purity: .purity Pyret: .arr Python: .py -Q: .q QB64: .qb64 QBasic: .basic Qi: .qi .QL: .ql QL SuperBASIC: .basic Qore: .qore +Q: .q Quackery: .quackery QuakeC: .c QuickBASIC: .basic Quill: .quill Quite BASIC: .basic Quorum: .quorum -R: .r -Ra: .ra Racket: .rkt Raku: .raku RapidQ: .rapidq Rapira: .rapira +Ra: .ra Rascal: .rascal RASEL: .rasel RATFOR: .ratfor Raven: .raven REALbasic: .basic Reason: .re +Rebol: .rebol REBOL: .rebol Red: .red Reduce: .reduce Refal: .refal Relation: .relation -ReScript: .re +ReScript: .res Retro: .retro Revolution: .rev REXX: .rexx @@ -739,23 +746,26 @@ RISC-V Assembly: .asm RLaB: .rlab RLSL: .rlsl Robotic: .robotic -Roc: .roc Rockstar: .rockstar -RPG: .rpg +Rocq: .rocq +Roc: .roc RPGIV: .rpgiv -RPL: .rpl +RPG: .rpg RPL/2: .rpl2 +RPL: .rpl +R: .r RTL/2: .rtl2 RTSL: .rtsl Rubylog: .rubylog Ruby: .rb Run BASIC: .basic Rust: .rs -S++: .s++ +Rye: .rye Sage: .sage Salmon: .salmon -SAS: .sas +SapbotVM: .sapbot SASL: .sasl +SAS: .sas Sass/SCSS: .sass Sather: .sa S-BASIC: .basic @@ -772,14 +782,15 @@ Seed7: .seed7 Self: .self SenseTalk: .sensetalk SequenceL: .sequencel -SETL: .setl Setl4: .setl4 Set lang: .set +SETL: .setl Shale: .shale SheerPower 4GL: .4gl Shen: .shen Shiny: .shiny Sidef: .sidef +SIL: .sil SimpleCode: .simplecode SimpleLang: .simple SIMPOL: .simpol @@ -796,8 +807,8 @@ Smalltalk: .st Smart BASIC: .basic SMEQL: .smeql SmileBASIC: .basic -Snobol: .sno SNOBOL4: .sno +Snobol: .sno SNUSP: .snusp Soar: .soar Soda: .soda @@ -805,14 +816,15 @@ SoneKing Assembly: .soneking SPAD: .spad SPARC Assembly: .sparc SparForte: .sparforte -SPARK: .spark Sparkling: .sparkling +SPARK: .spark Spin: .spin SPL: .spl SPSS: .spss -SQL: .sql SQL PL: .sql +SQL: .sql Squirrel: .nut +S++: .s++ SSEM: .ssem Standard ML: .ml Star: .star @@ -840,16 +852,16 @@ TechBASIC: .basic Teco: .teco TeLa: .tela Tern: .tern -Terra: .terra Terraform: .terraform +Terra: .terra TestML: .tml Thistle: .thistle Thyrd: .thyrd -TI BASIC: .basic TI-57: .ti57 TI-83 BASIC: .basic TI-83 Hex Assembly: .asm TI-89 BASIC: .basic +TI BASIC: .basic Tiny BASIC: .basic Tiny Craft Basic: .basic TIS-100: .tis100 @@ -886,28 +898,26 @@ Unison: .u UnixPipes: .up UNIX Shell: .sh Unlambda: .unlambda -Ursa: .ursa -Ursala: .ursala Ursalang: .ursa +Ursala: .ursala +Ursa: .ursa UScript: .u UserRPL: .rpl UTFool: .utfool Uxntal: .uxnatl -V: .v -V (Vlang): .v Vala: .vala Vale: .vale VAX Assembly: .vax VB6: .vb6 VBA: .vba -VBScript: .vb +VBScript: .vbs Vedit macro language: .vedit Verbexx: .verbexx Verilog: .v -VHDL: .vhdl +VHDL: .vhd Vim Script: .vim -Visual Basic: .vb Visual Basic .NET: .vb +Visual Basic: .vb Visual FoxPro: .fvp Visual Objects: .vobj Visual Prolog: .pro @@ -916,6 +926,8 @@ Vorpal: .vorpal Vox: .vox VRML: .vrml VTL-2: .vtl-2 +V: .v +V (Vlang): .v Vyxal: .vyxal Waduzitdo: .waduzitdo Wart: .wart @@ -934,37 +946,37 @@ Wren: .wren X10: .x10 X86-64 Assembly: .x86-64 X86 Assembly: .x86 -X-script: .x Xanadu: .xanadu XBase: .xbase XBasic: .basic XBS: .xbs XEec: .xeec -XL: .xl XLISP: .l +XL: .xl Xojo: .xojo XPath 2.0: .xpath XPL0: .xpl0 XProc: .xproc XProfan: .xprofan XQuery: .xquery -XS: .xs -XSLT: .xslt +X-script: .x XSLT 1.0: .xslt XSLT 2.0: .xslt +XSLT: .xslt +XS: .xs XTalk: .xtalk XUL: .xul -Ya: .ya Yabasic: .basic Yacas: .yacas YAMLScript: .ys +Ya: .ya Yorick: .yorick Z80 Assembly: .z80 ZED: .zed Zig: .zig Zkl: .zkl -Zoea: .zoea Zoea Visual: .zoea +Zoea: .zoea Zonnon: .zonnon Zoomscript: .zoom ZPL: .zpl From 4bb20c9b71c190f413cb34675535f6f4b71db978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Sun, 1 Feb 2026 16:33:20 -0800 Subject: [PATCH 11/12] Data update --- Lang/11l/Bioinformatics-base-count | 1 - Lang/11l/Meissel-Mertens-constant | 1 - Lang/11l/Miller-Rabin-primality-test | 1 - Lang/11l/Sorting-Algorithms-Circle-Sort | 1 - Lang/6502-Assembly/00-LANG.txt | 23 + .../Bioinformatics-base-count | 1 - .../Miller-Rabin-primality-test | 1 - .../Sorting-Algorithms-Circle-Sort | 1 - Lang/ALGOL-68/Bioinformatics-base-count | 1 - Lang/ALGOL-68/Meissel-Mertens-constant | 1 - Lang/ALGOL-68/Miller-Rabin-primality-test | 1 - Lang/ALGOL-68/Quaternion-type | 1 - Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort | 1 - Lang/ALGOL-W/Copy-a-string | 1 - Lang/ALGOL-W/Integer-comparison | 1 - Lang/ALGOL-W/Meissel-Mertens-constant | 1 - Lang/ALGOL-W/Quaternion-type | 1 - Lang/APL/Bioinformatics-base-count | 1 - Lang/ARM-Assembly/Bioinformatics-base-count | 1 - Lang/ARM-Assembly/Miller-Rabin-primality-test | 1 - .../Sorting-Algorithms-Circle-Sort | 1 - Lang/ATS/Quaternion-type | 1 - Lang/AWK/00-LANG.txt | 4 +- Lang/AWK/Bioinformatics-base-count | 1 - Lang/Action-/Bioinformatics-base-count | 1 - Lang/Action-/Quaternion-type | 1 - Lang/Action-/Sorting-Algorithms-Circle-Sort | 1 - Lang/Ada/Bioinformatics-base-count | 1 - Lang/Ada/Miller-Rabin-primality-test | 1 - Lang/Ada/Quaternion-type | 1 - Lang/Agena/00-LANG.txt | 3 + Lang/Agena/100-doors | 1 - Lang/Arturo/Bioinformatics-base-count | 1 - Lang/Arturo/Meissel-Mertens-constant | 1 - Lang/Arturo/Quaternion-type | 1 - Lang/Arturo/Sorting-Algorithms-Circle-Sort | 1 - Lang/Asymptote/Empty-program | 1 - Lang/AutoHotkey/Miller-Rabin-primality-test | 1 - Lang/AutoHotkey/Quaternion-type | 1 - .../AutoHotkey/Sorting-Algorithms-Circle-Sort | 1 - Lang/Axiom/Quaternion-type | 1 - ...ficient-and-perfect-number-classifications | 1 - Lang/BASIC/Ethiopian-multiplication | 1 - Lang/BASIC/Mayan-numerals | 1 - Lang/BASIC256/Empty-program | 1 - Lang/BASIC256/Meissel-Mertens-constant | 1 - Lang/BASIC256/Quaternion-type | 1 - Lang/BBC-BASIC/Bioinformatics-base-count | 1 - Lang/BBC-BASIC/Quaternion-type | 1 - Lang/BQN/Miller-Rabin-primality-test | 1 - Lang/Batch-File/Input-loop | 1 - Lang/Bc/Miller-Rabin-primality-test | 1 - Lang/Binary-Lambda-Calculus/00-LANG.txt | 11 +- Lang/BootBASIC/Empty-program | 1 - Lang/Bracmat/Miller-Rabin-primality-test | 1 - Lang/C++/Bioinformatics-base-count | 1 - Lang/C++/Meissel-Mertens-constant | 1 - Lang/C++/Miller-Rabin-primality-test | 1 - Lang/C++/Quaternion-type | 1 - Lang/C++/Sorting-Algorithms-Circle-Sort | 1 - Lang/C-sharp/00-LANG.txt | 4 + Lang/C-sharp/Miller-Rabin-primality-test | 1 - Lang/C-sharp/Quaternion-type | 1 - Lang/C-sharp/Sorting-Algorithms-Circle-Sort | 1 - Lang/C/Bioinformatics-base-count | 1 - Lang/C/Miller-Rabin-primality-test | 1 - Lang/C/Quaternion-type | 1 - Lang/C/Sorting-Algorithms-Circle-Sort | 1 - Lang/CLU/Quaternion-type | 1 - Lang/Clojure/Miller-Rabin-primality-test | 1 - Lang/CoffeeScript/Empty-program | 1 - .../Sorting-Algorithms-Circle-Sort | 1 - .../Miller-Rabin-primality-test | 1 - Lang/Common-Lisp/Miller-Rabin-primality-test | 1 - Lang/Common-Lisp/Quaternion-type | 1 - Lang/Component-Pascal/00-LANG.txt | 9 +- Lang/Coq/00-LANG.txt | 10 +- Lang/Coq/100-doors | 1 - Lang/Coq/Ackermann-function | 1 - Lang/Coq/Extend-your-language | 1 - Lang/Coq/Factorial | 1 - Lang/Coq/Fibonacci-sequence | 1 - Lang/Coq/FizzBuzz | 1 - Lang/Coq/Hello-world-Newbie | 1 - Lang/Coq/Hello-world-Text | 1 - Lang/Coq/Loops-For | 1 - Lang/Coq/Tree-traversal | 1 - Lang/Coq/Variadic-function | 1 - Lang/Crystal/Empty-program | 1 - Lang/Crystal/Miller-Rabin-primality-test | 1 - Lang/Crystal/Quaternion-type | 1 - Lang/Crystal/Sorting-Algorithms-Circle-Sort | 1 - Lang/D/Miller-Rabin-primality-test | 1 - Lang/D/Quaternion-type | 1 - Lang/D/Sorting-Algorithms-Circle-Sort | 1 - Lang/Dart/Meissel-Mertens-constant | 1 - Lang/Dart/Quaternion-type | 1 - Lang/Delphi/Bioinformatics-base-count | 1 - Lang/Delphi/Meissel-Mertens-constant | 1 - Lang/Delphi/Quaternion-type | 1 - Lang/Delphi/Sorting-Algorithms-Circle-Sort | 1 - Lang/DuckDB/Bioinformatics-base-count | 1 - Lang/E/Miller-Rabin-primality-test | 1 - Lang/E/Quaternion-type | 1 - Lang/ERRE/Quaternion-type | 1 - Lang/EasyLang/Bioinformatics-base-count | 1 - Lang/EasyLang/Meissel-Mertens-constant | 1 - Lang/EasyLang/Quaternion-type | 1 - Lang/EasyLang/Sorting-Algorithms-Circle-Sort | 1 - Lang/EchoLisp/Miller-Rabin-primality-test | 1 - Lang/Ed/00-LANG.txt | 4 +- Lang/Ed/Bioinformatics-base-count | 1 - Lang/Eero/Quaternion-type | 1 - Lang/Elena/Quaternion-type | 1 - Lang/Elixir/Empty-program | 1 - Lang/Elixir/Miller-Rabin-primality-test | 1 - Lang/Elixir/Sorting-Algorithms-Circle-Sort | 1 - Lang/Erlang/Miller-Rabin-primality-test | 1 - Lang/Euphoria/Empty-program | 1 - Lang/Euphoria/Quaternion-type | 1 - Lang/F-Sharp/Miller-Rabin-primality-test | 1 - Lang/F-Sharp/Quaternion-type | 1 - Lang/FALSE/Empty-program | 1 - Lang/Factor/Bioinformatics-base-count | 1 - Lang/Factor/Quaternion-type | 1 - Lang/Forth/Bioinformatics-base-count | 1 - Lang/Forth/Miller-Rabin-primality-test | 1 - Lang/Forth/Quaternion-type | 1 - Lang/Forth/Sorting-Algorithms-Circle-Sort | 1 - Lang/Fortran/Miller-Rabin-primality-test | 1 - Lang/Fortran/Quaternion-type | 1 - Lang/Fortran/Sorting-Algorithms-Circle-Sort | 1 - Lang/FreeBASIC/Bioinformatics-base-count | 1 - Lang/FreeBASIC/Meissel-Mertens-constant | 1 - Lang/FreeBASIC/Miller-Rabin-primality-test | 1 - Lang/FreeBASIC/Quaternion-type | 1 - Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort | 1 - Lang/FunL/Miller-Rabin-primality-test | 1 - Lang/FutureBasic/Bioinformatics-base-count | 1 - Lang/FutureBasic/Knights-tour | 1 - Lang/GAP/Quaternion-type | 1 - Lang/Gleam/00-LANG.txt | 5 +- Lang/Go/Bioinformatics-base-count | 1 - Lang/Go/Meissel-Mertens-constant | 1 - Lang/Go/Miller-Rabin-primality-test | 1 - Lang/Go/Quaternion-type | 1 - Lang/Go/Sorting-Algorithms-Circle-Sort | 1 - Lang/Goboscript/00-LANG.txt | 16 +- Lang/Groovy/Empty-program | 1 - Lang/Haskell/Bioinformatics-base-count | 1 - Lang/Haskell/Miller-Rabin-primality-test | 1 - Lang/Haskell/Quaternion-type | 1 - Lang/Haskell/Sorting-Algorithms-Circle-Sort | 1 - Lang/Icon/Miller-Rabin-primality-test | 1 - Lang/Idris/Quaternion-type | 1 - Lang/J/Bioinformatics-base-count | 1 - Lang/J/Meissel-Mertens-constant | 1 - Lang/J/Quaternion-type | 1 - Lang/J/Sorting-Algorithms-Circle-Sort | 1 - Lang/Java/Bioinformatics-base-count | 1 - Lang/Java/Meissel-Mertens-constant | 1 - Lang/Java/Miller-Rabin-primality-test | 1 - Lang/Java/Quaternion-type | 1 - Lang/Java/Sorting-Algorithms-Circle-Sort | 1 - Lang/JavaScript/Bioinformatics-base-count | 1 - Lang/JavaScript/Meissel-Mertens-constant | 1 - Lang/JavaScript/Miller-Rabin-primality-test | 1 - Lang/JavaScript/Quaternion-type | 1 - Lang/Jq/Bioinformatics-base-count | 1 - Lang/Jq/Quaternion-type | 1 - Lang/Jq/Sorting-Algorithms-Circle-Sort | 1 - Lang/Julia/Bioinformatics-base-count | 1 - Lang/Julia/Meissel-Mertens-constant | 1 - Lang/Julia/Miller-Rabin-primality-test | 1 - Lang/Julia/Quaternion-type | 1 - Lang/Julia/Sorting-Algorithms-Circle-Sort | 1 - Lang/K/Empty-program | 1 - Lang/Kotlin/Bioinformatics-base-count | 1 - Lang/Kotlin/Miller-Rabin-primality-test | 1 - Lang/Kotlin/Quaternion-type | 1 - Lang/Kotlin/Sorting-Algorithms-Circle-Sort | 1 - Lang/LSE/Empty-program | 1 - Lang/Lambdatalk/Bioinformatics-base-count | 1 - .../Liberty-BASIC/Miller-Rabin-primality-test | 1 - Lang/Liberty-BASIC/Quaternion-type | 1 - Lang/Logo/Associative-array-Creation | 1 - Lang/Lua/Bioinformatics-base-count | 1 - Lang/Lua/Empty-program | 1 - Lang/Lua/Miller-Rabin-primality-test | 1 - Lang/Lua/Quaternion-type | 1 - Lang/Lua/Sorting-Algorithms-Circle-Sort | 1 - Lang/M2000-Interpreter/00-LANG.txt | 24 +- .../Bioinformatics-base-count | 1 - .../Miller-Rabin-primality-test | 1 - Lang/M2000-Interpreter/Quaternion-type | 1 - Lang/M4/Empty-program | 1 - Lang/MATLAB/Bioinformatics-base-count | 1 - Lang/ML-I/Empty-program | 1 - Lang/Maple/Empty-program | 1 - Lang/Maple/Quaternion-type | 1 - Lang/Mathematica/Bioinformatics-base-count | 1 - Lang/Mathematica/Empty-program | 1 - Lang/Mathematica/Meissel-Mertens-constant | 1 - Lang/Mathematica/Miller-Rabin-primality-test | 1 - Lang/Mathematica/Quaternion-type | 1 - .../Sorting-Algorithms-Circle-Sort | 1 - Lang/Maxima/Meissel-Mertens-constant | 1 - Lang/Maxima/Miller-Rabin-primality-test | 1 - Lang/MelonBasic/Empty-program | 1 - Lang/Mercury/Miller-Rabin-primality-test | 1 - Lang/Mercury/Quaternion-type | 1 - Lang/MiniScript/Empty-program | 1 - Lang/Modula-2/00-LANG.txt | 9 +- Lang/Modula-3/00-LANG.txt | 9 +- Lang/Modula-3/Comments | 1 - Lang/NS-HUBASIC/Empty-program | 1 - Lang/Nickle/00-LANG.txt | 5 +- Lang/Nim/Bioinformatics-base-count | 1 - Lang/Nim/Meissel-Mertens-constant | 1 - Lang/Nim/Miller-Rabin-primality-test | 1 - Lang/Nim/Quaternion-type | 1 - Lang/Nim/Sorting-Algorithms-Circle-Sort | 1 - Lang/OCaml/Quaternion-type | 1 - Lang/Oberon-07/00-LANG.txt | 16 +- Lang/Oberon/Even-or-odd | 1 - Lang/Oberon/Loops-For-with-a-specified-step | 1 - Lang/Objeck/Sorting-Algorithms-Circle-Sort | 1 - Lang/Octave/Quaternion-type | 1 - Lang/Odin/00-LANG.txt | 25 +- Lang/Oforth/Quaternion-type | 1 - Lang/Ol/Quaternion-type | 1 - Lang/OoRexx/00-LANG.txt | 5 +- Lang/OoRexx/Quaternion-type | 1 - Lang/Openscad/Empty-program | 1 - Lang/Oz/Miller-Rabin-primality-test | 1 - Lang/PARI-GP/Empty-program | 1 - Lang/PARI-GP/Meissel-Mertens-constant | 1 - Lang/PARI-GP/Miller-Rabin-primality-test | 1 - Lang/PARI-GP/Quaternion-type | 1 - Lang/PARI-GP/Sorting-Algorithms-Circle-Sort | 1 - Lang/PHP/00-LANG.txt | 11 +- Lang/PHP/Miller-Rabin-primality-test | 1 - Lang/PL-I/Quaternion-type | 1 - Lang/Pascal/Bell-numbers | 1 - Lang/Pascal/Bioinformatics-base-count | 1 - Lang/Pascal/Brazilian-numbers | 1 - Lang/Pascal/Ethiopian-multiplication | 1 - Lang/Pascal/Gamma-function | 1 - Lang/Pascal/Leap-year | 1 - Lang/Pascal/Prime-decomposition | 1 - Lang/Pascal/Sorting-Algorithms-Circle-Sort | 1 - Lang/Pascal/Square-free-integers | 1 - Lang/PascalABC.NET/00-LANG.txt | 5 +- Lang/PascalABC.NET/Bioinformatics-base-count | 1 - Lang/PascalABC.NET/Meissel-Mertens-constant | 1 - .../PascalABC.NET/Miller-Rabin-primality-test | 1 - Lang/Perl/Bioinformatics-base-count | 1 - Lang/Perl/Meissel-Mertens-constant | 1 - Lang/Perl/Miller-Rabin-primality-test | 1 - Lang/Perl/Quaternion-type | 1 - Lang/Perl/Sorting-Algorithms-Circle-Sort | 1 - Lang/Phix/00-LANG.txt | 10 +- Lang/Phix/Bioinformatics-base-count | 1 - Lang/Phix/Meissel-Mertens-constant | 1 - Lang/Phix/Miller-Rabin-primality-test | 1 - Lang/Phix/Quaternion-type | 1 - Lang/Phix/Sorting-Algorithms-Circle-Sort | 1 - Lang/Picat/Bioinformatics-base-count | 1 - Lang/Picat/Quaternion-type | 1 - Lang/PicoLisp/Bioinformatics-base-count | 1 - Lang/PicoLisp/Miller-Rabin-primality-test | 1 - Lang/PicoLisp/Quaternion-type | 1 - Lang/Pike/Miller-Rabin-primality-test | 1 - Lang/Plain-English/00-LANG.txt | 218 +++- Lang/Pluto/00-LANG.txt | 6 + Lang/PowerShell/Quaternion-type | 1 - Lang/Prolog/Miller-Rabin-primality-test | 1 - Lang/Prolog/Quaternion-type | 1 - Lang/PureBasic/Bioinformatics-base-count | 1 - Lang/PureBasic/Meissel-Mertens-constant | 1 - Lang/PureBasic/Miller-Rabin-primality-test | 1 - Lang/PureBasic/Quaternion-type | 1 - Lang/Python/Bioinformatics-base-count | 1 - Lang/Python/Meissel-Mertens-constant | 1 - Lang/Python/Miller-Rabin-primality-test | 1 - Lang/Python/Quaternion-type | 1 - Lang/Python/Sorting-Algorithms-Circle-Sort | 1 - Lang/QBasic/Repeat-a-string | 1 - Lang/Quackery/00-LANG.txt | 2 +- Lang/Quackery/Bioinformatics-base-count | 1 - Lang/Quackery/Miller-Rabin-primality-test | 1 - Lang/Quackery/Sorting-Algorithms-Circle-Sort | 1 - Lang/Quite-BASIC/Empty-program | 1 - Lang/R/Bioinformatics-base-count | 1 - Lang/R/Quaternion-type | 1 - Lang/REBOL/00-LANG.txt | 5 - Lang/REBOL/00-META.yaml | 2 - Lang/REBOL/100-doors | 1 - Lang/REBOL/15-puzzle-game | 1 - Lang/REBOL/9-billion-names-of-God-the-integer | 1 - Lang/REBOL/99-bottles-of-beer | 1 - Lang/REBOL/A+B | 1 - Lang/REBOL/Abstract-type | 1 - Lang/REBOL/Accumulator-factory | 1 - Lang/REBOL/Ackermann-function | 1 - ...-a-variable-to-a-class-instance-at-runtime | 1 - Lang/REBOL/Align-columns | 1 - Lang/REBOL/Amicable-pairs | 1 - Lang/REBOL/Animation | 1 - Lang/REBOL/Anonymous-recursion | 1 - Lang/REBOL/Apply-a-callback-to-an-array | 1 - Lang/REBOL/Arithmetic-Integer | 1 - Lang/REBOL/Array-concatenation | 1 - Lang/REBOL/Array-length | 1 - Lang/REBOL/Arrays | 1 - Lang/REBOL/Averages-Arithmetic-mean | 1 - Lang/REBOL/Averages-Median | 1 - Lang/REBOL/Calendar | 1 - Lang/REBOL/Check-that-file-exists | 1 - Lang/REBOL/Classes | 1 - Lang/REBOL/Comma-quibbling | 1 - Lang/REBOL/Comments | 1 - Lang/REBOL/Copy-a-string | 1 - Lang/REBOL/Create-a-file | 1 - Lang/REBOL/Date-format | 1 - Lang/REBOL/Date-manipulation | 1 - Lang/REBOL/Day-of-the-week | 1 - Lang/REBOL/Delete-a-file | 1 - Lang/REBOL/Detect-division-by-zero | 1 - Lang/REBOL/Determine-if-a-string-is-numeric | 1 - Lang/REBOL/Documentation | 1 - Lang/REBOL/Dot-product | 1 - Lang/REBOL/Dynamic-variable-names | 1 - Lang/REBOL/Echo-server | 1 - Lang/REBOL/Empty-program | 1 - Lang/REBOL/Environment-variables | 1 - Lang/REBOL/Execute-Brain- | 1 - Lang/REBOL/Execute-a-system-command | 1 - Lang/REBOL/FTP | 1 - Lang/REBOL/Factorial | 1 - Lang/REBOL/File-input-output | 1 - Lang/REBOL/File-size | 1 - Lang/REBOL/Filter | 1 - Lang/REBOL/Find-the-last-Sunday-of-each-month | 1 - Lang/REBOL/First-class-functions | 1 - Lang/REBOL/Fixed-length-records | 1 - Lang/REBOL/FizzBuzz | 1 - Lang/REBOL/Flatten-a-list | 1 - Lang/REBOL/Flow-control-structures | 1 - Lang/REBOL/Formatted-numeric-output | 1 - Lang/REBOL/Function-composition | 1 - Lang/REBOL/Function-definition | 1 - Lang/REBOL/Generic-swap | 1 - Lang/REBOL/Greatest-common-divisor | 1 - Lang/REBOL/Greatest-element-of-a-list | 1 - Lang/REBOL/HTTP | 1 - Lang/REBOL/Hailstone-sequence | 1 - Lang/REBOL/Hello-world-Graphical | 1 - Lang/REBOL/Hello-world-Newline-omission | 1 - Lang/REBOL/Hello-world-Text | 1 - Lang/REBOL/Higher-order-functions | 1 - .../Horners-rule-for-polynomial-evaluation | 1 - Lang/REBOL/Hostname | 1 - Lang/REBOL/Increment-a-numerical-string | 1 - Lang/REBOL/Inheritance-Single | 1 - Lang/REBOL/Input-loop | 1 - Lang/REBOL/Integer-comparison | 1 - Lang/REBOL/Interactive-programming-repl- | 1 - Lang/REBOL/JSON | 1 - Lang/REBOL/Josephus-problem | 1 - Lang/REBOL/Keyboard-macros | 1 - Lang/REBOL/Knuth-shuffle | 1 - Lang/REBOL/Last-Friday-of-each-month | 1 - Lang/REBOL/Leap-year | 1 - Lang/REBOL/Literals-Integer | 1 - Lang/REBOL/Logical-operations | 1 - .../Loop-over-multiple-arrays-simultaneously | 1 - Lang/REBOL/Loops-Break | 1 - Lang/REBOL/Loops-Continue | 1 - Lang/REBOL/Loops-Do-while | 1 - Lang/REBOL/Loops-Downward-for | 1 - Lang/REBOL/Loops-For | 1 - Lang/REBOL/Loops-For-with-a-specified-step | 1 - Lang/REBOL/Loops-Foreach | 1 - ...oops-Increment-loop-index-within-loop-body | 1 - Lang/REBOL/Loops-Infinite | 1 - Lang/REBOL/Loops-N-plus-one-half | 1 - Lang/REBOL/Loops-Nested | 1 - Lang/REBOL/Loops-While | 1 - Lang/REBOL/Loops-With-multiple-ranges | 1 - Lang/REBOL/Loops-Wrong-ranges | 1 - Lang/REBOL/MD5 | 1 - Lang/REBOL/Mad-Libs | 1 - Lang/REBOL/Menu | 1 - Lang/REBOL/Multiplication-tables | 1 - Lang/REBOL/Mutual-recursion | 1 - Lang/REBOL/Null-object | 1 - Lang/REBOL/Number-reversal-game | 1 - Lang/REBOL/Object-serialization | 1 - Lang/REBOL/Palindrome-detection | 1 - .../Percentage-difference-between-images | 1 - Lang/REBOL/Perfect-numbers | 1 - Lang/REBOL/Polyspiral | 1 - Lang/REBOL/Primality-by-trial-division | 1 - Lang/REBOL/Program-termination | 1 - Lang/REBOL/Queue-Definition | 1 - Lang/REBOL/Queue-Usage | 1 - Lang/REBOL/Quine | 1 - Lang/REBOL/Read-a-specific-line-from-a-file | 1 - Lang/REBOL/Read-entire-file | 1 - Lang/REBOL/Regular-expressions | 1 - Lang/REBOL/Remove-duplicate-elements | 1 - Lang/REBOL/Rename-a-file | 1 - Lang/REBOL/Repeat-a-string | 1 - Lang/REBOL/Reverse-a-string | 1 - Lang/REBOL/Rot-13 | 1 - Lang/REBOL/Runtime-evaluation | 1 - .../Runtime-evaluation-In-an-environment | 1 - Lang/REBOL/SHA-1 | 1 - Lang/REBOL/SHA-256 | 1 - Lang/REBOL/Search-a-list | 1 - Lang/REBOL/Semordnilap | 1 - Lang/REBOL/Send-email | 1 - Lang/REBOL/Shell-one-liner | 1 - Lang/REBOL/Simple-database | 1 - Lang/REBOL/Simple-windowed-application | 1 - Lang/REBOL/Sleep | 1 - Lang/REBOL/Sort-an-integer-array | 1 - Lang/REBOL/Sort-stability | 1 - Lang/REBOL/Sorting-algorithms-Insertion-sort | 1 - Lang/REBOL/Stack | 1 - Lang/REBOL/Stair-climbing-puzzle | 1 - Lang/REBOL/String-case | 1 - Lang/REBOL/String-concatenation | 1 - Lang/REBOL/String-interpolation-included- | 1 - Lang/REBOL/String-length | 1 - Lang/REBOL/Substring | 1 - Lang/REBOL/Sum-and-product-of-an-array | 1 - Lang/REBOL/Symmetric-difference | 1 - Lang/REBOL/System-time | 1 - Lang/REBOL/Take-notes-on-the-command-line | 1 - Lang/REBOL/Tokenize-a-string | 1 - Lang/REBOL/Towers-of-Hanoi | 1 - Lang/REBOL/Tree-traversal | 1 - Lang/REBOL/Trigonometric-functions | 1 - Lang/REBOL/User-input-Graphical | 1 - Lang/REBOL/User-input-Text | 1 - Lang/REBOL/Variadic-function | 1 - Lang/REBOL/Web-scraping | 1 - Lang/REBOL/Window-creation | 1 - Lang/REBOL/XML-Input | 1 - Lang/REBOL/Y-combinator | 1 - Lang/REXX/00-LANG.txt | 7 +- Lang/REXX/Bioinformatics-base-count | 1 - Lang/REXX/Meissel-Mertens-constant | 1 - Lang/REXX/Miller-Rabin-primality-test | 1 - Lang/REXX/Quaternion-type | 1 - Lang/REXX/Sorting-Algorithms-Circle-Sort | 1 - Lang/RISC-V-Assembly/00-LANG.txt | 5 +- Lang/Racket/Bioinformatics-base-count | 1 - Lang/Racket/Miller-Rabin-primality-test | 1 - Lang/Racket/Quaternion-type | 1 - Lang/Racket/Sorting-Algorithms-Circle-Sort | 1 - Lang/Raku/Bioinformatics-base-count | 1 - Lang/Raku/Meissel-Mertens-constant | 1 - Lang/Raku/Miller-Rabin-primality-test | 1 - Lang/Raku/Quaternion-type | 1 - Lang/Raku/Sorting-Algorithms-Circle-Sort | 1 - Lang/RapidQ/M-bius-function | 1 - Lang/Red/Quaternion-type | 1 - Lang/Ring/Bioinformatics-base-count | 1 - Lang/Ring/Empty-program | 1 - Lang/Ring/Miller-Rabin-primality-test | 1 - Lang/Ring/Sorting-Algorithms-Circle-Sort | 1 - Lang/Robotic/Empty-program | 1 - Lang/Ruby/Bioinformatics-base-count | 1 - Lang/Ruby/Miller-Rabin-primality-test | 1 - Lang/Ruby/Quaternion-type | 1 - Lang/Ruby/Sorting-Algorithms-Circle-Sort | 1 - Lang/Run-BASIC/Meissel-Mertens-constant | 1 - Lang/Run-BASIC/Miller-Rabin-primality-test | 1 - Lang/Rust/Bioinformatics-base-count | 1 - Lang/Rust/Meissel-Mertens-constant | 1 - Lang/Rust/Miller-Rabin-primality-test | 1 - Lang/Rust/Quaternion-type | 1 - Lang/Rust/Sorting-Algorithms-Circle-Sort | 1 - Lang/Scala/Miller-Rabin-primality-test | 1 - Lang/Scala/Quaternion-type | 1 - Lang/Scala/Sorting-Algorithms-Circle-Sort | 1 - Lang/Scheme/Empty-program | 1 - Lang/Scheme/Miller-Rabin-primality-test | 1 - Lang/Scilab/Empty-program | 1 - Lang/Seed7/Miller-Rabin-primality-test | 1 - Lang/Seed7/Quaternion-type | 1 - Lang/Set-lang/Empty-program | 1 - Lang/Sidef/Empty-program | 1 - Lang/Sidef/Meissel-Mertens-constant | 1 - Lang/Sidef/Miller-Rabin-primality-test | 1 - Lang/Sidef/Quaternion-type | 1 - Lang/Sidef/Sorting-Algorithms-Circle-Sort | 1 - Lang/SimpleCode/Empty-program | 1 - Lang/Slate/Empty-program | 1 - Lang/Smalltalk/Miller-Rabin-primality-test | 1 - Lang/Sparkling/Empty-program | 1 - Lang/Standard-ML/Miller-Rabin-primality-test | 1 - Lang/Swift/Bioinformatics-base-count | 1 - Lang/Swift/Empty-program | 1 - Lang/Swift/Miller-Rabin-primality-test | 1 - Lang/Swift/Quaternion-type | 1 - Lang/Swift/Sorting-Algorithms-Circle-Sort | 1 - Lang/Symsyn/Empty-program | 1 - Lang/Tcl/Bioinformatics-base-count | 1 - Lang/Tcl/Miller-Rabin-primality-test | 1 - Lang/Tcl/Quaternion-type | 1 - Lang/Trith/Empty-program | 1 - Lang/True-BASIC/Meissel-Mertens-constant | 1 - Lang/Uiua/00-LANG.txt | 8 +- Lang/UnixPipes/00-LANG.txt | 4 +- Lang/Uxntal/Bioinformatics-base-count | 1 - Lang/V-(Vlang)/00-LANG.txt | 9 +- Lang/V-(Vlang)/Bioinformatics-base-count | 1 - Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort | 1 - Lang/VBA/Quaternion-type | 1 - Lang/VBScript/Bioinformatics-base-count | 1 - Lang/Visual-Basic-.NET/Quaternion-type | 1 - Lang/Wee-Basic/Empty-program | 1 - Lang/Wren/Bioinformatics-base-count | 1 - Lang/Wren/Empty-program | 1 - Lang/Wren/Meissel-Mertens-constant | 1 - Lang/Wren/Miller-Rabin-primality-test | 1 - Lang/Wren/Quaternion-type | 1 - Lang/Wren/Sorting-Algorithms-Circle-Sort | 1 - .../Miller-Rabin-primality-test | 1 - Lang/XPL0/Bioinformatics-base-count | 1 - Lang/XPL0/Meissel-Mertens-constant | 1 - Lang/XPL0/Quaternion-type | 1 - Lang/XPL0/Sorting-Algorithms-Circle-Sort | 1 - Lang/YAMLScript/00-LANG.txt | 65 +- Lang/Yabasic/Empty-program | 1 - Lang/Yabasic/Meissel-Mertens-constant | 1 - .../Sorting-Algorithms-Circle-Sort | 1 - Lang/Zkl/Bioinformatics-base-count | 1 - Lang/Zkl/Miller-Rabin-primality-test | 1 - Lang/Zkl/Quaternion-type | 1 - Lang/Zkl/Sorting-Algorithms-Circle-Sort | 1 - Lang/Zonnon/00-LANG.txt | 9 +- Task/100-doors/11l/100-doors.11l | 2 +- Task/100-doors/8080-Assembly/100-doors-2.8080 | 75 +- Task/100-doors/Ada/100-doors-1.ada | 22 - Task/100-doors/Ada/100-doors-2.ada | 16 - Task/100-doors/Agena/100-doors.agena | 19 - Task/100-doors/AutoIt/100-doors.autoit | 17 - Task/100-doors/AutoLISP/100-doors.l | 18 - Task/100-doors/COBOL/100-doors.cobol | 33 - Task/100-doors/Coq/100-doors-1.coq | 26 - Task/100-doors/Coq/100-doors-2.coq | 13 - Task/100-doors/Coq/100-doors-3.coq | 1 - Task/100-doors/Coq/100-doors-4.coq | 1 - Task/100-doors/Elena/100-doors.elena | 2 +- Task/100-doors/Emacs-Lisp/100-doors-1.l | 83 -- Task/100-doors/Emacs-Lisp/100-doors-2.l | 16 - Task/100-doors/Euphoria/100-doors.ex | 23 - Task/100-doors/Haxe/100-doors-1.haxe | 23 - Task/100-doors/Haxe/100-doors-2.haxe | 18 - Task/100-doors/Informix-4GL/100-doors-2.4gl | 2 +- Task/100-doors/OPL/100-doors.opl | 7 +- Task/100-doors/Odin/100-doors-1.odin | 30 +- Task/100-doors/Odin/100-doors-2.odin | 18 +- Task/100-doors/PowerShell/100-doors-1.psh | 14 - Task/100-doors/PowerShell/100-doors-2.psh | 37 - Task/100-doors/PowerShell/100-doors-3.psh | 2 - Task/100-doors/PowerShell/100-doors-4.psh | 3 - Task/100-doors/PowerShell/100-doors-5.psh | 3 - Task/100-doors/PowerShell/100-doors-6.psh | 6 - Task/100-doors/PowerShell/100-doors-7.psh | 1 - Task/100-doors/Python/100-doors-5.py | 6 +- Task/100-doors/Python/100-doors-6.py | 2 +- Task/100-doors/REBOL/100-doors-1.rebol | 5 - Task/100-doors/REBOL/100-doors-2.rebol | 26 - Task/100-doors/REBOL/100-doors-3.rebol | 6 - Task/100-doors/VBScript/100-doors.vb | 21 - Task/100-doors/VHDL/100-doors-1.vhdl | 28 - Task/100-doors/VHDL/100-doors-2.vhdl | 34 - Task/100-prisoners/11l/100-prisoners.11l | 4 +- Task/100-prisoners/Ada/100-prisoners-1.ada | 23 - Task/100-prisoners/Ada/100-prisoners-2.ada | 128 --- Task/100-prisoners/Ada/100-prisoners-3.ada | 17 - Task/100-prisoners/D/100-prisoners.d | 2 +- .../PowerShell/100-prisoners.psh | 121 -- Task/100-prisoners/VBScript/100-prisoners.vb | 62 - Task/15-puzzle-game/Ada/15-puzzle-game-1.ada | 16 - Task/15-puzzle-game/Ada/15-puzzle-game-2.ada | 57 - Task/15-puzzle-game/Ada/15-puzzle-game-3.ada | 72 -- Task/15-puzzle-game/Ada/15-puzzle-game-4.ada | 1 - .../Arturo/15-puzzle-game.arturo | 60 +- .../15-puzzle-game/COBOL/15-puzzle-game.cobol | 151 --- .../PowerShell/15-puzzle-game.psh | 259 ----- .../15-puzzle-game/REBOL/15-puzzle-game.rebol | 6 - .../15-puzzle-game/VBScript/15-puzzle-game.vb | 108 -- .../15-puzzle-solver/Ada/15-puzzle-solver.ada | 192 ---- .../Uiua/15-puzzle-solver.uiua | 42 +- Task/2048/Ada/2048.ada | 177 --- Task/2048/EasyLang/2048.easy | 2 +- Task/2048/Zig/2048.zig | 536 +++++---- Task/21-game/Ada/21-game.ada | 108 -- Task/21-game/Arturo/21-game.arturo | 2 +- Task/21-game/AutoHotkey/21-game.ahk | 60 +- Task/21-game/GDScript/21-game.gd | 114 +- Task/21-game/Python/21-game-1.py | 102 +- Task/21-game/Ring/21-game.ring | 10 +- Task/24-game-Solve/COBOL/24-game-solve.cobol | 446 -------- Task/24-game/Ada/24-game.ada | 172 --- Task/24-game/Arturo/24-game.arturo | 5 +- Task/24-game/AutoIt/24-game.autoit | 74 -- Task/24-game/COBOL/24-game.cobol | 843 -------------- Task/24-game/Elena/24-game.elena | 18 +- Task/24-game/PowerShell/24-game.psh | 73 -- .../Ada/4-rings-or-4-squares-puzzle.ada | 68 -- .../9-billion-names-of-god-the-integer.ada | 142 --- .../9-billion-names-of-god-the-integer.groovy | 2 +- .../9-billion-names-of-god-the-integer.rebol | 101 -- .../Ada/99-bottles-of-beer-1.ada | 12 - .../Ada/99-bottles-of-beer-2.ada | 39 - .../Arturo/99-bottles-of-beer.arturo | 5 +- .../COBOL/99-bottles-of-beer-1.cobol | 104 -- .../COBOL/99-bottles-of-beer-2.cobol | 122 -- .../COBOL/99-bottles-of-beer-3.cobol | 16 - .../Chapel/99-bottles-of-beer.chapel | 68 -- .../EasyLang/99-bottles-of-beer.easy | 13 +- .../Elena/99-bottles-of-beer.elena | 2 +- .../Emacs-Lisp/99-bottles-of-beer.l | 7 - .../Euphoria/99-bottles-of-beer-1.ex | 28 - .../Euphoria/99-bottles-of-beer-2.ex | 17 - .../Euphoria/99-bottles-of-beer-3.ex | 20 - .../Haxe/99-bottles-of-beer-1.haxe | 33 - .../Haxe/99-bottles-of-beer-2.haxe | 33 - .../REBOL/99-bottles-of-beer-1.rebol | 19 - .../REBOL/99-bottles-of-beer-2.rebol | 9 - .../REBOL/99-bottles-of-beer-3.rebol | 1 - .../YAMLScript/99-bottles-of-beer-1.ys | 2 +- Task/A+B/11l/a+b.11l | 2 +- Task/A+B/Ada/a+b-1.ada | 10 - Task/A+B/Ada/a+b-2.ada | 12 - Task/A+B/AutoIt/a+b-1.autoit | 7 - Task/A+B/AutoIt/a+b-2.autoit | 22 - Task/A+B/Batch-File/a+b-3.bat | 7 +- Task/A+B/COBOL/a+b-1.cobol | 20 - Task/A+B/COBOL/a+b-2.cobol | 38 - Task/A+B/Elena/a+b-1.elena | 2 +- Task/A+B/Elena/a+b-2.elena | 2 +- Task/A+B/Emacs-Lisp/a+b.l | 5 - Task/A+B/Euphoria/a+b.ex | 12 - Task/A+B/PowerShell/a+b-1.psh | 2 - Task/A+B/PowerShell/a+b-2.psh | 2 - Task/A+B/PowerShell/a+b-3.psh | 3 - Task/A+B/PowerShell/a+b-4.psh | 1 - Task/A+B/REBOL/a+b.rebol | 1 - Task/A+B/REXX/a+b.rexx | 4 +- Task/A+B/VBScript/a+b-1.vb | 6 - Task/A+B/VBScript/a+b-2.vb | 37 - Task/A+B/VHDL/a+b.vhdl | 23 - .../8080-Assembly/abc-problem.8080 | 154 +-- .../8086-Assembly/abc-problem.8086 | 126 +- Task/ABC-problem/8th/abc-problem.8th | 4 +- Task/ABC-problem/Ada/abc-problem.ada | 78 -- Task/ABC-problem/Arturo/abc-problem.arturo | 4 +- Task/ABC-problem/AutoHotkey/abc-problem-1.ahk | 40 +- Task/ABC-problem/AutoHotkey/abc-problem-2.ahk | 2 +- Task/ABC-problem/BASIC256/abc-problem.basic | 68 +- .../Ballerina/abc-problem.ballerina | 6 +- Task/ABC-problem/C-sharp/abc-problem-2.cs | 132 +-- Task/ABC-problem/C/abc-problem.c | 46 +- .../Component-Pascal/abc-problem.pas | 138 +-- Task/ABC-problem/EMal/abc-problem.emal | 2 +- Task/ABC-problem/EchoLisp/abc-problem.l | 19 +- Task/ABC-problem/Elena/abc-problem.elena | 12 +- Task/ABC-problem/Euphoria/abc-problem.ex | 35 - Task/ABC-problem/FBSL/abc-problem.fbsl | 70 +- Task/ABC-problem/Fortran/abc-problem-2.f | 444 +++---- Task/ABC-problem/Go/abc-problem.go | 52 +- Task/ABC-problem/Insitux/abc-problem.insitux | 2 +- Task/ABC-problem/Lang/abc-problem.lang | 58 +- Task/ABC-problem/Lua/abc-problem.lua | 48 +- Task/ABC-problem/MAXScript/abc-problem-1.max | 168 +-- Task/ABC-problem/MAXScript/abc-problem-3.max | 52 +- Task/ABC-problem/Maple/abc-problem.maple | 34 +- Task/ABC-problem/PowerBASIC/abc-problem.basic | 2 +- Task/ABC-problem/PowerShell/abc-problem.psh | 117 -- Task/ABC-problem/Prolog/abc-problem-1.pro | 22 +- Task/ABC-problem/SNOBOL4/abc-problem.sno | 58 +- .../SenseTalk/abc-problem-1.sensetalk | 76 +- .../SenseTalk/abc-problem-2.sensetalk | 16 +- .../SequenceL/abc-problem-1.sequencel | 42 +- .../SequenceL/abc-problem-2.sequencel | 42 +- Task/ABC-problem/Smalltalk/abc-problem.st | 32 +- Task/ABC-problem/Swift/abc-problem-2.swift | 28 +- Task/ABC-problem/Tcl/abc-problem.tcl | 20 +- Task/ABC-problem/Transd/abc-problem.transd | 4 +- .../Ultimate++/abc-problem.ultimate++ | 130 +-- Task/ABC-problem/V-(Vlang)/abc-problem.v | 40 +- Task/ABC-problem/Yabasic/abc-problem.basic | 46 +- Task/ABC-problem/Zkl/abc-problem.zkl | 10 +- Task/ABC-problem/Zonnon/abc-problem.zonnon | 114 +- Task/ADFGVX-cipher/11l/adfgvx-cipher.11l | 8 +- .../11l/aks-test-for-primes.11l | 2 +- .../Ada/aks-test-for-primes.ada | 88 -- .../Elena/aks-test-for-primes.elena | 2 +- .../PowerShell/aks-test-for-primes.psh | 84 -- .../REXX/aks-test-for-primes-2.rexx | 4 +- Task/AVL-tree/Ada/avl-tree.ada | 241 ---- Task/AVL-tree/Emacs-Lisp/avl-tree.l | 212 ---- .../Ada/abbreviations-automatic.ada | 71 -- .../COBOL/abbreviations-automatic.cobol | 158 --- .../Emacs-Lisp/abbreviations-automatic.l | 36 - .../VBScript/abbreviations-automatic.vb | 36 - .../Ada/abbreviations-easy.ada | 98 -- .../Euphoria/abbreviations-easy.ex | 35 - .../PowerShell/abbreviations-easy.psh | 44 - .../Ada/abbreviations-simple.ada | 130 --- .../EasyLang/abbreviations-simple.easy | 5 +- .../VBScript/abbreviations-simple.vb | 88 -- .../11l/abelian-sandpile-model-identity.11l | 30 +- .../Ada/abelian-sandpile-model-identity-1.ada | 15 - .../Ada/abelian-sandpile-model-identity-2.ada | 85 -- .../Ada/abelian-sandpile-model-identity-3.ada | 46 - .../Java/abelian-sandpile-model-identity.java | 150 +-- .../abelian-sandpile-model-identity.pluto | 2 +- .../Red/abelian-sandpile-model-identity.red | 100 +- .../Ada/abelian-sandpile-model.ada | 67 -- .../Pluto/abelian-sandpile-model.pluto | 2 +- Task/Abstract-type/Ada/abstract-type-1.ada | 3 - Task/Abstract-type/Ada/abstract-type-2.ada | 2 - Task/Abstract-type/Ada/abstract-type-3.ada | 10 - Task/Abstract-type/COBOL/abstract-type.cobol | 68 -- Task/Abstract-type/Haxe/abstract-type-1.haxe | 44 - Task/Abstract-type/Haxe/abstract-type-2.haxe | 3 - .../PowerShell/abstract-type-1.psh | 92 -- .../PowerShell/abstract-type-2.psh | 2 - .../PowerShell/abstract-type-3.psh | 2 - .../PowerShell/abstract-type-4.psh | 2 - .../PowerShell/abstract-type-5.psh | 2 - Task/Abstract-type/REBOL/abstract-type.rebol | 44 - Task/Abstract-type/ReScript/abstract-type.re | 1 - ...ent-and-perfect-number-classifications.ada | 35 - ...-and-perfect-number-classifications.arturo | 11 +- ...t-and-perfect-number-classifications.basic | 11 - ...nt-and-perfect-number-classifications.easy | 12 +- ...t-and-perfect-number-classifications.elena | 2 +- ...t-and-perfect-number-classifications-1.psh | 33 - ...t-and-perfect-number-classifications-2.psh | 56 - ...t-and-perfect-number-classifications-3.psh | 1 - ...-and-perfect-number-classifications-2.rexx | 9 +- ...ient-and-perfect-number-classifications.vb | 23 - .../ALGOL-68/abundant-odd-numbers.alg | 2 +- .../Ada/abundant-odd-numbers.ada | 57 - .../Agena/abundant-odd-numbers.agena | 4 +- .../Arturo/abundant-odd-numbers.arturo | 6 +- .../AutoHotkey/abundant-odd-numbers-1.ahk | 32 +- .../AutoHotkey/abundant-odd-numbers-2.ahk | 30 +- .../BASIC256/abundant-odd-numbers.basic | 54 +- .../MiniScript/abundant-odd-numbers.mini | 52 +- .../Phix/abundant-odd-numbers.phix | 45 +- .../Zkl/abundant-odd-numbers-1.zkl | 14 +- .../Ada/accumulator-factory-1.ada | 11 - .../Ada/accumulator-factory-2.ada | 11 - .../Ada/accumulator-factory-3.ada | 64 -- .../Elena/accumulator-factory.elena | 8 +- .../PowerShell/accumulator-factory-1.psh | 4 - .../PowerShell/accumulator-factory-2.psh | 3 - .../REBOL/accumulator-factory-1.rebol | 11 - .../REBOL/accumulator-factory-2.rebol | 25 - .../VBScript/accumulator-factory-1.vb | 10 - .../VBScript/accumulator-factory-2.vb | 8 - .../Achilles-numbers/Ada/achilles-numbers.ada | 205 ---- .../EasyLang/achilles-numbers.easy | 31 +- .../Phix/achilles-numbers.phix | 117 +- .../Ada/ackermann-function.ada | 21 - .../AutoIt/ackermann-function-1.autoit | 11 - .../AutoIt/ackermann-function-2.autoit | 18 - .../COBOL/ackermann-function.cobol | 32 - .../Chapel/ackermann-function.chapel | 8 - .../Coq/ackermann-function-1.coq | 18 - .../Coq/ackermann-function-2.coq | 13 - .../EasyLang/ackermann-function.easy | 10 +- .../Elena/ackermann-function.elena | 10 +- .../Emacs-Lisp/ackermann-function.l | 5 - .../Euphoria/ackermann-function.ex | 16 - .../Haxe/ackermann-function.haxe | 20 - .../PowerShell/ackermann-function-1.psh | 11 - .../PowerShell/ackermann-function-2.psh | 6 - .../PowerShell/ackermann-function-3.psh | 14 - .../PowerShell/ackermann-function-4.psh | 3 - .../Python/ackermann-function-2.py | 4 +- .../REBOL/ackermann-function-1.rebol | 7 - .../REBOL/ackermann-function-2.rebol | 16 - .../REXX/ackermann-function-1.rexx | 25 - .../REXX/ackermann-function-2.rexx | 21 - .../REXX/ackermann-function-3.rexx | 36 - .../ReScript/ackermann-function.re | 15 - .../VBScript/ackermann-function-1.vb | 20 - .../VBScript/ackermann-function-2.vb | 5 - .../AutoIt/active-directory-connect.autoit | 2 - .../VBScript/active-directory-connect.vb | 4 - .../active-directory-search-for-a-user.psh | 7 - .../active-directory-search-for-a-user-1.vb | 7 - .../active-directory-search-for-a-user-2.vb | 3 - .../active-directory-search-for-a-user-3.vb | 5 - Task/Active-object/Ada/active-object.ada | 65 -- ...ariable-to-a-class-instance-at-runtime.ada | 40 - ...able-to-a-class-instance-at-runtime.arturo | 2 +- ...iable-to-a-class-instance-at-runtime.elena | 2 +- ...riable-to-a-class-instance-at-runtime.phix | 19 +- ...ariable-to-a-class-instance-at-runtime.psh | 5 - ...iable-to-a-class-instance-at-runtime.rebol | 48 - Task/Additive-primes/Ada/additive-primes.ada | 58 - .../COBOL/additive-primes.cobol | 73 -- .../Delphi/additive-primes.pas | 28 +- Task/Additive-primes/Ksh/additive-primes.ksh | 40 +- .../Langur/additive-primes.langur | 4 +- .../MiniScript/additive-primes.mini | 32 +- .../Oberon-07/additive-primes.oberon | 20 +- .../Additive-primes/Phix/additive-primes.phix | 10 +- .../REXX/additive-primes-2.rexx | 9 +- .../ARM-Assembly/address-of-a-variable.arm | 65 +- .../Ada/address-of-a-variable-1.ada | 3 - .../Ada/address-of-a-variable-2.ada | 2 - .../Ada/address-of-a-variable-3.ada | 3 - .../Argile/address-of-a-variable-1.argile | 10 +- .../Argile/address-of-a-variable-2.argile | 2 +- .../COBOL/address-of-a-variable-1.cobol | 7 - .../COBOL/address-of-a-variable-2.cobol | 17 - .../address-of-a-variable.pas | 8 +- .../address-of-a-variable.basic | 8 +- .../Delphi/address-of-a-variable-1.pas | 8 +- .../Delphi/address-of-a-variable-2.pas | 6 +- .../GDScript/address-of-a-variable.gd | 34 +- .../Go/address-of-a-variable.go | 46 +- .../address-of-a-variable.m2000 | 56 +- .../REXX/address-of-a-variable.rexx | 13 +- .../Stata/address-of-a-variable.stata | 2 +- .../V-(Vlang)/address-of-a-variable.v | 8 +- .../Emacs-Lisp/algebraic-data-types.l | 28 - .../Phix/algebraic-data-types.phix | 224 ++-- Task/Align-columns/Ada/align-columns.ada | 65 -- .../Align-columns/AutoIt/align-columns.autoit | 83 -- .../Align-columns/COBOL/align-columns-1.cobol | 83 -- .../Align-columns/COBOL/align-columns-2.cobol | 21 - Task/Align-columns/Emacs-Lisp/align-columns.l | 134 --- Task/Align-columns/Euphoria/align-columns.ex | 61 - .../PowerShell/align-columns.psh | 22 - Task/Align-columns/REBOL/align-columns.rebol | 57 - Task/Align-columns/VBScript/align-columns.vb | 62 - .../aliquot-sequence-classifications-1.psh | 34 - .../aliquot-sequence-classifications-2.psh | 63 - .../aliquot-sequence-classifications-3.psh | 90 -- .../aliquot-sequence-classifications-4.psh | 5 - .../Ada/almkvist-giullera-formula-for-pi.ada | 94 -- Task/Almost-prime/ALGOL-68/almost-prime.alg | 8 +- Task/Almost-prime/Ada/almost-prime.ada | 25 - Task/Almost-prime/Arturo/almost-prime.arturo | 24 +- Task/Almost-prime/COBOL/almost-prime.cobol | 69 -- .../FutureBasic/almost-prime.basic | 46 +- Task/Almost-prime/Phix/almost-prime.phix | 31 +- Task/Almost-prime/Pluto/almost-prime.pluto | 2 +- Task/Almost-prime/REXX/almost-prime.rexx | 10 +- Task/Almost-prime/VBScript/almost-prime.vb | 54 - Task/Amb/Ada/amb-1.ada | 70 -- Task/Amb/Ada/amb-2.ada | 78 -- Task/Amb/Elena/amb.elena | 2 +- Task/Amb/Haxe/amb.haxe | 73 -- Task/Amb/Langur/amb.langur | 4 +- Task/Amb/Phix/amb-1.phix | 76 +- Task/Amb/Phix/amb-2.phix | 131 ++- Task/Amb/VBScript/amb-1.vb | 11 - Task/Amb/VBScript/amb-2.vb | 17 - Task/Amicable-pairs/Ada/amicable-pairs.ada | 20 - .../Arturo/amicable-pairs.arturo | 17 +- .../Elena/amicable-pairs-1.elena | 2 +- .../Elena/amicable-pairs-2.elena | 2 +- .../Elena/amicable-pairs-3.elena | 2 +- Task/Amicable-pairs/MATLAB/amicable-pairs.m | 35 - Task/Amicable-pairs/Phix/amicable-pairs.phix | 12 +- .../PowerShell/amicable-pairs.psh | 29 - .../Amicable-pairs/REBOL/amicable-pairs.rebol | 16 - .../Amicable-pairs/REXX/amicable-pairs-2.rexx | 10 +- .../Amicable-pairs/ReScript/amicable-pairs.re | 25 - .../Amicable-pairs/VBScript/amicable-pairs.vb | 36 - .../Ada/anagrams-deranged-anagrams.ada | 45 - .../Arturo/anagrams-deranged-anagrams.arturo | 2 +- .../AutoHotkey/anagrams-deranged-anagrams.ahk | 96 +- .../C-sharp/anagrams-deranged-anagrams.cs | 4 +- .../C/anagrams-deranged-anagrams.c | 126 +- .../COBOL/anagrams-deranged-anagrams.cobol | 181 --- .../anagrams-deranged-anagrams.lisp | 16 +- .../EchoLisp/anagrams-deranged-anagrams-1.l | 30 +- .../Eiffel/anagrams-deranged-anagrams.e | 214 ++-- .../Erlang/anagrams-deranged-anagrams.erl | 4 +- .../GAP/anagrams-deranged-anagrams.gap | 36 +- .../Go/anagrams-deranged-anagrams.go | 72 +- .../anagrams-deranged-anagrams-2.js | 36 +- .../Jq/anagrams-deranged-anagrams.jq | 4 +- .../Lasso/anagrams-deranged-anagrams.lasso | 68 +- .../anagrams-deranged-anagrams-1.math | 4 +- .../PowerShell/anagrams-deranged-anagrams.psh | 33 - .../Prolog/anagrams-deranged-anagrams.pro | 60 +- .../anagrams-deranged-anagrams.basic | 16 +- .../Tcl/anagrams-deranged-anagrams.tcl | 16 +- .../V-(Vlang)/anagrams-deranged-anagrams.v | 54 +- .../Zkl/anagrams-deranged-anagrams-1.zkl | 8 +- .../Zkl/anagrams-deranged-anagrams-2.zkl | 2 +- Task/Anagrams/00-TASK.txt | 2 +- Task/Anagrams/Ada/anagrams.ada | 69 -- Task/Anagrams/Arturo/anagrams.arturo | 2 +- Task/Anagrams/COBOL/anagrams.cobol | 243 ---- Task/Anagrams/Elena/anagrams.elena | 2 +- Task/Anagrams/Emacs-Lisp/anagrams-1.l | 87 -- Task/Anagrams/Emacs-Lisp/anagrams-2.l | 74 -- Task/Anagrams/Euphoria/anagrams.ex | 49 - Task/Anagrams/PowerShell/anagrams-1.psh | 13 - Task/Anagrams/PowerShell/anagrams-2.psh | 43 - Task/Anagrams/VBScript/anagrams.vb | 70 -- .../angle-difference-between-two-bearings.ada | 51 - ...ngle-difference-between-two-bearings.cobol | 149 --- ...ngle-difference-between-two-bearings-1.psh | 134 --- ...ngle-difference-between-two-bearings-2.psh | 2 - ...geometric-normalization-and-conversion.ada | 226 ---- ...eometric-normalization-and-conversion.phix | 37 +- ...s-geometric-normalization-and-conversion.r | 1 + .../Ada/animate-a-pendulum-1.ada | 19 - .../Ada/animate-a-pendulum-2.ada | 38 - .../Ada/animate-a-pendulum-3.ada | 24 - .../Animate-a-pendulum/C/animate-a-pendulum.c | 104 +- .../Euphoria/animate-a-pendulum.ex | 57 - .../VBScript/animate-a-pendulum.vb | 44 - Task/Animation/Ada/animation.ada | 92 -- Task/Animation/Emacs-Lisp/animation.l | 54 - Task/Animation/REBOL/animation.rebol | 43 - .../Ada/anonymous-recursion.ada | 16 - .../AutoIt/anonymous-recursion.autoit | 15 - .../Elena/anonymous-recursion.elena | 2 +- .../REBOL/anonymous-recursion.rebol | 1 - .../8086-Assembly/anti-primes.8086 | 84 +- Task/Anti-primes/Ada/anti-primes.ada | 38 - Task/Anti-primes/BASIC256/anti-primes.basic | 30 +- Task/Anti-primes/C-sharp/anti-primes.cs | 6 +- Task/Anti-primes/COBOL/anti-primes.cobol | 84 -- Task/Anti-primes/EasyLang/anti-primes.easy | 3 +- Task/Anti-primes/Elixir/anti-primes.ex | 52 +- Task/Anti-primes/Lua/anti-primes-1.lua | 42 +- .../Nanoquery/anti-primes.nanoquery | 32 +- Task/Anti-primes/Oberon/anti-primes.oberon | 13 +- Task/Anti-primes/Odin/anti-primes.odin | 68 +- Task/Anti-primes/Pluto/anti-primes.pluto | 4 +- Task/Anti-primes/REXX/anti-primes-1.rexx | 10 +- Task/Anti-primes/REXX/anti-primes-2.rexx | 11 +- Task/Anti-primes/Zkl/anti-primes-1.zkl | 4 +- ...end-a-record-to-the-end-of-a-text-file.ada | 120 -- ...d-a-record-to-the-end-of-a-text-file.cobol | 272 ----- ...d-a-record-to-the-end-of-a-text-file-1.psh | 163 --- ...d-a-record-to-the-end-of-a-text-file-2.psh | 25 - ...d-a-record-to-the-end-of-a-text-file-3.psh | 1 - ...d-a-record-to-the-end-of-a-text-file-4.psh | 4 - ...d-a-record-to-the-end-of-a-text-file-5.psh | 1 - ...d-a-record-to-the-end-of-a-text-file-6.psh | 11 - ...d-a-record-to-the-end-of-a-text-file-7.psh | 1 - ...d-a-record-to-the-end-of-a-text-file-8.psh | 4 - ...d-a-record-to-the-end-of-a-text-file-9.psh | 1 - .../Ada/apply-a-callback-to-an-array.ada | 37 - .../apply-a-callback-to-an-array.bracmat | 29 - .../COBOL/apply-a-callback-to-an-array.cobol | 20 - .../Elena/apply-a-callback-to-an-array.elena | 2 +- .../Euphoria/apply-a-callback-to-an-array.ex | 18 - .../Haxe/apply-a-callback-to-an-array.haxe | 10 - .../apply-a-callback-to-an-array-1.psh | 1 - .../apply-a-callback-to-an-array-2.psh | 4 - .../REBOL/apply-a-callback-to-an-array.rebol | 26 - .../REXX/apply-a-callback-to-an-array.rexx | 73 +- .../apply-a-callback-to-an-array-1.vb | 16 - .../apply-a-callback-to-an-array-2.vb | 13 - ...ital-filter-direct-form-ii-transposed-.ada | 60 - .../Ada/approximate-equality.ada | 46 - .../ReScript/approximate-equality.re | 19 - ...arbitrary-precision-integers-included-.ada | 16 - ...bitrary-precision-integers-included-.cobol | 133 --- ...arbitrary-precision-integers-included--1.l | 10 - ...arbitrary-precision-integers-included--2.l | 9 - ...bitrary-precision-integers-included-.m2000 | 13 +- ...bitrary-precision-integers-included-.pluto | 7 +- ...arbitrary-precision-integers-included-.psh | 9 - ...itrary-precision-integers-included--1.rexx | 15 - ...itrary-precision-integers-included--2.rexx | 22 - ...arbitrary-precision-integers-included-.tcl | 7 - .../Ada/archimedean-spiral.ada | 77 -- .../Ada/arena-storage-pool-1.ada | 2 - .../Ada/arena-storage-pool-2.ada | 27 - .../Ada/arena-storage-pool-3.ada | 22 - .../Ada/arena-storage-pool-4.ada | 15 - .../Phix/arena-storage-pool-1.phix | 6 +- .../Phix/arena-storage-pool-2.phix | 28 +- .../Ada/arithmetic-complex.ada | 47 - .../COBOL/arithmetic-complex-1.cobol | 14 - .../COBOL/arithmetic-complex-2.cobol | 98 -- .../Euphoria/arithmetic-complex.ex | 58 - .../Langur/arithmetic-complex.langur | 3 +- .../Phix/arithmetic-complex.phix | 40 +- .../PowerShell/arithmetic-complex-1.psh | 39 - .../PowerShell/arithmetic-complex-2.psh | 16 - .../REXX/arithmetic-complex.rexx | 4 +- .../Ada/arithmetic-integer.ada | 20 - .../Batch-File/arithmetic-integer.bat | 13 +- .../COBOL/arithmetic-integer.cobol | 44 - .../Elena/arithmetic-integer.elena | 2 +- .../Euphoria/arithmetic-integer.ex | 13 - .../Haxe/arithmetic-integer.haxe | 16 - .../OPL/arithmetic-integer.opl | 3 + .../PowerShell/arithmetic-integer-1.psh | 9 - .../PowerShell/arithmetic-integer-2.psh | 1 - .../REBOL/arithmetic-integer.rebol | 51 - .../REXX/arithmetic-integer.rexx | 42 +- .../ReScript/arithmetic-integer.re | 14 - .../VBScript/arithmetic-integer-1.vb | 17 - .../VBScript/arithmetic-integer-2.vb | 14 - .../Arturo/arithmetic-rational.arturo | 2 +- .../REXX/arithmetic-rational.rexx | 4 +- .../Ada/arithmetic-derivative.ada | 55 - .../R/arithmetic-derivative.r | 40 +- .../AutoHotkey/arithmetic-evaluation-1.ahk | 6 +- .../Clojure/arithmetic-evaluation.clj | 30 +- .../Elena/arithmetic-evaluation.elena | 4 +- .../Emacs-Lisp/arithmetic-evaluation.l | 93 -- .../Jq/arithmetic-evaluation-4.jq | 2 +- .../Lua/arithmetic-evaluation.lua | 20 +- .../arithmetic-evaluation-2.m2000 | 164 +-- .../MiniScript/arithmetic-evaluation.mini | 84 +- .../Python/arithmetic-evaluation-1.py | 4 +- .../Red/arithmetic-evaluation.red | 11 +- .../Standard-ML/arithmetic-evaluation.ml | 32 +- .../Tcl/arithmetic-evaluation.tcl | 4 +- ...arithmetic-geometric-mean-calculate-pi.ada | 34 - .../Ada/arithmetic-geometric-mean.ada | 26 - .../Arturo/arithmetic-geometric-mean.arturo | 6 +- .../COBOL/arithmetic-geometric-mean.cobol | 33 - .../PowerShell/arithmetic-geometric-mean.psh | 14 - .../VBScript/arithmetic-geometric-mean.vb | 10 - .../Ada/arithmetic-numbers.ada | 64 -- .../EasyLang/arithmetic-numbers.easy | 32 +- .../Phix/arithmetic-numbers.phix | 47 +- .../REXX/arithmetic-numbers.rexx | 9 +- .../VBScript/arithmetic-numbers.vb | 46 - .../Ada/array-concatenation.ada | 3 - .../AutoIt/array-concatenation.autoit | 18 - .../COBOL/array-concatenation.cobol | 47 - .../Elena/array-concatenation.elena | 6 +- .../Emacs-Lisp/array-concatenation.l | 2 - .../Euphoria/array-concatenation.ex | 5 - .../PowerShell/array-concatenation.psh | 5 - .../REBOL/array-concatenation.rebol | 7 - .../REXX/array-concatenation.rexx | 8 +- .../ReScript/array-concatenation.re | 1 - .../VBScript/array-concatenation.vb | 18 - Task/Array-length/Ada/array-length.ada | 16 - Task/Array-length/AutoIt/array-length.autoit | 9 - Task/Array-length/COBOL/array-length.cobol | 40 - Task/Array-length/Emacs-Lisp/array-length.l | 2 - Task/Array-length/Euphoria/array-length.ex | 18 - .../M2000-Interpreter/array-length.m2000 | 33 +- Task/Array-length/PowerShell/array-length.psh | 3 - Task/Array-length/REBOL/array-length.rebol | 2 - Task/Array-length/ReScript/array-length-1.re | 3 - Task/Array-length/ReScript/array-length-2.re | 14 - Task/Array-length/VBScript/array-length.vb | 2 - Task/Arrays/00-TASK.txt | 5 +- Task/Arrays/ALGOL-68/arrays.alg | 32 +- Task/Arrays/Ada/arrays.ada | 44 - Task/Arrays/AutoIt/arrays.autoit | 14 - Task/Arrays/COBOL/arrays.cobol | 39 - Task/Arrays/Euphoria/arrays.ex | 29 - Task/Arrays/Haxe/arrays.haxe | 22 - Task/Arrays/OPL/arrays.opl | 3 +- Task/Arrays/PowerShell/arrays-1.psh | 1 - Task/Arrays/PowerShell/arrays-2.psh | 2 - Task/Arrays/PowerShell/arrays-3.psh | 1 - Task/Arrays/PowerShell/arrays-4.psh | 1 - Task/Arrays/PowerShell/arrays-5.psh | 1 - Task/Arrays/PowerShell/arrays-6.psh | 1 - Task/Arrays/PowerShell/arrays-7.psh | 1 - Task/Arrays/PowerShell/arrays-8.psh | 1 - Task/Arrays/PowerShell/arrays-9.psh | 1 - Task/Arrays/REBOL/arrays-1.rebol | 2 - Task/Arrays/REBOL/arrays-2.rebol | 2 - Task/Arrays/REBOL/arrays-3.rebol | 4 - Task/Arrays/REBOL/arrays-4.rebol | 10 - Task/Arrays/REXX/arrays.rexx | 61 +- Task/Arrays/ReScript/arrays.re | 7 - Task/Arrays/VBScript/arrays.vb | 45 - Task/Arrays/VHDL/arrays.vhdl | 57 - .../Ascending-primes/Ada/ascending-primes.ada | 62 - .../Arturo/ascending-primes.arturo | 2 +- Task/Assertions/Ada/assertions-1.ada | 1 - Task/Assertions/Ada/assertions-2.ada | 3 - Task/Assertions/Ada/assertions-3.ada | 10 - Task/Assertions/Emacs-Lisp/assertions.l | 3 - Task/Assertions/Euphoria/assertions.ex | 7 - Task/Assertions/REXX/assertions-2.rexx | 27 +- Task/Assertions/VBScript/assertions-1.vb | 5 - Task/Assertions/VBScript/assertions-2.vb | 3 - Task/Assertions/VBScript/assertions-3.vb | 2 - .../Ada/associative-array-creation.ada | 33 - .../AutoIt/associative-array-creation.autoit | 127 -- .../Chapel/associative-array-creation.chapel | 29 - .../Elena/associative-array-creation-1.elena | 4 +- .../Elena/associative-array-creation-2.elena | 2 +- .../Emacs-Lisp/associative-array-creation-1.l | 2 - .../Emacs-Lisp/associative-array-creation-2.l | 2 - .../Haxe/associative-array-creation.haxe | 7 - .../Logo/associative-array-creation.logo | 6 - .../associative-array-creation-1.psh | 1 - .../associative-array-creation-2.psh | 4 - .../associative-array-creation-3.psh | 4 - .../associative-array-creation-4.psh | 20 - .../associative-array-creation-5.psh | 2 - .../associative-array-creation-6.psh | 4 - .../REXX/associative-array-creation.rexx | 17 +- .../V-(Vlang)/associative-array-creation.v | 5 +- .../Ada/associative-array-iteration.ada | 19 - .../Chapel/associative-array-iteration.chapel | 10 - .../Elena/associative-array-iteration.elena | 2 +- .../Haxe/associative-array-iteration.haxe | 18 - .../Lua/associative-array-iteration.lua | 16 +- .../associative-array-iteration-1.psh | 1 - .../associative-array-iteration-2.psh | 1 - .../associative-array-iteration-3.psh | 3 - .../associative-array-iteration-4.psh | 5 - .../associative-array-iteration-5.psh | 5 - .../REXX/associative-array-iteration.rexx | 18 +- .../VBScript/associative-array-iteration.vb | 12 - .../Ada/associative-array-merging.ada | 69 -- .../REXX/associative-array-merging.rexx | 7 +- .../Tcl/associative-array-merging.tcl | 5 - .../VBScript/associative-array-merging.vb | 29 - Task/Atomic-updates/Ada/atomic-updates.ada | 85 -- .../Atomic-updates/Euphoria/atomic-updates.ex | 69 -- .../Ada/attractive-numbers.ada | 67 -- .../COBOL/attractive-numbers.cobol | 88 -- .../Ada/average-loop-length.ada | 53 - .../EasyLang/average-loop-length.easy | 14 +- .../Phix/average-loop-length.phix | 60 +- .../PowerShell/average-loop-length-1.psh | 59 - .../PowerShell/average-loop-length-2.psh | 12 - .../VBScript/average-loop-length.vb | 48 - .../Ada/averages-arithmetic-mean.ada | 22 - .../COBOL/averages-arithmetic-mean-1.cobol | 1 - .../COBOL/averages-arithmetic-mean-2.cobol | 28 - .../Elena/averages-arithmetic-mean.elena | 2 +- .../Emacs-Lisp/averages-arithmetic-mean-1.l | 3 - .../Emacs-Lisp/averages-arithmetic-mean-2.l | 2 - .../Euphoria/averages-arithmetic-mean.ex | 16 - .../PowerShell/averages-arithmetic-mean-1.psh | 11 - .../PowerShell/averages-arithmetic-mean-2.psh | 7 - .../REBOL/averages-arithmetic-mean.rebol | 19 - .../ReScript/averages-arithmetic-mean.re | 7 - .../VBScript/averages-arithmetic-mean.vb | 11 - .../Ada/averages-mean-angle.ada | 34 - .../Euphoria/averages-mean-angle.ex | 26 - .../Phix/averages-mean-angle.phix | 32 +- .../PowerShell/averages-mean-angle-1.psh | 7 - .../PowerShell/averages-mean-angle-2.psh | 1 - .../Scheme/averages-mean-angle.scm | 23 - .../Ada/averages-mean-time-of-day.ada | 79 -- .../Euphoria/averages-mean-time-of-day.ex | 63 - .../Phix/averages-mean-time-of-day.phix | 62 +- .../averages-mean-time-of-day-1.psh | 66 -- .../averages-mean-time-of-day-2.psh | 2 - Task/Averages-Median/Ada/averages-median.ada | 31 - .../COBOL/averages-median.cobol | 1 - .../Elena/averages-median.elena | 2 +- .../Euphoria/averages-median.ex | 25 - .../PowerShell/averages-median-1.psh | 69 -- .../PowerShell/averages-median-2.psh | 2 - .../PowerShell/averages-median-3.psh | 1 - .../REBOL/averages-median.rebol | 15 - .../ReScript/averages-median.re | 24 - Task/Averages-Mode/Ada/averages-mode-1.ada | 8 - Task/Averages-Mode/Ada/averages-mode-2.ada | 102 -- Task/Averages-Mode/Ada/averages-mode-3.ada | 26 - .../Averages-Mode/Arturo/averages-mode.arturo | 2 +- Task/Averages-Mode/Elena/averages-mode.elena | 2 +- Task/Averages-Mode/Euphoria/averages-mode.ex | 39 - Task/Averages-Mode/Phix/averages-mode.phix | 79 +- .../PowerShell/averages-mode.psh | 3 - .../Ada/averages-pythagorean-means-1.ada | 6 - .../Ada/averages-pythagorean-means-2.ada | 33 - .../Ada/averages-pythagorean-means-3.ada | 13 - .../Euphoria/averages-pythagorean-means.ex | 52 - .../PowerShell/averages-pythagorean-means.psh | 23 - .../VBScript/averages-pythagorean-means.vb | 27 - .../Ada/averages-root-mean-square.ada | 20 - .../COBOL/averages-root-mean-square.cobol | 21 - .../Elena/averages-root-mean-square.elena | 2 +- .../Emacs-Lisp/averages-root-mean-square.l | 5 - .../Euphoria/averages-root-mean-square.ex | 14 - .../PowerShell/averages-root-mean-square.psh | 6 - .../Ada/averages-simple-moving-average-1.ada | 8 - .../Ada/averages-simple-moving-average-2.ada | 40 - .../Ada/averages-simple-moving-average-3.ada | 19 - .../averages-simple-moving-average.elena | 2 +- .../averages-simple-moving-average-1.phix | 53 - .../averages-simple-moving-average-2.phix | 14 - .../averages-simple-moving-average.psh | 26 - .../averages-simple-moving-average.vb | 37 - .../Ada/b-zier-curves-intersections.ada | 934 --------------- .../ARM-Assembly/babbage-problem.arm | 2 +- Task/Babbage-problem/Ada/babbage-problem.ada | 54 - .../Arturo/babbage-problem.arturo | 2 +- .../AutoHotkey/babbage-problem.ahk | 4 +- .../AutoLISP/babbage-problem.l | 54 - .../BASIC256/babbage-problem.basic | 2 +- Task/Babbage-problem/C/babbage-problem.c | 26 +- .../COBOL/babbage-problem.cobol | 32 - .../Component-Pascal/babbage-problem.pas | 12 +- .../Craft-Basic/babbage-problem.basic | 9 +- .../Babbage-problem/Dart/babbage-problem.dart | 10 +- .../Dyalect/babbage-problem-1.dyalect | 2 +- .../Dyalect/babbage-problem-2.dyalect | 8 +- .../Elena/babbage-problem.elena | 2 +- .../Erlang/babbage-problem.erl | 10 +- .../Frink/babbage-problem.frink | 2 +- Task/Babbage-problem/Go/babbage-problem.go | 28 +- .../Limbo/babbage-problem.limbo | 18 +- .../MAXScript/babbage-problem.max | 8 +- .../Nanoquery/babbage-problem.nanoquery | 2 +- .../Babbage-problem/NewLISP/babbage-problem.l | 10 +- .../PowerShell/babbage-problem-1.psh | 45 - .../PowerShell/babbage-problem-2.psh | 24 - .../Prolog/babbage-problem-1.pro | 16 +- .../Prolog/babbage-problem-2.pro | 12 +- .../Scala/babbage-problem-1.scala | 6 +- .../SenseTalk/babbage-problem.sensetalk | 12 +- .../SequenceL/babbage-problem.sequencel | 2 +- .../Swift/babbage-problem.swift | 8 +- .../UNIX-Shell/babbage-problem-2.sh | 48 +- .../V-(Vlang)/babbage-problem.v | 16 +- .../VBScript/babbage-problem.vb | 25 - .../babbage-problem.vedit | 4 +- .../XBasic/babbage-problem.basic | 18 +- .../Yabasic/babbage-problem.basic | 2 +- .../Ada/babylonian-spiral.ada | 136 --- .../EasyLang/babylonian-spiral.easy | 76 +- .../AWK/balanced-brackets.awk | 8 +- .../Ada/balanced-brackets.ada | 57 - .../Arturo/balanced-brackets.arturo | 9 +- .../AutoHotkey/balanced-brackets-1.ahk | 46 +- .../AutoHotkey/balanced-brackets-2.ahk | 32 +- .../AutoIt/balanced-brackets.autoit | 28 - .../AutoLISP/balanced-brackets.l | 12 - .../C-sharp/balanced-brackets-2.cs | 42 +- .../Balanced-brackets/C/balanced-brackets-1.c | 16 +- .../COBOL/balanced-brackets.cobol | 98 -- .../Clojure/balanced-brackets-1.clj | 8 +- .../Component-Pascal/balanced-brackets.pas | 72 +- .../EasyLang/balanced-brackets.easy | 4 +- .../EchoLisp/balanced-brackets.l | 23 +- .../Elena/balanced-brackets.elena | 2 +- .../Erlang/balanced-brackets.erl | 14 +- .../Euphoria/balanced-brackets.ex | 45 - .../GDScript/balanced-brackets.gd | 56 +- .../Java/balanced-brackets-2.java | 116 +- .../Java/balanced-brackets.java | 22 +- .../M2000-Interpreter/balanced-brackets.m2000 | 46 +- .../Mercury/balanced-brackets.mercury | 8 +- .../MiniScript/balanced-brackets-1.mini | 14 +- .../MiniScript/balanced-brackets-2.mini | 6 +- .../Nanoquery/balanced-brackets.nanoquery | 44 +- .../Balanced-brackets/Nu/balanced-brackets.nu | 10 +- .../PowerShell/balanced-brackets-1.psh | 18 - .../PowerShell/balanced-brackets-2.psh | 8 - .../PowerShell/balanced-brackets-3.psh | 57 - .../Prolog/balanced-brackets.pro | 62 +- .../Red/balanced-brackets.red | 12 +- .../Stata/balanced-brackets.stata | 10 +- .../Tcl/balanced-brackets-1.tcl | 16 +- .../Tcl/balanced-brackets-2.tcl | 4 +- .../VBScript/balanced-brackets-1.vb | 36 - .../VBScript/balanced-brackets-2.vb | 40 - .../XBS/balanced-brackets.xbs | 16 +- .../Balanced-brackets/Ya/balanced-brackets.ya | 56 +- .../Yabasic/balanced-brackets.basic | 2 +- .../Ada/balanced-ternary-1.ada | 47 - .../Ada/balanced-ternary-2.ada | 181 --- .../Ada/balanced-ternary-3.ada | 19 - Task/Barnsley-fern/Ada/barnsley-fern.ada | 94 -- .../Barnsley-fern/EasyLang/barnsley-fern.easy | 5 +- Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.l | 54 - .../Ada/base64-decode-data.ada | 14 - .../Haxe/base64-decode-data.haxe | 9 - .../base64-decode-data-1.m2000 | 2 +- .../Swift/base64-decode-data.swift | 2 +- .../Zkl/base64-decode-data-1.zkl | 2 +- .../ANSI-BASIC/bell-numbers.basic | 6 +- Task/Bell-numbers/Ada/bell-numbers.ada | 59 - Task/Bell-numbers/Pascal/bell-numbers.pas | 121 -- Task/Benfords-law/Ada/benfords-law-1.ada | 49 - Task/Benfords-law/Ada/benfords-law-2.ada | 1 - Task/Benfords-law/EasyLang/benfords-law.easy | 9 +- Task/Benfords-law/PowerShell/benfords-law.psh | 16 - .../Ada/bernoulli-numbers.ada | 32 - .../REXX/bernoulli-numbers.rexx | 16 +- Task/Best-shuffle/Ada/best-shuffle.ada | 50 - Task/Best-shuffle/Elena/best-shuffle.elena | 2 +- .../PowerShell/best-shuffle-1.psh | 52 - .../PowerShell/best-shuffle-2.psh | 6 - Task/Best-shuffle/VBScript/best-shuffle.vb | 52 - Task/Bifid-cipher/Ada/bifid-cipher.ada | 30 - Task/Bifid-cipher/Jq/bifid-cipher-2.jq | 2 +- Task/Bifid-cipher/Phix/bifid-cipher.phix | 76 +- .../Ada/bin-given-limits-1.ada | 8 - .../Ada/bin-given-limits-2.ada | 69 -- .../Ada/bin-given-limits-3.ada | 34 - .../Phix/bin-given-limits.phix | 76 +- Task/Binary-digits/Ada/binary-digits.ada | 13 - .../Binary-digits/Arturo/binary-digits.arturo | 6 +- .../Binary-digits/AutoIt/binary-digits.autoit | 15 - Task/Binary-digits/C++/binary-digits-2.cpp | 18 +- Task/Binary-digits/C++/binary-digits-3.cpp | 8 - Task/Binary-digits/C++/binary-digits-4.cpp | 7 - Task/Binary-digits/C++/binary-digits-5.cpp | 11 - .../Binary-digits/COBOL/binary-digits-1.cobol | 26 - .../Binary-digits/COBOL/binary-digits-2.cobol | 27 - Task/Binary-digits/Elena/binary-digits.elena | 2 +- Task/Binary-digits/Emacs-Lisp/binary-digits.l | 10 - .../Binary-digits/Euphoria/binary-digits-1.ex | 13 - .../Binary-digits/Euphoria/binary-digits-2.ex | 16 - Task/Binary-digits/Haxe/binary-digits.haxe | 15 - .../PowerShell/binary-digits.psh | 1 - Task/Binary-digits/REXX/binary-digits-1.rexx | 11 - Task/Binary-digits/REXX/binary-digits-2.rexx | 11 - Task/Binary-digits/REXX/binary-digits-3.rexx | 10 - Task/Binary-digits/REXX/binary-digits-4.rexx | 14 - Task/Binary-digits/VBScript/binary-digits.vb | 23 - Task/Binary-search/Ada/binary-search-1.ada | 54 - Task/Binary-search/Ada/binary-search-2.ada | 56 - .../Binary-search/Arturo/binary-search.arturo | 13 +- Task/Binary-search/COBOL/binary-search.cobol | 18 - .../Binary-search/Chapel/binary-search.chapel | 19 - Task/Binary-search/Emacs-Lisp/binary-search.l | 10 - .../Binary-search/Euphoria/binary-search-1.ex | 16 - .../Binary-search/Euphoria/binary-search-2.ex | 17 - .../PowerShell/binary-search-1.psh | 66 -- .../PowerShell/binary-search-2.psh | 4 - Task/Binary-search/Rust/binary-search.rs | 14 +- Task/Binary-search/VBScript/binary-search.vb | 27 - Task/Binary-strings/Ada/binary-strings-1.ada | 17 - Task/Binary-strings/Ada/binary-strings-2.ada | 3 - Task/Binary-strings/Ada/binary-strings-3.ada | 4 - .../Arturo/binary-strings.arturo | 4 +- Task/Binary-strings/Phix/binary-strings.phix | 52 +- .../PowerShell/binary-strings.psh | 67 -- .../Ada/bioinformatics-sequence-mutation.ada | 117 -- .../bioinformatics-sequence-mutation.arturo | 20 +- Task/Bioinformatics-base-count/00-TASK.txt | 23 +- .../11l/bioinformatics-base-count.11l | 33 - .../bioinformatics-base-count.aarch64 | 239 ---- .../ALGOL-68/bioinformatics-base-count.alg | 114 -- .../APL/bioinformatics-base-count.apl | 10 - .../bioinformatics-base-count.arm | 205 ---- .../AWK/bioinformatics-base-count.awk | 42 - .../Action-/bioinformatics-base-count.action | 67 -- .../Ada/bioinformatics-base-count.ada | 64 -- .../Arturo/bioinformatics-base-count-1.arturo | 33 - .../Arturo/bioinformatics-base-count-2.arturo | 20 - .../BBC-BASIC/bioinformatics-base-count.basic | 27 - .../C++/bioinformatics-base-count.cpp | 63 - .../C/bioinformatics-base-count.c | 36 - .../Delphi/bioinformatics-base-count.pas | 89 -- .../DuckDB/bioinformatics-base-count.duckdb | 18 - .../EasyLang/bioinformatics-base-count.easy | 33 - .../Ed/bioinformatics-base-count.ed | 53 - .../Factor/bioinformatics-base-count.factor | 29 - .../Forth/bioinformatics-base-count.fth | 35 - .../FreeBASIC/bioinformatics-base-count.basic | 49 - .../bioinformatics-base-count.basic | 45 - .../Go/bioinformatics-base-count.go | 49 - .../Haskell/bioinformatics-base-count.hs | 40 - .../J/bioinformatics-base-count-1.j | 12 - .../J/bioinformatics-base-count-2.j | 33 - .../Java/bioinformatics-base-count-1.java | 39 - .../Java/bioinformatics-base-count-2.java | 47 - .../JavaScript/bioinformatics-base-count.js | 67 -- .../Jq/bioinformatics-base-count-1.jq | 5 - .../Jq/bioinformatics-base-count-2.jq | 15 - .../Jq/bioinformatics-base-count-3.jq | 1 - .../Jq/bioinformatics-base-count-4.jq | 17 - .../Jq/bioinformatics-base-count-5.jq | 42 - .../Jq/bioinformatics-base-count-6.jq | 23 - .../Julia/bioinformatics-base-count.jl | 39 - .../Kotlin/bioinformatics-base-count.kts | 20 - .../bioinformatics-base-count.lambdatalk | 22 - .../Lua/bioinformatics-base-count.lua | 27 - .../bioinformatics-base-count.m2000 | 39 - .../MATLAB/bioinformatics-base-count.m | 13 - .../bioinformatics-base-count.math | 14 - .../Nim/bioinformatics-base-count.nim | 59 - .../Pascal/bioinformatics-base-count-1.pas | 77 -- .../Pascal/bioinformatics-base-count-2.pas | 106 -- .../bioinformatics-base-count.pas | 14 - .../Perl/bioinformatics-base-count.pl | 28 - .../Phix/bioinformatics-base-count.phix | 24 - .../Picat/bioinformatics-base-count.picat | 31 - .../PicoLisp/bioinformatics-base-count.l | 15 - .../PureBasic/bioinformatics-base-count.basic | 32 - .../Python/bioinformatics-base-count-1.py | 33 - .../Python/bioinformatics-base-count-2.py | 54 - .../Python/bioinformatics-base-count-3.py | 153 --- .../bioinformatics-base-count.quackery | 50 - .../R/bioinformatics-base-count.r | 42 - .../REXX/bioinformatics-base-count.rexx | 36 - .../Racket/bioinformatics-base-count.rkt | 55 - .../Raku/bioinformatics-base-count.raku | 21 - .../Ring/bioinformatics-base-count.ring | 39 - .../Ruby/bioinformatics-base-count.rb | 23 - .../Rust/bioinformatics-base-count.rs | 38 - .../Swift/bioinformatics-base-count.swift | 22 - .../Tcl/bioinformatics-base-count.tcl | 28 - .../Uxntal/bioinformatics-base-count.uxnatl | 80 -- .../V-(Vlang)/bioinformatics-base-count.v | 37 - .../VBScript/bioinformatics-base-count.vb | 31 - .../Wren/bioinformatics-base-count.wren | 38 - .../XPL0/bioinformatics-base-count.xpl0 | 35 - .../Zkl/bioinformatics-base-count.zkl | 19 - Task/Biorhythms/11l/biorhythms.11l | 2 +- Task/Biorhythms/Ada/biorhythms.ada | 65 -- Task/Biorhythms/COBOL/biorhythms-1.cobol | 144 --- Task/Biorhythms/COBOL/biorhythms-2.cobol | 9 - Task/Biorhythms/Emacs-Lisp/biorhythms.l | 15 - Task/Biorhythms/V-(Vlang)/biorhythms.v | 8 +- .../Ada/bitcoin-address-validation.ada | 128 --- .../Ada/bitmap-b-zier-curves-cubic-1.ada | 24 - .../Ada/bitmap-b-zier-curves-cubic-2.ada | 5 - .../Ada/bitmap-b-zier-curves-quadratic-1.ada | 23 - .../Ada/bitmap-b-zier-curves-quadratic-2.ada | 5 - .../bitmap-bresenhams-line-algorithm-1.ada | 40 - .../bitmap-bresenhams-line-algorithm-2.ada | 8 - .../bitmap-bresenhams-line-algorithm.autoit | 23 - .../bitmap-bresenhams-line-algorithm.ex | 115 -- .../bitmap-bresenhams-line-algorithm.pluto | 27 - .../bitmap-bresenhams-line-algorithm.vb | 53 - .../Ada/bitmap-flood-fill-1.ada | 106 -- .../Ada/bitmap-flood-fill-2.ada | 19 - .../Ada/bitmap-histogram-1.ada | 17 - .../Ada/bitmap-histogram-2.ada | 17 - .../Ada/bitmap-histogram-3.ada | 22 - .../bitmap-midpoint-circle-algorithm-1.ada | 35 - .../bitmap-midpoint-circle-algorithm-2.ada | 5 - .../bitmap-midpoint-circle-algorithm.pluto | 33 - .../Ada/bitmap-read-a-ppm-file-1.ada | 70 -- .../Ada/bitmap-read-a-ppm-file-2.ada | 9 - .../Euphoria/bitmap-read-a-ppm-file-1.ex | 41 - .../Euphoria/bitmap-read-a-ppm-file-2.ex | 5 - .../Ada/bitmap-write-a-ppm-file.ada | 29 - .../Euphoria/bitmap-write-a-ppm-file-1.ex | 15 - .../Euphoria/bitmap-write-a-ppm-file-2.ex | 14 - Task/Bitmap/Ada/bitmap-1.ada | 17 - Task/Bitmap/Ada/bitmap-2.ada | 20 - Task/Bitmap/Ada/bitmap-3.ada | 7 - Task/Bitmap/Crystal/bitmap.cr | 36 - Task/Bitmap/Euphoria/bitmap.ex | 23 - Task/Bitmap/Pluto/bitmap.pluto | 23 - Task/Bitwise-IO/Ada/bitwise-io-1.ada | 20 - Task/Bitwise-IO/Ada/bitwise-io-2.ada | 33 - Task/Bitwise-IO/Ada/bitwise-io-3.ada | 33 - .../Ada/bitwise-operations.ada | 23 - .../AutoIt/bitwise-operations.autoit | 12 - .../COBOL/bitwise-operations-1.cobol | 55 - .../COBOL/bitwise-operations-2.cobol | 41 - .../Elena/bitwise-operations.elena | 2 +- .../PowerShell/bitwise-operations-1.psh | 4 - .../PowerShell/bitwise-operations-2.psh | 6 - Task/Blum-integer/Ada/blum-integer.ada | 89 -- Task/Boolean-values/Ada/boolean-values.ada | 1 - .../Arturo/boolean-values.arturo | 6 +- .../COBOL/boolean-values-1.cobol | 1 - .../COBOL/boolean-values-2.cobol | 4 - .../COBOL/boolean-values-3.cobol | 28 - Task/Boolean-values/Crystal/boolean-values.cr | 2 +- Task/Boolean-values/Haxe/boolean-values.haxe | 8 - .../PowerShell/boolean-values.psh | 2 - .../Boolean-values/VBScript/boolean-values.vb | 6 - Task/Box-the-compass/11l/box-the-compass.11l | 2 +- Task/Box-the-compass/Ada/box-the-compass.ada | 66 -- .../AutoIt/box-the-compass.autoit | 18 - .../COBOL/box-the-compass.cobol | 67 -- .../Euphoria/box-the-compass.ex | 23 - .../Box-the-compass/Icon/box-the-compass.icon | 8 +- .../Phix/box-the-compass-1.phix | 86 +- .../Phix/box-the-compass-2.phix | 34 +- .../PowerShell/box-the-compass-1.psh | 16 - .../PowerShell/box-the-compass-2.psh | 23 - .../Ada/boyer-moore-string-search.ada | 63 - .../Emacs-Lisp/boyer-moore-string-search.l | 81 -- .../Phix/boyer-moore-string-search.phix | 202 ++-- Task/Brace-expansion/Ada/brace-expansion.ada | 58 - .../PowerShell/brace-expansion-1.psh | 55 - .../PowerShell/brace-expansion-2.psh | 14 - .../Arturo/brazilian-numbers.arturo | 6 +- .../Pascal/brazilian-numbers.pas | 292 ----- .../Phix/brazilian-numbers.phix | 104 +- .../Ada/break-oo-privacy-1.ada | 10 - .../Ada/break-oo-privacy-2.ada | 16 - .../Ada/break-oo-privacy-3.ada | 5 - .../Ada/break-oo-privacy-4.ada | 6 - .../Ada/break-oo-privacy-5.ada | 11 - .../Phix/break-oo-privacy.phix | 32 +- .../Ada/brilliant-numbers.ada | 56 - .../Arturo/brilliant-numbers.arturo | 2 +- .../EasyLang/brilliant-numbers.easy | 2 +- .../Brilliant-numbers/Go/brilliant-numbers.go | 2 +- .../Phix/brilliant-numbers.phix | 126 +- Task/Brownian-tree/Ada/brownian-tree.ada | 125 -- Task/Brownian-tree/Scheme/brownian-tree.scm | 108 -- .../Ada/bulls-and-cows-player.ada | 210 ---- .../AutoHotkey/bulls-and-cows-player.ahk | 158 +-- .../C++/bulls-and-cows-player.cpp | 100 +- .../C/bulls-and-cows-player-1.c | 106 +- .../Common-Lisp/bulls-and-cows-player.lisp | 6 +- .../Euphoria/bulls-and-cows-player.ex | 84 -- .../Haskell/bulls-and-cows-player-1.hs | 20 +- .../Lua/bulls-and-cows-player.lua | 152 +-- .../Mathematica/bulls-and-cows-player.math | 22 +- .../Prolog/bulls-and-cows-player-1.pro | 84 +- .../Prolog/bulls-and-cows-player-2.pro | 34 +- .../Raku/bulls-and-cows-player.raku | 48 +- .../Red/bulls-and-cows-player.red | 6 +- .../SenseTalk/bulls-and-cows-player.sensetalk | 236 ++-- .../Tcl/bulls-and-cows-player.tcl | 32 +- .../Yabasic/bulls-and-cows-player.basic | 10 +- .../8080-Assembly/bulls-and-cows.8080 | 374 +++--- Task/Bulls-and-cows/APL/bulls-and-cows-1.apl | 14 +- Task/Bulls-and-cows/Ada/bulls-and-cows.ada | 53 - .../AppleScript/bulls-and-cows.applescript | 88 +- .../Arturo/bulls-and-cows.arturo | 12 +- .../AutoHotkey/bulls-and-cows.ahk | 66 +- Task/Bulls-and-cows/C/bulls-and-cows-2.c | 2 +- Task/Bulls-and-cows/Eiffel/bulls-and-cows.e | 196 ++-- .../Bulls-and-cows/Elena/bulls-and-cows.elena | 2 +- .../Emacs-Lisp/bulls-and-cows.l | 132 --- .../Bulls-and-cows/Euphoria/bulls-and-cows.ex | 103 -- .../Factor/bulls-and-cows-1.factor | 23 +- Task/Bulls-and-cows/J/bulls-and-cows-1.j | 5 +- Task/Bulls-and-cows/J/bulls-and-cows-2.j | 15 +- Task/Bulls-and-cows/J/bulls-and-cows-3.j | 25 +- Task/Bulls-and-cows/J/bulls-and-cows-4.j | 40 +- Task/Bulls-and-cows/Java/bulls-and-cows.java | 90 +- Task/Bulls-and-cows/Julia/bulls-and-cows-1.jl | 60 +- Task/Bulls-and-cows/K/bulls-and-cows.k | 7 - .../Bulls-and-cows/Lasso/bulls-and-cows.lasso | 72 +- Task/Bulls-and-cows/Lua/bulls-and-cows-2.lua | 100 +- .../MAXScript/bulls-and-cows-1.max | 108 +- .../MAXScript/bulls-and-cows-2.max | 2 +- .../Bulls-and-cows/MUMPS/bulls-and-cows.mumps | 62 +- .../Bulls-and-cows/Maple/bulls-and-cows.maple | 100 +- .../Mathematica/bulls-and-cows.math | 18 +- .../Nanoquery/bulls-and-cows.nanoquery | 80 +- .../PowerShell/bulls-and-cows.psh | 47 - Task/Bulls-and-cows/Prolog/bulls-and-cows.pro | 74 +- Task/Bulls-and-cows/Red/bulls-and-cows.red | 16 +- .../SenseTalk/bulls-and-cows.sensetalk | 150 +-- .../Swift/bulls-and-cows-1.swift | 66 +- .../Bulls-and-cows/V-(Vlang)/bulls-and-cows.v | 94 +- .../Bulls-and-cows/VBScript/bulls-and-cows.vb | 43 - .../Jq/burrows-wheeler-transform-1.jq | 2 +- .../Ksh/burrows-wheeler-transform.ksh | 114 +- .../Phix/burrows-wheeler-transform.phix | 260 +++-- .../Zkl/burrows-wheeler-transform-1.zkl | 8 +- Task/CRC-32/11l/crc-32.11l | 2 +- Task/CRC-32/ALGOL-68/crc-32.alg | 4 +- Task/CRC-32/Ada/crc-32.ada | 14 - Task/CRC-32/COBOL/crc-32.cobol | 37 - Task/CRC-32/EasyLang/crc-32.easy | 13 +- Task/CRC-32/Haxe/crc-32.haxe | 9 - Task/CRC-32/Julia/crc-32-2.jl | 40 +- Task/CRC-32/Python/crc-32-1.py | 4 +- Task/CRC-32/VBScript/crc-32.vb | 32 - .../ALGOL-68/csv-data-manipulation.alg | 20 +- .../AWK/csv-data-manipulation.awk | 2 +- .../Ada/csv-data-manipulation-1.ada | 19 - .../Ada/csv-data-manipulation-2.ada | 24 - .../Ada/csv-data-manipulation-3.ada | 19 - .../C/csv-data-manipulation-1.c | 308 ++--- .../COBOL/csv-data-manipulation.cobol | 93 -- .../ECL/csv-data-manipulation.ecl | 2 +- .../EchoLisp/csv-data-manipulation-1.l | 14 +- .../Euphoria/csv-data-manipulation.ex | 91 -- .../Fortran/csv-data-manipulation-2.f | 34 +- .../FunL/csv-data-manipulation.funl | 2 +- .../Go/csv-data-manipulation.go | 78 +- .../Logo/csv-data-manipulation-1.logo | 30 +- .../Lua/csv-data-manipulation-1.lua | 12 +- .../MATLAB/csv-data-manipulation-1.m | 4 +- .../PowerShell/csv-data-manipulation.psh | 33 - .../Prolog/csv-data-manipulation.pro | 28 +- .../Red/csv-data-manipulation-2.red | 6 +- .../Scala/csv-data-manipulation.scala | 8 +- .../SenseTalk/csv-data-manipulation.sensetalk | 2 +- .../Tcl/csv-data-manipulation-1.tcl | 6 +- .../Tcl/csv-data-manipulation-2.tcl | 2 +- .../VBScript/csv-data-manipulation.vb | 35 - .../Ada/csv-to-html-translation-1.ada | 40 - .../Ada/csv-to-html-translation-2.ada | 8 - .../Ada/csv-to-html-translation-3.ada | 26 - .../AutoIt/csv-to-html-translation.autoit | 28 - .../C++/csv-to-html-translation-1.cpp | 8 +- .../C-sharp/csv-to-html-translation-4.cs | 48 +- .../C/csv-to-html-translation-1.c | 42 +- .../csv-to-html-translation-1.coffee | 32 +- .../csv-to-html-translation-1.lisp | 24 +- .../csv-to-html-translation-2.lisp | 12 +- .../EchoLisp/csv-to-html-translation-1.l | 26 +- .../EchoLisp/csv-to-html-translation-2.l | 10 +- .../Erlang/csv-to-html-translation.erl | 6 +- .../Euphoria/csv-to-html-translation-1.ex | 20 - .../Euphoria/csv-to-html-translation-2.ex | 8 - .../Forth/csv-to-html-translation-1.fth | 24 +- .../Fortran/csv-to-html-translation.f | 122 +- .../Haskell/csv-to-html-translation-2.hs | 2 +- .../Java/csv-to-html-translation-2.java | 154 +-- .../JavaScript/csv-to-html-translation-1.js | 10 +- .../JavaScript/csv-to-html-translation-3.js | 18 +- .../csv-to-html-translation.m2000 | 138 +-- .../MATLAB/csv-to-html-translation-3.m | 46 +- .../Maple/csv-to-html-translation.maple | 6 +- .../csv-to-html-translation.nanoquery | 14 +- .../csv-to-html-translation-2.openedge | 52 +- .../PowerShell/csv-to-html-translation-1.psh | 1 - .../PowerShell/csv-to-html-translation-2.psh | 13 - .../PowerShell/csv-to-html-translation-3.psh | 9 - .../PowerShell/csv-to-html-translation-4.psh | 21 - .../Prolog/csv-to-html-translation-1.pro | 44 +- .../Prolog/csv-to-html-translation-3.pro | 78 +- .../Raku/csv-to-html-translation-1.raku | 2 +- .../Run-BASIC/csv-to-html-translation.basic | 10 +- .../Tcl/csv-to-html-translation-1.tcl | 2 +- .../Tcl/csv-to-html-translation-2.tcl | 8 +- .../VBScript/csv-to-html-translation.vb | 33 - Task/CUSIP/11l/cusip.11l | 2 +- Task/CUSIP/ALGOL-68/cusip.alg | 65 +- Task/CUSIP/Ada/cusip.ada | 54 - Task/CUSIP/Arturo/cusip.arturo | 16 +- Task/CUSIP/EasyLang/cusip.easy | 6 +- Task/CUSIP/Langur/cusip-1.langur | 6 +- Task/CUSIP/Langur/cusip-2.langur | 6 +- Task/CUSIP/Phix/cusip.phix | 76 +- Task/CUSIP/PowerShell/cusip.psh | 48 - Task/Caesar-cipher/8th/caesar-cipher.8th | 2 +- Task/Caesar-cipher/Ada/caesar-cipher.ada | 58 - .../Caesar-cipher/Arturo/caesar-cipher.arturo | 10 +- .../AutoHotkey/caesar-cipher-2.ahk | 18 +- .../Caesar-cipher/AutoIt/caesar-cipher.autoit | 32 - Task/Caesar-cipher/Beads/caesar-cipher.beads | 48 +- Task/Caesar-cipher/C++/caesar-cipher-1.cpp | 20 +- Task/Caesar-cipher/C/caesar-cipher.c | 30 +- .../Caesar-cipher/COBOL/caesar-cipher-1.cobol | 36 - .../Caesar-cipher/COBOL/caesar-cipher-2.cobol | 84 -- .../Cubescript/caesar-cipher-1.cube | 100 +- Task/Caesar-cipher/Eiffel/caesar-cipher.e | 82 +- Task/Caesar-cipher/Elena/caesar-cipher.elena | 2 +- Task/Caesar-cipher/Euphoria/caesar-cipher.ex | 54 - .../Fhidwfe/caesar-cipher.fhidwfe | 2 +- Task/Caesar-cipher/GAP/caesar-cipher.gap | 36 +- Task/Caesar-cipher/Icon/caesar-cipher-2.icon | 6 +- Task/Caesar-cipher/Jq/caesar-cipher.jq | 10 +- Task/Caesar-cipher/Lua/caesar-cipher-1.lua | 34 +- .../M2000-Interpreter/caesar-cipher.m2000 | 4 +- Task/Caesar-cipher/MATLAB/caesar-cipher-1.m | 2 +- Task/Caesar-cipher/MLite/caesar-cipher.mlite | 48 +- .../Nanoquery/caesar-cipher.nanoquery | 52 +- .../PowerShell/caesar-cipher.psh | 75 -- Task/Caesar-cipher/Prolog/caesar-cipher.pro | 36 +- Task/Caesar-cipher/Python/caesar-cipher-1.py | 8 +- Task/Caesar-cipher/Sed/caesar-cipher.sed | 48 +- .../SequenceL/caesar-cipher.sequencel | 44 +- Task/Caesar-cipher/Stata/caesar-cipher.stata | 12 +- Task/Caesar-cipher/Tcl/caesar-cipher-1.tcl | 22 +- .../Caesar-cipher/TypeScript/caesar-cipher.ts | 8 +- Task/Caesar-cipher/Ursa/caesar-cipher.ursa | 16 +- Task/Caesar-cipher/V-(Vlang)/caesar-cipher.v | 48 +- Task/Caesar-cipher/VBScript/caesar-cipher.vb | 35 - .../Vedit-macro-language/caesar-cipher.vedit | 2 +- Task/Caesar-cipher/XBS/caesar-cipher.xbs | 48 +- .../Caesar-cipher/Yabasic/caesar-cipher.basic | 40 +- .../Caesar-cipher/Zonnon/caesar-cipher.zonnon | 66 +- .../Ada/calculating-the-value-of-e.ada | 25 - .../COBOL/calculating-the-value-of-e.cobol | 23 - .../Emacs-Lisp/calculating-the-value-of-e.l | 10 - .../Fortran/calculating-the-value-of-e.f | 16 - .../Phix/calculating-the-value-of-e.phix | 28 +- .../PowerShell/calculating-the-value-of-e.psh | 15 - .../REXX/calculating-the-value-of-e-1.rexx | 46 +- .../VBScript/calculating-the-value-of-e.vb | 12 - .../Ada/calendar---for-real-programmers.ada | 21 - .../calendar---for-real-programmers-1.ahk | 72 +- .../calendar---for-real-programmers-1.elena | 6 +- .../calendar---for-real-programmers-1.icon | 4 +- .../calendar---for-real-programmers.m2000 | 88 +- .../Red/calendar---for-real-programmers.red | 66 +- .../Tcl/calendar---for-real-programmers.tcl | 84 +- .../calendar---for-real-programmers.vedit | 16 +- Task/Calendar/Ada/calendar-1.ada | 48 - Task/Calendar/Ada/calendar-2.ada | 176 --- Task/Calendar/Ada/calendar-3.ada | 11 - Task/Calendar/AutoIt/calendar.autoit | 102 -- Task/Calendar/COBOL/calendar.cobol | 226 ---- Task/Calendar/PowerShell/calendar.psh | 36 - Task/Calendar/REBOL/calendar.rebol | 13 - Task/Calendar/VBScript/calendar.vb | 74 -- .../Ada/calkin-wilf-sequence.ada | 110 -- .../Arturo/calkin-wilf-sequence.arturo | 10 +- .../EasyLang/calkin-wilf-sequence.easy | 34 +- .../V-(Vlang)/calkin-wilf-sequence.v | 6 +- .../Ada/call-a-foreign-language-function.ada | 15 - .../call-a-foreign-language-function.cobol | 27 - .../Ol/call-a-foreign-language-function-2.ol | 13 +- .../Ol/call-a-foreign-language-function-3.ol | 52 +- .../call-a-function-in-a-shared-library-1.ada | 45 - .../call-a-function-in-a-shared-library-2.ada | 49 - ...call-a-function-in-a-shared-library.arturo | 5 +- .../call-a-function-in-a-shared-library.cobol | 37 - .../call-a-function-in-a-shared-library-2.ol | 18 +- .../call-a-function-in-a-shared-library.phix | 20 +- .../call-a-function-in-a-shared-library.rexx | 41 +- .../Call-a-function/Ada/call-a-function-1.ada | 1 - .../Call-a-function/Ada/call-a-function-2.ada | 5 - .../Call-a-function/Ada/call-a-function-3.ada | 12 - .../Call-a-function/Ada/call-a-function-4.ada | 9 - .../Call-a-function/Ada/call-a-function-5.ada | 3 - .../Arturo/call-a-function.arturo | 4 +- .../COBOL/call-a-function.cobol | 65 -- .../REXX/call-a-function-1.rexx | 19 - .../REXX/call-a-function-2.rexx | 25 - .../REXX/call-a-function-3.rexx | 18 - .../REXX/call-a-function-4.rexx | 27 - .../REXX/call-a-function-5.rexx | 16 - .../REXX/call-a-function-6.rexx | 11 - .../REXX/call-a-function-7.rexx | 18 - .../REXX/call-a-function-8.rexx | 24 - .../REXX/call-a-function-9.rexx | 77 -- .../Raku/call-a-function-11.raku | 2 - .../Ada/call-an-object-method-1.ada | 8 - .../Ada/call-an-object-method-2.ada | 18 - .../Ada/call-an-object-method-3.ada | 11 - .../Ada/call-an-object-method-4.ada | 20 - .../COBOL/call-an-object-method-1.cobol | 11 - .../COBOL/call-an-object-method-2.cobol | 3 - .../Haxe/call-an-object-method.haxe | 13 - .../Phix/call-an-object-method.phix | 24 +- .../PowerShell/call-an-object-method.psh | 3 - .../Ada/camel-case-and-snake-case.ada | 114 -- .../Arturo/camel-case-and-snake-case.arturo | 20 +- .../Phix/camel-case-and-snake-case.phix | 60 +- .../Ada/canonicalize-cidr.ada | 105 -- .../Phix/canonicalize-cidr.phix | 64 +- Task/Cantor-set/Ada/cantor-set.ada | 24 - Task/Cantor-set/Arturo/cantor-set.arturo | 4 +- Task/Cantor-set/C/cantor-set.c | 38 - Task/Cantor-set/COBOL/cantor-set.cobol | 48 - Task/Cantor-set/Phix/cantor-set.phix | 33 +- Task/Cantor-set/Python/cantor-set-1.py | 17 +- Task/Cantor-set/R/cantor-set.r | 8 +- .../carmichael-3-strong-pseudoprimes.alg | 6 +- .../Ada/carmichael-3-strong-pseudoprimes.ada | 41 - .../carmichael-3-strong-pseudoprimes.phix | 52 +- .../carmichael-3-strong-pseudoprimes.rexx | 9 +- ...cartesian-product-of-two-or-more-lists.ada | 104 -- ...tesian-product-of-two-or-more-lists.arturo | 2 +- ...tesian-product-of-two-or-more-lists.langur | 2 +- .../Ada/case-sensitivity-of-identifiers.ada | 6 - .../case-sensitivity-of-identifiers.cobol | 21 - .../D/case-sensitivity-of-identifiers.d | 4 +- .../case-sensitivity-of-identifiers.elena | 2 +- .../case-sensitivity-of-identifiers.ex | 5 - .../Nim/case-sensitivity-of-identifiers.nim | 2 +- .../case-sensitivity-of-identifiers.psh | 5 - .../case-sensitivity-of-identifiers.swift | 2 +- .../Ada/catalan-numbers-pascals-triangle.ada | 14 - .../catalan-numbers-pascals-triangle-1.phix | 28 +- .../catalan-numbers-pascals-triangle-3.phix | 40 +- .../catalan-numbers-pascals-triangle.vb | 20 - .../ALGOL-68/catalan-numbers.alg | 32 - Task/Catalan-numbers/Ada/catalan-numbers.ada | 16 - .../Arturo/catalan-numbers.arturo | 4 +- .../Euphoria/catalan-numbers.ex | 23 - .../Fantom/catalan-numbers.fantom | 2 +- .../Phix/catalan-numbers-1.phix | 72 +- .../Phix/catalan-numbers-2.phix | 56 +- .../PowerShell/catalan-numbers-1.psh | 10 - .../PowerShell/catalan-numbers-2.psh | 51 - .../PowerShell/catalan-numbers-3.psh | 1 - .../PowerShell/catalan-numbers-4.psh | 1 - .../REXX/catalan-numbers-2.rexx | 10 +- .../VBScript/catalan-numbers.vb | 23 - Task/Catamorphism/Ada/catamorphism.ada | 29 - Task/Catamorphism/Elena/catamorphism.elena | 2 +- Task/Catamorphism/PowerShell/catamorphism.psh | 1 - Task/Catamorphism/Python/catamorphism-1.py | 19 - Task/Catamorphism/Python/catamorphism-2.py | 14 - Task/Chaocipher/00-TASK.txt | 2 +- Task/Chaocipher/Ada/chaocipher.ada | 101 -- Task/Chaos-game/Ada/chaos-game.ada | 45 - Task/Chaos-game/Emacs-Lisp/chaos-game.l | 52 - Task/Character-codes/Ada/character-codes.ada | 6 - .../Arturo/character-codes.arturo | 2 +- .../COBOL/character-codes.cobol | 9 - .../Elena/character-codes.elena | 2 +- .../Emacs-Lisp/character-codes.l | 2 - .../Euphoria/character-codes.ex | 2 - .../Character-codes/Haxe/character-codes.haxe | 7 - Task/Character-codes/K/character-codes.k | 4 +- .../PowerShell/character-codes-1.psh | 1 - .../PowerShell/character-codes-2.psh | 1 - .../PowerShell/character-codes-3.psh | 1 - .../PowerShell/character-codes-4.psh | 1 - .../PowerShell/character-codes-5.psh | 2 - .../Retro/character-codes.retro | 3 +- .../VBScript/character-codes.vb | 5 - Task/Chat-server/Ada/chat-server.ada | 85 -- .../Ada/check-input-device-is-a-terminal.ada | 11 - .../check-input-device-is-a-terminal.cobol | 26 - .../check-input-device-is-a-terminal.phix | 6 +- .../check-output-device-is-a-terminal.6502 | 12 + .../Ada/check-output-device-is-a-terminal.ada | 11 - .../check-output-device-is-a-terminal.cobol | 26 - .../check-output-device-is-a-terminal.phix | 6 +- .../Ada/check-that-file-exists-1.ada | 17 - .../Ada/check-that-file-exists-2.ada | 20 - .../Batch-File/check-that-file-exists.bat | 23 +- .../COBOL/check-that-file-exists.cobol | 70 -- .../Elena/check-that-file-exists.elena | 2 +- .../Emacs-Lisp/check-that-file-exists.l | 4 - .../Euphoria/check-that-file-exists.ex | 22 - .../PowerShell/check-that-file-exists.psh | 6 - .../REBOL/check-that-file-exists.rebol | 5 - .../VBScript/check-that-file-exists.vb | 33 - .../Ada/checkpoint-synchronization.ada | 101 -- .../Phix/chernicks-carmichael-numbers-1.phix | 40 - .../Phix/chernicks-carmichael-numbers-2.phix | 53 - .../REXX/chernicks-carmichael-numbers.rexx | 15 +- .../Arturo/cheryls-birthday.arturo | 6 +- .../Ada/chinese-remainder-theorem.ada | 20 - Task/Chinese-zodiac/Ada/chinese-zodiac.ada | 116 -- Task/Chinese-zodiac/C/chinese-zodiac.c | 35 - Task/Chinese-zodiac/Phix/chinese-zodiac.phix | 30 +- .../PowerShell/chinese-zodiac-1.psh | 85 -- .../PowerShell/chinese-zodiac-2.psh | 1 - .../PowerShell/chinese-zodiac-3.psh | 1 - .../PowerShell/chinese-zodiac-4.psh | 1 - .../PowerShell/chinese-zodiac-5.psh | 12 - .../Chinese-zodiac/VBScript/chinese-zodiac.vb | 16 - .../Ada/cholesky-decomposition-1.ada | 9 - .../Ada/cholesky-decomposition-2.ada | 33 - .../Ada/cholesky-decomposition-3.ada | 45 - .../PowerShell/cholesky-decomposition.psh | 51 - .../ALGOL-68/chowla-numbers.alg | 41 +- Task/Chowla-numbers/Ada/chowla-numbers.ada | 70 -- Task/Chowla-numbers/REXX/chowla-numbers.rexx | 4 +- .../Chapel/church-numerals.chapel | 178 --- .../Church-numerals/Phix/church-numerals.phix | 153 ++- ...-of-given-radius-through-two-points.arturo | 4 +- ...es-of-given-radius-through-two-points.phix | 50 +- .../Arturo/circular-primes.arturo | 4 +- .../Free-Pascal-Lazarus/circular-primes.pas | 166 --- .../Phix/circular-primes-1.phix | 68 +- .../Phix/circular-primes-2.phix | 18 +- .../Circular-primes/REXX/circular-primes.rexx | 4 +- .../Ada/cistercian-numerals-1.ada | 92 -- .../Ada/cistercian-numerals-2.ada | 36 - .../Ada/cistercian-numerals-3.ada | 49 - .../Ada/cistercian-numerals-4.ada | 54 - .../Ada/cistercian-numerals-5.ada | 9 - .../Ada/cistercian-numerals-6.ada | 54 - .../Ada/cistercian-numerals-7.ada | 76 -- .../EasyLang/cistercian-numerals.easy | 18 +- .../Uiua/cistercian-numerals.uiua | 11 +- Task/Classes/Ada/classes-1.ada | 9 - Task/Classes/Ada/classes-2.ada | 13 - Task/Classes/Ada/classes-3.ada | 8 - Task/Classes/Arturo/classes.arturo | 66 +- Task/Classes/COBOL/classes.cobol | 66 -- Task/Classes/Elena/classes.elena | 6 +- Task/Classes/Haxe/classes-1.haxe | 14 - Task/Classes/Haxe/classes-2.haxe | 21 - Task/Classes/PowerShell/classes-1.psh | 28 - Task/Classes/PowerShell/classes-2.psh | 17 - Task/Classes/PowerShell/classes-3.psh | 33 - Task/Classes/PowerShell/classes-4.psh | 5 - Task/Classes/REBOL/classes.rebol | 39 - .../Ada/closest-pair-problem.ada | 67 -- .../Ada/closures-value-capture.ada | 30 - .../Elena/closures-value-capture.elena | 2 +- .../Emacs-Lisp/closures-value-capture.l | 7 - .../PowerShell/closures-value-capture-1.psh | 4 - .../PowerShell/closures-value-capture-2.psh | 9 - .../PowerShell/closures-value-capture-3.psh | 11 - Task/Collections/Ada/collections-1.ada | 11 - Task/Collections/Ada/collections-2.ada | 12 - Task/Collections/Ada/collections-3.ada | 13 - Task/Collections/Ada/collections-4.ada | 17 - Task/Collections/Ada/collections-5.ada | 17 - Task/Collections/COBOL/collections.cobol | 37 - Task/Collections/PowerShell/collections-1.psh | 47 - Task/Collections/PowerShell/collections-2.psh | 46 - Task/Collections/PowerShell/collections-3.psh | 9 - .../AutoIt/color-of-a-screen-pixel.autoit | 5 - Task/Color-wheel/Ada/color-wheel.ada | 89 -- Task/Color-wheel/C/color-wheel.c | 2 +- Task/Color-wheel/EasyLang/color-wheel.easy | 37 +- Task/Color-wheel/Emacs-Lisp/color-wheel.l | 75 -- Task/Color-wheel/VBScript/color-wheel.vb | 277 ----- Task/Colorful-numbers/00-TASK.txt | 4 +- .../Colorful-numbers/11l/colorful-numbers.11l | 6 +- .../Phix/colorful-numbers.phix | 122 +- .../Uiua/colorful-numbers.uiua | 10 +- .../Ada/colour-bars-display.ada | 49 - .../COBOL/colour-bars-display.cobol | 52 - .../PowerShell/colour-bars-display.psh | 14 - .../Ada/colour-pinstripe-display.ada | 74 -- .../Ada/colour-pinstripe-printer.ada | 83 -- .../Ada/combinations-and-permutations.ada | 69 -- .../combinations-and-permutations.easy | 24 +- .../VBScript/combinations-and-permutations.vb | 59 - .../Ada/combinations-with-repetitions.ada | 64 -- .../VBScript/combinations-with-repetitions.vb | 36 - Task/Combinations/Ada/combinations-1.ada | 56 - Task/Combinations/Ada/combinations-2.ada | 1 - Task/Combinations/Elena/combinations.elena | 2 +- Task/Combinations/Emacs-Lisp/combinations.l | 11 - Task/Combinations/PowerShell/combinations.psh | 35 - Task/Combinations/Uiua/combinations.uiua | 13 +- Task/Combinations/VBScript/combinations.vb | 40 - Task/Comma-quibbling/Ada/comma-quibbling.ada | 17 - .../Arturo/comma-quibbling.arturo | 8 +- .../COBOL/comma-quibbling.cobol | 75 -- .../EasyLang/comma-quibbling.easy | 8 +- .../Elena/comma-quibbling-1.elena | 2 +- .../Elena/comma-quibbling-2.elena | 2 +- .../PowerShell/comma-quibbling-1.psh | 41 - .../PowerShell/comma-quibbling-2.psh | 4 - .../PowerShell/comma-quibbling-3.psh | 11 - .../REBOL/comma-quibbling-1.rebol | 18 - .../REBOL/comma-quibbling-2.rebol | 24 - .../Comma-quibbling/Uiua/comma-quibbling.uiua | 6 +- .../VBScript/comma-quibbling.vb | 27 - .../Ada/command-line-arguments-1.ada | 14 - .../Ada/command-line-arguments-2.ada | 12 - .../COBOL/command-line-arguments-1.cobol | 14 - .../COBOL/command-line-arguments-2.cobol | 17 - .../COBOL/command-line-arguments-3.cobol | 57 - .../Elena/command-line-arguments.elena | 6 +- .../Emacs-Lisp/command-line-arguments.l | 2 - .../Euphoria/command-line-arguments.ex | 9 - .../PowerShell/command-line-arguments.psh | 4 - .../REXX/command-line-arguments-1.rexx | 34 +- .../REXX/command-line-arguments-2.rexx | 45 +- .../VBScript/command-line-arguments.vb | 17 - .../VBScript/commatizing-numbers.vb | 45 - Task/Comments/Ada/comments.ada | 1 - Task/Comments/AutoIt/comments.autoit | 5 - Task/Comments/COBOL/comments-1.cobol | 1 - Task/Comments/COBOL/comments-2.cobol | 1 - Task/Comments/COBOL/comments-3.cobol | 1 - Task/Comments/COBOL/comments-4.cobol | 1 - Task/Comments/COBOL/comments-5.cobol | 3 - Task/Comments/COBOL/comments-6.cobol | 11 - Task/Comments/Chapel/comments.chapel | 4 - Task/Comments/Emacs-Lisp/comments-1.l | 1 - Task/Comments/Emacs-Lisp/comments-2.l | 2 - Task/Comments/Emacs-Lisp/comments-3.l | 3 - Task/Comments/Euphoria/comments-1.ex | 1 - Task/Comments/Euphoria/comments-2.ex | 3 - Task/Comments/Haxe/comments.haxe | 7 - Task/Comments/Modula-2/comments.mod2 | 3 +- Task/Comments/Modula-3/comments.mod3 | 3 - Task/Comments/Oberon/comments.oberon | 2 +- Task/Comments/PowerShell/comments-1.psh | 1 - Task/Comments/PowerShell/comments-2.psh | 2 - Task/Comments/REBOL/comments-1.rebol | 5 - Task/Comments/REBOL/comments-2.rebol | 6 - Task/Comments/VBScript/comments.vb | 1 - Task/Comments/VHDL/comments.vhdl | 1 - .../Ada/compare-a-list-of-strings-1.ada | 4 - .../Ada/compare-a-list-of-strings-2.ada | 9 - .../Ada/compare-a-list-of-strings-3.ada | 9 - .../Ada/compare-a-list-of-strings-4.ada | 2 - .../Arturo/compare-a-list-of-strings.arturo | 2 +- .../COBOL/compare-a-list-of-strings.cobol | 60 - .../Elena/compare-a-list-of-strings.elena | 2 +- .../Icon/compare-a-list-of-strings.icon | 42 - .../Phix/compare-a-list-of-strings.phix | 44 +- .../PowerShell/compare-a-list-of-strings.psh | 10 - .../Python/compare-a-list-of-strings-1.py | 5 - .../Python/compare-a-list-of-strings-2.py | 18 - .../VBScript/compare-a-list-of-strings.vb | 23 - .../Ada/compare-length-of-two-strings.ada | 21 - .../compare-length-of-two-strings.arturo | 9 +- .../compare-length-of-two-strings.l | 7 - .../Ada/compile-time-calculation-1.ada | 7 - .../Ada/compile-time-calculation-2.ada | 16 - .../Ada/compile-time-calculation-3.ada | 12 - .../Ada/compile-time-calculation-4.ada | 2 - .../Phix/compile-time-calculation.phix | 9 +- .../PowerShell/compile-time-calculation.psh | 14 - .../COBOL/compiler-ast-interpreter.cobol | 497 -------- .../Phix/compiler-ast-interpreter.phix | 127 +- .../COBOL/compiler-code-generator.cobol | 652 ----------- .../Phix/compiler-code-generator-1.phix | 758 ++++++------ .../Phix/compiler-code-generator-2.phix | 372 +++--- .../Ada/compiler-lexical-analyzer.ada | 260 ----- .../COBOL/compiler-lexical-analyzer.cobol | 407 ------- .../Emacs-Lisp/compiler-lexical-analyzer.l | 419 ------- .../Euphoria/compiler-lexical-analyzer.ex | 226 ---- .../Phix/compiler-lexical-analyzer-1.phix | 272 +++-- .../Phix/compiler-lexical-analyzer-2.phix | 190 ++- .../Phix/compiler-lexical-analyzer-3.phix | 344 +++--- .../Phix/compiler-lexical-analyzer-4.phix | 88 +- .../Phix/compiler-lexical-analyzer-5.phix | 49 +- .../C/compiler-syntax-analyzer.c | 1 + .../COBOL/compiler-syntax-analyzer.cobol | 606 ---------- .../Phix/compiler-syntax-analyzer-1.phix | 279 +++-- .../Phix/compiler-syntax-analyzer-2.phix | 107 +- .../compiler-virtual-machine-interpreter.ada | 935 --------------- ...compiler-virtual-machine-interpreter.cobol | 422 ------- ...ompiler-virtual-machine-interpreter-1.phix | 70 +- ...ose-factors-are-all-substrings-of-k.arturo | 5 +- .../Ada/compound-data-type-1.ada | 4 - .../Ada/compound-data-type-2.ada | 4 - .../Ada/compound-data-type-3.ada | 11 - .../Arturo/compound-data-type.arturo | 29 +- .../COBOL/compound-data-type.cobol | 5 - .../Elena/compound-data-type.elena | 8 +- .../Euphoria/compound-data-type.ex | 11 - .../PowerShell/compound-data-type.psh | 18 - .../Compound-data-type/R/compound-data-type.r | 20 +- .../Ada/concurrent-computing.ada | 17 - .../Elena/concurrent-computing.elena | 2 +- .../Euphoria/concurrent-computing.ex | 17 - .../Phix/concurrent-computing.phix | 30 +- .../PowerShell/concurrent-computing-1.psh | 10 - .../PowerShell/concurrent-computing-2.psh | 16 - .../Ada/conditional-structures-1.ada | 10 - .../Ada/conditional-structures-2.ada | 13 - .../Ada/conditional-structures-3.ada | 6 - .../Ada/conditional-structures-4.ada | 1 - .../Ada/conditional-structures-5.ada | 13 - .../Ada/conditional-structures-6.ada | 9 - .../Ada/conditional-structures-7.ada | 10 - .../Ada/conditional-structures-8.ada | 7 - .../Ada/conditional-structures-9.ada | 5 - .../Arturo/conditional-structures-1.arturo | 10 +- .../Arturo/conditional-structures-2.arturo | 11 +- .../AutoIt/conditional-structures-1.autoit | 10 - .../AutoIt/conditional-structures-2.autoit | 11 - .../AutoIt/conditional-structures-3.autoit | 11 - .../COBOL/conditional-structures-1.cobol | 19 - .../COBOL/conditional-structures-2.cobol | 33 - .../PowerShell/conditional-structures-1.psh | 20 - .../PowerShell/conditional-structures-2.psh | 30 - .../VBScript/conditional-structures-1.vb | 14 - .../VBScript/conditional-structures-2.vb | 3 - .../VBScript/conditional-structures-3.vb | 19 - .../Ada/conjugate-transpose.ada | 47 - .../PowerShell/conjugate-transpose.psh | 76 -- .../R/conjugate-transpose.r | 94 +- ...h-ascending-or-descending-differences.rexx | 8 +- .../Ada/constrained-genericity-1.ada | 24 - .../Ada/constrained-genericity-2.ada | 8 - .../constrained-random-points-on-a-circle.ada | 94 -- ...onstrained-random-points-on-a-circle.cobol | 113 -- ...constrained-random-points-on-a-circle-1.ex | 65 -- ...constrained-random-points-on-a-circle-2.ex | 19 - .../constrained-random-points-on-a-circle.psh | 18 - ...thmetic-construct-from-rational-number.ada | 81 -- ...metic-construct-from-rational-number.pluto | 1 - ...etic-g-matrix-ng-continued-fraction-n-.ada | 368 ------ .../Ada/continued-fraction-1.ada | 6 - .../Ada/continued-fraction-2.ada | 11 - .../Ada/continued-fraction-3.ada | 35 - .../Ada/continued-fraction-4.ada | 6 - .../Ada/continued-fraction-5.ada | 18 - .../Ada/continued-fraction-6.ada | 87 -- .../COBOL/continued-fraction.cobol | 185 --- .../Chapel/continued-fraction.chapel | 35 - .../Phix/continued-fraction.phix | 38 +- .../Continued-fraction/R/continued-fraction.r | 16 +- .../REXX/continued-fraction-3.rexx | 4 +- .../Uiua/continued-fraction.uiua | 11 +- .../convert-decimal-number-to-rational-1.ada | 6 - .../convert-decimal-number-to-rational-2.ada | 29 - .../convert-decimal-number-to-rational-3.ada | 25 - .../convert-seconds-to-compound-duration.ada | 44 - ...onvert-seconds-to-compound-duration.arturo | 2 +- ...convert-seconds-to-compound-duration.cobol | 74 -- .../convert-seconds-to-compound-duration.psh | 116 -- .../convert-seconds-to-compound-duration.uiua | 10 +- .../convert-seconds-to-compound-duration.vb | 37 - Task/Convex-hull/Ada/convex-hull.ada | 88 -- Task/Convex-hull/Arturo/convex-hull.arturo | 44 +- Task/Convex-hull/Haxe/convex-hull.haxe | 93 -- .../11l/conways-game-of-life-1.11l | 2 +- .../11l/conways-game-of-life-2.11l | 2 +- .../68000-Assembly/conways-game-of-life.68000 | 790 ++++++------- .../ARM-Assembly/conways-game-of-life.arm | 186 +-- .../Ada/conways-game-of-life.ada | 56 - .../BASIC256/conways-game-of-life-2.basic | 108 +- .../C/conways-game-of-life-1.c | 64 +- .../COBOL/conways-game-of-life.cobol | 73 -- .../Chapel/conways-game-of-life.chapel | 90 -- .../Common-Lisp/conways-game-of-life-3.lisp | 20 +- .../Elena/conways-game-of-life.elena | 2 +- .../Emacs-Lisp/conways-game-of-life-1.l | 94 -- .../Emacs-Lisp/conways-game-of-life-2.l | 9 - .../Frink/conways-game-of-life.frink | 4 +- .../Go/conways-game-of-life.go | 128 +-- .../Groovy/conways-game-of-life.groovy | 174 +-- .../Java/conways-game-of-life-1.java | 172 +-- .../Java/conways-game-of-life-2.java | 292 ++--- .../JavaScript/conways-game-of-life-1.js | 150 +-- .../JavaScript/conways-game-of-life-2.js | 254 ++-- .../Ksh/conways-game-of-life.ksh | 108 +- .../conways-game-of-life.m2000 | 142 +-- .../MiniScript/conways-game-of-life.mini | 78 +- .../PL-I/conways-game-of-life.pli | 2 +- .../Perl/conways-game-of-life-1.pl | 4 +- .../Perl/conways-game-of-life-2.pl | 42 +- .../Prolog/conways-game-of-life.pro | 120 +- .../QBasic/conways-game-of-life.basic | 10 +- .../Red/conways-game-of-life.red | 56 - .../Scheme/conways-game-of-life.scm | 89 -- .../conways-game-of-life-1.sequencel | 38 +- .../conways-game-of-life-2.sequencel | 220 ++-- .../Smalltalk/conways-game-of-life-2.st | 2 +- .../Smalltalk/conways-game-of-life-4.st | 4 +- .../Uiua/conways-game-of-life.uiua | 8 +- .../V-(Vlang)/conways-game-of-life.v | 126 +- .../VBScript/conways-game-of-life-1.vb | 85 -- .../VBScript/conways-game-of-life-2.vb | 105 -- .../conways-game-of-life.vedit | 14 +- .../Zkl/conways-game-of-life-1.zkl | 2 +- .../Zkl/conways-game-of-life-2.zkl | 2 +- Task/Copy-a-string/ALGOL-W/copy-a-string.alg | 9 - Task/Copy-a-string/Ada/copy-a-string-1.ada | 2 - Task/Copy-a-string/Ada/copy-a-string-2.ada | 3 - Task/Copy-a-string/Ada/copy-a-string-3.ada | 6 - Task/Copy-a-string/Ada/copy-a-string-4.ada | 3 - .../Copy-a-string/Arturo/copy-a-string.arturo | 2 +- .../Copy-a-string/AutoIt/copy-a-string.autoit | 2 - Task/Copy-a-string/COBOL/copy-a-string.cobol | 2 - .../Copy-a-string/EasyLang/copy-a-string.easy | 2 + Task/Copy-a-string/Emacs-Lisp/copy-a-string.l | 7 - Task/Copy-a-string/Euphoria/copy-a-string.ex | 2 - .../PowerShell/copy-a-string-1.psh | 2 - .../PowerShell/copy-a-string-2.psh | 1 - Task/Copy-a-string/REBOL/copy-a-string.rebol | 21 - Task/Copy-a-string/REXX/copy-a-string.rexx | 18 +- Task/Copy-a-string/Tcl/copy-a-string.tcl | 2 - .../Ada/copy-stdin-to-stdout.ada | 11 - .../Phix/copy-stdin-to-stdout.phix | 14 +- .../VBScript/copy-stdin-to-stdout.vb | 4 - .../Count-in-factors/Ada/count-in-factors.ada | 30 - .../Euphoria/count-in-factors.ex | 28 - .../Count-in-factors/Lua/count-in-factors.lua | 23 +- .../Phix/count-in-factors.phix | 30 +- .../PowerShell/count-in-factors.psh | 32 - .../REXX/count-in-factors.rexx | 55 +- .../VBScript/count-in-factors.vb | 59 - Task/Count-in-octal/Ada/count-in-octal.ada | 10 - .../Arturo/count-in-octal.arturo | 2 +- .../Count-in-octal/COBOL/count-in-octal.cobol | 44 - .../EasyLang/count-in-octal.easy | 10 +- .../Emacs-Lisp/count-in-octal.l | 2 - .../Count-in-octal/Euphoria/count-in-octal.ex | 6 - .../PowerShell/count-in-octal.psh | 5 - .../Count-in-octal/VBScript/count-in-octal.vb | 3 - .../Ada/count-occurrences-of-a-substring.ada | 9 - .../count-occurrences-of-a-substring.arturo | 2 +- .../count-occurrences-of-a-substring.cobol | 22 - .../count-occurrences-of-a-substring.l | 20 - .../count-occurrences-of-a-substring.ex | 17 - .../count-occurrences-of-a-substring.phix | 42 +- .../count-occurrences-of-a-substring-1.psh | 1 - .../count-occurrences-of-a-substring-2.psh | 1 - .../count-occurrences-of-a-substring.rexx | 49 +- .../count-occurrences-of-a-substring-1.vb | 16 - .../count-occurrences-of-a-substring-2.vb | 10 - .../Count-the-coins/Ada/count-the-coins-1.ada | 32 - .../Count-the-coins/Ada/count-the-coins-2.ada | 26 - .../Arturo/count-the-coins.arturo | 2 +- .../COBOL/count-the-coins.cobol | 31 - .../EasyLang/count-the-coins.easy | 21 +- .../VBScript/count-the-coins.vb | 20 - Task/Cramers-rule/Ada/cramers-rule.ada | 70 -- .../create-a-file-on-magnetic-tape.arturo | 4 +- .../create-a-file-on-magnetic-tape.cobol | 26 - Task/Create-a-file/Ada/create-a-file.ada | 17 - .../Create-a-file/Arturo/create-a-file.arturo | 8 +- .../Batch-File/create-a-file-2.bat | 4 +- Task/Create-a-file/COBOL/create-a-file.cobol | 41 - Task/Create-a-file/Elena/create-a-file.elena | 2 +- Task/Create-a-file/Emacs-Lisp/create-a-file.l | 4 - Task/Create-a-file/Euphoria/create-a-file.ex | 11 - .../PowerShell/create-a-file.psh | 4 - Task/Create-a-file/REBOL/create-a-file.rebol | 9 - Task/Create-a-file/VBScript/create-a-file.vb | 9 - ...ate-a-two-dimensional-array-at-runtime.ada | 21 - ...-a-two-dimensional-array-at-runtime.autoit | 12 - ...a-two-dimensional-array-at-runtime-1.elena | 2 +- ...a-two-dimensional-array-at-runtime-2.elena | 2 +- ...eate-a-two-dimensional-array-at-runtime.ex | 15 - ...e-a-two-dimensional-array-at-runtime-1.psh | 22 - ...e-a-two-dimensional-array-at-runtime-2.psh | 6 - ...e-a-two-dimensional-array-at-runtime-3.psh | 4 - ...e-a-two-dimensional-array-at-runtime-4.psh | 1 - ...te-a-two-dimensional-array-at-runtime.rexx | 4 +- .../Ada/create-an-html-table-1.ada | 19 - .../Ada/create-an-html-table-2.ada | 56 - .../Ada/create-an-html-table-3.ada | 32 - .../Ada/create-an-html-table-4.ada | 11 - .../C++/create-an-html-table-1.cpp | 12 +- .../C-sharp/create-an-html-table-1.cs | 56 +- .../C-sharp/create-an-html-table-2.cs | 80 +- .../C/create-an-html-table.c | 18 +- .../COBOL/create-an-html-table.cobol | 115 -- .../Common-Lisp/create-an-html-table.lisp | 14 +- .../EchoLisp/create-an-html-table-1.l | 25 +- .../Erlang/create-an-html-table.erl | 12 +- .../Euphoria/create-an-html-table-1.ex | 10 - .../Euphoria/create-an-html-table-2.ex | 6 - .../Fortran/create-an-html-table.f | 750 ++++++------ .../Java/create-an-html-table-3.java | 44 +- .../JavaScript/create-an-html-table-1.js | 38 +- .../Lasso/create-an-html-table.lasso | 14 +- .../create-an-html-table.m2000 | 66 +- .../Modula-3/create-an-html-table.mod3 | 20 +- .../Nanoquery/create-an-html-table.nanoquery | 10 +- .../Oz/create-an-html-table.oz | 34 +- .../PHP/create-an-html-table-1.php | 18 +- .../PHP/create-an-html-table-2.php | 42 +- .../Peloton/create-an-html-table.peloton | 30 +- .../PowerShell/create-an-html-table-1.psh | 10 - .../PowerShell/create-an-html-table-2.psh | 25 - .../PowerShell/create-an-html-table-3.psh | 1 - .../Prolog/create-an-html-table-1.pro | 18 +- .../Rascal/create-an-html-table-1.rascal | 14 +- .../SNOBOL4/create-an-html-table.sno | 20 +- .../Standard-ML/create-an-html-table.ml | 40 +- .../Stata/create-an-html-table-1.stata | 18 +- .../Tcl/create-an-html-table.tcl | 20 +- .../VBScript/create-an-html-table.vb | 40 - .../create-an-object-at-a-given-address-1.ada | 3 - .../create-an-object-at-a-given-address-2.ada | 13 - .../create-an-object-at-a-given-address.cobol | 18 - Task/Cuban-primes/Ada/cuban-primes.ada | 136 --- Task/Cuban-primes/Phix/cuban-primes.phix | 64 +- Task/Cuban-primes/REXX/cuban-primes.rexx | 4 +- Task/Cullen-and-Woodall-numbers/00-TASK.txt | 2 +- .../COBOL/cullen-and-woodall-numbers.cobol | 29 - .../ALGOL-W/cumulative-standard-deviation.alg | 44 +- .../Ada/cumulative-standard-deviation.ada | 35 - .../cumulative-standard-deviation.arturo | 2 +- .../cumulative-standard-deviation-1.cobol | 71 -- .../cumulative-standard-deviation-2.cobol | 9 - .../cumulative-standard-deviation-1.l | 16 - .../cumulative-standard-deviation-2.l | 2 - .../cumulative-standard-deviation-3.l | 24 - .../Haxe/cumulative-standard-deviation.haxe | 23 - .../Phix/cumulative-standard-deviation.phix | 28 - .../cumulative-standard-deviation.psh | 13 - .../cumulative-standard-deviation.basic | 8 +- .../VBScript/cumulative-standard-deviation.vb | 21 - Task/Currency/Ada/currency.ada | 26 - Task/Currency/COBOL/currency.cobol | 28 - Task/Currency/EasyLang/currency.easy | 11 +- Task/Currying/Ada/currying-1.ada | 30 - Task/Currying/Ada/currying-2.ada | 18 - Task/Currying/Ada/currying-3.ada | 27 - Task/Currying/C/currying.c | 38 +- Task/Currying/Erlang/currying.erl | 34 +- Task/Currying/GDScript/currying.gd | 12 +- Task/Currying/Io/currying.io | 10 +- Task/Currying/Java/currying-2.java | 56 +- .../Currying/M2000-Interpreter/currying.m2000 | 80 +- Task/Currying/Nemerle/currying.nemerle | 10 +- Task/Currying/PowerShell/currying-1.psh | 1 - Task/Currying/PowerShell/currying-2.psh | 1 - Task/Currying/PowerShell/currying-3.psh | 1 - Task/Currying/REXX/currying-1.rexx | 16 +- Task/Currying/REXX/currying-2.rexx | 24 +- Task/Currying/Red/currying.red | 128 ++- Task/Curzon-numbers/Ada/curzon-numbers.ada | 57 - .../Arturo/curzon-numbers.arturo | 18 +- Task/Cut-a-rectangle/11l/cut-a-rectangle.11l | 2 +- .../Arturo/cyclops-numbers.arturo | 2 +- .../EasyLang/cyclops-numbers.easy | 13 +- .../Phix/cyclops-numbers-1.phix | 132 ++- .../Phix/cyclops-numbers-2.phix | 58 +- .../Cyclops-numbers/REXX/cyclops-numbers.rexx | 9 +- Task/DNS-query/Ada/dns-query-1.ada | 13 - Task/DNS-query/Ada/dns-query-2.ada | 14 - Task/DNS-query/Batch-File/dns-query.bat | 38 - Task/DNS-query/Phix/dns-query.phix | 276 +++-- Task/DNS-query/PowerShell/dns-query.psh | 2 - Task/DNS-query/VBScript/dns-query.vb | 16 - .../ALGOL-68/damm-algorithm.alg | 29 +- Task/Damm-algorithm/Ada/damm-algorithm.ada | 39 - Task/Damm-algorithm/Fortran/damm-algorithm.f | 97 +- .../PowerShell/damm-algorithm.psh | 25 - .../Damm-algorithm/REXX/damm-algorithm-2.rexx | 9 +- Task/Date-format/Ada/date-format.ada | 44 - Task/Date-format/AutoIt/date-format.autoit | 31 - Task/Date-format/COBOL/date-format.cobol | 64 -- Task/Date-format/Emacs-Lisp/date-format.l | 6 - Task/Date-format/Euphoria/date-format.ex | 11 - Task/Date-format/Julia/date-format.jl | 1 + Task/Date-format/Phix/date-format.phix | 10 +- Task/Date-format/PowerShell/date-format.psh | 5 - Task/Date-format/Python/date-format.py | 21 +- Task/Date-format/REBOL/date-format-1.rebol | 23 - Task/Date-format/REBOL/date-format-2.rebol | 1 - Task/Date-format/REXX/date-format-1.rexx | 12 - Task/Date-format/REXX/date-format-2.rexx | 28 - Task/Date-format/REXX/date-format-3.rexx | 6 - Task/Date-format/VBScript/date-format.vb | 5 - .../Ada/date-manipulation.ada | 97 -- .../COBOL/date-manipulation.cobol | 121 -- .../Emacs-Lisp/date-manipulation-1.l | 40 - .../Emacs-Lisp/date-manipulation-2.l | 41 - .../Euphoria/date-manipulation.ex | 10 - .../Phix/date-manipulation.phix | 19 +- .../PowerShell/date-manipulation.psh | 4 - .../REBOL/date-manipulation.rebol | 24 - Task/Day-of-the-week/Ada/day-of-the-week.ada | 11 - .../Arturo/day-of-the-week.arturo | 2 +- .../AutoIt/day-of-the-week.autoit | 7 - .../COBOL/day-of-the-week-1.cobol | 22 - .../COBOL/day-of-the-week-2.cobol | 68 -- .../Emacs-Lisp/day-of-the-week.l | 11 - .../Euphoria/day-of-the-week.ex | 15 - .../Day-of-the-week/Perl/day-of-the-week-1.pl | 8 +- .../PowerShell/day-of-the-week-1.psh | 1 - .../PowerShell/day-of-the-week-2.psh | 34 - .../PowerShell/day-of-the-week-3.psh | 1 - .../PowerShell/day-of-the-week-4.psh | 1 - .../PowerShell/day-of-the-week-5.psh | 1 - .../PowerShell/day-of-the-week-6.psh | 1 - .../REBOL/day-of-the-week.rebol | 9 - .../Standard-ML/day-of-the-week.ml | 34 +- .../VBScript/day-of-the-week.vb | 5 - .../11l/de-bruijn-sequences.11l | 2 +- .../Ada/de-bruijn-sequences.ada | 126 -- .../EasyLang/de-bruijn-sequences.easy | 4 +- .../Ruby/de-bruijn-sequences.rb | 73 -- .../Ada/deal-cards-for-freecell.ada | 38 - Task/Death-Star/Ada/death-star.ada | 143 --- Task/Death-Star/EasyLang/death-star.easy | 2 +- Task/Death-Star/VBScript/death-star.vb | 81 -- .../Free-Pascal-Lazarus/deceptive-numbers.pas | 117 -- .../Java/deceptive-numbers.java | 4 +- .../Deconvolution-1D/Ada/deconvolution-1d.ada | 53 - Task/Deepcopy/Ada/deepcopy.ada | 16 - Task/Deepcopy/Phix/deepcopy-1.phix | 14 +- Task/Deepcopy/Phix/deepcopy-2.phix | 30 +- Task/Deepcopy/Phix/deepcopy-3.phix | 8 +- .../Ada/define-a-primitive-data-type-1.ada | 1 - .../Ada/define-a-primitive-data-type-2.ada | 2 - .../Elena/define-a-primitive-data-type.elena | 2 +- .../Euphoria/define-a-primitive-data-type.ex | 3 - .../define-a-primitive-data-type.psh | 1 - Task/Delegates/Ada/delegates.ada | 48 - Task/Delegates/Elena/delegates-1.elena | 2 +- Task/Delegates/Elena/delegates-2.elena | 2 +- Task/Delete-a-file/Ada/delete-a-file-1.ada | 1 - Task/Delete-a-file/Ada/delete-a-file-2.ada | 4 - .../Batch-File/delete-a-file.bat | 5 +- .../Delete-a-file/COBOL/delete-a-file-1.cobol | 22 - .../Delete-a-file/COBOL/delete-a-file-2.cobol | 12 - Task/Delete-a-file/Elena/delete-a-file.elena | 2 +- Task/Delete-a-file/Emacs-Lisp/delete-a-file.l | 4 - .../PowerShell/delete-a-file.psh | 6 - Task/Delete-a-file/REBOL/delete-a-file.rebol | 7 - Task/Delete-a-file/VBScript/delete-a-file.vb | 21 - Task/Demings-funnel/Ada/demings-funnel.ada | 105 -- .../Ada/department-numbers.ada | 22 - .../COBOL/department-numbers.cobol | 37 - .../Julia/department-numbers.jl | 2 +- .../Nu/department-numbers.nu | 2 - .../Ada/detect-division-by-zero.ada | 32 - .../Arturo/detect-division-by-zero.arturo | 5 +- .../COBOL/detect-division-by-zero.cobol | 4 - .../EasyLang/detect-division-by-zero.easy | 13 +- .../Emacs-Lisp/detect-division-by-zero.l | 4 - .../Phix/detect-division-by-zero.phix | 19 +- .../PowerShell/detect-division-by-zero.psh | 6 - .../REBOL/detect-division-by-zero.rebol | 27 - .../REXX/detect-division-by-zero-2.rexx | 4 +- .../REXX/detect-division-by-zero-3.rexx | 4 - .../VBScript/detect-division-by-zero.vb | 13 - Task/Determinant-and-permanent/00-TASK.txt | 16 +- .../Arturo/determinant-and-permanent.arturo | 12 +- .../C++/determinant-and-permanent.cpp | 132 --- .../PowerShell/determinant-and-permanent.psh | 44 - ...f-a-string-has-all-the-same-characters.ada | 32 - ...-string-has-all-the-same-characters.arturo | 4 +- ...-a-string-has-all-the-same-characters.phix | 42 +- ...-if-a-string-has-all-unique-characters.ada | 27 - ...-a-string-has-all-unique-characters.arturo | 9 +- ...if-a-string-has-all-unique-characters.phix | 77 +- .../determine-if-a-string-is-collapsible.ada | 22 - .../determine-if-a-string-is-collapsible.easy | 4 +- .../determine-if-a-string-is-numeric-1.ada | 3 - .../determine-if-a-string-is-numeric-2.ada | 11 - .../determine-if-a-string-is-numeric-3.ada | 12 - .../determine-if-a-string-is-numeric.arturo | 3 +- .../determine-if-a-string-is-numeric-1.cobol | 10 - .../determine-if-a-string-is-numeric-2.cobol | 54 - .../determine-if-a-string-is-numeric-1.l | 12 - .../determine-if-a-string-is-numeric-2.l | 17 - .../determine-if-a-string-is-numeric.ex | 7 - .../determine-if-a-string-is-numeric.haxe | 11 - .../determine-if-a-string-is-numeric-1.psh | 8 - .../determine-if-a-string-is-numeric-2.psh | 5 - .../determine-if-a-string-is-numeric.rebol | 33 - .../determine-if-a-string-is-numeric.vb | 1 - .../determine-if-a-string-is-squeezable.ada | 25 - ...ermine-if-only-one-instance-is-running.ada | 28 - ...mine-if-only-one-instance-is-running-1.psh | 8 - ...mine-if-only-one-instance-is-running-2.psh | 8 - .../determine-if-two-triangles-overlap.11l | 4 +- .../determine-if-two-triangles-overlap.ada | 39 - .../determine-if-two-triangles-overlap.pas | 2 +- .../Ada/determine-sentence-type.ada | 35 - .../Emacs-Lisp/determine-sentence-type.l | 28 - .../Ada/dice-game-probabilities.ada | 57 - ...gital-root-multiplicative-digital-root.ada | 47 - ...al-root-multiplicative-digital-root-1.phix | 82 +- ...al-root-multiplicative-digital-root-2.phix | 8 +- Task/Digital-root/Ada/digital-root-1.ada | 15 - Task/Digital-root/Ada/digital-root-2.ada | 26 - Task/Digital-root/Ada/digital-root-3.ada | 26 - Task/Digital-root/COBOL/digital-root.cobol | 45 - Task/Digital-root/Elena/digital-root.elena | 2 +- .../PowerShell/digital-root-1.psh | 19 - .../PowerShell/digital-root-2.psh | 9 - Task/Digital-root/REXX/digital-root-2.rexx | 9 +- Task/Digital-root/VBScript/digital-root.vb | 15 - .../Ada/dijkstras-algorithm-1.ada | 32 - .../Ada/dijkstras-algorithm-2.ada | 91 -- .../Ada/dijkstras-algorithm-3.ada | 39 - .../Arturo/dijkstras-algorithm.arturo | 4 +- .../Emacs-Lisp/dijkstras-algorithm.l | 62 - .../Uiua/dijkstras-algorithm.uiua | 3 +- .../dinesmans-multiple-dwelling-problem.ada | 46 - .../dinesmans-multiple-dwelling-problem.easy | 11 +- .../dinesmans-multiple-dwelling-problem-1.psh | 68 -- .../dinesmans-multiple-dwelling-problem-2.psh | 1 - .../dinesmans-multiple-dwelling-problem-3.psh | 1 - .../Ada/dining-philosophers-1.ada | 50 - .../Ada/dining-philosophers-2.ada | 53 - .../Ada/dining-philosophers-3.ada | 75 -- .../Euphoria/dining-philosophers.ex | 54 - .../Disarium-numbers/Ada/disarium-numbers.ada | 34 - .../COBOL/disarium-numbers.cobol | 36 - .../EasyLang/disarium-numbers.easy | 31 +- Task/Discordian-date/Ada/discordian-date.ada | 203 ---- .../Euphoria/discordian-date.ex | 59 - .../Discordian-date/Phix/discordian-date.phix | 78 +- .../PowerShell/discordian-date.psh | 22 - .../Ada/display-a-linear-combination.ada | 54 - .../display-a-linear-combination.arturo | 11 +- .../C/display-a-linear-combination.c | 114 +- .../display-a-linear-combination.easy | 40 +- .../EchoLisp/display-a-linear-combination.l | 16 +- .../Phix/display-a-linear-combination.phix | 60 +- .../R/display-a-linear-combination.r | 22 +- .../V-(Vlang)/display-a-linear-combination.v | 26 +- Task/Distance-and-Bearing/00-TASK.txt | 1 - .../Phix/distance-and-bearing.phix | 126 +- .../Ada/distributed-programming-1.ada | 5 - .../Ada/distributed-programming-2.ada | 13 - .../Ada/distributed-programming-3.ada | 9 - .../Ada/distributed-programming-4.ada | 13 - ...ion-of-0-digits-in-factorial-series.arturo | 2 +- ...ution-of-0-digits-in-factorial-series.easy | 33 +- .../Ada/diversity-prediction-theorem.ada | 60 - Task/Documentation/Ada/documentation.ada | 25 - .../Documentation/COBOL/documentation-1.cobol | 57 - .../Documentation/COBOL/documentation-2.cobol | 16 - .../Emacs-Lisp/documentation-1.l | 3 - .../Emacs-Lisp/documentation-2.l | 2 - .../PowerShell/documentation.psh | 1 - Task/Documentation/REBOL/documentation.rebol | 64 -- Task/Doomsday-rule/00-TASK.txt | 2 +- Task/Dot-product/Ada/dot-product.ada | 19 - Task/Dot-product/C/dot-product.c | 56 +- Task/Dot-product/Elena/dot-product.elena | 2 +- Task/Dot-product/Emacs-Lisp/dot-product.l | 8 - Task/Dot-product/Euphoria/dot-product-1.ex | 11 - Task/Dot-product/Euphoria/dot-product-2.ex | 5 - Task/Dot-product/LFE/dot-product.lfe | 3 +- Task/Dot-product/Perl/dot-product.pl | 13 - Task/Dot-product/PowerShell/dot-product.psh | 5 - Task/Dot-product/REBOL/dot-product.rebol | 16 - Task/Dot-product/VBScript/dot-product.vb | 14 - .../doubly-linked-list-definition-1.psh | 8 - .../doubly-linked-list-definition-2.psh | 3 - .../doubly-linked-list-definition-3.psh | 14 - .../doubly-linked-list-definition-4.psh | 3 - .../Raku/doubly-linked-list-definition.raku | 42 +- ...oubly-linked-list-element-definition-1.ada | 7 - ...oubly-linked-list-element-definition-2.ada | 23 - ...oubly-linked-list-element-definition-3.ada | 5 - ...doubly-linked-list-element-insertion-1.ada | 11 - ...doubly-linked-list-element-insertion-2.ada | 12 - ...doubly-linked-list-element-insertion-3.ada | 19 - .../Ada/doubly-linked-list-traversal.ada | 27 - Task/Dragon-curve/Ada/dragon-curve-1.ada | 23 - Task/Dragon-curve/Ada/dragon-curve-2.ada | 21 - Task/Dragon-curve/Ada/dragon-curve-3.ada | 18 - Task/Dragon-curve/Ada/dragon-curve-4.ada | 77 -- Task/Dragon-curve/BASIC/dragon-curve.basic | 10 +- Task/Dragon-curve/BASIC256/dragon-curve.basic | 66 +- Task/Dragon-curve/C++/dragon-curve.cpp | 192 ++-- Task/Dragon-curve/C/dragon-curve.c | 120 +- Task/Dragon-curve/COBOL/dragon-curve.cobol | 173 --- Task/Dragon-curve/Emacs-Lisp/dragon-curve.l | 90 -- Task/Dragon-curve/Haskell/dragon-curve-2.hs | 6 +- .../Metafont/dragon-curve.metafont | 8 +- Task/Dragon-curve/Prolog/dragon-curve.pro | 66 +- Task/Dragon-curve/Raku/dragon-curve.raku | 2 +- .../SequenceL/dragon-curve-1.sequencel | 50 +- .../SequenceL/dragon-curve-2.sequencel | 94 +- Task/Dragon-curve/Tcl/dragon-curve.tcl | 8 +- Task/Dragon-curve/VBScript/dragon-curve.vb | 105 -- .../Vedit-macro-language/dragon-curve.vedit | 56 +- .../Dragon-curve/Yabasic/dragon-curve-1.basic | 52 +- Task/Draw-a-clock/Ada/draw-a-clock.ada | 99 -- Task/Draw-a-clock/Batch-File/draw-a-clock.bat | 26 +- Task/Draw-a-clock/C++/draw-a-clock.cpp | 328 +++--- Task/Draw-a-clock/C/draw-a-clock-1.c | 120 +- Task/Draw-a-clock/ContextFree/draw-a-clock.cf | 6 +- Task/Draw-a-clock/Go/draw-a-clock-1.go | 106 +- Task/Draw-a-clock/Go/draw-a-clock-2.go | 14 +- .../Draw-a-clock/JavaScript/draw-a-clock-1.js | 68 +- .../M2000-Interpreter/draw-a-clock.m2000 | 166 +-- .../Draw-a-clock/MiniScript/draw-a-clock.mini | 4 +- Task/Draw-a-clock/OPL/draw-a-clock.opl | 2 + Task/Draw-a-clock/Perl/draw-a-clock.pl | 29 - Task/Draw-a-clock/Red/draw-a-clock-2.red | 4 +- .../Draw-a-clock/Run-BASIC/draw-a-clock.basic | 70 +- Task/Draw-a-clock/Tcl/draw-a-clock.tcl | 10 +- Task/Draw-a-clock/V-(Vlang)/draw-a-clock.v | 248 ++-- Task/Draw-a-clock/VBScript/draw-a-clock.vb | 70 -- .../Draw-a-clock/Yabasic/draw-a-clock-2.basic | 252 ++-- Task/Draw-a-clock/Zkl/draw-a-clock.zkl | 2 +- Task/Draw-a-cuboid/Ada/draw-a-cuboid.ada | 55 - .../Draw-a-cuboid/EasyLang/draw-a-cuboid.easy | 2 +- Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb | 48 - .../ARM-Assembly/draw-a-pixel.arm | 6 +- Task/Draw-a-pixel/Ada/draw-a-pixel.ada | 47 - Task/Draw-a-pixel/AutoHotkey/draw-a-pixel.ahk | 10 +- Task/Draw-a-pixel/C/draw-a-pixel-1.c | 14 +- Task/Draw-a-pixel/C/draw-a-pixel-2.c | 116 +- Task/Draw-a-pixel/Forth/draw-a-pixel.fth | 14 +- Task/Draw-a-pixel/Go/draw-a-pixel-2.go | 30 +- Task/Draw-a-pixel/Go/draw-a-pixel-3.go | 6 +- Task/Draw-a-pixel/Java/draw-a-pixel-1.java | 28 +- Task/Draw-a-pixel/Java/draw-a-pixel-2.java | 52 +- Task/Draw-a-pixel/Lua/draw-a-pixel.lua | 6 +- Task/Draw-a-pixel/OPL/draw-a-pixel.opl | 3 + Task/Draw-a-pixel/Oberon/draw-a-pixel.oberon | 10 +- Task/Draw-a-pixel/Odin/draw-a-pixel.odin | 32 - Task/Draw-a-pixel/Perl/draw-a-pixel-3.pl | 46 +- Task/Draw-a-pixel/ReScript/draw-a-pixel-1.re | 15 - Task/Draw-a-pixel/ReScript/draw-a-pixel-2.re | 30 - .../Ada/draw-a-rotating-cube.ada | 105 -- Task/Draw-a-sphere/Ada/draw-a-sphere-1.ada | 30 - Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada | 12 - .../Draw-a-sphere/EasyLang/draw-a-sphere.easy | 2 +- Task/Draw-a-sphere/Emacs-Lisp/draw-a-sphere.l | 54 - Task/Draw-a-sphere/VBScript/draw-a-sphere.vb | 51 - .../Arturo/duffinian-numbers.arturo | 6 +- .../Ada/dutch-national-flag-problem.ada | 99 -- .../AutoIt/dutch-national-flag-problem.autoit | 24 - .../Phix/dutch-national-flag-problem.phix | 74 +- .../dutch-national-flag-problem.psh | 16 - .../VBScript/dutch-national-flag-problem.vb | 44 - .../Elena/dynamic-variable-names.elena | 2 +- .../Emacs-Lisp/dynamic-variable-names.l | 1 - .../Haskell/dynamic-variable-names-2.hs | 2 +- .../Haskell/dynamic-variable-names-3.hs | 2 +- .../PowerShell/dynamic-variable-names.psh | 3 - .../REBOL/dynamic-variable-names.rebol | 14 - .../Ada/ekg-sequence-convergence.ada | 116 -- ...arliest-difference-between-prime-gaps.phix | 66 +- Task/Eban-numbers/Ada/eban-numbers.ada | 175 --- Task/Echo-server/Ada/echo-server-1.ada | 39 - Task/Echo-server/Ada/echo-server-2.ada | 144 --- Task/Echo-server/REBOL/echo-server.rebol | 10 - .../Ada/egyptian-division.ada | 30 - .../Arturo/egyptian-division.arturo | 4 +- .../Ada/element-wise-operations-1.ada | 31 - .../Ada/element-wise-operations-2.ada | 16 - .../Ada/element-wise-operations-3.ada | 45 - .../Ada/elementary-cellular-automaton.ada | 66 -- ...tic-curve-digital-signature-algorithm.phix | 498 ++++---- .../Phix/elliptic-curve-arithmetic.phix | 134 ++- Task/Emirp-primes/Ada/emirp-primes.ada | 69 -- Task/Emirp-primes/Arturo/emirp-primes.arturo | 2 +- Task/Emirp-primes/EasyLang/emirp-primes.easy | 18 +- Task/Emirp-primes/Phix/emirp-primes.phix | 165 ++- Task/Emirp-primes/REXX/emirp-primes-2.rexx | 8 +- Task/Empty-directory/Ada/empty-directory.ada | 24 - .../PowerShell/empty-directory.psh | 6 - .../VBScript/empty-directory.vb | 12 - Task/Empty-program/Ada/empty-program.ada | 4 - .../Asymptote/empty-program.asymptote | 0 .../Empty-program/AutoIt/empty-program.autoit | 1 - .../BASIC256/empty-program.basic | 0 .../BootBASIC/empty-program.basic | 0 Task/Empty-program/COBOL/empty-program.cobol | 0 .../CoffeeScript/empty-program.coffee | 0 Task/Empty-program/Crystal/empty-program.cr | 0 Task/Empty-program/Elena/empty-program.elena | 2 +- Task/Empty-program/Elixir/empty-program.ex | 0 Task/Empty-program/Euphoria/empty-program.ex | 0 Task/Empty-program/FALSE/empty-program.false | 0 .../Empty-program/Groovy/empty-program.groovy | 0 Task/Empty-program/Haxe/empty-program.haxe | 4 - Task/Empty-program/Icon/empty-program.icon | 3 +- Task/Empty-program/K/empty-program.k | 0 Task/Empty-program/LSE/empty-program.lse | 0 Task/Empty-program/Lua/empty-program.lua | 0 Task/Empty-program/M4/empty-program.m4 | 0 Task/Empty-program/ML-I/empty-program.mli | 0 Task/Empty-program/Maple/empty-program.maple | 0 .../Mathematica/empty-program.math | 0 .../MelonBasic/empty-program.basic | 0 .../MiniScript/empty-program.mini | 0 .../NS-HUBASIC/empty-program.basic | 0 .../Empty-program/Objeck/empty-program.objeck | 1 + .../Empty-program/Openscad/empty-program.scad | 0 .../PARI-GP/empty-program.parigp | 0 .../PowerShell/empty-program.psh | 1 - .../Quite-BASIC/empty-program.basic | 0 Task/Empty-program/REBOL/empty-program.rebol | 1 - Task/Empty-program/Ring/empty-program.ring | 0 .../Robotic/empty-program.robotic | 0 Task/Empty-program/Scheme/empty-program.scm | 0 .../Empty-program/Scilab/empty-program.scilab | 0 Task/Empty-program/Set-lang/empty-program.set | 0 Task/Empty-program/Sidef/empty-program.sidef | 0 .../SimpleCode/empty-program.simplecode | 0 Task/Empty-program/Slate/empty-program.slate | 0 .../Sparkling/empty-program.sparkling | 0 Task/Empty-program/Swift/empty-program.swift | 0 .../Empty-program/Symsyn/empty-program.symsyn | 0 Task/Empty-program/Trith/empty-program.trith | 0 Task/Empty-program/VBScript/empty-program.vb | 1 - Task/Empty-program/VHDL/empty-program.vhdl | 6 - .../Wee-Basic/empty-program.basic | 0 Task/Empty-program/Wren/empty-program.wren | 0 .../Empty-program/Yabasic/empty-program.basic | 0 .../AArch64-Assembly/empty-string-2.aarch64 | 6 +- .../AArch64-Assembly/empty-string-3.aarch64 | 64 +- .../ARM-Assembly/empty-string.arm | 29 +- Task/Empty-string/AWK/empty-string.awk | 4 +- Task/Empty-string/Ada/empty-string.ada | 15 - .../AppleScript/empty-string.applescript | 12 +- .../Asymptote/empty-string.asymptote | 4 +- Task/Empty-string/BASIC256/empty-string.basic | 14 +- Task/Empty-string/COBOL/empty-string.cobol | 23 - .../Component-Pascal/empty-string.pas | 22 +- Task/Empty-string/EasyLang/empty-string.easy | 8 +- Task/Empty-string/Elena/empty-string.elena | 2 +- Task/Empty-string/Emacs-Lisp/empty-string-1.l | 6 - Task/Empty-string/Emacs-Lisp/empty-string-2.l | 5 - Task/Empty-string/Euphoria/empty-string.ex | 15 - Task/Empty-string/Go/empty-string-2.go | 26 +- Task/Empty-string/I/empty-string.i | 18 +- Task/Empty-string/Lasso/empty-string.lasso | 8 +- Task/Empty-string/Modula-3/empty-string.mod3 | 6 +- Task/Empty-string/Pascal/empty-string.pas | 40 +- Task/Empty-string/Pike/empty-string.pike | 16 +- .../PowerShell/empty-string-1.psh | 4 - .../PowerShell/empty-string-2.psh | 2 - Task/Empty-string/QBasic/empty-string.basic | 6 +- Task/Empty-string/REXX/empty-string.rexx | 55 +- .../Empty-string/Run-BASIC/empty-string.basic | 8 +- Task/Empty-string/Ursa/empty-string.ursa | 4 +- Task/Empty-string/V-(Vlang)/empty-string-2.v | 24 +- Task/Empty-string/Yabasic/empty-string.basic | 2 +- .../Z80-Assembly/empty-string-2.z80 | 14 +- .../Empty-string/Zoomscript/empty-string.zoom | 4 +- .../Ada/enforced-immutability-1.ada | 2 - .../Ada/enforced-immutability-2.ada | 6 - .../COBOL/enforced-immutability-1.cobol | 4 - .../COBOL/enforced-immutability-2.cobol | 1 - .../COBOL/enforced-immutability-3.cobol | 1 - .../COBOL/enforced-immutability-4.cobol | 2 - .../Euphoria/enforced-immutability.ex | 3 - .../Ada/entropy-narcissist.ada | 66 -- .../AutoLISP/entropy-narcissist.l | 46 - .../Emacs-Lisp/entropy-narcissist-1.l | 20 - .../Emacs-Lisp/entropy-narcissist-2.l | 2 - .../Phix/entropy-narcissist.phix | 48 +- Task/Entropy/Ada/entropy.ada | 28 - Task/Entropy/Arturo/entropy.arturo | 2 +- Task/Entropy/AutoLISP/entropy.l | 40 - Task/Entropy/EasyLang/entropy.easy | 8 +- Task/Entropy/Elena/entropy.elena | 2 +- Task/Entropy/Emacs-Lisp/entropy-1.l | 15 - Task/Entropy/Emacs-Lisp/entropy-2.l | 2 - Task/Entropy/PowerShell/entropy.psh | 9 - Task/Enumerations/Ada/enumerations.ada | 2 - Task/Enumerations/Phix/enumerations.phix | 6 +- .../PowerShell/enumerations-1.psh | 8 - .../PowerShell/enumerations-2.psh | 8 - .../Ada/environment-variables-1.ada | 7 - .../Ada/environment-variables-2.ada | 11 - .../Ada/environment-variables-3.ada | 15 - .../AutoIt/environment-variables.autoit | 11 - .../COBOL/environment-variables.cobol | 18 - .../Emacs-Lisp/environment-variables.l | 1 - .../Euphoria/environment-variables.ex | 1 - .../Phix/environment-variables.phix | 6 +- .../PowerShell/environment-variables-1.psh | 1 - .../PowerShell/environment-variables-2.psh | 1 - .../REBOL/environment-variables.rebol | 1 - .../equal-prime-and-composite-sums.alg | 42 +- .../Ada/equal-prime-and-composite-sums.ada | 88 -- .../equal-prime-and-composite-sums.easy | 43 +- .../Lua/equal-prime-and-composite-sums.lua | 4 +- .../Phix/equal-prime-and-composite-sums.phix | 64 +- .../Ada/equilibrium-index-1.ada | 18 - .../Ada/equilibrium-index-2.ada | 20 - .../Ada/equilibrium-index-3.ada | 52 - .../Ada/equilibrium-index-4.ada | 68 -- .../Arturo/equilibrium-index.arturo | 2 +- .../EasyLang/equilibrium-index.easy | 8 +- .../Elena/equilibrium-index.elena | 2 +- .../Euphoria/equilibrium-index.ex | 20 - .../Julia/equilibrium-index.jl | 2 +- .../Kotlin/equilibrium-index.kts | 2 +- .../Phix/equilibrium-index.phix | 39 +- .../PowerShell/equilibrium-index-1.psh | 22 - .../PowerShell/equilibrium-index-2.psh | 1 - .../ReScript/equilibrium-index.re | 17 - .../VBScript/equilibrium-index.vb | 19 - .../Esthetic-numbers/11l/esthetic-numbers.11l | 2 +- .../Arturo/esthetic-numbers.arturo | 2 +- .../EasyLang/esthetic-numbers.easy | 38 +- .../Phix/esthetic-numbers-1.phix | 130 +-- .../Phix/esthetic-numbers-2.phix | 38 +- .../REXX/esthetic-numbers.rexx | 221 +++- .../ethiopian-multiplication.8080 | 106 +- .../ActionScript/ethiopian-multiplication.as | 44 +- .../Ada/ethiopian-multiplication.ada | 14 - .../AutoHotkey/ethiopian-multiplication.ahk | 24 +- .../AutoIt/ethiopian-multiplication.autoit | 39 - .../BASIC/ethiopian-multiplication.basic | 35 - .../BASIC256/ethiopian-multiplication.basic | 26 +- .../C-Shell/ethiopian-multiplication.csh | 26 +- .../C-sharp/ethiopian-multiplication.cs | 108 +- .../C/ethiopian-multiplication.c | 2 +- .../COBOL/ethiopian-multiplication.cobol | 93 -- .../ColdFusion/ethiopian-multiplication-1.cfm | 6 +- .../ColdFusion/ethiopian-multiplication-2.cfm | 10 +- .../ethiopian-multiplication.basic | 44 +- .../Eiffel/ethiopian-multiplication.e | 82 +- .../Emacs-Lisp/ethiopian-multiplication.l | 14 - .../Erlang/ethiopian-multiplication.erl | 2 +- .../Euphoria/ethiopian-multiplication.ex | 31 - .../JavaScript/ethiopian-multiplication-1.js | 42 +- .../Limbo/ethiopian-multiplication.limbo | 50 +- .../ethiopian-multiplication.m2000 | 34 +- .../MMIX/ethiopian-multiplication.mmix | 84 +- .../Octave/ethiopian-multiplication.octave | 4 +- .../Oz/ethiopian-multiplication.oz | 6 +- .../Pascal/ethiopian-multiplication.pas | 34 - .../Perl/ethiopian-multiplication.pl | 12 +- .../PowerShell/ethiopian-multiplication-1.psh | 35 - .../PowerShell/ethiopian-multiplication-2.psh | 29 - .../ethiopian-multiplication.powerbuilder | 14 +- .../R/ethiopian-multiplication-2.r | 14 +- .../Raku/ethiopian-multiplication-1.raku | 6 +- .../Rascal/ethiopian-multiplication.rascal | 16 +- .../SNOBOL4/ethiopian-multiplication.sno | 30 +- .../Smalltalk/ethiopian-multiplication-1.st | 2 +- .../Tcl/ethiopian-multiplication-1.tcl | 20 +- .../True-BASIC/ethiopian-multiplication.basic | 50 +- .../UNIX-Shell/ethiopian-multiplication-1.sh | 6 +- .../VBScript/ethiopian-multiplication-1.vb | 89 -- .../VBScript/ethiopian-multiplication-2.vb | 1 - .../ethiopian-multiplication-1.x86 | 146 +-- .../Yabasic/ethiopian-multiplication.basic | 26 +- .../Z80-Assembly/ethiopian-multiplication.z80 | 200 ++-- .../EasyLang/euclid-mullin-sequence.easy | 26 +- .../Lua/euclid-mullin-sequence-1.lua | 4 +- .../REXX/euclid-mullin-sequence.rexx | 9 +- Task/Euler-method/Ada/euler-method-1.ada | 11 - Task/Euler-method/Ada/euler-method-2.ada | 17 - Task/Euler-method/Ada/euler-method-3.ada | 18 - Task/Euler-method/BASIC256/euler-method.basic | 28 +- Task/Euler-method/C-sharp/euler-method.cs | 66 +- Task/Euler-method/C/euler-method-1.c | 40 +- Task/Euler-method/COBOL/euler-method.cobol | 45 - .../Craft-Basic/euler-method.basic | 32 +- Task/Euler-method/Erlang/euler-method.erl | 48 +- Task/Euler-method/JavaScript/euler-method.js | 32 +- Task/Euler-method/Jq/euler-method-1.jq | 2 +- Task/Euler-method/Jq/euler-method-2.jq | 2 +- .../Lambdatalk/euler-method.lambdatalk | 22 +- Task/Euler-method/Lua/euler-method.lua | 4 +- Task/Euler-method/Maple/euler-method-2.maple | 20 +- Task/Euler-method/Odin/euler-method.odin | 4 +- Task/Euler-method/Pascal/euler-method.pas | 70 +- Task/Euler-method/PowerShell/euler-method.psh | 43 - Task/Euler-method/Python/euler-method.py | 12 +- Task/Euler-method/REXX/euler-method-2.rexx | 74 +- .../SequenceL/euler-method.sequencel | 24 +- Task/Euler-method/Smalltalk/euler-method.st | 20 +- Task/Euler-method/Tcl/euler-method-1.tcl | 4 +- Task/Euler-method/XBasic/euler-method.basic | 22 +- .../Ada/eulers-constant-0.5772....ada | 47 - .../Delphi/eulers-constant-0.5772....pas | 26 +- .../EasyLang/eulers-constant-0.5772....easy | 3 +- .../Java/eulers-constant-0.5772....java | 28 +- .../REXX/eulers-constant-0.5772....rexx | 4 +- Task/Eulers-identity/Ada/eulers-identity.ada | 8 - .../Phix/eulers-identity-1.phix | 15 +- .../Phix/eulers-identity-2.phix | 57 +- .../Ada/eulers-sum-of-powers-conjecture.ada | 76 -- .../eulers-sum-of-powers-conjecture.cobol | 97 -- .../Phix/eulers-sum-of-powers-conjecture.phix | 64 +- .../eulers-sum-of-powers-conjecture.psh | 23 - .../eulers-sum-of-powers-conjecture.vb | 20 - .../Ada/evaluate-binomial-coefficients.ada | 27 - .../evaluate-binomial-coefficients.easy | 19 +- .../evaluate-binomial-coefficients.pas | 2 +- .../evaluate-binomial-coefficients-1.phix | 16 +- .../evaluate-binomial-coefficients-2.phix | 4 +- .../evaluate-binomial-coefficients-3.phix | 20 +- .../evaluate-binomial-coefficients.psh | 17 - .../evaluate-binomial-coefficients.vb | 21 - Task/Even-or-odd/Ada/even-or-odd.ada | 15 - Task/Even-or-odd/Arturo/even-or-odd.arturo | 4 +- Task/Even-or-odd/Batch-File/even-or-odd.bat | 6 +- Task/Even-or-odd/COBOL/even-or-odd.cobol | 5 - Task/Even-or-odd/Crystal/even-or-odd.cr | 10 + Task/Even-or-odd/Emacs-Lisp/even-or-odd.l | 10 - Task/Even-or-odd/Euphoria/even-or-odd.ex | 5 - Task/Even-or-odd/Oberon/even-or-odd.oberon | 21 - Task/Even-or-odd/PowerShell/even-or-odd-1.psh | 2 - Task/Even-or-odd/PowerShell/even-or-odd-2.psh | 2 - Task/Even-or-odd/PowerShell/even-or-odd-3.psh | 2 - Task/Even-or-odd/ReScript/even-or-odd.re | 3 - Task/Even-or-odd/VBScript/even-or-odd.vb | 12 - Task/Events/Ada/events-1.ada | 7 - Task/Events/Ada/events-2.ada | 14 - Task/Events/Ada/events-3.ada | 18 - Task/Events/PowerShell/events.psh | 16 - .../8080-Assembly/evolutionary-algorithm.8080 | 324 +++--- .../8086-Assembly/evolutionary-algorithm.8086 | 246 ++-- .../Ada/evolutionary-algorithm.ada | 124 -- .../Arturo/evolutionary-algorithm.arturo | 2 +- .../AutoHotkey/evolutionary-algorithm.ahk | 62 +- .../C/evolutionary-algorithm-1.c | 64 +- .../COBOL/evolutionary-algorithm.cobol | 88 -- .../Ceylon/evolutionary-algorithm.ceylon | 88 +- .../Common-Lisp/evolutionary-algorithm-2.lisp | 22 +- .../EchoLisp/evolutionary-algorithm.l | 50 +- .../Elena/evolutionary-algorithm.elena | 4 +- .../Euphoria/evolutionary-algorithm.ex | 51 - .../Fortran/evolutionary-algorithm-1.f | 218 ++-- .../Icon/evolutionary-algorithm-1.icon | 66 +- .../JavaScript/evolutionary-algorithm-1.js | 10 +- .../Lua/evolutionary-algorithm.lua | 58 +- .../MATLAB/evolutionary-algorithm-4.m | 2 +- .../evolutionary-algorithm.nanoquery | 92 +- .../PARI-GP/evolutionary-algorithm.parigp | 58 +- .../Pascal/evolutionary-algorithm.pas | 122 +- .../Pony/evolutionary-algorithm-1.pony | 4 +- .../Prolog/evolutionary-algorithm.pro | 24 +- .../evolutionary-algorithm-1.sequencel | 26 +- .../evolutionary-algorithm-2.sequencel | 62 +- .../Tcl/evolutionary-algorithm-1.tcl | 8 +- .../Tcl/evolutionary-algorithm-2.tcl | 26 +- .../VBScript/evolutionary-algorithm.vb | 60 - .../Zkl/evolutionary-algorithm.zkl | 2 +- ...h-an-exception-thrown-in-a-nested-call.ada | 31 - ...an-exception-thrown-in-a-nested-call.elena | 2 +- ...-an-exception-thrown-in-a-nested-call.phix | 62 +- Task/Exceptions/Ada/exceptions-1.ada | 1 - Task/Exceptions/Ada/exceptions-2.ada | 4 - Task/Exceptions/Ada/exceptions-3.ada | 6 - Task/Exceptions/Ada/exceptions-4.ada | 9 - Task/Exceptions/Ada/exceptions-5.ada | 12 - Task/Exceptions/PowerShell/exceptions-1.psh | 1 - Task/Exceptions/PowerShell/exceptions-2.psh | 1 - Task/Exceptions/PowerShell/exceptions-3.psh | 12 - Task/Exceptions/PowerShell/exceptions-4.psh | 1 - Task/Exceptions/REXX/exceptions.rexx | 25 +- .../Ada/executable-library-1.ada | 4 - .../Ada/executable-library-2.ada | 49 - .../Ada/executable-library-3.ada | 1 - .../Ada/executable-library-4.ada | 35 - .../Execute-Brain-/Agena/execute-brain-.agena | 112 +- .../Arturo/execute-brain--1.arturo | 39 +- .../AutoIt/execute-brain-.autoit | 134 --- .../Factor/execute-brain-.factor | 4 +- Task/Execute-Brain-/Phix/execute-brain-.phix | 99 +- .../Execute-Brain-/REBOL/execute-brain-.rebol | 83 -- .../Execute-Brain-/VBScript/execute-brain-.vb | 76 -- .../Phix/execute-computer-zero.phix | 100 +- Task/Execute-HQ9+/Arturo/execute-hq9+.arturo | 13 +- Task/Execute-HQ9+/COBOL/execute-hq9+.cobol | 44 - Task/Execute-HQ9+/Haxe/execute-hq9+.haxe | 21 - Task/Execute-HQ9+/PowerShell/execute-hq9+.psh | 43 - .../Ada/execute-a-markov-algorithm-1.ada | 26 - .../Ada/execute-a-markov-algorithm-2.ada | 81 -- .../Ada/execute-a-markov-algorithm-3.ada | 48 - .../VBScript/execute-a-markov-algorithm-1.vb | 73 -- .../VBScript/execute-a-markov-algorithm-2.vb | 60 - .../VBScript/execute-a-markov-algorithm-3.vb | 5 - .../Ada/execute-a-system-command-1.ada | 8 - .../Ada/execute-a-system-command-2.ada | 9 - .../Ada/execute-a-system-command-3.ada | 20 - .../AutoIt/execute-a-system-command.autoit | 1 - .../COBOL/execute-a-system-command.cobol | 1 - .../Emacs-Lisp/execute-a-system-command-1.l | 1 - .../Emacs-Lisp/execute-a-system-command-2.l | 1 - .../Euphoria/execute-a-system-command.ex | 32 - .../PowerShell/execute-a-system-command-1.psh | 3 - .../PowerShell/execute-a-system-command-2.psh | 1 - .../REBOL/execute-a-system-command.rebol | 15 - .../VBScript/execute-a-system-command.vb | 2 - .../Ada/exponentiation-operator-1.ada | 15 - .../Ada/exponentiation-operator-2.ada | 19 - .../Ada/exponentiation-operator-3.ada | 49 - .../EasyLang/exponentiation-operator.easy | 6 +- .../PowerShell/exponentiation-operator.psh | 20 - .../VBScript/exponentiation-operator.vb | 23 - .../Ada/exponentiation-order.ada | 9 - .../Phix/exponentiation-order.phix | 6 +- .../VBScript/exponentiation-order.vb | 3 - .../00-TASK.txt | 2 +- ...-operators-in-or-operating-on-the-base.ada | 47 - .../Ada/extend-your-language.ada | 20 - .../Arturo/extend-your-language.arturo | 11 +- .../COBOL/extend-your-language.cobol | 10 - .../Coq/extend-your-language.coq | 1 - .../Emacs-Lisp/extend-your-language.l | 9 - .../PowerShell/extend-your-language-1.psh | 47 - .../PowerShell/extend-your-language-2.psh | 6 - .../PowerShell/extend-your-language-3.psh | 8 - .../Ada/extensible-prime-generator.ada | 71 -- .../Haskell/extensible-prime-generator-3.hs | 2 +- .../REXX/extensible-prime-generator.rexx | 13 +- .../VBScript/extensible-prime-generator.vb | 93 -- .../Ada/extreme-floating-point-values-1.ada | 1 - .../Ada/extreme-floating-point-values-2.ada | 29 - .../extreme-floating-point-values.easy | 17 +- .../Euphoria/extreme-floating-point-values.ex | 16 - .../Phix/extreme-floating-point-values.phix | 42 +- Task/FASTA-format/Ada/fasta-format-1.ada | 28 - Task/FASTA-format/Ada/fasta-format-2.ada | 46 - Task/FASTA-format/Arturo/fasta-format.arturo | 4 +- Task/FASTA-format/EasyLang/fasta-format.easy | 5 +- Task/FASTA-format/Perl/fasta-format.pl | 19 - .../PowerShell/fasta-format-1.psh | 21 - .../PowerShell/fasta-format-2.psh | 21 - Task/FTP/Ada/ftp.ada | 57 - Task/FTP/REBOL/ftp.rebol | 3 - .../Factorial-primes/Ada/factorial-primes.ada | 95 -- .../EasyLang/factorial-primes.easy | 10 +- .../Pluto/factorial-primes.pluto | 4 +- Task/Factorial/Ada/factorial-1.ada | 9 - Task/Factorial/Ada/factorial-2.ada | 8 - Task/Factorial/Ada/factorial-3.ada | 62 - Task/Factorial/Arturo/factorial-1.arturo | 9 +- Task/Factorial/Arturo/factorial-2.arturo | 4 + Task/Factorial/AutoIt/factorial-1.autoit | 12 - Task/Factorial/AutoIt/factorial-2.autoit | 10 - Task/Factorial/COBOL/factorial-1.cobol | 1 - Task/Factorial/COBOL/factorial-2.cobol | 21 - Task/Factorial/COBOL/factorial-3.cobol | 22 - Task/Factorial/COBOL/factorial-4.cobol | 34 - Task/Factorial/Chapel/factorial.chapel | 7 - Task/Factorial/Coq/factorial.coq | 5 - Task/Factorial/Emacs-Lisp/factorial-1.l | 11 - Task/Factorial/Emacs-Lisp/factorial-2.l | 8 - Task/Factorial/Emacs-Lisp/factorial-3.l | 4 - Task/Factorial/Euphoria/factorial-1.ex | 9 - Task/Factorial/Euphoria/factorial-2.ex | 7 - Task/Factorial/Euphoria/factorial-3.ex | 7 - Task/Factorial/Euphoria/factorial-4.ex | 106 -- Task/Factorial/Haxe/factorial-1.haxe | 6 - Task/Factorial/Haxe/factorial-2.haxe | 3 - Task/Factorial/Haxe/factorial-3.haxe | 7 - Task/Factorial/Haxe/factorial-4.haxe | 3 - Task/Factorial/Haxe/factorial-5.haxe | 58 - Task/Factorial/PowerShell/factorial-1.psh | 6 - Task/Factorial/PowerShell/factorial-2.psh | 9 - Task/Factorial/PowerShell/factorial-3.psh | 6 - Task/Factorial/REBOL/factorial.rebol | 55 - Task/Factorial/REXX/factorial-2.rexx | 28 +- Task/Factorial/Tcl/factorial-5.tcl | 1 + Task/Factorial/Tcl/factorial-6.tcl | 61 +- Task/Factorial/Tcl/factorial-7.tcl | 14 +- Task/Factorial/VBScript/factorial.vb | 41 - Task/Factorial/VHDL/factorial.vhdl | 74 -- Task/Factorions/Ada/factorions.ada | 64 -- Task/Factorions/Arturo/factorions.arturo | 6 +- Task/Factorions/R/factorions.r | 9 +- Task/Factorions/VBScript/factorions.vb | 23 - .../Ada/factors-of-a-mersenne-number.ada | 68 -- .../factors-of-a-mersenne-number.arturo | 8 +- .../factors-of-a-mersenne-number.easy | 32 +- .../factors-of-a-mersenne-number-1.parigp | 7 - .../factors-of-a-mersenne-number-2.parigp | 20 - .../REXX/factors-of-a-mersenne-number.rexx | 14 +- .../VBScript/factors-of-a-mersenne-number.vb | 63 - .../Ada/factors-of-an-integer.ada | 22 - .../AutoIt/factors-of-an-integer.autoit | 13 - .../COBOL/factors-of-an-integer.cobol | 40 - .../Chapel/factors-of-an-integer.chapel | 8 - .../PowerShell/factors-of-an-integer-1.psh | 3 - .../PowerShell/factors-of-an-integer-2.psh | 6 - .../REXX/factors-of-an-integer-2.rexx | 8 +- .../Uiua/factors-of-an-integer.uiua | 2 +- .../fairshare-between-two-and-more.arturo | 2 +- .../Phix/fairshare-between-two-and-more.phix | 49 +- .../Langur/farey-sequence.langur | 4 +- .../Ada/fast-fourier-transform-1.ada | 7 - .../Ada/fast-fourier-transform-2.ada | 39 - .../Ada/fast-fourier-transform-3.ada | 20 - .../PowerShell/fast-fourier-transform.psh | 32 - .../Ada/feigenbaum-constant-calculation.ada | 46 - .../REXX/feigenbaum-constant-calculation.rexx | 4 +- Task/Fermat-numbers/Phix/fermat-numbers.phix | 97 +- Task/Fermat-numbers/REXX/fermat-numbers.rexx | 9 +- .../fibonacci-n-step-number-sequences-1.ada | 11 - .../fibonacci-n-step-number-sequences-2.ada | 20 - .../fibonacci-n-step-number-sequences-3.ada | 21 - .../fibonacci-n-step-number-sequences.phix | 39 +- .../fibonacci-n-step-number-sequences-1.psh | 17 - .../fibonacci-n-step-number-sequences-2.psh | 10 - .../fibonacci-n-step-number-sequences.vb | 31 - Task/Fibonacci-sequence/00-TASK.txt | 16 +- .../Ada/fibonacci-sequence-1.ada | 19 - .../Ada/fibonacci-sequence-2.ada | 20 - .../Ada/fibonacci-sequence-3.ada | 33 - .../Ada/fibonacci-sequence-4.ada | 49 - .../Arturo/fibonacci-sequence.arturo | 8 - .../AutoIt/fibonacci-sequence-1.autoit | 27 - .../AutoIt/fibonacci-sequence-2.autoit | 19 - .../COBOL/fibonacci-sequence-1.cobol | 40 - .../COBOL/fibonacci-sequence-2.cobol | 45 - .../Chapel/fibonacci-sequence.chapel | 8 - .../Coq/fibonacci-sequence.coq | 8 - .../EasyLang/fibonacci-sequence-1.easy | 5 +- .../EasyLang/fibonacci-sequence-2.easy | 4 +- .../Elena/fibonacci-sequence-1.elena | 2 +- .../Elena/fibonacci-sequence-2.elena | 2 +- .../Emacs-Lisp/fibonacci-sequence-1.l | 10 - .../Emacs-Lisp/fibonacci-sequence-2.l | 15 - .../Emacs-Lisp/fibonacci-sequence-3.l | 3 - .../Euphoria/fibonacci-sequence-1.ex | 4 - .../Euphoria/fibonacci-sequence-2.ex | 10 - .../Euphoria/fibonacci-sequence-3.ex | 10 - .../Euphoria/fibonacci-sequence-4.ex | 78 -- .../Fortran/fibonacci-sequence-2.f | 27 + .../Haxe/fibonacci-sequence-1.haxe | 15 - .../Haxe/fibonacci-sequence-2.haxe | 19 - .../Haxe/fibonacci-sequence-3.haxe | 2 - .../Langur/fibonacci-sequence.langur | 3 - .../Pascal/fibonacci-sequence-1.pas | 1017 ++++++++++++++++- .../Pascal/fibonacci-sequence-2.pas | 25 +- .../Pascal/fibonacci-sequence-3.pas | 28 +- .../Pascal/fibonacci-sequence-4.pas | 22 +- .../Pascal/fibonacci-sequence-5.pas | 22 +- .../Pascal/fibonacci-sequence-6.pas | 80 +- .../PowerShell/fibonacci-sequence-1.psh | 9 - .../PowerShell/fibonacci-sequence-2.psh | 4 - .../PowerShell/fibonacci-sequence-3.psh | 8 - .../Python/fibonacci-sequence-1.py | 2 + .../Python/fibonacci-sequence-10.py | 36 +- .../Python/fibonacci-sequence-11.py | 15 +- .../Python/fibonacci-sequence-12.py | 18 +- .../Python/fibonacci-sequence-13.py | 14 +- .../Python/fibonacci-sequence-14.py | 30 +- .../Python/fibonacci-sequence-15.py | 25 +- .../Python/fibonacci-sequence-16.py | 18 +- .../Python/fibonacci-sequence-17.py | 9 +- .../Python/fibonacci-sequence-2.py | 36 +- .../Python/fibonacci-sequence-3.py | 63 +- .../Python/fibonacci-sequence-4.py | 10 +- .../Python/fibonacci-sequence-5.py | 15 +- .../Python/fibonacci-sequence-6.py | 18 +- .../Python/fibonacci-sequence-7.py | 11 +- .../Python/fibonacci-sequence-8.py | 8 +- .../Python/fibonacci-sequence-9.py | 31 +- .../REXX/fibonacci-sequence.rexx | 85 +- .../Uiua/fibonacci-sequence.uiua | 2 - .../VBScript/fibonacci-sequence-1.vb | 44 - .../VBScript/fibonacci-sequence-2.vb | 10 - Task/Fibonacci-word/Ada/fibonacci-word.ada | 56 - .../Arturo/fibonacci-word.arturo | 2 +- .../EasyLang/fibonacci-word.easy | 5 +- Task/Fibonacci-word/Uiua/fibonacci-word.uiua | 17 +- .../file-extension-is-in-extensions-list.ada | 42 - .../file-extension-is-in-extensions-list.phix | 53 +- .../Ada/file-input-output-1.ada | 30 - .../Ada/file-input-output-2.ada | 51 - .../Ada/file-input-output-3.ada | 26 - .../Ada/file-input-output-4.ada | 24 - .../Arturo/file-input-output.arturo | 2 +- .../Batch-File/file-input-output-1.bat | 6 +- .../Batch-File/file-input-output-2.bat | 14 +- .../Batch-File/file-input-output-3.bat | 2 +- .../COBOL/file-input-output-1.cobol | 40 - .../COBOL/file-input-output-2.cobol | 48 - .../COBOL/file-input-output-3.cobol | 2 - .../COBOL/file-input-output-4.cobol | 2 - .../Elena/file-input-output.elena | 2 +- .../Emacs-Lisp/file-input-output.l | 6 - .../Euphoria/file-input-output-1.ex | 2 - .../Euphoria/file-input-output-2.ex | 16 - .../PowerShell/file-input-output-1.psh | 1 - .../PowerShell/file-input-output-2.psh | 1 - .../REBOL/file-input-output.rebol | 7 - .../VBScript/file-input-output.vb | 1 - .../Ada/file-modification-time.ada | 8 - .../Emacs-Lisp/file-modification-time.l | 5 - .../PowerShell/file-modification-time.psh | 8 - .../VBScript/file-modification-time.vb | 1 - .../Ada/file-size-distribution.ada | 59 - Task/File-size/Ada/file-size.ada | 8 - Task/File-size/Batch-File/file-size.bat | 4 - Task/File-size/COBOL/file-size.cobol | 42 - Task/File-size/Elena/file-size.elena | 2 +- Task/File-size/Emacs-Lisp/file-size.l | 3 - Task/File-size/Euphoria/file-size.ex | 24 - Task/File-size/PowerShell/file-size.psh | 2 - Task/File-size/REBOL/file-size.rebol | 4 - Task/File-size/VBScript/file-size.vb | 4 - Task/Filter/Ada/filter-1.ada | 32 - Task/Filter/Ada/filter-2.ada | 28 - Task/Filter/Elena/filter-1.elena | 2 +- Task/Filter/Elena/filter-2.elena | 4 +- Task/Filter/Emacs-Lisp/filter.l | 1 - Task/Filter/Euphoria/filter.ex | 9 - Task/Filter/PowerShell/filter.psh | 2 - Task/Filter/REBOL/filter.rebol | 5 - Task/Filter/VBScript/filter.vb | 47 - .../Ada/find-common-directory-path.ada | 37 - .../Arturo/find-common-directory-path.arturo | 2 +- .../find-common-directory-path-1.psh | 27 - .../find-common-directory-path-2.psh | 2 - .../VBScript/find-common-directory-path.vb | 31 - .../Ada/find-duplicate-files.ada | 128 --- ...find-if-a-point-is-within-a-triangle-1.ada | 34 - ...find-if-a-point-is-within-a-triangle-2.ada | 21 - ...find-if-a-point-is-within-a-triangle-3.ada | 16 - .../C/find-if-a-point-is-within-a-triangle.c | 9 +- ...ind-if-a-point-is-within-a-triangle-1.phix | 24 +- ...ind-if-a-point-is-within-a-triangle-2.phix | 64 +- ...eft-truncatable-prime-in-a-given-base.rexx | 65 +- .../Ada/find-limit-of-recursion.ada | 13 - .../AutoIt/find-limit-of-recursion.autoit | 7 - .../COBOL/find-limit-of-recursion-1.cobol | 50 - .../COBOL/find-limit-of-recursion-2.cobol | 25 - .../Emacs-Lisp/find-limit-of-recursion.l | 6 - .../Phix/find-limit-of-recursion-1.phix | 31 +- .../Phix/find-limit-of-recursion-2.phix | 46 +- .../PowerShell/find-limit-of-recursion.psh | 15 - .../REXX/find-limit-of-recursion.rexx | 2 +- .../VBScript/find-limit-of-recursion-1.vb | 13 - .../VBScript/find-limit-of-recursion-2.vb | 14 - ...ers-in-both-binary-and-ternary-bases-1.ada | 27 - ...ers-in-both-binary-and-ternary-bases-2.ada | 49 - ...numbers-in-both-binary-and-ternary-bases.l | 52 - ...he-intersection-of-a-line-with-a-plane.ada | 56 - ...intersection-of-a-line-with-a-plane.arturo | 5 +- .../find-the-intersection-of-two-lines.ada | 44 - .../find-the-intersection-of-two-lines.arturo | 11 +- .../find-the-intersection-of-two-lines.easy | 50 +- .../find-the-intersection-of-two-lines.l | 26 - .../find-the-last-sunday-of-each-month.arturo | 4 +- .../find-the-last-sunday-of-each-month.cobol | 48 - .../find-the-last-sunday-of-each-month.l | 14 - ...ind-the-last-sunday-of-each-month-1.oberon | 59 +- ...ind-the-last-sunday-of-each-month-2.oberon | 42 +- ...ind-the-last-sunday-of-each-month-3.oberon | 12 - .../find-the-last-sunday-of-each-month.phix | 35 +- .../find-the-last-sunday-of-each-month-1.psh | 13 - .../find-the-last-sunday-of-each-month-2.psh | 97 -- .../find-the-last-sunday-of-each-month-3.psh | 1 - .../find-the-last-sunday-of-each-month-4.psh | 1 - .../find-the-last-sunday-of-each-month-5.psh | 1 - .../find-the-last-sunday-of-each-month.rebol | 16 - .../find-the-last-sunday-of-each-month.vb | 6 - .../11l/find-the-missing-permutation.11l | 4 +- .../Ada/find-the-missing-permutation.ada | 51 - .../find-the-missing-permutation.psh | 56 - .../Uiua/find-the-missing-permutation.uiua | 2 +- .../VBScript/find-the-missing-permutation.vb | 24 - ...lass-functions-use-numbers-analogously.ada | 22 - ...ss-functions-use-numbers-analogously.elena | 4 +- .../Ada/first-class-functions.ada | 56 - .../Elena/first-class-functions.elena | 2 +- .../Maxima/first-class-functions.maxima | 1 - .../REBOL/first-class-functions.rebol | 29 - ...square-in-base-n-with-n-unique-digits.easy | 31 +- ...square-in-base-n-with-n-unique-digits.uiua | 11 +- ...that-has-leading-decimal-digits-of-12.easy | 11 +- ...that-has-leading-decimal-digits-of-12.phix | 62 +- Task/Five-weekends/Ada/five-weekends.ada | 23 - .../Five-weekends/AutoIt/five-weekends.autoit | 41 - Task/Five-weekends/COBOL/five-weekends.cobol | 53 - Task/Five-weekends/Euphoria/five-weekends.ex | 42 - .../FutureBasic/five-weekends.basic | 2 + Task/Five-weekends/Julia/five-weekends.jl | 2 + Task/Five-weekends/Phix/five-weekends.phix | 60 +- .../PowerShell/five-weekends.psh | 20 - Task/Five-weekends/VBScript/five-weekends.vb | 11 - Task/Fivenum/11l/fivenum.11l | 2 +- Task/Fivenum/Ada/fivenum-1.ada | 71 -- Task/Fivenum/Ada/fivenum-2.ada | 80 -- .../Ada/fixed-length-records.ada | 41 - .../COBOL/fixed-length-records-1.cobol | 89 -- .../COBOL/fixed-length-records-2.cobol | 90 -- .../COBOL/fixed-length-records-3.cobol | 72 -- .../REBOL/fixed-length-records.rebol | 7 - Task/FizzBuzz/Ada/fizzbuzz.ada | 16 - Task/FizzBuzz/Arturo/fizzbuzz.arturo | 11 +- Task/FizzBuzz/AutoIt/fizzbuzz-1.autoit | 11 - Task/FizzBuzz/AutoIt/fizzbuzz-2.autoit | 25 - Task/FizzBuzz/CLIPS/fizzbuzz.clips | 35 +- Task/FizzBuzz/COBOL/fizzbuzz-1.cobol | 36 - Task/FizzBuzz/COBOL/fizzbuzz-2.cobol | 16 - Task/FizzBuzz/COBOL/fizzbuzz-3.cobol | 26 - Task/FizzBuzz/COBOL/fizzbuzz-4.cobol | 29 - Task/FizzBuzz/Chapel/fizzbuzz.chapel | 13 - Task/FizzBuzz/Coq/fizzbuzz.coq | 66 -- Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l | 9 - Task/FizzBuzz/Euphoria/fizzbuzz.ex | 33 - Task/FizzBuzz/Factor/fizzbuzz-1.factor | 2 +- Task/FizzBuzz/J/fizzbuzz-10.j | 37 +- Task/FizzBuzz/J/fizzbuzz-2.j | 2 +- Task/FizzBuzz/J/fizzbuzz-3.j | 2 +- Task/FizzBuzz/J/fizzbuzz-4.j | 2 +- Task/FizzBuzz/J/fizzbuzz-5.j | 6 +- Task/FizzBuzz/J/fizzbuzz-6.j | 7 +- Task/FizzBuzz/J/fizzbuzz-7.j | 7 +- Task/FizzBuzz/J/fizzbuzz-8.j | 7 +- Task/FizzBuzz/J/fizzbuzz-9.j | 8 +- Task/FizzBuzz/PowerShell/fizzbuzz-1.psh | 11 - Task/FizzBuzz/PowerShell/fizzbuzz-2.psh | 8 - Task/FizzBuzz/PowerShell/fizzbuzz-3.psh | 7 - Task/FizzBuzz/PowerShell/fizzbuzz-4.psh | 1 - Task/FizzBuzz/PowerShell/fizzbuzz-5.psh | 14 - Task/FizzBuzz/PowerShell/fizzbuzz-6.psh | 1 - Task/FizzBuzz/REBOL/fizzbuzz-1.rebol | 18 - Task/FizzBuzz/REBOL/fizzbuzz-2.rebol | 7 - Task/FizzBuzz/REBOL/fizzbuzz-3.rebol | 1 - Task/FizzBuzz/REBOL/fizzbuzz-4.rebol | 4 - Task/FizzBuzz/Uiua/fizzbuzz.uiua | 2 +- Task/FizzBuzz/VBScript/fizzbuzz-1.vb | 11 - Task/FizzBuzz/VBScript/fizzbuzz-2.vb | 7 - Task/FizzBuzz/VHDL/fizzbuzz.vhdl | 29 - Task/Flatten-a-list/Ada/flatten-a-list-1.ada | 32 - Task/Flatten-a-list/Ada/flatten-a-list-2.ada | 79 -- Task/Flatten-a-list/Ada/flatten-a-list-3.ada | 29 - .../Emacs-Lisp/flatten-a-list-1.l | 6 - .../Emacs-Lisp/flatten-a-list-2.l | 1 - .../Flatten-a-list/Euphoria/flatten-a-list.ex | 21 - Task/Flatten-a-list/Phix/flatten-a-list.phix | 4 +- .../PowerShell/flatten-a-list.psh | 7 - .../Flatten-a-list/REBOL/flatten-a-list.rebol | 9 - .../VBScript/flatten-a-list-1.vb | 32 - .../VBScript/flatten-a-list-2.vb | 4 - .../VBScript/flatten-a-list-3.vb | 15 - .../Ada/flipping-bits-game.ada | 104 -- .../Uiua/flipping-bits-game.uiua | 31 +- .../Ada/flow-control-structures-1.ada | 3 - .../Ada/flow-control-structures-2.ada | 10 - .../Ada/flow-control-structures-3.ada | 8 - .../Ada/flow-control-structures-4.ada | 8 - .../Ada/flow-control-structures-5.ada | 7 - .../COBOL/flow-control-structures-1.cobol | 8 - .../COBOL/flow-control-structures-2.cobol | 4 - .../COBOL/flow-control-structures-3.cobol | 13 - .../COBOL/flow-control-structures-4.cobol | 38 - .../COBOL/flow-control-structures-5.cobol | 23 - .../REBOL/flow-control-structures.rebol | 68 -- .../Ada/floyd-warshall-algorithm.ada | 183 --- .../Pluto/floyd-warshall-algorithm.pluto | 1 - Task/Floyds-triangle/Ada/floyds-triangle.ada | 12 - .../COBOL/floyds-triangle.cobol | 69 -- .../EasyLang/floyds-triangle.easy | 2 +- .../Floyds-triangle/Phix/floyds-triangle.phix | 38 +- .../VBScript/floyds-triangle.vb | 15 - Task/Forest-fire/Ada/forest-fire.ada | 69 -- .../Applesoft-BASIC/forest-fire.basic | 53 +- Task/Forest-fire/COBOL/forest-fire.cobol | 168 --- .../Commodore-BASIC/forest-fire.basic | 53 +- Task/Forest-fire/Emacs-Lisp/forest-fire-1.l | 97 -- Task/Forest-fire/Emacs-Lisp/forest-fire-2.l | 7 - Task/Forest-fire/Uiua/forest-fire.uiua | 16 +- Task/Fork/Ada/fork.ada | 18 - Task/Fork/Batch-File/fork.bat | 49 - Task/Fork/COBOL/fork.cobol | 30 - .../Ada/formal-power-series-1.ada | 23 - .../Ada/formal-power-series-2.ada | 103 -- .../Ada/formal-power-series-3.ada | 53 - .../Ada/formatted-numeric-output.ada | 14 - .../COBOL/formatted-numeric-output.cobol | 10 - .../Emacs-Lisp/formatted-numeric-output.l | 1 - .../Euphoria/formatted-numeric-output.ex | 7 - .../Logo/formatted-numeric-output-1.logo | 4 - .../Logo/formatted-numeric-output-2.logo | 1 - .../PowerShell/formatted-numeric-output-1.psh | 1 - .../PowerShell/formatted-numeric-output-2.psh | 1 - .../REBOL/formatted-numeric-output.rebol | 36 - .../VBScript/formatted-numeric-output.vb | 13 - .../Phix/fortunate-numbers.phix | 38 +- .../REXX/fortunate-numbers.rexx | 11 +- .../11l/forward-difference.11l | 2 +- .../Ada/forward-difference.ada | 50 - .../PowerShell/forward-difference.psh | 22 - Task/Four-bit-adder/Ada/four-bit-adder-1.ada | 23 - Task/Four-bit-adder/Ada/four-bit-adder-2.ada | 52 - .../Arturo/four-bit-adder.arturo | 6 +- .../AutoIt/four-bit-adder-1.autoit | 40 - .../AutoIt/four-bit-adder-2.autoit | 6 - .../Four-bit-adder/COBOL/four-bit-adder.cobol | 107 -- .../M2000-Interpreter/four-bit-adder.m2000 | 2 + Task/Four-bit-adder/Perl/four-bit-adder.pl | 43 - Task/Four-bit-adder/Phix/four-bit-adder.phix | 70 +- .../PowerShell/four-bit-adder-1.psh | 52 - .../PowerShell/four-bit-adder-2.psh | 131 --- .../PowerShell/four-bit-adder-3.psh | 1 - .../Four-bit-adder/VHDL/four-bit-adder-1.vhdl | 161 --- .../Four-bit-adder/VHDL/four-bit-adder-2.vhdl | 45 - Task/Four-is-magic/Phix/four-is-magic.phix | 143 ++- Task/Four-is-magic/V-(Vlang)/four-is-magic.v | 39 +- Task/Fractal-tree/Ada/fractal-tree.ada | 81 -- Task/Fractal-tree/Arturo/fractal-tree.arturo | 2 +- Task/Fractal-tree/EasyLang/fractal-tree.easy | 2 +- Task/Fractal-tree/Red/fractal-tree.red | 31 - .../Ada/fraction-reduction.ada | 120 -- Task/Fractran/Ada/fractran.ada | 43 - Task/Fractran/REXX/fractran.rexx | 8 +- .../Ada/function-composition-1.ada | 13 - .../Ada/function-composition-2.ada | 25 - .../Ada/function-composition-3.ada | 12 - .../Elena/function-composition.elena | 4 +- .../Emacs-Lisp/function-composition-1.l | 7 - .../Emacs-Lisp/function-composition-2.l | 5 - .../Emacs-Lisp/function-composition-3.l | 5 - .../PowerShell/function-composition-1.psh | 7 - .../PowerShell/function-composition-2.psh | 4 - .../REBOL/function-composition-1.rebol | 14 - .../REBOL/function-composition-2.rebol | 8 - .../REXX/function-composition.rexx | 22 +- .../VBScript/function-composition-1.vb | 18 - .../VBScript/function-composition-2.vb | 26 - .../Ada/function-definition-1.ada | 1 - .../Ada/function-definition-2.ada | 4 - .../Ada/function-definition-3.ada | 1 - .../Ada/function-definition-4.ada | 3 - .../Ada/function-definition-5.ada | 4 - .../Ada/function-definition-6.ada | 7 - .../AutoIt/function-definition.autoit | 7 - .../COBOL/function-definition-1.cobol | 26 - .../COBOL/function-definition-2.cobol | 26 - .../Chapel/function-definition-1.chapel | 4 - .../Chapel/function-definition-2.chapel | 4 - .../Emacs-Lisp/function-definition-1.l | 2 - .../Emacs-Lisp/function-definition-2.l | 3 - .../Euphoria/function-definition-1.ex | 3 - .../Euphoria/function-definition-2.ex | 12 - .../Haxe/function-definition.haxe | 3 - .../PowerShell/function-definition-1.psh | 3 - .../PowerShell/function-definition-2.psh | 3 - .../PowerShell/function-definition-3.psh | 3 - .../PowerShell/function-definition-4.psh | 4 - .../PowerShell/function-definition-5.psh | 3 - .../REBOL/function-definition.rebol | 1 - .../REXX/function-definition-1.rexx | 1 - .../REXX/function-definition-2.rexx | 1 - .../VBScript/function-definition-1.vb | 3 - .../VBScript/function-definition-2.vb | 2 - .../Arturo/function-frequency.arturo | 18 +- .../Ada/function-prototype-1.ada | 6 - .../Ada/function-prototype-2.ada | 5 - .../Ada/function-prototype-3.ada | 4 - .../Ada/function-prototype-4.ada | 13 - .../Ada/function-prototype-5.ada | 8 - .../COBOL/function-prototype.cobol | 39 - Task/Fusc-sequence/Ada/fusc-sequence.ada | 96 -- .../Fusc-sequence/Arturo/fusc-sequence.arturo | 8 +- .../Fusc-sequence/EasyLang/fusc-sequence.easy | 31 +- .../Ada/gui-maximum-window-dimensions.ada | 27 - .../Ada/gui-component-interaction.ada | 158 --- .../Euphoria/gui-component-interaction.ex | 42 - .../PowerShell/gui-component-interaction.psh | 25 - .../gui-enabling-disabling-of-controls.ada | 169 --- .../EasyLang/galton-box-animation.easy | 2 +- Task/Gamma-function/Ada/gamma-function-1.ada | 41 - Task/Gamma-function/Ada/gamma-function-2.ada | 9 - .../Arturo/gamma-function.arturo | 6 +- Task/Gamma-function/Pascal/gamma-function.pas | 76 -- .../Gamma-function/Phix/gamma-function-1.phix | 220 ++-- .../Gamma-function/Phix/gamma-function-2.phix | 206 ++-- .../PowerShell/gamma-function.psh | 3 - Task/Gamma-function/REXX/gamma-function.rexx | 4 +- Task/Gamma-function/XPL0/gamma-function.xpl0 | 50 - Task/Gapful-numbers/Ada/gapful-numbers.ada | 44 - .../AutoHotkey/gapful-numbers-1.ahk | 16 +- .../BASIC256/gapful-numbers.basic | 32 +- .../Ballerina/gapful-numbers.ballerina | 11 + .../Gapful-numbers/COBOL/gapful-numbers.cobol | 48 - .../Haskell/gapful-numbers-2.hs | 2 +- .../JavaScript/gapful-numbers-1.js | 48 +- Task/Gapful-numbers/Phix/gapful-numbers.phix | 44 +- .../PowerShell/gapful-numbers.psh | 43 - .../UNIX-Shell/gapful-numbers.sh | 27 +- Task/Gapful-numbers/XBS/gapful-numbers.xbs | 30 +- .../Yabasic/gapful-numbers.basic | 2 +- Task/Gapful-numbers/Zkl/gapful-numbers-1.zkl | 2 +- .../Perl/gauss-jordan-matrix-inversion.pl | 2 +- .../gauss-jordan-matrix-inversion.psh | 51 - .../REXX/gauss-jordan-matrix-inversion-2.rexx | 99 +- .../VBScript/gauss-jordan-matrix-inversion.vb | 88 -- .../Ada/gaussian-elimination.ada | 119 -- .../PowerShell/gaussian-elimination-1.psh | 53 - .../PowerShell/gaussian-elimination-2.psh | 51 - .../VBScript/gaussian-elimination.vb | 46 - .../General-FizzBuzz/Ada/general-fizzbuzz.ada | 50 - .../Crystal/general-fizzbuzz.cr | 56 +- .../Phix/general-fizzbuzz.phix | 34 +- .../PowerShell/general-fizzbuzz.psh | 19 - .../VBScript/general-fizzbuzz.vb | 34 - .../generate-chess960-starting-position.psh | 29 - .../generate-lower-case-ascii-alphabet-1.ada | 1 - .../generate-lower-case-ascii-alphabet-2.ada | 2 - .../generate-lower-case-ascii-alphabet-3.ada | 6 - .../generate-lower-case-ascii-alphabet-4.ada | 34 - .../generate-lower-case-ascii-alphabet.autoit | 7 - .../generate-lower-case-ascii-alphabet.cobol | 17 - .../generate-lower-case-ascii-alphabet.elena | 6 +- .../generate-lower-case-ascii-alphabet-1.psh | 2 - .../generate-lower-case-ascii-alphabet-2.psh | 1 - .../generate-lower-case-ascii-alphabet-3.psh | 1 - .../generate-lower-case-ascii-alphabet-4.psh | 1 - .../generate-lower-case-ascii-alphabet.vb | 9 - .../11l/generate-random-chess-position.11l | 2 +- .../Ada/generator-exponential-1.ada | 23 - .../Ada/generator-exponential-2.ada | 19 - .../Ada/generator-exponential-3.ada | 62 - .../Ada/generator-exponential-4.ada | 59 - .../Ada/generator-exponential-5.ada | 35 - .../Emacs-Lisp/generator-exponential.l | 28 - .../Phix/generator-exponential.phix | 79 +- Task/Generic-swap/Ada/generic-swap-1.ada | 10 - Task/Generic-swap/Ada/generic-swap-2.ada | 7 - .../Generic-swap/Arturo/generic-swap-2.arturo | 2 +- Task/Generic-swap/COBOL/generic-swap.cobol | 74 -- .../Generic-swap/Chapel/generic-swap-1.chapel | 1 - .../Generic-swap/Chapel/generic-swap-2.chapel | 1 - Task/Generic-swap/Elena/generic-swap.elena | 6 +- Task/Generic-swap/Emacs-Lisp/generic-swap-1.l | 6 - Task/Generic-swap/Emacs-Lisp/generic-swap-2.l | 2 - Task/Generic-swap/Emacs-Lisp/generic-swap-3.l | 8 - Task/Generic-swap/Euphoria/generic-swap.ex | 9 - .../PowerShell/generic-swap-1.psh | 1 - .../PowerShell/generic-swap-2.psh | 3 - .../PowerShell/generic-swap-3.psh | 1 - Task/Generic-swap/REBOL/generic-swap.rebol | 18 - Task/Generic-swap/VBScript/generic-swap-1.vb | 6 - Task/Generic-swap/VBScript/generic-swap-2.vb | 7 - Task/Generic-swap/VBScript/generic-swap-3.vb | 2 - .../Ada/get-system-command-output.ada | 39 - .../PowerShell/get-system-command-output.psh | 3 - .../REXX/get-system-command-output.rexx | 27 +- .../VBScript/get-system-command-output.vb | 20 - Task/Giuga-numbers/Ada/giuga-numbers.ada | 54 - .../Giuga-numbers/Arturo/giuga-numbers.arturo | 11 +- ...globally-replace-text-in-several-files.ada | 60 - ...globally-replace-text-in-several-files.psh | 6 - .../globally-replace-text-in-several-files.vb | 14 - .../Agena/goldbachs-comet.agena | 2 +- .../Arturo/goldbachs-comet.arturo | 4 +- .../Gambas/goldbachs-comet-2.gambas | 8 +- .../Pluto/goldbachs-comet.pluto | 23 - .../Goldbachs-comet/REXX/goldbachs-comet.rexx | 8 +- .../Ada/golden-ratio-convergence.ada | 30 - .../COBOL/golden-ratio-convergence.cobol | 28 - .../Phix/golden-ratio-convergence.phix | 20 +- Task/Gray-code/11l/gray-code.11l | 2 +- Task/Gray-code/Ada/gray-code.ada | 47 - Task/Gray-code/Arturo/gray-code.arturo | 6 +- Task/Gray-code/Euphoria/gray-code.ex | 34 - Task/Gray-code/Frink/gray-code.frink | 4 +- Task/Gray-code/VBScript/gray-code.vb | 29 - Task/Gray-code/VHDL/gray-code-1.vhdl | 14 - Task/Gray-code/VHDL/gray-code-2.vhdl | 17 - .../Grayscale-image/Ada/grayscale-image-1.ada | 1 - .../Grayscale-image/Ada/grayscale-image-2.ada | 20 - .../Grayscale-image/Ada/grayscale-image-3.ada | 10 - .../Euphoria/grayscale-image.ex | 20 - .../Ada/greatest-common-divisor.ada | 21 - .../AutoIt/greatest-common-divisor.autoit | 14 - .../COBOL/greatest-common-divisor.cobol | 28 - .../Elena/greatest-common-divisor.elena | 2 +- .../Emacs-Lisp/greatest-common-divisor.l | 5 - .../Euphoria/greatest-common-divisor-1.ex | 13 - .../Euphoria/greatest-common-divisor-2.ex | 9 - .../Euphoria/greatest-common-divisor-3.ex | 40 - .../PowerShell/greatest-common-divisor-1.psh | 18 - .../PowerShell/greatest-common-divisor-2.psh | 3 - .../PowerShell/greatest-common-divisor-3.psh | 6 - .../REBOL/greatest-common-divisor.rebol | 14 - .../Uiua/greatest-common-divisor.uiua | 2 +- .../VBScript/greatest-common-divisor.vb | 17 - .../Ada/greatest-element-of-a-list-1.ada | 28 - .../Ada/greatest-element-of-a-list-2.ada | 4 - .../Ada/greatest-element-of-a-list-3.ada | 8 - .../COBOL/greatest-element-of-a-list-1.cobol | 1 - .../COBOL/greatest-element-of-a-list-2.cobol | 25 - .../EasyLang/greatest-element-of-a-list.easy | 4 +- .../Elena/greatest-element-of-a-list.elena | 2 +- .../Emacs-Lisp/greatest-element-of-a-list-1.l | 8 - .../Emacs-Lisp/greatest-element-of-a-list-2.l | 1 - .../Emacs-Lisp/greatest-element-of-a-list-3.l | 2 - .../Emacs-Lisp/greatest-element-of-a-list-4.l | 1 - .../Euphoria/greatest-element-of-a-list-1.ex | 25 - .../Euphoria/greatest-element-of-a-list-2.ex | 16 - .../PowerShell/greatest-element-of-a-list.psh | 3 - .../REBOL/greatest-element-of-a-list.rebol | 14 - .../VBScript/greatest-element-of-a-list.vb | 13 - .../Ada/greatest-subsequential-sum.ada | 38 - .../Arturo/greatest-subsequential-sum.arturo | 4 +- .../AutoIt/greatest-subsequential-sum.autoit | 36 - .../Euphoria/greatest-subsequential-sum.ex | 22 - .../Lua/greatest-subsequential-sum.lua | 24 +- .../Phix/greatest-subsequential-sum.phix | 36 +- ...greedy-algorithm-for-egyptian-fractions.jl | 9 +- ...eedy-algorithm-for-egyptian-fractions.phix | 150 ++- .../greedy-algorithm-for-egyptian-fractions.r | 40 +- .../Ada/greyscale-bars-display.ada | 85 -- .../EasyLang/greyscale-bars-display.easy | 4 +- ...guess-the-number-with-feedback-player-.ada | 36 - ...ss-the-number-with-feedback-player-.arturo | 19 +- .../guess-the-number-with-feedback-player-.ex | 31 - .../Ada/guess-the-number-with-feedback.ada | 51 - .../guess-the-number-with-feedback.arturo | 15 +- .../guess-the-number-with-feedback.cobol | 30 - .../guess-the-number-with-feedback.elena | 2 +- .../guess-the-number-with-feedback.l | 15 - .../guess-the-number-with-feedback.ex | 19 - .../guess-the-number-with-feedback.psh | 45 - .../guess-the-number-with-feedback.vb | 26 - .../Guess-the-number/Ada/guess-the-number.ada | 92 -- .../AutoIt/guess-the-number.autoit | 6 - .../COBOL/guess-the-number.cobol | 25 - .../Elena/guess-the-number.elena | 2 +- .../Emacs-Lisp/guess-the-number.l | 4 - .../Euphoria/guess-the-number.ex | 17 - .../PowerShell/guess-the-number-1.psh | 12 - .../PowerShell/guess-the-number-2.psh | 2 - .../VBScript/guess-the-number.vb | 21 - Task/HTTP/Ada/http.ada | 9 - Task/HTTP/COBOL/http-1.cobol | 292 ----- Task/HTTP/COBOL/http-2.cobol | 192 ---- Task/HTTP/Elena/http.elena | 2 +- Task/HTTP/Emacs-Lisp/http-1.l | 5 - Task/HTTP/Emacs-Lisp/http-2.l | 3 - Task/HTTP/PowerShell/http-1.psh | 1 - Task/HTTP/PowerShell/http-2.psh | 2 - Task/HTTP/REBOL/http.rebol | 1 - Task/HTTP/VBScript/http.vb | 17 - .../PowerShell/https-authenticated.psh | 7 - Task/HTTPS/Ada/https.ada | 8 - Task/HTTPS/Elena/https.elena | 4 +- Task/HTTPS/PowerShell/https-1.psh | 1 - Task/HTTPS/PowerShell/https-2.psh | 2 - Task/HTTPS/VBScript/https.vb | 17 - .../Ada/hailstone-sequence-1.ada | 39 - .../Ada/hailstone-sequence-2.ada | 4 - .../Ada/hailstone-sequence-3.ada | 15 - .../Ada/hailstone-sequence-4.ada | 43 - .../Arturo/hailstone-sequence.arturo | 6 +- .../AutoIt/hailstone-sequence.autoit | 28 - .../COBOL/hailstone-sequence.cobol | 90 -- .../Elena/hailstone-sequence.elena | 2 +- .../Euphoria/hailstone-sequence.ex | 46 - .../PowerShell/hailstone-sequence.psh | 20 - .../REBOL/hailstone-sequence.rebol | 31 - .../VBScript/hailstone-sequence.vb | 42 - .../Ada/halt-and-catch-fire.ada | 4 - Task/Hamming-numbers/Ada/hamming-numbers.ada | 113 -- .../Chapel/hamming-numbers-1.chapel | 71 -- .../Chapel/hamming-numbers-2.chapel | 53 - .../Chapel/hamming-numbers-3.chapel | 82 -- .../Chapel/hamming-numbers-4.chapel | 85 -- .../Chapel/hamming-numbers-5.chapel | 90 -- .../Hamming-numbers/Mojo/hamming-numbers.mojo | 223 ++-- .../Hamming-numbers/REXX/hamming-numbers.rexx | 16 +- .../VBScript/hamming-numbers.vb | 22 - .../Handle-a-signal/Ada/handle-a-signal-1.ada | 14 - .../Handle-a-signal/Ada/handle-a-signal-2.ada | 29 - .../Handle-a-signal/Ada/handle-a-signal-3.ada | 37 - .../COBOL/handle-a-signal.cobol | 44 - .../PowerShell/handle-a-signal.psh | 18 - Task/Happy-numbers/Ada/happy-numbers.ada | 41 - .../Happy-numbers/Arturo/happy-numbers.arturo | 4 +- .../AutoIt/happy-numbers-1.autoit | 22 - .../AutoIt/happy-numbers-2.autoit | 24 - Task/Happy-numbers/COBOL/happy-numbers.cobol | 56 - Task/Happy-numbers/Elena/happy-numbers.elena | 2 +- Task/Happy-numbers/Euphoria/happy-numbers.ex | 29 - .../PowerShell/happy-numbers-1.psh | 20 - .../PowerShell/happy-numbers-2.psh | 2 - Task/Happy-numbers/REXX/happy-numbers-2.rexx | 82 +- Task/Happy-numbers/Rust/happy-numbers.rs | 25 +- Task/Happy-numbers/Uiua/happy-numbers.uiua | 13 +- Task/Happy-numbers/VBScript/happy-numbers.vb | 30 - Task/Harmonic-series/Ada/harmonic-series.ada | 41 - .../COBOL/harmonic-series.cobol | 39 - .../Phix/harmonic-series-1.phix | 50 +- .../Phix/harmonic-series-2.phix | 49 +- .../Harmonic-series/REXX/harmonic-series.rexx | 77 +- .../Ada/harshad-or-niven-series.ada | 26 - .../COBOL/harshad-or-niven-series.cobol | 78 -- .../PowerShell/harshad-or-niven-series-1.psh | 2 - .../PowerShell/harshad-or-niven-series-2.psh | 41 - .../PowerShell/harshad-or-niven-series-3.psh | 2 - .../VBScript/harshad-or-niven-series.vb | 36 - .../Ada/hash-from-two-arrays.ada | 43 - .../Emacs-Lisp/hash-from-two-arrays.l | 11 - .../PowerShell/hash-from-two-arrays.psh | 13 - .../VBScript/hash-from-two-arrays.vb | 9 - Task/Hash-join/Emacs-Lisp/hash-join.l | 34 - Task/Hash-join/Phix/hash-join.phix | 9 +- Task/Hash-join/VBScript/hash-join.vb | 30 - .../ALGOL-W/haversine-formula.alg | 6 +- .../Ada/haversine-formula.ada | 31 - .../Haversine-formula/Bc/haversine-formula.bc | 18 +- .../Elena/haversine-formula.elena | 2 +- .../Phix/haversine-formula.phix | 27 +- .../PowerShell/haversine-formula-1.psh | 6 - .../PowerShell/haversine-formula-2.psh | 28 - .../Ada/hello-world-graphical.ada | 47 - .../AutoIt/hello-world-graphical-1.autoit | 15 - .../AutoIt/hello-world-graphical-2.autoit | 1 - .../AutoIt/hello-world-graphical-3.autoit | 1 - .../COBOL/hello-world-graphical-1.cobol | 7 - .../COBOL/hello-world-graphical-2.cobol | 7 - .../COBOL/hello-world-graphical-3.cobol | 6 - .../COBOL/hello-world-graphical-4.cobol | 62 - .../COBOL/hello-world-graphical-5.cobol | 19 - .../Elena/hello-world-graphical-1.elena | 2 +- .../Elena/hello-world-graphical-2.elena | 29 +- .../Emacs-Lisp/hello-world-graphical.l | 1 - .../Euphoria/hello-world-graphical.ex | 4 - .../PowerShell/hello-world-graphical-1.psh | 1 - .../PowerShell/hello-world-graphical-2.psh | 9 - .../PowerShell/hello-world-graphical-3.psh | 1 - .../REBOL/hello-world-graphical.rebol | 1 - .../VBScript/hello-world-graphical.vb | 1 - .../360-Assembly/hello-world-line-printer.360 | 13 - .../Ada/hello-world-line-printer.ada | 17 - .../Arturo/hello-world-line-printer.arturo | 2 +- .../COBOL/hello-world-line-printer.cobol | 8 - .../Ada/hello-world-newbie-1.ada | 6 - .../Ada/hello-world-newbie-2.ada | 5 - .../Arturo/hello-world-newbie.arturo | 2 +- .../COBOL/hello-world-newbie-1.cobol | 1 - .../COBOL/hello-world-newbie-2.cobol | 7 - .../COBOL/hello-world-newbie-3.cobol | 1 - .../COBOL/hello-world-newbie-4.cobol | 2 - .../Coq/hello-world-newbie-1.coq | 1 - .../Coq/hello-world-newbie-2.coq | 3 - .../Elena/hello-world-newbie-1.elena | 2 +- .../Phix/hello-world-newbie-1.phix | 4 +- .../Phix/hello-world-newbie-2.phix | 19 +- .../Phix/hello-world-newbie-3.phix | 3 - .../Phix/hello-world-newbie-4.phix | 18 - .../PowerShell/hello-world-newbie-1.psh | 1 - .../PowerShell/hello-world-newbie-2.psh | 1 - .../PowerShell/hello-world-newbie-3.psh | 1 - .../Ada/hello-world-newline-omission-1.ada | 6 - .../Ada/hello-world-newline-omission-2.ada | 8 - .../hello-world-newline-omission.autoit | 1 - .../hello-world-newline-omission-2.bat | 2 +- .../COBOL/hello-world-newline-omission.cobol | 6 - .../Elena/hello-world-newline-omission.elena | 2 +- .../Emacs-Lisp/hello-world-newline-omission.l | 1 - .../Euphoria/hello-world-newline-omission.ex | 2 - .../hello-world-newline-omission.psh | 2 - .../REBOL/hello-world-newline-omission.rebol | 1 - .../Ada/hello-world-standard-error.ada | 6 - .../AutoIt/hello-world-standard-error.autoit | 1 - .../COBOL/hello-world-standard-error.cobol | 4 - .../Emacs-Lisp/hello-world-standard-error-1.l | 1 - .../Emacs-Lisp/hello-world-standard-error-2.l | 1 - .../Euphoria/hello-world-standard-error.ex | 1 - .../hello-world-standard-error-1.psh | 1 - .../hello-world-standard-error-2.psh | 1 - .../VBScript/hello-world-standard-error.vb | 1 - .../hello-world-text-2.aarch64 | 1 + .../hello-world-text-3.aarch64 | 1 + .../Hello-world-Text/Ada/hello-world-text.ada | 5 - .../AutoIt/hello-world-text.autoit | 1 - .../AutoLISP/hello-world-text.l | 1 - .../Batch-File/hello-world-text-2.bat | 2 +- .../COBOL/hello-world-text-1.cobol | 4 - .../COBOL/hello-world-text-2.cobol | 1 - .../Chapel/hello-world-text.chapel | 1 - .../Hello-world-Text/Coq/hello-world-text.coq | 3 - .../Elena/hello-world-text.elena | 2 +- .../Emacs-Lisp/hello-world-text-1.l | 1 - .../Emacs-Lisp/hello-world-text-2.l | 1 - .../Haxe/hello-world-text.haxe | 1 - .../PowerShell/hello-world-text.psh | 1 - .../REBOL/hello-world-text.rebol | 1 - .../ReScript/hello-world-text.re | 1 - .../VBScript/hello-world-text.vb | 1 - .../VHDL/hello-world-text.vhdl | 16 - .../X86-64-Assembly/hello-world-text-6.x86-64 | 6 +- .../AWK/hello-world-web-server.awk | 2 +- .../Ada/hello-world-web-server.ada | 19 - .../Aime/hello-world-web-server-1.aime | 2 +- .../AutoIt/hello-world-web-server.autoit | 17 - .../BBC-BASIC/hello-world-web-server.basic | 4 +- .../Common-Lisp/hello-world-web-server-2.lisp | 2 +- .../FunL/hello-world-web-server.funl | 2 +- .../Haskell/hello-world-web-server-3.hs | 2 +- .../hello-world-web-server.basic | 2 +- .../Panda/hello-world-web-server.panda | 2 +- .../Python/hello-world-web-server-2.py | 2 +- .../R/hello-world-web-server.r | 2 +- .../Run-BASIC/hello-world-web-server.basic | 2 +- .../Smalltalk/hello-world-web-server-1.st | 2 +- .../Smalltalk/hello-world-web-server-2.st | 2 +- .../Standard-ML/hello-world-web-server.ml | 2 +- Task/Here-document/Ada/here-document.ada | 20 - .../PowerShell/here-document.psh | 17 - Task/Here-document/VBScript/here-document.vb | 83 -- .../Ada/heronian-triangles.ada | 131 --- .../PowerShell/heronian-triangles-1.psh | 47 - .../PowerShell/heronian-triangles-2.psh | 23 - Task/Hex-words/Ada/hex-words.ada | 149 --- Task/Hex-words/Arturo/hex-words.arturo | 6 +- Task/Hex-words/Phix/hex-words.phix | 56 +- .../hickerson-series-of-almost-integers.ada | 62 - .../hickerson-series-of-almost-integers.cobol | 29 - .../hickerson-series-of-almost-integers.phix | 32 +- .../Ada/higher-order-functions-1.ada | 17 - .../Ada/higher-order-functions-2.ada | 52 - .../Elena/higher-order-functions.elena | 2 +- .../Euphoria/higher-order-functions.ex | 9 - .../Inform-7/higher-order-functions-2.inf | 2 +- .../Pascal/higher-order-functions-3.pas | 90 +- .../PowerShell/higher-order-functions-1.psh | 6 - .../PowerShell/higher-order-functions-2.psh | 6 - .../PowerShell/higher-order-functions-3.psh | 2 - .../REBOL/higher-order-functions.rebol | 30 - .../REXX/higher-order-functions.rexx | 11 +- Task/Hilbert-curve/Ada/hilbert-curve.ada | 75 -- Task/Hilbert-curve/VBScript/hilbert-curve.vb | 101 -- .../Ada/history-variables-1.ada | 34 - .../Ada/history-variables-2.ada | 35 - .../Ada/history-variables-3.ada | 32 - .../Ada/history-variables-4.ada | 32 - .../Arturo/history-variables.arturo | 59 +- .../Elena/history-variables.elena | 4 +- .../hofstadter-conway-$10-000-sequence.ada | 72 -- .../hofstadter-figure-figure-sequences-1.ada | 7 - .../hofstadter-figure-figure-sequences-2.ada | 51 - .../hofstadter-figure-figure-sequences-3.ada | 40 - .../hofstadter-figure-figure-sequences-4.ada | 2 - .../hofstadter-figure-figure-sequences.vb | 70 -- .../Ada/hofstadter-q-sequence.ada | 59 - .../Arturo/hofstadter-q-sequence.arturo | 2 +- .../COBOL/hofstadter-q-sequence.cobol | 40 - .../VBScript/hofstadter-q-sequence.vb | 27 - .../Ada/holidays-related-to-easter.ada | 52 - .../COBOL/holidays-related-to-easter.cobol | 123 -- .../holidays-related-to-easter-1.psh | 71 -- .../holidays-related-to-easter-2.psh | 8 - Task/Home-primes/Phix/home-primes.phix | 70 +- Task/Home-primes/REXX/home-primes.rexx | 29 +- Task/Honeycombs/Ada/honeycombs.ada | 205 ---- .../Ada/horizontal-sundial-calculations.ada | 45 - .../horizontal-sundial-calculations.cobol | 54 - .../horizontal-sundial-calculations.ex | 35 - .../horizontal-sundial-calculations.psh | 50 - ...horners-rule-for-polynomial-evaluation.ada | 17 - ...rners-rule-for-polynomial-evaluation.agena | 2 +- ...rners-rule-for-polynomial-evaluation.elena | 2 +- .../horners-rule-for-polynomial-evaluation.l | 7 - ...horners-rule-for-polynomial-evaluation.psh | 10 - ...rners-rule-for-polynomial-evaluation.rebol | 11 - ...ners-rule-for-polynomial-evaluation-2.rexx | 4 +- .../horners-rule-for-polynomial-evaluation.vb | 9 - .../Ada/host-introspection.ada | 8 - .../PowerShell/host-introspection.psh | 7 - Task/Hostname/Ada/hostname.ada | 7 - Task/Hostname/Batch-File/hostname.bat | 1 - Task/Hostname/COBOL/hostname.cobol | 15 - Task/Hostname/Emacs-Lisp/hostname.l | 1 - Task/Hostname/Phix/hostname.phix | 16 +- Task/Hostname/PowerShell/hostname-1.psh | 1 - Task/Hostname/PowerShell/hostname-2.psh | 1 - Task/Hostname/REBOL/hostname.rebol | 1 - Task/Hostname/VBScript/hostname.vb | 2 - Task/Huffman-coding/Ada/huffman-coding-1.ada | 83 -- Task/Huffman-coding/Ada/huffman-coding-2.ada | 244 ---- Task/Huffman-coding/Ada/huffman-coding-3.ada | 49 - Task/Huffman-coding/C/huffman-coding-1.c | 2 +- Task/Huffman-coding/C/huffman-coding-2.c | 132 +-- .../Clojure/huffman-coding-1.clj | 2 +- .../Clojure/huffman-coding-2.clj | 32 +- Task/Huffman-coding/Eiffel/huffman-coding.e | 288 ++--- .../Factor/huffman-coding.factor | 34 +- .../Huffman-coding/Icon/huffman-coding-1.icon | 2 +- .../JavaScript/huffman-coding-3.js | 144 +-- .../Objective-C/huffman-coding.m | 174 +-- Task/Huffman-coding/Perl/huffman-coding.pl | 54 +- .../PowerShell/huffman-coding.psh | 61 - Task/Huffman-coding/Prolog/huffman-coding.pro | 46 +- Task/Huffman-coding/Red/huffman-coding.red | 80 +- Task/Huffman-coding/Zkl/huffman-coding-1.zkl | 8 +- Task/Humble-numbers/Ada/humble-numbers.ada | 66 -- .../EasyLang/humble-numbers.easy | 3 +- .../Humble-numbers/Pluto/humble-numbers.pluto | 24 +- Task/Humble-numbers/REXX/humble-numbers.rexx | 8 +- .../Hunt-the-Wumpus/Ada/hunt-the-wumpus-1.ada | 3 - .../Hunt-the-Wumpus/Ada/hunt-the-wumpus-2.ada | 427 ------- .../Hunt-the-Wumpus/Ada/hunt-the-wumpus-3.ada | 6 - Task/I-before-E-except-after-C/00-TASK.txt | 2 +- .../i-before-e-except-after-c.8080 | 414 +++---- .../AWK/i-before-e-except-after-c.awk | 24 +- .../AutoHotkey/i-before-e-except-after-c.ahk | 2 +- .../BASIC256/i-before-e-except-after-c.basic | 14 +- .../i-before-e-except-after-c-1.bat | 14 +- .../Clojure/i-before-e-except-after-c.clj | 2 +- .../i-before-e-except-after-c.basic | 2 +- .../Go/i-before-e-except-after-c.go | 108 +- .../Haskell/i-before-e-except-after-c.hs | 2 +- .../Icon/i-before-e-except-after-c-1.icon | 2 +- .../Icon/i-before-e-except-after-c-2.icon | 2 +- .../Java/i-before-e-except-after-c-2.java | 2 +- .../Java/i-before-e-except-after-c-3.java | 104 +- .../Kotlin/i-before-e-except-after-c.kts | 2 +- .../Langur/i-before-e-except-after-c.langur | 4 +- .../Lasso/i-before-e-except-after-c.lasso | 2 +- .../Lua/i-before-e-except-after-c.lua | 2 +- .../MATLAB/i-before-e-except-after-c.m | 2 +- .../Maple/i-before-e-except-after-c.maple | 32 +- .../i-before-e-except-after-c-1.math | 2 +- .../Nim/i-before-e-except-after-c.nim | 2 +- .../Objeck/i-before-e-except-after-c.objeck | 2 +- .../Octave/i-before-e-except-after-c.octave | 24 +- .../PowerShell/i-before-e-except-after-c.psh | 29 - .../Python/i-before-e-except-after-c-1.py | 2 +- .../R/i-before-e-except-after-c.r | 2 +- .../REXX/i-before-e-except-after-c-1.rexx | 36 - .../REXX/i-before-e-except-after-c-2.rexx | 61 - .../Red/i-before-e-except-after-c.red | 42 +- .../Ruby/i-before-e-except-after-c.rb | 2 +- .../Rust/i-before-e-except-after-c.rs | 2 +- .../Scala/i-before-e-except-after-c.scala | 2 +- .../Swift/i-before-e-except-after-c.swift | 2 +- .../TUSCRIPT/i-before-e-except-after-c.tu | 2 +- .../Tcl/i-before-e-except-after-c.tcl | 24 +- .../V-(Vlang)/i-before-e-except-after-c.v | 38 +- .../VBScript/i-before-e-except-after-c.vb | 48 - .../i-before-e-except-after-c.vb | 2 +- .../Yabasic/i-before-e-except-after-c.basic | 8 +- Task/IBAN/Ada/iban-1.ada | 3 - Task/IBAN/Ada/iban-2.ada | 88 -- Task/IBAN/Ada/iban-3.ada | 21 - Task/IBAN/COBOL/iban.cobol | 161 --- Task/IBAN/PowerShell/iban-1.psh | 26 - Task/IBAN/PowerShell/iban-2.psh | 60 - Task/IBAN/PowerShell/iban-3.psh | 10 - Task/IBAN/VBScript/iban.vb | 58 - .../8080-Assembly/isbn13-check-digit.8080 | 134 +-- .../8086-Assembly/isbn13-check-digit.8086 | 108 +- .../Ada/isbn13-check-digit.ada | 37 - .../Arturo/isbn13-check-digit.arturo | 6 +- .../AutoHotkey/isbn13-check-digit-1.ahk | 6 +- .../AutoHotkey/isbn13-check-digit-2.ahk | 2 +- .../BASIC256/isbn13-check-digit.basic | 34 +- .../COBOL/isbn13-check-digit.cobol | 139 --- .../Delphi/isbn13-check-digit.pas | 22 +- .../EasyLang/isbn13-check-digit.easy | 18 +- .../isbn13-check-digit.m2000 | 54 +- .../MiniScript/isbn13-check-digit.mini | 20 +- .../Pascal/isbn13-check-digit.pas | 94 +- .../Phix/isbn13-check-digit.phix | 35 +- .../PowerShell/isbn13-check-digit.psh | 38 - .../Identity-matrix/Ada/identity-matrix-1.ada | 4 - .../Identity-matrix/Ada/identity-matrix-2.ada | 4 - .../Beads/identity-matrix.beads | 12 +- .../Component-Pascal/identity-matrix.pas | 34 +- Task/Identity-matrix/Eiffel/identity-matrix.e | 86 +- .../Elena/identity-matrix.elena | 2 +- Task/Identity-matrix/LSL/identity-matrix.lsl | 34 +- Task/Identity-matrix/PHP/identity-matrix.php | 6 +- .../PowerShell/identity-matrix-1.psh | 6 - .../PowerShell/identity-matrix-2.psh | 2 - .../Prolog/identity-matrix.pro | 38 +- .../Ring/identity-matrix-2.ring | 44 +- .../Scheme/identity-matrix-1.scm | 20 +- .../SenseTalk/identity-matrix.sensetalk | 32 +- .../Sparkling/identity-matrix.sparkling | 10 +- .../Identity-matrix/Tcl/identity-matrix-1.tcl | 2 +- .../Identity-matrix/Tcl/identity-matrix-2.tcl | 6 +- .../VBScript/identity-matrix-1.vb | 29 - .../VBScript/identity-matrix-2.vb | 15 - .../Identity-matrix/Vala/identity-matrix.vala | 46 +- .../XBasic/identity-matrix.basic | 2 +- ...haracters-that-can-be-used-for-symbols.ada | 12 - ...ll-the-lowercase-and-uppercase-letters.ada | 17 - ...the-lowercase-and-uppercase-letters.arturo | 4 +- ...-the-lowercase-and-uppercase-letters.cobol | 78 -- ...l-the-lowercase-and-uppercase-letters.easy | 11 +- ...l-the-lowercase-and-uppercase-letters-3.hs | 4 +- ...all-the-lowercase-and-uppercase-letters.jl | 21 +- ...l-the-lowercase-and-uppercase-letters.phix | 11 - .../Ada/image-convolution-1.ada | 35 - .../Ada/image-convolution-2.ada | 46 - .../Ada/image-convolution-3.ada | 12 - Task/Image-noise/Ada/image-noise-1.ada | 7 - Task/Image-noise/Ada/image-noise-2.ada | 28 - Task/Image-noise/Ada/image-noise-3.ada | 179 --- Task/Include-a-file/Ada/include-a-file.ada | 7 - .../Arturo/include-a-file.arturo | 4 +- .../Include-a-file/COBOL/include-a-file.cobol | 4 - .../Emacs-Lisp/include-a-file-1.l | 2 - .../Emacs-Lisp/include-a-file-2.l | 3 - .../Include-a-file/Euphoria/include-a-file.ex | 1 - .../PowerShell/include-a-file.psh | 14 - .../RISC-V-Assembly/include-a-file-2.asm | 34 + .../VBScript/include-a-file-1.vb | 8 - .../VBScript/include-a-file-2.vb | 1 - .../VBScript/include-a-file-3.vb | 7 - ...aps-between-consecutive-niven-numbers.easy | 44 +- .../Ada/increment-a-numerical-string.ada | 2 - .../increment-a-numerical-string.autoit | 3 - .../increment-a-numerical-string-1.cobol | 14 - .../increment-a-numerical-string-2.cobol | 13 - .../Elena/increment-a-numerical-string.elena | 2 +- .../Emacs-Lisp/increment-a-numerical-string.l | 1 - .../Euphoria/increment-a-numerical-string.ex | 12 - .../increment-a-numerical-string.pas | 69 +- .../increment-a-numerical-string-1.psh | 2 - .../increment-a-numerical-string-2.psh | 1 - .../REBOL/increment-a-numerical-string.rebol | 21 - ...x-finite-lists-of-positive-integers.arturo | 4 +- Task/Infinity/Ada/infinity-1.ada | 24 - Task/Infinity/Ada/infinity-2.ada | 26 - Task/Infinity/Ada/infinity-3.ada | 1 - Task/Infinity/Arturo/infinity.arturo | 4 +- Task/Infinity/Euphoria/infinity.ex | 3 - Task/Infinity/PowerShell/infinity.psh | 3 - .../Ada/inheritance-multiple.ada | 5 - .../COBOL/inheritance-multiple.cobol | 21 - .../Elena/inheritance-multiple-1.elena | 6 +- .../Elena/inheritance-multiple-2.elena | 6 +- .../PowerShell/inheritance-multiple.psh | 3 - .../Ada/inheritance-single.ada | 13 - .../COBOL/inheritance-single.cobol | 48 - .../Haxe/inheritance-single-1.haxe | 15 - .../Haxe/inheritance-single-2.haxe | 14 - .../PowerShell/inheritance-single.psh | 5 - .../REBOL/inheritance-single.rebol | 26 - Task/Input-loop/Ada/input-loop.ada | 18 - Task/Input-loop/Batch-File/input-loop.bat | 1 - Task/Input-loop/COBOL/input-loop.cobol | 33 - Task/Input-loop/Elena/input-loop-1.elena | 4 +- Task/Input-loop/Elena/input-loop-2.elena | 2 +- Task/Input-loop/Euphoria/input-loop.ex | 10 - Task/Input-loop/PowerShell/input-loop-1.psh | 4 - Task/Input-loop/PowerShell/input-loop-2.psh | 1 - Task/Input-loop/REBOL/input-loop.rebol | 21 - Task/Input-loop/REXX/input-loop-1.rexx | 3 - Task/Input-loop/REXX/input-loop-2.rexx | 4 - Task/Input-loop/REXX/input-loop-3.rexx | 5 - Task/Input-loop/REXX/input-loop-4.rexx | 4 - Task/Input-loop/REXX/input-loop-5.rexx | 4 - Task/Input-loop/VBScript/input-loop.vb | 12 - .../ALGOL-W/integer-comparison.alg | 14 - .../Ada/integer-comparison.ada | 24 - .../COBOL/integer-comparison.cobol | 26 - .../Elena/integer-comparison.elena | 12 +- .../Emacs-Lisp/integer-comparison.l | 7 - .../Euphoria/integer-comparison.ex | 15 - .../PowerShell/integer-comparison.psh | 10 - .../REBOL/integer-comparison.rebol | 13 - .../ReScript/integer-comparison.re | 11 - .../VBScript/integer-comparison.vb | 27 - .../Integer-overflow/Ada/integer-overflow.ada | 51 - .../COBOL/integer-overflow-1.cobol | 10 - .../COBOL/integer-overflow-2.cobol | 78 -- .../PowerShell/integer-overflow.psh | 30 - .../VBScript/integer-overflow.vb | 14 - .../Ada/integer-sequence-1.ada | 9 - .../Ada/integer-sequence-2.ada | 7 - .../COBOL/integer-sequence.cobol | 16 - .../EasyLang/integer-sequence.easy | 4 +- .../Elena/integer-sequence.elena | 4 +- .../Emacs-Lisp/integer-sequence.l | 2 - .../Euphoria/integer-sequence.ex | 6 - .../Kotlin/integer-sequence.kts | 2 +- .../PowerShell/integer-sequence.psh | 8 - .../Elena/interactive-programming-repl-.elena | 34 +- .../interactive-programming-repl--1.l | 5 - .../interactive-programming-repl--2.l | 7 - .../interactive-programming-repl-.psh | 10 - .../REBOL/interactive-programming-repl-.rebol | 5 - .../REXX/interactive-programming-repl--1.rexx | 16 +- .../REXX/interactive-programming-repl--2.rexx | 29 +- .../REXX/interactive-programming-repl--3.rexx | 7 - Task/Introspection/Ada/introspection.ada | 14 - .../Introspection/Arturo/introspection.arturo | 4 +- .../PowerShell/introspection.psh | 14 - Task/Inverted-index/Ada/inverted-index-1.ada | 114 -- Task/Inverted-index/Ada/inverted-index-2.ada | 63 - Task/Inverted-index/Ada/inverted-index-3.ada | 95 -- Task/Inverted-index/Ada/inverted-index-4.ada | 20 - Task/Inverted-index/Ada/inverted-index-5.ada | 42 - Task/Inverted-index/Ada/inverted-index-6.ada | 56 - Task/Inverted-index/Ada/inverted-index-7.ada | 82 -- .../PowerShell/inverted-index-1.psh | 43 - .../PowerShell/inverted-index-2.psh | 15 - .../PowerShell/inverted-index-3.psh | 2 - .../PowerShell/inverted-index-4.psh | 2 - Task/Inverted-syntax/Ada/inverted-syntax.ada | 5 - .../Phix/inverted-syntax-1.phix | 36 +- .../Phix/inverted-syntax-2.phix | 36 +- .../PowerShell/inverted-syntax-1.psh | 1 - .../PowerShell/inverted-syntax-2.psh | 8 - .../11l/isqrt-integer-square-root-of-x.11l | 11 +- .../Ada/isqrt-integer-square-root-of-x.ada | 87 -- .../isqrt-integer-square-root-of-x.arturo | 6 +- .../isqrt-integer-square-root-of-x.cobol | 74 -- .../isqrt-integer-square-root-of-x.easy | 4 +- .../Phix/isqrt-integer-square-root-of-x.phix | 86 +- .../REXX/isqrt-integer-square-root-of-x.rexx | 12 +- .../ALGOL-68/iterated-digits-squaring.alg | 2 +- .../Ada/iterated-digits-squaring.ada | 40 - .../Arturo/iterated-digits-squaring.arturo | 4 +- .../BQN/iterated-digits-squaring-1.bqn | 2 +- .../BQN/iterated-digits-squaring-2.bqn | 12 +- .../BQN/iterated-digits-squaring-3.bqn | 8 +- .../Phix/iterated-digits-squaring-1.phix | 82 +- .../Phix/iterated-digits-squaring-2.phix | 54 +- .../Phix/iterated-digits-squaring-3.phix | 118 +- .../VBScript/iterated-digits-squaring.vb | 20 - Task/JSON/Ada/json-1.ada | 41 - Task/JSON/Ada/json-2.ada | 41 - Task/JSON/Arturo/json.arturo | 2 +- Task/JSON/Bracmat/json-1.bracmat | 2 +- Task/JSON/Elena/json.elena | 6 +- Task/JSON/Emacs-Lisp/json-1.l | 18 - Task/JSON/Emacs-Lisp/json-2.l | 19 - Task/JSON/Hoon/json-1.hoon | 15 - Task/JSON/Hoon/json-2.hoon | 7 - Task/JSON/PowerShell/json-1.psh | 7 - Task/JSON/PowerShell/json-2.psh | 11 - Task/JSON/REBOL/json-1.rebol | 14 - Task/JSON/REBOL/json-2.rebol | 16 - Task/Jacobi-symbol/Phix/jacobi-symbol.phix | 50 +- Task/Jacobi-symbol/V-(Vlang)/jacobi-symbol.v | 4 +- .../Ada/jacobsthal-numbers.ada | 121 -- .../Agena/jacobsthal-numbers.agena | 2 +- .../Arturo/jacobsthal-numbers.arturo | 2 +- Task/Jaro-similarity/Ada/jaro-similarity.ada | 91 -- .../COBOL/jaro-similarity.cobol | 98 -- .../Emacs-Lisp/jaro-similarity.l | 55 - .../Jaro-similarity/Haxe/jaro-similarity.haxe | 39 - Task/Jensens-Device/Ada/jensens-device.ada | 26 - .../Arturo/jensens-device.arturo | 2 +- Task/Jensens-Device/Phix/jensens-device.phix | 22 +- .../Ada/jewels-and-stones.ada | 32 - .../EasyLang/jewels-and-stones.easy | 7 +- .../Euphoria/jewels-and-stones.ex | 11 - .../REXX/jewels-and-stones.rexx | 63 +- .../EasyLang/jordan-p-lya-numbers.easy | 42 +- Task/JortSort/Ada/jortsort.ada | 18 - Task/JortSort/Phix/jortsort-1.phix | 8 +- Task/JortSort/Phix/jortsort-2.phix | 6 +- Task/JortSort/Phix/jortsort-3.phix | 4 +- Task/JortSort/PowerShell/jortsort.psh | 3 - Task/JortSort/VBScript/jortsort.vb | 25 - .../Josephus-problem/Ada/josephus-problem.ada | 43 - .../Arturo/josephus-problem.arturo | 2 +- .../Emacs-Lisp/josephus-problem.l | 9 - .../PowerShell/josephus-problem-1.psh | 20 - .../PowerShell/josephus-problem-2.psh | 12 - .../REBOL/josephus-problem-1.rebol | 13 - .../REBOL/josephus-problem-2.rebol | 3 - .../VBScript/josephus-problem.vb | 32 - .../Juggler-sequence/Ada/juggler-sequence.ada | 78 -- .../Phix/juggler-sequence.phix | 97 +- Task/Julia-set/00-META.yaml | 1 + Task/Julia-set/Ada/julia-set.ada | 93 -- Task/Julia-set/COBOL/julia-set.cobol | 59 - Task/Julia-set/EasyLang/julia-set.easy | 35 +- Task/Julia-set/Emacs-Lisp/julia-set.l | 55 - Task/Julia-set/VBScript/julia-set.vb | 21 - Task/Jump-anywhere/Ada/jump-anywhere.ada | 48 - .../Jump-anywhere/COBOL/jump-anywhere-1.cobol | 32 - .../Jump-anywhere/COBOL/jump-anywhere-2.cobol | 7 - .../PowerShell/jump-anywhere-1.psh | 1 - .../PowerShell/jump-anywhere-2.psh | 9 - .../PowerShell/jump-anywhere-3.psh | 15 - .../Kaprekar-numbers/Ada/kaprekar-numbers.ada | 131 --- .../Arturo/kaprekar-numbers.arturo | 4 +- .../PowerShell/kaprekar-numbers-1.psh | 25 - .../PowerShell/kaprekar-numbers-2.psh | 5 - .../REXX/kaprekar-numbers.rexx | 208 +++- .../kernighans-large-earthquake-problem.ada | 33 - ...kernighans-large-earthquake-problem.arturo | 2 +- ...ernighans-large-earthquake-problem-1.cobol | 85 -- ...ernighans-large-earthquake-problem-2.cobol | 33 - .../kernighans-large-earthquake-problem.l | 10 - .../kernighans-large-earthquake-problem.pl | 1 - .../kernighans-large-earthquake-problem.phix | 28 +- ...yboard-input-flush-the-keyboard-buffer.ada | 20 - ...keyboard-input-flush-the-keyboard-buffer.l | 1 - ...eyboard-input-flush-the-keyboard-buffer.ex | 2 - ...oard-input-flush-the-keyboard-buffer-1.psh | 3 - ...oard-input-flush-the-keyboard-buffer-2.psh | 1 - .../Ada/keyboard-input-keypress-check.ada | 4 - .../keyboard-input-keypress-check.easy | 2 +- .../Elena/keyboard-input-keypress-check.elena | 8 +- .../keyboard-input-keypress-check.l | 21 - .../Euphoria/keyboard-input-keypress-check.ex | 2 - .../keyboard-input-keypress-check.psh | 3 - ...eyboard-input-obtain-a-y-or-n-response.ada | 13 - ...yboard-input-obtain-a-y-or-n-response.easy | 2 +- .../keyboard-input-obtain-a-y-or-n-response.l | 5 - ...keyboard-input-obtain-a-y-or-n-response.ex | 14 - ...eyboard-input-obtain-a-y-or-n-response.psh | 7 - .../REBOL/keyboard-macros.rebol | 28 - .../Ada/knapsack-problem-0-1.ada | 109 -- .../D/knapsack-problem-0-1-2.d | 4 +- .../Emacs-Lisp/knapsack-problem-0-1-1.l | 34 - .../Emacs-Lisp/knapsack-problem-0-1-2.l | 47 - .../JavaScript/knapsack-problem-0-1.js | 68 -- .../Python/knapsack-problem-0-1-4.py | 40 +- .../VBScript/knapsack-problem-0-1.vb | 214 ---- .../Wren/knapsack-problem-0-1.wren | 1 - .../Ada/knapsack-problem-bounded.ada | 143 --- .../ALGOL-W/knapsack-problem-continuous.alg | 15 +- .../Ada/knapsack-problem-continuous.ada | 102 -- .../Ada/knapsack-problem-unbounded.ada | 65 -- .../PowerShell/knapsack-problem-unbounded.psh | 62 - .../ANSI-BASIC/knights-tour.basic | 138 +-- Task/Knights-tour/Ada/knights-tour-1.ada | 22 - Task/Knights-tour/Ada/knights-tour-2.ada | 85 -- Task/Knights-tour/Ada/knights-tour-3.ada | 11 - Task/Knights-tour/Ada/knights-tour-4.ada | 4 - Task/Knights-tour/Ada/knights-tour-5.ada | 86 -- Task/Knights-tour/Ada/knights-tour-6.ada | 11 - .../FutureBasic/knights-tour.basic | 270 ----- Task/Knuth-shuffle/Ada/knuth-shuffle-1.ada | 5 - Task/Knuth-shuffle/Ada/knuth-shuffle-2.ada | 17 - Task/Knuth-shuffle/Ada/knuth-shuffle-3.ada | 22 - .../Knuth-shuffle/AutoIt/knuth-shuffle.autoit | 25 - Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol | 29 - Task/Knuth-shuffle/Elena/knuth-shuffle.elena | 6 +- Task/Knuth-shuffle/Euphoria/knuth-shuffle.ex | 23 - .../PowerShell/knuth-shuffle-1.psh | 2 - .../PowerShell/knuth-shuffle-2.psh | 9 - .../Knuth-shuffle/REBOL/knuth-shuffle-1.rebol | 4 - .../Knuth-shuffle/REBOL/knuth-shuffle-2.rebol | 48 - .../Knuth-shuffle/VBScript/knuth-shuffle-1.vb | 19 - .../Knuth-shuffle/VBScript/knuth-shuffle-2.vb | 14 - .../Ada/knuths-algorithm-s-1.ada | 12 - .../Ada/knuths-algorithm-s-2.ada | 38 - .../Ada/knuths-algorithm-s-3.ada | 34 - .../Elena/knuths-algorithm-s.elena | 8 +- .../Phix/knuths-algorithm-s-1.phix | 85 +- .../Phix/knuths-algorithm-s-2.phix | 20 +- .../11l/knuths-power-tree.11l | 2 +- .../Ada/knuths-power-tree.ada | 116 -- Task/Koch-curve/Ada/koch-curve.ada | 61 - Task/Koch-curve/VBScript/koch-curve.vb | 104 -- .../Arturo/kolakoski-sequence.arturo | 14 +- .../Ada/kronecker-product-based-fractals.ada | 114 -- .../Ada/kronecker-product.ada | 55 - .../Arturo/kronecker-product.arturo | 10 +- .../VBScript/kronecker-product.vb | 85 -- .../Ada/lu-decomposition-1.ada | 9 - .../Ada/lu-decomposition-2.ada | 77 -- .../Ada/lu-decomposition-3.ada | 53 - .../LZW-compression/Ada/lzw-compression-1.ada | 11 - .../LZW-compression/Ada/lzw-compression-2.ada | 116 -- .../LZW-compression/Ada/lzw-compression-3.ada | 21 - .../Arturo/lzw-compression.arturo | 14 +- Task/LZW-compression/Julia/lzw-compression.jl | 50 - .../LZW-compression/Phix/lzw-compression.phix | 59 - .../VBScript/lzw-compression.vb | 74 -- Task/Lah-numbers/11l/lah-numbers.11l | 4 +- Task/Lah-numbers/Ada/lah-numbers.ada | 70 -- Task/Lah-numbers/EasyLang/lah-numbers.easy | 4 +- Task/Lah-numbers/Phix/lah-numbers.phix | 84 +- Task/Lah-numbers/VBScript/lah-numbers.vb | 53 - Task/Langtons-ant/Ada/langtons-ant.ada | 56 - Task/Langtons-ant/AutoIt/langtons-ant.autoit | 76 -- Task/Langtons-ant/COBOL/langtons-ant.cobol | 91 -- Task/Langtons-ant/Chapel/langtons-ant.chapel | 68 -- Task/Langtons-ant/Euphoria/langtons-ant-1.ex | 65 -- Task/Langtons-ant/Euphoria/langtons-ant-2.ex | 2 - Task/Langtons-ant/Phix/langtons-ant.phix | 28 +- Task/Langtons-ant/PowerShell/langtons-ant.psh | 27 - Task/Langtons-ant/Uiua/langtons-ant.uiua | 5 +- .../largest-int-from-concatenated-ints-1.ada | 2 - .../largest-int-from-concatenated-ints-2.ada | 32 - .../largest-int-from-concatenated-ints.arturo | 2 +- .../largest-int-from-concatenated-ints-1.psh | 17 - .../largest-int-from-concatenated-ints-2.psh | 3 - .../largest-int-from-concatenated-ints.vb | 24 - ...largest-number-divisible-by-its-digits.ada | 48 - ...gest-number-divisible-by-its-digits.arturo | 4 +- ...rgest-number-divisible-by-its-digits.basic | 42 +- ...rgest-number-divisible-by-its-digits-2.cpp | 52 +- ...largest-number-divisible-by-its-digits-1.c | 40 +- ...argest-number-divisible-by-its-digits.easy | 22 +- ...gest-number-divisible-by-its-digits-2.java | 84 +- ...gest-number-divisible-by-its-digits-1.phix | 37 +- ...gest-number-divisible-by-its-digits-2.phix | 54 +- ...largest-number-divisible-by-its-digits.pro | 6 +- .../largest-number-divisible-by-its-digits.vb | 21 - ...rgest-number-divisible-by-its-digits-1.zkl | 2 +- ...rgest-number-divisible-by-its-digits-2.zkl | 2 +- .../Ada/largest-proper-divisor-of-n.ada | 25 - .../AutoLISP/largest-proper-divisor-of-n.l | 22 - .../Ada/last-friday-of-each-month.ada | 30 - .../Arturo/last-friday-of-each-month.arturo | 4 +- .../AutoIt/last-friday-of-each-month.autoit | 22 - .../COBOL/last-friday-of-each-month.cobol | 48 - .../Emacs-Lisp/last-friday-of-each-month.l | 14 - .../MATLAB/last-friday-of-each-month.m | 9 - .../Phix/last-friday-of-each-month.phix | 26 +- .../last-friday-of-each-month-1.psh | 13 - .../last-friday-of-each-month-2.psh | 97 -- .../last-friday-of-each-month-3.psh | 1 - .../last-friday-of-each-month-4.psh | 1 - .../last-friday-of-each-month-5.psh | 1 - .../Python/last-friday-of-each-month-1.py | 21 +- .../Python/last-friday-of-each-month-2.py | 23 +- .../Python/last-friday-of-each-month-3.py | 26 +- .../Python/last-friday-of-each-month-4.py | 26 +- .../REBOL/last-friday-of-each-month-1.rebol | 22 - .../REBOL/last-friday-of-each-month-2.rebol | 12 - .../11l/last-letter-first-letter.11l | 3 +- .../Ada/last-letter-first-letter.ada | 79 -- .../EasyLang/last-letter-first-letter.easy | 53 +- .../VBScript/last-letter-first-letter.vb | 58 - .../Ada/law-of-cosines---triples.ada | 70 -- Task/Leap-year/Ada/leap-year.ada | 35 - Task/Leap-year/AutoIt/leap-year.autoit | 12 - Task/Leap-year/COBOL/leap-year-1.cobol | 29 - Task/Leap-year/COBOL/leap-year-2.cobol | 33 - Task/Leap-year/Emacs-Lisp/leap-year.l | 4 - Task/Leap-year/Euphoria/leap-year.ex | 3 - Task/Leap-year/Oberon-07/leap-year-1.oberon | 74 ++ Task/Leap-year/Pascal/leap-year.pas | 17 - Task/Leap-year/PowerShell/leap-year.psh | 2 - Task/Leap-year/REBOL/leap-year.rebol | 15 - Task/Leap-year/VBScript/leap-year.vb | 17 - .../Ada/least-common-multiple.ada | 28 - .../AutoIt/least-common-multiple-1.autoit | 13 - .../AutoIt/least-common-multiple-2.autoit | 3 - .../COBOL/least-common-multiple.cobol | 63 - .../Elena/least-common-multiple.elena | 4 +- .../Euphoria/least-common-multiple.ex | 13 - .../Phix/least-common-multiple.phix | 8 +- .../PowerShell/least-common-multiple-1.psh | 16 - .../PowerShell/least-common-multiple-2.psh | 16 - .../Uiua/least-common-multiple.uiua | 8 +- .../VBScript/least-common-multiple.vb | 30 - Task/Left-factorials/Ada/left-factorials.ada | 76 -- .../PowerShell/left-factorials.psh | 26 - .../00-TASK.txt | 13 +- .../11l/legendre-prime-counting-function.11l | 2 +- .../legendre-prime-counting-function-1.chapel | 60 - .../legendre-prime-counting-function-2.chapel | 78 -- .../legendre-prime-counting-function-3.chapel | 66 -- .../legendre-prime-counting-function.mojo | 171 +-- .../legendre-prime-counting-function-4.nim | 168 +-- .../legendre-prime-counting-function-1.phix | 90 +- .../legendre-prime-counting-function-2.phix | 255 ++--- .../legendre-prime-counting-function.py | 24 - .../legendre-prime-counting-function-1.rexx | 8 +- .../legendre-prime-counting-function-2.rexx | 8 +- .../legendre-prime-counting-function-3.rexx | 8 +- .../Leonardo-numbers/Ada/leonardo-numbers.ada | 30 - .../COBOL/leonardo-numbers.cobol | 46 - .../REXX/leonardo-numbers.rexx | 54 +- .../Letter-frequency/Ada/letter-frequency.ada | 20 - .../AutoIt/letter-frequency.autoit | 26 - .../COBOL/letter-frequency.cobol | 182 --- .../Emacs-Lisp/letter-frequency.l | 15 - .../Euphoria/letter-frequency.ex | 24 - .../PowerShell/letter-frequency.psh | 9 - .../REXX/letter-frequency-1.rexx | 83 +- .../Letter-frequency/TAV/letter-frequency.tav | 8 +- .../V-(Vlang)/letter-frequency.v | 2 +- .../VBScript/letter-frequency.vb | 24 - .../Ada/levenshtein-distance-alignment.ada | 88 -- .../Ada/levenshtein-distance.ada | 34 - .../COBOL/levenshtein-distance.cobol | 62 - .../Euphoria/levenshtein-distance.ex | 47 - .../PowerShell/levenshtein-distance-1.psh | 59 - .../PowerShell/levenshtein-distance-2.psh | 2 - .../VBScript/levenshtein-distance.vb | 44 - .../Ada/linear-congruential-generator-1.ada | 11 - .../Ada/linear-congruential-generator-2.ada | 16 - .../Ada/linear-congruential-generator-3.ada | 20 - .../linear-congruential-generator.psh | 24 - .../REXX/linear-congruential-generator.rexx | 44 +- .../Ada/list-comprehensions.ada | 45 - .../Phix/list-comprehensions-1.phix | 16 +- .../Phix/list-comprehensions-2.phix | 46 +- .../R/list-comprehensions-1.r | 11 +- .../R/list-comprehensions-2.r | 2 +- .../Ada/literals-floating-point.ada | 3 - .../Euphoria/literals-floating-point.ex | 3 - .../REXX/literals-floating-point.rexx | 4 +- .../Literals-Integer/Ada/literals-integer.ada | 9 - .../COBOL/literals-integer-1.cobol | 2 - .../COBOL/literals-integer-2.cobol | 2 - .../Emacs-Lisp/literals-integer.l | 5 - .../Euphoria/literals-integer.ex | 6 - .../PowerShell/literals-integer-1.psh | 2 - .../PowerShell/literals-integer-2.psh | 4 - .../REBOL/literals-integer.rebol | 1 - .../REXX/literals-integer.rexx | 9 +- .../Literals-String/Ada/literals-string-1.ada | 1 - .../Literals-String/Ada/literals-string-2.ada | 2 - .../COBOL/literals-string-1.cobol | 2 - .../COBOL/literals-string-2.cobol | 2 - .../COBOL/literals-string-3.cobol | 6 - .../Emacs-Lisp/literals-string-1.l | 1 - .../Emacs-Lisp/literals-string-2.l | 2 - .../Ada/logical-operations.ada | 7 - .../COBOL/logical-operations.cobol | 26 - .../Elena/logical-operations.elena | 10 +- .../Euphoria/logical-operations.ex | 6 - .../Langur/logical-operations.langur | 2 +- .../PowerShell/logical-operations.psh | 7 - .../REBOL/logical-operations.rebol | 13 - .../ReScript/logical-operations.re | 15 - ...logistic-curve-fitting-in-epidemiology.ada | 91 -- ...istic-curve-fitting-in-epidemiology.arturo | 14 +- .../Ada/long-literals-with-continuations.ada | 34 - .../Ada/long-multiplication-1.ada | 34 - .../Ada/long-multiplication-2.ada | 145 --- .../Ada/long-multiplication-3.ada | 11 - .../Ada/long-multiplication-4.ada | 24 - .../Ada/long-multiplication-5.ada | 21 - .../Ada/long-multiplication-6.ada | 26 - .../Arturo/long-multiplication.arturo | 47 +- .../COBOL/long-multiplication.cobol | 88 -- .../Euphoria/long-multiplication.ex | 58 - .../Icon/long-multiplication.icon | 45 +- .../PowerShell/long-multiplication-1.psh | 80 -- .../PowerShell/long-multiplication-2.psh | 2 - Task/Long-primes/EasyLang/long-primes.easy | 4 +- Task/Long-primes/REXX/long-primes.rexx | 4 +- Task/Long-year/Ada/long-year.ada | 34 - Task/Long-year/Arturo/long-year.arturo | 4 +- Task/Long-year/Oberon-07/long-year-1.oberon | 28 - Task/Long-year/Oberon-07/long-year-2.oberon | 12 - Task/Long-year/Phix/long-year.phix | 44 +- Task/Long-year/PowerShell/long-year.psh | 10 - .../ALGOL-68/longest-common-subsequence.alg | 3 +- .../Ada/longest-common-subsequence-1.ada | 25 - .../Ada/longest-common-subsequence-2.ada | 45 - .../Arturo/longest-common-subsequence.arturo | 12 +- .../EasyLang/longest-common-subsequence.easy | 19 +- .../longest-common-subsequence-1.psh | 47 - .../longest-common-subsequence-2.psh | 1 - .../longest-common-subsequence-3.psh | 1 - .../longest-common-subsequence-4.psh | 25 - .../Ada/longest-common-substring.ada | 30 - .../Arturo/longest-common-substring.arturo | 7 +- .../Phix/longest-common-substring.phix | 51 +- .../PowerShell/longest-common-substring.psh | 62 - .../REXX/longest-common-substring.rexx | 73 +- .../VBScript/longest-common-substring.vb | 14 - .../Ada/longest-increasing-subsequence.ada | 51 - .../longest-increasing-subsequence.arturo | 2 +- .../Julia/longest-increasing-subsequence.jl | 24 +- .../Phix/longest-increasing-subsequence.phix | 76 +- .../longest-increasing-subsequence-1.psh | 48 - .../longest-increasing-subsequence-2.psh | 2 - .../longest-increasing-subsequence.vb | 37 - .../Ada/longest-string-challenge-1.ada | 144 --- .../Ada/longest-string-challenge-2.ada | 52 - .../Ada/longest-string-challenge-3.ada | 55 - .../Phix/longest-string-challenge-1.phix | 46 +- .../Phix/longest-string-challenge-2.phix | 24 +- .../PowerShell/longest-string-challenge-1.psh | 40 - .../PowerShell/longest-string-challenge-2.psh | 12 - .../VBScript/longest-string-challenge.vb | 25 - .../Ada/look-and-say-sequence-1.ada | 13 - .../Ada/look-and-say-sequence-2.ada | 10 - .../Arturo/look-and-say-sequence.arturo | 7 +- .../COBOL/look-and-say-sequence.cobol | 43 - .../Haxe/look-and-say-sequence.haxe | 39 - .../PowerShell/look-and-say-sequence.psh | 21 - .../VBScript/look-and-say-sequence-1.vb | 20 - .../VBScript/look-and-say-sequence-2.vb | 6 - ...op-over-multiple-arrays-simultaneously.ada | 13 - ...-over-multiple-arrays-simultaneously.cobol | 23 - ...over-multiple-arrays-simultaneously.chapel | 6 - ...ver-multiple-arrays-simultaneously-1.elena | 6 +- ...ver-multiple-arrays-simultaneously-2.elena | 6 +- ...p-over-multiple-arrays-simultaneously-1.ex | 9 - ...p-over-multiple-arrays-simultaneously-2.ex | 9 - ...p-over-multiple-arrays-simultaneously-3.ex | 12 - ...p-over-multiple-arrays-simultaneously.haxe | 22 - ...oop-over-multiple-arrays-simultaneously.pl | 13 - ...-over-multiple-arrays-simultaneously-1.psh | 10 - ...-over-multiple-arrays-simultaneously-2.psh | 1 - ...-over-multiple-arrays-simultaneously-3.psh | 1 - ...-over-multiple-arrays-simultaneously.rebol | 10 - ...p-over-multiple-arrays-simultaneously.uiua | 1 - ...oop-over-multiple-arrays-simultaneously.vb | 9 - Task/Loops-Break/Ada/loops-break.ada | 18 - Task/Loops-Break/COBOL/loops-break.cobol | 26 - Task/Loops-Break/Chapel/loops-break.chapel | 11 - Task/Loops-Break/Emacs-Lisp/loops-break.l | 10 - Task/Loops-Break/Euphoria/loops-break.ex | 9 - Task/Loops-Break/Haxe/loops-break.haxe | 12 - Task/Loops-Break/J/loops-break-1.j | 21 +- Task/Loops-Break/J/loops-break-2.j | 8 +- Task/Loops-Break/J/loops-break-3.j | 27 +- Task/Loops-Break/J/loops-break-4.j | 5 +- Task/Loops-Break/PowerShell/loops-break.psh | 9 - Task/Loops-Break/REBOL/loops-break.rebol | 16 - Task/Loops-Break/V-(Vlang)/loops-break.v | 4 +- Task/Loops-Break/VBScript/loops-break.vb | 17 - Task/Loops-Continue/Ada/loops-continue-1.ada | 15 - Task/Loops-Continue/Ada/loops-continue-2.ada | 18 - .../Loops-Continue/COBOL/loops-continue.cobol | 21 - .../Chapel/loops-continue.chapel | 8 - .../Euphoria/loops-continue-1.ex | 11 - .../Euphoria/loops-continue-2.ex | 18 - Task/Loops-Continue/Haxe/loops-continue.haxe | 8 - .../PowerShell/loops-continue.psh | 8 - .../REBOL/loops-continue-1.rebol | 20 - .../REBOL/loops-continue-2.rebol | 8 - Task/Loops-Do-while/Ada/loops-do-while-1.ada | 5 - Task/Loops-Do-while/Ada/loops-do-while-2.ada | 4 - .../Loops-Do-while/COBOL/loops-do-while.cobol | 15 - .../Chapel/loops-do-while.chapel | 5 - .../Emacs-Lisp/loops-do-while-1.l | 5 - .../Emacs-Lisp/loops-do-while-2.l | 5 - .../Loops-Do-while/Euphoria/loops-do-while.ex | 12 - Task/Loops-Do-while/Haxe/loops-do-while.haxe | 6 - .../PowerShell/loops-do-while.psh | 5 - .../Loops-Do-while/REBOL/loops-do-while.rebol | 15 - .../Ada/loops-downward-for.ada | 3 - .../COBOL/loops-downward-for.cobol | 14 - .../Chapel/loops-downward-for-1.chapel | 2 - .../Chapel/loops-downward-for-2.chapel | 2 - .../Euphoria/loops-downward-for.ex | 3 - .../Haxe/loops-downward-for.haxe | 22 - .../PowerShell/loops-downward-for-1.psh | 3 - .../PowerShell/loops-downward-for-2.psh | 1 - .../REBOL/loops-downward-for.rebol | 1 - .../Ada/loops-for-with-a-specified-step.ada | 63 - .../loops-for-with-a-specified-step.cobol | 14 - .../loops-for-with-a-specified-step.chapel | 6 - .../loops-for-with-a-specified-step.elena | 4 +- .../loops-for-with-a-specified-step-1.ex | 3 - .../loops-for-with-a-specified-step-2.ex | 2 - .../Haxe/loops-for-with-a-specified-step.haxe | 23 - .../loops-for-with-a-specified-step.oberon | 14 - .../loops-for-with-a-specified-step.psh | 3 - .../loops-for-with-a-specified-step.rebol | 2 - .../loops-for-with-a-specified-step.vb | 5 - Task/Loops-For/Ada/loops-for.ada | 6 - Task/Loops-For/COBOL/loops-for.cobol | 21 - Task/Loops-For/Chapel/loops-for.chapel | 4 - Task/Loops-For/Coq/loops-for.coq | 23 - Task/Loops-For/Elena/loops-for.elena | 6 +- Task/Loops-For/Emacs-Lisp/loops-for.l | 11 - Task/Loops-For/Euphoria/loops-for.ex | 6 - Task/Loops-For/Haxe/loops-for.haxe | 6 - Task/Loops-For/Oberon/loops-for.oberon | 2 +- Task/Loops-For/PowerShell/loops-for-1.psh | 6 - Task/Loops-For/PowerShell/loops-for-2.psh | 6 - Task/Loops-For/REBOL/loops-for.rebol | 13 - Task/Loops-For/ReScript/loops-for.re | 8 - Task/Loops-For/VBScript/loops-for.vb | 9 - Task/Loops-Foreach/Ada/loops-foreach-1.ada | 14 - Task/Loops-Foreach/Ada/loops-foreach-2.ada | 3 - Task/Loops-Foreach/Ada/loops-foreach-3.ada | 25 - Task/Loops-Foreach/Ada/loops-foreach-4.ada | 25 - Task/Loops-Foreach/COBOL/loops-foreach.cobol | 6 - .../Loops-Foreach/Chapel/loops-foreach.chapel | 2 - .../Loops-Foreach/Elena/loops-foreach-1.elena | 4 +- .../Loops-Foreach/Elena/loops-foreach-2.elena | 4 +- .../Emacs-Lisp/loops-foreach-1.l | 2 - .../Emacs-Lisp/loops-foreach-2.l | 3 - .../Emacs-Lisp/loops-foreach-3.l | 1 - Task/Loops-Foreach/Euphoria/loops-foreach.ex | 24 - Task/Loops-Foreach/Haxe/loops-foreach.haxe | 4 - .../PowerShell/loops-foreach.psh | 7 - Task/Loops-Foreach/REBOL/loops-foreach.rebol | 13 - Task/Loops-Foreach/ReScript/loops-foreach.re | 3 - Task/Loops-Foreach/VBScript/loops-foreach.vb | 5 - ...-increment-loop-index-within-loop-body.ada | 51 - ...crement-loop-index-within-loop-body.arturo | 15 +- ...increment-loop-index-within-loop-body.haxe | 37 - ...ncrement-loop-index-within-loop-body.rebol | 50 - Task/Loops-Infinite/Ada/loops-infinite.ada | 3 - .../Loops-Infinite/COBOL/loops-infinite.cobol | 10 - .../Chapel/loops-infinite.chapel | 1 - .../Loops-Infinite/Elena/loops-infinite.elena | 4 +- .../Emacs-Lisp/loops-infinite.l | 2 - .../Loops-Infinite/Euphoria/loops-infinite.ex | 3 - Task/Loops-Infinite/Haxe/loops-infinite.haxe | 2 - .../Oberon/loops-infinite.oberon | 8 - .../PowerShell/loops-infinite.psh | 3 - .../REBOL/loops-infinite-1.rebol | 1 - .../REBOL/loops-infinite-2.rebol | 1 - .../REBOL/loops-infinite-3.rebol | 1 - .../ReScript/loops-infinite-1.re | 3 - .../ReScript/loops-infinite-2.re | 4 - .../Loops-Infinite/VBScript/loops-infinite.vb | 3 - .../Ada/loops-n-plus-one-half.ada | 11 - .../Arturo/loops-n-plus-one-half.arturo | 2 +- .../AutoIt/loops-n-plus-one-half.autoit | 26 - .../COBOL/loops-n-plus-one-half-1.cobol | 27 - .../COBOL/loops-n-plus-one-half-2.cobol | 18 - .../COBOL/loops-n-plus-one-half-3.cobol | 18 - .../COBOL/loops-n-plus-one-half-4.cobol | 17 - .../Chapel/loops-n-plus-one-half.chapel | 2 - .../Euphoria/loops-n-plus-one-half.ex | 6 - .../Haxe/loops-n-plus-one-half.haxe | 2 - .../PowerShell/loops-n-plus-one-half-1.psh | 8 - .../PowerShell/loops-n-plus-one-half-2.psh | 5 - .../REBOL/loops-n-plus-one-half.rebol | 11 - Task/Loops-Nested/Ada/loops-nested.ada | 21 - Task/Loops-Nested/COBOL/loops-nested.cobol | 45 - Task/Loops-Nested/Chapel/loops-nested.chapel | 16 - Task/Loops-Nested/Euphoria/loops-nested.ex | 18 - Task/Loops-Nested/REBOL/loops-nested.rebol | 38 - Task/Loops-Nested/ReScript/loops-nested.re | 20 - Task/Loops-While/Ada/loops-while.ada | 8 - Task/Loops-While/COBOL/loops-while.cobol | 15 - Task/Loops-While/Chapel/loops-while.chapel | 5 - Task/Loops-While/Elena/loops-while.elena | 4 +- Task/Loops-While/Emacs-Lisp/loops-while.l | 4 - Task/Loops-While/Euphoria/loops-while.ex | 7 - Task/Loops-While/Fennel/loops-while.fennel | 4 +- Task/Loops-While/Haxe/loops-while-1.haxe | 6 - Task/Loops-While/Haxe/loops-while-2.haxe | 6 - Task/Loops-While/Oberon/loops-while.oberon | 25 +- Task/Loops-While/PowerShell/loops-while.psh | 5 - Task/Loops-While/Python/loops-while.py | 2 +- Task/Loops-While/REBOL/loops-while.rebol | 10 - Task/Loops-While/ReScript/loops-while.re | 5 - .../Visual-Basic-.NET/loops-while.vb | 14 +- .../Ada/loops-with-multiple-ranges.ada | 64 -- .../REBOL/loops-with-multiple-ranges.rebol | 59 - .../Ada/loops-wrong-ranges.ada | 51 - .../Arturo/loops-wrong-ranges.arturo | 25 +- .../REBOL/loops-wrong-ranges.rebol | 30 - .../Ada/lucas-lehmer-test.ada | 28 - .../Langur/lucas-lehmer-test.langur | 6 +- .../Phix/lucas-lehmer-test.phix | 102 +- .../PowerShell/lucas-lehmer-test-1.psh | 28 - .../PowerShell/lucas-lehmer-test-2.psh | 1 - .../REXX/lucas-lehmer-test.rexx | 9 +- .../V-(Vlang)/lucas-lehmer-test.v | 20 +- .../VBScript/lucas-lehmer-test.vb | 18 - Task/Ludic-numbers/Ada/ludic-numbers.ada | 100 -- .../Ludic-numbers/Arturo/ludic-numbers.arturo | 2 +- .../PowerShell/ludic-numbers-1.psh | 18 - .../PowerShell/ludic-numbers-2.psh | 15 - Task/Ludic-numbers/REXX/ludic-numbers.rexx | 8 +- Task/Ludic-numbers/VBScript/ludic-numbers.vb | 73 -- .../Ada/luhn-test-of-credit-card-numbers.ada | 30 - .../luhn-test-of-credit-card-numbers.arturo | 10 +- .../luhn-test-of-credit-card-numbers.autoit | 23 - .../luhn-test-of-credit-card-numbers.cobol | 87 -- .../luhn-test-of-credit-card-numbers.l | 20 - .../luhn-test-of-credit-card-numbers.ex | 27 - .../luhn-test-of-credit-card-numbers-1.psh | 60 - .../luhn-test-of-credit-card-numbers-2.psh | 1 - .../luhn-test-of-credit-card-numbers-3.psh | 3 - .../luhn-test-of-credit-card-numbers.vb | 33 - Task/Lychrel-numbers/00-TASK.txt | 2 +- Task/Lychrel-numbers/11l/lychrel-numbers.11l | 2 +- .../PowerShell/lychrel-numbers-1.psh | 102 -- .../PowerShell/lychrel-numbers-2.psh | 10 - .../Arturo/m-bius-function.arturo | 4 +- .../PowerShell/m-bius-function.psh | 28 - .../M-bius-function/REXX/m-bius-function.rexx | 10 +- .../RapidQ/m-bius-function.rapidq | 36 - .../Ada/mac-vendor-lookup.ada | 34 - .../PowerShell/mac-vendor-lookup.psh | 9 - .../VBScript/mac-vendor-lookup.vb | 11 - Task/MD4/Ada/md4.ada | 34 - Task/MD4/Emacs-Lisp/md4.l | 7 - .../11l/md5-implementation.11l | 2 +- .../Ada/md5-implementation-1.ada | 11 - .../Ada/md5-implementation-2.ada | 222 ---- .../Ada/md5-implementation-3.ada | 34 - .../Phix/md5-implementation.phix | 246 ++-- .../Raku/md5-implementation.raku | 43 +- Task/MD5/Ada/md5.ada | 7 - Task/MD5/COBOL/md5-1.cobol | 62 - Task/MD5/COBOL/md5-2.cobol | 87 -- Task/MD5/Emacs-Lisp/md5.l | 2 - Task/MD5/Haxe/md5.haxe | 8 - Task/MD5/PowerShell/md5.psh | 4 - Task/MD5/REBOL/md5-1.rebol | 2 - Task/MD5/REBOL/md5-2.rebol | 2 - Task/Machine-code/Ada/machine-code.ada | 68 -- Task/Machine-code/COBOL/machine-code-1.cobol | 10 - Task/Machine-code/COBOL/machine-code-2.cobol | 71 -- Task/Mad-Libs/Ada/mad-libs-1.ada | 32 - Task/Mad-Libs/Ada/mad-libs-2.ada | 25 - Task/Mad-Libs/Ada/mad-libs-3.ada | 51 - Task/Mad-Libs/Arturo/mad-libs.arturo | 2 +- Task/Mad-Libs/PowerShell/mad-libs-1.psh | 65 -- Task/Mad-Libs/PowerShell/mad-libs-2.psh | 1 - Task/Mad-Libs/PowerShell/mad-libs-3.psh | 1 - Task/Mad-Libs/PowerShell/mad-libs-4.psh | 8 - Task/Mad-Libs/REBOL/mad-libs.rebol | 4 - Task/Mad-Libs/VBScript/mad-libs.vb | 18 - Task/Magic-8-ball/Ada/magic-8-ball.ada | 53 - Task/Magic-8-ball/C++/magic-8-ball.cpp | 38 +- Task/Magic-8-ball/COBOL/magic-8-ball.cobol | 89 -- Task/Magic-8-ball/R/magic-8-ball.r | 23 +- Task/Magic-constant/Ada/magic-constant.ada | 68 -- .../Arturo/magic-constant.arturo | 2 +- Task/Magic-constant/REXX/magic-constant.rexx | 9 +- .../magic-squares-of-doubly-even-order.elena | 8 +- .../magic-squares-of-doubly-even-order.pluto | 2 +- .../magic-squares-of-doubly-even-order-1.py | 40 +- .../magic-squares-of-doubly-even-order.vb | 18 - .../Ada/magic-squares-of-odd-order.ada | 35 - .../VBScript/magic-squares-of-odd-order.vb | 39 - .../magic-squares-of-singly-even-order.pluto | 8 +- .../REXX/magnanimous-numbers.rexx | 9 +- .../Ada/make-directory-path.ada | 17 - .../Arturo/make-directory-path.arturo | 2 +- .../PowerShell/make-directory-path.psh | 1 - .../Man-or-boy-test/Ada/man-or-boy-test-1.ada | 36 - .../Man-or-boy-test/Ada/man-or-boy-test-2.ada | 30 - .../Man-or-boy-test/Ada/man-or-boy-test-3.ada | 41 - .../Elena/man-or-boy-test.elena | 30 +- .../Phix/man-or-boy-test-1.phix | 42 +- .../Phix/man-or-boy-test-2.phix | 34 +- .../Phix/man-or-boy-test-3.phix | 50 +- .../Man-or-boy-test/Rust/man-or-boy-test-1.rs | 24 +- .../Man-or-boy-test/Rust/man-or-boy-test-2.rs | 23 +- .../Man-or-boy-test/Rust/man-or-boy-test-3.rs | 18 +- Task/Mandelbrot-set/Ada/mandelbrot-set-1.ada | 40 - Task/Mandelbrot-set/Ada/mandelbrot-set-2.ada | 7 - Task/Mandelbrot-set/Ada/mandelbrot-set-3.ada | 155 --- .../Arturo/mandelbrot-set.arturo | 4 +- .../Mandelbrot-set/COBOL/mandelbrot-set.cobol | 51 - .../EasyLang/mandelbrot-set.easy | 2 +- .../Emacs-Lisp/mandelbrot-set-1.l | 42 - .../Emacs-Lisp/mandelbrot-set-2.l | 54 - .../Mandelbrot-set/Haxe/mandelbrot-set-1.haxe | 1 - .../Mandelbrot-set/Haxe/mandelbrot-set-2.haxe | 49 - .../PowerShell/mandelbrot-set.psh | 20 - .../Python/mandelbrot-set-10.py | 131 +-- .../Python/mandelbrot-set-11.py | 13 +- .../Python/mandelbrot-set-12.py | 5 - .../Mandelbrot-set/Python/mandelbrot-set-5.py | 6 +- .../Mandelbrot-set/Python/mandelbrot-set-6.py | 6 +- .../Mandelbrot-set/Python/mandelbrot-set-7.py | 10 +- .../Mandelbrot-set/Python/mandelbrot-set-8.py | 72 +- .../Mandelbrot-set/Python/mandelbrot-set-9.py | 129 ++- Task/Mandelbrot-set/R/mandelbrot-set-2.r | 27 +- .../Mandelbrot-set/VBScript/mandelbrot-set.vb | 263 ----- Task/Map-range/Ada/map-range.ada | 33 - Task/Map-range/COBOL/map-range.cobol | 53 - Task/Map-range/Emacs-Lisp/map-range.l | 5 - Task/Map-range/Euphoria/map-range.ex | 7 - Task/Map-range/Go/map-range.go | 12 - Task/Map-range/PowerShell/map-range-1.psh | 36 - Task/Map-range/PowerShell/map-range-2.psh | 1 - Task/Map-range/ReScript/map-range-1.re | 10 - Task/Map-range/ReScript/map-range-2.re | 15 - Task/Mastermind/Ada/mastermind.ada | 161 --- .../Ada/matrix-chain-multiplication-1.ada | 4 - .../Ada/matrix-chain-multiplication-2.ada | 91 -- .../Ada/matrix-chain-multiplication-3.ada | 14 - .../Ada/matrix-digital-rain.ada | 93 -- .../11l/matrix-exponentiation-operator.11l | 2 +- .../Ada/matrix-exponentiation-operator-1.ada | 90 -- .../Ada/matrix-exponentiation-operator-2.ada | 48 - .../Ada/matrix-exponentiation-operator-3.ada | 48 - .../matrix-exponentiation-operator-1.chapel | 12 - .../matrix-exponentiation-operator-2.chapel | 11 - .../Scheme/matrix-exponentiation-operator.scm | 23 - .../ALGOL-68/matrix-multiplication.alg | 6 +- .../Ada/matrix-multiplication-1.ada | 31 - .../Ada/matrix-multiplication-2.ada | 26 - .../Chapel/matrix-multiplication-1.chapel | 21 - .../Chapel/matrix-multiplication-2.chapel | 25 - .../Emacs-Lisp/matrix-multiplication.l | 11 - .../Euphoria/matrix-multiplication.ex | 16 - .../LFE/matrix-multiplication-1.lfe | 14 +- .../LFE/matrix-multiplication-2.lfe | 16 +- .../PowerShell/matrix-multiplication.psh | 33 - .../Scheme/matrix-multiplication.scm | 8 - .../VBScript/matrix-multiplication.vb | 27 - .../Ada/matrix-transposition.ada | 27 - .../Emacs-Lisp/matrix-transposition-1.l | 7 - .../Emacs-Lisp/matrix-transposition-2.l | 7 - .../Euphoria/matrix-transposition.ex | 19 - .../Haxe/matrix-transposition.haxe | 17 - .../LFE/matrix-transposition-1.lfe | 19 +- .../PowerShell/matrix-transposition-1.psh | 58 - .../PowerShell/matrix-transposition-2.psh | 22 - .../Scheme/matrix-transposition.scm | 2 - .../VBScript/matrix-transposition.vb | 31 - .../Ada/maximum-triangle-path-sum.ada | 41 - .../Elena/maximum-triangle-path-sum.elena | 6 +- .../VBScript/maximum-triangle-path-sum.vb | 25 - .../FutureBasic/mayan-calendar.basic | 4 + .../Arturo/mayan-numerals.arturo | 9 +- .../Mayan-numerals/BASIC/mayan-numerals.basic | 24 - .../Maze-generation/Ada/maze-generation-1.ada | 27 - .../Maze-generation/Ada/maze-generation-2.ada | 173 --- .../Maze-generation/Ada/maze-generation-3.ada | 8 - .../Chapel/maze-generation.chapel | 56 - .../Emacs-Lisp/maze-generation.l | 193 ---- .../Maze-generation/Uiua/maze-generation.uiua | 28 +- Task/Maze-solving/Ada/maze-solving.ada | 73 -- Task/Maze-solving/Emacs-Lisp/maze-solving.l | 193 ---- Task/Maze-solving/Uiua/maze-solving.uiua | 32 +- .../ALGOL-68/mcnuggets-problem.alg | 4 +- .../Ada/mcnuggets-problem.ada | 24 - .../Arturo/mcnuggets-problem.arturo | 2 +- .../COBOL/mcnuggets-problem.cobol | 35 - .../EasyLang/mcnuggets-problem.easy | 21 +- .../PowerShell/mcnuggets-problem.psh | 18 - Task/Median-filter/Ada/median-filter-1.ada | 60 - Task/Median-filter/Ada/median-filter-2.ada | 7 - Task/Meissel-Mertens-constant/00-TASK.txt | 38 +- .../11l/meissel-mertens-constant.11l | 22 - .../ALGOL-68/meissel-mertens-constant.alg | 45 - .../ALGOL-W/meissel-mertens-constant.alg | 54 - .../Arturo/meissel-mertens-constant.arturo | 11 - .../BASIC256/meissel-mertens-constant.basic | 19 - .../C++/meissel-mertens-constant.cpp | 38 - .../Dart/meissel-mertens-constant.dart | 18 - .../Delphi/meissel-mertens-constant.pas | 69 -- .../EasyLang/meissel-mertens-constant.easy | 20 - .../FreeBASIC/meissel-mertens-constant.basic | 10 - .../Go/meissel-mertens-constant.go | 33 - .../J/meissel-mertens-constant-1.j | 2 - .../J/meissel-mertens-constant-2.j | 2 - .../J/meissel-mertens-constant-3.j | 1 - .../J/meissel-mertens-constant-4.j | 2 - .../Java/meissel-mertens-constant.java | 37 - .../JavaScript/meissel-mertens-constant.js | 135 --- .../Julia/meissel-mertens-constant.jl | 9 - .../Mathematica/meissel-mertens-constant.math | 4 - .../Maxima/meissel-mertens-constant.maxima | 1 - .../Nim/meissel-mertens-constant.nim | 43 - .../PARI-GP/meissel-mertens-constant-1.parigp | 8 - .../PARI-GP/meissel-mertens-constant-2.parigp | 16 - .../meissel-mertens-constant.pas | 27 - .../Perl/meissel-mertens-constant.pl | 6 - .../Phix/meissel-mertens-constant-1.phix | 33 - .../Phix/meissel-mertens-constant-2.phix | 54 - .../PureBasic/meissel-mertens-constant.basic | 30 - .../Python/meissel-mertens-constant.py | 19 - .../REXX/meissel-mertens-constant.rexx | 67 -- .../Raku/meissel-mertens-constant.raku | 5 - .../Run-BASIC/meissel-mertens-constant.basic | 17 - .../Rust/meissel-mertens-constant.rs | 39 - .../Sidef/meissel-mertens-constant.sidef | 7 - .../True-BASIC/meissel-mertens-constant.basic | 25 - .../Wren/meissel-mertens-constant-1.wren | 16 - .../Wren/meissel-mertens-constant-2.wren | 51 - .../XPL0/meissel-mertens-constant.xpl0 | 24 - .../Yabasic/meissel-mertens-constant.basic | 18 - .../Ada/memory-allocation-1.ada | 5 - .../Ada/memory-allocation-2.ada | 6 - .../Ada/memory-allocation-3.ada | 8 - .../Ada/memory-allocation-4.ada | 3 - .../COBOL/memory-allocation.cobol | 15 - .../Ada/memory-layout-of-a-data-structure.ada | 24 - Task/Menu/Ada/menu.ada | 27 - Task/Menu/Arturo/menu.arturo | 2 +- Task/Menu/COBOL/menu.cobol | 92 -- Task/Menu/Emacs-Lisp/menu.l | 37 - Task/Menu/Euphoria/menu.ex | 22 - Task/Menu/Julia/menu.jl | 4 +- Task/Menu/Langur/menu.langur | 5 +- Task/Menu/Logo/menu.logo | 1 + Task/Menu/Perl/menu.pl | 4 +- Task/Menu/PowerShell/menu.psh | 77 -- Task/Menu/REBOL/menu.rebol | 21 - Task/Menu/VBScript/menu.vb | 36 - .../Arturo/mertens-function.arturo | 6 +- .../COBOL/mertens-function.cobol | 66 -- .../REXX/mertens-function.rexx | 9 +- .../Arturo/metaprogramming-4.arturo | 2 +- .../Ada/metered-concurrency-1.ada | 9 - .../Ada/metered-concurrency-2.ada | 40 - .../Ada/metered-concurrency-3.ada | 37 - .../Euphoria/metered-concurrency.ex | 65 -- Task/Metronome/Ada/metronome.ada | 22 - .../Ada/mian-chowla-sequence.ada | 60 - .../Arturo/mian-chowla-sequence.arturo | 4 +- .../VBScript/mian-chowla-sequence-1.vb | 45 - .../VBScript/mian-chowla-sequence-2.vb | 43 - .../Ada/middle-three-digits.ada | 43 - .../COBOL/middle-three-digits-1.cobol | 91 -- .../COBOL/middle-three-digits-2.cobol | 71 -- .../Elena/middle-three-digits.elena | 6 +- .../PowerShell/middle-three-digits.psh | 24 - .../VBScript/middle-three-digits.vb | 21 - Task/Miller-Rabin-primality-test/00-META.yaml | 1 - Task/Miller-Rabin-primality-test/00-TASK.txt | 25 +- .../11l/miller-rabin-primality-test.11l | 29 - .../miller-rabin-primality-test.aarch64 | 298 ----- .../ALGOL-68/miller-rabin-primality-test.alg | 38 - .../miller-rabin-primality-test.arm | 286 ----- .../Ada/miller-rabin-primality-test-1.ada | 9 - .../Ada/miller-rabin-primality-test-2.ada | 55 - .../Ada/miller-rabin-primality-test-3.ada | 25 - .../Ada/miller-rabin-primality-test-4.ada | 86 -- .../Ada/miller-rabin-primality-test-5.ada | 26 - .../miller-rabin-primality-test.ahk | 41 - .../BQN/miller-rabin-primality-test-1.bqn | 20 - .../BQN/miller-rabin-primality-test-2.bqn | 10 - .../BQN/miller-rabin-primality-test-3.bqn | 4 - .../Bc/miller-rabin-primality-test.bc | 68 -- .../miller-rabin-primality-test.bracmat | 70 -- .../C++/miller-rabin-primality-test.cpp | 132 --- .../C-sharp/miller-rabin-primality-test-1.cs | 27 - .../C-sharp/miller-rabin-primality-test-2.cs | 58 - .../C/miller-rabin-primality-test-1.c | 5 - .../C/miller-rabin-primality-test-2.c | 63 - .../C/miller-rabin-primality-test-3.c | 29 - .../C/miller-rabin-primality-test-4.c | 72 -- .../C/miller-rabin-primality-test-5.c | 37 - .../Clojure/miller-rabin-primality-test-1.clj | 74 -- .../Clojure/miller-rabin-primality-test-2.clj | 82 -- .../miller-rabin-primality-test.basic | 30 - .../miller-rabin-primality-test.lisp | 43 - .../Crystal/miller-rabin-primality-test-1.cr | 40 - .../Crystal/miller-rabin-primality-test-2.cr | 144 --- .../D/miller-rabin-primality-test.d | 50 - .../E/miller-rabin-primality-test-1.e | 23 - .../E/miller-rabin-primality-test-2.e | 4 - .../EchoLisp/miller-rabin-primality-test.l | 39 - .../Elixir/miller-rabin-primality-test-1.ex | 49 - .../Elixir/miller-rabin-primality-test-2.ex | 7 - .../Erlang/miller-rabin-primality-test-1.erl | 90 -- .../Erlang/miller-rabin-primality-test-2.erl | 182 --- .../F-Sharp/miller-rabin-primality-test.fs | 11 - .../Forth/miller-rabin-primality-test.fth | 88 -- .../Fortran/miller-rabin-primality-test-1.f | 56 - .../Fortran/miller-rabin-primality-test-2.f | 24 - .../Fortran/miller-rabin-primality-test-3.f | 77 -- .../miller-rabin-primality-test-1.basic | 101 -- .../miller-rabin-primality-test-2.basic | 115 -- .../FunL/miller-rabin-primality-test.funl | 30 - .../Go/miller-rabin-primality-test.go | 66 -- .../Haskell/miller-rabin-primality-test-1.hs | 44 - .../Haskell/miller-rabin-primality-test-2.hs | 55 - .../Haskell/miller-rabin-primality-test-3.hs | 15 - .../Icon/miller-rabin-primality-test.icon | 33 - .../Java/miller-rabin-primality-test-1.java | 9 - .../Java/miller-rabin-primality-test-2.java | 79 -- .../JavaScript/miller-rabin-primality-test.js | 24 - .../Julia/miller-rabin-primality-test.jl | 27 - .../Kotlin/miller-rabin-primality-test.kts | 53 - .../miller-rabin-primality-test.basic | 290 ----- .../Lua/miller-rabin-primality-test.lua | 59 - .../miller-rabin-primality-test.m2000 | 59 - .../miller-rabin-primality-test-1.math | 9 - .../miller-rabin-primality-test-2.math | 2 - .../Maxima/miller-rabin-primality-test.maxima | 47 - .../miller-rabin-primality-test.mercury | 218 ---- .../Nim/miller-rabin-primality-test-1.nim | 73 -- .../Nim/miller-rabin-primality-test-2.nim | 140 --- .../Nim/miller-rabin-primality-test-3.nim | 41 - .../Oz/miller-rabin-primality-test.oz | 104 -- .../miller-rabin-primality-test-1.parigp | 1 - .../miller-rabin-primality-test-2.parigp | 16 - .../miller-rabin-primality-test-3.parigp | 20 - .../PHP/miller-rabin-primality-test.php | 39 - .../miller-rabin-primality-test.pas | 57 - .../Perl/miller-rabin-primality-test-1.pl | 32 - .../Perl/miller-rabin-primality-test-2.pl | 10 - .../Perl/miller-rabin-primality-test-3.pl | 10 - .../Phix/miller-rabin-primality-test-1.phix | 69 -- .../Phix/miller-rabin-primality-test-2.phix | 104 -- .../Phix/miller-rabin-primality-test-3.phix | 30 - .../PicoLisp/miller-rabin-primality-test.l | 47 - .../Pike/miller-rabin-primality-test.pike | 89 -- .../Prolog/miller-rabin-primality-test.pro | 83 -- .../miller-rabin-primality-test.basic | 29 - .../Python/miller-rabin-primality-test-1.py | 39 - .../Python/miller-rabin-primality-test-2.py | 37 - .../miller-rabin-primality-test.quackery | 74 -- .../REXX/miller-rabin-primality-test.rexx | 31 - .../Racket/miller-rabin-primality-test.rkt | 32 - .../Raku/miller-rabin-primality-test.raku | 42 - .../Ring/miller-rabin-primality-test.ring | 48 - .../Ruby/miller-rabin-primality-test-1.rb | 22 - .../Ruby/miller-rabin-primality-test-2.rb | 7 - .../Ruby/miller-rabin-primality-test-3.rb | 124 -- .../miller-rabin-primality-test.basic | 55 - .../Rust/miller-rabin-primality-test-1.rs | 163 --- .../Rust/miller-rabin-primality-test-2.rs | 25 - .../Scala/miller-rabin-primality-test-1.scala | 6 - .../Scala/miller-rabin-primality-test-2.scala | 38 - .../Scheme/miller-rabin-primality-test.scm | 43 - .../Seed7/miller-rabin-primality-test.seed7 | 46 - .../Sidef/miller-rabin-primality-test.sidef | 28 - .../miller-rabin-primality-test-1.st | 34 - .../miller-rabin-primality-test-2.st | 3 - .../miller-rabin-primality-test.ml | 49 - .../Swift/miller-rabin-primality-test.swift | 37 - .../Tcl/miller-rabin-primality-test.tcl | 34 - .../Wren/miller-rabin-primality-test.wren | 17 - .../miller-rabin-primality-test.x86-64 | 383 ------- .../Zkl/miller-rabin-primality-test.zkl | 5 - .../Ada/mind-boggling-card-trick.ada | 100 -- .../Minesweeper-game/Ada/minesweeper-game.ada | 368 ------ .../EasyLang/minesweeper-game.easy | 2 +- .../Ada/minimal-steps-down-to-1.ada | 108 -- ...iple-of-m-where-digital-sum-equals-m.cobol | 42 - .../Julia/minkowski-question-mark-function.jl | 6 +- .../Ada/modified-random-distribution.ada | 115 -- .../Ada/modular-arithmetic.ada | 24 - .../Ada/modular-exponentiation.ada | 26 - .../Emacs-Lisp/modular-exponentiation.l | 5 - .../Nim/modular-exponentiation.nim | 11 +- .../Phix/modular-exponentiation.phix | 62 +- .../PowerShell/modular-exponentiation.psh | 18 - Task/Modular-inverse/Ada/modular-inverse.ada | 19 - .../PowerShell/modular-inverse.psh | 23 - .../Python/monads-maybe-monad.py | 104 +- .../Ada/monte-carlo-methods.ada | 23 - .../Arturo/monte-carlo-methods.arturo | 2 +- .../EasyLang/monte-carlo-methods.easy | 5 +- .../PowerShell/monte-carlo-methods.psh | 17 - Task/Monty-Hall-problem/00-TASK.txt | 10 +- .../ANSI-BASIC/monty-hall-problem.basic | 4 +- .../Ada/monty-hall-problem.ada | 76 -- .../Arturo/monty-hall-problem.arturo | 2 +- .../COBOL/monty-hall-problem.cobol | 89 -- .../Chapel/monty-hall-problem-1.chapel | 51 - .../Chapel/monty-hall-problem-2.chapel | 21 - .../Emacs-Lisp/monty-hall-problem.l | 15 - .../Euphoria/monty-hall-problem.ex | 20 - .../FutureBasic/monty-hall-problem.basic | 6 +- .../Minimal-BASIC/monty-hall-problem.basic | 4 +- .../Modula-2/monty-hall-problem.mod2 | 4 +- .../PowerShell/monty-hall-problem.psh | 54 - Task/Morse-code/Ada/morse-code-1.ada | 40 - Task/Morse-code/Ada/morse-code-2.ada | 72 -- Task/Morse-code/Ada/morse-code-3.ada | 5 - Task/Morse-code/PowerShell/morse-code-1.psh | 59 - Task/Morse-code/PowerShell/morse-code-2.psh | 1 - Task/Morse-code/PowerShell/morse-code-3.psh | 1 - .../Motzkin-numbers/REXX/motzkin-numbers.rexx | 4 +- Task/Mouse-position/Ada/mouse-position.ada | 67 -- .../Emacs-Lisp/mouse-position.l | 2 - Task/Mouse-position/Odin/mouse-position.odin | 35 - .../Ada/move-to-front-algorithm.ada | 82 -- .../Arturo/move-to-front-algorithm.arturo | 2 +- .../PowerShell/move-to-front-algorithm.psh | 75 -- .../VBScript/move-to-front-algorithm.vb | 49 - .../REXX/multi-base-primes.rexx | 64 +- .../Ada/multi-dimensional-array-1.ada | 5 - .../Ada/multi-dimensional-array-10.ada | 4 - .../Ada/multi-dimensional-array-11.ada | 4 - .../Ada/multi-dimensional-array-12.ada | 8 - .../Ada/multi-dimensional-array-13.ada | 12 - .../Ada/multi-dimensional-array-2.ada | 2 - .../Ada/multi-dimensional-array-3.ada | 1 - .../Ada/multi-dimensional-array-4.ada | 1 - .../Ada/multi-dimensional-array-5.ada | 1 - .../Ada/multi-dimensional-array-6.ada | 2 - .../Ada/multi-dimensional-array-7.ada | 3 - .../Ada/multi-dimensional-array-8.ada | 3 - .../Ada/multi-dimensional-array-9.ada | 4 - .../REXX/multi-dimensional-array-1.rexx | 1 - .../REXX/multi-dimensional-array-2.rexx | 4 - .../REXX/multi-dimensional-array-3.rexx | 23 - Task/Multifactorial/Ada/multifactorial.ada | 19 - .../Arturo/multifactorial.arturo | 4 +- Task/Multifactorial/Phix/multifactorial.phix | 29 +- .../Multifactorial/VBScript/multifactorial.vb | 25 - .../Ada/multiple-distinct-objects-1.ada | 1 - .../Ada/multiple-distinct-objects-2.ada | 1 - .../Ada/multiple-distinct-objects-3.ada | 1 - .../Elena/multiple-distinct-objects.elena | 2 +- .../multiple-distinct-objects-1.psh | 3 - .../multiple-distinct-objects-2.psh | 3 - .../Ada/multiple-regression-1.ada | 38 - .../Ada/multiple-regression-2.ada | 189 --- .../Ada/multiple-regression-3.ada | 68 -- .../Emacs-Lisp/multiple-regression.l | 5 - .../Ada/multiplication-tables.ada | 25 - .../AutoIt/multiplication-tables.autoit | 20 - .../COBOL/multiplication-tables.cobol | 46 - .../Euphoria/multiplication-tables.ex | 18 - .../PowerShell/multiplication-tables-1.psh | 21 - .../PowerShell/multiplication-tables-2.psh | 26 - .../REBOL/multiplication-tables.rebol | 33 - .../REXX/multiplication-tables.rexx | 49 +- .../VBScript/multiplication-tables.vb | 18 - .../Ada/multiplicative-order-1.ada | 21 - .../Ada/multiplicative-order-2.ada | 66 -- .../Ada/multiplicative-order-3.ada | 24 - Task/Multisplit/Ada/multisplit.ada | 81 -- Task/Multisplit/PowerShell/multisplit.psh | 11 - Task/Multisplit/VBScript/multisplit.vb | 27 - .../11l/munchausen-numbers.11l | 2 +- .../Ada/munchausen-numbers.ada | 25 - .../COBOL/munchausen-numbers.cobol | 33 - .../VBScript/munchausen-numbers.vb | 25 - .../Munching-squares/Ada/munching-squares.ada | 21 - .../EasyLang/munching-squares.easy | 2 +- Task/Musical-scale/Ada/musical-scale.ada | 74 -- Task/Musical-scale/Emacs-Lisp/musical-scale.l | 22 - .../PowerShell/musical-scale.psh | 4 - Task/Mutex/Ada/mutex-1.ada | 6 - Task/Mutex/Ada/mutex-2.ada | 10 - Task/Mutex/Ada/mutex-3.ada | 15 - .../Ada/mutual-recursion-1.ada | 28 - .../Ada/mutual-recursion-2.ada | 20 - .../Arturo/mutual-recursion.arturo | 4 +- .../Elena/mutual-recursion.elena | 6 +- .../Euphoria/mutual-recursion.ex | 21 - .../PowerShell/mutual-recursion.psh | 9 - .../REBOL/mutual-recursion.rebol | 18 - .../Ada/n-queens-problem-1.ada | 50 - .../Ada/n-queens-problem-2.ada | 49 - .../Arturo/n-queens-problem.arturo | 11 +- .../Emacs-Lisp/n-queens-problem.l | 80 -- .../Phix/n-queens-problem.phix | 104 +- .../PowerShell/n-queens-problem-1.psh | 59 - .../PowerShell/n-queens-problem-2.psh | 7 - .../Uiua/n-queens-problem.uiua | 7 +- .../VBScript/n-queens-problem.vb | 46 - .../Zkl/n-queens-problem-1.zkl | 17 +- .../Zkl/n-queens-problem-2.zkl | 9 +- .../REXX/n-smooth-numbers.rexx | 10 +- .../Ada/named-parameters-1.ada | 1 - .../Ada/named-parameters-2.ada | 4 - .../Pluto/named-parameters.pluto | 2 +- .../PowerShell/named-parameters-1.psh | 3 - .../PowerShell/named-parameters-2.psh | 5 - .../PowerShell/named-parameters-3.psh | 3 - .../PowerShell/named-parameters-4.psh | 3 - .../Ada/naming-conventions-1.ada | 8 - .../Ada/naming-conventions-2.ada | 3 - .../Ada/naming-conventions-3.ada | 3 - Task/Narcissist/Ada/narcissist.ada | 1 - Task/Narcissist/PowerShell/narcissist-1.psh | 6 - Task/Narcissist/PowerShell/narcissist-2.psh | 9 - .../Ada/narcissistic-decimal-number.ada | 32 - .../Arturo/narcissistic-decimal-number.arturo | 4 +- .../COBOL/narcissistic-decimal-number.cobol | 57 - .../EasyLang/narcissistic-decimal-number.easy | 44 +- .../narcissistic-decimal-number.psh | 30 - .../VBScript/narcissistic-decimal-number.vb | 17 - .../PowerShell/natural-sorting.psh | 62 - .../PowerShell/nautical-bell.psh | 79 -- .../Ada/negative-base-numbers.ada | 135 --- Task/Nested-function/Ada/nested-function.ada | 24 - .../Elena/nested-function.elena | 6 +- .../Ada/next-highest-int-from-digits.ada | 125 -- Task/Nim-game/Ada/nim-game.ada | 45 - Task/Nim-game/COBOL/nim-game.cobol | 25 - .../Ada/non-continuous-subsequences.ada | 37 - .../non-continuous-subsequences.psh | 69 -- .../VBScript/non-continuous-subsequences.vb | 33 - .../Ada/non-decimal-radices-convert.ada | 54 - .../Arturo/non-decimal-radices-convert.arturo | 12 +- .../EasyLang/non-decimal-radices-convert.easy | 17 +- .../Euphoria/non-decimal-radices-convert.ex | 35 - .../REXX/non-decimal-radices-convert.rexx | 42 +- .../Ada/non-decimal-radices-input.ada | 14 - .../Arturo/non-decimal-radices-input.arturo | 6 +- .../Phix/non-decimal-radices-input.phix | 30 +- .../non-decimal-radices-input-1.psh | 79 -- .../non-decimal-radices-input-2.psh | 7 - .../Ada/non-decimal-radices-output.ada | 12 - .../Arturo/non-decimal-radices-output.arturo | 6 +- .../Euphoria/non-decimal-radices-output.ex | 3 - .../Phix/non-decimal-radices-output.phix | 10 +- .../PowerShell/non-decimal-radices-output.psh | 9 - Task/Nonoblock/Phix/nonoblock.phix | 96 +- Task/Nth-root/Ada/nth-root.ada | 27 - Task/Nth-root/AutoIt/nth-root.autoit | 26 - Task/Nth-root/COBOL/nth-root.cobol | 98 -- Task/Nth-root/PowerShell/nth-root.psh | 39 - Task/Nth-root/REXX/nth-root.rexx | 9 +- Task/Nth/Ada/nth.ada | 26 - Task/Nth/Arturo/nth.arturo | 8 +- Task/Nth/Batch-File/nth.bat | 13 +- Task/Nth/COBOL/nth.cobol | 31 - Task/Nth/Elena/nth.elena | 14 +- Task/Nth/FutureBasic/nth.basic | 37 +- Task/Nth/Icon/nth-2.icon | 2 +- Task/Nth/PowerShell/nth-1.psh | 21 - Task/Nth/PowerShell/nth-2.psh | 23 - Task/Null-object/Ada/null-object.ada | 5 - Task/Null-object/AutoIt/null-object.autoit | 2 - Task/Null-object/COBOL/null-object.cobol | 43 - Task/Null-object/Chapel/null-object.chapel | 3 - Task/Null-object/PowerShell/null-object.psh | 3 - Task/Null-object/REBOL/null-object-1.rebol | 3 - Task/Null-object/REBOL/null-object-2.rebol | 2 - Task/Number-names/Ada/number-names.ada | 132 --- Task/Number-names/Arturo/number-names.arturo | 2 +- Task/Number-names/Euphoria/number-names.ex | 72 -- Task/Number-names/PowerShell/number-names.psh | 131 --- .../Ada/number-reversal-game.ada | 75 -- .../COBOL/number-reversal-game.cobol | 115 -- .../Elena/number-reversal-game.elena | 6 +- .../Euphoria/number-reversal-game.ex | 55 - .../PowerShell/number-reversal-game.psh | 24 - .../REBOL/number-reversal-game.rebol | 22 - ...h-are-not-the-sum-of-distinct-squares.phix | 46 +- ...f-the-product-of-their-proper-divisors.ada | 73 -- ...-the-product-of-their-proper-divisors.easy | 23 +- .../numbers-with-equal-rises-and-falls.ada | 44 - .../numbers-with-equal-rises-and-falls.easy | 25 +- .../numbers-with-equal-rises-and-falls.rexx | 89 +- .../Ada/numeric-error-propagation-1.ada | 48 - .../Ada/numeric-error-propagation-2.ada | 119 -- .../Ada/numeric-error-propagation-3.ada | 17 - .../Phix/numeric-error-propagation.phix | 94 +- .../numerical-and-alphabetical-suffixes-1.zkl | 80 +- .../numerical-and-alphabetical-suffixes-2.zkl | 20 +- ...tegration-gauss-legendre-quadrature-2.rexx | 15 +- .../Ada/numerical-integration-1.ada | 10 - .../Ada/numerical-integration-2.ada | 64 -- .../Ada/numerical-integration-3.ada | 104 -- .../Chapel/numerical-integration-1.chapel | 129 --- .../Chapel/numerical-integration-2.chapel | 27 - .../Euphoria/numerical-integration.ex | 79 -- .../REXX/numerical-integration.rexx | 4 +- .../Ada/object-serialization-1.ada | 25 - .../Ada/object-serialization-2.ada | 68 -- .../Ada/object-serialization-3.ada | 40 - .../REBOL/object-serialization.rebol | 84 -- .../Odd-word-problem/Ada/odd-word-problem.ada | 55 - .../Elena/old-russian-measure-of-length.elena | 24 +- .../R/old-russian-measure-of-length.r | 26 +- .../Ada/old-lady-swallowed-a-fly.ada | 58 - .../COBOL/old-lady-swallowed-a-fly.cobol | 89 -- .../Elena/old-lady-swallowed-a-fly.elena | 14 +- .../Julia/old-lady-swallowed-a-fly-1.jl | 1 + .../Phix/old-lady-swallowed-a-fly.phix | 52 +- .../PowerShell/old-lady-swallowed-a-fly.psh | 32 - .../VBScript/old-lady-swallowed-a-fly.vb | 30 - .../11l/one-dimensional-cellular-automata.11l | 2 +- .../Ada/one-dimensional-cellular-automata.ada | 42 - .../one-dimensional-cellular-automata.arturo | 6 +- .../one-dimensional-cellular-automata-1.cobol | 108 -- .../one-dimensional-cellular-automata-2.cobol | 32 - .../one-dimensional-cellular-automata.ex | 46 - .../one-dimensional-cellular-automata-3.icon | 4 +- .../Ada/one-of-n-lines-in-a-file.ada | 34 - .../Chapel/one-of-n-lines-in-a-file.chapel | 14 - .../Euphoria/one-of-n-lines-in-a-file.ex | 27 - .../PowerShell/one-of-n-lines-in-a-file-1.psh | 32 - .../PowerShell/one-of-n-lines-in-a-file-2.psh | 41 - .../VBScript/one-of-n-lines-in-a-file.vb | 19 - Task/OpenGL/Ada/opengl.ada | 121 -- Task/OpenGL/Euphoria/opengl.ex | 292 ----- .../Ada/optional-parameters-1.ada | 14 - .../Ada/optional-parameters-2.ada | 10 - .../Arturo/optional-parameters.arturo | 10 +- .../REXX/optional-parameters-1.rexx | 23 - .../REXX/optional-parameters-2.rexx | 8 - .../Arturo/order-by-pair-comparisons.arturo | 2 +- .../Arturo/order-disjoint-list-items.arturo | 2 +- .../PowerShell/order-disjoint-list-items.psh | 46 - .../Ada/order-two-numerical-lists.ada | 22 - .../order-two-numerical-lists-1.psh | 9 - .../order-two-numerical-lists-2.psh | 16 - .../order-two-numerical-lists-3.psh | 5 - .../VBScript/order-two-numerical-lists.vb | 33 - .../Ada/ordered-partitions-1.ada | 13 - .../Ada/ordered-partitions-2.ada | 148 --- .../Ada/ordered-partitions-3.ada | 61 - Task/Ordered-words/ALGOL-68/ordered-words.alg | 45 - Task/Ordered-words/AWK/ordered-words.awk | 54 +- Task/Ordered-words/Ada/ordered-words.ada | 32 - .../Ordered-words/Arturo/ordered-words.arturo | 2 +- Task/Ordered-words/C/ordered-words-3.c | 66 +- Task/Ordered-words/COBOL/ordered-words.cobol | 66 -- .../Common-Lisp/ordered-words-2.lisp | 6 +- Task/Ordered-words/EchoLisp/ordered-words.l | 18 +- Task/Ordered-words/Emacs-Lisp/ordered-words.l | 75 -- Task/Ordered-words/Euphoria/ordered-words.ex | 36 - Task/Ordered-words/Fortran/ordered-words.f | 154 +-- Task/Ordered-words/Java/ordered-words-1.java | 62 +- Task/Ordered-words/Java/ordered-words-2.java | 32 +- Task/Ordered-words/Lasso/ordered-words.lasso | 18 +- Task/Ordered-words/Lua/ordered-words.lua | 28 +- .../M2000-Interpreter/ordered-words.m2000 | 70 +- Task/Ordered-words/MATLAB/ordered-words.m | 6 +- Task/Ordered-words/Maple/ordered-words.maple | 24 +- .../PowerShell/ordered-words.psh | 16 - Task/Ordered-words/Prolog/ordered-words.pro | 40 +- .../Run-BASIC/ordered-words.basic | 18 +- Task/Ordered-words/Scheme/ordered-words.scm | 18 +- Task/Ordered-words/Tcl/ordered-words.tcl | 22 +- Task/Ordered-words/Uiua/ordered-words.uiua | 11 +- Task/Ordered-words/V-(Vlang)/ordered-words.v | 40 +- Task/Ordered-words/VBScript/ordered-words.vb | 34 - .../EasyLang/ormiston-triples.easy | 71 +- .../EasyLang/own-digits-power-sum.easy | 11 +- .../Palindrome-dates/Ada/palindrome-dates.ada | 34 - .../Ada/palindrome-detection-1.ada | 9 - .../Ada/palindrome-detection-2.ada | 2 - .../AutoIt/palindrome-detection-1.autoit | 31 - .../AutoIt/palindrome-detection-2.autoit | 7 - .../COBOL/palindrome-detection.cobol | 19 - .../Emacs-Lisp/palindrome-detection-1.l | 2 - .../Emacs-Lisp/palindrome-detection-2.l | 3 - .../Euphoria/palindrome-detection-1.ex | 8 - .../Euphoria/palindrome-detection-2.ex | 14 - .../PowerShell/palindrome-detection-1.psh | 5 - .../PowerShell/palindrome-detection-2.psh | 34 - .../PowerShell/palindrome-detection-3.psh | 1 - .../PowerShell/palindrome-detection-4.psh | 1 - .../PowerShell/palindrome-detection-5.psh | 1 - .../PowerShell/palindrome-detection-6.psh | 50 - .../REBOL/palindrome-detection.rebol | 29 - .../VBScript/palindrome-detection-1.vb | 18 - .../VBScript/palindrome-detection-2.vb | 4 - .../Delphi/palindromic-gapful-numbers.pas | 124 +- .../Phix/palindromic-gapful-numbers-1.phix | 112 +- .../Phix/palindromic-gapful-numbers-2.phix | 362 +++--- .../Zkl/palindromic-gapful-numbers-1.zkl | 4 +- .../Zkl/palindromic-gapful-numbers-3.zkl | 2 +- .../COBOL/pancake-numbers.cobol | 35 - Task/Pancake-numbers/Perl/pancake-numbers.pl | 62 +- .../Pangram-checker/Ada/pangram-checker-1.ada | 14 - .../Pangram-checker/Ada/pangram-checker-2.ada | 14 - .../AutoIt/pangram-checker.autoit | 9 - .../COBOL/pangram-checker.cobol | 51 - .../PowerShell/pangram-checker-1.psh | 13 - .../PowerShell/pangram-checker-2.psh | 9 - .../VBScript/pangram-checker-1.vb | 29 - .../VBScript/pangram-checker-2.vb | 2 - .../Ada/parallel-brute-force.ada | 72 -- .../C++/parallel-brute-force.cpp | 120 +- .../C/parallel-brute-force.c | 97 +- .../Ada/parallel-calculations-1.ada | 22 - .../Ada/parallel-calculations-2.ada | 50 - .../Ada/parallel-calculations-3.ada | 54 - .../Ada/parameterized-sql-statement.ada | 38 - .../Ada/parametric-polymorphism-1.ada | 14 - .../Ada/parametric-polymorphism-2.ada | 12 - .../COBOL/parametric-polymorphism.cobol | 34 - .../PowerShell/parse-an-ip-address-1.psh | 62 - .../PowerShell/parse-an-ip-address-2.psh | 2 - .../PowerShell/parse-an-ip-address-3.psh | 1 - .../PowerShell/parse-an-ip-address-4.psh | 1 - .../VBScript/parse-an-ip-address.vb | 87 -- .../Ada/parsing-rpn-calculator-algorithm.ada | 68 -- .../parsing-rpn-calculator-algorithm.cobol | 126 -- .../Perl/parsing-rpn-calculator-algorithm.pl | 27 - .../parsing-rpn-calculator-algorithm.psh | 132 --- .../parsing-rpn-calculator-algorithm.v | 6 +- .../Ada/parsing-rpn-to-infix-conversion-1.ada | 82 -- .../Ada/parsing-rpn-to-infix-conversion-2.ada | 12 - .../Julia/parsing-rpn-to-infix-conversion.jl | 4 +- .../Python/parsing-rpn-to-infix-conversion.py | 131 +-- .../C/parsing-shunting-yard-algorithm.c | 234 ++-- .../parsing-shunting-yard-algorithm.ceylon | 178 +-- .../parsing-shunting-yard-algorithm-1.f | 368 +++--- .../parsing-shunting-yard-algorithm-2.f | 34 +- .../Phix/parsing-shunting-yard-algorithm.phix | 160 ++- .../parsing-shunting-yard-algorithm.swift | 320 +++--- .../Tcl/parsing-shunting-yard-algorithm.tcl | 72 +- .../parsing-shunting-yard-algorithm-2.sh | 64 +- .../Zkl/parsing-shunting-yard-algorithm.zkl | 40 +- .../Ada/partial-function-application.ada | 50 - .../Elena/partial-function-application.elena | 6 +- .../partial-function-application-1.js | 20 - .../partial-function-application-2.js | 21 - .../partial-function-application-3.js | 32 - .../partial-function-application-4.js | 37 - .../REXX/partial-function-application.rexx | 67 +- .../partition-an-integer-x-into-n-primes.phix | 71 +- .../partition-an-integer-x-into-n-primes.rexx | 9 +- .../partition-an-integer-x-into-n-primes.vb | 63 - .../Phix/partition-function-p.phix | 74 +- .../Ada/pascal-matrix-generation.ada | 85 -- .../VBScript/pascal-matrix-generation.vb | 65 -- .../11l/pascals-triangle-puzzle.11l | 2 +- .../Ada/pascals-triangle-puzzle.ada | 69 -- .../Ada/pascals-triangle-1.ada | 11 - .../Ada/pascals-triangle-2.ada | 26 - .../Ada/pascals-triangle-3.ada | 18 - .../Arturo/pascals-triangle.arturo | 2 +- .../Emacs-Lisp/pascals-triangle-1.l | 10 - .../Emacs-Lisp/pascals-triangle-2.l | 8 - .../Emacs-Lisp/pascals-triangle-3.l | 10 - .../Euphoria/pascals-triangle.ex | 10 - .../PowerShell/pascals-triangle.psh | 64 -- .../VBScript/pascals-triangle.vb | 14 - .../Ada/password-generator.ada | 192 ---- .../Arturo/password-generator.arturo | 10 +- .../PowerShell/password-generator-1.psh | 119 -- .../PowerShell/password-generator-2.psh | 1 - .../PowerShell/password-generator-3.psh | 3 - ...pathological-floating-point-problems-1.ada | 46 - ...pathological-floating-point-problems-2.ada | 36 - ...pathological-floating-point-problems-3.ada | 19 - .../pathological-floating-point-problems.rexx | 4 +- Task/Peano-curve/Ada/peano-curve.ada | 62 - Task/Peano-curve/VBScript/peano-curve.vb | 101 -- Task/Pells-equation/Ada/pells-equation.ada | 65 -- .../Langur/pells-equation.langur | 4 +- Task/Pells-equation/Phix/pells-equation.phix | 116 +- Task/Penneys-game/Ada/penneys-game.ada | 102 -- Task/Pentagram/Ada/pentagram.ada | 94 -- ...percentage-difference-between-images-1.ada | 1 - ...percentage-difference-between-images-2.ada | 8 - ...percentage-difference-between-images-3.ada | 4 - ...percentage-difference-between-images-4.ada | 15 - ...percentage-difference-between-images-5.ada | 7 - ...percentage-difference-between-images.rebol | 50 - .../11l/percolation-bond-percolation.11l | 2 +- .../11l/percolation-site-percolation.11l | 2 +- Task/Perfect-numbers/Ada/perfect-numbers.ada | 10 - .../Arturo/perfect-numbers.arturo | 2 +- .../COBOL/perfect-numbers-1.cobol | 24 - .../COBOL/perfect-numbers-2.cobol | 37 - .../Elena/perfect-numbers.elena | 8 +- .../PowerShell/perfect-numbers.psh | 14 - .../REBOL/perfect-numbers.rebol | 9 - .../REXX/perfect-numbers-1.rexx | 8 +- .../VBScript/perfect-numbers.vb | 17 - Task/Perfect-shuffle/Ada/perfect-shuffle.ada | 28 - .../Arturo/perfect-shuffle.arturo | 2 +- .../FutureBasic/perfect-shuffle.basic | 2 +- .../Arturo/perfect-totient-numbers.arturo | 10 +- .../Phix/perfect-totient-numbers.phix | 70 +- .../ANSI-BASIC/periodic-table.basic | 7 +- Task/Periodic-table/Julia/periodic-table.jl | 58 +- .../Periodic-table/Phix/periodic-table-1.phix | 62 +- .../Periodic-table/Phix/periodic-table-2.phix | 100 +- .../Ada/peripheral-drift-illusion.ada | 100 -- Task/Perlin-noise/11l/perlin-noise.11l | 2 +- Task/Perlin-noise/EasyLang/perlin-noise.easy | 2 +- Task/Perlin-noise/Phix/perlin-noise.phix | 100 +- .../Ada/permutation-test-1.ada | 62 - .../Ada/permutation-test-2.ada | 16 - .../Ada/permutation-test-3.ada | 34 - .../11l/permutations-derangements.11l | 2 +- .../Ada/permutations-derangements.ada | 54 - .../Arturo/permutations-derangements.arturo | 2 +- .../permutations-rank-of-a-permutation.11l | 4 +- .../Ada/permutations-by-swapping.ada | 28 - .../Arturo/permutations-by-swapping.arturo | 6 +- .../PowerShell/permutations-by-swapping.psh | 37 - Task/Permutations/Ada/permutations-1.ada | 9 - Task/Permutations/Ada/permutations-2.ada | 71 -- Task/Permutations/Ada/permutations-3.ada | 30 - Task/Permutations/Euphoria/permutations.ex | 48 - Task/Permutations/PowerShell/permutations.psh | 26 - Task/Permutations/Uiua/permutations.uiua | 6 - Task/Permutations/VBScript/permutations.vb | 24 - .../Ada/pernicious-numbers-1.ada | 40 - .../Ada/pernicious-numbers-2.ada | 14 - .../Agena/pernicious-numbers.agena | 4 +- .../Arturo/pernicious-numbers.arturo | 2 +- .../COBOL/pernicious-numbers.cobol | 94 -- .../EasyLang/pernicious-numbers.easy | 13 +- .../Phix/pernicious-numbers.phix | 34 +- .../Pluto/pernicious-numbers.pluto | 11 +- .../PowerShell/pernicious-numbers-1.psh | 28 - .../PowerShell/pernicious-numbers-2.psh | 44 - .../PowerShell/pernicious-numbers-3.psh | 9 - .../REXX/pernicious-numbers.rexx | 17 +- .../VBScript/pernicious-numbers.vb | 64 -- .../Phrase-reversals/Ada/phrase-reversals.ada | 43 - .../COBOL/phrase-reversals.cobol | 35 - .../Elena/phrase-reversals.elena | 8 +- .../Emacs-Lisp/phrase-reversals.l | 19 - .../Java/phrase-reversals.java | 36 - .../PowerShell/phrase-reversals.psh | 13 - .../VBScript/phrase-reversals.vb | 38 - Task/Pi/Ada/pi.ada | 112 -- Task/Pi/Arturo/pi.arturo | 5 +- Task/Pi/PowerShell/pi-1.psh | 57 - Task/Pi/PowerShell/pi-2.psh | 1 - Task/Pi/PowerShell/pi-3.psh | 2 - Task/Pi/REXX/pi-1.rexx | 63 +- Task/Pi/REXX/pi-2.rexx | 72 +- .../Ada/pick-random-element.ada | 30 - .../COBOL/pick-random-element.cobol | 16 - .../Elena/pick-random-element.elena | 6 +- .../Emacs-Lisp/pick-random-element.l | 5 - .../Euphoria/pick-random-element.ex | 2 - .../PowerShell/pick-random-element.psh | 1 - .../ReScript/pick-random-element.re | 9 - .../VBScript/pick-random-element.vb | 6 - .../EasyLang/pierpont-primes.easy | 50 +- .../Pierpont-primes/Python/pierpont-primes.py | 25 +- .../REXX/pierpont-primes-1.rexx | 4 +- .../REXX/pierpont-primes-2.rexx | 4 +- .../Ada/pig-the-dice-game-player.ada | 37 - .../Ada/pig-the-dice-game-1.ada | 23 - .../Ada/pig-the-dice-game-2.ada | 51 - .../Ada/pig-the-dice-game-3.ada | 32 - .../Ada/pinstripe-display.ada | 68 -- .../Ada/pinstripe-printer.ada | 76 -- Task/Pisano-period/Agena/pisano-period.agena | 4 +- Task/Pisano-period/REXX/pisano-period.rexx | 12 +- .../Plasma-effect/EasyLang/plasma-effect.easy | 4 +- .../Ada/play-recorded-sounds.ada | 39 - Task/Playfair-cipher/11l/playfair-cipher.11l | 2 +- .../Playing-cards/Arturo/playing-cards.arturo | 27 +- .../Playing-cards/AutoIt/playing-cards.autoit | 51 - Task/Playing-cards/COBOL/playing-cards.cobol | 177 --- .../PowerShell/playing-cards.psh | 480 -------- .../Playing-cards/VBScript/playing-cards-1.vb | 66 -- .../Playing-cards/VBScript/playing-cards-2.vb | 17 - .../Ada/plot-coordinate-pairs.ada | 46 - .../EasyLang/plot-coordinate-pairs.easy | 4 +- .../Ada/pointers-and-references-1.ada | 2 - .../Ada/pointers-and-references-2.ada | 1 - .../Ada/pointers-and-references-3.ada | 7 - .../Ada/pointers-and-references-4.ada | 1 - .../Ada/pointers-and-references-5.ada | 2 - .../Ada/pointers-and-references-6.ada | 5 - .../Ada/pointers-and-references-7.ada | 8 - .../Ada/pointers-and-references-8.ada | 4 - .../COBOL/pointers-and-references-1.cobol | 2 - .../COBOL/pointers-and-references-2.cobol | 6 - .../COBOL/pointers-and-references-3.cobol | 1 - .../COBOL/pointers-and-references-4.cobol | 2 - .../COBOL/pointers-and-references-5.cobol | 2 - .../COBOL/pointers-and-references-6.cobol | 2 - .../COBOL/pointers-and-references-7.cobol | 1 - .../COBOL/pointers-and-references-8.cobol | 2 - .../Ada/poker-hand-analyser.ada | 162 --- .../VBScript/poker-hand-analyser.vb | 124 -- .../Polymorphic-copy/Ada/polymorphic-copy.ada | 53 - .../Elena/polymorphic-copy.elena | 4 +- Task/Polymorphism/Ada/polymorphism-1.ada | 17 - Task/Polymorphism/Ada/polymorphism-2.ada | 77 -- Task/Polymorphism/Ada/polymorphism-3.ada | 18 - Task/Polymorphism/Ada/polymorphism-4.ada | 106 -- Task/Polymorphism/Ada/polymorphism-5.ada | 10 - Task/Polymorphism/Arturo/polymorphism.arturo | 20 +- Task/Polymorphism/Elena/polymorphism.elena | 2 +- .../Ada/polynomial-long-division.ada | 110 -- .../REXX/polynomial-long-division-2.rexx | 4 +- .../Ada/polynomial-regression-1.ada | 12 - .../Ada/polynomial-regression-2.ada | 15 - .../Emacs-Lisp/polynomial-regression.l | 3 - .../PowerShell/polynomial-regression.psh | 80 -- Task/Polyspiral/REBOL/polyspiral.rebol | 42 - .../Ada/population-count-1.ada | 6 - .../Ada/population-count-2.ada | 18 - .../Ada/population-count-3.ada | 37 - .../Arturo/population-count.arturo | 2 +- .../COBOL/population-count.cobol | 73 -- .../Phix/population-count.phix | 52 +- .../PowerShell/population-count.psh | 6 - .../VBScript/population-count.vb | 33 - Task/Power-set/Ada/power-set.ada | 22 - Task/Power-set/PowerShell/power-set.psh | 34 - Task/Power-set/VBScript/power-set.vb | 33 - .../PowerShell/pragmatic-directives-1.psh | 5 - .../PowerShell/pragmatic-directives-2.psh | 1 - Task/Price-fraction/Ada/price-fraction-1.ada | 31 - Task/Price-fraction/Ada/price-fraction-2.ada | 11 - .../Price-fraction/Euphoria/price-fraction.ex | 20 - .../PowerShell/price-fraction-1.psh | 45 - .../PowerShell/price-fraction-2.psh | 1 - .../Price-fraction/VBScript/price-fraction.vb | 48 - .../Ada/primality-by-wilsons-theorem.ada | 39 - .../REXX/primality-by-wilsons-theorem.rexx | 4 +- .../ALGOL-M/primality-by-trial-division.alg | 83 +- .../Ada/primality-by-trial-division-1.ada | 20 - .../Ada/primality-by-trial-division-2.ada | 3 - .../Ada/primality-by-trial-division-3.ada | 13 - .../AutoIt/primality-by-trial-division.autoit | 34 - .../C/primality-by-trial-division.c | 10 - .../COBOL/primality-by-trial-division.cobol | 38 - .../Chapel/primality-by-trial-division.chapel | 11 - .../primality-by-trial-division-1.l | 5 - .../primality-by-trial-division-2.l | 4 - .../primality-by-trial-division-3.l | 5 - .../primality-by-trial-division-4.l | 3 - .../primality-by-trial-division-5.l | 4 - .../Euphoria/primality-by-trial-division.ex | 12 - .../primality-by-trial-division.psh | 10 - .../REBOL/primality-by-trial-division-1.rebol | 12 - .../REBOL/primality-by-trial-division-2.rebol | 1 - .../REXX/primality-by-trial-division.rexx | 4 +- .../VBScript/primality-by-trial-division.vb | 21 - .../EasyLang/prime-conspiracy.easy | 22 +- .../REXX/prime-conspiracy-2.rexx | 10 +- .../Ada/prime-decomposition-1.ada | 15 - .../Ada/prime-decomposition-2.ada | 31 - .../Ada/prime-decomposition-3.ada | 18 - .../Pascal/prime-decomposition-1.pas | 38 - .../Pascal/prime-decomposition-2.pas | 46 - .../PowerShell/prime-decomposition-1.psh | 32 - .../PowerShell/prime-decomposition-2.psh | 17 - .../REXX/prime-decomposition.rexx | 41 - .../VBScript/prime-decomposition.vb | 43 - ...ose-neighboring-pairs-are-tetraprimes.easy | 2 +- Task/Prime-triangle/Phix/prime-triangle.phix | 100 +- ...locate-descendants-to-their-ancestors.rexx | 11 +- .../11l/primorial-numbers.11l | 2 +- .../EasyLang/primorial-numbers.easy | 14 +- .../REXX/primorial-numbers.rexx | 13 +- Task/Priority-queue/Ada/priority-queue.ada | 43 - .../Arturo/priority-queue.arturo | 58 +- .../Priority-queue/COBOL/priority-queue.cobol | 286 ----- .../Priority-queue/VBScript/priority-queue.vb | 104 -- .../Ada/probabilistic-choice.ada | 34 - .../Arturo/probabilistic-choice.arturo | 5 +- .../Euphoria/probabilistic-choice.ex | 33 - .../PowerShell/probabilistic-choice.psh | 46 - .../ReScript/probabilistic-choice.re | 43 - .../VBScript/probabilistic-choice.vb | 32 - .../Ada/problem-of-apollonius-1.ada | 17 - .../Ada/problem-of-apollonius-2.ada | 86 -- .../Ada/problem-of-apollonius-3.ada | 25 - .../Arturo/problem-of-apollonius.arturo | 2 +- .../PowerShell/problem-of-apollonius-1.psh | 69 -- .../PowerShell/problem-of-apollonius-2.psh | 4 - Task/Program-name/Ada/program-name.ada | 6 - Task/Program-name/COBOL/program-name.cobol | 18 - Task/Program-name/Elena/program-name.elena | 6 +- Task/Program-name/Emacs-Lisp/program-name.l | 8 - Task/Program-name/Euphoria/program-name.ex | 2 - Task/Program-name/PowerShell/program-name.psh | 3 - Task/Program-name/REXX/program-name-1.rexx | 25 +- Task/Program-name/REXX/program-name-2.rexx | 14 +- Task/Program-name/REXX/program-name-3.rexx | 1 - Task/Program-name/REXX/program-name-4.rexx | 5 - Task/Program-name/REXX/program-name-5.rexx | 15 - Task/Program-name/VBScript/program-name.vb | 5 - .../Ada/program-termination-1.ada | 10 - .../Ada/program-termination-2.ada | 11 - .../Ada/program-termination-3.ada | 14 - .../Ada/program-termination-4.ada | 10 - .../AutoIt/program-termination.autoit | 3 - .../COBOL/program-termination-1.cobol | 3 - .../COBOL/program-termination-2.cobol | 3 - .../Emacs-Lisp/program-termination.l | 2 - .../Phix/program-termination-1.phix | 8 +- .../Phix/program-termination-2.phix | 8 +- .../PowerShell/program-termination.psh | 3 - .../REBOL/program-termination-1.rebol | 1 - .../REBOL/program-termination-2.rebol | 1 - .../REBOL/program-termination-3.rebol | 1 - .../REBOL/program-termination-4.rebol | 1 - .../VBScript/program-termination.vb | 11 - .../Proper-divisors/Ada/proper-divisors-1.ada | 19 - .../Proper-divisors/Ada/proper-divisors-2.ada | 59 - .../Phix/proper-divisors-1.phix | 62 +- .../Phix/proper-divisors-2.phix | 36 +- .../PowerShell/proper-divisors-1.psh | 17 - .../PowerShell/proper-divisors-2.psh | 15 - .../PowerShell/proper-divisors-3.psh | 49 - .../REXX/proper-divisors-2.rexx | 9 +- .../Proper-divisors/Uiua/proper-divisors.uiua | 6 +- ...ombined-recursive-generator-mrg32k3a-1.ada | 11 - ...ombined-recursive-generator-mrg32k3a-2.ada | 53 - ...ombined-recursive-generator-mrg32k3a-3.ada | 25 - ...do-random-numbers-middle-square-method.ada | 16 - ...-random-numbers-middle-square-method.cobol | 25 - ...o-random-numbers-middle-square-method.phix | 22 +- .../Ada/pseudo-random-numbers-pcg32-1.ada | 7 - .../Ada/pseudo-random-numbers-pcg32-2.ada | 58 - .../Ada/pseudo-random-numbers-pcg32-3.ada | 25 - .../pseudo-random-numbers-splitmix64-1.ada | 8 - .../pseudo-random-numbers-splitmix64-2.ada | 36 - .../pseudo-random-numbers-splitmix64-3.ada | 30 - .../pseudo-random-numbers-xorshift-star.ada | 52 - Task/Pythagoras-tree/00-META.yaml | 1 + Task/Pythagoras-tree/Ada/pythagoras-tree.ada | 86 -- .../AutoHotkey/pythagoras-tree.ahk | 2 +- .../BASIC256/pythagoras-tree.basic | 22 +- Task/Pythagoras-tree/C/pythagoras-tree.c | 106 +- .../EasyLang/pythagoras-tree.easy | 2 +- Task/Pythagoras-tree/Go/pythagoras-tree.go | 132 +-- Task/Pythagoras-tree/Jq/pythagoras-tree.jq | 6 +- .../M2000-Interpreter/pythagoras-tree-1.m2000 | 52 +- .../M2000-Interpreter/pythagoras-tree-2.m2000 | 82 +- .../Pythagoras-tree/Raku/pythagoras-tree.raku | 18 +- .../Ada/pythagorean-triples.ada | 33 - .../Arturo/pythagorean-triples.arturo | 4 +- .../Euphoria/pythagorean-triples.ex | 21 - .../Phix/pythagorean-triples.phix | 65 +- .../PowerShell/pythagorean-triples.psh | 50 - .../Python/pythagorean-triples-1.py | 3 +- .../Python/pythagorean-triples-2.py | 6 +- .../Python/pythagorean-triples-3.py | 7 - .../VBScript/pythagorean-triples.vb | 36 - .../QR-decomposition/Ada/qr-decomposition.ada | 95 -- .../PowerShell/qr-decomposition.psh | 86 -- Task/Quaternion-type/00-TASK.txt | 54 +- .../ALGOL-68/quaternion-type-1.alg | 259 ----- .../ALGOL-68/quaternion-type-2.alg | 55 - .../ALGOL-W/quaternion-type.alg | 101 -- Task/Quaternion-type/ATS/quaternion-type.ats | 266 ----- .../Action-/quaternion-type.action | 164 --- .../Quaternion-type/Ada/quaternion-type-1.ada | 16 - .../Quaternion-type/Ada/quaternion-type-2.ada | 59 - .../Quaternion-type/Ada/quaternion-type-3.ada | 26 - .../Arturo/quaternion-type.arturo | 40 - .../AutoHotkey/quaternion-type.ahk | 72 -- .../Axiom/quaternion-type.axiom | 48 - .../BASIC256/quaternion-type.basic | 86 -- .../BBC-BASIC/quaternion-type.basic | 42 - .../Quaternion-type/C++/quaternion-type-1.cpp | 116 -- .../Quaternion-type/C++/quaternion-type-2.cpp | 40 - .../C-sharp/quaternion-type-1.cs | 90 -- .../C-sharp/quaternion-type-2.cs | 34 - Task/Quaternion-type/C/quaternion-type-1.c | 131 --- Task/Quaternion-type/C/quaternion-type-2.c | 58 - Task/Quaternion-type/CLU/quaternion-type.clu | 82 -- .../Common-Lisp/quaternion-type.lisp | 77 -- .../Crystal/quaternion-type.cr | 89 -- Task/Quaternion-type/D/quaternion-type.d | 226 ---- .../Quaternion-type/Dart/quaternion-type.dart | 63 - .../Delphi/quaternion-type-1.pas | 129 --- .../Delphi/quaternion-type-2.pas | 32 - Task/Quaternion-type/E/quaternion-type-1.e | 61 - Task/Quaternion-type/E/quaternion-type-2.e | 17 - .../Quaternion-type/ERRE/quaternion-type.erre | 104 -- .../EasyLang/quaternion-type.easy | 61 - .../Quaternion-type/Eero/quaternion-type.eero | 102 -- .../Elena/quaternion-type.elena | 88 -- .../Euphoria/quaternion-type.ex | 48 - .../F-Sharp/quaternion-type.fs | 63 - .../Factor/quaternion-type.factor | 27 - .../Quaternion-type/Forth/quaternion-type.fth | 77 -- .../Quaternion-type/Fortran/quaternion-type.f | 161 --- .../FreeBASIC/quaternion-type.basic | 77 -- Task/Quaternion-type/GAP/quaternion-type.gap | 110 -- Task/Quaternion-type/Go/quaternion-type.go | 79 -- .../Haskell/quaternion-type-1.hs | 53 - .../Haskell/quaternion-type-2.hs | 43 - .../Haskell/quaternion-type-3.hs | 16 - .../Idris/quaternion-type-1.idris | 95 -- .../Idris/quaternion-type-2.idris | 11 - Task/Quaternion-type/J/quaternion-type-1.j | 11 - Task/Quaternion-type/J/quaternion-type-2.j | 20 - Task/Quaternion-type/J/quaternion-type-3.j | 21 - .../Quaternion-type/Java/quaternion-type.java | 103 -- .../JavaScript/quaternion-type-1.js | 58 - .../JavaScript/quaternion-type-2.js | 18 - Task/Quaternion-type/Jq/quaternion-type-1.jq | 92 -- Task/Quaternion-type/Jq/quaternion-type-2.jq | 17 - .../Julia/quaternion-type-1.jl | 40 - .../Julia/quaternion-type-2.jl | 26 - .../Kotlin/quaternion-type.kts | 57 - .../Liberty-BASIC/quaternion-type.basic | 111 -- .../Quaternion-type/Lua/quaternion-type-1.lua | 63 - .../Quaternion-type/Lua/quaternion-type-2.lua | 13 - .../M2000-Interpreter/quaternion-type.m2000 | 99 -- .../Maple/quaternion-type.maple | 146 --- .../Mathematica/quaternion-type.math | 30 - .../Mercury/quaternion-type-1.mercury | 38 - .../Mercury/quaternion-type-2.mercury | 76 -- Task/Quaternion-type/Nim/quaternion-type.nim | 72 -- .../OCaml/quaternion-type-1.ml | 64 -- .../OCaml/quaternion-type-2.ml | 11 - .../Octave/quaternion-type-1.octave | 1 - .../Octave/quaternion-type-2.octave | 24 - .../Oforth/quaternion-type-1.fth | 24 - .../Oforth/quaternion-type-2.fth | 20 - Task/Quaternion-type/Ol/quaternion-type.ol | 241 ---- .../OoRexx/quaternion-type.rexx | 150 --- .../PARI-GP/quaternion-type-1.parigp | 35 - .../PARI-GP/quaternion-type-2.parigp | 10 - Task/Quaternion-type/PL-I/quaternion-type.pli | 146 --- Task/Quaternion-type/Perl/quaternion-type.pl | 70 -- .../Quaternion-type/Phix/quaternion-type.phix | 74 -- .../Picat/quaternion-type.picat | 50 - .../PicoLisp/quaternion-type-1.l | 33 - .../PicoLisp/quaternion-type-2.l | 22 - .../PowerShell/quaternion-type-1.psh | 58 - .../PowerShell/quaternion-type-2.psh | 22 - .../Prolog/quaternion-type-1.pro | 22 - .../Prolog/quaternion-type-2.pro | 24 - .../PureBasic/quaternion-type-1.basic | 85 -- .../PureBasic/quaternion-type-2.basic | 29 - .../Python/quaternion-type-1.py | 82 -- .../Python/quaternion-type-2.py | 56 - Task/Quaternion-type/R/quaternion-type.r | 33 - .../Quaternion-type/REXX/quaternion-type.rexx | 41 - .../Racket/quaternion-type.rkt | 75 -- .../Quaternion-type/Raku/quaternion-type.raku | 54 - Task/Quaternion-type/Red/quaternion-type.red | 59 - Task/Quaternion-type/Ruby/quaternion-type.rb | 77 -- Task/Quaternion-type/Rust/quaternion-type.rs | 173 --- .../Scala/quaternion-type-1.scala | 31 - .../Scala/quaternion-type-2.scala | 35 - .../Seed7/quaternion-type.seed7 | 177 --- .../Sidef/quaternion-type.sidef | 39 - .../Swift/quaternion-type.swift | 134 --- .../Quaternion-type/Tcl/quaternion-type-1.tcl | 99 -- .../Quaternion-type/Tcl/quaternion-type-2.tcl | 22 - Task/Quaternion-type/VBA/quaternion-type.vba | 71 -- .../Visual-Basic-.NET/quaternion-type-1.vb | 96 -- .../Visual-Basic-.NET/quaternion-type-2.vb | 25 - .../Quaternion-type/Wren/quaternion-type.wren | 65 -- .../Quaternion-type/XPL0/quaternion-type.xpl0 | 62 - .../Quaternion-type/Zkl/quaternion-type-1.zkl | 53 - .../Quaternion-type/Zkl/quaternion-type-2.zkl | 39 - .../Ada/queue-definition-1.ada | 20 - .../Ada/queue-definition-10.ada | 11 - .../Ada/queue-definition-11.ada | 30 - .../Ada/queue-definition-12.ada | 48 - .../Ada/queue-definition-2.ada | 49 - .../Ada/queue-definition-3.ada | 17 - .../Ada/queue-definition-4.ada | 13 - .../Ada/queue-definition-5.ada | 25 - .../Ada/queue-definition-6.ada | 17 - .../Ada/queue-definition-7.ada | 11 - .../Ada/queue-definition-8.ada | 31 - .../Ada/queue-definition-9.ada | 56 - .../Arturo/queue-definition.arturo | 28 +- .../Elena/queue-definition.elena | 23 +- .../PowerShell/queue-definition.psh | 17 - .../REBOL/queue-definition.rebol | 31 - .../VBScript/queue-definition.vb | 37 - Task/Queue-Usage/Ada/queue-usage.ada | 21 - Task/Queue-Usage/Arturo/queue-usage.arturo | 46 +- Task/Queue-Usage/Elena/queue-usage.elena | 12 +- Task/Queue-Usage/PowerShell/queue-usage-1.psh | 26 - Task/Queue-Usage/PowerShell/queue-usage-2.psh | 3 - Task/Queue-Usage/PowerShell/queue-usage-3.psh | 1 - Task/Queue-Usage/PowerShell/queue-usage-4.psh | 1 - Task/Queue-Usage/PowerShell/queue-usage-5.psh | 1 - Task/Queue-Usage/PowerShell/queue-usage-6.psh | 1 - Task/Queue-Usage/PowerShell/queue-usage-7.psh | 1 - Task/Queue-Usage/PowerShell/queue-usage-8.psh | 1 - Task/Queue-Usage/REBOL/queue-usage.rebol | 15 - .../Ada/quickselect-algorithm.ada | 257 ----- .../Arturo/quickselect-algorithm.arturo | 9 +- .../C/quickselect-algorithm.c | 4 +- .../COBOL/quickselect-algorithm.cobol | 95 -- .../PowerShell/quickselect-algorithm.psh | 31 - Task/Quine/Ada/quine.ada | 1 - Task/Quine/Arturo/quine.arturo | 2 +- Task/Quine/COBOL/quine-1.cobol | 1 - Task/Quine/COBOL/quine-2.cobol | 339 ------ Task/Quine/COBOL/quine-3.cobol | 48 - Task/Quine/COBOL/quine-4.cobol | 24 - Task/Quine/Euphoria/quine.ex | 1 - Task/Quine/Joy/quine.joy | 2 +- Task/Quine/PowerShell/quine-1.psh | 2 - Task/Quine/PowerShell/quine-2.psh | 1 - Task/Quine/PowerShell/quine-3.psh | 1 - Task/Quine/PowerShell/quine-4.psh | 1 - Task/Quine/REBOL/quine-1.rebol | 1 - Task/Quine/REBOL/quine-2.rebol | 14 - Task/Quine/Rust/quine-1.rs | 2 +- Task/Quine/Rust/quine-2.rs | 3 +- Task/Quine/Rust/quine-3.rs | 7 +- Task/Quine/Rust/quine-4.rs | 64 +- Task/Quine/Rust/quine-5.rs | 101 +- Task/Quine/VHDL/quine.vhdl | 40 - Task/Quine/Zig/quine.zig | 6 - .../68000-Assembly/quoting-constructs-6.68000 | 28 +- .../C++/quoting-constructs.cpp | 30 +- .../Java/quoting-constructs.java | 44 +- .../REXX/quoting-constructs.rexx | 11 +- Task/RIPEMD-160/Ada/ripemd-160.ada | 34 - Task/RIPEMD-160/Phix/ripemd-160-1.phix | 9 +- Task/RIPEMD-160/Phix/ripemd-160-2.phix | 203 ++-- Task/RIPEMD-160/PowerShell/ripemd-160-1.psh | 51 - Task/RIPEMD-160/PowerShell/ripemd-160-2.psh | 1 - .../Arturo/rpg-attributes-generator.arturo | 4 +- .../Phix/rpg-attributes-generator.phix | 38 +- Task/RSA-code/Ada/rsa-code.ada | 38 - Task/RSA-code/PowerShell/rsa-code.psh | 13 - .../REXX/radical-of-an-integer-2.rexx | 60 +- .../EasyLang/ramanujan-primes-twins.easy | 17 +- .../REXX/ramanujan-primes-twins.rexx | 9 +- .../REXX/ramanujans-constant.rexx | 4 +- ...r-douglas-peucker-line-simplification.phix | 52 +- .../Arturo/random-latin-squares.arturo | 2 +- .../Ada/random-number-generator-device-.ada | 13 - .../random-number-generator-device--1.psh | 31 - .../random-number-generator-device--2.psh | 1 - .../random-number-generator-device--3.psh | 1 - .../REXX/random-number-generator-device-.rexx | 4 +- .../random-number-generator-included-.elena | 6 +- Task/Random-numbers/Ada/random-numbers.ada | 23 - .../Random-numbers/COBOL/random-numbers.cobol | 67 -- .../EasyLang/random-numbers.easy | 6 +- .../Random-numbers/Elena/random-numbers.elena | 10 +- .../Random-numbers/Euphoria/random-numbers.ex | 15 - Task/Random-numbers/Phix/random-numbers.phix | 20 +- .../PowerShell/random-numbers.psh | 35 - Task/Random-numbers/REXX/random-numbers.rexx | 4 +- .../Random-numbers/ReScript/random-numbers.re | 13 - Task/Random-sentence-from-book/00-TASK.txt | 3 +- .../Ada/range-consolidation.ada | 87 -- Task/Range-expansion/Ada/range-expansion.ada | 66 -- .../Arturo/range-expansion.arturo | 2 +- .../COBOL/range-expansion.cobol | 93 -- .../PowerShell/range-expansion-1.psh | 22 - .../PowerShell/range-expansion-2.psh | 42 - .../PowerShell/range-expansion-3.psh | 1 - .../Ada/range-extraction-1.ada | 46 - .../Ada/range-extraction-2.ada | 45 - .../Arturo/range-extraction.arturo | 9 +- .../COBOL/range-extraction-1.cobol | 180 --- .../COBOL/range-extraction-2.cobol | 6 - .../Emacs-Lisp/range-extraction-1.l | 17 - .../Emacs-Lisp/range-extraction-2.l | 31 - .../Euphoria/range-extraction.ex | 32 - .../PowerShell/range-extraction.psh | 30 - .../VBScript/range-extraction.vb | 41 - .../PowerShell/ranking-methods-1.psh | 142 --- .../PowerShell/ranking-methods-2.psh | 1 - .../PowerShell/ranking-methods-3.psh | 1 - .../PowerShell/ranking-methods-4.psh | 1 - .../PowerShell/ranking-methods-5.psh | 1 - .../PowerShell/ranking-methods-6.psh | 1 - .../PowerShell/ranking-methods-7.psh | 1 - Task/Rare-numbers/EasyLang/rare-numbers.easy | 53 +- Task/Rare-numbers/Phix/rare-numbers-1.phix | 62 +- Task/Rare-numbers/Phix/rare-numbers-2.phix | 456 ++++---- Task/Rate-counter/Ada/rate-counter.ada | 71 -- Task/Rate-counter/PowerShell/rate-counter.psh | 20 - .../Ada/ray-casting-algorithm-1.ada | 14 - .../Ada/ray-casting-algorithm-2.ada | 87 -- .../Ada/ray-casting-algorithm-3.ada | 91 -- .../Ada/read-a-configuration-file.ada | 17 - .../Arturo/read-a-configuration-file.arturo | 16 +- .../COBOL/read-a-configuration-file.cobol | 96 -- .../read-a-configuration-file-1.psh | 68 -- .../read-a-configuration-file-2.psh | 1 - .../read-a-configuration-file-3.psh | 1 - .../read-a-configuration-file-4.psh | 88 -- .../read-a-configuration-file-5.psh | 1 - .../read-a-configuration-file-6.psh | 1 - .../read-a-configuration-file-7.psh | 8 - .../read-a-configuration-file-8.psh | 45 - .../VBScript/read-a-configuration-file.vb | 38 - ...ead-a-file-character-by-character-utf8.ada | 21 - .../Ada/read-a-file-line-by-line.ada | 14 - .../COBOL/read-a-file-line-by-line.cobol | 38 - .../Elena/read-a-file-line-by-line.elena | 4 +- .../Euphoria/read-a-file-line-by-line.ex | 15 - .../PowerShell/read-a-file-line-by-line.psh | 10 - .../VBScript/read-a-file-line-by-line.vb | 8 - .../Ada/read-a-specific-line-from-a-file.ada | 29 - .../read-a-specific-line-from-a-file.bat | 11 +- .../read-a-specific-line-from-a-file.frink | 2 +- .../read-a-specific-line-from-a-file.psh | 7 - .../read-a-specific-line-from-a-file.rebol | 2 - .../read-a-specific-line-from-a-file.vb | 18 - .../Ada/read-entire-file-1.ada | 23 - .../Ada/read-entire-file-2.ada | 35 - .../AutoIt/read-entire-file.autoit | 3 - .../Emacs-Lisp/read-entire-file.l | 3 - .../Euphoria/read-entire-file.ex | 16 - .../PowerShell/read-entire-file-1.psh | 1 - .../PowerShell/read-entire-file-2.psh | 1 - .../PowerShell/read-entire-file-3.psh | 1 - .../REBOL/read-entire-file.rebol | 2 - .../VBScript/read-entire-file-1.vb | 3 - .../VBScript/read-entire-file-2.vb | 1 - .../Ada/real-constants-and-functions.ada | 9 - .../real-constants-and-functions.arturo | 2 +- .../real-constants-and-functions-1.cobol | 13 - .../real-constants-and-functions-2.cobol | 3 - .../real-constants-and-functions.easy | 4 +- .../Elena/real-constants-and-functions.elena | 22 +- .../real-constants-and-functions.psh | 9 - .../REXX/real-constants-and-functions-4.rexx | 29 +- .../Arturo/recamans-sequence.arturo | 4 +- .../COBOL/recamans-sequence.cobol | 59 - .../Lua/recamans-sequence.lua | 10 +- .../VBScript/recamans-sequence.vb | 58 - Task/Record-sound/Ada/record-sound.ada | 33 - .../Ada/reduced-row-echelon-form-1.ada | 11 - .../Ada/reduced-row-echelon-form-2.ada | 71 -- .../Ada/reduced-row-echelon-form-3.ada | 28 - .../AutoIt/reduced-row-echelon-form.autoit | 52 - .../Euphoria/reduced-row-echelon-form.ex | 39 - .../Elena/reflection-list-methods.elena | 4 +- .../Elena/reflection-list-properties.elena | 4 +- .../reflection-list-properties-1.psh | 1 - .../reflection-list-properties-2.psh | 1 - .../Ada/regular-expressions.ada | 43 - .../Emacs-Lisp/regular-expressions.l | 4 - .../PowerShell/regular-expressions.psh | 2 - .../REBOL/regular-expressions.rebol | 40 - .../VBScript/regular-expressions.vb | 9 - .../Ada/remove-duplicate-elements.ada | 15 - .../Elena/remove-duplicate-elements.elena | 4 +- .../Euphoria/remove-duplicate-elements.ex | 17 - .../remove-duplicate-elements-1.psh | 1 - .../remove-duplicate-elements-2.psh | 5 - .../remove-duplicate-elements-3.psh | 1 - .../remove-duplicate-elements-4.psh | 1 - .../REBOL/remove-duplicate-elements.rebol | 1 - .../VBScript/remove-duplicate-elements.vb | 15 - .../Ada/remove-lines-from-a-file.ada | 41 - .../Arturo/remove-lines-from-a-file.arturo | 2 +- .../PowerShell/remove-lines-from-a-file.psh | 11 - .../VBScript/remove-lines-from-a-file.vb | 31 - Task/Rename-a-file/Ada/rename-a-file.ada | 6 - .../Batch-File/rename-a-file.bat | 4 +- Task/Rename-a-file/Emacs-Lisp/rename-a-file.l | 4 - .../PowerShell/rename-a-file.psh | 4 - Task/Rename-a-file/REBOL/rename-a-file.rebol | 19 - Task/Rendezvous/Ada/rendezvous-1.ada | 6 - Task/Rendezvous/Ada/rendezvous-2.ada | 8 - Task/Rendezvous/Ada/rendezvous-3.ada | 77 -- Task/Rep-string/Ada/rep-string.ada | 31 - Task/Rep-string/Arturo/rep-string.arturo | 7 +- Task/Rep-string/VBScript/rep-string.vb | 37 - Task/Repeat-a-string/Ada/repeat-a-string.ada | 7 - .../AutoIt/repeat-a-string.autoit | 3 - .../COBOL/repeat-a-string.cobol | 9 - .../EasyLang/repeat-a-string.easy | 4 +- .../Elena/repeat-a-string.elena | 2 +- .../Emacs-Lisp/repeat-a-string-1.l | 1 - .../Emacs-Lisp/repeat-a-string-2.l | 1 - .../Emacs-Lisp/repeat-a-string-3.l | 2 - .../Euphoria/repeat-a-string-1.ex | 5 - .../Euphoria/repeat-a-string-2.ex | 3 - .../Euphoria/repeat-a-string-3.ex | 9 - .../Euphoria/repeat-a-string-4.ex | 4 - .../Euphoria/repeat-a-string-5.ex | 7 - .../PowerShell/repeat-a-string.psh | 1 - .../QBasic/repeat-a-string.basic | 12 - .../REBOL/repeat-a-string.rebol | 1 - .../ReScript/repeat-a-string.re | 1 - .../VBScript/repeat-a-string.vb | 1 - Task/Repeat/Ada/repeat.ada | 19 - Task/Repeat/Chapel/repeat-1.chapel | 13 - Task/Repeat/Chapel/repeat-2.chapel | 13 - Task/Repeat/Chapel/repeat-3.chapel | 13 - Task/Repeat/PowerShell/repeat.psh | 14 - Task/Repunit-primes/Phix/repunit-primes.phix | 60 +- Task/Resistor-mesh/Ada/resistor-mesh.ada | 69 -- Task/Resistor-mesh/Julia/resistor-mesh.jl | 32 +- .../Resistor-mesh/Maxima/resistor-mesh.maxima | 2 +- Task/Resistor-mesh/Phix/resistor-mesh.phix | 54 +- Task/Resistor-mesh/Python/resistor-mesh-1.py | 25 +- .../respond-to-an-unknown-method-call.elena | 8 +- .../Ada/return-multiple-values.ada | 14 - .../AutoIt/return-multiple-values.autoit | 6 - .../COBOL/return-multiple-values.cobol | 73 -- .../Elena/return-multiple-values-1.elena | 4 +- .../Elena/return-multiple-values-2.elena | 6 +- .../Euphoria/return-multiple-values.ex | 14 - .../Phix/return-multiple-values.phix | 10 +- .../PowerShell/return-multiple-values.psh | 9 - .../ReScript/return-multiple-values.re | 8 - .../Reverse-a-string/Ada/reverse-a-string.ada | 14 - .../AutoIt/reverse-a-string.autoit | 12 - .../Batch-File/reverse-a-string.bat | 17 - .../COBOL/reverse-a-string.cobol | 1 - .../Elena/reverse-a-string.elena | 4 +- .../Emacs-Lisp/reverse-a-string.l | 1 - .../Euphoria/reverse-a-string.ex | 2 - .../Pluto/reverse-a-string.pluto | 10 - .../PowerShell/reverse-a-string-1.psh | 1 - .../PowerShell/reverse-a-string-2.psh | 1 - .../PowerShell/reverse-a-string-3.psh | 1 - .../PowerShell/reverse-a-string-4.psh | 1 - .../PowerShell/reverse-a-string-5.psh | 3 - .../PowerShell/reverse-a-string-6.psh | 3 - .../PowerShell/reverse-a-string-7.psh | 1 - .../PowerShell/reverse-a-string-8.psh | 3 - .../PowerShell/reverse-a-string-9.psh | 6 - .../REBOL/reverse-a-string-1.rebol | 1 - .../REBOL/reverse-a-string-2.rebol | 3 - .../ReScript/reverse-a-string.re | 11 - .../Reverse-a-string/Tcl/reverse-a-string.tcl | 2 - .../VBScript/reverse-a-string.vb | 1 - .../Ada/reverse-words-in-a-string-1.ada | 11 - .../Ada/reverse-words-in-a-string-2.ada | 20 - .../Ada/reverse-words-in-a-string-3.ada | 21 - .../COBOL/reverse-words-in-a-string.cobol | 62 - .../Elena/reverse-words-in-a-string.elena | 6 +- .../Emacs-Lisp/reverse-words-in-a-string.l | 19 - .../PowerShell/reverse-words-in-a-string.psh | 20 - .../VBScript/reverse-words-in-a-string.vb | 39 - .../Arturo/rhonda-numbers.arturo | 2 +- .../Ada/rock-paper-scissors.ada | 107 -- .../AutoIt/rock-paper-scissors.autoit | 92 -- .../Euphoria/rock-paper-scissors.ex | 50 - .../Ada/roman-numerals-decode.ada | 151 --- .../Arturo/roman-numerals-decode.arturo | 20 +- .../C++/roman-numerals-decode.cpp | 2 +- .../COBOL/roman-numerals-decode.cobol | 75 -- .../Elena/roman-numerals-decode.elena | 8 +- .../Elixir/roman-numerals-decode.ex | 4 +- .../Emacs-Lisp/roman-numerals-decode.l | 16 - .../Euphoria/roman-numerals-decode.ex | 25 - .../Julia/roman-numerals-decode-2.jl | 2 +- .../PowerShell/roman-numerals-decode-1.psh | 33 - .../PowerShell/roman-numerals-decode-2.psh | 1 - .../Python/roman-numerals-decode-3.py | 1 + .../Tcl/roman-numerals-decode-1.tcl | 2 +- .../VBScript/roman-numerals-decode.vb | 20 - .../Ada/roman-numerals-encode.ada | 33 - .../Arturo/roman-numerals-encode.arturo | 2 +- .../AutoLISP/roman-numerals-encode.l | 24 - .../COBOL/roman-numerals-encode.cobol | 53 - .../Elena/roman-numerals-encode.elena | 8 +- .../Emacs-Lisp/roman-numerals-encode.l | 17 - .../Euphoria/roman-numerals-encode.ex | 18 - .../PowerShell/roman-numerals-encode-1.psh | 37 - .../PowerShell/roman-numerals-encode-2.psh | 1 - .../Ada/roots-of-a-function.ada | 39 - .../Arturo/roots-of-a-function.arturo | 8 +- .../Ada/roots-of-a-quadratic-function.ada | 22 - .../Phix/roots-of-a-quadratic-function.phix | 79 +- .../Pluto/roots-of-a-quadratic-function.pluto | 36 +- Task/Roots-of-unity/Ada/roots-of-unity.ada | 34 - .../Ada/rosetta-code-count-examples.ada | 102 -- .../rosetta-code-find-unimplemented-tasks.arm | 2 +- .../rosetta-code-find-unimplemented-tasks.ada | 119 -- .../rosetta-code-find-unimplemented-tasks.erl | 30 +- ...rosetta-code-find-unimplemented-tasks.icon | 75 +- ...osetta-code-find-unimplemented-tasks.maple | 2 +- ...osetta-code-find-unimplemented-tasks-1.psh | 20 - ...osetta-code-find-unimplemented-tasks-2.psh | 4 - ...rosetta-code-find-unimplemented-tasks-5.py | 5 +- .../R/rosetta-code-find-unimplemented-tasks.r | 18 +- ...osetta-code-find-unimplemented-tasks.basic | 38 +- .../rosetta-code-find-unimplemented-tasks.tcl | 30 +- .../rosetta-code-find-unimplemented-tasks.vb | 67 -- ...osetta-code-find-unimplemented-tasks-1.zkl | 8 +- ...etta-code-rank-languages-by-popularity.ada | 223 ---- ...ta-code-rank-languages-by-popularity.basic | 7 +- ...tta-code-rank-languages-by-popularity.icon | 35 +- ...ta-code-rank-languages-by-popularity-1.psh | 27 - ...ta-code-rank-languages-by-popularity-2.psh | 20 - ...ta-code-rank-languages-by-popularity-3.psh | 40 - ...setta-code-rank-languages-by-popularity.vb | 118 -- Task/Rot-13/Ada/rot-13.ada | 40 - Task/Rot-13/Arturo/rot-13.arturo | 10 +- Task/Rot-13/Batch-File/rot-13.bat | 47 - Task/Rot-13/COBOL/rot-13-1.cobol | 19 - Task/Rot-13/COBOL/rot-13-2.cobol | 21 - Task/Rot-13/Elena/rot-13.elena | 6 +- Task/Rot-13/Emacs-Lisp/rot-13-1.l | 5 - Task/Rot-13/Emacs-Lisp/rot-13-2.l | 15 - Task/Rot-13/Euphoria/rot-13.ex | 39 - Task/Rot-13/Haxe/rot-13.haxe | 11 - Task/Rot-13/PowerShell/rot-13-1.psh | 3 - Task/Rot-13/PowerShell/rot-13-2.psh | 41 - Task/Rot-13/PowerShell/rot-13-3.psh | 6 - Task/Rot-13/REBOL/rot-13.rebol | 82 -- Task/Rot-13/VBScript/rot-13.vb | 26 - .../Ada/run-length-encoding.ada | 48 - .../Arturo/run-length-encoding.arturo | 2 +- .../COBOL/run-length-encoding.cobol | 124 -- .../Elena/run-length-encoding.elena | 12 +- .../Emacs-Lisp/run-length-encoding-1.l | 10 - .../Emacs-Lisp/run-length-encoding-2.l | 7 - .../Euphoria/run-length-encoding.ex | 38 - .../PowerShell/run-length-encoding.psh | 18 - .../Ada/runge-kutta-method.ada | 52 - .../PowerShell/runge-kutta-method.psh | 36 - .../REXX/runge-kutta-method.rexx | 54 +- ...runtime-evaluation-in-an-environment.elena | 10 +- ...runtime-evaluation-in-an-environment.rebol | 5 - .../Elena/runtime-evaluation.elena | 2 +- .../PowerShell/runtime-evaluation-1.psh | 2 - .../PowerShell/runtime-evaluation-2.psh | 2 - .../PowerShell/runtime-evaluation-3.psh | 2 - .../PowerShell/runtime-evaluation-4.psh | 2 - .../PowerShell/runtime-evaluation-5.psh | 6 - .../PowerShell/runtime-evaluation-6.psh | 3 - .../REBOL/runtime-evaluation.rebol | 3 - .../EasyLang/ruth-aaron-numbers.easy | 4 +- Task/S-expressions/Ada/s-expressions-1.ada | 55 - Task/S-expressions/Ada/s-expressions-2.ada | 55 - Task/S-expressions/Ada/s-expressions-3.ada | 7 - Task/S-expressions/Ada/s-expressions-4.ada | 110 -- Task/S-expressions/Ada/s-expressions-5.ada | 23 - .../S-expressions/Arturo/s-expressions.arturo | 2 +- Task/SEDOLs/Ada/sedols.ada | 40 - Task/SEDOLs/Arturo/sedols.arturo | 10 +- Task/SEDOLs/COBOL/sedols.cobol | 79 -- Task/SEDOLs/PowerShell/sedols.psh | 48 - Task/SEDOLs/VBScript/sedols.vb | 44 - Task/SHA-1/Ada/sha-1.ada | 8 - Task/SHA-1/Emacs-Lisp/sha-1.l | 2 - Task/SHA-1/Haxe/sha-1.haxe | 8 - Task/SHA-1/Phix/sha-1.phix | 151 ++- Task/SHA-1/PowerShell/sha-1.psh | 11 - Task/SHA-1/REBOL/sha-1-1.rebol | 1 - Task/SHA-1/REBOL/sha-1-2.rebol | 1 - Task/SHA-256/Ada/sha-256.ada | 34 - Task/SHA-256/Emacs-Lisp/sha-256.l | 1 - Task/SHA-256/Fortran/sha-256.f | 96 -- Task/SHA-256/Haxe/sha-256.haxe | 8 - Task/SHA-256/PowerShell/sha-256.psh | 2 - Task/SHA-256/REBOL/sha-256.rebol | 1 - Task/SOAP/VBScript/soap.vb | 6 - Task/Safe-addition/Ada/safe-addition-1.ada | 4 - Task/Safe-addition/Ada/safe-addition-2.ada | 19 - Task/Safe-addition/Ada/safe-addition-3.ada | 10 - .../Ada/safe-primes-and-unsafe-primes.ada | 125 -- .../safe-primes-and-unsafe-primes.easy | 49 +- .../Phix/safe-primes-and-unsafe-primes.phix | 50 +- .../REXX/safe-primes-and-unsafe-primes.rexx | 9 +- ...sailors-coconuts-and-a-monkey-problem.phix | 31 - ...ilors-coconuts-and-a-monkey-problem-1.uiua | 4 +- ...ilors-coconuts-and-a-monkey-problem-2.uiua | 4 +- Task/Same-fringe/Ada/same-fringe-1.ada | 26 - Task/Same-fringe/Ada/same-fringe-2.ada | 52 - Task/Same-fringe/Ada/same-fringe-3.ada | 11 - Task/Same-fringe/Ada/same-fringe-4.ada | 23 - Task/Same-fringe/Ada/same-fringe-5.ada | 162 --- .../scope-function-names-and-labels-1.psh | 4 - .../scope-function-names-and-labels-2.psh | 1 - .../REXX/scope-function-names-and-labels.rexx | 47 +- .../Scope-modifiers/Ada/scope-modifiers-1.ada | 5 - .../Scope-modifiers/Ada/scope-modifiers-2.ada | 11 - .../Scope-modifiers/Ada/scope-modifiers-3.ada | 4 - .../Scope-modifiers/Ada/scope-modifiers-4.ada | 5 - .../PowerShell/scope-modifiers.psh | 6 - .../Ada/search-a-list-of-records.ada | 84 -- .../Arturo/search-a-list-of-records.arturo | 6 +- .../Elena/search-a-list-of-records.elena | 10 +- .../PowerShell/search-a-list-of-records-1.psh | 16 - .../PowerShell/search-a-list-of-records-2.psh | 1 - .../PowerShell/search-a-list-of-records-3.psh | 1 - .../PowerShell/search-a-list-of-records-4.psh | 1 - .../PowerShell/search-a-list-of-records-5.psh | 1 - Task/Search-a-list/Ada/search-a-list.ada | 42 - .../Search-a-list/Arturo/search-a-list.arturo | 5 +- Task/Search-a-list/COBOL/search-a-list.cobol | 63 - Task/Search-a-list/Elena/search-a-list.elena | 8 +- Task/Search-a-list/Emacs-Lisp/search-a-list.l | 26 - Task/Search-a-list/Euphoria/search-a-list.ex | 46 - Task/Search-a-list/Phix/search-a-list.phix | 14 +- .../PowerShell/search-a-list-1.psh | 12 - .../PowerShell/search-a-list-2.psh | 57 - .../PowerShell/search-a-list-3.psh | 1 - .../PowerShell/search-a-list-4.psh | 1 - .../PowerShell/search-a-list-5.psh | 1 - .../PowerShell/search-a-list-6.psh | 1 - .../PowerShell/search-a-list-7.psh | 1 - Task/Search-a-list/REBOL/search-a-list.rebol | 38 - Task/Search-a-list/VBScript/search-a-list.vb | 28 - .../Ada/secure-temporary-file.ada | 14 - .../Emacs-Lisp/secure-temporary-file.l | 2 - .../PowerShell/secure-temporary-file.psh | 4 - ...stances-of-a-character-within-a-string.ada | 42 - ...nces-of-a-character-within-a-string.arturo | 6 +- .../Ada/self-describing-numbers.ada | 25 - .../PowerShell/self-describing-numbers-1.psh | 12 - .../PowerShell/self-describing-numbers-2.psh | 1 - .../PowerShell/self-describing-numbers-3.psh | 6 - .../VBScript/self-describing-numbers.vb | 39 - Task/Self-numbers/EasyLang/self-numbers.easy | 72 +- Task/Self-numbers/Pluto/self-numbers.pluto | 2 +- Task/Semiprime/ALGOL-68/semiprime.alg | 34 +- Task/Semiprime/Ada/semiprime.ada | 21 - Task/Semiprime/PowerShell/semiprime.psh | 26 - Task/Semiprime/REXX/semiprime-2.rexx | 10 +- Task/Semordnilap/Ada/semordnilap-1.ada | 19 - Task/Semordnilap/Ada/semordnilap-2.ada | 35 - Task/Semordnilap/Ada/semordnilap-3.ada | 30 - Task/Semordnilap/Arturo/semordnilap.arturo | 2 +- Task/Semordnilap/PowerShell/semordnilap.psh | 35 - Task/Semordnilap/REBOL/semordnilap-1.rebol | 26 - Task/Semordnilap/REBOL/semordnilap-2.rebol | 25 - Task/Semordnilap/Uiua/semordnilap.uiua | 7 +- Task/Semordnilap/VBScript/semordnilap.vb | 36 - .../Elena/send-an-unknown-method-call.elena | 4 +- .../send-an-unknown-method-call.psh | 10 - Task/Send-email/Ada/send-email.ada | 27 - Task/Send-email/Emacs-Lisp/send-email.l | 13 - Task/Send-email/PowerShell/send-email.psh | 14 - Task/Send-email/REBOL/send-email.rebol | 1 - Task/Send-email/VBScript/send-email.vb | 20 - .../Ada/sequence-of-non-squares.ada | 24 - .../Arturo/sequence-of-non-squares.arturo | 6 +- .../COBOL/sequence-of-non-squares.cobol | 62 - .../EasyLang/sequence-of-non-squares.easy | 11 +- .../Euphoria/sequence-of-non-squares.ex | 24 - .../PowerShell/sequence-of-non-squares-1.psh | 3 - .../PowerShell/sequence-of-non-squares-2.psh | 1 - .../PowerShell/sequence-of-non-squares-3.psh | 6 - .../sequence-of-primes-by-trial-division.ada | 18 - ...equence-of-primes-by-trial-division.arturo | 2 +- ...sequence-of-primes-by-trial-division.elena | 4 +- .../sequence-of-primes-by-trial-division.psh | 22 - .../sequence-of-primes-by-trial-division.rexx | 4 +- .../REXX/sequence-of-primorial-primes.rexx | 4 +- ...-previous-term-with-exactly-n-divisors.ada | 40 - ...evious-term-with-exactly-n-divisors.arturo | 4 +- ...previous-term-with-exactly-n-divisors.easy | 7 +- ...allest-number-with-exactly-n-divisors.easy | 8 +- .../Ada/set-consolidation-1.ada | 27 - .../Ada/set-consolidation-2.ada | 77 -- .../Ada/set-consolidation-3.ada | 40 - .../VBScript/set-consolidation.vb | 33 - .../Elena/set-of-real-numbers.elena | 2 +- .../FreeBASIC/set-of-real-numbers.basic | 53 +- Task/Set-puzzle/Ada/set-puzzle-1.ada | 18 - Task/Set-puzzle/Ada/set-puzzle-2.ada | 78 -- Task/Set-puzzle/Ada/set-puzzle-3.ada | 50 - .../11l/set-right-adjacent-bits.11l | 2 +- .../Ada/set-right-adjacent-bits.ada | 75 -- .../Arturo/set-right-adjacent-bits.arturo | 8 +- .../Phix/set-right-adjacent-bits-1.phix | 52 +- .../Phix/set-right-adjacent-bits-2.phix | 52 +- .../Phix/set-right-adjacent-bits-3.phix | 42 +- Task/Set/Ada/set.ada | 29 - Task/Set/PowerShell/set.psh | 17 - ...even-sided-dice-from-five-sided-dice-1.ada | 10 - ...even-sided-dice-from-five-sided-dice-2.ada | 57 - ...even-sided-dice-from-five-sided-dice-3.ada | 51 - .../seven-sided-dice-from-five-sided-dice.vb | 13 - Task/Sexy-primes/EasyLang/sexy-primes.easy | 24 +- Task/Sexy-primes/Phix/sexy-primes.phix | 136 ++- Task/Sexy-primes/REXX/sexy-primes.rexx | 8 +- Task/Shell-one-liner/Ada/shell-one-liner.ada | 1 - .../COBOL/shell-one-liner-1.cobol | 1 - .../COBOL/shell-one-liner-2.cobol | 1 - .../Emacs-Lisp/shell-one-liner-1.l | 1 - .../Emacs-Lisp/shell-one-liner-2.l | 1 - .../PowerShell/shell-one-liner.psh | 2 - .../REBOL/shell-one-liner.rebol | 1 - .../shoelace-formula-for-polygonal-area.ada | 32 - ...shoelace-formula-for-polygonal-area.arturo | 14 +- ...shoelace-formula-for-polygonal-area-1.phix | 30 +- ...shoelace-formula-for-polygonal-area-2.phix | 32 +- .../shoelace-formula-for-polygonal-area.vb | 18 - .../Ada/short-circuit-evaluation.ada | 27 - .../Elena/short-circuit-evaluation.elena | 12 +- .../PowerShell/short-circuit-evaluation.psh | 33 - .../Ada/shortest-common-supersequence.ada | 37 - .../Show-ASCII-table/11l/show-ascii-table.11l | 2 +- .../Show-ASCII-table/Ada/show-ascii-table.ada | 23 - .../Arturo/show-ascii-table.arturo | 10 +- .../COBOL/show-ascii-table.cobol | 22 - Task/Show-the-epoch/Ada/show-the-epoch.ada | 9 - .../Show-the-epoch/COBOL/show-the-epoch.cobol | 17 - .../PowerShell/show-the-epoch-1.psh | 1 - .../PowerShell/show-the-epoch-2.psh | 1 - .../PowerShell/show-the-epoch-3.psh | 1 - .../PowerShell/show-the-epoch-4.psh | 1 - .../Ada/sierpinski-arrowhead-curve.ada | 64 -- .../Ada/sierpinski-carpet.ada | 76 -- .../Euphoria/sierpinski-carpet.ex | 26 - .../PowerShell/sierpinski-carpet-1.psh | 17 - .../PowerShell/sierpinski-carpet-2.psh | 54 - .../Sierpinski-carpet/R/sierpinski-carpet-1.r | 3 +- .../VBScript/sierpinski-carpet.vb | 32 - .../Ada/sierpinski-pentagon.ada | 45 - .../Ada/sierpinski-square-curve.ada | 49 - .../VBScript/sierpinski-square-curve.vb | 152 --- .../Ada/sierpinski-triangle-graphical.ada | 37 - .../VBScript/sierpinski-triangle-graphical.vb | 120 -- .../Ada/sierpinski-triangle-1.ada | 53 - .../Ada/sierpinski-triangle-2.ada | 28 - .../Arturo/sierpinski-triangle.arturo | 4 +- .../COBOL/sierpinski-triangle.cobol | 36 - .../Euphoria/sierpinski-triangle.ex | 12 - .../Haxe/sierpinski-triangle.haxe | 35 - .../PowerShell/sierpinski-triangle.psh | 21 - .../VBScript/sierpinski-triangle.vb | 27 - .../360-Assembly/sieve-of-eratosthenes.360 | 2 +- .../sieve-of-eratosthenes.68000 | 358 +++--- .../8086-Assembly/sieve-of-eratosthenes.8086 | 116 +- .../AWK/sieve-of-eratosthenes-1.awk | 22 +- .../ActionScript/sieve-of-eratosthenes.as | 38 +- .../Ada/sieve-of-eratosthenes.ada | 26 - .../Arturo/sieve-of-eratosthenes.arturo | 2 +- .../AutoHotkey/sieve-of-eratosthenes-2.ahk | 24 +- .../AutoHotkey/sieve-of-eratosthenes-3.ahk | 2 +- .../AutoIt/sieve-of-eratosthenes.autoit | 15 - .../Batch-File/sieve-of-eratosthenes.bat | 20 - .../C++/sieve-of-eratosthenes-2.cpp | 8 +- .../C++/sieve-of-eratosthenes-3.cpp | 2 +- .../C-Shell/sieve-of-eratosthenes.csh | 26 +- .../C/sieve-of-eratosthenes-1.c | 36 +- .../COBOL/sieve-of-eratosthenes.cobol | 55 - .../Chapel/sieve-of-eratosthenes-1.chapel | 23 - .../Chapel/sieve-of-eratosthenes-2.chapel | 8 - .../Chapel/sieve-of-eratosthenes-3.chapel | 40 - .../Chapel/sieve-of-eratosthenes-4.chapel | 44 - .../Chapel/sieve-of-eratosthenes-5.chapel | 52 - .../Chapel/sieve-of-eratosthenes-6.chapel | 96 -- .../Chapel/sieve-of-eratosthenes-7.chapel | 56 - .../Chapel/sieve-of-eratosthenes-8.chapel | 116 -- .../Chapel/sieve-of-eratosthenes-9.chapel | 313 ----- .../Clojure/sieve-of-eratosthenes-10.clj | 6 +- .../Clojure/sieve-of-eratosthenes-17.clj | 52 +- .../Clojure/sieve-of-eratosthenes-9.clj | 12 +- .../Craft-Basic/sieve-of-eratosthenes.basic | 18 +- .../EC/sieve-of-eratosthenes.ec | 95 +- .../EasyLang/sieve-of-eratosthenes.easy | 9 +- .../EchoLisp/sieve-of-eratosthenes-1.l | 10 +- .../EchoLisp/sieve-of-eratosthenes-2.l | 20 +- .../EchoLisp/sieve-of-eratosthenes-3.l | 10 +- .../Emacs-Lisp/sieve-of-eratosthenes-1.l | 7 - .../Emacs-Lisp/sieve-of-eratosthenes-2.l | 7 - .../Erlang/sieve-of-eratosthenes-1.erl | 10 +- .../Euphoria/sieve-of-eratosthenes.ex | 18 - .../GLBasic/sieve-of-eratosthenes.basic | 4 +- .../Go/sieve-of-eratosthenes-2.go | 76 +- .../Go/sieve-of-eratosthenes-3.go | 88 +- .../Go/sieve-of-eratosthenes-4.go | 64 +- .../Go/sieve-of-eratosthenes-5.go | 94 +- .../Java/sieve-of-eratosthenes-6.java | 54 +- .../JavaScript/sieve-of-eratosthenes-6.js | 6 +- .../K/sieve-of-eratosthenes.k | 10 - .../Limbo/sieve-of-eratosthenes.limbo | 50 +- .../Logtalk/sieve-of-eratosthenes-1.logtalk | 56 +- .../Lua/sieve-of-eratosthenes-1.lua | 18 +- .../Mojo/sieve-of-eratosthenes-3.mojo | 267 +++-- .../NewLISP/sieve-of-eratosthenes.l | 18 +- .../Odin/sieve-of-eratosthenes.odin | 2 +- .../Oz/sieve-of-eratosthenes.oz | 12 +- .../PHP/sieve-of-eratosthenes.php | 14 +- .../PL-SQL/sieve-of-eratosthenes-2.sql | 20 +- .../Perl/sieve-of-eratosthenes-10.pl | 150 +-- .../Perl/sieve-of-eratosthenes-6.pl | 6 +- .../Perl/sieve-of-eratosthenes-7.pl | 6 +- .../Perl/sieve-of-eratosthenes-9.pl | 14 +- .../PowerShell/sieve-of-eratosthenes-1.psh | 12 - .../PowerShell/sieve-of-eratosthenes-2.psh | 18 - .../Prolog/sieve-of-eratosthenes-1.pro | 2 +- .../Python/sieve-of-eratosthenes-10.py | 19 +- .../Python/sieve-of-eratosthenes-11.py | 48 +- .../Python/sieve-of-eratosthenes-12.py | 36 +- .../Python/sieve-of-eratosthenes-13.py | 58 +- .../Python/sieve-of-eratosthenes-14.py | 60 +- .../Python/sieve-of-eratosthenes-8.py | 88 +- .../Python/sieve-of-eratosthenes-9.py | 234 +++- .../REXX/sieve-of-eratosthenes-2.rexx | 8 +- .../Rust/sieve-of-eratosthenes-4.rs | 4 +- .../Rust/sieve-of-eratosthenes-5.rs | 292 ++--- .../Scheme/sieve-of-eratosthenes-8.scm | 6 +- .../Scheme/sieve-of-eratosthenes-9.scm | 4 +- .../Standard-ML/sieve-of-eratosthenes-1.ml | 14 +- .../Standard-ML/sieve-of-eratosthenes-2.ml | 10 +- .../Stata/sieve-of-eratosthenes-1.stata | 36 +- .../Stata/sieve-of-eratosthenes-3.stata | 24 +- .../UNIX-Shell/sieve-of-eratosthenes-4.sh | 32 +- .../VAX-Assembly/sieve-of-eratosthenes.vax | 40 +- .../VBScript/sieve-of-eratosthenes.vb | 20 - .../Vala/sieve-of-eratosthenes.vala | 60 +- .../Zkl/sieve-of-eratosthenes.zkl | 2 +- .../REXX/sieve-of-pritchard.rexx | 18 +- .../COBOL/simple-database.cobol | 262 ----- .../Emacs-Lisp/simple-database.l | 50 - .../PowerShell/simple-database-1.psh | 81 -- .../PowerShell/simple-database-2.psh | 1 - .../PowerShell/simple-database-3.psh | 1 - .../PowerShell/simple-database-4.psh | 1 - .../PowerShell/simple-database-5.psh | 1 - .../REBOL/simple-database.rebol | 15 - .../Ada/simple-turtle-graphics.ada | 169 --- .../Ada/simple-windowed-application.ada | 67 -- .../AutoIt/simple-windowed-application.autoit | 24 - .../Euphoria/simple-windowed-application.ex | 19 - .../JavaScript/simple-windowed-application.js | 29 - .../simple-windowed-application-1.psh | 20 - .../simple-windowed-application-2.psh | 23 - .../simple-windowed-application-3.psh | 38 - .../REBOL/simple-windowed-application.rebol | 27 - .../AutoIt/simulate-input-keyboard-1.autoit | 3 - .../AutoIt/simulate-input-keyboard-2.autoit | 3 - .../PowerShell/simulate-input-keyboard.psh | 6 - .../VBScript/simulate-input-keyboard.vb | 5 - .../FuncSug/simulate-input-mouse.funcsug | 2 +- Task/Singleton/Ada/singleton-1.ada | 10 - Task/Singleton/Ada/singleton-2.ada | 21 - Task/Singleton/Ada/singleton-3.ada | 11 - Task/Singleton/Ada/singleton-4.ada | 47 - .../singly-linked-list-element-definition.ada | 6 - .../singly-linked-list-element-insertion.ada | 34 - .../Ada/singly-linked-list-traversal.ada | 18 - .../Elena/singly-linked-list-traversal.elena | 2 +- .../Phix/sisyphus-sequence-1.phix | 70 +- .../Phix/sisyphus-sequence-2.phix | 54 +- .../Zig/sisyphus-sequence.zig | 47 +- Task/Sleep/Ada/sleep.ada | 11 - Task/Sleep/AutoIt/sleep.autoit | 6 - Task/Sleep/COBOL/sleep-1.cobol | 15 - Task/Sleep/COBOL/sleep-2.cobol | 18 - Task/Sleep/COBOL/sleep-3.cobol | 26 - Task/Sleep/Elena/sleep.elena | 8 +- Task/Sleep/Emacs-Lisp/sleep.l | 4 - Task/Sleep/PowerShell/sleep.psh | 4 - Task/Sleep/REBOL/sleep.rebol | 9 - Task/Sleep/REXX/sleep-3.rexx | 5 +- Task/Sleep/VBScript/sleep.vb | 4 - .../Ada/sleeping-beauty-problem.ada | 32 - .../Arturo/sleeping-beauty-problem.arturo | 4 +- .../Phix/sleeping-beauty-problem.phix | 29 +- ...2^m-is-composite-for-all-m-less-than-k.ada | 40 - .../EasyLang/smarandache-wellin-primes.easy | 10 +- .../Phix/smarandache-wellin-primes.phix | 89 +- .../smarandache-prime-digital-sequence.rexx | 12 +- Task/Smith-numbers/00-TASK.txt | 2 +- Task/Smith-numbers/Ada/smith-numbers.ada | 27 - .../Smith-numbers/Arturo/smith-numbers.arturo | 26 +- Task/Snake/Ada/snake.ada | 288 ----- Task/Snake/Emacs-Lisp/snake.l | 1 - Task/Sockets/Ada/sockets.ada | 14 - Task/Sockets/AutoIt/sockets.autoit | 7 - Task/Sockets/C/sockets.c | 38 - Task/Sockets/Elena/sockets.elena | 3 +- Task/Sockets/Emacs-Lisp/sockets.l | 5 - .../Ada/soloways-recurring-rainfall.ada | 48 - .../Arturo/soloways-recurring-rainfall.arturo | 5 +- .../COBOL/soloways-recurring-rainfall.cobol | 22 - .../Uiua/solve-a-hidato-puzzle.uiua | 42 +- .../Ada/solve-a-holy-knights-tour.ada | 36 - .../11l/solve-a-hopido-puzzle.11l | 4 +- .../11l/solve-a-numbrix-puzzle.11l | 168 +-- .../Python/solve-a-numbrix-puzzle-2.py | 5 +- .../Uiua/solve-a-numbrix-puzzle.uiua | 21 +- .../Ada/solve-the-no-connection-puzzle-1.ada | 10 - .../Ada/solve-the-no-connection-puzzle-2.ada | 47 - .../Ada/solve-the-no-connection-puzzle-3.ada | 6 - .../Ada/solve-the-no-connection-puzzle-4.ada | 73 -- .../Ada/solve-the-no-connection-puzzle-5.ada | 73 -- .../solve-the-no-connection-puzzle.chapel | 78 -- .../Ada/sort-a-list-of-object-identifiers.ada | 51 - .../sort-a-list-of-object-identifiers.jl | 3 +- .../sort-a-list-of-object-identifiers.rexx | 97 +- .../sort-a-list-of-object-identifiers.vb | 41 - ...ort-an-array-of-composite-structures-1.ada | 41 - ...ort-an-array-of-composite-structures-2.ada | 42 - ...ort-an-array-of-composite-structures-3.ada | 54 - ...ort-an-array-of-composite-structures.elena | 6 +- .../sort-an-array-of-composite-structures.ex | 15 - .../sort-an-array-of-composite-structures.psh | 9 - ...rt-an-array-of-composite-structures-2.rexx | 59 +- .../Ada/sort-an-integer-array.ada | 43 - .../COBOL/sort-an-integer-array.cobol | 22 - .../Elena/sort-an-integer-array.elena | 6 +- .../Euphoria/sort-an-integer-array.ex | 2 - .../PowerShell/sort-an-integer-array.psh | 1 - .../REBOL/sort-an-integer-array.rebol | 1 - .../REXX/sort-an-integer-array-1.rexx | 29 - .../REXX/sort-an-integer-array-2.rexx | 26 - .../Ada/sort-disjoint-sublist.ada | 57 - .../Arturo/sort-disjoint-sublist.arturo | 2 +- .../Elena/sort-disjoint-sublist.elena | 8 +- .../Euphoria/sort-disjoint-sublist.ex | 29 - .../Phix/sort-disjoint-sublist-1.phix | 18 - .../Phix/sort-disjoint-sublist-2.phix | 9 - .../PowerShell/sort-disjoint-sublist.psh | 9 - .../REXX/sort-disjoint-sublist.rexx | 76 +- .../Ada/sort-numbers-lexicographically.ada | 19 - .../sort-numbers-lexicographically.cobol | 36 - .../Phix/sort-numbers-lexicographically.phix | 22 +- .../Sort-stability/REBOL/sort-stability.rebol | 18 - .../Ada/sort-three-variables.ada | 64 -- .../COBOL/sort-three-variables.cobol | 43 - .../Elena/sort-three-variables.elena | 6 +- .../R/sort-three-variables-1.r | 4 - .../R/sort-three-variables-2.r | 26 - .../Racket/sort-three-variables.rkt | 2 - .../Ada/sort-using-a-custom-comparator.ada | 108 -- .../sort-using-a-custom-comparator.elena | 10 +- .../sort-using-a-custom-comparator.ex | 20 - .../sort-using-a-custom-comparator.psh | 2 - .../00-META.yaml | 1 - .../00-TASK.txt | 50 +- .../11l/sorting-algorithms-circle-sort.11l | 33 - .../sorting-algorithms-circle-sort.aarch64 | 206 ---- .../sorting-algorithms-circle-sort.alg | 67 -- .../sorting-algorithms-circle-sort.arm | 193 ---- .../sorting-algorithms-circle-sort.action | 111 -- .../sorting-algorithms-circle-sort.arturo | 41 - .../sorting-algorithms-circle-sort.ahk | 31 - .../C++/sorting-algorithms-circle-sort.cpp | 47 - .../C-sharp/sorting-algorithms-circle-sort.cs | 61 - .../C/sorting-algorithms-circle-sort.c | 34 - .../sorting-algorithms-circle-sort.coffee | 33 - .../Crystal/sorting-algorithms-circle-sort.cr | 35 - .../D/sorting-algorithms-circle-sort.d | 50 - .../Delphi/sorting-algorithms-circle-sort.pas | 70 -- .../sorting-algorithms-circle-sort.easy | 31 - .../Elixir/sorting-algorithms-circle-sort.ex | 43 - .../Forth/sorting-algorithms-circle-sort.fth | 33 - .../Fortran/sorting-algorithms-circle-sort.f | 75 -- .../sorting-algorithms-circle-sort.basic | 65 -- .../Go/sorting-algorithms-circle-sort.go | 42 - .../Haskell/sorting-algorithms-circle-sort.hs | 21 - .../J/sorting-algorithms-circle-sort-1.j | 5 - .../J/sorting-algorithms-circle-sort-2.j | 17 - .../Java/sorting-algorithms-circle-sort.java | 49 - .../Jq/sorting-algorithms-circle-sort-1.jq | 3 - .../Jq/sorting-algorithms-circle-sort-2.jq | 34 - .../Jq/sorting-algorithms-circle-sort-3.jq | 1 - .../Jq/sorting-algorithms-circle-sort-4.jq | 2 - .../Julia/sorting-algorithms-circle-sort.jl | 31 - .../Kotlin/sorting-algorithms-circle-sort.kts | 44 - .../Lua/sorting-algorithms-circle-sort.lua | 32 - .../sorting-algorithms-circle-sort.math | 35 - .../Nim/sorting-algorithms-circle-sort.nim | 37 - .../sorting-algorithms-circle-sort.objeck | 50 - .../sorting-algorithms-circle-sort.parigp | 26 - .../Pascal/sorting-algorithms-circle-sort.pas | 77 -- .../Perl/sorting-algorithms-circle-sort.pl | 23 - .../Phix/sorting-algorithms-circle-sort.phix | 44 - .../Python/sorting-algorithms-circle-sort.py | 53 - .../sorting-algorithms-circle-sort.quackery | 48 - .../REXX/sorting-algorithms-circle-sort.rexx | 26 - .../Racket/sorting-algorithms-circle-sort.rkt | 35 - .../Raku/sorting-algorithms-circle-sort.raku | 22 - .../Ring/sorting-algorithms-circle-sort.ring | 44 - .../Ruby/sorting-algorithms-circle-sort.rb | 31 - .../Rust/sorting-algorithms-circle-sort.rs | 42 - .../sorting-algorithms-circle-sort.scala | 40 - .../sorting-algorithms-circle-sort.sidef | 22 - .../sorting-algorithms-circle-sort.swift | 39 - .../sorting-algorithms-circle-sort.v | 42 - .../Wren/sorting-algorithms-circle-sort.wren | 36 - .../XPL0/sorting-algorithms-circle-sort.xpl0 | 33 - .../sorting-algorithms-circle-sort.basic | 11 - .../Zkl/sorting-algorithms-circle-sort-1.zkl | 24 - .../Zkl/sorting-algorithms-circle-sort-2.zkl | 2 - .../sorting-algorithms-bead-sort.arturo | 2 +- .../COBOL/sorting-algorithms-bead-sort.cobol | 98 -- .../Phix/sorting-algorithms-bead-sort.phix | 36 +- .../sorting-algorithms-bead-sort.psh | 40 - .../Python/sorting-algorithms-bead-sort.py | 17 +- .../Ada/sorting-algorithms-bogosort.ada | 50 - .../COBOL/sorting-algorithms-bogosort.cobol | 65 -- .../Elena/sorting-algorithms-bogosort.elena | 8 +- .../Euphoria/sorting-algorithms-bogosort.ex | 32 - .../Phix/sorting-algorithms-bogosort.phix | 26 +- .../sorting-algorithms-bogosort.psh | 29 - .../VBScript/sorting-algorithms-bogosort-1.vb | 30 - .../VBScript/sorting-algorithms-bogosort-2.vb | 10 - .../Ada/sorting-algorithms-bubble-sort.ada | 44 - .../sorting-algorithms-bubble-sort-1.cobol | 145 --- .../sorting-algorithms-bubble-sort-2.cobol | 54 - .../sorting-algorithms-bubble-sort.elena | 4 +- .../sorting-algorithms-bubble-sort.ex | 27 - .../Haxe/sorting-algorithms-bubble-sort.haxe | 39 - .../sorting-algorithms-bubble-sort.psh | 14 - .../sorting-algorithms-bubble-sort-1.vb | 31 - .../sorting-algorithms-bubble-sort-2.vb | 5 - ...ms-cocktail-sort-with-shifting-bounds.phix | 72 +- ...thms-cocktail-sort-with-shifting-bounds.vb | 31 - .../Ada/sorting-algorithms-cocktail-sort.ada | 37 - .../sorting-algorithms-cocktail-sort.cobol | 38 - .../sorting-algorithms-cocktail-sort.elena | 8 +- .../sorting-algorithms-cocktail-sort.ex | 25 - .../sorting-algorithms-cocktail-sort.haxe | 49 - .../sorting-algorithms-cocktail-sort.phix | 50 +- .../sorting-algorithms-cocktail-sort.psh | 32 - .../sorting-algorithms-cocktail-sort-1.vb | 30 - .../sorting-algorithms-cocktail-sort-2.vb | 7 - .../Ada/sorting-algorithms-comb-sort.ada | 47 - .../COBOL/sorting-algorithms-comb-sort.cobol | 41 - .../Elena/sorting-algorithms-comb-sort.elena | 8 +- .../Haxe/sorting-algorithms-comb-sort.haxe | 43 - .../Phix/sorting-algorithms-comb-sort.phix | 39 +- .../sorting-algorithms-comb-sort.psh | 31 - .../Ada/sorting-algorithms-counting-sort.ada | 49 - .../sorting-algorithms-counting-sort.elena | 8 +- .../sorting-algorithms-counting-sort.haxe | 33 - .../sorting-algorithms-counting-sort.phix | 33 +- .../sorting-algorithms-counting-sort.psh | 21 - .../sorting-algorithms-counting-sort-1.vb | 42 - .../sorting-algorithms-counting-sort-2.vb | 5 - .../Ada/sorting-algorithms-gnome-sort-1.ada | 6 - .../Ada/sorting-algorithms-gnome-sort-2.ada | 25 - .../Ada/sorting-algorithms-gnome-sort-3.ada | 19 - .../sorting-algorithms-gnome-sort.arturo | 5 +- .../COBOL/sorting-algorithms-gnome-sort.cobol | 30 - .../Elena/sorting-algorithms-gnome-sort.elena | 6 +- .../Euphoria/sorting-algorithms-gnome-sort.ex | 22 - .../Haxe/sorting-algorithms-gnome-sort.haxe | 39 - .../Phix/sorting-algorithms-gnome-sort.phix | 46 +- .../sorting-algorithms-gnome-sort.psh | 20 - .../sorting-algorithms-gnome-sort-1.vb | 27 - .../sorting-algorithms-gnome-sort-2.vb | 22 - .../sorting-algorithms-gnome-sort-3.vb | 5 - .../Ada/sorting-algorithms-heapsort-1.ada | 6 - .../Ada/sorting-algorithms-heapsort-2.ada | 50 - .../Ada/sorting-algorithms-heapsort-3.ada | 19 - .../Arturo/sorting-algorithms-heapsort.arturo | 4 +- .../COBOL/sorting-algorithms-heapsort.cobol | 81 -- .../Haxe/sorting-algorithms-heapsort.haxe | 60 - .../Phix/sorting-algorithms-heapsort.phix | 69 +- .../sorting-algorithms-heapsort.psh | 35 - .../REXX/sorting-algorithms-heapsort-2.rexx | 5 +- .../Ada/sorting-algorithms-insertion-sort.ada | 18 - .../sorting-algorithms-insertion-sort-1.cobol | 27 - .../sorting-algorithms-insertion-sort-2.cobol | 70 -- .../sorting-algorithms-insertion-sort.elena | 6 +- .../sorting-algorithms-insertion-sort.l | 30 - .../sorting-algorithms-insertion-sort.ex | 22 - .../sorting-algorithms-insertion-sort.basic | 3 +- .../sorting-algorithms-insertion-sort.haxe | 33 - .../sorting-algorithms-insertion-sort.phix | 36 +- .../sorting-algorithms-insertion-sort.psh | 15 - .../sorting-algorithms-insertion-sort.rebol | 39 - .../sorting-algorithms-insertion-sort.vb | 36 - .../Ada/sorting-algorithms-merge-sort-1.ada | 9 - .../Ada/sorting-algorithms-merge-sort-2.ada | 62 - .../Ada/sorting-algorithms-merge-sort-3.ada | 19 - .../sorting-algorithms-merge-sort.arturo | 5 +- .../COBOL/sorting-algorithms-merge-sort.cobol | 293 ----- .../Euphoria/sorting-algorithms-merge-sort.ex | 37 - .../Phix/sorting-algorithms-merge-sort.phix | 60 +- .../sorting-algorithms-merge-sort.psh | 36 - .../REXX/sorting-algorithms-merge-sort-3.rexx | 5 +- .../Ada/sorting-algorithms-pancake-sort.ada | 45 - .../sorting-algorithms-pancake-sort.elena | 6 +- .../sorting-algorithms-pancake-sort.ex | 34 - .../Haxe/sorting-algorithms-pancake-sort.haxe | 48 - .../Phix/sorting-algorithms-pancake-sort.phix | 36 +- .../sorting-algorithms-pancake-sort.psh | 38 - .../Ada/sorting-algorithms-patience-sort.ada | 288 ----- .../sorting-algorithms-patience-sort.phix | 72 +- .../sorting-algorithms-patience-sort.rexx | 92 +- .../sorting-algorithms-permutation-sort.ada | 39 - .../sorting-algorithms-permutation-sort.phix | 32 +- .../sorting-algorithms-permutation-sort.psh | 40 - .../Ada/sorting-algorithms-quicksort-1.ada | 9 - .../Ada/sorting-algorithms-quicksort-2.ada | 44 - .../Ada/sorting-algorithms-quicksort-3.ada | 32 - .../COBOL/sorting-algorithms-quicksort.cobol | 66 -- .../Elena/sorting-algorithms-quicksort.elena | 6 +- .../Emacs-Lisp/sorting-algorithms-quicksort.l | 10 - .../sorting-algorithms-quicksort-1.psh | 52 - .../sorting-algorithms-quicksort-2.psh | 15 - .../sorting-algorithms-quicksort-3.psh | 15 - .../REXX/sorting-algorithms-quicksort-5.rexx | 5 +- .../VBScript/sorting-algorithms-quicksort.vb | 35 - .../Ada/sorting-algorithms-radix-sort.ada | 83 -- .../C/sorting-algorithms-radix-sort.c | 66 -- .../Phix/sorting-algorithms-radix-sort.phix | 88 +- .../Ada/sorting-algorithms-selection-sort.ada | 31 - .../sorting-algorithms-selection-sort.arturo | 2 +- .../sorting-algorithms-selection-sort.cobol | 28 - .../sorting-algorithms-selection-sort.elena | 6 +- .../sorting-algorithms-selection-sort.ex | 24 - .../sorting-algorithms-selection-sort.haxe | 38 - .../sorting-algorithms-selection-sort.phix | 40 +- .../sorting-algorithms-selection-sort.psh | 20 - .../sorting-algorithms-selection-sort.vb | 19 - .../Ada/sorting-algorithms-shell-sort-1.ada | 7 - .../Ada/sorting-algorithms-shell-sort-2.ada | 30 - .../sorting-algorithms-shell-sort-1.cobol | 100 -- .../sorting-algorithms-shell-sort-2.cobol | 55 - .../Euphoria/sorting-algorithms-shell-sort.ex | 24 - .../Haxe/sorting-algorithms-shell-sort.haxe | 38 - .../Phix/sorting-algorithms-shell-sort.phix | 38 +- .../sorting-algorithms-shell-sort.psh | 26 - .../Ada/sorting-algorithms-sleep-sort.ada | 15 - .../Assembly/sorting-algorithms-sleep-sort.as | 113 -- .../Elena/sorting-algorithms-sleep-sort.elena | 8 +- .../sorting-algorithms-sleep-sort.l | 2 - .../Euphoria/sorting-algorithms-sleep-sort.ex | 31 - .../Phix/sorting-algorithms-sleep-sort.phix | 50 +- .../Ada/sorting-algorithms-stooge-sort.ada | 32 - .../sorting-algorithms-stooge-sort.cobol | 80 -- .../sorting-algorithms-stooge-sort.elena | 6 +- .../sorting-algorithms-stooge-sort.ex | 25 - .../Phix/sorting-algorithms-stooge-sort.phix | 30 +- .../sorting-algorithms-stooge-sort.psh | 22 - .../sorting-algorithms-strand-sort.ex | 43 - .../Phix/sorting-algorithms-strand-sort.phix | 72 +- Task/Soundex/Ada/soundex.ada | 42 - Task/Soundex/Arturo/soundex.arturo | 29 +- Task/Soundex/COBOL/soundex.cobol | 149 --- Task/Soundex/Emacs-Lisp/soundex.l | 108 -- Task/Soundex/PowerShell/soundex-1.psh | 81 -- Task/Soundex/PowerShell/soundex-2.psh | 2 - Task/Soundex/PowerShell/soundex-3.psh | 18 - Task/Soundex/PowerShell/soundex-4.psh | 15 - Task/Soundex/VBScript/soundex.vb | 43 - .../Arturo/sparkline-in-unicode.arturo | 2 +- .../Phix/sparkline-in-unicode.phix | 52 +- .../VBScript/sparkline-in-unicode.vb | 71 -- .../Ada/special-characters-1.ada | 6 - .../Ada/special-characters-2.ada | 6 - .../PowerShell/special-variables-1.psh | 40 - .../PowerShell/special-variables-2.psh | 1 - .../AutoIt/speech-synthesis.autoit | 2 - .../PowerShell/speech-synthesis.psh | 6 - .../VBScript/speech-synthesis.vb | 4 - .../Arturo/sphenic-numbers.arturo | 4 +- .../Ada/spinning-rod-animation-text.ada | 23 - .../Emacs-Lisp/spinning-rod-animation-text.l | 4 - .../360-Assembly/spiral-matrix.360 | 2 +- Task/Spiral-matrix/Ada/spiral-matrix-1.ada | 67 -- Task/Spiral-matrix/Ada/spiral-matrix-2.ada | 33 - .../Spiral-matrix/Arturo/spiral-matrix.arturo | 7 +- Task/Spiral-matrix/C++/spiral-matrix-1.cpp | 76 +- Task/Spiral-matrix/C++/spiral-matrix-2.cpp | 24 +- Task/Spiral-matrix/C-sharp/spiral-matrix-3.cs | 22 +- Task/Spiral-matrix/C/spiral-matrix-1.c | 42 +- Task/Spiral-matrix/C/spiral-matrix-2.c | 16 +- .../Common-Lisp/spiral-matrix-2.lisp | 4 +- Task/Spiral-matrix/Delphi/spiral-matrix.pas | 78 +- Task/Spiral-matrix/Euphoria/spiral-matrix.ex | 29 - Task/Spiral-matrix/Fortran/spiral-matrix.f | 2 +- Task/Spiral-matrix/Haskell/spiral-matrix-3.hs | 2 +- .../PowerShell/spiral-matrix.psh | 36 - Task/Spiral-matrix/Scala/spiral-matrix.scala | 2 +- Task/Spiral-matrix/Stata/spiral-matrix.stata | 18 +- Task/Spiral-matrix/VBScript/spiral-matrix.vb | 47 - ...er-string-based-on-change-of-character.ada | 16 - ...string-based-on-change-of-character.arturo | 7 +- ...-string-based-on-change-of-character.cobol | 61 - ...cter-string-based-on-change-of-character.l | 29 - ...-string-based-on-change-of-character-1.psh | 20 - ...-string-based-on-change-of-character-2.psh | 1 - .../Ada/square-but-not-cube.ada | 35 - .../COBOL/square-but-not-cube.cobol | 29 - .../Lua/square-but-not-cube.lua | 21 - .../Phix/square-but-not-cube.phix | 34 +- .../REXX/square-form-factorization.rexx | 107 +- .../Pascal/square-free-integers.pas | 162 --- .../Phix/square-free-integers.phix | 52 +- .../REXX/square-free-integers.rexx | 10 +- .../Uiua/square-free-integers.uiua | 13 +- .../PowerShell/stable-marriage-problem.psh | 136 --- Task/Stack-traces/Ada/stack-traces.ada | 31 - Task/Stack-traces/Elena/stack-traces.elena | 6 +- Task/Stack/Ada/stack-1.ada | 16 - Task/Stack/Ada/stack-2.ada | 42 - Task/Stack/Arturo/stack.arturo | 6 +- Task/Stack/Batch-File/stack.bat | 69 -- Task/Stack/COBOL/stack-1.cobol | 2 - Task/Stack/COBOL/stack-2.cobol | 5 - Task/Stack/COBOL/stack-3.cobol | 1 - Task/Stack/COBOL/stack-4.cobol | 3 - Task/Stack/COBOL/stack-5.cobol | 247 ---- Task/Stack/COBOL/stack-6.cobol | 37 - Task/Stack/Crystal/stack.cr | 17 +- Task/Stack/Elena/stack.elena | 2 +- Task/Stack/PowerShell/stack-1.psh | 3 - Task/Stack/PowerShell/stack-2.psh | 1 - Task/Stack/PowerShell/stack-3.psh | 1 - Task/Stack/PowerShell/stack-4.psh | 1 - Task/Stack/PowerShell/stack-5.psh | 1 - Task/Stack/PowerShell/stack-6.psh | 1 - Task/Stack/PowerShell/stack-7.psh | 1 - Task/Stack/REBOL/stack.rebol | 34 - Task/Stack/V-(Vlang)/stack.v | 4 +- Task/Stack/VBScript/stack-1.vb | 56 - Task/Stack/VBScript/stack-2.vb | 39 - .../Ada/stair-climbing-puzzle-1.ada | 6 - .../Ada/stair-climbing-puzzle-2.ada | 32 - .../Euphoria/stair-climbing-puzzle.ex | 6 - .../PowerShell/stair-climbing-puzzle.psh | 28 - .../REBOL/stair-climbing-puzzle.rebol | 39 - .../Ada/start-from-a-main-routine.ada | 5 - .../Phix/start-from-a-main-routine.phix | 10 +- .../Ada/statistics-basic-1.ada | 63 - .../Ada/statistics-basic-2.ada | 77 -- .../PARI-GP/statistics-basic-1.parigp | 4 +- .../Phix/statistics-basic.phix | 62 +- .../Haxe/steffensens-method.haxe | 94 -- .../Ada/stem-and-leaf-plot.ada | 40 - .../Euphoria/stem-and-leaf-plot.ex | 28 - .../PowerShell/stem-and-leaf-plot.psh | 10 - .../Uiua/stem-and-leaf-plot.uiua | 2 +- .../Ada/stern-brocot-sequence.ada | 94 -- .../PowerShell/stern-brocot-sequence.psh | 28 - .../VBScript/stern-brocot-sequence.vb | 40 - .../VBScript/straddling-checkerboard.vb | 88 -- Task/Strassens-algorithm/00-TASK.txt | 2 +- .../Python/strassens-algorithm.py | 77 +- Task/Stream-merge/Ada/stream-merge.ada | 72 -- Task/String-append/Ada/string-append.ada | 9 - .../String-append/Arturo/string-append.arturo | 4 +- Task/String-append/COBOL/string-append.cobol | 23 - Task/String-append/Elena/string-append.elena | 4 +- .../Emacs-Lisp/string-append-1.l | 3 - .../Emacs-Lisp/string-append-2.l | 5 - .../Emacs-Lisp/string-append-3.l | 8 - Task/String-append/Euphoria/string-append.ex | 7 - .../PowerShell/string-append.psh | 3 - Task/String-append/VBScript/string-append.vb | 3 - Task/String-case/Ada/string-case.ada | 9 - Task/String-case/AutoIt/string-case.autoit | 3 - Task/String-case/COBOL/string-case-1.cobol | 30 - Task/String-case/COBOL/string-case-2.cobol | 32 - Task/String-case/Elena/string-case.elena | 8 +- Task/String-case/Kotlin/string-case.kts | 12 +- Task/String-case/Maxima/string-case.maxima | 6 +- Task/String-case/PowerShell/string-case.psh | 6 - Task/String-case/Python/string-case-1.py | 11 - Task/String-case/Python/string-case-2.py | 2 - Task/String-case/REBOL/string-case.rebol | 3 - Task/String-case/VBScript/string-case.vb | 3 - .../Ada/string-comparison.ada | 28 - .../COBOL/string-comparison-1.cobol | 3 - .../COBOL/string-comparison-2.cobol | 3 - .../COBOL/string-comparison-3.cobol | 2 - .../Elena/string-comparison.elena | 16 +- .../PowerShell/string-comparison-1.psh | 6 - .../PowerShell/string-comparison-2.psh | 2 - .../Ada/string-concatenation.ada | 9 - .../COBOL/string-concatenation-1.cobol | 15 - .../COBOL/string-concatenation-2.cobol | 8 - .../COBOL/string-concatenation-3.cobol | 11 - .../Elena/string-concatenation.elena | 8 +- .../Emacs-Lisp/string-concatenation.l | 4 - .../Euphoria/string-concatenation.ex | 7 - .../PowerShell/string-concatenation.psh | 8 - .../REBOL/string-concatenation.rebol | 3 - .../ReScript/string-concatenation.re | 5 - .../VBScript/string-concatenation.vb | 3 - .../Ada/string-interpolation-included--1.ada | 11 - .../Ada/string-interpolation-included--2.ada | 1 - .../string-interpolation-included-.cobol | 12 - .../string-interpolation-included-.elena | 4 +- .../string-interpolation-included-.l | 4 - .../string-interpolation-included-.ex | 4 - .../Haxe/string-interpolation-included-.haxe | 7 - .../string-interpolation-included--1.psh | 2 - .../string-interpolation-included--2.psh | 2 - .../string-interpolation-included--3.psh | 2 - .../string-interpolation-included-.rebol | 7 - Task/String-length/Ada/string-length-1.ada | 2 - Task/String-length/Ada/string-length-2.ada | 6 - .../String-length/COBOL/string-length-1.cobol | 1 - .../String-length/COBOL/string-length-2.cobol | 1 - .../String-length/COBOL/string-length-3.cobol | 1 - .../String-length/COBOL/string-length-4.cobol | 1 - .../String-length/Elena/string-length-1.elena | 2 +- .../String-length/Elena/string-length-2.elena | 2 +- .../Emacs-Lisp/string-length-1.l | 2 - .../Emacs-Lisp/string-length-2.l | 2 - .../Emacs-Lisp/string-length-3.l | 7 - Task/String-length/Euphoria/string-length.ex | 1 - .../FutureBasic/string-length.basic | 2 + .../PowerShell/string-length-1.psh | 2 - .../PowerShell/string-length-2.psh | 2 - .../PowerShell/string-length-3.psh | 1 - .../String-length/REBOL/string-length-1.rebol | 5 - .../String-length/REBOL/string-length-2.rebol | 2 - Task/String-length/REXX/string-length.rexx | 26 +- Task/String-length/ReScript/string-length.re | 1 - .../String-length/VBScript/string-length-1.vb | 1 - .../String-length/VBScript/string-length-2.vb | 1 - Task/String-matching/Ada/string-matching.ada | 20 - .../AutoIt/string-matching.autoit | 29 - .../Batch-File/string-matching.bat | 70 -- .../Elena/string-matching.elena | 28 +- .../Emacs-Lisp/string-matching.l | 14 - .../Euphoria/string-matching.ex | 30 - .../Factor/string-matching-1.factor | 1 - .../Factor/string-matching-2.factor | 1 - .../Factor/string-matching-3.factor | 1 - .../Factor/string-matching-4.factor | 1 - .../Factor/string-matching-5.factor | 2 - .../Java/string-matching-1.java | 20 + .../Java/string-matching-10.java | 32 - .../Java/string-matching-2.java | 41 +- .../Java/string-matching-3.java | 1 - .../Java/string-matching-4.java | 1 - .../Java/string-matching-5.java | 1 - .../Java/string-matching-6.java | 1 - .../Java/string-matching-7.java | 1 - .../Java/string-matching-8.java | 6 - .../Java/string-matching-9.java | 7 - Task/String-matching/Jq/string-matching-1.jq | 20 + Task/String-matching/Jq/string-matching-2.jq | 15 +- Task/String-matching/Jq/string-matching-3.jq | 3 - Task/String-matching/Jq/string-matching-4.jq | 5 - Task/String-matching/Jq/string-matching-5.jq | 6 - Task/String-matching/Jq/string-matching-6.jq | 3 - .../M2000-Interpreter/string-matching-1.m2000 | 15 - .../M2000-Interpreter/string-matching-2.m2000 | 15 - .../OCaml/string-matching-1.ml | 6 - .../OCaml/string-matching-2.ml | 10 - .../OCaml/string-matching-3.ml | 6 - .../OCaml/string-matching-4.ml | 10 - .../OCaml/string-matching-5.ml | 12 - .../PL-I/string-matching-1.pli | 11 - .../PL-I/string-matching-2.pli | 20 - .../String-matching/Perl/string-matching-1.pl | 3 - .../String-matching/Perl/string-matching-2.pl | 3 - .../String-matching/Perl/string-matching-3.pl | 2 - .../String-matching/Perl/string-matching-4.pl | 1 - .../String-matching/Perl/string-matching-5.pl | 1 - .../String-matching/Phix/string-matching.phix | 53 +- .../PowerShell/string-matching.psh | 5 - .../PureBasic/string-matching-1.basic | 15 - .../PureBasic/string-matching-2.basic | 11 - .../PureBasic/string-matching-3.basic | 42 - .../Raku/string-matching-1.raku | 3 - .../Raku/string-matching-2.raku | 3 - .../Raku/string-matching-3.raku | 2 - .../Raku/string-matching-4.raku | 2 - .../String-matching/Sed/string-matching-1.sed | 1 - .../String-matching/Sed/string-matching-2.sed | 1 - .../String-matching/Sed/string-matching-3.sed | 1 - .../VBScript/string-matching.vb | 43 - Task/String-prepend/Ada/string-prepend.ada | 8 - .../Arturo/string-prepend.arturo | 4 +- .../COBOL/string-prepend-1.cobol | 25 - .../COBOL/string-prepend-2.cobol | 12 - .../String-prepend/Elena/string-prepend.elena | 8 +- .../Emacs-Lisp/string-prepend-1.l | 3 - .../Emacs-Lisp/string-prepend-2.l | 5 - .../Emacs-Lisp/string-prepend-3.l | 8 - Task/String-prepend/Phix/string-prepend.phix | 6 +- .../PowerShell/string-prepend.psh | 3 - .../String-prepend/VBScript/string-prepend.vb | 3 - ...trip-a-set-of-characters-from-a-string.ada | 27 - ...-set-of-characters-from-a-string.asymptote | 2 +- ...ip-a-set-of-characters-from-a-string.cobol | 47 - ...ip-a-set-of-characters-from-a-string.elena | 4 +- .../strip-a-set-of-characters-from-a-string.l | 6 - ...strip-a-set-of-characters-from-a-string.ex | 8 - ...rip-a-set-of-characters-from-a-string.odin | 16 - ...trip-a-set-of-characters-from-a-string.psh | 2 - ...strip-a-set-of-characters-from-a-string.vb | 10 - .../Ada/strip-block-comments.ada | 93 -- .../Ada/strip-comments-from-a-string.ada | 20 - .../strip-comments-from-a-string-1.autoit | 17 - .../strip-comments-from-a-string-2.autoit | 56 - .../COBOL/strip-comments-from-a-string.cobol | 21 - .../Emacs-Lisp/strip-comments-from-a-string.l | 5 - .../VBScript/strip-comments-from-a-string.vb | 11 - ...-and-extended-characters-from-a-string.ada | 35 - ...d-extended-characters-from-a-string.arturo | 4 +- ...nd-extended-characters-from-a-string-1.psh | 47 - ...nd-extended-characters-from-a-string-2.psh | 6 - ...nd-extended-characters-from-a-string-3.psh | 1 - ...s-and-extended-characters-from-a-string.vb | 26 - ...-whitespace-from-a-string-top-and-tail.ada | 10 - ...tespace-from-a-string-top-and-tail-1.cobol | 3 - ...tespace-from-a-string-top-and-tail-2.cobol | 3 - ...-whitespace-from-a-string-top-and-tail-1.l | 3 - ...-whitespace-from-a-string-top-and-tail-2.l | 8 - ...p-whitespace-from-a-string-top-and-tail.ex | 17 - ...-whitespace-from-a-string-top-and-tail.psh | 4 - ...whitespace-from-a-string-top-and-tail.ring | 21 +- ...hitespace-from-a-string-top-and-tail.seed7 | 10 - ...p-whitespace-from-a-string-top-and-tail.vb | 28 - .../EasyLang/strong-and-weak-primes.easy | 23 +- .../REXX/strong-and-weak-primes.rexx | 8 +- Task/Subleq/Ada/subleq.ada | 68 -- Task/Subleq/Arturo/subleq.arturo | 8 +- Task/Subleq/COBOL/subleq.cobol | 81 -- Task/Subleq/PowerShell/subleq-1.psh | 37 - Task/Subleq/PowerShell/subleq-2.psh | 1 - .../Ada/substitution-cipher.ada | 46 - .../Arturo/substitution-cipher-1.arturo | 4 +- .../Emacs-Lisp/substitution-cipher.l | 41 - .../Kotlin/substitution-cipher.kts | 2 +- .../VBScript/substitution-cipher.vb | 55 - .../Ada/substring-top-and-tail-1.ada | 11 - .../Ada/substring-top-and-tail-2.ada | 33 - .../Arturo/substring-top-and-tail.arturo | 2 +- .../COBOL/substring-top-and-tail.cobol | 17 - .../Elena/substring-top-and-tail.elena | 8 +- .../Emacs-Lisp/substring-top-and-tail.l | 4 - .../Euphoria/substring-top-and-tail.ex | 15 - .../PowerShell/substring-top-and-tail-1.psh | 5 - .../PowerShell/substring-top-and-tail-2.psh | 5 - .../VBScript/substring-top-and-tail.vb | 14 - Task/Substring/Ada/substring-1.ada | 1 - Task/Substring/Ada/substring-2.ada | 1 - Task/Substring/Ada/substring-3.ada | 14 - Task/Substring/COBOL/substring.cobol | 56 - Task/Substring/Elena/substring.elena | 12 +- Task/Substring/Euphoria/substring.ex | 39 - Task/Substring/PowerShell/substring.psh | 23 - Task/Substring/REBOL/substring.rebol | 41 - Task/Substring/ReScript/substring.re | 12 - Task/Substring/VBScript/substring.vb | 16 - .../11l/subtractive-generator.11l | 2 +- .../Ada/subtractive-generator-1.ada | 11 - .../Ada/subtractive-generator-2.ada | 33 - .../Ada/subtractive-generator-3.ada | 14 - .../PowerShell/subtractive-generator.psh | 46 - .../successive-prime-differences.arturo | 2 +- .../successive-prime-differences.easy | 39 +- .../REXX/successive-prime-differences.rexx | 8 +- Task/Sudan-function/Ada/sudan-function.ada | 19 - Task/Sudan-function/Phix/sudan-function.phix | 44 +- Task/Sudoku/11l/sudoku.11l | 10 +- Task/Sudoku/Ada/sudoku.ada | 108 -- Task/Sudoku/EasyLang/sudoku.easy | 20 +- Task/Sudoku/Uiua/sudoku.uiua | 24 +- Task/Sudoku/VBScript/sudoku-1.vb | 102 -- Task/Sudoku/VBScript/sudoku-2.vb | 117 -- .../Phix/suffixation-of-decimal-numbers.phix | 112 +- Task/Sum-and-product-of-an-array/00-TASK.txt | 7 + .../Ada/sum-and-product-of-an-array-1.ada | 7 - .../Ada/sum-and-product-of-an-array-2.ada | 8 - .../COBOL/sum-and-product-of-an-array.cobol | 25 - .../Elena/sum-and-product-of-an-array.elena | 2 +- .../sum-and-product-of-an-array-1.l | 3 - .../sum-and-product-of-an-array-2.l | 5 - .../sum-and-product-of-an-array-3.l | 5 - .../Euphoria/sum-and-product-of-an-array.ex | 14 - .../sum-and-product-of-an-array-1.psh | 3 - .../sum-and-product-of-an-array-2.psh | 11 - .../sum-and-product-of-an-array-3.psh | 7 - .../sum-and-product-of-an-array-4.psh | 16 - .../REBOL/sum-and-product-of-an-array.rebol | 35 - .../VBScript/sum-and-product-of-an-array.vb | 15 - .../ALGOL-68/sum-and-product-puzzle.alg | 6 +- .../Phix/sum-and-product-puzzle.phix | 98 +- .../Ada/sum-digits-of-an-integer.ada | 28 - .../Arturo/sum-digits-of-an-integer.arturo | 4 +- .../Emacs-Lisp/sum-digits-of-an-integer.l | 4 - .../PowerShell/sum-digits-of-an-integer.psh | 14 - .../REXX/sum-digits-of-an-integer-2.rexx | 49 +- .../REXX/sum-digits-of-an-integer-3.rexx | 13 - .../Ada/sum-multiples-of-3-and-5-1.ada | 21 - .../Ada/sum-multiples-of-3-and-5-2.ada | 39 - .../COBOL/sum-multiples-of-3-and-5-1.cobol | 23 - .../COBOL/sum-multiples-of-3-and-5-2.cobol | 47 - .../COBOL/sum-multiples-of-3-and-5-3.cobol | 40 - .../Emacs-Lisp/sum-multiples-of-3-and-5-1.l | 6 - .../Emacs-Lisp/sum-multiples-of-3-and-5-2.l | 4 - .../PowerShell/sum-multiples-of-3-and-5-1.psh | 9 - .../PowerShell/sum-multiples-of-3-and-5-2.psh | 10 - .../PowerShell/sum-multiples-of-3-and-5-3.psh | 31 - .../VBScript/sum-multiples-of-3-and-5.vb | 10 - Task/Sum-of-a-series/Ada/sum-of-a-series.ada | 20 - .../COBOL/sum-of-a-series.cobol | 19 - .../Elena/sum-of-a-series.elena | 2 +- .../Emacs-Lisp/sum-of-a-series.l | 6 - .../Euphoria/sum-of-a-series.ex | 13 - .../Haxe/sum-of-a-series-1.haxe | 11 - .../Haxe/sum-of-a-series-2.haxe | 10 - .../PowerShell/sum-of-a-series.psh | 4 - .../VBScript/sum-of-a-series.vb | 5 - ...elements-below-main-diagonal-of-matrix.ada | 39 - ...ements-below-main-diagonal-of-matrix.agena | 2 +- Task/Sum-of-squares/Ada/sum-of-squares.ada | 18 - .../Sum-of-squares/Elena/sum-of-squares.elena | 4 +- .../Emacs-Lisp/sum-of-squares.l | 4 - .../Sum-of-squares/Euphoria/sum-of-squares.ex | 8 - .../PowerShell/sum-of-squares.psh | 10 - .../ReScript/sum-of-squares-1.re | 3 - .../ReScript/sum-of-squares-2.re | 3 - .../Sum-of-squares/VBScript/sum-of-squares.vb | 11 - Task/Sum-to-100/ALGOL-68/sum-to-100.alg | 138 ++- Task/Sum-to-100/Ada/sum-to-100-1.ada | 12 - Task/Sum-to-100/Ada/sum-to-100-2.ada | 40 - Task/Sum-to-100/Ada/sum-to-100-3.ada | 10 - Task/Sum-to-100/Ada/sum-to-100-4.ada | 67 -- Task/Sum-to-100/D/sum-to-100.d | 1 - Task/Sum-to-100/EasyLang/sum-to-100.easy | 86 +- Task/Sum-to-100/Elixir/sum-to-100.ex | 11 +- Task/Sum-to-100/FutureBasic/sum-to-100.basic | 2 + Task/Sum-to-100/Phix/sum-to-100.phix | 149 ++- .../Ada/summarize-and-say-sequence.ada | 62 - .../EasyLang/summarize-primes.easy | 20 +- .../Phix/summarize-primes.phix | 8 +- Task/Superellipse/Ada/superellipse.ada | 73 -- .../sutherland-hodgman-polygon-clipping.ada | 113 -- .../ALGOL-68/sylvesters-sequence.alg | 12 +- .../Arturo/sylvesters-sequence.arturo | 2 +- .../PL-M/sylvesters-sequence.plm | 4 +- .../Ada/symmetric-difference.ada | 27 - .../PowerShell/symmetric-difference.psh | 21 - .../REBOL/symmetric-difference.rebol | 3 - .../Ada/synchronous-concurrency-1.ada | 6 - .../Ada/synchronous-concurrency-2.ada | 26 - .../Ada/synchronous-concurrency-3.ada | 19 - .../Euphoria/synchronous-concurrency.ex | 58 - .../Phix/synchronous-concurrency.phix | 94 +- Task/System-time/Ada/system-time.ada | 10 - Task/System-time/AutoIt/system-time.autoit | 1 - Task/System-time/COBOL/system-time.cobol | 15 - Task/System-time/Elena/system-time.elena | 4 +- Task/System-time/Emacs-Lisp/system-time.l | 2 - Task/System-time/Phix/system-time.phix | 13 +- Task/System-time/PowerShell/system-time-1.psh | 1 - Task/System-time/PowerShell/system-time-2.psh | 1 - Task/System-time/REBOL/system-time.rebol | 3 - Task/System-time/REXX/system-time.rexx | 77 +- Task/System-time/VBScript/system-time.vb | 1 - .../table-creation-postal-addresses.psh | 33 - .../table-creation-postal-addresses.vb | 14 - .../Ada/take-notes-on-the-command-line.ada | 51 - .../take-notes-on-the-command-line.arturo | 7 +- .../take-notes-on-the-command-line.cobol | 78 -- .../take-notes-on-the-command-line.ex | 32 - .../take-notes-on-the-command-line.psh | 9 - .../take-notes-on-the-command-line.rebol | 12 - Task/Tau-function/Arturo/tau-function.arturo | 2 +- Task/Tau-function/COBOL/tau-function.cobol | 65 -- Task/Tau-number/ALGOL-68/tau-number.alg | 2 +- Task/Tau-number/Arturo/tau-number.arturo | 5 +- Task/Tau-number/REXX/tau-number-2.rexx | 13 +- .../Arturo/teacup-rim-text.arturo | 2 +- .../Ada/temperature-conversion.ada | 14 - .../AutoIt/temperature-conversion.autoit | 20 - .../COBOL/temperature-conversion.cobol | 36 - .../Elena/temperature-conversion.elena | 18 +- .../Euphoria/temperature-conversion.ex | 7 - .../Insitux/temperature-conversion.insitux | 2 +- .../PowerShell/temperature-conversion-1.psh | 21 - .../PowerShell/temperature-conversion-2.psh | 27 - .../PowerShell/temperature-conversion-3.psh | 1 - .../VBScript/temperature-conversion.vb | 19 - .../terminal-control-clear-the-screen.aarch64 | 54 - .../Ada/terminal-control-clear-the-screen.ada | 5 - .../terminal-control-clear-the-screen.bat | 1 - .../C/terminal-control-clear-the-screen-2.c | 9 +- .../terminal-control-clear-the-screen.cobol | 11 - .../terminal-control-clear-the-screen.elena | 4 +- .../terminal-control-clear-the-screen.ex | 1 - .../terminal-control-clear-the-screen.psh | 1 - .../Ada/terminal-control-coloured-text.ada | 20 - .../terminal-control-coloured-text.cobol | 89 -- .../terminal-control-coloured-text.psh | 1 - .../Ada/terminal-control-cursor-movement.ada | 37 - .../terminal-control-cursor-positioning.ada | 9 - .../terminal-control-cursor-positioning.cobol | 8 - .../terminal-control-cursor-positioning.elena | 4 +- .../terminal-control-cursor-positioning.ex | 2 - .../terminal-control-cursor-positioning-1.psh | 2 - .../terminal-control-cursor-positioning-2.psh | 2 - .../COBOL/terminal-control-dimensions.cobol | 27 - .../Euphoria/terminal-control-dimensions.ex | 12 - ...ontrol-display-an-extended-character-1.ada | 7 - ...ontrol-display-an-extended-character-2.ada | 6 - ...ontrol-display-an-extended-character.cobol | 8 - .../terminal-control-hiding-the-cursor.ada | 17 - .../Ada/terminal-control-inverse-video.ada | 11 - .../terminal-control-inverse-video.cobol | 9 - .../terminal-control-positional-read.psh | 3 - .../terminal-control-preserve-screen.l | 17 - ...inal-control-ringing-the-terminal-bell.ada | 7 - ...inal-control-ringing-the-terminal-bell.bat | 5 +- ...-control-ringing-the-terminal-bell-1.cobol | 12 - ...-control-ringing-the-terminal-bell-2.cobol | 17 - ...-control-ringing-the-terminal-bell-3.cobol | 13 - ...rminal-control-ringing-the-terminal-bell.l | 2 - ...al-control-ringing-the-terminal-bell-1.psh | 1 - ...al-control-ringing-the-terminal-bell-2.psh | 1 - .../terminal-control-unicode-output.arturo | 7 +- Task/Ternary-logic/Ada/ternary-logic-1.ada | 15 - Task/Ternary-logic/Ada/ternary-logic-2.ada | 62 - Task/Ternary-logic/Ada/ternary-logic-3.ada | 35 - Task/Ternary-logic/Elena/ternary-logic.elena | 12 +- .../Test-a-function/Ada/test-a-function-1.ada | 28 - .../Test-a-function/Ada/test-a-function-2.ada | 5 - .../Euphoria/test-a-function.ex | 10 - .../Test-a-function/Uiua/test-a-function.uiua | 12 +- .../Test-integerness/Ada/test-integerness.ada | 49 - .../COBOL/test-integerness.cobol | 35 - .../PowerShell/test-integerness-1.psh | 20 - .../PowerShell/test-integerness-2.psh | 5 - .../Ada/text-processing-1.ada | 76 -- .../COBOL/text-processing-1.cobol | 144 --- .../PowerShell/text-processing-1.psh | 54 - .../VBScript/text-processing-1.vb | 63 - .../Ada/text-processing-2.ada | 63 - .../COBOL/text-processing-2.cobol | 163 --- .../PowerShell/text-processing-2-1.psh | 23 - .../PowerShell/text-processing-2-2.psh | 20 - .../VBScript/text-processing-2.vb | 54 - .../text-processing-max-licenses-in-use.ada | 70 -- .../text-processing-max-licenses-in-use.cobol | 90 -- .../text-processing-max-licenses-in-use.ex | 55 - .../text-processing-max-licenses-in-use.psh | 45 - Task/Textonyms/Arturo/textonyms.arturo | 4 +- Task/Textonyms/PowerShell/textonyms.psh | 45 - Task/Textonyms/VBScript/textonyms.vb | 47 - Task/The-Name-Game/Ada/the-name-game.ada | 53 - Task/The-Name-Game/COBOL/the-name-game.cobol | 58 - Task/The-Name-Game/Phix/the-name-game.phix | 46 +- .../PowerShell/the-name-game.psh | 53 - .../Ada/the-twelve-days-of-christmas.ada | 36 - .../AutoLISP/the-twelve-days-of-christmas.l | 30 - .../COBOL/the-twelve-days-of-christmas.cobol | 44 - .../Elena/the-twelve-days-of-christmas.elena | 10 +- .../the-twelve-days-of-christmas.psh | 39 - .../VBScript/the-twelve-days-of-christmas.vb | 27 - Task/The-sieve-of-Sundaram/00-TASK.txt | 20 + .../EasyLang/the-sieve-of-sundaram.easy | 6 +- .../Python/the-sieve-of-sundaram-2.py | 153 ++- .../REXX/the-sieve-of-sundaram.rexx | 11 +- .../Ada/thieles-interpolation-formula-1.ada | 17 - .../Ada/thieles-interpolation-formula-2.ada | 56 - .../Ada/thieles-interpolation-formula-3.ada | 43 - .../thieles-interpolation-formula.psh | 69 -- Task/Thue-Morse/Ada/thue-morse.ada | 18 - Task/Thue-Morse/Arturo/thue-morse.arturo | 4 +- Task/Thue-Morse/COBOL/thue-morse.cobol | 24 - Task/Thue-Morse/Elena/thue-morse.elena | 8 +- Task/Thue-Morse/Phix/thue-morse.phix | 12 +- Task/Thue-Morse/PowerShell/thue-morse.psh | 31 - Task/Tic-tac-toe/Ada/tic-tac-toe.ada | 124 -- Task/Tic-tac-toe/Euphoria/tic-tac-toe.ex | 100 -- Task/Tic-tac-toe/J/tic-tac-toe-1.j | 4 +- Task/Tic-tac-toe/J/tic-tac-toe-2.j | 4 +- Task/Tic-tac-toe/J/tic-tac-toe-4.j | 2 +- Task/Tic-tac-toe/Julia/tic-tac-toe.jl | 102 -- Task/Tic-tac-toe/K/tic-tac-toe.k | 11 +- Task/Tic-tac-toe/Lua/tic-tac-toe.lua | 190 --- Task/Time-a-function/11l/time-a-function.11l | 2 +- Task/Time-a-function/Ada/time-a-function.ada | 31 - .../Agena/time-a-function.agena | 4 +- .../Elena/time-a-function.elena | 10 +- .../Euphoria/time-a-function.ex | 5 - .../Insitux/time-a-function.insitux | 2 +- .../PowerShell/time-a-function.psh | 12 - .../REXX/time-a-function-2.rexx | 4 +- .../Ada/tokenize-a-string-with-escaping.ada | 57 - .../tokenize-a-string-with-escaping.arturo | 14 +- .../tokenize-a-string-with-escaping.cobol | 135 --- .../tokenize-a-string-with-escaping.elena | 6 +- .../tokenize-a-string-with-escaping-1.psh | 29 - .../tokenize-a-string-with-escaping-2.psh | 3 - .../Ada/tokenize-a-string.ada | 21 - .../COBOL/tokenize-a-string.cobol | 30 - .../EasyLang/tokenize-a-string.easy | 4 +- .../Elena/tokenize-a-string.elena | 4 +- .../Euphoria/tokenize-a-string.ex | 22 - .../PowerShell/tokenize-a-string-1.psh | 2 - .../PowerShell/tokenize-a-string-2.psh | 2 - .../PowerShell/tokenize-a-string-3.psh | 1 - .../REBOL/tokenize-a-string.rebol | 4 - .../REXX/tokenize-a-string-1.rexx | 24 +- .../Tcl/tokenize-a-string-1.tcl | 8 +- .../Tcl/tokenize-a-string-2.tcl | 3 +- .../Tcl/tokenize-a-string-3.tcl | 1 - .../Tcl/tokenize-a-string-4.tcl | 1 - .../VBScript/tokenize-a-string.vb | 2 - .../PowerShell/tonelli-shanks-algorithm.psh | 74 -- .../Ada/top-rank-per-group.ada | 71 -- .../Elena/top-rank-per-group.elena | 10 +- .../PowerShell/top-rank-per-group.psh | 32 - .../PowerShell/topic-variable-1.psh | 2 - .../PowerShell/topic-variable-2.psh | 1 - .../PowerShell/topic-variable-3.psh | 1 - .../Ada/topological-sort-1.ada | 52 - .../Ada/topological-sort-2.ada | 106 -- .../Ada/topological-sort-3.ada | 42 - .../Ada/topological-sort-4.ada | 68 -- .../Ada/topological-sort-5.ada | 83 -- .../PowerShell/topological-sort.psh | 99 -- .../Topological-sort/Rust/topological-sort.rs | 125 +- .../VBScript/topological-sort-1.vb | 79 -- .../VBScript/topological-sort-2.vb | 23 - Task/Topswops/Ada/topswops.ada | 39 - .../Ada/total-circles-area.ada | 109 -- .../Totient-function/Ada/totient-function.ada | 76 -- .../Agena/totient-function.agena | 2 +- .../Arturo/totient-function.arturo | 2 +- .../COBOL/totient-function.cobol | 93 -- .../REXX/totient-function.rexx | 10 +- Task/Towers-of-Hanoi/Ada/towers-of-hanoi.ada | 15 - .../AutoIt/towers-of-hanoi.autoit | 11 - .../COBOL/towers-of-hanoi-1.cobol | 28 - .../COBOL/towers-of-hanoi-2.cobol | 29 - .../COBOL/towers-of-hanoi-3.cobol | 91 -- .../Elena/towers-of-hanoi.elena | 2 +- .../Emacs-Lisp/towers-of-hanoi.l | 6 - .../PowerShell/towers-of-hanoi.psh | 10 - .../REBOL/towers-of-hanoi.rebol | 21 - .../Towers-of-Hanoi/Uiua/towers-of-hanoi.uiua | 11 +- .../VBScript/towers-of-hanoi.vb | 11 - .../Ada/trabb-pardo-knuth-algorithm.ada | 36 - .../Agena/trabb-pardo-knuth-algorithm.agena | 4 +- .../AutoIt/trabb-pardo-knuth-algorithm.autoit | 24 - .../Elena/trabb-pardo-knuth-algorithm.elena | 14 +- .../trabb-pardo-knuth-algorithm-1.psh | 49 - .../trabb-pardo-knuth-algorithm-2.psh | 2 - .../trabb-pardo-knuth-algorithm-3.psh | 1 - .../VBScript/trabb-pardo-knuth-algorithm.vb | 20 - ...english-text-using-the-greek-alphabet.phix | 176 ++- Task/Tree-traversal/00-TASK.txt | 1 + Task/Tree-traversal/Ada/tree-traversal.ada | 108 -- Task/Tree-traversal/Coq/tree-traversal.coq | 51 - .../Tree-traversal/Elena/tree-traversal.elena | 10 +- .../Tree-traversal/Euphoria/tree-traversal.ex | 67 -- .../Tree-traversal/REBOL/tree-traversal.rebol | 46 - .../Tree-traversal/VBScript/tree-traversal.vb | 60 - .../Ada/trigonometric-functions.ada | 35 - .../AutoLISP/trigonometric-functions.l | 25 - .../COBOL/trigonometric-functions.cobol | 39 - .../Elena/trigonometric-functions.elena | 34 +- .../PowerShell/trigonometric-functions-1.psh | 12 - .../PowerShell/trigonometric-functions-2.psh | 15 - .../REBOL/trigonometric-functions.rebol | 27 - .../REXX/trigonometric-functions.rexx | 4 +- .../Ada/truncatable-primes.ada | 69 -- .../EasyLang/truncatable-primes.easy | 30 +- .../Elena/truncatable-primes.elena | 12 +- .../PowerShell/truncatable-primes.psh | 51 - .../REXX/truncatable-primes-2.rexx | 11 +- .../Uiua/truncatable-primes.uiua | 9 +- .../VBScript/truncatable-primes.vb | 68 -- Task/Truncate-a-file/Ada/truncate-a-file.ada | 55 - .../Elena/truncate-a-file.elena | 24 +- .../PowerShell/truncate-a-file.psh | 3 - .../VBScript/truncate-a-file.vb | 39 - .../11l/twelve-statements.11l | 28 +- .../Ada/twelve-statements-1.ada | 79 -- .../Ada/twelve-statements-2.ada | 16 - .../Ada/twelve-statements-3.ada | 27 - .../Elena/twelve-statements.elena | 12 +- Task/Twin-primes/Ada/twin-primes.ada | 129 --- Task/Twin-primes/REXX/twin-primes.rexx | 8 +- .../11l/two-bullet-roulette.11l | 2 +- Task/Twos-complement/Ada/twos-complement.ada | 10 - .../COBOL/twos-complement.cobol | 31 - Task/UPC/Ada/upc.ada | 162 --- Task/UPC/VBScript/upc.vb | 102 -- Task/URL-decoding/Ada/url-decoding-1.ada | 7 - Task/URL-decoding/Ada/url-decoding-2.ada | 3 - Task/URL-decoding/Ada/url-decoding-3.ada | 28 - Task/URL-decoding/Ada/url-decoding-4.ada | 16 - Task/URL-decoding/Langur/url-decoding.langur | 4 +- Task/URL-decoding/Phix/url-decoding.phix | 68 +- Task/URL-decoding/PowerShell/url-decoding.psh | 1 - Task/URL-decoding/VBScript/url-decoding.vb | 45 - Task/URL-encoding/Ada/url-encoding.ada | 7 - Task/URL-encoding/EasyLang/url-encoding.easy | 40 +- Task/URL-encoding/Phix/url-encoding.phix | 56 +- Task/URL-encoding/PowerShell/url-encoding.psh | 3 - Task/URL-encoding/VBScript/url-encoding.vb | 16 - Task/URL-parser/Ada/url-parser.ada | 67 -- Task/URL-parser/PowerShell/url-parser-1.psh | 43 - Task/URL-parser/PowerShell/url-parser-2.psh | 17 - Task/URL-parser/V-(Vlang)/url-parser.v | 2 +- Task/URL-parser/VBScript/url-parser.vb | 96 -- .../Ada/utf-8-encode-and-decode.ada | 49 - .../Elena/utf-8-encode-and-decode.elena | 12 +- .../Langur/utf-8-encode-and-decode.langur | 2 +- .../VBScript/utf-8-encode-and-decode.vb | 86 -- .../Ada/ulam-spiral-for-primes--1.ada | 19 - .../Ada/ulam-spiral-for-primes--2.ada | 36 - .../Ada/ulam-spiral-for-primes--3.ada | 27 - .../PowerShell/ulam-spiral-for-primes-.psh | 40 - .../REXX/ulam-spiral-for-primes-.rexx | 12 +- .../VBScript/ulam-spiral-for-primes-.vb | 80 -- Task/Ultra-useful-primes/00-TASK.txt | 1 - .../Phix/ultra-useful-primes.phix | 46 +- .../Ada/unbias-a-random-generator.ada | 51 - .../Elena/unbias-a-random-generator.elena | 6 +- .../Euphoria/unbias-a-random-generator.ex | 25 - .../unbias-a-random-generator-1.psh | 15 - .../unbias-a-random-generator-2.psh | 15 - .../Undefined-values/Ada/undefined-values.ada | 23 - .../PowerShell/undefined-values-1.psh | 8 - .../PowerShell/undefined-values-2.psh | 1 - .../PowerShell/undefined-values-3.psh | 1 - .../PowerShell/undefined-values-4.psh | 1 - .../Arturo/unicode-strings.arturo | 3 +- .../Elena/unicode-strings.elena | 6 +- .../PowerShell/unicode-strings.psh | 2 - .../Ada/unicode-variable-names.ada | 8 - .../Elena/unicode-variable-names.elena | 4 +- .../Emacs-Lisp/unicode-variable-names.l | 3 - .../PowerShell/unicode-variable-names.psh | 3 - .../11l/universal-turing-machine.11l | 46 +- .../Ada/universal-turing-machine-1.ada | 54 - .../Ada/universal-turing-machine-2.ada | 98 -- .../Ada/universal-turing-machine-3.ada | 27 - .../Ada/universal-turing-machine-4.ada | 31 - Task/Unix-ls/Ada/unix-ls.ada | 32 - Task/Unix-ls/Perl/unix-ls-1.pl | 4 +- Task/Unix-ls/PowerShell/unix-ls.psh | 5 - .../Agena/unprimeable-numbers.agena | 4 +- .../Arturo/unprimeable-numbers.arturo | 2 +- .../REXX/unprimeable-numbers.rexx | 4 +- .../REXX/untouchable-numbers.rexx | 11 +- .../update-a-configuration-file-1.psh | 107 -- .../update-a-configuration-file-2.psh | 3 - .../VBScript/update-a-configuration-file.vb | 57 - ...-another-language-to-call-a-function-1.ada | 8 - ...-another-language-to-call-a-function-2.ada | 14 - ...-another-language-to-call-a-function-3.ada | 4 - ...-another-language-to-call-a-function.cobol | 33 - ...e-another-language-to-call-a-function.haxe | 1 - .../Ada/user-input-graphical.ada | 80 -- .../PowerShell/user-input-graphical.psh | 98 -- .../REBOL/user-input-graphical.rebol | 58 - .../VBScript/user-input-graphical.vb | 2 - .../User-input-Text/Ada/user-input-text-1.ada | 14 - .../User-input-Text/Ada/user-input-text-2.ada | 2 - .../User-input-Text/Ada/user-input-text-3.ada | 15 - .../User-input-Text/Ada/user-input-text-4.ada | 18 - .../Batch-File/user-input-text.bat | 7 +- .../COBOL/user-input-text.cobol | 17 - .../Elena/user-input-text.elena | 6 +- .../Euphoria/user-input-text.ex | 9 - Task/User-input-Text/OPL/user-input-text.opl | 21 +- .../PowerShell/user-input-text.psh | 2 - .../REBOL/user-input-text.rebol | 27 - .../V-(Vlang)/user-input-text-2.v | 2 +- ...ional-securities-identification-number.ada | 74 -- ...nal-securities-identification-number.cobol | 173 --- ...nal-securities-identification-number.basic | 2 + ...nal-securities-identification-number-1.psh | 63 - ...nal-securities-identification-number-2.psh | 6 - ...onal-securities-identification-number.uiua | 10 +- ...tional-securities-identification-number.vb | 47 - .../EasyLang/vampire-number.easy | 2 +- Task/Vampire-number/Phix/vampire-number.phix | 82 +- .../Van-Eck-sequence/Ada/van-eck-sequence.ada | 35 - .../Agena/van-eck-sequence.agena | 2 +- .../COBOL/van-eck-sequence.cobol | 46 - .../Uiua/van-eck-sequence.uiua | 10 +- .../Ada/van-der-corput-sequence.ada | 27 - .../Agena/van-der-corput-sequence.agena | 20 +- .../Euphoria/van-der-corput-sequence.ex | 20 - .../Lua/van-der-corput-sequence-1.lua | 8 + .../VBScript/van-der-corput-sequence.vb | 48 - .../Phix/variable-declaration-reset.phix | 20 +- .../Ada/variable-length-quantity.ada | 92 -- .../Euphoria/variable-length-quantity.ex | 41 - .../Ada/variable-size-get.ada | 2 - .../COBOL/variable-size-get.cobol | 61 - .../Ada/variable-size-set.ada | 2 - Task/Variables/Ada/variables.ada | 19 - Task/Variables/COBOL/variables-1.cobol | 5 - Task/Variables/COBOL/variables-2.cobol | 18 - Task/Variables/COBOL/variables-3.cobol | 4 - Task/Variables/COBOL/variables-4.cobol | 4 - Task/Variables/COBOL/variables-5.cobol | 8 - Task/Variables/COBOL/variables-6.cobol | 3 - Task/Variables/COBOL/variables-7.cobol | 6 - Task/Variables/Elena/variables.elena | 2 +- Task/Variables/PowerShell/variables-1.psh | 2 - Task/Variables/PowerShell/variables-2.psh | 2 - Task/Variables/PowerShell/variables-3.psh | 1 - Task/Variables/PowerShell/variables-4.psh | 1 - Task/Variables/PowerShell/variables-5.psh | 5 - Task/Variables/REXX/variables-1.rexx | 6 + Task/Variables/REXX/variables-2.rexx | 13 +- .../Ada/variadic-function.ada | 30 - .../Arturo/variadic-function.arturo | 9 +- .../COBOL/variadic-function.cobol | 58 - .../Coq/variadic-function-1.coq | 4 - .../Coq/variadic-function-2.coq | 1 - .../Coq/variadic-function-3.coq | 5 - .../Coq/variadic-function-4.coq | 1 - .../Coq/variadic-function-5.coq | 1 - .../Coq/variadic-function-6.coq | 11 - .../Coq/variadic-function-7.coq | 7 - .../Coq/variadic-function-8.coq | 1 - .../Coq/variadic-function-9.coq | 2 - .../Elena/variadic-function.elena | 4 +- .../Emacs-Lisp/variadic-function-1.l | 6 - .../Emacs-Lisp/variadic-function-2.l | 2 - .../Euphoria/variadic-function.ex | 8 - .../PowerShell/variadic-function-1.psh | 5 - .../PowerShell/variadic-function-2.psh | 1 - .../PowerShell/variadic-function-3.psh | 2 - .../PowerShell/variadic-function-4.psh | 1 - .../REBOL/variadic-function.rebol | 11 - .../REXX/variadic-function-1.rexx | 20 +- .../REXX/variadic-function-2.rexx | 16 +- .../REXX/variadic-function-3.rexx | 10 - .../REXX/variadic-function-4.rexx | 13 - .../Tcl/variadic-function-1.tcl | 10 - .../Tcl/variadic-function-2.tcl | 1 - Task/Vector-products/00-TASK.txt | 9 +- Task/Vector-products/Ada/vector-products.ada | 78 -- Task/Vector-products/C/vector-products.c | 47 - .../Euphoria/vector-products.ex | 36 - .../PowerShell/vector-products.psh | 27 - .../Vector-products/REXX/vector-products.rexx | 4 +- Task/Vector/00-TASK.txt | 18 + Task/Vector/ALGOL-68/vector.alg | 2 +- Task/Vector/Ada/vector.ada | 31 - Task/Vector/Arturo/vector.arturo | 49 +- Task/Vector/C++/vector.cpp | 90 +- Task/Vector/C/vector.c | 83 -- Task/Vector/Lang/vector.lang | 40 - Task/Vector/PowerShell/vector.psh | 8 - Task/Vector/REXX/vector.rexx | 4 +- .../Phix/verhoeff-algorithm.phix | 118 +- ...ribution-uniformity-chi-squared-test-1.ada | 8 - ...ribution-uniformity-chi-squared-test-2.ada | 27 - ...ribution-uniformity-chi-squared-test-3.ada | 28 - ...tribution-uniformity-chi-squared-test.rexx | 4 +- .../verify-distribution-uniformity-naive.ada | 51 - .../verify-distribution-uniformity-naive.rexx | 4 +- .../verify-distribution-uniformity-naive-1.vb | 24 - .../verify-distribution-uniformity-naive-2.vb | 2 - .../Ada/vigen-re-cipher-cryptanalysis.ada | 167 --- Task/Vigen-re-cipher/Ada/vigen-re-cipher.ada | 55 - .../Arturo/vigen-re-cipher.arturo | 10 +- .../EasyLang/vigen-re-cipher.easy | 10 +- .../Elena/vigen-re-cipher.elena | 12 +- .../PowerShell/vigen-re-cipher.psh | 85 -- .../VBScript/vigen-re-cipher-1.vb | 47 - .../VBScript/vigen-re-cipher-2.vb | 34 - .../Visualize-a-tree/Ada/visualize-a-tree.ada | 36 - .../Elena/visualize-a-tree.elena | 8 +- .../ReScript/voronoi-diagram.re | 66 -- .../EasyLang/wagstaff-primes.easy | 12 +- .../Wagstaff-primes/Phix/wagstaff-primes.phix | 35 - .../Ada/walk-a-directory-non-recursively.ada | 19 - .../walk-a-directory-non-recursively-2.bat | 4 +- .../walk-a-directory-non-recursively-3.bat | 1 - .../walk-a-directory-non-recursively.elena | 4 +- .../walk-a-directory-non-recursively.l | 5 - .../walk-a-directory-non-recursively.ex | 12 - .../walk-a-directory-non-recursively-1.psh | 2 - .../walk-a-directory-non-recursively-2.psh | 1 - .../walk-a-directory-non-recursively.vb | 10 - .../Ada/walk-a-directory-recursively.ada | 24 - .../Emacs-Lisp/walk-a-directory-recursively.l | 2 - .../walk-a-directory-recursively-1.psh | 1 - .../walk-a-directory-recursively-2.psh | 2 - .../walk-a-directory-recursively-3.psh | 3 - .../walk-a-directory-recursively-4.psh | 1 - Task/War-card-game/Ada/war-card-game.ada | 146 --- ...steful-equidigital-and-frugal-numbers.easy | 67 +- .../Ada/water-collected-between-towers.ada | 74 -- .../water-collected-between-towers-1.phix | 46 +- .../water-collected-between-towers-2.phix | 34 +- .../water-collected-between-towers-3.phix | 46 +- Task/Web-scraping/Ada/web-scraping.ada | 34 - .../PowerShell/web-scraping-1.psh | 4 - .../PowerShell/web-scraping-2.psh | 1 - .../PowerShell/web-scraping-3.psh | 1 - Task/Web-scraping/REBOL/web-scraping.rebol | 25 - Task/Web-scraping/VBScript/web-scraping.vb | 30 - Task/Weird-numbers/Ada/weird-numbers-1.ada | 109 -- Task/Weird-numbers/Ada/weird-numbers-2.ada | 105 -- .../Wieferich-primes/Ada/wieferich-primes.ada | 41 - .../Phix/wieferich-primes-1.phix | 20 +- .../Phix/wieferich-primes-2.phix | 22 +- .../REXX/wieferich-primes-2.rexx | 10 +- Task/Wilson-primes-of-order-n/00-TASK.txt | 1 - .../EasyLang/wilson-primes-of-order-n.easy | 26 +- .../REXX/wilson-primes-of-order-n-1.rexx | 9 +- .../REXX/wilson-primes-of-order-n-2.rexx | 11 +- .../COBOL/window-creation-x11.cobol | 175 --- Task/Window-creation/Ada/window-creation.ada | 41 - .../AutoIt/window-creation.autoit | 9 - .../Emacs-Lisp/window-creation.l | 1 - .../Euphoria/window-creation-1.ex | 5 - .../Euphoria/window-creation-2.ex | 6 - .../Euphoria/window-creation-3.ex | 10 - .../Euphoria/window-creation-4.ex | 5 - .../Euphoria/window-creation-5.ex | 5 - .../PowerShell/window-creation-1.psh | 1 - .../PowerShell/window-creation-2.psh | 4 - .../REBOL/window-creation.rebol | 1 - Task/Wireworld/11l/wireworld.11l | 2 +- Task/Wireworld/Ada/wireworld.ada | 66 -- Task/Wireworld/AutoIt/wireworld.autoit | 102 -- Task/Wireworld/Elena/wireworld.elena | 32 +- Task/Word-frequency/Ada/word-frequency.ada | 87 -- .../Arturo/word-frequency.arturo | 2 +- .../Word-frequency/COBOL/word-frequency.cobol | 213 ---- .../Emacs-Lisp/word-frequency.l | 28 - .../Word-frequency/REXX/word-frequency-1.rexx | 107 +- .../Word-frequency/REXX/word-frequency-2.rexx | 136 ++- Task/Word-ladder/Ada/word-ladder.ada | 146 --- Task/Word-ladder/Mathematica/word-ladder.math | 25 +- Task/Word-search/Ada/word-search.ada | 259 ----- Task/Word-wheel/Ada/word-wheel.ada | 56 - Task/Word-wheel/Rust/word-wheel.rs | 4 +- Task/Word-wheel/VBScript/word-wheel.vb | 74 -- Task/Word-wrap/Ada/word-wrap-1.ada | 18 - Task/Word-wrap/Ada/word-wrap-2.ada | 36 - Task/Word-wrap/Ada/word-wrap-3.ada | 62 - Task/Word-wrap/Elena/word-wrap.elena | 12 +- Task/Word-wrap/PowerShell/word-wrap-1.psh | 29 - Task/Word-wrap/PowerShell/word-wrap-2.psh | 52 - Task/Word-wrap/PowerShell/word-wrap-3.psh | 12 - Task/Word-wrap/VBScript/word-wrap.vb | 30 - Task/Wordiff/Arturo/wordiff.arturo | 4 +- Task/Wordiff/V-(Vlang)/wordiff.v | 2 +- .../11l/world-cup-group-stage.11l | 6 +- .../Elena/world-cup-group-stage.elena | 12 +- .../Ada/write-entire-file.ada | 18 - .../Arturo/write-entire-file.arturo | 2 +- .../COBOL/write-entire-file.cobol | 41 - .../Elena/write-entire-file.elena | 2 +- .../PowerShell/write-entire-file.psh | 1 - .../VBScript/write-entire-file.vb | 12 - .../Ada/write-float-arrays-to-a-text-file.ada | 34 - .../write-float-arrays-to-a-text-file.cobol | 42 - .../write-float-arrays-to-a-text-file.ex | 10 - .../write-float-arrays-to-a-text-file.psh | 8 - .../Ada/write-language-name-in-3d-ascii.ada | 17 - .../write-language-name-in-3d-ascii.cobol | 78 -- .../write-language-name-in-3d-ascii-1.phix | 22 +- .../write-language-name-in-3d-ascii-2.phix | 6 +- .../write-language-name-in-3d-ascii-3.phix | 38 +- .../write-to-windows-event-log-1.psh | 13 - .../write-to-windows-event-log-2.psh | 5 - .../write-to-windows-event-log-3.psh | 7 - .../VBScript/write-to-windows-event-log.vb | 21 - .../Ada/xml-dom-serialization.ada | 24 - Task/XML-Input/Ada/xml-input-1.ada | 23 - Task/XML-Input/Ada/xml-input-2.ada | 12 - Task/XML-Input/Ada/xml-input-3.ada | 14 - Task/XML-Input/Ada/xml-input-4.ada | 41 - Task/XML-Input/Ada/xml-input-5.ada | 16 - Task/XML-Input/Ada/xml-input-6.ada | 21 - Task/XML-Input/Ada/xml-input-7.ada | 39 - Task/XML-Input/Bracmat/xml-input-1.bracmat | 14 - Task/XML-Input/Bracmat/xml-input-2.bracmat | 27 - Task/XML-Input/PowerShell/xml-input.psh | 13 - Task/XML-Input/REBOL/xml-input.rebol | 35 - Task/XML-Output/Ada/xml-output-1.ada | 40 - Task/XML-Output/Ada/xml-output-2.ada | 53 - Task/XML-Output/Bracmat/xml-output.bracmat | 112 -- Task/XML-Output/Euphoria/xml-output.ex | 34 - Task/XML-Output/VBScript/xml-output.vb | 17 - Task/XML-XPath/PowerShell/xml-xpath-1.psh | 31 - Task/XML-XPath/PowerShell/xml-xpath-2.psh | 1 - Task/XML-XPath/PowerShell/xml-xpath-3.psh | 2 - Task/XML-XPath/PowerShell/xml-xpath-4.psh | 1 - Task/XML-XPath/PowerShell/xml-xpath-5.psh | 1 - Task/XML-XPath/VBScript/xml-xpath.vb | 29 - .../Y-combinator/Chapel/y-combinator-1.chapel | 36 - .../Y-combinator/Chapel/y-combinator-2.chapel | 48 - Task/Y-combinator/Elena/y-combinator.elena | 6 +- .../PowerShell/y-combinator-1.psh | 51 - .../PowerShell/y-combinator-2.psh | 48 - Task/Y-combinator/REBOL/y-combinator-1.rebol | 1 - Task/Y-combinator/REBOL/y-combinator-2.rebol | 2 - .../Ada/yellowstone-sequence.ada | 68 -- .../Agena/yellowstone-sequence.agena | 2 +- .../Arturo/yellowstone-sequence.arturo | 6 +- .../REXX/yellowstone-sequence.rexx | 4 +- Task/Yin-and-yang/Ada/yin-and-yang.ada | 32 - Task/Zebra-puzzle/Ada/zebra-puzzle.ada | 106 -- .../Elena/zeckendorf-arithmetic.elena | 126 +- .../zeckendorf-number-representation.alg | 31 +- .../Ada/zeckendorf-number-representation.ada | 26 - .../zeckendorf-number-representation.arturo | 10 +- .../zeckendorf-number-representation.autoit | 42 - .../zeckendorf-number-representation.elena | 6 +- .../zeckendorf-number-representation-1.psh | 26 - .../zeckendorf-number-representation-2.psh | 2 - .../zeckendorf-number-representation.vb | 25 - .../Ada/zero-to-the-zero-power.ada | 31 - .../C/zero-to-the-zero-power.c | 6 +- .../COBOL/zero-to-the-zero-power.cobol | 9 - .../Elena/zero-to-the-zero-power.elena | 4 +- .../Emacs-Lisp/zero-to-the-zero-power.l | 1 - .../PowerShell/zero-to-the-zero-power.psh | 1 - .../Python/zero-to-the-zero-power-2.py | 18 +- .../SNOBOL4/zero-to-the-zero-power.sno | 2 +- .../VBScript/zero-to-the-zero-power.vb | 1 - .../XBasic/zero-to-the-zero-power.basic | 6 +- .../11l/zhang-suen-thinning-algorithm.11l | 2 +- .../Elena/zhang-suen-thinning-algorithm.elena | 16 +- .../Julia/zhang-suen-thinning-algorithm.jl | 54 +- Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada | 50 - .../AppleScript/zig-zag-matrix-1.applescript | 40 +- .../AppleScript/zig-zag-matrix-2.applescript | 30 +- .../Arturo/zig-zag-matrix.arturo | 11 +- .../AutoIt/zig-zag-matrix.autoit | 27 - .../Zig-zag-matrix/Beads/zig-zag-matrix.beads | 90 +- Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp | 110 +- Task/Zig-zag-matrix/C/zig-zag-matrix.c | 24 +- .../Ceylon/zig-zag-matrix.ceylon | 90 +- .../Zig-zag-matrix/Clojure/zig-zag-matrix.clj | 4 +- Task/Zig-zag-matrix/Crystal/zig-zag-matrix.cr | 2 +- Task/Zig-zag-matrix/D/zig-zag-matrix-2.d | 2 +- Task/Zig-zag-matrix/Delphi/zig-zag-matrix.pas | 54 +- .../Zig-zag-matrix/Elena/zig-zag-matrix.elena | 4 +- Task/Zig-zag-matrix/Erlang/zig-zag-matrix.erl | 8 +- .../Zig-zag-matrix/Euphoria/zig-zag-matrix.ex | 20 - Task/Zig-zag-matrix/Ksh/zig-zag-matrix.ksh | 20 +- .../M2000-Interpreter/zig-zag-matrix.m2000 | 70 +- .../PARI-GP/zig-zag-matrix.parigp | 38 +- Task/Zig-zag-matrix/PHP/zig-zag-matrix.php | 34 +- Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl | 18 +- .../PlainTeX/zig-zag-matrix.tex | 26 +- .../PowerShell/zig-zag-matrix-1.psh | 39 - .../PowerShell/zig-zag-matrix-2.psh | 1 - Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro | 70 +- .../Zig-zag-matrix/Python/zig-zag-matrix-4.py | 28 +- Task/Zig-zag-matrix/Raku/zig-zag-matrix.raku | 26 +- .../Rascal/zig-zag-matrix-3.rascal | 22 +- .../Standard-ML/zig-zag-matrix.ml | 8 +- .../Stata/zig-zag-matrix-1.stata | 20 +- .../Stata/zig-zag-matrix-2.stata | 12 +- Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua | 7 - .../Zig-zag-matrix/VBScript/zig-zag-matrix.vb | 36 - 7735 files changed, 38060 insertions(+), 199180 deletions(-) delete mode 120000 Lang/11l/Bioinformatics-base-count delete mode 120000 Lang/11l/Meissel-Mertens-constant delete mode 120000 Lang/11l/Miller-Rabin-primality-test delete mode 120000 Lang/11l/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/AArch64-Assembly/Bioinformatics-base-count delete mode 120000 Lang/AArch64-Assembly/Miller-Rabin-primality-test delete mode 120000 Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/ALGOL-68/Bioinformatics-base-count delete mode 120000 Lang/ALGOL-68/Meissel-Mertens-constant delete mode 120000 Lang/ALGOL-68/Miller-Rabin-primality-test delete mode 120000 Lang/ALGOL-68/Quaternion-type delete mode 120000 Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/ALGOL-W/Copy-a-string delete mode 120000 Lang/ALGOL-W/Integer-comparison delete mode 120000 Lang/ALGOL-W/Meissel-Mertens-constant delete mode 120000 Lang/ALGOL-W/Quaternion-type delete mode 120000 Lang/APL/Bioinformatics-base-count delete mode 120000 Lang/ARM-Assembly/Bioinformatics-base-count delete mode 120000 Lang/ARM-Assembly/Miller-Rabin-primality-test delete mode 120000 Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/ATS/Quaternion-type delete mode 120000 Lang/AWK/Bioinformatics-base-count delete mode 120000 Lang/Action-/Bioinformatics-base-count delete mode 120000 Lang/Action-/Quaternion-type delete mode 120000 Lang/Action-/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Ada/Bioinformatics-base-count delete mode 120000 Lang/Ada/Miller-Rabin-primality-test delete mode 120000 Lang/Ada/Quaternion-type delete mode 120000 Lang/Agena/100-doors delete mode 120000 Lang/Arturo/Bioinformatics-base-count delete mode 120000 Lang/Arturo/Meissel-Mertens-constant delete mode 120000 Lang/Arturo/Quaternion-type delete mode 120000 Lang/Arturo/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Asymptote/Empty-program delete mode 120000 Lang/AutoHotkey/Miller-Rabin-primality-test delete mode 120000 Lang/AutoHotkey/Quaternion-type delete mode 120000 Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Axiom/Quaternion-type delete mode 120000 Lang/BASIC/Abundant-deficient-and-perfect-number-classifications delete mode 120000 Lang/BASIC/Ethiopian-multiplication delete mode 120000 Lang/BASIC/Mayan-numerals delete mode 120000 Lang/BASIC256/Empty-program delete mode 120000 Lang/BASIC256/Meissel-Mertens-constant delete mode 120000 Lang/BASIC256/Quaternion-type delete mode 120000 Lang/BBC-BASIC/Bioinformatics-base-count delete mode 120000 Lang/BBC-BASIC/Quaternion-type delete mode 120000 Lang/BQN/Miller-Rabin-primality-test delete mode 120000 Lang/Batch-File/Input-loop delete mode 120000 Lang/Bc/Miller-Rabin-primality-test delete mode 120000 Lang/BootBASIC/Empty-program delete mode 120000 Lang/Bracmat/Miller-Rabin-primality-test delete mode 120000 Lang/C++/Bioinformatics-base-count delete mode 120000 Lang/C++/Meissel-Mertens-constant delete mode 120000 Lang/C++/Miller-Rabin-primality-test delete mode 120000 Lang/C++/Quaternion-type delete mode 120000 Lang/C++/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/C-sharp/Miller-Rabin-primality-test delete mode 120000 Lang/C-sharp/Quaternion-type delete mode 120000 Lang/C-sharp/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/C/Bioinformatics-base-count delete mode 120000 Lang/C/Miller-Rabin-primality-test delete mode 120000 Lang/C/Quaternion-type delete mode 120000 Lang/C/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/CLU/Quaternion-type delete mode 120000 Lang/Clojure/Miller-Rabin-primality-test delete mode 120000 Lang/CoffeeScript/Empty-program delete mode 120000 Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Commodore-BASIC/Miller-Rabin-primality-test delete mode 120000 Lang/Common-Lisp/Miller-Rabin-primality-test delete mode 120000 Lang/Common-Lisp/Quaternion-type delete mode 120000 Lang/Coq/100-doors delete mode 120000 Lang/Coq/Ackermann-function delete mode 120000 Lang/Coq/Extend-your-language delete mode 120000 Lang/Coq/Factorial delete mode 120000 Lang/Coq/Fibonacci-sequence delete mode 120000 Lang/Coq/FizzBuzz delete mode 120000 Lang/Coq/Hello-world-Newbie delete mode 120000 Lang/Coq/Hello-world-Text delete mode 120000 Lang/Coq/Loops-For delete mode 120000 Lang/Coq/Tree-traversal delete mode 120000 Lang/Coq/Variadic-function delete mode 120000 Lang/Crystal/Empty-program delete mode 120000 Lang/Crystal/Miller-Rabin-primality-test delete mode 120000 Lang/Crystal/Quaternion-type delete mode 120000 Lang/Crystal/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/D/Miller-Rabin-primality-test delete mode 120000 Lang/D/Quaternion-type delete mode 120000 Lang/D/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Dart/Meissel-Mertens-constant delete mode 120000 Lang/Dart/Quaternion-type delete mode 120000 Lang/Delphi/Bioinformatics-base-count delete mode 120000 Lang/Delphi/Meissel-Mertens-constant delete mode 120000 Lang/Delphi/Quaternion-type delete mode 120000 Lang/Delphi/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/DuckDB/Bioinformatics-base-count delete mode 120000 Lang/E/Miller-Rabin-primality-test delete mode 120000 Lang/E/Quaternion-type delete mode 120000 Lang/ERRE/Quaternion-type delete mode 120000 Lang/EasyLang/Bioinformatics-base-count delete mode 120000 Lang/EasyLang/Meissel-Mertens-constant delete mode 120000 Lang/EasyLang/Quaternion-type delete mode 120000 Lang/EasyLang/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/EchoLisp/Miller-Rabin-primality-test delete mode 120000 Lang/Ed/Bioinformatics-base-count delete mode 120000 Lang/Eero/Quaternion-type delete mode 120000 Lang/Elena/Quaternion-type delete mode 120000 Lang/Elixir/Empty-program delete mode 120000 Lang/Elixir/Miller-Rabin-primality-test delete mode 120000 Lang/Elixir/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Erlang/Miller-Rabin-primality-test delete mode 120000 Lang/Euphoria/Empty-program delete mode 120000 Lang/Euphoria/Quaternion-type delete mode 120000 Lang/F-Sharp/Miller-Rabin-primality-test delete mode 120000 Lang/F-Sharp/Quaternion-type delete mode 120000 Lang/FALSE/Empty-program delete mode 120000 Lang/Factor/Bioinformatics-base-count delete mode 120000 Lang/Factor/Quaternion-type delete mode 120000 Lang/Forth/Bioinformatics-base-count delete mode 120000 Lang/Forth/Miller-Rabin-primality-test delete mode 120000 Lang/Forth/Quaternion-type delete mode 120000 Lang/Forth/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Fortran/Miller-Rabin-primality-test delete mode 120000 Lang/Fortran/Quaternion-type delete mode 120000 Lang/Fortran/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/FreeBASIC/Bioinformatics-base-count delete mode 120000 Lang/FreeBASIC/Meissel-Mertens-constant delete mode 120000 Lang/FreeBASIC/Miller-Rabin-primality-test delete mode 120000 Lang/FreeBASIC/Quaternion-type delete mode 120000 Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/FunL/Miller-Rabin-primality-test delete mode 120000 Lang/FutureBasic/Bioinformatics-base-count delete mode 120000 Lang/FutureBasic/Knights-tour delete mode 120000 Lang/GAP/Quaternion-type delete mode 120000 Lang/Go/Bioinformatics-base-count delete mode 120000 Lang/Go/Meissel-Mertens-constant delete mode 120000 Lang/Go/Miller-Rabin-primality-test delete mode 120000 Lang/Go/Quaternion-type delete mode 120000 Lang/Go/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Groovy/Empty-program delete mode 120000 Lang/Haskell/Bioinformatics-base-count delete mode 120000 Lang/Haskell/Miller-Rabin-primality-test delete mode 120000 Lang/Haskell/Quaternion-type delete mode 120000 Lang/Haskell/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Icon/Miller-Rabin-primality-test delete mode 120000 Lang/Idris/Quaternion-type delete mode 120000 Lang/J/Bioinformatics-base-count delete mode 120000 Lang/J/Meissel-Mertens-constant delete mode 120000 Lang/J/Quaternion-type delete mode 120000 Lang/J/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Java/Bioinformatics-base-count delete mode 120000 Lang/Java/Meissel-Mertens-constant delete mode 120000 Lang/Java/Miller-Rabin-primality-test delete mode 120000 Lang/Java/Quaternion-type delete mode 120000 Lang/Java/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/JavaScript/Bioinformatics-base-count delete mode 120000 Lang/JavaScript/Meissel-Mertens-constant delete mode 120000 Lang/JavaScript/Miller-Rabin-primality-test delete mode 120000 Lang/JavaScript/Quaternion-type delete mode 120000 Lang/Jq/Bioinformatics-base-count delete mode 120000 Lang/Jq/Quaternion-type delete mode 120000 Lang/Jq/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Julia/Bioinformatics-base-count delete mode 120000 Lang/Julia/Meissel-Mertens-constant delete mode 120000 Lang/Julia/Miller-Rabin-primality-test delete mode 120000 Lang/Julia/Quaternion-type delete mode 120000 Lang/Julia/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/K/Empty-program delete mode 120000 Lang/Kotlin/Bioinformatics-base-count delete mode 120000 Lang/Kotlin/Miller-Rabin-primality-test delete mode 120000 Lang/Kotlin/Quaternion-type delete mode 120000 Lang/Kotlin/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/LSE/Empty-program delete mode 120000 Lang/Lambdatalk/Bioinformatics-base-count delete mode 120000 Lang/Liberty-BASIC/Miller-Rabin-primality-test delete mode 120000 Lang/Liberty-BASIC/Quaternion-type delete mode 120000 Lang/Logo/Associative-array-Creation delete mode 120000 Lang/Lua/Bioinformatics-base-count delete mode 120000 Lang/Lua/Empty-program delete mode 120000 Lang/Lua/Miller-Rabin-primality-test delete mode 120000 Lang/Lua/Quaternion-type delete mode 120000 Lang/Lua/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/M2000-Interpreter/Bioinformatics-base-count delete mode 120000 Lang/M2000-Interpreter/Miller-Rabin-primality-test delete mode 120000 Lang/M2000-Interpreter/Quaternion-type delete mode 120000 Lang/M4/Empty-program delete mode 120000 Lang/MATLAB/Bioinformatics-base-count delete mode 120000 Lang/ML-I/Empty-program delete mode 120000 Lang/Maple/Empty-program delete mode 120000 Lang/Maple/Quaternion-type delete mode 120000 Lang/Mathematica/Bioinformatics-base-count delete mode 120000 Lang/Mathematica/Empty-program delete mode 120000 Lang/Mathematica/Meissel-Mertens-constant delete mode 120000 Lang/Mathematica/Miller-Rabin-primality-test delete mode 120000 Lang/Mathematica/Quaternion-type delete mode 120000 Lang/Mathematica/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Maxima/Meissel-Mertens-constant delete mode 120000 Lang/Maxima/Miller-Rabin-primality-test delete mode 120000 Lang/MelonBasic/Empty-program delete mode 120000 Lang/Mercury/Miller-Rabin-primality-test delete mode 120000 Lang/Mercury/Quaternion-type delete mode 120000 Lang/MiniScript/Empty-program delete mode 120000 Lang/Modula-3/Comments delete mode 120000 Lang/NS-HUBASIC/Empty-program delete mode 120000 Lang/Nim/Bioinformatics-base-count delete mode 120000 Lang/Nim/Meissel-Mertens-constant delete mode 120000 Lang/Nim/Miller-Rabin-primality-test delete mode 120000 Lang/Nim/Quaternion-type delete mode 120000 Lang/Nim/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/OCaml/Quaternion-type delete mode 120000 Lang/Oberon/Even-or-odd delete mode 120000 Lang/Oberon/Loops-For-with-a-specified-step delete mode 120000 Lang/Objeck/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Octave/Quaternion-type delete mode 120000 Lang/Oforth/Quaternion-type delete mode 120000 Lang/Ol/Quaternion-type delete mode 120000 Lang/OoRexx/Quaternion-type delete mode 120000 Lang/Openscad/Empty-program delete mode 120000 Lang/Oz/Miller-Rabin-primality-test delete mode 120000 Lang/PARI-GP/Empty-program delete mode 120000 Lang/PARI-GP/Meissel-Mertens-constant delete mode 120000 Lang/PARI-GP/Miller-Rabin-primality-test delete mode 120000 Lang/PARI-GP/Quaternion-type delete mode 120000 Lang/PARI-GP/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/PHP/Miller-Rabin-primality-test delete mode 120000 Lang/PL-I/Quaternion-type delete mode 120000 Lang/Pascal/Bell-numbers delete mode 120000 Lang/Pascal/Bioinformatics-base-count delete mode 120000 Lang/Pascal/Brazilian-numbers delete mode 120000 Lang/Pascal/Ethiopian-multiplication delete mode 120000 Lang/Pascal/Gamma-function delete mode 120000 Lang/Pascal/Leap-year delete mode 120000 Lang/Pascal/Prime-decomposition delete mode 120000 Lang/Pascal/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Pascal/Square-free-integers delete mode 120000 Lang/PascalABC.NET/Bioinformatics-base-count delete mode 120000 Lang/PascalABC.NET/Meissel-Mertens-constant delete mode 120000 Lang/PascalABC.NET/Miller-Rabin-primality-test delete mode 120000 Lang/Perl/Bioinformatics-base-count delete mode 120000 Lang/Perl/Meissel-Mertens-constant delete mode 120000 Lang/Perl/Miller-Rabin-primality-test delete mode 120000 Lang/Perl/Quaternion-type delete mode 120000 Lang/Perl/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Phix/Bioinformatics-base-count delete mode 120000 Lang/Phix/Meissel-Mertens-constant delete mode 120000 Lang/Phix/Miller-Rabin-primality-test delete mode 120000 Lang/Phix/Quaternion-type delete mode 120000 Lang/Phix/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Picat/Bioinformatics-base-count delete mode 120000 Lang/Picat/Quaternion-type delete mode 120000 Lang/PicoLisp/Bioinformatics-base-count delete mode 120000 Lang/PicoLisp/Miller-Rabin-primality-test delete mode 120000 Lang/PicoLisp/Quaternion-type delete mode 120000 Lang/Pike/Miller-Rabin-primality-test delete mode 120000 Lang/PowerShell/Quaternion-type delete mode 120000 Lang/Prolog/Miller-Rabin-primality-test delete mode 120000 Lang/Prolog/Quaternion-type delete mode 120000 Lang/PureBasic/Bioinformatics-base-count delete mode 120000 Lang/PureBasic/Meissel-Mertens-constant delete mode 120000 Lang/PureBasic/Miller-Rabin-primality-test delete mode 120000 Lang/PureBasic/Quaternion-type delete mode 120000 Lang/Python/Bioinformatics-base-count delete mode 120000 Lang/Python/Meissel-Mertens-constant delete mode 120000 Lang/Python/Miller-Rabin-primality-test delete mode 120000 Lang/Python/Quaternion-type delete mode 120000 Lang/Python/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/QBasic/Repeat-a-string delete mode 120000 Lang/Quackery/Bioinformatics-base-count delete mode 120000 Lang/Quackery/Miller-Rabin-primality-test delete mode 120000 Lang/Quackery/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Quite-BASIC/Empty-program delete mode 120000 Lang/R/Bioinformatics-base-count delete mode 120000 Lang/R/Quaternion-type delete mode 100644 Lang/REBOL/00-LANG.txt delete mode 100644 Lang/REBOL/00-META.yaml delete mode 120000 Lang/REBOL/100-doors delete mode 120000 Lang/REBOL/15-puzzle-game delete mode 120000 Lang/REBOL/9-billion-names-of-God-the-integer delete mode 120000 Lang/REBOL/99-bottles-of-beer delete mode 120000 Lang/REBOL/A+B delete mode 120000 Lang/REBOL/Abstract-type delete mode 120000 Lang/REBOL/Accumulator-factory delete mode 120000 Lang/REBOL/Ackermann-function delete mode 120000 Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime delete mode 120000 Lang/REBOL/Align-columns delete mode 120000 Lang/REBOL/Amicable-pairs delete mode 120000 Lang/REBOL/Animation delete mode 120000 Lang/REBOL/Anonymous-recursion delete mode 120000 Lang/REBOL/Apply-a-callback-to-an-array delete mode 120000 Lang/REBOL/Arithmetic-Integer delete mode 120000 Lang/REBOL/Array-concatenation delete mode 120000 Lang/REBOL/Array-length delete mode 120000 Lang/REBOL/Arrays delete mode 120000 Lang/REBOL/Averages-Arithmetic-mean delete mode 120000 Lang/REBOL/Averages-Median delete mode 120000 Lang/REBOL/Calendar delete mode 120000 Lang/REBOL/Check-that-file-exists delete mode 120000 Lang/REBOL/Classes delete mode 120000 Lang/REBOL/Comma-quibbling delete mode 120000 Lang/REBOL/Comments delete mode 120000 Lang/REBOL/Copy-a-string delete mode 120000 Lang/REBOL/Create-a-file delete mode 120000 Lang/REBOL/Date-format delete mode 120000 Lang/REBOL/Date-manipulation delete mode 120000 Lang/REBOL/Day-of-the-week delete mode 120000 Lang/REBOL/Delete-a-file delete mode 120000 Lang/REBOL/Detect-division-by-zero delete mode 120000 Lang/REBOL/Determine-if-a-string-is-numeric delete mode 120000 Lang/REBOL/Documentation delete mode 120000 Lang/REBOL/Dot-product delete mode 120000 Lang/REBOL/Dynamic-variable-names delete mode 120000 Lang/REBOL/Echo-server delete mode 120000 Lang/REBOL/Empty-program delete mode 120000 Lang/REBOL/Environment-variables delete mode 120000 Lang/REBOL/Execute-Brain- delete mode 120000 Lang/REBOL/Execute-a-system-command delete mode 120000 Lang/REBOL/FTP delete mode 120000 Lang/REBOL/Factorial delete mode 120000 Lang/REBOL/File-input-output delete mode 120000 Lang/REBOL/File-size delete mode 120000 Lang/REBOL/Filter delete mode 120000 Lang/REBOL/Find-the-last-Sunday-of-each-month delete mode 120000 Lang/REBOL/First-class-functions delete mode 120000 Lang/REBOL/Fixed-length-records delete mode 120000 Lang/REBOL/FizzBuzz delete mode 120000 Lang/REBOL/Flatten-a-list delete mode 120000 Lang/REBOL/Flow-control-structures delete mode 120000 Lang/REBOL/Formatted-numeric-output delete mode 120000 Lang/REBOL/Function-composition delete mode 120000 Lang/REBOL/Function-definition delete mode 120000 Lang/REBOL/Generic-swap delete mode 120000 Lang/REBOL/Greatest-common-divisor delete mode 120000 Lang/REBOL/Greatest-element-of-a-list delete mode 120000 Lang/REBOL/HTTP delete mode 120000 Lang/REBOL/Hailstone-sequence delete mode 120000 Lang/REBOL/Hello-world-Graphical delete mode 120000 Lang/REBOL/Hello-world-Newline-omission delete mode 120000 Lang/REBOL/Hello-world-Text delete mode 120000 Lang/REBOL/Higher-order-functions delete mode 120000 Lang/REBOL/Horners-rule-for-polynomial-evaluation delete mode 120000 Lang/REBOL/Hostname delete mode 120000 Lang/REBOL/Increment-a-numerical-string delete mode 120000 Lang/REBOL/Inheritance-Single delete mode 120000 Lang/REBOL/Input-loop delete mode 120000 Lang/REBOL/Integer-comparison delete mode 120000 Lang/REBOL/Interactive-programming-repl- delete mode 120000 Lang/REBOL/JSON delete mode 120000 Lang/REBOL/Josephus-problem delete mode 120000 Lang/REBOL/Keyboard-macros delete mode 120000 Lang/REBOL/Knuth-shuffle delete mode 120000 Lang/REBOL/Last-Friday-of-each-month delete mode 120000 Lang/REBOL/Leap-year delete mode 120000 Lang/REBOL/Literals-Integer delete mode 120000 Lang/REBOL/Logical-operations delete mode 120000 Lang/REBOL/Loop-over-multiple-arrays-simultaneously delete mode 120000 Lang/REBOL/Loops-Break delete mode 120000 Lang/REBOL/Loops-Continue delete mode 120000 Lang/REBOL/Loops-Do-while delete mode 120000 Lang/REBOL/Loops-Downward-for delete mode 120000 Lang/REBOL/Loops-For delete mode 120000 Lang/REBOL/Loops-For-with-a-specified-step delete mode 120000 Lang/REBOL/Loops-Foreach delete mode 120000 Lang/REBOL/Loops-Increment-loop-index-within-loop-body delete mode 120000 Lang/REBOL/Loops-Infinite delete mode 120000 Lang/REBOL/Loops-N-plus-one-half delete mode 120000 Lang/REBOL/Loops-Nested delete mode 120000 Lang/REBOL/Loops-While delete mode 120000 Lang/REBOL/Loops-With-multiple-ranges delete mode 120000 Lang/REBOL/Loops-Wrong-ranges delete mode 120000 Lang/REBOL/MD5 delete mode 120000 Lang/REBOL/Mad-Libs delete mode 120000 Lang/REBOL/Menu delete mode 120000 Lang/REBOL/Multiplication-tables delete mode 120000 Lang/REBOL/Mutual-recursion delete mode 120000 Lang/REBOL/Null-object delete mode 120000 Lang/REBOL/Number-reversal-game delete mode 120000 Lang/REBOL/Object-serialization delete mode 120000 Lang/REBOL/Palindrome-detection delete mode 120000 Lang/REBOL/Percentage-difference-between-images delete mode 120000 Lang/REBOL/Perfect-numbers delete mode 120000 Lang/REBOL/Polyspiral delete mode 120000 Lang/REBOL/Primality-by-trial-division delete mode 120000 Lang/REBOL/Program-termination delete mode 120000 Lang/REBOL/Queue-Definition delete mode 120000 Lang/REBOL/Queue-Usage delete mode 120000 Lang/REBOL/Quine delete mode 120000 Lang/REBOL/Read-a-specific-line-from-a-file delete mode 120000 Lang/REBOL/Read-entire-file delete mode 120000 Lang/REBOL/Regular-expressions delete mode 120000 Lang/REBOL/Remove-duplicate-elements delete mode 120000 Lang/REBOL/Rename-a-file delete mode 120000 Lang/REBOL/Repeat-a-string delete mode 120000 Lang/REBOL/Reverse-a-string delete mode 120000 Lang/REBOL/Rot-13 delete mode 120000 Lang/REBOL/Runtime-evaluation delete mode 120000 Lang/REBOL/Runtime-evaluation-In-an-environment delete mode 120000 Lang/REBOL/SHA-1 delete mode 120000 Lang/REBOL/SHA-256 delete mode 120000 Lang/REBOL/Search-a-list delete mode 120000 Lang/REBOL/Semordnilap delete mode 120000 Lang/REBOL/Send-email delete mode 120000 Lang/REBOL/Shell-one-liner delete mode 120000 Lang/REBOL/Simple-database delete mode 120000 Lang/REBOL/Simple-windowed-application delete mode 120000 Lang/REBOL/Sleep delete mode 120000 Lang/REBOL/Sort-an-integer-array delete mode 120000 Lang/REBOL/Sort-stability delete mode 120000 Lang/REBOL/Sorting-algorithms-Insertion-sort delete mode 120000 Lang/REBOL/Stack delete mode 120000 Lang/REBOL/Stair-climbing-puzzle delete mode 120000 Lang/REBOL/String-case delete mode 120000 Lang/REBOL/String-concatenation delete mode 120000 Lang/REBOL/String-interpolation-included- delete mode 120000 Lang/REBOL/String-length delete mode 120000 Lang/REBOL/Substring delete mode 120000 Lang/REBOL/Sum-and-product-of-an-array delete mode 120000 Lang/REBOL/Symmetric-difference delete mode 120000 Lang/REBOL/System-time delete mode 120000 Lang/REBOL/Take-notes-on-the-command-line delete mode 120000 Lang/REBOL/Tokenize-a-string delete mode 120000 Lang/REBOL/Towers-of-Hanoi delete mode 120000 Lang/REBOL/Tree-traversal delete mode 120000 Lang/REBOL/Trigonometric-functions delete mode 120000 Lang/REBOL/User-input-Graphical delete mode 120000 Lang/REBOL/User-input-Text delete mode 120000 Lang/REBOL/Variadic-function delete mode 120000 Lang/REBOL/Web-scraping delete mode 120000 Lang/REBOL/Window-creation delete mode 120000 Lang/REBOL/XML-Input delete mode 120000 Lang/REBOL/Y-combinator delete mode 120000 Lang/REXX/Bioinformatics-base-count delete mode 120000 Lang/REXX/Meissel-Mertens-constant delete mode 120000 Lang/REXX/Miller-Rabin-primality-test delete mode 120000 Lang/REXX/Quaternion-type delete mode 120000 Lang/REXX/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Racket/Bioinformatics-base-count delete mode 120000 Lang/Racket/Miller-Rabin-primality-test delete mode 120000 Lang/Racket/Quaternion-type delete mode 120000 Lang/Racket/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Raku/Bioinformatics-base-count delete mode 120000 Lang/Raku/Meissel-Mertens-constant delete mode 120000 Lang/Raku/Miller-Rabin-primality-test delete mode 120000 Lang/Raku/Quaternion-type delete mode 120000 Lang/Raku/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/RapidQ/M-bius-function delete mode 120000 Lang/Red/Quaternion-type delete mode 120000 Lang/Ring/Bioinformatics-base-count delete mode 120000 Lang/Ring/Empty-program delete mode 120000 Lang/Ring/Miller-Rabin-primality-test delete mode 120000 Lang/Ring/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Robotic/Empty-program delete mode 120000 Lang/Ruby/Bioinformatics-base-count delete mode 120000 Lang/Ruby/Miller-Rabin-primality-test delete mode 120000 Lang/Ruby/Quaternion-type delete mode 120000 Lang/Ruby/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Run-BASIC/Meissel-Mertens-constant delete mode 120000 Lang/Run-BASIC/Miller-Rabin-primality-test delete mode 120000 Lang/Rust/Bioinformatics-base-count delete mode 120000 Lang/Rust/Meissel-Mertens-constant delete mode 120000 Lang/Rust/Miller-Rabin-primality-test delete mode 120000 Lang/Rust/Quaternion-type delete mode 120000 Lang/Rust/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Scala/Miller-Rabin-primality-test delete mode 120000 Lang/Scala/Quaternion-type delete mode 120000 Lang/Scala/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Scheme/Empty-program delete mode 120000 Lang/Scheme/Miller-Rabin-primality-test delete mode 120000 Lang/Scilab/Empty-program delete mode 120000 Lang/Seed7/Miller-Rabin-primality-test delete mode 120000 Lang/Seed7/Quaternion-type delete mode 120000 Lang/Set-lang/Empty-program delete mode 120000 Lang/Sidef/Empty-program delete mode 120000 Lang/Sidef/Meissel-Mertens-constant delete mode 120000 Lang/Sidef/Miller-Rabin-primality-test delete mode 120000 Lang/Sidef/Quaternion-type delete mode 120000 Lang/Sidef/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/SimpleCode/Empty-program delete mode 120000 Lang/Slate/Empty-program delete mode 120000 Lang/Smalltalk/Miller-Rabin-primality-test delete mode 120000 Lang/Sparkling/Empty-program delete mode 120000 Lang/Standard-ML/Miller-Rabin-primality-test delete mode 120000 Lang/Swift/Bioinformatics-base-count delete mode 120000 Lang/Swift/Empty-program delete mode 120000 Lang/Swift/Miller-Rabin-primality-test delete mode 120000 Lang/Swift/Quaternion-type delete mode 120000 Lang/Swift/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Symsyn/Empty-program delete mode 120000 Lang/Tcl/Bioinformatics-base-count delete mode 120000 Lang/Tcl/Miller-Rabin-primality-test delete mode 120000 Lang/Tcl/Quaternion-type delete mode 120000 Lang/Trith/Empty-program delete mode 120000 Lang/True-BASIC/Meissel-Mertens-constant delete mode 120000 Lang/Uxntal/Bioinformatics-base-count delete mode 120000 Lang/V-(Vlang)/Bioinformatics-base-count delete mode 120000 Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/VBA/Quaternion-type delete mode 120000 Lang/VBScript/Bioinformatics-base-count delete mode 120000 Lang/Visual-Basic-.NET/Quaternion-type delete mode 120000 Lang/Wee-Basic/Empty-program delete mode 120000 Lang/Wren/Bioinformatics-base-count delete mode 120000 Lang/Wren/Empty-program delete mode 120000 Lang/Wren/Meissel-Mertens-constant delete mode 120000 Lang/Wren/Miller-Rabin-primality-test delete mode 120000 Lang/Wren/Quaternion-type delete mode 120000 Lang/Wren/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/X86-64-Assembly/Miller-Rabin-primality-test delete mode 120000 Lang/XPL0/Bioinformatics-base-count delete mode 120000 Lang/XPL0/Meissel-Mertens-constant delete mode 120000 Lang/XPL0/Quaternion-type delete mode 120000 Lang/XPL0/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Yabasic/Empty-program delete mode 120000 Lang/Yabasic/Meissel-Mertens-constant delete mode 120000 Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort delete mode 120000 Lang/Zkl/Bioinformatics-base-count delete mode 120000 Lang/Zkl/Miller-Rabin-primality-test delete mode 120000 Lang/Zkl/Quaternion-type delete mode 120000 Lang/Zkl/Sorting-Algorithms-Circle-Sort delete mode 100644 Task/100-doors/Ada/100-doors-1.ada delete mode 100644 Task/100-doors/Ada/100-doors-2.ada delete mode 100644 Task/100-doors/Agena/100-doors.agena delete mode 100644 Task/100-doors/AutoIt/100-doors.autoit delete mode 100644 Task/100-doors/AutoLISP/100-doors.l delete mode 100644 Task/100-doors/COBOL/100-doors.cobol delete mode 100644 Task/100-doors/Coq/100-doors-1.coq delete mode 100644 Task/100-doors/Coq/100-doors-2.coq delete mode 100644 Task/100-doors/Coq/100-doors-3.coq delete mode 100644 Task/100-doors/Coq/100-doors-4.coq delete mode 100644 Task/100-doors/Emacs-Lisp/100-doors-1.l delete mode 100644 Task/100-doors/Emacs-Lisp/100-doors-2.l delete mode 100644 Task/100-doors/Euphoria/100-doors.ex delete mode 100644 Task/100-doors/Haxe/100-doors-1.haxe delete mode 100644 Task/100-doors/Haxe/100-doors-2.haxe delete mode 100644 Task/100-doors/PowerShell/100-doors-1.psh delete mode 100644 Task/100-doors/PowerShell/100-doors-2.psh delete mode 100644 Task/100-doors/PowerShell/100-doors-3.psh delete mode 100644 Task/100-doors/PowerShell/100-doors-4.psh delete mode 100644 Task/100-doors/PowerShell/100-doors-5.psh delete mode 100644 Task/100-doors/PowerShell/100-doors-6.psh delete mode 100644 Task/100-doors/PowerShell/100-doors-7.psh delete mode 100644 Task/100-doors/REBOL/100-doors-1.rebol delete mode 100644 Task/100-doors/REBOL/100-doors-2.rebol delete mode 100644 Task/100-doors/REBOL/100-doors-3.rebol delete mode 100644 Task/100-doors/VBScript/100-doors.vb delete mode 100644 Task/100-doors/VHDL/100-doors-1.vhdl delete mode 100644 Task/100-doors/VHDL/100-doors-2.vhdl delete mode 100644 Task/100-prisoners/Ada/100-prisoners-1.ada delete mode 100644 Task/100-prisoners/Ada/100-prisoners-2.ada delete mode 100644 Task/100-prisoners/Ada/100-prisoners-3.ada delete mode 100644 Task/100-prisoners/PowerShell/100-prisoners.psh delete mode 100644 Task/100-prisoners/VBScript/100-prisoners.vb delete mode 100644 Task/15-puzzle-game/Ada/15-puzzle-game-1.ada delete mode 100644 Task/15-puzzle-game/Ada/15-puzzle-game-2.ada delete mode 100644 Task/15-puzzle-game/Ada/15-puzzle-game-3.ada delete mode 100644 Task/15-puzzle-game/Ada/15-puzzle-game-4.ada delete mode 100644 Task/15-puzzle-game/COBOL/15-puzzle-game.cobol delete mode 100644 Task/15-puzzle-game/PowerShell/15-puzzle-game.psh delete mode 100644 Task/15-puzzle-game/REBOL/15-puzzle-game.rebol delete mode 100644 Task/15-puzzle-game/VBScript/15-puzzle-game.vb delete mode 100644 Task/15-puzzle-solver/Ada/15-puzzle-solver.ada delete mode 100644 Task/2048/Ada/2048.ada delete mode 100644 Task/21-game/Ada/21-game.ada delete mode 100644 Task/24-game-Solve/COBOL/24-game-solve.cobol delete mode 100644 Task/24-game/Ada/24-game.ada delete mode 100644 Task/24-game/AutoIt/24-game.autoit delete mode 100644 Task/24-game/COBOL/24-game.cobol delete mode 100644 Task/24-game/PowerShell/24-game.psh delete mode 100644 Task/4-rings-or-4-squares-puzzle/Ada/4-rings-or-4-squares-puzzle.ada delete mode 100644 Task/9-billion-names-of-God-the-integer/Ada/9-billion-names-of-god-the-integer.ada delete mode 100644 Task/9-billion-names-of-God-the-integer/REBOL/9-billion-names-of-god-the-integer.rebol delete mode 100644 Task/99-bottles-of-beer/Ada/99-bottles-of-beer-1.ada delete mode 100644 Task/99-bottles-of-beer/Ada/99-bottles-of-beer-2.ada delete mode 100644 Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-1.cobol delete mode 100644 Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-2.cobol delete mode 100644 Task/99-bottles-of-beer/COBOL/99-bottles-of-beer-3.cobol delete mode 100644 Task/99-bottles-of-beer/Chapel/99-bottles-of-beer.chapel delete mode 100644 Task/99-bottles-of-beer/Emacs-Lisp/99-bottles-of-beer.l delete mode 100644 Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-1.ex delete mode 100644 Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-2.ex delete mode 100644 Task/99-bottles-of-beer/Euphoria/99-bottles-of-beer-3.ex delete mode 100644 Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-1.haxe delete mode 100644 Task/99-bottles-of-beer/Haxe/99-bottles-of-beer-2.haxe delete mode 100644 Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-1.rebol delete mode 100644 Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-2.rebol delete mode 100644 Task/99-bottles-of-beer/REBOL/99-bottles-of-beer-3.rebol delete mode 100644 Task/A+B/Ada/a+b-1.ada delete mode 100644 Task/A+B/Ada/a+b-2.ada delete mode 100644 Task/A+B/AutoIt/a+b-1.autoit delete mode 100644 Task/A+B/AutoIt/a+b-2.autoit delete mode 100644 Task/A+B/COBOL/a+b-1.cobol delete mode 100644 Task/A+B/COBOL/a+b-2.cobol delete mode 100644 Task/A+B/Emacs-Lisp/a+b.l delete mode 100644 Task/A+B/Euphoria/a+b.ex delete mode 100644 Task/A+B/PowerShell/a+b-1.psh delete mode 100644 Task/A+B/PowerShell/a+b-2.psh delete mode 100644 Task/A+B/PowerShell/a+b-3.psh delete mode 100644 Task/A+B/PowerShell/a+b-4.psh delete mode 100644 Task/A+B/REBOL/a+b.rebol delete mode 100644 Task/A+B/VBScript/a+b-1.vb delete mode 100644 Task/A+B/VBScript/a+b-2.vb delete mode 100644 Task/A+B/VHDL/a+b.vhdl delete mode 100644 Task/ABC-problem/Ada/abc-problem.ada delete mode 100644 Task/ABC-problem/Euphoria/abc-problem.ex delete mode 100644 Task/ABC-problem/PowerShell/abc-problem.psh delete mode 100644 Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada delete mode 100644 Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.psh delete mode 100644 Task/AVL-tree/Ada/avl-tree.ada delete mode 100644 Task/AVL-tree/Emacs-Lisp/avl-tree.l delete mode 100644 Task/Abbreviations-automatic/Ada/abbreviations-automatic.ada delete mode 100644 Task/Abbreviations-automatic/COBOL/abbreviations-automatic.cobol delete mode 100644 Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.l delete mode 100644 Task/Abbreviations-automatic/VBScript/abbreviations-automatic.vb delete mode 100644 Task/Abbreviations-easy/Ada/abbreviations-easy.ada delete mode 100644 Task/Abbreviations-easy/Euphoria/abbreviations-easy.ex delete mode 100644 Task/Abbreviations-easy/PowerShell/abbreviations-easy.psh delete mode 100644 Task/Abbreviations-simple/Ada/abbreviations-simple.ada delete mode 100644 Task/Abbreviations-simple/VBScript/abbreviations-simple.vb delete mode 100644 Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-1.ada delete mode 100644 Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-2.ada delete mode 100644 Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-3.ada delete mode 100644 Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.ada delete mode 100644 Task/Abstract-type/Ada/abstract-type-1.ada delete mode 100644 Task/Abstract-type/Ada/abstract-type-2.ada delete mode 100644 Task/Abstract-type/Ada/abstract-type-3.ada delete mode 100644 Task/Abstract-type/COBOL/abstract-type.cobol delete mode 100644 Task/Abstract-type/Haxe/abstract-type-1.haxe delete mode 100644 Task/Abstract-type/Haxe/abstract-type-2.haxe delete mode 100644 Task/Abstract-type/PowerShell/abstract-type-1.psh delete mode 100644 Task/Abstract-type/PowerShell/abstract-type-2.psh delete mode 100644 Task/Abstract-type/PowerShell/abstract-type-3.psh delete mode 100644 Task/Abstract-type/PowerShell/abstract-type-4.psh delete mode 100644 Task/Abstract-type/PowerShell/abstract-type-5.psh delete mode 100644 Task/Abstract-type/REBOL/abstract-type.rebol delete mode 100644 Task/Abstract-type/ReScript/abstract-type.re delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Ada/abundant-deficient-and-perfect-number-classifications.ada delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/BASIC/abundant-deficient-and-perfect-number-classifications.basic delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-1.psh delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-2.psh delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-3.psh delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/VBScript/abundant-deficient-and-perfect-number-classifications.vb delete mode 100644 Task/Abundant-odd-numbers/Ada/abundant-odd-numbers.ada delete mode 100644 Task/Accumulator-factory/Ada/accumulator-factory-1.ada delete mode 100644 Task/Accumulator-factory/Ada/accumulator-factory-2.ada delete mode 100644 Task/Accumulator-factory/Ada/accumulator-factory-3.ada delete mode 100644 Task/Accumulator-factory/PowerShell/accumulator-factory-1.psh delete mode 100644 Task/Accumulator-factory/PowerShell/accumulator-factory-2.psh delete mode 100644 Task/Accumulator-factory/REBOL/accumulator-factory-1.rebol delete mode 100644 Task/Accumulator-factory/REBOL/accumulator-factory-2.rebol delete mode 100644 Task/Accumulator-factory/VBScript/accumulator-factory-1.vb delete mode 100644 Task/Accumulator-factory/VBScript/accumulator-factory-2.vb delete mode 100644 Task/Achilles-numbers/Ada/achilles-numbers.ada delete mode 100644 Task/Ackermann-function/Ada/ackermann-function.ada delete mode 100644 Task/Ackermann-function/AutoIt/ackermann-function-1.autoit delete mode 100644 Task/Ackermann-function/AutoIt/ackermann-function-2.autoit delete mode 100644 Task/Ackermann-function/COBOL/ackermann-function.cobol delete mode 100644 Task/Ackermann-function/Chapel/ackermann-function.chapel delete mode 100644 Task/Ackermann-function/Coq/ackermann-function-1.coq delete mode 100644 Task/Ackermann-function/Coq/ackermann-function-2.coq delete mode 100644 Task/Ackermann-function/Emacs-Lisp/ackermann-function.l delete mode 100644 Task/Ackermann-function/Euphoria/ackermann-function.ex delete mode 100644 Task/Ackermann-function/Haxe/ackermann-function.haxe delete mode 100644 Task/Ackermann-function/PowerShell/ackermann-function-1.psh delete mode 100644 Task/Ackermann-function/PowerShell/ackermann-function-2.psh delete mode 100644 Task/Ackermann-function/PowerShell/ackermann-function-3.psh delete mode 100644 Task/Ackermann-function/PowerShell/ackermann-function-4.psh delete mode 100644 Task/Ackermann-function/REBOL/ackermann-function-1.rebol delete mode 100644 Task/Ackermann-function/REBOL/ackermann-function-2.rebol delete mode 100644 Task/Ackermann-function/REXX/ackermann-function-1.rexx delete mode 100644 Task/Ackermann-function/REXX/ackermann-function-2.rexx delete mode 100644 Task/Ackermann-function/REXX/ackermann-function-3.rexx delete mode 100644 Task/Ackermann-function/ReScript/ackermann-function.re delete mode 100644 Task/Ackermann-function/VBScript/ackermann-function-1.vb delete mode 100644 Task/Ackermann-function/VBScript/ackermann-function-2.vb delete mode 100644 Task/Active-Directory-Connect/AutoIt/active-directory-connect.autoit delete mode 100644 Task/Active-Directory-Connect/VBScript/active-directory-connect.vb delete mode 100644 Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh delete mode 100644 Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vb delete mode 100644 Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vb delete mode 100644 Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vb delete mode 100644 Task/Active-object/Ada/active-object.ada delete mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.ada delete mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/PowerShell/add-a-variable-to-a-class-instance-at-runtime.psh delete mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL/add-a-variable-to-a-class-instance-at-runtime.rebol delete mode 100644 Task/Additive-primes/Ada/additive-primes.ada delete mode 100644 Task/Additive-primes/COBOL/additive-primes.cobol delete mode 100644 Task/Address-of-a-variable/Ada/address-of-a-variable-1.ada delete mode 100644 Task/Address-of-a-variable/Ada/address-of-a-variable-2.ada delete mode 100644 Task/Address-of-a-variable/Ada/address-of-a-variable-3.ada delete mode 100644 Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cobol delete mode 100644 Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cobol delete mode 100644 Task/Algebraic-data-types/Emacs-Lisp/algebraic-data-types.l delete mode 100644 Task/Align-columns/Ada/align-columns.ada delete mode 100644 Task/Align-columns/AutoIt/align-columns.autoit delete mode 100644 Task/Align-columns/COBOL/align-columns-1.cobol delete mode 100644 Task/Align-columns/COBOL/align-columns-2.cobol delete mode 100644 Task/Align-columns/Emacs-Lisp/align-columns.l delete mode 100644 Task/Align-columns/Euphoria/align-columns.ex delete mode 100644 Task/Align-columns/PowerShell/align-columns.psh delete mode 100644 Task/Align-columns/REBOL/align-columns.rebol delete mode 100644 Task/Align-columns/VBScript/align-columns.vb delete mode 100644 Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-1.psh delete mode 100644 Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-2.psh delete mode 100644 Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.psh delete mode 100644 Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.psh delete mode 100644 Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.ada delete mode 100644 Task/Almost-prime/Ada/almost-prime.ada delete mode 100644 Task/Almost-prime/COBOL/almost-prime.cobol delete mode 100644 Task/Almost-prime/VBScript/almost-prime.vb delete mode 100644 Task/Amb/Ada/amb-1.ada delete mode 100644 Task/Amb/Ada/amb-2.ada delete mode 100644 Task/Amb/Haxe/amb.haxe delete mode 100644 Task/Amb/VBScript/amb-1.vb delete mode 100644 Task/Amb/VBScript/amb-2.vb delete mode 100644 Task/Amicable-pairs/Ada/amicable-pairs.ada delete mode 100644 Task/Amicable-pairs/MATLAB/amicable-pairs.m delete mode 100644 Task/Amicable-pairs/PowerShell/amicable-pairs.psh delete mode 100644 Task/Amicable-pairs/REBOL/amicable-pairs.rebol delete mode 100644 Task/Amicable-pairs/ReScript/amicable-pairs.re delete mode 100644 Task/Amicable-pairs/VBScript/amicable-pairs.vb delete mode 100644 Task/Anagrams-Deranged-anagrams/Ada/anagrams-deranged-anagrams.ada delete mode 100644 Task/Anagrams-Deranged-anagrams/COBOL/anagrams-deranged-anagrams.cobol delete mode 100644 Task/Anagrams-Deranged-anagrams/PowerShell/anagrams-deranged-anagrams.psh delete mode 100644 Task/Anagrams/Ada/anagrams.ada delete mode 100644 Task/Anagrams/COBOL/anagrams.cobol delete mode 100644 Task/Anagrams/Emacs-Lisp/anagrams-1.l delete mode 100644 Task/Anagrams/Emacs-Lisp/anagrams-2.l delete mode 100644 Task/Anagrams/Euphoria/anagrams.ex delete mode 100644 Task/Anagrams/PowerShell/anagrams-1.psh delete mode 100644 Task/Anagrams/PowerShell/anagrams-2.psh delete mode 100644 Task/Anagrams/VBScript/anagrams.vb delete mode 100644 Task/Angle-difference-between-two-bearings/Ada/angle-difference-between-two-bearings.ada delete mode 100644 Task/Angle-difference-between-two-bearings/COBOL/angle-difference-between-two-bearings.cobol delete mode 100644 Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-1.psh delete mode 100644 Task/Angle-difference-between-two-bearings/PowerShell/angle-difference-between-two-bearings-2.psh delete mode 100644 Task/Angles-geometric-normalization-and-conversion/Ada/angles-geometric-normalization-and-conversion.ada delete mode 100644 Task/Animate-a-pendulum/Ada/animate-a-pendulum-1.ada delete mode 100644 Task/Animate-a-pendulum/Ada/animate-a-pendulum-2.ada delete mode 100644 Task/Animate-a-pendulum/Ada/animate-a-pendulum-3.ada delete mode 100644 Task/Animate-a-pendulum/Euphoria/animate-a-pendulum.ex delete mode 100644 Task/Animate-a-pendulum/VBScript/animate-a-pendulum.vb delete mode 100644 Task/Animation/Ada/animation.ada delete mode 100644 Task/Animation/Emacs-Lisp/animation.l delete mode 100644 Task/Animation/REBOL/animation.rebol delete mode 100644 Task/Anonymous-recursion/Ada/anonymous-recursion.ada delete mode 100644 Task/Anonymous-recursion/AutoIt/anonymous-recursion.autoit delete mode 100644 Task/Anonymous-recursion/REBOL/anonymous-recursion.rebol delete mode 100644 Task/Anti-primes/Ada/anti-primes.ada delete mode 100644 Task/Anti-primes/COBOL/anti-primes.cobol delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Ada/append-a-record-to-the-end-of-a-text-file.ada delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/COBOL/append-a-record-to-the-end-of-a-text-file.cobol delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-1.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-2.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-3.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-4.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-5.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-6.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-7.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-8.psh delete mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PowerShell/append-a-record-to-the-end-of-a-text-file-9.psh delete mode 100644 Task/Apply-a-callback-to-an-array/Ada/apply-a-callback-to-an-array.ada delete mode 100644 Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat delete mode 100644 Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol delete mode 100644 Task/Apply-a-callback-to-an-array/Euphoria/apply-a-callback-to-an-array.ex delete mode 100644 Task/Apply-a-callback-to-an-array/Haxe/apply-a-callback-to-an-array.haxe delete mode 100644 Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-1.psh delete mode 100644 Task/Apply-a-callback-to-an-array/PowerShell/apply-a-callback-to-an-array-2.psh delete mode 100644 Task/Apply-a-callback-to-an-array/REBOL/apply-a-callback-to-an-array.rebol delete mode 100644 Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-1.vb delete mode 100644 Task/Apply-a-callback-to-an-array/VBScript/apply-a-callback-to-an-array-2.vb delete mode 100644 Task/Apply-a-digital-filter-direct-form-II-transposed-/Ada/apply-a-digital-filter-direct-form-ii-transposed-.ada delete mode 100644 Task/Approximate-equality/Ada/approximate-equality.ada delete mode 100644 Task/Approximate-equality/ReScript/approximate-equality.re delete mode 100644 Task/Arbitrary-precision-integers-included-/Ada/arbitrary-precision-integers-included-.ada delete mode 100644 Task/Arbitrary-precision-integers-included-/COBOL/arbitrary-precision-integers-included-.cobol delete mode 100644 Task/Arbitrary-precision-integers-included-/Emacs-Lisp/arbitrary-precision-integers-included--1.l delete mode 100644 Task/Arbitrary-precision-integers-included-/Emacs-Lisp/arbitrary-precision-integers-included--2.l delete mode 100644 Task/Arbitrary-precision-integers-included-/PowerShell/arbitrary-precision-integers-included-.psh delete mode 100644 Task/Arbitrary-precision-integers-included-/REXX/arbitrary-precision-integers-included--1.rexx delete mode 100644 Task/Arbitrary-precision-integers-included-/REXX/arbitrary-precision-integers-included--2.rexx delete mode 100644 Task/Arbitrary-precision-integers-included-/Tcl/arbitrary-precision-integers-included-.tcl delete mode 100644 Task/Archimedean-spiral/Ada/archimedean-spiral.ada delete mode 100644 Task/Arena-storage-pool/Ada/arena-storage-pool-1.ada delete mode 100644 Task/Arena-storage-pool/Ada/arena-storage-pool-2.ada delete mode 100644 Task/Arena-storage-pool/Ada/arena-storage-pool-3.ada delete mode 100644 Task/Arena-storage-pool/Ada/arena-storage-pool-4.ada delete mode 100644 Task/Arithmetic-Complex/Ada/arithmetic-complex.ada delete mode 100644 Task/Arithmetic-Complex/COBOL/arithmetic-complex-1.cobol delete mode 100644 Task/Arithmetic-Complex/COBOL/arithmetic-complex-2.cobol delete mode 100644 Task/Arithmetic-Complex/Euphoria/arithmetic-complex.ex delete mode 100644 Task/Arithmetic-Complex/PowerShell/arithmetic-complex-1.psh delete mode 100644 Task/Arithmetic-Complex/PowerShell/arithmetic-complex-2.psh delete mode 100644 Task/Arithmetic-Integer/Ada/arithmetic-integer.ada delete mode 100644 Task/Arithmetic-Integer/COBOL/arithmetic-integer.cobol delete mode 100644 Task/Arithmetic-Integer/Euphoria/arithmetic-integer.ex delete mode 100644 Task/Arithmetic-Integer/Haxe/arithmetic-integer.haxe delete mode 100644 Task/Arithmetic-Integer/PowerShell/arithmetic-integer-1.psh delete mode 100644 Task/Arithmetic-Integer/PowerShell/arithmetic-integer-2.psh delete mode 100644 Task/Arithmetic-Integer/REBOL/arithmetic-integer.rebol delete mode 100644 Task/Arithmetic-Integer/ReScript/arithmetic-integer.re delete mode 100644 Task/Arithmetic-Integer/VBScript/arithmetic-integer-1.vb delete mode 100644 Task/Arithmetic-Integer/VBScript/arithmetic-integer-2.vb delete mode 100644 Task/Arithmetic-derivative/Ada/arithmetic-derivative.ada delete mode 100644 Task/Arithmetic-evaluation/Emacs-Lisp/arithmetic-evaluation.l delete mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Ada/arithmetic-geometric-mean-calculate-pi.ada delete mode 100644 Task/Arithmetic-geometric-mean/Ada/arithmetic-geometric-mean.ada delete mode 100644 Task/Arithmetic-geometric-mean/COBOL/arithmetic-geometric-mean.cobol delete mode 100644 Task/Arithmetic-geometric-mean/PowerShell/arithmetic-geometric-mean.psh delete mode 100644 Task/Arithmetic-geometric-mean/VBScript/arithmetic-geometric-mean.vb delete mode 100644 Task/Arithmetic-numbers/Ada/arithmetic-numbers.ada delete mode 100644 Task/Arithmetic-numbers/VBScript/arithmetic-numbers.vb delete mode 100644 Task/Array-concatenation/Ada/array-concatenation.ada delete mode 100644 Task/Array-concatenation/AutoIt/array-concatenation.autoit delete mode 100644 Task/Array-concatenation/COBOL/array-concatenation.cobol delete mode 100644 Task/Array-concatenation/Emacs-Lisp/array-concatenation.l delete mode 100644 Task/Array-concatenation/Euphoria/array-concatenation.ex delete mode 100644 Task/Array-concatenation/PowerShell/array-concatenation.psh delete mode 100644 Task/Array-concatenation/REBOL/array-concatenation.rebol delete mode 100644 Task/Array-concatenation/ReScript/array-concatenation.re delete mode 100644 Task/Array-concatenation/VBScript/array-concatenation.vb delete mode 100644 Task/Array-length/Ada/array-length.ada delete mode 100644 Task/Array-length/AutoIt/array-length.autoit delete mode 100644 Task/Array-length/COBOL/array-length.cobol delete mode 100644 Task/Array-length/Emacs-Lisp/array-length.l delete mode 100644 Task/Array-length/Euphoria/array-length.ex delete mode 100644 Task/Array-length/PowerShell/array-length.psh delete mode 100644 Task/Array-length/REBOL/array-length.rebol delete mode 100644 Task/Array-length/ReScript/array-length-1.re delete mode 100644 Task/Array-length/ReScript/array-length-2.re delete mode 100644 Task/Array-length/VBScript/array-length.vb delete mode 100644 Task/Arrays/Ada/arrays.ada delete mode 100644 Task/Arrays/AutoIt/arrays.autoit delete mode 100644 Task/Arrays/COBOL/arrays.cobol delete mode 100644 Task/Arrays/Euphoria/arrays.ex delete mode 100644 Task/Arrays/Haxe/arrays.haxe delete mode 100644 Task/Arrays/PowerShell/arrays-1.psh delete mode 100644 Task/Arrays/PowerShell/arrays-2.psh delete mode 100644 Task/Arrays/PowerShell/arrays-3.psh delete mode 100644 Task/Arrays/PowerShell/arrays-4.psh delete mode 100644 Task/Arrays/PowerShell/arrays-5.psh delete mode 100644 Task/Arrays/PowerShell/arrays-6.psh delete mode 100644 Task/Arrays/PowerShell/arrays-7.psh delete mode 100644 Task/Arrays/PowerShell/arrays-8.psh delete mode 100644 Task/Arrays/PowerShell/arrays-9.psh delete mode 100644 Task/Arrays/REBOL/arrays-1.rebol delete mode 100644 Task/Arrays/REBOL/arrays-2.rebol delete mode 100644 Task/Arrays/REBOL/arrays-3.rebol delete mode 100644 Task/Arrays/REBOL/arrays-4.rebol delete mode 100644 Task/Arrays/ReScript/arrays.re delete mode 100644 Task/Arrays/VBScript/arrays.vb delete mode 100644 Task/Arrays/VHDL/arrays.vhdl delete mode 100644 Task/Ascending-primes/Ada/ascending-primes.ada delete mode 100644 Task/Assertions/Ada/assertions-1.ada delete mode 100644 Task/Assertions/Ada/assertions-2.ada delete mode 100644 Task/Assertions/Ada/assertions-3.ada delete mode 100644 Task/Assertions/Emacs-Lisp/assertions.l delete mode 100644 Task/Assertions/Euphoria/assertions.ex delete mode 100644 Task/Assertions/VBScript/assertions-1.vb delete mode 100644 Task/Assertions/VBScript/assertions-2.vb delete mode 100644 Task/Assertions/VBScript/assertions-3.vb delete mode 100644 Task/Associative-array-Creation/Ada/associative-array-creation.ada delete mode 100644 Task/Associative-array-Creation/AutoIt/associative-array-creation.autoit delete mode 100644 Task/Associative-array-Creation/Chapel/associative-array-creation.chapel delete mode 100644 Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-1.l delete mode 100644 Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-2.l delete mode 100644 Task/Associative-array-Creation/Haxe/associative-array-creation.haxe delete mode 100644 Task/Associative-array-Creation/Logo/associative-array-creation.logo delete mode 100644 Task/Associative-array-Creation/PowerShell/associative-array-creation-1.psh delete mode 100644 Task/Associative-array-Creation/PowerShell/associative-array-creation-2.psh delete mode 100644 Task/Associative-array-Creation/PowerShell/associative-array-creation-3.psh delete mode 100644 Task/Associative-array-Creation/PowerShell/associative-array-creation-4.psh delete mode 100644 Task/Associative-array-Creation/PowerShell/associative-array-creation-5.psh delete mode 100644 Task/Associative-array-Creation/PowerShell/associative-array-creation-6.psh delete mode 100644 Task/Associative-array-Iteration/Ada/associative-array-iteration.ada delete mode 100644 Task/Associative-array-Iteration/Chapel/associative-array-iteration.chapel delete mode 100644 Task/Associative-array-Iteration/Haxe/associative-array-iteration.haxe delete mode 100644 Task/Associative-array-Iteration/PowerShell/associative-array-iteration-1.psh delete mode 100644 Task/Associative-array-Iteration/PowerShell/associative-array-iteration-2.psh delete mode 100644 Task/Associative-array-Iteration/PowerShell/associative-array-iteration-3.psh delete mode 100644 Task/Associative-array-Iteration/PowerShell/associative-array-iteration-4.psh delete mode 100644 Task/Associative-array-Iteration/PowerShell/associative-array-iteration-5.psh delete mode 100644 Task/Associative-array-Iteration/VBScript/associative-array-iteration.vb delete mode 100644 Task/Associative-array-Merging/Ada/associative-array-merging.ada delete mode 100644 Task/Associative-array-Merging/Tcl/associative-array-merging.tcl delete mode 100644 Task/Associative-array-Merging/VBScript/associative-array-merging.vb delete mode 100644 Task/Atomic-updates/Ada/atomic-updates.ada delete mode 100644 Task/Atomic-updates/Euphoria/atomic-updates.ex delete mode 100644 Task/Attractive-numbers/Ada/attractive-numbers.ada delete mode 100644 Task/Attractive-numbers/COBOL/attractive-numbers.cobol delete mode 100644 Task/Average-loop-length/Ada/average-loop-length.ada delete mode 100644 Task/Average-loop-length/PowerShell/average-loop-length-1.psh delete mode 100644 Task/Average-loop-length/PowerShell/average-loop-length-2.psh delete mode 100644 Task/Average-loop-length/VBScript/average-loop-length.vb delete mode 100644 Task/Averages-Arithmetic-mean/Ada/averages-arithmetic-mean.ada delete mode 100644 Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cobol delete mode 100644 Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cobol delete mode 100644 Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-1.l delete mode 100644 Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.l delete mode 100644 Task/Averages-Arithmetic-mean/Euphoria/averages-arithmetic-mean.ex delete mode 100644 Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-1.psh delete mode 100644 Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-2.psh delete mode 100644 Task/Averages-Arithmetic-mean/REBOL/averages-arithmetic-mean.rebol delete mode 100644 Task/Averages-Arithmetic-mean/ReScript/averages-arithmetic-mean.re delete mode 100644 Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vb delete mode 100644 Task/Averages-Mean-angle/Ada/averages-mean-angle.ada delete mode 100644 Task/Averages-Mean-angle/Euphoria/averages-mean-angle.ex delete mode 100644 Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.psh delete mode 100644 Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.psh delete mode 100644 Task/Averages-Mean-angle/Scheme/averages-mean-angle.scm delete mode 100644 Task/Averages-Mean-time-of-day/Ada/averages-mean-time-of-day.ada delete mode 100644 Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.ex delete mode 100644 Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-1.psh delete mode 100644 Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-2.psh delete mode 100644 Task/Averages-Median/Ada/averages-median.ada delete mode 100644 Task/Averages-Median/COBOL/averages-median.cobol delete mode 100644 Task/Averages-Median/Euphoria/averages-median.ex delete mode 100644 Task/Averages-Median/PowerShell/averages-median-1.psh delete mode 100644 Task/Averages-Median/PowerShell/averages-median-2.psh delete mode 100644 Task/Averages-Median/PowerShell/averages-median-3.psh delete mode 100644 Task/Averages-Median/REBOL/averages-median.rebol delete mode 100644 Task/Averages-Median/ReScript/averages-median.re delete mode 100644 Task/Averages-Mode/Ada/averages-mode-1.ada delete mode 100644 Task/Averages-Mode/Ada/averages-mode-2.ada delete mode 100644 Task/Averages-Mode/Ada/averages-mode-3.ada delete mode 100644 Task/Averages-Mode/Euphoria/averages-mode.ex delete mode 100644 Task/Averages-Mode/PowerShell/averages-mode.psh delete mode 100644 Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-1.ada delete mode 100644 Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-2.ada delete mode 100644 Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-3.ada delete mode 100644 Task/Averages-Pythagorean-means/Euphoria/averages-pythagorean-means.ex delete mode 100644 Task/Averages-Pythagorean-means/PowerShell/averages-pythagorean-means.psh delete mode 100644 Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vb delete mode 100644 Task/Averages-Root-mean-square/Ada/averages-root-mean-square.ada delete mode 100644 Task/Averages-Root-mean-square/COBOL/averages-root-mean-square.cobol delete mode 100644 Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square.l delete mode 100644 Task/Averages-Root-mean-square/Euphoria/averages-root-mean-square.ex delete mode 100644 Task/Averages-Root-mean-square/PowerShell/averages-root-mean-square.psh delete mode 100644 Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-1.ada delete mode 100644 Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-2.ada delete mode 100644 Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-3.ada delete mode 100644 Task/Averages-Simple-moving-average/Phix/averages-simple-moving-average-1.phix delete mode 100644 Task/Averages-Simple-moving-average/Phix/averages-simple-moving-average-2.phix delete mode 100644 Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.psh delete mode 100644 Task/Averages-Simple-moving-average/VBScript/averages-simple-moving-average.vb delete mode 100644 Task/B-zier-curves-Intersections/Ada/b-zier-curves-intersections.ada delete mode 100644 Task/Babbage-problem/Ada/babbage-problem.ada delete mode 100644 Task/Babbage-problem/AutoLISP/babbage-problem.l delete mode 100644 Task/Babbage-problem/COBOL/babbage-problem.cobol delete mode 100644 Task/Babbage-problem/PowerShell/babbage-problem-1.psh delete mode 100644 Task/Babbage-problem/PowerShell/babbage-problem-2.psh delete mode 100644 Task/Babbage-problem/VBScript/babbage-problem.vb delete mode 100644 Task/Babylonian-spiral/Ada/babylonian-spiral.ada delete mode 100644 Task/Balanced-brackets/Ada/balanced-brackets.ada delete mode 100644 Task/Balanced-brackets/AutoIt/balanced-brackets.autoit delete mode 100644 Task/Balanced-brackets/AutoLISP/balanced-brackets.l delete mode 100644 Task/Balanced-brackets/COBOL/balanced-brackets.cobol delete mode 100644 Task/Balanced-brackets/Euphoria/balanced-brackets.ex delete mode 100644 Task/Balanced-brackets/PowerShell/balanced-brackets-1.psh delete mode 100644 Task/Balanced-brackets/PowerShell/balanced-brackets-2.psh delete mode 100644 Task/Balanced-brackets/PowerShell/balanced-brackets-3.psh delete mode 100644 Task/Balanced-brackets/VBScript/balanced-brackets-1.vb delete mode 100644 Task/Balanced-brackets/VBScript/balanced-brackets-2.vb delete mode 100644 Task/Balanced-ternary/Ada/balanced-ternary-1.ada delete mode 100644 Task/Balanced-ternary/Ada/balanced-ternary-2.ada delete mode 100644 Task/Balanced-ternary/Ada/balanced-ternary-3.ada delete mode 100644 Task/Barnsley-fern/Ada/barnsley-fern.ada delete mode 100644 Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.l delete mode 100644 Task/Base64-decode-data/Ada/base64-decode-data.ada delete mode 100644 Task/Base64-decode-data/Haxe/base64-decode-data.haxe delete mode 100644 Task/Bell-numbers/Ada/bell-numbers.ada delete mode 100644 Task/Bell-numbers/Pascal/bell-numbers.pas delete mode 100644 Task/Benfords-law/Ada/benfords-law-1.ada delete mode 100644 Task/Benfords-law/Ada/benfords-law-2.ada delete mode 100644 Task/Benfords-law/PowerShell/benfords-law.psh delete mode 100644 Task/Bernoulli-numbers/Ada/bernoulli-numbers.ada delete mode 100644 Task/Best-shuffle/Ada/best-shuffle.ada delete mode 100644 Task/Best-shuffle/PowerShell/best-shuffle-1.psh delete mode 100644 Task/Best-shuffle/PowerShell/best-shuffle-2.psh delete mode 100644 Task/Best-shuffle/VBScript/best-shuffle.vb delete mode 100644 Task/Bifid-cipher/Ada/bifid-cipher.ada delete mode 100644 Task/Bin-given-limits/Ada/bin-given-limits-1.ada delete mode 100644 Task/Bin-given-limits/Ada/bin-given-limits-2.ada delete mode 100644 Task/Bin-given-limits/Ada/bin-given-limits-3.ada delete mode 100644 Task/Binary-digits/Ada/binary-digits.ada delete mode 100644 Task/Binary-digits/AutoIt/binary-digits.autoit delete mode 100644 Task/Binary-digits/C++/binary-digits-3.cpp delete mode 100644 Task/Binary-digits/C++/binary-digits-4.cpp delete mode 100644 Task/Binary-digits/C++/binary-digits-5.cpp delete mode 100644 Task/Binary-digits/COBOL/binary-digits-1.cobol delete mode 100644 Task/Binary-digits/COBOL/binary-digits-2.cobol delete mode 100644 Task/Binary-digits/Emacs-Lisp/binary-digits.l delete mode 100644 Task/Binary-digits/Euphoria/binary-digits-1.ex delete mode 100644 Task/Binary-digits/Euphoria/binary-digits-2.ex delete mode 100644 Task/Binary-digits/Haxe/binary-digits.haxe delete mode 100644 Task/Binary-digits/PowerShell/binary-digits.psh delete mode 100644 Task/Binary-digits/REXX/binary-digits-1.rexx delete mode 100644 Task/Binary-digits/REXX/binary-digits-2.rexx delete mode 100644 Task/Binary-digits/REXX/binary-digits-3.rexx delete mode 100644 Task/Binary-digits/REXX/binary-digits-4.rexx delete mode 100644 Task/Binary-digits/VBScript/binary-digits.vb delete mode 100644 Task/Binary-search/Ada/binary-search-1.ada delete mode 100644 Task/Binary-search/Ada/binary-search-2.ada delete mode 100644 Task/Binary-search/COBOL/binary-search.cobol delete mode 100644 Task/Binary-search/Chapel/binary-search.chapel delete mode 100644 Task/Binary-search/Emacs-Lisp/binary-search.l delete mode 100644 Task/Binary-search/Euphoria/binary-search-1.ex delete mode 100644 Task/Binary-search/Euphoria/binary-search-2.ex delete mode 100644 Task/Binary-search/PowerShell/binary-search-1.psh delete mode 100644 Task/Binary-search/PowerShell/binary-search-2.psh delete mode 100644 Task/Binary-search/VBScript/binary-search.vb delete mode 100644 Task/Binary-strings/Ada/binary-strings-1.ada delete mode 100644 Task/Binary-strings/Ada/binary-strings-2.ada delete mode 100644 Task/Binary-strings/Ada/binary-strings-3.ada delete mode 100644 Task/Binary-strings/PowerShell/binary-strings.psh delete mode 100644 Task/Bioinformatics-Sequence-mutation/Ada/bioinformatics-sequence-mutation.ada delete mode 100644 Task/Bioinformatics-base-count/11l/bioinformatics-base-count.11l delete mode 100644 Task/Bioinformatics-base-count/AArch64-Assembly/bioinformatics-base-count.aarch64 delete mode 100644 Task/Bioinformatics-base-count/ALGOL-68/bioinformatics-base-count.alg delete mode 100644 Task/Bioinformatics-base-count/APL/bioinformatics-base-count.apl delete mode 100644 Task/Bioinformatics-base-count/ARM-Assembly/bioinformatics-base-count.arm delete mode 100644 Task/Bioinformatics-base-count/AWK/bioinformatics-base-count.awk delete mode 100644 Task/Bioinformatics-base-count/Action-/bioinformatics-base-count.action delete mode 100644 Task/Bioinformatics-base-count/Ada/bioinformatics-base-count.ada delete mode 100644 Task/Bioinformatics-base-count/Arturo/bioinformatics-base-count-1.arturo delete mode 100644 Task/Bioinformatics-base-count/Arturo/bioinformatics-base-count-2.arturo delete mode 100644 Task/Bioinformatics-base-count/BBC-BASIC/bioinformatics-base-count.basic delete mode 100644 Task/Bioinformatics-base-count/C++/bioinformatics-base-count.cpp delete mode 100644 Task/Bioinformatics-base-count/C/bioinformatics-base-count.c delete mode 100644 Task/Bioinformatics-base-count/Delphi/bioinformatics-base-count.pas delete mode 100644 Task/Bioinformatics-base-count/DuckDB/bioinformatics-base-count.duckdb delete mode 100644 Task/Bioinformatics-base-count/EasyLang/bioinformatics-base-count.easy delete mode 100644 Task/Bioinformatics-base-count/Ed/bioinformatics-base-count.ed delete mode 100644 Task/Bioinformatics-base-count/Factor/bioinformatics-base-count.factor delete mode 100644 Task/Bioinformatics-base-count/Forth/bioinformatics-base-count.fth delete mode 100644 Task/Bioinformatics-base-count/FreeBASIC/bioinformatics-base-count.basic delete mode 100644 Task/Bioinformatics-base-count/FutureBasic/bioinformatics-base-count.basic delete mode 100644 Task/Bioinformatics-base-count/Go/bioinformatics-base-count.go delete mode 100644 Task/Bioinformatics-base-count/Haskell/bioinformatics-base-count.hs delete mode 100644 Task/Bioinformatics-base-count/J/bioinformatics-base-count-1.j delete mode 100644 Task/Bioinformatics-base-count/J/bioinformatics-base-count-2.j delete mode 100644 Task/Bioinformatics-base-count/Java/bioinformatics-base-count-1.java delete mode 100644 Task/Bioinformatics-base-count/Java/bioinformatics-base-count-2.java delete mode 100644 Task/Bioinformatics-base-count/JavaScript/bioinformatics-base-count.js delete mode 100644 Task/Bioinformatics-base-count/Jq/bioinformatics-base-count-1.jq delete mode 100644 Task/Bioinformatics-base-count/Jq/bioinformatics-base-count-2.jq delete mode 100644 Task/Bioinformatics-base-count/Jq/bioinformatics-base-count-3.jq delete mode 100644 Task/Bioinformatics-base-count/Jq/bioinformatics-base-count-4.jq delete mode 100644 Task/Bioinformatics-base-count/Jq/bioinformatics-base-count-5.jq delete mode 100644 Task/Bioinformatics-base-count/Jq/bioinformatics-base-count-6.jq delete mode 100644 Task/Bioinformatics-base-count/Julia/bioinformatics-base-count.jl delete mode 100644 Task/Bioinformatics-base-count/Kotlin/bioinformatics-base-count.kts delete mode 100644 Task/Bioinformatics-base-count/Lambdatalk/bioinformatics-base-count.lambdatalk delete mode 100644 Task/Bioinformatics-base-count/Lua/bioinformatics-base-count.lua delete mode 100644 Task/Bioinformatics-base-count/M2000-Interpreter/bioinformatics-base-count.m2000 delete mode 100644 Task/Bioinformatics-base-count/MATLAB/bioinformatics-base-count.m delete mode 100644 Task/Bioinformatics-base-count/Mathematica/bioinformatics-base-count.math delete mode 100644 Task/Bioinformatics-base-count/Nim/bioinformatics-base-count.nim delete mode 100644 Task/Bioinformatics-base-count/Pascal/bioinformatics-base-count-1.pas delete mode 100644 Task/Bioinformatics-base-count/Pascal/bioinformatics-base-count-2.pas delete mode 100644 Task/Bioinformatics-base-count/PascalABC.NET/bioinformatics-base-count.pas delete mode 100644 Task/Bioinformatics-base-count/Perl/bioinformatics-base-count.pl delete mode 100644 Task/Bioinformatics-base-count/Phix/bioinformatics-base-count.phix delete mode 100644 Task/Bioinformatics-base-count/Picat/bioinformatics-base-count.picat delete mode 100644 Task/Bioinformatics-base-count/PicoLisp/bioinformatics-base-count.l delete mode 100644 Task/Bioinformatics-base-count/PureBasic/bioinformatics-base-count.basic delete mode 100644 Task/Bioinformatics-base-count/Python/bioinformatics-base-count-1.py delete mode 100644 Task/Bioinformatics-base-count/Python/bioinformatics-base-count-2.py delete mode 100644 Task/Bioinformatics-base-count/Python/bioinformatics-base-count-3.py delete mode 100644 Task/Bioinformatics-base-count/Quackery/bioinformatics-base-count.quackery delete mode 100644 Task/Bioinformatics-base-count/R/bioinformatics-base-count.r delete mode 100644 Task/Bioinformatics-base-count/REXX/bioinformatics-base-count.rexx delete mode 100644 Task/Bioinformatics-base-count/Racket/bioinformatics-base-count.rkt delete mode 100644 Task/Bioinformatics-base-count/Raku/bioinformatics-base-count.raku delete mode 100644 Task/Bioinformatics-base-count/Ring/bioinformatics-base-count.ring delete mode 100644 Task/Bioinformatics-base-count/Ruby/bioinformatics-base-count.rb delete mode 100644 Task/Bioinformatics-base-count/Rust/bioinformatics-base-count.rs delete mode 100644 Task/Bioinformatics-base-count/Swift/bioinformatics-base-count.swift delete mode 100644 Task/Bioinformatics-base-count/Tcl/bioinformatics-base-count.tcl delete mode 100644 Task/Bioinformatics-base-count/Uxntal/bioinformatics-base-count.uxnatl delete mode 100644 Task/Bioinformatics-base-count/V-(Vlang)/bioinformatics-base-count.v delete mode 100644 Task/Bioinformatics-base-count/VBScript/bioinformatics-base-count.vb delete mode 100644 Task/Bioinformatics-base-count/Wren/bioinformatics-base-count.wren delete mode 100644 Task/Bioinformatics-base-count/XPL0/bioinformatics-base-count.xpl0 delete mode 100644 Task/Bioinformatics-base-count/Zkl/bioinformatics-base-count.zkl delete mode 100644 Task/Biorhythms/Ada/biorhythms.ada delete mode 100644 Task/Biorhythms/COBOL/biorhythms-1.cobol delete mode 100644 Task/Biorhythms/COBOL/biorhythms-2.cobol delete mode 100644 Task/Biorhythms/Emacs-Lisp/biorhythms.l delete mode 100644 Task/Bitcoin-address-validation/Ada/bitcoin-address-validation.ada delete mode 100644 Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.ada delete mode 100644 Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.ada delete mode 100644 Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.ada delete mode 100644 Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.ada delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.ada delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.ada delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.autoit delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.ex delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm.pluto delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vb delete mode 100644 Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.ada delete mode 100644 Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.ada delete mode 100644 Task/Bitmap-Histogram/Ada/bitmap-histogram-1.ada delete mode 100644 Task/Bitmap-Histogram/Ada/bitmap-histogram-2.ada delete mode 100644 Task/Bitmap-Histogram/Ada/bitmap-histogram-3.ada delete mode 100644 Task/Bitmap-Midpoint-circle-algorithm/Ada/bitmap-midpoint-circle-algorithm-1.ada delete mode 100644 Task/Bitmap-Midpoint-circle-algorithm/Ada/bitmap-midpoint-circle-algorithm-2.ada delete mode 100644 Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm.pluto delete mode 100644 Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.ada delete mode 100644 Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.ada delete mode 100644 Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.ex delete mode 100644 Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.ex delete mode 100644 Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.ada delete mode 100644 Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.ex delete mode 100644 Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.ex delete mode 100644 Task/Bitmap/Ada/bitmap-1.ada delete mode 100644 Task/Bitmap/Ada/bitmap-2.ada delete mode 100644 Task/Bitmap/Ada/bitmap-3.ada delete mode 100644 Task/Bitmap/Crystal/bitmap.cr delete mode 100644 Task/Bitmap/Euphoria/bitmap.ex delete mode 100644 Task/Bitmap/Pluto/bitmap.pluto delete mode 100644 Task/Bitwise-IO/Ada/bitwise-io-1.ada delete mode 100644 Task/Bitwise-IO/Ada/bitwise-io-2.ada delete mode 100644 Task/Bitwise-IO/Ada/bitwise-io-3.ada delete mode 100644 Task/Bitwise-operations/Ada/bitwise-operations.ada delete mode 100644 Task/Bitwise-operations/AutoIt/bitwise-operations.autoit delete mode 100644 Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol delete mode 100644 Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol delete mode 100644 Task/Bitwise-operations/PowerShell/bitwise-operations-1.psh delete mode 100644 Task/Bitwise-operations/PowerShell/bitwise-operations-2.psh delete mode 100644 Task/Blum-integer/Ada/blum-integer.ada delete mode 100644 Task/Boolean-values/Ada/boolean-values.ada delete mode 100644 Task/Boolean-values/COBOL/boolean-values-1.cobol delete mode 100644 Task/Boolean-values/COBOL/boolean-values-2.cobol delete mode 100644 Task/Boolean-values/COBOL/boolean-values-3.cobol delete mode 100644 Task/Boolean-values/Haxe/boolean-values.haxe delete mode 100644 Task/Boolean-values/PowerShell/boolean-values.psh delete mode 100644 Task/Boolean-values/VBScript/boolean-values.vb delete mode 100644 Task/Box-the-compass/Ada/box-the-compass.ada delete mode 100644 Task/Box-the-compass/AutoIt/box-the-compass.autoit delete mode 100644 Task/Box-the-compass/COBOL/box-the-compass.cobol delete mode 100644 Task/Box-the-compass/Euphoria/box-the-compass.ex delete mode 100644 Task/Box-the-compass/PowerShell/box-the-compass-1.psh delete mode 100644 Task/Box-the-compass/PowerShell/box-the-compass-2.psh delete mode 100644 Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.ada delete mode 100644 Task/Boyer-Moore-string-search/Emacs-Lisp/boyer-moore-string-search.l delete mode 100644 Task/Brace-expansion/Ada/brace-expansion.ada delete mode 100644 Task/Brace-expansion/PowerShell/brace-expansion-1.psh delete mode 100644 Task/Brace-expansion/PowerShell/brace-expansion-2.psh delete mode 100644 Task/Brazilian-numbers/Pascal/brazilian-numbers.pas delete mode 100644 Task/Break-OO-privacy/Ada/break-oo-privacy-1.ada delete mode 100644 Task/Break-OO-privacy/Ada/break-oo-privacy-2.ada delete mode 100644 Task/Break-OO-privacy/Ada/break-oo-privacy-3.ada delete mode 100644 Task/Break-OO-privacy/Ada/break-oo-privacy-4.ada delete mode 100644 Task/Break-OO-privacy/Ada/break-oo-privacy-5.ada delete mode 100644 Task/Brilliant-numbers/Ada/brilliant-numbers.ada delete mode 100644 Task/Brownian-tree/Ada/brownian-tree.ada delete mode 100644 Task/Brownian-tree/Scheme/brownian-tree.scm delete mode 100644 Task/Bulls-and-cows-Player/Ada/bulls-and-cows-player.ada delete mode 100644 Task/Bulls-and-cows-Player/Euphoria/bulls-and-cows-player.ex delete mode 100644 Task/Bulls-and-cows/Ada/bulls-and-cows.ada delete mode 100644 Task/Bulls-and-cows/Emacs-Lisp/bulls-and-cows.l delete mode 100644 Task/Bulls-and-cows/Euphoria/bulls-and-cows.ex delete mode 100644 Task/Bulls-and-cows/K/bulls-and-cows.k delete mode 100644 Task/Bulls-and-cows/PowerShell/bulls-and-cows.psh delete mode 100644 Task/Bulls-and-cows/VBScript/bulls-and-cows.vb delete mode 100644 Task/CRC-32/Ada/crc-32.ada delete mode 100644 Task/CRC-32/COBOL/crc-32.cobol delete mode 100644 Task/CRC-32/Haxe/crc-32.haxe delete mode 100644 Task/CRC-32/VBScript/crc-32.vb delete mode 100644 Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.ada delete mode 100644 Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.ada delete mode 100644 Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.ada delete mode 100644 Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cobol delete mode 100644 Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.ex delete mode 100644 Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.psh delete mode 100644 Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb delete mode 100644 Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.ada delete mode 100644 Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.ada delete mode 100644 Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.ada delete mode 100644 Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.autoit delete mode 100644 Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.ex delete mode 100644 Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.ex delete mode 100644 Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.psh delete mode 100644 Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.psh delete mode 100644 Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.psh delete mode 100644 Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.psh delete mode 100644 Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb delete mode 100644 Task/CUSIP/Ada/cusip.ada delete mode 100644 Task/CUSIP/PowerShell/cusip.psh delete mode 100644 Task/Caesar-cipher/Ada/caesar-cipher.ada delete mode 100644 Task/Caesar-cipher/AutoIt/caesar-cipher.autoit delete mode 100644 Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol delete mode 100644 Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol delete mode 100644 Task/Caesar-cipher/Euphoria/caesar-cipher.ex delete mode 100644 Task/Caesar-cipher/PowerShell/caesar-cipher.psh delete mode 100644 Task/Caesar-cipher/VBScript/caesar-cipher.vb delete mode 100644 Task/Calculating-the-value-of-e/Ada/calculating-the-value-of-e.ada delete mode 100644 Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cobol delete mode 100644 Task/Calculating-the-value-of-e/Emacs-Lisp/calculating-the-value-of-e.l delete mode 100644 Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e.f delete mode 100644 Task/Calculating-the-value-of-e/PowerShell/calculating-the-value-of-e.psh delete mode 100644 Task/Calculating-the-value-of-e/VBScript/calculating-the-value-of-e.vb delete mode 100644 Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.ada delete mode 100644 Task/Calendar/Ada/calendar-1.ada delete mode 100644 Task/Calendar/Ada/calendar-2.ada delete mode 100644 Task/Calendar/Ada/calendar-3.ada delete mode 100644 Task/Calendar/AutoIt/calendar.autoit delete mode 100644 Task/Calendar/COBOL/calendar.cobol delete mode 100644 Task/Calendar/PowerShell/calendar.psh delete mode 100644 Task/Calendar/REBOL/calendar.rebol delete mode 100644 Task/Calendar/VBScript/calendar.vb delete mode 100644 Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.ada delete mode 100644 Task/Call-a-foreign-language-function/Ada/call-a-foreign-language-function.ada delete mode 100644 Task/Call-a-foreign-language-function/COBOL/call-a-foreign-language-function.cobol delete mode 100644 Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada delete mode 100644 Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-2.ada delete mode 100644 Task/Call-a-function-in-a-shared-library/COBOL/call-a-function-in-a-shared-library.cobol delete mode 100644 Task/Call-a-function/Ada/call-a-function-1.ada delete mode 100644 Task/Call-a-function/Ada/call-a-function-2.ada delete mode 100644 Task/Call-a-function/Ada/call-a-function-3.ada delete mode 100644 Task/Call-a-function/Ada/call-a-function-4.ada delete mode 100644 Task/Call-a-function/Ada/call-a-function-5.ada delete mode 100644 Task/Call-a-function/COBOL/call-a-function.cobol delete mode 100644 Task/Call-a-function/REXX/call-a-function-1.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-2.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-3.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-4.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-5.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-6.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-7.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-8.rexx delete mode 100644 Task/Call-a-function/REXX/call-a-function-9.rexx delete mode 100644 Task/Call-an-object-method/Ada/call-an-object-method-1.ada delete mode 100644 Task/Call-an-object-method/Ada/call-an-object-method-2.ada delete mode 100644 Task/Call-an-object-method/Ada/call-an-object-method-3.ada delete mode 100644 Task/Call-an-object-method/Ada/call-an-object-method-4.ada delete mode 100644 Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol delete mode 100644 Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol delete mode 100644 Task/Call-an-object-method/Haxe/call-an-object-method.haxe delete mode 100644 Task/Call-an-object-method/PowerShell/call-an-object-method.psh delete mode 100644 Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.ada delete mode 100644 Task/Canonicalize-CIDR/Ada/canonicalize-cidr.ada delete mode 100644 Task/Cantor-set/Ada/cantor-set.ada delete mode 100644 Task/Cantor-set/C/cantor-set.c delete mode 100644 Task/Cantor-set/COBOL/cantor-set.cobol delete mode 100644 Task/Carmichael-3-strong-pseudoprimes/Ada/carmichael-3-strong-pseudoprimes.ada delete mode 100644 Task/Cartesian-product-of-two-or-more-lists/Ada/cartesian-product-of-two-or-more-lists.ada delete mode 100644 Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.ada delete mode 100644 Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cobol delete mode 100644 Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.ex delete mode 100644 Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.psh delete mode 100644 Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.ada delete mode 100644 Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vb delete mode 100644 Task/Catalan-numbers/ALGOL-68/catalan-numbers.alg delete mode 100644 Task/Catalan-numbers/Ada/catalan-numbers.ada delete mode 100644 Task/Catalan-numbers/Euphoria/catalan-numbers.ex delete mode 100644 Task/Catalan-numbers/PowerShell/catalan-numbers-1.psh delete mode 100644 Task/Catalan-numbers/PowerShell/catalan-numbers-2.psh delete mode 100644 Task/Catalan-numbers/PowerShell/catalan-numbers-3.psh delete mode 100644 Task/Catalan-numbers/PowerShell/catalan-numbers-4.psh delete mode 100644 Task/Catalan-numbers/VBScript/catalan-numbers.vb delete mode 100644 Task/Catamorphism/Ada/catamorphism.ada delete mode 100644 Task/Catamorphism/PowerShell/catamorphism.psh delete mode 100644 Task/Catamorphism/Python/catamorphism-1.py delete mode 100644 Task/Catamorphism/Python/catamorphism-2.py delete mode 100644 Task/Chaocipher/Ada/chaocipher.ada delete mode 100644 Task/Chaos-game/Ada/chaos-game.ada delete mode 100644 Task/Chaos-game/Emacs-Lisp/chaos-game.l delete mode 100644 Task/Character-codes/Ada/character-codes.ada delete mode 100644 Task/Character-codes/COBOL/character-codes.cobol delete mode 100644 Task/Character-codes/Emacs-Lisp/character-codes.l delete mode 100644 Task/Character-codes/Euphoria/character-codes.ex delete mode 100644 Task/Character-codes/Haxe/character-codes.haxe delete mode 100644 Task/Character-codes/PowerShell/character-codes-1.psh delete mode 100644 Task/Character-codes/PowerShell/character-codes-2.psh delete mode 100644 Task/Character-codes/PowerShell/character-codes-3.psh delete mode 100644 Task/Character-codes/PowerShell/character-codes-4.psh delete mode 100644 Task/Character-codes/PowerShell/character-codes-5.psh delete mode 100644 Task/Character-codes/VBScript/character-codes.vb delete mode 100644 Task/Chat-server/Ada/chat-server.ada delete mode 100644 Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.ada delete mode 100644 Task/Check-input-device-is-a-terminal/COBOL/check-input-device-is-a-terminal.cobol delete mode 100644 Task/Check-output-device-is-a-terminal/Ada/check-output-device-is-a-terminal.ada delete mode 100644 Task/Check-output-device-is-a-terminal/COBOL/check-output-device-is-a-terminal.cobol delete mode 100644 Task/Check-that-file-exists/Ada/check-that-file-exists-1.ada delete mode 100644 Task/Check-that-file-exists/Ada/check-that-file-exists-2.ada delete mode 100644 Task/Check-that-file-exists/COBOL/check-that-file-exists.cobol delete mode 100644 Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.l delete mode 100644 Task/Check-that-file-exists/Euphoria/check-that-file-exists.ex delete mode 100644 Task/Check-that-file-exists/PowerShell/check-that-file-exists.psh delete mode 100644 Task/Check-that-file-exists/REBOL/check-that-file-exists.rebol delete mode 100644 Task/Check-that-file-exists/VBScript/check-that-file-exists.vb delete mode 100644 Task/Checkpoint-synchronization/Ada/checkpoint-synchronization.ada delete mode 100644 Task/Chernicks-Carmichael-numbers/Phix/chernicks-carmichael-numbers-1.phix delete mode 100644 Task/Chernicks-Carmichael-numbers/Phix/chernicks-carmichael-numbers-2.phix delete mode 100644 Task/Chinese-remainder-theorem/Ada/chinese-remainder-theorem.ada delete mode 100644 Task/Chinese-zodiac/Ada/chinese-zodiac.ada delete mode 100644 Task/Chinese-zodiac/C/chinese-zodiac.c delete mode 100644 Task/Chinese-zodiac/PowerShell/chinese-zodiac-1.psh delete mode 100644 Task/Chinese-zodiac/PowerShell/chinese-zodiac-2.psh delete mode 100644 Task/Chinese-zodiac/PowerShell/chinese-zodiac-3.psh delete mode 100644 Task/Chinese-zodiac/PowerShell/chinese-zodiac-4.psh delete mode 100644 Task/Chinese-zodiac/PowerShell/chinese-zodiac-5.psh delete mode 100644 Task/Chinese-zodiac/VBScript/chinese-zodiac.vb delete mode 100644 Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.ada delete mode 100644 Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.ada delete mode 100644 Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.ada delete mode 100644 Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.psh delete mode 100644 Task/Chowla-numbers/Ada/chowla-numbers.ada delete mode 100644 Task/Church-numerals/Chapel/church-numerals.chapel delete mode 100644 Task/Circular-primes/Free-Pascal-Lazarus/circular-primes.pas delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-1.ada delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-2.ada delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-3.ada delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-4.ada delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-5.ada delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-6.ada delete mode 100644 Task/Cistercian-numerals/Ada/cistercian-numerals-7.ada delete mode 100644 Task/Classes/Ada/classes-1.ada delete mode 100644 Task/Classes/Ada/classes-2.ada delete mode 100644 Task/Classes/Ada/classes-3.ada delete mode 100644 Task/Classes/COBOL/classes.cobol delete mode 100644 Task/Classes/Haxe/classes-1.haxe delete mode 100644 Task/Classes/Haxe/classes-2.haxe delete mode 100644 Task/Classes/PowerShell/classes-1.psh delete mode 100644 Task/Classes/PowerShell/classes-2.psh delete mode 100644 Task/Classes/PowerShell/classes-3.psh delete mode 100644 Task/Classes/PowerShell/classes-4.psh delete mode 100644 Task/Classes/REBOL/classes.rebol delete mode 100644 Task/Closest-pair-problem/Ada/closest-pair-problem.ada delete mode 100644 Task/Closures-Value-capture/Ada/closures-value-capture.ada delete mode 100644 Task/Closures-Value-capture/Emacs-Lisp/closures-value-capture.l delete mode 100644 Task/Closures-Value-capture/PowerShell/closures-value-capture-1.psh delete mode 100644 Task/Closures-Value-capture/PowerShell/closures-value-capture-2.psh delete mode 100644 Task/Closures-Value-capture/PowerShell/closures-value-capture-3.psh delete mode 100644 Task/Collections/Ada/collections-1.ada delete mode 100644 Task/Collections/Ada/collections-2.ada delete mode 100644 Task/Collections/Ada/collections-3.ada delete mode 100644 Task/Collections/Ada/collections-4.ada delete mode 100644 Task/Collections/Ada/collections-5.ada delete mode 100644 Task/Collections/COBOL/collections.cobol delete mode 100644 Task/Collections/PowerShell/collections-1.psh delete mode 100644 Task/Collections/PowerShell/collections-2.psh delete mode 100644 Task/Collections/PowerShell/collections-3.psh delete mode 100644 Task/Color-of-a-screen-pixel/AutoIt/color-of-a-screen-pixel.autoit delete mode 100644 Task/Color-wheel/Ada/color-wheel.ada delete mode 100644 Task/Color-wheel/Emacs-Lisp/color-wheel.l delete mode 100644 Task/Color-wheel/VBScript/color-wheel.vb delete mode 100644 Task/Colour-bars-Display/Ada/colour-bars-display.ada delete mode 100644 Task/Colour-bars-Display/COBOL/colour-bars-display.cobol delete mode 100644 Task/Colour-bars-Display/PowerShell/colour-bars-display.psh delete mode 100644 Task/Colour-pinstripe-Display/Ada/colour-pinstripe-display.ada delete mode 100644 Task/Colour-pinstripe-Printer/Ada/colour-pinstripe-printer.ada delete mode 100644 Task/Combinations-and-permutations/Ada/combinations-and-permutations.ada delete mode 100644 Task/Combinations-and-permutations/VBScript/combinations-and-permutations.vb delete mode 100644 Task/Combinations-with-repetitions/Ada/combinations-with-repetitions.ada delete mode 100644 Task/Combinations-with-repetitions/VBScript/combinations-with-repetitions.vb delete mode 100644 Task/Combinations/Ada/combinations-1.ada delete mode 100644 Task/Combinations/Ada/combinations-2.ada delete mode 100644 Task/Combinations/Emacs-Lisp/combinations.l delete mode 100644 Task/Combinations/PowerShell/combinations.psh delete mode 100644 Task/Combinations/VBScript/combinations.vb delete mode 100644 Task/Comma-quibbling/Ada/comma-quibbling.ada delete mode 100644 Task/Comma-quibbling/COBOL/comma-quibbling.cobol delete mode 100644 Task/Comma-quibbling/PowerShell/comma-quibbling-1.psh delete mode 100644 Task/Comma-quibbling/PowerShell/comma-quibbling-2.psh delete mode 100644 Task/Comma-quibbling/PowerShell/comma-quibbling-3.psh delete mode 100644 Task/Comma-quibbling/REBOL/comma-quibbling-1.rebol delete mode 100644 Task/Comma-quibbling/REBOL/comma-quibbling-2.rebol delete mode 100644 Task/Comma-quibbling/VBScript/comma-quibbling.vb delete mode 100644 Task/Command-line-arguments/Ada/command-line-arguments-1.ada delete mode 100644 Task/Command-line-arguments/Ada/command-line-arguments-2.ada delete mode 100644 Task/Command-line-arguments/COBOL/command-line-arguments-1.cobol delete mode 100644 Task/Command-line-arguments/COBOL/command-line-arguments-2.cobol delete mode 100644 Task/Command-line-arguments/COBOL/command-line-arguments-3.cobol delete mode 100644 Task/Command-line-arguments/Emacs-Lisp/command-line-arguments.l delete mode 100644 Task/Command-line-arguments/Euphoria/command-line-arguments.ex delete mode 100644 Task/Command-line-arguments/PowerShell/command-line-arguments.psh delete mode 100644 Task/Command-line-arguments/VBScript/command-line-arguments.vb delete mode 100644 Task/Commatizing-numbers/VBScript/commatizing-numbers.vb delete mode 100644 Task/Comments/Ada/comments.ada delete mode 100644 Task/Comments/AutoIt/comments.autoit delete mode 100644 Task/Comments/COBOL/comments-1.cobol delete mode 100644 Task/Comments/COBOL/comments-2.cobol delete mode 100644 Task/Comments/COBOL/comments-3.cobol delete mode 100644 Task/Comments/COBOL/comments-4.cobol delete mode 100644 Task/Comments/COBOL/comments-5.cobol delete mode 100644 Task/Comments/COBOL/comments-6.cobol delete mode 100644 Task/Comments/Chapel/comments.chapel delete mode 100644 Task/Comments/Emacs-Lisp/comments-1.l delete mode 100644 Task/Comments/Emacs-Lisp/comments-2.l delete mode 100644 Task/Comments/Emacs-Lisp/comments-3.l delete mode 100644 Task/Comments/Euphoria/comments-1.ex delete mode 100644 Task/Comments/Euphoria/comments-2.ex delete mode 100644 Task/Comments/Haxe/comments.haxe delete mode 100644 Task/Comments/Modula-3/comments.mod3 delete mode 100644 Task/Comments/PowerShell/comments-1.psh delete mode 100644 Task/Comments/PowerShell/comments-2.psh delete mode 100644 Task/Comments/REBOL/comments-1.rebol delete mode 100644 Task/Comments/REBOL/comments-2.rebol delete mode 100644 Task/Comments/VBScript/comments.vb delete mode 100644 Task/Comments/VHDL/comments.vhdl delete mode 100644 Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-1.ada delete mode 100644 Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-2.ada delete mode 100644 Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-3.ada delete mode 100644 Task/Compare-a-list-of-strings/Ada/compare-a-list-of-strings-4.ada delete mode 100644 Task/Compare-a-list-of-strings/COBOL/compare-a-list-of-strings.cobol delete mode 100644 Task/Compare-a-list-of-strings/Icon/compare-a-list-of-strings.icon delete mode 100644 Task/Compare-a-list-of-strings/PowerShell/compare-a-list-of-strings.psh delete mode 100644 Task/Compare-a-list-of-strings/Python/compare-a-list-of-strings-1.py delete mode 100644 Task/Compare-a-list-of-strings/Python/compare-a-list-of-strings-2.py delete mode 100644 Task/Compare-a-list-of-strings/VBScript/compare-a-list-of-strings.vb delete mode 100644 Task/Compare-length-of-two-strings/Ada/compare-length-of-two-strings.ada delete mode 100644 Task/Compare-length-of-two-strings/Emacs-Lisp/compare-length-of-two-strings.l delete mode 100644 Task/Compile-time-calculation/Ada/compile-time-calculation-1.ada delete mode 100644 Task/Compile-time-calculation/Ada/compile-time-calculation-2.ada delete mode 100644 Task/Compile-time-calculation/Ada/compile-time-calculation-3.ada delete mode 100644 Task/Compile-time-calculation/Ada/compile-time-calculation-4.ada delete mode 100644 Task/Compile-time-calculation/PowerShell/compile-time-calculation.psh delete mode 100644 Task/Compiler-AST-interpreter/COBOL/compiler-ast-interpreter.cobol delete mode 100644 Task/Compiler-code-generator/COBOL/compiler-code-generator.cobol delete mode 100644 Task/Compiler-lexical-analyzer/Ada/compiler-lexical-analyzer.ada delete mode 100644 Task/Compiler-lexical-analyzer/COBOL/compiler-lexical-analyzer.cobol delete mode 100644 Task/Compiler-lexical-analyzer/Emacs-Lisp/compiler-lexical-analyzer.l delete mode 100644 Task/Compiler-lexical-analyzer/Euphoria/compiler-lexical-analyzer.ex delete mode 100644 Task/Compiler-syntax-analyzer/COBOL/compiler-syntax-analyzer.cobol delete mode 100644 Task/Compiler-virtual-machine-interpreter/Ada/compiler-virtual-machine-interpreter.ada delete mode 100644 Task/Compiler-virtual-machine-interpreter/COBOL/compiler-virtual-machine-interpreter.cobol delete mode 100644 Task/Compound-data-type/Ada/compound-data-type-1.ada delete mode 100644 Task/Compound-data-type/Ada/compound-data-type-2.ada delete mode 100644 Task/Compound-data-type/Ada/compound-data-type-3.ada delete mode 100644 Task/Compound-data-type/COBOL/compound-data-type.cobol delete mode 100644 Task/Compound-data-type/Euphoria/compound-data-type.ex delete mode 100644 Task/Compound-data-type/PowerShell/compound-data-type.psh delete mode 100644 Task/Concurrent-computing/Ada/concurrent-computing.ada delete mode 100644 Task/Concurrent-computing/Euphoria/concurrent-computing.ex delete mode 100644 Task/Concurrent-computing/PowerShell/concurrent-computing-1.psh delete mode 100644 Task/Concurrent-computing/PowerShell/concurrent-computing-2.psh delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-1.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-2.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-3.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-4.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-5.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-6.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-7.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-8.ada delete mode 100644 Task/Conditional-structures/Ada/conditional-structures-9.ada delete mode 100644 Task/Conditional-structures/AutoIt/conditional-structures-1.autoit delete mode 100644 Task/Conditional-structures/AutoIt/conditional-structures-2.autoit delete mode 100644 Task/Conditional-structures/AutoIt/conditional-structures-3.autoit delete mode 100644 Task/Conditional-structures/COBOL/conditional-structures-1.cobol delete mode 100644 Task/Conditional-structures/COBOL/conditional-structures-2.cobol delete mode 100644 Task/Conditional-structures/PowerShell/conditional-structures-1.psh delete mode 100644 Task/Conditional-structures/PowerShell/conditional-structures-2.psh delete mode 100644 Task/Conditional-structures/VBScript/conditional-structures-1.vb delete mode 100644 Task/Conditional-structures/VBScript/conditional-structures-2.vb delete mode 100644 Task/Conditional-structures/VBScript/conditional-structures-3.vb delete mode 100644 Task/Conjugate-transpose/Ada/conjugate-transpose.ada delete mode 100644 Task/Conjugate-transpose/PowerShell/conjugate-transpose.psh delete mode 100644 Task/Constrained-genericity/Ada/constrained-genericity-1.ada delete mode 100644 Task/Constrained-genericity/Ada/constrained-genericity-2.ada delete mode 100644 Task/Constrained-random-points-on-a-circle/Ada/constrained-random-points-on-a-circle.ada delete mode 100644 Task/Constrained-random-points-on-a-circle/COBOL/constrained-random-points-on-a-circle.cobol delete mode 100644 Task/Constrained-random-points-on-a-circle/Euphoria/constrained-random-points-on-a-circle-1.ex delete mode 100644 Task/Constrained-random-points-on-a-circle/Euphoria/constrained-random-points-on-a-circle-2.ex delete mode 100644 Task/Constrained-random-points-on-a-circle/PowerShell/constrained-random-points-on-a-circle.psh delete mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Ada/continued-fraction-arithmetic-construct-from-rational-number.ada delete mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Ada/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.ada delete mode 100644 Task/Continued-fraction/Ada/continued-fraction-1.ada delete mode 100644 Task/Continued-fraction/Ada/continued-fraction-2.ada delete mode 100644 Task/Continued-fraction/Ada/continued-fraction-3.ada delete mode 100644 Task/Continued-fraction/Ada/continued-fraction-4.ada delete mode 100644 Task/Continued-fraction/Ada/continued-fraction-5.ada delete mode 100644 Task/Continued-fraction/Ada/continued-fraction-6.ada delete mode 100644 Task/Continued-fraction/COBOL/continued-fraction.cobol delete mode 100644 Task/Continued-fraction/Chapel/continued-fraction.chapel delete mode 100644 Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-1.ada delete mode 100644 Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-2.ada delete mode 100644 Task/Convert-decimal-number-to-rational/Ada/convert-decimal-number-to-rational-3.ada delete mode 100644 Task/Convert-seconds-to-compound-duration/Ada/convert-seconds-to-compound-duration.ada delete mode 100644 Task/Convert-seconds-to-compound-duration/COBOL/convert-seconds-to-compound-duration.cobol delete mode 100644 Task/Convert-seconds-to-compound-duration/PowerShell/convert-seconds-to-compound-duration.psh delete mode 100644 Task/Convert-seconds-to-compound-duration/VBScript/convert-seconds-to-compound-duration.vb delete mode 100644 Task/Convex-hull/Ada/convex-hull.ada delete mode 100644 Task/Convex-hull/Haxe/convex-hull.haxe delete mode 100644 Task/Conways-Game-of-Life/Ada/conways-game-of-life.ada delete mode 100644 Task/Conways-Game-of-Life/COBOL/conways-game-of-life.cobol delete mode 100644 Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel delete mode 100644 Task/Conways-Game-of-Life/Emacs-Lisp/conways-game-of-life-1.l delete mode 100644 Task/Conways-Game-of-Life/Emacs-Lisp/conways-game-of-life-2.l delete mode 100644 Task/Conways-Game-of-Life/Red/conways-game-of-life.red delete mode 100644 Task/Conways-Game-of-Life/Scheme/conways-game-of-life.scm delete mode 100644 Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vb delete mode 100644 Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vb delete mode 100644 Task/Copy-a-string/ALGOL-W/copy-a-string.alg delete mode 100644 Task/Copy-a-string/Ada/copy-a-string-1.ada delete mode 100644 Task/Copy-a-string/Ada/copy-a-string-2.ada delete mode 100644 Task/Copy-a-string/Ada/copy-a-string-3.ada delete mode 100644 Task/Copy-a-string/Ada/copy-a-string-4.ada delete mode 100644 Task/Copy-a-string/AutoIt/copy-a-string.autoit delete mode 100644 Task/Copy-a-string/COBOL/copy-a-string.cobol delete mode 100644 Task/Copy-a-string/Emacs-Lisp/copy-a-string.l delete mode 100644 Task/Copy-a-string/Euphoria/copy-a-string.ex delete mode 100644 Task/Copy-a-string/PowerShell/copy-a-string-1.psh delete mode 100644 Task/Copy-a-string/PowerShell/copy-a-string-2.psh delete mode 100644 Task/Copy-a-string/REBOL/copy-a-string.rebol delete mode 100644 Task/Copy-a-string/Tcl/copy-a-string.tcl delete mode 100644 Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.ada delete mode 100644 Task/Copy-stdin-to-stdout/VBScript/copy-stdin-to-stdout.vb delete mode 100644 Task/Count-in-factors/Ada/count-in-factors.ada delete mode 100644 Task/Count-in-factors/Euphoria/count-in-factors.ex delete mode 100644 Task/Count-in-factors/PowerShell/count-in-factors.psh delete mode 100644 Task/Count-in-factors/VBScript/count-in-factors.vb delete mode 100644 Task/Count-in-octal/Ada/count-in-octal.ada delete mode 100644 Task/Count-in-octal/COBOL/count-in-octal.cobol delete mode 100644 Task/Count-in-octal/Emacs-Lisp/count-in-octal.l delete mode 100644 Task/Count-in-octal/Euphoria/count-in-octal.ex delete mode 100644 Task/Count-in-octal/PowerShell/count-in-octal.psh delete mode 100644 Task/Count-in-octal/VBScript/count-in-octal.vb delete mode 100644 Task/Count-occurrences-of-a-substring/Ada/count-occurrences-of-a-substring.ada delete mode 100644 Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cobol delete mode 100644 Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.l delete mode 100644 Task/Count-occurrences-of-a-substring/Euphoria/count-occurrences-of-a-substring.ex delete mode 100644 Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.psh delete mode 100644 Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.psh delete mode 100644 Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-1.vb delete mode 100644 Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-2.vb delete mode 100644 Task/Count-the-coins/Ada/count-the-coins-1.ada delete mode 100644 Task/Count-the-coins/Ada/count-the-coins-2.ada delete mode 100644 Task/Count-the-coins/COBOL/count-the-coins.cobol delete mode 100644 Task/Count-the-coins/VBScript/count-the-coins.vb delete mode 100644 Task/Cramers-rule/Ada/cramers-rule.ada delete mode 100644 Task/Create-a-file-on-magnetic-tape/COBOL/create-a-file-on-magnetic-tape.cobol delete mode 100644 Task/Create-a-file/Ada/create-a-file.ada delete mode 100644 Task/Create-a-file/COBOL/create-a-file.cobol delete mode 100644 Task/Create-a-file/Emacs-Lisp/create-a-file.l delete mode 100644 Task/Create-a-file/Euphoria/create-a-file.ex delete mode 100644 Task/Create-a-file/PowerShell/create-a-file.psh delete mode 100644 Task/Create-a-file/REBOL/create-a-file.rebol delete mode 100644 Task/Create-a-file/VBScript/create-a-file.vb delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Ada/create-a-two-dimensional-array-at-runtime.ada delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/AutoIt/create-a-two-dimensional-array-at-runtime.autoit delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Euphoria/create-a-two-dimensional-array-at-runtime.ex delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-1.psh delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-2.psh delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-3.psh delete mode 100644 Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-4.psh delete mode 100644 Task/Create-an-HTML-table/Ada/create-an-html-table-1.ada delete mode 100644 Task/Create-an-HTML-table/Ada/create-an-html-table-2.ada delete mode 100644 Task/Create-an-HTML-table/Ada/create-an-html-table-3.ada delete mode 100644 Task/Create-an-HTML-table/Ada/create-an-html-table-4.ada delete mode 100644 Task/Create-an-HTML-table/COBOL/create-an-html-table.cobol delete mode 100644 Task/Create-an-HTML-table/Euphoria/create-an-html-table-1.ex delete mode 100644 Task/Create-an-HTML-table/Euphoria/create-an-html-table-2.ex delete mode 100644 Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh delete mode 100644 Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh delete mode 100644 Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh delete mode 100644 Task/Create-an-HTML-table/VBScript/create-an-html-table.vb delete mode 100644 Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.ada delete mode 100644 Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.ada delete mode 100644 Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cobol delete mode 100644 Task/Cuban-primes/Ada/cuban-primes.ada delete mode 100644 Task/Cullen-and-Woodall-numbers/COBOL/cullen-and-woodall-numbers.cobol delete mode 100644 Task/Cumulative-standard-deviation/Ada/cumulative-standard-deviation.ada delete mode 100644 Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-1.cobol delete mode 100644 Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-2.cobol delete mode 100644 Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-1.l delete mode 100644 Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-2.l delete mode 100644 Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-3.l delete mode 100644 Task/Cumulative-standard-deviation/Haxe/cumulative-standard-deviation.haxe delete mode 100644 Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation.phix delete mode 100644 Task/Cumulative-standard-deviation/PowerShell/cumulative-standard-deviation.psh delete mode 100644 Task/Cumulative-standard-deviation/VBScript/cumulative-standard-deviation.vb delete mode 100644 Task/Currency/Ada/currency.ada delete mode 100644 Task/Currency/COBOL/currency.cobol delete mode 100644 Task/Currying/Ada/currying-1.ada delete mode 100644 Task/Currying/Ada/currying-2.ada delete mode 100644 Task/Currying/Ada/currying-3.ada delete mode 100644 Task/Currying/PowerShell/currying-1.psh delete mode 100644 Task/Currying/PowerShell/currying-2.psh delete mode 100644 Task/Currying/PowerShell/currying-3.psh delete mode 100644 Task/Curzon-numbers/Ada/curzon-numbers.ada delete mode 100644 Task/DNS-query/Ada/dns-query-1.ada delete mode 100644 Task/DNS-query/Ada/dns-query-2.ada delete mode 100644 Task/DNS-query/Batch-File/dns-query.bat delete mode 100644 Task/DNS-query/PowerShell/dns-query.psh delete mode 100644 Task/DNS-query/VBScript/dns-query.vb delete mode 100644 Task/Damm-algorithm/Ada/damm-algorithm.ada delete mode 100644 Task/Damm-algorithm/PowerShell/damm-algorithm.psh delete mode 100644 Task/Date-format/Ada/date-format.ada delete mode 100644 Task/Date-format/AutoIt/date-format.autoit delete mode 100644 Task/Date-format/COBOL/date-format.cobol delete mode 100644 Task/Date-format/Emacs-Lisp/date-format.l delete mode 100644 Task/Date-format/Euphoria/date-format.ex delete mode 100644 Task/Date-format/PowerShell/date-format.psh delete mode 100644 Task/Date-format/REBOL/date-format-1.rebol delete mode 100644 Task/Date-format/REBOL/date-format-2.rebol delete mode 100644 Task/Date-format/REXX/date-format-1.rexx delete mode 100644 Task/Date-format/REXX/date-format-2.rexx delete mode 100644 Task/Date-format/REXX/date-format-3.rexx delete mode 100644 Task/Date-format/VBScript/date-format.vb delete mode 100644 Task/Date-manipulation/Ada/date-manipulation.ada delete mode 100644 Task/Date-manipulation/COBOL/date-manipulation.cobol delete mode 100644 Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.l delete mode 100644 Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.l delete mode 100644 Task/Date-manipulation/Euphoria/date-manipulation.ex delete mode 100644 Task/Date-manipulation/PowerShell/date-manipulation.psh delete mode 100644 Task/Date-manipulation/REBOL/date-manipulation.rebol delete mode 100644 Task/Day-of-the-week/Ada/day-of-the-week.ada delete mode 100644 Task/Day-of-the-week/AutoIt/day-of-the-week.autoit delete mode 100644 Task/Day-of-the-week/COBOL/day-of-the-week-1.cobol delete mode 100644 Task/Day-of-the-week/COBOL/day-of-the-week-2.cobol delete mode 100644 Task/Day-of-the-week/Emacs-Lisp/day-of-the-week.l delete mode 100644 Task/Day-of-the-week/Euphoria/day-of-the-week.ex delete mode 100644 Task/Day-of-the-week/PowerShell/day-of-the-week-1.psh delete mode 100644 Task/Day-of-the-week/PowerShell/day-of-the-week-2.psh delete mode 100644 Task/Day-of-the-week/PowerShell/day-of-the-week-3.psh delete mode 100644 Task/Day-of-the-week/PowerShell/day-of-the-week-4.psh delete mode 100644 Task/Day-of-the-week/PowerShell/day-of-the-week-5.psh delete mode 100644 Task/Day-of-the-week/PowerShell/day-of-the-week-6.psh delete mode 100644 Task/Day-of-the-week/REBOL/day-of-the-week.rebol delete mode 100644 Task/Day-of-the-week/VBScript/day-of-the-week.vb delete mode 100644 Task/De-Bruijn-sequences/Ada/de-bruijn-sequences.ada delete mode 100644 Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences.rb delete mode 100644 Task/Deal-cards-for-FreeCell/Ada/deal-cards-for-freecell.ada delete mode 100644 Task/Death-Star/Ada/death-star.ada delete mode 100644 Task/Death-Star/VBScript/death-star.vb delete mode 100644 Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers.pas delete mode 100644 Task/Deconvolution-1D/Ada/deconvolution-1d.ada delete mode 100644 Task/Deepcopy/Ada/deepcopy.ada delete mode 100644 Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-1.ada delete mode 100644 Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-2.ada delete mode 100644 Task/Define-a-primitive-data-type/Euphoria/define-a-primitive-data-type.ex delete mode 100644 Task/Define-a-primitive-data-type/PowerShell/define-a-primitive-data-type.psh delete mode 100644 Task/Delegates/Ada/delegates.ada delete mode 100644 Task/Delete-a-file/Ada/delete-a-file-1.ada delete mode 100644 Task/Delete-a-file/Ada/delete-a-file-2.ada delete mode 100644 Task/Delete-a-file/COBOL/delete-a-file-1.cobol delete mode 100644 Task/Delete-a-file/COBOL/delete-a-file-2.cobol delete mode 100644 Task/Delete-a-file/Emacs-Lisp/delete-a-file.l delete mode 100644 Task/Delete-a-file/PowerShell/delete-a-file.psh delete mode 100644 Task/Delete-a-file/REBOL/delete-a-file.rebol delete mode 100644 Task/Delete-a-file/VBScript/delete-a-file.vb delete mode 100644 Task/Demings-funnel/Ada/demings-funnel.ada delete mode 100644 Task/Department-numbers/Ada/department-numbers.ada delete mode 100644 Task/Department-numbers/COBOL/department-numbers.cobol delete mode 100644 Task/Detect-division-by-zero/Ada/detect-division-by-zero.ada delete mode 100644 Task/Detect-division-by-zero/COBOL/detect-division-by-zero.cobol delete mode 100644 Task/Detect-division-by-zero/Emacs-Lisp/detect-division-by-zero.l delete mode 100644 Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh delete mode 100644 Task/Detect-division-by-zero/REBOL/detect-division-by-zero.rebol delete mode 100644 Task/Detect-division-by-zero/REXX/detect-division-by-zero-3.rexx delete mode 100644 Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb delete mode 100644 Task/Determinant-and-permanent/C++/determinant-and-permanent.cpp delete mode 100644 Task/Determinant-and-permanent/PowerShell/determinant-and-permanent.psh delete mode 100644 Task/Determine-if-a-string-has-all-the-same-characters/Ada/determine-if-a-string-has-all-the-same-characters.ada delete mode 100644 Task/Determine-if-a-string-has-all-unique-characters/Ada/determine-if-a-string-has-all-unique-characters.ada delete mode 100644 Task/Determine-if-a-string-is-collapsible/Ada/determine-if-a-string-is-collapsible.ada delete mode 100644 Task/Determine-if-a-string-is-numeric/Ada/determine-if-a-string-is-numeric-1.ada delete mode 100644 Task/Determine-if-a-string-is-numeric/Ada/determine-if-a-string-is-numeric-2.ada delete mode 100644 Task/Determine-if-a-string-is-numeric/Ada/determine-if-a-string-is-numeric-3.ada delete mode 100644 Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-1.cobol delete mode 100644 Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric-2.cobol delete mode 100644 Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-1.l delete mode 100644 Task/Determine-if-a-string-is-numeric/Emacs-Lisp/determine-if-a-string-is-numeric-2.l delete mode 100644 Task/Determine-if-a-string-is-numeric/Euphoria/determine-if-a-string-is-numeric.ex delete mode 100644 Task/Determine-if-a-string-is-numeric/Haxe/determine-if-a-string-is-numeric.haxe delete mode 100644 Task/Determine-if-a-string-is-numeric/PowerShell/determine-if-a-string-is-numeric-1.psh delete mode 100644 Task/Determine-if-a-string-is-numeric/PowerShell/determine-if-a-string-is-numeric-2.psh delete mode 100644 Task/Determine-if-a-string-is-numeric/REBOL/determine-if-a-string-is-numeric.rebol delete mode 100644 Task/Determine-if-a-string-is-numeric/VBScript/determine-if-a-string-is-numeric.vb delete mode 100644 Task/Determine-if-a-string-is-squeezable/Ada/determine-if-a-string-is-squeezable.ada delete mode 100644 Task/Determine-if-only-one-instance-is-running/Ada/determine-if-only-one-instance-is-running.ada delete mode 100644 Task/Determine-if-only-one-instance-is-running/PowerShell/determine-if-only-one-instance-is-running-1.psh delete mode 100644 Task/Determine-if-only-one-instance-is-running/PowerShell/determine-if-only-one-instance-is-running-2.psh delete mode 100644 Task/Determine-if-two-triangles-overlap/Ada/determine-if-two-triangles-overlap.ada delete mode 100644 Task/Determine-sentence-type/Ada/determine-sentence-type.ada delete mode 100644 Task/Determine-sentence-type/Emacs-Lisp/determine-sentence-type.l delete mode 100644 Task/Dice-game-probabilities/Ada/dice-game-probabilities.ada delete mode 100644 Task/Digital-root-Multiplicative-digital-root/Ada/digital-root-multiplicative-digital-root.ada delete mode 100644 Task/Digital-root/Ada/digital-root-1.ada delete mode 100644 Task/Digital-root/Ada/digital-root-2.ada delete mode 100644 Task/Digital-root/Ada/digital-root-3.ada delete mode 100644 Task/Digital-root/COBOL/digital-root.cobol delete mode 100644 Task/Digital-root/PowerShell/digital-root-1.psh delete mode 100644 Task/Digital-root/PowerShell/digital-root-2.psh delete mode 100644 Task/Digital-root/VBScript/digital-root.vb delete mode 100644 Task/Dijkstras-algorithm/Ada/dijkstras-algorithm-1.ada delete mode 100644 Task/Dijkstras-algorithm/Ada/dijkstras-algorithm-2.ada delete mode 100644 Task/Dijkstras-algorithm/Ada/dijkstras-algorithm-3.ada delete mode 100644 Task/Dijkstras-algorithm/Emacs-Lisp/dijkstras-algorithm.l delete mode 100644 Task/Dinesmans-multiple-dwelling-problem/Ada/dinesmans-multiple-dwelling-problem.ada delete mode 100644 Task/Dinesmans-multiple-dwelling-problem/PowerShell/dinesmans-multiple-dwelling-problem-1.psh delete mode 100644 Task/Dinesmans-multiple-dwelling-problem/PowerShell/dinesmans-multiple-dwelling-problem-2.psh delete mode 100644 Task/Dinesmans-multiple-dwelling-problem/PowerShell/dinesmans-multiple-dwelling-problem-3.psh delete mode 100644 Task/Dining-philosophers/Ada/dining-philosophers-1.ada delete mode 100644 Task/Dining-philosophers/Ada/dining-philosophers-2.ada delete mode 100644 Task/Dining-philosophers/Ada/dining-philosophers-3.ada delete mode 100644 Task/Dining-philosophers/Euphoria/dining-philosophers.ex delete mode 100644 Task/Disarium-numbers/Ada/disarium-numbers.ada delete mode 100644 Task/Disarium-numbers/COBOL/disarium-numbers.cobol delete mode 100644 Task/Discordian-date/Ada/discordian-date.ada delete mode 100644 Task/Discordian-date/Euphoria/discordian-date.ex delete mode 100644 Task/Discordian-date/PowerShell/discordian-date.psh delete mode 100644 Task/Display-a-linear-combination/Ada/display-a-linear-combination.ada delete mode 100644 Task/Distributed-programming/Ada/distributed-programming-1.ada delete mode 100644 Task/Distributed-programming/Ada/distributed-programming-2.ada delete mode 100644 Task/Distributed-programming/Ada/distributed-programming-3.ada delete mode 100644 Task/Distributed-programming/Ada/distributed-programming-4.ada delete mode 100644 Task/Diversity-prediction-theorem/Ada/diversity-prediction-theorem.ada delete mode 100644 Task/Documentation/Ada/documentation.ada delete mode 100644 Task/Documentation/COBOL/documentation-1.cobol delete mode 100644 Task/Documentation/COBOL/documentation-2.cobol delete mode 100644 Task/Documentation/Emacs-Lisp/documentation-1.l delete mode 100644 Task/Documentation/Emacs-Lisp/documentation-2.l delete mode 100644 Task/Documentation/PowerShell/documentation.psh delete mode 100644 Task/Documentation/REBOL/documentation.rebol delete mode 100644 Task/Dot-product/Ada/dot-product.ada delete mode 100644 Task/Dot-product/Emacs-Lisp/dot-product.l delete mode 100644 Task/Dot-product/Euphoria/dot-product-1.ex delete mode 100644 Task/Dot-product/Euphoria/dot-product-2.ex delete mode 100644 Task/Dot-product/Perl/dot-product.pl delete mode 100644 Task/Dot-product/PowerShell/dot-product.psh delete mode 100644 Task/Dot-product/REBOL/dot-product.rebol delete mode 100644 Task/Dot-product/VBScript/dot-product.vb delete mode 100644 Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-1.psh delete mode 100644 Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-2.psh delete mode 100644 Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-3.psh delete mode 100644 Task/Doubly-linked-list-Definition/PowerShell/doubly-linked-list-definition-4.psh delete mode 100644 Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-1.ada delete mode 100644 Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-2.ada delete mode 100644 Task/Doubly-linked-list-Element-definition/Ada/doubly-linked-list-element-definition-3.ada delete mode 100644 Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-1.ada delete mode 100644 Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-2.ada delete mode 100644 Task/Doubly-linked-list-Element-insertion/Ada/doubly-linked-list-element-insertion-3.ada delete mode 100644 Task/Doubly-linked-list-Traversal/Ada/doubly-linked-list-traversal.ada delete mode 100644 Task/Dragon-curve/Ada/dragon-curve-1.ada delete mode 100644 Task/Dragon-curve/Ada/dragon-curve-2.ada delete mode 100644 Task/Dragon-curve/Ada/dragon-curve-3.ada delete mode 100644 Task/Dragon-curve/Ada/dragon-curve-4.ada delete mode 100644 Task/Dragon-curve/COBOL/dragon-curve.cobol delete mode 100644 Task/Dragon-curve/Emacs-Lisp/dragon-curve.l delete mode 100644 Task/Dragon-curve/VBScript/dragon-curve.vb delete mode 100644 Task/Draw-a-clock/Ada/draw-a-clock.ada delete mode 100644 Task/Draw-a-clock/Perl/draw-a-clock.pl delete mode 100644 Task/Draw-a-clock/VBScript/draw-a-clock.vb delete mode 100644 Task/Draw-a-cuboid/Ada/draw-a-cuboid.ada delete mode 100644 Task/Draw-a-cuboid/VBScript/draw-a-cuboid.vb delete mode 100644 Task/Draw-a-pixel/Ada/draw-a-pixel.ada delete mode 100644 Task/Draw-a-pixel/Odin/draw-a-pixel.odin delete mode 100644 Task/Draw-a-pixel/ReScript/draw-a-pixel-1.re delete mode 100644 Task/Draw-a-pixel/ReScript/draw-a-pixel-2.re delete mode 100644 Task/Draw-a-rotating-cube/Ada/draw-a-rotating-cube.ada delete mode 100644 Task/Draw-a-sphere/Ada/draw-a-sphere-1.ada delete mode 100644 Task/Draw-a-sphere/Ada/draw-a-sphere-2.ada delete mode 100644 Task/Draw-a-sphere/Emacs-Lisp/draw-a-sphere.l delete mode 100644 Task/Draw-a-sphere/VBScript/draw-a-sphere.vb delete mode 100644 Task/Dutch-national-flag-problem/Ada/dutch-national-flag-problem.ada delete mode 100644 Task/Dutch-national-flag-problem/AutoIt/dutch-national-flag-problem.autoit delete mode 100644 Task/Dutch-national-flag-problem/PowerShell/dutch-national-flag-problem.psh delete mode 100644 Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vb delete mode 100644 Task/Dynamic-variable-names/Emacs-Lisp/dynamic-variable-names.l delete mode 100644 Task/Dynamic-variable-names/PowerShell/dynamic-variable-names.psh delete mode 100644 Task/Dynamic-variable-names/REBOL/dynamic-variable-names.rebol delete mode 100644 Task/EKG-sequence-convergence/Ada/ekg-sequence-convergence.ada delete mode 100644 Task/Eban-numbers/Ada/eban-numbers.ada delete mode 100644 Task/Echo-server/Ada/echo-server-1.ada delete mode 100644 Task/Echo-server/Ada/echo-server-2.ada delete mode 100644 Task/Echo-server/REBOL/echo-server.rebol delete mode 100644 Task/Egyptian-division/Ada/egyptian-division.ada delete mode 100644 Task/Element-wise-operations/Ada/element-wise-operations-1.ada delete mode 100644 Task/Element-wise-operations/Ada/element-wise-operations-2.ada delete mode 100644 Task/Element-wise-operations/Ada/element-wise-operations-3.ada delete mode 100644 Task/Elementary-cellular-automaton/Ada/elementary-cellular-automaton.ada delete mode 100644 Task/Emirp-primes/Ada/emirp-primes.ada delete mode 100644 Task/Empty-directory/Ada/empty-directory.ada delete mode 100644 Task/Empty-directory/PowerShell/empty-directory.psh delete mode 100644 Task/Empty-directory/VBScript/empty-directory.vb delete mode 100644 Task/Empty-program/Ada/empty-program.ada delete mode 100644 Task/Empty-program/Asymptote/empty-program.asymptote delete mode 100644 Task/Empty-program/AutoIt/empty-program.autoit delete mode 100644 Task/Empty-program/BASIC256/empty-program.basic delete mode 100644 Task/Empty-program/BootBASIC/empty-program.basic delete mode 100644 Task/Empty-program/COBOL/empty-program.cobol delete mode 100644 Task/Empty-program/CoffeeScript/empty-program.coffee delete mode 100644 Task/Empty-program/Crystal/empty-program.cr delete mode 100644 Task/Empty-program/Elixir/empty-program.ex delete mode 100644 Task/Empty-program/Euphoria/empty-program.ex delete mode 100644 Task/Empty-program/FALSE/empty-program.false delete mode 100644 Task/Empty-program/Groovy/empty-program.groovy delete mode 100644 Task/Empty-program/Haxe/empty-program.haxe delete mode 100644 Task/Empty-program/K/empty-program.k delete mode 100644 Task/Empty-program/LSE/empty-program.lse delete mode 100644 Task/Empty-program/Lua/empty-program.lua delete mode 100644 Task/Empty-program/M4/empty-program.m4 delete mode 100644 Task/Empty-program/ML-I/empty-program.mli delete mode 100644 Task/Empty-program/Maple/empty-program.maple delete mode 100644 Task/Empty-program/Mathematica/empty-program.math delete mode 100644 Task/Empty-program/MelonBasic/empty-program.basic delete mode 100644 Task/Empty-program/MiniScript/empty-program.mini delete mode 100644 Task/Empty-program/NS-HUBASIC/empty-program.basic delete mode 100644 Task/Empty-program/Openscad/empty-program.scad delete mode 100644 Task/Empty-program/PARI-GP/empty-program.parigp delete mode 100644 Task/Empty-program/PowerShell/empty-program.psh delete mode 100644 Task/Empty-program/Quite-BASIC/empty-program.basic delete mode 100644 Task/Empty-program/REBOL/empty-program.rebol delete mode 100644 Task/Empty-program/Ring/empty-program.ring delete mode 100644 Task/Empty-program/Robotic/empty-program.robotic delete mode 100644 Task/Empty-program/Scheme/empty-program.scm delete mode 100644 Task/Empty-program/Scilab/empty-program.scilab delete mode 100644 Task/Empty-program/Set-lang/empty-program.set delete mode 100644 Task/Empty-program/Sidef/empty-program.sidef delete mode 100644 Task/Empty-program/SimpleCode/empty-program.simplecode delete mode 100644 Task/Empty-program/Slate/empty-program.slate delete mode 100644 Task/Empty-program/Sparkling/empty-program.sparkling delete mode 100644 Task/Empty-program/Swift/empty-program.swift delete mode 100644 Task/Empty-program/Symsyn/empty-program.symsyn delete mode 100644 Task/Empty-program/Trith/empty-program.trith delete mode 100644 Task/Empty-program/VBScript/empty-program.vb delete mode 100644 Task/Empty-program/VHDL/empty-program.vhdl delete mode 100644 Task/Empty-program/Wee-Basic/empty-program.basic delete mode 100644 Task/Empty-program/Wren/empty-program.wren delete mode 100644 Task/Empty-program/Yabasic/empty-program.basic delete mode 100644 Task/Empty-string/Ada/empty-string.ada delete mode 100644 Task/Empty-string/COBOL/empty-string.cobol delete mode 100644 Task/Empty-string/Emacs-Lisp/empty-string-1.l delete mode 100644 Task/Empty-string/Emacs-Lisp/empty-string-2.l delete mode 100644 Task/Empty-string/Euphoria/empty-string.ex delete mode 100644 Task/Empty-string/PowerShell/empty-string-1.psh delete mode 100644 Task/Empty-string/PowerShell/empty-string-2.psh delete mode 100644 Task/Enforced-immutability/Ada/enforced-immutability-1.ada delete mode 100644 Task/Enforced-immutability/Ada/enforced-immutability-2.ada delete mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-1.cobol delete mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-2.cobol delete mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-3.cobol delete mode 100644 Task/Enforced-immutability/COBOL/enforced-immutability-4.cobol delete mode 100644 Task/Enforced-immutability/Euphoria/enforced-immutability.ex delete mode 100644 Task/Entropy-Narcissist/Ada/entropy-narcissist.ada delete mode 100644 Task/Entropy-Narcissist/AutoLISP/entropy-narcissist.l delete mode 100644 Task/Entropy-Narcissist/Emacs-Lisp/entropy-narcissist-1.l delete mode 100644 Task/Entropy-Narcissist/Emacs-Lisp/entropy-narcissist-2.l delete mode 100644 Task/Entropy/Ada/entropy.ada delete mode 100644 Task/Entropy/AutoLISP/entropy.l delete mode 100644 Task/Entropy/Emacs-Lisp/entropy-1.l delete mode 100644 Task/Entropy/Emacs-Lisp/entropy-2.l delete mode 100644 Task/Entropy/PowerShell/entropy.psh delete mode 100644 Task/Enumerations/Ada/enumerations.ada delete mode 100644 Task/Enumerations/PowerShell/enumerations-1.psh delete mode 100644 Task/Enumerations/PowerShell/enumerations-2.psh delete mode 100644 Task/Environment-variables/Ada/environment-variables-1.ada delete mode 100644 Task/Environment-variables/Ada/environment-variables-2.ada delete mode 100644 Task/Environment-variables/Ada/environment-variables-3.ada delete mode 100644 Task/Environment-variables/AutoIt/environment-variables.autoit delete mode 100644 Task/Environment-variables/COBOL/environment-variables.cobol delete mode 100644 Task/Environment-variables/Emacs-Lisp/environment-variables.l delete mode 100644 Task/Environment-variables/Euphoria/environment-variables.ex delete mode 100644 Task/Environment-variables/PowerShell/environment-variables-1.psh delete mode 100644 Task/Environment-variables/PowerShell/environment-variables-2.psh delete mode 100644 Task/Environment-variables/REBOL/environment-variables.rebol delete mode 100644 Task/Equal-prime-and-composite-sums/Ada/equal-prime-and-composite-sums.ada delete mode 100644 Task/Equilibrium-index/Ada/equilibrium-index-1.ada delete mode 100644 Task/Equilibrium-index/Ada/equilibrium-index-2.ada delete mode 100644 Task/Equilibrium-index/Ada/equilibrium-index-3.ada delete mode 100644 Task/Equilibrium-index/Ada/equilibrium-index-4.ada delete mode 100644 Task/Equilibrium-index/Euphoria/equilibrium-index.ex delete mode 100644 Task/Equilibrium-index/PowerShell/equilibrium-index-1.psh delete mode 100644 Task/Equilibrium-index/PowerShell/equilibrium-index-2.psh delete mode 100644 Task/Equilibrium-index/ReScript/equilibrium-index.re delete mode 100644 Task/Equilibrium-index/VBScript/equilibrium-index.vb delete mode 100644 Task/Ethiopian-multiplication/Ada/ethiopian-multiplication.ada delete mode 100644 Task/Ethiopian-multiplication/AutoIt/ethiopian-multiplication.autoit delete mode 100644 Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication.basic delete mode 100644 Task/Ethiopian-multiplication/COBOL/ethiopian-multiplication.cobol delete mode 100644 Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l delete mode 100644 Task/Ethiopian-multiplication/Euphoria/ethiopian-multiplication.ex delete mode 100644 Task/Ethiopian-multiplication/Pascal/ethiopian-multiplication.pas delete mode 100644 Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-1.psh delete mode 100644 Task/Ethiopian-multiplication/PowerShell/ethiopian-multiplication-2.psh delete mode 100644 Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-1.vb delete mode 100644 Task/Ethiopian-multiplication/VBScript/ethiopian-multiplication-2.vb delete mode 100644 Task/Euler-method/Ada/euler-method-1.ada delete mode 100644 Task/Euler-method/Ada/euler-method-2.ada delete mode 100644 Task/Euler-method/Ada/euler-method-3.ada delete mode 100644 Task/Euler-method/COBOL/euler-method.cobol delete mode 100644 Task/Euler-method/PowerShell/euler-method.psh delete mode 100644 Task/Eulers-constant-0.5772.../Ada/eulers-constant-0.5772....ada delete mode 100644 Task/Eulers-identity/Ada/eulers-identity.ada delete mode 100644 Task/Eulers-sum-of-powers-conjecture/Ada/eulers-sum-of-powers-conjecture.ada delete mode 100644 Task/Eulers-sum-of-powers-conjecture/COBOL/eulers-sum-of-powers-conjecture.cobol delete mode 100644 Task/Eulers-sum-of-powers-conjecture/PowerShell/eulers-sum-of-powers-conjecture.psh delete mode 100644 Task/Eulers-sum-of-powers-conjecture/VBScript/eulers-sum-of-powers-conjecture.vb delete mode 100644 Task/Evaluate-binomial-coefficients/Ada/evaluate-binomial-coefficients.ada delete mode 100644 Task/Evaluate-binomial-coefficients/PowerShell/evaluate-binomial-coefficients.psh delete mode 100644 Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vb delete mode 100644 Task/Even-or-odd/Ada/even-or-odd.ada delete mode 100644 Task/Even-or-odd/COBOL/even-or-odd.cobol delete mode 100644 Task/Even-or-odd/Emacs-Lisp/even-or-odd.l delete mode 100644 Task/Even-or-odd/Euphoria/even-or-odd.ex delete mode 100644 Task/Even-or-odd/Oberon/even-or-odd.oberon delete mode 100644 Task/Even-or-odd/PowerShell/even-or-odd-1.psh delete mode 100644 Task/Even-or-odd/PowerShell/even-or-odd-2.psh delete mode 100644 Task/Even-or-odd/PowerShell/even-or-odd-3.psh delete mode 100644 Task/Even-or-odd/ReScript/even-or-odd.re delete mode 100644 Task/Even-or-odd/VBScript/even-or-odd.vb delete mode 100644 Task/Events/Ada/events-1.ada delete mode 100644 Task/Events/Ada/events-2.ada delete mode 100644 Task/Events/Ada/events-3.ada delete mode 100644 Task/Events/PowerShell/events.psh delete mode 100644 Task/Evolutionary-algorithm/Ada/evolutionary-algorithm.ada delete mode 100644 Task/Evolutionary-algorithm/COBOL/evolutionary-algorithm.cobol delete mode 100644 Task/Evolutionary-algorithm/Euphoria/evolutionary-algorithm.ex delete mode 100644 Task/Evolutionary-algorithm/VBScript/evolutionary-algorithm.vb delete mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ada/exceptions-catch-an-exception-thrown-in-a-nested-call.ada delete mode 100644 Task/Exceptions/Ada/exceptions-1.ada delete mode 100644 Task/Exceptions/Ada/exceptions-2.ada delete mode 100644 Task/Exceptions/Ada/exceptions-3.ada delete mode 100644 Task/Exceptions/Ada/exceptions-4.ada delete mode 100644 Task/Exceptions/Ada/exceptions-5.ada delete mode 100644 Task/Exceptions/PowerShell/exceptions-1.psh delete mode 100644 Task/Exceptions/PowerShell/exceptions-2.psh delete mode 100644 Task/Exceptions/PowerShell/exceptions-3.psh delete mode 100644 Task/Exceptions/PowerShell/exceptions-4.psh delete mode 100644 Task/Executable-library/Ada/executable-library-1.ada delete mode 100644 Task/Executable-library/Ada/executable-library-2.ada delete mode 100644 Task/Executable-library/Ada/executable-library-3.ada delete mode 100644 Task/Executable-library/Ada/executable-library-4.ada delete mode 100644 Task/Execute-Brain-/AutoIt/execute-brain-.autoit delete mode 100644 Task/Execute-Brain-/REBOL/execute-brain-.rebol delete mode 100644 Task/Execute-Brain-/VBScript/execute-brain-.vb delete mode 100644 Task/Execute-HQ9+/COBOL/execute-hq9+.cobol delete mode 100644 Task/Execute-HQ9+/Haxe/execute-hq9+.haxe delete mode 100644 Task/Execute-HQ9+/PowerShell/execute-hq9+.psh delete mode 100644 Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-1.ada delete mode 100644 Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-2.ada delete mode 100644 Task/Execute-a-Markov-algorithm/Ada/execute-a-markov-algorithm-3.ada delete mode 100644 Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-1.vb delete mode 100644 Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-2.vb delete mode 100644 Task/Execute-a-Markov-algorithm/VBScript/execute-a-markov-algorithm-3.vb delete mode 100644 Task/Execute-a-system-command/Ada/execute-a-system-command-1.ada delete mode 100644 Task/Execute-a-system-command/Ada/execute-a-system-command-2.ada delete mode 100644 Task/Execute-a-system-command/Ada/execute-a-system-command-3.ada delete mode 100644 Task/Execute-a-system-command/AutoIt/execute-a-system-command.autoit delete mode 100644 Task/Execute-a-system-command/COBOL/execute-a-system-command.cobol delete mode 100644 Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-1.l delete mode 100644 Task/Execute-a-system-command/Emacs-Lisp/execute-a-system-command-2.l delete mode 100644 Task/Execute-a-system-command/Euphoria/execute-a-system-command.ex delete mode 100644 Task/Execute-a-system-command/PowerShell/execute-a-system-command-1.psh delete mode 100644 Task/Execute-a-system-command/PowerShell/execute-a-system-command-2.psh delete mode 100644 Task/Execute-a-system-command/REBOL/execute-a-system-command.rebol delete mode 100644 Task/Execute-a-system-command/VBScript/execute-a-system-command.vb delete mode 100644 Task/Exponentiation-operator/Ada/exponentiation-operator-1.ada delete mode 100644 Task/Exponentiation-operator/Ada/exponentiation-operator-2.ada delete mode 100644 Task/Exponentiation-operator/Ada/exponentiation-operator-3.ada delete mode 100644 Task/Exponentiation-operator/PowerShell/exponentiation-operator.psh delete mode 100644 Task/Exponentiation-operator/VBScript/exponentiation-operator.vb delete mode 100644 Task/Exponentiation-order/Ada/exponentiation-order.ada delete mode 100644 Task/Exponentiation-order/VBScript/exponentiation-order.vb delete mode 100644 Task/Exponentiation-with-infix-operators-in-or-operating-on-the-base/Ada/exponentiation-with-infix-operators-in-or-operating-on-the-base.ada delete mode 100644 Task/Extend-your-language/Ada/extend-your-language.ada delete mode 100644 Task/Extend-your-language/COBOL/extend-your-language.cobol delete mode 100644 Task/Extend-your-language/Coq/extend-your-language.coq delete mode 100644 Task/Extend-your-language/Emacs-Lisp/extend-your-language.l delete mode 100644 Task/Extend-your-language/PowerShell/extend-your-language-1.psh delete mode 100644 Task/Extend-your-language/PowerShell/extend-your-language-2.psh delete mode 100644 Task/Extend-your-language/PowerShell/extend-your-language-3.psh delete mode 100644 Task/Extensible-prime-generator/Ada/extensible-prime-generator.ada delete mode 100644 Task/Extensible-prime-generator/VBScript/extensible-prime-generator.vb delete mode 100644 Task/Extreme-floating-point-values/Ada/extreme-floating-point-values-1.ada delete mode 100644 Task/Extreme-floating-point-values/Ada/extreme-floating-point-values-2.ada delete mode 100644 Task/Extreme-floating-point-values/Euphoria/extreme-floating-point-values.ex delete mode 100644 Task/FASTA-format/Ada/fasta-format-1.ada delete mode 100644 Task/FASTA-format/Ada/fasta-format-2.ada delete mode 100644 Task/FASTA-format/Perl/fasta-format.pl delete mode 100644 Task/FASTA-format/PowerShell/fasta-format-1.psh delete mode 100644 Task/FASTA-format/PowerShell/fasta-format-2.psh delete mode 100644 Task/FTP/Ada/ftp.ada delete mode 100644 Task/FTP/REBOL/ftp.rebol delete mode 100644 Task/Factorial-primes/Ada/factorial-primes.ada delete mode 100644 Task/Factorial/Ada/factorial-1.ada delete mode 100644 Task/Factorial/Ada/factorial-2.ada delete mode 100644 Task/Factorial/Ada/factorial-3.ada delete mode 100644 Task/Factorial/AutoIt/factorial-1.autoit delete mode 100644 Task/Factorial/AutoIt/factorial-2.autoit delete mode 100644 Task/Factorial/COBOL/factorial-1.cobol delete mode 100644 Task/Factorial/COBOL/factorial-2.cobol delete mode 100644 Task/Factorial/COBOL/factorial-3.cobol delete mode 100644 Task/Factorial/COBOL/factorial-4.cobol delete mode 100644 Task/Factorial/Chapel/factorial.chapel delete mode 100644 Task/Factorial/Coq/factorial.coq delete mode 100644 Task/Factorial/Emacs-Lisp/factorial-1.l delete mode 100644 Task/Factorial/Emacs-Lisp/factorial-2.l delete mode 100644 Task/Factorial/Emacs-Lisp/factorial-3.l delete mode 100644 Task/Factorial/Euphoria/factorial-1.ex delete mode 100644 Task/Factorial/Euphoria/factorial-2.ex delete mode 100644 Task/Factorial/Euphoria/factorial-3.ex delete mode 100644 Task/Factorial/Euphoria/factorial-4.ex delete mode 100644 Task/Factorial/Haxe/factorial-1.haxe delete mode 100644 Task/Factorial/Haxe/factorial-2.haxe delete mode 100644 Task/Factorial/Haxe/factorial-3.haxe delete mode 100644 Task/Factorial/Haxe/factorial-4.haxe delete mode 100644 Task/Factorial/Haxe/factorial-5.haxe delete mode 100644 Task/Factorial/PowerShell/factorial-1.psh delete mode 100644 Task/Factorial/PowerShell/factorial-2.psh delete mode 100644 Task/Factorial/PowerShell/factorial-3.psh delete mode 100644 Task/Factorial/REBOL/factorial.rebol delete mode 100644 Task/Factorial/VBScript/factorial.vb delete mode 100644 Task/Factorial/VHDL/factorial.vhdl delete mode 100644 Task/Factorions/Ada/factorions.ada delete mode 100644 Task/Factorions/VBScript/factorions.vb delete mode 100644 Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.ada delete mode 100644 Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-1.parigp delete mode 100644 Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number-2.parigp delete mode 100644 Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vb delete mode 100644 Task/Factors-of-an-integer/Ada/factors-of-an-integer.ada delete mode 100644 Task/Factors-of-an-integer/AutoIt/factors-of-an-integer.autoit delete mode 100644 Task/Factors-of-an-integer/COBOL/factors-of-an-integer.cobol delete mode 100644 Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chapel delete mode 100644 Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-1.psh delete mode 100644 Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-2.psh delete mode 100644 Task/Fast-Fourier-transform/Ada/fast-fourier-transform-1.ada delete mode 100644 Task/Fast-Fourier-transform/Ada/fast-fourier-transform-2.ada delete mode 100644 Task/Fast-Fourier-transform/Ada/fast-fourier-transform-3.ada delete mode 100644 Task/Fast-Fourier-transform/PowerShell/fast-fourier-transform.psh delete mode 100644 Task/Feigenbaum-constant-calculation/Ada/feigenbaum-constant-calculation.ada delete mode 100644 Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-1.ada delete mode 100644 Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-2.ada delete mode 100644 Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-3.ada delete mode 100644 Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.psh delete mode 100644 Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.psh delete mode 100644 Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vb delete mode 100644 Task/Fibonacci-sequence/Ada/fibonacci-sequence-1.ada delete mode 100644 Task/Fibonacci-sequence/Ada/fibonacci-sequence-2.ada delete mode 100644 Task/Fibonacci-sequence/Ada/fibonacci-sequence-3.ada delete mode 100644 Task/Fibonacci-sequence/Ada/fibonacci-sequence-4.ada delete mode 100644 Task/Fibonacci-sequence/Arturo/fibonacci-sequence.arturo delete mode 100644 Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-1.autoit delete mode 100644 Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-2.autoit delete mode 100644 Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cobol delete mode 100644 Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cobol delete mode 100644 Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chapel delete mode 100644 Task/Fibonacci-sequence/Coq/fibonacci-sequence.coq delete mode 100644 Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.l delete mode 100644 Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.l delete mode 100644 Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.l delete mode 100644 Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-1.ex delete mode 100644 Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-2.ex delete mode 100644 Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-3.ex delete mode 100644 Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-4.ex delete mode 100644 Task/Fibonacci-sequence/Haxe/fibonacci-sequence-1.haxe delete mode 100644 Task/Fibonacci-sequence/Haxe/fibonacci-sequence-2.haxe delete mode 100644 Task/Fibonacci-sequence/Haxe/fibonacci-sequence-3.haxe delete mode 100644 Task/Fibonacci-sequence/Langur/fibonacci-sequence.langur delete mode 100644 Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-1.psh delete mode 100644 Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-2.psh delete mode 100644 Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-3.psh delete mode 100644 Task/Fibonacci-sequence/Uiua/fibonacci-sequence.uiua delete mode 100644 Task/Fibonacci-sequence/VBScript/fibonacci-sequence-1.vb delete mode 100644 Task/Fibonacci-sequence/VBScript/fibonacci-sequence-2.vb delete mode 100644 Task/Fibonacci-word/Ada/fibonacci-word.ada delete mode 100644 Task/File-extension-is-in-extensions-list/Ada/file-extension-is-in-extensions-list.ada delete mode 100644 Task/File-input-output/Ada/file-input-output-1.ada delete mode 100644 Task/File-input-output/Ada/file-input-output-2.ada delete mode 100644 Task/File-input-output/Ada/file-input-output-3.ada delete mode 100644 Task/File-input-output/Ada/file-input-output-4.ada delete mode 100644 Task/File-input-output/COBOL/file-input-output-1.cobol delete mode 100644 Task/File-input-output/COBOL/file-input-output-2.cobol delete mode 100644 Task/File-input-output/COBOL/file-input-output-3.cobol delete mode 100644 Task/File-input-output/COBOL/file-input-output-4.cobol delete mode 100644 Task/File-input-output/Emacs-Lisp/file-input-output.l delete mode 100644 Task/File-input-output/Euphoria/file-input-output-1.ex delete mode 100644 Task/File-input-output/Euphoria/file-input-output-2.ex delete mode 100644 Task/File-input-output/PowerShell/file-input-output-1.psh delete mode 100644 Task/File-input-output/PowerShell/file-input-output-2.psh delete mode 100644 Task/File-input-output/REBOL/file-input-output.rebol delete mode 100644 Task/File-input-output/VBScript/file-input-output.vb delete mode 100644 Task/File-modification-time/Ada/file-modification-time.ada delete mode 100644 Task/File-modification-time/Emacs-Lisp/file-modification-time.l delete mode 100644 Task/File-modification-time/PowerShell/file-modification-time.psh delete mode 100644 Task/File-modification-time/VBScript/file-modification-time.vb delete mode 100644 Task/File-size-distribution/Ada/file-size-distribution.ada delete mode 100644 Task/File-size/Ada/file-size.ada delete mode 100644 Task/File-size/Batch-File/file-size.bat delete mode 100644 Task/File-size/COBOL/file-size.cobol delete mode 100644 Task/File-size/Emacs-Lisp/file-size.l delete mode 100644 Task/File-size/Euphoria/file-size.ex delete mode 100644 Task/File-size/PowerShell/file-size.psh delete mode 100644 Task/File-size/REBOL/file-size.rebol delete mode 100644 Task/File-size/VBScript/file-size.vb delete mode 100644 Task/Filter/Ada/filter-1.ada delete mode 100644 Task/Filter/Ada/filter-2.ada delete mode 100644 Task/Filter/Emacs-Lisp/filter.l delete mode 100644 Task/Filter/Euphoria/filter.ex delete mode 100644 Task/Filter/PowerShell/filter.psh delete mode 100644 Task/Filter/REBOL/filter.rebol delete mode 100644 Task/Filter/VBScript/filter.vb delete mode 100644 Task/Find-common-directory-path/Ada/find-common-directory-path.ada delete mode 100644 Task/Find-common-directory-path/PowerShell/find-common-directory-path-1.psh delete mode 100644 Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.psh delete mode 100644 Task/Find-common-directory-path/VBScript/find-common-directory-path.vb delete mode 100644 Task/Find-duplicate-files/Ada/find-duplicate-files.ada delete mode 100644 Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-1.ada delete mode 100644 Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-2.ada delete mode 100644 Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-3.ada delete mode 100644 Task/Find-limit-of-recursion/Ada/find-limit-of-recursion.ada delete mode 100644 Task/Find-limit-of-recursion/AutoIt/find-limit-of-recursion.autoit delete mode 100644 Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-1.cobol delete mode 100644 Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-2.cobol delete mode 100644 Task/Find-limit-of-recursion/Emacs-Lisp/find-limit-of-recursion.l delete mode 100644 Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion.psh delete mode 100644 Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-1.vb delete mode 100644 Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-2.vb delete mode 100644 Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-1.ada delete mode 100644 Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.ada delete mode 100644 Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Emacs-Lisp/find-palindromic-numbers-in-both-binary-and-ternary-bases.l delete mode 100644 Task/Find-the-intersection-of-a-line-with-a-plane/Ada/find-the-intersection-of-a-line-with-a-plane.ada delete mode 100644 Task/Find-the-intersection-of-two-lines/Ada/find-the-intersection-of-two-lines.ada delete mode 100644 Task/Find-the-intersection-of-two-lines/Emacs-Lisp/find-the-intersection-of-two-lines.l delete mode 100644 Task/Find-the-last-Sunday-of-each-month/COBOL/find-the-last-sunday-of-each-month.cobol delete mode 100644 Task/Find-the-last-Sunday-of-each-month/Emacs-Lisp/find-the-last-sunday-of-each-month.l delete mode 100644 Task/Find-the-last-Sunday-of-each-month/Oberon-07/find-the-last-sunday-of-each-month-3.oberon delete mode 100644 Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-1.psh delete mode 100644 Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-2.psh delete mode 100644 Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-3.psh delete mode 100644 Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-4.psh delete mode 100644 Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-5.psh delete mode 100644 Task/Find-the-last-Sunday-of-each-month/REBOL/find-the-last-sunday-of-each-month.rebol delete mode 100644 Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vb delete mode 100644 Task/Find-the-missing-permutation/Ada/find-the-missing-permutation.ada delete mode 100644 Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.psh delete mode 100644 Task/Find-the-missing-permutation/VBScript/find-the-missing-permutation.vb delete mode 100644 Task/First-class-functions-Use-numbers-analogously/Ada/first-class-functions-use-numbers-analogously.ada delete mode 100644 Task/First-class-functions/Ada/first-class-functions.ada delete mode 100644 Task/First-class-functions/REBOL/first-class-functions.rebol delete mode 100644 Task/Five-weekends/Ada/five-weekends.ada delete mode 100644 Task/Five-weekends/AutoIt/five-weekends.autoit delete mode 100644 Task/Five-weekends/COBOL/five-weekends.cobol delete mode 100644 Task/Five-weekends/Euphoria/five-weekends.ex delete mode 100644 Task/Five-weekends/PowerShell/five-weekends.psh delete mode 100644 Task/Five-weekends/VBScript/five-weekends.vb delete mode 100644 Task/Fivenum/Ada/fivenum-1.ada delete mode 100644 Task/Fivenum/Ada/fivenum-2.ada delete mode 100644 Task/Fixed-length-records/Ada/fixed-length-records.ada delete mode 100644 Task/Fixed-length-records/COBOL/fixed-length-records-1.cobol delete mode 100644 Task/Fixed-length-records/COBOL/fixed-length-records-2.cobol delete mode 100644 Task/Fixed-length-records/COBOL/fixed-length-records-3.cobol delete mode 100644 Task/Fixed-length-records/REBOL/fixed-length-records.rebol delete mode 100644 Task/FizzBuzz/Ada/fizzbuzz.ada delete mode 100644 Task/FizzBuzz/AutoIt/fizzbuzz-1.autoit delete mode 100644 Task/FizzBuzz/AutoIt/fizzbuzz-2.autoit delete mode 100644 Task/FizzBuzz/COBOL/fizzbuzz-1.cobol delete mode 100644 Task/FizzBuzz/COBOL/fizzbuzz-2.cobol delete mode 100644 Task/FizzBuzz/COBOL/fizzbuzz-3.cobol delete mode 100644 Task/FizzBuzz/COBOL/fizzbuzz-4.cobol delete mode 100644 Task/FizzBuzz/Chapel/fizzbuzz.chapel delete mode 100644 Task/FizzBuzz/Coq/fizzbuzz.coq delete mode 100644 Task/FizzBuzz/Emacs-Lisp/fizzbuzz.l delete mode 100644 Task/FizzBuzz/Euphoria/fizzbuzz.ex delete mode 100644 Task/FizzBuzz/PowerShell/fizzbuzz-1.psh delete mode 100644 Task/FizzBuzz/PowerShell/fizzbuzz-2.psh delete mode 100644 Task/FizzBuzz/PowerShell/fizzbuzz-3.psh delete mode 100644 Task/FizzBuzz/PowerShell/fizzbuzz-4.psh delete mode 100644 Task/FizzBuzz/PowerShell/fizzbuzz-5.psh delete mode 100644 Task/FizzBuzz/PowerShell/fizzbuzz-6.psh delete mode 100644 Task/FizzBuzz/REBOL/fizzbuzz-1.rebol delete mode 100644 Task/FizzBuzz/REBOL/fizzbuzz-2.rebol delete mode 100644 Task/FizzBuzz/REBOL/fizzbuzz-3.rebol delete mode 100644 Task/FizzBuzz/REBOL/fizzbuzz-4.rebol delete mode 100644 Task/FizzBuzz/VBScript/fizzbuzz-1.vb delete mode 100644 Task/FizzBuzz/VBScript/fizzbuzz-2.vb delete mode 100644 Task/FizzBuzz/VHDL/fizzbuzz.vhdl delete mode 100644 Task/Flatten-a-list/Ada/flatten-a-list-1.ada delete mode 100644 Task/Flatten-a-list/Ada/flatten-a-list-2.ada delete mode 100644 Task/Flatten-a-list/Ada/flatten-a-list-3.ada delete mode 100644 Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-1.l delete mode 100644 Task/Flatten-a-list/Emacs-Lisp/flatten-a-list-2.l delete mode 100644 Task/Flatten-a-list/Euphoria/flatten-a-list.ex delete mode 100644 Task/Flatten-a-list/PowerShell/flatten-a-list.psh delete mode 100644 Task/Flatten-a-list/REBOL/flatten-a-list.rebol delete mode 100644 Task/Flatten-a-list/VBScript/flatten-a-list-1.vb delete mode 100644 Task/Flatten-a-list/VBScript/flatten-a-list-2.vb delete mode 100644 Task/Flatten-a-list/VBScript/flatten-a-list-3.vb delete mode 100644 Task/Flipping-bits-game/Ada/flipping-bits-game.ada delete mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-1.ada delete mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-2.ada delete mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-3.ada delete mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-4.ada delete mode 100644 Task/Flow-control-structures/Ada/flow-control-structures-5.ada delete mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-1.cobol delete mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-2.cobol delete mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-3.cobol delete mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-4.cobol delete mode 100644 Task/Flow-control-structures/COBOL/flow-control-structures-5.cobol delete mode 100644 Task/Flow-control-structures/REBOL/flow-control-structures.rebol delete mode 100644 Task/Floyd-Warshall-algorithm/Ada/floyd-warshall-algorithm.ada delete mode 100644 Task/Floyds-triangle/Ada/floyds-triangle.ada delete mode 100644 Task/Floyds-triangle/COBOL/floyds-triangle.cobol delete mode 100644 Task/Floyds-triangle/VBScript/floyds-triangle.vb delete mode 100644 Task/Forest-fire/Ada/forest-fire.ada delete mode 100644 Task/Forest-fire/COBOL/forest-fire.cobol delete mode 100644 Task/Forest-fire/Emacs-Lisp/forest-fire-1.l delete mode 100644 Task/Forest-fire/Emacs-Lisp/forest-fire-2.l delete mode 100644 Task/Fork/Ada/fork.ada delete mode 100644 Task/Fork/Batch-File/fork.bat delete mode 100644 Task/Fork/COBOL/fork.cobol delete mode 100644 Task/Formal-power-series/Ada/formal-power-series-1.ada delete mode 100644 Task/Formal-power-series/Ada/formal-power-series-2.ada delete mode 100644 Task/Formal-power-series/Ada/formal-power-series-3.ada delete mode 100644 Task/Formatted-numeric-output/Ada/formatted-numeric-output.ada delete mode 100644 Task/Formatted-numeric-output/COBOL/formatted-numeric-output.cobol delete mode 100644 Task/Formatted-numeric-output/Emacs-Lisp/formatted-numeric-output.l delete mode 100644 Task/Formatted-numeric-output/Euphoria/formatted-numeric-output.ex delete mode 100644 Task/Formatted-numeric-output/Logo/formatted-numeric-output-1.logo delete mode 100644 Task/Formatted-numeric-output/Logo/formatted-numeric-output-2.logo delete mode 100644 Task/Formatted-numeric-output/PowerShell/formatted-numeric-output-1.psh delete mode 100644 Task/Formatted-numeric-output/PowerShell/formatted-numeric-output-2.psh delete mode 100644 Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol delete mode 100644 Task/Formatted-numeric-output/VBScript/formatted-numeric-output.vb delete mode 100644 Task/Forward-difference/Ada/forward-difference.ada delete mode 100644 Task/Forward-difference/PowerShell/forward-difference.psh delete mode 100644 Task/Four-bit-adder/Ada/four-bit-adder-1.ada delete mode 100644 Task/Four-bit-adder/Ada/four-bit-adder-2.ada delete mode 100644 Task/Four-bit-adder/AutoIt/four-bit-adder-1.autoit delete mode 100644 Task/Four-bit-adder/AutoIt/four-bit-adder-2.autoit delete mode 100644 Task/Four-bit-adder/COBOL/four-bit-adder.cobol delete mode 100644 Task/Four-bit-adder/Perl/four-bit-adder.pl delete mode 100644 Task/Four-bit-adder/PowerShell/four-bit-adder-1.psh delete mode 100644 Task/Four-bit-adder/PowerShell/four-bit-adder-2.psh delete mode 100644 Task/Four-bit-adder/PowerShell/four-bit-adder-3.psh delete mode 100644 Task/Four-bit-adder/VHDL/four-bit-adder-1.vhdl delete mode 100644 Task/Four-bit-adder/VHDL/four-bit-adder-2.vhdl delete mode 100644 Task/Fractal-tree/Ada/fractal-tree.ada delete mode 100644 Task/Fractal-tree/Red/fractal-tree.red delete mode 100644 Task/Fraction-reduction/Ada/fraction-reduction.ada delete mode 100644 Task/Fractran/Ada/fractran.ada delete mode 100644 Task/Function-composition/Ada/function-composition-1.ada delete mode 100644 Task/Function-composition/Ada/function-composition-2.ada delete mode 100644 Task/Function-composition/Ada/function-composition-3.ada delete mode 100644 Task/Function-composition/Emacs-Lisp/function-composition-1.l delete mode 100644 Task/Function-composition/Emacs-Lisp/function-composition-2.l delete mode 100644 Task/Function-composition/Emacs-Lisp/function-composition-3.l delete mode 100644 Task/Function-composition/PowerShell/function-composition-1.psh delete mode 100644 Task/Function-composition/PowerShell/function-composition-2.psh delete mode 100644 Task/Function-composition/REBOL/function-composition-1.rebol delete mode 100644 Task/Function-composition/REBOL/function-composition-2.rebol delete mode 100644 Task/Function-composition/VBScript/function-composition-1.vb delete mode 100644 Task/Function-composition/VBScript/function-composition-2.vb delete mode 100644 Task/Function-definition/Ada/function-definition-1.ada delete mode 100644 Task/Function-definition/Ada/function-definition-2.ada delete mode 100644 Task/Function-definition/Ada/function-definition-3.ada delete mode 100644 Task/Function-definition/Ada/function-definition-4.ada delete mode 100644 Task/Function-definition/Ada/function-definition-5.ada delete mode 100644 Task/Function-definition/Ada/function-definition-6.ada delete mode 100644 Task/Function-definition/AutoIt/function-definition.autoit delete mode 100644 Task/Function-definition/COBOL/function-definition-1.cobol delete mode 100644 Task/Function-definition/COBOL/function-definition-2.cobol delete mode 100644 Task/Function-definition/Chapel/function-definition-1.chapel delete mode 100644 Task/Function-definition/Chapel/function-definition-2.chapel delete mode 100644 Task/Function-definition/Emacs-Lisp/function-definition-1.l delete mode 100644 Task/Function-definition/Emacs-Lisp/function-definition-2.l delete mode 100644 Task/Function-definition/Euphoria/function-definition-1.ex delete mode 100644 Task/Function-definition/Euphoria/function-definition-2.ex delete mode 100644 Task/Function-definition/Haxe/function-definition.haxe delete mode 100644 Task/Function-definition/PowerShell/function-definition-1.psh delete mode 100644 Task/Function-definition/PowerShell/function-definition-2.psh delete mode 100644 Task/Function-definition/PowerShell/function-definition-3.psh delete mode 100644 Task/Function-definition/PowerShell/function-definition-4.psh delete mode 100644 Task/Function-definition/PowerShell/function-definition-5.psh delete mode 100644 Task/Function-definition/REBOL/function-definition.rebol delete mode 100644 Task/Function-definition/REXX/function-definition-1.rexx delete mode 100644 Task/Function-definition/REXX/function-definition-2.rexx delete mode 100644 Task/Function-definition/VBScript/function-definition-1.vb delete mode 100644 Task/Function-definition/VBScript/function-definition-2.vb delete mode 100644 Task/Function-prototype/Ada/function-prototype-1.ada delete mode 100644 Task/Function-prototype/Ada/function-prototype-2.ada delete mode 100644 Task/Function-prototype/Ada/function-prototype-3.ada delete mode 100644 Task/Function-prototype/Ada/function-prototype-4.ada delete mode 100644 Task/Function-prototype/Ada/function-prototype-5.ada delete mode 100644 Task/Function-prototype/COBOL/function-prototype.cobol delete mode 100644 Task/Fusc-sequence/Ada/fusc-sequence.ada delete mode 100644 Task/GUI-Maximum-window-dimensions/Ada/gui-maximum-window-dimensions.ada delete mode 100644 Task/GUI-component-interaction/Ada/gui-component-interaction.ada delete mode 100644 Task/GUI-component-interaction/Euphoria/gui-component-interaction.ex delete mode 100644 Task/GUI-component-interaction/PowerShell/gui-component-interaction.psh delete mode 100644 Task/GUI-enabling-disabling-of-controls/Ada/gui-enabling-disabling-of-controls.ada delete mode 100644 Task/Gamma-function/Ada/gamma-function-1.ada delete mode 100644 Task/Gamma-function/Ada/gamma-function-2.ada delete mode 100644 Task/Gamma-function/Pascal/gamma-function.pas delete mode 100644 Task/Gamma-function/PowerShell/gamma-function.psh delete mode 100644 Task/Gamma-function/XPL0/gamma-function.xpl0 delete mode 100644 Task/Gapful-numbers/Ada/gapful-numbers.ada delete mode 100644 Task/Gapful-numbers/COBOL/gapful-numbers.cobol delete mode 100644 Task/Gapful-numbers/PowerShell/gapful-numbers.psh delete mode 100644 Task/Gauss-Jordan-matrix-inversion/PowerShell/gauss-jordan-matrix-inversion.psh delete mode 100644 Task/Gauss-Jordan-matrix-inversion/VBScript/gauss-jordan-matrix-inversion.vb delete mode 100644 Task/Gaussian-elimination/Ada/gaussian-elimination.ada delete mode 100644 Task/Gaussian-elimination/PowerShell/gaussian-elimination-1.psh delete mode 100644 Task/Gaussian-elimination/PowerShell/gaussian-elimination-2.psh delete mode 100644 Task/Gaussian-elimination/VBScript/gaussian-elimination.vb delete mode 100644 Task/General-FizzBuzz/Ada/general-fizzbuzz.ada delete mode 100644 Task/General-FizzBuzz/PowerShell/general-fizzbuzz.psh delete mode 100644 Task/General-FizzBuzz/VBScript/general-fizzbuzz.vb delete mode 100644 Task/Generate-Chess960-starting-position/PowerShell/generate-chess960-starting-position.psh delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-1.ada delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-2.ada delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-3.ada delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/Ada/generate-lower-case-ascii-alphabet-4.ada delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/AutoIt/generate-lower-case-ascii-alphabet.autoit delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/COBOL/generate-lower-case-ascii-alphabet.cobol delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/PowerShell/generate-lower-case-ascii-alphabet-1.psh delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/PowerShell/generate-lower-case-ascii-alphabet-2.psh delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/PowerShell/generate-lower-case-ascii-alphabet-3.psh delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/PowerShell/generate-lower-case-ascii-alphabet-4.psh delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/VBScript/generate-lower-case-ascii-alphabet.vb delete mode 100644 Task/Generator-Exponential/Ada/generator-exponential-1.ada delete mode 100644 Task/Generator-Exponential/Ada/generator-exponential-2.ada delete mode 100644 Task/Generator-Exponential/Ada/generator-exponential-3.ada delete mode 100644 Task/Generator-Exponential/Ada/generator-exponential-4.ada delete mode 100644 Task/Generator-Exponential/Ada/generator-exponential-5.ada delete mode 100644 Task/Generator-Exponential/Emacs-Lisp/generator-exponential.l delete mode 100644 Task/Generic-swap/Ada/generic-swap-1.ada delete mode 100644 Task/Generic-swap/Ada/generic-swap-2.ada delete mode 100644 Task/Generic-swap/COBOL/generic-swap.cobol delete mode 100644 Task/Generic-swap/Chapel/generic-swap-1.chapel delete mode 100644 Task/Generic-swap/Chapel/generic-swap-2.chapel delete mode 100644 Task/Generic-swap/Emacs-Lisp/generic-swap-1.l delete mode 100644 Task/Generic-swap/Emacs-Lisp/generic-swap-2.l delete mode 100644 Task/Generic-swap/Emacs-Lisp/generic-swap-3.l delete mode 100644 Task/Generic-swap/Euphoria/generic-swap.ex delete mode 100644 Task/Generic-swap/PowerShell/generic-swap-1.psh delete mode 100644 Task/Generic-swap/PowerShell/generic-swap-2.psh delete mode 100644 Task/Generic-swap/PowerShell/generic-swap-3.psh delete mode 100644 Task/Generic-swap/REBOL/generic-swap.rebol delete mode 100644 Task/Generic-swap/VBScript/generic-swap-1.vb delete mode 100644 Task/Generic-swap/VBScript/generic-swap-2.vb delete mode 100644 Task/Generic-swap/VBScript/generic-swap-3.vb delete mode 100644 Task/Get-system-command-output/Ada/get-system-command-output.ada delete mode 100644 Task/Get-system-command-output/PowerShell/get-system-command-output.psh delete mode 100644 Task/Get-system-command-output/VBScript/get-system-command-output.vb delete mode 100644 Task/Giuga-numbers/Ada/giuga-numbers.ada delete mode 100644 Task/Globally-replace-text-in-several-files/Ada/globally-replace-text-in-several-files.ada delete mode 100644 Task/Globally-replace-text-in-several-files/PowerShell/globally-replace-text-in-several-files.psh delete mode 100644 Task/Globally-replace-text-in-several-files/VBScript/globally-replace-text-in-several-files.vb delete mode 100644 Task/Goldbachs-comet/Pluto/goldbachs-comet.pluto delete mode 100644 Task/Golden-ratio-Convergence/Ada/golden-ratio-convergence.ada delete mode 100644 Task/Golden-ratio-Convergence/COBOL/golden-ratio-convergence.cobol delete mode 100644 Task/Gray-code/Ada/gray-code.ada delete mode 100644 Task/Gray-code/Euphoria/gray-code.ex delete mode 100644 Task/Gray-code/VBScript/gray-code.vb delete mode 100644 Task/Gray-code/VHDL/gray-code-1.vhdl delete mode 100644 Task/Gray-code/VHDL/gray-code-2.vhdl delete mode 100644 Task/Grayscale-image/Ada/grayscale-image-1.ada delete mode 100644 Task/Grayscale-image/Ada/grayscale-image-2.ada delete mode 100644 Task/Grayscale-image/Ada/grayscale-image-3.ada delete mode 100644 Task/Grayscale-image/Euphoria/grayscale-image.ex delete mode 100644 Task/Greatest-common-divisor/Ada/greatest-common-divisor.ada delete mode 100644 Task/Greatest-common-divisor/AutoIt/greatest-common-divisor.autoit delete mode 100644 Task/Greatest-common-divisor/COBOL/greatest-common-divisor.cobol delete mode 100644 Task/Greatest-common-divisor/Emacs-Lisp/greatest-common-divisor.l delete mode 100644 Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-1.ex delete mode 100644 Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-2.ex delete mode 100644 Task/Greatest-common-divisor/Euphoria/greatest-common-divisor-3.ex delete mode 100644 Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.psh delete mode 100644 Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.psh delete mode 100644 Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.psh delete mode 100644 Task/Greatest-common-divisor/REBOL/greatest-common-divisor.rebol delete mode 100644 Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb delete mode 100644 Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada delete mode 100644 Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-2.ada delete mode 100644 Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-3.ada delete mode 100644 Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-1.cobol delete mode 100644 Task/Greatest-element-of-a-list/COBOL/greatest-element-of-a-list-2.cobol delete mode 100644 Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-1.l delete mode 100644 Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-2.l delete mode 100644 Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l delete mode 100644 Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-4.l delete mode 100644 Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-1.ex delete mode 100644 Task/Greatest-element-of-a-list/Euphoria/greatest-element-of-a-list-2.ex delete mode 100644 Task/Greatest-element-of-a-list/PowerShell/greatest-element-of-a-list.psh delete mode 100644 Task/Greatest-element-of-a-list/REBOL/greatest-element-of-a-list.rebol delete mode 100644 Task/Greatest-element-of-a-list/VBScript/greatest-element-of-a-list.vb delete mode 100644 Task/Greatest-subsequential-sum/Ada/greatest-subsequential-sum.ada delete mode 100644 Task/Greatest-subsequential-sum/AutoIt/greatest-subsequential-sum.autoit delete mode 100644 Task/Greatest-subsequential-sum/Euphoria/greatest-subsequential-sum.ex delete mode 100644 Task/Greyscale-bars-Display/Ada/greyscale-bars-display.ada delete mode 100644 Task/Guess-the-number-With-feedback-player-/Ada/guess-the-number-with-feedback-player-.ada delete mode 100644 Task/Guess-the-number-With-feedback-player-/Euphoria/guess-the-number-with-feedback-player-.ex delete mode 100644 Task/Guess-the-number-With-feedback/Ada/guess-the-number-with-feedback.ada delete mode 100644 Task/Guess-the-number-With-feedback/COBOL/guess-the-number-with-feedback.cobol delete mode 100644 Task/Guess-the-number-With-feedback/Emacs-Lisp/guess-the-number-with-feedback.l delete mode 100644 Task/Guess-the-number-With-feedback/Euphoria/guess-the-number-with-feedback.ex delete mode 100644 Task/Guess-the-number-With-feedback/PowerShell/guess-the-number-with-feedback.psh delete mode 100644 Task/Guess-the-number-With-feedback/VBScript/guess-the-number-with-feedback.vb delete mode 100644 Task/Guess-the-number/Ada/guess-the-number.ada delete mode 100644 Task/Guess-the-number/AutoIt/guess-the-number.autoit delete mode 100644 Task/Guess-the-number/COBOL/guess-the-number.cobol delete mode 100644 Task/Guess-the-number/Emacs-Lisp/guess-the-number.l delete mode 100644 Task/Guess-the-number/Euphoria/guess-the-number.ex delete mode 100644 Task/Guess-the-number/PowerShell/guess-the-number-1.psh delete mode 100644 Task/Guess-the-number/PowerShell/guess-the-number-2.psh delete mode 100644 Task/Guess-the-number/VBScript/guess-the-number.vb delete mode 100644 Task/HTTP/Ada/http.ada delete mode 100644 Task/HTTP/COBOL/http-1.cobol delete mode 100644 Task/HTTP/COBOL/http-2.cobol delete mode 100644 Task/HTTP/Emacs-Lisp/http-1.l delete mode 100644 Task/HTTP/Emacs-Lisp/http-2.l delete mode 100644 Task/HTTP/PowerShell/http-1.psh delete mode 100644 Task/HTTP/PowerShell/http-2.psh delete mode 100644 Task/HTTP/REBOL/http.rebol delete mode 100644 Task/HTTP/VBScript/http.vb delete mode 100644 Task/HTTPS-Authenticated/PowerShell/https-authenticated.psh delete mode 100644 Task/HTTPS/Ada/https.ada delete mode 100644 Task/HTTPS/PowerShell/https-1.psh delete mode 100644 Task/HTTPS/PowerShell/https-2.psh delete mode 100644 Task/HTTPS/VBScript/https.vb delete mode 100644 Task/Hailstone-sequence/Ada/hailstone-sequence-1.ada delete mode 100644 Task/Hailstone-sequence/Ada/hailstone-sequence-2.ada delete mode 100644 Task/Hailstone-sequence/Ada/hailstone-sequence-3.ada delete mode 100644 Task/Hailstone-sequence/Ada/hailstone-sequence-4.ada delete mode 100644 Task/Hailstone-sequence/AutoIt/hailstone-sequence.autoit delete mode 100644 Task/Hailstone-sequence/COBOL/hailstone-sequence.cobol delete mode 100644 Task/Hailstone-sequence/Euphoria/hailstone-sequence.ex delete mode 100644 Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh delete mode 100644 Task/Hailstone-sequence/REBOL/hailstone-sequence.rebol delete mode 100644 Task/Hailstone-sequence/VBScript/hailstone-sequence.vb delete mode 100644 Task/Halt-and-catch-fire/Ada/halt-and-catch-fire.ada delete mode 100644 Task/Hamming-numbers/Ada/hamming-numbers.ada delete mode 100644 Task/Hamming-numbers/Chapel/hamming-numbers-1.chapel delete mode 100644 Task/Hamming-numbers/Chapel/hamming-numbers-2.chapel delete mode 100644 Task/Hamming-numbers/Chapel/hamming-numbers-3.chapel delete mode 100644 Task/Hamming-numbers/Chapel/hamming-numbers-4.chapel delete mode 100644 Task/Hamming-numbers/Chapel/hamming-numbers-5.chapel delete mode 100644 Task/Hamming-numbers/VBScript/hamming-numbers.vb delete mode 100644 Task/Handle-a-signal/Ada/handle-a-signal-1.ada delete mode 100644 Task/Handle-a-signal/Ada/handle-a-signal-2.ada delete mode 100644 Task/Handle-a-signal/Ada/handle-a-signal-3.ada delete mode 100644 Task/Handle-a-signal/COBOL/handle-a-signal.cobol delete mode 100644 Task/Handle-a-signal/PowerShell/handle-a-signal.psh delete mode 100644 Task/Happy-numbers/Ada/happy-numbers.ada delete mode 100644 Task/Happy-numbers/AutoIt/happy-numbers-1.autoit delete mode 100644 Task/Happy-numbers/AutoIt/happy-numbers-2.autoit delete mode 100644 Task/Happy-numbers/COBOL/happy-numbers.cobol delete mode 100644 Task/Happy-numbers/Euphoria/happy-numbers.ex delete mode 100644 Task/Happy-numbers/PowerShell/happy-numbers-1.psh delete mode 100644 Task/Happy-numbers/PowerShell/happy-numbers-2.psh delete mode 100644 Task/Happy-numbers/VBScript/happy-numbers.vb delete mode 100644 Task/Harmonic-series/Ada/harmonic-series.ada delete mode 100644 Task/Harmonic-series/COBOL/harmonic-series.cobol delete mode 100644 Task/Harshad-or-Niven-series/Ada/harshad-or-niven-series.ada delete mode 100644 Task/Harshad-or-Niven-series/COBOL/harshad-or-niven-series.cobol delete mode 100644 Task/Harshad-or-Niven-series/PowerShell/harshad-or-niven-series-1.psh delete mode 100644 Task/Harshad-or-Niven-series/PowerShell/harshad-or-niven-series-2.psh delete mode 100644 Task/Harshad-or-Niven-series/PowerShell/harshad-or-niven-series-3.psh delete mode 100644 Task/Harshad-or-Niven-series/VBScript/harshad-or-niven-series.vb delete mode 100644 Task/Hash-from-two-arrays/Ada/hash-from-two-arrays.ada delete mode 100644 Task/Hash-from-two-arrays/Emacs-Lisp/hash-from-two-arrays.l delete mode 100644 Task/Hash-from-two-arrays/PowerShell/hash-from-two-arrays.psh delete mode 100644 Task/Hash-from-two-arrays/VBScript/hash-from-two-arrays.vb delete mode 100644 Task/Hash-join/Emacs-Lisp/hash-join.l delete mode 100644 Task/Hash-join/VBScript/hash-join.vb delete mode 100644 Task/Haversine-formula/Ada/haversine-formula.ada delete mode 100644 Task/Haversine-formula/PowerShell/haversine-formula-1.psh delete mode 100644 Task/Haversine-formula/PowerShell/haversine-formula-2.psh delete mode 100644 Task/Hello-world-Graphical/Ada/hello-world-graphical.ada delete mode 100644 Task/Hello-world-Graphical/AutoIt/hello-world-graphical-1.autoit delete mode 100644 Task/Hello-world-Graphical/AutoIt/hello-world-graphical-2.autoit delete mode 100644 Task/Hello-world-Graphical/AutoIt/hello-world-graphical-3.autoit delete mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-1.cobol delete mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-2.cobol delete mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-3.cobol delete mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-4.cobol delete mode 100644 Task/Hello-world-Graphical/COBOL/hello-world-graphical-5.cobol delete mode 100644 Task/Hello-world-Graphical/Emacs-Lisp/hello-world-graphical.l delete mode 100644 Task/Hello-world-Graphical/Euphoria/hello-world-graphical.ex delete mode 100644 Task/Hello-world-Graphical/PowerShell/hello-world-graphical-1.psh delete mode 100644 Task/Hello-world-Graphical/PowerShell/hello-world-graphical-2.psh delete mode 100644 Task/Hello-world-Graphical/PowerShell/hello-world-graphical-3.psh delete mode 100644 Task/Hello-world-Graphical/REBOL/hello-world-graphical.rebol delete mode 100644 Task/Hello-world-Graphical/VBScript/hello-world-graphical.vb delete mode 100644 Task/Hello-world-Line-printer/360-Assembly/hello-world-line-printer.360 delete mode 100644 Task/Hello-world-Line-printer/Ada/hello-world-line-printer.ada delete mode 100644 Task/Hello-world-Line-printer/COBOL/hello-world-line-printer.cobol delete mode 100644 Task/Hello-world-Newbie/Ada/hello-world-newbie-1.ada delete mode 100644 Task/Hello-world-Newbie/Ada/hello-world-newbie-2.ada delete mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-1.cobol delete mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-2.cobol delete mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-3.cobol delete mode 100644 Task/Hello-world-Newbie/COBOL/hello-world-newbie-4.cobol delete mode 100644 Task/Hello-world-Newbie/Coq/hello-world-newbie-1.coq delete mode 100644 Task/Hello-world-Newbie/Coq/hello-world-newbie-2.coq delete mode 100644 Task/Hello-world-Newbie/Phix/hello-world-newbie-3.phix delete mode 100644 Task/Hello-world-Newbie/Phix/hello-world-newbie-4.phix delete mode 100644 Task/Hello-world-Newbie/PowerShell/hello-world-newbie-1.psh delete mode 100644 Task/Hello-world-Newbie/PowerShell/hello-world-newbie-2.psh delete mode 100644 Task/Hello-world-Newbie/PowerShell/hello-world-newbie-3.psh delete mode 100644 Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-1.ada delete mode 100644 Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-2.ada delete mode 100644 Task/Hello-world-Newline-omission/AutoIt/hello-world-newline-omission.autoit delete mode 100644 Task/Hello-world-Newline-omission/COBOL/hello-world-newline-omission.cobol delete mode 100644 Task/Hello-world-Newline-omission/Emacs-Lisp/hello-world-newline-omission.l delete mode 100644 Task/Hello-world-Newline-omission/Euphoria/hello-world-newline-omission.ex delete mode 100644 Task/Hello-world-Newline-omission/PowerShell/hello-world-newline-omission.psh delete mode 100644 Task/Hello-world-Newline-omission/REBOL/hello-world-newline-omission.rebol delete mode 100644 Task/Hello-world-Standard-error/Ada/hello-world-standard-error.ada delete mode 100644 Task/Hello-world-Standard-error/AutoIt/hello-world-standard-error.autoit delete mode 100644 Task/Hello-world-Standard-error/COBOL/hello-world-standard-error.cobol delete mode 100644 Task/Hello-world-Standard-error/Emacs-Lisp/hello-world-standard-error-1.l delete mode 100644 Task/Hello-world-Standard-error/Emacs-Lisp/hello-world-standard-error-2.l delete mode 100644 Task/Hello-world-Standard-error/Euphoria/hello-world-standard-error.ex delete mode 100644 Task/Hello-world-Standard-error/PowerShell/hello-world-standard-error-1.psh delete mode 100644 Task/Hello-world-Standard-error/PowerShell/hello-world-standard-error-2.psh delete mode 100644 Task/Hello-world-Standard-error/VBScript/hello-world-standard-error.vb delete mode 100644 Task/Hello-world-Text/Ada/hello-world-text.ada delete mode 100644 Task/Hello-world-Text/AutoIt/hello-world-text.autoit delete mode 100644 Task/Hello-world-Text/AutoLISP/hello-world-text.l delete mode 100644 Task/Hello-world-Text/COBOL/hello-world-text-1.cobol delete mode 100644 Task/Hello-world-Text/COBOL/hello-world-text-2.cobol delete mode 100644 Task/Hello-world-Text/Chapel/hello-world-text.chapel delete mode 100644 Task/Hello-world-Text/Coq/hello-world-text.coq delete mode 100644 Task/Hello-world-Text/Emacs-Lisp/hello-world-text-1.l delete mode 100644 Task/Hello-world-Text/Emacs-Lisp/hello-world-text-2.l delete mode 100644 Task/Hello-world-Text/Haxe/hello-world-text.haxe delete mode 100644 Task/Hello-world-Text/PowerShell/hello-world-text.psh delete mode 100644 Task/Hello-world-Text/REBOL/hello-world-text.rebol delete mode 100644 Task/Hello-world-Text/ReScript/hello-world-text.re delete mode 100644 Task/Hello-world-Text/VBScript/hello-world-text.vb delete mode 100644 Task/Hello-world-Text/VHDL/hello-world-text.vhdl delete mode 100644 Task/Hello-world-Web-server/Ada/hello-world-web-server.ada delete mode 100644 Task/Hello-world-Web-server/AutoIt/hello-world-web-server.autoit delete mode 100644 Task/Here-document/Ada/here-document.ada delete mode 100644 Task/Here-document/PowerShell/here-document.psh delete mode 100644 Task/Here-document/VBScript/here-document.vb delete mode 100644 Task/Heronian-triangles/Ada/heronian-triangles.ada delete mode 100644 Task/Heronian-triangles/PowerShell/heronian-triangles-1.psh delete mode 100644 Task/Heronian-triangles/PowerShell/heronian-triangles-2.psh delete mode 100644 Task/Hex-words/Ada/hex-words.ada delete mode 100644 Task/Hickerson-series-of-almost-integers/Ada/hickerson-series-of-almost-integers.ada delete mode 100644 Task/Hickerson-series-of-almost-integers/COBOL/hickerson-series-of-almost-integers.cobol delete mode 100644 Task/Higher-order-functions/Ada/higher-order-functions-1.ada delete mode 100644 Task/Higher-order-functions/Ada/higher-order-functions-2.ada delete mode 100644 Task/Higher-order-functions/Euphoria/higher-order-functions.ex delete mode 100644 Task/Higher-order-functions/PowerShell/higher-order-functions-1.psh delete mode 100644 Task/Higher-order-functions/PowerShell/higher-order-functions-2.psh delete mode 100644 Task/Higher-order-functions/PowerShell/higher-order-functions-3.psh delete mode 100644 Task/Higher-order-functions/REBOL/higher-order-functions.rebol delete mode 100644 Task/Hilbert-curve/Ada/hilbert-curve.ada delete mode 100644 Task/Hilbert-curve/VBScript/hilbert-curve.vb delete mode 100644 Task/History-variables/Ada/history-variables-1.ada delete mode 100644 Task/History-variables/Ada/history-variables-2.ada delete mode 100644 Task/History-variables/Ada/history-variables-3.ada delete mode 100644 Task/History-variables/Ada/history-variables-4.ada delete mode 100644 Task/Hofstadter-Conway-$10-000-sequence/Ada/hofstadter-conway-$10-000-sequence.ada delete mode 100644 Task/Hofstadter-Figure-Figure-sequences/Ada/hofstadter-figure-figure-sequences-1.ada delete mode 100644 Task/Hofstadter-Figure-Figure-sequences/Ada/hofstadter-figure-figure-sequences-2.ada delete mode 100644 Task/Hofstadter-Figure-Figure-sequences/Ada/hofstadter-figure-figure-sequences-3.ada delete mode 100644 Task/Hofstadter-Figure-Figure-sequences/Ada/hofstadter-figure-figure-sequences-4.ada delete mode 100644 Task/Hofstadter-Figure-Figure-sequences/VBScript/hofstadter-figure-figure-sequences.vb delete mode 100644 Task/Hofstadter-Q-sequence/Ada/hofstadter-q-sequence.ada delete mode 100644 Task/Hofstadter-Q-sequence/COBOL/hofstadter-q-sequence.cobol delete mode 100644 Task/Hofstadter-Q-sequence/VBScript/hofstadter-q-sequence.vb delete mode 100644 Task/Holidays-related-to-Easter/Ada/holidays-related-to-easter.ada delete mode 100644 Task/Holidays-related-to-Easter/COBOL/holidays-related-to-easter.cobol delete mode 100644 Task/Holidays-related-to-Easter/PowerShell/holidays-related-to-easter-1.psh delete mode 100644 Task/Holidays-related-to-Easter/PowerShell/holidays-related-to-easter-2.psh delete mode 100644 Task/Honeycombs/Ada/honeycombs.ada delete mode 100644 Task/Horizontal-sundial-calculations/Ada/horizontal-sundial-calculations.ada delete mode 100644 Task/Horizontal-sundial-calculations/COBOL/horizontal-sundial-calculations.cobol delete mode 100644 Task/Horizontal-sundial-calculations/Euphoria/horizontal-sundial-calculations.ex delete mode 100644 Task/Horizontal-sundial-calculations/PowerShell/horizontal-sundial-calculations.psh delete mode 100644 Task/Horners-rule-for-polynomial-evaluation/Ada/horners-rule-for-polynomial-evaluation.ada delete mode 100644 Task/Horners-rule-for-polynomial-evaluation/Emacs-Lisp/horners-rule-for-polynomial-evaluation.l delete mode 100644 Task/Horners-rule-for-polynomial-evaluation/PowerShell/horners-rule-for-polynomial-evaluation.psh delete mode 100644 Task/Horners-rule-for-polynomial-evaluation/REBOL/horners-rule-for-polynomial-evaluation.rebol delete mode 100644 Task/Horners-rule-for-polynomial-evaluation/VBScript/horners-rule-for-polynomial-evaluation.vb delete mode 100644 Task/Host-introspection/Ada/host-introspection.ada delete mode 100644 Task/Host-introspection/PowerShell/host-introspection.psh delete mode 100644 Task/Hostname/Ada/hostname.ada delete mode 100644 Task/Hostname/Batch-File/hostname.bat delete mode 100644 Task/Hostname/COBOL/hostname.cobol delete mode 100644 Task/Hostname/Emacs-Lisp/hostname.l delete mode 100644 Task/Hostname/PowerShell/hostname-1.psh delete mode 100644 Task/Hostname/PowerShell/hostname-2.psh delete mode 100644 Task/Hostname/REBOL/hostname.rebol delete mode 100644 Task/Hostname/VBScript/hostname.vb delete mode 100644 Task/Huffman-coding/Ada/huffman-coding-1.ada delete mode 100644 Task/Huffman-coding/Ada/huffman-coding-2.ada delete mode 100644 Task/Huffman-coding/Ada/huffman-coding-3.ada delete mode 100644 Task/Huffman-coding/PowerShell/huffman-coding.psh delete mode 100644 Task/Humble-numbers/Ada/humble-numbers.ada delete mode 100644 Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-1.ada delete mode 100644 Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-2.ada delete mode 100644 Task/Hunt-the-Wumpus/Ada/hunt-the-wumpus-3.ada delete mode 100644 Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh delete mode 100644 Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-1.rexx delete mode 100644 Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c-2.rexx delete mode 100644 Task/I-before-E-except-after-C/VBScript/i-before-e-except-after-c.vb delete mode 100644 Task/IBAN/Ada/iban-1.ada delete mode 100644 Task/IBAN/Ada/iban-2.ada delete mode 100644 Task/IBAN/Ada/iban-3.ada delete mode 100644 Task/IBAN/COBOL/iban.cobol delete mode 100644 Task/IBAN/PowerShell/iban-1.psh delete mode 100644 Task/IBAN/PowerShell/iban-2.psh delete mode 100644 Task/IBAN/PowerShell/iban-3.psh delete mode 100644 Task/IBAN/VBScript/iban.vb delete mode 100644 Task/ISBN13-check-digit/Ada/isbn13-check-digit.ada delete mode 100644 Task/ISBN13-check-digit/COBOL/isbn13-check-digit.cobol delete mode 100644 Task/ISBN13-check-digit/PowerShell/isbn13-check-digit.psh delete mode 100644 Task/Identity-matrix/Ada/identity-matrix-1.ada delete mode 100644 Task/Identity-matrix/Ada/identity-matrix-2.ada delete mode 100644 Task/Identity-matrix/PowerShell/identity-matrix-1.psh delete mode 100644 Task/Identity-matrix/PowerShell/identity-matrix-2.psh delete mode 100644 Task/Identity-matrix/VBScript/identity-matrix-1.vb delete mode 100644 Task/Identity-matrix/VBScript/identity-matrix-2.vb delete mode 100644 Task/Idiomatically-determine-all-the-characters-that-can-be-used-for-symbols/Ada/idiomatically-determine-all-the-characters-that-can-be-used-for-symbols.ada delete mode 100644 Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Ada/idiomatically-determine-all-the-lowercase-and-uppercase-letters.ada delete mode 100644 Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/COBOL/idiomatically-determine-all-the-lowercase-and-uppercase-letters.cobol delete mode 100644 Task/Idiomatically-determine-all-the-lowercase-and-uppercase-letters/Phix/idiomatically-determine-all-the-lowercase-and-uppercase-letters.phix delete mode 100644 Task/Image-convolution/Ada/image-convolution-1.ada delete mode 100644 Task/Image-convolution/Ada/image-convolution-2.ada delete mode 100644 Task/Image-convolution/Ada/image-convolution-3.ada delete mode 100644 Task/Image-noise/Ada/image-noise-1.ada delete mode 100644 Task/Image-noise/Ada/image-noise-2.ada delete mode 100644 Task/Image-noise/Ada/image-noise-3.ada delete mode 100644 Task/Include-a-file/Ada/include-a-file.ada delete mode 100644 Task/Include-a-file/COBOL/include-a-file.cobol delete mode 100644 Task/Include-a-file/Emacs-Lisp/include-a-file-1.l delete mode 100644 Task/Include-a-file/Emacs-Lisp/include-a-file-2.l delete mode 100644 Task/Include-a-file/Euphoria/include-a-file.ex delete mode 100644 Task/Include-a-file/PowerShell/include-a-file.psh delete mode 100644 Task/Include-a-file/VBScript/include-a-file-1.vb delete mode 100644 Task/Include-a-file/VBScript/include-a-file-2.vb delete mode 100644 Task/Include-a-file/VBScript/include-a-file-3.vb delete mode 100644 Task/Increment-a-numerical-string/Ada/increment-a-numerical-string.ada delete mode 100644 Task/Increment-a-numerical-string/AutoIt/increment-a-numerical-string.autoit delete mode 100644 Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-1.cobol delete mode 100644 Task/Increment-a-numerical-string/COBOL/increment-a-numerical-string-2.cobol delete mode 100644 Task/Increment-a-numerical-string/Emacs-Lisp/increment-a-numerical-string.l delete mode 100644 Task/Increment-a-numerical-string/Euphoria/increment-a-numerical-string.ex delete mode 100644 Task/Increment-a-numerical-string/PowerShell/increment-a-numerical-string-1.psh delete mode 100644 Task/Increment-a-numerical-string/PowerShell/increment-a-numerical-string-2.psh delete mode 100644 Task/Increment-a-numerical-string/REBOL/increment-a-numerical-string.rebol delete mode 100644 Task/Infinity/Ada/infinity-1.ada delete mode 100644 Task/Infinity/Ada/infinity-2.ada delete mode 100644 Task/Infinity/Ada/infinity-3.ada delete mode 100644 Task/Infinity/Euphoria/infinity.ex delete mode 100644 Task/Infinity/PowerShell/infinity.psh delete mode 100644 Task/Inheritance-Multiple/Ada/inheritance-multiple.ada delete mode 100644 Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol delete mode 100644 Task/Inheritance-Multiple/PowerShell/inheritance-multiple.psh delete mode 100644 Task/Inheritance-Single/Ada/inheritance-single.ada delete mode 100644 Task/Inheritance-Single/COBOL/inheritance-single.cobol delete mode 100644 Task/Inheritance-Single/Haxe/inheritance-single-1.haxe delete mode 100644 Task/Inheritance-Single/Haxe/inheritance-single-2.haxe delete mode 100644 Task/Inheritance-Single/PowerShell/inheritance-single.psh delete mode 100644 Task/Inheritance-Single/REBOL/inheritance-single.rebol delete mode 100644 Task/Input-loop/Ada/input-loop.ada delete mode 100644 Task/Input-loop/Batch-File/input-loop.bat delete mode 100644 Task/Input-loop/COBOL/input-loop.cobol delete mode 100644 Task/Input-loop/Euphoria/input-loop.ex delete mode 100644 Task/Input-loop/PowerShell/input-loop-1.psh delete mode 100644 Task/Input-loop/PowerShell/input-loop-2.psh delete mode 100644 Task/Input-loop/REBOL/input-loop.rebol delete mode 100644 Task/Input-loop/REXX/input-loop-1.rexx delete mode 100644 Task/Input-loop/REXX/input-loop-2.rexx delete mode 100644 Task/Input-loop/REXX/input-loop-3.rexx delete mode 100644 Task/Input-loop/REXX/input-loop-4.rexx delete mode 100644 Task/Input-loop/REXX/input-loop-5.rexx delete mode 100644 Task/Input-loop/VBScript/input-loop.vb delete mode 100644 Task/Integer-comparison/ALGOL-W/integer-comparison.alg delete mode 100644 Task/Integer-comparison/Ada/integer-comparison.ada delete mode 100644 Task/Integer-comparison/COBOL/integer-comparison.cobol delete mode 100644 Task/Integer-comparison/Emacs-Lisp/integer-comparison.l delete mode 100644 Task/Integer-comparison/Euphoria/integer-comparison.ex delete mode 100644 Task/Integer-comparison/PowerShell/integer-comparison.psh delete mode 100644 Task/Integer-comparison/REBOL/integer-comparison.rebol delete mode 100644 Task/Integer-comparison/ReScript/integer-comparison.re delete mode 100644 Task/Integer-comparison/VBScript/integer-comparison.vb delete mode 100644 Task/Integer-overflow/Ada/integer-overflow.ada delete mode 100644 Task/Integer-overflow/COBOL/integer-overflow-1.cobol delete mode 100644 Task/Integer-overflow/COBOL/integer-overflow-2.cobol delete mode 100644 Task/Integer-overflow/PowerShell/integer-overflow.psh delete mode 100644 Task/Integer-overflow/VBScript/integer-overflow.vb delete mode 100644 Task/Integer-sequence/Ada/integer-sequence-1.ada delete mode 100644 Task/Integer-sequence/Ada/integer-sequence-2.ada delete mode 100644 Task/Integer-sequence/COBOL/integer-sequence.cobol delete mode 100644 Task/Integer-sequence/Emacs-Lisp/integer-sequence.l delete mode 100644 Task/Integer-sequence/Euphoria/integer-sequence.ex delete mode 100644 Task/Integer-sequence/PowerShell/integer-sequence.psh delete mode 100644 Task/Interactive-programming-repl-/Emacs-Lisp/interactive-programming-repl--1.l delete mode 100644 Task/Interactive-programming-repl-/Emacs-Lisp/interactive-programming-repl--2.l delete mode 100644 Task/Interactive-programming-repl-/PowerShell/interactive-programming-repl-.psh delete mode 100644 Task/Interactive-programming-repl-/REBOL/interactive-programming-repl-.rebol delete mode 100644 Task/Interactive-programming-repl-/REXX/interactive-programming-repl--3.rexx delete mode 100644 Task/Introspection/Ada/introspection.ada delete mode 100644 Task/Introspection/PowerShell/introspection.psh delete mode 100644 Task/Inverted-index/Ada/inverted-index-1.ada delete mode 100644 Task/Inverted-index/Ada/inverted-index-2.ada delete mode 100644 Task/Inverted-index/Ada/inverted-index-3.ada delete mode 100644 Task/Inverted-index/Ada/inverted-index-4.ada delete mode 100644 Task/Inverted-index/Ada/inverted-index-5.ada delete mode 100644 Task/Inverted-index/Ada/inverted-index-6.ada delete mode 100644 Task/Inverted-index/Ada/inverted-index-7.ada delete mode 100644 Task/Inverted-index/PowerShell/inverted-index-1.psh delete mode 100644 Task/Inverted-index/PowerShell/inverted-index-2.psh delete mode 100644 Task/Inverted-index/PowerShell/inverted-index-3.psh delete mode 100644 Task/Inverted-index/PowerShell/inverted-index-4.psh delete mode 100644 Task/Inverted-syntax/Ada/inverted-syntax.ada delete mode 100644 Task/Inverted-syntax/PowerShell/inverted-syntax-1.psh delete mode 100644 Task/Inverted-syntax/PowerShell/inverted-syntax-2.psh delete mode 100644 Task/Isqrt-integer-square-root-of-X/Ada/isqrt-integer-square-root-of-x.ada delete mode 100644 Task/Isqrt-integer-square-root-of-X/COBOL/isqrt-integer-square-root-of-x.cobol delete mode 100644 Task/Iterated-digits-squaring/Ada/iterated-digits-squaring.ada delete mode 100644 Task/Iterated-digits-squaring/VBScript/iterated-digits-squaring.vb delete mode 100644 Task/JSON/Ada/json-1.ada delete mode 100644 Task/JSON/Ada/json-2.ada delete mode 100644 Task/JSON/Emacs-Lisp/json-1.l delete mode 100644 Task/JSON/Emacs-Lisp/json-2.l delete mode 100644 Task/JSON/Hoon/json-1.hoon delete mode 100644 Task/JSON/Hoon/json-2.hoon delete mode 100644 Task/JSON/PowerShell/json-1.psh delete mode 100644 Task/JSON/PowerShell/json-2.psh delete mode 100644 Task/JSON/REBOL/json-1.rebol delete mode 100644 Task/JSON/REBOL/json-2.rebol delete mode 100644 Task/Jacobsthal-numbers/Ada/jacobsthal-numbers.ada delete mode 100644 Task/Jaro-similarity/Ada/jaro-similarity.ada delete mode 100644 Task/Jaro-similarity/COBOL/jaro-similarity.cobol delete mode 100644 Task/Jaro-similarity/Emacs-Lisp/jaro-similarity.l delete mode 100644 Task/Jaro-similarity/Haxe/jaro-similarity.haxe delete mode 100644 Task/Jensens-Device/Ada/jensens-device.ada delete mode 100644 Task/Jewels-and-stones/Ada/jewels-and-stones.ada delete mode 100644 Task/Jewels-and-stones/Euphoria/jewels-and-stones.ex delete mode 100644 Task/JortSort/Ada/jortsort.ada delete mode 100644 Task/JortSort/PowerShell/jortsort.psh delete mode 100644 Task/JortSort/VBScript/jortsort.vb delete mode 100644 Task/Josephus-problem/Ada/josephus-problem.ada delete mode 100644 Task/Josephus-problem/Emacs-Lisp/josephus-problem.l delete mode 100644 Task/Josephus-problem/PowerShell/josephus-problem-1.psh delete mode 100644 Task/Josephus-problem/PowerShell/josephus-problem-2.psh delete mode 100644 Task/Josephus-problem/REBOL/josephus-problem-1.rebol delete mode 100644 Task/Josephus-problem/REBOL/josephus-problem-2.rebol delete mode 100644 Task/Josephus-problem/VBScript/josephus-problem.vb delete mode 100644 Task/Juggler-sequence/Ada/juggler-sequence.ada delete mode 100644 Task/Julia-set/Ada/julia-set.ada delete mode 100644 Task/Julia-set/COBOL/julia-set.cobol delete mode 100644 Task/Julia-set/Emacs-Lisp/julia-set.l delete mode 100644 Task/Julia-set/VBScript/julia-set.vb delete mode 100644 Task/Jump-anywhere/Ada/jump-anywhere.ada delete mode 100644 Task/Jump-anywhere/COBOL/jump-anywhere-1.cobol delete mode 100644 Task/Jump-anywhere/COBOL/jump-anywhere-2.cobol delete mode 100644 Task/Jump-anywhere/PowerShell/jump-anywhere-1.psh delete mode 100644 Task/Jump-anywhere/PowerShell/jump-anywhere-2.psh delete mode 100644 Task/Jump-anywhere/PowerShell/jump-anywhere-3.psh delete mode 100644 Task/Kaprekar-numbers/Ada/kaprekar-numbers.ada delete mode 100644 Task/Kaprekar-numbers/PowerShell/kaprekar-numbers-1.psh delete mode 100644 Task/Kaprekar-numbers/PowerShell/kaprekar-numbers-2.psh delete mode 100644 Task/Kernighans-large-earthquake-problem/Ada/kernighans-large-earthquake-problem.ada delete mode 100644 Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-1.cobol delete mode 100644 Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-2.cobol delete mode 100644 Task/Kernighans-large-earthquake-problem/Emacs-Lisp/kernighans-large-earthquake-problem.l delete mode 100644 Task/Kernighans-large-earthquake-problem/Perl/kernighans-large-earthquake-problem.pl delete mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Ada/keyboard-input-flush-the-keyboard-buffer.ada delete mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Emacs-Lisp/keyboard-input-flush-the-keyboard-buffer.l delete mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Euphoria/keyboard-input-flush-the-keyboard-buffer.ex delete mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/PowerShell/keyboard-input-flush-the-keyboard-buffer-1.psh delete mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/PowerShell/keyboard-input-flush-the-keyboard-buffer-2.psh delete mode 100644 Task/Keyboard-input-Keypress-check/Ada/keyboard-input-keypress-check.ada delete mode 100644 Task/Keyboard-input-Keypress-check/Emacs-Lisp/keyboard-input-keypress-check.l delete mode 100644 Task/Keyboard-input-Keypress-check/Euphoria/keyboard-input-keypress-check.ex delete mode 100644 Task/Keyboard-input-Keypress-check/PowerShell/keyboard-input-keypress-check.psh delete mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Ada/keyboard-input-obtain-a-y-or-n-response.ada delete mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Emacs-Lisp/keyboard-input-obtain-a-y-or-n-response.l delete mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Euphoria/keyboard-input-obtain-a-y-or-n-response.ex delete mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/PowerShell/keyboard-input-obtain-a-y-or-n-response.psh delete mode 100644 Task/Keyboard-macros/REBOL/keyboard-macros.rebol delete mode 100644 Task/Knapsack-problem-0-1/Ada/knapsack-problem-0-1.ada delete mode 100644 Task/Knapsack-problem-0-1/Emacs-Lisp/knapsack-problem-0-1-1.l delete mode 100644 Task/Knapsack-problem-0-1/Emacs-Lisp/knapsack-problem-0-1-2.l delete mode 100644 Task/Knapsack-problem-0-1/JavaScript/knapsack-problem-0-1.js delete mode 100644 Task/Knapsack-problem-0-1/VBScript/knapsack-problem-0-1.vb delete mode 100644 Task/Knapsack-problem-Bounded/Ada/knapsack-problem-bounded.ada delete mode 100644 Task/Knapsack-problem-Continuous/Ada/knapsack-problem-continuous.ada delete mode 100644 Task/Knapsack-problem-Unbounded/Ada/knapsack-problem-unbounded.ada delete mode 100644 Task/Knapsack-problem-Unbounded/PowerShell/knapsack-problem-unbounded.psh delete mode 100644 Task/Knights-tour/Ada/knights-tour-1.ada delete mode 100644 Task/Knights-tour/Ada/knights-tour-2.ada delete mode 100644 Task/Knights-tour/Ada/knights-tour-3.ada delete mode 100644 Task/Knights-tour/Ada/knights-tour-4.ada delete mode 100644 Task/Knights-tour/Ada/knights-tour-5.ada delete mode 100644 Task/Knights-tour/Ada/knights-tour-6.ada delete mode 100644 Task/Knights-tour/FutureBasic/knights-tour.basic delete mode 100644 Task/Knuth-shuffle/Ada/knuth-shuffle-1.ada delete mode 100644 Task/Knuth-shuffle/Ada/knuth-shuffle-2.ada delete mode 100644 Task/Knuth-shuffle/Ada/knuth-shuffle-3.ada delete mode 100644 Task/Knuth-shuffle/AutoIt/knuth-shuffle.autoit delete mode 100644 Task/Knuth-shuffle/COBOL/knuth-shuffle.cobol delete mode 100644 Task/Knuth-shuffle/Euphoria/knuth-shuffle.ex delete mode 100644 Task/Knuth-shuffle/PowerShell/knuth-shuffle-1.psh delete mode 100644 Task/Knuth-shuffle/PowerShell/knuth-shuffle-2.psh delete mode 100644 Task/Knuth-shuffle/REBOL/knuth-shuffle-1.rebol delete mode 100644 Task/Knuth-shuffle/REBOL/knuth-shuffle-2.rebol delete mode 100644 Task/Knuth-shuffle/VBScript/knuth-shuffle-1.vb delete mode 100644 Task/Knuth-shuffle/VBScript/knuth-shuffle-2.vb delete mode 100644 Task/Knuths-algorithm-S/Ada/knuths-algorithm-s-1.ada delete mode 100644 Task/Knuths-algorithm-S/Ada/knuths-algorithm-s-2.ada delete mode 100644 Task/Knuths-algorithm-S/Ada/knuths-algorithm-s-3.ada delete mode 100644 Task/Knuths-power-tree/Ada/knuths-power-tree.ada delete mode 100644 Task/Koch-curve/Ada/koch-curve.ada delete mode 100644 Task/Koch-curve/VBScript/koch-curve.vb delete mode 100644 Task/Kronecker-product-based-fractals/Ada/kronecker-product-based-fractals.ada delete mode 100644 Task/Kronecker-product/Ada/kronecker-product.ada delete mode 100644 Task/Kronecker-product/VBScript/kronecker-product.vb delete mode 100644 Task/LU-decomposition/Ada/lu-decomposition-1.ada delete mode 100644 Task/LU-decomposition/Ada/lu-decomposition-2.ada delete mode 100644 Task/LU-decomposition/Ada/lu-decomposition-3.ada delete mode 100644 Task/LZW-compression/Ada/lzw-compression-1.ada delete mode 100644 Task/LZW-compression/Ada/lzw-compression-2.ada delete mode 100644 Task/LZW-compression/Ada/lzw-compression-3.ada delete mode 100644 Task/LZW-compression/Julia/lzw-compression.jl delete mode 100644 Task/LZW-compression/Phix/lzw-compression.phix delete mode 100644 Task/LZW-compression/VBScript/lzw-compression.vb delete mode 100644 Task/Lah-numbers/Ada/lah-numbers.ada delete mode 100644 Task/Lah-numbers/VBScript/lah-numbers.vb delete mode 100644 Task/Langtons-ant/Ada/langtons-ant.ada delete mode 100644 Task/Langtons-ant/AutoIt/langtons-ant.autoit delete mode 100644 Task/Langtons-ant/COBOL/langtons-ant.cobol delete mode 100644 Task/Langtons-ant/Chapel/langtons-ant.chapel delete mode 100644 Task/Langtons-ant/Euphoria/langtons-ant-1.ex delete mode 100644 Task/Langtons-ant/Euphoria/langtons-ant-2.ex delete mode 100644 Task/Langtons-ant/PowerShell/langtons-ant.psh delete mode 100644 Task/Largest-int-from-concatenated-ints/Ada/largest-int-from-concatenated-ints-1.ada delete mode 100644 Task/Largest-int-from-concatenated-ints/Ada/largest-int-from-concatenated-ints-2.ada delete mode 100644 Task/Largest-int-from-concatenated-ints/PowerShell/largest-int-from-concatenated-ints-1.psh delete mode 100644 Task/Largest-int-from-concatenated-ints/PowerShell/largest-int-from-concatenated-ints-2.psh delete mode 100644 Task/Largest-int-from-concatenated-ints/VBScript/largest-int-from-concatenated-ints.vb delete mode 100644 Task/Largest-number-divisible-by-its-digits/Ada/largest-number-divisible-by-its-digits.ada delete mode 100644 Task/Largest-number-divisible-by-its-digits/VBScript/largest-number-divisible-by-its-digits.vb delete mode 100644 Task/Largest-proper-divisor-of-n/Ada/largest-proper-divisor-of-n.ada delete mode 100644 Task/Largest-proper-divisor-of-n/AutoLISP/largest-proper-divisor-of-n.l delete mode 100644 Task/Last-Friday-of-each-month/Ada/last-friday-of-each-month.ada delete mode 100644 Task/Last-Friday-of-each-month/AutoIt/last-friday-of-each-month.autoit delete mode 100644 Task/Last-Friday-of-each-month/COBOL/last-friday-of-each-month.cobol delete mode 100644 Task/Last-Friday-of-each-month/Emacs-Lisp/last-friday-of-each-month.l delete mode 100644 Task/Last-Friday-of-each-month/MATLAB/last-friday-of-each-month.m delete mode 100644 Task/Last-Friday-of-each-month/PowerShell/last-friday-of-each-month-1.psh delete mode 100644 Task/Last-Friday-of-each-month/PowerShell/last-friday-of-each-month-2.psh delete mode 100644 Task/Last-Friday-of-each-month/PowerShell/last-friday-of-each-month-3.psh delete mode 100644 Task/Last-Friday-of-each-month/PowerShell/last-friday-of-each-month-4.psh delete mode 100644 Task/Last-Friday-of-each-month/PowerShell/last-friday-of-each-month-5.psh delete mode 100644 Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-1.rebol delete mode 100644 Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-2.rebol delete mode 100644 Task/Last-letter-first-letter/Ada/last-letter-first-letter.ada delete mode 100644 Task/Last-letter-first-letter/VBScript/last-letter-first-letter.vb delete mode 100644 Task/Law-of-cosines---triples/Ada/law-of-cosines---triples.ada delete mode 100644 Task/Leap-year/Ada/leap-year.ada delete mode 100644 Task/Leap-year/AutoIt/leap-year.autoit delete mode 100644 Task/Leap-year/COBOL/leap-year-1.cobol delete mode 100644 Task/Leap-year/COBOL/leap-year-2.cobol delete mode 100644 Task/Leap-year/Emacs-Lisp/leap-year.l delete mode 100644 Task/Leap-year/Euphoria/leap-year.ex delete mode 100644 Task/Leap-year/Pascal/leap-year.pas delete mode 100644 Task/Leap-year/PowerShell/leap-year.psh delete mode 100644 Task/Leap-year/REBOL/leap-year.rebol delete mode 100644 Task/Leap-year/VBScript/leap-year.vb delete mode 100644 Task/Least-common-multiple/Ada/least-common-multiple.ada delete mode 100644 Task/Least-common-multiple/AutoIt/least-common-multiple-1.autoit delete mode 100644 Task/Least-common-multiple/AutoIt/least-common-multiple-2.autoit delete mode 100644 Task/Least-common-multiple/COBOL/least-common-multiple.cobol delete mode 100644 Task/Least-common-multiple/Euphoria/least-common-multiple.ex delete mode 100644 Task/Least-common-multiple/PowerShell/least-common-multiple-1.psh delete mode 100644 Task/Least-common-multiple/PowerShell/least-common-multiple-2.psh delete mode 100644 Task/Least-common-multiple/VBScript/least-common-multiple.vb delete mode 100644 Task/Left-factorials/Ada/left-factorials.ada delete mode 100644 Task/Left-factorials/PowerShell/left-factorials.psh delete mode 100644 Task/Legendre-prime-counting-function/Chapel/legendre-prime-counting-function-1.chapel delete mode 100644 Task/Legendre-prime-counting-function/Chapel/legendre-prime-counting-function-2.chapel delete mode 100644 Task/Legendre-prime-counting-function/Chapel/legendre-prime-counting-function-3.chapel delete mode 100644 Task/Legendre-prime-counting-function/Python/legendre-prime-counting-function.py delete mode 100644 Task/Leonardo-numbers/Ada/leonardo-numbers.ada delete mode 100644 Task/Leonardo-numbers/COBOL/leonardo-numbers.cobol delete mode 100644 Task/Letter-frequency/Ada/letter-frequency.ada delete mode 100644 Task/Letter-frequency/AutoIt/letter-frequency.autoit delete mode 100644 Task/Letter-frequency/COBOL/letter-frequency.cobol delete mode 100644 Task/Letter-frequency/Emacs-Lisp/letter-frequency.l delete mode 100644 Task/Letter-frequency/Euphoria/letter-frequency.ex delete mode 100644 Task/Letter-frequency/PowerShell/letter-frequency.psh delete mode 100644 Task/Letter-frequency/VBScript/letter-frequency.vb delete mode 100644 Task/Levenshtein-distance-Alignment/Ada/levenshtein-distance-alignment.ada delete mode 100644 Task/Levenshtein-distance/Ada/levenshtein-distance.ada delete mode 100644 Task/Levenshtein-distance/COBOL/levenshtein-distance.cobol delete mode 100644 Task/Levenshtein-distance/Euphoria/levenshtein-distance.ex delete mode 100644 Task/Levenshtein-distance/PowerShell/levenshtein-distance-1.psh delete mode 100644 Task/Levenshtein-distance/PowerShell/levenshtein-distance-2.psh delete mode 100644 Task/Levenshtein-distance/VBScript/levenshtein-distance.vb delete mode 100644 Task/Linear-congruential-generator/Ada/linear-congruential-generator-1.ada delete mode 100644 Task/Linear-congruential-generator/Ada/linear-congruential-generator-2.ada delete mode 100644 Task/Linear-congruential-generator/Ada/linear-congruential-generator-3.ada delete mode 100644 Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.psh delete mode 100644 Task/List-comprehensions/Ada/list-comprehensions.ada delete mode 100644 Task/Literals-Floating-point/Ada/literals-floating-point.ada delete mode 100644 Task/Literals-Floating-point/Euphoria/literals-floating-point.ex delete mode 100644 Task/Literals-Integer/Ada/literals-integer.ada delete mode 100644 Task/Literals-Integer/COBOL/literals-integer-1.cobol delete mode 100644 Task/Literals-Integer/COBOL/literals-integer-2.cobol delete mode 100644 Task/Literals-Integer/Emacs-Lisp/literals-integer.l delete mode 100644 Task/Literals-Integer/Euphoria/literals-integer.ex delete mode 100644 Task/Literals-Integer/PowerShell/literals-integer-1.psh delete mode 100644 Task/Literals-Integer/PowerShell/literals-integer-2.psh delete mode 100644 Task/Literals-Integer/REBOL/literals-integer.rebol delete mode 100644 Task/Literals-String/Ada/literals-string-1.ada delete mode 100644 Task/Literals-String/Ada/literals-string-2.ada delete mode 100644 Task/Literals-String/COBOL/literals-string-1.cobol delete mode 100644 Task/Literals-String/COBOL/literals-string-2.cobol delete mode 100644 Task/Literals-String/COBOL/literals-string-3.cobol delete mode 100644 Task/Literals-String/Emacs-Lisp/literals-string-1.l delete mode 100644 Task/Literals-String/Emacs-Lisp/literals-string-2.l delete mode 100644 Task/Logical-operations/Ada/logical-operations.ada delete mode 100644 Task/Logical-operations/COBOL/logical-operations.cobol delete mode 100644 Task/Logical-operations/Euphoria/logical-operations.ex delete mode 100644 Task/Logical-operations/PowerShell/logical-operations.psh delete mode 100644 Task/Logical-operations/REBOL/logical-operations.rebol delete mode 100644 Task/Logical-operations/ReScript/logical-operations.re delete mode 100644 Task/Logistic-curve-fitting-in-epidemiology/Ada/logistic-curve-fitting-in-epidemiology.ada delete mode 100644 Task/Long-literals-with-continuations/Ada/long-literals-with-continuations.ada delete mode 100644 Task/Long-multiplication/Ada/long-multiplication-1.ada delete mode 100644 Task/Long-multiplication/Ada/long-multiplication-2.ada delete mode 100644 Task/Long-multiplication/Ada/long-multiplication-3.ada delete mode 100644 Task/Long-multiplication/Ada/long-multiplication-4.ada delete mode 100644 Task/Long-multiplication/Ada/long-multiplication-5.ada delete mode 100644 Task/Long-multiplication/Ada/long-multiplication-6.ada delete mode 100644 Task/Long-multiplication/COBOL/long-multiplication.cobol delete mode 100644 Task/Long-multiplication/Euphoria/long-multiplication.ex delete mode 100644 Task/Long-multiplication/PowerShell/long-multiplication-1.psh delete mode 100644 Task/Long-multiplication/PowerShell/long-multiplication-2.psh delete mode 100644 Task/Long-year/Ada/long-year.ada delete mode 100644 Task/Long-year/Oberon-07/long-year-1.oberon delete mode 100644 Task/Long-year/Oberon-07/long-year-2.oberon delete mode 100644 Task/Long-year/PowerShell/long-year.psh delete mode 100644 Task/Longest-common-subsequence/Ada/longest-common-subsequence-1.ada delete mode 100644 Task/Longest-common-subsequence/Ada/longest-common-subsequence-2.ada delete mode 100644 Task/Longest-common-subsequence/PowerShell/longest-common-subsequence-1.psh delete mode 100644 Task/Longest-common-subsequence/PowerShell/longest-common-subsequence-2.psh delete mode 100644 Task/Longest-common-subsequence/PowerShell/longest-common-subsequence-3.psh delete mode 100644 Task/Longest-common-subsequence/PowerShell/longest-common-subsequence-4.psh delete mode 100644 Task/Longest-common-substring/Ada/longest-common-substring.ada delete mode 100644 Task/Longest-common-substring/PowerShell/longest-common-substring.psh delete mode 100644 Task/Longest-common-substring/VBScript/longest-common-substring.vb delete mode 100644 Task/Longest-increasing-subsequence/Ada/longest-increasing-subsequence.ada delete mode 100644 Task/Longest-increasing-subsequence/PowerShell/longest-increasing-subsequence-1.psh delete mode 100644 Task/Longest-increasing-subsequence/PowerShell/longest-increasing-subsequence-2.psh delete mode 100644 Task/Longest-increasing-subsequence/VBScript/longest-increasing-subsequence.vb delete mode 100644 Task/Longest-string-challenge/Ada/longest-string-challenge-1.ada delete mode 100644 Task/Longest-string-challenge/Ada/longest-string-challenge-2.ada delete mode 100644 Task/Longest-string-challenge/Ada/longest-string-challenge-3.ada delete mode 100644 Task/Longest-string-challenge/PowerShell/longest-string-challenge-1.psh delete mode 100644 Task/Longest-string-challenge/PowerShell/longest-string-challenge-2.psh delete mode 100644 Task/Longest-string-challenge/VBScript/longest-string-challenge.vb delete mode 100644 Task/Look-and-say-sequence/Ada/look-and-say-sequence-1.ada delete mode 100644 Task/Look-and-say-sequence/Ada/look-and-say-sequence-2.ada delete mode 100644 Task/Look-and-say-sequence/COBOL/look-and-say-sequence.cobol delete mode 100644 Task/Look-and-say-sequence/Haxe/look-and-say-sequence.haxe delete mode 100644 Task/Look-and-say-sequence/PowerShell/look-and-say-sequence.psh delete mode 100644 Task/Look-and-say-sequence/VBScript/look-and-say-sequence-1.vb delete mode 100644 Task/Look-and-say-sequence/VBScript/look-and-say-sequence-2.vb delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Ada/loop-over-multiple-arrays-simultaneously.ada delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/COBOL/loop-over-multiple-arrays-simultaneously.cobol delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Chapel/loop-over-multiple-arrays-simultaneously.chapel delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Euphoria/loop-over-multiple-arrays-simultaneously-1.ex delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Euphoria/loop-over-multiple-arrays-simultaneously-2.ex delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Euphoria/loop-over-multiple-arrays-simultaneously-3.ex delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Haxe/loop-over-multiple-arrays-simultaneously.haxe delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Perl/loop-over-multiple-arrays-simultaneously.pl delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/PowerShell/loop-over-multiple-arrays-simultaneously-1.psh delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/PowerShell/loop-over-multiple-arrays-simultaneously-2.psh delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/PowerShell/loop-over-multiple-arrays-simultaneously-3.psh delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/REBOL/loop-over-multiple-arrays-simultaneously.rebol delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Uiua/loop-over-multiple-arrays-simultaneously.uiua delete mode 100644 Task/Loop-over-multiple-arrays-simultaneously/VBScript/loop-over-multiple-arrays-simultaneously.vb delete mode 100644 Task/Loops-Break/Ada/loops-break.ada delete mode 100644 Task/Loops-Break/COBOL/loops-break.cobol delete mode 100644 Task/Loops-Break/Chapel/loops-break.chapel delete mode 100644 Task/Loops-Break/Emacs-Lisp/loops-break.l delete mode 100644 Task/Loops-Break/Euphoria/loops-break.ex delete mode 100644 Task/Loops-Break/Haxe/loops-break.haxe delete mode 100644 Task/Loops-Break/PowerShell/loops-break.psh delete mode 100644 Task/Loops-Break/REBOL/loops-break.rebol delete mode 100644 Task/Loops-Break/VBScript/loops-break.vb delete mode 100644 Task/Loops-Continue/Ada/loops-continue-1.ada delete mode 100644 Task/Loops-Continue/Ada/loops-continue-2.ada delete mode 100644 Task/Loops-Continue/COBOL/loops-continue.cobol delete mode 100644 Task/Loops-Continue/Chapel/loops-continue.chapel delete mode 100644 Task/Loops-Continue/Euphoria/loops-continue-1.ex delete mode 100644 Task/Loops-Continue/Euphoria/loops-continue-2.ex delete mode 100644 Task/Loops-Continue/Haxe/loops-continue.haxe delete mode 100644 Task/Loops-Continue/PowerShell/loops-continue.psh delete mode 100644 Task/Loops-Continue/REBOL/loops-continue-1.rebol delete mode 100644 Task/Loops-Continue/REBOL/loops-continue-2.rebol delete mode 100644 Task/Loops-Do-while/Ada/loops-do-while-1.ada delete mode 100644 Task/Loops-Do-while/Ada/loops-do-while-2.ada delete mode 100644 Task/Loops-Do-while/COBOL/loops-do-while.cobol delete mode 100644 Task/Loops-Do-while/Chapel/loops-do-while.chapel delete mode 100644 Task/Loops-Do-while/Emacs-Lisp/loops-do-while-1.l delete mode 100644 Task/Loops-Do-while/Emacs-Lisp/loops-do-while-2.l delete mode 100644 Task/Loops-Do-while/Euphoria/loops-do-while.ex delete mode 100644 Task/Loops-Do-while/Haxe/loops-do-while.haxe delete mode 100644 Task/Loops-Do-while/PowerShell/loops-do-while.psh delete mode 100644 Task/Loops-Do-while/REBOL/loops-do-while.rebol delete mode 100644 Task/Loops-Downward-for/Ada/loops-downward-for.ada delete mode 100644 Task/Loops-Downward-for/COBOL/loops-downward-for.cobol delete mode 100644 Task/Loops-Downward-for/Chapel/loops-downward-for-1.chapel delete mode 100644 Task/Loops-Downward-for/Chapel/loops-downward-for-2.chapel delete mode 100644 Task/Loops-Downward-for/Euphoria/loops-downward-for.ex delete mode 100644 Task/Loops-Downward-for/Haxe/loops-downward-for.haxe delete mode 100644 Task/Loops-Downward-for/PowerShell/loops-downward-for-1.psh delete mode 100644 Task/Loops-Downward-for/PowerShell/loops-downward-for-2.psh delete mode 100644 Task/Loops-Downward-for/REBOL/loops-downward-for.rebol delete mode 100644 Task/Loops-For-with-a-specified-step/Ada/loops-for-with-a-specified-step.ada delete mode 100644 Task/Loops-For-with-a-specified-step/COBOL/loops-for-with-a-specified-step.cobol delete mode 100644 Task/Loops-For-with-a-specified-step/Chapel/loops-for-with-a-specified-step.chapel delete mode 100644 Task/Loops-For-with-a-specified-step/Euphoria/loops-for-with-a-specified-step-1.ex delete mode 100644 Task/Loops-For-with-a-specified-step/Euphoria/loops-for-with-a-specified-step-2.ex delete mode 100644 Task/Loops-For-with-a-specified-step/Haxe/loops-for-with-a-specified-step.haxe delete mode 100644 Task/Loops-For-with-a-specified-step/Oberon/loops-for-with-a-specified-step.oberon delete mode 100644 Task/Loops-For-with-a-specified-step/PowerShell/loops-for-with-a-specified-step.psh delete mode 100644 Task/Loops-For-with-a-specified-step/REBOL/loops-for-with-a-specified-step.rebol delete mode 100644 Task/Loops-For-with-a-specified-step/VBScript/loops-for-with-a-specified-step.vb delete mode 100644 Task/Loops-For/Ada/loops-for.ada delete mode 100644 Task/Loops-For/COBOL/loops-for.cobol delete mode 100644 Task/Loops-For/Chapel/loops-for.chapel delete mode 100644 Task/Loops-For/Coq/loops-for.coq delete mode 100644 Task/Loops-For/Emacs-Lisp/loops-for.l delete mode 100644 Task/Loops-For/Euphoria/loops-for.ex delete mode 100644 Task/Loops-For/Haxe/loops-for.haxe delete mode 100644 Task/Loops-For/PowerShell/loops-for-1.psh delete mode 100644 Task/Loops-For/PowerShell/loops-for-2.psh delete mode 100644 Task/Loops-For/REBOL/loops-for.rebol delete mode 100644 Task/Loops-For/ReScript/loops-for.re delete mode 100644 Task/Loops-For/VBScript/loops-for.vb delete mode 100644 Task/Loops-Foreach/Ada/loops-foreach-1.ada delete mode 100644 Task/Loops-Foreach/Ada/loops-foreach-2.ada delete mode 100644 Task/Loops-Foreach/Ada/loops-foreach-3.ada delete mode 100644 Task/Loops-Foreach/Ada/loops-foreach-4.ada delete mode 100644 Task/Loops-Foreach/COBOL/loops-foreach.cobol delete mode 100644 Task/Loops-Foreach/Chapel/loops-foreach.chapel delete mode 100644 Task/Loops-Foreach/Emacs-Lisp/loops-foreach-1.l delete mode 100644 Task/Loops-Foreach/Emacs-Lisp/loops-foreach-2.l delete mode 100644 Task/Loops-Foreach/Emacs-Lisp/loops-foreach-3.l delete mode 100644 Task/Loops-Foreach/Euphoria/loops-foreach.ex delete mode 100644 Task/Loops-Foreach/Haxe/loops-foreach.haxe delete mode 100644 Task/Loops-Foreach/PowerShell/loops-foreach.psh delete mode 100644 Task/Loops-Foreach/REBOL/loops-foreach.rebol delete mode 100644 Task/Loops-Foreach/ReScript/loops-foreach.re delete mode 100644 Task/Loops-Foreach/VBScript/loops-foreach.vb delete mode 100644 Task/Loops-Increment-loop-index-within-loop-body/Ada/loops-increment-loop-index-within-loop-body.ada delete mode 100644 Task/Loops-Increment-loop-index-within-loop-body/Haxe/loops-increment-loop-index-within-loop-body.haxe delete mode 100644 Task/Loops-Increment-loop-index-within-loop-body/REBOL/loops-increment-loop-index-within-loop-body.rebol delete mode 100644 Task/Loops-Infinite/Ada/loops-infinite.ada delete mode 100644 Task/Loops-Infinite/COBOL/loops-infinite.cobol delete mode 100644 Task/Loops-Infinite/Chapel/loops-infinite.chapel delete mode 100644 Task/Loops-Infinite/Emacs-Lisp/loops-infinite.l delete mode 100644 Task/Loops-Infinite/Euphoria/loops-infinite.ex delete mode 100644 Task/Loops-Infinite/Haxe/loops-infinite.haxe delete mode 100644 Task/Loops-Infinite/Oberon/loops-infinite.oberon delete mode 100644 Task/Loops-Infinite/PowerShell/loops-infinite.psh delete mode 100644 Task/Loops-Infinite/REBOL/loops-infinite-1.rebol delete mode 100644 Task/Loops-Infinite/REBOL/loops-infinite-2.rebol delete mode 100644 Task/Loops-Infinite/REBOL/loops-infinite-3.rebol delete mode 100644 Task/Loops-Infinite/ReScript/loops-infinite-1.re delete mode 100644 Task/Loops-Infinite/ReScript/loops-infinite-2.re delete mode 100644 Task/Loops-Infinite/VBScript/loops-infinite.vb delete mode 100644 Task/Loops-N-plus-one-half/Ada/loops-n-plus-one-half.ada delete mode 100644 Task/Loops-N-plus-one-half/AutoIt/loops-n-plus-one-half.autoit delete mode 100644 Task/Loops-N-plus-one-half/COBOL/loops-n-plus-one-half-1.cobol delete mode 100644 Task/Loops-N-plus-one-half/COBOL/loops-n-plus-one-half-2.cobol delete mode 100644 Task/Loops-N-plus-one-half/COBOL/loops-n-plus-one-half-3.cobol delete mode 100644 Task/Loops-N-plus-one-half/COBOL/loops-n-plus-one-half-4.cobol delete mode 100644 Task/Loops-N-plus-one-half/Chapel/loops-n-plus-one-half.chapel delete mode 100644 Task/Loops-N-plus-one-half/Euphoria/loops-n-plus-one-half.ex delete mode 100644 Task/Loops-N-plus-one-half/Haxe/loops-n-plus-one-half.haxe delete mode 100644 Task/Loops-N-plus-one-half/PowerShell/loops-n-plus-one-half-1.psh delete mode 100644 Task/Loops-N-plus-one-half/PowerShell/loops-n-plus-one-half-2.psh delete mode 100644 Task/Loops-N-plus-one-half/REBOL/loops-n-plus-one-half.rebol delete mode 100644 Task/Loops-Nested/Ada/loops-nested.ada delete mode 100644 Task/Loops-Nested/COBOL/loops-nested.cobol delete mode 100644 Task/Loops-Nested/Chapel/loops-nested.chapel delete mode 100644 Task/Loops-Nested/Euphoria/loops-nested.ex delete mode 100644 Task/Loops-Nested/REBOL/loops-nested.rebol delete mode 100644 Task/Loops-Nested/ReScript/loops-nested.re delete mode 100644 Task/Loops-While/Ada/loops-while.ada delete mode 100644 Task/Loops-While/COBOL/loops-while.cobol delete mode 100644 Task/Loops-While/Chapel/loops-while.chapel delete mode 100644 Task/Loops-While/Emacs-Lisp/loops-while.l delete mode 100644 Task/Loops-While/Euphoria/loops-while.ex delete mode 100644 Task/Loops-While/Haxe/loops-while-1.haxe delete mode 100644 Task/Loops-While/Haxe/loops-while-2.haxe delete mode 100644 Task/Loops-While/PowerShell/loops-while.psh delete mode 100644 Task/Loops-While/REBOL/loops-while.rebol delete mode 100644 Task/Loops-While/ReScript/loops-while.re delete mode 100644 Task/Loops-With-multiple-ranges/Ada/loops-with-multiple-ranges.ada delete mode 100644 Task/Loops-With-multiple-ranges/REBOL/loops-with-multiple-ranges.rebol delete mode 100644 Task/Loops-Wrong-ranges/Ada/loops-wrong-ranges.ada delete mode 100644 Task/Loops-Wrong-ranges/REBOL/loops-wrong-ranges.rebol delete mode 100644 Task/Lucas-Lehmer-test/Ada/lucas-lehmer-test.ada delete mode 100644 Task/Lucas-Lehmer-test/PowerShell/lucas-lehmer-test-1.psh delete mode 100644 Task/Lucas-Lehmer-test/PowerShell/lucas-lehmer-test-2.psh delete mode 100644 Task/Lucas-Lehmer-test/VBScript/lucas-lehmer-test.vb delete mode 100644 Task/Ludic-numbers/Ada/ludic-numbers.ada delete mode 100644 Task/Ludic-numbers/PowerShell/ludic-numbers-1.psh delete mode 100644 Task/Ludic-numbers/PowerShell/ludic-numbers-2.psh delete mode 100644 Task/Ludic-numbers/VBScript/ludic-numbers.vb delete mode 100644 Task/Luhn-test-of-credit-card-numbers/Ada/luhn-test-of-credit-card-numbers.ada delete mode 100644 Task/Luhn-test-of-credit-card-numbers/AutoIt/luhn-test-of-credit-card-numbers.autoit delete mode 100644 Task/Luhn-test-of-credit-card-numbers/COBOL/luhn-test-of-credit-card-numbers.cobol delete mode 100644 Task/Luhn-test-of-credit-card-numbers/Emacs-Lisp/luhn-test-of-credit-card-numbers.l delete mode 100644 Task/Luhn-test-of-credit-card-numbers/Euphoria/luhn-test-of-credit-card-numbers.ex delete mode 100644 Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-1.psh delete mode 100644 Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-2.psh delete mode 100644 Task/Luhn-test-of-credit-card-numbers/PowerShell/luhn-test-of-credit-card-numbers-3.psh delete mode 100644 Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb delete mode 100644 Task/Lychrel-numbers/PowerShell/lychrel-numbers-1.psh delete mode 100644 Task/Lychrel-numbers/PowerShell/lychrel-numbers-2.psh delete mode 100644 Task/M-bius-function/PowerShell/m-bius-function.psh delete mode 100644 Task/M-bius-function/RapidQ/m-bius-function.rapidq delete mode 100644 Task/MAC-vendor-lookup/Ada/mac-vendor-lookup.ada delete mode 100644 Task/MAC-vendor-lookup/PowerShell/mac-vendor-lookup.psh delete mode 100644 Task/MAC-vendor-lookup/VBScript/mac-vendor-lookup.vb delete mode 100644 Task/MD4/Ada/md4.ada delete mode 100644 Task/MD4/Emacs-Lisp/md4.l delete mode 100644 Task/MD5-Implementation/Ada/md5-implementation-1.ada delete mode 100644 Task/MD5-Implementation/Ada/md5-implementation-2.ada delete mode 100644 Task/MD5-Implementation/Ada/md5-implementation-3.ada delete mode 100644 Task/MD5/Ada/md5.ada delete mode 100644 Task/MD5/COBOL/md5-1.cobol delete mode 100644 Task/MD5/COBOL/md5-2.cobol delete mode 100644 Task/MD5/Emacs-Lisp/md5.l delete mode 100644 Task/MD5/Haxe/md5.haxe delete mode 100644 Task/MD5/PowerShell/md5.psh delete mode 100644 Task/MD5/REBOL/md5-1.rebol delete mode 100644 Task/MD5/REBOL/md5-2.rebol delete mode 100644 Task/Machine-code/Ada/machine-code.ada delete mode 100644 Task/Machine-code/COBOL/machine-code-1.cobol delete mode 100644 Task/Machine-code/COBOL/machine-code-2.cobol delete mode 100644 Task/Mad-Libs/Ada/mad-libs-1.ada delete mode 100644 Task/Mad-Libs/Ada/mad-libs-2.ada delete mode 100644 Task/Mad-Libs/Ada/mad-libs-3.ada delete mode 100644 Task/Mad-Libs/PowerShell/mad-libs-1.psh delete mode 100644 Task/Mad-Libs/PowerShell/mad-libs-2.psh delete mode 100644 Task/Mad-Libs/PowerShell/mad-libs-3.psh delete mode 100644 Task/Mad-Libs/PowerShell/mad-libs-4.psh delete mode 100644 Task/Mad-Libs/REBOL/mad-libs.rebol delete mode 100644 Task/Mad-Libs/VBScript/mad-libs.vb delete mode 100644 Task/Magic-8-ball/Ada/magic-8-ball.ada delete mode 100644 Task/Magic-8-ball/COBOL/magic-8-ball.cobol delete mode 100644 Task/Magic-constant/Ada/magic-constant.ada delete mode 100644 Task/Magic-squares-of-doubly-even-order/VBScript/magic-squares-of-doubly-even-order.vb delete mode 100644 Task/Magic-squares-of-odd-order/Ada/magic-squares-of-odd-order.ada delete mode 100644 Task/Magic-squares-of-odd-order/VBScript/magic-squares-of-odd-order.vb delete mode 100644 Task/Make-directory-path/Ada/make-directory-path.ada delete mode 100644 Task/Make-directory-path/PowerShell/make-directory-path.psh delete mode 100644 Task/Man-or-boy-test/Ada/man-or-boy-test-1.ada delete mode 100644 Task/Man-or-boy-test/Ada/man-or-boy-test-2.ada delete mode 100644 Task/Man-or-boy-test/Ada/man-or-boy-test-3.ada delete mode 100644 Task/Mandelbrot-set/Ada/mandelbrot-set-1.ada delete mode 100644 Task/Mandelbrot-set/Ada/mandelbrot-set-2.ada delete mode 100644 Task/Mandelbrot-set/Ada/mandelbrot-set-3.ada delete mode 100644 Task/Mandelbrot-set/COBOL/mandelbrot-set.cobol delete mode 100644 Task/Mandelbrot-set/Emacs-Lisp/mandelbrot-set-1.l delete mode 100644 Task/Mandelbrot-set/Emacs-Lisp/mandelbrot-set-2.l delete mode 100644 Task/Mandelbrot-set/Haxe/mandelbrot-set-1.haxe delete mode 100644 Task/Mandelbrot-set/Haxe/mandelbrot-set-2.haxe delete mode 100644 Task/Mandelbrot-set/PowerShell/mandelbrot-set.psh delete mode 100644 Task/Mandelbrot-set/Python/mandelbrot-set-12.py delete mode 100644 Task/Mandelbrot-set/VBScript/mandelbrot-set.vb delete mode 100644 Task/Map-range/Ada/map-range.ada delete mode 100644 Task/Map-range/COBOL/map-range.cobol delete mode 100644 Task/Map-range/Emacs-Lisp/map-range.l delete mode 100644 Task/Map-range/Euphoria/map-range.ex delete mode 100644 Task/Map-range/Go/map-range.go delete mode 100644 Task/Map-range/PowerShell/map-range-1.psh delete mode 100644 Task/Map-range/PowerShell/map-range-2.psh delete mode 100644 Task/Map-range/ReScript/map-range-1.re delete mode 100644 Task/Map-range/ReScript/map-range-2.re delete mode 100644 Task/Mastermind/Ada/mastermind.ada delete mode 100644 Task/Matrix-chain-multiplication/Ada/matrix-chain-multiplication-1.ada delete mode 100644 Task/Matrix-chain-multiplication/Ada/matrix-chain-multiplication-2.ada delete mode 100644 Task/Matrix-chain-multiplication/Ada/matrix-chain-multiplication-3.ada delete mode 100644 Task/Matrix-digital-rain/Ada/matrix-digital-rain.ada delete mode 100644 Task/Matrix-exponentiation-operator/Ada/matrix-exponentiation-operator-1.ada delete mode 100644 Task/Matrix-exponentiation-operator/Ada/matrix-exponentiation-operator-2.ada delete mode 100644 Task/Matrix-exponentiation-operator/Ada/matrix-exponentiation-operator-3.ada delete mode 100644 Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-1.chapel delete mode 100644 Task/Matrix-exponentiation-operator/Chapel/matrix-exponentiation-operator-2.chapel delete mode 100644 Task/Matrix-exponentiation-operator/Scheme/matrix-exponentiation-operator.scm delete mode 100644 Task/Matrix-multiplication/Ada/matrix-multiplication-1.ada delete mode 100644 Task/Matrix-multiplication/Ada/matrix-multiplication-2.ada delete mode 100644 Task/Matrix-multiplication/Chapel/matrix-multiplication-1.chapel delete mode 100644 Task/Matrix-multiplication/Chapel/matrix-multiplication-2.chapel delete mode 100644 Task/Matrix-multiplication/Emacs-Lisp/matrix-multiplication.l delete mode 100644 Task/Matrix-multiplication/Euphoria/matrix-multiplication.ex delete mode 100644 Task/Matrix-multiplication/PowerShell/matrix-multiplication.psh delete mode 100644 Task/Matrix-multiplication/Scheme/matrix-multiplication.scm delete mode 100644 Task/Matrix-multiplication/VBScript/matrix-multiplication.vb delete mode 100644 Task/Matrix-transposition/Ada/matrix-transposition.ada delete mode 100644 Task/Matrix-transposition/Emacs-Lisp/matrix-transposition-1.l delete mode 100644 Task/Matrix-transposition/Emacs-Lisp/matrix-transposition-2.l delete mode 100644 Task/Matrix-transposition/Euphoria/matrix-transposition.ex delete mode 100644 Task/Matrix-transposition/Haxe/matrix-transposition.haxe delete mode 100644 Task/Matrix-transposition/PowerShell/matrix-transposition-1.psh delete mode 100644 Task/Matrix-transposition/PowerShell/matrix-transposition-2.psh delete mode 100644 Task/Matrix-transposition/Scheme/matrix-transposition.scm delete mode 100644 Task/Matrix-transposition/VBScript/matrix-transposition.vb delete mode 100644 Task/Maximum-triangle-path-sum/Ada/maximum-triangle-path-sum.ada delete mode 100644 Task/Maximum-triangle-path-sum/VBScript/maximum-triangle-path-sum.vb delete mode 100644 Task/Mayan-numerals/BASIC/mayan-numerals.basic delete mode 100644 Task/Maze-generation/Ada/maze-generation-1.ada delete mode 100644 Task/Maze-generation/Ada/maze-generation-2.ada delete mode 100644 Task/Maze-generation/Ada/maze-generation-3.ada delete mode 100644 Task/Maze-generation/Chapel/maze-generation.chapel delete mode 100644 Task/Maze-generation/Emacs-Lisp/maze-generation.l delete mode 100644 Task/Maze-solving/Ada/maze-solving.ada delete mode 100644 Task/Maze-solving/Emacs-Lisp/maze-solving.l delete mode 100644 Task/McNuggets-problem/Ada/mcnuggets-problem.ada delete mode 100644 Task/McNuggets-problem/COBOL/mcnuggets-problem.cobol delete mode 100644 Task/McNuggets-problem/PowerShell/mcnuggets-problem.psh delete mode 100644 Task/Median-filter/Ada/median-filter-1.ada delete mode 100644 Task/Median-filter/Ada/median-filter-2.ada delete mode 100644 Task/Meissel-Mertens-constant/11l/meissel-mertens-constant.11l delete mode 100644 Task/Meissel-Mertens-constant/ALGOL-68/meissel-mertens-constant.alg delete mode 100644 Task/Meissel-Mertens-constant/ALGOL-W/meissel-mertens-constant.alg delete mode 100644 Task/Meissel-Mertens-constant/Arturo/meissel-mertens-constant.arturo delete mode 100644 Task/Meissel-Mertens-constant/BASIC256/meissel-mertens-constant.basic delete mode 100644 Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp delete mode 100644 Task/Meissel-Mertens-constant/Dart/meissel-mertens-constant.dart delete mode 100644 Task/Meissel-Mertens-constant/Delphi/meissel-mertens-constant.pas delete mode 100644 Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy delete mode 100644 Task/Meissel-Mertens-constant/FreeBASIC/meissel-mertens-constant.basic delete mode 100644 Task/Meissel-Mertens-constant/Go/meissel-mertens-constant.go delete mode 100644 Task/Meissel-Mertens-constant/J/meissel-mertens-constant-1.j delete mode 100644 Task/Meissel-Mertens-constant/J/meissel-mertens-constant-2.j delete mode 100644 Task/Meissel-Mertens-constant/J/meissel-mertens-constant-3.j delete mode 100644 Task/Meissel-Mertens-constant/J/meissel-mertens-constant-4.j delete mode 100644 Task/Meissel-Mertens-constant/Java/meissel-mertens-constant.java delete mode 100644 Task/Meissel-Mertens-constant/JavaScript/meissel-mertens-constant.js delete mode 100644 Task/Meissel-Mertens-constant/Julia/meissel-mertens-constant.jl delete mode 100644 Task/Meissel-Mertens-constant/Mathematica/meissel-mertens-constant.math delete mode 100644 Task/Meissel-Mertens-constant/Maxima/meissel-mertens-constant.maxima delete mode 100644 Task/Meissel-Mertens-constant/Nim/meissel-mertens-constant.nim delete mode 100644 Task/Meissel-Mertens-constant/PARI-GP/meissel-mertens-constant-1.parigp delete mode 100644 Task/Meissel-Mertens-constant/PARI-GP/meissel-mertens-constant-2.parigp delete mode 100644 Task/Meissel-Mertens-constant/PascalABC.NET/meissel-mertens-constant.pas delete mode 100644 Task/Meissel-Mertens-constant/Perl/meissel-mertens-constant.pl delete mode 100644 Task/Meissel-Mertens-constant/Phix/meissel-mertens-constant-1.phix delete mode 100644 Task/Meissel-Mertens-constant/Phix/meissel-mertens-constant-2.phix delete mode 100644 Task/Meissel-Mertens-constant/PureBasic/meissel-mertens-constant.basic delete mode 100644 Task/Meissel-Mertens-constant/Python/meissel-mertens-constant.py delete mode 100644 Task/Meissel-Mertens-constant/REXX/meissel-mertens-constant.rexx delete mode 100644 Task/Meissel-Mertens-constant/Raku/meissel-mertens-constant.raku delete mode 100644 Task/Meissel-Mertens-constant/Run-BASIC/meissel-mertens-constant.basic delete mode 100644 Task/Meissel-Mertens-constant/Rust/meissel-mertens-constant.rs delete mode 100644 Task/Meissel-Mertens-constant/Sidef/meissel-mertens-constant.sidef delete mode 100644 Task/Meissel-Mertens-constant/True-BASIC/meissel-mertens-constant.basic delete mode 100644 Task/Meissel-Mertens-constant/Wren/meissel-mertens-constant-1.wren delete mode 100644 Task/Meissel-Mertens-constant/Wren/meissel-mertens-constant-2.wren delete mode 100644 Task/Meissel-Mertens-constant/XPL0/meissel-mertens-constant.xpl0 delete mode 100644 Task/Meissel-Mertens-constant/Yabasic/meissel-mertens-constant.basic delete mode 100644 Task/Memory-allocation/Ada/memory-allocation-1.ada delete mode 100644 Task/Memory-allocation/Ada/memory-allocation-2.ada delete mode 100644 Task/Memory-allocation/Ada/memory-allocation-3.ada delete mode 100644 Task/Memory-allocation/Ada/memory-allocation-4.ada delete mode 100644 Task/Memory-allocation/COBOL/memory-allocation.cobol delete mode 100644 Task/Memory-layout-of-a-data-structure/Ada/memory-layout-of-a-data-structure.ada delete mode 100644 Task/Menu/Ada/menu.ada delete mode 100644 Task/Menu/COBOL/menu.cobol delete mode 100644 Task/Menu/Emacs-Lisp/menu.l delete mode 100644 Task/Menu/Euphoria/menu.ex delete mode 100644 Task/Menu/PowerShell/menu.psh delete mode 100644 Task/Menu/REBOL/menu.rebol delete mode 100644 Task/Menu/VBScript/menu.vb delete mode 100644 Task/Mertens-function/COBOL/mertens-function.cobol delete mode 100644 Task/Metered-concurrency/Ada/metered-concurrency-1.ada delete mode 100644 Task/Metered-concurrency/Ada/metered-concurrency-2.ada delete mode 100644 Task/Metered-concurrency/Ada/metered-concurrency-3.ada delete mode 100644 Task/Metered-concurrency/Euphoria/metered-concurrency.ex delete mode 100644 Task/Metronome/Ada/metronome.ada delete mode 100644 Task/Mian-Chowla-sequence/Ada/mian-chowla-sequence.ada delete mode 100644 Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-1.vb delete mode 100644 Task/Mian-Chowla-sequence/VBScript/mian-chowla-sequence-2.vb delete mode 100644 Task/Middle-three-digits/Ada/middle-three-digits.ada delete mode 100644 Task/Middle-three-digits/COBOL/middle-three-digits-1.cobol delete mode 100644 Task/Middle-three-digits/COBOL/middle-three-digits-2.cobol delete mode 100644 Task/Middle-three-digits/PowerShell/middle-three-digits.psh delete mode 100644 Task/Middle-three-digits/VBScript/middle-three-digits.vb delete mode 100644 Task/Miller-Rabin-primality-test/11l/miller-rabin-primality-test.11l delete mode 100644 Task/Miller-Rabin-primality-test/AArch64-Assembly/miller-rabin-primality-test.aarch64 delete mode 100644 Task/Miller-Rabin-primality-test/ALGOL-68/miller-rabin-primality-test.alg delete mode 100644 Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm delete mode 100644 Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-1.ada delete mode 100644 Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-2.ada delete mode 100644 Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-3.ada delete mode 100644 Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-4.ada delete mode 100644 Task/Miller-Rabin-primality-test/Ada/miller-rabin-primality-test-5.ada delete mode 100644 Task/Miller-Rabin-primality-test/AutoHotkey/miller-rabin-primality-test.ahk delete mode 100644 Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-1.bqn delete mode 100644 Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-2.bqn delete mode 100644 Task/Miller-Rabin-primality-test/BQN/miller-rabin-primality-test-3.bqn delete mode 100644 Task/Miller-Rabin-primality-test/Bc/miller-rabin-primality-test.bc delete mode 100644 Task/Miller-Rabin-primality-test/Bracmat/miller-rabin-primality-test.bracmat delete mode 100644 Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp delete mode 100644 Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-1.cs delete mode 100644 Task/Miller-Rabin-primality-test/C-sharp/miller-rabin-primality-test-2.cs delete mode 100644 Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-1.c delete mode 100644 Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-2.c delete mode 100644 Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-3.c delete mode 100644 Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-4.c delete mode 100644 Task/Miller-Rabin-primality-test/C/miller-rabin-primality-test-5.c delete mode 100644 Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-1.clj delete mode 100644 Task/Miller-Rabin-primality-test/Clojure/miller-rabin-primality-test-2.clj delete mode 100644 Task/Miller-Rabin-primality-test/Commodore-BASIC/miller-rabin-primality-test.basic delete mode 100644 Task/Miller-Rabin-primality-test/Common-Lisp/miller-rabin-primality-test.lisp delete mode 100644 Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-1.cr delete mode 100644 Task/Miller-Rabin-primality-test/Crystal/miller-rabin-primality-test-2.cr delete mode 100644 Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d delete mode 100644 Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-1.e delete mode 100644 Task/Miller-Rabin-primality-test/E/miller-rabin-primality-test-2.e delete mode 100644 Task/Miller-Rabin-primality-test/EchoLisp/miller-rabin-primality-test.l delete mode 100644 Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-1.ex delete mode 100644 Task/Miller-Rabin-primality-test/Elixir/miller-rabin-primality-test-2.ex delete mode 100644 Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-1.erl delete mode 100644 Task/Miller-Rabin-primality-test/Erlang/miller-rabin-primality-test-2.erl delete mode 100644 Task/Miller-Rabin-primality-test/F-Sharp/miller-rabin-primality-test.fs delete mode 100644 Task/Miller-Rabin-primality-test/Forth/miller-rabin-primality-test.fth delete mode 100644 Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-1.f delete mode 100644 Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-2.f delete mode 100644 Task/Miller-Rabin-primality-test/Fortran/miller-rabin-primality-test-3.f delete mode 100644 Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-1.basic delete mode 100644 Task/Miller-Rabin-primality-test/FreeBASIC/miller-rabin-primality-test-2.basic delete mode 100644 Task/Miller-Rabin-primality-test/FunL/miller-rabin-primality-test.funl delete mode 100644 Task/Miller-Rabin-primality-test/Go/miller-rabin-primality-test.go delete mode 100644 Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-1.hs delete mode 100644 Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-2.hs delete mode 100644 Task/Miller-Rabin-primality-test/Haskell/miller-rabin-primality-test-3.hs delete mode 100644 Task/Miller-Rabin-primality-test/Icon/miller-rabin-primality-test.icon delete mode 100644 Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-1.java delete mode 100644 Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java delete mode 100644 Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js delete mode 100644 Task/Miller-Rabin-primality-test/Julia/miller-rabin-primality-test.jl delete mode 100644 Task/Miller-Rabin-primality-test/Kotlin/miller-rabin-primality-test.kts delete mode 100644 Task/Miller-Rabin-primality-test/Liberty-BASIC/miller-rabin-primality-test.basic delete mode 100644 Task/Miller-Rabin-primality-test/Lua/miller-rabin-primality-test.lua delete mode 100644 Task/Miller-Rabin-primality-test/M2000-Interpreter/miller-rabin-primality-test.m2000 delete mode 100644 Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-1.math delete mode 100644 Task/Miller-Rabin-primality-test/Mathematica/miller-rabin-primality-test-2.math delete mode 100644 Task/Miller-Rabin-primality-test/Maxima/miller-rabin-primality-test.maxima delete mode 100644 Task/Miller-Rabin-primality-test/Mercury/miller-rabin-primality-test.mercury delete mode 100644 Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-1.nim delete mode 100644 Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-2.nim delete mode 100644 Task/Miller-Rabin-primality-test/Nim/miller-rabin-primality-test-3.nim delete mode 100644 Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz delete mode 100644 Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-1.parigp delete mode 100644 Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-2.parigp delete mode 100644 Task/Miller-Rabin-primality-test/PARI-GP/miller-rabin-primality-test-3.parigp delete mode 100644 Task/Miller-Rabin-primality-test/PHP/miller-rabin-primality-test.php delete mode 100644 Task/Miller-Rabin-primality-test/PascalABC.NET/miller-rabin-primality-test.pas delete mode 100644 Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl delete mode 100644 Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl delete mode 100644 Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl delete mode 100644 Task/Miller-Rabin-primality-test/Phix/miller-rabin-primality-test-1.phix delete mode 100644 Task/Miller-Rabin-primality-test/Phix/miller-rabin-primality-test-2.phix delete mode 100644 Task/Miller-Rabin-primality-test/Phix/miller-rabin-primality-test-3.phix delete mode 100644 Task/Miller-Rabin-primality-test/PicoLisp/miller-rabin-primality-test.l delete mode 100644 Task/Miller-Rabin-primality-test/Pike/miller-rabin-primality-test.pike delete mode 100644 Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro delete mode 100644 Task/Miller-Rabin-primality-test/PureBasic/miller-rabin-primality-test.basic delete mode 100644 Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-1.py delete mode 100644 Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test-2.py delete mode 100644 Task/Miller-Rabin-primality-test/Quackery/miller-rabin-primality-test.quackery delete mode 100644 Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx delete mode 100644 Task/Miller-Rabin-primality-test/Racket/miller-rabin-primality-test.rkt delete mode 100644 Task/Miller-Rabin-primality-test/Raku/miller-rabin-primality-test.raku delete mode 100644 Task/Miller-Rabin-primality-test/Ring/miller-rabin-primality-test.ring delete mode 100644 Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-1.rb delete mode 100644 Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-2.rb delete mode 100644 Task/Miller-Rabin-primality-test/Ruby/miller-rabin-primality-test-3.rb delete mode 100644 Task/Miller-Rabin-primality-test/Run-BASIC/miller-rabin-primality-test.basic delete mode 100644 Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-1.rs delete mode 100644 Task/Miller-Rabin-primality-test/Rust/miller-rabin-primality-test-2.rs delete mode 100644 Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala delete mode 100644 Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala delete mode 100644 Task/Miller-Rabin-primality-test/Scheme/miller-rabin-primality-test.scm delete mode 100644 Task/Miller-Rabin-primality-test/Seed7/miller-rabin-primality-test.seed7 delete mode 100644 Task/Miller-Rabin-primality-test/Sidef/miller-rabin-primality-test.sidef delete mode 100644 Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-1.st delete mode 100644 Task/Miller-Rabin-primality-test/Smalltalk/miller-rabin-primality-test-2.st delete mode 100644 Task/Miller-Rabin-primality-test/Standard-ML/miller-rabin-primality-test.ml delete mode 100644 Task/Miller-Rabin-primality-test/Swift/miller-rabin-primality-test.swift delete mode 100644 Task/Miller-Rabin-primality-test/Tcl/miller-rabin-primality-test.tcl delete mode 100644 Task/Miller-Rabin-primality-test/Wren/miller-rabin-primality-test.wren delete mode 100644 Task/Miller-Rabin-primality-test/X86-64-Assembly/miller-rabin-primality-test.x86-64 delete mode 100644 Task/Miller-Rabin-primality-test/Zkl/miller-rabin-primality-test.zkl delete mode 100644 Task/Mind-boggling-card-trick/Ada/mind-boggling-card-trick.ada delete mode 100644 Task/Minesweeper-game/Ada/minesweeper-game.ada delete mode 100644 Task/Minimal-steps-down-to-1/Ada/minimal-steps-down-to-1.ada delete mode 100644 Task/Minimum-multiple-of-m-where-digital-sum-equals-m/COBOL/minimum-multiple-of-m-where-digital-sum-equals-m.cobol delete mode 100644 Task/Modified-random-distribution/Ada/modified-random-distribution.ada delete mode 100644 Task/Modular-arithmetic/Ada/modular-arithmetic.ada delete mode 100644 Task/Modular-exponentiation/Ada/modular-exponentiation.ada delete mode 100644 Task/Modular-exponentiation/Emacs-Lisp/modular-exponentiation.l delete mode 100644 Task/Modular-exponentiation/PowerShell/modular-exponentiation.psh delete mode 100644 Task/Modular-inverse/Ada/modular-inverse.ada delete mode 100644 Task/Modular-inverse/PowerShell/modular-inverse.psh delete mode 100644 Task/Monte-Carlo-methods/Ada/monte-carlo-methods.ada delete mode 100644 Task/Monte-Carlo-methods/PowerShell/monte-carlo-methods.psh delete mode 100644 Task/Monty-Hall-problem/Ada/monty-hall-problem.ada delete mode 100644 Task/Monty-Hall-problem/COBOL/monty-hall-problem.cobol delete mode 100644 Task/Monty-Hall-problem/Chapel/monty-hall-problem-1.chapel delete mode 100644 Task/Monty-Hall-problem/Chapel/monty-hall-problem-2.chapel delete mode 100644 Task/Monty-Hall-problem/Emacs-Lisp/monty-hall-problem.l delete mode 100644 Task/Monty-Hall-problem/Euphoria/monty-hall-problem.ex delete mode 100644 Task/Monty-Hall-problem/PowerShell/monty-hall-problem.psh delete mode 100644 Task/Morse-code/Ada/morse-code-1.ada delete mode 100644 Task/Morse-code/Ada/morse-code-2.ada delete mode 100644 Task/Morse-code/Ada/morse-code-3.ada delete mode 100644 Task/Morse-code/PowerShell/morse-code-1.psh delete mode 100644 Task/Morse-code/PowerShell/morse-code-2.psh delete mode 100644 Task/Morse-code/PowerShell/morse-code-3.psh delete mode 100644 Task/Mouse-position/Ada/mouse-position.ada delete mode 100644 Task/Mouse-position/Emacs-Lisp/mouse-position.l delete mode 100644 Task/Mouse-position/Odin/mouse-position.odin delete mode 100644 Task/Move-to-front-algorithm/Ada/move-to-front-algorithm.ada delete mode 100644 Task/Move-to-front-algorithm/PowerShell/move-to-front-algorithm.psh delete mode 100644 Task/Move-to-front-algorithm/VBScript/move-to-front-algorithm.vb delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-1.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-10.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-11.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-12.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-13.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-2.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-3.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-4.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-5.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-6.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-7.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-8.ada delete mode 100644 Task/Multi-dimensional-array/Ada/multi-dimensional-array-9.ada delete mode 100644 Task/Multi-dimensional-array/REXX/multi-dimensional-array-1.rexx delete mode 100644 Task/Multi-dimensional-array/REXX/multi-dimensional-array-2.rexx delete mode 100644 Task/Multi-dimensional-array/REXX/multi-dimensional-array-3.rexx delete mode 100644 Task/Multifactorial/Ada/multifactorial.ada delete mode 100644 Task/Multifactorial/VBScript/multifactorial.vb delete mode 100644 Task/Multiple-distinct-objects/Ada/multiple-distinct-objects-1.ada delete mode 100644 Task/Multiple-distinct-objects/Ada/multiple-distinct-objects-2.ada delete mode 100644 Task/Multiple-distinct-objects/Ada/multiple-distinct-objects-3.ada delete mode 100644 Task/Multiple-distinct-objects/PowerShell/multiple-distinct-objects-1.psh delete mode 100644 Task/Multiple-distinct-objects/PowerShell/multiple-distinct-objects-2.psh delete mode 100644 Task/Multiple-regression/Ada/multiple-regression-1.ada delete mode 100644 Task/Multiple-regression/Ada/multiple-regression-2.ada delete mode 100644 Task/Multiple-regression/Ada/multiple-regression-3.ada delete mode 100644 Task/Multiple-regression/Emacs-Lisp/multiple-regression.l delete mode 100644 Task/Multiplication-tables/Ada/multiplication-tables.ada delete mode 100644 Task/Multiplication-tables/AutoIt/multiplication-tables.autoit delete mode 100644 Task/Multiplication-tables/COBOL/multiplication-tables.cobol delete mode 100644 Task/Multiplication-tables/Euphoria/multiplication-tables.ex delete mode 100644 Task/Multiplication-tables/PowerShell/multiplication-tables-1.psh delete mode 100644 Task/Multiplication-tables/PowerShell/multiplication-tables-2.psh delete mode 100644 Task/Multiplication-tables/REBOL/multiplication-tables.rebol delete mode 100644 Task/Multiplication-tables/VBScript/multiplication-tables.vb delete mode 100644 Task/Multiplicative-order/Ada/multiplicative-order-1.ada delete mode 100644 Task/Multiplicative-order/Ada/multiplicative-order-2.ada delete mode 100644 Task/Multiplicative-order/Ada/multiplicative-order-3.ada delete mode 100644 Task/Multisplit/Ada/multisplit.ada delete mode 100644 Task/Multisplit/PowerShell/multisplit.psh delete mode 100644 Task/Multisplit/VBScript/multisplit.vb delete mode 100644 Task/Munchausen-numbers/Ada/munchausen-numbers.ada delete mode 100644 Task/Munchausen-numbers/COBOL/munchausen-numbers.cobol delete mode 100644 Task/Munchausen-numbers/VBScript/munchausen-numbers.vb delete mode 100644 Task/Munching-squares/Ada/munching-squares.ada delete mode 100644 Task/Musical-scale/Ada/musical-scale.ada delete mode 100644 Task/Musical-scale/Emacs-Lisp/musical-scale.l delete mode 100644 Task/Musical-scale/PowerShell/musical-scale.psh delete mode 100644 Task/Mutex/Ada/mutex-1.ada delete mode 100644 Task/Mutex/Ada/mutex-2.ada delete mode 100644 Task/Mutex/Ada/mutex-3.ada delete mode 100644 Task/Mutual-recursion/Ada/mutual-recursion-1.ada delete mode 100644 Task/Mutual-recursion/Ada/mutual-recursion-2.ada delete mode 100644 Task/Mutual-recursion/Euphoria/mutual-recursion.ex delete mode 100644 Task/Mutual-recursion/PowerShell/mutual-recursion.psh delete mode 100644 Task/Mutual-recursion/REBOL/mutual-recursion.rebol delete mode 100644 Task/N-queens-problem/Ada/n-queens-problem-1.ada delete mode 100644 Task/N-queens-problem/Ada/n-queens-problem-2.ada delete mode 100644 Task/N-queens-problem/Emacs-Lisp/n-queens-problem.l delete mode 100644 Task/N-queens-problem/PowerShell/n-queens-problem-1.psh delete mode 100644 Task/N-queens-problem/PowerShell/n-queens-problem-2.psh delete mode 100644 Task/N-queens-problem/VBScript/n-queens-problem.vb delete mode 100644 Task/Named-parameters/Ada/named-parameters-1.ada delete mode 100644 Task/Named-parameters/Ada/named-parameters-2.ada delete mode 100644 Task/Named-parameters/PowerShell/named-parameters-1.psh delete mode 100644 Task/Named-parameters/PowerShell/named-parameters-2.psh delete mode 100644 Task/Named-parameters/PowerShell/named-parameters-3.psh delete mode 100644 Task/Named-parameters/PowerShell/named-parameters-4.psh delete mode 100644 Task/Naming-conventions/Ada/naming-conventions-1.ada delete mode 100644 Task/Naming-conventions/Ada/naming-conventions-2.ada delete mode 100644 Task/Naming-conventions/Ada/naming-conventions-3.ada delete mode 100644 Task/Narcissist/Ada/narcissist.ada delete mode 100644 Task/Narcissist/PowerShell/narcissist-1.psh delete mode 100644 Task/Narcissist/PowerShell/narcissist-2.psh delete mode 100644 Task/Narcissistic-decimal-number/Ada/narcissistic-decimal-number.ada delete mode 100644 Task/Narcissistic-decimal-number/COBOL/narcissistic-decimal-number.cobol delete mode 100644 Task/Narcissistic-decimal-number/PowerShell/narcissistic-decimal-number.psh delete mode 100644 Task/Narcissistic-decimal-number/VBScript/narcissistic-decimal-number.vb delete mode 100644 Task/Natural-sorting/PowerShell/natural-sorting.psh delete mode 100644 Task/Nautical-bell/PowerShell/nautical-bell.psh delete mode 100644 Task/Negative-base-numbers/Ada/negative-base-numbers.ada delete mode 100644 Task/Nested-function/Ada/nested-function.ada delete mode 100644 Task/Next-highest-int-from-digits/Ada/next-highest-int-from-digits.ada delete mode 100644 Task/Nim-game/Ada/nim-game.ada delete mode 100644 Task/Nim-game/COBOL/nim-game.cobol delete mode 100644 Task/Non-continuous-subsequences/Ada/non-continuous-subsequences.ada delete mode 100644 Task/Non-continuous-subsequences/PowerShell/non-continuous-subsequences.psh delete mode 100644 Task/Non-continuous-subsequences/VBScript/non-continuous-subsequences.vb delete mode 100644 Task/Non-decimal-radices-Convert/Ada/non-decimal-radices-convert.ada delete mode 100644 Task/Non-decimal-radices-Convert/Euphoria/non-decimal-radices-convert.ex delete mode 100644 Task/Non-decimal-radices-Input/Ada/non-decimal-radices-input.ada delete mode 100644 Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-1.psh delete mode 100644 Task/Non-decimal-radices-Input/PowerShell/non-decimal-radices-input-2.psh delete mode 100644 Task/Non-decimal-radices-Output/Ada/non-decimal-radices-output.ada delete mode 100644 Task/Non-decimal-radices-Output/Euphoria/non-decimal-radices-output.ex delete mode 100644 Task/Non-decimal-radices-Output/PowerShell/non-decimal-radices-output.psh delete mode 100644 Task/Nth-root/Ada/nth-root.ada delete mode 100644 Task/Nth-root/AutoIt/nth-root.autoit delete mode 100644 Task/Nth-root/COBOL/nth-root.cobol delete mode 100644 Task/Nth-root/PowerShell/nth-root.psh delete mode 100644 Task/Nth/Ada/nth.ada delete mode 100644 Task/Nth/COBOL/nth.cobol delete mode 100644 Task/Nth/PowerShell/nth-1.psh delete mode 100644 Task/Nth/PowerShell/nth-2.psh delete mode 100644 Task/Null-object/Ada/null-object.ada delete mode 100644 Task/Null-object/AutoIt/null-object.autoit delete mode 100644 Task/Null-object/COBOL/null-object.cobol delete mode 100644 Task/Null-object/Chapel/null-object.chapel delete mode 100644 Task/Null-object/PowerShell/null-object.psh delete mode 100644 Task/Null-object/REBOL/null-object-1.rebol delete mode 100644 Task/Null-object/REBOL/null-object-2.rebol delete mode 100644 Task/Number-names/Ada/number-names.ada delete mode 100644 Task/Number-names/Euphoria/number-names.ex delete mode 100644 Task/Number-names/PowerShell/number-names.psh delete mode 100644 Task/Number-reversal-game/Ada/number-reversal-game.ada delete mode 100644 Task/Number-reversal-game/COBOL/number-reversal-game.cobol delete mode 100644 Task/Number-reversal-game/Euphoria/number-reversal-game.ex delete mode 100644 Task/Number-reversal-game/PowerShell/number-reversal-game.psh delete mode 100644 Task/Number-reversal-game/REBOL/number-reversal-game.rebol delete mode 100644 Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/Ada/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.ada delete mode 100644 Task/Numbers-with-equal-rises-and-falls/Ada/numbers-with-equal-rises-and-falls.ada delete mode 100644 Task/Numeric-error-propagation/Ada/numeric-error-propagation-1.ada delete mode 100644 Task/Numeric-error-propagation/Ada/numeric-error-propagation-2.ada delete mode 100644 Task/Numeric-error-propagation/Ada/numeric-error-propagation-3.ada delete mode 100644 Task/Numerical-integration/Ada/numerical-integration-1.ada delete mode 100644 Task/Numerical-integration/Ada/numerical-integration-2.ada delete mode 100644 Task/Numerical-integration/Ada/numerical-integration-3.ada delete mode 100644 Task/Numerical-integration/Chapel/numerical-integration-1.chapel delete mode 100644 Task/Numerical-integration/Chapel/numerical-integration-2.chapel delete mode 100644 Task/Numerical-integration/Euphoria/numerical-integration.ex delete mode 100644 Task/Object-serialization/Ada/object-serialization-1.ada delete mode 100644 Task/Object-serialization/Ada/object-serialization-2.ada delete mode 100644 Task/Object-serialization/Ada/object-serialization-3.ada delete mode 100644 Task/Object-serialization/REBOL/object-serialization.rebol delete mode 100644 Task/Odd-word-problem/Ada/odd-word-problem.ada delete mode 100644 Task/Old-lady-swallowed-a-fly/Ada/old-lady-swallowed-a-fly.ada delete mode 100644 Task/Old-lady-swallowed-a-fly/COBOL/old-lady-swallowed-a-fly.cobol delete mode 100644 Task/Old-lady-swallowed-a-fly/PowerShell/old-lady-swallowed-a-fly.psh delete mode 100644 Task/Old-lady-swallowed-a-fly/VBScript/old-lady-swallowed-a-fly.vb delete mode 100644 Task/One-dimensional-cellular-automata/Ada/one-dimensional-cellular-automata.ada delete mode 100644 Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-1.cobol delete mode 100644 Task/One-dimensional-cellular-automata/COBOL/one-dimensional-cellular-automata-2.cobol delete mode 100644 Task/One-dimensional-cellular-automata/Euphoria/one-dimensional-cellular-automata.ex delete mode 100644 Task/One-of-n-lines-in-a-file/Ada/one-of-n-lines-in-a-file.ada delete mode 100644 Task/One-of-n-lines-in-a-file/Chapel/one-of-n-lines-in-a-file.chapel delete mode 100644 Task/One-of-n-lines-in-a-file/Euphoria/one-of-n-lines-in-a-file.ex delete mode 100644 Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-1.psh delete mode 100644 Task/One-of-n-lines-in-a-file/PowerShell/one-of-n-lines-in-a-file-2.psh delete mode 100644 Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vb delete mode 100644 Task/OpenGL/Ada/opengl.ada delete mode 100644 Task/OpenGL/Euphoria/opengl.ex delete mode 100644 Task/Optional-parameters/Ada/optional-parameters-1.ada delete mode 100644 Task/Optional-parameters/Ada/optional-parameters-2.ada delete mode 100644 Task/Optional-parameters/REXX/optional-parameters-1.rexx delete mode 100644 Task/Optional-parameters/REXX/optional-parameters-2.rexx delete mode 100644 Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.psh delete mode 100644 Task/Order-two-numerical-lists/Ada/order-two-numerical-lists.ada delete mode 100644 Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-1.psh delete mode 100644 Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-2.psh delete mode 100644 Task/Order-two-numerical-lists/PowerShell/order-two-numerical-lists-3.psh delete mode 100644 Task/Order-two-numerical-lists/VBScript/order-two-numerical-lists.vb delete mode 100644 Task/Ordered-partitions/Ada/ordered-partitions-1.ada delete mode 100644 Task/Ordered-partitions/Ada/ordered-partitions-2.ada delete mode 100644 Task/Ordered-partitions/Ada/ordered-partitions-3.ada delete mode 100644 Task/Ordered-words/ALGOL-68/ordered-words.alg delete mode 100644 Task/Ordered-words/Ada/ordered-words.ada delete mode 100644 Task/Ordered-words/COBOL/ordered-words.cobol delete mode 100644 Task/Ordered-words/Emacs-Lisp/ordered-words.l delete mode 100644 Task/Ordered-words/Euphoria/ordered-words.ex delete mode 100644 Task/Ordered-words/PowerShell/ordered-words.psh delete mode 100644 Task/Ordered-words/VBScript/ordered-words.vb delete mode 100644 Task/Palindrome-dates/Ada/palindrome-dates.ada delete mode 100644 Task/Palindrome-detection/Ada/palindrome-detection-1.ada delete mode 100644 Task/Palindrome-detection/Ada/palindrome-detection-2.ada delete mode 100644 Task/Palindrome-detection/AutoIt/palindrome-detection-1.autoit delete mode 100644 Task/Palindrome-detection/AutoIt/palindrome-detection-2.autoit delete mode 100644 Task/Palindrome-detection/COBOL/palindrome-detection.cobol delete mode 100644 Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-1.l delete mode 100644 Task/Palindrome-detection/Emacs-Lisp/palindrome-detection-2.l delete mode 100644 Task/Palindrome-detection/Euphoria/palindrome-detection-1.ex delete mode 100644 Task/Palindrome-detection/Euphoria/palindrome-detection-2.ex delete mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection-1.psh delete mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection-2.psh delete mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection-3.psh delete mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection-4.psh delete mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection-5.psh delete mode 100644 Task/Palindrome-detection/PowerShell/palindrome-detection-6.psh delete mode 100644 Task/Palindrome-detection/REBOL/palindrome-detection.rebol delete mode 100644 Task/Palindrome-detection/VBScript/palindrome-detection-1.vb delete mode 100644 Task/Palindrome-detection/VBScript/palindrome-detection-2.vb delete mode 100644 Task/Pancake-numbers/COBOL/pancake-numbers.cobol delete mode 100644 Task/Pangram-checker/Ada/pangram-checker-1.ada delete mode 100644 Task/Pangram-checker/Ada/pangram-checker-2.ada delete mode 100644 Task/Pangram-checker/AutoIt/pangram-checker.autoit delete mode 100644 Task/Pangram-checker/COBOL/pangram-checker.cobol delete mode 100644 Task/Pangram-checker/PowerShell/pangram-checker-1.psh delete mode 100644 Task/Pangram-checker/PowerShell/pangram-checker-2.psh delete mode 100644 Task/Pangram-checker/VBScript/pangram-checker-1.vb delete mode 100644 Task/Pangram-checker/VBScript/pangram-checker-2.vb delete mode 100644 Task/Parallel-brute-force/Ada/parallel-brute-force.ada delete mode 100644 Task/Parallel-calculations/Ada/parallel-calculations-1.ada delete mode 100644 Task/Parallel-calculations/Ada/parallel-calculations-2.ada delete mode 100644 Task/Parallel-calculations/Ada/parallel-calculations-3.ada delete mode 100644 Task/Parameterized-SQL-statement/Ada/parameterized-sql-statement.ada delete mode 100644 Task/Parametric-polymorphism/Ada/parametric-polymorphism-1.ada delete mode 100644 Task/Parametric-polymorphism/Ada/parametric-polymorphism-2.ada delete mode 100644 Task/Parametric-polymorphism/COBOL/parametric-polymorphism.cobol delete mode 100644 Task/Parse-an-IP-Address/PowerShell/parse-an-ip-address-1.psh delete mode 100644 Task/Parse-an-IP-Address/PowerShell/parse-an-ip-address-2.psh delete mode 100644 Task/Parse-an-IP-Address/PowerShell/parse-an-ip-address-3.psh delete mode 100644 Task/Parse-an-IP-Address/PowerShell/parse-an-ip-address-4.psh delete mode 100644 Task/Parse-an-IP-Address/VBScript/parse-an-ip-address.vb delete mode 100644 Task/Parsing-RPN-calculator-algorithm/Ada/parsing-rpn-calculator-algorithm.ada delete mode 100644 Task/Parsing-RPN-calculator-algorithm/COBOL/parsing-rpn-calculator-algorithm.cobol delete mode 100644 Task/Parsing-RPN-calculator-algorithm/Perl/parsing-rpn-calculator-algorithm.pl delete mode 100644 Task/Parsing-RPN-calculator-algorithm/PowerShell/parsing-rpn-calculator-algorithm.psh delete mode 100644 Task/Parsing-RPN-to-infix-conversion/Ada/parsing-rpn-to-infix-conversion-1.ada delete mode 100644 Task/Parsing-RPN-to-infix-conversion/Ada/parsing-rpn-to-infix-conversion-2.ada delete mode 100644 Task/Partial-function-application/Ada/partial-function-application.ada delete mode 100644 Task/Partial-function-application/JavaScript/partial-function-application-1.js delete mode 100644 Task/Partial-function-application/JavaScript/partial-function-application-2.js delete mode 100644 Task/Partial-function-application/JavaScript/partial-function-application-3.js delete mode 100644 Task/Partial-function-application/JavaScript/partial-function-application-4.js delete mode 100644 Task/Partition-an-integer-x-into-n-primes/VBScript/partition-an-integer-x-into-n-primes.vb delete mode 100644 Task/Pascal-matrix-generation/Ada/pascal-matrix-generation.ada delete mode 100644 Task/Pascal-matrix-generation/VBScript/pascal-matrix-generation.vb delete mode 100644 Task/Pascals-triangle-Puzzle/Ada/pascals-triangle-puzzle.ada delete mode 100644 Task/Pascals-triangle/Ada/pascals-triangle-1.ada delete mode 100644 Task/Pascals-triangle/Ada/pascals-triangle-2.ada delete mode 100644 Task/Pascals-triangle/Ada/pascals-triangle-3.ada delete mode 100644 Task/Pascals-triangle/Emacs-Lisp/pascals-triangle-1.l delete mode 100644 Task/Pascals-triangle/Emacs-Lisp/pascals-triangle-2.l delete mode 100644 Task/Pascals-triangle/Emacs-Lisp/pascals-triangle-3.l delete mode 100644 Task/Pascals-triangle/Euphoria/pascals-triangle.ex delete mode 100644 Task/Pascals-triangle/PowerShell/pascals-triangle.psh delete mode 100644 Task/Pascals-triangle/VBScript/pascals-triangle.vb delete mode 100644 Task/Password-generator/Ada/password-generator.ada delete mode 100644 Task/Password-generator/PowerShell/password-generator-1.psh delete mode 100644 Task/Password-generator/PowerShell/password-generator-2.psh delete mode 100644 Task/Password-generator/PowerShell/password-generator-3.psh delete mode 100644 Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-1.ada delete mode 100644 Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-2.ada delete mode 100644 Task/Pathological-floating-point-problems/Ada/pathological-floating-point-problems-3.ada delete mode 100644 Task/Peano-curve/Ada/peano-curve.ada delete mode 100644 Task/Peano-curve/VBScript/peano-curve.vb delete mode 100644 Task/Pells-equation/Ada/pells-equation.ada delete mode 100644 Task/Penneys-game/Ada/penneys-game.ada delete mode 100644 Task/Pentagram/Ada/pentagram.ada delete mode 100644 Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-1.ada delete mode 100644 Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-2.ada delete mode 100644 Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-3.ada delete mode 100644 Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-4.ada delete mode 100644 Task/Percentage-difference-between-images/Ada/percentage-difference-between-images-5.ada delete mode 100644 Task/Percentage-difference-between-images/REBOL/percentage-difference-between-images.rebol delete mode 100644 Task/Perfect-numbers/Ada/perfect-numbers.ada delete mode 100644 Task/Perfect-numbers/COBOL/perfect-numbers-1.cobol delete mode 100644 Task/Perfect-numbers/COBOL/perfect-numbers-2.cobol delete mode 100644 Task/Perfect-numbers/PowerShell/perfect-numbers.psh delete mode 100644 Task/Perfect-numbers/REBOL/perfect-numbers.rebol delete mode 100644 Task/Perfect-numbers/VBScript/perfect-numbers.vb delete mode 100644 Task/Perfect-shuffle/Ada/perfect-shuffle.ada delete mode 100644 Task/Peripheral-drift-illusion/Ada/peripheral-drift-illusion.ada delete mode 100644 Task/Permutation-test/Ada/permutation-test-1.ada delete mode 100644 Task/Permutation-test/Ada/permutation-test-2.ada delete mode 100644 Task/Permutation-test/Ada/permutation-test-3.ada delete mode 100644 Task/Permutations-Derangements/Ada/permutations-derangements.ada delete mode 100644 Task/Permutations-by-swapping/Ada/permutations-by-swapping.ada delete mode 100644 Task/Permutations-by-swapping/PowerShell/permutations-by-swapping.psh delete mode 100644 Task/Permutations/Ada/permutations-1.ada delete mode 100644 Task/Permutations/Ada/permutations-2.ada delete mode 100644 Task/Permutations/Ada/permutations-3.ada delete mode 100644 Task/Permutations/Euphoria/permutations.ex delete mode 100644 Task/Permutations/PowerShell/permutations.psh delete mode 100644 Task/Permutations/Uiua/permutations.uiua delete mode 100644 Task/Permutations/VBScript/permutations.vb delete mode 100644 Task/Pernicious-numbers/Ada/pernicious-numbers-1.ada delete mode 100644 Task/Pernicious-numbers/Ada/pernicious-numbers-2.ada delete mode 100644 Task/Pernicious-numbers/COBOL/pernicious-numbers.cobol delete mode 100644 Task/Pernicious-numbers/PowerShell/pernicious-numbers-1.psh delete mode 100644 Task/Pernicious-numbers/PowerShell/pernicious-numbers-2.psh delete mode 100644 Task/Pernicious-numbers/PowerShell/pernicious-numbers-3.psh delete mode 100644 Task/Pernicious-numbers/VBScript/pernicious-numbers.vb delete mode 100644 Task/Phrase-reversals/Ada/phrase-reversals.ada delete mode 100644 Task/Phrase-reversals/COBOL/phrase-reversals.cobol delete mode 100644 Task/Phrase-reversals/Emacs-Lisp/phrase-reversals.l delete mode 100644 Task/Phrase-reversals/Java/phrase-reversals.java delete mode 100644 Task/Phrase-reversals/PowerShell/phrase-reversals.psh delete mode 100644 Task/Phrase-reversals/VBScript/phrase-reversals.vb delete mode 100644 Task/Pi/Ada/pi.ada delete mode 100644 Task/Pi/PowerShell/pi-1.psh delete mode 100644 Task/Pi/PowerShell/pi-2.psh delete mode 100644 Task/Pi/PowerShell/pi-3.psh delete mode 100644 Task/Pick-random-element/Ada/pick-random-element.ada delete mode 100644 Task/Pick-random-element/COBOL/pick-random-element.cobol delete mode 100644 Task/Pick-random-element/Emacs-Lisp/pick-random-element.l delete mode 100644 Task/Pick-random-element/Euphoria/pick-random-element.ex delete mode 100644 Task/Pick-random-element/PowerShell/pick-random-element.psh delete mode 100644 Task/Pick-random-element/ReScript/pick-random-element.re delete mode 100644 Task/Pick-random-element/VBScript/pick-random-element.vb delete mode 100644 Task/Pig-the-dice-game-Player/Ada/pig-the-dice-game-player.ada delete mode 100644 Task/Pig-the-dice-game/Ada/pig-the-dice-game-1.ada delete mode 100644 Task/Pig-the-dice-game/Ada/pig-the-dice-game-2.ada delete mode 100644 Task/Pig-the-dice-game/Ada/pig-the-dice-game-3.ada delete mode 100644 Task/Pinstripe-Display/Ada/pinstripe-display.ada delete mode 100644 Task/Pinstripe-Printer/Ada/pinstripe-printer.ada delete mode 100644 Task/Play-recorded-sounds/Ada/play-recorded-sounds.ada delete mode 100644 Task/Playing-cards/AutoIt/playing-cards.autoit delete mode 100644 Task/Playing-cards/COBOL/playing-cards.cobol delete mode 100644 Task/Playing-cards/PowerShell/playing-cards.psh delete mode 100644 Task/Playing-cards/VBScript/playing-cards-1.vb delete mode 100644 Task/Playing-cards/VBScript/playing-cards-2.vb delete mode 100644 Task/Plot-coordinate-pairs/Ada/plot-coordinate-pairs.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-1.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-2.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-3.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-4.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-5.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-6.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-7.ada delete mode 100644 Task/Pointers-and-references/Ada/pointers-and-references-8.ada delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-1.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-2.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-3.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-4.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-5.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-6.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-7.cobol delete mode 100644 Task/Pointers-and-references/COBOL/pointers-and-references-8.cobol delete mode 100644 Task/Poker-hand-analyser/Ada/poker-hand-analyser.ada delete mode 100644 Task/Poker-hand-analyser/VBScript/poker-hand-analyser.vb delete mode 100644 Task/Polymorphic-copy/Ada/polymorphic-copy.ada delete mode 100644 Task/Polymorphism/Ada/polymorphism-1.ada delete mode 100644 Task/Polymorphism/Ada/polymorphism-2.ada delete mode 100644 Task/Polymorphism/Ada/polymorphism-3.ada delete mode 100644 Task/Polymorphism/Ada/polymorphism-4.ada delete mode 100644 Task/Polymorphism/Ada/polymorphism-5.ada delete mode 100644 Task/Polynomial-long-division/Ada/polynomial-long-division.ada delete mode 100644 Task/Polynomial-regression/Ada/polynomial-regression-1.ada delete mode 100644 Task/Polynomial-regression/Ada/polynomial-regression-2.ada delete mode 100644 Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.l delete mode 100644 Task/Polynomial-regression/PowerShell/polynomial-regression.psh delete mode 100644 Task/Polyspiral/REBOL/polyspiral.rebol delete mode 100644 Task/Population-count/Ada/population-count-1.ada delete mode 100644 Task/Population-count/Ada/population-count-2.ada delete mode 100644 Task/Population-count/Ada/population-count-3.ada delete mode 100644 Task/Population-count/COBOL/population-count.cobol delete mode 100644 Task/Population-count/PowerShell/population-count.psh delete mode 100644 Task/Population-count/VBScript/population-count.vb delete mode 100644 Task/Power-set/Ada/power-set.ada delete mode 100644 Task/Power-set/PowerShell/power-set.psh delete mode 100644 Task/Power-set/VBScript/power-set.vb delete mode 100644 Task/Pragmatic-directives/PowerShell/pragmatic-directives-1.psh delete mode 100644 Task/Pragmatic-directives/PowerShell/pragmatic-directives-2.psh delete mode 100644 Task/Price-fraction/Ada/price-fraction-1.ada delete mode 100644 Task/Price-fraction/Ada/price-fraction-2.ada delete mode 100644 Task/Price-fraction/Euphoria/price-fraction.ex delete mode 100644 Task/Price-fraction/PowerShell/price-fraction-1.psh delete mode 100644 Task/Price-fraction/PowerShell/price-fraction-2.psh delete mode 100644 Task/Price-fraction/VBScript/price-fraction.vb delete mode 100644 Task/Primality-by-Wilsons-theorem/Ada/primality-by-wilsons-theorem.ada delete mode 100644 Task/Primality-by-trial-division/Ada/primality-by-trial-division-1.ada delete mode 100644 Task/Primality-by-trial-division/Ada/primality-by-trial-division-2.ada delete mode 100644 Task/Primality-by-trial-division/Ada/primality-by-trial-division-3.ada delete mode 100644 Task/Primality-by-trial-division/AutoIt/primality-by-trial-division.autoit delete mode 100644 Task/Primality-by-trial-division/C/primality-by-trial-division.c delete mode 100644 Task/Primality-by-trial-division/COBOL/primality-by-trial-division.cobol delete mode 100644 Task/Primality-by-trial-division/Chapel/primality-by-trial-division.chapel delete mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-1.l delete mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-2.l delete mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-3.l delete mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-4.l delete mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-5.l delete mode 100644 Task/Primality-by-trial-division/Euphoria/primality-by-trial-division.ex delete mode 100644 Task/Primality-by-trial-division/PowerShell/primality-by-trial-division.psh delete mode 100644 Task/Primality-by-trial-division/REBOL/primality-by-trial-division-1.rebol delete mode 100644 Task/Primality-by-trial-division/REBOL/primality-by-trial-division-2.rebol delete mode 100644 Task/Primality-by-trial-division/VBScript/primality-by-trial-division.vb delete mode 100644 Task/Prime-decomposition/Ada/prime-decomposition-1.ada delete mode 100644 Task/Prime-decomposition/Ada/prime-decomposition-2.ada delete mode 100644 Task/Prime-decomposition/Ada/prime-decomposition-3.ada delete mode 100644 Task/Prime-decomposition/Pascal/prime-decomposition-1.pas delete mode 100644 Task/Prime-decomposition/Pascal/prime-decomposition-2.pas delete mode 100644 Task/Prime-decomposition/PowerShell/prime-decomposition-1.psh delete mode 100644 Task/Prime-decomposition/PowerShell/prime-decomposition-2.psh delete mode 100644 Task/Prime-decomposition/REXX/prime-decomposition.rexx delete mode 100644 Task/Prime-decomposition/VBScript/prime-decomposition.vb delete mode 100644 Task/Priority-queue/Ada/priority-queue.ada delete mode 100644 Task/Priority-queue/COBOL/priority-queue.cobol delete mode 100644 Task/Priority-queue/VBScript/priority-queue.vb delete mode 100644 Task/Probabilistic-choice/Ada/probabilistic-choice.ada delete mode 100644 Task/Probabilistic-choice/Euphoria/probabilistic-choice.ex delete mode 100644 Task/Probabilistic-choice/PowerShell/probabilistic-choice.psh delete mode 100644 Task/Probabilistic-choice/ReScript/probabilistic-choice.re delete mode 100644 Task/Probabilistic-choice/VBScript/probabilistic-choice.vb delete mode 100644 Task/Problem-of-Apollonius/Ada/problem-of-apollonius-1.ada delete mode 100644 Task/Problem-of-Apollonius/Ada/problem-of-apollonius-2.ada delete mode 100644 Task/Problem-of-Apollonius/Ada/problem-of-apollonius-3.ada delete mode 100644 Task/Problem-of-Apollonius/PowerShell/problem-of-apollonius-1.psh delete mode 100644 Task/Problem-of-Apollonius/PowerShell/problem-of-apollonius-2.psh delete mode 100644 Task/Program-name/Ada/program-name.ada delete mode 100644 Task/Program-name/COBOL/program-name.cobol delete mode 100644 Task/Program-name/Emacs-Lisp/program-name.l delete mode 100644 Task/Program-name/Euphoria/program-name.ex delete mode 100644 Task/Program-name/PowerShell/program-name.psh delete mode 100644 Task/Program-name/REXX/program-name-3.rexx delete mode 100644 Task/Program-name/REXX/program-name-4.rexx delete mode 100644 Task/Program-name/REXX/program-name-5.rexx delete mode 100644 Task/Program-name/VBScript/program-name.vb delete mode 100644 Task/Program-termination/Ada/program-termination-1.ada delete mode 100644 Task/Program-termination/Ada/program-termination-2.ada delete mode 100644 Task/Program-termination/Ada/program-termination-3.ada delete mode 100644 Task/Program-termination/Ada/program-termination-4.ada delete mode 100644 Task/Program-termination/AutoIt/program-termination.autoit delete mode 100644 Task/Program-termination/COBOL/program-termination-1.cobol delete mode 100644 Task/Program-termination/COBOL/program-termination-2.cobol delete mode 100644 Task/Program-termination/Emacs-Lisp/program-termination.l delete mode 100644 Task/Program-termination/PowerShell/program-termination.psh delete mode 100644 Task/Program-termination/REBOL/program-termination-1.rebol delete mode 100644 Task/Program-termination/REBOL/program-termination-2.rebol delete mode 100644 Task/Program-termination/REBOL/program-termination-3.rebol delete mode 100644 Task/Program-termination/REBOL/program-termination-4.rebol delete mode 100644 Task/Program-termination/VBScript/program-termination.vb delete mode 100644 Task/Proper-divisors/Ada/proper-divisors-1.ada delete mode 100644 Task/Proper-divisors/Ada/proper-divisors-2.ada delete mode 100644 Task/Proper-divisors/PowerShell/proper-divisors-1.psh delete mode 100644 Task/Proper-divisors/PowerShell/proper-divisors-2.psh delete mode 100644 Task/Proper-divisors/PowerShell/proper-divisors-3.psh delete mode 100644 Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Ada/pseudo-random-numbers-combined-recursive-generator-mrg32k3a-1.ada delete mode 100644 Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Ada/pseudo-random-numbers-combined-recursive-generator-mrg32k3a-2.ada delete mode 100644 Task/Pseudo-random-numbers-Combined-recursive-generator-MRG32k3a/Ada/pseudo-random-numbers-combined-recursive-generator-mrg32k3a-3.ada delete mode 100644 Task/Pseudo-random-numbers-Middle-square-method/Ada/pseudo-random-numbers-middle-square-method.ada delete mode 100644 Task/Pseudo-random-numbers-Middle-square-method/COBOL/pseudo-random-numbers-middle-square-method.cobol delete mode 100644 Task/Pseudo-random-numbers-PCG32/Ada/pseudo-random-numbers-pcg32-1.ada delete mode 100644 Task/Pseudo-random-numbers-PCG32/Ada/pseudo-random-numbers-pcg32-2.ada delete mode 100644 Task/Pseudo-random-numbers-PCG32/Ada/pseudo-random-numbers-pcg32-3.ada delete mode 100644 Task/Pseudo-random-numbers-Splitmix64/Ada/pseudo-random-numbers-splitmix64-1.ada delete mode 100644 Task/Pseudo-random-numbers-Splitmix64/Ada/pseudo-random-numbers-splitmix64-2.ada delete mode 100644 Task/Pseudo-random-numbers-Splitmix64/Ada/pseudo-random-numbers-splitmix64-3.ada delete mode 100644 Task/Pseudo-random-numbers-Xorshift-star/Ada/pseudo-random-numbers-xorshift-star.ada delete mode 100644 Task/Pythagoras-tree/Ada/pythagoras-tree.ada delete mode 100644 Task/Pythagorean-triples/Ada/pythagorean-triples.ada delete mode 100644 Task/Pythagorean-triples/Euphoria/pythagorean-triples.ex delete mode 100644 Task/Pythagorean-triples/PowerShell/pythagorean-triples.psh delete mode 100644 Task/Pythagorean-triples/Python/pythagorean-triples-3.py delete mode 100644 Task/Pythagorean-triples/VBScript/pythagorean-triples.vb delete mode 100644 Task/QR-decomposition/Ada/qr-decomposition.ada delete mode 100644 Task/QR-decomposition/PowerShell/qr-decomposition.psh delete mode 100644 Task/Quaternion-type/ALGOL-68/quaternion-type-1.alg delete mode 100644 Task/Quaternion-type/ALGOL-68/quaternion-type-2.alg delete mode 100644 Task/Quaternion-type/ALGOL-W/quaternion-type.alg delete mode 100644 Task/Quaternion-type/ATS/quaternion-type.ats delete mode 100644 Task/Quaternion-type/Action-/quaternion-type.action delete mode 100644 Task/Quaternion-type/Ada/quaternion-type-1.ada delete mode 100644 Task/Quaternion-type/Ada/quaternion-type-2.ada delete mode 100644 Task/Quaternion-type/Ada/quaternion-type-3.ada delete mode 100644 Task/Quaternion-type/Arturo/quaternion-type.arturo delete mode 100644 Task/Quaternion-type/AutoHotkey/quaternion-type.ahk delete mode 100644 Task/Quaternion-type/Axiom/quaternion-type.axiom delete mode 100644 Task/Quaternion-type/BASIC256/quaternion-type.basic delete mode 100644 Task/Quaternion-type/BBC-BASIC/quaternion-type.basic delete mode 100644 Task/Quaternion-type/C++/quaternion-type-1.cpp delete mode 100644 Task/Quaternion-type/C++/quaternion-type-2.cpp delete mode 100644 Task/Quaternion-type/C-sharp/quaternion-type-1.cs delete mode 100644 Task/Quaternion-type/C-sharp/quaternion-type-2.cs delete mode 100644 Task/Quaternion-type/C/quaternion-type-1.c delete mode 100644 Task/Quaternion-type/C/quaternion-type-2.c delete mode 100644 Task/Quaternion-type/CLU/quaternion-type.clu delete mode 100644 Task/Quaternion-type/Common-Lisp/quaternion-type.lisp delete mode 100644 Task/Quaternion-type/Crystal/quaternion-type.cr delete mode 100644 Task/Quaternion-type/D/quaternion-type.d delete mode 100644 Task/Quaternion-type/Dart/quaternion-type.dart delete mode 100644 Task/Quaternion-type/Delphi/quaternion-type-1.pas delete mode 100644 Task/Quaternion-type/Delphi/quaternion-type-2.pas delete mode 100644 Task/Quaternion-type/E/quaternion-type-1.e delete mode 100644 Task/Quaternion-type/E/quaternion-type-2.e delete mode 100644 Task/Quaternion-type/ERRE/quaternion-type.erre delete mode 100644 Task/Quaternion-type/EasyLang/quaternion-type.easy delete mode 100644 Task/Quaternion-type/Eero/quaternion-type.eero delete mode 100644 Task/Quaternion-type/Elena/quaternion-type.elena delete mode 100644 Task/Quaternion-type/Euphoria/quaternion-type.ex delete mode 100644 Task/Quaternion-type/F-Sharp/quaternion-type.fs delete mode 100644 Task/Quaternion-type/Factor/quaternion-type.factor delete mode 100644 Task/Quaternion-type/Forth/quaternion-type.fth delete mode 100644 Task/Quaternion-type/Fortran/quaternion-type.f delete mode 100644 Task/Quaternion-type/FreeBASIC/quaternion-type.basic delete mode 100644 Task/Quaternion-type/GAP/quaternion-type.gap delete mode 100644 Task/Quaternion-type/Go/quaternion-type.go delete mode 100644 Task/Quaternion-type/Haskell/quaternion-type-1.hs delete mode 100644 Task/Quaternion-type/Haskell/quaternion-type-2.hs delete mode 100644 Task/Quaternion-type/Haskell/quaternion-type-3.hs delete mode 100644 Task/Quaternion-type/Idris/quaternion-type-1.idris delete mode 100644 Task/Quaternion-type/Idris/quaternion-type-2.idris delete mode 100644 Task/Quaternion-type/J/quaternion-type-1.j delete mode 100644 Task/Quaternion-type/J/quaternion-type-2.j delete mode 100644 Task/Quaternion-type/J/quaternion-type-3.j delete mode 100644 Task/Quaternion-type/Java/quaternion-type.java delete mode 100644 Task/Quaternion-type/JavaScript/quaternion-type-1.js delete mode 100644 Task/Quaternion-type/JavaScript/quaternion-type-2.js delete mode 100644 Task/Quaternion-type/Jq/quaternion-type-1.jq delete mode 100644 Task/Quaternion-type/Jq/quaternion-type-2.jq delete mode 100644 Task/Quaternion-type/Julia/quaternion-type-1.jl delete mode 100644 Task/Quaternion-type/Julia/quaternion-type-2.jl delete mode 100644 Task/Quaternion-type/Kotlin/quaternion-type.kts delete mode 100644 Task/Quaternion-type/Liberty-BASIC/quaternion-type.basic delete mode 100644 Task/Quaternion-type/Lua/quaternion-type-1.lua delete mode 100644 Task/Quaternion-type/Lua/quaternion-type-2.lua delete mode 100644 Task/Quaternion-type/M2000-Interpreter/quaternion-type.m2000 delete mode 100644 Task/Quaternion-type/Maple/quaternion-type.maple delete mode 100644 Task/Quaternion-type/Mathematica/quaternion-type.math delete mode 100644 Task/Quaternion-type/Mercury/quaternion-type-1.mercury delete mode 100644 Task/Quaternion-type/Mercury/quaternion-type-2.mercury delete mode 100644 Task/Quaternion-type/Nim/quaternion-type.nim delete mode 100644 Task/Quaternion-type/OCaml/quaternion-type-1.ml delete mode 100644 Task/Quaternion-type/OCaml/quaternion-type-2.ml delete mode 100644 Task/Quaternion-type/Octave/quaternion-type-1.octave delete mode 100644 Task/Quaternion-type/Octave/quaternion-type-2.octave delete mode 100644 Task/Quaternion-type/Oforth/quaternion-type-1.fth delete mode 100644 Task/Quaternion-type/Oforth/quaternion-type-2.fth delete mode 100644 Task/Quaternion-type/Ol/quaternion-type.ol delete mode 100644 Task/Quaternion-type/OoRexx/quaternion-type.rexx delete mode 100644 Task/Quaternion-type/PARI-GP/quaternion-type-1.parigp delete mode 100644 Task/Quaternion-type/PARI-GP/quaternion-type-2.parigp delete mode 100644 Task/Quaternion-type/PL-I/quaternion-type.pli delete mode 100644 Task/Quaternion-type/Perl/quaternion-type.pl delete mode 100644 Task/Quaternion-type/Phix/quaternion-type.phix delete mode 100644 Task/Quaternion-type/Picat/quaternion-type.picat delete mode 100644 Task/Quaternion-type/PicoLisp/quaternion-type-1.l delete mode 100644 Task/Quaternion-type/PicoLisp/quaternion-type-2.l delete mode 100644 Task/Quaternion-type/PowerShell/quaternion-type-1.psh delete mode 100644 Task/Quaternion-type/PowerShell/quaternion-type-2.psh delete mode 100644 Task/Quaternion-type/Prolog/quaternion-type-1.pro delete mode 100644 Task/Quaternion-type/Prolog/quaternion-type-2.pro delete mode 100644 Task/Quaternion-type/PureBasic/quaternion-type-1.basic delete mode 100644 Task/Quaternion-type/PureBasic/quaternion-type-2.basic delete mode 100644 Task/Quaternion-type/Python/quaternion-type-1.py delete mode 100644 Task/Quaternion-type/Python/quaternion-type-2.py delete mode 100644 Task/Quaternion-type/R/quaternion-type.r delete mode 100644 Task/Quaternion-type/REXX/quaternion-type.rexx delete mode 100644 Task/Quaternion-type/Racket/quaternion-type.rkt delete mode 100644 Task/Quaternion-type/Raku/quaternion-type.raku delete mode 100644 Task/Quaternion-type/Red/quaternion-type.red delete mode 100644 Task/Quaternion-type/Ruby/quaternion-type.rb delete mode 100644 Task/Quaternion-type/Rust/quaternion-type.rs delete mode 100644 Task/Quaternion-type/Scala/quaternion-type-1.scala delete mode 100644 Task/Quaternion-type/Scala/quaternion-type-2.scala delete mode 100644 Task/Quaternion-type/Seed7/quaternion-type.seed7 delete mode 100644 Task/Quaternion-type/Sidef/quaternion-type.sidef delete mode 100644 Task/Quaternion-type/Swift/quaternion-type.swift delete mode 100644 Task/Quaternion-type/Tcl/quaternion-type-1.tcl delete mode 100644 Task/Quaternion-type/Tcl/quaternion-type-2.tcl delete mode 100644 Task/Quaternion-type/VBA/quaternion-type.vba delete mode 100644 Task/Quaternion-type/Visual-Basic-.NET/quaternion-type-1.vb delete mode 100644 Task/Quaternion-type/Visual-Basic-.NET/quaternion-type-2.vb delete mode 100644 Task/Quaternion-type/Wren/quaternion-type.wren delete mode 100644 Task/Quaternion-type/XPL0/quaternion-type.xpl0 delete mode 100644 Task/Quaternion-type/Zkl/quaternion-type-1.zkl delete mode 100644 Task/Quaternion-type/Zkl/quaternion-type-2.zkl delete mode 100644 Task/Queue-Definition/Ada/queue-definition-1.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-10.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-11.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-12.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-2.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-3.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-4.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-5.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-6.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-7.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-8.ada delete mode 100644 Task/Queue-Definition/Ada/queue-definition-9.ada delete mode 100644 Task/Queue-Definition/PowerShell/queue-definition.psh delete mode 100644 Task/Queue-Definition/REBOL/queue-definition.rebol delete mode 100644 Task/Queue-Definition/VBScript/queue-definition.vb delete mode 100644 Task/Queue-Usage/Ada/queue-usage.ada delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-1.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-2.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-3.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-4.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-5.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-6.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-7.psh delete mode 100644 Task/Queue-Usage/PowerShell/queue-usage-8.psh delete mode 100644 Task/Queue-Usage/REBOL/queue-usage.rebol delete mode 100644 Task/Quickselect-algorithm/Ada/quickselect-algorithm.ada delete mode 100644 Task/Quickselect-algorithm/COBOL/quickselect-algorithm.cobol delete mode 100644 Task/Quickselect-algorithm/PowerShell/quickselect-algorithm.psh delete mode 100644 Task/Quine/Ada/quine.ada delete mode 100644 Task/Quine/COBOL/quine-1.cobol delete mode 100644 Task/Quine/COBOL/quine-2.cobol delete mode 100644 Task/Quine/COBOL/quine-3.cobol delete mode 100644 Task/Quine/COBOL/quine-4.cobol delete mode 100644 Task/Quine/Euphoria/quine.ex delete mode 100644 Task/Quine/PowerShell/quine-1.psh delete mode 100644 Task/Quine/PowerShell/quine-2.psh delete mode 100644 Task/Quine/PowerShell/quine-3.psh delete mode 100644 Task/Quine/PowerShell/quine-4.psh delete mode 100644 Task/Quine/REBOL/quine-1.rebol delete mode 100644 Task/Quine/REBOL/quine-2.rebol delete mode 100644 Task/Quine/VHDL/quine.vhdl delete mode 100644 Task/Quine/Zig/quine.zig delete mode 100644 Task/RIPEMD-160/Ada/ripemd-160.ada delete mode 100644 Task/RIPEMD-160/PowerShell/ripemd-160-1.psh delete mode 100644 Task/RIPEMD-160/PowerShell/ripemd-160-2.psh delete mode 100644 Task/RSA-code/Ada/rsa-code.ada delete mode 100644 Task/RSA-code/PowerShell/rsa-code.psh delete mode 100644 Task/Random-number-generator-device-/Ada/random-number-generator-device-.ada delete mode 100644 Task/Random-number-generator-device-/PowerShell/random-number-generator-device--1.psh delete mode 100644 Task/Random-number-generator-device-/PowerShell/random-number-generator-device--2.psh delete mode 100644 Task/Random-number-generator-device-/PowerShell/random-number-generator-device--3.psh delete mode 100644 Task/Random-numbers/Ada/random-numbers.ada delete mode 100644 Task/Random-numbers/COBOL/random-numbers.cobol delete mode 100644 Task/Random-numbers/Euphoria/random-numbers.ex delete mode 100644 Task/Random-numbers/PowerShell/random-numbers.psh delete mode 100644 Task/Random-numbers/ReScript/random-numbers.re delete mode 100644 Task/Range-consolidation/Ada/range-consolidation.ada delete mode 100644 Task/Range-expansion/Ada/range-expansion.ada delete mode 100644 Task/Range-expansion/COBOL/range-expansion.cobol delete mode 100644 Task/Range-expansion/PowerShell/range-expansion-1.psh delete mode 100644 Task/Range-expansion/PowerShell/range-expansion-2.psh delete mode 100644 Task/Range-expansion/PowerShell/range-expansion-3.psh delete mode 100644 Task/Range-extraction/Ada/range-extraction-1.ada delete mode 100644 Task/Range-extraction/Ada/range-extraction-2.ada delete mode 100644 Task/Range-extraction/COBOL/range-extraction-1.cobol delete mode 100644 Task/Range-extraction/COBOL/range-extraction-2.cobol delete mode 100644 Task/Range-extraction/Emacs-Lisp/range-extraction-1.l delete mode 100644 Task/Range-extraction/Emacs-Lisp/range-extraction-2.l delete mode 100644 Task/Range-extraction/Euphoria/range-extraction.ex delete mode 100644 Task/Range-extraction/PowerShell/range-extraction.psh delete mode 100644 Task/Range-extraction/VBScript/range-extraction.vb delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-1.psh delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-2.psh delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-3.psh delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-4.psh delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-5.psh delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-6.psh delete mode 100644 Task/Ranking-methods/PowerShell/ranking-methods-7.psh delete mode 100644 Task/Rate-counter/Ada/rate-counter.ada delete mode 100644 Task/Rate-counter/PowerShell/rate-counter.psh delete mode 100644 Task/Ray-casting-algorithm/Ada/ray-casting-algorithm-1.ada delete mode 100644 Task/Ray-casting-algorithm/Ada/ray-casting-algorithm-2.ada delete mode 100644 Task/Ray-casting-algorithm/Ada/ray-casting-algorithm-3.ada delete mode 100644 Task/Read-a-configuration-file/Ada/read-a-configuration-file.ada delete mode 100644 Task/Read-a-configuration-file/COBOL/read-a-configuration-file.cobol delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-1.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-2.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-3.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-4.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-5.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-6.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-7.psh delete mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-8.psh delete mode 100644 Task/Read-a-configuration-file/VBScript/read-a-configuration-file.vb delete mode 100644 Task/Read-a-file-character-by-character-UTF8/Ada/read-a-file-character-by-character-utf8.ada delete mode 100644 Task/Read-a-file-line-by-line/Ada/read-a-file-line-by-line.ada delete mode 100644 Task/Read-a-file-line-by-line/COBOL/read-a-file-line-by-line.cobol delete mode 100644 Task/Read-a-file-line-by-line/Euphoria/read-a-file-line-by-line.ex delete mode 100644 Task/Read-a-file-line-by-line/PowerShell/read-a-file-line-by-line.psh delete mode 100644 Task/Read-a-file-line-by-line/VBScript/read-a-file-line-by-line.vb delete mode 100644 Task/Read-a-specific-line-from-a-file/Ada/read-a-specific-line-from-a-file.ada delete mode 100644 Task/Read-a-specific-line-from-a-file/PowerShell/read-a-specific-line-from-a-file.psh delete mode 100644 Task/Read-a-specific-line-from-a-file/REBOL/read-a-specific-line-from-a-file.rebol delete mode 100644 Task/Read-a-specific-line-from-a-file/VBScript/read-a-specific-line-from-a-file.vb delete mode 100644 Task/Read-entire-file/Ada/read-entire-file-1.ada delete mode 100644 Task/Read-entire-file/Ada/read-entire-file-2.ada delete mode 100644 Task/Read-entire-file/AutoIt/read-entire-file.autoit delete mode 100644 Task/Read-entire-file/Emacs-Lisp/read-entire-file.l delete mode 100644 Task/Read-entire-file/Euphoria/read-entire-file.ex delete mode 100644 Task/Read-entire-file/PowerShell/read-entire-file-1.psh delete mode 100644 Task/Read-entire-file/PowerShell/read-entire-file-2.psh delete mode 100644 Task/Read-entire-file/PowerShell/read-entire-file-3.psh delete mode 100644 Task/Read-entire-file/REBOL/read-entire-file.rebol delete mode 100644 Task/Read-entire-file/VBScript/read-entire-file-1.vb delete mode 100644 Task/Read-entire-file/VBScript/read-entire-file-2.vb delete mode 100644 Task/Real-constants-and-functions/Ada/real-constants-and-functions.ada delete mode 100644 Task/Real-constants-and-functions/COBOL/real-constants-and-functions-1.cobol delete mode 100644 Task/Real-constants-and-functions/COBOL/real-constants-and-functions-2.cobol delete mode 100644 Task/Real-constants-and-functions/PowerShell/real-constants-and-functions.psh delete mode 100644 Task/Recamans-sequence/COBOL/recamans-sequence.cobol delete mode 100644 Task/Recamans-sequence/VBScript/recamans-sequence.vb delete mode 100644 Task/Record-sound/Ada/record-sound.ada delete mode 100644 Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-1.ada delete mode 100644 Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-2.ada delete mode 100644 Task/Reduced-row-echelon-form/Ada/reduced-row-echelon-form-3.ada delete mode 100644 Task/Reduced-row-echelon-form/AutoIt/reduced-row-echelon-form.autoit delete mode 100644 Task/Reduced-row-echelon-form/Euphoria/reduced-row-echelon-form.ex delete mode 100644 Task/Reflection-List-properties/PowerShell/reflection-list-properties-1.psh delete mode 100644 Task/Reflection-List-properties/PowerShell/reflection-list-properties-2.psh delete mode 100644 Task/Regular-expressions/Ada/regular-expressions.ada delete mode 100644 Task/Regular-expressions/Emacs-Lisp/regular-expressions.l delete mode 100644 Task/Regular-expressions/PowerShell/regular-expressions.psh delete mode 100644 Task/Regular-expressions/REBOL/regular-expressions.rebol delete mode 100644 Task/Regular-expressions/VBScript/regular-expressions.vb delete mode 100644 Task/Remove-duplicate-elements/Ada/remove-duplicate-elements.ada delete mode 100644 Task/Remove-duplicate-elements/Euphoria/remove-duplicate-elements.ex delete mode 100644 Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-1.psh delete mode 100644 Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-2.psh delete mode 100644 Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-3.psh delete mode 100644 Task/Remove-duplicate-elements/PowerShell/remove-duplicate-elements-4.psh delete mode 100644 Task/Remove-duplicate-elements/REBOL/remove-duplicate-elements.rebol delete mode 100644 Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vb delete mode 100644 Task/Remove-lines-from-a-file/Ada/remove-lines-from-a-file.ada delete mode 100644 Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.psh delete mode 100644 Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb delete mode 100644 Task/Rename-a-file/Ada/rename-a-file.ada delete mode 100644 Task/Rename-a-file/Emacs-Lisp/rename-a-file.l delete mode 100644 Task/Rename-a-file/PowerShell/rename-a-file.psh delete mode 100644 Task/Rename-a-file/REBOL/rename-a-file.rebol delete mode 100644 Task/Rendezvous/Ada/rendezvous-1.ada delete mode 100644 Task/Rendezvous/Ada/rendezvous-2.ada delete mode 100644 Task/Rendezvous/Ada/rendezvous-3.ada delete mode 100644 Task/Rep-string/Ada/rep-string.ada delete mode 100644 Task/Rep-string/VBScript/rep-string.vb delete mode 100644 Task/Repeat-a-string/Ada/repeat-a-string.ada delete mode 100644 Task/Repeat-a-string/AutoIt/repeat-a-string.autoit delete mode 100644 Task/Repeat-a-string/COBOL/repeat-a-string.cobol delete mode 100644 Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-1.l delete mode 100644 Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-2.l delete mode 100644 Task/Repeat-a-string/Emacs-Lisp/repeat-a-string-3.l delete mode 100644 Task/Repeat-a-string/Euphoria/repeat-a-string-1.ex delete mode 100644 Task/Repeat-a-string/Euphoria/repeat-a-string-2.ex delete mode 100644 Task/Repeat-a-string/Euphoria/repeat-a-string-3.ex delete mode 100644 Task/Repeat-a-string/Euphoria/repeat-a-string-4.ex delete mode 100644 Task/Repeat-a-string/Euphoria/repeat-a-string-5.ex delete mode 100644 Task/Repeat-a-string/PowerShell/repeat-a-string.psh delete mode 100644 Task/Repeat-a-string/QBasic/repeat-a-string.basic delete mode 100644 Task/Repeat-a-string/REBOL/repeat-a-string.rebol delete mode 100644 Task/Repeat-a-string/ReScript/repeat-a-string.re delete mode 100644 Task/Repeat-a-string/VBScript/repeat-a-string.vb delete mode 100644 Task/Repeat/Ada/repeat.ada delete mode 100644 Task/Repeat/Chapel/repeat-1.chapel delete mode 100644 Task/Repeat/Chapel/repeat-2.chapel delete mode 100644 Task/Repeat/Chapel/repeat-3.chapel delete mode 100644 Task/Repeat/PowerShell/repeat.psh delete mode 100644 Task/Resistor-mesh/Ada/resistor-mesh.ada delete mode 100644 Task/Return-multiple-values/Ada/return-multiple-values.ada delete mode 100644 Task/Return-multiple-values/AutoIt/return-multiple-values.autoit delete mode 100644 Task/Return-multiple-values/COBOL/return-multiple-values.cobol delete mode 100644 Task/Return-multiple-values/Euphoria/return-multiple-values.ex delete mode 100644 Task/Return-multiple-values/PowerShell/return-multiple-values.psh delete mode 100644 Task/Return-multiple-values/ReScript/return-multiple-values.re delete mode 100644 Task/Reverse-a-string/Ada/reverse-a-string.ada delete mode 100644 Task/Reverse-a-string/AutoIt/reverse-a-string.autoit delete mode 100644 Task/Reverse-a-string/Batch-File/reverse-a-string.bat delete mode 100644 Task/Reverse-a-string/COBOL/reverse-a-string.cobol delete mode 100644 Task/Reverse-a-string/Emacs-Lisp/reverse-a-string.l delete mode 100644 Task/Reverse-a-string/Euphoria/reverse-a-string.ex delete mode 100644 Task/Reverse-a-string/Pluto/reverse-a-string.pluto delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-1.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-2.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-3.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-4.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-5.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-6.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-7.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-8.psh delete mode 100644 Task/Reverse-a-string/PowerShell/reverse-a-string-9.psh delete mode 100644 Task/Reverse-a-string/REBOL/reverse-a-string-1.rebol delete mode 100644 Task/Reverse-a-string/REBOL/reverse-a-string-2.rebol delete mode 100644 Task/Reverse-a-string/ReScript/reverse-a-string.re delete mode 100644 Task/Reverse-a-string/Tcl/reverse-a-string.tcl delete mode 100644 Task/Reverse-a-string/VBScript/reverse-a-string.vb delete mode 100644 Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-1.ada delete mode 100644 Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-2.ada delete mode 100644 Task/Reverse-words-in-a-string/Ada/reverse-words-in-a-string-3.ada delete mode 100644 Task/Reverse-words-in-a-string/COBOL/reverse-words-in-a-string.cobol delete mode 100644 Task/Reverse-words-in-a-string/Emacs-Lisp/reverse-words-in-a-string.l delete mode 100644 Task/Reverse-words-in-a-string/PowerShell/reverse-words-in-a-string.psh delete mode 100644 Task/Reverse-words-in-a-string/VBScript/reverse-words-in-a-string.vb delete mode 100644 Task/Rock-paper-scissors/Ada/rock-paper-scissors.ada delete mode 100644 Task/Rock-paper-scissors/AutoIt/rock-paper-scissors.autoit delete mode 100644 Task/Rock-paper-scissors/Euphoria/rock-paper-scissors.ex delete mode 100644 Task/Roman-numerals-Decode/Ada/roman-numerals-decode.ada delete mode 100644 Task/Roman-numerals-Decode/COBOL/roman-numerals-decode.cobol delete mode 100644 Task/Roman-numerals-Decode/Emacs-Lisp/roman-numerals-decode.l delete mode 100644 Task/Roman-numerals-Decode/Euphoria/roman-numerals-decode.ex delete mode 100644 Task/Roman-numerals-Decode/PowerShell/roman-numerals-decode-1.psh delete mode 100644 Task/Roman-numerals-Decode/PowerShell/roman-numerals-decode-2.psh delete mode 100644 Task/Roman-numerals-Decode/VBScript/roman-numerals-decode.vb delete mode 100644 Task/Roman-numerals-Encode/Ada/roman-numerals-encode.ada delete mode 100644 Task/Roman-numerals-Encode/AutoLISP/roman-numerals-encode.l delete mode 100644 Task/Roman-numerals-Encode/COBOL/roman-numerals-encode.cobol delete mode 100644 Task/Roman-numerals-Encode/Emacs-Lisp/roman-numerals-encode.l delete mode 100644 Task/Roman-numerals-Encode/Euphoria/roman-numerals-encode.ex delete mode 100644 Task/Roman-numerals-Encode/PowerShell/roman-numerals-encode-1.psh delete mode 100644 Task/Roman-numerals-Encode/PowerShell/roman-numerals-encode-2.psh delete mode 100644 Task/Roots-of-a-function/Ada/roots-of-a-function.ada delete mode 100644 Task/Roots-of-a-quadratic-function/Ada/roots-of-a-quadratic-function.ada delete mode 100644 Task/Roots-of-unity/Ada/roots-of-unity.ada delete mode 100644 Task/Rosetta-Code-Count-examples/Ada/rosetta-code-count-examples.ada delete mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/Ada/rosetta-code-find-unimplemented-tasks.ada delete mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/PowerShell/rosetta-code-find-unimplemented-tasks-1.psh delete mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/PowerShell/rosetta-code-find-unimplemented-tasks-2.psh delete mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/VBScript/rosetta-code-find-unimplemented-tasks.vb delete mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/Ada/rosetta-code-rank-languages-by-popularity.ada delete mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/PowerShell/rosetta-code-rank-languages-by-popularity-1.psh delete mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/PowerShell/rosetta-code-rank-languages-by-popularity-2.psh delete mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/PowerShell/rosetta-code-rank-languages-by-popularity-3.psh delete mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/VBScript/rosetta-code-rank-languages-by-popularity.vb delete mode 100644 Task/Rot-13/Ada/rot-13.ada delete mode 100644 Task/Rot-13/Batch-File/rot-13.bat delete mode 100644 Task/Rot-13/COBOL/rot-13-1.cobol delete mode 100644 Task/Rot-13/COBOL/rot-13-2.cobol delete mode 100644 Task/Rot-13/Emacs-Lisp/rot-13-1.l delete mode 100644 Task/Rot-13/Emacs-Lisp/rot-13-2.l delete mode 100644 Task/Rot-13/Euphoria/rot-13.ex delete mode 100644 Task/Rot-13/Haxe/rot-13.haxe delete mode 100644 Task/Rot-13/PowerShell/rot-13-1.psh delete mode 100644 Task/Rot-13/PowerShell/rot-13-2.psh delete mode 100644 Task/Rot-13/PowerShell/rot-13-3.psh delete mode 100644 Task/Rot-13/REBOL/rot-13.rebol delete mode 100644 Task/Rot-13/VBScript/rot-13.vb delete mode 100644 Task/Run-length-encoding/Ada/run-length-encoding.ada delete mode 100644 Task/Run-length-encoding/COBOL/run-length-encoding.cobol delete mode 100644 Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-1.l delete mode 100644 Task/Run-length-encoding/Emacs-Lisp/run-length-encoding-2.l delete mode 100644 Task/Run-length-encoding/Euphoria/run-length-encoding.ex delete mode 100644 Task/Run-length-encoding/PowerShell/run-length-encoding.psh delete mode 100644 Task/Runge-Kutta-method/Ada/runge-kutta-method.ada delete mode 100644 Task/Runge-Kutta-method/PowerShell/runge-kutta-method.psh delete mode 100644 Task/Runtime-evaluation-In-an-environment/REBOL/runtime-evaluation-in-an-environment.rebol delete mode 100644 Task/Runtime-evaluation/PowerShell/runtime-evaluation-1.psh delete mode 100644 Task/Runtime-evaluation/PowerShell/runtime-evaluation-2.psh delete mode 100644 Task/Runtime-evaluation/PowerShell/runtime-evaluation-3.psh delete mode 100644 Task/Runtime-evaluation/PowerShell/runtime-evaluation-4.psh delete mode 100644 Task/Runtime-evaluation/PowerShell/runtime-evaluation-5.psh delete mode 100644 Task/Runtime-evaluation/PowerShell/runtime-evaluation-6.psh delete mode 100644 Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol delete mode 100644 Task/S-expressions/Ada/s-expressions-1.ada delete mode 100644 Task/S-expressions/Ada/s-expressions-2.ada delete mode 100644 Task/S-expressions/Ada/s-expressions-3.ada delete mode 100644 Task/S-expressions/Ada/s-expressions-4.ada delete mode 100644 Task/S-expressions/Ada/s-expressions-5.ada delete mode 100644 Task/SEDOLs/Ada/sedols.ada delete mode 100644 Task/SEDOLs/COBOL/sedols.cobol delete mode 100644 Task/SEDOLs/PowerShell/sedols.psh delete mode 100644 Task/SEDOLs/VBScript/sedols.vb delete mode 100644 Task/SHA-1/Ada/sha-1.ada delete mode 100644 Task/SHA-1/Emacs-Lisp/sha-1.l delete mode 100644 Task/SHA-1/Haxe/sha-1.haxe delete mode 100644 Task/SHA-1/PowerShell/sha-1.psh delete mode 100644 Task/SHA-1/REBOL/sha-1-1.rebol delete mode 100644 Task/SHA-1/REBOL/sha-1-2.rebol delete mode 100644 Task/SHA-256/Ada/sha-256.ada delete mode 100644 Task/SHA-256/Emacs-Lisp/sha-256.l delete mode 100644 Task/SHA-256/Fortran/sha-256.f delete mode 100644 Task/SHA-256/Haxe/sha-256.haxe delete mode 100644 Task/SHA-256/PowerShell/sha-256.psh delete mode 100644 Task/SHA-256/REBOL/sha-256.rebol delete mode 100644 Task/SOAP/VBScript/soap.vb delete mode 100644 Task/Safe-addition/Ada/safe-addition-1.ada delete mode 100644 Task/Safe-addition/Ada/safe-addition-2.ada delete mode 100644 Task/Safe-addition/Ada/safe-addition-3.ada delete mode 100644 Task/Safe-primes-and-unsafe-primes/Ada/safe-primes-and-unsafe-primes.ada delete mode 100644 Task/Sailors-coconuts-and-a-monkey-problem/Phix/sailors-coconuts-and-a-monkey-problem.phix delete mode 100644 Task/Same-fringe/Ada/same-fringe-1.ada delete mode 100644 Task/Same-fringe/Ada/same-fringe-2.ada delete mode 100644 Task/Same-fringe/Ada/same-fringe-3.ada delete mode 100644 Task/Same-fringe/Ada/same-fringe-4.ada delete mode 100644 Task/Same-fringe/Ada/same-fringe-5.ada delete mode 100644 Task/Scope-Function-names-and-labels/PowerShell/scope-function-names-and-labels-1.psh delete mode 100644 Task/Scope-Function-names-and-labels/PowerShell/scope-function-names-and-labels-2.psh delete mode 100644 Task/Scope-modifiers/Ada/scope-modifiers-1.ada delete mode 100644 Task/Scope-modifiers/Ada/scope-modifiers-2.ada delete mode 100644 Task/Scope-modifiers/Ada/scope-modifiers-3.ada delete mode 100644 Task/Scope-modifiers/Ada/scope-modifiers-4.ada delete mode 100644 Task/Scope-modifiers/PowerShell/scope-modifiers.psh delete mode 100644 Task/Search-a-list-of-records/Ada/search-a-list-of-records.ada delete mode 100644 Task/Search-a-list-of-records/PowerShell/search-a-list-of-records-1.psh delete mode 100644 Task/Search-a-list-of-records/PowerShell/search-a-list-of-records-2.psh delete mode 100644 Task/Search-a-list-of-records/PowerShell/search-a-list-of-records-3.psh delete mode 100644 Task/Search-a-list-of-records/PowerShell/search-a-list-of-records-4.psh delete mode 100644 Task/Search-a-list-of-records/PowerShell/search-a-list-of-records-5.psh delete mode 100644 Task/Search-a-list/Ada/search-a-list.ada delete mode 100644 Task/Search-a-list/COBOL/search-a-list.cobol delete mode 100644 Task/Search-a-list/Emacs-Lisp/search-a-list.l delete mode 100644 Task/Search-a-list/Euphoria/search-a-list.ex delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-1.psh delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-2.psh delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-3.psh delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-4.psh delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-5.psh delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-6.psh delete mode 100644 Task/Search-a-list/PowerShell/search-a-list-7.psh delete mode 100644 Task/Search-a-list/REBOL/search-a-list.rebol delete mode 100644 Task/Search-a-list/VBScript/search-a-list.vb delete mode 100644 Task/Secure-temporary-file/Ada/secure-temporary-file.ada delete mode 100644 Task/Secure-temporary-file/Emacs-Lisp/secure-temporary-file.l delete mode 100644 Task/Secure-temporary-file/PowerShell/secure-temporary-file.psh delete mode 100644 Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/Ada/selectively-replace-multiple-instances-of-a-character-within-a-string.ada delete mode 100644 Task/Self-describing-numbers/Ada/self-describing-numbers.ada delete mode 100644 Task/Self-describing-numbers/PowerShell/self-describing-numbers-1.psh delete mode 100644 Task/Self-describing-numbers/PowerShell/self-describing-numbers-2.psh delete mode 100644 Task/Self-describing-numbers/PowerShell/self-describing-numbers-3.psh delete mode 100644 Task/Self-describing-numbers/VBScript/self-describing-numbers.vb delete mode 100644 Task/Semiprime/Ada/semiprime.ada delete mode 100644 Task/Semiprime/PowerShell/semiprime.psh delete mode 100644 Task/Semordnilap/Ada/semordnilap-1.ada delete mode 100644 Task/Semordnilap/Ada/semordnilap-2.ada delete mode 100644 Task/Semordnilap/Ada/semordnilap-3.ada delete mode 100644 Task/Semordnilap/PowerShell/semordnilap.psh delete mode 100644 Task/Semordnilap/REBOL/semordnilap-1.rebol delete mode 100644 Task/Semordnilap/REBOL/semordnilap-2.rebol delete mode 100644 Task/Semordnilap/VBScript/semordnilap.vb delete mode 100644 Task/Send-an-unknown-method-call/PowerShell/send-an-unknown-method-call.psh delete mode 100644 Task/Send-email/Ada/send-email.ada delete mode 100644 Task/Send-email/Emacs-Lisp/send-email.l delete mode 100644 Task/Send-email/PowerShell/send-email.psh delete mode 100644 Task/Send-email/REBOL/send-email.rebol delete mode 100644 Task/Send-email/VBScript/send-email.vb delete mode 100644 Task/Sequence-of-non-squares/Ada/sequence-of-non-squares.ada delete mode 100644 Task/Sequence-of-non-squares/COBOL/sequence-of-non-squares.cobol delete mode 100644 Task/Sequence-of-non-squares/Euphoria/sequence-of-non-squares.ex delete mode 100644 Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-1.psh delete mode 100644 Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-2.psh delete mode 100644 Task/Sequence-of-non-squares/PowerShell/sequence-of-non-squares-3.psh delete mode 100644 Task/Sequence-of-primes-by-trial-division/Ada/sequence-of-primes-by-trial-division.ada delete mode 100644 Task/Sequence-of-primes-by-trial-division/PowerShell/sequence-of-primes-by-trial-division.psh delete mode 100644 Task/Sequence:-smallest-number-greater-than-previous-term-with-exactly-n-divisors/Ada/sequence:-smallest-number-greater-than-previous-term-with-exactly-n-divisors.ada delete mode 100644 Task/Set-consolidation/Ada/set-consolidation-1.ada delete mode 100644 Task/Set-consolidation/Ada/set-consolidation-2.ada delete mode 100644 Task/Set-consolidation/Ada/set-consolidation-3.ada delete mode 100644 Task/Set-consolidation/VBScript/set-consolidation.vb delete mode 100644 Task/Set-puzzle/Ada/set-puzzle-1.ada delete mode 100644 Task/Set-puzzle/Ada/set-puzzle-2.ada delete mode 100644 Task/Set-puzzle/Ada/set-puzzle-3.ada delete mode 100644 Task/Set-right-adjacent-bits/Ada/set-right-adjacent-bits.ada delete mode 100644 Task/Set/Ada/set.ada delete mode 100644 Task/Set/PowerShell/set.psh delete mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-1.ada delete mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-2.ada delete mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Ada/seven-sided-dice-from-five-sided-dice-3.ada delete mode 100644 Task/Seven-sided-dice-from-five-sided-dice/VBScript/seven-sided-dice-from-five-sided-dice.vb delete mode 100644 Task/Shell-one-liner/Ada/shell-one-liner.ada delete mode 100644 Task/Shell-one-liner/COBOL/shell-one-liner-1.cobol delete mode 100644 Task/Shell-one-liner/COBOL/shell-one-liner-2.cobol delete mode 100644 Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-1.l delete mode 100644 Task/Shell-one-liner/Emacs-Lisp/shell-one-liner-2.l delete mode 100644 Task/Shell-one-liner/PowerShell/shell-one-liner.psh delete mode 100644 Task/Shell-one-liner/REBOL/shell-one-liner.rebol delete mode 100644 Task/Shoelace-formula-for-polygonal-area/Ada/shoelace-formula-for-polygonal-area.ada delete mode 100644 Task/Shoelace-formula-for-polygonal-area/VBScript/shoelace-formula-for-polygonal-area.vb delete mode 100644 Task/Short-circuit-evaluation/Ada/short-circuit-evaluation.ada delete mode 100644 Task/Short-circuit-evaluation/PowerShell/short-circuit-evaluation.psh delete mode 100644 Task/Shortest-common-supersequence/Ada/shortest-common-supersequence.ada delete mode 100644 Task/Show-ASCII-table/Ada/show-ascii-table.ada delete mode 100644 Task/Show-ASCII-table/COBOL/show-ascii-table.cobol delete mode 100644 Task/Show-the-epoch/Ada/show-the-epoch.ada delete mode 100644 Task/Show-the-epoch/COBOL/show-the-epoch.cobol delete mode 100644 Task/Show-the-epoch/PowerShell/show-the-epoch-1.psh delete mode 100644 Task/Show-the-epoch/PowerShell/show-the-epoch-2.psh delete mode 100644 Task/Show-the-epoch/PowerShell/show-the-epoch-3.psh delete mode 100644 Task/Show-the-epoch/PowerShell/show-the-epoch-4.psh delete mode 100644 Task/Sierpinski-arrowhead-curve/Ada/sierpinski-arrowhead-curve.ada delete mode 100644 Task/Sierpinski-carpet/Ada/sierpinski-carpet.ada delete mode 100644 Task/Sierpinski-carpet/Euphoria/sierpinski-carpet.ex delete mode 100644 Task/Sierpinski-carpet/PowerShell/sierpinski-carpet-1.psh delete mode 100644 Task/Sierpinski-carpet/PowerShell/sierpinski-carpet-2.psh delete mode 100644 Task/Sierpinski-carpet/VBScript/sierpinski-carpet.vb delete mode 100644 Task/Sierpinski-pentagon/Ada/sierpinski-pentagon.ada delete mode 100644 Task/Sierpinski-square-curve/Ada/sierpinski-square-curve.ada delete mode 100644 Task/Sierpinski-square-curve/VBScript/sierpinski-square-curve.vb delete mode 100644 Task/Sierpinski-triangle-Graphical/Ada/sierpinski-triangle-graphical.ada delete mode 100644 Task/Sierpinski-triangle-Graphical/VBScript/sierpinski-triangle-graphical.vb delete mode 100644 Task/Sierpinski-triangle/Ada/sierpinski-triangle-1.ada delete mode 100644 Task/Sierpinski-triangle/Ada/sierpinski-triangle-2.ada delete mode 100644 Task/Sierpinski-triangle/COBOL/sierpinski-triangle.cobol delete mode 100644 Task/Sierpinski-triangle/Euphoria/sierpinski-triangle.ex delete mode 100644 Task/Sierpinski-triangle/Haxe/sierpinski-triangle.haxe delete mode 100644 Task/Sierpinski-triangle/PowerShell/sierpinski-triangle.psh delete mode 100644 Task/Sierpinski-triangle/VBScript/sierpinski-triangle.vb delete mode 100644 Task/Sieve-of-Eratosthenes/Ada/sieve-of-eratosthenes.ada delete mode 100644 Task/Sieve-of-Eratosthenes/AutoIt/sieve-of-eratosthenes.autoit delete mode 100644 Task/Sieve-of-Eratosthenes/Batch-File/sieve-of-eratosthenes.bat delete mode 100644 Task/Sieve-of-Eratosthenes/COBOL/sieve-of-eratosthenes.cobol delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-1.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-2.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-3.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-4.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-5.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-6.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-7.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-8.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Chapel/sieve-of-eratosthenes-9.chapel delete mode 100644 Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-1.l delete mode 100644 Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-2.l delete mode 100644 Task/Sieve-of-Eratosthenes/Euphoria/sieve-of-eratosthenes.ex delete mode 100644 Task/Sieve-of-Eratosthenes/K/sieve-of-eratosthenes.k delete mode 100644 Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.psh delete mode 100644 Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.psh delete mode 100644 Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb delete mode 100644 Task/Simple-database/COBOL/simple-database.cobol delete mode 100644 Task/Simple-database/Emacs-Lisp/simple-database.l delete mode 100644 Task/Simple-database/PowerShell/simple-database-1.psh delete mode 100644 Task/Simple-database/PowerShell/simple-database-2.psh delete mode 100644 Task/Simple-database/PowerShell/simple-database-3.psh delete mode 100644 Task/Simple-database/PowerShell/simple-database-4.psh delete mode 100644 Task/Simple-database/PowerShell/simple-database-5.psh delete mode 100644 Task/Simple-database/REBOL/simple-database.rebol delete mode 100644 Task/Simple-turtle-graphics/Ada/simple-turtle-graphics.ada delete mode 100644 Task/Simple-windowed-application/Ada/simple-windowed-application.ada delete mode 100644 Task/Simple-windowed-application/AutoIt/simple-windowed-application.autoit delete mode 100644 Task/Simple-windowed-application/Euphoria/simple-windowed-application.ex delete mode 100644 Task/Simple-windowed-application/JavaScript/simple-windowed-application.js delete mode 100644 Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.psh delete mode 100644 Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.psh delete mode 100644 Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.psh delete mode 100644 Task/Simple-windowed-application/REBOL/simple-windowed-application.rebol delete mode 100644 Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.autoit delete mode 100644 Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.autoit delete mode 100644 Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.psh delete mode 100644 Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vb delete mode 100644 Task/Singleton/Ada/singleton-1.ada delete mode 100644 Task/Singleton/Ada/singleton-2.ada delete mode 100644 Task/Singleton/Ada/singleton-3.ada delete mode 100644 Task/Singleton/Ada/singleton-4.ada delete mode 100644 Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.ada delete mode 100644 Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.ada delete mode 100644 Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.ada delete mode 100644 Task/Sleep/Ada/sleep.ada delete mode 100644 Task/Sleep/AutoIt/sleep.autoit delete mode 100644 Task/Sleep/COBOL/sleep-1.cobol delete mode 100644 Task/Sleep/COBOL/sleep-2.cobol delete mode 100644 Task/Sleep/COBOL/sleep-3.cobol delete mode 100644 Task/Sleep/Emacs-Lisp/sleep.l delete mode 100644 Task/Sleep/PowerShell/sleep.psh delete mode 100644 Task/Sleep/REBOL/sleep.rebol delete mode 100644 Task/Sleep/VBScript/sleep.vb delete mode 100644 Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.ada delete mode 100644 Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Ada/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.ada delete mode 100644 Task/Smith-numbers/Ada/smith-numbers.ada delete mode 100644 Task/Snake/Ada/snake.ada delete mode 100644 Task/Snake/Emacs-Lisp/snake.l delete mode 100644 Task/Sockets/Ada/sockets.ada delete mode 100644 Task/Sockets/AutoIt/sockets.autoit delete mode 100644 Task/Sockets/C/sockets.c delete mode 100644 Task/Sockets/Emacs-Lisp/sockets.l delete mode 100644 Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.ada delete mode 100644 Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cobol delete mode 100644 Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.ada delete mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.ada delete mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.ada delete mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.ada delete mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.ada delete mode 100644 Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.ada delete mode 100644 Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chapel delete mode 100644 Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.ada delete mode 100644 Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vb delete mode 100644 Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.ada delete mode 100644 Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.ada delete mode 100644 Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.ada delete mode 100644 Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.ex delete mode 100644 Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.psh delete mode 100644 Task/Sort-an-integer-array/Ada/sort-an-integer-array.ada delete mode 100644 Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cobol delete mode 100644 Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.ex delete mode 100644 Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.psh delete mode 100644 Task/Sort-an-integer-array/REBOL/sort-an-integer-array.rebol delete mode 100644 Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx delete mode 100644 Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx delete mode 100644 Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.ada delete mode 100644 Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.ex delete mode 100644 Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist-1.phix delete mode 100644 Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist-2.phix delete mode 100644 Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.psh delete mode 100644 Task/Sort-numbers-lexicographically/Ada/sort-numbers-lexicographically.ada delete mode 100644 Task/Sort-numbers-lexicographically/COBOL/sort-numbers-lexicographically.cobol delete mode 100644 Task/Sort-stability/REBOL/sort-stability.rebol delete mode 100644 Task/Sort-three-variables/Ada/sort-three-variables.ada delete mode 100644 Task/Sort-three-variables/COBOL/sort-three-variables.cobol delete mode 100644 Task/Sort-three-variables/R/sort-three-variables-1.r delete mode 100644 Task/Sort-three-variables/R/sort-three-variables-2.r delete mode 100644 Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.ada delete mode 100644 Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.ex delete mode 100644 Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.psh delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/11l/sorting-algorithms-circle-sort.11l delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/AArch64-Assembly/sorting-algorithms-circle-sort.aarch64 delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/ALGOL-68/sorting-algorithms-circle-sort.alg delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/ARM-Assembly/sorting-algorithms-circle-sort.arm delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Action-/sorting-algorithms-circle-sort.action delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Arturo/sorting-algorithms-circle-sort.arturo delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/AutoHotkey/sorting-algorithms-circle-sort.ahk delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/C++/sorting-algorithms-circle-sort.cpp delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/C-sharp/sorting-algorithms-circle-sort.cs delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/C/sorting-algorithms-circle-sort.c delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/CoffeeScript/sorting-algorithms-circle-sort.coffee delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Crystal/sorting-algorithms-circle-sort.cr delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/D/sorting-algorithms-circle-sort.d delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Delphi/sorting-algorithms-circle-sort.pas delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/EasyLang/sorting-algorithms-circle-sort.easy delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Elixir/sorting-algorithms-circle-sort.ex delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Forth/sorting-algorithms-circle-sort.fth delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Fortran/sorting-algorithms-circle-sort.f delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/FreeBASIC/sorting-algorithms-circle-sort.basic delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Go/sorting-algorithms-circle-sort.go delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Haskell/sorting-algorithms-circle-sort.hs delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/J/sorting-algorithms-circle-sort-1.j delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/J/sorting-algorithms-circle-sort-2.j delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Java/sorting-algorithms-circle-sort.java delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Jq/sorting-algorithms-circle-sort-1.jq delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Jq/sorting-algorithms-circle-sort-2.jq delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Jq/sorting-algorithms-circle-sort-3.jq delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Jq/sorting-algorithms-circle-sort-4.jq delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Julia/sorting-algorithms-circle-sort.jl delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Kotlin/sorting-algorithms-circle-sort.kts delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Lua/sorting-algorithms-circle-sort.lua delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Mathematica/sorting-algorithms-circle-sort.math delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Nim/sorting-algorithms-circle-sort.nim delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Objeck/sorting-algorithms-circle-sort.objeck delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/PARI-GP/sorting-algorithms-circle-sort.parigp delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Pascal/sorting-algorithms-circle-sort.pas delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Perl/sorting-algorithms-circle-sort.pl delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Phix/sorting-algorithms-circle-sort.phix delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Python/sorting-algorithms-circle-sort.py delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Quackery/sorting-algorithms-circle-sort.quackery delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/REXX/sorting-algorithms-circle-sort.rexx delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Racket/sorting-algorithms-circle-sort.rkt delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Raku/sorting-algorithms-circle-sort.raku delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Ring/sorting-algorithms-circle-sort.ring delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Ruby/sorting-algorithms-circle-sort.rb delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Rust/sorting-algorithms-circle-sort.rs delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Scala/sorting-algorithms-circle-sort.scala delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Sidef/sorting-algorithms-circle-sort.sidef delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Swift/sorting-algorithms-circle-sort.swift delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/V-(Vlang)/sorting-algorithms-circle-sort.v delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Wren/sorting-algorithms-circle-sort.wren delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/XPL0/sorting-algorithms-circle-sort.xpl0 delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/ZX-Spectrum-Basic/sorting-algorithms-circle-sort.basic delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-1.zkl delete mode 100644 Task/Sorting-Algorithms-Circle-Sort/Zkl/sorting-algorithms-circle-sort-2.zkl delete mode 100644 Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cobol delete mode 100644 Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.psh delete mode 100644 Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.ada delete mode 100644 Task/Sorting-algorithms-Bogosort/COBOL/sorting-algorithms-bogosort.cobol delete mode 100644 Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.ex delete mode 100644 Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.psh delete mode 100644 Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vb delete mode 100644 Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vb delete mode 100644 Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.ada delete mode 100644 Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-1.cobol delete mode 100644 Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-2.cobol delete mode 100644 Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.ex delete mode 100644 Task/Sorting-algorithms-Bubble-sort/Haxe/sorting-algorithms-bubble-sort.haxe delete mode 100644 Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.psh delete mode 100644 Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vb delete mode 100644 Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vb delete mode 100644 Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/VBScript/sorting-algorithms-cocktail-sort-with-shifting-bounds.vb delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.ada delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cobol delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.ex delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/Haxe/sorting-algorithms-cocktail-sort.haxe delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.psh delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vb delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vb delete mode 100644 Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.ada delete mode 100644 Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cobol delete mode 100644 Task/Sorting-algorithms-Comb-sort/Haxe/sorting-algorithms-comb-sort.haxe delete mode 100644 Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.psh delete mode 100644 Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada delete mode 100644 Task/Sorting-algorithms-Counting-sort/Haxe/sorting-algorithms-counting-sort.haxe delete mode 100644 Task/Sorting-algorithms-Counting-sort/PowerShell/sorting-algorithms-counting-sort.psh delete mode 100644 Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vb delete mode 100644 Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vb delete mode 100644 Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.ada delete mode 100644 Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.ada delete mode 100644 Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.ada delete mode 100644 Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cobol delete mode 100644 Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.ex delete mode 100644 Task/Sorting-algorithms-Gnome-sort/Haxe/sorting-algorithms-gnome-sort.haxe delete mode 100644 Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.psh delete mode 100644 Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vb delete mode 100644 Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vb delete mode 100644 Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vb delete mode 100644 Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.ada delete mode 100644 Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.ada delete mode 100644 Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.ada delete mode 100644 Task/Sorting-algorithms-Heapsort/COBOL/sorting-algorithms-heapsort.cobol delete mode 100644 Task/Sorting-algorithms-Heapsort/Haxe/sorting-algorithms-heapsort.haxe delete mode 100644 Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.psh delete mode 100644 Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.ada delete mode 100644 Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-1.cobol delete mode 100644 Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-2.cobol delete mode 100644 Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.l delete mode 100644 Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.ex delete mode 100644 Task/Sorting-algorithms-Insertion-sort/Haxe/sorting-algorithms-insertion-sort.haxe delete mode 100644 Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.psh delete mode 100644 Task/Sorting-algorithms-Insertion-sort/REBOL/sorting-algorithms-insertion-sort.rebol delete mode 100644 Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vb delete mode 100644 Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.ada delete mode 100644 Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.ada delete mode 100644 Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.ada delete mode 100644 Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cobol delete mode 100644 Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.ex delete mode 100644 Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh delete mode 100644 Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.ada delete mode 100644 Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.ex delete mode 100644 Task/Sorting-algorithms-Pancake-sort/Haxe/sorting-algorithms-pancake-sort.haxe delete mode 100644 Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.psh delete mode 100644 Task/Sorting-algorithms-Patience-sort/Ada/sorting-algorithms-patience-sort.ada delete mode 100644 Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.ada delete mode 100644 Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.psh delete mode 100644 Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.ada delete mode 100644 Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada delete mode 100644 Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.ada delete mode 100644 Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cobol delete mode 100644 Task/Sorting-algorithms-Quicksort/Emacs-Lisp/sorting-algorithms-quicksort.l delete mode 100644 Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-1.psh delete mode 100644 Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.psh delete mode 100644 Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-3.psh delete mode 100644 Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vb delete mode 100644 Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.ada delete mode 100644 Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort.c delete mode 100644 Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.ada delete mode 100644 Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cobol delete mode 100644 Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.ex delete mode 100644 Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.haxe delete mode 100644 Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.psh delete mode 100644 Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vb delete mode 100644 Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.ada delete mode 100644 Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.ada delete mode 100644 Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cobol delete mode 100644 Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-2.cobol delete mode 100644 Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.ex delete mode 100644 Task/Sorting-algorithms-Shell-sort/Haxe/sorting-algorithms-shell-sort.haxe delete mode 100644 Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.psh delete mode 100644 Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.ada delete mode 100644 Task/Sorting-algorithms-Sleep-sort/Assembly/sorting-algorithms-sleep-sort.as delete mode 100644 Task/Sorting-algorithms-Sleep-sort/Emacs-Lisp/sorting-algorithms-sleep-sort.l delete mode 100644 Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.ex delete mode 100644 Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.ada delete mode 100644 Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cobol delete mode 100644 Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.ex delete mode 100644 Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.psh delete mode 100644 Task/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.ex delete mode 100644 Task/Soundex/Ada/soundex.ada delete mode 100644 Task/Soundex/COBOL/soundex.cobol delete mode 100644 Task/Soundex/Emacs-Lisp/soundex.l delete mode 100644 Task/Soundex/PowerShell/soundex-1.psh delete mode 100644 Task/Soundex/PowerShell/soundex-2.psh delete mode 100644 Task/Soundex/PowerShell/soundex-3.psh delete mode 100644 Task/Soundex/PowerShell/soundex-4.psh delete mode 100644 Task/Soundex/VBScript/soundex.vb delete mode 100644 Task/Sparkline-in-unicode/VBScript/sparkline-in-unicode.vb delete mode 100644 Task/Special-characters/Ada/special-characters-1.ada delete mode 100644 Task/Special-characters/Ada/special-characters-2.ada delete mode 100644 Task/Special-variables/PowerShell/special-variables-1.psh delete mode 100644 Task/Special-variables/PowerShell/special-variables-2.psh delete mode 100644 Task/Speech-synthesis/AutoIt/speech-synthesis.autoit delete mode 100644 Task/Speech-synthesis/PowerShell/speech-synthesis.psh delete mode 100644 Task/Speech-synthesis/VBScript/speech-synthesis.vb delete mode 100644 Task/Spinning-rod-animation-Text/Ada/spinning-rod-animation-text.ada delete mode 100644 Task/Spinning-rod-animation-Text/Emacs-Lisp/spinning-rod-animation-text.l delete mode 100644 Task/Spiral-matrix/Ada/spiral-matrix-1.ada delete mode 100644 Task/Spiral-matrix/Ada/spiral-matrix-2.ada delete mode 100644 Task/Spiral-matrix/Euphoria/spiral-matrix.ex delete mode 100644 Task/Spiral-matrix/PowerShell/spiral-matrix.psh delete mode 100644 Task/Spiral-matrix/VBScript/spiral-matrix.vb delete mode 100644 Task/Split-a-character-string-based-on-change-of-character/Ada/split-a-character-string-based-on-change-of-character.ada delete mode 100644 Task/Split-a-character-string-based-on-change-of-character/COBOL/split-a-character-string-based-on-change-of-character.cobol delete mode 100644 Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.l delete mode 100644 Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-1.psh delete mode 100644 Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-2.psh delete mode 100644 Task/Square-but-not-cube/Ada/square-but-not-cube.ada delete mode 100644 Task/Square-but-not-cube/COBOL/square-but-not-cube.cobol delete mode 100644 Task/Square-but-not-cube/Lua/square-but-not-cube.lua delete mode 100644 Task/Square-free-integers/Pascal/square-free-integers.pas delete mode 100644 Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.psh delete mode 100644 Task/Stack-traces/Ada/stack-traces.ada delete mode 100644 Task/Stack/Ada/stack-1.ada delete mode 100644 Task/Stack/Ada/stack-2.ada delete mode 100644 Task/Stack/Batch-File/stack.bat delete mode 100644 Task/Stack/COBOL/stack-1.cobol delete mode 100644 Task/Stack/COBOL/stack-2.cobol delete mode 100644 Task/Stack/COBOL/stack-3.cobol delete mode 100644 Task/Stack/COBOL/stack-4.cobol delete mode 100644 Task/Stack/COBOL/stack-5.cobol delete mode 100644 Task/Stack/COBOL/stack-6.cobol delete mode 100644 Task/Stack/PowerShell/stack-1.psh delete mode 100644 Task/Stack/PowerShell/stack-2.psh delete mode 100644 Task/Stack/PowerShell/stack-3.psh delete mode 100644 Task/Stack/PowerShell/stack-4.psh delete mode 100644 Task/Stack/PowerShell/stack-5.psh delete mode 100644 Task/Stack/PowerShell/stack-6.psh delete mode 100644 Task/Stack/PowerShell/stack-7.psh delete mode 100644 Task/Stack/REBOL/stack.rebol delete mode 100644 Task/Stack/VBScript/stack-1.vb delete mode 100644 Task/Stack/VBScript/stack-2.vb delete mode 100644 Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.ada delete mode 100644 Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.ada delete mode 100644 Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.ex delete mode 100644 Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.psh delete mode 100644 Task/Stair-climbing-puzzle/REBOL/stair-climbing-puzzle.rebol delete mode 100644 Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.ada delete mode 100644 Task/Statistics-Basic/Ada/statistics-basic-1.ada delete mode 100644 Task/Statistics-Basic/Ada/statistics-basic-2.ada delete mode 100644 Task/Steffensens-method/Haxe/steffensens-method.haxe delete mode 100644 Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.ada delete mode 100644 Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.ex delete mode 100644 Task/Stem-and-leaf-plot/PowerShell/stem-and-leaf-plot.psh delete mode 100644 Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.ada delete mode 100644 Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.psh delete mode 100644 Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vb delete mode 100644 Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vb delete mode 100644 Task/Stream-merge/Ada/stream-merge.ada delete mode 100644 Task/String-append/Ada/string-append.ada delete mode 100644 Task/String-append/COBOL/string-append.cobol delete mode 100644 Task/String-append/Emacs-Lisp/string-append-1.l delete mode 100644 Task/String-append/Emacs-Lisp/string-append-2.l delete mode 100644 Task/String-append/Emacs-Lisp/string-append-3.l delete mode 100644 Task/String-append/Euphoria/string-append.ex delete mode 100644 Task/String-append/PowerShell/string-append.psh delete mode 100644 Task/String-append/VBScript/string-append.vb delete mode 100644 Task/String-case/Ada/string-case.ada delete mode 100644 Task/String-case/AutoIt/string-case.autoit delete mode 100644 Task/String-case/COBOL/string-case-1.cobol delete mode 100644 Task/String-case/COBOL/string-case-2.cobol delete mode 100644 Task/String-case/PowerShell/string-case.psh delete mode 100644 Task/String-case/Python/string-case-1.py delete mode 100644 Task/String-case/Python/string-case-2.py delete mode 100644 Task/String-case/REBOL/string-case.rebol delete mode 100644 Task/String-case/VBScript/string-case.vb delete mode 100644 Task/String-comparison/Ada/string-comparison.ada delete mode 100644 Task/String-comparison/COBOL/string-comparison-1.cobol delete mode 100644 Task/String-comparison/COBOL/string-comparison-2.cobol delete mode 100644 Task/String-comparison/COBOL/string-comparison-3.cobol delete mode 100644 Task/String-comparison/PowerShell/string-comparison-1.psh delete mode 100644 Task/String-comparison/PowerShell/string-comparison-2.psh delete mode 100644 Task/String-concatenation/Ada/string-concatenation.ada delete mode 100644 Task/String-concatenation/COBOL/string-concatenation-1.cobol delete mode 100644 Task/String-concatenation/COBOL/string-concatenation-2.cobol delete mode 100644 Task/String-concatenation/COBOL/string-concatenation-3.cobol delete mode 100644 Task/String-concatenation/Emacs-Lisp/string-concatenation.l delete mode 100644 Task/String-concatenation/Euphoria/string-concatenation.ex delete mode 100644 Task/String-concatenation/PowerShell/string-concatenation.psh delete mode 100644 Task/String-concatenation/REBOL/string-concatenation.rebol delete mode 100644 Task/String-concatenation/ReScript/string-concatenation.re delete mode 100644 Task/String-concatenation/VBScript/string-concatenation.vb delete mode 100644 Task/String-interpolation-included-/Ada/string-interpolation-included--1.ada delete mode 100644 Task/String-interpolation-included-/Ada/string-interpolation-included--2.ada delete mode 100644 Task/String-interpolation-included-/COBOL/string-interpolation-included-.cobol delete mode 100644 Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.l delete mode 100644 Task/String-interpolation-included-/Euphoria/string-interpolation-included-.ex delete mode 100644 Task/String-interpolation-included-/Haxe/string-interpolation-included-.haxe delete mode 100644 Task/String-interpolation-included-/PowerShell/string-interpolation-included--1.psh delete mode 100644 Task/String-interpolation-included-/PowerShell/string-interpolation-included--2.psh delete mode 100644 Task/String-interpolation-included-/PowerShell/string-interpolation-included--3.psh delete mode 100644 Task/String-interpolation-included-/REBOL/string-interpolation-included-.rebol delete mode 100644 Task/String-length/Ada/string-length-1.ada delete mode 100644 Task/String-length/Ada/string-length-2.ada delete mode 100644 Task/String-length/COBOL/string-length-1.cobol delete mode 100644 Task/String-length/COBOL/string-length-2.cobol delete mode 100644 Task/String-length/COBOL/string-length-3.cobol delete mode 100644 Task/String-length/COBOL/string-length-4.cobol delete mode 100644 Task/String-length/Emacs-Lisp/string-length-1.l delete mode 100644 Task/String-length/Emacs-Lisp/string-length-2.l delete mode 100644 Task/String-length/Emacs-Lisp/string-length-3.l delete mode 100644 Task/String-length/Euphoria/string-length.ex delete mode 100644 Task/String-length/PowerShell/string-length-1.psh delete mode 100644 Task/String-length/PowerShell/string-length-2.psh delete mode 100644 Task/String-length/PowerShell/string-length-3.psh delete mode 100644 Task/String-length/REBOL/string-length-1.rebol delete mode 100644 Task/String-length/REBOL/string-length-2.rebol delete mode 100644 Task/String-length/ReScript/string-length.re delete mode 100644 Task/String-length/VBScript/string-length-1.vb delete mode 100644 Task/String-length/VBScript/string-length-2.vb delete mode 100644 Task/String-matching/Ada/string-matching.ada delete mode 100644 Task/String-matching/AutoIt/string-matching.autoit delete mode 100644 Task/String-matching/Batch-File/string-matching.bat delete mode 100644 Task/String-matching/Emacs-Lisp/string-matching.l delete mode 100644 Task/String-matching/Euphoria/string-matching.ex delete mode 100644 Task/String-matching/Factor/string-matching-1.factor delete mode 100644 Task/String-matching/Factor/string-matching-2.factor delete mode 100644 Task/String-matching/Factor/string-matching-3.factor delete mode 100644 Task/String-matching/Factor/string-matching-4.factor delete mode 100644 Task/String-matching/Factor/string-matching-5.factor delete mode 100644 Task/String-matching/Java/string-matching-10.java delete mode 100644 Task/String-matching/Java/string-matching-3.java delete mode 100644 Task/String-matching/Java/string-matching-4.java delete mode 100644 Task/String-matching/Java/string-matching-5.java delete mode 100644 Task/String-matching/Java/string-matching-6.java delete mode 100644 Task/String-matching/Java/string-matching-7.java delete mode 100644 Task/String-matching/Java/string-matching-8.java delete mode 100644 Task/String-matching/Java/string-matching-9.java delete mode 100644 Task/String-matching/Jq/string-matching-3.jq delete mode 100644 Task/String-matching/Jq/string-matching-4.jq delete mode 100644 Task/String-matching/Jq/string-matching-5.jq delete mode 100644 Task/String-matching/Jq/string-matching-6.jq delete mode 100644 Task/String-matching/M2000-Interpreter/string-matching-1.m2000 delete mode 100644 Task/String-matching/M2000-Interpreter/string-matching-2.m2000 delete mode 100644 Task/String-matching/OCaml/string-matching-1.ml delete mode 100644 Task/String-matching/OCaml/string-matching-2.ml delete mode 100644 Task/String-matching/OCaml/string-matching-3.ml delete mode 100644 Task/String-matching/OCaml/string-matching-4.ml delete mode 100644 Task/String-matching/OCaml/string-matching-5.ml delete mode 100644 Task/String-matching/PL-I/string-matching-1.pli delete mode 100644 Task/String-matching/PL-I/string-matching-2.pli delete mode 100644 Task/String-matching/Perl/string-matching-1.pl delete mode 100644 Task/String-matching/Perl/string-matching-2.pl delete mode 100644 Task/String-matching/Perl/string-matching-3.pl delete mode 100644 Task/String-matching/Perl/string-matching-4.pl delete mode 100644 Task/String-matching/Perl/string-matching-5.pl delete mode 100644 Task/String-matching/PowerShell/string-matching.psh delete mode 100644 Task/String-matching/PureBasic/string-matching-1.basic delete mode 100644 Task/String-matching/PureBasic/string-matching-2.basic delete mode 100644 Task/String-matching/PureBasic/string-matching-3.basic delete mode 100644 Task/String-matching/Raku/string-matching-1.raku delete mode 100644 Task/String-matching/Raku/string-matching-2.raku delete mode 100644 Task/String-matching/Raku/string-matching-3.raku delete mode 100644 Task/String-matching/Raku/string-matching-4.raku delete mode 100644 Task/String-matching/Sed/string-matching-1.sed delete mode 100644 Task/String-matching/Sed/string-matching-2.sed delete mode 100644 Task/String-matching/Sed/string-matching-3.sed delete mode 100644 Task/String-matching/VBScript/string-matching.vb delete mode 100644 Task/String-prepend/Ada/string-prepend.ada delete mode 100644 Task/String-prepend/COBOL/string-prepend-1.cobol delete mode 100644 Task/String-prepend/COBOL/string-prepend-2.cobol delete mode 100644 Task/String-prepend/Emacs-Lisp/string-prepend-1.l delete mode 100644 Task/String-prepend/Emacs-Lisp/string-prepend-2.l delete mode 100644 Task/String-prepend/Emacs-Lisp/string-prepend-3.l delete mode 100644 Task/String-prepend/PowerShell/string-prepend.psh delete mode 100644 Task/String-prepend/VBScript/string-prepend.vb delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.ada delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cobol delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/Emacs-Lisp/strip-a-set-of-characters-from-a-string.l delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.ex delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string.odin delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.psh delete mode 100644 Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vb delete mode 100644 Task/Strip-block-comments/Ada/strip-block-comments.ada delete mode 100644 Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.ada delete mode 100644 Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.autoit delete mode 100644 Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.autoit delete mode 100644 Task/Strip-comments-from-a-string/COBOL/strip-comments-from-a-string.cobol delete mode 100644 Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.l delete mode 100644 Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vb delete mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.ada delete mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.psh delete mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.psh delete mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.psh delete mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vb delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.ada delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-1.cobol delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cobol delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.l delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.l delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.ex delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.psh delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail.seed7 delete mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vb delete mode 100644 Task/Subleq/Ada/subleq.ada delete mode 100644 Task/Subleq/COBOL/subleq.cobol delete mode 100644 Task/Subleq/PowerShell/subleq-1.psh delete mode 100644 Task/Subleq/PowerShell/subleq-2.psh delete mode 100644 Task/Substitution-cipher/Ada/substitution-cipher.ada delete mode 100644 Task/Substitution-cipher/Emacs-Lisp/substitution-cipher.l delete mode 100644 Task/Substitution-cipher/VBScript/substitution-cipher.vb delete mode 100644 Task/Substring-Top-and-tail/Ada/substring-top-and-tail-1.ada delete mode 100644 Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.ada delete mode 100644 Task/Substring-Top-and-tail/COBOL/substring-top-and-tail.cobol delete mode 100644 Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.l delete mode 100644 Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.ex delete mode 100644 Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-1.psh delete mode 100644 Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-2.psh delete mode 100644 Task/Substring-Top-and-tail/VBScript/substring-top-and-tail.vb delete mode 100644 Task/Substring/Ada/substring-1.ada delete mode 100644 Task/Substring/Ada/substring-2.ada delete mode 100644 Task/Substring/Ada/substring-3.ada delete mode 100644 Task/Substring/COBOL/substring.cobol delete mode 100644 Task/Substring/Euphoria/substring.ex delete mode 100644 Task/Substring/PowerShell/substring.psh delete mode 100644 Task/Substring/REBOL/substring.rebol delete mode 100644 Task/Substring/ReScript/substring.re delete mode 100644 Task/Substring/VBScript/substring.vb delete mode 100644 Task/Subtractive-generator/Ada/subtractive-generator-1.ada delete mode 100644 Task/Subtractive-generator/Ada/subtractive-generator-2.ada delete mode 100644 Task/Subtractive-generator/Ada/subtractive-generator-3.ada delete mode 100644 Task/Subtractive-generator/PowerShell/subtractive-generator.psh delete mode 100644 Task/Sudan-function/Ada/sudan-function.ada delete mode 100644 Task/Sudoku/Ada/sudoku.ada delete mode 100644 Task/Sudoku/VBScript/sudoku-1.vb delete mode 100644 Task/Sudoku/VBScript/sudoku-2.vb delete mode 100644 Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-1.ada delete mode 100644 Task/Sum-and-product-of-an-array/Ada/sum-and-product-of-an-array-2.ada delete mode 100644 Task/Sum-and-product-of-an-array/COBOL/sum-and-product-of-an-array.cobol delete mode 100644 Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-1.l delete mode 100644 Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-2.l delete mode 100644 Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array-3.l delete mode 100644 Task/Sum-and-product-of-an-array/Euphoria/sum-and-product-of-an-array.ex delete mode 100644 Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-1.psh delete mode 100644 Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-2.psh delete mode 100644 Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-3.psh delete mode 100644 Task/Sum-and-product-of-an-array/PowerShell/sum-and-product-of-an-array-4.psh delete mode 100644 Task/Sum-and-product-of-an-array/REBOL/sum-and-product-of-an-array.rebol delete mode 100644 Task/Sum-and-product-of-an-array/VBScript/sum-and-product-of-an-array.vb delete mode 100644 Task/Sum-digits-of-an-integer/Ada/sum-digits-of-an-integer.ada delete mode 100644 Task/Sum-digits-of-an-integer/Emacs-Lisp/sum-digits-of-an-integer.l delete mode 100644 Task/Sum-digits-of-an-integer/PowerShell/sum-digits-of-an-integer.psh delete mode 100644 Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-3.rexx delete mode 100644 Task/Sum-multiples-of-3-and-5/Ada/sum-multiples-of-3-and-5-1.ada delete mode 100644 Task/Sum-multiples-of-3-and-5/Ada/sum-multiples-of-3-and-5-2.ada delete mode 100644 Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-1.cobol delete mode 100644 Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-2.cobol delete mode 100644 Task/Sum-multiples-of-3-and-5/COBOL/sum-multiples-of-3-and-5-3.cobol delete mode 100644 Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-1.l delete mode 100644 Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-2.l delete mode 100644 Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5-1.psh delete mode 100644 Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5-2.psh delete mode 100644 Task/Sum-multiples-of-3-and-5/PowerShell/sum-multiples-of-3-and-5-3.psh delete mode 100644 Task/Sum-multiples-of-3-and-5/VBScript/sum-multiples-of-3-and-5.vb delete mode 100644 Task/Sum-of-a-series/Ada/sum-of-a-series.ada delete mode 100644 Task/Sum-of-a-series/COBOL/sum-of-a-series.cobol delete mode 100644 Task/Sum-of-a-series/Emacs-Lisp/sum-of-a-series.l delete mode 100644 Task/Sum-of-a-series/Euphoria/sum-of-a-series.ex delete mode 100644 Task/Sum-of-a-series/Haxe/sum-of-a-series-1.haxe delete mode 100644 Task/Sum-of-a-series/Haxe/sum-of-a-series-2.haxe delete mode 100644 Task/Sum-of-a-series/PowerShell/sum-of-a-series.psh delete mode 100644 Task/Sum-of-a-series/VBScript/sum-of-a-series.vb delete mode 100644 Task/Sum-of-elements-below-main-diagonal-of-matrix/Ada/sum-of-elements-below-main-diagonal-of-matrix.ada delete mode 100644 Task/Sum-of-squares/Ada/sum-of-squares.ada delete mode 100644 Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.l delete mode 100644 Task/Sum-of-squares/Euphoria/sum-of-squares.ex delete mode 100644 Task/Sum-of-squares/PowerShell/sum-of-squares.psh delete mode 100644 Task/Sum-of-squares/ReScript/sum-of-squares-1.re delete mode 100644 Task/Sum-of-squares/ReScript/sum-of-squares-2.re delete mode 100644 Task/Sum-of-squares/VBScript/sum-of-squares.vb delete mode 100644 Task/Sum-to-100/Ada/sum-to-100-1.ada delete mode 100644 Task/Sum-to-100/Ada/sum-to-100-2.ada delete mode 100644 Task/Sum-to-100/Ada/sum-to-100-3.ada delete mode 100644 Task/Sum-to-100/Ada/sum-to-100-4.ada delete mode 100644 Task/Summarize-and-say-sequence/Ada/summarize-and-say-sequence.ada delete mode 100644 Task/Superellipse/Ada/superellipse.ada delete mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Ada/sutherland-hodgman-polygon-clipping.ada delete mode 100644 Task/Symmetric-difference/Ada/symmetric-difference.ada delete mode 100644 Task/Symmetric-difference/PowerShell/symmetric-difference.psh delete mode 100644 Task/Symmetric-difference/REBOL/symmetric-difference.rebol delete mode 100644 Task/Synchronous-concurrency/Ada/synchronous-concurrency-1.ada delete mode 100644 Task/Synchronous-concurrency/Ada/synchronous-concurrency-2.ada delete mode 100644 Task/Synchronous-concurrency/Ada/synchronous-concurrency-3.ada delete mode 100644 Task/Synchronous-concurrency/Euphoria/synchronous-concurrency.ex delete mode 100644 Task/System-time/Ada/system-time.ada delete mode 100644 Task/System-time/AutoIt/system-time.autoit delete mode 100644 Task/System-time/COBOL/system-time.cobol delete mode 100644 Task/System-time/Emacs-Lisp/system-time.l delete mode 100644 Task/System-time/PowerShell/system-time-1.psh delete mode 100644 Task/System-time/PowerShell/system-time-2.psh delete mode 100644 Task/System-time/REBOL/system-time.rebol delete mode 100644 Task/System-time/VBScript/system-time.vb delete mode 100644 Task/Table-creation-Postal-addresses/PowerShell/table-creation-postal-addresses.psh delete mode 100644 Task/Table-creation-Postal-addresses/VBScript/table-creation-postal-addresses.vb delete mode 100644 Task/Take-notes-on-the-command-line/Ada/take-notes-on-the-command-line.ada delete mode 100644 Task/Take-notes-on-the-command-line/COBOL/take-notes-on-the-command-line.cobol delete mode 100644 Task/Take-notes-on-the-command-line/Euphoria/take-notes-on-the-command-line.ex delete mode 100644 Task/Take-notes-on-the-command-line/PowerShell/take-notes-on-the-command-line.psh delete mode 100644 Task/Take-notes-on-the-command-line/REBOL/take-notes-on-the-command-line.rebol delete mode 100644 Task/Tau-function/COBOL/tau-function.cobol delete mode 100644 Task/Temperature-conversion/Ada/temperature-conversion.ada delete mode 100644 Task/Temperature-conversion/AutoIt/temperature-conversion.autoit delete mode 100644 Task/Temperature-conversion/COBOL/temperature-conversion.cobol delete mode 100644 Task/Temperature-conversion/Euphoria/temperature-conversion.ex delete mode 100644 Task/Temperature-conversion/PowerShell/temperature-conversion-1.psh delete mode 100644 Task/Temperature-conversion/PowerShell/temperature-conversion-2.psh delete mode 100644 Task/Temperature-conversion/PowerShell/temperature-conversion-3.psh delete mode 100644 Task/Temperature-conversion/VBScript/temperature-conversion.vb delete mode 100644 Task/Terminal-control-Clear-the-screen/AArch64-Assembly/terminal-control-clear-the-screen.aarch64 delete mode 100644 Task/Terminal-control-Clear-the-screen/Ada/terminal-control-clear-the-screen.ada delete mode 100644 Task/Terminal-control-Clear-the-screen/Batch-File/terminal-control-clear-the-screen.bat delete mode 100644 Task/Terminal-control-Clear-the-screen/COBOL/terminal-control-clear-the-screen.cobol delete mode 100644 Task/Terminal-control-Clear-the-screen/Euphoria/terminal-control-clear-the-screen.ex delete mode 100644 Task/Terminal-control-Clear-the-screen/PowerShell/terminal-control-clear-the-screen.psh delete mode 100644 Task/Terminal-control-Coloured-text/Ada/terminal-control-coloured-text.ada delete mode 100644 Task/Terminal-control-Coloured-text/COBOL/terminal-control-coloured-text.cobol delete mode 100644 Task/Terminal-control-Coloured-text/PowerShell/terminal-control-coloured-text.psh delete mode 100644 Task/Terminal-control-Cursor-movement/Ada/terminal-control-cursor-movement.ada delete mode 100644 Task/Terminal-control-Cursor-positioning/Ada/terminal-control-cursor-positioning.ada delete mode 100644 Task/Terminal-control-Cursor-positioning/COBOL/terminal-control-cursor-positioning.cobol delete mode 100644 Task/Terminal-control-Cursor-positioning/Euphoria/terminal-control-cursor-positioning.ex delete mode 100644 Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-1.psh delete mode 100644 Task/Terminal-control-Cursor-positioning/PowerShell/terminal-control-cursor-positioning-2.psh delete mode 100644 Task/Terminal-control-Dimensions/COBOL/terminal-control-dimensions.cobol delete mode 100644 Task/Terminal-control-Dimensions/Euphoria/terminal-control-dimensions.ex delete mode 100644 Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-1.ada delete mode 100644 Task/Terminal-control-Display-an-extended-character/Ada/terminal-control-display-an-extended-character-2.ada delete mode 100644 Task/Terminal-control-Display-an-extended-character/COBOL/terminal-control-display-an-extended-character.cobol delete mode 100644 Task/Terminal-control-Hiding-the-cursor/Ada/terminal-control-hiding-the-cursor.ada delete mode 100644 Task/Terminal-control-Inverse-video/Ada/terminal-control-inverse-video.ada delete mode 100644 Task/Terminal-control-Inverse-video/COBOL/terminal-control-inverse-video.cobol delete mode 100644 Task/Terminal-control-Positional-read/PowerShell/terminal-control-positional-read.psh delete mode 100644 Task/Terminal-control-Preserve-screen/Emacs-Lisp/terminal-control-preserve-screen.l delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Ada/terminal-control-ringing-the-terminal-bell.ada delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-3.cobol delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Emacs-Lisp/terminal-control-ringing-the-terminal-bell.l delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-1.psh delete mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/PowerShell/terminal-control-ringing-the-terminal-bell-2.psh delete mode 100644 Task/Ternary-logic/Ada/ternary-logic-1.ada delete mode 100644 Task/Ternary-logic/Ada/ternary-logic-2.ada delete mode 100644 Task/Ternary-logic/Ada/ternary-logic-3.ada delete mode 100644 Task/Test-a-function/Ada/test-a-function-1.ada delete mode 100644 Task/Test-a-function/Ada/test-a-function-2.ada delete mode 100644 Task/Test-a-function/Euphoria/test-a-function.ex delete mode 100644 Task/Test-integerness/Ada/test-integerness.ada delete mode 100644 Task/Test-integerness/COBOL/test-integerness.cobol delete mode 100644 Task/Test-integerness/PowerShell/test-integerness-1.psh delete mode 100644 Task/Test-integerness/PowerShell/test-integerness-2.psh delete mode 100644 Task/Text-processing-1/Ada/text-processing-1.ada delete mode 100644 Task/Text-processing-1/COBOL/text-processing-1.cobol delete mode 100644 Task/Text-processing-1/PowerShell/text-processing-1.psh delete mode 100644 Task/Text-processing-1/VBScript/text-processing-1.vb delete mode 100644 Task/Text-processing-2/Ada/text-processing-2.ada delete mode 100644 Task/Text-processing-2/COBOL/text-processing-2.cobol delete mode 100644 Task/Text-processing-2/PowerShell/text-processing-2-1.psh delete mode 100644 Task/Text-processing-2/PowerShell/text-processing-2-2.psh delete mode 100644 Task/Text-processing-2/VBScript/text-processing-2.vb delete mode 100644 Task/Text-processing-Max-licenses-in-use/Ada/text-processing-max-licenses-in-use.ada delete mode 100644 Task/Text-processing-Max-licenses-in-use/COBOL/text-processing-max-licenses-in-use.cobol delete mode 100644 Task/Text-processing-Max-licenses-in-use/Euphoria/text-processing-max-licenses-in-use.ex delete mode 100644 Task/Text-processing-Max-licenses-in-use/PowerShell/text-processing-max-licenses-in-use.psh delete mode 100644 Task/Textonyms/PowerShell/textonyms.psh delete mode 100644 Task/Textonyms/VBScript/textonyms.vb delete mode 100644 Task/The-Name-Game/Ada/the-name-game.ada delete mode 100644 Task/The-Name-Game/COBOL/the-name-game.cobol delete mode 100644 Task/The-Name-Game/PowerShell/the-name-game.psh delete mode 100644 Task/The-Twelve-Days-of-Christmas/Ada/the-twelve-days-of-christmas.ada delete mode 100644 Task/The-Twelve-Days-of-Christmas/AutoLISP/the-twelve-days-of-christmas.l delete mode 100644 Task/The-Twelve-Days-of-Christmas/COBOL/the-twelve-days-of-christmas.cobol delete mode 100644 Task/The-Twelve-Days-of-Christmas/PowerShell/the-twelve-days-of-christmas.psh delete mode 100644 Task/The-Twelve-Days-of-Christmas/VBScript/the-twelve-days-of-christmas.vb delete mode 100644 Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-1.ada delete mode 100644 Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-2.ada delete mode 100644 Task/Thieles-interpolation-formula/Ada/thieles-interpolation-formula-3.ada delete mode 100644 Task/Thieles-interpolation-formula/PowerShell/thieles-interpolation-formula.psh delete mode 100644 Task/Thue-Morse/Ada/thue-morse.ada delete mode 100644 Task/Thue-Morse/COBOL/thue-morse.cobol delete mode 100644 Task/Thue-Morse/PowerShell/thue-morse.psh delete mode 100644 Task/Tic-tac-toe/Ada/tic-tac-toe.ada delete mode 100644 Task/Tic-tac-toe/Euphoria/tic-tac-toe.ex delete mode 100644 Task/Tic-tac-toe/Julia/tic-tac-toe.jl delete mode 100644 Task/Tic-tac-toe/Lua/tic-tac-toe.lua delete mode 100644 Task/Time-a-function/Ada/time-a-function.ada delete mode 100644 Task/Time-a-function/Euphoria/time-a-function.ex delete mode 100644 Task/Time-a-function/PowerShell/time-a-function.psh delete mode 100644 Task/Tokenize-a-string-with-escaping/Ada/tokenize-a-string-with-escaping.ada delete mode 100644 Task/Tokenize-a-string-with-escaping/COBOL/tokenize-a-string-with-escaping.cobol delete mode 100644 Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-1.psh delete mode 100644 Task/Tokenize-a-string-with-escaping/PowerShell/tokenize-a-string-with-escaping-2.psh delete mode 100644 Task/Tokenize-a-string/Ada/tokenize-a-string.ada delete mode 100644 Task/Tokenize-a-string/COBOL/tokenize-a-string.cobol delete mode 100644 Task/Tokenize-a-string/Euphoria/tokenize-a-string.ex delete mode 100644 Task/Tokenize-a-string/PowerShell/tokenize-a-string-1.psh delete mode 100644 Task/Tokenize-a-string/PowerShell/tokenize-a-string-2.psh delete mode 100644 Task/Tokenize-a-string/PowerShell/tokenize-a-string-3.psh delete mode 100644 Task/Tokenize-a-string/REBOL/tokenize-a-string.rebol delete mode 100644 Task/Tokenize-a-string/Tcl/tokenize-a-string-3.tcl delete mode 100644 Task/Tokenize-a-string/Tcl/tokenize-a-string-4.tcl delete mode 100644 Task/Tokenize-a-string/VBScript/tokenize-a-string.vb delete mode 100644 Task/Tonelli-Shanks-algorithm/PowerShell/tonelli-shanks-algorithm.psh delete mode 100644 Task/Top-rank-per-group/Ada/top-rank-per-group.ada delete mode 100644 Task/Top-rank-per-group/PowerShell/top-rank-per-group.psh delete mode 100644 Task/Topic-variable/PowerShell/topic-variable-1.psh delete mode 100644 Task/Topic-variable/PowerShell/topic-variable-2.psh delete mode 100644 Task/Topic-variable/PowerShell/topic-variable-3.psh delete mode 100644 Task/Topological-sort/Ada/topological-sort-1.ada delete mode 100644 Task/Topological-sort/Ada/topological-sort-2.ada delete mode 100644 Task/Topological-sort/Ada/topological-sort-3.ada delete mode 100644 Task/Topological-sort/Ada/topological-sort-4.ada delete mode 100644 Task/Topological-sort/Ada/topological-sort-5.ada delete mode 100644 Task/Topological-sort/PowerShell/topological-sort.psh delete mode 100644 Task/Topological-sort/VBScript/topological-sort-1.vb delete mode 100644 Task/Topological-sort/VBScript/topological-sort-2.vb delete mode 100644 Task/Topswops/Ada/topswops.ada delete mode 100644 Task/Total-circles-area/Ada/total-circles-area.ada delete mode 100644 Task/Totient-function/Ada/totient-function.ada delete mode 100644 Task/Totient-function/COBOL/totient-function.cobol delete mode 100644 Task/Towers-of-Hanoi/Ada/towers-of-hanoi.ada delete mode 100644 Task/Towers-of-Hanoi/AutoIt/towers-of-hanoi.autoit delete mode 100644 Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-1.cobol delete mode 100644 Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-2.cobol delete mode 100644 Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-3.cobol delete mode 100644 Task/Towers-of-Hanoi/Emacs-Lisp/towers-of-hanoi.l delete mode 100644 Task/Towers-of-Hanoi/PowerShell/towers-of-hanoi.psh delete mode 100644 Task/Towers-of-Hanoi/REBOL/towers-of-hanoi.rebol delete mode 100644 Task/Towers-of-Hanoi/VBScript/towers-of-hanoi.vb delete mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Ada/trabb-pardo-knuth-algorithm.ada delete mode 100644 Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.autoit delete mode 100644 Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.psh delete mode 100644 Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.psh delete mode 100644 Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.psh delete mode 100644 Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vb delete mode 100644 Task/Tree-traversal/Ada/tree-traversal.ada delete mode 100644 Task/Tree-traversal/Coq/tree-traversal.coq delete mode 100644 Task/Tree-traversal/Euphoria/tree-traversal.ex delete mode 100644 Task/Tree-traversal/REBOL/tree-traversal.rebol delete mode 100644 Task/Tree-traversal/VBScript/tree-traversal.vb delete mode 100644 Task/Trigonometric-functions/Ada/trigonometric-functions.ada delete mode 100644 Task/Trigonometric-functions/AutoLISP/trigonometric-functions.l delete mode 100644 Task/Trigonometric-functions/COBOL/trigonometric-functions.cobol delete mode 100644 Task/Trigonometric-functions/PowerShell/trigonometric-functions-1.psh delete mode 100644 Task/Trigonometric-functions/PowerShell/trigonometric-functions-2.psh delete mode 100644 Task/Trigonometric-functions/REBOL/trigonometric-functions.rebol delete mode 100644 Task/Truncatable-primes/Ada/truncatable-primes.ada delete mode 100644 Task/Truncatable-primes/PowerShell/truncatable-primes.psh delete mode 100644 Task/Truncatable-primes/VBScript/truncatable-primes.vb delete mode 100644 Task/Truncate-a-file/Ada/truncate-a-file.ada delete mode 100644 Task/Truncate-a-file/PowerShell/truncate-a-file.psh delete mode 100644 Task/Truncate-a-file/VBScript/truncate-a-file.vb delete mode 100644 Task/Twelve-statements/Ada/twelve-statements-1.ada delete mode 100644 Task/Twelve-statements/Ada/twelve-statements-2.ada delete mode 100644 Task/Twelve-statements/Ada/twelve-statements-3.ada delete mode 100644 Task/Twin-primes/Ada/twin-primes.ada delete mode 100644 Task/Twos-complement/Ada/twos-complement.ada delete mode 100644 Task/Twos-complement/COBOL/twos-complement.cobol delete mode 100644 Task/UPC/Ada/upc.ada delete mode 100644 Task/UPC/VBScript/upc.vb delete mode 100644 Task/URL-decoding/Ada/url-decoding-1.ada delete mode 100644 Task/URL-decoding/Ada/url-decoding-2.ada delete mode 100644 Task/URL-decoding/Ada/url-decoding-3.ada delete mode 100644 Task/URL-decoding/Ada/url-decoding-4.ada delete mode 100644 Task/URL-decoding/PowerShell/url-decoding.psh delete mode 100644 Task/URL-decoding/VBScript/url-decoding.vb delete mode 100644 Task/URL-encoding/Ada/url-encoding.ada delete mode 100644 Task/URL-encoding/PowerShell/url-encoding.psh delete mode 100644 Task/URL-encoding/VBScript/url-encoding.vb delete mode 100644 Task/URL-parser/Ada/url-parser.ada delete mode 100644 Task/URL-parser/PowerShell/url-parser-1.psh delete mode 100644 Task/URL-parser/PowerShell/url-parser-2.psh delete mode 100644 Task/URL-parser/VBScript/url-parser.vb delete mode 100644 Task/UTF-8-encode-and-decode/Ada/utf-8-encode-and-decode.ada delete mode 100644 Task/UTF-8-encode-and-decode/VBScript/utf-8-encode-and-decode.vb delete mode 100644 Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.ada delete mode 100644 Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.ada delete mode 100644 Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.ada delete mode 100644 Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.psh delete mode 100644 Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vb delete mode 100644 Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.ada delete mode 100644 Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.ex delete mode 100644 Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-1.psh delete mode 100644 Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-2.psh delete mode 100644 Task/Undefined-values/Ada/undefined-values.ada delete mode 100644 Task/Undefined-values/PowerShell/undefined-values-1.psh delete mode 100644 Task/Undefined-values/PowerShell/undefined-values-2.psh delete mode 100644 Task/Undefined-values/PowerShell/undefined-values-3.psh delete mode 100644 Task/Undefined-values/PowerShell/undefined-values-4.psh delete mode 100644 Task/Unicode-strings/PowerShell/unicode-strings.psh delete mode 100644 Task/Unicode-variable-names/Ada/unicode-variable-names.ada delete mode 100644 Task/Unicode-variable-names/Emacs-Lisp/unicode-variable-names.l delete mode 100644 Task/Unicode-variable-names/PowerShell/unicode-variable-names.psh delete mode 100644 Task/Universal-Turing-machine/Ada/universal-turing-machine-1.ada delete mode 100644 Task/Universal-Turing-machine/Ada/universal-turing-machine-2.ada delete mode 100644 Task/Universal-Turing-machine/Ada/universal-turing-machine-3.ada delete mode 100644 Task/Universal-Turing-machine/Ada/universal-turing-machine-4.ada delete mode 100644 Task/Unix-ls/Ada/unix-ls.ada delete mode 100644 Task/Unix-ls/PowerShell/unix-ls.psh delete mode 100644 Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.psh delete mode 100644 Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.psh delete mode 100644 Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vb delete mode 100644 Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.ada delete mode 100644 Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.ada delete mode 100644 Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.ada delete mode 100644 Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cobol delete mode 100644 Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.haxe delete mode 100644 Task/User-input-Graphical/Ada/user-input-graphical.ada delete mode 100644 Task/User-input-Graphical/PowerShell/user-input-graphical.psh delete mode 100644 Task/User-input-Graphical/REBOL/user-input-graphical.rebol delete mode 100644 Task/User-input-Graphical/VBScript/user-input-graphical.vb delete mode 100644 Task/User-input-Text/Ada/user-input-text-1.ada delete mode 100644 Task/User-input-Text/Ada/user-input-text-2.ada delete mode 100644 Task/User-input-Text/Ada/user-input-text-3.ada delete mode 100644 Task/User-input-Text/Ada/user-input-text-4.ada delete mode 100644 Task/User-input-Text/COBOL/user-input-text.cobol delete mode 100644 Task/User-input-Text/Euphoria/user-input-text.ex delete mode 100644 Task/User-input-Text/PowerShell/user-input-text.psh delete mode 100644 Task/User-input-Text/REBOL/user-input-text.rebol delete mode 100644 Task/Validate-International-Securities-Identification-Number/Ada/validate-international-securities-identification-number.ada delete mode 100644 Task/Validate-International-Securities-Identification-Number/COBOL/validate-international-securities-identification-number.cobol delete mode 100644 Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-1.psh delete mode 100644 Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-2.psh delete mode 100644 Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vb delete mode 100644 Task/Van-Eck-sequence/Ada/van-eck-sequence.ada delete mode 100644 Task/Van-Eck-sequence/COBOL/van-eck-sequence.cobol delete mode 100644 Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.ada delete mode 100644 Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.ex delete mode 100644 Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vb delete mode 100644 Task/Variable-length-quantity/Ada/variable-length-quantity.ada delete mode 100644 Task/Variable-length-quantity/Euphoria/variable-length-quantity.ex delete mode 100644 Task/Variable-size-Get/Ada/variable-size-get.ada delete mode 100644 Task/Variable-size-Get/COBOL/variable-size-get.cobol delete mode 100644 Task/Variable-size-Set/Ada/variable-size-set.ada delete mode 100644 Task/Variables/Ada/variables.ada delete mode 100644 Task/Variables/COBOL/variables-1.cobol delete mode 100644 Task/Variables/COBOL/variables-2.cobol delete mode 100644 Task/Variables/COBOL/variables-3.cobol delete mode 100644 Task/Variables/COBOL/variables-4.cobol delete mode 100644 Task/Variables/COBOL/variables-5.cobol delete mode 100644 Task/Variables/COBOL/variables-6.cobol delete mode 100644 Task/Variables/COBOL/variables-7.cobol delete mode 100644 Task/Variables/PowerShell/variables-1.psh delete mode 100644 Task/Variables/PowerShell/variables-2.psh delete mode 100644 Task/Variables/PowerShell/variables-3.psh delete mode 100644 Task/Variables/PowerShell/variables-4.psh delete mode 100644 Task/Variables/PowerShell/variables-5.psh delete mode 100644 Task/Variadic-function/Ada/variadic-function.ada delete mode 100644 Task/Variadic-function/COBOL/variadic-function.cobol delete mode 100644 Task/Variadic-function/Coq/variadic-function-1.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-2.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-3.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-4.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-5.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-6.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-7.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-8.coq delete mode 100644 Task/Variadic-function/Coq/variadic-function-9.coq delete mode 100644 Task/Variadic-function/Emacs-Lisp/variadic-function-1.l delete mode 100644 Task/Variadic-function/Emacs-Lisp/variadic-function-2.l delete mode 100644 Task/Variadic-function/Euphoria/variadic-function.ex delete mode 100644 Task/Variadic-function/PowerShell/variadic-function-1.psh delete mode 100644 Task/Variadic-function/PowerShell/variadic-function-2.psh delete mode 100644 Task/Variadic-function/PowerShell/variadic-function-3.psh delete mode 100644 Task/Variadic-function/PowerShell/variadic-function-4.psh delete mode 100644 Task/Variadic-function/REBOL/variadic-function.rebol delete mode 100644 Task/Variadic-function/REXX/variadic-function-3.rexx delete mode 100644 Task/Variadic-function/REXX/variadic-function-4.rexx delete mode 100644 Task/Variadic-function/Tcl/variadic-function-1.tcl delete mode 100644 Task/Variadic-function/Tcl/variadic-function-2.tcl delete mode 100644 Task/Vector-products/Ada/vector-products.ada delete mode 100644 Task/Vector-products/C/vector-products.c delete mode 100644 Task/Vector-products/Euphoria/vector-products.ex delete mode 100644 Task/Vector-products/PowerShell/vector-products.psh delete mode 100644 Task/Vector/Ada/vector.ada delete mode 100644 Task/Vector/C/vector.c delete mode 100644 Task/Vector/Lang/vector.lang delete mode 100644 Task/Vector/PowerShell/vector.psh delete mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-1.ada delete mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-2.ada delete mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ada/verify-distribution-uniformity-chi-squared-test-3.ada delete mode 100644 Task/Verify-distribution-uniformity-Naive/Ada/verify-distribution-uniformity-naive.ada delete mode 100644 Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-1.vb delete mode 100644 Task/Verify-distribution-uniformity-Naive/VBScript/verify-distribution-uniformity-naive-2.vb delete mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Ada/vigen-re-cipher-cryptanalysis.ada delete mode 100644 Task/Vigen-re-cipher/Ada/vigen-re-cipher.ada delete mode 100644 Task/Vigen-re-cipher/PowerShell/vigen-re-cipher.psh delete mode 100644 Task/Vigen-re-cipher/VBScript/vigen-re-cipher-1.vb delete mode 100644 Task/Vigen-re-cipher/VBScript/vigen-re-cipher-2.vb delete mode 100644 Task/Visualize-a-tree/Ada/visualize-a-tree.ada delete mode 100644 Task/Voronoi-diagram/ReScript/voronoi-diagram.re delete mode 100644 Task/Wagstaff-primes/Phix/wagstaff-primes.phix delete mode 100644 Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.ada delete mode 100644 Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-3.bat delete mode 100644 Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.l delete mode 100644 Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.ex delete mode 100644 Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.psh delete mode 100644 Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.psh delete mode 100644 Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vb delete mode 100644 Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.ada delete mode 100644 Task/Walk-a-directory-Recursively/Emacs-Lisp/walk-a-directory-recursively.l delete mode 100644 Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.psh delete mode 100644 Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.psh delete mode 100644 Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.psh delete mode 100644 Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.psh delete mode 100644 Task/War-card-game/Ada/war-card-game.ada delete mode 100644 Task/Water-collected-between-towers/Ada/water-collected-between-towers.ada delete mode 100644 Task/Web-scraping/Ada/web-scraping.ada delete mode 100644 Task/Web-scraping/PowerShell/web-scraping-1.psh delete mode 100644 Task/Web-scraping/PowerShell/web-scraping-2.psh delete mode 100644 Task/Web-scraping/PowerShell/web-scraping-3.psh delete mode 100644 Task/Web-scraping/REBOL/web-scraping.rebol delete mode 100644 Task/Web-scraping/VBScript/web-scraping.vb delete mode 100644 Task/Weird-numbers/Ada/weird-numbers-1.ada delete mode 100644 Task/Weird-numbers/Ada/weird-numbers-2.ada delete mode 100644 Task/Wieferich-primes/Ada/wieferich-primes.ada delete mode 100644 Task/Window-creation-X11/COBOL/window-creation-x11.cobol delete mode 100644 Task/Window-creation/Ada/window-creation.ada delete mode 100644 Task/Window-creation/AutoIt/window-creation.autoit delete mode 100644 Task/Window-creation/Emacs-Lisp/window-creation.l delete mode 100644 Task/Window-creation/Euphoria/window-creation-1.ex delete mode 100644 Task/Window-creation/Euphoria/window-creation-2.ex delete mode 100644 Task/Window-creation/Euphoria/window-creation-3.ex delete mode 100644 Task/Window-creation/Euphoria/window-creation-4.ex delete mode 100644 Task/Window-creation/Euphoria/window-creation-5.ex delete mode 100644 Task/Window-creation/PowerShell/window-creation-1.psh delete mode 100644 Task/Window-creation/PowerShell/window-creation-2.psh delete mode 100644 Task/Window-creation/REBOL/window-creation.rebol delete mode 100644 Task/Wireworld/Ada/wireworld.ada delete mode 100644 Task/Wireworld/AutoIt/wireworld.autoit delete mode 100644 Task/Word-frequency/Ada/word-frequency.ada delete mode 100644 Task/Word-frequency/COBOL/word-frequency.cobol delete mode 100644 Task/Word-frequency/Emacs-Lisp/word-frequency.l delete mode 100644 Task/Word-ladder/Ada/word-ladder.ada delete mode 100644 Task/Word-search/Ada/word-search.ada delete mode 100644 Task/Word-wheel/Ada/word-wheel.ada delete mode 100644 Task/Word-wheel/VBScript/word-wheel.vb delete mode 100644 Task/Word-wrap/Ada/word-wrap-1.ada delete mode 100644 Task/Word-wrap/Ada/word-wrap-2.ada delete mode 100644 Task/Word-wrap/Ada/word-wrap-3.ada delete mode 100644 Task/Word-wrap/PowerShell/word-wrap-1.psh delete mode 100644 Task/Word-wrap/PowerShell/word-wrap-2.psh delete mode 100644 Task/Word-wrap/PowerShell/word-wrap-3.psh delete mode 100644 Task/Word-wrap/VBScript/word-wrap.vb delete mode 100644 Task/Write-entire-file/Ada/write-entire-file.ada delete mode 100644 Task/Write-entire-file/COBOL/write-entire-file.cobol delete mode 100644 Task/Write-entire-file/PowerShell/write-entire-file.psh delete mode 100644 Task/Write-entire-file/VBScript/write-entire-file.vb delete mode 100644 Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.ada delete mode 100644 Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol delete mode 100644 Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.ex delete mode 100644 Task/Write-float-arrays-to-a-text-file/PowerShell/write-float-arrays-to-a-text-file.psh delete mode 100644 Task/Write-language-name-in-3D-ASCII/Ada/write-language-name-in-3d-ascii.ada delete mode 100644 Task/Write-language-name-in-3D-ASCII/COBOL/write-language-name-in-3d-ascii.cobol delete mode 100644 Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-1.psh delete mode 100644 Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-2.psh delete mode 100644 Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-3.psh delete mode 100644 Task/Write-to-Windows-event-log/VBScript/write-to-windows-event-log.vb delete mode 100644 Task/XML-DOM-serialization/Ada/xml-dom-serialization.ada delete mode 100644 Task/XML-Input/Ada/xml-input-1.ada delete mode 100644 Task/XML-Input/Ada/xml-input-2.ada delete mode 100644 Task/XML-Input/Ada/xml-input-3.ada delete mode 100644 Task/XML-Input/Ada/xml-input-4.ada delete mode 100644 Task/XML-Input/Ada/xml-input-5.ada delete mode 100644 Task/XML-Input/Ada/xml-input-6.ada delete mode 100644 Task/XML-Input/Ada/xml-input-7.ada delete mode 100644 Task/XML-Input/Bracmat/xml-input-1.bracmat delete mode 100644 Task/XML-Input/Bracmat/xml-input-2.bracmat delete mode 100644 Task/XML-Input/PowerShell/xml-input.psh delete mode 100644 Task/XML-Input/REBOL/xml-input.rebol delete mode 100644 Task/XML-Output/Ada/xml-output-1.ada delete mode 100644 Task/XML-Output/Ada/xml-output-2.ada delete mode 100644 Task/XML-Output/Bracmat/xml-output.bracmat delete mode 100644 Task/XML-Output/Euphoria/xml-output.ex delete mode 100644 Task/XML-Output/VBScript/xml-output.vb delete mode 100644 Task/XML-XPath/PowerShell/xml-xpath-1.psh delete mode 100644 Task/XML-XPath/PowerShell/xml-xpath-2.psh delete mode 100644 Task/XML-XPath/PowerShell/xml-xpath-3.psh delete mode 100644 Task/XML-XPath/PowerShell/xml-xpath-4.psh delete mode 100644 Task/XML-XPath/PowerShell/xml-xpath-5.psh delete mode 100644 Task/XML-XPath/VBScript/xml-xpath.vb delete mode 100644 Task/Y-combinator/Chapel/y-combinator-1.chapel delete mode 100644 Task/Y-combinator/Chapel/y-combinator-2.chapel delete mode 100644 Task/Y-combinator/PowerShell/y-combinator-1.psh delete mode 100644 Task/Y-combinator/PowerShell/y-combinator-2.psh delete mode 100644 Task/Y-combinator/REBOL/y-combinator-1.rebol delete mode 100644 Task/Y-combinator/REBOL/y-combinator-2.rebol delete mode 100644 Task/Yellowstone-sequence/Ada/yellowstone-sequence.ada delete mode 100644 Task/Yin-and-yang/Ada/yin-and-yang.ada delete mode 100644 Task/Zebra-puzzle/Ada/zebra-puzzle.ada delete mode 100644 Task/Zeckendorf-number-representation/Ada/zeckendorf-number-representation.ada delete mode 100644 Task/Zeckendorf-number-representation/AutoIt/zeckendorf-number-representation.autoit delete mode 100644 Task/Zeckendorf-number-representation/PowerShell/zeckendorf-number-representation-1.psh delete mode 100644 Task/Zeckendorf-number-representation/PowerShell/zeckendorf-number-representation-2.psh delete mode 100644 Task/Zeckendorf-number-representation/VBScript/zeckendorf-number-representation.vb delete mode 100644 Task/Zero-to-the-zero-power/Ada/zero-to-the-zero-power.ada delete mode 100644 Task/Zero-to-the-zero-power/COBOL/zero-to-the-zero-power.cobol delete mode 100644 Task/Zero-to-the-zero-power/Emacs-Lisp/zero-to-the-zero-power.l delete mode 100644 Task/Zero-to-the-zero-power/PowerShell/zero-to-the-zero-power.psh delete mode 100644 Task/Zero-to-the-zero-power/VBScript/zero-to-the-zero-power.vb delete mode 100644 Task/Zig-zag-matrix/Ada/zig-zag-matrix.ada delete mode 100644 Task/Zig-zag-matrix/AutoIt/zig-zag-matrix.autoit delete mode 100644 Task/Zig-zag-matrix/Euphoria/zig-zag-matrix.ex delete mode 100644 Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-1.psh delete mode 100644 Task/Zig-zag-matrix/PowerShell/zig-zag-matrix-2.psh delete mode 100644 Task/Zig-zag-matrix/Uiua/zig-zag-matrix.uiua delete mode 100644 Task/Zig-zag-matrix/VBScript/zig-zag-matrix.vb diff --git a/Lang/11l/Bioinformatics-base-count b/Lang/11l/Bioinformatics-base-count deleted file mode 120000 index d8c9e2572d..0000000000 --- a/Lang/11l/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/11l \ No newline at end of file diff --git a/Lang/11l/Meissel-Mertens-constant b/Lang/11l/Meissel-Mertens-constant deleted file mode 120000 index 908ef16ca2..0000000000 --- a/Lang/11l/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/11l \ No newline at end of file diff --git a/Lang/11l/Miller-Rabin-primality-test b/Lang/11l/Miller-Rabin-primality-test deleted file mode 120000 index cec9772a16..0000000000 --- a/Lang/11l/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/11l \ No newline at end of file diff --git a/Lang/11l/Sorting-Algorithms-Circle-Sort b/Lang/11l/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 38059f4dea..0000000000 --- a/Lang/11l/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/11l \ No newline at end of file diff --git a/Lang/6502-Assembly/00-LANG.txt b/Lang/6502-Assembly/00-LANG.txt index a7fa28ad34..1273acfa02 100644 --- a/Lang/6502-Assembly/00-LANG.txt +++ b/Lang/6502-Assembly/00-LANG.txt @@ -131,6 +131,29 @@ This flag is set if the BRK command was executed. The BRK basically * Set with: BRK * Cleared with: RTI * There are no branches associated with this command. + +This flag is used only for differentiating a BRK from an hardware IRQ +IRQ: + STA saveAccumulator ; save accumulator + PLA ; get flags + STA saveFlags ; save flags + AND #$10 ; check "break" flag + BNE IRQ_fromBreak ; if(break flag set){ goto IRQ_fromBreak; } + JMP IRQ_fromHardware ; else{ goto IRQ_fromInterrupt; } +IRQ_fromBreak: + LDA saveFlags ; load flags from temp address + PHA ; restore flags to stack + LDA saveAccumulator ; restore accumulator + ;... + RTI ; return from interrupt + +IRQ_fromInterrupt: + LDA saveFlags ; load flags from temp address + PHA ; restore flags to stack + LDA saveAccumulator ; restore accumulator + ;... + RTI ; return from interrupt +

    ===Decimal=== diff --git a/Lang/AArch64-Assembly/Bioinformatics-base-count b/Lang/AArch64-Assembly/Bioinformatics-base-count deleted file mode 120000 index 77532b44f2..0000000000 --- a/Lang/AArch64-Assembly/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Miller-Rabin-primality-test b/Lang/AArch64-Assembly/Miller-Rabin-primality-test deleted file mode 120000 index f452839a71..0000000000 --- a/Lang/AArch64-Assembly/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort b/Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 6922a69550..0000000000 --- a/Lang/AArch64-Assembly/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/AArch64-Assembly \ No newline at end of file diff --git a/Lang/ALGOL-68/Bioinformatics-base-count b/Lang/ALGOL-68/Bioinformatics-base-count deleted file mode 120000 index cb9d66b55c..0000000000 --- a/Lang/ALGOL-68/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Meissel-Mertens-constant b/Lang/ALGOL-68/Meissel-Mertens-constant deleted file mode 120000 index e7b400c689..0000000000 --- a/Lang/ALGOL-68/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Miller-Rabin-primality-test b/Lang/ALGOL-68/Miller-Rabin-primality-test deleted file mode 120000 index c0a1c115c4..0000000000 --- a/Lang/ALGOL-68/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Quaternion-type b/Lang/ALGOL-68/Quaternion-type deleted file mode 120000 index 9934ee409f..0000000000 --- a/Lang/ALGOL-68/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort b/Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index de6d7c8e6a..0000000000 --- a/Lang/ALGOL-68/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Copy-a-string b/Lang/ALGOL-W/Copy-a-string deleted file mode 120000 index 4a449ab936..0000000000 --- a/Lang/ALGOL-W/Copy-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Copy-a-string/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Integer-comparison b/Lang/ALGOL-W/Integer-comparison deleted file mode 120000 index b056aab0f7..0000000000 --- a/Lang/ALGOL-W/Integer-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-comparison/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Meissel-Mertens-constant b/Lang/ALGOL-W/Meissel-Mertens-constant deleted file mode 120000 index 48dc998c83..0000000000 --- a/Lang/ALGOL-W/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Quaternion-type b/Lang/ALGOL-W/Quaternion-type deleted file mode 120000 index 9f1593930d..0000000000 --- a/Lang/ALGOL-W/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ALGOL-W \ No newline at end of file diff --git a/Lang/APL/Bioinformatics-base-count b/Lang/APL/Bioinformatics-base-count deleted file mode 120000 index f9e2de8949..0000000000 --- a/Lang/APL/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/Bioinformatics-base-count b/Lang/ARM-Assembly/Bioinformatics-base-count deleted file mode 120000 index baff8c16a9..0000000000 --- a/Lang/ARM-Assembly/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Miller-Rabin-primality-test b/Lang/ARM-Assembly/Miller-Rabin-primality-test deleted file mode 120000 index 195623d60d..0000000000 --- a/Lang/ARM-Assembly/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort b/Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 21eb603d7e..0000000000 --- a/Lang/ARM-Assembly/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/ARM-Assembly \ No newline at end of file diff --git a/Lang/ATS/Quaternion-type b/Lang/ATS/Quaternion-type deleted file mode 120000 index 95bd8641ec..0000000000 --- a/Lang/ATS/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ATS \ No newline at end of file diff --git a/Lang/AWK/00-LANG.txt b/Lang/AWK/00-LANG.txt index 8c5a32efdd..4d384747d7 100644 --- a/Lang/AWK/00-LANG.txt +++ b/Lang/AWK/00-LANG.txt @@ -8,13 +8,13 @@ Each AWK program consists of pattern-action statements. The program reads each input line, checks lines against patterns, and runs matching actions. For programs that never read input lines, the entire program can be one BEGIN { ... } block. -* ''List users who have /bin/ksh as a shell.''$ awk -F: '$7 == "/bin/ksh" { print $1 }' /etc/passwd +* ''List users who have /bin/ksh as a shell.''$ awk -F: '$7 == "/bin/ksh" { print $1 }' /etc/passwd AWK has only three types of variables: they are strings, floating-point numbers, and associative arrays (where every array index is a string). Conversion between strings and numbers is automatic. AWK also has regular expressions, which appear in many AWK programs. There are a few built-in functions, like cos() and sprintf(). -* ''Find average line length.''$ awk '{ cnt += length($0) } END { print cnt / NR }' /etc/rc +* ''Find average line length.''$ awk '{ cnt += length($0) } END { print cnt / NR }' /etc/rc The name "AWK" comes from the initials of Alfred Aho, Peter Weinberger and Brian Kernighan: they invented AWK during the 1970s. A few decades later, Kernighan continues to maintain the [[nawk|reference implementation]] of AWK. diff --git a/Lang/AWK/Bioinformatics-base-count b/Lang/AWK/Bioinformatics-base-count deleted file mode 120000 index 0d26eb27e1..0000000000 --- a/Lang/AWK/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/AWK \ No newline at end of file diff --git a/Lang/Action-/Bioinformatics-base-count b/Lang/Action-/Bioinformatics-base-count deleted file mode 120000 index 2a7e093367..0000000000 --- a/Lang/Action-/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Action- \ No newline at end of file diff --git a/Lang/Action-/Quaternion-type b/Lang/Action-/Quaternion-type deleted file mode 120000 index 0cfb07db30..0000000000 --- a/Lang/Action-/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Action- \ No newline at end of file diff --git a/Lang/Action-/Sorting-Algorithms-Circle-Sort b/Lang/Action-/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index a9db72f0ce..0000000000 --- a/Lang/Action-/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Action- \ No newline at end of file diff --git a/Lang/Ada/Bioinformatics-base-count b/Lang/Ada/Bioinformatics-base-count deleted file mode 120000 index 59c9c9dde5..0000000000 --- a/Lang/Ada/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ada \ No newline at end of file diff --git a/Lang/Ada/Miller-Rabin-primality-test b/Lang/Ada/Miller-Rabin-primality-test deleted file mode 120000 index 79bf6fd437..0000000000 --- a/Lang/Ada/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Ada \ No newline at end of file diff --git a/Lang/Ada/Quaternion-type b/Lang/Ada/Quaternion-type deleted file mode 120000 index 9dc0eab94d..0000000000 --- a/Lang/Ada/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Ada \ No newline at end of file diff --git a/Lang/Agena/00-LANG.txt b/Lang/Agena/00-LANG.txt index c8171cc29e..5398f01156 100644 --- a/Lang/Agena/00-LANG.txt +++ b/Lang/Agena/00-LANG.txt @@ -20,6 +20,9 @@ The syntax looks like very simplified [[ALGOL 68]] with elements taken from [[Lu == How has it been implemented ? == Agena is based on the [[ANSI]] [[C]] source code of [[Lua]], a popular and widely used Open Source programming language. +== Todo == +[[Tasks not implemented in Agena]] + == See Also == [[ALGOL 68]]
    [[Lua]]
    diff --git a/Lang/Agena/100-doors b/Lang/Agena/100-doors deleted file mode 120000 index 3a9139bb1c..0000000000 --- a/Lang/Agena/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Agena \ No newline at end of file diff --git a/Lang/Arturo/Bioinformatics-base-count b/Lang/Arturo/Bioinformatics-base-count deleted file mode 120000 index 6562f48c25..0000000000 --- a/Lang/Arturo/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Meissel-Mertens-constant b/Lang/Arturo/Meissel-Mertens-constant deleted file mode 120000 index a360b321e1..0000000000 --- a/Lang/Arturo/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Quaternion-type b/Lang/Arturo/Quaternion-type deleted file mode 120000 index b96cba3183..0000000000 --- a/Lang/Arturo/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Arturo \ No newline at end of file diff --git a/Lang/Arturo/Sorting-Algorithms-Circle-Sort b/Lang/Arturo/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index fc98e0e878..0000000000 --- a/Lang/Arturo/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Arturo \ No newline at end of file diff --git a/Lang/Asymptote/Empty-program b/Lang/Asymptote/Empty-program deleted file mode 120000 index 5636b8fc49..0000000000 --- a/Lang/Asymptote/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Asymptote \ No newline at end of file diff --git a/Lang/AutoHotkey/Miller-Rabin-primality-test b/Lang/AutoHotkey/Miller-Rabin-primality-test deleted file mode 120000 index 518dd6b131..0000000000 --- a/Lang/AutoHotkey/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Quaternion-type b/Lang/AutoHotkey/Quaternion-type deleted file mode 120000 index 00a1a5a068..0000000000 --- a/Lang/AutoHotkey/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort b/Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 975740b1fa..0000000000 --- a/Lang/AutoHotkey/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/AutoHotkey \ No newline at end of file diff --git a/Lang/Axiom/Quaternion-type b/Lang/Axiom/Quaternion-type deleted file mode 120000 index 483576377a..0000000000 --- a/Lang/Axiom/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Axiom \ No newline at end of file diff --git a/Lang/BASIC/Abundant-deficient-and-perfect-number-classifications b/Lang/BASIC/Abundant-deficient-and-perfect-number-classifications deleted file mode 120000 index 732a066bdf..0000000000 --- a/Lang/BASIC/Abundant-deficient-and-perfect-number-classifications +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abundant-deficient-and-perfect-number-classifications/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Ethiopian-multiplication b/Lang/BASIC/Ethiopian-multiplication deleted file mode 120000 index 94be458bb2..0000000000 --- a/Lang/BASIC/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Mayan-numerals b/Lang/BASIC/Mayan-numerals deleted file mode 120000 index ae24d05061..0000000000 --- a/Lang/BASIC/Mayan-numerals +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mayan-numerals/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Empty-program b/Lang/BASIC256/Empty-program deleted file mode 120000 index 163b273495..0000000000 --- a/Lang/BASIC256/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Meissel-Mertens-constant b/Lang/BASIC256/Meissel-Mertens-constant deleted file mode 120000 index 6ff8d02267..0000000000 --- a/Lang/BASIC256/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Quaternion-type b/Lang/BASIC256/Quaternion-type deleted file mode 120000 index ecfff3f315..0000000000 --- a/Lang/BASIC256/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/Bioinformatics-base-count b/Lang/BBC-BASIC/Bioinformatics-base-count deleted file mode 120000 index 109612c5db..0000000000 --- a/Lang/BBC-BASIC/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Quaternion-type b/Lang/BBC-BASIC/Quaternion-type deleted file mode 120000 index 018816057d..0000000000 --- a/Lang/BBC-BASIC/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/BBC-BASIC \ No newline at end of file diff --git a/Lang/BQN/Miller-Rabin-primality-test b/Lang/BQN/Miller-Rabin-primality-test deleted file mode 120000 index 88fd3a622d..0000000000 --- a/Lang/BQN/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/BQN \ No newline at end of file diff --git a/Lang/Batch-File/Input-loop b/Lang/Batch-File/Input-loop deleted file mode 120000 index a2a4a9b473..0000000000 --- a/Lang/Batch-File/Input-loop +++ /dev/null @@ -1 +0,0 @@ -../../Task/Input-loop/Batch-File \ No newline at end of file diff --git a/Lang/Bc/Miller-Rabin-primality-test b/Lang/Bc/Miller-Rabin-primality-test deleted file mode 120000 index 1ae2fd8406..0000000000 --- a/Lang/Bc/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Bc \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/00-LANG.txt b/Lang/Binary-Lambda-Calculus/00-LANG.txt index 3f502204f1..694f9a9437 100644 --- a/Lang/Binary-Lambda-Calculus/00-LANG.txt +++ b/Lang/Binary-Lambda-Calculus/00-LANG.txt @@ -5,7 +5,16 @@ }} {{language programming paradigm|functional}} '''Binary Lambda Calculus''' is a minimal, pure, functional, esoteric language based on lambda calculus. [[provides::Capability:First class functions| ]] + ==External links== * https://tromp.github.io/cl/cl.html * https://www.ioccc.org/2012/tromp/hint.html -* https://gist.github.com/tromp/86b3184f852f65bfb814e3ab0987d861 \ No newline at end of file +* https://gist.github.com/tromp/86b3184f852f65bfb814e3ab0987d861 + +Some implementations of BLC: +* [https://www.ioccc.org/2012/tromp/hint.html original tromp's implementation] for IOCCC, in pure ANSI C +* [https://github.com/tromp/AIT tromp's AIT], a project utilizing BLC for Information Theory research. Also includes a Haskell->BLC compiler and several other implementations +* [https://codeberg.org/aartaka/cl-blc aartaka's cl-blc], implementing BLC in Lisp + +==To do== +[[Tasks not implemented in Binary Lambda Calculus]] \ No newline at end of file diff --git a/Lang/BootBASIC/Empty-program b/Lang/BootBASIC/Empty-program deleted file mode 120000 index 5aaffbd057..0000000000 --- a/Lang/BootBASIC/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/BootBASIC \ No newline at end of file diff --git a/Lang/Bracmat/Miller-Rabin-primality-test b/Lang/Bracmat/Miller-Rabin-primality-test deleted file mode 120000 index 7c953943cd..0000000000 --- a/Lang/Bracmat/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Bracmat \ No newline at end of file diff --git a/Lang/C++/Bioinformatics-base-count b/Lang/C++/Bioinformatics-base-count deleted file mode 120000 index e0584bb6b7..0000000000 --- a/Lang/C++/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/C++ \ No newline at end of file diff --git a/Lang/C++/Meissel-Mertens-constant b/Lang/C++/Meissel-Mertens-constant deleted file mode 120000 index 3242c970c7..0000000000 --- a/Lang/C++/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/C++ \ No newline at end of file diff --git a/Lang/C++/Miller-Rabin-primality-test b/Lang/C++/Miller-Rabin-primality-test deleted file mode 120000 index 615ee001e8..0000000000 --- a/Lang/C++/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/C++ \ No newline at end of file diff --git a/Lang/C++/Quaternion-type b/Lang/C++/Quaternion-type deleted file mode 120000 index 053fd1142a..0000000000 --- a/Lang/C++/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-Algorithms-Circle-Sort b/Lang/C++/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 91c7b06653..0000000000 --- a/Lang/C++/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/C++ \ No newline at end of file diff --git a/Lang/C-sharp/00-LANG.txt b/Lang/C-sharp/00-LANG.txt index 17083312b1..2ffb00e180 100644 --- a/Lang/C-sharp/00-LANG.txt +++ b/Lang/C-sharp/00-LANG.txt @@ -17,6 +17,10 @@ ==Citations== *[[wp:C_Sharp_(programming_language)|Wikipedia:C#]] +== External links == +=== Online editors and compilers === +*[https://www.onlinegdb.com/ GDB Online Compiler] (Select C#) + {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} {{language programming paradigm|Generic}} diff --git a/Lang/C-sharp/Miller-Rabin-primality-test b/Lang/C-sharp/Miller-Rabin-primality-test deleted file mode 120000 index 4d27fefcbd..0000000000 --- a/Lang/C-sharp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Quaternion-type b/Lang/C-sharp/Quaternion-type deleted file mode 120000 index 53c4bd6185..0000000000 --- a/Lang/C-sharp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Sorting-Algorithms-Circle-Sort b/Lang/C-sharp/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 6f1414c420..0000000000 --- a/Lang/C-sharp/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/C-sharp \ No newline at end of file diff --git a/Lang/C/Bioinformatics-base-count b/Lang/C/Bioinformatics-base-count deleted file mode 120000 index 4819495149..0000000000 --- a/Lang/C/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/C \ No newline at end of file diff --git a/Lang/C/Miller-Rabin-primality-test b/Lang/C/Miller-Rabin-primality-test deleted file mode 120000 index b9ab762a9c..0000000000 --- a/Lang/C/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/C \ No newline at end of file diff --git a/Lang/C/Quaternion-type b/Lang/C/Quaternion-type deleted file mode 120000 index 25d9910755..0000000000 --- a/Lang/C/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/C \ No newline at end of file diff --git a/Lang/C/Sorting-Algorithms-Circle-Sort b/Lang/C/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 335574f406..0000000000 --- a/Lang/C/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/C \ No newline at end of file diff --git a/Lang/CLU/Quaternion-type b/Lang/CLU/Quaternion-type deleted file mode 120000 index abdefd8765..0000000000 --- a/Lang/CLU/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/CLU \ No newline at end of file diff --git a/Lang/Clojure/Miller-Rabin-primality-test b/Lang/Clojure/Miller-Rabin-primality-test deleted file mode 120000 index 67b048eb10..0000000000 --- a/Lang/Clojure/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Empty-program b/Lang/CoffeeScript/Empty-program deleted file mode 120000 index c325b31ffa..0000000000 --- a/Lang/CoffeeScript/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort b/Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e4d7481d88..0000000000 --- a/Lang/CoffeeScript/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/CoffeeScript \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Miller-Rabin-primality-test b/Lang/Commodore-BASIC/Miller-Rabin-primality-test deleted file mode 120000 index 7354bc510f..0000000000 --- a/Lang/Commodore-BASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Common-Lisp/Miller-Rabin-primality-test b/Lang/Common-Lisp/Miller-Rabin-primality-test deleted file mode 120000 index 4f8dbe695d..0000000000 --- a/Lang/Common-Lisp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Quaternion-type b/Lang/Common-Lisp/Quaternion-type deleted file mode 120000 index dd7bafa7e8..0000000000 --- a/Lang/Common-Lisp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/00-LANG.txt b/Lang/Component-Pascal/00-LANG.txt index a83cc2b2e7..7056dd922c 100644 --- a/Lang/Component-Pascal/00-LANG.txt +++ b/Lang/Component-Pascal/00-LANG.txt @@ -1,4 +1,11 @@ {{language|Component Pascal}}'''Component Pascal''' is a programming language in the tradition of Oberon and [[Oberon-2]], the last language Niklaus Wirth designed before he retired in 1999. It bears the name of the [[Pascal]] programming language but is incompatible with it. Instead, it is a minor variant and refinement of Oberon-2, designed and supported by a small ETH Zürich spin-off company called Oberon microsystems. Their [[IDE]] is called BlackBox Component Builder. At the time the first version was released (1994) it presented a novel approach to graphical user interface ([[GUI]]) construction based on editable forms, where fields and command buttons are linked to exported variables and executable procedures. This approach bears some similarity to the code-behind way used in [[Microsoft]]'s [[.NET]] 3.0 to access code in XAML. ==Citations== -* [http://en.wikipedia.org/wiki/Component_Pascal Wikipedia:Component Pascal] \ No newline at end of file +* [http://en.wikipedia.org/wiki/Component_Pascal Wikipedia:Component Pascal] + +===See also=== +* [[Oberon-07]] +* [[Oberon-2]] +* [[Zonnon]] +* [[Modula-2]] +* [[Modula-3]] \ No newline at end of file diff --git a/Lang/Coq/00-LANG.txt b/Lang/Coq/00-LANG.txt index 3a03214cba..dac9774672 100644 --- a/Lang/Coq/00-LANG.txt +++ b/Lang/Coq/00-LANG.txt @@ -1,9 +1 @@ -{{language|Coq -|site=http://coq.inria.fr -}} -In computer science, Coq is a proof assistant application. It allows the expression of mathematical assertions, mechanically checks proofs of these assertions, helps to find formal proofs, and extracts a certified program from the constructive proof of its formal specification. Coq works within the theory of the calculus of inductive constructions, a derivative of the calculus of constructions. Coq is not an automated [[wp:Theorem_prover|theorem prover]] but includes automatic theorem proving tactics and various decision procedures. - -==Citations== -* [[wp:Coq|Coq]] - -[[Category:Mathematical programming languages]] \ No newline at end of file +#REDIRECT [[:Category:Rocq]] \ No newline at end of file diff --git a/Lang/Coq/100-doors b/Lang/Coq/100-doors deleted file mode 120000 index fd39f903ef..0000000000 --- a/Lang/Coq/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/Coq \ No newline at end of file diff --git a/Lang/Coq/Ackermann-function b/Lang/Coq/Ackermann-function deleted file mode 120000 index 03a0752c76..0000000000 --- a/Lang/Coq/Ackermann-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ackermann-function/Coq \ No newline at end of file diff --git a/Lang/Coq/Extend-your-language b/Lang/Coq/Extend-your-language deleted file mode 120000 index 2e717c1027..0000000000 --- a/Lang/Coq/Extend-your-language +++ /dev/null @@ -1 +0,0 @@ -../../Task/Extend-your-language/Coq \ No newline at end of file diff --git a/Lang/Coq/Factorial b/Lang/Coq/Factorial deleted file mode 120000 index 3d35ebeb5f..0000000000 --- a/Lang/Coq/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/Coq \ No newline at end of file diff --git a/Lang/Coq/Fibonacci-sequence b/Lang/Coq/Fibonacci-sequence deleted file mode 120000 index fc6d7d958a..0000000000 --- a/Lang/Coq/Fibonacci-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fibonacci-sequence/Coq \ No newline at end of file diff --git a/Lang/Coq/FizzBuzz b/Lang/Coq/FizzBuzz deleted file mode 120000 index 966d79dca5..0000000000 --- a/Lang/Coq/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/Coq \ No newline at end of file diff --git a/Lang/Coq/Hello-world-Newbie b/Lang/Coq/Hello-world-Newbie deleted file mode 120000 index 53590d7473..0000000000 --- a/Lang/Coq/Hello-world-Newbie +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Newbie/Coq \ No newline at end of file diff --git a/Lang/Coq/Hello-world-Text b/Lang/Coq/Hello-world-Text deleted file mode 120000 index 194b2d17df..0000000000 --- a/Lang/Coq/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Coq \ No newline at end of file diff --git a/Lang/Coq/Loops-For b/Lang/Coq/Loops-For deleted file mode 120000 index b1341b994c..0000000000 --- a/Lang/Coq/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/Coq \ No newline at end of file diff --git a/Lang/Coq/Tree-traversal b/Lang/Coq/Tree-traversal deleted file mode 120000 index e38e9a0bdd..0000000000 --- a/Lang/Coq/Tree-traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tree-traversal/Coq \ No newline at end of file diff --git a/Lang/Coq/Variadic-function b/Lang/Coq/Variadic-function deleted file mode 120000 index 391626fb92..0000000000 --- a/Lang/Coq/Variadic-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variadic-function/Coq \ No newline at end of file diff --git a/Lang/Crystal/Empty-program b/Lang/Crystal/Empty-program deleted file mode 120000 index 78e7f559d2..0000000000 --- a/Lang/Crystal/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Miller-Rabin-primality-test b/Lang/Crystal/Miller-Rabin-primality-test deleted file mode 120000 index 3714050251..0000000000 --- a/Lang/Crystal/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Quaternion-type b/Lang/Crystal/Quaternion-type deleted file mode 120000 index 5a28c33333..0000000000 --- a/Lang/Crystal/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-Algorithms-Circle-Sort b/Lang/Crystal/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2618e0f461..0000000000 --- a/Lang/Crystal/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Crystal \ No newline at end of file diff --git a/Lang/D/Miller-Rabin-primality-test b/Lang/D/Miller-Rabin-primality-test deleted file mode 120000 index 407bdbfce4..0000000000 --- a/Lang/D/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/D \ No newline at end of file diff --git a/Lang/D/Quaternion-type b/Lang/D/Quaternion-type deleted file mode 120000 index 4703070a3f..0000000000 --- a/Lang/D/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/D \ No newline at end of file diff --git a/Lang/D/Sorting-Algorithms-Circle-Sort b/Lang/D/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 950d2a1c8c..0000000000 --- a/Lang/D/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/D \ No newline at end of file diff --git a/Lang/Dart/Meissel-Mertens-constant b/Lang/Dart/Meissel-Mertens-constant deleted file mode 120000 index bac3ec4c99..0000000000 --- a/Lang/Dart/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Dart \ No newline at end of file diff --git a/Lang/Dart/Quaternion-type b/Lang/Dart/Quaternion-type deleted file mode 120000 index fb391b98d0..0000000000 --- a/Lang/Dart/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Dart \ No newline at end of file diff --git a/Lang/Delphi/Bioinformatics-base-count b/Lang/Delphi/Bioinformatics-base-count deleted file mode 120000 index 8964650820..0000000000 --- a/Lang/Delphi/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Meissel-Mertens-constant b/Lang/Delphi/Meissel-Mertens-constant deleted file mode 120000 index 2b1c7d3804..0000000000 --- a/Lang/Delphi/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Quaternion-type b/Lang/Delphi/Quaternion-type deleted file mode 120000 index fe804d3654..0000000000 --- a/Lang/Delphi/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sorting-Algorithms-Circle-Sort b/Lang/Delphi/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index d4a4f938c0..0000000000 --- a/Lang/Delphi/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Delphi \ No newline at end of file diff --git a/Lang/DuckDB/Bioinformatics-base-count b/Lang/DuckDB/Bioinformatics-base-count deleted file mode 120000 index 6f72a9bb3a..0000000000 --- a/Lang/DuckDB/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/DuckDB \ No newline at end of file diff --git a/Lang/E/Miller-Rabin-primality-test b/Lang/E/Miller-Rabin-primality-test deleted file mode 120000 index f586feb18b..0000000000 --- a/Lang/E/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/E \ No newline at end of file diff --git a/Lang/E/Quaternion-type b/Lang/E/Quaternion-type deleted file mode 120000 index ecc55ca8a4..0000000000 --- a/Lang/E/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/E \ No newline at end of file diff --git a/Lang/ERRE/Quaternion-type b/Lang/ERRE/Quaternion-type deleted file mode 120000 index fcc1edb64e..0000000000 --- a/Lang/ERRE/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/ERRE \ No newline at end of file diff --git a/Lang/EasyLang/Bioinformatics-base-count b/Lang/EasyLang/Bioinformatics-base-count deleted file mode 120000 index 3bc65db849..0000000000 --- a/Lang/EasyLang/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Meissel-Mertens-constant b/Lang/EasyLang/Meissel-Mertens-constant deleted file mode 120000 index 2673a3a653..0000000000 --- a/Lang/EasyLang/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Quaternion-type b/Lang/EasyLang/Quaternion-type deleted file mode 120000 index fd590dabb6..0000000000 --- a/Lang/EasyLang/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-Algorithms-Circle-Sort b/Lang/EasyLang/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 575205820f..0000000000 --- a/Lang/EasyLang/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/EasyLang \ No newline at end of file diff --git a/Lang/EchoLisp/Miller-Rabin-primality-test b/Lang/EchoLisp/Miller-Rabin-primality-test deleted file mode 120000 index a1456f561f..0000000000 --- a/Lang/EchoLisp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/EchoLisp \ No newline at end of file diff --git a/Lang/Ed/00-LANG.txt b/Lang/Ed/00-LANG.txt index 07b70e4e49..0ffa56bf3c 100644 --- a/Lang/Ed/00-LANG.txt +++ b/Lang/Ed/00-LANG.txt @@ -1,7 +1,7 @@ {{stub}} {{language|Ed}} This is the command language used by [[wp:ed_(software)]], -the line oriented text editor. +the line oriented text editor, not to be confused with [[Sed]], the stream editor. Implementations are [[GNU Ed]], [[Plan 9 Ed]], BSD ed, and original UNIX ed. Ed is also a precursor to a whole family of other text editors and command languages. @@ -19,6 +19,8 @@ cat script.ed | ed -s file.in There's a convention of starting every ed script with capital H on a line of its own, to toggle more verbose error messages on. And optionally end the script with capital Q to force-quit without saving the changes to file. +A good reference for Ed is it's info page, which can be found online [https://linux.die.net/man/1/ed here]. + Also see [[Tasks not implemented in Ed]] [[Category:Editor]] diff --git a/Lang/Ed/Bioinformatics-base-count b/Lang/Ed/Bioinformatics-base-count deleted file mode 120000 index 1af1da6104..0000000000 --- a/Lang/Ed/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ed \ No newline at end of file diff --git a/Lang/Eero/Quaternion-type b/Lang/Eero/Quaternion-type deleted file mode 120000 index 91a82e433f..0000000000 --- a/Lang/Eero/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Eero \ No newline at end of file diff --git a/Lang/Elena/Quaternion-type b/Lang/Elena/Quaternion-type deleted file mode 120000 index 1637f784c6..0000000000 --- a/Lang/Elena/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Elena \ No newline at end of file diff --git a/Lang/Elixir/Empty-program b/Lang/Elixir/Empty-program deleted file mode 120000 index e1c7956a55..0000000000 --- a/Lang/Elixir/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Miller-Rabin-primality-test b/Lang/Elixir/Miller-Rabin-primality-test deleted file mode 120000 index 911bb7e6dd..0000000000 --- a/Lang/Elixir/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-Algorithms-Circle-Sort b/Lang/Elixir/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 97335bafb5..0000000000 --- a/Lang/Elixir/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Elixir \ No newline at end of file diff --git a/Lang/Erlang/Miller-Rabin-primality-test b/Lang/Erlang/Miller-Rabin-primality-test deleted file mode 120000 index 5bdd377694..0000000000 --- a/Lang/Erlang/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/Empty-program b/Lang/Euphoria/Empty-program deleted file mode 120000 index 241cd5711b..0000000000 --- a/Lang/Euphoria/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Quaternion-type b/Lang/Euphoria/Quaternion-type deleted file mode 120000 index aedb6b51e1..0000000000 --- a/Lang/Euphoria/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Euphoria \ No newline at end of file diff --git a/Lang/F-Sharp/Miller-Rabin-primality-test b/Lang/F-Sharp/Miller-Rabin-primality-test deleted file mode 120000 index 4b1a1d67d8..0000000000 --- a/Lang/F-Sharp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Quaternion-type b/Lang/F-Sharp/Quaternion-type deleted file mode 120000 index 2de1d9f870..0000000000 --- a/Lang/F-Sharp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/F-Sharp \ No newline at end of file diff --git a/Lang/FALSE/Empty-program b/Lang/FALSE/Empty-program deleted file mode 120000 index 35445789cd..0000000000 --- a/Lang/FALSE/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/FALSE \ No newline at end of file diff --git a/Lang/Factor/Bioinformatics-base-count b/Lang/Factor/Bioinformatics-base-count deleted file mode 120000 index cf4a54a26f..0000000000 --- a/Lang/Factor/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Factor \ No newline at end of file diff --git a/Lang/Factor/Quaternion-type b/Lang/Factor/Quaternion-type deleted file mode 120000 index 47f0548ea8..0000000000 --- a/Lang/Factor/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Factor \ No newline at end of file diff --git a/Lang/Forth/Bioinformatics-base-count b/Lang/Forth/Bioinformatics-base-count deleted file mode 120000 index b72b7872d9..0000000000 --- a/Lang/Forth/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Forth \ No newline at end of file diff --git a/Lang/Forth/Miller-Rabin-primality-test b/Lang/Forth/Miller-Rabin-primality-test deleted file mode 120000 index 6d752b6553..0000000000 --- a/Lang/Forth/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Forth \ No newline at end of file diff --git a/Lang/Forth/Quaternion-type b/Lang/Forth/Quaternion-type deleted file mode 120000 index bed4c03ac8..0000000000 --- a/Lang/Forth/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Forth \ No newline at end of file diff --git a/Lang/Forth/Sorting-Algorithms-Circle-Sort b/Lang/Forth/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 0f0dc80920..0000000000 --- a/Lang/Forth/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Forth \ No newline at end of file diff --git a/Lang/Fortran/Miller-Rabin-primality-test b/Lang/Fortran/Miller-Rabin-primality-test deleted file mode 120000 index 6d501f45e9..0000000000 --- a/Lang/Fortran/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Quaternion-type b/Lang/Fortran/Quaternion-type deleted file mode 120000 index a1829748df..0000000000 --- a/Lang/Fortran/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-Algorithms-Circle-Sort b/Lang/Fortran/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 62558aaa6e..0000000000 --- a/Lang/Fortran/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Fortran \ No newline at end of file diff --git a/Lang/FreeBASIC/Bioinformatics-base-count b/Lang/FreeBASIC/Bioinformatics-base-count deleted file mode 120000 index 89403f2018..0000000000 --- a/Lang/FreeBASIC/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Meissel-Mertens-constant b/Lang/FreeBASIC/Meissel-Mertens-constant deleted file mode 120000 index f9f037c2ea..0000000000 --- a/Lang/FreeBASIC/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Miller-Rabin-primality-test b/Lang/FreeBASIC/Miller-Rabin-primality-test deleted file mode 120000 index 31ca057e36..0000000000 --- a/Lang/FreeBASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Quaternion-type b/Lang/FreeBASIC/Quaternion-type deleted file mode 120000 index f82c3a440e..0000000000 --- a/Lang/FreeBASIC/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort b/Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index ea5bf17e30..0000000000 --- a/Lang/FreeBASIC/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/FreeBASIC \ No newline at end of file diff --git a/Lang/FunL/Miller-Rabin-primality-test b/Lang/FunL/Miller-Rabin-primality-test deleted file mode 120000 index 592d9059fa..0000000000 --- a/Lang/FunL/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/FunL \ No newline at end of file diff --git a/Lang/FutureBasic/Bioinformatics-base-count b/Lang/FutureBasic/Bioinformatics-base-count deleted file mode 120000 index 8f826b0063..0000000000 --- a/Lang/FutureBasic/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Knights-tour b/Lang/FutureBasic/Knights-tour deleted file mode 120000 index c40890eb0e..0000000000 --- a/Lang/FutureBasic/Knights-tour +++ /dev/null @@ -1 +0,0 @@ -../../Task/Knights-tour/FutureBasic \ No newline at end of file diff --git a/Lang/GAP/Quaternion-type b/Lang/GAP/Quaternion-type deleted file mode 120000 index 67ec7fa115..0000000000 --- a/Lang/GAP/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/GAP \ No newline at end of file diff --git a/Lang/Gleam/00-LANG.txt b/Lang/Gleam/00-LANG.txt index 1105755c96..6a2642caa9 100644 --- a/Lang/Gleam/00-LANG.txt +++ b/Lang/Gleam/00-LANG.txt @@ -1,2 +1,5 @@ {{stub}}{{language|Gleam|hopl=no|site=https://gleam.run/}} -Gleam is a type-safe functional programming language that runs on the [[Erlang]] virtual machine. \ No newline at end of file +Gleam is a type-safe functional programming language that runs on the [[Erlang]] virtual machine. + +== Todo == +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Gleam Tasks not implemented in Gleam] \ No newline at end of file diff --git a/Lang/Go/Bioinformatics-base-count b/Lang/Go/Bioinformatics-base-count deleted file mode 120000 index 485b68c3c6..0000000000 --- a/Lang/Go/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Go \ No newline at end of file diff --git a/Lang/Go/Meissel-Mertens-constant b/Lang/Go/Meissel-Mertens-constant deleted file mode 120000 index 8c13ff2d6b..0000000000 --- a/Lang/Go/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Go \ No newline at end of file diff --git a/Lang/Go/Miller-Rabin-primality-test b/Lang/Go/Miller-Rabin-primality-test deleted file mode 120000 index c9da74462b..0000000000 --- a/Lang/Go/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Go \ No newline at end of file diff --git a/Lang/Go/Quaternion-type b/Lang/Go/Quaternion-type deleted file mode 120000 index e62c595975..0000000000 --- a/Lang/Go/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Go \ No newline at end of file diff --git a/Lang/Go/Sorting-Algorithms-Circle-Sort b/Lang/Go/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 1288f4ddcf..0000000000 --- a/Lang/Go/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Go \ No newline at end of file diff --git a/Lang/Goboscript/00-LANG.txt b/Lang/Goboscript/00-LANG.txt index 4cafdccd97..fbf55e819e 100644 --- a/Lang/Goboscript/00-LANG.txt +++ b/Lang/Goboscript/00-LANG.txt @@ -1 +1,15 @@ -{{stub}}{{language|goboscript}} \ No newline at end of file +{{stub}}{{language +|tags=compiled, transpiled, Scratch +| site=https://aspizu.github.io/goboscript/ +|parampass=value +|goboscript}} + +From [https://github.com/aspizu/goboscript/ the goboscript repo]:
    + +goboscript is a text-based programming language that compiles to Scratch. Write Scratch projects in text, and compile it into a .sb3 file -- which can be opened in the Scratch editor, TurboWarp or be uploaded to the Scratch website. + +===Package managers=== +Despite being a relatively new programming language, goboscript has multiple package managers. + +* [https://github.com/aspizu/backpack backpack] - The official goboscript package manager +* [https://github.com/inflated-goboscript/inflator inflator] - A more powerful package manager inspired by Python's pip \ No newline at end of file diff --git a/Lang/Groovy/Empty-program b/Lang/Groovy/Empty-program deleted file mode 120000 index 8d1c7a42ae..0000000000 --- a/Lang/Groovy/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Groovy \ No newline at end of file diff --git a/Lang/Haskell/Bioinformatics-base-count b/Lang/Haskell/Bioinformatics-base-count deleted file mode 120000 index cf913dcdcd..0000000000 --- a/Lang/Haskell/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Miller-Rabin-primality-test b/Lang/Haskell/Miller-Rabin-primality-test deleted file mode 120000 index c41f1ba06c..0000000000 --- a/Lang/Haskell/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Quaternion-type b/Lang/Haskell/Quaternion-type deleted file mode 120000 index 14aca84bfa..0000000000 --- a/Lang/Haskell/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sorting-Algorithms-Circle-Sort b/Lang/Haskell/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 7f6f1559db..0000000000 --- a/Lang/Haskell/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Haskell \ No newline at end of file diff --git a/Lang/Icon/Miller-Rabin-primality-test b/Lang/Icon/Miller-Rabin-primality-test deleted file mode 120000 index 0a9d526a8b..0000000000 --- a/Lang/Icon/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Icon \ No newline at end of file diff --git a/Lang/Idris/Quaternion-type b/Lang/Idris/Quaternion-type deleted file mode 120000 index 6489466168..0000000000 --- a/Lang/Idris/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Idris \ No newline at end of file diff --git a/Lang/J/Bioinformatics-base-count b/Lang/J/Bioinformatics-base-count deleted file mode 120000 index 78c6127b60..0000000000 --- a/Lang/J/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/J \ No newline at end of file diff --git a/Lang/J/Meissel-Mertens-constant b/Lang/J/Meissel-Mertens-constant deleted file mode 120000 index 04eb0042a3..0000000000 --- a/Lang/J/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/J \ No newline at end of file diff --git a/Lang/J/Quaternion-type b/Lang/J/Quaternion-type deleted file mode 120000 index 0868577467..0000000000 --- a/Lang/J/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/J \ No newline at end of file diff --git a/Lang/J/Sorting-Algorithms-Circle-Sort b/Lang/J/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index c9563959dd..0000000000 --- a/Lang/J/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/J \ No newline at end of file diff --git a/Lang/Java/Bioinformatics-base-count b/Lang/Java/Bioinformatics-base-count deleted file mode 120000 index a3d5761560..0000000000 --- a/Lang/Java/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Java \ No newline at end of file diff --git a/Lang/Java/Meissel-Mertens-constant b/Lang/Java/Meissel-Mertens-constant deleted file mode 120000 index f7dce3ca3d..0000000000 --- a/Lang/Java/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Java \ No newline at end of file diff --git a/Lang/Java/Miller-Rabin-primality-test b/Lang/Java/Miller-Rabin-primality-test deleted file mode 120000 index 5708188da1..0000000000 --- a/Lang/Java/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Java \ No newline at end of file diff --git a/Lang/Java/Quaternion-type b/Lang/Java/Quaternion-type deleted file mode 120000 index 3cf154640d..0000000000 --- a/Lang/Java/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Java \ No newline at end of file diff --git a/Lang/Java/Sorting-Algorithms-Circle-Sort b/Lang/Java/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2c7141e7c3..0000000000 --- a/Lang/Java/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Java \ No newline at end of file diff --git a/Lang/JavaScript/Bioinformatics-base-count b/Lang/JavaScript/Bioinformatics-base-count deleted file mode 120000 index 033fba4ffa..0000000000 --- a/Lang/JavaScript/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Meissel-Mertens-constant b/Lang/JavaScript/Meissel-Mertens-constant deleted file mode 120000 index 8dd5c0b197..0000000000 --- a/Lang/JavaScript/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Miller-Rabin-primality-test b/Lang/JavaScript/Miller-Rabin-primality-test deleted file mode 120000 index 41f625032e..0000000000 --- a/Lang/JavaScript/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Quaternion-type b/Lang/JavaScript/Quaternion-type deleted file mode 120000 index e2a6535526..0000000000 --- a/Lang/JavaScript/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/JavaScript \ No newline at end of file diff --git a/Lang/Jq/Bioinformatics-base-count b/Lang/Jq/Bioinformatics-base-count deleted file mode 120000 index 87df406d18..0000000000 --- a/Lang/Jq/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Jq \ No newline at end of file diff --git a/Lang/Jq/Quaternion-type b/Lang/Jq/Quaternion-type deleted file mode 120000 index 36df977f17..0000000000 --- a/Lang/Jq/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Jq \ No newline at end of file diff --git a/Lang/Jq/Sorting-Algorithms-Circle-Sort b/Lang/Jq/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index acb625912d..0000000000 --- a/Lang/Jq/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Jq \ No newline at end of file diff --git a/Lang/Julia/Bioinformatics-base-count b/Lang/Julia/Bioinformatics-base-count deleted file mode 120000 index 37835d6558..0000000000 --- a/Lang/Julia/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Julia \ No newline at end of file diff --git a/Lang/Julia/Meissel-Mertens-constant b/Lang/Julia/Meissel-Mertens-constant deleted file mode 120000 index 24fa8f526c..0000000000 --- a/Lang/Julia/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Julia \ No newline at end of file diff --git a/Lang/Julia/Miller-Rabin-primality-test b/Lang/Julia/Miller-Rabin-primality-test deleted file mode 120000 index 1a7339a0d3..0000000000 --- a/Lang/Julia/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Julia \ No newline at end of file diff --git a/Lang/Julia/Quaternion-type b/Lang/Julia/Quaternion-type deleted file mode 120000 index 8a462d73ba..0000000000 --- a/Lang/Julia/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-Algorithms-Circle-Sort b/Lang/Julia/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index a8c5c2c2be..0000000000 --- a/Lang/Julia/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Julia \ No newline at end of file diff --git a/Lang/K/Empty-program b/Lang/K/Empty-program deleted file mode 120000 index f255a9c6f6..0000000000 --- a/Lang/K/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/K \ No newline at end of file diff --git a/Lang/Kotlin/Bioinformatics-base-count b/Lang/Kotlin/Bioinformatics-base-count deleted file mode 120000 index 998809c6ab..0000000000 --- a/Lang/Kotlin/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Miller-Rabin-primality-test b/Lang/Kotlin/Miller-Rabin-primality-test deleted file mode 120000 index 4a724f8c08..0000000000 --- a/Lang/Kotlin/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Quaternion-type b/Lang/Kotlin/Quaternion-type deleted file mode 120000 index a85b316d4c..0000000000 --- a/Lang/Kotlin/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-Algorithms-Circle-Sort b/Lang/Kotlin/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 74cde5ab2a..0000000000 --- a/Lang/Kotlin/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Kotlin \ No newline at end of file diff --git a/Lang/LSE/Empty-program b/Lang/LSE/Empty-program deleted file mode 120000 index 16856f6969..0000000000 --- a/Lang/LSE/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/LSE \ No newline at end of file diff --git a/Lang/Lambdatalk/Bioinformatics-base-count b/Lang/Lambdatalk/Bioinformatics-base-count deleted file mode 120000 index 03508c2431..0000000000 --- a/Lang/Lambdatalk/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Lambdatalk \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Miller-Rabin-primality-test b/Lang/Liberty-BASIC/Miller-Rabin-primality-test deleted file mode 120000 index 01eccc1a73..0000000000 --- a/Lang/Liberty-BASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Quaternion-type b/Lang/Liberty-BASIC/Quaternion-type deleted file mode 120000 index 33da9602b0..0000000000 --- a/Lang/Liberty-BASIC/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Logo/Associative-array-Creation b/Lang/Logo/Associative-array-Creation deleted file mode 120000 index 3776b1b4e9..0000000000 --- a/Lang/Logo/Associative-array-Creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Associative-array-Creation/Logo \ No newline at end of file diff --git a/Lang/Lua/Bioinformatics-base-count b/Lang/Lua/Bioinformatics-base-count deleted file mode 120000 index cb9548dcc8..0000000000 --- a/Lang/Lua/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Lua \ No newline at end of file diff --git a/Lang/Lua/Empty-program b/Lang/Lua/Empty-program deleted file mode 120000 index 451d4b192d..0000000000 --- a/Lang/Lua/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Lua \ No newline at end of file diff --git a/Lang/Lua/Miller-Rabin-primality-test b/Lang/Lua/Miller-Rabin-primality-test deleted file mode 120000 index 45a2ff22f4..0000000000 --- a/Lang/Lua/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Lua \ No newline at end of file diff --git a/Lang/Lua/Quaternion-type b/Lang/Lua/Quaternion-type deleted file mode 120000 index 09499b7f9c..0000000000 --- a/Lang/Lua/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-Algorithms-Circle-Sort b/Lang/Lua/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e6dc299d24..0000000000 --- a/Lang/Lua/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Lua \ No newline at end of file diff --git a/Lang/M2000-Interpreter/00-LANG.txt b/Lang/M2000-Interpreter/00-LANG.txt index 5e1cdf3a46..5d4d3cba07 100644 --- a/Lang/M2000-Interpreter/00-LANG.txt +++ b/Lang/M2000-Interpreter/00-LANG.txt @@ -471,4 +471,26 @@ M2000 Interpreter can work with Structures and Buffers. Buffer is a memory block \\ Print Eval(P, 0!x)=1212.12~, Eval(P, 0!y)=21.1212~ } -Kappa \ No newline at end of file +Kappa +Module Kappa { + Function Theta(x) { + Structure Points_single { + x as single + y as single + } + Buffer Clear Points as Points_single*x + =Points + } + P=Theta(100) + Print Len(P)=800 ' 2x4x100 bytes + ' new way to use fields of structure + P[0]|x=1212.12 + P[0]|y=21.1212 + Print Eval(P, 0!x)=1212.12~, Eval(P, 0!y)=21.1212~ + Print P[0]|x=1212.12~, P[0]|y=21.1212~ + P[4]=P[0] ' copy of structure at offser 4*len of structrure Points_single + ' p(0) is address of first struct, p(4) is address of 5th struct + Print P[4]|x=1212.12~, P[4]|y=21.1212~, p(4)-p(0)=32 +} +Kappa + \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Bioinformatics-base-count b/Lang/M2000-Interpreter/Bioinformatics-base-count deleted file mode 120000 index a75bd15fc5..0000000000 --- a/Lang/M2000-Interpreter/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Miller-Rabin-primality-test b/Lang/M2000-Interpreter/Miller-Rabin-primality-test deleted file mode 120000 index 70c84948c0..0000000000 --- a/Lang/M2000-Interpreter/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Quaternion-type b/Lang/M2000-Interpreter/Quaternion-type deleted file mode 120000 index 7027a86930..0000000000 --- a/Lang/M2000-Interpreter/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/M2000-Interpreter \ No newline at end of file diff --git a/Lang/M4/Empty-program b/Lang/M4/Empty-program deleted file mode 120000 index 3ce502532c..0000000000 --- a/Lang/M4/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/M4 \ No newline at end of file diff --git a/Lang/MATLAB/Bioinformatics-base-count b/Lang/MATLAB/Bioinformatics-base-count deleted file mode 120000 index 2622a73422..0000000000 --- a/Lang/MATLAB/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/MATLAB \ No newline at end of file diff --git a/Lang/ML-I/Empty-program b/Lang/ML-I/Empty-program deleted file mode 120000 index 48b06f2449..0000000000 --- a/Lang/ML-I/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/ML-I \ No newline at end of file diff --git a/Lang/Maple/Empty-program b/Lang/Maple/Empty-program deleted file mode 120000 index f9fceb04a1..0000000000 --- a/Lang/Maple/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Maple \ No newline at end of file diff --git a/Lang/Maple/Quaternion-type b/Lang/Maple/Quaternion-type deleted file mode 120000 index dc174952ef..0000000000 --- a/Lang/Maple/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Maple \ No newline at end of file diff --git a/Lang/Mathematica/Bioinformatics-base-count b/Lang/Mathematica/Bioinformatics-base-count deleted file mode 120000 index 986950c20f..0000000000 --- a/Lang/Mathematica/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Empty-program b/Lang/Mathematica/Empty-program deleted file mode 120000 index 7445caa973..0000000000 --- a/Lang/Mathematica/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Meissel-Mertens-constant b/Lang/Mathematica/Meissel-Mertens-constant deleted file mode 120000 index 8d1d0df59d..0000000000 --- a/Lang/Mathematica/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Miller-Rabin-primality-test b/Lang/Mathematica/Miller-Rabin-primality-test deleted file mode 120000 index 400d0fb0e3..0000000000 --- a/Lang/Mathematica/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Quaternion-type b/Lang/Mathematica/Quaternion-type deleted file mode 120000 index 700c56b146..0000000000 --- a/Lang/Mathematica/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-Algorithms-Circle-Sort b/Lang/Mathematica/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 9ff1fc78ae..0000000000 --- a/Lang/Mathematica/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/Meissel-Mertens-constant b/Lang/Maxima/Meissel-Mertens-constant deleted file mode 120000 index ea7cea2fda..0000000000 --- a/Lang/Maxima/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Miller-Rabin-primality-test b/Lang/Maxima/Miller-Rabin-primality-test deleted file mode 120000 index 331b953779..0000000000 --- a/Lang/Maxima/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Maxima \ No newline at end of file diff --git a/Lang/MelonBasic/Empty-program b/Lang/MelonBasic/Empty-program deleted file mode 120000 index 8fb3b62c73..0000000000 --- a/Lang/MelonBasic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/MelonBasic \ No newline at end of file diff --git a/Lang/Mercury/Miller-Rabin-primality-test b/Lang/Mercury/Miller-Rabin-primality-test deleted file mode 120000 index 6022def69b..0000000000 --- a/Lang/Mercury/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Quaternion-type b/Lang/Mercury/Quaternion-type deleted file mode 120000 index 34fd045795..0000000000 --- a/Lang/Mercury/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Mercury \ No newline at end of file diff --git a/Lang/MiniScript/Empty-program b/Lang/MiniScript/Empty-program deleted file mode 120000 index 60da45f9ae..0000000000 --- a/Lang/MiniScript/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/MiniScript \ No newline at end of file diff --git a/Lang/Modula-2/00-LANG.txt b/Lang/Modula-2/00-LANG.txt index 854aa29a1a..62faf6e14c 100644 --- a/Lang/Modula-2/00-LANG.txt +++ b/Lang/Modula-2/00-LANG.txt @@ -26,4 +26,11 @@ Modula-2 was designed by Niklaus Wirth at ETH Zurich as a systems implementation * [http://sourceforge.net/projects/schwarzerkaffee Schwarzer Kaffee] ==Modula-2 on IRC== -* [irc://irc.freenode.net/#modula-2 irc://irc.freenode.net/#modula-2] \ No newline at end of file +* [irc://irc.freenode.net/#modula-2 irc://irc.freenode.net/#modula-2] + +===See also=== +* [[Modula-3]] +* [[Oberon-07]] +* [[Oberon-2]] +* [[Component Pascal]] +* [[Zonnon]] \ No newline at end of file diff --git a/Lang/Modula-3/00-LANG.txt b/Lang/Modula-3/00-LANG.txt index 582f870540..aaa0f4b8bf 100644 --- a/Lang/Modula-3/00-LANG.txt +++ b/Lang/Modula-3/00-LANG.txt @@ -21,4 +21,11 @@ Its main implementation is [[Critical Mass Modula-3]]. Modula-3 influenced a few languages such as [[C Sharp|C#]], [[Java]], [[Ocaml]] and [[Python]]. ==Links== -* [http://en.wikipedia.org/wiki/Modula-3 Modula-3 at Wikipedia] \ No newline at end of file +* [http://en.wikipedia.org/wiki/Modula-3 Modula-3 at Wikipedia] + +===See also=== +* [[Modula-2]] +* [[Oberon-07]] +* [[Oberon-2]] +* [[Component Pascal]] +* [[Zonnon]] \ No newline at end of file diff --git a/Lang/Modula-3/Comments b/Lang/Modula-3/Comments deleted file mode 120000 index 8c3489c305..0000000000 --- a/Lang/Modula-3/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/Modula-3 \ No newline at end of file diff --git a/Lang/NS-HUBASIC/Empty-program b/Lang/NS-HUBASIC/Empty-program deleted file mode 120000 index 8edcb8591a..0000000000 --- a/Lang/NS-HUBASIC/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/NS-HUBASIC \ No newline at end of file diff --git a/Lang/Nickle/00-LANG.txt b/Lang/Nickle/00-LANG.txt index 53bb3afeae..e2643c2540 100644 --- a/Lang/Nickle/00-LANG.txt +++ b/Lang/Nickle/00-LANG.txt @@ -19,7 +19,7 @@ Other datatypes include multi-dimensional arrays, strings, structures, tagged un The reference implementation includes an interactive top level with byte code compilation before evaluation. Example: -/* Arrays to JSON */ +/* Arrays to JSON */ autoimport JSON; int [*] d = {1,2,3}; poly [*] p = {1, "abc", 42}; @@ -39,7 +39,8 @@ print f; for (int i = 0; i < dim(p); i++) { printf("%v ", p[i]); } -printf("\n"); +printf("\n"); + {{out}}
    prompt$ nickle sampler.5c
    diff --git a/Lang/Nim/Bioinformatics-base-count b/Lang/Nim/Bioinformatics-base-count
    deleted file mode 120000
    index 14fcd687ff..0000000000
    --- a/Lang/Nim/Bioinformatics-base-count
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Bioinformatics-base-count/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Meissel-Mertens-constant b/Lang/Nim/Meissel-Mertens-constant
    deleted file mode 120000
    index 760c7d7443..0000000000
    --- a/Lang/Nim/Meissel-Mertens-constant
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Meissel-Mertens-constant/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Miller-Rabin-primality-test b/Lang/Nim/Miller-Rabin-primality-test
    deleted file mode 120000
    index 1ce4ac13f6..0000000000
    --- a/Lang/Nim/Miller-Rabin-primality-test
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Miller-Rabin-primality-test/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Quaternion-type b/Lang/Nim/Quaternion-type
    deleted file mode 120000
    index 384e273bfc..0000000000
    --- a/Lang/Nim/Quaternion-type
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Quaternion-type/Nim
    \ No newline at end of file
    diff --git a/Lang/Nim/Sorting-Algorithms-Circle-Sort b/Lang/Nim/Sorting-Algorithms-Circle-Sort
    deleted file mode 120000
    index 80141c2866..0000000000
    --- a/Lang/Nim/Sorting-Algorithms-Circle-Sort
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Sorting-Algorithms-Circle-Sort/Nim
    \ No newline at end of file
    diff --git a/Lang/OCaml/Quaternion-type b/Lang/OCaml/Quaternion-type
    deleted file mode 120000
    index cc65de3875..0000000000
    --- a/Lang/OCaml/Quaternion-type
    +++ /dev/null
    @@ -1 +0,0 @@
    -../../Task/Quaternion-type/OCaml
    \ No newline at end of file
    diff --git a/Lang/Oberon-07/00-LANG.txt b/Lang/Oberon-07/00-LANG.txt
    index 3e769f71f7..fecc62a2b8 100644
    --- a/Lang/Oberon-07/00-LANG.txt
    +++ b/Lang/Oberon-07/00-LANG.txt
    @@ -13,4 +13,18 @@
     
     Oberon-07 contains a WHILE loop that allows multiple conditions and statements - similar to the loop in [[wp:Guarded_Command_Language|Edsgar Dijkstra's Guarded Command Language]], though with different syntax and without non-determinism. See [[Loops/N_plus_one_half#Oberon-07]] for an example.
     

    -In addition to the samples below, many of the [[Oberon-2]] samples should work with Oberon-07, particularly if the Oberon-07 compiler you are using allows LONGINT as a synonym for INTEGER (LONGINT, SHORTINT, LONGREAL and SHORTREAL were dropped from Oberon-07). \ No newline at end of file +In addition to the samples below, many of the [[Oberon-2]] samples should work with Oberon-07, particularly if the Oberon-07 compiler you are using allows LONGINT as a synonym for INTEGER (LONGINT, SHORTINT, LONGREAL and SHORTREAL were dropped from Oberon-07). + +==Tasks not implemented in Oberon-07== +[[Tasks not implemented in Oberon-07]] + +== Library modules used in Rosetta Code samples == +* [[:Category:Oberon-07-primes|Prime related]] +* [[:Category:Oberon-07-words|Word related]] + +== See also == +* [[Oberon-2]] +* [[Modula-2]] +* [[Modula-3]] +* [[Component Pascal]] +* [[Zonnon]] \ No newline at end of file diff --git a/Lang/Oberon/Even-or-odd b/Lang/Oberon/Even-or-odd deleted file mode 120000 index 02920c353c..0000000000 --- a/Lang/Oberon/Even-or-odd +++ /dev/null @@ -1 +0,0 @@ -../../Task/Even-or-odd/Oberon \ No newline at end of file diff --git a/Lang/Oberon/Loops-For-with-a-specified-step b/Lang/Oberon/Loops-For-with-a-specified-step deleted file mode 120000 index e73c849d2b..0000000000 --- a/Lang/Oberon/Loops-For-with-a-specified-step +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For-with-a-specified-step/Oberon \ No newline at end of file diff --git a/Lang/Objeck/Sorting-Algorithms-Circle-Sort b/Lang/Objeck/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 4475fe5763..0000000000 --- a/Lang/Objeck/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Objeck \ No newline at end of file diff --git a/Lang/Octave/Quaternion-type b/Lang/Octave/Quaternion-type deleted file mode 120000 index 6dec972e26..0000000000 --- a/Lang/Octave/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Octave \ No newline at end of file diff --git a/Lang/Odin/00-LANG.txt b/Lang/Odin/00-LANG.txt index 2c96551228..1a08002d21 100644 --- a/Lang/Odin/00-LANG.txt +++ b/Lang/Odin/00-LANG.txt @@ -1 +1,24 @@ -{{stub}}{{language|Odin}} \ No newline at end of file +{{language +|exec=machine +|gc=no +|safety=unsafe +|parampass=reference +|checking=static +|compat=nominative +|strength=strong +|site=https://odin-lang.org/ +|tag=odin +}}{{language programming paradigm|Imperative}}{{Codepad}} + +'''Odin''' is a general-purpose, [[procedural programming|procedural]], [[imperative programming|imperative]] programming language developed by [https://www.gingerbill.org/ gingerBill] as a "C alternative for the joy of programming". + +Odin is distributed under [https://github.com/odin-lang/Odin/blob/master/LICENSE zlib license]. + +==Links== +* [https://odin-lang.org/docs/install/ Compiler installation instructions] +* [https://github.com/odin-lang/Odin Repository] +* [https://odin-lang.org/docs/overview/ Language overview] +* [https://pkg.odin-lang.org/ Standard library documentation] + +==Todo== +[[Tasks_not_implemented_in_Odin]] \ No newline at end of file diff --git a/Lang/Oforth/Quaternion-type b/Lang/Oforth/Quaternion-type deleted file mode 120000 index 51caedda0e..0000000000 --- a/Lang/Oforth/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Oforth \ No newline at end of file diff --git a/Lang/Ol/Quaternion-type b/Lang/Ol/Quaternion-type deleted file mode 120000 index a3e712c033..0000000000 --- a/Lang/Ol/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Ol \ No newline at end of file diff --git a/Lang/OoRexx/00-LANG.txt b/Lang/OoRexx/00-LANG.txt index 8031f8ae00..84a3f74109 100644 --- a/Lang/OoRexx/00-LANG.txt +++ b/Lang/OoRexx/00-LANG.txt @@ -10,4 +10,7 @@ open sourced, maintained by the [http://www.rexxla.org/ Rexx Language Associatio ooRexx can be used to run many programs shown here in the [[REXX]] category. See http://rosettacode.org/wiki/Rosetta_Code:Village_Pump/Dialects#REXX.2C_ooRexx.2C_and_others -for differences. \ No newline at end of file +for differences. + +== Rosetta Code tasks not implemented in OoRexx == +[[Tasks not implemented in OoRexx]] \ No newline at end of file diff --git a/Lang/OoRexx/Quaternion-type b/Lang/OoRexx/Quaternion-type deleted file mode 120000 index be3652b55d..0000000000 --- a/Lang/OoRexx/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/OoRexx \ No newline at end of file diff --git a/Lang/Openscad/Empty-program b/Lang/Openscad/Empty-program deleted file mode 120000 index 89182791e6..0000000000 --- a/Lang/Openscad/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Openscad \ No newline at end of file diff --git a/Lang/Oz/Miller-Rabin-primality-test b/Lang/Oz/Miller-Rabin-primality-test deleted file mode 120000 index e6999d8858..0000000000 --- a/Lang/Oz/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Oz \ No newline at end of file diff --git a/Lang/PARI-GP/Empty-program b/Lang/PARI-GP/Empty-program deleted file mode 120000 index e5621857fc..0000000000 --- a/Lang/PARI-GP/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Meissel-Mertens-constant b/Lang/PARI-GP/Meissel-Mertens-constant deleted file mode 120000 index b03a10e2fd..0000000000 --- a/Lang/PARI-GP/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Miller-Rabin-primality-test b/Lang/PARI-GP/Miller-Rabin-primality-test deleted file mode 120000 index 6c17b6de21..0000000000 --- a/Lang/PARI-GP/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Quaternion-type b/Lang/PARI-GP/Quaternion-type deleted file mode 120000 index 87636fd8d1..0000000000 --- a/Lang/PARI-GP/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sorting-Algorithms-Circle-Sort b/Lang/PARI-GP/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2e42235ea5..0000000000 --- a/Lang/PARI-GP/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/00-LANG.txt b/Lang/PHP/00-LANG.txt index ad1d2b043d..894fa89337 100644 --- a/Lang/PHP/00-LANG.txt +++ b/Lang/PHP/00-LANG.txt @@ -13,4 +13,13 @@ '''PHP''' (PHP: Hypertext Preprocessor) is a [[reflective programming]] language originally designed for producing dynamic Web pages. PHP is used mainly in server-side application software, but can be used from a command line interface or in standalone graphical applications. ==Citations== -* [[wp:PHP|Wikipedia:PHP]] \ No newline at end of file +* [[wp:PHP|Wikipedia:PHP]] + +==External links== +=== Online compilers === +* [https://onlinephp.io/ PHP Sandbox - Execute PHP code online through your browser] (online compiler) +* [https://www.mycompiler.io/new/php Create a new PHP program - myCompiler - myCompiler] (online compiler) + +=== Tutorials and manuals === +* [https://www.w3schools.com/php/default.asp PHP Tutorial] on [https://www.w3schools.com www.w3schools.com] +* [https://www.geeksforgeeks.org/php/php-tutorial/ PHP Tutorial - GeeksforGeeks] \ No newline at end of file diff --git a/Lang/PHP/Miller-Rabin-primality-test b/Lang/PHP/Miller-Rabin-primality-test deleted file mode 120000 index bff04d1a83..0000000000 --- a/Lang/PHP/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PHP \ No newline at end of file diff --git a/Lang/PL-I/Quaternion-type b/Lang/PL-I/Quaternion-type deleted file mode 120000 index b86d406fec..0000000000 --- a/Lang/PL-I/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PL-I \ No newline at end of file diff --git a/Lang/Pascal/Bell-numbers b/Lang/Pascal/Bell-numbers deleted file mode 120000 index c4ab57da43..0000000000 --- a/Lang/Pascal/Bell-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bell-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Bioinformatics-base-count b/Lang/Pascal/Bioinformatics-base-count deleted file mode 120000 index 97aaee2dbb..0000000000 --- a/Lang/Pascal/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Brazilian-numbers b/Lang/Pascal/Brazilian-numbers deleted file mode 120000 index 152f3a22d2..0000000000 --- a/Lang/Pascal/Brazilian-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Brazilian-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Ethiopian-multiplication b/Lang/Pascal/Ethiopian-multiplication deleted file mode 120000 index 53e5b905d2..0000000000 --- a/Lang/Pascal/Ethiopian-multiplication +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ethiopian-multiplication/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Gamma-function b/Lang/Pascal/Gamma-function deleted file mode 120000 index f83dad18cb..0000000000 --- a/Lang/Pascal/Gamma-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Gamma-function/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Leap-year b/Lang/Pascal/Leap-year deleted file mode 120000 index 5eb674ed97..0000000000 --- a/Lang/Pascal/Leap-year +++ /dev/null @@ -1 +0,0 @@ -../../Task/Leap-year/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Prime-decomposition b/Lang/Pascal/Prime-decomposition deleted file mode 120000 index 7b392e005f..0000000000 --- a/Lang/Pascal/Prime-decomposition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Prime-decomposition/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sorting-Algorithms-Circle-Sort b/Lang/Pascal/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 3100a6716d..0000000000 --- a/Lang/Pascal/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Square-free-integers b/Lang/Pascal/Square-free-integers deleted file mode 120000 index 874a24625c..0000000000 --- a/Lang/Pascal/Square-free-integers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Square-free-integers/Pascal \ No newline at end of file diff --git a/Lang/PascalABC.NET/00-LANG.txt b/Lang/PascalABC.NET/00-LANG.txt index 48e9f6ce41..7f652b8be9 100644 --- a/Lang/PascalABC.NET/00-LANG.txt +++ b/Lang/PascalABC.NET/00-LANG.txt @@ -1,4 +1,4 @@ -{{language|PascalABC.NET}} +{{language|site=https://pascalabc.net/en/}} {{implementation|Pascal}} PascalABC.NET is the new generation Pascal programming language that combines simplicity of classic Pascal, a great number of modern extensions and broad capabilities of Microsoft .NET Framework. @@ -16,4 +16,5 @@ begin end. -{{unimpl_Page|PascalABC.NET}} \ No newline at end of file +==Tasks not implemented in PascalABC.NET== +[[Tasks not implemented in PascalABC.NET]] \ No newline at end of file diff --git a/Lang/PascalABC.NET/Bioinformatics-base-count b/Lang/PascalABC.NET/Bioinformatics-base-count deleted file mode 120000 index 8f0159ab8b..0000000000 --- a/Lang/PascalABC.NET/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Meissel-Mertens-constant b/Lang/PascalABC.NET/Meissel-Mertens-constant deleted file mode 120000 index 96e15ce1b8..0000000000 --- a/Lang/PascalABC.NET/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/PascalABC.NET \ No newline at end of file diff --git a/Lang/PascalABC.NET/Miller-Rabin-primality-test b/Lang/PascalABC.NET/Miller-Rabin-primality-test deleted file mode 120000 index 629803a659..0000000000 --- a/Lang/PascalABC.NET/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PascalABC.NET \ No newline at end of file diff --git a/Lang/Perl/Bioinformatics-base-count b/Lang/Perl/Bioinformatics-base-count deleted file mode 120000 index 38044107bd..0000000000 --- a/Lang/Perl/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Perl \ No newline at end of file diff --git a/Lang/Perl/Meissel-Mertens-constant b/Lang/Perl/Meissel-Mertens-constant deleted file mode 120000 index d5ec169595..0000000000 --- a/Lang/Perl/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Perl \ No newline at end of file diff --git a/Lang/Perl/Miller-Rabin-primality-test b/Lang/Perl/Miller-Rabin-primality-test deleted file mode 120000 index f2d8f376aa..0000000000 --- a/Lang/Perl/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Perl \ No newline at end of file diff --git a/Lang/Perl/Quaternion-type b/Lang/Perl/Quaternion-type deleted file mode 120000 index 6c26830ce6..0000000000 --- a/Lang/Perl/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Perl \ No newline at end of file diff --git a/Lang/Perl/Sorting-Algorithms-Circle-Sort b/Lang/Perl/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index dec6111fc4..0000000000 --- a/Lang/Perl/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Perl \ No newline at end of file diff --git a/Lang/Phix/00-LANG.txt b/Lang/Phix/00-LANG.txt index cbc88ce28e..7a127fa93c 100644 --- a/Lang/Phix/00-LANG.txt +++ b/Lang/Phix/00-LANG.txt @@ -11,13 +11,13 @@ |LCT=yes |bnf=http://phix.x10.mx/bnf.php }} -Phix is a self-hosted hybrid interpreter/compiler, developed by Pete Lomax. It is very easy to use, and similar to -[https://rosettacode.org/wiki/Category:Euphoria Euphoria]. +Phix is a self-hosted hybrid interpreter/compiler, developed by Pete Lomax.
    + -On [https://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity/Full_list?oldid=294533 26th December 2021, Phix became the first programming language on this site to have submissions for 100% of all tasks].
    -(On 20th June 2022 [[Wren]] became the second, albeit with [https://www.rosettacode.org/wiki/Category:WrenGo 13]+[https://rosettacode.org/wiki/Special:Search?search=wren.h&wprov=acrw1_-1 66] of those embedded that I, for one, have been unable to run.) +On 26th December 2021, Phix became the first language on this site to have [https://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity/Full_list?oldid=294533 submissions for 100%] of all tasks.
    +(On 20th June 2022 [[Wren]] became the second, albeit there are [https://www.rosettacode.org/wiki/Category:WrenGo 13]+[https://rosettacode.org/wiki/Special:Search?search=wren.h&wprov=acrw1_-1 66] of those I have never been able to run.) -[http://phix.x10.mx/download.php A simple 30MB download] contains a pre-compiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in under 20 seconds. The download also contains a full-featured programmer's editor and about 1000 demo programs. +[http://phix.x10.mx/download.php A simple 30MB download] contains a pre-compiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in under 20 seconds. The download also contains a full-featured programmer's editor and about 1000 demos. You can also [https://replit.com/@PeteLomax1/PhixInterpreter#main.sh run Phix on replit here] (1.0.3 Lnx 64 bit), and several manually transpiled and uploaded entries [https://rosettacode.org/wiki/Category:Phix/online here] diff --git a/Lang/Phix/Bioinformatics-base-count b/Lang/Phix/Bioinformatics-base-count deleted file mode 120000 index 88d72c5b75..0000000000 --- a/Lang/Phix/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Phix \ No newline at end of file diff --git a/Lang/Phix/Meissel-Mertens-constant b/Lang/Phix/Meissel-Mertens-constant deleted file mode 120000 index a9b8084fb5..0000000000 --- a/Lang/Phix/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Phix \ No newline at end of file diff --git a/Lang/Phix/Miller-Rabin-primality-test b/Lang/Phix/Miller-Rabin-primality-test deleted file mode 120000 index 440728dd57..0000000000 --- a/Lang/Phix/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Phix \ No newline at end of file diff --git a/Lang/Phix/Quaternion-type b/Lang/Phix/Quaternion-type deleted file mode 120000 index bae473b66e..0000000000 --- a/Lang/Phix/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Phix \ No newline at end of file diff --git a/Lang/Phix/Sorting-Algorithms-Circle-Sort b/Lang/Phix/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 2aea38718d..0000000000 --- a/Lang/Phix/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Phix \ No newline at end of file diff --git a/Lang/Picat/Bioinformatics-base-count b/Lang/Picat/Bioinformatics-base-count deleted file mode 120000 index c724eb719d..0000000000 --- a/Lang/Picat/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Picat \ No newline at end of file diff --git a/Lang/Picat/Quaternion-type b/Lang/Picat/Quaternion-type deleted file mode 120000 index e15dda2aeb..0000000000 --- a/Lang/Picat/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Picat \ No newline at end of file diff --git a/Lang/PicoLisp/Bioinformatics-base-count b/Lang/PicoLisp/Bioinformatics-base-count deleted file mode 120000 index a4931ebf04..0000000000 --- a/Lang/PicoLisp/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Miller-Rabin-primality-test b/Lang/PicoLisp/Miller-Rabin-primality-test deleted file mode 120000 index eae524ec57..0000000000 --- a/Lang/PicoLisp/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Quaternion-type b/Lang/PicoLisp/Quaternion-type deleted file mode 120000 index 2120681801..0000000000 --- a/Lang/PicoLisp/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PicoLisp \ No newline at end of file diff --git a/Lang/Pike/Miller-Rabin-primality-test b/Lang/Pike/Miller-Rabin-primality-test deleted file mode 120000 index 2cc78451b0..0000000000 --- a/Lang/Pike/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Pike \ No newline at end of file diff --git a/Lang/Plain-English/00-LANG.txt b/Lang/Plain-English/00-LANG.txt index be0ed94cc3..b52aba7348 100644 --- a/Lang/Plain-English/00-LANG.txt +++ b/Lang/Plain-English/00-LANG.txt @@ -88,10 +88,10 @@ Intel $8B85080000008B008B9D0C0000000103. And yes, that is 80x86 machine code in Intel hex format. It decompiles to -mov eax, [ebp+8] ; $8B8508000000 -> load the current stack address + 8 into the accumulator -mov eax, [eax] ; $8B00 -> load memory pointed to by accumulator into accumulator -mov ebx, [ebp+12] ; $8B9D0C000000-> load the current stack address + 12 into working register -add [ebx],eax ; $0103 -> add accumulator to memory pointed to by working register +mov eax, [ebp+8] ; $8B8508000000 -> Load the value at (EBP + 8) into EAX (1st function argument) +mov eax, [eax] ; $8B00 -> Dereference EAX (load the value from the address stored in EAX) +mov ebx, [ebp+12] ; $8B9D0C000000-> Load the value at (EBP + 12) into EBX (2nd function argument) +add [ebx],eax ; $0103 -> Add EAX to the value stored at the address in EBX So the language has stacked pointers (all parameters are passed by reference) to the two numbers via a number to another number and then it calls this code which gets the first number, and adds it to the second. Hopefully this example shows how high level and low level Plain English is at the same time. @@ -251,4 +251,212 @@ https://forums.parallax.com/discussion/163792/plain-english-programming a long r * [https://forums.parallax.com/discussion/163792/plain-english-programming Plain English Programming] ==Todo== -[[Reports:Tasks_not_implemented_in_PlainEnglish]] \ No newline at end of file +[[Reports:Tasks_not_implemented_in_PlainEnglish]] + +=Plain English Sources= +[https://en.WikipediA.org/wiki/Integrated_development_environment IDE] +and Compiler. +==Creators== +* Gerry Rzeppa (Father) +[https://www.quora.com/profile/Gerry-Rzeppa Quora Profile] +[https://www.linkedin.com/in/gerry-rzeppa-17b8051b/ LinkedIn Profile] +[https://twitter.com/gerryrzeppa Twitter Profile] +[https://github.com/GerryRzeppa GitHub Profile] +* Dan Rzeppa (Son) +[https://github.com/danrzeppa GitHub Profile] + +==Contributors== +* Elender Góis Gallas (Plain Portuguese Creator) +[https://www.quora.com/profile/Elender-G%C3%B3is-Gallas-%E3%82%A8%E3%83%AC%E3%83%B3%E3%83%87-%E3%82%AC%E3%83%A9%E3%82%B9 Quora Profile] +[https://www.linkedin.com/in/elender/ LinkedIn Profile] +[https://twitter.com/elenderg Twitter Profile] +[https://github.com/elenderg GitHub Profile] +* Pablo Cayuela (Plain Spanish Creator) +[https://www.linkedin.com/in/pablo-cayuela-a42b019/ LinkedIn Profile] + +==Copyright Owner== +* The Osmosian Order +** [http://www.Osmosian.com/ The Osmosian Order of Plain English Programmers] Brochure +*** [http://www.osmosian.com/manifesto.pdf The Osmosian Manifesto] +** [https://OsmosianPlainEnglishProgramming.blog/ Wordpress Blog]
    In chronological order: +*** 2018 +**** 05 +***** 01 [https://OsmosianPlainEnglishProgramming.blog/2018/05/01/a-solution-to-the-fatal-flaw-in-relational-database-systems/ A Solution to the Fatal Flaw in Relational Database Systems] +***** 02 [https://OsmosianPlainEnglishProgramming.blog/2018/05/02/plain-english-programming-fractal-forests/ Fractal Forests] +***** 02 [https://OsmosianPlainEnglishProgramming.blog/2018/05/02/plain-english-programming-is-a-picture-worth-1000-words/ Plain English Programming — Is a Picture Worth 1000 Words?] +***** 03 [https://OsmosianPlainEnglishProgramming.blog/2018/05/03/plain-english-programming-robotics/ Robotics] +***** 03 [https://OsmosianPlainEnglishProgramming.blog/2018/05/03/plain-english-programming-a-wysiwyg-document-editor/ A WYSIWYG Document Editor] +***** 04 [https://OsmosianPlainEnglishProgramming.blog/2018/05/04/plain-english-programming-musings-on-the-a-in-ai/ Musings on the “A” in “AI”] +***** 04 [https://OsmosianPlainEnglishProgramming.blog/2018/05/04/plain-english-programming-a-simple-merge-sort/ Robotics] +***** 05 [https://OsmosianPlainEnglishProgramming.blog/2018/05/05/plain-english-programming-smoothing-polygons/ Plain English Programming — Smoothing Polygons] +***** 05 [https://OsmosianPlainEnglishProgramming.blog/2018/05/05/plain-english-programming-kobayashi-maru-primes/ Kobayashi Maru Primes] +***** 06 [https://OsmosianPlainEnglishProgramming.blog/2018/05/06/plain-english-programming-nested-ifs/ Plain English Programming — Nested IFs] +***** 06 [https://OsmosianPlainEnglishProgramming.blog/2018/05/06/plain-english-programming-the-malevolent-mathemagician/ Plain English Programming — The Malevolent Mathemagician] +***** 07 [https://OsmosianPlainEnglishProgramming.blog/2018/05/07/plain-english-programming-parsing-with-riders/ Parsing with Riders] +***** 07 [https://OsmosianPlainEnglishProgramming.blog/2018/05/07/plain-english-programming-jackson-pollocks-alphabet-soup/ Plain English Programming — Jackson Pollock’s Alphabet Soup] +***** 08 [https://OsmosianPlainEnglishProgramming.blog/2018/05/08/plain-english-programming-random-numbers/ Random Numbers] +***** 08 [https://OsmosianPlainEnglishProgramming.blog/2018/05/08/plain-english-programming-sierpinski-koch/ Sierpinski & Koch] +***** 09 [https://OsmosianPlainEnglishProgramming.blog/2018/05/09/plain-english-programming-the-travelling-salesman/ The Travelling Salesman] +***** 09 [https://OsmosianPlainEnglishProgramming.blog/2018/05/09/plain-english-programming-a-jigsaw-puzzle/ A Jigsaw Puzzle] +***** 10 [https://OsmosianPlainEnglishProgramming.blog/2018/05/10/plain-english-programming-anagrams/ Anagrams] +***** 11 [https://OsmosianPlainEnglishProgramming.blog/2018/05/11/plain-english-programming-the-amazing-multimaze/ The Amazing MultiMaze] +***** 12 [https://OsmosianPlainEnglishProgramming.blog/2018/05/12/plain-english-programming-painting-like-monet/ Painting Like Monet] +***** 13 [https://OsmosianPlainEnglishProgramming.blog/2018/05/13/plain-english-programming-bresenhams-circle-drawing-algorithm/ Bresenham’s Circle Drawing Algorithm] +***** 14 [https://OsmosianPlainEnglishProgramming.blog/2018/05/14/plain-english-programming-hiding-in-plain-sight/ Hiding in Plain Sight] +***** 14 [https://OsmosianPlainEnglishProgramming.blog/2018/05/14/plain-english-programming-sudoku-solver/ Sudoku Solver] +***** 15 [https://OsmosianPlainEnglishProgramming.blog/2018/05/15/plain-english-programming-teaching-kids/ Teaching Kids to Program] +***** 16 [https://OsmosianPlainEnglishProgramming.blog/2018/05/16/the-journey-begins/ Plain English Programming] +==IDE including Compiler== +===Creator supplied=== +*[http://www.osmosian.com/cal-3040.zip cal-3040] 2006/08/14 +**[http://www.osmosian.com/ebnf EBNF] +**[http://www.osmosian.com/instructions.pdf instructions] +*[http://www.osmosian.com/cal-4700.zip cal-4700] 2017/01/27 + +===GitHub=== +*[https://GitHub.com/GerryRzeppa/osmosian /GerryRzeppa/osmosian] cal-3040 +*[https://GitHub.com/Folds/osmosian /Folds/osmosian] cal-3040 (Unauthorized) +*[https://GitHub.com/elenderg/Portugues-Puro /elenderg/Portugues-Puro] cal-4700 Translated to Portuguese + +==Forums== +===[https://www.AnandTech.com/ AnandTech]=== +*[https://forums.anandtech.com/threads/natural-language-programming.2358744/ Natural Language Programming: Good Idea? Yes Maybe No] +*[https://forums.anandtech.com/threads/conversational-storytelling-with-javascript.2410448/ Conversational Storytelling with JavaScript] +*[https://forums.anandtech.com/threads/natural-language-programming-english-and-or-español.2559516/ Natural Language Programming -- English and/or Español] +*[https://forums.anandtech.com/threads/learning-programming.2406202/#post-36858285 Learning programming] +*[https://forums.anandtech.com/threads/official-free-tools-thread.199156/page-4#post-36861957 Official Free Tools Thread | Plain English contribution] +*[https://news.yCombinator.com/item?id=8719957 Plain English Programming (2013)] +*[https://news.yCombinator.com/item?id=19355965 Do You Approve the Plain English?] +===[https://Forum.Arduino.cc/ Arduino]=== +*[https://forum.arduino.cc/t/plain-english-programming/371096/15 Plain English Programming] +===[https://groups.google.com/g/comp.compilers/ comp.compilers]=== +*[https://groups.google.com/g/comp.compilers/c/p30I_zVRlps/m/9UshbYjqZzwJ Writing A Plain English Compiler] +*[https://groups.google.com/g/comp.compilers/c/4t3_Dq6foFA/m/CYfdnKMBkAsJ Re: A Plain English Compiler] +===[https://www.GeeksForGeeks.org/ GeeksForGeeks]=== +*[https://www.geeksforgeeks.org/the-malevolent-mathemagician-natural-language-programming/ The Malevolent Mathemagician | Natural Language Programming] +*[https://www.geeksforgeeks.org/creating-wysiwyg-document-editor/ Creating WYSIWYG Document Editor | Natural Language Programming] +*[https://www.geeksforgeeks.org/a-kobayashi-maru-approach-to-finding-primes/ A Kobayashi Maru Approach to Finding Primes] +*[https://www.geeksforgeeks.org/natural-language-programming-sorting/ Sorting | Natural Language Programming] +*[https://www.geeksforgeeks.org/natural-language-programming-teaching-kids/ Natural Language Programming — Teaching Kids] +*[https://www.geeksforgeeks.org/natural-language-programming/ Natural Language Programming] +===[https://IntFiction.org/ Interactive Fiction Community Forum]=== +*[https://intfiction.org/t/writer-wanted-for-a-conversational-storytelling-project/6169 Writer wanted for a “Conversational Storytelling” project] +*[https://intfiction.org/t/inform-system-developers-do-you-approve-the-plain-english-programming/42213 Inform system developers, do you approve the Plain English Programming?] +===[https://Forums.Parallax.com/ Parallax Forums]=== +*[https://forums.parallax.com/discussion/163792/plain-english-programming Plain English Programming] +===[https://www.PC-Control.co.uk/ PC Control Limited]=== +*[https://www.pc-control.co.uk/control/articles/article10.php Automated Maze solver using a servo hawk] +**[https://www.pc-control.co.uk/control/articles/images/photo%2009%20-%20definitions.png photo 09 - definitions] +**[https://www.pc-control.co.uk/control/articles/images/photo%2010%20-%20low-level%20helper%20routines.png photo 10 - low-level helper routines] +**[https://www.pc-control.co.uk/control/articles/images/photo%2011%20-%20mid-level%20helper%20routines.png photo 11 - mid-level helper routines] +**[https://www.pc-control.co.uk/control/articles/images/photo%2012%20-%20high-level%20helper%20routines.png photo 12 - high-level helper routines] +**[https://www.pc-control.co.uk/control/articles/images/photo%2013%20-%20main%20routine.png photo 13 - main routine] +**[https://www.pc-control.co.uk/control/articles/images/photo%2014%20-%20terminal%20output.png photo 14 - terminal output] +===[https://www.Quora.com/ Quora]=== +*Jul 06, 2021 - [https://www.quora.com/What-can-a-beginner-programmer-use-as-a-programming-IDE-I-tried-using-Visual-Studio-Express-but-it-was-too-hard-to-use-and-understand-Is-there-anything-else-I-can-use/answer/Gerry-Rzeppa What can a beginner programmer use as a programming IDE? I tried using Visual Studio Express but it was too hard to use and understand. Is there anything else I can use?] +**"To get started with Plain English, see here (it’s fast, friendly, and free):" +**Reference to another Gerry Rzeppa Quora article: Jun 27, 2021 - [https://www.quora.com/Is-there-a-right-way-to-learn-to-code-1/answer/Gerry-Rzeppa Is there a right way to learn to code?] +*Jul 06, 2021 - [https://www.quora.com/How-often-when-puzzling-out-a-solution-to-a-problem-do-you-think-or-say-aloud-Are-we-asking-the-right-question-questions/answer/Gerry-Rzeppa How often when puzzling out a solution to a problem, do you think or say aloud, “Are we asking the right question/questions?”] +**"Almost every time." +**Reference to another Gerry Rzeppa Quora article: May 11, 2021 [https://www.quora.com/What-IDE-has-impressed-you-with-its-ease-of-use-and-how-productive-were-you-with-it/answer/Gerry-Rzeppa What IDE has impressed you with its ease of use, and how productive were you with it?] +*Jul 06, 2021 - [https://www.quora.com/What-are-the-best-examples-of-poetry-written-in-programming-languages/answer/Gerry-Rzeppa What are the best examples of poetry written in programming languages?] +**A poem written in Plain English that, when run, makes the picture the poem describes. +*Jul 05, 2021 - [https://www.quora.com/What-is-the-character-limit-for-one-line-of-code-you-go-by/answer/Gerry-Rzeppa What is the character limit for one line of code you go by?] +**"... if handwritten code fits on the screen, it’s okay by me." +*Jul 05, 2021 - [https://www.quora.com/How-is-a-one-dimensional-character-array-and-a-string-similar/answer/Gerry-Rzeppa How is a one-dimensional character array and a string similar?] + +**Strings +**Substrings +**String Riders +*Jun 27, 2021 - [https://www.quora.com/Is-there-a-right-way-to-learn-to-code-1/answer/Gerry-Rzeppa Is there a right way to learn to code?] +**A offering of the Plain English IDE and personal tutoring. +*Jun 10, 2021 - [https://www.quora.com/Is-there-any-way-to-write-genuine-self-modifying-code-in-Windows/answer/Gerry-Rzeppa Is there any way to write genuine self-modifying code in Windows?] + +**Memory Map +**Memory Pointers +*Jun 10, 2021 - [https://www.quora.com/How-can-I-write-a-Python-program-where-a-bunch-of-students-will-be-assigned-thesis-themes-using-the-FIFO-method/answer/Gerry-Rzeppa How can I write a Python program where a bunch of students will be assigned thesis themes using the FIFO method?] +** Use of path variable. +** Iterative development. +** Relation of item in a list and the name of the list. +** Screen space management. +** Use of "backwards". +*Jun 09, 2021 - [https://www.quora.com/How-do-computers-execute-if-statements-to-the-core-machine-code-and-opcodes/answer/Gerry-Rzeppa How do computers execute if statements to the core machine code and opcodes?] + +** List command and explanation of display produced +** Memory Map +** Uses [https://defuse.ca/online-x86-assembler.htm Online x86 and x64 Intel Instruction Assembler] to disassemble code in the List output. +** Offers free “How to Write a Plain English Compiler in Plain English” course via email. +*Jun 08, 2021 - [https://www.quora.com/How-can-I-draw-the-flag-of-a-country-in-C-beginner/answer/Gerry-Rzeppa How can I draw the flag of a country in C#? (beginner)] +** Make a box +** Center the box +** Draw and fill the box +** Stroke +*Jun 07, 2021 - [https://www.quora.com/Is-it-wise-to-ask-query-like-why-curly-braces-are-preferred-in-C-instead-of-opening-and-closing-bracket-when-writing-functions-or-we-just-need-to-memorize-that-as-a-random-rule-Is-there-any-book-which-deals-with/answer/Gerry-Rzeppa Is it wise to ask query like why curly braces are preferred in C instead of opening and closing bracket when writing functions, or we just need to memorize that as a random rule? Is there any book which deals with such miscellaneous things about C?] +** “Arbitrary and unnecessary rule” +*Jun 06, 2021 - [https://www.quora.com/How-would-I-go-about-creating-dots-and-boxes-in-Java/answer/Gerry-Rzeppa How would I go about creating dots and boxes in Java?] +*Jun 06, 2021 - [https://www.quora.com/How-can-I-write-a-menu-driven-program-to-perform-following-operations-on-the-stack-using-array-a-i-Push-ii-Pop-iii-Peek/answer/Gerry-Rzeppa How can I write a menu-driven program to perform the following operations on the stack using array- a (i) Push (ii) Pop (iii) Peek?] +*Jun 06, 2021 - [https://www.quora.com/How-do-I-make-a-countdown-and-when-it-finishes-it-shows-a-text-in-coding-I-want-to-add-a-picture-as-a-border-or-what-else-to-countdown/answer/Gerry-Rzeppa How do I make a countdown and when it finishes, it shows a text in coding? I want to add a picture as a border or what else to countdown.] +*Jun 06, 2021 - [https://www.quora.com/What-is-recursion-Can-you-explain-the-main-principles-of-recursions-Can-you-do-the-code-algorithm-of-the-Fibonacci-series-using-recursion/answer/Gerry-Rzeppa What is recursion? Can you explain the main principles of recursions? Can you do the code/algorithm of the Fibonacci series using recursion?] +*Jun 06, 2021 - [https://www.quora.com/How-do-you-find-the-intersection-point-between-a-line-and-a-rectangle-algorithm-geometry-line-intersection-development/answer/Gerry-Rzeppa What is recursion? How do you find the intersection point between a line and a rectangle (algorithm, geometry, line, intersection, development)?] +*Jun 06, 2021 - [https://www.quora.com/How-do-you-handle-algorithms-to-create-polygons-no-Thiesen-Voronoi-Python-Shapely-Voronoi-development/answer/Gerry-Rzeppa How do you handle algorithms to create polygons (no Thiesen/Voronoi) (Python, Shapely, Voronoi, development)?] +*Jun 04, 2021 - [https://www.quora.com/I-want-to-get-into-programming-What-languages-should-I-learn-first/answer/Gerry-Rzeppa I want to get into programming. What languages should I learn first?] +*Jun 04, 2021 - [https://www.quora.com/How-do-I-make-a-programme-using-codes/answer/Gerry-Rzeppa How do I make a programme using codes?] +*Jun 04, 2021 - [https://www.quora.com/Why-is-Hello-World-the-default-line-in-programming-languages/answer/Gerry-Rzeppa Why is "Hello World" the default line in programming languages?] +*Jun 04, 2021 - [https://www.quora.com/Why-cant-I-find-any-real-photo-of-a-compiler-Is-it-too-small/answer/Gerry-Rzeppa Why can't I find any real photo of a compiler? Is it too small?] +*Jun 03, 2021 - [https://www.quora.com/Why-must-the-starting-value-of-a-control-variable-be-less-than-the-ending-value-in-a-for-loop-expression/answer/Gerry-Rzeppa Why must the starting value of a control variable be less than the ending value in a for loop expression?] +*Jun 03, 2021 - [https://www.quora.com/What-is-the-purpose-of-initialization-of-counter-variable-in-a-loop/answer/Gerry-Rzeppa What is the purpose of "initialization of counter variable" in a loop?] +*Jun 03, 2021 - [https://www.quora.com/What-is-the-nature-of-a-variable-with-real-life-examples/answer/Gerry-Rzeppa What is the nature of a variable with real life examples?] +*Jun 03, 2021 - [https://www.quora.com/Why-is-UML-a-significant-area-of-study/answer/Gerry-Rzeppa Why is UML a significant area of study?] +*May 29, 2021 [https://www.quora.com/Is-it-easier-to-write-an-interpreter-than-a-compiler-Why/answer/Gerry-Rzeppa Is it easier to write an interpreter than a compiler? Why?] +**"Yes. An interpreter can be written with less knowledge of the hardware and operating system." +**Reference to another Gerry Rzeppa Quora article: May 18, 2021 [https://www.quora.com/How-do-I-make-programming-language/answer/Gerry-Rzeppa How do I make programming language?] +*May 18, 2021 [https://www.quora.com/How-do-I-make-programming-language/answer/Gerry-Rzeppa How do I make programming language?] +**Reference to another Gerry Rzeppa Quora article: Dec 22, 2020 [https://www.quora.com/How-do-you-start-writing-your-interpreter-from-scratch/answer/Gerry-Rzeppa How do you start writing your interpreter from scratch?] +**Reference to another Gerry Rzeppa Quora article: Aug 30, 2020 [https://www.quora.com/What-is-a-compiler-and-the-stages-of-a-compiler/answer/Gerry-Rzeppa What is a compiler and the stages of a compiler?] +*May 11, 2021 [https://www.quora.com/What-IDE-has-impressed-you-with-its-ease-of-use-and-how-productive-were-you-with-it/answer/Gerry-Rzeppa What IDE has impressed you with its ease of use, and how productive were you with it?] +*Apr 28, 2021 - [https://www.quora.com/I-need-some-good-project-related-to-data-structure-I-am-a-2rd-year-computer-science-student-What-is-your-suggestion/answer/Gerry-Rzeppa I need some good project related to data structure. I am a 2rd year computer science student. What is your suggestion?] + +**Data types +***Fundamental +****byte +****record +***Pointers +****Generic +****Typed +***Strings +***Things +****Stacks +****Queues +****Hashed Indices +**Memory Map +**WYSIWYG document editor +*Apr 12, 2021 - [https://www.quora.com/What-is-the-relationship-between-a-compiler-algorithm-and-data-structure/answer/Gerry-Rzeppa What is the relationship between a compiler, algorithm, and data structure?] +** "A compiler uses data structures and algorithms to translate high-level source code into low-level executable machine code." +** Discussion of the Plain English compiler +*Mar 29, 2021 - [https://www.quora.com/What-is-the-most-interesting-Python-algorithm-in-less-than-ten-lines-of-code/answer/Gerry-Rzeppa What is the most interesting Python algorithm in less than ten lines of code?] +**Lindenmayer interpreter +*Mar 27, 2021 - [https://www.quora.com/What-is-the-best-way-to-present-an-algorithm/answer/Gerry-Rzeppa What is the best way to present an algorithm?] +**Three-step process +*Mar 24, 2021 - [https://www.quora.com/Why-is-it-hard-to-understand-linked-lists-in-programming/answer/Gerry-Rzeppa Why is it hard to understand linked lists in programming?] +**Discuss Plain English linked list. +*Dec 22, 2020 [https://www.quora.com/How-do-you-start-writing-your-interpreter-from-scratch/answer/Gerry-Rzeppa How do you start writing your interpreter from scratch?] +** “primitive” BASIC editor/interpreter +*Oct 03, 2020 - [https://www.quora.com/In-procedural-programming-how-do-you-plan-your-code-without-UML/answer/Gerry-Rzeppa In procedural programming, how do you plan your code without UML?] +**Osmosian maxim: “If it’s hard, it’s wrong.” +**Pair Programming +**"During the winter of 2005-2006, we wrote (and documented) 25,000 lines of Plain English code in just six months ..." +**'“Just tell us what you need, sonny, and we’ll show you how to live without it.”' +*Aug 30, 2020 [https://www.quora.com/What-is-a-compiler-and-the-stages-of-a-compiler/answer/Gerry-Rzeppa What is a compiler and the stages of a compiler?] +**Structure of the Plain English compiler. +*Jul 09, 2020 - [https://www.quora.com/Who-can-print-this-string-Hello-world-more-smartly-and-clearly/answer/Gerry-Rzeppa Who can print this string "Hello world" more smartly and clearly?] +**Plain English program to print in a circle. +**Español Llano (Plain Spanish) program to print in a circle. +*Jun 08, 2020 - [https://www.quora.com/Why-do-some-programmers-write-their-own-compilers/answer/Gerry-Rzeppa Why do some programmers write their own compilers?] +**'My elder son and I wrote our own Plain English compiler and IDE, in Plain English, originally, for three reasons. We wanted to know:' +***'1. Is it easier to program when you don’t have to translate your natural-language thoughts into an alternate syntax?' +***'2. Can natural languages be parsed in a relatively “sloppy” manner (as humans apparently parse them) and still provide a stable enough environment for productive programming?' +***'3. Can low-level programs (like compilers) be conveniently and efficiently written in high level languages (like English)? +**'Turns out the answers to all of three questions is, “Yes!”' + +==Successor Project (Trial)== +*[https://www.indiegogo.com/projects/the-hybrid-programming-language#/ The Hybrid Programming Language] - Plain English with snippets of formulas and graphics where needed \ No newline at end of file diff --git a/Lang/Pluto/00-LANG.txt b/Lang/Pluto/00-LANG.txt index debf9ec69a..80e65c9293 100644 --- a/Lang/Pluto/00-LANG.txt +++ b/Lang/Pluto/00-LANG.txt @@ -31,6 +31,12 @@ Here is a list of custom libraries used on Rosetta Code: |- |13 || [[:Category:Pluto-uchar|uchar]] || 14 || [[:Category:Pluto-gchar|gchar]] |- +|15 || [[:Category:Pluto-matrix|matrix]] || 16 || [[:Category:Pluto-poly|poly]] +|- +|17 || [[:Category:Pluto-audio|audio]] || 18 || [[:Category:Pluto-bitmap|bitmap]] +|- +|19 || [[:Category:Pluto-lsystem|lsystem]] || 20 || [[:Category:Pluto-bignum|bignum]] +|- |} == To do == diff --git a/Lang/PowerShell/Quaternion-type b/Lang/PowerShell/Quaternion-type deleted file mode 120000 index 60f8156bec..0000000000 --- a/Lang/PowerShell/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PowerShell \ No newline at end of file diff --git a/Lang/Prolog/Miller-Rabin-primality-test b/Lang/Prolog/Miller-Rabin-primality-test deleted file mode 120000 index 77f0bc56fd..0000000000 --- a/Lang/Prolog/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Quaternion-type b/Lang/Prolog/Quaternion-type deleted file mode 120000 index 458f5f70bc..0000000000 --- a/Lang/Prolog/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Prolog \ No newline at end of file diff --git a/Lang/PureBasic/Bioinformatics-base-count b/Lang/PureBasic/Bioinformatics-base-count deleted file mode 120000 index 16be5f27be..0000000000 --- a/Lang/PureBasic/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Meissel-Mertens-constant b/Lang/PureBasic/Meissel-Mertens-constant deleted file mode 120000 index 81f0bd26b3..0000000000 --- a/Lang/PureBasic/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Miller-Rabin-primality-test b/Lang/PureBasic/Miller-Rabin-primality-test deleted file mode 120000 index af69162304..0000000000 --- a/Lang/PureBasic/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Quaternion-type b/Lang/PureBasic/Quaternion-type deleted file mode 120000 index 6551ed8e89..0000000000 --- a/Lang/PureBasic/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/PureBasic \ No newline at end of file diff --git a/Lang/Python/Bioinformatics-base-count b/Lang/Python/Bioinformatics-base-count deleted file mode 120000 index 7f8a0873e8..0000000000 --- a/Lang/Python/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Python \ No newline at end of file diff --git a/Lang/Python/Meissel-Mertens-constant b/Lang/Python/Meissel-Mertens-constant deleted file mode 120000 index 04fd530b92..0000000000 --- a/Lang/Python/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Python \ No newline at end of file diff --git a/Lang/Python/Miller-Rabin-primality-test b/Lang/Python/Miller-Rabin-primality-test deleted file mode 120000 index 4ec507954a..0000000000 --- a/Lang/Python/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Python \ No newline at end of file diff --git a/Lang/Python/Quaternion-type b/Lang/Python/Quaternion-type deleted file mode 120000 index 4219e34b85..0000000000 --- a/Lang/Python/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Python \ No newline at end of file diff --git a/Lang/Python/Sorting-Algorithms-Circle-Sort b/Lang/Python/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 3e7a80b339..0000000000 --- a/Lang/Python/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Python \ No newline at end of file diff --git a/Lang/QBasic/Repeat-a-string b/Lang/QBasic/Repeat-a-string deleted file mode 120000 index 4c99978a73..0000000000 --- a/Lang/QBasic/Repeat-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Repeat-a-string/QBasic \ No newline at end of file diff --git a/Lang/Quackery/00-LANG.txt b/Lang/Quackery/00-LANG.txt index 7eab14d4c5..b70d597b46 100644 --- a/Lang/Quackery/00-LANG.txt +++ b/Lang/Quackery/00-LANG.txt @@ -3,7 +3,7 @@ {{language programming paradigm|Imperative}} Quackery is an open-source, lightweight, entry-level concatenative language for educational and recreational programming, and an extensible compiler for a hypothetical processor, the Quackery Engine. -It is coded as a Python 3 function in about 48k of Pythonscript, about half of which is a string of Quackery code. +It is coded as a Python 3 function in about 50k of Pythonscript, about half of which is a string of Quackery code. The Quackery GitHub repository, which includes the Quackery manual "The Book of Quackery" as a pdf, is at [https://github.com/GordonCharlton/Quackery github.com/GordonCharlton/Quackery]. diff --git a/Lang/Quackery/Bioinformatics-base-count b/Lang/Quackery/Bioinformatics-base-count deleted file mode 120000 index 65cab8d1ed..0000000000 --- a/Lang/Quackery/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Miller-Rabin-primality-test b/Lang/Quackery/Miller-Rabin-primality-test deleted file mode 120000 index d8e4ec56b5..0000000000 --- a/Lang/Quackery/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sorting-Algorithms-Circle-Sort b/Lang/Quackery/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e4abaee49d..0000000000 --- a/Lang/Quackery/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Quackery \ No newline at end of file diff --git a/Lang/Quite-BASIC/Empty-program b/Lang/Quite-BASIC/Empty-program deleted file mode 120000 index fb2bfba5b2..0000000000 --- a/Lang/Quite-BASIC/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Quite-BASIC \ No newline at end of file diff --git a/Lang/R/Bioinformatics-base-count b/Lang/R/Bioinformatics-base-count deleted file mode 120000 index 2ca416a985..0000000000 --- a/Lang/R/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/R \ No newline at end of file diff --git a/Lang/R/Quaternion-type b/Lang/R/Quaternion-type deleted file mode 120000 index 2e826895b9..0000000000 --- a/Lang/R/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/R \ No newline at end of file diff --git a/Lang/REBOL/00-LANG.txt b/Lang/REBOL/00-LANG.txt deleted file mode 100644 index f5919f4e5a..0000000000 --- a/Lang/REBOL/00-LANG.txt +++ /dev/null @@ -1,5 +0,0 @@ -{{stub}}{{language|REBOL -|site=http://rebol.com}} -REBOL stands for Relative Expression Based Object Language. - -See also: [https://rosettacode.org/wiki/Category:Rebol Category:Rebol] \ No newline at end of file diff --git a/Lang/REBOL/00-META.yaml b/Lang/REBOL/00-META.yaml deleted file mode 100644 index 58070bb517..0000000000 --- a/Lang/REBOL/00-META.yaml +++ /dev/null @@ -1,2 +0,0 @@ ---- -from: http://rosettacode.org/wiki/Category:REBOL diff --git a/Lang/REBOL/100-doors b/Lang/REBOL/100-doors deleted file mode 120000 index 3c604849c4..0000000000 --- a/Lang/REBOL/100-doors +++ /dev/null @@ -1 +0,0 @@ -../../Task/100-doors/REBOL \ No newline at end of file diff --git a/Lang/REBOL/15-puzzle-game b/Lang/REBOL/15-puzzle-game deleted file mode 120000 index ca19266202..0000000000 --- a/Lang/REBOL/15-puzzle-game +++ /dev/null @@ -1 +0,0 @@ -../../Task/15-puzzle-game/REBOL \ No newline at end of file diff --git a/Lang/REBOL/9-billion-names-of-God-the-integer b/Lang/REBOL/9-billion-names-of-God-the-integer deleted file mode 120000 index d19b039600..0000000000 --- a/Lang/REBOL/9-billion-names-of-God-the-integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/9-billion-names-of-God-the-integer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/99-bottles-of-beer b/Lang/REBOL/99-bottles-of-beer deleted file mode 120000 index 464d38e243..0000000000 --- a/Lang/REBOL/99-bottles-of-beer +++ /dev/null @@ -1 +0,0 @@ -../../Task/99-bottles-of-beer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/A+B b/Lang/REBOL/A+B deleted file mode 120000 index a6531c3ec1..0000000000 --- a/Lang/REBOL/A+B +++ /dev/null @@ -1 +0,0 @@ -../../Task/A+B/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Abstract-type b/Lang/REBOL/Abstract-type deleted file mode 120000 index c01205f584..0000000000 --- a/Lang/REBOL/Abstract-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abstract-type/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Accumulator-factory b/Lang/REBOL/Accumulator-factory deleted file mode 120000 index 9f94ac82f1..0000000000 --- a/Lang/REBOL/Accumulator-factory +++ /dev/null @@ -1 +0,0 @@ -../../Task/Accumulator-factory/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Ackermann-function b/Lang/REBOL/Ackermann-function deleted file mode 120000 index bb556d5ce8..0000000000 --- a/Lang/REBOL/Ackermann-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Ackermann-function/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime b/Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime deleted file mode 120000 index 901f7e7487..0000000000 --- a/Lang/REBOL/Add-a-variable-to-a-class-instance-at-runtime +++ /dev/null @@ -1 +0,0 @@ -../../Task/Add-a-variable-to-a-class-instance-at-runtime/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Align-columns b/Lang/REBOL/Align-columns deleted file mode 120000 index 67ffa18d54..0000000000 --- a/Lang/REBOL/Align-columns +++ /dev/null @@ -1 +0,0 @@ -../../Task/Align-columns/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Amicable-pairs b/Lang/REBOL/Amicable-pairs deleted file mode 120000 index 238ed42eb6..0000000000 --- a/Lang/REBOL/Amicable-pairs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Amicable-pairs/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Animation b/Lang/REBOL/Animation deleted file mode 120000 index 0fccfbad33..0000000000 --- a/Lang/REBOL/Animation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Animation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Anonymous-recursion b/Lang/REBOL/Anonymous-recursion deleted file mode 120000 index 5c9e13cbb0..0000000000 --- a/Lang/REBOL/Anonymous-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Anonymous-recursion/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Apply-a-callback-to-an-array b/Lang/REBOL/Apply-a-callback-to-an-array deleted file mode 120000 index a9a331e92d..0000000000 --- a/Lang/REBOL/Apply-a-callback-to-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Apply-a-callback-to-an-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Arithmetic-Integer b/Lang/REBOL/Arithmetic-Integer deleted file mode 120000 index acafb7724e..0000000000 --- a/Lang/REBOL/Arithmetic-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arithmetic-Integer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Array-concatenation b/Lang/REBOL/Array-concatenation deleted file mode 120000 index 679c10ed62..0000000000 --- a/Lang/REBOL/Array-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Array-concatenation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Array-length b/Lang/REBOL/Array-length deleted file mode 120000 index d083adde64..0000000000 --- a/Lang/REBOL/Array-length +++ /dev/null @@ -1 +0,0 @@ -../../Task/Array-length/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Arrays b/Lang/REBOL/Arrays deleted file mode 120000 index 9fc95551ee..0000000000 --- a/Lang/REBOL/Arrays +++ /dev/null @@ -1 +0,0 @@ -../../Task/Arrays/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Averages-Arithmetic-mean b/Lang/REBOL/Averages-Arithmetic-mean deleted file mode 120000 index de8cb5e395..0000000000 --- a/Lang/REBOL/Averages-Arithmetic-mean +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Arithmetic-mean/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Averages-Median b/Lang/REBOL/Averages-Median deleted file mode 120000 index 96ef2cd694..0000000000 --- a/Lang/REBOL/Averages-Median +++ /dev/null @@ -1 +0,0 @@ -../../Task/Averages-Median/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Calendar b/Lang/REBOL/Calendar deleted file mode 120000 index f396941538..0000000000 --- a/Lang/REBOL/Calendar +++ /dev/null @@ -1 +0,0 @@ -../../Task/Calendar/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Check-that-file-exists b/Lang/REBOL/Check-that-file-exists deleted file mode 120000 index 70f5435458..0000000000 --- a/Lang/REBOL/Check-that-file-exists +++ /dev/null @@ -1 +0,0 @@ -../../Task/Check-that-file-exists/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Classes b/Lang/REBOL/Classes deleted file mode 120000 index f823823847..0000000000 --- a/Lang/REBOL/Classes +++ /dev/null @@ -1 +0,0 @@ -../../Task/Classes/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Comma-quibbling b/Lang/REBOL/Comma-quibbling deleted file mode 120000 index b2f7530541..0000000000 --- a/Lang/REBOL/Comma-quibbling +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comma-quibbling/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Comments b/Lang/REBOL/Comments deleted file mode 120000 index 2dad54191c..0000000000 --- a/Lang/REBOL/Comments +++ /dev/null @@ -1 +0,0 @@ -../../Task/Comments/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Copy-a-string b/Lang/REBOL/Copy-a-string deleted file mode 120000 index 8babad9959..0000000000 --- a/Lang/REBOL/Copy-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Copy-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Create-a-file b/Lang/REBOL/Create-a-file deleted file mode 120000 index 3089537d01..0000000000 --- a/Lang/REBOL/Create-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Create-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Date-format b/Lang/REBOL/Date-format deleted file mode 120000 index 33ce065e87..0000000000 --- a/Lang/REBOL/Date-format +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-format/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Date-manipulation b/Lang/REBOL/Date-manipulation deleted file mode 120000 index 2722a008ce..0000000000 --- a/Lang/REBOL/Date-manipulation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Date-manipulation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Day-of-the-week b/Lang/REBOL/Day-of-the-week deleted file mode 120000 index 82d7509a60..0000000000 --- a/Lang/REBOL/Day-of-the-week +++ /dev/null @@ -1 +0,0 @@ -../../Task/Day-of-the-week/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Delete-a-file b/Lang/REBOL/Delete-a-file deleted file mode 120000 index 66f14845d7..0000000000 --- a/Lang/REBOL/Delete-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Delete-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Detect-division-by-zero b/Lang/REBOL/Detect-division-by-zero deleted file mode 120000 index b0ccafd718..0000000000 --- a/Lang/REBOL/Detect-division-by-zero +++ /dev/null @@ -1 +0,0 @@ -../../Task/Detect-division-by-zero/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Determine-if-a-string-is-numeric b/Lang/REBOL/Determine-if-a-string-is-numeric deleted file mode 120000 index 045a0ae13f..0000000000 --- a/Lang/REBOL/Determine-if-a-string-is-numeric +++ /dev/null @@ -1 +0,0 @@ -../../Task/Determine-if-a-string-is-numeric/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Documentation b/Lang/REBOL/Documentation deleted file mode 120000 index daa69740d8..0000000000 --- a/Lang/REBOL/Documentation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Documentation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Dot-product b/Lang/REBOL/Dot-product deleted file mode 120000 index 0e405ceca0..0000000000 --- a/Lang/REBOL/Dot-product +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dot-product/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Dynamic-variable-names b/Lang/REBOL/Dynamic-variable-names deleted file mode 120000 index dc26f8842e..0000000000 --- a/Lang/REBOL/Dynamic-variable-names +++ /dev/null @@ -1 +0,0 @@ -../../Task/Dynamic-variable-names/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Echo-server b/Lang/REBOL/Echo-server deleted file mode 120000 index e5f15ce096..0000000000 --- a/Lang/REBOL/Echo-server +++ /dev/null @@ -1 +0,0 @@ -../../Task/Echo-server/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Empty-program b/Lang/REBOL/Empty-program deleted file mode 120000 index 15b162acc2..0000000000 --- a/Lang/REBOL/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Environment-variables b/Lang/REBOL/Environment-variables deleted file mode 120000 index 1742700711..0000000000 --- a/Lang/REBOL/Environment-variables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Environment-variables/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Execute-Brain- b/Lang/REBOL/Execute-Brain- deleted file mode 120000 index 5d49896311..0000000000 --- a/Lang/REBOL/Execute-Brain- +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-Brain-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Execute-a-system-command b/Lang/REBOL/Execute-a-system-command deleted file mode 120000 index 6177e36583..0000000000 --- a/Lang/REBOL/Execute-a-system-command +++ /dev/null @@ -1 +0,0 @@ -../../Task/Execute-a-system-command/REBOL \ No newline at end of file diff --git a/Lang/REBOL/FTP b/Lang/REBOL/FTP deleted file mode 120000 index 7ab1c53c58..0000000000 --- a/Lang/REBOL/FTP +++ /dev/null @@ -1 +0,0 @@ -../../Task/FTP/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Factorial b/Lang/REBOL/Factorial deleted file mode 120000 index 8643656c0a..0000000000 --- a/Lang/REBOL/Factorial +++ /dev/null @@ -1 +0,0 @@ -../../Task/Factorial/REBOL \ No newline at end of file diff --git a/Lang/REBOL/File-input-output b/Lang/REBOL/File-input-output deleted file mode 120000 index 30e510fb5d..0000000000 --- a/Lang/REBOL/File-input-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-input-output/REBOL \ No newline at end of file diff --git a/Lang/REBOL/File-size b/Lang/REBOL/File-size deleted file mode 120000 index 61c4252f32..0000000000 --- a/Lang/REBOL/File-size +++ /dev/null @@ -1 +0,0 @@ -../../Task/File-size/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Filter b/Lang/REBOL/Filter deleted file mode 120000 index d25c807398..0000000000 --- a/Lang/REBOL/Filter +++ /dev/null @@ -1 +0,0 @@ -../../Task/Filter/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Find-the-last-Sunday-of-each-month b/Lang/REBOL/Find-the-last-Sunday-of-each-month deleted file mode 120000 index c54d330170..0000000000 --- a/Lang/REBOL/Find-the-last-Sunday-of-each-month +++ /dev/null @@ -1 +0,0 @@ -../../Task/Find-the-last-Sunday-of-each-month/REBOL \ No newline at end of file diff --git a/Lang/REBOL/First-class-functions b/Lang/REBOL/First-class-functions deleted file mode 120000 index 729d2ef773..0000000000 --- a/Lang/REBOL/First-class-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/First-class-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Fixed-length-records b/Lang/REBOL/Fixed-length-records deleted file mode 120000 index c6d6d1ea72..0000000000 --- a/Lang/REBOL/Fixed-length-records +++ /dev/null @@ -1 +0,0 @@ -../../Task/Fixed-length-records/REBOL \ No newline at end of file diff --git a/Lang/REBOL/FizzBuzz b/Lang/REBOL/FizzBuzz deleted file mode 120000 index 5fada5dc79..0000000000 --- a/Lang/REBOL/FizzBuzz +++ /dev/null @@ -1 +0,0 @@ -../../Task/FizzBuzz/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Flatten-a-list b/Lang/REBOL/Flatten-a-list deleted file mode 120000 index c63e60f1ae..0000000000 --- a/Lang/REBOL/Flatten-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Flatten-a-list/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Flow-control-structures b/Lang/REBOL/Flow-control-structures deleted file mode 120000 index 02978f970b..0000000000 --- a/Lang/REBOL/Flow-control-structures +++ /dev/null @@ -1 +0,0 @@ -../../Task/Flow-control-structures/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Formatted-numeric-output b/Lang/REBOL/Formatted-numeric-output deleted file mode 120000 index 6231201b56..0000000000 --- a/Lang/REBOL/Formatted-numeric-output +++ /dev/null @@ -1 +0,0 @@ -../../Task/Formatted-numeric-output/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Function-composition b/Lang/REBOL/Function-composition deleted file mode 120000 index 00fbef410f..0000000000 --- a/Lang/REBOL/Function-composition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-composition/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Function-definition b/Lang/REBOL/Function-definition deleted file mode 120000 index 24045b17c8..0000000000 --- a/Lang/REBOL/Function-definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Function-definition/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Generic-swap b/Lang/REBOL/Generic-swap deleted file mode 120000 index 252d05095f..0000000000 --- a/Lang/REBOL/Generic-swap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Generic-swap/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Greatest-common-divisor b/Lang/REBOL/Greatest-common-divisor deleted file mode 120000 index 66251fda3d..0000000000 --- a/Lang/REBOL/Greatest-common-divisor +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-common-divisor/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Greatest-element-of-a-list b/Lang/REBOL/Greatest-element-of-a-list deleted file mode 120000 index bf835b648c..0000000000 --- a/Lang/REBOL/Greatest-element-of-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Greatest-element-of-a-list/REBOL \ No newline at end of file diff --git a/Lang/REBOL/HTTP b/Lang/REBOL/HTTP deleted file mode 120000 index 7ade844f73..0000000000 --- a/Lang/REBOL/HTTP +++ /dev/null @@ -1 +0,0 @@ -../../Task/HTTP/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hailstone-sequence b/Lang/REBOL/Hailstone-sequence deleted file mode 120000 index f668d98fe0..0000000000 --- a/Lang/REBOL/Hailstone-sequence +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hailstone-sequence/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Graphical b/Lang/REBOL/Hello-world-Graphical deleted file mode 120000 index 65375f6063..0000000000 --- a/Lang/REBOL/Hello-world-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Graphical/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Newline-omission b/Lang/REBOL/Hello-world-Newline-omission deleted file mode 120000 index a1ab230770..0000000000 --- a/Lang/REBOL/Hello-world-Newline-omission +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Newline-omission/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Text b/Lang/REBOL/Hello-world-Text deleted file mode 120000 index 417f675e90..0000000000 --- a/Lang/REBOL/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Higher-order-functions b/Lang/REBOL/Higher-order-functions deleted file mode 120000 index e0da7764d4..0000000000 --- a/Lang/REBOL/Higher-order-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Higher-order-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Horners-rule-for-polynomial-evaluation b/Lang/REBOL/Horners-rule-for-polynomial-evaluation deleted file mode 120000 index 3ed4d272a6..0000000000 --- a/Lang/REBOL/Horners-rule-for-polynomial-evaluation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Horners-rule-for-polynomial-evaluation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hostname b/Lang/REBOL/Hostname deleted file mode 120000 index 00509fe88c..0000000000 --- a/Lang/REBOL/Hostname +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hostname/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Increment-a-numerical-string b/Lang/REBOL/Increment-a-numerical-string deleted file mode 120000 index 0b8ae5b473..0000000000 --- a/Lang/REBOL/Increment-a-numerical-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Increment-a-numerical-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Inheritance-Single b/Lang/REBOL/Inheritance-Single deleted file mode 120000 index 8790c38450..0000000000 --- a/Lang/REBOL/Inheritance-Single +++ /dev/null @@ -1 +0,0 @@ -../../Task/Inheritance-Single/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Input-loop b/Lang/REBOL/Input-loop deleted file mode 120000 index 81d9914a81..0000000000 --- a/Lang/REBOL/Input-loop +++ /dev/null @@ -1 +0,0 @@ -../../Task/Input-loop/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Integer-comparison b/Lang/REBOL/Integer-comparison deleted file mode 120000 index 6f12d33801..0000000000 --- a/Lang/REBOL/Integer-comparison +++ /dev/null @@ -1 +0,0 @@ -../../Task/Integer-comparison/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Interactive-programming-repl- b/Lang/REBOL/Interactive-programming-repl- deleted file mode 120000 index a2a59ee516..0000000000 --- a/Lang/REBOL/Interactive-programming-repl- +++ /dev/null @@ -1 +0,0 @@ -../../Task/Interactive-programming-repl-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/JSON b/Lang/REBOL/JSON deleted file mode 120000 index bbdd962074..0000000000 --- a/Lang/REBOL/JSON +++ /dev/null @@ -1 +0,0 @@ -../../Task/JSON/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Josephus-problem b/Lang/REBOL/Josephus-problem deleted file mode 120000 index d092745290..0000000000 --- a/Lang/REBOL/Josephus-problem +++ /dev/null @@ -1 +0,0 @@ -../../Task/Josephus-problem/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Keyboard-macros b/Lang/REBOL/Keyboard-macros deleted file mode 120000 index 4c918106f7..0000000000 --- a/Lang/REBOL/Keyboard-macros +++ /dev/null @@ -1 +0,0 @@ -../../Task/Keyboard-macros/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Knuth-shuffle b/Lang/REBOL/Knuth-shuffle deleted file mode 120000 index e1ef5ac835..0000000000 --- a/Lang/REBOL/Knuth-shuffle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Knuth-shuffle/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Last-Friday-of-each-month b/Lang/REBOL/Last-Friday-of-each-month deleted file mode 120000 index 592b3befd7..0000000000 --- a/Lang/REBOL/Last-Friday-of-each-month +++ /dev/null @@ -1 +0,0 @@ -../../Task/Last-Friday-of-each-month/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Leap-year b/Lang/REBOL/Leap-year deleted file mode 120000 index e1fde0d2a0..0000000000 --- a/Lang/REBOL/Leap-year +++ /dev/null @@ -1 +0,0 @@ -../../Task/Leap-year/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Literals-Integer b/Lang/REBOL/Literals-Integer deleted file mode 120000 index c018808d2d..0000000000 --- a/Lang/REBOL/Literals-Integer +++ /dev/null @@ -1 +0,0 @@ -../../Task/Literals-Integer/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Logical-operations b/Lang/REBOL/Logical-operations deleted file mode 120000 index b2be03cb20..0000000000 --- a/Lang/REBOL/Logical-operations +++ /dev/null @@ -1 +0,0 @@ -../../Task/Logical-operations/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loop-over-multiple-arrays-simultaneously b/Lang/REBOL/Loop-over-multiple-arrays-simultaneously deleted file mode 120000 index 509d196c87..0000000000 --- a/Lang/REBOL/Loop-over-multiple-arrays-simultaneously +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loop-over-multiple-arrays-simultaneously/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Break b/Lang/REBOL/Loops-Break deleted file mode 120000 index b12b588bcd..0000000000 --- a/Lang/REBOL/Loops-Break +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Break/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Continue b/Lang/REBOL/Loops-Continue deleted file mode 120000 index 620f8d42c2..0000000000 --- a/Lang/REBOL/Loops-Continue +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Continue/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Do-while b/Lang/REBOL/Loops-Do-while deleted file mode 120000 index a092621ef7..0000000000 --- a/Lang/REBOL/Loops-Do-while +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Do-while/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Downward-for b/Lang/REBOL/Loops-Downward-for deleted file mode 120000 index e956288e68..0000000000 --- a/Lang/REBOL/Loops-Downward-for +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Downward-for/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-For b/Lang/REBOL/Loops-For deleted file mode 120000 index 9c59f991f0..0000000000 --- a/Lang/REBOL/Loops-For +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-For-with-a-specified-step b/Lang/REBOL/Loops-For-with-a-specified-step deleted file mode 120000 index 3174e4899e..0000000000 --- a/Lang/REBOL/Loops-For-with-a-specified-step +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-For-with-a-specified-step/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Foreach b/Lang/REBOL/Loops-Foreach deleted file mode 120000 index 98cc61392e..0000000000 --- a/Lang/REBOL/Loops-Foreach +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Foreach/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Increment-loop-index-within-loop-body b/Lang/REBOL/Loops-Increment-loop-index-within-loop-body deleted file mode 120000 index 1d1b2df2c6..0000000000 --- a/Lang/REBOL/Loops-Increment-loop-index-within-loop-body +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Increment-loop-index-within-loop-body/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Infinite b/Lang/REBOL/Loops-Infinite deleted file mode 120000 index cd80f1fc2f..0000000000 --- a/Lang/REBOL/Loops-Infinite +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Infinite/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-N-plus-one-half b/Lang/REBOL/Loops-N-plus-one-half deleted file mode 120000 index 530a004b19..0000000000 --- a/Lang/REBOL/Loops-N-plus-one-half +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-N-plus-one-half/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Nested b/Lang/REBOL/Loops-Nested deleted file mode 120000 index fad704e1b5..0000000000 --- a/Lang/REBOL/Loops-Nested +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Nested/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-While b/Lang/REBOL/Loops-While deleted file mode 120000 index 7caecdb43d..0000000000 --- a/Lang/REBOL/Loops-While +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-While/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-With-multiple-ranges b/Lang/REBOL/Loops-With-multiple-ranges deleted file mode 120000 index bd25edb4b9..0000000000 --- a/Lang/REBOL/Loops-With-multiple-ranges +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-With-multiple-ranges/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Loops-Wrong-ranges b/Lang/REBOL/Loops-Wrong-ranges deleted file mode 120000 index a8f17c4209..0000000000 --- a/Lang/REBOL/Loops-Wrong-ranges +++ /dev/null @@ -1 +0,0 @@ -../../Task/Loops-Wrong-ranges/REBOL \ No newline at end of file diff --git a/Lang/REBOL/MD5 b/Lang/REBOL/MD5 deleted file mode 120000 index 5cb019110c..0000000000 --- a/Lang/REBOL/MD5 +++ /dev/null @@ -1 +0,0 @@ -../../Task/MD5/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Mad-Libs b/Lang/REBOL/Mad-Libs deleted file mode 120000 index db4b8d6171..0000000000 --- a/Lang/REBOL/Mad-Libs +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mad-Libs/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Menu b/Lang/REBOL/Menu deleted file mode 120000 index 3b0b7dc2de..0000000000 --- a/Lang/REBOL/Menu +++ /dev/null @@ -1 +0,0 @@ -../../Task/Menu/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Multiplication-tables b/Lang/REBOL/Multiplication-tables deleted file mode 120000 index 1b70d39ee9..0000000000 --- a/Lang/REBOL/Multiplication-tables +++ /dev/null @@ -1 +0,0 @@ -../../Task/Multiplication-tables/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Mutual-recursion b/Lang/REBOL/Mutual-recursion deleted file mode 120000 index cb2de22d29..0000000000 --- a/Lang/REBOL/Mutual-recursion +++ /dev/null @@ -1 +0,0 @@ -../../Task/Mutual-recursion/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Null-object b/Lang/REBOL/Null-object deleted file mode 120000 index 0b324069d2..0000000000 --- a/Lang/REBOL/Null-object +++ /dev/null @@ -1 +0,0 @@ -../../Task/Null-object/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Number-reversal-game b/Lang/REBOL/Number-reversal-game deleted file mode 120000 index a23e4203b5..0000000000 --- a/Lang/REBOL/Number-reversal-game +++ /dev/null @@ -1 +0,0 @@ -../../Task/Number-reversal-game/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Object-serialization b/Lang/REBOL/Object-serialization deleted file mode 120000 index 71f73b27eb..0000000000 --- a/Lang/REBOL/Object-serialization +++ /dev/null @@ -1 +0,0 @@ -../../Task/Object-serialization/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Palindrome-detection b/Lang/REBOL/Palindrome-detection deleted file mode 120000 index 45e3490dd4..0000000000 --- a/Lang/REBOL/Palindrome-detection +++ /dev/null @@ -1 +0,0 @@ -../../Task/Palindrome-detection/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Percentage-difference-between-images b/Lang/REBOL/Percentage-difference-between-images deleted file mode 120000 index 47e0c29027..0000000000 --- a/Lang/REBOL/Percentage-difference-between-images +++ /dev/null @@ -1 +0,0 @@ -../../Task/Percentage-difference-between-images/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Perfect-numbers b/Lang/REBOL/Perfect-numbers deleted file mode 120000 index 888589d0dd..0000000000 --- a/Lang/REBOL/Perfect-numbers +++ /dev/null @@ -1 +0,0 @@ -../../Task/Perfect-numbers/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Polyspiral b/Lang/REBOL/Polyspiral deleted file mode 120000 index 70a487676d..0000000000 --- a/Lang/REBOL/Polyspiral +++ /dev/null @@ -1 +0,0 @@ -../../Task/Polyspiral/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Primality-by-trial-division b/Lang/REBOL/Primality-by-trial-division deleted file mode 120000 index 6e14471054..0000000000 --- a/Lang/REBOL/Primality-by-trial-division +++ /dev/null @@ -1 +0,0 @@ -../../Task/Primality-by-trial-division/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Program-termination b/Lang/REBOL/Program-termination deleted file mode 120000 index 7c4ce8b3c8..0000000000 --- a/Lang/REBOL/Program-termination +++ /dev/null @@ -1 +0,0 @@ -../../Task/Program-termination/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Queue-Definition b/Lang/REBOL/Queue-Definition deleted file mode 120000 index aa21697e36..0000000000 --- a/Lang/REBOL/Queue-Definition +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Definition/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Queue-Usage b/Lang/REBOL/Queue-Usage deleted file mode 120000 index 488c4682f8..0000000000 --- a/Lang/REBOL/Queue-Usage +++ /dev/null @@ -1 +0,0 @@ -../../Task/Queue-Usage/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Quine b/Lang/REBOL/Quine deleted file mode 120000 index 391f27dc9c..0000000000 --- a/Lang/REBOL/Quine +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quine/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Read-a-specific-line-from-a-file b/Lang/REBOL/Read-a-specific-line-from-a-file deleted file mode 120000 index fc3cb7c086..0000000000 --- a/Lang/REBOL/Read-a-specific-line-from-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-a-specific-line-from-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Read-entire-file b/Lang/REBOL/Read-entire-file deleted file mode 120000 index 8d1ffdb8c8..0000000000 --- a/Lang/REBOL/Read-entire-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Read-entire-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Regular-expressions b/Lang/REBOL/Regular-expressions deleted file mode 120000 index cc056f3dfc..0000000000 --- a/Lang/REBOL/Regular-expressions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Regular-expressions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Remove-duplicate-elements b/Lang/REBOL/Remove-duplicate-elements deleted file mode 120000 index 989597f93c..0000000000 --- a/Lang/REBOL/Remove-duplicate-elements +++ /dev/null @@ -1 +0,0 @@ -../../Task/Remove-duplicate-elements/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Rename-a-file b/Lang/REBOL/Rename-a-file deleted file mode 120000 index d5b1f76dba..0000000000 --- a/Lang/REBOL/Rename-a-file +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rename-a-file/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Repeat-a-string b/Lang/REBOL/Repeat-a-string deleted file mode 120000 index df3bda003c..0000000000 --- a/Lang/REBOL/Repeat-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Repeat-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Reverse-a-string b/Lang/REBOL/Reverse-a-string deleted file mode 120000 index 4fa66fa042..0000000000 --- a/Lang/REBOL/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Rot-13 b/Lang/REBOL/Rot-13 deleted file mode 120000 index 344b9949b8..0000000000 --- a/Lang/REBOL/Rot-13 +++ /dev/null @@ -1 +0,0 @@ -../../Task/Rot-13/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Runtime-evaluation b/Lang/REBOL/Runtime-evaluation deleted file mode 120000 index 4f29a7904a..0000000000 --- a/Lang/REBOL/Runtime-evaluation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Runtime-evaluation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Runtime-evaluation-In-an-environment b/Lang/REBOL/Runtime-evaluation-In-an-environment deleted file mode 120000 index 00ac88948d..0000000000 --- a/Lang/REBOL/Runtime-evaluation-In-an-environment +++ /dev/null @@ -1 +0,0 @@ -../../Task/Runtime-evaluation-In-an-environment/REBOL \ No newline at end of file diff --git a/Lang/REBOL/SHA-1 b/Lang/REBOL/SHA-1 deleted file mode 120000 index b430af646a..0000000000 --- a/Lang/REBOL/SHA-1 +++ /dev/null @@ -1 +0,0 @@ -../../Task/SHA-1/REBOL \ No newline at end of file diff --git a/Lang/REBOL/SHA-256 b/Lang/REBOL/SHA-256 deleted file mode 120000 index b5f39ed805..0000000000 --- a/Lang/REBOL/SHA-256 +++ /dev/null @@ -1 +0,0 @@ -../../Task/SHA-256/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Search-a-list b/Lang/REBOL/Search-a-list deleted file mode 120000 index 30c4450829..0000000000 --- a/Lang/REBOL/Search-a-list +++ /dev/null @@ -1 +0,0 @@ -../../Task/Search-a-list/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Semordnilap b/Lang/REBOL/Semordnilap deleted file mode 120000 index fee60064bb..0000000000 --- a/Lang/REBOL/Semordnilap +++ /dev/null @@ -1 +0,0 @@ -../../Task/Semordnilap/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Send-email b/Lang/REBOL/Send-email deleted file mode 120000 index 7a102c33ea..0000000000 --- a/Lang/REBOL/Send-email +++ /dev/null @@ -1 +0,0 @@ -../../Task/Send-email/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Shell-one-liner b/Lang/REBOL/Shell-one-liner deleted file mode 120000 index 3efd76bee3..0000000000 --- a/Lang/REBOL/Shell-one-liner +++ /dev/null @@ -1 +0,0 @@ -../../Task/Shell-one-liner/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Simple-database b/Lang/REBOL/Simple-database deleted file mode 120000 index 2171f3e8b2..0000000000 --- a/Lang/REBOL/Simple-database +++ /dev/null @@ -1 +0,0 @@ -../../Task/Simple-database/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Simple-windowed-application b/Lang/REBOL/Simple-windowed-application deleted file mode 120000 index 3eb2f5011a..0000000000 --- a/Lang/REBOL/Simple-windowed-application +++ /dev/null @@ -1 +0,0 @@ -../../Task/Simple-windowed-application/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sleep b/Lang/REBOL/Sleep deleted file mode 120000 index 49498dee8f..0000000000 --- a/Lang/REBOL/Sleep +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sleep/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sort-an-integer-array b/Lang/REBOL/Sort-an-integer-array deleted file mode 120000 index be40906bd3..0000000000 --- a/Lang/REBOL/Sort-an-integer-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-an-integer-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sort-stability b/Lang/REBOL/Sort-stability deleted file mode 120000 index 7a6119bc4e..0000000000 --- a/Lang/REBOL/Sort-stability +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sort-stability/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sorting-algorithms-Insertion-sort b/Lang/REBOL/Sorting-algorithms-Insertion-sort deleted file mode 120000 index 5a9f9f2f24..0000000000 --- a/Lang/REBOL/Sorting-algorithms-Insertion-sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-algorithms-Insertion-sort/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Stack b/Lang/REBOL/Stack deleted file mode 120000 index 70bb3936ee..0000000000 --- a/Lang/REBOL/Stack +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stack/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Stair-climbing-puzzle b/Lang/REBOL/Stair-climbing-puzzle deleted file mode 120000 index 935f1a3925..0000000000 --- a/Lang/REBOL/Stair-climbing-puzzle +++ /dev/null @@ -1 +0,0 @@ -../../Task/Stair-climbing-puzzle/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-case b/Lang/REBOL/String-case deleted file mode 120000 index 2279191d8d..0000000000 --- a/Lang/REBOL/String-case +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-case/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-concatenation b/Lang/REBOL/String-concatenation deleted file mode 120000 index 8be78ed69f..0000000000 --- a/Lang/REBOL/String-concatenation +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-concatenation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-interpolation-included- b/Lang/REBOL/String-interpolation-included- deleted file mode 120000 index 1158cc37bc..0000000000 --- a/Lang/REBOL/String-interpolation-included- +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-interpolation-included-/REBOL \ No newline at end of file diff --git a/Lang/REBOL/String-length b/Lang/REBOL/String-length deleted file mode 120000 index 06c8f5cbd6..0000000000 --- a/Lang/REBOL/String-length +++ /dev/null @@ -1 +0,0 @@ -../../Task/String-length/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Substring b/Lang/REBOL/Substring deleted file mode 120000 index ae87eb5a53..0000000000 --- a/Lang/REBOL/Substring +++ /dev/null @@ -1 +0,0 @@ -../../Task/Substring/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Sum-and-product-of-an-array b/Lang/REBOL/Sum-and-product-of-an-array deleted file mode 120000 index 5ce08d6535..0000000000 --- a/Lang/REBOL/Sum-and-product-of-an-array +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sum-and-product-of-an-array/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Symmetric-difference b/Lang/REBOL/Symmetric-difference deleted file mode 120000 index 27c9c680ad..0000000000 --- a/Lang/REBOL/Symmetric-difference +++ /dev/null @@ -1 +0,0 @@ -../../Task/Symmetric-difference/REBOL \ No newline at end of file diff --git a/Lang/REBOL/System-time b/Lang/REBOL/System-time deleted file mode 120000 index 7ea31d4a27..0000000000 --- a/Lang/REBOL/System-time +++ /dev/null @@ -1 +0,0 @@ -../../Task/System-time/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Take-notes-on-the-command-line b/Lang/REBOL/Take-notes-on-the-command-line deleted file mode 120000 index f00a0f5d0a..0000000000 --- a/Lang/REBOL/Take-notes-on-the-command-line +++ /dev/null @@ -1 +0,0 @@ -../../Task/Take-notes-on-the-command-line/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Tokenize-a-string b/Lang/REBOL/Tokenize-a-string deleted file mode 120000 index ee10fb0551..0000000000 --- a/Lang/REBOL/Tokenize-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tokenize-a-string/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Towers-of-Hanoi b/Lang/REBOL/Towers-of-Hanoi deleted file mode 120000 index a173272546..0000000000 --- a/Lang/REBOL/Towers-of-Hanoi +++ /dev/null @@ -1 +0,0 @@ -../../Task/Towers-of-Hanoi/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Tree-traversal b/Lang/REBOL/Tree-traversal deleted file mode 120000 index 0c44bbca9b..0000000000 --- a/Lang/REBOL/Tree-traversal +++ /dev/null @@ -1 +0,0 @@ -../../Task/Tree-traversal/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Trigonometric-functions b/Lang/REBOL/Trigonometric-functions deleted file mode 120000 index 8f4c11188c..0000000000 --- a/Lang/REBOL/Trigonometric-functions +++ /dev/null @@ -1 +0,0 @@ -../../Task/Trigonometric-functions/REBOL \ No newline at end of file diff --git a/Lang/REBOL/User-input-Graphical b/Lang/REBOL/User-input-Graphical deleted file mode 120000 index 001538e055..0000000000 --- a/Lang/REBOL/User-input-Graphical +++ /dev/null @@ -1 +0,0 @@ -../../Task/User-input-Graphical/REBOL \ No newline at end of file diff --git a/Lang/REBOL/User-input-Text b/Lang/REBOL/User-input-Text deleted file mode 120000 index b81fcf9c85..0000000000 --- a/Lang/REBOL/User-input-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/User-input-Text/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Variadic-function b/Lang/REBOL/Variadic-function deleted file mode 120000 index c3eb7c285d..0000000000 --- a/Lang/REBOL/Variadic-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/Variadic-function/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Web-scraping b/Lang/REBOL/Web-scraping deleted file mode 120000 index 4c37db2bfe..0000000000 --- a/Lang/REBOL/Web-scraping +++ /dev/null @@ -1 +0,0 @@ -../../Task/Web-scraping/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Window-creation b/Lang/REBOL/Window-creation deleted file mode 120000 index d3c3450624..0000000000 --- a/Lang/REBOL/Window-creation +++ /dev/null @@ -1 +0,0 @@ -../../Task/Window-creation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/XML-Input b/Lang/REBOL/XML-Input deleted file mode 120000 index f96cb4fd5e..0000000000 --- a/Lang/REBOL/XML-Input +++ /dev/null @@ -1 +0,0 @@ -../../Task/XML-Input/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Y-combinator b/Lang/REBOL/Y-combinator deleted file mode 120000 index 492c58627d..0000000000 --- a/Lang/REBOL/Y-combinator +++ /dev/null @@ -1 +0,0 @@ -../../Task/Y-combinator/REBOL \ No newline at end of file diff --git a/Lang/REXX/00-LANG.txt b/Lang/REXX/00-LANG.txt index fd028fe2bc..592349f719 100644 --- a/Lang/REXX/00-LANG.txt +++ b/Lang/REXX/00-LANG.txt @@ -30,8 +30,9 @@ Using Classic REXX closely resembles pseudo code and many languages like Basic o Some items that might differ from what you are familiar with.
    * Caseless, fully free format. * Code blocks delimited by do...end, no brackets (){}. -* Usual control structures present: do...by...to, do while/until, select, leave, iterate. -* No data types, no declarations, everything is string. String functions such as Left() or Substr() may be applied on numbers. +* A programs starts always with line 1, so you'll need 'exit' before the code for procedures and routines. +* Usual control structures present: do...by...to, do while/until, select, leave, iterate, call, return, exit, & (and), \ (not). +* No data types, no declarations, everything is string. String functions such as 'Left()' or 'Substr()' may be applied on numbers. * All arithmetic is decimal based, not binary. So stuff like bit shifting or multiply/divide by 2 using exponent add/subtract does not apply. * Exponentiation is designated by '**' thus x^2 = x**2. * Integer division is designated by '%' thus 13%3 = 4. @@ -129,4 +130,4 @@ Some items that might differ from what you are familiar with.
    * [http://www.rexxla.org/ CRX Open Source (right column side)] == Rosetta Code tasks not implemented in REXX == -[[Reports:Tasks_not_implemented_in_REXX]] \ No newline at end of file +[[Tasks not implemented in REXX]] \ No newline at end of file diff --git a/Lang/REXX/Bioinformatics-base-count b/Lang/REXX/Bioinformatics-base-count deleted file mode 120000 index c722864481..0000000000 --- a/Lang/REXX/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/REXX \ No newline at end of file diff --git a/Lang/REXX/Meissel-Mertens-constant b/Lang/REXX/Meissel-Mertens-constant deleted file mode 120000 index 20c3a86a87..0000000000 --- a/Lang/REXX/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/REXX \ No newline at end of file diff --git a/Lang/REXX/Miller-Rabin-primality-test b/Lang/REXX/Miller-Rabin-primality-test deleted file mode 120000 index 6b9607754b..0000000000 --- a/Lang/REXX/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/REXX \ No newline at end of file diff --git a/Lang/REXX/Quaternion-type b/Lang/REXX/Quaternion-type deleted file mode 120000 index 18e452fac4..0000000000 --- a/Lang/REXX/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/REXX \ No newline at end of file diff --git a/Lang/REXX/Sorting-Algorithms-Circle-Sort b/Lang/REXX/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 383d356065..0000000000 --- a/Lang/REXX/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/REXX \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/00-LANG.txt b/Lang/RISC-V-Assembly/00-LANG.txt index 6a2bfde754..3f4a6ea98e 100644 --- a/Lang/RISC-V-Assembly/00-LANG.txt +++ b/Lang/RISC-V-Assembly/00-LANG.txt @@ -43,7 +43,7 @@ copy the file .uf2 to raspberry pico2 (see documentation raspberry pi pico2) Start serial connexion on host (ex: putty on windows11) Example CMakeLists.txt : - + cmake_minimum_required(VERSION 3.13) include(pico_sdk_import.cmake) @@ -67,10 +67,13 @@ pico_enable_stdio_usb(hello 1) pico_enable_stdio_uart(hello 0) pico_add_extra_outputs(hello) + see source program on hello world rosetta code cmake -DPython3_EXECUTABLE=C:\Users\Vincent\AppData\Local\Microsoft\WindowsApps\python3.10.exe -DPICO_PLATFORM=rp2350-riscv -DPICO_TOOLCHAIN_PATH=E:\Pico2\tools\bin -DPICO_SDK_PATH=..\..\..\pico-sdk -G "NMake Makefiles" .. +see instructions list on chapter 3.8.1.6. Alphabetical list of instructions on rp2350 datasheet + [[Category:Assembler language]] [[Category:Assembly]] \ No newline at end of file diff --git a/Lang/Racket/Bioinformatics-base-count b/Lang/Racket/Bioinformatics-base-count deleted file mode 120000 index e2d3d89548..0000000000 --- a/Lang/Racket/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Racket \ No newline at end of file diff --git a/Lang/Racket/Miller-Rabin-primality-test b/Lang/Racket/Miller-Rabin-primality-test deleted file mode 120000 index db07b51bff..0000000000 --- a/Lang/Racket/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Racket \ No newline at end of file diff --git a/Lang/Racket/Quaternion-type b/Lang/Racket/Quaternion-type deleted file mode 120000 index 88e3ea41c9..0000000000 --- a/Lang/Racket/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Racket \ No newline at end of file diff --git a/Lang/Racket/Sorting-Algorithms-Circle-Sort b/Lang/Racket/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 4c351d18cc..0000000000 --- a/Lang/Racket/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Racket \ No newline at end of file diff --git a/Lang/Raku/Bioinformatics-base-count b/Lang/Raku/Bioinformatics-base-count deleted file mode 120000 index 7d4ea3da69..0000000000 --- a/Lang/Raku/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Raku \ No newline at end of file diff --git a/Lang/Raku/Meissel-Mertens-constant b/Lang/Raku/Meissel-Mertens-constant deleted file mode 120000 index 5a835b7f73..0000000000 --- a/Lang/Raku/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Raku \ No newline at end of file diff --git a/Lang/Raku/Miller-Rabin-primality-test b/Lang/Raku/Miller-Rabin-primality-test deleted file mode 120000 index 5ec2c83bd9..0000000000 --- a/Lang/Raku/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Raku \ No newline at end of file diff --git a/Lang/Raku/Quaternion-type b/Lang/Raku/Quaternion-type deleted file mode 120000 index 3333adafb6..0000000000 --- a/Lang/Raku/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Raku \ No newline at end of file diff --git a/Lang/Raku/Sorting-Algorithms-Circle-Sort b/Lang/Raku/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 1ba8b44162..0000000000 --- a/Lang/Raku/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Raku \ No newline at end of file diff --git a/Lang/RapidQ/M-bius-function b/Lang/RapidQ/M-bius-function deleted file mode 120000 index 72bc6192fb..0000000000 --- a/Lang/RapidQ/M-bius-function +++ /dev/null @@ -1 +0,0 @@ -../../Task/M-bius-function/RapidQ \ No newline at end of file diff --git a/Lang/Red/Quaternion-type b/Lang/Red/Quaternion-type deleted file mode 120000 index 7b5fc87ddd..0000000000 --- a/Lang/Red/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Red \ No newline at end of file diff --git a/Lang/Ring/Bioinformatics-base-count b/Lang/Ring/Bioinformatics-base-count deleted file mode 120000 index 291f269ac6..0000000000 --- a/Lang/Ring/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ring \ No newline at end of file diff --git a/Lang/Ring/Empty-program b/Lang/Ring/Empty-program deleted file mode 120000 index 05941ac0c2..0000000000 --- a/Lang/Ring/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Ring \ No newline at end of file diff --git a/Lang/Ring/Miller-Rabin-primality-test b/Lang/Ring/Miller-Rabin-primality-test deleted file mode 120000 index dd0885b5c9..0000000000 --- a/Lang/Ring/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-Algorithms-Circle-Sort b/Lang/Ring/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index de0338125a..0000000000 --- a/Lang/Ring/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Ring \ No newline at end of file diff --git a/Lang/Robotic/Empty-program b/Lang/Robotic/Empty-program deleted file mode 120000 index 5e2d95817a..0000000000 --- a/Lang/Robotic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Robotic \ No newline at end of file diff --git a/Lang/Ruby/Bioinformatics-base-count b/Lang/Ruby/Bioinformatics-base-count deleted file mode 120000 index af92d7709c..0000000000 --- a/Lang/Ruby/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Miller-Rabin-primality-test b/Lang/Ruby/Miller-Rabin-primality-test deleted file mode 120000 index d7cbf43733..0000000000 --- a/Lang/Ruby/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Quaternion-type b/Lang/Ruby/Quaternion-type deleted file mode 120000 index c1af2a1904..0000000000 --- a/Lang/Ruby/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sorting-Algorithms-Circle-Sort b/Lang/Ruby/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 022b44ef66..0000000000 --- a/Lang/Ruby/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Meissel-Mertens-constant b/Lang/Run-BASIC/Meissel-Mertens-constant deleted file mode 120000 index 44168b020e..0000000000 --- a/Lang/Run-BASIC/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Miller-Rabin-primality-test b/Lang/Run-BASIC/Miller-Rabin-primality-test deleted file mode 120000 index 13b7319b57..0000000000 --- a/Lang/Run-BASIC/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/Bioinformatics-base-count b/Lang/Rust/Bioinformatics-base-count deleted file mode 120000 index 412ded1361..0000000000 --- a/Lang/Rust/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Rust \ No newline at end of file diff --git a/Lang/Rust/Meissel-Mertens-constant b/Lang/Rust/Meissel-Mertens-constant deleted file mode 120000 index 30f216e193..0000000000 --- a/Lang/Rust/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Rust \ No newline at end of file diff --git a/Lang/Rust/Miller-Rabin-primality-test b/Lang/Rust/Miller-Rabin-primality-test deleted file mode 120000 index 937aebe94f..0000000000 --- a/Lang/Rust/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Rust \ No newline at end of file diff --git a/Lang/Rust/Quaternion-type b/Lang/Rust/Quaternion-type deleted file mode 120000 index 92c25b946f..0000000000 --- a/Lang/Rust/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-Algorithms-Circle-Sort b/Lang/Rust/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 924c0eb5ac..0000000000 --- a/Lang/Rust/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Rust \ No newline at end of file diff --git a/Lang/Scala/Miller-Rabin-primality-test b/Lang/Scala/Miller-Rabin-primality-test deleted file mode 120000 index 28de5ef463..0000000000 --- a/Lang/Scala/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Scala \ No newline at end of file diff --git a/Lang/Scala/Quaternion-type b/Lang/Scala/Quaternion-type deleted file mode 120000 index 15f3eda4c9..0000000000 --- a/Lang/Scala/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-Algorithms-Circle-Sort b/Lang/Scala/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 5b9f057951..0000000000 --- a/Lang/Scala/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Scala \ No newline at end of file diff --git a/Lang/Scheme/Empty-program b/Lang/Scheme/Empty-program deleted file mode 120000 index ee1ee662be..0000000000 --- a/Lang/Scheme/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Miller-Rabin-primality-test b/Lang/Scheme/Miller-Rabin-primality-test deleted file mode 120000 index 644cc32269..0000000000 --- a/Lang/Scheme/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Scheme \ No newline at end of file diff --git a/Lang/Scilab/Empty-program b/Lang/Scilab/Empty-program deleted file mode 120000 index 0cb8f21cc3..0000000000 --- a/Lang/Scilab/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Scilab \ No newline at end of file diff --git a/Lang/Seed7/Miller-Rabin-primality-test b/Lang/Seed7/Miller-Rabin-primality-test deleted file mode 120000 index 298c8872f9..0000000000 --- a/Lang/Seed7/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Quaternion-type b/Lang/Seed7/Quaternion-type deleted file mode 120000 index d621b24ce0..0000000000 --- a/Lang/Seed7/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Seed7 \ No newline at end of file diff --git a/Lang/Set-lang/Empty-program b/Lang/Set-lang/Empty-program deleted file mode 120000 index e6f84e5a85..0000000000 --- a/Lang/Set-lang/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Set-lang \ No newline at end of file diff --git a/Lang/Sidef/Empty-program b/Lang/Sidef/Empty-program deleted file mode 120000 index c7465e3077..0000000000 --- a/Lang/Sidef/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Meissel-Mertens-constant b/Lang/Sidef/Meissel-Mertens-constant deleted file mode 120000 index 7eda1518da..0000000000 --- a/Lang/Sidef/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Miller-Rabin-primality-test b/Lang/Sidef/Miller-Rabin-primality-test deleted file mode 120000 index 5bb5523a0e..0000000000 --- a/Lang/Sidef/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Quaternion-type b/Lang/Sidef/Quaternion-type deleted file mode 120000 index 5e28a5e41d..0000000000 --- a/Lang/Sidef/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Sorting-Algorithms-Circle-Sort b/Lang/Sidef/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index e866329cad..0000000000 --- a/Lang/Sidef/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Sidef \ No newline at end of file diff --git a/Lang/SimpleCode/Empty-program b/Lang/SimpleCode/Empty-program deleted file mode 120000 index dc55c70d09..0000000000 --- a/Lang/SimpleCode/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/SimpleCode \ No newline at end of file diff --git a/Lang/Slate/Empty-program b/Lang/Slate/Empty-program deleted file mode 120000 index cea8e90b74..0000000000 --- a/Lang/Slate/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Slate \ No newline at end of file diff --git a/Lang/Smalltalk/Miller-Rabin-primality-test b/Lang/Smalltalk/Miller-Rabin-primality-test deleted file mode 120000 index e3a303744d..0000000000 --- a/Lang/Smalltalk/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Smalltalk \ No newline at end of file diff --git a/Lang/Sparkling/Empty-program b/Lang/Sparkling/Empty-program deleted file mode 120000 index 519287810d..0000000000 --- a/Lang/Sparkling/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Sparkling \ No newline at end of file diff --git a/Lang/Standard-ML/Miller-Rabin-primality-test b/Lang/Standard-ML/Miller-Rabin-primality-test deleted file mode 120000 index ba4b002043..0000000000 --- a/Lang/Standard-ML/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Standard-ML \ No newline at end of file diff --git a/Lang/Swift/Bioinformatics-base-count b/Lang/Swift/Bioinformatics-base-count deleted file mode 120000 index c497b7a9fe..0000000000 --- a/Lang/Swift/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Swift \ No newline at end of file diff --git a/Lang/Swift/Empty-program b/Lang/Swift/Empty-program deleted file mode 120000 index 2c1baaa481..0000000000 --- a/Lang/Swift/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Swift \ No newline at end of file diff --git a/Lang/Swift/Miller-Rabin-primality-test b/Lang/Swift/Miller-Rabin-primality-test deleted file mode 120000 index 08a41b9961..0000000000 --- a/Lang/Swift/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Swift \ No newline at end of file diff --git a/Lang/Swift/Quaternion-type b/Lang/Swift/Quaternion-type deleted file mode 120000 index d74f88c4be..0000000000 --- a/Lang/Swift/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Swift \ No newline at end of file diff --git a/Lang/Swift/Sorting-Algorithms-Circle-Sort b/Lang/Swift/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 367310fdad..0000000000 --- a/Lang/Swift/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Swift \ No newline at end of file diff --git a/Lang/Symsyn/Empty-program b/Lang/Symsyn/Empty-program deleted file mode 120000 index 73cbdf1eb6..0000000000 --- a/Lang/Symsyn/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Symsyn \ No newline at end of file diff --git a/Lang/Tcl/Bioinformatics-base-count b/Lang/Tcl/Bioinformatics-base-count deleted file mode 120000 index 2d2ea8e987..0000000000 --- a/Lang/Tcl/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Miller-Rabin-primality-test b/Lang/Tcl/Miller-Rabin-primality-test deleted file mode 120000 index 5e3095425f..0000000000 --- a/Lang/Tcl/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Quaternion-type b/Lang/Tcl/Quaternion-type deleted file mode 120000 index 50905d75b8..0000000000 --- a/Lang/Tcl/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Tcl \ No newline at end of file diff --git a/Lang/Trith/Empty-program b/Lang/Trith/Empty-program deleted file mode 120000 index a3056b4a8b..0000000000 --- a/Lang/Trith/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Trith \ No newline at end of file diff --git a/Lang/True-BASIC/Meissel-Mertens-constant b/Lang/True-BASIC/Meissel-Mertens-constant deleted file mode 120000 index fd72ec2c53..0000000000 --- a/Lang/True-BASIC/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/True-BASIC \ No newline at end of file diff --git a/Lang/Uiua/00-LANG.txt b/Lang/Uiua/00-LANG.txt index 820e780454..f3cc2f1ee5 100644 --- a/Lang/Uiua/00-LANG.txt +++ b/Lang/Uiua/00-LANG.txt @@ -7,8 +7,9 @@ |LCT=yes}} {{language programming paradigm|array}} {{language programming paradigm|functional|array}} +From [https://www.uiua.org uiua.org]: -Uiua (''wee-wuh'') is a general purpose, stack-based, array-oriented programming language with a focus on simplicity, beauty, and tacit code. +"Uiua (''wee-wuh'') is a general purpose, stack-based, array-oriented programming language with a focus on simplicity, beauty, and tacit code. Uiua has a simple, context-free, LL(3) grammar. Code runs from right to left, top to bottom, with only one precedence rule. As operators are to the left of their operands, Uiua code reads a little bit like a Lisp, but with fewer parentheses. @@ -18,7 +19,10 @@ Uiua's one and only composite data type, the array, is based on those of APL, J, Unlike other array languages, Uiua does not have monadic and dyadic versions of each glyph. Every glyph does only one thing, so you don't need to parse an entire expression to know which version it is. -Find out more, and run code in your browser at https://www.uiua.org +Find out more, and run code in your browser at [https://www.uiua.org https://www.uiua.org]." + +===Note=== +The Uiua programming language uses a custom font and colorful syntax highlighting to increase the readability of its code. As such syntax highlighting is not possible to display on this wiki, it is recommended to paste code into [https://www.uiua.org/pad the online Uiua pad] (or a [https://www.uiua.org/install#editor-support supported editor]) to view code more easily. ==Todo== [https://rosettacode.org/wiki/Tasks_not_implemented_in_Uiua Tasks not implemented in Uiua] \ No newline at end of file diff --git a/Lang/UnixPipes/00-LANG.txt b/Lang/UnixPipes/00-LANG.txt index 8a315a0473..421b024690 100644 --- a/Lang/UnixPipes/00-LANG.txt +++ b/Lang/UnixPipes/00-LANG.txt @@ -13,7 +13,7 @@ Using utilities from, [http://packages.debian.org/unstable/utils/moreutils moreu Defining unfold as the opposite of xargs, i.e take a list of arguments and send them one at a time. The definition would be - + |cat unfold num=$1 while read xxx; do @@ -27,7 +27,7 @@ done 4 5 6 7 8 - + == Deleted solutions == We delete a UnixPipes solution when it is too similar to its UNIX Shell equivalent, or when it is incorrect (but the UNIX Shell solution is correct). diff --git a/Lang/Uxntal/Bioinformatics-base-count b/Lang/Uxntal/Bioinformatics-base-count deleted file mode 120000 index f9af105afe..0000000000 --- a/Lang/Uxntal/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Uxntal \ No newline at end of file diff --git a/Lang/V-(Vlang)/00-LANG.txt b/Lang/V-(Vlang)/00-LANG.txt index d8ee4e2c69..56c1cc8279 100644 --- a/Lang/V-(Vlang)/00-LANG.txt +++ b/Lang/V-(Vlang)/00-LANG.txt @@ -21,13 +21,15 @@ V is an easier to learn, read, and use language. [https://vlang.io V] first appeared in 2019 in a trial web sandbox, "The V Playground". -V's design has been influenced by Go, Oberon, Rust, Swift, Kotlin, and Python. [https://github.com/vlang/v/wiki/FAQ For V's FAQ] +V's design and history has been influenced by Go, C, Oberon, Rust, Swift, Kotlin, and Python. -V's sources are published at [https://github.com/vlang/v GitHub], presently on version [https://github.com/vlang/v/releases 0.4.x]. +V's sources are published at [https://github.com/vlang/v GitHub], presently on version [https://github.com/vlang/v/releases 0.5.x]. + +V's [https://github.com/vlang/v/wiki/FAQ FAQ] and [https://github.com/vlang/v/blob/master/ROADMAP.md roadmap] to see its validity, promise, and delivery of features. V's compiler tool is similar in implementation to a multi purpose command processor: ''prompt$ v help'' -V language review and documentation are [https://github.com/vlang/v/blob/master/doc/docs.md here]. +V language review and documentation is [https://github.com/vlang/v/blob/master/doc/docs.md here] for the professional, student, or as a hobby. ==Helpful links== * [https://en.everybodywiki.com/V_(programming_language) V in Wiki] @@ -35,6 +37,7 @@ V language review and documentation are [https://github.com/vlang/v/blob/master/ * [https://www.youtube.com/watch?v=pchEsYwA74Q V language overview and introduction] on behalf of the Sydney Computing Society * [https://www.youtube.com/watch?v=_dIAcNp9bJs V language overview and presentation] for IBM * Some of the code snippets are available at the archived [//github.com/v-community/v_rosetta V-Community (V Rosetta) GitHub] +* For venturing into how to contribute, join, or help the V project can be found [https://github.com/vlang/v/blob/master/CONTRIBUTING.md#how-to-help-and-contribute-to-the-v-project here]. * More info on the below can be found at [https://modules.vlang.io/ modules used by V] {| class="wikitable" diff --git a/Lang/V-(Vlang)/Bioinformatics-base-count b/Lang/V-(Vlang)/Bioinformatics-base-count deleted file mode 120000 index 93867218eb..0000000000 --- a/Lang/V-(Vlang)/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/V-(Vlang) \ No newline at end of file diff --git a/Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort b/Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 90876b0ca9..0000000000 --- a/Lang/V-(Vlang)/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/V-(Vlang) \ No newline at end of file diff --git a/Lang/VBA/Quaternion-type b/Lang/VBA/Quaternion-type deleted file mode 120000 index b9d823193e..0000000000 --- a/Lang/VBA/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/VBA \ No newline at end of file diff --git a/Lang/VBScript/Bioinformatics-base-count b/Lang/VBScript/Bioinformatics-base-count deleted file mode 120000 index 27b49dfc57..0000000000 --- a/Lang/VBScript/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/VBScript \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Quaternion-type b/Lang/Visual-Basic-.NET/Quaternion-type deleted file mode 120000 index 111784d7c2..0000000000 --- a/Lang/Visual-Basic-.NET/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Wee-Basic/Empty-program b/Lang/Wee-Basic/Empty-program deleted file mode 120000 index 132197773e..0000000000 --- a/Lang/Wee-Basic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Wee-Basic \ No newline at end of file diff --git a/Lang/Wren/Bioinformatics-base-count b/Lang/Wren/Bioinformatics-base-count deleted file mode 120000 index 620c92bb71..0000000000 --- a/Lang/Wren/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Wren \ No newline at end of file diff --git a/Lang/Wren/Empty-program b/Lang/Wren/Empty-program deleted file mode 120000 index e0842518a1..0000000000 --- a/Lang/Wren/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Wren \ No newline at end of file diff --git a/Lang/Wren/Meissel-Mertens-constant b/Lang/Wren/Meissel-Mertens-constant deleted file mode 120000 index 2a9c71a439..0000000000 --- a/Lang/Wren/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Wren \ No newline at end of file diff --git a/Lang/Wren/Miller-Rabin-primality-test b/Lang/Wren/Miller-Rabin-primality-test deleted file mode 120000 index 26f77867d2..0000000000 --- a/Lang/Wren/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Wren \ No newline at end of file diff --git a/Lang/Wren/Quaternion-type b/Lang/Wren/Quaternion-type deleted file mode 120000 index 42a26f0111..0000000000 --- a/Lang/Wren/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Wren \ No newline at end of file diff --git a/Lang/Wren/Sorting-Algorithms-Circle-Sort b/Lang/Wren/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 3d8f8916cb..0000000000 --- a/Lang/Wren/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Wren \ No newline at end of file diff --git a/Lang/X86-64-Assembly/Miller-Rabin-primality-test b/Lang/X86-64-Assembly/Miller-Rabin-primality-test deleted file mode 120000 index 0607272f30..0000000000 --- a/Lang/X86-64-Assembly/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/X86-64-Assembly \ No newline at end of file diff --git a/Lang/XPL0/Bioinformatics-base-count b/Lang/XPL0/Bioinformatics-base-count deleted file mode 120000 index 485c648b6c..0000000000 --- a/Lang/XPL0/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Meissel-Mertens-constant b/Lang/XPL0/Meissel-Mertens-constant deleted file mode 120000 index 8f73d24896..0000000000 --- a/Lang/XPL0/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Quaternion-type b/Lang/XPL0/Quaternion-type deleted file mode 120000 index 03ac35a45d..0000000000 --- a/Lang/XPL0/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Sorting-Algorithms-Circle-Sort b/Lang/XPL0/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index a68d7b0426..0000000000 --- a/Lang/XPL0/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/XPL0 \ No newline at end of file diff --git a/Lang/YAMLScript/00-LANG.txt b/Lang/YAMLScript/00-LANG.txt index 53f8a21c4a..7e44330500 100644 --- a/Lang/YAMLScript/00-LANG.txt +++ b/Lang/YAMLScript/00-LANG.txt @@ -49,4 +49,67 @@ Test the new installation: -e, --eval YSEXPR Evaluate a YS expression ... -See https://yamlscript.org for more information. \ No newline at end of file +See https://yamlscript.org for more information. + +==Adding YS Entries to Rosetta Code== + +Here's a YS program that you can use to format a YS program and it's output to a MediaWiki text to insert into a Rosetta Code task page: + +
    +#!/usr/bin/env ys-0
    +
    +# Create a Rosetta Code entry for a YS program:
    +
    +defn main(program *args):
    +  say: |-
    +
    +    =={{header|YAMLScript}}==
    +    
    +    $chomp(program:read)
    +    
    +
    +  when-not ENV.NO_OUT.?:
    +    command =: "ys $program$fmt-args(args)"
    +    output =: bash(command).out:chomp
    +    say: |-
    +
    +      {{out}}
    +      
    +      $ $command
    +      $output
    +      </pre>
    +
    +defn fmt-args(args):
    +  args =: !:joins
    +    map _ args:
    +      \(re-matches(/[-+,.:\w]+/ _:S)
    +        .if(_ pr-str(_)))
    +  when args.?: " $args"
    +
    + +You run it like this: + +
    +$ ys rosetta-code-ys-entry fibonacci-sequence.ys 5
    +
    +=={{header|YAMLScript}}==
    +
    +!YS-v0
    +
    +defn main(n=10):
    +  loop a 0, b 1, i 1:
    +    say: a
    +    when i < n:
    +      recur: b, (a + b), i.++
    +
    +
    +{{out}}
    +
    +$ ys fibonacci-sequence.ys 5
    +0
    +1
    +1
    +2
    +3
    +</pre>
    +
    \ No newline at end of file diff --git a/Lang/Yabasic/Empty-program b/Lang/Yabasic/Empty-program deleted file mode 120000 index 86460983fb..0000000000 --- a/Lang/Yabasic/Empty-program +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-program/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/Meissel-Mertens-constant b/Lang/Yabasic/Meissel-Mertens-constant deleted file mode 120000 index 2300a0e96d..0000000000 --- a/Lang/Yabasic/Meissel-Mertens-constant +++ /dev/null @@ -1 +0,0 @@ -../../Task/Meissel-Mertens-constant/Yabasic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort b/Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index c34f35480d..0000000000 --- a/Lang/ZX-Spectrum-Basic/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/Zkl/Bioinformatics-base-count b/Lang/Zkl/Bioinformatics-base-count deleted file mode 120000 index f344937ca4..0000000000 --- a/Lang/Zkl/Bioinformatics-base-count +++ /dev/null @@ -1 +0,0 @@ -../../Task/Bioinformatics-base-count/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Miller-Rabin-primality-test b/Lang/Zkl/Miller-Rabin-primality-test deleted file mode 120000 index 92bfcfa6ff..0000000000 --- a/Lang/Zkl/Miller-Rabin-primality-test +++ /dev/null @@ -1 +0,0 @@ -../../Task/Miller-Rabin-primality-test/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Quaternion-type b/Lang/Zkl/Quaternion-type deleted file mode 120000 index d36f19dd00..0000000000 --- a/Lang/Zkl/Quaternion-type +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quaternion-type/Zkl \ No newline at end of file diff --git a/Lang/Zkl/Sorting-Algorithms-Circle-Sort b/Lang/Zkl/Sorting-Algorithms-Circle-Sort deleted file mode 120000 index 6de597a14d..0000000000 --- a/Lang/Zkl/Sorting-Algorithms-Circle-Sort +++ /dev/null @@ -1 +0,0 @@ -../../Task/Sorting-Algorithms-Circle-Sort/Zkl \ No newline at end of file diff --git a/Lang/Zonnon/00-LANG.txt b/Lang/Zonnon/00-LANG.txt index 8a95e192c9..e4a45b3fa4 100644 --- a/Lang/Zonnon/00-LANG.txt +++ b/Lang/Zonnon/00-LANG.txt @@ -3,4 +3,11 @@ |site=http://www.zonnon.ethz.ch/ |LCT=yes }} -Zonnon is a general-purpose programming language in the [[Pascal]], [[Modula-2]] and [[Oberon]] family. It retains an emphasis on simplicity, clear syntax and separation of concerns whilst focusing on concurrency and ease of composition and expression. Unification of abstractions is at the heart of its design and this is reflected in its conceptual model based on modules, objects, definitions and implementations. Zonnon offers a new computing model based on active objects with their interaction defined by syntax controlled dialogs. It also introduces new features including operator overloading and exception handling, and is specifically designed to be platform independent. \ No newline at end of file +Zonnon is a general-purpose programming language in the [[Pascal]], [[Modula-2]] and [[Oberon]] family. It retains an emphasis on simplicity, clear syntax and separation of concerns whilst focusing on concurrency and ease of composition and expression. Unification of abstractions is at the heart of its design and this is reflected in its conceptual model based on modules, objects, definitions and implementations. Zonnon offers a new computing model based on active objects with their interaction defined by syntax controlled dialogs. It also introduces new features including operator overloading and exception handling, and is specifically designed to be platform independent. + +===See also=== +* [[Oberon-07]] +* [[Oberon-2]] +* [[Component Pascal]] +* [[Modula-2]] +* [[Modula-3]] \ No newline at end of file diff --git a/Task/100-doors/11l/100-doors.11l b/Task/100-doors/11l/100-doors.11l index 3783f3ff5a..2808744415 100644 --- a/Task/100-doors/11l/100-doors.11l +++ b/Task/100-doors/11l/100-doors.11l @@ -1,5 +1,5 @@ V doors = [0B] * 100 -L(i) 100 +L(i) 0.<100 L(j) (i .< 100).step(i + 1) doors[j] = !doors[j] print(‘Door ’(i + 1)‘: ’(I doors[i] {‘open’} E ‘close’)) diff --git a/Task/100-doors/8080-Assembly/100-doors-2.8080 b/Task/100-doors/8080-Assembly/100-doors-2.8080 index 48acc304f5..d5cb28c55f 100644 --- a/Task/100-doors/8080-Assembly/100-doors-2.8080 +++ b/Task/100-doors/8080-Assembly/100-doors-2.8080 @@ -1,58 +1,45 @@ - ;------------------------------------------------------ - ; useful equates - ;------------------------------------------------------ wboot equ 0 ; jump to BIOS warm boot routine -bdos equ 5 ; BDOS entry -conout equ 2 ; BDOS console output function +bdos equ 5 ; BDOS entry +conout equ 2 ; BDOS console output function putstr equ 9 ; BDOS print string function -ndoors equ 100 +ndoors equ 100 ; number of doors ; org 100h lxi sp,stack ; set our own stack - lxi d,signon ; print signon message + lxi d,intro ; print introductory message mvi c,putstr - call bdos + call bdos ; - ; generate sequence of squares from 1 to specified limit + ; generate sequence of squares to specified limit + ; HL holds the current square + ; DE holds the increment + ; BC holds the negative of the limit ; -gensqr: - lxi h,1 ; starting value of square +gensqr: lxi h,1 ; starting value of square lxi d,3 ; starting value of increment - lxi b,ndoors+1 -sqrs2: - call cmpbchl ; have we exceeded the limit? - jnc done ; we're finished - call putdec ; otherwise print current square - mvi a,' ' ; separate with a space - call putchr - dad d ; square += incrememnt - inx d ; increment += 2 + lxi b,-ndoors +sqrs2: call putdec ; otherwise print current square + mvi a,' ' ; separate with a space + call putchr + push h ; have we reached the limit? + dad b + pop h + jc done ; CY if HL > limit + dad d ; square += incrememnt + inx d ; increment += 2 inx d - jmp sqrs2 ; repeat until finished + jmp sqrs2 ; repeat until finished ; -done: jmp wboot ; exit to command prompt - ; - ;--------------------------------------------------- - ; 16-bit unsigned comparison of HL and BC - ; if HL = BC then Z flag set - ; if HL < BC then CY flag set (NC if HL >= BC) - ;------------------------------------------------------ -cmpbchl: - mov a,h - cmp b - rnz - mov a,l - cmp c - ret +done: jmp wboot ; exit with warm boot ;--------------------------------------------------- ; console output of char in A register ;--------------------------------------------------- -putchr: push h - push d - push b +putchr: push h + push d + push b mov e,a mvi c,conout - call bdos + call bdos pop b pop d pop h @@ -61,9 +48,9 @@ putchr: push h ; Output decimal number to console ; HL holds 16-bit unsigned binary number to print ;--------------------------------------------------- -putdec: push b - push d - push h +putdec: push b + push d + push h lxi b,-10 lxi d,-1 putdec2: @@ -78,7 +65,7 @@ putdec2: cnz putdec ; recursive call mov a,e adi '0' - call putchr + call putchr pop h pop d pop b @@ -86,7 +73,7 @@ putdec2: ;--------------------------------------------------- ; data area and stack ;--------------------------------------------------- -signon: db 'The open doors are: $' +intro: db 'The open doors are: $' stack equ $+128 ; 64-level stack ; end diff --git a/Task/100-doors/Ada/100-doors-1.ada b/Task/100-doors/Ada/100-doors-1.ada deleted file mode 100644 index fd746501f2..0000000000 --- a/Task/100-doors/Ada/100-doors-1.ada +++ /dev/null @@ -1,22 +0,0 @@ -with Ada.Text_Io; use Ada.Text_Io; - - procedure Doors is - type Door_State is (Closed, Open); - type Door_List is array(Positive range 1..100) of Door_State; - The_Doors : Door_List := (others => Closed); - begin - for I in 1..100 loop - for J in The_Doors'range loop - if J mod I = 0 then - if The_Doors(J) = Closed then - The_Doors(J) := Open; - else - The_Doors(J) := Closed; - end if; - end if; - end loop; - end loop; - for I in The_Doors'range loop - Put_Line(Integer'Image(I) & " is " & Door_State'Image(The_Doors(I))); - end loop; - end Doors; diff --git a/Task/100-doors/Ada/100-doors-2.ada b/Task/100-doors/Ada/100-doors-2.ada deleted file mode 100644 index 0af233cef5..0000000000 --- a/Task/100-doors/Ada/100-doors-2.ada +++ /dev/null @@ -1,16 +0,0 @@ -with Ada.Text_Io; use Ada.Text_Io; - with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; - - procedure Doors_Optimized is - Num : Float; - begin - for I in 1..100 loop - Num := Sqrt(Float(I)); - Put(Integer'Image(I) & " is "); - if Float'Floor(Num) = Num then - Put_Line("Opened"); - else - Put_Line("Closed"); - end if; - end loop; - end Doors_Optimized; diff --git a/Task/100-doors/Agena/100-doors.agena b/Task/100-doors/Agena/100-doors.agena deleted file mode 100644 index 18c9cb1963..0000000000 --- a/Task/100-doors/Agena/100-doors.agena +++ /dev/null @@ -1,19 +0,0 @@ -# find the first few squares via the unoptimised door flipping method -scope - - local doorMax := 100; - local door; - create register door( doorMax ); - - # set all doors to closed - for i to doorMax do door[ i ] := false od; - - # repeatedly flip the doors - for i to doorMax do - for j from i to doorMax by i do door[ j ] := not door[ j ] od - od; - - # display the results - for i to doorMax do if door[ i ] then write( " ", i ) fi od; print() - -epocs diff --git a/Task/100-doors/AutoIt/100-doors.autoit b/Task/100-doors/AutoIt/100-doors.autoit deleted file mode 100644 index d8988366c6..0000000000 --- a/Task/100-doors/AutoIt/100-doors.autoit +++ /dev/null @@ -1,17 +0,0 @@ -#include -$doors = 100 - -;door array, 0 = closed, 1 = open -Local $door[$doors +1] - -For $ii = 1 To $doors - For $i = $ii To $doors Step $ii - $door[$i] = Not $door[$i] - next -Next - -;display to screen -For $i = 1 To $doors - ConsoleWrite (Number($door[$i])& " ") - If Mod($i,10) = 0 Then ConsoleWrite(@CRLF) -Next diff --git a/Task/100-doors/AutoLISP/100-doors.l b/Task/100-doors/AutoLISP/100-doors.l deleted file mode 100644 index d4a0ebbe77..0000000000 --- a/Task/100-doors/AutoLISP/100-doors.l +++ /dev/null @@ -1,18 +0,0 @@ -(defun CreateDoors (n / doors) - (repeat n - (setq doors (cons nil doors)) - ) -) - -(defun Doors (doors / cnt) - (setq cnt 0) - (mapcar - '(lambda (d) - (zerop (rem (sqrt (setq cnt (1+ cnt))) 1)) - ) - doors - ) -) - -> (Doors (CreateDoors 100)) -(T nil nil T nil nil nil nil T nil nil nil nil nil nil T nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil nil T nil nil nil nil) diff --git a/Task/100-doors/COBOL/100-doors.cobol b/Task/100-doors/COBOL/100-doors.cobol deleted file mode 100644 index c33e3bb962..0000000000 --- a/Task/100-doors/COBOL/100-doors.cobol +++ /dev/null @@ -1,33 +0,0 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. 100Doors. - - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 Current-n PIC 9(3). - 01 StepSize PIC 9(3). - 01 DoorTable. - 02 Doors PIC 9(1) OCCURS 100 TIMES. - 88 ClosedDoor VALUE ZERO. - 01 Idx PIC 9(3). - - PROCEDURE DIVISION. - Begin. - INITIALIZE DoorTable - PERFORM VARYING StepSize FROM 1 BY 1 UNTIL StepSize > 100 - PERFORM VARYING Current-n FROM StepSize BY StepSize - UNTIL Current-n > 100 - SUBTRACT Doors (Current-n) FROM 1 GIVING Doors (Current-n) - END-PERFORM - END-PERFORM - - PERFORM VARYING Idx FROM 1 BY 1 - UNTIL Idx > 100 - IF ClosedDoor (Idx) - DISPLAY Idx " is closed." - ELSE - DISPLAY Idx " is open." - END-IF - END-PERFORM - - STOP RUN - . diff --git a/Task/100-doors/Coq/100-doors-1.coq b/Task/100-doors/Coq/100-doors-1.coq deleted file mode 100644 index a37db1f5d0..0000000000 --- a/Task/100-doors/Coq/100-doors-1.coq +++ /dev/null @@ -1,26 +0,0 @@ -Require Import List. - -Fixpoint rep {A} (a : A) n := - match n with - | O => nil - | S n' => a::(rep a n') - end. - -Fixpoint flip (l : list bool) (n k : nat) : list bool := - match l with - | nil => nil - | cons h t => match k with - | O => (negb h) :: (flip t n n) - | S k' => h :: (flip t n k') - end - end. - -Definition flipeach l n := flip l n n. - -Fixpoint flipwhile l n := - match n with - | O => flipeach l 0 - | S n' => flipwhile (flipeach l (S n')) n' - end. - -Definition prison cells := flipwhile (rep false cells) cells. diff --git a/Task/100-doors/Coq/100-doors-2.coq b/Task/100-doors/Coq/100-doors-2.coq deleted file mode 100644 index c3f1f1158f..0000000000 --- a/Task/100-doors/Coq/100-doors-2.coq +++ /dev/null @@ -1,13 +0,0 @@ -Require Import List. - -Fixpoint prisoo' nd n k accu := - match nd with - | O => rev accu - | S nd' => let ra := match k with - | O => (true, S n, (n + n)) - | S k' => (false, n, k') - end in - prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu) - end. - -Definition prisoo cells := prisoo' cells 1 0 nil. diff --git a/Task/100-doors/Coq/100-doors-3.coq b/Task/100-doors/Coq/100-doors-3.coq deleted file mode 100644 index 56df2e7103..0000000000 --- a/Task/100-doors/Coq/100-doors-3.coq +++ /dev/null @@ -1 +0,0 @@ -Goal prison 100 = prisoo 100. compute. reflexivity. Qed. diff --git a/Task/100-doors/Coq/100-doors-4.coq b/Task/100-doors/Coq/100-doors-4.coq deleted file mode 100644 index c469094c8e..0000000000 --- a/Task/100-doors/Coq/100-doors-4.coq +++ /dev/null @@ -1 +0,0 @@ -Goal forall n, prison n = prisoo n. Abort. diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena index dd7db1e5c7..b376bcd9da 100644 --- a/Task/100-doors/Elena/100-doors.elena +++ b/Task/100-doors/Elena/100-doors.elena @@ -1,7 +1,7 @@ import system'routines; import extensions; -public program() +public Program() { var Doors := Array.allocate(100).populate::(n=>false); for(int i := 0; i < 100; i++) diff --git a/Task/100-doors/Emacs-Lisp/100-doors-1.l b/Task/100-doors/Emacs-Lisp/100-doors-1.l deleted file mode 100644 index 518fbd4193..0000000000 --- a/Task/100-doors/Emacs-Lisp/100-doors-1.l +++ /dev/null @@ -1,83 +0,0 @@ -(defun create-doors () - "Returns a list of closed doors - -Each door only has two status: open or closed. -If a door is closed it has the value 0, if it's open it has the value 1." - (let ((return_value '(0)) - ;; There is already a door in the return_value, so k starts at 1 - ;; otherwise we would need to compare k against 99 and not 100 in - ;; the while loop - (k 1)) - (while (< k 100) - (setq return_value (cons 0 return_value)) - (setq k (+ 1 k))) - return_value)) - -(defun toggle-single-door (doors) - "Toggle the stat of the door at the `car' position of the DOORS list - -DOORS is a list of integers with either the value 0 or 1 and it represents -a row of doors. - -Returns a list where the `car' of the list has it's value toggled (if open -it becomes closed, if closed it becomes open)." - (if (= (car doors) 1) - (cons 0 (cdr doors)) - (cons 1 (cdr doors)))) - -(defun toggle-doors (doors step original-step) - "Step through all elements of the doors' list and toggle a door when step is 1 - -DOORS is a list of integers with either the value 0 or 1 and it represents -a row of doors. -STEP is the number of doors we still need to transverse before we arrive -at a door that has to be toggled. -ORIGINAL-STEP is the value of the argument step when this function is -called for the first time. - -Returns a list of doors" - (cond ((null doors) - '()) - ((= step 1) - (cons (car (toggle-single-door doors)) - (toggle-doors (cdr doors) original-step original-step))) - (t - (cons (car doors) - (toggle-doors (cdr doors) (- step 1) original-step))))) - -(defun main-program () - "The main loop for the program" - (let ((doors_list (create-doors)) - (k 1) - ;; We need to define max-specpdl-size and max-specpdl-size to big - ;; numbers otherwise the loop reaches the max recursion depth and - ;; throws an error. - ;; If you want more information about these variables, press Ctrl - ;; and h at the same time and then press v and then type the name - ;; of the variable that you want to read the documentation. - (max-specpdl-size 5000) - (max-lisp-eval-depth 2000)) - (while (< k 101) - (setq doors_list (toggle-doors doors_list k k)) - (setq k (+ 1 k))) - doors_list)) - -(defun print-doors (doors) - "This function prints the values of the doors into the current buffer. - -DOORS is a list of integers with either the value 0 or 1 and it represents -a row of doors. -" - ;; As in the main-program function, we need to set the variable - ;; max-lisp-eval-depth to a big number so it doesn't reach max recursion - ;; depth. - (let ((max-lisp-eval-depth 5000)) - (unless (null doors) - (insert (int-to-string (car doors))) - (print-doors (cdr doors))))) - -;; Returns a list with the final solution -(main-program) - -;; Print the final solution on the buffer -(print-doors (main-program)) diff --git a/Task/100-doors/Emacs-Lisp/100-doors-2.l b/Task/100-doors/Emacs-Lisp/100-doors-2.l deleted file mode 100644 index 66b2cff437..0000000000 --- a/Task/100-doors/Emacs-Lisp/100-doors-2.l +++ /dev/null @@ -1,16 +0,0 @@ -(defun one-hundred-doors(initial-state) - "Turn doors in INITIAL-STATE according to 100 Doors problem." - (interactive "nEnter initial doors' state (as a number): ") - (cl-loop for x from 1 to 100 - do (cl-loop for y from (1- x) to 99 by x - do (setq initial-state (logxor initial-state (ash 1 y))))) - (let ((counter 1) - (open-doors nil)) - (while (> initial-state 0) - (when (eq (mod initial-state 2) 1) - (push counter open-doors)) - (cl-incf counter) - (setq initial-state (/ initial-state 2))) - (message "Open doors are %s" (reverse open-doors)))) - -(one-hundred-doors 0) diff --git a/Task/100-doors/Euphoria/100-doors.ex b/Task/100-doors/Euphoria/100-doors.ex deleted file mode 100644 index 989e2a7ae4..0000000000 --- a/Task/100-doors/Euphoria/100-doors.ex +++ /dev/null @@ -1,23 +0,0 @@ --- doors.ex -include std/console.e -sequence doors -doors = repeat( 0, 100 ) -- 1 to 100, initialised to false - -for pass = 1 to 100 do - for door = pass to 100 by pass do - --printf( 1, "%d", doors[door] ) - --printf( 1, "%d", not doors[door] ) - doors[door] = not doors[door] - end for -end for - -sequence oc - -for i = 1 to 100 do - if doors[i] then - oc = "open" - else - oc = "closed" - end if - printf( 1, "door %d is %s\n", { i, oc } ) -end for diff --git a/Task/100-doors/Haxe/100-doors-1.haxe b/Task/100-doors/Haxe/100-doors-1.haxe deleted file mode 100644 index f4cab3c8b8..0000000000 --- a/Task/100-doors/Haxe/100-doors-1.haxe +++ /dev/null @@ -1,23 +0,0 @@ -class Main -{ - static public function main() - { - findOpenDoors( 100 ); - } - - static function findOpenDoors( n : Int ) - { - var door = []; - for( i in 0...n + 1 ){ door[ i ] = false; } - for( i in 1...n + 1 ){ - var j = i; - while( j <= n ){ - door[ j ] = ! door[ j ]; - j += i; - } - } - for( i in 1...n + 1 ){ - if( door[ i ] ){ Sys.print( ' $i' ); } - } - } -} diff --git a/Task/100-doors/Haxe/100-doors-2.haxe b/Task/100-doors/Haxe/100-doors-2.haxe deleted file mode 100644 index 30853b01fb..0000000000 --- a/Task/100-doors/Haxe/100-doors-2.haxe +++ /dev/null @@ -1,18 +0,0 @@ -class RosettaDemo -{ - static public function main() - { - findOpenLockers(100); - } - - static function findOpenLockers(n : Int) - { - var i = 1; - - while((i*i) <= n) - { - Sys.println(i*i); - i++; - } - } -} diff --git a/Task/100-doors/Informix-4GL/100-doors-2.4gl b/Task/100-doors/Informix-4GL/100-doors-2.4gl index 77483d70d0..6a8949775e 100644 --- a/Task/100-doors/Informix-4GL/100-doors-2.4gl +++ b/Task/100-doors/Informix-4GL/100-doors-2.4gl @@ -2,7 +2,7 @@ (for i (range 1 101) i2 (range (dec i) 100 i) - (var! doors (set-at [i2] (! (i2 doors)))) + (var! doors (set-at [i2] (not (i2 doors)))) (continue)) (-> (xmap vec doors) diff --git a/Task/100-doors/OPL/100-doors.opl b/Task/100-doors/OPL/100-doors.opl index e5026a3076..097dc00ccd 100644 --- a/Task/100-doors/OPL/100-doors.opl +++ b/Task/100-doors/OPL/100-doors.opl @@ -1,9 +1,4 @@ -REM Author.....: Eva Broccoli -REM Date.......: 23 May 2025 -REM Description: OPL solution for "100 doors" task on https://rosettacode.org -REM Tested with: Psion Series 3a & Series 5 -REM Contact....: eva.klassen@kittymail.com - +REM https://github.com/Eva-Broccoli/OPL-Rosetta-Code/blob/main/A100door.opl PROC main: LOCAL door%(100),i%,j% i%=1 diff --git a/Task/100-doors/Odin/100-doors-1.odin b/Task/100-doors/Odin/100-doors-1.odin index b4fcc95bd6..7169d3893a 100644 --- a/Task/100-doors/Odin/100-doors-1.odin +++ b/Task/100-doors/Odin/100-doors-1.odin @@ -1,24 +1,22 @@ -package main +package doors import "core:fmt" main :: proc() { - using fmt + doors: [100]bool - Door_State :: enum {Closed, Open} + for every_n := 1; every_n < len(doors); every_n += 1 { + i := every_n - 1 + for true { + if i >= len(doors) do break - doors := [?]Door_State { 0..<100 = .Closed } + doors[i] = !doors[i] - for i in 1..=100 { - for j := i-1; j < 100; j += i { - if doors[j] == .Closed { - doors[j] = .Open - } else { - doors[j] = .Closed - } - } - } - for state, i in doors { - println("Door: ",int(i+1)," -> ",state) - } + i += every_n + } + } + + for &door, i in doors { + if door do fmt.printf("%d ", i + 1) + } } diff --git a/Task/100-doors/Odin/100-doors-2.odin b/Task/100-doors/Odin/100-doors-2.odin index 77e9cd99ef..b4fcc95bd6 100644 --- a/Task/100-doors/Odin/100-doors-2.odin +++ b/Task/100-doors/Odin/100-doors-2.odin @@ -1,7 +1,6 @@ package main import "core:fmt" -import "core:math" main :: proc() { using fmt @@ -11,12 +10,15 @@ main :: proc() { doors := [?]Door_State { 0..<100 = .Closed } for i in 1..=100 { - res := math.sqrt_f64( f64(i) ) - if math.mod_f64( res, 1) == 0 { - doors[i-1] = .Open - } else { - doors[i-1] = .Closed - } - println("Door: ", i, " -> ", doors[i-1]) + for j := i-1; j < 100; j += i { + if doors[j] == .Closed { + doors[j] = .Open + } else { + doors[j] = .Closed + } + } + } + for state, i in doors { + println("Door: ",int(i+1)," -> ",state) } } diff --git a/Task/100-doors/PowerShell/100-doors-1.psh b/Task/100-doors/PowerShell/100-doors-1.psh deleted file mode 100644 index 816268d1b7..0000000000 --- a/Task/100-doors/PowerShell/100-doors-1.psh +++ /dev/null @@ -1,14 +0,0 @@ -$doors = @(0..99) -for($i=0; $i -lt 100; $i++) { - $doors[$i] = 0 # start with all doors closed -} -for($i=0; $i -lt 100; $i++) { - $step = $i + 1 - for($j=$i; $j -lt 100; $j = $j + $step) { - $doors[$j] = $doors[$j] -bxor 1 - } -} -foreach($doornum in 1..100) { - if($doors[($doornum-1)] -eq $true) {"$doornum open"} - else {"$doornum closed"} -} diff --git a/Task/100-doors/PowerShell/100-doors-2.psh b/Task/100-doors/PowerShell/100-doors-2.psh deleted file mode 100644 index 896a25e1fb..0000000000 --- a/Task/100-doors/PowerShell/100-doors-2.psh +++ /dev/null @@ -1,37 +0,0 @@ -function Get-DoorState($NumberOfDoors) -{ - begin - { - $Doors = @() - $Multiple = 1 - } - - process - { - for ($i = 1; $i -le $NumberOfDoors; $i++) - { - $Door = [pscustomobject]@{ - Name = $i - Open = $false - } - - $Doors += $Door - } - - While ($Multiple -le $NumberOfDoors) - { - Foreach ($Door in $Doors) - { - if ($Door.name % $Multiple -eq 0) - { - If ($Door.open -eq $False){$Door.open = $True} - Else {$Door.open = $False} - } - } - - $Multiple++ - } - } - - end {$Doors} -} diff --git a/Task/100-doors/PowerShell/100-doors-3.psh b/Task/100-doors/PowerShell/100-doors-3.psh deleted file mode 100644 index acc1a5f397..0000000000 --- a/Task/100-doors/PowerShell/100-doors-3.psh +++ /dev/null @@ -1,2 +0,0 @@ -$doors = 1..100 | ForEach-Object {0} -1..100 | ForEach-Object { $a=$_;1..100 | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1 }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } } diff --git a/Task/100-doors/PowerShell/100-doors-4.psh b/Task/100-doors/PowerShell/100-doors-4.psh deleted file mode 100644 index c7903f1a70..0000000000 --- a/Task/100-doors/PowerShell/100-doors-4.psh +++ /dev/null @@ -1,3 +0,0 @@ -$doors = 1..100 | ForEach-Object {0} -$visited = 1..100 -1..100 | ForEach-Object { $a=$_;$visited[0..([math]::floor(100/$a)-1)] | Where-Object { -not ( $_ % $a ) } | ForEach-Object { $doors[$_-1] = $doors[$_-1] -bxor 1;$visited[$_/$a-1]+=($_/$a) }; if ( $doors[$a-1] ) { "door opened" } else { "door closed" } } diff --git a/Task/100-doors/PowerShell/100-doors-5.psh b/Task/100-doors/PowerShell/100-doors-5.psh deleted file mode 100644 index 9012ac03a5..0000000000 --- a/Task/100-doors/PowerShell/100-doors-5.psh +++ /dev/null @@ -1,3 +0,0 @@ -1..100|foreach-object {$pipe += "toggle $_ |"} -begin {$pipe=""} -filter toggle($pass) {$_.door = $_.door -xor !($_.index % $pass);$_} -invoke-expression "1..100| foreach-object {@{index=`$_;door=`$false}} | $pipe out-host" diff --git a/Task/100-doors/PowerShell/100-doors-6.psh b/Task/100-doors/PowerShell/100-doors-6.psh deleted file mode 100644 index fc185f3853..0000000000 --- a/Task/100-doors/PowerShell/100-doors-6.psh +++ /dev/null @@ -1,6 +0,0 @@ -Workflow Calc-Doors { - Foreach –parallel ($number in 1..100) { - "Door " + $number.ToString("0000") + ": " + @{$true="Closed";$false="Open"}[([Math]::pow($number, 0.5)%1) -ne 0] - } -} -Calc-Doors | sort diff --git a/Task/100-doors/PowerShell/100-doors-7.psh b/Task/100-doors/PowerShell/100-doors-7.psh deleted file mode 100644 index 1714f382c9..0000000000 --- a/Task/100-doors/PowerShell/100-doors-7.psh +++ /dev/null @@ -1 +0,0 @@ -1..10|%{"Door "+ $_*$_ + " is open"} diff --git a/Task/100-doors/Python/100-doors-5.py b/Task/100-doors/Python/100-doors-5.py index c3f39a49a6..96e57804d7 100644 --- a/Task/100-doors/Python/100-doors-5.py +++ b/Task/100-doors/Python/100-doors-5.py @@ -1,6 +1,2 @@ for i in range(1, 101): - if i**0.5 % 1: - state='closed' - else: - state='open' - print("Door {}:{}".format(i, state)) + print(f"Door {i}:{"closed" if i**0.5 % 1 else "open"}") diff --git a/Task/100-doors/Python/100-doors-6.py b/Task/100-doors/Python/100-doors-6.py index 7524fc9970..b42230ac44 100644 --- a/Task/100-doors/Python/100-doors-6.py +++ b/Task/100-doors/Python/100-doors-6.py @@ -1 +1 @@ -for i in range(1,11): print("Door %s is open" % i**2) +for i in range(1,11): print(f"Door {i**2} is open") diff --git a/Task/100-doors/REBOL/100-doors-1.rebol b/Task/100-doors/REBOL/100-doors-1.rebol deleted file mode 100644 index aa422858bd..0000000000 --- a/Task/100-doors/REBOL/100-doors-1.rebol +++ /dev/null @@ -1,5 +0,0 @@ -doors: array/initial 100 'closed -repeat i 100 [ - door: at doors i - forskip door i [change door either 'open = first door ['closed] ['open]] -] diff --git a/Task/100-doors/REBOL/100-doors-2.rebol b/Task/100-doors/REBOL/100-doors-2.rebol deleted file mode 100644 index b8428a69d9..0000000000 --- a/Task/100-doors/REBOL/100-doors-2.rebol +++ /dev/null @@ -1,26 +0,0 @@ -;; Create a bitset with capacity for 100 bits (representing 100 doors) -;; Each bit represents a door state: 0 = closed, 1 = open -doors: make bitset! 100 - -;; Outer loop: Make 100 passes (i = 1 to 100) -repeat i 100 [ - ;; Inner loop: Check each door position (j = 1 to 100) - repeat j 100 [ - ;; If door j index is divisible by pass number i (no remainder) - if zero? (j // i) [ - ;; Toggle the door's bit: - ;; doors/:j accesses door j in the bitset - ;; 'not' flips the bit value (0 -> 1, 1 -> 0) - doors/:j: not doors/:j - ] - ] -] - -;; Final loop: Check which doors are open, print their numbers -repeat i 100 [ - ;; If door i's bit is set (open) - if doors/:i [ - ;; Print the door's number and that it is open - print ["door" i "is open"] - ] -] diff --git a/Task/100-doors/REBOL/100-doors-3.rebol b/Task/100-doors/REBOL/100-doors-3.rebol deleted file mode 100644 index 318cdd4a11..0000000000 --- a/Task/100-doors/REBOL/100-doors-3.rebol +++ /dev/null @@ -1,6 +0,0 @@ -;; Loop variable i from 1 to 10 (since 10^2 = 100, covers doors 1 to 100) -repeat i 10 [ - ;; Print that door number (i squared) is open - ;; These are exactly the doors with perfect square numbers: 1, 4, 9, ..., 100 - print ["door" (i * i) "is open"] -] diff --git a/Task/100-doors/VBScript/100-doors.vb b/Task/100-doors/VBScript/100-doors.vb deleted file mode 100644 index b0ccc343de..0000000000 --- a/Task/100-doors/VBScript/100-doors.vb +++ /dev/null @@ -1,21 +0,0 @@ -Dim doorIsOpen(100), pass, currentDoor, text - -For currentDoor = 0 To 99 - doorIsOpen(currentDoor) = False -Next - -For pass = 0 To 99 - For currentDoor = pass To 99 Step pass + 1 - doorIsOpen(currentDoor) = Not doorIsOpen(currentDoor) - Next -Next - -For currentDoor = 0 To 99 - text = "Door #" & currentDoor + 1 & " is " - If doorIsOpen(currentDoor) Then - text = text & "open." - Else - text = text & "closed." - End If - WScript.Echo(text) -Next diff --git a/Task/100-doors/VHDL/100-doors-1.vhdl b/Task/100-doors/VHDL/100-doors-1.vhdl deleted file mode 100644 index 605574c224..0000000000 --- a/Task/100-doors/VHDL/100-doors-1.vhdl +++ /dev/null @@ -1,28 +0,0 @@ -library IEEE; -use IEEE.STD_LOGIC_1164.ALL; - -entity DOORS is - port (CLK: in std_logic; OUTPUT: out std_logic_vector(1 to 100)); -end DOORS; - -architecture Behavioral of DOORS is -begin - process (CLK) - variable TEMP: std_logic_vector(1 to 100); - begin - --setup closed doors - TEMP := (others => '0'); - - --looping through - for i in 1 to TEMP'length loop - for j in i to TEMP'length loop - if (j mod i) = 0 then - TEMP(j) := not TEMP(j); - end if; - end loop; - end loop; - - --assign output - OUTPUT <= TEMP; - end process; -end Behavioral; diff --git a/Task/100-doors/VHDL/100-doors-2.vhdl b/Task/100-doors/VHDL/100-doors-2.vhdl deleted file mode 100644 index d63de9a7ac..0000000000 --- a/Task/100-doors/VHDL/100-doors-2.vhdl +++ /dev/null @@ -1,34 +0,0 @@ -LIBRARY ieee; -USE ieee.std_logic_1164.all; - - -entity doors is - port ( - clk : in std_logic; - reset : in std_logic; - door : buffer std_logic_vector(1 to 100) - ); -end entity doors; - - -architecture rtl of doors is - signal step : integer range 1 to 101; - signal addr : integer range 1 to 201; -begin - proc_step: process(clk, reset) - begin - if reset = '1' then - step <= 1; - addr <= 1; - door <= (others => '0'); - elsif rising_edge(clk) then - if addr <= 100 then - door(addr) <= not door(addr); - addr <= addr + step; - elsif step <= 100 then - addr <= step + 1; - step <= step + 1; - end if; - end if; - end process; -end; diff --git a/Task/100-prisoners/11l/100-prisoners.11l b/Task/100-prisoners/11l/100-prisoners.11l index f8e57ab878..0bacfb4489 100644 --- a/Task/100-prisoners/11l/100-prisoners.11l +++ b/Task/100-prisoners/11l/100-prisoners.11l @@ -5,7 +5,7 @@ F play_random(n) L 0 .< n random:shuffle(&in_drawer) V found = 0B - L(prisoner) 100 + L(prisoner) 0.<100 found = 0B L(reveal) random:sample(sampler, 50) V card = in_drawer[reveal] @@ -24,7 +24,7 @@ F play_optimal(n) L 0 .< n random:shuffle(&in_drawer) V found = 0B - L(prisoner) 100 + L(prisoner) 0.<100 V reveal = prisoner found = 0B L 50 diff --git a/Task/100-prisoners/Ada/100-prisoners-1.ada b/Task/100-prisoners/Ada/100-prisoners-1.ada deleted file mode 100644 index 0758b5ec27..0000000000 --- a/Task/100-prisoners/Ada/100-prisoners-1.ada +++ /dev/null @@ -1,23 +0,0 @@ -package Prisoners is - - type Win_Percentage is digits 2 range 0.0 .. 100.0; - type Drawers is array (1 .. 100) of Positive; - - function Play_Game - (Repetitions : in Positive; - Strategy : not null access function - (Cupboard : in Drawers; Max_Prisoners : Integer; - Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean) - return Win_Percentage; - -- Play the game with a specified number of repetitions, the chosen strategy - -- is passed to this function - - function Optimal_Strategy - (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer; - Prisoner_Number : Integer) return Boolean; - - function Random_Strategy - (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer; - Prisoner_Number : Integer) return Boolean; - -end Prisoners; diff --git a/Task/100-prisoners/Ada/100-prisoners-2.ada b/Task/100-prisoners/Ada/100-prisoners-2.ada deleted file mode 100644 index f37ded4cb6..0000000000 --- a/Task/100-prisoners/Ada/100-prisoners-2.ada +++ /dev/null @@ -1,128 +0,0 @@ -pragma Ada_2012; -with Ada.Numerics.Discrete_Random; -with Ada.Text_IO; use Ada.Text_IO; - -package body Prisoners is - - subtype Drawer_Range is Positive range 1 .. 100; - package Random_Drawer is new Ada.Numerics.Discrete_Random (Drawer_Range); - use Random_Drawer; - - -- Helper procedures to initialise and shuffle the drawers - - procedure Swap (A, B : Positive; Cupboard : in out Drawers) is - Temp : Positive; - begin - Temp := Cupboard (B); - Cupboard (B) := Cupboard (A); - Cupboard (A) := Temp; - end Swap; - - procedure Shuffle (Cupboard : in out Drawers) is - G : Generator; - begin - Reset (G); - for I in Cupboard'Range loop - Swap (I, Random (G), Cupboard); - end loop; - end Shuffle; - - procedure Initialise_Drawers (Cupboard : in out Drawers) is - begin - for I in Cupboard'Range loop - Cupboard (I) := I; - end loop; - Shuffle (Cupboard); - end Initialise_Drawers; - - -- The two strategies for playing the game - - function Optimal_Strategy - (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer; - Prisoner_Number : Integer) return Boolean - is - Current_Card : Positive; - begin - Current_Card := Cupboard (Prisoner_Number); - if Current_Card = Prisoner_Number then - return True; - else - for I in Integer range 1 .. Max_Attempts loop - Current_Card := Cupboard (Current_Card); - if Current_Card = Prisoner_Number then - return True; - end if; - end loop; - end if; - return False; - end Optimal_Strategy; - - function Random_Strategy - (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer; - Prisoner_Number : Integer) return Boolean - is - Current_Card : Positive; - G : Generator; - begin - Reset (G); - Current_Card := Cupboard (Prisoner_Number); - if Current_Card = Prisoner_Number then - return True; - else - for I in Integer range 1 .. Max_Attempts loop - Current_Card := Cupboard (Random (G)); - if Current_Card = Prisoner_Number then - return True; - end if; - end loop; - end if; - return False; - end Random_Strategy; - - function Prisoners_Attempts - (Cupboard : in Drawers; Max_Prisoners : Integer; Max_Attempts : Integer; - Strategy : not null access function - (Cupboard : in Drawers; Max_Prisoners : Integer; - Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean) - return Boolean - is - begin - for Prisoner_Number in Integer range 1 .. Max_Prisoners loop - if not Strategy - (Cupboard, Max_Prisoners, Max_Attempts, Prisoner_Number) - then - return False; - end if; - end loop; - return True; - end Prisoners_Attempts; - - -- The function to play the game itself - - function Play_Game - (Repetitions : in Positive; - Strategy : not null access function - (Cupboard : in Drawers; Max_Prisoners : Integer; - Max_Attempts : Integer; Prisoner_Number : Integer) return Boolean) - return Win_Percentage - is - Cupboard : Drawers; - Win, Game_Count : Natural := 0; - Number_Of_Prisoners : constant Integer := 100; - Max_Attempts : constant Integer := 50; - begin - loop - Initialise_Drawers (Cupboard); - if Prisoners_Attempts - (Cupboard => Cupboard, Max_Prisoners => Number_Of_Prisoners, - Max_Attempts => Max_Attempts, Strategy => Strategy) - then - Win := Win + 1; - end if; - Game_Count := Game_Count + 1; - exit when Game_Count = Repetitions; - end loop; - return Win_Percentage ((Float (Win) / Float (Repetitions)) * 100.0); - end Play_Game; - -end Prisoners; diff --git a/Task/100-prisoners/Ada/100-prisoners-3.ada b/Task/100-prisoners/Ada/100-prisoners-3.ada deleted file mode 100644 index fafdb76a09..0000000000 --- a/Task/100-prisoners/Ada/100-prisoners-3.ada +++ /dev/null @@ -1,17 +0,0 @@ -with Prisoners; use Prisoners; -with Ada.Text_IO; use Ada.Text_IO; - -procedure Main is - Wins : Win_Percentage; - package Win_Percentage_IO is new Float_IO (Win_Percentage); -begin - Wins := Play_Game (100_000, Optimal_Strategy'Access); - Put ("Optimal Strategy = "); - Win_Percentage_IO.Put (Wins, 2, 2, 0); - Put ("%"); - New_Line; - Wins := Play_Game (100_000, Random_Strategy'Access); - Put ("Random Strategy = "); - Win_Percentage_IO.Put (Wins, 2, 2, 0); - Put ("%"); -end Main; diff --git a/Task/100-prisoners/D/100-prisoners.d b/Task/100-prisoners/D/100-prisoners.d index 04986ae37c..5c70291510 100644 --- a/Task/100-prisoners/D/100-prisoners.d +++ b/Task/100-prisoners/D/100-prisoners.d @@ -37,7 +37,7 @@ bool playRandom() { double exec(const size_t n, bool function() play) { size_t success = 0; - for (int i = n; i > 0; i--) { + for (size_t i = n; i > 0; i--) { if (play()) { success++; } diff --git a/Task/100-prisoners/PowerShell/100-prisoners.psh b/Task/100-prisoners/PowerShell/100-prisoners.psh deleted file mode 100644 index 6bcb37f11a..0000000000 --- a/Task/100-prisoners/PowerShell/100-prisoners.psh +++ /dev/null @@ -1,121 +0,0 @@ -### Clear Screen from old Output -Clear-Host - -Function RandomOpening () - { - $Prisoners = 1..100 | Sort-Object {Get-Random} - $Cupboard = 1..100 | Sort-Object {Get-Random} - ## Loop for the Prisoners - $Survived = $true - for ($I=1;$I -le 100;$i++) - { - $OpeningListe = 1..100 | Sort-Object {Get-Random} - $Gefunden = $false - ## Loop for the trys of every prisoner - for ($X=1;$X -le 50;$X++) - { - $OpenNumber = $OpeningListe[$X] - IF ($Cupboard[$OpenNumber] -eq $Prisoners[$I]) - { - $Gefunden = $true - } - ## Cancel loop if prisoner found his number (yeah i know, dirty way ^^ ) - IF ($Gefunden) - { - $X = 55 - } - } - IF ($Gefunden -eq $false) - { - $I = 120 - $Survived = $false - } - } - Return $Survived - } - - Function StrategyOpening () - { - $Prisoners = 1..100 | Sort-Object {Get-Random} - $Cupboard = 1..100 | Sort-Object {Get-Random} - $Survived = $true - for ($I=1;$I -le 100;$i++) - { - $Gefunden = $false - $OpeningNumber = $Prisoners[$I-1] - for ($X=1;$X -le 50;$X++) - { - IF ($Cupboard[$OpeningNumber-1] -eq $Prisoners[$I-1]) - { - $Gefunden = $true - } - else - { - $OpeningNumber = $Cupboard[$OpeningNumber-1] - } - IF ($Gefunden) - { - $X = 55 - } - } - IF ($Gefunden -eq $false) - { - $I = 120 - $Survived = $false - } - } - Return $Survived - } - -$MaxRounds = 10000 - -Function TestRandom - { - $WinnerRandom = 0 - for ($Round = 1; $Round -le $MaxRounds;$Round++) - { - IF (($Round%1000) -eq 0) - { - $Time = Get-Date - Write-Host "Currently we are at rount $Round at $Time" - } - $Rueckgabewert = RandomOpening - IF ($Rueckgabewert) - { - $WinnerRandom++ - } - } - - $Prozent = (100/$MaxRounds)*$WinnerRandom - Write-Host "There are $WinnerRandom survivors whit random opening. This is $Prozent percent" - } - -Function TestStrategy - { - $WinnersStrategy = 0 - for ($Round = 1; $Round -le $MaxRounds;$Round++) - { - IF (($Round%1000) -eq 0) - { - $Time = Get-Date - Write-Host "Currently we are at $Round at $Time" - } - $Rueckgabewert = StrategyOpening - IF ($Rueckgabewert) - { - $WinnersStrategy++ - } - } - - $Prozent = (100/$MaxRounds)*$WinnersStrategy - Write-Host "There are $WinnersStrategy survivors whit strategic opening. This is $Prozent percent" - } - -Function Main () - { - Clear-Host - TestRandom - TestStrategy - } - -Main diff --git a/Task/100-prisoners/VBScript/100-prisoners.vb b/Task/100-prisoners/VBScript/100-prisoners.vb deleted file mode 100644 index 9e21f34467..0000000000 --- a/Task/100-prisoners/VBScript/100-prisoners.vb +++ /dev/null @@ -1,62 +0,0 @@ -option explicit -const npris=100 -const ntries=50 -const ntests=1000. -dim drawer(100),opened(100),i -for i=1 to npris: drawer(i)=i:next -shuffle drawer -wscript.echo rf(tests(false)/ntests*100,10," ") &" % success for random" -wscript.echo rf(tests(true) /ntests*100,10," ") &" % success for optimal strategy" - -function rf(v,n,s) rf=right(string(n,s)& v,n):end function - -sub shuffle(d) 'knut's shuffle -dim i,j,t -randomize timer -for i=1 to npris - j=int(rnd()*i+1) - t=d(i):d(i)=d(j):d(j)=t -next -end sub - -function tests(strat) -dim cntp,i,j -tests=0 -for i=1 to ntests - shuffle drawer - cntp=0 - if strat then - for j=1 to npris - if not trystrat(j) then exit for - next - else - for j=1 to npris - if not tryrand(j) then exit for - next - end if - if j>=npris then tests=tests+1 -next -end function - -function tryrand(pris) - dim i,r - erase opened - for i=1 to ntries - do - r=int(rnd*npris+1) - loop until opened(r)=false - opened(r)=true - if drawer(r)= pris then tryrand=true : exit function - next - tryrand=false -end function - -function trystrat(pris) - dim i,r - r=pris - for i=1 to ntries - if drawer(r)= pris then trystrat=true :exit function - r=drawer(r) - next - trystrat=false -end function diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-1.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-1.ada deleted file mode 100644 index 634015c5bc..0000000000 --- a/Task/15-puzzle-game/Ada/15-puzzle-game-1.ada +++ /dev/null @@ -1,16 +0,0 @@ -generic - Rows, Cols: Positive; - with function Name(N: Natural) return String; -- with Pre => (N < Rows*Cols); - -- Name(0) shall return the name for the empty tile -package Generic_Puzzle is - - subtype Row_Type is Positive range 1 .. Rows; - subtype Col_Type is Positive range 1 .. Cols; - type Moves is (Up, Down, Left, Right); - type Move_Arr is array(Moves) of Boolean; - - function Get_Point(Row: Row_Type; Col: Col_Type) return String; - function Possible return Move_Arr; - procedure Move(The_Move: Moves); - -end Generic_Puzzle; diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-2.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-2.ada deleted file mode 100644 index 86a2432cb1..0000000000 --- a/Task/15-puzzle-game/Ada/15-puzzle-game-2.ada +++ /dev/null @@ -1,57 +0,0 @@ -package body Generic_Puzzle is - - Field: array(Row_Type, Col_Type) of Natural; - Current_R: Row_Type := Rows; - Current_C: Col_Type := Cols; - -- invariant: Field(Current_R, Current_C=0) - -- and for all R, C: Field(R, C) < R*C - -- and for all (R, C) /= (RR, CC): Field(R, C) /= Field(RR, CC) - - function Get_Point(Row: Row_Type; Col: Col_Type) return String is - (Name(Field(Row, Col))); - - function Possible return Move_Arr is - (Up => Current_R > 1, Down => Current_R < Rows, - Left => Current_C > 1, Right => Current_C < Cols); - - procedure Move(The_Move: Moves) is - Old_R: Row_Type; Old_C: Col_Type; N: Natural; - begin - if not Possible(The_Move) then - raise Constraint_Error with "attempt to make impossible move"; - else - -- remember current row and column - Old_R := Current_R; - Old_C := Current_C; - - -- move the virtual cursor to a new position - case The_Move is - when Up => Current_R := Current_R - 1; - when Down => Current_R := Current_R + 1; - when Left => Current_C := Current_C - 1; - when Right => Current_C := Current_C + 1; - end case; - - -- swap the tiles on the board - N := Field(Old_R, Old_C); - Field(Old_R, Old_C) := Field(Current_R, Current_C); - Field(Current_R, Current_C) := N; - end if; - end Move; - -begin - declare -- set field to its basic setting - N: Positive := 1; - begin - for R in Row_Type loop - for C in Col_Type loop - if (R /= Current_R) or else (C /= Current_C) then - Field(R, C) := N; - N := N + 1; - else - Field(R, C) := 0; - end if; - end loop; - end loop; - end; -end Generic_Puzzle; diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-3.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-3.ada deleted file mode 100644 index 67ca38ab0a..0000000000 --- a/Task/15-puzzle-game/Ada/15-puzzle-game-3.ada +++ /dev/null @@ -1,72 +0,0 @@ -with Generic_Puzzle, Ada.Text_IO, - Ada.Numerics.Discrete_Random, Ada.Command_Line; - -procedure Puzzle_15 is - - function Image(N: Natural) return String is - (if N=0 then " " elsif N < 10 then " " & Integer'Image(N) - else Integer'Image(N)); - - package Puzzle is new Generic_Puzzle(Rows => 4, Cols => 4, Name => Image); - - package Rnd is new Ada.Numerics.Discrete_Random(Puzzle.Moves); - Rand_Gen: Rnd.Generator; - - Level: Natural := (if Ada.Command_Line.Argument_Count = 0 then 10 - else Natural'Value(Ada.Command_Line.Argument(1))); - Initial_Moves: Natural := (2**(Level/2) + 2**((1+Level)/2))/2; - Texts: constant array(Puzzle.Moves) of String(1..9) := - ("u,U,^,8: ", "d,D,v,2: ", "l,L,<,4: ", "r,R,>,6: "); - Move_Counter: Natural := 0; - Command: Character; - - begin - -- randomize board - for I in 1 .. Initial_Moves loop - declare - M: Puzzle.Moves := Rnd.Random(Rand_Gen); - begin - if Puzzle.Possible(M) then - Puzzle.Move(M); - end if; - end; - end loop; - - -- read command and perform move - loop - -- Print board - for R in Puzzle.Row_Type loop - for C in Puzzle.Col_Type loop - Ada.Text_IO.Put(Puzzle.Get_Point(R, C)); - end loop; - Ada.Text_IO.New_Line; - end loop; - Ada.Text_IO.Get(Command); - begin - case Command is - when 'u' | 'U' | '^' | '8' => - Ada.Text_IO.Put_Line("Up!"); Puzzle.Move(Puzzle.Up); - when 'd' | 'D' | 'v' | '2' => - Ada.Text_IO.Put_Line("Down!"); Puzzle.Move(Puzzle.Down); - when 'l' | 'L' | '<' | '4' => - Ada.Text_IO.Put_Line("Left!"); Puzzle.Move(Puzzle.Left); - when 'r' | 'R' | '>' | '6' => - Ada.Text_IO.Put_Line("Right!"); Puzzle.Move(Puzzle.Right); - when '!' => - Ada.Text_IO.Put_Line(Natural'Image(Move_Counter) & " moves!"); - exit; - when others => - raise Constraint_Error with "wrong input"; - end case; - Move_Counter := Move_Counter + 1; - exception when Constraint_Error => - Ada.Text_IO.Put_Line("Possible Moves and Commands:"); - for M in Puzzle.Moves loop - if Puzzle.Possible(M) then - Ada.Text_IO.Put(Texts(M) & Puzzle.Moves'Image(M) & " "); - end if; - end loop; - Ada.Text_IO.Put_Line("!: Quit"); - end; - end loop; -end Puzzle_15; diff --git a/Task/15-puzzle-game/Ada/15-puzzle-game-4.ada b/Task/15-puzzle-game/Ada/15-puzzle-game-4.ada deleted file mode 100644 index 8452c72460..0000000000 --- a/Task/15-puzzle-game/Ada/15-puzzle-game-4.ada +++ /dev/null @@ -1 +0,0 @@ - package Puzzle is new Generic_Puzzle(Rows => 3, Cols => 3, Name => Image); diff --git a/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo b/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo index 4d08ffb095..9dcfaaed59 100644 --- a/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo +++ b/Task/15-puzzle-game/Arturo/15-puzzle-game.arturo @@ -107,17 +107,13 @@ validMovement?: $[ movement :literal ][ pos: game\playerPosition - case [movement] - when? [='up] - -> return (not? in? pos [0..3]) - when? [='down] - -> return (not? in? pos [12..15]) - when? [='left] - -> return (not? in? pos [0 4 8 12]) - when? [='right] - -> return (not? in? pos [3 7 11 15]) - else - -> return false + case movement [ + 'up -> return (not? in? pos [0..3]) + 'down -> return (not? in? pos [12..15]) + 'left -> return (not? in? pos [0 4 8 12]) + 'right -> return (not? in? pos [3 7 11 15]) + any -> return false + ] ] @@ -130,13 +126,14 @@ validMovement?: $[ ;; will be returned the same input as a :string parseInput: $[inp :string][ lowerInp: lower inp - case [lowerInp] - when? [="w"] -> return 'up - when? [="a"] -> return 'left - when? [="s"] -> return 'down - when? [="d"] -> return 'right - when? [="q"] -> return 'quit - else -> return inp + case lowerInp [ + "w" -> return 'up + "a" -> return 'left + "s" -> return 'down + "d" -> return 'right + "q" -> return 'quit + any -> return inp + ] ] ;; Moves the player in Game's Table @@ -155,7 +152,7 @@ movePlayer: $[ playerPosition :integer relativePosition :integer ][ - try [ + if throws? [ ; 'otherPosition is the real index of the 'relativePosition otherPosition: + playerPosition relativePosition @@ -168,20 +165,16 @@ movePlayer: $[ ; -- Updates player's status game\playerPosition: otherPosition game\movements: inc game\movements - ] else -> panic "'movement didn't checked." + ] -> panic "'movement didn't checked." ] - case [movement] - when? [='up] - -> (updateGame game position (neg 4)) - when? [='down] - -> (updateGame game position (4)) - when? [='left] - -> (updateGame game position (neg 1)) - when? [='right] - -> (updateGame game position (1)) - else -> panic "'movement didn't checked." - + case movement [ + 'up -> updateGame game position neg 4 + 'down -> updateGame game position 4 + 'left -> updateGame game position neg 1 + 'right -> updateGame game position 1 + any -> panic "movement didn't check." + ] ] endGame: $[ @@ -209,13 +202,12 @@ runGame: $[sampleTable :block][ -> endGame "Exiting game..." validInp: validInput? command - if? validInp [ + switch validInp [ validMov: validMovement? game command (validMov)? -> movePlayer game command -> printWrongMovement command - ] else - -> printWrongInput command + ] -> printWrongInput command if sampleTable = game -> endGame "Congratulations! You won!" diff --git a/Task/15-puzzle-game/COBOL/15-puzzle-game.cobol b/Task/15-puzzle-game/COBOL/15-puzzle-game.cobol deleted file mode 100644 index 1ce6bdcbbe..0000000000 --- a/Task/15-puzzle-game/COBOL/15-puzzle-game.cobol +++ /dev/null @@ -1,151 +0,0 @@ - >>SOURCE FORMAT FREE -*> This code is dedicated to the public domain -*> This is GNUCOBOL 2.0 -identification division. -program-id. fifteen. -environment division. -configuration section. -repository. function all intrinsic. -data division. -working-storage section. - -01 r pic 9. -01 r-empty pic 9. -01 r-to pic 9. -01 r-from pic 9. - -01 c pic 9. -01 c-empty pic 9. -01 c-to pic 9. -01 c-from pic 9. - -01 display-table. - 03 display-row occurs 4. - 05 display-cell occurs 4 pic 99. - -01 tile-number pic 99. -01 tile-flags pic x(16). - -01 display-move value spaces. - 03 tile-id pic 99. - -01 row-separator pic x(21) value all '.'. -01 column-separator pic x(3) value ' . '. - -01 inversions pic 99. -01 current-tile pic 99. - -01 winning-display pic x(32) value - '01020304' - & '05060708' - & '09101112' - & '13141500'. - -procedure division. -start-fifteen. - display 'start fifteen puzzle' - display ' enter a two-digit tile number and press to move' - display ' press only to exit' - - *> tables with an odd number of inversions are not solvable - perform initialize-table with test after until inversions = 0 - perform show-table - accept display-move - perform until display-move = spaces - perform move-tile - perform show-table - move spaces to display-move - accept display-move - end-perform - stop run - . -initialize-table. - compute tile-number = random(seconds-past-midnight) *> seed only - move spaces to tile-flags - move 0 to current-tile inversions - perform varying r from 1 by 1 until r > 4 - after c from 1 by 1 until c > 4 - perform with test after - until tile-flags(tile-number + 1:1) = space - compute tile-number = random() * 100 - compute tile-number = mod(tile-number, 16) - end-perform - move 'x' to tile-flags(tile-number + 1:1) - if tile-number > 0 and < current-tile - add 1 to inversions - end-if - move tile-number to display-cell(r,c) current-tile - end-perform - compute inversions = mod(inversions,2) - . -show-table. - if display-table = winning-display - display 'winning' - end-if - display space row-separator - perform varying r from 1 by 1 until r > 4 - perform varying c from 1 by 1 until c > 4 - display column-separator with no advancing - if display-cell(r,c) = 00 - display ' ' with no advancing - move r to r-empty - move c to c-empty - else - display display-cell(r,c) with no advancing - end-if - end-perform - display column-separator - end-perform - display space row-separator - . -move-tile. - if not (tile-id numeric and tile-id >= 01 and <= 15) - display 'invalid tile number' - exit paragraph - end-if - - *> find the entered tile-id row and column (r,c) - perform varying r from 1 by 1 until r > 4 - after c from 1 by 1 until c > 4 - if display-cell(r,c) = tile-id - exit perform - end-if - end-perform - - *> show-table filled (r-empty,c-empty) - evaluate true - when r = r-empty - if c-empty < c - *> shift left - perform varying c-to from c-empty by 1 until c-to > c - compute c-from = c-to + 1 - move display-cell(r-empty,c-from) to display-cell(r-empty,c-to) - end-perform - else - *> shift right - perform varying c-to from c-empty by -1 until c-to < c - compute c-from = c-to - 1 - move display-cell(r-empty,c-from) to display-cell(r-empty,c-to) - end-perform - end-if - move 00 to display-cell(r,c) - when c = c-empty - if r-empty < r - *>shift up - perform varying r-to from r-empty by 1 until r-to > r - compute r-from = r-to + 1 - move display-cell(r-from,c-empty) to display-cell(r-to,c-empty) - end-perform - else - *> shift down - perform varying r-to from r-empty by -1 until r-to < r - compute r-from = r-to - 1 - move display-cell(r-from,c-empty) to display-cell(r-to,c-empty) - end-perform - end-if - move 00 to display-cell(r,c) - when other - display 'invalid move' - end-evaluate - . -end program fifteen. diff --git a/Task/15-puzzle-game/PowerShell/15-puzzle-game.psh b/Task/15-puzzle-game/PowerShell/15-puzzle-game.psh deleted file mode 100644 index 72bca40e20..0000000000 --- a/Task/15-puzzle-game/PowerShell/15-puzzle-game.psh +++ /dev/null @@ -1,259 +0,0 @@ -#15 Puzzle Game -$Script:Neighbours = @{ - "1" = @("2","5") - "2" = @("1","3","6") - "3" = @("2","4","7") - "4" = @("3","8") - "5" = @("1","6","9") - "6" = @("2","5","7","10") - "7" = @("3","6","8","11") - "8" = @("4","7","12") - "9" = @("5","10","13") - "10" = @("6","9","11","14") - "11" = @("7","10","12","15") - "12" = @("8","11","0") - "13" = @("9","14") - "14" = @("10","13","15") - "15" = @("11","14","0") - "0" = @("12","15") -} -$script:blank = '' -#region XAML window definition -$xaml = @' - - - - - - - - - - - - - - -
    -

    Clicks: 0

    - - - diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.psh deleted file mode 100644 index 6e9eee80f9..0000000000 --- a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.psh +++ /dev/null @@ -1,20 +0,0 @@ -$Label1 = [System.Windows.Forms.Label]@{ - Text = 'There have been no clicks yet' - Size = '200, 20' } -$Button1 = [System.Windows.Forms.Button]@{ - Text = 'Click me' - Location = '0, 20' } - -$Button1.Add_Click( - { - $Script:Clicks++ - If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" } - Else { $Label1.Text = "There have been $Clicks clicks" } - } ) - -$Form1 = New-Object System.Windows.Forms.Form -$Form1.Controls.AddRange( @( $Label1, $Button1 ) ) - -$Clicks = 0 - -$Result = $Form1.ShowDialog() diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.psh deleted file mode 100644 index 75c42bc50b..0000000000 --- a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.psh +++ /dev/null @@ -1,23 +0,0 @@ -Add-Type -AssemblyName System.Windows.Forms - -$Label1 = New-Object System.Windows.Forms.Label -$Label1.Text = 'There have been no clicks yet' -$Label1.Size = '200, 20' - -$Button1 = New-Object System.Windows.Forms.Button -$Button1.Text = 'Click me' -$Button1.Location = '0, 20' - -$Button1.Add_Click( - { - $Script:Clicks++ - If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" } - Else { $Label1.Text = "There have been $Clicks clicks" } - } ) - -$Form1 = New-Object System.Windows.Forms.Form -$Form1.Controls.AddRange( @( $Label1, $Button1 ) ) - -$Clicks = 0 - -$Result = $Form1.ShowDialog() diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.psh b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.psh deleted file mode 100644 index 3f3ed52bdb..0000000000 --- a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.psh +++ /dev/null @@ -1,38 +0,0 @@ -[xml]$Xaml = @" - - -
    +{{out|input=3 4}} +
    +7
    diff --git a/Task/A+B/VBScript/a+b-1.vbs b/Task/A+B/VBScript/a+b-1.vbs
    new file mode 100644
    index 0000000000..70ec9e210e
    --- /dev/null
    +++ b/Task/A+B/VBScript/a+b-1.vbs
    @@ -0,0 +1,6 @@
    +s=InputBox("Enter two numbers separated by a blank")
    +t=Split(s)
    +a=CInt(t(0))
    +b=CInt(t(1))
    +c=a+b
    +MsgBox c
    diff --git a/Task/A+B/VBScript/a+b-2.vbs b/Task/A+B/VBScript/a+b-2.vbs
    new file mode 100644
    index 0000000000..08f40b34e4
    --- /dev/null
    +++ b/Task/A+B/VBScript/a+b-2.vbs
    @@ -0,0 +1,37 @@
    +Option Explicit
    +Dim a, b
    +Select Case WScript.Arguments.Count
    +	Case 0	'No arguments, prompt for them.
    +		WScript.Echo "Enter values for a and b"
    +		a = WScript.Stdin.ReadLine
    +		if Instr(a, " ") > 0 then	'If two variables were passed
    +			b = Split(a)(1)
    +			a = Split(a)(0)
    +		else
    +			WScript.Echo "Enter value for b"
    +			b = WScript.Stdin.ReadLine
    +		end if
    +	Case 1	'One argument, assume it's an input file, e.g. "in.txt"
    +		Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
    +		With FSO.OpenTextFile(WScript.Arguments(0), 1)
    +			a = .ReadLine
    +			b = Split(a)(1)
    +			a = Split(a)(0)
    +			.Close
    +		End With
    +	Case 2 'Two arguments, assume they are values
    +		a = WScript.Arguments(0)
    +		b = WScript.Arguments(1)
    +End Select
    +'At this point, a and b are strings as entered, make them numbers
    +a = CInt(a)
    +b = CInt(b)
    +
    +'Write the sum
    +Wscript.Echo a + b
    +if 1 = WScript.Arguments.Count then
    +	With FSO.CreateTextFile("out.txt")
    +		.WriteLine a + b
    +		.Close
    +	End With
    +end if
    diff --git a/Task/A+B/VHDL/a+b.vhd b/Task/A+B/VHDL/a+b.vhd
    new file mode 100644
    index 0000000000..5eea2b5c05
    --- /dev/null
    +++ b/Task/A+B/VHDL/a+b.vhd
    @@ -0,0 +1,23 @@
    +LIBRARY std;
    +USE std.TEXTIO.all;
    +
    +
    +entity test is
    +end entity test;
    +
    +
    +architecture beh of test is
    +begin
    +  process
    +    variable line_in, line_out : line;
    +    variable a,b : integer;
    +  begin
    +    readline(INPUT, line_in);
    +    read(line_in, a);
    +    read(line_in, b);
    +
    +    write(line_out, a+b);
    +    writeline(OUTPUT, line_out);
    +    wait; -- needed to stop the execution
    +  end process;
    +end architecture beh;
    diff --git a/Task/ABC-problem/Ada/abc-problem.adb b/Task/ABC-problem/Ada/abc-problem.adb
    new file mode 100644
    index 0000000000..28ac345566
    --- /dev/null
    +++ b/Task/ABC-problem/Ada/abc-problem.adb
    @@ -0,0 +1,78 @@
    +with Ada.Characters.Handling;
    +use Ada.Characters.Handling;
    +
    +
    +package Abc is
    +    type Block_Faces is array(1..2) of Character;
    +    type Block_List is array(positive range <>) of Block_Faces;
    +    function Can_Make_Word(W: String; Blocks: Block_List) return Boolean;
    +end Abc;
    +
    +
    +package body Abc is
    +
    +function Can_Make_Word(W: String; Blocks: Block_List) return Boolean is
    +    Used : array(Blocks'Range) of Boolean := (Others => False);
    +    subtype wIndex is Integer range W'First..W'Last;
    +    wPos : wIndex;
    +begin
    +    if W'Length = 0 then
    +        return True;
    +    end if;
    +    wPos := W'First;
    +    while True loop
    +        declare
    +            C : Character := To_Upper(W(wPos));
    +            X : constant wIndex := wPos;
    +        begin
    +            for I in Blocks'Range loop
    +                if (not Used(I)) then
    +                    if C = To_Upper(Blocks(I)(1)) or C = To_Upper(Blocks(I)(2)) then
    +                        Used(I) := True;
    +                        if wPos = W'Last then
    +                            return True;
    +                        end if;
    +                        wPos := wIndex'Succ(wPos);
    +                        exit;
    +                    end if;
    +                end if;
    +            end loop;
    +            if X = wPos then
    +                return False;
    +            end if;
    +        end;
    +    end loop;
    +    return False;
    +end Can_Make_Word;
    +
    +end Abc;
    +
    +with Ada.Text_IO, Ada.Strings.Unbounded, Abc;
    +use Ada.Text_IO, Ada.Strings.Unbounded, Abc;
    +
    +procedure Abc_Problem is
    +    Blocks : Block_List := (
    +          ('B','O'), ('X','K'), ('D','Q'), ('C','P')
    +        , ('N','A'), ('G','T'), ('R','E'), ('T','G')
    +        , ('Q','D'), ('F','S'), ('J','W'), ('H','U')
    +        , ('V','I'), ('A','N'), ('O','B'), ('E','R')
    +        , ('F','S'), ('L','Y'), ('P','C'), ('Z','M')
    +    );
    +    function "+" (S : String) return Unbounded_String renames To_Unbounded_String;
    +    words : array(positive range <>) of Unbounded_String := (
    +          +"A"
    +        , +"BARK"
    +        , +"BOOK"
    +        , +"TREAT"
    +        , +"COMMON"
    +        , +"SQUAD"
    +        , +"CONFUSE"
    +        -- Border cases:
    +        -- , +"CONFUSE2"
    +        -- , +""
    +    );
    +begin
    +    for I in words'Range loop
    +        Put_Line ( To_String(words(I)) & ": " & Boolean'Image(Can_Make_Word(To_String(words(I)),Blocks)) );
    +    end loop;
    +end Abc_Problem;
    diff --git a/Task/ABC-problem/COBOL/abc-problem.cob b/Task/ABC-problem/COBOL/abc-problem.cob
    new file mode 100644
    index 0000000000..7c1b0e20c6
    --- /dev/null
    +++ b/Task/ABC-problem/COBOL/abc-problem.cob
    @@ -0,0 +1,64 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. ABC-PROBLEM.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 INPUT-DATA.
    +          03 BLOCK-SET          PIC X(40) VALUE
    +                        'BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM'.
    +          03 WORD-DATA.
    +             05 FILLER          PIC X(7) VALUE 'A'.
    +             05 FILLER          PIC X(7) VALUE 'BARK'.
    +             05 FILLER          PIC X(7) VALUE 'BOOK'.
    +             05 FILLER          PIC X(7) VALUE 'TREAT'.
    +             05 FILLER          PIC X(7) VALUE 'COMMON'.
    +             05 FILLER          PIC X(7) VALUE 'SQUAD'.
    +             05 FILLER          PIC X(7) VALUE 'CONFUSE'.
    +          03 WORDS              PIC X(7) OCCURS 7 TIMES, INDEXED BY W,
    +                                REDEFINES WORD-DATA.
    +
    +       01 OUTPUT-LINE.
    +          03 OUT-WORD           PIC X(7).
    +          03 FILLER             PIC XX VALUE ': '.
    +          03 RESULT             PIC X(3).
    +          03 FOO                PIC 999.
    +
    +       01 VARIABLES.
    +          03 BLOCK-SET          PIC X(40).
    +          03 BLOCKS             OCCURS 20 TIMES, INDEXED BY B,
    +                                REDEFINES BLOCK-SET.
    +             05 FACE-A          PIC X.
    +             05 FACE-B          PIC X.
    +          03 WORD.
    +             05 LETTERS         PIC X OCCURS 7 TIMES, INDEXED BY L.
    +          03 FAIL-FLAG          PIC X.
    +             88 FAILED          VALUE 'X'.
    +
    +       PROCEDURE DIVISION.
    +       BEGIN.
    +           PERFORM CHECK-WORD VARYING W FROM 1 BY 1
    +           UNTIL W IS GREATER THAN 7.
    +           STOP RUN.
    +
    +       CHECK-WORD.
    +           MOVE BLOCK-SET OF INPUT-DATA TO BLOCK-SET OF VARIABLES.
    +
    +           MOVE WORDS(W) TO WORD.
    +           SET L TO 1.
    +           MOVE SPACE TO FAIL-FLAG.
    +           PERFORM CHECK-LETTER VARYING L FROM 1 BY 1
    +               UNTIL FAILED
    +               OR L IS GREATER THAN 7
    +               OR LETTERS(L) IS EQUAL TO SPACE.
    +
    +           MOVE WORDS(W) TO OUT-WORD.
    +           IF FAILED, MOVE 'NO' TO RESULT, ELSE MOVE 'YES' TO RESULT.
    +           DISPLAY OUTPUT-LINE.
    +
    +       CHECK-LETTER.
    +           SET B TO 1.
    +           SEARCH BLOCKS VARYING B
    +               AT END
    +                   MOVE 'X' TO FAIL-FLAG
    +               WHEN LETTERS(L) IS EQUAL TO FACE-A(B) OR FACE-B(B)
    +                   MOVE SPACES TO BLOCKS(B).
    diff --git a/Task/ABC-problem/Crystal/abc-problem.cr b/Task/ABC-problem/Crystal/abc-problem.cr
    new file mode 100644
    index 0000000000..5f3ec7d4ff
    --- /dev/null
    +++ b/Task/ABC-problem/Crystal/abc-problem.cr
    @@ -0,0 +1,17 @@
    +def can_make_word? (word, blocks, i=0)
    +  return true if word.empty?
    +  ch = word[0].upcase
    +  blocks.each_with_index do |block, idx|
    +    if ch.in? block.upcase
    +      return true if can_make_word? word[1..], blocks[...idx] + blocks[(idx+1)..], i+1
    +    end
    +  end
    +  false
    +end
    +
    +blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM".split
    +
    +["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"].each do |word|
    +  print word, " -> ", can_make_word?(word, blocks), "\n"
    +end
    +print "abba", " -> ", can_make_word?("abba", ["AB", "AB", "AC", "AC"]), "\n"
    diff --git a/Task/ABC-problem/Euphoria/abc-problem.eu b/Task/ABC-problem/Euphoria/abc-problem.eu
    new file mode 100644
    index 0000000000..be5498a568
    --- /dev/null
    +++ b/Task/ABC-problem/Euphoria/abc-problem.eu
    @@ -0,0 +1,35 @@
    +include std/text.e
    +
    +sequence blocks = {{'B','O'},{'X','K'},{'D','Q'},{'C','P'},{'N','A'},
    +                   {'G','T'},{'R','E'},{'T','G'},{'Q','D'},{'F','S'},
    +                   {'J','W'},{'H','U'},{'V','I'},{'A','N'},{'O','B'},
    +                   {'E','R'},{'F','S'},{'L','Y'},{'P','C'},{'Z','M'}}
    +sequence words = {"A","BarK","BOOK","TrEaT","COMMON","SQUAD","CONFUSE"}
    +
    +sequence current_word
    +sequence temp
    +integer matches
    +
    +for i = 1 to length(words) do
    +   current_word = upper(words[i])
    +   temp = blocks
    +   matches = 0
    +   for j = 1 to length(current_word) do
    +      for k = 1 to length(temp) do
    +         if find(current_word[j],temp[k]) then
    +            temp = remove(temp,k)
    +            matches += 1
    +            exit
    +         end if
    +      end for
    +      if length(current_word) = matches then
    +         printf(1,"%s: TRUE\n",{words[i]})
    +         exit
    +      end if
    +   end for
    +   if length(current_word) != matches then
    +      printf(1,"%s: FALSE\n",{words[i]})
    +   end if
    +end for
    +
    +if getc(0) then end if
    diff --git a/Task/ABC-problem/PowerShell/abc-problem.ps1 b/Task/ABC-problem/PowerShell/abc-problem.ps1
    new file mode 100644
    index 0000000000..3c8a1239a4
    --- /dev/null
    +++ b/Task/ABC-problem/PowerShell/abc-problem.ps1
    @@ -0,0 +1,117 @@
    +<#
    +.Synopsis
    +  ABC Problem
    +.DESCRIPTION
    +   You are given a collection of ABC blocks. Just like the ones you had when you were a kid.
    +   There are twenty blocks with two letters on each block. You are guaranteed to have a
    +   complete alphabet amongst all sides of the blocks
    +   blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"
    +   The goal of this task is to write a function that takes a string and can determine whether
    +   you can spell the word with the given collection of blocks.
    +
    +   The rules are simple:
    +        1.Once a letter on a block is used that block cannot be used again
    +        2.The function should be case-insensitive
    +        3. Show your output on this page for the following words:
    +        >>> can_make_word("A")
    +        True
    +        >>> can_make_word("BARK")
    +        True
    +        >>> can_make_word("BOOK")
    +        False
    +        >>> can_make_word("TREAT")
    +        True
    +        >>> can_make_word("COMMON")
    +        False
    +        >>> can_make_word("SQUAD")
    +        True
    +        >>> can_make_word("CONFUSE")
    +        True
    +
    +   Using the examples below  you can either see just the value or
    +   status and the values using the verbose switch
    +
    +.EXAMPLE
    +   test-blocks -testword confuse
    +
    +.EXAMPLE
    +   test-blocks -testword confuse -verbose
    +
    +#>
    +
    +function test-blocks
    +{
    +   [CmdletBinding()]
    +   #  [OutputType([int])]
    +   Param
    +   (
    +      # word to test against blocks
    +      [Parameter(Mandatory = $true,
    +               ValueFromPipelineByPropertyName = $true)]
    +      $testword
    +
    +   )
    +
    +   $word = $testword
    +
    +   #define array of blocks
    +   [System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"
    +
    +   #send word to chararray
    +   $chararray = $word.ToCharArray()
    +   $chars = $chararray
    +
    +   #get the character count
    +   $charscount = $chars.count
    +
    +   #get the initial count of the blocks
    +   $blockcount = $blockarray.Count
    +
    +   #find out how many blocks should be left from the difference
    +   #of the blocks and characters in the word - 1 letter/1 block
    +   $correctblockcount = $blockcount - $charscount
    +
    +   #loop through the characters in the word
    +   foreach ($char in $chars)
    +   {
    +
    +      #loop through the blocks
    +      foreach ($block in $blockarray)
    +      {
    +
    +         #check the current character against each letter on the current block
    +         #and break if found so the array can reload
    +         if ($char -in $block[0] -or $char -in $block[1])
    +         {
    +
    +            write-verbose "match for letter - $char - removing block $block"
    +            $blockarray.Remove($block)
    +            break
    +
    +         }
    +
    +      }
    +
    +   }
    +   #get final count of blocks left in array to determine if the word was
    +   #correctly made
    +   $finalblockcount = $blockarray.count
    +   if ($finalblockcount -ne $correctblockcount)
    +   {
    +      write-verbose "$word : $false "
    +      return $false
    +   }
    +   else
    +   {
    +      write-verbose "$word : $true "
    +      return $true
    +   }
    +
    +}
    +
    +#loop all the words and pass them to the function
    +$wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse"
    +foreach ($word in $wordlist)
    +{
    +   test-blocks -testword $word -Verbose
    +}
    diff --git a/Task/ABC-problem/Rebol/abc-problem.rebol b/Task/ABC-problem/Rebol/abc-problem.rebol
    new file mode 100644
    index 0000000000..fe63851d8f
    --- /dev/null
    +++ b/Task/ABC-problem/Rebol/abc-problem.rebol
    @@ -0,0 +1,38 @@
    +Rebol [
    +    title: "Rosetta code: ABC problem"
    +    file:  %ABC_problem.r3
    +    url:   https://rosettacode.org/wiki/ABC_problem
    +    needs: 3.10.0 ;; or something like that
    +    note:  "Based on Red language solution"
    +]
    +;; Define the function 'test' that takes a string argument 's'
    +test: function [s [string!]][
    +    ;; Make a copy of the input string to work on (avoid mutation of original)
    +    s: copy s
    +    ;; Initialize 'p' as a copy of a specific character sequence
    +    p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
    +    ;; Start an infinite loop
    +    forever [
    +        ;; If 's' is empty, return true (all characters matched/removed)
    +        if 0 = length? s [return  true]
    +        ;; If 'p' is at the tail (all pairs tried), return false (no match)
    +        if tail? p       [return false]
    +        ;; Create a parsing rule of the current two characters in 'p'
    +        rule: reduce [first p  '| second p]
    +        ;; Try to parse 's' according to the current rule:
    +        ;; If parsing succeeds, remove that rule from the string
    +        p: either parse s [to rule remove rule to end ] [
    +            ;; If parsing succeeded, remove the current pair from 'p'
    +            head remove/part p 2
    +        ][
    +            ;; If parsing failed, skip the current pair in 'p' (move to next pair)
    +            skip p 2
    +        ]
    +    ]
    +]
    +
    +;; Test the 'test' function on each word split from a string (split by space).
    +foreach word split {A bark book TrEAT COmMoN SQUAD conFUsE} space [
    +    ;; Print the word and its result from 'test'
    +    printf [8 ": "] reduce [word test word]
    +]
    diff --git a/Task/ABC-problem/Uiua/abc-problem.uiua b/Task/ABC-problem/Uiua/abc-problem.uiua
    new file mode 100644
    index 0000000000..244ecba154
    --- /dev/null
    +++ b/Task/ABC-problem/Uiua/abc-problem.uiua
    @@ -0,0 +1,4 @@
    +s   ← "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM"
    +Flt ← ⊂⊙↘₂⊃↙↘-⊸◿2⊸˜⨂ # remove block holding letter
    +{"A" "BARK" "BOOK" "TREAT" "COMMON" "SQUAD" "CONFUSE"}
    +≡⊂⟜⍚(◌◌⍥(⍥(⊙⊙⋅0)⊸≍⟜˜Flt⊙°⊂)◡⋅⧻ s ⊙1)
    diff --git a/Task/ABC-problem/V-(Vlang)/abc-problem.v b/Task/ABC-problem/V-(Vlang)/abc-problem.v
    index cf760dbe08..f34fa80d4b 100644
    --- a/Task/ABC-problem/V-(Vlang)/abc-problem.v
    +++ b/Task/ABC-problem/V-(Vlang)/abc-problem.v
    @@ -1,13 +1,12 @@
    -const
    -(
    -   blocks = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
    -   words = ["A", BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"]
    -)
    +const blocks = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS",
    +"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]
    +
    +const words = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"]
     
     fn main() {
        for word in words {
           println('>>> can_make_word("${word.to_upper()}"): ')
    -      if check_word(word, blocks) == true {println('True')} else {println('False')}
    +      if check_word(word, blocks) == true { println("True") } else { println("False") }
        }
     }
     
    @@ -18,12 +17,12 @@ fn check_word(word string, blocks []string) bool {
           found = false
           for idx, _ in tblocks {
              if tblocks[idx].contains(chr.ascii_str()) == true {
    -            tblocks[idx] =''
    +            tblocks[idx] =""
                 found = true
                 break
              }
           }
    -      if found == false {return found}
    +      if found == false { return found }
        }
        return found
     }
    diff --git a/Task/ABC-problem/Zig/abc-problem.zig b/Task/ABC-problem/Zig/abc-problem.zig
    new file mode 100644
    index 0000000000..ea586f7323
    --- /dev/null
    +++ b/Task/ABC-problem/Zig/abc-problem.zig
    @@ -0,0 +1,54 @@
    +const std = @import("std");
    +
    +const Block: type = struct { Char1: u8, Char2: u8 };
    +const BLOCK_SIZE: comptime_int = 20;
    +const blocks: [BLOCK_SIZE]Block = .{
    +    .{ .Char1 = 'B', .Char2 = 'O' }, .{ .Char1 = 'X', .Char2 = 'K' },
    +    .{ .Char1 = 'D', .Char2 = 'Q' }, .{ .Char1 = 'C', .Char2 = 'P' },
    +    .{ .Char1 = 'N', .Char2 = 'A' }, .{ .Char1 = 'G', .Char2 = 'T' },
    +    .{ .Char1 = 'R', .Char2 = 'E' }, .{ .Char1 = 'T', .Char2 = 'G' },
    +    .{ .Char1 = 'Q', .Char2 = 'D' }, .{ .Char1 = 'F', .Char2 = 'S' },
    +    .{ .Char1 = 'J', .Char2 = 'W' }, .{ .Char1 = 'H', .Char2 = 'U' },
    +    .{ .Char1 = 'V', .Char2 = 'I' }, .{ .Char1 = 'A', .Char2 = 'N' },
    +    .{ .Char1 = 'O', .Char2 = 'B' }, .{ .Char1 = 'E', .Char2 = 'R' },
    +    .{ .Char1 = 'F', .Char2 = 'S' }, .{ .Char1 = 'L', .Char2 = 'Y' },
    +    .{ .Char1 = 'P', .Char2 = 'C' }, .{ .Char1 = 'Z', .Char2 = 'M' },
    +};
    +
    +fn can_make_word(word: []const u8) bool {
    +    var marked: [BLOCK_SIZE]bool = [_]bool{false} ** BLOCK_SIZE;
    +
    +    for (word) |char| {
    +        var hasBlock: bool = false;
    +
    +        for (blocks, 0..) |block, index| {
    +            if ((block.Char1 == char or block.Char2 == char) and !marked[index]) {
    +                hasBlock = true;
    +                marked[index] = true;
    +                break;
    +            }
    +        }
    +
    +        if (!hasBlock) {
    +            return false;
    +        }
    +    }
    +
    +    return true;
    +}
    +
    +pub fn main() !void {
    +    const words: []const []const u8 = &.{
    +        "A",
    +        "BARK",
    +        "BOOK",
    +        "TREAT",
    +        "COMMON",
    +        "SQUAD",
    +        "CONFUSE",
    +    };
    +
    +    for (words) |word| {
    +        std.debug.print("{s}\t{any}\n", .{ word, can_make_word(word) });
    +    }
    +}
    diff --git a/Task/ADFGVX-cipher/APL/adfgvx-cipher.apl b/Task/ADFGVX-cipher/APL/adfgvx-cipher.apl
    new file mode 100644
    index 0000000000..93c8c07787
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/APL/adfgvx-cipher.apl
    @@ -0,0 +1,39 @@
    +adfgvx←{
    +    n←⎕NS''
    +    n.split←↑{⍺≥⍴⍵:⊂⍵ ⋄ (⊂⍺↑⍵),⍺∇⍺↓⍵}
    +
    +    n.enc←⍺{
    +        t←∊(∘.,⍨'ADFGVX')[⊃∘⍸∘(⍺⍺∘=)¨⍵]
    +        w←↓⍉((⍴⍵⍵)split t)[;⍋⍵⍵]
    +        1↓∊' ',¨w~¨' '
    +    }⍵
    +
    +    n.dec←⍺{
    +        t←↓2 split (∊(⍉↑⍵⊆⍨' '≠⍵)[;⍋⍋⍵⍵])~' '
    +        ⍺⍺['ADFGVX'∘⍳¨t]
    +    }⍵
    +
    +    n
    +}
    +
    +adfgvx_test←{
    +    square←6 6⍴(⎕A,⎕D)[?⍨36]
    +    ⎕←'Polybius square:'
    +    ⎕←' ─ADFGVX','│┼││││││','A D F G V X' ⍪'─'⍪(11⍴1 0)\square
    +    ⎕←''
    +
    +    key←{
    +        file←'e:\unixdict.txt'
    +        dict←(~data∊⎕TC)⊆data←⊃⎕NGET file
    +        dict←(⍵{⍺=≢⍵}¨dict)/dict
    +        dict←({⍵≡∪⍵}¨dict)/dict
    +        1⎕C ⊃dict[?⍴dict]
    +    }9
    +    ⎕←'Key: ',key
    +
    +    a←square adfgvx key
    +
    +    ⎕←'Plaintext: ',plaintext←'ATTACKAT1200AM'
    +    ⎕←'Encrypted: ',encrypted←a.enc plaintext
    +    ⎕←'Decrypted: ',a.dec encrypted
    +}
    diff --git a/Task/ADFGVX-cipher/Crystal/adfgvx-cipher.cr b/Task/ADFGVX-cipher/Crystal/adfgvx-cipher.cr
    new file mode 100644
    index 0000000000..3236abc45a
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Crystal/adfgvx-cipher.cr
    @@ -0,0 +1,62 @@
    +def make_square
    +  # it's a square at heart...
    +  (('A'..'Z').to_a + ('0'..'9').to_a).shuffle!
    +end
    +
    +def make_key (size)
    +  words = File.open("unixdict.txt") do |f|
    +    f.each_line.select {|w| w.size == size && w.chars.to_set.size == size }.to_a
    +  end
    +  raise "no suitable key found" if words.empty?
    +  words.sample
    +end
    +
    +def adfgvx_encrypt (message, square, key)
    +  h = "ADFGVX".chars
    +  message.chars.flat_map {|ch|
    +    row, col = square.index!(ch).divmod(6)
    +    [ h[row], h[col] ]
    +  }
    +    .in_groups_of(key.size)
    +    .transpose
    +    .zip(key.chars)
    +    .sort_by {|_, key| key }
    +    .map {|col, _| col.join }
    +    .join(" ")
    +end
    +
    +def adfgvx_decrypt (message, square, key)
    +  h = "ADFGVX".chars
    +  sorted_key = key.chars.sort!
    +  cols = message.split.map &.chars
    +  max_size = cols.max_of &.size
    +  cols.map {|col| col + [nil]*(max_size-col.size) }
    +    .zip(sorted_key)
    +    .sort_by {|_, ch| key.index! ch }
    +    .map {|col, _| col }
    +    .transpose
    +    .flatten.compact
    +    .in_slices_of(2)
    +    .map {|(row, col)| square[ h.index!(row)*6 + h.index!(col) ] }
    +    .join
    +end
    +
    +def show (title, message, square, key)
    +  encrypted = adfgvx_encrypt message, square, key
    +  decrypted = adfgvx_decrypt encrypted, square, key
    +  puts title
    +  puts " - Alphabet: #{square.join}"
    +  puts " - Key:      #{key}"
    +  puts " - Message:   #{message}"
    +  puts " - Encrypted: #{encrypted}"
    +  puts " - Decrypted: #{decrypted}"
    +  puts
    +end
    +
    +message = "ATTACKAT1200AM"
    +
    +wiki_square = "NA1C3H8TB2OME5WRPD4F6G7I9J0KLQSUVXYZ".chars
    +wiki_key = "PRIVACY"
    +
    +show "Wikipedia example:", message, wiki_square, wiki_key
    +show "Random square and key:", message, make_square, make_key(9)
    diff --git a/Task/ADFGVX-cipher/Fortran/adfgvx-cipher.f b/Task/ADFGVX-cipher/Fortran/adfgvx-cipher.f
    new file mode 100644
    index 0000000000..40af143af8
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Fortran/adfgvx-cipher.f
    @@ -0,0 +1,618 @@
    +!
    +! ADFGVX Cipher
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +! VSI Fortran on VMS does not compile it because it cannot handle
    +! allocatable character strings.
    +! U.B., December 2025
    +!==============================================================================
    +
    +program ADFGVXCipher
    +
    +  implicit none
    +
    +  logical, parameter :: DEBUG = .false.     ! set to .true. for reproducable, not random results
    +  logical, parameter :: VERBOSE = .false.   ! set this to .true. to print some intermediate results
    +  integer, parameter :: maxLen=100          ! Maximum length of any test message (including extensions as 'X')
    +
    +  integer, parameter :: minPassLen=7, maxPassLen=12   ! Minimum and maximum password length
    +
    +  ! The complete alphabet of capital letters as used in most western languages, plus numbers 0...9
    +  character (len=36), parameter :: Alphabet ='ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567879'
    +  character (len=*), parameter :: ADFGVX = 'ADFGVX'
    +
    +  character (len=maxLen)    :: MsgToEncrypt, DecryptedMsg
    +  character (len=2*maxLen) :: EncryptedMsg   ! encrypt makes 2 letters from 1
    +  character (len=25)        :: PassPhrase
    +  integer, parameter :: ColWidth = 6     ! depends on length of the used alphabet but we use only 36 letters
    +
    +  character (len=36) :: PolyAlphabet      ! Permutation of Alphabet to represent Polybius square
    +  integer :: i
    +
    +  ! Initialize random number generator once for the entire run-time of the program and all test cases
    +  call random_seed()
    +
    +
    +  ! The message to encrypt - for 1 test case
    +  ! the plain text message is from the task description
    +  MsgToEncrypt = 'ATTACKAT1200AM'
    +
    +  if (.not. DEBUG) then
    +    print  '("Init: DEBUG is .false., i.e. password and Polybius square are randomized.")'
    +    PassPhrase = getRandomPassPhrase()       ! select random password from unixdict.txt
    +  else
    +    ! for DEBUG only: force constant password for reproducible result:
    +    print  '("Init: DEBUG is .true., i.e. the code reproduces results of the NIM solution")'
    +    PassPhrase = 'EXCURSION'  ! Taken from the NIM solution
    +  endif
    +
    +  print '("Init: PassPhrase for encode and decode is ", A)' , PassPhrase
    +
    +  if (.not. DEBUG) then
    +    call createRandomPolybiusSquare ()       ! Create random Permutation of Alphabet to represent Polybius square
    +  else
    +    ! For DEBUG only: force constant string for reproducable results
    +    ! Both the Alphabet and the password are from the NIM solution.
    +    ! If DEBUG is .true., the result of the NIM solution is exactly reproduced.
    +    PolyAlphabet =   'XOFPD6VHC40ZJMKRU5IA9YBW3L21NGQTE78S'
    +  endif
    +
    +  call PrintSquare ("Init: Following Polybius square is used for encode/decode:", PolyAlphabet, ColWidth)
    +
    +  call encode (MsgToEncrypt , EncryptedMsg, PolyAlphabet, PassPhrase)
    +  call decode (EncryptedMsg, DecryptedMsg, PolyAlphabet, PassPhrase)
    +
    +  call printResult (MsgToEncrypt, EncryptedMsg, DecryptedMsg)
    +
    +contains
    +
    +
    +
    +! ==========================================================
    +! Find random length of the new password,
    +! then pick a random word of this length from the word list
    +! ==========================================================
    +function getRandomPassPhrase()   result (retval)
    +  character (len=maxPassLen) :: retval
    +  integer :: leng                                             ! required length of password to pick
    +
    +  leng = randominInterval (minPassLen, maxPassLen)
    +  retval = getRandomWord (leng)
    +
    +end function getRandomPassPhrase
    +
    +! ==================================================================================
    +! Read the wordlist unixdict.txt and select a random word  with the requested length
    +! ==================================================================================
    +function getRandomWord (leng) result (retval)
    +  integer, intent(in) :: leng
    +  character (len=maxPassLen) :: retval
    +
    +  character(len=100)  :: word                                     ! is longer than expected input word length
    +  character (len=maxPassLen), allocatable :: Candidates (:)
    +  integer:: capacity, content
    +  integer :: io_stat, l, idx, ii
    +
    +  ! Read all words from unixdict.txt having length "len" and no repeating letters
    +  open(unit=10, file='unixdict.txt', status='old', action='read', iostat=io_stat)
    +  if (io_stat .ne. 0) then      ! File open MUST be successful, otherwise total program failure.
    +     print *, "Error opening file"
    +     stop
    +  end if
    +  capacity = 128
    +  call resize (Candidates, maxPassLen, capacity)
    +  content = 0
    +  do
    +    read (10,'(A)', iostat=io_stat)   word               ! ok for both intel and GNU.
    +    l = len_trim (word)                                  ! use this instead of Q format
    +    if (io_stat < 0) exit    ! EOF: Normal end of this loop
    +    if (io_stat > 0) then
    +      print *, "Read error" ! ERROR: (never seen)
    +      exit
    +    end if
    +    if (l .ne. leng) cycle
    +    if (hasDuplicateChars(word)) cycle
    +    if (content .eq. capacity) then
    +      capacity = capacity * 2
    +      call resize (Candidates, maxPassLen, capacity)
    +    end if
    +    content = content + 1
    +    Candidates (content) = word
    +  enddo
    +  idx = randominInterval (1, content)
    +  retval = candidates (idx)
    +  do ii=1, leng
    +    if (retval(ii:ii) .ge. 'a' .and. retval(ii:ii) .le. 'z') then
    +      retval(ii:ii) = char (ichar(retval(ii:ii)) - ichar('a') + ichar('A'))
    +    endif
    +  end do
    +  close (10)
    +
    +end function getRandomWord
    +
    +! ========================================================================
    +! Return true if argument word contains duplicate letters, otherwise false.
    +! ========================================================================
    +function hasDuplicateChars (word) result (itHas)
    +  character (len=*), intent(in) :: word
    +  logical :: itHas
    +  integer :: ii, jj, l
    +  l = len_trim(word)
    +  do ii=1, l
    +    do jj=ii+1, l
    +      if (word(ii:ii) .eq. word(jj:jj)) then
    +        itHas = .true.
    +        return
    +      endif
    +    end do
    +  end do
    +  itHas = .false.
    +end function hasDuplicateChars
    +
    +
    +  !==============================================================
    +  ! Creating a random Polybius square is equivalent with creating
    +  ! a random permutation of the used alphabet
    +  ! Use the Sattolo algorithm to create such a permutation .
    +  !==============================================================
    +subroutine createRandomPolybiusSquare ()
    +
    +  character :: tmp                                      ! for swapping single letters
    +
    +  integer :: j, k, l                                    ! Helper variables: indices into words, words' length
    +
    +
    +  PolyAlphabet = Alphabet
    +  l = len (Alphabet)
    +  do j = l, 1, -1                                       ! For all letters from end down to begin
    +    k = randominInterval (1, j-1)                       ! Select random letters between 1 and j-1
    +    tmp = PolyAlphabet(j:j)                             ! then swap letter at pos j with letter at pos k
    +    PolyAlphabet (j:j) = PolyAlphabet (k:k)
    +    PolyAlphabet (k:k) = tmp
    +  end do
    +
    +end subroutine createRandomPolybiusSquare
    +
    +
    +
    +! =============================================
    +! Increase allocated size of string array 'var'
    +! =============================================
    +subroutine resize(var, sLen, newSize)
    +  integer, intent(in)                              :: sLen       ! LEngth of 1 element of string array
    +  character (len=sLen), allocatable, intent(inout) :: var(:)     ! The array to be increased
    +  integer, intent(in)                              :: newSize    ! The new size of var
    +  character (len=sLen), allocatable                :: tmp(:)     ! Temporary storage
    +  integer                                          :: oldSize    ! Current array size
    +  integer                                          :: ii         ! Loop index
    +
    +  ! Copy allocated values to temporary, then allocate var with
    +  ! new size and copy back saved values.
    +  ! Could be done with move_alloc but this would not be portable to OpenVMS Fortran
    +
    +  if (allocated(var)) then
    +    oldSize = size(var)
    +  else
    +    oldSize = 0
    +  end if
    +
    +  if (newSize .gt. oldSize) then           ! only increment
    +    if (oldSize .gt.0) then
    +      allocate(tmp (oldSize))
    +      tmp(:oldSize) = var(:oldSize)
    +      deallocate (var)
    +    end if
    +    allocate(var(newSize))
    +    if (allocated(tmp) .and. allocated (var) ) then
    +      oldSize = min(size(tmp, 1), size(var, 1))
    +      var(:oldSize) = tmp(:oldSize)
    +      deallocate (tmp)
    +    end if
    +  end if
    +end subroutine resize
    +
    +
    +  ! ===========================================================
    +  ! Generate random number between @lo and @hi (inclusive)
    +  ! Assume Random Number Generator has been initialized before.
    +  ! ===========================================================
    +function randominInterval (lo, hi) result (r)
    +  integer, intent(in) :: lo, hi                         ! the interval
    +  integer :: r                                          ! resultant (pseudo-)random number
    +  real :: rnd                                           ! Fortran random number generator generates float values
    +
    +  call random_number (rnd)
    +  r = lo + FLOOR((hi+1-lo)*rnd)                         ! We want to choose one between [lo,hi]
    +
    +end function randominInterval
    +
    +
    +
    +! =============================================
    +! Encode a given string using the ADFGVX Cipher
    +! =============================================
    +subroutine encode (argInString, outString, argAlphabet, argPassPhrase)
    +  character (len=*), intent(in)  :: argInString     ! The string to encode
    +  character (len=*), intent(out) :: outString       ! The resultant encoded text
    +  character (len=*), intent(in)  :: argAlphabet     ! The alphabet that makes the Polybius square
    +  character (len=*), intent(in) :: argPassPhrase    ! the password used for encode and also decode.
    +  integer :: nRow
    +  integer :: argLen, passLen, newlen, ii, jj, kk, row, col
    +  character(len=2*len(OutString)+len_trim(argPassPhrase))  newAlphabet
    +
    +  character, dimension(:,:), allocatable :: Matrix, expandedMatrix
    +
    +  argLen = len_trim (argInString)
    +  passLen = len_trim (argPassPhrase)
    +  newlen = len(OutString)+len_trim(argPassPhrase)
    +  ! 1st step: encode with the given alphabet (resp. the equivalent 6x6 square),
    +  ! the output string being the row/col of each letter, expressed in terms of ADFGVX
    +  outString = ' '
    +  jj = 1
    +  do ii=1,argLen
    +    call getRC (argInString(ii:ii),row,col, argAlphabet)
    +    outString (jj:jj) = ADFGVX (row:row)
    +    jj = jj + 1
    +    outString (jj:jj) = ADFGVX (col:col)
    +    jj = jj + 1
    +  end do
    +
    +  if (VERBOSE) then
    +    print '("Encode, first step: ")'
    +    do ii=1, arglen
    +      write (*,'(A3)', advance='no') ArgInString (ii:ii)
    +    end do
    +    print *, 'becomes'
    +
    +    do ii=1, 2*argLen, 2
    +      write (*,'(x,A2)', advance='no') outString (ii:ii+1)
    +    end do
    +    write (*,'(///)')
    +  endif
    +
    +  jj = 1
    +  kk = 1
    +  newAlphabet = argPassPhrase (:passLen) // outString(:len_trim(outString))
    +
    +  nRow = (len_trim (newAlphabet) + passLen - 1)/passLen ! Required net number of lines for the Matrix
    +  allocate (Matrix (passLen, nRow))
    +
    +  ! Without any complications: Just accept that last line might be incomplete - complete it with spaces.
    +  do row=1, nRow
    +    do col=1,passLen
    +      if (row .eq. 1 ) then                             ! Top row gets the password
    +        Matrix (col,row) = newAlphabet (jj:jj)
    +        jj = jj + 1
    +      else
    +        if (jj .gt. len_trim(newAlphabet)) then         ! Entire new alphabet copied to Matrix
    +          Matrix(col,row) = ' '                         ! remaining Matrix is all blank
    +        else
    +          Matrix (col,row) = newAlphabet (jj:jj)
    +          jj = jj + 1
    +        endif
    +      endif
    +    end do
    +    if (jj .gt. len_trim(newAlphabet)) exit
    +  end do
    +  jj = 1
    +  do row=1, nRow
    +    do col=1,passLen
    +      newAlphabet (jj:jj) = Matrix (col,row)
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Encode: This results in a new matrix: ', Matrix, nRow, passLen)
    +  ! Sort columns
    +  call quicksort_matrix (Matrix, passLen, nRow, 1, passlen)
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Encode: After sorting columns, this becomes: ', Matrix, nRow, passLen)
    +
    +  jj = 1
    +  do row=1, nRow
    +    do col=1,passLen
    +      newAlphabet (jj:jj) = Matrix (col,row)
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  allocate (expandedMatrix (passLen, nRow))
    +  ! Initialize al to blank
    +  do row=1, 2*kk
    +    do col=1,passLen
    +      expandedMatrix (col,row) = ' '
    +    end do
    +  end do
    +
    +  jj=1
    +  do row=1, nRow
    +    do col=1,passLen
    +      if (jj .le. len_trim(newAlphabet))  then
    +        expandedMatrix (col,row) = newAlphabet (jj:jj)
    +      else
    +        expandedMatrix (col,row) = ' '
    +      endif
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  outString = ' '
    +  jj = 1
    +  do col=1,passLen
    +    do row=2, nRow
    +      if (expandedMatrix (col,row) .ne. ' ') then
    +        outString (jj:jj) = expandedMatrix (col,row)
    +        jj = jj + 1
    +      end if
    +    end do
    +    outString (jj:jj) = ' '
    +    jj = jj + 1
    +  end do
    +
    +end subroutine encode
    +
    +
    +! ==================================================================================
    +! Sort columns of a Matrix, taking elements of top row as key to decide "lt" or ge".
    +! ==================================================================================
    +recursive subroutine quicksort_matrix (mat, ncols, nrows, low, high)
    +
    +  integer, intent(in) :: ncols,nrows
    +  character, dimension (ncols,nrows), intent(inout) :: mat
    +
    +  integer, intent(in) :: low, high
    +  integer :: pivot_index
    +  integer :: i, j, mid
    +  character :: pivot, temp
    +
    +  if (low .lt. high) then
    +    ! The list is already "almost sorted", so use midlle word as pivot.
    +    mid = low + (high-low) / 2
    +    pivot = mat (mid,1)
    +
    +    !Move pivot to the end
    +    call swapMat (mat,ncols,nrows,mid,high)
    +
    +    i = low - 1
    +    do j = low, high - 1
    +      if (mat(j,1) .le. pivot) then
    +        i = i + 1
    +        call swapMat (mat,ncols,nrows,i,j)
    +      end if
    +    end do
    +
    +    call swapMat (mat,ncols,nrows,i+1,high)
    +    pivot_index = i + 1
    +
    +    call quicksort_matrix (mat, ncols,nrows, low, pivot_index - 1)
    +    call quicksort_matrix (mat, ncols,nrows,  pivot_index + 1, high)
    +  end if
    +end subroutine quicksort_matrix
    +
    +! ===============================================
    +! Swap two columns of a Matrix (Used for sorting)
    +! ===============================================
    +subroutine swapMat (mat,ncols,nrows,col1,col2)
    +  integer, intent(in) :: ncols,nrows                        ! Size of ...
    +  character, dimension (ncols,nrows), intent(inout) :: mat  ! ... the matrix
    +  integer, intent(in) :: col1, col2                         ! The 2 columns to swap
    +
    +  character :: tmp                                    ! Helpers to swap 2 elements
    +  integer :: row
    +
    +  ! early return in trivial noop case
    +  if (col1 .eq. col2) return
    +
    +  do row=1, nrows                                    ! Swap all elements of col 1 and col 2
    +    tmp = mat (col1,row)
    +    mat (col1,row) = mat(col2,row)
    +    mat(col2,row) = tmp
    +  end do
    +
    +end subroutine swapMat
    +
    +! =======================================================
    +! Decode a given (encoded) string using the ADFGVX Cipher
    +! =======================================================
    +subroutine decode (argInString, outString, argAlphabet, argPassPhrase)
    +  character (len=*), intent(in)  :: argInString     ! The encoded string to decode
    +  character (len=*), intent(out) :: outString       ! Result of the decode
    +  character (len=*), intent(in)  :: argAlphabet     ! The Polybius Square to encode and decode
    +  character (len=*), intent(in) :: argPassPhrase    ! The Password used to encode and decode
    +  character (len=MaxLen) :: tmpString               ! Temporary torage for intermediate result
    +  character, allocatable :: Matrix (:,:)            ! Matrix to constructed from input string
    +  character (len=:),allocatable :: SortedPassPhrase ! The password after sorting its letters
    +  integer :: nRow, passLen                          ! NMUmbner of rows and columns of above Matrix
    +  integer :: inLen, col,row, ii, jj, idx            ! Length of input string, and some helpers
    +
    +  ! Estimate input string lengths
    +  inLen = len_trim (argInString)
    +  passLen = len_trim (argPassPhrase)
    +
    +  outString = ' '
    +  nRow = (inLen + (passLen-1)) / passLen  + 1     ! 1 extra for top row = password
    +
    +  allocate (Matrix (passLen, nRow))
    +
    +  ! Initialize entire matrix
    +  do col=1,passLen
    +    do row=1, nRow
    +      Matrix (col,row) = ' '
    +    end do
    +    ! Fill the column as far as required
    +  end do
    +
    +
    +  ! The columns of the result matrix are sorted as password letters and
    +  ! the sorted password letters makeup top row of th is matrix
    +  SortedPassPhrase = argPassPhrase
    +  call  quicksort_matrix (SortedPassPhrase, passlen,  1, 1, passlen)
    +
    +  row=1
    +  do col=1, passLen
    +    Matrix (col,row) = SortedPassPhrase(col:col)
    +  end do
    +
    +  ! Set rest ( row 2 ff.) of the Matrix: column by column
    +  jj = 1
    +  do col=1,passLen
    +    row = 2
    +    do while (argInString (jj:jj) .ne. ' ')
    +      Matrix (col,row) = argInString (jj:jj)
    +      jj = jj + 1
    +      row = row + 1
    +    enddo
    +    jj = jj + 1
    +  end do
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Decode: the reconstructed Code matrix is ', Matrix, nROw, passLen)
    +
    +  ! We know the columns of this matrix are sorted together with the password
    +  !
    +  ! restore the correct order of thet sorted matrix
    +  call UndoSort (Matrix, passLen, nRow, argPassPhrase, passlen)
    +
    +  if (VERBOSE) &
    +    call printMatrix ('Decode: After Undo Sorting, this becomes', Matrix, nRow, passLen)
    +
    +  ! The matrix is in the correct order now, so its rows, one by one,  represent the first encoded string
    +  !
    +  jj = 1
    +  tmpString = ' '
    +  do row = 2, nRow          ! Skip top row (=Passwprd)
    +    do col=1,passLen
    +      tmpString (jj:jj) = Matrix(col,row)
    +      jj = jj + 1
    +    end do
    +  end do
    +
    +  ! Now we have the encoded string, each 2 letters are row/col in ADFGVX scheme
    +  jj = 1
    +  do ii=1, len_trim(tmpString), 2
    +    row = index (ADFGVX, tmpString(ii:ii))
    +    col = index (ADFGVX, tmpString((ii+1) : (ii+1)))
    +    outString (jj:jj) = getChar (row,col,argAlphabet)   ! Decode from row/col to clear text
    +    jj = jj + 1
    +  end do
    +end subroutine decode
    +
    +! =============================================================================
    +! Print all nRow x nCol elements of a Matrix, togehther with a descriptive text
    +! =============================================================================
    +subroutine printMatrix (comment, Matrix, nRow, nCol)
    +  integer, intent(in) :: nRow, nCol
    +  character (len=*), intent(in) :: Comment
    +  character , intent(in) :: Matrix (nCol, nRow)
    +  integer :: r, c
    +
    +  write (*,'(/A/)')  Comment
    +  do r=1, nROw
    +    do c=1, nCol
    +      write (*, '(A2)', advance='no')  Matrix(c,r)
    +    end do
    +    write (*,*)
    +  end do
    +end subroutine printMatrix
    +
    +!=============================================================
    +! Matrix has been sorted before, with top row as key elements.
    +! Here undo that sort operation
    +!=============================================================
    +subroutine UndoSort (Matrix, nCol, nRow, argPassPhrase, passLen)
    +  integer, intent(in) :: nCol, nRow, passLen
    +  character, intent(inout)  :: Matrix (nCol, nROw)
    +  character                 :: resultMatrix (nCol, nROw)
    +
    +  character (len=passLen), intent(in) :: argPassPhrase
    +
    +  integer :: ii, jj, kk
    +
    +  do ii=1, passLen
    +    ! find whatever letter should be at pos ii within the unscrambled string
    +    jj = index (argPassPhrase, Matrix(ii, 1) )
    +    ! so letter "PassPhrase(jj:jj)" should be at pos ii in line 1 of Matrix
    +    if (jj .ne. ii) then
    +      do kk=1, nRow
    +        resultMatrix (jj,kk) = Matrix(ii,kk)
    +      end do
    +    else
    +      do kk=1, nRow
    +        resultMatrix (jj,kk) = Matrix(jj,kk)
    +      end do
    +    endif
    +  end do
    +  matrix = resultMatrix
    +end subroutine UndoSort
    +
    +
    +! ======================================================
    +! Get Row and Column  of a letter in the Polybius square
    +! ======================================================
    +subroutine getRC (c,row,col, argAlphabet)
    +  character, intent(in) :: c
    +  integer, intent(out) :: row,col
    +  character (len=*), intent(in)  :: argAlphabet             ! Argument to use for encoding
    +  integer :: idx
    +
    +  idx = index (argAlphabet, c) - 1
    +
    +  row = 1 + idx / ColWidth
    +  col = 1 + mod (idx, ColWidth)
    +
    +end subroutine getRC
    +
    +! ==================================================
    +! Return letter in row column of the Polybius square
    +! ==================================================
    +function getChar (row,column,argAlphabet) result (chr)
    +  integer, intent(in) :: row, column
    +  character (len=*), intent(in)  :: argAlphabet             ! Argument to use for encoding
    +  character :: chr
    +  integer :: idx
    +
    +  idx = (row-1) * ColWidth + column
    +  chr = argAlphabet (idx:idx)
    +
    +end function getChar
    +
    +! ===========================================
    +! Print original, encoded and decoded strings
    +! ===========================================
    +subroutine printResult (m1,m2,m3)
    +  character (len=*), intent(in) :: m1,m2,m3
    +  write (*,'("Original:  ", A)')  m1(:len_trim(m1))
    +  write (*,'(" Encoded:  ", A)')  m2(:len_trim(m2))
    +  write (*,'(" Decoded:  ", A)')  m3(:len_trim(m3))
    +  print *
    +end subroutine printResult
    +
    +! ================================================================================
    +! Print the resulting Polybius square based on the alphabet used for encode/decode
    +! ================================================================================
    +subroutine PrintSquare (Comment, Alp, cw)
    +  character (len=*), intent(in) :: Comment
    +  character (len=*), intent(in)  :: Alp
    +  integer, intent(in) :: cw                                     ! column width for dormatted display
    +  integer:: ii, l
    +
    +  l = len_trim(alp)
    +  write (*,'(/A/)')  Comment
    +  Write (*, "('   A D F G V X', /,' +------------',/  A, '|')", advance='no') ADFGVX (1:1)
    +  do ii=1, l
    +    write (*, '(A2)', advance='no')  Alp(ii:ii)
    +    if (mod (ii, cw) .eq. 0) then
    +      if (ii .ne. l)  then
    +        write (*,'(/,A1,"|")', advance='no') ADFGVX (1 +  ii/cw:1 +  ii/cw)
    +      else
    +        write (*,*) ! just EOL
    +      endif
    +    endif
    +  end do
    +  print *                                                       ! one extra blank line
    +end subroutine PrintSquare
    +
    +
    +end program ADFGVXCipher
    diff --git a/Task/ADFGVX-cipher/Free-Pascal-Lazarus/adfgvx-cipher.pas b/Task/ADFGVX-cipher/Free-Pascal-Lazarus/adfgvx-cipher.pas
    new file mode 100644
    index 0000000000..b35f201644
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Free-Pascal-Lazarus/adfgvx-cipher.pas
    @@ -0,0 +1,198 @@
    +program adfgvxcipher;
    +
    +uses
    +  SysUtils,
    +  Classes;
    +
    +const
    +  ADFGVX = 'ADFGVX';
    +  ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    +  MESSAGE = 'ATTACKAT1200AM';
    +
    +type
    +  //tPolybiusarr = array[1..6,1..6] of string;
    +  tPolybiusarr = array[1..6, 1..6] of char;
    +
    +  procedure init_Polybius(var Polybius: tPolybiusarr);
    +
    +    procedure ShuffleString(var S: string);
    +    var
    +      i, j: integer;
    +      c: char;
    +    begin
    +      for i := Length(S) downto 2 do
    +      begin
    +        j := Random(i) + 1;  // 1..i
    +        c := S[i];
    +        S[i] := S[j];
    +        S[j] := c;
    +      end;
    +    end;
    +
    +  var
    +    ShuffledAlphabet: string;
    +    x, y, i: integer;
    +  begin
    +    ShuffledAlphabet := ALPHABET;
    +    ShuffleString(ShuffledAlphabet);
    +    i := 1;
    +    for x := 1 to 6 do
    +      for y := 1 to 6 do
    +      begin
    +        Polybius[x, y] := ShuffledAlphabet[i];
    +        Inc(i);
    +      end;
    +  end;
    +
    +  procedure PrintPolybius(Polybius: tPolybiusarr);
    +  var
    +    x, y: integer;
    +    ch: char;
    +  begin
    +    writeln('The 6 x 6 Polybius square:');
    +    writeln;
    +    Write('  |');
    +    for ch in ADFGVX do
    +      Write(ch: 2);
    +    writeln;
    +    writeln('---------------');
    +    for x := 1 to 6 do
    +    begin
    +      Write(ADFGVX[x], ' |');
    +      for y := 1 to 6 do
    +      begin
    +        Write(Polybius[x, y]: 2);
    +      end;
    +      writeln;
    +    end;
    +  end;
    +
    +  function CreateKey(size: integer): string;
    +
    +    procedure FilterList(var lst: TStringList; size: integer);
    +
    +      function HasRepeatedCharacters(const str: string): boolean;
    +      var
    +        seen: array[0..255] of boolean;
    +        i: integer;
    +        c: byte;
    +      begin
    +        FillChar(seen, SizeOf(seen), False);
    +        for i := 1 to Length(str) do
    +        begin
    +          c := Ord(str[i]);
    +          if seen[c] then
    +            Exit(True);    // repeated character found
    +          seen[c] := True;
    +        end;
    +        Result := False;   // no repeats
    +      end;
    +
    +    var
    +      x: integer;
    +    begin
    +      for x := lst.Count - 1 downto 0 do
    +        if (length(lst[x]) <> size) or HasRepeatedCharacters(lst[x]) then lst.Delete(x);
    +    end;
    +
    +  const
    +    FNAME = 'unixdict.txt';
    +  var
    +    list: TStringList;
    +  begin
    +    if (size < 7) or (size > 12) then
    +    begin
    +      writeln('Key should contain between 7 and 12 letters, both inclusive.');
    +      halt;
    +    end;
    +    list := TStringList.Create;
    +    list.LoadFromFile(FNAME);
    +    filterlist(list, size);
    +    Result := UpperCase(list[random(list.Count)]);
    +    list.Free;
    +  end;
    +
    +  function FindCharachter(ch: char; polybius: tPolybiusarr): string;
    +  var
    +    x, y: integer;
    +  begin
    +    for x := 1 to 6 do
    +      for y := 1 to 6 do
    +        if polybius[x, y] = ch then
    +          exit(ADFGVX[x] + ADFGVX[y]);
    +  end;
    +
    +  function Encrypt(plainText, key: string; Polybius: tPolybiusarr): string;
    +  var
    +    ch: char;
    +    str: string;
    +    lst: TStringList;
    +    x, keylength: integer;
    +  begin
    +    str := '';
    +    keylength := length(key);
    +    lst := TStringList.Create;
    +    for x := 1 to keylength do
    +      lst.Add(key[x]);
    +    x := 0;
    +    for ch in plainText do
    +    begin
    +      lst[x] := lst[x] + FindCharachter(ch, Polybius);
    +      Inc(x);
    +      if x = keylength then x := 0;
    +    end;
    +    lst.Sort;
    +    writeln;
    +    for x := 0 to keylength - 1 do
    +      str := str + lst[x] + ' ';
    +    Result := TrimRight(str);
    +    lst.Free;
    +  end;
    +
    +  function Decrypt(encryptedTex, key: string; polybius: tPolybiusarr): string;
    +    // Note: simplified decryption logic for demonstration purposes
    +    // need some work for longer messages
    +  var
    +    lst, tmp: TStringList;
    +    ch: char;
    +    s, str: string;
    +  begin
    +    lst := TStringList.Create;
    +    tmp := TStringList.Create;
    +    lst.AddDelimitedtext(encryptedTex, ' ', True);
    +    for ch in key do
    +      for str in lst do
    +        if str[1] = ch then
    +        begin
    +          tmp.Add(str);
    +          break;
    +        end;
    +    Result := '';
    +    s := '';
    +    for str in tmp do
    +    begin
    +      Result := Result + polybius[pos(str[2], ADFGVX), pos(str[3], ADFGVX)];
    +      if length(str) > 3 then s := s + polybius[pos(str[4], ADFGVX), pos(str[5], ADFGVX)];
    +    end;
    +    Result := Result + s;
    +    lst.Free;
    +    tmp.Free;
    +  end;
    +
    +var
    +  Polybius: tPolybiusarr;
    +  key, encryptedMessage, decryptedMessage: string;
    +
    +begin
    +  Randomize;
    +  init_Polybius(Polybius);
    +  PrintPolybius(Polybius);
    +  key := createkey(Random(12 - 7 + 1) + 7); //set length of word to 7 - 12
    +  encryptedMessage := Encrypt(MESSAGE, key, Polybius);
    +  decryptedMessage := Decrypt(encryptedMessage, key, polybius);
    +  writeln('The key is              : ', key);
    +  writeln('the plain message is    : ', MESSAGE);
    +  writeln('the encrypted message is: ', encryptedMessage);
    +  writeln('the decrypted message is: ', decryptedMessage);
    +
    +end.
    diff --git a/Task/ADFGVX-cipher/Mathematica/adfgvx-cipher.math b/Task/ADFGVX-cipher/Mathematica/adfgvx-cipher.math
    new file mode 100644
    index 0000000000..b66c4cb9fc
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/Mathematica/adfgvx-cipher.math
    @@ -0,0 +1,24 @@
    +encrypt[plaintext_, polybius_, key_] := Module[{fraction, fractioned},
    +   fraction = Thread[Characters[polybius] -> Tuples[Characters["ADFGVX"], 2]];
    +   fractioned = Partition[Flatten[Characters[plaintext] /. fraction], UpTo[StringLength[key]]];
    +   StringJoin[Flatten[Part[Flatten[fractioned, {2}], Ordering[Characters[key]]]]]];
    +
    +decrypt[encrypted_, polybius_, key_] := Module[{perm, colLengths, fractioned, defraction},
    +   perm = Ordering[Characters[key]];
    +   colLengths = Length /@ Part[Flatten[Partition[Characters[encrypted], UpTo[Length[perm]]], {2}], perm];
    +   fractioned = Flatten[Part[TakeList[Characters[encrypted], colLengths], InversePermutation[perm]], {2}];
    +   defraction = Thread[Tuples[Characters["ADFGVX"], 2] -> Characters[polybius]];
    +   StringJoin[Partition[Flatten[fractioned], 2] /. defraction]];
    +
    +words = ReadList["unixdict.txt", Word];
    +key = Select[words, StringLength[#] == 9 && DuplicateFreeQ[Characters[#]] &] // RandomChoice;
    +polybius = StringJoin@RandomSample@Characters["ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"];
    +plaintext = "ATTACKAT1200AM";
    +encrypted = encrypt[plaintext, polybius, key];
    +decrypted = decrypt[encrypted, polybius, key];
    +
    +Print["Key: ", key];
    +Print["Polybius: ", polybius];
    +Print["Plaintext: ", plaintext];
    +Print["Encrypted: ", encrypted];
    +Print["Decrypted: ", decrypted];
    diff --git a/Task/ADFGVX-cipher/R/adfgvx-cipher.r b/Task/ADFGVX-cipher/R/adfgvx-cipher.r
    new file mode 100644
    index 0000000000..87fc86e172
    --- /dev/null
    +++ b/Task/ADFGVX-cipher/R/adfgvx-cipher.r
    @@ -0,0 +1,173 @@
    +# The ADFGVX cipher.
    +# See also eg. https://www.nku.edu/~christensen/092hnr304%20ADFGVX.pdf
    +
    +# ADFGVX class using R6
    +library(R6)
    +
    +ADFGVX <- R6Class("ADFGVX",
    +  public = list(
    +    polybius = NULL,
    +    pdim = NULL,
    +    key = NULL,
    +    keylen = NULL,
    +    alphabet = NULL,
    +    encode = NULL,
    +    decode = NULL,
    +
    +    # Constructor
    +    initialize = function(s, k, alph = "ADFGVX") {
    +      self$polybius <- toupper(strsplit(s, "")[[1]])
    +      self$pdim <- floor(sqrt(length(self$polybius)))
    +      self$alphabet <- toupper(strsplit(alph, "")[[1]])
    +
    +      # Create encoding dictionary
    +      self$encode <- list()
    +      for (i in 1:self$pdim) {
    +        for (j in 1:self$pdim) {
    +          char <- self$polybius[(i - 1) * self$pdim + j]
    +          self$encode[[char]] <- c(self$alphabet[i], self$alphabet[j])
    +        }
    +      }
    +
    +      # Create decoding dictionary
    +      self$decode <- list()
    +      for (char in names(self$encode)) {
    +        key_str <- paste(self$encode[[char]], collapse = "")
    +        self$decode[[key_str]] <- char
    +      }
    +
    +      stopifnot(self$pdim^2 == length(self$polybius) &&
    +                self$pdim == length(self$alphabet))
    +
    +      self$key <- toupper(strsplit(k, "")[[1]])
    +      self$keylen <- length(self$key)
    +    },
    +
    +    # Encrypt with the ADFGVX cipher
    +    encrypt = function(s) {
    +      chars_upper <- toupper(strsplit(s, "")[[1]])
    +      chars_filtered <- chars_upper[chars_upper %in% self$polybius]
    +
    +      # Encode characters
    +      chars <- unlist(lapply(chars_filtered, function(c) self$encode[[c]]))
    +
    +      # Create column vectors
    +      colvecs <- list()
    +      for (i in 1:self$keylen) {
    +        indices <- seq(i, length(chars), by = self$keylen)
    +        colvecs[[self$key[i]]] <- chars[indices]
    +      }
    +
    +      # Sort by key
    +      sorted_names <- sort(names(colvecs))
    +      result <- unlist(lapply(sorted_names, function(name) colvecs[[name]]))
    +
    +      return(paste(result, collapse = ""))
    +    },
    +
    +    # Decrypt with the ADFGVX cipher
    +    decrypt = function(s) {
    +      chars <- toupper(strsplit(s, "")[[1]])
    +      chars <- chars[chars %in% self$alphabet]
    +
    +      sortedkey <- sort(self$key)
    +      order <- sapply(sortedkey, function(ch) which(self$key == ch)[1])
    +      originalorder <- sapply(self$key, function(ch) which(sortedkey == ch)[1])
    +
    +      # Calculate strides (column lengths)
    +      div_result <- length(chars) %/% self$keylen
    +      rem_result <- length(chars) %% self$keylen
    +      strides <- sapply(order, function(i) {
    +        div_result + ifelse(rem_result >= i, 1, 0)
    +      })
    +
    +      # Calculate starts and ends of columns
    +      starts <- c(1, cumsum(strides[-length(strides)]) + 1)
    +      ends <- starts + strides - 1
    +
    +      # Get reordered columns
    +      cols <- lapply(originalorder, function(i) {
    +        chars[starts[i]:ends[i]]
    +      })
    +
    +      # Recover the rows
    +      nrows <- (length(chars) - 1) %/% self$keylen + 1
    +      pairs <- c()
    +      for (i in 1:nrows) {
    +        for (j in 1:self$keylen) {
    +          if ((i - 1) * self$keylen + j > length(chars)) break
    +          pairs <- c(pairs, cols[[j]][i])
    +        }
    +      }
    +
    +      # Decode pairs
    +      result <- c()
    +      for (i in seq(1, length(pairs) - 1, by = 2)) {
    +        pair_str <- paste(pairs[i:(i+1)], collapse = "")
    +        result <- c(result, self$decode[[pair_str]])
    +      }
    +
    +      return(paste(result, collapse = ""))
    +    }
    +  )
    +)
    +
    +# Main execution
    +set.seed(123)  # For reproducibility
    +POLYBIUS <- paste(sample(strsplit("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "")[[1]]),
    +                  collapse = "")
    +
    +# Get dictionary words - try multiple sources
    +get_valid_key <- function() {
    +  # Try to read unixdict.txt if it exists
    +  if (file.exists("unixdict.txt")) {
    +    dict_words <- readLines("unixdict.txt")
    +  } else {
    +    # Use sample words if file doesn't exist
    +    dict_words <- c("absolutes", "abruption", "abundance", "abysmally",
    +                    "acrobatic", "algorithm", "ambiguity", "amplitude",
    +                    "ancestory", "archetype", "asynchron", "auctioned",
    +                    "backbone", "backfired", "backlights", "bandwidth",
    +                    "benchmark", "biography", "birthplace", "blasphemy",
    +                    "boulevard", "bricklaying", "broadcast", "butchering",
    +                    "cauterize", "chemicals", "chromatic", "clipboard",
    +                    "completing", "conjugate", "copyright", "daughters",
    +                    "debuggers", "delimiters", "demograph", "dialyzing",
    +                    "dictionary", "education", "equations", "factorize",
    +                    "geography", "goshdarn", "graciously", "graphed",
    +                    "hampshire", "imploding", "indexable", "jeculates",
    +                    "keyboards", "labyrinth", "livestock", "logarithm",
    +                    "machinery", "molecules", "nightmare", "obscurity",
    +                    "particles", "quizboard", "racehorst", "reduction",
    +                    "savepoint", "sectional", "shipyard", "splatting",
    +                    "substance", "technology", "ulceration", "vineyard",
    +                    "warehouse", "workplace", "xanthopsy", "yachtsmen")
    +  }
    +
    +  # Filter for 9-letter words with unique characters
    +  valid_words <- dict_words[sapply(dict_words, function(w) {
    +    n <- nchar(w)
    +    n == 9 && length(unique(strsplit(w, "")[[1]])) == n
    +  })]
    +
    +  if (length(valid_words) == 0) {
    +    stop("No valid 9-letter words with unique characters found")
    +  }
    +
    +  return(toupper(sample(valid_words, 1)))
    +}
    +
    +KEY <- get_valid_key()
    +
    +# Create cipher and encrypt/decrypt
    +SECRETS <- ADFGVX$new(POLYBIUS, KEY)
    +message <- "ATTACKAT1200AM"
    +
    +cat("Polybius:", POLYBIUS, ", Key:", KEY, "\n")
    +cat("Message:", message, "\n")
    +
    +encoded <- SECRETS$encrypt(message)
    +decoded <- SECRETS$decrypt(encoded)
    +
    +cat("Encoded:", encoded, "\n")
    +cat("Decoded:", decoded, "\n")
    diff --git a/Task/AKS-test-for-primes/Ada/aks-test-for-primes.adb b/Task/AKS-test-for-primes/Ada/aks-test-for-primes.adb
    new file mode 100644
    index 0000000000..0ea9ed95f6
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Ada/aks-test-for-primes.adb
    @@ -0,0 +1,88 @@
    +with Ada.Text_IO;
    +
    +procedure Test_For_Primes is
    +
    +   type Pascal_Triangle_Type is array (Natural range <>) of Long_Long_Integer;
    +
    +   function Calculate_Pascal_Triangle (N : in Natural) return Pascal_Triangle_Type is
    +      Pascal_Triangle : Pascal_Triangle_Type (0 .. N);
    +   begin
    +      Pascal_Triangle (0) := 1;
    +      for I in Pascal_Triangle'First .. Pascal_Triangle'Last - 1 loop
    +         Pascal_Triangle (1 + I) := 1;
    +         for J in reverse 1 .. I loop
    +            Pascal_Triangle (J) := Pascal_Triangle (J - 1) - Pascal_Triangle (J);
    +         end loop;
    +         Pascal_Triangle (0) := -Pascal_Triangle (0);
    +      end loop;
    +      return Pascal_Triangle;
    +   end Calculate_Pascal_Triangle;
    +
    +   function Is_Prime (N : Integer) return Boolean is
    +      I      : Integer;
    +      Result : Boolean := True;
    +      Pascal_Triangle : constant Pascal_Triangle_Type := Calculate_Pascal_Triangle (N);
    +   begin
    +      I := N / 2;
    +      while Result and I > 1 loop
    +         Result := Result and Pascal_Triangle (I) mod Long_Long_Integer (N) = 0;
    +         I := I - 1;
    +      end loop;
    +      return Result;
    +   end Is_Prime;
    +
    +   function Image (N    : in Long_Long_Integer;
    +                   Sign : in Boolean := False) return String is
    +      Image : constant String := N'Image;
    +   begin
    +      if N < 0 then
    +         return Image;
    +      else
    +         if Sign then
    +            return "+" & Image (Image'First + 1 .. Image'Last);
    +         else
    +            return Image (Image'First + 1 .. Image'Last);
    +         end if;
    +      end if;
    +   end Image;
    +
    +   procedure Show (Triangle : in Pascal_Triangle_Type) is
    +      use Ada.Text_IO;
    +   Begin
    +      for I in reverse Triangle'Range loop
    +         Put (Image (Triangle (I), Sign => True));
    +         Put ("x^");
    +         Put (Image (Long_Long_Integer (I)));
    +         Put (" ");
    +      end loop;
    +   end Show;
    +
    +   procedure Show_Pascal_Triangles is
    +      use Ada.Text_IO;
    +   begin
    +      for N in 0 .. 9 loop
    +         declare
    +            Pascal_Triangle : constant Pascal_Triangle_Type := Calculate_Pascal_Triangle (N);
    +         begin
    +            Put ("(x-1)^" & Image (Long_Long_Integer (N)) & " = ");
    +            Show (Pascal_Triangle);
    +            New_Line;
    +         end;
    +      end loop;
    +   end Show_Pascal_Triangles;
    +
    +   procedure Show_Primes is
    +      use Ada.Text_IO;
    +   begin
    +      for N in 2 .. 63 loop
    +         if Is_Prime (N) then
    +            Put (N'Image);
    +         end if;
    +      end loop;
    +      New_Line;
    +   end Show_Primes;
    +
    +begin
    +   Show_Pascal_Triangles;
    +   Show_Primes;
    +end Test_For_Primes;
    diff --git a/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy b/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy
    index 54fc26429d..10fa6635e4 100644
    --- a/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy
    +++ b/Task/AKS-test-for-primes/EasyLang/aks-test-for-primes.easy
    @@ -1,7 +1,7 @@
     func[] coefs n .
    -   list[] = [ 1 ]
    -   arrbase list[] 0
    -   for k = 0 to n : list[] &= list[k] * (n - k) / (k + 1)
    +   len list[] n + 2
    +   list[0] = 1
    +   for k = 0 to n : list[k + 1] = list[k] * (n - k) / (k + 1)
        for k = 1 step 2 to n : list[k] = -list[k]
        return list[]
     .
    diff --git a/Task/AKS-test-for-primes/Loglan82/aks-test-for-primes.loglan82 b/Task/AKS-test-for-primes/Loglan82/aks-test-for-primes.loglan82
    new file mode 100644
    index 0000000000..73629f52ea
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/Loglan82/aks-test-for-primes.loglan82
    @@ -0,0 +1,89 @@
    +program AKS;
    +(* AKS test for primes *)
    +
    +const
    +  Pas_tri_last = 33; (* 33 for 32-bit integer type; 17 for 16-bit integer *)
    +var
    +  n: integer;
    +
    +  (* Calculate the n'th line 0 .. middle *)
    +  unit Pascal_triangle: procedure (n: integer; Pas_tri: arrayof integer);
    +  var
    +    j, k: integer;
    +  begin
    +    Pas_tri(0) := 1;
    +    j := 1;
    +    while j <= n
    +    do
    +      j := j + 1;
    +      k := j div 2;
    +      Pas_tri(k) := Pas_tri(k - 1);
    +      while k >= 1
    +      do
    +        Pas_tri(k) := Pas_tri(k) + Pas_tri(k - 1);
    +        k := k - 1
    +      od;
    +    od;
    +  end Pascal_triangle;
    +
    +  unit is_prime: function (n: integer): boolean;
    +  var
    +    i: integer,
    +    Pas_tri: arrayof integer;
    +  begin
    +    array Pas_tri dim (0 : n);
    +    call Pascal_triangle(n, Pas_tri);
    +    result := true;
    +    i := n div 2;
    +    while result and (i > 1)
    +    do
    +      result := result and (Pas_tri(i) mod n = 0);
    +      i := i - 1;
    +    od;
    +  end is_prime;
    +
    +  unit vz: function (b: boolean): character;
    +  begin
    +    if b then result := '-' else result := '+' fi;
    +  end vz;
    +
    +  unit expand_poly: procedure (n: integer);
    +  var
    +    Pas_tri: arrayof integer,
    +    bvz: boolean,
    +    j: integer;
    +  begin
    +    array Pas_tri dim (0 : n);
    +    case n
    +      when 0: writeln("(x - 1) ^ 0 = 1")
    +      when 1: writeln("(x - 1) ^ 1 = x - 1")
    +      otherwise
    +        call Pascal_triangle(n, Pas_tri);
    +        write("(x - 1) ^ ", n: 1, " = x ^ ", n: 1, " ");
    +        bvz := true;
    +        for j := n - 1 downto (n div 2) + 1
    +        do
    +          write(vz(bvz), " ", Pas_tri(n - j): 1, " * x ^ ", j: 1, " ");
    +          bvz := not bvz;
    +        od;
    +        for j := (n div 2) downto 2
    +        do
    +          write(vz(bvz), " ", Pas_tri(j): 1, " * x ^ ", j: 1, " ");
    +          bvz := not bvz
    +        od;
    +        write(vz(bvz), " ", Pas_tri(1): 1, " * x ");
    +        bvz := not bvz;
    +        writeln(vz(bvz), " ", Pas_tri(0): 1);
    +    esac;
    +  end expand_poly;
    +
    +begin
    +  for n := 0 to 9
    +  do
    +    call expand_poly(n)
    +  od;
    +  for n := 2 to Pas_tri_last do
    +    if is_prime(n) then write(n: 1, " ") fi;
    +  od;
    +  writeln;
    +end
    diff --git a/Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.ps1 b/Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.ps1
    new file mode 100644
    index 0000000000..c79bcdf5e7
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/PowerShell/aks-test-for-primes.ps1
    @@ -0,0 +1,84 @@
    +# AKS test for primes
    +
    +$script:PasTriMax = 61 # for long type of Pascal triangle numbers
    +
    +function Pascal-Triangle {
    +  # Calculate the n'th line 0.. middle
    +  param(
    +    [int]$N
    +  )
    +
    +  $pasTri = [long[]]::new([math]::Ceiling(($N + 2) / 2))
    +  $pasTri[0] = 1
    +  [int]$j = 1
    +  while ($j -le $N) {
    +    $j++
    +    [int]$k = [math]::Floor($j / 2)
    +    $pasTri[$k] = $pasTri[$k - 1]
    +    for (; $k -ge 1; $k--) {
    +      $pasTri[$k] += $pasTri[$k - 1]
    +    }
    +  }
    +  # Now: $j -eq ($N + 1), so $k -eq [math]::Floor(($N + 1) / 2)
    +  return $pasTri
    +}
    +
    +function Expand-Poly {
    +  param ([int]$N)
    +
    +  if ($N -gt $script:PasTriMax) {
    +    throw "$N is out of range"
    +  }
    +  switch($N) {
    +    0 {Write-Output "(x-1)^0 = 1"}
    +    1 {Write-Output "(x-1)^1 = x-1"}
    +    default {
    +      $VZ = @('+', '-')
    +      $pasTri = Pascal-Triangle($N)
    +      [string]$outTri = @()
    +      $outTri += "(x-1)^$N = x^$N"
    +      [bool]$bVz = $true
    +      [int]$nDiv2 = [math]::Floor($N / 2)
    +      for ([int]$j = $N - 1; $j -gt $nDiv2; $j--) {
    +        $outTri += "$($VZ[$bVz]) $($pasTri[$N - $j])*x^$j"
    +        $bVz = -not $bVz
    +      }
    +      for ([int]$j = $nDiv2; $j -gt 1; $j--) {
    +        $outTri += "$($VZ[$bVz]) $($pasTri[$j])*x^$j"
    +        $bVz = -not $bVz
    +      }
    +      $outTri += "$($VZ[$bVz]) $($pasTri[1])*x"
    +      $bVz = -not $bVz
    +      $outTri += "$($VZ[$bVz]) $($pasTri[0])"
    +      Write-Output $outTri
    +    }
    +  }
    +}
    +
    +function Is-Prime {
    +  param([int]$N)
    +
    +  if ($N -gt $script:PasTriMax) {
    +    throw "$N is out of range"
    +  }
    +  $pasTri = Pascal-Triangle($N)
    +  [bool]$res = $true
    +  [int]$i = [math]::Floor($N / 2)
    +  while ($res -and ($i -gt 1)) {
    +    $res = $res -and ($pasTri[$i] % $N -eq 0)
    +    $i--
    +  }
    +  return $res
    +}
    +
    +# Test program
    +foreach ($n in 0..9) {
    +  Expand-Poly($n)
    +}
    +[string]$primes = @()
    +foreach ($n in 2..$script:PasTriMax) {
    +  if (Is-Prime($n)) {
    +    $primes += "{0,3}" -f $n
    +  }
    +}
    +Write-Output $primes
    diff --git a/Task/AKS-test-for-primes/QuickBASIC/aks-test-for-primes.basic b/Task/AKS-test-for-primes/QuickBASIC/aks-test-for-primes.basic
    new file mode 100644
    index 0000000000..87b3cb1b3b
    --- /dev/null
    +++ b/Task/AKS-test-for-primes/QuickBASIC/aks-test-for-primes.basic
    @@ -0,0 +1,76 @@
    +' AKS test for primes
    +DECLARE SUB PascalTriangle (N%, PasTri&())
    +DECLARE FUNCTION IsPrime% (N%)
    +DECLARE SUB ExpandPoly (N%)
    +CONST PASTRILAST% = 33 ' for 32-bit integer type
    +CONST TRUE% = -1, FALSE% = 0
    +FOR N% = 0 TO 9
    +  CALL ExpandPoly(N%)
    +NEXT N%
    +FOR N% = 2 TO PASTRILAST%
    +  IF IsPrime%(N%) THEN PRINT USING "###"; N%;
    +NEXT N%
    +PRINT
    +END
    +
    +SUB ExpandPoly (N%)
    +  DIM VZ$(0 TO 1)
    +  VZ$(0) = "+"
    +  VZ$(1) = "-"
    +  DIM PasTri&(0 TO PASTRILAST%)
    +  IF N% > PASTRILAST% THEN
    +    PRINT N%; "is out of range"
    +    STOP
    +  END IF
    +  SELECT CASE N%
    +    CASE 0
    +      PRINT "(x - 1) ^ 0 = 1"
    +    CASE 1
    +      PRINT "(x - 1) ^ 1 = x - 1"
    +    CASE ELSE
    +      CALL PascalTriangle(N%, PasTri&())
    +      PRINT "(x - 1) ^"; N%; " = x ^"; N%;
    +      BVZ% = 1
    +      FOR J% = N% - 1 TO N% \ 2 + 1 STEP -1
    +        PRINT VZ$(BVZ%); PasTri&(N% - J%); "* x ^"; J%;
    +        BVZ% = ABS(1 - BVZ%)
    +      NEXT J%
    +      FOR J% = N% \ 2 TO 2 STEP -1
    +        PRINT VZ$(BVZ%); PasTri&(J%); "* x ^"; J%;
    +        BVZ% = ABS(1 - BVZ%)
    +      NEXT J%
    +      PRINT VZ$(BVZ%); PasTri&(1); "* x ";
    +      BVZ% = ABS(1 - BVZ%)
    +      PRINT VZ$(BVZ%); PasTri&(0)
    +  END SELECT
    +END SUB
    +
    +FUNCTION IsPrime% (N%)
    +  DIM PasTri&(0 TO PASTRILAST%)
    +  IF N% > PASTRILAST% THEN
    +    PRINT N%; "is out of range"
    +    STOP
    +  END IF
    +  CALL PascalTriangle(N%, PasTri&())
    +  Res% = TRUE%
    +  I% = N% \ 2
    +  DO WHILE Res% AND (I% > 1)
    +    Res% = Res% AND (PasTri&(I%) MOD N% = 0)
    +    I% = I% - 1
    +  LOOP
    +  IsPrime% = Res%
    +END FUNCTION
    +
    +SUB PascalTriangle (N%, PasTri&())
    +  ' Calculate the N'th line 0.. middle
    +  PasTri&(0) = 1
    +  J% = 1
    +  DO WHILE J% <= N%
    +    J% = J% + 1
    +    K% = J% \ 2
    +    PasTri&(K%) = PasTri&(K% - 1)
    +    FOR K% = K% TO 1 STEP -1
    +      PasTri&(K%) = PasTri&(K%) + PasTri&(K% - 1)
    +    NEXT K%
    +  LOOP
    +END SUB
    diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx
    index c900672143..2cc1ad89b3 100644
    --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx
    +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx
    @@ -1,87 +1,63 @@
    --- 23 Aug 2025
    +-- 21 Feb 2026
     include Setting
     arg p
    -if p = '' then
    -   p = 10
    +if p='' then
    +   p=100
     
    -say 'AKS TEST FOR PRIMES'
    +say 'AKS TEST FOR PRIMES' p
     say version
     say
    -numeric digits Max(10,Abs(p)%3)
    -call Combis p
    -call Polynomials p
    -call Showprimes p
    +numeric digits Max(10,Abs(p%3))
    +say Combmemo(p) 'combinations generated'
    +say
    +say Getprimes(p) 'primes found'
    +say
    +call Showprimes
    +say
    +call Timer
     exit
     
    -Combis:
    -procedure expose comb.
    +Getprimes:
    +procedure expose Poly. Work. Prim. Memo.
     arg p
    -call Time('r')
    -if p > 0 then
    -   say 'Combinations up to' p'...'
    -else
    -   say 'Combinations for' Abs(p)'...'
    -say Combinations(p) 'combinations generated'
    -say Format(Time('e'),,3) 'seconds'
    -say
    -return
    -
    -Polynomials:
    -procedure expose poly. comb. work. prim.
    -arg p
    -call Time('r')
    -say 'Polynomials...'
    -if p < 0 then
    -   b = Abs(p)
    -else
    -   b = 0
    -p = Abs(p); prim. = 0; n = 0
    -do i = b to p
    -   a = PowP('1 -1',i)
    -   if i < 11 then
    -      say '(x-1)^'i '=' Lst2FormP(Arr2LstP())
    -   s = 1
    -   do j = 2 to poly.0-1
    -      a = poly.coef.j
    -      if a//i > 0 then do
    -         s = 0
    +q=-p*(p<0); p=Abs(p)
    +say 'Get primes...'
    +Poly.=0; Prim.=0; n=0
    +do i=q to p
    +-- Generate power of x-1, also saves coefficients
    +   a=PowP('1 -1',i)
    +   if i<11 then
    +      say '(x-1)^'i '=' Poly2form(Stem2poly())
    +-- AKS algorithm using saved coefficients
    +   s=1
    +   do j=2 to Poly.0-1
    +      a=Poly.j
    +      if a//i>0 then do
    +         s=0
              leave j
           end
        end
    -   if s = 1 then do
    -      if i > 1 then do
    -         n = n+1
    -         prim.n = i
    +-- Bump prime
    +   if s=1 then do
    +      if i>1 then do
    +         n+=1; Prim.n=i
           end
        end
     end
    -prim.0 = n
    -say Format(Time('e'),,3) 'seconds'
    -say
    -return
    +-- Prime count
    +Prim.0=n
    +return n
     
     Showprimes:
    -procedure expose prim.
    -arg p
    -call Time('r')
    +procedure expose Prim.
     say 'Primes...'
    -if p < 0 then do
    -   p = Abs(p)
    -   if prim.0 > 0 then
    -      say p 'is prime'
    -   else
    -      say p 'is not prime'
    +do i=1 to Prim.0
    +   call Charout ,Right(Prim.i,5)
    +   if i//20=0 then
    +      say
     end
    -else do
    -   do i = 1 to prim.0
    -      call Charout ,Right(prim.i,5)
    -      if i//20 = 0 then
    -         say
    -   end
    -   say
    -end
    -say Format(Time('e'),,3) 'seconds'
     say
     return
     
    +-- Combmemo; PowP; Poly2form; Stem2poly; Timer
     include Math
    diff --git a/Task/ASCII-art-diagram-converter/Crystal/ascii-art-diagram-converter-1.cr b/Task/ASCII-art-diagram-converter/Crystal/ascii-art-diagram-converter-1.cr
    new file mode 100644
    index 0000000000..8116d0c048
    --- /dev/null
    +++ b/Task/ASCII-art-diagram-converter/Crystal/ascii-art-diagram-converter-1.cr
    @@ -0,0 +1,124 @@
    +macro convert_diagram (typename, s)
    +  {% lines = s.strip.split(/\r?\n/).map(&.strip) %}
    +
    +  # check if it's actually a diagram
    +  {% for line, i in lines %}
    +    {% unless (i % 2 == 0 && line =~ /^\+(--\+)+$/) ||     # well formed border?
    +              (i % 2 != 0 && line =~ /^\|([ \w]+\|)+$/) %} # inside probably ok?
    +      {% raise "bad diagram format" %}
    +    {% end %}
    +  {% end %}
    +
    +  # count size
    +  {% row_size = lines[0].split('+').size - 2 %}
    +  {% unless [8, 16, 32, 64, 128].includes?(row_size) %}
    +    {% raise "Invalid data size : " + row_size %}
    +  {% end %}
    +
    +  # get rid of the borders now
    +  {% lines = lines.reject {|line| line.starts_with?("+--+") } %}
    +
    +  {% element_type = "UInt" + row_size.stringify %}
    +  {% suffix = "_u" + row_size.stringify %}
    +  {% array_size = lines.size %}
    +  {% field_names = [] of StringLiteral %}
    +  {% field_sizes = [] of IntLiteral %}
    +
    +  # build the type
    +  class {{typename.id}}
    +    @data = Array({{element_type.id}}).new({{array_size.id}}, 0)
    +
    +    def self.from_io (io)
    +      o = new
    +      o.@data.map! { {{element_type.id}}.from_io(io, IO::ByteFormat::NetworkEndian) }
    +      o
    +    end
    +
    +    def to_io (io)
    +      @data.each do |n| n.to_io(io, IO::ByteFormat::NetworkEndian) end
    +    end
    +
    +    {% for line, idx in lines %}
    +      {% fields = line.split('|')[1...-1] %}
    +      {% offset = row_size %}
    +      {% for field in fields %}
    +        {% field_size = (field.size+1) // 3 %}
    +        {% field_sizes << field_size %}
    +        {% field_name = field.strip.downcase %}
    +        {% field_names << field_name %}
    +        {% offset -= field_size %}
    +
    +        {% if field_size == row_size %}
    +          def {{field_name.id}}
    +            @data[{{idx.id}}]
    +          end
    +
    +          def {{field_name.id}}= (v)
    +            @data[{{idx.id}}] = v.to{{suffix.id}}
    +          end
    +        {% else %}
    +          def {{field_name.id}}
    +            @data[{{idx.id}}].bits({{offset.id}} ... {{(offset + field_size).id}})
    +          end
    +
    +          def {{field_name.id}}= (v)
    +            mask = (1{{suffix.id}} << {{field_size.id}}) - 1
    +            raise "overflow" unless 0 <= v <= mask
    +            @data[{{idx.id}}] = (@data[{{idx.id}}] & ~(mask << {{offset.id}})) | (v.to{{suffix.id}} << {{offset.id}})
    +          end
    +          {% if field_size == 1 %}
    +            def {{field_name.id}}= (v : Bool)
    +              self.{{field_name.id}} = v ? 1 : 0
    +            end
    +
    +            def {{field_name.id}}?
    +              self.{{field_name.id}} == 1
    +            end
    +          {% end %}
    +        {% end %}
    +      {% end %}
    +    {% end %}
    +    def values
    +      {
    +        {% for field_name in field_names %}
    +          {{ field_name.id }}: self.{{field_name.id}},
    +        {% end %}
    +      }
    +    end
    +    def self.field_sizes
    +      {
    +        {% for field_name, i in field_names %}
    +          {{ field_name.id }}: {{ field_sizes[i].id }},
    +        {% end %}
    +      }
    +    end
    +  end # class
    +end
    +
    +convert_diagram MessageHeader, <<-EOD
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  |                      ID                       |
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  |                    QDCOUNT                    |
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  |                    ANCOUNT                    |
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  |                    NSCOUNT                    |
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  |                    ARCOUNT                    |
    +  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +  EOD
    +
    +io = IO::Memory.new "78477bbf5496e12e1bf169a4".hexbytes
    +
    +h = MessageHeader.from_io(io)
    +
    +sizes = MessageHeader.field_sizes
    +
    +puts "   Field    Sz   Value   (binary)"
    +puts "   ------------------------------"
    +h.values.each do |name, value|
    +  puts "%8s:   %2d   %5d   %0*b" % {name, sizes[name], value, sizes[name], value}
    +end
    diff --git a/Task/ASCII-art-diagram-converter/Crystal/ascii-art-diagram-converter-2.cr b/Task/ASCII-art-diagram-converter/Crystal/ascii-art-diagram-converter-2.cr
    new file mode 100644
    index 0000000000..1b1cd2f7a1
    --- /dev/null
    +++ b/Task/ASCII-art-diagram-converter/Crystal/ascii-art-diagram-converter-2.cr
    @@ -0,0 +1,231 @@
    +   class MessageHeader
    +     @data = Array(UInt16).new(6, 0)
    +
    +     def self.from_io(io)
    +       o = new
    +       (o.@data).map! do UInt16.from_io(io, IO::ByteFormat::NetworkEndian) end
    +       o
    +     end
    +
    +     def to_io(io)
    +       @data.each do |n| n.to_io(io, IO::ByteFormat::NetworkEndian) end
    +     end
    +
    +     def id
    +       @data[0]
    +     end
    +
    +     def id=(v)
    +       @data[0] = v.to_u16
    +     end
    +
    +     def qr
    +       @data[1].bits(15...16)
    +     end
    +
    +     def qr=(v)
    +       mask = (1_u16 << 1) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 15))) | (v.to_u16 << 15)
    +     end
    +
    +     def qr=(v : Bool)
    +       self.qr = v ? 1 : 0
    +     end
    +
    +     def qr?
    +       self.qr == 1
    +     end
    +
    +     def opcode
    +       @data[1].bits(11...15)
    +     end
    +
    +     def opcode=(v)
    +       mask = (1_u16 << 4) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 11))) | (v.to_u16 << 11)
    +     end
    +
    +     def aa
    +       @data[1].bits(10...11)
    +     end
    +
    +     def aa=(v)
    +       mask = (1_u16 << 1) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 10))) | (v.to_u16 << 10)
    +     end
    +
    +     def aa=(v : Bool)
    +       self.aa = v ? 1 : 0
    +     end
    +
    +     def aa?
    +       self.aa == 1
    +     end
    +
    +     def tc
    +       @data[1].bits(9...10)
    +     end
    +
    +     def tc=(v)
    +       mask = (1_u16 << 1) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 9))) | (v.to_u16 << 9)
    +     end
    +
    +     def tc=(v : Bool)
    +       self.tc = v ? 1 : 0
    +     end
    +
    +     def tc?
    +       self.tc == 1
    +     end
    +
    +     def rd
    +       @data[1].bits(8...9)
    +     end
    +
    +     def rd=(v)
    +       mask = (1_u16 << 1) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 8))) | (v.to_u16 << 8)
    +     end
    +
    +     def rd=(v : Bool)
    +       self.rd = v ? 1 : 0
    +     end
    +
    +     def rd?
    +       self.rd == 1
    +     end
    +
    +     def ra
    +       @data[1].bits(7...8)
    +     end
    +
    +     def ra=(v)
    +       mask = (1_u16 << 1) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 7))) | (v.to_u16 << 7)
    +     end
    +
    +     def ra=(v : Bool)
    +       self.ra = v ? 1 : 0
    +     end
    +
    +     def ra?
    +       self.ra == 1
    +     end
    +
    +     def z
    +       @data[1].bits(4...7)
    +     end
    +
    +     def z=(v)
    +       mask = (1_u16 << 3) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 4))) | (v.to_u16 << 4)
    +     end
    +
    +     def rcode
    +       @data[1].bits(0...4)
    +     end
    +
    +     def rcode=(v)
    +       mask = (1_u16 << 4) - 1
    +       if 0 <= v && v <= mask
    +       else
    +         raise("overflow")
    +       end
    +       @data[1] = (@data[1] & (~(mask << 0))) | (v.to_u16 << 0)
    +     end
    +
    +     def qdcount
    +       @data[2]
    +     end
    +
    +     def qdcount=(v)
    +       @data[2] = v.to_u16
    +     end
    +
    +     def ancount
    +       @data[3]
    +     end
    +
    +     def ancount=(v)
    +       @data[3] = v.to_u16
    +     end
    +
    +     def nscount
    +       @data[4]
    +     end
    +
    +     def nscount=(v)
    +       @data[4] = v.to_u16
    +     end
    +
    +     def arcount
    +       @data[5]
    +     end
    +
    +     def arcount=(v)
    +       @data[5] = v.to_u16
    +     end
    +
    +     def values
    +       { id: self.id,
    +         qr: self.qr,
    +         opcode: self.opcode,
    +         aa: self.aa,
    +         tc: self.tc,
    +         rd: self.rd,
    +         ra: self.ra,
    +         z: self.z,
    +         rcode: self.rcode,
    +         qdcount: self.qdcount,
    +         ancount: self.ancount,
    +         nscount: self.nscount,
    +         arcount: self.arcount,
    +       }
    +     end
    +
    +     def self.field_sizes
    +       { id: 16,
    +         qr: 1,
    +         opcode: 4,
    +         aa: 1,
    +         tc: 1,
    +         rd: 1,
    +         ra: 1,
    +         z: 3,
    +         rcode: 4,
    +         qdcount: 16,
    +         ancount: 16,
    +         nscount: 16,
    +         arcount: 16,
    +       }
    +     end
    +   end
    diff --git a/Task/ASCII-art-diagram-converter/Pluto/ascii-art-diagram-converter.pluto b/Task/ASCII-art-diagram-converter/Pluto/ascii-art-diagram-converter.pluto
    new file mode 100644
    index 0000000000..d0ab1c791b
    --- /dev/null
    +++ b/Task/ASCII-art-diagram-converter/Pluto/ascii-art-diagram-converter.pluto
    @@ -0,0 +1,108 @@
    +require "bignum"
    +local fmt = require "fmt"
    +
    +class result
    +    function __construct(public name, public size, public start, public finish)
    +    end
    +end
    +
    +local function validate(diagram)
    +    local lines = {}
    +    for diagram:split("\n") as line do
    +        line = line:strip(" \t")
    +        if line != "" then lines:insert(line) end
    +    end
    +    if #lines == 0 then error("diagram has no non-empty lines!") end
    +    local width = #lines[1]
    +    local cols = (width - 1) // 3
    +    if cols != 8 and cols != 16 and cols != 32 and cols != 64 then
    +        error("number of columns should be 8, 16, 32 or 64")
    +    end
    +    if #lines % 2 == 0 then
    +        error("number of non-empty lines should be odd")
    +    end
    +    if lines[1] != string.rep("+--", cols) .. "+" then error("incorrect header line") end
    +    local i = 0
    +    for lines as line do
    +        if i == 0 then
    +            continue
    +        elseif i % 2 == 0 then
    +            if line != lines[1] then error("incorrect separator line") end
    +        elseif #line != width then
    +            error("inconsistent line widths")
    +        elseif line[1] != "|" or line[width] != "|" then
    +            error("non-separator lines must begin and end with '|'")
    +        end
    +        i += 1
    +    end
    +    return lines
    +end
    +
    +local function decode(lines)
    +    print("Name     Bits  Start  End")
    +    print("=======  ====  =====  ===")
    +    local start = 0
    +    local width = #lines[1]
    +    local results = {}
    +    local i = 0
    +    for lines as line do
    +        if i % 2 == 0 then
    +            i += 1
    +            continue
    +        end
    +        line = line:sub(2, width - 1)
    +        for line:split("|") as name do
    +            local size = (#name + 1) // 3
    +            name = name:strip()
    +            local r = new result(name, size, start, start + size - 1)
    +            results:insert(r)
    +            fmt.print("%-7s   %2d    %3d   %3d", r.name, r.size, r.start, r.finish)
    +            start += size
    +        end
    +        i += 1
    +    end
    +    return results
    +end
    +
    +local function hex2bin(hex)
    +    local z = bigint.frombase(hex, 16)
    +    return fmt.lpad(bigint.tobase(z, 2), 4 * #hex, "0")
    +end
    +
    +local function unpack(results, hex)
    +    print("\nTest string in hex:")
    +    print(hex)
    +    print("\nTest string in binary:")
    +    local bin = hex2bin(hex)
    +    print(bin)
    +    print("\nUnpacked:\n")
    +    print("Name     Size  Bit pattern")
    +    print("=======  ====  ================")
    +    for results as res do
    +        fmt.print("%-7s   %2d   %s", res.name, res.size, bin:sub(res.start + 1, res.finish + 1))
    +    end
    +end
    +
    +local diagram = [[
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +     |                      ID                       |
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +    |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +    |                    QDCOUNT                    |
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +
    +    |                    ANCOUNT                    |
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +    |                    NSCOUNT                    |
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +    |                    ARCOUNT                    |
    +    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    +]]
    +local lines = validate(diagram)
    +print("Diagram after trimming whitespace and removal of blank lines:\n")
    +for lines as line do print(line) end
    +print("\nDecoded:\n")
    +local results = decode(lines)
    +local hex = "78477bbf5496e12e1bf169a4"  -- test string
    +unpack(results, hex)
    diff --git a/Task/AVL-tree/Ada/avl-tree.adb b/Task/AVL-tree/Ada/avl-tree.adb
    new file mode 100644
    index 0000000000..23f26aef02
    --- /dev/null
    +++ b/Task/AVL-tree/Ada/avl-tree.adb
    @@ -0,0 +1,241 @@
    +with Ada.Text_IO, Ada.Finalization, Ada.Unchecked_Deallocation;
    +
    +procedure Main is
    +
    +   generic
    +      type Key_Type is private;
    +      with function "<"(a, b : Key_Type) return Boolean is <>;
    +      with function "="(a, b : Key_Type) return Boolean is <>;
    +      with function "<="(a, b : Key_Type) return Boolean is <>;
    +   package AVL_Tree is
    +      type Tree is tagged limited private;
    +      function insert(self : in out Tree; key : Key_Type) return Boolean;
    +      procedure delete(self : in out Tree; key : Key_Type);
    +      procedure print_balance(self : in out Tree);
    +
    +   private
    +      type Height_Amt is range -1 .. Integer'Last;
    +
    +      -- Since only one key is inserted before each rebalance, the balance of
    +      -- all trees/subtrees will stay in range -2 .. 2
    +      type Balance_Amt is range -2 .. 2;
    +
    +      type Node;
    +      type Node_Ptr is access Node;
    +      type Node is new Ada.Finalization.Limited_Controlled with record
    +         left, right, parent : Node_Ptr := null;
    +         key : Key_Type;
    +         balance : Balance_Amt := 0;
    +      end record;
    +      overriding procedure Finalize(self : in out Node);
    +      subtype Node_Parent is Ada.Finalization.Limited_Controlled;
    +
    +      type Tree is new Ada.Finalization.Limited_Controlled with record
    +         root : Node_Ptr := null;
    +      end record;
    +      overriding procedure Finalize(self : in out Tree);
    +
    +   end AVL_Tree;
    +
    +   package body AVL_Tree is
    +
    +      procedure Free_Node is new Ada.Unchecked_Deallocation(Node, Node_Ptr);
    +
    +      overriding procedure Finalize(self : in out Node) is
    +      begin
    +         Free_Node(self.left);
    +         Free_Node(self.right);
    +      end Finalize;
    +
    +      overriding procedure Finalize(self : in out Tree) is
    +      begin
    +         Free_Node(self.root);
    +      end Finalize;
    +
    +
    +      function height(n : Node_Ptr) return Height_Amt is
    +      begin
    +         if n = null then
    +            return -1;
    +         else
    +            return 1 + Height_Amt'Max(height(n.left), height(n.right));
    +         end if;
    +      end height;
    +
    +      procedure set_balance(n : not null Node_Ptr) is
    +      begin
    +         n.balance := Balance_Amt(height(n.right) - height(n.left));
    +      end set_balance;
    +
    +      procedure update_parent(parent : Node_Ptr; new_child : Node_Ptr; old_child : Node_Ptr) is
    +      begin
    +         if parent /= null then
    +            if parent.right = old_child then
    +               parent.right := new_child;
    +            else
    +               parent.left := new_child;
    +            end if;
    +         end if;
    +      end update_parent;
    +
    +      function rotate_left(a : not null Node_Ptr) return Node_Ptr is
    +         b : Node_Ptr := a.right;
    +      begin
    +         b.parent := a.parent;
    +         a.right := b.left;
    +         if a.right /= null then
    +            a.right.parent := a;
    +         end if;
    +         b.left := a;
    +         a.parent := b;
    +         update_parent(parent => b.parent, new_child => b, old_child => a);
    +
    +         set_balance(a);
    +         set_balance(b);
    +         return b;
    +      end rotate_left;
    +
    +      function rotate_right(a : not null Node_Ptr) return Node_Ptr is
    +         b : Node_Ptr := a.left;
    +      begin
    +         b.parent := a.parent;
    +         a.left := b.right;
    +         if a.left /= null then
    +            a.left.parent := a;
    +         end if;
    +         b.right := a;
    +         a.parent := b;
    +         update_parent(parent => b.parent, new_child => b, old_child => a);
    +
    +         set_balance(a);
    +         set_balance(b);
    +         return b;
    +      end rotate_right;
    +
    +      function rotate_left_right(n : not null Node_Ptr) return Node_Ptr is
    +      begin
    +         n.left := rotate_left(n.left);
    +         return rotate_right(n);
    +      end rotate_left_right;
    +
    +      function rotate_right_left(n : not null Node_Ptr) return Node_Ptr is
    +      begin
    +         n.right := rotate_right(n.right);
    +         return rotate_left(n);
    +      end rotate_right_left;
    +
    +      procedure rebalance(self : in out Tree; n : not null Node_Ptr) is
    +         new_n : Node_Ptr := n;
    +      begin
    +         set_balance(new_n);
    +         if new_n.balance = -2 then
    +            if height(new_n.left.left) >= height(new_n.left.right) then
    +               new_n := rotate_right(new_n);
    +            else
    +               new_n := rotate_left_right(new_n);
    +            end if;
    +         elsif new_n.balance = 2 then
    +            if height(new_n.right.right) >= height(new_n.right.left) then
    +               new_n := rotate_left(new_n);
    +            else
    +               new_n := rotate_right_left(new_n);
    +            end if;
    +         end if;
    +
    +         if new_n.parent /= null then
    +            rebalance(self, new_n.parent);
    +         else
    +            self.root := new_n;
    +         end if;
    +      end rebalance;
    +
    +      function new_node(key : Key_Type) return Node_Ptr is
    +        (new Node'(Node_Parent with key => key, others => <>));
    +
    +      function insert(self : in out Tree; key : Key_Type) return Boolean is
    +         curr, parent : Node_Ptr;
    +         go_left : Boolean;
    +      begin
    +         if self.root = null then
    +            self.root := new_node(key);
    +            return True;
    +         end if;
    +
    +         curr := self.root;
    +         while curr.key /= key loop
    +            parent := curr;
    +            go_left := key < curr.key;
    +            curr := (if go_left then curr.left else curr.right);
    +            if curr = null then
    +               if go_left then
    +                  parent.left := new_node(key);
    +                  parent.left.parent := parent;
    +               else
    +                  parent.right := new_node(key);
    +                  parent.right.parent := parent;
    +               end if;
    +               rebalance(self, parent);
    +               return True;
    +            end if;
    +         end loop;
    +         return False;
    +      end insert;
    +
    +      procedure delete(self : in out Tree; key : Key_Type) is
    +         successor, parent, child : Node_Ptr := self.root;
    +         to_delete : Node_Ptr := null;
    +      begin
    +         if self.root = null then
    +            return;
    +         end if;
    +
    +         while child /= null loop
    +            parent := successor;
    +            successor := child;
    +            child := (if successor.key <= key then successor.right else successor.left);
    +            if successor.key = key then
    +               to_delete := successor;
    +            end if;
    +         end loop;
    +
    +         if to_delete = null then
    +            return;
    +         end if;
    +         to_delete.key := successor.key;
    +         child := (if successor.left = null then successor.right else successor.left);
    +         if self.root.key = key then
    +            self.root := child;
    +         else
    +            update_parent(parent => parent, new_child => child, old_child => successor);
    +            rebalance(self, parent);
    +         end if;
    +         Free_Node(successor);
    +      end delete;
    +
    +      procedure print_balance(n : Node_Ptr) is
    +      begin
    +         if n /= null then
    +            print_balance(n.left);
    +            Ada.Text_IO.Put(n.balance'Image);
    +            print_balance(n.right);
    +         end if;
    +      end print_balance;
    +
    +      procedure print_balance(self : in out Tree) is
    +      begin
    +         print_balance(self.root);
    +      end print_balance;
    +   end AVL_Tree;
    +
    +   package Int_AVL_Tree is new AVL_Tree(Integer);
    +
    +   tree : Int_AVL_Tree.Tree;
    +   success : Boolean;
    +begin
    +   for i in 1 .. 10 loop
    +      success := tree.insert(i);
    +   end loop;
    +   Ada.Text_IO.Put("Printing balance: ");
    +   tree.print_balance;
    +   Ada.Text_IO.New_Line;
    +end Main;
    diff --git a/Task/AVL-tree/COBOL/avl-tree.cob b/Task/AVL-tree/COBOL/avl-tree.cob
    new file mode 100644
    index 0000000000..48796414fd
    --- /dev/null
    +++ b/Task/AVL-tree/COBOL/avl-tree.cob
    @@ -0,0 +1,515 @@
    + IDENTIFICATION DIVISION.
    + PROGRAM-ID. AVL-TREE.
    +
    + DATA DIVISION.
    + WORKING-STORAGE SECTION.
    +
    +*>--------------------------------------------------------
    +*> Node pool - array-based tree storage (0 = null)
    +*>--------------------------------------------------------
    + 01  WS-NODE-COUNT            PIC 9(4) VALUE 0.
    + 01  WS-ROOT                  PIC 9(4) VALUE 0.
    +
    + 01  WS-NODE-TABLE.
    +     05  WS-NODES OCCURS 1000 TIMES.
    +         10  WS-N-KEY         PIC S9(8) VALUE 0.
    +         10  WS-N-BAL         PIC S9(4) VALUE 0.
    +         10  WS-N-HGT         PIC S9(4) VALUE 0.
    +         10  WS-N-LEFT        PIC 9(4)  VALUE 0.
    +         10  WS-N-RIGHT       PIC 9(4)  VALUE 0.
    +         10  WS-N-PARENT      PIC 9(4)  VALUE 0.
    +
    +*>--------------------------------------------------------
    +*> Subroutine parameters and return values
    +*>--------------------------------------------------------
    + 01  WS-INSERT-KEY            PIC S9(8).
    + 01  WS-INSERT-OK             PIC 9 VALUE 0.
    +     88  INSERT-SUCCESS       VALUE 1.
    +     88  INSERT-FAILURE       VALUE 0.
    +
    + 01  WS-DELETE-KEY            PIC S9(8).
    +
    + 01  WS-NEW-IDX               PIC 9(4).
    + 01  WS-ALLOC-KEY             PIC S9(8).
    + 01  WS-ALLOC-PARENT          PIC 9(4).
    +
    + 01  WS-ROT-A                 PIC 9(4).
    + 01  WS-ROT-B                 PIC 9(4).
    + 01  WS-ROT-RESULT            PIC 9(4).
    +
    + 01  WS-HGT-IDX              PIC 9(4).
    + 01  WS-HGT-RESULT           PIC S9(4).
    +
    + 01  WS-SETBAL-IDX           PIC 9(4).
    +
    + 01  WS-RB-IDX                PIC 9(4).
    +
    +*>--------------------------------------------------------
    +*> Internal working variables
    +*>--------------------------------------------------------
    + 01  WS-CURR-IDX              PIC 9(4).
    + 01  WS-PARENT-IDX            PIC 9(4).
    + 01  WS-GO-LEFT               PIC 9 VALUE 0.
    +     88  GOING-LEFT           VALUE 1.
    +     88  GOING-RIGHT          VALUE 0.
    +
    + 01  WS-TEMP-IDX              PIC 9(4).
    + 01  WS-HEIGHT-LL             PIC S9(4).
    + 01  WS-HEIGHT-LR             PIC S9(4).
    + 01  WS-HEIGHT-RL             PIC S9(4).
    + 01  WS-HEIGHT-RR             PIC S9(4).
    + 01  WS-HGT-LEFT             PIC S9(4).
    + 01  WS-HGT-RIGHT            PIC S9(4).
    + 01  WS-MAX-HGT              PIC S9(4).
    +
    + 01  WS-DEL-NODE              PIC 9(4).
    + 01  WS-DEL-CHILD             PIC 9(4).
    + 01  WS-DEL-PARENT            PIC 9(4).
    + 01  WS-SEARCH-IDX            PIC 9(4).
    +
    +*>--------------------------------------------------------
    +*> Print balance - iterative in-order traversal stack
    +*>--------------------------------------------------------
    + 01  WS-PB-CURR              PIC 9(4).
    + 01  WS-PB-TOP               PIC 9(4) VALUE 0.
    + 01  WS-PB-STACK.
    +     05  WS-PB-ITEMS OCCURS 1000 TIMES
    +                             PIC 9(4).
    + 01  WS-DISPLAY-BAL          PIC -9.
    +
    +*>--------------------------------------------------------
    +*> Loop counter
    +*>--------------------------------------------------------
    + 01  WS-I                    PIC S9(8).
    +
    + PROCEDURE DIVISION.
    +
    +*>========================================================
    + MAIN-PROGRAM.
    +*>========================================================
    +     DISPLAY "Inserting values 1 to 10"
    +     PERFORM VARYING WS-I FROM 1 BY 1
    +         UNTIL WS-I > 9
    +         MOVE WS-I TO WS-INSERT-KEY
    +         PERFORM INSERT-NODE
    +     END-PERFORM
    +
    +     DISPLAY "Printing balance: " WITH NO ADVANCING
    +     PERFORM PRINT-BALANCE
    +     DISPLAY " "
    +
    +     STOP RUN
    +     .
    +
    +*>========================================================
    +*> ALLOCATE-NODE
    +*> Input:  WS-ALLOC-KEY, WS-ALLOC-PARENT
    +*> Output: WS-NEW-IDX
    +*>========================================================
    + ALLOCATE-NODE.
    +     ADD 1 TO WS-NODE-COUNT
    +     MOVE WS-NODE-COUNT TO WS-NEW-IDX
    +     MOVE WS-ALLOC-KEY    TO WS-N-KEY(WS-NEW-IDX)
    +     MOVE 0               TO WS-N-BAL(WS-NEW-IDX)
    +     MOVE 0               TO WS-N-HGT(WS-NEW-IDX)
    +     MOVE 0               TO WS-N-LEFT(WS-NEW-IDX)
    +     MOVE 0               TO WS-N-RIGHT(WS-NEW-IDX)
    +     MOVE WS-ALLOC-PARENT TO WS-N-PARENT(WS-NEW-IDX)
    +     .
    +
    +*>========================================================
    +*> INSERT-NODE
    +*> Input:  WS-INSERT-KEY
    +*> Output: WS-INSERT-OK (1=success, 0=duplicate)
    +*>========================================================
    + INSERT-NODE.
    +     SET INSERT-FAILURE TO TRUE
    +
    +     IF WS-ROOT = 0
    +         MOVE WS-INSERT-KEY TO WS-ALLOC-KEY
    +         MOVE 0 TO WS-ALLOC-PARENT
    +         PERFORM ALLOCATE-NODE
    +         MOVE WS-NEW-IDX TO WS-ROOT
    +         SET INSERT-SUCCESS TO TRUE
    +     ELSE
    +         MOVE WS-ROOT TO WS-CURR-IDX
    +         PERFORM INSERT-SEARCH
    +             UNTIL WS-CURR-IDX = 0
    +             OR INSERT-SUCCESS
    +     END-IF
    +     .
    +
    + INSERT-SEARCH.
    +     IF WS-N-KEY(WS-CURR-IDX) = WS-INSERT-KEY
    +         SET INSERT-FAILURE TO TRUE
    +         MOVE 0 TO WS-CURR-IDX
    +     ELSE
    +         MOVE WS-CURR-IDX TO WS-PARENT-IDX
    +         IF WS-N-KEY(WS-CURR-IDX) > WS-INSERT-KEY
    +             SET GOING-LEFT TO TRUE
    +             MOVE WS-N-LEFT(WS-CURR-IDX)
    +                 TO WS-CURR-IDX
    +         ELSE
    +             SET GOING-RIGHT TO TRUE
    +             MOVE WS-N-RIGHT(WS-CURR-IDX)
    +                 TO WS-CURR-IDX
    +         END-IF
    +
    +         IF WS-CURR-IDX = 0
    +             MOVE WS-INSERT-KEY TO WS-ALLOC-KEY
    +             MOVE WS-PARENT-IDX TO WS-ALLOC-PARENT
    +             PERFORM ALLOCATE-NODE
    +             IF GOING-LEFT
    +                 MOVE WS-NEW-IDX
    +                     TO WS-N-LEFT(WS-PARENT-IDX)
    +             ELSE
    +                 MOVE WS-NEW-IDX
    +                     TO WS-N-RIGHT(WS-PARENT-IDX)
    +             END-IF
    +             MOVE WS-PARENT-IDX TO WS-RB-IDX
    +             PERFORM REBALANCE
    +             SET INSERT-SUCCESS TO TRUE
    +         END-IF
    +     END-IF
    +     .
    +
    +*>========================================================
    +*> DELETE-BY-KEY
    +*> Input: WS-DELETE-KEY
    +*>========================================================
    + DELETE-BY-KEY.
    +     IF WS-ROOT NOT = 0
    +         MOVE WS-ROOT TO WS-SEARCH-IDX
    +         PERFORM DELETE-KEY-SEARCH
    +             UNTIL WS-SEARCH-IDX = 0
    +     END-IF
    +     .
    +
    + DELETE-KEY-SEARCH.
    +     MOVE WS-SEARCH-IDX TO WS-DEL-NODE
    +     IF WS-DELETE-KEY >= WS-N-KEY(WS-DEL-NODE)
    +         MOVE WS-N-RIGHT(WS-DEL-NODE)
    +             TO WS-SEARCH-IDX
    +     ELSE
    +         MOVE WS-N-LEFT(WS-DEL-NODE)
    +             TO WS-SEARCH-IDX
    +     END-IF
    +
    +     IF WS-DELETE-KEY = WS-N-KEY(WS-DEL-NODE)
    +         PERFORM DELETE-NODE
    +         MOVE 0 TO WS-SEARCH-IDX
    +     END-IF
    +     .
    +
    +*>========================================================
    +*> DELETE-NODE (iterative replacement of Java recursion)
    +*> Input: WS-DEL-NODE
    +*>========================================================
    + DELETE-NODE.
    +*>    Swap key with predecessor/successor until leaf
    +     PERFORM UNTIL WS-N-LEFT(WS-DEL-NODE) = 0
    +         AND WS-N-RIGHT(WS-DEL-NODE) = 0
    +
    +         IF WS-N-LEFT(WS-DEL-NODE) NOT = 0
    +             MOVE WS-N-LEFT(WS-DEL-NODE)
    +                 TO WS-DEL-CHILD
    +             PERFORM UNTIL
    +                 WS-N-RIGHT(WS-DEL-CHILD) = 0
    +                 MOVE WS-N-RIGHT(WS-DEL-CHILD)
    +                     TO WS-DEL-CHILD
    +             END-PERFORM
    +         ELSE
    +             MOVE WS-N-RIGHT(WS-DEL-NODE)
    +                 TO WS-DEL-CHILD
    +             PERFORM UNTIL
    +                 WS-N-LEFT(WS-DEL-CHILD) = 0
    +                 MOVE WS-N-LEFT(WS-DEL-CHILD)
    +                     TO WS-DEL-CHILD
    +             END-PERFORM
    +         END-IF
    +
    +         MOVE WS-N-KEY(WS-DEL-CHILD)
    +             TO WS-N-KEY(WS-DEL-NODE)
    +         MOVE WS-DEL-CHILD TO WS-DEL-NODE
    +
    +     END-PERFORM
    +
    +*>    Now WS-DEL-NODE is a leaf - remove it
    +     IF WS-N-PARENT(WS-DEL-NODE) = 0
    +         MOVE 0 TO WS-ROOT
    +     ELSE
    +         MOVE WS-N-PARENT(WS-DEL-NODE)
    +             TO WS-DEL-PARENT
    +         IF WS-N-LEFT(WS-DEL-PARENT) = WS-DEL-NODE
    +             MOVE 0 TO WS-N-LEFT(WS-DEL-PARENT)
    +         ELSE
    +             MOVE 0 TO WS-N-RIGHT(WS-DEL-PARENT)
    +         END-IF
    +         MOVE WS-DEL-PARENT TO WS-RB-IDX
    +         PERFORM REBALANCE
    +     END-IF
    +     .
    +
    +*>========================================================
    +*> REBALANCE (iterative - walks up to root)
    +*> Input: WS-RB-IDX
    +*>========================================================
    + REBALANCE.
    +     PERFORM REBALANCE-STEP
    +         UNTIL WS-RB-IDX = 0
    +     .
    +
    + REBALANCE-STEP.
    +     MOVE WS-RB-IDX TO WS-SETBAL-IDX
    +     PERFORM SET-BALANCE
    +
    +     EVALUATE TRUE
    +
    +         WHEN WS-N-BAL(WS-RB-IDX) = -2
    +             MOVE WS-N-LEFT(WS-RB-IDX)
    +                 TO WS-TEMP-IDX
    +             MOVE WS-N-LEFT(WS-TEMP-IDX)
    +                 TO WS-HGT-IDX
    +             PERFORM GET-HEIGHT
    +             MOVE WS-HGT-RESULT TO WS-HEIGHT-LL
    +             MOVE WS-N-RIGHT(WS-TEMP-IDX)
    +                 TO WS-HGT-IDX
    +             PERFORM GET-HEIGHT
    +             MOVE WS-HGT-RESULT TO WS-HEIGHT-LR
    +             IF WS-HEIGHT-LL >= WS-HEIGHT-LR
    +*>                rotateRight(n)
    +                 MOVE WS-RB-IDX TO WS-ROT-A
    +                 PERFORM ROTATE-RIGHT
    +                 MOVE WS-ROT-RESULT TO WS-RB-IDX
    +             ELSE
    +*>                rotateLeftThenRight(n)
    +                 MOVE WS-N-LEFT(WS-RB-IDX)
    +                     TO WS-ROT-A
    +                 PERFORM ROTATE-LEFT
    +                 MOVE WS-ROT-RESULT
    +                     TO WS-N-LEFT(WS-RB-IDX)
    +                 MOVE WS-RB-IDX TO WS-ROT-A
    +                 PERFORM ROTATE-RIGHT
    +                 MOVE WS-ROT-RESULT TO WS-RB-IDX
    +             END-IF
    +
    +         WHEN WS-N-BAL(WS-RB-IDX) = 2
    +             MOVE WS-N-RIGHT(WS-RB-IDX)
    +                 TO WS-TEMP-IDX
    +             MOVE WS-N-RIGHT(WS-TEMP-IDX)
    +                 TO WS-HGT-IDX
    +             PERFORM GET-HEIGHT
    +             MOVE WS-HGT-RESULT TO WS-HEIGHT-RR
    +             MOVE WS-N-LEFT(WS-TEMP-IDX)
    +                 TO WS-HGT-IDX
    +             PERFORM GET-HEIGHT
    +             MOVE WS-HGT-RESULT TO WS-HEIGHT-RL
    +             IF WS-HEIGHT-RR >= WS-HEIGHT-RL
    +*>                rotateLeft(n)
    +                 MOVE WS-RB-IDX TO WS-ROT-A
    +                 PERFORM ROTATE-LEFT
    +                 MOVE WS-ROT-RESULT TO WS-RB-IDX
    +             ELSE
    +*>                rotateRightThenLeft(n)
    +                 MOVE WS-N-RIGHT(WS-RB-IDX)
    +                     TO WS-ROT-A
    +                 PERFORM ROTATE-RIGHT
    +                 MOVE WS-ROT-RESULT
    +                     TO WS-N-RIGHT(WS-RB-IDX)
    +                 MOVE WS-RB-IDX TO WS-ROT-A
    +                 PERFORM ROTATE-LEFT
    +                 MOVE WS-ROT-RESULT TO WS-RB-IDX
    +             END-IF
    +
    +         WHEN OTHER
    +             CONTINUE
    +
    +     END-EVALUATE
    +
    +     IF WS-N-PARENT(WS-RB-IDX) NOT = 0
    +         MOVE WS-N-PARENT(WS-RB-IDX) TO WS-RB-IDX
    +     ELSE
    +         MOVE WS-RB-IDX TO WS-ROOT
    +         MOVE 0 TO WS-RB-IDX
    +     END-IF
    +     .
    +
    +*>========================================================
    +*> ROTATE-LEFT
    +*> Input:  WS-ROT-A
    +*> Output: WS-ROT-RESULT
    +*>========================================================
    + ROTATE-LEFT.
    +*>    Node b = a.right
    +     MOVE WS-N-RIGHT(WS-ROT-A) TO WS-ROT-B
    +*>    b.parent = a.parent
    +     MOVE WS-N-PARENT(WS-ROT-A)
    +         TO WS-N-PARENT(WS-ROT-B)
    +*>    a.right = b.left
    +     MOVE WS-N-LEFT(WS-ROT-B)
    +         TO WS-N-RIGHT(WS-ROT-A)
    +*>    if (a.right != null) a.right.parent = a
    +     IF WS-N-RIGHT(WS-ROT-A) NOT = 0
    +         MOVE WS-N-RIGHT(WS-ROT-A) TO WS-TEMP-IDX
    +         MOVE WS-ROT-A
    +             TO WS-N-PARENT(WS-TEMP-IDX)
    +     END-IF
    +*>    b.left = a
    +     MOVE WS-ROT-A TO WS-N-LEFT(WS-ROT-B)
    +*>    a.parent = b
    +     MOVE WS-ROT-B TO WS-N-PARENT(WS-ROT-A)
    +*>    if (b.parent != null) { fix parent's child ptr }
    +     IF WS-N-PARENT(WS-ROT-B) NOT = 0
    +         MOVE WS-N-PARENT(WS-ROT-B) TO WS-TEMP-IDX
    +         IF WS-N-RIGHT(WS-TEMP-IDX) = WS-ROT-A
    +             MOVE WS-ROT-B
    +                 TO WS-N-RIGHT(WS-TEMP-IDX)
    +         ELSE
    +             MOVE WS-ROT-B
    +                 TO WS-N-LEFT(WS-TEMP-IDX)
    +         END-IF
    +     END-IF
    +*>    setBalance(a, b)
    +     MOVE WS-ROT-A TO WS-SETBAL-IDX
    +     PERFORM SET-BALANCE
    +     MOVE WS-ROT-B TO WS-SETBAL-IDX
    +     PERFORM SET-BALANCE
    +*>    return b
    +     MOVE WS-ROT-B TO WS-ROT-RESULT
    +     .
    +
    +*>========================================================
    +*> ROTATE-RIGHT
    +*> Input:  WS-ROT-A
    +*> Output: WS-ROT-RESULT
    +*>========================================================
    + ROTATE-RIGHT.
    +*>    Node b = a.left
    +     MOVE WS-N-LEFT(WS-ROT-A) TO WS-ROT-B
    +*>    b.parent = a.parent
    +     MOVE WS-N-PARENT(WS-ROT-A)
    +         TO WS-N-PARENT(WS-ROT-B)
    +*>    a.left = b.right
    +     MOVE WS-N-RIGHT(WS-ROT-B)
    +         TO WS-N-LEFT(WS-ROT-A)
    +*>    if (a.left != null) a.left.parent = a
    +     IF WS-N-LEFT(WS-ROT-A) NOT = 0
    +         MOVE WS-N-LEFT(WS-ROT-A) TO WS-TEMP-IDX
    +         MOVE WS-ROT-A
    +             TO WS-N-PARENT(WS-TEMP-IDX)
    +     END-IF
    +*>    b.right = a
    +     MOVE WS-ROT-A TO WS-N-RIGHT(WS-ROT-B)
    +*>    a.parent = b
    +     MOVE WS-ROT-B TO WS-N-PARENT(WS-ROT-A)
    +*>    if (b.parent != null) { fix parent's child ptr }
    +     IF WS-N-PARENT(WS-ROT-B) NOT = 0
    +         MOVE WS-N-PARENT(WS-ROT-B) TO WS-TEMP-IDX
    +         IF WS-N-RIGHT(WS-TEMP-IDX) = WS-ROT-A
    +             MOVE WS-ROT-B
    +                 TO WS-N-RIGHT(WS-TEMP-IDX)
    +         ELSE
    +             MOVE WS-ROT-B
    +                 TO WS-N-LEFT(WS-TEMP-IDX)
    +         END-IF
    +     END-IF
    +*>    setBalance(a, b)
    +     MOVE WS-ROT-A TO WS-SETBAL-IDX
    +     PERFORM SET-BALANCE
    +     MOVE WS-ROT-B TO WS-SETBAL-IDX
    +     PERFORM SET-BALANCE
    +*>    return b
    +     MOVE WS-ROT-B TO WS-ROT-RESULT
    +     .
    +
    +*>========================================================
    +*> GET-HEIGHT
    +*> Input:  WS-HGT-IDX (0 = null node)
    +*> Output: WS-HGT-RESULT
    +*>========================================================
    + GET-HEIGHT.
    +     IF WS-HGT-IDX = 0
    +         MOVE -1 TO WS-HGT-RESULT
    +     ELSE
    +         MOVE WS-N-HGT(WS-HGT-IDX)
    +             TO WS-HGT-RESULT
    +     END-IF
    +     .
    +
    +*>========================================================
    +*> SET-BALANCE
    +*> Input: WS-SETBAL-IDX
    +*>========================================================
    + SET-BALANCE.
    +     PERFORM REHEIGHT
    +
    +     MOVE WS-N-RIGHT(WS-SETBAL-IDX) TO WS-HGT-IDX
    +     PERFORM GET-HEIGHT
    +     MOVE WS-HGT-RESULT TO WS-HGT-RIGHT
    +
    +     MOVE WS-N-LEFT(WS-SETBAL-IDX) TO WS-HGT-IDX
    +     PERFORM GET-HEIGHT
    +     MOVE WS-HGT-RESULT TO WS-HGT-LEFT
    +
    +     SUBTRACT WS-HGT-LEFT FROM WS-HGT-RIGHT
    +         GIVING WS-N-BAL(WS-SETBAL-IDX)
    +     .
    +
    +*>========================================================
    +*> REHEIGHT
    +*> Input: WS-SETBAL-IDX
    +*>========================================================
    + REHEIGHT.
    +     IF WS-SETBAL-IDX NOT = 0
    +         MOVE WS-N-LEFT(WS-SETBAL-IDX) TO WS-HGT-IDX
    +         PERFORM GET-HEIGHT
    +         MOVE WS-HGT-RESULT TO WS-HGT-LEFT
    +
    +         MOVE WS-N-RIGHT(WS-SETBAL-IDX) TO WS-HGT-IDX
    +         PERFORM GET-HEIGHT
    +         MOVE WS-HGT-RESULT TO WS-HGT-RIGHT
    +
    +         IF WS-HGT-LEFT > WS-HGT-RIGHT
    +             MOVE WS-HGT-LEFT TO WS-MAX-HGT
    +         ELSE
    +             MOVE WS-HGT-RIGHT TO WS-MAX-HGT
    +         END-IF
    +
    +         ADD 1 TO WS-MAX-HGT
    +         MOVE WS-MAX-HGT
    +             TO WS-N-HGT(WS-SETBAL-IDX)
    +     END-IF
    +     .
    +
    +*>========================================================
    +*> PRINT-BALANCE (iterative in-order traversal)
    +*>========================================================
    + PRINT-BALANCE.
    +     MOVE 0 TO WS-PB-TOP
    +     MOVE WS-ROOT TO WS-PB-CURR
    +
    +     PERFORM UNTIL WS-PB-CURR = 0
    +         AND WS-PB-TOP = 0
    +
    +         PERFORM UNTIL WS-PB-CURR = 0
    +             ADD 1 TO WS-PB-TOP
    +             MOVE WS-PB-CURR
    +                 TO WS-PB-ITEMS(WS-PB-TOP)
    +             MOVE WS-N-LEFT(WS-PB-CURR)
    +                 TO WS-PB-CURR
    +         END-PERFORM
    +
    +         IF WS-PB-TOP > 0
    +             MOVE WS-PB-ITEMS(WS-PB-TOP)
    +                 TO WS-PB-CURR
    +             SUBTRACT 1 FROM WS-PB-TOP
    +             MOVE WS-N-BAL(WS-PB-CURR)
    +                 TO WS-DISPLAY-BAL
    +             DISPLAY WS-DISPLAY-BAL " "
    +                 WITH NO ADVANCING
    +             MOVE WS-N-RIGHT(WS-PB-CURR)
    +                 TO WS-PB-CURR
    +         END-IF
    +
    +     END-PERFORM
    +     .
    diff --git a/Task/AVL-tree/Emacs-Lisp/avl-tree.el b/Task/AVL-tree/Emacs-Lisp/avl-tree.el
    new file mode 100644
    index 0000000000..f639c21adc
    --- /dev/null
    +++ b/Task/AVL-tree/Emacs-Lisp/avl-tree.el
    @@ -0,0 +1,212 @@
    +(defvar avl-all-nodes (make-vector 100 nil))
    +(defvar avl-root-node nil "root node")
    +
    +(defun avl-create-node (key parent)
    +  (copy-tree `((:key . ,key) (:balance . nil) (:height . nil)
    +	       (:left . nil) (:right . nil) (:parent . ,parent))))
    +
    +(defun avl-node (pos)
    +  (if (or (null pos) (> pos (1- (length avl-all-nodes))))
    +      nil
    +    (aref avl-all-nodes pos)))
    +
    +(defun avl-node-prop (noderef &rest props)
    +  (if (null noderef)
    +      nil
    +    (progn
    +      ;;(when (integerp noderef) (setq node (avl-node node)))
    +      (let ((val noderef))
    +        (dolist (prop props)
    +          (if (null (avl-node val))
    +	      (setq val nil)
    +	    (progn
    +	      (setq val (alist-get prop (avl-node val))))))
    +        val)
    +      )
    +    )
    +  )
    +
    +
    +(defun avl-set-prop (node &rest props-and-value)
    +  (when (integerp node) (setq node (avl-node node)))
    +  (when (< (length props-and-value) 2)
    +    (error "Both property name and value must be given."))
    +  (let (noderef (props (seq-take props-and-value (1- (length props-and-value))))
    +                (value (seq-elt props-and-value (1- (length props-and-value)))))
    +    (when (> (length props) 0)
    +      (dolist (prop (seq-take props (1- (length props))))
    +	(if (null node)
    +	    (progn (setq noderef nil) (setq node nil))
    +	  (progn
    +	    (setq noderef (alist-get prop node))
    +	    (setq node (avl-node noderef))))))
    +
    +    (if (or (null (last props)) (null node))
    +	nil
    +      (setcdr (assoc (car (last props)) node) value))))
    +
    +
    +(defun avl-height (noderef)
    +  (or (avl-node-prop noderef :height) -1))
    +
    +(defun avl-reheight (noderef)
    +  (if (null noderef)
    +      nil
    +    (avl-set-prop noderef :height
    +                  (1+ (max (avl-height (avl-node-prop noderef :left))
    +		           (avl-height (avl-node-prop noderef :right)))))))
    +
    +(defun avl-setbalance (noderef)
    +  ;;(when (integerp node) (setq node (avl-node node)))
    +  (avl-reheight noderef)
    +  (avl-set-prop noderef :balance
    +		(- (avl-height (avl-node-prop noderef :right))
    +		   (avl-height (avl-node-prop noderef :left)))))
    +
    +(defun avl-add-node (key parent)
    +  (let (result (idx 0))
    +    (cl-loop for idx from 0 to (1- (seq-length avl-all-nodes))
    +             while (null result) do
    +             (when (null (aref avl-all-nodes idx))
    +	       (aset avl-all-nodes idx (avl-create-node key parent))
    +	       (setq result idx)))
    +    result))
    +
    +(defun avl-insert (key)
    +  (if (null avl-root-node)
    +      (progn (setq avl-root-node (avl-add-node key nil)) avl-root-node)
    +    (progn
    +      (let ((n avl-root-node) (end-loop nil) parent go-left result)
    +	(while (not end-loop)
    +	  (if (equal key (avl-node-prop n :key))
    +	      (setq end-loop 't)
    +	    (progn
    +	      (setq parent n)
    +	      (setq go-left (> (avl-node-prop n :key) key))
    +	      (setq n (if go-left
    +                          (avl-node-prop n :left)
    +                        (avl-node-prop n :right)))
    +	
    +	      (when (null n)
    +                (setq result (avl-add-node key parent))
    +		(if go-left
    +		    (progn
    +		      (avl-set-prop parent :left result))
    +		  (progn
    +		    (avl-set-prop parent :right result)))
    +		(avl-rebalance parent) ;;rebalance
    +		(setq end-loop 't)))))
    +	result))))
    +
    +
    +(defun avl-rotate-left (noderef)
    +  (when (not (integerp noderef)) (error "parameter must be an integer"))
    +  (let ((a noderef) b)
    +    (setq b (avl-node-prop a :right))
    +    (avl-set-prop b :parent (avl-node-prop a :parent))
    +
    +    (avl-set-prop a :right (avl-node-prop b :left))
    +
    +    (when (avl-node-prop a :right) (avl-set-prop a :right :parent a))
    +
    +    (avl-set-prop b :left a)
    +    (avl-set-prop a :parent b)
    +
    +    (when (not (null (avl-node-prop b :parent)))
    +      (if (equal (avl-node-prop b :parent :right) a)
    +          (avl-set-prop b :parent :right b)
    +        (avl-set-prop b :parent :left b)))
    +
    +    (avl-setbalance a)
    +    (avl-setbalance b)
    +    b))
    +
    +
    +
    +(defun avl-rotate-right (node-idx)
    +  (when (not (integerp node-idx)) (error "parameter must be an integer"))
    +  (let ((a node-idx) b)
    +    (setq b (avl-node-prop a :left))
    +    (avl-set-prop b :parent (avl-node-prop a :parent))
    +
    +    (avl-set-prop a :left (avl-node-prop b :right))
    +
    +    (when (avl-node-prop a :right) (avl-set-prop a :right :parent a))
    +
    +    (avl-set-prop b :left a)
    +    (avl-set-prop a :parent b)
    +
    +    (when (not (null (avl-node-prop b :parent)))
    +      (if (equal (avl-node-prop b :parent :right) a)
    +          (avl-set-prop b :parent :right b)
    +        (avl-set-prop b :parent :left b)))
    +
    +    (avl-setbalance a)
    +    (avl-setbalance b)
    +    b))
    +
    +(defun avl-rotate-left-then-right (noderef)
    +  (avl-set-prop noderef :left (avl-rotate-left (avl-node-prop noderef :left)))
    +  (avl-rotate-right noderef))
    +
    +(defun avl-rotate-right-then-left (noderef)
    +  (avl-set-prop noderef :right (avl-rotate-left (avl-node-prop noderef :right)))
    +  (avl-rotate-left noderef))
    +
    +(defun avl-rebalance (noderef)
    +  (avl-setbalance noderef)
    +  (cond
    +   ((equal -2 (avl-node-prop noderef :balance))
    +    (if (>= (avl-height (avl-node-prop noderef :left :left))
    +	    (avl-height (avl-node-prop noderef :left :right)))
    +	(setq noderef (avl-rotate-right noderef))
    +      (setq noderef (avl-rotate-left-then-right noderef)))
    +    )
    +   ((equal 2 (avl-node-prop noderef :balance))
    +    (if (>= (avl-height (avl-node-prop noderef :right :right))
    +	    (avl-height (avl-node-prop noderef :right :left)))
    +	(setq noderef (avl-rotate-left noderef))
    +      (setq noderef (avl-rotate-right-then-left noderef)))))
    +
    +  (if (not (null (avl-node-prop noderef :parent)))
    +      (avl-rebalance (avl-node-prop noderef :parent))
    +    (setq avl-root-node noderef)))
    +
    +
    +(defun avl-delete (noderef)
    +  (when noderef
    +    (when (and (null (avl-node-prop noderef :left))
    +               (null (avl-node-prop noderef :right)))
    +      (if (null (avl-node-prop noderef :parent))
    +          (setq avl-root-node nil)
    +        (let ((parent (avl-node-prop noderef :parent)))
    +          (if (equal noderef (avl-node-prop parent :left))
    +              (avl-set-prop parent :left nil)
    +            (avl-set-prop parent :right nil))
    +          (avl-rebalance parent))))
    +
    +    (if (not (null (avl-node-prop noderef :left)))
    +        (let ((child (avl-node-prop noderef :left)))
    +          (while (not (null (avl-node-prop child :right)))
    +            (setq child (avl-node-prop child :right)))
    +          (avl-set-prop noderef :key (avl-node-prop child :key))
    +          (avl-delete child))
    +      (let ((child (avl-node-prop noderef :right)))
    +        (while (not (null (avl-node-prop child :left)))
    +          (setq child (avl-node-prop child :left)))
    +        (avl-set-prop noderef :key (avl-node-prop child :key))
    +        (avl-delete child)))))
    +
    +;; Main procedure
    +(let ((cnt 10) balances)
    +  (fillarray avl-all-nodes nil)
    +  (setq avl-root-node nil)
    +
    +  (dotimes (val cnt)
    +    (avl-insert (1+ val)))
    +
    +  (setq balances (seq-map (lambda (x) (or (avl-node-prop x :balance) 0))
    +			  (number-sequence 0 (1- cnt))))
    +
    +  (message "Inserting values 1 to %d" cnt)
    +  (message "Printing balance: %s" (string-join (seq-map (lambda (x) (format "%S" x)) balances) " ")))
    diff --git a/Task/Abbreviations-automatic/Ada/abbreviations-automatic.adb b/Task/Abbreviations-automatic/Ada/abbreviations-automatic.adb
    new file mode 100644
    index 0000000000..94a8c878f4
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/Ada/abbreviations-automatic.adb
    @@ -0,0 +1,71 @@
    +with Ada.Containers.Indefinite_Vectors;
    +with Ada.Strings.Fixed;
    +with Ada.Strings.Maps;
    +with Ada.Text_IO;
    +
    +procedure Abbreviations is
    +
    +   package String_Vectors is
    +     new Ada.Containers.Indefinite_Vectors (Index_Type   => Positive,
    +                                            Element_Type => String);
    +   use Ada.Text_IO, String_Vectors;
    +
    +   function Split (Line : String) return Vector is
    +      Result : Vector;
    +      First  : Natural;
    +      Last   : Natural := Line'First - 1;
    +   begin
    +      while Last + 1 in Line'Range loop
    +         Ada.Strings.Fixed.Find_Token
    +           (Line, Ada.Strings.Maps.To_Set (" "), Last + 1,
    +            Ada.Strings.Outside, First, Last);
    +         exit when Last = 0;
    +         Append (Result, Line (First .. Last));
    +      end loop;
    +      return Result;
    +   end Split;
    +
    +   function Abbrev_Length (Items : Vector) return Natural is
    +      use type Ada.Containers.Count_Type;
    +      Max     : Natural := 0;
    +      Abbrevs : Vector;
    +   begin
    +      for Item of Items loop
    +         Max := Natural'Max (Max, Item'Length);
    +      end loop;
    +
    +      for Length in 1 .. Max loop
    +         Abbrevs := Empty_Vector;
    +         for Item of Items loop
    +            declare
    +               Last : constant Natural
    +                 := Natural'Min (Item'Last, Item'First + Length - 1);
    +
    +               Abbrev : String renames Item (Item'First .. Last);
    +            begin
    +               exit when Abbrevs.Contains (Abbrev);
    +               Abbrevs.Append (Abbrev);
    +            end;
    +         end loop;
    +         if Abbrevs.Length = Items.Length then
    +            return Length;
    +         end if;
    +      end loop;
    +      return 0;
    +   end Abbrev_Length;
    +
    +   procedure Process (Line : String) is
    +      package Natural_IO is new Ada.Text_IO.Integer_IO (Natural);
    +      Words  : constant Vector  := Split (Line);
    +      Length : constant Natural := Abbrev_Length (Words);
    +   begin
    +      Natural_IO.Put (Length, Width => 2);
    +      Put (" ");
    +      Put_Line (Line);
    +   end Process;
    +
    +begin
    +   while not End_Of_File loop
    +      Process (Get_Line);
    +   end loop;
    +end Abbreviations;
    diff --git a/Task/Abbreviations-automatic/COBOL/abbreviations-automatic.cob b/Task/Abbreviations-automatic/COBOL/abbreviations-automatic.cob
    new file mode 100644
    index 0000000000..617cf60927
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/COBOL/abbreviations-automatic.cob
    @@ -0,0 +1,158 @@
    +            IDENTIFICATION DIVISION.
    +            PROGRAM-ID. AUTO-ABBREVIATIONS.
    +
    +            ENVIRONMENT DIVISION.
    +
    +            INPUT-OUTPUT SECTION.
    +            FILE-CONTROL.
    +              SELECT DOW ASSIGN TO "days-of-week.txt"
    +              ORGANIZATION IS LINE SEQUENTIAL.
    +
    +            DATA DIVISION.
    +              FILE SECTION.
    +              FD DOW.
    +              01 DOW-FILE PIC X(200).
    +
    +              WORKING-STORAGE SECTION. *> a.k.a. variables
    +              01 DOW-LINE PIC X(200).
    +              01 ENDO PIC 9(1).
    +              01 ENDO2 PIC 9(1).
    +              01 CURDAY PIC X(50).
    +              01 ABPTR PIC 999.
    +              01 LINE-NUM PIC 9(3) VALUE 1.
    +              01 CHARAMT PIC 9(3) VALUE 1.
    +              01 LARGESTCHARAMT PIC 9(3).
    +              01 DAYNUM PIC 9(3) VALUE 1.
    +              01 ABRESTART PIC 9(1).
    +              01 CURABBR PIC X(50).
    +              01 TMP1 PIC 9(3).
    +              01 TMP2 PIC 9(3).
    +              01 TINDEX PIC 9(3) VALUE 1.
    +              01 ABBRLIST.
    +                05 ABBRITEM PIC X(50) OCCURS 7 TIMES.
    +
    +
    +            PROCEDURE DIVISION.
    +              OPEN INPUT DOW.
    +                PERFORM UNTIL ENDO = 1
    +                  READ DOW INTO DOW-LINE
    +                    AT END MOVE 1 TO ENDO
    +                    NOT AT END PERFORM
    +                      *> loop through each line
    +                      IF DOW-LINE = "" THEN
    +                        DISPLAY ""
    +                      ELSE
    +                        MOVE 0 TO ENDO2
    +                        MOVE 0 TO CHARAMT
    +
    +                        PERFORM UNTIL ENDO2 > 0
    +                          MOVE 1 TO ABPTR
    +                          MOVE 1 TO DAYNUM
    +                          MOVE 0 TO ABRESTART
    +
    +                          ADD 1 TO CHARAMT
    +
    +                          *> reset the abbreviation table
    +                          MOVE 1 TO TINDEX
    +                          PERFORM 7 TIMES
    +                            MOVE SPACE TO ABBRITEM(TINDEX)
    +                            ADD 1 TO TINDEX
    +                          END-PERFORM
    +
    +                          *> loop through each day
    +                          PERFORM 7 TIMES
    +                            UNSTRING DOW-LINE DELIMITED BY SPACE
    +                              INTO CURDAY
    +                              WITH POINTER ABPTR
    +                            END-UNSTRING
    +
    +                            MOVE 0 TO TMP1
    +                            MOVE 0 TO TMP2
    +                            INSPECT CURDAY
    +                              TALLYING TMP1 FOR ALL CHARACTERS
    +                            INSPECT CURDAY
    +                              TALLYING TMP2 FOR ALL SPACE
    +                            SUBTRACT TMP2 FROM TMP1
    +                            IF TMP1 > LARGESTCHARAMT THEN
    +                              MOVE TMP1 TO LARGESTCHARAMT
    +                            END-IF
    +
    +                            *> not enough days error
    +                            IF CURDAY = "" THEN
    +                              MOVE 3 TO ENDO2
    +                            END-IF
    +
    +                            MOVE CURDAY(1:CHARAMT) TO CURABBR
    +
    +                            *> check if the current abbreviation is already taken
    +                            MOVE 1 TO TINDEX
    +                            PERFORM 7 TIMES
    +                              IF ABBRITEM(TINDEX) = CURABBR THEN
    +                                MOVE 1 TO ABRESTART
    +                              END-IF
    +                              ADD 1 TO TINDEX
    +                            END-PERFORM
    +
    +                            MOVE CURABBR TO ABBRITEM(DAYNUM)
    +
    +                            ADD 1 TO DAYNUM
    +
    +                          END-PERFORM
    +
    +                          IF ABRESTART = 0 THEN
    +                            MOVE 1 TO ENDO2
    +                          END-IF
    +
    +                          *> identical days error
    +                          IF CHARAMT > LARGESTCHARAMT THEN
    +                            MOVE 2 TO ENDO2
    +                          END-IF
    +
    +                        END-PERFORM
    +
    +                        DISPLAY "Line " LINE-NUM ": " WITH NO ADVANCING
    +
    +                        IF ENDO2 = 3 THEN
    +                          DISPLAY "Error: not enough " WITH NO ADVANCING
    +                          DISPLAY "days"
    +                        ELSE IF ENDO2 = 2 THEN
    +                          DISPLAY "Error: identical " WITH NO ADVANCING
    +                          DISPLAY "days"
    +                        ELSE
    +                          DISPLAY CHARAMT ": " WITH NO ADVANCING
    +
    +                          *> loop through each day and display its abbreviation
    +                          MOVE 1 TO TINDEX
    +                          PERFORM 7 TIMES
    +                            MOVE ABBRITEM(TINDEX) TO CURABBR
    +
    +                            MOVE 0 TO TMP1
    +                            MOVE 0 TO TMP2
    +                            INSPECT CURABBR
    +                              TALLYING TMP1 FOR ALL CHARACTERS
    +                            INSPECT CURABBR
    +                              TALLYING TMP2 FOR TRAILING SPACES
    +                            SUBTRACT TMP2 FROM TMP1
    +
    +                            DISPLAY CURABBR(1:TMP1) WITH NO ADVANCING
    +                            DISPLAY "." WITH NO ADVANCING
    +
    +                            IF TINDEX < 7 THEN
    +                              DISPLAY SPACE WITH NO ADVANCING
    +                            ELSE
    +                              DISPLAY X"0a" WITH NO ADVANCING *> go to next line
    +                            END-IF
    +
    +                            ADD 1 TO TINDEX
    +                          END-PERFORM
    +                        END-IF
    +
    +                      END-IF
    +
    +                    END-PERFORM
    +                  END-READ
    +
    +                  ADD 1 TO LINE-NUM
    +                END-PERFORM.
    +              CLOSE DOW.
    +              STOP RUN.
    diff --git a/Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.el b/Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.el
    new file mode 100644
    index 0000000000..8877dc684b
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/Emacs-Lisp/abbreviations-automatic.el
    @@ -0,0 +1,36 @@
    +(defun abbreviate-list (list-of-days abbreviation-length)
    +  "Take each element of LIST-OF-DAYS and abbreviate to ABBREVIATION-LENGTH."
    +  (let ((abbrev-list)
    +        (abbrev-element))
    +    (dolist (one-element list-of-days)                                        ; loop through each day of week
    +;; if the day of week is at least as long as the abbreviation
    +      (if (>= (length one-element) abbreviation-length)                       ; if day >= abbreviation length
    +          (setq abbrev-element (substring one-element 0 abbreviation-length)) ; abbreviate the day of the week
    +        (setq abbrev-element one-element))                                    ; otherwise don't abbreviate
    +      (push abbrev-element abbrev-list))                                      ; put the abbreviated/non-abbreviated day on our list
    +    abbrev-list))                                                             ; return the list of abbreviated days
    +
    +(defun cycle-days (list-of-days)
    +  "Find shortest unique abbreviation in LIST-OF-DAYS list."
    +  (let ((abbrev-list)
    +        (abbrev-length 1)
    +        (current-abbrev)
    +        (looking-for-shortest-list t))
    +    (if (= (length list-of-days) 0)                                   ; if list-of-days is empty (i.e., blank line)
    +        (setq looking-for-shortest-list nil))                         ; then don't look for the shortest unique abbreviations
    +    (while looking-for-shortest-list                                  ; as long as we are looking for the shortest unique abbreviations
    +      (setq abbrev-list (abbreviate-list list-of-days abbrev-length)) ; get a list of abbreviated day names
    +      (if (= (length list-of-days) (length (seq-uniq abbrev-list)))   ; if abbreviated list has no duplicates
    +          (progn
    +            (message (format "%d %s" abbrev-length list-of-days))     ; then in echo buffer show length and days
    +            (setq looking-for-shortest-list nil))                     ; also, then don't look for the shortest unique abbreviations
    +        (setq abbrev-length (+ abbrev-length 1))))))                  ; else increase the length of the abbreviation; loop to while
    +
    +(defun days-of-week ()
    +  "Find minimum abbreviation length of days of week."
    +  (let ((current-line-list))
    +  (find-file "Days_of_week.txt")                             ; open file or switch to buffer
    +  (beginning-of-buffer)                                      ; go to the top of the buffer
    +  (dolist (current-line (split-string (buffer-string) "\n")) ; go line by line through buffer
    +    (setq current-line-list (split-string current-line " ")) ; change each line into list of days of week
    +    (cycle-days current-line-list))))
    diff --git a/Task/Abbreviations-automatic/Fortran/abbreviations-automatic.f b/Task/Abbreviations-automatic/Fortran/abbreviations-automatic.f
    new file mode 100644
    index 0000000000..a53f211014
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/Fortran/abbreviations-automatic.f
    @@ -0,0 +1,113 @@
    +!
    +! Abbreviations, automatic
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +!             VSI Fortran x86-64 V8.6-001                   on OpenVMS x86_64 V9.2-3
    +! U.B., December 2025
    +!==============================================================================
    +
    +program AbbrAuto
    +  integer, parameter :: longestLine = 210    ! Longest input line
    +  integer, parameter :: LongestDay = 30      ! Longest length of 1 day name
    +  character (len=longestLine) :: Line
    +  character (len=LongestDay)  :: Days(7)      ! 1 week
    +
    +  integer :: l, io_stat
    +  logical :: OK
    +
    +  open (unit=10, file = 'days_of_week.txt', status='old', action='read', iostat=io_stat)
    +  if (io_stat /= 0) then
    +     print *, "Error opening file"
    +     stop
    +  end if
    +
    +
    +  do                                        ! Read all lines
    +    read (10, '(A)', iostat=io_stat) Line
    +    if (io_stat <0) exit                    ! Normal: EOF on input
    +    if (io_stat >0) then                    ! Not Normal: Read error
    +      print *, "Read error"                 ! has never been observed during testing.
    +      exit
    +    end if
    +    call separateDays (Line, Days, OK)
    +    if (OK) then                             ! 7 week days' name found
    +      print '(I2, X, A)' , smallestAbreviation (Days), Line (:len_trim(Line))
    +    else
    +      print *                                 ! Null string for empty or invalid line
    +    endif
    +
    +  end do    ! Read all lines
    +
    +  contains
    +
    +
    +  ! =========================================================================================
    +  ! Argument argLine contains space-separated list of (expected) 7 names of week days.
    +  ! Separate day names into array argDays, OK is .false. if number of days is not exactly 7.
    +  ! =========================================================================================
    +  subroutine separateDays (argLine, argDays, OK)
    +
    +  character (len=longestLine), intent(in) :: argLine
    +  character (len=LongestDay) , intent(out) :: argDays(7)      ! 1 week
    +  logical, intent(out) :: OK
    +  integer :: ip1, ip2, nDays            ! 2 Pointers into line, number of day names detected
    +  integer :: l
    +
    +  ip1 = 1
    +  nDays = 0
    +
    +  l = len_trim (argLine)
    +  do while (ip1 .le. l)                                     ! Loop untill entire line processed.
    +    do while (ip1 .le. l .and. argLine (ip1:ip1) .eq. ' ')  ! Skip space(s)
    +      ip1 = ip1 + 1
    +    end do
    +    if (ip1 .le. l) then                                    ! still inside Line?
    +      ip2 = ip1
    +      do while (ip2 .le. l .and. argLine (ip2:ip2) .ne. ' ')  ! Find end of current word
    +        ip2 = ip2 + 1
    +      end do
    +
    +      ! Here found space or end of line: Word is complete
    +        if (ip2 .gt. l) ip2 = l                               ! End reached
    +        if (argLine (ip2:ip2) .eq. ' ') ip2 = ip2 - 1         ! Space found
    +        if (ip2 .gt. ip1) then                                ! day name has at least 2 letters
    +          nDays = nDays + 1
    +          argDays (nDays) = ' '
    +          argDays (nDays) = argLine (ip1:ip2)
    +        endif                               !
    +      ip1 = ip2 + 1         ! Prepare for next day search: set behind current word
    +    endif
    +  end do
    +  OK = (nDays .eq. 7)   ! Result is OK only if number of days is 7
    +  end subroutine separateDays
    +
    +  ! =============================================================================
    +  ! Find length of smallest abbreviation of 7 day names so that abbreviated name
    +  ! is still unique.
    +  ! =============================================================================
    +  function smallestAbreviation (argDays)   result (nUniq)
    +  character (len=LongestDay) , intent(in) :: argDays(7)      ! 1 week
    +  integer :: nUniq
    +  integer :: ii, jj
    +  logical :: done
    +  nUniq = 1
    +  done = .false.
    +  do while (.not. done)
    +    done = .true.
    +    daysLoop: do ii=1, 6
    +      do jj=ii+1,7
    +        if (argDays (ii)(:nUniq) .eq. argDays(jj)(:nUniq)) then
    +          ! nUniq is too small for useful abbreviation of week days' name
    +          nUniq = nUniq + 1
    +          done = .false.
    +          exit daysLoop             ! go and try tith next larger nUniq
    +        end if
    +      end do
    +    end do daysLoop
    +    ! here: done is .true. if no two day names are identical in first 'nUuniq' characters
    +    ! otherwise still the abbreviation is still too short
    +  end do
    +  end function smallestAbreviation
    +
    +
    +end program AbbrAuto
    diff --git a/Task/Abbreviations-automatic/Pluto/abbreviations-automatic.pluto b/Task/Abbreviations-automatic/Pluto/abbreviations-automatic.pluto
    new file mode 100644
    index 0000000000..3b32fef82e
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/Pluto/abbreviations-automatic.pluto
    @@ -0,0 +1,65 @@
    +do  -- Abbreviatiions automatic - find the minimum abbreviation lengths for days of the week
    +    --                            in various languages
    +
    +    require( "uchar" )         -- RC Pluto Unicode character library
    +
    +    -- returns the table of space delimited words in s
    +    local function getWords( s : string ) : table
    +        local t, cmds, w = s, {}, s
    +        while t:contains( " " ) do
    +            w, t = t:partition( " " )
    +            if w != "" then
    +                cmds[ # cmds + 1 ] = w
    +            end
    +        end
    +        if t != "" then
    +            cmds[ # cmds + 1 ] = t
    +        end
    +        return cmds
    +    end
    +
    +    for dow in io.lines( "daysOfWeekNames.txt" ) do
    +        local names  = getWords( dow )
    +        if # names == 0 then
    +            io.write( "\n" )
    +        elseif # names != 7 then
    +            error( dow .. ": expected 7 names" )
    +        elseif # names > 0 then
    +            -- try abbreviation lengths up to the minimum word length
    +            local maxLen, uName = -1, {}
    +            for i, n in ipairs( names ) do
    +                uName[ i ] = uchar.of( n )
    +                local thisLen  = uName[ i ]:len()
    +                if thisLen > maxLen then
    +                    maxLen = thisLen
    +                end
    +            end
    +            local found = false
    +            for abLen = 1, maxLen do
    +                local prefixes  = {}
    +                found = true
    +                for nPos = 1, # names do
    +                    local subLen  = if uName[ nPos ]:len() < abLen
    +                                           then uName[ nPos ]:len()
    +                                           else abLen
    +                                           end
    +                    local ab      = uName[ nPos ]:sub( 1, subLen )
    +                    if prefixes:contains( ab ) then
    +                        found = false
    +                        break
    +                    else
    +                        prefixes[ ab ] = ab
    +                    end
    +                end
    +                if found then
    +                    io.write( string.format( "%2d %s\n", abLen, dow ) )
    +                    break
    +                end
    +            end
    +            if not found then
    +                error( "No unique abbreviations for: " .. dow )
    +            end
    +        end
    +    end
    +
    +end
    diff --git a/Task/Abbreviations-automatic/Rebol/abbreviations-automatic.rebol b/Task/Abbreviations-automatic/Rebol/abbreviations-automatic.rebol
    new file mode 100644
    index 0000000000..7f2f40aacf
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/Rebol/abbreviations-automatic.rebol
    @@ -0,0 +1,30 @@
    +Rebol [
    +    title: "Rosetta code: Abbreviations, automatic"
    +    file:  %Abbreviations,_automatic.r3
    +    url:   https://rosettacode.org/wiki/Abbreviations,_automatic
    +    needs: 3.0.0
    +    note:  "Based on Red language solution"
    +]
    +data: read/lines %abbrev.txt
    +foreach line data [                    ;; split data in lines at carriage return & line feed:
    +    if  empty?  trim line [
    +        print ""
    +        continue                       ;; continues at head of loop
    +    ]
    +    arr: split line space              ;; now split line in words ; accumulate in array / series
    +    min: 1                             ;; preset min length
    +    m: make map! []
    +    until [                            ;; head is the first position of series
    +        if head? arr [clear m]         ;; define an empty map (key -value store)
    +        abbr: copy/part first arr min  ;; copy/part ~  leftstr of first word with length min
    +        arr: either m/:abbr [          ;; abbreviation already exists ?
    +        min: min + 1
    +            head arr                   ;; reset series position to head
    +        ][                             ;; otherwise ....
    +            m/:abbr: true              ;; mark abreviation in map as existent
    +            next arr                   ;; set series position to next word
    +        ]
    +        tail? arr                      ;; this is the until condition , end /tail of  series reached ?
    +    ]
    +    print [min line]                   ;; print automatically reduces all words in block
    +]
    diff --git a/Task/Abbreviations-automatic/VBScript/abbreviations-automatic.vbs b/Task/Abbreviations-automatic/VBScript/abbreviations-automatic.vbs
    new file mode 100644
    index 0000000000..daaf4f3a31
    --- /dev/null
    +++ b/Task/Abbreviations-automatic/VBScript/abbreviations-automatic.vbs
    @@ -0,0 +1,36 @@
    +sub print(s) wscript.stdout.writeline s   :end sub
    +
    +set d=createobject("Scripting.Dictionary")
    +set fso=createobject("Scripting.Filesystemobject")
    +
    +const fn="weekdays_ansi.txt"
    +sfn=WScript.ScriptFullName
    +sfn= Left(sfn, InStrRev(sfn, "\"))
    +set f=fso.opentextfile(sfn & fn,1)
    +
    +while not f.atendofstream
    +  s=f.readline
    +  if s=vbNullString then
    +	   print " "
    +	else
    +    a=split(trim(s)," ")
    +    for abrlen=1 to 14
    +      d.removeall
    +      for wd=0 to 6
    +        k=left(a(wd),abrlen)
    +        if d.exists(k) then
    +          exit for
    +        else
    +          d.add k,""
    +        end if
    +      next  'wd
    +      if wd>6 then exit for
    +    next 'abrlen
    +	  b=right("  " & abrlen,2)
    +	  for wd=0 to 6
    +       b=b &" "& left(a(wd),abrlen)
    +    next
    +    print b
    +  end if	
    +wend  'line
    +f.close
    diff --git a/Task/Abbreviations-easy/AWK/abbreviations-easy.awk b/Task/Abbreviations-easy/AWK/abbreviations-easy.awk
    index 70a7c2cac5..4885af4516 100644
    --- a/Task/Abbreviations-easy/AWK/abbreviations-easy.awk
    +++ b/Task/Abbreviations-easy/AWK/abbreviations-easy.awk
    @@ -10,28 +10,28 @@ split("   Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPre
           "   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up" \
           , CMD);
     
    -	for (k=1; k <= length(CMD); k++) {
    -		cmd[k] = CMD[k];
    -		sub(/[a-z]*$/,"",cmd[k]);
    -		# print "0: ",CMD[k],"\t",cmd[k];
    -	}
    +  for (k=1; k <= length(CMD); k++) {
    +    cmd[k] = CMD[k];
    +    sub(/[a-z]*$/,"",cmd[k]);
    +    # print "0: ",CMD[k],"\t",cmd[k];
    +  }
     }
     
     function GET_ABBR(input) {
    -	for (k2=1; k2<=length(CMD); k2++) {
    -		if (index(toupper(CMD[k2]),input)==1) {
    -			if (index(input,toupper(cmd[k2]))==1) {
    -				return toupper(CMD[k2]);
    -			}
    -		}
    -	}
    -	return "*error*";
    +  for (k2=1; k2<=length(CMD); k2++) {
    +    if (index(toupper(CMD[k2]),input)==1) {
    +      if (index(input,toupper(cmd[k2]))==1) {
    +        return toupper(CMD[k2]);
    +      }
    +    }
    +  }
    +  return "*error*";
     }
     
     {
    -	R="";	
    -	for (k1=1; k1 <= NF; k1++) {
    -		R=R" "GET_ABBR(toupper($k1))
    -	}
    -	print R;
    +  R="";
    +  for (k1=1; k1 <= NF; k1++) {
    +    R=R" "GET_ABBR(toupper($k1))
    +  }
    +  print R;
     }
    diff --git a/Task/Abbreviations-easy/Ada/abbreviations-easy.adb b/Task/Abbreviations-easy/Ada/abbreviations-easy.adb
    new file mode 100644
    index 0000000000..17dbc7a2c5
    --- /dev/null
    +++ b/Task/Abbreviations-easy/Ada/abbreviations-easy.adb
    @@ -0,0 +1,98 @@
    +with Ada.Characters.Handling;
    +with Ada.Containers.Indefinite_Vectors;
    +with Ada.Strings.Fixed;
    +with Ada.Strings.Maps.Constants;
    +with Ada.Text_IO;
    +
    +procedure Abbreviations_Easy is
    +
    +   package Command_Vectors
    +   is new Ada.Containers.Indefinite_Vectors (Index_Type   => Positive,
    +                                             Element_Type => String);
    +   use Command_Vectors;
    +
    +   Commands : Vector;
    +
    +   procedure Append (Word_List : String) is
    +      use Ada.Strings;
    +      First : Positive := Word_List'First;
    +      Last  : Natural;
    +   begin
    +      loop
    +         Fixed.Find_Token (Word_List,
    +                           Set   => Maps.Constants.Letter_Set,
    +                           From  => First,
    +                           Test  => Inside,
    +                           First => First,
    +                           Last  => Last);
    +         exit when Last = 0;
    +         Commands.Append (Word_List (First .. Last));
    +         exit when Last = Word_List'Last;
    +         First := Last + 1;
    +      end loop;
    +   end Append;
    +
    +   function Match (Word : String) return String is
    +      use Ada.Strings;
    +      use Ada.Characters.Handling;
    +      Upper_Word   : constant String := To_Upper (Word);
    +      Prefix_First : Positive;
    +      Prefix_Last  : Natural;
    +   begin
    +      if Word = "" then
    +         return "";
    +      end if;
    +
    +      for Command of Commands loop
    +         Fixed.Find_Token (Command, Maps.Constants.Upper_Set, Inside,
    +                           Prefix_First, Prefix_Last);
    +         declare
    +            Upper_Prefix  : constant String  := Command (Prefix_First .. Prefix_Last);
    +            Upper_Command : constant String  := To_Upper (Command);
    +            Valid_Length  : constant Boolean := Word'Length >= Upper_Prefix'Length;
    +            Match_Length  : constant Natural := Natural'Min (Word'Length,
    +                                                             Command'Length);
    +            Valid_Match   : constant Boolean
    +              := Fixed.Head (Upper_Word, Upper_Word'Length)
    +                = Fixed.Head (Upper_Command, Upper_Word'Length);
    +         begin
    +            if Valid_Length and Valid_Match then
    +               return Upper_Command;
    +            end if;
    +         end;
    +      end loop;
    +      return "*error*";
    +   end Match;
    +
    +   procedure Put_Match (To : String) is
    +      use Ada.Text_IO;
    +      M : constant String := Match (To);
    +   begin
    +      Put ("Match to '");  Put (To);
    +      Put ("' is '");      Put (M);
    +      Put_Line ("'");
    +   end Put_Match;
    +
    +   procedure A (Item : String) renames Append;
    +begin
    +   A ("Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy");
    +   A ("COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find");
    +   A ("NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput");
    +   A ("Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO");
    +   A ("MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT");
    +   A ("READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT");
    +   A ("RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up");
    +
    +   Put_Match ("riG");
    +   Put_Match ("rePEAT");
    +   Put_Match ("copies");
    +   Put_Match ("put");
    +   Put_Match ("mo");
    +   Put_Match ("rest");
    +   Put_Match ("types");
    +   Put_Match ("fup.");
    +   Put_Match ("6");
    +   Put_Match ("poweRin");
    +   Put_Match ("");
    +   Put_Match ("o");
    +end Abbreviations_Easy;
    diff --git a/Task/Abbreviations-easy/AutoHotkey/abbreviations-easy.ahk b/Task/Abbreviations-easy/AutoHotkey/abbreviations-easy.ahk
    index f188819fb2..103aee1a03 100644
    --- a/Task/Abbreviations-easy/AutoHotkey/abbreviations-easy.ahk
    +++ b/Task/Abbreviations-easy/AutoHotkey/abbreviations-easy.ahk
    @@ -16,7 +16,7 @@ str := StrReplace(str,"`n")
     comTable := StrSplit(RegExReplace(str, "\s+", " "), " ")
     comTableCapsCount := []
     for cmds in comTable
    -	comTableCapsCount.push(StrLen(RegExReplace(comTable[cmds], "[a-z]")))
    +  comTableCapsCount.push(StrLen(RegExReplace(comTable[cmds], "[a-z]")))
     
     ; Take and process user input into an array of abbreviations
     InputBox, abbrev, Command, Type in your command(s).`n If you have several commands`, leave spaces between them.
    @@ -26,19 +26,19 @@ abbrev := StrSplit(RegExReplace(abbrev, "\s+", " "), " ")
     
     ; Double loop compares abbreviations to commands in command table
     Loop % abbrev.MaxIndex() {
    -	count := A_Index
    -	found := false
    -	for cmds in comTable {
    -		command := SubStr(comTable[cmds], 1, StrLen(abbrev[count]))
    -		StringLower, lowerCaseCommand, command
    -		if (lowerCaseCommand = abbrev[count]) and (StrLen(abbrev[count]) >= comTableCapsCount[cmds]) {
    -			StringUpper, foundCmd, % comTable[cmds]
    -			found := true
    -		}
    -	}
    -	if (found)
    -		result .= " " foundCmd
    -	else
    -		result .= " *error*"
    +  count := A_Index
    +  found := false
    +  for cmds in comTable {
    +    command := SubStr(comTable[cmds], 1, StrLen(abbrev[count]))
    +    StringLower, lowerCaseCommand, command
    +    if (lowerCaseCommand = abbrev[count]) and (StrLen(abbrev[count]) >= comTableCapsCount[cmds]) {
    +      StringUpper, foundCmd, % comTable[cmds]
    +      found := true
    +    }
    +  }
    +  if (found)
    +    result .= " " foundCmd
    +  else
    +    result .= " *error*"
     }
     MsgBox % Trim(result)
    diff --git a/Task/Abbreviations-easy/Euphoria/abbreviations-easy.eu b/Task/Abbreviations-easy/Euphoria/abbreviations-easy.eu
    new file mode 100644
    index 0000000000..a840e20d63
    --- /dev/null
    +++ b/Task/Abbreviations-easy/Euphoria/abbreviations-easy.eu
    @@ -0,0 +1,35 @@
    +include std/text.e  -- for upper conversion
    +include std/console.e -- for display
    +include std/sequence.e
    +
    +sequence ct = """
    +Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy
    +COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
    +NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
    +Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO
    +MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT
    +READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT
    +RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up
    +"""
    +ct = upper(split(join(split(ct,"\n")," ")," "))
    +
    +object input = remove_all("\n",upper(remove_all("",split(gets(0)))))
    +display(validate(input))
    +
    +-------------------------------
    +function validate(object words)
    +-------------------------------
    +object results = repeat("*error*",length(words)) -- build an output list;
    +integer x
    +for i = 1 to length(words) do
    +    words[i] = remove_all('\n',words[i]) -- final word in input line (may) have \n, get rid of it;
    +    for j = 1 to length(ct) do
    +        x = match(words[i],ct[j])
    +        if x = 1 then
    +            results[i] = ct[j] -- replace this slot in the output list with the "found" word;
    +            exit -- and don't look further into the list;
    +        end if
    +    end for
    +end for
    +return flatten(join(results," ")) -- convert sequence of strings into one string, words separated by a single space;
    +end function
    diff --git a/Task/Abbreviations-easy/Fortran/abbreviations-easy.f b/Task/Abbreviations-easy/Fortran/abbreviations-easy.f
    new file mode 100644
    index 0000000000..45a7c90bce
    --- /dev/null
    +++ b/Task/Abbreviations-easy/Fortran/abbreviations-easy.f
    @@ -0,0 +1,152 @@
    +!
    +! Abbreviations, easy
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +!             VSI Fortran x86-64 V8.6-001                   on OpenVMS x86_64 V9.2-3
    +! U.B., December 2025
    +!==============================================================================
    +program AbbrEasy
    +
    +  implicit none
    +
    +  integer, parameter  :: lenCmd = 10
    +  character (len=*), parameter  :: cmdTable =  &
    +    'Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy ' // &
    +    'COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ' // &
    +    'NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput ' // &
    +    'Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO ' // &
    +    'MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT ' // &
    +    'READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT ' // &
    +    'RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up'
    +
    +  character (len=*), parameter  :: userCmds  = &
    +   ' riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin'
    +
    +  character (len=*), parameter :: invalid = '*error*'
    +
    +  character (len=len(cmdTable))   :: upcaseCmdTable
    +  character (len=len(userCmds))   :: upcaseUserCmds
    +  character (len=lenCmd) :: parsedCmd
    +  character (len=lenCmd), allocatable :: allCmd (:), allUpcaseCmd(:)
    +  character (len=lenCmd)  inputCmd(10), upcaseInputCmd(10)    ! 10 counted manually.
    +
    +  integer :: ip1, ip2
    +  integer :: ii, l, la, nSpaces, nUP
    +
    +  ! Have a second command table, all in UPCASE , and count spaces so we get an idea how many
    +  ! commands there are in total.
    +  nSpaces = 0
    +  do ii=1, len(cmdTable)
    +    upcaseCmdTable (ii:ii) = toupper (cmdTable (ii:ii))
    +    if (upcaseCmdTable (ii:ii) .eq. ' ') nSpaces = nSpaces + 1
    +  end do
    +
    +  ! Also, have all user commands in UPCASE
    +  do ii=1, len(userCmds)
    +    upcaseUserCmds (ii:ii) = toupper (userCmds (ii:ii))
    +  end do
    +
    +  ! make space for the array with all commands bioth upper and lower case.
    +  allocate (allCmd (nSpaces+1))           ! might be more than needed bc superfluous spaces
    +  allocate (allUpcaseCmd (nSpaces+1))
    +
    +  ! Prepare lists of allowed commands and input commands
    +  call tokenize (cmdTable, upcaseCmdTable, allCmd,allUpcaseCmd)
    +  call tokenize (userCmds, upcaseUserCmds, inputCmd, upcaseInputCmd)
    +
    +  ! As first output line, print user input
    +  write (*, '(10(A10,x))') (inputCmd(ip1), ip1=1, size(inputCmd))
    +  ! Parse all user input commands
    +  do ip1 = 1, size(inputCmd)
    +    l = len_trim (inputCmd(ip1))
    +    parsedCmd = invalid
    +    do ip2 = 1, size(allCmd)
    +      la =len_trim(allCmd(ip2))
    +      if (la .ge. l) then           ! input is possible abbreviation of this command
    +        ! Case blind comparison
    +        if (allUpcaseCmd(ip2)(:l) .eq. upcaseInputCmd (ip1) (:l))  then
    +          ! at least this input cmd is a short form of this full command.
    +          ! But is it valid?
    +          NUP = 0                   ! Count number of starting UPCASE letters of command
    +          do ii=1, la
    +            if (allCmd (ip2)(ii:ii) .eq. allUpcaseCmd (ip2)(ii:ii)) then
    +              NUP = NUP + 1
    +            else
    +              exit                  ! found number of upcase characters, quit search.
    +            end if
    +          end do
    +          if (NUP .gt. l) then
    +            cycle     ! input is shorter than required minimum length,  try next command
    +          endif
    +        else
    +          cycle       ! input does not match command
    +        endif
    +        ! Here we know that input an abbreviation of command,
    +        ! and that it is not too short
    +        parsedCmd = allUpcaseCmd (ip2)  ! We have a result
    +        exit                            ! no need to check input against following commands
    +      else
    +        ! input is longer than this command, nothing to do.
    +      end if
    +    end do
    +    ! here we found the valid command, or the parsed value is still
    +    write (*, '(A10,X)', advance='no')  parsedCmd
    +  end do
    +  write (*,*)         ! Terminate output line.
    +
    +contains
    +
    +  ! ======================================================================================
    +  ! Divide a string of words separated by blanks into an array of the words without blanks
    +  ! ======================================================================================
    +  subroutine tokenize (tokenString, upCaseString, retList, upcaseRetList  )
    +
    +  character (len=*), intent(in) :: tokenString, upcaseString  ! input "as is" and "upcase"
    +  character (len=lencmd), intent(inout) :: retList(*), upcaseRetList(*)  ! Result "as is" and "Upcase"
    +  integer :: ip1, ip2
    +  integer :: nTokens
    +  ip1 = 1
    +  nTokens = 0
    +
    +  ! Divide single string to a list of words without spaces.
    +  l = len_trim (tokenString)
    +  do while (ip1 .le. l)
    +    do while (ip1 .le. l .and. tokenString (ip1:ip1) .eq. ' ')  ! Skip space(s)
    +      ip1 = ip1 + 1
    +    end do
    +    if (ip1 .le. l) then                                    ! still inside Line?
    +      ip2 = ip1
    +      do while (ip2 .le. l .and. tokenString (ip2:ip2) .ne. ' ')  ! Find end of current word
    +        ip2 = ip2 + 1
    +      end do
    +      if (ip2 .gt. l) ip2 = l                               ! End reached
    +      nTokens = nTokens + 1
    +!      print *, 'Command = ', tokenString (ip1:ip2)
    +      retList (nTokens) = tokenString (ip1:ip2)
    +      upcaseRetList (nTokens) = upcaseString (ip1:ip2)
    +      ip1 = ip2 + 1
    +    endif
    +  end do
    +
    +  end subroutine tokenize
    +
    +  ! =========================================================
    +  ! Convert a character c to UPPER CASE, if its in lower case.
    +  ! =========================================================
    +
    +  function toupper (c) result (U)
    +  character, intent(in) :: c        ! input
    +  character :: U                    ! output
    +  integer :: ix                     ! Helper: index of c in alphabet
    +
    +  Character(26), Parameter :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    +  Character(26), Parameter :: low = 'abcdefghijklmnopqrstuvwxyz'
    +
    +  ix = index (low, c)      ! find c in lower case alphabet
    +  if (ix .gt. 0) then      ! c found: it is in lower case
    +    U = cap (ix:ix)        !    ...and needs conversion
    +  else                     ! c not found, so is already in upper case,
    +    U = c                  !     ...or it is not a letter. Just copy to result.
    +  endif
    +  end function toupper
    +end program AbbrEasy
    diff --git a/Task/Abbreviations-easy/JavaScript/abbreviations-easy.js b/Task/Abbreviations-easy/JavaScript/abbreviations-easy.js
    index c277c13403..82bdef3953 100644
    --- a/Task/Abbreviations-easy/JavaScript/abbreviations-easy.js
    +++ b/Task/Abbreviations-easy/JavaScript/abbreviations-easy.js
    @@ -15,7 +15,7 @@ console.log(input.length==0?null:input.trim().split(/\s+/)
                   (s=>abr.filter(
                     a=>(new RegExp('^'+escapeRegex(s),'i'))
                       .test(a)&&s.length>=a.match(/^[A-Z]+/)[0].length
    -				  )[0])
    -				)
    +          )[0])
    +        )
                 .map(_=>typeof _=="undefined"?"*error*":_).join(' ')
    -			)
    +      )
    diff --git a/Task/Abbreviations-easy/Lua/abbreviations-easy.lua b/Task/Abbreviations-easy/Lua/abbreviations-easy.lua
    index 2ad8bedd27..4fb6ff8fab 100644
    --- a/Task/Abbreviations-easy/Lua/abbreviations-easy.lua
    +++ b/Task/Abbreviations-easy/Lua/abbreviations-easy.lua
    @@ -44,10 +44,10 @@ local function is_valid(cmd,abbrev)
     
        -- test if any lowercase in "cmd"
        if false then do -- NOTE!: requirement spec error .. put not equal PUT
    -	 local lowcase = string.match(cmd,"%l+")
    -	 if lowcase == nil then return -2 end
    -	 if #lowcase < 1 then return -3 end
    -		 end
    +   local lowcase = string.match(cmd,"%l+")
    +   if lowcase == nil then return -2 end
    +   if #lowcase < 1 then return -3 end
    +     end
        end
     
        -- test if abbrev is too long
    @@ -75,13 +75,13 @@ local function start()
        for i = 1,#t2 do
           good = 0
           for j = 1,#t1 do
    -	 local abbrev = t2[i]
    -	 local cmd = t1[j]
    -	 good = is_valid(cmd,abbrev)
    -	 if good==1 then do
    -	       result[#result+1] = t1[j]:upper()
    -	       break end
    -	 end  --if
    +   local abbrev = t2[i]
    +   local cmd = t1[j]
    +   good = is_valid(cmd,abbrev)
    +   if good==1 then do
    +         result[#result+1] = t1[j]:upper()
    +         break end
    +   end  --if
           end --for j
           if good < 1 then result[#result+1] = "*error*" end
        end --for i
    diff --git a/Task/Abbreviations-easy/MATLAB/abbreviations-easy.m b/Task/Abbreviations-easy/MATLAB/abbreviations-easy.m
    index 5e99ffc691..d080f05416 100644
    --- a/Task/Abbreviations-easy/MATLAB/abbreviations-easy.m
    +++ b/Task/Abbreviations-easy/MATLAB/abbreviations-easy.m
    @@ -8,22 +8,22 @@ CMD=strsplit(['Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst C
     '   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT' ...
     '   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up' ],' ');
     
    -for k=1:length(CMD)	
    -	cmd{k} = CMD{k}(CMD{k}<'a');
    -	CMD{k} = upper(CMD{k});
    +for k=1:length(CMD)
    +  cmd{k} = CMD{k}(CMD{k}<'a');
    +  CMD{k} = upper(CMD{k});
     end
     
     ilist = strsplit(input,' ');
     R = '';
     for k=1:length(ilist)
    -	input = upper(ilist{k});
    +  input = upper(ilist{k});
     
    -	ix = find(strncmp(CMD, input, length(input)));
    -	result= '*error*';
    -	for k = ix(:)',	
    -		if strncmp(input, cmd{k}, length(cmd{k}));
    -			result = CMD{k};
    -		end
    -	end
    -	R = [R,' ',result];
    +  ix = find(strncmp(CMD, input, length(input)));
    +  result= '*error*';
    +  for k = ix(:)',
    +    if strncmp(input, cmd{k}, length(cmd{k}));
    +      result = CMD{k};
    +    end
    +  end
    +  R = [R,' ',result];
     end
    diff --git a/Task/Abbreviations-easy/Pluto/abbreviations-easy.pluto b/Task/Abbreviations-easy/Pluto/abbreviations-easy.pluto
    new file mode 100644
    index 0000000000..9b177460f5
    --- /dev/null
    +++ b/Task/Abbreviations-easy/Pluto/abbreviations-easy.pluto
    @@ -0,0 +1,79 @@
    +do  -- Abbreviatiions Easy - expand command name abbreviations
    +
    +    -- returns the table of space delimited words in s
    +    local function getWords( s : string ) : table
    +        local t, cmds, w = s, {}, s
    +        while t:contains( " " ) do
    +            w, t = t:partition( " " )
    +            if w != "" then
    +                cmds[ # cmds + 1 ] = w
    +            end
    +        end
    +        if t != "" then
    +            cmds[ # cmds + 1 ] = t
    +        end
    +        return cmds
    +   end
    +
    +   local commandStrings  = "Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy "
    +                        .. "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
    +                        .. "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
    +                        .. "Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO "
    +                        .. "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT "
    +                        .. "READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT "
    +                        .. "RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up"
    +
    +    local function expandEasyAbbreviations( cmds : string, input : string ) : table
    +        local cmdTable, inputTable, outputTable = getWords( cmds ), getWords( input ), {}
    +
    +        local function isCommand( cmd : string, word : string ) : boolean
    +            local result, uCmd, uWord = false, cmd:upper(), word:upper()
    +            if # cmd >= # word then                 -- word is not longer than the command
    +                if uCmd == uWord then   -- the word is the command
    +                    result = true
    +                else                                -- word is shorter than the command
    +                    local ab = cmd:gsub( "%l", "" ) -- remove lowercase
    +                    if # ab <= # word then          -- the minimum abbreviation isn't longer than the word
    +                        result = uWord == uCmd:sub( 1, # word )
    +                    end
    +                end
    +            end
    +            return result
    +        end
    +
    +        for i = 1, # inputTable do
    +            local w, u = inputTable[ i ], "*error*"
    +            for c = 1, # cmdTable do
    +                if isCommand( cmdTable[ c ], w ) then
    +                    u = cmdTable[ c ]:upper()
    +                    break
    +                end
    +            end
    +            outputTable[ # outputTable + 1 ] = u
    +        end
    +        return { inputTable, outputTable }
    +    end
    +
    +    local function printExpansion( expansion : table )
    +        local fmt, input, output = {}, expansion[ 1 ], expansion[ 2 ]
    +        for i, v in ipairs( output ) do
    +            fmt[ i ] = " %" .. # v .. "s"
    +        end
    +        io.write( "Input: " )
    +        for i, v in ipairs( input ) do
    +            io.write( string.format( fmt[ i ], v ) )
    +        end
    +        io.write( "\nOutput:" )
    +        for i, v in ipairs( output ) do
    +            io.write( string.format( fmt[ i ], v ) )
    +        end
    +        io.write( "\n" )
    +    end
    +
    +    printExpansion( expandEasyAbbreviations( commandStrings
    +                                           , (  "riG   rePEAT copies  put mo   rest    "
    +                                             .. "types   fup.    6       poweRin"
    +                                             )
    +                                           )
    +                  )
    +end
    diff --git a/Task/Abbreviations-easy/PowerShell/abbreviations-easy.ps1 b/Task/Abbreviations-easy/PowerShell/abbreviations-easy.ps1
    new file mode 100644
    index 0000000000..ad178249f3
    --- /dev/null
    +++ b/Task/Abbreviations-easy/PowerShell/abbreviations-easy.ps1
    @@ -0,0 +1,44 @@
    +<# Start with a string of the commands #>
    +$cmdTableStr =
    +"Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy
    + COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
    + NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
    + Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO
    + MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT
    + READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT
    + RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up"
    +<# String of inputs #>
    +$userWordStr = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    +
    +$outputStr = $null # Set this string to null only so all variables are intialized
    +
    +$cmdTabArray = @() # Arrays for the commands and the inputs
    +$userWordArray = @()
    +
    +<# Split the strings into arrays using a space as the delimiter.
    +   This also removes "blank" entries, which fits the requirement
    +   "A blank input (or a null input) should return a null string." #>
    +$cmdTabArray = $cmdTableStr.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries)
    +$userWordArray = $userWordStr.Split(" ", [System.StringSplitOptions]::RemoveEmptyEntries)
    +
    +<# Begins a loop to iterate through the inputs #>
    +foreach($word in $userWordArray)
    +{
    +    $match = $false # Variable set to false so that if a match is never found, the "*error*" string can be appended
    +    foreach($cmd in $cmdTabArray)
    +    {
    +        <# This test: 1) ensures inputs match the leading characters of the command
    +                      2) are abbreviations of the command
    +                      3) the abbreviations is at least the number of capital characters in the command #>
    +        if($cmd -like "$word*" -and ($word.Length -ge ($cmd -creplace '[a-z]').Length))
    +        {
    +            $outputStr += $cmd.ToUpper() + " " # Adds the command in all caps to the output string
    +            $match = $true # Sets the variable so that "*error*" is not appended
    +            break # Break keep the loop from continuing and wasting time once a match was found
    +        }
    +    }
    +    if($match -eq $false){ $outputStr += "*error* " } # Appends error if no match was found
    +}
    +# Below lines display the input and output
    +"User text: " + $userWordStr
    +"Full text: " + $outputStr
    diff --git a/Task/Abbreviations-easy/Rebol/abbreviations-easy.rebol b/Task/Abbreviations-easy/Rebol/abbreviations-easy.rebol
    new file mode 100644
    index 0000000000..78065be75f
    --- /dev/null
    +++ b/Task/Abbreviations-easy/Rebol/abbreviations-easy.rebol
    @@ -0,0 +1,55 @@
    +Rebol [
    +    title: "Rosetta code: Abbreviations, easy"
    +    file:  %Abbreviations,_easy.r3
    +    url:   https://rosettacode.org/wiki/Abbreviations,_easy
    +]
    +
    +get-full-name: function [
    +    "Validate abbreviated commands against a command table"
    +    word [string! char!]
    +    commands [block!]
    +][
    +    word: to string! word
    +    foreach cmd commands [
    +        ;; count required uppercase prefix length
    +        prefix-end: 0
    +        foreach c cmd [
    +            if c > #"Z" [break]
    +            ++ prefix-end
    +        ]
    +        prefix: copy/part cmd prefix-end
    +        if all [
    +            parse word [prefix to end] ;; starts with required prefix
    +            parse cmd  [word   to end] ;; is not longer than command
    +        ][
    +            return uppercase copy cmd
    +        ]
    +    ]
    +    "*error*"
    +]
    +
    +split-commands: function/with [commands [string!]][
    +    parse commands [
    +        any delimit
    +        collect any [keep some chars any delimit]
    +    ]
    +][
    +    delimit: charset " ^-^/"
    +    chars: complement delimit
    +]
    +
    +commands: split-commands {
    +   Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy
    +   COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
    +   NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
    +   Join SPlit SPLTJOIN  LOAD  Locate CLocate  LOWercase UPPercase  LPrefix MACRO
    +   MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD  Query  QUIT
    +   READ  RECover REFRESH RENum REPeat  Replace CReplace  RESet  RESTore  RGTLEFT
    +   RIght LEft  SAVE  SET SHift SI  SORT  SOS  STAck STATus  TOP TRAnsfer Type Up}
    +
    +inputs: split-commands {riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin}
    +
    +foreach cmd inputs [
    +    full: get-full-name cmd commands
    +    print [pad cmd 10 '-> full]
    +]
    diff --git a/Task/Abbreviations-easy/Vedit-macro-language/abbreviations-easy.vedit b/Task/Abbreviations-easy/Vedit-macro-language/abbreviations-easy.vedit
    index 91e698f43c..540839e16e 100644
    --- a/Task/Abbreviations-easy/Vedit-macro-language/abbreviations-easy.vedit
    +++ b/Task/Abbreviations-easy/Vedit-macro-language/abbreviations-easy.vedit
    @@ -16,18 +16,18 @@ Ins_Text("riG rePEAT copies  put mo   rest    types   fup.    6       poweRin ")
     BOF
     
     // Main program
    -#20 = Reg_Free()			// Text register for the word to be converted
    +#20 = Reg_Free()      // Text register for the word to be converted
     Repeat(ALL) {
    -    Buf_Switch(#11)			// Buffer for example input
    -    Search("|!|X", ERRBREAK)		// Find next non-space character
    -    #30 = Cur_Pos			// #30 = begin of a word
    -    Search("|X", NOERR+NORESTORE)	// Find whitespace (end of the word)
    -    Reg_Copy_Block(#20, #30, Cur_Pos)	// Get the word to text register #20
    -    Call("acronym_to_word")		// Convert acronym to full word
    -    Reg_Type(#20)			// Display the full word
    -    Type_Char(' ')			// Display a space character
    +    Buf_Switch(#11)     // Buffer for example input
    +    Search("|!|X", ERRBREAK)    // Find next non-space character
    +    #30 = Cur_Pos     // #30 = begin of a word
    +    Search("|X", NOERR+NORESTORE) // Find whitespace (end of the word)
    +    Reg_Copy_Block(#20, #30, Cur_Pos) // Get the word to text register #20
    +    Call("acronym_to_word")   // Convert acronym to full word
    +    Reg_Type(#20)     // Display the full word
    +    Type_Char(' ')      // Display a space character
     }
    -Buf_Switch(#10) Buf_Quit(OK)		// Clean-up
    +Buf_Switch(#10) Buf_Quit(OK)    // Clean-up
     Buf_Switch(#11) Buf_Quit(OK)
     Reg_Empty(#20)
     Return
    @@ -37,29 +37,29 @@ Return
     // Return: @(#20) = the full word
     //
     :acronym_to_word:
    -if (Reg_Size(#20) == 0) {		// If zero length input,
    -    return				// return zero length string
    +if (Reg_Size(#20) == 0) {   // If zero length input,
    +    return        // return zero length string
     }
    -Buf_Switch(#10)				// Switch to command table
    +Buf_Switch(#10)       // Switch to command table
     BOF
     While (!At_EOF) {
    -    if (Search("|S|@(#20)", NOERR)) {		// Find (the first part of) the word
    -	Char					// Skip the separator
    -	#31 = Cur_Pos				// #31 = Begin of the acronym
    -	Char(Reg_Size(#20))			// Check if the acronym is log enough
    -	if (Cur_Char < 'A' || Cur_Char > 'Z') {	// Not a capital letter, verified
    -	    Search("|X")			// Find the end of the word
    -	    Reg_Copy_Block(#20, #31, Cur_Pos)	// Get the word into text register #20
    -	    Buf_Switch(Buf_Free)		// Convert to upper case using tmp buffer
    -	    Reg_Ins(#20)
    -	    Case_Upper_Block(0, Cur_Pos)
    -	    Reg_Copy_Block(#20, 0, Cur_Pos)
    -	    Buf_Quit(OK)
    -	    break				// Word found, exit loop
    -	}
    -    } else {					// Not found
    -	Reg_Set(#20, "*error*")
    -	break
    +    if (Search("|S|@(#20)", NOERR)) {   // Find (the first part of) the word
    +  Char          // Skip the separator
    +  #31 = Cur_Pos       // #31 = Begin of the acronym
    +  Char(Reg_Size(#20))     // Check if the acronym is log enough
    +  if (Cur_Char < 'A' || Cur_Char > 'Z') { // Not a capital letter, verified
    +      Search("|X")      // Find the end of the word
    +      Reg_Copy_Block(#20, #31, Cur_Pos) // Get the word into text register #20
    +      Buf_Switch(Buf_Free)    // Convert to upper case using tmp buffer
    +      Reg_Ins(#20)
    +      Case_Upper_Block(0, Cur_Pos)
    +      Reg_Copy_Block(#20, 0, Cur_Pos)
    +      Buf_Quit(OK)
    +      break       // Word found, exit loop
    +  }
    +    } else {          // Not found
    +  Reg_Set(#20, "*error*")
    +  break
         }
     }
     Return
    diff --git a/Task/Abbreviations-easy/Zkl/abbreviations-easy.zkl b/Task/Abbreviations-easy/Zkl/abbreviations-easy.zkl
    index 83e3a2f98d..3ded775160 100644
    --- a/Task/Abbreviations-easy/Zkl/abbreviations-easy.zkl
    +++ b/Task/Abbreviations-easy/Zkl/abbreviations-easy.zkl
    @@ -1,4 +1,4 @@
    -commands:=Data(0,String,	// "Add\0ALTer\0..."
    +commands:=Data(0,String,  // "Add\0ALTer\0..."
     #<<<
     "Add ALTer  BAckup Bottom  CAppend Change SCHANGE  CInsert CLAst COMPress COpy
      COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
    @@ -11,14 +11,14 @@ commands:=Data(0,String,	// "Add\0ALTer\0..."
     #<<<
     
     testText:=" riG   rePEAT copies  put mo   rest    types "
    -	  "fup.    6       poweRin";
    +    "fup.    6       poweRin";
     
     testText.split().apply('wrap(word){
        sz,w := word.len(),word + "*";
    -   foreach c in (commands){	// rather inelegant but gotta ignore case
    +   foreach c in (commands){ // rather inelegant but gotta ignore case
           // check for length requirement and, if there, verify
           if(c.matches(w) and sz>=(c-"abcdefghijklmnopqrstuvwxyz").len())
    -	 return(c.toUpper());
    +   return(c.toUpper());
        }
        "*error*"
     .concat(" ").println();
    diff --git a/Task/Abbreviations-simple/Ada/abbreviations-simple.adb b/Task/Abbreviations-simple/Ada/abbreviations-simple.adb
    new file mode 100644
    index 0000000000..89413455d5
    --- /dev/null
    +++ b/Task/Abbreviations-simple/Ada/abbreviations-simple.adb
    @@ -0,0 +1,130 @@
    +with Ada.Characters.Handling;
    +with Ada.Containers.Vectors;
    +with Ada.Strings.Fixed;
    +with Ada.Strings.Maps.Constants;
    +with Ada.Strings.Unbounded;
    +with Ada.Text_IO;
    +
    +procedure Abbreviations_Simple is
    +
    +   use Ada.Strings.Unbounded;
    +   subtype Ustring is Unbounded_String;
    +
    +   type Word_Entry is record
    +      Word : Ustring;
    +      Min  : Natural;
    +   end record;
    +
    +   package Command_Vectors
    +   is new Ada.Containers.Vectors (Index_Type   => Positive,
    +                                  Element_Type => Word_Entry);
    +
    +   Commands      : Command_Vectors.Vector;
    +   Last_Word     : Ustring;
    +   Last_Was_Word : Boolean := False;
    +
    +   procedure Append (Word_List : String) is
    +      use Ada.Strings;
    +
    +      function Is_Word (Item : String) return Boolean
    +      is (Fixed.Count (Item, Maps.Constants.Letter_Set) /= 0);
    +
    +      procedure Process (Token : String) is
    +      begin
    +         if Is_Word (Token) then
    +            if Last_Was_Word then
    +               Commands.Append ((Word => Last_Word,
    +                                 Min  => Length (Last_Word)));
    +            end if;
    +            Last_Word     := To_Unbounded_String (Token);
    +            Last_Was_Word := True;
    +
    +         else  -- Token is expected to be decimal
    +            Commands.Append ((Word => Last_Word,
    +                              Min  => Natural'Value (Token)));
    +            Last_Was_Word := False;
    +         end if;
    +      end Process;
    +
    +      Token_First : Positive := Word_List'First;
    +      Token_Last  : Natural;
    +   begin
    +      while Token_First in Word_List'Range loop
    +
    +         Fixed.Find_Token (Word_List, Maps.Constants.Alphanumeric_Set,
    +                           Token_First, Inside,
    +                           Token_First, Token_Last);
    +         exit when Token_Last = 0;
    +
    +         Process (Word_List (Token_First .. Token_Last));
    +
    +         Token_First := Token_Last + 1;
    +      end loop;
    +   end Append;
    +
    +   function Match (Word : String) return String is
    +      use Ada.Characters.Handling;
    +      use Ada.Strings.Fixed;
    +      Result : Ustring := To_Unbounded_String ("*error*");
    +      Min    : Natural := 0;
    +      Upper_Word : constant String := To_Upper (Word);
    +   begin
    +      if Upper_Word = "" then
    +         return "";
    +      end if;
    +
    +      for Candidate of Commands loop
    +         declare
    +            Upper_Cand : constant String  := To_Upper (To_String (Candidate.Word));
    +            Length     : constant Natural := Natural'Max (Candidate.Min,
    +                                                          Upper_Word'Length);
    +            Upper_Abbrev_Cand : constant String := Head (Upper_Cand, Length);
    +            Upper_Abbrev_Word : constant String := Head (Upper_Word, Length);
    +         begin
    +            if Upper_Word = Upper_Cand
    +              and then Upper_Word'Length > Min
    +            then
    +               Result := To_Unbounded_String (Upper_Cand);
    +               Min    := Upper_Word'Length;
    +            elsif Upper_Abbrev_Word = Upper_Abbrev_Cand
    +              and then Upper_Abbrev_Word'Length > Min
    +            then
    +               Result := To_Unbounded_String (Upper_Cand);
    +               Min    := Upper_Abbrev_Word'Length;
    +            end if;
    +         end;
    +      end loop;
    +      return To_String (Result);
    +   end Match;
    +
    +   procedure Put_Match (To : String) is
    +      use Ada.Text_IO;
    +   begin
    +      Put ("Match to '");  Put (To);
    +      Put ("' is '");      Put (Match (To));
    +      Put_Line ("'");
    +   end Put_Match;
    +
    +   procedure A (Item : String) renames Append;
    +begin
    +   A ("add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3");
    +   A ("compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate");
    +   A ("3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2");
    +   A ("forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load");
    +   A ("locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2");
    +   A ("msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3");
    +   A ("refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left");
    +   A ("2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1");
    +
    +   Put_Match ("riG");
    +   Put_Match ("rePEAT");
    +   Put_Match ("copies");
    +   Put_Match ("put");
    +   Put_Match ("mo");
    +   Put_Match ("rest");
    +   Put_Match ("types");
    +   Put_Match ("fup.");
    +   Put_Match ("6");
    +   Put_Match ("poweRin");
    +   Put_Match ("");
    +end Abbreviations_Simple;
    diff --git a/Task/Abbreviations-simple/D/abbreviations-simple.d b/Task/Abbreviations-simple/D/abbreviations-simple.d
    index b071380f6d..7d3702b122 100644
    --- a/Task/Abbreviations-simple/D/abbreviations-simple.d
    +++ b/Task/Abbreviations-simple/D/abbreviations-simple.d
    @@ -1,36 +1,36 @@
     class Abbreviations
     {
    -	import std.array: split, join;
    -	import std.uni:toUpper;
    +  import std.array: split, join;
    +  import std.uni:toUpper;
     
    -	string[string] replaces;
    -	
    -	this(string table)
    -	{
    -		import std.ascii;
    -		import std.conv:parse;
    +  string[string] replaces;
     
    -		string saved;
    -		auto add = (string word){ if(word.length) replaces[word] = word; };
    +  this(string table)
    +  {
    +    import std.ascii;
    +    import std.conv:parse;
     
    -		foreach(word; table.toUpper.split)
    -			if(isDigit(word[0]))
    -			{
    -				for(int length=parse!int(word); length<=saved.length; ++length)
    -					replaces[saved[0..length]] = saved;
    -			} else
    -			{
    -				add(saved);
    -				saved = word;
    -			}
    -		add(saved);
    -	}
    +    string saved;
    +    auto add = (string word){ if(word.length) replaces[word] = word; };
     
    -	string expand(string input) // pre-filled hashtable is used
    -	{
    -		import std.algorithm: map;
    -		return input.toUpper.split.map!(word => word in replaces ? replaces[word] : "*error*").join(" ");
    -	}
    +    foreach(word; table.toUpper.split)
    +      if(isDigit(word[0]))
    +      {
    +        for(int length=parse!int(word); length<=saved.length; ++length)
    +          replaces[saved[0..length]] = saved;
    +      } else
    +      {
    +        add(saved);
    +        saved = word;
    +      }
    +    add(saved);
    +  }
    +
    +  string expand(string input) // pre-filled hashtable is used
    +  {
    +    import std.algorithm: map;
    +    return input.toUpper.split.map!(word => word in replaces ? replaces[word] : "*error*").join(" ");
    +  }
     }
     
     string table = "
    @@ -48,16 +48,16 @@ string expected = "RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error*
     
     unittest // 'dmd -unittest ...' to activate it
     {
    -	auto expander = new Abbreviations(table);
    -	assert(expander.expand(input) == expected);
    -	assert(expander.expand("") == "");
    -	assert(expander.expand("addadd") == "*error*");
    +  auto expander = new Abbreviations(table);
    +  assert(expander.expand(input) == expected);
    +  assert(expander.expand("") == "");
    +  assert(expander.expand("addadd") == "*error*");
     }
     
     void main()
     {
    -	import std.stdio:writeln;
    +  import std.stdio:writeln;
     
    -	writeln("Input : ", input);
    -	writeln("Output: ", new Abbreviations(table).expand(input));
    +  writeln("Input : ", input);
    +  writeln("Output: ", new Abbreviations(table).expand(input));
     }
    diff --git a/Task/Abbreviations-simple/Fortran/abbreviations-simple.f b/Task/Abbreviations-simple/Fortran/abbreviations-simple.f
    new file mode 100644
    index 0000000000..996e18f840
    --- /dev/null
    +++ b/Task/Abbreviations-simple/Fortran/abbreviations-simple.f
    @@ -0,0 +1,184 @@
    +!
    +! Abbreviations, simple
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +! VSI Fortran does not/not yet compile this code.
    +! U.B., December 2025
    +!==============================================================================
    +program AbbrSimple
    +
    +  implicit none
    +
    +  integer, parameter  :: lenCmd = 10
    +  character (len=*), parameter  :: cmdTable =  &
    +   'add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 '&
    +   'compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate '&
    +   '3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 '&
    +   'forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load '&
    +   'locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 '&
    +   'msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 '&
    +   'refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left '&
    +   '2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 '
    +
    +
    +  character (len=*), parameter  :: userCmds  = &
    +   ' riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin'
    +
    +  character (len=*), parameter :: invalid = '*error*'
    +
    +  character (len=len(cmdTable))   :: upcaseCmdTable
    +  character (len=len(userCmds))   :: upcaseUserCmds
    +  character (len=lenCmd) :: parsedCmd
    +  character (len=lenCmd), allocatable :: allCmd (:), allUpcaseCmd(:)
    +  integer, allocatable  :: minLength (:)
    +
    +  character (len=lenCmd)  inputCmd(10), upcaseInputCmd(10)    ! 10 counted manually.
    +
    +  integer :: ip1, ip2
    +  integer :: ii, l, la, nSpaces
    +
    +  ! Prepare command table to UPPER CASE for case-blind compare
    +  ! count spaces so we get an idea how many commands there are in total.
    +
    +  nSpaces = 0
    +  do ii=1, len(cmdTable)
    +    upcaseCmdTable (ii:ii) = toupper (cmdTable (ii:ii))
    +    if (upcaseCmdTable (ii:ii) .eq. ' ') nSpaces = nSpaces + 1
    +  end do
    +
    +  ! Also, have all user commands in UPCASE
    +  do ii=1, len(userCmds)
    +    upcaseUserCmds (ii:ii) = toupper (userCmds (ii:ii))
    +  end do
    +
    +  ! make space for the array with all commands bioth upper and lower case.
    +  allocate (character(len=lenCmd) :: allCmd (nSpaces+1))           ! might be more than needed bc superfluous spaces
    +  allocate (character(len=lenCmd) :: allUpcaseCmd(nSpaces+1))
    +  allocate (integer :: minLength (nSpaces+1))
    +
    +  ! Prepare lists of allowed commands and input commands
    +  call tokenize (cmdTable, upcaseCmdTable, allCmd,allUpcaseCmd, minLength)
    +  call tokenize (userCmds, upcaseUserCmds, inputCmd, upcaseInputCmd) ! 5th arg is optional
    +
    +  ! As first output line, print user input
    +  write (*, '("Input:  ", 10(A10,x))') (inputCmd(ip1), ip1=1, size(inputCmd))
    +  write (*, '("Parsed: ")', advance='no')
    +  ! Parse all user input commands
    +  do ip1 = 1, size(inputCmd)
    +    l = len_trim (inputCmd(ip1))
    +    parsedCmd = invalid
    +    do ip2 = 1, size(allCmd)
    +      la =len_trim(allCmd(ip2))
    +      if (la .ge. l) then           ! input is possible abbreviation of this command
    +        ! Case blind comparison
    +        if (allUpcaseCmd(ip2)(:l) .eq. upcaseInputCmd (ip1) (:l))  then
    +          ! at least this input cmd is a short form of this full command.
    +          ! But is it valid?
    +          if (minLength(ip2) .gt. l) then
    +            cycle     ! input is shorter than required minimum length,  try next command
    +          endif
    +        else
    +          cycle       ! input does not match command
    +        endif
    +        ! Here we know that input an abbreviation of command,
    +        ! and that it is not too short
    +        parsedCmd = allUpcaseCmd (ip2)  ! We have a result
    +        exit                            ! no need to check input against following commands
    +      else
    +        ! input is longer than this command, nothing to do.
    +      end if
    +    end do
    +    ! here we found the valid command, or the parsed value is still
    +    write (*, '(A10,X)', advance='no')  parsedCmd
    +  end do
    +  write (*,*)         ! Terminate output line.
    +
    +contains
    +
    +  ! ======================================================================================
    +  ! Divide a string of words separated by blanks into an array of the words without blanks
    +  ! ======================================================================================
    +  subroutine tokenize (tokenString, upCaseString, retList, upcaseRetList, minLength  )
    +
    +  character (len=*), intent(in) :: tokenString, upcaseString            ! input "as is" and "upcase"
    +  character (len=lencmd), intent(out) :: retList(*), upcaseRetList(*)   ! Result "as is" and "Upcase"
    +  integer, intent(out), optional :: minLength(*)                        ! Minimum lengths of commands
    +  integer :: ip1, ip2                                                   ! pointers into tokenString
    +  integer :: nTokens                                                    ! Counter forisolated words
    +  integer :: lstr                                                       ! Length of the tokenString
    +
    +  ip1 = 1
    +  nTokens = 0
    +  lstr = len_trim (tokenString)
    +  ! Expect keyword first, then an optional number.
    +   do while (ip1 .le. lstr)
    +    ! First scan for a command
    +    do while (ip1 .le. lstr .and. tokenString (ip1:ip1) .eq. ' ')  ! Skip space(s)
    +      ip1 = ip1 + 1
    +    end do
    +
    +    if (ip1 .le. lstr) then                                    ! still inside Line?
    +      ip2 = ip1
    +      ! First expect keyword
    +      do while (ip2 .le. lstr .and. tokenString (ip2:ip2) .ne. ' ')  ! Find end of current word
    +        ip2 = ip2 + 1
    +      end do
    +      ip2 = ip2 - 1     ! set to the true end of the new command, not one behind the next keyword
    +      nTokens = nTokens + 1
    +
    +      retList (nTokens) = tokenString (ip1:ip2)
    +      upcaseRetList (nTokens) = upcaseString (ip1:ip2)
    +
    +      ! Now go look for the number
    +      ip1 = ip2 + 1                   ! prepare to find start of next text (numeric or not)
    +      if (ip1 .le. lstr) then         ! Still not past the end of tokenString?
    +        do while (ip1 .le. lstr .and. tokenString (ip1:ip1) .eq. ' ')  ! Skip space(s)
    +          ip1 = ip1 + 1
    +        end do
    +        if (isDigit (tokenString (ip1:ip1))) then
    +          if (present (minLength)) then
    +            ip2 = ip1
    +            read (tokenString (ip1:), *)  minLength (nTokens)
    +            do while (ip2 .le. lstr .and. isDigit (tokenString(ip2:ip2)) )  ! Find end of current Number
    +              ip2 = ip2 + 1
    +            end do
    +            ip1 = ip2         ! prepare for next text search. ip2 is already behind the number.
    +          endif
    +        endif
    +      endif
    +    endif
    +  end do
    +
    +  end subroutine tokenize
    +
    +  ! =========================================================
    +  ! Convert a character c to UPPER CASE, if its in lower case.
    +  ! =========================================================
    +
    +  function toupper (c) result (U)
    +  character, intent(in) :: c        ! input
    +  character :: U                    ! output
    +  integer :: ix                     ! Helper: index of c in alphabet
    +
    +  Character(26), Parameter :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    +  Character(26), Parameter :: low = 'abcdefghijklmnopqrstuvwxyz'
    +
    +  ix = index (low, c)      ! find c in lower case alphabet
    +  if (ix .gt. 0) then      ! c found: it is in lower case
    +    U = cap (ix:ix)        !    ...and needs conversion
    +  else                     ! c not found, so is already in upper case,
    +    U = c                  !     ...or it is not a letter. Just copy to result.
    +  endif
    +  end function toupper
    +
    +
    +  ! ==========================================================
    +  ! Returns .true. if input character c is in interval [0...9]
    +  ! ==========================================================
    +  function isDigit (c) result (YN)
    +  character, intent(in) :: c
    +  logical :: YN
    +  YN = (index ('0123456789', c) .ne. 0)
    +  end function isDigit
    +
    +end program AbbrSimple
    diff --git a/Task/Abbreviations-simple/Go/abbreviations-simple.go b/Task/Abbreviations-simple/Go/abbreviations-simple.go
    index d5cac0b13b..0f3e4d6af0 100644
    --- a/Task/Abbreviations-simple/Go/abbreviations-simple.go
    +++ b/Task/Abbreviations-simple/Go/abbreviations-simple.go
    @@ -1,90 +1,90 @@
     package main
     
     import (
    -	"io"
    -	"os"
    -	"strconv"
    -	"strings"
    -	"text/tabwriter"
    +  "io"
    +  "os"
    +  "strconv"
    +  "strings"
    +  "text/tabwriter"
     )
     
     func readTable(table string) ([]string, []int) {
    -	fields := strings.Fields(table)
    -	var commands []string
    -	var minLens []int
    +  fields := strings.Fields(table)
    +  var commands []string
    +  var minLens []int
     
    -	for i, max := 0, len(fields); i < max; {
    -		cmd := fields[i]
    -		cmdLen := len(cmd)
    -		i++
    +  for i, max := 0, len(fields); i < max; {
    +    cmd := fields[i]
    +    cmdLen := len(cmd)
    +    i++
     
    -		if i < max {
    -			num, err := strconv.Atoi(fields[i])
    -			if err == nil && 1 <= num && num < cmdLen {
    -				cmdLen = num
    -				i++
    -			}
    -		}
    +    if i < max {
    +      num, err := strconv.Atoi(fields[i])
    +      if err == nil && 1 <= num && num < cmdLen {
    +        cmdLen = num
    +        i++
    +      }
    +    }
     
    -		commands = append(commands, cmd)
    -		minLens = append(minLens, cmdLen)
    -	}
    +    commands = append(commands, cmd)
    +    minLens = append(minLens, cmdLen)
    +  }
     
    -	return commands, minLens
    +  return commands, minLens
     }
     
     func validateCommands(commands []string, minLens []int, words []string) []string {
    -	var results []string
    -	for _, word := range words {
    -		matchFound := false
    -		wlen := len(word)
    -		for i, command := range commands {
    -			if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
    -				continue
    -			}
    -			c := strings.ToUpper(command)
    -			w := strings.ToUpper(word)
    -			if strings.HasPrefix(c, w) {
    -				results = append(results, c)
    -				matchFound = true
    -				break
    -			}
    -		}
    -		if !matchFound {
    -			results = append(results, "*error*")
    -		}
    -	}
    -	return results
    +  var results []string
    +  for _, word := range words {
    +    matchFound := false
    +    wlen := len(word)
    +    for i, command := range commands {
    +      if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) {
    +        continue
    +      }
    +      c := strings.ToUpper(command)
    +      w := strings.ToUpper(word)
    +      if strings.HasPrefix(c, w) {
    +        results = append(results, c)
    +        matchFound = true
    +        break
    +      }
    +    }
    +    if !matchFound {
    +      results = append(results, "*error*")
    +    }
    +  }
    +  return results
     }
     
     func printResults(words []string, results []string) {
    -	wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
    -	io.WriteString(wr, "user words:")
    -	for _, word := range words {
    -		io.WriteString(wr, "\t"+word)
    -	}
    -	io.WriteString(wr, "\n")
    -	io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
    -	wr.Flush()
    +  wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0)
    +  io.WriteString(wr, "user words:")
    +  for _, word := range words {
    +    io.WriteString(wr, "\t"+word)
    +  }
    +  io.WriteString(wr, "\n")
    +  io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n")
    +  wr.Flush()
     }
     
     func main() {
    -	const table = "" +
    -		"add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 " +
    -		"compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate " +
    -		"3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
    -		"forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load " +
    -		"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 " +
    -		"msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 " +
    -		"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
    -		"2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 "
    +  const table = "" +
    +    "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 " +
    +    "compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate " +
    +    "3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " +
    +    "forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load " +
    +    "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 " +
    +    "msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 " +
    +    "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " +
    +    "2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 "
     
    -	const sentence = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    +  const sentence = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
     
    -	commands, minLens := readTable(table)
    -	words := strings.Fields(sentence)
    +  commands, minLens := readTable(table)
    +  words := strings.Fields(sentence)
     
    -	results := validateCommands(commands, minLens, words)
    +  results := validateCommands(commands, minLens, words)
     
    -	printResults(words, results)
    +  printResults(words, results)
     }
    diff --git a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-1.m2000 b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-1.m2000
    index 90d9a00bf6..cb21cfad50 100644
    --- a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-1.m2000
    +++ b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-1.m2000
    @@ -1,56 +1,56 @@
     Module Abbreviations_Simple {
    -	Function Lex {
    -		a$={add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
    -		   compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
    -		   3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
    -		   forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
    -		   locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
    -		   msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
    -		   refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
    -		   2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1
    -		}
    -		const crlftab$={
    -		}+chr$(9)
    -		
    -		Lex=Queue
    -		Word$=""
    -		dim part$()
    -		part$()=piece$(trim$(filter$(a$, crlftab$)), " ")
    -		for i=0 to len(part$())-1
    -		if part$(i)<>"" then
    -			k=val(part$(i))
    -			if k=0 then
    -				if Word$<>"" then Append Lex, Word$:=Word$
    -				Word$=ucase$(part$(i))
    -			else
    -				for j=k to len(Word$)
    -				Append Lex, left$(Word$,j):=Word$
    -				next j
    -				word$=""
    -			end if
    -		end if
    -		next i
    -		if Word$<>"" then Append Lex, Word$:=Word$
    -		=Lex
    -	}
    -	Parse$=Lambda$ Lex=Lex() (a$) -> {
    -		Dim part$()
    -		Rep$=""
    -		part$()=piece$(a$," ")
    -		if len(part$())=0 then exit
    -		for i=0 to len(part$())-1
    -		if part$(i)<>"" then
    -			if exist(Lex, ucase$(part$(i))) then
    -				Rep$+=if$(Rep$=""->"", " ")+Eval$(lex)
    -			else
    -				Rep$+=if$(Rep$=""->"", " ")+"*error*"
    -			end if
    -		end if
    -		next i
    -		=Rep$
    -	}
    -	Print Parse$("riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin")
    -	Print Parse$("riG   macro copies macr")
    -	Print Parse$("")=""
    +  Function Lex {
    +    a$={add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
    +       compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
    +       3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
    +       forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
    +       locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
    +       msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
    +       refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
    +       2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1
    +    }
    +    const crlftab$={
    +    }+chr$(9)
    +
    +    Lex=Queue
    +    Word$=""
    +    dim part$()
    +    part$()=piece$(trim$(filter$(a$, crlftab$)), " ")
    +    for i=0 to len(part$())-1
    +    if part$(i)<>"" then
    +      k=val(part$(i))
    +      if k=0 then
    +        if Word$<>"" then Append Lex, Word$:=Word$
    +        Word$=ucase$(part$(i))
    +      else
    +        for j=k to len(Word$)
    +        Append Lex, left$(Word$,j):=Word$
    +        next j
    +        word$=""
    +      end if
    +    end if
    +    next i
    +    if Word$<>"" then Append Lex, Word$:=Word$
    +    =Lex
    +  }
    +  Parse$=Lambda$ Lex=Lex() (a$) -> {
    +    Dim part$()
    +    Rep$=""
    +    part$()=piece$(a$," ")
    +    if len(part$())=0 then exit
    +    for i=0 to len(part$())-1
    +    if part$(i)<>"" then
    +      if exist(Lex, ucase$(part$(i))) then
    +        Rep$+=if$(Rep$=""->"", " ")+Eval$(lex)
    +      else
    +        Rep$+=if$(Rep$=""->"", " ")+"*error*"
    +      end if
    +    end if
    +    next i
    +    =Rep$
    +  }
    +  Print Parse$("riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin")
    +  Print Parse$("riG   macro copies macr")
    +  Print Parse$("")=""
     }
     Abbreviations_Simple
    diff --git a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-2.m2000 b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-2.m2000
    index 7cb46266da..3572afdec0 100644
    --- a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-2.m2000
    +++ b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-2.m2000
    @@ -1,66 +1,66 @@
     Module Abbreviations_Simple_2 {
    -	Function Lex$ {
    -		a$={add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
    -		   compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
    -		   3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
    -		   forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
    -		   locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
    -		   msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
    -		   refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
    -		   2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1
    -		}
    -		const crlftab$={
    -		}+chr$(9)
    -		
    -		Lex$=""
    -		Word$=""
    -		dim part$()
    -		part$()=piece$(trim$(filter$(a$, crlftab$)), " ")
    -		for i=0 to len(part$())-1
    -		if part$(i)<>"" then
    -			k=val(part$(i))
    -			if k=0 then
    -				if Word$<>"" then Lex$+="#"+Word$+" 0"
    -				Word$=ucase$(part$(i))
    -			else
    -				Lex$+="#"+ Word$+str$(k)
    -				word$=""
    -			end if
    -		end if
    -		next i
    -		if Word$<>"" then Lex$+="#"+Word$+" 0"
    -		=Lex$
    -	}
    -	Parse$=Lambda$ Lex$=Lex$() (a$) -> {
    -		Dim part$()
    -		Rep$=""
    -		part$()=piece$(a$," ")
    -		if len(part$())=0 then exit
    -		for i=0 to len(part$())-1
    -		if part$(i)<>"" then
    -			j=1
    -			do
    -				j=instr(Lex$, "#"+ucase$(part$(i)), j)
    -				if j=0 then exit
    -				q=instr(Lex$, " ", j+1)
    -				if Val(Mid$(lex$, q,10))=0 then
    -					if Mid$(Lex$, j+1, q-j)=ucase$(part$(i))+" " then exit
    -				else.if len(part$(i))>=Val(Mid$(lex$, q,10)) then
    -					exit
    -				end if
    -				j++
    -			Always
    -			if j>0 then
    -				Rep$+=if$(Rep$=""->"", " ")+Mid$(Lex$, j+1, q-j-1)
    -			else
    -				Rep$+=if$(Rep$=""->"", " ")+"*error*"
    -			end if
    -		end if
    -		next i
    -		=Rep$
    -	}
    -	Print Parse$("riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin")
    -	Print Parse$("riG   macro copies macr")
    -	Print Parse$("")=""
    +  Function Lex$ {
    +    a$={add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
    +       compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
    +       3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
    +       forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
    +       locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
    +       msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
    +       refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
    +       2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1
    +    }
    +    const crlftab$={
    +    }+chr$(9)
    +
    +    Lex$=""
    +    Word$=""
    +    dim part$()
    +    part$()=piece$(trim$(filter$(a$, crlftab$)), " ")
    +    for i=0 to len(part$())-1
    +    if part$(i)<>"" then
    +      k=val(part$(i))
    +      if k=0 then
    +        if Word$<>"" then Lex$+="#"+Word$+" 0"
    +        Word$=ucase$(part$(i))
    +      else
    +        Lex$+="#"+ Word$+str$(k)
    +        word$=""
    +      end if
    +    end if
    +    next i
    +    if Word$<>"" then Lex$+="#"+Word$+" 0"
    +    =Lex$
    +  }
    +  Parse$=Lambda$ Lex$=Lex$() (a$) -> {
    +    Dim part$()
    +    Rep$=""
    +    part$()=piece$(a$," ")
    +    if len(part$())=0 then exit
    +    for i=0 to len(part$())-1
    +    if part$(i)<>"" then
    +      j=1
    +      do
    +        j=instr(Lex$, "#"+ucase$(part$(i)), j)
    +        if j=0 then exit
    +        q=instr(Lex$, " ", j+1)
    +        if Val(Mid$(lex$, q,10))=0 then
    +          if Mid$(Lex$, j+1, q-j)=ucase$(part$(i))+" " then exit
    +        else.if len(part$(i))>=Val(Mid$(lex$, q,10)) then
    +          exit
    +        end if
    +        j++
    +      Always
    +      if j>0 then
    +        Rep$+=if$(Rep$=""->"", " ")+Mid$(Lex$, j+1, q-j-1)
    +      else
    +        Rep$+=if$(Rep$=""->"", " ")+"*error*"
    +      end if
    +    end if
    +    next i
    +    =Rep$
    +  }
    +  Print Parse$("riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin")
    +  Print Parse$("riG   macro copies macr")
    +  Print Parse$("")=""
     }
     Abbreviations_Simple_2
    diff --git a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000 b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000
    index e710dbc3c6..856910db96 100644
    --- a/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000
    +++ b/Task/Abbreviations-simple/M2000-Interpreter/abbreviations-simple-3.m2000
    @@ -1,71 +1,71 @@
     Module Abbreviations_simple {
    -	commands=list
    -	a$="add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 "
    -	a$+="compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate "
    -	a$+="3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
    -	a$+="forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load "
    -	a$+="locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 "
    -	a$+="msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 "
    -	a$+="refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
    -	a$+="2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1"
    -	gosub cleanspaces
    -	gosub makelist
    -	if not empty then gosub processstack
    -	a$="riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    -	Print a$
    -	gosub cleanspaces
    -	gosub findresult	
    -	a$="riG   macro copies macr"
    -	Print a$
    -	gosub cleanspaces
    -	gosub findresult	
    -	End
    +  commands=list
    +  a$="add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 "
    +  a$+="compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate "
    +  a$+="3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
    +  a$+="forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load "
    +  a$+="locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 "
    +  a$+="msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 "
    +  a$+="refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
    +  a$+="2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1"
    +  gosub cleanspaces
    +  gosub makelist
    +  if not empty then gosub processstack
    +  a$="riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    +  Print a$
    +  gosub cleanspaces
    +  gosub findresult
    +  a$="riG   macro copies macr"
    +  Print a$
    +  gosub cleanspaces
    +  gosub findresult
    +  End
     processstack:
    -	Read many, word$
    -	if many>0  and many0  and many"" then data 0, ucase$(w$):w$=""
    -		end if
    -	next
    -	return
    +  let b$="", w$="", n$=""
    +  flush
    +  for i=1 to len(A$)
    +    c$=mid$(a$, i, 1)
    +    if c$~"[a-zA-Z]" then
    +      if w$="" and not empty then gosub processstack
    +      w$+=c$
    +    else.if c$~"[1-9]" then
    +      drop : push val(c$)
    +    else
    +      if w$<>"" then data 0, ucase$(w$):w$=""
    +    end if
    +  next
    +  return
     findresult:
    -	dim a$()
    -	a$()=piece$(ucase$(a$), " ")
    -	flush
    -	for i=0 to len(a$())-1
    -		if exist(commands, a$(i)) then
    -			Data eval$(commands)
    -		else
    -			Data "*error*"
    -		end if
    -	next
    -	Print Array([])#str$(" ")
    -	Return
    +  dim a$()
    +  a$()=piece$(ucase$(a$), " ")
    +  flush
    +  for i=0 to len(a$())-1
    +    if exist(commands, a$(i)) then
    +      Data eval$(commands)
    +    else
    +      Data "*error*"
    +    end if
    +  next
    +  Print Array([])#str$(" ")
    +  Return
     }
     Abbreviations_simple
    diff --git a/Task/Abbreviations-simple/Pluto/abbreviations-simple.pluto b/Task/Abbreviations-simple/Pluto/abbreviations-simple.pluto
    new file mode 100644
    index 0000000000..5354c7545d
    --- /dev/null
    +++ b/Task/Abbreviations-simple/Pluto/abbreviations-simple.pluto
    @@ -0,0 +1,102 @@
    +do  -- Abbreviatiions Simple - expand command name abbreviations
    +
    +    -- returns the table of space delimited words in s
    +    local function getWords( s : string ) : table
    +        local t, cmds, w = s, {}, s
    +        while t:contains( " " ) do
    +            w, t = t:partition( " " )
    +            if w != "" then
    +                cmds[ # cmds + 1 ] = w
    +            end
    +        end
    +        if t != "" then
    +            cmds[ # cmds + 1 ] = t
    +        end
    +        return cmds
    +   end
    +
    +   local commandStrings
    +       = "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3"
    +      .. " compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate"
    +      .. " 3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2"
    +      .. " forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load"
    +      .. " locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2"
    +      .. " msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3"
    +      .. " refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left"
    +      .. " 2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1"
    +
    +    local function expandEasyAbbreviations( cmds : string, input : string ) : table
    +        local cmdTable, inputTable, outputTable = getWords( cmds ), getWords( input ), {}
    +
    +        local function isCommand( cmd : string, word : string ) : boolean
    +            local result, uCmd, uWord = false, cmd:upper(), word:upper()
    +            if # cmd >= # word then                 -- word is not longer than the command
    +                if uCmd == uWord then   -- the word is the command
    +                    result = true
    +                else                                -- word is shorter than the command
    +                    local ab = cmd:gsub( "%l", "" ) -- remove lowercase
    +                    if # ab <= # word then          -- the minimum abbreviation isn't longer than the word
    +                        result = uWord == uCmd:sub( 1, # word )
    +                    end
    +                end
    +            end
    +            return result
    +        end
    +
    +        for i = 1, # inputTable do
    +            local w, u = inputTable[ i ], "*error*"
    +            for c = 1, # cmdTable do
    +                if isCommand( cmdTable[ c ], w ) then
    +                    u = cmdTable[ c ]:upper()
    +                    break
    +                end
    +            end
    +            outputTable[ # outputTable + 1 ] = u
    +        end
    +        return { inputTable, outputTable }
    +    end
    +
    +    local function printExpansion( expansion : table )
    +        local fmt, input, output = {}, expansion[ 1 ], expansion[ 2 ]
    +        for i, v in ipairs( output ) do
    +            fmt[ i ] = " %" .. # v .. "s"
    +        end
    +        io.write( "Input: " )
    +        for i, v in ipairs( input ) do
    +            io.write( string.format( fmt[ i ], v ) )
    +        end
    +        io.write( "\nOutput:" )
    +        for i, v in ipairs( output ) do
    +            io.write( string.format( fmt[ i ], v ) )
    +        end
    +        io.write( "\n" )
    +    end
    +
    +    -- maps a "simple" format command list to "easy" format
    +    local function simpleToEasyFormat( cmds : string ) : string
    +        local words  = getWords( cmds )
    +        local wPos, wMax, easy = 1, # words, ""
    +        while wPos <= wMax do
    +            local w = words[ wPos ]
    +            local lenStr  = if wPos == wMax then "" else words[ wPos + 1 ] end
    +            if not lenStr:match( "^%d+$" ) then
    +                easy ..= " " .. w:upper()
    +            else
    +                -- have a minimum length
    +                local len  = tonumber( lenStr )
    +                easy ..= " " .. w:sub( 1, len ):upper()
    +                if len < # w then easy ..= w:sub( len + 1, -1 ):lower() end
    +                ++ wPos
    +            end
    +            ++ wPos
    +        end
    +        return easy
    +    end
    +
    +    printExpansion( expandEasyAbbreviations( simpleToEasyFormat( commandStrings )
    +                                           , (  "riG   rePEAT copies  put mo   rest    "
    +                                             .. "types   fup.    6       poweRin"
    +                                             )
    +                                           )
    +                  )
    +end
    diff --git a/Task/Abbreviations-simple/Rebol/abbreviations-simple.rebol b/Task/Abbreviations-simple/Rebol/abbreviations-simple.rebol
    new file mode 100644
    index 0000000000..4a08df3f58
    --- /dev/null
    +++ b/Task/Abbreviations-simple/Rebol/abbreviations-simple.rebol
    @@ -0,0 +1,66 @@
    +Rebol [
    +    title: "Rosetta code: Abbreviations, simple"
    +    file:  %Abbreviations,_simple.r3
    +    url:   https://rosettacode.org/wiki/Abbreviations,_simple
    +]
    +
    +find-abbreviation-lengths: function [
    +    "Find minimal abbreviation length for each command"
    +    text [string!]
    +][
    +    result: make map! []
    +    parse transcode text [
    +        some [
    +             set cmd: word! (cmd: form cmd)
    +            [set len: integer! | (len: length? cmd)]
    +            (result/:cmd: len)
    +        ]
    +    ]
    +    result
    +]
    +
    +build-abbreviations-table: function [
    +    "Expand each command into all valid abbreviations"
    +    cmd-lengths [map!]
    +][
    +    result: make map! []
    +    foreach [cmd min-len] cmd-lengths [
    +        cmd-up: uppercase copy cmd
    +        ;; step down from full length to min-len
    +        for i length? cmd min-len -1 [
    +            abbr: lowercase copy/part cmd i
    +            result/:abbr: cmd-up
    +        ]
    +    ]
    +    result
    +]
    +
    +split-commands: function/with [commands [string!]][
    +    out: copy []
    +    parse commands [
    +        any [any delimit copy cmd: some chars (append out cmd)]
    +    ]
    +    out
    +][
    +    delimit: charset " ^-^/"
    +    chars: complement delimit
    +]
    +
    +abbrevs: build-abbreviations-table find-abbreviation-lengths {
    +   add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
    +   compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
    +   3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2
    +   forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load
    +   locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2
    +   msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3
    +   refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left
    +   2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1}
    +
    +
    +inputs: split-commands {
    +   riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin}
    +
    +foreach cmd inputs [
    +    full: any [abbrevs/:cmd "*error*"]
    +    print [pad cmd 10 '-> full]
    +]
    diff --git a/Task/Abbreviations-simple/SNOBOL4/abbreviations-simple.sno b/Task/Abbreviations-simple/SNOBOL4/abbreviations-simple.sno
    index 47e5e52dde..5c156c5349 100644
    --- a/Task/Abbreviations-simple/SNOBOL4/abbreviations-simple.sno
    +++ b/Task/Abbreviations-simple/SNOBOL4/abbreviations-simple.sno
    @@ -3,7 +3,7 @@
     * Description: Abbreviations, simple
     * Comment: Tested using the Spitbol for Linux version of SNOBOL4
     
    -	commands =
    +  commands =
     +   "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 "
     +   "compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate "
     +   "3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "
    @@ -13,49 +13,49 @@
     +   "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "
     +   "2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 "
     
    -	commands = replace(commands,&lcase,&ucase)
    -	numerals = '0123456789'
    +  commands = replace(commands,&lcase,&ucase)
    +  numerals = '0123456789'
     
     
     * Function filltable will fill the command abbreviations table
    -	define("filltable(s,n)slen,i")
    -		ct = table(300, ,"*error*") :f(errr);* command abbreviations table
    -	:(filltable_end)
    +  define("filltable(s,n)slen,i")
    +    ct = table(300, ,"*error*") :f(errr);* command abbreviations table
    +  :(filltable_end)
     filltable
    -	slen = size(s)
    -	ct[s] = s
    -	eq(n,slen) :s(filltable3)
    -	i = n - 1
    +  slen = size(s)
    +  ct[s] = s
    +  eq(n,slen) :s(filltable3)
    +  i = n - 1
     filltable2
    -	i = lt(i,slen - 1) i + 1 :f(filltable3)
    -	ct[substr(s,1,i)] = s
    -	:(filltable2)
    +  i = lt(i,slen - 1) i + 1 :f(filltable3)
    +  ct[substr(s,1,i)] = s
    +  :(filltable2)
     filltable3
    -	filltable = ""
    -	:(return)
    +  filltable = ""
    +  :(return)
     filltable_end
     
     
     x0
     * Populate command abbreviations table
    -	commands ? (span(' ') | "") breakx(&ucase) span(&ucase) . c
    -+		span(' ') (span(numerals) | "") . ablen = "" :f(x1)
    -	ablen = ident(ablen) size(c)
    -	ret = filltable(c,ablen)
    +  commands ? (span(' ') | "") breakx(&ucase) span(&ucase) . c
    ++   span(' ') (span(numerals) | "") . ablen = "" :f(x1)
    +  ablen = ident(ablen) size(c)
    +  ret = filltable(c,ablen)
         :(x0)
     x1
     * Process user string
    -	userstring = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    -	output = "Original user string:"
    -	output = userstring
    -	userstring = replace(userstring,&lcase,&ucase)
    +  userstring = "riG   rePEAT copies  put mo   rest    types   fup.    6       poweRin"
    +  output = "Original user string:"
    +  output = userstring
    +  userstring = replace(userstring,&lcase,&ucase)
     x2
    -	userstring ? (span(' ') | "") (break(' ') | (len(1) rem)) . c = "" :f(x3)
    -	user_commands = (gt(size(user_commands),0) user_commands ' ' ct[c], ct[c])
    -	:(x2)
    +  userstring ? (span(' ') | "") (break(' ') | (len(1) rem)) . c = "" :f(x3)
    +  user_commands = (gt(size(user_commands),0) user_commands ' ' ct[c], ct[c])
    +  :(x2)
     x3
    -	output = ""
    -	output = "User string with abbreviations expanded:"
    -	output = user_commands
    +  output = ""
    +  output = "User string with abbreviations expanded:"
    +  output = user_commands
     
     END
    diff --git a/Task/Abbreviations-simple/VBScript/abbreviations-simple.vbs b/Task/Abbreviations-simple/VBScript/abbreviations-simple.vbs
    new file mode 100644
    index 0000000000..23328381b6
    --- /dev/null
    +++ b/Task/Abbreviations-simple/VBScript/abbreviations-simple.vbs
    @@ -0,0 +1,88 @@
    +option explicit
    +
    +function iif(c,t,f) if c then iif=t else iif=f end if: end function
    +function usrin(pr)  wscript.stdout.write vbcrlf &pr &": ":usrin= wscript.stdin.readline:end function
    +
    +sub do_abbrev
    +  dim j, sm,n,n0,a
    +  for each j in m
    +    sm=trim(lcase(j.submatches(0)))
    +    n0=iif (j.submatches(1)="",1,  j.submatches(1))
    +    n=1
    +    do
    +      a=left(sm,n)
    +      if not d.exists(a)  then
    +        d.add a,sm
    +      else
    +        if len(a)=len(sm) then
    +           d(a)=sm
    +        elseif len(d(a))>len(a) then
    +          d(a)=null
    +        end if
    +      end if
    +      n=n+1
    +    loop until n>len(sm)
    +  next
    +end sub
    +'output sorted
    +
    +sub display
    +  dim d2,k,j,kk,mm
    +  set d2=createobject("Scripting.dictionary")
    +  for each k in d
    +      kk=d(k)
    +    if not isnull(kk) then
    +     if not d2.exists(kk) then
    +       d2.add kk,k
    +     else
    +       d2(kk)= d2(kk) & " " & k
    +     end if
    +     end if
    +  next
    +  for each j in m
    +    mm=trim(lcase(j.submatches(0)))
    +    wscript.echo left(mm&space(15),15),d2(mm)
    +  next
    +  wscript.echo
    +  set d2=nothing
    +end sub
    +
    +sub test
    +  wscript.echo vbcrlf&"test:"
    +  dim a,i,k,s1
    +  do
    +    s1= lcase(usrin("Command?"))
    +    if trim(s1)="" then wscript.quit
    +    a=split(trim(s1)," ")
    +    for i=0 to ubound(a)
    +      if a(i)<>"" then
    +        wscript.stdout.write iif (d.exists(a(i)), ucase(d(a(i)))," **ERROR**")& " "
    +      end if
    +    next
    +  loop
    +end sub
    +
    +'main program
    +dim s:s=_
    +   "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3 "&_
    +   "compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate "&_
    +   "3 xEdit 1 expand 3 extract 3  find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 "&_
    +   "forward 2  get  help 1 hexType 4  input 1 powerInput 3  join 1 split 2 spltJOIN load "&_
    +   "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2  macro  merge 2 modify 3 move 2 "&_
    +   "msg  next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit  read recover 3 "&_
    +   "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left "&_
    +   "2  save  set  shift 2  si  sort  sos  stack 3 status 4 top  transfer 3  type 1  up 1 "
    +dim m,d
    +
    +'use regexp to separate input
    +with new regexp
    + .pattern="([a-z]+?)\s+(\d?)"
    + .global=true
    + .ignorecase=true
    + set m=.execute(s)
    +end with
    +
    +set d=createobject("Scripting.dictionary")
    +do_abbrev
    +'display
    +test
    diff --git a/Task/Abbreviations-simple/Zkl/abbreviations-simple.zkl b/Task/Abbreviations-simple/Zkl/abbreviations-simple.zkl
    index dde5b77dd6..107e7dba15 100644
    --- a/Task/Abbreviations-simple/Zkl/abbreviations-simple.zkl
    +++ b/Task/Abbreviations-simple/Zkl/abbreviations-simple.zkl
    @@ -1,4 +1,4 @@
    -commands:=Data(0,String,	// "add\01\0alter\0..."
    +commands:=Data(0,String,  // "add\01\0alter\0..."
     #<<<
     "add 1  alter 3  backup 2  bottom 1  Cappend 2  change 1  Schange  Cinsert 2  Clast 3
     compress 4 copy 2 count 3 Coverlay 3 cursor 3  delete 3 Cdelete 2  down 1  duplicate
    @@ -16,7 +16,7 @@ n:=0; while(n=szs.find(n,99999)) return(c);
           n+=c.len();
    diff --git a/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-1.adb b/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-1.adb
    new file mode 100644
    index 0000000000..2683729e0b
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-1.adb
    @@ -0,0 +1,15 @@
    +-- Works with Ada 2012
    +
    +package Abelian_Sandpile is
    +   Limit : constant Integer := 4;
    +
    +   type Sandpile is array (0 .. 2, 0 .. 2) of Natural with
    +      Default_Component_Value => 0;
    +
    +   procedure Stabalize (Pile : in out Sandpile);
    +   function Is_Stable (Pile : in Sandpile) return Boolean;
    +   procedure Topple (Pile : in out Sandpile);
    +   function "+" (Left, Right : Sandpile) return Sandpile;
    +   procedure Print(PIle : in Sandpile);
    +
    +end Abelian_Sandpile;
    diff --git a/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-2.adb b/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-2.adb
    new file mode 100644
    index 0000000000..8e38a56088
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-2.adb
    @@ -0,0 +1,85 @@
    +with Ada.Text_Io; use Ada.Text_IO;
    +
    +package body Abelian_Sandpile is
    +
    +   ---------------
    +   -- Stabalize --
    +   ---------------
    +
    +   procedure Stabalize (Pile : in out Sandpile) is
    +   begin
    +      while not Is_Stable(Pile) loop
    +         Topple(Pile);
    +      end loop;
    +   end Stabalize;
    +
    +   ---------------
    +   -- Is_Stable --
    +   ---------------
    +
    +   function Is_Stable (Pile : in Sandpile) return Boolean is
    +   begin
    +     return (for all E of Pile => E < Limit);
    +   end Is_Stable;
    +
    +   ------------
    +   -- Topple --
    +   ------------
    +
    +   procedure Topple (Pile : in out Sandpile) is
    +   begin
    +      outer:
    +      for Row in Pile'Range(1) loop
    +         for Col in Pile'Range(2) loop
    +            if Pile(Row, Col) >= Limit then
    +               Pile(Row, Col) := Pile(Row, Col) - Limit;
    +               if Row > 0 then
    +                  Pile(Row - 1, Col) := Pile(Row -1, Col) + 1;
    +               end if;
    +               if Row < Pile'Last(1) then
    +                  Pile(Row + 1, Col) := Pile(Row + 1, Col) + 1;
    +               end if;
    +               if Col > 0 then
    +                  Pile(Row, Col - 1) := Pile(Row, Col - 1) + 1;
    +               end if;
    +               if Col < Pile'Last(2) then
    +                  Pile(Row, Col + 1) := Pile(Row, Col + 1) + 1;
    +               end if;
    +
    +               exit outer;
    +            end if;
    +         end loop;
    +      end loop outer;
    +   end Topple;
    +
    +   ---------
    +   -- "+" --
    +   ---------
    +
    +   function "+" (Left, Right : Sandpile) return Sandpile is
    +      Result : Sandpile;
    +   begin
    +      for I in Sandpile'Range(1) loop
    +         for J in Sandpile'Range(2) loop
    +            Result(I, J) := Left(I, J) + Right(I, J);
    +         end loop;
    +      end loop;
    +      Stabalize(Result);
    +      return Result;
    +   end "+";
    +
    +   -----------
    +   -- Print --
    +   -----------
    +
    +   procedure Print(Pile : in Sandpile) is
    +   begin
    +      for row in Pile'Range(1) loop
    +         for col in Pile'Range(2) loop
    +            Put(Integer'Image(Pile(row, col)));
    +         end loop;
    +         New_Line;
    +      end loop;
    +      New_Line;
    +   end Print;
    +end Abelian_Sandpile;
    diff --git a/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-3.adb b/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-3.adb
    new file mode 100644
    index 0000000000..350d3736a7
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model-Identity/Ada/abelian-sandpile-model-identity-3.adb
    @@ -0,0 +1,46 @@
    +with Ada.Text_IO;      use Ada.Text_IO;
    +with Abelian_Sandpile; use Abelian_Sandpile;
    +
    +procedure Main is
    +   sp    : Sandpile := ((4, 3, 3), (3, 1, 2), (0, 2, 3));
    +   s1    : Sandpile := ((1, 2, 0), (2, 1, 1), (0, 1, 3));
    +   s2    : Sandpile := ((2, 1, 3), (1, 0, 1), (0, 1, 0));
    +   s3    : Sandpile := ((3, 3, 3), (3, 3, 3), (3, 3, 3));
    +   s3_id : Sandpile := ((2, 1, 2), (1, 0, 1), (2, 1, 2));
    +   sum1  : Sandpile := s1 + s2;
    +   sum2  : Sandpile := s2 + s1;
    +   sum3  : Sandpile := s3 + s3_id;
    +   sum4  : Sandpile := s3_id + s3_id;
    +
    +begin
    +   Put_Line ("Avalanche:");
    +   while not Is_Stable (sp) loop
    +      Print (sp);
    +      Put_Line ("stable? " & Boolean'Image (Is_Stable (sp)));
    +      New_Line;
    +      Topple (sp);
    +   end loop;
    +   Print (sp);
    +   Put_Line ("stable? " & Boolean'Image (Is_Stable (sp)));
    +   New_Line;
    +
    +   Put_Line ("Commutivity:");
    +   Put_Line ("s1 + s2 equals s2 + s2? " & Boolean'Image (sum1 = sum2));
    +   New_Line;
    +   Put_Line ("S1 : s2 =");
    +   Print (sum1);
    +   New_Line;
    +   Put_Line ("s2 + s1 =");
    +   Print (sum2);
    +   New_Line;
    +
    +   Put_Line ("Identity:");
    +   Put_Line ("s3 + s3_id equals s3? " & Boolean'Image (sum3 = s3));
    +   Put_Line ("s3_id + s3_id equals s3_id? " & Boolean'Image (sum4 = s3_id));
    +   New_Line;
    +   Put_Line ("s3 + s3_id =");
    +   Print (sum3);
    +   Put_Line ("s3_id + s3_id =");
    +   Print (sum4);
    +
    +end Main;
    diff --git a/Task/Abelian-sandpile-model-Identity/Crystal/abelian-sandpile-model-identity.cr b/Task/Abelian-sandpile-model-Identity/Crystal/abelian-sandpile-model-identity.cr
    new file mode 100644
    index 0000000000..f768a9132b
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model-Identity/Crystal/abelian-sandpile-model-identity.cr
    @@ -0,0 +1,86 @@
    +class Sandpile
    +  getter pile   : Array(Array(Int32))
    +  getter width  : Int32
    +  getter height : Int32
    +
    +  def initialize (values : Array(Array(Int32)))
    +    @pile = values.map {|row| row.dup }
    +    @width = @pile[0].size
    +    @height = @pile.size
    +    stabilize
    +  end
    +
    +  def initialize (@width, @height)
    +    @pile = Array.new(@height) { Array.new(@width, 0) }
    +  end
    +
    +  def stabilize
    +    pile, h, w = @pile, @width, @height
    +    loop do
    +      done = true
    +      (0...h).each do |r|
    +        (0...w).each do |c|
    +          stack = pile[r][c]
    +          if stack >= 4
    +            portion = stack // 4
    +            pile[r][c] %= 4
    +            (pile[r][c-1] += portion)   if c-1 >= 0
    +            (pile[r][c+1] += portion)   if c+1 < width
    +            (pile[r-1][c] += portion)   if r-1 >= 0
    +            (pile[r+1][c] += portion)   if r+1 < height
    +            done = false
    +          end
    +        end
    +      end
    +      break if done
    +    end
    +    @pile = pile
    +    self
    +  end
    +
    +  def check_compatible (other)
    +    raise "incompatible sandpiles" unless other.height == height &&
    +                                          other.width  == width
    +  end
    +
    +  def + (other)
    +    check_compatible(other)
    +    new_pile = @pile.zip(other.@pile).map {|(row1, row2)|
    +      row1.zip(row2).map {|a, b| a + b }
    +    }
    +    Sandpile.new(new_pile)
    +  end
    +end
    +
    +def print_row (items)
    +  heights = items.map {|item| item.is_a?(Sandpile) ? item.height : 1 }
    +  lines = heights.max
    +  (0...lines).each do |i|
    +    items.each do |item|
    +      if item.is_a?(Sandpile)
    +        print item.pile[i].join(" ")
    +      elsif i == lines // 2
    +        print item
    +      else
    +        print " "*item.size
    +      end
    +    end
    +    puts
    +  end
    +end
    +
    +
    +s1 = Sandpile.new([[1,2,0],[2,1,1],[0,1,3]])
    +s2 = Sandpile.new([[2,1,3],[1,0,1],[0,1,0]])
    +s3 = Sandpile.new([[3,3,3],[3,3,3],[3,3,3]])
    +s3_id = Sandpile.new([[2,1,2],[1,0,1],[2,1,2]])
    +
    +print_row ["s1 + s2 = s2 + s1  =   ", s1, " + ", s2, " = ", s1 + s2,
    +           "  =  ", s2, " + ", s1, " = ", s2 + s1]
    +
    +puts
    +print_row ["s3 + s3_id = s3  =  ",
    +           s3, " + ", s3_id, " = ", s3 + s3_id]
    +puts
    +print_row ["s3_id + s3_id = s3_id  =  ",
    +           s3_id, " + ", s3_id, " = ", s3_id + s3_id]
    diff --git a/Task/Abelian-sandpile-model-Identity/Fortran/abelian-sandpile-model-identity.f b/Task/Abelian-sandpile-model-Identity/Fortran/abelian-sandpile-model-identity.f
    new file mode 100644
    index 0000000000..158267f648
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model-Identity/Fortran/abelian-sandpile-model-identity.f
    @@ -0,0 +1,223 @@
    +!
    +! Abelian sandpile model/Identity
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.04
    +!             GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0  on Kubuntu 25.04
    +!             VSI Fortran x86-64 V8.6-001                   on OpenVMS x86_64 V9.2-3
    +! No Non-standard features used, should compile on any fairly recent Fortran.
    +! U.B., September 2025
    +!
    +  program Abelian
    +  implicit none
    +
    +  integer :: av (3,3), s1(3,3), s2(3,3), s3(3,3), s3_id(3,3), result1(3,3), result2(3,3)
    +
    +  av =  reshape ( [ &       ! Start value for Avalanche
    +        4,3,3, &
    +        3,1,2, &
    +        0,2,3], shape(s3))
    +
    +  s1 =  reshape ( [ &       ! S1,s2,s3,s3_id as in task description
    +        1,2,0, &
    +        2,1,1, &
    +        0,1,3], shape(s1))
    +  s2 =  reshape ( [ &
    +        2,1,3, &
    +        1,0,1, &
    +        0,1,0], shape(s2))
    +  s3 =  reshape ( [ &
    +        3,3,3, &
    +        3,3,3, &
    +        3,3,3], shape(s3))
    +  s3_id =  reshape ( [ &
    +        2,1,2, &
    +        1,0,1, &
    +        2,1,2], shape(s3_id))
    +
    +
    +
    +  print '("Avalanche: ")'
    +  print '("---------- ")'
    +
    +  call print_it ("Start with ", av)
    +  do
    +    if (isStable (av)) then
    +      print '(A/)', 'is stable.'
    +      exit
    +    else
    +      print '(A/)', 'is not stable.'
    +    endif
    +    call topple (av)
    +    call print_it ("           ", s3)
    +  end do
    +
    +
    +  print '(///A)', 'Commutivity:'
    +  print '(A)',    '------------'
    +
    +  call print_it ('s1   =    ', s1)
    +  print *
    +  call print_it ('s2   =    ', s2)
    +  print *
    +  result1 = add(s1,s2)
    +  call print_it ('s1 + s2 = ', result1)
    +  print *
    +  result2 = add(s2,s1)
    +  call print_it ('s2 + s1 = ', result2)
    +  print *
    +
    +  if (isEqual (result1,result2))  then
    +    print '(A)', 's1 + s2 = s2 + s1 VERIFIED'
    +  else
    +    print '(A)', 's1 + s2 = s2 + s1 NOT VERIFIED'
    +  endif
    +
    +  print '(///A)', 'Identity:'
    +  print '(A)',    '---------'
    +
    +  call print_it ('s3         =    ', s3)
    +  print *
    +  call print_it ('s3_id      =    ', s3_ID)
    +  print *
    +  result1 = add (s3, s3_id)
    +  do while ( .not. isstable (result1))
    +    call topple (result1)
    +  end do
    +  call print_it ('s3 + s3_id =    ', result1)
    +  print *
    +  if (isEqual (s3,result1))  then
    +    print '(A/)', 's3 + s3_id = s3 VERIFIED'
    +  else
    +    print '(A/)', 's3 + s3_id = s3 NOT VERIFIED'
    +  endif
    +
    +  result1 = add (s3_id, s3_id)
    +  do while ( .not. isstable (result1))
    +    call topple (result1)
    +  end do
    +  call print_it ('s3_id + s3_id =    ', result1)
    +  print *
    +  if (isEqual (s3_id, result1))  then
    +    print '(A)', 's3_id + s3_id = s3_id VERIFIED'
    +  else
    +    print '(A)', 's3_id + s3_id = s3_id NOT VERIFIED'
    +  endif
    +
    +
    +
    +  contains
    +
    +
    +  ! -----------------------------------
    +  ! Check if 2 sand piles are identical
    +  ! -----------------------------------
    +  function isEqual (a,b) result (r)
    +
    +  integer, intent(in) :: a(3,3),B(3,3)
    +  integer :: ii,jj
    +  logical :: r
    +
    +  r = .false.
    +  do ii=1,3
    +    do jj=1,3
    +      if ( a(ii,jj) .ne. b(ii,jj) ) return
    +    end do
    +  end do
    +  r=.true.
    +  end function isEqual
    +
    +
    +  ! ----------------------------------------------------------
    +  ! Print sand pile contents, together with a descriptive text
    +  ! ----------------------------------------------------------
    +  subroutine print_it (text, a)
    +
    +  integer :: a (3,3)
    +
    +  character (len=*) :: text
    +  character (len=:), allocatable :: blank
    +
    +  integer :: ii, jj
    +
    +  ! create blank string with same length as text
    +  blank = text
    +  do ii=1, len (blank)
    +    blank(ii:ii) = ' '
    +  end do
    +  do jj = 1, 3                                ! three lines to print. Note: 2nd index is row, 1st is column
    +    if (jj .eq. 2) then                       ! Description in middle line
    +      write (*,'(A)', advance='no')   text
    +    else
    +      write (*,'(A)', advance='no')   blank   ! empty space to have same indent for the other lines
    +    endif
    +    do ii=1,3                                 ! then the 3 columns of this row
    +      write (*, '(i1," ")', advance='no')  a(ii,jj)
    +    end do
    +    write (*,*)                               ! terminate current line
    +  end do
    +
    +  end subroutine print_it
    +
    +
    +  ! --------------------------------
    +  ! Add the contents of 2 sand piles
    +  ! --------------------------------
    +  function add (a,b) result (c)
    +
    +  integer, intent(in) :: a (3,3),b(3,3)
    +  integer  ::c(3,3)
    +
    +  integer :: ii, jj
    +    do ii = 1, 3
    +      do jj=1,3
    +        c(ii,jj) = a(ii,jj) + b(ii,jj)
    +      end do
    +    end do
    +  end function add
    +
    +
    +  ! ----------------------------------------------
    +  ! Check if sand pile is stable (all elements <4)
    +  ! ----------------------------------------------
    +  function isStable (a) result(Yes)
    +
    +  integer, intent(in)  :: a(3,3)
    +  logical :: Yes
    +  integer :: ii, jj
    +
    +  yes = .true.
    +  do ii = 1, 3
    +    do jj=1, 3
    +      if (a(ii,jj) .gt.3) then   ! >3 means not stable.
    +        Yes = .false.
    +        return
    +      end if
    +    end do
    +  end do
    +  end function isStable
    +
    +
    +  ! ----------------------------------
    +  ! 1 cycle of toppling of a sand pile
    +  ! ----------------------------------
    +  subroutine topple (a)
    +  implicit none
    +
    +  integer, intent(inout) :: a (3,3)
    +  logical :: Yes
    +  integer :: ii, jj
    +
    +  do jj = 1, 3                        ! row is second index
    +    do ii=1,3                         ! col is 1st index
    +      if (a(ii,jj) .gt.3) then
    +        a(ii,jj) = a(ii,jj) - 4
    +        if (ii .gt. 1) a(ii-1,jj) = a(ii-1,jj) + 1
    +        if (ii .lt. 3) a(ii+1,jj) = a(ii+1,jj) + 1
    +        if (jj .gt. 1) a(ii,jj-1) = a(ii,jj-1) + 1
    +        if (jj .lt. 3) a(ii,jj+1) = a(ii,jj+1) + 1
    +        return
    +      end if
    +    end do
    +  end do
    +  end subroutine topple
    +
    +  end program Abelian
    diff --git a/Task/Abelian-sandpile-model-Identity/Rebol/abelian-sandpile-model-identity.rebol b/Task/Abelian-sandpile-model-Identity/Rebol/abelian-sandpile-model-identity.rebol
    new file mode 100644
    index 0000000000..f3014baa6e
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model-Identity/Rebol/abelian-sandpile-model-identity.rebol
    @@ -0,0 +1,105 @@
    +Rebol [
    +    title: "Rosetta code: Abelian sandpile model/Identity"
    +    file:  %Abelian_sandpile_model-Identitys.r3
    +    url:   https://rosettacode.org/wiki/Abelian_sandpile_model/Identity
    +    note:  "Based on Red language solution"
    +]
    +sadd: context [
    +    ;; 'comb' adds two 3x3 piles cell by cell, then validates the result
    +    comb: function [pile1 [series!] pile2 [series!]] [
    +        ;; Loop over rows 1 to 3
    +        repeat r 3 [
    +            ;; Loop over columns 1 to 3
    +            repeat c 3 [
    +                ;; Add corresponding cell values from pile1 to pile2
    +                pile2/:r/:c: pile2/:r/:c + pile1/:r/:c
    +            ]
    +        ]
    +        ;; Validate and stabilize the resulting pile
    +        check pile2
    +    ]
    +    ;; 'check' ensures no cell exceeds threshold (4); if it does, it topples
    +    check: function [pile [series!]] [
    +        stable:   true  ;; Flag to track if pile is stable
    +        row: col: none  ;; Coordinates of any unstable cell
    +        ;; Scan the 3x3 grid for cells >= 4
    +        repeat r 3 [
    +            repeat c 3 [
    +                if pile/:r/:c >= 4 [
    +                    stable: false
    +                    ;; Subtract threshold from the unstable cell
    +                    pile/:r/:c: pile/:r/:c - 4
    +                    row: r col: c
    +                    break  ;; Exit inner repeat when found
    +                ]
    +            ]
    +            unless stable [break]  ;; Exit outer repeat if unstable cell found
    +        ]
    +        ;; If no unstable cell was found, print final pile and exit
    +        if stable [
    +            print trim/with mold/only pile "[]"
    +            print ""
    +            exit
    +        ]
    +        ;; Distribute ("spill") grains from the unstable cell to neighbors
    +        spill pile row col
    +    ]
    +    ;; 'spill' distributes one grain to each valid neighbor of (r, c)
    +    spill: function [pile [series!] r [integer!] c [integer!]] [
    +        ;; Define neighbor offsets: right, up, left, down
    +        neigh: reduce [
    +            right: reduce [r c - 1]
    +            up:    reduce [r + 1 c]
    +            left:  reduce [r c + 1]
    +            down:  reduce [r - 1 c]
    +        ]
    +        ;; For each neighbor coordinate pair 'n'
    +        foreach n neigh [
    +            ;; If neighbor cell exists (not off-grid), add one grain
    +            unless any [
    +                none? pile/(n/1)
    +                none? pile/(n/1)/(n/2)
    +            ][
    +                pile/(n/1)/(n/2): pile/(n/1)/(n/2) + 1
    +            ]
    +        ]
    +        ;; Re-check pile for further toppling
    +        check pile
    +    ]
    +]
    +
    +s1: [
    +    [1 2 0]
    +    [2 1 1]
    +    [0 1 3]
    +]
    +s2: [
    +    [2 1 3]
    +    [1 0 1]
    +    [0 1 0]
    +]
    +s3: [
    +    [3 3 3]
    +    [3 3 3]
    +    [3 3 3]
    +]
    +s3_id: [
    +    [2 1 2]
    +    [1 0 1]
    +    [2 1 2]
    +]
    +ex: [
    +    [4 3 3]
    +    [3 1 2]
    +    [0 2 3]
    +]
    +print "Avalanche of topplings"
    +sadd/check copy/deep ex
    +print "Add s1 to s2"
    +sadd/comb copy/deep s1 copy/deep s2
    +print "Add s2 to s1"
    +sadd/comb copy/deep s2 copy/deep s1
    +print "Add s3 to s3_id"
    +sadd/comb copy/deep s3 copy/deep s3_id
    +print "Add s3_id to s3_id"
    +sadd/comb copy/deep s3_id copy/deep s3_id
    diff --git a/Task/Abelian-sandpile-model/APL/abelian-sandpile-model-1.apl b/Task/Abelian-sandpile-model/APL/abelian-sandpile-model-1.apl
    new file mode 100644
    index 0000000000..7c007133c3
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model/APL/abelian-sandpile-model-1.apl
    @@ -0,0 +1,12 @@
    +⍝ Collapse a sandpile in a given matrix
    +sandpile←{⍵-(4×S)-⊃+/(1 ¯1⊖¨⊂S)+1 ¯1⌽¨⊂S←⍵≥4}⍣≡
    +
    +⍝ An ⍺-by-⍺ matrix with its middle element set to ⍵
    +middle←{⍺ ⍺↑(-⌈⍺ ⍺÷2)↑⍵}
    +
    +⍝ Write the sandpile in ⍵ as a PPM image to file ⍺
    +to_ppm←{
    +    colors←'0 0 0' '0 1 0' '1 0 1' '1 1 0'
    +    ppm←∊⎕TC[2],⍨¨'P3'(⍕⍴⍵)(,⊂'1'),colors[1+,⍵]
    +    (⊂ppm)⎕NPUT⍺
    +}
    diff --git a/Task/Abelian-sandpile-model/APL/abelian-sandpile-model-2.apl b/Task/Abelian-sandpile-model/APL/abelian-sandpile-model-2.apl
    new file mode 100644
    index 0000000000..fbda092c12
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model/APL/abelian-sandpile-model-2.apl
    @@ -0,0 +1,14 @@
    +      ⍝ Result of collapsing '64'
    +      sandpile 9 middle 64
    +0 0 0 0 0 0 0 0 0
    +0 0 0 1 2 1 0 0 0
    +0 0 2 2 2 2 2 0 0
    +0 1 2 2 2 2 2 1 0
    +0 2 2 2 0 2 2 2 0
    +0 1 2 2 2 2 2 1 0
    +0 0 2 2 2 2 2 0 0
    +0 0 0 1 2 1 0 0 0
    +0 0 0 0 0 0 0 0 0
    +
    +      ⍝ Write image of result of collapsing 22000
    +      'sandpile.ppm' to_ppm sandpile 121 middle 22000
    diff --git a/Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.adb b/Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.adb
    new file mode 100644
    index 0000000000..10aa915326
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model/Ada/abelian-sandpile-model.adb
    @@ -0,0 +1,67 @@
    +pragma Ada_2022;
    +with Ada.Command_Line;  use Ada.Command_Line;
    +with Ada.Text_IO;       use Ada.Text_IO;
    +procedure Abelian_Sandpile is
    +   type Grid_2D is array (Positive range <>, Positive range <>) of Natural;
    +
    +   procedure Write_PPM (Grid : Grid_2D; Filename : String) is
    +      PPM_File : File_Type;
    +   begin
    +      Create (PPM_File, Out_File, Filename);
    +      Put_Line (PPM_File, "P3");
    +      Put_Line (PPM_File, Grid'Length (1)'Image & Grid'Length (2)'Image);
    +      Put_Line (PPM_File, "7");
    +      for Y in 1 .. Grid'Length (2) loop
    +         for X in 1 .. Grid'Length (1) loop
    +            case Grid (X, Y) is
    +               when 0 => Put_Line (PPM_File, "0 0 0");      --  black
    +               when 1 => Put_Line (PPM_File, "0 7 0");      --  green
    +               when 2 => Put_Line (PPM_File, "7 0 7");      --  lilac
    +               when 3 => Put_Line (PPM_File, "7 7 0");      --  yellow
    +               when others => Put_Line (PPM_File, "0 0 7"); --  blue, shouldn't happen
    +            end case;
    +         end loop;
    +      end loop;
    +      Close (PPM_File);
    +   end Write_PPM;
    +begin
    +   if Argument_Count /= 2 then
    +      Put_Line ("Error: Must specify  ");
    +   else
    +      declare
    +         Initial_Height : constant Positive := Positive'Value (Argument (1));
    +         Grid_Size      : constant Positive := Positive'Value (Argument (2));
    +         Sandpile       : Grid_2D (1 .. Grid_Size, 1 .. Grid_Size) := [others => [others => 0]];
    +         More_To_Do     : Boolean := True;
    +         Overspill      : Natural;
    +      begin
    +         Sandpile (Grid_Size / 2, Grid_Size / 2) := Initial_Height;
    +         while More_To_Do loop
    +            More_To_Do := False;
    +            for X in 1 .. Grid_Size loop
    +               for Y in 1 .. Grid_Size loop
    +                  if Sandpile (X, Y) >= 4 then
    +                     Overspill := Sandpile (X, Y) / 4;
    +                     Sandpile (X, Y) :=  @ mod 4;
    +                     More_To_Do := True;
    +                     if X > 1 then
    +                        Sandpile (X - 1, Y) := @ + Overspill;
    +                     end if;
    +                     if Y > 1 then
    +                        Sandpile (X, Y - 1) := @ + Overspill;
    +                     end if;
    +                     if X < Grid_Size then
    +                        Sandpile (X + 1, Y) := @ + Overspill;
    +                     end if;
    +                     if Y < Grid_Size then
    +                        Sandpile (X, Y + 1) := @ + Overspill;
    +                     end if;
    +                  end if;
    +               end loop;
    +            end loop;
    +         end loop;
    +         if Grid_Size < 16 then Put_Line (Sandpile'Image); end if;
    +         Write_PPM (Sandpile, "sandpile.ppm");
    +      end;
    +   end if;
    +end Abelian_Sandpile;
    diff --git a/Task/Abelian-sandpile-model/Crystal/abelian-sandpile-model.cr b/Task/Abelian-sandpile-model/Crystal/abelian-sandpile-model.cr
    new file mode 100644
    index 0000000000..f09cfac038
    --- /dev/null
    +++ b/Task/Abelian-sandpile-model/Crystal/abelian-sandpile-model.cr
    @@ -0,0 +1,76 @@
    +def abelian_sandpile (width, height, stacks)
    +  pile = Array(Array(Int32)).new(height) { Array(Int32).new(width, 0) }
    +  minr = maxr = height // 2
    +  minc = maxc = width // 2
    +  stacks.each do |(c, r), stack|
    +    pile[r][c] = stack
    +    minc = c if c < minc
    +    maxc = c if c > maxc
    +    minr = r if r < minr
    +    maxr = r if r > maxr
    +  end
    +  loop do
    +    done = true
    +    (minr .. maxr).each do |r|
    +      (minc .. maxc).each do |c|
    +        stack = pile[r][c]
    +        if stack >= 4
    +          portion = stack // 4
    +          pile[r][c] %= 4
    +          (pile[r][c-1] += portion) && (minc = Math.min(minc, c-1))  if c-1 >= 0
    +          (pile[r][c+1] += portion) && (maxc = Math.max(maxc, c+1))  if c+1 < width
    +          (pile[r-1][c] += portion) && (minr = Math.min(minr, r-1))  if r-1 >= 0
    +          (pile[r+1][c] += portion) && (maxr = Math.max(maxr, r+1))  if r+1 < height
    +          done = false
    +        end
    +      end
    +    end
    +    break if done
    +  end
    +  pile
    +end
    +
    +def write_sandpile_to_ppm (name, pile, palette = [0, 0x73AAF9, 0xFFC000, 0x7C0000])
    +  File.open(name, "w") do |f|
    +    f.print "P6\n#{pile[0].size} #{pile.size} 255"
    +    f.write_byte 10
    +    pile.each do |row|
    +      row.each do |stack|
    +        color = palette[stack]
    +        f.write_byte (color >> 16 & 0xff).to_u8   # red
    +        f.write_byte (color >>  8 & 0xff).to_u8   # green
    +        f.write_byte (color       & 0xff).to_u8   # blue
    +      end
    +    end
    +  end
    +end
    +
    +def usage
    +  STDERR.puts "Usage: #$0 filename width height x y stacksize [x y stacksize ...]"
    +  STDERR.puts "   or: #$0 filename stacksize"
    +  exit
    +end
    +
    +filename = ""
    +width = height = 0
    +stacks = [] of { {Int32, Int32}, Int32 }
    +
    +begin
    +  filename = ARGV.shift
    +  if ARGV.size == 1
    +    stacksize = ARGV.shift.to_i
    +    size = Math.sqrt(stacksize / 1.75).to_i + 3
    +    size += 1 unless size.odd?
    +    height = width = size
    +    stacks << { { size // 2, size // 2 }, stacksize }
    +  else
    +    width, height = ARGV.shift.to_i, ARGV.shift.to_i
    +    ARGV.each_slice(3) do |slice|
    +      stacks << { { slice[0].to_i, slice[1].to_i }, slice[2].to_i }
    +    end
    +  end
    +rescue
    +  usage
    +end
    +
    +write_sandpile_to_ppm filename, abelian_sandpile(width, height, stacks)
    diff --git a/Task/Abelian-sandpile-model/Uiua/abelian-sandpile-model.uiua b/Task/Abelian-sandpile-model/Uiua/abelian-sandpile-model.uiua
    index bff94f44fb..73c63c9302 100644
    --- a/Task/Abelian-sandpile-model/Uiua/abelian-sandpile-model.uiua
    +++ b/Task/Abelian-sandpile-model/Uiua/abelian-sandpile-model.uiua
    @@ -1,10 +1,16 @@
    -G ← ⍜⊡⋅6000⌊÷2⟜↯⊟.71 0 # good demo
    +# Experimental!
    +G     ← ⍜⊡⋅6000⌊÷2⟜↯˙⊟71 0 # good demo
     PadTL ← ↻¯≡↥0⊙⬚°◌↙⟜(+⌵)⊙⊸△
     # Pad the differences grid to same size, making ops *much* faster.
    -D ← ⬚0PadTL-△G △.[0_1_0 1_¯4_1 0_1_0]
    -Scale ← ▽⟜≡▽4÷/↥/↥.                                # Greyscale and upscale for output.
    -Abelian₁ ← ∧(+(↻¯:D))≡(-1_1)⊚≥4.⊙(+1)              # Moves grains one at a time
    -Abelian₄ ← ∧(+×⊃(⌊÷4⊡+1_1|↻¯:D)⊙.)≡(-1_1)⊚≥4.⊙(+1) # Moves all >= 4 -- slightly faster
    -⟜Scale&p⍜now⍥Abelian₄ 100G 0
    -⟜Scale&p⍜now⍥Abelian₄ 900⊙,
    -Scale⍥Abelian₄∞⊙, # Run to completion
    +D        ← ⬚0PadTL-△G⊸△[0_1_0 1_¯4_1 0_1_0]
    +Scale    ← ▽⟜≡▽4÷/↥⊸/↥                              # Greyscale and upscale for output.
    +Abelian₁ ← ∧(+(↻˜¯D))≡(-1_1)⊚⊸≥4⊙(+1)               # Moves grains one at a time
    +Abelian₄ ← ∧(+×⊃(⌊÷4⊡+1_1|↻˜¯D)⊃⊙∘⋅∘)≡(-1_1)⊚⊸≥4⊙+₁ # Moves all >= 4 -- slightly faster
    +A        ← (≡Scale↘200⍥(⤚Abelian₄)600G 0)
    +B ← (
    +  ⟜Scale&p⍜now⍥Abelian₄ 100G 0
    +  ⟜Scale&p⍜now⍥Abelian₄ 900⊃⊙⋅∘⋅⊙∘
    +  Scale⍥Abelian₄∞⊃⊙⋅∘⋅⊙∘ # Run to completion
    +)
    +# Choose A or B
    +A
    diff --git a/Task/Abstract-type/00-TASK.txt b/Task/Abstract-type/00-TASK.txt
    index 12c67b0c1a..bc11ecc714 100644
    --- a/Task/Abstract-type/00-TASK.txt
    +++ b/Task/Abstract-type/00-TASK.txt
    @@ -1,6 +1,6 @@
     '''Abstract type''' is a type without instances or without definition.
     
    -For example in [[object-oriented programming]] using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called '''interfaces'''. In the languages that do not support multiple [[inheritance]] ([[Ada]], [[Java]]), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like [[C++]]) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, [[object-oriented programming | OO]] languages normally prevent instantiation from them  (instantiation must derived from one of their descendant classes).
    +For example in [[object-oriented programming]] using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract types without any implementation are called [[wp:Interface_(object-oriented_programming)|'''interfaces''']]. In the languages that do not support multiple [[inheritance]] ([[Ada]], [[Java]]), classes can, nonetheless, inherit from multiple interfaces. The languages with multiple inheritance (like [[C++]]) usually make no distinction between partially implementable abstract types and interfaces. Because the abstract type's implementation is incomplete, [[object-oriented programming | OO]] languages normally prevent instantiation from them  (instantiation must derived from one of their descendant classes).
     
     The term '''abstract datatype''' also may denote a type, with an implementation provided by the programmer rather than directly by the language (a '''built-in''' or an inferred type). Here the word ''abstract'' means that the implementation is abstracted away, irrelevant for the user of the type. Such implementation can and should be hidden if the language supports separation of implementation and specification. This hides complexity while allowing the implementation to change without repercussions on the usage. The corresponding software design practice is said to follow the [[wp:Information_hiding|information hiding principle]].
     
    diff --git a/Task/Abstract-type/Ada/abstract-type-1.adb b/Task/Abstract-type/Ada/abstract-type-1.adb
    new file mode 100644
    index 0000000000..ec6e7dfe56
    --- /dev/null
    +++ b/Task/Abstract-type/Ada/abstract-type-1.adb
    @@ -0,0 +1,3 @@
    +type Queue is limited interface;
    +procedure Enqueue (Lounge : in out Queue; Item : in out Element) is abstract;
    +procedure Dequeue (Lounge : in out Queue; Item : in out Element) is abstract;
    diff --git a/Task/Abstract-type/Ada/abstract-type-2.adb b/Task/Abstract-type/Ada/abstract-type-2.adb
    new file mode 100644
    index 0000000000..09512a4fd8
    --- /dev/null
    +++ b/Task/Abstract-type/Ada/abstract-type-2.adb
    @@ -0,0 +1,2 @@
    +type Scheduler is task interface;
    +procedure Plan (Manager : in out Scheduler; Activity : in out Job) is abstract;
    diff --git a/Task/Abstract-type/Ada/abstract-type-3.adb b/Task/Abstract-type/Ada/abstract-type-3.adb
    new file mode 100644
    index 0000000000..712648f9b7
    --- /dev/null
    +++ b/Task/Abstract-type/Ada/abstract-type-3.adb
    @@ -0,0 +1,10 @@
    +with Ada.Finalization;
    +...
    +type Node is abstract new Ada.Finalization.Limited_Controlled and Queue with record
    +   Previous : not null access Node'Class := Node'Unchecked_Access;
    +   Next     : not null access Node'Class := Node'Unchecked_Access;
    +end record;
    +overriding procedure Finalize (X : in out Node); -- Removes the node from its list if any
    +overriding procedure Dequeue (Lounge : in out Node; Item : in out Element);
    +overriding procedure Enqueue (Lounge : in out Node; Item : in out Element);
    +procedure Process (X : in out Node) is abstract; -- To be implemented
    diff --git a/Task/Abstract-type/COBOL/abstract-type.cob b/Task/Abstract-type/COBOL/abstract-type.cob
    new file mode 100644
    index 0000000000..3010951b3c
    --- /dev/null
    +++ b/Task/Abstract-type/COBOL/abstract-type.cob
    @@ -0,0 +1,68 @@
    +       IDENTIFICATION DIVISION.
    +       INTERFACE-ID. Shape.
    +
    +       PROCEDURE DIVISION.
    +
    +       IDENTIFICATION DIVISION.
    +       METHOD-ID. perimeter.
    +       DATA DIVISION.
    +       LINKAGE SECTION.
    +       01  ret USAGE FLOAT-LONG.
    +       PROCEDURE DIVISION RETURNING ret.
    +       END METHOD perimeter.
    +
    +       IDENTIFICATION DIVISION.
    +       METHOD-ID. shape-area.
    +       DATA DIVISION.
    +       LINKAGE SECTION.
    +       01  ret USAGE FLOAT-LONG.
    +       PROCEDURE DIVISION RETURNING ret.
    +       END METHOD shape-area.
    +
    +       END INTERFACE Shape.
    +
    +
    +       IDENTIFICATION DIVISION.
    +       CLASS-ID. Rectangle.
    +
    +       ENVIRONMENT DIVISION.
    +       CONFIGURATION SECTION.
    +       REPOSITORY.
    +           INTERFACE Shape.
    +
    +       IDENTIFICATION DIVISION.
    +       OBJECT IMPLEMENTS Shape.
    +           DATA DIVISION.
    +           WORKING-STORAGE SECTION.
    +           01  width  USAGE FLOAT-LONG PROPERTY.
    +           01  height USAGE FLOAT-LONG PROPERTY.
    +
    +           PROCEDURE DIVISION.
    +
    +           IDENTIFICATION DIVISION.
    +           METHOD-ID. perimeter.
    +           DATA DIVISION.
    +           LINKAGE SECTION.
    +           01  ret USAGE FLOAT-LONG.
    +           PROCEDURE DIVISION RETURNING ret.
    +               COMPUTE
    +                   ret = width * 2.0 + height * 2.0
    +               END-COMPUTE
    +               GOBACK.
    +           END METHOD perimeter.
    +
    +           IDENTIFICATION DIVISION.
    +           METHOD-ID. shape-area.
    +           DATA DIVISION.
    +           LINKAGE SECTION.
    +           01  ret USAGE FLOAT-LONG.
    +           PROCEDURE DIVISION RETURNING ret.
    +               COMPUTE
    +                   ret = width * height
    +               END-COMPUTE
    +               GOBACK.
    +           END METHOD shape-area.
    +
    +       END OBJECT.
    +
    +       END CLASS Rectangle.
    diff --git a/Task/Abstract-type/Gleam/abstract-type.gleam b/Task/Abstract-type/Gleam/abstract-type.gleam
    new file mode 100644
    index 0000000000..df8cda4c81
    --- /dev/null
    +++ b/Task/Abstract-type/Gleam/abstract-type.gleam
    @@ -0,0 +1,24 @@
    +pub fn main() {
    +  let positive = new(1)
    +  let zero = new(0)
    +  let negative = new(-1)
    +
    +  echo to_int(positive)
    +  echo to_int(zero)
    +  echo to_int(negative)
    +}
    +
    +pub opaque type PositiveInt {
    +  PositiveInt(inner: Int)
    +}
    +
    +pub fn new(i: Int) -> PositiveInt {
    +  case i >= 0 {
    +    True -> PositiveInt(i)
    +    False -> PositiveInt(0)
    +  }
    +}
    +
    +pub fn to_int(i: PositiveInt) -> Int {
    +  i.inner
    +}
    diff --git a/Task/Abstract-type/Haxe/abstract-type-1.hx b/Task/Abstract-type/Haxe/abstract-type-1.hx
    new file mode 100644
    index 0000000000..91134488e5
    --- /dev/null
    +++ b/Task/Abstract-type/Haxe/abstract-type-1.hx
    @@ -0,0 +1,44 @@
    +interface Vocal {
    +	public function speak():String;
    +}
    +
    +interface Gravitational {
    +	public function getWeight():Int;
    +}
    +
    +abstract class Dog implements Vocal implements Gravitational {
    +	public function speak():String {
    +		return "Woof";
    +	}
    +
    +	public function new() {}
    +}
    +
    +class Chihuahua extends Dog {
    +	public function getWeight():Int {
    +		return 5;
    +	}
    +}
    +
    +class GreatDane extends Dog {
    +	public function getWeight():Int {
    +		return 150;
    +	}
    +}
    +
    +class Main {
    +	static public function main():Void {
    +		var dogs:Array = [];
    +
    +		var david = new Chihuahua();
    +		var goliath = new GreatDane();
    +
    +		dogs.push(david);
    +		dogs.push(goliath);
    +
    +		for (dog in dogs) {
    +			trace(dog.speak());
    +			trace(dog.getWeight());
    +		}
    +	}
    +}
    diff --git a/Task/Abstract-type/Haxe/abstract-type-2.hx b/Task/Abstract-type/Haxe/abstract-type-2.hx
    new file mode 100644
    index 0000000000..7745ff6089
    --- /dev/null
    +++ b/Task/Abstract-type/Haxe/abstract-type-2.hx
    @@ -0,0 +1,3 @@
    +class abstraction()
    +    abstract method compare(l,r) # generates runerr(700, "method compare()")
    +end
    diff --git a/Task/Abstract-type/PowerShell/abstract-type-1.ps1 b/Task/Abstract-type/PowerShell/abstract-type-1.ps1
    new file mode 100644
    index 0000000000..c1c82d3b36
    --- /dev/null
    +++ b/Task/Abstract-type/PowerShell/abstract-type-1.ps1
    @@ -0,0 +1,92 @@
    +#Requires -Version 5.0
    +
    +Class Player
    +{
    +  <#
    +    Properties: Name, Team, Position and Number
    +  #>
    +    [string]$Name
    +
    +    [ValidateSet("Baltimore Ravens","Cincinnati Bengals","Cleveland Browns","Pittsburgh Steelers",
    +                 "Chicago Bears","Detroit Lions","Green Bay Packers","Minnesota Vikings",
    +                 "Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans",
    +                 "Atlanta Falcons","Carolina Panthers","New Orleans Saints","Tampa Bay Buccaneers",
    +                 "Buffalo Bills","Miami Dolphins","New England Patriots","New York Jets",
    +                 "Dallas Cowboys","New York Giants","Philadelphia Eagles","Washington Redskins",
    +                 "Denver Broncos","Kansas City Chiefs","Oakland Raiders","San Diego Chargers",
    +                 "Arizona Cardinals","Los Angeles Rams","San Francisco 49ers","Seattle Seahawks")]
    +    [string]$Team
    +
    +    [ValidateSet("C","G","T","QB","RB","WR","TE","DT","DE","ILB","OLB","CB","S","K","H","LS","P","KOS","R")]
    +    [string]$Position
    +
    +    [ValidateRange(0,99)]
    +    [int]$Number
    +
    +  <#
    +    Constructor: Creates a new Player object, with the specified Name, Team, Position and Number.
    +  #>
    +    Player([string]$Name, [string]$Team, [string]$Position, [int]$Number)
    +    {
    +        $this.Name     = (Get-Culture).TextInfo.ToTitleCase("$Name")
    +        $this.Team     = (Get-Culture).TextInfo.ToTitleCase("$Team")
    +        $this.Position = $Position.ToUpper()
    +        $this.Number   = $Number
    +    }
    +
    +  <#
    +    Methods: Trade the player to a different team (optional parameters for methods in PowerShell 5 classes are not available.  Boo!!)
    +             An overloaded method is a method with the same name as another method but in a different context,
    +             in this case with different parameters.
    +  #>
    +    Trade([string]$NewTeam)
    +    {
    +        [string[]]$league = "Baltimore Ravens","Cincinnati Bengals","Cleveland Browns","Pittsburgh Steelers",
    +                            "Chicago Bears","Detroit Lions","Green Bay Packers","Minnesota Vikings",
    +                            "Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans",
    +                            "Atlanta Falcons","Carolina Panthers","New Orleans Saints","Tampa Bay Buccaneers",
    +                            "Buffalo Bills","Miami Dolphins","New England Patriots","New York Jets",
    +                            "Dallas Cowboys","New York Giants","Philadelphia Eagles","Washington Redskins",
    +                            "Denver Broncos","Kansas City Chiefs","Oakland Raiders","San Diego Chargers",
    +                            "Arizona Cardinals","Los Angeles Rams","San Francisco 49ers","Seattle Seahawks"
    +
    +        if ($NewTeam -in $league | Where-Object {$_ -notmatch $this.Team})
    +        {
    +            $this.Team = (Get-Culture).TextInfo.ToTitleCase("$NewTeam")
    +        }
    +        else
    +        {
    +            throw "Invalid Team"
    +        }
    +    }
    +
    +    Trade([string]$NewTeam, [int]$NewNumber)
    +    {
    +        [string[]]$league = "Baltimore Ravens","Cincinnati Bengals","Cleveland Browns","Pittsburgh Steelers",
    +                            "Chicago Bears","Detroit Lions","Green Bay Packers","Minnesota Vikings",
    +                            "Houston Texans","Indianapolis Colts","Jacksonville Jaguars","Tennessee Titans",
    +                            "Atlanta Falcons","Carolina Panthers","New Orleans Saints","Tampa Bay Buccaneers",
    +                            "Buffalo Bills","Miami Dolphins","New England Patriots","New York Jets",
    +                            "Dallas Cowboys","New York Giants","Philadelphia Eagles","Washington Redskins",
    +                            "Denver Broncos","Kansas City Chiefs","Oakland Raiders","San Diego Chargers",
    +                            "Arizona Cardinals","Los Angeles Rams","San Francisco 49ers","Seattle Seahawks"
    +
    +        if ($NewTeam -in $league | Where-Object {$_ -notmatch $this.Team})
    +        {
    +            $this.Team = (Get-Culture).TextInfo.ToTitleCase("$NewTeam")
    +        }
    +        else
    +        {
    +            throw "Invalid Team"
    +        }
    +
    +        if ($NewNumber -in 0..99)
    +        {
    +            $this.Number = $NewNumber
    +        }
    +        else
    +        {
    +            throw "Invalid Number"
    +        }
    +    }
    +}
    diff --git a/Task/Abstract-type/PowerShell/abstract-type-2.ps1 b/Task/Abstract-type/PowerShell/abstract-type-2.ps1
    new file mode 100644
    index 0000000000..a0711e85f9
    --- /dev/null
    +++ b/Task/Abstract-type/PowerShell/abstract-type-2.ps1
    @@ -0,0 +1,2 @@
    +$player1 = [Player]::new("sam bradford", "philadelphia eagles", "qb", 7)
    +$player1
    diff --git a/Task/Abstract-type/PowerShell/abstract-type-3.ps1 b/Task/Abstract-type/PowerShell/abstract-type-3.ps1
    new file mode 100644
    index 0000000000..4c2ddc606c
    --- /dev/null
    +++ b/Task/Abstract-type/PowerShell/abstract-type-3.ps1
    @@ -0,0 +1,2 @@
    +$player1.Trade("minnesota vikings", 8)
    +$player1
    diff --git a/Task/Abstract-type/PowerShell/abstract-type-4.ps1 b/Task/Abstract-type/PowerShell/abstract-type-4.ps1
    new file mode 100644
    index 0000000000..7cd5678d1b
    --- /dev/null
    +++ b/Task/Abstract-type/PowerShell/abstract-type-4.ps1
    @@ -0,0 +1,2 @@
    +$player2 = [Player]::new("demarco murray", "philadelphia eagles", "rb", 29)
    +$player2
    diff --git a/Task/Abstract-type/PowerShell/abstract-type-5.ps1 b/Task/Abstract-type/PowerShell/abstract-type-5.ps1
    new file mode 100644
    index 0000000000..1b65e884e8
    --- /dev/null
    +++ b/Task/Abstract-type/PowerShell/abstract-type-5.ps1
    @@ -0,0 +1,2 @@
    +$player2.Trade("tennessee titans")
    +$player2
    diff --git a/Task/Abstract-type/Python/abstract-type-1.py b/Task/Abstract-type/Python/abstract-type-1.py
    index 97bcd27dd4..0d3279e755 100644
    --- a/Task/Abstract-type/Python/abstract-type-1.py
    +++ b/Task/Abstract-type/Python/abstract-type-1.py
    @@ -1,13 +1,33 @@
    -class BaseQueue(object):
    -    """Abstract/Virtual Class
    -    """
    -    def __init__(self):
    -        self.contents = list()
    -        raise NotImplementedError
    -    def Enqueue(self, item):
    -        raise NotImplementedError
    -    def Dequeue(self):
    -        raise NotImplementedError
    -    def Print_Contents(self):
    -        for i in self.contents:
    -            print i,
    +from abc import ABC
    +from abc import abstractmethod
    +from typing import Literal
    +
    +class Pet(ABC):
    +    def __init__(self, name: str) -> None:
    +        self.name = name
    +
    +    @abstractmethod
    +    def speak(self) -> str: ...
    +
    +class Cat(Pet):
    +    def speak(self) -> str:
    +        return f"{self.name} says meow"
    +
    +class Dog(Pet):
    +    def __init__(self, name: str, size: Literal["small", "big"] = "small") -> None:
    +        super().__init__(name)
    +        self.size = size
    +
    +    def speak(self) -> str:
    +        return "woof" if self.size == "small" else "loud woof"
    +
    +
    +if __name__ == "__main__":
    +    pets: list[Pet] = [
    +        Cat(name="Fluffy"),
    +        Dog(name="Gary"),
    +        Dog(name="Sue", size="big"),
    +    ]
    +
    +    for pet in pets:
    +        print(pet.speak())
    diff --git a/Task/Abstract-type/Python/abstract-type-2.py b/Task/Abstract-type/Python/abstract-type-2.py
    index d7e1b0f7eb..5f803fcc7e 100644
    --- a/Task/Abstract-type/Python/abstract-type-2.py
    +++ b/Task/Abstract-type/Python/abstract-type-2.py
    @@ -1,21 +1,31 @@
    -from abc import ABCMeta, abstractmethod
    +from typing import Literal
    +from typing import Protocol
     
    -class BaseQueue():
    -    """Abstract Class
    -    """
    -    __metaclass__ = ABCMeta
    +class Pet(Protocol):
    +    def speak(self) -> str: ...
     
    -    def __init__(self):
    -        self.contents = list()
    +class Cat:
    +    def __init__(self, name: str) -> None:
    +        self.name = name
     
    -    @abstractmethod
    -    def Enqueue(self, item):
    -        pass
    +    def speak(self) -> str:
    +        return f"{self.name} says meow"
     
    -    @abstractmethod
    -    def Dequeue(self):
    -        pass
    +class Dog:
    +    def __init__(self, name: str, size: Literal["small", "big"] = "small") -> None:
    +        self.name = name
    +        self.size = size
     
    -    def Print_Contents(self):
    -        for i in self.contents:
    -            print i,
    +    def speak(self) -> str:
    +        return "woof" if self.size == "small" else "loud woof"
    +
    +
    +if __name__ == "__main__":
    +    pets: list[Pet] = [
    +        Cat(name="Fluffy"),
    +        Dog(name="Gary"),
    +        Dog(name="Sue", size="big"),
    +    ]
    +
    +    for pet in pets:
    +        print(pet.speak())
    diff --git a/Task/Abstract-type/ReScript/abstract-type.res b/Task/Abstract-type/ReScript/abstract-type.res
    new file mode 100644
    index 0000000000..63c57c4e0c
    --- /dev/null
    +++ b/Task/Abstract-type/ReScript/abstract-type.res
    @@ -0,0 +1 @@
    +type t
    diff --git a/Task/Abstract-type/Rebol/abstract-type.rebol b/Task/Abstract-type/Rebol/abstract-type.rebol
    new file mode 100644
    index 0000000000..184d2223f1
    --- /dev/null
    +++ b/Task/Abstract-type/Rebol/abstract-type.rebol
    @@ -0,0 +1,44 @@
    +REBOL [
    +	Title: "Abstract Type"
    +	URL: http://rosettacode.org/wiki/Abstract_type
    +]
    +
    +; The "shape" class is an abstract class -- it defines the "pen"
    +; property and "line" method, but "size" and "draw" are undefined and
    +; unimplemented.
    +
    +shape: make object! [
    +	pen:  "X"
    +	size: none
    +
    +	line: func [count][loop count [prin self/pen]  prin crlf]
    +	draw: does [none]
    +]
    +
    +; The "box" class inherits from "shape" and provides the missing
    +; information for drawing boxes.
    +
    +box: make shape [
    +	size: 10
    +	draw: does [loop self/size [line self/size]]
    +]
    +
    +; "rectangle" also inherits from "shape", but handles the
    +; implementation very differently.
    +
    +rectangle: make shape [
    +	size: 20x10
    +	draw: does [loop self/size/y [line self/size/x]]
    +]
    +
    +; Unlike some languages discussed, REBOL has absolutely no qualms
    +; about instantiating an "abstract" class -- that's how I created the
    +; derived classes of "rectangle" and "box", after all.
    +
    +s: make shape []  s/draw ; Nothing happens.
    +
    +print "A box:"
    +b: make box [pen: "O" size: 5]  b/draw
    +
    +print "^/A rectangle:"
    +r: make rectangle [size: 32x5]  r/draw
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/ANSI-BASIC/abundant-deficient-and-perfect-number-classifications.basic b/Task/Abundant-deficient-and-perfect-number-classifications/ANSI-BASIC/abundant-deficient-and-perfect-number-classifications.basic
    new file mode 100644
    index 0000000000..90cade1723
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/ANSI-BASIC/abundant-deficient-and-perfect-number-classifications.basic
    @@ -0,0 +1,34 @@
    +100 REM Abundant, deficient and perfect number classifications
    +110 DIM Pds(1 TO 20000)
    +120 LET MaxNumber = UBOUND(Pds)
    +130 LET ACount = 0
    +140 LET DCount = 0
    +150 LET PCount = 0
    +160 LET Pds(1) = 0
    +170 FOR I = 2 TO MaxNumber
    +180    LET Pds(I) = 1
    +190 NEXT I
    +200 FOR I = 2 TO MaxNumber
    +210    FOR J = I + I TO MaxNumber STEP I
    +220       LET Pds(J) = Pds(J) + I
    +230    NEXT J
    +240 NEXT I
    +250 REM Classify the numbers
    +260 FOR I = 1 TO MaxNumber
    +270    LET DSum = Pds(I)
    +280    IF DSum > I THEN
    +290       LET ACount = ACount + 1
    +300    ELSEIF DSum < I THEN
    +310       LET DCount = DCount + 1
    +320    ELSE
    +330       LET PCount = PCount + 1
    +340    END IF
    +350 NEXT I
    +360 PRINT "Up to"; MaxNumber
    +370 PRINT "Number of abundants :";
    +380 PRINT USING "######": ACount
    +390 PRINT "Number of perfects  :";
    +400 PRINT USING "######": PCount
    +410 PRINT "Number of deficients:";
    +420 PRINT USING "######": DCount
    +430 END
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Ada/abundant-deficient-and-perfect-number-classifications.adb b/Task/Abundant-deficient-and-perfect-number-classifications/Ada/abundant-deficient-and-perfect-number-classifications.adb
    new file mode 100644
    index 0000000000..6f066bde65
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Ada/abundant-deficient-and-perfect-number-classifications.adb
    @@ -0,0 +1,35 @@
    +with Ada.Text_IO, Generic_Divisors;
    +
    +procedure ADB_Classification is
    +   function Same(P: Positive) return Positive is (P);
    +   package Divisor_Sum is new Generic_Divisors
    +     (Result_Type => Natural, None => 0, One => Same, Add =>  "+");
    +
    +   type Class_Type is (Deficient, Perfect, Abundant);
    +
    +   function Class(D_Sum, N: Natural) return Class_Type is
    +      (if D_Sum < N then Deficient
    +       elsif D_Sum = N then Perfect
    +       else Abundant);
    +
    +   Cls: Class_Type;
    +   Results: array (Class_Type) of Natural := (others => 0);
    +
    +   package NIO is new Ada.Text_IO.Integer_IO(Natural);
    +   package CIO is new Ada.Text_IO.Enumeration_IO(Class_Type);
    +begin
    +   for N in 1 .. 20_000 loop
    +      Cls := Class(Divisor_Sum.Process(N), N);
    +      Results(Cls) := Results(Cls)+1;
    +   end loop;
    +   for Class in Results'Range loop
    +      CIO.Put(Class, 12);
    +      NIO.Put(Results(Class), 8);
    +      Ada.Text_IO.New_Line;
    +   end loop;
    +   Ada.Text_IO.Put_Line("--------------------");
    +   Ada.Text_IO.Put("Sum         ");
    +   NIO.Put(Results(Deficient)+Results(Perfect)+Results(Abundant), 8);
    +   Ada.Text_IO.New_Line;
    +   Ada.Text_IO.Put_Line("====================");
    +end ADB_Classification;
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Berkeley-Logo/abundant-deficient-and-perfect-number-classifications.logo b/Task/Abundant-deficient-and-perfect-number-classifications/Berkeley-Logo/abundant-deficient-and-perfect-number-classifications.logo
    new file mode 100644
    index 0000000000..34985543b5
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Berkeley-Logo/abundant-deficient-and-perfect-number-classifications.logo
    @@ -0,0 +1,33 @@
    +; Abundant, deficient and perfect number classifications
    +
    +to print.summary :num.kind :c
    +  type sentence "|Number of | :num.kind
    +  type "|:|
    +  print form :c 6 0
    +end
    +
    +to abundant.etc :max.number
    +  make "pds (array :max.number) ; proper divisor sums
    +  make "a.count 0
    +  make "d.count 0
    +  make "p.count 0
    +  setitem 1 :pds 0
    +  for [i 2 :max.number] [setitem :i :pds 1]
    +  for [i 2 :max.number] ~
    +   [make "dbl.i :i + :i
    +    for [j :dbl.i :max.number :i]
    +     [setitem :j :pds (item :j :pds) + :i]]
    +  ; Classify the numbers
    +  for [i 1 :max.number] ~
    +   [make "d.sum (item :i :pds)
    +    ifelse :d.sum > :i ~
    +     [make "a.count :a.count + 1] ~
    +     [ifelse :d.sum < :i ~
    +       [make "d.count :d.count + 1] ~
    +       [make "p.count :p.count + 1]]]
    +  erase [[] [pds] []]
    +  print sentence "|Up to| :max.number
    +  print.summary "|abundants | :a.count
    +  print.summary "|perfects  | :p.count
    +  print.summary "|deficients| :d.count
    +end
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Crystal/abundant-deficient-and-perfect-number-classifications.cr b/Task/Abundant-deficient-and-perfect-number-classifications/Crystal/abundant-deficient-and-perfect-number-classifications.cr
    new file mode 100644
    index 0000000000..2e5aefc80b
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Crystal/abundant-deficient-and-perfect-number-classifications.cr
    @@ -0,0 +1,13 @@
    +def sum_proper_divisors (n)
    +  z = n.class.zero
    +  (z+1..n//2).sum(z) {|i| n % i == 0 ? i : 0 }
    +end
    +
    +labels = %w(abundant perfect deficient)
    +
    +(1..20_000).tally_by {|i| i <=> sum_proper_divisors(i) }
    +  .to_a.sort
    +  .zip(labels)
    +  .each do |(_, count), label|
    +  printf "%6d %s\n", count, label
    +end
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/GW-BASIC/abundant-deficient-and-perfect-number-classifications.basic b/Task/Abundant-deficient-and-perfect-number-classifications/GW-BASIC/abundant-deficient-and-perfect-number-classifications.basic
    new file mode 100644
    index 0000000000..53f97b74c8
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/GW-BASIC/abundant-deficient-and-perfect-number-classifications.basic
    @@ -0,0 +1,11 @@
    +10 DEFINT A-Z: LM=20000
    +20 DIM P(LM)
    +30 FOR I=1 TO LM: P(I)=-32767: NEXT
    +40 FOR I=1 TO LM/2: FOR J=I+I TO LM STEP I: P(J)=P(J)+I: NEXT: NEXT
    +50 FOR I=1 TO LM
    +60 X=I-32767
    +70 IF P(I) i
    +    then
    +      a_count := a_count + 1
    +    else
    +      if d_sum < i
    +      then
    +        d_count := d_count + 1
    +      else
    +        p_count := p_count + 1
    +      fi
    +    fi
    +  od;
    +  writeln("Up to ", max_number: 1);
    +  writeln("Number of abundants :", a_count: 6);
    +  writeln("Number of perfects  :", p_count: 6);
    +  writeln("Number of deficients:", d_count: 6);
    +end
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Minimal-BASIC/abundant-deficient-and-perfect-number-classifications.basic b/Task/Abundant-deficient-and-perfect-number-classifications/Minimal-BASIC/abundant-deficient-and-perfect-number-classifications.basic
    new file mode 100644
    index 0000000000..e8c2de759d
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Minimal-BASIC/abundant-deficient-and-perfect-number-classifications.basic
    @@ -0,0 +1,33 @@
    +100 REM Abundant, deficient and perfect number classifications
    +110 OPTION BASE 1
    +120 REM F(I): sum of proper factors of I
    +130 DIM F(20000)
    +140 LET M = 20000
    +150 LET A = 0
    +160 LET D = 0
    +170 LET P = 0
    +180 LET F(1) = 0
    +190 FOR I = 2 TO M
    +200 LET F(I) = 1
    +210 NEXT I
    +220 FOR I = 2 TO M
    +230 FOR J = I + I TO M STEP I
    +240 LET F(J) = F(J) + I
    +250 NEXT J
    +260 NEXT I
    +270 REM Classify the numbers
    +280 FOR I = 1 TO M
    +290 LET S = F(I)
    +300 IF S <= I THEN 330
    +310 LET A = A + 1
    +320 GOTO 370
    +330 IF S >= I THEN 360
    +340 LET D = D + 1
    +350 GOTO 370
    +360 LET P = P + 1
    +370 NEXT I
    +380 PRINT "Up to"; M
    +390 PRINT "Number of abundants :"; A
    +400 PRINT "Number of perfects  :"; P
    +410 PRINT "Number of deficients:"; D
    +420 END
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/MoonRock/abundant-deficient-and-perfect-number-classifications.moonrock b/Task/Abundant-deficient-and-perfect-number-classifications/MoonRock/abundant-deficient-and-perfect-number-classifications.moonrock
    new file mode 100644
    index 0000000000..24768330b5
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/MoonRock/abundant-deficient-and-perfect-number-classifications.moonrock
    @@ -0,0 +1,59 @@
    +' Abundant, deficient and perfect number classifications
    +
    +BEGIN DEF
    +SUB PrintStr(S$, Width%)
    +%MaxNumber = 1000
    +%LastIndex = %MaxNumber - 1
    +DIM PDS&[%MaxNumber] ' PDS&[k] proper divisor sums of k + 1 (k + 1 because of indexing from 0)
    +'TODO: Check if DIM HUGE is possible. Contrary to the manual, it does not work in MR 0.50
    +
    +BEGIN CODE
    +ACount& = 0
    +DCount& = 0
    +PCount& = 0
    +PDS&[0] = 0
    +FOR I% = 1 TO %LastIndex
    +  PDS&[I%] = 1
    +NEXT
    +FOR I% = 2 TO %MaxNumber
    +  J% = I% + I%
    +  WHILE J% <= %MaxNumber
    +    JMin1% = J% - 1
    +    PDS&[JMin1%] = PDS&[JMin1%] + I%
    +    J% = J% + I%
    +  WEND
    +NEXT
    +' Classify the numbers and count each type
    +FOR I& = 1 TO %MaxNumber
    +  IMin1& = I& - 1
    +  DSum& = PDS&[IMin1&]
    +  IF DSum& > I& THEN
    +    ACount& = ACount& + 1
    +  ELSE
    +    IF DSum& < I& THEN
    +      DCount& = DCount& + 1
    +    ELSE
    +      PCount& = PCount& + 1
    +    ENDIF
    +  ENDIF
    +NEXT
    +PRINT "Up to " + STR(%MaxNumber) + "\n"
    +PRINT "Number of abundants :"
    +CALL PrintStr(STR(ACount&), 6)
    +PRINT "\n"
    +PRINT "Number of perfects  :"
    +CALL PrintStr(STR(PCount&), 6)
    +PRINT "\n"
    +PRINT "Number of deficients:"
    +CALL PrintStr(STR(DCount&), 6)
    +PRINT "\n"
    +END
    +
    +SUB PrintStr(S$, Width%)
    +IF LEN(S$) > Width% THEN
    +  PRINT S$
    +ELSE
    +  S$ = SPACE(Width%) + S$
    +  PRINT RIGHT(S$, Width%)
    +ENDIF
    +END SUB
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Oberon/abundant-deficient-and-perfect-number-classifications.oberon b/Task/Abundant-deficient-and-perfect-number-classifications/Oberon/abundant-deficient-and-perfect-number-classifications.oberon
    new file mode 100644
    index 0000000000..20f23f5b48
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Oberon/abundant-deficient-and-perfect-number-classifications.oberon
    @@ -0,0 +1,50 @@
    +MODULE AbundantDeficientAndPerfect;
    +          (* classify the numbers 1 : 20 000 as abudant, deficient or perfect *)
    +    IMPORT Out;                                    (* translation of Algol 68 *)
    +
    +    CONST  maxNumber = 20000;
    +    VAR    abundantCount, deficientCount, perfectCount : INTEGER;
    +           pds       : ARRAY maxNumber + 1 OF INTEGER;
    +
    +    (* constructs the table of the proper divisor sums            *)
    +    PROCEDURE sumDivisors;
    +        VAR   i, j  : INTEGER;
    +        BEGIN
    +            pds[ 1 ] := 0;
    +            FOR i := 2 TO maxNumber DO pds[ i ] := 1 END;
    +            FOR i := 2 TO maxNumber DO
    +                j := i + i;
    +                WHILE j <= maxNumber DO
    +                    INC( pds[ j ], i );
    +                    INC(      j,   i )
    +                END
    +            END
    +        END sumDivisors;
    +
    +    (* classifies and counts the numbers                          *)
    +    PROCEDURE countAbundantDeficientAndPerfect;
    +        VAR   n, pdSum       : INTEGER;
    +        BEGIN
    +            abundantCount    := 0;
    +            deficientCount   := 0;
    +            perfectCount     := 0;
    +            FOR n := 1 TO maxNumber DO
    +                pdSum := pds[ n ];
    +                IF      pdSum < n THEN
    +                    INC( deficientCount )
    +                ELSIF   pdSum = n THEN
    +                    INC( perfectCount )
    +                ELSE (* pdSum > n *)
    +                    INC( abundantCount )
    +                END
    +            END
    +        END countAbundantDeficientAndPerfect;
    +
    +BEGIN
    +    sumDivisors;
    +    countAbundantDeficientAndPerfect;
    +
    +    Out.String( "abundant  " );Out.Int(  abundantCount, 0 );Out.Ln;
    +    Out.String( "deficient " );Out.Int( deficientCount, 0 );Out.Ln;
    +    Out.String( "perfect   " );Out.Int(   perfectCount, 0 );Out.Ln
    +END AbundantDeficientAndPerfect.
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/PHP/abundant-deficient-and-perfect-number-classifications.php b/Task/Abundant-deficient-and-perfect-number-classifications/PHP/abundant-deficient-and-perfect-number-classifications.php
    new file mode 100644
    index 0000000000..dd72f9400c
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/PHP/abundant-deficient-and-perfect-number-classifications.php
    @@ -0,0 +1,27 @@
    + $i + 1)
    +    $a_count++;
    +  else if ($d_sum <= $i)
    +    $d_count++;
    +  else
    +    $p_count++;
    +}
    +echo 'Up to '.MAX_NUMBER.PHP_EOL;
    +echo 'Number of abundants :'.str_pad($a_count, 6, " ", STR_PAD_LEFT).PHP_EOL;
    +echo 'Number of perfects  :'.str_pad($p_count, 6, " ", STR_PAD_LEFT).PHP_EOL;
    +echo 'Number of deficients:'.str_pad($d_count, 6, " ", STR_PAD_LEFT).PHP_EOL;
    +?>
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Pascal-P/abundant-deficient-and-perfect-number-classifications.pas b/Task/Abundant-deficient-and-perfect-number-classifications/Pascal-P/abundant-deficient-and-perfect-number-classifications.pas
    new file mode 100644
    index 0000000000..fdf657a2cc
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Pascal-P/abundant-deficient-and-perfect-number-classifications.pas
    @@ -0,0 +1,34 @@
    +program abundantetc(output);
    +(* Abundant, deficient and perfect number classifications *)
    +
    +const
    +  maxnumber = 20000;
    +var
    +  pds: array [1 .. maxnumber] of integer;
    +  i, j, acount, dcount, pcount, divsrsum: integer;
    +begin
    +  acount := 0; dcount := 0; pcount := 0;
    +  pds[1] := 0;
    +  for i := 2 to maxnumber do pds[i] := 1;
    +  for i := 2 to maxnumber do
    +  begin
    +    j := i + i;
    +    while j <= maxnumber do
    +    begin
    +      pds[j] := pds[j] + i;
    +      j := j + i;
    +    end;
    +  end;
    +  (* Classify the numbers and count each type *)
    +  for i := 1 to maxnumber do
    +  begin
    +    divsrsum := pds[i];
    +    if divsrsum > i then acount := acount + 1
    +    else if divsrsum < i then dcount := dcount + 1
    +    else pcount := pcount + 1;
    +  end;
    +  writeln('Up to', maxnumber: 6);
    +  writeln('Number of abundants :', acount: 6);
    +  writeln('Number of perfects  :', pcount: 6);
    +  writeln('Number of deficients:', dcount: 6);
    +end.
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-1.ps1 b/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-1.ps1
    new file mode 100644
    index 0000000000..010bc23ece
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-1.ps1
    @@ -0,0 +1,33 @@
    +function Get-ProperDivisorSum ( [int]$N )
    +    {
    +    If ( $N -lt 2 ) { return 0 }
    +
    +    $Sum = 1
    +    If ( $N -gt 3 )
    +        {
    +        $SqrtN = [math]::Sqrt( $N )
    +        ForEach ( $Divisor in 2..$SqrtN )
    +            {
    +            If ( $N % $Divisor -eq 0 ) { $Sum += $Divisor + $N / $Divisor }
    +            }
    +        If ( $N % $SqrtN -eq 0 ) { $Sum -= $SqrtN }
    +        }
    +    return $Sum
    +    }
    +
    +
    +$Deficient = $Perfect = $Abundant = 0
    +
    +ForEach ( $N in 1..20000 )
    +    {
    +    Switch ( [math]::Sign( ( Get-ProperDivisorSum $N ) - $N ) )
    +        {
    +        -1 { $Deficient++ }
    +         0 { $Perfect++   }
    +         1 { $Abundant++  }
    +        }
    +    }
    +
    +"Deficient: $Deficient"
    +"Perfect  : $Perfect"
    +"Abundant : $Abundant"
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-2.ps1 b/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-2.ps1
    new file mode 100644
    index 0000000000..74593a216c
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-2.ps1
    @@ -0,0 +1,56 @@
    +function Get-NumberClassification
    +{
    +    [CmdletBinding()]
    +    [OutputType([PSCustomObject])]
    +    Param
    +    (
    +        [Parameter(Mandatory=$true,
    +                   ValueFromPipeline=$true,
    +                   ValueFromPipelineByPropertyName=$true,
    +                   Position=0)]
    +        [int]
    +        $Number
    +    )
    +
    +    Begin
    +    {
    +        function Get-ProperDivisorSum ([int]$Number)
    +        {
    +            if ($Number -lt 2) {return 0}
    +
    +            $sum = 1
    +
    +            if ($Number -gt 3)
    +            {
    +                $sqrtNumber = [Math]::Sqrt($Number)
    +
    +                foreach ($divisor in 2..$sqrtNumber)
    +                {
    +                    if ($Number % $divisor -eq 0) {$sum += $divisor + $Number / $divisor}
    +                }
    +
    +                if ($Number % $sqrtNumber -eq 0) {$sum -= $sqrtNumber}
    +            }
    +
    +            $sum
    +        }
    +
    +        [System.Collections.ArrayList]$numbers = @()
    +    }
    +    Process
    +    {
    +        switch ([Math]::Sign((Get-ProperDivisorSum $Number) - $Number))
    +        {
    +            -1 { [void]$numbers.Add([PSCustomObject]@{Class="Deficient"; Number=$Number}) }
    +             0 { [void]$numbers.Add([PSCustomObject]@{Class="Perfect"  ; Number=$Number}) }
    +             1 { [void]$numbers.Add([PSCustomObject]@{Class="Abundant" ; Number=$Number}) }
    +        }
    +    }
    +    End
    +    {
    +        $numbers | Group-Object  -Property Class |
    +                   Select-Object -Property Count,
    +                                           @{Name='Class' ; Expression={$_.Name}},
    +                                           @{Name='Number'; Expression={$_.Group.Number}}
    +    }
    +}
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-3.ps1 b/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-3.ps1
    new file mode 100644
    index 0000000000..fd9ab5621c
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/PowerShell/abundant-deficient-and-perfect-number-classifications-3.ps1
    @@ -0,0 +1 @@
    +1..20000 | Get-NumberClassification
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Uiua/abundant-deficient-and-perfect-number-classifications.uiua b/Task/Abundant-deficient-and-perfect-number-classifications/Uiua/abundant-deficient-and-perfect-number-classifications.uiua
    new file mode 100644
    index 0000000000..cba50fafa9
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Uiua/abundant-deficient-and-perfect-number-classifications.uiua
    @@ -0,0 +1,11 @@
    +# Given a positive integer, find the divisors
    +Divs ← (
    +  ⇡₁⌊√⊸∘           # n -- n trial_divisors
    +  ⊙(⇌÷) ⟜∘ +1⊚=0⊸◿ # partition into small, large divisors
    +  ⊂↘¯=◡(∩⊢⊣)       # join the arrays, but compensate for squares
    +)
    +
    +ProperSum ← /+↘¯1 Divs
    +Class     ← ± -⟜ProperSum
    +
    +&p $"_ deficient, _ perfect, _ abundant." °⊟₃ ⊕⧻ ⊸⊛ ≡Class ⇡₁2e4
    diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/VBScript/abundant-deficient-and-perfect-number-classifications.vbs b/Task/Abundant-deficient-and-perfect-number-classifications/VBScript/abundant-deficient-and-perfect-number-classifications.vbs
    new file mode 100644
    index 0000000000..17ddc48cbf
    --- /dev/null
    +++ b/Task/Abundant-deficient-and-perfect-number-classifications/VBScript/abundant-deficient-and-perfect-number-classifications.vbs
    @@ -0,0 +1,23 @@
    +Deficient = 0
    +Perfect = 0
    +Abundant = 0
    +For i = 1 To 20000
    +	sum = 0
    +	For n = 1 To 20000
    +		If n < i Then
    +			If i Mod n = 0 Then
    +				sum = sum + n
    +			End If
    +		End If
    +	Next
    +	If sum < i Then
    +		Deficient = Deficient + 1
    +	ElseIf sum = i Then
    +		Perfect = Perfect + 1
    +	ElseIf sum > i Then
    +		Abundant = Abundant + 1
    +	End If
    +Next
    +WScript.Echo "Deficient = " & Deficient & vbCrLf &_
    +			 "Perfect = " & Perfect & vbCrLf &_
    +			 "Abundant = " & Abundant
    diff --git a/Task/Abundant-odd-numbers/ANSI-BASIC/abundant-odd-numbers.basic b/Task/Abundant-odd-numbers/ANSI-BASIC/abundant-odd-numbers.basic
    new file mode 100644
    index 0000000000..9f7c01e624
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/ANSI-BASIC/abundant-odd-numbers.basic
    @@ -0,0 +1,49 @@
    +100 REM Abundant odd numbers
    +110 DECLARE EXTERNAL FUNCTION DivisorSum
    +120 REM first 25 odd abundant numbers
    +130 LET OddNumber = 1
    +140 LET ACount = 0
    +150 LET DSum = 0
    +160 PRINT "The first 25 abundant odd numbers:"
    +170 DO WHILE ACount < 25
    +180    LET DSum = DivisorSum(OddNumber)
    +190    IF DSum > OddNumber THEN
    +200       LET ACount = Acount + 1
    +210       PRINT USING "######": OddNumber;
    +220       PRINT " proper divisor sum: ";
    +230       PRINT USING "######": DSum
    +240    END IF
    +250    LET OddNumber = OddNumber + 2
    +260 LOOP
    +270 REM 1000th odd abundant number
    +280 DO WHILE ACount < 1000
    +290    LET DSum = DivisorSum(OddNumber)
    +300    IF DSum > OddNumber THEN LET ACount = Acount + 1
    +310    LET OddNumber = OddNumber + 2
    +320 LOOP
    +330 PRINT "1000th abundant odd number:"
    +340 PRINT "   "; OddNumber - 2; "proper divisor sum:"; DSum
    +350 REM first odd abundant number > 1000000000
    +360 LET OddNumber = 1000000001
    +370 LET Found = 0
    +380 DO WHILE Found = 0
    +390    LET DSum = DivisorSum(OddNumber)
    +400    IF DSum > OddNumber THEN
    +410       LET Found = 1
    +420       PRINT "First abundant odd number > 1 000 000 000:"
    +430       PRINT "   "; OddNumber; "proper divisor sum:"; DSum
    +440    END IF
    +450    LET OddNumber = OddNumber + 2
    +460 LOOP
    +470 END
    +480 External Function DivisorSum(N)
    +490 LET Sum = 1
    +500 FOR D = 2 TO INT(SQR(N))
    +510    IF MOD(N, D) = 0 THEN
    +520       LET Sum = Sum + D
    +530       LET OtherD = INT(N / D)
    +540       IF OtherD <> D THEN LET Sum = Sum + OtherD
    +550    END IF
    +560 NEXT D
    +570 LET DivisorSum = Sum
    +580 END FUNCTION
    diff --git a/Task/Abundant-odd-numbers/Ada/abundant-odd-numbers.adb b/Task/Abundant-odd-numbers/Ada/abundant-odd-numbers.adb
    new file mode 100644
    index 0000000000..a393c7c42a
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Ada/abundant-odd-numbers.adb
    @@ -0,0 +1,57 @@
    +with Ada.Text_IO, Generic_Divisors;
    +
    +procedure Odd_Abundant is
    +   function Same(P: Positive) return Positive is (P);
    +
    +   package Divisor_Sum is new Generic_Divisors
    +     (Result_Type => Natural, None => 0, One => Same, Add =>  "+");
    +
    +   function Abundant(N: Positive) return Boolean is
    +      (Divisor_Sum.Process(N) > N);
    +
    +   package NIO is new Ada.Text_IO.Integer_IO(Natural);
    +
    +   Current: Positive := 1;
    +
    +   procedure Print_Abundant_Line
    +     (Idx: Positive; N: Positive; With_Idx: Boolean:= True) is
    +   begin
    +      if With_Idx then
    +     NIO.Put(Idx, 6);  Ada.Text_IO.Put(" |");
    +      else
    +     Ada.Text_IO.Put("   *** |");
    +      end if;
    +      NIO.Put(N, 12); Ada.Text_IO.Put(" | ");
    +      NIO.Put(Divisor_Sum.Process(N), 12); Ada.Text_IO.New_Line;
    +   end Print_Abundant_Line;
    +
    +begin
    +   -- the first 25 abundant odd numbers
    +   Ada.Text_IO.Put_Line(" index |      number | proper divisor sum ");
    +   Ada.Text_IO.Put_Line("-------+-------------+--------------------");
    +   for I in 1 .. 25 loop
    +      while not Abundant(Current) loop
    +     Current := Current + 2;
    +      end loop;
    +      Print_Abundant_Line(I, Current);
    +      Current := Current + 2;
    +   end loop;
    +
    +   -- the one thousandth abundant odd number
    +   Ada.Text_IO.Put_Line("-------+-------------+--------------------");
    +   for I in 26 .. 1_000 loop
    +      Current := Current + 2;
    +      while not Abundant(Current) loop
    +     Current := Current + 2;
    +      end loop;
    +   end loop;
    +   Print_Abundant_Line(1000, Current);
    +
    +   -- the first abundant odd number greater than 10**9
    +   Ada.Text_IO.Put_Line("-------+-------------+--------------------");
    +   Current := 10**9+1;
    +   while not Abundant(Current) loop
    +      Current := Current + 2;
    +   end loop;
    +   Print_Abundant_Line(1, Current, False);
    +end Odd_Abundant;
    diff --git a/Task/Abundant-odd-numbers/BQN/abundant-odd-numbers.bqn b/Task/Abundant-odd-numbers/BQN/abundant-odd-numbers.bqn
    new file mode 100644
    index 0000000000..703a5b4dd2
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/BQN/abundant-odd-numbers.bqn
    @@ -0,0 +1,20 @@
    +Divisors ← {
    +  n ← 𝕩 ⋄ r ← ⌊√n
    +  lower ← 1 + /0 = (1↓↕r+1)|¨n
    +  upper ← {n ÷ 𝕩}¨lower
    +  lower ∾ (n = r⋆2)↓⌽upper
    +}
    +
    +Proper ← {(-𝕩) +´ Divisors 𝕩}
    +Abundant ← {𝕩 < Proper 𝕩}
    +
    +kap ← 250_000 # number of candidates to test
    +a ← 1+2×/Abundant¨1+2×↕kap
    +
    +•Out "The first 25 abundant odd numbers:"
    +{•Out (•Fmt 𝕩)∾"; proper sum: "∾•Fmt Proper 𝕩}¨25↑a
    +
    +•Out "The 1000th: "∾(•Fmt 999 ⊑ a)∾"; proper sum: "∾•Fmt Proper 999 ⊑ a
    +
    +big ← {𝕩+2} •_while_(¬Abundant) 1000000001
    +•Out "The first > 1e9: " ∾(•Fmt big)∾"; proper sum: "∾•Fmt Proper big
    diff --git a/Task/Abundant-odd-numbers/COBOL/abundant-odd-numbers.cob b/Task/Abundant-odd-numbers/COBOL/abundant-odd-numbers.cob
    new file mode 100644
    index 0000000000..b71d41d8a1
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/COBOL/abundant-odd-numbers.cob
    @@ -0,0 +1,100 @@
    +IDENTIFICATION DIVISION.
    +       PROGRAM-ID. ABUNDANT-ODD-NUMBERS.
    +
    +       ENVIRONMENT DIVISION.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01  WS-VARIABLES.
    +           05  WS-ODD-NUM              PIC 9(10).
    +           05  WS-TO-DIVIDE            PIC 9(10).
    +           05  WS-REMAINDER            PIC 9(10).
    +           05  WS-SUM                  PIC 9(10).
    +           05  WS-RESULT-COUNT         PIC 9(5) VALUE 0.
    +           05  WS-LIST-INDEX           PIC 9(5) VALUE 0.
    +           05  WS-START                PIC 9(10).
    +           05  WS-FINISH               PIC 9(10).
    +           05  WS-LIST-SIZE            PIC 9(5).
    +           05  WS-PRINT-ONE            PIC X VALUE 'N'.
    +
    +       01  WS-DIVISOR-LIST.
    +           05  WS-DIVISOR OCCURS 1000 TIMES PIC 9(10).
    +
    +       01  WS-DISPLAY-FIELDS.
    +           05  WS-DISPLAY-NUM          PIC Z(5)9.
    +           05  WS-DISPLAY-SUM          PIC Z(5)9.
    +
    +       PROCEDURE DIVISION.
    +       MAIN-PROCEDURE.
    +           DISPLAY "First 24: ".
    +           MOVE 1 TO WS-START.
    +           MOVE 100000 TO WS-FINISH.
    +           MOVE 25 TO WS-LIST-SIZE.
    +           MOVE 'N' TO WS-PRINT-ONE.
    +           PERFORM ABUNDANT-ODD.
    +
    +           DISPLAY " ".
    +           DISPLAY " ".
    +           DISPLAY "Thousandth: ".
    +           MOVE 0 TO WS-RESULT-COUNT.
    +           MOVE 1 TO WS-START.
    +           MOVE 2500000 TO WS-FINISH.
    +           MOVE 1000 TO WS-LIST-SIZE.
    +           MOVE 'Y' TO WS-PRINT-ONE.
    +           PERFORM ABUNDANT-ODD.
    +
    +           DISPLAY " ".
    +           DISPLAY " ".
    +           DISPLAY "First over 1bn:".
    +           MOVE 0 TO WS-RESULT-COUNT.
    +           MOVE 1000000001 TO WS-START.
    +           MOVE 2147483647 TO WS-FINISH.
    +           MOVE 1 TO WS-LIST-SIZE.
    +           MOVE 'N' TO WS-PRINT-ONE.
    +           PERFORM ABUNDANT-ODD.
    +
    +           STOP RUN.
    +
    +       ABUNDANT-ODD.
    +           MOVE WS-START TO WS-ODD-NUM.
    +           IF FUNCTION MOD(WS-ODD-NUM, 2) = 0
    +               ADD 1 TO WS-ODD-NUM
    +           END-IF.
    +
    +           PERFORM UNTIL WS-ODD-NUM >= WS-FINISH
    +                      OR WS-RESULT-COUNT >= WS-LIST-SIZE
    +               MOVE 0 TO WS-LIST-INDEX
    +               MOVE 0 TO WS-SUM
    +
    +               PERFORM VARYING WS-TO-DIVIDE FROM 1 BY 2
    +                   UNTIL WS-TO-DIVIDE >= WS-ODD-NUM
    +                   DIVIDE WS-ODD-NUM BY WS-TO-DIVIDE
    +                       GIVING WS-REMAINDER
    +                       REMAINDER WS-REMAINDER
    +                   END-DIVIDE
    +
    +                   IF WS-REMAINDER = 0
    +                       ADD 1 TO WS-LIST-INDEX
    +                       MOVE WS-TO-DIVIDE TO WS-DIVISOR(WS-LIST-INDEX)
    +                       ADD WS-TO-DIVIDE TO WS-SUM
    +                   END-IF
    +               END-PERFORM
    +
    +               IF WS-SUM > WS-ODD-NUM
    +                   ADD 1 TO WS-RESULT-COUNT
    +                   IF WS-PRINT-ONE = 'N'
    +                       MOVE WS-ODD-NUM TO WS-DISPLAY-NUM
    +                       MOVE WS-SUM TO WS-DISPLAY-SUM
    +                       DISPLAY WS-DISPLAY-NUM " <= " WS-DISPLAY-SUM
    +                   END-IF
    +               END-IF
    +
    +               IF WS-PRINT-ONE = 'Y'
    +                   AND WS-RESULT-COUNT >= WS-LIST-SIZE
    +                   MOVE WS-ODD-NUM TO WS-DISPLAY-NUM
    +                   MOVE WS-SUM TO WS-DISPLAY-SUM
    +                   DISPLAY WS-DISPLAY-NUM " <= " WS-DISPLAY-SUM
    +               END-IF
    +
    +               ADD 2 TO WS-ODD-NUM
    +           END-PERFORM.
    diff --git a/Task/Abundant-odd-numbers/Crystal/abundant-odd-numbers.cr b/Task/Abundant-odd-numbers/Crystal/abundant-odd-numbers.cr
    new file mode 100644
    index 0000000000..d5beac4356
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Crystal/abundant-odd-numbers.cr
    @@ -0,0 +1,30 @@
    +def sum_proper_odd_divisors (n)
    +  √n = Math.isqrt(n)
    +  z = n.class.zero
    +  sum = z+1
    +  (z+3 .. √n).step(2) do |i|
    +    if n % i == 0
    +      sum += i + (i == (j = n // i) ? 0 : j)
    +    end
    +  end
    +  sum
    +end
    +
    +def abunseq (start=1)
    +  start += 1 unless start.odd?
    +  (start..).step(2).each.select {|n| n < sum_proper_odd_divisors(n) }
    +end
    +
    +iter = abunseq
    +puts "First 25:"
    +iter.first(25).each do |aon|
    +  printf "%6d  (%d)\n", aon, sum_proper_odd_divisors(aon)
    +end
    +
    +n1k = iter.skip(999-25).next
    +raise "?" if n1k.is_a?(Iterator::Stop)
    +print "\nThe 1000th: ", n1k, " (", sum_proper_odd_divisors(n1k), ")"
    +
    +n1b = abunseq(1_000_000_000).next
    +raise "?" if n1b.is_a?(Iterator::Stop)
    +print "\nThe first > 1B: ", n1b, " (", sum_proper_odd_divisors(n1b), ")\n"
    diff --git a/Task/Abundant-odd-numbers/Pascal/abundant-odd-numbers.pas b/Task/Abundant-odd-numbers/Free-Pascal-Lazarus/abundant-odd-numbers.pas
    similarity index 100%
    rename from Task/Abundant-odd-numbers/Pascal/abundant-odd-numbers.pas
    rename to Task/Abundant-odd-numbers/Free-Pascal-Lazarus/abundant-odd-numbers.pas
    diff --git a/Task/Abundant-odd-numbers/K/abundant-odd-numbers.k b/Task/Abundant-odd-numbers/K/abundant-odd-numbers.k
    new file mode 100644
    index 0000000000..26ff10cb5b
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/K/abundant-odd-numbers.k
    @@ -0,0 +1,20 @@
    +divs: {
    +    r: _%x;
    +    lower: 1 + &0 = (1 + !r)!' x;
    +    upper: ({(-y)!x}[x;])' lower;
    +    lower, (x = r*r)_|upper}
    +
    +proper: {(-x) +/ divs x}
    +abundant: {x < proper x}
    +
    +kap: 250000 /number of candidates to test; tweak until result is above 1k
    +
    +n: 1+2*!kap
    +a: n[&abundant' n]
    +
    +`0: "The first 25 abundant odd numbers:"
    +nulls: {`0: ($x), "; proper sum: ", $proper x}' 25#a
    +`0: "The 1000th: ", ($a[999]), "; proper sum: ", $proper a[999]
    +
    +big: {~abundant x} {x+2}/ 1000000001
    +`0: "The first > 1e9: ", ($big), "; proper sum: ", $proper big
    diff --git a/Task/Abundant-odd-numbers/Loglan82/abundant-odd-numbers.loglan82 b/Task/Abundant-odd-numbers/Loglan82/abundant-odd-numbers.loglan82
    new file mode 100644
    index 0000000000..21154c7e94
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Loglan82/abundant-odd-numbers.loglan82
    @@ -0,0 +1,65 @@
    +program AbundantOdd;
    +(* Abundant odd numbers *)
    +
    +var
    +  odd_number, a_count, d_sum: integer,
    +  found: boolean;
    +
    +  (* Returns the sum of the proper divisors of n *)
    +  unit divisor_sum: function (n: integer): integer;
    +  var
    +    sum, d, sqrt_n, other_d: integer;
    +  begin
    +    sum := 1;
    +    sqrt_n := entier(sqrt(n));
    +    for d := 2 to sqrt_n
    +    do
    +      if n mod d = 0
    +      then
    +        sum := sum + d;
    +        other_d := n div d;
    +        if other_d =/= d then sum := sum + other_d fi;
    +      fi;
    +    od;
    +    result := sum;
    +  end divisor_sum;
    +
    +begin
    +  (* first 25 odd abundant numbers *)
    +  odd_number := 1;
    +  a_count := 0;
    +  d_sum := 0;
    +  writeln("The first 25 abundant odd numbers:");
    +  while a_count < 25
    +  do
    +    d_sum := divisor_sum(odd_number);
    +    if d_sum > odd_number
    +    then
    +      a_count := a_count + 1;
    +      writeln(odd_number: 6, " proper divisor sum: ", d_sum: 6);
    +    fi;
    +    odd_number := odd_number + 2;
    +  od;
    +  (* 1000th odd abundant number *)
    +  while a_count < 1000
    +  do
    +    d_sum := divisor_sum(odd_number);
    +    if d_sum > odd_number then a_count := a_count + 1 fi;
    +    odd_number := odd_number + 2
    +  od;
    +  writeln("1000th abundant odd number:");
    +  writeln("   ", odd_number - 2: 1, " proper divisor sum: ", d_sum: 1);
    +  (* First odd abundant number > 1000000000 *)
    +  odd_number := 1000000001;
    +  found := false;
    +  while not found do
    +    d_sum := divisor_sum(odd_number);
    +    if d_sum > odd_number
    +    then
    +      found := true;
    +      writeln("First abundant odd number > 1 000 000 000:");
    +      writeln("   ", odd_number: 1, " proper divisor sum: ", d_sum: 1);
    +    fi;
    +    odd_number := odd_number + 2
    +  od;
    +end AbundantOdd.
    diff --git a/Task/Abundant-odd-numbers/Modula-2/abundant-odd-numbers.mod2 b/Task/Abundant-odd-numbers/Modula-2/abundant-odd-numbers.mod2
    new file mode 100644
    index 0000000000..2a6df42459
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Modula-2/abundant-odd-numbers.mod2
    @@ -0,0 +1,80 @@
    +MODULE AbundantOdd;
    +(* Abundant odd numbers *)
    +FROM SWholeIO IMPORT
    +  WriteInt;
    +FROM STextIO IMPORT
    +  WriteLn, WriteString;
    +FROM RealMath IMPORT
    +  sqrt;
    +
    +VAR
    +  OddNumber, ACount, DSum: CARDINAL;
    +  Found: BOOLEAN;
    +
    +PROCEDURE DivisorSum(N: CARDINAL): CARDINAL;
    +VAR
    +  D, OtherD, Sum: CARDINAL;
    +BEGIN
    +  Sum := 1;
    +  FOR D := 2 TO TRUNC(sqrt(FLOAT(N))) DO
    +    IF N MOD D = 0 THEN
    +      Sum := Sum + D;
    +      OtherD := N DIV D;
    +      IF OtherD <> D THEN
    +        Sum := Sum + OtherD
    +      END;
    +    END;
    +  END;
    +  RETURN Sum
    +END DivisorSum;
    +
    +BEGIN
    +  (* First 25 odd abundant numbers *)
    +  OddNumber := 1;
    +  ACount := 0;
    +  DSum := 0;
    +  WriteString("The first 25 abundant odd numbers:");
    +  WriteLn;
    +  WHILE ACount < 25 DO
    +    DSum := DivisorSum(OddNumber);
    +    IF DSum > OddNumber THEN
    +      ACount := ACount + 1;
    +      WriteInt(OddNumber, 6);
    +      WriteString(" proper divisor sum: ");
    +      WriteInt(DSum, 6);
    +      WriteLn
    +    END;
    +    OddNumber := OddNumber + 2
    +  END;
    +  (* 1000th odd abundant number *)
    +  WHILE ACount < 1000 DO
    +    DSum := DivisorSum(OddNumber);
    +    IF DSum > OddNumber THEN
    +      ACount := ACount + 1
    +    END;
    +    OddNumber := OddNumber + 2
    +  END;
    +  WriteString("1000th abundant odd number:");
    +  WriteLn;
    +  WriteString("   ");
    +  WriteInt(OddNumber - 2, 1);
    +  WriteString(" proper divisor sum: ");
    +  WriteInt(DSum, 1);
    +  WriteLn;
    +  (* First odd abundant number > 1000000000 *)
    +  OddNumber := 1000000001;
    +  Found := FALSE;
    +  WHILE NOT Found DO
    +    DSum := DivisorSum(OddNumber);
    +    IF DSum > OddNumber THEN
    +      Found := TRUE;
    +      WriteString("First abundant odd number > 1 000 000 000:");
    +      WriteLn;
    +      WriteString("   ");
    +      WriteInt(OddNumber, 1);
    +      WriteString(" proper divisor sum: ");
    +      WriteInt(DSum, 1);
    +    END;
    +    OddNumber := OddNumber + 2
    +  END;
    +END AbundantOdd.
    diff --git a/Task/Abundant-odd-numbers/Oberon-07/abundant-odd-numbers.oberon b/Task/Abundant-odd-numbers/Oberon-07/abundant-odd-numbers.oberon
    new file mode 100644
    index 0000000000..d90e21a5a0
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Oberon-07/abundant-odd-numbers.oberon
    @@ -0,0 +1,69 @@
    +MODULE AbundantOddNumbers;
    +    (* find some abundant odd numbers - numbers where the proper divisor sum *)
    +    (*                                  is bigger than the number itself     *)
    +
    +    IMPORT    Out, Math;
    +
    +    (* returns the sum of the proper divisors of n                           *)
    +    PROCEDURE divisorSum( n : INTEGER ) : INTEGER;
    +        VAR   sum, d, otherD : INTEGER;
    +
    +        BEGIN
    +            sum := 1;
    +            FOR d := 2 TO FLOOR( Math.sqrt( FLT( n ) ) ) DO
    +                IF n MOD d = 0 THEN
    +                    INC( sum, d );
    +                    otherD := n DIV d;
    +                    IF otherD # d THEN INC( sum, otherD ) END
    +                END
    +            END;
    +        RETURN sum
    +        END divisorSum;
    +
    +        PROCEDURE doTask;           (* find the numbers required by the task *)
    +            VAR   oddNumber, aCount, dSum : INTEGER;
    +                  found                   : BOOLEAN;
    +            BEGIN
    +
    +                (* first 25 odd abundant numbers                             *)
    +                oddNumber := 1;
    +                aCount    := 0;
    +                dSum      := 0;
    +                Out.String( "The first 25 abundant odd numbers:" );Out.Ln;
    +                WHILE aCount < 25 DO
    +                    dSum := divisorSum( oddNumber );
    +                    IF dSum > oddNumber THEN
    +                        INC( aCount );
    +                        Out.Int( oddNumber, 6 );Out.String( " proper divisor sum: " );Out.Int( dSum, 0 );Out.Ln
    +                    END;
    +                    INC( oddNumber, 2 )
    +                END;
    +
    +                (* 1000th odd abundant number                                *)
    +                WHILE aCount < 1000 DO
    +                    dSum := divisorSum( oddNumber );
    +                    IF dSum > oddNumber THEN
    +                        INC( aCount )
    +                    END;
    +                    INC( oddNumber, 2 )
    +                END;
    +                Out.String( "1000th abundant odd number:" );Out.Ln;Out.String( "    " );
    +                Out.Int( oddNumber - 2, 0 );Out.String( " proper divisor sum: " );Out.Int( dSum, 0 );Out.Ln;
    +
    +                (* first odd abundant number > one billion                   *)
    +                oddNumber := 1000000001;
    +                found     := FALSE;
    +                WHILE ~ found DO
    +                    dSum := divisorSum( oddNumber );
    +                    IF dSum > oddNumber THEN
    +                        found := TRUE;
    +                        Out.String( "First abundant odd number > 1 000 000 000:" );Out.Ln;Out.String( "    " );
    +                        Out.Int( oddNumber, 0 );Out.String( " proper divisor sum: " );Out.Int( dSum, 0 );Out.Ln
    +                    END;
    +                    INC( oddNumber, 2 )
    +                END
    +            END doTask;
    +
    +BEGIN
    +    doTask
    +END AbundantOddNumbers.
    diff --git a/Task/Abundant-odd-numbers/PHP/abundant-odd-numbers.php b/Task/Abundant-odd-numbers/PHP/abundant-odd-numbers.php
    new file mode 100644
    index 0000000000..a5ee26efd5
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/PHP/abundant-odd-numbers.php
    @@ -0,0 +1,53 @@
    + $odd_number) {
    +    $a_count++;
    +    echo str_pad($odd_number, 6, " ", STR_PAD_LEFT).
    +      ' proper divisor sum: '.
    +      str_pad($d_sum, 6, " ", STR_PAD_LEFT).PHP_EOL;
    +  }
    +  $odd_number += 2;
    +}
    +// 1000th odd abundant number
    +while ($a_count < 1000) {
    +  $d_sum = divisor_sum($odd_number);
    +  if ($d_sum > $odd_number)
    +    $a_count++;
    +  $odd_number += 2;
    +}
    +echo '1000th abundant odd number:'.PHP_EOL;
    +echo '    '.($odd_number - 2).' proper divisor sum: '.$d_sum.PHP_EOL;
    +// first odd abundant number > 1000000000
    +$odd_number = 1000000001;
    +$found = false;
    +while (!$found) {
    +  $d_sum = divisor_sum($odd_number);
    +  if ($d_sum > $odd_number) {
    +    $found = true;
    +    echo 'First abundant odd number > 1 000 000 000:'.PHP_EOL;
    +    echo '    '.$odd_number.' proper divisor sum: '.$d_sum.PHP_EOL;
    +  }
    +  $odd_number += 2;
    +}
    +?>
    diff --git a/Task/Abundant-odd-numbers/PL-I/abundant-odd-numbers.pli b/Task/Abundant-odd-numbers/PL-I/abundant-odd-numbers.pli
    new file mode 100644
    index 0000000000..cf63f05fee
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/PL-I/abundant-odd-numbers.pli
    @@ -0,0 +1,39 @@
    +/* Abundant odd numbers (1st part) */
    +
    +abundant_odd:
    +  procedure options(main);
    +  /* first 25 odd abundant numbers */
    +  declare
    +    (odd_number, a_count, d_sum) fixed binary(15);
    +  odd_number = 1;
    +  a_count = 0;
    +  d_sum = 0;
    +  put list('The first 25 abundant odd numbers:');
    +  do while (a_count < 25);
    +    d_sum = divisor_sum(odd_number);
    +    if d_sum > odd_number then do;
    +      a_count = a_count + 1;
    +      put skip edit(odd_number, ' proper divisor sum: ', d_sum)
    +          (f(6), a, f(6));
    +    end;
    +    odd_number = odd_number + 2;
    +  end;
    +
    +  /* returns the sum of the proper divisors of n */
    +  divisor_sum:
    +    procedure (n) returns (fixed binary(15));
    +    declare
    +      (n, sum, d, sqrt_n, other_d) fixed binary(15);
    +    sum = 1;
    +    sqrt_n = sqrt(n);
    +    do d = 2 to sqrt_n;
    +      if mod(n, d) = 0 then do;
    +        sum = sum + d;
    +        other_d = n / d;
    +        if other_d ~= d then
    +          sum = sum + other_d;
    +      end;
    +    end;
    +    return (sum);
    +  end divisor_sum;
    +end abundant_odd;
    diff --git a/Task/Abundant-odd-numbers/Pascal-P/abundant-odd-numbers.pas b/Task/Abundant-odd-numbers/Pascal-P/abundant-odd-numbers.pas
    new file mode 100644
    index 0000000000..1968c93432
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Pascal-P/abundant-odd-numbers.pas
    @@ -0,0 +1,68 @@
    +program abundodd(output);
    +
    +  (* Abundant odd numbers *)
    +
    +var
    +  oddnumber, acount, dsum: integer;
    +  found: boolean;
    +
    +  (* returns the sum of the proper divisors of n *)
    +  function divisorsum(n: integer): integer;
    +  var
    +    sum, d, otherd: integer;
    +  begin
    +    sum := 1;
    +    for d := 2 to trunc(sqrt(n)) do
    +      if n mod d = 0 then
    +      begin
    +        sum := sum + d;
    +        otherd := n div d;
    +        if otherd <> d then
    +          sum := sum + otherd;
    +      end;
    +    divisorsum := sum;
    +  end;
    +
    +begin
    +  (* first 25 odd abundant numbers *)
    +  oddnumber := 1;
    +  acount := 0;
    +  dsum := 0;
    +  writeln('The first 25 abundant odd numbers:');
    +  while acount < 25 do
    +  begin
    +    dsum := divisorsum(oddnumber);
    +    if dsum > oddnumber then
    +    begin
    +      acount := acount + 1;
    +      writeln(oddnumber: 6, ' proper divisor sum: ', dsum: 6);
    +    end;
    +    oddnumber := oddnumber + 2;
    +  end;
    +
    +  (* 1000th odd abundant number - requires 32-bit integer *)
    +  while acount < 1000 do
    +  begin
    +    dsum := divisorsum(oddnumber);
    +    if dsum > oddnumber then
    +      acount := acount + 1;
    +    oddnumber := oddnumber + 2;
    +  end;
    +  writeln('1000th abundant odd number:');
    +  writeln('    ', oddnumber - 2: 1, ' proper divisor sum: ', dsum: 1);
    +  (* first odd abundant number > 1000000000  - requires 32-bit integer *)
    +  oddnumber := 1000000001;
    +  found := false;
    +  while not found do
    +  begin
    +    dsum := divisorsum(oddnumber);
    +    if dsum > oddnumber then
    +    begin
    +      found := true;
    +      writeln('First abundant odd number > 1 000 000 000:');
    +      writeln('    ', oddnumber: 1, ' proper divisor sum: ', dsum: 1);
    +    end;
    +    oddnumber := oddnumber + 2;
    +  end;
    +  (* readln; *)
    +end.
    diff --git a/Task/Abundant-odd-numbers/PowerShell/abundant-odd-numbers.ps1 b/Task/Abundant-odd-numbers/PowerShell/abundant-odd-numbers.ps1
    new file mode 100644
    index 0000000000..b521d170e5
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/PowerShell/abundant-odd-numbers.ps1
    @@ -0,0 +1,57 @@
    +# Abundant odd numbers
    +
    +# Returns the sum of the proper divisors of $N
    +function Divisor-Sum([uint32]$N) {
    +  [uint32]$sum = 1
    +  [uint32]$intSqrtN = [uint32]([Math]::Sqrt($N))
    +  for ($d = 2; $d -le $intSqrtN; $d++) {
    +    # The for loop is used because foreach goes downwards if $intSqrtN < 2
    +    if ($N % $d -eq 0) {
    +      $sum += $d
    +      [uint32]$otherD = $N / $d
    +      if ($otherD -ne $d) {
    +        $sum += $otherD
    +      }
    +    }
    +  }
    +  return $sum
    +}
    +
    +# first 25 odd abundant numbers
    +[uint32]$oddNumber = 1
    +[uint32]$aCount = 0
    +[uint32]$dSum = 0
    +Write-Output "The first 25 abundant odd numbers:"
    +while ($aCount -lt 25) {
    +  $dSum = Divisor-Sum $oddNumber
    +  if ($dSum -gt $oddNumber) {
    +    $aCount++
    +    [string]$out = "{0, 6} proper divisor sum: {1, 6}" -f $oddNumber, $dSum
    +    Write-Output $out
    +  }
    +  $oddNumber += 2
    +}
    +
    +# 1000th odd abundant number
    +while ($aCount -lt 1000) {
    +  $dSum = Divisor-Sum $oddNumber
    +  if ($dSum -gt $oddNumber) {
    +    $aCount++
    +  }
    +  $oddNumber += 2
    +}
    +Write-Output "1000th abundant odd number:"
    +Write-Output "    $($oddNumber - 2) proper divisor sum: $dSum"
    +
    +# first odd abundant number > 1000000000
    +$oddNumber = 1000000001
    +[bool]$found = $false
    +while (-not $found) {
    +  $dSum = Divisor-Sum $oddNumber
    +  if ($dSum -gt $oddNumber) {
    +      $found = $true
    +      Write-Output "First abundant odd number > 1 000 000 000:"
    +      Write-Output "    $oddNumber proper divisor sum: $dSum"
    +  }
    +  $oddNumber += 2
    +}
    diff --git a/Task/Abundant-odd-numbers/QuickBASIC/abundant-odd-numbers.basic b/Task/Abundant-odd-numbers/QuickBASIC/abundant-odd-numbers.basic
    new file mode 100644
    index 0000000000..7f0b6b4b66
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/QuickBASIC/abundant-odd-numbers.basic
    @@ -0,0 +1,54 @@
    +' Abundant odd numbers
    +DECLARE FUNCTION DivisorSum& (N AS LONG)
    +' First 25 odd abundant numbers
    +CONST TRUE% = -1, FALSE% = 0
    +DIM OddNumber AS LONG, Acount AS LONG, DSum AS LONG
    +DIM Found AS INTEGER
    +OddNumber = 1
    +Acount = 0
    +DSum = 0
    +PRINT "The first 25 abundant odd numbers:"
    +DO WHILE Acount < 25
    +  DSum = DivisorSum&(OddNumber)
    +  IF DSum > OddNumber THEN
    +    Acount = Acount + 1
    +    PRINT USING "######"; OddNumber;
    +    PRINT " proper divisor sum: ";
    +    PRINT USING "######"; DSum
    +  END IF
    +  OddNumber = OddNumber + 2
    +LOOP
    +' 1000th odd abundant number
    +DO WHILE Acount < 1000
    +  DSum = DivisorSum&(OddNumber)
    +  IF DSum > OddNumber THEN Acount = Acount + 1
    +  OddNumber = OddNumber + 2
    +LOOP
    +PRINT "1000th abundant odd number:"
    +PRINT "   "; OddNumber - 2; "proper divisor sum:"; DSum
    +' first odd abundant number > 1000000000
    +OddNumber = 1000000001
    +Found = FALSE%
    +DO WHILE NOT Found
    +  DSum = DivisorSum&(OddNumber)
    +  IF DSum > OddNumber THEN
    +    Found = TRUE%
    +    PRINT "First abundant odd number > 1 000 000 000:"
    +    PRINT "   "; OddNumber; "proper divisor sum:"; DSum
    +  END IF
    +  OddNumber = OddNumber + 2
    +LOOP
    +END
    +
    +FUNCTION DivisorSum& (N AS LONG)
    +DIM D AS LONG, OtherD AS LONG, Sum AS LONG
    +Sum = 1
    +FOR D = 2 TO INT(SQR(N))
    +  IF N MOD D = 0 THEN
    +    Sum = Sum + D
    +    OtherD = N \ D
    +    IF OtherD <> D THEN Sum = Sum + OtherD
    +  END IF
    +NEXT D
    +DivisorSum& = Sum
    +END FUNCTION
    diff --git a/Task/Abundant-odd-numbers/Rebol/abundant-odd-numbers.rebol b/Task/Abundant-odd-numbers/Rebol/abundant-odd-numbers.rebol
    new file mode 100644
    index 0000000000..58cb640fe0
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Rebol/abundant-odd-numbers.rebol
    @@ -0,0 +1,51 @@
    +Rebol [
    +    title: "Rosetta code: Abundant odd numbers"
    +    file:  %Abundant_odd_numbers.r3
    +    url:   https://rosettacode.org/wiki/Abundant_odd_numbers
    +    needs: 3.20.0 ;; because of the `prime?` native used
    +    ;@@ https://github.com/Oldes/Rebol3/discussions/140
    +]
    +
    +sum-proper-divisors: function[
    +    "Compute the sum of proper divisors of n"
    +    n [number!]
    +][
    +    db: clear []  ;; List to store divisors
    +    ;; Iterate divisors up to sqrt(n)
    +    for div 1 to integer! square-root n 1 [
    +        if zero? n % div [     ;; If div divides n exactly
    +            append db div      ;; Add the divisor
    +            append db n / div  ;; Add the paired divisor
    +        ]
    +    ]
    +    ;; Sum unique divisors and exclude the number itself
    +    (sum unique db) - n
    +]
    +
    +billion: 1'000'000'000         ;; One billion constant
    +n: ix: 1                       ;; Initialize current number and index
    +
    +print "The first 25 abundant odd numbers:"
    +
    +forever [
    +    n: n + 2                         ;; Move to the next odd number
    +    if prime? n [continue]           ;; Skip primes (never abundant)
    +    prop-div: sum-proper-divisors n  ;; Calculate proper divisor sum
    +    if prop-div <= n [continue]      ;; Not abundant if sum ≤ n
    +
    +    ;; Handle reporting for milestones and early results
    +    case [
    +        ix <= 25 [
    +            print [pad n -5 ":" prop-div]  ;; List first 25 found
    +        ]
    +        ix = 1000 [
    +            print ["1000th abundant odd number:" n ":" prop-div]
    +            n: billion + 1                 ;; Skip ahead
    +        ]
    +        n > billion [
    +            print ["First abundant odd number > 1'000'000'000:" n ":" prop-div]
    +            break                          ;; Exit after this milestone
    +        ]
    +    ]
    +    ++ ix  ;; Increment index of abundant odd numbers found
    +]
    diff --git a/Task/Abundant-odd-numbers/Uiua/abundant-odd-numbers.uiua b/Task/Abundant-odd-numbers/Uiua/abundant-odd-numbers.uiua
    new file mode 100644
    index 0000000000..311e18169e
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/Uiua/abundant-odd-numbers.uiua
    @@ -0,0 +1,7 @@
    +AD ← ◴⊂⟜(⇌÷)▽⤚(=₀◿)⊸(↘1⇡+1⌊⊸√)
    +DS ← /+↘¯1 AD
    +⋅⇌⍢(+2⍥⟜⊂⊸<⊸DS|<1000⋅⧻)1 []
    +⊃(⟜DS⊣|≡⊸DS↙25)
    +
    +⋅⇌⍢(+2⍥⟜⊂⊸<⊸DS|<1⋅⧻)+1 1e9 []
    +⟜DS⊣
    diff --git a/Task/Abundant-odd-numbers/VBA/abundant-odd-numbers.vba b/Task/Abundant-odd-numbers/VBA/abundant-odd-numbers.vba
    new file mode 100644
    index 0000000000..de6dd7e450
    --- /dev/null
    +++ b/Task/Abundant-odd-numbers/VBA/abundant-odd-numbers.vba
    @@ -0,0 +1,63 @@
    +' Abundant odd numbers
    +
    +Function DivisorSum(ByVal N As Long) As Long
    +  ' Returns the sum of the proper divisors of N
    +  Dim Sum As Long, D As Long, OtherD As Long
    +  Sum = 1
    +  For D = 2 To Int(Sqr(N))
    +    If N Mod D = 0 Then
    +      Sum = Sum + D
    +      OtherD = N \ D
    +      If OtherD <> D Then Sum = Sum + OtherD
    +    End If
    +  Next D
    +  DivisorSum = Sum
    +End Function
    +
    +Function FormatLong(ByVal Num As Long, L As Integer) As String
    +  Dim S As String
    +  S = Trim(Str(Num))
    +  If Len(S) > L Then
    +    FormatLong = String(L, "#")
    +  Else
    +    FormatLong = Right(String(L, " ") & S, L)
    +  End If
    +End Function
    +
    +Sub AbundantOddMain()
    +  Dim OddNumber As Long, ACount As Long, DSum As Long
    +  Dim Found As Boolean
    +  ' first 25 odd abundant numbers
    +  OddNumber = 1
    +  ACount = 0
    +  DSum = 0
    +  Debug.Print "The first 25 abundant odd numbers:"
    +  Do While ACount < 25
    +    DSum = DivisorSum(OddNumber)
    +    If DSum > OddNumber Then
    +      ACount = ACount + 1
    +      Debug.Print FormatLong(OddNumber, 6) & " proper divisor sum: " & FormatLong(DSum, 6)
    +    End If
    +    OddNumber = OddNumber + 2
    +  Loop
    +  ' 1000th odd abundant number
    +  Do While ACount < 1000
    +    DSum = DivisorSum(OddNumber)
    +    If DSum > OddNumber Then ACount = ACount + 1
    +    OddNumber = OddNumber + 2
    +  Loop
    +  Debug.Print "1000th abundant odd number:"
    +  Debug.Print "    " & OddNumber - 2 & " proper divisor sum: " & DSum
    +  ' first odd abundant number > 1000000000
    +  OddNumber = 1000000001
    +  Found = False
    +  Do Until Found
    +    DSum = DivisorSum(OddNumber)
    +    If DSum > OddNumber Then
    +      Found = True
    +      Debug.Print "First abundant odd number > 1 000 000 000:"
    +      Debug.Print "    " & OddNumber & " proper divisor sum: " & DSum
    +    End If
    +    OddNumber = OddNumber + 2
    +  Loop
    +End Sub
    diff --git a/Task/Accumulator-factory/Ada/accumulator-factory-1.adb b/Task/Accumulator-factory/Ada/accumulator-factory-1.adb
    new file mode 100644
    index 0000000000..7a2d4fde69
    --- /dev/null
    +++ b/Task/Accumulator-factory/Ada/accumulator-factory-1.adb
    @@ -0,0 +1,11 @@
    +with Accumulator;
    +with Ada.Text_IO; use Ada.Text_IO;
    +
    +procedure Example is
    +   package A is new Accumulator;
    +   package B is new Accumulator;
    +begin
    +   Put_Line (Integer'Image (A.The_Function (5)));
    +   Put_Line (Integer'Image (B.The_Function (3)));
    +   Put_Line (Float'Image (A.The_Function (2.3)));
    +end;
    diff --git a/Task/Accumulator-factory/Ada/accumulator-factory-2.adb b/Task/Accumulator-factory/Ada/accumulator-factory-2.adb
    new file mode 100644
    index 0000000000..90f6fbbec0
    --- /dev/null
    +++ b/Task/Accumulator-factory/Ada/accumulator-factory-2.adb
    @@ -0,0 +1,11 @@
    +generic package Accumulator is
    +
    +--  This Ada generic package represents an accumulator factory.
    +--  The required function is provided as The_Function.
    +--  The first call to The_Function sets the initial value.
    +--  (Marius Amado-Alves)
    +
    +   function The_Function (X : Integer) return Integer;
    +   function The_Function (X : Integer) return Float;
    +   function The_Function (X : Float) return Float;
    +end;
    diff --git a/Task/Accumulator-factory/Ada/accumulator-factory-3.adb b/Task/Accumulator-factory/Ada/accumulator-factory-3.adb
    new file mode 100644
    index 0000000000..4d3ccb7a5f
    --- /dev/null
    +++ b/Task/Accumulator-factory/Ada/accumulator-factory-3.adb
    @@ -0,0 +1,64 @@
    +package body Accumulator is
    +
    +--  The accumulator lives through three states. It is in Virgin_State
    +--  before any use of The_Function. It changes to Integer_State or
    +--  Float_State, according to the input type used. The accumulation is
    +--  memorized in variable I or F, according to the state. Float_State,
    +--  once reached, is never left. A Float output on an Integer_State is
    +--  simply a conversion, sans effect on state. (Marius Amado-Alves)
    +
    +   type State_T is (Virgin_State, Integer_State, Float_State);
    +   State : State_T := Virgin_State;
    +   I : Integer;
    +   F : Float;
    +
    +   function The_Function (X : Float) return Float is
    +   begin
    +      case State is
    +         when Virgin_State =>
    +            State := Float_State;
    +            F := X;
    +            return F;
    +         when Integer_State =>
    +            State := Float_State;
    +            F := Float (I) + X;
    +            return F;
    +         when Float_State =>
    +            F := F + X;
    +            return F;
    +      end case;
    +   end;
    +
    +   function The_Function (X : Integer) return Float is
    +   begin
    +      case State is
    +         when Virgin_State =>
    +            State := Integer_State;
    +            I := X;
    +            return Float (I);
    +         when Integer_State =>
    +            I := I + X;
    +            return Float (I);
    +         when Float_State =>
    +            F := F + Float (X);
    +            return F;
    +      end case;
    +   end;
    +
    +   function The_Function (X : Integer) return Integer is
    +   begin
    +      case State is
    +         when Virgin_State =>
    +            State := Integer_State;
    +            I := X;
    +            return I;
    +         when Integer_State =>
    +            I := I + X;
    +            return I;
    +         when Float_State =>
    +            F := F + Float (X);
    +            return Integer (F);
    +      end case;
    +   end;
    +
    +end;
    diff --git a/Task/Accumulator-factory/EMal/accumulator-factory.emal b/Task/Accumulator-factory/EMal/accumulator-factory.emal
    index 0204d00a15..b0da805059 100644
    --- a/Task/Accumulator-factory/EMal/accumulator-factory.emal
    +++ b/Task/Accumulator-factory/EMal/accumulator-factory.emal
    @@ -9,7 +9,7 @@ type Number allows int, real
     type AccumulatorUsingNumber
     fun foo ← fun by Number n
       fun g ← Number by Number i
    -    return n += i
    +    return n +← i
       end
       return g
     end
    @@ -26,7 +26,7 @@ fun foo ← fun by var n
       checkType(n)
       fun g ← var by var i
         checkType(i)
    -    return n += i
    +    return n +← i
       end
       return g
     end
    @@ -38,7 +38,7 @@ type Main
     List solutions ← generic[AccumulatorUsingNumber, AccumulatorUsingVar]
     for int i ← 0; i < solutions.length; ++i
       generic solution ← solutions[i]
    -  writeLine("=== solution " + (i + 1) + " ===")
    +  writeLine("[ solution " + (i + 1) + " ]")
       fun x ← :solution.foo(1)
       x(5)
       :solution.foo(3)
    diff --git a/Task/Accumulator-factory/Pluto/accumulator-factory.pluto b/Task/Accumulator-factory/Pluto/accumulator-factory.pluto
    new file mode 100644
    index 0000000000..5baa4348fd
    --- /dev/null
    +++ b/Task/Accumulator-factory/Pluto/accumulator-factory.pluto
    @@ -0,0 +1,11 @@
    +local function accumulator(acc)
    +    return |n| -> do
    +        acc += n
    +        return acc
    +    end
    +end
    +
    +local x = accumulator(1)
    +x(5)
    +accumulator(3)
    +print(x(2.3))
    diff --git a/Task/Accumulator-factory/PowerShell/accumulator-factory-1.ps1 b/Task/Accumulator-factory/PowerShell/accumulator-factory-1.ps1
    new file mode 100644
    index 0000000000..9d6b0bc910
    --- /dev/null
    +++ b/Task/Accumulator-factory/PowerShell/accumulator-factory-1.ps1
    @@ -0,0 +1,4 @@
    +function Get-Accumulator ([double]$Start)
    +{
    +    {param([double]$Plus) return $script:Start += $Plus}.GetNewClosure()
    +}
    diff --git a/Task/Accumulator-factory/PowerShell/accumulator-factory-2.ps1 b/Task/Accumulator-factory/PowerShell/accumulator-factory-2.ps1
    new file mode 100644
    index 0000000000..35ce2c8ca6
    --- /dev/null
    +++ b/Task/Accumulator-factory/PowerShell/accumulator-factory-2.ps1
    @@ -0,0 +1,3 @@
    +$total = Get-Accumulator -Start 1
    +& $total -Plus 5.0 | Out-Null
    +& $total -Plus 2.3
    diff --git a/Task/Accumulator-factory/Rebol/accumulator-factory-1.rebol b/Task/Accumulator-factory/Rebol/accumulator-factory-1.rebol
    new file mode 100644
    index 0000000000..0738505b60
    --- /dev/null
    +++ b/Task/Accumulator-factory/Rebol/accumulator-factory-1.rebol
    @@ -0,0 +1,11 @@
    +make-acc-gen: func [start-val] [
    +    use [state] [
    +        state: start-val
    +        func [value] [
    +            state: state + value
    +        ]
    +    ]
    +]
    +gen: make-acc-gen 1
    +print gen 5   ;== 6
    +print gen 2.3 ;== 8.3
    diff --git a/Task/Accumulator-factory/Rebol/accumulator-factory-2.rebol b/Task/Accumulator-factory/Rebol/accumulator-factory-2.rebol
    new file mode 100644
    index 0000000000..02468d5450
    --- /dev/null
    +++ b/Task/Accumulator-factory/Rebol/accumulator-factory-2.rebol
    @@ -0,0 +1,25 @@
    +;; Define a generator function 'gen' with an optional refinement '/init'
    +;; - 'value' is a required number passed to the function
    +;; - '/init' is an optional refinement for initialization
    +gen: function/with [value [number!] /init] [
    +
    +    ;; If '/init' refinement is used, initialize state and exit immediately
    +    if init [
    +        state: value    ;; Set the initial state to the provided value
    +        exit            ;; Exit, so nothing else in the function is run
    +    ]
    +
    +    ;; If not initializing, add 'value' to 'state'
    +    state: state + value
    +
    +    ;; The function returns the new state each call
    +][state: 0]             ;; 'state' is a local variable, initialized once per definition (persistent closure)
    +
    +;; Initialize the 'state' value of gen to 1 by calling it with '/init'
    +gen/init 1
    +
    +;; Call gen with 5: Adds 5 to state and prints the result (should print 6)
    +print gen 5
    +
    +;; Call gen with 2.3: Adds 2.3 to state and prints the result (should print 8.3)
    +print gen 2.3
    diff --git a/Task/Accumulator-factory/Red/accumulator-factory.red b/Task/Accumulator-factory/Red/accumulator-factory.red
    new file mode 100644
    index 0000000000..9bceca4447
    --- /dev/null
    +++ b/Task/Accumulator-factory/Red/accumulator-factory.red
    @@ -0,0 +1,15 @@
    +Red [ "Accumulator factory - hinjolicious" ]
    +
    +; just a helper func to display informative output
    +demo: function [s b] [print ["^/==" s "==^/^/" mold/only b "^/>>"] do b]
    +
    +demo "Accumulator" [
    +foo: function [init] [
    +	acc: init
    +	closure [val][acc: acc + val]
    +]
    +x: foo 1
    +print x 5 ; 6
    +foo 3 ; no effect!
    +print x 2.3 ; 8.3
    +]
    diff --git a/Task/Accumulator-factory/V-(Vlang)/accumulator-factory.v b/Task/Accumulator-factory/V-(Vlang)/accumulator-factory.v
    new file mode 100644
    index 0000000000..c799934393
    --- /dev/null
    +++ b/Task/Accumulator-factory/V-(Vlang)/accumulator-factory.v
    @@ -0,0 +1,23 @@
    +struct Generator {
    +	mut:
    +    a_n []f64
    +}
    +
    +fn (mut gen Generator) generator(ir f64) fn (f64) f64 {
    +    gen.a_n << ir
    +    id := gen.a_n.len - 1
    +    return fn (mut gen Generator, id int) fn (f64) f64 {
    +        return fn [mut gen, id] (d f64) f64 {
    +            gen.a_n[id] += d
    +            return gen.a_n[id]
    +        }
    +    }(mut gen, id)
    +}
    +
    +fn main() {
    +    mut o_generator := Generator{}
    +    accumulator := o_generator.generator(1)
    +    println(accumulator(5))
    +    o_generator.generator(3)
    +    println(accumulator(2.3))
    +}
    diff --git a/Task/Accumulator-factory/VBScript/accumulator-factory-1.vbs b/Task/Accumulator-factory/VBScript/accumulator-factory-1.vbs
    new file mode 100644
    index 0000000000..0973ec6443
    --- /dev/null
    +++ b/Task/Accumulator-factory/VBScript/accumulator-factory-1.vbs
    @@ -0,0 +1,10 @@
    +class accumulator
    +	dim A
    +	public default function acc(x)
    +		A = A + x
    +		acc = A
    +	end function
    +	public property get accum
    +		accum = A
    +	end property
    +end class
    diff --git a/Task/Accumulator-factory/VBScript/accumulator-factory-2.vbs b/Task/Accumulator-factory/VBScript/accumulator-factory-2.vbs
    new file mode 100644
    index 0000000000..c61351aaad
    --- /dev/null
    +++ b/Task/Accumulator-factory/VBScript/accumulator-factory-2.vbs
    @@ -0,0 +1,8 @@
    +dim a
    +set a = new accumulator
    +x = a( 1 )
    +a 5
    +dim b
    +set b = new accumulator
    +b 3
    +wscript.echo a(2.3)
    diff --git a/Task/Achilles-numbers/Ada/achilles-numbers.adb b/Task/Achilles-numbers/Ada/achilles-numbers.adb
    new file mode 100644
    index 0000000000..054f448da3
    --- /dev/null
    +++ b/Task/Achilles-numbers/Ada/achilles-numbers.adb
    @@ -0,0 +1,205 @@
    +pragma Ada_2022;
    +
    +with Ada.Text_IO;
    +with Ada.Numerics; use Ada.Numerics;
    +with Ada.Numerics.Long_Elementary_Functions;
    +use  Ada.Numerics.Long_Elementary_Functions;
    +with Ada.Strings; use Ada.Strings;
    +with Ada.Strings.Fixed; use Ada.Strings.Fixed;
    +with Prime_Numbers;
    +
    +procedure Achilles_Numbers is
    +
    +   package Long_Integer_Prime_Numbers is new Prime_Numbers
    +     (Integer, 0, 1, 2);
    +   use Long_Integer_Prime_Numbers;
    +
    +   --  A powerful number N is such that for every primer factor P of it
    +   --  P^2 also divides N
    +   --  Is_Powerful function decomposes the given number N in its prime factors
    +   --  and then it checks if each factor squared is a divisor of N
    +   function Is_Powerful (Number : Natural) return Boolean is
    +      List : constant Number_List  := Decompose (Integer (Number));
    +   begin
    +      for Index in List'Range loop
    +         declare
    +            N : constant Long_Long_Integer := Long_Long_Integer (Number);
    +            F : constant Long_Long_Integer := Long_Long_Integer (List (Index));
    +         begin
    +            if N mod (F * F) /= 0 then
    +               return False;
    +            end if;
    +         end;
    +      end loop;
    +
    +      return True;
    +   end Is_Powerful;
    +
    +   --  The Is_Power  function checks if a given number N can be written
    +   --  as a power of two integers that are > 1
    +   --  It makes use of the mathematical expression N = A^B
    +   --  taking Log(N) = Log (A^B) equals to B = Log (N) / Log (A)
    +   --  where the solutions are when B is an integer > 1
    +   function Is_Power (N : Integer) return Boolean is
    +
    +      function Is_Almost_Equal (A : Long_Float;
    +                                B : Long_Float) return Boolean is
    +         Epsilon : constant := 0.000_000_000_000_001;
    +      begin
    +         if abs (A - B) < Epsilon then
    +            return True;
    +         else
    +            return False;
    +         end if;
    +      end Is_Almost_Equal;
    +
    +      A       : Integer := 2;
    +      B       : Long_Float;
    +      Log_Of_N : constant Long_Float := Log (Long_Float (N), 2.0);
    +   begin
    +      if N = 1 then
    +         return True;
    +      end if;
    +
    +      while True loop
    +         B := Log_Of_N / Log (Long_Float (A), 2.0);
    +
    +         if Is_Almost_Equal (B, Long_Float (Integer (B)))
    +           and then Integer (B) > 1
    +         then
    +            return True;
    +         end if;
    +
    +         exit when A * A > N;
    +         A := @ + 1;
    +      end loop;
    +
    +      return False;
    +
    +   end Is_Power;
    +
    +   --  An Achilles number is a powerful number that can't be expressed
    +   --  as a power
    +   function Is_Achilles (N : Integer) return Boolean is
    +   begin
    +      if Is_Powerful (N) then
    +         if Is_Power (N) = False then
    +            return True;
    +         end if;
    +      end if;
    +
    +      return False;
    +   end Is_Achilles;
    +
    +   --  Calculates the Euler totient of a number
    +   function Totient (N : Integer) return Integer is
    +      Tot : Integer := N;
    +      I   : Integer;
    +      N2  : Integer := N;
    +   begin
    +      I := 2;
    +      while I * I <= N2 loop
    +         if N2 mod I = 0 then
    +            while N2 mod I = 0 loop
    +               N2 := N2 / I;
    +            end loop;
    +            Tot := Tot - Tot / I;
    +         end if;
    +
    +         if I = 2 then
    +            I := 1;
    +         end if;
    +         I := I + 2;
    +      end loop;
    +
    +      if N2 > 1 then
    +         Tot := Tot - Tot / N2;
    +      end if;
    +
    +      return Tot;
    +   end Totient;
    +
    +   --  A Strong Achilles number is an Achilles number whose Euler Totient
    +   --  is also an Achilles number
    +   function Is_Strong_Achilles (N : Integer) return Boolean is
    +   begin
    +      if Is_Achilles (N) then
    +         if Is_Achilles (Totient (N)) then
    +            return True;
    +         end if;
    +      end if;
    +
    +      return False;
    +   end Is_Strong_Achilles;
    +
    +   --  Counts the digits in a number by taking the string from
    +   --  its 'Image attribute, trimming it and counting the characters
    +   function Count_Digits (N : Integer) return Natural is
    +      Integer_Str : constant String := Trim (N'Image, Both);
    +   begin
    +      return Integer_Str'Length;
    +   end Count_Digits;
    +
    +begin
    +   --  Find the first 50 Achilles numbers
    +   declare
    +      N : Integer := 1;
    +      Count : Integer := 1;
    +   begin
    +      Ada.Text_IO.Put_Line ("First 50 Achilles numbers:");
    +
    +      while Count <= 50 loop
    +
    +         if Is_Achilles (N) then
    +            Count := @ + 1;
    +            Ada.Text_IO.Put (N'Image & " ");
    +         end if;
    +
    +         N := @ + 1;
    +      end loop;
    +
    +      Ada.Text_IO.New_Line;
    +   end;
    +
    +   --  Find the first 20 Strong Achilles numbers
    +   declare
    +      N : Integer := 1;
    +      Count : Integer := 1;
    +   begin
    +      Ada.Text_IO.Put_Line ("First 20 Strong Achilles numbers:");
    +
    +      while Count <= 20 loop
    +
    +         if Is_Strong_Achilles (N) then
    +            Count := @ + 1;
    +            Ada.Text_IO.Put (N'Image & " ");
    +         end if;
    +
    +         N := @ + 1;
    +      end loop;
    +
    +      Ada.Text_IO.New_Line;
    +   end;
    +
    +   --  Count numbers with digits
    +   declare
    +      Counts : array (2 .. 6) of Natural := [others => 0];
    +      N      : Integer := 1;
    +   begin
    +      Ada.Text_IO.Put_Line ("Number of Achilles numbers with:");
    +
    +      while Count_Digits (N) <= Counts'Last loop
    +
    +         --  Ada.Text_IO.Put_Line ("Testing: " & N'Image);
    +
    +         if Is_Achilles (N) then
    +            Counts (Count_Digits (N)) := @ + 1;
    +         end if;
    +         N := @ + 1;
    +      end loop;
    +
    +      for I in Counts'Range loop
    +         Ada.Text_IO.Put_Line (I'Image & " digits: " & Counts (I)'Image);
    +      end loop;
    +   end;
    +end Achilles_Numbers;
    diff --git a/Task/Achilles-numbers/Arturo/achilles-numbers.arturo b/Task/Achilles-numbers/Arturo/achilles-numbers.arturo
    new file mode 100644
    index 0000000000..939ef41b2a
    --- /dev/null
    +++ b/Task/Achilles-numbers/Arturo/achilles-numbers.arturo
    @@ -0,0 +1,36 @@
    +prettyPrint: function [res][
    +    res | split.every: 10
    +        | loop => [print map & 'x -> pad to :string x 7]
    +]
    +
    +achilles?: function [n][
    +    exps: values tally factors.prime n
    +    and? -> not? some? exps => one?
    +         -> 1 = fold exps [a b] -> gcd @[a b]
    +]
    +
    +phi: function [n][
    +    pf: tally factors.prime n
    +    fold.seed:1 keys pf [res pr][
    +        ipr: to :integer pr
    +        res * (ipr - 1) * ipr ^ dec to :integer pf\[ipr]
    +    ]
    +]
    +
    +n: 50
    +print ["First" n "Achilles numbers:"]
    +2..∞ | select.first: n => achilles?
    +     | prettyPrint
    +
    +print ""
    +print ["First" n "strong Achilles numbers:"]
    +2..∞ | select.first: n 'x -> and? [achilles? x][achilles? phi x]
    +     | prettyPrint
    +
    +print ""
    +counts: 2..1000000 | select => achilles?
    +                   | map => [size digits &]
    +                   | tally
    +
    +loop counts [k v]->
    +    print [k "digits:" v]
    diff --git a/Task/Achilles-numbers/C/achilles-numbers.c b/Task/Achilles-numbers/C/achilles-numbers.c
    new file mode 100644
    index 0000000000..f7ed293f8e
    --- /dev/null
    +++ b/Task/Achilles-numbers/C/achilles-numbers.c
    @@ -0,0 +1,105 @@
    +#include 
    +#include 
    +#include 
    +#include 
    +
    +bool is_prime(int n) {
    +    if (n < 2) return false;
    +    if (n % 2 == 0 && n != 2) return false;
    +    for (int i = 3; i <= sqrt(n); i += 2) {
    +        if (n % i == 0) return false;
    +    }
    +    return true;
    +}
    +
    +int phi(int n) {
    +    int result = n;
    +    for (int p = 2; p * p <= n; p++) {
    +        if (n % p == 0) {
    +            while (n % p == 0) n /= p;
    +            result -= result / p;
    +        }
    +    }
    +    if (n > 1) result -= result / n;
    +    return result;
    +}
    +
    +bool is_powerful(int n) {
    +    int m = n;
    +    for (int p = 2; p * p <= n; p++) {
    +        if (m % p == 0) {
    +            int exp = 0;
    +            while (m % p == 0) {
    +                m /= p;
    +                exp++;
    +            }
    +            if (exp < 2) return false;
    +        }
    +    }
    +    if (m > 1) return false;
    +    return true;
    +}
    +
    +bool is_perfect_power(int n) {
    +    for (int k = 2; k <= log2(n); k++) {
    +        double root = pow(n, 1.0 / k);
    +        int r = round(root);
    +        if (pow(r, k) == n) return true;
    +    }
    +    return false;
    +}
    +
    +bool is_achilles(int n) {
    +    return is_powerful(n) && !is_perfect_power(n);
    +}
    +
    +int main() {
    +    int *achilles = NULL, *strong = NULL;
    +    int a_count = 0, s_count = 0;
    +    int digit_counts[7] = {0};
    +
    +    for (int n = 2; a_count < 50 || s_count < 50; n++) {
    +        if (is_achilles(n)) {
    +            if (a_count < 50){
    +                achilles = realloc(achilles, (a_count+1)*sizeof(int));
    +                achilles[a_count++] = n;
    +            }
    +
    +            int ph = phi(n);
    +            if (is_achilles(ph)) {
    +                if (s_count < 50){
    +                    strong = realloc(strong, (s_count+1)*sizeof(int));
    +                    strong[s_count++] = n;
    +                }
    +            }
    +
    +        }
    +    }
    +
    +    for (int n = 2; n <= 1000000; n++) {
    +        if (is_achilles(n)) {
    +            int digits = floor(log10(n)) + 1;
    +            if (digits >= 2 && digits <= 15) {
    +                digit_counts[digits]++;
    +            }
    +        }
    +    }
    +
    +    printf("First 50 Achilles numbers:\n");
    +    for (int i = 0; i < 50; i++) {
    +        printf("%d ", achilles[i]);
    +    }
    +    printf("\n\n");
    +
    +    printf("First 50 Strong Achilles numbers:\n");
    +    for (int i = 0; i < 50; i++) {
    +        printf("%d ", strong[i]);
    +    }
    +    printf("\n\n");
    +
    +    for (int d = 2; d <= 6; d++) {
    +        printf("Achilles numbers with %d digits: %d\n", d, digit_counts[d]);
    +    }
    +
    +    return 0;
    +}
    diff --git a/Task/Achilles-numbers/COBOL/achilles-numbers.cob b/Task/Achilles-numbers/COBOL/achilles-numbers.cob
    new file mode 100644
    index 0000000000..f5fdc87beb
    --- /dev/null
    +++ b/Task/Achilles-numbers/COBOL/achilles-numbers.cob
    @@ -0,0 +1,257 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. ACHILLES-NUMBERS.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 CONSTANTS.
    +          05 MAX-LIMIT     PIC 9(10) COMP VALUE 100000000.
    +          05 MAX-LIMIT-SQR PIC 9(6) COMP VALUE 10000.
    +          05 MAX-LIMIT-CUB PIC 9(6) COMP VALUE 464.
    +
    +       01 PP-TEMP-DATA.
    +          05 PP-TEMP-COUNT PIC 9(6) COMP VALUE 0.
    +          05 PP-TEMP-TABLE.
    +             10 PP-TEMP OCCURS 1 TO 15000 TIMES DEPENDING ON PP-TEMP-COUNT
    +                            ASCENDING KEY IS PP-TEMP
    +                            PIC 9(10) COMP.
    +
    +       01 PP-FINAL-DATA.
    +          05 PP-COUNT      PIC 9(6) COMP VALUE 0.
    +          05 PP-TABLE.
    +             10 P-POWER    OCCURS 1 TO 15000 TIMES DEPENDING ON PP-COUNT
    +                            ASCENDING KEY IS P-POWER
    +                            INDEXED BY PP-IDX
    +                            PIC 9(10) COMP.
    +
    +       01 ACH-TEMP-DATA.
    +          05 ACH-TEMP-COUNT PIC 9(6) COMP VALUE 0.
    +          05 ACH-TEMP-TABLE.
    +             10 ACH-TEMP   OCCURS 1 TO 35000 TIMES DEPENDING ON ACH-TEMP-COUNT
    +                            ASCENDING KEY IS ACH-TEMP
    +                            PIC 9(10) COMP.
    +
    +       01 ACH-FINAL-DATA.
    +          05 ACH-COUNT     PIC 9(6) COMP VALUE 0.
    +          05 ACH-TABLE.
    +             10 ACHILLES   OCCURS 1 TO 15000 TIMES DEPENDING ON ACH-COUNT
    +                            ASCENDING KEY IS ACHILLES
    +                            INDEXED BY ACH-IDX
    +                            PIC 9(10) COMP.
    +
    +       01 LOOP-VARS.
    +          05 I             PIC 9(6) COMP.
    +          05 B             PIC 9(6) COMP.
    +          05 A             PIC 9(6) COMP.
    +          05 LAST-VAL      PIC 9(10) COMP.
    +
    +       01 CALC-VARS.
    +          05 P             PIC 9(18) COMP.
    +          05 B3            PIC 9(18) COMP.
    +          05 SEARCH-P      PIC 9(10) COMP.
    +
    +       01 TOT-VARS.
    +          05 TOTIENT-IN    PIC 9(10) COMP.
    +          05 TOTIENT-OUT   PIC 9(10) COMP.
    +          05 TOT-I         PIC 9(10) COMP.
    +          05 TOT-N         PIC 9(10) COMP.
    +          05 TOT-Q         PIC 9(10) COMP.
    +          05 TOT-R         PIC 9(10) COMP.
    +          05 SUB-VAL       PIC 9(10) COMP.
    +
    +       01 STRONG-ACH-VARS.
    +          05 FOUND-FLAG    PIC 9 VALUE 0.
    +          05 STRONG-COUNT  PIC 9(4) COMP VALUE 0.
    +          05 STRONG-ACH    OCCURS 30 TIMES PIC 9(10) COMP.
    +
    +       01 REPORT-VARS.
    +          05 DISP-4        PIC ZZZ9.
    +          05 DISP-5        PIC ZZZZ9.
    +          05 DISP-2        PIC Z9.
    +          05 DISP-NUM      PIC Z(9)9.
    +          05 FORMATTED-LINE PIC X(60) VALUE SPACES.
    +          05 LINE-POS      PIC 9(4) COMP VALUE 1.
    +          05 ROW-COUNT     PIC 9(4) COMP VALUE 0.
    +          05 DIGIT-COUNT   PIC 9(10) COMP.
    +          05 D             PIC 9(2) COMP.
    +          05 LOWER-BND     PIC 9(10) COMP.
    +          05 UPPER-BND     PIC 9(10) COMP.
    +
    +       PROCEDURE DIVISION.
    +       MAIN-PARA.
    +           PERFORM GENERATE-PERFECT-POWERS.
    +           PERFORM GENERATE-ACHILLES.
    +           PERFORM PRINT-FIRST-50.
    +           PERFORM PRINT-STRONG-30.
    +           PERFORM PRINT-DIGITS.
    +           STOP RUN.
    +
    +       GENERATE-PERFECT-POWERS.
    +           MOVE 0 TO PP-TEMP-COUNT.
    +           PERFORM VARYING I FROM 2 BY 1 UNTIL I > MAX-LIMIT-SQR
    +               COMPUTE P = I * I
    +               PERFORM UNTIL P >= MAX-LIMIT
    +                   ADD 1 TO PP-TEMP-COUNT
    +                   MOVE P TO PP-TEMP(PP-TEMP-COUNT)
    +                   COMPUTE P = P * I
    +               END-PERFORM
    +           END-PERFORM.
    +
    +           SORT PP-TEMP ON ASCENDING KEY PP-TEMP.
    +
    +           MOVE 0 TO PP-COUNT.
    +           MOVE 0 TO LAST-VAL.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > PP-TEMP-COUNT
    +               IF PP-TEMP(I) NOT = LAST-VAL THEN
    +                   ADD 1 TO PP-COUNT
    +                   MOVE PP-TEMP(I) TO P-POWER(PP-COUNT)
    +                   MOVE PP-TEMP(I) TO LAST-VAL
    +               END-IF
    +           END-PERFORM.
    +
    +       GENERATE-ACHILLES.
    +           MOVE 0 TO ACH-TEMP-COUNT.
    +           PERFORM VARYING B FROM 1 BY 1 UNTIL B > MAX-LIMIT-CUB
    +               COMPUTE B3 = B * B * B
    +               PERFORM VARYING A FROM 1 BY 1 UNTIL A > MAX-LIMIT-SQR
    +                   COMPUTE P = B3 * A * A
    +                   IF P >= MAX-LIMIT THEN
    +                       EXIT PERFORM
    +                   END-IF
    +
    +                   IF P > 1 THEN
    +                       MOVE P TO SEARCH-P
    +                       MOVE 0 TO FOUND-FLAG
    +                       SEARCH ALL P-POWER
    +                           AT END
    +                               MOVE 0 TO FOUND-FLAG
    +                           WHEN P-POWER(PP-IDX) = SEARCH-P
    +                               MOVE 1 TO FOUND-FLAG
    +                       END-SEARCH
    +
    +                       IF FOUND-FLAG = 0 THEN
    +                           ADD 1 TO ACH-TEMP-COUNT
    +                           MOVE P TO ACH-TEMP(ACH-TEMP-COUNT)
    +                       END-IF
    +                   END-IF
    +               END-PERFORM
    +           END-PERFORM.
    +
    +           SORT ACH-TEMP ON ASCENDING KEY ACH-TEMP.
    +
    +           MOVE 0 TO ACH-COUNT.
    +           MOVE 0 TO LAST-VAL.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > ACH-TEMP-COUNT
    +               IF ACH-TEMP(I) NOT = LAST-VAL THEN
    +                   ADD 1 TO ACH-COUNT
    +                   MOVE ACH-TEMP(I) TO ACHILLES(ACH-COUNT)
    +                   MOVE ACH-TEMP(I) TO LAST-VAL
    +               END-IF
    +           END-PERFORM.
    +
    +       CALC-TOTIENT.
    +           MOVE TOTIENT-IN TO TOT-N
    +           MOVE TOTIENT-IN TO TOTIENT-OUT
    +           MOVE 2 TO TOT-I
    +           PERFORM UNTIL TOT-I * TOT-I > TOT-N
    +               DIVIDE TOT-N BY TOT-I GIVING TOT-Q REMAINDER TOT-R
    +               IF TOT-R = 0 THEN
    +                   PERFORM UNTIL TOT-R NOT = 0
    +                       DIVIDE TOT-N BY TOT-I GIVING TOT-Q REMAINDER TOT-R
    +                       IF TOT-R = 0 THEN
    +                           MOVE TOT-Q TO TOT-N
    +                       END-IF
    +                   END-PERFORM
    +                   DIVIDE TOTIENT-OUT BY TOT-I GIVING SUB-VAL
    +                   SUBTRACT SUB-VAL FROM TOTIENT-OUT
    +               END-IF
    +               IF TOT-I = 2 THEN
    +                   MOVE 1 TO TOT-I
    +               END-IF
    +               ADD 2 TO TOT-I
    +           END-PERFORM.
    +           IF TOT-N > 1 THEN
    +               DIVIDE TOTIENT-OUT BY TOT-N GIVING SUB-VAL
    +               SUBTRACT SUB-VAL FROM TOTIENT-OUT
    +           END-IF.
    +
    +       PRINT-FIRST-50.
    +           DISPLAY "First 50 Achilles numbers:".
    +           MOVE SPACES TO FORMATTED-LINE.
    +           MOVE 1 TO LINE-POS.
    +           MOVE 0 TO ROW-COUNT.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 50
    +               MOVE ACHILLES(I) TO DISP-4
    +               STRING DISP-4 " " DELIMITED BY SIZE
    +                      INTO FORMATTED-LINE WITH POINTER LINE-POS
    +               ADD 1 TO ROW-COUNT
    +               IF ROW-COUNT = 10 THEN
    +                   DISPLAY FORMATTED-LINE(1:LINE-POS - 1)
    +                   MOVE SPACES TO FORMATTED-LINE
    +                   MOVE 1 TO LINE-POS
    +                   MOVE 0 TO ROW-COUNT
    +               END-IF
    +           END-PERFORM.
    +
    +       PRINT-STRONG-30.
    +           DISPLAY " ".
    +           DISPLAY "First 30 strong Achilles numbers:".
    +           MOVE 0 TO STRONG-COUNT.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL STRONG-COUNT >= 30 OR I > ACH-COUNT
    +               MOVE ACHILLES(I) TO TOTIENT-IN
    +               PERFORM CALC-TOTIENT
    +
    +               MOVE TOTIENT-OUT TO SEARCH-P
    +               MOVE 0 TO FOUND-FLAG
    +               SEARCH ALL ACHILLES
    +                   AT END
    +                       MOVE 0 TO FOUND-FLAG
    +                   WHEN ACHILLES(ACH-IDX) = SEARCH-P
    +                       MOVE 1 TO FOUND-FLAG
    +               END-SEARCH
    +
    +               IF FOUND-FLAG = 1 THEN
    +                   ADD 1 TO STRONG-COUNT
    +                   MOVE ACHILLES(I) TO STRONG-ACH(STRONG-COUNT)
    +               END-IF
    +           END-PERFORM.
    +
    +           MOVE SPACES TO FORMATTED-LINE.
    +           MOVE 1 TO LINE-POS.
    +           MOVE 0 TO ROW-COUNT.
    +           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 30
    +               MOVE STRONG-ACH(I) TO DISP-5
    +               STRING DISP-5 " " DELIMITED BY SIZE
    +                      INTO FORMATTED-LINE WITH POINTER LINE-POS
    +               ADD 1 TO ROW-COUNT
    +               IF ROW-COUNT = 10 THEN
    +                   DISPLAY FORMATTED-LINE(1:LINE-POS - 1)
    +                   MOVE SPACES TO FORMATTED-LINE
    +                   MOVE 1 TO LINE-POS
    +                   MOVE 0 TO ROW-COUNT
    +               END-IF
    +           END-PERFORM.
    +
    +       PRINT-DIGITS.
    +           DISPLAY " ".
    +           DISPLAY "Number of Achilles numbers with:".
    +           MOVE 10 TO LOWER-BND.
    +           COMPUTE UPPER-BND = 100.
    +           PERFORM VARYING D FROM 2 BY 1 UNTIL D > 8
    +               MOVE 0 TO DIGIT-COUNT
    +               PERFORM VARYING I FROM 1 BY 1 UNTIL I > ACH-COUNT
    +                   IF ACHILLES(I) >= UPPER-BND THEN
    +                       EXIT PERFORM
    +                   END-IF
    +                   IF ACHILLES(I) >= LOWER-BND THEN
    +                       ADD 1 TO DIGIT-COUNT
    +                   END-IF
    +               END-PERFORM
    +
    +               MOVE D TO DISP-2
    +               MOVE DIGIT-COUNT TO DISP-NUM
    +
    +               DISPLAY DISP-2 " digits: " FUNCTION TRIM(DISP-NUM)
    +
    +               MOVE UPPER-BND TO LOWER-BND
    +               COMPUTE UPPER-BND = UPPER-BND * 10
    +           END-PERFORM.
    diff --git a/Task/Achilles-numbers/Crystal/achilles-numbers.cr b/Task/Achilles-numbers/Crystal/achilles-numbers.cr
    new file mode 100644
    index 0000000000..2cb66173f9
    --- /dev/null
    +++ b/Task/Achilles-numbers/Crystal/achilles-numbers.cr
    @@ -0,0 +1,86 @@
    +struct Int
    +  def totient
    +    n = self
    +    return 0 if n < 1
    +    tot = n
    +    i = typeof(n).new(2)
    +    while i*i <= n
    +      if n % i == 0
    +        while n % i == 0
    +          n //= i
    +        end
    +        tot -= tot // i
    +      end
    +      if i == 2; i = 1 end
    +      i += 2
    +    end
    +    if n > 1
    +      tot -= tot // n
    +    end
    +    tot
    +  end
    +end
    +
    +def get_perfect_powers (max_exp)
    +  upper = 10_u64 ** max_exp
    +  pps = Set(UInt64).new
    +  (2_u64 .. Math.isqrt(upper)).each do |i|
    +    p = i
    +    while (p *= i) < upper
    +      pps << p
    +    end
    +  end
    +  pps
    +end
    +
    +def get_achilles (min_exp, max_exp, pps)
    +  lower = 10_u64 ** min_exp
    +  upper = 10_u64 ** max_exp
    +  achilles = Set(UInt64).new
    +  (1_u64 .. Math.cbrt(upper).to_u64).each do |b|
    +    b3 = b * b * b
    +    (1_u64 .. Math.isqrt(upper)).each do |a|
    +      p = b3 * a * a
    +      break if p >= upper
    +      if p >= lower
    +        achilles << p unless p.in? pps
    +      end
    +    end
    +  end
    +  achilles
    +end
    +
    +def tprint (fmt, seq, row_sz)
    +  seq.in_slices_of(row_sz).each do |slice|
    +    puts slice.map {|elt| fmt % { elt } }.join(" ")
    +  end
    +end
    +
    +max_digits = 12
    +pps = get_perfect_powers(max_digits)
    +
    +achilles_set = get_achilles(1, 5, pps)
    +achilles = achilles_set.to_a.sort!
    +
    +puts "First 50 Achilles numbers:"
    +tprint("%4d", achilles.first(50), 10)
    +
    +puts "\nFirst 30 strong Achilles numbers:"
    +strong_achilles = [] of UInt64
    +count = 0
    +n = 0
    +while count < 30
    +  tot = achilles[n].totient
    +  if tot.in? achilles_set
    +    strong_achilles << achilles[n]
    +    count += 1
    +  end
    +  n += 1
    +end
    +tprint("%5d", strong_achilles, 10)
    +
    +puts "\nNumber of Achilles numbers with:"
    +(2..max_digits).each do |d|
    +  ac = get_achilles(d-1, d, pps).size
    +  puts "%2d digits: %d" % { d, ac }
    +end
    diff --git a/Task/Achilles-numbers/JavaScript/achilles-numbers.js b/Task/Achilles-numbers/JavaScript/achilles-numbers.js
    new file mode 100644
    index 0000000000..3f0113554c
    --- /dev/null
    +++ b/Task/Achilles-numbers/JavaScript/achilles-numbers.js
    @@ -0,0 +1,129 @@
    +class AchillesNumbers {
    +    constructor() {
    +        this.pps = new Map(); // Stores perfect powers
    +    }
    +
    +    // Euler's totient function
    +    totient(n) {
    +        let tot = n;
    +        let i = 2;
    +        while (i * i <= n) {
    +            if (n % i === 0) {
    +                // Remove all factors of i
    +                while (n % i === 0) {
    +                    n = Math.floor(n / i);
    +                }
    +                tot -= Math.floor(tot / i);
    +            }
    +            // Handle even/odd step correctly
    +            if (i === 2) {
    +                i = 1;
    +            }
    +            i += 2;
    +        }
    +        // If remaining n is a prime
    +        if (n > 1) {
    +            tot -= Math.floor(tot / n);
    +        }
    +        return tot;
    +    }
    +
    +    // Generate all perfect powers up to 10^maxExp
    +    getPerfectPowers(maxExp) {
    +        const upper = Math.pow(10, maxExp);
    +        const sqrtUpper = Math.floor(Math.sqrt(upper));
    +
    +        for (let i = 2; i <= sqrtUpper; i++) {
    +            let p = i;
    +            while (true) {
    +                p *= i;
    +                if (p >= upper) break;
    +                this.pps.set(Math.floor(p), true);
    +            }
    +        }
    +    }
    +
    +    // Generate all Achilles numbers between 10^minExp and 10^maxExp
    +    getAchilles(minExp, maxExp) {
    +        const lower = Math.pow(10, minExp);
    +        const upper = Math.pow(10, maxExp);
    +        const achilles = new Map();
    +
    +        const cbrtUpper = Math.floor(Math.cbrt(upper));
    +        for (let b = 1; b <= cbrtUpper; b++) {
    +            const b3 = b * b * b;
    +            const sqrtUpper = Math.floor(Math.sqrt(upper));
    +
    +            for (let a = 1; a <= sqrtUpper; a++) {
    +                const p = b3 * a * a;
    +                if (p >= upper) break;
    +
    +                if (p >= lower) {
    +                    if (!this.pps.has(p)) {
    +                        achilles.set(p, true);
    +                    }
    +                }
    +            }
    +        }
    +        return achilles;
    +    }
    +
    +    static main() {
    +        const an = new AchillesNumbers();
    +        const maxDigits = 8;
    +
    +        an.getPerfectPowers(maxDigits);
    +        const achillesSet = an.getAchilles(1, 5);
    +
    +        // Convert map keys to sorted array
    +        const achilles = Array.from(achillesSet.keys()).sort((a, b) => a - b);
    +
    +        // Print first 50 Achilles numbers
    +        console.log("First 50 Achilles numbers:");
    +        let output = "";
    +        for (let i = 0; i < 50; i++) {
    +            output += `${achilles[i].toString().padStart(4)} `;
    +            if ((i + 1) % 10 === 0) {
    +                console.log(output);
    +                output = "";
    +            }
    +        }
    +        if (output) console.log(output);
    +
    +        // Print first 30 strong Achilles numbers
    +        console.log("\nFirst 30 strong Achilles numbers:");
    +        const strongAchilles = [];
    +        let count = 0;
    +        let idx = 0;
    +
    +        while (count < 30 && idx < achilles.length) {
    +            const n = achilles[idx];
    +            const tot = an.totient(n);
    +            if (achillesSet.has(tot)) {
    +                strongAchilles.push(n);
    +                count++;
    +            }
    +            idx++;
    +        }
    +
    +        output = "";
    +        for (let i = 0; i < 30; i++) {
    +            output += `${strongAchilles[i].toString().padStart(5)} `;
    +            if ((i + 1) % 10 === 0) {
    +                console.log(output);
    +                output = "";
    +            }
    +        }
    +        if (output) console.log(output);
    +
    +        // Print counts per digit length
    +        console.log("\nNumber of Achilles numbers with:");
    +        for (let d = 2; d <= maxDigits; d++) {
    +            const ac = an.getAchilles(d - 1, d).size;
    +            console.log(`${d.toString().padStart(2)} digits: ${ac}`);
    +        }
    +    }
    +}
    +
    +// Execute the main method
    +AchillesNumbers.main();
    diff --git a/Task/Ackermann-function/Ada/ackermann-function.adb b/Task/Ackermann-function/Ada/ackermann-function.adb
    new file mode 100644
    index 0000000000..bbabde3783
    --- /dev/null
    +++ b/Task/Ackermann-function/Ada/ackermann-function.adb
    @@ -0,0 +1,21 @@
    +with Ada.Text_IO;  use Ada.Text_IO;
    +
    +procedure Test_Ackermann is
    +   function Ackermann (M, N : Natural) return Natural is
    +   begin
    +      if M = 0 then
    +         return N + 1;
    +      elsif N = 0 then
    +         return Ackermann (M - 1, 1);
    +      else
    +         return Ackermann (M - 1, Ackermann (M, N - 1));
    +      end if;
    +   end Ackermann;
    +begin
    +   for M in 0..3 loop
    +      for N in 0..6 loop
    +         Put (Natural'Image (Ackermann (M, N)));
    +      end loop;
    +      New_Line;
    +   end loop;
    +end Test_Ackermann;
    diff --git a/Task/Ackermann-function/Agena/ackermann-function.agena b/Task/Ackermann-function/Agena/ackermann-function.agena
    new file mode 100644
    index 0000000000..3a0a4d1c93
    --- /dev/null
    +++ b/Task/Ackermann-function/Agena/ackermann-function.agena
    @@ -0,0 +1,39 @@
    +scope # Ackermann function
    +
    +    proc ackermann( m :: number, n :: number ) :: number
    +        feature reminisce; # create a remember table for this procedure
    +                           # it seems the procedure must be global for this statement
    +        return if   m = 0 then n + 1
    +               elif m = 1 then n + 2                   # expand some cases to avoid more
    +               elif m = 2 then 3 + 2 * n               # recursion - as in the Maple
    +               elif m = 3 then 5 + 8 * ( 2 ^ n - 1 )   # Mathematica, etc. samples
    +               elif n = 0 then ackermann( m - 1, 1 )
    +               else ackermann( m - 1, ackermann( m, n - 1 ) )
    +               fi
    +    end;
    +
    +    local constant fmt := seq( " %1.0f", " %2.0f", " %2.0f", " %2.0f"
    +                             , " %3.0f", " %3.0f", " %3.0f", " %4.0f"
    +                             , " %4.0f", " %4.0f", " %4.0f", " %5.0f"
    +                             , " %5.0f", " %5.0f", " %6.0f", " %6.0f"
    +                             , " %6.0f", " %7.0f", " %7.0f", " %7.0f"
    +                             , " %7.0f", " %7.0f", " %7.0f", " %7.0f"
    +                            );
    +    local constant maxN := 20;
    +
    +    printf( "  n" );
    +    for n from 0 to maxN do printf( fmt[ n + 1 ], n ) od;
    +    print();
    +    printf( " m+" );
    +    for n from 0 to 18 do printf( "------", n ) od;
    +    print();
    +
    +    for m from 0 to 3 do
    +        printf( "%2d|", m );
    +        for n from 0 to maxN do
    +            printf( fmt[ n + 1 ], ackermann( m, n ) )
    +        od;
    +        print()
    +    od
    +
    +end
    diff --git a/Task/Ackermann-function/AutoIt/ackermann-function-1.au3 b/Task/Ackermann-function/AutoIt/ackermann-function-1.au3
    new file mode 100644
    index 0000000000..6fec759786
    --- /dev/null
    +++ b/Task/Ackermann-function/AutoIt/ackermann-function-1.au3
    @@ -0,0 +1,11 @@
    +Func Ackermann($m, $n)
    +    If ($m = 0) Then
    +        Return $n+1
    +    Else
    +        If ($n = 0) Then
    +            Return Ackermann($m-1, 1)
    +        Else
    +            return Ackermann($m-1, Ackermann($m, $n-1))
    +        EndIf
    +    EndIf
    +EndFunc
    diff --git a/Task/Ackermann-function/AutoIt/ackermann-function-2.au3 b/Task/Ackermann-function/AutoIt/ackermann-function-2.au3
    new file mode 100644
    index 0000000000..f45c87f759
    --- /dev/null
    +++ b/Task/Ackermann-function/AutoIt/ackermann-function-2.au3
    @@ -0,0 +1,18 @@
    +Global $ackermann[2047][2047] ; Set the size to whatever you want
    +Func Ackermann($m, $n)
    +	If ($ackermann[$m][$n] <> 0) Then
    +		Return $ackermann[$m][$n]
    +	Else
    +		If ($m = 0) Then
    +			$return = $n + 1
    +		Else
    +			If ($n = 0) Then
    +				$return = Ackermann($m - 1, 1)
    +			Else
    +				$return = Ackermann($m - 1, Ackermann($m, $n - 1))
    +			EndIf
    +		EndIf
    +		$ackermann[$m][$n] = $return
    +		Return $return
    +	EndIf
    +EndFunc   ;==>Ackermann
    diff --git a/Task/Ackermann-function/COBOL/ackermann-function.cob b/Task/Ackermann-function/COBOL/ackermann-function.cob
    new file mode 100644
    index 0000000000..8fafd91540
    --- /dev/null
    +++ b/Task/Ackermann-function/COBOL/ackermann-function.cob
    @@ -0,0 +1,32 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. Ackermann.
    +
    +       DATA DIVISION.
    +       LINKAGE SECTION.
    +       01  M          USAGE UNSIGNED-LONG.
    +       01  N          USAGE UNSIGNED-LONG.
    +
    +       01  Return-Val USAGE UNSIGNED-LONG.
    +
    +       PROCEDURE DIVISION USING M N Return-Val.
    +           EVALUATE M ALSO N
    +               WHEN 0 ALSO ANY
    +                   ADD 1 TO N GIVING Return-Val
    +
    +               WHEN NOT 0 ALSO 0
    +                   SUBTRACT 1 FROM M
    +                   CALL "Ackermann" USING BY CONTENT M BY CONTENT 1
    +                       BY REFERENCE Return-Val
    +
    +               WHEN NOT 0 ALSO NOT 0
    +                   SUBTRACT 1 FROM N
    +                   CALL "Ackermann" USING BY CONTENT M BY CONTENT N
    +                       BY REFERENCE Return-Val
    +
    +                   SUBTRACT 1 FROM M
    +                   CALL "Ackermann" USING BY CONTENT M
    +                       BY CONTENT Return-Val BY REFERENCE Return-Val
    +           END-EVALUATE
    +
    +           GOBACK
    +           .
    diff --git a/Task/Ackermann-function/Chapel/ackermann-function.chpl b/Task/Ackermann-function/Chapel/ackermann-function.chpl
    new file mode 100644
    index 0000000000..20b6590fc7
    --- /dev/null
    +++ b/Task/Ackermann-function/Chapel/ackermann-function.chpl
    @@ -0,0 +1,8 @@
    +proc A(m:int, n:int):int {
    +        if m == 0 then
    +                return n + 1;
    +        else if n == 0 then
    +                return A(m - 1, 1);
    +        else
    +                return A(m - 1, A(m, n - 1));
    +}
    diff --git a/Task/Ackermann-function/Emacs-Lisp/ackermann-function.el b/Task/Ackermann-function/Emacs-Lisp/ackermann-function.el
    new file mode 100644
    index 0000000000..cf6cce77b9
    --- /dev/null
    +++ b/Task/Ackermann-function/Emacs-Lisp/ackermann-function.el
    @@ -0,0 +1,5 @@
    +(defun ackermann (m n)
    +  (cond ((zerop m) (1+ n))
    +	((zerop n) (ackermann (1- m) 1))
    +	(t         (ackermann (1- m)
    +			      (ackermann m (1- n))))))
    diff --git a/Task/Ackermann-function/Euphoria/ackermann-function-1.eu b/Task/Ackermann-function/Euphoria/ackermann-function-1.eu
    new file mode 100644
    index 0000000000..cd4d6a4745
    --- /dev/null
    +++ b/Task/Ackermann-function/Euphoria/ackermann-function-1.eu
    @@ -0,0 +1,16 @@
    +function ack(atom m, atom n)
    +    if m = 0 then
    +        return n + 1
    +    elsif m > 0 and n = 0 then
    +        return ack(m - 1, 1)
    +    else
    +        return ack(m - 1, ack(m, n - 1))
    +    end if
    +end function
    +
    +for i = 0 to 3 do
    +    for j = 0 to 6 do
    +        printf( 1, "%5d", ack( i, j ) )
    +    end for
    +    puts( 1, "\n" )
    +end for
    diff --git a/Task/Ackermann-function/Euphoria/ackermann-function-2.eu b/Task/Ackermann-function/Euphoria/ackermann-function-2.eu
    new file mode 100644
    index 0000000000..74b9aed6af
    --- /dev/null
    +++ b/Task/Ackermann-function/Euphoria/ackermann-function-2.eu
    @@ -0,0 +1,12 @@
    +function ackermann(integer m, integer n)
    +  if m=0 then return n+1
    +  elsif m>0 and n=0 then return ackermann(m-1, 1)
    +  elsif m>0 and n>0 then return ackermann(m-1, ackermann(m,n-1))
    +  else return 0
    +  end if
    +  return 0
    +end function
    +
    +? ackermann(0, 0)
    +? ackermann(3, 4)
    +? ackermann(3, 10)
    diff --git a/Task/Ackermann-function/Gleam/ackermann-function.gleam b/Task/Ackermann-function/Gleam/ackermann-function.gleam
    new file mode 100644
    index 0000000000..a7e3dabae4
    --- /dev/null
    +++ b/Task/Ackermann-function/Gleam/ackermann-function.gleam
    @@ -0,0 +1,20 @@
    +pub fn ackermann(m: Int, n: Int) -> Int {
    +  case m, n {
    +    0, n -> n + 1
    +    m, 0 -> ackermann(m - 1, 1)
    +    m, n -> ackermann(m - 1, ackermann(m, n - 1))
    +  }
    +}
    +
    +pub fn main() {
    +  echo ackermann(0, 0)
    +  echo ackermann(0, 4)
    +  echo ackermann(1, 0)
    +  echo ackermann(1, 1)
    +  echo ackermann(2, 1)
    +  echo ackermann(2, 2)
    +  echo ackermann(3, 1)
    +  echo ackermann(3, 3)
    +  echo ackermann(4, 0)
    +  echo ackermann(4, 1)
    +}
    diff --git a/Task/Ackermann-function/HPPPL/ackermann-function.hpppl b/Task/Ackermann-function/HPPPL/ackermann-function.hpppl
    new file mode 100644
    index 0000000000..58ff78bae1
    --- /dev/null
    +++ b/Task/Ackermann-function/HPPPL/ackermann-function.hpppl
    @@ -0,0 +1,17 @@
    +//subAck1();
    +EXPORT Ackermann_function(m,n)
    +BEGIN
    +PRINT;
    + PRINT("Ackermann("+m+","+n+") = "+subAck1(m,n));
    +END;
    +
    +subAck1(m,n)
    +BEGIN
    +CASE
    + IF m<0 OR n<0 THEN "m y n deben ser >=0" END;
    + IF m=0 THEN n+1 END;
    + IF m>0 AND n=0 THEN subAck1((m-1),1); END;
    + IF m>0 AND n>0 THEN subAck1((m-1),subAck1(m,(n-1))); END;
    + DEFAULT RETURN PRINT("ERROR");
    +END;
    +END;
    diff --git a/Task/Ackermann-function/Haxe/ackermann-function.hx b/Task/Ackermann-function/Haxe/ackermann-function.hx
    new file mode 100644
    index 0000000000..e95d735efc
    --- /dev/null
    +++ b/Task/Ackermann-function/Haxe/ackermann-function.hx
    @@ -0,0 +1,20 @@
    +class RosettaDemo
    +{
    +    static public function main()
    +    {
    +        Sys.print(ackermann(3, 4));
    +    }
    +
    +    static function ackermann(m : Int, n : Int)
    +    {
    +        if (m == 0)
    +        {
    +            return n + 1;
    +        }
    +        else if (n == 0)
    +        {
    +            return ackermann(m-1, 1);
    +        }
    +        return ackermann(m-1, ackermann(m, n-1));
    +    }
    +}
    diff --git a/Task/Ackermann-function/Phix/ackermann-function-1.phix b/Task/Ackermann-function/Phix/ackermann-function-1.phix
    index a97f6e3ba8..6947767a02 100644
    --- a/Task/Ackermann-function/Phix/ackermann-function-1.phix
    +++ b/Task/Ackermann-function/Phix/ackermann-function-1.phix
    @@ -1,4 +1,4 @@
    -(phixonline)-->
    +(phixonline)--(notpygments)-->
      function ack(integer m, integer n)
          if m=0 then
              return n+1
    diff --git a/Task/Ackermann-function/Phix/ackermann-function-2.phix b/Task/Ackermann-function/Phix/ackermann-function-2.phix
    index 6080743529..3c54091afd 100644
    --- a/Task/Ackermann-function/Phix/ackermann-function-2.phix
    +++ b/Task/Ackermann-function/Phix/ackermann-function-2.phix
    @@ -1,4 +1,4 @@
    -(phixonline)-->
    +(phixonline)--(notpygments)-->
      -- demo\rosetta\Ackermann.exw
      include mpfr.e
     
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-1.ps1 b/Task/Ackermann-function/PowerShell/ackermann-function-1.ps1
    new file mode 100644
    index 0000000000..f9d21e4e7f
    --- /dev/null
    +++ b/Task/Ackermann-function/PowerShell/ackermann-function-1.ps1
    @@ -0,0 +1,11 @@
    +function ackermann ([long] $m, [long] $n) {
    +    if ($m -eq 0) {
    +        return $n + 1
    +    }
    +
    +    if ($n -eq 0) {
    +        return (ackermann ($m - 1) 1)
    +    }
    +
    +    return (ackermann ($m - 1) (ackermann $m ($n - 1)))
    +}
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-2.ps1 b/Task/Ackermann-function/PowerShell/ackermann-function-2.ps1
    new file mode 100644
    index 0000000000..a8ef2f8842
    --- /dev/null
    +++ b/Task/Ackermann-function/PowerShell/ackermann-function-2.ps1
    @@ -0,0 +1,6 @@
    +foreach ($m in 0..3) {
    +    foreach ($n in 0..6) {
    +        Write-Host -NoNewline ("{0,5}" -f (ackermann $m $n))
    +    }
    +    Write-Host
    +}
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-3.ps1 b/Task/Ackermann-function/PowerShell/ackermann-function-3.ps1
    new file mode 100644
    index 0000000000..cb92013c7d
    --- /dev/null
    +++ b/Task/Ackermann-function/PowerShell/ackermann-function-3.ps1
    @@ -0,0 +1,14 @@
    +function Get-Ackermann ([int64]$m, [int64]$n)
    +{
    +    if ($m -eq 0)
    +    {
    +        return $n + 1
    +    }
    +
    +    if ($n -eq 0)
    +    {
    +        return Get-Ackermann ($m - 1) 1
    +    }
    +
    +    return (Get-Ackermann ($m - 1) (Get-Ackermann $m ($n - 1)))
    +}
    diff --git a/Task/Ackermann-function/PowerShell/ackermann-function-4.ps1 b/Task/Ackermann-function/PowerShell/ackermann-function-4.ps1
    new file mode 100644
    index 0000000000..c43df1d52a
    --- /dev/null
    +++ b/Task/Ackermann-function/PowerShell/ackermann-function-4.ps1
    @@ -0,0 +1,3 @@
    +$ackermann = 0..3 | ForEach-Object {$m = $_; 0..6 | ForEach-Object {Get-Ackermann $m  $_}}
    +
    +$ackermann | Format-Wide {"{0,3}" -f $_} -Column 7 -Force
    diff --git a/Task/Ackermann-function/REXX/ackermann-function.rexx b/Task/Ackermann-function/REXX/ackermann-function.rexx
    new file mode 100644
    index 0000000000..5ef80aa39d
    --- /dev/null
    +++ b/Task/Ackermann-function/REXX/ackermann-function.rexx
    @@ -0,0 +1,83 @@
    +-- 27 Oct 2025
    +include Setting
    +numeric digits 310000
    +
    +say 'ACKERMANN FUNCTION'
    +say version
    +say
    +call Ackermann1
    +call Ackermann2
    +exit
    +
    +Ackermann1:
    +procedure expose glob.
    +say 'Using recursion...'
    +do i=0 to 3
    +   do j=0 to 10
    +      say 'Ackermann('i','j')' '=' Acker1(i,j) Elaps('r')'s'
    +   end
    +end
    +say
    +return
    +
    +Acker1:
    +procedure
    +arg xx,yy
    +select
    +   when xx = 0 then
    +      return yy+1
    +   when yy = 0 then
    +      return Acker1(xx-1,1)
    +   otherwise
    +      return Acker1(xx-1,Acker1(xx,yy-1))
    +end
    +
    +Ackermann2:
    +procedure expose glob.
    +say 'Using closed formulas...'
    +do i=0 to 3
    +   do j=0 to 10
    +      say 'Ackermann('i','j')' '=' Acker2(i,j) Elaps('r')'s'
    +   end
    +end
    +say 'Ackermann(3,100) =' Acker2(3,100) Elaps('r')'s'
    +say 'Ackermann(3,1000) has' Length(Acker2(3,1000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(3,10000) has' Length(Acker2(3,10000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(3,100000) has' Length(Acker2(3,100000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(3,1000000) has' Length(Acker2(3,1000000)) 'digits' Elaps('r')'s'
    +say 'Ackermann(4,0) =' Acker2(4,0) Elaps('r')'s'
    +say 'Ackermann(4,1) =' Acker2(4,1) Elaps('r')'s'
    +say 'Ackermann(4,2) has' Length(Acker2(4,2)) 'digits' Elaps('r')'s'
    +return
    +
    +Acker2:
    +procedure
    +arg xx,yy
    +select
    +   when xx=0 then
    +      rr=yy+1
    +   when xx=1 then
    +      rr=yy+2
    +   when xx=2 then
    +      rr=yy+yy+3
    +   when xx=3 then
    +      rr=2**(yy+3)-3
    +   when xx=4 then
    +      select
    +         when yy=0 then
    +            rr=2**(2**2)-3
    +         when yy=1 then
    +            rr=2**(2**(2**2))-3
    +         when yy=2 then
    +            rr=2**(2**(2**(2**2)))-3
    +         otherwise
    +            rr=0
    +      end
    +   otherwise
    +      rr=0
    +end
    +return rr
    +
    +include Abend
    +-- Elaps
    +include Timer
    diff --git a/Task/Ackermann-function/ReScript/ackermann-function.res b/Task/Ackermann-function/ReScript/ackermann-function.res
    new file mode 100644
    index 0000000000..edb6660918
    --- /dev/null
    +++ b/Task/Ackermann-function/ReScript/ackermann-function.res
    @@ -0,0 +1,15 @@
    +let _m = Sys.argv[2]
    +let _n = Sys.argv[3]
    +
    +let m = int_of_string(_m)
    +let n = int_of_string(_n)
    +
    +let rec a = (m, n) =>
    +  switch (m, n) {
    +  | (0, n) => (n+1)
    +  | (m, 0) => a(m-1, 1)
    +  | (m, n) => a(m-1, a(m, n-1))
    +  }
    +
    +Js.log("ackermann(" ++ _m ++ ", " ++ _n ++ ") = "
    +    ++ string_of_int(a(m, n)))
    diff --git a/Task/Ackermann-function/Rebol/ackermann-function-1.rebol b/Task/Ackermann-function/Rebol/ackermann-function-1.rebol
    new file mode 100644
    index 0000000000..52928c349e
    --- /dev/null
    +++ b/Task/Ackermann-function/Rebol/ackermann-function-1.rebol
    @@ -0,0 +1,7 @@
    +ackermann: func [m n] [
    +    case [
    +        m = 0 [n + 1]
    +        n = 0 [ackermann m - 1 1]
    +        true [ackermann m - 1 ackermann m n - 1]
    +    ]
    +]
    diff --git a/Task/Ackermann-function/Rebol/ackermann-function-2.rebol b/Task/Ackermann-function/Rebol/ackermann-function-2.rebol
    new file mode 100644
    index 0000000000..c6e294cb60
    --- /dev/null
    +++ b/Task/Ackermann-function/Rebol/ackermann-function-2.rebol
    @@ -0,0 +1,16 @@
    +ackermann: func [
    +    m [integer!]
    +    n [integer!]
    +] [
    +    ;; Small-m closed forms
    +    case [
    +        m = 0 [n + 1]
    +        m = 1 [n + 2]
    +        m = 2 [(2 * n) + 3]
    +        m = 3 [
    +            ;; 2^(n+3) - 3
    +            (to integer! power 2 (n + 3)) - 3
    +        ]
    +        ;; m >= 4 causes stack overflow
    +    ]
    +]
    diff --git a/Task/Ackermann-function/Rocq/ackermann-function-1.rocq b/Task/Ackermann-function/Rocq/ackermann-function-1.rocq
    new file mode 100644
    index 0000000000..61c12cc988
    --- /dev/null
    +++ b/Task/Ackermann-function/Rocq/ackermann-function-1.rocq
    @@ -0,0 +1,18 @@
    +Fixpoint ack (m : nat) : nat -> nat :=
    +  fix ack_m (n : nat) : nat :=
    +    match m with
    +      | 0 => S n
    +      | S pm =>
    +        match n with
    +          | 0 => ack pm 1
    +          | S pn => ack pm (ack_m pn)
    +        end
    +    end.
    +
    +
    +(*
    +  Example:
    +    A(3, 2) = 29
    +*)
    +
    +Eval compute in ack 3 2.
    diff --git a/Task/Ackermann-function/Rocq/ackermann-function-2.rocq b/Task/Ackermann-function/Rocq/ackermann-function-2.rocq
    new file mode 100644
    index 0000000000..bf18b5faa4
    --- /dev/null
    +++ b/Task/Ackermann-function/Rocq/ackermann-function-2.rocq
    @@ -0,0 +1,13 @@
    +Require Import Utf8.
    +
    +Section FOLD.
    +  Context {A : Type} (f : A → A) (a : A).
    +  Fixpoint fold (n : nat) : A :=
    +    match n with
    +      | O => a
    +      | S k => f (fold k)
    +    end.
    +End FOLD.
    +
    +Definition ackermann : nat → nat → nat :=
    +  fold (λ g, fold g (g (S O))) S.
    diff --git a/Task/Ackermann-function/Uiua/ackermann-function.uiua b/Task/Ackermann-function/Uiua/ackermann-function.uiua
    new file mode 100644
    index 0000000000..cebcb838cb
    --- /dev/null
    +++ b/Task/Ackermann-function/Uiua/ackermann-function.uiua
    @@ -0,0 +1,7 @@
    +A ←|2.1 (
    +  ◡(×+1>0:>0)
    +  sw(+1pop|A-1:1pop:
    +    |A-1:off(A:-1:))
    +)
    +
    +A 1 1
    diff --git a/Task/Ackermann-function/VBScript/ackermann-function-1.vbs b/Task/Ackermann-function/VBScript/ackermann-function-1.vbs
    new file mode 100644
    index 0000000000..a9a32ec1ee
    --- /dev/null
    +++ b/Task/Ackermann-function/VBScript/ackermann-function-1.vbs
    @@ -0,0 +1,20 @@
    +option explicit
    +'~ dim depth
    +function ack(m, n)
    +	'~ wscript.stdout.write depth & " "
    +	if m = 0 then
    +		'~ depth = depth + 1
    +		ack = n + 1
    +		'~ depth = depth - 1
    +	elseif m > 0 and n = 0 then
    +		'~ depth = depth + 1
    +		ack = ack(m - 1, 1)
    +		'~ depth = depth - 1
    +	'~ elseif m > 0 and n > 0 then
    +	else
    +		'~ depth = depth + 1
    +		ack = ack(m - 1, ack(m, n - 1))
    +		'~ depth = depth - 1
    +	end if
    +	
    +end function
    diff --git a/Task/Ackermann-function/VBScript/ackermann-function-2.vbs b/Task/Ackermann-function/VBScript/ackermann-function-2.vbs
    new file mode 100644
    index 0000000000..3d186bb0ed
    --- /dev/null
    +++ b/Task/Ackermann-function/VBScript/ackermann-function-2.vbs
    @@ -0,0 +1,5 @@
    +wscript.echo ack( 1, 10 )
    +'~ depth = 0
    +wscript.echo ack( 2, 1 )
    +'~ depth = 0
    +wscript.echo ack( 4, 4 )
    diff --git a/Task/Active-Directory-Connect/AutoIt/active-directory-connect.au3 b/Task/Active-Directory-Connect/AutoIt/active-directory-connect.au3
    new file mode 100644
    index 0000000000..21c0bf11dc
    --- /dev/null
    +++ b/Task/Active-Directory-Connect/AutoIt/active-directory-connect.au3
    @@ -0,0 +1,2 @@
    + #include 
    +_AD_Open()
    diff --git a/Task/Active-Directory-Connect/VBScript/active-directory-connect.vbs b/Task/Active-Directory-Connect/VBScript/active-directory-connect.vbs
    new file mode 100644
    index 0000000000..20a4d6788c
    --- /dev/null
    +++ b/Task/Active-Directory-Connect/VBScript/active-directory-connect.vbs
    @@ -0,0 +1,4 @@
    +Set objConn = CreateObject("ADODB.Connection")
    +Set objCmd = CreateObject("ADODB.Command")
    +objConn.Provider = "ADsDSOObject"
    +objConn.Open
    diff --git a/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.ps1 b/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.ps1
    new file mode 100644
    index 0000000000..63a5c8a5cf
    --- /dev/null
    +++ b/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.ps1
    @@ -0,0 +1,7 @@
    +Import-Module ActiveDirectory
    +
    +$searchData = "user name"
    +$searchBase = "DC=example,DC=com"
    +
    +#searches by some of the most common unique identifiers
    +get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
    diff --git a/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vbs b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vbs
    new file mode 100644
    index 0000000000..7dc75eaa5c
    --- /dev/null
    +++ b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-1.vbs
    @@ -0,0 +1,7 @@
    +strUsername = "TestUser"
    +strQuery = ";"_
    + & "(&(objectclass=*)(samaccountname=" & strUsername & "));distinguishedname;subtree"
    +objCmd.ActiveConnection = objConn
    +objCmd.Properties("Page Size")=100
    +objCmd.CommandText = strQuery
    +Set objRS = objCmd.Execute
    diff --git a/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vbs b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vbs
    new file mode 100644
    index 0000000000..8a3b362d41
    --- /dev/null
    +++ b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-2.vbs
    @@ -0,0 +1,3 @@
    +If objRS.RecordCount = 1 Then
    +  WScript.Echo objRS.Fields("DistinguishedName")
    +End If
    diff --git a/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vbs b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vbs
    new file mode 100644
    index 0000000000..6619fc8fa9
    --- /dev/null
    +++ b/Task/Active-Directory-Search-for-a-user/VBScript/active-directory-search-for-a-user-3.vbs
    @@ -0,0 +1,5 @@
    +If objRS.RecordCount > 0 Then
    +  For Each objUser in ObjRS
    +    WScript.Echo objRS.Fields("DistinguishedName")
    +  Next
    +End If
    diff --git a/Task/Active-object/Ada/active-object.adb b/Task/Active-object/Ada/active-object.adb
    new file mode 100644
    index 0000000000..c8410cb4d4
    --- /dev/null
    +++ b/Task/Active-object/Ada/active-object.adb
    @@ -0,0 +1,65 @@
    +with Ada.Calendar;                       use Ada.Calendar;
    +with Ada.Numerics;                       use Ada.Numerics;
    +with Ada.Numerics.Elementary_Functions;  use Ada.Numerics.Elementary_Functions;
    +with Ada.Text_IO;                        use Ada.Text_IO;
    +
    +procedure Test_Integrator is
    +   type Func is access function (T : Time) return Float;
    +
    +   function Zero (T : Time) return Float is
    +   begin
    +      return 0.0;
    +   end Zero;
    +
    +   Epoch : constant Time := Clock;
    +
    +   function Sine (T : Time) return Float is
    +   begin
    +      return Sin (Pi * Float (T - Epoch));
    +   end Sine;
    +
    +   task type Integrator is
    +      entry Input  (Value : Func);
    +      entry Output (Value : out Float);
    +      entry Shut_Down;
    +   end Integrator;
    +
    +   task body Integrator is
    +      K  : Func  := Zero'Access;
    +      S  : Float := 0.0;
    +      F0 : Float := 0.0;
    +      F1 : Float;
    +      T0 : Time  := Clock;
    +      T1 : Time;
    +   begin
    +      loop
    +         select
    +            accept Input (Value : Func) do
    +               K := Value;
    +            end Input;
    +         or accept Output (Value : out Float) do
    +               Value := S;
    +            end Output;
    +         or accept Shut_Down;
    +            exit;
    +         else
    +            T1 := Clock;
    +            F1 := K (T1);
    +            S  := S + 0.5 * (F1 + F0) * Float (T1 - T0);
    +            T0 := T1;
    +            F0 := F1;
    +         end select;
    +      end loop;
    +   end Integrator;
    +
    +   I : Integrator;
    +   S : Float;
    +begin
    +   I.Input (Sine'Access);
    +   delay 2.0;
    +   I.Input (Zero'Access);
    +   delay 0.5;
    +   I.Output (S);
    +   Put_Line ("Integrated" & Float'Image (S) & "s");
    +   I.Shut_Down;
    +end Test_Integrator;
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.adb b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.adb
    new file mode 100644
    index 0000000000..599852f288
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Ada/add-a-variable-to-a-class-instance-at-runtime.adb
    @@ -0,0 +1,40 @@
    +with Ada.Text_IO;  use Ada.Text_IO;
    +
    +procedure Dynamic is
    +   package Abstract_Class is
    +      type Class is limited interface;
    +      function Boo (X : Class) return String is abstract;
    +   end Abstract_Class;
    +   use Abstract_Class;
    +
    +   package Base_Class is
    +      type Base is new Class with null record;
    +      overriding function Boo (X : Base) return String;
    +   end Base_Class;
    +
    +   package body Base_Class is
    +      function Boo (X : Base) return String is
    +      begin
    +         return "I am Class";
    +      end Boo;
    +   end Base_Class;
    +   use Base_Class;
    +
    +   E : aliased Base;  -- An instance of Base
    +
    +begin
    +   -- Gone run-time
    +   declare
    +      type Monkey_Patch (Root : access Base) is new Class with record
    +         Foo : Integer := 1;
    +      end record;
    +      overriding function Boo (X : Monkey_Patch) return String;
    +      function Boo (X : Monkey_Patch) return String is
    +      begin -- Delegation to the base
    +         return X.Root.Boo;
    +      end Boo;
    +      EE : Monkey_Patch (E'Access); -- Extend E
    +   begin
    +      Put_Line (EE.Boo & " with" & Integer'Image (EE.Foo));
    +   end;
    +end Dynamic;
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal/add-a-variable-to-a-class-instance-at-runtime.cr b/Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal/add-a-variable-to-a-class-instance-at-runtime.cr
    new file mode 100644
    index 0000000000..9d091d3e04
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Crystal/add-a-variable-to-a-class-instance-at-runtime.cr
    @@ -0,0 +1,25 @@
    +class SuperDynamic
    +  @vars = {} of String => String | Int32
    +
    +  def set_vars (@vars)
    +  end
    +
    +  macro method_missing (call)
    +    {% name = call.name %}
    +    {% if name.ends_with? "=" %}
    +      {% name = name.gsub(/=$/, "") %}
    +      raise "unknown var" unless @vars.has_key? {{name.id.stringify}}
    +      @vars[{{name.id.stringify}}] = {{call.args[0].id}}
    +    {% else %}
    +      @vars[{{name.id.stringify}}]
    +    {% end %}
    +  end
    +end
    +
    +sd = SuperDynamic.new
    +
    +sd.set_vars({ "a" => 1, "b" => "2" })
    +
    +p! sd.a
    +sd.a = 99
    +p! sd.a
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Pluto/add-a-variable-to-a-class-instance-at-runtime.pluto b/Task/Add-a-variable-to-a-class-instance-at-runtime/Pluto/add-a-variable-to-a-class-instance-at-runtime.pluto
    new file mode 100644
    index 0000000000..40869ae8f9
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Pluto/add-a-variable-to-a-class-instance-at-runtime.pluto
    @@ -0,0 +1,5 @@
    +class myclass end
    +
    +local mc = new myclass()
    +mc.somevar = 21
    +print(mc.somevar * 2)
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/PowerShell/add-a-variable-to-a-class-instance-at-runtime.ps1 b/Task/Add-a-variable-to-a-class-instance-at-runtime/PowerShell/add-a-variable-to-a-class-instance-at-runtime.ps1
    new file mode 100644
    index 0000000000..0e1f1589a8
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/PowerShell/add-a-variable-to-a-class-instance-at-runtime.ps1
    @@ -0,0 +1,5 @@
    +$x = 42 `
    +     | Add-Member -PassThru `
    +        NoteProperty `
    +        Title `
    +        "The answer to the question about life, the universe and everything"
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol/add-a-variable-to-a-class-instance-at-runtime-1.rebol b/Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol/add-a-variable-to-a-class-instance-at-runtime-1.rebol
    new file mode 100644
    index 0000000000..f78f102672
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol/add-a-variable-to-a-class-instance-at-runtime-1.rebol
    @@ -0,0 +1,48 @@
    +Rebol [
    +	Title: "Add Variables to Class at Runtime"
    +	URL: http://rosettacode.org/wiki/Adding_variables_to_a_class_instance_at_runtime
    +]
    +
    +; As I understand it, a REBOL object can only ever have whatever
    +; properties it was born with. However, this is somewhat offset by the
    +; fact that every instance can serve as a prototype for a new object
    +; that also has the new parameter you want to add.
    +
    +; Here I create an empty instance of the base object (x), then add the
    +; new instance variable while creating a new object prototyped from
    +; x. I assign the new object to x, et voila', a dynamically added
    +; variable.
    +
    +x: make object! [] ; Empty object.
    +
    +x: make x [
    +	newvar: "forty-two" ; New property.
    +]
    +
    +print "Empty object modifed with 'newvar' property:"
    +probe x
    +
    +; A slightly more interesting example:
    +
    +starfighter: make object! [
    +	model: "unknown"
    +	pilot: none
    +]
    +x-wing: make starfighter [
    +	model: "Incom T-65 X-wing"
    +]
    +	
    +squadron: reduce [
    +	make x-wing [pilot: "Luke Skywalker"]
    +	make x-wing [pilot: "Wedge Antilles"]
    +	make starfighter [
    +		model: "Slayn & Korpil B-wing"
    +		pilot: "General Salm"
    +	]
    +]
    +
    +; Adding new property here.
    +squadron/1: make squadron/1 [deathstar-removal-expert: yes]
    +
    +print [crlf "Fighter squadron:"]
    +foreach pilot squadron [probe pilot]
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol/add-a-variable-to-a-class-instance-at-runtime-2.rebol b/Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol/add-a-variable-to-a-class-instance-at-runtime-2.rebol
    new file mode 100644
    index 0000000000..47e1beaf8d
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Rebol/add-a-variable-to-a-class-instance-at-runtime-2.rebol
    @@ -0,0 +1,5 @@
    +>> o: object [a: 1]  put o 'b 2  o
    +== make object! [
    +    a: 1
    +    b: 2
    +]
    diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/V-(Vlang)/add-a-variable-to-a-class-instance-at-runtime.v b/Task/Add-a-variable-to-a-class-instance-at-runtime/V-(Vlang)/add-a-variable-to-a-class-instance-at-runtime.v
    new file mode 100644
    index 0000000000..7ef1ee8833
    --- /dev/null
    +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/V-(Vlang)/add-a-variable-to-a-class-instance-at-runtime.v
    @@ -0,0 +1,35 @@
    +import os
    +import strconv
    +
    +struct Obj {
    +    mut:
    +    var map[string]string
    +}
    +
    +fn main() {
    +    mut obj := Obj{}
    +	mut nir, mut ir := 0, 1
    +	mut name, mut val := "", ""
    +    for nir < 1 || nir > 3 {
    +		nir = strconv.atoi(os.input("How many variables to create (max 3): ")) or
    +		{println("Invalid input!") continue}
    +    }
    +	for ir <= nir {
    +		println("Enter the variable names and their values, below:")
    +		println("Variable ${ir}")
    +        name = os.input_opt("    Name: ") or {println("Invalid input!") exit(1)}
    +		for {
    +			val = os.input_opt("    Value: ") or {println("Invalid input!") exit(2)}
    +			break
    +		}
    +		obj.var[name] = val
    +        ir++
    +	}
    +	println("\n" + "Enter q to quit")
    +	for {
    + 		name = os.input_opt("Which variable (field) name to inspect : ") or {continue}
    +        if name.to_lower() == "q" {break}
    +        if name !in obj.var {println("There's no variable (field) of that name, try again")}
    +        else {println("It's value is: '${obj.var[name]}'")}
    +    }		
    +}
    diff --git a/Task/Additive-primes/Ada/additive-primes.adb b/Task/Additive-primes/Ada/additive-primes.adb
    new file mode 100644
    index 0000000000..800f5d1f23
    --- /dev/null
    +++ b/Task/Additive-primes/Ada/additive-primes.adb
    @@ -0,0 +1,58 @@
    +with Ada.Text_Io;
    +
    +procedure Additive_Primes is
    +
    +   Last    : constant := 499;
    +   Columns : constant := 12;
    +
    +   type Prime_List is array (2 .. Last) of Boolean;
    +
    +   function Get_Primes return Prime_List is
    +      Prime : Prime_List := (others => True);
    +   begin
    +      for P in Prime'Range loop
    +         if Prime (P) then
    +            for N in 2 .. Positive'Last loop
    +               exit when N * P not in Prime'Range;
    +               Prime (N * P) := False;
    +            end loop;
    +         end if;
    +      end loop;
    +      return Prime;
    +   end Get_Primes;
    +
    +   function Sum_Of (N : Natural) return Natural is
    +      Image : constant String := Natural'Image (N);
    +      Sum   : Natural := 0;
    +   begin
    +      for Char of Image loop
    +         Sum := Sum + (if Char in '0' .. '9'
    +                       then Natural'Value ("" & Char)
    +                       else 0);
    +      end loop;
    +      return Sum;
    +   end Sum_Of;
    +
    +   package Natural_Io is new Ada.Text_Io.Integer_Io (Natural);
    +   use Ada.Text_Io, Natural_Io;
    +
    +   Prime : constant Prime_List := Get_Primes;
    +   Count : Natural := 0;
    +begin
    +   Put_Line ("Additive primes <500:");
    +   for N in Prime'Range loop
    +      if Prime (N) and then Prime (Sum_Of (N)) then
    +         Count := Count + 1;
    +         Put (N, Width => 5);
    +         if Count mod Columns = 0 then
    +            New_Line;
    +         end if;
    +      end if;
    +   end loop;
    +   New_Line;
    +
    +   Put ("There are ");
    +   Put (Count, Width => 2);
    +   Put (" additive primes.");
    +   New_Line;
    +end Additive_Primes;
    diff --git a/Task/Additive-primes/COBOL/additive-primes.cob b/Task/Additive-primes/COBOL/additive-primes.cob
    new file mode 100644
    index 0000000000..bcdc97c71e
    --- /dev/null
    +++ b/Task/Additive-primes/COBOL/additive-primes.cob
    @@ -0,0 +1,73 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. ADDITIVE-PRIMES.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 VARIABLES.
    +          03 MAXIMUM            PIC 999.
    +          03 AMOUNT             PIC 999.
    +          03 CANDIDATE          PIC 999.
    +          03 DIGIT              PIC 9 OCCURS 3 TIMES,
    +                                REDEFINES CANDIDATE.
    +          03 DIGITSUM           PIC 99.
    +
    +       01 PRIME-DATA.
    +          03 COMPOSITE-FLAG     PIC X OCCURS 500 TIMES.
    +             88 PRIME           VALUE ' '.
    +          03 SIEVE-PRIME        PIC 999.
    +          03 SIEVE-COMP-START   PIC 999.
    +          03 SIEVE-COMP         PIC 999.
    +          03 SIEVE-MAX          PIC 999.
    +
    +       01 OUT-FMT.
    +          03 NUM-FMT            PIC ZZZ9.
    +          03 OUT-LINE           PIC X(40).
    +          03 OUT-PTR            PIC 99.
    +
    +       PROCEDURE DIVISION.
    +       BEGIN.
    +           MOVE 500 TO MAXIMUM.
    +           MOVE 1 TO OUT-PTR.
    +           PERFORM SIEVE.
    +           MOVE ZERO TO AMOUNT.
    +           PERFORM TEST-NUMBER
    +               VARYING CANDIDATE FROM 2 BY 1
    +               UNTIL CANDIDATE IS GREATER THAN MAXIMUM.
    +           DISPLAY OUT-LINE.
    +           DISPLAY SPACES.
    +           MOVE AMOUNT TO NUM-FMT.
    +           DISPLAY 'Amount of additive primes found: ' NUM-FMT.
    +           STOP RUN.
    +
    +       TEST-NUMBER.
    +           ADD DIGIT(1), DIGIT(2), DIGIT(3) GIVING DIGITSUM.
    +           IF PRIME(CANDIDATE) AND PRIME(DIGITSUM),
    +               ADD 1 TO AMOUNT,
    +               PERFORM WRITE-NUMBER.
    +
    +       WRITE-NUMBER.
    +           MOVE CANDIDATE TO NUM-FMT.
    +           STRING NUM-FMT DELIMITED BY SIZE INTO OUT-LINE
    +               WITH POINTER OUT-PTR.
    +           IF OUT-PTR IS GREATER THAN 40,
    +               DISPLAY OUT-LINE,
    +               MOVE SPACES TO OUT-LINE,
    +               MOVE 1 TO OUT-PTR.
    +
    +       SIEVE.
    +           MOVE SPACES TO PRIME-DATA.
    +           DIVIDE MAXIMUM BY 2 GIVING SIEVE-MAX.
    +           PERFORM SIEVE-OUTER-LOOP
    +               VARYING SIEVE-PRIME FROM 2 BY 1
    +               UNTIL SIEVE-PRIME IS GREATER THAN SIEVE-MAX.
    +
    +       SIEVE-OUTER-LOOP.
    +           IF PRIME(SIEVE-PRIME),
    +               MULTIPLY SIEVE-PRIME BY 2 GIVING SIEVE-COMP-START,
    +               PERFORM SIEVE-INNER-LOOP
    +                   VARYING SIEVE-COMP
    +                       FROM SIEVE-COMP-START BY SIEVE-PRIME
    +                   UNTIL SIEVE-COMP IS GREATER THAN MAXIMUM.
    +
    +       SIEVE-INNER-LOOP.
    +           MOVE 'X' TO COMPOSITE-FLAG(SIEVE-COMP).
    diff --git a/Task/Additive-primes/Icon/additive-primes.icon b/Task/Additive-primes/Icon/additive-primes.icon
    new file mode 100644
    index 0000000000..513992b151
    --- /dev/null
    +++ b/Task/Additive-primes/Icon/additive-primes.icon
    @@ -0,0 +1,13 @@
    +link factors
    +
    +procedure main(A)
    +   limit := \A[1] | 500
    +   every p := prime() do
    +      if p < 500 then writes(" ",additive(p)) else break
    +   write()
    +end
    +
    +procedure additive(a)
    +   a ? (sum := 0, while sum +:= move(1))
    +   return (isprime(sum),a)
    +end
    diff --git a/Task/Additive-primes/Langur/additive-primes.langur b/Task/Additive-primes/Langur/additive-primes.langur
    index d6d80fd05f..8fe40c3325 100644
    --- a/Task/Additive-primes/Langur/additive-primes.langur
    +++ b/Task/Additive-primes/Langur/additive-primes.langur
    @@ -1,9 +1,9 @@
    -val isPrime = fn(i) {
    -   i == 2 or i > 2 and
    -      not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x)
    +val isPrime = fn(i number) {
    +	i == 2 or i > 2 and
    +		not any(series(2 .. i ^/ 2, asconly=true), by=fn(x) { i div x })
     }
     
    -val sumDigits = fn i: fold(s2n(string(i)), by=fn{+})
    +val sumDigits = fn(i) { fold(s2n(string(i)), by=fn{+}) }
     
     writeln "Additive primes less than 500:"
     
    diff --git a/Task/Additive-primes/Pluto/additive-primes.pluto b/Task/Additive-primes/Pluto/additive-primes.pluto
    new file mode 100644
    index 0000000000..dfc881f585
    --- /dev/null
    +++ b/Task/Additive-primes/Pluto/additive-primes.pluto
    @@ -0,0 +1,14 @@
    +local int = require "int"
    +local fmt = require "fmt"
    +
    +print("Additive primes less than 500:")
    +local primes = int.primes(499)
    +local count = 0
    +for primes as p  do
    +    if int.isprime(int.digstat(p)[2]) do
    +        count += 1
    +        fmt.write("%3d  ", p)
    +        if count % 10 == 0 then print() end
    +    end
    +end
    +print($"\n\n{count} additive primes found.")
    diff --git a/Task/Additive-primes/Rebol/additive-primes.rebol b/Task/Additive-primes/Rebol/additive-primes.rebol
    new file mode 100644
    index 0000000000..eb5759c7c4
    --- /dev/null
    +++ b/Task/Additive-primes/Rebol/additive-primes.rebol
    @@ -0,0 +1,42 @@
    +Rebol [
    +    title: "Rosetta code: Additive primes"
    +    file:  %Additive_primes.r3
    +    url:   https://rosettacode.org/wiki/Additive_primes
    +    note:  "Based on Red language solution"
    +]
    +primes: function [n [integer!]][
    +    ;; See: https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Rebol
    +    poke prim: make bitset! n 1 true
    +    r: 2 while [r * r <= n][repeat q n / r - 1 [poke prim q + 1 * r true]
    +    until [not pick prim r: r + 1]]
    +    collect [repeat i n [unless prim/:i [keep i]]]
    +]
    +;; Compute the digit sum (cross-sum) of an integer n
    +cross-sum: function [n][
    +    out: 0                 ;; accumulator for sum of digits
    +    foreach m form n [     ;; iterate over the characters of n's string form
    +        out: out - 48 + m  ;; convert char to integer, add to out
    +    ]
    +    out
    +]
    +;; Return all additive primes <= n:
    +;; A prime p is "additive" if its digit-sum is also prime.
    +additive-primes: function [n][
    +    collect [
    +        foreach p ps: primes n [       ;; generate primes up to n and iterate over them
    +            if find ps cross-sum p [   ;; check if digit-sum of p is itself in the prime set
    +                keep p                 ;; keep p if digit-sum is prime
    +            ]
    +        ]
    +    ]
    +]
    +
    +;; Generate additive primes up to 500
    +result: additive-primes 500
    +;; Format nicely by rows of 10 (with newlines)
    +print [length? result "additive primes < 500:"]
    +forall result [
    +    prin pad result/1 -4
    +    if zero? ((index? result) % 10) [print ""]
    +]
    +print ""
    diff --git a/Task/Additive-primes/Uiua/additive-primes.uiua b/Task/Additive-primes/Uiua/additive-primes-1.uiua
    similarity index 100%
    rename from Task/Additive-primes/Uiua/additive-primes.uiua
    rename to Task/Additive-primes/Uiua/additive-primes-1.uiua
    diff --git a/Task/Additive-primes/Uiua/additive-primes-2.uiua b/Task/Additive-primes/Uiua/additive-primes-2.uiua
    new file mode 100644
    index 0000000000..447a6cbce2
    --- /dev/null
    +++ b/Task/Additive-primes/Uiua/additive-primes-2.uiua
    @@ -0,0 +1,2 @@
    +Prime ← =₁⧻°/×
    +⊸⧻▽⊸≡(×Prime/+⊥₁₀⟜Prime) ↘2⇡500
    diff --git a/Task/Additive-primes/Uiua/additive-primes-3.uiua b/Task/Additive-primes/Uiua/additive-primes-3.uiua
    new file mode 100644
    index 0000000000..c5f88cba42
    --- /dev/null
    +++ b/Task/Additive-primes/Uiua/additive-primes-3.uiua
    @@ -0,0 +1 @@
    +Prime ← =₁⧻°/×
    diff --git a/Task/Additive-primes/Uiua/additive-primes-4.uiua b/Task/Additive-primes/Uiua/additive-primes-4.uiua
    new file mode 100644
    index 0000000000..dff5cee7d4
    --- /dev/null
    +++ b/Task/Additive-primes/Uiua/additive-primes-4.uiua
    @@ -0,0 +1 @@
    +↘2⇡500
    diff --git a/Task/Additive-primes/Uiua/additive-primes-5.uiua b/Task/Additive-primes/Uiua/additive-primes-5.uiua
    new file mode 100644
    index 0000000000..87bc54f816
    --- /dev/null
    +++ b/Task/Additive-primes/Uiua/additive-primes-5.uiua
    @@ -0,0 +1 @@
    +≡(×Prime/+⊥₁₀⟜Prime)
    diff --git a/Task/Additive-primes/Uiua/additive-primes-6.uiua b/Task/Additive-primes/Uiua/additive-primes-6.uiua
    new file mode 100644
    index 0000000000..07cb55f295
    --- /dev/null
    +++ b/Task/Additive-primes/Uiua/additive-primes-6.uiua
    @@ -0,0 +1 @@
    +⊸⧻▽⊸
    diff --git a/Task/Additive-primes/V-(Vlang)/additive-primes.v b/Task/Additive-primes/V-(Vlang)/additive-primes.v
    index 47e8c46bad..49aabd1688 100644
    --- a/Task/Additive-primes/V-(Vlang)/additive-primes.v
    +++ b/Task/Additive-primes/V-(Vlang)/additive-primes.v
    @@ -1,56 +1,34 @@
    -fn is_prime(n int) bool {
    -    if n < 2 {
    -        return false
    -    } else if n%2 == 0 {
    -        return n == 2
    -    } else if n%3 == 0 {
    -        return n == 3
    -    } else {
    -        mut d := 5
    -        for d*d <= n {
    -            if n%d == 0 {
    -                return false
    -            }
    -            d += 2
    -            if n%d == 0 {
    -                return false
    -            }
    -            d += 4
    -        }
    -        return true
    -    }
    -}
    +import strconv
     
    -fn sum_digits(nn int) int {
    -    mut n := nn
    -    mut sum := 0
    -    for n > 0 {
    -        sum += n % 10
    -        n /= 10
    +fn is_prime(n int) bool {
    +    if n <= 1 { return false }
    +    for i := 2; i * i <= n; i++ {
    +        if n % i == 0 { return false }
         }
    -    return sum
    +    return true
     }
     
     fn main() {
    -    println("Additive primes less than 500:")
    -    mut i := 2
    -    mut count := 0
    -    for {
    -        if is_prime(i) && is_prime(sum_digits(i)) {
    -            count++
    -            print("${i:3}  ")
    -            if count%10 == 0 {
    -                println('')
    +    mut row := 0
    +    limit := 500	
    +    println("working...")
    +    println("Additive primes are:")
    +    for n := 1; n <= limit; n++ {
    +        if is_prime(n) {
    +            strn := n.str()
    +            mut num := 0
    +            for ch in strn {
    +                digit := strconv.atoi(ch.ascii_str()) or { exit(1) }
    +                num += digit
    +            }
    +            if is_prime(num) {
    +                row++
    +                print("$n ")
    +                if row % 10 == 0 { println("") }
                 }
             }
    -        if i > 2 {
    -            i += 2
    -        } else {
    -            i++
    -        }
    -        if i > 499 {
    -            break
    -        }
         }
    -    println("\n\n$count additive primes found.")
    +    println("")
    +    println("found $row additive primes.")
    +    println("done...")
     }
    diff --git a/Task/Address-of-a-variable/Ada/address-of-a-variable-1.adb b/Task/Address-of-a-variable/Ada/address-of-a-variable-1.adb
    new file mode 100644
    index 0000000000..b4b3d87235
    --- /dev/null
    +++ b/Task/Address-of-a-variable/Ada/address-of-a-variable-1.adb
    @@ -0,0 +1,3 @@
    +The_Address : System.Address;
    +I : Integer;
    +The_Address := I'Address;
    diff --git a/Task/Address-of-a-variable/Ada/address-of-a-variable-2.adb b/Task/Address-of-a-variable/Ada/address-of-a-variable-2.adb
    new file mode 100644
    index 0000000000..665d4b3960
    --- /dev/null
    +++ b/Task/Address-of-a-variable/Ada/address-of-a-variable-2.adb
    @@ -0,0 +1,2 @@
    +I : Integer;
    +for I'Address use 16#A100#;
    diff --git a/Task/Address-of-a-variable/Ada/address-of-a-variable-3.adb b/Task/Address-of-a-variable/Ada/address-of-a-variable-3.adb
    new file mode 100644
    index 0000000000..f903d446b9
    --- /dev/null
    +++ b/Task/Address-of-a-variable/Ada/address-of-a-variable-3.adb
    @@ -0,0 +1,3 @@
    +I : Integer;
    +J : Integer;
    +for I'Address use J'Address;
    diff --git a/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cob b/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cob
    new file mode 100644
    index 0000000000..2bde5d6a6e
    --- /dev/null
    +++ b/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cob
    @@ -0,0 +1,7 @@
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 ptr USAGE POINTER.
    +       01 var PIC X(64).
    +
    +       PROCEDURE DIVISION.
    +           SET ptr TO ADDRESS OF var.
    diff --git a/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cob b/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cob
    new file mode 100644
    index 0000000000..86e2b0b3f2
    --- /dev/null
    +++ b/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cob
    @@ -0,0 +1,17 @@
    +OCOBOL*> Rosetta Code set address example
    +      *> tectonics: cobc -x setaddr.cob && ./setaddr
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. setaddr.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01 prealloc PIC X(8) VALUE 'somedata'.
    +       01 var      PIC X(8) BASED.
    +
    +       PROCEDURE DIVISION.
    +           SET ADDRESS OF var TO ADDRESS OF prealloc
    +           DISPLAY var END-DISPLAY
    +      *>    'somedata'
    +           GOBACK.
    +
    +       END PROGRAM setaddr.
    diff --git a/Task/Address-of-a-variable/Crystal/address-of-a-variable.cr b/Task/Address-of-a-variable/Crystal/address-of-a-variable.cr
    new file mode 100644
    index 0000000000..4110c86ba4
    --- /dev/null
    +++ b/Task/Address-of-a-variable/Crystal/address-of-a-variable.cr
    @@ -0,0 +1,8 @@
    +icr:1> a = 123
    + => 123
    +icr:2> p = pointerof(a)
    + => Pointer(Int32)@0x1ed36c20000
    +icr:3> p.value = 321
    + => 321
    +icr:4> a
    + => 321
    diff --git a/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx b/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx
    index 4c8e5959ea..274996e7a3 100644
    --- a/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx
    +++ b/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx
    @@ -1,11 +1,12 @@
    --- 23 Aug 2025
    +-- 21 Feb 2026
     include Setting
     
     say 'ADDRESS OF A VARIABLE'
     say version
     say
     call Primes 10
    -call DumpVariables
    +call Showvars
     exit
     
    +-- Primes; Showvars
     include Math
    diff --git a/Task/Algebraic-data-types/Emacs-Lisp/algebraic-data-types.el b/Task/Algebraic-data-types/Emacs-Lisp/algebraic-data-types.el
    new file mode 100644
    index 0000000000..8c007bfc1f
    --- /dev/null
    +++ b/Task/Algebraic-data-types/Emacs-Lisp/algebraic-data-types.el
    @@ -0,0 +1,28 @@
    +(defun rbt-balance (tree)
    +  (pcase tree
    +    (`(B (R (R ,a ,x ,b) ,y ,c) ,z ,d) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d)))
    +    (`(B (R ,a ,x (R ,b ,y ,c)) ,z ,d) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d)))
    +    (`(B ,a ,x (R (R ,b ,y ,c) ,z ,d)) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d)))
    +    (`(B ,a ,x (R ,b ,y (R ,c ,z ,d))) `(R (B ,a ,x ,b) ,y (B ,c ,z ,d)))
    +    (_                                 tree)))
    +
    +(defun rbt-insert- (x s)
    +  (pcase s
    +    (`nil              `(R nil ,x nil))
    +    (`(,color ,a ,y ,b) (cond ((< x y)
    +                               (rbt-balance `(,color ,(rbt-insert- x a) ,y ,b)))
    +                              ((> x y)
    +                               (rbt-balance `(,color ,a ,y ,(rbt-insert- x b))))
    +                              (t
    +                               s)))
    +    (_                  (error "Expected tree: %S" s))))
    +
    +(defun rbt-insert (x s)
    +  (pcase (rbt-insert- x s)
    +    (`(,_ ,a ,y ,b) `(B ,a ,y ,b))
    +    (_              (error "Internal error: %S" s))))
    +
    +(let ((s nil))
    +  (dotimes (i 16)
    +    (setq s (rbt-insert (1+ i) s)))
    +  (pp s))
    diff --git a/Task/Algebraic-data-types/Pluto/algebraic-data-types.pluto b/Task/Algebraic-data-types/Pluto/algebraic-data-types.pluto
    new file mode 100644
    index 0000000000..4d8388263b
    --- /dev/null
    +++ b/Task/Algebraic-data-types/Pluto/algebraic-data-types.pluto
    @@ -0,0 +1,78 @@
    +$define R = "R"
    +$define B = "B"
    +
    +class Tree
    +    function ins(_) end  -- overridden by child classes
    +
    +    function insert(x)   -- inherited by child classes
    +        local t = self:ins(x)
    +        if t:type() == "T" then return new T(B, t.le, t.aa, t.ri) end
    +        if t:type() == "E" then return new E() end
    +        return nil
    +    end
    +end
    +
    +class T extends Tree
    +    function __construct(
    +        public cl, -- color
    +        public le, -- Tree
    +        public aa, -- integer
    +        public ri  -- Tree
    +    )
    +    end
    +
    +    function type() return "T" end
    +
    +    function balance()
    +        if self.cl != B then return self end
    +        local le2 = self.le:type() == "T" ? self.le : nil
    +        local lele, leri
    +        if le2 then
    +            lele = self.le.le:type() == "T" ? self.le.le : nil
    +            leri = self.le.ri:type() == "T" ? self.le.ri : nil
    +        end
    +        local ri2 = self.ri:type() == "T" ? self.ri : nil
    +        local rile, riri
    +        if ri2 then
    +            rile = self.ri.le:type() == "T" ? self.ri.le : nil
    +            riri = self.ri.ri.type() == "T" ? self.ri.ri : nil
    +        end
    +        if le2 and lele and le2.cl == R and lele.cl == R then
    +            local t = le2.le
    +            return new T(R, new T(B, t.le, t.aa, t.ri), le2.aa, new T(B, le2.ri, self.aa, self.ri))
    +        end
    +        if le2 and leri and le2.cl == R and leri.cl == R then
    +            local t = le2.ri
    +            return new T(R, new T(B, le2.le, le2.aa, t.le), t.aa, new T(B, t.ri, self.aa, self.ri))
    +        end
    +        if ri2 and rile and ri2.cl == R and rile.cl == R then
    +            local t = ri2.ri
    +            return new T(R, new T(B, self.le, self.aa, t.le), t.aa, new T(B, t.ri, ri2.aa, ri2.ri))
    +        end
    +        if ri2 and riri and ri2.cl == R and riri.cl == R then
    +            local t = ri2.ri
    +            return new T(R, new T(B, self.le, self.aa, ri2.le), ri2.aa, new T(B, t.le, t.aa, t.ri))
    +        end
    +        return self
    +    end
    +
    +    function ins(x)
    +        if x < self.aa then return new T(self.cl, self.le:ins(x), self.aa, self.ri):balance() end
    +        if x > self.aa then return new T(self.cl, self.le, self.aa, self.ri:ins(x)):balance() end
    +        return self
    +    end
    +
    +    function __tostring() return $"T({self.cl}, {self.le}, {self.aa}, {self.ri})" end
    +end
    +
    +class E extends Tree
    +    function ins(x) return new T(R, new E(), x, new E()) end
    +
    +    function type() return "E" end
    +
    +    function __tostring() return "E" end
    +end
    +
    +local tr = new E()
    +for i = 1, 16 do tr = tr:insert(i) end
    +print(tr)
    diff --git a/Task/Align-columns/Ada/align-columns.adb b/Task/Align-columns/Ada/align-columns.adb
    new file mode 100644
    index 0000000000..16c857d27a
    --- /dev/null
    +++ b/Task/Align-columns/Ada/align-columns.adb
    @@ -0,0 +1,65 @@
    +with Ada.Characters.Latin_1;  use Ada.Characters.Latin_1;
    +with Ada.Text_IO;             use Ada.Text_IO;
    +with Strings_Edit;            use Strings_Edit;
    +
    +procedure Column_Aligner is
    +   Text : constant String :=
    +      "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & NUL &
    +      "are$delineated$by$a$single$'dollar'$character,$write$a$program" & NUL &
    +      "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & NUL &
    +      "column$are$separated$by$at$least$one$space." & NUL &
    +      "Further,$allow$for$each$word$in$a$column$to$be$either$left$" & NUL &
    +      "justified,$right$justified,$or$center$justified$within$its$column." & NUL;
    +   File    : File_Type;
    +   Width   : array (1..1_000) of Natural := (others => 0);
    +   Line    : String (1..200);
    +   Column  : Positive := 1;
    +   Start   : Positive := 1;
    +   Pointer : Positive;
    +begin
    +   Create (File, Out_File, "columned.txt");
    +      -- Determining the widths of columns
    +   for I in Text'Range loop
    +      case Text (I) is
    +         when '$' | NUL =>
    +            Width (Column) := Natural'Max (Width (Column), I - Start + 1);
    +            Start  := I + 1;
    +            if Text (I) = NUL then
    +               Column := 1;
    +            else
    +               Column := Column + 1;
    +            end if;
    +         when others =>
    +            null;
    +      end case;
    +   end loop;
    +      -- Formatting
    +   for Align in Alignment loop
    +      Column  := 1;
    +      Start   := 1;
    +      Pointer := 1;
    +      for I in Text'Range loop
    +         case Text (I) is
    +            when '$' | NUL =>
    +               Put -- Formatted output of a word
    +               (  Destination => Line,
    +                  Pointer     => Pointer,
    +                  Value       => Text (Start..I - 1),
    +                  Field       => Width (Column),
    +                  Justify     => Align
    +               );
    +               Start  := I + 1;
    +               if Text (I) = NUL then
    +                  Put_Line (File, Line (1..Pointer - 1));
    +                  Pointer := 1;
    +                  Column := 1;
    +               else
    +                  Column := Column + 1;
    +               end if;
    +            when others =>
    +               null;
    +         end case;
    +      end loop;
    +   end loop;
    +   Close (File);
    +end Column_Aligner;
    diff --git a/Task/Align-columns/AutoIt/align-columns.au3 b/Task/Align-columns/AutoIt/align-columns.au3
    new file mode 100644
    index 0000000000..9f63e34736
    --- /dev/null
    +++ b/Task/Align-columns/AutoIt/align-columns.au3
    @@ -0,0 +1,83 @@
    +; == If the given text is in an file, it will read with:
    +#include 
    +Global $aRead
    +_FileReadToArray($sPath, $aRead)  ; == $aRead[0] includes count of lines, every line stored in one item (without linebreak)
    +
    +; == For example we get the same result with StringSplit()
    +Global $sText = _
    +"Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & @CRLF & _
    +"are$delineated$by$a$single$'dollar'$character,$write$a$program" & @CRLF & _
    +"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & @CRLF & _
    +"column$are$separated$by$at$least$one$space." & @CRLF & _
    +"Further,$allow$for$each$word$in$a$column$to$be$either$left$" & @CRLF & _
    +"justified,$right$justified,$or$center$justified$within$its$column." & @CRLF
    +
    +$aRead = StringSplit($sText, @CRLF, 1)
    +
    +; == strip leading and trailing "$" and trailing spaces, count remaining "$" to get max column number
    +Global $iMaxColumn = 0, $iLines = 0
    +For $i = 1 To $aRead[0]
    +	If $aRead[$i] = '' Then ContinueLoop   ; skip empty lines
    +	$iLines += 1
    +	$aRead[$i] = StringRegExpReplace(StringRegExpReplace(StringRegExpReplace($aRead[$i], '^\$', ''), '\$$', ''), '\s*$', '')
    +	StringReplace($aRead[$i], '$', '$')
    +	If @extended +1 > $iMaxColumn Then $iMaxColumn = @extended +1
    +Next
    +
    +; == build array to store all fields and length of every item
    +Global $aFields[$iLines][$iMaxColumn +1][2]
    +; == and store the max. length of item in columns
    +Global $aColLen[$iMaxColumn]
    +
    +; == fill the array
    +Global $aSplitLine
    +$iLines = 0
    +For $i = 1 To $aRead[0]
    +	If $aRead[$i] = '' Then ContinueLoop   ; skip empty lines
    +	$iMaxColLen = 0
    +	$aSplitLine = StringSplit($aRead[$i], '$')
    +	For $j = 1 To $aSplitLine[0]
    +		$aFields[$iLines][$j-1][0] = $aSplitLine[$j]
    +		$aFields[$iLines][$j-1][1] = StringLen($aSplitLine[$j])
    +		If $aFields[$iLines][$j-1][1] > $aColLen[$j-1] Then $aColLen[$j-1] = $aFields[$iLines][$j-1][1]
    +	Next
    +	$iLines += 1
    +Next
    +
    +; == let the user select the alignment for every column
    +$sAlign = InputBox('Column alignment', 'There are ' & $iMaxColumn & ' columns.' & @LF & '0 = left    1 = center    2 = right' & @LF &  _
    +                   'Input alignment for all columns without delimiters.' & @LF & 'Let it empty, to align all left.')
    +If $sAlign = '' Then
    +	For $i = 1 To $iMaxColumn
    +		$sAlign &= '0'
    +	Next
    +EndIf
    +Global $aAlignment = StringSplit($sAlign, '', 2)
    +
    +; == output all to console
    +Global $sLineOut
    +For $i = 0 To UBound($aFields) -1
    +	$sLineOut = ''
    +	For $j = 0 To $iMaxColumn -1
    +		If $aFields[$i][$j][0] = '' Then ContinueLoop
    +		$sLineOut &= _GetAligned($aFields[$i][$j][0], $aFields[$i][$j][1], $aAlignment[$j], $aColLen[$j])
    +	Next
    +	ConsoleWrite(StringTrimRight($sLineOut, 1) & @LF)
    +Next
    +
    +Func _GetAligned($_sString, $_iLen, $_iAlign, $_iMaxLen)
    +	Local $sSpace = ''
    +	For $i = 1 To $_iMaxLen
    +		$sSpace &= ' '
    +	Next
    +	Switch $_iAlign
    +		Case 0
    +			Return $_sString & StringLeft($sSpace, $_iMaxLen - $_iLen +1)
    +		Case 1
    +			Local $iLenLeft = Int(($_iMaxLen - $_iLen)/2)
    +			Local $iLenRight = $_iMaxLen - $iLenLeft - $_iLen
    +			Return StringLeft($sSpace, $iLenLeft) & $_sString & StringLeft($sSpace, $iLenRight) & ' '
    +		Case 2
    +			Return StringLeft($sSpace, $_iMaxLen - $_iLen) & $_sString & ' '
    +	EndSwitch
    +EndFunc  ;==>_GetAligned
    diff --git a/Task/Align-columns/COBOL/align-columns-1.cob b/Task/Align-columns/COBOL/align-columns-1.cob
    new file mode 100644
    index 0000000000..9228acbc68
    --- /dev/null
    +++ b/Task/Align-columns/COBOL/align-columns-1.cob
    @@ -0,0 +1,83 @@
    +       identification division.
    +       program-id. AlignColumns.
    +
    +       data division.
    +       working-storage section.
    +      *>-> Constants
    +       78 MAX-LINES value 6.
    +       78 MAX-LINE-SIZE value 66.
    +       78 MAX-COLUMNS value 12.
    +       78 MAX-COLUMN-SIZE value 16.
    +      *>-> Indexes
    +       01 w-idx                   pic is 9(2).
    +       01 w-idy                   pic is 9(2).
    +       01 w-pos                   pic is 9(3).
    +      *>-> Data structures
    +       01 w-lines.
    +          05 w-line               pic is x(MAX-LINE-SIZE) occurs MAX-LINES.
    +       01 w-column-sizes.
    +          05 w-column-size        pic is 99 occurs MAX-COLUMNS value zeros.
    +       01 w-matrix.
    +          05 filler               occurs MAX-LINES.
    +             10 filler            occurs MAX-COLUMNS.
    +                15 w-content      pic is x(MAX-COLUMN-SIZE).
    +      *>-> Output
    +       01 w-line-out              pic is x(120).
    +      *>-> Data alignment
    +       01 w-alignment             pic is x(1).
    +          88 alignment-left       value is "L".
    +          88 alignment-center     value is "C".
    +          88 alignment-right      value is "R".
    +
    +       procedure division.
    +       main.
    +           move "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" to w-line(1)
    +           move "are$delineated$by$a$single$'dollar'$character,$write$a$program" to w-line(2)
    +           move "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" to w-line(3)
    +           move "column$are$separated$by$at$least$one$space." to w-line(4)
    +           move "Further,$allow$for$each$word$in$a$column$to$be$either$left$" to w-line(5)
    +           move "justified,$right$justified,$or$center$justified$within$its$column." to w-line(6)
    +           perform calculate-size-columns
    +           set alignment-left to true
    +           perform show-content
    +           set alignment-center to true
    +           perform show-content
    +           set alignment-right to true
    +           perform show-content
    +           goback
    +           .
    +       calculate-size-columns.
    +           perform
    +              varying             w-idx from 1 by 1
    +                 until            w-idx > MAX-LINES
    +              unstring w-line(w-idx) delimited by "$" into w-content(w-idx, 1), w-content(w-idx, 2),
    +                  w-content(w-idx, 3), w-content(w-idx, 4), w-content(w-idx, 5), w-content(w-idx, 6),
    +                  w-content(w-idx, 7), w-content(w-idx, 8), w-content(w-idx, 9), w-content(w-idx, 10),
    +                  w-content(w-idx, 11), w-content(w-idx, 12),
    +              perform
    +                 varying          w-idy from 1 by 1
    +                    until         w-idy > MAX-COLUMNS
    +                 if function stored-char-length(w-content(w-idx, w-idy)) > w-column-size(w-idy)
    +                    move function stored-char-length(w-content(w-idx, w-idy)) to w-column-size(w-idy)
    +                 end-if
    +              end-perform
    +           end-perform
    +           .
    +       show-content.
    +           move all "-" to w-line-out
    +           display w-line-out
    +           perform
    +              varying             w-idx from 1 by 1
    +                 until            w-idx > MAX-LINES
    +              move spaces to w-line-out
    +              move 1 to w-pos
    +              perform
    +                 varying          w-idy from 1 by 1
    +                    until         w-idy > MAX-COLUMNS
    +                 call "C$JUSTIFY" using w-content(w-idx, w-idy)(1:w-column-size(w-idy)), w-alignment
    +                 move w-content(w-idx, w-idy) to w-line-out(w-pos:w-column-size(w-idy))
    +                 compute w-pos = w-pos + w-column-size(w-idy) + 1
    +              end-perform
    +              display w-line-out
    +           end-perform
    +           .
    diff --git a/Task/Align-columns/COBOL/align-columns-2.cob b/Task/Align-columns/COBOL/align-columns-2.cob
    new file mode 100644
    index 0000000000..9e71439879
    --- /dev/null
    +++ b/Task/Align-columns/COBOL/align-columns-2.cob
    @@ -0,0 +1,21 @@
    +------------------------------------------------------------------------------------------------------------------------
    +Given      a          text       file   of     many      lines,     where    fields  within  a      line
    +are        delineated by         a      single 'dollar'  character, write    a       program
    +that       aligns     each       column of     fields    by         ensuring that    words   in     each
    +column     are        separated  by     at     least     one        space.
    +Further,   allow      for        each   word   in        a          column   to      be      either left
    +justified, right      justified, or     center justified within     its      column.
    +------------------------------------------------------------------------------------------------------------------------
    +  Given        a         text     file    of     many      lines,    where   fields  within    a    line
    +   are     delineated     by       a    single 'dollar'  character,  write      a    program
    +   that      aligns      each    column   of    fields       by     ensuring  that    words    in   each
    +  column      are     separated    by     at     least      one      space.
    + Further,    allow       for      each   word     in         a       column    to      be    either left
    +justified,   right    justified,   or   center justified   within     its    column.
    +------------------------------------------------------------------------------------------------------------------------
    +     Given          a       text   file     of      many     lines,    where  fields  within      a line
    +       are delineated         by      a single  'dollar' character,    write       a program
    +      that     aligns       each column     of    fields         by ensuring    that   words     in each
    +    column        are  separated     by     at     least        one   space.
    +  Further,      allow        for   each   word        in          a   column      to      be either left
    +justified,      right justified,     or center justified     within      its column.
    diff --git a/Task/Align-columns/Crystal/align-columns.cr b/Task/Align-columns/Crystal/align-columns.cr
    new file mode 100644
    index 0000000000..9ce66f84c8
    --- /dev/null
    +++ b/Task/Align-columns/Crystal/align-columns.cr
    @@ -0,0 +1,37 @@
    +enum Justification
    +  Left
    +  Right
    +  Center
    +end
    +
    +def align_columns (text, justification = Justification::Left)
    +  rows = text.lines.map(&.split('$'))
    +
    +  field_sizes = (0...rows.max_of(&.size)).map {|idx|
    +    rows.max_of {|r| (r[idx]? || "").size }
    +  }
    +  rows.each do |row|
    +    puts row.zip(field_sizes).map {|field, size|
    +      case justification
    +      in Justification::Left   then field.ljust(size)
    +      in Justification::Right  then field.rjust(size)
    +      in Justification::Center then field.center(size)
    +      end
    +    }.join(' ')
    +  end
    +end
    +
    +DSV = <<-EOT
    +  Given$a$text$file$of$many$lines,$where$fields$within$a$line$
    +  are$delineated$by$a$single$'dollar'$character,$write$a$program
    +  that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
    +  column$are$separated$by$at$least$one$space.
    +  Further,$allow$for$each$word$in$a$column$to$be$either$left$
    +  justified,$right$justified,$or$center$justified$within$its$column.
    +  EOT
    +
    +Justification.values.each do |just|
    +  puts "#{just}:"
    +  align_columns DSV, just
    +  puts
    +end
    diff --git a/Task/Align-columns/Emacs-Lisp/align-columns.el b/Task/Align-columns/Emacs-Lisp/align-columns.el
    new file mode 100644
    index 0000000000..3588e6e422
    --- /dev/null
    +++ b/Task/Align-columns/Emacs-Lisp/align-columns.el
    @@ -0,0 +1,134 @@
    +(defun prepare-data ()
    +  "Process data into list of lists."
    +  (let ((all-lines)
    +        (processed-line))
    +    (dolist (one-line (split-string "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
    +are$delineated$by$a$single$'dollar'$character,$write$a$program
    +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
    +column$are$separated$by$at$least$one$space.
    +Further,$allow$for$each$word$in$a$column$to$be$either$left$
    +justified,$right$justified,$or$center$justified$within$its$column." "[\n\r]" :OMIT-NULLS))
    +      (dolist (one-word (split-string one-line "\\$"))
    +        (push one-word processed-line))
    +      (push (nreverse processed-line) all-lines)
    +      (setq processed-line nil))
    +    (nreverse all-lines)))
    +
    +(defun get-column (column-number data)
    +  "Get words from COLUMN-NUMBER column in DATA."
    +  (let ((column-result))
    +    (setq column-number (- column-number 1))
    +    (dolist (line data)
    +      (if (nth column-number line)
    +          (push (nth column-number line) column-result)
    +        (push "" column-result)))
    +    column-result))
    +
    +(defun calc-column-width (column-number data)
    +  "Calculate padded width for COLUMN-NUMBER in DATA."
    +  (let ((column-words (get-column column-number data)))
    +    (+ 2 (apply #'max (mapcar #'length column-words)))))
    +
    +(defun get-last-column (data)
    +  "Find the last column in DATA."
    +  (apply #'max (mapcar #'length data)))
    +
    +(defun get-column-widths (data)
    +  "Get a list of column widths from DATA."
    +  (let ((current-column 1)
    +        (last-column (get-last-column data))
    +        (column-widths))
    +    (while (<= current-column last-column)
    +      (push (calc-column-width current-column data) column-widths)
    +      (setq current-column (1+ current-column)))
    +    (nreverse column-widths)))
    +
    +(defun get-one-column-width (column-number data)
    +  "Get column width of COLUMN-NUMBER from DATA."
    +  (let ((column-widths (get-column-widths data)))
    +    (nth (- column-number 1) column-widths)))
    +
    +(defun center-align-one-word (word column-width)
    +  "Center align WORD in space of COLUMN-WIDTH."
    +  (let* ((word-width (length word))
    +         (total-padding (- column-width word-width))
    +        (pre-padding-length (/ total-padding 2))
    +        (post-padding-length (- column-width (+ pre-padding-length word-width)))
    +        (pre-padding (make-string pre-padding-length ? ))
    +        (post-padding (make-string post-padding-length ? )))
    +     (insert (format "%s%s%s" pre-padding word post-padding))))
    +
    +(defun center-align-one-line (one-line column-widths)
    +  "Center align ONE-LINE using COLUMN-WIDTHS."
    +  (let ((word-position 0))
    +    (dolist (word one-line)
    +      (center-align-one-word word (nth word-position column-widths))
    +      (setq word-position (1+ word-position)))))
    +
    +(defun center-align-lines (data)
    +  "Center align columns of words in DATA."
    +  (let ((column-widths (get-column-widths data)))
    +    (dolist (one-line data)
    +      (center-align-one-line one-line column-widths)
    +      (insert (format "%s" "\n")))))
    +
    +(defun left-align-one-word (word column-width)
    +  "Left align WORD in space of COLUMN-WIDTH."
    +  (let* ((word-width (length word))
    +         (total-padding (- column-width word-width))
    +        (pre-padding-length 1)
    +        (post-padding-length (- column-width (+ pre-padding-length word-width)))
    +        (pre-padding (make-string pre-padding-length ? ))
    +        (post-padding (make-string post-padding-length ? )))
    +     (insert (format "%s%s%s" pre-padding word post-padding))))
    +
    +(defun left-align-one-line (one-line column-widths)
    +  "Left align ONE-LINE using COLUMN-WIDTHS."
    +  (let ((word-position 0))
    +    (dolist (word one-line)
    +      (left-align-one-word word (nth word-position column-widths))
    +      (setq word-position (1+ word-position)))))
    +
    +(defun left-align-lines (data)
    +  "Left align columns of words in DATA."
    +  (let ((column-widths (get-column-widths data)))
    +    (dolist (one-line data)
    +      (left-align-one-line one-line column-widths)
    +      (insert (format "%s" "\n")))))
    +
    +(defun right-align-one-word (word column-width)
    +  "Right align WORD in space of COLUMN-WIDTH."
    +  (let* ((word-width (length word))
    +         (total-padding (- column-width word-width))
    +        (post-padding-length 1)
    +        (pre-padding-length (- column-width (+ post-padding-length word-width)))
    +        (pre-padding (make-string pre-padding-length ? ))
    +        (post-padding (make-string post-padding-length ? )))
    +     (insert (format "%s%s%s" pre-padding word post-padding))))
    +
    +(defun right-align-one-line (one-line column-widths)
    +  "Right align ONE-LINE using COLUMN-WIDTHS."
    +  (let ((word-position 0))
    +    (dolist (word one-line)
    +      (right-align-one-word word (nth word-position column-widths))
    +      (setq word-position (1+ word-position)))))
    +
    +(defun right-align-lines (data)
    +  "Right align columns of words in DATA."
    +  (let ((column-widths (get-column-widths data)))
    +    (dolist (one-line data)
    +      (right-align-one-line one-line column-widths)
    +      (insert (format "%s" "\n")))))
    +
    +(defun align-lines (alignment data)
    +  "Write DATA with given ALIGNMENT.
    +DATA consists of a list of lists. Each internal list conists of a list
    +of words."
    +  (let ((align-function (pcase alignment
    +                          ('left 'left-align-lines)
    +                          ("left" 'left-align-lines)
    +                          ('center 'center-align-lines)
    +                          ("center" 'center-align-lines)
    +                          ('right 'right-align-lines)
    +                          ("right" 'right-align-lines))))
    +    (funcall align-function data)))
    diff --git a/Task/Align-columns/Euphoria/align-columns.eu b/Task/Align-columns/Euphoria/align-columns.eu
    new file mode 100644
    index 0000000000..6e031deaf3
    --- /dev/null
    +++ b/Task/Align-columns/Euphoria/align-columns.eu
    @@ -0,0 +1,61 @@
    +constant data = {
    +    "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
    +    "are$delineated$by$a$single$'dollar'$character,$write$a$program",
    +    "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
    +    "column$are$separated$by$at$least$one$space.",
    +    "Further,$allow$for$each$word$in$a$column$to$be$either$left$",
    +    "justified,$right$justified,$or$center$justified$within$its$column."
    +}
    +
    +function split(sequence s, integer c)
    +    sequence out
    +    integer first, delim
    +    out = {}
    +    first = 1
    +    while first<=length(s) do
    +        delim = find_from(c,s,first)
    +        if delim = 0 then
    +            delim = length(s)+1
    +        end if
    +        out = append(out,s[first..delim-1])
    +        first = delim + 1
    +    end while
    +    return out
    +end function
    +
    +function align(sequence s, integer width, integer alignment)
    +    integer n
    +    n = width - length(s)
    +    if n <= 0 then
    +        return s
    +    elsif alignment < 0 then
    +        return s & repeat(' ', n)
    +    elsif alignment > 0 then
    +        return repeat(' ', n) & s
    +    else
    +        return repeat(' ', floor(n/2)) & s & repeat(' ', floor(n/2+0.5))
    +    end if
    +end function
    +
    +integer maxlen
    +sequence lines
    +maxlen = 0
    +lines = repeat(0,length(data))
    +for i = 1 to length(data) do
    +    lines[i] = split(data[i],'$')
    +    for j = 1 to length(lines[i]) do
    +        if length(lines[i][j]) > maxlen then
    +            maxlen = length(lines[i][j])
    +        end if
    +    end for
    +end for
    +
    +for a = -1 to 1 do
    +    for i = 1 to length(lines) do
    +        for j = 1 to length(lines[i]) do
    +            puts(1, align(lines[i][j],maxlen,a) & ' ')
    +        end for
    +        puts(1,'\n')
    +    end for
    +    puts(1,'\n')
    +end for
    diff --git a/Task/Align-columns/PowerShell/align-columns.ps1 b/Task/Align-columns/PowerShell/align-columns.ps1
    new file mode 100644
    index 0000000000..3cfe07a5d2
    --- /dev/null
    +++ b/Task/Align-columns/PowerShell/align-columns.ps1
    @@ -0,0 +1,22 @@
    +$file =
    +@'
    +Given$a$text$file$of$many$lines,$where$fields$within$a$line$
    +are$delineated$by$a$single$'dollar'$character,$write$a$program
    +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
    +column$are$separated$by$at$least$one$space.
    +Further,$allow$for$each$word$in$a$column$to$be$either$left$
    +justified,$right$justified,$or$center$justified$within$its$column.
    +'@.Split("`n")
    +
    +$arr = @()
    +$file | foreach {
    +    $line = $_
    +    $i = 0
    +    $hash = [ordered]@{}
    +    $line.split('$') | foreach{
    +        $hash["$i"] = "$_"
    +        $i++
    +     }
    +    $arr += @([pscustomobject]$hash)
    +}
    +$arr | Format-Table -HideTableHeaders -Wrap *
    diff --git a/Task/Align-columns/Rebol/align-columns.rebol b/Task/Align-columns/Rebol/align-columns.rebol
    new file mode 100644
    index 0000000000..4af5a57fd6
    --- /dev/null
    +++ b/Task/Align-columns/Rebol/align-columns.rebol
    @@ -0,0 +1,58 @@
    +Rebol [
    +    Title: "Align Columns"
    +    URL: http://rosettacode.org/wiki/Align_columns
    +]
    +
    +specimen: {Given$a$text$file$of$many$lines,$where$fields$within$a$line$
    +are$delineated$by$a$single$'dollar'$character,$write$a$program
    +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
    +column$are$separated$by$at$least$one$space.
    +Further,$allow$for$each$word$in$a$column$to$be$either$left$
    +justified,$right$justified,$or$center$justified$within$its$column.}
    +
    +; Parse specimen into data grid.
    +data: copy []
    +
    +either function? get/any 'split [
    +    ;; Rebol 3 version
    +    foreach line split-lines specimen [
    +        append/only data split line #"$"
    +    ]
    +][  ;; Rebol 2 version
    +    foreach line parse specimen to-string lf [ ; Break into lines.
    +        append/only data parse line "$"        ; Break into columns.
    +    ]
    +]
    +; Compute independent widths for each column.
    +widths: copy []  insert/dup widths 0 length? data/1
    +foreach line data [
    +    forall line [
    +        i: index? line
    +        widths/:i: max widths/:i length? line/1
    +    ]
    +]
    +
    +pad: func [n /local x][x: copy ""  insert/dup x " " n  x]
    +; These formatting functions are passed as arguments to entable.
    +right:  func [n s][rejoin [pad n - length? s  s]]
    +left:   func [n s][rejoin [s  pad n - length? s]]
    +centre: func [n s /local h][
    +    h: round/down (n - length? s) / 2
    +    rejoin [pad h  s  pad n - h - length? s]
    +]
    +
    +; Display data as table.
    +entable: func [data format] [
    +    foreach line data [
    +        forall line [
    +            prin rejoin [format  pick widths index? line  line/1  " "]
    +        ]
    +        print ""
    +    ]
    +]
    +
    +; Format data table.
    +foreach i [left centre right] [
    +    print ["^/Align" i "...^/"]
    +    entable data get i
    +]
    diff --git a/Task/Align-columns/VBScript/align-columns.vbs b/Task/Align-columns/VBScript/align-columns.vbs
    new file mode 100644
    index 0000000000..902397b02e
    --- /dev/null
    +++ b/Task/Align-columns/VBScript/align-columns.vbs
    @@ -0,0 +1,62 @@
    +' Align columns - RC - VBScript
    +	Const nr=16, nc=16
    +	ReDim d(nc),t(nr), wor(nr,nc)
    +	i=i+1: t(i) = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"
    +	i=i+1: t(i) = "are$delineated$by$a$single$'dollar'$character,$write$a$program"
    +	i=i+1: t(i) = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"
    +	i=i+1: t(i) = "column$are$separated$by$at$least$one$space."
    +	i=i+1: t(i) = "Further,$allow$for$each$word$in$a$column$To$be$either$left$"
    +	i=i+1: t(i) = "justified,$right$justified,$or$center$justified$within$its$column."
    +	For r=1 to nr
    +		If t(r)="" Then Exit For
    +		w=xRTrim(t(r),"$")
    +		m=Split(w,"$")
    +		For c=1 To UBound(m)+1
    +			wor(r,c)=m(c-1)
    +			If Len(wor(r,c))>d(c) Then d(c)=Len(wor(r,c))
    +		Next 'c
    +		If c>cols Then cols=c
    +	Next 'r
    +	rows=r-1
    +	tt=Array("Left","Right","Center")
    +	For n=1 To 3
    +		Wscript.Echo
    +		Wscript.Echo "*****" & tt(n-1) & "*****"
    +		For r=1 To rows
    +			w=""
    +			For c=1 To cols
    +				x=wor(r,c): s=Space(d(c))
    +				Select Case n
    +					Case 1: w=w &" "& Left   (x & s,d(c))
    +					Case 2: w=w &" "& Right  (s & x,d(c))
    +					Case 3: w=w &" "& xCentre(x,d(c)," ")
    +				End Select 'n
    +			Next 'c
    +			Wscript.Echo Mid(w,2)
    +		Next 'r
    +	Next 'n
    +	
    +Function xCentre(c, n, Pad)
    +    Dim j
    +    If n > Len(c) Then
    +		j = (n - Len(c)) \  2
    +		If (n - Len(c)) Mod 2 <> 0 Then j = j + 1
    +		xCentre = Mid(String(j, Pad) & c & String(j, Pad), 1, n)
    +    Else
    +		xCentre = c
    +    End If
    +End Function 'xCentre
    +
    +Function xRTrim(c, Pad)
    +	Dim i2, l, cc
    +	cc = "": l = Len(c)
    +	If l > 0 Then
    +		i2 = l
    +		Do While (Mid(c, i2, 1) = Pad And i2 > 1)
    +			i2 = i2 - 1
    +		Loop
    +		If i2 = 1 And Mid(c, i2, 1) = Pad Then i2 = 0
    +		If i2 > 0 Then cc = Mid(c, 1, i2)
    +	End If
    +	xRTrim = cc
    +End Function 'xRTrim
    diff --git a/Task/Aliquot-sequence-classifications/Crystal/aliquot-sequence-classifications.cr b/Task/Aliquot-sequence-classifications/Crystal/aliquot-sequence-classifications.cr
    new file mode 100644
    index 0000000000..5c4c4e4100
    --- /dev/null
    +++ b/Task/Aliquot-sequence-classifications/Crystal/aliquot-sequence-classifications.cr
    @@ -0,0 +1,35 @@
    +def sum_proper_divisors (n)
    +  z = n.class.zero
    +  (z+1..n//2).sum(z) {|i| n % i == 0 ? i : 0 }
    +end
    +
    +def aliquot (n)
    +  seq = [n]
    +  limit = 2_i64**47
    +  15.times do
    +    n = sum_proper_divisors(n)
    +    case n
    +    when 0         then return { "terminating", seq << n }
    +    when .>(limit) then return { "non-terminating", seq << n }
    +    when seq[0]    then return { case seq.size
    +                                 when 1 then "perfect"
    +                                 when 2 then "amicable"
    +                                 else "sociable"
    +                                 end, seq }
    +    when seq.last  then return { "aspiring", seq }
    +    when .in?(seq) then return { "cyclic", seq << n }
    +    end
    +    seq << n
    +  end
    +  { "non-terminating", seq }
    +end
    +
    +(1..10).each do |i|
    +  kind, seq = aliquot(i)
    +  puts "%s: %s" % { kind, seq }
    +end
    +puts
    +[11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488].each do |i|
    +  kind, seq = aliquot(i)
    +  puts "%s: %s" % { kind, seq }
    +end
    diff --git a/Task/Aliquot-sequence-classifications/Pluto/aliquot-sequence-classifications.pluto b/Task/Aliquot-sequence-classifications/Pluto/aliquot-sequence-classifications.pluto
    new file mode 100644
    index 0000000000..f4301abc48
    --- /dev/null
    +++ b/Task/Aliquot-sequence-classifications/Pluto/aliquot-sequence-classifications.pluto
    @@ -0,0 +1,56 @@
    +local int = require "int"
    +local fmt = require "fmt"
    +require "table2"
    +
    +$define THRESHOLD = 1 << 47
    +
    +class classification
    +    function __construct(public seq, public aliquot) end
    +end
    +
    +local function classify_sequence(k)
    +    assert(k > 0, "K must be positive")
    +    local last = k
    +    local seq = {k}
    +    while true do
    +        last = int.divisors(last, true):sum()
    +        seq:insert(last)
    +        local n = #seq
    +        local aliquot = ""
    +        if last == 0 then
    +            aliquot = "Terminating"
    +        elseif n == 2 and last == k then
    +            aliquot = "Perfect"
    +        elseif n == 3 and last == k then
    +            aliquot = "Amicable"
    +        elseif n >= 4 and last == k then
    +            aliquot = $"Sociable[{n - 1}]"
    +        elseif last == seq[n - 1] then
    +            aliquot = "Aspiring"
    +        elseif n > 3 and (last in seq:slice(2, n - 2)) then
    +            local ix = seq:findindex(|e| -> e == last) ?? -1
    +            aliquot = $"Cyclic[{n - ix}]"
    +        elseif n == 16 or last > THRESHOLD then
    +            aliquot = "Non-terminating"
    +        end
    +        if aliquot != "" then return new classification(seq, aliquot) end
    +    end
    +end
    +
    +print("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n")
    +for k = 1, 10 do
    +    local c = classify_sequence(k)
    +    fmt.print("%2d: %-15s %,s", k, c.aliquot, c.seq)
    +end
    +
    +print()
    +local a = {11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488}
    +for a as k do
    +    local c = classify_sequence(k)
    +    fmt.print("%7d: %-15s %,s", k, c.aliquot, c.seq)
    +end
    +
    +print()
    +local k = 15355717786080
    +local c = classify_sequence(k)
    +fmt.print("%d: %-15s %,s", k, c.aliquot, c.seq)
    diff --git a/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-1.ps1 b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-1.ps1
    new file mode 100644
    index 0000000000..1ffa188a7b
    --- /dev/null
    +++ b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-1.ps1
    @@ -0,0 +1,34 @@
    +function Get-NextAliquot ( [int]$X )
    +    {
    +    If ( $X -gt 1 )
    +        {
    +        $NextAliquot = 0
    +        (1..($X/2)).Where{ $x % $_ -eq 0 }.ForEach{ $NextAliquot += $_ }.Where{ $_ }
    +        return $NextAliquot
    +        }
    +    }
    +
    +function Get-AliquotSequence ( [int]$K, [int]$N )
    +    {
    +    $X = $K
    +    $X
    +    (1..($N-1)).ForEach{ $X = Get-NextAliquot $X; $X }
    +    }
    +
    +function Classify-AlliquotSequence ( [int[]]$Sequence )
    +    {
    +    $K = $Sequence[0]
    +    $LastN = $Sequence.Count
    +    If ( $Sequence[-1] -eq 0 ) { return "terminating" }
    +    If ( $Sequence[-1] -eq 1 ) { return "terminating" }
    +    If ( $Sequence[1] -eq $K ) { return "perfect"     }
    +    If ( $Sequence[2] -eq $K ) { return "amicable"    }
    +    If ( $Sequence[3..($Sequence.Count-1)] -contains $K ) { return "sociable" }
    +    If ( $Sequence[-1] -eq $Sequence[-2] ) { return "aspiring" }
    +    If ( $Sequence.Count -gt ( $Sequence | Select -Unique ).Count ) { return "cyclic" }
    +    return "non-terminating and non-repeating through N = $($Sequence.Count)"
    +    }
    +
    +(1..10).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
    +
    +( 11, 12, 28, 496, 220, 1184, 790, 909, 562, 1064, 1488 ).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
    diff --git a/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-2.ps1 b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-2.ps1
    new file mode 100644
    index 0000000000..33b3d4fa4f
    --- /dev/null
    +++ b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-2.ps1
    @@ -0,0 +1,63 @@
    +function Get-NextAliquot ( [int]$X )
    +    {
    +    If ( $X -gt 1 )
    +        {
    +        $NextAliquot = 1
    +        If ( $X -gt 2 )
    +            {
    +            $XSquareRoot = [math]::Sqrt( $X )
    +
    +            (2..$XSquareRoot).Where{ $X % $_ -eq 0 }.ForEach{ $NextAliquot += $_ + $x / $_ }
    +
    +            If ( $XSquareRoot % 1 -eq 0 ) { $NextAliquot -= $XSquareRoot }
    +            }
    +        return $NextAliquot
    +        }
    +    }
    +
    +function Get-AliquotSequence ( [int]$K, [int]$N )
    +    {
    +    $X = $K
    +    $X
    +    $i = 1
    +    While ( $X -and $i -lt $N )
    +        {
    +        $i++
    +        $Next = Get-NextAliquot $X
    +        If ( $Next )
    +            {
    +            If ( $X -eq $Next )
    +                {
    +                ($i..$N).ForEach{ $X }
    +                $i = $N
    +                }
    +            Else
    +                {
    +                $X = $Next
    +                $X
    +                }
    +            }
    +        Else
    +            {
    +            $i = $N
    +            }
    +        }
    +    }
    +
    +function Classify-AlliquotSequence ( [int[]]$Sequence )
    +    {
    +    $K = $Sequence[0]
    +    $LastN = $Sequence.Count
    +    If ( $Sequence[-1] -eq 0 ) { return "terminating" }
    +    If ( $Sequence[-1] -eq 1 ) { return "terminating" }
    +    If ( $Sequence[1] -eq $K ) { return "perfect"     }
    +    If ( $Sequence[2] -eq $K ) { return "amicable"    }
    +    If ( $Sequence[3..($Sequence.Count-1)] -contains $K ) { return "sociable" }
    +    If ( $Sequence[-1] -eq $Sequence[-2] ) { return "aspiring" }
    +    If ( $Sequence.Count -gt ( $Sequence | Select -Unique ).Count ) { return "cyclic" }
    +    return "non-terminating and non-repeating through N = $($Sequence.Count)"
    +    }
    +
    +(1..10).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
    +
    +( 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 ).ForEach{ [string]$_ + " is " + ( Classify-AlliquotSequence -Sequence ( Get-AliquotSequence -K $_ -N 16 ) ) }
    diff --git a/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.ps1 b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.ps1
    new file mode 100644
    index 0000000000..9999c547fc
    --- /dev/null
    +++ b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-3.ps1
    @@ -0,0 +1,90 @@
    +function Get-Aliquot
    +{
    +    [CmdletBinding()]
    +    [OutputType([PScustomObject])]
    +    Param
    +    (
    +        [Parameter(Mandatory=$true,
    +                   ValueFromPipeline=$true,
    +                   ValueFromPipelineByPropertyName=$true)]
    +        [int]
    +        $InputObject
    +    )
    +
    +    Begin
    +    {
    +        function Get-NextAliquot ([int]$X)
    +        {
    +            if ($X -gt 1)
    +            {
    +                $nextAliquot = 1
    +
    +                if ($X -gt 2)
    +                {
    +                    $xSquareRoot = [Math]::Sqrt($X)
    +
    +                    2..$xSquareRoot | Where-Object {$X % $_ -eq 0} | ForEach-Object {$nextAliquot += $_ + $x / $_}
    +
    +                    if ($xSquareRoot % 1 -eq 0) {$nextAliquot -= $xSquareRoot}
    +                }
    +
    +                $nextAliquot
    +            }
    +        }
    +
    +        function Get-AliquotSequence ([int]$K, [int]$N)
    +        {
    +            $X = $K
    +            $X
    +            $i = 1
    +
    +            while ($X -and $i -lt $N)
    +            {
    +                $i++
    +                $next = Get-NextAliquot $X
    +
    +                if ($next)
    +                {
    +                    if ($X -eq $next)
    +                    {
    +                        $i..$N  | ForEach-Object {$X}
    +                        $i = $N
    +                    }
    +                    else
    +                    {
    +                        $X = $next
    +                        $X
    +                    }
    +                }
    +                else
    +                {
    +                    $i = $N
    +                }
    +            }
    +        }
    +
    +        function Classify-AlliquotSequence ([int[]]$Sequence)
    +        {
    +            $k = $Sequence[0]
    +
    +            if ($Sequence[-1] -eq 0)                                     {return "terminating"}
    +            if ($Sequence[-1] -eq 1)                                     {return "terminating"}
    +            if ($Sequence[1]  -eq $k)                                    {return "perfect"    }
    +            if ($Sequence[2]  -eq $k)                                    {return "amicable"   }
    +            if ($Sequence[3..($Sequence.Count-1)] -contains $k)          {return "sociable"   }
    +            if ($Sequence[-1] -eq $Sequence[-2] )                        {return "aspiring"   }
    +            if ($Sequence.Count -gt ($Sequence | Select -Unique).Count ) {return "cyclic"     }
    +
    +            return "non-terminating and non-repeating through N = $($Sequence.Count)"
    +        }
    +    }
    +    Process
    +    {
    +        $_ | ForEach-Object {
    +            [PSCustomObject]@{
    +                Number         = $_
    +                Classification = (Classify-AlliquotSequence -Sequence (Get-AliquotSequence -K $_ -N 16))
    +            }
    +        }
    +    }
    +}
    diff --git a/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.ps1 b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.ps1
    new file mode 100644
    index 0000000000..d6e159aeda
    --- /dev/null
    +++ b/Task/Aliquot-sequence-classifications/PowerShell/aliquot-sequence-classifications-4.ps1
    @@ -0,0 +1,5 @@
    +$oneToTen = 1..10 | Get-Aliquot
    +$selected = 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 | Get-Aliquot
    +
    +$numbers = $oneToTen, $selected
    +$numbers
    diff --git a/Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.adb b/Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.adb
    new file mode 100644
    index 0000000000..400094aff2
    --- /dev/null
    +++ b/Task/Almkvist-Giullera-formula-for-pi/Ada/almkvist-giullera-formula-for-pi.adb
    @@ -0,0 +1,94 @@
    +-- Big_Reals is an Ada 2022 unit
    +with Ada.Numerics.Big_Numbers.Big_Reals;
    +with Ada.Text_IO;
    +
    +use Ada.Numerics.Big_Numbers.Big_Reals;
    +
    +procedure Almkvist_Giullera is
    +
    +   function "+" (B : Big_Real; A : Integer) return Big_Real is (B + To_Real (A));
    +   function "*" (A : Integer; B : Big_Real) return Big_Real is (To_Real (A) * B);
    +   B0 : constant Big_Real := To_Real (0);
    +   B1 : constant Big_Real := B0 + 1;
    +
    +   function Factorial (N : Big_Real) return Big_Real
    +   is
    +      I : Big_Real := N;
    +      F : Big_Real := B1;
    +   begin
    +      while I > B1 loop
    +         F := F * I;
    +         I := I - B1;
    +      end loop;
    +
    +      return F;
    +   end Factorial;
    +
    +   function F (N : Big_Real) return Big_Real renames Factorial;
    +   procedure Put_Line (S : String) renames Ada.Text_IO.Put_Line;
    +
    +   function Integer_Term (N : Big_Real) return Big_Real is
    +     (32 * F (6 * N) / (3 * F (N) ** 6) * (532 * N ** 2 + 126 * N + 9));
    +
    +   procedure Show_Integer_Terms (N : Positive) is
    +   begin
    +      for I in 0 .. N - 1 loop
    +         Put_Line ("Almkvist-Giullera integer term "
    +                   & I'Image & " is "
    +                   & To_String (Integer_Term (To_Real (I)), Aft => 0));
    +      end loop;
    +   end Show_Integer_Terms;
    +
    +   -- Use Newton's Method
    +   function Sqrt (N : Big_Real; Precision : Positive) return Big_Real is
    +      Diff : Big_Real := To_Real (10) ** (-Precision);
    +      Estimate : Big_Real := B0;
    +      Next : Big_Real := N;
    +   begin
    +      while abs (Next - Estimate) > Diff loop
    +         Estimate := Next;
    +         Next := Estimate - (Estimate ** 2 - N) / (2 * Estimate);
    +         -- Nasty hack to limit precision. Otherwise there is a storage error.
    +         Next := From_String (To_String (Next, Aft => Precision + 2));
    +      end loop;
    +
    +      return Estimate;
    +   end Sqrt;
    +
    +   function Estimate_Pi (N : Integer; Precision : Positive) return Big_Real is
    +      Sum : Big_Real := B0;
    +   begin
    +      for I in 0 .. N loop
    +         Sum := Sum + Integer_Term (To_Real (I)) / To_Real (10) ** (6 * I + 3);
    +         Sum := From_String (To_String (Sum, Aft => Precision + 2));
    +      end loop;
    +
    +      return B1 / Sqrt (Sum, Precision + 2);
    +   end Estimate_Pi;
    +
    +   function Compute_Pi (Precision : Positive) return Big_Real is
    +      Diff : constant Big_Real := To_Real (10) ** (-Precision);
    +      Pi_Estimate : Big_Real := B0;
    +      Next : Big_Real := B1;
    +      N : Integer := 1;
    +   begin
    +      while abs (Next - Pi_Estimate) > Diff loop
    +         N := N * 2;
    +         Pi_Estimate := Next;
    +         Next := Estimate_Pi (N, Precision);
    +      end loop;
    +
    +      return Pi_Estimate;
    +   end Compute_Pi;
    +
    +   procedure Show_Pi (Precision : Positive) is
    +      Pi : constant Big_Real := Compute_Pi (Precision);
    +   begin
    +      Put_Line ("Pi to " & Precision'Image & " places is "
    +                & To_String (Pi, Aft => Precision));
    +   end Show_Pi;
    +
    +begin
    +   Show_Integer_Terms (10);
    +   Show_Pi (70);
    +end almkvist_giullera;
    diff --git a/Task/Almkvist-Giullera-formula-for-pi/FutureBasic/almkvist-giullera-formula-for-pi.basic b/Task/Almkvist-Giullera-formula-for-pi/FutureBasic/almkvist-giullera-formula-for-pi.basic
    new file mode 100644
    index 0000000000..87aaa6d0a3
    --- /dev/null
    +++ b/Task/Almkvist-Giullera-formula-for-pi/FutureBasic/almkvist-giullera-formula-for-pi.basic
    @@ -0,0 +1,139 @@
    +//
    +//   FutureBasic 7.0.35 —  Almkvist–Giullera PI
    +//
    +//  September 2025, R.W.
    +
    +include "mpfr.incl"
    +
    +long PRECISION
    +long n
    +
    +// Almkvist–Giullera PI estimate via MPFR (256-bit).
    +//
    +// 1 / π² = 32 × Σ (from n = 0 to ∞) [ (6n)! / (3 × (n!)⁶) × ¬
    +//         (532n² + 126n + 9) × 1 / (10^(6n + 3)) ]
    +
    +void local fn AG_Pi256_Compute ( AgPI as mpfr_t )
    +  long tmp
    +  CFStringRef pLine
    +  Boolean iterating = _True
    +
    +  mpz_t t1, t2, t3
    +  mpfr_t f1, f2, sum, prev, diff, epsilon
    +
    +  // Init big integers
    +  mpz_init( t1 )
    +  mpz_init( t2 )
    +  mpz_init( t3 )
    +
    +  // Init MPFR floats at 256 bits
    +
    +  mpfr_init2(        f1, PRECISION )
    +  mpfr_init2(        f2, PRECISION )
    +  mpfr_init2(       sum, PRECISION )
    +  mpfr_init2(      prev, PRECISION )
    +  mpfr_init2(      diff, PRECISION )
    +  mpfr_init2(   epsilon, PRECISION )
    +
    +  // Looking at accuracy of 70 decimal digits
    +  // Set epsilon to = 10^-70
    +
    +  fn mpfr_set_ui( epsilon, 10, MPFR_RNDN)
    +  fn mpfr_pow_ui( epsilon, epsilon, 70, MPFR_RNDN )
    +  fn mpfr_ui_div( epsilon, 1, epsilon, MPFR_RNDN )
    +
    +  // sum = 0
    +  fn mpfr_set_ui( sum, 0, MPFR_RNDN )
    +
    +  // Sum_{n = 0..kTerms}
    +  // ( (6n)! * (532 n^2 + 126 n + 9) * 2^5 ) / ( 3 * (n!)^6 * 10^(6n+3) )
    +  //
    +  While iterating
    +    mpz_fac_ui( t1, 6 * n )    // t1 = (6n)!
    +    //                         // t2 = 532 n^2 + 126 n + 9
    +    mpz_ui_pow_ui( t2, n, 2 )  // t2 = n^2
    +    mpz_mul_ui( t2, t2, 532 )  // 532 n^2
    +    mpz_set_ui( t3, n )        // t3 = n
    +    mpz_mul_ui( t3, t3, 126 )  // 126 n
    +    mpz_add( t2, t2, t3 )      // 532 n^2 + 126 n
    +    mpz_add_ui( t2, t2, 9 )    // + 9
    +    //                         // t3 = 3 * (n!)^6
    +    mpz_fac_ui( t3, n )        // t3 = n!
    +    mpz_pow_ui( t3, t3, 6 )    // (n!)^6
    +    mpz_mul_ui( t3, t3, 3 )    // 3 * (n!)^6
    +    //                         // t1 = t1 * t2 * 2^5 / t3
    +    mpz_mul( t1, t1, t2 )      // t1 = t1 * t2
    +    mpz_mul_2exp( t1, t1, 5 )  // t1 = t1 * t1 ^5
    +    mpz_divexact( t1, t1, t3 ) // t1 = t1 / t3
    +
    +    // Print t1 if n less than 10
    +    // to fullfil Rosetta Task requirement
    +    if n < 10
    +      pLine = @""
    +      pLine = fn mpz_cf(10,t1)
    +      pLine = concat(str(n),@" | ",pLine)
    +      print @ pLine
    +      if n == 9
    +        print@
    +        print@ "Estimating PI.."
    +        print @
    +      end if
    +    end if
    +
    +    // f1 = t1 / 10^(6n+3)
    +    fn mpfr_set_z( f1, t1, MPFR_RNDN )
    +    tmp = 6 * n + 3
    +    fn mpfr_set_ui( f2, 10, MPFR_RNDN )
    +    fn mpfr_pow_ui( f2, f2, tmp, MPFR_RNDN )
    +    fn mpfr_div( f1, f1, f2, MPFR_RNDN )
    +    // sum += f1
    +    fn mpfr_add( sum, sum, f1, MPFR_RNDN )
    +    // find the difference between previous sum and current
    +    fn mpfr_sub( diff, sum, prev, MPFR_RNDN)
    +    //mpfr_set_ui(prev, 10, MPFR_RNDN )    //sum -> prev
    +    fn mpfr_set(prev, sum, MPFR_RNDN)
    +
    +    // if (sum - prev) < epsilon, then we're done
    +
    +    if (fn mpfr_cmpabs( diff, epsilon ) < 0 ) then iterating = _False
    +    fn mpfr_sqrt( f2, sum, MPFR_RNDN )
    +    fn mpfr_ui_div( AgPI, 1, f2, MPFR_RNDN ) // 1 / sqrt(sum)
    +    n++
    +  wend
    +
    +  // Final output
    +  print @fn mpfr_cf2(71, AgPi, MPFR_RNDN)
    +  print@
    +  print @"70 decimal digits accuracy achieved after ";n;" iterations."
    +
    +  // Cleanup
    +  mpfr_clear( epsilon )
    +  mpfr_clear( diff )
    +  mpfr_clear( prev )
    +  mpfr_clear( sum )
    +  mpfr_clear( f2 )
    +  mpfr_clear( f1 )
    +  mpz_clear( t3 )
    +  mpz_clear( t2 )
    +  mpz_clear( t1 )
    +
    +end fn
    +
    +//------------------ Main
    +window 1, @"Almkvist–Giullera PI"
    +print@
    +print " n |              Integer of Nth term"
    +printf fn StringByPaddingToLength( @"", 48, @"-", 0 )
    +
    +PRECISION = 256
    +mpfr_t AgPi
    +mpfr_init2( AgPI, PRECISION )
    +
    +fn AG_Pi256_Compute ( AgPI )
    +
    +mpfr_clear( AgPI )
    +
    +
    +HandleEvents
    +
    +//
    diff --git a/Task/Almkvist-Giullera-formula-for-pi/Phix/almkvist-giullera-formula-for-pi.phix b/Task/Almkvist-Giullera-formula-for-pi/Phix/almkvist-giullera-formula-for-pi.phix
    index 0cb0773019..42386d1df4 100644
    --- a/Task/Almkvist-Giullera-formula-for-pi/Phix/almkvist-giullera-formula-for-pi.phix
    +++ b/Task/Almkvist-Giullera-formula-for-pi/Phix/almkvist-giullera-formula-for-pi.phix
    @@ -1,53 +1,51 @@
    -(phixonline)-->
    - with javascript_semantics
    - requires("1.0.0")
    - include mpfr.e
    - mpfr_set_default_precision(-70)
    +with javascript_semantics
    +requires("1.0.0")
    +include mpfr.e
    +mpfr_set_default_precision(-70)
     
    - function almkvistGiullera(integer n, bool bPrint)
    -     mpz {t1,t2,ip} = mpz_inits(3)
    -     mpz_fac_ui(t1,6*n)
    -     mpz_mul_si(t1,t1,32)                -- t1:=2^5*(6n)!
    -     mpz_fac_ui(t2,n)
    -     mpz_pow_ui(t2,t2,6)
    -     mpz_mul_si(t2,t2,3)                 -- t2:=3*(n!)^6
    -     mpz_mul_si(ip,t1,532*n*n+126*n+9)   -- ip:=t1*(532n^2+126n+9)
    -     mpz_fdiv_q(ip,ip,t2)                -- ip:=ip/t2
    -     integer pw := 6*n+3
    -     mpz_ui_pow_ui(t1,10,pw)             -- t1 := 10^(6n+3)
    -     mpq tm = mpq_init_set_z(ip,t1)      -- tm := rat(ip/t1)
    -     if bPrint then
    -         string ips = mpz_get_str(ip),
    -                tms = mpfr_get_fixed(mpfr_init_set_q(tm),50)
    -         tms = trim_tail(tms,"0")
    -         printf(1,"%d  %44s  %3d  %s\n", {n, ips, -pw, tms})
    -     end if
    -     return tm
    - end function
    +function almkvistGiullera(integer n, bool bPrint)
    +    mpz {t1,t2,ip} = mpz_inits(3)
    +    mpz_fac_ui(t1,6*n)
    +    mpz_mul_si(t1,t1,32)                -- t1:=2^5*(6n)!
    +    mpz_fac_ui(t2,n)
    +    mpz_pow_ui(t2,t2,6)
    +    mpz_mul_si(t2,t2,3)                 -- t2:=3*(n!)^6
    +    mpz_mul_si(ip,t1,532*n*n+126*n+9)   -- ip:=t1*(532n^2+126n+9)
    +    mpz_fdiv_q(ip,ip,t2)                -- ip:=ip/t2
    +    integer pw := 6*n+3
    +    mpz_ui_pow_ui(t1,10,pw)             -- t1 := 10^(6n+3)
    +    mpq tm = mpq_init_set_z(ip,t1)      -- tm := rat(ip/t1)
    +    if bPrint then
    +        string ips = mpz_get_str(ip),
    +               tms = mpfr_get_fixed(mpfr_init_set_q(tm),50)
    +        tms = trim_tail(tms,"0")
    +        printf(1,"%d  %44s  %3d  %s\n", {n, ips, -pw, tms})
    +    end if
    +    return tm
    +end function
     
    - constant hdr = "N --------------- Integer portion -------------  Pow  ----------------- Nth term (50 dp) -----------------"
    - printf(1,"%s\n%s\n",{hdr,repeat('-',length(hdr))})
    - for n=0 to 9 do
    -     {} = almkvistGiullera(n, true)
    - end for
    +constant hdr = "N --------------- Integer portion -------------  Pow  ----------------- Nth term (50 dp) -----------------"
    +printf(1,"%s\n%s\n",{hdr,repeat('-',length(hdr))})
    +for n=0 to 9 do
    +    {} = almkvistGiullera(n, true)
    +end for
     
    - mpq {res,prev,z} = mpq_inits(3),
    -     prec = mpq_init_set_str(sprintf("1/1%s",repeat('0',70)))
    - integer n = 0
    - while true do
    -     mpq term := almkvistGiullera(n, false)
    -     mpq_add(res,res,term)
    -     mpq_sub(z,res,prev)
    -     mpq_abs(z,z)
    -     if mpq_cmp(z,prec) < 0 then exit end if
    -     mpq_set(prev,res)
    -     n += 1
    - end while
    - mpq_inv(res,res)
    - mpfr pi = mpfr_init_set_q(res)
    - mpfr_sqrt(pi,pi)
    - printf(1,"\nCalculation of pi took %d iterations using the Almkvist-Giullera formula.\n\n",n)
    - printf(1,"Pi to 70 d.p.: %s\n",mpfr_get_fixed(pi,70))
    - mpfr_const_pi(pi)
    - printf(1,"Pi (builtin) : %s\n",mpfr_get_fixed(pi,70))
    -
    - -- demo\rosetta\Arithmetic_evaluation.exw
    - with javascript_semantics
    +-- demo\rosetta\Arithmetic_evaluation.exw
    +sequence opstack = {}       -- atom elements are literals,
    +                            -- sequence elements are subexpressions
    +                            -- on completion length(opstack) should be 1
    +object token
     
    - sequence opstack = {}       -- atom elements are literals,
    -                             -- sequence elements are subexpressions
    -                             -- on completion length(opstack) should be 1
    - object token
    +constant p_p_op = -1,       -- expressions stored as p1,p2,op
    +         p_op_p =  0,       -- expressions stored as p1,op,p2
    +         op_p_p = +1,       -- expressions stored as op,p1,p2
    +         opp = op_p_p
     
    - constant op_p_p = 1         --  1: expressions stored as op,p1,p2
    -     --   p_op_p             --  0: expressions stored as p1,op,p2
    -     --   p_p_op             -- -1: expressions stored as p1,p2,op
    +object op = 0   -- 0 if none, else "+", "-", "*", "/", "^", "%", or "u-"
     
    - object op = 0   -- 0 if none, else "+", "-", "*", "/", "^", "%", or "u-"
    +string s        -- the expression being parsed
    +integer ch
    +integer sidx
     
    - string s        -- the expression being parsed
    - integer ch
    - integer sidx
    +procedure err(string msg)
    +    crash("%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg})
    +end procedure
     
    - procedure err(string msg)
    -     printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg})
    -     {} = wait_key()
    -     abort(0)
    - end procedure
    +procedure nxtch(object msg="eof")
    +    sidx += 1
    +    if sidx>length(s) then
    +        if string(msg) then err(msg) end if
    +        ch = -1
    +    else
    +        ch = s[sidx]
    +    end if
    +end procedure
     
    - procedure nxtch(object msg="eof")
    -     sidx += 1
    -     if sidx>length(s) then
    -         if string(msg) then err(msg) end if
    -         ch = -1
    -     else
    -         ch = s[sidx]
    -     end if
    - end procedure
    +procedure skipspaces()
    +    while find(ch," \t\r\n") do nxtch(0) end while
    +end procedure
     
    - procedure skipspaces()
    -     while find(ch,{' ','\t','\r','\n'})!=0 do nxtch(0) end while
    - end procedure
    +procedure get_token()
    +    skipspaces()
    +    if ch=-1 then token = "eof" return end if
    +    if ch>='0' and ch<='9' then
    +        atom n = ch-'0'
    +        while 1 do
    +            nxtch(0)
    +            if ch<'0' or ch>'9' then exit end if
    +            n = n*10+(ch-'0')
    +        end while
    +        if ch='.' then
    +            integer decimal = 1
    +            atom fraction = 0
    +            while true do
    +                nxtch(0)
    +                if ch<'0' or ch>'9' then exit end if
    +                fraction = fraction*10 + (ch-'0')
    +                decimal *= 10
    +            end while
    +            n += fraction/decimal
    +        end if
    +--      if find(ch,"eE") then   -- you get the idea
    +--      end if
    +        token = n
    +        return
    +    end if
    +    if find(ch,"+-/*()^%")=0 then err("syntax error") end if
    +    token = s[sidx..sidx]
    +    nxtch(0)
    +    return
    +end procedure
     
    - procedure get_token()
    - atom n, fraction
    - integer dec
    -     skipspaces()
    -     if ch=-1 then token = "eof" return end if
    -     if ch>='0' and ch<='9' then
    -         n = ch-'0'
    -         while 1 do
    -             nxtch(0)
    -             if ch<'0' or ch>'9' then exit end if
    -             n = n*10+ch-'0'
    -         end while
    -         if ch='.' then
    -             dec = 1
    -             fraction = 0
    -             while 1 do
    -                 nxtch(0)
    -                 if ch<'0' or ch>'9' then exit end if
    -                 fraction = fraction*10 + ch-'0'
    -                 dec *= 10
    -             end while
    -             n += fraction/dec
    -         end if
    - --      if find(ch,"eE") then   -- you get the idea
    - --      end if
    -         token = n
    -         return
    -     end if
    -     if find(ch,"+-/*()^%")=0 then err("syntax error") end if
    -     token = s[sidx..sidx]
    -     nxtch(0)
    -     return
    - end procedure
    +procedure Match(string t)
    +    if token!=t then err(t&" expected") end if
    +    get_token()
    +end procedure
     
    - procedure Match(string t)
    -     if token!=t then err(t&" expected") end if
    -     get_token()
    - end procedure
    +procedure PopFactor()
    +    object p1, p2 = opstack[$], f
    +    if op="u-" then
    +        p1 = 0
    +    else
    +        opstack = opstack[1..$-1]
    +        p1 = opstack[$]
    +    end if
    +    switch opp do
    +        case op_p_p:    f = {op,p1,p2}
    +        case p_op_p:    f = {p1,op,p2}
    +        case p_p_op:    f = {p1,p2,op}
    +    end switch
    +    opstack[$] = f
    +    op = 0
    +end procedure
     
    - procedure PopFactor()
    -     object p1, p2 = opstack[$]
    -     if op="u-" then
    -         p1 = 0
    -     else
    -         opstack = opstack[1..$-1]
    -         p1 = opstack[$]
    -     end if
    -     if op_p_p=1 then
    -         opstack[$] = {op,p1,p2}  -- op_p_p
    -     elsif op_p_p=0 then
    -         opstack[$] = {p1,op,p2}  -- p_op_p
    -     else -- -1
    -         opstack[$] = {p1,p2,op}  -- p_p_op
    -     end if
    -     op = 0
    - end procedure
    +procedure PushFactor(atom t)
    +    if op!=0 then PopFactor() end if
    +    opstack = append(opstack,t)
    +end procedure
     
    - procedure PushFactor(atom t)
    -     if op!=0 then PopFactor() end if
    -     opstack = append(opstack,t)
    - end procedure
    +procedure PushOp(string t)
    +    if op!=0 then PopFactor() end if
    +    op = t
    +end procedure
     
    - procedure PushOp(string t)
    -     if op!=0 then PopFactor() end if
    -     op = t
    - end procedure
    +forward procedure Expr(integer p)
     
    - forward procedure Expr(integer p)
    +procedure Factor()
    +    if atom(token) then
    +        PushFactor(token)
    +        if ch!=-1 then
    +            get_token()
    +        end if
    +    elsif token="+" then -- (ignore)
    +        nxtch()
    +        Factor()
    +    elsif token="-" then
    +        get_token()
    +--      Factor()
    +        Expr(3) -- makes "-3^2" yield -9 (ie -(3^2)) not 9 (ie (-3)^2).
    +        if op!=0 then PopFactor() end if
    +        if integer(opstack[$]) then
    +            opstack[$] = -opstack[$]
    +        else
    +            PushOp("u-")
    +        end if
    +    elsif token="(" then
    +        get_token()
    +        Expr(0)
    +        Match(")")
    +    else
    +        err("syntax error")
    +    end if
    +end procedure
     
    - procedure Factor()
    -     if atom(token) then
    -         PushFactor(token)
    -         if ch!=-1 then
    -             get_token()
    -         end if
    -     elsif token="+" then -- (ignore)
    -         nxtch()
    -         Factor()
    -     elsif token="-" then
    -         get_token()
    - --      Factor()
    -         Expr(3) -- makes "-3^2" yield -9 (ie -(3^2)) not 9 (ie (-3)^2).
    -         if op!=0 then PopFactor() end if
    -         if integer(opstack[$]) then
    -             opstack[$] = -opstack[$]
    -         else
    -             PushOp("u-")
    -         end if
    -     elsif token="(" then
    -         get_token()
    -         Expr(0)
    -         Match(")")
    -     else
    -         err("syntax error")
    -     end if
    - end procedure
    +constant {operators,
    +          precedence,
    +          associativity} = columnize({{"^",3,0},
    +                                      {"%",2,1},
    +                                      {"*",2,1},
    +                                      {"/",2,1},
    +                                      {"+",1,1},
    +                                      {"-",1,1},
    +                                      $})
     
    - constant {operators,
    -           precedence,
    -           associativity} = columnize({{"^",3,0},
    -                                       {"%",2,1},
    -                                       {"*",2,1},
    -                                       {"/",2,1},
    -                                       {"+",1,1},
    -                                       {"-",1,1},
    -                                       $})
    +procedure Expr(integer p)
    +--
    +-- Parse an expression, using precedence climbing.
    +--
    +-- p is the precedence level we should parse to, eg/ie
    +--      4: Factor only (may as well just call Factor)
    +--      3: "" and ^
    +--      2: "" and *,/,%
    +--      1: "" and +,-
    +--      0: full expression (effectively the same as 1)
    +--  obviously, parentheses override any setting of p.
    +--
    +    Factor()
    +    while 1 do
    +        integer k = find(token,operators) -- *,/,+,-
    +        if k=0 then exit end if
    +        integer thisp = precedence[k]
    +        if thisp

    procedure Expr(integer p) - -- - -- Parse an expression, using precedence climbing. - -- - -- p is the precedence level we should parse to, eg/ie - -- 4: Factor only (may as well just call Factor) - -- 3: "" and ^ - -- 2: "" and *,/,% - -- 1: "" and +,- - -- 0: full expression (effectively the same as 1) - -- obviously, parentheses override any setting of p. - -- - integer k, thisp - Factor() - while 1 do - k = find(token,operators) -- *,/,+,- - if k=0 then exit end if - thisp = precedence[k] - if thisp<p then exit end if - get_token() - Expr(thisp+associativity[k]) - PushOp(operators[k]) - end while - end procedure +function evaluate(object s) + object lhs, rhs + string op + if atom(s) then return s end if + switch opp do + case op_p_p: {op,lhs,rhs} = s + case p_op_p: {lhs,op,rhs} = s + case p_p_op: {lhs,rhs,op} = s + default: ?9/0 + end switch + if sequence(lhs) then lhs = evaluate(lhs) end if + if sequence(rhs) then rhs = evaluate(rhs) end if + if op="+" then return lhs+rhs + elsif op="-" then return lhs-rhs + elsif op="*" then return lhs*rhs + elsif op="/" then return lhs/rhs + elsif op="^" then return power(lhs,rhs) + elsif op="%" then return rmdr(lhs,rhs) + elsif op="u-" then return -rhs + else ?9/0 + end if +end function - function evaluate(object s) - object lhs, rhs - string op - if atom(s) then - return s - end if - if op_p_p=1 then -- op_p_p - {op,lhs,rhs} = s - elsif op_p_p=0 then -- p_op_p - {lhs,op,rhs} = s - else -- -1 -- p_p_op - {lhs,rhs,op} = s - end if - if sequence(lhs) then lhs = evaluate(lhs) end if - if sequence(rhs) then rhs = evaluate(rhs) end if - if op="+" then - return lhs+rhs - elsif op="-" then - return lhs-rhs - elsif op="*" then - return lhs*rhs - elsif op="/" then - return lhs/rhs - elsif op="^" then - return power(lhs,rhs) - elsif op="%" then - return remainder(lhs,rhs) - elsif op="u-" then - return -rhs - else - ?9/0 - end if - end function - - s = "3+4+5+6*7/1*5^2^3" -- 16406262 - sidx = 0 - nxtch() - get_token() - Expr(0) - if op!=0 then PopFactor() end if - if length(opstack)!=1 then err("some error") end if - printf(1,"expression: \"%s\"\n",{s}) - puts(1,"AST (flat): ") - ?opstack[1] - puts(1,"AST (tree):\n") - ppEx(opstack[1],{pp_Nest,9999}) - puts(1,"result: ") - ?evaluate(opstack[1]) - {} = wait_key() -(quotient,remainder) - if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt())); - return(self.fcn(n,k+1+k.isOdd,acc,maxD)) + q,r:=n.divr(k); // divr-->(quotient,remainder) + if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt())); + return(self.fcn(n,k+1+k.isOdd,acc,maxD)) } }(n,2,Sink(List),n.toFloat().sqrt()); m:=acc.reduce('*,1); // mulitply factors diff --git a/Task/Average-loop-length/Ada/average-loop-length.adb b/Task/Average-loop-length/Ada/average-loop-length.adb new file mode 100644 index 0000000000..09e9455936 --- /dev/null +++ b/Task/Average-loop-length/Ada/average-loop-length.adb @@ -0,0 +1,53 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Generic_Elementary_Functions; +with Ada.Numerics.Discrete_Random; +procedure Avglen is + package IIO is new Ada.Text_IO.Integer_IO (Positive); use IIO; + package LFIO is new Ada.Text_IO.Float_IO (Long_Float); use LFIO; + subtype FactN is Natural range 0..20; + TESTS : constant Natural := 1_000_000; + + function Factorial (N : FactN) return Long_Float is + Result : Long_Float := 1.0; + begin + for I in 2..N loop Result := Result * Long_Float(I); end loop; + return Result; + end Factorial; + + function Analytical (N : FactN) return Long_Float is + Sum : Long_Float := 0.0; + begin + for I in 1..N loop + Sum := Sum + Factorial(N) / Factorial(N - I) / Long_Float(N)**I; + end loop; + return Sum; + end Analytical; + + function Experimental (N : FactN) return Long_Float is + subtype RandInt is Natural range 1..N; + package Random is new Ada.Numerics.Discrete_Random(RandInt); + seed : Random.Generator; + Num : RandInt; + count : Natural := 0; + bits : array(RandInt'Range) of Boolean; + begin + Random.Reset(seed); + for run in 1..TESTS loop + bits := (others => false); + for I in RandInt'Range loop + Num := Random.Random(seed); exit when bits(Num); + bits(Num) := True; count := count + 1; + end loop; + end loop; + return Long_Float(count)/Long_Float(TESTS); + end Experimental; + + A, E, err : Long_Float; +begin + Put_Line(" N avg calc %diff"); + for I in 1..20 loop + A := Analytical(I); E := Experimental(I); err := abs(E-A)/A*100.0; + Put(I, Width=>2); Put(E ,Aft=>4, exp=>0); Put(A, Aft=>4, exp=>0); + Put(err, Fore=>3, Aft=>3, exp=>0); New_line; + end loop; +end Avglen; diff --git a/Task/Average-loop-length/Crystal/average-loop-length.cr b/Task/Average-loop-length/Crystal/average-loop-length.cr new file mode 100644 index 0000000000..713284e441 --- /dev/null +++ b/Task/Average-loop-length/Crystal/average-loop-length.cr @@ -0,0 +1,26 @@ +struct Int + def factorial + raise "only positive" if self < 0 + (1_i64..self.to_i64).product + end +end + +def rand_until_rep (n) + rands = {} of Int32 => Bool + loop do + r = rand(1..n) + return rands.size if rands[r]? + rands[r] = true + end +end + +runs = 1_000_000 + +puts " N average exp. diff ", + "=== ======== ======== ===========" +(1..20).each do |n| + sum_of_runs = runs.times.sum(0_i64) { rand_until_rep(n) } + avg = sum_of_runs / runs + analytical = (1..n).sum(0.0) {|i| (n.factorial / (n.to_f**i) / (n-i).factorial) } + puts "%3d %8.4f %8.4f (%8.4f%%)" % {n, avg, analytical, (avg/analytical - 1)*100} +end diff --git a/Task/Average-loop-length/EasyLang/average-loop-length.easy b/Task/Average-loop-length/EasyLang/average-loop-length.easy index f12cc4ee3c..d036ff7912 100644 --- a/Task/Average-loop-length/EasyLang/average-loop-length.easy +++ b/Task/Average-loop-length/EasyLang/average-loop-length.easy @@ -3,7 +3,7 @@ fastfunc average n reps . len seen[] n for r to reps for i = 1 to n - f[i] = random n + f[i] = random 1 n seen[i] = 0 . x = 1 diff --git a/Task/Average-loop-length/Pluto/average-loop-length.pluto b/Task/Average-loop-length/Pluto/average-loop-length.pluto new file mode 100644 index 0000000000..48b0c75253 --- /dev/null +++ b/Task/Average-loop-length/Pluto/average-loop-length.pluto @@ -0,0 +1,39 @@ +require "table2" +local fmt = require "fmt" + +local nmax = 20 + +local function avg(n) + local tests = 1e4 + local sum = 0 + for _ = 1, tests do + local v = table.rep(nmax, false) + local x = 1 + while !v[x] do + v[x] = true + sum += 1 + x = math.random(1, n) + end + end + return sum / tests +end + +local function ana(n) + if n < 2 then return 1 end + local term = 1 + local sum = 1 + for i = n, 2, -1 do + term *= (i - 1) / n + sum += term + end + return sum +end + +print(" N average analytical (error)") +print("=== ========= ============ =========") +for n = 1, nmax do + local a = avg(n) + local b = ana(n) + local e = math.abs(a - b) / b * 100 + fmt.print("%3d %9.4f %12.4f (%6.2f%%)", n, a, b, e) +end diff --git a/Task/Average-loop-length/PowerShell/average-loop-length-1.ps1 b/Task/Average-loop-length/PowerShell/average-loop-length-1.ps1 new file mode 100644 index 0000000000..20b6979f45 --- /dev/null +++ b/Task/Average-loop-length/PowerShell/average-loop-length-1.ps1 @@ -0,0 +1,59 @@ +function Get-AnalyticalLoopAverage ( [int]$N ) + { + # Expected loop average = sum from i = 1 to N of N! / (N-i)! / N^(N-i+1) + # Equivalently, Expected loop average = sum from i = 1 to N of F(i) + # where F(N) = 1, and F(i) = F(i+1)*i/N + + $LoopAverage = $Fi = 1 + + If ( $N -eq 1 ) { return $LoopAverage } + + ForEach ( $i in ($N-1)..1 ) + { + $Fi *= $i / $N + $LoopAverage += $Fi + } + return $LoopAverage + } + +function Get-ExperimentalLoopAverage ( [int]$N, [int]$Tests = 100000 ) + { + If ( $N -eq 1 ) { return 1 } + + # Using 0 through N-1 instead of 1 through N for speed and simplicity + $NMO = $N - 1 + + # Create array to hold mapping function + $F = New-Object int[] ( $N ) + + $Count = 0 + $Random = New-Object System.Random + + ForEach ( $Test in 1..$Tests ) + { + # Map each number to a random number + ForEach ( $i in 0..$NMO ) + { + $F[$i] = $Random.Next( $N ) + } + + # For each number... + ForEach ( $i in 0..$NMO ) + { + # Add the number to the list + $List = @() + $Count++ + $List += $X = $i + + # If loop does not yet exist in list... + While ( $F[$X] -notin $List ) + { + # Go to the next mapped number and add it to the list + $Count++ + $List += $X = $F[$X] + } + } + } + $LoopAvereage = $Count / $N / $Tests + return $LoopAvereage + } diff --git a/Task/Average-loop-length/PowerShell/average-loop-length-2.ps1 b/Task/Average-loop-length/PowerShell/average-loop-length-2.ps1 new file mode 100644 index 0000000000..3729fdebcd --- /dev/null +++ b/Task/Average-loop-length/PowerShell/average-loop-length-2.ps1 @@ -0,0 +1,12 @@ +# Display results for N = 1 through 20 +ForEach ( $N in 1..20 ) + { + $AnalyticalAverage = Get-AnalyticalLoopAverage $N + $ExperimentalAverage = Get-ExperimentalLoopAverage $N + [pscustomobject] @{ + N = $N.ToString().PadLeft( 2, ' ' ) + Analytical = $AnalyticalAverage.ToString( '0.00000000' ) + Experimental = $ExperimentalAverage.ToString( '0.00000000' ) + 'Error (%)' = ( [math]::Abs( $AnalyticalAverage - $ExperimentalAverage ) / $AnalyticalAverage * 100 ).ToString( '0.00000000' ) + } + } diff --git a/Task/Average-loop-length/VBScript/average-loop-length.vbs b/Task/Average-loop-length/VBScript/average-loop-length.vbs new file mode 100644 index 0000000000..e23bd4d744 --- /dev/null +++ b/Task/Average-loop-length/VBScript/average-loop-length.vbs @@ -0,0 +1,48 @@ +Const MAX = 20 +Const ITER = 100000 + +Function expected(n) + Dim sum + ni=n + For i = 1 To n + sum = sum + fact(n) / ni / fact(n-i) + ni=ni*n + Next + expected = sum +End Function + +Function test(n ) + Dim coun,x,bits + For i = 1 To ITER + x = 1 + bits = 0 + Do While Not bits And x + count = count + 1 + bits = bits Or x + x =shift(Int(n * Rnd())) + Loop + Next + test = count / ITER +End Function + +'VBScript formats numbers but does'nt align them! +function rf(v,n,s) rf=right(string(n,s)& v,n):end function + +'some precalculations to speed things up... +dim fact(20),shift(20) +fact(0)=1:shift(0)=1 +for i=1 to 20 + fact(i)=i*fact(i-1) + shift(i)=2*shift(i-1) +next + +Dim n +Wscript.echo "For " & ITER &" iterations" +Wscript.Echo " n avg. exp. (error%)" +Wscript.Echo "== ====== ====== ==========" +For n = 1 To MAX + av = test(n) + ex = expected(n) + Wscript.Echo rf(n,2," ")& " "& rf(formatnumber(av, 4),7," ") & " "& _ + rf(formatnumber(ex,4),6," ")& " ("& rf(Formatpercent(1 - av / ex,4),8," ") & ")" +Next diff --git a/Task/Averages-Arithmetic-mean/Ada/averages-arithmetic-mean.adb b/Task/Averages-Arithmetic-mean/Ada/averages-arithmetic-mean.adb new file mode 100644 index 0000000000..74ae542c0c --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Ada/averages-arithmetic-mean.adb @@ -0,0 +1,22 @@ +with Ada.Float_Text_Io; use Ada.Float_Text_Io; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Mean_Main is + type Vector is array (Positive range <>) of Float; + function Mean (Item : Vector) return float with pre => Item'length > 0; + function Mean (Item : Vector) return Float is + Sum : Float := 0.0; + begin + for I in Item'range loop + Sum := Sum + Item(I); + end loop; + return Sum / Float(Item'Length); + end Mean; + A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0); +begin + Put(Item => Mean (A), Fore => 1, Exp => 0); + New_Line; + -- test for zero length vector + Put(Item => Mean(A (1..0)), Fore => 1, Exp => 0); + New_Line; +end Mean_Main; diff --git a/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cob b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cob new file mode 100644 index 0000000000..43f1b8f9ff --- /dev/null +++ b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-1.cob @@ -0,0 +1 @@ +FUNCTION MEAN(some-table (ALL)) diff --git a/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cob b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cob new file mode 100644 index 0000000000..0afbedd5dd --- /dev/null +++ b/Task/Averages-Arithmetic-mean/COBOL/averages-arithmetic-mean-2.cob @@ -0,0 +1,28 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. find-mean. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 i PIC 9(4). + + 01 summ USAGE FLOAT-LONG. + + LINKAGE SECTION. + 01 nums-area. + 03 nums-len PIC 9(4). + 03 nums USAGE FLOAT-LONG + OCCURS 0 TO 1000 TIMES + DEPENDING ON nums-len. + + 01 result USAGE FLOAT-LONG. + + PROCEDURE DIVISION USING nums-area, result. + IF nums-len = 0 + MOVE 0 TO result + GOBACK + END-IF + + DIVIDE FUNCTION SUM(nums (ALL)) BY nums-len GIVING result + + GOBACK + . diff --git a/Task/Averages-Arithmetic-mean/Calc/averages-arithmetic-mean.calc b/Task/Averages-Arithmetic-mean/Calc/averages-arithmetic-mean.calc new file mode 100644 index 0000000000..ac2762584f --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Calc/averages-arithmetic-mean.calc @@ -0,0 +1 @@ +u M diff --git a/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy b/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy index 4e9bb83c20..3e05c7c28d 100644 --- a/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy +++ b/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy @@ -1,6 +1,5 @@ -func mean &f[] . - for i = 1 to len f[] : s += f[i] +func mean f[] . + for v in f[] : s += v return s / len f[] . -f[] = [ 1 2 3 4 5 6 7 8 ] -print mean f[] +print mean [ 1 2 3 4 5 6 7 8 ] diff --git a/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-1.el b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-1.el new file mode 100644 index 0000000000..10499d020b --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-1.el @@ -0,0 +1,3 @@ +(defun mean (lst) + (/ (float (apply '+ lst)) (length lst))) +(mean '(1 2 3 4)) diff --git a/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.el b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.el new file mode 100644 index 0000000000..05764b43ec --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.el @@ -0,0 +1,2 @@ +(let ((x '(1 2 3 4))) + (calc-eval "vmean($1)" nil (append '(vec) x))) diff --git a/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-3.el b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-3.el new file mode 100644 index 0000000000..9a674c11de --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-3.el @@ -0,0 +1,4 @@ +(let ((x '(1 2 3 4))) + (string-to-number + (math-format-value + (calcFunc-vmean (cons 'vec x))))) diff --git a/Task/Averages-Arithmetic-mean/Euphoria/averages-arithmetic-mean.eu b/Task/Averages-Arithmetic-mean/Euphoria/averages-arithmetic-mean.eu new file mode 100644 index 0000000000..80058ad511 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Euphoria/averages-arithmetic-mean.eu @@ -0,0 +1,16 @@ +function mean(sequence s) + atom sum + if length(s) = 0 then + return 0 + else + sum = 0 + for i = 1 to length(s) do + sum += s[i] + end for + return sum/length(s) + end if +end function + +sequence test +test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159} +? mean(test) diff --git a/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur b/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur index ad6e0ac086..9b9bdda03a 100644 --- a/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur +++ b/Task/Averages-Arithmetic-mean/Langur/averages-arithmetic-mean.langur @@ -1,4 +1,4 @@ -val umean = fn x:fold(x, by=fn{+}) / len(x) +val umean = fn(x list) { fold(x, by=fn{+}) / len(x) } writeln " custom: ", umean([7, 3, 12]) writeln "built-in: ", mean([7, 3, 12]) diff --git a/Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-1.ps1 b/Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-1.ps1 new file mode 100644 index 0000000000..17594cda09 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-1.ps1 @@ -0,0 +1,11 @@ +function mean ($x) { + if ($x.Count -eq 0) { + return 0 + } else { + $sum = 0 + foreach ($i in $x) { + $sum += $i + } + return $sum / $x.Count + } +} diff --git a/Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-2.ps1 b/Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-2.ps1 new file mode 100644 index 0000000000..5e5b533ad3 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/PowerShell/averages-arithmetic-mean-2.ps1 @@ -0,0 +1,7 @@ +function mean ($x) { + if ($x.Count -eq 0) { + return 0 + } else { + return ($x | Measure-Object -Average).Average + } +} diff --git a/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx b/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx index efa4be3b69..dfddd0144b 100644 --- a/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx +++ b/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx @@ -1,27 +1,29 @@ -/*REXX program finds the averages/arithmetic mean of several lists (vectors) or CL input*/ -parse arg @.1; if @.1='' then do; #=6 /*vector from the C.L.?*/ - @.1 = 10 9 8 7 6 5 4 3 2 1 - @.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 - @.3 = '10 20 30 40 50 -100 4.7 -11e2' - @.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2' - @.5 = 'World War I & World War II' - @.6 = /* ◄─── a null value. */ - end - else #=1 /*number of CL vectors.*/ - do j=1 for # - say ' numbers = ' @.j - say ' average = ' avg(@.j) - say copies('═', 79) - end /*t*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -avg: procedure; parse arg x; #=words(x) /*#: number of items.*/ - if #==0 then return 'N/A: ───[null vector.]' /*No words? Return N/A*/ - $=0 - do k=1 for #; _=word(x,k) /*obtain a number. */ - if datatype(_,'N') then do; $=$+_; iterate; end /*if numeric, then add*/ - say left('',40) "***error*** non-numeric: " _; #=#-1 /*error; adjust number*/ - end /*k*/ +-- 21 Feb 2026 +include Setting - if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A*/ - return $ / # /*return the average. */ +say 'ARITHMETIC MEAN' +say version +say +call Task '1;2;3;4;5;6;7;8;9;10' +call Task '1;10;100;1000;100000' +call Task '1' +exit + +Task: +procedure +arg xx +say 'Arithmetic mean of' List2form(xx) '=' AmeanL(xx) +return + +AmeanL: +procedure +arg xx +rr=0; nn=0 +do while xx<>'' + parse var xx xw';'xx + rr+=xw; nn+=1 +end +return rr/nn + +-- AmeanL full version; List2form +include Math diff --git a/Task/Averages-Arithmetic-mean/ReScript/averages-arithmetic-mean.res b/Task/Averages-Arithmetic-mean/ReScript/averages-arithmetic-mean.res new file mode 100644 index 0000000000..adc2db3484 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/ReScript/averages-arithmetic-mean.res @@ -0,0 +1,7 @@ +let arr = [3, 8, 4, 1, 5, 12] + +let num = Js.Array.length(arr) +let tot = Js.Array.reduce(\"+", 0, arr) +let mean = float_of_int(tot) /. float_of_int(num) + +Js.log(Js.Float.toString(mean)) diff --git a/Task/Averages-Arithmetic-mean/Rebol/averages-arithmetic-mean-1.rebol b/Task/Averages-Arithmetic-mean/Rebol/averages-arithmetic-mean-1.rebol new file mode 100644 index 0000000000..ca58cf86ef --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Rebol/averages-arithmetic-mean-1.rebol @@ -0,0 +1,19 @@ +rebol [ + Title: "Arithmetic Mean (Average)" + URL: http://rosettacode.org/wiki/Average/Arithmetic_mean +] + +average: func [v /local sum][ + if empty? v [return 0] + + sum: 0 + forall v [sum: sum + v/1] + sum / length? v +] + +; Note precision loss as spread increased. + +print [mold x: [] "->" average x] +print [mold x: [3 1 4 1 5 9] "->" average x] +print [mold x: [1000 3 1 4 1 5 9 -1000] "->" average x] +print [mold x: [1e20 3 1 4 1 5 9 -1e20] "->" average x] diff --git a/Task/Averages-Arithmetic-mean/Rebol/averages-arithmetic-mean-2.rebol b/Task/Averages-Arithmetic-mean/Rebol/averages-arithmetic-mean-2.rebol new file mode 100644 index 0000000000..b6075652c4 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Rebol/averages-arithmetic-mean-2.rebol @@ -0,0 +1,4 @@ +probe vect: #(i8! [3 1 4 1 5 9]) +print ["mean:" vect/mean] +print "" +print query vect object! ;; to show all vector's info diff --git a/Task/Averages-Arithmetic-mean/Uiua/averages-arithmetic-mean.uiua b/Task/Averages-Arithmetic-mean/Uiua/averages-arithmetic-mean.uiua new file mode 100644 index 0000000000..8395a54436 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Uiua/averages-arithmetic-mean.uiua @@ -0,0 +1,2 @@ +Avg ← ÷⧻⟜/+ +Avg [1 2 3 4] diff --git a/Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vbs b/Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vbs new file mode 100644 index 0000000000..3201a0e9e1 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vbs @@ -0,0 +1,11 @@ +Function mean(arr) + size = UBound(arr) + 1 + mean = 0 + For i = 0 To UBound(arr) + mean = mean + arr(i) + Next + mean = mean/size +End Function + +'Example +WScript.Echo mean(Array(3,1,4,1,5,9)) diff --git a/Task/Averages-Mean-angle/Ada/averages-mean-angle.adb b/Task/Averages-Mean-angle/Ada/averages-mean-angle.adb new file mode 100644 index 0000000000..13b4bd91ed --- /dev/null +++ b/Task/Averages-Mean-angle/Ada/averages-mean-angle.adb @@ -0,0 +1,34 @@ +with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; + +procedure Mean_Angles is + + type X_Real is digits 4; -- or more digits for improved precision + subtype Real is X_Real range 0.0 .. 360.0; -- the range of interest + type Angles is array(Positive range <>) of Real; + + procedure Put(R: Real) is + package IO is new Ada.Text_IO.Float_IO(Real); + begin + IO.Put(R, Fore => 3, Aft => 2, Exp => 0); + end Put; + + function Mean_Angle(A: Angles) return Real is + Sin_Sum, Cos_Sum: X_Real := 0.0; -- X_Real since sums might exceed 360.0 + package Math is new Ada.Numerics.Generic_Elementary_Functions(Real); + use Math; + begin + for I in A'Range loop + Sin_Sum := Sin_Sum + Sin(A(I), Cycle => 360.0); + Cos_Sum := Cos_Sum + Cos(A(I), Cycle => 360.0); + end loop; + return Arctan(Sin_Sum / X_Real(A'Length), Cos_Sum / X_Real(A'Length), + Cycle => 360.0); + -- may raise Ada.Numerics.Argument_Error if inputs are + -- numerically instable, e.g., when Cos_Sum is 0.0 + end Mean_Angle; + +begin + Put(Mean_Angle((10.0, 20.0, 30.0))); Ada.Text_IO.New_Line; -- 20.00 + Put(Mean_Angle((10.0, 350.0))); Ada.Text_IO.New_Line; -- 0.00 + Put(Mean_Angle((90.0, 180.0, 270.0, 360.0))); -- Ada.Numerics.Argument_Error! +end Mean_Angles; diff --git a/Task/Averages-Mean-angle/Crystal/averages-mean-angle.cr b/Task/Averages-Mean-angle/Crystal/averages-mean-angle.cr new file mode 100644 index 0000000000..6ea8a0ca43 --- /dev/null +++ b/Task/Averages-Mean-angle/Crystal/averages-mean-angle.cr @@ -0,0 +1,17 @@ +require "complex" + +def deg_to_rad (d) + d * Math::PI / 180 +end + +def rad_to_deg (r) + r * 180 / Math::PI +end + +def mean_angle (angles) + rad_to_deg(angles.sum {|deg| deg_to_rad(deg).cis }.phase) +end + +[[350, 10], [90, 180, 270, 360], [10, 20, 30]].each do |angles| + puts "The mean angle of %s is: %.2f°." % [angles, mean_angle(angles)] +end diff --git a/Task/Averages-Mean-angle/Euphoria/averages-mean-angle.eu b/Task/Averages-Mean-angle/Euphoria/averages-mean-angle.eu new file mode 100644 index 0000000000..4cd862d7a7 --- /dev/null +++ b/Task/Averages-Mean-angle/Euphoria/averages-mean-angle.eu @@ -0,0 +1,26 @@ +include std/console.e +include std/mathcons.e + +sequence AngleList = {{350,10},{90,180,270,360},{10,20,30}} + +function atan2(atom y, atom x) + return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y) +end function + +function MeanAngle(sequence angles) + atom x = 0, y = 0 + integer l = length(angles) + + for i = 1 to length(angles) do + x += cos(angles[i] * PI / 180) + y += sin(angles[i] * PI / 180) + end for + + return atan2(y / l, x / l) * 180 / PI +end function + +for i = 1 to length(AngleList) do + printf(1,"Mean Angle for set %d: %3.5f\n",{i,MeanAngle(AngleList[i])}) +end for + +if getc(0) then end if diff --git a/Task/Averages-Mean-angle/Pluto/averages-mean-angle.pluto b/Task/Averages-Mean-angle/Pluto/averages-mean-angle.pluto new file mode 100644 index 0000000000..9e228705ef --- /dev/null +++ b/Task/Averages-Mean-angle/Pluto/averages-mean-angle.pluto @@ -0,0 +1,20 @@ +local fmt = require "fmt" + +local function mean_angle(angles) + local n = #angles + local sin_sum = 0 + local cos_sum = 0 + for angles as angle do + sin_sum += math.sin(angle * math.pi / 180.0) + cos_sum += math.cos(angle * math.pi / 180.0) + end + return math.atan(sin_sum / n, cos_sum / n) * 180.0 / math.pi +end + +local angles1 = {350, 10} +local angles2 = {90, 180, 270, 360} +local angles3 = {10, 20, 30} + +for i, angles in {angles1, angles2, angles3} do + fmt.print("Mean for angles %d is : %6.2f", i, mean_angle(angles)) +end diff --git a/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.ps1 b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.ps1 new file mode 100644 index 0000000000..85708d1e36 --- /dev/null +++ b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-1.ps1 @@ -0,0 +1,7 @@ +function Get-MeanAngle ([double[]]$Angles) +{ + $x = ($Angles | ForEach-Object {[Math]::Cos($_ * [Math]::PI / 180)} | Measure-Object -Average).Average + $y = ($Angles | ForEach-Object {[Math]::Sin($_ * [Math]::PI / 180)} | Measure-Object -Average).Average + + [Math]::Atan2($y, $x) * 180 / [Math]::PI +} diff --git a/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.ps1 b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.ps1 new file mode 100644 index 0000000000..10d8e76fc9 --- /dev/null +++ b/Task/Averages-Mean-angle/PowerShell/averages-mean-angle-2.ps1 @@ -0,0 +1 @@ +@(350, 10), @(90, 180, 270, 360), @(10, 20, 30) | ForEach-Object {Get-MeanAngle $_} diff --git a/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx b/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx index 02deb03dad..ad33aa359e 100644 --- a/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx +++ b/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx @@ -1,55 +1,39 @@ -/*REXX program computes the mean angle for a group of angles (expressed in degrees). */ -call pi /*define the value of pi to some accuracy.*/ -numeric digits length(pi) - 1; /*use PI width decimal digits of precision,*/ - showDig= 10 /*only display ten decimal digits. */ -#= 350 10 ; say show(#, meanAngleD(#)) /*display mean angle (in degrees), 1st case.*/ -#= 90 180 270 360 ; say show(#, meanAngleD(#)) /* " " " " " 2nd " */ -#= 10 20 30 ; say show(#, meanAngleD(#)) /* " " " " " 3rd " */ -exit /*stick a fork in it, we're all done with it*/ -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -.sinCos: arg z,_,i; x=x*x; do k=2 by 2 until p=z; p=z; _=-_*x/(k*(k+i)); z=z+_; end; return z -$fuzz: return min(arg(1), max(1, digits() - arg(2) ) ) -Acos: procedure; parse arg x; return pi() * .5 - Asin(x) -Atan: parse arg x; if abs(x)=1 then return pi()*.25 * sign(x); return Asin(x/sqrt(1 + x*x)) -d2d: return arg(1) // 360 -d2r: return r2r(d2d(arg(1)) / 180 * pi() ) -r2d: return d2d((r2r(arg(1)) / pi()) * 180) -r2r: return arg(1) // (pi() * 2) -pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862;return pi -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -Asin: procedure; parse arg x 1 z 1 o 1 p; a= abs(x); aa= a * a - if a>1 then call AsinErr x /*argument X is out of range.*/ - if a >= sqrt(2) * .5 then return sign(x) * acos( sqrt(1 - aa), '-ASIN') - do j=2 by 2 until p=z; p= z; o= o * aa * (j-1) / j; z= z +o / (j+1); end - return z /* [↑] compute until no noise*/ -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -Atan2: procedure; parse arg y,x; call pi; s= sign(y) - select - when x=0 then z= s * pi * .5 - when x<0 then if y=0 then z= pi; else z= s * (pi - abs( Atan(y/x) ) ) - otherwise z= s * Atan(y / x) - end /*select*/; return z -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure; parse arg x; x= r2r(x); numeric fuzz $fuzz(6, 3) - a= abs(x); if a=0 then return 1; if a=pi then return -1 - if a=pi*.5 | a= pi*1.5 then return 0; if a=pi/3 then return .5 - if a= pi*2/3 then return -.5; return .sinCos(1, 1, -1) -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -meanAngleD: procedure; parse arg x; numeric digits digits() + digits() % 4 - n= words(x); _sin= 0; _cos= 0 - do j=1 for n; != d2r( word(x, j)); _sin= _sin + sin(!); _cos= _cos + cos(!) - end /*j*/ - return r2d( Atan2( _sin/n, _cos/n) ) -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -show: parse arg a,mA; _= format(ma, , showDig, 0) / 1 - return left('angles='a, 30) "mean angle=" right(_, max(4, length(_) ) ) -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -sin: procedure; parse arg x; x= r2r(x); numeric fuzz $fuzz(5, 3) - if x=pi * .5 then return 1; if x==pi * 1.5 then return -1 - if abs(x)=pi | x=0 then return 0; return .sinCos(x, x, +1) -/*───────────────────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h= d+6 - numeric digits; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g= g * .5'e'_ % 2 - do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g= (g + x/g) * .5; end /*k*/ - return g +-- 21 Feb 2026 +include Setting + +say 'MEAN ANGLE' +say version +say +numeric digits 11 +say 'Meaningful...' +call Task '350;10' +call Task '10;20;30' +call Task '180' +say +say 'Mathematically undefined...' +call Task '90;180;270;360' +call Task '0;180' +call Task '45;225' +call Task '90;270' +call Task '135;305' +exit + +Task: +procedure expose Memo. +arg xx +say 'Mean angle of list {'xx'} =' DegL(CmeanL(RadL(xx)))/1 +return + +CmeanL: +-- Returns circular mean of a list +procedure expose Memo. +arg xx +ss=0; sc=0 +do while xx<>'' + parse var xx xw';'xx + ss+=Sin(xw); sc+=Cos(xw) +end +return Arctan2(sc,ss) + +-- CmeanL (full); DegL; RadL; Sin; Cos; Arctan2 +include Math diff --git a/Task/Averages-Mean-angle/Scheme/averages-mean-angle-1.scm b/Task/Averages-Mean-angle/Scheme/averages-mean-angle-1.scm new file mode 100644 index 0000000000..87cc164852 --- /dev/null +++ b/Task/Averages-Mean-angle/Scheme/averages-mean-angle-1.scm @@ -0,0 +1,23 @@ +(import (srfi 1 lists)) ;; use 'fold' from library + +(define (average l) + (/ (fold + 0 l) (length l))) + +(define pi 3.14159265358979323846264338327950288419716939937510582097) + +(define (radians a) + (* pi 1/180 a)) + +(define (degrees a) + (* 180 (/ 1 pi) a)) + +(define (mean-angle angles) + (let* ((angles (map radians angles)) + (cosines (map cos angles)) + (sines (map sin angles))) + (degrees (atan (average sines) (average cosines))))) + +(for-each (lambda (angles) + (display "The mean angle of ") (display angles) + (display " is ") (display (mean-angle angles)) (newline)) + '((350 10) (90 180 270 360) (10 20 30))) diff --git a/Task/Averages-Mean-angle/Scheme/averages-mean-angle-2.scm b/Task/Averages-Mean-angle/Scheme/averages-mean-angle-2.scm new file mode 100644 index 0000000000..4e39400575 --- /dev/null +++ b/Task/Averages-Mean-angle/Scheme/averages-mean-angle-2.scm @@ -0,0 +1,24 @@ +(define pi (* 4 (atan 1))) + +(define (->radians d) (* d (/ pi 180))) +(define (->degrees r) (* r (/ 180 pi))) + +(define (average-direction angles) + (->degrees + ;; find the angle of the sum in radians + (angle + (apply + (map (lambda (d) + ;; a complex number on the unit circle + (make-polar 1 (->radians d))) + angles))))) + +(for-each (lambda (l) + (for-each display + (list "The mean angle of " + l + " is " + (average-direction l) + #\newline))) + '((350 10) + (90 180 270 360) + (10 20 30))) diff --git a/Task/Averages-Mean-time-of-day/Ada/averages-mean-time-of-day.adb b/Task/Averages-Mean-time-of-day/Ada/averages-mean-time-of-day.adb new file mode 100644 index 0000000000..368e425a78 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Ada/averages-mean-time-of-day.adb @@ -0,0 +1,79 @@ +with Ada.Calendar.Formatting; +with Ada.Command_Line; +with Ada.Numerics.Elementary_Functions; +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Mean_Time_Of_Day is + + subtype Time is Ada.Calendar.Time; + subtype Time_Of_Day is Ada.Calendar.Day_Duration; + subtype Time_String is String (1 .. 8); -- "HH:MM:SS" + + type Time_List is array (Positive range <>) of Time_String; + + function Average_Time (List : Time_List) return Time_String is + + function To_Time (Time_Image : Time_String) return Time + is (Ada.Calendar.Formatting.Value ("2000-01-01 " & Time_Image)); + + function To_Time_Of_Day (TS : Time) return Time_Of_Day is + use Ada.Calendar.Formatting; + Hour_Part : constant Time_Of_Day := 60.0 * 60.0 * Hour (TS); + Min_Part : constant Time_Of_Day := 60.0 * Minute (TS); + Sec_Part : constant Time_Of_Day := Time_Of_Day (Second (TS)); + begin + return Hour_Part + Min_Part + Sec_Part; + end To_Time_Of_Day; + + function To_Time_Image (Angle : Time_Of_Day) return Time_String + is + use Ada.Calendar.Formatting; + TOD : constant Time := Time_Of + (Year => 2000, Month => 1, Day => 1, -- Not used + Seconds => Angle); + begin + return Ada.Strings.Fixed.Tail (Image (TOD), Time_String'Length); + end To_Time_Image; + + function Average_Time_Of_Day (List : Time_List) return Time_Of_Day is + use Ada.Numerics.Elementary_Functions; + Cycle : constant Float := Float (Time_Of_Day'Last); + X_Sum, Y_Sum : Float := 0.0; + Angle : Float; + begin + for Time_Stamp of List loop + Angle := Float (To_Time_Of_Day (To_Time (Time_Stamp))); + X_Sum := X_Sum + Cos (Angle, Cycle => Cycle); + Y_Sum := Y_Sum + Sin (Angle, Cycle => Cycle); + end loop; + Angle := Arctan (Y_Sum, X_Sum, Cycle => Cycle); + if Angle < 0.0 then + Angle := Angle + Cycle; + elsif Angle > Cycle then + Angle := Angle - Cycle; + end if; + return Time_Of_Day (Angle); + end Average_Time_Of_Day; + + begin + return To_Time_Image (Average_Time_Of_Day (List)); + end Average_Time; + + use Ada.Command_Line; + List : Time_List (1 .. Argument_Count); +begin + if Argument_Count = 0 then + raise Constraint_Error; + end if; + + for A in 1 .. Argument_Count loop + List (A) := Argument (A); + end loop; + Ada.Text_IO.Put_Line (Average_Time (List)); + +exception + when others => + Ada.Text_IO.Put_Line ("Usage: mean_time_of_day ..."); + Ada.Text_IO.Put_Line (" ... 'HH:MM:SS' format"); +end Mean_Time_Of_Day; diff --git a/Task/Averages-Mean-time-of-day/Crystal/averages-mean-time-of-day.cr b/Task/Averages-Mean-time-of-day/Crystal/averages-mean-time-of-day.cr new file mode 100644 index 0000000000..586ce7a1f4 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Crystal/averages-mean-time-of-day.cr @@ -0,0 +1,39 @@ +require "complex" + +def sec_to_rad (d) + (d - 43200) * Math::PI / 43200 +end + +def rad_to_sec (r) + r * 43200 / Math::PI + 43200 +end + +def time_to_sec (t) + if t =~ /^(\d\d):(\d\d):(\d\d)$/ + $1.to_i * 3600 + $2.to_i * 60 + $3.to_i + else + raise "invalid time format" + end +end + +def sec_to_time (s) + h, s = s.divmod(3600) + m, s = s.divmod(60) + "%02d:%02d:%02d" % {h, m, s.round.to_i} +end + +def rad_to_time (r) + sec_to_time(rad_to_sec(r)) +end + +def time_to_rad (t) + sec_to_rad(time_to_sec(t)) +end + +def mean_time (times) + rad_to_time(times.sum {|time| time_to_rad(time).cis }.phase) +end + +[["23:00:17", "23:40:20", "00:12:45", "00:17:19"]].each do |times| + puts "The mean time of (%s) is: %s." % [times.join(" "), mean_time(times)] + end diff --git a/Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.eu b/Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.eu new file mode 100644 index 0000000000..243f11d54f --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.eu @@ -0,0 +1,63 @@ +include std/console.e +include std/math.e +include std/mathcons.e +include std/sequence.e +include std/get.e + +function T2D(sequence TimeSeq) + return (360 * TimeSeq[1] / 24 + 360 * TimeSeq[2] / (24 * 60) + + 360 * TimeSeq[3] / (24 * 3600)) +end function + +function D2T(atom angle) + sequence TimeSeq = {0,0,0} + atom seconds = 24 * 60 * 60 * angle / 360 + + TimeSeq[3] = mod(seconds,60) + TimeSeq[2] = (mod(seconds,3600) - TimeSeq[3]) / 60 + TimeSeq[1] = seconds / 3600 + + return TimeSeq +end function + +function MeanAngle(sequence angles) + atom x = 0, y = 0 + integer l = length(angles) + + for i = 1 to length(angles) do + x += cos(angles[i] * PI / 180) + y += sin(angles[i] * PI / 180) + end for + + return atan2(y / l, x / l) * 180 / PI +end function + +sequence TimeEntry, TimeList = {}, TimeSeq + +puts(1,"Enter times. Enter with no input to end\n") +while 1 do + TimeEntry = prompt_string("") + if equal(TimeEntry,"") then -- no more entries + for i = 1 to length(TimeList) do + TimeList[i] = split(TimeList[i],":") -- split the times into sequences + for j = 1 to 3 do + TimeList[i][j] = defaulted_value(TimeList[i][j],0) -- convert to numerical values + end for + end for + exit + end if + TimeList = append(TimeList,TimeEntry) +end while + +sequence AngleList = repeat({},length(TimeList)) + +for i = 1 to length(AngleList) do + AngleList[i] = T2D(TimeList[i]) +end for + +sequence MeanTime = D2T(360+MeanAngle(AngleList)) + +printf(1,"\nMean Time: %d:%d:%d\n",MeanTime) + + +if getc(0) then end if diff --git a/Task/Averages-Mean-time-of-day/Pluto/averages-mean-time-of-day.pluto b/Task/Averages-Mean-time-of-day/Pluto/averages-mean-time-of-day.pluto new file mode 100644 index 0000000000..aa6e073aec --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Pluto/averages-mean-time-of-day.pluto @@ -0,0 +1,32 @@ +local function time_to_degs(time) + local t = time:split(":") + local h = tonumber(t[1]) * 3600 + local m = tonumber(t[2]) * 60 + local s = tonumber(t[3]) + return (h + m + s) / 240 +end + +local function degs_to_time(d) + while d < 0 do d += 360 end + local s = math.round(d * 240) + local h = s // 3600 + local m = s % 3600 + s = m % 60 + m //= 60 + return string.format("%2d:%2d:%2d", h, m, s) +end + +local function mean_angle(angles) + local n = #angles + local sin_sum = 0 + local cos_sum = 0 + for angles as angle do + sin_sum += math.sin(angle * math.pi / 180) + cos_sum += math.cos(angle * math.pi / 180) + end + return math.atan(sin_sum / n, cos_sum / n) * 180 / math.pi +end + +local times = {"23:00:17", "23:40:20", "00:12:45", "00:17:19"} +local angles = times:mapped(|t| -> time_to_degs(t)) +print($"Mean time of day is : {degs_to_time(mean_angle(angles))}") diff --git a/Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-1.ps1 b/Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-1.ps1 new file mode 100644 index 0000000000..778a83e523 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-1.ps1 @@ -0,0 +1,66 @@ +function Get-MeanTimeOfDay +{ + [CmdletBinding()] + [OutputType([timespan])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true)] + [ValidatePattern("(?:2[0-3]|[01]?[0-9])[:.][0-5]?[0-9][:.][0-5]?[0-9]")] + [string[]] + $Time + ) + + Begin + { + [double[]]$angles = @() + + function ConvertFrom-Time ([timespan]$Time) + { + [double]((360 * $Time.Hours / 24) + (360 * $Time.Minutes / (24 * 60)) + (360 * $Time.Seconds / (24 * 3600))) + } + + function ConvertTo-Time ([double]$Angle) + { + $t = New-TimeSpan -Hours ([int](24 * 60 * 60 * $Angle / 360) / 3600) ` + -Minutes (([int](24 * 60 * 60 * $Angle / 360) % 3600 - [int](24 * 60 * 60 * $Angle / 360) % 60) / 60) ` + -Seconds ([int]((24 * 60 * 60 * $Angle / 360) % 60)) + + if ($t.Days -gt 0) + { + return ($t - (New-TimeSpan -Hours 1)) + } + + $t + } + + function Get-MeanAngle ([double[]]$Angles) + { + [double]$x,$y = 0 + + for ($i = 0; $i -lt $Angles.Count; $i++) + { + $x += [Math]::Cos($Angles[$i] * [Math]::PI / 180) + $y += [Math]::Sin($Angles[$i] * [Math]::PI / 180) + } + + $result = [Math]::Atan2(($y / $Angles.Count), ($x / $Angles.Count)) * 180 / [Math]::PI + + if ($result -lt 0) + { + return ($result + 360) + } + + $result + } + } + Process + { + $angles += ConvertFrom-Time $_ + } + End + { + ConvertTo-Time (Get-MeanAngle $angles) + } +} diff --git a/Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-2.ps1 b/Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-2.ps1 new file mode 100644 index 0000000000..450ffa6166 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/PowerShell/averages-mean-time-of-day-2.ps1 @@ -0,0 +1,2 @@ +[timespan]$meanTimeOfDay = "23:00:17","23:40:20","00:12:45","00:17:19" | Get-MeanTimeOfDay +"Mean time is {0}" -f (Get-Date $meanTimeOfDay.ToString()).ToString("hh:mm:ss tt") diff --git a/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua b/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua index 291cc80510..314db64b4d 100644 --- a/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua +++ b/Task/Averages-Mean-time-of-day/Uiua/averages-mean-time-of-day.uiua @@ -16,9 +16,3 @@ Ts ← "23:00:17, 23:40:20, 00:12:45, 00:17:19" ⊜(PtoC ⊟1 ×RpS ParseTS)¬⦷", ".Ts # Get TSs as unit complex numbers. ⁅÷RpS⊡1°PtoC÷⊃(⧻|/+) # Average them and convert back to seconds. °ParseTS+×SpD<0. # Ensure its >0, format as TS. - - -{{out}} -

    -"23:47:43"
    -
    diff --git a/Task/Averages-Median/Ada/averages-median.adb b/Task/Averages-Median/Ada/averages-median.adb new file mode 100644 index 0000000000..8d85b80a30 --- /dev/null +++ b/Task/Averages-Median/Ada/averages-median.adb @@ -0,0 +1,31 @@ +with Ada.Text_IO, Ada.Float_Text_IO; + +procedure FindMedian is + + f: array(1..10) of float := ( 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 ); + min_idx: integer; + min_val, median_val, swap: float; + +begin + for i in f'range loop + min_idx := i; + min_val := f(i); + for j in i+1 .. f'last loop + if f(j) < min_val then + min_idx := j; + min_val := f(j); + end if; + end loop; + swap := f(i); f(i) := f(min_idx); f(min_idx) := swap; + end loop; + + if f'length mod 2 /= 0 then + median_val := f( f'length/2+1 ); + else + median_val := ( f(f'length/2) + f(f'length/2+1) ) / 2.0; + end if; + + Ada.Text_IO.Put( "Median value: " ); + Ada.Float_Text_IO.Put( median_val ); + Ada.Text_IO.New_line; +end FindMedian; diff --git a/Task/Averages-Median/COBOL/averages-median.cob b/Task/Averages-Median/COBOL/averages-median.cob new file mode 100644 index 0000000000..bac369fdfa --- /dev/null +++ b/Task/Averages-Median/COBOL/averages-median.cob @@ -0,0 +1 @@ +FUNCTION MEDIAN(some-table (ALL)) diff --git a/Task/Averages-Median/Euphoria/averages-median.eu b/Task/Averages-Median/Euphoria/averages-median.eu new file mode 100644 index 0000000000..79839c9c20 --- /dev/null +++ b/Task/Averages-Median/Euphoria/averages-median.eu @@ -0,0 +1,25 @@ +function median(sequence s) + atom min,k + -- Selection sort of half+1 + for i = 1 to length(s)/2+1 do + min = s[i] + k = 0 + for j = i+1 to length(s) do + if s[j] < min then + min = s[j] + k = j + end if + end for + if k then + s[k] = s[i] + s[i] = min + end if + end for + if remainder(length(s),2) = 0 then + return (s[$/2]+s[$/2+1])/2 + else + return s[$/2+1] + end if +end function + +? median({ 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 }) diff --git a/Task/Averages-Median/PowerShell/averages-median-1.ps1 b/Task/Averages-Median/PowerShell/averages-median-1.ps1 new file mode 100644 index 0000000000..10f1443537 --- /dev/null +++ b/Task/Averages-Median/PowerShell/averages-median-1.ps1 @@ -0,0 +1,69 @@ +function Measure-Data +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + Position=0)] + [double[]] + $Data + ) + + Begin + { + function Get-Mode ([double[]]$Data) + { + if ($Data.Count -gt ($Data | Select-Object -Unique).Count) + { + $groups = $Data | Group-Object | Sort-Object -Property Count -Descending + + return ($groups | Where-Object {[double]$_.Count -eq [double]$groups[0].Count}).Name | ForEach-Object {[double]$_} + } + else + { + return $null + } + } + + function Get-StandardDeviation ([double[]]$Data) + { + $variance = 0 + $average = $Data | Measure-Object -Average | Select-Object -Property Count, Average + + foreach ($number in $Data) + { + $variance += [Math]::Pow(($number - $average.Average),2) + } + + return [Math]::Sqrt($variance / ($average.Count-1)) + } + + function Get-Median ([double[]]$Data) + { + if ($Data.Count % 2) + { + return $Data[[Math]::Floor($Data.Count/2)] + } + else + { + return ($Data[$Data.Count/2], $Data[$Data.Count/2-1] | Measure-Object -Average).Average + } + } + } + Process + { + $Data = $Data | Sort-Object + + $Data | Measure-Object -Maximum -Minimum -Sum -Average | + Select-Object -Property Count, + Sum, + Minimum, + Maximum, + @{Name='Range'; Expression={$_.Maximum - $_.Minimum}}, + @{Name='Mean' ; Expression={$_.Average}} | + Add-Member -MemberType NoteProperty -Name Median -Value (Get-Median $Data) -PassThru | + Add-Member -MemberType NoteProperty -Name StandardDeviation -Value (Get-StandardDeviation $Data) -PassThru | + Add-Member -MemberType NoteProperty -Name Mode -Value (Get-Mode $Data) -PassThru + } +} diff --git a/Task/Averages-Median/PowerShell/averages-median-2.ps1 b/Task/Averages-Median/PowerShell/averages-median-2.ps1 new file mode 100644 index 0000000000..96c1411d1a --- /dev/null +++ b/Task/Averages-Median/PowerShell/averages-median-2.ps1 @@ -0,0 +1,2 @@ +$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3 +$statistics diff --git a/Task/Averages-Median/PowerShell/averages-median-3.ps1 b/Task/Averages-Median/PowerShell/averages-median-3.ps1 new file mode 100644 index 0000000000..2157fc0087 --- /dev/null +++ b/Task/Averages-Median/PowerShell/averages-median-3.ps1 @@ -0,0 +1 @@ +$statistics.Median diff --git a/Task/Averages-Median/ReScript/averages-median.res b/Task/Averages-Median/ReScript/averages-median.res new file mode 100644 index 0000000000..7d073928ea --- /dev/null +++ b/Task/Averages-Median/ReScript/averages-median.res @@ -0,0 +1,24 @@ +let median = (arr) => +{ + let float_compare = (a, b) => { + let diff = a -. b + if diff == 0.0 { 0 } else + if diff > 0.0 { 1 } else { -1 } + } + let _ = Js.Array2.sortInPlaceWith(arr, float_compare) + let count = Js.Array.length(arr) + // find the middle value, or the lowest middle value + let middleval = ((count - 1) / 2) + let median = + if (mod(count, 2) != 0) { // odd number, middle is the median + arr[middleval] + } else { // even number, calculate avg of 2 medians + let low = arr[middleval] + let high = arr[middleval+1] + ((low +. high) /. 2.0) + } + median +} + +Js.log(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2])) +Js.log(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2])) diff --git a/Task/Averages-Median/Rebol/averages-median-1.rebol b/Task/Averages-Median/Rebol/averages-median-1.rebol new file mode 100644 index 0000000000..3b059ddcdc --- /dev/null +++ b/Task/Averages-Median/Rebol/averages-median-1.rebol @@ -0,0 +1,15 @@ +median: func [ + "Returns the midpoint value in a series of numbers; half the values are above, half are below." + block [any-block!] + /local len mid +][ + if empty? block [return none] + block: sort copy block + len: length? block + mid: to integer! len / 2 + either odd? len [ + pick block add 1 mid + ][ + (block/:mid) + (pick block add 1 mid) / 2 + ] +] diff --git a/Task/Averages-Median/Rebol/averages-median-2.rebol b/Task/Averages-Median/Rebol/averages-median-2.rebol new file mode 100644 index 0000000000..e16f4890cd --- /dev/null +++ b/Task/Averages-Median/Rebol/averages-median-2.rebol @@ -0,0 +1,5 @@ +vect: #(i8! [3 1 4 1 5 9]) +vect/median +;== 3.5 +query vect 'median +;== 3.5 diff --git a/Task/Averages-Median/Uiua/averages-median.uiua b/Task/Averages-Median/Uiua/averages-median.uiua new file mode 100644 index 0000000000..b97c295022 --- /dev/null +++ b/Task/Averages-Median/Uiua/averages-median.uiua @@ -0,0 +1,4 @@ +Median ← ÷2/+⊏[∩(⌊÷2)⊸-₁]⊸⧻⍆ + +Median [4.1 5.6 7.2 1.7 9.3 4.4 3.2] +Median [4.1 7.2 1.7 9.3 4.4 3.2] diff --git a/Task/Averages-Mode/Ada/averages-mode-1.adb b/Task/Averages-Mode/Ada/averages-mode-1.adb new file mode 100644 index 0000000000..0757dcc331 --- /dev/null +++ b/Task/Averages-Mode/Ada/averages-mode-1.adb @@ -0,0 +1,8 @@ +generic + type Element_Type is private; + type Element_Array is array (Positive range <>) of Element_Type; +package Mode is + + function Get_Mode (Set : Element_Array) return Element_Array; + +end Mode; diff --git a/Task/Averages-Mode/Ada/averages-mode-2.adb b/Task/Averages-Mode/Ada/averages-mode-2.adb new file mode 100644 index 0000000000..08dee1b804 --- /dev/null +++ b/Task/Averages-Mode/Ada/averages-mode-2.adb @@ -0,0 +1,102 @@ +with Ada.Containers.Indefinite_Vectors; + +package body Mode is + + -- map Count to Elements + package Count_Vectors is new Ada.Containers.Indefinite_Vectors + (Element_Type => Element_Array, + Index_Type => Positive); + + procedure Add (To : in out Count_Vectors.Vector; Item : Element_Type) is + use type Count_Vectors.Cursor; + Position : Count_Vectors.Cursor := To.First; + Found : Boolean := False; + begin + while not Found and then Position /= Count_Vectors.No_Element loop + declare + Elements : Element_Array := Count_Vectors.Element (Position); + begin + for I in Elements'Range loop + if Elements (I) = Item then + Found := True; + end if; + end loop; + end; + if not Found then + Position := Count_Vectors.Next (Position); + end if; + end loop; + if Position /= Count_Vectors.No_Element then + -- element found, remove it and insert to next count + declare + New_Position : Count_Vectors.Cursor := + Count_Vectors.Next (Position); + begin + -- remove from old position + declare + Old_Elements : Element_Array := + Count_Vectors.Element (Position); + New_Elements : Element_Array (1 .. Old_Elements'Length - 1); + New_Index : Positive := New_Elements'First; + begin + for I in Old_Elements'Range loop + if Old_Elements (I) /= Item then + New_Elements (New_Index) := Old_Elements (I); + New_Index := New_Index + 1; + end if; + end loop; + To.Replace_Element (Position, New_Elements); + end; + -- new position not already there? + if New_Position = Count_Vectors.No_Element then + declare + New_Array : Element_Array (1 .. 1) := (1 => Item); + begin + To.Append (New_Array); + end; + else + -- add to new position + declare + Old_Elements : Element_Array := + Count_Vectors.Element (New_Position); + New_Elements : Element_Array (1 .. Old_Elements'Length + 1); + begin + New_Elements (1 .. Old_Elements'Length) := Old_Elements; + New_Elements (New_Elements'Last) := Item; + To.Replace_Element (New_Position, New_Elements); + end; + end if; + end; + else + -- element not found, add to count 1 + Position := To.First; + if Position = Count_Vectors.No_Element then + declare + New_Array : Element_Array (1 .. 1) := (1 => Item); + begin + To.Append (New_Array); + end; + else + declare + Old_Elements : Element_Array := + Count_Vectors.Element (Position); + New_Elements : Element_Array (1 .. Old_Elements'Length + 1); + begin + New_Elements (1 .. Old_Elements'Length) := Old_Elements; + New_Elements (New_Elements'Last) := Item; + To.Replace_Element (Position, New_Elements); + end; + end if; + end if; + end Add; + + function Get_Mode (Set : Element_Array) return Element_Array is + Counts : Count_Vectors.Vector; + begin + for I in Set'Range loop + Add (Counts, Set (I)); + end loop; + return Counts.Last_Element; + end Get_Mode; + +end Mode; diff --git a/Task/Averages-Mode/Ada/averages-mode-3.adb b/Task/Averages-Mode/Ada/averages-mode-3.adb new file mode 100644 index 0000000000..514d0078ec --- /dev/null +++ b/Task/Averages-Mode/Ada/averages-mode-3.adb @@ -0,0 +1,26 @@ +with Ada.Text_IO; +with Mode; +procedure Main is + type Int_Array is array (Positive range <>) of Integer; + package Int_Mode is new Mode (Integer, Int_Array); + + Test_1 : Int_Array := (1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6); + Result : Int_Array := Int_Mode.Get_Mode (Test_1); +begin + Ada.Text_IO.Put ("Input: "); + for I in Test_1'Range loop + Ada.Text_IO.Put (Integer'Image (Test_1 (I))); + if I /= Test_1'Last then + Ada.Text_IO.Put (","); + end if; + end loop; + Ada.Text_IO.New_Line; + Ada.Text_IO.Put ("Result:"); + for I in Result'Range loop + Ada.Text_IO.Put (Integer'Image (Result (I))); + if I /= Result'Last then + Ada.Text_IO.Put (","); + end if; + end loop; + Ada.Text_IO.New_Line; +end Main; diff --git a/Task/Averages-Mode/Euphoria/averages-mode.eu b/Task/Averages-Mode/Euphoria/averages-mode.eu new file mode 100644 index 0000000000..7b4cfce394 --- /dev/null +++ b/Task/Averages-Mode/Euphoria/averages-mode.eu @@ -0,0 +1,39 @@ +include misc.e + +function mode(sequence s) + sequence uniques, counts, modes + integer j,max + uniques = {} + counts = {} + for i = 1 to length(s) do + j = find(s[i], uniques) + if j then + counts[j] += 1 + else + uniques = append(uniques, s[i]) + counts = append(counts, 1) + end if + end for + + max = counts[1] + for i = 2 to length(counts) do + if counts[i] > max then + max = counts[i] + end if + end for + + j = 1 + modes = {} + while j <= length(s) do + j = find_from(max, counts, j) + if j = 0 then + exit + end if + modes = append(modes, uniques[j]) + j += 1 + end while + return modes +end function + +constant s = { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" } +pretty_print(1,mode(s),{3}) diff --git a/Task/Averages-Mode/Pluto/averages-mode.pluto b/Task/Averages-Mode/Pluto/averages-mode.pluto new file mode 100644 index 0000000000..bc911b3239 --- /dev/null +++ b/Task/Averages-Mode/Pluto/averages-mode.pluto @@ -0,0 +1,23 @@ +local fmt = require "fmt" + +local function mode(a) + local t = a:countvalues() + local max = t:values():max() + local res = {} + for k, v in t do + if v == max then res:insert(k) end + end + return res +end + +local tests = { + {1, 2, 5, -5, -9.5, 3.14159}, + { 1, "blue", 2, 7.5, 5, "green", "red", 5, 2, "blue", "white" }, + {1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6}, + {.2, .7, .1, .8, .2}, + {"two", 7, 1, 8, "two", 8}, + "Hello there world":split(""), + {} +} + +for tests as test do fmt.lprint(mode(test)) end diff --git a/Task/Averages-Mode/PowerShell/averages-mode.ps1 b/Task/Averages-Mode/PowerShell/averages-mode.ps1 new file mode 100644 index 0000000000..a390910fd6 --- /dev/null +++ b/Task/Averages-Mode/PowerShell/averages-mode.ps1 @@ -0,0 +1,3 @@ +$data = @(1,1,1,2,3,4,5,5,6,7,7,7) +$groups = $data | group-object | sort-object count -Descending +$groups | ? {$_.Count -eq $groups[0].Count} diff --git a/Task/Averages-Mode/Uiua/averages-mode.uiua b/Task/Averages-Mode/Uiua/averages-mode.uiua new file mode 100644 index 0000000000..34819b895d --- /dev/null +++ b/Task/Averages-Mode/Uiua/averages-mode.uiua @@ -0,0 +1,3 @@ +Modes ← ▽=⊸/↥⊕⊃⧻⊢⊸⊛ +Modes [1 3 6 6 6 6 7 7 12 12 17] +Modes [1 1 2 4 4] diff --git a/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-1.adb b/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-1.adb new file mode 100644 index 0000000000..37d9a64ce3 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-1.adb @@ -0,0 +1,6 @@ +package Pythagorean_Means is + type Set is array (Positive range <>) of Float; + function Arithmetic_Mean (Data : Set) return Float; + function Geometric_Mean (Data : Set) return Float; + function Harmonic_Mean (Data : Set) return Float; +end Pythagorean_Means; diff --git a/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-2.adb b/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-2.adb new file mode 100644 index 0000000000..c7aa66b7ac --- /dev/null +++ b/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-2.adb @@ -0,0 +1,33 @@ +with Ada.Numerics.Generic_Elementary_Functions; +package body Pythagorean_Means is + package Math is new Ada.Numerics.Generic_Elementary_Functions (Float); + function "**" (Left, Right : Float) return Float renames Math."**"; + + function Arithmetic_Mean (Data : Set) return Float is + Sum : Float := 0.0; + begin + for I in Data'Range loop + Sum := Sum + Data (I); + end loop; + return Sum / Float (Data'Length); + end Arithmetic_Mean; + + function Geometric_Mean (Data : Set) return Float is + Product : Float := 1.0; + begin + for I in Data'Range loop + Product := Product * Data (I); + end loop; + return Product**(1.0/Float(Data'Length)); + end Geometric_Mean; + + function Harmonic_Mean (Data : Set) return Float is + Reciprocal_Sum : Float := 0.0; + begin + for I in Data'Range loop + Reciprocal_Sum := Reciprocal_Sum + Data (I)**(-1); + end loop; + return Float (Data'Length) / Reciprocal_Sum; + end Harmonic_Mean; + +end Pythagorean_Means; diff --git a/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-3.adb b/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-3.adb new file mode 100644 index 0000000000..4b4710e5b2 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Ada/averages-pythagorean-means-3.adb @@ -0,0 +1,13 @@ +with Ada.Text_IO; +with Pythagorean_Means; +procedure Main is + My_Set : Pythagorean_Means.Set := (1.0, 2.0, 3.0, 4.0, 5.0, + 6.0, 7.0, 8.0, 9.0, 10.0); + Arithmetic_Mean : Float := Pythagorean_Means.Arithmetic_Mean (My_Set); + Geometric_Mean : Float := Pythagorean_Means.Geometric_Mean (My_Set); + Harmonic_Mean : Float := Pythagorean_Means.Harmonic_Mean (My_Set); +begin + Ada.Text_IO.Put_Line (Float'Image (Arithmetic_Mean) & " >= " & + Float'Image (Geometric_Mean) & " >= " & + Float'Image (Harmonic_Mean)); +end Main; diff --git a/Task/Averages-Pythagorean-means/Euphoria/averages-pythagorean-means.eu b/Task/Averages-Pythagorean-means/Euphoria/averages-pythagorean-means.eu new file mode 100644 index 0000000000..f4d6e0d812 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Euphoria/averages-pythagorean-means.eu @@ -0,0 +1,52 @@ +function arithmetic_mean(sequence s) + atom sum + if length(s) = 0 then + return 0 + else + sum = 0 + for i = 1 to length(s) do + sum += s[i] + end for + return sum/length(s) + end if +end function + +function geometric_mean(sequence s) + atom p + p = 1 + for i = 1 to length(s) do + p *= s[i] + end for + return power(p,1/length(s)) +end function + +function harmonic_mean(sequence s) + atom sum + if length(s) = 0 then + return 0 + else + sum = 0 + for i = 1 to length(s) do + sum += 1/s[i] + end for + return length(s) / sum + end if +end function + +function true_or_false(atom x) + if x then + return "true" + else + return "false" + end if +end function + +constant s = {1,2,3,4,5,6,7,8,9,10} +constant arithmetic = arithmetic_mean(s), + geometric = geometric_mean(s), + harmonic = harmonic_mean(s) +printf(1,"Arithmetic: %g\n", arithmetic) +printf(1,"Geometric: %g\n", geometric) +printf(1,"Harmonic: %g\n", harmonic) +printf(1,"Arithmetic>=Geometric>=Harmonic: %s\n", + {true_or_false(arithmetic>=geometric and geometric>=harmonic)}) diff --git a/Task/Averages-Pythagorean-means/PowerShell/averages-pythagorean-means.ps1 b/Task/Averages-Pythagorean-means/PowerShell/averages-pythagorean-means.ps1 new file mode 100644 index 0000000000..bce581d667 --- /dev/null +++ b/Task/Averages-Pythagorean-means/PowerShell/averages-pythagorean-means.ps1 @@ -0,0 +1,23 @@ +$A = 0 +$LogG = 0 +$InvH = 0 + +$ii = 1..10 +foreach($i in $ii) { + # Arithmetic mean is computed directly + $A += $i / $ii.Count + # Geometric mean is computed using Logarithms + $LogG += [Math]::Log($i) / $ii.Count + # Harmonic mean is computed using its inverse + $InvH += 1 / ($i * $ii.Count) +} + +$G = [Math]::Exp($LogG) +$H = 1/$InvH + +write-host "Arithmetic mean: A = $A" +write-host "Geometric mean: G = $G" +write-host "Harmonic mean: H = $H" + +write-host "Is A >= G ? $($A -ge $G)" +write-host "Is G >= H ? $($G -ge $H)" diff --git a/Task/Averages-Pythagorean-means/SuperCollider/averages-pythagorean-means.sc b/Task/Averages-Pythagorean-means/SuperCollider/averages-pythagorean-means.sc new file mode 100644 index 0000000000..e7e5567596 --- /dev/null +++ b/Task/Averages-Pythagorean-means/SuperCollider/averages-pythagorean-means.sc @@ -0,0 +1,32 @@ +( +// Usage: ~arithmetic_mean.(x), where x is an array +// of numbers. +// +// Return the artithmetic mean of the values in x. +~arithmetic_mean = { + arg x; (x.sum)/(x.size) +}; + +// Usage: ~geometric_mean.(x), where x is an array +// of positive or null numbers. +// +// Return the geometric mean of the values in x. +~geometric_mean = { + arg x; (x.product)**(1/(x.size)) +}; + +// Usage: ~harmonic_mean.(x), where x is an array +// of non-null numbers. +// +// Return the harmonic mean of the values in x. +~harmonic_mean = { + arg x; (x.size)/((1/x).sum) +}; + +~x = Array.fill(10, {|i| i + 1}); +"Array: ".post; ~x.postln; +"----------------------------------".postln; +"Arithmetic mean:\t".post; ~arithmetic_mean.(~x).postln; +"Geometric mean:\t".post; ~geometric_mean.(~x).postln; +"Harmonic mean:\t".post; ~harmonic_mean.(~x).postln; +) diff --git a/Task/Averages-Pythagorean-means/Uiua/averages-pythagorean-means.uiua b/Task/Averages-Pythagorean-means/Uiua/averages-pythagorean-means.uiua new file mode 100644 index 0000000000..009e2498eb --- /dev/null +++ b/Task/Averages-Pythagorean-means/Uiua/averages-pythagorean-means.uiua @@ -0,0 +1,4 @@ +A ← ÷⊃⧻/+ +G ← ⁿ⊃(˜÷1⧻)/× +H ← ÷⊃(/+˜÷1)⧻ +⊃(A|G|H)+1⇡10 diff --git a/Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vbs b/Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vbs new file mode 100644 index 0000000000..e087a2174d --- /dev/null +++ b/Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vbs @@ -0,0 +1,27 @@ +Function arithmetic_mean(arr) + sum = 0 + For i = 0 To UBound(arr) + sum = sum + arr(i) + Next + arithmetic_mean = sum / (UBound(arr)+1) +End Function + +Function geometric_mean(arr) + product = 1 + For i = 0 To UBound(arr) + product = product * arr(i) + Next + geometric_mean = product ^ (1/(UBound(arr)+1)) +End Function + +Function harmonic_mean(arr) + sum = 0 + For i = 0 To UBound(arr) + sum = sum + (1/arr(i)) + Next + harmonic_mean = (UBound(arr)+1) / sum +End Function + +WScript.StdOut.WriteLine arithmetic_mean(Array(1,2,3,4,5,6,7,8,9,10)) +WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10)) +WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10)) diff --git a/Task/Averages-Root-mean-square/Ada/averages-root-mean-square.adb b/Task/Averages-Root-mean-square/Ada/averages-root-mean-square.adb new file mode 100644 index 0000000000..bc446862ed --- /dev/null +++ b/Task/Averages-Root-mean-square/Ada/averages-root-mean-square.adb @@ -0,0 +1,20 @@ +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Numerics.Elementary_Functions; +use Ada.Numerics.Elementary_Functions; +procedure calcrms is + type float_arr is array(1..10) of Float; + + function rms(nums : float_arr) return Float is + sum : Float := 0.0; + begin + for p in nums'Range loop + sum := sum + nums(p)**2; + end loop; + return sqrt(sum/Float(nums'Length)); + end rms; + + list : float_arr; +begin +list := (1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0); +put( rms(list) , Exp=>0); +end calcrms; diff --git a/Task/Averages-Root-mean-square/COBOL/averages-root-mean-square.cob b/Task/Averages-Root-mean-square/COBOL/averages-root-mean-square.cob new file mode 100644 index 0000000000..95698c0314 --- /dev/null +++ b/Task/Averages-Root-mean-square/COBOL/averages-root-mean-square.cob @@ -0,0 +1,21 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. QUADRATIC-MEAN-PROGRAM. +DATA DIVISION. +WORKING-STORAGE SECTION. +01 QUADRATIC-MEAN-VARS. + 05 N PIC 99 VALUE 0. + 05 N-SQUARED PIC 999. + 05 RUNNING-TOTAL PIC 999 VALUE 0. + 05 MEAN-OF-SQUARES PIC 99V9(16). + 05 QUADRATIC-MEAN PIC 9V9(15). +PROCEDURE DIVISION. +CONTROL-PARAGRAPH. + PERFORM MULTIPLICATION-PARAGRAPH 10 TIMES. + DIVIDE RUNNING-TOTAL BY 10 GIVING MEAN-OF-SQUARES. + COMPUTE QUADRATIC-MEAN = FUNCTION SQRT(MEAN-OF-SQUARES). + DISPLAY QUADRATIC-MEAN UPON CONSOLE. + STOP RUN. +MULTIPLICATION-PARAGRAPH. + ADD 1 TO N. + MULTIPLY N BY N GIVING N-SQUARED. + ADD N-SQUARED TO RUNNING-TOTAL. diff --git a/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square.el b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square.el new file mode 100644 index 0000000000..c5dd34968a --- /dev/null +++ b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square.el @@ -0,0 +1,5 @@ +(defun rms (nums) + (sqrt (/ (apply '+ (mapcar (lambda (x) (* x x)) nums)) + (float (length nums))))) + +(rms (number-sequence 1 10)) diff --git a/Task/Averages-Root-mean-square/Euphoria/averages-root-mean-square.eu b/Task/Averages-Root-mean-square/Euphoria/averages-root-mean-square.eu new file mode 100644 index 0000000000..7ad2ff66b8 --- /dev/null +++ b/Task/Averages-Root-mean-square/Euphoria/averages-root-mean-square.eu @@ -0,0 +1,14 @@ +function rms(sequence s) + atom sum + if length(s) = 0 then + return 0 + end if + sum = 0 + for i = 1 to length(s) do + sum += power(s[i],2) + end for + return sqrt(sum/length(s)) +end function + +constant s = {1,2,3,4,5,6,7,8,9,10} +? rms(s) diff --git a/Task/Averages-Root-mean-square/Frink/averages-root-mean-square.frink b/Task/Averages-Root-mean-square/Frink/averages-root-mean-square.frink new file mode 100644 index 0000000000..c2668d12c4 --- /dev/null +++ b/Task/Averages-Root-mean-square/Frink/averages-root-mean-square.frink @@ -0,0 +1,3 @@ +rms[array] := sqrt[sum[map[{|x| x^2}, array]] / length[array]] + +println[rms[array[1 to 10]]] diff --git a/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kts b/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kts index 7faec39916..b31b1ec432 100644 --- a/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kts +++ b/Task/Averages-Root-mean-square/Kotlin/averages-root-mean-square.kts @@ -1,7 +1,7 @@ // version 1.0.5-2 fun quadraticMean(vector: Array) : Double { - val sum = vector.sumByDouble { it * it } + val sum = vector.sumOf { it * it } return Math.sqrt(sum / vector.size) } diff --git a/Task/Averages-Root-mean-square/Lua/averages-root-mean-square.lua b/Task/Averages-Root-mean-square/Lua/averages-root-mean-square.lua index 6343c2ab2a..eda8ca8215 100644 --- a/Task/Averages-Root-mean-square/Lua/averages-root-mean-square.lua +++ b/Task/Averages-Root-mean-square/Lua/averages-root-mean-square.lua @@ -1,4 +1,4 @@ function sumsq(a, ...) return a and a^2 + sumsq(...) or 0 end -function rms(t) return (sumsq(unpack(t)) / #t)^.5 end +function rms(t) return (sumsq(table.unpack(t)) / #t)^.5 end print(rms{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) diff --git a/Task/Averages-Root-mean-square/PowerShell/averages-root-mean-square.ps1 b/Task/Averages-Root-mean-square/PowerShell/averages-root-mean-square.ps1 new file mode 100644 index 0000000000..b6fa95fcad --- /dev/null +++ b/Task/Averages-Root-mean-square/PowerShell/averages-root-mean-square.ps1 @@ -0,0 +1,6 @@ +function get-rms([float[]]$nums){ + $sqsum=$nums | foreach-object { $_*$_} | measure-object -sum | select-object -expand Sum + return [math]::sqrt($sqsum/$nums.count) +} + +get-rms @(1..10) diff --git a/Task/Averages-Root-mean-square/Uiua/averages-root-mean-square.uiua b/Task/Averages-Root-mean-square/Uiua/averages-root-mean-square.uiua new file mode 100644 index 0000000000..80aa03dbf7 --- /dev/null +++ b/Task/Averages-Root-mean-square/Uiua/averages-root-mean-square.uiua @@ -0,0 +1,3 @@ +RMS ← √÷⊃⧻/+≡ⁿ2 + +RMS +1⇡10 diff --git a/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-1.adb b/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-1.adb new file mode 100644 index 0000000000..bb3ea3665a --- /dev/null +++ b/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-1.adb @@ -0,0 +1,8 @@ +generic + Max_Elements : Positive; + type Number is digits <>; +package Moving is + procedure Add_Number (N : Number); + function Moving_Average (N : Number) return Number; + function Get_Average return Number; +end Moving; diff --git a/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-2.adb b/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-2.adb new file mode 100644 index 0000000000..288f762396 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-2.adb @@ -0,0 +1,40 @@ +with Ada.Containers.Vectors; + +package body Moving is + use Ada.Containers; + + package Number_Vectors is new Ada.Containers.Vectors + (Element_Type => Number, + Index_Type => Natural); + + Current_List : Number_Vectors.Vector := Number_Vectors.Empty_Vector; + + procedure Add_Number (N : Number) is + begin + if Natural (Current_List.Length) >= Max_Elements then + Current_List.Delete_First; + end if; + Current_List.Append (N); + end Add_Number; + + function Get_Average return Number is + Average : Number := 0.0; + procedure Sum (Position : Number_Vectors.Cursor) is + begin + Average := Average + Number_Vectors.Element (Position); + end Sum; + begin + Current_List.Iterate (Sum'Access); + if Current_List.Length > 1 then + Average := Average / Number (Current_List.Length); + end if; + return Average; + end Get_Average; + + function Moving_Average (N : Number) return Number is + begin + Add_Number (N); + return Get_Average; + end Moving_Average; + +end Moving; diff --git a/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-3.adb b/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-3.adb new file mode 100644 index 0000000000..c0c087b378 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Ada/averages-simple-moving-average-3.adb @@ -0,0 +1,19 @@ +with Ada.Text_IO; +with Moving; +procedure Main is + package Three_Average is new Moving (Max_Elements => 3, Number => Float); + package Five_Average is new Moving (Max_Elements => 5, Number => Float); +begin + for I in 1 .. 5 loop + Ada.Text_IO.Put_Line ("Inserting" & Integer'Image (I) & + " into max-3: " & Float'Image (Three_Average.Moving_Average (Float (I)))); + Ada.Text_IO.Put_Line ("Inserting" & Integer'Image (I) & + " into max-5: " & Float'Image (Five_Average.Moving_Average (Float (I)))); + end loop; + for I in reverse 1 .. 5 loop + Ada.Text_IO.Put_Line ("Inserting" & Integer'Image (I) & + " into max-3: " & Float'Image (Three_Average.Moving_Average (Float (I)))); + Ada.Text_IO.Put_Line ("Inserting" & Integer'Image (I) & + " into max-5: " & Float'Image (Five_Average.Moving_Average (Float (I)))); + end loop; +end Main; diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.jl b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.jl deleted file mode 100644 index df8c164afe..0000000000 --- a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.jl +++ /dev/null @@ -1 +0,0 @@ -using Statistics diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.jl b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.jl deleted file mode 100644 index 691844d737..0000000000 --- a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.jl +++ /dev/null @@ -1,22 +0,0 @@ -function movingaverage(::Type{T} = Float64; lim::Integer = -1) where T<:Real - buffer = Vector{T}(0) - if lim == -1 - # unlimited buffer - return (y::T) -> begin - push!(buffer, y) - return mean(buffer) - end - else - # limited size buffer - return (y) -> begin - push!(buffer, y) - if length(buffer) > lim shift!(buffer) end - return mean(buffer) - end - end -end - -test = movingaverage() -@show test(1.0) # mean([1]) -@show test(2.0) # mean([1, 2]) -@show test(3.0) # mean([1, 2, 3]) diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.jl b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.jl new file mode 100644 index 0000000000..5ce4a23851 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.jl @@ -0,0 +1,29 @@ +using Statistics + +""" + Return a function that computes a moving average over a buffer of values. + + Optional Named Arguments: + - ` buffer = buffer::Vector{T}`: optional initial buffer of values of + type `T` (default empty Float64 array) + - `limit = limit::Integer`: optional maximum length of the buffer; + if -1 (default), the buffer is unlimited + + Returns: + - a function `(y::T) -> mean(buffer)` that, when called with a new value `y`, + appends it to the buffer (and removes the oldest value if the buffer exceeds + `limit`), and returns the mean of the buffer +""" +function movingaverage(; buffer::Vector{T} = Float64[], limit::Integer = -1) where T <: Real + return (y::T) -> begin + push!(buffer, T(y)) + limit > 0 && length(buffer) > limit && popfirst!(buffer) + return mean(buffer) + end +end + + +test = movingaverage() +@show test(1.0) # mean([1]) +@show test(2.0) # mean([1, 2]) +@show test(3.0) # mean([1, 2, 3]) diff --git a/Task/Averages-Simple-moving-average/Lua/averages-simple-moving-average.lua b/Task/Averages-Simple-moving-average/Lua/averages-simple-moving-average.lua index a0ba7eb93f..6e4cadbb69 100644 --- a/Task/Averages-Simple-moving-average/Lua/averages-simple-moving-average.lua +++ b/Task/Averages-Simple-moving-average/Lua/averages-simple-moving-average.lua @@ -1,13 +1,13 @@ function sma(period) local t = {} - function sum(t) - sum = 0 + local function sum(t) + local tot = 0 for _, v in ipairs(t) do - sum = sum + v + tot = tot + v end - return sum + return tot end - function average(n) + local function average(n) if #t == period then table.remove(t, 1) end t[#t + 1] = n return sum(t) / #t diff --git a/Task/Averages-Simple-moving-average/Phix/averages-simple-moving-average.phix b/Task/Averages-Simple-moving-average/Phix/averages-simple-moving-average.phix new file mode 100644 index 0000000000..0a9fcc2785 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Phix/averages-simple-moving-average.phix @@ -0,0 +1,62 @@ +with javascript_semantics +-- (optional) put first part in sma.e for encapsulation/reuse +sequence sma = {} -- ((period,history,circnxt)) +integer sma_free = 0 + +global function new_sma(integer period) + integer res + if sma_free then + res = sma_free + sma_free = sma[sma_free] + sma[res] = {period,{},0} + else + sma = append(sma,{period,{},0}) + res = length(sma) + end if + return res +end function + +global procedure add_sma(integer sidx, atom val) + integer period, circnxt + sequence history + {period, history, circnxt} = sma[sidx] + sma[sidx][2] = 0 -- (kill refcount) + if length(history)period then + circnxt = 1 + end if + sma[sidx][3] = circnxt + history[circnxt] = val + end if + sma[sidx][2] = history +end procedure + +global function get_sma_average(integer sidx) + sequence history = sma[sidx][2] + integer l = length(history) + return iff(l=0?0:sum(history)/l) +end function + +global function moving_average(integer sidx, atom val) + add_sma(sidx,val) + return get_sma_average(sidx) +end function + +global procedure free_sma(integer sidx) + sma[sidx] = sma_free + sma_free = sidx +end procedure +-- +--include sma.e + +constant sma3 = new_sma(3) +constant sma5 = new_sma(5) +printf(1," x sma3 sma5\n") +for x in {1,2,3,4,5,5,4,3,2,1} do + atom a3 = moving_average(sma3,x), + a5 = moving_average(sma5,x) + printf(1,"%2g %=6.3g %=4.3g\n",{x,a3,a5}) +end for diff --git a/Task/Averages-Simple-moving-average/Pluto/averages-simple-moving-average.pluto b/Task/Averages-Simple-moving-average/Pluto/averages-simple-moving-average.pluto new file mode 100644 index 0000000000..b01d898d71 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Pluto/averages-simple-moving-average.pluto @@ -0,0 +1,24 @@ +local fmt = require "fmt" + +local function sma(period) + local i = 0 + local sum = 0 + local storage = {} + return function(input) + if #storage < period then + sum += input + storage:insert(input) + end + sum += input - storage[i + 1] + storage[i + 1] = input + i = (i + 1) % period + return sum / #storage + end +end + +local sma3 = sma(3) +local sma5 = sma(5) +print(" x sma3 sma5") +for {1, 2, 3, 4, 5, 5, 4, 3, 2, 1} as x do + fmt.print("%5.3f %5.3f %5.3f", x, sma3(x), sma5(x)) +end diff --git a/Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.ps1 b/Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.ps1 new file mode 100644 index 0000000000..c6036363e7 --- /dev/null +++ b/Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.ps1 @@ -0,0 +1,26 @@ +#This version allows a user to enter numbers one at a time to figure this into the SMA calculations + +$inputs = @() #Create an array to hold all inputs as they are entered. +$period1 = 3 #Define the periods you want to utilize +$period2 = 5 + +Write-host "Enter numbers to observe their moving averages." -ForegroundColor Green + +function getSMA ($inputs, [int]$period) #Function takes a array of entered values and a period (3 and 5 in this case) +{ + if($inputs.Count -lt $period){$period = $inputs.Count} #Makes sure that if there's less numbers than the designated period (3 in this case), the number of availble values is used as the period instead. + + for($count = 0; $count -lt $period; $count++) #Loop sums the latest available values + { + $result += $inputs[($inputs.Count) - $count - 1] + } + + return ($result | ForEach-Object -begin {$sum=0 }-process {$sum+=$_} -end {$sum/$period}) #Gets the average for a given period +} + +while($true) #Infinite loop so the user can keep entering numbers +{ + try{$inputs += [decimal] (Read-Host)}catch{Write-Host "Enter only numbers" -ForegroundColor Red} #Enter the numbers. Error checking to help mitigate bad inputs (non-number values) + + "Added " + $inputs[(($inputs.Count) - 1)] + ", sma($period1) = " + (getSMA $inputs $Period1) + ", sma($period2) = " + (getSMA $inputs $period2) +} diff --git a/Task/Averages-Simple-moving-average/VBScript/averages-simple-moving-average.vbs b/Task/Averages-Simple-moving-average/VBScript/averages-simple-moving-average.vbs new file mode 100644 index 0000000000..2fbb368d27 --- /dev/null +++ b/Task/Averages-Simple-moving-average/VBScript/averages-simple-moving-average.vbs @@ -0,0 +1,37 @@ +data = "1,2,3,4,5,5,4,3,2,1" +token = Split(data,",") +stream = "" +WScript.StdOut.WriteLine "Number" & vbTab & "SMA3" & vbTab & "SMA5" +For j = LBound(token) To UBound(token) + If Len(stream) = 0 Then + stream = token(j) + Else + stream = stream & "," & token(j) + End If + WScript.StdOut.WriteLine token(j) & vbTab & Round(SMA(stream,3),2) & vbTab & Round(SMA(stream,5),2) +Next + +Function SMA(s,p) + If Len(s) = 0 Then + SMA = 0 + Exit Function + End If + d = Split(s,",") + sum = 0 + If UBound(d) + 1 >= p Then + c = 0 + For i = UBound(d) To LBound(d) Step -1 + sum = sum + Int(d(i)) + c = c + 1 + If c = p Then + Exit For + End If + Next + SMA = sum / p + Else + For i = UBound(d) To LBound(d) Step -1 + sum = sum + Int(d(i)) + Next + SMA = sum / (UBound(d) + 1) + End If +End Function diff --git a/Task/B-zier-curves-Intersections/Ada/b-zier-curves-intersections.adb b/Task/B-zier-curves-Intersections/Ada/b-zier-curves-intersections.adb new file mode 100644 index 0000000000..c980b0f9cf --- /dev/null +++ b/Task/B-zier-curves-Intersections/Ada/b-zier-curves-intersections.adb @@ -0,0 +1,934 @@ +pragma wide_character_encoding (utf8); +pragma ada_2022; +pragma assertion_policy (check); + +-- +-- The algorithm here is iterated "Bézier clipping" [1] of quadratic +-- Bézier curves in a plane. However, the curves will be represented +-- in the s-power basis [2,3], and there will be these other +-- differences from the algorithms suggested by [1]: +-- +-- * Before clipping, the problem will be moved to a coordinate system +-- in which the "skeleton" of the clipper curve—the line segment +-- between its endpoints—extends from (0,0) and (1,0). In this +-- coordinate system, the "distance function" is the y-coordinate. +-- +-- * The fat line will be the best possible parallel to the "skeleton" +-- of the clipper curve. This is easily done in the s-power basis, +-- once one has transformed coordinate systems as described above: +-- the center coefficient of the (y,t)-polynomial is exactly four +-- times the optimum signed fat line width. +-- +-- * Intersections with fat line boundaries will be found not by +-- extending the sides of control polygons, but instead by the +-- quadratic formula. +-- +-- * Mechanisms to ensure termination of the algorithm, and to improve +-- the chances of finding intersections, may differ. +-- +-- Inputs and outputs to the algorithms will be in single +-- precision. However, the internals will be in double precision. This +-- decision helps resolve some minor numerical quandaries. +-- +-- References: +-- +-- [1] Sederberg, Thomas W., "Computer Aided Geometric Design" +-- (2012). Faculty +-- Publications. 1. https://scholarsarchive.byu.edu/facpub/1 +-- http://hdl.lib.byu.edu/1877/2822 +-- +-- [2] J. Sánchez-Reyes, ‘The symmetric analogue of the polynomial +-- power basis’, ACM Transactions on Graphics, vol 16 no 3, July +-- 1997, page 319. +-- +-- [3] J. Sánchez-Reyes, ‘Applications of the polynomial s-power basis +-- in geometry processing’, ACM Transactions on Graphics, vol 19 +-- no 1, January 2000, page 35. +-- +-- Suggestions for the future: +-- +-- * Combination of Bézier clipping and flatness testing. Remember +-- from other Rosetta Code examples, that in the s-power basis it is +-- simple to test the "flatness" of a parametric plane +-- curve. Suppose two curves are running nearly parallel to each +-- other, so they are difficult to reduce by clipping. Nevertheless, +-- they can be made flatter and flatter, so eventually they become +-- "segment-like" and can be tested by a line-intersection routine. +-- + +with ada.text_io; +use ada.text_io; + +with ada.float_text_io; +use ada.float_text_io; + +with ada.numerics.elementary_functions; +use ada.numerics.elementary_functions; + +with ada.numerics.long_elementary_functions; +use ada.numerics.long_elementary_functions; + +with ada.unchecked_deallocation; + +procedure bezier_intersections is + + subtype real is float; + subtype lreal is long_float; + + function between_0_and_1 (x : real) + return boolean is + begin + return 0.0 <= x and x <= 1.0; + end between_0_and_1; + + function between_0_and_1 (x : lreal) + return boolean is + begin + return 0.0 <= x and x <= 1.0; + end between_0_and_1; + + procedure quadratic_formula (a, b, c : lreal; + has_smaller : out boolean; + smaller : out lreal; + has_larger : out boolean; + larger : out lreal) + with post => has_smaller or not has_larger + is + -- + -- This routine is based on QUADPL from the Naval Surface Warfare + -- Center mathematical library nswc.f90 https://archive.ph/2IpWb + -- + -- We are interested only in real roots. Be aware that, if there + -- are two roots, they might be a double root. + -- + + bh, e, d : lreal; + + -- Avogadro’s number, by definition (since 2019): + arbitrary_value : constant lreal := 6.012214076e23; + begin + has_smaller := false; + has_larger := false; + smaller := arbitrary_value; + larger := arbitrary_value; + + if a = 0.0 then + if b = 0.0 then + -- The equation is a constant equation. I do not know what to + -- do with that. There may be no solution, or there may be + -- infinitely many solutions. Let us treat it as having no + -- USEFUL solutions. + null; + else + -- The equation is linear. There truly is only one root. + has_smaller := true; + smaller := -c / b; + end if; + elsif c = 0.0 then + -- The equation is quadratic, but the constant term + -- vanishes. One of the roots is trivially zero. + has_smaller := true; + has_larger := true; + smaller := 0.0; + larger := -b / a; + else + -- Compute the discriminant, avoiding overflow. + bh := b / 2.0; + if abs (bh) >= abs (c) then + e := 1.0 - (a / bh) * (c / bh); + d := sqrt (abs (e)) * abs(bh); + else + e := (if c < 0.0 then -a else a); + e := bh * (bh / abs (c)) - e; + d := sqrt (abs (e)) * sqrt (abs (c)); + end if; + if e < 0.0 then + -- The solutions are complex conjugates, but we are interested + -- only in real solutions. + null; + else + has_smaller := true; + has_larger := true; + if bh >= 0.0 then + d := -d; + end if; + larger := (-bh + d) / a; + if larger = 0.0 then + smaller := 0.0; -- Obviously a double root. + else + smaller := (c / larger) / a; + end if; + end if; + end if; + end quadratic_formula; + + type point is + record + x, y : real; + end record; + + type control_point_curve is + record + pt0, pt1, pt2 : point; + end record; + + type spower_poly is + record + c0, c1, c2 : real; + end record; + + type spower_curve is + record + x, y : spower_poly; + end record; + + function eval (poly : spower_poly; + t : real) + return real is + c0, c1, c2 : real; + begin + c0 := poly.c0; + c1 := poly.c1; + c2 := poly.c2; + return (if t <= 0.5 then + c0 + t * ((c2 - c0) + ((1.0 - t) * c1)) + else + c2 + (1.0 - t) * ((c0 - c2) + (t * c1))); + end eval; + + function eval (curve : spower_curve; + t : real) + return point is + begin + return (x => eval (curve.x, t), + y => eval (curve.y, t)); + end eval; + + function to_spower_curve (ctrl : control_point_curve) + return spower_curve is + curve : spower_curve; + p0x, p0y : long_float; + p1x, p1y : long_float; + p2x, p2y : long_float; + begin + curve.x.c0 := ctrl.pt0.x; + curve.y.c0 := ctrl.pt0.y; + + curve.x.c2 := ctrl.pt2.x; + curve.y.c2 := ctrl.pt2.y; + + p0x := long_float (ctrl.pt0.x); + p0y := long_float (ctrl.pt0.y); + p1x := long_float (ctrl.pt1.x); + p1y := long_float (ctrl.pt1.y); + p2x := long_float (ctrl.pt2.x); + p2y := long_float (ctrl.pt2.y); + curve.x.c1 := float (p1x + p1x - p0x - p2x); + curve.y.c1 := float (p1y + p1y - p0y - p2y); + + return curve; + end to_spower_curve; + + type opoint is + record + -- A point relative to the origin. + x, y : lreal; + end record; + + type dpoint is + record + -- A point relative to some other point. + dx, dy : lreal; + end record; + + function "-" (pt1, pt2 : opoint) + return dpoint is + begin + return (dx => pt1.x - pt2.x, + dy => pt1.y - pt2.y); + end "-"; + + function "+" (opt : opoint; + dpt : dpoint) + return opoint is + begin + return (x => opt.x + dpt.dx, + y => opt.y + dpt.dy); + end "+"; + + function "+" (pt1, pt2 : dpoint) + return dpoint is + begin + return (dx => pt1.dx + pt2.dx, + dy => pt1.dy + pt2.dy); + end "+"; + + function "*" (scalar : lreal; + pt : dpoint) + return dpoint is + begin + return (dx => scalar * pt.dx, + dy => scalar * pt.dy); + end "*"; + + type geocurve is + record + -- + -- A plane curve in s-power basis, represented geometrically. + -- + -- pt0 and pt2 form the curve’s ‘skeleton’. Their convex combination, + -- ((1.0-t)*pt0)+(t*pt1), form the linear backbone of the curve. + -- + -- (1.0-t)*t*pt1 forms (x,t) and (y,t) parabolas that are + -- convex-up/down, and which (because this is an s-power curve) + -- vanish as the curve becomes linear. + -- + -- The actual geocurve is the locus of (1.0-t)*t*pt1 relative to + -- the skeleton, respectively for each value of t in [0,1]. + -- + -- If [t0,t1] is not [0.0,1.0], then this is a portion of some + -- parent curve that is determined by context. + -- + -- (I feel as if all this can be crafted nicely in terms of a + -- geometric algebra, with special points not only at infinity + -- but also at the origin, but let us not worry about that for + -- now. Likely the calculations would not change much, but the + -- names of things might.) + -- + pt0 : opoint; + pt1 : dpoint; + pt2 : opoint; + t0, t1 : lreal; + end record; + + function to_geocurve (scurve : spower_curve) + return geocurve is + gcurve : geocurve; + begin + gcurve.pt0.x := lreal (scurve.x.c0); + gcurve.pt0.y := lreal (scurve.y.c0); + gcurve.pt1.dx := lreal (scurve.x.c1); + gcurve.pt1.dy := lreal (scurve.y.c1); + gcurve.pt2.x := lreal (scurve.x.c2); + gcurve.pt2.y := lreal (scurve.y.c2); + gcurve.t0 := 0.0; + gcurve.t1 := 1.0; + return gcurve; + end to_geocurve; + + function eval (gcurve : geocurve; + t : lreal) + return opoint is + pt0 : opoint; + pt1 : dpoint; + pt2 : opoint; + begin + pt0 := gcurve.pt0; + pt1 := gcurve.pt1; + pt2 := gcurve.pt2; + return (if t <= 0.5 then + pt0 + t * ((pt2 - pt0) + ((1.0 - t) * pt1)) + else + pt2 + (1.0 - t) * ((pt0 - pt2) + (t * pt1))); + end eval; + + type affine_projection is + record + -- + -- An affine transformation used to project objects into the + -- coordinate system of what we are calling a "skeleton". + -- + -- If it is an opoint, first add transpose[dx,dy]. If it is a + -- dpoint, ignore dx,dy. Then, in either case, premultiply by + -- [[a,b],[c,d]]. (One can view dx,dy as a dpoint.) + -- + dx, dy : lreal; + a, b : lreal; + c, d : lreal; + end record; + + function project (pt : opoint; + trans : affine_projection) + return opoint is + x, y : lreal; + begin + -- Apply an affine transformation to an opoint, projecting it from + -- one coordinate system to another. + x := pt.x + trans.dx; -- The origin may have moved. + y := pt.y + trans.dy; + return (x => trans.a * x + trans.b * y, -- Rotation, scaling, etc. + y => trans.c * x + trans.d * y); + end project; + + function project (pt : dpoint; + trans : affine_projection) + return dpoint is + x, y : lreal; + begin + -- Apply an affine transformation to a dpoint, projecting it from + -- one coordinate system to another. + x := pt.dx; -- With dpoint, translation is not performed. + y := pt.dy; + return (dx => trans.a * x + trans.b * y, -- Rotation, scaling, &c. + dy => trans.c * x + trans.d * y); + end project; + + function project (gcurve : geocurve; + trans : affine_projection) + return geocurve is + begin + -- Apply an affine transformation to a geocurve, projecting it + -- from one coordinate system to another. + return (pt0 => project (gcurve.pt0, trans), + pt1 => project (gcurve.pt1, trans), + pt2 => project (gcurve.pt2, trans), + t0 => 0.0, t1 => 1.0); + end project; + + function segment_projection_to_0_1 (pt0, pt1 : opoint) + return affine_projection is + a, b : lreal; + denom : lreal; + begin + -- Return the transformation that projects pt0 to (0,0) and pt1 to + -- (1,0) without any distortions except translation, rotation, and + -- scaling. + a := pt1.x - pt0.x; + b := pt1.y - pt0.y; + denom := (a * a) + (b * b); + pragma assert (denom /= 0.0); + a := a / denom; + b := b / denom; + return (dx => -pt0.x, dy => -pt0.y, + a => a, b => b, + c => -b, d => a); + end segment_projection_to_0_1; + + procedure test_segment_projection_to_0_1 is + trans : affine_projection; + pt : opoint; + begin + -- Some unit testing. + + trans := segment_projection_to_0_1 ((1.0, 2.0), (-3.0, 5.0)); + pt := project ((1.0, 2.0), trans); + pragma assert (abs (pt.x) < 1.0e-10); + pragma assert (abs (pt.y) < 1.0e-10); + pt := project ((-3.0, 5.0), trans); + pragma assert (abs (pt.x - 1.0) < 1.0e-10); + pragma assert (abs (pt.y) < 1.0e-10); + + trans := segment_projection_to_0_1 ((0.0, 2.0), (0.0, -50.0)); + pt := project ((0.0, 2.0), trans); + pragma assert (abs (pt.x) < 1.0e-10); + pragma assert (abs (pt.y) < 1.0e-10); + pt := project ((0.0, -50.0), trans); + pragma assert (abs (pt.x - 1.0) < 1.0e-10); + pragma assert (abs (pt.y) < 1.0e-10); + end test_segment_projection_to_0_1; + + function skeleton_projection (clipper : geocurve) + return affine_projection is + begin + -- Return the transformation that projects the "skeleton" of the + -- clipper into a coordinate system where the skeleton goes from + -- the origin (0,0) to the point (1,0). + return segment_projection_to_0_1 (clipper.pt0, clipper.pt2); + end skeleton_projection; + + procedure fat_line_bounds (projected_clipper : geocurve; + dmin, dmax : out lreal) is + d : lreal; + d1, d2 : lreal; + padding : constant lreal := lreal (real'model_epsilon) / 1000.0; + begin + -- + -- (1-t)*t is bounded on [0,1] by 0 and 1/4. Thus we have our fat + -- line boundaries. We leave some padding, however, for numerical + -- safety. The padding is much smaller than our tolerance. (We are + -- calculating in double precision, but to obtain results in + -- single precision.) + -- + -- The fat line bounds will be y=dmin and y=dmax. If you ignore + -- the padding, the fat line is the best possible among those + -- parallel to the skeleton. It is likely to be much tighter than + -- what you would infer from the Bernstein-basis control polygon. + -- + + d := projected_clipper.pt1.dy / 4.0; + d1 := -padding * d; + d2 := (1.0 + padding) * d; + dmin := lreal'min (d1, d2); + dmax := lreal'max (d1, d2); + end fat_line_bounds; + + type clipping_places is + (clip_everywhere, + clip_nowhere, + clip_left_and_right); + + type clipping_plan is + record + where : clipping_places; + t_lft : lreal; + t_rgt : lreal; + end record; + + function make_clipping_plan (projected_clippehend : geocurve; + dmin, dmax : lreal) + return clipping_plan is + ncrossings : integer range 0 .. 4; + tcrossings : array (1 .. 4) of lreal; + dcrossings : array (1 .. 4) of lreal; + has_smaller : boolean; + has_larger : boolean; + smaller : lreal; + larger : lreal; + c0, c1, c2 : lreal; + + function outside_of_bounds + return boolean is + dy, ymin, ymax : lreal; + begin + -- (1-t)*t is bounded on [0,1] by 0 and 1/4. Use that fact to + -- make padding for a simple (although not especially tight) + -- bounds on y. + dy := abs (projected_clippehend.pt1.dy) / 4.0; + ymin := -dy + lreal'min (projected_clippehend.pt0.y, + projected_clippehend.pt2.y); + ymax := dy + lreal'max (projected_clippehend.pt0.y, + projected_clippehend.pt2.y); + return (ymax <= dmin or dmax <= ymin); + end outside_of_bounds; + + procedure find_crossings (yvalue : lreal) is + begin + quadratic_formula (-c1, c1 + c2 - c0, c0 - yvalue, + has_smaller, smaller, has_larger, larger); + if has_smaller then + if between_0_and_1 (smaller) then + ncrossings := ncrossings + 1; + tcrossings(ncrossings) := smaller; + dcrossings(ncrossings) := yvalue; + end if; + end if; + if has_larger then + if between_0_and_1 (larger) then + ncrossings := ncrossings + 1; + tcrossings(ncrossings) := larger; + dcrossings(ncrossings) := yvalue; + end if; + end if; + end find_crossings; + + function create_a_clipping_plan + return clipping_plan is + plan : clipping_plan; + begin + -- + -- For simplicity, there is just one situation in which we will + -- clip: when there is one crossing of dmin and one crossing of + -- dmax. + -- + if ncrossings = 2 and then dcrossings(1) /= dcrossings(2) then + plan.where := clip_left_and_right; + plan.t_lft := lreal'min (tcrossings(1), tcrossings(2)); + plan.t_rgt := lreal'max (tcrossings(1), tcrossings(2)); + else + plan.where := clip_nowhere; + -- Arbitrary values: + plan.t_lft := 0.0; + plan.t_rgt := 0.0; + end if; + return plan; + end create_a_clipping_plan; + + function analyze_and_plan + return clipping_plan is + begin + c0 := projected_clippehend.pt0.y; + c1 := projected_clippehend.pt1.dy; + c2 := projected_clippehend.pt2.y; + ncrossings := 0; + find_crossings (dmin); + find_crossings (dmax); + return create_a_clipping_plan; + end analyze_and_plan; + + begin + return (if outside_of_bounds then + (where => clip_everywhere, + -- Arbitrary values: + t_lft => 0.0, t_rgt => 0.0) + else + analyze_and_plan); + end make_clipping_plan; + + function make_portion (gcurve : geocurve; + t0, t1 : lreal) + return geocurve is + pt0 : opoint; + pt1 : dpoint; + pt2 : opoint; + begin + pt0 := eval (gcurve, t0); + pt1 := ((t1 - t0 - t0) * t1 + (t0 * t0)) * gcurve.pt1; + pt2 := eval (gcurve, t1); + return (pt0 => pt0, pt1 => pt1, pt2 => pt2, + t0 => t0, t1 => t1); + end make_portion; + + procedure segment_parameters (a0, a1 : opoint; + b0, b1 : opoint; + ta, tb : out lreal) is + axdiff : lreal; + aydiff : lreal; + bxdiff : lreal; + bydiff : lreal; + denom : lreal; + ta1 : lreal; + tb1 : lreal; + begin + -- Do the line segments (a0,a1) and (b0,b1) intersect? If so, + -- return t-parameter values in ta,tb in [0,1] for the point of + -- intersection, treating them as parametric splines of degree + -- 1. Otherwise return ta=-1.0 and tb=-1.0. + + ta := -1.0; + tb := -1.0; + + axdiff := a1.x - a0.x; + aydiff := a1.y - a0.y; + bxdiff := b1.x - b0.x; + bydiff := b1.y - b0.y; + + denom := (axdiff * bydiff) - (aydiff * bxdiff); + + ta1 := ((bxdiff * a0.y) - (bydiff * a0.x) + + (b0.x * b1.y) - (b1.x * b0.y)); + ta1 := ta1 / denom; + if between_0_and_1 (ta1) then + tb1 := -((axdiff * b0.y) - (aydiff * b0.x) + + (a0.x * a1.y) - (a1.x * a0.y)); + tb1 := tb1 / denom; + if between_0_and_1 (tb1) then + ta := ta1; + tb := tb1; + end if; + end if; + end segment_parameters; + + type t_pair; + type t_pair_access is access t_pair; + type t_pair is + record + tp, tq : real; -- Single precision results. + next : t_pair_access; + end record; + procedure t_pair_delete is + new ada.unchecked_deallocation (t_pair, t_pair_access); + + function length (params : t_pair_access) + return natural is + n : natural; + p : t_pair_access; + begin + n := 0; + p := params; + while p /= null loop + n := n + 1; + p := p.next; + end loop; + return n; + end length; + + procedure insert_t_pair (params : in out t_pair_access; + tp, tq : real) + with pre => between_0_and_1 (tp) and between_0_and_1 (tq) + is + pair : t_pair_access; + begin + -- Test for duplicates and also sort as we insert. This is a + -- recursive implementation. + if params = null then + pair := new t_pair; + params := pair; + pair.next := null; + pair.tp := tp; + pair.tq := tq; + elsif abs (params.tp - tp) <= real'model_epsilon then + null; -- A duplicate, to within epsilon. + elsif params.tp < tp then + insert_t_pair (params.next, tp, tq); + else + pair := new t_pair; + pair.next := params.next; + params.next := pair; + pair.tp := params.tp; + pair.tq := params.tq; + params.tp := tp; + params.tq := tq; + end if; + end insert_t_pair; + + procedure insert_t_pair (params : in out t_pair_access; + tp, tq : lreal) + with pre => between_0_and_1 (tp) and between_0_and_1 (tq) + is + begin + insert_t_pair (params, real (tp), real (tq)); + end insert_t_pair; + + type clipping_roles is + (pportion_clips_qportion, + qportion_clips_pportion); + + type intersection_job; + type intersection_job_access is access intersection_job; + type intersection_job is + record + pportion : geocurve; + qportion : geocurve; + roles : clipping_roles; + next : intersection_job_access; + end record; + procedure intersection_job_delete is + new ada.unchecked_deallocation (intersection_job, + intersection_job_access); + + function find_intersections (p, q : geocurve) + return t_pair_access is + params : t_pair_access; + workload : intersection_job_access; + pportion : geocurve; + qportion : geocurve; + roles : clipping_roles; + tp, tq : lreal; + + tolerance : constant lreal := 0.4 * lreal (real'model_epsilon); + bisection_threshold : constant lreal := 0.2; + + procedure insert_job (pportion : geocurve; + qportion : geocurve; + roles : clipping_roles) + with post => workload /= null + is + job : intersection_job_access; + begin + job := new intersection_job; + job.pportion := pportion; + job.qportion := qportion; + job.roles := roles; + job.next := workload; + workload := job; + end insert_job; + + procedure insert_job (pportion : geocurve; + qportion : geocurve) + with post => workload /= null + is + roles : clipping_roles; + begin + if pportion.t1 - pportion.t0 <= qportion.t1 - qportion.t0 then + roles := pportion_clips_qportion; + else + roles := qportion_clips_pportion; + end if; + insert_job (pportion, qportion, roles); + end insert_job; + + procedure choose_job + with pre => workload /= null + is + job : intersection_job_access; + begin + job := workload; + workload := workload.next; + pportion := job.pportion; + qportion := job.qportion; + roles := job.roles; + intersection_job_delete (job); + end choose_job; + + function t_parameters_are_within_tolerance + return boolean is + begin + return (pportion.t1 - pportion.t0 <= tolerance + and qportion.t1 - qportion.t0 <= tolerance); + end t_parameters_are_within_tolerance; + + procedure insert_intersection_parameters is + begin + segment_parameters (pportion.pt0, pportion.pt2, + qportion.pt0, qportion.pt2, tp, tq); + if between_0_and_1 (tp) and between_0_and_1 (tq) then + tp := (1.0 - tp) * pportion.t0 + tp * pportion.t1; + tq := (1.0 - tq) * qportion.t0 + tq * qportion.t1; + insert_t_pair (params, tp, tq); + end if; + end insert_intersection_parameters; + + procedure no_intersections is + begin + -- Do nothing. The reason to have a procedure for this is so the + -- code will document itself. + null; + end no_intersections; + + procedure bisect_them is + pportion1 : geocurve; + pportion2 : geocurve; + qportion1 : geocurve; + qportion2 : geocurve; + t0, t1, th : lreal; + begin + -- + -- Sederberg employs heuristics to decide what to bisect and who + -- should be the clipper. We will simply bisect both curves, and + -- use some heuristic coded elsewhere to choose the + -- clipper. + -- + -- (Bisection as it is normally done in the s-power basis is + -- equivalent to change of homogeneous coordinates. It can be + -- applied to p and q directly and, for quadratics, is a simple + -- operation.) + -- + + t0 := pportion.t0; + t1 := pportion.t1; + th := 0.5 * t0 + 0.5 * t1; + pportion1 := make_portion (p, t0, th); + pportion2 := make_portion (p, th, t1); + + t0 := qportion.t0; + t1 := qportion.t1; + th := 0.5 * t0 + 0.5 * t1; + qportion1 := make_portion (q, t0, th); + qportion2 := make_portion (q, th, t1); + + insert_job (pportion1, qportion1); + insert_job (pportion1, qportion2); + insert_job (pportion2, qportion1); + insert_job (pportion2, qportion2); + end bisect_them; + + procedure clip_and_maybe_bisect (plan : clipping_plan) is + clipping : geocurve; + t_lft : lreal; + t_rgt : lreal; + t0, t1 : lreal; + begin + t_lft := plan.t_lft; + t_rgt := plan.t_rgt; + if roles = pportion_clips_qportion then + t0 := (1.0 - t_lft) * qportion.t0 + t_lft * qportion.t1; + t1 := (1.0 - t_rgt) * qportion.t0 + t_rgt * qportion.t1; + clipping := make_portion (q, t0, t1); + if 1.0 - (t_rgt - t_lft) < bisection_threshold then + qportion := clipping; + bisect_them; + else + insert_job (pportion, clipping, qportion_clips_pportion); + end if; + else + t0 := (1.0 - t_lft) * pportion.t0 + t_lft * pportion.t1; + t1 := (1.0 - t_rgt) * pportion.t0 + t_rgt * pportion.t1; + clipping := make_portion (p, t0, t1); + if 1.0 - (t_rgt - t_lft) < bisection_threshold then + pportion := clipping; + bisect_them; + else + insert_job (clipping, qportion, pportion_clips_qportion); + end if; + end if; + end clip_and_maybe_bisect; + + procedure perform_clipping is + clippehend, clipper : geocurve; + projected_clippehend : geocurve; + projected_clipper : geocurve; + trans : affine_projection; + dmin, dmax : lreal; + plan : clipping_plan; + begin + if roles = pportion_clips_qportion then + clipper := pportion; + clippehend := qportion; + else + clipper := qportion; + clippehend := pportion; + end if; + trans := skeleton_projection (clipper); + projected_clipper := project (clipper, trans); + fat_line_bounds (projected_clipper, dmin, dmax); + projected_clippehend := project (clippehend, trans); + plan := make_clipping_plan (projected_clippehend, dmin, dmax); + case plan.where is + when clip_everywhere => no_intersections; + when clip_nowhere => bisect_them; + when clip_left_and_right => clip_and_maybe_bisect (plan); + end case; + end perform_clipping; + + begin + params := null; + workload := null; + insert_job (p, q); + while workload /= null loop + choose_job; + if t_parameters_are_within_tolerance then + insert_intersection_parameters; + else + perform_clipping; + end if; + end loop; + return params; + end find_intersections; + + function find_intersections (p, q : spower_curve) + return t_pair_access is + begin + return find_intersections (to_geocurve (p), to_geocurve (q)); + end find_intersections; + + pctrl, qctrl : control_point_curve; + p, q : spower_curve; + params, ptr : t_pair_access; + +begin + test_segment_projection_to_0_1; + pctrl := ((x => -1.0, y => 0.0), + (x => 0.0, y => 10.0), + (x => 1.0, y => 0.0)); + qctrl := ((x => 2.0, y => 1.0), + (x => -8.0, y => 2.0), + (x => 2.0, y => 3.0)); + p := to_spower_curve (pctrl); + q := to_spower_curve (qctrl); + params := find_intersections (p, q); + + set_col (to => 9); + put ("convex up"); + set_col (to => 44); + put_line ("convex left"); + ptr := params; + while ptr /= null loop + set_col (to => 3); + put (ptr.tp, fore => 1, aft => 6, exp => 0); + set_col (to => 13); + put ("("); + put (eval (p, ptr.tp).x, fore => 1, aft => 6, exp => 0); + put (", "); + put (eval (p, ptr.tp).y, fore => 1, aft => 6, exp => 0); + put (")"); + set_col (to => 38); + put (ptr.tq, fore => 1, aft => 6, exp => 0); + set_col (to => 48); + put ("("); + put (eval (q, ptr.tq).x, fore => 1, aft => 6, exp => 0); + put (", "); + put (eval (q, ptr.tq).y, fore => 1, aft => 6, exp => 0); + put_line (")"); + ptr := ptr.next; + end loop; +end bezier_intersections; diff --git a/Task/Babbage-problem/ANSI-BASIC/babbage-problem.basic b/Task/Babbage-problem/ANSI-BASIC/babbage-problem.basic new file mode 100644 index 0000000000..f821fc97e2 --- /dev/null +++ b/Task/Babbage-problem/ANSI-BASIC/babbage-problem.basic @@ -0,0 +1,11 @@ +100 REM Babbage problem +110 REM We can start at the square root of 269696 +120 LET I = 520 +130 REM 269696 is a multiple of 4, 520 too +140 REM so we can increment I by 4 +150 DO WHILE MOD((I * I), 1000000) <> 269696 +160 LET I = I + 4 +170 LOOP +180 PRINT "The smallest positive integer whose square ends in the digits 269696 is"; I +190 PRINT "Its square is"; I * I +200 END diff --git a/Task/Babbage-problem/AWK/babbage-problem.awk b/Task/Babbage-problem/AWK/babbage-problem-1.awk similarity index 100% rename from Task/Babbage-problem/AWK/babbage-problem.awk rename to Task/Babbage-problem/AWK/babbage-problem-1.awk diff --git a/Task/Babbage-problem/AWK/babbage-problem-2.awk b/Task/Babbage-problem/AWK/babbage-problem-2.awk new file mode 100644 index 0000000000..a7bf3896a2 --- /dev/null +++ b/Task/Babbage-problem/AWK/babbage-problem-2.awk @@ -0,0 +1,49 @@ +#!/usr/bin/awk -f +# Quite efficient solution based on modulo arithmetic +# needs 270 square/mod calculations (variable tally) +# to calculate all solutions, and stop if none +BEGIN { + q = 269696 + if (ARGC > 1) q = ARGV[1] + # print q ":" + set[1] = 0 + m = 1 + while (m < q && length(set) > 0) { + new_set(set, m, q) + m *= 10 + } + if (length(set) > 1) { + asort(set) + for (i in set) { + v = set[i] + printf("%6d^2 -- %12d\n", v, v*v) + } + print tally " square/mod calculations" + } else { + print "NO SOLUTION" + } +} + +function new_set (old, m, q, new, mm, qm, i, j, k, l) { + mm = 10 * m + qm = q % mm + for (i in old) + for (j = 0; j < 10*m; j += m) { + tally += 1 + k = i + j + l = (k*k) % mm + if (l == qm) + new[k] = k + } + # new set in old + delete old + for (i in new) + old[i] = new[i] + # show(new) +} + +function show(set) { + for (i in set) + printf("%d ", i) + print "" +} diff --git a/Task/Babbage-problem/Ada/babbage-problem.adb b/Task/Babbage-problem/Ada/babbage-problem.adb new file mode 100644 index 0000000000..38861162c0 --- /dev/null +++ b/Task/Babbage-problem/Ada/babbage-problem.adb @@ -0,0 +1,54 @@ +-- The program is written in the programming language Ada. The name "Ada" +-- has been chosen in honour of your friend, +-- Augusta Ada King-Noel, Countess of Lovelace (née Byron). +-- +-- This is an program to search for the smallest integer X, such that +-- (X*X) mod 1_000_000 = 269_696. +-- +-- In the Ada language, "*" represents the multiplication symbol, "mod" the +-- modulo reduction, and the underscore "_" after every third digit in +-- literals is supposed to simplify reading numbers for humans. +-- Everything written after "--" in a line is a comment for the human, +-- and will be ignored by the computer. + +with Ada.Text_IO; +-- We need this to tell the computer how it will later output its result. + +procedure Babbage_Problem is + + -- We know that 99_736*99_736 is 9_947_269_696. This implies: + -- 1. The smallest X with X*X mod 1_000_000 = 269_696 is at most 99_736. + -- 2. The largest square X*X, which the program may have to deal with, + -- will be at most 9_947_269_69. + + type Number is range 1 .. 99_736*99_736; + X: Number := 1; + -- X can store numbers between 1 and 99_736*99_736. Computations + -- involving X can handle intermediate results in that range. + -- Initially the value stored at X is 1. + -- When running the program, the value will become 2, 3, 4, etc. + +begin + -- The program starts running. + + -- The computer first squares X, then it truncates the square, such + -- that the result is a six-digit number. + -- Finally, the computer checks if this number is 269_696. + while not (((X*X) mod 1_000_000) = 269_696) loop + + -- When the computer goes here, the number was not 269_696. + X := X+1; + -- So we replace X by X+1, and then go back and try again. + + end loop; + + -- When the computer eventually goes here, the number is 269_696. + -- E.e., the value stored at X is the value we are searching for. + -- We still have to print out this value. + + Ada.Text_IO.Put_Line(Number'Image(X)); + -- Number'Image(X) converts the value stored at X into a string of + -- printable characters (more specifically, of digits). + -- Ada.Text_IO.Put_Line(...) prints this string, for humans to read. + -- I did already run the program, and it did print out 25264. +end Babbage_Problem; diff --git a/Task/Babbage-problem/AutoLISP/babbage-problem.lsp b/Task/Babbage-problem/AutoLISP/babbage-problem.lsp new file mode 100644 index 0000000000..9636fbb3f5 --- /dev/null +++ b/Task/Babbage-problem/AutoLISP/babbage-problem.lsp @@ -0,0 +1,54 @@ +;; Let's Create a tool [a function] that helps us check positive integers +;; to see which one's square is the first one that ends in ...269696 +;; It should be noted that a function can be used many times repetitively +;; so let's create that function which will be used many times. + +;; First, define the function, give it a name and parameters; it will look like: +;; (defun [function_name] ([input_parameter] / [local_variables]) +(defun SquareEndsWith269696? (number / ) + ;; Let's have the computer Square the number (whichever number was passed to the function) + (setq number (* number number)) + ;; Now let's convert that number to a string + (setq numberString (itoa number)) + ;; Is the length of the numberString greater than or equal to 6 digits? + (if (>= (strlen numberString) 6) + ;; If it was greater than or equal to 6, we will check the last 6 characters to see if they are equal to "269696" + ;; If this equality check is successful, then we have found our number, and will return a successful function check! + (eq "269696" (substr numberString (- (strlen numberString) 5))) + ;; Otherwise, an unsuccessful function check will be returned + ) +) + +;; Second, we will create a function that only needs to be used once, they do not always need to be used many times +;; Let's use your name as the initiator/name for this function +(defun c:BABBAGE ( / integer SquareFound) + ;; Once we have initiated the function, let's create our first integer to check + (setq integer 1) + ;; Now, let's perform a loop do perform an action many times within the function + ;; We do not want our loop to run infinitely, so let's create a True/False variable to identify if our task is complete + (setq SquareFound nil) + ;; ok, let's use the loop and True/False variable to continually check if we have found our correct integer + (while (not SquareFound) + ;; Now within the loop, let's use our First function to check if we have the correct integer + ;; We will save the new result of our check over our existing True/False variable + (setq SquareFound (SquareEndsWith269696? integer)) + ;; If the square was not found... + (if (not SquareFound) + ;; ...increase our integer number by 1 + (setq integer (1+ integer)) + ) + ;; Once the integer is found, our loop will end and the code will continue forward + ;; Otherwise, it will start back at "(while ..." + ) + ;; If we have made it this far, then our integer has been found! + ;; let's show everyone what the integer is + (prompt + (strcat + "\nThe smallest integer has been found!" + "\nInteger: " (itoa integer) ;; <-- we are converting the integer to a string + "\nSquared: " (itoa (* integer integer)) ;; <-- let's show everyone the squared number to prove it + ) + ) + ;; All done, this last line is not required, but makes the ending cleaner + (princ) +) diff --git a/Task/Babbage-problem/Berkeley-Logo/babbage-problem.logo b/Task/Babbage-problem/Berkeley-Logo/babbage-problem.logo new file mode 100644 index 0000000000..938e2c01b6 --- /dev/null +++ b/Task/Babbage-problem/Berkeley-Logo/babbage-problem.logo @@ -0,0 +1,9 @@ +to babbage.problem + ; We can start at the square root of 269696 + make "I 520 + ; 269696 is a multiple of 4, 520 too + ; so we can increment :i by 4 + while [not (modulo (:i * :i) 1000000 = 269696)] [make "i :i + 4] + print sentence "|The smallest positive integer whose square ends in the digits 269696 is| :i + print sentence "|Its square is|" (:i * :i) +end diff --git a/Task/Babbage-problem/COBOL/babbage-problem.cob b/Task/Babbage-problem/COBOL/babbage-problem.cob new file mode 100644 index 0000000000..3649fdb16e --- /dev/null +++ b/Task/Babbage-problem/COBOL/babbage-problem.cob @@ -0,0 +1,32 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. BABBAGE-PROGRAM. +* A line beginning with an asterisk is an explanatory note. +* The machine will disregard any such line. + + DATA DIVISION. + WORKING-STORAGE SECTION. +* In this part of the program we reserve the storage space we shall +* be using for our variables, using a 'PICTURE' clause to specify +* how many digits the machine is to keep free. +* The prefixed number 77 indicates that these variables do not form part +* of any larger 'record' that we might want to deal with as a whole. + 77 N PICTURE 99999. +* We know that 99,736 is a valid answer. + 77 N-SQUARED PICTURE 9999999999. + 77 LAST-SIX PICTURE 999999. + + PROCEDURE DIVISION. +* Here we specify the calculations that the machine is to carry out. + CONTROL-PARAGRAPH. + PERFORM COMPUTATION-PARAGRAPH VARYING N FROM 1 BY 1 + UNTIL LAST-SIX IS EQUAL TO 269696. + STOP RUN. + COMPUTATION-PARAGRAPH. + MULTIPLY N BY N GIVING N-SQUARED. + MOVE N-SQUARED TO LAST-SIX. +* Since the variable LAST-SIX can hold a maximum of six digits, +* only the final six digits of N-SQUARED will be moved into it: +* the rest will not fit and will simply be discarded. + IF LAST-SIX IS EQUAL TO 269696 THEN DISPLAY N. + + END PROGRAM BABBAGE-PROGRAM. diff --git a/Task/Babbage-problem/Crystal/babbage-problem.cr b/Task/Babbage-problem/Crystal/babbage-problem.cr new file mode 100644 index 0000000000..5d78758faf --- /dev/null +++ b/Task/Babbage-problem/Crystal/babbage-problem.cr @@ -0,0 +1,7 @@ +# brute force approach +i = Math.isqrt(269_696) +i -= 1 unless i.even? +while i*i % 1_000_000 != 269_696 + i += 2 +end +p i diff --git a/Task/Babbage-problem/HPPPL/babbage-problem.hpppl b/Task/Babbage-problem/HPPPL/babbage-problem.hpppl new file mode 100644 index 0000000000..1c6a7d9f51 --- /dev/null +++ b/Task/Babbage-problem/HPPPL/babbage-problem.hpppl @@ -0,0 +1,9 @@ +EXPORT BabbageProblem() +BEGIN +PRINT(); +PRINT("BABBAGE PROBLEM:"); +I := 520; +WHILE I*I MOD 1000000 ≠ 269696 DO + I := I + 4; +END; +PRINT("Min X = " + I + " con X² = " + I*I); diff --git a/Task/Babbage-problem/Icon/babbage-problem.icon b/Task/Babbage-problem/Icon/babbage-problem.icon new file mode 100644 index 0000000000..9d245893e9 --- /dev/null +++ b/Task/Babbage-problem/Icon/babbage-problem.icon @@ -0,0 +1,5 @@ +procedure main(A) + tail := \A[1] | 269696 + size := 10^*tail + if ((n := seq())^2 % size) = tail then write(n," -> ",n^2) +end diff --git a/Task/Babbage-problem/Phix/babbage-problem-2.phix b/Task/Babbage-problem/Phix/babbage-problem-2.phix index 26c4d411c6..fe5df40091 100644 --- a/Task/Babbage-problem/Phix/babbage-problem-2.phix +++ b/Task/Babbage-problem/Phix/babbage-problem-2.phix @@ -12,6 +12,7 @@ procedure solve_babbage_problem() -- (so that return quits 3 loops) cc += 1 if remainder(square,r10) = remainder(269696,r10) then if digits=6 then +-- if remainder(square,1e6)=269696 then printf(1,"Solution: %d (%d calcs)\n",{cand,cc}) return -- leave solve_babbage_problem() end if @@ -20,7 +21,8 @@ procedure solve_babbage_problem() -- (so that return quits 3 loops) end for end for {cands,nextc} = {nextc,{}} - printf(1,"%d-digit candidates: %v\n",{digits,cands}) + string cs = join(cands,",",fmt:=sprintf("%%0%dd",digits)) + printf(1,"%d-digit candidates: %s\n",{digits,cs}) p10 *= 10 r10 *= 10 end for diff --git a/Task/Babbage-problem/Pluto/babbage-problem.pluto b/Task/Babbage-problem/Pluto/babbage-problem.pluto new file mode 100644 index 0000000000..279df6a570 --- /dev/null +++ b/Task/Babbage-problem/Pluto/babbage-problem.pluto @@ -0,0 +1,25 @@ +--[[ + The answer must be an even number and it can't be less than the square root of 269,696. + So, if we start from that, keep on adding 2 and squaring it we'll eventually find the answer. + However, we can skip numbers which don't end in 4 or 6 as their squares can't end in 6. +]] + +local fmt = require "fmt" -- this enables us to format numbers with thousand separators +local start = math.sqrt(269696) -- get the square root of the starting value +start = math.ceil(start) -- get the next integer higher than (or equal to) the square root +start = math.ceil(start / 2) * 2 -- if it's odd, use the next even integer +local i = start -- assign it to a variable 'i' for use in the following loop +while true do -- loop indefinitely till we find the answer + local sq = i * i -- get the square of 'i' + local last6 = sq % 1000000 -- get its last 6 digits by taking the remainder after division by a million + if last6 == 269696 then -- if those digits are 269696, we're done and can print the result + fmt.print($"The lowest number whose square ends in 269,696 is %,s.", i) + fmt.print($"Its square is %,s.", sq) + break -- break from the loop and end the program + end + if i % 10 == 6 then -- get the last digit by taking the remainder after division by 10 + i += 8 -- if the last digit is 6 add 8 (to end in 4) + else + i += 2 -- otherwise add 2 + end +end diff --git a/Task/Babbage-problem/PowerShell/babbage-problem-1.ps1 b/Task/Babbage-problem/PowerShell/babbage-problem-1.ps1 new file mode 100644 index 0000000000..58701ec339 --- /dev/null +++ b/Task/Babbage-problem/PowerShell/babbage-problem-1.ps1 @@ -0,0 +1,45 @@ +########################################################################################### +# +# Definitions: +# +# Lines that begin with the "#" symbol are comments: they will be ignored by the machine. +# +# ----------------------------------------------------------------------------------------- +# +# While +# +# Run a command block based on the results of a conditional test. +# +# Syntax +# while (condition) {command_block} +# +# Key +# +# condition If this evaluates to TRUE the loop {command_block} runs. +# when the loop has run once the condition is evaluated again. +# +# command_block Commands to run each time the loop repeats. +# +# As long as the condition remains true, PowerShell reruns the {command_block} section. +# +# ----------------------------------------------------------------------------------------- +# +# * means 'multiplied by' +# % means 'modulo', or remainder after division +# -ne means 'is not equal to' +# ++ means 'increment variable by one' +# +########################################################################################### + +# Declare a variable, $integer, with a starting value of 0. + +$integer = 0 + +while (($integer * $integer) % 1000000 -ne 269696) +{ + $integer++ +} + +# Show the result. + +$integer diff --git a/Task/Babbage-problem/PowerShell/babbage-problem-2.ps1 b/Task/Babbage-problem/PowerShell/babbage-problem-2.ps1 new file mode 100644 index 0000000000..a52ad7c4ea --- /dev/null +++ b/Task/Babbage-problem/PowerShell/babbage-problem-2.ps1 @@ -0,0 +1,24 @@ +# Start with the smallest potential square number +$TestSquare = 269696 + +# Test if our potential square is a square +# by testing if the square root of it is an integer +# Test if the square root is an integer by testing if the remainder +# of the square root divided by 1 is greater than zero +# % is the remainder operator +# -gt is the "greater than" operator + +# While the remainder of the square root divided by one is greater than zero +While ( [Math]::Sqrt( $TestSquare ) % 1 -gt 0 ) + { + # Add 100,000 to get the next potential square number + $TestSquare = $TestSquare + 1000000 + } +# This will loop until we get a value for $TestSquare that is a square number + +# Caclulate the root +$Root = [Math]::Sqrt( $TestSquare ) + +# Display the result and its square +$Root +$TestSquare diff --git a/Task/Babbage-problem/Rebol/babbage-problem.rebol b/Task/Babbage-problem/Rebol/babbage-problem.rebol new file mode 100644 index 0000000000..f391c2c268 --- /dev/null +++ b/Task/Babbage-problem/Rebol/babbage-problem.rebol @@ -0,0 +1,10 @@ +number: 510 ;; starting number +;; repeat, until the last condition in the block is true +until [ + number: number + 2 ;; only even numbers can have even squares + ;; The word modulo computes the non-negative remainder of the + ;; first argument divided by the second argument. + ;; ** => Returns a number raised to a given power (exponent) + 269696 = modulo (number ** 2) 1000000 +] +?? number diff --git a/Task/Babbage-problem/TAV/babbage-problem-1.tav b/Task/Babbage-problem/TAV/babbage-problem-1.tav new file mode 100644 index 0000000000..227950ff22 --- /dev/null +++ b/Task/Babbage-problem/TAV/babbage-problem-1.tav @@ -0,0 +1,6 @@ +main (p):+ + q = 269696 \ ending to be found + m = 1000000 \ corresponding modulus + for i = from 1 upto m^2 + if i^2 %% m = q: break + print i, i^2, q diff --git a/Task/Babbage-problem/TAV/babbage-problem-2.tav b/Task/Babbage-problem/TAV/babbage-problem-2.tav new file mode 100644 index 0000000000..7ed9909dc8 --- /dev/null +++ b/Task/Babbage-problem/TAV/babbage-problem-2.tav @@ -0,0 +1,39 @@ +main (p):+ + q =: string p.1 as integer else 269696 + debug enable + debug print "Sets:" + + \ central loop: calculate new set of endings for powers of 10 + set =: new row size 1 init 0 + m =: 1 + while m < q && set.Count > 0 + set =: new set set mod m find q + debug print join set + m =*10 + rounds += 1 + debug print '' + \ show result + + print format "Result for %_;:" q + if set.Count < 1 + print "NO SOLUTION" + return + row set sort ascending + for x =: row set give values + print format '%6;^2 = %16_;', x, x^2 + print rounds, "rounds, ", $tally, "square/mod calculations" + $tally =: () + +\ calculate new set of endings mod m from m-1 +new set (old) mod (m) find (q): + new =: new row + mm =: 10 * m + qm =: q %% mm + for i =: give values old + for j =: from 0 upto 9*m step m + k =: i + j + l =: k^2 %% mm + $tally += 1 \ global to count calculations + if l = qm + new[] =: k + return new diff --git a/Task/Babbage-problem/Uiua/babbage-problem.uiua b/Task/Babbage-problem/Uiua/babbage-problem.uiua new file mode 100644 index 0000000000..4165f6a1da --- /dev/null +++ b/Task/Babbage-problem/Uiua/babbage-problem.uiua @@ -0,0 +1 @@ +⍢(+1|≠269696◿₁₀₀₀₀₀₀˙×) 1 diff --git a/Task/Babbage-problem/VBScript/babbage-problem.vbs b/Task/Babbage-problem/VBScript/babbage-problem.vbs new file mode 100644 index 0000000000..71a343cc88 --- /dev/null +++ b/Task/Babbage-problem/VBScript/babbage-problem.vbs @@ -0,0 +1,25 @@ +'Sir, this is a script that could solve your problem. + +'Lines that begin with the apostrophe are comments. The machine ignores them. + +'The next line declares a variable n and sets it to 0. Note that the +'equals sign "assigns", not just "relates". So in here, this is more +'of a command, rather than just a mere proposition. +n = 0 + +'Starting from the initial value, which is 0, n is being incremented +'by 1 while its square, n * n (* means multiplication) does not have +'a modulo of 269696 when divided by one million. This means that the +'loop will stop when the smallest positive integer whose square ends +'in 269696 is found and stored in n. Before I forget, "<>" basically +'means "not equal to". +Do While ((n * n) Mod 1000000) <> 269696 + n = n + 1 'Increment by 1. +Loop + +'The function "WScript.Echo" displays the string to the monitor. The +'ampersand concatenates strings or variables to be displayed. +WScript.Echo("The smallest positive integer whose square ends in 269696 is " & n & ".") +WScript.Echo("Its square is " & n*n & ".") + +'End of Program. diff --git a/Task/Babylonian-spiral/Ada/babylonian-spiral.adb b/Task/Babylonian-spiral/Ada/babylonian-spiral.adb new file mode 100644 index 0000000000..53593c0b29 --- /dev/null +++ b/Task/Babylonian-spiral/Ada/babylonian-spiral.adb @@ -0,0 +1,136 @@ +pragma Ada_2022; +with Ada.Containers.Vectors; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Babylonian_Spiral is + + type Fixed_10_4 is delta 10.0 ** (-4) digits 9; + type Point is record + X, Y : Integer; + end record; + type Points_Array is array (1 .. 10_000) of Point; + Points : Points_Array := [1 => (0, 0), 2 => (0, 1), others => (0, 0)]; + Ante_Previous_Point, Previous_Point : Point; + package Point_Vectors is new Ada.Containers.Vectors (Positive, Point); + use Point_Vectors; + Point_Vector, PVC : Point_Vectors.Vector; + Min_Radius : Integer := 1; + Previous_Dist : Fixed_10_4; -- The previous distance which must be exceeded + Min_Dist, Tmp_Dist : Fixed_10_4; + Max_Angle, Tmp_Angle : Fixed_10_4; + Tmp_Ix, Cand_Ix : Integer; + Fixed_Pi : constant Fixed_10_4 := 3.1416; + SVG_File : File_Type; + X, Y : Integer; + + function Distance (Point1, Point2 : Point) return Fixed_10_4 is + (Fixed_10_4 (Sqrt (Float (Point2.X - Point1.X)**2 + + Float (Point2.Y - Point1.Y)**2))); + + function Generate_Square_Of_Points (Centre : Point; Max_Radius : Positive) + return Point_Vectors.Vector is + PV : Point_Vectors.Vector; + begin + for X in Centre.X - Max_Radius .. Centre.X + Max_Radius loop + for Y in Centre.Y - Max_Radius .. Centre.Y + Max_Radius loop + PV.Append ((X, Y), 1); + end loop; + end loop; + return PV; + end Generate_Square_Of_Points; + + function Atan2 (Y, X : Float) return Float is + Res : Float; + begin + if X > 0.0 then Res := Arctan (Y / X); + elsif X < 0.0 and then Y >= 0.0 then Res := Arctan (Y / X) + Pi; + elsif X < 0.0 and then Y < 0.0 then Res := Arctan (Y / X) - Pi; + elsif X = 0.0 and then Y > 0.0 then Res := Pi / 2.0; + elsif X = 0.0 and then Y > 0.0 then Res := -Pi / 2.0; + else Res := -Pi / 2.0; -- Technically: Undefined + end if; + return Res; + end Atan2; + + function Angle (Centre, P2, P3 : Point) return Fixed_10_4 is + Res : Float; + begin + Res := Atan2 (Float (P3.Y) - Float (Centre.Y), Float (P3.X) - Float (Centre.X)) - + Atan2 (Float (P2.Y) - Float (Centre.Y), Float (P2.X) - Float (Centre.X)); + return Fixed_10_4 (Res); + end Angle; + + function Collinear (Pt1, Pt2, Pt3 : Point) return Boolean is + begin + if Pt1.X = Pt2.X and then Pt2.X = Pt3.X then + return True; + end if; + if Pt1.Y = Pt2.Y and then Pt2.Y = Pt3.Y then + return True; + end if; + return Pt1.X * (Pt2.Y - Pt3.Y) + Pt2.X * (Pt3.Y - Pt1.Y) + Pt3.X * (Pt1.Y - Pt2.Y) = 0; + end Collinear; + +begin + for Point_Ix in 3 .. Points'Last loop + Ante_Previous_Point := Points (Point_Ix - 2); + Previous_Point := Points (Point_Ix - 1); + Previous_Dist := Distance (Points (Point_Ix - 1), Points (Point_Ix - 2)); + Min_Radius := Integer (Previous_Dist); + Min_Dist := 99999.999; + Max_Angle := 0.0; + + -- examine surrounding points + Point_Vector := Generate_Square_Of_Points (Previous_Point, Min_Radius + 4); + for Pt of Point_Vector loop + if not Collinear (Pt, Previous_Point, Ante_Previous_Point) then + Tmp_Dist := Distance (Pt, Previous_Point); + if Tmp_Dist > Previous_Dist and then Tmp_Dist < Min_Dist then + Min_Dist := Tmp_Dist; + end if; + end if; + + end loop; + + -- Grab closest Points + PVC.Clear; + for Pt of Point_Vector loop + if Distance (Pt, Previous_Point) = Min_Dist then + PVC.Append (Pt); + end if; + end loop; + + Tmp_Ix := 1; + for Pt of PVC loop + Tmp_Angle := Angle (Previous_Point, Ante_Previous_Point, Pt); + if Tmp_Angle < -(Fixed_Pi) then + Tmp_Angle := Tmp_Angle + (2.0 * Fixed_Pi); + end if; + if Tmp_Angle < Fixed_Pi and then Tmp_Angle > Max_Angle then + Cand_Ix := Tmp_Ix; + Max_Angle := Tmp_Angle; + end if; + Tmp_Ix := Tmp_Ix + 1; + end loop; + if Point_Ix < 41 then + Put ("(" & PVC (Cand_Ix).X'Image & "," & PVC (Cand_Ix).Y'Image & ") "); + end if; + Points (Point_Ix) := PVC (Cand_Ix); + end loop; + Create (SVG_File, Out_File, "babylonian_spiral.svg"); + Put_Line (SVG_File, ""); + Put_Line (SVG_File, ""); + X := 500 + Points (1).X; + Y := 10000 - Points (1).Y; + Put (SVG_File, "\n"); + Close (SVG_File); +end Babylonian_Spiral; diff --git a/Task/Babylonian-spiral/C++/babylonian-spiral.cpp b/Task/Babylonian-spiral/C++/babylonian-spiral.cpp index 9cbf1f7d2d..38aebc699a 100644 --- a/Task/Babylonian-spiral/C++/babylonian-spiral.cpp +++ b/Task/Babylonian-spiral/C++/babylonian-spiral.cpp @@ -7,68 +7,68 @@ typedef std::pair point; std::vector babylonian_spiral(int32_t step_count) { - const double tau = 2 * std::numbers::pi; + const double tau = 2 * std::numbers::pi; - std::vector squares(step_count + 1); - for ( int32_t i = 0; i < step_count; ++i ) { - squares[i] = i * i; - } - std::vector points { point(0, 0), point (0, 1) }; - int32_t norm = 1; + std::vector squares(step_count + 1); + for ( int32_t i = 0; i < step_count; ++i ) { + squares[i] = i * i; + } + std::vector points { point(0, 0), point (0, 1) }; + int32_t norm = 1; - for ( int32_t step = 0; step < step_count - 2; ++step ) { - point previousPoint = points.back(); - const double theta = atan2(previousPoint.second, previousPoint.first); - std::vector candidates; - while ( candidates.empty() ) { - norm += 1; - for ( int32_t i = 0; i < step_count; ++i ) { - int32_t a = squares[i]; - if ( a > norm / 2 ) { - break; - } - for ( int32_t j = sqrt(norm) + 1; j >= 0; --j ) { - int32_t b = squares[j]; - if ( a + b < norm ) { - break; - } - if ( a + b == norm ) { - std::vector next_points = { point(i, j), point(-i, j), point(i, -j), point(-i, -j), - point(j, i), point(-j, i), point(j, -i), point(-j, -i) }; - candidates.reserve(next_points.size()); - std::move(next_points.begin(), next_points.end(), std::back_inserter(candidates)); - } - } - } - } + for ( int32_t step = 0; step < step_count - 2; ++step ) { + point previousPoint = points.back(); + const double theta = atan2(previousPoint.second, previousPoint.first); + std::vector candidates; + while ( candidates.empty() ) { + norm += 1; + for ( int32_t i = 0; i < step_count; ++i ) { + int32_t a = squares[i]; + if ( a > norm / 2 ) { + break; + } + for ( int32_t j = sqrt(norm) + 1; j >= 0; --j ) { + int32_t b = squares[j]; + if ( a + b < norm ) { + break; + } + if ( a + b == norm ) { + std::vector next_points = { point(i, j), point(-i, j), point(i, -j), point(-i, -j), + point(j, i), point(-j, i), point(j, -i), point(-j, -i) }; + candidates.reserve(next_points.size()); + std::move(next_points.begin(), next_points.end(), std::back_inserter(candidates)); + } + } + } + } - point minimum; - double minimum_value = tau; - for ( point candidate : candidates ) { - double value = fmod(theta - atan2(candidate.second, candidate.first) + tau, tau); - if ( value < minimum_value ) { - minimum_value = value; - minimum = candidate; - } - } + point minimum; + double minimum_value = tau; + for ( point candidate : candidates ) { + double value = fmod(theta - atan2(candidate.second, candidate.first) + tau, tau); + if ( value < minimum_value ) { + minimum_value = value; + minimum = candidate; + } + } - points.push_back(minimum); - } + points.push_back(minimum); + } - for ( uint64_t i = 0; i < points.size() - 1; ++i ) { - points[i + 1] = point(points[i].first + points[i + 1].first, points[i].second + points[i + 1].second); - } - return points; + for ( uint64_t i = 0; i < points.size() - 1; ++i ) { + points[i + 1] = point(points[i].first + points[i + 1].first, points[i].second + points[i + 1].second); + } + return points; } int main() { - std::vector points = babylonian_spiral(40); - std::cout << "The first 40 points of the Babylonian spiral are:" << std::endl; - for ( int32_t i = 0, column = 0; i < 40; ++i ) { - std::string point_str = "(" + std::to_string(points[i].first) + ", " + std::to_string(points[i].second) + ")"; - std::cout << std::setw(10) << point_str; - if ( ++column % 10 == 0 ) { - std::cout << std::endl; - } - } + std::vector points = babylonian_spiral(40); + std::cout << "The first 40 points of the Babylonian spiral are:" << std::endl; + for ( int32_t i = 0, column = 0; i < 40; ++i ) { + std::string point_str = "(" + std::to_string(points[i].first) + ", " + std::to_string(points[i].second) + ")"; + std::cout << std::setw(10) << point_str; + if ( ++column % 10 == 0 ) { + std::cout << std::endl; + } + } } diff --git a/Task/Babylonian-spiral/Crystal/babylonian-spiral.cr b/Task/Babylonian-spiral/Crystal/babylonian-spiral.cr new file mode 100644 index 0000000000..0ef5e1c50e --- /dev/null +++ b/Task/Babylonian-spiral/Crystal/babylonian-spiral.cr @@ -0,0 +1,40 @@ +def spiral + next_p = [{x: 1, y: 1, hyp: 2}] + next_interval = ->(int : Int32) { + next_p.concat((0..int).map {|i| {x: int, y: i, hyp: int**2 + i**2 } }) + next_p.sort_by! &.[:hyp] + } + interval = 1 + last_p = tail = {0,1} + [{0,0}, tail].each.chain Iterator.of { + θ = Math.atan2 *tail.reverse + this = [next_p.shift] + while !next_p.empty? && next_p[0][:hyp] == this[0][:hyp] + this << next_p.shift + end + candidates = this.flat_map {|n| + i, j = n[:x], n[:y] + next_interval.call(interval += 1) if interval == i + [{i,j},{-i,j},{i,-j},{-i,-j},{j,i},{-j,i},{j,-i},{-j,-i}] + } + tail = candidates.min_by {|c| (θ - Math.atan2(*c.reverse)) % (Math::PI*2) } + last_p = { tail[0] + last_p[0], tail[1] + last_p[1] } + } +end + +spiral.first(40).each_slice(10) do |row| + puts row.map {|c| " %9s" % c.to_s}.join +end + +# stretch: + +svg = [%()] +svg << %() +svg << %() +svg << %() + +File.write("crystal_babylonian_spiral.svg", svg.join) diff --git a/Task/Babylonian-spiral/Java/babylonian-spiral.java b/Task/Babylonian-spiral/Java/babylonian-spiral.java index 8ca93aa152..601a49cd37 100644 --- a/Task/Babylonian-spiral/Java/babylonian-spiral.java +++ b/Task/Babylonian-spiral/Java/babylonian-spiral.java @@ -12,76 +12,76 @@ import java.util.stream.Stream; public final class BabylonianSpiral { - public static void main(String[] aArgs) throws IOException { - List points = babylonianSpiral(10_000); - System.out.println("The first 40 points of the Babylonian spiral are:"); - for ( int i = 0, column = 0; i < 40; i++ ) { - System.out.print(String.format("%9s%s", - "(" + points.get(i).x + ", " + points.get(i).y + ")", ( ++column % 10 == 0 ) ? "\n" : " ")); - } - System.out.println(); - - String text = svgText(points, 800); - Files.write(Paths.get("C:/Users/psnow/Desktop/BabylonianSpiralJava.svg"), text.getBytes()); - } - - private static List babylonianSpiral(int aStepCount) { - final double tau = 2 * Math.PI; - List squares = IntStream.rangeClosed(0, aStepCount).map( i -> i * i ).boxed().toList(); - List points = Stream.of( new Point(0, 0), new Point(0, 1) ).collect(Collectors.toList()); - int norm = 1; - - for ( int step = 0; step < aStepCount - 2; step++ ) { - Point previousPoint = points.get(points.size() - 1); - final double theta = Math.atan2(previousPoint.y, previousPoint.x); - Set candidates = new HashSet(); - while ( candidates.isEmpty() ) { - norm += 1; - for ( int i = 0; i < aStepCount; i++ ) { - int a = squares.get(i); - if ( a > norm / 2 ) { - break; - } - for ( int j = (int) Math.sqrt(norm) + 1; j >= 0; j-- ) { - int b = squares.get(j); - if ( a + b < norm ) { - break; - } - if ( a + b == norm ) { - candidates.addAll( - List.of( new Point(i, j), new Point(-i, j), new Point(i, -j), new Point(-i, -j), - new Point(j, i), new Point(-j, i), new Point(j, -i), new Point(-j, -i) )); - } - } - } - } - - Comparator comparatorPoint = (one, two) -> Double.compare( - ( theta - Math.atan2(one.y, one.x) + tau ) % tau, ( theta - Math.atan2(two.y, two.x) + tau ) % tau); - - Point minimum = candidates.stream().min(comparatorPoint).get(); - points.add(minimum); - } - - for ( int i = 0; i < points.size() - 1; i++ ) { - points.set(i + 1, new Point(points.get(i).x + points.get(i + 1).x, points.get(i).y + points.get(i + 1).y)); - } - return points; - } + public static void main(String[] aArgs) throws IOException { + List points = babylonianSpiral(10_000); + System.out.println("The first 40 points of the Babylonian spiral are:"); + for ( int i = 0, column = 0; i < 40; i++ ) { + System.out.print(String.format("%9s%s", + "(" + points.get(i).x + ", " + points.get(i).y + ")", ( ++column % 10 == 0 ) ? "\n" : " ")); + } + System.out.println(); - private static String svgText(List aPoints, int aSize) { - StringBuilder text = new StringBuilder(); - text.append(" babylonianSpiral(int aStepCount) { + final double tau = 2 * Math.PI; + List squares = IntStream.rangeClosed(0, aStepCount).map( i -> i * i ).boxed().toList(); + List points = Stream.of( new Point(0, 0), new Point(0, 1) ).collect(Collectors.toList()); + int norm = 1; + + for ( int step = 0; step < aStepCount - 2; step++ ) { + Point previousPoint = points.get(points.size() - 1); + final double theta = Math.atan2(previousPoint.y, previousPoint.x); + Set candidates = new HashSet(); + while ( candidates.isEmpty() ) { + norm += 1; + for ( int i = 0; i < aStepCount; i++ ) { + int a = squares.get(i); + if ( a > norm / 2 ) { + break; + } + for ( int j = (int) Math.sqrt(norm) + 1; j >= 0; j-- ) { + int b = squares.get(j); + if ( a + b < norm ) { + break; + } + if ( a + b == norm ) { + candidates.addAll( + List.of( new Point(i, j), new Point(-i, j), new Point(i, -j), new Point(-i, -j), + new Point(j, i), new Point(-j, i), new Point(j, -i), new Point(-j, -i) )); + } + } + } + } + + Comparator comparatorPoint = (one, two) -> Double.compare( + ( theta - Math.atan2(one.y, one.x) + tau ) % tau, ( theta - Math.atan2(two.y, two.x) + tau ) % tau); + + Point minimum = candidates.stream().min(comparatorPoint).get(); + points.add(minimum); + } + + for ( int i = 0; i < points.size() - 1; i++ ) { + points.set(i + 1, new Point(points.get(i).x + points.get(i + 1).x, points.get(i).y + points.get(i + 1).y)); + } + return points; + } + + private static String svgText(List aPoints, int aSize) { + StringBuilder text = new StringBuilder(); + text.append("\n"); text.append("\n"); text.append("\n\n"); return text.toString(); } - + } diff --git a/Task/Babylonian-spiral/JavaScript/babylonian-spiral.js b/Task/Babylonian-spiral/JavaScript/babylonian-spiral.js new file mode 100644 index 0000000000..e30ed1365f --- /dev/null +++ b/Task/Babylonian-spiral/JavaScript/babylonian-spiral.js @@ -0,0 +1,66 @@ +function babylonianSpiral(stepCount) { + const tau = 2 * Math.PI; + const squares = Array(stepCount + 1).fill(0).map((_, i) => i * i); + const points = [[0, 0], [0, 1]]; + let norm = 1; + + for (let step = 0; step < stepCount - 2; ++step) { + const previousPoint = points[points.length - 1]; + const theta = Math.atan2(previousPoint[1], previousPoint[0]); + let candidates = []; + + while (candidates.length === 0) { + norm += 1; + for (let i = 0; i < stepCount; ++i) { + const a = squares[i]; + if (a > norm / 2) break; + for (let j = Math.floor(Math.sqrt(norm)) + 1; j >= 0; --j) { + const b = squares[j]; + if (a + b < norm) break; + if (a + b === norm) { + const nextPoints = [ + [i, j], [-i, j], [i, -j], [-i, -j], + [j, i], [-j, i], [j, -i], [-j, -i] + ]; + candidates.push(...nextPoints); + } + } + } + } + + let minimum = null; + let minimumValue = tau; + for (const candidate of candidates) { + const value = (theta - Math.atan2(candidate[1], candidate[0]) + tau) % tau; + if (value < minimumValue) { + minimumValue = value; + minimum = candidate; + } + } + points.push(minimum); + } + + // Accumulate points + for (let i = 0; i < points.length - 1; ++i) { + points[i + 1] = [ + points[i][0] + points[i + 1][0], + points[i][1] + points[i + 1][1] + ]; + } + + return points; +} + +function main() { + const points = babylonianSpiral(40); + console.log("The first 40 points of the Babylonian spiral are:"); + for (let i = 0, column = 0; i < 40; ++i) { + const pointStr = `(${points[i][0]}, ${points[i][1]})`; + process.stdout.write(pointStr.padStart(10)); + if (++column % 10 === 0) { + console.log(); + } + } +} + +main(); diff --git a/Task/Babylonian-spiral/M2000-Interpreter/babylonian-spiral.m2000 b/Task/Babylonian-spiral/M2000-Interpreter/babylonian-spiral.m2000 index affe90862c..40db56f027 100644 --- a/Task/Babylonian-spiral/M2000-Interpreter/babylonian-spiral.m2000 +++ b/Task/Babylonian-spiral/M2000-Interpreter/babylonian-spiral.m2000 @@ -1,79 +1,79 @@ module Babylonian_spiral (max=40) { - declare math math - const TAU=6.283185307179586 - dim sq() - sq()=lambda (m)-> { - for i=0 to m-1:data i*i:next - =array([]) - }(max) - xydeltas=((0&, 0&), (0&, 1&)) - def isqrt(n)=val(sqrt(n)->long) - def pr(c)="("+c#str$(", ")+")" - long δsquared = 1 - - for L=0 to max-3 - (x,y)=xydeltas#val(len(xydeltas)-1) - θ = @atan2(y, x) - candidates=stack - while len(candidates)=0 - δsquared++ - for i=0& to max-1 - a=sq(i) - if a > δsquared/2& then exit for - for j =isqrt(δsquared) + 1 to 1 - b = sq(j) - if a + b < δsquared then exit for - if a + b = δsquared then - stack candidates { - Data (i, j), (-i, j), (i, -j), (-i, -j), (j, i), (-j, i), (j, -i), (-j, -i) - } - end if - next - next - end while - minimum=(,) - minVal=TAU - stack candidates { - while not empty - read candidate() - val = (θ - @atan2(candidate(1), candidate(0))) mod# TAU - if val < minVal then minVal = val : minimum = candidate() - end while - } - append xyDeltas, (minimum,) - next - for i=0 to len(xyDeltas)-2 - Return xyDeltas, i+1:=@add(xyDeltas#val(i+1), xyDeltas#val(i)) - next - Drawing 12000, 12000 { - Cls, 0 - pen 0 - (m1, m2, s1)=(6000, 6000, twipsX*10) - move m1, m2 - k=each(xyDeltas) - dim b() - while k - b()=array(k) - b=b() - b*=s1 - draw to b(0)+m1, m2-b(1): circle fill 1, 30 - end while - } as Drw - image drw - clipboard drw as "emf" - Document Doc$ - for i=0 to len(xyDeltas)-2 - Doc$=pr(xyDeltas#val(i))+", " - next - Doc$=pr(xyDeltas#val(i)) - Print Doc$ - Save.Doc Doc$, "out.txt" - function add(a(), b()) - =a(0)+b(0), a(1)+b(1) - end function - function atan2(y, x) - method math, "atan2", y, x as ret - =ret // radians - end function + declare math math + const TAU=6.283185307179586 + dim sq() + sq()=lambda (m)-> { + for i=0 to m-1:data i*i:next + =array([]) + }(max) + xydeltas=((0&, 0&), (0&, 1&)) + def isqrt(n)=val(sqrt(n)->long) + def pr(c)="("+c#str$(", ")+")" + long δsquared = 1 + + for L=0 to max-3 + (x,y)=xydeltas#val(len(xydeltas)-1) + θ = @atan2(y, x) + candidates=stack + while len(candidates)=0 + δsquared++ + for i=0& to max-1 + a=sq(i) + if a > δsquared/2& then exit for + for j =isqrt(δsquared) + 1 to 1 + b = sq(j) + if a + b < δsquared then exit for + if a + b = δsquared then + stack candidates { + Data (i, j), (-i, j), (i, -j), (-i, -j), (j, i), (-j, i), (j, -i), (-j, -i) + } + end if + next + next + end while + minimum=(,) + minVal=TAU + stack candidates { + while not empty + read candidate() + val = (θ - @atan2(candidate(1), candidate(0))) mod# TAU + if val < minVal then minVal = val : minimum = candidate() + end while + } + append xyDeltas, (minimum,) + next + for i=0 to len(xyDeltas)-2 + Return xyDeltas, i+1:=@add(xyDeltas#val(i+1), xyDeltas#val(i)) + next + Drawing 12000, 12000 { + Cls, 0 + pen 0 + (m1, m2, s1)=(6000, 6000, twipsX*10) + move m1, m2 + k=each(xyDeltas) + dim b() + while k + b()=array(k) + b=b() + b*=s1 + draw to b(0)+m1, m2-b(1): circle fill 1, 30 + end while + } as Drw + image drw + clipboard drw as "emf" + Document Doc$ + for i=0 to len(xyDeltas)-2 + Doc$=pr(xyDeltas#val(i))+", " + next + Doc$=pr(xyDeltas#val(i)) + Print Doc$ + Save.Doc Doc$, "out.txt" + function add(a(), b()) + =a(0)+b(0), a(1)+b(1) + end function + function atan2(y, x) + method math, "atan2", y, x as ret + =ret // radians + end function } Babylonian_spiral 40 diff --git a/Task/Babylonian-spiral/Rebol/babylonian-spiral.rebol b/Task/Babylonian-spiral/Rebol/babylonian-spiral.rebol new file mode 100644 index 0000000000..4e9ecb5208 --- /dev/null +++ b/Task/Babylonian-spiral/Rebol/babylonian-spiral.rebol @@ -0,0 +1,72 @@ +Rebol [ + title: "Rosetta code: Babylonian spiral" + file: %Babylonian_spiral.r3 + url: https://rosettacode.org/wiki/Babylonian_spiral +] + +babylonian-spiral: function/with [ + "Get points along a Babylonian spiral of nsteps steps." + nsteps [integer!] +][ + ;; Grow the shared square-cache if needed so index i holds i*i + if nsteps > s: length? square-cache [ + for i s nsteps 1 [ + append square-cache i * i + ] + ] + ;; Start with the origin and the first unit step along +y + output: reduce [0x0 0x1] + delta-squared: 1 + + loop nsteps - 2 [ + ;; Heading of the last delta vector, in degrees + theta: arctangent2 last output + ;; Search increasing vector lengths until at least one integer candidate is found + candidates: clear [] + while [empty? candidates] [ + ++ delta-squared + ;; Enumerate all pairs (i,j) where i²+j²=delta-squared + for i 0 (-1 + length? square-cache) 1 [ + a: pickz square-cache i + if a > delta-squared / 2 [break] ;; a <= delta-squared/2 by symmetry + j: 1 + to integer! square-root delta-squared + while [j >= 1] [ + b: square-cache/(j + 1) + if delta-squared > a + b [break] ;; j only decreases from here + if delta-squared = a + b [ + ;; Add all 8 reflections of the (i,j) solution + -i: negate i + -j: negate j + repend candidates [ + as-pair i j as-pair -i j + as-pair i -j as-pair -i -j + as-pair j i as-pair -j i + as-pair j -i as-pair -j -i + ] + ] + -- j + ] + ] + ] + ;; Pick the candidate whose heading deviates least clockwise from theta + append output first sort/compare candidates func [da db] [ + angle-a: theta - arctangent2 da + angle-b: theta - arctangent2 db + ; Wrap into [0, 360) so smallest clockwise turn sorts first + angle-a: angle-a % 360 if angle-a < 0 [angle-a: angle-a + 360] + angle-b: angle-b % 360 if angle-b < 0 [angle-b: angle-b + 360] + angle-a < angle-b + ] + ] + ;; Convert delta sequence in-place to absolute positions by cumulative summation + pos: 0x0 forall output [ change output pos: pos + output/1 ] + output +][ + ;; Persistent square-cache shared across calls, initialised empty + square-cache: clear [] +] + +; --- Main --- +print as-yellow "The first 40 points of the Babylonian spiral are:" +points: babylonian-spiral 40 +while [not empty? points][ print [TAB take/part points 10] ] diff --git a/Task/Balanced-brackets/Ada/balanced-brackets.adb b/Task/Balanced-brackets/Ada/balanced-brackets.adb new file mode 100644 index 0000000000..a5762a9580 --- /dev/null +++ b/Task/Balanced-brackets/Ada/balanced-brackets.adb @@ -0,0 +1,57 @@ +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; +with Ada.Strings.Fixed; +procedure Brackets is + package Random_Positive is new Ada.Numerics.Discrete_Random (Positive); + Positive_Generator : Random_Positive.Generator; + procedure Swap (Left, Right : in out Character) is + Temp : constant Character := Left; + begin + Left := Right; + Right := Temp; + end Swap; + function Generate_Brackets (Bracket_Count : Natural; + Opening_Bracket : Character := '['; + Closing_Bracket : Character := ']') + return String is + use Ada.Strings.Fixed; + All_Brackets : String := Bracket_Count * Opening_Bracket & Bracket_Count * Closing_Bracket; + begin + for I in All_Brackets'Range loop + Swap (All_Brackets (I), All_Brackets (Random_Positive.Random (Positive_Generator) mod (Bracket_Count * 2) + 1)); + end loop; + return All_Brackets; + end Generate_Brackets; + + function Check_Brackets (Test : String; + Opening_Bracket : Character := '['; + Closing_Bracket : Character := ']') + return Boolean is + Open : Natural := 0; + begin + for I in Test'Range loop + if Test (I) = Opening_Bracket then + Open := Open + 1; + elsif Test (I) = Closing_Bracket then + if Open = 0 then + return False; + else + Open := Open - 1; + end if; + end if; + end loop; + return True; + end Check_Brackets; +begin + Random_Positive.Reset (Positive_Generator); + Ada.Text_IO.Put_Line ("Brackets"); + for I in 0 .. 4 loop + for J in 0 .. I loop + declare + My_String : constant String := Generate_Brackets (I); + begin + Ada.Text_IO.Put_Line (My_String & ": " & Boolean'Image (Check_Brackets (My_String))); + end; + end loop; + end loop; +end Brackets; diff --git a/Task/Balanced-brackets/AutoIt/balanced-brackets.au3 b/Task/Balanced-brackets/AutoIt/balanced-brackets.au3 new file mode 100644 index 0000000000..9e2aa93920 --- /dev/null +++ b/Task/Balanced-brackets/AutoIt/balanced-brackets.au3 @@ -0,0 +1,28 @@ +#include +Local $Array[1] +_ArrayAdd($Array, "[]") +_ArrayAdd($Array, "[][]") +_ArrayAdd($Array, "[[][]]") +_ArrayAdd($Array, "][") +_ArrayAdd($Array, "][][") +_ArrayAdd($Array, "[]][[]") + +For $i = 0 To UBound($Array) -1 + Balanced_Brackets($Array[$i]) + If @error Then + ConsoleWrite($Array[$i] &" = NOT OK"&@CRLF) + Else + ConsoleWrite($Array[$i] &" = OK"&@CRLF) + EndIf +Next + +Func Balanced_Brackets($String) + Local $cnt = 0 + $Split = Stringsplit($String, "") + For $i = 1 To $Split[0] + If $split[$i] = "[" Then $cnt += 1 + If $split[$i] = "]" Then $cnt -= 1 + If $cnt < 0 Then Return SetError(1,0,0) + Next + Return 1 +EndFunc diff --git a/Task/Balanced-brackets/AutoLISP/balanced-brackets.lsp b/Task/Balanced-brackets/AutoLISP/balanced-brackets.lsp new file mode 100644 index 0000000000..90ed32a229 --- /dev/null +++ b/Task/Balanced-brackets/AutoLISP/balanced-brackets.lsp @@ -0,0 +1,12 @@ +(defun BalancedBrackets (str / cntOpen curr) + (setq cntOpen 0) + (setq str (vl-string->list str)) + (while (and (>= cntOpen 0) str) + (setq curr (car str) str (cdr str)) + (cond + ((= 91 curr) (setq cntOpen (1+ cntOpen))) + ((= 93 curr) (setq cntOpen (1- cntOpen))) + ) + ) + (and (null str) (zerop cntOpen)) +) diff --git a/Task/Balanced-brackets/COBOL/balanced-brackets.cob b/Task/Balanced-brackets/COBOL/balanced-brackets.cob new file mode 100644 index 0000000000..2eefa88ef6 --- /dev/null +++ b/Task/Balanced-brackets/COBOL/balanced-brackets.cob @@ -0,0 +1,98 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. test-balanced-brackets. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 True-Val CONSTANT 0. + 01 False-Val CONSTANT 1. + + LOCAL-STORAGE SECTION. + 01 current-time PIC 9(10). + + 01 bracket-type PIC 9. + 88 add-open-bracket VALUE 1. + + 01 bracket-string-area. + 03 bracket-string PIC X(10) OCCURS 10 TIMES. + + 01 i PIC 999. + 01 j PIC 999. + + PROCEDURE DIVISION. + *> Seed RANDOM(). + MOVE FUNCTION CURRENT-DATE (7:10) TO current-time + MOVE FUNCTION RANDOM(current-time) TO current-time + + + *> Generate random strings of brackets. + PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i + PERFORM VARYING j FROM 1 BY 1 UNTIL i < j + COMPUTE bracket-type = + FUNCTION REM(FUNCTION RANDOM * 1000, 2) + + IF add-open-bracket + MOVE "[" TO bracket-string (i) (j:1) + ELSE + MOVE "]" TO bracket-string (i) (j:1) + END-IF + END-PERFORM + END-PERFORM + + *> Display if the strings are balanced or not. + PERFORM VARYING i FROM 1 BY 1 UNTIL 10 < i + CALL "check-if-balanced" USING bracket-string (i) + IF RETURN-CODE = True-Val + DISPLAY FUNCTION TRIM(bracket-string (i)) + " is balanced." + ELSE + DISPLAY FUNCTION TRIM(bracket-string (i)) + " is not balanced." + END-IF + END-PERFORM + + GOBACK + . + + END PROGRAM test-balanced-brackets. + + IDENTIFICATION DIVISION. + PROGRAM-ID. check-if-balanced. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 True-Val CONSTANT 0. + 01 False-Val CONSTANT 1. + + LOCAL-STORAGE SECTION. + 01 nesting-level PIC S999. + 01 i PIC 999. + + LINKAGE SECTION. + 01 bracket-string PIC X(100). + + PROCEDURE DIVISION USING bracket-string. + PERFORM VARYING i FROM 1 BY 1 + UNTIL (100 < i) + OR (bracket-string (i:1) = SPACE) + OR (nesting-level < 0) + IF bracket-string (i:1) = "[" + ADD 1 TO nesting-level + ELSE + SUBTRACT 1 FROM nesting-level + IF nesting-level < 0 + MOVE False-Val TO RETURN-CODE + GOBACK + END-IF + END-IF + END-PERFORM + + IF nesting-level = 0 + MOVE True-Val TO RETURN-CODE + ELSE + MOVE False-Val TO RETURN-CODE + END-IF + + GOBACK + . + + END PROGRAM check-if-balanced. diff --git a/Task/Balanced-brackets/Euphoria/balanced-brackets.eu b/Task/Balanced-brackets/Euphoria/balanced-brackets.eu new file mode 100644 index 0000000000..186ecbdb66 --- /dev/null +++ b/Task/Balanced-brackets/Euphoria/balanced-brackets.eu @@ -0,0 +1,45 @@ +function check_brackets(sequence s) + integer level + level = 0 + for i = 1 to length(s) do + if s[i] = '[' then + level += 1 + elsif s[i] = ']' then + level -= 1 + if level < 0 then + return 0 + end if + end if + end for + return level = 0 +end function + +function generate_brackets(integer n) + integer opened,closed,r + sequence s + opened = n + closed = n + s = "" + for i = 1 to n*2 do + r = rand(opened+closed) + if r<=opened then + s &= '[' + opened -= 1 + else + s &= ']' + closed -= 1 + end if + end for + return s +end function + +sequence s +for i = 1 to 10 do + s = generate_brackets(3) + puts(1,s) + if check_brackets(s) then + puts(1," OK\n") + else + puts(1," NOT OK\n") + end if +end for diff --git a/Task/Balanced-brackets/PowerShell/balanced-brackets-1.ps1 b/Task/Balanced-brackets/PowerShell/balanced-brackets-1.ps1 new file mode 100644 index 0000000000..1ab6ded8d1 --- /dev/null +++ b/Task/Balanced-brackets/PowerShell/balanced-brackets-1.ps1 @@ -0,0 +1,18 @@ +function Get-BalanceStatus ( $String ) + { + $Open = 0 + ForEach ( $Character in [char[]]$String ) + { + switch ( $Character ) + { + "[" { $Open++ } + "]" { $Open-- } + default { $Open = -1 } + } + # If Open drops below zero (close before open or non-allowed character) + # Exit loop + If ( $Open -lt 0 ) { Break } + } + $Status = ( "NOT OK", "OK" )[( $Open -eq 0 )] + return $Status + } diff --git a/Task/Balanced-brackets/PowerShell/balanced-brackets-2.ps1 b/Task/Balanced-brackets/PowerShell/balanced-brackets-2.ps1 new file mode 100644 index 0000000000..733e1c50e7 --- /dev/null +++ b/Task/Balanced-brackets/PowerShell/balanced-brackets-2.ps1 @@ -0,0 +1,8 @@ +# Test +$Strings = @( "" ) +$Strings += 1..5 | ForEach { ( [char[]]("[]" * $_) | Get-Random -Count ( $_ * 2 ) ) -join "" } + +ForEach ( $String in $Strings ) + { + $String.PadRight( 12, " " ) + (Get-BalanceStatus $String) + } diff --git a/Task/Balanced-brackets/PowerShell/balanced-brackets-3.ps1 b/Task/Balanced-brackets/PowerShell/balanced-brackets-3.ps1 new file mode 100644 index 0000000000..35184e8424 --- /dev/null +++ b/Task/Balanced-brackets/PowerShell/balanced-brackets-3.ps1 @@ -0,0 +1,57 @@ +function Test-BalancedBracket +{ + <# + .SYNOPSIS + Tests a string for balanced brackets. + .DESCRIPTION + Tests a string for balanced brackets. ("<>", "[]", "{}" or "()") + .EXAMPLE + Test-BalancedBracket -Bracket Brace -String '{abc(def[0]).xyz}' + Test a string for balanced braces. + .EXAMPLE + Test-BalancedBracket -Bracket Curly -String '{abc(def[0]).xyz}' + Test a string for balanced curly braces. + .EXAMPLE + Test-BalancedBracket -Bracket Curly -String ([System.IO.File]::ReadAllText('.\Foo.ps1')) + Test a file for balanced curly braces. + .LINK + http://go.microsoft.com/fwlink/?LinkId=133231 + #> + [CmdletBinding()] + [OutputType([bool])] + Param + ( + [Parameter(Mandatory=$true)] + [ValidateSet("Angle", "Brace", "Curly", "Paren")] + [string] + $Bracket, + + [Parameter(Mandatory=$true)] + [AllowEmptyString()] + [string] + $String + ) + + $notFound = -1 + + $brackets = @{ + Angle = @{Left="<"; Right=">"; Regex="^[^<>]*(?>(?>(?'pair'\<)[^<>]*)+(?>(?'-pair'\>)[^<>]*)+)+(?(pair)(?!))$"} + Brace = @{Left="["; Right="]"; Regex="^[^\[\]]*(?>(?>(?'pair'\[)[^\[\]]*)+(?>(?'-pair'\])[^\[\]]*)+)+(?(pair)(?!))$"} + Curly = @{Left="{"; Right="}"; Regex="^[^{}]*(?>(?>(?'pair'\{)[^{}]*)+(?>(?'-pair'\})[^{}]*)+)+(?(pair)(?!))$"} + Paren = @{Left="("; Right=")"; Regex="^[^()]*(?>(?>(?'pair'\()[^()]*)+(?>(?'-pair'\))[^()]*)+)+(?(pair)(?!))$"} + } + + if ($String.IndexOf($brackets.$Bracket.Left) -eq $notFound -and + $String.IndexOf($brackets.$Bracket.Right) -eq $notFound -or $String -eq [String]::Empty) + { + return $true + } + + $String -match $brackets.$Bracket.Regex +} + + +'', '[]', '][', '[][]', '][][', '[[][]]', '[]][[]' | ForEach-Object { + if ($_ -eq "") { $s = "(Empty)" } else { $s = $_ } + "{0}: {1}" -f $s.PadRight(8), "$(if (Test-BalancedBracket Brace $s) {'Is balanced.'} else {'Is not balanced.'})" +} diff --git a/Task/Balanced-brackets/Rebol/balanced-brackets.rebol b/Task/Balanced-brackets/Rebol/balanced-brackets.rebol new file mode 100644 index 0000000000..63f0bd4e48 --- /dev/null +++ b/Task/Balanced-brackets/Rebol/balanced-brackets.rebol @@ -0,0 +1,21 @@ +Rebol [ + title: "Rosetta code: Balanced brackets" + file: %Balanced_brackets.r3 + url: https://rosettacode.org/wiki/Balanced_brackets +] + +;; Returns TRUE if all square brackets in `str` are properly nested and balanced +balanced?: function/with [str][parse str rule][ + ;; Recursive rule: a balanced group is [ followed by any nested balanced groups, then ] + balanced-brackets: [#"[" any balanced-brackets #"]"] + ;; Full string must consist entirely of balanced groups with nothing left over + rule: [any balanced-brackets end] +] + +;; Test: generate 10 random substrings of bracket pairs and check each +random/seed 2 +repeat i 10 [ + str: random copy/part "[][][][][][][][][][]" i * 2 ;; shuffle first i*2 chars + res: pick ["balanced" "unbalanced"] balanced? str ;; label the result + printf [-2 ". " 11] reduce [i res mold str] ;; print index, verdict, string +] diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets-1.vbs b/Task/Balanced-brackets/VBScript/balanced-brackets-1.vbs new file mode 100644 index 0000000000..d271076d80 --- /dev/null +++ b/Task/Balanced-brackets/VBScript/balanced-brackets-1.vbs @@ -0,0 +1,36 @@ +For n = 1 To 10 + sequence = Generate_Sequence(n) + WScript.Echo sequence & " is " & Check_Balance(sequence) & "." +Next + +Function Generate_Sequence(n) + For i = 1 To n + j = Round(Rnd()) + If j = 0 Then + Generate_Sequence = Generate_Sequence & "[" + Else + Generate_Sequence = Generate_Sequence & "]" + End If + Next +End Function + +Function Check_Balance(s) + Set Stack = CreateObject("System.Collections.Stack") + For i = 1 To Len(s) + char = Mid(s,i,1) + If i = 1 Or char = "[" Then + Stack.Push(char) + ElseIf Stack.Count <> 0 Then + If char = "]" And Stack.Peek = "[" Then + Stack.Pop + End If + Else + Stack.Push(char) + End If + Next + If Stack.Count > 0 Then + Check_Balance = "Not Balanced" + Else + Check_Balance = "Balanced" + End If +End Function diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets-2.vbs b/Task/Balanced-brackets/VBScript/balanced-brackets-2.vbs new file mode 100644 index 0000000000..674efc6e13 --- /dev/null +++ b/Task/Balanced-brackets/VBScript/balanced-brackets-2.vbs @@ -0,0 +1,40 @@ +option explicit + +function do_brackets(bal) + dim s,i,cnt,r + if bal then s="[":cnt=1 else s="":cnt=0 + for i=1 to 20 + if (rnd>0.7) then r=not r + if not r then + s=s+"[" :cnt=cnt+1 + else + if not bal or (bal and cnt>0) then s=s+"]":cnt=cnt-1 + end if + next + if bal and cnt<>0 then s=s&string(cnt,"]") + if not bal and cnt=0 then s=s&"]" + do_brackets=s +end function + +function isbalanced(s) + dim s1,i,cnt: cnt=0 + for i=1 to len(s) + s1=mid(s,i,1) + if s1="[" then cnt=cnt+1 + if s1="]" then cnt=cnt-1 + if cnt<0 then isbalanced=false:exit function + next + isbalanced=(cnt=0) +end function + +function iif(a,b,c): if a then iif=b else iif=c end if : end function + +randomize timer +dim i,s,bal,bb +for i=1 to 10 + bal=(rnd>.5) + s=do_brackets(bal) + bb=isbalanced(s) + wscript.echo iif (bal,"","un")& "balanced string " &vbtab _ + & s & vbtab & " Checks as " & iif(bb,"","un")&"balanced" +next diff --git a/Task/Balanced-ternary/Ada/balanced-ternary-1.adb b/Task/Balanced-ternary/Ada/balanced-ternary-1.adb new file mode 100644 index 0000000000..dd4c353d57 --- /dev/null +++ b/Task/Balanced-ternary/Ada/balanced-ternary-1.adb @@ -0,0 +1,47 @@ +with Ada.Finalization; + +package BT is + + type Balanced_Ternary is private; + + -- conversions + function To_Balanced_Ternary (Num : Integer) return Balanced_Ternary; + function To_Balanced_Ternary (Str : String) return Balanced_Ternary; + function To_Integer (Num : Balanced_Ternary) return Integer; + function To_string (Num : Balanced_Ternary) return String; + + -- Arithmetics + -- unary minus + function "-" (Left : in Balanced_Ternary) + return Balanced_Ternary; + + -- subtraction + function "-" (Left, Right : in Balanced_Ternary) + return Balanced_Ternary; + + -- addition + function "+" (Left, Right : in Balanced_Ternary) + return Balanced_Ternary; + -- multiplication + function "*" (Left, Right : in Balanced_Ternary) + return Balanced_Ternary; + +private + -- a balanced ternary number is a unconstrained array of (1,0,-1) + -- dinamically allocated, least significant trit leftmost + type Trit is range -1..1; + type Trit_Array is array (Positive range <>) of Trit; + pragma Pack(Trit_Array); + + type Trit_Access is access Trit_Array; + + type Balanced_Ternary is new Ada.Finalization.Controlled + with record + Ref : Trit_access; + end record; + + procedure Initialize (Object : in out Balanced_Ternary); + procedure Adjust (Object : in out Balanced_Ternary); + procedure Finalize (Object : in out Balanced_Ternary); + +end BT; diff --git a/Task/Balanced-ternary/Ada/balanced-ternary-2.adb b/Task/Balanced-ternary/Ada/balanced-ternary-2.adb new file mode 100644 index 0000000000..dd743e2dec --- /dev/null +++ b/Task/Balanced-ternary/Ada/balanced-ternary-2.adb @@ -0,0 +1,181 @@ +with Ada.Unchecked_Deallocation; + +package body BT is + + procedure Free is new Ada.Unchecked_Deallocation (Trit_Array, Trit_Access); + + -- Conversions + -- String to BT + function To_Balanced_Ternary (Str: String) return Balanced_Ternary is + J : Positive := 1; + Tmp : Trit_Access; + begin + Tmp := new Trit_Array (1..Str'Last); + for I in reverse Str'Range loop + case Str(I) is + when '+' => Tmp (J) := 1; + when '-' => Tmp (J) := -1; + when '0' => Tmp (J) := 0; + when others => raise Constraint_Error; + end case; + J := J + 1; + end loop; + return (Ada.Finalization.Controlled with Ref => Tmp); + end To_Balanced_Ternary; + + -- Integer to BT + function To_Balanced_Ternary (Num: Integer) return Balanced_Ternary is + K : Integer := 0; + D : Integer; + Value : Integer := Num; + Tmp : Trit_Array(1..19); -- 19 trits is enough to contain + -- a 32 bits signed integer + begin + loop + D := (Value mod 3**(K+1))/3**K; + if D = 2 then D := -1; end if; + Value := Value - D*3**K; + K := K + 1; + Tmp(K) := Trit(D); + exit when Value = 0; + end loop; + return (Ada.Finalization.Controlled + with Ref => new Trit_Array'(Tmp(1..K))); + end To_Balanced_Ternary; + + -- BT to Integer -- + -- If the BT number is too large Ada will raise CONSTRAINT ERROR + function To_Integer (Num : Balanced_Ternary) return Integer is + Value : Integer := 0; + Pos : Integer := 1; + begin + for I in Num.Ref.all'Range loop + Value := Value + Integer(Num.Ref(I)) * Pos; + Pos := Pos * 3; + end loop; + return Value; + end To_Integer; + + -- BT to String -- + function To_String (Num : Balanced_Ternary) return String is + I : constant Integer := Num.Ref.all'Last; + Result : String (1..I); + begin + for J in Result'Range loop + case Num.Ref(I-J+1) is + when 0 => Result(J) := '0'; + when -1 => Result(J) := '-'; + when 1 => Result(J) := '+'; + end case; + end loop; + return Result; + end To_String; + + -- unary minus -- + function "-" (Left : in Balanced_Ternary) + return Balanced_Ternary is + Result : constant Balanced_Ternary := Left; + begin + for I in Result.Ref.all'Range loop + Result.Ref(I) := - Result.Ref(I); + end loop; + return Result; + end "-"; + + -- addition -- + Carry : Trit; + + function Add (Left, Right : in Trit) + return Trit is + begin + if Left /= Right then + Carry := 0; + return Left + Right; + else + Carry := Left; + return -Right; + end if; + end Add; + pragma Inline (Add); + + function "+" (Left, Right : in Trit_Array) + return Balanced_Ternary is + Max_Size : constant Integer := + Integer'Max(Left'Last, Right'Last); + Tmp_Left, Tmp_Right : Trit_Array(1..Max_Size) := (others => 0); + Result : Trit_Array(1..Max_Size+1) := (others => 0); + begin + Tmp_Left (1..Left'Last) := Left; + Tmp_Right(1..Right'Last) := Right; + for I in Tmp_Left'Range loop + Result(I) := Add (Result(I), Tmp_Left(I)); + Result(I+1) := Carry; + Result(I) := Add(Result(I), Tmp_Right(I)); + Result(I+1) := Add(Result(I+1), Carry); + end loop; + -- remove trailing zeros + for I in reverse Result'Range loop + if Result(I) /= 0 then + return (Ada.Finalization.Controlled + with Ref => new Trit_Array'(Result(1..I))); + end if; + end loop; + return (Ada.Finalization.Controlled + with Ref => new Trit_Array'(1 => 0)); + end "+"; + + function "+" (Left, Right : in Balanced_Ternary) + return Balanced_Ternary is + begin + return Left.Ref.all + Right.Ref.all; + end "+"; + + -- Subtraction + function "-" (Left, Right : in Balanced_Ternary) + return Balanced_Ternary is + begin + return Left + (-Right); + end "-"; + + -- multiplication + function "*" (Left, Right : in Balanced_Ternary) + return Balanced_Ternary is + A, B : Trit_Access; + Result : Balanced_Ternary; + begin + if Left.Ref.all'Length > Right.Ref.all'Length then + A := Right.Ref; B := Left.Ref; + else + B := Right.Ref; A := Left.Ref; + end if; + for I in A.all'Range loop + if A(I) /= 0 then + declare + Tmp_Result : Trit_Array (1..I+B.all'Length-1) := (others => 0); + begin + for J in B.all'Range loop + Tmp_Result(I+J-1) := B(J) * A(I); + end loop; + Result := Result.Ref.all + Tmp_Result; + end; + end if; + end loop; + return Result; + end "*"; + + procedure Adjust (Object : in out Balanced_Ternary) is + begin + Object.Ref := new Trit_Array'(Object.Ref.all); + end Adjust; + + procedure Finalize (Object : in out Balanced_Ternary) is + begin + Free (Object.Ref); + end Finalize; + + procedure Initialize (Object : in out Balanced_Ternary) is + begin + Object.Ref := new Trit_Array'(1 => 0); + end Initialize; + +end BT; diff --git a/Task/Balanced-ternary/Ada/balanced-ternary-3.adb b/Task/Balanced-ternary/Ada/balanced-ternary-3.adb new file mode 100644 index 0000000000..309de4f858 --- /dev/null +++ b/Task/Balanced-ternary/Ada/balanced-ternary-3.adb @@ -0,0 +1,19 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; +with BT; use BT; + +procedure TestBT is + Result, A, B, C : Balanced_Ternary; +begin + A := To_Balanced_Ternary("+-0++0+"); + B := To_Balanced_Ternary(-436); + C := To_Balanced_Ternary("+-++-"); + + Result := A * (B - C); + + Put("a = "); Put(To_integer(A), 4); New_Line; + Put("b = "); Put(To_integer(B), 4); New_Line; + Put("c = "); Put(To_integer(C), 4); New_Line; + Put("a * (b - c) = "); Put(To_integer(Result), 4); + Put_Line (" " & To_String(Result)); +end TestBT; diff --git a/Task/Balanced-ternary/Quackery/balanced-ternary.quackery b/Task/Balanced-ternary/Quackery/balanced-ternary.quackery new file mode 100644 index 0000000000..f28cf0fdc1 --- /dev/null +++ b/Task/Balanced-ternary/Quackery/balanced-ternary.quackery @@ -0,0 +1,79 @@ + [ -1 1 clamp 1+ ]'[ swap peek do ] is sif ( n --> ) + + [ $ "" swap witheach + [ sif [ char - char 0 char + ] + swap join ] ] is t->$ ( t --> ) + + [ [] swap witheach + [ char - - sif [ 1 -1 0 ] + swap join ] ] is $->t ( $ --> t ) + + [ 0 swap reverse witheach [ swap 3 * + ] ] is t->n ( $ --> t ) + + [ [] swap + [ 3 /mod [ table 0 1 [ 1+ -1 ] ] do + swap dip join dup 0 = until ] + drop ] is n->t ( n --> t ) + + [ -1 peek ] is tsign ( t --> n ) + + [ ' [ 0 ] = ] is tzero ( t --> b ) + + [ tsign -1 = ] is tneg ( t --> b ) + + [ tsign 1 = ] is tpos ( t --> b ) + + [ [] swap witheach [ negate join ] ] is -t ( t --> t ) + + [ 0 over size times + [ 1 - 2dup peek if conclude ] + 1+ dup if split drop ] is tnorm ( t --> t ) + + [ [] 0 2swap + over size over size - dup 0 < + if [ dip swap negate ] + 0 swap of join temp put + witheach + [ temp share i^ peek + + + 3 + + [ table + [ 0 -1 ] [ 1 -1 ] [ -1 0 ] + [ 0 0 ] [ 1 0 ] [ -1 1 ] + [ 0 1 ] ] do + dip join ] + join tnorm + temp release ] is t+ ( t t --> t ) + + [ -t t+ ] is t- ( t t --> t ) + + [ t- tneg ] is t< ( t t --> b ) + + [ t- tpos ] is t> ( t t --> b ) + + [ behead swap witheach + [ 2dup t> if swap + drop ] ] is tmin ( [ --> t ) + + [ behead swap witheach + [ 2dup t< if swap + drop ] ] is tmax ( [ --> t ) + + [ dup t+ ] is twice ( t --> t ) + + [ 0 swap join ] is thrice ( t --> t ) + + [ ' [ 0 ] swap witheach + [ dip over + sif [ t- drop t+ ] + dip thrice ] + nip ] is t* ( t t --> t ) + + say "a: " $ "+-0++0+" dup echo$ say " = " $->t t->n echo cr + say "b: " -436 dup echo say " = " n->t t->$ echo$ cr + say "c: " $ "+-++-" dup echo$ say " = " $->t t->n echo cr + say "a*(b-c): = " + $ "+-0++0+" $->t + -436 n->t + $ "+-++-" $->t + t- t* + dup t->$ echo$ say " = " t->n echo cr diff --git a/Task/Balanced-ternary/R/balanced-ternary.r b/Task/Balanced-ternary/R/balanced-ternary.r new file mode 100644 index 0000000000..2c8f76dd35 --- /dev/null +++ b/Task/Balanced-ternary/R/balanced-ternary.r @@ -0,0 +1,138 @@ +## BalancedTernary in R (S3) + +## Constructor helpers ---- +new_BalancedTernary <- function(digits) { + # digits are least-significant first, values in {-1,0,1} + structure(list(digits = as.integer(digits)), class = "BalancedTernary") +} + +BalancedTernary <- function(x = 0L) { + if (inherits(x, "BalancedTernary")) return(x) + if (is.character(x)) return(BalancedTernary_from_string(x)) + if (length(x) != 1 || !is.finite(x)) stop("BalancedTernary: need a single finite number or a string.") + BalancedTernary_from_int(as.integer(x)) +} + +BalancedTernary_zero <- function() new_BalancedTernary(0L) + +## Conversions ---- +BalancedTernary_from_int <- function(n) { + n <- as.integer(n) + if (n == 0L) return(new_BalancedTernary(0L)) + digs <- integer(0) + while (n != 0L) { + r <- n %% 3L + if (r == 0L) { + digs <- c(digs, 0L); n <- n %/% 3L + } else if (r == 1L) { + digs <- c(digs, 1L); n <- n %/% 3L + } else { # r == 2 -> digit -1 and carry +1 (i.e., add 1 then divide) + digs <- c(digs, -1L); n <- (n + 1L) %/% 3L + } + } + new_BalancedTernary(digs) +} + +BalancedTernary_from_string <- function(s) { + # string is most-significant first with '-', '0', '+' + map <- c("-" = -1L, "0" = 0L, "+" = 1L) + chs <- strsplit(s, "", fixed = TRUE)[[1]] + if (!all(chs %in% names(map))) stop("String may only contain '-', '0', '+'.") + # reverse to least-significant first + new_BalancedTernary(unname(map[rev(chs)])) +} + +bt <- function(s) BalancedTernary_from_string(s) # macro-ish convenience + +## Printing & coercion ---- +print.BalancedTernary <- function(x, ...) { + cat(as.character(x), "\n", sep = "") + invisible(x) +} + +as.character.BalancedTernary <- function(x, ...) { + map <- c(`-1` = "-", `0` = "0", `1` = "+") + # display most-significant first + paste0(rev(map[as.character(x$digits)]), collapse = "") +} + +as.integer.BalancedTernary <- function(x, ...) { + s <- x$digits + if (length(s) == 1L && s[1] == 0L) return(0L) + ex <- seq_along(s) - 1L + # use double accumulate then coerce to integer (safe for moderate sizes) + val <- sum((3 ^ ex) * s) + as.integer(val) +} + +## Unary minus ---- +`-.BalancedTernary` <- function(e1) new_BalancedTernary(-e1$digits) + +## Core arithmetic helpers ---- +# Addition table for (a1 + b1 + c) -> (digit, carry), +# indexed by 4 + a1 + b1 + c where a1,b1,c in {-1,0,1} gives 1..7 +.bt_table_digit <- c( 0, 1, -1, 0, 1, -1, 0) # d +.bt_table_carry <- c(-1, -1, 0, 0, 0, 1, 1) # c + +.bt_add <- function(a, b, c = 0L) { + # a,b are integer vectors of digits (LSB first) in {-1,0,1} + if (length(a) == 0L || length(b) == 0L) { + if (c == 0L) return(if (length(a) == 0L) b else a) + return(.bt_add(c(c), if (length(a) == 0L) b else a)) + } else { + a1 <- a[1]; b1 <- b[1] + idx <- 4L + a1 + b1 + c + d <- .bt_table_digit[idx] + c2 <- .bt_table_carry[idx] + r <- .bt_add(a[-1], b[-1], c2) + if (length(r) != 0L || d != 0L) { + return(c(d, r)) # unshift + } else { + return(r) + } + } +} + +.bt_mul <- function(a, b) { + # schoolbook recursion with balanced digits + if (length(a) == 0L || length(b) == 0L) return(integer(0)) + a1 <- a[1] + if (a1 == -1L) x <- (-BalancedTernary(new_BalancedTernary(b)))$digits + else if (a1 == 0L) x <- integer(0) + else if (a1 == 1L) x <- b + # shift (multiply by 3) = prepend a 0 digit to recursive product + y <- c(0L, .bt_mul(a[-1], b)) + .bt_add(x, y) +} + +.normalize_zero <- function(v) if (length(v) == 0L) 0L else v + +## Binary operators ---- +`+.BalancedTernary` <- function(e1, e2) { + v <- .bt_add(e1$digits, e2$digits) + new_BalancedTernary(.normalize_zero(v)) +} + +`-.BalancedTernary` # already defined (unary) + +`%minus_bt%` <- function(a, b) a + (-b) # internal helper if needed + +`*.BalancedTernary` <- function(e1, e2) { + v <- .bt_mul(e1$digits, e2$digits) + new_BalancedTernary(.normalize_zero(v)) +} + +## Demo / tests ---- +a <- bt("+-0++0+") +cat("a: ", as.integer(a), ", ", as.character(a), "\n", sep = "") + +b <- BalancedTernary(-436L) +cat("b: ", as.integer(b), ", ", as.character(b), "\n", sep = "") + +c <- BalancedTernary("+-++-") +cat("c: ", as.integer(c), ", ", as.character(c), "\n", sep = "") + +r <- a * (b + (-c)) # a * (b - c) +cat("a * (b - c): ", as.integer(r), ", ", as.character(r), "\n", sep = "") + +stopifnot(as.integer(r) == as.integer(a) * (as.integer(b) - as.integer(c))) diff --git a/Task/Balanced-ternary/Zig/balanced-ternary.zig b/Task/Balanced-ternary/Zig/balanced-ternary.zig new file mode 100644 index 0000000000..cf7423ff0a --- /dev/null +++ b/Task/Balanced-ternary/Zig/balanced-ternary.zig @@ -0,0 +1,297 @@ +const std = @import("std"); +const ArrayList = std.ArrayList; +const Allocator = std.mem.Allocator; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const stdout = std.io.getStdOut().writer(); + + var a = try BalancedTernary.fromString(allocator, "+-0++0+"); + defer a.deinit(); + const a_val = try a.toI128(); + const a_str = try a.toString(allocator); + defer allocator.free(a_str); + try stdout.print("a = {s} = {d}\n", .{ a_str, a_val }); + + var b = try BalancedTernary.fromI128(allocator, -436); + defer b.deinit(); + const b_val = try b.toI128(); + const b_str = try b.toString(allocator); + defer allocator.free(b_str); + try stdout.print("b = {s} = {d}\n", .{ b_str, b_val }); + + var c = try BalancedTernary.fromString(allocator, "+-++-"); + defer c.deinit(); + const c_val = try c.toI128(); + const c_str = try c.toString(allocator); + defer allocator.free(c_str); + try stdout.print("c = {s} = {d}\n", .{ c_str, c_val }); + + var c_neg = try c.clone(allocator); + defer c_neg.deinit(); + c_neg.negate(); + + var b_plus_neg_c = try b.add(allocator, c_neg); + defer b_plus_neg_c.deinit(); + + var d = try a.mul(allocator, b_plus_neg_c); + defer d.deinit(); + const d_val = try d.toI128(); + const d_str = try d.toString(allocator); + defer allocator.free(d_str); + try stdout.print("a * (b - c) = {s} = {d}\n", .{ d_str, d_val }); + + var e = try BalancedTernary.fromString(allocator, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + defer e.deinit(); + const e_result = e.toI128(); + try std.testing.expect(e_result == error.Overflow); +} + +const Trit = enum { + Zero, + Pos, + Neg, + + fn fromChar(c: u8) !Trit { + return switch (c) { + '0' => .Zero, + '+' => .Pos, + '-' => .Neg, + else => error.InvalidCharacter, + }; + } + + fn toChar(self: Trit) u8 { + return switch (self) { + .Zero => '0', + .Pos => '+', + .Neg => '-', + }; + } + + fn add(self: Trit, rhs: Trit) struct { carry: Trit, current: Trit } { + return switch (self) { + .Zero => .{ .carry = .Zero, .current = rhs }, + .Pos => switch (rhs) { + .Zero => .{ .carry = .Zero, .current = .Pos }, + .Neg => .{ .carry = .Zero, .current = .Zero }, + .Pos => .{ .carry = .Pos, .current = .Neg }, + }, + .Neg => switch (rhs) { + .Zero => .{ .carry = .Zero, .current = .Neg }, + .Pos => .{ .carry = .Zero, .current = .Zero }, + .Neg => .{ .carry = .Neg, .current = .Pos }, + }, + }; + } + + fn mul(self: Trit, rhs: Trit) Trit { + return switch (self) { + .Zero => .Zero, + .Pos => switch (rhs) { + .Zero => .Zero, + .Pos => .Pos, + .Neg => .Neg, + }, + .Neg => switch (rhs) { + .Zero => .Zero, + .Pos => .Neg, + .Neg => .Pos, + }, + }; + } + + fn negate(self: Trit) Trit { + return switch (self) { + .Zero => .Zero, + .Pos => .Neg, + .Neg => .Pos, + }; + } +}; + +const BalancedTernary = struct { + digits: ArrayList(Trit), + + fn deinit(self: *BalancedTernary) void { + self.digits.deinit(); + } + + fn clone(self: BalancedTernary, allocator: Allocator) !BalancedTernary { + var new_digits = try ArrayList(Trit).initCapacity(allocator, self.digits.items.len); + try new_digits.appendSlice(self.digits.items); + return BalancedTernary{ .digits = new_digits }; + } + + fn fromString(allocator: Allocator, s: []const u8) !BalancedTernary { + var digits = ArrayList(Trit).init(allocator); + errdefer digits.deinit(); + + var i: usize = s.len; + while (i > 0) { + i -= 1; + const trit = try Trit.fromChar(s[i]); + try digits.append(trit); + } + + return BalancedTernary{ .digits = digits }; + } + + fn fromI128(allocator: Allocator, x: i128) !BalancedTernary { + var digits = ArrayList(Trit).init(allocator); + errdefer digits.deinit(); + + var curr = x; + + while (true) { + const rem = @rem(curr, 3); + + const trit: Trit = switch (rem) { + 0 => .Zero, + 1, -2 => .Pos, + 2, -1 => .Neg, + else => unreachable, + }; + try digits.append(trit); + + const offset = @as(i128, @intFromFloat(@round(@as(f64, @floatFromInt(rem)) / 3.0))); + curr = @divTrunc(curr, 3) + offset; + + if (curr == 0) break; + } + + return BalancedTernary{ .digits = digits }; + } + + fn toString(self: BalancedTernary, allocator: Allocator) ![]const u8 { + var result = try ArrayList(u8).initCapacity(allocator, self.digits.items.len); + defer result.deinit(); + + var i: usize = self.digits.items.len; + while (i > 0) { + i -= 1; + try result.append(self.digits.items[i].toChar()); + } + + return result.toOwnedSlice(); + } + + fn toI128(self: BalancedTernary) !i128 { + var acc: i128 = 0; + + for (self.digits.items, 0..) |trit, i| { + const index: u32 = std.math.cast(u32, i) orelse return error.Overflow; + + switch (trit) { + .Zero => {}, + .Pos => { + const power = std.math.powi(i128, 3, index) catch return error.Overflow; + acc = std.math.add(i128, acc, power) catch return error.Overflow; + }, + .Neg => { + const power = std.math.powi(i128, 3, index) catch return error.Overflow; + acc = std.math.sub(i128, acc, power) catch return error.Overflow; + }, + } + } + + return acc; + } + + fn trim(digits: *ArrayList(Trit)) void { + while (digits.items.len > 0) { + const last = digits.items[digits.items.len - 1]; + if (last != .Zero) { + break; + } + _ = digits.pop(); + } + } + + fn add(self: BalancedTernary, allocator: Allocator, rhs: BalancedTernary) !BalancedTernary { + if (rhs.digits.items.len == 0) { + if (self.digits.items.len == 0) { + var digits = ArrayList(Trit).init(allocator); + try digits.append(.Zero); + return BalancedTernary{ .digits = digits }; + } + return try self.clone(allocator); + } + + const length = @min(self.digits.items.len, rhs.digits.items.len); + var sum = ArrayList(Trit).init(allocator); + errdefer sum.deinit(); + + var carry = ArrayList(Trit).init(allocator); + errdefer carry.deinit(); + try carry.append(.Zero); + + for (0..length) |i| { + const result = self.digits.items[i].add(rhs.digits.items[i]); + try sum.append(result.current); + try carry.append(result.carry); + } + + if (self.digits.items.len > length) { + try sum.appendSlice(self.digits.items[length..]); + } + if (rhs.digits.items.len > length) { + try sum.appendSlice(rhs.digits.items[length..]); + } + + trim(&sum); + trim(&carry); + + var sum_bt = BalancedTernary{ .digits = sum }; + const carry_bt = BalancedTernary{ .digits = carry }; + //defer carry_bt.deinit(); + + return try sum_bt.add(allocator, carry_bt); + } + + fn mul(self: BalancedTernary, allocator: Allocator, rhs: BalancedTernary) !BalancedTernary { + var results = ArrayList(BalancedTernary).init(allocator); + defer { + for (results.items) |*item| { + item.deinit(); + } + results.deinit(); + } + + for (rhs.digits.items, 0..) |rhs_trit, i| { + var digits = ArrayList(Trit).init(allocator); + errdefer digits.deinit(); + + for (0..i) |_| { + try digits.append(.Zero); + } + + for (self.digits.items) |self_trit| { + try digits.append(self_trit.mul(rhs_trit)); + } + + try results.append(BalancedTernary{ .digits = digits }); + } + + var acc_digits = ArrayList(Trit).init(allocator); + try acc_digits.append(.Zero); + var acc = BalancedTernary{ .digits = acc_digits }; + + for (results.items) |item| { + const new_acc = try acc.add(allocator, item); + acc.deinit(); + acc = new_acc; + } + + return acc; + } + + fn negate(self: *BalancedTernary) void { + for (self.digits.items) |*trit| { + trit.* = trit.negate(); + } + } +}; diff --git a/Task/Barnsley-fern/Ada/barnsley-fern.adb b/Task/Barnsley-fern/Ada/barnsley-fern.adb new file mode 100644 index 0000000000..3d9631cbec --- /dev/null +++ b/Task/Barnsley-fern/Ada/barnsley-fern.adb @@ -0,0 +1,94 @@ +with Ada.Numerics.Discrete_Random; + +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Events.Events; + +procedure Barnsley_Fern is + + Iterations : constant := 1_000_000; + Width : constant := 500; + Height : constant := 750; + Scale : constant := 70.0; + + type Percentage is range 1 .. 100; + package Random_Percentages is + new Ada.Numerics.Discrete_Random (Percentage); + + Gen : Random_Percentages.Generator; + Window : SDL.Video.Windows.Window; + Renderer : SDL.Video.Renderers.Renderer; + Event : SDL.Events.Events.Events; + + procedure Draw_Barnsley_Fern is + use type SDL.C.int; + subtype F1_Range is Percentage range Percentage'First .. Percentage'First; + subtype F2_Range is Percentage range F1_Range'Last + 1 .. F1_Range'Last + 85; + subtype F3_Range is Percentage range F2_Range'Last + 1 .. F2_Range'Last + 7; + subtype F4_Range is Percentage range F3_Range'Last + 1 .. F3_Range'Last + 7; + + X0, Y0 : Float := 0.00; + X1, Y1 : Float; + begin + for I in 1 .. Iterations loop + case Random_Percentages.Random (Gen) is + + when F1_Range => + X1 := 0.00; + Y1 := 0.16 * Y0; + + when F2_Range => + X1 := 0.85 * X0 + 0.04 * Y0; + Y1 := -0.04 * X0 + 0.85 * Y0 + 1.60; + + when F3_Range => + X1 := 0.20 * X0 - 0.26 * Y0; + Y1 := 0.23 * X0 + 0.22 * Y0 + 1.60; + + when F4_Range => + X1 := -0.15 * X0 + 0.28 * Y0; + Y1 := 0.26 * X0 + 0.24 * Y0 + 0.44; + + end case; + Renderer.Draw (Point => (X => Width / 2 + SDL.C.int (Scale * X1), + Y => Height - SDL.C.int (Scale * Y1))); + X0 := X1; Y0 := Y1; + + end loop; + end Draw_Barnsley_Fern; + + procedure Wait is + use type SDL.Events.Event_Types; + begin + loop + while SDL.Events.Events.Poll (Event) loop + if Event.Common.Event_Type = SDL.Events.Quit then + return; + end if; + end loop; + end loop; + end Wait; + +begin + if not SDL.Initialise (Flags => SDL.Enable_Screen) then + return; + end if; + + SDL.Video.Windows.Makers.Create (Win => Window, + Title => "Barnsley Fern", + Position => SDL.Natural_Coordinates'(X => 10, Y => 10), + Size => SDL.Positive_Sizes'(Width, Height), + Flags => 0); + SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); + Renderer.Set_Draw_Colour ((0, 0, 0, 255)); + Renderer.Fill (Rectangle => (0, 0, Width, Height)); + Renderer.Set_Draw_Colour ((0, 220, 0, 255)); + + Random_Percentages.Reset (Gen); + Draw_Barnsley_Fern; + Window.Update_Surface; + + Wait; + Window.Finalize; + SDL.Finalise; +end Barnsley_Fern; diff --git a/Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.el b/Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.el new file mode 100644 index 0000000000..88f31ac7ce --- /dev/null +++ b/Task/Barnsley-fern/Emacs-Lisp/barnsley-fern.el @@ -0,0 +1,54 @@ +; Barnsley fern + +(defun make-array (size) + "Create an empty array with size*size elements." + (setq m-array (make-vector size nil)) + (dotimes (i size) + (setf (aref m-array i) (make-vector size 0))) + m-array) + +(defun barnsley-next (p) + "Return the next Barnsley fern coordinates." + (let ((r (random 100)) + (x (car p)) + (y (cdr p))) + (cond ((< r 2) (setq nx 0) (setq ny (* 0.16 y))) + ((< r 9) (setq nx (- (* 0.2 x) (* 0.26 y))) + (setq ny (+ 1.6 (* 0.23 x) (* 0.22 y)))) + ((< r 16) (setq nx (+ (* -0.15 x) (* 0.28 y))) + (setq ny (+ 0.44 (* 0.26 x) (* 0.24 y)))) + (t (setq nx (+ (* 0.85 x) (* 0.04 y))) + (setq ny (+ 1.6 (* -0.04 x) (* 0.85 y))))) + (cons nx ny))) + +(defun barnsley-lines (arr size) + "Turn array into a string for XPM conversion." + (setq all "") + (dotimes (y size) + (setq line "") + (dotimes (x size) + (setq line (concat line (if (= (elt (elt arr y) x) 1) "*" ".")))) + (setq all (concat all "\"" line "\",\n"))) + all) + +(defun barnsley-show (arr size) + "Convert size*size array to XPM image and show it." + (insert-image (create-image (concat (format "/* XPM */ +static char * barnsley[] = { +\"%i %i 2 1\", +\". c #000000\", +\"* c #00ff00\"," size size) + (barnsley-lines arr size) "};") 'xpm t))) + +(defun barnsley (size scale max-iter) + "Plot the Barnsley fern." + (let ((arr (make-array size)) + (p (cons 0 0))) + (dotimes (it max-iter) + (setq p (barnsley-next p)) + (setq x (round (+ (/ size 2) (* scale (car p))))) + (setq y (round (- size (* scale (cdr p)) 1))) + (setf (elt (elt arr y) x) 1)) + (barnsley-show arr size))) + +(barnsley 400 35 100000) diff --git a/Task/Barnsley-fern/Pluto/barnsley-fern.pluto b/Task/Barnsley-fern/Pluto/barnsley-fern.pluto new file mode 100644 index 0000000000..fe97f4f1e1 --- /dev/null +++ b/Task/Barnsley-fern/Pluto/barnsley-fern.pluto @@ -0,0 +1,35 @@ +require "bitmap" + +local w, h = 640, 640 +local bmp = bitmap.of(w, h, color.black, "Barnsley Fern") +local n = 200_000 + +local function create_fern() + local x = 0 + local y = 0 + local c = bitmap.rgbColor(0x32, 0xcd, 0x32) + for i = 0, n - 1 do + local tx + local ty + local r = math.random() + if r <= 0.01 then + tx = 0 + ty = 0.16 * y + elseif r <= 0.86 then + tx = 0.85 * x + 0.04 * y + ty = -0.04 * x + 0.85 * y + 1.6 + elseif r <= 0.93 then + tx = 0.2 * x - 0.26 * y + ty = 0.23 * x + 0.22 * y + 1.6 + else + tx = -0.15 * x + 0.28 * y + ty = 0.26 * x + 0.24 * y + 0.44 + end + x = tx + y = ty + bmp:set(math.round(w / 2 + x * w / 11), math.round(h - y * h / 11), c) + end +end + +create_fern() +bmp:view() diff --git a/Task/Barnsley-fern/Rebol/barnsley-fern.rebol b/Task/Barnsley-fern/Rebol/barnsley-fern.rebol new file mode 100644 index 0000000000..b272eaf806 --- /dev/null +++ b/Task/Barnsley-fern/Rebol/barnsley-fern.rebol @@ -0,0 +1,35 @@ +Rebol [ + title: "Rosetta code: Barnsley Fern" + file: %Barnsley_fern.r3 + url: https://rosettacode.org/wiki/Barnsley_fern + needs: 3.0.0 +] +barnsley-fern: function [size [pair!]][ + img: make image! reduce [size 0.0.0] + width: size/x + height: size/y + + p: 0x0 x: y: 0.0 + repeat i 100000 [ + xt: yt: 0.0 + r: random 100 + case [ + r <= 1 [xt: 0.0 yt: 0.16 * y] + r <= 8 [xt: ( 0.20 * x) - (0.26 * y) yt: ( 0.23 * x) + (0.22 * y) + 1.60] + r <= 15 [xt: (-0.15 * x) + (0.28 * y) yt: ( 0.26 * x) + (0.24 * y) + 0.44] + 'else [xt: ( 0.85 * x) + (0.04 * y) yt: (-0.04 * x) + (0.85 * y) + 1.60] + ] + x: xt y: yt + p/x: round (width / 2 + (60 * x)) + p/y: height - round (60 * y) + change at img p green + ] +] + +img: barnsley-fern 640x640 +save %barnsley-fern.png img + +if cv: attempt [import 'opencv][ + cv/imshow/name img "Barnsley" + cv/waitKey 0 +] diff --git a/Task/Barnsley-fern/Rust/barnsley-fern.rs b/Task/Barnsley-fern/Rust/barnsley-fern.rs index d756f3ebee..fe8f6a528c 100644 --- a/Task/Barnsley-fern/Rust/barnsley-fern.rs +++ b/Task/Barnsley-fern/Rust/barnsley-fern.rs @@ -15,7 +15,7 @@ fn main() { let mut x = 0.; let mut y = 0.; for _ in 0..max_iterations { - let r = rng.gen::(); + let r = rng.r#gen::(); let cx: f64; let cy: f64; diff --git a/Task/Base64-decode-data/Ada/base64-decode-data.adb b/Task/Base64-decode-data/Ada/base64-decode-data.adb new file mode 100644 index 0000000000..8c35fb5a21 --- /dev/null +++ b/Task/Base64-decode-data/Ada/base64-decode-data.adb @@ -0,0 +1,14 @@ +with Ada.Text_IO; + +with AWS.Translator; + +procedure Decode_AWS is + Input : constant String := + "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" & + "IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="; + Result : constant String := AWS.Translator.Base64_Decode (Input); +begin + Ada.Text_IO.Put_Line (Input); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (Result); +end Decode_AWS; diff --git a/Task/Base64-decode-data/Batch-File/base64-decode-data.bat b/Task/Base64-decode-data/Batch-File/base64-decode-data.bat new file mode 100644 index 0000000000..73b80ec78d --- /dev/null +++ b/Task/Base64-decode-data/Batch-File/base64-decode-data.bat @@ -0,0 +1,2 @@ +certutil -f -decodehex "%temp%\favicon.tmp" favicon1.ico 1 +fc /B favicon.ico favicon1.ico diff --git a/Task/Base64-decode-data/Haxe/base64-decode-data.hx b/Task/Base64-decode-data/Haxe/base64-decode-data.hx new file mode 100644 index 0000000000..bcba8367c2 --- /dev/null +++ b/Task/Base64-decode-data/Haxe/base64-decode-data.hx @@ -0,0 +1,9 @@ +class Main { + static function main() { + var data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVw" + + "IHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="; + Sys.println('$data\n'); + var decoded = haxe.crypto.Base64.decode(data); + Sys.println(decoded); + } +} diff --git a/Task/Base64-decode-data/PowerShell/base64-decode-data-1.ps1 b/Task/Base64-decode-data/PowerShell/base64-decode-data-1.ps1 new file mode 100644 index 0000000000..429bf1334a --- /dev/null +++ b/Task/Base64-decode-data/PowerShell/base64-decode-data-1.ps1 @@ -0,0 +1 @@ +[Text.Encoding]::ASCII.GetString([Convert]::FromBase64String("VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=")) diff --git a/Task/Base64-decode-data/PowerShell/base64-decode-data-2.ps1 b/Task/Base64-decode-data/PowerShell/base64-decode-data-2.ps1 new file mode 100644 index 0000000000..8e3ff8d7a3 --- /dev/null +++ b/Task/Base64-decode-data/PowerShell/base64-decode-data-2.ps1 @@ -0,0 +1,2 @@ +$bytes=... +[IO.File]::WriteAllBytes('favicon.ico', [Convert]::FromBase64String($bytes)) diff --git a/Task/Base64-decode-data/REXX/base64-decode-data-1.rexx b/Task/Base64-decode-data/REXX/base64-decode-data-1.rexx new file mode 100644 index 0000000000..3d85bbec31 --- /dev/null +++ b/Task/Base64-decode-data/REXX/base64-decode-data-1.rexx @@ -0,0 +1,20 @@ +z= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +do i=1 to 64 + bs.i=x2b(d2x(i-1)) + c=substr(z,i,1) + ds.c=right(bs.i,6,0) + End +e='YW55IGNhcm5hbCBwbGVhc3VyZS4' +r='' +ec=e +Do While ec<>'' + Parse Var ec c +1 ec + r=r||ds.c + End +res='' +Do while r<>'' + Parse Var r x +8 r + res=res||x2c(b2x(x)) + End +Say 'Input: >'e'<' +Say 'decoded: >'res'<' diff --git a/Task/Base64-decode-data/REXX/base64-decode-data-2.rexx b/Task/Base64-decode-data/REXX/base64-decode-data-2.rexx new file mode 100644 index 0000000000..90d8c0c1ce --- /dev/null +++ b/Task/Base64-decode-data/REXX/base64-decode-data-2.rexx @@ -0,0 +1,56 @@ +-- 3 Oct 2025 +include Setting +signal off notready + +say 'BASE64 DECODE DATA' +say version +say +call Task1 'TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu' +call Task1 'TWFu' +call Task1 'TWE=' +call Task1 'TQ==' +call Task1 'YW55IGNhcm5hbCBwbGVhc3VyZS4=' +call Task2 +exit + +Task1: +procedure +parse arg xx +say 'Encoded ' xx +say 'Original' Decode64(xx) +say +return + +Task2: +procedure +in='favicon.dat'; out='favcopy.ico' +rr=Decode64(Charin(in,1,30000)) +call Charout out,rr,1 +return + +Decode64: +procedure +parse arg xx +-- Alphabet +a='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +lx=Length(xx) +rr='' +-- Loop thru encoded characters +do i=1 to lx + c=Substr(xx,i,1) +-- If padding, discard 2 bits + if c='=' then do + rr=Left(rr,Length(rr)-2) + iterate i + end +-- Find position in alphabet + p=Pos(c,a)-1 +-- Convert to bits and take last 6 + b=Right(0000||X2b(D2x(p)),6) +-- Append + rr||=b +end +-- Convert to character +return X2c(B2x(rr)) + +include Abend diff --git a/Task/Base64-decode-data/Rebol/base64-decode-data.rebol b/Task/Base64-decode-data/Rebol/base64-decode-data.rebol new file mode 100644 index 0000000000..a921880d20 --- /dev/null +++ b/Task/Base64-decode-data/Rebol/base64-decode-data.rebol @@ -0,0 +1,3 @@ +print to string! debase { +VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIH +VwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo} 64 diff --git a/Task/Base64-decode-data/YAMLScript/base64-decode-data.ys b/Task/Base64-decode-data/YAMLScript/base64-decode-data.ys new file mode 100644 index 0000000000..940785796f --- /dev/null +++ b/Task/Base64-decode-data/YAMLScript/base64-decode-data.ys @@ -0,0 +1,4 @@ +!YS-v0 + +defn main(str): + say: base64-decode(str) diff --git a/Task/Bell-numbers/AWK/bell-numbers.awk b/Task/Bell-numbers/AWK/bell-numbers.awk new file mode 100644 index 0000000000..f304853fb9 --- /dev/null +++ b/Task/Bell-numbers/AWK/bell-numbers.awk @@ -0,0 +1,23 @@ +# syntax: GAWK --bignum -f BELL_NUMBERS.AWK +BEGIN { + arr[0,0] = 1 + printf(" 0: %10d\n",arr[0,0]) + printf(" 1: %10d\n",arr[0,0]) + for (i=1; i<50; i++) { + arr[i,0] = arr[i-1,i-1] + for (j=1; j<=i; j++) { + arr[i,j] = arr[i,j-1] + arr[i-1,j-1] + bt[i] = sprintf("%s%s ",bt[i],arr[i-1,j-1]) # build Bell's triangle + } + if (i <= 13) { + printf("%2d: %10d\n",i+1,arr[i,i]) + } + if (i == 49) { + printf("%2d: %d (%d digits)\n\n",i+1,arr[i,i],length(arr[i,i])) + } + } + for (i=1; i<=10; i++) { # show Bell's triangle + printf("%2d: %s\n",i,bt[i]) + } + exit(0) +} diff --git a/Task/Bell-numbers/Ada/bell-numbers.adb b/Task/Bell-numbers/Ada/bell-numbers.adb new file mode 100644 index 0000000000..ffb0e2190e --- /dev/null +++ b/Task/Bell-numbers/Ada/bell-numbers.adb @@ -0,0 +1,59 @@ +with Ada.Text_IO; use Ada.Text_IO; +procedure Main is + type Bell_Triangle is array(Positive range <>, Positive range <>) of Natural; + + + procedure Print_Rows (Row : in Positive; Triangle : in Bell_Triangle) is + begin + if Row in Triangle'Range(1) then + for I in Triangle'First(1) .. Row loop + Put_Line (Triangle (I, 1)'Image); + end loop; + end if; + end Print_Rows; + + procedure Print_Triangle (Num : in Positive; Triangle : in Bell_Triangle) is + begin + if Num in Triangle'Range then + for I in Triangle'First(1) .. Num loop + for J in Triangle'First(2) .. Num loop + if Triangle (I, J) /= 0 then + Put (Triangle (I, J)'Image); + end if; + end loop; + New_Line; + end loop; + end if; + end Print_Triangle; + + procedure Bell_Numbers is + Triangle : Bell_Triangle(1..15, 1..15) := (Others => (Others => 0)); + Temp : Positive := 1; + begin + + Triangle (1, 1) := 1; + + for I in Triangle'First(1) + 1 .. Triangle'Last(1) loop + Triangle (I, 1) := Temp; + + for J in Triangle'First(2) .. Triangle'Last(2) - 1 loop + if Triangle (I - 1, J) /= 0 then + Triangle (I, J + 1) := Triangle (I, J) + Triangle (I - 1, J); + else + Temp := Triangle (I, J); + exit; + end if; + end loop; + end loop; + + Put_Line ("First 15 Bell numbers:"); + Print_Rows (15, Triangle); + + New_Line; + + Put_Line ("First 10 rows of the Bell triangle:"); + Print_Triangle (10, Triangle); + end Bell_Numbers; +begin + Bell_Numbers; +end Main; diff --git a/Task/Bell-numbers/Berkeley-Logo/bell-numbers.logo b/Task/Bell-numbers/Berkeley-Logo/bell-numbers.logo new file mode 100644 index 0000000000..6a7e9966a9 --- /dev/null +++ b/Task/Bell-numbers/Berkeley-Logo/bell-numbers.logo @@ -0,0 +1,21 @@ +to bell.numbers :max.n + make "a (array :max.n 0) + make "n 0 + make "ubound.a :max.n - 1 + for [i 0 :ubound.a] [setitem :i :a 0] + setitem 0 :a 1 + type "|B(| + type form :n 2 0 + type "|) = | + print form item 0 :a 9 0 + while [:n < :max.n] ~ + [setitem :n :a item 0 :a + for [j :n 1 -1] ~ + [setitem :j - 1 :a (item :j - 1 :a) + (item :j :a)] + make "n :n + 1 + type "|B(| + type form :n 2 0 + type "|) = | + print form item 0 :a 9 0] + erase [[] [a] []] +end diff --git a/Task/Bell-numbers/Crystal/bell-numbers.cr b/Task/Bell-numbers/Crystal/bell-numbers.cr new file mode 100644 index 0000000000..2ad901f5b0 --- /dev/null +++ b/Task/Bell-numbers/Crystal/bell-numbers.cr @@ -0,0 +1,12 @@ +require "big" + +row = [1.to_big_i] + +(1..50).each do |i| + puts "%2d: %s" % { i, i <= 10 ? row : row.first } if 1 <= i <= 15 || i == 50 + next_row = [row.last] + row.each do |n| + next_row << n + next_row.last + end + row = next_row +end diff --git a/Task/Bell-numbers/EasyLang/bell-numbers.easy b/Task/Bell-numbers/EasyLang/bell-numbers.easy index e554895111..d4a9e3ac8c 100644 --- a/Task/Bell-numbers/EasyLang/bell-numbers.easy +++ b/Task/Bell-numbers/EasyLang/bell-numbers.easy @@ -10,5 +10,6 @@ func bell n . return list[n] . for i = 1 to 15 - print bell i + write bell i & " " . +print "" diff --git a/Task/Bell-numbers/Free-Pascal-Lazarus/bell-numbers.pas b/Task/Bell-numbers/Free-Pascal-Lazarus/bell-numbers.pas new file mode 100644 index 0000000000..731ee0520a --- /dev/null +++ b/Task/Bell-numbers/Free-Pascal-Lazarus/bell-numbers.pas @@ -0,0 +1,121 @@ +program BellNumbers; +{$Ifdef FPC} + {$optimization on,all} +{$ElseIf} + {Apptype console} +{$EndIf} +uses + sysutils,gmp; +var + T0 :TDateTime; +procedure BellNumbersUint64(OnlyBellNumbers:Boolean); +var + BList : array[0..24] of Uint64; + BellNum : Uint64; + BListLenght,i :nativeUInt; +begin + IF OnlyBellNUmbers then + Begin + writeln('Bell triangles '); + writeln(' 1 = 1'); + end + else + Begin + writeln('Bell numbers'); + writeln(' 1 = 1'); + writeln(' 2 = 1'); + end; + + BList[0]:= 1; + BListLenght := 1; + BellNum := 1; + repeat +// For i := BListLenght downto 1 do BList[i] := BList[i-1]; or + move(Blist[0],Blist[1],BListLenght*SizeOf(Blist[0])); + BList[0] := BellNum; + For i := 1 to BListLenght do + Begin + BellNum += BList[i]; + BList[i] := BellNum; + end; + +// Output + IF OnlyBellNUmbers then + Begin + IF BListLenght<=9 then + Begin + write(BListLenght+1:3,' = '); + For i := 0 to BListLenght do + write(BList[i]:7); + writeln; + end + ELSE + BREAK; + end + else + writeln(BListLenght+2:3,' = ',BellNum); + + inc(BListLenght); + until BListLenght >= 25; + writeln; +end; + +procedure BellNumbersMPInteger; +const + MaxIndex = 5000;//must be > 0 +var +//MPInteger as alternative to mpz_t -> selfcleaning + BList : array[0..MaxIndex] of MPInteger; + BellNum : MPInteger; + BListLenght,i :nativeUInt; + BellNumStr : AnsiString; +Begin + BellNumStr := ''; + z_init(BellNum); + z_ui_pow_ui(BellNum,10,32767); + BListLenght := z_size(BellNum); + writeln('init length ',BListLenght); + For i := 0 to MaxIndex do + Begin +// z_init2_set(BList[i],BListLenght); + z_add_ui( BList[i],i); + end; + writeln('init length ',z_size(BList[0])); + + T0 := now; + BListLenght := 1; + z_set_ui(BList[0],1); + z_set_ui(BellNum,1); + repeat + //Move does not fit moving interfaces // call fpc_intf_assign + For i := BListLenght downto 1 do BList[i] := BList[i-1]; + z_set(BList[0],BellNum); + For i := 1 to BListLenght do + Begin + BellNum := z_add(BellNum,BList[i]); + z_set(BList[i],BellNum); + end; + inc(BListLenght); + if (BListLenght+1) MOD 100 = 0 then + Begin + BellNumStr:= z_get_str(10,BellNum); + //z_sizeinbase (BellNum, 10) is not exact :-( + write('Bell(',(IntToStr(BListLenght)):6,') has ', + (IntToStr(Length(BellNumStr))):6,' decimal digits'); + writeln(FormatDateTime(' NN:SS.ZZZ',now-T0),'s'); + end; + until BListLenght>=MaxIndex; + BellNumStr:= z_get_str(10,BellNum); + writeln(BListLenght:6,'.th ',Length(BellNumStr):8); + +//clean up ;-) + BellNumStr := ''; + z_clear(BellNum); + For i := MaxIndex downto 0 do + z_clear(BList[i]); +end; + +BEGIN + BellNumbersUint64(True);BellNumbersUint64(False); + BellNumbersMPInteger; +END. diff --git a/Task/Bell-numbers/JavaScript/bell-numbers.js b/Task/Bell-numbers/JavaScript/bell-numbers.js new file mode 100644 index 0000000000..d6982673f0 --- /dev/null +++ b/Task/Bell-numbers/JavaScript/bell-numbers.js @@ -0,0 +1,75 @@ +// --------------------------------------------------------------- +// Bell Triangle implementation (JavaScript) +// --------------------------------------------------------------- + +class BellTriangle { + /** + * @param {number} n – number of rows to generate + */ + constructor(n) { + // total number of elements in a triangular array of size n + const length = (n * (n + 1)) / 2; + // use a plain array, pre‑filled with zeros + this.arr = new Array(length).fill(0); + + // initialise first element (row 1, col 0) = 1 + this.set(1, 0, 1); + + // build the triangle row by row + for (let i = 2; i <= n; ++i) { + // first element of a row copies the last element of the previous row + this.set(i, 0, this.get(i - 1, i - 2)); + + // the remaining entries are sums of the element above‑left + // and the element to the left in the current row + for (let j = 1; j < i; ++j) { + const value = this.get(i, j - 1) + this.get(i - 1, j - 1); + this.set(i, j, value); + } + } + } + + /** Convert (row, col) into a linear index. Rows start at 1. */ + index(row, col) { + if (row > 0 && col >= 0 && col < row) { + // triangular number formula: sum_{k=1}^{row-1} k = row*(row-1)/2 + return (row * (row - 1)) / 2 + col; + } + throw new Error('Invalid row/col'); + } + + /** Return the value at (row, col). */ + get(row, col) { + const i = this.index(row, col); + return this.arr[i]; + } + + /** Store `value` at (row, col). */ + set(row, col, value) { + const i = this.index(row, col); + this.arr[i] = value; + } +} + +// --------------------------------------------------------------- +// Main program – reproduces the Java `main` method +// --------------------------------------------------------------- +(function main() { + const rows = 15; + const bt = new BellTriangle(rows); + + console.log('First fifteen Bell numbers:'); + for (let i = 0; i < rows; ++i) { + // the Bell number Bₙ is the first entry of row n (row index = n, col = 0) + console.log(`${i + 1}: ${bt.get(i + 1, 0)}`); + } + + // Print the whole triangle for the first 10 rows (exactly as Java did) + for (let i = 1; i <= 10; ++i) { + let line = `${bt.get(i, 0)}`; + for (let j = 1; j < i; ++j) { + line += `, ${bt.get(i, j)}`; + } + console.log(line); + } +})(); diff --git a/Task/Bell-numbers/Loglan82/bell-numbers.loglan82 b/Task/Bell-numbers/Loglan82/bell-numbers.loglan82 new file mode 100644 index 0000000000..141ec17f83 --- /dev/null +++ b/Task/Bell-numbers/Loglan82/bell-numbers.loglan82 @@ -0,0 +1,28 @@ +(* Bell numbers *) + +block +const + max_n = 13; +var + a: arrayof integer, + i, j, n: integer; +begin + array a dim (0 : max_n); + n := 0; + for i := 0 to max_n - 1 + do + a(i) := 0 + od; + a(0) := 1; + writeln("B(", n: 2, ") = ", a(0): 9); + while n < max_n + do + a(n) := a(0); + for j := n downto 1 + do + a(j - 1) := a(j - 1) + a(j) + od; + n := n + 1; + writeln("B(", n: 2, ") = ", a(0): 9); + od; +end; diff --git a/Task/Bell-numbers/MoonRock/bell-numbers.moonrock b/Task/Bell-numbers/MoonRock/bell-numbers.moonrock new file mode 100644 index 0000000000..21caf0d119 --- /dev/null +++ b/Task/Bell-numbers/MoonRock/bell-numbers.moonrock @@ -0,0 +1,43 @@ +' Bell numbers + +BEGIN DEF +SUB PrintStr(S$, Width%) +%MaxN = 14 +DIM A&[%MaxN] + +BEGIN CODE +N% = 0 +FOR I% = 0 TO %MaxN -1 + A&[I%] = 0 +NEXT +A&[0] = 1 +PRINT "B(" +CALL PrintStr(STR(N%), 2) +PRINT ") = " +CALL PrintStr(STR(A&[0]), 9) +PRINT "\n" +WHILE N% < %MaxN + A&[N%] = A&[0] + J% = N% + WHILE J% >= 1 + JMin1% = J% - 1 + A&[JMin1%] = A&[JMin1%] + A&[J%] + J% = J% - 1 + WEND + N% = N% + 1 + PRINT "B(" + CALL PrintStr(STR(N%), 2) + PRINT ") = " + CALL PrintStr(STR(A&[0]), 9) + PRINT "\n" +WEND +END + +SUB PrintStr(S$, Width%) +IF LEN(S$) > Width% THEN + PRINT S$ +ELSE + S$ = SPACE(Width%) + S$ + PRINT RIGHT(S$, Width%) +ENDIF +END SUB diff --git a/Task/Bell-numbers/Oberon-07/bell-numbers.oberon b/Task/Bell-numbers/Oberon-07/bell-numbers.oberon new file mode 100644 index 0000000000..0d8ac34e3d --- /dev/null +++ b/Task/Bell-numbers/Oberon-07/bell-numbers.oberon @@ -0,0 +1,28 @@ +MODULE BellNumbers; + IMPORT Out; + + PROCEDURE showBellNumbers; + CONST maxBell = 15; + VAR a : ARRAY maxBell - 1 OF INTEGER; + i, n, j : INTEGER; + + PROCEDURE showOneBellNumber( n, bellNumber : INTEGER ); + BEGIN + Out.Int( n, 2 );Out.String( ": " );Out.Int( bellNumber, 0 );Out.Ln + END showOneBellNumber; + + BEGIN + FOR i := 1 TO LEN( a ) - 1 DO a[ i ] := 0 END; + a[ 0 ] := 1; + showOneBellNumber( 1, a[ 0 ] ); + FOR n := 0 TO maxBell - 2 DO + (* replace a with the next line of the triangle *) + a[ n ] := a[ 0 ]; + FOR j := n TO 1 BY -1 DO INC( a[ j - 1 ], a[ j ] ) END; + showOneBellNumber( n + 2, a[ 0 ] ) + END + END showBellNumbers; + +BEGIN + showBellNumbers +END BellNumbers. diff --git a/Task/Bell-numbers/PHP/bell-numbers.php b/Task/Bell-numbers/PHP/bell-numbers.php new file mode 100644 index 0000000000..ead13effb8 --- /dev/null +++ b/Task/Bell-numbers/PHP/bell-numbers.php @@ -0,0 +1,17 @@ += 1; $j--) + $a[$j - 1] += $a[$j]; + $n++; + echo 'B('.str_pad($n, 2, " ", STR_PAD_LEFT).') = '. + str_pad($a[0], 9, " ", STR_PAD_LEFT).PHP_EOL; +} +?> diff --git a/Task/Bell-numbers/PL-I/bell-numbers.pli b/Task/Bell-numbers/PL-I/bell-numbers.pli new file mode 100644 index 0000000000..f9386c59bf --- /dev/null +++ b/Task/Bell-numbers/PL-I/bell-numbers.pli @@ -0,0 +1,25 @@ +/* Bell numbers */ + +Bell_nums: + procedure options(main); + %replace nmax by 9; + declare + a(0 : nmax) fixed binary(15), + (i, j, n) fixed binary(15); + n = 0; + do i = 0 to nmax - 1; + a(i) = 0; + end; + a(0) = 1; + put list('B('); + put edit(n, ') = ', a(0))(f(2), a, f(9)); + do while (n < nmax); + a(n) = a(0); + do j = n to 1 by -1; + a(j - 1) = a(j - 1) + a(j); + end; + n = n + 1; + put skip list('B('); + put edit(n, ') = ', a(0))(f(2), a, f(9)); + end; +end Bell_nums; diff --git a/Task/Bell-numbers/Pascal-P/bell-numbers.pas b/Task/Bell-numbers/Pascal-P/bell-numbers.pas new file mode 100644 index 0000000000..4cfaf86cfc --- /dev/null +++ b/Task/Bell-numbers/Pascal-P/bell-numbers.pas @@ -0,0 +1,20 @@ +program bellnums(output); + (* Bell numbers *) +const + maxn = 14; (* with 32-bit integer *) +var + a: array[0..maxn - 1] of integer; + i, j, n: integer; +begin + n := 0; + for i := 0 to maxn - 1 do a[i] := 0; + a[0] := 1; + writeln('B(', n: 2, ') = ', a[0]: 9); + while n < maxn do + begin + a[n] := a[0]; + for j := n downto 1 do a[j - 1] := a[j - 1] + a[j]; + n := n + 1; + writeln('B(', n: 2, ') = ', a[0]: 9); + end; +end. diff --git a/Task/Bell-numbers/PowerShell/bell-numbers.ps1 b/Task/Bell-numbers/PowerShell/bell-numbers.ps1 new file mode 100644 index 0000000000..2a173ea9e9 --- /dev/null +++ b/Task/Bell-numbers/PowerShell/bell-numbers.ps1 @@ -0,0 +1,19 @@ +# Bell numbers +[uint32]$script:MaxN = 14 +$a = [uint32[]]::new($script:MaxN) +foreach ($i in 0..($script:MaxN - 1)) { + $a[$i] = 0 +} +[uint32]$n = 0 +$a[0] = 1 +[string]$row = "B({0, 2}) = {1,9}" -f $n, $a[0] +Write-Output $row +while ($n -lt $script:MaxN) { + $a[$n] = $a[0] + foreach ($j in $n..1) { + $a[$j - 1] += $a[$j] + } + $n++ + [string]$row = "B({0, 2}) = {1,9}" -f $n, $a[0] + Write-Output $row +} diff --git a/Task/Bell-numbers/Uiua/bell-numbers.uiua b/Task/Bell-numbers/Uiua/bell-numbers.uiua new file mode 100644 index 0000000000..c6d1180ce3 --- /dev/null +++ b/Task/Bell-numbers/Uiua/bell-numbers.uiua @@ -0,0 +1,12 @@ +# Generate Bell numbers. + +# Use Marcos' BigInt library. +~ "git: https://github.com/Marcos-cat/uiua-bigint" ~ Add New Str + +# Generate next row of the Bell triangle. +# Supply simple `+` for ints, or `⍜∩°□Add` for BigInts. +Next! ← ⊙◌⍢(⊂⊙^0⊓⟜⊣°⊂|>0⋅⧻)⊸[⊣] + +&p⍥⊃Next!+⊢15 [1] # First fifteen. +&pStr°□⊢⍥Next!⍜∩°□Add49[1] # Fiftieth. +≡&p⍥⊃Next!+□10 [1] # First ten lines of triangle. diff --git a/Task/Bell-numbers/VBA/bell-numbers.vba b/Task/Bell-numbers/VBA/bell-numbers.vba new file mode 100644 index 0000000000..35b134c90f --- /dev/null +++ b/Task/Bell-numbers/VBA/bell-numbers.vba @@ -0,0 +1,32 @@ +' Bell numbers + +Const MaxN As Integer = 14 + +Sub BellNumsMain() + Dim A(MaxN - 1) As Long + Dim N, J As Integer + For I = 0 To MaxN - 1 + A(I) = 0 + Next I + N = 0 + A(0) = 1 + Debug.Print "B(" & FormatLong(N, 2) & ") = " & FormatLong(A(0), 9) + Do While N < MaxN + A(N) = A(0) + For J = N To 1 Step -1 + A(J - 1) = A(J - 1) + A(J) + Next J + N = N + 1 + Debug.Print "B(" & FormatLong(N, 2) & ") = " & FormatLong(A(0), 9) + Loop +End Sub + +Function FormatLong(ByVal Num As Long, L As Integer) As String + Dim S As String + S = Trim(Str(Num)) + If Len(S) > L Then + FormatLong = String(L, "#") + Else + FormatLong = Right(String(L, " ") & S, L) + End If +End Function diff --git a/Task/Benfords-law/Ada/benfords-law-1.adb b/Task/Benfords-law/Ada/benfords-law-1.adb new file mode 100644 index 0000000000..b11e243437 --- /dev/null +++ b/Task/Benfords-law/Ada/benfords-law-1.adb @@ -0,0 +1,49 @@ +with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions; + +procedure Benford is + + subtype Nonzero_Digit is Natural range 1 .. 9; + function First_Digit(S: String) return Nonzero_Digit is + (if S(S'First) in '1' .. '9' + then Nonzero_Digit'Value(S(S'First .. S'First)) + else First_Digit(S(S'First+1 .. S'Last))); + + package N_IO is new Ada.Text_IO.Integer_IO(Natural); + + procedure Print(D: Nonzero_Digit; Counted, Sum: Natural) is + package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); + package F_IO is new Ada.Text_IO.Float_IO(Float); + Actual: constant Float := Float(Counted) / Float(Sum); + Expected: constant Float := Math.Log(1.0 + 1.0 / Float(D), Base => 10.0); + Deviation: constant Float := abs(Expected-Actual); + begin + N_IO.Put(D, 5); + N_IO.Put(Counted, 14); + F_IO.Put(Float(Sum)*Expected, Fore => 16, Aft => 1, Exp => 0); + F_IO.Put(100.0*Actual, Fore => 9, Aft => 2, Exp => 0); + F_IO.Put(100.0*Expected, Fore => 11, Aft => 2, Exp => 0); + F_IO.Put(100.0*Deviation, Fore => 13, Aft => 2, Exp => 0); + end Print; + + Cnt: array(Nonzero_Digit) of Natural := (1 .. 9 => 0); + D: Nonzero_Digit; + Sum: Natural := 0; + Counter: Positive; + +begin + while not Ada.Text_IO.End_Of_File loop + -- each line in the input file holds Counter, followed by Fib(Counter) + N_IO.Get(Counter); + -- Counter and skip it, we just don't need it + D := First_Digit(Ada.Text_IO.Get_Line); + -- read the rest of the line and extract the first digit + Cnt(D) := Cnt(D)+1; + Sum := Sum + 1; + end loop; + Ada.Text_IO.Put_Line(" Digit Found[total] Expected[total] Found[%]" + & " Expected[%] Difference[%]"); + for I in Nonzero_Digit loop + Print(I, Cnt(I), Sum); + Ada.Text_IO.New_Line; + end loop; +end Benford; diff --git a/Task/Benfords-law/Ada/benfords-law-2.adb b/Task/Benfords-law/Ada/benfords-law-2.adb new file mode 100644 index 0000000000..e041c0ce41 --- /dev/null +++ b/Task/Benfords-law/Ada/benfords-law-2.adb @@ -0,0 +1 @@ + -- N_IO.Get(Counter); diff --git a/Task/Benfords-law/Dart/benfords-law.dart b/Task/Benfords-law/Dart/benfords-law.dart new file mode 100644 index 0000000000..4182f28c03 --- /dev/null +++ b/Task/Benfords-law/Dart/benfords-law.dart @@ -0,0 +1,35 @@ +import 'dart:math'; + +digits(n) sync* { + double a = 0, b = 1; + for (var i = 0; i < n; i++) { + yield b.toString().codeUnitAt(0) - 48; + (a, b) = (b, a + b); + } +} + +lineout(s1, s2, s3) { + print( + s1.toString().padLeft(8) + + s2.toString().padLeft(12) + + s3.toString().padLeft(12), + ); +} + +main() { + var tally = List.filled(9, 0); + for (var d in digits(1000)) { + tally[d - 1] += 1; + } + + lineout("Digit", "Expected", "Actual"); + print("-" * 40); + + for (var d = 1; d < 10; d += 1) { + lineout( + d, + (log(1 + 1 / d) * log10e).toStringAsFixed(4), + (tally[d - 1] / 1000).toStringAsFixed(3), + ); + } +} diff --git a/Task/Benfords-law/Fortran/benfords-law-3.f b/Task/Benfords-law/Fortran/benfords-law-3.f new file mode 100644 index 0000000000..5c2ca6d8b6 --- /dev/null +++ b/Task/Benfords-law/Fortran/benfords-law-3.f @@ -0,0 +1,33 @@ + PROGRAM benford + INTEGER counts(9) + + expected(d) = log10(1.0 + 1.0/d) + + CALL tally(counts) + + PRINT 100, 'Digit', 'Actual', 'Expected' + DO 10, i = 1, 9 +10 PRINT 101, i, counts(i)/1E3, expected(real(i)) + +100 FORMAT (A6, 1X, A9, 1X, A9) +101 FORMAT (I4, 3X, F9.3, 1X, F9.4) + END PROGRAM + + + SUBROUTINE tally(counts) + INTEGER counts(9) + CHARACTER*20 str + DOUBLE PRECISION a, b, c + INTEGER d + + counts = [(0, i = 1, 9)] + a = 0 + b = 1 + DO 10, i = 1, 1000 + WRITE (str, '(E12.6)') b + d = ichar(str(3:3)) - ichar('0') + counts(d) = counts(d) + 1 + c = a + b + a = b +10 b = c + END SUBROUTINE diff --git a/Task/Benfords-law/K/benfords-law.k b/Task/Benfords-law/K/benfords-law.k new file mode 100644 index 0000000000..5418b93641 --- /dev/null +++ b/Task/Benfords-law/K/benfords-law.k @@ -0,0 +1,7 @@ +law: {(`ln 1 + 1%x) % `ln 10} +tally: #' = {*$x}' +\[1000; 0.0; 1.0] + +`0: (8$"digit"), (12$"Expected"), "Actual" + +row: {`0: (-3$$x), (-13$7#$law x), -10$"0.", $tally[*$x]} +nop: 9 {row x; x + 1}/ 1 diff --git a/Task/Benfords-law/Pluto/benfords-law.pluto b/Task/Benfords-law/Pluto/benfords-law.pluto new file mode 100644 index 0000000000..b5354c40ab --- /dev/null +++ b/Task/Benfords-law/Pluto/benfords-law.pluto @@ -0,0 +1,30 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" +require "table2" + +local function fib1000() + local a = bigint.new(0) + local b = bigint.new(1) + local r = table.create(1000) + for i = 1, 1000 do + r[i] = b + a, b = b, b + a + end + return r +end + +local function show(c, title) + local f = table.rep(9, 0) + for c as v do + local t = v:tostring():byte() - 48 + f[t] += 1 + end + print(title) + print("Digit Observed Predicted") + for i = 1, #f do + local t = math.log(1 / i + 1, 10) + fmt.print(" %d %8.3f %8.3f", i, f[i] / #c, t) + end +end + +show(fib1000(), "First 1000 Fibonacci numbers:") diff --git a/Task/Benfords-law/PowerShell/benfords-law.ps1 b/Task/Benfords-law/PowerShell/benfords-law.ps1 new file mode 100644 index 0000000000..32add2876b --- /dev/null +++ b/Task/Benfords-law/PowerShell/benfords-law.ps1 @@ -0,0 +1,16 @@ +$url = "https://oeis.org/A000045/b000045.txt" +$file = "$env:TEMP\FibonacciNumbers.txt" +(New-Object System.Net.WebClient).DownloadFile($url, $file) + +$benford = Get-Content -Path $file | + Select-Object -Skip 1 -First 1000 | + ForEach-Object {(($_ -split " ")[1].ToString().ToCharArray())[0]} | + Group-Object | + Select-Object -Property @{Name="Digit" ; Expression={[int]($_.Name)}}, + Count, + @{Name="Actual" ; Expression={$_.Count/1000}}, + @{Name="Expected"; Expression={[double]("{0:f5}" -f [Math]::Log10(1 + 1 / $_.Name))}} + +$benford | Sort-Object -Property Digit | Format-Table -AutoSize + +Remove-Item -Path $file -Force -ErrorAction SilentlyContinue diff --git a/Task/Bernoulli-numbers/Ada/bernoulli-numbers-1.adb b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-1.adb new file mode 100644 index 0000000000..2bcbe560fe --- /dev/null +++ b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-1.adb @@ -0,0 +1,32 @@ +WITH GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings; +USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings; + +PROCEDURE Main IS + + FUNCTION Bernoulli_Number (N : Natural) RETURN Unbounded_Fraction IS + FUNCTION "/" (Left, Right : Natural) RETURN Unbounded_Fraction IS + (To_Unbounded_Integer (Left) / To_Unbounded_Integer (Right)); + A : ARRAY (0 .. N) OF Unbounded_Fraction; + BEGIN + FOR M IN 0 .. N LOOP + A (M) := 1 / (M + 1); + FOR J IN REVERSE 1 .. M LOOP + A (J - 1) := (J / 1 ) * (A (J - 1) - A (J)); + END LOOP; + END LOOP; + RETURN A (0); + END Bernoulli_Number; + +BEGIN + FOR I IN 0 .. 60 LOOP + IF I MOD 2 = 0 OR I = 1 THEN + DECLARE + B : Unbounded_Fraction := Bernoulli_Number (I); + S : String := Image (GMP.Rationals.Numerator (B)); + BEGIN + Put_Line ("B (" & (IF I < 10 THEN " " ELSE "") & Trim (I'Img, Left) + & ")=" & (44 - S'Length) * " " & Image (B)); + END; + END IF; + END LOOP; +END Main; diff --git a/Task/Bernoulli-numbers/Ada/bernoulli-numbers-2.adb b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-2.adb new file mode 100644 index 0000000000..16ff6c98fa --- /dev/null +++ b/Task/Bernoulli-numbers/Ada/bernoulli-numbers-2.adb @@ -0,0 +1,45 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit; use Strings_Edit; +with Strings_Edit.Integers; use Strings_Edit.Integers; +with Unbounded_Rationals; use Unbounded_Rationals; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Bernoulli is + function Bernoulli_Number (N : Natural) return Unbounded_Rational is + A : array (0..Half_Word (N)) of Unbounded_Rational; + begin + for M in 0..Half_Word (N) loop + A (M) := Unbounded_Rationals.One / (M + 1); + for J in reverse 1..M LOOP + A (J - 1) := J * (A (J - 1) - A (J)); + end loop; + end loop; + return A (0); + end Bernoulli_Number; + B : Unbounded_Rational; + Line : String (1..80); + Pointer : Integer; +begin + for I in 0..60 loop + if I mod 2 = 0 or else I = 1 then + B := Bernoulli_Number (I); + if not Is_Zero (B) then + Pointer := 1; + Put (Line, Pointer, "B("); + Put (Line, Pointer, I, 10, False, 2, Right); + Put (Line, Pointer, ") = "); + if Is_Negative (B) then + Put (Line, Pointer, '-' & Image (Get_Numerator (B)), 45, Right); + else + Put (Line, Pointer, Get_Numerator (B), 10, 45, Right); + end if; + Put (Line, Pointer, " / "); + Put (Line, Pointer, Get_Denominator (B)); + Put_Line (Line (1..Pointer - 1)); + end if; + end if; + end loop; +end Bernoulli; diff --git a/Task/Bernoulli-numbers/FutureBasic/bernoulli-numbers.basic b/Task/Bernoulli-numbers/FutureBasic/bernoulli-numbers.basic new file mode 100644 index 0000000000..b0d0000ba4 --- /dev/null +++ b/Task/Bernoulli-numbers/FutureBasic/bernoulli-numbers.basic @@ -0,0 +1,93 @@ +// +// Bernoulli Number +// Using FutureBasic 7.0.35 +// +// September 2025, R.W +// + +include "gmp.incl" + +_kMaxN = 200 // max Bernoulli terms + +mpq_t tmp +dim a( _kMaxN ) as mpq_t // workspace a(0.._kMaxN) + +// Bernoulli: +// B_m = -(1 / (m+1)) * sum_{k=0..m-1} binomial(m+1, k) * B_k + +local fn Bernoulli( rop as mpq_t, n as long ) + long m, j + if n < 0 then n = 0 + if n > _kMaxN then n = _kMaxN + for m = 1 to n + 1 + mpq_set_si( a(m-1), 1, m ) + // j = m-1..1 + for j = m - 1 to 1 step -1 + // a[j] = a[j+1] - a[j] with 0-based mapping + mpq_sub( a(j-1), a(j), a(j-1) ) + // multiply by j + mpq_set_si( tmp, j, 1 ) + mpq_mul( a(j-1), a(j-1), tmp ) + next + next + mpq_set( rop, a(0) ) +end fn + + +//-------------- Main --------- + +Window 1, @"Bernoulli Numbers",(0,0,500,500) + +CFStringRef cfnum, cfden, pLine, filler,sp,sp2 +Int terms +long i + +terms = 60 + +mpq_init( tmp ) +for i = 0 to terms + mpq_init( a(i) ) +next +filler = @" " +mpq_t rop +mpz_t num, den + +mpq_init( rop ) +mpz_init( num ) +mpz_init( den ) +pLine = @"" +for i = 0 to 60 step 2 + if i = 2 then i-- + if i = 3 then i-- + fn Bernoulli( rop, i ) + mpq_get_num( num, rop ) + if i == 1 + mpz_neg( num, num ) + end if + if fn mpz_cmp_si( num, 0 ) // nonzero? + mpq_get_den( den, rop ) + cfnum = fn mpz_cf(10, num) + cfden = fn mpz_cf(10, den) + if i < 10 + sp = @" " + else + sp = @"" + end if + sp2 = left(filler,44 - len(cfnum)) + pLine = concat(sp, @"B(",mid(str(i),1),@") = ",sp2 ,cfnum, @" / ", cfden) + print@ pLine + end if +next + +// clean up +for i = 0 to terms + mpq_clear( a(i) ) +next +mpq_clear( tmp ) +mpz_clear( den ) +mpz_clear( num ) +mpq_clear( rop ) + +HandleEvents + +// diff --git a/Task/Bernoulli-numbers/JavaScript/bernoulli-numbers.js b/Task/Bernoulli-numbers/JavaScript/bernoulli-numbers.js new file mode 100644 index 0000000000..c0a1f14c6b --- /dev/null +++ b/Task/Bernoulli-numbers/JavaScript/bernoulli-numbers.js @@ -0,0 +1,76 @@ +class Fraction { + constructor(numerator, denominator = 1) { + if (denominator === 0) throw new Error("Denominator cannot be zero"); + + // Convert to BigInt + this.numerator = BigInt(numerator); + this.denominator = BigInt(denominator); + + // Handle negative denominator + if (this.denominator < 0n) { + this.numerator = -this.numerator; + this.denominator = -this.denominator; + } + + // Simplify + const gcdVal = this.gcd(this.abs(this.numerator), this.abs(this.denominator)); + this.numerator = this.numerator / gcdVal; + this.denominator = this.denominator / gcdVal; + } + + abs(n) { + return n < 0n ? -n : n; + } + + gcd(a, b) { + while (b !== 0n) { + const temp = b; + b = a % b; + a = temp; + } + return a; + } + + subtract(other) { + const num = this.numerator * other.denominator - other.numerator * this.denominator; + const den = this.denominator * other.denominator; + return new Fraction(num, den); + } + + multiply(other) { + const num = this.numerator * other.numerator; + const den = this.denominator * other.denominator; + return new Fraction(num, den); + } + + equals(other) { + return this.numerator === other.numerator && this.denominator === other.denominator; + } + + toString() { + if (this.denominator === 1n) { + return this.numerator.toString(); + } + return `${this.numerator} / ${this.denominator}`; + } +} + +function bernoulli(n) { + const A = new Array(n + 1); + for (let m = 0; m <= n; m++) { + A[m] = new Fraction(1, m + 1); + for (let j = m; j >= 1; j--) { + A[j - 1] = A[j - 1].subtract(A[j]).multiply(new Fraction(j)); + } + } + return A[0]; +} + +// Main execution +const ZERO = new Fraction(0); +for (let n = 0; n <= 60; n++) { + const b = bernoulli(n); + if (!b.equals(ZERO)) { + console.log(`B(${n.toString().padEnd(2)}) = ${b}`); + } +} diff --git a/Task/Bernoulli-numbers/Pluto/bernoulli-numbers.pluto b/Task/Bernoulli-numbers/Pluto/bernoulli-numbers.pluto new file mode 100644 index 0000000000..2a23069296 --- /dev/null +++ b/Task/Bernoulli-numbers/Pluto/bernoulli-numbers.pluto @@ -0,0 +1,22 @@ +require "bignum" +local fmt = require "fmt" + +local function bernoulli(n) + assert(n >= 0, "Argument must be non-negative") + local a = table.create(n + 1) + for m = 0, n do + a[m + 1] = bigrat.recip(m + 1) + local j = m + while j >= 1 do + a[j] = (a[j] - a[j + 1]) * bigrat.int(j) + j -= 1 + end + end + return n != 1 ? a[1] : -a[1] --'first' Bernoulli number +end + +local zero = bigrat.int(0) +for n = 0, 60 do + local b = bernoulli(n) + if b != zero then fmt.print("B(%2d) = %44s / %s", n, b:getNum(), b:getDen()) end +end diff --git a/Task/Bernoulli-numbers/TAV/bernoulli-numbers-1.tav b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-1.tav new file mode 100644 index 0000000000..b24fd56d97 --- /dev/null +++ b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-1.tav @@ -0,0 +1,14 @@ +bernoulli (n): + a =: new row + for m =: from 0 upto n + a[m] =: 1 / (m + 1) + for j =: from m downto 1 + a[j-1] =: j * (a[j-1] - a[j]) + return a[0] + +main (p):+ + max =: string p.1 as integer else 60 \ max number as parameter + for i =: from 2 upto max step 2 + b =: bernoulli i + \ to align the slash, print numerator and denominator separately + print format "B(%2;) = %50; / %;" i, b.num, b.den diff --git a/Task/Bernoulli-numbers/TAV/bernoulli-numbers-2.tav b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-2.tav new file mode 100644 index 0000000000..67e1634b4b --- /dev/null +++ b/Task/Bernoulli-numbers/TAV/bernoulli-numbers-2.tav @@ -0,0 +1,22 @@ +main (parms):+ + n =: string parms[1] as integer else 30 + print n bernoullis + +\ ierative version as used by Ada Lovelace +print (max) bernoullis: + b =: [] + b[1] =: 1/6 + print 'B[1]=' _ b[1] + ?# n =: from 2 upto max + k =: 2*n - 1 + n2 =: 2*n + a0 =: - (n2 - 1) / (n2 + 1) / 2 + a1 =: n2 / 2 + x =: a0 + (b[1] * a1) + aj =: a1 + ?# j =: from 3 upto k-1 step 2 + aj =* (n2 - (j-2)) / j + aj =* (n2 - (j-1)) / (j + 1) + x =+ b[j] * aj + b[k] =: -x + print format "B(%2;) = %50; / %;" k, b[k].num, b[k].den diff --git a/Task/Best-shuffle/Ada/best-shuffle.adb b/Task/Best-shuffle/Ada/best-shuffle.adb new file mode 100644 index 0000000000..37b1b32286 --- /dev/null +++ b/Task/Best-shuffle/Ada/best-shuffle.adb @@ -0,0 +1,50 @@ +with Ada.Text_IO; +with Ada.Strings.Unbounded; + +procedure Best_Shuffle is + + function Best_Shuffle (S : String) return String; + + function Best_Shuffle (S : String) return String is + T : String (S'Range) := S; + Tmp : Character; + begin + for I in S'Range loop + for J in S'Range loop + if I /= J and S (I) /= T (J) and S (J) /= T (I) then + Tmp := T (I); + T (I) := T (J); + T (J) := Tmp; + end if; + end loop; + end loop; + return T; + end Best_Shuffle; + + Test_Cases : constant array (1 .. 6) + of Ada.Strings.Unbounded.Unbounded_String := + (Ada.Strings.Unbounded.To_Unbounded_String ("abracadabra"), + Ada.Strings.Unbounded.To_Unbounded_String ("seesaw"), + Ada.Strings.Unbounded.To_Unbounded_String ("elk"), + Ada.Strings.Unbounded.To_Unbounded_String ("grrrrrr"), + Ada.Strings.Unbounded.To_Unbounded_String ("up"), + Ada.Strings.Unbounded.To_Unbounded_String ("a")); + +begin -- main procedure + for Test_Case in Test_Cases'Range loop + declare + Original : constant String := Ada.Strings.Unbounded.To_String + (Test_Cases (Test_Case)); + Shuffle : constant String := Best_Shuffle (Original); + Score : Natural := 0; + begin + for I in Original'Range loop + if Original (I) = Shuffle (I) then + Score := Score + 1; + end if; + end loop; + Ada.Text_IO.Put_Line (Original & ", " & Shuffle & ", (" & + Natural'Image (Score) & " )"); + end; + end loop; +end Best_Shuffle; diff --git a/Task/Best-shuffle/Fortran/best-shuffle.f b/Task/Best-shuffle/Fortran/best-shuffle.f new file mode 100644 index 0000000000..8a02f8f4a4 --- /dev/null +++ b/Task/Best-shuffle/Fortran/best-shuffle.f @@ -0,0 +1,110 @@ +! +! Best Shuffle +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! +! VSI Fortran on VMS does not compile this code because its current version +! cannot handle allocatable character strings +! +! U.B., October 2025 +!============================================================================== + +program bestShuffle + + implicit none + + integer, parameter :: MAXLEN = 100 ! Maximum length of strings to shuffle + character (len=MAXLEN), dimension(:),allocatable :: wordsToShuffle ! Test cases as in task description + character (len=MAXLEN) shuffledWord ! Result of a shuffle operation + integer :: ii, nWords, scr ! little helpers + integer:: longest ! Length of longest test string + character (len=50) :: vFormat ! Variable format for printing + + wordsToShuffle = & ! Preset test cases + [character(len=MAXLEN) :: 'abcdefghijk', & ! all letters different -> always score 0 + 'abracadabra', & ! The other test cases from task description + 'seesaw', & + 'elk', & + 'grrrrrrr', & + 'up', & + 'a'] ! This style makes both ifx AND gfortran happy. + nWords = size (wordsToShuffle) ! Number of test cases + longest = 0 + do ii=1, nWords ! Find length of longest test string + longest = max (longest, len_trim(wordsToShuffle(ii))) + end do + + ! Create a variable format depending on the length of the longest test string, + ! to print the original string, the shuffled string and the score in three columns + write (vFormat,'("(A", i0, ", x, A, T", i0,", i0)" )') longest, 2*longest+3 + + ! Initialize random number generator once for the entire run-time of the program and all test cases + call random_seed() + + do ii = 1, nWords + ! Using the Sattolo cycle guarantees that each and every letter will be moved from its original + ! position. However, duplicate letters within a word can lead to shuffled words that have a score >0 + ! If all letters aof the string are different, score will be 0 each time this program is run. + call sattolo_cycle (wordsToShuffle(ii), shuffledWord, scr) + print vFormat, trim(wordsToShuffle(ii)), trim(shuffledWord), scr + end do + + contains + + !============================================================= + ! shuffle using the Sattolo algorithm, and calculate the score + ! @win: word to shuffle, @wout: resultant string + ! @resultantscore: with the obvious meaning + !============================================================= + subroutine sattolo_cycle (win, wout, resultantscore) + + character (len=MAXLEN) , intent (in) :: win ! The word to shuffle + character (len=MAXLEN) , intent (out) :: wout ! The resultant word after shuffling + character :: tmp ! for swapping single letters + integer, intent(out) :: resultantscore ! the calculated score of the resultant string + + integer :: j, k, l ! Helper variables: indices into words, words' length + + wout = win + l = len_trim (wout) + do j = l, 1, -1 ! For all letters from end down to begin + k = randominInterval (1, j-1) ! Select random letters between 1 and j-1 + tmp = wout(j:j) ! then swap letter at pos j with letter at pos k + wout (j:j) = wout (k:k) + wout(k:k) = tmp + end do + + resultantscore = score (win,wout,l) ! Calculate score + end subroutine sattolo_cycle + + + ! =========================================================== + ! Generate random number between @lo and @hi (inclusive) + ! Assume Random Number Generator has been initialized before. + ! =========================================================== + function randominInterval (lo, hi) result (r) + integer, intent(in) :: lo, hi ! the interval + integer :: r ! resultant (pseudo-)random number + real :: rnd ! Fortran random number generator generates float values + + call random_number (rnd) + r = lo + FLOOR((hi+1-lo)*rnd) ! We want to choose one between [lo,hi] + + end function randominInterval + + !=============================================================================== + ! Calculate score: count positions that have the same letter as before shuffling + !=============================================================================== + function score (win, wout, l) result (scr) + character (len=MAXLEN) , intent (in) :: win, wout ! The two words to compare + integer , intent(in) :: l ! Length of the words to consider + integer :: scr ! Resultant score + integer :: jj ! Loop index + + scr = 0 + do jj=1,l + if (win(jj:jj) .eq. wout(jj:jj) ) scr = scr + 1 + enddo + end function score + +end program bestShuffle diff --git a/Task/Best-shuffle/Pluto/best-shuffle.pluto b/Task/Best-shuffle/Pluto/best-shuffle.pluto new file mode 100644 index 0000000000..1f4a50c9bd --- /dev/null +++ b/Task/Best-shuffle/Pluto/best-shuffle.pluto @@ -0,0 +1,17 @@ +require "table2" +local fmt = require "fmt" + +local tests = {"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"} +for tests as s do + local t = s:split(""):shuffle() + for i = 1, #t do + for j = 1, #t do + if i != j and t[i] != s[j] and t[j] != s[i] then + t[i], t[j] = t[j], t[i] + break + end + end + end + local c = range(1, #s):count(|i| -> s[i] == t[i]) + fmt.print("%s, %s, (%d)\n", s, t:concat(""), c) +end diff --git a/Task/Best-shuffle/PowerShell/best-shuffle-1.ps1 b/Task/Best-shuffle/PowerShell/best-shuffle-1.ps1 new file mode 100644 index 0000000000..0bab21590c --- /dev/null +++ b/Task/Best-shuffle/PowerShell/best-shuffle-1.ps1 @@ -0,0 +1,52 @@ +# Calculate best possible shuffle score for a given string +# (Split out into separate function so we can use it separately in our output) +function Get-BestScore ( [string]$String ) + { + # Convert to array of characters, group identical characters, + # sort by frequecy, get size of first group + $MostRepeats = $String.ToCharArray() | + Group | + Sort Count -Descending | + Select -First 1 -ExpandProperty Count + + # Return count of most repeated character minus all other characters (math simplified) + return [math]::Max( 0, 2 * $MostRepeats - $String.Length ) + } + +function Get-BestShuffle ( [string]$String ) + { + # Convert to arrays of characters, one for comparison, one for manipulation + $S1 = $String.ToCharArray() + $S2 = $String.ToCharArray() + + # Calculate best possible score as our goal + $BestScore = Get-BestScore $String + + # Unshuffled string has score equal to number of characters + $Length = $String.Length + $Score = $Length + + # While still striving for perfection... + While ( $Score -gt $BestScore ) + { + # For each character + ForEach ( $i in 0..($Length-1) ) + { + # If the shuffled character still matches the original character... + If ( $S1[$i] -eq $S2[$i] ) + { + # Swap it with a random character + # (Random character $j may be the same as or may even be + # character $i. The minor impact on speed was traded for + # a simple solution to guarantee randomness.) + $j = Get-Random -Maximum $Length + $S2[$i], $S2[$j] = $S2[$j], $S2[$i] + } + } + # Count the number of indexes where the two arrays match + $Score = ( 0..($Length-1) ).Where({ $S1[$_] -eq $S2[$_] }).Count + } + # Put it back into a string + $Shuffle = ( [string[]]$S2 -join '' ) + return $Shuffle + } diff --git a/Task/Best-shuffle/PowerShell/best-shuffle-2.ps1 b/Task/Best-shuffle/PowerShell/best-shuffle-2.ps1 new file mode 100644 index 0000000000..3a491b67ff --- /dev/null +++ b/Task/Best-shuffle/PowerShell/best-shuffle-2.ps1 @@ -0,0 +1,6 @@ +ForEach ( $String in ( 'abracadabra', 'seesaw', 'elk', 'grrrrrr', 'up', 'a' ) ) + { + $Shuffle = Get-BestShuffle $String + $Score = Get-BestScore $String + "$String, $Shuffle, ($Score)" + } diff --git a/Task/Best-shuffle/V-(Vlang)/best-shuffle.v b/Task/Best-shuffle/V-(Vlang)/best-shuffle.v new file mode 100644 index 0000000000..082b173897 --- /dev/null +++ b/Task/Best-shuffle/V-(Vlang)/best-shuffle.v @@ -0,0 +1,30 @@ +fn best_shuffle(s1 string) string { + mut s2 := s1.clone() + len_s2 := s2.len + mut s2_bytes := s2.bytes() + s1_bytes := s1.bytes() + for i in 0 .. len_s2 { + for j in 0 .. len_s2 { + if i != j && s2_bytes[i] != s1_bytes[j] && s2_bytes[j] != s1_bytes[i] { + i1 := if j < i { j } else { i } + j1 := if j < i { i } else { j } + // swap characters at i1 and j1 in s2_bytes + s2_bytes[i1], s2_bytes[j1] = s2_bytes[j1], s2_bytes[i1] + } + } + } + return s2_bytes.bytestr() +} + +fn main() { + lista := ["abracadabra", "seesaw", "pop", "grrrrrr", "up", "a"] + mut puntos := 0 + for palabra in lista { + bs := best_shuffle(palabra) + puntos = 0 + for i := 0; i < palabra.len; i++ { + if palabra[i] == bs[i] { puntos++ } + } + println("$palabra ==> $bs (puntuación: $puntos)") + } +} diff --git a/Task/Best-shuffle/VBScript/best-shuffle.vbs b/Task/Best-shuffle/VBScript/best-shuffle.vbs new file mode 100644 index 0000000000..8d21c6236c --- /dev/null +++ b/Task/Best-shuffle/VBScript/best-shuffle.vbs @@ -0,0 +1,52 @@ +'Best Shuffle Task +'VBScript Implementation + +Function bestshuffle(s) + Dim arr:Redim arr(Len(s)-1) + + 'The Following Does the toCharArray() Functionality + For i = 0 To Len(s)-1 + arr(i) = Mid(s, i + 1, 1) + Next + + arr = shuffler(arr) 'Make this line a comment for deterministic solution + For i = 0 To UBound(arr):Do + If arr(i) <> Mid(s, i + 1, 1) Then Exit Do + For j = 0 To UBound(arr) + If arr(i) <> arr(j) And arr(i) <> Mid(s, j + 1, 1) And arr(j) <> Mid(s, i + 1, 1) Then + tmp = arr(i) + arr(i) = arr(j) + arr(j) = tmp + End If + Next + Loop While False:Next + + shuffled_word = Join(arr,"") + + 'This section is the scorer + score = 0 + For k = 1 To Len(s) + If Mid(s,k,1) = Mid(shuffled_word,k,1) Then + score = score + 1 + End If + Next + + bestshuffle = shuffled_word & ",(" & score & ")" +End Function + +Function shuffler(array) + Set rand = CreateObject("System.Random") + For i = UBound(array) to 0 Step -1 + r = rand.next_2(0, i + 1) + tmp = array(i) + array(i) = array(r) + array(r) = tmp + Next + shuffler = array +End Function + +'Testing the function +word_list = Array("abracadabra","seesaw","elk","grrrrrr","up","a") +For Each word In word_list + WScript.StdOut.WriteLine word & "," & bestshuffle(word) +Next diff --git a/Task/Bifid-cipher/Ada/bifid-cipher.adb b/Task/Bifid-cipher/Ada/bifid-cipher.adb new file mode 100644 index 0000000000..c066bfefe4 --- /dev/null +++ b/Task/Bifid-cipher/Ada/bifid-cipher.adb @@ -0,0 +1,30 @@ +-- Bifid cipher +-- J. Carter 2023 May +-- The Bifid cipher is included as part of the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Encryption.Bifid; + +procedure Bifid_Test is + package Bifid renames PragmARC.Encryption.Bifid; + + Key_1 : constant Bifid.Square_Layout := ("ABCDE", "FGHIK", "LMNOP", "QRSTU", "VWXYZ"); + Key_2 : constant Bifid.Square_Layout := ("BGWKZ", "QPNDS", "IOAXE", "FCLUM", "THYVR"); + + Msg_1 : constant String := "ATTACKATDAWN"; + Msg_2 : constant String := "FLEEATONCE"; + Msg_3 : constant String := "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; + + Crypt_1 : String (Msg_1'Range); + Crypt_2 : String (Msg_2'Range); + Crypt_3 : String (Msg_3'Range); +begin -- Bifid_Test + Crypt_1 := Bifid.Encrypt (Msg_1, Key_1); + Ada.Text_IO.Put_Line (Item => Msg_1 & " => " & Crypt_1 & " => " & Bifid.Decrypt (Crypt_1, Key_1) ); + Crypt_2 := Bifid.Encrypt (Msg_2, Key_2); + Ada.Text_IO.Put_Line (Item => Msg_2 & " => " & Crypt_2 & " => " & Bifid.Decrypt (Crypt_2, Key_2) ); + Crypt_1 := Bifid.Encrypt (Msg_1, Key_2); + Ada.Text_IO.Put_Line (Item => Msg_1 & " => " & Crypt_1 & " => " & Bifid.Decrypt (Crypt_1, Key_2) ); + Crypt_3 := Bifid.Encrypt (Msg_3, Key_2); + Ada.Text_IO.Put_Line (Item => Msg_3 & " => " & Crypt_3 & " => " & Bifid.Decrypt (Crypt_3, Key_2) ); +end Bifid_Test; diff --git a/Task/Bifid-cipher/C++/bifid-cipher.cpp b/Task/Bifid-cipher/C++/bifid-cipher.cpp index 0e93a81f8a..411515802a 100644 --- a/Task/Bifid-cipher/C++/bifid-cipher.cpp +++ b/Task/Bifid-cipher/C++/bifid-cipher.cpp @@ -9,104 +9,104 @@ typedef std::pair point; class Bifid { public: - Bifid(const int32_t n, std::string_view text) { - if ( text.length() != n * n ) { - throw std::invalid_argument("Incorrect length of text"); - } + Bifid(const int32_t n, std::string_view text) { + if ( text.length() != n * n ) { + throw std::invalid_argument("Incorrect length of text"); + } - grid.resize(n); - for ( uint64_t i = 0; i < grid.size(); i++ ) { - grid[i].resize(n); - } + grid.resize(n); + for ( uint64_t i = 0; i < grid.size(); i++ ) { + grid[i].resize(n); + } - int32_t row = 0; - int32_t col = 0; - for ( const char& ch : text ) { - grid[row][col] = ch; - coordinates[ch] = point(row, col); - col += 1; - if ( col == n ) { - col = 0; - row += 1; - } - } + int32_t row = 0; + int32_t col = 0; + for ( const char& ch : text ) { + grid[row][col] = ch; + coordinates[ch] = point(row, col); + col += 1; + if ( col == n ) { + col = 0; + row += 1; + } + } - if ( n == 5 ) { - coordinates['J'] = coordinates['I']; - } - } + if ( n == 5 ) { + coordinates['J'] = coordinates['I']; + } + } - std::string encrypt(std::string_view text) { - std::vector row_one, row_two; - for ( const char& ch : text ) { - point coordinate = coordinates[ch]; - row_one.push_back(coordinate.first); - row_two.push_back(coordinate.second); - } + std::string encrypt(std::string_view text) { + std::vector row_one, row_two; + for ( const char& ch : text ) { + point coordinate = coordinates[ch]; + row_one.push_back(coordinate.first); + row_two.push_back(coordinate.second); + } - row_one.insert(row_one.end(), row_two.begin(), row_two.end()); - std::string result; - for ( uint64_t i = 0; i < row_one.size() - 1; i += 2 ) { - result += grid[row_one[i]][row_one[i + 1]]; - } - return result; - } + row_one.insert(row_one.end(), row_two.begin(), row_two.end()); + std::string result; + for ( uint64_t i = 0; i < row_one.size() - 1; i += 2 ) { + result += grid[row_one[i]][row_one[i + 1]]; + } + return result; + } - std::string decrypt(std::string_view text) { - std::vector row; - for ( const char& ch : text ) { - point coordinate = coordinates[ch]; - row.push_back(coordinate.first); - row.push_back(coordinate.second); - } + std::string decrypt(std::string_view text) { + std::vector row; + for ( const char& ch : text ) { + point coordinate = coordinates[ch]; + row.push_back(coordinate.first); + row.push_back(coordinate.second); + } - const int middle = row.size() / 2; - std::vector row_one = { row.begin(), row.begin() + middle }; - std::vector row_two = { row.begin() + middle, row.end() }; - std::string result; - for ( int32_t i = 0; i < middle; i++ ) { - result += grid[row_one[i]][row_two[i]]; - } - return result; - } + const int middle = row.size() / 2; + std::vector row_one = { row.begin(), row.begin() + middle }; + std::vector row_two = { row.begin() + middle, row.end() }; + std::string result; + for ( int32_t i = 0; i < middle; i++ ) { + result += grid[row_one[i]][row_two[i]]; + } + return result; + } - void display() const { - for ( const std::vector& row : grid ) { - for ( const char& ch : row ) { - std::cout << ch << " "; - } - std::cout << std::endl; - } - } + void display() const { + for ( const std::vector& row : grid ) { + for ( const char& ch : row ) { + std::cout << ch << " "; + } + std::cout << std::endl; + } + } private: - std::vector> grid; - std::unordered_map coordinates; + std::vector> grid; + std::unordered_map coordinates; }; void runTest(Bifid& bifid, std::string_view message) { - std::cout << "Using Polybius square:" << std::endl; - bifid.display(); - std::cout << "Message: " << message << std::endl; - std::string encrypted = bifid.encrypt(message); - std::cout << "Encrypted: " << encrypted << std::endl; - std::string decrypted = bifid.decrypt(encrypted); - std::cout << "Decrypted: " << decrypted << std::endl; - std::cout << std::endl; + std::cout << "Using Polybius square:" << std::endl; + bifid.display(); + std::cout << "Message: " << message << std::endl; + std::string encrypted = bifid.encrypt(message); + std::cout << "Encrypted: " << encrypted << std::endl; + std::string decrypted = bifid.decrypt(encrypted); + std::cout << "Decrypted: " << decrypted << std::endl; + std::cout << std::endl; } int main() { - const std::string_view message1 = "ATTACKATDAWN"; - const std::string_view message2 = "FLEEATONCE"; - const std::string_view message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; + const std::string_view message1 = "ATTACKATDAWN"; + const std::string_view message2 = "FLEEATONCE"; + const std::string_view message3 = "THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY"; - Bifid bifid1(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); - Bifid bifid2(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); + Bifid bifid1(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); + Bifid bifid2(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); - runTest(bifid1, message1); - runTest(bifid2, message2); - runTest(bifid2, message1); - runTest(bifid1, message2); + runTest(bifid1, message1); + runTest(bifid2, message2); + runTest(bifid2, message1); + runTest(bifid1, message2); - Bifid bifid3(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); - runTest(bifid3, message3); + Bifid bifid3(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + runTest(bifid3, message3); } diff --git a/Task/Bifid-cipher/Crystal/bifid-cipher.cr b/Task/Bifid-cipher/Crystal/bifid-cipher.cr new file mode 100644 index 0000000000..ce327b9dfa --- /dev/null +++ b/Task/Bifid-cipher/Crystal/bifid-cipher.cr @@ -0,0 +1,46 @@ +enum BifidOp + Encode + Decode +end + +def bifid_encode (message, alphabet, op : BifidOp = :encode) + square = alphabet.chars + side = Math.isqrt(square.size) + raise "alphabet not a square" unless side*side == square.size + chars = message.chars + raise "incomplete alphabet" unless chars.all?(&.in? square) + + coords = chars.flat_map {|ch| [*square.index!(ch).divmod(side)] } + + coords = if op.encode? + (0...coords.size).step(2).map {|i| coords[i] }.to_a + + (1...coords.size).step(2).map {|i| coords[i] }.to_a + else + half = coords.size//2 + coords[...half].zip(coords[half..]).map {|c1, c2| + [c1, c2] + }.flatten + end + coords.each_slice(2).map {|(row, col)| + square[row * side + col] + }.join +end + +poly1 = "ABCDEFGHIKLMNOPQRSTUVWXYZ" +poly2 = "BGWKZQPNDSIOAXEFCLUMTHYVR" +superpoly = (' '..'~').join + "¡éßñø" + +attack = "ATTACKATDAWN" +flee = "FLEEATONCE" +invasion = "The invasion will start on the first of January".upcase.tr("J", "I").delete("^A-Z") +ataque = "¡Attack on 1/1 at 23:59, señor!" + +[{attack, poly1}, {flee, poly2}, {attack, poly2}, + {invasion, poly1}, {ataque, superpoly}].each do |message, alphabet| + encoded = bifid_encode(message, alphabet) + decoded = bifid_encode(encoded, alphabet, :decode) + puts "Message: #{message} #{alphabet.size > 80 ? "\n" : " "}- Alphabet: #{alphabet}" + puts "Encoded: #{encoded}" + puts "Decoded: #{decoded}" + puts +end diff --git a/Task/Bifid-cipher/EMal/bifid-cipher.emal b/Task/Bifid-cipher/EMal/bifid-cipher.emal index d3e0d7b680..786b4e3400 100644 --- a/Task/Bifid-cipher/EMal/bifid-cipher.emal +++ b/Task/Bifid-cipher/EMal/bifid-cipher.emal @@ -18,13 +18,13 @@ model end fun asText ← text by block text result - for int y ← 0; y < me.grid.length; y++ - for int x ← 0; x < me.grid[y].length; x++ - result.append(" " + me.grid[y][x]) - end - result.appendLine() - end - return result + for int y ← 0; y < me.grid.length; y++ + for int x ← 0; x < me.grid[y].length; x++ + result.append(" " + me.grid[y][x]) + end + result.appendLine() + end + return result end end type BifidCipher diff --git a/Task/Bifid-cipher/Fortran/bifid-cipher.f b/Task/Bifid-cipher/Fortran/bifid-cipher.f new file mode 100644 index 0000000000..4d804626f9 --- /dev/null +++ b/Task/Bifid-cipher/Fortran/bifid-cipher.f @@ -0,0 +1,219 @@ +! +! Bifid cipher +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! +! U.B., October 2025 +!============================================================================== + +program BifidCipher + +implicit none + +! Constants: + +integer, parameter :: nTests = 6 ! NUmber of different test messages +integer, parameter :: maxLen=100 ! Maximum length of any test message + +! Instead of drawing the Polybius squares, we only define the alphabet to applied and calculate +! row and column number on the fly when needed. +! If necessary, the Encrypt and Decrypt subroutines extend the alphabets using "SpareAlpha" +! until the total length of the extended alphabet is a square number. This is important because +! otherwise the enccrypt or decrypt algorithm may calculate a row/column combination that is +! not used by the actual alphabet. + +! The alphabet as shown in the task description has no J. +character (len=*), parameter :: Alphabet_no_J ='ABCDEFGHIKLMNOPQRSTUVWXYZ' + +! The alphabet of capital letters as used in most western languages +character (len=*), parameter :: Alphabet_With_J ='ABCDEFGHIJKLMNOPQRSTUVWXYZ' + +! The square in the wikipedia article in 1 long string: +character (len=*), parameter :: AlternateAlphabet = 'BGWKZQPNDSIOAXEFCLUMTHYVR' + +! Standard Alphabet with CAPITAL and small letters +character (len=*), parameter :: Alphabet_withSmallLetters = & + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + +! Printable spare characters to extend alphabets so the total length becomes the +! next larger square number > the alphabet's length +character (len=*), parameter :: SpareAlpha = '1234567890!"§$%&/()=' ! omitted ! and " + +! Variables: + +character (len=maxLen) :: MsgToEncrypt (nTests), EncryptedMsg (nTests), DecryptedMsg (nTests) + +integer :: ColWidth ! Is variable and depends on length of the used alphabet + +integer :: i, lx + +! The test strings: (1) is from the task description, (2) is from the Wikipedia Article, (3) is +! the additional message as presented in the task description +MsgToEncrypt(1) = 'ATTACKATDAWN' +MsgToEncrypt(2) = 'FLEEATONCE' +MsgToEncrypt(3) = 'THEINVASIONWILLSTARTONTHEFIRSTOFJANUARY' + +! Same text, with both small and capital letters, to be used with an extended Polybius square +MsgToEncrypt(4) = 'AttackAtDawn' +MsgToEncrypt(5) = 'FleeAtOnce' +MsgToEncrypt(6) = 'TheInvasionWillStartOnTheFirstOfJanuary' + +print '(A/)', 'Using the alphabet and Polybius square without "J"' +call PrintSquare (Alphabet_no_J) +do i=1, nTests/2 + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , Alphabet_no_J) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , Alphabet_no_J) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +enddo + +print '(/A/)', 'Using the extended alphabet and Polybius square that includes "J"' +call PrintSquare (Alphabet_with_J) +do i=1, nTests/2 + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , Alphabet_with_J) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , Alphabet_with_J) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +end do + +print '(/A/)', 'Using the alphabet and Polybius square as shown in the Wikipedia article (no J!)' +call PrintSquare (AlternateAlphabet) +do i=1, nTests/2 + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , AlternateAlphabet) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , AlternateAlphabet) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +end do + +print '(/A/)', 'Using the extended alphabet with both upper case and lower case letters, including J and j' +call PrintSquare (Alphabet_withSmallLetters) +do i=nTests/2+1, nTests + lx = len_trim (MsgToEncrypt(i)) + call encrypt (MsgToEncrypt(i)(:lx) , EncryptedMsg (i) , Alphabet_withSmallLetters) + call decrypt (EncryptedMsg(i) (:lx), DecryptedMsg (i) , Alphabet_withSmallLetters) + print '(A, " => ", A, " => ", A)', MsgToEncrypt(i)(:lx), EncryptedMsg (i)(:lx), DecryptedMsg (i)(:lx) +end do + +contains + +!====================== +! Encode a given string +! ====================== +subroutine encrypt (inString,outString, argAlphabet) +character (len=*), intent(in) :: argAlphabet +character (len=*), intent(in) :: inString +character (len=*), intent(out) :: outString +character (len=100) :: Alphabet + +integer :: idxLine(2*maxLen) +integer :: l, ii, idx, row, col + +! Calculate required column width: so that ColWidth^2 >= (length of Alphabet) +Alphabet = argAlphabet +l = len_trim(alphabet) +ColWidth = 1 +do while (ColWidth*ColWidth .lt. l) + ColWidth = ColWidth + 1 +end do +if (ColWidth .gt.8) stop 'ERROR: Cannot handle Alphabets with more than 64 characters.' +! Provide some printable chars until the length is a square number +Alphabet (l+1:) = SpareAlpha + +l = len_trim (inString) +if (l .gt. len(outString)) stop 'ERROR: not enough storage space for encrypt result string.' + +do ii=1, l +! print *, ' ii = ', ii, ' instring(ii) = ', inString(ii:ii) + idx = index (Alphabet, inString(ii:ii)) + if (idx .eq. 0) idx = index (Alphabet, char(ichar(instring(ii:ii))-1)) ! J=I, j=i, just in case + row = (idx+ColWidth-1) / ColWidth ! e.g. 'A' ...'E', idx=1...5, row=(5...9)/5 = 1, col = 1...5 + col = 1+mod (idx+ColWidth-1, ColWidth) ! e.g. 'F' ...'K', idx=6...10, row=(10...14)/5 = 2, col = 1...5 + idxLine (ii) = row + idxLine (ii+l) = col +end do + +do ii=1, l + idx = 10*idxLine(1+2*(ii-1)) + idxLine (2+2*(ii-1)) + row = idxLine(1+2*(ii-1)) + col = idxLine (2+2*(ii-1)) + idx = ColWidth*(row-1) + col + outString (ii:ii) = alphabet (idx:idx) +enddo +end subroutine encrypt + + +!====================== +! Decode a given string +!====================== +subroutine decrypt (inString,outString, argAlphabet) + +character (len=*), intent(in) :: inString +character (len=*), intent(out) :: outString +character (len=*), intent(in) :: argAlphabet + +character (len=100) :: Alphabet + +integer :: idxLine(2*maxLen) +integer :: l, ii, idx, row, col + +! Calculate required column width: so that ColWidth^2 >= (length of Alphabet) +Alphabet = argAlphabet +l = len_trim(alphabet) +ColWidth = 1 +do while (ColWidth*ColWidth .lt. l) + ColWidth = ColWidth + 1 +end do + +! Append some spare characters so that the square is completely filled without undefined fields +Alphabet (l+1:) = SpareAlpha + +l = len_trim (inString) +if (l .gt. len(outString)) stop 'ERROR: not enough storage space for decrypt result string.' + +do ii=1, l + idx = index (Alphabet, inString(ii:ii)) + row = (idx+ColWidth-1) / ColWidth ! idx 1...5 is row 1, 6...10 is row 2 etc + col = 1+mod (idx+ColWidth-1, ColWidth) ! so that 21...29 -> 1...9 etc. + idxLine (1+2*(ii-1)) = row + idxLine (2+2*(ii-1)) = col +end do + +do ii=1, l + row = idxLine (ii) + col = idxLine (ii+l) + idx = ColWidth*(row-1) + col + outString (ii:ii) = alphabet (idx:idx) +end do + +end subroutine decrypt + + +! ================================================================================ +! Print the resulting Polybius square based on the alphabet used for encode/decode +! ================================================================================ +subroutine PrintSquare (Alphabet) +character (len=*), intent(in) :: Alphabet +integer:: ii, l + +l = len_trim(alphabet) +ColWidth = 1 +do while (ColWidth*ColWidth .lt. l) + ColWidth = ColWidth + 1 +end do +print '("The alphabet has a length of ", I0, " so it requires the square size of ", I0, "x", I0 /)' , l, ColWidth, ColWidth + +do ii=1, ColWidth*ColWidth + if (ii .le. l) then + write (*, '(A2)', advance='no') Alphabet(ii:ii) + else + write (*, '(A2)', advance='no') SpareAlpha (ii-l:ii-l) ! Use spares to complete the square + endif + if (mod (ii, ColWidth) .eq. 0) print * ! End of line +end do +print * ! one extra blank line +end subroutine PrintSquare + + +end program BifidCipher diff --git a/Task/Bifid-cipher/Go/bifid-cipher.go b/Task/Bifid-cipher/Go/bifid-cipher.go index c8a6cfa6fe..ad8846cf1b 100644 --- a/Task/Bifid-cipher/Go/bifid-cipher.go +++ b/Task/Bifid-cipher/Go/bifid-cipher.go @@ -5,176 +5,176 @@ package main import ( - "fmt" - "strings" + "fmt" + "strings" ) var ( - squareRosetta [][]byte = [][]byte{ //rosettacode - {'A', 'B', 'C', 'D', 'E'}, - {'F', 'G', 'H', 'I', 'K'}, - {'L', 'M', 'N', 'O', 'P'}, - {'Q', 'R', 'S', 'T', 'U'}, - {'V', 'W', 'X', 'Y', 'Z'}, - {'J', '1', '2', '3', '4'}, - } + squareRosetta [][]byte = [][]byte{ //rosettacode + {'A', 'B', 'C', 'D', 'E'}, + {'F', 'G', 'H', 'I', 'K'}, + {'L', 'M', 'N', 'O', 'P'}, + {'Q', 'R', 'S', 'T', 'U'}, + {'V', 'W', 'X', 'Y', 'Z'}, + {'J', '1', '2', '3', '4'}, + } - squareWikipedia [][]byte = [][]byte{ // wikipedia + squareWikipedia [][]byte = [][]byte{ // wikipedia - {'B', 'G', 'W', 'K', 'Z'}, - {'Q', 'P', 'N', 'D', 'S'}, - {'I', 'O', 'A', 'X', 'E'}, - {'F', 'C', 'L', 'U', 'M'}, - {'T', 'H', 'Y', 'V', 'R'}, - {'J', '1', '2', '3', '4'}, - } + {'B', 'G', 'W', 'K', 'Z'}, + {'Q', 'P', 'N', 'D', 'S'}, + {'I', 'O', 'A', 'X', 'E'}, + {'F', 'C', 'L', 'U', 'M'}, + {'T', 'H', 'Y', 'V', 'R'}, + {'J', '1', '2', '3', '4'}, + } - textRosetta string = "0ATTACKATDAWN" - textRosettaEncoded string = "DQBDAXDQPDQH" // only for test - textWikipedia string = "FLEEATONCE" - textWikipediaEncoded string = "UAEOLWRINS" // only for test - textTest string = "The invasion will start on the first of January" - textTextEncoded string = "RASOAQXFIOORXESXADETSWLTNIAZQOISBRGBALY" // only for test + textRosetta string = "0ATTACKATDAWN" + textRosettaEncoded string = "DQBDAXDQPDQH" // only for test + textWikipedia string = "FLEEATONCE" + textWikipediaEncoded string = "UAEOLWRINS" // only for test + textTest string = "The invasion will start on the first of January" + textTextEncoded string = "RASOAQXFIOORXESXADETSWLTNIAZQOISBRGBALY" // only for test ) type koord struct { - X byte - Y byte + X byte + Y byte } func (k *koord) LessThen(other *koord) bool { - if k.Y > other.Y { - return false - } - if k.Y < other.Y { - return true - } - if k.X < other.X { - return true - } - return false + if k.Y > other.Y { + return false + } + if k.Y < other.Y { + return true + } + if k.X < other.X { + return true + } + return false } func (k *koord) EqualTo(other koord) bool { - if k.X == other.X && k.Y == other.Y { - return true - } - return false + if k.X == other.X && k.Y == other.Y { + return true + } + return false } var encryptMap map[byte]koord var decryptMap map[koord]byte func squareToMaps(square [][]byte) (map[byte]koord, map[koord]byte) { - eMap := make(map[byte]koord) - dMap := make(map[koord]byte) - for x, col := range square { - for y, v := range col { - eMap[v] = koord{byte(x), byte(y)} - dMap[koord{byte(x), byte(y)}] = v + eMap := make(map[byte]koord) + dMap := make(map[koord]byte) + for x, col := range square { + for y, v := range col { + eMap[v] = koord{byte(x), byte(y)} + dMap[koord{byte(x), byte(y)}] = v - } - } - return eMap, dMap + } + } + return eMap, dMap } func removeSpaceI(text string) string { - var n string - s := strings.ToUpper(text) - for _, b := range []byte(s) { - //use only ASCII Characters from A to Z - if b < 'A' || b > 'Z' { - continue - } - if b == 'J' { - b = 'I' - } - n = n + string(b) - } - return n + var n string + s := strings.ToUpper(text) + for _, b := range []byte(s) { + //use only ASCII Characters from A to Z + if b < 'A' || b > 'Z' { + continue + } + if b == 'J' { + b = 'I' + } + n = n + string(b) + } + return n } func removeSpace(text string, square map[byte]koord) string { - var n string - //to UpperCase and then remove all Spaces an Characters witch are not in square - s := strings.ReplaceAll(strings.ToUpper(text), " ", "") - for _, b := range []byte(s) { - _, ok := square[b] - if ok { - n = n + string(b) - } - } - return n + var n string + //to UpperCase and then remove all Spaces an Characters witch are not in square + s := strings.ReplaceAll(strings.ToUpper(text), " ", "") + for _, b := range []byte(s) { + _, ok := square[b] + if ok { + n = n + string(b) + } + } + return n } func encrypt(text string, emap map[byte]koord, dmap map[koord]byte) string { - text = removeSpace(text, emap) - var row0, row1 []byte - for _, b := range []byte(text) { - xy := emap[b] - row0 = append(row0, xy.X) - row1 = append(row1, xy.Y) - } - row0 = append(row0, row1...) + text = removeSpace(text, emap) + var row0, row1 []byte + for _, b := range []byte(text) { + xy := emap[b] + row0 = append(row0, xy.X) + row1 = append(row1, xy.Y) + } + row0 = append(row0, row1...) - var s string - for i := 0; i < len(row0); i += 2 { - s = s + string(dmap[koord{row0[i], row0[i+1]}]) - } - return s + var s string + for i := 0; i < len(row0); i += 2 { + s = s + string(dmap[koord{row0[i], row0[i+1]}]) + } + return s } func decrypt(text string, emap map[byte]koord, dmap map[koord]byte) string { - text = removeSpace(text, emap) - k := make([]koord, len(text)) + text = removeSpace(text, emap) + k := make([]koord, len(text)) - for i, b := range []byte(text) { - k[i] = emap[b] - } + for i, b := range []byte(text) { + k[i] = emap[b] + } - kl := make([]byte, len(k)*2) - i := int(0) - for _, ki := range k { - kl[i] = ki.X - kl[i+1] = ki.Y - i += 2 - } - l := len(kl) / 2 - k1 := kl[:l] - k2 := kl[l:] - var s string + kl := make([]byte, len(k)*2) + i := int(0) + for _, ki := range k { + kl[i] = ki.X + kl[i+1] = ki.Y + i += 2 + } + l := len(kl) / 2 + k1 := kl[:l] + k2 := kl[l:] + var s string - for i := 0; i < l; i++ { - s = s + string(dmap[koord{k1[i], k2[i]}]) - } - return s + for i := 0; i < l; i++ { + s = s + string(dmap[koord{k1[i], k2[i]}]) + } + return s } func main() { - encryptMap, decryptMap = squareToMaps(squareRosetta) - fmt.Println("from Rosettacode") - fmt.Println("original:\t", textRosetta) - s := encrypt(textRosetta, encryptMap, decryptMap) - fmt.Println("codiert:\t", s) - s = decrypt(s, encryptMap, decryptMap) - fmt.Println("and back:\t", s) + encryptMap, decryptMap = squareToMaps(squareRosetta) + fmt.Println("from Rosettacode") + fmt.Println("original:\t", textRosetta) + s := encrypt(textRosetta, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) - fmt.Println("from Wikipedia") - encryptMap, decryptMap = squareToMaps(squareWikipedia) - fmt.Println("original:\t", textWikipedia) - s = encrypt(textWikipedia, encryptMap, decryptMap) - fmt.Println("codiert:\t", s) - s = decrypt(s, encryptMap, decryptMap) - fmt.Println("and back:\t", s) + fmt.Println("from Wikipedia") + encryptMap, decryptMap = squareToMaps(squareWikipedia) + fmt.Println("original:\t", textWikipedia) + s = encrypt(textWikipedia, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) - encryptMap, decryptMap = squareToMaps(squareWikipedia) - fmt.Println("from Rosettacode long part") - fmt.Println("original:\t", textTest) - s = encrypt(textTest, encryptMap, decryptMap) - fmt.Println("codiert:\t", s) - // Wenn der Text eine ungerade Anzahl Buchstaben hat, funktioniert der Algorithmus nicht!!! - s = decrypt(s, encryptMap, decryptMap) - fmt.Println("and back:\t", s) + encryptMap, decryptMap = squareToMaps(squareWikipedia) + fmt.Println("from Rosettacode long part") + fmt.Println("original:\t", textTest) + s = encrypt(textTest, encryptMap, decryptMap) + fmt.Println("codiert:\t", s) + // Wenn der Text eine ungerade Anzahl Buchstaben hat, funktioniert der Algorithmus nicht!!! + s = decrypt(s, encryptMap, decryptMap) + fmt.Println("and back:\t", s) } diff --git a/Task/Bifid-cipher/Java/bifid-cipher.java b/Task/Bifid-cipher/Java/bifid-cipher.java index a4a88f3db9..90b4f09174 100644 --- a/Task/Bifid-cipher/Java/bifid-cipher.java +++ b/Task/Bifid-cipher/Java/bifid-cipher.java @@ -7,101 +7,101 @@ import java.util.Map; public final class BifidCipher { - public static void main(String[] aArgs) { - final String message1 = "ATTACKATDAWN"; - final String message2 = "FLEEATONCE"; - final String message3 = "The invasion will start on the first of January".toUpperCase().replace(" ", ""); - - Bifid bifid1 = new Bifid(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); - Bifid bifid2 = new Bifid(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); - - runTest(bifid1, message1); - runTest(bifid2, message2); - runTest(bifid2, message1); - runTest(bifid1, message2); - - Bifid bifid3 = new Bifid(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); - runTest(bifid3, message3); - } - - private static void runTest(Bifid aBifid, String aMessage) { - System.out.println("Using Polybius square:"); - aBifid.display(); - System.out.println("Message: " + aMessage); - String encrypted = aBifid.encrypt(aMessage); - System.out.println("Encrypted: " + encrypted); - String decrypted = aBifid.decrypt(encrypted); - System.out.println("Decrypted: " + decrypted); - System.out.println(); - } - + public static void main(String[] aArgs) { + final String message1 = "ATTACKATDAWN"; + final String message2 = "FLEEATONCE"; + final String message3 = "The invasion will start on the first of January".toUpperCase().replace(" ", ""); + + Bifid bifid1 = new Bifid(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); + Bifid bifid2 = new Bifid(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); + + runTest(bifid1, message1); + runTest(bifid2, message2); + runTest(bifid2, message1); + runTest(bifid1, message2); + + Bifid bifid3 = new Bifid(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + runTest(bifid3, message3); + } + + private static void runTest(Bifid aBifid, String aMessage) { + System.out.println("Using Polybius square:"); + aBifid.display(); + System.out.println("Message: " + aMessage); + String encrypted = aBifid.encrypt(aMessage); + System.out.println("Encrypted: " + encrypted); + String decrypted = aBifid.decrypt(encrypted); + System.out.println("Decrypted: " + decrypted); + System.out.println(); + } + } - + final class Bifid { - - public Bifid(int aN, String aText) { - if ( aText.length() != aN * aN ) { - throw new IllegalArgumentException("Incorrect length of text"); - } - - grid = new char[aN][aN]; - int row = 0; - int col = 0; - for ( char ch : aText.toCharArray() ) { - grid[row][col] = ch; - coordinates.put(ch, new Point(row, col) ); - col += 1; - if ( col == aN ) { - col = 0; - row += 1; - } - } - - if ( aN == 5 ) { - coordinates.put('J', coordinates.get('I')); - } - } - - public String encrypt(String aText) { - List rowOne = new ArrayList(); - List rowTwo = new ArrayList(); - for ( char ch : aText.toCharArray() ) { - Point coordinate = coordinates.get(ch); - rowOne.add(coordinate.x); - rowTwo.add(coordinate.y); - } - - rowOne.addAll(rowTwo); - StringBuilder result = new StringBuilder(); - for ( int i = 0; i < rowOne.size() - 1; i += 2 ) { - result.append(grid[rowOne.get(i)][rowOne.get(i + 1)]); - } - return result.toString(); - } - - public String decrypt(String aText) { - List row = new ArrayList(); - for ( char ch : aText.toCharArray() ) { - Point coordinate = coordinates.get(ch); - row.add(coordinate.x); - row.add(coordinate.y); - } - - final int middle = row.size() / 2; - List rowOne = row.subList(0, middle); - List rowTwo = row.subList(middle, row.size()); - StringBuilder result = new StringBuilder(); - for ( int i = 0; i < middle; i++ ) { - result.append(grid[rowOne.get(i)][rowTwo.get(i)]); - } - return result.toString(); - } + + public Bifid(int aN, String aText) { + if ( aText.length() != aN * aN ) { + throw new IllegalArgumentException("Incorrect length of text"); + } + + grid = new char[aN][aN]; + int row = 0; + int col = 0; + for ( char ch : aText.toCharArray() ) { + grid[row][col] = ch; + coordinates.put(ch, new Point(row, col) ); + col += 1; + if ( col == aN ) { + col = 0; + row += 1; + } + } + + if ( aN == 5 ) { + coordinates.put('J', coordinates.get('I')); + } + } + + public String encrypt(String aText) { + List rowOne = new ArrayList(); + List rowTwo = new ArrayList(); + for ( char ch : aText.toCharArray() ) { + Point coordinate = coordinates.get(ch); + rowOne.add(coordinate.x); + rowTwo.add(coordinate.y); + } + + rowOne.addAll(rowTwo); + StringBuilder result = new StringBuilder(); + for ( int i = 0; i < rowOne.size() - 1; i += 2 ) { + result.append(grid[rowOne.get(i)][rowOne.get(i + 1)]); + } + return result.toString(); + } + + public String decrypt(String aText) { + List row = new ArrayList(); + for ( char ch : aText.toCharArray() ) { + Point coordinate = coordinates.get(ch); + row.add(coordinate.x); + row.add(coordinate.y); + } + + final int middle = row.size() / 2; + List rowOne = row.subList(0, middle); + List rowTwo = row.subList(middle, row.size()); + StringBuilder result = new StringBuilder(); + for ( int i = 0; i < middle; i++ ) { + result.append(grid[rowOne.get(i)][rowTwo.get(i)]); + } + return result.toString(); + } public void display() { - Arrays.stream(grid).forEach( row -> System.out.println(Arrays.toString(row)) ); - } - - private char[][] grid; - private Map coordinates = new HashMap(); - + Arrays.stream(grid).forEach( row -> System.out.println(Arrays.toString(row)) ); + } + + private char[][] grid; + private Map coordinates = new HashMap(); + } diff --git a/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 b/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 index 67d507af7a..b0234f8353 100644 --- a/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 +++ b/Task/Bifid-cipher/M2000-Interpreter/bifid-cipher.m2000 @@ -1,64 +1,64 @@ module Bifid_cipher (f, code$) { - n=sqrt(len(code$)) - print #f," "; - for i=1 to n - print #f, i+" "; - next - print #f - for i=0 to n-1 - Print #f, (i+1)+" "+STR$(mid$(code$,1+i*n, n),STRING$("@ ", 5)) - next - tables=lambda (a$)->{ - n=sqrt(len(a$)) - a=list - for i=1 to len(a$) - append a, mid$(a$,i, 1):=((i-1) mod n+1, (i-1) div n+1 ) - next - b=list - m=each(a) - while m - z=eval(m) - append b, z#val$(1)+z#val$(0):=eval$(m!) - end while - =a, b - }(code$) - encode= lambda (a, b)->{ - =lambda a,b (mess as string) -> { - document code$ - for n=1 to 0 - for i=1 to len(mess) - q=mid$(mess, i,1) - if not exist(a, q) then - if q="J" then q="I" else q="A" - end if - code$=a(q)#val$(n) - next - next - document final$ - for i=1 to len(code$) step 2 - final$=b$(mid$(code$, i, 2)) - next - = final$ - } - }(!tables) - decode= lambda (a, b)->{ - =lambda a,b (final as string) -> { - document code$, mess$ - for i=1 to len(final) - q=a(mid$(final, i, 1)) - code$=q#val$(1)+q#val$(0) - next - offset=len(code$) div 2 - for i=1 to offset - mess$=b$(mid$(code$,i,1)+mid$(code$,i+offset,1)) - next - = mess$ - } - }(!tables) - Print #f, encode("ATTACKATDAWN") - Print #f, decode(encode("ATTACKATDAWN"))="ATTACKATDAWN" - Print #f, encode(ucase$(filter$("The invasion will start on the first of January", " "))) - Print #f, decode(encode(ucase$(filter$("The invasion will start on the first of January", " ")))) + n=sqrt(len(code$)) + print #f," "; + for i=1 to n + print #f, i+" "; + next + print #f + for i=0 to n-1 + Print #f, (i+1)+" "+STR$(mid$(code$,1+i*n, n),STRING$("@ ", 5)) + next + tables=lambda (a$)->{ + n=sqrt(len(a$)) + a=list + for i=1 to len(a$) + append a, mid$(a$,i, 1):=((i-1) mod n+1, (i-1) div n+1 ) + next + b=list + m=each(a) + while m + z=eval(m) + append b, z#val$(1)+z#val$(0):=eval$(m!) + end while + =a, b + }(code$) + encode= lambda (a, b)->{ + =lambda a,b (mess as string) -> { + document code$ + for n=1 to 0 + for i=1 to len(mess) + q=mid$(mess, i,1) + if not exist(a, q) then + if q="J" then q="I" else q="A" + end if + code$=a(q)#val$(n) + next + next + document final$ + for i=1 to len(code$) step 2 + final$=b$(mid$(code$, i, 2)) + next + = final$ + } + }(!tables) + decode= lambda (a, b)->{ + =lambda a,b (final as string) -> { + document code$, mess$ + for i=1 to len(final) + q=a(mid$(final, i, 1)) + code$=q#val$(1)+q#val$(0) + next + offset=len(code$) div 2 + for i=1 to offset + mess$=b$(mid$(code$,i,1)+mid$(code$,i+offset,1)) + next + = mess$ + } + }(!tables) + Print #f, encode("ATTACKATDAWN") + Print #f, decode(encode("ATTACKATDAWN"))="ATTACKATDAWN" + Print #f, encode(ucase$(filter$("The invasion will start on the first of January", " "))) + Print #f, decode(encode(ucase$(filter$("The invasion will start on the first of January", " ")))) } open "out.txt" for output as #a Bifid_cipher a, "ABCDEFGHIKLMNOPQRSTUVWXYZ" diff --git a/Task/Bifid-cipher/Pluto/bifid-cipher.pluto b/Task/Bifid-cipher/Pluto/bifid-cipher.pluto new file mode 100644 index 0000000000..2a55d9872b --- /dev/null +++ b/Task/Bifid-cipher/Pluto/bifid-cipher.pluto @@ -0,0 +1,60 @@ +require "table2" + +class bifid + static function encrypt(polybius, message) + message = message:upper():replace("J", "I") + local rows = {} + local cols = {} + for i = 1, #message do + local c = message[i] + local ix = polybius:find(c, 1, true) + if !ix then continue end + rows:insert((ix - 1) // 5 + 1) + cols:insert((ix - 1) % 5 + 1) + end + local s = "" + for table.joined(rows, cols):chunk(2) as pair do + local ix = (pair[1] - 1) * 5 + pair[2] + s ..= polybius[ix] + end + return s + end + + static function decrypt(polybius, message) + local rows = {} + local cols = {} + for i = 1, #message do + local c = message[i] + local ix = polybius:find(c, 1, true) + rows:insert((ix - 1) // 5 + 1) + cols:insert((ix - 1) % 5 + 1) + end + local lines = table.zip(rows, cols):flatten() + local count = #lines // 2 + rows = lines:slice(1, count) + cols = lines:slice(count + 1) + local s = "" + for i = 1, count do + local ix = (rows[i] - 1) * 5 + cols[i] + s ..= polybius[ix] + end + return s + end +end + +local poly1 = "ABCDEFGHIKLMNOPQRSTUVWXYZ" +local poly2 = "BGWKZQPNDSIOAXEFCLUMTHYVR" +local poly3 = "PLAYFIREXMBCDGHKNOQSTUVWZ" +local polys = {poly1, poly2, poly2, poly3} +local msg1 = "ATTACKATDAWN" +local msg2 = "FLEEATONCE" +local msg3 = "The invasion will start on the first of January" +local msgs = {msg1, msg2, msg1, msg3} +for i = 1, #msgs do + local encrypted = bifid.encrypt(polys[i], msgs[i]) + local decrypted = bifid.decrypt(polys[i], encrypted) + print($"Message : {msgs[i]}") + print($"Encrypted : {encrypted}") + print($"Decrypted : {decrypted}") + if i < #msgs then print() end +end diff --git a/Task/Bifid-cipher/Rebol/bifid-cipher.rebol b/Task/Bifid-cipher/Rebol/bifid-cipher.rebol new file mode 100644 index 0000000000..8d8f219f6c --- /dev/null +++ b/Task/Bifid-cipher/Rebol/bifid-cipher.rebol @@ -0,0 +1,137 @@ +Rebol [ + title: "Rosetta code: Bifid cipher" + file: %Bifid_cipher.r3 + url: https://rosettacode.org/wiki/Bifid_cipher +] + +make-square: function [ + {Build a Polybius square from an alphabet string. + Returns a block of rows, each row a block of single-character strings. + The square is sized ceil(sqrt(len)) x ceil(sqrt(len)), with none padding + if the alphabet does not fill the last row exactly.} + alphabet [string!] +][ + size: to-integer round/ceiling square-root length? alphabet + rows: copy [] + row: copy [] + i: 0 + foreach ch alphabet [ + append row ch + ++ i + if i = size [ + append/only rows row + row: copy [] + i: 0 + ] + ] + unless empty? row [ ;; pad final row with none + append/dup row none (size - length? row) + append/only rows row + ] + new-line/all rows true +] + +square-map: function [ + {Return a map of character -> [row col] (1-based) for the given square.} + square [block!] +][ + m: make map! 64 + r: 1 + foreach row square [ + c: 1 + foreach ch row [ + if ch [ m/:ch: reduce [r c] ] ; skip none padding + ++ c + ] + ++ r + ] + m +] + +encrypt: function [ + {Encrypt plaintext using the bifid cipher with the given Polybius square. + Collects all row coordinates then all column coordinates, pairs them up, + and maps each pair back through the square.} + message [string!] + square [block!] +][ + m: square-map square + rows: copy [] + cols: copy [] + foreach ch message [ + if coord: m/:ch [ + append rows coord/1 + append cols coord/2 + ] + ] + combined: append copy rows cols ;; [r1 r2 .. rN c1 c2 .. cN] + result: copy "" + i: 1 + while [i < length? combined] [ + r: pick combined i + c: pick combined i + 1 + append result pick (pick square r) c + i: i + 2 + ] + result +] + +decrypt: function [ + {Decrypt ciphertext using the bifid cipher with the given Polybius square. + Splits the coordinate stream into the first half (rows) and second half + (cols), zips them, and maps each pair back through the square.} + message [string!] + square [block!] +][ + m: square-map square + coords: copy [] + foreach ch message [ + if coord: m/:ch [ repend coords coord ] + ] + half: (length? coords) / 2 ;; split interleaved coords at midpoint + rows: copy/part coords half + cols: copy/part (skip coords half) half + result: copy "" + i: 1 + while [i <= half] [ + r: rows/:i + c: cols/:i + append result square/:r/:c + ++ i + ] + result +] + +normalize: func [ + {Replace J with I for a standard 25-letter Polybius square.} + message [string!] +][ + replace/all copy message "J" "I" +] + +; --- Polybius squares used in test cases --- + +typical-square: make-square "ABCDEFGHIKLMNOPQRSTUVWXYZ" ;; 25 letters, no J +example-square: make-square "BGWKZQPNDSIOAXEFCLUMTHYVR" +playfair-square: make-square "PLAYFIREXMBCDGHKNOQSTUVWZ" +digits-square: make-square "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + +; --- Test cases --- + +test-cases: reduce [ + "ATTACKATDAWN" typical-square + "FLEEATONCE" example-square + "FLEEATONCE" typical-square + normalize "The invasion will start on the first of January" playfair-square + "The invasion will start on the first of January" digits-square +] + +foreach [msg square] test-cases [ + probe square + enc: encrypt msg square + dec: decrypt enc square + print ["Message :" msg] + print ["Encrypted:" enc] + print ["Decrypted:" dec] + print "" +] diff --git a/Task/Bin-given-limits/Ada/bin-given-limits-1.adb b/Task/Bin-given-limits/Ada/bin-given-limits-1.adb new file mode 100644 index 0000000000..a888af31ed --- /dev/null +++ b/Task/Bin-given-limits/Ada/bin-given-limits-1.adb @@ -0,0 +1,8 @@ +package binning is + type Nums_Array is array (Natural range <>) of Integer; + function Is_Sorted (Item : Nums_Array) return Boolean; + subtype Limits_Array is Nums_Array with + Dynamic_Predicate => Is_Sorted (Limits_Array); + function Bins (Limits : Limits_Array; Data : Nums_Array) return Nums_Array; + procedure Print (Limits : Limits_Array; Bin_Result : Nums_Array); +end binning; diff --git a/Task/Bin-given-limits/Ada/bin-given-limits-2.adb b/Task/Bin-given-limits/Ada/bin-given-limits-2.adb new file mode 100644 index 0000000000..22d2b0c83b --- /dev/null +++ b/Task/Bin-given-limits/Ada/bin-given-limits-2.adb @@ -0,0 +1,69 @@ +pragma Ada_2012; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; + +package body binning is + + --------------- + -- Is_Sorted -- + --------------- + + function Is_Sorted (Item : Nums_Array) return Boolean is + begin + return + (for all i in Item'First .. Item'Last - 1 => Item (i) < Item (i + 1)); + end Is_Sorted; + + ---------- + -- Bins -- + ---------- + + function Bins (Limits : Limits_Array; Data : Nums_Array) return Nums_Array + is + Result : Nums_Array (Limits'First .. Limits'Last + 1) := (others => 0); + Bin_Index : Natural; + begin + for value of Data loop + Bin_Index := Result'First; + for I in reverse Limits'Range loop + if value >= Limits (I) then + Bin_Index := I + 1; + exit; + end if; + end loop; + Result (Bin_Index) := Result (Bin_Index) + 1; + end loop; + return Result; + end Bins; + + ----------- + -- Print -- + ----------- + + procedure Print (Limits : Limits_Array; Bin_Result : Nums_Array) is + begin + if Limits'Length = 0 then + return; + end if; + Put (" < "); + Put (Item => Limits (Limits'First), Width => 3); + Put (": "); + Put (Item => Bin_Result (Bin_Result'First), Width => 2); + New_Line; + for i in Limits'First + 1 .. Limits'Last loop + Put (">= "); + Put (Item => Limits (i - 1), Width => 3); + Put (" and < "); + Put (Item => Limits (i), Width => 3); + Put (": "); + Put (Item => Bin_Result (i), Width => 2); + New_Line; + end loop; + Put (">= "); + Put (Item => Limits (Limits'Last), Width => 3); + Put (" : "); + Put (Item => Bin_Result (Bin_Result'Last), Width => 2); + New_Line; + end Print; + +end binning; diff --git a/Task/Bin-given-limits/Ada/bin-given-limits-3.adb b/Task/Bin-given-limits/Ada/bin-given-limits-3.adb new file mode 100644 index 0000000000..0b2dc4d7a9 --- /dev/null +++ b/Task/Bin-given-limits/Ada/bin-given-limits-3.adb @@ -0,0 +1,34 @@ +with Ada.Text_IO; use Ada.Text_IO; +with binning; use binning; + +procedure Main is + Limits_1 : Limits_Array := (23, 37, 43, 53, 67, 83); + Data_1 : Nums_Array := + (95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, + 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, + 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55); + Limits_2 : Limits_Array := (14, 18, 249, 312, 389, 392, 513, 591, 634, 720); + Data_2 : Nums_Array := + (445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, + 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, + 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, + 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, + 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, + 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, + 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, + 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, + 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, + 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, + 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, + 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, + 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, + 717, 918, 8, 374, 101, 684, 727, 749); + Bin_1 : Nums_Array := Bins (Limits => Limits_1, Data => Data_1); + Bin_2 : Nums_Array := Bins (Limits => Limits_2, Data => Data_2); +begin + Put_Line ("Example 1:"); + Print (Limits => Limits_1, Bin_Result => Bin_1); + New_Line; + Put_Line ("Example 2:"); + Print (Limits => Limits_2, Bin_Result => Bin_2); +end Main; diff --git a/Task/Bin-given-limits/Fortran/bin-given-limits.f b/Task/Bin-given-limits/Fortran/bin-given-limits.f new file mode 100644 index 0000000000..91a2dac4bb --- /dev/null +++ b/Task/Bin-given-limits/Fortran/bin-given-limits.f @@ -0,0 +1,98 @@ +! +! Bin given limits +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran (V8.6) does compile this code because it +! does not like the dimension (*) of the parameters +! U.B., January 2026 +!============================================================================== +program binLimits + +implicit none + +! Limits and Data for first example from task description +integer, parameter :: limits1 (*) = [23, 37, 43, 53, 67, 83 ] +integer, parameter :: values1 (*) = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, & + 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] + +! Second example +integer, parameter :: limits2 (*) = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] +integer, parameter :: values2 (*) = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, & + 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, & + 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, & + 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, & + 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, & + 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, & + 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, & + 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, & + 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, & + 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] + +call solve (limits1, size(limits1), values1, size(values1)) +call solve (limits2, size(limits2), values2, size(values2)) + +contains + +! ================================================== +! Create array of Histogram bins, then print results +! ================================================== +subroutine solve (l, nl, v,nv) +integer, intent(in) :: nl, nv ! Array sizes +integer, intent(in) :: l(nl), v(nv) ! Limits and Data arryays +integer :: hist (0:nl) ! THe resultant histogram + +call build_Histogram (l,nl,v,nv,hist) +call print_LimitsAndHistogram (l,nl,hist) + +end subroutine solve + + +! ============================== +! Create array of Histogram bins +! ============================== +subroutine build_Histogram (l,nl,v,nv,hist) + +integer, intent(in) :: nl, nv ! Array sizes +integer, intent(in) :: l(nl), v(nv) ! Limits and Data arryays +integer,intent(out) :: hist (0:nl) ! The resultant histogram + +integer :: iv, il ! Loop indices into values and limits + +hist = 0 +do iv=1, nv + ! If number of limits nl is small (here: 5 resp. 10), linear search for bin is sufficient. + ! for large nl consider to use binary search, that can be more efficient. + do il= nl, 1, -1 + if (v(iv) .ge. l(il)) then + hist(il) = hist(il) + 1 + exit + else if (il .eq. 1) then + hist(0) = hist(0) + 1 + end if + end do +end do + +end subroutine build_Histogram + +subroutine print_LimitsAndHistogram (l,nl,hist) + +integer, intent(in) :: nl ! Array size +integer, intent(in) :: l(nl) ! Limits to print +integer, intent(in) :: hist (0:nl) ! Histogram values to print + +integer :: il ! Loop index + +do il=0, nl + if (il .eq. 0) then + write (*,'(" < ", i3, ": ", i3)') l(1), hist(il) + else if (il .lt. nl) then + write (*,'(">= ", i3, " ... < ", i3, ": ", i3)') l(il), l(il+1), hist(il) + else + write (*,'(">= ", i3, " : ", i3)') l(il) , hist(il) + end if +end do +write (*,*) ! 1 empty line + +end subroutine print_LimitsAndHistogram + +end program binLimits diff --git a/Task/Bin-given-limits/Icon/bin-given-limits.icon b/Task/Bin-given-limits/Icon/bin-given-limits.icon new file mode 100644 index 0000000000..dc6aaa8920 --- /dev/null +++ b/Task/Bin-given-limits/Icon/bin-given-limits.icon @@ -0,0 +1,43 @@ +procedure main() + limits := [23, 37, 43, 53, 67, 83] + data := [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71, + 61,54,58,47,16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97, + 45,64,60,29,49,36,43,55] + write("1st limits and data set:") + bins := buildbins(limits, data) + summary(limits, bins) + + limits := [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] + data := [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570, + 219,367,523,442,933,416,589,930,373,202,253,775, 47,731,685, + 293,126,133,450,545,100,741,583,763,306,655,267,248,477,549, + 238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, + 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458, + 945,733,507,916,123,345,110,720,917,313,845,426, 9,457,628, + 410,723,354,895,881,953,677,137,397, 97,854,740, 83,216,421, + 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, + 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989, + 614,987,770,384,692,698,765,331,487,251,600,879,342,982,527, + 736,795,585, 40, 54,901,408,359,577,237,605,847,353,968,832, + 205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, + 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8, + 374,101,684,727,749] + write("\n2nd limits and data set:") + bins := buildbins(limits, data) + summary(limits, bins) +end + +procedure buildbins(limits, data) + bins := list(*limits+1, 0) + every item := !data do + if item < (limits[i := 1 to *limits]) then bins[i] +:= 1 + else bins[*limits+1] +:= 1 + return bins +end + +procedure summary(limits, bins) + write(repl(" ",8)," < ",right(limits[1],5)," -> ",right(bins[1],4)) + every i := 2 to *limits do + write(right(limits[i-1],8)," .. ",right(limits[i],4)," -> ",right(bins[i],4)) + write(right("> ",11),right(limits[*limits],5)," -> ",right(bins[*bins],4)) +end diff --git a/Task/Bin-given-limits/Perl/bin-given-limits-3.pl b/Task/Bin-given-limits/Perl/bin-given-limits-3.pl new file mode 100644 index 0000000000..854d56e080 --- /dev/null +++ b/Task/Bin-given-limits/Perl/bin-given-limits-3.pl @@ -0,0 +1,43 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Bin_given_limits +use warnings; +use List::MoreUtils qw( upper_bound slide ); + +for ( +{ +example => 1, +limits => [23, 37, 43, 53, 67, 83], +data => [ + 95,21,94,12,99,4,70,75,83,93,52,80,57, 5,53,86,65,17,92,83,71,61,54,58,47, + 16, 8, 9,32,84,7,87,46,19,30,37,96, 6,98,40,79,97,45,64,60,29,49,36,43,55 +] +}, +{ +example => 2, +limits => [14, 18, 249, 312, 389, 392, 513, 591, 634, 720], +data => [ + 445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, + 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, + 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, + 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, + 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, + 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, + 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, + 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, + 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, + 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749 +] +} +) + { + print "\nExample $_->{example}:\n"; + my @bins; + my @limits = @{ $_->{limits} }; + for my $n ( @{ $_->{data} } ) + { + $bins[ upper_bound { $_ <=> $n } @limits ]++; + } + slide { printf "%4s <= value < %4s : %d\n", $a, $b, shift @bins // 0 } + '-inf', @limits, '+inf'; + } diff --git a/Task/Bin-given-limits/Pluto/bin-given-limits.pluto b/Task/Bin-given-limits/Pluto/bin-given-limits.pluto new file mode 100644 index 0000000000..7628274cb7 --- /dev/null +++ b/Task/Bin-given-limits/Pluto/bin-given-limits.pluto @@ -0,0 +1,63 @@ +require "table2" +local fmt = require "fmt" + +local function bisect_right(array, x, low = 1, high = #array + 1) + while low < high do + local middle = (low + high) // 2 + if x < array[middle] then + high = middle + else + low = middle + 1 + end + end + return low +end + +local function bin_it(limits, data) + local bins = table.rep(#limits + 1, 0) + for data as d do + bins[bisect_right(limits, d)] += 1 + end + return bins +end + +local function bin_print(limits, bins) + fmt.print(" < %3d := %3d", limits[1], bins[1]) + local z = limits:zip(limits:slice(2)):zip(bins:slice(2)) + for z as p do + local [lo, hi] = p[1] + fmt.print(">= %3d .. < %3d := %3d", lo, hi, p[2]) + end + fmt.print(">= %3d := %3d", limits:back(), bins:back()) +end + +print("RC FIRST EXAMPLE:") +local limits = {23, 37, 43, 53, 67, 83} +local data = { + 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, + 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, + 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55 +} +local bins = bin_it(limits, data) +bin_print(limits, bins) + +print("\nRC SECOND EXAMPLE:") +limits = {14, 18, 249, 312, 389, 392, 513, 591, 634, 720} +data = { + 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, + 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, + 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, + 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, + 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, + 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, + 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, + 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, + 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, + 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, + 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, + 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, + 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, + 374, 101, 684, 727, 749 +} +bins = bin_it(limits, data) +bin_print(limits, bins) diff --git a/Task/Bin-given-limits/Uiua/bin-given-limits.uiua b/Task/Bin-given-limits/Uiua/bin-given-limits.uiua new file mode 100644 index 0000000000..ad18779a5c --- /dev/null +++ b/Task/Bin-given-limits/Uiua/bin-given-limits.uiua @@ -0,0 +1,5 @@ +Limits ← [23 37 43 53 67 83] +Data ← [95 21 94 12 99 4 70 75 83 93 52 80 57 5 53 86 65 17 92 83 71 61 54 58 47 + 16 8 9 32 84 7 87 46 19 30 37 96 6 98 40 79 97 45 64 60 29 49 36 43 55] +⊕⧻⤚≡(˜⨂1>)⊙¤⊙⟜∘ Data Limits # Fill bins +≡(&p$"Bin < _ has:\t_"°⊟)⍉⬚∞˜⊟ # Count contents diff --git a/Task/Binary-digits/Ada/binary-digits.adb b/Task/Binary-digits/Ada/binary-digits.adb new file mode 100644 index 0000000000..1248df864f --- /dev/null +++ b/Task/Binary-digits/Ada/binary-digits.adb @@ -0,0 +1,13 @@ +with ada.text_io; use ada.text_io; +procedure binary is + bit : array (0..1) of character := ('0','1'); + + function bin_image (n : Natural) return string is + (if n < 2 then (1 => bit (n)) else bin_image (n / 2) & bit (n mod 2)); + + test_values : array (1..3) of Natural := (5,50,9000); +begin + for test of test_values loop + put_line ("Output for" & test'img & " is " & bin_image (test)); + end loop; +end binary; diff --git a/Task/Binary-digits/AutoIt/binary-digits.au3 b/Task/Binary-digits/AutoIt/binary-digits.au3 new file mode 100644 index 0000000000..7f528b0718 --- /dev/null +++ b/Task/Binary-digits/AutoIt/binary-digits.au3 @@ -0,0 +1,15 @@ +ConsoleWrite(IntToBin(50) & @CRLF) + +Func IntToBin($iInt) + $Stack = ObjCreate("System.Collections.Stack") + Local $b = -1, $r = "" + While $iInt <> 0 + $b = Mod($iInt, 2) + $iInt = INT($iInt/2) + $Stack.Push ($b) + WEnd + For $i = 1 TO $Stack.Count + $r &= $Stack.Pop + Next + Return $r +EndFunc ;==>IntToBin diff --git a/Task/Binary-digits/Ballerina/binary-digits.ballerina b/Task/Binary-digits/Ballerina/binary-digits.ballerina new file mode 100644 index 0000000000..fece82b194 --- /dev/null +++ b/Task/Binary-digits/Ballerina/binary-digits.ballerina @@ -0,0 +1,17 @@ +import ballerina/io; + +function bin(int number) returns string { + int n = number; + string out = ""; + while n > 0 { + out = (n % 2).toString() + out; + n /= 2; + } + return out; +} + +public function main() { + foreach int i in [5, 50, 9000] { + io:println(bin(i)); + } +} diff --git a/Task/Binary-digits/Binary-Lambda-Calculus/binary-digits-1.blc b/Task/Binary-digits/Binary-Lambda-Calculus/binary-digits-1.blc new file mode 100644 index 0000000000..b153cb42fd --- /dev/null +++ b/Task/Binary-digits/Binary-Lambda-Calculus/binary-digits-1.blc @@ -0,0 +1,41 @@ +(let ((div2 (lambda (n) + (n (lambda (x) + (x (lambda (so-far odd?) + (odd? + ;; lambda (p) here and after is inlined cons + (lambda (p) + (p + ;; Inlined successor + (lambda (f x) + (f (so-far f x))) + nil)) + ;; cons so-far t + (lambda (p) (p so-far t)))))) + (lambda (p) (p 0 nil))))) + (fixpoint-combinator2 + #+nil + (lambda (g) + (let ((inner (lambda (x) (g (x x))))) + (inner inner))) + (lambda (f) + (let ((inner (lambda (x) + (f (lambda (y z) + (x x y z)))))) + (inner inner)))) + (ascii-zero (lambda (f) + (2 2 2 (3 f)))) + (ascii-one (lambda (f x) + (f (ascii-zero f x)))) + (binary (fixpoint-combinator2 + (lambda (recur acc n) + ((div2 n) + (lambda (res rem) + (let ((todigit (lambda (x) + (x ascii-one ascii-zero)))) + (res + (lambda (x) + ;; cons ascii acc + (recur (lambda (p) (p (todigit rem) acc)) res)) + ;; cons ascii acc + (lambda (p) (p (todigit rem) acc)))))))))) + (binary nil)) diff --git a/Task/Binary-digits/Binary-Lambda-Calculus/binary-digits-2.blc b/Task/Binary-digits/Binary-Lambda-Calculus/binary-digits-2.blc new file mode 100644 index 0000000000..0378ab0996 --- /dev/null +++ b/Task/Binary-digits/Binary-Lambda-Calculus/binary-digits-2.blc @@ -0,0 +1,35 @@ +(let ((div2 (lambda (n) + (n (lambda (x) + (x (lambda (so-far odd?) + (odd? + ;; lambda (p) here and after is inlined cons + (lambda (p) + (p + ;; Inlined successor + (lambda (f x) + (f (so-far f x))) + nil)) + ;; cons so-far t + (lambda (p) (p so-far t)))))) + (lambda (p) (p 0 nil))))) + (fixpoint-combinator2 + #+nil + (lambda (g) + (let ((inner (lambda (x) (g (x x))))) + (inner inner))) + (lambda (f) + (let ((inner (lambda (x) + (f (lambda (y z) + (x x y z)))))) + (inner inner)))) + (binary (fixpoint-combinator2 + (lambda (recur acc n) + ((div2 n) + (lambda (res rem) + (res + (lambda (x) + ;; cons bool acc + (recur (lambda (p) (p rem acc)) res)) + ;; cons bool acc + (lambda (p) (p rem acc))))))))) + (binary nil)) diff --git a/Task/Binary-digits/COBOL/binary-digits-1.cob b/Task/Binary-digits/COBOL/binary-digits-1.cob new file mode 100644 index 0000000000..71ac0cebbc --- /dev/null +++ b/Task/Binary-digits/COBOL/binary-digits-1.cob @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. SAMPLE. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 binary_number pic X(21). + 01 str pic X(21). + 01 binary_digit pic X. + 01 digit pic 9. + 01 n pic 9(7). + 01 nstr pic X(7). + + PROCEDURE DIVISION. + accept nstr + move nstr to n + perform until n equal 0 + divide n by 2 giving n remainder digit + move digit to binary_digit + string binary_digit DELIMITED BY SIZE + binary_number DELIMITED BY SPACE + into str + move str to binary_number + end-perform. + display binary_number + stop run. diff --git a/Task/Binary-digits/COBOL/binary-digits-2.cob b/Task/Binary-digits/COBOL/binary-digits-2.cob new file mode 100644 index 0000000000..3dc11fedb9 --- /dev/null +++ b/Task/Binary-digits/COBOL/binary-digits-2.cob @@ -0,0 +1,27 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. binary-conversion. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 binary-number pic X(21). +01 digit pic 9. +01 n pic 9(7). +01 nstr pic X(7). +01 ptr pic 99. + +PROCEDURE DIVISION. + display "Number: " with no advancing. + accept nstr. + move nstr to n. + move zeroes to binary-number. + move length binary-number to ptr. + perform until n equal 0 + divide n by 2 giving n remainder digit + move digit to binary-number(ptr:1) + subtract 1 from ptr + if ptr < 1 + exit perform + end-if + end-perform. + display binary-number. + stop run. diff --git a/Task/Binary-digits/Emacs-Lisp/binary-digits.el b/Task/Binary-digits/Emacs-Lisp/binary-digits.el new file mode 100644 index 0000000000..3964100e36 --- /dev/null +++ b/Task/Binary-digits/Emacs-Lisp/binary-digits.el @@ -0,0 +1,10 @@ +(defun int-to-binary (val) + (let ((x val) (result "")) + (while (> x 0) + (setq result (concat (number-to-string (% x 2)) result)) + (setq x (/ x 2))) + result)) + +(message "5 => %s" (int-to-binary 5)) +(message "50 => %s" (int-to-binary 50)) +(message "9000 => %s" (int-to-binary 9000)) diff --git a/Task/Binary-digits/Euphoria/binary-digits-1.eu b/Task/Binary-digits/Euphoria/binary-digits-1.eu new file mode 100644 index 0000000000..8778bdea7e --- /dev/null +++ b/Task/Binary-digits/Euphoria/binary-digits-1.eu @@ -0,0 +1,13 @@ +function toBinary(integer i) + sequence s + s = {} + while i do + s = prepend(s, '0'+and_bits(i,1)) + i = floor(i/2) + end while + return s +end function + +puts(1, toBinary(5) & '\n') +puts(1, toBinary(50) & '\n') +puts(1, toBinary(9000) & '\n') diff --git a/Task/Binary-digits/Euphoria/binary-digits-2.eu b/Task/Binary-digits/Euphoria/binary-digits-2.eu new file mode 100644 index 0000000000..f78a552487 --- /dev/null +++ b/Task/Binary-digits/Euphoria/binary-digits-2.eu @@ -0,0 +1,16 @@ +include std/math.e +include std/convert.e + +function Bin(integer n, sequence s = "") + if n > 0 then + return Bin(floor(n/2),(mod(n,2) + #30) & s) + end if + if length(s) = 0 then + return to_integer("0") + end if + return to_integer(s) +end function + +printf(1, "%d\n", Bin(5)) +printf(1, "%d\n", Bin(50)) +printf(1, "%d\n", Bin(9000)) diff --git a/Task/Binary-digits/Gleam/binary-digits.gleam b/Task/Binary-digits/Gleam/binary-digits.gleam new file mode 100644 index 0000000000..26d5c7ebab --- /dev/null +++ b/Task/Binary-digits/Gleam/binary-digits.gleam @@ -0,0 +1,9 @@ +import gleam/format +import gleam/list + +pub fn main() -> Nil { + // Using format library: https://hexdocs.pm/format/gleam/format.html + [5, 50, 9000] + |> list.map(format.printf("~.2B~n", _)) + Nil +} diff --git a/Task/Binary-digits/Haxe/binary-digits.hx b/Task/Binary-digits/Haxe/binary-digits.hx new file mode 100644 index 0000000000..f732d3f6e8 --- /dev/null +++ b/Task/Binary-digits/Haxe/binary-digits.hx @@ -0,0 +1,15 @@ +class Main { + static public function main() { + var integers = [5, 50, 9000]; + + for (i in integers) { + var bin = ""; + while (i > 1) { + bin = (i % 2) + bin; + i = Std.int(i / 2); + } + bin = i + bin; + trace(bin); + } + } +} diff --git a/Task/Binary-digits/PowerShell/binary-digits.ps1 b/Task/Binary-digits/PowerShell/binary-digits.ps1 new file mode 100644 index 0000000000..fbfb21b747 --- /dev/null +++ b/Task/Binary-digits/PowerShell/binary-digits.ps1 @@ -0,0 +1 @@ +@(5,50,900) | foreach-object { [Convert]::ToString($_,2) } diff --git a/Task/Binary-digits/REXX/binary-digits.rexx b/Task/Binary-digits/REXX/binary-digits.rexx new file mode 100644 index 0000000000..c1f4af09fa --- /dev/null +++ b/Task/Binary-digits/REXX/binary-digits.rexx @@ -0,0 +1,24 @@ +-- 12 Sep 2025 +include Setting +numeric digits 100 + +say 'BINARY DIGITS' +say version +say +say left('Decimal',9) '= Binary' +call Task 0 +call Task 5 +call Task 50 +call Task 9000 +call Task 999999999 +call Task 1e30 +exit + +Task: +arg xx +-- Built-in Decimal2Hex -> Hex2Binary -> Normalize +say left(xx,9) '=' X2B(D2X(xx)) +say left(xx,9) '=' X2B(D2X(xx))+0 +return 0 + +include Math diff --git a/Task/Binary-digits/Rebol/binary-digits.rebol b/Task/Binary-digits/Rebol/binary-digits.rebol new file mode 100644 index 0000000000..8796ee675f --- /dev/null +++ b/Task/Binary-digits/Rebol/binary-digits.rebol @@ -0,0 +1,5 @@ +foreach number [5 50 9000] [ + ;; any returns first not false value, used to cut leading zeroes + binstr: copy any [find enbase/flat to binary! number 2 #"1" #"0"] + print reduce [ pad number -5 binstr ] +] diff --git a/Task/Binary-digits/VBScript/binary-digits.vbs b/Task/Binary-digits/VBScript/binary-digits.vbs new file mode 100644 index 0000000000..969a2b6052 --- /dev/null +++ b/Task/Binary-digits/VBScript/binary-digits.vbs @@ -0,0 +1,23 @@ +Option Explicit +Dim bin +bin=Array(" "," I"," I "," II"," I "," I I"," II "," III","I ","I I","I I ","I II"," I ","II I","III ","IIII") + +Function num2bin(n) + Dim s,i,n1,n2 + s=Hex(n) + For i=1 To Len(s) + n1=Asc(Mid(s,i,1)) + If n1>64 Then n2=n1-55 Else n2=n1-48 + num2bin=num2bin & bin(n2) + Next + num2bin=Replace(Replace(LTrim(num2bin)," ","0"),"I",1) + End Function + + Sub print(s): + On Error Resume Next + WScript.stdout.WriteLine (s) + If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit + End Sub + print num2bin(5) + print num2bin(50) + print num2bin(9000) diff --git a/Task/Binary-search/Ada/binary-search-1.adb b/Task/Binary-search/Ada/binary-search-1.adb new file mode 100644 index 0000000000..f399a4debe --- /dev/null +++ b/Task/Binary-search/Ada/binary-search-1.adb @@ -0,0 +1,54 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Recursive_Binary_Search is + Not_Found : exception; + + generic + type Index is range <>; + type Element is private; + type Array_Of_Elements is array (Index range <>) of Element; + with function "<" (L, R : Element) return Boolean is <>; + function Search (Container : Array_Of_Elements; Value : Element) return Index; + + function Search (Container : Array_Of_Elements; Value : Element) return Index is + Mid : Index; + begin + if Container'Length > 0 then + Mid := (Container'First + Container'Last) / 2; + if Value < Container (Mid) then + if Container'First /= Mid then + return Search (Container (Container'First..Mid - 1), Value); + end if; + elsif Container (Mid) < Value then + if Container'Last /= Mid then + return Search (Container (Mid + 1..Container'Last), Value); + end if; + else + return Mid; + end if; + end if; + raise Not_Found; + end Search; + + type Integer_Array is array (Positive range <>) of Integer; + function Find is new Search (Positive, Integer, Integer_Array); + + procedure Test (X : Integer_Array; E : Integer) is + begin + New_Line; + for I in X'Range loop + Put (Integer'Image (X (I))); + end loop; + Put (" contains" & Integer'Image (E) & " at" & Integer'Image (Find (X, E))); + exception + when Not_Found => + Put (" does not contain" & Integer'Image (E)); + end Test; +begin + Test ((2, 4, 6, 8, 9), 2); + Test ((2, 4, 6, 8, 9), 1); + Test ((2, 4, 6, 8, 9), 8); + Test ((2, 4, 6, 8, 9), 10); + Test ((2, 4, 6, 8, 9), 9); + Test ((2, 4, 6, 8, 9), 5); +end Test_Recursive_Binary_Search; diff --git a/Task/Binary-search/Ada/binary-search-2.adb b/Task/Binary-search/Ada/binary-search-2.adb new file mode 100644 index 0000000000..0c5133631c --- /dev/null +++ b/Task/Binary-search/Ada/binary-search-2.adb @@ -0,0 +1,56 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Binary_Search is + Not_Found : exception; + + generic + type Index is range <>; + type Element is private; + type Array_Of_Elements is array (Index range <>) of Element; + with function "<" (L, R : Element) return Boolean is <>; + function Search (Container : Array_Of_Elements; Value : Element) return Index; + + function Search (Container : Array_Of_Elements; Value : Element) return Index is + Low : Index := Container'First; + High : Index := Container'Last; + Mid : Index; + begin + if Container'Length > 0 then + loop + Mid := (Low + High) / 2; + if Value < Container (Mid) then + exit when Low = Mid; + High := Mid - 1; + elsif Container (Mid) < Value then + exit when High = Mid; + Low := Mid + 1; + else + return Mid; + end if; + end loop; + end if; + raise Not_Found; + end Search; + + type Integer_Array is array (Positive range <>) of Integer; + function Find is new Search (Positive, Integer, Integer_Array); + + procedure Test (X : Integer_Array; E : Integer) is + begin + New_Line; + for I in X'Range loop + Put (Integer'Image (X (I))); + end loop; + Put (" contains" & Integer'Image (E) & " at" & Integer'Image (Find (X, E))); + exception + when Not_Found => + Put (" does not contain" & Integer'Image (E)); + end Test; +begin + Test ((2, 4, 6, 8, 9), 2); + Test ((2, 4, 6, 8, 9), 1); + Test ((2, 4, 6, 8, 9), 8); + Test ((2, 4, 6, 8, 9), 10); + Test ((2, 4, 6, 8, 9), 9); + Test ((2, 4, 6, 8, 9), 5); +end Test_Binary_Search; diff --git a/Task/Binary-search/COBOL/binary-search.cob b/Task/Binary-search/COBOL/binary-search.cob new file mode 100644 index 0000000000..09d47c9289 --- /dev/null +++ b/Task/Binary-search/COBOL/binary-search.cob @@ -0,0 +1,18 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. binary-search. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 nums-area VALUE "01040612184356". + 03 nums PIC 9(2) + OCCURS 7 TIMES + ASCENDING KEY nums + INDEXED BY nums-idx. +PROCEDURE DIVISION. + SEARCH ALL nums + WHEN nums (nums-idx) = 4 + DISPLAY "Found 4 at index " nums-idx + END-SEARCH + . +END PROGRAM binary-search. diff --git a/Task/Binary-search/Chapel/binary-search.chpl b/Task/Binary-search/Chapel/binary-search.chpl new file mode 100644 index 0000000000..e5ab05d298 --- /dev/null +++ b/Task/Binary-search/Chapel/binary-search.chpl @@ -0,0 +1,19 @@ +proc binsearch(A : [], value) +{ + var low = A.domain.dim(0).low; + var high = A.domain.dim(0).high; + while (low <= high) + { + var mid = (low + high) / 2; + + if A(mid) > value then + high = mid - 1; + else if A(mid) < value then + low = mid + 1; + else + return mid; + } + return 0; +} + +writeln(binsearch([3, 4, 6, 9, 11], 9)); diff --git a/Task/Binary-search/Emacs-Lisp/binary-search.el b/Task/Binary-search/Emacs-Lisp/binary-search.el new file mode 100644 index 0000000000..da99c84fd0 --- /dev/null +++ b/Task/Binary-search/Emacs-Lisp/binary-search.el @@ -0,0 +1,10 @@ +(defun binary-search (value array) + (let ((low 0) + (high (1- (length array)))) + (cl-do () ((< high low) nil) + (let ((middle (floor (+ low high) 2))) + (cond ((> (aref array middle) value) + (setf high (1- middle))) + ((< (aref array middle) value) + (setf low (1+ middle))) + (t (cl-return middle))))))) diff --git a/Task/Binary-search/Euphoria/binary-search-1.eu b/Task/Binary-search/Euphoria/binary-search-1.eu new file mode 100644 index 0000000000..6c8719c37a --- /dev/null +++ b/Task/Binary-search/Euphoria/binary-search-1.eu @@ -0,0 +1,16 @@ +function binary_search(sequence s, object val, integer low, integer high) + integer mid, cmp + if high < low then + return 0 -- not found + else + mid = floor( (low + high) / 2 ) + cmp = compare(s[mid], val) + if cmp > 0 then + return binary_search(s, val, low, mid-1) + elsif cmp < 0 then + return binary_search(s, val, mid+1, high) + else + return mid + end if + end if +end function diff --git a/Task/Binary-search/Euphoria/binary-search-2.eu b/Task/Binary-search/Euphoria/binary-search-2.eu new file mode 100644 index 0000000000..4ffa8d6cb3 --- /dev/null +++ b/Task/Binary-search/Euphoria/binary-search-2.eu @@ -0,0 +1,17 @@ +function binary_search(sequence s, object val) + integer low, high, mid, cmp + low = 1 + high = length(s) + while low <= high do + mid = floor( (low + high) / 2 ) + cmp = compare(s[mid], val) + if cmp > 0 then + high = mid - 1 + elsif cmp < 0 then + low = mid + 1 + else + return mid + end if + end while + return 0 -- not found +end function diff --git a/Task/Binary-search/Pluto/binary-search.pluto b/Task/Binary-search/Pluto/binary-search.pluto new file mode 100644 index 0000000000..49dfe6e967 --- /dev/null +++ b/Task/Binary-search/Pluto/binary-search.pluto @@ -0,0 +1,34 @@ +require "table2" +local fmt = require "fmt" + +local function rec_bsearch(a, v, low = 1, high = #a) + if high < low then return false, 0 end + local mid = low + (high - low) // 2 + if a[mid] > v then return rec_bsearch(a, v, low, mid - 1) end + if a[mid] < v then return rec_bsearch(a, v, mid + 1, high) end + return true, mid +end + +local a = {10, 22, 45, 67, 89, 97} +fmt.lprint(a, ", ", "{}", "array = ") +print() + +local texts = {"Using the library function (iterative algorithm):", + "Using the recursive algorithm:"} + +local values = { {22, 70}, {67, 93} } + +local fns = {table.bsearch, rec_bsearch} + +for i = 1, 2 do + print(texts[i]) + for values[i] as v do + local found, index = fns[i](a, v) + if found then + print($" {v} was found at index {index} of the array") + else + print($" {v} was not found in the array") + end + end + if i == 1 then print() end +end diff --git a/Task/Binary-search/PowerShell/binary-search-1.ps1 b/Task/Binary-search/PowerShell/binary-search-1.ps1 new file mode 100644 index 0000000000..1e97404d8f --- /dev/null +++ b/Task/Binary-search/PowerShell/binary-search-1.ps1 @@ -0,0 +1,66 @@ +function BinarySearch-Iterative ([int[]]$Array, [int]$Value) +{ + [int]$low = 0 + [int]$high = $Array.Count - 1 + + while ($low -le $high) + { + [int]$mid = ($low + $high) / 2 + + if ($Array[$mid] -gt $Value) + { + $high = $mid - 1 + } + elseif ($Array[$mid] -lt $Value) + { + $low = $mid + 1 + } + else + { + return $mid + } + } + + return -1 +} + +function BinarySearch-Recursive ([int[]]$Array, [int]$Value, [int]$Low = 0, [int]$High = $Array.Count) +{ + if ($High -lt $Low) + { + return -1 + } + + [int]$mid = ($Low + $High) / 2 + + if ($Array[$mid] -gt $Value) + { + return BinarySearch $Array $Value $Low ($mid - 1) + } + elseif ($Array[$mid] -lt $Value) + { + return BinarySearch $Array $Value ($mid + 1) $High + } + else + { + return $mid + } +} + +function Show-SearchResult ([int[]]$Array, [int]$Search, [ValidateSet("Iterative", "Recursive")][string]$Function) +{ + switch ($Function) + { + "Iterative" {$index = BinarySearch-Iterative -Array $Array -Value $Search} + "Recursive" {$index = BinarySearch-Recursive -Array $Array -Value $Search} + } + + if ($index -ge 0) + { + Write-Host ("Using BinarySearch-{0}: {1} is at index {2}" -f $Function, $numbers[$index], $index) + } + else + { + Write-Host ("Using BinarySearch-{0}: {1} not found" -f $Function, $Search) -ForegroundColor Red + } +} diff --git a/Task/Binary-search/PowerShell/binary-search-2.ps1 b/Task/Binary-search/PowerShell/binary-search-2.ps1 new file mode 100644 index 0000000000..3b44875c6c --- /dev/null +++ b/Task/Binary-search/PowerShell/binary-search-2.ps1 @@ -0,0 +1,4 @@ +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 41 -Function Iterative +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 99 -Function Iterative +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 86 -Function Recursive +Show-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive diff --git a/Task/Binary-search/RISC-V-Assembly/binary-search.asm b/Task/Binary-search/RISC-V-Assembly/binary-search.asm new file mode 100644 index 0000000000..067c70654e --- /dev/null +++ b/Task/Binary-search/RISC-V-Assembly/binary-search.asm @@ -0,0 +1,145 @@ +# riscv assembly raspberry pico2 rp2350 +# program binarysearch.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szMessResult: .asciz "Value found at index : " +szMessNotFound: .asciz "Value not found. \r\n" + +.align 2 +TableNumber: .int -10,4,6,7,10,11,15,22,30,35 +.equ NBELEMENTS1, . - TableNumber +.equ NBELEMENTS, NBELEMENTS1 / 4 + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + li a0,-10 # find first value + call testSearch + li a0,35 # find last value + call testSearch + li a0,10 # find medium value + call testSearch + + li a0,100 # value not in array + call testSearch + li a0,-100 # value not in array + call testSearch + + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* test binary search */ +/**********************************************/ +/* a0 search value */ +testSearch: # INFO: testSearch + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + la a1,TableNumber + li a2,NBELEMENTS + call bsearch + bltz a0,1f + mv s0,a0 + la a0,szMessResult + call writeString + mv a0,s0 + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szCariageReturn + call writeString + j 100f +1: + la a0,szMessNotFound + call writeString +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/***************************************************/ +/* binary search */ +/***************************************************/ +/* a0 search value */ +/* a1 array address */ +/* a2 array size */ +/* a0 return index or -1 if not find */ +bsearch: # INFO: bsearch + addi sp, sp, -8 # save registres + sw ra, 0(sp) + li t0,0 # low index + addi t1,a2,-1 # high index N - 1 +1: + bgt t0,t1,99f # not found + add t2,t0,t1 + srli t2,t2,1 # compute (low+high)/ 2 + sh2add t3,t2,a1 # compute index address + lw t4,(t3) # load array value + blt t4,a0,2f + bgt t4,a0,3f + mv a0,t2 # value found return index + j 100f +2: # lower + addi t0,t2,1 # low index = index + 1 + j 1b +3: # upper + addi t1,t2,-1 # high index = index - 1 + j 1b +99: + li a0,-1 +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Binary-search/VBScript/binary-search.vbs b/Task/Binary-search/VBScript/binary-search.vbs new file mode 100644 index 0000000000..fc18dfe54b --- /dev/null +++ b/Task/Binary-search/VBScript/binary-search.vbs @@ -0,0 +1,27 @@ +Function binary_search(arr,value,lo,hi) + If hi < lo Then + binary_search = 0 + Else + middle=Int((hi+lo)/2) + If value < arr(middle) Then + binary_search = binary_search(arr,value,lo,middle-1) + ElseIf value > arr(middle) Then + binary_search = binary_search(arr,value,middle+1,hi) + Else + binary_search = middle + Exit Function + End If + End If +End Function + +'Tesing the function. +num_range = Array(2,3,5,6,8,10,11,15,19,20) +n = CInt(WScript.Arguments(0)) +idx = binary_search(num_range,n,LBound(num_range),UBound(num_range)) +If idx > 0 Then + WScript.StdOut.Write n & " found at index " & idx + WScript.StdOut.WriteLine +Else + WScript.StdOut.Write n & " not found" + WScript.StdOut.WriteLine +End If diff --git a/Task/Binary-strings/Ada/binary-strings-1.adb b/Task/Binary-strings/Ada/binary-strings-1.adb new file mode 100644 index 0000000000..2ac3851060 --- /dev/null +++ b/Task/Binary-strings/Ada/binary-strings-1.adb @@ -0,0 +1,17 @@ +declare + Data : Storage_Array (1..20); -- Data created +begin + Data := (others => 0); -- Assign all zeros + if Data = (1..10 => 0) then -- Compare with 10 zeros + declare + Copy : Storage_Array := Data; -- Copy Data + begin + if Data'Length = 0 then -- If empty + ... + end if; + end; + end if; + ... Data & 1 ... -- The result is Data with byte 1 appended + ... Data & (1,2,3,4) ... -- The result is Data with bytes 1,2,3,4 appended + ... Data (3..5) ... -- The result the substring of Data from 3 to 5 +end; -- Data destructed diff --git a/Task/Binary-strings/Ada/binary-strings-2.adb b/Task/Binary-strings/Ada/binary-strings-2.adb new file mode 100644 index 0000000000..34ba140c32 --- /dev/null +++ b/Task/Binary-strings/Ada/binary-strings-2.adb @@ -0,0 +1,3 @@ +type Octet is mod 2**8; +for Octet'Size use 8; +type Octet_String is array (Positive range <>) of Octet; diff --git a/Task/Binary-strings/Ada/binary-strings-3.adb b/Task/Binary-strings/Ada/binary-strings-3.adb new file mode 100644 index 0000000000..c12234d0cb --- /dev/null +++ b/Task/Binary-strings/Ada/binary-strings-3.adb @@ -0,0 +1,4 @@ +with Interfaces; use Interfaces; +... +type Octet is new Interfaces.Unsigned_8; +type Octet_String is array (Positive range <>) of Octet; diff --git a/Task/Binary-strings/Pluto/binary-strings.pluto b/Task/Binary-strings/Pluto/binary-strings.pluto new file mode 100644 index 0000000000..80a647d8c9 --- /dev/null +++ b/Task/Binary-strings/Pluto/binary-strings.pluto @@ -0,0 +1,36 @@ +-- Create string. +local s = "abc" + +-- Destroy string (not really see notes above). +s = nil + +-- (Re)assignment. +s = "def" + +-- Comparison. +local b = (s == "abc") -- false +local c = (s <= "ghi") -- true + +-- Cloning/copying. +local t = s + +-- Check if empty. +s = "" +b = (s != "") -- false +b = (#s == 0) -- true + +-- Append a byte. +s ..= "b" + +-- Extract a substring. +s = "ghijkl" +t = s:sub(2, 5) -- "hijk" + +-- Replace a byte or string. +s = "abracadabra" +s = s:replace("a", "z") -- "zbrzczdzbrz" + +-- Join strings. +s = "abc" +t = "def" +local u = s .. t -- "abcdef" diff --git a/Task/Binary-strings/PowerShell/binary-strings.ps1 b/Task/Binary-strings/PowerShell/binary-strings.ps1 new file mode 100644 index 0000000000..fa8b1c8f00 --- /dev/null +++ b/Task/Binary-strings/PowerShell/binary-strings.ps1 @@ -0,0 +1,67 @@ +Clear-Host + +## String creation (which is string assignment): +Write-Host "`nString creation (which is string assignment):" -ForegroundColor Cyan +Write-Host '[string]$s = "Hello cruel world"' -ForegroundColor Yellow +[string]$s = "Hello cruel world" + +## String (or any variable) destruction: +Write-Host "`nString (or any variable) destruction:" -ForegroundColor Cyan +Write-Host 'Remove-Variable -Name s -Force' -ForegroundColor Yellow +Remove-Variable -Name s -Force + +## Now reassign the variable: +Write-Host "`nNow reassign the variable:" -ForegroundColor Cyan +Write-Host '[string]$s = "Hello cruel world"' -ForegroundColor Yellow +[string]$s = "Hello cruel world" + +Write-Host "`nString comparison -- default is case insensitive:" -ForegroundColor Cyan +Write-Host '$s -eq "HELLO CRUEL WORLD"' -ForegroundColor Yellow +$s -eq "HELLO CRUEL WORLD" +Write-Host '$s -match "HELLO CRUEL WORLD"' -ForegroundColor Yellow +$s -match "HELLO CRUEL WORLD" +Write-Host '$s -cmatch "HELLO CRUEL WORLD"' -ForegroundColor Yellow +$s -cmatch "HELLO CRUEL WORLD" + +## Copy a string: +Write-Host "`nCopy a string:" -ForegroundColor Cyan +Write-Host '$t = $s' -ForegroundColor Yellow +$t = $s + +## Check if a string is empty: +Write-Host "`nCheck if a string is empty:" -ForegroundColor Cyan +Write-Host 'if ($s -eq "") {"String is empty."} else {"String = $s"}' -ForegroundColor Yellow +if ($s -eq "") {"String is empty."} else {"String = $s"} + +## Append a byte to a string: +Write-Host "`nAppend a byte to a string:" -ForegroundColor Cyan +Write-Host "`$s += [char]46`n`$s" -ForegroundColor Yellow +$s += [char]46 +$s + +## Extract (and display) substring from a string: +Write-Host "`nExtract (and display) substring from a string:" -ForegroundColor Cyan +Write-Host '"Is the world $($s.Substring($s.IndexOf("c"),5))?"' -ForegroundColor Yellow +"Is the world $($s.Substring($s.IndexOf("c"),5))?" + +## Replace every occurrence of a byte (or a string) in a string with another string: +Write-Host "`nReplace every occurrence of a byte (or a string) in a string with another string:" -ForegroundColor Cyan +Write-Host "`$t = `$s -replace `"cruel`", `"beautiful`"`n`$t" -ForegroundColor Yellow +$t = $s -replace "cruel", "beautiful" +$t + +## Join strings: +Write-Host "`nJoin strings [1]:" -ForegroundColor Cyan +Write-Host '"Is the world $($s.Split()[1]) or $($t.Split()[1])?"' -ForegroundColor Yellow +"Is the world $($s.Split()[1]) or $($t.Split()[1])?" +Write-Host "`nJoin strings [2]:" -ForegroundColor Cyan +Write-Host '"{0} or {1}... I don''t care." -f (Get-Culture).TextInfo.ToTitleCase($s.Split()[1]), $t.Split()[1]' -ForegroundColor Yellow +"{0} or {1}... I don't care." -f (Get-Culture).TextInfo.ToTitleCase($s.Split()[1]), $t.Split()[1] +Write-Host "`nJoin strings [3] (display an integer array using the -join operater):" -ForegroundColor Cyan +Write-Host '1..12 -join ", "' -ForegroundColor Yellow +1..12 -join ", " + +## Display an integer array in a tablular format: +Write-Host "`nMore string madness... display an integer array in a tablular format:" -ForegroundColor Cyan +Write-Host '1..12 | Format-Wide {$_.ToString().PadLeft(2)}-Column 3 -Force' -NoNewline -ForegroundColor Yellow +1..12 | Format-Wide {$_.ToString().PadLeft(2)} -Column 3 -Force diff --git a/Task/Binary-strings/Rebol/binary-strings.rebol b/Task/Binary-strings/Rebol/binary-strings.rebol new file mode 100644 index 0000000000..8b9875b3e3 --- /dev/null +++ b/Task/Binary-strings/Rebol/binary-strings.rebol @@ -0,0 +1,25 @@ +;; String creation and destruction +str: make string! 5 +str: none +;; String assignment +str: "Hello" +;; String comparison +str == "Hello" ;; case sensitive +str = "hello" ;; case insensitive +;; String cloning and copying +tmp: copy str +;; Check if a string is empty +empty? tmp +clear tmp +empty? tmp +;; Append a byte to a string +append tmp "x" ;== "x" +append/dup tmp "y" 2 ;== "xyy" +;; Extract a substring from a string +copy/part next tmp 2 ;== "yy" +;; Replace every occurrence of a byte (or a string) in a string with another string +replace/all str "l" "L" +;; Join strings +join str tmp +rejoin [str space tmp] +ajoin [str space tmp] diff --git a/Task/Bioinformatics-Global-alignment/Crystal/bioinformatics-global-alignment.cr b/Task/Bioinformatics-Global-alignment/Crystal/bioinformatics-global-alignment.cr new file mode 100644 index 0000000000..f53b9a42d1 --- /dev/null +++ b/Task/Bioinformatics-Global-alignment/Crystal/bioinformatics-global-alignment.cr @@ -0,0 +1,54 @@ +def shortest_supersequence (seqs) + # remove duplicated and contained sequences + seqs = seqs.sort_by {|s| -s.size } + ss = [] of String + until seqs.empty? + seq = seqs.pop + ss << seq unless seqs.any? &.includes?(seq) + end + # connect them and find shortest + shortest = nil + ss.each_permutation do |perm| + superseq = perm.reduce {|sseq, seq| + if sseq && (idx = (1...seq.size).reverse_each.find {|len| sseq.ends_with? seq[0, len] }) + sseq + seq[idx..] + end + } + if superseq && (shortest.nil? || shortest.size > superseq.size) + shortest = superseq + end + end + shortest +end + +sequences = [ + ["TA", "AAG", "TA", "GAA", "TA"], + ["CATTAGGG", "ATTAG", "GGG", "TA"], + ["AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"], + ["ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", + "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", + "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", + "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", + "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", + "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", + "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", + "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", + "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", + "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", + "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", + "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA"], +] + +sequences.each do |ss| + if shortest = shortest_supersequence ss + puts "Nucleotide counts for #{shortest}:" + shortest.chars.tally.to_a.sort.each do |letter, count| + puts " #{letter}: #{count}" + end + puts " TOTAL= #{shortest.size}" + else + puts "Couldn't link #{ss.size} sequences." + end + puts +end diff --git a/Task/Bioinformatics-Global-alignment/Haskell/bioinformatics-global-alignment.hs b/Task/Bioinformatics-Global-alignment/Haskell/bioinformatics-global-alignment.hs new file mode 100644 index 0000000000..a9edc74f38 --- /dev/null +++ b/Task/Bioinformatics-Global-alignment/Haskell/bioinformatics-global-alignment.hs @@ -0,0 +1 @@ +H diff --git a/Task/Bioinformatics-Sequence-mutation/Ada/bioinformatics-sequence-mutation.adb b/Task/Bioinformatics-Sequence-mutation/Ada/bioinformatics-sequence-mutation.adb new file mode 100644 index 0000000000..048b7001cc --- /dev/null +++ b/Task/Bioinformatics-Sequence-mutation/Ada/bioinformatics-sequence-mutation.adb @@ -0,0 +1,117 @@ +with Ada.Containers.Vectors; +with Ada.Numerics.Discrete_Random; +with Ada.Text_Io; + +procedure Mutations is + + Width : constant := 60; + + type Nucleotide_Type is (A, C, G, T); + type Operation_Type is (Delete, Insert, Swap); + type Position_Type is new Natural; + + package Position_Io is new Ada.Text_Io.Integer_Io (Position_Type); + package Nucleotide_Io is new Ada.Text_Io.Enumeration_Io (Nucleotide_Type); + package Operation_Io is new Ada.Text_Io.Enumeration_Io (Operation_Type); + + use Ada.Text_Io, Position_Io, Nucleotide_Io, Operation_Io; + + package Sequence_Vectors is new Ada.Containers.Vectors (Index_Type => Position_Type, + Element_Type => Nucleotide_Type); + package Nucleotide_Generators is new Ada.Numerics.Discrete_Random (Result_Subtype => Nucleotide_Type); + package Operation_Generators is new Ada.Numerics.Discrete_Random (Result_Subtype => Operation_Type); + + procedure Pretty_Print (Sequence : Sequence_Vectors.Vector) is + First : Position_Type := Sequence.First_Index; + Last : Position_Type; + Count : array (Nucleotide_Type) of Natural := (others => 0); + begin + Last := Position_Type'Min (First + Width - 1, + Sequence.Last_Index); + loop + Position_Io.Put (First, Width => 4); + Put (": "); + for N in First .. Last loop + declare + Nucleotide : Nucleotide_Type renames Sequence (N); + begin + Put (Nucleotide); + Count (Nucleotide) := Count (Nucleotide) + 1; + end; + end loop; + New_Line; + exit when Last = Sequence.Last_Index; + First := Last + 1; + Last := Position_Type'Min (First + Width - 1, + Sequence.Last_Index); + end loop; + + for N in Count'Range loop + Put ("Count of "); Put (N); Put (" is "); Put (Natural'Image (Count (N))); New_Line; + end loop; + + end Pretty_Print; + + function Random_Position (First, Last : Position_Type) return Position_Type is + subtype Position_Range is Position_Type range First .. Last; + package Position_Generators is new Ada.Numerics.Discrete_Random (Result_Subtype => Position_Range); + Generator : Position_Generators.Generator; + begin + Position_Generators.Reset (Generator); + return Position_Generators.Random (Generator); + end Random_Position; + + Nucleotide_Generator : Nucleotide_Generators.Generator; + Operation_Generator : Operation_Generators.Generator; + + Sequence : Sequence_Vectors.Vector; + Position : Position_Type; + Nucleotide : Nucleotide_Type; + Operation : Operation_Type; +begin + Nucleotide_Generators.Reset (Nucleotide_Generator); + Operation_Generators.Reset (Operation_Generator); + + for A in 1 .. 200 loop + Sequence.Append (Nucleotide_Generators.Random (Nucleotide_Generator)); + end loop; + + Put_Line ("Initial sequence:"); + Pretty_Print (Sequence); + New_Line; + + Put_Line ("Mutations:"); + for Mutate in 1 .. 10 loop + + Operation := Operation_Generators.Random (Operation_Generator); + case Operation is + + when Delete => + Position := Random_Position (Sequence.First_Index, Sequence.Last_Index); + Sequence.Delete (Index => Position); + Put (Operation); Put (" at position "); Put (Position, Width => 0); New_Line; + + when Insert => + Position := Random_Position (Sequence.First_Index, Sequence.Last_Index + 1); + Nucleotide := Nucleotide_Generators.Random (Nucleotide_Generator); + Sequence.Insert (Before => Position, + New_Item => Nucleotide); + Put (Operation); Put (" "); Put (Nucleotide); Put (" at position "); + Put (Position, Width => 0); New_Line; + + when Swap => + Position := Random_Position (Sequence.First_Index, Sequence.Last_Index); + Nucleotide := Nucleotide_Generators.Random (Nucleotide_Generator); + Sequence.Replace_Element (Index => Position, + New_Item => Nucleotide); + Put (Operation); Put (" at position "); Put (Position, Width => 0); + Put (" to "); Put (Nucleotide); New_Line; + + end case; + end loop; + + New_Line; + Put_Line ("Mutated sequence:"); + Pretty_Print (Sequence); + +end Mutations; diff --git a/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy b/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy index 5ff9a347ef..652cd67955 100644 --- a/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy +++ b/Task/Bioinformatics-Sequence-mutation/EasyLang/bioinformatics-sequence-mutation.easy @@ -28,7 +28,7 @@ proc init . seqnx[] = [ 2 ] seqpr[] = [ 0 ] for i = 2 to 201 - seq[] &= random 4 + seq[] &= random 1 4 seqnx[] &= i + 1 seqpr[] &= i - 1 . @@ -51,7 +51,7 @@ proc delete pos . len seqpr[] -1 . proc insert pos . - seq[] &= random 4 + seq[] &= random 1 4 last = len seq[] seqnx[] &= pos seqpr[] &= seqpr[pos] @@ -59,10 +59,10 @@ proc insert pos . seqpr[pos] = last . proc mutate . - op = random 3 - pos = random (len seq[] - 1) + 1 + op = random 1 3 + pos = random 2 len seq[] if op = 1 - seq[pos] = random 4 + seq[pos] = random 1 4 elif op = 2 insert pos else diff --git a/Task/Bioinformatics-Sequence-mutation/Fortran/bioinformatics-sequence-mutation.f b/Task/Bioinformatics-Sequence-mutation/Fortran/bioinformatics-sequence-mutation.f new file mode 100644 index 0000000000..ee89b85796 --- /dev/null +++ b/Task/Bioinformatics-Sequence-mutation/Fortran/bioinformatics-sequence-mutation.f @@ -0,0 +1,108 @@ +! +! Bioinformatics/Sequence mutation +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 26.04 +! GNU gfortran (Ubuntu 15.2.0-16ubuntu1) 15.2.0 on Kubuntu 26.04 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +! U.B., April 2026 +! +program BioInfo + +implicit none + +integer, parameter :: IniLen = 200 ! Initial length of the DNA sequence +integer, parameter :: nMutations = 10 ! Number of Mutations to apply +integer, parameter :: MaxLen = IniLen + nMutations ! Each mutation could be an insertion + +character (len=MaxLen) :: DNASequence ! The DNA Sequence to work with + +character ,dimension(4), parameter :: Bases = ['A','C','G','T'] ! Thew 4 bases in the sequence +integer, dimension(4) :: hist ! COunters of bases +character :: newBase ! character for Replacement/Insertion mutation +integer :: ii, posMut ! Loop index, position of mutation + +call random_seed() ! Initialize random generator + +! Fill the sequence +do ii=1, IniLen + DNASequence (ii:ii) = Bases(randominInterval (1, 4)) +end do +DNASequence (iniLen+1:) = ' ' ! THe rest is blank + +! Print it +call prettyPrint (DNASequence, 100, "Sequence:") + +! Apply the mutations +write (*, '(/,i0, X, "Mutations:")') nMutations +do ii=1, nMutations + posMut = randominInterval (1, iniLen) ! Where to mutate... + select case (randominInterval (1,3)) ! ... and how + case (1) + ! Swap + newBase = Bases(randominInterval (1, 4)) + write (*,'(A10, x, A1, " at ", I0, " with ", A1 )') 'Substitute', DNASequence (posMut:posMut), posMut, newBase + DNASequence (posMut:posMut) = newBase + case (2) + ! Delete + write (*,'(A10, x, A1, " at ", I0)') 'Delete', DNASequence (posMut:posMut), posMut + DNASequence = DNASequence (1:posMut-1) // DNASequence (posMut+1:maxLen) + case (3) + ! Insert before + newBase = Bases(randominInterval (1, 4)) + write (*,'(A10, x, A1, " before ", A1 , " at ", I0)') 'Insert', newBase, DNASequence(posMut:posMut), posMut + DNASequence = DNASequence (1:posMut-1) // newBase // DNASequence (posMut:maxLen) + end select +enddo + +! Print result +call prettyPrint (DNASequence, 100, "Sequence after the mutations:") + +contains + +! ============================================================ +! Print one line of explanatory text, then the DNA Sequence rs +! (max. iLine in a line), and the Base Counts +! ============================================================= +subroutine prettyPrint (rs, lLine, Explanation) +integer, intent(in) :: lLine +character (len=*), intent(in) ::rs, Explanation +integer :: ii, idx, l +l = len_trim(rs) + +write (*,'(/A)') Explanation +do ii=1, l, lLine + write (*, '(i3,": ", A)') ii, rs(ii:min(l,ii+lLine-1)) +end do + +hist = 0 +do ii=1, len_trim(rs) + do idx = 1, 4 + if (rs(ii:ii) .eq. Bases (idx)) then + hist (idx) = hist(idx) + 1 + exit + end if + end do +end do + +write (*, '(/,"Base Count:")') +do ii=1,4 + write (*,'(A5, ": ", i3)') Bases (ii), hist (ii) +end do +write (*, '("Total: ", i3)') l +end subroutine prettyPrint + + +! =========================================================== +! Generate random number between @lo and @hi (inclusive) +! Assume Random Number Generator has been initialized before. +! =========================================================== +function randominInterval (lo, hi) result (r) +integer, intent(in) :: lo, hi ! the interval +integer :: r ! resultant (pseudo-)random number +real :: rnd ! Fortran random number generator generates float values +call random_number (rnd) ! 0. <= rnd < 1. +r = lo + FLOOR((hi+1-lo)*rnd) ! We want to choose one between [lo,hi]: add +1 to possibly include "hi". +end function randominInterval + + + +end program BioInfo diff --git a/Task/Bioinformatics-Sequence-mutation/R/bioinformatics-sequence-mutation.r b/Task/Bioinformatics-Sequence-mutation/R/bioinformatics-sequence-mutation.r new file mode 100644 index 0000000000..40bc25d56c --- /dev/null +++ b/Task/Bioinformatics-Sequence-mutation/R/bioinformatics-sequence-mutation.r @@ -0,0 +1,51 @@ +library(stringr) + +bases <- c("A", "C", "G", "T") +dna <- sample(bases, 200, replace=TRUE) + +mutate_base <- function(v){ + pos <- sample(seq_along(v), 1) + action <- sample(1:3, 1) + if(action==1){ + base_swap <- sample(bases, 1) + print(str_glue("Base {v[pos]} at position {pos} swapped to {base_swap}")) + v[pos] <- base_swap + } + else if(action==2){ + print(str_glue("Base {v[pos]} at position {pos} deleted")) + v <- v[-pos] + } + else if(action==3){ + base_insert <- sample(bases, 1) + print(str_glue("Base {base_insert} inserted at position {pos}")) + v <- c(v[1:(pos-1)], base_insert, v[pos:length(v)]) + } + return(v) +} + +count_bases <- function(v){ + base_counts <- sapply(bases, function(s) sum(v==s)) + cat("Base counts:\n") + cat(paste0(bases, ": ", base_counts), "\n") + cat("Total:", length(v), "\n") +} + +prettify <- function(title, v){ + cat(title, "\n") + nline <- function(s, n) rep(s, n%%50==0) + rownum <- function(n) paste0(n, ": ", collapse="") + for(i in seq_along(v)) cat(nline(rownum(i-1), i-1), + v[i], + nline("\n", i), + sep="") +} + +prettify("Initial DNA sequence:", dna) +count_bases(dna) + +dna <- Reduce(function(x, f) f(x), + rep(list(mutate_base), 10), + init=dna) + +prettify("Mutated DNA sequence:", dna) +count_bases(dna) diff --git a/Task/Biorhythms/Ada/biorhythms.adb b/Task/Biorhythms/Ada/biorhythms.adb new file mode 100644 index 0000000000..8f1fb796b8 --- /dev/null +++ b/Task/Biorhythms/Ada/biorhythms.adb @@ -0,0 +1,65 @@ +with Ada.Calendar; +with Ada.Calendar.Arithmetic; +with Ada.Calendar.Formatting; +with Ada.Command_Line; +with Ada.Numerics; +with Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; + +use Ada.Calendar; +use Ada.Calendar.Arithmetic; +use Ada.Calendar.Formatting; +use Ada.Command_Line; +use Ada.Numerics; +use Ada.Numerics.Elementary_Functions; +use Ada.Text_IO; + +procedure Biorhythms is + Birth_Date : Time := Value (Argument (1) & " 00:00:00"); + Target_Date : Time := Value (Argument (2) & " 00:00:00"); + Days : Day_Count := Target_Date - Birth_Date; + + -- There's not much point having types for these for such a short + -- problem, but in a big program this would be useful to prevent + -- accidentally assigning wrong values. + type Physical_Type is mod 23; + type Emotional_Type is mod 28; + type Mental_Type is mod 33; + type Biorhythm_Type is + record + Physical : Physical_Type; + Emotional : Emotional_Type; + Mental : Mental_Type; + end record; + + function To_Biorhythm (D : Day_Count) return Biorhythm_Type is + ( + Physical_Type (D mod Physical_Type'Modulus), + Emotional_Type (D mod Emotional_Type'Modulus), + Mental_Type (D mod Mental_Type'Modulus) + ); + + Biorhythm : Biorhythm_Type := To_Biorhythm (Days); + + package Float_IO is new Ada.Text_IO.Float_IO (Float); + use Float_IO; + + function To_Percent (F : Float) return Float is + (100.0 * Sin (2.0 * Pi * F)); + + procedure Report_Biorhythm (B : Biorhythm_Type) is + PFrac : Float := Float (B.Physical) / Float (Physical_Type'Modulus); + EFrac : Float := Float (B.Emotional) / Float (Emotional_Type'Modulus); + MFrac : Float := Float (B.Mental) / Float (Mental_Type'Modulus); + Physical : Float := To_Percent (PFrac); + Emotional : Float := To_Percent (EFrac); + Mental : Float := To_Percent (MFrac); + begin + Put_Line ("Age in days: " & Days'Image); + Put ("Physical cycle: "); Put (Physical, 3, 1, 0); Put ("%"); New_Line; + Put ("Emotional cycle: "); Put (Emotional, 3, 1, 0); Put ("%"); New_Line; + Put ("Mental cycle: "); Put (Mental, 3, 1, 0); Put ("%"); New_Line; + end Report_Biorhythm; +begin + Report_Biorhythm (Biorhythm); +end Biorhythms; diff --git a/Task/Biorhythms/COBOL/biorhythms-1.cob b/Task/Biorhythms/COBOL/biorhythms-1.cob new file mode 100644 index 0000000000..5d2dc28202 --- /dev/null +++ b/Task/Biorhythms/COBOL/biorhythms-1.cob @@ -0,0 +1,144 @@ + identification division. + program-id. bio. + environment division. + ************************************************************* + **** To execute on command line enter program name followed + **** by birth date ccyymmdd and then target date. + **** Example: bio 18090102 18631117 + **** Will display the three cycles: + **** Physcial 23 days, Emotional 28 days, Mental 33 days + **** for that date. + **** + ************************************************************* + configuration section. + source-computer. + System76 + * with debugging mode + . + repository. + function all intrinsic. + + data division. + working-storage section. + 01 w-d1 pic x(08). + 01 w-d2 pic x(08). + 01 n-d1 pic 9(08). + 01 n-d2 pic 9(08). + 01 w-i1 comp-x pic x(04). + 01 w-i2 comp-x pic x(04). + 01 w-days pic 9(07). + 01 arg-knt comp-5 pic x(01). + 01 bx pic 9. + 01 bio-tbl value 'Physical 23Emotional28Mental 33'. + 05 bio-entry occurs 3 times. + 10 bio-cyc pic x(09). + 10 bio-lth pic 9(02). + 01 bio-data occurs 3 times. + 05 bio-mod pic 9(02). + 05 bio-sin pic s999v9. + 05 bio-dsc pic x(09). + + procedure division. + accept arg-knt from argument-number + if arg-knt <> 2 + then + display 'two arguments are required:' upon SYSERR + display ' 1. first date ccyymmdd' upon SYSERR + display ' 2. second date ccyymmdd' upon SYSERR + stop run returning -1 + end-if + accept w-d1 from argument-value + if w-d1 not numeric + display ' first date not numeric ' upon syserr + move 2 to return-code + stop run + end-if + move w-d1 to n-d1 + if (n-d1 > 99991231) + display ' first date must be less than 99991232' + upon syserr + move 3 to return-code + stop run + end-if + if (n-d1 < 16010101) + display ' first date must be greater than 16010100' + upon syserr + move 4 to return-code + stop run + end-if + if ((n-d1(5:2) = '00') + or + (n-d1(5:2) > '12')) + display ' invalid month for first date ' upon syserr + move 5 to return-code + stop run + end-if + if ((n-d1(7:2) = '00') + or + (n-d1(7:2) > '31')) + display ' invalid day for first date ' upon syserr + move 6 to return-code + stop run + end-if + accept w-d2 from argument-value + if w-d2 not numeric + display 'second date not numeric ' upon syserr + move 12 to return-code + stop run + end-if + move w-d2 to n-d2 + if (n-d2 > 99991231) + display ' second date must be less than 99991232' + upon syserr + move 13 to return-code + stop run + end-if + if (n-d2 < 16010101) + display ' second date must be greater than 16010100' + upon syserr + move 14 to return-code + stop run + end-if + if ((n-d2(5:2) = '00') + or + (n-d2(5:2) > '12')) + display ' invalid month for second date ' upon syserr + move 15 to return-code + stop run + end-if + if ((n-d2(7:2) = '00') + or + (n-d2(7:2) > '31')) + display ' invalid day for second date ' upon syserr + move 16 to return-code + stop run + end-if + move w-d1 to n-d1 + move w-d2 to n-d2 + move integer-of-date(n-d1) to w-i1 + move integer-of-date(n-d2) to w-i2 + compute w-days = w-i1 - w-i2 + display w-days + perform varying bx from 1 by 1 until bx greater than 3 + move mod(w-days, bio-lth(bx)) to bio-mod(bx) + compute bio-sin(bx) rounded + = 100 * sin(2 * PI * bio-mod(bx) / bio-lth(bx)) + end-compute + display bio-cyc(bx) " " + bio-mod(bx) ":" + bio-sin(bx) "%" with no advancing + end-display + if bio-sin(bx) > 95 + move " peak" to bio-dsc(bx) + end-if + if bio-sin(bx) < -95 + move " valley" to bio-dsc(bx) + end-if + if abs(bio-sin(bx)) < 5 + move " critical" to bio-dsc(bx) + end-if + display bio-dsc(bx) + end-perform + move 0 to return-code + goback + . diff --git a/Task/Biorhythms/COBOL/biorhythms-2.cob b/Task/Biorhythms/COBOL/biorhythms-2.cob new file mode 100644 index 0000000000..104223a73c --- /dev/null +++ b/Task/Biorhythms/COBOL/biorhythms-2.cob @@ -0,0 +1,9 @@ +Compile and Test +C:\GnuCOBOL> +C:\GnuCOBOL>cobc -x bio.cbl + +C:\GnuCOBOL>bio 18090112 18631119 +0020034 +Physical 01:+027.0% +Emotional 14:+000.0% critical +Mental 03:+054.1% diff --git a/Task/Biorhythms/Crystal/biorhythms.cr b/Task/Biorhythms/Crystal/biorhythms.cr new file mode 100644 index 0000000000..b6c9cdba70 --- /dev/null +++ b/Task/Biorhythms/Crystal/biorhythms.cr @@ -0,0 +1,48 @@ +module BioRhythms + enum Cycle + Physical = 23 + Emotional = 28 + Mental = 33 + end + + Quadrants = [ {"up and raising", "peak"}, + {"up but falling", "transition"}, + {"down and falling", "valley"}, + {"down but raising", "transition"} ] + + def self.report (birthday, date = Time.utc) + # regularize to avoid fractional days difference + birthday, date = birthday.to_utc, date.to_utc + birthday -= birthday.time_of_day + date -= date.time_of_day + + days = (date - birthday).days + + puts "Born #{birthday.to_s("%F")}, Target #{date.to_s("%F")}" + puts "Day #{days}:" + Cycle.each do |kind, length| + position = days % length + quadrant = (position / length * 4).to_i + percentage = (Math.sin(position / length * 2 * Math::PI)*1000).to_i / 10 + description = if percentage > 95 + "peak" + elsif percentage < -95 + "valley" + elsif percentage.abs < 5 + "critical transition" + else + transition = date + ((quadrant + 1)/4 * length).to_i.days - position.days + trend, the_next = Quadrants[quadrant] + "#{percentage}% (#{trend}, next #{the_next} #{transition.to_s("%F")})" + end + puts "%-13s %2d: %s" % {kind.to_s + " day", position, description} + end + end +end + +[{"1943-03-09", "1972-07-11"}, + {"1809-01-12", "1863-11-19"}, + {"1809-02-12", "1863-11-19"}].each do |bd, target| + BioRhythms.report Time.parse_utc(bd, "%F"), Time.parse_utc(target, "%F") + puts +end diff --git a/Task/Biorhythms/EasyLang/biorhythms.easy b/Task/Biorhythms/EasyLang/biorhythms.easy index cebda43194..8307ee3761 100644 --- a/Task/Biorhythms/EasyLang/biorhythms.easy +++ b/Task/Biorhythms/EasyLang/biorhythms.easy @@ -28,10 +28,10 @@ proc cycle now cyc t$ col . gtext 4 cyc * 1.2 - 20 t$ glinewidth 0.5 gpenup - for d = now - 20 to now + 20 + for d = now - 20 step 0.2 to now + 20 y = 50 + 20 * sin (360 * d / cyc) glineto x y - x += 2.5 + x += 0.5 . . days = init birth$ date$ diff --git a/Task/Biorhythms/Emacs-Lisp/biorhythms.el b/Task/Biorhythms/Emacs-Lisp/biorhythms.el new file mode 100644 index 0000000000..1165910d29 --- /dev/null +++ b/Task/Biorhythms/Emacs-Lisp/biorhythms.el @@ -0,0 +1,15 @@ +(require 'calendar) + +(setq biorhythm-birthdate '(3 16 1953)) + +(defun biorhythm () + "Show today's biorhythm." + (interactive) + (let* ((diff (abs (- (string-to-number (calendar-astro-date-string + biorhythm-birthdate)) (string-to-number + (calendar-astro-date-string))))) + (rhyt '(23 28 33)) + (perc (mapcar (lambda (x) (round (* 100 (sin + (* 2 pi diff (/ 1.0 x)))))) rhyt))) + (message "age: %i physical: %i%% emotional: %i%% intellectual: %i%%" + diff (car perc) (cadr perc) (caddr perc)))) diff --git a/Task/Biorhythms/Phix/biorhythms.phix b/Task/Biorhythms/Phix/biorhythms.phix index e88bb994b4..d4c003fc47 100644 --- a/Task/Biorhythms/Phix/biorhythms.phix +++ b/Task/Biorhythms/Phix/biorhythms.phix @@ -1,44 +1,42 @@ -(phixonline)--> - with javascript_semantics - include timedate.e +with javascript_semantics +include timedate.e - constant cycles = {"Physical day ", "Emotional day", "Mental day "}, - lengths = {23, 28, 33}, - quadrants = {{"up and rising", "peak"}, - {"up but falling", "transition"}, - {"down and falling", "valley"}, - {"down but rising", "transition"}} +constant cycles = {"Physical day ", "Emotional day", "Mental day "}, + lengths = {23, 28, 33}, + quadrants = {{"up and rising", "peak"}, + {"up but falling", "transition"}, + {"down and falling", "valley"}, + {"down but rising", "transition"}} - procedure biorhythms(string birthDate, targetDate) - timedate bd = parse_date_string(birthDate,{"YYYY-MM-DD"}), - td = parse_date_string(targetDate,{"YYYY-MM-DD"}) - integer days = floor(timedate_diff(bd, td, DT_DAY)/(60*60*24)) - printf(1,"Born %s, Target %s\n",{birthDate,targetDate}) - printf(1,"Day %d\n",days) - for i=1 to 3 do - integer len = lengths[i], - posn = remainder(days,len), - quadrant = floor(posn/len*4)+1 - atom percent = floor(sin(2*PI*posn/len)*1000)/10 - string cycle = cycles[i], - desc = iff(percent>95 ? " peak" : - iff(percent<-95 ? " valley" : - iff(abs(percent)<5 ? " critical transition" : "other"))) - if desc == "other" then - timedate t = adjust_timedate(td,timedelta(days:=floor(quadrant/4*len)-posn)) - string transition = format_timedate(t,"YYYY-MM-DD"), - {trend,next} = quadrants[quadrant] - desc = sprintf("%5.1f%% (%s, next %s %s)", {percent, trend, next, transition}) - end if - printf(1,"%s %2d : %s\n", {cycle, posn, desc}) - end for - printf(1,"\n") - end procedure +procedure biorhythms(string birthDate, targetDate) + timedate bd = parse_date_string(birthDate,{"YYYY-MM-DD"}), + td = parse_date_string(targetDate,{"YYYY-MM-DD"}) + integer days = floor(timedate_diff(bd, td, DT_DAY)/(60*60*24)) + printf(1,"Born %s, Target %s\n",{birthDate,targetDate}) + printf(1,"Day %d\n",days) + for i=1 to 3 do + integer len = lengths[i], + posn = remainder(days,len), + quadrant = floor(posn/len*4)+1 + atom percent = floor(sin(2*PI*posn/len)*1000)/10 + string cycle = cycles[i], + desc = iff(percent>95 ? " peak" : + iff(percent<-95 ? " valley" : + iff(abs(percent)<5 ? " critical transition" : "other"))) + if desc == "other" then + timedate t = adjust_timedate(td,timedelta(days:=floor(quadrant/4*len)-posn)) + string transition = format_timedate(t,"YYYY-MM-DD"), + {trend,next} = quadrants[quadrant] + desc = sprintf("%5.1f%% (%s, next %s %s)", {percent, trend, next, transition}) + end if + printf(1,"%s %2d : %s\n", {cycle, posn, desc}) + end for + printf(1,"\n") +end procedure - constant datePairs = { - {"1943-03-09", "1972-07-11"}, - {"1809-01-12", "1863-11-19"}, - {"1809-02-12", "1863-11-19"} // correct DOB for Abraham Lincoln - } - for i=1 to length(datePairs) do biorhythms(datePairs[i][1], datePairs[i][2]) end for - Data (byte bucket) out:=Data().fill(0,25); @@ -9,7 +9,7 @@ fcn unbase58(str){ // --> Data (byte bucket) [24..0,-1].reduce('wrap(c,idx){ c+=58*out[idx]; // throws if not enough data out[idx]=c; - c/256; // should be zero when done + c/256; // should be zero when done },n) : if(_) throw(Exception.ValueError("address too long")); }); out; diff --git a/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.adb b/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.adb new file mode 100644 index 0000000000..520ce6f248 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-1.adb @@ -0,0 +1,24 @@ +procedure Cubic_Bezier + ( Picture : in out Image; + P1, P2, P3, P4 : Point; + Color : Pixel; + N : Positive := 20 + ) is + Points : array (0..N) of Point; +begin + for I in Points'Range loop + declare + T : constant Float := Float (I) / Float (N); + A : constant Float := (1.0 - T)**3; + B : constant Float := 3.0 * T * (1.0 - T)**2; + C : constant Float := 3.0 * T**2 * (1.0 - T); + D : constant Float := T**3; + begin + Points (I).X := Positive (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X) + D * Float (P4.X)); + Points (I).Y := Positive (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y) + D * Float (P4.Y)); + end; + end loop; + for I in Points'First..Points'Last - 1 loop + Line (Picture, Points (I), Points (I + 1), Color); + end loop; +end Cubic_Bezier; diff --git a/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.adb b/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.adb new file mode 100644 index 0000000000..7e2a86272d --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Ada/bitmap-b-zier-curves-cubic-2.adb @@ -0,0 +1,5 @@ + X : Image (1..16, 1..16); +begin + Fill (X, White); + Cubic_Bezier (X, (16, 1), (1, 4), (3, 16), (15, 11), Black); + Print (X); diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.adb b/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.adb new file mode 100644 index 0000000000..8d3a3f83ce --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-1.adb @@ -0,0 +1,23 @@ +procedure Quadratic_Bezier + ( Picture : in out Image; + P1, P2, P3 : Point; + Color : Pixel; + N : Positive := 20 + ) is + Points : array (0..N) of Point; +begin + for I in Points'Range loop + declare + T : constant Float := Float (I) / Float (N); + A : constant Float := (1.0 - T)**2; + B : constant Float := 2.0 * T * (1.0 - T); + C : constant Float := T**2; + begin + Points (I).X := Positive (A * Float (P1.X) + B * Float (P2.X) + C * Float (P3.X)); + Points (I).Y := Positive (A * Float (P1.Y) + B * Float (P2.Y) + C * Float (P3.Y)); + end; + end loop; + for I in Points'First..Points'Last - 1 loop + Line (Picture, Points (I), Points (I + 1), Color); + end loop; +end Quadratic_Bezier; diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.adb b/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.adb new file mode 100644 index 0000000000..1c346c9eaa --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Ada/bitmap-b-zier-curves-quadratic-2.adb @@ -0,0 +1,5 @@ + X : Image (1..16, 1..16); +begin + Fill (X, White); + Quadratic_Bezier (X, (8, 2), (13, 8), (2, 15), Black); + Print (X); diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.adb b/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.adb new file mode 100644 index 0000000000..ae513fcfc4 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-1.adb @@ -0,0 +1,40 @@ +procedure Line (Picture : in out Image; Start, Stop : Point; Color : Pixel) is + DX : constant Float := abs Float (Stop.X - Start.X); + DY : constant Float := abs Float (Stop.Y - Start.Y); + Err : Float; + X : Positive := Start.X; + Y : Positive := Start.Y; + Step_X : Integer := 1; + Step_Y : Integer := 1; +begin + if Start.X > Stop.X then + Step_X := -1; + end if; + if Start.Y > Stop.Y then + Step_Y := -1; + end if; + if DX > DY then + Err := DX / 2.0; + while X /= Stop.X loop + Picture (X, Y) := Color; + Err := Err - DY; + if Err < 0.0 then + Y := Y + Step_Y; + Err := Err + DX; + end if; + X := X + Step_X; + end loop; + else + Err := DY / 2.0; + while Y /= Stop.Y loop + Picture (X, Y) := Color; + Err := Err - DX; + if Err < 0.0 then + X := X + Step_X; + Err := Err + DY; + end if; + Y := Y + Step_Y; + end loop; + end if; + Picture (X, Y) := Color; -- Ensure dots to be drawn +end Line; diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.adb b/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.adb new file mode 100644 index 0000000000..9fa0a0abaf --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Ada/bitmap-bresenhams-line-algorithm-2.adb @@ -0,0 +1,8 @@ + X : Image (1..16, 1..16); +begin + Fill (X, White); + Line (X, ( 1, 8), ( 8,16), Black); + Line (X, ( 8,16), (16, 8), Black); + Line (X, (16, 8), ( 8, 1), Black); + Line (X, ( 8, 1), ( 1, 8), Black); + Print (X); diff --git a/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.au3 b/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.au3 new file mode 100644 index 0000000000..60a2debaef --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.au3 @@ -0,0 +1,23 @@ +Local $var = drawBresenhamLine(2, 3, 2, 6) + +Func drawBresenhamLine($iX0, $iY0, $iX1, $iY1) + Local $iDx = Abs($iX1 - $iX0) + Local $iSx = $iX0 < $iX1 ? 1 : -1 + Local $iDy = Abs($iY1 - $iY0) + Local $iSy = $iY0 < $iY1 ? 1 : -1 + Local $iErr = ($iDx > $iDy ? $iDx : -$iDy) / 2, $e2 + + While $iX0 <= $iX1 + ConsoleWrite("plot( $x=" & $iX0 & ", $y=" & $iY0 & " )" & @LF) + If ($iX0 = $iX1) And ($iY0 = $iY1) Then Return + $e2 = $iErr + If ($e2 > -$iDx) Then + $iErr -= $iDy + $iX0 += $iSx + EndIf + If ($e2 < $iDy) Then + $iErr += $iDx + $iY0 += $iSy + EndIf + WEnd +EndFunc ;==>drawBresenhamLine diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-1.cr b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-1.cr new file mode 100644 index 0000000000..f0a7e50bb0 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-1.cr @@ -0,0 +1,17 @@ +require "./pixmap" + +class Pixmap + def line (x0, y0, x1, y1, color) + dx, sx = (x1-x0).abs, x0dy ? dx : -dy) // 2 + + loop do + self[x0, y0] = color + break if x0 == x1 && y0 == y1 + e2 = err + (err -= dy; x0 += sx) if e2 >-dx + (err += dx; y0 += sy) if e2 < dy + end + end +end diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-2.cr b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-2.cr new file mode 100644 index 0000000000..fa74ba9af7 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Crystal/bitmap-bresenhams-line-algorithm-2.cr @@ -0,0 +1,7 @@ +require "./bresenham" + +img = Pixmap.new 10, 5, Color::WHITE + +img.line 0, 3, 9, 0, Color::RED + +img.write STDOUT diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.eu b/Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.eu new file mode 100644 index 0000000000..279a27aa62 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Euphoria/bitmap-bresenhams-line-algorithm.eu @@ -0,0 +1,115 @@ +include std/console.e +include std/graphics.e +include std/math.e + +-- the new_image function and related code in the 25 or so +-- lines below are from http://rosettacode.org/wiki/Basic_bitmap_storage#Euphoria +-- as of friday, march 2, 2012 + +-- Some color constants: +constant + black = #000000, + white = #FFFFFF, + red = #FF0000, + green = #00FF00, + blue = #0000FF + +-- Create new image filled with some color +function new_image(integer width, integer height, atom fill_color) + return repeat(repeat(fill_color,height),width) +end function + +--grid used for drawing lines in this program +sequence screenData = new_image(16,16,black) + +--the line algorithm +function bresLine(sequence screenData, integer x0, integer y0, integer x1, integer y1, integer color) + + integer deltaX = abs(x1 - x0), deltaY = abs(y1 - y0) + integer stepX, stepY, lineError, error2 + + if x0 < x1 then + stepX = 1 + else + stepX = -1 + end if + + if y0 < y1 then + stepY = 1 + else + stepY = -1 + end if + + if deltaX > deltaY then + lineError = deltaX + else + lineError = -deltaY + end if + + lineError = round(lineError / 2, 1) + + while 1 do + + screenData[x0][y0] = color + + if (x0 = x1 and y0 = y1) then + exit + end if + + error2 = lineError + + if error2 > -deltaX then + lineError -= deltaY + x0 += stepX + end if + if error2 < deltaY then + lineError += deltaX + y0 += stepY + end if + end while + return screenData -- return modified version of the screenData sequence +end function + +--prevents console output wrapping to next line if it is too big for the screen +wrap(0) +--outer diamond +screenData = bresLine(screenData,8,1,16,8,white) +screenData = bresLine(screenData,16,8,8,16,white) +screenData = bresLine(screenData,8,16,1,8,white) +screenData = bresLine(screenData,1,8,8,1,white) +--inner diamond +screenData = bresLine(screenData,8,4,12,8,white) +screenData = bresLine(screenData,12,8,8,12,white) +screenData = bresLine(screenData,8,12,4,8,white) +screenData = bresLine(screenData,4,8,8,4,white) +-- center lines drawing from left to right, and the next from right to left. +screenData = bresLine(screenData,7,7,9,7,white) +screenData = bresLine(screenData,9,9,7,9,white) +--center dot +screenData = bresLine(screenData,8,8,8,8,white) + +--print to the standard console output +for i = 1 to 16 do + puts(1,"\n") + for j = 1 to 16 do + if screenData[j][i] = black then + printf(1, "%s", ".") + else + printf(1, "%s", "#") + end if + end for +end for + +puts(1,"\n\n") +any_key() + +--/* +--output was edited to replace the color's hex digits for clearer output graphics. +--to output all the hex digits, use printf(1,"%06x", screenData[j][i]) +--to output 'shortened' hex digits, use : +--printf(1, "%x", ( abs( ( (screenData[j][i] / #FFFFF) - 1 ) ) - 1 ) ) +--and +--printf(1,"%x", abs( ( (screenData[j][i] / #FFFFF) - 1 ) ) ) +-- +--,respectively in the last if check. +--*/ diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-1.pluto b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-1.pluto new file mode 100644 index 0000000000..8ab23127e7 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-1.pluto @@ -0,0 +1,27 @@ +local canvas = require "canvas" + +local function line(c, x0, y0, x1, y1, col) + local dx = math.abs(x1 - x0) + local dy = math.abs(y1 - y0) + local sx = (x0 < x1) ? 1 : -1 + local sy = (y0 < y1) ? 1 : -1 + local err = (dx > dy ? dx : - dy) // 2 + while true do + c:set(x0, y0, col) + if x0 == x1 and y0 == y1 then break end + local e2 = err + if e2 > -dx then + err -= dy + x0 += sx + end + if e2 < dy then + err += dx + y0 += sy + end + end +end + +local c = canvas.new(400, 400) +c:fill(0xffffff) -- white background +line(c, 0, 0, 399, 399, 0x0000ff) -- draw a red diagonal +io.contents("mybmp.bmp", c:tobmp()) -- save to a bitmap file diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-2.pluto b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-2.pluto new file mode 100644 index 0000000000..a3504b25b4 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Pluto/bitmap-bresenhams-line-algorithm-2.pluto @@ -0,0 +1,6 @@ +require "bitmap" + +local bmp = bitmap.of(400, 400, color.white, "mybmp") +bmp:line(0, 0, 399, 399, color.red) +bmp:view() +bmp:save() -- if required diff --git a/Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vbs b/Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vbs new file mode 100644 index 0000000000..ae619cc394 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/VBScript/bitmap-bresenhams-line-algorithm.vbs @@ -0,0 +1,53 @@ +'Bitmap/Bresenham's line algorithm - VBScript - 13/05/2019 + Dim map(48,40), list(10), ox, oy + data=Array(1,8, 8,16, 16,8, 8,1, 1,8) + For i=0 To UBound(map,1): For j=0 To UBound(map,2) + map(i,j)="." + Next: Next 'j, i + points=(UBound(data)+1)/2 + For p=1 To points + x=data((p-1)*2) + y=data((p-1)*2+1) + list(p)=Array(x,y) + If p=1 Then minX=x: maxX=x: minY=y: maxY=y + If xmaxX Then maxX=x + If ymaxY Then maxY=y + Next 'p + border=2 + minX=minX-border*2 : maxX=maxX+border*2 + minY=minY-border : maxY=maxY+border + ox =-minX : oy =-minY + wx=UBound(map,1)-ox : If maxX>wx Then maxX=wx + wy=UBound(map,2)-oy : If maxY>wy Then maxY=wy + For x=minX To maxX: map(x+ox,0+oy)="-": Next 'x + For y=minY To maxY: map(0+ox,y+oy)="|": Next 'y + map(ox,oy)="+" + For p=1 To points-1 + draw_line list(p), list(p+1) + Next 'p + For y=maxY To minY Step -1 + line="" + For x=minX To maxX + line=line & map(x+ox,y+oy) + Next 'x + Wscript.Echo line + Next 'y + +Sub draw_line(p1, p2) + Dim x,y,xf,yf,dx,dy,sx,sy,err,err2 + x =p1(0) : y =p1(1) + xf=p2(0) : yf=p2(1) + dx=Abs(xf-x) : dy=Abs(yf-y) + If x-dy Then err=err-dy: x=x+sx + If err2< dx Then err=err+dx: y=y+sy + Loop +End Sub 'draw_line diff --git a/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.adb b/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.adb new file mode 100644 index 0000000000..3ed634e0a2 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-1.adb @@ -0,0 +1,106 @@ +procedure Flood_Fill + ( Picture : in out Image; + From : Point; + Fill : Pixel; + Replace : Pixel; + Distance : Luminance := 20 + ) is + function Diff (A, B : Luminance) return Luminance is + pragma Inline (Diff); + begin + if A > B then + return A - B; + else + return B - A; + end if; + end Diff; + + function "-" (A, B : Pixel) return Luminance is + pragma Inline ("-"); + begin + return Luminance'Max (Luminance'Max (Diff (A.R, B.R), Diff (A.G, B.G)), Diff (A.B, B.B)); + end "-"; + procedure Column (From : Point); + procedure Row (From : Point); + + Visited : array (Picture'Range (1), Picture'Range (2)) of Boolean := + (others => (others => False)); + + procedure Column (From : Point) is + X1 : Positive := From.X; + X2 : Positive := From.X; + begin + Visited (From.X, From.Y) := True; + for X in reverse Picture'First (1)..From.X - 1 loop + exit when Visited (X, From.Y); + declare + Color : Pixel renames Picture (X, From.Y); + begin + Visited (X, From.Y) := True; + exit when Color - Replace > Distance; + Color := Fill; + X1 := X; + end; + end loop; + for X in From.X + 1..Picture'Last (1) loop + exit when Visited (X, From.Y); + declare + Color : Pixel renames Picture (X, From.Y); + begin + Visited (X, From.Y) := True; + exit when Color - Replace > Distance; + Color := Fill; + X2 := X; + end; + end loop; + for X in X1..From.X - 1 loop + Row ((X, From.Y)); + end loop; + for X in From.X + 1..X2 loop + Row ((X, From.Y)); + end loop; + end Column; + + procedure Row (From : Point) is + Y1 : Positive := From.Y; + Y2 : Positive := From.Y; + begin + Visited (From.X, From.Y) := True; + for Y in reverse Picture'First (2)..From.Y - 1 loop + exit when Visited (From.X, Y); + declare + Color : Pixel renames Picture (From.X, Y); + begin + Visited (From.X, Y) := True; + exit when Color - Replace > Distance; + Color := Fill; + Y1 := Y; + end; + end loop; + for Y in From.Y + 1..Picture'Last (2) loop + exit when Visited (From.X, Y); + declare + Color : Pixel renames Picture (From.X, Y); + begin + Visited (From.X, Y) := True; + exit when Color - Replace > Distance; + Color := Fill; + Y2 := Y; + end; + end loop; + for Y in Y1..From.Y - 1 loop + Column ((From.X, Y)); + end loop; + for Y in From.Y + 1..Y2 loop + Column ((From.X, Y)); + end loop; + end Row; + + Color : Pixel renames Picture (From.X, From.Y); +begin + if Color - Replace <= Distance then + Visited (From.X, From.Y) := True; + Color := Fill; + Column (From); + end if; +end Flood_Fill; diff --git a/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.adb b/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.adb new file mode 100644 index 0000000000..3c1295d8e5 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Ada/bitmap-flood-fill-2.adb @@ -0,0 +1,19 @@ +declare + File : File_Type; +begin + Open (File, In_File, "Unfilledcirc.ppm"); + declare + Picture : Image := Get_PPM (File); + begin + Close (File); + Flood_Fill + ( Picture => Picture, + From => (122, 30), + Fill => (255,0,0), + Replace => White + ); + Create (File, Out_File, "Filledcirc.ppm"); + Put_PPM (File, Picture); + Close (File); + end; +end; diff --git a/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk b/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk index 9ff5334cf8..ab321c5681 100644 --- a/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk +++ b/Task/Bitmap-Flood-fill/AutoHotkey/bitmap-flood-fill-2.ahk @@ -1,55 +1,55 @@ #NoEnv #SingleInstance, Force - SetBatchLines, -1 - CoordMode, Mouse - CoordMode, Pixel + SetBatchLines, -1 + CoordMode, Mouse + CoordMode, Pixel return CapsLock:: - KeyWait, CapsLock - MouseGetPos, X, Y - PixelGetColor, color, X, Y - FloodFill(x, y, color, 0x000000, 1, "Esc") - MsgBox Done! + KeyWait, CapsLock + MouseGetPos, X, Y + PixelGetColor, color, X, Y + FloodFill(x, y, color, 0x000000, 1, "Esc") + MsgBox Done! Return FloodFill( 0x, 0y, target, replacement, mode=1, key="" ) { - VarSetCapacity(Rect, 16, 0) - hDC := DllCall("GetDC", UInt, 0) - hBrush := DllCall("CreateSolidBrush", UInt, replacement) - - l := 0 - while l >= 0 - { - if getkeystate(key, "P") - return - x := %l%x, y := %l%y - %l%p++ - p := %l%p - PixelGetColor, color, x, y - if (color = target) - { - NumPut(x, Rect, 0) - NumPut(y, Rect, 4) - NumPut(x+1, Rect, 8) - NumPut(y+1, Rect, 12) - DllCall("FillRect", UInt, hDC, Str, Rect, UInt, hBrush) - } - else if (p = 1) - { - %l%x := %l%y := %l%p := "", l-- - continue - } - if (p < 5) - ol := l++ - , %l%x := %ol%x + (p = 1 ? 1 : p = 2 ? -1 : 0) - , %l%y := %ol%y + (p = 3 ? 1 : p = 4 ? -1 : 0) - else - %l%x := %l%y := %l%p := "", l-- - } - - DllCall("ReleaseDC", UInt, 0, UInt, hDC) - DllCall("DeleteObject", UInt, hBrush) + VarSetCapacity(Rect, 16, 0) + hDC := DllCall("GetDC", UInt, 0) + hBrush := DllCall("CreateSolidBrush", UInt, replacement) + + l := 0 + while l >= 0 + { + if getkeystate(key, "P") + return + x := %l%x, y := %l%y + %l%p++ + p := %l%p + PixelGetColor, color, x, y + if (color = target) + { + NumPut(x, Rect, 0) + NumPut(y, Rect, 4) + NumPut(x+1, Rect, 8) + NumPut(y+1, Rect, 12) + DllCall("FillRect", UInt, hDC, Str, Rect, UInt, hBrush) + } + else if (p = 1) + { + %l%x := %l%y := %l%p := "", l-- + continue + } + if (p < 5) + ol := l++ + , %l%x := %ol%x + (p = 1 ? 1 : p = 2 ? -1 : 0) + , %l%y := %ol%y + (p = 3 ? 1 : p = 4 ? -1 : 0) + else + %l%x := %l%y := %l%p := "", l-- + } + + DllCall("ReleaseDC", UInt, 0, UInt, hDC) + DllCall("DeleteObject", UInt, hBrush) } diff --git a/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp b/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp index 3518acceab..1791da5b87 100644 --- a/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp +++ b/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp @@ -16,25 +16,25 @@ void FloodFillAlgorithm::flood(Point startPoint, Mat* tgtMat) { if (image->at(startPoint) == srcColor) { queue pointQueue; - pointQueue.push(startPoint); + pointQueue.push(startPoint); - while (!pointQueue.empty()) { - Point p = pointQueue.front(); - pointQueue.pop(); + while (!pointQueue.empty()) { + Point p = pointQueue.front(); + pointQueue.pop(); - if (insideImage(p)) { + if (insideImage(p)) { - if ((image->at(p) == srcColor)) { - image->at(p) = tgtMat->at(p); + if ((image->at(p) == srcColor)) { + image->at(p) = tgtMat->at(p); - pointQueue.push(Point(p.x + 1, p.y)); - pointQueue.push(Point(p.x - 1, p.y)); - pointQueue.push(Point(p.x, p.y + 1)); - pointQueue.push(Point(p.x, p.y - 1)); - } - } + pointQueue.push(Point(p.x + 1, p.y)); + pointQueue.push(Point(p.x - 1, p.y)); + pointQueue.push(Point(p.x, p.y + 1)); + pointQueue.push(Point(p.x, p.y - 1)); + } + } - } + } } } diff --git a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c index 9e3b20b4a1..69c8175bc1 100644 --- a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c +++ b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-3.c @@ -5,5 +5,5 @@ typedef struct { typedef rgb_color *rgb_color_p; void floodfill(image img, int px, int py, - rgb_color_p bankscolor, - rgb_color_p rcolor); + rgb_color_p bankscolor, + rgb_color_p rcolor); diff --git a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c index 8e9134edf6..453c999fed 100644 --- a/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c +++ b/Task/Bitmap-Flood-fill/C/bitmap-flood-fill-4.c @@ -29,8 +29,8 @@ inline void _ffill_enqueue(_ffill_queue *q, int px, int py) inline double color_distance( rgb_color_p a, rgb_color_p b ) { return sqrt( (double)(a->red - b->red)*(a->red - b->red) + - (double)(a->green - b->green)*(a->green - b->green) + - (double)(a->blue - b->blue)*(a->blue - b->blue) ) / (256.0*sqrt(3.0)); + (double)(a->green - b->green)*(a->green - b->green) + + (double)(a->blue - b->blue)*(a->blue - b->blue) ) / (256.0*sqrt(3.0)); } inline void _ffill_rgbcolor(image img, rgb_color_p tc, int px, int py) @@ -41,25 +41,25 @@ inline void _ffill_rgbcolor(image img, rgb_color_p tc, int px, int py) } -#define NSOE(X,Y) do { \ - if ( ((X)>=0)&&((Y)>=0) && ((X)width)&&((Y)height)) { \ - _ffill_rgbcolor(img, &thisnode, (X), (Y)); \ - if ( color_distance(&thisnode, bankscolor) > tolerance ) { \ - if (color_distance(&thisnode, rcolor) > 0.0) { \ - put_pixel_unsafe(img, (X), (Y), rcolor->red, \ - rcolor->green, \ - rcolor->blue); \ - _ffill_enqueue(&head, (X), (Y)); \ - pixelcount++; \ - } \ - } \ - } \ +#define NSOE(X,Y) do { \ + if ( ((X)>=0)&&((Y)>=0) && ((X)width)&&((Y)height)) { \ + _ffill_rgbcolor(img, &thisnode, (X), (Y)); \ + if ( color_distance(&thisnode, bankscolor) > tolerance ) { \ + if (color_distance(&thisnode, rcolor) > 0.0) { \ + put_pixel_unsafe(img, (X), (Y), rcolor->red, \ + rcolor->green, \ + rcolor->blue); \ + _ffill_enqueue(&head, (X), (Y)); \ + pixelcount++; \ + } \ + } \ + } \ } while(0) unsigned int floodfill(image img, int px, int py, - rgb_color_p bankscolor, - rgb_color_p rcolor) + rgb_color_p bankscolor, + rgb_color_p rcolor) { _ffill_queue head; rgb_color thisnode; diff --git a/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-1.cr b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-1.cr new file mode 100644 index 0000000000..1a294cd573 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-1.cr @@ -0,0 +1,37 @@ +require "./pixmap" + +class Pixmap + def flood_fill (x, y, color) + old_color = self[x, y] + queue = Deque(Int32).new + width = @width + size = @data.size + idx = y * width + x + queue << idx + + until queue.empty? + idx = queue.shift + next unless @data[idx] == old_color + start = idx + # go left + limit = start // width * width + while idx >= limit && @data[idx] == old_color + @data[idx] = color + up, dn = idx - width, idx + width + queue << up if up >= 0 && @data[up] == old_color + queue << dn if dn < size && @data[dn] == old_color + idx -= 1 + end + # go right + limit = (start + width) // width * width + idx = start + 1 + while idx < limit && @data[idx] == old_color + @data[idx] = color + up, dn = idx - width, idx + width + queue << up if up >= 0 && @data[up] == old_color + queue << dn if dn < size && @data[dn] == old_color + idx += 1 + end + end + end +end diff --git a/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-2.cr b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-2.cr new file mode 100644 index 0000000000..eb33ea7d5d --- /dev/null +++ b/Task/Bitmap-Flood-fill/Crystal/bitmap-flood-fill-2.cr @@ -0,0 +1,22 @@ +require "./circle" +require "./flood_fill" +require "./write_ppm" +require "./load_ppm" + +img = Pixmap.new 120, 80, Color::WHITE +img.circle 60, 40, 35, Color::BLACK +img.circle 100, 20, 18, Color::RED + +img.flood_fill 10, 10, Color.new(210, 230, 0) +img.flood_fill 60, 40, Color.new(255, 128, 76) + +img.write "crystal_flood_fill.ppm" + + +img = Pixmap.load "Unfilledcirc.ppm" +img.flood_fill 10, 10, Color.new(0, 128, 240) +img.flood_fill img.width-1, img.height-1, Color.new(0, 128, 240) +img.flood_fill 10, img.height//2, Color.new(240, 180, 10) +img.flood_fill 100, 100, Color.new(255, 60, 10) + +img.write "crystal_filledcirc.ppm" diff --git a/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl b/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl index 2cc3085c3c..b359ffe534 100644 --- a/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl +++ b/Task/Bitmap-Flood-fill/FBSL/bitmap-flood-fill.fbsl @@ -15,23 +15,23 @@ FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height) DrawCircles() ' Initialize circles BEGIN EVENTS - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN: FillCircles() ' Flood fill circles - CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: FillCircles() ' Flood fill circles + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT END EVENTS SUB FillCircles() - FILL(FBSL.GETDC, Breadth / 2, Height / 2, &HFFFF) ' Yellow: flood fill using intrinsics - FOR DIM x = 0 TO Breadth / 2 ' Red: flood fill iteratively - FOR DIM y = 0 TO Height / 2 - IF NOT POINT(FBSL.GETDC, x, y) THEN PSET(FBSL.GETDC, x, y, &HFF) - NEXT - NEXT - FBSLSETTEXT(ME, "After Flood Fill") ' Reset form caption + FILL(FBSL.GETDC, Breadth / 2, Height / 2, &HFFFF) ' Yellow: flood fill using intrinsics + FOR DIM x = 0 TO Breadth / 2 ' Red: flood fill iteratively + FOR DIM y = 0 TO Height / 2 + IF NOT POINT(FBSL.GETDC, x, y) THEN PSET(FBSL.GETDC, x, y, &HFF) + NEXT + NEXT + FBSLSETTEXT(ME, "After Flood Fill") ' Reset form caption END SUB SUB DrawCircles() ' Concatenate function calls - CIRCLE(FBSL.GETDC, Breadth / 2, Height / 2, 85, &HFFFFFF, 0, 360, 1, TRUE) _ ' White - (FBSL.GETDC, Breadth / 3, Height / 3, 30, 0, 0, 360, 1, TRUE) ' Black + CIRCLE(FBSL.GETDC, Breadth / 2, Height / 2, 85, &HFFFFFF, 0, 360, 1, TRUE) _ ' White + (FBSL.GETDC, Breadth / 3, Height / 3, 30, 0, 0, 360, 1, TRUE) ' Black END SUB diff --git a/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini b/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini index ea71b8be0a..e4a6dfa8d6 100644 --- a/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini +++ b/Task/Bitmap-Flood-fill/MiniScript/bitmap-flood-fill.mini @@ -1,18 +1,18 @@ floodFill = function(bmp, x, y, targetColor, replacementColor) - // Check if pixel is outside the bounds - if not(0 < x < bmp.width) or not(0 < y < bmp.height) then return - - // Check the current pixel color - currentColor = bmp.pixel(x, y) - if currentColor != targetColor then return - - // Replace the color - bmp.setPixel x, y, replacementColor - // Recursively apply to adjacent pixels - floodFill(bmp, x + 1, y, targetColor, replacementColor) - floodFill(bmp, x - 1, y, targetColor, replacementColor) - floodFill(bmp, x, y + 1, targetColor, replacementColor) - floodFill(bmp, x, y - 1, targetColor, replacementColor) + // Check if pixel is outside the bounds + if not(0 < x < bmp.width) or not(0 < y < bmp.height) then return + + // Check the current pixel color + currentColor = bmp.pixel(x, y) + if currentColor != targetColor then return + + // Replace the color + bmp.setPixel x, y, replacementColor + // Recursively apply to adjacent pixels + floodFill(bmp, x + 1, y, targetColor, replacementColor) + floodFill(bmp, x - 1, y, targetColor, replacementColor) + floodFill(bmp, x, y + 1, targetColor, replacementColor) + floodFill(bmp, x, y - 1, targetColor, replacementColor) end function clear img = file.loadImage("Unfilledcirc.png") diff --git a/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl b/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl index 049af58478..dae6942463 100644 --- a/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl +++ b/Task/Bitmap-Flood-fill/Perl/bitmap-flood-fill-2.pl @@ -23,20 +23,20 @@ sub floodfill if ( colordistance(\@tcol, \@col) > $distparameter ) { return; } push @queue, [$x, $y]; while ( @queue ) { - my $pointref = shift(@queue); - ( $x, $y ) = @$pointref; - if ( ($x < 0) || ($y < 0) || ( $x >= $img->width ) || ( $y >= $img->height ) ) { next; } - if ( ! exists($visited{"$x,$y"}) ) { - @col = $img->query_pixel($x, $y); - if ( colordistance(\@tcol, \@col) <= $distparameter ) { - $img->draw_point($x, $y); - $visited{"$x,$y"} = 1; - push @queue, [$x+1, $y]; - push @queue, [$x-1, $y]; - push @queue, [$x, $y+1]; - push @queue, [$x, $y-1]; - } - } + my $pointref = shift(@queue); + ( $x, $y ) = @$pointref; + if ( ($x < 0) || ($y < 0) || ( $x >= $img->width ) || ( $y >= $img->height ) ) { next; } + if ( ! exists($visited{"$x,$y"}) ) { + @col = $img->query_pixel($x, $y); + if ( colordistance(\@tcol, \@col) <= $distparameter ) { + $img->draw_point($x, $y); + $visited{"$x,$y"} = 1; + push @queue, [$x+1, $y]; + push @queue, [$x-1, $y]; + push @queue, [$x, $y+1]; + push @queue, [$x, $y-1]; + } + } } } diff --git a/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku b/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku index fa29c20997..7cafc0de1d 100644 --- a/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku +++ b/Task/Bitmap-Flood-fill/Raku/bitmap-flood-fill.raku @@ -4,16 +4,16 @@ class Bitmap { has Pixel @.data; method pixel( - $i where ^$!width, - $j where ^$!height - --> Pixel + $i where ^$!width, + $j where ^$!height + --> Pixel ) is rw { @!data[$i + $j * $!width] } } role PPM { method P6 returns Blob { - "P6\n{self.width} {self.height}\n255\n".encode('ascii') - ~ Blob.new: flat map { .R, .G, .B }, self.data + "P6\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: flat map { .R, .G, .B }, self.data } } diff --git a/Task/Bitmap-Flood-fill/Rebol/bitmap-flood-fill.rebol b/Task/Bitmap-Flood-fill/Rebol/bitmap-flood-fill.rebol new file mode 100644 index 0000000000..f5deeabdf5 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Rebol/bitmap-flood-fill.rebol @@ -0,0 +1,64 @@ +Rebol [ + title: "Rosetta code: Bitmap/Flood fill" + file: %Bitmap-Flood_fill.r3 + url: https://rosettacode.org/wiki/Bitmap/Bitmap-Flood_fill +] + +flood-fill: function [ + image [image! file! url!] + position [pair!] "Start position" + color1 [tuple!] "Target color to replace" + color2 [tuple!] "Replacement color" +][ + unless image? image [image: load image] ;; Load image if not already loaded + xsize: image/size/x + ysize: image/size/y + + color2/4: color1/4: 255 ;; Ensure both colors are fully opaque + + que: copy [] + if image/:position != color1 [return image] ;; Bail if seed pixel isn't target color + + append que position + while [not empty? que][ + position: take que ;; Dequeue next position to process + if image/:position == color1 [ ;; Skip if already recolored + W: position + ;; Scan west, recoloring pixels until we leave the target-color region + while [image/:W == color1][ + image/:W: color2 + next: W + 0x1 ;; Pixel south of W + if all [next/y < ysize color1 == image/:next][append que next] + next: W - 0x1 ;; Pixel north of W + if all [next/y > 0 color1 == image/:next][append que next] + next: W - 1x0 ;; Step west + either next/x > 1 [W: next][break] ;; Stop at left edge + ] + E: position + 1x0 ;; Start east scan one step right of seed + if E/x < xsize [ + ;; Scan east, recoloring pixels until we leave the target-color region + while [image/:E == color1][ + image/:E: color2 + next: E + 0x1 ;; Pixel south of E + if all [next/y < ysize color1 == image/:next][append que next] + next: E - 0x1 ;; Pixel north of E + if all [next/y > 0 color1 == image/:next][append que next] + next: E + 1x0 ;; Step east + either next/x < xsize [E: next][break] ;; Stop at right edge + ] + ] + ] + ] + image ;; Return the modified image +] + +;; Download the test image if not already cached locally +unless exists? file: %Unfilledcirc.png [ + write file read https://static.wikitide.net/rosettacodewiki/0/0f/Unfilledcirc.png +] + +img: load %Unfilledcirc.png +img: flood-fill img 200x200 white red +img: flood-fill img 100x100 black blue + +browse save %Filledcirc.png img ;; Save result and open in browser diff --git a/Task/Bitmap-Flood-fill/Uiua/bitmap-flood-fill.uiua b/Task/Bitmap-Flood-fill/Uiua/bitmap-flood-fill.uiua new file mode 100644 index 0000000000..0808eee12c --- /dev/null +++ b/Task/Bitmap-Flood-fill/Uiua/bitmap-flood-fill.uiua @@ -0,0 +1,12 @@ +# Drop a png onto this pane, then Run. +&p$"Found a _" °img&frab "image.png" +≡≡⊢ # Convert to greyscale. +Sensitivity ← 0.3 # Lower is finer. +N₄ ← [1_0 0_1 ¯ 1_0 0_¯1] +[40_40]⊙0.8 # Starting point, fill colour. +Good ← >Sensitivity⌵-⬚0.5⊡⊢ # Needs filling. Simple edges-check. +# Take first of list. If needs fill, do so and then add +# its four neighbours into queue. Repeat until queue is empty. +⍢(⨬(↘1|◴⊂+N₄¤°⊂ ⊃(⋅∘|∘|⋅⋅⋅∘)◡(⍜(⊡|⋅∘)⊢))◡Good +| >0⧻) +⋅⊙⋅ diff --git a/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl b/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl index ccd3c7df5a..24f859e0a8 100644 --- a/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl +++ b/Task/Bitmap-Flood-fill/Zkl/bitmap-flood-fill-1.zkl @@ -4,11 +4,11 @@ fcn flood(pixmap, x,y, repl){ // slow! while(stack){ x,y:=stack.pop(); if((0<=y 0); +begin + for I in Picture'Range (1) loop + for J in Picture'Range (2) loop + declare + Count : Pixel_Count renames Result (Picture (I, J)); + begin + Count := Count + 1; + end; + end loop; + end loop; + return Result; +end Get_Histogram; diff --git a/Task/Bitmap-Histogram/Ada/bitmap-histogram-2.adb b/Task/Bitmap-Histogram/Ada/bitmap-histogram-2.adb new file mode 100644 index 0000000000..2a0092b9c2 --- /dev/null +++ b/Task/Bitmap-Histogram/Ada/bitmap-histogram-2.adb @@ -0,0 +1,17 @@ +function Median (H : Histogram) return Luminance is + From : Luminance := Luminance'First; + To : Luminance := Luminance'Last; + Left : Pixel_Count := H (From); + Right : Pixel_Count := H (To); +begin + while From /= To loop + if Left < Right then + From := From + 1; + Left := Left + H (From); + else + To := To - 1; + Right := Right + H (To); + end if; + end loop; + return From; +end Median; diff --git a/Task/Bitmap-Histogram/Ada/bitmap-histogram-3.adb b/Task/Bitmap-Histogram/Ada/bitmap-histogram-3.adb new file mode 100644 index 0000000000..684e132fe5 --- /dev/null +++ b/Task/Bitmap-Histogram/Ada/bitmap-histogram-3.adb @@ -0,0 +1,22 @@ + F1, F2 : File_Type; +begin + Open (F1, In_File, "city.ppm"); + declare + X : Image := Get_PPM (F1); + Y : Grayscale_Image := Grayscale (X); + T : Luminance := Median (Get_Histogram (Y)); + begin + Close (F1); + Create (F2, Out_File, "city_art.ppm"); + for I in Y'Range (1) loop + for J in Y'Range (2) loop + if Y (I, J) < T then + X (I, J) := Black; + else + X (I, J) := White; + end if; + end loop; + end loop; + Put_PPM (F2, X); + end; + Close (F2); diff --git a/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl b/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl index caccb395fa..ed4243ea46 100644 --- a/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl +++ b/Task/Bitmap-Histogram/FBSL/bitmap-histogram.fbsl @@ -20,31 +20,31 @@ FBSLTILE(FBSLFORM("B/w"), FBSLLOADIMAGE(blackwhite)) ' ditto, black-and-white RESIZE(FBSLFORM, 0, 0, 136, 162): CENTER(FBSLFORM): SHOW(FBSLFORM) BEGIN EVENTS ' main message loop - IF CBMSG = WM_CLOSE THEN DESTROY(ME) ' click any [X] button to quit + IF CBMSG = WM_CLOSE THEN DESTROY(ME) ' click any [X] button to quit END EVENTS SUB ToGrayScale() - FOR ptr = head TO tail STEP 3 - b = PEEK(ptr + 0, 1) ' Windows stores colors in BGR order - g = PEEK(ptr + 1, 1) - r = PEEK(ptr + 2, 1) - l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' derive luminance - POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' set pixel to shade of gray - m = m + l - NEXT - FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save grayscale image + FOR ptr = head TO tail STEP 3 + b = PEEK(ptr + 0, 1) ' Windows stores colors in BGR order + g = PEEK(ptr + 1, 1) + r = PEEK(ptr + 2, 1) + l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' derive luminance + POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' set pixel to shade of gray + m = m + l + NEXT + FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save grayscale image END SUB SUB ToBlackAndWhite() - STATIC b = CHR(0), w = CHR(255) ' initialize once - - m = m / (tail - head) * 3 ' derive median - FOR ptr = head TO tail STEP 3 - IF PEEK(ptr + 0, 1) < m THEN ' set pixel black - POKE(ptr + 0, b)(ptr + 1, b)(ptr + 2, b) - ELSE ' set pixel white - POKE(ptr + 0, w)(ptr + 1, w)(ptr + 2, w) - END IF - NEXT - FILEPUT(FILEOPEN(blackwhite, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save b/w image + STATIC b = CHR(0), w = CHR(255) ' initialize once + + m = m / (tail - head) * 3 ' derive median + FOR ptr = head TO tail STEP 3 + IF PEEK(ptr + 0, 1) < m THEN ' set pixel black + POKE(ptr + 0, b)(ptr + 1, b)(ptr + 2, b) + ELSE ' set pixel white + POKE(ptr + 0, w)(ptr + 1, w)(ptr + 2, w) + END IF + NEXT + FILEPUT(FILEOPEN(blackwhite, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' save b/w image END SUB diff --git a/Task/Bitmap-Histogram/PHP/bitmap-histogram.php b/Task/Bitmap-Histogram/PHP/bitmap-histogram.php index 631623d041..f2e10b03ca 100644 --- a/Task/Bitmap-Histogram/PHP/bitmap-histogram.php +++ b/Task/Bitmap-Histogram/PHP/bitmap-histogram.php @@ -1,11 +1,11 @@ -define('src_name', 'input.jpg'); // source image -define('dest_name', 'output.jpg'); // destination image +define('src_name', 'input.jpg'); // source image +define('dest_name', 'output.jpg'); // destination image -$img = imagecreatefromjpeg(src_name); // read image +$img = imagecreatefromjpeg(src_name); // read image if(empty($img)){ - echo 'Image could not be loaded!'; - exit; + echo 'Image could not be loaded!'; + exit; } $black = imagecolorallocate($img, 0, 0, 0); @@ -13,42 +13,42 @@ $white = imagecolorallocate($img, 255, 255, 255); $width = imagesx($img); $height = imagesy($img); -$array_lum = array(); // for storage of luminosity of each pixel -$sum_lum = 0; // total sum of luminosity -$average_lum = 0; // average luminosity of whole image +$array_lum = array(); // for storage of luminosity of each pixel +$sum_lum = 0; // total sum of luminosity +$average_lum = 0; // average luminosity of whole image -for($x = 0; $x < $width; $x++){ - for($y = 0; $y < $height; $y++){ - // read pixel value - $color = imagecolorat($img, $x, $y); - $r = ($color >> 16) & 0xFF; - $g = ($color >> 8) & 0xFF; - $b = $color & 0xFF; - // save pixel luminosity in temporary array - $array_lum[$x][$y] = ($r + $g + $b); - // add pixel luminosity to sum - $sum_lum += $array_lum[$x][$y]; - } +for($x = 0; $x < $width; $x++){ + for($y = 0; $y < $height; $y++){ + // read pixel value + $color = imagecolorat($img, $x, $y); + $r = ($color >> 16) & 0xFF; + $g = ($color >> 8) & 0xFF; + $b = $color & 0xFF; + // save pixel luminosity in temporary array + $array_lum[$x][$y] = ($r + $g + $b); + // add pixel luminosity to sum + $sum_lum += $array_lum[$x][$y]; + } } // calculate average luminosity $average_lum = $sum_lum / ($width * $height); -for($x = 0; $x < $width; $x++){ - for($y = 0; $y < $height; $y++){ - // pixel is brighter than average -> set white - // else -> set black - if($array_lum[$x][$y] > $average_lum){ - imagesetpixel($img, $x, $y, $white); - } - else{ - imagesetpixel($img, $x, $y, $black); - } - } +for($x = 0; $x < $width; $x++){ + for($y = 0; $y < $height; $y++){ + // pixel is brighter than average -> set white + // else -> set black + if($array_lum[$x][$y] > $average_lum){ + imagesetpixel($img, $x, $y, $white); + } + else{ + imagesetpixel($img, $x, $y, $black); + } + } } // save black and white image to dest_name imagejpeg($img, dest_name); if(!file_exists(dest_name)){ - echo 'Image not saved! Check permission!'; + echo 'Image not saved! Check permission!'; } diff --git a/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku b/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku index fa9a0b9efc..e94fea18fb 100644 --- a/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku +++ b/Task/Bitmap-Histogram/Raku/bitmap-histogram.raku @@ -7,8 +7,8 @@ class Bitmap { role PBM { has @.BM; method P4 returns Blob { - "P4\n{self.width} {self.height}\n".encode('ascii') - ~ Blob.new: self.BM + "P4\n{self.width} {self.height}\n".encode('ascii') + ~ Blob.new: self.BM } } diff --git a/Task/Bitmap-Histogram/Rebol/bitmap-histogram-1.rebol b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-1.rebol new file mode 100644 index 0000000000..94755e279b --- /dev/null +++ b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-1.rebol @@ -0,0 +1,27 @@ +Rebol [ + title: "Rosetta code: Bitmap/Histogram" + file: %Bitmap-Histogram.r3 + url: https://rosettacode.org/wiki/Bitmap/Bitmap-Histogram + needs: 3.21.9 +] + +;; Load source image from file +img: load %Lenna50.jpg +;; Extract luminosity as vector for statistical operations +vec: to vector! img/luminosity +;; Compute median brightness threshold +med: vec/median +;; Allocate 256-bucket uint32 histogram (one bucket per brightness level) +histogram: make vector! [uint32! 255] +;; In a single pass: build brightness histogram and threshold each pixel +forall vec [ + val: vec/1 + histogram/:val: histogram/:val + 1 ;; tally pixel's brightness bucket + vec/1: either val < med [0][255] ;; binarize: black or white +] +;; Inspect histogram distribution +? histogram +;; Write thresholded grayscale data back to image +img/gray: vec +;; Save result as PNG and open in browser +browse save %Lenna50-bw.png img diff --git a/Task/Bitmap-Histogram/Rebol/bitmap-histogram-2.rebol b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-2.rebol new file mode 100644 index 0000000000..2586976144 --- /dev/null +++ b/Task/Bitmap-Histogram/Rebol/bitmap-histogram-2.rebol @@ -0,0 +1,8 @@ +img: load %Lenna50.jpg +foreach channel [red green blue] [ + vec: to vector! img/:channel + med: vec/median + forall vec [vec/1: either vec/1 < med [0][255]] + img/:channel: vec +] +browse save %Lenna50-rgb.png img diff --git a/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala b/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala index 4646774d80..2d5144c867 100644 --- a/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala +++ b/Task/Bitmap-Histogram/Scala/bitmap-histogram-1.scala @@ -27,6 +27,6 @@ object BitmapOps { val c2=Color.WHITE for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y))) image.setPixel(x, y, if(l>threshold) c2 else c1) - image + image } } diff --git a/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit b/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit index df0380645d..8018fff516 100644 --- a/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit +++ b/Task/Bitmap-Histogram/Vedit-macro-language/bitmap-histogram.vedit @@ -1,10 +1,10 @@ :HISTOGRAM: -#30 = Buf_Free // #30 = buffer to store histogram data +#30 = Buf_Free // #30 = buffer to store histogram data for (#9=0; #9<256; #9++) { - Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted - Buf_Switch(#15) // switch to image buffer - #8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values - Buf_Switch(#30) // switch to histogram buffer - Num_Ins(#8, FILL) // store count + Out_Reg(21) TC(#9) Out_Reg(Clear) // @21 = intensity value to be counted + Buf_Switch(#15) // switch to image buffer + #8 = Search(@21, CASE+BEGIN+ALL+NOERR) // count intensity values + Buf_Switch(#30) // switch to histogram buffer + Num_Ins(#8, FILL) // store count } Return diff --git a/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl b/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl index 5d99339833..69d94f35f3 100644 --- a/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl +++ b/Task/Bitmap-Histogram/Zkl/bitmap-histogram-1.zkl @@ -1,5 +1,5 @@ fcn histogram(image){ - hist:=List.createLong(256,0); // array[256] of zero + hist:=List.createLong(256,0); // array[256] of zero image.data.howza(0).pump(Void,'wrap(c){ hist[c]+=1 }); // byte by byte loop hist; } @@ -8,7 +8,7 @@ fcn histogramMedian(hist){ left,right:=hist[from],hist[to]; while(from!=to){ if(left= 0 then + Y := Y - 1; + ddF_Y := ddF_Y + 2; + F := F + ddF_Y; + end if; + X := X + 1; + ddF_X := ddF_X + 2; + F := F + ddF_X + 1; + Picture (Center.X + X, Center.Y + Y) := Color; + Picture (Center.X - X, Center.Y + Y) := Color; + Picture (Center.X + X, Center.Y - Y) := Color; + Picture (Center.X - X, Center.Y - Y) := Color; + Picture (Center.X + Y, Center.Y + X) := Color; + Picture (Center.X - Y, Center.Y + X) := Color; + Picture (Center.X + Y, Center.Y - X) := Color; + Picture (Center.X - Y, Center.Y - X) := Color; + end loop; +end Circle; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Ada/bitmap-midpoint-circle-algorithm-2.adb b/Task/Bitmap-Midpoint-circle-algorithm/Ada/bitmap-midpoint-circle-algorithm-2.adb new file mode 100644 index 0000000000..2965984410 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Ada/bitmap-midpoint-circle-algorithm-2.adb @@ -0,0 +1,5 @@ + X : Image (1..16, 1..16); +begin + Fill (X, White); + Circle (X, (8, 8), 5, Black); + Print (X); diff --git a/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic b/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic index bacbdc429a..149c596ea0 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic +++ b/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic @@ -7,33 +7,33 @@ color blue call DrawCircle(200,200,50) refresh - #Function DrawCircle - #1st param = X-coord of center - #2nd param = Y-coord of center - #3rd param = radius + #Function DrawCircle + #1st param = X-coord of center + #2nd param = Y-coord of center + #3rd param = radius Function DrawCircle(x0,y0,radius) - x=radius - y=0 - decisionOver2=1-x + x=radius + y=0 + decisionOver2=1-x - while x>=y - plot( x + x0, y + y0) - plot( y + x0, x + y0) - plot(-x + x0, y + y0) - plot(-y + x0, x + y0) - plot(-x + x0, -y + y0) - plot(-y + x0, -x + y0) - plot( x + x0, -y + y0) - plot( y + x0, -x + y0) + while x>=y + plot( x + x0, y + y0) + plot( y + x0, x + y0) + plot(-x + x0, y + y0) + plot(-y + x0, x + y0) + plot(-x + x0, -y + y0) + plot(-y + x0, -x + y0) + plot( x + x0, -y + y0) + plot( y + x0, -x + y0) - y++ + y++ - if decisionOver2<=0 then - decisionOver2+=2*y+1 - else - x-- - decisionOver2+=2*(y-x)+1 - end if - end while - return 0 + if decisionOver2<=0 then + decisionOver2+=2*y+1 + else + x-- + decisionOver2+=2*(y-x)+1 + end if + end while + return 0 End Function diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat b/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat index 45665a2733..ba0ddcb5fe 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat +++ b/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat @@ -1,7 +1,7 @@ @echo off setlocal enabledelayedexpansion - %== Initializations ==% + %== Initializations ==% set width=50 set height=30 @@ -11,62 +11,62 @@ echo Rendering... set "outp=" for /l %%i in (1,1,%height%) do ( - for /l %%j in (1,1,%width%) do ( - set "c[%%i][%%j]= " - ) + for /l %%j in (1,1,%width%) do ( + set "c[%%i][%%j]= " + ) ) - %== Set the parameters for making circle ==% + %== Set the parameters for making circle ==% call :DrawCircle 20 20 10 call :DrawCircle 10 30 15 - %== Output result ==% + %== Output result ==% for /l %%i in (1,1,%height%) do ( - for /l %%j in (1,1,%width%) do ( - set "outp=!outp!!c[%%i][%%j]!" - ) + for /l %%j in (1,1,%width%) do ( + set "outp=!outp!!c[%%i][%%j]!" + ) ) cls echo !outp! pause>nul exit /b - %== The main function ==% + %== The main function ==% :DrawCircle - set x0=%1 - set y0=%2 - set radius=%3 + set x0=%1 + set y0=%2 + set radius=%3 - set x=!radius! - set y=0 - set /a decisionOver2 = 1 - !x! + set x=!radius! + set y=0 + set /a decisionOver2 = 1 - !x! - :circle_loop - if !x! geq !y! ( - set /a "hor=x + x0","ver=y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=y + x0","ver=x + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-x + x0","ver=y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-y + x0","ver=x + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-x + x0","ver=-y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=-y + x0","ver=-x + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=x + x0","ver=-y + y0" - set "c[!hor!][!ver!]=Û" - set /a "hor=y + x0","ver=-x + y0" - set "c[!hor!][!ver!]=Û" + :circle_loop + if !x! geq !y! ( + set /a "hor=x + x0","ver=y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=y + x0","ver=x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-x + x0","ver=y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-y + x0","ver=x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-x + x0","ver=-y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-y + x0","ver=-x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=x + x0","ver=-y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=y + x0","ver=-x + y0" + set "c[!hor!][!ver!]=Û" - set /a y+=1 - if !decisionOver2! leq 0 ( - set /a "decisionOver2 = !decisionOver2! + (2 * y^) + 1" - ) else ( - set /a x-=1 - set /a "decisionOver2 = !decisionOver2! + 2 * (y - x^) + 1" - ) - goto circle_loop - ) + set /a y+=1 + if !decisionOver2! leq 0 ( + set /a "decisionOver2 = !decisionOver2! + (2 * y^) + 1" + ) else ( + set /a x-=1 + set /a "decisionOver2 = !decisionOver2! + 2 * (y - x^) + 1" + ) + goto circle_loop + ) goto :EOF diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-1.cr b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-1.cr new file mode 100644 index 0000000000..662403d75a --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-1.cr @@ -0,0 +1,40 @@ +require "./pixmap" +require "./bresenham" + +class Pixmap + def circle (cx, cy, r, color, fill = false) + f = 1 - r + ddF_X = 0 + ddF_Y = -2 * r + x = 0 + y = r + self[cx, cy + r] = color + self[cx, cy - r] = color + p1, p2 = {cx + r, cy}, {cx - r, cy} + if fill + line(*p1, *p2, color) + else + self[*p1] = self[*p2] = color + end + while x < y + if f >= 0 + y -= 1 + ddF_Y += 2 + f += ddF_Y + end + x += 1 + ddF_X += 2 + f += ddF_X + 1 + [{cx - x, cy - y}, {cx + x, cy - y}, + {cx - x, cy + y}, {cx + x, cy + y}, + {cx - y, cy - x}, {cx + y, cy - x}, + {cx - y, cy + x}, {cx + y, cy + x}].each_slice(2, reuse: true) do |(p1, p2)| + if fill + line(*p1, *p2, color) + else + self[*p1] = self[*p2] = color + end + end + end + end +end diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-2.cr b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-2.cr new file mode 100644 index 0000000000..821729bbd3 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Crystal/bitmap-midpoint-circle-algorithm-2.cr @@ -0,0 +1,12 @@ +require "./circle" +require "./write_ppm" + +img = Pixmap.new 100, 100, Color::WHITE + +img.circle 50, 50, 40, Color::RED, true +img.circle 70, 60, 15, Color::BLUE, true +img.circle 40, 20, 20, Color::BLACK +img.circle 40, 20, 19, Color.new(255, 144, 0) +img.circle 40, 20, 18, Color::BLACK + +img.write "crystal_circles.ppm" diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas b/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas index a27d5aad00..70e6487fce 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas +++ b/Task/Bitmap-Midpoint-circle-algorithm/Delphi/bitmap-midpoint-circle-algorithm.pas @@ -3,18 +3,18 @@ var T1,T2: integer; var X,Y: integer; var Cnt: integer; - procedure DrawPixels(X,Y: integer); - {Draw pixel into all 8 octents} - begin - Image.Canvas.Pixels[Center.X + x, Center.Y + y]:=clRed; - Image.Canvas.Pixels[Center.X - X, Center.Y + Y]:=clRed; - Image.Canvas.Pixels[Center.X + X, Center.Y - Y]:=clRed; - Image.Canvas.Pixels[Center.X - X, Center.Y - Y]:=clRed; - Image.Canvas.Pixels[Center.X + Y, Center.Y + X]:=clRed; - Image.Canvas.Pixels[Center.X - Y, Center.Y + X]:=clRed; - Image.Canvas.Pixels[Center.X + y, Center.Y - X]:=clRed; - Image.Canvas.Pixels[Center.X - Y, Center.Y - X]:=clRed; - end; + procedure DrawPixels(X,Y: integer); + {Draw pixel into all 8 octents} + begin + Image.Canvas.Pixels[Center.X + x, Center.Y + y]:=clRed; + Image.Canvas.Pixels[Center.X - X, Center.Y + Y]:=clRed; + Image.Canvas.Pixels[Center.X + X, Center.Y - Y]:=clRed; + Image.Canvas.Pixels[Center.X - X, Center.Y - Y]:=clRed; + Image.Canvas.Pixels[Center.X + Y, Center.Y + X]:=clRed; + Image.Canvas.Pixels[Center.X - Y, Center.Y + X]:=clRed; + Image.Canvas.Pixels[Center.X + y, Center.Y - X]:=clRed; + Image.Canvas.Pixels[Center.X - Y, Center.Y - X]:=clRed; + end; begin Cnt:=0; @@ -22,18 +22,18 @@ T1:= Radius div 32; {Start on X-axis} X:= Radius; Y:= 0; repeat - begin - DrawPixels(X, Y); - Y:=Y + 1; - T1:=T1 + Y; - T2:=T1 - X; - if T2 >= 0 then - begin - T1:=T2; - X:=X - 1; - end; - Inc(Cnt); - end + begin + DrawPixels(X, Y); + Y:=Y + 1; + T1:=T1 + Y; + T2:=T1 - X; + if T2 >= 0 then + begin + T1:=T2; + X:=X - 1; + end; + Inc(Cnt); + end until x < y; Form1.Caption:=IntToStr(Cnt); end; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl b/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl index 4ab0e557c9..c26d8ea33c 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl +++ b/Task/Bitmap-Midpoint-circle-algorithm/FBSL/bitmap-midpoint-circle-algorithm.fbsl @@ -13,29 +13,29 @@ DIM Breadth AS INTEGER, Height AS INTEGER FBSL.GETCLIENTRECT(ME, 0, 0, Breadth, Height) BEGIN EVENTS ' Main message loop - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN: MidpointCircle() ' Draw - CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN: MidpointCircle() ' Draw + CASE WM_CLOSE: FBSL.RELEASEDC(ME, FBSL.GETDC) ' Clean up + END SELECT END EVENTS SUB MidpointCircle() - BresenhamCircle(Breadth \ 2, Height \ 2, 80, &HFF) ' Red: Windows stores colors in BGR order - BresenhamCircle(Breadth \ 2, Height \ 2, 40, 0) ' Black - - SUB BresenhamCircle(cx, cy, radius, colour) - DIM x = 0, y = radius, f = 1 - radius, dx = 0, dy = -2 * radius - - PSET(FBSL.GETDC, cx, cy + radius, colour)(FBSL.GETDC, cx, cy - radius, colour) - PSET(FBSL.GETDC, cx + radius, cy, colour)(FBSL.GETDC, cx - radius, cy, colour) - - WHILE x < y - IF f >= 0 THEN: DECR(y): INCR(dy, 2)(f, dy): END IF ' Try also "IF f THEN" :) - INCR(x)(dx, 2)(f, dx + 1) - PSET(FBSL.GETDC, cx + x, cy + y, colour)(FBSL.GETDC, cx - x, cy + y, colour) - PSET(FBSL.GETDC, cx + x, cy - y, colour)(FBSL.GETDC, cx - x, cy - y, colour) - PSET(FBSL.GETDC, cx + y, cy + x, colour)(FBSL.GETDC, cx - y, cy + x, colour) - PSET(FBSL.GETDC, cx + y, cy - x, colour)(FBSL.GETDC, cx - y, cy - x, colour) - WEND - END SUB + BresenhamCircle(Breadth \ 2, Height \ 2, 80, &HFF) ' Red: Windows stores colors in BGR order + BresenhamCircle(Breadth \ 2, Height \ 2, 40, 0) ' Black + + SUB BresenhamCircle(cx, cy, radius, colour) + DIM x = 0, y = radius, f = 1 - radius, dx = 0, dy = -2 * radius + + PSET(FBSL.GETDC, cx, cy + radius, colour)(FBSL.GETDC, cx, cy - radius, colour) + PSET(FBSL.GETDC, cx + radius, cy, colour)(FBSL.GETDC, cx - radius, cy, colour) + + WHILE x < y + IF f >= 0 THEN: DECR(y): INCR(dy, 2)(f, dy): END IF ' Try also "IF f THEN" :) + INCR(x)(dx, 2)(f, dx + 1) + PSET(FBSL.GETDC, cx + x, cy + y, colour)(FBSL.GETDC, cx - x, cy + y, colour) + PSET(FBSL.GETDC, cx + x, cy - y, colour)(FBSL.GETDC, cx - x, cy - y, colour) + PSET(FBSL.GETDC, cx + y, cy + x, colour)(FBSL.GETDC, cx - y, cy + x, colour) + PSET(FBSL.GETDC, cx + y, cy - x, colour)(FBSL.GETDC, cx - y, cy - x, colour) + WEND + END SUB END SUB diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java b/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java index 9019b3a968..67697a0840 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java +++ b/Task/Bitmap-Midpoint-circle-algorithm/Java/bitmap-midpoint-circle-algorithm.java @@ -1,35 +1,35 @@ import java.awt.Color; public class MidPointCircle { - private BasicBitmapStorage image; + private BasicBitmapStorage image; - public MidPointCircle(final int imageWidth, final int imageHeight) { - this.image = new BasicBitmapStorage(imageWidth, imageHeight); - } + public MidPointCircle(final int imageWidth, final int imageHeight) { + this.image = new BasicBitmapStorage(imageWidth, imageHeight); + } - private void drawCircle(final int centerX, final int centerY, final int radius) { - int d = (5 - radius * 4)/4; - int x = 0; - int y = radius; - Color circleColor = Color.white; + private void drawCircle(final int centerX, final int centerY, final int radius) { + int d = (5 - radius * 4)/4; + int x = 0; + int y = radius; + Color circleColor = Color.white; - do { - image.setPixel(centerX + x, centerY + y, circleColor); - image.setPixel(centerX + x, centerY - y, circleColor); - image.setPixel(centerX - x, centerY + y, circleColor); - image.setPixel(centerX - x, centerY - y, circleColor); - image.setPixel(centerX + y, centerY + x, circleColor); - image.setPixel(centerX + y, centerY - x, circleColor); - image.setPixel(centerX - y, centerY + x, circleColor); - image.setPixel(centerX - y, centerY - x, circleColor); - if (d < 0) { - d += 2 * x + 1; - } else { - d += 2 * (x - y) + 1; - y--; - } - x++; - } while (x <= y); + do { + image.setPixel(centerX + x, centerY + y, circleColor); + image.setPixel(centerX + x, centerY - y, circleColor); + image.setPixel(centerX - x, centerY + y, circleColor); + image.setPixel(centerX - x, centerY - y, circleColor); + image.setPixel(centerX + y, centerY + x, circleColor); + image.setPixel(centerX + y, centerY - x, circleColor); + image.setPixel(centerX - y, centerY + x, circleColor); + image.setPixel(centerX - y, centerY - x, circleColor); + if (d < 0) { + d += 2 * x + 1; + } else { + d += 2 * (x - y) + 1; + y--; + } + x++; + } while (x <= y); - } + } } diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-1.pluto b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-1.pluto new file mode 100644 index 0000000000..c0d4f3ed9c --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-1.pluto @@ -0,0 +1,33 @@ +local canvas = require "canvas" + +local function trunc(x) return x >= 0 ? math.floor(x) : math.ceil(x) end + +local function circle(c, cx, cy, r, col) + local d = trunc((5 - r * 4) / 4) + local x = 0 + local y = r + repeat + c:set(cx + x, cy + y, col) + c:set(cx + x, cy - y, col) + c:set(cx - x, cy + y, col) + c:set(cx - x, cy - y, col) + c:set(cx + y, cy + x, col) + c:set(cx + y, cy - x, col) + c:set(cx - y, cy + x, col) + c:set(cx - y, cy - x, col) + if d < 0 then + d += 2 * x + 1 + else + d += 2 * (x - y) + 1 + y -= 1 + end + ++x + until x > y +end + +local c = canvas.new(400, 400) +c:fill(0xffffff) -- white background + +-- Draw a blue circle with centre at (200, 200) and radius 100. +circle(c, 200, 200, 100, 0xff0000) +io.contents("mybmp.bmp", c:tobmp()) -- save to a bitmap file diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-2.pluto b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-2.pluto new file mode 100644 index 0000000000..97f3494948 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Pluto/bitmap-midpoint-circle-algorithm-2.pluto @@ -0,0 +1,6 @@ +require "bitmap" + +local bmp = bitmap.of(400, 400, color.white, "mybmp") +bmp:circle(200, 200, 100, color.blue) +bmp:view() +bmp:save() -- if required diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Rebol/bitmap-midpoint-circle-algorithm.rebol b/Task/Bitmap-Midpoint-circle-algorithm/Rebol/bitmap-midpoint-circle-algorithm.rebol new file mode 100644 index 0000000000..fe3a8f7661 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Rebol/bitmap-midpoint-circle-algorithm.rebol @@ -0,0 +1,49 @@ +Rebol [ + title: "Rosetta code: Bitmap/Midpoint circle algorithm" + file: %Bitmap-Midpoint_circle_algorithm.r3 + url: https://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm +] + +draw-circle: func [ + "Draw a circle on an image using the Midpoint Circle Algorithm." + bitmap [image!] center [pair!] radius [integer!] color [tuple!] +][ + x: center/x ;; unpack center coords from pair for arithmetic + y: center/y + dx: radius dy: 0 + err: 1 - radius ;; initial error term for midpoint decision + + while [dx >= dy] [ ;; iterate through the first octant only + ;; Mirror the single computed point into all 8 octants at once, + ;; exploiting the 8-fold symmetry of the circle. + bitmap/(as-pair x + dx y + dy): color ; octant 1 + bitmap/(as-pair x - dx y + dy): color ; octant 2 + bitmap/(as-pair x + dx y - dy): color ; octant 8 + bitmap/(as-pair x - dx y - dy): color ; octant 7 + bitmap/(as-pair x + dy y + dx): color ; octant 3 + bitmap/(as-pair x - dy y + dx): color ; octant 4 (swapped dx/dy) + bitmap/(as-pair x + dy y - dx): color ; octant 5 + bitmap/(as-pair x - dy y - dx): color ; octant 6 + + dy: dy + 1 ;; advance one step along the minor axis + + ;; Update the error term and conditionally step inward on dx. + ;; err < 0 means we are still inside the circle boundary + either err < 0 [ + err: err + (2 * dy) + 1 ;; correct error for dy step + ][ + dx: dx - 1 ;; step inward on major axis + err: err + (2 * (dy - dx)) + 1 ;; correct error for both steps + ] + ] +] + +img: make image! 29x29 ;; create a blank 29x29 canvas (white by default) +draw-circle img 15x15 5 black ;; small inner circle +draw-circle img 15x15 10 red ;; mid-size red ring +draw-circle img 15x15 14 green ;; large green ring, nearly fills the canvas + +;; scale up 10x with nearest-neighbour (Box) to keep pixel edges sharp +img: resize/filter img 290 'Box +save %midpoint-circles.png img +try [view img] diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala b/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala index a9a9542002..1cb33f2446 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala +++ b/Task/Bitmap-Midpoint-circle-algorithm/Scala/bitmap-midpoint-circle-algorithm.scala @@ -22,7 +22,7 @@ object BitmapOps { x+=1 ddF_x+=2 f+=ddF_x - + bm.setPixel(x0+x, y0+y, c) bm.setPixel(x0-x, y0+y, c) bm.setPixel(x0+x, y0-y, c) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh b/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh index c11e2e9da6..e4db4df45c 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh +++ b/Task/Bitmap-Midpoint-circle-algorithm/UNIX-Shell/bitmap-midpoint-circle-algorithm.sh @@ -13,10 +13,10 @@ function drawcircle { for y in $( seq $((y0-radius)) $((y0+radius)) ) do echo -en "\e[${y}H" - for x in $( seq $((x0+radius)) ) - do - echo -n "-" - done + for x in $( seq $((x0+radius)) ) + do + echo -n "-" + done done x=$((radius-1)) @@ -38,12 +38,12 @@ function drawcircle { if [ $err -le 0 ] then - ((++y)) + ((++y)) ((err+=dy)) ((dy+=2)) fi if [ $err -gt 0 ] - then + then ((--x)) ((dx+=2)) ((err+=dx-(radius<<1))) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit b/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit index 3a37522166..96c740f247 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit +++ b/Task/Bitmap-Midpoint-circle-algorithm/Vedit-macro-language/bitmap-midpoint-circle-algorithm.vedit @@ -2,11 +2,11 @@ // #21 = center x, #22 = center y; #23 = radius :DRAW_CIRCLE: -#30 = 1 - #23 // f -#31 = 0 // ddF_x -#32 = -2 * #23 // ddF_y -#41 = 0 // x -#42 = #23 // y +#30 = 1 - #23 // f +#31 = 0 // ddF_x +#32 = -2 * #23 // ddF_y +#41 = 0 // x +#42 = #23 // y while (#41 <= #42) { #1 = #21+#41; #2 = #22+#42; Call("DRAW_PIXEL") @@ -18,9 +18,9 @@ while (#41 <= #42) { #1 = #21+#42; #2 = #22-#41; Call("DRAW_PIXEL") #1 = #21-#42; #2 = #22-#41; Call("DRAW_PIXEL") if (#30 >= 0) { - #42-- - #32 += 2 - #30 += #32 + #42-- + #32 += 2 + #30 += #32 } #41++ #31 += 2 diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl index f651983a78..82685d593e 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl +++ b/Task/Bitmap-Midpoint-circle-algorithm/Zkl/bitmap-midpoint-circle-algorithm-1.zkl @@ -2,15 +2,15 @@ x:=r; y:=0; radiusError:=1-x; while(x >= y){ __sSet(rgb, x + x0, y + y0); - __sSet(rgb, y + x0, x + y0); - __sSet(rgb,-x + x0, y + y0); - __sSet(rgb,-y + x0, x + y0); - self[-x + x0, -y + y0]=rgb; // or do it this way, __sSet gets called as above - self[-y + x0, -x + y0]=rgb; - self[ x + x0, -y + y0]=rgb; - self[ y + x0, -x + y0]=rgb; - y+=1; - if (radiusError<0) radiusError+=2*y + 1; - else{ x-=1; radiusError+=2*(y - x + 1); } + __sSet(rgb, y + x0, x + y0); + __sSet(rgb,-x + x0, y + y0); + __sSet(rgb,-y + x0, x + y0); + self[-x + x0, -y + y0]=rgb; // or do it this way, __sSet gets called as above + self[-y + x0, -x + y0]=rgb; + self[ x + x0, -y + y0]=rgb; + self[ y + x0, -x + y0]=rgb; + y+=1; + if (radiusError<0) radiusError+=2*y + 1; + else{ x-=1; radiusError+=2*(y - x + 1); } } } diff --git a/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.adb b/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.adb new file mode 100644 index 0000000000..f65e4e307b --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-1.adb @@ -0,0 +1,70 @@ +with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; + +function Get_PPM (File : File_Type) return Image is + use Ada.Characters.Latin_1; + use Ada.Integer_Text_IO; + + function Get_Line return String is -- Skips comments + Byte : Character; + Buffer : String (1..80); + begin + loop + for I in Buffer'Range loop + Character'Read (Stream (File), Byte); + if Byte = LF then + exit when Buffer (1) = '#'; + return Buffer (1..I - 1); + end if; + Buffer (I) := Byte; + end loop; + if Buffer (1) /= '#' then + raise Data_Error; + end if; + end loop; + end Get_Line; + + Height : Integer; + Width : Integer; +begin + if Get_Line /= "P6" then + raise Data_Error; + end if; + declare + Line : String := Get_Line; + Start : Integer := Line'First; + Last : Positive; + begin + Get (Line, Width, Last); Start := Start + Last; + Get (Line (Start..Line'Last), Height, Last); Start := Start + Last; + if Start <= Line'Last then + raise Data_Error; + end if; + if Width < 1 or else Height < 1 then + raise Data_Error; + end if; + end; + if Get_Line /= "255" then + raise Data_Error; + end if; + declare + Result : Image (1..Height, 1..Width); + Buffer : String (1..Width * 3); + Index : Positive; + begin + for I in Result'Range (1) loop + String'Read (Stream (File), Buffer); + Index := Buffer'First; + for J in Result'Range (2) loop + Result (I, J) := + ( R => Luminance (Character'Pos (Buffer (Index))), + G => Luminance (Character'Pos (Buffer (Index + 1))), + B => Luminance (Character'Pos (Buffer (Index + 2))) + ); + Index := Index + 3; + end loop; + end loop; + return Result; + end; +end Get_PPM; diff --git a/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.adb b/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.adb new file mode 100644 index 0000000000..2c362394f4 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Ada/bitmap-read-a-ppm-file-2.adb @@ -0,0 +1,9 @@ +declare + F1, F2 : File_Type; +begin + Open (F1, In_File, "city.ppm"); + Create (F2, Out_File, "city_grayscale.ppm"); + Put_PPM (F2, Color (Grayscale (Get_PPM (F1)))); + Close (F1); + Close (F2); +end; diff --git a/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk b/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk index 13ce33a881..df5682b996 100644 --- a/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk +++ b/Task/Bitmap-Read-a-PPM-file/AutoHotkey/bitmap-read-a-ppm-file.ahk @@ -46,11 +46,11 @@ loop % width * height if (j == width) { - j := 1 - i += 1 + j := 1 + i += 1 } else - j++ + j++ } return bitmap } diff --git a/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp b/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp index 511eba41d7..c68f4c654d 100644 --- a/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp +++ b/Task/Bitmap-Read-a-PPM-file/Common-Lisp/bitmap-read-a-ppm-file-1.lisp @@ -13,59 +13,59 @@ (defun read-ppm-file-header (file) (with-open-file (s file :direction :input) (do ((failure-count 0 (1+ failure-count)) - (tokens nil (let ((t1 (read-header-chars s))) - (if (> (length t1) 0) - (cons t1 tokens) - tokens)))) - ((>= (length tokens) 4) (values (nreverse tokens) - (file-position s))) + (tokens nil (let ((t1 (read-header-chars s))) + (if (> (length t1) 0) + (cons t1 tokens) + tokens)))) + ((>= (length tokens) 4) (values (nreverse tokens) + (file-position s))) (when (>= failure-count 10) - (error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file))) + (error (format nil "File ~a does not seem to be a proper ppm file - maybe too many comment lines" file))) (when (= (length tokens) 1) - (when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3"))) - (error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens)))))))) + (when (not (or (string= (first tokens) "P6") (string= (first tokens) "P3"))) + (error (format nil "File ~a is not a ppm file - wrong magic-number. Read ~a instead of P6 or P3 " file (first tokens)))))))) (defun read-ppm-image (file) (flet ((image-data-reader (stream start-position width height image-build-function read-function) - (file-position stream start-position) - (dotimes (row height) - (dotimes (col width) - (funcall image-build-function row col (funcall read-function stream)))))) + (file-position stream start-position) + (dotimes (row height) + (dotimes (col width) + (funcall image-build-function row col (funcall read-function stream)))))) (multiple-value-bind (header file-pos) (read-ppm-file-header file) (let* ((image-type (first header)) - (width (parse-integer (second header) :junk-allowed t)) - (height (parse-integer (third header) :junk-allowed t)) - (max-value (parse-integer (fourth header) :junk-allowed t)) - (image (make-rgb-pixel-buffer width height))) - (when (> max-value 255) - (error "unsupported depth - convert to 1byte depth with pamdepth")) - (cond ((string= "P6" image-type) - (with-open-file (stream file :direction :input :element-type '(unsigned-byte 8)) - (image-data-reader stream - file-pos - width - height - #'(lambda (w h val) - (setf (rgb-pixel image w h) val)) - #'(lambda (stream) - (make-rgb-pixel (read-byte stream) - (read-byte stream) - (read-byte stream)))) - image)) - ((string= "P3" image-type) - (with-open-file (stream file :direction :input) - (image-data-reader stream - file-pos - width - height - #'(lambda (w h val) - (setf (rgb-pixel image w h) val)) - #'(lambda (stream) - (make-rgb-pixel (read stream) - (read stream) - (read stream)))) - image)) - (t 'unsupported)) + (width (parse-integer (second header) :junk-allowed t)) + (height (parse-integer (third header) :junk-allowed t)) + (max-value (parse-integer (fourth header) :junk-allowed t)) + (image (make-rgb-pixel-buffer width height))) + (when (> max-value 255) + (error "unsupported depth - convert to 1byte depth with pamdepth")) + (cond ((string= "P6" image-type) + (with-open-file (stream file :direction :input :element-type '(unsigned-byte 8)) + (image-data-reader stream + file-pos + width + height + #'(lambda (w h val) + (setf (rgb-pixel image w h) val)) + #'(lambda (stream) + (make-rgb-pixel (read-byte stream) + (read-byte stream) + (read-byte stream)))) + image)) + ((string= "P3" image-type) + (with-open-file (stream file :direction :input) + (image-data-reader stream + file-pos + width + height + #'(lambda (w h val) + (setf (rgb-pixel image w h) val)) + #'(lambda (stream) + (make-rgb-pixel (read stream) + (read stream) + (read stream)))) + image)) + (t 'unsupported)) image)))) (export 'read-ppm-image) diff --git a/Task/Bitmap-Read-a-PPM-file/Crystal/bitmap-read-a-ppm-file.cr b/Task/Bitmap-Read-a-PPM-file/Crystal/bitmap-read-a-ppm-file.cr new file mode 100644 index 0000000000..4b8e3b6639 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Crystal/bitmap-read-a-ppm-file.cr @@ -0,0 +1,51 @@ +require "./pixmap" + +class Pixmap + def self.load_ppm (io) + blanks = StaticArray[9, 10, 11, 12, 13, 32] + magic = Bytes.new(3) + io.read magic + raise "Invalid format" unless magic[0] == 'P'.ord && + magic[1] == '6'.ord && + magic[2].in? blanks + data = io.getb_to_end + pos = 0 + get_number = -> : Int32 { + start = pos + loop do # skip blanks and comments + case data[start] + when .in? blanks then start += 1 + when '#'.ord + while data[start] != 10 + start += 1 + end + else break + end + end + stop = start + until data[stop].in? blanks + stop += 1 + end + pos = stop + String.new(data[start..stop]).to_i + } + begin + width = get_number.call + height = get_number.call + maxval = get_number.call + rescue ex + raise "Bad P6 file" + end + raise "Unsupported color depth" unless maxval = 255 + pos += 1 + raise "Invalid data" unless (data.size - pos) % 3 == 0 + len = (data.size - pos) // 3 + raise "Bad bounds" unless len == width * height + pixels = Array(Color).new(len) { |i| + Color.new(data[i*3 + pos], data[i*3 + pos + 1], data[i*3 + pos + 2]) + } + Pixmap.new width, height, pixels + end + + register_loader ".ppm", load_ppm +end diff --git a/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.eu b/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.eu new file mode 100644 index 0000000000..43a403152e --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-1.eu @@ -0,0 +1,41 @@ +include get.e + +function get2(integer fn) + sequence temp + temp = get(fn) + return temp[2] - temp[1]*temp[1] +end function + +function read_ppm(sequence filename) + sequence image, line + integer dimx, dimy, maxcolor + atom fn + fn = open(filename, "rb") + if fn < 0 then + return -1 -- unable to open + end if + line = gets(fn) + if not equal(line,"P6\n") then + return -1 -- only ppm6 files are supported + end if + dimx = get2(fn) + if dimx < 0 then + return -1 + end if + dimy = get2(fn) + if dimy < 0 then + return -1 + end if + maxcolor = get2(fn) + if maxcolor != 255 then + return -1 -- maxcolors other then 255 are not supported + end if + image = repeat(repeat(0,dimy),dimx) + for y = 1 to dimy do + for x = 1 to dimx do + image[x][y] = getc(fn)*#10000 + getc(fn)*#100 + getc(fn) + end for + end for + close(fn) + return image +end function diff --git a/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.eu b/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.eu new file mode 100644 index 0000000000..e23aa5fafd --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Euphoria/bitmap-read-a-ppm-file-2.eu @@ -0,0 +1,5 @@ +sequence image +image = read_ppm("image.ppm") +image = to_gray(image) +image = to_color(image) +write_ppm("image_gray.ppm",image) diff --git a/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl b/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl index b2d7f3528e..188aa0caa2 100644 --- a/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl +++ b/Task/Bitmap-Read-a-PPM-file/FBSL/bitmap-read-a-ppm-file.fbsl @@ -8,11 +8,11 @@ blobsize = INSTR(FILEGET, "\n255\n") + 4 ' Get sizeof PPM header head = @FILEGET + blobsize: tail = @FILEGET + FILELEN ' Set loop bounds FOR ptr = head TO tail STEP 3 ' Transform color triplets - r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order - g = PEEK(ptr + 1, 1) - b = PEEK(ptr + 2, 1) - l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance - POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale + r = PEEK(ptr + 0, 1) ' Read colors stored in RGB order + g = PEEK(ptr + 1, 1) + b = PEEK(ptr + 2, 1) + l = 0.2126 * r + 0.7152 * g + 0.0722 * b ' Derive luminance + POKE(ptr + 0, CHR(l))(ptr + 1, CHR)(ptr + 2, CHR) ' Write grayscale NEXT FILEPUT(FILEOPEN(grayscale, BINARY_NEW), FILEGET): FILECLOSE(FILEOPEN) ' Save buffer diff --git a/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth b/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth index 20b30e7793..28824390fc 100644 --- a/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth +++ b/Task/Bitmap-Read-a-PPM-file/Forth/bitmap-read-a-ppm-file.fth @@ -3,7 +3,7 @@ s" P6" compare abort" Only P6 supported." pad dup 80 fid read-line throw 0= abort" Partial line" 0. 2swap >number - 1 /string \ skip space + 1 /string \ skip space 0. 2swap >number 2drop drop nip ( w h ) bitmap { bmp } diff --git a/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java b/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java index 6d1e33c878..9670723d2d 100644 --- a/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java +++ b/Task/Bitmap-Read-a-PPM-file/Java/bitmap-read-a-ppm-file.java @@ -12,32 +12,32 @@ import javax.imageio.ImageIO; public class ReadPPMFile { - public static void main(String[] aArgs) throws IOException { + public static void main(String[] aArgs) throws IOException { // Using the file created in the Bitmap task - String filePath = "output.ppm"; - - reader = new BufferedInputStream( new FileInputStream(filePath) ); - final char header1 = (char) reader.read(); + String filePath = "output.ppm"; + + reader = new BufferedInputStream( new FileInputStream(filePath) ); + final char header1 = (char) reader.read(); final char header2 = (char) reader.read(); final char header3 = (char) reader.read(); if ( header1 != 'P' || header2 != '6' || header3 != END_OF_LINE) { - reader.close(); - throw new IllegalArgumentException("Not a valid P6 PPM file"); + reader.close(); + throw new IllegalArgumentException("Not a valid P6 PPM file"); } final int width = processCharacters(SPACE_CHARACTER); final int height = processCharacters(END_OF_LINE); final int maxColorValue = processCharacters(END_OF_LINE); if ( maxColorValue < 0 || maxColorValue > 255 ) { - reader.close(); - throw new IllegalArgumentException("Maximum color value is outside the range 0..255"); + reader.close(); + throw new IllegalArgumentException("Maximum color value is outside the range 0..255"); } // Remove any comments before reading data reader.mark(1); while ( reader.read() == START_OF_COMMENT ) { - while ( reader.read() != END_OF_LINE ); - reader.mark(1); + while ( reader.read() != END_OF_LINE ); + reader.mark(1); } reader.reset(); @@ -47,10 +47,10 @@ public class ReadPPMFile { byte[] buffer = new byte[width * 3]; for ( int y = 0; y < height; y++ ) { reader.read(buffer, 0, buffer.length); - for ( int x = 0; x < width; x++ ) { + for ( int x = 0; x < width; x++ ) { Color color = new Color(Byte.toUnsignedInt(buffer[x * 3]), - Byte.toUnsignedInt(buffer[x * 3 + 1]), - Byte.toUnsignedInt(buffer[x * 3 + 2])); + Byte.toUnsignedInt(buffer[x * 3 + 1]), + Byte.toUnsignedInt(buffer[x * 3 + 2])); bitmap.setPixel(x, y, color); } } @@ -60,29 +60,29 @@ public class ReadPPMFile { // Convert to gray scale and save to a file bitmap.convertToGrayscale(); File grayFile = new File("outputGray.jpg"); - ImageIO.write((RenderedImage) bitmap.getImage(), "jpg", grayFile); - } - - private static int processCharacters(char aChar) throws IOException { - StringBuilder characters = new StringBuilder(); - char ch; - while ( ( ch = (char) reader.read() ) != aChar ) { - if ( ch == START_OF_COMMENT ) { - while ( reader.read() != END_OF_LINE ); - continue; - } - characters.append(ch); - } - return Integer.valueOf(characters.toString()); - } - - private static BufferedInputStream reader; - - private static final char START_OF_COMMENT = '#'; - private static final char SPACE_CHARACTER = ' '; - private static final char END_OF_LINE = '\n'; + ImageIO.write((RenderedImage) bitmap.getImage(), "jpg", grayFile); + } -} + private static int processCharacters(char aChar) throws IOException { + StringBuilder characters = new StringBuilder(); + char ch; + while ( ( ch = (char) reader.read() ) != aChar ) { + if ( ch == START_OF_COMMENT ) { + while ( reader.read() != END_OF_LINE ); + continue; + } + characters.append(ch); + } + return Integer.valueOf(characters.toString()); + } + + private static BufferedInputStream reader; + + private static final char START_OF_COMMENT = '#'; + private static final char SPACE_CHARACTER = ' '; + private static final char END_OF_LINE = '\n'; + +} final class BasicBitmapStorage { @@ -105,12 +105,12 @@ final class BasicBitmapStorage { } public Image getImage() { - return image; + return image; } public void convertToGrayscale() { for ( int y = 0; y < image.getHeight(); y++ ) { - for ( int x = 0; x < image.getWidth(); x++ ) { + for ( int x = 0; x < image.getWidth(); x++ ) { int color = image.getRGB(x, y); int alpha = ( color >> 24 ) & 255; diff --git a/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz b/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz index 5d3fd1c6e4..33b5a7e6ef 100644 --- a/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz +++ b/Task/Bitmap-Read-a-PPM-file/Oz/bitmap-read-a-ppm-file-1.oz @@ -10,31 +10,31 @@ define F = {New Open.file init(name:Filename)} fun {ReadColor8 _} - Bytes = {F read(list:$ size:3)} + Bytes = {F read(list:$ size:3)} in - {List.toTuple color Bytes} + {List.toTuple color Bytes} end fun {ReadColor16 _} - Bytes = {F read(list:$ size:6)} + Bytes = {F read(list:$ size:6)} in - {List.toTuple color {Map {PairUp Bytes} FromBytes}} + {List.toTuple color {Map {PairUp Bytes} FromBytes}} end in try - Magic = {F read(size:2 list:$)} - if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end - Width = {ReadNumber F} - Height = {ReadNumber F} - MaxVal = {ReadNumber F} - MaxVal =< 0xffff = true - Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end - B = {Bitmap.new Width Height} + Magic = {F read(size:2 list:$)} + if Magic \= "P6" then raise bitmapIO(read unsupportedFormat(Magic)) end end + Width = {ReadNumber F} + Height = {ReadNumber F} + MaxVal = {ReadNumber F} + MaxVal =< 0xffff = true + Reader = if MaxVal =< 0xff then ReadColor8 else ReadColor16 end + B = {Bitmap.new Width Height} in - {Bitmap.transform B Reader} - B + {Bitmap.transform B Reader} + B finally - {F close} + {F close} end end @@ -43,12 +43,12 @@ define in {SkipWS F} Ds = for collect:Collect break:Break do - [C] = {F read(list:$ size:1)} - in - if {Char.isDigit C} then {Collect C} - else {Break} - end - end + [C] = {F read(list:$ size:1)} + in + if {Char.isDigit C} then {Collect C} + else {Break} + end + end {SkipWS F} {String.toInt Ds} end @@ -58,9 +58,9 @@ define in if {Char.isSpace C} then {SkipWS F} elseif C == &# then - {SkipLine F} + {SkipLine F} else - {F seek(whence:current offset:~1)} + {F seek(whence:current offset:~1)} end end diff --git a/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku b/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku index 5f77cfb471..395d55219b 100644 --- a/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku +++ b/Task/Bitmap-Read-a-PPM-file/Raku/bitmap-read-a-ppm-file.raku @@ -7,8 +7,8 @@ class Bitmap { role PGM { has @.GS; method P5 returns Blob { - "P5\n{self.width} {self.height}\n255\n".encode('ascii') - ~ Blob.new: self.GS + "P5\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: self.GS } } diff --git a/Task/Bitmap-Read-a-PPM-file/Rebol/bitmap-read-a-ppm-file.rebol b/Task/Bitmap-Read-a-PPM-file/Rebol/bitmap-read-a-ppm-file.rebol new file mode 100644 index 0000000000..7c8de98fa0 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Rebol/bitmap-read-a-ppm-file.rebol @@ -0,0 +1,50 @@ +Rebol [ + title: "Rosetta code: Bitmap/Read a PPM file" + file: %Bitmap-Read_a_PPM_file.r3 + url: https://rosettacode.org/wiki/Bitmap/Read_a_PPM_file +] + +decode-ppm: function[ppm [string! file! url!]][ + ;; Load source into a string if a file or URL was given + unless string? ppm [ppm: read/string ppm] + if all [ + ;; Strip the "P3" magic header and any comment lines + parse/case ppm ["P3" any [LF | #"#" to LF skip] ppm: to end] + ;; Lex the remaining text into Rebol values + try [ppm: transcode ppm] + ;; Extract image dimensions, colour depth, and raw RGB values + parse ppm [ + set width: integer! + set height: integer! + set depth: integer! + rgb: to end + ] + ][ + img: make image! as-pair width height + i: 1 clr: 0.0.0 + foreach [r g b] rgb [ + ;; Normalise each channel to 0–255 + clr/1: 255 * (r / depth) + clr/2: 255 * (g / depth) + clr/3: 255 * (b / depth) + img/:i: clr + ++ i + ] + ;; Return the completed image + img + ] +] + +img: decode-ppm {P3 +# feep.ppm +4 4 +15 +0 0 0 0 0 0 0 0 0 15 0 15 +0 0 0 0 15 7 0 0 0 0 0 0 +0 0 0 0 0 0 0 15 7 0 0 0 +15 0 15 0 0 0 0 0 0 0 0 0} + +print "Source image:" +print img +print "Grayscale PPM output:" +print to-ppm grayscale img ;@@ https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file diff --git a/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala b/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala index 672dee049f..c97a82aeab 100644 --- a/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala +++ b/Task/Bitmap-Read-a-PPM-file/Scala/bitmap-read-a-ppm-file-1.scala @@ -6,7 +6,7 @@ import javax.swing.ImageIcon object Pixmap { private case class PpmHeader(format:String, width:Int, height:Int, maxColor:Int) - + def load(filename:String):Option[RgbBitmap]={ implicit val in=new BufferedInputStream(new FileInputStream(filename)) val header=readHeader @@ -22,7 +22,7 @@ object Pixmap { private def readHeader(implicit in:InputStream)={ var format=readLine - + var line=readLine while(line.startsWith("#")) //skip comments line=readLine @@ -31,7 +31,7 @@ object Pixmap { val width=parts(0).toInt val height=parts(1).toInt val maxColor=readLine.toInt - + new PpmHeader(format, width, height, maxColor) } diff --git a/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit b/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit index c5de2d216f..4e7dbe614d 100644 --- a/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit +++ b/Task/Bitmap-Read-a-PPM-file/Vedit-macro-language/bitmap-read-a-ppm-file-1.vedit @@ -7,11 +7,11 @@ :LOAD_PPM: File_Open(@10) BOF -Search("|X", ADVANCE) // skip "P6" -#11 = Num_Eval(ADVANCE) // #11 = width -Match("|X", ADVANCE) // skip separator -#12 = Num_Eval(ADVANCE) // #12 = height +Search("|X", ADVANCE) // skip "P6" +#11 = Num_Eval(ADVANCE) // #11 = width +Match("|X", ADVANCE) // skip separator +#12 = Num_Eval(ADVANCE) // #12 = height Match("|X", ADVANCE) -Search("|X", ADVANCE) // skip maxval (assume 255) -Del_Block(0,CP) // remove the header +Search("|X", ADVANCE) // skip maxval (assume 255) +Del_Block(0,CP) // remove the header Return diff --git a/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic b/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic index 6252db3926..4bf6e89591 100644 --- a/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic +++ b/Task/Bitmap-Read-a-PPM-file/Yabasic/bitmap-read-a-ppm-file.basic @@ -1,27 +1,27 @@ sub readPPM(f$) - local ff, x, y, t$, dcol$, wid, hei + local ff, x, y, t$, dcol$, wid, hei - if f$ = "" print "No PPM file name indicate." : return false + if f$ = "" print "No PPM file name indicate." : return false - ff = open (f$, "rb") - if not ff print "File ", f$, " not found." : return false + ff = open (f$, "rb") + if not ff print "File ", f$, " not found." : return false - input #ff t$, wid, hei, dcol$ + input #ff t$, wid, hei, dcol$ - if t$ = "P6" then - open window wid, hei - - for x = 0 to hei - 1 - for y = 0 to wid - 1 - color peek(#ff), peek(#ff), peek(#ff) - dot y, x - next y - next x - - close #ff - else - print "File is NOT PPM P6 type." : return false - end if - - return true + if t$ = "P6" then + open window wid, hei + + for x = 0 to hei - 1 + for y = 0 to wid - 1 + color peek(#ff), peek(#ff), peek(#ff) + dot y, x + next y + next x + + close #ff + else + print "File is NOT PPM P6 type." : return false + end if + + return true end sub diff --git a/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.adb b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.adb new file mode 100644 index 0000000000..c3611189b3 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Ada/bitmap-write-a-ppm-file.adb @@ -0,0 +1,29 @@ +with Ada.Characters.Latin_1; +with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; + +with Bitmap_Store; use Bitmap_Store; +-- This package is defined in the Bitmap task. + +procedure Put_PPM (File : File_Type; Picture : Image) is + use Ada.Characters.Latin_1; + Size : constant String := Integer'Image (Picture'Length (2)) & Integer'Image (Picture'Length (1)); + Buffer : String (1..Picture'Length (2) * 3); + Color : Pixel; + Index : Positive; +begin + String'Write (Stream (File), "P6" & LF); + String'Write (Stream (File), Size (2..Size'Last) & LF); + String'Write (Stream (File), "255" & LF); + for I in Picture'Range (1) loop + Index := Buffer'First; + for J in Picture'Range (2) loop + Color := Picture (I, J); + Buffer (Index) := Character'Val (Color.R); + Buffer (Index + 1) := Character'Val (Color.G); + Buffer (Index + 2) := Character'Val (Color.B); + Index := Index + 3; + end loop; + String'Write (Stream (File), Buffer); + end loop; + Character'Write (Stream (File), LF); +end Put_PPM; diff --git a/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp b/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp index d922a0db8d..d4046e677b 100644 --- a/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp +++ b/Task/Bitmap-Write-a-PPM-file/Common-Lisp/bitmap-write-a-ppm-file.lisp @@ -1,28 +1,28 @@ (defun write-rgb-buffer-to-ppm-file (filename buffer) (with-open-file (stream filename - :element-type '(unsigned-byte 8) - :direction :output - :if-does-not-exist :create - :if-exists :supersede) + :element-type '(unsigned-byte 8) + :direction :output + :if-does-not-exist :create + :if-exists :supersede) (let* ((dimensions (array-dimensions buffer)) - (width (first dimensions)) - (height (second dimensions)) - (header (format nil "P6~A~D ~D~A255~A" - #\newline - width height #\newline - #\newline))) + (width (first dimensions)) + (height (second dimensions)) + (header (format nil "P6~A~D ~D~A255~A" + #\newline + width height #\newline + #\newline))) (loop - :for char :across header - :do (write-byte (char-code char) stream)) #| Assumes char-codes match ASCII |# + :for char :across header + :do (write-byte (char-code char) stream)) #| Assumes char-codes match ASCII |# (loop - :for x :upfrom 0 :below width - :do (loop :for y :upfrom 0 :below height - :do (let ((pixel (rgb-pixel buffer x y))) - (let ((red (rgb-pixel-red pixel)) - (green (rgb-pixel-green pixel)) - (blue (rgb-pixel-blue pixel))) - (write-byte red stream) - (write-byte green stream) - (write-byte blue stream))))))) + :for x :upfrom 0 :below width + :do (loop :for y :upfrom 0 :below height + :do (let ((pixel (rgb-pixel buffer x y))) + (let ((red (rgb-pixel-red pixel)) + (green (rgb-pixel-green pixel)) + (blue (rgb-pixel-blue pixel))) + (write-byte red stream) + (write-byte green stream) + (write-byte blue stream))))))) filename) diff --git a/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-1.cr b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-1.cr new file mode 100644 index 0000000000..24affee476 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-1.cr @@ -0,0 +1,13 @@ +require "./pixmap" + +class Pixmap + def write_ppm (io) + io.print "P6\n# Visit Rosetta code!\n#{width} #{height}\n255\n" + @data.each do |c| + io.write_byte c.r + io.write_byte c.g + io.write_byte c.b + end + end + register_writer ".ppm", write_ppm +end diff --git a/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-2.cr b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-2.cr new file mode 100644 index 0000000000..1e3919cea7 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Crystal/bitmap-write-a-ppm-file-2.cr @@ -0,0 +1,14 @@ +require "./write_ppm" + +img = Pixmap.new 3, 2, Color::WHITE + +[[0xFF0000, 0x00FF00, 0x0000FF], + [0xFFFF00, 0x00FFFF, 0xFF00FF]].each_with_index do |row, y| + row.each_with_index do |color, x| + img[x, y] = Color.new color + end +end + +img.write "mini.ppm" + +File.read("mini.ppm").unsafe_byte_slice(0).hexdump(STDOUT) diff --git a/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.eu b/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.eu new file mode 100644 index 0000000000..b7ab37e6f8 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-1.eu @@ -0,0 +1,15 @@ +constant dimx = 800, dimy = 800 +constant fn = open("first.ppm","wb") -- b - binary mode +sequence color +printf(fn, "P6\n%d %d\n255\n", {dimx,dimy}) +for j = 0 to dimy-1 do + for i = 0 to dimx-1 do + color = { + remainder(i,256), -- red + remainder(j,256), -- green + remainder(i*j,256) -- blue + } + puts(fn,color) + end for +end for +close(fn) diff --git a/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.eu b/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.eu new file mode 100644 index 0000000000..4a3c444ae5 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Euphoria/bitmap-write-a-ppm-file-2.eu @@ -0,0 +1,14 @@ +procedure write_ppm(sequence filename, sequence image) + integer fn,dimx,dimy + dimy = length(image[1]) + dimx = length(image) + fn = open(filename,"wb") + printf(fn, "P6\n%d %d\n255\n", {dimx,dimy}) + for y = 1 to dimy do + for x = 1 to dimx do + puts(fn, and_bits(image[x][y], {#FF0000,#FF00,#FF}) / + {#010000,#0100,#01}) -- unpack color triple + end for + end for + close(fn) +end procedure diff --git a/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl b/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl index 2c7f0057d2..6db33e290f 100644 --- a/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl +++ b/Task/Bitmap-Write-a-PPM-file/FBSL/bitmap-write-a-ppm-file.fbsl @@ -12,12 +12,12 @@ DIM head = @ppmdata + STRLEN, tail = @FILEGET + FILELEN - breadth * 3 - 2 ' Star ppmdata = ppmheader ' Copy PPM file header WHILE tail >= @FILEGET + bmpblob ' Flip upside down - FOR DIM w = 0 TO (breadth - 1) * 3 STEP 3 - POKE(head + 0 + w, CHR(PEEK(tail + 2 + w, 1))) ' Swap R - POKE(head + 1 + w, CHR(PEEK(tail + 1 + w, 1))) ' Keep G - POKE(head + 2 + w, CHR(PEEK(tail + 0 + w, 1))) ' Swap B - NEXT - INCR(head, breadth * 3): DECR(tail, breadth * 3) ' Next scanline + FOR DIM w = 0 TO (breadth - 1) * 3 STEP 3 + POKE(head + 0 + w, CHR(PEEK(tail + 2 + w, 1))) ' Swap R + POKE(head + 1 + w, CHR(PEEK(tail + 1 + w, 1))) ' Keep G + POKE(head + 2 + w, CHR(PEEK(tail + 0 + w, 1))) ' Swap B + NEXT + INCR(head, breadth * 3): DECR(tail, breadth * 3) ' Next scanline WEND FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN) diff --git a/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz b/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz index dca6a5e19e..c05f456d0a 100644 --- a/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz +++ b/Task/Bitmap-Write-a-PPM-file/Oz/bitmap-write-a-ppm-file.oz @@ -12,28 +12,28 @@ define F = {New Open.file init(name:Filename flags:[write create truncate binary])} proc {WriteColor8 color(R G B)} - {F write(vs:[R G B])} + {F write(vs:[R G B])} end fun {ToBytes C} - [C div 0x100 C mod 0x100] + [C div 0x100 C mod 0x100] end proc {WriteColor16 color(R G B)} - {F write(vs:{Flatten {Map [R G B] ToBytes}})} + {F write(vs:{Flatten {Map [R G B] ToBytes}})} end MaxCol = {Bitmap.maxValue B} MaxVal#Writer = if MaxCol =< 0xff then 0xff#WriteColor8 - else 0xffff#WriteColor16 - end + else 0xffff#WriteColor16 + end Header = "P6\n"#W#" "#H#" "#MaxVal#"\n" in try - {F write(vs:Header)} - {Bitmap.forAllPixels B Writer} + {F write(vs:Header)} + {Bitmap.forAllPixels B Writer} finally - {F close} + {F close} end end end diff --git a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro index c10545d911..7b7fd228ad 100644 --- a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro +++ b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-1.pro @@ -1,16 +1,16 @@ :- module(bitmapIO, [ - write_ppm_p6/2]). + write_ppm_p6/2]). :- use_module(library(lists)). %write_ppm_p6(File,Bitmap) write_ppm_p6(Filename,[[X,Y],Pixels]):- - open(Filename,write,Output,[encoding(octet)]), - %write p6 header - writeln(Output, 'P6'), - atomic_list_concat([X, Y], ' ', Dimensions), - writeln(Output, Dimensions), - writeln(Output, '255'), - %write bytes - maplist(maplist(maplist(put_byte(Output))),Pixels), - close(Output). + open(Filename,write,Output,[encoding(octet)]), + %write p6 header + writeln(Output, 'P6'), + atomic_list_concat([X, Y], ' ', Dimensions), + writeln(Output, Dimensions), + writeln(Output, '255'), + %write bytes + maplist(maplist(maplist(put_byte(Output))),Pixels), + close(Output). diff --git a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro index 6c3b784711..63e26ab585 100644 --- a/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro +++ b/Task/Bitmap-Write-a-PPM-file/Prolog/bitmap-write-a-ppm-file-2.pro @@ -2,6 +2,6 @@ :- use_module(bitmapIO). write :- - new_bitmap(AllBlack,[50,50],[0,0,0]), - set_pixel0(AlmostAllBlack,AllBlack,[25,25],[255,255,255]), - write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack). + new_bitmap(AllBlack,[50,50],[0,0,0]), + set_pixel0(AlmostAllBlack,AllBlack,[25,25],[255,255,255]), + write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack). diff --git a/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku b/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku index 3efa08e181..7739ea243e 100644 --- a/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku +++ b/Task/Bitmap-Write-a-PPM-file/Raku/bitmap-write-a-ppm-file.raku @@ -7,9 +7,9 @@ class Bitmap { @!data = $p.clone xx ($!width*$!height) } method pixel( - $i where ^$!width, - $j where ^$!height - --> Pixel + $i where ^$!width, + $j where ^$!height + --> Pixel ) is rw { @!data[$i*$!height + $j] } method data { @!data } @@ -17,8 +17,8 @@ class Bitmap { role PPM { method P6 returns Blob { - "P6\n{self.width} {self.height}\n255\n".encode('ascii') - ~ Blob.new: flat map { .R, .G, .B }, self.data + "P6\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: flat map { .R, .G, .B }, self.data } } diff --git a/Task/Bitmap-Write-a-PPM-file/Rebol/bitmap-write-a-ppm-file.rebol b/Task/Bitmap-Write-a-PPM-file/Rebol/bitmap-write-a-ppm-file.rebol new file mode 100644 index 0000000000..fd0ef3b840 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Rebol/bitmap-write-a-ppm-file.rebol @@ -0,0 +1,57 @@ +Rebol [ + title: "Rosetta code: Bitmap/Write a PPM file" + file: %Bitmap-Write_a_PPM_file.r3 + url: https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file +] + +to-ppm: function [ + "Converts an image to a PPM (Portable Pixmap) format string" + ;; This function is using padding in the output. + ;; In the real life usage it could be removed. + img [image!] +][ + ;; Extract image dimensions as integers + wide: to integer! img/size/x + high: to integer! img/size/y + + ;; Build the PPM header: + ;; P3 = plain RGB text format + ;; wide/high = pixel dimensions + ;; 255 = max color value (8-bit per channel) + out: rejoin ["P3^/" wide SP high "^/255^/"] + + ;; Iterate over every pixel in the image + n: 0 ;; Pixel counter, used to detect end of each row + foreach clr img [ + ++ n + ;; Append R, G, B channel values, right-aligned in fixed-width columns + ;; pad ... -5/-4 = right-align in field of 5 or 4 characters + append out ajoin [ + pad clr/1 -5 ;R + pad clr/2 -4 ;G + pad clr/3 -4 ;B + ;; After the last pixel in each row, insert a newline + if zero? n % wide [ newline ] + ] + ] + out +] + +; --- Demo --- +; Create a 2x2 image and set pixels 1 (top-left) and 4 (bottom-right) to black +img: make image! 2x2 +img/1: img/4: black +print to-ppm img + +;; It is also possible to register a PPM codec +register-codec [ + name: 'ppm + type: 'image + title: "Portable Pixmap (PPM) File Format" + suffixes: [%.ppm] + encode: :to-ppm +] +;; Then use it as: +ppm-data: encode 'ppm img +;; or +save %image.ppm img diff --git a/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata b/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata index 62077b718a..23beb00d54 100644 --- a/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata +++ b/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata @@ -1,16 +1,16 @@ mata void writeppm(name, r, g, b) { - n = rows(r) - p = cols(r) - f = fopen(name, "w") - fput(f, "P3") - fput(f, strofreal(p) + " " + strofreal(n) + " 255") - for (i = 1; i <= n; i++) { - for (j = 1; j <= p; j++) { - fput(f, strofreal(r[i,j]) + " " + strofreal(g[i,j]) + " " + strofreal(b[i,j])) - } - } - fclose(f) + n = rows(r) + p = cols(r) + f = fopen(name, "w") + fput(f, "P3") + fput(f, strofreal(p) + " " + strofreal(n) + " 255") + for (i = 1; i <= n; i++) { + for (j = 1; j <= p; j++) { + fput(f, strofreal(r[i,j]) + " " + strofreal(g[i,j]) + " " + strofreal(b[i,j])) + } + } + fclose(f) } r = J(1, 6, (0::5) * 51) diff --git a/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic b/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic index 3d5929176a..9f907661eb 100644 --- a/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic +++ b/Task/Bitmap-Write-a-PPM-file/Yabasic/bitmap-write-a-ppm-file.basic @@ -18,12 +18,12 @@ fn = open("exmaple.PPM", "wb") print #fn header$ for x = 0 to hei - 1 - for y = 0 to wid - 1 - c$ = right$(getbit$(y, x, y, x), 6) - poke #fn, dec(left$(c$, 2)) - poke #fn, dec(right$(c$, 2)) - poke #fn, dec(mid$(c$, 3, 2)) - next y + for y = 0 to wid - 1 + c$ = right$(getbit$(y, x, y, x), 6) + poke #fn, dec(left$(c$, 2)) + poke #fn, dec(right$(c$, 2)) + poke #fn, dec(mid$(c$, 3, 2)) + next y next x poke #fn, asc("\n") diff --git a/Task/Bitmap/ARM-Assembly/bitmap.arm b/Task/Bitmap/ARM-Assembly/bitmap.arm index a10f4f2666..a547d1f0c9 100644 --- a/Task/Bitmap/ARM-Assembly/bitmap.arm +++ b/Task/Bitmap/ARM-Assembly/bitmap.arm @@ -1,51 +1,51 @@ Bitmap_FloodFill: - ;input: - ;r0 = color to fill screen with (15-bit color) - STMFD sp!,{r0-r12,lr} - - MOV R2,#160 - MOV R4,#0x06000000 + ;input: + ;r0 = color to fill screen with (15-bit color) + STMFD sp!,{r0-r12,lr} + + MOV R2,#160 + MOV R4,#0x06000000 outerloop_floodfill: - MOV R1,#240 ;restore inner loop counter + MOV R1,#240 ;restore inner loop counter innerloop_floodfill: - strH r0,[r4] - add r4,r4,#2 ;next pixel - subs r1,r1,#1 ;decrement loop counter - bne innerloop_floodfill - subs r2,r2,#1 - bne outerloop_floodfill - - LDMFD sp!,{r0-r12,pc} - + strH r0,[r4] + add r4,r4,#2 ;next pixel + subs r1,r1,#1 ;decrement loop counter + bne innerloop_floodfill + subs r2,r2,#1 + bne outerloop_floodfill + + LDMFD sp!,{r0-r12,pc} + Bitmap_Locate: ;given x and y coordinates, offsets vram addr to that pixel on screen. - ;input: - ;r0 = x - ;r1 = y - ;output: r2 = vram area - STMFD sp!,{r4-r12,lr} - mov r2,#0x06000000 ;vram base + ;input: + ;r0 = x + ;r1 = y + ;output: r2 = vram area + STMFD sp!,{r4-r12,lr} + mov r2,#0x06000000 ;vram base + + + mov r4,#240*2 ;240 pixels across, 2 bytes per pixel + mul r1,r4,r1 + add r2,r2,r1 ;add y*480 + add r2,r2,r0,lsl #1 ;add x*2 + LDMFD sp!,{r4-r12,pc} - - mov r4,#240*2 ;240 pixels across, 2 bytes per pixel - mul r1,r4,r1 - add r2,r2,r1 ;add y*480 - add r2,r2,r0,lsl #1 ;add x*2 - LDMFD sp!,{r4-r12,pc} - Bitmap_StorePixel: - ;input: r3 = color - ;r0 = x - ;r1 = y - bl Bitmap_Locate - strH r3,[r2] ;store the pixel color in video memory - bx lr - + ;input: r3 = color + ;r0 = x + ;r1 = y + bl Bitmap_Locate + strH r3,[r2] ;store the pixel color in video memory + bx lr + Bitmap_GetPixel: ;retrieves the color of the pixel at [r2] and stores its color value in r3. - ;r0 = x - ;r1 = y - ;output in r3 - bl Bitmap_Locate - ldrH r3,[r2] - bx lr + ;r0 = x + ;r1 = y + ;output in r3 + bl Bitmap_Locate + ldrH r3,[r2] + bx lr diff --git a/Task/Bitmap/Ada/bitmap-1.adb b/Task/Bitmap/Ada/bitmap-1.adb new file mode 100644 index 0000000000..c239196025 --- /dev/null +++ b/Task/Bitmap/Ada/bitmap-1.adb @@ -0,0 +1,17 @@ +package Bitmap_Store is + type Luminance is mod 2**8; + type Pixel is record + R, G, B : Luminance := Luminance'First; + end record; + Black : constant Pixel := (others => Luminance'First); + White : constant Pixel := (others => Luminance'Last); + type Image is array (Positive range <>, Positive range <>) of Pixel; + + procedure Fill (Picture : in out Image; Color : Pixel); + + procedure Print (Picture : Image); + + type Point is record + X, Y : Positive; + end record; +end Bitmap_Store; diff --git a/Task/Bitmap/Ada/bitmap-2.adb b/Task/Bitmap/Ada/bitmap-2.adb new file mode 100644 index 0000000000..72c9941cf1 --- /dev/null +++ b/Task/Bitmap/Ada/bitmap-2.adb @@ -0,0 +1,20 @@ +with Ada.Text_IO; use Ada.Text_IO; + +package body Bitmap_Store is + + procedure Fill (Picture : in out Image; Color : Pixel) is + begin + for p of Picture loop x:= Color;end loop; + end Fill; + + procedure Print (Picture : Image) is + begin + for I in Picture'Range (1) loop + for J in Picture'Range (2) loop + Put (if Picture (I, J) = White then ' ' else 'H'); + end loop; + New_Line; + end loop; + end Print; + +end Bitmap_Store; diff --git a/Task/Bitmap/Ada/bitmap-3.adb b/Task/Bitmap/Ada/bitmap-3.adb new file mode 100644 index 0000000000..440209b31c --- /dev/null +++ b/Task/Bitmap/Ada/bitmap-3.adb @@ -0,0 +1,7 @@ +use Bitmap_Store; with Bitmap_Store; + ... + X : Image (1..64, 1..64); +begin + Fill (X, (255, 255, 255)); + X (1, 2) := (R => 255, others => 0); + X (3, 4) := X (1, 2); diff --git a/Task/Bitmap/AutoHotkey/bitmap.ahk b/Task/Bitmap/AutoHotkey/bitmap.ahk index 791a7d7bc8..2c8ccd888f 100644 --- a/Task/Bitmap/AutoHotkey/bitmap.ahk +++ b/Task/Bitmap/AutoHotkey/bitmap.ahk @@ -21,13 +21,13 @@ background := black if !BitmapType BitmapType := Object("fill", "Bitmap_Fill" - ,"write", "Bitmap_write_ppm3") + ,"write", "Bitmap_write_ppm3") - img := Object("width", width + img := Object("width", width ,"height", height , "base" , BitmapType) - img._SetCapacity(height) ; an array of rows + img._SetCapacity(height) ; an array of rows img.fill(background) Return img } diff --git a/Task/Bitmap/C/bitmap-1.c b/Task/Bitmap/C/bitmap-1.c index 44b484cea5..0ff4592b18 100644 --- a/Task/Bitmap/C/bitmap-1.c +++ b/Task/Bitmap/C/bitmap-1.c @@ -24,14 +24,14 @@ void fill_img(image img, color_component g, color_component b ); void put_pixel_unsafe( - image img, + image img, unsigned int x, unsigned int y, color_component r, color_component g, color_component b ); void put_pixel_clip( - image img, + image img, unsigned int x, unsigned int y, color_component r, diff --git a/Task/Bitmap/C/bitmap-2.c b/Task/Bitmap/C/bitmap-2.c index 22756034b3..b8b6167bce 100644 --- a/Task/Bitmap/C/bitmap-2.c +++ b/Task/Bitmap/C/bitmap-2.c @@ -31,7 +31,7 @@ void fill_img( } void put_pixel_unsafe( - image img, + image img, unsigned int x, unsigned int y, color_component r, @@ -46,7 +46,7 @@ void put_pixel_unsafe( } void put_pixel_clip( - image img, + image img, unsigned int x, unsigned int y, color_component r, diff --git a/Task/Bitmap/Clojure/bitmap.clj b/Task/Bitmap/Clojure/bitmap.clj index b447f4462c..d2bba0e538 100644 --- a/Task/Bitmap/Clojure/bitmap.clj +++ b/Task/Bitmap/Clojure/bitmap.clj @@ -1,5 +1,5 @@ (import '[java.awt Color Graphics Image] - '[java.awt.image BufferedImage]) + '[java.awt.image BufferedImage]) (defn blank-bitmap [width height] (BufferedImage. width height BufferedImage/TYPE_3BYTE_BGR)) diff --git a/Task/Bitmap/Common-Lisp/bitmap-2.lisp b/Task/Bitmap/Common-Lisp/bitmap-2.lisp index c50a1e9e8a..926118a474 100644 --- a/Task/Bitmap/Common-Lisp/bitmap-2.lisp +++ b/Task/Bitmap/Common-Lisp/bitmap-2.lisp @@ -59,11 +59,11 @@ (declare (type rgb-pixel-buffer buffer)) (declare (type rgb-pixel pixel)) (let* ((dimensions (array-dimensions buffer)) - (width (first dimensions)) - (height (second dimensions))) + (width (first dimensions)) + (height (second dimensions))) (loop :for y :of-type fixnum :upfrom 0 :below height :do (loop - :for x :of-type fixnum :upfrom 0 :below width - :do (setf (rgb-pixel buffer x y) pixel))) + :for x :of-type fixnum :upfrom 0 :below width + :do (setf (rgb-pixel buffer x y) pixel))) buffer)) diff --git a/Task/Bitmap/Crystal/bitmap-1.cr b/Task/Bitmap/Crystal/bitmap-1.cr new file mode 100644 index 0000000000..ad7043f36d --- /dev/null +++ b/Task/Bitmap/Crystal/bitmap-1.cr @@ -0,0 +1,105 @@ +record Color, r : UInt8, g : UInt8, b : UInt8 do + def self.new (r : Int32, g : Int32, b : Int32) + self.new r.to_u8, g.to_u8, b.to_u8 + end + + def self.new (hex : Int32) + self.new (hex >> 16 & 0xFF).to_u8, (hex >> 8 & 0xFF).to_u8, (hex & 0xFF).to_u8 + end + + def to_i + (r.to_i << 16) + (g.to_i << 8) + b.to_i + end + + def == (other : Color) + self.to_i == other.to_i + end + + WHITE = new 0xFFFFFF + BLACK = new 0x000000 + RED = new 0xFF0000 + GREEN = new 0x00FF00 + BLUE = new 0x0000FF +end + +class Pixmap + getter width, height + @data : Array(Color) + + def initialize (@width : Int32, @height : Int32, bg_color = Color::BLACK) + @data = Array.new(@width * @height, bg_color) + end + + def initialize (@width : Int32, @height : Int32, @data : Array(Color), copy = false) + raise "Wrong bounds" unless @width * @height == @data.size + @data = @data.dup if copy + end + + def initialize (other : self) + @width = other.@width + @height = other.@height + @data = other.@data.dup + end + + def fill (color) + @data.fill color + end + + def [] (x, y) + raise "Outside bounds" unless 0 <= x < @width && 0 <= y < @height + @data[y * @width + x] + end + + def []= (x, y, color) + if 0 <= x < @width && 0 <= y < @height + @data[y * @width + x] = color + end + color + end + + @@loaders = {} of String => Proc(IO, Pixmap) + @@writers = {} of String | Nil => Proc(Pixmap, IO, Nil) + + macro register_loader (ext, method) + @@loaders[{{ext}}] = ->(io : IO) { {{method.id}}(io) } + end + + macro register_writer (ext, method) + @@writers[{{ext}}] = ->(img : Pixmap, io : IO) { img.{{method.id}}(io) } + end + + def self.load (filename) + ext = File.extname(filename) + loader = @@loaders[ext]? || raise "No loader for '.#{ext}'" + File.open(filename) do |f| + loader.call(f) + end + end + + def write (filename_or_io : Path | String | IO) + if filename_or_io.is_a?(IO) + writer = @@writers[nil]? || raise "No console writer" + writer.call(self, filename_or_io) + else + ext = File.extname(filename_or_io) + writer = @@writers[ext]? || raise "No writer for '#{ext}'" + File.open(filename_or_io, "w") do |f| + writer.call(self, f) + end + end + end + + def write_poor_text (io) + (0...@height).each do |y| + (0...@width).each do |x| + print case self[x, y] + when Color::BLACK then '#' + when Color::WHITE then ' ' + else 'X' + end + end + puts + end + end + register_writer nil, write_poor_text +end diff --git a/Task/Bitmap/Crystal/bitmap-2.cr b/Task/Bitmap/Crystal/bitmap-2.cr new file mode 100644 index 0000000000..99b21e439e --- /dev/null +++ b/Task/Bitmap/Crystal/bitmap-2.cr @@ -0,0 +1,9 @@ +require "./pixmap" + +img = Pixmap.new(10, 5) +(0...10).each do |x| + img[x, x // 2] = Color::WHITE + img[9-x, x // 2] = Color::RED +end + +img.write(STDOUT) diff --git a/Task/Bitmap/Delphi/bitmap.pas b/Task/Bitmap/Delphi/bitmap.pas index 70def79db7..7f6926a01d 100644 --- a/Task/Bitmap/Delphi/bitmap.pas +++ b/Task/Bitmap/Delphi/bitmap.pas @@ -12,21 +12,21 @@ Image.Canvas.Brush.Color:=clBlue; Image.Canvas.FloodFill(55,55,clRed,fsBorder); {Draw random dots on the screen} for I:=1 to 1000 do - begin - X:=trunc((Random * 450) + 50); - Y:=trunc((Random * 250) + 50); - C:=RGB(Random(255),Random(255),Random(255)); - {draw 9 pixels for each point to make dots more visible} - Image.Canvas.Pixels[X-1,Y-1]:=C; - Image.Canvas.Pixels[X ,Y-1]:=C; - Image.Canvas.Pixels[X+1,Y-1]:=C; - Image.Canvas.Pixels[X-1,Y ]:=C; - Image.Canvas.Pixels[X ,Y ]:=C; - Image.Canvas.Pixels[X+1,Y ]:=C; - Image.Canvas.Pixels[X-1,Y+1]:=C; - Image.Canvas.Pixels[X ,Y+1]:=C; - Image.Canvas.Pixels[X+1,Y+1]:=C; - end; + begin + X:=trunc((Random * 450) + 50); + Y:=trunc((Random * 250) + 50); + C:=RGB(Random(255),Random(255),Random(255)); + {draw 9 pixels for each point to make dots more visible} + Image.Canvas.Pixels[X-1,Y-1]:=C; + Image.Canvas.Pixels[X ,Y-1]:=C; + Image.Canvas.Pixels[X+1,Y-1]:=C; + Image.Canvas.Pixels[X-1,Y ]:=C; + Image.Canvas.Pixels[X ,Y ]:=C; + Image.Canvas.Pixels[X+1,Y ]:=C; + Image.Canvas.Pixels[X-1,Y+1]:=C; + Image.Canvas.Pixels[X ,Y+1]:=C; + Image.Canvas.Pixels[X+1,Y+1]:=C; + end; {Draw lime-green line from corner to cornder} Image.Canvas.Pen.Color:=clLime; Image.Canvas.MoveTo(50,50); diff --git a/Task/Bitmap/Euphoria/bitmap.eu b/Task/Bitmap/Euphoria/bitmap.eu new file mode 100644 index 0000000000..e27c170c4e --- /dev/null +++ b/Task/Bitmap/Euphoria/bitmap.eu @@ -0,0 +1,23 @@ +-- Some color constants: +constant + black = #000000, + white = #FFFFFF, + red = #FF0000, + green = #00FF00, + blue = #0000FF + +-- Create new image filled with some color +function new_image(integer width, integer height, atom fill_color) + return repeat(repeat(fill_color,height),width) +end function + +-- Usage example: +sequence image +image = new_image(800,600,black) + +-- Set pixel color: +image[400][300] = red + +-- Get pixel color +atom color +color = image[400][300] -- Now color is #FF0000 diff --git a/Task/Bitmap/FBSL/bitmap.fbsl b/Task/Bitmap/FBSL/bitmap.fbsl index 910530fbc6..dccbf2fbf5 100644 --- a/Task/Bitmap/FBSL/bitmap.fbsl +++ b/Task/Bitmap/FBSL/bitmap.fbsl @@ -11,12 +11,12 @@ CENTER(ME) SHOW(ME) BEGIN EVENTS - SELECT CASE CBMSG - CASE WM_LBUTTONDOWN ' Set color at current coords as hex literal - PSET(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM), &H0000FF) ' Red: Windows stores colors in BGR order - CASE WM_RBUTTONDOWN ' Get color at current coords as hex literal - FBSLSETTEXT(ME, "&H" & HEX(POINT(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM)))) - CASE WM_CLOSE ' Clean up - FBSL.RELEASEDC(ME, FBSL.GETDC) - END SELECT + SELECT CASE CBMSG + CASE WM_LBUTTONDOWN ' Set color at current coords as hex literal + PSET(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM), &H0000FF) ' Red: Windows stores colors in BGR order + CASE WM_RBUTTONDOWN ' Get color at current coords as hex literal + FBSLSETTEXT(ME, "&H" & HEX(POINT(FBSL.GETDC, LOWORD(CBLPARAM), HIWORD(CBLPARAM)))) + CASE WM_CLOSE ' Clean up + FBSL.RELEASEDC(ME, FBSL.GETDC) + END SELECT END EVENTS diff --git a/Task/Bitmap/Go/bitmap-1.go b/Task/Bitmap/Go/bitmap-1.go index d6dd1a630b..f275d34761 100644 --- a/Task/Bitmap/Go/bitmap-1.go +++ b/Task/Bitmap/Go/bitmap-1.go @@ -1,57 +1,57 @@ package main import ( - "bytes" - "fmt" - "image" - "image/color" - "image/draw" - "image/png" + "bytes" + "fmt" + "image" + "image/color" + "image/draw" + "image/png" ) func main() { - // A rectangle from 0,0 to 300,240. - r := image.Rect(0, 0, 300, 240) + // A rectangle from 0,0 to 300,240. + r := image.Rect(0, 0, 300, 240) - // Create an image - im := image.NewNRGBA(r) + // Create an image + im := image.NewNRGBA(r) - // set some color variables for convience - var ( - red = color.RGBA{0xff, 0x00, 0x00, 0xff} - blue = color.RGBA{0x00, 0x00, 0xff, 0xff} - ) + // set some color variables for convience + var ( + red = color.RGBA{0xff, 0x00, 0x00, 0xff} + blue = color.RGBA{0x00, 0x00, 0xff, 0xff} + ) - // Fill with a uniform color - draw.Draw(im, r, &image.Uniform{red}, image.ZP, draw.Src) + // Fill with a uniform color + draw.Draw(im, r, &image.Uniform{red}, image.ZP, draw.Src) - // Set individual pixels - im.Set(10, 20, blue) - im.Set(20, 30, color.Black) - im.Set(30, 40, color.RGBA{0x10, 0x20, 0x30, 0xff}) + // Set individual pixels + im.Set(10, 20, blue) + im.Set(20, 30, color.Black) + im.Set(30, 40, color.RGBA{0x10, 0x20, 0x30, 0xff}) - // Get the values of specific pixels as color.Color types. - // The color will be in the color.Model of the image (in this - // case color.NRGBA) but color models can convert their values - // to other models. - c1 := im.At(0, 0) - c2 := im.At(10, 20) + // Get the values of specific pixels as color.Color types. + // The color will be in the color.Model of the image (in this + // case color.NRGBA) but color models can convert their values + // to other models. + c1 := im.At(0, 0) + c2 := im.At(10, 20) - // or directly as RGB components (scaled values) - redc, greenc, bluec, _ := c1.RGBA() - redc, greenc, bluec, _ = im.At(30, 40).RGBA() + // or directly as RGB components (scaled values) + redc, greenc, bluec, _ := c1.RGBA() + redc, greenc, bluec, _ = im.At(30, 40).RGBA() - // Images can be read and writen in various formats - var buf bytes.Buffer - err := png.Encode(&buf, im) - if err != nil { - fmt.Println(err) - } + // Images can be read and writen in various formats + var buf bytes.Buffer + err := png.Encode(&buf, im) + if err != nil { + fmt.Println(err) + } - fmt.Println("Image size:", im.Bounds().Dx(), "×", im.Bounds().Dy()) - fmt.Println(buf.Len(), "bytes when encoded as PNG.") - fmt.Printf("Pixel at %7v is %v\n", image.Pt(0, 0), c1) - fmt.Printf("Pixel at %7v is %#v\n", image.Pt(10, 20), c2) // %#v shows type details - fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n", - image.Pt(30, 40), redc, greenc, bluec) + fmt.Println("Image size:", im.Bounds().Dx(), "×", im.Bounds().Dy()) + fmt.Println(buf.Len(), "bytes when encoded as PNG.") + fmt.Printf("Pixel at %7v is %v\n", image.Pt(0, 0), c1) + fmt.Printf("Pixel at %7v is %#v\n", image.Pt(10, 20), c2) // %#v shows type details + fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n", + image.Pt(30, 40), redc, greenc, bluec) } diff --git a/Task/Bitmap/Maple/bitmap.maple b/Task/Bitmap/Maple/bitmap.maple index c09fcaa799..5182a05be3 100644 --- a/Task/Bitmap/Maple/bitmap.maple +++ b/Task/Bitmap/Maple/bitmap.maple @@ -1,23 +1,23 @@ allocateImg := proc(width, height) - return Array(1..width, 1..height, 1..3); + return Array(1..width, 1..height, 1..3); end proc: fillColor := proc(img, rgb::list) - local i; - for i from 1 to 3 do - img[..,..,i] := map(x->rgb[i], img[..,..,i]): - end do: + local i; + for i from 1 to 3 do + img[..,..,i] := map(x->rgb[i], img[..,..,i]): + end do: end proc: setColor := proc(x, y, img, rgb::list) - local i: - for i from 1 to 3 do - img[x,y,i] := rgb[i]: - end do: + local i: + for i from 1 to 3 do + img[x,y,i] := rgb[i]: + end do: end proc: getColor := proc(x,y,img) - local rgb,i: - rgb := Array(1..3): - for i from 1 to 3 do - rgb(i) := img[x,y,i]: - end do: - return rgb: + local rgb,i: + rgb := Array(1..3): + for i from 1 to 3 do + rgb(i) := img[x,y,i]: + end do: + return rgb: end proc: diff --git a/Task/Bitmap/MiniScript/bitmap.mini b/Task/Bitmap/MiniScript/bitmap.mini index b9f2eed398..28cfdc4c47 100644 --- a/Task/Bitmap/MiniScript/bitmap.mini +++ b/Task/Bitmap/MiniScript/bitmap.mini @@ -12,7 +12,7 @@ img = Image.create(width, height, colr) // Create a diagonal line of multiple colors. Uses // Cartesian coordinates so (0, 0) is lower left corner. for i in range(0, 255) - img.setPixel i, i, color.rgb(i, i, i) + img.setPixel i, i, color.rgb(i, i, i) end for // Get pixel color as RGBA hex values diff --git a/Task/Bitmap/Oz/bitmap-1.oz b/Task/Bitmap/Oz/bitmap-1.oz index 894345a7e0..e7394ba62c 100644 --- a/Task/Bitmap/Oz/bitmap-1.oz +++ b/Task/Bitmap/Oz/bitmap-1.oz @@ -9,12 +9,12 @@ define C = {Array.new 1 Height unit} in for Row in 1..Height do - C.Row := {Array.new 1 Width Init} + C.Row := {Array.new 1 Width Init} end array2d(width:Width - height:Height - contents:C) + height:Height + contents:C) end fun {Get array2d(contents:C ...) X Y} @@ -27,9 +27,9 @@ define proc {Transform array2d(contents:C width:W height:H ...) Fun} for Y in 1..H do - for X in 1..W do - C.Y.X := {Fun C.Y.X} - end + for X in 1..W do + C.Y.X := {Fun C.Y.X} + end end end diff --git a/Task/Bitmap/Pascal/bitmap.pas b/Task/Bitmap/Pascal/bitmap.pas index 09867f7945..d588e54d4e 100644 --- a/Task/Bitmap/Pascal/bitmap.pas +++ b/Task/Bitmap/Pascal/bitmap.pas @@ -117,14 +117,14 @@ Procedure CreateBmpFile32(directory: string; FileName: string; { fill the pixel data area } for y := (height - 1) downto 0 do begin - for x := 0 to (width - 1) do - begin { Pixel(x,y) } - color32.Blue := 255; - color32.Green := 0; - color32.Red := 0; - color32.Alfa := 0; - BlockWrite(bmpFile, color32, 4); - end; { for x ... } + for x := 0 to (width - 1) do + begin { Pixel(x,y) } + color32.Blue := 255; + color32.Green := 0; + color32.Red := 0; + color32.Alfa := 0; + BlockWrite(bmpFile, color32, 4); + end; { for x ... } end; { for y ... } Close(bmpFile); end; { with bmpInfoHeader, bmpFileHeader } diff --git a/Task/Bitmap/Pluto/bitmap-1.pluto b/Task/Bitmap/Pluto/bitmap-1.pluto new file mode 100644 index 0000000000..8901f27d06 --- /dev/null +++ b/Task/Bitmap/Pluto/bitmap-1.pluto @@ -0,0 +1,23 @@ +local canvas = require "canvas" + +-- Create a new canvas object: 400 pixels wide and 400 pixels high. +local c = canvas.new(400, 400) + +-- Color the whole canvas blue. +c:fill(0xff0000) + +-- Draw a red square in the middle. +for i = 1, 51 do + for j = 1, 51 do + c:set(174 + i, 174 + j, 0x0000ff) + end +end + +-- Print to the terminal the color (as an integer) of a pixel. +print(c:get(200, 200)) -- 255 + +-- Convert the canvas to a BMP image. +local image = c:tobmp() + +-- Save the image to a file. +io.contents("mybmp.bmp", image) diff --git a/Task/Bitmap/Pluto/bitmap-2.pluto b/Task/Bitmap/Pluto/bitmap-2.pluto new file mode 100644 index 0000000000..bee038a9ef --- /dev/null +++ b/Task/Bitmap/Pluto/bitmap-2.pluto @@ -0,0 +1,16 @@ +require "bitmap" + +-- Create a new bitmap object: 400 pixels wide and 400 pixels high +local bmp = bitmap.of(400, 400, color.blue, "mybmp") + +-- Draw a red square in the middle. +bmp:square(200, 200, 50, color.red, 0, true) + +-- Print to the terminal the color (as an integer) of a pixel. +print(bmp:get(200, 200)) -- 255 + +-- View the image using the default viewer for the platform. +bmp:view() + +-- Save the image to the file mybmp.bmp in the current directory. +bmp:save() diff --git a/Task/Bitmap/Prolog/bitmap.pro b/Task/Bitmap/Prolog/bitmap.pro index 1ea949bb5f..13b5e3511d 100644 --- a/Task/Bitmap/Prolog/bitmap.pro +++ b/Task/Bitmap/Prolog/bitmap.pro @@ -1,20 +1,20 @@ :- module(bitmap, [ - new_bitmap/3, - fill_bitmap/3, - get_pixel0/3, - set_pixel0/4 ]). + new_bitmap/3, + fill_bitmap/3, + get_pixel0/3, + set_pixel0/4 ]). :- use_module(library(lists)). %-----------------------------------------------------------------------------% % Convenience Predicates replicate(Term,Times,L):- - length(L,Times), - maplist(=(Term),L). + length(L,Times), + maplist(=(Term),L). replace0(N,OL,E,NL):- - nth0(N,OL,_,TL), - nth0(N,NL,E,TL). + nth0(N,OL,_,TL), + nth0(N,NL,E,TL). %-----------------------------------------------------------------------------% % Bitmap Utilities % @@ -25,27 +25,27 @@ replace0(N,OL,E,NL):- % in other bitmap tasks it is assumed to be a list [R,G,B] where % each is an int between 0 and 255, in code: rgb_pixel(RGB):- - length(RGB,3), - maplist(integer,RGB), - maplist(between(0,255),RGB). + length(RGB,3), + maplist(integer,RGB), + maplist(between(0,255),RGB). %new_bitmap(Bitmap,Dimensions,RGB) new_bitmap([[X,Y],Pixels],[X,Y],RGB) :- - replicate(RGB,X,Row), - replicate(Row,Y,Pixels). - + replicate(RGB,X,Row), + replicate(Row,Y,Pixels). + %fill_bitmap(New_Bitmap,Bitmap,RGB) fill_bitmap(New_Bitmap,[[X,Y],_],RGB) :- - new_bitmap(New_Bitmap,[X,Y],RGB). + new_bitmap(New_Bitmap,[X,Y],RGB). %here get and set use 0 based indexing %get_pixel0(Bitmap,Coordinates,RGB) get_pixel0([[_DimX,_DimY],Pixels],[X,Y],RGB) :- - nth0(Y,Pixels,Row), - nth0(X,Row,RGB). + nth0(Y,Pixels,Row), + nth0(X,Row,RGB). %set_pixel0(New Bitmap, Bitmap, Coordinates, RGB) set_pixel0([[DimX,DimY],New_Pixels],[[DimX,DimY],Pixels],[X,Y],RGB) :- - nth0(Y,Pixels,Row), - replace0(X,Row,RGB,New_Row), - replace0(Y,Pixels,New_Row,New_Pixels). + nth0(Y,Pixels,Row), + replace0(X,Row,RGB,New_Row), + replace0(Y,Pixels,New_Row,New_Pixels). diff --git a/Task/Bitmap/Raku/bitmap.raku b/Task/Bitmap/Raku/bitmap.raku index 1bf117941a..e2a0e66931 100644 --- a/Task/Bitmap/Raku/bitmap.raku +++ b/Task/Bitmap/Raku/bitmap.raku @@ -7,16 +7,16 @@ class Bitmap { @!data = $p.clone xx ($!width*$!height) } method pixel( - $i where ^$!width, - $j where ^$!height - --> Pixel + $i where ^$!width, + $j where ^$!height + --> Pixel ) is rw { @!data[$i + $j * $!width] } method set-pixel ($i, $j, Pixel $p) { - self.pixel($i, $j) = $p.clone; + self.pixel($i, $j) = $p.clone; } method get-pixel ($i, $j) returns Pixel { - self.pixel($i, $j); + self.pixel($i, $j); } } diff --git a/Task/Bitmap/RapidQ/bitmap.rapidq b/Task/Bitmap/RapidQ/bitmap.rapidq index ad4ebfe355..71baea5c92 100644 --- a/Task/Bitmap/RapidQ/bitmap.rapidq +++ b/Task/Bitmap/RapidQ/bitmap.rapidq @@ -5,8 +5,8 @@ CREATE form AS QForm Height = 480 CREATE canvas AS QCanvas Height = form.ClientHeight - Width = form.ClientWidth - OnPaint = PaintCanvas + Width = form.ClientWidth + OnPaint = PaintCanvas END CREATE END CREATE diff --git a/Task/Bitmap/Rebol/bitmap.rebol b/Task/Bitmap/Rebol/bitmap.rebol new file mode 100644 index 0000000000..f4d893806b --- /dev/null +++ b/Task/Bitmap/Rebol/bitmap.rebol @@ -0,0 +1,58 @@ +;; make image using pair +img: make image! 2x2 +;; make image using pair and RGB tuple +img: make image! [2x2 255.0.0] +;; make image using pair and RGBA tuple" +img: make image! [2x2 255.0.0.10] + +;; Rebol3's construction syntax +img1: #(image! 4x4) ;; white by default +img2: #(image! 2x2 0.0.0) ;; black image + +;; Raw binary access: +probe img1/rgb +;== #{ +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF} + +;; Blit image to image +change at img1 2x2 img2 +probe img1/rgb +;== #{ +;== FFFFFFFFFFFFFFFFFFFFFFFF +;== FFFFFF000000000000FFFFFF +;== FFFFFF000000000000FFFFFF +;== FFFFFFFFFFFFFFFFFFFFFFFF} + +;; Pixel access +img1/1 ;== 255.255.255.255 +img2/1 ;== 0.0.0.255 +img1/2x2 ;== 0.0.0.255 + +;; Other binary accessors: +img: #(image! 2x1) +img/1: 1.2.3.100 +img/2: 4.5.6.200 +img/rgba ;== #{01020364040506C8} +img/rgbo ;== #{0102039B04050637} +img/argb ;== #{64010203C8040506} +img/orgb ;== #{9B01020337040506} +img/bgra ;== #{03020164060504C8} +img/bgro ;== #{0302019B06050437} +img/abgr ;== #{64030201C8060504} +img/obgr ;== #{9B03020137060504} +img/opacity ;== #{9B37} +img/alpha ;== #{64C8} + +;; Drawing may be done using extensions like Blend2D +import blend2d ;@@ https://github.com/Siskin-framework/Rebol-Blend2D +img: draw 100x100 [ + fill red + pen black + line-width 10 + circle 50x50 20 + fill none + line 0x0 100x100 +] diff --git a/Task/Bitmap/SequenceL/bitmap.sequencel b/Task/Bitmap/SequenceL/bitmap.sequencel index 5facc762fe..ba7a4ffd42 100644 --- a/Task/Bitmap/SequenceL/bitmap.sequencel +++ b/Task/Bitmap/SequenceL/bitmap.sequencel @@ -2,37 +2,37 @@ RGB ::= (R: int(0), G: int(0), B: int(0)); newBitmap: int * int -> RGB(2); newBitmap(width, height)[y, x] := - (R: 0, G: 0, B: 0) - foreach y within 1 ... height, - x within 1 ... width; + (R: 0, G: 0, B: 0) + foreach y within 1 ... height, + x within 1 ... width; fill: RGB(2) * RGB -> RGB(2); fill(bitmap(2), color)[y, x] := - color - foreach y within 1 ... size(bitmap), - x within 1 ... size(bitmap[y]); + color + foreach y within 1 ... size(bitmap), + x within 1 ... size(bitmap[y]); setColorAt: RGB(2) * int * int * RGB -> RGB(2); setColorAt(bitmap(2), x, y, color)[Y, X] := - color when Y = y and X = x - else - bitmap[Y, X]; - -getColorAt: RGB(2) * int * int -> RGB; + color when Y = y and X = x + else + bitmap[Y, X]; + +getColorAt: RGB(2) * int * int -> RGB; getColorAt(bitmap(2), x, y) := bitmap[y, x]; lightGreen := (R: 51, G: 255, B: 51); lightRed := (R: 255, G: 51, B: 51); main(args(2)) := - let - width := 1920; - height := 1200; - - cleanImage := newBitmap(width, height); - - filledGreen := fill(cleanImage, lightGreen); - - redCenter := setColorAt(filledGreen, width / 2, height / 2, lightRed); - in - getColorAt(redCenter, width / 2, height / 2); + let + width := 1920; + height := 1200; + + cleanImage := newBitmap(width, height); + + filledGreen := fill(cleanImage, lightGreen); + + redCenter := setColorAt(filledGreen, width / 2, height / 2, lightRed); + in + getColorAt(redCenter, width / 2, height / 2); diff --git a/Task/Bitmap/Uiua/bitmap.uiua b/Task/Bitmap/Uiua/bitmap.uiua new file mode 100644 index 0000000000..3e952126ca --- /dev/null +++ b/Task/Bitmap/Uiua/bitmap.uiua @@ -0,0 +1,3 @@ +↯ 50_50_3 Red # Fill with red. +⍜(⊡25_25|⋅White) # Add white spot. +⊸⊡0_0 # Get pixel [0 0]. diff --git a/Task/Bitmap/Vedit-macro-language/bitmap.vedit b/Task/Bitmap/Vedit-macro-language/bitmap.vedit index 616c17071b..56f41c3f72 100644 --- a/Task/Bitmap/Vedit-macro-language/bitmap.vedit +++ b/Task/Bitmap/Vedit-macro-language/bitmap.vedit @@ -1,5 +1,5 @@ -#11 = 400 // Width of the image -#12 = 300 // Height of the image +#11 = 400 // Width of the image +#12 = 300 // Height of the image // Create an empty RGB image and fill it with black color // @@ -13,16 +13,16 @@ Repeat(#11 * #12) { // Fill the image with dark blue color // -#5 = 0 // Red -#6 = 0 // Green -#7 = 64 // Blue +#5 = 0 // Red +#6 = 0 // Green +#7 = 64 // Blue Call("FILL_IMAGE") // Draw one pixel in orange color // -#1 = 100 // x -#2 = 50 // y -#5 = 255 #6 = 128 #7 = 0 // Orange color +#1 = 100 // x +#2 = 50 // y +#5 = 255 #6 = 128 #7 = 0 // Orange color Call("DRAW_PIXEL") // Get the color of a pixel diff --git a/Task/Bitmap/Yabasic/bitmap.basic b/Task/Bitmap/Yabasic/bitmap.basic index cad0519374..0dbe5417f2 100644 --- a/Task/Bitmap/Yabasic/bitmap.basic +++ b/Task/Bitmap/Yabasic/bitmap.basic @@ -6,8 +6,8 @@ backcolor 255, 0, 0 // red clear window -color 0, 255, 0 // green +color 0, 255, 0 // green dot 100, 100 -c$ = getbit$(100, 100, 100, 100) // get color area 1x1 pixel +c$ = getbit$(100, 100, 100, 100) // get color area 1x1 pixel print c$ diff --git a/Task/Bitmap/Zig/bitmap.zig b/Task/Bitmap/Zig/bitmap.zig new file mode 100644 index 0000000000..08b57964ef --- /dev/null +++ b/Task/Bitmap/Zig/bitmap.zig @@ -0,0 +1,96 @@ +const std = @import("std"); + +pub const Rgb = struct { + r: u8, + g: u8, + b: u8, +}; + +pub const PixelOutOfBounds = error{PixelOutOfBounds}; + +pub const Bitmap = struct { + width: usize, + height: usize, + pixels: []Rgb, + + // The ! next to the return type communicates that the function may return an error + pub fn new(allocator: std.mem.Allocator, width: usize, height: usize) !Bitmap { + // In Zig libraries that allocate receive an allocator + // instead of choosing one themselves + var pixels = try allocator.alloc(Rgb, width * height); + + for (0..width*height) | i | { + pixels[i] = Rgb { .r = 0, .g = 0, .b = 0 }; + } + + return Bitmap { + .width = width, + .height = height, + .pixels = pixels, + }; + } + + pub fn free(self: Bitmap, allocator: std.mem.Allocator) void { + allocator.free(self.pixels); + } + + pub fn fill(self: *Bitmap, color: Rgb) void { + for (0..self.width*self.height) | i | { + self.pixels[i] = color; + } + } + + pub fn get_pixel_unchecked(self: Bitmap, x: usize, y: usize) Rgb { + return self.pixels[self.height * y + x]; + } + + pub fn get_pixel(self: Bitmap, x: usize, y: usize) !Rgb { + if (self.width <= x or self.height <= y) { + return error.PixelOutOfBounds; + } + + return self.get_pixel_unchecked(x, y); + } + + pub fn set_pixel_unchecked(self: *Bitmap, x: usize, y: usize, color: Rgb) void { + self.pixels[self.height * y + x] = color; + } + + pub fn set_pixel(self: *Bitmap, x: usize, y: usize, color: Rgb) !void { + if (self.width <= x or self.height <= y) { + return error.PixelOutOfBounds; + } + + return self.set_pixel_unchecked(x, y, color); + } +}; + +test "putting a pixel gets the pixel" { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var bm = try Bitmap.new(allocator, 10, 10); + defer bm.free(allocator); + + try bm.set_pixel(4, 4, Rgb {.r=255, .g=0, .b=0}); + + const pixel = try bm.get_pixel(4, 4); + + try std.testing.expectEqual(255, pixel.r); +} + +test "filling a pixel gets all the pixels" { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + const allocator = gpa.allocator(); + + var bm = try Bitmap.new(allocator, 10, 10); + defer bm.free(allocator); + + bm.fill(Rgb {.r=255, .g=0, .b=0}); + + for (0..10) | x | { + for (0..10) | y | { + try std.testing.expectEqual(255, bm.get_pixel_unchecked(x, y).r); + } + } +} diff --git a/Task/Bitmap/Zkl/bitmap-1.zkl b/Task/Bitmap/Zkl/bitmap-1.zkl index b0784bda52..684616c368 100644 --- a/Task/Bitmap/Zkl/bitmap-1.zkl +++ b/Task/Bitmap/Zkl/bitmap-1.zkl @@ -1,16 +1,16 @@ -class PPM{ // (0,0) is logically bottom left +class PPM{ // (0,0) is logically bottom left fcn init(width,height){ sz:=width*height*3; var [const] data=sz.pump(Data(sz),0), // initialize to Black (RGB=000) - w=width, h=height; + w=width, h=height; } fcn fill(rgb){ sz:=data.len()/3; data.clear(); sz.pump(data,T(Void,rgb.toBigEndian(3))); } fcn __sGet(x,y) { data.toBigEndian(3*y*w + 3*x,3); } //ppm[x,y] - fcn __sSet(rbg,x,y){ data[3*y*w + 3*x,3]=rbg.toBigEndian(3); } //ppm[x,y]=rgb + fcn __sSet(rbg,x,y){ data[3*y*w + 3*x,3]=rbg.toBigEndian(3); } //ppm[x,y]=rgb fcn write(out){ // write bottom to top to move (0,0) from bottom left to bottom left out.write("P6\n#rosettacode PPM\n%d %d\n255\n".fmt(w,h)); [h-1..0, -1].pump(out,'wrap(h){ data.seek(3*h*w); data.read(3*w) }); diff --git a/Task/Bitwise-IO/Ada/bitwise-io-1.adb b/Task/Bitwise-IO/Ada/bitwise-io-1.adb new file mode 100644 index 0000000000..f91b32ddf9 --- /dev/null +++ b/Task/Bitwise-IO/Ada/bitwise-io-1.adb @@ -0,0 +1,20 @@ +with Ada.Streams; use Ada.Streams; +with Ada.Finalization; + +package Bit_Streams is + type Bit is range 0..1; + type Bit_Array is array (Positive range <>) of Bit; + type Bit_Stream (Channel : not null access Root_Stream_Type'Class) is limited private; + procedure Read (Stream : in out Bit_Stream; Data : out Bit_Array); + procedure Write (Stream : in out Bit_Stream; Data : Bit_Array); +private + type Bit_Stream (Channel : not null access Root_Stream_Type'Class) is + new Ada.Finalization.Limited_Controlled with + record + Read_Count : Natural := 0; + Write_Count : Natural := 0; + Input : Stream_Element_Array (1..1); + Output : Stream_Element_Array (1..1); + end record; + overriding procedure Finalize (Stream : in out Bit_Stream); +end Bit_Streams; diff --git a/Task/Bitwise-IO/Ada/bitwise-io-2.adb b/Task/Bitwise-IO/Ada/bitwise-io-2.adb new file mode 100644 index 0000000000..0468988655 --- /dev/null +++ b/Task/Bitwise-IO/Ada/bitwise-io-2.adb @@ -0,0 +1,33 @@ +package body Bit_Streams is + procedure Finalize (Stream : in out Bit_Stream) is + begin + if Stream.Write_Count > 0 then + Stream.Output (1) := Stream.Output (1) * 2**(Stream_Element'Size - Stream.Write_Count); + Stream.Channel.Write (Stream.Output); + end if; + end Finalize; + procedure Read (Stream : in out Bit_Stream; Data : out Bit_Array) is + Last : Stream_Element_Offset; + begin + for Index in Data'Range loop + if Stream.Read_Count = 0 then + Stream.Channel.Read (Stream.Input, Last); + Stream.Read_Count := Stream_Element'Size; + end if; + Data (Index) := Bit (Stream.Input (1) / 2**(Stream_Element'Size - 1)); + Stream.Input (1) := Stream.Input (1) * 2; + Stream.Read_Count := Stream.Read_Count - 1; + end loop; + end Read; + procedure Write (Stream : in out Bit_Stream; Data : Bit_Array) is + begin + for Index in Data'Range loop + if Stream.Write_Count = Stream_Element'Size then + Stream.Channel.Write (Stream.Output); + Stream.Write_Count := 0; + end if; + Stream.Output (1) := Stream.Output (1) * 2 or Stream_Element (Data (Index)); + Stream.Write_Count := Stream.Write_Count + 1; + end loop; + end Write; +end Bit_Streams; diff --git a/Task/Bitwise-IO/Ada/bitwise-io-3.adb b/Task/Bitwise-IO/Ada/bitwise-io-3.adb new file mode 100644 index 0000000000..a2db2756aa --- /dev/null +++ b/Task/Bitwise-IO/Ada/bitwise-io-3.adb @@ -0,0 +1,33 @@ +with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO; +with Bit_Streams; use Bit_Streams; + +procedure Test_Bit_Streams is + File : File_Type; + ABACUS : Bit_Array := + ( 1,0,0,0,0,0,1, -- A, big endian + 1,0,0,0,0,1,0, -- B + 1,0,0,0,0,0,1, -- A + 1,0,0,0,0,1,1, -- C + 1,0,1,0,1,0,1, -- U + 1,0,1,0,0,1,1 -- S + ); + Data : Bit_Array (ABACUS'Range); +begin + Create (File, Out_File, "abacus.dat"); + declare + Bits : Bit_Stream (Stream (File)); + begin + Write (Bits, ABACUS); + end; + Close (File); + Open (File, In_File, "abacus.dat"); + declare + Bits : Bit_Stream (Stream (File)); + begin + Read (Bits, Data); + end; + Close (File); + if Data /= ABACUS then + raise Data_Error; + end if; +end Test_Bit_Streams; diff --git a/Task/Bitwise-IO/Rebol/bitwise-io.rebol b/Task/Bitwise-IO/Rebol/bitwise-io.rebol new file mode 100644 index 0000000000..80dccaaf08 --- /dev/null +++ b/Task/Bitwise-IO/Rebol/bitwise-io.rebol @@ -0,0 +1,59 @@ +Rebol [ + title: "Rosetta code: Bitwise IO" + file: %Bitwise_IO.r3 + url: https://rosettacode.org/wiki/Bitwise_IO + note: "Based on Vasyl Zubko's Red language implementation!" +] + +compress-7bit: function [ + "Pack 8-bit bytes into 7-bit chunks (lossless for 7-bit ASCII)" + str [string! binary!] +][ + buf: clear "" ;; string buffer for 7-bit bitstream + bits: enbase/flat str 2 ;; convert input to a flat binary string "0101..." + while [not tail? bits][ ;; take 7 bits out of every 8 + append buf copy/part next bits 7 ;; append bits 2..8 (skip the first bit of each byte) + bits: skip bits 8 ;; move to next 8-bit group + ] + ;; Pad to multiple of 8 bits so it can be debased to bytes + unless zero? (pad-bits: (length? buf) // 8) [ + append/dup buf #"0" 8 - pad-bits + ] + debase buf 2 ;; turn the 7-bit stream (padded) back into binary bytes +] + +decompress-7bit: function [ + "Unpack 7-bit chunks back to 8-bit by re-inserting the leading zero bit per group of 7" + bin [binary!] +][ + bits: enbase/flat bin 2 ;; bitstring of the compressed bytes + filled: 0 ;; counter within a 7-bit group + buf: clear #{} ;; output binary buffer + acc: clear "" ;; accumulator for 7 bits + + foreach bit bits [ + append acc bit ;; collect one bit + filled: filled + 1 + if filled = 7 [ + ;; Prepend a '0' to restore 8th bit, debase to a byte, append to output + append buf debase join #"0" acc 2 + clear acc + filled: 0 + ] + ] + ;; If padding produced a final 0 byte, drop it + if 0 == last buf [take/last buf] + to string! buf ;; return original as string +] + +;- DEMO: +in-string: "Rebol is not dead!" +compressed: compress-7bit in-string ;; compress to 7-bit packed binary +expanded: decompress-7bit compressed ;; decompress back to original + +print [ + "^/in-string :" in-string + "^/in-binary :" to binary! in-string + "^/compressed:" compressed + "^/expanded :" expanded +] diff --git a/Task/Bitwise-operations/Ada/bitwise-operations.adb b/Task/Bitwise-operations/Ada/bitwise-operations.adb new file mode 100644 index 0000000000..c81c073512 --- /dev/null +++ b/Task/Bitwise-operations/Ada/bitwise-operations.adb @@ -0,0 +1,23 @@ +with Ada.Text_IO, Interfaces; +use Ada.Text_IO, Interfaces; + +procedure Bitwise is + subtype Byte is Unsigned_8; + package Byte_IO is new Ada.Text_Io.Modular_IO (Byte); + + A : constant Byte := 2#00011110#; + B : constant Byte := 2#11110100#; + X : constant Byte := 128; + N : constant Natural := 1; +begin + Put ("A and B = "); Byte_IO.Put (Item => A and B, Base => 2); New_Line; + Put ("A or B = "); Byte_IO.Put (Item => A or B, Base => 2); New_Line; + Put ("A xor B = "); Byte_IO.Put (Item => A xor B, Base => 2); New_Line; + Put ("not A = "); Byte_IO.Put (Item => not A, Base => 2); New_Line; + New_Line (2); + Put_Line (Unsigned_8'Image (Shift_Left (X, N))); + Put_Line (Unsigned_8'Image (Shift_Right (X, N))); + Put_Line (Unsigned_8'Image (Shift_Right_Arithmetic (X, N))); + Put_Line (Unsigned_8'Image (Rotate_Left (X, N))); + Put_Line (Unsigned_8'Image (Rotate_Right (X, N))); +end Bitwise; diff --git a/Task/Bitwise-operations/AutoIt/bitwise-operations.au3 b/Task/Bitwise-operations/AutoIt/bitwise-operations.au3 new file mode 100644 index 0000000000..0428a6ff04 --- /dev/null +++ b/Task/Bitwise-operations/AutoIt/bitwise-operations.au3 @@ -0,0 +1,12 @@ +bitwise(255, 5) +Func bitwise($a, $b) + MsgBox(1, '', _ + $a & " AND " & $b & ": " & BitAND($a, $b) & @CRLF & _ + $a & " OR " & $b & ": " & BitOR($a, $b) & @CRLF & _ + $a & " XOR " & $b & ": " & BitXOR($a, $b) & @CRLF & _ + "NOT " & $a & ": " & BitNOT($a) & @CRLF & _ + $a & " SHL " & $b & ": " & BitShift($a, $b * -1) & @CRLF & _ + $a & " SHR " & $b & ": " & BitShift($a, $b) & @CRLF & _ + $a & " ROL " & $b & ": " & BitRotate($a, $b) & @CRLF & _ + $a & " ROR " & $b & ": " & BitRotate($a, $b * -1) & @CRLF ) +EndFunc diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-1.cob b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cob new file mode 100644 index 0000000000..2c7db9603d --- /dev/null +++ b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cob @@ -0,0 +1,55 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. bitwise-ops. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 a PIC 1(32) USAGE BIT. + 01 b PIC 1(32) USAGE BIT. + 01 result PIC 1(32) USAGE BIT. + 01 result-disp REDEFINES result + PIC S9(9) USAGE COMPUTATIONAL. + LINKAGE SECTION. + 01 a-int USAGE BINARY-LONG. + 01 b-int USAGE BINARY-LONG. + + PROCEDURE DIVISION USING a-int, b-int. + MOVE FUNCTION BOOLEAN-OF-INTEGER(a-int, 32) TO a + MOVE FUNCTION BOOLEAN-OF-INTEGER(b-int, 32) TO b + + COMPUTE result = a B-AND b + DISPLAY "a and b is " result-disp + + COMPUTE result = a B-OR b + DISPLAY "a or b is " result-disp + + COMPUTE result = B-NOT a + DISPLAY "Not a is " result-disp + + COMPUTE result = a B-XOR b + DISPLAY "a exclusive-or b is " result-disp + + *> More complex operations can be constructed from these. + + COMPUTE result = B-NOT (a B-XOR b) + DISPLAY "Logical equivalence of a and b is " result-disp + + COMPUTE result = (B-NOT a) B-AND b + DISPLAY "Logical implication of a and b is " result-disp + + *> Shift and rotation operators were only added in COBOL 2023. + + COMPUTE result = a B-SHIFT-L b + DISPLAY "a shifted left by b is " result-disp + + COMPUTE result = b B-SHIFT-R a + DISPLAY "b shifted right by a is " result-disp + + COMPUTE result = a B-SHIFT-LC b + DISPLAY "a rotated left by b is " result-disp + + COMPUTE result = b B-SHIFT-RC a + DISPLAY "b rotated right by a is " result-disp + + GOBACK. + + END PROGRAM bitwise-ops. diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-2.cob b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cob new file mode 100644 index 0000000000..08d7cdc4d6 --- /dev/null +++ b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cob @@ -0,0 +1,41 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. mf-bitwise-ops. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 result USAGE BINARY-LONG. + 78 arg-len VALUE LENGTH OF result. + + LINKAGE SECTION. + 01 a USAGE BINARY-LONG. + 01 b USAGE BINARY-LONG. + + PROCEDURE DIVISION USING a, b. + main-line. + MOVE b TO result + CALL "CBL_AND" USING a, result, VALUE arg-len + DISPLAY "a and b is " result + + MOVE b TO result + CALL "CBL_OR" USING a, result, VALUE arg-len + DISPLAY "a or b is " result + + MOVE a TO result + CALL "CBL_NOT" USING result, VALUE arg-len + DISPLAY "Not a is " result + + MOVE b TO result + CALL "CBL_XOR" USING a, result, VALUE arg-len + DISPLAY "a exclusive-or b is " result + + MOVE b TO result + CALL "CBL_EQ" USING a, result, VALUE arg-len + DISPLAY "Logical equivalence of a and b is " result + + MOVE b TO result + CALL "CBL_IMP" USING a, result, VALUE arg-len + DISPLAY "Logical implication of a and b is " result + + GOBACK. + + END PROGRAM mf-bitwise-ops. diff --git a/Task/Bitwise-operations/Crystal/bitwise-operations.cr b/Task/Bitwise-operations/Crystal/bitwise-operations.cr new file mode 100644 index 0000000000..3fa0470d8a --- /dev/null +++ b/Task/Bitwise-operations/Crystal/bitwise-operations.cr @@ -0,0 +1,9 @@ +def operations (x, y) + p! x, y, + x & y, x | y, x ^ y, + ~x, + x << y, x >> y, + x.rotate_left(y), x.rotate_right(y) +end + +operations 10, 2 diff --git a/Task/Bitwise-operations/PowerShell/bitwise-operations-1.ps1 b/Task/Bitwise-operations/PowerShell/bitwise-operations-1.ps1 new file mode 100644 index 0000000000..d16e1bfbb0 --- /dev/null +++ b/Task/Bitwise-operations/PowerShell/bitwise-operations-1.ps1 @@ -0,0 +1,4 @@ +$X -band $Y +$X -bor $Y +$X -bxor $Y +-bnot $X diff --git a/Task/Bitwise-operations/PowerShell/bitwise-operations-2.ps1 b/Task/Bitwise-operations/PowerShell/bitwise-operations-2.ps1 new file mode 100644 index 0000000000..b316ff6efa --- /dev/null +++ b/Task/Bitwise-operations/PowerShell/bitwise-operations-2.ps1 @@ -0,0 +1,6 @@ +$X -shl $Y +# Arithmetic right shift +$X -shr $Y + +# Requires quite a stretch of the imagination to call this "native" support of right rotate, but it works +[System.Security.Cryptography.SHA256Managed].GetMethod('RotateRight', 'NonPublic, Static', $null, @([UInt32], [Int32]), $null).Invoke($null, @([uint32]$X, $Y)) diff --git a/Task/Bitwise-operations/RISC-V-Assembly/bitwise-operations.asm b/Task/Bitwise-operations/RISC-V-Assembly/bitwise-operations.asm new file mode 100644 index 0000000000..a3766dfca1 --- /dev/null +++ b/Task/Bitwise-operations/RISC-V-Assembly/bitwise-operations.asm @@ -0,0 +1,295 @@ + # riscv assembly raspberry pico2 rp2350 +# program bitwise.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szCariageReturn: .asciz "\r\n" +szMessReg0: .asciz "Register s0:\r\n" +szMessReg1: .asciz "Register s1:\r\n" +szMessAnd: .asciz "And result:\r\n" +szMessOr: .asciz "Or result :\r\n" +szMessXor: .asciz "Xor result :\r\n" +szMessNot: .asciz "Not result :\r\n" +szMessNeg: .asciz "Neg result :\r\n" +szMessBset: .asciz "Set single bit result :\r\n" +szMessSll: .asciz "Shift left result :\r\n" +szMessSrl: .asciz "Shift right result :\r\n" +szMessSra: .asciz "Shift right arithmetic result :\r\n" +szMessRol: .asciz "Rotation left result :\r\n" +szMessRor: .asciz "Rotation right result :\r\n" +szMessBclr: .asciz "Clear single bit result :\r\n" +szMessBext: .asciz "Extraction single bit result :\r\n" +szMessBinv: .asciz "Inversion single bit result :\r\n" +szMessBrev: .asciz "Bit-reverse within each byte result :\r\n" +szMessClz: .asciz "Count leading zeroes result :\r\n" +szMessCtz: .asciz "Count trailing zeroes result :\r\n" +szMessCpop: .asciz "Population count result :\r\n" +szMessPack: .asciz "Pack two halfwords into one word result :\r\n" +szMessPackh: .asciz "Pack two byte into one halfword result :\r\n" +szMessZip: .asciz "Zip result :\r\n" +szMessUnzip: .asciz "Unzip result :\r\n" +.align 2 + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +sConvBinaire: .skip 36 +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szMessReg0 # message address + call writeString # display message + li s0,0b1100 + mv a0,s0 + call displayResult + + la a0,szMessReg1 # message address + call writeString # display message + li s1,0b1001 + mv a0,s1 + call displayResult + + la a0,szMessAnd # and + call writeString # display message + andi a0,s0,0b1001 # and immediat value + call displayResult + and a0,s0,s1 # register and + call displayResult + andn a0,s0,s1 # register and and not + call displayResult + + la a0,szMessOr # or + call writeString # display message + ori a0,s0,0b1001 # or immediat value + call displayResult + or a0,s0,s1 # or register + call displayResult + orn a0,s0,s1 # or and not register + call displayResult + orc.b a0,s0 # OR-combine of bits within each byte. Generates a mask of nonzero bytes + call displayResult + + + la a0,szMessXor # xor + call writeString # display message + xori a0,s0,0b1001 # xor immediat value + call displayResult + xor a0,s0,s1 # xor register + call displayResult + xnor a0,s0,s1 # Bitwise XOR with inverted operand. Equivalently, bitwise NOT of bitwise XOR + call displayResult + + la a0,szMessNot # not + call writeString # display message + not a0,s0 # not + call displayResult + + la a0,szMessNeg # negation + call writeString # display message + neg a0,s0 # negation + call displayResult + + la a0,szMessSll # shift left + call writeString # display message + slli a0,s0,11 # shift left immediat value + call displayResult + li t0,5 + sll a0,s0,t0 # shift left register + call displayResult + + la a0,szMessSrl # shift right + call writeString # display message + srli a0,s0,1 # shift right immediat value + call displayResult + li t0,5 + srl a0,s0,t0 # shift right register + call displayResult + + la a0,szMessSra # Shift right, arithmetic + call writeString # display message + srai a0,s0,1 # shift right arithmetic immediat value + call displayResult + li t0,5 + li t1,0b10000000000000001100000000000000 + sra a0,t1,t0 # shift right arithmetic register + call displayResult + + la a0,szMessRol # rotation left + call writeString # display message + li t0,5 + rol a0,s0,t0 # rotation left register + call displayResult + + la a0,szMessRor # rotation right + call writeString # display message + rori a0,s0,10 # rotation right immediat value + call displayResult + li t0,5 + ror a0,s0,t0 # rotation right register + call displayResult + + la a0,szMessBclr # Clear single bit. + call writeString # display message + bclri a0,s0,3 # Clear single bit. immediat value + call displayResult + li t0,2 + bclr a0,s0,t0 # Clear single bit. register + call displayResult + + la a0,szMessBext # Extraction single bit. + call writeString # display message + bexti a0,s0,3 # Extraction single bit. immediat value + call displayResult + li t0,2 + bext a0,s0,t0 # Extraction single bit. register + call displayResult + + la a0,szMessBinv # Inversion single bit. + call writeString # display message + binvi a0,s0,3 # Inversion bit. immediat value + call displayResult + li t0,2 + binv a0,s0,t0 # Inversion single bit. register + call displayResult + + la a0,szMessBset # Set single bit + call writeString # display message + bseti a0,s0,8 # Set single bit (immediate). + call displayResult + li t0,17 + bset a0,s0,t0 # Set single bit + call displayResult + + la a0,szMessClz # Count leading zeroes (starting from MSB, searching LSB-ward). + call writeString # display message + clz a0,s0 # + call displayResultD + + la a0,szMessCtz # Count trailing zeroes (starting from LSB, searching MSB-ward). + call writeString # display message + ctz a0,s0 # + call displayResultD + + la a0,szMessCpop # Population count + call writeString # display message + cpop a0,s0 # + call displayResultD + + la a0,szMessBrev # Bit-reverse within each byte + call writeString # display message + brev8 a0,s0 # + call displayResult + + la a0,szMessPack # Pack two halfwords into one word + call writeString # display message + li t0,0x1234 + li t1,0x5678 + pack a0,t1,t0 # + call displayResultHex + + la a0,szMessPackh # Pack two halfwords into one word + call writeString # display message + li t0,0x12 + li t1,0x34 + packh a0,t1,t0 # + call displayResultHex + + la a0,szMessZip # Interleave upper/lower half of register into odd/even bits of result + call writeString # display message + zip s2,s0 + mv a0,s2 # + call displayResult + + la a0,szMessUnzip # Deinterleave odd/even bits of register into upper/lower half of result + call writeString # display message + unzip a0,s2 # + call displayResult + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* display binary Result */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResult: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvBinaire # conversion result address + call conversion2 # binary conversion + la a0,sConvBinaire # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* display hexadecimal result */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultHex: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion16 # conversion decimal + la a0,sConvArea # message address + call writeString # display message + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Bitwise-operations/Rebol/bitwise-operations.rebol b/Task/Bitwise-operations/Rebol/bitwise-operations.rebol new file mode 100644 index 0000000000..13a05d8bd0 --- /dev/null +++ b/Task/Bitwise-operations/Rebol/bitwise-operations.rebol @@ -0,0 +1,32 @@ +Rebol [ + title: "Rosetta code: Bitwise operations" + file: %Bitwise_operations.r3 + url: https://rosettacode.org/wiki/Bitwise_operations + needs: 3.10.0 +] + +do-test: function [code][ + res: try code + case [ + error? res [res: join "error: " res/id] + integer? res [res: enbase to-binary res 2] + ] + printf [-21 " == "] reduce [form code res] +] +foreach test [ + [10] + [2] + [10 AND 2] + [10 & 2] + [10 OR 2] + [10 | 2] + [10 XOR 2] + [10 >> 2] + [10 << 2] + [-65432] + [complement -65432] + [255] + [shift 255 -2] + [shift 255 56] + [shift/logical 255 56] +][ do-test test ] diff --git a/Task/Bitwise-operations/Uiua/bitwise-operations.uiua b/Task/Bitwise-operations/Uiua/bitwise-operations.uiua new file mode 100644 index 0000000000..3b42c9fbd9 --- /dev/null +++ b/Task/Bitwise-operations/Uiua/bitwise-operations.uiua @@ -0,0 +1,9 @@ +a ← 10 +b ← 2 +# Experimental! +¬a # bitwise NOT +°⋯ /× ⋯ ⊟ a b # bitwise AND +°⋯ /∨ ⋯ ⊟ a b # bitwise OR +°⋯ /≠ ⋯ ⊟ a b # bitwise XOR +* a ⁿ:2 b # SHL +⌊÷: a ⁿ:2 b # ASR diff --git a/Task/Bitwise-operations/V-(Vlang)/bitwise-operations.v b/Task/Bitwise-operations/V-(Vlang)/bitwise-operations.v new file mode 100644 index 0000000000..9f8b2187cb --- /dev/null +++ b/Task/Bitwise-operations/V-(Vlang)/bitwise-operations.v @@ -0,0 +1,9 @@ +fn bitwise(a int, b int) { + println("a AND b: ${a & b}") + println("a OR b: ${a | b}") + println("a XOR b: ${a ^ b}") + println("NOT a: ${~a}") + println("a SHL b: ${a << b}") // left shift + println("a SHR b: ${a >> b}") // right shift + println("a USHR b: ${a >>> b}") // unsigned right shift +} diff --git a/Task/Blum-integer/AWK/blum-integer.awk b/Task/Blum-integer/AWK/blum-integer.awk new file mode 100644 index 0000000000..a50028c636 --- /dev/null +++ b/Task/Blum-integer/AWK/blum-integer.awk @@ -0,0 +1,53 @@ +# syntax: GAWK -f BLUM_INTEGER.AWK +# converted from FutureBasic +# +# sorting: +# PROCINFO["sorted_in"] is used by GAWK +# SORTTYPE is used by Thompson Automation's TAWK +# +BEGIN { + n = 3 + prime2 = 0 + print("The first 50 Blum integers:") + while (1) { + if (is_semiprime(n)) { + if (prime1 % 4 == 3) { + prime2 = n / prime1 + if ((prime2 != prime1) && (prime2 % 4 == 3)) { + arr[substr(n,length(n),1)]++ + total++ + if (++count <= 50) { + printf("%4d%s",n,count%10?"":"\n") + } + if (count ~ /^(26828|[1-4]00000)$/) { + printf("\nThe %6dth Blum integer: %7d",count,n) + if (count >= 400000) { + break + } + } + } + } + } + n += 2 + } + PROCINFO["sorted_in"] = "@ind_num_asc" ; SORTTYPE = 1 + printf("\n\nFor Blum integers up to %d:\n",count) + for (i in arr) { + printf("%7.3f%% end in %d\n",arr[i]/total*100,i) + } + exit(0) +} +function is_semiprime(n, c,d) { + c = 0 + d = 3 + while (d * d <= n) { + while (n % d == 0) { + if (c == 2) { return(0) } + n /= d + c++ + } + d += 2 + } + prime1 = n + return(c == 1) +} diff --git a/Task/Blum-integer/Ada/blum-integer.adb b/Task/Blum-integer/Ada/blum-integer.adb new file mode 100644 index 0000000000..5c8e2c59ca --- /dev/null +++ b/Task/Blum-integer/Ada/blum-integer.adb @@ -0,0 +1,89 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; + +procedure Blum is + + Inc : Constant array (1 .. 8) of Integer := (4, 2, 4, 2, 4, 6, 2, 6); + + function Is_Prime (N : Integer) return Boolean is + D : Integer := 5; + begin + if N < 2 then return False; end if; + if N mod 2 = 0 then return N = 2; end if; + if N mod 3 = 0 then return N = 3; end if; + + while D * D <= N loop + if N mod D = 0 then return False; end if; + D := D + 2; + if N mod D = 0 then return False; end if; + D := D + 4; + end loop; + + return True; + end Is_Prime; + + function First_Prime_Factor (N : Integer) return Integer is + D : Integer := 7; + I : Integer := 1; + begin + if N = 1 then return 1; end if; + if N mod 3 = 0 then return 3; end if; + if N mod 5 = 0 then return 5; end if; + + while D * D <= N loop + if N mod D = 0 then + return D; + end if; + D := D + Inc(I); + I := (I mod 8) + 1; + end loop; + + return N; + end First_Prime_Factor; + + I, Blum_Count : Integer := 1; + J, P, Q : Integer; + Blums : Array (1 .. 50) of Integer; + Counts : Array (1 .. 4) of Integer := (others => 0); + Final_Digits : Array (1 .. 4) of Integer := (1, 3, 7, 9); + +begin + loop + P := First_Prime_Factor(I); + if P mod 4 = 3 then + Q := I / P; + if Q /= P and Q mod 4 = 3 and Is_Prime(Q) then + if Blum_Count < 51 then Blums(Blum_Count) := I; end if; + Counts(((I mod 10) / 3) + 1) := Counts(((I mod 10) / 3) + 1) + 1; + Blum_Count := Blum_Count + 1; + if Blum_Count = 51 then + Put("First 50 Blum Integers:"); New_Line; + for J in Integer range 1 .. 50 loop + Put(Item => Blums(J), Width => 3); Put(" "); + if J mod 10 = 0 then New_Line; end if; + end loop; + New_Line; + elsif Blum_Count = 26829 or Blum_Count mod 100000 = 1 then + Put("The "); Put(Item => Blum_Count, Width => 7); + Put("th Blum Integer is: "); Put(Item => I, Width => 9); + New_Line; + if Blum_Count = 400001 then + New_Line; Put("% Distribution of the First 400,000 Blum Integers:"); New_Line; + for J in Integer range 1 .. 4 loop + Put(" "); Put(Item => Float(Counts(J)) / 4000.0, Fore => 2, Aft => 3, Exp => 0); + Put("% end in "); Put(Item => Final_Digits(J), Width => 1); + New_Line; + end loop; + exit; + end if; + end if; + end if; + end if; + if I mod 5 = 3 then + I := I + 4; + else + I := I + 2; + end if; + end loop; +end Blum; diff --git a/Task/Blum-integer/Arturo/blum-integer.arturo b/Task/Blum-integer/Arturo/blum-integer.arturo new file mode 100644 index 0000000000..2ca6df51a1 --- /dev/null +++ b/Task/Blum-integer/Arturo/blum-integer.arturo @@ -0,0 +1,17 @@ +blum?: function [n][ + if any? @[n < 21, even? n, zero? n % 5] + -> return false + + f: factors.prime n + if or? [2 <> size f][f\0 = f\1] + -> return false + + every? f => [3 = & % 4] +] + +print "First 50 Blum numbers:" +1..∞ | select.first: 50 => blum? + | split.every: 10 + | loop => [print map & 'x -> pad to :string x 4] + +print ["\n26828th Blum number:" select.n:26828 1..∞ => blum?] diff --git a/Task/Blum-integer/Frink/blum-integer.frink b/Task/Blum-integer/Frink/blum-integer.frink new file mode 100644 index 0000000000..7f566d6cf6 --- /dev/null +++ b/Task/Blum-integer/Frink/blum-integer.frink @@ -0,0 +1,27 @@ +isBlum = {|x| + f = factorFlat[x] + if length[f] != 2 + return false + + f1 = first[f] + f2 = last[f] + return (f1 != f2) and (first[f] mod 4 == 3) and (last[f] mod 4 == 3) +} + +println["First 50:"] +println[first[select[count[1], isBlum], 50]] + +ret = new array +for n = [26828, 100000, 200000, 300000, 400000] + ret.push[["${n}th is: ", nth1[select[count[1], isBlum], n]]] + +println[formatTable[ret, "right"]] + +d = new dict +for n = first[select[count[1], isBlum], 400000] + d.increment[right[toString[n],1]] + +println["Distribution of the first 400000 Blum integers:"] +sum = sum[d.values[]] +for k = sort[d.keys[]] + println[formatFix[d@k / sum, "percent", 3] + " end in $k"] diff --git a/Task/Blum-integer/Pluto/blum-integer.pluto b/Task/Blum-integer/Pluto/blum-integer.pluto new file mode 100644 index 0000000000..1f47fd7135 --- /dev/null +++ b/Task/Blum-integer/Pluto/blum-integer.pluto @@ -0,0 +1,53 @@ +local int = require "int" +local fmt = require "fmt" + +local inc = {4, 2, 4, 2, 4, 6, 2, 6} + +-- Assumes n is odd. +local function first_prime_factor(n) + if n == 1 then return 1 end + if n % 3 == 0 then return 3 end + if n % 5 == 0 then return 5 end + local k = 7 + local i = 1 + while k * k <= n do + if n % k == 0 then + return k + else + k = k + inc[i] + i = i % 8 + 1 + end + end + return n +end + +local blum = {} +local bc = 0 +local counts = { [1] = 0, [3] = 0, [7] = 0, [9] = 0 } +local i = 1 +while true do + local p = first_prime_factor(i) + if p % 4 == 3 then + local q = i // p + if q != p and q % 4 == 3 and int.isprime(q) then + if bc < 50 then blum:insert(i) end + counts[i % 10] += 1 + bc += 1 + if bc == 50 then + print("First 50 Blum integers:") + fmt.tprint("%3d ", blum, 10) + print() + elseif bc == 26828 or bc % 100_000 == 0 then + fmt.print("The %9s Blum integer is: %9s", fmt.ord(bc, true), fmt.int(i)) + if bc == 400_000 then + print("\n% distribution of the first 400,000 Blum integers:") + for {1, 3, 7, 9} as j do + fmt.print(" %6.3f%% end in %d", counts[j] / 4000, j) + end + return + end + end + end + end + i = (i % 5 == 3) ? i + 4 : i + 2 +end diff --git a/Task/Blum-integer/REXX/blum-integer-1.rexx b/Task/Blum-integer/REXX/blum-integer-1.rexx new file mode 100644 index 0000000000..f2ec8d05b6 --- /dev/null +++ b/Task/Blum-integer/REXX/blum-integer-1.rexx @@ -0,0 +1,59 @@ +include Setting + +Say Time() +Call Time 'R' +blumCount = 0 +blums.=0 +lastDigitCounts.=0 +Do number=5 By 4 While blumCount < 400000 + Prime=leastPrimeFactor(number) + If Prime // 4=3 Then Do + quotient=number / Prime; + If quotient <> Prime & isPrimeType3(quotient) Then Do + blumCount+=1 + If blumCount<=50 Then Do + blums.blumCount=number + End + lastdigit=Right(number,1) + lastDigitCounts.lastdigit+=1 + If blumCount=50 Then Do + Say "The first 50 Blum integers:" + Do i=1 To 50 + If Right(i,1)=1 Then + l=Format(blums.i,3) + Else + l=l Format(blums.i,3) + If i//10=0 Then + Say l + End + Say '' + End + Else Do + If blumCount=26828 | blumCount // 100000 = 0 Then Do + Say "The " Format(blumCount,7)"th Blum Integer is:" Format(number,7) Time() + If blumCount=400000 Then Do + Say '' + Say "Percent distribution of the first 400000 Blum integers:" + Do i=0 To 9 + If lastDigitCounts.i>0 Then + Say Format(lastDigitCounts.i/4000,6,3)'% end in' i + End + End + End + End + End + End + End +Say Time() +say Time('E') 'seconds' +Exit + +isPrimeType3: Procedure expose Memo. + Parse Arg number + Return Prime(number) & (number//4=3) + +leastPrimeFactor: Procedure expose Memo. + Parse Arg number + Return FFactor(number) + +include Math diff --git a/Task/Blum-integer/REXX/blum-integer-2.rexx b/Task/Blum-integer/REXX/blum-integer-2.rexx new file mode 100644 index 0000000000..9c5598e2ee --- /dev/null +++ b/Task/Blum-integer/REXX/blum-integer-2.rexx @@ -0,0 +1,89 @@ +-- 28 Aug 2025 +include Setting +arg count +if count = '' then + count = 400000 +threshold=25*count + +say 'BLUM INTEGER' +say version +say +say 'Parameters...' +say 'Threshold' threshold 'Count' count +say +say 'Collect primes...' +say Primes(threshold) 'found'; say +say 'Filter primes 3 modulo 4...' +say Filter3Mod4() 'found'; say +say 'Generate Blum integers...' +say GenerateBlum(threshold) 'found'; say +say 'Blum integers...'; say +call Results threshold,count +call Timer +exit + +Filter3Mod4: +procedure expose Prim. +n=0 +do i = 1 to Prim.0 + if Prim.i//4 = 3 then + n=n+1 + else + Prim.i=0 +end +return n + +GenerateBlum: +procedure expose Prim. Blum. +arg threshold +Blum.=0; n=0 +do i = 1 to Prim.0 + if Prim.i <> 0 then do + do j = i+1 to Prim.0 + if Prim.j <> 0 then do + p=Prim.i*Prim.j + if p > threshold then + leave j + n=n+1; Blum.p=1 + end + end + end +end +return n + +Results: +procedure expose Blum. +arg threshold,count +n=0; digs.=0 +do i = 5 by 4 to threshold + if \ Blum.i then + iterate i + n=n+1 + if n > count then + leave i + d=Right(i,1); digs.d=digs.d+1 + if n < 51 then do + if n = 1 then + say 'The first 50 are' + call CharOut ,Right(i,4) + if n//10 = 0 then + say + if n = 50 then + say + iterate i + end + if n = 26828 | n//100000 = 0 then + say 'The' n'th is' i + if n = count then do + say + say 'Percent distribution of the first' count + do i = 1 to 9 + if digs.i > 0 then + say format(digs.i*100/count,2,3)'% ends in' i + end + end +end +say +return 0 + +include Math diff --git a/Task/Boolean-values/Ada/boolean-values.adb b/Task/Boolean-values/Ada/boolean-values.adb new file mode 100644 index 0000000000..9316e2af11 --- /dev/null +++ b/Task/Boolean-values/Ada/boolean-values.adb @@ -0,0 +1 @@ + type Boolean is (False, True); diff --git a/Task/Boolean-values/COBOL/boolean-values-1.cob b/Task/Boolean-values/COBOL/boolean-values-1.cob new file mode 100644 index 0000000000..d5f1241abb --- /dev/null +++ b/Task/Boolean-values/COBOL/boolean-values-1.cob @@ -0,0 +1 @@ + 01 some-bool PIC 1 BIT. diff --git a/Task/Boolean-values/COBOL/boolean-values-2.cob b/Task/Boolean-values/COBOL/boolean-values-2.cob new file mode 100644 index 0000000000..39dd3a3df5 --- /dev/null +++ b/Task/Boolean-values/COBOL/boolean-values-2.cob @@ -0,0 +1,4 @@ + 01 X PIC 9. + 88 X-Is-One VALUE 1. + 88 X-Is-Even VALUE 0 2 4 6 8. + 88 X-Larger-Than-5 VALUE 6 THRU 9. diff --git a/Task/Boolean-values/COBOL/boolean-values-3.cob b/Task/Boolean-values/COBOL/boolean-values-3.cob new file mode 100644 index 0000000000..bb411f5080 --- /dev/null +++ b/Task/Boolean-values/COBOL/boolean-values-3.cob @@ -0,0 +1,28 @@ + PROGRAM-ID. Condition-Example. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Foo PIC 9 VALUE 5. + 88 Is-Not-Zero VALUE 1 THRU 9 + WHEN SET TO FALSE IS 0. + + PROCEDURE DIVISION. + Main. + PERFORM Is-Foo-Zero + + SET Is-Not-Zero TO FALSE + PERFORM Is-Foo-Zero + + SET Is-Not-Zero TO TRUE + PERFORM Is-Foo-Zero + + GOBACK + . + + Is-Foo-Zero. + IF Is-Not-Zero + DISPLAY "Foo is not zero, it is " Foo "." + ELSE + DISPLAY "Foo is zero." + END-IF + . diff --git a/Task/Boolean-values/Haxe/boolean-values.hx b/Task/Boolean-values/Haxe/boolean-values.hx new file mode 100644 index 0000000000..c2f8a2ed4c --- /dev/null +++ b/Task/Boolean-values/Haxe/boolean-values.hx @@ -0,0 +1,8 @@ +class Main { + static public function main():Void { + var t = true; + var f = false; + $type(t); + $type(f); + } +} diff --git a/Task/Boolean-values/LOLCODE/boolean-values.lol b/Task/Boolean-values/LOLCODE/boolean-values.lol new file mode 100644 index 0000000000..5e3e1bc953 --- /dev/null +++ b/Task/Boolean-values/LOLCODE/boolean-values.lol @@ -0,0 +1,15 @@ +HAI 1.3 + + FAIL, O RLY?, YA RLY, VISIBLE " 0"!, NO WAI, VISIBLE " -0"!, OIC BTW GET -0 + WIN, O RLY?, YA RLY, VISIBLE " 1"!, NO WAI, VISIBLE " -1"!, OIC BTW GET 1 + "", O RLY?, YA RLY, VISIBLE " 2"!, NO WAI, VISIBLE " -2"!, OIC BTW GET -2 + ".", O RLY?, YA RLY, VISIBLE " 3"!, NO WAI, VISIBLE " -3"!, OIC BTW GET 3 + 0, O RLY?, YA RLY, VISIBLE " 4"!, NO WAI, VISIBLE " -4"!, OIC BTW GET -4 + 1, O RLY?, YA RLY, VISIBLE " 5"!, NO WAI, VISIBLE " -5"!, OIC BTW GET 5 + 0.0, O RLY?, YA RLY, VISIBLE " 6"!, NO WAI, VISIBLE " -6"!, OIC BTW GET -6 + 1.0, O RLY?, YA RLY, VISIBLE " 7"!, NO WAI, VISIBLE " -7"!, OIC BTW GET 7 + + I HAS A N0 ITZ A NOOB + N0, O RLY?, YA RLY, VISIBLE " 8"!, NO WAI, VISIBLE " -8"!, OIC BTW GET -8 + +KTHXBYE diff --git a/Task/Boolean-values/PowerShell/boolean-values.ps1 b/Task/Boolean-values/PowerShell/boolean-values.ps1 new file mode 100644 index 0000000000..4d06109c52 --- /dev/null +++ b/Task/Boolean-values/PowerShell/boolean-values.ps1 @@ -0,0 +1,2 @@ +$true +$false diff --git a/Task/Boolean-values/Red/boolean-values.red b/Task/Boolean-values/Red/boolean-values.red new file mode 100644 index 0000000000..8ed1e79643 --- /dev/null +++ b/Task/Boolean-values/Red/boolean-values.red @@ -0,0 +1,8 @@ +;- 3 ways to declare true in a variable named a +a: true +a: on +a: yes +;- 3 ways to declare false in a variable named b +b: false +b: off +b: no diff --git a/Task/Boolean-values/Uiua/boolean-values.uiua b/Task/Boolean-values/Uiua/boolean-values.uiua new file mode 100644 index 0000000000..769ce8a2eb --- /dev/null +++ b/Task/Boolean-values/Uiua/boolean-values.uiua @@ -0,0 +1,4 @@ += 4 4 # --> 1 += 4 5 # --> 1 +↧ 1 0 # --> 0 +↥ 0 1 # --> 1 diff --git a/Task/Boolean-values/VBScript/boolean-values.vbs b/Task/Boolean-values/VBScript/boolean-values.vbs new file mode 100644 index 0000000000..d4db3e03a4 --- /dev/null +++ b/Task/Boolean-values/VBScript/boolean-values.vbs @@ -0,0 +1,6 @@ +a = True +b = False +Randomize Timer +x = Int(Rnd * 2) <> 0 +y = Int(Rnd * 2) = 0 +MsgBox a & " " & b & " " & x & " " & y diff --git a/Task/Box-the-compass/Ada/box-the-compass.adb b/Task/Box-the-compass/Ada/box-the-compass.adb new file mode 100644 index 0000000000..6396c3b50b --- /dev/null +++ b/Task/Box-the-compass/Ada/box-the-compass.adb @@ -0,0 +1,66 @@ +with Ada.Text_IO; + +procedure Box_The_Compass is + + type Degrees is digits 5 range 0.00 .. 359.99; + type Index_Type is mod 32; + + function Long_Name(Short: String) return String is + + function Char_To_Name(Char: Character) return String is + begin + case Char is + when 'N' | 'n' => return Char & "orth"; + when 'S' | 's' => return Char & "outh"; + when 'E' | 'e' => return Char & "ast"; + when 'W' | 'w' => return Char & "est"; + when 'b' => return " by "; + when '-' => return "-"; + when others => raise Constraint_Error; + end case; + end Char_To_Name; + + begin + if Short'Length = 0 or else Short(Short'First)=' ' then + return ""; + else + return Char_To_Name(Short(Short'First)) + & Long_Name(Short(Short'First+1 .. Short'Last)); + end if; + end Long_Name; + + procedure Put_Line(Angle: Degrees) is + + function Index(D: Degrees) return Index_Type is + begin + return Index_Type(Integer(Degrees'Rounding(D/11.25)) mod 32); + end Index; + + I: Integer := Integer(Index(Angle))+1; + package DIO is new Ada.Text_IO.Float_IO(Degrees); + Abbr: constant array(Index_Type) of String(1 .. 4) + := ("N ", "Nbe ", "N-ne", "Nebn", "Ne ", "Nebe", "E-ne", "Ebn ", + "E ", "Ebs ", "E-se", "Sebe", "Se ", "Sebs", "S-se", "Sbe ", + "S ", "Sbw ", "S-sw", "Swbs", "Sw ", "Swbw", "W-sw", "Wbs ", + "W ", "Wbn ", "W-nw", "Nwbw", "Nw ", "Nwbn", "N-nw", "Nbw "); + + begin + DIO.Put(Angle, Fore => 3, Aft => 2, Exp => 0); -- format "zzx.xx" + Ada.Text_IO.Put(" |"); + if I <= 9 then + Ada.Text_IO.Put(" "); + end if; + Ada.Text_IO.Put_Line(" " & Integer'Image(I) & " | " + & Long_Name(Abbr(Index(Angle)))); + end Put_Line; + + Difference: constant array(0..2) of Degrees'Base + := (0=> 0.0, 1=> +5.62, 2=> - 5.62); + +begin + Ada.Text_IO.Put_Line(" angle | box | compass point"); + Ada.Text_IO.Put_Line(" ---------------------------------"); + for I in 0 .. 32 loop + Put_Line(Degrees(Degrees'Base(I) * 11.25 + Difference(I mod 3))); + end loop; +end Box_The_Compass; diff --git a/Task/Box-the-compass/AutoIt/box-the-compass.au3 b/Task/Box-the-compass/AutoIt/box-the-compass.au3 new file mode 100644 index 0000000000..7049c0455f --- /dev/null +++ b/Task/Box-the-compass/AutoIt/box-the-compass.au3 @@ -0,0 +1,18 @@ +Local $avArray[33] = [0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, _ + 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, _ + 303.75, 320.62, 320.63, 337.5, 354.37, 354.38] + +For $i = 0 To UBound($avArray) - 1 + Boxing_the_compass($avArray[$i]) +Next + +Func Boxing_the_compass($Degree) + Local $namearray[33] = ["North", "North by east", "North-northeast", "Northeast by north", "Northeast", _ + "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", _ + "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", _ + "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", _ + "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", _ + "North-northwest", "North by west", "North"] + ConsoleWrite(StringFormat("%-2s", Mod(Floor($Degree / 11.25 + 0.5), 32)) & " : " & _ + StringFormat("%-20s", $namearray[Mod(Floor($Degree / 11.25 + 0.5), 32)]) & " : " & $Degree & @CRLF) +EndFunc ;==>Boxing_the_compass diff --git a/Task/Box-the-compass/COBOL/box-the-compass.cob b/Task/Box-the-compass/COBOL/box-the-compass.cob new file mode 100644 index 0000000000..697e53d2db --- /dev/null +++ b/Task/Box-the-compass/COBOL/box-the-compass.cob @@ -0,0 +1,67 @@ + identification division. + program-id. box-compass. + data division. + working-storage section. + 01 point pic 99. + 01 degrees usage float-short. + 01 degrees-rounded pic 999v99. + 01 show-degrees pic zz9.99. + 01 box pic z9. + 01 fudge pic 9. + 01 compass pic x(4). + 01 compass-point pic x(18). + 01 shortform pic x. + 01 short-names. + 05 short-name pic x(4) occurs 33 times. + 01 overlay. + 05 value "N " & "NbE " & "N-NE" & "NEbN" & "NE " & + "NEbE" & "E-NE" & "EbN " & "E " & "EbS " & + "E-SE" & "SEbE" & "SE " & "SEbS" & "S-SE" & + "SbE " & "S " & "SbW " & "S-SW" & "SWbS" & + "SW " & "SWbW" & "W-SW" & "WbS " & "W " & + "WbN " & "W-NW" & "NWbW" & "NW " & "NWbN" & + "N-NW" & "NbW " & "N ". + + procedure division. + display "Index Compass point Degree" + + move overlay to short-names. + perform varying point from 0 by 1 until point > 32 + compute box = function mod(point 32) + 1 + compute degrees = point * 11.25 + compute fudge = function mod(point 3) + evaluate fudge + when equal 1 + add 5.62 to degrees + when equal 2 + subtract 5.62 from degrees + end-evaluate + + compute degrees-rounded rounded = degrees + move degrees-rounded to show-degrees + inspect show-degrees replacing trailing '00' by '0 ' + inspect show-degrees replacing trailing '50' by '5 ' + + move short-name(point + 1) to compass + move spaces to compass-point + display space box space space space with no advancing + perform varying tally from 1 by 1 until tally > 4 + move compass(tally:1) to shortform + move function concatenate(function trim(compass-point), + function substitute(shortform, + "N", "North", + "E", "East", + "S", "South", + "W", "West", + "b", " byZ", + "-", "-")) + to compass-point + end-perform + move function substitute(compass-point, "Z", " ") + to compass-point + move function lower-case(compass-point) to compass-point + move function upper-case(compass-point(1:1)) + to compass-point(1:1) + display compass-point space show-degrees + end-perform + goback. diff --git a/Task/Box-the-compass/Euphoria/box-the-compass.eu b/Task/Box-the-compass/Euphoria/box-the-compass.eu new file mode 100644 index 0000000000..89204975e6 --- /dev/null +++ b/Task/Box-the-compass/Euphoria/box-the-compass.eu @@ -0,0 +1,23 @@ +constant names = {"North","North by east","North-northeast","Northeast by north", + "Northeast","Northeast by east","East-northeast","East by north","East", + "East by south","East-southeast","Southeast by east","Southeast","Southeast by south", + "South-southeast","South by east","South","South by west","South-southwest", + "Southwest by south","Southwest","Southwest by west","West-southwest", + "West by south","West","West by north","West-northwest","Northwest by west", + "Northwest","Northwest by north","North-northwest","North by west"} + +function deg2ind(atom degree) + return remainder(floor(degree*32/360+.5),32)+1 +end function + +sequence degrees +degrees = {} +for i = 0 to 32 do + degrees &= i*11.25 + 5.62*(remainder(i+1,3)-1) +end for + +integer j +for i = 1 to length(degrees) do + j = deg2ind(degrees[i]) + printf(1, "%6.2f %2d %-22s\n", {degrees[i], j, names[j]}) +end for diff --git a/Task/Box-the-compass/Pluto/box-the-compass.pluto b/Task/Box-the-compass/Pluto/box-the-compass.pluto new file mode 100644 index 0000000000..aa3cb8abae --- /dev/null +++ b/Task/Box-the-compass/Pluto/box-the-compass.pluto @@ -0,0 +1,63 @@ +local fmt = require "fmt" + +---'cpx' returns integer index from 1 to 32 corresponding to compass point. +-- Input heading h is in degrees. +local function cpx(h) + local x = math.floor(h /11.25 + 0.5) % 32 + if x < 0 then x += 32 end + return x + 1 +end + +-- Printable compass points. +local compass_point = { + "North", + "North by east", + "North-northeast", + "Northeast by north", + "Northeast", + "Northeast by east", + "East-northeast", + "East by north", + "East", + "East by south", + "East-southeast", + "Southeast by east", + "Southeast", + "Southeast by south", + "South-southeast", + "South by east", + "South", + "South by west", + "South-southwest", + "Southwest by south", + "Southwest", + "Southwest by west", + "West-southwest", + "West by south", + "West", + "West by north", + "West-northwest", + "Northwest by west", + "Northwest", + "Northwest by north", + "North-northwest", + "North by west" +} + +-- Function required by task. +local function degrees_to_compass_point(h) return compass_point[cpx(h)] end +local r = { + 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, + 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, + 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, + 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 +} + +print("Index Compass point Degree") +local i = 0 +for r as h do + local index = i % 32 + 1 + local d = degrees_to_compass_point(h) + fmt.print("%4d %-19s %7.2f°", index, d, h) + i += 1 +end diff --git a/Task/Box-the-compass/PowerShell/box-the-compass-1.ps1 b/Task/Box-the-compass/PowerShell/box-the-compass-1.ps1 new file mode 100644 index 0000000000..7fbf594f28 --- /dev/null +++ b/Task/Box-the-compass/PowerShell/box-the-compass-1.ps1 @@ -0,0 +1,16 @@ +function Convert-DegreeToDirection ( [double]$Degree ) + { + + $Directions = @( 'n','n by e','n-ne','ne by n','ne','ne by e','e-ne','e by n', + 'e','e by s','e-se','se by e','se','se by s','s-se','s by e', + 's','s by w','s-sw','sw by s','sw','sw by w','w-sw','w by s', + 'w','w by n','w-nw','nw by w','nw','nw by n','n-nw','n by w', + 'n' + ).Replace( 's', 'south' ).Replace( 'e', 'east' ).Replace( 'n', 'north' ).Replace( 'w', 'west' ) + + $Directions[[math]::floor(( $Degree % 360 ) / 11.25 + 0.5 )] + } + +$x = 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 + +$x | % { Convert-DegreeToDirection -Degree $_ } diff --git a/Task/Box-the-compass/PowerShell/box-the-compass-2.ps1 b/Task/Box-the-compass/PowerShell/box-the-compass-2.ps1 new file mode 100644 index 0000000000..5c1ab4244e --- /dev/null +++ b/Task/Box-the-compass/PowerShell/box-the-compass-2.ps1 @@ -0,0 +1,23 @@ +function Convert-DegreeToDirection ( [double]$Degree, [int]$Points ) + { + + $Directions = @( 'n','n by e','n-ne','ne by n','ne','ne by e','e-ne','e by n', + 'e','e by s','e-se','se by e','se','se by s','s-se','s by e', + 's','s by w','s-sw','sw by s','sw','sw by w','w-sw','w by s', + 'w','w by n','w-nw','nw by w','nw','nw by n','n-nw','n by w', + 'n' + ).Replace( 's', 'south' ).Replace( 'e', 'east' ).Replace( 'n', 'north' ).Replace( 'w', 'west' ) + + $Directions[[math]::floor((( $Degree % 360 ) * $Points / 360 + 0.5 )) * 32 / $Points ] + } + +$x = 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38 + + +$Values = @() +ForEach ( $Degree in $X ) { $Values += [pscustomobject]@{ Degree = $Degree + 32 = ( Convert-DegreeToDirection -Degree $Degree -Points 32 ) + 16 = ( Convert-DegreeToDirection -Degree $Degree -Points 16 ) + 8 = ( Convert-DegreeToDirection -Degree $Degree -Points 8 ) + 4 = ( Convert-DegreeToDirection -Degree $Degree -Points 4 ) } } +$Values | Format-Table diff --git a/Task/Box-the-compass/Rebol/box-the-compass.rebol b/Task/Box-the-compass/Rebol/box-the-compass.rebol new file mode 100644 index 0000000000..9784b5a0eb --- /dev/null +++ b/Task/Box-the-compass/Rebol/box-the-compass.rebol @@ -0,0 +1,107 @@ +Rebol [ + title: "Rosetta code: Box the compass" + file: %Box_the_compass.r3 + url: https://rosettacode.org/wiki/Box_the_compass + needs: 3.10.0 ;; or something like that +] + +form-angle: func[ + "Format the angle as a string with at least one decimal and pad to 2 decimals" + angle [decimal!] +][ + angle: form round/to angle 0.01 + pad/with find/last angle #"." 3 #"0" ;; ensure two digits after the decimal point + append angle #"°" ;; add the degree symbol +] + +compass: context [ + points: none + + make-points: function [/verbose][ + out: copy [] + ;; Define a character set for the four main directions + main-dir: charset "NESW" + ;; 32-wind compass notation (with quarter winds and by-points) + words: [ + N NbE NNE NEbN NE NEbE ENE EbN E EbS ESE SEbE SE SEbS SSE + SbE S SbW SSW SWbS SW SWbW WSW WbS W WbN WNW NWbW NW NWbN NNW NbW N + ] + ;; Replacement map from shorthand characters to full words (and spacing) + replacement: #[ + #"N" "north" + #"b" " by " + #"S" "south" + #"E" "east" + #"W" "west" + ] + i: 0 ;; index of the current compass point (0..32) + foreach word words [ + ;; Compute heading angle: + ;; Each step is 11.25°, with offsets of +5.62, 0.0, or -5.62 for the 1/3 sub-steps. + heading: i * 11.25 + (pickz [0.0 5.62 -5.62] i % 3) + ;; Start with the symbolic label (e.g., "NEbE") as a mutable string + text: to string! word + ;; Insert a hyphen after the first main direction if followed by two more main directions + ;; (e.g., "NEbE" -> "N-EbE") + parse text [1 main-dir ahead 2 main-dir insert "-"] + ;; Expand shorthand letters to full words using the replacement table: + ;; - Replace N/S/E/W with north/south/east/west + ;; - Replace 'b' with " by " + parse text [any [p: change skip (any [replacement/(p/1) p/1])]] + ;; Capitalize first letter of the expanded label (e.g., "north by east" -> "North by east") + uppercase/part text 1 + if verbose [ + ;; Print three columns: + ;; - Ordinal index within 32-wind cycle (1..32) + ;; - Formatted angle + ;; - Expanded textual compass point + print [ + pad (i % 32 + 1) -3 + pad form-angle heading -7 + pad form word 5 + text + ] + ] + repend out [heading word text] + ++ i + ] + new-line/skip out true 3 + out + ] + + nearest-text: function [ + "Returns the nearest compass point text for a given angle." + angle [number! integer! decimal!] + ][ + ;; :lazily build the points table if not already built + unless points [points: make-points] + ;; Normalize query angle into [0,360) + angle: angle % 360.0 + if angle < 0 [angle: angle + 360.0] + + best-diff: 1e9 + ;; Walk triples: angle word text + foreach [deg wrd txt] points [ + ;; Compute minimal circular difference + diff: abs deg - angle + if diff < best-diff [ + best-diff: diff + best: txt ;; remember the text for the closest heading + ] + ] + best + ] +] + +;; Print all angle texts +compass/make-points/verbose + +print "^/Resolve texts for random angles:" +random/seed 1 +loop 5 [ + angle: random 360.0 + print [ + pad form-angle angle -7 + compass/nearest-text angle + ] +] diff --git a/Task/Box-the-compass/V-(Vlang)/box-the-compass.v b/Task/Box-the-compass/V-(Vlang)/box-the-compass.v new file mode 100644 index 0000000000..fb5e231b0f --- /dev/null +++ b/Task/Box-the-compass/V-(Vlang)/box-the-compass.v @@ -0,0 +1,21 @@ +const names = ["North", "North by east", "North-northeast", + "Northeast by north", "Northeast", "Northeast by east", "East-northeast", + "East by north", "East", "East by south", "East-southeast", + "Southeast by east", "Southeast", "Southeast by south", "South-southeast", + "South by east", "South", "South by west", "South-southwest", + "Southwest by south", "Southwest", "Southwest by west", "West-southwest", + "West by south", "West", "West by north", "West-northwest", + "Northwest by west", "Northwest", "Northwest by north", "North-northwest", + "North by west", "North"] + +const degrees = [f32(0), 16.87, 16.88, 33.75, 50.62, 50.63, + 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135, 151.87, 151.88, 168.75, + 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270, + 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38] + +fn main() { + for idx, degree in degrees { + mut jdx := if idx >= 32 {idx - 31} else {idx + 1} + println("${jdx:2} ${names[jdx]:-18} ${degree:6.2f}") + } +} diff --git a/Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.adb b/Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.adb new file mode 100644 index 0000000000..3c23105aee --- /dev/null +++ b/Task/Boyer-Moore-string-search/Ada/boyer-moore-string-search.adb @@ -0,0 +1,63 @@ +with Ada.Text_IO; + +with GNATColl.Boyer_Moore; + +procedure Boyermoore is + + procedure Search_All (Needle : in String; + Haystack : in String) + is + use Ada.Text_IO; + use GNATColl.Boyer_Moore; + + Found : String (Haystack'Range) := (others => ' '); + Count : Natural := 0; + Motif : Pattern; + First : Positive := Haystack'First; + Position : Integer; + begin + Put_Line ("Needle : " & Needle); + Put_Line ("Haystack: " & Haystack); + Put ("Found : "); + + Compile (Motif => Motif, + From_String => Needle, + Case_Sensitive => True); + loop + Position := Search (Motif => Motif, + In_String => Haystack (First .. Haystack'Last)); + exit when Position = -1; + + Count := Count + 1; + Found (Position .. Position + Needle'Length - 1) := (others => '^'); + First := Position + 1; + end loop; + + Free (Motif); + + if Count = 0 then + Put_Line (""); + else + Put_Line (Found); + end if; + New_Line; + end Search_All; + + Text_1 : constant String := "InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented"; + + Text_2 : constant String := "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk."; + + Text_3 : constant String := "GCTAGCTCTACGAGTCTA"; + Text_4 : constant String := "GGCTATAATGCGTA"; + Text_5 : constant String := "there would have been a time for such a word"; + Text_6 : constant String := "needle need noodle needle"; + +begin + Search_All ("put", Text_1); + Search_All ("and", Text_1); + Search_All ("alfalfa", Text_2); + Search_All ("TCTA", Text_3); + Search_All ("TAATAAA", Text_4); + Search_All ("word", Text_5); + Search_All ("needle", Text_6); +end Boyermoore; diff --git a/Task/Boyer-Moore-string-search/Emacs-Lisp/boyer-moore-string-search.el b/Task/Boyer-Moore-string-search/Emacs-Lisp/boyer-moore-string-search.el new file mode 100644 index 0000000000..ae77ff3fd7 --- /dev/null +++ b/Task/Boyer-Moore-string-search/Emacs-Lisp/boyer-moore-string-search.el @@ -0,0 +1,81 @@ +(defun bm_compile_pattern (pattern) + "Compile the pattern to a right most position map" + (let ((patLen (length pattern)) + (rightMap (make-vector 256 -1)) + (j -1)) + (while (> patLen (setq j (1+ j))) + (aset rightMap (elt pattern j) j) ) + rightMap + ) + ) +;; +(defun bm_make_suffix_table (text) + (let ((suffix-table (make-vector (length text) -1)) (textLen (length text)) + (suffix-found nil) + ) + (cl-loop for pos from (1- textLen) downto 1 do + (setq suffix-found nil) + (cl-loop for ptn from (- textLen 2) downto 0 while (not suffix-found) do + (let ((start1 pos) (end1 (1- textLen)) + (start2 (- ptn (- (1- textLen) pos))) (end2 ptn) + (matched 't) + ) + (if (< start2 0) (setq start2 0)) + (cl-loop for idx1 from end1 downto start1 and idx2 from end2 downto start2 while matched do + (if (/= (elt text idx1) (elt text idx2)) + (setq matched nil)) + ) + (when matched + (aset suffix-table pos start2) + (setq suffix-found 't) ) + ) + ) + ) + suffix-table + ) + ) +;; +;; +(defun bm_substring_search (pattern text) + "Boyer-Moore string search" + (let ((patLen (length pattern)) + (txtLen (length text)) + (startPos 0) + (result nil) + (rightMap (bm_compile_pattern pattern)) + (suffixTable (bm_make_suffix_table pattern))) + ;; Continue this loop when no result and not exceed the text length + (while (and (not result) (<= (+ startPos patLen) txtLen)) + + (let ((idx patLen) + (suffixSkip 0) + (badCharSkip 0) + (skip 0)) + (while (and (= 0 skip) (<= 0 (setq idx (1- idx)))) + (setq suffixSkip 0) + (setq badCharSkip 0) + ;; skip when the character at position idx is different + (when (/= (elt pattern idx) (elt text (+ startPos idx))) + (when (< idx (1- (length pattern))) + (setq suffixSkip (aref suffixTable (1+ idx))) ) + (setq badCharSkip (- idx (aref rightMap (elt text (+ startPos idx))))) + ;; looking up the right most position in pattern + + (setq skip (max 1 badCharSkip suffixSkip)) + ) + ) + (if (< 0 skip) + (setq startPos (+ startPos skip)) + (setq result startPos) + ) + ) + ) + result + ) + ) +;; +(let ((pattern "alfalfa") + (full_text "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk.")) + (bm_substring_search pattern full_text) ) + +) diff --git a/Task/Boyer-Moore-string-search/R/boyer-moore-string-search.r b/Task/Boyer-Moore-string-search/R/boyer-moore-string-search.r new file mode 100644 index 0000000000..c9d0a568bc --- /dev/null +++ b/Task/Boyer-Moore-string-search/R/boyer-moore-string-search.r @@ -0,0 +1,344 @@ +# Helper function to convert string to character vector +str_to_vec <- function(s) { + strsplit(s, "")[[1]] +} + +# Use Z algorithm to preprocess s +z_array <- function(s) { + s_vec <- str_to_vec(s) + len <- length(s_vec) + stopifnot(len > 1) + + z <- c(len, integer(len - 1)) + + # Initial comparison of s[2:] with prefix + for (i in 1:(len - 1)) { + if (!is.na(s_vec[i + 1]) && !is.na(s_vec[i]) && s_vec[i + 1] == s_vec[i]) { + z[2] <- z[2] + 1 + } else { + break + } + } + + r <- 0 + l <- 0 + if (z[2] > 0) { + r <- z[2] + l <- 1 + } + + for (k in 2:(len - 1)) { + stopifnot(z[k + 1] == 0) + if (k > r) { + # Case 1 + for (i in k:(len - 1)) { + if (!is.na(s_vec[i + 1]) && !is.na(s_vec[i - k + 1]) && s_vec[i + 1] == s_vec[i - k + 1]) { + z[k + 1] <- z[k + 1] + 1 + } else { + break + } + } + r <- k + z[k + 1] - 1 + l <- k + } else { + # Case 2 + nbeta <- r - k + 1 + zkp <- z[k - l + 1] + if (nbeta > zkp) { + # Case 2a: Zkp wins + z[k + 1] <- zkp + } else { + # Case 2b: Compare characters just past r + nmatch <- 0 + for (i in (r + 1):(len - 1)) { + if (!is.na(s_vec[i + 1]) && !is.na(s_vec[i - k + 1]) && s_vec[i + 1] == s_vec[i - k + 1]) { + nmatch <- nmatch + 1 + } else { + break + } + } + l <- k + r <- r + nmatch + z[k + 1] <- r - k + 1 + } + } + } + return(z) +} + +# Compile the N array (Gusfield theorem 2.2.2) from the Z array +n_array <- function(s) { + s_vec <- str_to_vec(s) + rev_s <- paste(rev(s_vec), collapse = "") + return(rev(z_array(rev_s))) +} + +# Compile L' array (Gusfield theorem 2.2.2) using p and N array +big_l_prime_array <- function(p, n) { + len <- nchar(p) + lp <- integer(len) + for (j in 1:(len - 1)) { + i <- len - n[j] + if (i < len) { + lp[i + 1] <- j + 1 + } + } + return(lp) +} + +# Compile L array (Gusfield theorem 2.2.2) using p and L' array +big_l_array <- function(p, lp) { + l <- integer(nchar(p)) + l[2] <- lp[2] + if (length(l) >= 3) { + for (i in 3:length(l)) { + l[i] <- max(l[i - 1], lp[i]) + } + } + return(l) +} + +# Compile lp' array (Gusfield theorem 2.2.4) using N array +small_l_prime_array <- function(narray) { + len <- length(narray) + small_lp <- integer(len) + for (i in seq_along(narray)) { + if (narray[i] == i) { # prefix matching a suffix + small_lp[len - i + 1] <- i + } + } + for (i in (len - 1):1) { # "smear" them out to the left + if (small_lp[i] == 0) { + small_lp[i] <- small_lp[i + 1] + } + } + return(small_lp) +} + +# Return tables needed to apply good suffix rule +good_suffix_table <- function(p) { + n <- n_array(p) + lp <- big_l_prime_array(p, n) + list( + lp = lp, + big_l = big_l_array(p, lp), + small_l_prime = small_l_prime_array(n) + ) +} + +# Given a mismatch at offset i, return amount to shift per good suffix rule +good_suffix_mismatch <- function(i, big_l_prime, small_l_prime) { + len <- length(big_l_prime) + stopifnot(i < len) + if (i == len - 1) { + return(0) + } + i <- i + 1 # i points to leftmost matching position of P + if (big_l_prime[i] > 0) { + return(len - big_l_prime[i]) + } + return(len - small_l_prime[i]) +} + +# Given a full match of P to T, return amount to shift per good suffix rule +good_suffix_match <- function(small_l_prime) { + length(small_l_prime) - small_l_prime[2] +} + +# Create dense bad character table +dense_bad_char_tab <- function(p, amap) { + p_vec <- str_to_vec(p) + tab <- list() + nxt <- integer(length(amap)) + for (i in seq_along(p_vec)) { + c <- p_vec[i] + stopifnot(c %in% names(amap)) + tab[[i]] <- nxt + nxt[amap[[c]]] <- i + } + return(tab) +} + +# Boyer-Moore object (list) +BoyerMoore <- function(p, alphabet = "ACGT") { + # Create map from alphabet characters to integers + alphabet_vec <- str_to_vec(alphabet) + amap <- setNames(seq_along(alphabet_vec), alphabet_vec) + + # Make bad character rule table + bad_char <- dense_bad_char_tab(p, amap) + + # Create good suffix rule table + gs_table <- good_suffix_table(p) + + list( + pat = p, + alphabet = alphabet, + amap = amap, + bad_char = bad_char, + big_l = gs_table$big_l, + small_l_prime = gs_table$small_l_prime + ) +} + +# Return # skips given by bad character rule at offset i +bad_character_rule <- function(bm, i, c) { + stopifnot(c %in% names(bm$amap)) + ci <- bm$amap[[c]] + stopifnot(i > bm$bad_char[[i + 1]][ci] - 1) + return(i - (bm$bad_char[[i + 1]][ci] - 1)) +} + +# Given a mismatch at offset i, return amount to shift per good suffix rule +good_suffix_rule <- function(bm, i) { + len <- length(bm$big_l) + stopifnot(i < len) + if (i == len - 1) { + return(0) + } + i <- i + 1 # i points to leftmost matching position of P + if (bm$big_l[i + 1] > 0) { + return(len - bm$big_l[i + 1]) + } + return(len - bm$small_l_prime[i + 1]) +} + +# Return amount to shift when P matches T +match_skip <- function(bm) { + length(bm$small_l_prime) - bm$small_l_prime[2] +} + +# Do Boyer-Moore matching +boyer_moore <- function(p, p_bm, t) { + p_vec <- str_to_vec(p) + t_vec <- str_to_vec(t) + i <- 0 + occurrences <- integer(0) + + while (i < length(t_vec) - length(p_vec) + 1) { + shift <- 1 + mismatched <- FALSE + for (j in (length(p_vec) - 1):0) { + if (!is.na(p_vec[j + 1]) && !is.na(t_vec[i + j + 1]) && p_vec[j + 1] != t_vec[i + j + 1]) { + skip_bc <- bad_character_rule(p_bm, j, t_vec[i + j + 1]) + skip_gs <- good_suffix_rule(p_bm, j) + shift <- max(shift, skip_bc, skip_gs) + mismatched <- TRUE + break + } else if (is.na(p_vec[j + 1]) || is.na(t_vec[i + j + 1])) { + # Treat NA as mismatch + mismatched <- TRUE + shift <- 1 + break + } + } + if (!mismatched) { + occurrences <- c(occurrences, i) + skip_gs <- match_skip(p_bm) + shift <- max(shift, skip_gs) + } + i <- i + shift + } + return(occurrences) +} + +# Do Boyer-Moore matching with counts +boyer_moore_with_counts <- function(p, p_bm, t) { + p_vec <- str_to_vec(p) + t_vec <- str_to_vec(t) + i <- 0 + occurrences <- integer(0) + alignments_tried <- 0 + comparison_count <- 0 + + while (i < length(t_vec) - length(p_vec) + 1) { + alignments_tried <- alignments_tried + 1 + shift <- 1 + mismatched <- FALSE + for (j in (length(p_vec) - 1):0) { + comparison_count <- comparison_count + 1 + if (!is.na(p_vec[j + 1]) && !is.na(t_vec[i + j + 1]) && p_vec[j + 1] != t_vec[i + j + 1]) { + skip_bc <- bad_character_rule(p_bm, j, t_vec[i + j + 1]) + skip_gs <- good_suffix_rule(p_bm, j) + shift <- max(shift, skip_bc, skip_gs) + mismatched <- TRUE + break + } else if (is.na(p_vec[j + 1]) || is.na(t_vec[i + j + 1])) { + # Treat NA as mismatch + mismatched <- TRUE + shift <- 1 + break + } + } + if (!mismatched) { + occurrences <- c(occurrences, i) + skip_gs <- match_skip(p_bm) + shift <- max(shift, skip_gs) + } + i <- i + shift + } + return(list( + occurrences = occurrences, + alignments_tried = alignments_tried, + comparison_count = comparison_count + )) +} + +# Test cases +cat("Test 1:\n") +p1 <- "TCTA" +p_bm1 <- BoyerMoore(p1, "ACGT") +t1 <- "GCTAGCTCTACGAGTCTA" +cat("boyer_moore(p1, p_bm1, t1)=", boyer_moore(p1, p_bm1, t1), "\n") + +cat("\nTest 2:\n") +p2 <- "TAATAAA" +p_bm2 <- BoyerMoore(p2, "ACGT") +cat("bad_character_rule(p_bm2, 1, 'T')=", bad_character_rule(p_bm2, 1, 'T'), "\n") + +cat("\nTest 3:\n") +p3 <- "word" +t3 <- "there would have been a time for such a word" +lowercase_alphabet <- "abcdefghijklmnopqrstuvwxyz " +p_bm3 <- BoyerMoore(p3, lowercase_alphabet) +result3 <- boyer_moore_with_counts(p3, p_bm3, t3) +cat("Occurrences:", result3$occurrences, "\n") +cat("Alignments:", result3$alignments_tried, "\n") +cat("Comparisons:", result3$comparison_count, "\n") + +cat("\nTest 4:\n") +p4 <- "needle" +t4 <- "needle need noodle needle" +p_bm4 <- BoyerMoore(p4, lowercase_alphabet) +result4 <- boyer_moore_with_counts(p4, p_bm4, t4) +cat("Occurrences:", result4$occurrences, "\n") +cat("Alignments:", result4$alignments_tried, "\n") +cat("Comparisons:", result4$comparison_count, "\n") + +cat("\nTest 5:\n") +p5 <- "put" +t5 <- "InhisbookseriesTheArtofComputerProgrammingpublishedbyAddisonWesleyDKnuthusesanimaginarycomputertheMIXanditsassociatedmachinecodeandassemblylanguagestoillustratetheconceptsandalgorithmsastheyarepresented" +# Create ASCII chars string (characters 0-255) +ASCIIchars <- intToUtf8(0:255) +p_bm5 <- BoyerMoore(p5, ASCIIchars) +result5 <- boyer_moore_with_counts(p5, p_bm5, t5) +cat("Occurrences:", result5$occurrences, "\n") +cat("Alignments:", result5$alignments_tried, "\n") +cat("Comparisons:", result5$comparison_count, "\n") + +cat("\nTest 6:\n") +p6 <- "and" +p_bm6 <- BoyerMoore(p6, ASCIIchars) +result6 <- boyer_moore_with_counts(p6, p_bm6, t5) +cat("Occurrences:", result6$occurrences, "\n") +cat("Alignments:", result6$alignments_tried, "\n") +cat("Comparisons:", result6$comparison_count, "\n") + +cat("\nTest 7:\n") +p7 <- "alfalfa" +t7 <- "Nearby farms grew a half acre of alfalfa on the dairy's behalf, with bales of all that alfalfa exchanged for milk." +p_bm7 <- BoyerMoore(p7, ASCIIchars) +result7 <- boyer_moore_with_counts(p7, p_bm7, t7) +cat("Occurrences:", result7$occurrences, "\n") +cat("Alignments:", result7$alignments_tried, "\n") +cat("Comparisons:", result7$comparison_count, "\n") diff --git a/Task/Brace-expansion/Ada/brace-expansion.adb b/Task/Brace-expansion/Ada/brace-expansion.adb new file mode 100644 index 0000000000..93ddba1ca7 --- /dev/null +++ b/Task/Brace-expansion/Ada/brace-expansion.adb @@ -0,0 +1,58 @@ +pragma Ada_2022; +with Ada.Containers; use Ada.Containers; +with Ada.Containers.Vectors; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +procedure Brace_Expansion is + procedure Expand_Braces (Str : Unbounded_String) is + package Position_Vectors is new Ada.Containers.Vectors (Natural, Natural); + Escaped : Boolean := False; + Depth : Integer := 0; + Brace_Points : Position_Vectors.Vector; + Braces_To_Parse : Position_Vectors.Vector; + Prefix, Suffix, Option : Unbounded_String := Null_Unbounded_String; + begin + for Idx in 1 .. Length (Str) loop + case Element (Str, Idx) is + when '\' => Escaped := not Escaped; + when '{' => + Depth := Depth + 1; + if not Escaped and then Depth = 1 then + Brace_Points.Clear; + Brace_Points.Append (Idx); + end if; + when ',' => + if not Escaped and then Depth = 1 then + Brace_Points.Append (Idx); + end if; + when '}' => + if not Escaped and then Depth = 1 and then Brace_Points.Length > 1 then + Braces_To_Parse.Clear; + Braces_To_Parse.Append_Vector (Brace_Points); + Braces_To_Parse.Append (Idx); + end if; + Depth := Depth - 1; + when others => null; + end case; + if Element (Str, Idx) /= '\' then + Escaped := False; + end if; + end loop; + if Braces_To_Parse.Length > 0 then + Prefix := Unbounded_Slice (Str, 1, Braces_To_Parse (0) - 1); + Suffix := Unbounded_Slice (Str, Braces_To_Parse.Last_Element + 1, Length (Str)); + for Idx in 1 .. Braces_To_Parse.Length - 1 loop + Option := Unbounded_Slice (Str, Braces_To_Parse (Natural (Idx - 1)) + 1, Braces_To_Parse (Natural (Idx)) - 1); + Expand_Braces (Prefix & Option & Suffix); + end loop; + else + Put_Line (Str'Image); + end if; + end Expand_Braces; + function "+"(S : String) return Unbounded_String renames To_Unbounded_String; +begin + Expand_Braces (+"~/{Downloads,Pictures}/*.{jpg,gif,png}"); + Expand_Braces (+"It{{em,alic}iz,erat}e{d,}, please."); + Expand_Braces (+"{,{,gotta have{ ,\, again\, }}more }cowbell!"); + Expand_Braces (+"{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}"); +end Brace_Expansion; diff --git a/Task/Brace-expansion/PowerShell/brace-expansion-1.ps1 b/Task/Brace-expansion/PowerShell/brace-expansion-1.ps1 new file mode 100644 index 0000000000..33b93c1251 --- /dev/null +++ b/Task/Brace-expansion/PowerShell/brace-expansion-1.ps1 @@ -0,0 +1,55 @@ +function Expand-Braces ( [string]$String ) + { + $Escaped = $False + $Stack = New-Object System.Collections.Stack + $ClosedBraces = $BracesToParse = $Null + + ForEach ( $i in 0..($String.Length-1) ) + { + Switch ( $String[$i] ) + { + '\' { + $Escaped = -not $Escaped + break + } + + '{' { + If ( -not $Escaped ) { $Stack.Push( [pscustomobject]@{ Delimiters = @( $i ) } ) } + } + + ',' { + If ( -not $Escaped -and $Stack.Count ) { $Stack.Peek().Delimiters += $i } + } + + '}' { + If ( -not $Escaped -and $Stack.Count ) + { + $Stack.Peek().Delimiters += $i + $ClosedBraces = $Stack.Pop() + If ( $ClosedBraces.Delimiters.Count -gt 2 ) + { + $BracesToParse = $ClosedBraces + } + } + } + + default { $Escaped = $False } + } + } + + If ( $BracesToParse ) + { + $Start = $String.Substring( 0, $BracesToParse.Delimiters[0] ) + $End = $String.Substring( $BracesToParse.Delimiters[-1] + 1 ) + + ForEach ( $i in 0..($BracesToParse.Delimiters.Count-2) ) + { + $Option = $String.Substring( $BracesToParse.Delimiters[$i] + 1, $BracesToParse.Delimiters[$i+1] - $BracesToParse.Delimiters[$i] - 1 ) + Expand-Braces ( $Start + $Option + $End ) + } + } + Else + { + $String + } + } diff --git a/Task/Brace-expansion/PowerShell/brace-expansion-2.ps1 b/Task/Brace-expansion/PowerShell/brace-expansion-2.ps1 new file mode 100644 index 0000000000..a716b6c1be --- /dev/null +++ b/Task/Brace-expansion/PowerShell/brace-expansion-2.ps1 @@ -0,0 +1,14 @@ +$TestStrings = @( + 'It{{em,alic}iz,erat}e{d,}, please.' + '~/{Downloads,Pictures}/*.{jpg,gif,png}' + '{,{,gotta have{ ,\, again\, }}more }cowbell!' + '{}} some }{,{\\{ edge, edge} \,}{ cases, {here} \\\\\}' + ) + +ForEach ( $String in $TestStrings ) + { + '' + $String + '------' + Expand-Braces $String + } diff --git a/Task/Brazilian-numbers/Agena/brazilian-numbers.agena b/Task/Brazilian-numbers/Agena/brazilian-numbers.agena new file mode 100644 index 0000000000..cbef878108 --- /dev/null +++ b/Task/Brazilian-numbers/Agena/brazilian-numbers.agena @@ -0,0 +1,77 @@ +# Brazilian numbers + +proc same_digits(n :: number, b :: number) :: boolean is + # Result: true if n has same digits in the base b, false otherwise + ntmp := n; + f := ntmp symmod b; + ntmp \:= b; + while ntmp > 0 do + if ntmp symmod b <> f then return false fi; + ntmp \:= b + od; + return true; +end; + +proc is_brazilian(n :: number) :: boolean is + if n < 7 then return false + elif n symmod 2 = 0 and n >= 8 then return true + else + for b from 2 to n - 2 do + if same_digits(n, b) then return true fi + od; + return false + fi +end; + +proc is_prime(n :: number) :: boolean is + if n < 2 then return false + elif n symmod 2 = 0 then return (n = 2) + elif n symmod 3 = 0 then return (n = 3) + else + d := 5; + while d * d <= n do + if n symmod d = 0 then return false + else + d +:= 2; + if n symmod d = 0 then return false + else d +:= 4 + fi + fi + od; + return true + fi +end; + +scope + print("First 20 Brazilian numbers:"); + c := 0; + n := 7; + while c < 20 do + if is_brazilian(n) then + printf("%d ", n); + c +:= 1; + fi; + n +:= 1; + od; + printf("\n\nFirst 20 odd Brazilian numbers:\n"); + c := 0; + n := 7; + while c < 20 do + if is_brazilian(n) then + printf("%d ", n); + c +:= 1; + fi; + n +:= 2; + od; + printf("\n\nFirst 20 prime Brazilian numbers:\n"); + c := 0; + n := 7; + while c < 20 do + if is_brazilian(n) then + printf("%d ", n); + c +:= 1 + fi; + do n +:= 2 as not is_prime(n); + od; + printf("\n"); +epocs diff --git a/Task/Brazilian-numbers/Free-Pascal-Lazarus/brazilian-numbers.pas b/Task/Brazilian-numbers/Free-Pascal-Lazarus/brazilian-numbers.pas new file mode 100644 index 0000000000..865c31da74 --- /dev/null +++ b/Task/Brazilian-numbers/Free-Pascal-Lazarus/brazilian-numbers.pas @@ -0,0 +1,292 @@ +program brazilianNumbers; + +{$IFDEF FPC} + {$MODE DELPHI}{$OPTIMIZATION ON,All} + {$CODEALIGN proc=32,loop=4} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + SysUtils; + +const + //Must not be a prime + PrimeMarker = 0; + SquareMarker = PrimeMarker + 1; + //MAX = 110468;// 1E5 brazilian + //MAX = 1084566;// 1E6 brazilian + //MAX = 10708453;// 1E7 brazilian + //MAX = 106091516;// 1E8 brazilian + MAX = 1053421821;// 1E9 brazilian + +var + isprime: array of word; + + procedure MarkSmallestFactor; + //sieve of erathotenes + //but saving the smallest factor + var + i, j, lmt: NativeUint; + begin + lmt := High(isPrime); + fillWord(isPrime[0], lmt + 1, PrimeMarker); + //mark even numbers + i := 2; + j := i * i; + isPrime[j] := SquareMarker; + Inc(j, 2); + while j <= lmt do + begin + isPrime[j] := 2; + Inc(j, 2); + end; + //mark 3 but not 2 + i := 3; + j := i * i; + isPrime[j] := SquareMarker; + Inc(j, 6); + while j <= lmt do + begin + isPrime[j] := 3; + Inc(j, 6); + end; + + i := 5; + while i * i <= lmt do + begin + if isPrime[i] = 0 then + begin + j := lmt div i; + if not (odd(j)) then + Dec(j); + while j > i do + begin + if isPrime[j] = 0 then + isPrime[i * j] := i; + Dec(j, 2); + end; + //mark square prime + isPrime[i * i] := SquareMarker; + end; + Inc(i, 2); + end; + end; + + procedure OutFactors(n: NativeUint); + var + divisor, Next, rest: NativeUint; + pot: NativeUint; + begin + divisor := 2; + Next := 3; + rest := n; + Write(n: 10, ' = '); + while (rest <> 1) do + begin + if (rest mod divisor = 0) then + begin + Write(divisor); + pot := 0; + repeat + rest := rest div divisor; + Inc(pot) + until rest mod divisor <> 0; + if pot > 1 then + Write('^', pot); + if rest > 1 then + Write('*'); + end; + divisor := Next; + Next := Next + 2; + // cut condition: avoid many useless iterations + if (rest <> 1) and (rest < divisor * divisor) then + begin + Write(rest); + rest := 1; + end; + end; + Write(' ', #9#9#9); + end; + + procedure OutToBase(number, base: NativeUint); + var + BaseDgt: array[0..63] of NativeUint; + i, rest: NativeINt; + begin + OutFactors(number); + i := 0; + while number <> 0 do + begin + rest := number div base; + BaseDgt[i] := number - rest * base; + number := rest; + Inc(i); + end; + while i > 1 do + begin + Dec(i); + Write(BaseDgt[i]); + end; + writeln(BaseDgt[0], ' to base ', base); + end; + + function PrimeBase(number: NativeUint): NativeUint; + var + lnN: extended; + i, exponent, n: NativeUint; + begin + // primes are only brazilian if 111...11 to base > 2 + // the count of "1" must be odd , because brazilian primes are odd + lnN := ln(number); + exponent := 4; + //result := exponent.th root of number + Result := trunc(exp(lnN*0.25)); + while result >2 do + Begin + // calc sum(i= 0 to exponent ) base^i; + n := Result + 1; + i := 2; + repeat + Inc(i); + n := n*result + 1; + until i > exponent; + if n = number then + EXIT; + Inc(exponent,2); + Result := trunc(exp(lnN/exponent)); + end; + //not brazilian + Result := 0; + end; + + function GetPrimeBrazilianBase(number: NativeUint): NativeUint; + //result is base + begin + // prime of 2^n - 1 + if (Number and (number + 1)) = 0 then + Result := 2 + else + begin + Result := trunc(sqrt(number)); + //most of the brazilian primes are of this type base^2+base+1 + IF (sqr(result)+result+1) <> number then + result := PrimeBase(number); + end; + end; + + function GetBrazilianBase(number: NativeUInt): NativeUint; inline; + begin + Result := isPrime[number]; + if Result > SquareMarker then + Result := (number div Result) - 1 + else + begin + if Result = SquareMarker then + begin + if number = 121 then + Result := 3 + else + Result := 0; + end + else + Result := GetPrimeBrazilianBase(number); + end; + end; + + procedure First20Brazilian; + var + i, n, cnt: NativeUInt; + begin + writeln('first 20 brazilian numbers'); + i := 7; + cnt := 0; + while cnt < 20 do + begin + n := GetBrazilianBase(i); + if n <> 0 then + begin + Inc(cnt); + OutToBase(i, n); + end; + Inc(i); + end; + writeln; + end; + + procedure First33OddBrazilian; + var + i, n, cnt: NativeUInt; + begin + writeln('first 33 odd brazilian numbers'); + i := 7; + cnt := 0; + while cnt < 33 do + begin + n := GetBrazilianBase(i); + if N <> 0 then + begin + Inc(cnt); + OutToBase(i, n); + end; + Inc(i, 2); + end; + writeln; + end; + + procedure First20BrazilianPrimes; + var + i, n, cnt: NativeUInt; + begin + writeln('first 20 brazilian prime numbers'); + i := 7; + cnt := 0; + while cnt < 20 do + begin + IF isPrime[i] = PrimeMarker then + Begin + n := GetBrazilianBase(i); + if n <> 0 then + begin + Inc(cnt); + OutToBase(i, n); + end; + end; + Inc(i); + end; + writeln; + end; + +var + T1, T0: TDateTime; + i, n, cnt, lmt: NativeUInt; +begin + lmt := MAX; + setlength(isPrime, lmt + 1); + MarkSmallestFactor; + + First20Brazilian; + First33OddBrazilian; + First20BrazilianPrimes; + + Write('count brazilian numbers up to ', lmt, ' = '); + T0 := now; + i := 7; + cnt := 0; + n := 0; + + while (i <= lmt) do + begin + Inc(n, Ord(isPrime[i] = PrimeMarker)); + if GetBrazilianBase(i) <> 0 then + Inc(cnt); + Inc(i); + end; + + T1 := now; + + writeln(cnt); + writeln('Count of primes ', n: 11+13); + writeln((T1 - T0) * 86400 * 1000: 10: 0, ' ms'); + + setlength(isPrime, 0); +end. diff --git a/Task/Brazilian-numbers/JavaScript/brazilian-numbers.js b/Task/Brazilian-numbers/JavaScript/brazilian-numbers.js new file mode 100644 index 0000000000..582fed7a40 --- /dev/null +++ b/Task/Brazilian-numbers/JavaScript/brazilian-numbers.js @@ -0,0 +1,77 @@ +function sameDigits(n, b) { + let f = n % b; + while ((n = Math.floor(n / b)) > 0) { + if (n % b !== f) { + return false; + } + } + return true; +} + +function isBrazilian(n) { + if (n < 7) return false; + if (n % 2 === 0) return true; + for (let b = 2; b < n - 1; b++) { + if (sameDigits(n, b)) { + return true; + } + } + return false; +} + +function isPrime(n) { + if (n < 2) return false; + if (n % 2 === 0) return n === 2; + if (n % 3 === 0) return n === 3; + let d = 5; + while (d * d <= n) { + if (n % d === 0) return false; + d += 2; + if (n % d === 0) return false; + d += 4; + } + return true; +} + +function main() { + const kinds = ["", "odd ", "prime "]; + + for (const kind of kinds) { + let quiet = false; + const BigLim = 99999; + const limit = 20; + console.log(`First ${limit} ${kind}Brazilian numbers:`); + let c = 0; + let n = 7; + + while (c < BigLim) { + if (isBrazilian(n)) { + if (!quiet) process.stdout.write(n + ' '); + if (++c === limit) { + console.log("\n"); + quiet = true; + } + } + if (quiet && kind !== "") continue; + + if (kind === "") { + n++; + } else if (kind === "odd ") { + n += 2; + } else if (kind === "prime ") { + while (true) { + n += 2; + if (isPrime(n)) break; + } + } else { + throw new Error("Unexpected"); + } + } + + if (kind === "") { + console.log(`The ${BigLim + 1}th Brazilian number is: ${n}\n`); + } + } +} + +main(); diff --git a/Task/Brazilian-numbers/PHP/brazilian-numbers.php b/Task/Brazilian-numbers/PHP/brazilian-numbers.php new file mode 100644 index 0000000000..9f114562bc --- /dev/null +++ b/Task/Brazilian-numbers/PHP/brazilian-numbers.php @@ -0,0 +1,87 @@ + 0) { + if ($n_tmp % $b != $f) + return false; + $n_tmp = intdiv($n_tmp, $b); + } + return true; +} + +function is_brazilian(int $n): bool { + if ($n < 7) + return false; + else if ($n % 2 == 0 && $n >= 8) + return true; + else { + for ($b = 2; $b <= $n - 2; $b++) + if (same_digits($n, $b)) + return true; + return false; + } +} + +function is_prime(int $n): bool { + if ($n < 2) + return false; + else if ($n % 2 == 0) + return ($n == 2); + else if ($n % 3 == 0) + return ($n == 3); + else { + $d = 5; + while ($d * $d <= $n) { + if ($n % $d == 0) + return false; + else { + $d += 2; + if ($n % $d == 0) + return false; + else + $d += 4; + } + } + return true; + } +} + +echo 'First 20 Brazilian numbers:'.PHP_EOL; +$c = 0; +$n = 7; +while ($c < 20) { + if (is_brazilian($n)) { + echo $n.' '; + $c++; + } + $n++; +} +echo PHP_EOL.PHP_EOL.'First 20 odd Brazilian numbers:'.PHP_EOL; +$c = 0; +$n = 7; +while ($c < 20) { + if (is_brazilian($n)) { + echo $n.' '; + $c++; + } + $n += 2; +} +echo PHP_EOL.PHP_EOL.'First 20 prime Brazilian numbers:'.PHP_EOL; +$c = 0; +$n = 7; +while ($c < 20) { + if (is_brazilian($n)) { + echo $n.' '; + $c++; + } + do + $n += 2; + while (!is_prime($n)); +} +echo PHP_EOL; +?> diff --git a/Task/Brazilian-numbers/Pascal-P/brazilian-numbers.pas b/Task/Brazilian-numbers/Pascal-P/brazilian-numbers.pas new file mode 100644 index 0000000000..2eb7203fcc --- /dev/null +++ b/Task/Brazilian-numbers/Pascal-P/brazilian-numbers.pas @@ -0,0 +1,102 @@ +program brazilnums(output); +(* Brazilian numbers *) + +var + c, n: integer; + + function samedigits(n: integer; b: integer): boolean; + (* Result: true if n has same digits in the base b, false otherwise *) + var + f: integer; + sd: boolean; + begin + f := n mod b; n := n div b; + sd := true; + while sd and (n > 0) do + if n mod b <> f then sd := false + else n := n div b; + samedigits := sd + end; + + function isbrazilian(n: integer): boolean; + var + b, nm2: integer; + br: boolean; + begin + if n < 7 then isbrazilian := false + else if (n mod 2 = 0) and (n >= 8) then isbrazilian := true + else + begin + b := 2; nm2 := n - 2; + br := false; + while (not br) and (b <= nm2) do + if samedigits(n, b) then br := true + else b := b + 1; + isbrazilian := br + end; + end; + + function isprime(n: integer): boolean; + var + d: integer; + pr: boolean; + begin + if n < 2 then isprime := false + else if n mod 2 = 0 then isprime := n = 2 + else if n mod 3 = 0 then isprime := n = 3 + else + begin + d := 5; + pr := true; + while pr and (d * d <= n) do + if n mod d = 0 then pr := false + else + begin + d := d + 2; + if n mod d = 0 then pr := false + else d := d + 4; + end; + isprime := pr + end; + end; + +begin + writeln('First 20 Brazilian numbers:'); + c := 0; n := 7; + while c < 20 do + begin + if isbrazilian(n) then + begin + write(n:10 ); + c := c + 1; + end; + n := n + 1; + end; + writeln; writeln; + writeln('First 20 odd Brazilian numbers:'); + c := 0; n := 7; + while c < 20 do + begin + if isbrazilian(n) then + begin + write(n:10); + c := c + 1; + end; + n := n + 2; + end; + writeln; writeln; + writeln('First 20 prime Brazilian numbers:'); + c := 0; n := 7; + while c < 20 do + begin + if isbrazilian(n) then + begin + write(n:10); + c := c + 1; + end; + repeat + n := n + 2; + until isprime(n); + end; + writeln; +end. diff --git a/Task/Brazilian-numbers/Pluto/brazilian-numbers.pluto b/Task/Brazilian-numbers/Pluto/brazilian-numbers.pluto new file mode 100644 index 0000000000..cdc6b4ef7c --- /dev/null +++ b/Task/Brazilian-numbers/Pluto/brazilian-numbers.pluto @@ -0,0 +1,54 @@ +local int = require "int" + +local function same_digits(n, b) + local f = n % b + n //= b + while n > 0 do + if n % b != f then return false end + n //= b + end + return true +end + +local function is_brazilian(n) + if n < 7 then return false end + if n % 2 == 0 and n >= 8 then return true end + for b = 2, n - 2 do + if same_digits(n, b) then return true end + end + return false +end + +for {" ", " odd ", " prime "} as kind do + print($"First 20{kind}Brazilian numbers:") + local c = 0 + local n = 7 + while true do + if is_brazilian(n) then + io.write($"{n} ") + c += 1 + if c == 20 then + print("\n") + break + end + end + if kind == " " then + n += 1 + elseif kind == " odd " then + n += 2 + else + while true do + n += 2 + if int.isprime(n) then break end + end + end + end +end + +local c = 0 +local n = 7 +while c < 1e5 do + if is_brazilian(n) then c += 1 end + n += 1 +end +print($"The 100,000th Brazilian number: {n - 1}") diff --git a/Task/Brazilian-numbers/PowerShell/brazilian-numbers.ps1 b/Task/Brazilian-numbers/PowerShell/brazilian-numbers.ps1 new file mode 100644 index 0000000000..a3c6acbfa2 --- /dev/null +++ b/Task/Brazilian-numbers/PowerShell/brazilian-numbers.ps1 @@ -0,0 +1,96 @@ +# Brazilian numbers + +function Same-Digits($N, $B) { + # Result: $true if $N has same digits in the base $B, $false otherwise + $nl = $N + $f = $nl % $B + $nl = [math]::Floor($nl / $B) + while ($nl -gt 0) { + if (($nl % $B) -ne $f) { + return $false + } + $nl = [math]::Floor($nl / $B) + } + return $true +} + +function Is-Brazilian($N) { + if ($N -lt 7) { + return $false + } elseif (($N % 2 -eq 0) -and ($N -ge 8)) { + return $true + } else { + foreach ($b in 2..($N - 2)) { + if (Same-Digits $N $b) { + return $true + } + } + return $false + } +} + +function Is-Prime($N) { + if ($N -lt 2) { + return $false + } elseif (($N % 2) -eq 0) { + return ($N -eq 2) + } elseif ($N % 3 -eq 0) { + return ($N -eq 3) + } else { + $d = 5 + while ($d * $d -le $N) { + if (($N % $d) -eq 0) { + return $false + } else { + $d += 2 + if (($N % $d) -eq 0) { + return $false + } else { + $d += 4 + } + } + } # while + return $true + } +} + +Write-Output "First 20 Brazilian numbers:" +$c = 0 +$n = 7 +[string]$row = @() +while ($c -lt 20) { + if (Is-Brazilian $n) { + $row += "$n " + $c++ + } + $n++ +} +Write-Output $row +Write-Output "" +Write-Output "First 20 odd Brazilian numbers:" +$c = 0 +$n = 7 +[string]$row = @() +while ($c -lt 20) { + if (Is-Brazilian $n) { + $row += "$n " + $c++ + } + $n += 2 +} +Write-Output $row +Write-Output "" +Write-Output "First 20 prime Brazilian numbers:" +$c = 0 +$n = 7 +[string]$row = @() +while ($c -lt 20) { + if (Is-Brazilian $n) { + $row += "$n " + $c++ + } + do { + $n += 2 + } while (-not (Is-Prime $n)) +} +Write-Output $row diff --git a/Task/Brazilian-numbers/QuickBASIC/brazilian-numbers.basic b/Task/Brazilian-numbers/QuickBASIC/brazilian-numbers.basic new file mode 100644 index 0000000000..8aa0b81f1a --- /dev/null +++ b/Task/Brazilian-numbers/QuickBASIC/brazilian-numbers.basic @@ -0,0 +1,98 @@ +' Brazilian numbers + +DECLARE FUNCTION IsBrazilian% (N%) +DECLARE FUNCTION SameDigits% (BYVAL N%, B%) +DECLARE FUNCTION IsPrime% (N%) +CONST TRUE% = -1, FALSE% = 0 +PRINT "First 20 Brazilian numbers:" +C% = 0: N% = 7 +DO WHILE C% < 20 + IF IsBrazilian%(N%) THEN + PRINT N%; + C% = C% + 1 + END IF + N% = N% + 1 +LOOP +PRINT +PRINT +PRINT "First 20 odd Brazilian numbers:" +C% = 0: N% = 7 +DO WHILE C% < 20 + IF IsBrazilian%(N%) THEN + PRINT N%; + C% = C% + 1 + END IF + N% = N% + 2 +LOOP +PRINT +PRINT +PRINT "First 20 prime Brazilian numbers:" +C% = 0: N% = 7 +DO WHILE C% < 20 + IF IsBrazilian%(N%) THEN + PRINT N%; + C% = C% + 1 + END IF + DO + N% = N% + 2 + LOOP UNTIL IsPrime%(N%) +LOOP +PRINT +END + +FUNCTION IsBrazilian% (N%) + IF N% < 7 THEN + IsBrazilian% = FALSE% + ELSEIF (N% MOD 2 = 0) AND (N% >= 8) THEN + IsBrazilian% = TRUE% + ELSE + FOR B% = 2 TO N% - 2 + IF SameDigits%(N%, B%) THEN + IsBrazilian% = TRUE% + EXIT FUNCTION + END IF + NEXT B% + IsBrazilian% = FALSE% + END IF +END FUNCTION + +FUNCTION IsPrime% (N%) + IF N% < 2 THEN + IsPrime% = FALSE% + ELSEIF N% MOD 2 = 0 THEN + IsPrime% = (N% = 2) + ELSEIF N% MOD 3 = 0 THEN + IsPrime% = (N% = 3) + ELSE + D& = 5 + DO WHILE D& * D& <= N% + IF N% MOD D& = 0 THEN + IsPrime% = FALSE% + EXIT FUNCTION + ELSE + D& = D& + 2 + IF N% MOD D& = 0 THEN + IsPrime% = FALSE% + EXIT FUNCTION + ELSE + D& = D& + 4 + END IF + END IF + LOOP + IsPrime% = TRUE% + END IF +END FUNCTION + +FUNCTION SameDigits% (BYVAL N%, B%) + ' Result: TRUE% if N has same digits in the base B%, FALSE% otherwise + F = N% MOD B% + N% = N% \ B% + DO WHILE N% > 0 + IF N% MOD B% <> F THEN + SameDigits% = FALSE% + EXIT FUNCTION + END IF + N% = N% \ B% + LOOP + SameDigits% = TRUE% +END FUNCTION diff --git a/Task/Brazilian-numbers/R/brazilian-numbers.r b/Task/Brazilian-numbers/R/brazilian-numbers.r new file mode 100644 index 0000000000..0c8783159c --- /dev/null +++ b/Task/Brazilian-numbers/R/brazilian-numbers.r @@ -0,0 +1,91 @@ +# Brazilian numbers + +SameDigits <- function(n, b) { + # Result: TRUE if n has same digits in the base b, FALSE otherwise + nl <- n + f <- nl %% b + nl <- nl %/% b + while (nl > 0) { + if (nl %% b != f) + return(FALSE) + nl <- nl %/% b + } + return(TRUE) +} + +IsBrazilian <- function(n) { + if (n < 7) + return(FALSE) + else if (n %% 2 == 0 && n >= 8) + return(TRUE) + else { + for (b in 2:(n - 2)) + if (SameDigits(n, b)) + return(TRUE) + return(FALSE) + } +} + +IsPrime <- function(n) { + if (n < 2) + return(FALSE) + else if (n %% 2 == 0) + return(n == 2) + else if (n %% 3 == 0) + return(n == 3) + else { + d <- 5 + while (d * d <= n) { + if (n %% d == 0) + return(FALSE) + else { + d <- d + 2 + if (n %% d == 0) + return(FALSE) + else + d <- d + 4 + } + } # while + return(TRUE) + } +} + +print("First 20 Brazilian numbers:") +c <- 0 +n <- 7 +result.list <- c() +while (c < 20) { + if (IsBrazilian(n)) { + result.list <- append(result.list, n) + c <- c + 1 + } + n <- n + 1 +} +result.list +print("First 20 odd Brazilian numbers:") +c <- 0 +n <- 7 +result.list <- c() +while (c < 20) { + if (IsBrazilian(n)) { + result.list <- append(result.list, n) + c <- c + 1 + } + n <- n + 2 +} +result.list +print("First 20 prime Brazilian numbers:") +c <- 0 +n <- 7 +result.list <- c() +while (c < 20) { + if (IsBrazilian(n)) { + result.list <- append(result.list, n) + c <- c + 1 + } + repeat { + n <- n + 2 + if (IsPrime(n)) break + } +} +result.list diff --git a/Task/Brazilian-numbers/VBA/brazilian-numbers.vba b/Task/Brazilian-numbers/VBA/brazilian-numbers.vba new file mode 100644 index 0000000000..058f55fa47 --- /dev/null +++ b/Task/Brazilian-numbers/VBA/brazilian-numbers.vba @@ -0,0 +1,103 @@ +' Brazilian numbers + +Sub BrazilNumsMain() + Dim C, N As Long + Debug.Print "First 20 Brazilian numbers:" + C = 0 + N = 7 + Do While C < 20 + If IsBrazilian(N) Then + Debug.Print N; + C = C + 1 + End If + N = N + 1 + Loop + Debug.Print + Debug.Print + Debug.Print "First 20 odd Brazilian numbers:" + C = 0 + N = 7 + Do While C < 20 + If IsBrazilian(N) Then + Debug.Print N; + C = C + 1 + End If + N = N + 2 + Loop + Debug.Print + Debug.Print + Debug.Print "First 20 prime Brazilian numbers:" + C = 0 + N = 7 + Do While C < 20 + If IsBrazilian(N) Then + Debug.Print N; + C = C + 1 + End If + Do + N = N + 2 + Loop While Not IsPrime(N) + Loop + Debug.Print +End Sub + +Function IsBrazilian(N As Long) As Boolean + Dim B As Long + If N < 7 Then + IsBrazilian = False + ElseIf (N Mod 2 = 0) And (N >= 8) Then + IsBrazilian = True + Else + For B = 2 To N - 2 + If SameDigits(N, B) Then + IsBrazilian = True + Exit Function + End If + Next B + IsBrazilian = False + End If +End Function + +Function SameDigits(N As Long, B As Long) As Boolean + ' Result: True if N has same digits in the base B, False otherwise + Dim NL, F As Long + NL = N ' Local N + F = NL Mod B + NL = NL \ B + Do While NL > 0 + If NL Mod B <> F Then + SameDigits = False + Exit Function + End If + NL = NL \ B + Loop + SameDigits = True +End Function + +Function IsPrime(N As Long) As Boolean + Dim D As Long + If N < 2 Then + IsPrime = False + ElseIf N Mod 2 = 0 Then + IsPrime = (N = 2) + ElseIf N Mod 3 = 0 Then + IsPrime = (N = 3) + Else + D = 5 + Do While D * D <= N + If N Mod D = 0 Then + IsPrime = False + Exit Function + Else + D = D + 2 + If N Mod D = 0 Then + IsPrime = False + Exit Function + Else + D = D + 4 + End If + End If + Loop + IsPrime = True + End If +End Function diff --git a/Task/Break-OO-privacy/Ada/break-oo-privacy-1.adb b/Task/Break-OO-privacy/Ada/break-oo-privacy-1.adb new file mode 100644 index 0000000000..996fc9276b --- /dev/null +++ b/Task/Break-OO-privacy/Ada/break-oo-privacy-1.adb @@ -0,0 +1,10 @@ +package OO_Privacy is + + type Confidential_Stuff is tagged private; + subtype Password_Type is String(1 .. 8); + +private + type Confidential_Stuff is tagged record + Password: Password_Type := "default!"; -- the "secret" + end record; +end OO_Privacy; diff --git a/Task/Break-OO-privacy/Ada/break-oo-privacy-2.adb b/Task/Break-OO-privacy/Ada/break-oo-privacy-2.adb new file mode 100644 index 0000000000..216ce7c3e8 --- /dev/null +++ b/Task/Break-OO-privacy/Ada/break-oo-privacy-2.adb @@ -0,0 +1,16 @@ +with OO_Privacy, Ada.Unchecked_Conversion, Ada.Text_IO; + +procedure OO_Break_Privacy is + + type Hacker_Stuff is tagged record + Password: OO_Privacy.Password_Type := "?unknown"; + end record; + + function Hack is new Ada.Unchecked_Conversion + (Source => OO_Privacy.Confidential_Stuff, Target => Hacker_Stuff); + + C: OO_Privacy.Confidential_Stuff; -- which password is hidden inside C? + +begin + Ada.Text_IO.Put_Line("The secret password is """ & Hack(C).Password & """"); +end OO_Break_Privacy; diff --git a/Task/Break-OO-privacy/Ada/break-oo-privacy-3.adb b/Task/Break-OO-privacy/Ada/break-oo-privacy-3.adb new file mode 100644 index 0000000000..754a95a401 --- /dev/null +++ b/Task/Break-OO-privacy/Ada/break-oo-privacy-3.adb @@ -0,0 +1,5 @@ +package OO_Privacy.Friend is -- child package of OO.Privacy + + function Get_Password(Secret: Confidential_Stuff) return String; + +end OO_Privacy.Friend; diff --git a/Task/Break-OO-privacy/Ada/break-oo-privacy-4.adb b/Task/Break-OO-privacy/Ada/break-oo-privacy-4.adb new file mode 100644 index 0000000000..c97a1b152d --- /dev/null +++ b/Task/Break-OO-privacy/Ada/break-oo-privacy-4.adb @@ -0,0 +1,6 @@ +package body OO_Privacy.Friend is -- implementation of the child package + + function Get_Password(Secret: Confidential_Stuff) return String is + (Secret.Password); + +end OO_Privacy.Friend; diff --git a/Task/Break-OO-privacy/Ada/break-oo-privacy-5.adb b/Task/Break-OO-privacy/Ada/break-oo-privacy-5.adb new file mode 100644 index 0000000000..893f52f8c2 --- /dev/null +++ b/Task/Break-OO-privacy/Ada/break-oo-privacy-5.adb @@ -0,0 +1,11 @@ +with OO_Privacy.Friend, Ada.Text_IO; + +procedure Bypass_OO_Privacy is + + C: OO_Privacy.Confidential_Stuff; -- which password is hidden inside C? + +begin + Ada.Text_IO.Put_Line("Password: """ & + OO_Privacy.Friend.Get_Password(C) & + """"); +end Bypass_OO_Privacy; diff --git a/Task/Break-OO-privacy/Pluto/break-oo-privacy.pluto b/Task/Break-OO-privacy/Pluto/break-oo-privacy.pluto new file mode 100644 index 0000000000..0c3849d7d9 --- /dev/null +++ b/Task/Break-OO-privacy/Pluto/break-oo-privacy.pluto @@ -0,0 +1,19 @@ +class safe + function __construct(private secret1, protected secret2) + end +end + +local s = new safe(42, 43) + +-- Attempt to access secrets directly +print($"secret1 = {s.secret1}") +print($"secret2 = {s.secret2}") + +print("\nor using more devious means:\n") + +for k, v in s do + if k:startswith("__restricted__") then + local name = k:replace("__restricted__", "") + print($"{name} = {v}") + end +end diff --git a/Task/Brilliant-numbers/AWK/brilliant-numbers.awk b/Task/Brilliant-numbers/AWK/brilliant-numbers.awk new file mode 100644 index 0000000000..8024b121c1 --- /dev/null +++ b/Task/Brilliant-numbers/AWK/brilliant-numbers.awk @@ -0,0 +1,51 @@ +# syntax: GAWK -f BRILLIANT_NUMBERS.AWK +# converted from FreeBASIC +BEGIN { + n = 0 + while (count < 100) { + ff = first_prime_factor(n) + sf = n / ff + if (is_prime(sf) && length(ff) == length(sf)) { + printf("%5d",n) + if (++count % 10 == 0) { printf("\n") } + } + n++ + } + printf("\n") + count = expo = n = 0 + while (expo < 7) { + ff = first_prime_factor(n) + sf = n / ff + if (is_prime(sf) && length(ff) == length(sf)) { + count++ + if (n > 10^expo) { + printf("%8d is brilliant # %d\n",n,count) + expo++ + } + } + n++ + } + exit(0) +} +function first_prime_factor(n, i) { + if (n % 2 == 0) { + return(2) + } + for (i=3; i<=sqrt(n); i+=2) { + if (n % i == 0) { + return(i) + } + } + return(n) +} +function is_prime(x, i) { + if (x <= 1) { + return(0) + } + for (i=2; i<=int(sqrt(x)); i++) { + if (x % i == 0) { + return(0) + } + } + return(1) +} diff --git a/Task/Brilliant-numbers/Ada/brilliant-numbers.adb b/Task/Brilliant-numbers/Ada/brilliant-numbers.adb new file mode 100644 index 0000000000..a880cca413 --- /dev/null +++ b/Task/Brilliant-numbers/Ada/brilliant-numbers.adb @@ -0,0 +1,56 @@ +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Brilliant_Numbers is + subtype Prime_Numbers is Positive range 2 .. 10_000_000 with + Dynamic_Predicate => (for all I in 2 .. (Prime_Numbers / 2) + => (Prime_Numbers mod I) /= 0); + + Count, N, FPF, SF, Expo : Integer := 0; + + function First_Prime_Factor (N : Integer) return Integer is + I : Integer := 3; + begin + if N mod 2 = 0 then + return 2; + end if; + while I < Integer (Sqrt (Float (N)) + 1.0) loop + if N mod I = 0 then + return I; + end if; + I := I + 2; + end loop; + return N; + end First_Prime_Factor; + +begin + while Count < 100 loop + FPF := First_Prime_Factor (N); + SF := N / FPF; + if SF in Prime_Numbers and then FPF'Image'Length = SF'Image'Length then + Put (N'Image); + Count := Count + 1; + if Count mod 6 = 0 then + New_Line; + end if; + end if; + N := N + 1; + end loop; + + Count := 0; + N := 0; + loop + FPF := First_Prime_Factor (N); + SF := N / FPF; + if SF in Prime_Numbers and then FPF'Image'Length = SF'Image'Length then + Count := Count + 1; + if N > 10 ** Expo then + Put_Line (N'Image & " is brilliant number:" & Count'Image); + Expo := Expo + 1; + exit when Expo = 7; + end if; + end if; + N := N + 1; + end loop; + +end Brilliant_Numbers; diff --git a/Task/Brilliant-numbers/Fortran/brilliant-numbers.f b/Task/Brilliant-numbers/Fortran/brilliant-numbers.f new file mode 100644 index 0000000000..843246f327 --- /dev/null +++ b/Task/Brilliant-numbers/Fortran/brilliant-numbers.f @@ -0,0 +1,161 @@ +Brilliant numbers +! +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! Can be compiled on VSI Fortran x86-64 but it does not run on OpenVMS +! without modifying process quotas to allow abundant memory allocation +! +! U.B., March 2026 +! +program Brilliant +implicit none + +integer, allocatable :: primes(:) +integer :: primeCount +integer, parameter :: maxBrill=1010000000 ! Looking for the first B.N >= 1 000 000 000 +integer, parameter :: maxBrillToPrint=100 +integer(kind=1), dimension(maxBrill) :: brill ! indicates for each number up to the Maximum if it is brilliant + +! Looking for the first "brilliant number" .gt. 1 000 000 000, i.e. the product of 2 primes +! not much larger than 1 000 000, it is sufficient to generate primes up to 200000 +integer, parameter :: primeLimit= 200000 + +integer :: brilliantCount, magnitude +integer(kind=8) :: brilliantNum +integer :: ii, jj, maxprimj + +primeCount = initPrimes (primelimit) +brill = 0 + +! Find and display the first 100 brilliant numbers. +! The first entry is known: +brilliantCount = 0 + +! First construct all brilliant numbers from the preset primes. +outmost: do ii=1, primeCount + jj = ii + maxprimj = magMax (primes(ii)) + do while (jj .le. primecount .and. primes(jj) .le. maxprimj) + ! Beware of overflow. Use 8 byte integer arithmetic to calculate brilliant numbers + ! + brilliantNum =int(primes(ii),8)*int(primes(jj),8) + brilliantCount = brilliantCount + 1 + if (brilliantNum .gt. 0 .and. BrilliantNum .le. maxBrill) then + brill (brilliantNum) = 1 + endif + jj = jj + 1 + end do +end do outmost + +! Now print the first 100 numbers, in 10 lines +brilliantCount = 0 +ii = 1 +do while (brilliantCount .lt. maxBrillToPrint) + if (brill(ii) .ne. 0) then + brilliantCount = brilliantCount + 1 + write (*, '(i4, x)', advance='no') ii + if (mod (brilliantCount , 10) .eq. 0) write (*,*) ! after 10 numbers, newline + end if + ii = ii + 1 +end do + +write (*,*) +jj=0 + +! For the orders of magnitude 1 through 9, find and show the first brilliant +! number greater than or equal to the order of magnitude, and, its position +! in the series (or the count of brilliant numbers up to that point). + + ii = 1 + maxprimj = 1 ! Set the limit to exceed + brilliantCount = 0 + do ii=1, maxBrill ! go through the Brill array + if (brill(ii).ne. 0) then ! is this a brilliant number? + brilliantCount = brilliantCount + 1 ! yes, count it + if (ii .ge. maxprimj) then ! Does it exceed the given limit? If so, print it + write (*, '("First Brilliant Number .ge.", i10, " is ", i10, " at position ", i0 )') maxprimj, ii, brilliantCount + maxprimj = 10*maxprimj ! next limit is 10 times larger + endif + endif + end do + +contains + +! ============================================================= +! return the largest number in the same order of magnitude as n +! ============================================================= +function magMax (n) result (m) +integer, intent(in) :: n +integer :: m + +! prepare for max 100 000 000 +if (n .ge. 100000000) then + m = 999999999 +else if (n .ge. 10000000) then + m = 99999999 +else if (n .ge. 1000000) then + m = 9999999 +else if (n .ge. 100000) then + m = 999999 +else if (n .ge. 10000) then + m = 99999 +else if (n .ge. 1000) then + m = 9999 +else if (n .ge. 100) then + m = 999 +else if (n .ge. 10) then + m = 99 +else + m = 9 +endif + +end function magMax + +! ============================== +! The well-nown sieve for primes +! ============================== +function initPrimes (limit) result (count) + +integer, intent(in) :: limit +! The array for the primes is located in main program +logical(kind=1), allocatable :: isPrime(:) + +integer count +integer :: i, j,k + +allocate(isPrime(limit)) +if (.not. allocated (isPrime)) then + print *, 'Cannot allocate enough memory for primes up to ', limit + stop +end if + +isPrime = .true. +primeCount = 0 +do i = 2, limit + if (isPrime(i)) then ! Have a new prime + primeCount = primeCount + 1 + do j = i+i, limit, i ! Multiples of this prime aren't prime. + isPrime(j) = .false. + end do + end if +end do +count = primecount +allocate (primes(primeCount)) +if (.not. allocated (isPrime)) then + print *, 'Cannot allocate enough memory for ', primeCount, ' primes.' + stop +end if + +j = 1 +do i = 2, limit + if (isPrime(i)) then + primes(j) = i + j = j + 1 + k=i + end if +end do +deallocate (isPrime) +end function initPrimes + + +end program Brilliant diff --git a/Task/Brilliant-numbers/Icon/brilliant-numbers.icon b/Task/Brilliant-numbers/Icon/brilliant-numbers.icon new file mode 100644 index 0000000000..80eb312004 --- /dev/null +++ b/Task/Brilliant-numbers/Icon/brilliant-numbers.icon @@ -0,0 +1,21 @@ +link factors + +procedure main(A) + limit := \A[1] | 100 + every writes(" ",brilliant()\limit) + write("\n") + every write(brillianth(10^(1 to 6))) +end + +procedure brilliant() + suspend (*(f := factors(i := seq())) = 2, *f[1] = *f[2], i) +end + +procedure brillianth(e) + static ln, j + initial ln := j := 0 + + every (*(f := factors(i := seq(j+1))) = 2,*f[1] = *f[2],j := i,ln +:= 1) do { + if i >= e then return i||" is >= "||e||" and is brilliant number: "||ln + } +end diff --git a/Task/Brilliant-numbers/JavaScript/brilliant-numbers.js b/Task/Brilliant-numbers/JavaScript/brilliant-numbers.js new file mode 100644 index 0000000000..edc03f92c6 --- /dev/null +++ b/Task/Brilliant-numbers/JavaScript/brilliant-numbers.js @@ -0,0 +1,144 @@ +class PrimeGenerator { + constructor(limit, segmentSize) { + this.limit = limit; + this.segmentSize = segmentSize; + this.primes = this.sieve(limit); + this.currentIndex = 0; + } + + sieve(limit) { + if (limit < 2) return []; + + const isPrime = new Array(limit + 1).fill(true); + isPrime[0] = isPrime[1] = false; + + for (let i = 2; i * i <= limit; i++) { + if (isPrime[i]) { + for (let j = i * i; j <= limit; j += i) { + isPrime[j] = false; + } + } + } + + const primes = []; + for (let i = 2; i <= limit; i++) { + if (isPrime[i]) primes.push(i); + } + return primes; + } + + nextPrime() { + if (this.currentIndex < this.primes.length) { + return this.primes[this.currentIndex++]; + } + return -1; + } +} + +function getPrimesByDigits(limit) { + const primeGen = new PrimeGenerator(100000, 100000); + const primesByDigits = []; + let primes = []; + let p = 10; + + while (p <= limit) { + const prime = primeGen.nextPrime(); + if (prime === -1) break; + + if (prime > p) { + primesByDigits.push([...primes]); + primes = []; + p *= 10; + } + primes.push(prime); + } + + if (primes.length > 0) { + primesByDigits.push(primes); + } + + return primesByDigits; +} + +function binarySearch(arr, target) { + let left = 0; + let right = arr.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (arr[mid] === target) return mid; + if (arr[mid] < target) left = mid + 1; + else right = mid - 1; + } + + return -left - 1; +} + +function main() { + const primesByDigits = getPrimesByDigits(100000000); + console.log("First 100 brilliant numbers:"); + + let brilliantNumbers = []; + for (const primes of primesByDigits) { + const n = primes.length; + for (let i = 0; i < n; i++) { + const prime1 = primes[i]; + for (let j = i; j < n; j++) { + const prime2 = primes[j]; + brilliantNumbers.push(prime1 * prime2); + } + } + if (brilliantNumbers.length >= 100) break; + } + + brilliantNumbers.sort((a, b) => a - b); + brilliantNumbers = brilliantNumbers.slice(0, 100); + + let output = ""; + for (let i = 0; i < 100; i++) { + const c = (i + 1) % 10 === 0 ? '\n' : ' '; + output += brilliantNumbers[i].toLocaleString().padStart(5) + c; + } + console.log(output); + console.log(); + + let power = 10; + let count = 0; + + for (let p = 1; p < 2 * primesByDigits.length; p++) { + const primes = primesByDigits[Math.floor(p / 2)]; + let position = count + 1; + let minProduct = 0; + const n = primes.length; + + for (let i = 0; i < n; i++) { + const prime1 = primes[i]; + const primes2 = primes.slice(i); + const q = Math.ceil(power / prime1); + let j = binarySearch(primes2, q); + + if (j < 0) j = -j - 1; + if (j >= primes2.length) continue; + + const prime2 = primes2[j]; + const product = prime1 * prime2; + + if (minProduct === 0 || product < minProduct) { + minProduct = product; + } + + position += j; + if (prime1 >= prime2) break; + } + + console.log(`First brilliant number >= 10^${p} is ${minProduct.toLocaleString()} at position ${position.toLocaleString()}`); + power *= 10; + + if (p % 2 === 1) { + const size = primes.length; + count += size * (size + 1) / 2; + } + } +} + +main(); diff --git a/Task/Brilliant-numbers/Oberon-07/brilliant-numbers.oberon b/Task/Brilliant-numbers/Oberon-07/brilliant-numbers.oberon new file mode 100644 index 0000000000..a2281f762a --- /dev/null +++ b/Task/Brilliant-numbers/Oberon-07/brilliant-numbers.oberon @@ -0,0 +1,80 @@ +MODULE BrilliantNumbers; (* Find Brilliant numbers - semi-primes whose two *) + (* prime factors have the same number of digits *) + + IMPORT Primes, Out; + + CONST maxPrime = 1010; (* maximum prime we will consider, should be *) + (* enough to find the first brilliant number > 10^6 *) + maxBrilliant = maxPrime * maxPrime; + + VAR primeSieve : ARRAY maxPrime + 1 OF BOOLEAN; + brilliant : ARRAY maxBrilliant + 1 OF BOOLEAN; + + + (* construct a table of brilliant numbers *) + (* LEN( bn ) must be at least 15 and LEN( ps ) squared *) + PROCEDURE findBrilliant( VAR bn : ARRAY OF BOOLEAN; prime : ARRAY OF BOOLEAN ); + VAR n, maxB, maxP, p, q, pStart, pEnd : INTEGER; + BEGIN + maxB := LEN( bn ) - 1; + maxP := LEN( prime ) - 1; + FOR n := 0 TO maxB DO brilliant[ n ] := FALSE END; + (* brilliant numbers where one of the fators is 2 *) + bn[ 4 ] := TRUE; + FOR p := 3 TO 7 BY 2 DO brilliant[ 2 * p ] := TRUE END; + (* brilliant numbers where both factors are odd *) + pStart := 1; pEnd := 9; + WHILE pStart < maxP DO + FOR p := pStart TO pEnd BY 2 DO + IF prime[ p ] THEN + bn[ p * p ] := TRUE; + FOR q := p + 2 TO pEnd BY 2 DO + IF prime[ q ] THEN + bn[ p * q ] := TRUE + END + END + END + END; + pStart := pEnd + 2; + pEnd := ( ( pStart - 1 ) * 10 ) - 1; + IF pEnd > maxP THEN pEnd := maxP END + END + END findBrilliant ; + + PROCEDURE showBrilliant; + VAR bCount, n, p10 : INTEGER; + BEGIN + (* show the first 100 brilliant numbers *) + bCount := 0; + n := 0; + WHILE bCount < 100 DO + INC( n ); + IF brilliant[ n ] THEN + Out.Int( n, 6 ); + INC( bCount ); + IF bCount MOD 10 = 0 THEN Out.Ln END + END + END; + (* first brilliant number >= 10^n, n = 1, 2, ..., 6 *) + bCount := 0; + p10 := 10; + FOR n := 1 TO maxBrilliant DO + IF brilliant[ n ] THEN + INC( bCount ); + IF n >= p10 THEN + Out.String( "First brilliant number >= " );Out.Int( p10, 8 ); + Out.String( ": " );Out.Int( n, 8 ); + Out.String( " at position " );Out.Int( bCount, 6 ); + Out.Ln; + p10 := p10 * 10 + END + END + END + END showBrilliant ; + +BEGIN + Primes.sieve( primeSieve ); + findBrilliant( brilliant, primeSieve ); + showBrilliant + +END BrilliantNumbers. diff --git a/Task/Brilliant-numbers/Pluto/brilliant-numbers.pluto b/Task/Brilliant-numbers/Pluto/brilliant-numbers.pluto new file mode 100644 index 0000000000..a5243ca182 --- /dev/null +++ b/Task/Brilliant-numbers/Pluto/brilliant-numbers.pluto @@ -0,0 +1,72 @@ +do -- Find Brilliant numbers - semi-primes whose two prime factors + -- have the same number of digits + + local fmt = require( "fmt" ) -- RC Pluto formatting library + local int = require( "int" ) -- RC Pluto integer library, inc. prime utilities + + -- returns a table of brilliant numbers to maxBrilliant + local function findBrialliant( maxBrilliant : number, ps : table ) : table + local bn , maxPs = {}, # ps + for n = 1, maxBrilliant do bn[ n ] = false end + + -- brilliant numbers where one of the fators is 2 + bn[ 4 ] = true + for p = 3, 7, 2 do bn[ 2 * p ] = true end + + -- brilliant numbers where both factors are odd + local pStart, pEnd = 1, 9 + while pStart < maxPs do + for p = pStart, pEnd, 2 do + if ps[ p ] then + bn[ p * p ] = true + for q = p + 2, pEnd, 2 do + if ps[ q ] then + bn[ p * q ] = true + end + end + end + end + pStart = pEnd + 2 + pEnd = ( ( pStart - 1 ) * 10 ) - 1 + if pEnd > maxPs then pEnd = maxPs end + end + return bn + end + + do -- task + + local maxPrime = 1010 -- maximum prime we will consider, should be + -- enough to find the first brilliant number > 10^6 + + -- construct a sieve of brilliant numbers to maxPrime squared + -- using a sieve of primes to maxPrime + local brilliant = findBrialliant( maxPrime * maxPrime + , int.arecomps( maxPrime ):map( | v | -> not v ) + ) + + -- show the first 100 brilliant numbers + local bCount, n, p10 = 0, 0, 0 + while bCount < 100 do + n += 1 + if brilliant[ n ] then + fmt.write( "%6d", n ) + bCount += 1 + if bCount % 10 == 0 then print() end + end + end + + -- show the first brilliant number >= 10^n, n = 1, 2, ..., 6 + bCount, p10 = 0, 10 + for bPos = 1, # brilliant do + if brilliant[ bPos ] then + bCount += 1 + if bPos >= p10 then + fmt.write( "First brilliant number >= %8d: %8d", p10, bPos ) + fmt.print( " at position %6d", bCount ) + p10 *= 10 + end + end + end + end + +end diff --git a/Task/Brownian-tree/Ada/brownian-tree.adb b/Task/Brownian-tree/Ada/brownian-tree.adb new file mode 100644 index 0000000000..fb12999349 --- /dev/null +++ b/Task/Brownian-tree/Ada/brownian-tree.adb @@ -0,0 +1,125 @@ +with Ada.Numerics.Discrete_Random; + +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Events.Events; + +procedure Brownian_Tree is + + Width : constant := 800; + Height : constant := 600; + Points : constant := 50_000; + + subtype Width_Range is Integer range 1 .. Width; + subtype Height_Range is Integer range 1 .. Height; + type Direction is (N, NE, E, SE, S, SW, W, NW); + package Random_Width is new Ada.Numerics.Discrete_Random (Width_Range); + package Random_Height is new Ada.Numerics.Discrete_Random (Height_Range); + package Random_Direc is new Ada.Numerics.Discrete_Random (Direction); + + Window : SDL.Video.Windows.Window; + Renderer : SDL.Video.Renderers.Renderer; + Event : SDL.Events.Events.Events; + + Width_Gen : Random_Width.Generator; + Height_Gen : Random_Height.Generator; + Direc_Gen : Random_Direc.Generator; + + function Poll_Quit return Boolean is + use type SDL.Events.Event_Types; + begin + while SDL.Events.Events.Poll (Event) loop + if Event.Common.Event_Type = SDL.Events.Quit then + return True; + end if; + end loop; + return False; + end Poll_Quit; + + procedure Draw_Brownian_Tree is + Field : array (Width_Range, Height_Range) of Boolean := (others => (others => False)); + X : Width_Range; + Y : Height_Range; + Direc : Direction; + + procedure Random_Free (X : out Width_Range; Y : out Height_Range) is + begin + -- Find free random spot + loop + X := Random_Width.Random (Width_Gen); + Y := Random_Height.Random (Height_Gen); + exit when Field (X, Y) = False; + end loop; + end Random_Free; + + begin + -- Seed + Field (Random_Width.Random (Width_Gen), + Random_Height.Random (Height_Gen)) := True; + + for I in 0 .. Points loop + Random_Free (X, Y); + loop + -- If collide with wall then new random start + while + X = Width_Range'First or X = Width_Range'Last or + Y = Height_Range'First or Y = Height_Range'Last + loop + Random_Free (X, Y); + end loop; + exit when Field (X - 1, Y - 1) or Field (X, Y - 1) or Field (X + 1, Y - 1); + exit when Field (X - 1, Y) or Field (X + 1, Y); + exit when Field (X - 1, Y + 1) or Field (X, Y + 1) or Field (X + 1, Y + 1); + Direc := Random_Direc.Random (Direc_Gen); + case Direc is + when NW | N | NE => Y := Y - 1; + when SW | S | SE => Y := Y + 1; + when others => null; + end case; + case Direc is + when NW | W | SW => X := X - 1; + when SE | E | NE => X := X + 1; + when others => null; + end case; + end loop; + Field (X, Y) := True; + Renderer.Draw (Point => (SDL.C.int (X), SDL.C.int (Y))); + + if I mod 100 = 0 then + if Poll_Quit then + return; + end if; + Window.Update_Surface; + end if; + end loop; + end Draw_Brownian_Tree; + +begin + Random_Width.Reset (Width_Gen); + Random_Height.Reset (Height_Gen); + Random_Direc.Reset (Direc_Gen); + + if not SDL.Initialise (Flags => SDL.Enable_Screen) then + return; + end if; + + SDL.Video.Windows.Makers.Create (Win => Window, + Title => "Brownian tree", + Position => SDL.Natural_Coordinates'(X => 10, Y => 10), + Size => SDL.Positive_Sizes'(Width, Height), + Flags => 0); + SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); + Renderer.Set_Draw_Colour ((0, 0, 0, 255)); + Renderer.Fill (Rectangle => (0, 0, Width, Height)); + Renderer.Set_Draw_Colour ((200, 200, 200, 255)); + + Draw_Brownian_Tree; + Window.Update_Surface; + + loop + exit when Poll_Quit; + delay 0.050; + end loop; + Window.Finalize; + SDL.Finalise; +end Brownian_Tree; diff --git a/Task/Brownian-tree/EasyLang/brownian-tree.easy b/Task/Brownian-tree/EasyLang/brownian-tree.easy index b5012e14d2..cad6bf6875 100644 --- a/Task/Brownian-tree/EasyLang/brownian-tree.easy +++ b/Task/Brownian-tree/EasyLang/brownian-tree.easy @@ -11,15 +11,15 @@ set 100 100 n = 6000 while i < n repeat - x = random 200 - 1 - y = random 200 - 1 + x = random 0 199 + y = random 0 199 until get x y <> 1 . while 1 = 1 xo = x yo = y - x += random 3 - 2 - y += random 3 - 2 + x += random -1 1 + y += random -1 1 if x < 0 or y < 0 or x >= 200 or y >= 200 : break 1 if get x y = 1 set xo yo diff --git a/Task/Brownian-tree/Scheme/brownian-tree-1.scm b/Task/Brownian-tree/Scheme/brownian-tree-1.scm new file mode 100644 index 0000000000..b924ac4f54 --- /dev/null +++ b/Task/Brownian-tree/Scheme/brownian-tree-1.scm @@ -0,0 +1,108 @@ +; Save bitmap to external file +(define (save-pbm bitmap filename) + (define f (open-output-file filename)) + (simple-format f "P1\n~A ~A\n" + (list-ref (array-dimensions bitmap) 0) + (list-ref (array-dimensions bitmap) 1)) + (do ((c 0 (+ c 1))) ((eqv? c (list-ref (array-dimensions bitmap) 1))) + (do ((r 0 (+ r 1))) ((eqv? r (list-ref (array-dimensions bitmap) 0))) + (display (array-ref bitmap r c) f)) + (newline f)) + (close-output-port f) +) + +; Return a random coordinate in the bitmap that isn't filled yet along with a direction +(define (new-particle bitmap) + (define x (random (list-ref (array-dimensions bitmap) 0))) + (define y (random (list-ref (array-dimensions bitmap) 1))) + (define dx (- (random 3) 1)) + (define dy (- (random 3) 1)) + ;Repeat until we find an unused location + (if (> (array-ref bitmap x y) 0) + (new-particle bitmap) + (list (list x y) (list dx dy)))) + +; Check neighboring coordinates to see if a collision occured +(define (collision-check bitmap p) + (define c #f) + (define oob #f) + (define x (list-ref (car p) 0)) + (define y (list-ref (car p) 1)) + (define dx (list-ref (cadr p) 0)) + (define dy (list-ref (cadr p) 1)) + (define w (list-ref (array-dimensions bitmap) 0)) + (define h (list-ref (array-dimensions bitmap) 1)) + + ; If the particle hasn't gone out of bounds keep checking for a collision + (if (or (> 0 x) (> 0 y) (<= w x) (<= h y)) + (set! oob #t) + (do ((x (- (list-ref (car p) 0) 1) (+ x 1))) ((eqv? x (+ (list-ref (car p) 0) 2))) + (do ((y (- (list-ref (car p) 1) 1) (+ y 1))) ((eqv? y (+ (list-ref (car p) 1) 2))) + ; Check existing neighbors for collisions + (if (and (<= 0 x) (<= 0 y) (> w x) (> h y)) + (if (not (zero? (array-ref bitmap x y))) + (set! c #t)))))) + (if oob + #f ; Return false if out of bounds + (if c + p ; Return the point of collision if a collision occured + (if (and (zero? dx) (zero? dy)) + #f ; Return false if particle is motionless with no collision + (collision-check bitmap (particle-move p)))))) + +; Plot a particle on the bitmap +(define (particle-plot! bitmap p) + (array-set! bitmap 1 (list-ref (car p) 0) (list-ref (car p) 1))) + +; Move a particle along its slope +(define (particle-move p) + (list (list + (+ (list-ref (car p) 0) (list-ref (cadr p) 0)) + (+ (list-ref (car p) 1) (list-ref (cadr p) 1))) + (cadr p))) + +; Grow a brownian tree +(define (grow-brownian-tree! bitmap collisions) + (define w (list-ref (array-dimensions bitmap) 0)) + (define h (list-ref (array-dimensions bitmap) 1)) + + ; Generate a new particle at a random location + (define p (new-particle bitmap)) + + ; Find a collision or lack of one and plot it on the bitmap + (set! p (collision-check bitmap p)) + (if p (begin + ; Display collision number and the place it happened + (display collisions)(display ": ")(display (car p))(newline) + (set! collisions (- collisions 1)) + ; Plot the point + (particle-plot! bitmap p))) + + ; If we're done say so + (if (zero? collisions) + (display "Done\n")) + + ; Keep going until we have enough collisions + ; or have filled the bitmap + (if (and (< 0 collisions) (memq 0 (array->list (array-contents bitmap)))) + (grow-brownian-tree! bitmap collisions))) + +; Plot a random point to seed the brownian tree +(define (seed-brownian-tree! bitmap) + (define p (new-particle bitmap)) + (particle-plot! bitmap p)) + +;;; Example usage ;;; +; Seed the random number generator +(let ((time (gettimeofday))) + (set! *random-state* + (seed->random-state (+ (car time) (cdr time))))) + +; Generate a tree with 320*240 collisions on a bitmap of the size 640x480 +; The bitmap is zeroed to start and written with a one where a collision occurs +(define bitmap (make-array 0 640 480)) +(seed-brownian-tree! bitmap) +(grow-brownian-tree! bitmap (* 320 240)) + +; Save to a portable bitmap file +(save-pbm bitmap "brownian-tree.pbm") diff --git a/Task/Brownian-tree/Scheme/brownian-tree-2.scm b/Task/Brownian-tree/Scheme/brownian-tree-2.scm new file mode 100644 index 0000000000..55260d063b --- /dev/null +++ b/Task/Brownian-tree/Scheme/brownian-tree-2.scm @@ -0,0 +1,85 @@ +(import (srfi 231)) ;; intervals and arrays +(import (srfi 27)) ;; random number generation + +(define make-direction cons) +(define direction-r car) +(define direction-c cdr) + +(define (random-direction) + (let* ((r (- (random-integer 3) 1)) ;; -1, 0, or 1 + (c (- (random-integer 3) 1))) ;; -1, 0, or 1 + (if (and (zero? r) (zero? c)) + ;; we need a nonzero direction + (random-direction) + (make-direction r c)))) + +(define (brownian-tree rows columns points) + (let* ((D + ;; The domain of the result bit-map + (make-interval (vector rows columns))) + (E + ;; A bit-map of zeros extending D, with a one extra row + ;; and column of zeros above and below, left and right of D + (array-copy! (make-array (interval-dilate D '#(-1 -1) '#(1 1)) + (lambda args 0)) + u1-storage-class + #t)) ;; mutable + (B + ;; The bit-map where we place dots, extracted from the + ;; center of the extended bit-map + (array-extract E D)) + (Ns + ;; views of the extended bit-map E that give the + ;; eight neighbors of bits in B via translation + (map (lambda (translate) + (array-extract (array-translate E translate) D)) + '(#( 1 0) #(0 1) #(-1 0) #(0 -1) + #(-1 1) #(1 -1) #(-1 -1) #(1 1)))) + (B_ (array-getter B)) ;; gets values of B + (B! (array-setter B)) ;; sets values of B + (Ns_ (map array-getter Ns))) ;; gets values of all the neighbors + ;; Set the seed bit + (B! 1 (random-integer rows) (random-integer columns)) + (let loop1 ((p 0)) + (if (= p points) + B + (let* ((r (random-integer rows)) + (c (random-integer columns))) + (if (positive? (B_ r c)) + ;; already a bit there, loop without incrementing + ;; the number of placed points + (loop1 p) + (let loop2 ((r r) + (c c)) + (if (any (lambda (g) (positive? (g r c))) Ns_) + ;; at least one of the neighbors is 1 + (begin + (B! 1 r c) ;; set the bit to 1 + (loop1 (+ p 1))) ;; increment number of placed points + (let* ((direction (random-direction)) + (r (+ r (direction-r direction))) + (c (+ c (direction-c direction)))) + (if (and (< -1 r rows) (< -1 c columns)) + ;; point remains in the domain + (loop2 r c) + ;; walked outside the domain, loop without + ;; incrementing the number of placed points. + (loop1 p))))))))))) + +(define (write-pbm array file) + (with-output-to-file file + (lambda () + (let* ((domain (array-domain array)) + (rows (interval-width domain 0)) + (columns (interval-width domain 1))) + (display "P1") (newline) + (display columns) (display " ") (display rows) (newline) + (array-for-each (let ((next-pixel-in-line 1)) + (lambda (p) + (write p) + (if (zero? (modulo next-pixel-in-line 64)) (newline)) + (set! next-pixel-in-line (+ 1 next-pixel-in-line)))) + array))))) + +(write-pbm (brownian-tree 320 640 20000) + "brownian-tree-320-640-20000.pbm") diff --git a/Task/Brownian-tree/Uiua/brownian-tree-1.uiua b/Task/Brownian-tree/Uiua/brownian-tree-1.uiua deleted file mode 100644 index 6bf39c8210..0000000000 --- a/Task/Brownian-tree/Uiua/brownian-tree-1.uiua +++ /dev/null @@ -1,21 +0,0 @@ -S ← 80 -# Create SxS grid, and set the centre point as seed. -⍜⊡(+1)↯2⌊÷2S ↯ S_S 0 - -RandInt ← ⌊×⚂ -RandPoint ← ([⍥(RandInt S)2]) -# Update the pair to be a new adjacent [[Here] [Last]] -Move ← ⊟∵(-1+⌊RandInt 3).⊢ -In ← /××⊃(≥0)( Sequence, + Index_Type => Positive); + + -- check if sequence contains each digit only once + function Is_Valid (S : Sequence) return Boolean is + Appeared : array (Digit) of Boolean := (others => False); + begin + for I in S'Range loop + if Appeared (S (I)) then + return False; + end if; + Appeared (S (I)) := True; + end loop; + return True; + end Is_Valid; + + -- calculate all possible sequences and store them in the vector + procedure Fill_Pool (Pool : in out Sequence_Vectors.Vector) is + Finished : exception; + -- count the sequence up by one + function Next (S : Sequence) return Sequence is + Result : Sequence := S; + Index : Positive := S'Last; + begin + loop + -- overflow at a position causes next position to increase + if Result (Index) = Digit'Last then + Result (Index) := Digit'First; + -- overflow at maximum position + -- we have processed all possible values + if Index = Result'First then + raise Finished; + end if; + Index := Index - 1; + else + Result (Index) := Result (Index) + 1; + return Result; + end if; + end loop; + end Next; + X : Sequence := (others => 1); + begin + loop + -- append all valid values + if Is_Valid (X) then + Pool.Append (X); + end if; + X := Next (X); + end loop; + exception + when Finished => + -- the exception tells us that we have added all possible values + -- simply return and do nothing. + null; + end Fill_Pool; + + -- generate a random index from the pool + function Random_Index (Pool : Sequence_Vectors.Vector) return Positive is + subtype Possible_Indexes is Positive range + Pool.First_Index .. Pool.Last_Index; + package Index_Random is new Ada.Numerics.Discrete_Random + (Possible_Indexes); + Index_Gen : Index_Random.Generator; + begin + Index_Random.Reset (Index_Gen); + return Index_Random.Random (Index_Gen); + end Random_Index; + + -- get the answer from the player, simple validity tests + procedure Get_Answer (S : Sequence; Bulls, Cows : out Natural) is + Valid : Boolean := False; + begin + Bulls := 0; + Cows := 0; + while not Valid loop + -- output the sequence + Ada.Text_IO.Put ("How is the score for:"); + for I in S'Range loop + Ada.Text_IO.Put (Digit'Image (S (I))); + end loop; + Ada.Text_IO.New_Line; + begin + Ada.Text_IO.Put ("Bulls:"); + Nat_IO.Get (Bulls); + Ada.Text_IO.Put ("Cows:"); + Nat_IO.Get (Cows); + if Bulls + Cows <= Guessing_Length then + Valid := True; + else + Ada.Text_IO.Put_Line ("Invalid answer, try again."); + end if; + exception + when others => + null; + end; + end loop; + end Get_Answer; + + -- remove all sequences that wouldn't give an equivalent score + procedure Strip + (V : in out Sequence_Vectors.Vector; + S : Sequence; + Bulls, Cows : Natural) + is + function Has_To_Be_Removed (Position : Positive) return Boolean is + Testant : constant Sequence := V.Element (Position); + Bull_Score : Natural := 0; + Cow_Score : Natural := 0; + begin + for I in Testant'Range loop + for J in S'Range loop + if Testant (I) = S (J) then + -- same digit at same position: Bull! + if I = J then + Bull_Score := Bull_Score + 1; + else + Cow_Score := Cow_Score + 1; + end if; + end if; + end loop; + end loop; + return Cow_Score /= Cows or else Bull_Score /= Bulls; + end Has_To_Be_Removed; + begin + for Index in reverse V.First_Index .. V.Last_Index loop + if Has_To_Be_Removed (Index) then + V.Delete (Index); + end if; + end loop; + end Strip; + + -- main routine + procedure Solve is + All_Sequences : Sequence_Vectors.Vector; + Test_Index : Positive; + Test_Sequence : Sequence; + Bulls, Cows : Natural; + begin + -- generate all possible sequences + Fill_Pool (All_Sequences); + loop + -- pick at random + Test_Index := Random_Index (All_Sequences); + Test_Sequence := All_Sequences.Element (Test_Index); + -- ask player + Get_Answer (Test_Sequence, Bulls, Cows); + -- hooray, we have it! + exit when Bulls = 4; + All_Sequences.Delete (Test_Index); + Strip (All_Sequences, Test_Sequence, Bulls, Cows); + exit when All_Sequences.Length <= 1; + end loop; + if All_Sequences.Length = 0 then + -- oops, shouldn't happen + Ada.Text_IO.Put_Line + ("I give up, there has to be a bug in" & + "your scoring or in my algorithm."); + else + if All_Sequences.Length = 1 then + Ada.Text_IO.Put ("The sequence you thought has to be:"); + Test_Sequence := All_Sequences.First_Element; + else + Ada.Text_IO.Put ("The sequence you thought of was:"); + end if; + for I in Test_Sequence'Range loop + Ada.Text_IO.Put (Digit'Image (Test_Sequence (I))); + end loop; + end if; + end Solve; + +begin + -- output blah blah + Ada.Text_IO.Put_Line ("Bulls and Cows, Your turn!"); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line + ("Think of a sequence of" & + Integer'Image (Guessing_Length) & + " different digits."); + Ada.Text_IO.Put_Line ("I will try to guess it. For each correctly placed"); + Ada.Text_IO.Put_Line ("digit I score 1 Bull. For each digit that is on"); + Ada.Text_IO.Put_Line ("the wrong place I score 1 Cow. After each guess"); + Ada.Text_IO.Put_Line ("you tell me my score."); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line ("Let's start."); + Ada.Text_IO.New_Line; + -- solve the puzzle + Solve; +end Bulls_Player; diff --git a/Task/Bulls-and-cows-Player/EasyLang/bulls-and-cows-player.easy b/Task/Bulls-and-cows-Player/EasyLang/bulls-and-cows-player.easy new file mode 100644 index 0000000000..c9497fedc7 --- /dev/null +++ b/Task/Bulls-and-cows-Player/EasyLang/bulls-and-cows-player.easy @@ -0,0 +1,54 @@ +size = 4 +choices$[] = [ ] +proc mkperms pre$ rest$ sz . + if len pre$ = sz + choices$[] &= pre$ + return + . + for i = 1 to len rest$ + npre$ = pre$ & substr rest$ i 1 + nrest$ = substr rest$ 1 (i - 1) & substr rest$ (i + 1) 99 + mkperms npre$ nrest$ sz + . +. +mkperms "" "123456789" size +for i = len choices$[] downto 2 + j = random 1 i + swap choices$[i] choices$[j] +. +answers$[] = [ ] +print "Playing Bulls & Cows with " & size & " unique digits" +while 1 = 1 + ans$ = choices$[1] + answers$[] &= ans$ + write "Guess " & len answers$[] & " is " & ans$ & ". Enter score (bulls,cows): " + score$ = input + print score$ + a$[] = strtok score$ ", " + bulls = number a$[1] + cows = number a$[2] + if bulls = size and cows = 0 + print "Ye-haw!" + break 1 + . + nchoices$[] = [ ] + for c$ in choices$[] + b = 0 + cw = 0 + for i = 1 to size + if substr c$ i 1 = substr ans$ i 1 + b += 1 + elif strpos ans$ substr c$ i 1 > 0 + cw += 1 + . + . + if b = bulls and cw = cows + nchoices$[] &= c$ + . + . + swap choices$[] nchoices$[] + if len choices$[] = 0 + print "Bad scoring? Nothing fits!" + break 1 + . +. diff --git a/Task/Bulls-and-cows-Player/Euphoria/bulls-and-cows-player.eu b/Task/Bulls-and-cows-Player/Euphoria/bulls-and-cows-player.eu new file mode 100644 index 0000000000..5cc5d4d04b --- /dev/null +++ b/Task/Bulls-and-cows-Player/Euphoria/bulls-and-cows-player.eu @@ -0,0 +1,84 @@ +include std/sequence.e + +constant line = "--------+--------------------\n" +constant digits = "123456789" +sequence list = {} + +function get_digits(integer n) + integer j + sequence d = digits, ret = "" + for i=1 to n do + j = rand(length(digits)-i) + ret &= d[i+j] + if j then + d[i+j] = d[i] + d[i] = ret[i] + end if + end for + return ret +end function + +function MASK(integer x) + return power(2,x-digits[1]) +end function + +function score(sequence pattern, sequence guess) + integer bits = 0, bull = 0, cow = 0 + for i = 1 to length(guess) do + if guess[i] != pattern[i] then + bits += MASK(pattern[i]) + else + bull += 1 + end if + end for + + for i = 1 to length(guess) do + cow += and_bits(bits,MASK(guess[i])) != 0 + end for + + return {bull, cow} +end function + +procedure pick(integer n, integer got, integer marker, sequence buf) + integer bits = 1 + if got >= n then + list = append(list,buf) + else + for i = 0 to length(digits)-1 do + if not and_bits(marker,bits) then + buf[got+1] = i+digits[1] + pick(n, got+1, or_bits(marker,bits), buf) + end if + bits *= 2 + end for + end if +end procedure + +function tester(sequence item, sequence data) + return equal(score(item,data[1]),data[2]) +end function + +constant tester_id = routine_id("tester") + +procedure game(sequence tgt) + integer p, n = length(tgt) + sequence buf = repeat(0,n), bc + list = {} + pick(n,0,0,buf) + p = 1 + bc = {0,0} + while bc[1]result constraints + foreach [k v] results [ + if v <> check guess k [guess: copy "" break] + ] + ;; skip candidate if it violated any constraint + if empty? guess [continue] + ;; evaluate feedback (bulls/cows) for this guess against the secret and store it + results/:guess: res: check guess secret + ;; stop searching when four bulls achieved + if res == "BBBB" [break] + ] + ;; display guess history and their feedback + foreach [k v] results [print [k "-" v]] + ;; summary: found number and number of attempts + print ["^/Found" as-yellow last k: keys-of results "in" as-yellow length? k "attempts" CR] +][ + secret: none + digits: charset "0123456789" ;; character set of digits for parse rule + results: make map! [] ;; map of guess -> feedback string (e.g., "BBC") + + check: function [ + "compute bulls and cows feedback for a guess vs. a secret" + guess secret + ][ + sort append copy "" collect [ + repeat pos 4 [ + either guess/:pos == secret/:pos [ + keep #"B" + ][ + if find secret guess/:pos [keep #"C"] + ] + ] + ] + ] + valid: function [ + "validate a guess: exactly 4 digits and all unique" + guess + ][ + all [ + parse guess [4 digits] + 4 == length? unique guess + ] + ] + ;; precompute all valid 4-unique-digit numbers as candidate guesses + possible: collect [ + repeat i 9876 [ + if valid secret: to string! i [keep secret] + ] + ] +] + +;; DEMO: +bulls-and-cows-player 1543 diff --git a/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua b/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua index afd3791852..33b90b6562 100644 --- a/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua +++ b/Task/Bulls-and-cows-Player/Uiua/bulls-and-cows-player.uiua @@ -1,18 +1,13 @@ # Sets and plays a game of Bulls and Cows (Mastermind) -T ← [⍥(+1⌊×⚂9)4] # Random target -# Score a guess against a target, or vice versa :-). -Score ← ( - :⟜/+=,, # Find bulls. - ⊟⊙(/+↧∩(≡/+⊞=+1⇡9)∩▽⊙:.¬) # Find cows. -) +T ← ⍥(+1⌊×⚂9)4 # Random target +# Score a guess against a target (or vice versa :-). +Score ← [∩/+]⊃(=|↧∩(≡/+⊞=+1⇡9)▽◡≠) &p $"_ <- Target\n" T -⍥(☇1⊞⊂.)2+1⇡9 # Proposed targets [1-9 1-9 1-9 1-9] -⍢( - - ⟜(&p$"_\t_",,⟜(Score T)⊡⊸(⌊×⚂⧻)) # Pick from Ps, and play it against T - ▽:⟜(≡≍⊙¤≡Score⊙¤) # Only keep Ps that match that score -| >1⧻ +⧅⋅⋅1 4 +1⇡9 # Proposed targets [1-9 1-9 1-9 1-9] +⍢(⟜(&p◡$"_\t_"⟜(Score T)⊡⌊×⚂⊸⧻) # Pick from Ps, and play it against T + ▽⊃(≡⌟≍≡⌟Score|∘) # Only keep Ps that match that score +| >1⧻ # Until we get to just one solution. ) &p↯21@- -&p $"_\t_" :⊸(⟨"UHOH"|"good"⟩≍T)⊢ +&p $"_\t_" ⟜(⨬("UHOH"|"good")≍T)⊢ diff --git a/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl b/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl index 0a155b8011..d51921fac3 100644 --- a/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl +++ b/Task/Bulls-and-cows/APL/bulls-and-cows-1.apl @@ -1,4 +1,4 @@ -output← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵} -guess ← ⍎¨{⍞←'Guess: ' ⋄ 7↓⍞}⍣((∧/⍤∊∘⎕D ∧ 4=≢)⊣) -game ← (output ⊣ (+/⍤= , ∊+/⍤∧≠) guess)⍣(4 0≡⊣) -moo ← 'You win!'⊣(1+4?9⍨)game⊢ +{R←1+4?9 + _←{G←⍎¨{⍞←'Guess: '⋄7↓⍞}⍣((∧/⍤∊∘⎕D∧4=≢)⊣)⍬ + BC⊣⎕←(↑'Bulls: ' 'Cows: '),⍕⍪BC←R(+.=,∊+.∧≠)G + }⍣(4 0≡⊣)⍬⋄'You win!'}⍬ diff --git a/Task/Bulls-and-cows/APL/bulls-and-cows-2.apl b/Task/Bulls-and-cows/APL/bulls-and-cows-2.apl index 72560506f2..b63752b1e2 100644 --- a/Task/Bulls-and-cows/APL/bulls-and-cows-2.apl +++ b/Task/Bulls-and-cows/APL/bulls-and-cows-2.apl @@ -1 +1,4 @@ -moo←'You win!'⊣((1+4?9⍨)(({⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵⋄⍵}⊣((+/=),(+/∊∧≠))(⍎¨{⍞←'Guess: '⋄7↓⍞}⍣(((∧/⎕D∊⍨⊢)∧4=≢)⊣)))⍣(4 0≡⊣))⊢) +output← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵} +guess ← ⍎¨{⍞←'Guess: ' ⋄ 7↓⍞}⍣((∧/⍤∊∘⎕D ∧ 4=≢)⊣) +game ← (output ⊣ (+.= , ∊+.∧≠) guess)⍣(4 0≡⊣) +moo ← 'You win!'⊣(1+4?9⍨)game⊢ diff --git a/Task/Bulls-and-cows/APL/bulls-and-cows-3.apl b/Task/Bulls-and-cows/APL/bulls-and-cows-3.apl new file mode 100644 index 0000000000..72560506f2 --- /dev/null +++ b/Task/Bulls-and-cows/APL/bulls-and-cows-3.apl @@ -0,0 +1 @@ +moo←'You win!'⊣((1+4?9⍨)(({⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵⋄⍵}⊣((+/=),(+/∊∧≠))(⍎¨{⍞←'Guess: '⋄7↓⍞}⍣(((∧/⎕D∊⍨⊢)∧4=≢)⊣)))⍣(4 0≡⊣))⊢) diff --git a/Task/Bulls-and-cows/APL/bulls-and-cows-4.apl b/Task/Bulls-and-cows/APL/bulls-and-cows-4.apl new file mode 100644 index 0000000000..fa91aa7235 --- /dev/null +++ b/Task/Bulls-and-cows/APL/bulls-and-cows-4.apl @@ -0,0 +1,10 @@ +input ← {⍞←'Guess: ' ⋄ 7↓⍞} +output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵} +isdigits← ∧/⎕D∊⍨⊢ +valid ← isdigits∧4=≢ +guess ← ⍎¨input⍣(valid⊣) +bulls ← +/= +cows ← +/∊∧≠ +game ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣) +random ← 1+4?9 +moo ← 'You win!'⊣(random game⊢) diff --git a/Task/Bulls-and-cows/Ada/bulls-and-cows.adb b/Task/Bulls-and-cows/Ada/bulls-and-cows.adb new file mode 100644 index 0000000000..44363d6546 --- /dev/null +++ b/Task/Bulls-and-cows/Ada/bulls-and-cows.adb @@ -0,0 +1,53 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Discrete_Random; + +procedure Bulls_And_Cows is + package Random_Natural is new Ada.Numerics.Discrete_Random (Natural); + Number : String (1..4); +begin + declare -- Generation of number + use Random_Natural; + Digit : String := "123456789"; + Size : Positive := 9; + Dice : Generator; + Position : Natural; + begin + Reset (Dice); + for I in Number'Range loop + Position := Random (Dice) mod Size + 1; + Number (I) := Digit (Position); + Digit (Position..Size - 1) := Digit (Position + 1..Size); + Size := Size - 1; + end loop; + end; + loop -- Guessing loop + Put ("Enter four digits:"); + declare + Guess : String := Get_Line; + Bulls : Natural := 0; + Cows : Natural := 0; + begin + if Guess'Length /= 4 then + raise Data_Error; + end if; + for I in Guess'Range loop + for J in Number'Range loop + if Guess (I) not in '1'..'9' or else (I < J and then Guess (I) = Guess (J)) then + raise Data_Error; + end if; + if Number (I) = Guess (J) then + if I = J then + Bulls := Bulls + 1; + else + Cows := Cows + 1; + end if; + end if; + end loop; + end loop; + exit when Bulls = 4; + Put_Line (Integer'Image (Bulls) & " bulls," & Integer'Image (Cows) & " cows"); + exception + when Data_Error => Put_Line ("You should enter four different digits 1..9"); + end; + end loop; +end Bulls_And_Cows; diff --git a/Task/Bulls-and-cows/C3/bulls-and-cows.c3 b/Task/Bulls-and-cows/C3/bulls-and-cows.c3 new file mode 100644 index 0000000000..66a5bf1e1e --- /dev/null +++ b/Task/Bulls-and-cows/C3/bulls-and-cows.c3 @@ -0,0 +1,90 @@ +module bulls_and_cows; +import std::io; +import std::math::random; + +const MAXNUM = 9877; + +fn uint get_digit(uint num, uint ps) +{ + while (ps-- > 0) { + num /= 10; + } + return num % 10; +} + +fn bool is_malformed(uint num) +{ + if (num >= MAXNUM) { + return true; + } + for (uint i = 0; i <= 2; i++) { + for (uint j = i + 1; j <= 3; j++) { + if (get_digit(num, j) == get_digit(num, i)) { + return true; + } + } + } + return false; +} + +fn uint make_number() +{ + uint num; + do { + num = random::rand(MAXNUM); + } while (is_malformed(num)); + return num; +} + +fn uint? input() +{ + String line = io::treadline()!; + uint num; + foreach (ch : line) { + if (!ch.is_digit()) { + break; + } + num *= 10; + num += ch - '0'; + } + return num; +} + +fn void main() +{ + io::printn("Welcome to bulls and cows!\n" + "\n" + "I choose a number made of 4 digits (from 0 to 9) without repetitions.\n" + "You enter a number of 4 digits, and I say you how many of them\n" + "are in my secret number but in wrong position (cows),\n" + "and how many are in the right position (bulls).\n"); + + uint secret = make_number(); + uint count, guess; + while (guess != secret) { + count++; + do { + io::printn("Guess a number."); + if (try reply = input()) { + guess = reply; + } else { + return; + } + } while (is_malformed(guess)); + + uint cows, bulls; + for (uint i = 0; i <= 3; i++) { + for (uint j = 0; j <= 3; j++) { + if (get_digit(secret, i) == get_digit(guess, j)) { + if (i == j) { + bulls++; + } else { + cows++; + } + } + } + } + io::printfn("You scored %d bulls and %d cows.\n", bulls, cows); + } + io::printfn("Correct. That took you %d guesses.", count); +} diff --git a/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy b/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy index b692c49a54..07232a3cc4 100644 --- a/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy +++ b/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy @@ -1,42 +1,39 @@ -dig[] = [ 1 2 3 4 5 6 7 8 9 ] -for i = 1 to 4 - h = i - 1 + random (10 - i) - swap dig[i] dig[h] -. -# print dig[] -len g[] 4 -attempts = 0 -repeat - repeat - ok = 0 - s$[] = strchars input - if len s$[] = 4 - ok = 1 +proc game . + dig[] = [ 1 2 3 4 5 6 7 8 9 ] + for i = 1 to 4 + h = random i 9 + swap dig[i] dig[h] + . + len g[] 4 + repeat + repeat + ok = 0 + s$[] = strchars input + if len s$[] = 4 + ok = 1 + for i = 1 to 4 + g[i] = number s$[i] + if g[i] = 0 : ok = 0 + . + . + until ok = 1 + . + print g[] + attempts += 1 + bulls = 0 + cows = 0 for i = 1 to 4 - g[i] = number s$[i] - if g[i] = 0 - ok = 0 - . + if g[i] = dig[i] + bulls += 1 + else + for j = 1 to 4 + if dig[j] = g[i] : cows += 1 + . + . . - . - until ok = 1 - . - print g[] - attempts += 1 - bulls = 0 - cows = 0 - for i = 1 to 4 - if g[i] = dig[i] - bulls += 1 - else - for j = 1 to 4 - if dig[j] = g[i] - cows += 1 - . - . - . - . - print "bulls:" & bulls & " cows:" & cows - until bulls = 4 + print "bulls:" & bulls & " cows:" & cows + until bulls = 4 + . + print "Well done! " & attempts & " attempts needed." . -print "Well done! " & attempts & " attempts needed." +game diff --git a/Task/Bulls-and-cows/Emacs-Lisp/bulls-and-cows.el b/Task/Bulls-and-cows/Emacs-Lisp/bulls-and-cows.el new file mode 100644 index 0000000000..a04a27d74c --- /dev/null +++ b/Task/Bulls-and-cows/Emacs-Lisp/bulls-and-cows.el @@ -0,0 +1,132 @@ +(defun get-list-4-random-digits () + "Generate a list of 4 random non-repeating digits." + (let ((list-of-digits '(0 1 2 3 4 5 6 7 8 9)) + (one-digit) + (four-digits)) + (dotimes (n 4) + (setq one-digit (seq-random-elt list-of-digits)) + (push one-digit four-digits) + (setq list-of-digits (delq one-digit (copy-sequence list-of-digits)))) + four-digits)) + +(defun list-digits (guess-string) + "List individual digits of GUESS-STRING." + (let ((list-of-digits) + (one-digit) + (total-digits (length guess-string))) + (dotimes (n total-digits) + (setq one-digit (string-to-number (substring guess-string n (1+ n)))) + (push one-digit list-of-digits)) + (reverse list-of-digits))) + +(defun number-list-to-string (numbers) + (mapconcat #'number-to-string numbers)) + +(defun four-non-repeating-digits-p (guess-string) + "Test if GUESS-STRING has 4 one-digit numbers that do not repeat." + ;; if GUESS-STRING contains non-numeric characters, then + ;; the non-numeric characters will be converted to 0s + (let ((number-list (list-digits guess-string))) + + (and + ;; GUESS-STRING must consist of exactly 4 digits + (string-match-p "^[[:digit:]]\\{4\\}$" guess-string) + + ;; the length of the list must still be 4 after + ;; removing duplicate characters, and + (= (length (seq-uniq number-list)) 4)))) + +(defun count-bulls (guess answer) + "Count number of bulls in GUESS as compared to ANSWER. +In this game, a bull is an exact match. Both GUESS and +ANSWER are lists of numbers." + (let ((bulls 0) + (position-in-list -1)) + (dolist (guess-number guess) + (setq position-in-list (1+ position-in-list)) + (when (= guess-number (nth position-in-list answer)) + (setq bulls (1+ bulls)))) + bulls)) + +(defun is-cow-p (number-list position answer) + "Test if NUMBER-LIST is in ANSWER but not in same POSITION." + (and + ;; NUMBER-LIST is found in ANSWER + (seq-position answer number-list) + ;; NUMBER-LIST is not in same POSITION in ANSWER + (not (equal number-list (nth position answer))))) + +(defun count-cows (guess answer) + "Count number of cows in GUESS as compared to ANSWER. +In this game, a cow is a match, but only in a different position. +Both GUESS and ANSWER are lists of numbers." + (let ((cows 0) + (zero-based-position 0)) + (dotimes (n 4) + (when (is-cow-p (nth zero-based-position guess) zero-based-position answer) + (setq cows (1+ cows))) + (setq zero-based-position (1+ zero-based-position))) + cows)) + +(defun count-bulls-and-cows (guess answer count) + "Give game feedback for GUESS as compared to ANSWER." + (let ((cows (count-cows guess answer)) + (bulls (count-bulls guess answer))) + (goto-char (point-max)) + (insert (format "\n%3s - %s Bulls = %s Cows = %s" count (number-list-to-string guess) bulls cows)) + (when (= bulls 4) + (insert " You win!") + t))) + +(defun get-player-guess () + "Get player guess." + (let ((player-guess)) + (setq player-guess (read-string "Enter a 4 digit number or Q to quit: ")) + player-guess)) + +(defun play-bulls-and-cows () + "Play bulls and cows game." + (interactive) + (let ((answer (get-list-4-random-digits)) + (player-guess-string) + (player-guess-list-of-numbers) + (count 0)) + (with-current-buffer (pop-to-buffer "bulls and cows game") + (erase-buffer) + (insert (propertize + (concat + "Rules: Enter a 4 digit number whose digits do not repeat." + "\n For example, 2468 is 4 digit number with non-repeating digits." + "\n Digits that match both the number and position will be scored as bulls." + "\n Digits that match the number but *not* the position will be scored as cows.") 'face 'shadow)) + + ;; (insert "Rules: Enter a 4 digit number whose digits do not repeat.") + ;; (insert "\n For example, 2468 is 4 digit number with non-repeating digits.") + ;; (insert "\n Digits that match both the number and position will be scored as bulls.") + ;; (insert "\n Digits that match the number but *not* the position will be scored as cows.") + (insert (propertize + (concat + "\n" + "\nTurn Your guess Result" + "\n---- ---------- ------") + 'face 'bold)) + (catch 'end-game + (while t + (progn + ;; get input + (setq player-guess-string (get-player-guess)) + (setq player-guess-list-of-numbers (list-digits player-guess-string)) + ;; evaluate input + (cond + ((string-equal-ignore-case player-guess-string "Q") + (insert "\nGame ended because Q was entered") + (throw 'end-game t)) + ((four-non-repeating-digits-p player-guess-string) + ;; increase count of turns played by 1 + (setq count (1+ count)) + ;; count-bulls-and-cows returns nil if 4 bulls + (and (count-bulls-and-cows player-guess-list-of-numbers answer count) + (throw 'end-game t))) + (t + (goto-char (point-max)) + (insert (propertize (format "\nThe guess entered was %S\nYou must enter a number with 4 non-repeating digits or Q to quit." player-guess-string) 'face 'error)))))))))) diff --git a/Task/Bulls-and-cows/Euphoria/bulls-and-cows.eu b/Task/Bulls-and-cows/Euphoria/bulls-and-cows.eu new file mode 100644 index 0000000000..9f0c4620ff --- /dev/null +++ b/Task/Bulls-and-cows/Euphoria/bulls-and-cows.eu @@ -0,0 +1,103 @@ +include std\text.e +include std\os.e +include std\sequence.e +include std\console.e + +sequence bcData = {0,0} --bull,cow score for the player +sequence goalNum = { {0,0,0,0}, {0,0,0,0}, 0} --computer's secret number digits (element 1), marked as bull/cow +--indexes in element 2, integer value of it in element 3 +sequence currentGuess = { {0,0,0,0}, {0,0,0,0}, 0} --player's guess, same format as goalNum +sequence removeChars = 0 & " 0\r\t\n" --characters to trim (remove) from user's input. \r, \t are single escaped characters, +--0 is ascii 0x0 and number zero is ascii 48, or 0x30. The rest are wysiwyg +integer tries = 0 --track number of tries to guess the number +sequence bcStrings ={"bull", "cow"} --stores singular and/or plural strings depending on score in bcData + +goalNum[1] = rand( {9,9,9,9} ) --rand function works on objects. here it outputs into each sequence element. +goalNum[3] = goalNum[1][1] * 1000 + goalNum[1][2] * 100 + goalNum[1][3] * 10 + goalNum[1][4] --convert digits to an integer +--and store it + +procedure getInputAndProcess(integer stage = 1) --object = 1 sets default value for the parameter if it isn't specified + + goalNum[2][1..4] = 0 --{0,0,0,0} --set these to unscaned (0) since the scanning will start over. + currentGuess[1][1..4] = 0 --{0,0,0,0} --these too, or they will contain old marks + currentGuess[2][1..4] = 0 + tries += 1 --equivalent to tries = tries + 1, but faster and shorter to write + bcData[1..2] = 0 -- {0,0} + + if stage <= 1 then --if this process was run for the first time or with no parameters, then.. + puts(1,"The program has thought of a four digit number using only digits 1 to 9.\nType your guess and press enter.\n") + end if + + while 1 label "guesscheck" do --labels can be used to specify a jump point from exit or retry, and help readability + currentGuess[1] = trim(gets(0), removeChars) --get user input, trim unwanted characters from it, store it in currentGuess[1] + currentGuess[1] = mapping( currentGuess[1], {49,50,51,52,53,54,55,56,57}, {1,2,3,4,5,6,7,8,9} ) --convert ascii codes to + -- integer digits they represent + integer tempF = find('0',currentGuess[1]) + if length(currentGuess[1]) != 4 or tempF != 0 then --if the input string is now more than 4 characters/integers, + --the input won't be used. + puts(1,"You probably typed too many digits or a 0. Try typing a new 4 digit number with only numbers 1 through 9.\n") + retry "guesscheck" + else + exit "guesscheck" + end if + end while + --convert separate digits to the one integer they represent and store it, like with goalNum[3] + currentGuess[3] = currentGuess[1][1] * 1000 + currentGuess[1][2] * 100 + currentGuess[1][3] * 10 + currentGuess[1][4] +--convert digits to the integer they represent, to print to a string later + + --check for bulls + for i = 1 to 4 do + if goalNum[1][i] = currentGuess[1][i] then + goalNum[2][i] = 1 + currentGuess[2][i] = 1 + bcData[1] += 1 + end if + end for + + --check for cows, but not slots marked as bulls or cows already. + for i = 1 to 4 label "iGuessElem"do --loop through each guessed digit + for j = 1 to 4 label "jGoalElem" do --but first go through each goal digit, comparing the first guessed digit, + --and then the other guessed digits 2 through 4 + + if currentGuess[2][i] = 1 then --if the guessed digit we're comparing right now has been marked as bull or cow already + continue "iGuessElem" --skip to the next guess digit without comparing this guess digit to the other goal digits + end if + + if goalNum[2][j] = 1 then --if the goal digit we're comparing to right now has been marked as a bull or cow already + continue "jGoalElem" --skip to the next goal digit + end if + + if currentGuess[1][i] = goalNum[1][j] then --if the guessed digit is the same as the goal one, + --it won't be a bull, so it's a cow + bcData[2] += 1 --score one more cow + goalNum[2][j] = 1 --mark this digit as a found cow in the subsequence that stores 0's or 1's as flags + continue "iGuessElem" --skip to the next guess digit, so that this digit won't try to check for + --matches(cow) with other goal digits + end if + + end for --this guess digit was compared to one goal digit , try comparing this guess digit with the next goal digit + end for --this guess digit was compared with all goal digits, compare the next guess digit to all the goal digits + + if bcData[1] = 1 then --uses singular noun when there is score of 1, else plural + bcStrings[1] = "bull" + else + bcStrings[1] = "bulls" + end if + + if bcData[2] = 1 then --the same kind of thing as above block + bcStrings[2] = "cow" + else + bcStrings[2] = "cows" + end if + + if bcData[1] < 4 then --if less than 4 bulls were found, the player hasn't won, else they have... + printf(1, "Guess #%d : You guessed %d . You found %d %s, %d %s. Type new guess.\n", {tries, currentGuess[3], bcData[1], bcStrings[1], bcData[2], bcStrings[2]} ) + getInputAndProcess(2) + else --else they have won and the procedure ends + printf(1, "The number was %d. You guessed %d in %d tries.\n", {goalNum[3], currentGuess[3], tries} ) + any_key()--wait for keypress before closing console window. + end if + +end procedure +--run the procedure +getInputAndProcess(1) diff --git a/Task/Bulls-and-cows/J/bulls-and-cows-5.j b/Task/Bulls-and-cows/J/bulls-and-cows-5.j new file mode 100644 index 0000000000..2d74b0eb9a --- /dev/null +++ b/Task/Bulls-and-cows/J/bulls-and-cows-5.j @@ -0,0 +1,16 @@ + bullcow'' +Guess my number: 1234 +0 bulls and 1 cow. +Guess my number: 5678 +3 bulls and 0 cows. +Guess my number: 2349 +0 bulls and 0 cows. +Guess my number: 1567 +0 bulls and 3 cows. +Guess my number: 6178 +3 bulls and 0 cows. +Guess my number: 6157 +1 bull and 2 cows. +Guess my number: 5178 +4 bulls and 0 cows. +you win diff --git a/Task/Bulls-and-cows/K/bulls-and-cows-1.k b/Task/Bulls-and-cows/K/bulls-and-cows-1.k new file mode 100644 index 0000000000..e31753aa63 --- /dev/null +++ b/Task/Bulls-and-cows/K/bulls-and-cows-1.k @@ -0,0 +1,4 @@ +{1}{`1:"guess: ";g:(`i$-1_1:`)-48 / -48 to convert ascii digit codepoints to corresponding int values + $[x~g;[`0:"yup!";`exit 0] + (4=#g)&*/(g<10)&~g<0;[`0:"bulls & cows: "," & "/$(b;(#g^g^x)-b:+/x=g);x] + [`0:"bad input";x]]}/1+-4?9 / argument is the same on every iteration diff --git a/Task/Bulls-and-cows/K/bulls-and-cows-2.k b/Task/Bulls-and-cows/K/bulls-and-cows-2.k new file mode 100644 index 0000000000..2d82b0b976 --- /dev/null +++ b/Task/Bulls-and-cows/K/bulls-and-cows-2.k @@ -0,0 +1,5 @@ +n:1+-4?9 +{1}{`1:"guess: ";g:(`i$-1_1:`)-48 / -48 to convert ascii digit codepoints to corresponding int values + $[n~g;[`0:"yup!";`exit 0] + (4=#g)&*/(g<10)&~g<0;`0:"bulls & cows: "," & "/$(b;(#g^g^n)-b:+/n=g) + `0:"bad input"]}/0 / "while true: loop". 0 is a dummy arg diff --git a/Task/Bulls-and-cows/PowerShell/bulls-and-cows.ps1 b/Task/Bulls-and-cows/PowerShell/bulls-and-cows.ps1 new file mode 100644 index 0000000000..a517bbe89c --- /dev/null +++ b/Task/Bulls-and-cows/PowerShell/bulls-and-cows.ps1 @@ -0,0 +1,47 @@ +[int]$guesses = $bulls = $cows = 0 +[string]$guess = "none" +[string]$digits = "" + +while ($digits.Length -lt 4) +{ + $character = [char](49..57 | Get-Random) + + if ($digits.IndexOf($character) -eq -1) {$digits += $character} +} + +Write-Host "`nGuess four digits (1-9) using no digit twice.`n" -ForegroundColor Cyan + +while ($bulls -lt 4) +{ + do + { + $prompt = "Guesses={0:0#}, Last='{1,4}', Bulls={2}, Cows={3}; Enter your guess" -f $guesses, $guess, $bulls, $cows + $guess = Read-Host $prompt + + if ($guess.Length -ne 4) {Write-Host "`nMust be a four-digit number`n" -ForegroundColor Red} + if ($guess -notmatch "[1-9][1-9][1-9][1-9]") {Write-Host "`nMust be numbers 1-9`n" -ForegroundColor Red} + } + until ($guess.Length -eq 4) + + $guesses += 1 + $bulls = $cows = 0 + + for ($i = 0; $i -lt 4; $i++) + { + $character = $digits.Substring($i,1) + + if ($guess.Substring($i,1) -eq $character) + { + $bulls += 1 + } + else + { + if ($guess.IndexOf($character) -ge 0) + { + $cows += 1 + } + } + } +} + +Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan diff --git a/Task/Bulls-and-cows/Rebol/bulls-and-cows.rebol b/Task/Bulls-and-cows/Rebol/bulls-and-cows.rebol new file mode 100644 index 0000000000..3287a848ee --- /dev/null +++ b/Task/Bulls-and-cows/Rebol/bulls-and-cows.rebol @@ -0,0 +1,47 @@ +Rebol [ + title: "Rosetta code: Bulls and cows" + file: %Bulls_and_cows.r3 + url: https://rosettacode.org/wiki/Bulls_and_cows + needs: 3.10.0 ;; or something like that + note: "Based on Red language solution" +] + +bulls-and-cows: function/with [ + "Bulls and cows game" + /seed "optional refinement to provide a custom RNG seed" + value +][ + ;; Initialize RNG seed: use provided value, otherwise current time + random/seed any [value now/time] + ;; Secret 4-digit number with (implicitly) distinct digits from a random permutation + number: copy/part random numbers 4 + guesses: 0 + ;; Main game loop: continue until all 4 digits are correct and in correct positions + while [bulls <> 4] [ + bulls: cows: 0 ;; reset counters for this round + ;; Read user's guess + unless guess: ask "Make a guess: " [return none] ;; none on CTRL+C + ;; Validate: exactly 4 digits (note: does not enforce distinctness here) + unless parse guess [4 digits] [ + print "Guess should include exactly four different digits!" + continue + ] + ++ guesses + ;; Count bulls: correct digit in the correct position + repeat i 4 [ + if guess/:i == number/:i [++ bulls] + ] + ;; Count cows: correct digits in any position, minus the bulls + cows: (length? intersect guess number) - bulls + print ["bulls: " bulls " cows: " cows] + ] + print ["You won after" guesses "guesses!"] +][ + ;; WITH body: shared environment for the function + numbers: "0123456789" ;; pool of digits for generating the secret number + digits: charset numbers ;; character set used by the parser rule [4 digits] + bulls: cows: guesses: 0 ;; initialize counters +] + +;; DEMO: +bulls-and-cows/seed 1 diff --git a/Task/Bulls-and-cows/VBScript/bulls-and-cows.vbs b/Task/Bulls-and-cows/VBScript/bulls-and-cows.vbs new file mode 100644 index 0000000000..0c0f44c378 --- /dev/null +++ b/Task/Bulls-and-cows/VBScript/bulls-and-cows.vbs @@ -0,0 +1,43 @@ +randomize timer +fail=array("Wrong number of chars","Only figures 0 to 9 allowed","Two or more figures are the same") +p=dopuzzle() +wscript.echo "Bulls and Cows. Guess my 4 figure number!" +do + do + wscript.stdout.write vbcrlf & "your move ": s=trim(wscript.stdin.readline) + c=checkinput(s) + if not isarray (c) then wscript.stdout.write fail(c) :exit do + bu=c(0) + wscript.stdout.write "bulls: " & c(0) & " | cows: " & c(1) + loop while 0 +loop until bu=4 +wscript.stdout.write vbcrlf & "You won! " + + +function dopuzzle() + dim b(10) + for i=1 to 4 + do + r=fix(rnd*10) + loop until b(r)=0 + b(r)=1:dopuzzle=dopuzzle+chr(r+48) + next +end function + +function checkinput(s) + dim c(10) + bu=0:co=0 + if len(s)<>4 then checkinput=0:exit function + for i=1 to 4 + b=mid(s,i,1) + if instr("0123456789",b)=0 then checkinput=1 :exit function + if c(asc(b)-48)<>0 then checkinput=2 :exit function + c(asc(b)-48)=1 + for j=1 to 4 + if asc(b)=asc(mid(p,j,1)) then + if i=j then bu=bu+1 else co=co+1 + end if + next + next + checkinput=array(bu,co) +end function diff --git a/Task/Burrows-Wheeler-transform/Pluto/burrows-wheeler-transform.pluto b/Task/Burrows-Wheeler-transform/Pluto/burrows-wheeler-transform.pluto new file mode 100644 index 0000000000..e0a45fe217 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Pluto/burrows-wheeler-transform.pluto @@ -0,0 +1,59 @@ +require "table2" + +$define STX = "\x02" +$define ETX = "\x03" + +local function bwt(s) + if s:find(STX, 1, true) or s:find(ETX, 1, true) then return nil end + s = STX .. s .. ETX + local len = #s + local tbl = table.rep(len, "") + tbl[1] = s + for i = 2, len do tbl[i] = s:sub(i) .. s:sub(1, i - 1) end + tbl:sort() + local last_chars = table.rep(len, "") + for i = 1, len do last_chars[i] = tbl[i][len] end + return last_chars:concat() +end + +local function ibwt(r) + local len = #r + if len == 0 then return "" end + local tbl = table.rep(len, "") + for i = 1, len do + for j = 1, len do tbl[j] = r[j].. tbl[j] end + tbl:sort() + end + for tbl as row do + if row:endswith(ETX) then return row:sub(2, -2) end + end + return "" +end + +local function make_printable(s) + -- Substitute ^ for STX and | for ETX to print results. + s = s:replace(STX, "^") + return s:replace(ETX, "|") +end + +local tests = { + "banana", + "appellee", + "dogwood", + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", + "\x02ABC\x03" +} +for tests as test do + print(make_printable(test)) + io.write(" --> ") + local t = bwt(test) + if !t then + print("ERROR: String can't contain STX or ETX") + t = "" + else + print(make_printable(t)) + end + local r = ibwt(t) + print($" --> {r}\n") +end diff --git a/Task/Burrows-Wheeler-transform/Rebol/burrows-wheeler-transform.rebol b/Task/Burrows-Wheeler-transform/Rebol/burrows-wheeler-transform.rebol new file mode 100644 index 0000000000..c9d62158d6 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Rebol/burrows-wheeler-transform.rebol @@ -0,0 +1,80 @@ +Rebol [ + title: "Rosetta code: Burrows–Wheeler transform" + file: %Burrows–Wheeler_transform.r3 + url: https://rosettacode.org/wiki/Burrows–Wheeler_transform +] + +bwt: function [ + "Burrows–Wheeler Transform" + input [string!] "The original text to encode" +][ + ;; Add sentinel markers: + ;; STX (^(02)) at the front to mark the start + ;; ETX (^(03)) at the end to mark the terminus + ;; These ensure unambiguous reconstruction and a fixed sort position. + input: rejoin [#"^(02)" input #"^(03)"] + len: length? input ;; Length of the sentinel-marked string + rotations: clear [] ;; Will hold all cyclic rotations of the string + ;; Generate all cyclic rotations: + repeat i len [ + append rotations rejoin [ + copy at input i ;; from position i to end + copy/part input i - 1 ;; then from start up to (i-1) + ] + ] + ;; Sort all rotations lexicographically + rotations: sort rotations + transformed: copy "" ;; This will be the BWT output (last column) + ;; Take the last character from each sorted rotation and accumulate + foreach r rotations [ + append transformed last r + ] + ;; Return the "last column" as the BWT-transformed string + transformed +] + + +ibwt: function [ + "Inverse Burrows–Wheeler Transform" + input [string!] "The BWT-produced last column string" +][ + ;; Make a copy so we preserve the original argument + input: copy input + len: length? input ;; Number of rows/characters + ;; Initialise a table (block of strings), initially containing `len` empty strings + table: make block! len + loop len [append table copy ""] + ;; Rebuild rotation table iteratively: + ;; Each iteration: + ;; 1. Prepend each character of last column to corresponding row + ;; 2. Sort the rows + repeat j len [ + repeat i len [ + insert table/:i input/:i ;; insert char from last column at row start + ] + table: sort table ;; keep table lexicographically sorted + ] + ;; After len iterations, table contains all sorted rotations. + ;; The original rotation is the one starting with STX and ending with ETX. + ;; With STX as the smallest char, it will always be the first row (table/1). + if table/1/1 == #"^(02)" [ + ;; Skip STX, copy the rest minus ETX. + ;; `next table/1` skips first char (STX) + ;; `len - 2` excludes both sentinels + copy/part next table/1 len - 2 + ] +] + +; Example usage +foreach text [ + "banana" + "appellee" + "abracadabra" + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" +][ + print ["Original text: " mold text] + print ["After transformation: " mold a: bwt text] + print ["After inverse transformation:" mold b: ibwt a lf] + assert [b == text] +] diff --git a/Task/Burrows-Wheeler-transform/Uiua/burrows-wheeler-transform.uiua b/Task/Burrows-Wheeler-transform/Uiua/burrows-wheeler-transform.uiua new file mode 100644 index 0000000000..e3b6984a28 --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Uiua/burrows-wheeler-transform.uiua @@ -0,0 +1,5 @@ +# Apply Burrows–Wheeler transform + +Bwt ← ⌅(⊣⍉⍆≡⌟↻⇡⊸⧻$"\x02_\x03"|↘₁↘₋₁⊢⊙◌⍥(⍆⊸≡˜⊂)⤙˜↯""⊸⧻) +{"banana" "appellee" "abracadabra" "Unusual Uiua"} +≡(&p$"_ > _ > _"⊸°Bwt⊸Bwt) diff --git a/Task/Burrows-Wheeler-transform/V-(Vlang)/burrows-wheeler-transform.v b/Task/Burrows-Wheeler-transform/V-(Vlang)/burrows-wheeler-transform.v new file mode 100644 index 0000000000..cc21976c5e --- /dev/null +++ b/Task/Burrows-Wheeler-transform/V-(Vlang)/burrows-wheeler-transform.v @@ -0,0 +1,65 @@ +const tests = [ + "banana", + "appellee", + "dogwood", + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", + "\x02ABC\x03" +] + +struct BWT { + mut: + stx string = "\x02" + etx string = "\x03" +} + +fn (bwt BWT) bwt(sg string) !string { + if sg.contains(bwt.stx) || sg.contains(bwt.etx) { + return error("FormatException: String cannot contain STX or ETX") + } + ss := bwt.stx + sg + bwt.etx + mut table := []string{} + for ial in 0 .. ss.len { + before := ss[ial..] + after := ss[..ial] + table << before + after + } + table.sort() + return table.map(it[it.len - 1].ascii_str()).join("") +} + +fn (bwt BWT) ibwt(r string) string { + len := r.len + mut table := []string{len: len, init: ""} + for _ in 0 .. len { + for ial in 0 .. len { + table[ial] = r[ial].ascii_str() + table[ial] + } + table.sort() + } + for row in table { + if row.ends_with(bwt.etx) { return row[1..len - 1] } + } + return "" +} + +fn (bwt BWT) make_printable(sg string) string { + return sg.replace(bwt.stx, "^").replace(bwt.etx, "|") +} + +fn main() { + mut bwt_inst := BWT{} + mut tsg := "" + for idx, test in tests { + println(bwt_inst.make_printable(test)) + print(" --> ") + tsg = bwt_inst.bwt(test) or { + println("ERROR: {$err}") + tsg = "" + continue + } + println(bwt_inst.make_printable(tsg)) + rsg := bwt_inst.ibwt(tsg) + if idx < tests.len { println(" --> $rsg\n") } else { println(" --> $rsg") } + } +} diff --git a/Task/CRC-32/Ada/crc-32.adb b/Task/CRC-32/Ada/crc-32.adb new file mode 100644 index 0000000000..1346ffd67a --- /dev/null +++ b/Task/CRC-32/Ada/crc-32.adb @@ -0,0 +1,14 @@ +with Ada.Text_IO; use Ada.Text_IO; +with GNAT.CRC32; use GNAT.CRC32; +with Interfaces; use Interfaces; +procedure TestCRC is + package IIO is new Ada.Text_IO.Modular_IO (Unsigned_32); + crc : CRC32; + num : Unsigned_32; + str : String := "The quick brown fox jumps over the lazy dog"; +begin + Initialize (crc); + Update (crc, str); + num := Get_Value (crc); + IIO.Put (num, Base => 16); New_Line; +end TestCRC; diff --git a/Task/CRC-32/COBOL/crc-32.cob b/Task/CRC-32/COBOL/crc-32.cob new file mode 100644 index 0000000000..0b843fd7ad --- /dev/null +++ b/Task/CRC-32/COBOL/crc-32.cob @@ -0,0 +1,37 @@ + *> tectonics: cobc -xj crc32-zlib.cob -lz + identification division. + program-id. rosetta-crc32. + + environment division. + configuration section. + repository. + function all intrinsic. + + data division. + working-storage section. + 01 crc32-initial usage binary-c-long. + 01 crc32-result usage binary-c-long unsigned. + 01 crc32-input. + 05 value "The quick brown fox jumps over the lazy dog". + 01 crc32-hex usage pointer. + + procedure division. + crc32-main. + + *> libz crc32 + call "crc32" using + by value crc32-initial + by reference crc32-input + by value length(crc32-input) + returning crc32-result + on exception + display "error: no crc32 zlib linkage" upon syserr + end-call + call "printf" using "checksum: %lx" & x"0a" by value crc32-result + + *> GnuCOBOL pointers are displayed in hex by default + set crc32-hex up by crc32-result + display 'crc32 of "' crc32-input '" is ' crc32-hex + + goback. + end program rosetta-crc32. diff --git a/Task/CRC-32/Haxe/crc-32.hx b/Task/CRC-32/Haxe/crc-32.hx new file mode 100644 index 0000000000..d1259bb95e --- /dev/null +++ b/Task/CRC-32/Haxe/crc-32.hx @@ -0,0 +1,9 @@ +using StringTools; + +class Main { + static function main() { + var data = haxe.io.Bytes.ofString("The quick brown fox jumps over the lazy dog"); + var crc = haxe.crypto.Crc32.make(data); + Sys.println(crc.hex()); + } +} diff --git a/Task/CRC-32/Rebol/crc-32.rebol b/Task/CRC-32/Rebol/crc-32.rebol new file mode 100644 index 0000000000..ac677bfc59 --- /dev/null +++ b/Task/CRC-32/Rebol/crc-32.rebol @@ -0,0 +1,4 @@ +sum: checksum "The quick brown fox jumps over the lazy dog" 'crc32 +;== 1095738169 +enbase sum 16 ;; available since 3.19.5 +;== "414FA339" diff --git a/Task/CRC-32/UNIX-Shell/crc-32-1.sh b/Task/CRC-32/UNIX-Shell/crc-32-1.sh new file mode 100644 index 0000000000..d3f1b53f48 --- /dev/null +++ b/Task/CRC-32/UNIX-Shell/crc-32-1.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +declare -i -a CRC32_LOOKUP_TABLE + +__generate_crc_lookup_table() { + local -i -r LSB_CRC32_POLY=0xEDB88320 # The CRC32 polynomal LSB order + local -i index byte lsb + for index in {0..255}; do + ((byte = 255 - index)) + for _ in {0..7}; do # 8-bit lsb shift + ((lsb = byte & 0x01, byte = ((byte >> 1) & 0x7FFFFFFF) ^ (lsb == 0 ? LSB_CRC32_POLY : 0))) + done + ((CRC32_LOOKUP_TABLE[index] = byte)) + done +} +__generate_crc_lookup_table +typeset -r CRC32_LOOKUP_TABLE + +crc32_string() { + [[ ${#} -eq 1 ]] || return + local -i i byte crc=0xFFFFFFFF index + for ((i = 0; i < ${#1}; i++)); do + byte=$(printf '%d' "'${1:i:1}") # Get byte value of character at i + ((index = (crc ^ byte) & 0xFF, crc = (CRC32_LOOKUP_TABLE[index] ^ (crc >> 8)) & 0xFFFFFFFF)) + done + echo $((crc ^ 0xFFFFFFFF)) +} + +printf 'The CRC32 of: %s\nis: 0x%08x\n' "${1}" "$(crc32_string "${1}")" + +# crc32_string "The quick brown fox jumps over the lazy dog" +# yields 414fa339 diff --git a/Task/CRC-32/UNIX-Shell/crc-32-2.sh b/Task/CRC-32/UNIX-Shell/crc-32-2.sh new file mode 100644 index 0000000000..79918e4f81 --- /dev/null +++ b/Task/CRC-32/UNIX-Shell/crc-32-2.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env sh +# POSIX Shell CRC32 of string +# @Name: crc32.sh +# @Version: 1.0.1 +# @Author: Léa Gris +# @Date: Wed, 27 Mar 2019 +# @License: WTFPL http://www.wtfpl.net/ + +# POSIX Shell has no array or string index +# Implementing a pre-computed CRC32 byte indexed look-up table +# would cost more CPU cycles calling external tools like +# awk or tr to index records from a string. + +# Computes the CRC32 of the input data stream +# <&1: The input data stream +# >&1: The CRC32 integer of the input data stream +crc32_stream() { + crc=0xFFFFFFFF # The Initial CRC32 value + p=0xedb88320 # The CRC32 polynomial + r=0 # The polynomial reminder + c='' # The current character + byte=0 # The byte value of the current character + # Iterates each character of the input stream + while c="$(dd bs=1 count=1 2>/dev/null)" && [ -n "$c" ]; do + byte=$(printf '%d' "'$c") # Converts the character into its byte value + r=$(((crc & 0xff) ^ byte)) # XOR LSB of CRC with current byte + # 8-bit lsb shift with XOR polynomial reminder when odd + for _ in _ _ _ _ _ _ _ _; do + t=$((r >> 1)) + r=$(((r & 1) ? t ^ p : t)) + done + crc=$(((crc >> 8) ^ r)) # XOR MSB of CRC with Reminder + done + + # Output CRC32 integer XOR mask 32 bits + echo $((crc ^ 0xFFFFFFFF)) +} + +# Computes the CRC32 of the argument string +# 1: The argument string +# >&1: The CRC32 integer of the argument string +crc32_string() { + [ $# -eq 1 ] || return # argument required + # Streams with printf to prevent suffixing the string + # with a newline, since echo -n is not available in POSIX Shell + printf '%s' "$1" | crc32_stream +} + +printf 'The CRC32 of: %s\nis: %08x\n' "$1" "$(crc32_string "$1")" + +# crc32_string "The quick brown fox jumps over the lazy dog" +# yields 414fa339 diff --git a/Task/CRC-32/Uiua/crc-32.uiua b/Task/CRC-32/Uiua/crc-32.uiua new file mode 100644 index 0000000000..c43fd20584 --- /dev/null +++ b/Task/CRC-32/Uiua/crc-32.uiua @@ -0,0 +1,8 @@ +String ← "The quick brown fox jumps over the lazy dog" +Key ← ⋕₁₆"1db710640" +InitCRC ← ⋕₁₆"ffffffff" +Xor ← °⋯⬚0≡≠∩⋯ +ShR ← ⍜⋯(⬚0˜↻)⊃⋅∘∘ +Table ← ≡⍥₈(ShR1 ⍥(Xor Key)⊸◿2)⇡256 +⍢(Xor⊃(ShR8|˜⊡Table Xor◿256)⊙°⊂|>0⧻◌) InitCRC -@\0String +°⋕₁₆⍜⋯¬⊙◌ diff --git a/Task/CRC-32/VBScript/crc-32.vbs b/Task/CRC-32/VBScript/crc-32.vbs new file mode 100644 index 0000000000..7f74ce3533 --- /dev/null +++ b/Task/CRC-32/VBScript/crc-32.vbs @@ -0,0 +1,32 @@ +dim crctbl(255) +const crcc =&hEDB88320 + +sub gencrctable +for i= 0 to 255 + k=i + for j=1 to 8 + if k and 1 then + k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) + k=k xor crcc + else + k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) + end if + next ' j + crctbl(i)=k + next +end sub + + function crc32 (buf) + dim r,r1,i + r=&hffffffff + for i=1 to len(buf) + r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0) + r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) + next + crc32=r xor &hffffffff +end function + + +'414FA339 +gencrctable +wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog")) diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.adb b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.adb new file mode 100644 index 0000000000..66d0814c1a --- /dev/null +++ b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.adb @@ -0,0 +1,19 @@ +package CSV is + + type Row(<>) is tagged private; + + function Line(S: String; Separator: Character := ',') return Row; + function Next(R: in out Row) return Boolean; + -- if there is still an item in R, Next advances to it and returns True + function Item(R: Row) return String; + -- after calling R.Next i times, this returns the i'th item (if any) + +private + type Row(Length: Natural) is tagged record + Str: String(1 .. Length); + Fst: Positive; + Lst: Natural; + Nxt: Positive; + Sep: Character; + end record; +end CSV; diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.adb b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.adb new file mode 100644 index 0000000000..d3be3a211f --- /dev/null +++ b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.adb @@ -0,0 +1,24 @@ +package body CSV is + + function Line(S: String; Separator: Character := ',') + return Row is + (Length => S'Length, Str => S, + Fst => S'First, Lst => S'Last, Nxt => S'First, Sep => Separator); + + function Item(R: Row) return String is + (R.Str(R.Fst .. R.Lst)); + + function Next(R: in out Row) return Boolean is + Last: Natural := R.Nxt; + begin + R.Fst := R.Nxt; + while Last <= R.Str'Last and then R.Str(Last) /= R.Sep loop + -- find Separator + Last := Last + 1; + end loop; + R.Lst := Last - 1; + R.Nxt := Last + 1; + return (R.Fst <= R.Str'Last); + end Next; + +end CSV; diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.adb b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.adb new file mode 100644 index 0000000000..f402572d3f --- /dev/null +++ b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.adb @@ -0,0 +1,19 @@ +with CSV, Ada.Text_IO; use Ada.Text_IO; + +procedure CSV_Data_Manipulation is + Header: String := Get_Line; +begin + Put_Line(Header & ", SUM"); + while not End_Of_File loop + declare + R: CSV.Row := CSV.Line(Get_Line); + Sum: Integer := 0; + begin + while R.Next loop + Sum := Sum + Integer'Value(R.Item); + Put(R.Item & ","); + end loop; + Put_Line(Integer'Image(Sum)); + end; + end loop; +end CSV_Data_Manipulation; diff --git a/Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cob b/Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cob new file mode 100644 index 0000000000..c35b4d5f9e --- /dev/null +++ b/Task/CSV-data-manipulation/COBOL/csv-data-manipulation.cob @@ -0,0 +1,93 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. CSV. + AUTHOR. Bill Gunshannon. + INSTALLATION. Home. + DATE-WRITTEN. 19 December 2021. + ************************************************************ + ** Program Abstract: + ** CSVs are something COBOL does pretty well. + ** The commented out CONCATENATE statements are a + ** second method other than the STRING method. + ************************************************************ + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION ALL INTRINSIC. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT CSV-File ASSIGN TO "csv.txt" + ORGANIZATION IS LINE SEQUENTIAL. + SELECT Out-File ASSIGN TO "new.csv.txt" + ORGANIZATION IS LINE SEQUENTIAL. + + + DATA DIVISION. + + FILE SECTION. + + FD CSV-File + DATA RECORD IS CSV-Record. + 01 CSV-Record. + 05 Field1 PIC X(64). + + FD Out-File + DATA RECORD IS Out-Line. + 01 Out-Line PIC X(80). + + WORKING-STORAGE SECTION. + + 01 Eof PIC X VALUE 'F'. + + 01 CSV-Data. + 05 CSV-Col1 PIC 9(5). + 05 CSV-Col2 PIC 9(5). + 05 CSV-Col3 PIC 9(5). + 05 CSV-Col4 PIC 9(5). + 05 CSV-Col5 PIC 9(5). + + 01 CSV-Sum PIC ZZZ9. + 01 CSV-Sum-Alpha + REDEFINES CSV-Sum PIC X(4). + + PROCEDURE DIVISION. + + Main-Program. + OPEN INPUT CSV-File + OPEN OUTPUT Out-File + PERFORM Read-a-Record + PERFORM Build-Header + PERFORM UNTIL Eof = 'T' + PERFORM Read-a-Record + IF Eof NOT EQUAL 'T' PERFORM Process-a-Record + END-PERFORM + CLOSE CSV-File + CLOSE Out-File + STOP RUN. + + Read-a-Record. + READ CSV-File + AT END MOVE 'T' TO Eof + END-READ. + + Build-Header. + ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" + ** TO Out-Line. + STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. + WRITE Out-Line. + MOVE SPACES TO Out-Line. + + Process-a-Record. + UNSTRING CSV-Record DELIMITED BY ',' INTO + CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. + COMPUTE CSV-Sum = + CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. + ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) + ** TO Out-Line. + STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) + INTO Out-Line. + WRITE Out-Line. + MOVE SPACES TO Out-Line. + + END-PROGRAM. diff --git a/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.eu b/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.eu new file mode 100644 index 0000000000..66f5a8b1dd --- /dev/null +++ b/Task/CSV-data-manipulation/Euphoria/csv-data-manipulation.eu @@ -0,0 +1,91 @@ +--- Read CSV file and add columns headed with 'SUM' +--- with trace +-- trace(0) + +include get.e +include std/text.e + +function split(sequence s, integer c) + sequence removables = " \t\n\r\x05\u0234\" " + sequence out + integer first, delim + out = {} + first = 1 + while first <= length(s) do + delim = find_from(c,s,first) + if delim = 0 then + delim = length(s)+1 + end if + out = append(out,trim(s[first..delim-1],removables)) + first = delim + 1 + end while + return out +end function + +procedure main() + integer fn -- the file number + integer fn2 -- the output file number + integer e -- the number of lines read + object line -- the next line from the file + sequence data = {} -- parsed csv data row + sequence headerNames = {} -- array saving column names + atom sum = 0.0 -- sum for each row + sequence var -- holds numerical data read + + -- First we try to open the file called "data.csv". + fn = open("data.csv", "r") + if fn = -1 then + puts(1, "Can't open data.csv\n") + -- abort(); + end if + + -- Then we create an output file for processed data. + fn2 = open("newdata.csv", "w") + if fn2 = -1 then + puts(1, "Can't create newdata.csv\n") + end if + + -- By successfully opening the file we have established that + -- the file exists, and open() gives us a file number (or "handle") + -- that we can use to perform operations on the file. + + e = 1 + while 1 do + line = gets(fn) + if atom(line) then + exit + end if + data = split(line, ',') + + if (e=1) then + -- Save the header labels and + -- write them to output file. + headerNames = data + for i=1 to length(headerNames) do + printf(fn2, "%s,", {headerNames[i]}) + end for + printf(fn2, "SUM\n") + end if + + -- Run a sum for the numerical data. + if (e >= 2) then + for i=1 to length(data) do + printf(fn2, "%s,", {data[i]}) + var = value(data[i]) + if var[1] = 0 then + -- data read is numerical + -- add to sum + sum = sum + var[2] + end if + end for + printf(fn2, "%g\n", {sum}) + sum = 0.0 + end if + e = e + 1 + end while + + close(fn) + close(fn2) +end procedure + +main() diff --git a/Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.ps1 b/Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.ps1 new file mode 100644 index 0000000000..3623ef05e8 --- /dev/null +++ b/Task/CSV-data-manipulation/PowerShell/csv-data-manipulation.ps1 @@ -0,0 +1,33 @@ +## Create a CSV file +@" +C1,C2,C3,C4,C5 +1,5,9,13,17 +2,6,10,14,18 +3,7,11,15,19 +4,8,12,16,20 +"@ -split "`r`n" | Out-File -FilePath .\Temp.csv -Force + +## Import each line of the CSV file into an array of PowerShell objects +$records = Import-Csv -Path .\Temp.csv + +## Sum the values of the properties of each object +$sums = $records | ForEach-Object { + [int]$sum = 0 + foreach ($field in $_.PSObject.Properties.Name) + { + $sum += $_.$field + } + $sum +} + +## Add a column (Sum) and its value to each object in the array +$records = for ($i = 0; $i -lt $sums.Count; $i++) +{ + $records[$i] | Select-Object *,@{Name='Sum';Expression={$sums[$i]}} +} + +## Export the array of modified objects to the CSV file +$records | Export-Csv -Path .\Temp.csv -Force + +## Display the object in tabular form +$records | Format-Table -AutoSize diff --git a/Task/CSV-data-manipulation/Python/csv-data-manipulation-4.py b/Task/CSV-data-manipulation/Python/csv-data-manipulation-4.py new file mode 100644 index 0000000000..a35b14ce8d --- /dev/null +++ b/Task/CSV-data-manipulation/Python/csv-data-manipulation-4.py @@ -0,0 +1,9 @@ +import polars as pl + +filepath = "data.csv" + +( + pl.scan_csv(filepath) + .with_columns(pl.sum_horizontal(pl.all()).alias("SUM")) + .sink_csv(filepath) +) diff --git a/Task/CSV-data-manipulation/Rebol/csv-data-manipulation.rebol b/Task/CSV-data-manipulation/Rebol/csv-data-manipulation.rebol new file mode 100644 index 0000000000..5f0eab3980 --- /dev/null +++ b/Task/CSV-data-manipulation/Rebol/csv-data-manipulation.rebol @@ -0,0 +1,35 @@ +Rebol [ + title: "Rosetta code: CSV data manipulation" + file: %CSV_data_manipulation.r3 + url: https://rosettacode.org/wiki/CSV_data_manipulation +] + +write %test.csv {C1,C2,C3,C4,C5 +1,5,9,13,17 +2,6,10,14,18 +3,7,11,15,19 +4,8,12,16,20} ;; create a sample CSV file on disk + +probe-csv: func [data][ + foreach row data [probe row] ;; helper: print each parsed CSV row using probe +] + +import csv ;; enable CSV codec for load/save of CSV files + +data: load %test.csv ;; load CSV into a block of rows (row 1 is header) +print "^/Original:" probe-csv data ;; show original data + +;; Add SUM column: +append data/1 "SUM" ;; extend header with a new column "SUM" +foreach row next data [ ;; iterate over data rows (skip header) + sum: 0 + forall row [ ;; walk each cell in the row in place + change row to integer! row/1 ;; convert current cell to integer (mutates row) + sum: sum + row/1 ;; accumulate the running total + ] + append row sum ;; append the computed sum at the end of the row +] +print "^/Modified:" probe-csv data ;; show data after adding the SUM column + +save %new.csv data ;; save the modified data to a new CSV file +print "^/Reloaded:" probe-csv load %new.csv ;; reload and display to verify persistence diff --git a/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua b/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua index 9e4022ca99..e6b7e04c7f 100644 --- a/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua +++ b/Task/CSV-data-manipulation/Uiua/csv-data-manipulation.uiua @@ -7,5 +7,5 @@ $ 2,6,10,14,18 $ 3,7,11,15,19 $ 4,8,12,16,20 -&p⍜°csv(⍜⍉⊂:⊂□"SUM"≡(□⍜⋕/+)↘1.) +&p⍜°csv(⍜⍉˜⊂⊂□"SUM"≡(□⍜⋕/+)⊸↘1) # Save using `&fwa "example.csv"` diff --git a/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vbs b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vbs new file mode 100644 index 0000000000..00e334063a --- /dev/null +++ b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vbs @@ -0,0 +1,35 @@ +'Instatiate FSO. +Set objFSO = CreateObject("Scripting.FileSystemObject") +'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv. +Set objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",1,False) +'Set header status to account for the first line as the column headers. +IsHeader = True +'Initialize the var for the output string. +OutTxt = "" +'Read each line of the file. +Do Until objInCSV.AtEndOfStream + line = objInCSV.ReadLine + If IsHeader Then + OutTxt = OutTxt & line & ",SUM" & vbCrLf + IsHeader = False + Else + OutTxt = OutTxt & line & "," & AddElements(line) & vbCrLf + End If +Loop +'Close the file. +objInCSV.Close +'Open the same file for writing. +Set objOutCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",2,True) +'Write the var OutTxt to the file overwriting existing contents. +objOutCSV.Write OutTxt +'Close the file. +objOutCSV.Close +Set objFSO = Nothing + +'Routine to add each element in a row. +Function AddElements(s) + arr = Split(s,",") + For i = 0 To UBound(arr) + AddElements = AddElements + CInt(arr(i)) + Next +End Function diff --git a/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.adb b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.adb new file mode 100644 index 0000000000..158e12fe06 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-1.adb @@ -0,0 +1,40 @@ +with Ada.Strings.Fixed; +with Ada.Text_IO; +with Templates_Parser; + +procedure Csv2Html is + use type Templates_Parser.Vector_Tag; + + Chars : Templates_Parser.Vector_Tag; + Speeches : Templates_Parser.Vector_Tag; + + CSV_File : Ada.Text_IO.File_Type; +begin + -- read the csv data + Ada.Text_IO.Open (File => CSV_File, + Mode => Ada.Text_IO.In_File, + Name => "data.csv"); + + -- fill the tags + while not Ada.Text_IO.End_Of_File (CSV_File) loop + declare + Whole_Line : String := Ada.Text_IO.Get_Line (CSV_File); + Comma_Pos : Natural := Ada.Strings.Fixed.Index (Whole_Line, ","); + begin + Chars := Chars & Whole_Line (Whole_Line'First .. Comma_Pos - 1); + Speeches := Speeches & Whole_Line (Comma_Pos + 1 .. Whole_Line'Last); + end; + end loop; + + Ada.Text_IO.Close (CSV_File); + + -- build translation table and output html + declare + Translations : constant Templates_Parser.Translate_Table := + (1 => Templates_Parser.Assoc ("CHAR", Chars), + 2 => Templates_Parser.Assoc ("SPEECH", Speeches)); + begin + Ada.Text_IO.Put_Line + (Templates_Parser.Parse ("table.tmplt", Translations)); + end; +end Csv2Html; diff --git a/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.adb b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.adb new file mode 100644 index 0000000000..4126ce0394 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-2.adb @@ -0,0 +1,8 @@ + +@@TABLE@@ + + + + +@@END_TABLE@@ +
    @_WEB_ESCAPE:CHAR_@@_WEB_ESCAPE:SPEECH_@
    diff --git a/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.adb b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.adb new file mode 100644 index 0000000000..4238d95db6 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Ada/csv-to-html-translation-3.adb @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.au3 b/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.au3 new file mode 100644 index 0000000000..050b3b68a8 --- /dev/null +++ b/Task/CSV-to-HTML-translation/AutoIt/csv-to-html-translation.au3 @@ -0,0 +1,28 @@ + Local $ascarray[4] = [34,38,60,62] + $String = "Character,Speech" & @CRLF + $String &= "The multitude,The messiah! Show us the messiah!" & @CRLF + $String &= "Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!" & @CRLF + $String &= "The multitude,Who are you?" & @CRLF + $String &= "Brians mother,I'm his mother; that's who!" & @CRLF + $String &= "The multitude,Behold his mother! Behold his mother!" + For $i = 0 To UBound($ascarray) -1 + $String = Stringreplace($String, chr($ascarray[$i]), "&#"&$ascarray[$i]&";") + Next + $newstring = "" & @CRLF + $crlfsplit = StringSplit($String, @CRLF, 1) + For $i = 1 To $crlfsplit[0] + If $i = 1 Then $newstring &= "" & @CRLF + $newstring &= "" & @CRLF + $komsplit = StringSplit($crlfsplit[$i], ",") + For $k = 1 To $komsplit[0] + If $i = 1 Then + $newstring &= "" & @CRLF + Else + $newstring &= "" & @CRLF + EndIf + Next + $newstring &= "" & @CRLF + If $i = 1 Then $newstring &= "" & @CRLF + Next + $newstring &= "
    " &$komsplit[$k] & "" &$komsplit[$k] & "
    " + ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $newstring = ' & $newstring & @crlf & '>Error code: ' & @error & @crlf) ;### Debug Console diff --git a/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.eu b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.eu new file mode 100644 index 0000000000..6ab63d1683 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.eu @@ -0,0 +1,20 @@ +constant input = "Character,Speech\n" & + "The multitude,The messiah! Show us the messiah!\n" & + "Brians mother,Now you listen here! He's not the messiah; " & + "he's a very naughty boy! Now go away!\n" & + "The multitude,Who are you?\n" & + "Brians mother,I'm his mother; that's who!\n" & + "The multitude,Behold his mother! Behold his mother!" + +puts(1,"\n\n\n
    ") +for i = 1 to length(input) do + switch input[i] do + case '\n' then puts(1,"
    ") + case ',' then puts(1,"") + case '<' then puts(1,"<") + case '>' then puts(1,">") + case '&' then puts(1,"&") + case else puts(1,input[i]) + end switch +end for +puts(1,"
    ") diff --git a/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.eu b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.eu new file mode 100644 index 0000000000..0964db10ff --- /dev/null +++ b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.eu @@ -0,0 +1,8 @@ + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.ps1 b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.ps1 new file mode 100644 index 0000000000..41bdd3067e --- /dev/null +++ b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-1.ps1 @@ -0,0 +1 @@ +Import-Csv -Path .\csv_html_test.csv | ConvertTo-Html -Fragment | Out-File .\csv_html_test.html diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.ps1 b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.ps1 new file mode 100644 index 0000000000..30d5135ea8 --- /dev/null +++ b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-2.ps1 @@ -0,0 +1,13 @@ + ++++ + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.ps1 b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.ps1 new file mode 100644 index 0000000000..0d58c33260 --- /dev/null +++ b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-3.ps1 @@ -0,0 +1,9 @@ +$htmlformat = 'Csv to Html' +$htmlformat += '' +Import-Csv -Path .\csv_html_test.csv | ConvertTo-Html -Head $htmlformat -Body '

    Csv to Html

    ' | Out-File .\csv_html_test.html +Invoke-Expression .\csv_html_test.html diff --git a/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.ps1 b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.ps1 new file mode 100644 index 0000000000..0eae705991 --- /dev/null +++ b/Task/CSV-to-HTML-translation/PowerShell/csv-to-html-translation-4.ps1 @@ -0,0 +1,21 @@ + + + +Csv to Html + +

    Csv to Html

    + ++++ + + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    + diff --git a/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-1.rebol b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-1.rebol new file mode 100644 index 0000000000..406c067313 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-1.rebol @@ -0,0 +1,53 @@ +Rebol [ + title: "Rosetta code: CSV to HTML translation" + file: %CSV_to_HTML_translation.r3 + url: https://rosettacode.org/wiki/CSV_to_HTML_translation + needs: 3.15.0 ;; or something like that +] +import csv + +csv-to-html: function/with [ + "Generate string with html table from csv data file" + csv [string! file!] "input .csv data" +][ + escape-html csv + + data: decode 'csv csv + html: copy "^/" + + emit-row/head data/1 + foreach row next data [ emit-row row ] + emit
    +][ + html: none + emit: func [val][ + if block? val [val: ajoin val] + append html val + ] + emit-row: func[row /head][ + emit [""] + foreach col row [ + emit-tag either head ['th]['td] col + ] + emit "^/" + ] + emit-tag: func [tag content][ + emit [#"<" tag #">" content ""] + ] + escape-html: function/with [str][ + parse str [any[ + to esc [ + change #"<" "<" + | change #">" ">" + | change #"&" "&" + ] + ]] + ][ esc: charset "<>&" ] +] + +print csv-to-html {Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!} diff --git a/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-2.rebol b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-2.rebol new file mode 100644 index 0000000000..dfebcd13ff --- /dev/null +++ b/Task/CSV-to-HTML-translation/Rebol/csv-to-html-translation-2.rebol @@ -0,0 +1,8 @@ + + + + + + + +
    CharacterSpeech
    The multitudeThe messiah! Show us the messiah!
    Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
    The multitudeWho are you?
    Brians motherI'm his mother; that's who!
    The multitudeBehold his mother! Behold his mother!
    diff --git a/Task/CSV-to-HTML-translation/Uiua/csv-to-html-translation.uiua b/Task/CSV-to-HTML-translation/Uiua/csv-to-html-translation.uiua new file mode 100644 index 0000000000..8b7fe76408 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Uiua/csv-to-html-translation.uiua @@ -0,0 +1,9 @@ +$ Character,Speech +$ The multitude,The messiah! Show us the messiah! +$ Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +$ The multitude,Who are you? +$ Brians mother,I'm his mother; that's who! +$ The multitude,Behold his mother! Behold his mother! +⊜(□$"_"/◇⊂⊜(□$"_")⊸≠@,)⊸≠@\n +/◇$"_\n_" +&p$"\n\n_\n
    CharacterSpeech
    " diff --git a/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vbs b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vbs new file mode 100644 index 0000000000..33894748ed --- /dev/null +++ b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vbs @@ -0,0 +1,33 @@ +Set objfso = CreateObject("Scripting.FileSystemObject") + +parent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & "\" + +Set objcsv = objfso.OpenTextFile(parent_folder & "in.csv",1,False) +Set objhtml = objfso.OpenTextFile(paren_folder & "out.html",2,True) + +objhtml.Write(csv_to_html(objcsv.ReadAll)) + +objcsv.Close +objhtml.Close +Set objfso = Nothing + +Function csv_to_html(s) + row = Split(s,vbCrLf) + 'write the header + tmp = "" + For i = 0 To UBound(row) + field = Split(row(i),",") + If i = 0 Then + tmp = tmp & "" + Else + tmp = tmp & "" + End If + Next + 'write the footer + tmp = tmp & "
    " & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
    " & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
    " + csv_to_html = tmp +End Function + +Function replace_chars(s) + replace_chars = Replace(Replace(s,"<","<"),">",">") +End Function diff --git a/Task/CUSIP/ANSI-BASIC/cusip.basic b/Task/CUSIP/ANSI-BASIC/cusip.basic new file mode 100644 index 0000000000..13e8080304 --- /dev/null +++ b/Task/CUSIP/ANSI-BASIC/cusip.basic @@ -0,0 +1,63 @@ +100 REM CUSIP +110 DECLARE EXTERNAL SUB PrintVerdict +120 DECLARE EXTERNAL FUNCTION CusipCheckDigit +130 DECLARE EXTERNAL FUNCTION IsValidCusip +140 PRINT "CUSIP Verdict" +150 CALL PrintVerdict("037833100") +160 CALL PrintVerdict("17275R102") +170 CALL PrintVerdict("38259P508") +180 CALL PrintVerdict("594918104") +190 CALL PrintVerdict("68389X106") +200 CALL PrintVerdict("68389X105") +210 END +220 REM ** +230 EXTERNAL FUNCTION CusipCheckDigit(Cusip$) +240 LET I = 1 +250 LET Sum = 0 +260 LET L = LEN(Cusip$) +270 DO WHILE I < L +280 LET C$ = Cusip$(I:I) +290 IF ("0" <= C$) AND (C$ <= "9") THEN +300 LET V = VAL(C$) +310 ELSEIF ("A" <= C$) AND (C$ <= "Z") THEN +320 LET V = ORD(C$) - 65 + 10 +330 ELSEIF C$ = "*" THEN +340 LET V = 36 +350 ELSEIF C$ = "@" THEN +360 LET V = 37 +370 ELSEIF C$ = "#" THEN +380 LET V = 38 +390 ELSE +400 LET CusipCheckDigit = -1 +410 EXIT FUNCTION +420 END IF +430 IF MOD(I - 1, 2) = 1 THEN LET V = 2 * V +440 IF I <= 8 THEN LET Sum = Sum + INT(V / 10) + MOD(V, 10) +450 LET I = I + 1 +460 LOOP +470 IF I <> 9 THEN +480 LET CusipCheckDigit = -1 +490 ELSE +500 LET CusipCheckDigit = MOD(10 - MOD(Sum, 10), 10) +510 END IF +520 END FUNCTION +530 REM ** +540 EXTERNAL FUNCTION IsValidCusip (Cusip$) +550 LET Check = CusipCheckDigit(Cusip$) +560 IF Check < 0 THEN +570 LET IsValidCusip = 0 +580 ELSEIF Cusip$(9:9) = CHR$(48 + Check) THEN +590 LET IsValidCusip = -1 +600 ELSE +610 LET IsValidCusip = 0 +620 END IF +630 END FUNCTION +640 REM ** +650 EXTERNAL SUB PrintVerdict (Cusip$) +660 PRINT Cusip$; +670 IF IsValidCusip(Cusip$) <>0 THEN +680 PRINT " : Valid" +690 ELSE +700 PRINT " : Invalid" +710 END IF +720 END SUB diff --git a/Task/CUSIP/Ada/cusip.adb b/Task/CUSIP/Ada/cusip.adb new file mode 100644 index 0000000000..8ca355afe8 --- /dev/null +++ b/Task/CUSIP/Ada/cusip.adb @@ -0,0 +1,54 @@ +with Ada.Text_IO; + +procedure Cusip_Test is + use Ada.Text_IO; + + subtype Cusip is String (1 .. 9); + + function Check_Cusip (Code : Cusip) return Boolean is + Sum : Integer := 0; + V : Integer; + + begin + for I in Code'First .. Code'Last - 1 loop + case Code (I) is + when '0' .. '9' => + V := Character'Pos (Code (I)) - Character'Pos ('0'); + when 'A' .. 'Z' => + V := Character'Pos (Code (I)) - Character'Pos ('A') + 10; + when '*' => V := 36; + when '@' => V := 37; + when '#' => V := 38; + when others => return False; + end case; + + if I mod 2 = 0 then + V := V * 2; + end if; + + Sum := Sum + V / 10 + (V mod 10); + end loop; + + return (10 - (Sum mod 10)) mod 10 = + Character'Pos (Code (Code'Last)) - Character'Pos ('0'); + end Check_Cusip; + + type Cusip_Array is array (Natural range <>) of Cusip; + + Test_Array : Cusip_Array := + ("037833100", + "17275R102", + "38259P508", + "594918104", + "68389X106", + "68389X105"); +begin + for I in Test_Array'Range loop + Put (Test_Array (I) & ": "); + if Check_Cusip (Test_Array (I)) then + Put_Line ("valid"); + else + Put_Line ("not valid"); + end if; + end loop; +end Cusip_Test; diff --git a/Task/CUSIP/Crystal/cusip.cr b/Task/CUSIP/Crystal/cusip.cr new file mode 100644 index 0000000000..f601d4b0cf --- /dev/null +++ b/Task/CUSIP/Crystal/cusip.cr @@ -0,0 +1,28 @@ +def cusip_check (input) + return false unless input.size == 9 + sum = 0 + input.chars.each_with_index do |c, i| + break if i == 8 + v = case c + when .ascii_number? then c.to_i + when .ascii_uppercase? then c.ord - 'A'.ord + 10 + when '*' then 36 + when '@' then 37 + when '#' then 38 + else return false + end + v *= 2 if (i+1).even? + + sum += v // 10 + v % 10 + end + input[-1].to_i? == (10 - sum % 10) % 10 +end + +["037833100", + "17275R102", + "38259P508", + "594918104", + "68389X106", + "68389X105"].each do |cusip| + print cusip, ": ", cusip_check(cusip) ? "valid" : "invalid", "\n" +end diff --git a/Task/CUSIP/Loglan82/cusip.loglan82 b/Task/CUSIP/Loglan82/cusip.loglan82 new file mode 100644 index 0000000000..7a3a1210de --- /dev/null +++ b/Task/CUSIP/Loglan82/cusip.loglan82 @@ -0,0 +1,89 @@ +(* CUSIP *) + +block + + unit check_digit: function (cusip: string): integer; + var + sum, v, i_first, i_last, i: integer, + c: character, + check_needed: boolean, + ccusip: arrayof character; + begin + sum := 0; + ccusip := unpack(cusip); + i, i_first := lower(ccusip); + i_last := upper(ccusip); + check_needed := true; + while (i < i_last) and check_needed + do + c := ccusip(i); + if ord(c) >= ord('0') and ord(c) <= ord('9') + then + v := ord(c) - ord('0') + else + if ord('A') <= ord(c) and ord(c) <= ord('Z') + then + v := ord(c) - ord('A') + 10 + else + case c + when '*': v := 36; + when '@': v := 37; + when '#': v := 38; + otherwise + result := -1; + check_needed := false + esac + fi + fi; + if check_needed + then + if (i - i_first) mod 2 = 1 then v := 2 * v fi; + if i - i_first <= 7 then sum := sum + v div 10 + v mod 10 fi; + i := i + 1 + fi; + od; + if check_needed + then + if i - i_first =/= 8 + then + result := -1 + else + result := (10 - sum mod 10) mod 10 + fi; + fi; + end check_digit; + + unit is_valid: function (cusip: string): boolean; + var + check: integer, + ccusip: arrayof character; + begin + check := check_digit(cusip); + if check < 0 + then + result := false + else + ccusip := unpack(cusip); + result := ord(ccusip(lower(ccusip) + 8)) = ord('0') + check + fi; + end is_valid; + + unit write_verdict: procedure (cusip: string); + begin + if is_valid(cusip) + then + writeln(cusip, " : Valid") + else + writeln(cusip, " : Invalid") + fi + end write_verdict; + +begin + writeln("CUSIP Verdict"); + call write_verdict("037833100"); + call write_verdict("17275R102"); + call write_verdict("38259P508"); + call write_verdict("594918104"); + call write_verdict("68389X106"); + call write_verdict("68389X105"); +end; diff --git a/Task/CUSIP/Oberon-07/cusip.oberon b/Task/CUSIP/Oberon-07/cusip.oberon new file mode 100644 index 0000000000..23d635fd12 --- /dev/null +++ b/Task/CUSIP/Oberon-07/cusip.oberon @@ -0,0 +1,60 @@ +MODULE Cusip; (* validate CUSIP codes *) + IMPORT Strings, Out; + + CONST cusipBase = 39; + cusipLength = 9; + VAR cusipDigits : ARRAY cusipBase + 1 OF CHAR; (* 39 digits + trailing nul *) + + (* returns TRUE if cusip is a valid CUSIP code, FALSE otherwise *) + PROCEDURE isCusip( cusip : ARRAY OF CHAR ) : BOOLEAN; + VAR sum, digit, cPos, checkDigit : INTEGER; + isValid : BOOLEAN; + + (* returns the base 39 digit corresponding to a character of a CUSIP code *) + PROCEDURE cusipDigit( cChar : CHAR ) : INTEGER; + VAR digit, dPos : INTEGER; + BEGIN + digit := -999; + dPos := 0; + WHILE ( dPos <= cusipBase ) & ( digit < 0 ) DO + IF cusipDigits[ dPos ] = cChar THEN digit := dPos END; + INC( dPos ) + END + RETURN digit + END cusipDigit ; + + BEGIN + IF Strings.Length( cusip ) # cusipLength THEN + isValid := FALSE (* invalid length code *) + ELSE + (* CUSIP code has the correct length *) + sum := 0; + checkDigit := cusipDigit( cusip[ cusipLength - 1 ] ); + FOR cPos := 0 TO cusipLength - 2 DO + digit := cusipDigit( cusip[ cPos ] ); + IF ODD( cPos ) THEN digit := digit * 2 END; + INC( sum, ( digit DIV 10 ) + ( digit MOD 10 ) ) + END; + isValid := ( 10 - ( sum MOD 10 ) ) MOD 10 = checkDigit + END + RETURN isValid + END isCusip ; + + PROCEDURE testCusip( cusip : ARRAY OF CHAR ) ; + BEGIN + Out.String( cusip ); + IF isCusip( cusip ) THEN Out.String( " valid" ) ELSE Out.String( " invalid" ) END; + Out.Ln + END testCusip; + +BEGIN + + cusipDigits := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"; + + testCusip( "037833100" ); + testCusip( "17275R102" ); + testCusip( "38259P508" ); + testCusip( "594918104" ); + testCusip( "68389X106" ); + testCusip( "68389X105" ) +END Cusip. diff --git a/Task/CUSIP/Pascal-P/cusip.pas b/Task/CUSIP/Pascal-P/cusip.pas new file mode 100644 index 0000000000..34d081a34a --- /dev/null +++ b/Task/CUSIP/Pascal-P/cusip.pas @@ -0,0 +1,70 @@ +program cusip(output); + +const + cusiplen = 9; + +type + tcusip = array [1 .. cusiplen] of char; + + function cusipcheckdigit(cusip: tcusip): integer; + (* Check digit *) + var + i, sum, v: integer; + c: char; + contcheck: boolean; (* Continue checking? *) + begin + i := 1; + sum := 0; + contcheck := true; + while (i <= cusiplen) and contcheck do + begin + c := cusip[i]; + if ('0' <= c) and (c <= '9') then v := ord(c) - 48 + else if ('A' <= c) and (c <= 'Z') then v := ord(c) - 65 + 10 + else if c = '*' then v := 36 + else if c = '@' then v := 37 + else if c = '#' then v := 38 + else + begin + cusipcheckdigit := -1; + contcheck := false; + end; + if contcheck then + begin + if (i - 1) mod 2 = 1 then v := 2 * v; + if i <= 8 then sum := sum + (v div 10) + (v mod 10); + i := i + 1; + end; + end; + if contcheck then + if i <> 10 then cusipcheckdigit := -1 + else cusipcheckdigit := (10 - (sum mod 10)) mod 10; + end; + + function isvalidcusip(cusip: tcusip): boolean; + var + check: integer; + begin + check := cusipcheckdigit(cusip); + if check < 0 then isvalidcusip := false + else isvalidcusip := (ord(cusip[9]) = ord(48 + check)); + end; + + procedure writeverdict(cusip: tcusip); + (* Write the verdict *) + begin + write(cusip); + if isvalidcusip(cusip) then writeln(' : Valid') + else writeln(' : Invalid'); + end; + +begin + writeln('CUSIP Verdict'); + writeverdict('037833100'); + writeverdict('17275R102'); + writeverdict('38259P508'); + writeverdict('594918104'); + writeverdict('68389X106'); + writeverdict('68389X105'); + (* readln; *) +end. diff --git a/Task/CUSIP/Pluto/cusip.pluto b/Task/CUSIP/Pluto/cusip.pluto new file mode 100644 index 0000000000..63b90850a5 --- /dev/null +++ b/Task/CUSIP/Pluto/cusip.pluto @@ -0,0 +1,33 @@ +local function is_cusip(s) + if #s != 9 then return false end + local sum = 0 + for i = 1, 8 do + local c = s[i] + local v = switch true do + case c >= '0' and c <= '9' -> c:byte() - 48 + case c >= 'A' and c <= 'Z' -> c:byte() - 55 + case c == "*" -> 36 + case c == "@" -> 37 + case c == "#" -> 38 + default -> nil + end + if !v then return false end + if i % 2 == 0 then v = v * 2 end -- check if even as using 1-based indexing + sum += v // 10 + v % 10 + end + return s[9]:byte() - 48 == (10 - (sum % 10)) % 10 +end + +local candidates = { + "037833100", + "17275R102", + "38259P508", + "594918104", + "68389X106", + "68389X105" +} + +for candidates as candidate do + local b = is_cusip(candidate) ? "correct" : "incorrect" + print($"{candidate} -> {b}") +end diff --git a/Task/CUSIP/PowerShell/cusip.ps1 b/Task/CUSIP/PowerShell/cusip.ps1 new file mode 100644 index 0000000000..1a6c4cd1d3 --- /dev/null +++ b/Task/CUSIP/PowerShell/cusip.ps1 @@ -0,0 +1,48 @@ +function Get-CheckDigitCUSIP { + [CmdletBinding()] + [OutputType([int])] + Param ( # Validate input + [Parameter(Mandatory=$true, Position=0)] + [ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )] # @#* + [ValidateScript({$_.Length -eq 9})] + [string] + $cusip + ) + $sum = 0 + 0..7 | ForEach { $c = $cusip[$_] ; $v = $null + if ([Char]::IsDigit($c)) { $v = [char]::GetNumericValue($c) } + if ([Char]::IsLetter($c)) { $v = [int][char]$c - [int][char]'A' +10 } + if ($c -eq '*') { $v = 36 } + if ($c -eq '@') { $v = 37 } + if ($c -eq '#') { $v = 38 } + if($_ % 2){ $v += $v } + $sum += [int][Math]::Floor($v / 10 ) + ($v % 10) + } + [int]$checkDigit_calculated = ( 10 - ($sum % 10) ) % 10 + return( $checkDigit_calculated ) +} + +function Test-IsCUSIP { + [CmdletBinding()] + [OutputType([bool])] + Param ( + [Parameter(Mandatory=$true, Position=0)] + [ValidatePattern( '^[A-Z0-9@#*]{8}\d$' )] + [ValidateScript({$_.Length -eq 9})] + [string] + $cusip + ) + [int]$checkDigit_told = $cusip[-1].ToString() + $checkDigit_calculated = Get-CheckDigitCUSIP $cusip + ($checkDigit_calculated -eq $checkDigit_told) +} + +$data = @" +037833100`tApple Incorporated +17275R102`tCisco Systems +38259P508`tGoogle Incorporated +594918104`tMicrosoft Corporation +68389X106`tOracle Corporation (incorrect) +68389X105`tOracle Corporation +"@ -split "`n" +$data |%{ Test-IsCUSIP $_.Split("`t")[0] } diff --git a/Task/CUSIP/QuickBASIC/cusip.basic b/Task/CUSIP/QuickBASIC/cusip.basic new file mode 100644 index 0000000000..4bfa9ca77a --- /dev/null +++ b/Task/CUSIP/QuickBASIC/cusip.basic @@ -0,0 +1,61 @@ +' CUSIP +DECLARE SUB PrintVerdict (Cusip$) +DECLARE FUNCTION CusipCheckDigit% (Cusip$) +DECLARE FUNCTION IsValidCusip% (Cusip$) +CONST TRUE% = -1, FALSE% = 0 +PRINT "CUSIP Verdict" +PrintVerdict "037833100" +PrintVerdict "17275R102" +PrintVerdict "38259P508" +PrintVerdict "594918104" +PrintVerdict "68389X106" +PrintVerdict "68389X105" +END + +FUNCTION CusipCheckDigit% (Cusip$) + I% = 1 + Sum% = 0 + L% = LEN(Cusip$) + DO WHILE I% < L% + IF ("0" <= MID$(Cusip$, I%, 1)) AND (MID$(Cusip$, I%, 1) <= "9") THEN + V% = ASC(MID$(Cusip$, I%, 1)) - 48 ' 0 + ELSEIF ("A" <= MID$(Cusip$, I%, 1)) AND (MID$(Cusip$, I%, 1) <= "Z") THEN + V% = ASC(MID$(Cusip$, I%, 1)) - 65 + 10 + ELSEIF MID$(Cusip$, I%, 1) = "*" THEN + V% = 36 + ELSEIF MID$(Cusip$, I%, 1) = "@" THEN + V% = 37 + ELSEIF MID$(Cusip$, I%, 1) = "#" THEN + V% = 38 + ELSE + CusipCheckDigit% = -1 + EXIT FUNCTION + END IF + IF (I% - 1) MOD 2 = 1 THEN V% = 2 * V% + IF I% <= 8 THEN Sum% = Sum% + (V% \ 10) + (V% MOD 10) + I% = I% + 1 + LOOP + IF I% <> 9 THEN + CusipCheckDigit% = -1 + ELSE + CusipCheckDigit% = (10 - (Sum% MOD 10)) MOD 10 + END IF +END FUNCTION + +FUNCTION IsValidCusip% (Cusip$) + Check% = CusipCheckDigit%(Cusip$) + IF Check% < 0 THEN + IsValidCusip% = FALSE + ELSE + IsValidCusip% = (MID$(Cusip$, 9, 1) = CHR$(48 + Check%)) + END IF +END FUNCTION + +SUB PrintVerdict (Cusip$) + PRINT Cusip$; + IF IsValidCusip%(Cusip$) THEN + PRINT " : Valid" + ELSE + PRINT " : Invalid" + END IF +END SUB diff --git a/Task/Caesar-cipher/Ada/caesar-cipher.adb b/Task/Caesar-cipher/Ada/caesar-cipher.adb new file mode 100644 index 0000000000..2969e50b30 --- /dev/null +++ b/Task/Caesar-cipher/Ada/caesar-cipher.adb @@ -0,0 +1,58 @@ +-- Caesar Cipher Implementation in Ada + +with Ada.Text_IO; use Ada.Text_IO; + +procedure Caesar is + + -- Base function to encrypt a character + function Cipher(Char_To_Encrypt: Character; Shift: Integer; Base: Character) return Character is + Base_Pos : constant Natural := Character'Pos(Base); + begin + return Character'Val((Character'Pos(Char_To_Encrypt) + Shift - Base_Pos) mod 26 + Base_Pos); + end Cipher; + + -- Function to encrypt a character + function Encrypt_Char(Char_To_Encrypt: Character; Shift: Integer) return Character is + begin + case Char_To_Encrypt is + when 'A'..'Z' => + -- Encrypt uppercase letters + return Cipher (Char_To_Encrypt, Shift, 'A'); + when 'a'..'z' => + -- Encrypt lowercase letters + return Cipher (Char_To_Encrypt, Shift, 'a'); + when others => + -- Leave other characters unchanged + return Char_To_Encrypt; + end case; + end Encrypt_Char; + + -- Function to decrypt a character + function Decrypt_Char(Char_To_Decrypt: Character; Shift: Integer) return Character is + begin + return Encrypt_Char(Char_To_Decrypt, -Shift); + end Decrypt_Char; + + Message: constant String := Ada.Text_IO.Get_Line; + Shift: Positive := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher + -- Shift value (can be any positive integer) + + Encrypted_Message: String(Message'Range); + Decrypted_Message: String(Message'Range); +begin + -- Encrypt the message + for I in Message'Range loop + Encrypted_Message(I) := Encrypt_Char(Message(I), Shift); + end loop; + + -- Decrypt the encrypted message + for I in Message'Range loop + Decrypted_Message(I) := Decrypt_Char(Encrypted_Message(I), Shift); + end loop; + + -- Display results + Put_Line("Plaintext: " & Message); + Put_Line("Ciphertext: " & Encrypted_Message); + Put_Line("Decrypted Ciphertext: " & Decrypted_Message); + +end Caesar; diff --git a/Task/Caesar-cipher/AutoIt/caesar-cipher.au3 b/Task/Caesar-cipher/AutoIt/caesar-cipher.au3 new file mode 100644 index 0000000000..38bc2d140f --- /dev/null +++ b/Task/Caesar-cipher/AutoIt/caesar-cipher.au3 @@ -0,0 +1,32 @@ +$Caesar = Caesar("Hi", 2, True) +MsgBox(0, "Caesar", $Caesar) +Func Caesar($String, $int, $encrypt = True) + If Not IsNumber($int) Or Not StringIsDigit($int) Then Return SetError(1, 0, 0) + If $int < 1 Or $int > 25 Then Return SetError(2, 0, 0) + Local $sLetters, $x + $String = StringUpper($String) + $split = StringSplit($String, "") + For $i = 1 To $split[0] + If Asc($split[$i]) - 64 > 26 Or Asc($split[$i]) - 64 < 1 Then + $sLetters &= $split[$i] + ContinueLoop + EndIf + If $encrypt = True Then + $move = Asc($split[$i]) - 64 + $int + Else + $move = Asc($split[$i]) - 64 - $int + EndIf + If $move > 26 Then + $move -= 26 + ElseIf $move < 1 Then + $move += 26 + EndIf + While $move + $x = Mod($move, 26) + If $x = 0 Then $x = 26 + $sLetters &= Chr($x + 64) + $move = ($move - $x) / 26 + WEnd + Next + Return $sLetters +EndFunc ;==>Caesar diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher-1.cob b/Task/Caesar-cipher/COBOL/caesar-cipher-1.cob new file mode 100644 index 0000000000..02c1bfd4bd --- /dev/null +++ b/Task/Caesar-cipher/COBOL/caesar-cipher-1.cob @@ -0,0 +1,36 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. CAESAR. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 MSG PIC X(50) + VALUE "The quick brown fox jumped over the lazy dog.". + 01 OFFSET PIC 9(4) VALUE 7 USAGE BINARY. + 01 FROM-CHARS PIC X(52). + 01 TO-CHARS PIC X(52). + 01 TABL. + 02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz". + 02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ". + 02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz". + 02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ". + + PROCEDURE DIVISION. + BEGIN. + DISPLAY MSG + PERFORM ENCRYPT + DISPLAY MSG + PERFORM DECRYPT + DISPLAY MSG + STOP RUN. + + ENCRYPT. + MOVE TABL (1:52) TO FROM-CHARS + MOVE TABL (1 + OFFSET:52) TO TO-CHARS + INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS. + + DECRYPT. + MOVE TABL (1 + OFFSET:52) TO FROM-CHARS + MOVE TABL (1:52) TO TO-CHARS + INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS. + + END PROGRAM CAESAR. diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher-2.cob b/Task/Caesar-cipher/COBOL/caesar-cipher-2.cob new file mode 100644 index 0000000000..20f86ddb95 --- /dev/null +++ b/Task/Caesar-cipher/COBOL/caesar-cipher-2.cob @@ -0,0 +1,84 @@ + >>SOURCE FORMAT IS FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. caesar-cipher. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION encrypt + FUNCTION decrypt. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 plaintext PIC X(50). +01 offset USAGE BINARY-CHAR. +01 encrypted-str PIC X(50). + +PROCEDURE DIVISION. + DISPLAY "Enter a message to encrypt: " WITH NO ADVANCING + ACCEPT plaintext + DISPLAY "Enter the amount to shift by: " WITH NO ADVANCING + ACCEPT offset + MOVE encrypt(offset, plaintext) TO encrypted-str + DISPLAY "Encrypted: " encrypted-str + DISPLAY "Decrypted: " decrypt(offset, encrypted-str). + +END PROGRAM caesar-cipher. + +IDENTIFICATION DIVISION. +FUNCTION-ID. encrypt. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION ALL INTRINSIC. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 i USAGE INDEX. +01 a USAGE BINARY-CHAR. +LINKAGE SECTION. +01 offset USAGE BINARY-CHAR. +01 str PIC X(50). +01 encrypted-str PIC X(50). + +PROCEDURE DIVISION USING offset, str RETURNING encrypted-str. + PERFORM VARYING i FROM 1 BY 1 UNTIL i > LENGTH(str) + IF str(i:1) IS NOT ALPHABETIC OR str(i:1) = SPACE + MOVE str(i:1) TO encrypted-str(i:1) + EXIT PERFORM CYCLE + END-IF + IF str(i:1) IS ALPHABETIC-UPPER + MOVE ORD("A") TO a + ELSE + MOVE ORD("a") TO a + END-IF + MOVE CHAR(MOD(ORD(str(i:1)) - a + offset, 26) + a) + TO encrypted-str(i:1) + END-PERFORM + EXIT FUNCTION. + +END FUNCTION encrypt. + +IDENTIFICATION DIVISION. +FUNCTION-ID. decrypt. + +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION encrypt. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 decrypt-offset USAGE BINARY-CHAR. +LINKAGE SECTION. +01 offset USAGE BINARY-CHAR. +01 str PIC X(50). +01 decrypted-str PIC X(50). + +PROCEDURE DIVISION USING offset, str RETURNING decrypted-str. + SUBTRACT offset FROM 26 GIVING decrypt-offset + MOVE encrypt(decrypt-offset, str) TO decrypted-str + EXIT FUNCTION. + +END FUNCTION decrypt. diff --git a/Task/Caesar-cipher/Euphoria/caesar-cipher.eu b/Task/Caesar-cipher/Euphoria/caesar-cipher.eu new file mode 100644 index 0000000000..f7ca288339 --- /dev/null +++ b/Task/Caesar-cipher/Euphoria/caesar-cipher.eu @@ -0,0 +1,54 @@ +--caesar cipher for Rosetta Code wiki +--User:Lnettnay + +--usage eui caesar ->default text, key and encode flag +--usage eui caesar 'Text with spaces and punctuation!' 5 D +--If text has imbedded spaces must use apostophes instead of quotes so all punctuation works +--key = integer from 1 to 25, defaults to 13 +--flag = E (Encode) or D (Decode), defaults to E +--no error checking is done on key or flag + +include std/get.e +include std/types.e + + +sequence cmd = command_line() +sequence val +-- default text for encryption +sequence text = "The Quick Brown Fox Jumps Over The Lazy Dog." +atom key = 13 -- default to Rot-13 +sequence flag = "E" -- default to Encrypt +atom offset +atom num_letters = 26 -- number of characters in alphabet + +--get text +if length(cmd) >= 3 then + text = cmd[3] +end if + +--get key value +if length(cmd) >= 4 then + val = value(cmd[4]) + key = val[2] +end if + +--get Encrypt/Decrypt flag +if length(cmd) = 5 then + flag = cmd[5] + if compare(flag, "D") = 0 then + key = 26 - key + end if +end if + +for i = 1 to length(text) do + if t_alpha(text[i]) then + if t_lower(text[i]) then + offset = 'a' + else + offset = 'A' + end if + text[i] = remainder(text[i] - offset + key, num_letters) + offset + end if +end for + +printf(1,"%s\n",{text}) diff --git a/Task/Caesar-cipher/Langur/caesar-cipher.langur b/Task/Caesar-cipher/Langur/caesar-cipher.langur index 7b3a36cc20..447cb4856b 100644 --- a/Task/Caesar-cipher/Langur/caesar-cipher.langur +++ b/Task/Caesar-cipher/Langur/caesar-cipher.langur @@ -2,7 +2,7 @@ val rot = fn(s, key) { cp2s map(s2cp(s), by=fn(c) { rotate(rotate(c, distance=key, range='a'..'z'), distance=key, range='A'..'Z') }) } -val s = "A quick brown fox jumped over something, you know." +val s = "A quick brown fox jumped over something." val key = 3 writeln " original: ", s diff --git a/Task/Caesar-cipher/PowerShell/caesar-cipher.ps1 b/Task/Caesar-cipher/PowerShell/caesar-cipher.ps1 new file mode 100644 index 0000000000..4eb37cd988 --- /dev/null +++ b/Task/Caesar-cipher/PowerShell/caesar-cipher.ps1 @@ -0,0 +1,75 @@ +# Author: M. McNabb +function Get-CaesarCipher +{ +Param +( +[Parameter( +Mandatory=$true,ValueFromPipeline=$true)] +[string] +$Text, + +[ValidateRange(1,25)] +[int] +$Key = 1, + +[switch] +$Decode +) + +begin +{ + $LowerAlpha = [char]'a'..[char]'z' + $UpperAlpha = [char]'A'..[char]'Z' +} + +process +{ + $Chars = $Text.ToCharArray() + + function encode + { + param + ( + $Char, + $Alpha = [char]'a'..[char]'z' + ) + $Index = $Alpha.IndexOf([int]$Char) + $NewIndex = ($Index + $Key) - $Alpha.Length + $Alpha[$NewIndex] + } + + function decode + { + param + ( + $Char, + $Alpha = [char]'a'..[char]'z' + ) + $Index = $Alpha.IndexOf([int]$Char) + $int = $Index - $Key + if ($int -lt 0) {$NewIndex = $int + $Alpha.Length} + else {$NewIndex = $int} + $Alpha[$NewIndex] + } + + foreach ($Char in $Chars) + { + if ([int]$Char -in $LowerAlpha) + { + if ($Decode) {$Char = decode $Char} + else {$Char = encode $Char} + } + elseif ([int]$Char -in $UpperAlpha) + { + if ($Decode) {$Char = decode $Char $UpperAlpha} + else {$Char = encode $Char $UpperAlpha} + } + + $Char = [char]$Char + [string]$OutText += $Char + } + + $OutText + $OutText = $null +} +} diff --git a/Task/Caesar-cipher/Rebol/caesar-cipher.rebol b/Task/Caesar-cipher/Rebol/caesar-cipher.rebol new file mode 100644 index 0000000000..80053bbce7 --- /dev/null +++ b/Task/Caesar-cipher/Rebol/caesar-cipher.rebol @@ -0,0 +1,37 @@ +Rebol [ + title: "Rosetta code: Caesar cipher" + file: %Caesar_cipher.r3 + url: https://rosettacode.org/wiki/Caesar_cipher + needs: 3.0.0 + note: {Based on Red language version} +] + +caesar: function/with [ + src [string!] + key [integer!] +][ + parse/case src [ + any [ + change s: [lower (o: #"a") | upper (o: #"A")] (rot s/1 key o) + | skip + ] + ] + src +][ + lower: charset [#"a" - #"z"] + upper: charset [#"A" - #"Z"] + rot: func [ + char [char!] + key [number!] + ofs [char!] + ][ + to char! key + char - ofs // 26 + ofs + ] +] + +encrypt: :caesar +decrypt: func spec-of :caesar [caesar src negate key] + +;; DEMO: +print encrypt "Ceasar Cipher" 4 ;== Giewev Gmtliv +print decrypt "Giewev Gmtliv" 4 ;== Ceasar Cipher diff --git a/Task/Caesar-cipher/SheerPower-4GL/caesar-cipher.4gl b/Task/Caesar-cipher/SheerPower-4GL/caesar-cipher.4gl new file mode 100644 index 0000000000..0e623ae1f1 --- /dev/null +++ b/Task/Caesar-cipher/SheerPower-4GL/caesar-cipher.4gl @@ -0,0 +1,46 @@ +declare string plaintext$, ciphertext$, decrypted$ + +plaintext$ = 'The Quick Brown Fox Jumps Over The Lazy Dog' + +print 'Plaintext: '; plaintext$ + +ciphertext$ = caesar$(plaintext$, 13) +print 'ROT13: '; ciphertext$ + +decrypted$ = caesar$(ciphertext$, 13) +print 'Decrypted: '; decrypted$ + +print +print 'Shift 3 example (classic Caesar):' +ciphertext$ = caesar$('Attack at dawn', 3) +print 'Encrypted: '; ciphertext$ +print 'Decrypted: '; caesar$(ciphertext$, 23) + +! ============================================================================= +! Routine: caesar$(text$, shift%) +! +! Shift each letter in text$ by shift% positions. A–Z and a–z wrap +! within their own ranges; all other characters are copied unchanged. +! ============================================================================= +routine caesar$(text$, shift%) + declare string result$, ch$ + declare integer i%, code% + + result$ = '' + for i% = 1 to len(text$) + ch$ = mid$(text$, i%, 1) + code% = ord(ch$) + + if code% >= 65 and code% <= 90 then + ! Uppercase A–Z: rotate within 65–90 + result$ = result$ + chr$((code% - 65 + shift%) mod 26 + 65) + elseif code% >= 97 and code% <= 122 then + ! Lowercase a–z: rotate within 97–122 + result$ = result$ + chr$((code% - 97 + shift%) mod 26 + 97) + else + ! Non-letter: pass through unchanged + result$ = result$ + ch$ + end if + next i% + caesar$ = result$ +end routine diff --git a/Task/Caesar-cipher/Uiua/caesar-cipher.uiua b/Task/Caesar-cipher/Uiua/caesar-cipher.uiua new file mode 100644 index 0000000000..4f3720c52e --- /dev/null +++ b/Task/Caesar-cipher/Uiua/caesar-cipher.uiua @@ -0,0 +1,7 @@ +k ← 3 +m ← -:26 k +Rot ← +@A◿26+k-@A +Rrot ← +@A◿26+m-@A +&sc +&p. ⍥(¯≡(⍥Rot=1±.))2 +&p ⍥(¯≡(⍥Rrot=1±.))2 diff --git a/Task/Caesar-cipher/V-(Vlang)/caesar-cipher.v b/Task/Caesar-cipher/V-(Vlang)/caesar-cipher.v index c6a0c8b57c..6be2839b81 100644 --- a/Task/Caesar-cipher/V-(Vlang)/caesar-cipher.v +++ b/Task/Caesar-cipher/V-(Vlang)/caesar-cipher.v @@ -1,9 +1,7 @@ import rand -const ( - lo_abc = 'abcdefghijklmnopqrstuvwxyz' - up_abc = 'ABCDEFGHIJKLMNIPQRSTUVWXYZ' -) +const lo_abc = 'abcdefghijklmnopqrstuvwxyz' +const up_abc = 'ABCDEFGHIJKLMNIPQRSTUVWXYZ' fn main() { key := rand.int_in_range(2, 25) or {13} diff --git a/Task/Caesar-cipher/VBScript/caesar-cipher.vbs b/Task/Caesar-cipher/VBScript/caesar-cipher.vbs new file mode 100644 index 0000000000..73b7fd082c --- /dev/null +++ b/Task/Caesar-cipher/VBScript/caesar-cipher.vbs @@ -0,0 +1,35 @@ + str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES." + + Wscript.Echo str + Wscript.Echo Rotate(str,5) + Wscript.Echo Rotate(Rotate(str,5),-5) + + 'Rotate (Caesar encrypt/decrypt) test positions. + ' numpos < 0 - rotate left + ' numpos > 0 - rotate right + 'Left rotation is converted to equivalent right rotation + + Function Rotate (text, numpos) + + dim dic: set dic = CreateObject("Scripting.Dictionary") + dim ltr: ltr = Split("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z") + dim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation + dim ch + dim i + + for i = 0 to ubound(ltr) + dic(ltr(i)) = ltr((rot+i) Mod 26) + next + + Rotate = "" + + for i = 1 to Len(text) + ch = Mid(text,i,1) + if dic.Exists(ch) Then + Rotate = Rotate & dic(ch) + else + Rotate = Rotate & ch + end if + next + + End Function diff --git a/Task/Calculating-the-value-of-e/Ada/calculating-the-value-of-e.adb b/Task/Calculating-the-value-of-e/Ada/calculating-the-value-of-e.adb new file mode 100644 index 0000000000..d645fa8bfb --- /dev/null +++ b/Task/Calculating-the-value-of-e/Ada/calculating-the-value-of-e.adb @@ -0,0 +1,25 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO; + +procedure Euler is + Epsilon : constant := 1.0E-15; + Fact : Long_Integer := 1; + E : Long_Float := 2.0; + E0 : Long_Float := 0.0; + N : Long_Integer := 2; + +begin + + loop + E0 := E; + Fact := Fact * N; + N := N + 1; + E := E + (1.0 / Long_Float (Fact)); + exit when abs (E - E0) < Epsilon; + end loop; + + Put ("e = "); + Put (E, 0, 15, 0); + New_Line; + +end Euler; diff --git a/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cob b/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cob new file mode 100644 index 0000000000..d20ba6e3fe --- /dev/null +++ b/Task/Calculating-the-value-of-e/COBOL/calculating-the-value-of-e.cob @@ -0,0 +1,23 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. euler. + DATA DIVISION. + WORKING-STORAGE SECTION. + 77 epsilon USAGE FLOAT-LONG VALUE IS 1.0E-15. + 77 fact USAGE IS BINARY-DOUBLE UNSIGNED VALUE IS 1. + 77 n USAGE IS BINARY-LONG UNSIGNED. + 77 e USAGE IS FLOAT-LONG VALUE IS 2.0. + 77 e0 USAGE IS FLOAT-LONG VALUE IS 0.0. + 01 result-message. + 03 FILLER PICTURE IS X(4) VALUE IS 'e = '. + 03 result-value PICTURE IS 9.9(18) USAGE IS DISPLAY. + PROCEDURE DIVISION. + PERFORM WITH TEST BEFORE VARYING n FROM 2 BY 1 + UNTIL FUNCTION ABS(e - e0) IS LESS THAN epsilon + MOVE e TO e0 + MULTIPLY n BY fact + COMPUTE e = e + 1.0 / fact + END-PERFORM. + MOVE e TO result-value. + DISPLAY result-message. + STOP RUN. + END PROGRAM euler. diff --git a/Task/Calculating-the-value-of-e/Emacs-Lisp/calculating-the-value-of-e.el b/Task/Calculating-the-value-of-e/Emacs-Lisp/calculating-the-value-of-e.el new file mode 100644 index 0000000000..e12d50bd96 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Emacs-Lisp/calculating-the-value-of-e.el @@ -0,0 +1,10 @@ +(defun factorial (i) + "Compute factorial of i." + (apply #'* (number-sequence 1 i))) + +(defun compute-e (iter) + "Compute e." + (apply #'+ 1 (mapcar (lambda (x) (/ 1.0 x)) + (mapcar #'factorial (number-sequence 1 iter))))) + +(compute-e 20) diff --git a/Task/Calculating-the-value-of-e/Euphoria/calculating-the-value-of-e.eu b/Task/Calculating-the-value-of-e/Euphoria/calculating-the-value-of-e.eu new file mode 100644 index 0000000000..19492b0e56 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Euphoria/calculating-the-value-of-e.eu @@ -0,0 +1,23 @@ +include std/math.e + +-- native +? E +? exp(1) + +-- calculated +atom n, n1 +atom e1, e + +n = 1.0 +n1 = 1.0 +e1 = 0.0 +e = 1.0 + +while (e != e1) do + e1 = e + e += (1.0 / n) + n1 += 1 + n *= n1 +end while + +? e diff --git a/Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e-1.f b/Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e-1.f new file mode 100644 index 0000000000..b5ea0e818d --- /dev/null +++ b/Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e-1.f @@ -0,0 +1,16 @@ +Program eee +implicit none +integer, parameter :: QP = selected_real_kind(16) +real(QP), parameter :: one = 1.0 +real(QP) :: ee + +write(*,*) ' exp(1.) ', exp(1._QP) + +ee = 1. +(one +(one +(one +(one +(one+ (one +(one +(one +(one +(one +(one & + +(one +(one +(one +(one +(one +(one +(one +(one +(one +(one) & + /21.)/20.)/19.)/18.)/17.)/16.)/15.)/14.)/13.)/12.)/11.)/10.)/9.) & + /8.)/7.)/6.)/5.)/4.)/3.)/2.) + +write(*,*) ' polynomial ', ee + +end Program eee diff --git a/Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e-2.f b/Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e-2.f new file mode 100644 index 0000000000..6501cc105a --- /dev/null +++ b/Task/Calculating-the-value-of-e/Fortran/calculating-the-value-of-e-2.f @@ -0,0 +1,32 @@ +program calculate_e + use iso_fortran_env, only: ep => real128 + implicit none + + integer :: n + real(kind=ep) :: sum_e, term, eps, c, y, t + real(kind=ep), parameter :: e_ref = 2.7182818284590452353602874713526624_ep + + sum_e = 0.0_ep + c = 0.0_ep + n = 0 + eps = epsilon(1.0_ep) + + do + term = 1.0_ep / gamma(real(n + 1, kind=ep)) + if (term < eps) exit + + ! Kahan summation to keep precision + y = term - c + t = sum_e + y + c = (t - sum_e) - y + sum_e = t + + n = n + 1 + end do + + write(*,'(a,t45,a)') 'Literature supplied value = ', & + '2.7182818284590452353602874713526624' + write(*,'(a,t41,F40.34)') 'Approximation of e using Taylor series = ', sum_e + write(*,'(a,t45,EN0.5)') 'Variance = ', abs(sum_e - e_ref) + write(*,*) 'Converged after', n, 'terms.' +end program calculate_e diff --git a/Task/Calculating-the-value-of-e/Liberty-BASIC/calculating-the-value-of-e.basic b/Task/Calculating-the-value-of-e/Liberty-BASIC/calculating-the-value-of-e.basic new file mode 100644 index 0000000000..83db0832f4 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Liberty-BASIC/calculating-the-value-of-e.basic @@ -0,0 +1,30 @@ +' Cálculo de e con alta precisión visual usando Brother's formula +eFLB = exp(1) +euler = 0 + +print "Primeras 10 aproximaciones con Fórmula de Brother" +print +print "Iter.", "Valor (14 decim)", "Error" +print "----------------------------------------------------------" + +for n = 0 to 10 + numerador = 2*n + 2 + denominador = factorial(2*n + 1) + termino = numerador / denominador + euler = euler + termino + diferencia = abs(euler - eFLB) + print n, using("#.##############", euler), diferencia ' Ver 14 decimales +next n + +print "----------------------------------------------------------" +print +print "Valor de la función LB exp(1): "; using("#.##############", eFLB) +end + +function factorial(num) + f = 1 + for i = 1 to num + f = f*i + next i + factorial = f +end function diff --git a/Task/Calculating-the-value-of-e/M2000-Interpreter/calculating-the-value-of-e-1.m2000 b/Task/Calculating-the-value-of-e/M2000-Interpreter/calculating-the-value-of-e-1.m2000 index 3971cc6e8c..25ce9e9897 100644 --- a/Task/Calculating-the-value-of-e/M2000-Interpreter/calculating-the-value-of-e-1.m2000 +++ b/Task/Calculating-the-value-of-e/M2000-Interpreter/calculating-the-value-of-e-1.m2000 @@ -1,17 +1,22 @@ Module FindE { - Function comp_e (n){ - \\ max 28 for decimal (in one line with less spaces) - n/=28:For i=27to 1:n=1+n/i:Next i:=n - } - Clipboard Str$(comp_e(1@),"")+" Decimal"+{ - }+Str$(comp_e(1),"")+" Double"+{ - }+Str$(comp_e(1~),"")+" Float"+{ - }+Str$(comp_e(1#),"")+" Currency"+{ - } - Report Str$(comp_e(1@),"")+" Decimal"+{ - }+Str$(comp_e(1),"")+" Double"+{ - }+Str$(comp_e(1~),"")+" Float"+{ - }+Str$(comp_e(1#),"")+" Currency"+{ - } + Function comp_e (n, decimals ){ + unit=n:n/=decimals:For i=decimals-1 to 1:n=Unit+n/i:Next i:=n + } + p=1000 + k=comp_e(biginteger("1"+string$("0", p)), p) + string t1=str$(k), t=left$(t1, 39) + if len(t1)>39 then + for i=40 to len(t1) step 40 + t+={ + }+mid$(t1, i, 40) + next + end if + all=(comp_e(1@, 28))+" Decimal"+{ + }+(comp_e(1, 19))+" Double"+{ + }+(comp_e(1~, 11))+" Float"+{ + }+(comp_e(1#, 8))+" Currency"+{ + }+ left$(t,1)+locale$(14)+mid$(t,2) +" Arbitrary-precision :"+p + Clipboard all + Report all } FindE diff --git a/Task/Calculating-the-value-of-e/Oberon-07/calculating-the-value-of-e.oberon b/Task/Calculating-the-value-of-e/Oberon-07/calculating-the-value-of-e.oberon new file mode 100644 index 0000000000..82212e18c0 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Oberon-07/calculating-the-value-of-e.oberon @@ -0,0 +1,25 @@ +MODULE CalculateE; +IMPORT Out; + +VAR + fact,n : INTEGER; + e,e0 : REAL; + +BEGIN + fact := 1; + e := 2.0; + e0 := 0.0; + n := 2; + + WHILE e > e0 DO + e0 := e; + fact := fact * n; + INC(n); + e := e + 1.0 / FLT(fact) + END; + + Out.String("e = ");Out.Real(e, 0); + Out.String(", ");Out.Int(n,0); + Out.String(" iterations");Out.Ln + +END CalculateE. diff --git a/Task/Calculating-the-value-of-e/Pluto/calculating-the-value-of-e.pluto b/Task/Calculating-the-value-of-e/Pluto/calculating-the-value-of-e.pluto new file mode 100644 index 0000000000..c9a4175a86 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Pluto/calculating-the-value-of-e.pluto @@ -0,0 +1,12 @@ +local epsilon = 1e-15 +local fact = 1 +local e = 2 +local n = 2 +while true do + local e0 = e + fact *= n + n += 1 + e += 1 / fact + if math.abs(e - e0) < epsilon then break end +end +print($"e = {e}") diff --git a/Task/Calculating-the-value-of-e/PowerShell/calculating-the-value-of-e.ps1 b/Task/Calculating-the-value-of-e/PowerShell/calculating-the-value-of-e.ps1 new file mode 100644 index 0000000000..2eeb482b39 --- /dev/null +++ b/Task/Calculating-the-value-of-e/PowerShell/calculating-the-value-of-e.ps1 @@ -0,0 +1,15 @@ +$e0 = 0 +$e = 2 +$n = 0 +$fact = 1 +while([Math]::abs($e-$e0) -gt 1E-15){ + $e0 = $e + $n += 1 + $fact *= 2*$n*(2*$n+1) + $e += (2*$n+2)/$fact +} + +Write-Host "Computed e = $e" +Write-Host " Real e = $([Math]::Exp(1))" +Write-Host " Error = $([Math]::Exp(1) - $e)" +Write-Host "Number of iterations = $n" diff --git a/Task/Calculating-the-value-of-e/Uiua/calculating-the-value-of-e.uiua b/Task/Calculating-the-value-of-e/Uiua/calculating-the-value-of-e.uiua new file mode 100644 index 0000000000..b4130396a0 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Uiua/calculating-the-value-of-e.uiua @@ -0,0 +1 @@ +&p $"e = _" /+⨪⊂1\×⇡₁17 diff --git a/Task/Calculating-the-value-of-e/VBScript/calculating-the-value-of-e.vbs b/Task/Calculating-the-value-of-e/VBScript/calculating-the-value-of-e.vbs new file mode 100644 index 0000000000..e70f5bdbf7 --- /dev/null +++ b/Task/Calculating-the-value-of-e/VBScript/calculating-the-value-of-e.vbs @@ -0,0 +1,12 @@ +e0 = 0 : e = 2 : n = 0 : fact = 1 +While (e - e0) > 1E-15 + e0 = e + n = n + 1 + fact = fact * 2*n * (2*n + 1) + e = e + (2*n + 2)/fact +Wend + +WScript.Echo "Computed e = " & e +WScript.Echo "Real e = " & Exp(1) +WScript.Echo "Error = " & (Exp(1) - e) +WScript.Echo "Number of iterations = " & n diff --git a/Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.adb b/Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.adb new file mode 100644 index 0000000000..5fc5d7f293 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Ada/calendar---for-real-programmers.adb @@ -0,0 +1,21 @@ +WITH PRINTABLE_CALENDAR; + +PROCEDURE REAL_CAL IS + + C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132 + ((WEEKDAY_REP => + "MO TU WE TH FR SA SO", + MONTH_REP => + (" JANUARY ", " FEBRUARY ", + " MARCH ", " APRIL ", + " MAY ", " JUNE ", + " JULY ", " AUGUST ", + " SEPTEMBER ", " OCTOBER ", + " NOVEMBER ", " DECEMBER ") + )); + +BEGIN + C.PRINT_LINE_CENTERED("[SNOOPY]"); + C.NEW_LINE; + C.PRINT(1969, "NINETEEN-SIXTY-NINE"); +END REAL_CAL; diff --git a/Task/Calendar---for-REAL-programmers/Rebol/calendar---for-real-programmers.rebol b/Task/Calendar---for-REAL-programmers/Rebol/calendar---for-real-programmers.rebol new file mode 100644 index 0000000000..9a8844469f --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Rebol/calendar---for-real-programmers.rebol @@ -0,0 +1,58 @@ +Rebol [ + title: {Rosetta code: Calendar - for "REAL" programmers} + file: %Calendar_for_REAL_programmers.r3 + url: https://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers + note: "Based on Red language implementation!" +] +REAL-CALENDAR: FUNCTION/WITH [YEAR [INTEGER!]][ + PRINT CENTR "[ S N O O P Y ]" 130 ; PRINT SNOOPY BLOCK CENTERED + PRINT CENTR TO-STRING Y 130 ; PRINT YEAR + + FOREACH R [[1 2 3 4 5 6][7 8 9 10 11 12]] [ + ; PRINT MONTH'S NAME + FOREACH M R [ + PRIN REJOIN [CENTR UPPERCASE MONTHS/:M 21 " "] + ] PRINT "" + + ; PRINT FOR EACH WEEK ACROSS MONTHS + FOREACH W [0 1 2 3 4 5 6] [ + ; EACH MONTHS + FOREACH M R [ + EITHER W = 0 [ ; PRINT WEEKDAYS + FOREACH D ["SU" "MO" "TU" "WE" "TH" "FR" "SA"] + [PRIN [FORM PAD D 3]] + ] [ + FOREACH WD [1 2 3 4 5 6 7] [ ; PRINT DATES + ; RECONSTRUCT THE DAY + EITHER 0 < DT: GETDAY Y M W WD [ + PRIN [FORM PAD DT -2] + ] [ + PRIN " " + ] PRIN " " + ] + ] PRIN " " + ] PRINT "" + ] PRINT "" + ] +][ + MONTHS: SYSTEM/LOCALE/MONTHS + ; GET DAY FROM YEAR, MONTH, WEEK, AND WEEKDAY! + GETDAY: FUNCTION [Y[INTEGER!] M[INTEGER!] W[INTEGER!] WD[INTEGER!]] [ + FD: TO-DATE REDUCE [1 M Y] ; FIRST DAY! + SWD: FD/WEEKDAY + 1 IF SWD > 7 [SWD: 1] ; SHIFT FROM MON=1 TO SUN=1 + OFS: (W - 1) * 7 + (WD - SWD) ; OFFSET + D: FD + OFS ; DATE + EITHER D/MONTH = M [D/DAY][0] ; RETURN DAY OR ZERO! + ] + + ; CENTER STRING + CENTR: FUNCTION [STR WID] [ + GAP: WID - LENGTH? STR + LPAD: TO-INTEGER GAP / 2 + PAD STR NEGATE (WID - LPAD) + PAD STR WID + ] +] + +;; DEMO: +REAL-CALENDAR 2015 diff --git a/Task/Calendar/Ada/calendar-1.adb b/Task/Calendar/Ada/calendar-1.adb new file mode 100644 index 0000000000..442ac4b3a0 --- /dev/null +++ b/Task/Calendar/Ada/calendar-1.adb @@ -0,0 +1,48 @@ +with Ada.Calendar.Formatting; + +package Printable_Calendar is + + subtype String20 is String(1 .. 20); + type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20; + + type Description is record + Weekday_Rep: String20; + Month_Rep: Month_Rep_Type; + end record; + -- for internationalization, you only need to define a new description + + Default_Description: constant Description := + (Weekday_Rep => + "Mo Tu We Th Fr Sa So", + Month_Rep => + (" January ", " February ", " March ", + " April ", " May ", " June ", + " July ", " August ", " September ", + " October ", " November ", " December ")); + + type Calendar (<>) is tagged private; + + -- Initialize a calendar for devices with 80- or 132-characters per row + function Init_80(Des: Description := Default_Description) return Calendar; + function Init_132(Des: Description := Default_Description) return Calendar; + + -- the following procedures output to standard IO; override if neccessary + procedure New_Line(Cal: Calendar); + procedure Put_String(Cal: Calendar; S: String); + + -- the following procedures do the real stuff + procedure Print_Line_Centered(Cal: Calendar'Class; Line: String); + procedure Print(Cal: Calendar'Class; + Year: Ada.Calendar.Year_Number; + Year_String: String); -- this is the main Thing + +private + type Calendar is tagged record + Columns, Rows, Space_Between_Columns: Positive; + Left_Space: Natural; + + Weekday_Rep: String20; + Month_Rep: Month_Rep_Type; + end record; + +end Printable_Calendar; diff --git a/Task/Calendar/Ada/calendar-2.adb b/Task/Calendar/Ada/calendar-2.adb new file mode 100644 index 0000000000..730f017d95 --- /dev/null +++ b/Task/Calendar/Ada/calendar-2.adb @@ -0,0 +1,176 @@ +with Ada.Text_IO; + +package body Printable_Calendar is + + use Ada.Calendar; + package F renames Ada.Calendar.Formatting; + + function Days_Per_Month(Year: Year_Number; Month: Month_Number) + return Day_Number is + begin + case Month is + when 1 | 3 | 5 | 7 | 8 | 10 | 12 => return 31; + when 4 | 6 | 9 | 11 => return 30; + when 2 => + if Year mod 4 /= 0 then + return 28; + elsif Year mod 100 /= 0 then + return 29; + elsif Year mod 400 /= 0 then + return 28; + else + return 29; + end if; + end case; + end Days_Per_Month; + + type Full_Month_Rep is array (1 .. 6) of String20; + function Generate_Printable_Month (Y: Ada.Calendar.Year_Number; + M: Ada.Calendar.Month_Number) + return Full_Month_Rep is + + X: Full_Month_Rep := (others => " "); + -- If X=Generate_Printable_Month(2011, 01), the result could be + -- " January ", -- Month_Rep(01) + -- "Mo Tu We Th Fr Sa Su" -- Weekday_Rep + -- " 1 2" -- X(1) + -- " 3 4 5 6 7 8 9" -- X(2) + -- "10 11 12 13 14 15 16" -- X(3) + -- "17 18 19 20 21 22 23" -- X(4) + -- "24 25 26 27 28 29 30" -- X(5) + -- "31 " -- X(6) + + Row: Integer range 1 .. 6 := 1; + Day_Index: constant array(F.Day_Name) of Positive + := (1, 4, 7, 10, 13, 16, 19); + begin + for I in 1 .. Days_Per_Month(Y, M) loop + declare + Weekday: constant F.Day_Name := F.Day_Of_Week(F.Time_Of(Y, M, I)); + Pos: constant Positive := Day_Index(Weekday); + Cleartext_Name: constant String := Day_Number'Image(I); + L: constant Positive := Cleartext_Name'Last; + begin + X(Row)(Pos .. Pos+1) := Cleartext_Name(L-1 .. L); + if F."="(Weekday, F.Sunday) then + Row := Row + 1; + end if; + end; + end loop; + return X; + end Generate_Printable_Month; + + + procedure Print(Cal: Calendar'class; + Year: Ada.Calendar.Year_Number; + Year_String: String) is + + The_Month: Month_Number := Month_Number'First; + + procedure Write_Space(Length: Natural) is + begin + for I in 1 .. Length loop + Cal.Put_String(" "); + end loop; + end Write_Space; + + Year_Rep: array(Month_Number) of Full_Month_Rep; + + begin + -- print the year + Cal.Print_Line_Centered(Year_String); + + -- generate a printable form for all the months + for Month in Month_Number loop + Year_Rep(Month) := Generate_Printable_Month(Year, Month); + end loop; + + begin + while True loop + + -- new line + Cal.New_Line; + + -- write month names + Write_Space(Cal.Left_Space); + for Month in The_Month .. The_Month+Cal.Columns-2 loop + Cal.Put_String(Cal.Month_Rep(Month)); + Write_Space(Cal.Space_Between_Columns); + end loop; + Cal.Put_String(Cal.Month_Rep(The_Month+Cal.Columns-1)); + Cal.New_Line; + + -- write "Mo Tu .. So" - or whatever is defined by Weekday_Rep + Write_Space(Cal.Left_Space); + for Month in The_Month .. The_Month+Cal.Columns-2 loop + Cal.Put_String(Cal.Weekday_Rep); + Write_Space(Cal.Space_Between_Columns); + end loop; + Cal.Put_String(Cal.Weekday_Rep); + Cal.New_Line; + + -- write the dates + for I in 1 .. 6 loop + Write_Space(Cal.Left_Space); + for Month in The_Month .. The_Month+Cal.Columns-2 loop + Cal.Put_String(Year_Rep(Month)(I)); + Write_Space(Cal.Space_Between_Columns); + end loop; + Cal.Put_String(Year_Rep(The_Month+Cal.Columns-1)(I)); + Cal.New_Line; + end loop; + + The_Month := The_Month + Cal.Columns; + -- this will eventually raise Constraint_Error to terminate the loop + end loop; + exception + when Constraint_Error => null; + end; + end Print; + + procedure New_Line(Cal: Calendar) is + begin + Ada.Text_IO.New_Line; + end New_Line; + + procedure Put_String(Cal: Calendar; S: String) is + begin + Ada.Text_IO.Put(S); + end Put_String; + + procedure Print_Line_Centered(Cal: Calendar'Class; Line: String) is + Width : constant Positive := Cal.Columns*20 + + (Cal.Columns-1)*Cal.Space_Between_Columns + + Cal.Left_Space; + begin + if Line'Length >= Width-1 then + Cal.Put_String(Line); + Cal.New_Line; + else + Print_Line_Centered(Cal, " " & Line & " "); + end if; + end Print_Line_Centered; + + function Init_80(Des: Description := Default_Description) return Calendar is + X: Calendar:= + (Columns => 3, Rows => 4, Space_Between_Columns => 4, + Left_Space => 1, + Weekday_Rep => Des.Weekday_Rep, + Month_Rep => Des.Month_Rep + ); + begin + return X; + end Init_80; + + function Init_132(Des: Description := Default_Description) return Calendar is + X: Calendar:= + (Columns => 6, Rows => 2, Space_Between_Columns => 2, + Left_Space => 1, + Weekday_Rep => Des.Weekday_Rep, + Month_Rep => Des.Month_Rep + ); + begin + return X; + end Init_132; + +end Printable_Calendar; diff --git a/Task/Calendar/Ada/calendar-3.adb b/Task/Calendar/Ada/calendar-3.adb new file mode 100644 index 0000000000..93fd95516b --- /dev/null +++ b/Task/Calendar/Ada/calendar-3.adb @@ -0,0 +1,11 @@ +with Printable_Calendar; + +procedure Cal is + + C: Printable_Calendar.Calendar := Printable_Calendar.Init_80; + +begin + C.Print_Line_Centered("[reserved for Snoopy]"); + C.New_Line; + C.Print(1969, "Nineteen-Sixty-Nine"); +end Cal; diff --git a/Task/Calendar/AutoIt/calendar.au3 b/Task/Calendar/AutoIt/calendar.au3 new file mode 100644 index 0000000000..9cfc37d67f --- /dev/null +++ b/Task/Calendar/AutoIt/calendar.au3 @@ -0,0 +1,102 @@ +#include + +; Set the count of characters in each line, minimum is 20 - one month. +Global $iPrintSize = 132 + +; Set the count of months, you want to print side by side. With "0" it calculates automatically. +; The number will corrected, if it not allowed to print in an rectangle. +; If your print size is to small for given count, it will set back to automatically calculation. +Global $iSideBySide = 3 + +; Set the count of spaces between months. +Global $iSpace = 4 + +_CreateCalendar( 1969 ) + + +Func _CreateCalendar($_iYear) + Local $aMon[12] = [' January ', ' February ', ' March ', _ + ' April ', ' May ', ' June ', _ + ' July ', ' August ', ' September ', _ + ' October ', ' November ', ' December '] + Local $sHead = 'Mo Tu We Th Fr Sa Su' + Local $aDaysInMonth[12] = [31,28,31,30,31,30,31,31,30,31,30,31] + If _DateIsLeapYear($_iYear) Then $aDaysInMonth[1] = 29 + + ; == assign date in weekday table for the whole year + Local $aAllDaysInMonth[6][7][12] ; [ lines ][ weekdays ][ months ] + Local $iDay = 1, $iShift + For $i = 1 To 12 + $iShift = _DateToDayOfWeekISO($_iYear, $i, 1) -1 + For $j = 0 To 5 + For $k = $iShift To 6 + $aAllDaysInMonth[$j][$k][$i-1] = $iDay + $iDay += 1 + If $iDay > $aDaysInMonth[$i-1] Then ExitLoop(2) + Next + $iShift = 0 + Next + $iDay = 1 + Next + + ; == check given side by side count, calculate if needed + If $iSideBySide > 0 Then + If $iPrintSize < ($iSideBySide *(20 +$iSpace) -$iSpace) Then $iSideBySide = 0 + EndIf + Switch $iSideBySide + Case 0 + $iSideBySide = Int($iPrintSize /(20 +$iSpace)) + If $iPrintSize < 20 Then Return _PrintLine('Escape: Size Error') + If $iPrintSize < (20 +$iSpace) Then $iSideBySide = 1 + Case 5 + $iSideBySide = 4 + Case 7 To 11 + $iSideBySide = 6 + EndSwitch + + ; == create space string + Local $sSpace = '' + For $i = 1 To $iSpace + $sSpace &= ' ' + Next + + ; == print header + _PrintLine(@LF) + _PrintLine('[ here is Snoopy ]', @LF) + _PrintLine(StringRegExpReplace($_iYear, '(\d)(\d)(\d)(\d)', '$1 $2 $3 $4'), @LF) + + ; == create data for each line, in dependence to count of months in one line + Local $sLine, $iRight, $sTmp1, $sTmp2 + For $n = 0 To 12 /$iSideBySide -1 + $sTmp1 = '' + $sTmp2 = '' + For $z = 0 To $iSideBySide -1 + $sTmp1 &= $aMon[$iSideBySide *$n+$z] & $sSpace + $sTmp2 &= $sHead & $sSpace + Next + _PrintLine(StringTrimRight($sTmp1, $iSpace)) + _PrintLine(StringTrimRight($sTmp2, $iSpace)) + For $j = 0 To 5 + $sLine = '' + For $i = 1 To $iSideBySide + For $k = 0 To 6 + $iRight = 3 + If $k = 0 Then $iRight = 2 + $sLine &= StringRight(' ' & $aAllDaysInMonth[$j][$k][$iSideBySide*$n+$i-1], $iRight) + Next + If $i < $iSideBySide Then $sLine &= $sSpace + Next + _PrintLine($sLine) + Next + Next +EndFunc ;==>_CreateCalendar + +Func _PrintLine($_sLine, $_sLF='') + Local $iLen = StringLen($_sLine) + Local $sSpace = '', $sLeft = '' + For $i = 1 To $iPrintSize-1 + $sSpace &= ' ' + Next + If $iLen < $iPrintSize Then $sLeft = StringLeft($sSpace, Int(($iPrintSize-$iLen)/2)) + ConsoleWrite($sLeft & $_sLine & $_sLF & @LF) +EndFunc ;==>_PrintLine diff --git a/Task/Calendar/COBOL/calendar.cob b/Task/Calendar/COBOL/calendar.cob new file mode 100644 index 0000000000..bb1d66b14d --- /dev/null +++ b/Task/Calendar/COBOL/calendar.cob @@ -0,0 +1,226 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. CALEND. + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + DATA DIVISION. + + WORKING-STORAGE SECTION. + 01 WS-DAY-NAMES-DEF. + 03 FILLER PIC X(09) VALUE 'SUNDAY '. + 03 FILLER PIC X(09) VALUE 'MONDAY '. + 03 FILLER PIC X(09) VALUE 'TUESDAY '. + 03 FILLER PIC X(09) VALUE 'WEDNESDAY'. + 03 FILLER PIC X(09) VALUE 'THURSDAY '. + 03 FILLER PIC X(09) VALUE 'FRIDAY '. + 03 FILLER PIC X(09) VALUE 'SATURDAY '. + 01 FILLER REDEFINES WS-DAY-NAMES-DEF. + 03 WS-DAY-NAME PIC X(09) OCCURS 07 TIMES. + + 01 WS-MTH-INFO-DEF. + 03 FILLER PIC X(11) VALUE 'JANUARY 31'. + 03 FILLER PIC X(11) VALUE 'FEBRUARY 28'. + 03 FILLER PIC X(11) VALUE 'MARCH 31'. + 03 FILLER PIC X(11) VALUE 'APRIL 30'. + 03 FILLER PIC X(11) VALUE 'MAY 31'. + 03 FILLER PIC X(11) VALUE 'JUNE 30'. + 03 FILLER PIC X(11) VALUE 'JULY 31'. + 03 FILLER PIC X(11) VALUE 'AUGUST 31'. + 03 FILLER PIC X(11) VALUE 'SEPTEMBER30'. + 03 FILLER PIC X(11) VALUE 'OCTOBER 31'. + 03 FILLER PIC X(11) VALUE 'NOVEMBER 30'. + 03 FILLER PIC X(11) VALUE 'DECEMBER 31'. + 01 FILLER REDEFINES WS-MTH-INFO-DEF. + 03 WS-MTH-INFO-TABLE OCCURS 12 TIMES. + 05 WS-MTH-INFO-NAME PIC X(09). + 05 WS-MTH-INFO-DAYS PIC 9(02). + + 01 WS-MTH-AREA. + 03 WS-MTH-DD PIC S99. + 03 WS-DAY1 PIC 9. + 03 WS-DAYS PIC 99. + 03 WS-DD PIC 9. + 03 WS-WK PIC 9. + 03 WS-MM PIC 99. + 03 WS-QQ PIC 99. + + 03 WS-MTH-MONTH OCCURS 12 TIMES. + 05 WS-MTH-WEEK OCCURS 6 TIMES. + 07 WS-DAY-FLD OCCURS 7 TIMES. + 09 WS-DAY PIC ZZ. + 01 INPDATE-RECORD. + 05 INPD-YEAR PIC 9(04). + 05 FILLER PIC X(01). + 05 INPD-MONTH PIC 9(02). + 05 FILLER PIC X(01). + 05 INPD-DAY PIC 9(02). + 01 WMS-DOW PIC 9(01). + 01 WS-PRT PIC X(132). + 01 WS-COL PIC 9(03) VALUE 0. + 01 WS-PP PIC 9(03) VALUE 0. + 01 WS-CFGN. + 03 FILLER PIC 9(03) VALUE 80. + 03 FILLER PIC 9(02) VALUE 5. + 03 FILLER PIC 9(01) VALUE 1. + 03 FILLER PIC 9(02) VALUE 5. + 03 FILLER PIC 9(01) VALUE 2. + 01 WS-CFGW. + 03 FILLER PIC 9(03) VALUE 120. + 03 FILLER PIC 9(02) VALUE 10. + 03 FILLER PIC 9(01) VALUE 2. + 03 FILLER PIC 9(02) VALUE 10. + 03 FILLER PIC 9(01) VALUE 3. + 01 WS-CFG. + 03 WS-LS PIC 9(03) VALUE 120. + 03 WS-LMAR PIC 9(02) VALUE 10. + 03 WS-SPBD PIC 9(01) VALUE 2. + 03 WS-SPBC PIC 9(02) VALUE 10. + 03 WS-DNMW PIC 9(01) VALUE 3. + PROCEDURE DIVISION. + MOVE '1969-01-01' TO INPDATE-RECORD + MOVE WS-CFGN TO WS-CFG + IF (FUNCTION MOD ( INPD-YEAR , 400 ) = 0 + OR (FUNCTION MOD ( INPD-YEAR , 4 ) = 0 + AND + FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0)) + MOVE 29 TO WS-MTH-INFO-DAYS (02) + ELSE + MOVE 28 TO WS-MTH-INFO-DAYS (02) + END-IF + + PERFORM VARYING WS-MM FROM 1 BY +1 + UNTIL WS-MM > 12 + MOVE WS-MM TO INPD-MONTH + CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW + COMPUTE WS-MTH-DD = 1 - WMS-DOW + COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH) + PERFORM VARYING WS-WK FROM 1 BY +1 + UNTIL WS-WK > 6 + PERFORM VARYING WS-DD FROM 1 BY +1 + UNTIL WS-DD > 7 + COMPUTE WS-MTH-DD = WS-MTH-DD + 1 + IF (WS-MTH-DD < 1) + OR (WS-MTH-DD > WS-DAYS) + MOVE 0 TO WS-DAY (WS-MM, WS-WK, WS-DD) + ELSE + MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD) + END-IF + END-PERFORM + END-PERFORM + END-PERFORM + + COMPUTE WS-MM = 0 + PERFORM VARYING WS-QQ FROM 1 BY +1 + UNTIL WS-QQ > 4 + + INITIALIZE WS-PRT + COMPUTE WS-PP = 1 + PERFORM VARYING WS-COL FROM 1 BY +1 + UNTIL WS-COL > 3 + COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL + + IF WS-COL = 1 + COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW + ELSE + COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW + END-IF + MOVE WS-MTH-INFO-NAME (WS-MM) + TO WS-PRT(WS-PP:9) + COMPUTE WS-PP + = WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1) + - 4 + MOVE INPD-YEAR TO WS-PRT (WS-PP:4) + COMPUTE WS-PP = WS-PP + 4 + END-PERFORM + DISPLAY WS-PRT (1:WS-LS) + + INITIALIZE WS-PRT + COMPUTE WS-PP = 1 + PERFORM VARYING WS-COL FROM 1 BY +1 + UNTIL WS-COL > 3 + COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL + + IF WS-COL = 1 + COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW + ELSE + COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW + END-IF + PERFORM VARYING WS-DD FROM 1 BY +1 + UNTIL WS-DD > 7 + IF WS-DD > 1 + COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW + END-IF + MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW) + TO WS-PRT (WS-PP:WS-DNMW) + COMPUTE WS-PP = WS-PP + WS-DNMW + END-PERFORM + END-PERFORM + DISPLAY WS-PRT (1:WS-LS) + + PERFORM VARYING WS-WK FROM 1 BY +1 + UNTIL WS-WK > 6 + INITIALIZE WS-PRT + COMPUTE WS-PP = 1 + PERFORM VARYING WS-COL FROM 1 BY +1 + UNTIL WS-COL > 3 + COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL + + IF WS-COL = 1 + COMPUTE WS-PP = WS-PP + WS-LMAR + ELSE + COMPUTE WS-PP = WS-PP + WS-SPBC + END-IF + PERFORM VARYING WS-DD FROM 1 BY +1 + UNTIL WS-DD > 7 + IF WS-DD > 1 + COMPUTE WS-PP = WS-PP + WS-SPBD + END-IF + MOVE WS-DAY (WS-MM, WS-WK, WS-DD) + TO WS-PRT (WS-PP:2) + COMPUTE WS-PP = WS-PP + 2 + END-PERFORM + END-PERFORM + DISPLAY WS-PRT (1:WS-LS) + END-PERFORM + DISPLAY ' ' + END-PERFORM + GOBACK + . + END PROGRAM CALEND. + IDENTIFICATION DIVISION. + PROGRAM-ID. DATE2DOW. + ENVIRONMENT DIVISION. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 WMS-WORK-AREA. + 03 WMS-YEAR PIC 9(04). + 03 WMS-MONTH PIC 9(02). + 03 WMS-CSYS PIC 9(01) VALUE 1. + 03 WMS-SUM pic 9(04). + LINKAGE SECTION. + 01 INPDATE-RECORD. + 05 INPD-YEAR PIC 9(04). + 05 FILLER PIC X(01). + 05 INPD-MONTH PIC 9(02). + 05 FILLER PIC X(01). + 05 INPD-DAY PIC 9(02). + 01 WMS-DOW PIC 9(01). + PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW. + 1010-CONVERT-DATE-TO-DOW. + IF INPD-MONTH < 3 + COMPUTE WMS-MONTH = INPD-MONTH + 12 + COMPUTE WMS-YEAR = INPD-YEAR - 1 + ELSE + COMPUTE WMS-MONTH = INPD-MONTH + COMPUTE WMS-YEAR = INPD-YEAR + END-IF + COMPUTE WMS-SUM = + ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR + + FUNCTION INTEGER (6 * (WMS-MONTH + 1) / 10) + + FUNCTION INTEGER ( WMS-YEAR / 4 ) + - FUNCTION INTEGER ( WMS-YEAR / 100 ) + + FUNCTION INTEGER ( WMS-YEAR / 400 ) + + WMS-CSYS ) + COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1 + GOBACK + . + END PROGRAM DATE2DOW. diff --git a/Task/Calendar/PowerShell/calendar.ps1 b/Task/Calendar/PowerShell/calendar.ps1 new file mode 100644 index 0000000000..4e9a027847 --- /dev/null +++ b/Task/Calendar/PowerShell/calendar.ps1 @@ -0,0 +1,36 @@ +Param([int]$Year = 1969) +Begin { + $COL_WIDTH = 21 + $COLS = 3 + $MONTH_COUNT = 12 + $MONTH_LINES = 9 + + Function CenterStr([string]$s, [int]$lineSize) { + $padSize = [int](($lineSize - $s.Length) / 2) + ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') + } + + Function MonthLines([int]$month) { + $dt = [System.DateTime]::new($Year, $month, 1) + $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH + $line += 'Su Mo Tu We Th Fr Sa' + $line += $(' ' * $dt.DayOfWeek.value__) + $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) + $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) + New-Object –TypeName PSObject –Prop(@{ + 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } + 'Dt'=$dt}) + } +} +Process { + Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) + $(0..($MONTH_COUNT / $COLS - 1)) | %{ + $fm = $_ * $COLS + $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } + $months = $monthNums | %{ MonthLines $_ } + $(0..($MONTH_LINES - 1)) | %{ + $ml = $_ + Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) + } + } +} diff --git a/Task/Calendar/Rebol/calendar.rebol b/Task/Calendar/Rebol/calendar.rebol new file mode 100644 index 0000000000..56fcdd3901 --- /dev/null +++ b/Task/Calendar/Rebol/calendar.rebol @@ -0,0 +1,13 @@ +Rebol [] +do [if "" = y: ask "Year (ENTER for current):^/^/" [prin y: now/year] +foreach m system/locale/months [ + prin rejoin ["^/^/ " m "^/^/ "] + foreach day system/locale/days [prin join copy/part day 2 " "] + print "" f: to-date rejoin ["1-"m"-"y] loop f/weekday - 1 [prin " "] + repeat i 31 [ + if attempt [c: to-date rejoin [i"-"m"-"y]][ + prin join either 1 = length? form i [" "][" "] i + if c/weekday = 7 [print ""] + ] + ] +] ask "^/^/Press [ENTER] to Continue..."] diff --git a/Task/Calendar/VBScript/calendar.vbs b/Task/Calendar/VBScript/calendar.vbs new file mode 100644 index 0000000000..c52338ba2f --- /dev/null +++ b/Task/Calendar/VBScript/calendar.vbs @@ -0,0 +1,74 @@ +'call it with year, number of months per row (1,2,3,4,6) and locale ("" for default) +docal 1969,6,"" + +function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function +sub print(x) wscript.stdout.writeline x : end sub +function iif(a,b,c) :if a then iif=b else iif =c end if : end function + +sub docal (yr,nmonth,sloc) +'yr year to print +'nmonth number of monts side to side, allowed values :1,2,3,4,6 +'sloc locale to use . "" uses the default + +dim ld(6) +dim d(6) +if nmonth=5 or nmonth>6 or nmonth<1 then wscript.stderr.writeline "Can't use width " & nmonth :exit sub + +'set the locale (names of months and weekdays plus first day of week) +if sloc<>"" then Setlocale sloc + +'make a row of short weekday names to put on top of the month days +'trim the names to 2 char and align them right +wday="" +for i=1 to 7 + wday=wday &" "&right(" "& left(weekdayname(i,true,vbUseSystemDayOfWeek),2),2) +next + +'print header of the calendar +ncols=nmonth*21+(nmonth-1)*1 +print center("[Snoopy]",ncols) +print center(yr,ncols) +print string(ncols,"=") + +'row of months +for i=1 to 12\nmonth + s="": s1="":esp="" + + for j=1 to nmonth + 'build header of the month row + s=s & esp & center(monthname(m+j),21) + s1=s1 & esp & wday + + 'get negative offset of first day of week to the weekday of day 1 of each month + d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2 + 'get last day of each month from Windows + ld(j)=day(dateserial(yr,m+j+1,0)) + esp=" " + next + + 'print the row of months header (name of month and weekday names) + print s: print s1 + + 'weekday rows. makes 5 or 6 rows according to the month requiring most + while(d(1)ld(j),"",d(j)),3) + d(j)=d(j)+1 + next + s=s&" " + next + 'print a complete row of days + print s + wend + 'go for the next row of monts + m=m+nmonth + if i<>12\nmonth then print "" +next + +'print footer +print string(ncols,"=") +end sub diff --git a/Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence.alg b/Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence-1.alg similarity index 100% rename from Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence.alg rename to Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence-1.alg diff --git a/Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence-2.alg b/Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence-2.alg new file mode 100644 index 0000000000..5416dd2308 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/ALGOL-68/calkin-wilf-sequence-2.alg @@ -0,0 +1,35 @@ +BEGIN # Calculate members of the Calkin-Wilf sequence - translation of the Nim sample via EasyLang # + + INT n := 0, d := 0; + + PROC first cw = VOID: + BEGIN + n := 1; + d := 1 + END # first cw # ; + + PROC next cw = VOID: + BEGIN + n := 2 * ( n OVER d ) * d + d - n; + INT t = n; + n := d; + d := t + END # next cw # ; + + print( ( "The first 20 elements of the Calkin-Wilf sequence are:", newline, " " ) ); + first cw; + FOR i TO 20 DO + print( ( " ", whole( n, 0 ), "/", whole( d, 0 ) ) ); + next cw + OD; + print( ( newline, "Position of 83116/51639 in the sequence: " ) ); + BEGIN + first cw; + INT pos := 1; + WHILE n /= 83116 OR d /= 51639 DO + next cw; + pos +:= 1 + OD; + print( ( whole( pos, 0 ), newline ) ) + END +END diff --git a/Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.adb b/Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.adb new file mode 100644 index 0000000000..31840223a0 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Ada/calkin-wilf-sequence.adb @@ -0,0 +1,110 @@ +with Ada.Text_IO; + +procedure Calkin_Wilf is + type Rational is + record + Numerator : Integer; + Denominator : Positive; + end record; + + -- A generic solution would use Ada.Containers.Vectors, but + -- these puzzles are written to avoid numbers larger than + -- what fit in 64 bits, so we can assume a limit of 64 terms + type Term_Array is array (1 .. 64) of Positive; + + type Continued_Fraction is + record + Count : Positive; + Terms : Term_Array; + end record; + + -- Don't bother with reducing or negatives + function "+" (A, B : Rational) return Rational is + (A.Numerator * B.Denominator + B.Numerator * A.Denominator, + A.Denominator * B.Denominator); + + function "-" (A : Rational) return Rational is + (-A.Numerator, A.Denominator); + + function "-" (A, B : Rational) return Rational is + (A + (-B)); + + function "*" (A, B : Rational) return Rational is + (A.Numerator * B.Numerator, + A.Denominator * B.Denominator); + + function Invert (A : Rational) return Rational is + (A.Denominator, + A.Numerator); + + function Floor (A : Rational) return Rational is + (A.Numerator / A.Denominator, + 1); + + function Image (A : Rational) return String is + (A.Numerator'Image & " /" & A.Denominator'Image); + + function "=" (A, B : Rational) return Boolean is + (A.Numerator = B.Numerator and A.Denominator = B.Denominator); + + function Next_Calkin_Wilf_Term (R : Rational) return Rational is + (Invert ((2, 1) * Floor (R) + (1, 1) - R)); + + procedure Put_First_Terms (N : Positive) is + R : Rational := (1, 1); + begin + Ada.Text_IO.Put_Line ( + "The first " & N'Image & " terms of the Calkin-Wilf Sequence are:"); + for I in 1 .. N loop + Ada.Text_IO.Put_Line (I'Image & ": " & Image (R)); + R := Next_Calkin_Wilf_Term (R); + end loop; + end Put_First_Terms; + + function To_Continued_Fraction (R : Rational) return Continued_Fraction is + Count : Natural := 0; + Terms : Term_Array; + N : Natural := R.Numerator; + D : Natural := R.Denominator; + M : Natural; + begin + while D > 0 loop + Count := Count + 1; + Terms (Count) := N / D; + M := N mod D; + N := D; + D := M; + end loop; + + if Count mod 2 = 0 then + Terms (Count .. Count + 1) := (Terms (Count) - 1, 1); + Count := Count + 1; + end if; + + return (Count, Terms); + end To_Continued_Fraction; + + function To_Index (R : Rational) return Natural is + Cont_Frac : Continued_Fraction := To_Continued_Fraction (R); + Terms : Term_Array renames Cont_Frac.Terms; + Index : Natural := 0; + begin + for I in reverse 1 .. Cont_Frac.Count loop + for J in 1 .. Terms (I) loop + Index := Index * 2 + (I mod 2); + end loop; + end loop; + + return Index; + end To_Index; + + procedure Put_Term_Index (R : Rational) is + Index : Natural := To_Index (R); + begin + Ada.Text_IO.Put_Line ("Term " & Image (R) & " is at index " & Index'Image); + end Put_Term_Index; + +begin + Put_First_Terms (20); + Put_Term_Index((83116, 51639)); +end Calkin_Wilf; diff --git a/Task/Calkin-Wilf-sequence/Agena/calkin-wilf-sequence.agena b/Task/Calkin-Wilf-sequence/Agena/calkin-wilf-sequence.agena new file mode 100644 index 0000000000..d957c6b5a6 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Agena/calkin-wilf-sequence.agena @@ -0,0 +1,29 @@ +begin # Calculate members of the Calkin-Wilf sequence + + local n, d := 0, 0; + + local proc firstCW() + n, d := 1, 1 + end; + + local proc nextCW() + n, d := d, ( d + ( 2 * d * ( n \ d ) ) ) - n + end; + + printf( "The first 20 elements of the Calkin-Wilf sequence are:\n " ) + firstCW(); + for i to 20 do + printf( " %d/%d", n, d ); + nextCW() + od; + print(); + + firstCW(); + local pos := 1; + while n <> 83116 or d <> 51639 do + nextCW(); + pos +:= 1 + od; + printf( "Position of 83116/51639 in the sequence: %d\n", pos ) + +end diff --git a/Task/Calkin-Wilf-sequence/COBOL/calkin-wilf-sequence.cob b/Task/Calkin-Wilf-sequence/COBOL/calkin-wilf-sequence.cob new file mode 100644 index 0000000000..f1c18aa115 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/COBOL/calkin-wilf-sequence.cob @@ -0,0 +1,213 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. CALKIN-WILF. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + *> Current term + 01 WS-TERM-N PIC S9(18) VALUE 1. + 01 WS-TERM-D PIC S9(18) VALUE 1. + + *> Loop counter + 01 WS-INDEX PIC 9(4). + + *>---------------------------------------------------------------- + *> GCD helper inputs/output + *>---------------------------------------------------------------- + 01 WS-GCD-A PIC S9(18). + 01 WS-GCD-B PIC S9(18). + 01 WS-GCD-TEMP PIC S9(18). + 01 WS-GCD-OUT PIC S9(18). + + *>---------------------------------------------------------------- + *> NEXT-CALKIN-WILF working storage + *>---------------------------------------------------------------- + *> floor(term) + 01 WS-FL-N PIC S9(18). + *> 2*floor+1 (always integer so denom=1) + 01 WS-TMP-N PIC S9(18). + *> divisor = (2*floor+1) - term + 01 WS-DIVIS-N PIC S9(18). + 01 WS-DIVIS-D PIC S9(18). + *> next term = 1 / divisor + 01 WS-NEXT-N PIC S9(18). + 01 WS-NEXT-D PIC S9(18). + + *>---------------------------------------------------------------- + *> Continued fraction + *>---------------------------------------------------------------- + 01 WS-CF-N PIC S9(18). + 01 WS-CF-D PIC S9(18). + 01 WS-CF-TMP PIC S9(18). + 01 WS-CF-SIZE PIC 9(4) VALUE 0. + 01 WS-CF-TABLE. + 05 WS-CF-ENTRY PIC S9(18) OCCURS 128 TIMES. + 01 WS-CF-BACK PIC S9(18). + + *>---------------------------------------------------------------- + *> TERM-INDEX working storage + *>---------------------------------------------------------------- + 01 WS-TI-RESULT PIC S9(18) VALUE 0. + 01 WS-TI-BIT PIC S9(18) VALUE 1. + 01 WS-TI-POWER PIC 9(4) VALUE 0. + 01 WS-TI-I PIC 9(4). + 01 WS-TI-J PIC 9(4). + 01 WS-TI-TERM PIC S9(18). + 01 WS-TI-SHIFT PIC S9(18). + + *>---------------------------------------------------------------- + *> Input rational + *>---------------------------------------------------------------- + 01 WS-IN-N PIC S9(18) VALUE 83116. + 01 WS-IN-D PIC S9(18) VALUE 51639. + + *>---------------------------------------------------------------- + *> Display helpers + *>---------------------------------------------------------------- + 01 WS-DISP-IDX PIC Z9. + 01 WS-DISP-N PIC S9(18). + 01 WS-DISP-D PIC S9(18). + 01 WS-DISP-RES PIC S9(18). + + PROCEDURE DIVISION. + MAIN-PARA. + DISPLAY "First 20 terms of the Calkin-Wilf sequence are:" + + MOVE 1 TO WS-TERM-N + MOVE 1 TO WS-TERM-D + + PERFORM VARYING WS-INDEX FROM 1 BY 1 + UNTIL WS-INDEX > 20 + MOVE WS-INDEX TO WS-DISP-IDX + MOVE WS-TERM-N TO WS-DISP-N + MOVE WS-TERM-D TO WS-DISP-D + DISPLAY WS-DISP-IDX ": " WS-DISP-N "/" WS-DISP-D + + PERFORM NEXT-CALKIN-WILF + MOVE WS-NEXT-N TO WS-TERM-N + MOVE WS-NEXT-D TO WS-TERM-D + END-PERFORM + + DISPLAY SPACES + + MOVE WS-IN-N TO WS-CF-N + MOVE WS-IN-D TO WS-CF-D + PERFORM CONTINUED-FRACTION-PARA + PERFORM TERM-INDEX-PARA + + MOVE WS-IN-N TO WS-DISP-N + MOVE WS-IN-D TO WS-DISP-D + MOVE WS-TI-RESULT TO WS-DISP-RES + DISPLAY " " WS-DISP-N "/" WS-DISP-D + " is the " WS-DISP-RES "th term of the sequence." + + STOP RUN. + + *>---------------------------------------------------------------- + *> NEXT-CALKIN-WILF + *> Input : WS-TERM-N, WS-TERM-D + *> Output: WS-NEXT-N, WS-NEXT-D + *> + *> next = 1 / (2*floor(n/d) + 1 - n/d) + *> + *> Working entirely with numerator over WS-TERM-D denominator: + *> floor(n/d) -> integer q = n/d (COBOL integer divide) + *> 2*q + 1 -> integer (2q+1) + *> (2q+1) - n/d -> expressed as ((2q+1)*d - n) / d + *> 1 / above -> d / ((2q+1)*d - n) then reduce + *>---------------------------------------------------------------- + NEXT-CALKIN-WILF. + COMPUTE WS-FL-N = WS-TERM-N / WS-TERM-D + COMPUTE WS-TMP-N = 2 * WS-FL-N + 1 + + *> divisor numerator = (2q+1)*d - n, denominator = d + COMPUTE WS-DIVIS-N = WS-TMP-N * WS-TERM-D - WS-TERM-N + MOVE WS-TERM-D TO WS-DIVIS-D + + *> next = 1/divisor = d / ((2q+1)*d - n) + MOVE WS-DIVIS-D TO WS-NEXT-N + MOVE WS-DIVIS-N TO WS-NEXT-D + + MOVE WS-NEXT-N TO WS-GCD-A + IF WS-GCD-A < 0 + COMPUTE WS-GCD-A = -WS-GCD-A + END-IF + MOVE WS-NEXT-D TO WS-GCD-B + PERFORM GCD-PARA + DIVIDE WS-GCD-OUT INTO WS-NEXT-N + DIVIDE WS-GCD-OUT INTO WS-NEXT-D. + + *>---------------------------------------------------------------- + *> GCD (iterative Euclidean) + *> Input : WS-GCD-A (>= 0), WS-GCD-B + *> Output: WS-GCD-OUT + *>---------------------------------------------------------------- + GCD-PARA. + PERFORM UNTIL WS-GCD-B = 0 + MOVE WS-GCD-B TO WS-GCD-TEMP + COMPUTE WS-GCD-B = + FUNCTION MOD(WS-GCD-A, WS-GCD-B) + MOVE WS-GCD-TEMP TO WS-GCD-A + END-PERFORM + MOVE WS-GCD-A TO WS-GCD-OUT. + + *>---------------------------------------------------------------- + *> CONTINUED-FRACTION-PARA + *> Input : WS-CF-N, WS-CF-D + *> Output: WS-CF-TABLE(1..WS-CF-SIZE) + *>---------------------------------------------------------------- + CONTINUED-FRACTION-PARA. + MOVE 0 TO WS-CF-SIZE + + PERFORM UNTIL WS-CF-N = 1 + ADD 1 TO WS-CF-SIZE + COMPUTE WS-CF-ENTRY(WS-CF-SIZE) = + WS-CF-N / WS-CF-D + MOVE WS-CF-N TO WS-CF-TMP + MOVE WS-CF-D TO WS-CF-N + COMPUTE WS-CF-D = + FUNCTION MOD(WS-CF-TMP, WS-CF-D) + END-PERFORM + + *> If even-length, split last entry: [..., k] -> [..., k-1, 1] + IF WS-CF-SIZE > 0 AND + FUNCTION MOD(WS-CF-SIZE, 2) = 0 + MOVE WS-CF-ENTRY(WS-CF-SIZE) TO WS-CF-BACK + COMPUTE WS-CF-ENTRY(WS-CF-SIZE) = WS-CF-BACK - 1 + ADD 1 TO WS-CF-SIZE + MOVE 1 TO WS-CF-ENTRY(WS-CF-SIZE) + END-IF. + + *>---------------------------------------------------------------- + *> TERM-INDEX-PARA + *> Input : WS-CF-TABLE(1..WS-CF-SIZE) + *> Output: WS-TI-RESULT + *> + *> Reconstructs the binary representation by treating + *> continued fraction terms as run-length counts of + *> alternating 1-bits and 0-bits. + *>---------------------------------------------------------------- + TERM-INDEX-PARA. + MOVE 0 TO WS-TI-RESULT + MOVE 1 TO WS-TI-BIT + MOVE 0 TO WS-TI-POWER + + PERFORM VARYING WS-TI-I FROM 1 BY 1 + UNTIL WS-TI-I > WS-CF-SIZE + + MOVE WS-CF-ENTRY(WS-TI-I) TO WS-TI-TERM + + PERFORM VARYING WS-TI-J FROM 1 BY 1 + UNTIL WS-TI-J > WS-TI-TERM + COMPUTE WS-TI-SHIFT = + WS-TI-BIT * (2 ** WS-TI-POWER) + ADD WS-TI-SHIFT TO WS-TI-RESULT + ADD 1 TO WS-TI-POWER + END-PERFORM + + IF WS-TI-BIT = 0 + MOVE 1 TO WS-TI-BIT + ELSE + MOVE 0 TO WS-TI-BIT + END-IF + END-PERFORM. diff --git a/Task/Calkin-Wilf-sequence/Fortran/calkin-wilf-sequence-1.f b/Task/Calkin-Wilf-sequence/Fortran/calkin-wilf-sequence-1.f new file mode 100644 index 0000000000..7861ca36d8 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Fortran/calkin-wilf-sequence-1.f @@ -0,0 +1,262 @@ +! +! Calkin-Wilf sequence +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +! U.B., April 2026 +! +program CalkinWilf + +implicit none +integer, parameter :: tInt=8, tReal=8 ! We use this for integer and Real numbers + +type Rational + integer(kind=tInt) :: numerator + integer(kind=tInt) :: denominator +end type Rational + +! A simple dynamic array that can grow as new values get inserted +type vect + integer(kind=tInt), dimension(:), allocatable :: Values + integer :: capacity=0 + integer :: current=0 +end type vect + +Type(Rational) :: cwNum +integer:: idx + +call printFirstTerms (20) + +! find the index of 83116 / 51639 within the sequence +cwNum%numerator = 83116 +cwNum%denominator = 51639 + +idx = term_Number (cwNum) +write (*, '(/,"83116 / 51639 is the ", i0, "th term of the sequence.")') idx + +contains + + + +! ============================================================================================== +! Calculate the first 'n' values of the Calkin-Wilf sequence as rational numbers and print them . +! ============================================================================================== +subroutine printFirstTerms (n) +integer :: n +integer :: I + +cwNum%numerator = 1 +cwNum%denominator = 1 +write (*,'("First ",i0," terms of the Calkin-Wilf sequence are: ")') n +do i=1, n + call printRational (i, cwNum) + cwnum = nextInSeq(cwnum) +end do +end subroutine printFirstTerms + +! ================================================================================== +! Formatted print function for rational number r, appearing at pos k in our sequence +! ================================================================================== +subroutine printRational (k,r) +integer, intent(in) :: k +type(Rational), intent(in) :: r + +write (*, '(i2, ": ",i0,x,"/",x,i0)') k, r%numerator, r%denominator + +end subroutine printRational + +! ============================================================== +! Calculate the index int the Calkin-WIlf sequence for element R +! ============================================================== +function term_Number (R) result (res) + +type(Rational), intent(in) :: r +integer (kind=tInt) :: res +integer (kind=tInt) :: d, p, n, idxn, i + +type (vect) :: cf ! will contain the continued fraction + +res = 0 +d = 1 +p = 0 +call continued_fraction (r, cf) +do idxn=1, cf%current ! Set the bits of the result value + n = cf%values(idxn) + do i = 0, n-1 + res = ior (res, ishft (d, p)) + p = p + 1 + enddo + d = 1-d ! After setting bits, we skip bits and after skipping bits, we set bits. +enddo +end function term_Number + +! ====================================================================================== +! Calculate the continued fraction 'cf' from rational number 'r' +! (This is basically Euclid's gcd algorithm, in which we store the intermediate results) +! ====================================================================================== +subroutine continued_fraction (r, cf) +type (Rational), intent(in) :: r +type (vect), intent(inout) :: cf + +integer (kind=tInt) :: a, b, c +a = r%numerator +b = r%denominator +do while (a .ne. 1) + call push_back (cf, a/b) + c = A + a = b + b = mod (c, b) +enddo + +! Care for an odd number of terms in the continued fraction. +if (cf%current .gt.0) then ! Any elements? + if (mod (cf%current,2) .eq. 0) then ! Even number of entries? + cf%Values(cf%current) = cf%Values(cf%current)-1 ! Decrement last entry and + call push_back (cf, 1_tInt) ! insert an additional 1 + endif ! No else: it's odd as it should. +end if +end subroutine continued_fraction + + +! =========================================== +! Insert a new value to the end of the vector +! =========================================== +subroutine push_back (V, value) +type (vect), intent(inout) :: V +integer(kind=tInt) :: value + +V%current = V%current + 1 +if (V%current .gt. V%capacity) then ! Extend Vector if necessary + call alloc (V, 2*V%capacity) +endif +V%values(V%current) = value +end subroutine push_back + +! ============================== +! Resize vector "V" to "newSize" +! ============================== +! +subroutine alloc (V,newSize) +type (vect), intent(inout) :: v ! The Vector to extend +integer,intent(in) :: newSIze ! the new size +integer :: n ! the new size + +integer (kind=tInt), dimension(:), allocatable :: tmp ! Temporary during extension + +! at the very first allocation (from push_back(), the "newSize" might be 2*0=0 +! Make sure we alloc space for at least 1 element, not 0 +! +n = max (newSize, 1) +if (n .gt. v%capacity) then ! Only if its a real extension + if (v%capacity .gt. 0) then ! not for very first allocation + ! call move_alloc (v%values, tmp) ! Copy to tmp, F 2003, not for FSI Fortran + allocate (tmp(v%capacity)) ! FOr compatibility with F95, write some extras lines + tmp (:v%capacity) = v%values(:v%capacity) + deallocate (v%values) + endif + allocate (v%values ( n)) ! Allocate new size + if (.not. allocated (v%values)) then !check if allocation went OK + print *, 'FATAL: ALLOC FAILED.' + endif + + if (allocated (tmp)) then ! must copy Old values from tmp to V? + v%Values(:v%capacity) = tmp (:v%capacity) + deallocate (tmp) + endif + v%capacity = n +endif ! No Else, no decrease size. + +end subroutine alloc + +! =================================================================================================== +! Calculate floor (numerator/denominator) and return result as new rational number with denominator 1 +! =================================================================================================== +function Rfloor (R) result (F) +type(Rational), intent(in) :: R +type(Rational) :: F + +! numerator and denominator are integers. Do it simply without converting to reals and +! cutting of decimal fraction after the division. +F%numerator = R%numerator / R%denominator +F%denominator = 1 + +end function Rfloor + +! =========================================== +! Arithmetic operatinos with Rational Numbers +! =========================================== +! +! a + b +! +function add (a, b) result (sum) +type(Rational), intent(in) :: a, b +type(Rational) :: sum + +sum%numerator = a%numerator * b%denominator + b%numerator * a%denominator +sum%denominator = a%denominator * b%denominator + +end function add +! +! a - b +! +function sub (a, b) result (dif) +type(Rational), intent(in) :: a, b +type(Rational) :: dif + +dif%numerator = a%numerator * b%denominator - b%numerator * a%denominator +dif%denominator = a%denominator * b%denominator + +end function sub + +! +! a * b +! +function mul (a,b) result (prod) +type(Rational), intent(in) :: a, b +type(Rational) :: prod + +prod%numerator = a%numerator*b%numerator +prod%denominator = a%denominator*b%denominator + +end function mul + +! +! 1 / a +! +function inv (a) result (inva) +type(Rational), intent(in) :: a +type(Rational) :: inva + +inva%numerator = a%denominator +inva%denominator = a%numerator +end function inv + +! ======================================================= +! Calculate next value in the sequence from current value +! following the definition of the Calkin-Wilf sequence +! ======================================================= +function nextInSeq (Cur) result (nxt) +type (Rational), intent(in) :: Cur +type (Rational) :: nxt + +type (Rational) :: a,b,c ! Store intermediate values +type (Rational) :: two, one ! constants 1/1 and 2/1 + +one%numerator = 1 +one%denominator = 1 +two%numerator = 2 +two%denominator = 1 + +! Use variables for intermediate values. +! This is equivalent to the more compact but unreadable +! +! nxt = inv (sub(add( mul(two,RFloor(cur)), one),cur)) +! +a = mul(two, Rfloor(cur)) +b = add (a, one) +c = sub (b, cur) +nxt = inv(c) + +end function nextInSeq + +end program CalkinWilf diff --git a/Task/Calkin-Wilf-sequence/FreeBASIC/calkin-wilf-sequence.basic b/Task/Calkin-Wilf-sequence/Fortran/calkin-wilf-sequence-2.f similarity index 100% rename from Task/Calkin-Wilf-sequence/FreeBASIC/calkin-wilf-sequence.basic rename to Task/Calkin-Wilf-sequence/Fortran/calkin-wilf-sequence-2.f diff --git a/Task/Calkin-Wilf-sequence/JavaScript/calkin-wilf-sequence.js b/Task/Calkin-Wilf-sequence/JavaScript/calkin-wilf-sequence.js new file mode 100644 index 0000000000..c67e8237da --- /dev/null +++ b/Task/Calkin-Wilf-sequence/JavaScript/calkin-wilf-sequence.js @@ -0,0 +1,99 @@ +class Rational { + constructor(numerator, denominator) { + if (denominator === 0n) throw new Error("Denominator cannot be zero"); + if (numerator === 0n) denominator = 1n; + if (denominator < 0n) { + this.numer = -numerator; + this.denom = -denominator; + } else { + this.numer = numerator; + this.denom = denominator; + } + const g = this.#gcd(this.numer < 0n ? -this.numer : this.numer, this.denom); + this.numer /= g; + this.denom /= g; + } + + add(other) { + return new Rational(this.numer * other.denom + other.numer * this.denom, this.denom * other.denom); + } + + subtract(other) { + return new Rational(this.numer * other.denom - other.numer * this.denom, this.denom * other.denom); + } + + multiply(other) { + return new Rational(this.numer * other.numer, this.denom * other.denom); + } + + divide(other) { + return new Rational(this.numer * other.denom, this.denom * other.numer); + } + + floor() { + return new Rational(this.numer / this.denom, 1n); + } + + numerator() { return this.numer; } + denominator() { return this.denom; } + + toString() { return `${this.numer}/${this.denom}`; } + + #gcd(a, b) { return b === 0n ? a : this.#gcd(b, a % b); } + + static ONE = new Rational(1n, 1n); + static TWO = new Rational(2n, 1n); // Fixed: was 2n, 2n +} + +function nextCalkinWilf(term) { + const divisor = Rational.TWO.multiply(term.floor()).add(Rational.ONE).subtract(term); + return Rational.ONE.divide(divisor); +} + +function continuedFraction(rational) { + let numerator = rational.numerator(); + let denominator = rational.denominator(); + const result = []; + + while (numerator !== 1n) { + result.push(numerator / denominator); + const copyNumerator = numerator; + numerator = denominator; + denominator = copyNumerator % denominator; + } + + if (result.length > 0 && result.length % 2 === 0) { + const back = result.pop(); + result.push(back - 1n); + result.push(1n); + } + + return result; +} + +function termIndex(rational) { + let result = 0n; + let binaryDigit = 1n; + let power = 0n; + + for (const term of continuedFraction(rational)) { + for (let i = 0n; i < term; i++, power++) { + result |= (binaryDigit << power); + } + binaryDigit = binaryDigit === 0n ? 1n : 0n; + } + + return result; +} + +// Main +let term = Rational.ONE; +console.log("First 20 terms of the Calkin-Wilf sequence are:"); +for (let i = 1; i <= 20; i++) { + console.log(`${String(i).padStart(2)}: ${term}`); + term = nextCalkinWilf(term); +} + +console.log(); +const rational = new Rational(83116n, 51639n); +console.log(` ${rational} is the ${termIndex(rational)}th term of the sequence.`); diff --git a/Task/Calkin-Wilf-sequence/Lua/calkin-wilf-sequence.lua b/Task/Calkin-Wilf-sequence/Lua/calkin-wilf-sequence.lua new file mode 100644 index 0000000000..224e89a076 --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Lua/calkin-wilf-sequence.lua @@ -0,0 +1,29 @@ +do -- Calculate members of the Calkin-Wilf sequence + + local n, d = 0, 0 + + local function firstCW() + n, d = 1, 1 + end + + local function nextCW() + n, d = d, ( d + ( 2 * d * ( n // d ) ) ) - n + end + + io.write( "The first 20 elements of the Calkin-Wilf sequence are:\n " ) + firstCW() + for i = 1, 20 do + io.write( " " .. n .. "/" .. d ) + nextCW() + end + io.write( "\n" ) + + firstCW() + local pos = 1 + while n ~= 83116 or d ~= 51639 do + nextCW() + pos = pos + 1 + end + io.write( "Position of 83116/51639 in the sequence: " .. pos .. "\n" ) + +end diff --git a/Task/Calkin-Wilf-sequence/Oberon/calkin-wilf-sequence.oberon b/Task/Calkin-Wilf-sequence/Oberon/calkin-wilf-sequence.oberon new file mode 100644 index 0000000000..1efede16da --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Oberon/calkin-wilf-sequence.oberon @@ -0,0 +1,37 @@ +MODULE CalkinWilfSequence; (* Calculate members of the Calkin-Wilf sequence *) + IMPORT Out; + + VAR n, d, i : INTEGER; + + PROCEDURE first; + BEGIN + n := 1; + d := 1 + END first; + + PROCEDURE next; + VAR t : INTEGER; + BEGIN + n := 2 * ( n DIV d ) * d + d - n; + t := n; + n := d; + d := t + END next; + +BEGIN + Out.String( "The first 20 terms of the Calkin-Wilf sequence are:" );Out.Ln; + first; + FOR i := 1 TO 20 DO + Out.String( " " );Out.Int( n, 0 );Out.String( "/" );Out.Int( d, 0 ); + next + END; + Out.Ln; + Out.String( "83116/51639 is at position " ); + first; + i := 1; + WHILE ( n # 83116 ) OR ( d # 51639 ) DO + next; + INC( i ) + END; + Out.Int( i, 0 );Out.Ln +END CalkinWilfSequence. diff --git a/Task/Call-a-foreign-language-function/Ada/call-a-foreign-language-function.adb b/Task/Call-a-foreign-language-function/Ada/call-a-foreign-language-function.adb new file mode 100644 index 0000000000..793acdfec7 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Ada/call-a-foreign-language-function.adb @@ -0,0 +1,15 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Interfaces.C; use Interfaces.C; +with Interfaces.C.Strings; use Interfaces.C.Strings; + +procedure Test_C_Interface is + function strdup (s1 : Char_Array) return Chars_Ptr; + pragma Import (C, strdup, "_strdup"); + + S1 : constant String := "Hello World!"; + S2 : Chars_Ptr; +begin + S2 := strdup (To_C (S1)); + Put_Line (Value (S2)); + Free (S2); +end Test_C_Interface; diff --git a/Task/Call-a-foreign-language-function/AppleScript/call-a-foreign-language-function.applescript b/Task/Call-a-foreign-language-function/AppleScript/call-a-foreign-language-function.applescript new file mode 100644 index 0000000000..1811b2fc45 --- /dev/null +++ b/Task/Call-a-foreign-language-function/AppleScript/call-a-foreign-language-function.applescript @@ -0,0 +1,5 @@ +on js_isnan(s) + run script "isNaN(" & s & ")" in "JavaScript" +end js_isnan + +js_isnan("{}+{}") diff --git a/Task/Call-a-foreign-language-function/Batch-File/call-a-foreign-language-function.bat b/Task/Call-a-foreign-language-function/Batch-File/call-a-foreign-language-function.bat new file mode 100644 index 0000000000..24f6649b1f --- /dev/null +++ b/Task/Call-a-foreign-language-function/Batch-File/call-a-foreign-language-function.bat @@ -0,0 +1 @@ +rundll32 sysdm.cpl,EditEnvironmentVariables diff --git a/Task/Call-a-foreign-language-function/COBOL/call-a-foreign-language-function.cob b/Task/Call-a-foreign-language-function/COBOL/call-a-foreign-language-function.cob new file mode 100644 index 0000000000..5993b75909 --- /dev/null +++ b/Task/Call-a-foreign-language-function/COBOL/call-a-foreign-language-function.cob @@ -0,0 +1,27 @@ + identification division. + program-id. foreign. + + data division. + working-storage section. + 01 hello. + 05 value z"Hello, world". + 01 duplicate usage pointer. + 01 buffer pic x(16) based. + 01 storage pic x(16). + + procedure division. + call "strdup" using hello returning duplicate + on exception + display "error calling strdup" upon syserr + end-call + if duplicate equal null then + display "strdup returned null" upon syserr + else + set address of buffer to duplicate + string buffer delimited by low-value into storage + display function trim(storage) + call "free" using by value duplicate + on exception + display "error calling free" upon syserr + end-if + goback. diff --git a/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-2.ol b/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-2.ol index 3811ca3052..ee9ae37eb4 100644 --- a/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-2.ol +++ b/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-2.ol @@ -3,8 +3,9 @@ (define libc (or (load-dynamic-library "libc.so") ; General Posix (load-dynamic-library "libc.so.6") ; Linux + (load-dynamic-library "libc.so.6.1") ; Linux (DEC Alpha) (load-dynamic-library "libc.so.7") ; Latest *BSD - (load-dynamic-library "libSystem.B.dylib") ; Mac + (load-dynamic-library "libSystem.B.dylib") ; macOS / Darwin (load-dynamic-library "shlwapi.dll") )) ; Windows (define strdup (or diff --git a/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-3.ol b/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-3.ol index 7808ec5fa9..2b343bee07 100644 --- a/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-3.ol +++ b/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-3.ol @@ -3,8 +3,9 @@ (define libc (or (load-dynamic-library "libc.so") ; General Posix (load-dynamic-library "libc.so.6") ; Linux + (load-dynamic-library "libc.so.6.1") ; Linux (DEC Alpha) (load-dynamic-library "libc.so.7") ; Latest *BSD - (load-dynamic-library "libSystem.B.dylib") ; Mac + (load-dynamic-library "libSystem.B.dylib") ; macOS / Darwin (load-dynamic-library "shlwapi.dll") )) ; Windows (define lib2 diff --git a/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-4.ol b/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-4.ol new file mode 100644 index 0000000000..a9cf851b51 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Ol/call-a-foreign-language-function-4.ol @@ -0,0 +1,34 @@ +; The sample usage of GTK3+ library +(import (otus ffi) + (lib glib-2) + (lib gtk-3)) + +(define print_hello (vm:pin (cons + (cons gint (list GtkWidget* gpointer)) + (lambda (widget userdata) + (print "hello, world") + TRUE +)))) + +(define activate (vm:pin (cons + (cons gint (list GtkApplication* gpointer)) + (lambda (app userdata) + (define window (gtk_application_window_new app)) + (print "window created.") + (gtk_window_set_title window "Window") + (gtk_window_set_default_size window 200 200) + + (define button_box (gtk_button_box_new GTK_ORIENTATION_HORIZONTAL)) + (gtk_container_add window button_box) + + (define button (gtk_button_new_with_label "Press me!")) + (g_signal_connect button "clicked" (G_CALLBACK print_hello) NULL) + (gtk_container_add button_box button) + + (gtk_widget_show_all window) +)))) + +(define app (gtk_application_new (c-string "org.gtk.example") G_APPLICATION_FLAGS_NONE)) +(g_signal_connect app (c-string "activate") (G_CALLBACK activate) NULL) + +(g_application_run app 0 #false) diff --git a/Task/Call-a-foreign-language-function/PowerShell/call-a-foreign-language-function.ps1 b/Task/Call-a-foreign-language-function/PowerShell/call-a-foreign-language-function.ps1 new file mode 100644 index 0000000000..601f4ba4ed --- /dev/null +++ b/Task/Call-a-foreign-language-function/PowerShell/call-a-foreign-language-function.ps1 @@ -0,0 +1,33 @@ +<# : +@echo off +setlocal enableextensions +pushd %~dp0 +start "Rotating Donut" conhost powershell -NoProfile -NoLogo "iex (${%~f0} | out-string)" +goto :eof +#> +# https://www.dostips.com/forum/viewtopic.php?t=10156 +Add-Type ' +using System; +using System.Runtime.InteropServices; +[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] public struct FontInfo{ +public int objSize; +public int nFont; +public short fontSizeX; +public short fontSizeY; +public int fontFamily; +public int fontWeight; +[MarshalAs(UnmanagedType.ByValTStr,SizeConst=32)] public string faceName;} +public class WApi{ +[DllImport("kernel32.dll")] public static extern IntPtr CreateFile(string name,int acc,int share,IntPtr sec,int how,int flags,IntPtr tmplt); +[DllImport("kernel32.dll")] public static extern void GetCurrentConsoleFontEx(IntPtr hOut,int maxWnd,ref FontInfo info); +[DllImport("kernel32.dll")] public static extern void SetCurrentConsoleFontEx(IntPtr hOut,int maxWnd,ref FontInfo info); +[DllImport("kernel32.dll")] public static extern void CloseHandle(IntPtr handle);}'; +$hOut = [WApi]::CreateFile('CONOUT$',-1073741824,2,[IntPtr]::Zero,3,0,[IntPtr]::Zero); +$fInf = New-Object FontInfo; +$fInf.objSize = 84; +$fInf.nFont=12; $fInf.fontSizeX=16; $fInf.fontSizeY=12; $fInf.fontFamily=48; $fInf.fontWeight=400; $fInf.faceName='Terminal' +[WApi]::SetCurrentConsoleFontEx($hOut,0,[ref]$fInf); +[WApi]::CloseHandle($hOut); +$env:isAutoran=1 +cmd /c _donut.bat +# download _donut.bat and save it in the same directory as the script's : https://www.dostips.com/forum/viewtopic.php?f=3&t=11919&p=71274 diff --git a/Task/Call-a-foreign-language-function/R/call-a-foreign-language-function-1.r b/Task/Call-a-foreign-language-function/R/call-a-foreign-language-function-1.r new file mode 100644 index 0000000000..a036d1e1e8 --- /dev/null +++ b/Task/Call-a-foreign-language-function/R/call-a-foreign-language-function-1.r @@ -0,0 +1,8 @@ +#include +#include +#include +void test(char *s) { + char *s_ptr = strdup(s); + printf(s_ptr); + free(s_ptr); +} diff --git a/Task/Call-a-foreign-language-function/R/call-a-foreign-language-function-2.r b/Task/Call-a-foreign-language-function/R/call-a-foreign-language-function-2.r new file mode 100644 index 0000000000..3903c0c534 --- /dev/null +++ b/Task/Call-a-foreign-language-function/R/call-a-foreign-language-function-2.r @@ -0,0 +1,6 @@ +s <- "Hello World!" +system("R CMD SHLIB rtask.c") +dyn.load("rtask.dll") +#Output from .C() is always a list, so take only the first element from it +result <- .C("test", s)[[1]] +print(result) diff --git a/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.adb b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.adb new file mode 100644 index 0000000000..e65662b2bc --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.adb @@ -0,0 +1,45 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Interfaces; use Interfaces; +with Interfaces.C; use Interfaces.C; +with System; use System; + +with Ada.Unchecked_Conversion; + +procedure Shared_Library_Call is + -- + -- Interface to kernel32.dll which is responsible for loading DLLs under Windows. + -- There are ready to use Win32 bindings. We don't want to use them here. + -- + type HANDLE is new Unsigned_32; -- on x64 system, replace by Unsigned_64 to make it work + function LoadLibrary (lpFileName : char_array) return HANDLE; + pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA"); -- Ada95 does not have the @n suffix. + + function GetProcAddress (hModule : HANDLE; lpProcName : char_array) + return Address; + pragma Import (stdcall, GetProcAddress, "GetProcAddress", "_GetProcAddress"); -- + -- + -- The interface of the function we want to call. It is a pointer (access type) + -- because we will link it dynamically. The function is from User32.dll + -- + type MessageBox is access function + ( hWnd : Address := Null_Address; + lpText : char_array; + lpCaption : char_array := To_C ("Greeting"); + uType : Unsigned_16 := 0 + ) return Integer_16; + pragma Convention (Stdcall, MessageBox); + function To_MessageBox is new Ada.Unchecked_Conversion (Address, MessageBox); + + Library : HANDLE := LoadLibrary (To_C ("user32.dll")); + Pointer : Address := GetProcAddress (Library, To_C ("MessageBoxA")); +begin + if Pointer /= Null_Address then + declare + Result : Integer_16; + begin + Result := To_MessageBox (Pointer) (lpText => To_C ("Hello!")); + end; + else + Put_Line ("Unable to load the library " & HANDLE'Image (Library)); + end if; +end Shared_Library_Call; diff --git a/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-2.adb b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-2.adb new file mode 100644 index 0000000000..19c2015e54 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-2.adb @@ -0,0 +1,49 @@ +with Ada.Environment_Variables; use Ada.Environment_Variables; +with Ada.Text_IO; use Ada.Text_IO; +with Interfaces; use Interfaces; +with Interfaces.C; use Interfaces.C; +with System; use System; + +with Ada.Unchecked_Conversion; + +procedure Shared_Library_Call is + -- + -- Interface to libdl to load dynamically linked libraries + -- + function dlopen (FileName : char_array; Flag : int) return Address; + pragma Import (C, dlopen); + + function dlsym (Handle : address; Symbol : char_array) return Address; + pragma Import (C, dlsym); + -- + -- The interfaces of the functions we want to call. These are pointers + -- (access type) because we will link it dynamically. The functions + -- come from libX11.so. + -- + type XOpenDisplay is access function (Display_Name : char_array) return Address; + pragma Convention (C, XOpenDisplay); + function To_Ptr is new Ada.Unchecked_Conversion (Address, XOpenDisplay); + + type XDisplayWidth is access function (Display : Address; Screen : int) return int; + pragma Convention (C, XDisplayWidth); + function To_Ptr is new Ada.Unchecked_Conversion (Address, XDisplayWidth); + + Library : Address := dlopen (To_C ("libX11.so"), 1); + OpenDisplay : XOpenDisplay := To_Ptr (dlsym (Library, To_C ("XOpenDisplay"))); + DisplayWidth : XDisplayWidth := To_Ptr (dlsym (Library, To_C ("XDisplayWidth"))); +begin + if OpenDisplay /= null and then DisplayWidth /= null then + declare + Display : Address; + begin + Display := OpenDisplay (To_C (Value ("DISPLAY"))); + if Display = Null_Address then + Put_Line ("Unable to open display " & Value ("DISPLAY")); + else + Put_Line (Value ("DISPLAY") & " width is" & int'image (DisplayWidth (Display, 0))); + end if; + end; + else + Put_Line ("Unable to load the library"); + end if; +end Shared_Library_Call; diff --git a/Task/Call-a-function-in-a-shared-library/COBOL/call-a-function-in-a-shared-library.cob b/Task/Call-a-function-in-a-shared-library/COBOL/call-a-function-in-a-shared-library.cob new file mode 100644 index 0000000000..da813822b4 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/COBOL/call-a-function-in-a-shared-library.cob @@ -0,0 +1,37 @@ + identification division. + program-id. callsym. + + data division. + working-storage section. + 01 handle usage pointer. + 01 addr usage program-pointer. + + procedure division. + call "dlopen" using + by reference null + by value 1 + returning handle + on exception + display function exception-statement upon syserr + goback + end-call + if handle equal null then + display function module-id ": error getting dlopen handle" + upon syserr + goback + end-if + + call "dlsym" using + by value handle + by content z"perror" + returning addr + end-call + if addr equal null then + display function module-id ": error getting perror symbol" + upon syserr + else + call addr returning omitted + end-if + + goback. + end program callsym. diff --git a/Task/Call-a-function-in-a-shared-library/Odin/call-a-function-in-a-shared-library.odin b/Task/Call-a-function-in-a-shared-library/Odin/call-a-function-in-a-shared-library.odin new file mode 100644 index 0000000000..5e794455a9 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Odin/call-a-function-in-a-shared-library.odin @@ -0,0 +1,13 @@ +package beep +foreign import kernel32 "system:kernel32.lib" + +main :: proc() { + // Declare function in foreign block + foreign kernel32 { + @(link_name="Beep") Beep :: proc(x,y: u32) -> bool --- + } + // Calling Beep function + // https://learn.microsoft.com/en-us/windows/win32/api/utilapiset/nf-utilapiset-beep + // Beep(Frequency,Duration) + Beep( 750, 300 ) +} diff --git a/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto b/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto index e32bbfc202..f8805aa29b 100644 --- a/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto +++ b/Task/Call-a-function-in-a-shared-library/Pluto/call-a-function-in-a-shared-library.pluto @@ -1,8 +1,16 @@ -local s1, s2 = "Hello", " World!" +local s1, s2 = "Hello" .. string.rep("\0", 8), " World!" local ffi = require "pluto:ffi" -local lib = ffi.open(os.platform == "windows" ? "msvcrt" : "libc.so.6") +local libname +if os.platform == "windows" then + libname = "msvcrt" +elseif os.platform == "macos" then + libname = "libSystem.B.dylib" +else + libname = "libc.so.6" +end +local lib = ffi.open(libname) if lib then - print("Shared library found") + print($"Shared library, {libname}, found") lib:cdef[[ char *strcat(char *dest, const char *src); size_t strlen(const char *str); @@ -12,7 +20,7 @@ if lib then print(lib.strlen(s)) lib = nil else - print("Shared library not found.") + print($"Shared library, {libname}, not found.") local s = s1 .. s2 print(s) print(#s) diff --git a/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx b/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx index b2a25be44d..35af797e0f 100644 --- a/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx +++ b/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx @@ -1,15 +1,12 @@ --- 12 Sep 2025 +-- 21 Feb 2026 include Setting say 'CALL A FUNCTION IN A SHARED LIBRARY' say version say 'Dump the variable pool' say -if Pos('Regina',version) > 0 | Pos('ooRexx',version) > 0 then do - call RxFuncAdd 'sysloadfuncs','rexxutil','sysloadfuncs' - call SysLoadFuncs +if Glob.Regina | Glob.ooRexx then call SysDumpVariables -end else say 'Sorry! Not supported for your interpreter.' exit diff --git a/Task/Call-a-function/Ada/call-a-function-1.adb b/Task/Call-a-function/Ada/call-a-function-1.adb new file mode 100644 index 0000000000..2c7f62fc2f --- /dev/null +++ b/Task/Call-a-function/Ada/call-a-function-1.adb @@ -0,0 +1 @@ +S: String := Ada.Text_IO.Get_Line; diff --git a/Task/Call-a-function/Ada/call-a-function-2.adb b/Task/Call-a-function/Ada/call-a-function-2.adb new file mode 100644 index 0000000000..9f7a9920f7 --- /dev/null +++ b/Task/Call-a-function/Ada/call-a-function-2.adb @@ -0,0 +1,5 @@ +function F(X: Integer; Y: Integer := 0) return Integer; -- Y is optional +... +A : Integer := F(12); +B : Integer := F(12, 0); -- the same as A +C : Integer := F(12, 1); -- something different diff --git a/Task/Call-a-function/Ada/call-a-function-3.adb b/Task/Call-a-function/Ada/call-a-function-3.adb new file mode 100644 index 0000000000..d325032344 --- /dev/null +++ b/Task/Call-a-function/Ada/call-a-function-3.adb @@ -0,0 +1,12 @@ +type Integer_Array is array (Positive range <>) of Integer; +function Sum(A: Integer_Array) return Integer is + S: Integer := 0; +begin + for I in A'Range loop + S := S + A(I); + end loop; + return S; +end Sum; +... +A := Sum((1,2,3)); -- A = 6 +B := Sum((1,2,3,4)); -- B = 10 diff --git a/Task/Call-a-function/Ada/call-a-function-4.adb b/Task/Call-a-function/Ada/call-a-function-4.adb new file mode 100644 index 0000000000..cfb52c391a --- /dev/null +++ b/Task/Call-a-function/Ada/call-a-function-4.adb @@ -0,0 +1,9 @@ +function H (Int: Integer; + Fun: not null access function (X: Integer; Y: Integer) + return Integer); + return Integer; + +... + +X := H(A, F'Access) -- assuming X and A are Integers, and F is a function + -- taking two Integers and returning an Integer. diff --git a/Task/Call-a-function/Ada/call-a-function-5.adb b/Task/Call-a-function/Ada/call-a-function-5.adb new file mode 100644 index 0000000000..0850c849f8 --- /dev/null +++ b/Task/Call-a-function/Ada/call-a-function-5.adb @@ -0,0 +1,3 @@ +Positional := H(A, F'Access); +Named := H(Int => A, Fun => F'Access); +Mixed := H(A, Fun=>F'Access); diff --git a/Task/Call-a-function/COBOL/call-a-function.cob b/Task/Call-a-function/COBOL/call-a-function.cob new file mode 100644 index 0000000000..1fd60183bc --- /dev/null +++ b/Task/Call-a-function/COBOL/call-a-function.cob @@ -0,0 +1,65 @@ +CALL "No-Arguments" + +*> Fixed number of arguments. +CALL "2-Arguments" USING Foo Bar + +CALL "Optional-Arguments" USING Foo +CALL "Optional-Arguments" USING Foo Bar +*> If an optional argument is omitted and replaced with OMITTED, any following +*> arguments can still be specified. +CALL "Optional-Arguments" USING Foo OMITTED Bar +*> Interestingly, even arguments not marked as optional can be omitted without +*> a compiler warning. It is highly unlikely the function will still work, +*> however. +CALL "2-Arguments" USING Foo + +*> COBOL does not support a variable number of arguments, or named arguments. + +*> Values to return can be put in either one of the arguments or, in OpenCOBOL, +*> the RETURN-CODE register. +*> A standard function call cannot be done in another statement. +CALL "Some-Func" USING Foo +MOVE Return-Code TO Bar + +*> Intrinsic functions can be used in any place a literal value may go (i.e. in +*> statements) and are optionally preceded by FUNCTION. +*> Intrinsic functions that do not take arguments may optionally have a pair of +*> empty parentheses. +*> Intrinsic functions cannot be defined by the user. +MOVE FUNCTION PI TO Bar +MOVE FUNCTION MEDIAN(4, 5, 6) TO Bar + +*> Built-in functions/subroutines typically have prefixes indicating which +*> compiler originally incorporated it: +*> - C$ - ACUCOBOL-GT +*> - CBL_ - Micro Focus +*> - CBL_OC_ - OpenCOBOL +*> Note: The user could name their functions similarly if they wanted to. +CALL "C$MAKEDIR" USING Foo +CALL "CBL_CREATE_DIR" USING Foo +CALL "CBL_OC_NANOSLEEP" USING Bar +*> Although some built-in functions identified by numbers. +CALL X"F4" USING Foo Bar + +*> Parameters can be passed in 3 different ways: +*> - BY REFERENCE - this is the default way in OpenCOBOL and this clause may +*> be omitted. The address of the argument is passed to the function. +*> The function is allowed to modify the variable. +*> - BY CONTENT - a copy is made and the function is passed the address +*> of the copy, which it can then modify. This is recomended when +*> passing a literal to a function. +*> - BY VALUE - the function is passed the address of the argument (like a +*> pointer). This is mostly used to provide compatibility with other +*> languages, such as C. +CALL "Modify-Arg" USING BY REFERENCE Foo *> Foo is modified. +CALL "Modify-Arg" USING BY CONTENT Foo *> Foo is unchanged. +CALL "C-Func" USING BY VALUE Bar + +*> Partial application is impossible as COBOL does not support first-class +*> functions. +*> However, as functions are called using a string of their PROGRAM-ID, +*> you could pass a 'function' as an argument to another function, or store +*> it in a variable, or get it at runtime. +ACCEPT Foo *> Get a PROGRAM-ID from the user. +CALL "Use-Func" USING Foo +CALL Foo USING Bar diff --git a/Task/Call-a-function/Langur/call-a-function-5.langur b/Task/Call-a-function/Langur/call-a-function-5.langur index 7faa408981..c5ed446ddc 100644 --- a/Task/Call-a-function/Langur/call-a-function-5.langur +++ b/Task/Call-a-function/Langur/call-a-function-5.langur @@ -1 +1 @@ -val fibonacci = fn x:if x < 2 { x } else { fn((x - 1)) + fn((x - 2)) } +val fibonacci = fn(x) { if x < 2 { x } else { fn((x - 1)) + fn((x - 2)) } } diff --git a/Task/Call-a-function/REXX/call-a-function.rexx b/Task/Call-a-function/REXX/call-a-function.rexx new file mode 100644 index 0000000000..54326c2921 --- /dev/null +++ b/Task/Call-a-function/REXX/call-a-function.rexx @@ -0,0 +1,77 @@ +/* REXX *************************************************************** +* 29.07.2013 Walter Pachl trying to address the task concisely +*********************************************************************** +* f1 Calling a function that requires no arguments +* f2 Calling a function with a fixed number of arguments +* f3 Calling a function with optional arguments +* f4 Calling a function with a variable number of arguments +* f5 Calling a function with named arguments +* f6 Using a function in statement context +* f7 Using a function within an expression +* f8 Obtaining the return value of a function +* f8(...) is replaced by the returned value +* call f8 ... returned value is in special vatiable RESULT +* f9 Distinguishing built-in functions and user-defined functions +* bif is enforced by using its name quoted in uppercase +* fa,fb Distinguishing subroutines and functions +* Stating whether arguments are passed by value or by reference +* Arguments are passed by value +* ooRexx supports passing by reference (Use Arg instruction) +* Is partial application possible and how +* no ideas +**********************************************************************/ +say f1() +Say f2(1,2,3) +say f2(1,2,3,4) +say f3(1,,,4) +Say f4(1,2) +Say f4(1,2,3) +a=4700; b=11; +Say f5('A','B') +f6() /* returned value is used as command */ +x=f7()**2 +call f8 1,2; Say result '=' f8(1,2) +f9: Say 'DATE'('S') date() +call fa 11,22; Say result '=' fa(1,, + 2) /* the second comma above is for line continuation */ +Signal On Syntax +Call fb 1,2 +x=fb(1,2) +Exit +f1: Return 'f1 doesn''t need an argument' +f2: If arg()=3 Then + Return 'f2: Sum of 3 arguments:' arg(1)+arg(2)+arg(3) + Else + Return 'f2: Invalid invocation:' arg() 'arguments. Needed: 3' +f3: sum=0 + do i=1 To arg() + If arg(i,'E')=0 Then Say 'f3: Argument' i 'omitted' + Else sum=sum+arg(i) + End + Return 'f3 sum=' sum +f4: sum=0; Do i=1 To arg(); sum=sum+arg(i); End + Return 'f4: Sum of' arg() 'arguments is' sum +f5: Parse Arg p1,p2 + Say 'f5: Argument 1 ('p1') contains' value(p1) + Say 'f5: Argument 2 ('p2') contains' value(p2) + Return 'f5: sum='value(p1)+value(p2) +f6: Say 'f6: dir ft.rex' + Return 'dir ft.rex' +f7: Say 'f7 returns 7' + Return 7 +f8: Say 'f8 returns arg(1)+arg(2)' + Return arg(1)+arg(2) +date: Say 'date is my date function' + Return translate('ef/gh/abcd','DATE'('S'),'abcdefgh') +fa: Say 'fa returns arg(1)+arg(2)' + Return arg(1)+arg(2) +fb: Say 'fb:' arg(1)','arg(2) + Return + +Syntax: + Say 'Syntax raised in line' sigl + Say sourceline(sigl) + Say 'rc='rc '('errortext(rc)')' + If sigl=39 Then + Say 'fb cannot be invoked as function (it does not return a value' + Exit diff --git a/Task/Call-a-function/Red/call-a-function.red b/Task/Call-a-function/Red/call-a-function.red new file mode 100644 index 0000000000..2639b3e2b3 --- /dev/null +++ b/Task/Call-a-function/Red/call-a-function.red @@ -0,0 +1,38 @@ +;- function without agument +;- first example like a subroutine call +hello: does [print "hello"] +;- calling +hello +;- second return a value +phi: func [][return to-float ((1.0 + sqrt(5.0)) / 2.0)] +;-calling print phi +print phi +;-function with optional arguments +optional: func [arg1 /opt1 /opt2][ + print arg1 + if opt1 [print "option1"] + if opt2 [print "option2"] +] +;- calling +optional 10 +optional/opt1 10 +optional/opt2 10 +optional/opt1/opt2 10 +;function with variable number of arguments +;we can use block type to do it +blocksum: func [b][r: 0 foreach n b [r: r + n] r] +; calling +print blocksum [1] +print blocksum [1 2 3 4 5 6 7 8 9] +;- first class function +;- creating function from à function at run time +square: func[n][return (n * n)] +cube: func[n][ return (n * ( square n))] +;-calling +print cube 3 +;- use function as argument of another function +print cube square 3 +;- store functions in collections +myfuncs: [square cube] +;-calling +foreach f myfuncs [print reduce [f 2]] diff --git a/Task/Call-a-function/Uiua/call-a-function.uiua b/Task/Call-a-function/Uiua/call-a-function.uiua new file mode 100644 index 0000000000..c0004d9904 --- /dev/null +++ b/Task/Call-a-function/Uiua/call-a-function.uiua @@ -0,0 +1,18 @@ +# Generally functions have a fixed number of un-named arguments. +JustOne ← (1) # Nonadic. Returns a 1. +PlusOne ← +1 # Monadic. Adds 1 to its argument. +MeanOne ← ÷ 2 + # Dyadic. Mean of its two arguments. +# Triadic = ++, Tetradic = +++, Pentadic = ++++, etc + +# Values are passed and returned on the stack. +JustOne # -> 1 on the stack +PlusOne # consumes the 1, adds 1, leaves the 2 on the stack. +MeanOne 3 # MeanOne sees 3 and 2 on the stack and returns 2.5 + +# Some functions can take an optional suffix. +⁅1.23456 # ->1 +⁅₂1.23456 # -> 1.23 + +# Some operators can take function packs, leading to more flexibility. +# E.g. '⊃ fork' applies all the functions to its arguments. +⊃(¯|+|-|÷|×|$"_ _ _"1) 2 3 # -> ¯2 5 1 1.5 6 "1 2 3" diff --git a/Task/Call-an-object-method/Ada/call-an-object-method-1.adb b/Task/Call-an-object-method/Ada/call-an-object-method-1.adb new file mode 100644 index 0000000000..e93faaa423 --- /dev/null +++ b/Task/Call-an-object-method/Ada/call-an-object-method-1.adb @@ -0,0 +1,8 @@ + package My_Class is + type Object is tagged private; + procedure Primitive(Self: Object); -- primitive subprogram + procedure Dynamic(Self: Object'Class); + procedure Static; + private + type Object is tagged null record; + end My_Class; diff --git a/Task/Call-an-object-method/Ada/call-an-object-method-2.adb b/Task/Call-an-object-method/Ada/call-an-object-method-2.adb new file mode 100644 index 0000000000..2c4d8a5cbe --- /dev/null +++ b/Task/Call-an-object-method/Ada/call-an-object-method-2.adb @@ -0,0 +1,18 @@ + package body My_Class is + procedure Primitive(Self: Object) is + begin + Put_Line("Hello World!"); + end Primitive; + + procedure Dynamic(Self: Object'Class) is + begin + Put("Hi there! ... "); + Self.Primitive; -- dispatching call: calls different subprograms, + -- depending on the type of Self + end Dynamic; + + procedure Static is + begin + Put_Line("Greetings"); + end Static; + end My_Class; diff --git a/Task/Call-an-object-method/Ada/call-an-object-method-3.adb b/Task/Call-an-object-method/Ada/call-an-object-method-3.adb new file mode 100644 index 0000000000..f798d282a6 --- /dev/null +++ b/Task/Call-an-object-method/Ada/call-an-object-method-3.adb @@ -0,0 +1,11 @@ + package Other_Class is + type Object is new My_Class.Object with null record; + overriding procedure Primitive(Self: Object); + end Other_Class; + + package body Other_Class is + procedure Primitive(Self: Object) is + begin + Put_Line("Hello Universe!"); + end Primitive; + end Other_Class; diff --git a/Task/Call-an-object-method/Ada/call-an-object-method-4.adb b/Task/Call-an-object-method/Ada/call-an-object-method-4.adb new file mode 100644 index 0000000000..f839fbf175 --- /dev/null +++ b/Task/Call-an-object-method/Ada/call-an-object-method-4.adb @@ -0,0 +1,20 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Call_Method is + + package My_Class is ... -- see above + package body My_Class is ... -- see above + + package Other_Class is ... -- see above + package body Other_Class is ... -- see above + + Ob1: My_Class.Object; -- our "root" type + Ob2: Other_Class.Object; -- a type derived from the "root" type + +begin + My_Class.Static; + Ob1.Primitive; + Ob2.Primitive; + Ob1.Dynamic; + Ob2.Dynamic; +end Call_Method; diff --git a/Task/Call-an-object-method/COBOL/call-an-object-method-1.cob b/Task/Call-an-object-method/COBOL/call-an-object-method-1.cob new file mode 100644 index 0000000000..a661f29ef1 --- /dev/null +++ b/Task/Call-an-object-method/COBOL/call-an-object-method-1.cob @@ -0,0 +1,11 @@ +*> INVOKE statements. +INVOKE my-class "some-method" *> Factory object + USING BY REFERENCE some-parameter + RETURNING foo +INVOKE my-instance "another-method" *> Instance object + USING BY REFERENCE some-parameter + RETURNING foo + +*> Inline method invocation. +MOVE my-class::"some-method"(some-parameter) TO foo *> Factory object +MOVE my-instance::"another-method"(some-parameter) TO foo *> Instance object diff --git a/Task/Call-an-object-method/COBOL/call-an-object-method-2.cob b/Task/Call-an-object-method/COBOL/call-an-object-method-2.cob new file mode 100644 index 0000000000..a15053b585 --- /dev/null +++ b/Task/Call-an-object-method/COBOL/call-an-object-method-2.cob @@ -0,0 +1,3 @@ +INVOKE some-instance "FactoryObject" RETURNING foo-factory +*> foo-factory can be treated like a normal object reference. +INVOKE foo-factory "someMethod" diff --git a/Task/Call-an-object-method/F-Sharp/call-an-object-method.fs b/Task/Call-an-object-method/F-Sharp/call-an-object-method.fs new file mode 100644 index 0000000000..0cf49e8a23 --- /dev/null +++ b/Task/Call-an-object-method/F-Sharp/call-an-object-method.fs @@ -0,0 +1,8 @@ +// Call an object method. Nigel Galloway: April 17th., 2026 +type myClass(g:string)= + let n=g + static member whoAreUstat n=printfn "A static member of myClass %s" n + member this.whoAreUins=printfn "An instance member of myClass %s" n + +myClass.whoAreUstat "Nigel" +(myClass "Nigel").whoAreUins diff --git a/Task/Call-an-object-method/Haxe/call-an-object-method.hx b/Task/Call-an-object-method/Haxe/call-an-object-method.hx new file mode 100644 index 0000000000..5eb6663bd5 --- /dev/null +++ b/Task/Call-an-object-method/Haxe/call-an-object-method.hx @@ -0,0 +1,13 @@ +class ExampleClass { + public function exampleMethod() { + return "This is a method!"; + } + public function new() {} +} + +class Main { + static public function main():Void { + var exampleObject = new ExampleClass(); + trace(exampleObject.exampleMethod()); + } +} diff --git a/Task/Call-an-object-method/Pluto/call-an-object-method.pluto b/Task/Call-an-object-method/Pluto/call-an-object-method.pluto new file mode 100644 index 0000000000..c8ef2d4bff --- /dev/null +++ b/Task/Call-an-object-method/Pluto/call-an-object-method.pluto @@ -0,0 +1,9 @@ +class myclass + static function smethod() print("static method called") end + + function imethod() print("instance method called") end +end + +myclass.smethod() +local mc = new myclass() +mc.imethod() diff --git a/Task/Call-an-object-method/PowerShell/call-an-object-method.ps1 b/Task/Call-an-object-method/PowerShell/call-an-object-method.ps1 new file mode 100644 index 0000000000..dc5f5ea454 --- /dev/null +++ b/Task/Call-an-object-method/PowerShell/call-an-object-method.ps1 @@ -0,0 +1,3 @@ +$Date = Get-Date +$Date.AddDays( 1 ) +[System.Math]::Sqrt( 2 ) diff --git a/Task/Call-an-object-method/Red/call-an-object-method.red b/Task/Call-an-object-method/Red/call-an-object-method.red new file mode 100644 index 0000000000..cfbd2101be --- /dev/null +++ b/Task/Call-an-object-method/Red/call-an-object-method.red @@ -0,0 +1,22 @@ +;-object creation +my-proto: object [ + val1: 2 + val2: 3 + set: func [arg1 arg2] [self/val1: arg1 self/val2: arg2] + sum: func [][ return (val1 + val2)] +] + +;-create an instance +my-obj1: copy my-proto +;-calling internal method to get value +print my-obj1/sum + +;-create a new instance +my-obj2: copy my-proto +;- calling an internal mathod to set value +my-obj2/set 1 1 +;-calling the get method +print my-obj2/sum + +;-calling the get method on the first object +print my-obj1/sum diff --git a/Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.adb b/Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.adb new file mode 100644 index 0000000000..8da706fcd8 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Ada/camel-case-and-snake-case.adb @@ -0,0 +1,114 @@ +with Ada.Characters.Handling, + Ada.Strings, + Ada.Strings.Fixed, + Ada.Strings.Maps, + Ada.Strings.Maps.Constants, + Ada.Text_IO; + +use Ada.Characters.Handling, + Ada.Strings, + Ada.Strings.Fixed, + Ada.Strings.Maps, + Ada.Strings.Maps.Constants; + +procedure Camel_Snake_Case is + type Sample_Array is array (Positive range <>) of access constant String; + -- Work around for array elements needing to be the same size. + -- Could also use Ada.Strings.Bounded_Strings instead. + S1 : aliased constant String := "snakeCase"; + S2 : aliased constant String := "snake_case"; + S3 : aliased constant String := "variable_10_case"; + S4 : aliased constant String := "variable10Case"; + S5 : aliased constant String := "ɛrgo rE tHis"; + S6 : aliased constant String := "hurry-up-joe!"; + S7 : aliased constant String := "c://my-docs/happy_Flag-Day/12.doc"; + S8 : aliased constant String := " spaces "; + + Samples : constant Sample_Array := + ( + S1'Access, + S2'Access, + S3'Access, + S4'Access, + S5'Access, + S6'Access, + S7'Access, + S8'Access + ); + + function Should_Insert (This, Last : Character) return Boolean is + ( + (Is_In (Last, Lower_Set) and then + Is_In (This, Upper_Set or Decimal_Digit_Set)) + or else + (Is_In (Last, Upper_Set) and then + Is_In (This, Decimal_Digit_Set)) + or else + (Is_In (Last, Decimal_Digit_Set) and then + Is_In (This, Upper_Set)) + ); + + function To_Snake_Case (S : String) return String is + Trimmed : constant String := Trim (S, Both); + Separator_Map : constant Character_Mapping := To_Mapping (" -", "__"); + Translated : constant String := Translate (Trimmed, Separator_Map); + New_Word_Set : constant Character_Set := Upper_Set or Decimal_Digit_Set; + New_Word_Chars : constant Natural := Count (Translated, New_Word_Set); + Snake : String (1 .. Translated'Length + New_Word_Chars); + J : Positive := 2; + L : Character; + begin + Snake (1 .. Translated'Length) := Translated; + + for I in 2 .. Translated'Last loop + if Should_Insert (Translated (I), Translated (I - 1)) then + Snake (J) := '_'; + J := J + 1; + end if; + + L := Translated (I); + + if Is_In (Translated (I), Upper_Set) then + L := To_Lower (L); + end if; + + Snake (J) := L; + J := J + 1; + end loop; + + return Snake (1 .. J - 1); + end To_Snake_Case; + + function To_Camel_Case (S : String) return String is + Trimmed : constant String := Trim (S, Both); + Separators : constant Character_Set := To_Set (" -_"); + Snake : String (Trimmed'Range) := Trimmed; + J : Positive := 2; + begin + for I in 2 .. Trimmed'Length loop + if not Is_In (Trimmed (I), Separators) then + if Is_In (Trimmed (I - 1), Separators) and then + Is_In (Trimmed (I), Lower_Set) then + Snake (J) := To_Upper (Trimmed (I)); + else + Snake (J) := Trimmed (I); + end if; + + J := J + 1; + end if; + end loop; + + return Snake (1 .. J - 1); + end To_Camel_Case; + +begin + Ada.Text_IO.Put_Line ("=Snake Case="); + for I of Samples loop + Ada.Text_IO.Put_Line (I.all & " => " & To_Snake_Case (I.all)); + end loop; + + Ada.Text_IO.Put_Line ("=Camel Case="); + for I of Samples loop + Ada.Text_IO.Put_Line (I.all & " => " & To_Camel_Case (I.all)); + end loop; +end Camel_Snake_Case; diff --git a/Task/Camel-case-and-snake-case/Crystal/camel-case-and-snake-case.cr b/Task/Camel-case-and-snake-case/Crystal/camel-case-and-snake-case.cr new file mode 100644 index 0000000000..38a8fc567f --- /dev/null +++ b/Task/Camel-case-and-snake-case/Crystal/camel-case-and-snake-case.cr @@ -0,0 +1,6 @@ +["snakeCase", "snake_case", "variable_10_case", "variable10Case", "ɛrgo rE tHis", + "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces "].each do |ident| + print ident, " => " + print ident.strip.gsub(/[ -]/, "_").camelcase, ", " + puts ident.strip.gsub(/[ -]/, "_").underscore +end diff --git a/Task/Camel-case-and-snake-case/Fortran/camel-case-and-snake-case.f b/Task/Camel-case-and-snake-case/Fortran/camel-case-and-snake-case.f new file mode 100644 index 0000000000..8d54399adc --- /dev/null +++ b/Task/Camel-case-and-snake-case/Fortran/camel-case-and-snake-case.f @@ -0,0 +1,291 @@ +! Camel case and snake case +! +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! +! +! U.B., August 2025 +! +program CaseConverter + +implicit none + +! sep is a marker to separate words within given strings. +! Selected "§" because this is never part of a legit text. +! +character, parameter :: sep='§' + +character (len=:), allocatable :: testWord + + +print *, ' ***** Converting test strings to Snake Case *****' + +testWord = 'snakeCase' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'snake_case' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'variable_10_case' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'variable10Case' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'ɛrgo rE tHis' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'hurry-up-joe!' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = 'c://my-docs/happy_Flag-Day/12.doc' +call printResult (testWord, toSnakeCase (testWord)) + +testWord = ' spaces ' +call printResult (testWord, toSnakeCase (testWord)) + +print * +print *, ' ***** Converting test strings to Camel Case *****' + +testWord = 'snakeCase' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'snake_case' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'variable_10_case' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'variable10Case' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'ɛrgo rE tHis' +call printResult (testWord, toCamelCase(testWord)) + +testWord = 'hurry-up-joe!' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = 'c://my-docs/happy_Flag-Day/12.doc' +call printResult ( testWord, toCamelCase (testWord) ) + +testWord = ' spaces ' +call printResult ( testWord, toCamelCase (testWord) ) + + + + +contains + + +! ---------------------------------------------------------- +! print with variable format to display the greek "ɛ" +! and the following text positioned correctly. +! Letter "ɛ" uses 2 bytes so len("ɛ") = 2 but ulen("ɛ") = 1 +! ---------------------------------------------------------- + +subroutine printResult (a,b) +character*(*), intent(in) :: a,b +character (len=100) ::fmt +write (fmt, *) '(A', 34+ (len(a)-ulen(a)) ,', " => ",A)' +print fmt, a, b + +end subroutine printResult + + +!--------------------------------------- +! change ASCII a...z to upper case a...z +!--------------------------------------- +function toupper (c) result(retc) + +character ::c +character :: retc + +if (c >='a' .and. c <= 'z') then + retc = achar (iachar('A') + (iachar(c)-iachar('a'))) +else + retc = c +end if + +end function toupper + +!--------------------------------------- +! change ASCII A...Z to lower case a...z +!--------------------------------------- +function tolower (c) result(retc) + +character ::c +character :: retc + +if (c >='A' .and. c <= 'Z') then ! is upper case + retc = achar (iachar('a') + (iachar(c)-iachar('A'))) +else + retc = c +end if + +end function tolower + +!--------------------------------------------------------------------------------- +! Scan input text, mark all positions between distinct words within the text +! so that later in the actual conversion these points can be rewritten accordingly. +!--------------------------------------------------------------------------------- +function prepare (txt) result (newtext) + +character (len=*), intent (in) :: txt +character (len=:), allocatable :: text, newtext +integer :: ip1, ip2, ip3, l +character :: beginword + + +newtext=''; + +! First remove leading and trailing spaces +text = trim (txt) +text = adjustl (text) +text = trim (text) +l = len_trim(text) + +ip1 = 1 +ip2 = 2 +ip3 = 1 +do while (ip2 <= l) + if (text(ip2:ip2) >= 'A' .and. text(ip2:ip2) <='Z' ) then ! upcase letter indicates beginning of a word + newtext = newtext(:len_trim(newtext)) // text(ip1:ip2-1) // sep + ip1 = ip2 + ip2 = ip1+1 + else if (text(ip2:ip2) .eq. '_' & + .or. text(ip2:ip2) .eq. '-' & + .or. text(ip2:ip2) .eq. ' ' ) then ! Separator is behind current word, new word following. + if (ip2 .lt. l) then ! ip2+1 still inside text + beginword = tolower (text(ip2+1:ip2+1)) + newtext = newtext(:len_trim(newtext)) // text (ip1:ip2-1) // sep // beginword + else + ! separator at ip2 is last character of text. Just drop it. + newtext = newtext(:len_trim(newtext)) // text (ip1:ip2-1) + endif + ip1 = ip2+2 ! skip separator and begin of next word + ip2 = ip1 + else + ip2 = ip2 + 1 + end if +end do + +newtext = newtext(:len_trim(newtext)) // text(ip1:) + +end function prepare + +!----------------------------------- +! Convert prepared text to CamelCase +!----------------------------------- +function toCamelCase (txt) result(newtext) +! +! 1st char is lowercase, all spaces removed and word beginnings upperCase +! +character (len=*), intent (in) :: txt +character (:), allocatable :: text, newtext +integer :: ip, l +character :: beginword + +newtext = '' +text = prepare (txt) + +l = len_trim(text) +newtext = newtext(:len_trim(newtext)) // tolower (text(1:1)) + +ip = 2 + +do while (ip <= l) + if (text(ip:ip) .eq. sep) then + ip = ip + 1 ! skip the separator + if (ip ( int(Z'C0') + 1)) .and. ( ich < int(Z'E0') )) THEN + retlen=2 + else if ( ich < int(Z'F0') ) THEN + retlen=3 + else if ( ich <= int(Z'F4') ) THEN + retlen=4 + else + retlen=1 !assume we process larger seqences, 1 by 1 bytes + end if +end function + + +end program diff --git a/Task/Camel-case-and-snake-case/Go/camel-case-and-snake-case.go b/Task/Camel-case-and-snake-case/Go/camel-case-and-snake-case.go new file mode 100644 index 0000000000..143ef584c5 --- /dev/null +++ b/Task/Camel-case-and-snake-case/Go/camel-case-and-snake-case.go @@ -0,0 +1,104 @@ +package main + +import ( + "fmt" + "strings" + "unicode" +) + +func snakeCaseToCamelCase(word string, sep rune) string { + var sb strings.Builder + + wordRunes := []rune(strings.TrimSpace(word)) + wordLen := len(wordRunes) + + for i := 0; i < wordLen; i++ { + c := wordRunes[i] + + if c == sep { + if i+1 < wordLen && wordRunes[i+1] != sep { + sb.WriteRune(unicode.ToUpper(wordRunes[i+1])) + i++ + } + } else { + if i == 0 { + c = unicode.ToLower(c) + } + sb.WriteRune(c) + } + } + + return sb.String() +} + +func camelCaseToSnakeCase(word string, sep rune) string { + word = strings.TrimSpace(word) + var sb strings.Builder + var lastRune rune + + for i, c := range word { + if i != 0 && unicode.IsUpper(c) { + if lastRune != sep { + sb.WriteRune(sep) + } + } + sb.WriteRune(unicode.ToLower(c)) + lastRune = c + } + + return sb.String() +} + +func main() { + words := []string{ + "snakeCase", + "snake_case", + "variable_10_case", + "variable10Case", + "ɛrgo rE tHis", + "hurry-up-joe!", + "c://my-docs/happy_Flag-Day/12.doc", + " spaces ", + } + + fmt.Print("snake_case to camelCase:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", snakeCaseToCamelCase(word, '_')) + } + + fmt.Println() + fmt.Print("kebab-case to camelCase:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", snakeCaseToCamelCase(word, '-')) + } + + fmt.Println() + fmt.Print("space case to camelCase:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", snakeCaseToCamelCase(word, ' ')) + } + + fmt.Println() + fmt.Print("camelCase to snake_case:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", camelCaseToSnakeCase(word, '_')) + } + + fmt.Println() + fmt.Print("camelCase to kebab-case:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", camelCaseToSnakeCase(word, '-')) + } + + fmt.Println() + fmt.Print("camelCase to space case:\n\n") + + for _, word := range words { + fmt.Println(word, "=>", camelCaseToSnakeCase(word, ' ')) + } +} diff --git a/Task/Camel-case-and-snake-case/Pluto/camel-case-and-snake-case.pluto b/Task/Camel-case-and-snake-case/Pluto/camel-case-and-snake-case.pluto new file mode 100644 index 0000000000..fdfb1b00cc --- /dev/null +++ b/Task/Camel-case-and-snake-case/Pluto/camel-case-and-snake-case.pluto @@ -0,0 +1,56 @@ +local fmt = require "fmt" + +local function to_camel(snake) + snake = snake:strip() + local camel = "" + local underscore = false + for i = 1, #snake do + local c = snake[i] + if c in "_- " then + underscore = true + elseif underscore then + camel ..= c:upper() + underscore = false + else + camel ..= c + end + end + return camel +end + +local function to_snake(camel) + camel = camel:strip():replace(" ", "_") -- we don't want any spaces in the result + local snake = "" + local first = true + for i = 1, #camel do + local c = camel[i] + if first then + snake ..= c + first = false + elseif !first and "A" <= c <= "Z" then + if snake[-1] == "_" or snake[-1] == "-" then + snake ..= c:lower() + else + snake ..= "_" .. c:lower() + end + else + snake ..= c + end + end + return snake +end + +local tests = { + "snakeCase", "snake_case", "variable_10_case", "variable10Case", "ɛrgo rE tHis", + "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces " +} + +print(" === to_snake_case ===") +for tests as camel do + fmt.print("%s -> %s", fmt.lpad(camel, 33), to_snake(camel)) +end + +print("\n === toCamelCase ===") +for tests as snake do + fmt.print("%s -> %s", fmt.lpad(snake, 33), to_camel(snake)) +end diff --git a/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.adb b/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.adb new file mode 100644 index 0000000000..a138a754ae --- /dev/null +++ b/Task/Canonicalize-CIDR/Ada/canonicalize-cidr.adb @@ -0,0 +1,105 @@ +with Ada.Strings; +with Ada.Strings.Fixed; +with Ada.Strings.Maps; +with Ada.Text_IO; + +use Ada.Strings; +use Ada.Strings.Fixed; +use Ada.Strings.Maps; +use Ada.Text_IO; + +procedure Canonicalize_CIDR is + type IP_Octet_Type is mod 256; + + type IP_Record_Type is record + A, B, C, D : IP_Octet_Type; + end record + with Size => 32; + + for IP_Record_Type use record + -- Use little-endian ordering to match bit array + D at 0 range 0 .. 7; + C at 1 range 0 .. 7; + B at 2 range 0 .. 7; + A at 3 range 0 .. 7; + end record; + + type IP_Bitarray_Type is array (0 .. 31) of Boolean + with Component_Size => 1; + + subtype IP_Mask_Type is Natural range 0 .. 32; + + type IP_CIDR_Type is record + IP : IP_Record_Type; + Mask : IP_Mask_Type; + end record; + + function Parse_IP_CIDR (S : String) return IP_CIDR_Type is + IP_Record : IP_CIDR_Type; + Digit_Range : Character_Range := ('0', '9'); + Digit_Set : Character_Set := To_Set (Digit_Range); + Octets : array (1 .. 4) of IP_Octet_Type; + First : Positive; + Last : Natural := 0; + begin + for I in Octets'Range loop + Find_Token (S, Digit_Set, Last + 1, Inside, First, Last); + Octets (I) := IP_Octet_Type'Value (S (First .. Last)); + end loop; + IP_Record.IP.A := Octets (1); + IP_Record.IP.B := Octets (2); + IP_Record.IP.C := Octets (3); + IP_Record.IP.D := Octets (4); + + Find_Token (S, Digit_Set, Last + 1, Inside, First, Last); + IP_Record.Mask := IP_Mask_Type'Value (S (First .. Last)); + + return IP_Record; + end Parse_IP_CIDR; + + procedure Canonicalize_IP_CIDR (Addr : in out IP_CIDR_Type) is + -- Fun part. I can overlay different types over the same bits. + Bit_Overlay : IP_Bitarray_Type with Address => Addr.IP'Address; + begin + for I in Bit_Overlay'First .. Bit_Overlay'Last - Addr.Mask loop + Bit_Overlay (I) := False; + end loop; + end Canonicalize_IP_CIDR; + + procedure Put_IP_CIDR (Addr : IP_CIDR_TYPE) is + package Octet_IO is new Ada.Text_IO.Modular_IO (IP_Octet_Type); + package Mask_IO is new Ada.Text_IO.Integer_IO (IP_Mask_Type); + begin + Octet_IO.Put (Addr.IP.A, 0); + Put ("."); + Octet_IO.Put (Addr.IP.B, 0); + Put ("."); + Octet_IO.Put (Addr.IP.C, 0); + Put ("."); + Octet_IO.Put (Addr.IP.D, 0); + Put ("/"); + Mask_IO.Put (Addr.Mask, 0); + end Put_IP_CIDR; + + procedure Show_IP_Canonicalize (S : String) is + Canon : IP_CIDR_Type := Parse_IP_CIDR (S); + begin + Canonicalize_IP_Cidr (Canon); + Put (S & " -> "); + Put_IP_CIDR (Canon); + New_Line; + end Show_IP_Canonicalize; + + Test_IPs : array (1 .. 5) of String (1 .. 18) := + ( + "36.18.154.103/12 ", + "62.62.197.11/29 ", + "67.137.119.181/4 ", + "161.214.74.21/24 ", + "184.232.176.184/18" + ); +begin + for I of Test_IPs loop + Show_IP_Canonicalize (I); + end loop; +end Canonicalize_CIDR; diff --git a/Task/Canonicalize-CIDR/FutureBasic/canonicalize-cidr.basic b/Task/Canonicalize-CIDR/FutureBasic/canonicalize-cidr.basic new file mode 100644 index 0000000000..8594d42eb7 --- /dev/null +++ b/Task/Canonicalize-CIDR/FutureBasic/canonicalize-cidr.basic @@ -0,0 +1,132 @@ +// +// Canonicalize CIDR +// +// Using FutureBasic 7.0.34 +// August 25, R.W +// +// Given a Classless Inter-Domain Routing (CIDR) +// IPv4 address, returns the canonical form. +// + +Int networkWidth // network width in bits +CFStringRef errorCode // global err and CCIDR +CFStringRef CCIDR // canonical CIDR IPv4 + +// Type for IP address +begin record IPv4_Address + Int octets[3] // xxx.xxx.xxx.xx/xx +end record + +// Validate CIDR string +local fn ValidateCIDR(ip as IPv4_Address, SnetworkWidth as Int, cidr as CFStringRef) as Boolean + Int i + boolean result + result = _True + if instr(0, cidr, @"/") == NSNotFound + errorCode = concat(@"Bad CIDR ",cidr) + result = _False + return result + end if + if SnetworkWidth < 1 || SnetworkWidth > 32 //validate network width + errorCode = concat(@"Bad Net Width",str(networkWidth)) + result = _False + return result + end if + for i = 0 to 3 + if ip.octets[i] > 255 + errorCode = concat(@"Bad Octet ",str(ip.octets[i])) + result = _False + return result + end if + next +end fn = result + +// Check if a character is a digit +local fn IsDigit(ch as CFStringRef) as boolean + Boolean IsDigit + IsDigit = (ucc(ch) > 47) && (ucc(ch) < 58) +end fn = IsDigit + +// Parse CIDR string into IP structure and network width +local fn ParseIPv4_Address(cidr as CFStringRef) as IPv4_Address + IPv4_Address ip + Int i, slashPos, currentOctet, octetValue + CFStringRef ipPart + ipPart = @"" + slashPos = instr(0, cidr, @"/") + if slashPos > 0 + ipPart = left(cidr, slashPos) + networkWidth = Intval(mid(cidr, slashPos + 1)) + else + ipPart = cidr + networkWidth = -1 + end if + currentOctet = 0: octetValue = 0 + for i = 0 to len(ipPart)-1 + select case mid(ipPart, i, 1) + case @"." + ip.octets[currentOctet] = octetValue + currentOctet ++ + octetValue = 0 + case else + if fn IsDigit(mid(ipPart, i, 1)) + octetValue = octetValue * 10 + Intval(mid(ipPart, i, 1)) + end if + end select + next + ip.octets[currentOctet] = octetValue +end fn = ip + +// Apply network mask to IP +local fn ApplyNetworkMask(ip as IPv4_Address, SnetworkWidth as Int) as IPv4_Address + IPv4_Address result + Int completeOctets, remainingBits, i + result = ip + completeOctets = SnetworkWidth \ 8 //octet bits + remainingBits = SnetworkWidth AND 7 + if completeOctets < 4 + result.octets[completeOctets] = result.octets[completeOctets] AND (255 - 2^(8 - remainingBits) + 1) + for i = completeOctets + 1 to 3 + result.octets[i] = 0 + next + end if +end fn = result + +// Process a CIDR string, sets global CCIDR +local fn ProcessCIDR(cidr as CFStringRef) as CFStringRef + IPv4_Address ip + CFStringRef result + Int i + result = @"" + ip = fn ParseIPv4_Address(cidr) + if fn ValidateCIDR(ip, networkWidth, cidr) // validate + ip = fn ApplyNetworkMask(ip, networkWidth) + result = mid(str(ip.octets[0]),1) + for i = 1 to 3 + result = concat(result,@".",mid(str(ip.octets[i]),1)) + next + result = concat(result,@"/",mid(str(networkWidth),1)) + else + print@ errorCode + end if + CCIDR = result +end fn = result + +// +// Main + +Window 1,@"Canonicalize CIDR" +print@ + +// Test data from the Rosetta Stone task + +CFStringRef cidr(5) = {@"87.70.141.1/22", @"36.18.154.103/12", @"62.62.197.11/29", ¬ +@"67.137.119.181/4", @"161.214.74.21/24", @"184.232.176.184/18"} + +for Int i = 0 to 5 + print@ fn ProcessCIDR(cidr(i)) +next + +HandleEvents + +// diff --git a/Task/Canonicalize-CIDR/Pluto/canonicalize-cidr.pluto b/Task/Canonicalize-CIDR/Pluto/canonicalize-cidr.pluto new file mode 100644 index 0000000000..182f3661d5 --- /dev/null +++ b/Task/Canonicalize-CIDR/Pluto/canonicalize-cidr.pluto @@ -0,0 +1,35 @@ +local fmt = require "fmt" + +-- Canonicalize a CIDR block: make sure none of the host bits are set. +local function canonicalize(cidr) + -- Dotted-decimal / bits in network part. + local split = cidr:split("/") + local dotted = split[1] + local size = tonumber(split[2]) + + -- Get IP as binary string. + local binary = dotted:split("."):map(|n| -> fmt.lpad(fmt.bin(tonumber(n)), 8, "0")):concat() + + -- Replace the host part with all zeros. + binary = binary:sub(1, size) .. string.rep("0", 32 - size) + + -- Convert back to dotted-decimal. + local chunks = binary:split(""):chunk(8):map(|c| -> c:concat()) + local canon = chunks:map(|c| -> tonumber(c, 2)):concat(".") + + -- And return + return canon .. "/" .. split[2] +end + +local tests = { + "87.70.141.1/22", + "36.18.154.103/12", + "62.62.197.11/29", + "67.137.119.181/4", + "161.214.74.21/24", + "184.232.176.184/18" +} + +for tests as test do + fmt.print("%-18s -> %s", test, canonicalize(test)) +end diff --git a/Task/Canonicalize-CIDR/V-(Vlang)/canonicalize-cidr.v b/Task/Canonicalize-CIDR/V-(Vlang)/canonicalize-cidr.v new file mode 100644 index 0000000000..7b647c4936 --- /dev/null +++ b/Task/Canonicalize-CIDR/V-(Vlang)/canonicalize-cidr.v @@ -0,0 +1,47 @@ +import strconv +import log + +// canonicalize a CIDR block: make sure none of the host bits are set +fn canonicalize(cidr string) string { + mut l := log.Log{} + mut binary := "" + mut ir := 0 + mut num := i64(0) + mut bin, mut canon := []string{}, []string{} + + // dotted-decimal / bits in network part + split_arr := cidr.split("/") + dotted := split_arr[0] + size := strconv.atoi(split_arr[1]) or {l.fatal('fatal 1')} + + // get IP as binary string + for n in dotted.split(".") { + ir = strconv.atoi(n) or {l.fatal('fatal 2')} + bin << "${ir:08b}" + } + + // replace the host part with all zeros + binary = bin.join("")[0..size] + "0".repeat(32 - size) + + // convert back to dotted-decimal + for i := 0; i < binary.len; i += 8 { + num = strconv.parse_int(binary[i..i + 8], 2, 64) or {l.fatal('fatal 3')} + canon << "${num}" + } + + // and return + return canon.join(".") + "/" + split_arr[1] +} + +fn main() { + tests := ["87.70.141.1/22", + "36.18.154.103/12", + "62.62.197.11/29", + "67.137.119.181/4", + "161.214.74.21/24", + "184.232.176.184/18"] + + for test in tests { + println("${test:-18} -> ${canonicalize(test)}") + } +} diff --git a/Task/Cantor-set/Ada/cantor-set.adb b/Task/Cantor-set/Ada/cantor-set.adb new file mode 100644 index 0000000000..56b5a5996a --- /dev/null +++ b/Task/Cantor-set/Ada/cantor-set.adb @@ -0,0 +1,24 @@ +with Ada.Text_IO; + +procedure Cantor_Set is + + subtype Level_Range is Integer range 1 .. 5; + Image : array (Level_Range) of String (1 .. 81) := (others => (others => ' ')); + + procedure Cantor (Level : Natural; Length : Natural; Start : Natural) is + begin + if Level in Level_Range then + Image (Level) (Start .. Start + Length - 1) := (others => '*'); + Cantor (Level + 1, Length / 3, Start); + Cantor (Level + 1, Length / 3, Start + 2 * Length / 3); + end if; + end Cantor; +begin + Cantor (Level => Level_Range'First, + Length => 81, + Start => 1); + + for L in Level_Range loop + Ada.Text_IO.Put_Line (Image (L)); + end loop; +end Cantor_Set; diff --git a/Task/Cantor-set/C/cantor-set-1.c b/Task/Cantor-set/C/cantor-set-1.c new file mode 100644 index 0000000000..265194b8fe --- /dev/null +++ b/Task/Cantor-set/C/cantor-set-1.c @@ -0,0 +1,38 @@ +#include + +#define WIDTH 81 +#define HEIGHT 5 + +char lines[HEIGHT][WIDTH]; + +void init() { + int i, j; + for (i = 0; i < HEIGHT; ++i) { + for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; + } +} + +void cantor(int start, int len, int index) { + int i, j, seg = len / 3; + if (seg == 0) return; + for (i = index; i < HEIGHT; ++i) { + for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; + } + cantor(start, seg, index + 1); + cantor(start + seg * 2, seg, index + 1); +} + +void print() { + int i, j; + for (i = 0; i < HEIGHT; ++i) { + for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); + printf("\n"); + } +} + +int main() { + init(); + cantor(0, WIDTH, 1); + print(); + return 0; +} diff --git a/Task/Cantor-set/C/cantor-set-2.c b/Task/Cantor-set/C/cantor-set-2.c new file mode 100644 index 0000000000..6371752161 --- /dev/null +++ b/Task/Cantor-set/C/cantor-set-2.c @@ -0,0 +1,28 @@ +#include + +#define WIDTH 81 + +int l, w, n, i; + +void split (char* s) +{ + l /= 3; n = 0; + + do { + n += l; if (s[n] != ' ') for (i = 0; i < l; i++) s[n+i] = ' '; n += l+l; + } while (n < w); +} + +void go (char* s) +{ + puts (s); do { split (s); puts (s); } while (l > 1); +} + +int main () +{ + char s[WIDTH+1]; + + l = w = WIDTH; + for (i = 0; i < WIDTH; i++) s[i] = '#'; s[WIDTH] = '\0'; go (s); + return (0); +} diff --git a/Task/Cantor-set/COBOL/cantor-set.cob b/Task/Cantor-set/COBOL/cantor-set.cob new file mode 100644 index 0000000000..23b91b1fde --- /dev/null +++ b/Task/Cantor-set/COBOL/cantor-set.cob @@ -0,0 +1,48 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. CANTOR. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 SETTINGS. + 03 NUM-LINES PIC 9 VALUE 5. + 03 FILL-CHAR PIC X VALUE '#'. + 01 VARIABLES. + 03 CUR-LINE. + 05 CHAR PIC X OCCURS 81 TIMES. + 03 WIDTH PIC 99. + 03 CUR-SIZE PIC 99. + 03 POS PIC 99. + 03 MAXPOS PIC 99. + 03 NEXTPOS PIC 99. + 03 I PIC 99. + + PROCEDURE DIVISION. + BEGIN. + COMPUTE WIDTH = 3 ** (NUM-LINES - 1). + PERFORM INIT. + MOVE WIDTH TO CUR-SIZE. + DISPLAY CUR-LINE. + PERFORM DO-LINE UNTIL CUR-SIZE IS EQUAL TO 1. + STOP RUN. + + INIT. + PERFORM INIT-CHAR VARYING I FROM 1 BY 1 + UNTIL I IS GREATER THAN WIDTH. + + INIT-CHAR. + MOVE FILL-CHAR TO CHAR(I). + + DO-LINE. + DIVIDE 3 INTO CUR-SIZE. + MOVE 1 TO POS. + SUBTRACT CUR-SIZE FROM WIDTH GIVING MAXPOS. + PERFORM BLANK-REGIONS UNTIL POS IS GREATER THAN MAXPOS. + DISPLAY CUR-LINE. + + BLANK-REGIONS. + ADD CUR-SIZE TO POS. + PERFORM BLANK-CHAR CUR-SIZE TIMES. + + BLANK-CHAR. + MOVE SPACE TO CHAR(POS). + ADD 1 TO POS. diff --git a/Task/Cantor-set/M4/cantor-set.m4 b/Task/Cantor-set/M4/cantor-set.m4 new file mode 100644 index 0000000000..4e62535e27 --- /dev/null +++ b/Task/Cantor-set/M4/cantor-set.m4 @@ -0,0 +1,29 @@ +local WIDTH = 81 +divert(-1) +changequote(`[',`]') + +define([Cantor],[dnl +define([cantor],[C() +])dnl +define([line],[C()])dnl +define([C],[[C()C()C()]])dnl +define([_],[[_()_()_()]])dnl +Cantor_loop([$1])dnl +undefine([line])dnl +define([C],[*])dnl +define([_],[ ])dnl +cantor()dnl +undefine([C])dnl +undefine([_])dnl +undefine([cantor])dnl +]) + +define([Cantor_loop],[ifelse([$1],[0],,[dnl +pushdef([C],[[C()_()C()]])dnl +define([line],line)dnl +popdef([C])dnl +define([cantor],cantor()defn([line]) +)dnl +Cantor_loop(decr([$1]))])]) + +divert(0)Cantor([4]) diff --git a/Task/Cantor-set/Pluto/cantor-set.pluto b/Task/Cantor-set/Pluto/cantor-set.pluto new file mode 100644 index 0000000000..74d8c97f32 --- /dev/null +++ b/Task/Cantor-set/Pluto/cantor-set.pluto @@ -0,0 +1,17 @@ +local n = 5 +local w = 3 ^ (n - 1) +local len = w +local line = table.create(w) +for i = 1, w do line[i] = "#" end + +while true do + print(line:concat("")) + if len == 1 then break end + len //= 3 + local pos = 1 + while pos < w - len do + pos += len + for i = pos, pos + len - 1 do line[i] = " " end + pos += len + end +end diff --git a/Task/Cantor-set/Scheme/cantor-set.scm b/Task/Cantor-set/Scheme/cantor-set.scm new file mode 100644 index 0000000000..2c05ac6d5d --- /dev/null +++ b/Task/Cantor-set/Scheme/cantor-set.scm @@ -0,0 +1,22 @@ +(import srfi/231) + +(define (kronecker-product A B) + (array-block (array-map (lambda (a) (array-map (lambda (b) (* a b)) B)) A))) + +(define Cantor-base (list*->array 1 '(1))) +(define Cantor-iterate (list*->array 1 '(1 0 1))) + +(define (do-Cantor levels) + (let loop ((l 0) + (C_l Cantor-base)) + (if (<= l levels) + (begin + (array-for-each (lambda (entry) + (display (make-string (expt 3 (- levels l)) + (if (positive? entry) #\* #\ )))) + C_l) + (newline) + (loop (+ l 1) + (kronecker-product Cantor-iterate C_l)))))) + +(do-Cantor 4) diff --git a/Task/Cantor-set/Uiua/cantor-set.uiua b/Task/Cantor-set/Uiua/cantor-set.uiua new file mode 100644 index 0000000000..3d507a4e36 --- /dev/null +++ b/Task/Cantor-set/Uiua/cantor-set.uiua @@ -0,0 +1,4 @@ +[[0 81]] +P ← &p+@\s×3/↥⬚0≡(°⊚↘⊙⇡°⊟) +N ← ♭₂≡(⊟⇌⍜⊟⍉⊸+[⟜¯]÷3⊸/-) +P⍢(⊃P N|>1⊣⊢) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Ada/carmichael-3-strong-pseudoprimes.adb b/Task/Carmichael-3-strong-pseudoprimes/Ada/carmichael-3-strong-pseudoprimes.adb new file mode 100644 index 0000000000..0a15563767 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Ada/carmichael-3-strong-pseudoprimes.adb @@ -0,0 +1,41 @@ +with Ada.Text_IO, Miller_Rabin; + +procedure Nemesis is + + type Number is range 0 .. 2**40-1; -- sufficiently large for the task + + function Is_Prime(N: Number) return Boolean is + package MR is new Miller_Rabin(Number); use MR; + begin + return MR.Is_Prime(N) = Probably_Prime; + end Is_Prime; + +begin + for P1 in Number(2) .. 61 loop + if Is_Prime(P1) then + for H3 in Number(1) .. P1 loop + declare + G: Number := H3 + P1; + P2, P3: Number; + begin + Inner: + for D in 1 .. G-1 loop + if ((H3+P1) * (P1-1)) mod D = 0 and then + (-(P1 * P1)) mod H3 = D mod H3 + then + P2 := 1 + ((P1-1) * G / D); + P3 := 1 +(P1*P2/H3); + if Is_Prime(P2) and then Is_Prime(P3) + and then (P2*P3) mod (P1-1) = 1 + then + Ada.Text_IO.Put_Line + ( Number'Image(P1) & " *" & Number'Image(P2) & " *" & + Number'Image(P3) & " = " & Number'Image(P1*P2*P3) ); + end if; + end if; + end loop Inner; + end; + end loop; + end if; + end loop; +end Nemesis; diff --git a/Task/Carmichael-3-strong-pseudoprimes/JavaScript/carmichael-3-strong-pseudoprimes.js b/Task/Carmichael-3-strong-pseudoprimes/JavaScript/carmichael-3-strong-pseudoprimes.js new file mode 100644 index 0000000000..b5d6635b48 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/JavaScript/carmichael-3-strong-pseudoprimes.js @@ -0,0 +1,43 @@ +"use strict"; + +function mod(n, m) { + return ((n % m) + m) % m; +} + +function isPrime(n) { + if (n === 2 || n === 3) return true; + if (n < 2 || n % 2 === 0 || n % 3 === 0) return false; + for (let div = 5, inc = 2; div * div <= n; div += inc, inc = 6 - inc) { + if (n % div === 0) return false; + } + return true; +} + +// emulate Java's integer division (truncation toward zero) +function idiv(a, b) { + return Math.trunc(a / b); +} + +function main() { + for (let p = 2; p < 62; p++) { + if (!isPrime(p)) continue; + + for (let h3 = 2; h3 < p; h3++) { + const g = h3 + p; + + for (let d = 1; d < g; d++) { + if ((g * (p - 1)) % d !== 0 || mod(-p * p, h3) !== d % h3) continue; + + const q = 1 + idiv((p - 1) * g, d); + if (!isPrime(q)) continue; + + const r = 1 + idiv(p * q, h3); + if (!isPrime(r) || (q * r) % (p - 1) !== 1) continue; + + console.log(`${p} x ${q} x ${r}`); + } + } + } +} + +main(); diff --git a/Task/Carmichael-3-strong-pseudoprimes/Maxima/carmichael-3-strong-pseudoprimes.maxima b/Task/Carmichael-3-strong-pseudoprimes/Maxima/carmichael-3-strong-pseudoprimes.maxima new file mode 100644 index 0000000000..26016b2f23 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Maxima/carmichael-3-strong-pseudoprimes.maxima @@ -0,0 +1,8 @@ +for p1 in primes(2, 61) do( + for h3 from 2 thru p1 do( + for d from 1 thru h3+p1 do( + if mod((h3+p1)*(p1-1), d)=0 and mod(-p1^2, h3)=mod(d, h3) then block( + p2: 1+floor((p1-1)*(h3+p1)/d), + if primep(p2) and p2#p1 then block( + p3: 1+floor(p1*p2/h3), + if primep(p3) and mod(p2*p3, p1-1)=1 then print([p1, p2, p3])))))); diff --git a/Task/Carmichael-3-strong-pseudoprimes/Oberon-07/carmichael-3-strong-pseudoprimes.oberon b/Task/Carmichael-3-strong-pseudoprimes/Oberon-07/carmichael-3-strong-pseudoprimes.oberon new file mode 100644 index 0000000000..369bfbd7bd --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Oberon-07/carmichael-3-strong-pseudoprimes.oberon @@ -0,0 +1,40 @@ +MODULE Carmichael3; (* find some Carmichael 3 strong pseudoprimes *) + IMPORT Primes, Out; + + (* isPrime will be set to a sieve of primes *) + (* to find the pseudoprimes with Prime1 up to 61, we need to consider *) + (* primes up to around 120 000, so the following should be large enough *) + VAR isPrime : ARRAY 200001 OF BOOLEAN; + prime1, prime2, prime3, h3, d : INTEGER; +BEGIN + + (* construct a sieve of primes as required for the task *) + Primes.sieve( isPrime ); + + (* Find the Carmichael 3 Stromg Pseudoprimes for Prime1 up to 61 *) + (* prime1 cannot be 2 as there no integers h3 such that 1 < h3 < 2 *) + FOR prime1 := 3 TO 61 BY 2 DO + IF isPrime[ prime1 ] THEN + FOR h3 := 1 TO prime1 - 1 DO + FOR d := 1 TO ( h3 + prime1 ) - 1 DO + IF ( ( h3 + prime1 ) * ( prime1 - 1 ) MOD d = 0 ) + & ( ( - ( prime1 * prime1 ) ) MOD h3 = d MOD h3 ) + THEN + prime2 := 1 + ( ( prime1 - 1 ) * ( h3 + prime1 ) DIV d ); + IF isPrime[ prime2 ] THEN + prime3 := 1 + ( prime1 * prime2 DIV h3 ); + IF isPrime[ prime3 ] THEN + IF ( prime2 * prime3 ) MOD ( prime1 - 1 ) = 1 THEN + Out.Int( prime1, 0 );Out.String( " " ); + Out.Int( prime2, 0 );Out.String( " " ); + Out.Int( prime3, 0 );Out.Ln + END + END + END + END + END + END + END + END + +END Carmichael3. diff --git a/Task/Carmichael-3-strong-pseudoprimes/Pluto/carmichael-3-strong-pseudoprimes.pluto b/Task/Carmichael-3-strong-pseudoprimes/Pluto/carmichael-3-strong-pseudoprimes.pluto new file mode 100644 index 0000000000..586b258950 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Pluto/carmichael-3-strong-pseudoprimes.pluto @@ -0,0 +1,30 @@ +local fmt = require "fmt" +local int = require "int" + +local mod = |n, m| -> ((n % m) + m) % m + +local function carmichael(p1) + for h3 = 2, p1 - 1 do + for d = 1, h3 + p1 - 1 do + if (h3 + p1) * (p1 - 1) % d == 0 and mod(-p1 * p1, h3) == d % h3 then + local p2 = 1 + (p1 - 1) * (h3 + p1) // d + if int.isprime(p2) then + local p3 = 1 + p1 * p2 // h3 + if int.isprime(p3) then + if p2 * p3 % (p1 - 1) == 1 then + local c = p1 * p2 * p3 + fmt.print("%2d %4d %5d %10d", p1, p2, p3, c) + end + end + end + end + end + end +end + +print("The following are Carmichael munbers for p1 <= 61:\n") +print("p1 p2 p3 product") +print("== == == =======") +for p1 = 2, 61 do + if int.isprime(p1) then carmichael(p1) end +end diff --git a/Task/Cartesian-product-of-two-or-more-lists/Ada/cartesian-product-of-two-or-more-lists.adb b/Task/Cartesian-product-of-two-or-more-lists/Ada/cartesian-product-of-two-or-more-lists.adb new file mode 100644 index 0000000000..c825808b83 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Ada/cartesian-product-of-two-or-more-lists.adb @@ -0,0 +1,104 @@ +with Ada.Text_IO; use Ada.Text_Io; +with Ada.Containers.Doubly_Linked_Lists; +with Ada.Strings.Fixed; + +procedure Cartesian is + + type Element_Type is new Long_Integer; + + package Lists is + new Ada.Containers.Doubly_Linked_Lists (Element_Type); + package List_Lists is + new Ada.Containers.Doubly_Linked_Lists (Lists.List, Lists."="); + + subtype List is Lists.List; + subtype List_List is List_Lists.List; + + function "*" (Left, Right : List) return List_List is + Result : List_List; + Sub : List; + begin + for Outer of Left loop + for Inner of Right loop + Sub.Clear; + Sub.Append (Outer); + Sub.Append (Inner); + Result.Append (Sub); + end loop; + end loop; + return Result; + end "*"; + + function "*" (Left : List_List; + Right : List) return List_List + is + Result : List_List; + Sub : List; + begin + for Outer of Left loop + for Inner of Right loop + Sub := Outer; + Sub.Append (Inner); + Result.Append (Sub); + end loop; + end loop; + return Result; + end "*"; + + procedure Put (L : List) is + use Ada.Strings; + First : Boolean := True; + begin + Put ("("); + for E of L loop + if not First then + Put (","); + end if; + Put (Fixed.Trim (E'Image, Left)); + First := False; + end loop; + Put (")"); + end Put; + + procedure Put (LL : List_List) is + First : Boolean := True; + begin + Put ("{"); + for E of LL loop + if not First then + Put (","); + end if; + Put (E); + First := False; + end loop; + Put ("}"); + end Put; + + function "&" (Left : List; Right : Element_Type) return List is + Result : List := Left; + begin + Result.Append (Right); + return Result; + end "&"; + + Nil : List renames Lists.Empty_List; + List_1_2 : constant List := Nil & 1 & 2; + List_3_4 : constant List := Nil & 3 & 4; + List_Empty : constant List := Nil; + List_1_2_3 : constant List := Nil & 1 & 2 & 3; +begin + Put (List_1_2 * List_3_4); New_Line; + + Put (List_3_4 * List_1_2); New_Line; + + Put (List_Empty * List_1_2); New_Line; + + Put (List_1_2 * List_Empty); New_Line; + + Put (List'(Nil & 1776 & 1789) * List'(Nil & 7 & 12) * + List'(Nil & 4 & 14 & 23) * List'(Nil & 0 & 1)); New_Line; + + Put (List_1_2_3 * List'(Nil & 30) * List'(Nil & 500 & 100)); New_Line; + + Put (List_1_2_3 * List_Empty * List'(Nil & 500 & 100)); New_Line; +end Cartesian; diff --git a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur index 651b2109a5..5465330760 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur +++ b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur @@ -1,4 +1,4 @@ -val X = fn x...:x +val X = fn(x...) { x } writeln mapX([1, 2], [3, 4], by=X) == [[1, 3], [1, 4], [2, 3], [2, 4]] writeln mapX([3, 4], [1, 2], by=X) == [[3, 1], [3, 2], [4, 1], [4, 2]] diff --git a/Task/Case-sensitivity-of-identifiers/ALGOL-M/case-sensitivity-of-identifiers.alg b/Task/Case-sensitivity-of-identifiers/ALGOL-M/case-sensitivity-of-identifiers.alg new file mode 100644 index 0000000000..5e25c79838 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/ALGOL-M/case-sensitivity-of-identifiers.alg @@ -0,0 +1,13 @@ +begin + +string dog; +comment + An attempt to declare Dog or DOG after declaring + dog will result in a compile-time error ("Doubly + Declared identifier"); +dog := "Benjamin"; +Dog := "Samba"; +DOG := "Bernie"; +write("There is just one dog named ", dog); + +end diff --git a/Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.adb b/Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.adb new file mode 100644 index 0000000000..76dfe613ba --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Ada/case-sensitivity-of-identifiers.adb @@ -0,0 +1,6 @@ +with Ada.Text_IO; +procedure Dogs is + Dog : String := "Bernie"; +begin + Ada.Text_IO.Put_Line ("There is just one dog named " & DOG); +end Dogs; diff --git a/Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cob b/Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cob new file mode 100644 index 0000000000..fa4d953536 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/COBOL/case-sensitivity-of-identifiers.cob @@ -0,0 +1,21 @@ +* Case sensitivity of identifiers + *>* Commented-out lines in the working storage + *>* are considered as invalid redefinitions + *>* of ''dog'' that can only be ambiguously + *>* referenced in the procedure body. + + IDENTIFICATION DIVISION. + PROGRAM-ID. case-sensitivity. + DATA DIVISION. + WORKING-STORAGE SECTION. + *>* 01 dog PICTURE X(8) VALUE IS "Benjamin". + *>* 01 Dog PICTURE X(5) VALUE IS "Samba". + 01 DOG PICTURE X(6) VALUE IS "Bernie". + PROCEDURE DIVISION. + DISPLAY + *>* "The three dogs are named " + *>* dog ", " Dog " and " DOG "." + "There is just one dog named " DOG "." + END-DISPLAY + STOP RUN. + END PROGRAM case-sensitivity. diff --git a/Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.eu b/Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.eu new file mode 100644 index 0000000000..7bbee06105 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Euphoria/case-sensitivity-of-identifiers.eu @@ -0,0 +1,5 @@ +-- These variables are all different +sequence dog = "Benjamin" +sequence Dog = "Samba" +sequence DOG = "Bernie" +printf( 1, "The three dogs are named %s, %s and %s\n", {dog, Dog, DOG} ) diff --git a/Task/Case-sensitivity-of-identifiers/LOLCODE/case-sensitivity-of-identifiers.lol b/Task/Case-sensitivity-of-identifiers/LOLCODE/case-sensitivity-of-identifiers.lol new file mode 100644 index 0000000000..bbf2bc3047 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/LOLCODE/case-sensitivity-of-identifiers.lol @@ -0,0 +1,12 @@ +HAI 1.3 + +I HAS A dog ITZ "Benjamin" +I HAS A Dog ITZ "Samba" +I HAS A DOG ITZ "Bernie" + +EITHER OF DIFFRINT dog AN Dog AN DIFFRINT Dog AN DOG, O RLY? + YA RLY, VISIBLE "TEH 3 DOGZ R NAEMD :{dog}, :{Dog}, AN :{DOG}." + NO WAI, VISIBLE "THERE IZ JUST 1 DOG NAEMD :{DOG}." +OIC + +KTHXBYE diff --git a/Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.ps1 b/Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.ps1 new file mode 100644 index 0000000000..1edfb33162 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/PowerShell/case-sensitivity-of-identifiers.ps1 @@ -0,0 +1,5 @@ +$dog = "Benjamin" +$Dog = "Samba" +$DOG = "Bernie" + +"There is just one dog named {0}." -f $dOg diff --git a/Task/Case-sensitivity-of-identifiers/Red/case-sensitivity-of-identifiers.red b/Task/Case-sensitivity-of-identifiers/Red/case-sensitivity-of-identifiers.red new file mode 100644 index 0000000000..5d1432eea1 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Red/case-sensitivity-of-identifiers.red @@ -0,0 +1,8 @@ +dog: "Benjamin" +Dog: "Samba" +DOG: "Bernie" + +print [ "The three dogs are " dog "," Dog "," DOG ] + +;- as Red is not case sensitive, will ouput +;- The three dogs are Bernie , Bernie , Bernie diff --git a/Task/Case-sensitivity-of-identifiers/Refal/case-sensitivity-of-identifiers.refal b/Task/Case-sensitivity-of-identifiers/Refal/case-sensitivity-of-identifiers.refal new file mode 100644 index 0000000000..11adce0813 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Refal/case-sensitivity-of-identifiers.refal @@ -0,0 +1,6 @@ +$ENTRY Go { + , 'Benjamin': e.dog + , 'Samba': e.Dog + , 'Bernie': e.DOG + = ; +}; diff --git a/Task/Case-sensitivity-of-identifiers/S-BASIC/case-sensitivity-of-identifiers.basic b/Task/Case-sensitivity-of-identifiers/S-BASIC/case-sensitivity-of-identifiers.basic new file mode 100644 index 0000000000..de5524ecca --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/S-BASIC/case-sensitivity-of-identifiers.basic @@ -0,0 +1,13 @@ +var dog = string +comment + An attempt to declare Dog or DOG after declaring dog + will result in a compile-time error ("One of these VAR + names in use") +end + +dog = "Benjamin" +Dog = "Samba" +DOG = "Bernie" +print "There is just one dog named "; dog + +end diff --git a/Task/Casting-out-nines/Fortran/casting-out-nines.f b/Task/Casting-out-nines/Fortran/casting-out-nines.f new file mode 100644 index 0000000000..a2e0705db8 --- /dev/null +++ b/Task/Casting-out-nines/Fortran/casting-out-nines.f @@ -0,0 +1,220 @@ +program main + implicit none + + type :: test_case + integer :: base + character(len=10) :: begin, end_ + character(len=10), dimension(5) :: kaprekar + integer :: nkap + end type test_case + + type(test_case), dimension(2) :: testcases + type(test_case) :: tc + integer :: it, i, j + character(len=20), allocatable :: s(:) + logical :: found + + ! Initialize test cases + testcases(1)%base = 10 + testcases(1)%begin = '1' + testcases(1)%end_ = '100' + testcases(1)%kaprekar(1:5) = (/'1 ', '9 ', '45 ', '55 ', '99 '/) + testcases(1)%nkap = 5 + + testcases(2)%base = 17 + testcases(2)%begin = '10' + testcases(2)%end_ = 'gg' + testcases(2)%kaprekar(1:3) = (/'3d', 'd4', 'gg'/) + testcases(2)%nkap = 3 + + do it = 1, 2 + tc = testcases(it) + write(*, *) '' + write(*, '(A, I0, A, A, A, A)') 'Test case base = ', tc%base, ', begin = ', trim(tc%begin), ', end = ', trim(tc%end_) + call subset(tc%base, tc%begin, tc%end_, s) + write(*, '(A)', advance='no') 'Subset: ' + do i = 1, size(s) + write(*, '(A, A)', advance='no') trim(s(i)), ' ' + end do + write(*, *) + write(*, '(A)', advance='no') 'Kaprekar: ' + do i = 1, tc%nkap + write(*, '(A, A)', advance='no') trim(tc%kaprekar(i)), ' ' + end do + write(*, *) + + ! Check if all Kaprekar are in subset + j = 1 + do i = 1, tc%nkap + found = .false. + do while (j <= size(s)) + if (trim(s(j)) == trim(tc%kaprekar(i))) then + found = .true. + j = j + 1 + exit + end if + j = j + 1 + end do + if (.not. found) then + write(*, '(A, A, A)') 'Fail: ', trim(tc%kaprekar(i)), ' not in subset' + stop + end if + end do + write(*, *) 'Valid subset.' + if (allocated(s)) deallocate(s) + end do + +contains + + subroutine subset(base, begin, end_, s) + integer, intent(in) :: base + character(len=*), intent(in) :: begin, end_ + character(len=20), allocatable, intent(out) :: s(:) + integer(8) :: begin64, end64, k, kk + character(len=20) :: ks, kks + character(1) :: rk, rk2 + + begin64 = str_to_int(base, begin) + end64 = str_to_int(base, end_) + + allocate(s(0)) ! Start empty + + do k = begin64, end64 + ks = int_to_str(base, k) + rk = check_digit(base, ks) + kk = k * k + kks = int_to_str(base, kk) + rk2 = check_digit(base, kks) + if (rk == rk2) then + call append_str(s, ks) + end if + end do + end subroutine subset + + subroutine append_str(list, val) + character(len=20), allocatable, intent(inout) :: list(:) + character(len=*), intent(in) :: val + character(len=20), allocatable :: tmp(:) + + if (allocated(list)) then + allocate(tmp(size(list))) + tmp = list + deallocate(list) + allocate(list(size(tmp) + 1)) + list(1:size(tmp)) = tmp + list(size(tmp) + 1) = val + else + allocate(list(1)) + list(1) = val + end if + end subroutine append_str + + recursive function check_digit(base, n) result(r) + integer, intent(in) :: base + character(len=*), intent(in) :: n + character(1) :: r + character(1) :: d, b9 + character(len=20) :: s, s9 + integer :: i, v9 + + v9 = base - 1 + s9 = int_to_str(base, int(v9, 8)) + b9 = s9(1:1) ! Single digit + + r = '0' + do i = 1, len_trim(n) + d = n(i:i) + if (d == b9) cycle + if (r == '0') then + r = d + cycle + end if + s = add_digits(base, r, d) + if (trim(s) == trim(s9)) then + r = '0' + cycle + end if + if (len_trim(s) == 1) then + r = s(1:1) + cycle + end if + ! Recurse on two-digit sum + r = check_digit(base, trim(s)) + end do + end function check_digit + + function add_digits(base, a, b) result(res) + integer, intent(in) :: base + character(1), intent(in) :: a, b + character(len=20) :: res + integer :: ai, bi + + ai = digit_value(a, base) + bi = digit_value(b, base) + res = int_to_str(base, int(ai + bi, 8)) + end function add_digits + + function digit_value(c, base) result(v) + character(1), intent(in) :: c + integer, intent(in) :: base + integer :: v + + if (c >= '0' .and. c <= '9') then + v = iachar(c) - iachar('0') + else if (c >= 'a' .and. c <= 'z') then + v = 10 + iachar(c) - iachar('a') + else + stop 'invalid digit' + end if + if (v < 0 .or. v >= base) stop 'invalid digit for base' + end function digit_value + + function value_to_digit(v) result(c) + integer, intent(in) :: v + character(1) :: c + + if (v < 10) then + c = achar(iachar('0') + v) + else + c = achar(iachar('a') + v - 10) + end if + end function value_to_digit + + function int_to_str(base, k) result(s) + integer, intent(in) :: base + integer(8), intent(in) :: k + character(len=20) :: s + integer(8) :: kk + integer :: digit + + kk = k + if (kk < 0) kk = -kk ! But not handling negatives in this context + s = '' + if (kk == 0) then + s = '0' + return + end if + do while (kk > 0) + digit = mod(kk, int(base, 8)) + s = value_to_digit(digit) // s + kk = kk / int(base, 8) + end do + end function int_to_str + + function str_to_int(base, s) result(val) + integer, intent(in) :: base + character(len=*), intent(in) :: s + integer(8) :: val + integer :: i, lens, v + character(len=20) :: ss + + ss = adjustl(s) + lens = len_trim(ss) + val = 0 + do i = 1, lens + v = digit_value(ss(i:i), base) + val = val * int(base, 8) + int(v, 8) + end do + end function str_to_int + +end program main diff --git a/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 b/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 index a0cc83dae1..633d55d35e 100644 --- a/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 +++ b/Task/Catalan-numbers-Pascals-triangle/360-Assembly/catalan-numbers-pascals-triangle.360 @@ -68,7 +68,7 @@ ENLOOP2J EQU * MVC C,Z OI C+L'C-1,X'F0' MVC WTOBUF(8),C+8 - WTO MF=(E,WTOMSG) + WTO MF=(E,WTOMSG) B LOOPI ENDLOOPI EQU * * ---- END CODE diff --git a/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.adb b/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.adb new file mode 100644 index 0000000000..477d3b78a9 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Ada/catalan-numbers-pascals-triangle.adb @@ -0,0 +1,14 @@ +with Ada.Text_IO, Pascal; + +procedure Catalan is + + Last: Positive := 15; + Row: Pascal.Row := Pascal.First_Row(2*Last+1); + +begin + for I in 1 .. Last loop + Row := Pascal.Next_Row(Row); + Row := Pascal.Next_Row(Row); + Ada.Text_IO.Put(Integer'Image(Row(I+1)-Row(I+2))); + end loop; +end Catalan; diff --git a/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk b/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk index 4921c4ed98..67ce3c01c6 100644 --- a/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk +++ b/Task/Catalan-numbers-Pascals-triangle/AutoHotkey/catalan-numbers-pascals-triangle.ahk @@ -6,25 +6,25 @@ Array := [], Array[2,1] := Array[2,2] := 1 ; Array inititated and 2nd row of pas INI := 3 ; starts with calculating the 3rd row and as such the value Loop, 31 ; every odd row is taken for calculating catalan number as such to obtain 15 we need 2n+1 { - if ( A_index > 2 ) - { - Loop, % A_INDEX - { - old := ini-1, index := A_index, index_1 := A_index + 1 - Array[ini, index_1] := Array[old, index] + Array[old, index_1] - Array[ini, 1] := Array[ini, ini] := 1 - line .= Array[ini, A_index] " " - } - ;~ MsgBox % line ; gives rows of pascal's triangle - ; calculating every odd row starting from 1st so as to obtain catalan's numbers - if ( mod(ini,2) != 0) - { - StringSplit, res, line, %A_Space% - ans := res0//2, ans_1 := ans++ - result := result . res%ans_1% - res%ans% " " - } - line := - ini++ - } + if ( A_index > 2 ) + { + Loop, % A_INDEX + { + old := ini-1, index := A_index, index_1 := A_index + 1 + Array[ini, index_1] := Array[old, index] + Array[old, index_1] + Array[ini, 1] := Array[ini, ini] := 1 + line .= Array[ini, A_index] " " + } + ;~ MsgBox % line ; gives rows of pascal's triangle + ; calculating every odd row starting from 1st so as to obtain catalan's numbers + if ( mod(ini,2) != 0) + { + StringSplit, res, line, %A_Space% + ans := res0//2, ans_1 := ans++ + result := result . res%ans_1% - res%ans% " " + } + line := + ini++ + } } MsgBox % result diff --git a/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat b/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat index 707de0dc95..9c096844a1 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat +++ b/Task/Catalan-numbers-Pascals-triangle/Batch-File/catalan-numbers-pascals-triangle.bat @@ -8,15 +8,15 @@ for /L %%i in (1,1,%n%) do ( set /A ip=%%i+1 for /L %%j in (%%i,-1,1) do ( set /A jm=%%j-1 - set /A t.%%j=t.%%j+t.!jm! - ) - set /A t.!ip!=t.%%i + set /A t.%%j=t.%%j+t.!jm! + ) + set /A t.!ip!=t.%%i for /L %%j in (!ip!,-1,1) do ( set /A jm=%%j-1 - set /A t.%%j=t.%%j+t.!jm! - ) + set /A t.%%j=t.%%j+t.!jm! + ) set /A ci=t.!ip!-t.%%i - echo !ci! + echo !ci! ) ) pause diff --git a/Task/Catalan-numbers-Pascals-triangle/EchoLisp/catalan-numbers-pascals-triangle-1.l b/Task/Catalan-numbers-Pascals-triangle/EchoLisp/catalan-numbers-pascals-triangle-1.l index ae9d26b5a5..0f482f344c 100644 --- a/Task/Catalan-numbers-Pascals-triangle/EchoLisp/catalan-numbers-pascals-triangle-1.l +++ b/Task/Catalan-numbers-Pascals-triangle/EchoLisp/catalan-numbers-pascals-triangle-1.l @@ -5,11 +5,11 @@ ;; T (i , j) = T(i-1,j) + T (i, j-1) (define (T n) - (define i (modulo n dim)) - (define j (quotient n dim)) - (cond - ((zero? i) 1) ;; left column = 1 - ((= i j) (T (Tidx (1- i) j))) ;; diagonal value = left value - (else (+ (T (Tidx (1- i) j)) (T (Tidx i (1- j))))))) - + (define i (modulo n dim)) + (define j (quotient n dim)) + (cond + ((zero? i) 1) ;; left column = 1 + ((= i j) (T (Tidx (1- i) j))) ;; diagonal value = left value + (else (+ (T (Tidx (1- i) j)) (T (Tidx i (1- j))))))) + (remember 'T #(1)) diff --git a/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl b/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl index 6d2e956134..9845f5822d 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl +++ b/Task/Catalan-numbers-Pascals-triangle/Erlang/catalan-numbers-pascals-triangle.erl @@ -1,17 +1,17 @@ -module(catalin). -compile(export_all). mul(N,D,S,S)-> - N2=N*(S+S), - D2=D*S, - K = N2 div D2 ; + N2=N*(S+S), + D2=D*S, + K = N2 div D2 ; mul(N,D,S,L)-> - N2=N*(S+L), - D2=D*L, - K = mul(N2,D2,S,L+1). - + N2=N*(S+L), + D2=D*L, + K = mul(N2,D2,S,L+1). + catl(Ans,16) -> Ans; catl(D,S)-> - C=mul(1,1,S,2), - catl([D|C],S+1). + C=mul(1,1,S,2), + catl([D|C],S+1). main()-> - Ans=catl(1,2). + Ans=catl(1,2). diff --git a/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f b/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f index e334dbf7af..aeb18b829c 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f +++ b/Task/Catalan-numbers-Pascals-triangle/Fortran/catalan-numbers-pascals-triangle.f @@ -11,10 +11,10 @@ program calc_catalan implicit none - integer, parameter :: nMax=15 ! Number of catalan numbers to print - integer :: catalan ! result of calculation - integer :: i, j ! Loop indices - integer :: t(nMax+3) ! 1 line of pascal's triangle + integer, parameter :: nMax=15 ! Number of catalan numbers to print + integer :: catalan ! result of calculation + integer :: i, j ! Loop indices + integer :: t(nMax+3) ! 1 line of pascal's triangle ! straight copy of the algorithm presented in the C++ solution ! @@ -57,7 +57,7 @@ ! (remember i is 5 to calculate C4.) catalan = t(i+1) - t(i) - write (*, '(I0,x) ', ADVANCE='NO') catalan ! all in 1 line + write (*, '(I0,x) ', ADVANCE='NO') catalan ! all in 1 line end do write (*,*) ' ' ! Terminate output line diff --git a/Task/Catalan-numbers-Pascals-triangle/Pluto/catalan-numbers-pascals-triangle.pluto b/Task/Catalan-numbers-Pascals-triangle/Pluto/catalan-numbers-pascals-triangle.pluto new file mode 100644 index 0000000000..b84dda2410 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Pluto/catalan-numbers-pascals-triangle.pluto @@ -0,0 +1,12 @@ +require "table2" + +local n = 15 +local t = table.rep(n + 2, 0) +t[2] = 1 +for i = 1, n do + for j = i, 2, -1 do t[j + 1] += t[j] end + t[i + 2] = t[i + 1] + for j = i + 1, 2, -1 do t[j + 1] += t[j] end + io.write($"{t[i + 2] - t[i + 1]} ") +end +print() diff --git a/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py b/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py index 8d350427f3..82b845fce6 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py +++ b/Task/Catalan-numbers-Pascals-triangle/Python/catalan-numbers-pascals-triangle-1.py @@ -2,11 +2,11 @@ >>> t = [0] * (n + 2) >>> t[1] = 1 >>> for i in range(1, n + 1): - for j in range(i, 1, -1): t[j] += t[j - 1] - t[i + 1] = t[i] - for j in range(i + 1, 1, -1): t[j] += t[j - 1] - print(t[i+1] - t[i], end=' ') + for j in range(i, 1, -1): t[j] += t[j - 1] + t[i + 1] = t[i] + for j in range(i + 1, 1, -1): t[j] += t[j - 1] + print(t[i+1] - t[i], end=' ') + - 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845 >>> diff --git a/Task/Catalan-numbers-Pascals-triangle/R/catalan-numbers-pascals-triangle.r b/Task/Catalan-numbers-Pascals-triangle/R/catalan-numbers-pascals-triangle.r new file mode 100644 index 0000000000..a6979fd807 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/R/catalan-numbers-pascals-triangle.r @@ -0,0 +1,8 @@ +pascal_row <- function(n) choose(n, 0:n) + +catalan <- function(n){ + pr <- pascal_row(2*n) + pr[n+1]-pr[n+2] +} + +cat(sapply(1:15, catalan), "\n") diff --git a/Task/Catalan-numbers-Pascals-triangle/Rebol/catalan-numbers-pascals-triangle.rebol b/Task/Catalan-numbers-Pascals-triangle/Rebol/catalan-numbers-pascals-triangle.rebol new file mode 100644 index 0000000000..75ceb9f107 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Rebol/catalan-numbers-pascals-triangle.rebol @@ -0,0 +1,23 @@ +Rebol [ + title: "Rosetta code: Catalan numbers/Pascal's triangle" + file: %Catalan_numbers-Pascal's_triangle.r3 + url: https://rosettacode.org/wiki/Catalan_numbers/Pascal's_triangle +] + +catalan-number: function [ + "Compute the nth Catalan number using the product formula:" + "C(n) = product((n+k)/k) for k in 2..n" + n [integer!] +][ + nm: dm: 1.0 ;; accumulate numerator and denominator as decimals to avoid integer overflow + repeat k n [ + if k >= 2 [ ;; product starts at k=2; k=1 contributes (n+1)/1 which is handled by nm/dm=1 + nm: nm * (n + k) ;; multiply numerator by (n+k) + dm: dm * k ;; multiply denominator by k + ] + ] + to integer! nm / dm ;; divide and convert back to integer (result is always whole) +] + +;; Build a block of the first 15 Catalan numbers using collect/keep +probe result: collect [ repeat n 15 [keep catalan-number n] ] diff --git a/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rs b/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rs index 39701bbfcb..5e35484e10 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rs +++ b/Task/Catalan-numbers-Pascals-triangle/Rust/catalan-numbers-pascals-triangle.rs @@ -5,23 +5,23 @@ fn main() let mut j:usize; for i in 1..n+1 { - j=i; - loop{ - if j==1{ - break; - } - t[j]=t[j] + t[j-1]; - j=j-1; - } - t[i+1]= t[i]; - j=i+1; - loop{ - if j==1{ - break; - } - t[j]=t[j] + t[j-1]; - j=j-1; - } - print!("{} ", t[i+1]-t[i]); + j=i; + loop{ + if j==1{ + break; + } + t[j]=t[j] + t[j-1]; + j=j-1; + } + t[i+1]= t[i]; + j=i+1; + loop{ + if j==1{ + break; + } + t[j]=t[j] + t[j-1]; + j=j-1; + } + print!("{} ", t[i+1]-t[i]); } } diff --git a/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl b/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl index 4af0c8f296..60110346a7 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl +++ b/Task/Catalan-numbers-Pascals-triangle/Tcl/catalan-numbers-pascals-triangle.tcl @@ -2,10 +2,10 @@ proc catalan n { set result {} array set t {0 0 1 1} for {set i 1} {[set k $i] <= $n} {incr i} { - for {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])} - set t([incr k]) $t($i) - for {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])} - lappend result [expr {$t($k) - $t($i)}] + for {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])} + set t([incr k]) $t($i) + for {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])} + lappend result [expr {$t($k) - $t($i)}] } return $result } diff --git a/Task/Catalan-numbers-Pascals-triangle/Uiua/catalan-numbers-pascals-triangle.uiua b/Task/Catalan-numbers-Pascals-triangle/Uiua/catalan-numbers-pascals-triangle.uiua new file mode 100644 index 0000000000..251f91fcda --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Uiua/catalan-numbers-pascals-triangle.uiua @@ -0,0 +1,3 @@ +Pascal ← ⍥(⊙□+⊸⊃˜⊂⊂ 0)⊙[1] +Cats ← ≡◇(˜-⊢₂↘⌊÷2⊸⧻)↘1▽◿2⊸≡◇⧻≡Pascal +1×2 +Cats 15 diff --git a/Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vbs b/Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vbs new file mode 100644 index 0000000000..9483b61427 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/VBScript/catalan-numbers-pascals-triangle.vbs @@ -0,0 +1,20 @@ +dim t() +if Wscript.arguments.count=1 then + n=Wscript.arguments.item(0) +else + n=15 +end if +redim t(n+1) +'t(*)=0 +t(1)=1 +for i=1 to n + ip=i+1 + for j = i to 1 step -1 + t(j)=t(j)+t(j-1) + next 'j + t(i+1)=t(i) + for j = i+1 to 1 step -1 + t(j)=t(j)+t(j-1) + next 'j + Wscript.echo t(i+1)-t(i) +next 'i diff --git a/Task/Catalan-numbers-Pascals-triangle/XBasic/catalan-numbers-pascals-triangle.basic b/Task/Catalan-numbers-Pascals-triangle/XBasic/catalan-numbers-pascals-triangle.basic index 9fe718d291..ee926c1457 100644 --- a/Task/Catalan-numbers-Pascals-triangle/XBasic/catalan-numbers-pascals-triangle.basic +++ b/Task/Catalan-numbers-Pascals-triangle/XBasic/catalan-numbers-pascals-triangle.basic @@ -1,5 +1,5 @@ -PROGRAM "Pascal's triangle" -VERSION "0.0000" +PROGRAM "Pascal's triangle" +VERSION "0.0000" DECLARE FUNCTION Entry () diff --git a/Task/Catalan-numbers/ALGOL-68/catalan-numbers-1.alg b/Task/Catalan-numbers/ALGOL-68/catalan-numbers-1.alg new file mode 100644 index 0000000000..0f514656ce --- /dev/null +++ b/Task/Catalan-numbers/ALGOL-68/catalan-numbers-1.alg @@ -0,0 +1,11 @@ +BEGIN # print some catalan numbers # + PROC print catalan = ( LONG INT n, cn )VOID: + print( ( whole( n, -3 ), ": ", whole( cn, 0 ), newline ) ); + + LONG INT cprev := 1; # C0 # + print catalan( 0, cprev ); + FOR n TO 15 DO + cprev := ROUND ( ( ( ( 4 * n ) - 2 ) / ( n + 1 ) ) * cprev ); + print catalan( n, cprev ) + OD +END diff --git a/Task/Catalan-numbers/ALGOL-68/catalan-numbers-2.alg b/Task/Catalan-numbers/ALGOL-68/catalan-numbers-2.alg new file mode 100644 index 0000000000..862e99ef68 --- /dev/null +++ b/Task/Catalan-numbers/ALGOL-68/catalan-numbers-2.alg @@ -0,0 +1,32 @@ +# calculate the first few catalan numbers, using LONG INT values # +# (64-bit quantities in Algol 68G which can handle up to C23) # + +# returns n!/k! # +PROC factorial over factorial = ( INT n, k )LONG INT: + IF k > n THEN 0 + ELIF k = n THEN 1 + ELSE # k < n # + LONG INT f := 1; + FOR i FROM k + 1 TO n DO f *:= i OD; + f + FI # factorial over factorial # ; + +# returns n! # +PROC factorial = ( INT n )LONG INT: + BEGIN + LONG INT f := 1; + FOR i FROM 2 TO n DO f *:= i OD; + f + END # factorial # ; + +# returnss the nth Catalan number using binomial coefficeients # +# uses the factorial over factorial procedure for a slight optimisation # +# note: Cn = 1/(n+1)(2n n) # +# = (2n)!/((n+1)!n!) # +# = factorial over factorial( 2n, n+1 )/n! # +PROC catalan = ( INT n )LONG INT: IF n < 2 THEN 1 ELSE factorial over factorial( n + n, n + 1 ) OVER factorial( n ) FI; + +# show the first few catalan numbers # +FOR i FROM 0 TO 15 DO + print( ( whole( i, -2 ), ": ", whole( catalan( i ), 0 ), newline ) ) +OD diff --git a/Task/Catalan-numbers/ANSI-BASIC/catalan-numbers.basic b/Task/Catalan-numbers/ANSI-BASIC/catalan-numbers.basic new file mode 100644 index 0000000000..7795f726b9 --- /dev/null +++ b/Task/Catalan-numbers/ANSI-BASIC/catalan-numbers.basic @@ -0,0 +1,17 @@ +100 REM Catalan numbers +110 LET MaxN = 14 +120 LET N = 0 +130 LET C = 1 +140 PRINT USING "C(##) = ########": N, C +150 DO WHILE N < MaxN +160 LET N = N + 1 +170 LET I = 0 +180 DO WHILE C > 0 +190 LET C = C - (N + 1) +200 LET I = I + 1 +210 LOOP +220 LET C = INT(2 * (2 * N - 1) * C / (N + 1)) +230 LET C = C + 2 * I * (2 * N - 1) +240 PRINT USING "C(##) = ########": N, C +250 LOOP +260 END diff --git a/Task/Catalan-numbers/Ada/catalan-numbers.adb b/Task/Catalan-numbers/Ada/catalan-numbers.adb new file mode 100644 index 0000000000..aa503151a3 --- /dev/null +++ b/Task/Catalan-numbers/Ada/catalan-numbers.adb @@ -0,0 +1,16 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Catalan is + function Catalan (N : Natural) return Natural is + Result : Positive := 1; + begin + for I in 1..N loop + Result := Result * 2 * (2 * I - 1) / (I + 1); + end loop; + return Result; + end Catalan; +begin + for N in 0..15 loop + Put_Line (Integer'Image (N) & " =" & Integer'Image (Catalan (N))); + end loop; +end Test_Catalan; diff --git a/Task/Catalan-numbers/Agena/catalan-numbers.agena b/Task/Catalan-numbers/Agena/catalan-numbers.agena new file mode 100644 index 0000000000..b0dc609b94 --- /dev/null +++ b/Task/Catalan-numbers/Agena/catalan-numbers.agena @@ -0,0 +1,11 @@ +scope # print some catalan numbers + local proc printCatalan( n :: number, cn :: number ) + printf( "%3d: %d\n", n, cn ) + end + local Cprev := 1; # C0 + printCatalan( 0, Cprev ) + for n to 15 do + Cprev := round( ( ( ( 4 * n ) - 2 ) / ( n + 1 ) ) * Cprev ); + printCatalan( n, Cprev ) + od +epocs diff --git a/Task/Catalan-numbers/AppleScript/catalan-numbers.applescript b/Task/Catalan-numbers/AppleScript/catalan-numbers.applescript new file mode 100644 index 0000000000..2f36873065 --- /dev/null +++ b/Task/Catalan-numbers/AppleScript/catalan-numbers.applescript @@ -0,0 +1,5 @@ +set catalan to 1 +repeat with n from 1 to 15 + log catalan as integer + set catalan to 2 * (2 * n - 1) * catalan / (n + 1) +end repeat diff --git a/Task/Catalan-numbers/Arturo/catalan-numbers.arturo b/Task/Catalan-numbers/Arturo/catalan-numbers.arturo index 35bfbc1d94..87be141424 100644 --- a/Task/Catalan-numbers/Arturo/catalan-numbers.arturo +++ b/Task/Catalan-numbers/Arturo/catalan-numbers.arturo @@ -1,11 +1,11 @@ catalan: function [n][ - switch n=0 -> 1 - -> div (catalan n-1) * (4*n)-2 n+1 + switch n=0 -> 1 + -> div (catalan n-1) * (4*n)-2 n+1 ] loop 0..15 [i][ - print [ - pad.right to :string i 5 - pad.left to :string catalan i 20 - ] + print [ + pad.right to :string i 5 + pad.left to :string catalan i 20 + ] ] diff --git a/Task/Catalan-numbers/BASIC/catalan-numbers.basic b/Task/Catalan-numbers/BASIC/catalan-numbers.basic index d374bf70f8..a8233d6b76 100644 --- a/Task/Catalan-numbers/BASIC/catalan-numbers.basic +++ b/Task/Catalan-numbers/BASIC/catalan-numbers.basic @@ -10,9 +10,9 @@ FUNCTION catalan (n as INTEGER) AS SINGLE IF UBOUND(results) < n THEN REDIM PRESERVE results(n) IF 0 = n THEN - results(0) = 1 + results(0) = 1 ELSE - results(n) = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1) + results(n) = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1) END IF catalan = results(n) END FUNCTION diff --git a/Task/Catalan-numbers/C/catalan-numbers.c b/Task/Catalan-numbers/C/catalan-numbers.c index e53382ede7..573af42042 100644 --- a/Task/Catalan-numbers/C/catalan-numbers.c +++ b/Task/Catalan-numbers/C/catalan-numbers.c @@ -4,43 +4,43 @@ typedef unsigned long long ull; ull binomial(ull m, ull n) { - ull r = 1, d = m - n; - if (d > n) { n = d; d = m - n; } + ull r = 1, d = m - n; + if (d > n) { n = d; d = m - n; } - while (m > n) { - r *= m--; - while (d > 1 && ! (r%d) ) r /= d--; - } + while (m > n) { + r *= m--; + while (d > 1 && ! (r%d) ) r /= d--; + } - return r; + return r; } ull catalan1(int n) { - return binomial(2 * n, n) / (1 + n); + return binomial(2 * n, n) / (1 + n); } ull catalan2(int n) { - int i; - ull r = !n; + int i; + ull r = !n; - for (i = 0; i < n; i++) - r += catalan2(i) * catalan2(n - 1 - i); - return r; + for (i = 0; i < n; i++) + r += catalan2(i) * catalan2(n - 1 - i); + return r; } ull catalan3(int n) { - return n ? 2 * (2 * n - 1) * catalan3(n - 1) / (1 + n) : 1; + return n ? 2 * (2 * n - 1) * catalan3(n - 1) / (1 + n) : 1; } int main(void) { - int i; - puts("\tdirect\tsumming\tfrac"); - for (i = 0; i < 16; i++) { - printf("%d\t%llu\t%llu\t%llu\n", i, - catalan1(i), catalan2(i), catalan3(i)); - } + int i; + puts("\tdirect\tsumming\tfrac"); + for (i = 0; i < 16; i++) { + printf("%d\t%llu\t%llu\t%llu\n", i, + catalan1(i), catalan2(i), catalan3(i)); + } - return 0; + return 0; } diff --git a/Task/Catalan-numbers/Clojure/catalan-numbers.clj b/Task/Catalan-numbers/Clojure/catalan-numbers.clj index 57fb520b3a..2c2e384fb2 100644 --- a/Task/Catalan-numbers/Clojure/catalan-numbers.clj +++ b/Task/Catalan-numbers/Clojure/catalan-numbers.clj @@ -2,13 +2,13 @@ (defn catalan-numbers-direct [] (map #(/ (! (* 2 %)) - (* (! (inc %)) (! %))) (range))) + (* (! (inc %)) (! %))) (range))) (def catalan-numbers-recursive #(->> [1 1] ; [c0 n1] - (iterate (fn [[c n]] - [(* 2 (dec (* 2 n)) (/ (inc n)) c) (inc n)]) ,) - (map first ,))) + (iterate (fn [[c n]] + [(* 2 (dec (* 2 n)) (/ (inc n)) c) (inc n)]) ,) + (map first ,))) user> (take 15 (catalan-numbers-direct)) (1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440) diff --git a/Task/Catalan-numbers/Common-Lisp/catalan-numbers.lisp b/Task/Catalan-numbers/Common-Lisp/catalan-numbers.lisp index 90dc815c36..2e79edd33d 100644 --- a/Task/Catalan-numbers/Common-Lisp/catalan-numbers.lisp +++ b/Task/Catalan-numbers/Common-Lisp/catalan-numbers.lisp @@ -5,18 +5,18 @@ ;; cache (defparameter *catalans* (make-array 5 - :fill-pointer 0 - :adjustable t - :element-type 'integer)) + :fill-pointer 0 + :adjustable t + :element-type 'integer)) (defun catalan2 (n) (if (zerop n) 1 ;; check cache (if (< n (length *catalans*)) (aref *catalans* n) (loop with c = 0 for i from 0 to (1- n) collect - (incf c (* (catalan2 i) (catalan2 (- n 1 i)))) - ;; lower values always get calculated first, so - ;; vector-push-extend is safe - finally (progn (vector-push-extend c *catalans*) (return c)))))) + (incf c (* (catalan2 i) (catalan2 (- n 1 i)))) + ;; lower values always get calculated first, so + ;; vector-push-extend is safe + finally (progn (vector-push-extend c *catalans*) (return c)))))) (defun catalan3 (n) (if (zerop n) 1 (/ (* 2 (+ n n -1) (catalan3 (1- n))) (1+ n)))) diff --git a/Task/Catalan-numbers/Craft-Basic/catalan-numbers.basic b/Task/Catalan-numbers/Craft-Basic/catalan-numbers.basic index 37990e350e..533428522a 100644 --- a/Task/Catalan-numbers/Craft-Basic/catalan-numbers.basic +++ b/Task/Catalan-numbers/Craft-Basic/catalan-numbers.basic @@ -4,16 +4,16 @@ let c[0] = 1 for n = 0 to 15 - let p = n + 1 - let c[p] = 0 + let p = n + 1 + let c[p] = 0 - for i = 0 to n + for i = 0 to n - let q = n - i - let c[p] = c[p] + c[i] * c[q] + let q = n - i + let c[p] = c[p] + c[i] * c[q] - next i + next i - print n, " ", c[n] + print n, " ", c[n] next n diff --git a/Task/Catalan-numbers/EchoLisp/catalan-numbers.l b/Task/Catalan-numbers/EchoLisp/catalan-numbers.l index 65ac46bf72..450fd816e0 100644 --- a/Task/Catalan-numbers/EchoLisp/catalan-numbers.l +++ b/Task/Catalan-numbers/EchoLisp/catalan-numbers.l @@ -9,7 +9,7 @@ ;; using a recursive procedure with memoization (define (C2 n) ;; ( Σ ...)is the same as (sigma ..) - (Σ (lambda(i) (* (C2 i) (C2 (- n i 1)))) 0 (1- n))) + (Σ (lambda(i) (* (C2 i) (C2 (- n i 1)))) 0 (1- n))) (remember 'C2 #(1)) ;; first term defined here (for ((i [1 .. 16])) (write (C2 i))) diff --git a/Task/Catalan-numbers/Eiffel/catalan-numbers.e b/Task/Catalan-numbers/Eiffel/catalan-numbers.e index 48e6ace4fe..3e8225c6ee 100644 --- a/Task/Catalan-numbers/Eiffel/catalan-numbers.e +++ b/Task/Catalan-numbers/Eiffel/catalan-numbers.e @@ -1,35 +1,35 @@ class - APPLICATION + APPLICATION create - make + make feature {NONE} - make - do - across - 0 |..| 14 as c - loop - io.put_double (nth_catalan_number (c.item)) - io.new_line - end - end + make + do + across + 0 |..| 14 as c + loop + io.put_double (nth_catalan_number (c.item)) + io.new_line + end + end - nth_catalan_number (n: INTEGER): DOUBLE - --'n'th number in the sequence of Catalan numbers. - require - n_not_negative: n >= 0 - local - s, t: DOUBLE - do - if n = 0 then - Result := 1.0 - else - t := 4 * n.to_double - 2 - s := n.to_double + 1 - Result := t / s * nth_catalan_number (n - 1) - end - end + nth_catalan_number (n: INTEGER): DOUBLE + --'n'th number in the sequence of Catalan numbers. + require + n_not_negative: n >= 0 + local + s, t: DOUBLE + do + if n = 0 then + Result := 1.0 + else + t := 4 * n.to_double - 2 + s := n.to_double + 1 + Result := t / s * nth_catalan_number (n - 1) + end + end end diff --git a/Task/Catalan-numbers/Euphoria/catalan-numbers.eu b/Task/Catalan-numbers/Euphoria/catalan-numbers.eu new file mode 100644 index 0000000000..c57c8bc2a8 --- /dev/null +++ b/Task/Catalan-numbers/Euphoria/catalan-numbers.eu @@ -0,0 +1,23 @@ +--Catalan number task from Rosetta Code wiki +--User:Lnettnay + +--function from factorial task +function factorial(integer n) +atom f = 1 +while n > 1 do + f *= n + n -= 1 +end while + +return f +end function + +function catalan(integer n) +atom numerator = factorial(2 * n) +atom denominator = factorial(n+1)*factorial(n) +return numerator/denominator +end function + +for i = 0 to 15 do + ? catalan(i) +end for diff --git a/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js b/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js index ffea51d934..aeeca0bb0e 100644 --- a/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js +++ b/Task/Catalan-numbers/JavaScript/catalan-numbers-1.js @@ -1,29 +1,29 @@ Catalan
    
    diff --git a/Task/Catalan-numbers/LOLCODE/catalan-numbers.lol b/Task/Catalan-numbers/LOLCODE/catalan-numbers.lol
    new file mode 100644
    index 0000000000..9376389839
    --- /dev/null
    +++ b/Task/Catalan-numbers/LOLCODE/catalan-numbers.lol
    @@ -0,0 +1,19 @@
    +HAI 1.3
    +
    +I HAS A CATALAN ITZ 1
    +IM IN YR LOOP UPPIN YR N TIL BOTH SAEM N AN 15
    +    VISIBLE CATALAN " "!
    +    CATALAN R ...
    +        QUOSHUNT OF ...
    +            PRODUKT OF ...
    +                CATALAN AN ...
    +                PRODUKT OF ...
    +                    2 AN ...
    +                    SUM OF ...
    +                        PRODUKT OF 2 AN N ...
    +                        AN 1 ...
    +            AN SUM OF N AN 2
    +IM OUTTA YR LOOP
    +VISIBLE ""
    +
    +KTHXBYE
    diff --git a/Task/Catalan-numbers/Lambdatalk/catalan-numbers-4.lambdatalk b/Task/Catalan-numbers/Lambdatalk/catalan-numbers-4.lambdatalk
    index bbbc62d423..332a93def3 100644
    --- a/Task/Catalan-numbers/Lambdatalk/catalan-numbers-4.lambdatalk
    +++ b/Task/Catalan-numbers/Lambdatalk/catalan-numbers-4.lambdatalk
    @@ -13,20 +13,20 @@
             {S.serie 0 15}}
     }
     
    -	   cat1    cat2    cat3
    - 0 	      1 	  1 	  1
    - 1 	      1 	  1 	  1
    - 2 	      2 	  2 	  2
    - 3 	      5 	  5 	  5
    - 4 	     14 	 14 	 14
    - 5 	     42 	 42 	 42
    - 6 	    132 	132 	132
    - 7 	    429 	429 	429
    - 8 	   1430    1430    1430
    - 9 	   4862    4862    4862
    -10 	  16796   16796   16796
    -11 	  58786   58786   58786
    -12 	 208012  208012  208012
    -13 	 742900  742900  742900
    -14 	2674440 2674440 2674440
    -15 	9694845 9694845 9694845
    +     cat1    cat2    cat3
    + 0        1     1     1
    + 1        1     1     1
    + 2        2     2     2
    + 3        5     5     5
    + 4       14    14    14
    + 5       42    42    42
    + 6      132   132   132
    + 7      429   429   429
    + 8     1430    1430    1430
    + 9     4862    4862    4862
    +10    16796   16796   16796
    +11    58786   58786   58786
    +12   208012  208012  208012
    +13   742900  742900  742900
    +14  2674440 2674440 2674440
    +15  9694845 9694845 9694845
    diff --git a/Task/Catalan-numbers/Langur/catalan-numbers.langur b/Task/Catalan-numbers/Langur/catalan-numbers.langur
    index 51ff6b65a4..2857c038e6 100644
    --- a/Task/Catalan-numbers/Langur/catalan-numbers.langur
    +++ b/Task/Catalan-numbers/Langur/catalan-numbers.langur
    @@ -1,6 +1,6 @@
    -val factorial = fn x:if(x < 2: 1; x * fn((x - 1)))
    +val factorial = fn(x number) { if(x < 2: 1; x * fn((x - 1))) }
     
    -val catalan = fn n:factorial(2 * n) / factorial(n+1) / factorial(n)
    +val catalan = fn(n number) { factorial(2 * n) / factorial(n+1) / factorial(n) }
     
     for i in 0..15 {
         writeln "{{i:2}}: {{catalan(i):10}}"
    diff --git a/Task/Catalan-numbers/Loglan82/catalan-numbers.loglan82 b/Task/Catalan-numbers/Loglan82/catalan-numbers.loglan82
    new file mode 100644
    index 0000000000..ba04f68c61
    --- /dev/null
    +++ b/Task/Catalan-numbers/Loglan82/catalan-numbers.loglan82
    @@ -0,0 +1,26 @@
    +(* Catalan numbers *)
    +
    +block
    +const
    +  max_n = 13; (* 13 with 32-bit signed integer; 10 for 16-bit signed integer *)
    +var
    +  c, n, i: integer;
    +begin
    +  n := 0;
    +  c := 1;
    +  writeln(" N     C");
    +  writeln(n: 2, c: 8);
    +  while n < max_n
    +  do
    +    n := n + 1;
    +    i := 0;
    +    while c > 0
    +    do
    +      c := c - (n + 1);
    +      i := i + 1
    +    od;
    +    c := 2 * (2 * n - 1) * c div (n + 1);
    +    c := c + 2 * i * (2 * n - 1);
    +    writeln(n: 2, c: 8);
    +  od;
    +end;
    diff --git a/Task/Catalan-numbers/Oberon-07/catalan-numbers.oberon b/Task/Catalan-numbers/Oberon-07/catalan-numbers.oberon
    new file mode 100644
    index 0000000000..69260c98f2
    --- /dev/null
    +++ b/Task/Catalan-numbers/Oberon-07/catalan-numbers.oberon
    @@ -0,0 +1,29 @@
    +MODULE CatalanNumbers; (* print some catalan numbers *)
    +    IMPORT Out;
    +
    +    VAR    Cprev, n  : INTEGER;
    +
    +    PROCEDURE round( v : REAL ) : INTEGER;
    +        VAR   iv     : INTEGER;
    +              rv     : REAL;
    +        BEGIN
    +            rv := ABS( v );
    +            iv := FLOOR( rv );
    +            IF ( rv - FLT( iv ) ) >= 0.5 THEN INC( iv ) END;
    +            IF v < 0.0 THEN iv := - iv END
    +        RETURN iv
    +        END round;
    +
    +    PROCEDURE printCatalan( n, cn : INTEGER );
    +        BEGIN
    +            Out.Int( n, 3 );Out.String( ": " );Out.Int( cn, 0 );Out.Ln
    +        END printCatalan;
    +
    +BEGIN
    +    Cprev := 1;  (* C0 *)
    +    printCatalan( 0, Cprev );
    +    FOR n := 1 TO 15 DO
    +        Cprev := round( ( FLT( ( 4 * n ) - 2 ) / FLT( n + 1 ) ) * FLT( Cprev ) );
    +        printCatalan( n, Cprev )
    +    END
    +END CatalanNumbers.
    diff --git a/Task/Catalan-numbers/Pascal-P/catalan-numbers.pas b/Task/Catalan-numbers/Pascal-P/catalan-numbers.pas
    new file mode 100644
    index 0000000000..8c68a5e192
    --- /dev/null
    +++ b/Task/Catalan-numbers/Pascal-P/catalan-numbers.pas
    @@ -0,0 +1,25 @@
    +program catalan(output);
    +  (* Catalan numbers *)
    +const
    +  maxn = 14; (* with 32-bit integer; 10 for 16-bit integer *)
    +var
    +  n, c, i: integer;
    +begin
    +  n := 0;
    +  c := 1;
    +  writeln('C(', n: 2, ') = ', c: 8);
    +  while n < maxn do
    +  begin
    +    n := n + 1;
    +    i := 0;
    +    while c > 0 do
    +    begin
    +      c := c - (n + 1);
    +      i := i + 1;
    +    end;
    +    c := 2 * (2 * n - 1) * c div (n + 1);
    +    c := c + 2 * i * (2 * n - 1);
    +    writeln('C(', n: 2, ') = ', c: 8);
    +  end;
    +  (* readln; *)
    +end.
    diff --git a/Task/Catalan-numbers/PlainTeX/catalan-numbers.tex b/Task/Catalan-numbers/PlainTeX/catalan-numbers.tex
    index 0b7113ddac..f4e48250c0 100644
    --- a/Task/Catalan-numbers/PlainTeX/catalan-numbers.tex
    +++ b/Task/Catalan-numbers/PlainTeX/catalan-numbers.tex
    @@ -4,19 +4,19 @@
     \newcount\ii
     
     \def\catalan#1{%
    -	\n#1\advance\n by1\ii1\r1%
    -	\loop{%
    -		\x\ii%
    -		\multiply\x by 2 \advance\x by -1 \multiply\x by 2%
    -		\global\multiply\r by\x%
    -		\global\advance\ii by1%
    -		\global\divide\r by\ii%
    -	} \ifnum\number\ii<\n\repeat%
    -	\the\r
    +  \n#1\advance\n by1\ii1\r1%
    +  \loop{%
    +    \x\ii%
    +    \multiply\x by 2 \advance\x by -1 \multiply\x by 2%
    +    \global\multiply\r by\x%
    +    \global\advance\ii by1%
    +    \global\divide\r by\ii%
    +  } \ifnum\number\ii<\n\repeat%
    +  \the\r
     }
     
     \rightskip=0pt plus1fil\parindent=0pt
     \loop{${\rm Catalan}(\the\x) = \catalan{\the\x}$\hfil\break}%
    -	\advance\x by 1\ifnum\x<15\repeat
    +  \advance\x by 1\ifnum\x<15\repeat
     
     \bye
    diff --git a/Task/Catalan-numbers/Pluto/catalan-numbers.pluto b/Task/Catalan-numbers/Pluto/catalan-numbers.pluto
    new file mode 100644
    index 0000000000..f158c3faf9
    --- /dev/null
    +++ b/Task/Catalan-numbers/Pluto/catalan-numbers.pluto
    @@ -0,0 +1,11 @@
    +do  -- print some catalan numbers
    +    local function printCatalan( n : number, cn : number )
    +        print( string.format( "%3d: %d", n, cn ) )
    +    end
    +    local Cprev = 1 -- C0
    +    printCatalan( 0, Cprev )
    +    for n = 1, 15 do
    +        Cprev = math.round( ( ( ( 4 * n ) - 2 ) / ( n + 1 ) ) * Cprev )
    +        printCatalan( n, Cprev )
    +    end
    +end
    diff --git a/Task/Catalan-numbers/PowerShell/catalan-numbers-1.ps1 b/Task/Catalan-numbers/PowerShell/catalan-numbers-1.ps1
    new file mode 100644
    index 0000000000..22a8095ac7
    --- /dev/null
    +++ b/Task/Catalan-numbers/PowerShell/catalan-numbers-1.ps1
    @@ -0,0 +1,10 @@
    +function Catalan([uint64]$m) {
    +    function fact([bigint]$n) {
    +        if($n -lt 2) {[bigint]::one}
    +        else{2..$n | foreach -Begin {$prod = [bigint]::one} -Process {$prod = [bigint]::Multiply($prod,$_)} -End {$prod}}
    +    }
    +    $fact = fact $m
    +    $fact1 = [bigint]::Multiply($m+1,$fact)
    +    [bigint]::divide((fact (2*$m)), [bigint]::Multiply($fact,$fact1))
    +}
    +0..15 | foreach {"catalan($_): $(catalan $_)"}
    diff --git a/Task/Catalan-numbers/PowerShell/catalan-numbers-2.ps1 b/Task/Catalan-numbers/PowerShell/catalan-numbers-2.ps1
    new file mode 100644
    index 0000000000..f0bc38b0e7
    --- /dev/null
    +++ b/Task/Catalan-numbers/PowerShell/catalan-numbers-2.ps1
    @@ -0,0 +1,51 @@
    +function Get-CatalanNumber
    +{
    +    [CmdletBinding()]
    +    [OutputType([PSCustomObject])]
    +    Param
    +    (
    +        [Parameter(Mandatory=$true,
    +                   ValueFromPipeline=$true,
    +                   ValueFromPipelineByPropertyName=$true,
    +                   Position=0)]
    +        [uint32[]]
    +        $InputObject
    +    )
    +
    +    Begin
    +    {
    +        function Get-Factorial ([int]$Number)
    +        {
    +            if ($Number -eq 0)
    +            {
    +                return 1
    +            }
    +
    +            $factorial = 1
    +
    +            1..$Number | ForEach-Object {$factorial *= $_}
    +
    +            $factorial
    +        }
    +
    +        function Get-Catalan ([int]$Number)
    +        {
    +            if ($Number -eq 0)
    +            {
    +                return 1
    +            }
    +
    +            (Get-Factorial (2 * $Number)) / ((Get-Factorial (1 + $Number)) * (Get-Factorial $Number))
    +        }
    +    }
    +    Process
    +    {
    +        foreach ($number in $InputObject)
    +        {
    +            [PSCustomObject]@{
    +                Number        = $number
    +                CatalanNumber = Get-Catalan $number
    +            }
    +        }
    +    }
    +}
    diff --git a/Task/Catalan-numbers/PowerShell/catalan-numbers-3.ps1 b/Task/Catalan-numbers/PowerShell/catalan-numbers-3.ps1
    new file mode 100644
    index 0000000000..97a6ba77e4
    --- /dev/null
    +++ b/Task/Catalan-numbers/PowerShell/catalan-numbers-3.ps1
    @@ -0,0 +1 @@
    +0..14 | Get-CatalanNumber
    diff --git a/Task/Catalan-numbers/PowerShell/catalan-numbers-4.ps1 b/Task/Catalan-numbers/PowerShell/catalan-numbers-4.ps1
    new file mode 100644
    index 0000000000..c7fca55fba
    --- /dev/null
    +++ b/Task/Catalan-numbers/PowerShell/catalan-numbers-4.ps1
    @@ -0,0 +1 @@
    +(0..14 | Get-CatalanNumber).CatalanNumber
    diff --git a/Task/Catalan-numbers/Prolog/catalan-numbers.pro b/Task/Catalan-numbers/Prolog/catalan-numbers.pro
    index ba46d3eb74..5a63ce234a 100644
    --- a/Task/Catalan-numbers/Prolog/catalan-numbers.pro
    +++ b/Task/Catalan-numbers/Prolog/catalan-numbers.pro
    @@ -1,17 +1,17 @@
     catalan(N) :-
    -	length(L1, N),
    -	L = [1 | L1],
    -	init(1,1,L1),
    -	numlist(0, N, NL),
    -	maplist(my_write, NL, L).
    +  length(L1, N),
    +  L = [1 | L1],
    +  init(1,1,L1),
    +  numlist(0, N, NL),
    +  maplist(my_write, NL, L).
     
     
     init(_, _, []).
     
     init(V, N, [H | T]) :-
    -	N1 is N+1,
    -	H is 2 * (2 * N - 1) * V / N1,
    -	init(H, N1, T).
    +  N1 is N+1,
    +  H is 2 * (2 * N - 1) * V / N1,
    +  init(H, N1, T).
     
     my_write(N, V) :-
    -	format('~w : ~w~n', [N, V]).
    +  format('~w : ~w~n', [N, V]).
    diff --git a/Task/Catalan-numbers/QuickBASIC/catalan-numbers.basic b/Task/Catalan-numbers/QuickBASIC/catalan-numbers.basic
    new file mode 100644
    index 0000000000..27bf542ff5
    --- /dev/null
    +++ b/Task/Catalan-numbers/QuickBASIC/catalan-numbers.basic
    @@ -0,0 +1,17 @@
    +' Catalan numbers
    +CONST MAXN% = 13 ' with 32-bit signed  integer; 10 for 16-bit signed integer
    +N% = 0
    +C& = 1
    +PRINT USING "C(##) = ########"; N%, C&
    +DO WHILE N% < MAXN%
    +  N% = N% + 1
    +  I% = 0
    +  DO WHILE C& > 0
    +    C& = C& - (N% + 1)
    +    I% = I% + 1
    +  LOOP
    +  C& = 2 * (2& * N% - 1) * C& \ (N% + 1)
    +  C& = C& + 2& * I% * (2 * N% - 1)
    +  PRINT USING "C(##) = ########"; N%, C&
    +LOOP
    +END
    diff --git a/Task/Catalan-numbers/Rebol/catalan-numbers.rebol b/Task/Catalan-numbers/Rebol/catalan-numbers.rebol
    new file mode 100644
    index 0000000000..3ccc45b926
    --- /dev/null
    +++ b/Task/Catalan-numbers/Rebol/catalan-numbers.rebol
    @@ -0,0 +1,21 @@
    +Rebol [
    +    title: "Rosetta code: Catalan numbers"
    +    file:  %Catalan_numbers.r3
    +    url:   https://rosettacode.org/wiki/Catalan_numbers
    +]
    +
    +catalan: func [
    +    "Compute the nth Catalan number recursively"
    +    n [integer!]
    +][
    +    either zero? n [1][
    +        (catalan n - 1) * (4 * n - 2) / (n + 1)
    +    ]
    +]
    +
    +for n 0 15 1 [
    +    print [
    +        pad n 5
    +        pad catalan n -20
    +    ]
    +]
    diff --git a/Task/Catalan-numbers/SuperCollider/catalan-numbers.sc b/Task/Catalan-numbers/SuperCollider/catalan-numbers.sc
    new file mode 100644
    index 0000000000..267e493b1e
    --- /dev/null
    +++ b/Task/Catalan-numbers/SuperCollider/catalan-numbers.sc
    @@ -0,0 +1,18 @@
    +(
    +// Usage: ~catalan.(n)
    +// Return a list of all Catalan numbers C(0), ..., C(n),
    +// where n is a positive or null integer.
    +~catalan = {
    +  arg n; var out = [1], x;
    +
    +  if(n == 0){}{
    +    for(1, n){
    +      arg i;
    +      x = (2*(2*i - 1)/(i + 1))*out[i - 1];
    +      out = out ++ [x];
    +  };};
    +  out;
    +};
    +
    +~catalan.(14).do{arg item; item.postln};
    +)
    diff --git a/Task/Catalan-numbers/Tcl/catalan-numbers-1.tcl b/Task/Catalan-numbers/Tcl/catalan-numbers-1.tcl
    index 1b09dc0b0c..955ebe5f26 100644
    --- a/Task/Catalan-numbers/Tcl/catalan-numbers-1.tcl
    +++ b/Task/Catalan-numbers/Tcl/catalan-numbers-1.tcl
    @@ -5,7 +5,7 @@ proc memoize {function value generator} {
         variable memoize
         set key $function,$value
         if {![info exists memoize($key)]} {
    -	set memoize($key) [uplevel 1 $generator]
    +  set memoize($key) [uplevel 1 $generator]
         }
         return $memoize($key)
     }
    @@ -14,6 +14,6 @@ proc memoize {function value generator} {
     proc tcl::mathfunc::catalan n {
         if {[incr n 0] < 0} {error "must not be negative"}
         memoize catalan $n {expr {
    -	$n == 0 ? 1 : 2 * (2*$n - 1) * catalan($n - 1) / ($n + 1)
    +  $n == 0 ? 1 : 2 * (2*$n - 1) * catalan($n - 1) / ($n + 1)
         }}
     }
    diff --git a/Task/Catalan-numbers/Uiua/catalan-numbers.uiua b/Task/Catalan-numbers/Uiua/catalan-numbers.uiua
    new file mode 100644
    index 0000000000..b29b09f1f4
    --- /dev/null
    +++ b/Task/Catalan-numbers/Uiua/catalan-numbers.uiua
    @@ -0,0 +1,2 @@
    +C ← |1 memo⨬(/+×∩C⊸⇌⇡|⋅1)⊸=₀
    +C⇡15
    diff --git a/Task/Catalan-numbers/V-(Vlang)/catalan-numbers.v b/Task/Catalan-numbers/V-(Vlang)/catalan-numbers.v
    index 8b8ecf58ab..28fb9de2a6 100644
    --- a/Task/Catalan-numbers/V-(Vlang)/catalan-numbers.v
    +++ b/Task/Catalan-numbers/V-(Vlang)/catalan-numbers.v
    @@ -3,8 +3,8 @@ import math.big
     fn main() {
         mut b:= big.zero_int
         for n := i64(0); n < 15; n++ {
    -		b = big.integer_from_i64(n)
    -		b = (b*big.two_int).factorial()/(b.factorial()*(b*big.two_int-b).factorial())
    +    b = big.integer_from_i64(n)
    +    b = (b*big.two_int).factorial()/(b.factorial()*(b*big.two_int-b).factorial())
             println(b/big.integer_from_i64(n+1))
         }
     }
    diff --git a/Task/Catalan-numbers/VBScript/catalan-numbers.vbs b/Task/Catalan-numbers/VBScript/catalan-numbers.vbs
    new file mode 100644
    index 0000000000..29a731fe09
    --- /dev/null
    +++ b/Task/Catalan-numbers/VBScript/catalan-numbers.vbs
    @@ -0,0 +1,23 @@
    +Function catalan(n)
    +  catalan = factorial(2*n)/(factorial(n+1)*factorial(n))
    +End Function
    +
    +Function factorial(n)
    +  If n = 0 Then
    +    Factorial = 1
    +  Else
    +    For i = n To 1 Step -1
    +      If i = n Then
    +        factorial = n
    +      Else
    +        factorial = factorial * i
    +      End If
    +    Next
    +  End If
    +End Function
    +
    +'Find the first 15 Catalan numbers.
    +For j = 1 To 15
    +  WScript.StdOut.Write j & " = " & catalan(j)
    +  WScript.StdOut.WriteLine
    +Next
    diff --git a/Task/Catalan-numbers/XLISP/catalan-numbers.l b/Task/Catalan-numbers/XLISP/catalan-numbers.l
    index 45c4464433..80c543520a 100644
    --- a/Task/Catalan-numbers/XLISP/catalan-numbers.l
    +++ b/Task/Catalan-numbers/XLISP/catalan-numbers.l
    @@ -1,11 +1,11 @@
     (defun catalan (n)
    -	(if (= n 0)
    -		1
    -		(* (/ (* 2 (- (* 2 n) 1)) (+ n 1)) (catalan (- n 1))) ) )
    +  (if (= n 0)
    +    1
    +    (* (/ (* 2 (- (* 2 n) 1)) (+ n 1)) (catalan (- n 1))) ) )
     
     (defun range (x y)
    -	(cons x
    -		(if (< x y)
    -			(range (+ x 1) y) ) ) )
    +  (cons x
    +    (if (< x y)
    +      (range (+ x 1) y) ) ) )
     
     (print (mapcar catalan (range 0 14)))
    diff --git a/Task/Catalan-numbers/Yabasic/catalan-numbers.basic b/Task/Catalan-numbers/Yabasic/catalan-numbers.basic
    index fb8c32adcc..289517f3fe 100644
    --- a/Task/Catalan-numbers/Yabasic/catalan-numbers.basic
    +++ b/Task/Catalan-numbers/Yabasic/catalan-numbers.basic
    @@ -2,7 +2,7 @@ print "  n   First    Second    Third"
     print "  -   -----    ------    -----"
     print
     for i = 0 to 15
    -	print i using "###", catalan1(i) using "########", catalan2(i) using "########", catalan3(i) using "########"
    +  print i using "###", catalan1(i) using "########", catalan2(i) using "########", catalan3(i) using "########"
     next i
     end
     
    diff --git a/Task/Catamorphism/Ada/catamorphism.adb b/Task/Catamorphism/Ada/catamorphism.adb
    new file mode 100644
    index 0000000000..2c85c94544
    --- /dev/null
    +++ b/Task/Catamorphism/Ada/catamorphism.adb
    @@ -0,0 +1,29 @@
    +with Ada.Text_IO;
    +
    +procedure Catamorphism is
    +
    +   type Fun is access function (Left, Right: Natural) return Natural;
    +   type Arr is array(Natural range <>) of Natural;
    +
    +   function Fold_Left (F: Fun; A: Arr) return Natural is
    +      Result: Natural := A(A'First);
    +   begin
    +      for I in A'First+1 .. A'Last loop
    +	 Result := F(Result, A(I));
    +      end loop;
    +      return Result;
    +   end Fold_Left;
    +
    +   function Max (L, R: Natural) return Natural is (if L > R then L else R);
    +   function Min (L, R: Natural) return Natural is (if L < R then L else R);
    +   function Add (Left, Right: Natural) return Natural is (Left + Right);
    +   function Mul (Left, Right: Natural) return Natural is (Left * Right);
    +
    +   package NIO is new Ada.Text_IO.Integer_IO(Natural);
    +
    +begin
    +   NIO.Put(Fold_Left(Min'Access, (1,2,3,4)), Width => 3);
    +   NIO.Put(Fold_Left(Max'Access, (1,2,3,4)), Width => 3);
    +   NIO.Put(Fold_Left(Add'Access, (1,2,3,4)), Width => 3);
    +   NIO.Put(Fold_Left(Mul'Access, (1,2,3,4)), Width => 3);
    +end Catamorphism;
    diff --git a/Task/Catamorphism/Crystal/catamorphism.cr b/Task/Catamorphism/Crystal/catamorphism.cr
    new file mode 100644
    index 0000000000..c9c23aced2
    --- /dev/null
    +++ b/Task/Catamorphism/Crystal/catamorphism.cr
    @@ -0,0 +1,16 @@
    +arr = [1, 2, 3, 4, 5]
    +
    +# basic form:
    +arr.reduce {|acc, n| acc + n }      # => 15
    +
    +# with initial value:
    +arr.reduce(100) {|acc, n| acc + n } # => 115
    +
    +# there are some built-in reducers:
    +arr.product                         # => 120
    +arr.sum                             # => 15
    +arr.accumulate                      # => [1, 3, 6, 10, 15]
    +
    +# they allow for an initial value
    +# and/or a block to map the elements beforehand:
    +arr.sum(1000) {|elt| elt * 100 }    # => 2500
    diff --git a/Task/Catamorphism/Gleam/catamorphism.gleam b/Task/Catamorphism/Gleam/catamorphism.gleam
    new file mode 100644
    index 0000000000..c715dd322b
    --- /dev/null
    +++ b/Task/Catamorphism/Gleam/catamorphism.gleam
    @@ -0,0 +1,7 @@
    +import gleam/list
    +
    +pub fn main() {
    +  let _ = [1, 4, 8, 3] |> list.reduce(fn(x, y) { x + y })  // Ok(16)
    +  // Or, with a seed
    +  let _ = [1, 4, 8, 3] |> list.fold(from: 100, with: fn(x, y) { x + y }) // 116
    +}
    diff --git a/Task/Catamorphism/Pluto/catamorphism.pluto b/Task/Catamorphism/Pluto/catamorphism.pluto
    new file mode 100644
    index 0000000000..11dcc0b7d8
    --- /dev/null
    +++ b/Task/Catamorphism/Pluto/catamorphism.pluto
    @@ -0,0 +1,8 @@
    +local a = {1, 2, 3, 4, 5}
    +local sum    = a:reduce(|acc, i| -> acc + i)
    +local prod   = a:reduce(|acc, i| -> acc * i, 1)
    +local sum_sq = a:reduce(|acc, i| -> acc + i * i)
    +print("{" .. a:concat(", ") .. "}")
    +print($"Sum is {sum}")
    +print($"Product is {prod}")
    +print($"Sum of squares is {sum_sq}")
    diff --git a/Task/Catamorphism/PowerShell/catamorphism.ps1 b/Task/Catamorphism/PowerShell/catamorphism.ps1
    new file mode 100644
    index 0000000000..a35fbb9761
    --- /dev/null
    +++ b/Task/Catamorphism/PowerShell/catamorphism.ps1
    @@ -0,0 +1 @@
    +1..5 | ForEach-Object -Begin {$result = 0} -Process {$result += $_} -End {$result}
    diff --git a/Task/Catamorphism/Python/catamorphism.py b/Task/Catamorphism/Python/catamorphism.py
    new file mode 100644
    index 0000000000..47ed91cbe8
    --- /dev/null
    +++ b/Task/Catamorphism/Python/catamorphism.py
    @@ -0,0 +1,13 @@
    +from functools import reduce
    +from operator import add
    +from operator import mul
    +
    +def concat(a: int | str, b: int | str) -> str:
    +    return str(a) + str(b)
    +
    +a = list(range(1, 11))
    +
    +print(a)
    +print(f"sum: {reduce(add, a)}")
    +print(f"product: {reduce(mul, a)}")
    +print(f"concat: {reduce(concat, a)}")
    diff --git a/Task/Catamorphism/Rye/catamorphism.rye b/Task/Catamorphism/Rye/catamorphism.rye
    new file mode 100644
    index 0000000000..e22677fc88
    --- /dev/null
    +++ b/Task/Catamorphism/Rye/catamorphism.rye
    @@ -0,0 +1,8 @@
    +; use first element as seed
    +print reduce { 10 5 7 2 } 'acc { + acc }
    +
    +; provide a seed
    +print fold\do { } 'acc 1 { * acc }
    +
    +; use a function instead of word + block
    +print fold { 1 2 3 } 20 fn { x acc } { + acc }
    diff --git a/Task/Catamorphism/Uiua/catamorphism.uiua b/Task/Catamorphism/Uiua/catamorphism.uiua
    new file mode 100644
    index 0000000000..d04275cebe
    --- /dev/null
    +++ b/Task/Catamorphism/Uiua/catamorphism.uiua
    @@ -0,0 +1,2 @@
    +/× [1 2 3 4]
    +∧× [1 2 3 4] 10
    diff --git a/Task/Catmull-Clark-subdivision-surface/Raku/catmull-clark-subdivision-surface.raku b/Task/Catmull-Clark-subdivision-surface/Raku/catmull-clark-subdivision-surface.raku
    new file mode 100644
    index 0000000000..f9c4b3253b
    --- /dev/null
    +++ b/Task/Catmull-Clark-subdivision-surface/Raku/catmull-clark-subdivision-surface.raku
    @@ -0,0 +1,351 @@
    +# 20260201 Raku programming solution
    +
    +use NativeCall;
    +
    +constant WIN-WIDTH  = 600;       # Window Width
    +constant WIN-HEIGHT = 600;       # Window Height
    +constant OBJ-SCALE  = 1.8e0;     # Scale factor
    +constant X-ROT-FREQ = 0.0006e0;  # X rotation frequency
    +enum GLbitfield
    +   ( GL_COLOR_BUFFER_BIT => 0x00004000, GL_DEPTH_BUFFER_BIT => 0x00000100 );
    +enum GLmatrix ( GL_MODELVIEW  => 0x1700, GL_PROJECTION => 0x1701 );
    +enum GLcap
    +   ( GL_DEPTH_TEST => 0x0B71, GL_LIGHTING => 0x0B50, GL_LIGHT0 => 0x4000 );
    +enum GLparam
    +   ( GL_DIFFUSE => 0x1201, GL_POSITION => 0x1203, GL_FRONT_AND_BACK => 0x0408 );
    +enum GLprimitive (  GL_LINES   => 0x0001, GL_POLYGON => 0x0009 );
    +enum GLmode ( GL_LINE => 0x1B01 );
    +enum GLattrib
    +   ( GL_POLYGON_BIT => 0x00000008, GL_LIGHTING_BIT => 0x00000040, GL_ENABLE_BIT => 0x00002000 );
    +enum GLUTstate ( GLUT_ELAPSED_TIME => 0x02BC );
    +
    +# GLUT Bindings
    +constant $glutlib = 'glut';
    +sub glutInit(CArray[uint32], CArray[Str]) is native($glutlib) {*}
    +sub glutInitDisplayMode(uint32) is native($glutlib) {*}
    +sub glutInitWindowSize(int32, int32) is native($glutlib) {*}
    +sub glutCreateWindow(Str) is native($glutlib) {*}
    +sub glutDisplayFunc(&func ()) is native($glutlib) {*}
    +sub glutReshapeFunc(&func (int32, int32)) is native($glutlib) {*}
    +sub glutKeyboardFunc(&func (uint8, int32, int32)) is native($glutlib) {*}
    +sub glutIdleFunc(&func ()) is native($glutlib) {*}
    +sub glutSwapBuffers() is native($glutlib) {*}
    +sub glutMainLoop() is native($glutlib) {*}
    +sub glutPostRedisplay() is native($glutlib) {*}
    +sub glutGet(int32 --> int32) is native($glutlib) {*}
    +
    +# OpenGL Bindings
    +constant $gllib = 'GL';
    +sub glClear(int32) is native($gllib) {*}
    +sub glClearColor(num32, num32, num32, num32) is native($gllib) {*}
    +sub glClearDepth(num64) is native($gllib) {*}
    +sub glEnable(int32) is native($gllib) {*}
    +sub glDisable(int32) is native($gllib) {*}
    +sub glViewport(int32, int32, int32, int32) is native($gllib) {*}
    +sub glMatrixMode(int32) is native($gllib) {*}
    +sub glLoadIdentity() is native($gllib) {*}
    +sub glBegin(int32) is native($gllib) {*}
    +sub glEnd() is native($gllib) {*}
    +sub glVertex3f(num32, num32, num32) is native($gllib) {*}
    +sub glVertex3fv(CArray[num32]) is native($gllib) {*}
    +sub glNormal3fv(CArray[num32]) is native($gllib) {*}
    +sub glColor3f(num32, num32, num32) is native($gllib) {*}
    +sub glPushAttrib(int32) is native($gllib) {*}
    +sub glPopAttrib() is native($gllib) {*}
    +sub glMaterialfv(int32, int32, CArray[num32]) is native($gllib) {*}
    +sub glLightfv(int32, int32, CArray[num32]) is native($gllib) {*}
    +sub glPolygonMode(int32, int32) is native($gllib) {*}
    +sub glFrustum(num64, num64, num64, num64, num64, num64) is native($gllib) {*}
    +sub glTranslatef(num32, num32, num32) is native($gllib) {*}
    +sub glRotatef(num32, num32, num32, num32) is native($gllib) {*}
    +sub glScalef(num32, num32, num32) is native($gllib) {*}
    +
    +# Vector Math
    +class Vec3 { has num32 ($.x, $.y, $.z);
    +   method new(num32 $x = 0e0, num32 $y = 0e0, num32 $z = 0e0) {
    +      self.bless(:$x, :$y, :$z)
    +   }
    +   method copy()        { Vec3.new: $!x, $!y, $!z }
    +   method add(Vec3 $v)  { Vec3.new: $!x + $v.x, $!y + $v.y, $!z + $v.z }
    +   method sub(Vec3 $v)  { Vec3.new: $!x - $v.x, $!y - $v.y, $!z - $v.z }
    +   method mul(num32 $s) { Vec3.new: $!x * $s, $!y * $s, $!z * $s }
    +   method dot(Vec3 $v)  { $!x * $v.x + $!y * $v.y + $!z * $v.z }
    +   method len()         { sqrt(self.dot(self)).Num }
    +   method normalize() { do given self { .len > 0 ??  .mul(1e0/.len) !! .copy } }
    +   method cross(Vec3 $v) {
    +     Vec3.new: $!y*$v.z - $!z*$v.y, $!z*$v.x - $!x*$v.z, $!x*$v.y - $!y*$v.x
    +   }
    +   method to-array() { CArray[num32].new: $!x, $!y, $!z }
    +}
    +
    +# Mesh Data Structures
    +class Vertex {
    +   has      (@.edges, @.faces) is rw;
    +   has Vec3 ($.pos, $.newpos)  is rw;
    +   method new(Vec3 :$pos!) { self.bless(:$pos, newpos => $pos.copy) }
    +}
    +
    +class Face {
    +   has @.verts is rw;
    +   has Int $.fvert is rw;
    +}
    +
    +class Edge { has Int ($.v0, $.v1, $.f0, $.f1, $.evert) is rw }
    +
    +class Mesh { has (@.vertices, @.normals, @.faces);
    +   method add-vertex(Vec3 $v) { @!vertices.push($v) }
    +   method add-normal(Vec3 $n) { @!normals.push($n) }
    +   method add-face(@verts) { @!faces.push: Face.new(:verts(@verts),:fvert(-1)) }
    +
    +   method compute-normals() {
    +      @!normals = Vec3.new xx @!vertices.elems;
    +      for @!faces -> $face {
    +         for ^$face.verts.elems -> \j {
    +            my $v0=@!vertices[$face.verts[j]];
    +            my $v1=@!vertices[$face.verts[(j+1) % +$face.verts]];
    +            my $v2=@!vertices[$face.verts[(j+ +$face.verts-1) % +$face.verts]];
    +            given $v1.sub($v0).cross($v2.sub($v0)) {
    +               @!normals[$face.verts[j]] .= add: $_
    +            }
    +         }
    +      }
    +      $_ .= normalize for @!normals
    +   }
    +}
    +
    +# Subdivision
    +class SubdivMesh { has (@.verts, @.faces, @.edges);
    +   method find-edge(Int $v0, Int $v1) {
    +      for @!verts[$v0].edges -> $ei {
    +         my $e = @!edges[$ei];
    +         return $ei if $e.v0==$v0 && $e.v1==$v1 or $e.v0==$v1 && $e.v1==$v0
    +      }
    +      return -1;
    +   }
    +
    +   method update-links() {
    +      for @!verts { ( .faces, .edges ) = | [] xx 2 }
    +      @!edges = [];
    +      for @!faces.kv -> $fi, $face {
    +         for ^$face.verts.elems -> $j {
    +            @!verts[ my $v0 = $face.verts[$j] ].faces.push: $fi;
    +            my $v1 = $face.verts[ ($j+1) % $face.verts.elems ];
    +            if ( my $ei = self.find-edge($v0, $v1) ) == -1 {
    +               @!edges.push: Edge.new( :v0($v0), :v1($v1),
    +                                       :f0($fi), :f1(-1),  :evert(-1));
    +               given $ei=+@!edges-1 { @!verts[$_].edges.push($ei) for $v0,$v1 }
    +            } else {
    +               @!edges[$ei].f1 = $fi
    +            }
    +         }
    +      }
    +   }
    +
    +   method subdivide() {
    +      my ($V, $F, $E) = [ @!verts, @!faces, @!edges].map: *.elems;
    +      for @!faces -> $face { # Create face vertices
    +         my $p = Vec3.new;
    +         for $face.verts -> $vi { $p .= add: @!verts[$vi].pos }
    +         @!verts.push: Vertex.new(pos => $p.mul(1e0 / $face.verts.elems));
    +         $face.fvert = @!verts.elems - 1
    +      }
    +      for @!edges -> $edge { # Create edge vertices
    +         my $p = Vec3.new;
    +         $p .= add(@!verts[$edge.v0].pos);
    +         $p .= add(@!verts[$edge.v1].pos);
    +         $p .= add(@!verts[@!faces[$edge.f0].fvert].pos);
    +         $p .= add(@!verts[@!faces[$edge.f1].fvert].pos);
    +         @!verts.push: Vertex.new(pos => $p.mul(0.25e0));
    +         $edge.evert = @!verts.elems - 1
    +      }
    +      for ^$V -> $vi { # Update original vertices
    +         my $n    = (my $v = @!verts[$vi]).faces.elems;
    +         my ($newp,$p1) = $v.pos.mul(($n-2e0)/$n), Vec3.new;
    +
    +         for $v.faces -> $fi { $p1 .= add(@!verts[@!faces[$fi].fvert].pos) }
    +         $newp .= add($p1.mul(1e0 / ($n * $n)));
    +         my $p2 = Vec3.new;
    +         for $v.edges -> $ei {
    +            given @!edges[$ei] { $p2 .= add(@!verts[.v0==$vi??.v1!!.v0].pos) }
    +         }
    +         $v.newpos = $newp .= add($p2.mul(1e0 / ($n * $n)))
    +      }
    +      for ^$V -> $vi { @!verts[$vi].pos = @!verts[$vi].newpos.copy }
    +
    +      @!faces = gather for @!faces -> $face { # Create new faces
    +         for ^$face.verts.elems -> $j {
    +            my $v0 = $face.verts[($j-1+$face.verts.elems) % $face.verts.elems];
    +            my $v  = $face.verts[$j];
    +            my $v1 = $face.verts[($j + 1) % $face.verts.elems];
    +            my $e0 = @!edges[self.find-edge($v0, $v)];
    +            my $e1 = @!edges[self.find-edge($v, $v1)];
    +            take Face.new(:verts($e0.evert,$v,$e1.evert,$face.fvert),:fvert(-1))
    +         }
    +      }
    +      self.update-links();
    +   }
    +
    +   method to-mesh() {
    +      my $mesh = Mesh.new;
    +      for @!verts -> $v    { $mesh.add-vertex($v.pos) }
    +      for @!faces -> $face { $mesh.add-face($face.verts) }
    +      $mesh.compute-normals;
    +      return $mesh
    +   }
    +}
    +
    +sub load-cube() { # Load Cube OBJ
    +   my $mesh = Mesh.new;
    +   for (-1,-1,1,1,-1,1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1).rotor(3) {
    +      $mesh.add-vertex(Vec3.new: | ($_ X* 0.5e0)) # 8 Corner vertices
    +   }
    +   for [0,1,3,2], [2,3,5,4], [4,5,7,6], [6,7,1,0], [1,7,5,3], [6,0,2,4] {
    +      $mesh.add-face: $_  # 6 Faces
    +   }
    +   $mesh.compute-normals;
    +   return $mesh
    +}
    +
    +sub create-subdivision-levels(Mesh $base, Int $levels) {
    +   my @meshes = $base;
    +   my $sd     = SubdivMesh.new;
    +
    +   for $base.vertices -> $v { $sd.verts.push(Vertex.new(pos => $v)) }
    +   for $base.faces -> $face {
    +      $sd.faces.push(Face.new(verts => $face.verts, fvert => -1))
    +   }
    +   $sd.update-links;
    +   return @meshes.append: ^($levels - 1) .map: {
    +      $sd.subdivide;
    +      $sd.to-mesh
    +   }
    +}
    +
    +sub render-mesh(Mesh $mesh) {
    +   for $mesh.faces -> $face {
    +      glBegin(GL_POLYGON);
    +      for $face.verts -> $vi {
    +         glNormal3fv($mesh.normals[$vi].to-array);
    +         glVertex3fv($mesh.vertices[$vi].to-array);
    +      }
    +      glEnd
    +   }
    +}
    +
    +sub draw-xyz() { # Draw XYZ Axis Lines
    +   glPushAttrib(GL_LIGHTING_BIT +| GL_ENABLE_BIT);
    +   glDisable(GL_LIGHTING);
    +   glBegin(GL_LINES);
    +   for (1e0,0e0,0e0), (0e0,1e0,0e0), (0e0,0e0,1e0) -> @color { # XYZ <-> RGB
    +      glColor3f(|@color);
    +      glVertex3f(0e0, 0e0, 0e0);
    +      glVertex3f(|@color)
    +   }
    +   glEnd;
    +   glPopAttrib
    +}
    +
    +# Global State
    +my ( $auto-phase, $auto-dir, $auto-level, $cur-level, $y-rot, $x-rot ) =
    +               0,         1,           0,          0,    0e0,    0e0 ;
    +my ($wireframe, @meshes) = False;
    +
    +sub display() {
    +   glClear(GL_COLOR_BUFFER_BIT +| GL_DEPTH_BUFFER_BIT);
    +
    +   # Setup projection
    +   glMatrixMode(GL_PROJECTION);
    +   glLoadIdentity;
    +   my ( $fovy, $near, $far,   $aspect ) =
    +        60e0,  0.1e0, 1000e0, WIN-WIDTH.Num / WIN-HEIGHT.Num ;
    +   my $top = $near * tan($fovy * pi / 360e0);
    +   glFrustum(-$top * $aspect, $top * $aspect, -$top, $top, $near, 1000e0);
    +
    +   # Setup modelview
    +   glMatrixMode(GL_MODELVIEW);
    +   glLoadIdentity;
    +
    +   # Headlamp Lighting
    +   glEnable(GL_LIGHTING);
    +   glEnable(GL_LIGHT0);
    +   glLightfv(GL_LIGHT0, GL_DIFFUSE, CArray[num32].new(1e0, 1e0, 1e0, 1e0));
    +   glLightfv(GL_LIGHT0, GL_POSITION, CArray[num32].new(0e0, 0e0, 0e0, 1e0));
    +
    +   # Transformations
    +   glTranslatef(0e0, 0e0, -5e0); # Move back from camera
    +   glRotatef($x-rot, 1e0, 0e0, 0e0); # Rotate around X
    +   glRotatef($y-rot, 0e0, 1e0, 0e0); # Rotate around Y
    +
    +   # Scale Object
    +   glScalef(OBJ-SCALE, OBJ-SCALE, OBJ-SCALE);
    +
    +   # Render mesh
    +   glPushAttrib(GL_LIGHTING_BIT +| GL_POLYGON_BIT);
    +   glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, CArray[num32].new(1e0, 1e0, 1e0, 1e0));
    +
    +   if $wireframe {
    +      glDisable(GL_LIGHTING);
    +      glColor3f(0e0, 1e0, 0e0);
    +      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
    +   }
    +   render-mesh(@meshes[$cur-level]);
    +   glPopAttrib;
    +   draw-xyz();
    +   glutSwapBuffers;
    +}
    +
    +sub reshape(int32 $w, int32 $h) {
    +   glViewport(0, 0, $w, $h);
    +   glClearDepth(1e0);
    +   glClearColor(0e0, 0e0, 0e0, 0e0);
    +   glEnable(GL_DEPTH_TEST)
    +}
    +
    +sub keyboard(uint8 $key, int32 $x, int32 $y) {
    +   given $key.chr { when 'q' | 'Q' | "\x1b" { exit(0) } }  # q, Q, or Esc
    +}
    +
    +sub auto-step() {
    +   return unless @meshes.Bool;
    +   ($wireframe, $cur-level) = ($auto-phase == 0), $auto-level;
    +
    +   if $auto-dir > 0 {
    +      $auto-level >= @meshes.elems - 1 ?? ( $auto-dir = -1 ) !! $auto-level++
    +   } else {
    +      $auto-level <= 0 ?? (($auto-phase,$auto-dir) = ($auto-phase + 1) % 2, 1)
    +                       !! $auto-level--
    +   }
    +}
    +
    +sub idle() {
    +   state ($last-ms, $last-auto-ms) = -1, -1;
    +   my $now = glutGet(GLUT_ELAPSED_TIME);
    +   if $last-ms < 0 { ($last-ms, $last-auto-ms) = $now xx 2 }
    +
    +   given my $dt = ($now - $last-ms) / 1000e0 {
    +      $last-ms = $now;
    +      $y-rot += 35e0 * $dt;
    +      $x-rot  = 15e0 * sin($now * X-ROT-FREQ);
    +   }
    +   if ($now - $last-auto-ms) >= 500 {
    +      auto-step();
    +      $last-auto-ms = $now;
    +   }
    +   glutPostRedisplay
    +}
    +
    +# Main
    +glutInit(CArray[uint32].new, CArray[Str].new);
    +glutInitDisplayMode(0x0000 +| 0x0002 +| 0x0010);
    +glutInitWindowSize(WIN-WIDTH, WIN-HEIGHT);
    +glutCreateWindow("Catmull-Clark (Raku)");
    +glutReshapeFunc(&reshape);
    +glutDisplayFunc(&display);
    +glutKeyboardFunc(&keyboard);
    +glutIdleFunc(&idle);
    +
    +say "Generating meshes...";
    +@meshes = create-subdivision-levels(load-cube(), 5);
    +say "Starting loop.\nPress ,  or  to quit.";
    +
    +glutMainLoop;
    diff --git a/Task/Chaocipher/Ada/chaocipher.adb b/Task/Chaocipher/Ada/chaocipher.adb
    new file mode 100644
    index 0000000000..322048ac1d
    --- /dev/null
    +++ b/Task/Chaocipher/Ada/chaocipher.adb
    @@ -0,0 +1,101 @@
    +with Ada.Text_IO; use Ada.Text_IO;
    +
    +procedure chao_slices is
    +   type iMode is (Encrypt, Decrypt);
    +
    +   L_Alphabet : String := "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
    +   R_Alphabet : String := "PTLNBQDEOYSFAVZKGJRIHWXUMC";
    +   plaintext  : String := "WELLDONEISBETTERTHANWELLSAID";
    +   ciphertext : String (1 .. plaintext'length);
    +   plaintext2 : String (1 .. plaintext'length);
    +   offset     : Natural;
    +
    +   function IndexOf (Source : String; Value : Character) return Positive is
    +      Result : Positive;
    +
    +   begin
    +      for I in Source'Range loop
    +         if Source (I) = Value then
    +            Result := I;
    +            exit;
    +         end if;
    +      end loop;
    +      return Result;
    +   end IndexOf;
    +
    +   function Exec
    +     (Text : String; mode : iMode; showsteps : Boolean := False) return String
    +   is
    +      etext : String (Text'First .. Text'Last);
    +      temp  : String (1 .. 26);
    +      index : Positive;
    +      store : Character;
    +      left  : String := L_Alphabet;
    +      right : String := R_Alphabet;
    +   begin
    +      for I in Text'Range loop
    +         if showsteps then
    +            Put_Line (left & "  " & right);
    +         end if;
    +
    +         if mode = Encrypt then
    +            index     := IndexOf (Source => right, Value => Text (I));
    +            etext (I) := left (index);
    +         else
    +            index     := IndexOf (Source => left, Value => Text (I));
    +            etext (I) := right (index);
    +         end if;
    +
    +         exit when I = Text'Last;
    +
    +         -- permute left
    +         -- The array value permutations are performed using array slices
    +         -- rather than explicit loops
    +
    +         if index > 1 then
    +            offset                 := 26 - index;
    +            temp (1 .. offset + 1) := left (index .. index + offset);
    +
    +            temp (offset + 2 .. 26) := left (1 .. index - 1);
    +            store                   := temp (2);
    +
    +            temp (2 .. 13) := temp (3 .. 14);
    +            temp (14)      := store;
    +            left           := temp;
    +
    +            -- permute right
    +            -- The array value permutations are performed using array slices
    +            -- rather than explicit loops
    +
    +            temp (1 .. offset + 1) := right (index .. index + offset);
    +
    +            temp (offset + 2 .. 26) := right (1 .. index - 1);
    +            store                   := temp (1);
    +
    +            temp (1 .. 25) := temp (2 .. 26);
    +            temp (26)      := store;
    +            store          := temp (3);
    +
    +            temp (3 .. 13) := temp (4 .. 14);
    +            temp (14)      := store;
    +            right          := temp;
    +         end if;
    +
    +      end loop;
    +
    +      return etext;
    +
    +   end Exec;
    +begin
    +   Put_Line ("The original text is : " & plaintext);
    +   New_Line;
    +   Put_Line
    +     ("The left and right alphabets after each permutation during encryption are:");
    +   New_Line;
    +   ciphertext := Exec (plaintext, Encrypt, True);
    +   New_Line;
    +   Put_Line ("The ciphertext is : " & ciphertext);
    +   plaintext2 := Exec (ciphertext, Decrypt);
    +   New_Line;
    +   Put_Line ("The recovered plaintext is : " & plaintext2);
    +end chao_slices;
    diff --git a/Task/Chaocipher/Crystal/chaocipher.cr b/Task/Chaocipher/Crystal/chaocipher.cr
    new file mode 100644
    index 0000000000..452e1edf99
    --- /dev/null
    +++ b/Task/Chaocipher/Crystal/chaocipher.cr
    @@ -0,0 +1,40 @@
    +enum Chaoperation
    +  Encode
    +  Decode
    +end
    +
    +class Array
    +  # useful method to work on parts of the array
    +  def slice (start, length)
    +    start = size - start if start < 0
    +    raise "Out of bounds" unless start >= 0 && length >= 0 && start + length <= size
    +    Slice.new(to_unsafe + start, length)
    +  end
    +end
    +
    +def chaocipher (message : String, left : String, right : String,
    +                op : Chaoperation = Chaoperation::Encode)
    +  ct = left.chars
    +  pt = right.chars
    +  String.build do |s|
    +    message.each_char do |ch|
    +      idx = (op == Chaoperation::Encode ? pt : ct).index! ch
    +      s <<  (op == Chaoperation::Encode ? ct : pt)[idx]
    +      # permute left
    +      ct.rotate! idx
    +      ct.slice(1, 13).rotate! 1
    +      # permute right
    +      pt.rotate! idx+1
    +      pt.slice(2, 12).rotate! 1
    +    end
    +  end
    +end
    +
    +left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    +right = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
    +message = "WELLDONEISBETTERTHANWELLSAID"
    +
    +encoded = chaocipher(message, left, right)
    +decoded = chaocipher(encoded, left, right, Chaoperation::Decode)
    +
    +print message, " -> ", encoded, " -> ", decoded, "\n"
    diff --git a/Task/Chaocipher/Forth/chaocipher.fth b/Task/Chaocipher/Forth/chaocipher.fth
    new file mode 100644
    index 0000000000..630e902613
    --- /dev/null
    +++ b/Task/Chaocipher/Forth/chaocipher.fth
    @@ -0,0 +1,77 @@
    +                                       \ triple words
    +: 3drop drop drop drop ;               ( n1 n2 n3 ---)
    +: 3dup >r over over r@ rot rot r> ;    ( n1 n2 n3 -- n1 n2 n3 n1 n2 n3)
    +                                       \ ASCIIZ string words
    +: zstring create chars allot ;         ( a1 -- a1 n1)
    +: zcount dup begin dup c@ while char+ repeat over - ;
    +: zplace over chars over + >r swap cmove 0 r> c! ;
    +: +zplace zcount chars + zplace ;      ( a1 n1 a2 --)
    +                                       \ find character in string
    +: where?                               ( c a1 n1 -- n2)
    +  0 ?do over over i chars + c@ = if drop i negate leave then loop nip negate ;
    +
    +64 constant /str                       \ size of input/output string
    +27 constant /alpha                     \ size of alphabet
    +
    +/str zstring {i}                       \ input string
    +/str zstring {o}                       \ output string
    +
    +/alpha zstring l                       \ left alphabet
    +/alpha zstring r                       \ right alphabet
    +/alpha zstring t                       \ temporary alphabet
    +
    +: [] chars + ;                         ( a n -- a+n)
    +: .tab 9 emit ;                        ( --)
    +: .list cr .tab zcount type cr ;       ( a --)
    +
    +: PermuteLeft                          ( index --)
    +  26 over ?do t over negate i + [] l i [] c@ swap c! loop
    +  dup   0 ?do t over negate 26 i + + [] l i [] c@ swap c! loop drop
    +  t char+ c@ >r t 2 [] dup char- 12 cmove r> t 13 [] c! t zcount l zplace
    +;
    +
    +: PermuteRight                         ( index --)
    +  26 over ?do t over negate i + [] r i [] c@ swap c! loop
    +  dup   0 ?do t over negate 26 i + + [] r i [] c@ swap c! loop drop
    +  t c@ >r      t char+ dup char- 25 cmove r> t 25 [] c!
    +  t 2 [] c@ >r t 3 []  dup char- 11 cmove r> t 13 [] c! t zcount r zplace
    +;
    +
    +: Encrypt                              ( input output index1 -- index2)
    +  >r swap r@ [] c@ r /alpha where? dup 0< abort" Corrupt right alphabet"
    +  l over [] c@ rot r> [] c!
    +;
    +
    +: Decrypt                              ( input output index1 -- index2)
    +  >r swap r@ [] c@ l /alpha where? dup 0< abort" Corrupt left alphabet"
    +  r over [] c@ rot r> [] c!
    +;
    +
    +: chao                                 ( i o xt f --)
    +  s" HXUCZVAMDSLKPEFJRIGTWOBNYQ" l zplace
    +  s" PTLNBQDEOYSFAVZKGJRIHWXUMC" r zplace
    +  t /alpha erase >r                    \ erase temporary string
    +                                       ( i o xt R: f)
    +  r@ if cr ." The left and right alphabets after each permutation:" cr then
    +  >r over r> swap zcount 1- nip >r     ( i o xt R: f len)
    +
    +  0 begin                              ( i o xt 0 R: f len)
    +    r> r@ if l zcount type 2 spaces r zcount type cr then >r
    +    >r 3dup r@ swap execute r> dup r@ <
    +  while                                ( i o xt 0 R: f len)
    +    >r dup PermuteLeft PermuteRight r> 1+
    +  repeat rdrop rdrop drop drop 3drop
    +;
    +
    +: main
    +  s" WELLDONEISBETTERTHANWELLSAID" {i} zplace
    +  {o} /str erase                       \ initialize output string
    +
    +     ." The original plaintext is :"  {i} .list
    +  {i} {o} ['] Encrypt true  chao
    +  cr ." The ciphertext is :"          {o} .list
    +  {o} {i} ['] Decrypt false chao
    +  cr ." The recovered plaintext is :" {i} .list
    +;
    +
    +main
    diff --git a/Task/Chaocipher/Pluto/chaocipher.pluto b/Task/Chaocipher/Pluto/chaocipher.pluto
    new file mode 100644
    index 0000000000..92add48042
    --- /dev/null
    +++ b/Task/Chaocipher/Pluto/chaocipher.pluto
    @@ -0,0 +1,55 @@
    +require "table2"
    +
    +enum chao begin
    +    encrypt,
    +    decrypt
    +end
    +
    +local function exec(text, mode, show_steps)
    +    local len = #text
    +    local left  = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    +    local right = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
    +    local etext = table.rep(len, 0)
    +    local temp  = table.rep(26, "")
    +    for i = 1, len do
    +        if show_steps then print($"{left}  {right}") end
    +        local index
    +        if mode == chao.encrypt then
    +            index = right:find(text[i], 1, true)
    +            etext[i] = left[index]
    +        else
    +            index = left:find(text[i], 1, true)
    +            etext[i] = right[index]
    +        end
    +        if i == len then break end
    +
    +        -- Permute left.
    +        for j = index, 26 do temp[j - index + 1] = left[j] end
    +        for j = 1, index - 1 do temp[27 - index + j] = left[j] end
    +        local store = temp[2]
    +        for j = 3, 14 do temp[j - 1] = temp[j] end
    +        temp[14] = store
    +        left = temp:concat("")
    +
    +        -- Permute right.
    +        for j = index, 26 do temp[j - index + 1] = right[j] end
    +        for j = 1, index - 1 do temp[27 - index + j] = right[j] end
    +        store = temp[1]
    +        for j = 2, 26 do temp[j - 1] = temp[j] end
    +        temp[26] = store
    +        store = temp[3]
    +        for j = 4, 14 do temp[j - 1] = temp[j] end
    +        temp[14] = store
    +        right = temp:concat("")
    +    end
    +    return etext:concat("")
    +end
    +
    +local plain_text = "WELLDONEISBETTERTHANWELLSAID"
    +print($"The original plaintext is : {plain_text}")
    +io.write("\nThe left and right alphabets after each permutation ")
    +print("during encryption are :\n")
    +local cipher_text = exec(plain_text, chao.encrypt, true)
    +print($"\nThe ciphertext is : {cipher_text}")
    +local plain_text2 = exec(cipher_text, chao.decrypt, false)
    +print($"\nThe recovered plaintext is : {plain_text2}")
    diff --git a/Task/Chaocipher/Tcl/chaocipher.tcl b/Task/Chaocipher/Tcl/chaocipher.tcl
    new file mode 100644
    index 0000000000..a0fc593619
    --- /dev/null
    +++ b/Task/Chaocipher/Tcl/chaocipher.tcl
    @@ -0,0 +1,160 @@
    +#!/usr/bin/env  tclsh
    +
    +# Tcl implementation of Chaocipher
    +#    (John F. Byrne, 1918)
    +#
    +# from paper "CHAOCIPHER REVEALED: THE ALGORITHM"
    +#    (Moshe Rubin, 2010)
    +#    http://www.mountainvistasoft.com/chaocipher/ActualChaocipher/Chaocipher-Revealed-Algorithm.pdf
    +#
    +
    +# ============ globals "wheels" ============
    +variable l_key  {HXUCZVAMDSLKPEFJRIGTWOBNYQ}
    +variable r_key  {PTLNBQDEOYSFAVZKGJRIHWXUMC}
    +
    +
    +
    +# ============ procedures ==================
    +
    +
    +# swap range of n letters from end to front
    +proc permute {alpha  n } {
    +
    +    set  A [string range $alpha 0 $n-1 ]
    +    set  B [string range $alpha $n end ]
    +
    +    return "${B}${A}"
    +}
    +
    +
    +# rotate based on key in right alphabet
    +# (permute each by same amnount)
    +proc rotate { left right key } {
    +
    +    set idx [string first $key $right]
    +
    +    set L   [permute $left $idx ]
    +
    +    set R   [permute $right $idx]
    +
    +    return [list $L $R]
    +}
    +
    +
    +# split and rearrange each alphabet
    +# according to recipe
    +proc cycle { left right } {
    +
    +    # (0)(2-13)(1)(14-25)
    +    set l1 [string index $left 0     ]
    +    set l2 [string range $left 2 13  ]
    +    set l3 [string index $left 1     ]
    +    set l4 [string range $left 14 end]
    +
    +    set L [join [list $l1 $l2 $l3 $l4] ""]
    +
    +    # (1-2)(4-14)(3)(15-25)(0)
    +    set r1 [string range $right 1  2  ]
    +    set r2 [string range $right 4  14 ]
    +    set r3 [string index $right 3     ]
    +    set r4 [string range $right 15 end]
    +    set r5 [string index $right 0     ]
    +
    +    set R [join [list $r1 $r2 $r3 $r4 $r5] ""]
    +
    +    return [list $L $R]
    +}
    +
    +
    +# rotate wheels and generate cipher text or
    +# recover plain text
    +proc chao { input left right mode verbose } {
    +
    +    set out {}
    +
    +    set wheels {}
    +
    +    set len [string length $input]
    +
    +    if { $verbose } {
    +	    puts stdout "input\t$input\tLENGTH $len"
    +
    +	    set s [format "%-${len}s\t|\t%-${len}s" $left $right]
    +
    +	    puts stdout "keys:\t$s"
    +
    +	    puts stdout "\ncycled keys:"
    +    }
    +
    +    # string -> list
    +    set input_list [split $input ""]
    +
    +    set count 0
    +    # iterate each letter
    +    foreach letter $input_list {
    +
    +	    incr count
    +	
    +	    if {$mode eq "encrypt" } {
    +	        # encrypt
    +
    +	        # rotate and permute
    +	        set wheels [rotate $left $right $letter]
    +	        lassign $wheels left right
    +
    +	        # ciphered letter to output (left[0])
    +	        lappend out [string index $left 0]
    +	
    +	    } else {
    +
    +	        # decrypt
    +
    +	        # rotate and permute
    +	        set wheels [rotate $right $left $letter]
    +	        lassign $wheels right left
    +
    +	        # deciphered letter to output (right[0])
    +	        lappend out [string index $right 0]
    + 	    }
    +
    +	    # cycle the alphabets
    +	    set cycled  [cycle $left $right]
    +	    lassign $cycled left right
    +	
    +	    if {$verbose} { puts stderr "${count}\t${left}\t|\t${right}" }
    +
    +	
    +    } ; # foreach letter
    +
    +    # list -> string
    +    set out [join $out ""]
    +
    +    return $out
    +}
    +
    +
    +# ============= main =================
    +if { [info script] eq $::argv0 } {
    +
    +    # --------- init ------------------
    +    set left  $l_key
    +    set right $r_key
    +    set plain_text "WELLDONEISBETTERTHANWELLSAID"
    +
    +    # ---------- encipher -------------
    +
    +    set cipher_text [chao $plain_text $left $right encrypt 1]
    +
    +    # ---------- decipher -------------
    +
    +    set decrypted_text [chao $cipher_text $left $right decrypt 0]
    +    # ----------- output --------------
    +
    +    puts stdout "\nplain text:  \t ${plain_text}"
    +    puts stdout "\ncipher text: \t ${cipher_text}"
    +    puts stdout "\ndecrypted:   \t ${decrypted_text}"
    +
    +    return 0
    +}
    +
    +# end
    diff --git a/Task/Chaos-game/Ada/chaos-game.adb b/Task/Chaos-game/Ada/chaos-game.adb
    new file mode 100644
    index 0000000000..fe213c85fc
    --- /dev/null
    +++ b/Task/Chaos-game/Ada/chaos-game.adb
    @@ -0,0 +1,45 @@
    +pragma Ada_2022;
    +with Ada.Numerics;  use Ada.Numerics;
    +with Ada.Numerics.Discrete_Random;
    +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
    +with Easy_Graphics; use Easy_Graphics;
    +
    +procedure Chaos_Game is
    +   Img : Easy_Image := New_Image ((1, 1), (512, 512), WHITE);
    +
    +   procedure Chaos (Image        : in out Easy_Image;
    +                    Vertex_Count : Positive;
    +                    Radius       : Float;
    +                    Iters        : Positive) is
    +      type Vertex_Array is array (1 .. Vertex_Count) of Point;
    +      Vertices : Vertex_Array;
    +      subtype Vertex_Range is Integer range 1 .. Vertex_Count;
    +      package Rand_V is new Ada.Numerics.Discrete_Random (Vertex_Range);
    +      use Rand_V;
    +      Gen : Generator;
    +      Half_X  : constant Integer := X_Last (Image) / 2;
    +      Half_Y  : constant Integer := Y_Last (Image) / 2;
    +      Half_Pi : constant Float   := Float (Pi) / 2.0;
    +      Two_Pi  : constant Float   := Float (Pi) * 2.0;
    +      V       : Integer;
    +      X       : Integer := Half_X;
    +      Y       : Integer := Half_Y;
    +   begin
    +      for V in 1 .. Vertex_Count loop
    +         Vertices (V).X := Half_X + Integer (Float (Half_X) *
    +                           Cos (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count)));
    +         Vertices (V).Y := Half_Y - Integer (Float (Half_Y) *
    +                           Sin (Half_Pi + (Float (V - 1)) * Two_Pi / Float (Vertex_Count)));
    +      end loop;
    +      for I in 1 .. Iters loop
    +         V := Random (Gen);
    +         X := X + Integer (Radius * Float (Vertices (V).X - X));
    +         Y := Y + Integer (Radius * Float (Vertices (V).Y - Y));
    +         Plot (Image, (X, Y), BLACK);
    +      end loop;
    +   end Chaos;
    +
    +begin
    +   Chaos (Img, 3, 0.5, 250_000);
    +   Write_GIF (Img, "chaos_game.gif");
    +end Chaos_Game;
    diff --git a/Task/Chaos-game/EasyLang/chaos-game.easy b/Task/Chaos-game/EasyLang/chaos-game.easy
    index 20f9411330..ae10673f1b 100644
    --- a/Task/Chaos-game/EasyLang/chaos-game.easy
    +++ b/Task/Chaos-game/EasyLang/chaos-game.easy
    @@ -5,7 +5,7 @@ x = randomf * 100
     y = randomf * 100
     for i = 1 to 100000
        grect x y 0.3 0.3
    -   h = random 3
    +   h = random 1 3
        x = (x + x[h]) / 2
        y = (y + y[h]) / 2
     .
    diff --git a/Task/Chaos-game/Emacs-Lisp/chaos-game.el b/Task/Chaos-game/Emacs-Lisp/chaos-game.el
    new file mode 100644
    index 0000000000..0d3a071cba
    --- /dev/null
    +++ b/Task/Chaos-game/Emacs-Lisp/chaos-game.el
    @@ -0,0 +1,52 @@
    +; Chaos game
    +
    +(defun make-array (size)
    +  "Create an empty array with size*size elements."
    +  (setq m-array (make-vector size nil))
    +  (dotimes (i size)
    +    (setf (aref m-array i) (make-vector size 0)))
    +  m-array)
    +
    +(defun chaos-next (p)
    +  "Return the next coordinates."
    +  (let* ((points (list (cons 1 0) (cons -1 0) (cons 0 (sqrt 3))))
    + 	 (v (elt points (random 3)))
    +         (x (car p))
    +         (y (cdr p))
    +         (x2 (car v))
    +         (y2 (cdr v)))
    +      (setq nx (/ (+ x x2) 2.0))
    +      (setq ny (/ (+ y y2) 2.0))
    +      (cons nx ny)))
    +
    +(defun chaos-lines (arr size)
    +  "Turn array into a string for XPM conversion."
    +  (setq all "")
    +  (dotimes (y size)
    +    (setq line "")
    +    (dotimes (x size)
    +      (setq line (concat line (if (= (elt (elt arr y) x) 1) "*" "."))))
    +    (setq all (concat all "\"" line "\",\n")))
    +  all)
    +
    +(defun chaos-show (arr size)
    +  "Convert size*size array to XPM image and show it."
    +  (insert-image (create-image (concat (format "/* XPM */
    +static char * chaos[] = {
    +\"%i %i 2 1\",
    +\".      c #000000\",
    +\"*      c #00ff00\"," size size)
    +    (chaos-lines arr size) "};") 'xpm t)))
    +
    +(defun chaos (size scale max-iter)
    +  "Play the chaos game."
    +  (let ((arr (make-array size))
    +        (p (cons 0 0)))
    +    (dotimes (it max-iter)
    +      (setq p (chaos-next p))
    +      (setq x (round (+ (/ size 2) (* scale (car p)))))
    +      (setq y (round (+ (- size 10) (* -1 scale (cdr p)))))
    +      (setf (elt (elt arr y) x) 1))
    +    (chaos-show arr size)))
    +
    +(chaos 400 180 50000)
    diff --git a/Task/Chaos-game/Uxntal/chaos-game.uxnatl b/Task/Chaos-game/Uxntal/chaos-game.uxnatl
    new file mode 100644
    index 0000000000..13873818ad
    --- /dev/null
    +++ b/Task/Chaos-game/Uxntal/chaos-game.uxnatl
    @@ -0,0 +1,82 @@
    +|00 @System/vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
    +|20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1
    +|c0 @DateTime &year $2 &month $1 &day $1 &hour $1 &minute $1 &second $1 &dotw $1 &doty $2 &isdst $1
    +
    +|00
    +	@State &x $2 &y $2
    +
    +|0100
    +@on-reset ( -> )
    +	.DateTime/minute DEI2 SWP #20 SFT2 lcg/
    +
    +	#0f0f DUP2k
    +	.System/r DEO2
    +	.System/g DEO2
    +	.System/b DEO2
    +
    +	( 256 x 222 fits all three reference points )
    +	#0100 .Screen/width DEO2
    +	#00de .Screen/height DEO2
    +
    +	start-point
    +	.State/x STZ2
    +	.State/y STZ2
    +
    +	;on-frame .Screen/vector DEO2
    +	BRK
    +
    +@on-frame ( -> )
    +	[ LIT2 00 -State/x ] LDZ .Screen/x DEO2
    +	[ LIT2 00 -State/y ] LDZ .Screen/y DEO2
    +	[ LIT2 01 -Screen/pixel ] DEO
    +
    +	next-point
    +	.State/x STZ2
    +	.State/y STZ2
    +	BRK
    +
    +@start-point ( -- y* x* )
    +	( pick a random point in a square )
    +	lcg/next lcg/next
    +	( mirror point if needed to move point to top left triangle )
    +	ADD2k OVR2 GTH2 ?{
    +		#0000 SWP2 SUB2 SWP2
    +		#0000 SWP2 SUB2
    +	}
    +	( skew points so triangle has a point in the bottom middle )
    +	SWP2 OVR2 #01 SFT2 ADD2
    +	( mirror points vertically to make the triangle point up )
    +	STH2 #0000 SWP2 SUB2
    +	( fixed point multiply y by cos 30deg to make it equilateral )
    +	( hi * hi ) OVR #00 SWP #00dd MUL2 STH2
    +	( hi * lo ) SWP #00 SWP #00b4 MUL2 STH2
    +	( lo * hi ) #00 SWP #00dd MUL2
    +	( add low bytes ) STH2r ADD2 #08 SFT2
    +	( add to high product ) STH2r ADD2
    +	STH2r
    +
    +	JMP2r
    +
    +@next-point ( -- y* x* )
    +	( midpoint of previous State and a random corner )
    +	random-corner
    +	#01 SFT2 .State/x LDZ2 #01 SFT2 ADD2
    +	STH2
    +	#01 SFT2 .State/y LDZ2 #01 SFT2 ADD2
    +	STH2r JMP2r
    +
    +@random-corner ( -- y* x* )
    +	( randomly pick one of the three corners )
    +	lcg/next
    +	#0003 DIV2k INC2 MUL2 SUB2 NIP
    +	INC DUP ?{ POP #0000 #8000 JMP2r }
    +	INC DUP ?{ POP #ddb4 #0000 JMP2r }
    +	POP #ddb4 #ffff JMP2r
    +
    +@lcg/ ( seed* -- )
    +	,&State STR2 JMP2r
    +
    +@lcg/next ( -- x* )
    +	[ LIT2 &State $2 ]
    +	#0815 MUL2 #1419 ADD2 DUP2 ,&State STR2
    +	JMP2r
    diff --git a/Task/Character-codes/Ada/character-codes.adb b/Task/Character-codes/Ada/character-codes.adb
    new file mode 100644
    index 0000000000..1ca9ae2042
    --- /dev/null
    +++ b/Task/Character-codes/Ada/character-codes.adb
    @@ -0,0 +1,6 @@
    +with Ada.Text_IO;  use Ada.Text_IO;
    +
    +procedure Char_Code is
    +begin
    +   Put_Line (Character'Val (97) & " =" & Integer'Image (Character'Pos ('a')));
    +end Char_Code;
    diff --git a/Task/Character-codes/Agena/character-codes.agena b/Task/Character-codes/Agena/character-codes.agena
    new file mode 100644
    index 0000000000..a1410f30ad
    --- /dev/null
    +++ b/Task/Character-codes/Agena/character-codes.agena
    @@ -0,0 +1,2 @@
    +print( abs "a" );    # prints the character code of a (97 in ASCII)
    +print( char( 97 ) ); # prints the character corresponding to code 97 ("a" in ASCII)
    diff --git a/Task/Character-codes/ArkScript/character-codes.ark b/Task/Character-codes/ArkScript/character-codes.ark
    new file mode 100644
    index 0000000000..d96abc35c4
    --- /dev/null
    +++ b/Task/Character-codes/ArkScript/character-codes.ark
    @@ -0,0 +1,4 @@
    +(import std.String)
    +
    +(print (string:ord "a"))
    +(print (string:chr 97))
    diff --git a/Task/Character-codes/COBOL/character-codes.cob b/Task/Character-codes/COBOL/character-codes.cob
    new file mode 100644
    index 0000000000..a935bb806c
    --- /dev/null
    +++ b/Task/Character-codes/COBOL/character-codes.cob
    @@ -0,0 +1,9 @@
    +       identification division.
    +       program-id. character-codes.
    +       remarks. COBOL is an ordinal language, first is 1.
    +       remarks. 42nd ASCII code is ")" not, "*".
    +       procedure division.
    +       display function char(42)
    +       display function ord('*')
    +       goback.
    +       end program character-codes.
    diff --git a/Task/Character-codes/Emacs-Lisp/character-codes.el b/Task/Character-codes/Emacs-Lisp/character-codes.el
    new file mode 100644
    index 0000000000..092377d357
    --- /dev/null
    +++ b/Task/Character-codes/Emacs-Lisp/character-codes.el
    @@ -0,0 +1,2 @@
    +(string-to-char "a") ;=> 97
    +(format "%c" 97) ;=> "a"
    diff --git a/Task/Character-codes/Euphoria/character-codes.eu b/Task/Character-codes/Euphoria/character-codes.eu
    new file mode 100644
    index 0000000000..48741c5aba
    --- /dev/null
    +++ b/Task/Character-codes/Euphoria/character-codes.eu
    @@ -0,0 +1,2 @@
    +printf(1,"%d\n", 'a') -- prints "97"
    +printf(1,"%s\n", 97) -- prints "a"
    diff --git a/Task/Character-codes/Haxe/character-codes.hx b/Task/Character-codes/Haxe/character-codes.hx
    new file mode 100644
    index 0000000000..3d1788b91d
    --- /dev/null
    +++ b/Task/Character-codes/Haxe/character-codes.hx
    @@ -0,0 +1,7 @@
    +class Main {
    +    static public function main():Void {
    +        trace("a".code);
    +        trace("∅".code);
    +        trace("🍆".code);
    +    }
    +}
    diff --git a/Task/Character-codes/Odin/character-codes.odin b/Task/Character-codes/Odin/character-codes.odin
    new file mode 100644
    index 0000000000..0acc50a345
    --- /dev/null
    +++ b/Task/Character-codes/Odin/character-codes.odin
    @@ -0,0 +1,11 @@
    +package main
    +
    +import "core:fmt"
    +
    +main :: proc() {
    +	// No difference between chracters and ints
    +    a:int=97
    +    fmt.println(rune(a))
    +    number:int='a'
    +    fmt.println(number)
    +}
    diff --git a/Task/Character-codes/PowerShell/character-codes-1.ps1 b/Task/Character-codes/PowerShell/character-codes-1.ps1
    new file mode 100644
    index 0000000000..ff83d8a73d
    --- /dev/null
    +++ b/Task/Character-codes/PowerShell/character-codes-1.ps1
    @@ -0,0 +1 @@
    +$char = [convert]::toChar(0x2f) #=> /
    diff --git a/Task/Character-codes/PowerShell/character-codes-2.ps1 b/Task/Character-codes/PowerShell/character-codes-2.ps1
    new file mode 100644
    index 0000000000..ef33e7b589
    --- /dev/null
    +++ b/Task/Character-codes/PowerShell/character-codes-2.ps1
    @@ -0,0 +1 @@
    +$char = [char] 'a'
    diff --git a/Task/Character-codes/PowerShell/character-codes-3.ps1 b/Task/Character-codes/PowerShell/character-codes-3.ps1
    new file mode 100644
    index 0000000000..0fa7235522
    --- /dev/null
    +++ b/Task/Character-codes/PowerShell/character-codes-3.ps1
    @@ -0,0 +1 @@
    +$charcode = [int] $char   # => 97
    diff --git a/Task/Character-codes/PowerShell/character-codes-4.ps1 b/Task/Character-codes/PowerShell/character-codes-4.ps1
    new file mode 100644
    index 0000000000..3182e3dde5
    --- /dev/null
    +++ b/Task/Character-codes/PowerShell/character-codes-4.ps1
    @@ -0,0 +1 @@
    +[int] [char] '☺'          # => 9786
    diff --git a/Task/Character-codes/PowerShell/character-codes-5.ps1 b/Task/Character-codes/PowerShell/character-codes-5.ps1
    new file mode 100644
    index 0000000000..a707209b12
    --- /dev/null
    +++ b/Task/Character-codes/PowerShell/character-codes-5.ps1
    @@ -0,0 +1,2 @@
    +[char] 97    # a
    +[char] 9786  # ☺
    diff --git a/Task/Character-codes/Rebol/character-codes.rebol b/Task/Character-codes/Rebol/character-codes.rebol
    new file mode 100644
    index 0000000000..8566b5bd09
    --- /dev/null
    +++ b/Task/Character-codes/Rebol/character-codes.rebol
    @@ -0,0 +1,7 @@
    +print to integer! first "a" ;; == 97
    +print to integer! #"a"      ;; == 97
    +print to binary! "a"        ;; == #{61}
    +print to char! 97           ;; == a
    +print to char! 0#61         ;; == a  ;; available only in Rebol3
    +print #"^(61)"              ;; == a
    +print to-hex #"a"           ;; == 61 ;; since Rebol 3.20.0
    diff --git a/Task/Character-codes/Uiua/character-codes.uiua b/Task/Character-codes/Uiua/character-codes.uiua
    new file mode 100644
    index 0000000000..75f72c71f7
    --- /dev/null
    +++ b/Task/Character-codes/Uiua/character-codes.uiua
    @@ -0,0 +1,2 @@
    +-@\0@a
    ++@\097
    diff --git a/Task/Character-codes/VBScript/character-codes.vbs b/Task/Character-codes/VBScript/character-codes.vbs
    new file mode 100644
    index 0000000000..4be511c69b
    --- /dev/null
    +++ b/Task/Character-codes/VBScript/character-codes.vbs
    @@ -0,0 +1,5 @@
    +'prints a
    +WScript.StdOut.WriteLine Chr(97)
    +
    +'prints 97
    +WScript.StdOut.WriteLine Asc("a")
    diff --git a/Task/Chat-server/Ada/chat-server.adb b/Task/Chat-server/Ada/chat-server.adb
    new file mode 100644
    index 0000000000..1c9f22cabc
    --- /dev/null
    +++ b/Task/Chat-server/Ada/chat-server.adb
    @@ -0,0 +1,85 @@
    +with Ada.Containers.Vectors;
    +with Ada.Command_Line; use Ada.Command_Line;
    +with Ada.Exceptions;   use Ada.Exceptions;
    +with Ada.Text_IO;      use Ada.Text_IO;
    +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
    +with Sockets;          use Sockets;
    +
    +procedure Chat_Server is
    +
    +   package Client_Vectors is new Ada.Containers.Vectors
    +     (Element_Type => Socket_FD, Index_Type => Positive);
    +   All_Clients : Client_Vectors.Vector;
    +
    +   procedure Write (S : String) is
    +      procedure Output (Position : Client_Vectors.Cursor) is
    +         Sock : Socket_FD := Client_Vectors.Element (Position);
    +      begin
    +         Put_Line (Sock, S);
    +      end Output;
    +   begin
    +      All_Clients.Iterate (Output'Access);
    +   end Write;
    +
    +   task type Client_Task is
    +      entry Start (FD : Socket_FD);
    +   end Client_Task;
    +
    +   task body Client_Task is
    +      Sock    : Socket_FD;
    +      Sock_ID : Positive;
    +      Name    : Unbounded_String;
    +   begin
    +      select
    +         accept Start (FD : Socket_FD) do
    +            Sock := FD;
    +         end Start;
    +      or
    +         terminate;
    +      end select;
    +
    +      while Name = Null_Unbounded_String loop
    +         Put (Sock, "Enter Name:");
    +         Name := To_Unbounded_String (Get_Line (Sock));
    +      end loop;
    +      Write (To_String (Name) & " joined.");
    +      All_Clients.Append (Sock);
    +      Sock_ID := All_Clients.Find_Index (Sock);
    +      loop
    +         declare
    +            Input : String := Get_Line (Sock);
    +         begin
    +            Write (To_String (Name) & ": " & Input);
    +         end;
    +      end loop;
    +   exception
    +      when Connection_Closed =>
    +         Put_Line ("Connection closed");
    +         Shutdown (Sock, Both);
    +         All_Clients.Delete (Sock_ID);
    +         Write (To_String (Name) & " left.");
    +   end Client_Task;
    +
    +   Accepting_Socket : Socket_FD;
    +   Incoming_Socket  : Socket_FD;
    +
    +   type Client_Access is access Client_Task;
    +   Dummy : Client_Access;
    +begin
    +   if Argument_Count /= 1 then
    +      Raise_Exception (Constraint_Error'Identity,
    +                       "Usage: " & Command_Name & " port");
    +   end if;
    +   Socket (Accepting_Socket, PF_INET, SOCK_STREAM);
    +   Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1);
    +   Bind (Accepting_Socket, Positive'Value (Argument (1)));
    +   Listen (Accepting_Socket);
    +   loop
    +      Put_Line ("Waiting for new connection");
    +      Accept_Socket (Accepting_Socket, Incoming_Socket);
    +      Put_Line ("New connection acknowledged");
    +
    +      Dummy := new Client_Task;
    +      Dummy.Start (Incoming_Socket);
    +   end loop;
    +end Chat_Server;
    diff --git a/Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.adb b/Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.adb
    new file mode 100644
    index 0000000000..5f2c334950
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Ada/check-input-device-is-a-terminal.adb
    @@ -0,0 +1,11 @@
    +with Ada.Text_IO;          use Ada.Text_IO;
    +with Interfaces.C_Streams; use Interfaces.C_Streams;
    +
    +procedure Test_tty is
    +begin
    +   if Isatty(Fileno(Stdin)) = 0 then
    +      Put_Line(Standard_Error, "stdin is not a tty.");
    +   else
    +      Put_Line(Standard_Error, "stdin is a tty.");
    +   end if;
    +end Test_tty;
    diff --git a/Task/Check-input-device-is-a-terminal/Batch-File/check-input-device-is-a-terminal.bat b/Task/Check-input-device-is-a-terminal/Batch-File/check-input-device-is-a-terminal.bat
    new file mode 100644
    index 0000000000..8fcd2d94e2
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Batch-File/check-input-device-is-a-terminal.bat
    @@ -0,0 +1 @@
    +(timeout /t 0 >nul 2>nul && echo Stdin is a terminal || echo Stdin is not a terminal) 
    +      *> istty, check id fd 0 is a tty
    +      *> Tectonics: cobc -xj istty.cob
    +      *>            echo "test" | ./istty
    +      *>
    +       identification division.
    +       program-id. istty.
    +
    +       data division.
    +       working-storage section.
    +       01 rc usage binary-long.
    +
    +       procedure division.
    +       sample-main.
    +
    +       call "isatty" using by value 0 returning rc
    +       display "fd 0 tty: " rc
    +
    +       call "isatty" using by value 1 returning rc
    +       display "fd 1 tty: " rc upon syserr
    +
    +       call "isatty" using by value 2 returning rc
    +       display "fd 2 tty: " rc
    +
    +       goback.
    +       end program istty.
    diff --git a/Task/Check-input-device-is-a-terminal/Fortran/check-input-device-is-a-terminal.f b/Task/Check-input-device-is-a-terminal/Fortran/check-input-device-is-a-terminal.f
    new file mode 100644
    index 0000000000..d90076c414
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Fortran/check-input-device-is-a-terminal.f
    @@ -0,0 +1,34 @@
    +!
    +!Check input device is a terminal
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +!
    +! This is completely non-standard. It relies on the function isatty(lun)
    +! which is documented as compiler-specific extension to both ifx and Gnu gfortran.
    +!
    +! U.B., January 2026
    +!==============================================================================
    +program checkTTY
    +
    +implicit none
    +
    +integer :: unit
    +logical :: isatty
    +
    +! expect units 5 (standard input)  and 6 (standard output) to be terminals,
    +! unless it redirected to a file
    +! ./checktty will write that units 5 and 6 are Terminals,
    +! ./checktty b.out will write to b.out, and this contains unit 5 is a terminal but unit 6 ism't
    +! ./checktty < a.out >b.out will write to b.out, and both units 5 and 6 are not terminals.
    +!
    +! Check units 1...10 if they are connected to a terminal.
    +do unit=1,10
    +  if (isatty (unit)) then
    +    write (*, '("Unit ", i2, " is a Terminal")') unit
    +  else
    +    write (*, '("Unit ", i2, " is NOT a Terminal")') unit
    +  endif
    +enddo
    +
    +end program checkTTY
    diff --git a/Task/Check-input-device-is-a-terminal/Janet/check-input-device-is-a-terminal.janet b/Task/Check-input-device-is-a-terminal/Janet/check-input-device-is-a-terminal.janet
    new file mode 100644
    index 0000000000..f0fb90c650
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Janet/check-input-device-is-a-terminal.janet
    @@ -0,0 +1,3 @@
    +(if (os/isatty stdin)
    +  (print "The input device is a terminal.")
    +  (print "The input device is not a terminal."))
    diff --git a/Task/Check-input-device-is-a-terminal/Pluto/check-input-device-is-a-terminal-1.pluto b/Task/Check-input-device-is-a-terminal/Pluto/check-input-device-is-a-terminal-1.pluto
    new file mode 100644
    index 0000000000..aa5db3f39b
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Pluto/check-input-device-is-a-terminal-1.pluto
    @@ -0,0 +1,5 @@
    +os.execute("test -t 0 ; echo $? > tmp")
    +os.sleep(1)
    +local res = io.contents("tmp"):rstrip()
    +print($"Input device is a terminal? {res == "0"}")
    +os.remove("tmp")
    diff --git a/Task/Check-input-device-is-a-terminal/Pluto/check-input-device-is-a-terminal-2.pluto b/Task/Check-input-device-is-a-terminal/Pluto/check-input-device-is-a-terminal-2.pluto
    new file mode 100644
    index 0000000000..d620f9df74
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Pluto/check-input-device-is-a-terminal-2.pluto
    @@ -0,0 +1,6 @@
    +local ffi = require "pluto:ffi"
    +local lib = ffi.open("libc.so.6")
    +lib:cdef[[ int isatty(int fd); ]]
    +
    +local res = lib.isatty(0)
    +print($"Input device is a terminal? {res == 1}")
    diff --git a/Task/Check-input-device-is-a-terminal/Rebol/check-input-device-is-a-terminal.rebol b/Task/Check-input-device-is-a-terminal/Rebol/check-input-device-is-a-terminal.rebol
    new file mode 100644
    index 0000000000..6fc98f44e3
    --- /dev/null
    +++ b/Task/Check-input-device-is-a-terminal/Rebol/check-input-device-is-a-terminal.rebol
    @@ -0,0 +1,5 @@
    +either system/options/flags/cgi [
    +    print "CGI mode - no terminal"
    +    ;; get input data
    +    probe data: read system/ports/input
    +][  print "not CGI mode" ]
    diff --git a/Task/Check-output-device-is-a-terminal/Ada/check-output-device-is-a-terminal.adb b/Task/Check-output-device-is-a-terminal/Ada/check-output-device-is-a-terminal.adb
    new file mode 100644
    index 0000000000..25c923d819
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Ada/check-output-device-is-a-terminal.adb
    @@ -0,0 +1,11 @@
    +with Ada.Text_IO;          use Ada.Text_IO;
    +with Interfaces.C_Streams; use Interfaces.C_Streams;
    +
    +procedure Test_tty is
    +begin
    +   if Isatty(Fileno(Stdout)) = 0 then
    +      Put_Line(Standard_Error, "stdout is not a tty.");
    +   else
    +      Put_Line(Standard_Error, "stdout is a tty.");
    +   end if;
    +end Test_tty;
    diff --git a/Task/Check-output-device-is-a-terminal/Applesoft-BASIC/check-output-device-is-a-terminal.basic b/Task/Check-output-device-is-a-terminal/Applesoft-BASIC/check-output-device-is-a-terminal.basic
    new file mode 100644
    index 0000000000..04d01ca899
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Applesoft-BASIC/check-output-device-is-a-terminal.basic
    @@ -0,0 +1 @@
    +?MID$("GRAPHICSTEXT",1+(PEEK(49178)>127)*8,8)" MODE";
    diff --git a/Task/Check-output-device-is-a-terminal/Batch-File/check-output-device-is-a-terminal.bat b/Task/Check-output-device-is-a-terminal/Batch-File/check-output-device-is-a-terminal.bat
    new file mode 100644
    index 0000000000..6e3bcd172c
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Batch-File/check-output-device-is-a-terminal.bat
    @@ -0,0 +1,7 @@
    +@echo off
    +setlocal enableextensions enabledelayedexpansion
    +for /f %%a in ('copy /z "%~f0" nul') do set "CR=%%a"
    +(set check=^>con set/p"=Stdout is redirected^!CR^!"^&set/p"=Stdout is not redirected")
    +con echo:
    +&2 (%check:out=err%)
    diff --git a/Task/Check-output-device-is-a-terminal/COBOL/check-output-device-is-a-terminal.cob b/Task/Check-output-device-is-a-terminal/COBOL/check-output-device-is-a-terminal.cob
    new file mode 100644
    index 0000000000..86d0565c39
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/COBOL/check-output-device-is-a-terminal.cob
    @@ -0,0 +1,26 @@
    +      *>
    +      *> istty, check id fd 0 is a tty
    +      *> Tectonics: cobc -xj istty.cob
    +      *>            echo "test" | ./istty
    +      *>
    +       identification division.
    +       program-id. istty.
    +
    +       data division.
    +       working-storage section.
    +       01 rc usage binary-long.
    +
    +       procedure division.
    +       sample-main.
    +
    +       call "isatty" using by value 0 returning rc
    +       display "fd 0 tty: " rc
    +
    +       call "isatty" using by value 1 returning rc
    +       display "fd 1 tty: " rc upon syserr
    +
    +       call "isatty" using by value 2 returning rc
    +       display "fd 2 tty: " rc
    +
    +       goback.
    +       end program istty.
    diff --git a/Task/Check-output-device-is-a-terminal/Fortran/check-output-device-is-a-terminal.f b/Task/Check-output-device-is-a-terminal/Fortran/check-output-device-is-a-terminal.f
    new file mode 100644
    index 0000000000..fac994b759
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Fortran/check-output-device-is-a-terminal.f
    @@ -0,0 +1,16 @@
    +program check_terminal
    +  use iso_c_binding
    +  implicit none
    +
    +  logical :: is_terminal
    +
    +  ! Check if standard output (unit 6) is a terminal
    +  is_terminal = isatty(6)
    +
    +  if (is_terminal) then
    +     print *, 'Standard output is a terminal.'
    +  else
    +     print *, 'Standard output is not a terminal (e.g., redirected to a file).'
    +  end if
    +
    +end program check_terminal
    diff --git a/Task/Check-output-device-is-a-terminal/Janet/check-output-device-is-a-terminal.janet b/Task/Check-output-device-is-a-terminal/Janet/check-output-device-is-a-terminal.janet
    new file mode 100644
    index 0000000000..72335c5e20
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Janet/check-output-device-is-a-terminal.janet
    @@ -0,0 +1,3 @@
    +(if (os/isatty)
    +  (print "The output device is a terminal.")
    +  (print "The output device is not a terminal."))
    diff --git a/Task/Check-output-device-is-a-terminal/Java/check-output-device-is-a-terminal.java b/Task/Check-output-device-is-a-terminal/Java/check-output-device-is-a-terminal.java
    new file mode 100644
    index 0000000000..a76c810fbb
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Java/check-output-device-is-a-terminal.java
    @@ -0,0 +1,11 @@
    +import java.io.Console;
    +
    +public class Main {
    +    public static void main(String[] args) {
    +        if (System.console() != null) {
    +            System.out.println("stdout is a terminal");
    +        } else {
    +            System.out.println("stdout is not a terminal");
    +        }
    +    }
    +}
    diff --git a/Task/Check-output-device-is-a-terminal/Pluto/check-output-device-is-a-terminal-1.pluto b/Task/Check-output-device-is-a-terminal/Pluto/check-output-device-is-a-terminal-1.pluto
    new file mode 100644
    index 0000000000..41947c4e04
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Pluto/check-output-device-is-a-terminal-1.pluto
    @@ -0,0 +1,5 @@
    +os.execute("test -t 1 ; echo $? > tmp")
    +os.sleep(1)
    +local res = io.contents("tmp"):rstrip()
    +print($"Output device is a terminal? {res == "0"}")
    +os.remove("tmp")
    diff --git a/Task/Check-output-device-is-a-terminal/Pluto/check-output-device-is-a-terminal-2.pluto b/Task/Check-output-device-is-a-terminal/Pluto/check-output-device-is-a-terminal-2.pluto
    new file mode 100644
    index 0000000000..ab0edb2811
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Pluto/check-output-device-is-a-terminal-2.pluto
    @@ -0,0 +1,6 @@
    +local ffi = require "pluto:ffi"
    +local lib = ffi.open(os.platform == "macos" ? "libSystem.B.dylib" : "libc.so.6")
    +lib:cdef[[ int isatty(int fd); ]]
    +
    +local res = lib.isatty(1)
    +print($"Output device is a terminal? {res == 1}")
    diff --git a/Task/Check-output-device-is-a-terminal/Uiua/check-output-device-is-a-terminal.uiua b/Task/Check-output-device-is-a-terminal/Uiua/check-output-device-is-a-terminal.uiua
    new file mode 100644
    index 0000000000..ca86bdd9c6
    --- /dev/null
    +++ b/Task/Check-output-device-is-a-terminal/Uiua/check-output-device-is-a-terminal.uiua
    @@ -0,0 +1,2 @@
    +&runc "tty" # run and capture output
    +&runi "tty" # run and wait
    diff --git a/Task/Check-that-file-exists/Ada/check-that-file-exists-1.adb b/Task/Check-that-file-exists/Ada/check-that-file-exists-1.adb
    new file mode 100644
    index 0000000000..9fbc024932
    --- /dev/null
    +++ b/Task/Check-that-file-exists/Ada/check-that-file-exists-1.adb
    @@ -0,0 +1,17 @@
    +with Ada.Text_IO; use Ada.Text_IO;
    +
    +procedure File_Exists is
    +   function Does_File_Exist (Name : String) return Boolean is
    +      The_File : Ada.Text_IO.File_Type;
    +   begin
    +      Open (The_File, In_File, Name);
    +      Close (The_File);
    +      return True;
    +   exception
    +      when Name_Error =>
    +         return False;
    +   end Does_File_Exist;
    +begin
    +   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
    +   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
    +end File_Exists;
    diff --git a/Task/Check-that-file-exists/Ada/check-that-file-exists-2.adb b/Task/Check-that-file-exists/Ada/check-that-file-exists-2.adb
    new file mode 100644
    index 0000000000..fd3bb4384b
    --- /dev/null
    +++ b/Task/Check-that-file-exists/Ada/check-that-file-exists-2.adb
    @@ -0,0 +1,20 @@
    +with Ada.Text_IO; use Ada.Text_IO;
    +with Ada.Directories; use Ada.Directories;
    +
    +procedure File_Exists is
    +   procedure Print_File_Exist (Name : String) is
    +   begin
    +      Put_Line ("Does " & Name & " exist? " &
    +                  Boolean'Image (Exists (Name)));
    +   end Print_File_Exist;
    +   procedure Print_Dir_Exist (Name : String) is
    +   begin
    +      Put_Line ("Does directory " & Name & " exist? " &
    +                  Boolean'Image (Exists (Name) and then Kind (Name) = Directory));
    +   end Print_Dir_Exist;
    +begin
    +   Print_File_Exist ("input.txt" );
    +   Print_File_Exist ("/input.txt");
    +   Print_Dir_Exist ("docs");
    +   Print_Dir_Exist ("/docs");
    +end File_Exists;
    diff --git a/Task/Check-that-file-exists/COBOL/check-that-file-exists.cob b/Task/Check-that-file-exists/COBOL/check-that-file-exists.cob
    new file mode 100644
    index 0000000000..7337ccb5f1
    --- /dev/null
    +++ b/Task/Check-that-file-exists/COBOL/check-that-file-exists.cob
    @@ -0,0 +1,70 @@
    +       identification division.
    +       program-id. check-file-exist.
    +
    +       environment division.
    +       configuration section.
    +       repository.
    +           function all intrinsic.
    +
    +       data division.
    +       working-storage section.
    +       01 skip                 pic 9 value 2.
    +       01 file-name.
    +          05 value "/output.txt".
    +       01 dir-name.
    +          05 value "/docs/".
    +       01 unusual-name.
    +          05 value "Abdu'l-Bahá.txt".
    +
    +       01 test-name            pic x(256).
    +
    +       01 file-handle          usage binary-long.
    +       01 file-info.
    +          05 file-size         pic x(8) comp-x.
    +          05 file-date.
    +             10 file-day       pic x comp-x.
    +             10 file-month     pic x comp-x.
    +             10 file-year      pic xx comp-x.
    +          05 file-time.
    +             10 file-hours     pic x comp-x.
    +             10 file-minutes   pic x comp-x.
    +             10 file-seconds   pic x comp-x.
    +             10 file-hundredths  pic x comp-x.
    +
    +       procedure division.
    +       files-main.
    +
    +      *> check in current working dir
    +       move file-name(skip:) to test-name
    +       perform check-file
    +
    +       move dir-name(skip:) to test-name
    +       perform check-file
    +
    +       move unusual-name to test-name
    +       perform check-file
    +
    +      *> check in root dir
    +       move 1 to skip
    +       move file-name(skip:) to test-name
    +       perform check-file
    +
    +       move dir-name(skip:) to test-name
    +       perform check-file
    +
    +       goback.
    +
    +       check-file.
    +       call "CBL_CHECK_FILE_EXIST" using test-name file-info
    +       if return-code equal zero then
    +           display test-name(1:32) ": size " file-size ", "
    +                   file-year "-" file-month "-" file-day space
    +                   file-hours ":" file-minutes ":" file-seconds "."
    +                   file-hundredths
    +       else
    +           display "error: CBL_CHECK_FILE_EXIST " return-code space
    +                   trim(test-name)
    +       end-if
    +       .
    +
    +       end program check-file-exist.
    diff --git a/Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.el b/Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.el
    new file mode 100644
    index 0000000000..93c74c0e76
    --- /dev/null
    +++ b/Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.el
    @@ -0,0 +1,4 @@
    +(file-exists-p "input.txt")
    +(file-directory-p "docs")
    +(file-exists-p "/input.txt")
    +(file-directory-p "/docs")
    diff --git a/Task/Check-that-file-exists/Euphoria/check-that-file-exists.eu b/Task/Check-that-file-exists/Euphoria/check-that-file-exists.eu
    new file mode 100644
    index 0000000000..1925397350
    --- /dev/null
    +++ b/Task/Check-that-file-exists/Euphoria/check-that-file-exists.eu
    @@ -0,0 +1,22 @@
    +include file.e
    +
    +procedure ensure_exists(sequence name)
    +    object x
    +    sequence s
    +    x = dir(name)
    +    if sequence(x) then
    +        if find('d',x[1][D_ATTRIBUTES]) then
    +            s = "directory"
    +        else
    +            s = "file"
    +        end if
    +        printf(1,"%s %s exists.\n",{name,s})
    +    else
    +        printf(1,"%s does not exist.\n",{name})
    +    end if
    +end procedure
    +
    +ensure_exists("input.txt")
    +ensure_exists("docs")
    +ensure_exists("/input.txt")
    +ensure_exists("/docs")
    diff --git a/Task/Check-that-file-exists/Phix/check-that-file-exists.phix b/Task/Check-that-file-exists/Phix/check-that-file-exists.phix
    index 1479c218fe..61580b6799 100644
    --- a/Task/Check-that-file-exists/Phix/check-that-file-exists.phix
    +++ b/Task/Check-that-file-exists/Phix/check-that-file-exists.phix
    @@ -1,17 +1,15 @@
    -(notonline)-->
    - without js -- (file i/o)
    - procedure check(string name)
    -     bool bExists = file_exists(name),
    -          bDir = get_file_type(name)=FILETYPE_DIRECTORY
    -     string exists = iff(bExists?"exists":"does not exist"),
    -            dfs = iff(bExists?iff(bDir?"directory ":"file "):"")
    -     printf(1,"%s%s %s.\n",{dfs,name,exists})
    - end procedure
    +without js -- (file i/o)
    +procedure check(string name)
    +    bool bExists = file_exists(name),
    +         bDir = get_file_type(name)=FILETYPE_DIRECTORY
    +    string exists = iff(bExists?"exists":"does not exist"),
    +           dfs = iff(bExists?iff(bDir?"directory ":"file "):"")
    +    printf(1,"%s%s %s.\n",{dfs,name,exists})
    +end procedure
     
    - check("input.txt")
    - check("docs")
    - check("/input.txt")
    - check("/docs")
    - check("/pagefile.sys")
    - check("/Program Files (x86)")
    - list of strings
    +fcn ceToChineseZodiac(ce_year){ // --> list of strings
        # encoding: utf-8
        var [const] pinyin=SD(  // create some static variables, SD is small fixed dictionary
          "甲","jiă",  "乙","yĭ",  "丙","bĭng", "丁","dīng", "戊","wù", "己","jĭ",
    @@ -11,7 +11,7 @@ fcn ceToChineseZodiac(ce_year){	// --> list of strings
        celestial  =T("甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"),
        terrestrial=T("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"),
        animals    =T("Rat",   "Ox",   "Tiger",  "Rabbit",  "Dragon", "Snake",
    -		 "Horse", "Goat", "Monkey", "Rooster", "Dog",    "Pig"),
    +       "Horse", "Goat", "Monkey", "Rooster", "Dog",    "Pig"),
        elements   =T("Wood", "Fire", "Earth", "Metal", "Water"),
        aspects    =T("yang","yin"),
        ;
    @@ -28,5 +28,5 @@ fcn ceToChineseZodiac(ce_year){	// --> list of strings
        branch_han,branch_pinyin := terrestrial[branch_number], pinyin[branch_han];
     
        return(stem_han,branch_han,
    -	  stem_pinyin,branch_pinyin, element,animal,aspect)
    +     stem_pinyin,branch_pinyin, element,animal,aspect)
     }
    diff --git a/Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.adb b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.adb
    new file mode 100644
    index 0000000000..84bcaf0a47
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-1.adb
    @@ -0,0 +1,9 @@
    +with Ada.Numerics.Generic_Real_Arrays;
    +generic
    +   with package Matrix is new Ada.Numerics.Generic_Real_Arrays (<>);
    +package Decomposition is
    +
    +   -- decompose a square matrix A by A = L * Transpose (L)
    +   procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix);
    +
    +end Decomposition;
    diff --git a/Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.adb b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.adb
    new file mode 100644
    index 0000000000..f37c631081
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-2.adb
    @@ -0,0 +1,33 @@
    +with Ada.Numerics.Generic_Elementary_Functions;
    +
    +package body Decomposition is
    +   package Math is new Ada.Numerics.Generic_Elementary_Functions
    +     (Matrix.Real);
    +
    +   procedure Decompose (A : Matrix.Real_Matrix; L : out Matrix.Real_Matrix) is
    +      use type Matrix.Real_Matrix, Matrix.Real;
    +      Order : constant Positive := A'Length (1);
    +      S     : Matrix.Real;
    +   begin
    +      L := (others => (others => 0.0));
    +      for I in 0 .. Order - 1 loop
    +         for K in 0 .. I loop
    +            S := 0.0;
    +            for J in 0 .. K - 1 loop
    +               S := S +
    +                 L (L'First (1) + I, L'First (2) + J) *
    +                 L (L'First (1) + K, L'First (2) + J);
    +            end loop;
    +            -- diagonals
    +            if K = I then
    +               L (L'First (1) + K, L'First (2) + K) :=
    +                 Math.Sqrt (A (A'First (1) + K, A'First (2) + K) - S);
    +            else
    +               L (L'First (1) + I, L'First (2) + K) :=
    +                 1.0 / L (L'First (1) + K, L'First (2) + K) *
    +                 (A (A'First (1) + I, A'First (2) + K) - S);
    +            end if;
    +         end loop;
    +      end loop;
    +   end Decompose;
    +end Decomposition;
    diff --git a/Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.adb b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.adb
    new file mode 100644
    index 0000000000..1f504b2c61
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/Ada/cholesky-decomposition-3.adb
    @@ -0,0 +1,45 @@
    +with Ada.Numerics.Real_Arrays;
    +with Ada.Text_IO;
    +with Decomposition;
    +procedure Decompose_Example is
    +   package Real_Decomposition is new Decomposition
    +     (Matrix => Ada.Numerics.Real_Arrays);
    +
    +   package Real_IO is new Ada.Text_IO.Float_IO (Float);
    +
    +   procedure Print (M : Ada.Numerics.Real_Arrays.Real_Matrix) is
    +   begin
    +      for Row in M'Range (1) loop
    +         for Col in M'Range (2) loop
    +            Real_IO.Put (M (Row, Col), 4, 3, 0);
    +         end loop;
    +         Ada.Text_IO.New_Line;
    +      end loop;
    +   end Print;
    +
    +   Example_1 : constant Ada.Numerics.Real_Arrays.Real_Matrix :=
    +     ((25.0, 15.0, -5.0),
    +      (15.0, 18.0, 0.0),
    +      (-5.0, 0.0, 11.0));
    +   L_1 : Ada.Numerics.Real_Arrays.Real_Matrix (Example_1'Range (1),
    +                                               Example_1'Range (2));
    +   Example_2 : constant Ada.Numerics.Real_Arrays.Real_Matrix :=
    +     ((18.0, 22.0, 54.0, 42.0),
    +      (22.0, 70.0, 86.0, 62.0),
    +      (54.0, 86.0, 174.0, 134.0),
    +      (42.0, 62.0, 134.0, 106.0));
    +   L_2 : Ada.Numerics.Real_Arrays.Real_Matrix (Example_2'Range (1),
    +                                               Example_2'Range (2));
    +begin
    +   Real_Decomposition.Decompose (A => Example_1,
    +                                 L => L_1);
    +   Real_Decomposition.Decompose (A => Example_2,
    +                                 L => L_2);
    +   Ada.Text_IO.Put_Line ("Example 1:");
    +   Ada.Text_IO.Put_Line ("A:"); Print (Example_1);
    +   Ada.Text_IO.Put_Line ("L:"); Print (L_1);
    +   Ada.Text_IO.New_Line;
    +   Ada.Text_IO.Put_Line ("Example 2:");
    +   Ada.Text_IO.Put_Line ("A:"); Print (Example_2);
    +   Ada.Text_IO.Put_Line ("L:"); Print (L_2);
    +end Decompose_Example;
    diff --git a/Task/Cholesky-decomposition/Excel/cholesky-decomposition.excel b/Task/Cholesky-decomposition/Excel/cholesky-decomposition.excel
    new file mode 100644
    index 0000000000..1586be05f1
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/Excel/cholesky-decomposition.excel
    @@ -0,0 +1,38 @@
    +=LAMBDA(A,
    + LET(
    +  r, ROWS(A),
    +  sqa, SQRT(INDEX(A,1,1)),
    +  IF(
    +    r=1,
    +    sqa,
    +    REDUCE(
    +      VSTACK(sqa, DROP(TAKE(A,,1),1)/sqa),
    +      SEQUENCE(r-1,,2),
    +      LAMBDA(s, t,
    +        LET(
    +          diag, SQRT(INDEX(A,t,t) - SUMSQ(INDEX(s,t))),
    +          HSTACK(
    +            s,
    +            VSTACK(
    +              EXPAND(0,t-1,1,0),
    +              IF(
    +                t=r,
    +                diag,
    +                REDUCE(
    +                  diag,
    +                  SEQUENCE(r-t,1,t+1),
    +                  LAMBDA(x,y,
    +                    VSTACK(
    +                      x,
    +                      (INDEX(A,y,t) - SUM(INDEX(s,t)*INDEX(s,y))) / diag
    +                    )
    +                  )
    +                )
    +              )
    +            )
    +          )
    +        )
    +      )
    +    )
    +  )
    +)
    diff --git a/Task/Cholesky-decomposition/Pluto/cholesky-decomposition.pluto b/Task/Cholesky-decomposition/Pluto/cholesky-decomposition.pluto
    new file mode 100644
    index 0000000000..5a31f92f26
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/Pluto/cholesky-decomposition.pluto
    @@ -0,0 +1,21 @@
    +require "matrix"
    +
    +local arrays = {
    +    { {25, 15, -5},
    +      {15, 18,  0},
    +      {-5,  0, 11} },
    +
    +    { {18, 22,  54,  42},
    +      {22, 70,  86,  62},
    +      {54, 86, 174, 134},
    +      {42, 62, 134, 106} }
    +}
    +
    +for arrays as array do
    +    local m = matrix.from(array)
    +    print("Original:")
    +    print(m)
    +    print("\nLower Cholesky factor:")
    +    print(m:cholesky():format("%8.5f"))
    +    print()
    +end
    diff --git a/Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.ps1 b/Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.ps1
    new file mode 100644
    index 0000000000..1ade9884aa
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/PowerShell/cholesky-decomposition.ps1
    @@ -0,0 +1,51 @@
    +function cholesky ($a) {
    +    $l = @()
    +    if ($a) {
    +        $n = $a.count
    +        $end = $n - 1
    +        $l = 1..$n | foreach {$row = @(0) * $n; ,$row}
    +        foreach ($k in 0..$end) {
    +            $m = $k - 1
    +            $sum = 0
    +            if(0 -lt $k) {
    +                foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]}
    +            }
    +            $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum)
    +            if ($k -lt $end) {
    +                foreach ($i in ($k+1)..$end) {
    +                    $sum = 0
    +                    if (0 -lt $k) {
    +                        foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]}
    +                    }
    +                    $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k]
    +                }
    +            }
    +        }
    +    }
    +    $l
    +}
    +
    +function show($a) {$a | foreach {"$_"}}
    +
    +$a1 = @(
    +@(25, 15, -5),
    +@(15, 18, 0),
    +@(-5, 0, 11)
    +)
    +"a1 ="
    +show $a1
    +""
    +"l1 ="
    +show (cholesky $a1)
    +""
    +$a2 = @(
    +@(18, 22, 54, 42),
    +@(22, 70, 86, 62),
    +@(54, 86, 174, 134),
    +@(42, 62, 134, 106)
    +)
    +"a2 ="
    +show $a2
    +""
    +"l2 ="
    +show (cholesky $a2)
    diff --git a/Task/Cholesky-decomposition/Scheme/cholesky-decomposition.scm b/Task/Cholesky-decomposition/Scheme/cholesky-decomposition.scm
    new file mode 100644
    index 0000000000..fbe516a678
    --- /dev/null
    +++ b/Task/Cholesky-decomposition/Scheme/cholesky-decomposition.scm
    @@ -0,0 +1,55 @@
    +(import srfi/231)
    +
    +(define (Cholesky A)
    +  ;; Assumes the domain of A is [0,n)\\times [0,n)
    +  (let ((n  (interval-upper-bound (array-domain A) 0))
    +        (A_ (array-getter A))
    +        (A! (array-setter A)))
    +    (do ((i 0 (+ i 1)))
    +        ((= i n) A)
    +      (let* ((pivot (sqrt (A_ i i)))
    +             (column/row-domain
    +              ;; both will be one-dimensional
    +              (make-interval (vector (+ i 1)) (vector n)))
    +             (column
    +              ;; the column below the (i,i) entry
    +              (specialized-array-share A
    +                                       column/row-domain
    +                                       (lambda (k) (values k i))))
    +             (row
    +              ;; the row to the right of the (i,i) entry
    +              (specialized-array-share A
    +                                       column/row-domain
    +                                       (lambda (k) (values i k))))
    +             (subarray
    +              ;; the subarray to the right and below the (i,i) entry
    +              (array-extract A (make-interval (vector (+ i 1) (+ i 1)) (vector n n)))))
    +        ;; set diagonal value
    +        (A! pivot i i)
    +        ;; compute multipliers
    +        (array-assign! column (array-map (lambda (x) (/ x pivot)) column))
    +        ;; zero the rest of the ith row, preserving exactness
    +        (array-assign! row (make-array column/row-domain
    +                                       ;; a zero with the same exactness as pivot
    +                                       (lambda (j) (- pivot pivot))))
    +        ;; subtract the outer product of i'th
    +        ;; row and column from the subarray
    +        (array-assign! subarray
    +                       (array-map -
    +                                  subarray
    +                                  (array-outer-product * column column)))))))
    +
    +(define Example-1
    +  (list*->array 2 '((25 15 -5)
    +                    (15 18  0)
    +                    (-5  0 11))))
    +
    +(define Example-2
    +  (list*->array 2 '((18 22 54 42)
    +                    (22 70 86 62)
    +                    (54 86 174 134)
    +                    (42 62 134 106))))
    +
    +(pretty-print (array->list* (Cholesky Example-1)))
    +(newline)
    +(pretty-print (array->list* (Cholesky Example-2)))
    diff --git a/Task/Chowla-numbers/Ada/chowla-numbers.adb b/Task/Chowla-numbers/Ada/chowla-numbers.adb
    new file mode 100644
    index 0000000000..4f48ba270c
    --- /dev/null
    +++ b/Task/Chowla-numbers/Ada/chowla-numbers.adb
    @@ -0,0 +1,70 @@
    +with Ada.Text_IO;
    +
    +procedure Chowla_Numbers is
    +
    +   function Chowla (N : Positive) return Natural is
    +      Sum : Natural  := 0;
    +      I   : Positive := 2;
    +      J   : Positive;
    +   begin
    +      while I * I <= N loop
    +         if N mod I = 0 then
    +            J   := N / I;
    +            Sum := Sum + I + (if I = J then 0 else J);
    +            end if;
    +            I := I + 1;
    +      end loop;
    +      return Sum;
    +   end Chowla;
    +
    +   procedure Put_37_First is
    +      use Ada.Text_IO;
    +   begin
    +      for A in Positive range 1 .. 37 loop
    +         Put_Line ("chowla(" & A'Image & ") = " & Chowla (A)'Image);
    +      end loop;
    +   end Put_37_First;
    +
    +   procedure Put_Prime is
    +      use Ada.Text_IO;
    +      Count : Natural  := 0;
    +      Power : Positive := 100;
    +   begin
    +      for N in Positive range 2 .. 10_000_000 loop
    +         if Chowla (N) = 0 then
    +            Count := Count + 1;
    +         end if;
    +         if N mod Power = 0 then
    +            Put_Line ("There are " & Count'Image & " primes < " & Power'Image);
    +            Power := Power * 10;
    +         end if;
    +      end loop;
    +   end Put_Prime;
    +
    +   procedure Put_Perfect is
    +      use Ada.Text_IO;
    +      Count : Natural  := 0;
    +      Limit : constant := 350_000_000;
    +      K     : Natural := 2;
    +      Kk    : Natural := 3;
    +      P     : Natural;
    +   begin
    +      loop
    +         P := K * Kk;
    +         exit when P > Limit;
    +
    +         if Chowla (P) = P - 1 then
    +            Put_Line (P'Image & " is a perfect number");
    +            Count := Count + 1;
    +         end if;
    +         K  := Kk + 1;
    +         Kk := Kk + K;
    +      end loop;
    +      Put_Line ("There are " & Count'Image & " perfect numbers < " & Limit'Image);
    +   end Put_Perfect;
    +
    +begin
    +   Put_37_First;
    +   Put_Prime;
    +   Put_Perfect;
    +end Chowla_Numbers;
    diff --git a/Task/Chowla-numbers/Agena/chowla-numbers.agena b/Task/Chowla-numbers/Agena/chowla-numbers.agena
    new file mode 100644
    index 0000000000..f483192c9a
    --- /dev/null
    +++ b/Task/Chowla-numbers/Agena/chowla-numbers.agena
    @@ -0,0 +1,57 @@
    +scope # find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 )
    +
    +    # returns the divisor sums of [1 n], the sums exclude 1 and n
    +    local proc sumDivisors( n :: number ) :: sequence
    +        local constant sums := seq();
    +        for i to n do sums[ i ] := 0 od;
    +        for i from 2 to n do
    +            for j from i + i to n by i do sums[ j ] +:= i od
    +        od;
    +        return sums
    +    end;
    +
    +    local constant ds := sumDivisors( 10_000_000 );
    +
    +    local proc chowla( n :: number ) :: number     # returns the Chowla number of n
    +        local sum := 0;
    +        if n > 0 then
    +            if n <= size ds then
    +                sum := ds[ n ]
    +            else
    +                for i from 2 while i * i <= n do
    +                    if n mod i = 0 then
    +                        local constant j := n \ i;
    +                        sum +:= i + if i = j then 0 else j fi
    +                    fi
    +                od
    +            fi
    +        fi;
    +        return sum
    +    end;
    +
    +    # first 37 chowla numbers
    +    for n to 37 do printf( "chowla(%d) = %d\n", n, chowla( n ) ) od;
    +
    +    # number of primes up to 10_000_000
    +    local count, power := 0, 100;
    +    for n from 2 to 10_000_000 do
    +        if chowla( n ) = 0 then count +:= 1 fi;
    +        if n mod power = 0 then
    +            printf( "There are %6d primes < %d\n", count, power );
    +            power *:= 10
    +        fi
    +    od;
    +
    +    # perfect numbers to 35_000_000
    +    local constant perfectMax := 35_000_000;
    +    count := 0;
    +    local k, kk, p := 2, 3, 6; # p is k * kk;
    +    while p <= perfectMax do
    +        if chowla( p ) = p - 1 then
    +            printf( "        %8d is a perfect number\n", p );
    +            count +:= 1
    +        fi;
    +        k := kk + 1; kk +:= k; p := k * kk
    +    od;
    +    printf( "There are %d perfect numbers < %d\n", count, perfectMax )
    +end
    diff --git a/Task/Chowla-numbers/Fennel/chowla-numbers.fennel b/Task/Chowla-numbers/Fennel/chowla-numbers.fennel
    new file mode 100644
    index 0000000000..5bfb4bd8c4
    --- /dev/null
    +++ b/Task/Chowla-numbers/Fennel/chowla-numbers.fennel
    @@ -0,0 +1,61 @@
    +(do ;;; find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 )
    +
    +    (fn sum-divisors [n]
    +        (local sums {})
    +        (for [i 1 n] (tset sums i 0))
    +        (for [i 2 n]
    +             (for [j (+ i i) n i] (tset sums j (+ (. sums j) i)))
    +        )
    +        sums
    +    )
    +
    +    (local ds (sum-divisors 10_000_000))
    +
    +    (fn chowla [n]         ; returns the Chowla number of n
    +        (var sum 0)
    +        (when (> n 0)
    +              (if (<= n (length ds))
    +                  (set sum (. ds n))
    +              ;else
    +                  (for [i 2 (math.floor (math.sqrt n))]
    +                       (when (= 0 (% n i))
    +                             (local j (math.floor (/ n i)))
    +                             (set sum (+ sum i (if (= i j) 0 j)))
    +                       )
    +                  )
    +              )
    +        )
    +        sum
    +    )
    +
    +
    +    ; first 37 chowla numbers
    +    (for [n 1 37] (print (.. "chowla(" n ") = " (chowla n))))
    +
    +    ; number of primes up to 10_000_000
    +    (var (count power) (values 0 100))
    +    (for [n 2 10_000_000]
    +         (when (= 0 (chowla n))
    +               (set count (+ count 1))
    +         )
    +         (when (= 0 (% n power))
    +               (print (string.format "There are %6d primes < %d" count power))
    +               (set power (* power 10))
    +         )
    +    )
    +
    +    ; perfect numbers to 35_000_000
    +    (local perfect-max 35_000_000)
    +    (set count 0)
    +    (var (k kk p) (values 2 3 6))       ; p is k * kk
    +    (while (<= p perfect-max)
    +           (when (= (chowla p) (- p 1))
    +                 (print (string.format "        %8d is a perfect number" p))
    +                 (set count (+ count 1))
    +           )
    +           (set k  (+ kk 1))
    +           (set kk (+ kk k))
    +           (set p  (* kk k))
    +    )
    +    (print (.. "There are " count " perfect numbers < " perfect-max))
    +)
    diff --git a/Task/Chowla-numbers/JavaScript/chowla-numbers.js b/Task/Chowla-numbers/JavaScript/chowla-numbers.js
    new file mode 100644
    index 0000000000..1ff725b65f
    --- /dev/null
    +++ b/Task/Chowla-numbers/JavaScript/chowla-numbers.js
    @@ -0,0 +1,79 @@
    +// Chowla function: calculates sum of proper divisors of n (excluding n itself)
    +function chowla(n) {
    +    let sum = 0;
    +    for (let i = 2; i * i <= n; i++) {
    +        if (n % i === 0) {
    +            const j = n / i;
    +            sum += i + (i === j ? 0 : j);
    +        }
    +    }
    +    return sum;
    +}
    +
    +// Sieve function: returns array where true denotes composite, false denotes prime
    +// Only interested in odd numbers >= 3
    +function sieve(limit) {
    +    // True denotes composite, false denotes prime
    +    const c = new Array(limit).fill(false);
    +
    +    for (let i = 3; i * 3 < limit; i += 2) {
    +        if (!c[i] && chowla(i) === 0) {
    +            for (let j = 3 * i; j < limit; j += 2 * i) {
    +                c[j] = true;
    +            }
    +        }
    +    }
    +    return c;
    +}
    +
    +// Main execution
    +function main() {
    +    // Part 1: Print chowla values for 1-37
    +    console.log("Chowla function values for 1-37:");
    +    for (let i = 1; i <= 37; i++) {
    +        console.log(`chowla(${i}) = ${chowla(i)}`);
    +    }
    +    console.log("\n");
    +
    +    // Part 2: Count primes up to powers of 10
    +    console.log("Prime counting using Chowla's sieve:");
    +    let count = 1;
    +    const limit = 10000000; // 1e7
    +    let power = 100;
    +
    +    const c = sieve(limit);
    +
    +    for (let i = 3; i < limit; i += 2) {
    +        if (!c[i]) count++;
    +
    +        if (i === power - 1) {
    +            console.log(`Count of primes up to ${power.toLocaleString()} = ${count.toLocaleString()}`);
    +            power *= 10;
    +        }
    +    }
    +    console.log("\n");
    +
    +    // Part 3: Find perfect numbers
    +    console.log("Perfect numbers <= 35,000,000:");
    +    count = 0;
    +    const perfectLimit = 35000000;
    +
    +    let k = 2, kk = 3, p;
    +    for (let i = 2; ; i++) {
    +        p = k * kk;
    +        if (p > perfectLimit) break;
    +
    +        if (chowla(p) === p - 1) {
    +            console.log(`${p.toLocaleString()} is a perfect number`);
    +            count++;
    +        }
    +
    +        k = kk + 1;
    +        kk += k;
    +    }
    +
    +    console.log(`\nThere are ${count} perfect numbers <= 35,000,000`);
    +}
    +
    +// Execute the main function
    +main();
    diff --git a/Task/Chowla-numbers/Julia/chowla-numbers.jl b/Task/Chowla-numbers/Julia/chowla-numbers.jl
    index cc27df514d..1402756727 100644
    --- a/Task/Chowla-numbers/Julia/chowla-numbers.jl
    +++ b/Task/Chowla-numbers/Julia/chowla-numbers.jl
    @@ -1,4 +1,4 @@
    -using Primes, Formatting
    +using Primes, Format
     
     function chowla(n)
         if n < 1
    diff --git a/Task/Chowla-numbers/Maxima/chowla-numbers.maxima b/Task/Chowla-numbers/Maxima/chowla-numbers.maxima
    new file mode 100644
    index 0000000000..be58f3e5ab
    --- /dev/null
    +++ b/Task/Chowla-numbers/Maxima/chowla-numbers.maxima
    @@ -0,0 +1,13 @@
    +chowla(n) := if(n=1) then 0 else divsum(n)-n-1$
    +chowla_seq(n, start) := map(chowla, makelist(i,i,start,n))$
    +chowla_seq(37, 1);
    +
    +chowla_numprimes(n) := length(sublist_indices(chowla_seq(n, 2), lambda([x], x=0)))$
    +map(chowla_numprimes, makelist(10^i, i, 2, 7));
    +
    +chowla_perfects(n) := block(
    +    chowla_list: chowla_seq(n, 1),
    +    is_perfect(x) := if(x>n or x=0) then false else x=chowla_list[x+1],
    +    unique(sublist(chowla_list, is_perfect)+1))$
    +
    +chowla_perfects(10000);
    diff --git a/Task/Chowla-numbers/Pluto/chowla-numbers.pluto b/Task/Chowla-numbers/Pluto/chowla-numbers.pluto
    new file mode 100644
    index 0000000000..7170013ac8
    --- /dev/null
    +++ b/Task/Chowla-numbers/Pluto/chowla-numbers.pluto
    @@ -0,0 +1,57 @@
    +do  -- find some Chowla numbers ( Chowla n = sum of divisors of n exclusing n and 1 )
    +
    +    -- returns the divisor sums of [1 n], the sums exclude 1 and n
    +    local function sumDivisors( n : number ) : table
    +        local sums  = {}
    +        for i = 1, n do sums[ i ] = 0 end
    +        for i = 2, n do
    +            for j = i + i, n, i do sums[ j ] += i end
    +        end
    +        return sums
    +    end
    +
    +    local ds  = sumDivisors( 10_000_000 )
    +
    +    local function chowla( n : number ) : number   -- returns the Chowla number of n
    +        local sum = 0
    +        if n > 0 then
    +            if n <= # ds then
    +                sum = ds[ n ]
    +            else
    +                for i = 2, math.floor( math.sqrt( n ) ) do
    +                    if n % i == 0 then
    +                        local j  = n // i
    +                        sum += i + if i == j then 0 else j end
    +                    end
    +                end
    +            end
    +        end
    +        return sum
    +    end
    +
    +    -- first 37 chowla numbers
    +    for n = 1, 37 do print( $"chowla({n}) = {chowla(n)}" ) end
    +
    +    -- number of primes up to 10_000_000
    +    local count, power = 0, 100
    +    for n = 2, 10_000_000 do
    +        if chowla( n ) == 0 then count += 1 end
    +        if n % power == 0 then
    +            print( string.format( "There are %6d primes < %d", count, power ) )
    +            power *= 10
    +        end
    +    end
    +
    +    -- perfect numbers to 35_000_000
    +    local perfectMax  = 35_000_000
    +    count = 0
    +    local k, kk, p = 2, 3, 6       -- p is k * kk
    +    while p <= perfectMax do
    +        if chowla( p ) == p - 1 then
    +            print( string.format( "        %8d is a perfect number", p ) )
    +            count += 1
    +        end
    +        k = kk + 1; kk += k; p = k * kk
    +    end
    +    print( $"There are {count} perfect numbers < {perfectMax}" )
    +end
    diff --git a/Task/Chowla-numbers/REXX/chowla-numbers.rexx b/Task/Chowla-numbers/REXX/chowla-numbers.rexx
    index 7e5cf5ad9b..7f52a942e8 100644
    --- a/Task/Chowla-numbers/REXX/chowla-numbers.rexx
    +++ b/Task/Chowla-numbers/REXX/chowla-numbers.rexx
    @@ -1,4 +1,4 @@
    --- 23 Aug 2025
    +-- 21 Feb 2026
     include Setting
     numeric digits 12
     
    @@ -6,8 +6,11 @@ say 'CHOWLA NUMBERS'
     say version
     say
     call ChowlaNumbers
    +call Timer 'R'
     call PrimeCount
    +call Timer 'R'
     call PerfectNumbers
    +call Timer 'R'
     exit
     
     ChowlaNumbers:
    @@ -19,13 +22,11 @@ do i = 1 to m
        say Right(i,2) Right(Chowla(i),9)
     end
     say sep
    -say Format(Time('e'),,3) 'seconds'
    -say
     return
     
     PrimeCount:
     procedure expose Memo. work.
    -call Time('r'); sep = Copies('-',17)
    +sep = Copies('-',17)
     say sep; say Right('n',8) Right('Primes perfect_limit) break;
    +        if (chowla(p) == p - 1) {
    +            std.debug.print("{} is a number that is perfect\n", .{p});
    +            perfect_count += 1;
    +        }
    +        k = kk + 1;
    +        kk += k;
    +    }
    +
    +    std.debug.print("There are {} perfect numbers <= 35,000,000\n", .{perfect_count});
    +}
    diff --git a/Task/Church-numerals/Applesoft-BASIC/church-numerals.basic b/Task/Church-numerals/Applesoft-BASIC/church-numerals.basic
    new file mode 100644
    index 0000000000..954ef14625
    --- /dev/null
    +++ b/Task/Church-numerals/Applesoft-BASIC/church-numerals.basic
    @@ -0,0 +1,29 @@
    + 0  DIM OP(13),N(13),X(13,1):READ OP(ZERO),N(ZERO),X(ZERO,0),X(ZERO,1):CN = CN + 1:DATA1,0,0,1
    + 1 C = ZERO:GOSUB 10:C=R:GOSUB 10:C=R:GOSUB 10:THREE = R
    + 2 C = THREE                         :GOSUB 10:FOUR  = R
    + 3 C = THREE                         :GOSUB 80:PRINT "THREE        -> "R
    + 4 C = FOUR                          :GOSUB 80:PRINT "FOUR         -> "R
    + 5 C = THREE:D = FOUR :GOSUB 50:C = R:GOSUB 80:PRINT "THREE + FOUR -> "R
    + 6 C = THREE:D = FOUR :GOSUB 60:C = R:GOSUB 80:PRINT "THREE * FOUR -> "R
    + 7 C = THREE:D = FOUR :GOSUB 70:C = R:GOSUB 80:PRINT "THREE ^ FOUR -> "R
    + 8 C = FOUR :D = THREE:GOSUB 70:C = R:GOSUB 80:PRINT "FOUR ^ THREE -> "R
    + 9 I = 5              :GOSUB 90:C = R:GOSUB 80:PRINT "5 -> FIVE    -> "R;:END
    +REM SUCC
    + 10 R = CN:OP(R) = OP(C):N(R) = N(C) + 1:X(R,0) = X(C,0):X(R,1) = X(C,1):CN = CN + 1:RETURN
    +REM SUM
    + 20  FOR I = 1 TO N:A = A + B:NEXT I:R = A:RETURN
    +REM MUL
    + 30  FOR I = 1 TO N:A = A * B:NEXT I:R = A:RETURN
    +REM POW
    + 40  FOR I = 1 TO N:A = A ^ B:NEXT I:R =  INT (A):RETURN
    +REM CHURCH SUM
    + 50 RES = CN:OP(RES) = 1:N(RES) = 1:X(RES,0) = N(C):X(RES,1) = N(D):CN = CN + 1:R = RES:RETURN
    +REM CHURCH MUL
    + 60 RES = CN:OP(RES) = 2:N(RES) = 1:X(RES,0) = N(C):X(RES,1) = N(D):CN = CN + 1:R = RES:RETURN
    +REM CHURCH POW
    + 70 RES = CN:OP(RES) = 3:N(RES) = 1:X(RES,0) = N(C):X(RES,1) = N(D):CN = CN + 1:R = RES:RETURN
    +REM CHURCH TO NUM
    + 80 N = N(C):A = X(C,0):B = X(C,1):ON OP(C) GOTO 20,30,40:STOP
    +REM NUM TO CHURCH
    + 90 R = ZERO:IF I = 0 THEN RETURN
    + 91 I = I - 1:GOSUB 90:C = R:GOTO 10"SUCC
    diff --git a/Task/Church-numerals/Binary-Lambda-Calculus/church-numerals.blc b/Task/Church-numerals/Binary-Lambda-Calculus/church-numerals.blc
    new file mode 100644
    index 0000000000..d228e6480d
    --- /dev/null
    +++ b/Task/Church-numerals/Binary-Lambda-Calculus/church-numerals.blc
    @@ -0,0 +1,27 @@
    +(let ((zero 0)
    +      (succ (lambda (n f x)
    +              (f (n f x))))
    +      (one (succ zero))
    +      (two (succ one))
    +      (three (succ two))
    +      (four (succ three))
    +      (plus (lambda (m n f x)
    +              (m f (n f x))))
    +      (times (lambda (m n f)
    +               (m (n f))))
    +      (power (lambda (m n)
    +               (n m)))
    +      (cons (lambda (x y f)
    +              (f x y))))
    +  (lambda (in)
    +    (cons
    +     (plus three four)
    +     (cons
    +      (times three four)
    +      (cons
    +       (power three four)
    +       (cons
    +        (power four three)
    +        (cons
    +         (power (power two two) (plus two one))
    +         nil)))))))
    diff --git a/Task/Church-numerals/Chapel/church-numerals.chpl b/Task/Church-numerals/Chapel/church-numerals.chpl
    new file mode 100644
    index 0000000000..67bb37dfd5
    --- /dev/null
    +++ b/Task/Church-numerals/Chapel/church-numerals.chpl
    @@ -0,0 +1,178 @@
    +class Church { // identity Church function by default
    +    proc this(f: shared Church): shared Church { return f; }
    +}
    +
    +// utility Church functions...
    +class ComposeChurch : Church {
    +    const l, r: shared Church;
    +    override proc this(f: shared Church): shared Church {
    +        return l(r(f)); }
    +}
    +
    +proc composeChurch(chl: shared Church, chr: shared Church) : shared Church {
    +    return new shared ComposeChurch(chl, chr): shared Church;
    +}
    +
    +class ConstChurch : Church {
    +    const ch: shared Church;
    +    override proc this(f: shared Church): shared Church { return ch; }
    +}
    +
    +proc constChurch(ch: shared Church): shared Church {
    +    return new shared ConstChurch(ch): shared Church;
    +}
    +
    +// Church constants...
    +const cIdentityChurch: shared Church = new shared Church();
    +const cChurchZero = constChurch(cIdentityChurch);
    +const cChurchOne = cIdentityChurch; // default is identity!
    +
    +// Church functions...
    +class SuccChurch: Church {
    +    const curr: shared Church;
    +    override proc this(f: shared Church): shared Church {
    +        return composeChurch(f, curr(f)); }
    +}
    +
    +proc succChurch(ch: shared Church): shared Church {
    +    return new shared SuccChurch(ch) : shared Church;
    +}
    +
    +class AddChurch: Church {
    +    const chf, chs: shared Church;
    +    override proc this(f: shared Church): shared Church {
    +        return composeChurch(chf(f), chs(f)); }
    +}
    +
    +proc addChurch(cha: shared Church, chb: shared Church): shared Church {
    +    return new shared AddChurch(cha, chb) : shared Church;
    +}
    +
    +class MultChurch: Church {
    +    const chf, chs: shared Church;
    +    override proc this(f: shared Church): shared Church {
    +        return composeChurch(chf, chs)(f); }
    +}
    +
    +proc multChurch(cha: shared Church, chb: shared Church): shared Church {
    +    return new shared MultChurch(cha, chb) : shared Church;
    +}
    +
    +class ExpChurch : Church {
    +    const b, e : shared Church;
    +    override proc this(f : shared Church): shared Church { return e(b)(f); }
    +}
    +
    +proc expChurch(chbs: shared Church, chexp: shared Church): shared Church {
    +    return new shared ExpChurch(chbs, chexp) : shared Church;
    +}
    +
    +class IsZeroChurch : Church {
    +    const c : shared Church;
    +    override proc this(f : shared Church): shared Church {
    +        return c(constChurch(cChurchZero))(cChurchOne)(f); }
    +}
    +
    +proc isZeroChurch(ch: shared Church): shared Church {
    +    return new shared IsZeroChurch(ch) : shared Church;
    +}
    +
    +class PredChurch : Church {
    +    const c : shared Church;
    +    class XFunc : Church {
    +        const cf, fnc: shared Church;
    +        class GFunc : Church {
    +            const fnc: shared Church;
    +            class HFunc : Church {
    +                const fnc, g: shared Church;
    +                override proc this(f : shared Church): shared Church {
    +                    return f(g(fnc)); }
    +            }
    +            override proc this(f : shared Church): shared Church {
    +                return new shared HFunc(fnc, f): shared Church; }
    +        }
    +        override proc this(f : shared Church): shared Church {
    +            const prd = new shared GFunc(fnc): shared Church;
    +            return cf(prd)(constChurch(f))(cIdentityChurch); }
    +    }
    +    override proc this(f : shared Church): shared Church {
    +        return new shared XFunc(c, f) : shared Church; }
    +}
    +
    +proc predChurch(ch: shared Church): shared Church {
    +    return new shared PredChurch(ch) : shared Church;
    +}
    +
    +class SubChurch : Church {
    +    const a, b : shared Church;
    +    class PredFunc : Church {
    +        override proc this(f : shared Church): shared Church {
    +            return new shared PredChurch(f): shared Church;
    +        }
    +    }
    +    override proc this(f : shared Church): shared Church {
    +        const prdf = new shared PredFunc(): shared Church;
    +        return b(prdf)(a)(f); }
    +}
    +
    +proc subChurch(cha: shared Church, chb: shared Church): shared Church {
    +    return new shared SubChurch(cha, chb) : shared Church;
    +}
    +
    +class DivrChurch : Church {
    +    const v, d : shared Church;
    +    override proc this(f : shared Church): shared Church {
    +        const loopr = constChurch(succChurch(divr(v, d)));
    +        return v(loopr)(cChurchZero)(f); }
    +}
    +
    +proc divr(n: shared Church, d : shared Church): shared Church {
    +    return new shared DivrChurch(subChurch(n, d), d): shared Church;
    +}
    +
    +proc divChurch(chdvdnd: shared Church, chdvsr: shared Church): shared Church {
    +    return divr(succChurch(chdvdnd), chdvsr);
    +}
    +
    +// conversion functions...
    +proc loopChurch(i: int, ch: shared Church) : shared Church { // tail call...
    +    return if (i <= 0) then ch else loopChurch(i - 1, succChurch(ch));
    +}
    +
    +proc churchFromInt(n: int): shared Church {
    +    return loopChurch(n, cChurchZero); // can't embed "worker" proc!
    +}
    +
    +class IntChurch : Church {
    +    const value: int;
    +}
    +
    +class IncChurch : Church {
    +    override proc this(f: shared Church): shared Church {
    +        const tst = f: IntChurch;
    +        if tst != nil {
    +          return new shared IntChurch(tst.value + 1): shared Church; }
    +        else return f; } // shouldn't happen!
    +}
    +
    +proc intFromChurch(ch: shared Church): int {
    +    const zero = new shared IntChurch(0): shared Church;
    +    const tst = ch(new shared IncChurch(): shared Church)(zero): IntChurch;
    +    if tst != nil { return tst.value; }
    +    else return -1; // should never happen!
    +}
    +
    +// testing...
    +const ch3 = churchFromInt(3); const ch4 = succChurch(ch3);
    +const ch11 = churchFromInt(11); const ch12 = succChurch(ch11);
    +write(intFromChurch(addChurch(ch3, ch4)), ", ");
    +write(intFromChurch(multChurch(ch3, ch4)), ", ");
    +write(intFromChurch(expChurch(ch3, ch4)), ", ");
    +write(intFromChurch(expChurch(ch4, ch3)), ", ");
    +write(intFromChurch(isZeroChurch(cChurchZero)), ", ");
    +write(intFromChurch(isZeroChurch(ch3)), ", ");
    +write(intFromChurch(predChurch(ch4)), ", ");
    +write(intFromChurch(predChurch(cChurchZero)), ", ");
    +write(intFromChurch(subChurch(ch11, ch3)), ", ");
    +write(intFromChurch(divChurch(ch11, ch3)), ", ");
    +writeln(intFromChurch(divChurch(ch12, ch3)));
    diff --git a/Task/Church-numerals/Pluto/church-numerals.pluto b/Task/Church-numerals/Pluto/church-numerals.pluto
    new file mode 100644
    index 0000000000..d6c93b55a3
    --- /dev/null
    +++ b/Task/Church-numerals/Pluto/church-numerals.pluto
    @@ -0,0 +1,31 @@
    +class church
    +    static function zero() return || -> (|x| -> x) end
    +
    +    static function succ(c) return |f| -> (|x| -> f(c(f)(x))) end
    +
    +    static function add(c, d) return |f| -> (|x| -> c(f)(d(f)(x))) end
    +
    +    static function mul(c, d) return |f| -> c(d(f)) end
    +
    +    static function pow(c, e) return e(c) end
    +
    +    static function fromint(n)
    +        local ret = zero()
    +        if n > 0 then
    +            for i = 1, n do ret = succ(ret) end
    +        end
    +        return ret
    +    end
    +
    +    static function toint(c) return c(|x| -> x + 1)(0) end
    +end
    +
    +local three = church.succ(church.succ(church.succ(church.zero())))
    +local four = church.succ(three)
    +
    +print($"three         -> {church.toint(three)}")
    +print($"four          -> {church.toint(four)}")
    +print($"three + four  -> {church.toint(church.add(three, four))}")
    +print($"three * four  -> {church.toint(church.mul(three, four))}")
    +print($"three ^ four  -> {church.toint(church.pow(three, four))}")
    +print($"four  ^ three -> {church.toint(church.pow(four, three))}")
    diff --git a/Task/Circles-of-given-radius-through-two-points/Pluto/circles-of-given-radius-through-two-points.pluto b/Task/Circles-of-given-radius-through-two-points/Pluto/circles-of-given-radius-through-two-points.pluto
    new file mode 100644
    index 0000000000..fb21bb1e9e
    --- /dev/null
    +++ b/Task/Circles-of-given-radius-through-two-points/Pluto/circles-of-given-radius-through-two-points.pluto
    @@ -0,0 +1,57 @@
    +local Two  = "Two circles."
    +local R0   = "R == 0 does not describe circles."
    +local Co   = "Coincident points describe an infinite number of circles."
    +local CoR0 = "Coincident points with r == 0 describe a degenerate circle."
    +local Diam = "Points form a diameter and describe only a single circle."
    +local Far  = "Points too far apart to form circles."
    +
    +class point
    +    function __construct(public x, public y) end
    +
    +    function __eq(other) return self.x == other.x and self.y == other.y end
    +
    +    function __tostring() return $"({self.x}, {self.y})" end
    +end
    +
    +local function circles(p1, p2, r)
    +    local c1 = new point(0, 0)
    +    local c2 = new point(0, 0)
    +    if p1 == p2 then
    +        if r == 0 then return p1, p1, CoR0 end
    +        return c1, c2, Co
    +    end
    +    if r == 0 then return p1, p2, R0 end
    +    local dx = p2.x - p1.x
    +    local dy = p2.y - p1.y
    +    local q = math.hypot(dx, dy)
    +    if q > 2 * r then return c1, c2, Far end
    +    local m = new point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2)
    +    if q == 2 * r then return m, m, Diam end
    +    local d = math.sqrt(r * r - q * q / 4)
    +    local ox = d * dx / q
    +    local oy = d * dy / q
    +    return new point(m.x - oy, m.y + ox), new point(m.x + oy, m.y - ox), Two
    +end
    +
    +local td = {
    +    {new point(0.1234, 0.9876), new point(0.8765, 0.2345), 2.0},
    +    {new point(0.0000, 2.0000), new point(0.0000, 0.0000), 1.0},
    +    {new point(0.1234, 0.9876), new point(0.1234, 0.9876), 2.0},
    +    {new point(0.1234, 0.9876), new point(0.8765, 0.2345), 0.5},
    +    {new point(0.1234, 0.9876), new point(0.1234, 0.9876), 0.0}
    +}
    +for td as t do
    +    local [p1, p2, r] = t
    +    print($"p1: {p1}")
    +    print($"p2: {p2}")
    +    print($"r : {r}")
    +    local c1, c2, s = circles(p1, p2, r)
    +    print($"    {s}")
    +    if s == CoR0 or s == Diam then
    +        print($"    Center: {c1}")
    +    elseif s == Two then
    +        print($"    Center 1: {c1}")
    +        print($"    Center 2: {c2}")
    +    end
    +    print()
    +end
    diff --git a/Task/Circles-of-given-radius-through-two-points/V-(Vlang)/circles-of-given-radius-through-two-points.v b/Task/Circles-of-given-radius-through-two-points/V-(Vlang)/circles-of-given-radius-through-two-points.v
    index 004623e3a7..40507db999 100644
    --- a/Task/Circles-of-given-radius-through-two-points/V-(Vlang)/circles-of-given-radius-through-two-points.v
    +++ b/Task/Circles-of-given-radius-through-two-points/V-(Vlang)/circles-of-given-radius-through-two-points.v
    @@ -1,13 +1,11 @@
     import math
     
    -const (
    -    two  = "two circles."
    -    r0   = "R==0.0 does not describe circles."
    -    co   = "coincident points describe an infinite number of circles."
    -    cor0 = "coincident points with r==0.0 describe a degenerate circle."
    -    diam = "Points form a diameter and describe only a single circle."
    -    far  = "Points too far apart to form circles."
    -)
    +const two = 'two circles.'
    +const r0 = 'R==0.0 does not describe circles.'
    +const co = 'coincident points describe an infinite number of circles.'
    +const cor0 = 'coincident points with r==0.0 describe a degenerate circle.'
    +const diam = 'Points form a diameter and describe only a single circle.'
    +const far = 'Points too far apart to form circles.'
     
     struct Point {
     	x f64
    @@ -17,63 +15,64 @@ struct Point {
     fn circles(p1 Point, p2 Point, r f64) (Point, Point, string) {
     	mut case := ''
     	c1, c2 := p1, p2
    -    if p1 == p2 {
    -        if r == 0 {
    -            return p1, p1, cor0
    -        }
    -        case = co
    -        return c1, c2, case
    -    }
    -    if r == 0 {
    -        return p1, p2, r0
    -    }
    -    dx := p2.x - p1.x
    -    dy := p2.y - p1.y
    -    q := math.hypot(dx, dy)
    -    if q > 2*r {
    -        case = far
    -        return c1, c2, case
    -    }
    -    m := Point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2}
    -    if q == 2*r {
    -        return m, m, diam
    -    }
    -    d := math.sqrt(r*r - q*q/4)
    -    ox := d * dx / q
    -    oy := d * dy / q
    -    return Point{m.x - oy, m.y + ox}, Point{m.x + oy, m.y - ox}, two
    +	if p1 == p2 {
    +		if r == 0 {
    +			return p1, p1, cor0
    +		}
    +		case = co
    +		return c1, c2, case
    +	}
    +	if r == 0 {
    +		return p1, p2, r0
    +	}
    +	dx := p2.x - p1.x
    +	dy := p2.y - p1.y
    +	q := math.hypot(dx, dy)
    +	if q > 2 * r {
    +		case = far
    +		return c1, c2, case
    +	}
    +	m := Point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2}
    +	if q == 2 * r {
    +		return m, m, diam
    +	}
    +	d := math.sqrt(r * r - q * q / 4)
    +	ox := d * dx / q
    +	oy := d * dy / q
    +	return Point{m.x - oy, m.y + ox}, Point{m.x + oy, m.y - ox}, two
     }
     
     struct Cir {
     	p1 Point
     	p2 Point
    -	r f64
    +	r  f64
     }
    +
     const td = [
    -    Cir{Point{0.1234, 0.9876}, Point{0.8765, 0.2345}, 2.0},
    -    Cir{Point{0.0000, 2.0000}, Point{0.0000, 0.0000}, 1.0},
    -    Cir{Point{0.1234, 0.9876}, Point{0.1234, 0.9876}, 2.0},
    -    Cir{Point{0.1234, 0.9876}, Point{0.8765, 0.2345}, 0.5},
    -    Cir{Point{0.1234, 0.9876}, Point{0.1234, 0.9876}, 0.0},
    +	Cir{Point{0.1234, 0.9876}, Point{0.8765, 0.2345}, 2.0},
    +	Cir{Point{0.0000, 2.0000}, Point{0.0000, 0.0000}, 1.0},
    +	Cir{Point{0.1234, 0.9876}, Point{0.1234, 0.9876}, 2.0},
    +	Cir{Point{0.1234, 0.9876}, Point{0.8765, 0.2345}, 0.5},
    +	Cir{Point{0.1234, 0.9876}, Point{0.1234, 0.9876}, 0.0},
     ]
     
     fn main() {
    -    for tc in td {
    -        println("p1:  $tc.p1")
    -        println("p2:  $tc.p2")
    -        println("r:  $tc.r")
    -        c1, c2, case := circles(tc.p1, tc.p2, tc.r)
    -        println("   $case")
    -        match case {
    -        	cor0, diam{
    -            	println("   Center:  $c1")
    +	for tc in td {
    +		println('p1:  ${tc.p1}')
    +		println('p2:  ${tc.p2}')
    +		println('r:  ${tc.r}')
    +		c1, c2, case := circles(tc.p1, tc.p2, tc.r)
    +		println('   ${case}')
    +		match case {
    +			cor0, diam {
    +				println('   Center:  ${c1}')
     			}
    -        	two {
    -				println("   Center 1:  $c1")
    -				println("   Center 2:  $c2")
    +			two {
    +				println('   Center 1:  ${c1}')
    +				println('   Center 2:  ${c2}')
     			}
    -			else{}
    +			else {}
     		}
    -        println('')
    -    }
    +		println('')
    +	}
     }
    diff --git a/Task/Circular-primes/Free-Pascal-Lazarus/circular-primes-1.pas b/Task/Circular-primes/Free-Pascal-Lazarus/circular-primes-1.pas
    new file mode 100644
    index 0000000000..6b623050ae
    --- /dev/null
    +++ b/Task/Circular-primes/Free-Pascal-Lazarus/circular-primes-1.pas
    @@ -0,0 +1,61 @@
    +program circularprimes;
    +{$mode objfpc}
    +  function IsPrime(n: Cardinal): Boolean;inline;
    +  var
    +    i, limit: Cardinal;
    +  begin
    +    if (n = 2) or (n = 3) then Exit(True);
    +    if (n <= 1) or (n mod 2 = 0) or (n mod 3 = 0) then Exit(False);
    +
    +    i := 5;
    +    limit := Trunc(Sqrt(n));
    +    while i <= limit do
    +    begin
    +      if (n mod i = 0) or (n mod (i + 2) = 0) then Exit(False);
    +      Inc(i, 6);
    +    end;
    +    Result := True;
    +  end;
    +
    +  function cycle(const n:Cardinal):Cardinal;inline;
    +  var
    +    m:Cardinal;
    +    p:Cardinal = 1;
    +  begin
    +    m := n;
    +    while m >= 10 do
    +    begin
    +        p := p * 10;
    +        m := m div 10;
    +    end;
    +    result := m + 10 * (n mod p);
    +  end;
    +
    +  function IsCircularPrime(N: Cardinal): boolean;inline;
    +  var
    +    p:Cardinal;
    +  begin
    +    p := n;
    +    repeat
    +      if not IsPrime(p) or (p= 19 then break;
    +    If c mod 5 = 0 then s:=s+lineEnding;
    +    end;
    +  writeln(s,' Count = ',c);
    +end.
    diff --git a/Task/Circular-primes/Free-Pascal-Lazarus/circular-primes-2.pas b/Task/Circular-primes/Free-Pascal-Lazarus/circular-primes-2.pas
    new file mode 100644
    index 0000000000..df5cc070ad
    --- /dev/null
    +++ b/Task/Circular-primes/Free-Pascal-Lazarus/circular-primes-2.pas
    @@ -0,0 +1,283 @@
    +program CircularPrimes;
    +//nearly the way it is done:
    +//http://www.worldofnumbers.com/circular.htm
    +
    +{$IFDEF FPC}
    +  {$Release}
    +  {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$Coperators ON}
    +//  {$O+,R+}
    +  uses
    +    Sysutils,gmp;
    +{$ENDIF}
    +{$IFDEF Delphi}
    +  uses
    +    System.Sysutils,?gmp?;
    +{$ENDIF}
    +
    +{$IFDEF WINDOWS}
    +   {$APPTYPE CONSOLE}
    +{$ENDIF}
    +const
    +  Pot10 :array[0..19] of Uint64 =
    +      (1,10,100,1000,10000,100000,1000000,
    +      10000000,100000000,1000000000,10000000000,100000000000,1000000000000,10000000000000,
    +      100000000000000,1000000000000000,10000000000000000,100000000000000000,1000000000000000000,10000000000000000000);
    +  MAXCNTOFDIGITS = 19;
    +
    +type
    +  tDigits = 0..9;
    +  tUsedDigits = set of tDigits;
    +  tmyNum = record
    +              Dgts: array[0..MAXCNTOFDIGITS] of tDigits;
    +              num : Uint64;
    +              UsedDgt : tUsedDigits;
    +           end;
    +
    +var
    +  CheckNum : array[0..MAXCNTOFDIGITS] of Uint64;
    +  Found : array[0..23] of Uint64;
    +  mpz : mpz_t;
    +  cntPrmTest,
    +  cntRot : Uint64;
    +  SolCount : Int32;
    +
    +  procedure ExtendRepUnit(var mpz:mpz_t;idx1,idx2:Int32);
    +  begin
    +    inc(idx1);
    +    dec(idx2,9);
    +    while idx1 < idx2 do
    +    begin
    +      mpz_mul_ui(mpz,mpz,1000000000);// 2020 Windows only uses Uint32
    +      mpz_add_ui(mpz,mpz,0111111111);
    +      inc(idx1,9);
    +    end;
    +    inc(idx2,9);
    +    For idx1 := idx1 to idx2 do
    +    begin
    +      mpz_mul_ui(mpz,mpz,10);
    +      mpz_add_ui(mpz,mpz,1);
    +    end;
    +  end;
    +
    +  procedure CheckOne(MaxIdx:integer);
    +  begin
    +    MaxIdx -= 1;
    +    Found[SolCount] := CheckNum[MaxIdx];
    +    repeat
    +      mpz_set_ui(mpz,CheckNum[MaxIdx]);
    +      If mpz_probab_prime_p(mpz,3)=0then
    +        EXIT;
    +      inc(cntPrmTest);
    +      dec(MaxIdx);
    +    until MaxIdx < 0;
    +    inc(SolCount);
    +  end;
    +
    +  procedure InitNum(var myNum:tmyNum;maxDgt:Int32);
    +  var
    +    i: Int32;
    +  begin
    +    fillchar(myNum,SizeOf(myNum),#0);
    +    with myNum do
    +    Begin
    +      num := 0;
    +      For i := 0 to MaxDgt-1 do
    +      begin
    +        Dgts[i] := 1;
    +        num += Pot10[i];
    +      end;
    +    end;
    +  end;
    +
    +  procedure CorrectNum(var myNum:tmyNum;maxIdx,idx:Int32);
    +  var
    +    n : Uint64;
    +    dgt :int32;
    +  begin
    +    with myNum do
    +    begin
    +      dec(MaxIdx);
    +      dgt := Dgts[maxIdx];
    +      n := 0;
    +      while maxIdx>idx do
    +      Begin
    +        n += Dgts[maxIdx]*Pot10[maxIdx];
    +        dec(maxIdx);
    +      end;
    +      For Idx := Idx downto 0 do
    +      Begin
    +        Dgts[idx]:= dgt;
    +        n += Dgt*Pot10[Idx];
    +      end;
    +      num := n;
    +    end;
    +  end;
    +
    +  function IncNum(var myNum:tmyNum;maxDgt:Int32):boolean;
    +  //Next number with only digits of 1,3,7,9
    +  var
    +    n :Uint64;
    +    i,dgt: Int64;
    +    Udgt : tusedDigits;
    +  begin
    +    with myNum do
    +    Begin
    +      n := num;
    +      i := 0;
    +      repeat
    +        dgt := Dgts[i];
    +        dgt +=2;
    +        n += 2*Pot10[i];
    +        if dgt = 5 then
    +        begin
    +          dgt := 7;
    +          n += 2*Pot10[i];
    +        end;
    +        if dgt < 10 then
    +        begin
    +          Dgts[i] := dgt;
    +          Break;
    +        end;
    +        //correct values
    +        Dgts[i] := 1;
    +        dec(n,Pot10[i]*10);
    +        inc(i);
    +      until i >= maxDgt;
    +      if i >= maxDgt then
    +        EXIT(false);
    +
    +      dgt := Dgts[maxDgt-1];
    +      if dgt > 1 then
    +      Begin
    +        i := maxDgt-2;
    +        while i >= 0 do
    +        begin
    +          if Dgts[i]< dgt then
    +          begin
    +            //311->333 // 91111 -> 99999
    +            CorrectNum(myNum,maxDgt,i);
    +            EXIT(true);
    +          end;
    +          dec(i);
    +        end;
    +      end;
    +      num := n;
    +    end;
    +    result := true;
    +  end;
    +
    +  function rotateNum(n:Uint64;maxDgt:Int32):boolean;
    +  //rotate number and check divisibility by 3 and 7
    +  var
    +    Pot,q ,dgt,n0: Uint64;
    +  begin
    +    n0 := n;
    +    if n0 mod 3 = 0 then
    +      exit(false);
    +    if n0 mod 7 = 0 then
    +      exit(false);
    +
    +    dec(maxDgt);
    +    CheckNum[maxDgt] := n;
    +    Pot := Pot10[maxDgt];
    +    while maxDgt>0 do
    +    Begin
    +      inc(cntRot);
    +      q := n div 10;
    +      //last dgt = n mod 10
    +      dgt := n - 10*q;
    +      n := dgt*Pot+q;
    +      //tested elsewhere before
    +      if n < n0 then
    +        exit(false);
    +
    +      if n mod 7 = 0 then
    +        exit(false);
    +      dec(maxDgt);
    +      CheckNum[maxDgt] := n;
    +    end;
    +    result := true;
    +  end;
    +
    +var
    +  myNum : TmyNum;
    +  s :AnsiString;
    +  T0: Int64;
    +  idx,idx2 : NativeInt;
    +begin
    +  T0 := GetTickCount64;
    +  mpz_init(mpz);
    +
    +  SolCount := 0;
    +  //one digit primes including 5
    +  For idx := 2 to 10 do
    +    if idx in[2,3,5,7] then
    +    begin
    +      Found[SolCount]:= Idx;
    +      inc(SolCount);
    +    end;
    +
    +  writeln(' search for circular Primes');
    +  writeln(' digits  found  rotated numbers     to test  time in ms ');
    +  cntPrmTest := 0;
    +  cntRot := 0;
    +  For idx := 2 to 16 do
    +  begin
    +    InitNum(myNum,idx);
    +    repeat
    +      if rotateNum(myNum.num,idx) then
    +        CheckOne(idx);
    +    until Not(IncNUm(myNum,idx));
    +    writeln(idx:7,Solcount:7,cntRot:17,cntPrmTest:12,GetTickCount64-T0:8);
    +  end;
    +
    +  writeln;
    +  writeln('Found these ',solcount,' circular primes: ');
    +  For idx := 0 to solCount-2 do
    +    write(Found[idx],',');
    +  writeln(Found[solCount-1]);
    +
    +  mpz_set_ui(mpz,1);
    +  For idx := 2 to 1031 do
    +  begin
    +    mpz_mul_ui(mpz,mpz,10);
    +    mpz_add_ui(mpz,mpz,1);
    +    if mpz_probab_prime_p(mpz,1)=1 then
    +      writeln('Found prime RepUnit(',idx,')');
    +  end;
    +(*
    +  idx := 1031;idx2 := 5003;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +  idx := idx2;idx2 := 9887;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +  idx := idx2;idx2 := 15073;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +  idx := idx2;idx2 := 15073;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +  idx := idx2;idx2 := 25031;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +  idx := idx2;idx2 := 35317;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +  idx := idx2;idx2 := 49081;
    +  ExtendRepUnit(mpz,idx,idx2);
    +  write(' Found prime RepUnit(',idx2,')');
    +  writeln(boolean(Ord(mpz_probab_prime_p(mpz,1))));
    +// real  8m9,733s
    +*)
    +  mpz_clear(mpz);
    +  {$IFDEF WINDOWS}
    +  readln;
    +  {$ENDIF}
    +end.
    diff --git a/Task/Circular-primes/JavaScript/circular-primes.js b/Task/Circular-primes/JavaScript/circular-primes.js
    new file mode 100644
    index 0000000000..f1970c2e64
    --- /dev/null
    +++ b/Task/Circular-primes/JavaScript/circular-primes.js
    @@ -0,0 +1,167 @@
    +// Check if a number is prime (works with Number type)
    +function isPrime(n) {
    +  if (n < 2) return false;
    +  if (n % 2 === 0) return n === 2;
    +  if (n % 3 === 0) return n === 3;
    +  for (let p = 5; p * p <= n; p += 4) {
    +    if (n % p === 0) return false;
    +    p += 2;
    +    if (n % p === 0) return false;
    +  }
    +  return true;
    +}
    +
    +// Rotate the digits of a number: 197 -> 719 -> 971
    +function cycle(n) {
    +  const s = n.toString();
    +  if (s.length === 1) return n;
    +  return parseInt(s.slice(1) + s[0], 10);
    +}
    +
    +// Check if a number is a circular prime
    +function isCircularPrime(p) {
    +  if (!isPrime(p)) return false;
    +
    +  // Quick check: multi-digit circular primes cannot contain 0,2,4,5,6,8
    +  const s = p.toString();
    +  if (s.length > 1 && /[024568]/.test(s)) return false;
    +
    +  let p2 = cycle(p);
    +  while (p2 !== p) {
    +    if (p2 < p || !isPrime(p2)) return false;
    +    p2 = cycle(p2);
    +  }
    +  return true;
    +}
    +
    +// Modular exponentiation: (base^exp) % mod
    +function powerMod(base, exp, mod) {
    +  let result = 1n;
    +  base = base % mod;
    +  while (exp > 0n) {
    +    if (exp % 2n === 1n) result = (result * base) % mod;
    +    exp >>= 1n;
    +    base = (base * base) % mod;
    +  }
    +  return result;
    +}
    +
    +// Generate random BigInt in range [min, max] (inclusive)
    +function generateRandomBigInt(min, max) {
    +  if (max < min) throw new Error("Invalid range");
    +
    +  const range = max - min + 1n;
    +  // If range is small enough, use Math.random
    +  if (range <= BigInt(Number.MAX_SAFE_INTEGER)) {
    +    return min + BigInt(Math.floor(Math.random() * Number(range)));
    +  }
    +
    +  // For large ranges, generate a random number with appropriate digit length
    +  const maxStr = max.toString();
    +  const len = maxStr.length;
    +
    +  let randomStr;
    +  do {
    +    // Generate a number with one fewer digit than max
    +    randomStr = '';
    +    for (let i = 0; i < len - 1; i++) {
    +      randomStr += Math.floor(Math.random() * 10).toString();
    +    }
    +    // Remove leading zeros and ensure it's not empty
    +    randomStr = randomStr.replace(/^0+/, '');
    +    if (randomStr === '') randomStr = '0';
    +  } while (BigInt(randomStr) > max);
    +
    +  const result = BigInt(randomStr);
    +  return result >= min ? result : min;
    +}
    +
    +// Miller-Rabin primality test for BigInt
    +function isProbablePrime(n, k = 15) {
    +  if (n === 2n || n === 3n) return true;
    +  if (n < 2n || n % 2n === 0n) return false;
    +
    +  // Write n-1 as d*2^s
    +  let d = n - 1n;
    +  let s = 0;
    +  while (d % 2n === 0n) {
    +    d /= 2n;
    +    s++;
    +  }
    +
    +  // Witness loop
    +  for (let i = 0; i < k; i++) {
    +    // Generate random BigInt a in range [2, n-2]
    +    const a = generateRandomBigInt(2n, n - 2n);
    +
    +    let x = powerMod(a, d, n);
    +    if (x === 1n || x === n - 1n) continue;
    +
    +    let composite = true;
    +    for (let r = 0; r < s - 1; r++) {
    +      x = (x * x) % n;
    +      if (x === n - 1n) {
    +        composite = false;
    +        break;
    +      }
    +    }
    +
    +    if (composite) return false;
    +  }
    +
    +  return true;
    +}
    +
    +// Create a repunit: digits=3 -> 111n
    +function repunit(digits) {
    +  return (10n ** BigInt(digits) - 1n) / 9n;
    +}
    +
    +// Test repunit primality
    +function testRepunit(digits) {
    +  const r = repunit(digits);
    +  if (isProbablePrime(r, 15)) {
    +    console.log(`R(${digits}) is probably prime.`);
    +  } else {
    +    console.log(`R(${digits}) is not prime.`);
    +  }
    +}
    +
    +// Main execution
    +console.log("First 19 circular primes:");
    +let p = 2;
    +let count = 0;
    +while (count < 19) {
    +  if (isCircularPrime(p)) {
    +    if (count > 0) process.stdout.write(", ");
    +    process.stdout.write(p.toString());
    +    count++;
    +  }
    +  p++;
    +}
    +console.log();
    +
    +console.log("Next 4 circular primes:");
    +let digits = 1;
    +let repunitVal = 1n;
    +while (repunitVal < BigInt(p)) {
    +  digits++;
    +  repunitVal = repunit(digits);
    +}
    +
    +count = 0;
    +while (count < 4) {
    +  if (isProbablePrime(repunitVal, 15)) {
    +    if (count > 0) process.stdout.write(", ");
    +    process.stdout.write(`R(${digits})`);
    +    count++;
    +  }
    +  digits++;
    +  repunitVal = repunitVal * 10n + 1n;
    +}
    +console.log();
    +
    +testRepunit(5003);
    +testRepunit(9887);
    +testRepunit(15073);
    +testRepunit(25031);
    diff --git a/Task/Circular-primes/K/circular-primes.k b/Task/Circular-primes/K/circular-primes.k
    new file mode 100644
    index 0000000000..a54ce86cd3
    --- /dev/null
    +++ b/Task/Circular-primes/K/circular-primes.k
    @@ -0,0 +1,19 @@
    +pm: { /print matrix
    +    fw: -(3 + _log10e * 1e-12 + |/`ln x)
    +    `0: (,/fw$$)'(0N;y) # x}
    +
    +pr: {$[x < 5; |/ x = 2 3; &/ ~0=(`pri (`i$ 1 + %x))!' x]}
    +
    +log10e: 1%`ln 10
    +len: {1+_1e-12+log10e*`ln x}
    +rot: {10/ {(1_x), *x} (10\x)}
    +rots: {(-1 + len x) rot\ x}
    +circ: {r: rots x; $[&/~(*r) > 1_r; &/pr' r; 0]}
    +
    +gen: {[n] {{y+10*x}/x}' (1 3 7 9)@+!n#4}
    +cand: ,/gen' 2+!5
    +
    +ps: 2, 3, 5, 7, cand@&circ' cand
    +
    +`0: "The circular primes are:"
    +pm[ps; 10]
    diff --git a/Task/Circular-primes/Pluto/circular-primes.pluto b/Task/Circular-primes/Pluto/circular-primes.pluto
    new file mode 100644
    index 0000000000..56611708bb
    --- /dev/null
    +++ b/Task/Circular-primes/Pluto/circular-primes.pluto
    @@ -0,0 +1,74 @@
    +local int = require "int"
    +local fmt = require "fmt"
    +require "bignum"
    +
    +local circs = {}
    +
    +local function is_circular(n)
    +    local nn = n
    +    local pow = 1  -- will eventually contain 10 ^ d where d is number of digits in n
    +    while nn > 0 do
    +        pow *= 10
    +        nn //= 10
    +    end
    +    nn = n
    +    while true do
    +        nn *= 10
    +        local f = nn // pow  -- first digit
    +        nn += f * (1 - pow)
    +        if nn in circs then return false end
    +        if nn == n then break end
    +        if !int.isprime(nn) then return false end
    +    end
    +    return true
    +end
    +
    +print("The first 19 circular primes are:")
    +local digits = {1, 3, 7, 9}
    +local q = {1, 2, 3, 5, 7, 9}   -- queue the numbers to be examined
    +local fq = {1, 2, 3, 5, 7, 9}  -- also queue the corresponding first digits
    +local count = 0
    +while true do
    +    local f = q[1]    -- peek first element
    +    local fd = fq[1]  -- peek first digit
    +    if int.isprime(f) and is_circular(f) then
    +        circs:insert(f)
    +        count += 1
    +        if count == 19 then break end
    +    end
    +    q:remove(1)   -- pop first element
    +    fq:remove(1)  -- ditto for first digit queue
    +    if f != 2 and f != 5 then  -- if digits > 1 can't contain a 2 or 5
    +        -- add numbers with one more digit to queue
    +        -- only numbers whose last digit >= first digit need be added
    +        for digits as d do
    +            if d >= fd then
    +                q:insert(f * 10 + d)
    +                fq:insert(fd)
    +            end
    +        end
    +    end
    +end
    +fmt.lprint(circs)
    +
    +print("\nThe next 4 circular primes, in repunit format, are:")
    +count = 0
    +mpz.init()
    +local rus = {}
    +local primes = int.primes(10_000)
    +local repunit
    +for i = 4, #primes do
    +    local p = primes[i]
    +    repunit = bigint.new(string.rep("1", p))
    +    if mpz.isprobableprime(repunit) then
    +        rus:insert($"R({p})")
    +        count += 1
    +        if count == 4 then break end
    +    end
    +end
    +fmt.lprint(rus)
    +print("\nThe following repunits are probably circular primes:")
    +for {5003, 9887, 15073, 25031, 35317, 49081} as i do
    +    repunit = bigint.new(string.rep("1", i))
    +    fmt.print("R(%-5d) : %s", i, mpz.isprobableprime(repunit))
    +end
    diff --git a/Task/Circular-primes/REXX/circular-primes.rexx b/Task/Circular-primes/REXX/circular-primes.rexx
    index 3f3955da27..0abad89779 100644
    --- a/Task/Circular-primes/REXX/circular-primes.rexx
    +++ b/Task/Circular-primes/REXX/circular-primes.rexx
    @@ -1,24 +1,27 @@
    --- 23 Aug 2025
    +-- 25 Apr 2026
     include Setting
     
     say 'CIRCULAR PRIMES'
     say version
     say
     call First19
    +call Timer 'r'
     call Next3
    -call HigherReps
    +call Timer 'r'
    +call Rep1031
    +call Timer 'r'
     exit
     
     First19:
    -procedure expose Memo. prim.
    -call Time('r')
    +procedure expose Memo. Prim.
     numeric digits 10
     say 'First 19 circular primes:'
     p = Primes(200000)
     do i = 1 to p
    -   a = prim.i
    -   if Verify(a,'024568','m') > 0 then
    -      iterate i
    +   a = Prim.i
    +   if a>10 then
    +      if Verify(a,'024568','m') > 0 then
    +         iterate i
        b = a; l = Length(b)
        do l-1
           b = Right(b,l-1)||Left(b,1)
    @@ -30,14 +33,11 @@ do i = 1 to p
        call Charout ,a' '
     end
     say
    -say Format(Time('e'),,3) 'seconds'
    -say
     return
     
     Next3:
     procedure expose Memo.
    -call Time('r')
    -numeric digits 320
    +numeric digits 1000
     say 'Next 3 circular primes:'
     do i = 7 to 320
        r = Repunit(i)
    @@ -45,21 +45,18 @@ do i = 7 to 320
           call Charout ,'R('i') '
     end
     say
    -say Format(Time('e'),,3) 'seconds'
    -say
     return
     
    -HigherReps:
    +Rep1031:
     procedure expose Memo.
     call Time('r')
    -numeric digits 1040
    +numeric digits 10000
     say 'Primality of R(1031):'
     if Prime(Repunit(1031)) then
    -   say 'R(1031) is probable prime'
    +   say 'R(1031) is probably prime'
     else
        say 'R(1031) is composite'
    -say Format(Time('e'),,3) 'seconds'
    -say
     return
     
    +-- Primes Prime Repunit Timer
     include Math
    diff --git a/Task/Circular-primes/Uiua/circular-primes-1.uiua b/Task/Circular-primes/Uiua/circular-primes-1.uiua
    new file mode 100644
    index 0000000000..30a653976c
    --- /dev/null
    +++ b/Task/Circular-primes/Uiua/circular-primes-1.uiua
    @@ -0,0 +1,4 @@
    +# Find first 19 circular primes
    +Rots   ← ⇌⋕≡⌟↻⇡⊸⧻°⋕
    +IsCirc ← ⨬(⋅0|/↧≡(=1⧻°/×))⊸(=⊙/↧)⟜Rots
    +⍜now(▽⊸≡IsCirc+1⊚=⊣⊸°/×+1⇡1e6)
    diff --git a/Task/Circular-primes/Uiua/circular-primes-2.uiua b/Task/Circular-primes/Uiua/circular-primes-2.uiua
    new file mode 100644
    index 0000000000..c76b0b8e94
    --- /dev/null
    +++ b/Task/Circular-primes/Uiua/circular-primes-2.uiua
    @@ -0,0 +1,13 @@
    +Prime ← =1 ⧻ °/×
    +Len   ← +1 ⌊+1e-12 °ₑ₁₀
    +
    +Rot      ← ⌝⊥10 ↻1 ⊥10
    +AllRot   ← ⍥(⊸Rot) Len ⟜∘
    +FirstLEq ← /↧ ≥ ⊃⊢(↘1)
    +Circ     ← /↧ ⊂ ⊃(≡Prime) FirstLEq AllRot
    +
    +Gen  ← ≡/(+×10) ♭₂ ≡(˜⊏[1 3 7 9]) ⇡˜▽4
    +Cand ← /◇⊂ ≡(□Gen) ⇡₂5
    +Ps   ← ⊂ [2 3 5 7] ⊏(⊚≡Circ Cand) Cand
    +
    +⬚NaN ↯[∞ 10] Ps
    diff --git a/Task/Circular-primes/Uiua/circular-primes.uiua b/Task/Circular-primes/Uiua/circular-primes.uiua
    deleted file mode 100644
    index b1921de8de..0000000000
    --- a/Task/Circular-primes/Uiua/circular-primes.uiua
    +++ /dev/null
    @@ -1,6 +0,0 @@
    -# Find first 19 circular primes
    -
    -IsP ← =1⧻°/×
    -Rots ← ≡(⋕↻)+1⊙¤⇡⧻.°⋕
    -Circ ← ⨬(⋅0|/↧≡IsP)⊸(=⊙/↧)⟜Rots
    -▽⊸≡Circ▽⊸≡IsP+1⇡1e6
    diff --git a/Task/Circular-primes/Unicon/circular-primes.unicon b/Task/Circular-primes/Unicon/circular-primes.unicon
    new file mode 100644
    index 0000000000..b56cf80d3e
    --- /dev/null
    +++ b/Task/Circular-primes/Unicon/circular-primes.unicon
    @@ -0,0 +1,45 @@
    +link fastprime
    +
    +procedure main(A)
    +   limit := \A[1] | 19
    +   write("First ",limit," circular primes are:")
    +   every writes(" ",(x := circular(genprimes())\limit)|"\n")
    +
    +   limit := 3   # Patience wore out when limit = 4...
    +   writes("Next ",limit," are:")
    +   y := repunit(*x)
    +   cnt := 0
    +   while cnt < limit do {
    +      if (circular(is_prime(y)),cnt +:= 1) then writes(" R(",*y,")")
    +      y := 10*y+1
    +      }
    +   write()
    +
    +   limit := 1   # Patience wore out when limit > 1...
    +   every x := (5003|9887|15073|25031|35317|49081)\limit do {
    +      writes("R(",x,") ")
    +      y := repunit(x)
    +      write("is ",if is_prime(y) then "prime" else "not prime")
    +      }
    +end
    +
    +procedure repunit(x)
    +   every (y := 0, 1 to x, y := 10*y+1)
    +   return y
    +end
    +
    +procedure circular(n)
    +   static seen
    +   initial seen := set()
    +   if member(seen,n) then fail
    +   m := c := n
    +   x := *n
    +   every i := 2 to x do {
    +       if (d := c%10) = 0 then fail
    +       c := (d*10^(x-1))+(c/10)
    +       if not is_prime(numeric(c)) then fail
    +       if member(seen,m >:= c) then fail
    +       }
    +   insert(seen,m)
    +   return n
    +end
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-1.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-1.adb
    new file mode 100644
    index 0000000000..87889f9cd1
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-1.adb
    @@ -0,0 +1,92 @@
    +--  cistercian_numerals.adb
    +--
    +--  test program for the Cistercian Representation Library
    +--  possibly overengineered in order to demonstrate use of types,
    +--  conditions, etc.
    +--  threw in some exception handling
    +
    +--  modern Ada
    +pragma Ada_2022;
    +
    +pragma Assertion_Policy (Check);
    +
    +--  imports
    +
    +with Ada.Text_IO;
    +
    +with Cistercian;
    +with Cistercian.Ascii;
    +with Cistercian.Ascii_Requirements;
    +
    +procedure Cistercian_Numerals is
    +
    +   package IO renames Ada.Text_IO;
    +
    +   Test_Values : constant array (1 .. 8) of Cistercian.Representable_Range :=
    +     [0, 1, 20, 300, 4_000, 5_555, 6_789, 1_983];
    +   --  test values required by task
    +   User_Value  : Integer;
    +   --  value user requests
    +
    +   Temp      : Integer;
    +   Dimension : Cistercian.Ascii_Requirements.Valid_Dimension;
    +
    +begin
    +
    +   loop
    +      begin
    +         IO.Put_Line ("How large would you like your Cistercian numerals?");
    +         IO.Put_Line ("(You must supply an odd number greater than 5)");
    +         IO.Put ("> ");
    +         Dimension :=
    +           Cistercian.Ascii_Requirements.Valid_Dimension'Value (IO.Get_Line);
    +         --  kind of perplexed why I have to assert this
    +         --  when the dynamic predicate should do so
    +         pragma
    +           Assert (Dimension in Cistercian.Ascii_Requirements.Valid_Dimension);
    +         exit;
    +      exception
    +         when others =>
    +            IO.Put_Line ("You must supply an odd number greater than 5");
    +      end;
    +   end loop;
    +
    +   declare
    +      package Cist_Ascii is new Cistercian.Ascii (Dimension);
    +   begin
    +
    +      --  first print test values
    +      for Value of Test_Values loop
    +         begin
    +            IO.Put_Line
    +              ("The Cistercian representation of" & Value'Image & " is:");
    +            Cist_Ascii.Put (Cistercian.From (Value));
    +            IO.New_Line;
    +         exception
    +            when others =>
    +               IO.Put_Line ("Hit an unrecoverable error. Terminating");
    +               return;
    +         end;
    +      end loop;
    +
    +      --  now let user choose own values
    +      loop
    +         begin
    +            IO.Put ("What other value would you like to see? ");
    +            IO.Put_Line ("(enter a negative number to stop) ");
    +            IO.Put ("? ");
    +            User_Value := Integer'Value (IO.Get_Line);
    +            Cist_Ascii.Put (Cistercian.From (User_Value));
    +            IO.New_Line;
    +         exception
    +            when others =>
    +               if User_Value < 0 then
    +                  exit;
    +               end if;
    +               IO.Put_Line ("Please enter a valid number from 0 to 9999.");
    +               IO.Put ("? ");
    +         end;
    +      end loop;
    +   end;
    +
    +end Cistercian_Numerals;
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-2.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-2.adb
    new file mode 100644
    index 0000000000..d2f8f44da9
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-2.adb
    @@ -0,0 +1,36 @@
    +--  cistercian.ads
    +--  representations of Cistercian numbers
    +
    +package Cistercian is
    +
    +   type Representation is private;
    +   --  this type holds the Cistercian representation of a number
    +
    +   subtype Representable_Range is Natural range 0 .. 9999;
    +   --  the system only works with values in this range
    +
    +   function From (Value : Representable_Range) return Representation;
    +   --  converts `Value` to a `Representation`
    +
    +   type Quadrant is (Ones, Tens, Hundreds, Thousands);
    +   --  corresponds to the quadrants used by the system
    +
    +   type Strokes_Enum is (Diag_From_Far, Diag_From_Near, Far, Near, Side);
    +   --  corresponds to the line segments:
    +   --  * Diag_From_Far corresponds to what you'll see in 3, 30, 300, 3000
    +   --  * Diag_From_Near corresponds to what you'll see in 4, 40, 400, 4000
    +   --  * Far corresponds to what you'll see in 1, 10, 100, 1000
    +   --  * Near corresponds to what you'll see in 2, 20, 200, 2000
    +   --  * Side corresponds to what you'll see in 6, 60, 600, 6000
    +   --
    +   --  the others are combinations of these
    +
    +private
    +
    +   type Stroke_Used_Array is array (Strokes_Enum) of Boolean;
    +   --  whether a stroke should be set
    +
    +   type Representation is array (Quadrant) of Stroke_Used_Array;
    +   --  indicates which quadrants' strokes are set
    +
    +end Cistercian;
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-3.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-3.adb
    new file mode 100644
    index 0000000000..1757bd50b3
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-3.adb
    @@ -0,0 +1,49 @@
    +--  cistercian.adb
    +
    +pragma Ada_2022;
    +
    +package body Cistercian is
    +
    +   subtype Digit_Range is Natural range 0 .. 9;
    +
    +   Digit_Strokes : constant array (Digit_Range) of Stroke_Used_Array :=
    +     [0 => [others => False],
    +      1 => [Far => True, others => False],
    +      2 => [Near => True, others => False],
    +      3 => [Diag_From_Far => True, others => False],
    +      4 => [Diag_From_Near => True, others => False],
    +      5 => [Diag_From_Near => True, Far => True, others => False],
    +      6 => [Side => True, others => False],
    +      7 => [Far => True, Side => True, others => False],
    +      8 => [Near => True, Side => True, others => False],
    +      9 => [Far => True, Near => True, Side => True, others => False]];
    +   --  maps each digit to the corresponding strokes
    +   --  this makes it easy for us to assign strokes later
    +
    +   function From (Value : Representable_Range) return Representation is
    +      --  converts Value to a Representation
    +      Result : Representation;
    +
    +      --  obtain digits, then...
    +
    +      Ones_Digit : constant Digit_Range := Value rem 10;
    +      Tens_Digit : constant Digit_Range := ((Value - Ones_Digit) / 10) rem 10;
    +      Hund_Digit : constant Digit_Range :=
    +        ((Value - (Tens_Digit * 10 + Ones_Digit)) / 100) rem 10;
    +      Thou_Digit : constant Digit_Range :=
    +        (Value - (Hund_Digit * 100 + Tens_Digit * 10 + Ones_Digit)) / 1000;
    +
    +   begin
    +
    +      --  assign strokes to corresponding quadrants
    +
    +      Result (Ones) := Digit_Strokes (Ones_Digit);
    +      Result (Tens) := Digit_Strokes (Tens_Digit);
    +      Result (Hundreds) := Digit_Strokes (Hund_Digit);
    +      Result (Thousands) := Digit_Strokes (Thou_Digit);
    +
    +      return Result;
    +
    +   end From;
    +
    +end Cistercian;
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-4.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-4.adb
    new file mode 100644
    index 0000000000..907571096b
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-4.adb
    @@ -0,0 +1,54 @@
    +--  cistercian-motion.ads
    +--
    +--  details information on how to draw each Cistercian stroke
    +--
    +--  this is fairly general, so it should be adaptable to any medium,
    +--  though we have adapted it only to ASCII
    +
    +pragma Ada_2022;
    +
    +with Cistercian; use Cistercian;
    +
    +package Cistercian.Motion is
    +   type Start_Enum is (Near, Far);
    +   --  whether the stroke starts near to or far from the center
    +
    +   subtype Motion_Delta is Integer range -1 .. 1;
    +   --  how the pen should step across the image in a given dimension
    +
    +   type Motion_Record is record
    +      --  record of a stroke's motion:
    +      --  the location to start, as well as which direction to move
    +      Col_Start, Row_Start : Start_Enum;
    +      Col_Delta, Row_Delta : Motion_Delta;
    +   end record;
    +
    +   Stroke_Arrangement :
    +     constant array (Quadrant, Cistercian.Strokes_Enum) of Motion_Record :=
    +       [Ones      =>
    +          [Diag_From_Far  => (Near, Far, 1, 1),
    +           Diag_From_Near => (Near, Near, 1, -1),
    +           Far            => (Near, Far, 1, 0),
    +           Near           => (Near, Near, 1, 0),
    +           Side           => (Far, Far, 0, 1)],
    +        Tens      =>
    +          [Diag_From_Far  => (Near, Far, -1, 1),
    +           Diag_From_Near => (Far, Far, 1, 1),
    +           Far            => (Far, Far, 1, 0),
    +           Near           => (Far, Near, 1, 0),
    +           Side           => (Far, Far, 0, 1)],
    +        Hundreds  =>
    +          [Diag_From_Far  => (Near, Far, 1, -1),
    +           Diag_From_Near => (Near, Near, 1, 1),
    +           Far            => (Near, Far, 1, 0),
    +           Near           => (Near, Near, 1, 0),
    +           Side           => (Far, Near, 0, 1)],
    +        Thousands =>
    +          [Diag_From_Far  => (Far, Near, 1, 1),
    +           Diag_From_Near => (Near, Near, -1, 1),
    +           Far            => (Far, Far, 1, 0),
    +           Near           => (Far, Near, 1, 0),
    +           Side           => (Far, Near, 0, 1)]];
    +   --  maps a quadrant-stoke pair to a motion
    +
    +end Cistercian.Motion;
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-5.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-5.adb
    new file mode 100644
    index 0000000000..6a0a804035
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-5.adb
    @@ -0,0 +1,9 @@
    +--  cistercian-ascii_requirements.ads
    +--
    +--  have to separate this because gnat requires only one compilation unit
    +--  per file
    +
    +package Cistercian.Ascii_Requirements is
    +   subtype Valid_Dimension is Positive
    +   with Static_Predicate => Valid_Dimension > 5;
    +end Cistercian.Ascii_Requirements;
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-6.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-6.adb
    new file mode 100644
    index 0000000000..75e07a62dc
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-6.adb
    @@ -0,0 +1,54 @@
    +--  cistercian-ascii.ads
    +--  ASCII printout of Cistercian representations
    +--  this is generic, so that you can make it as large as you like
    +--  (within reason)
    +
    +pragma Ada_2022;
    +
    +with Cistercian.Ascii_Requirements;
    +
    +generic
    +   Dimension : Cistercian.Ascii_Requirements.Valid_Dimension := 7;
    +package Cistercian.Ascii is
    +
    +   type Block (<>) is private;
    +   --  as i understand it, this particular use of the discriminant
    +   --  prevents the client from instantiating a `Block` without
    +   --  going through one of our generator functions,
    +   --  and the only one of those is `Zero`
    +
    +   function Zero return Block;
    +   --  returns a `Block` corresponding to 0;
    +   --  i.e., a vertical line through the center
    +
    +   function From (Value : Cistercian.Representation) return Block;
    +   --  converts a Cistercian representation to an ASCII block
    +
    +   procedure Put (Value : Cistercian.Representation);
    +   --  print the value to standard output
    +
    +private
    +
    +   Max : constant Integer := (Dimension - 1) / 2;
    +   --  the maximum coordinate we can access in any one dimension
    +   Mid : constant Integer := Max / 2 + 1;
    +   --  midway to `Max`, natch
    +
    +   subtype Cistercian_Ascii_Range is Integer range -(Max + 1) .. (Max + 1);
    +   --  we leave some room for aesthetic reasons
    +   --  (i had another reason originally, but i don't think it applies anymore)
    +
    +   type Block is
    +     array (Cistercian_Ascii_Range, Cistercian_Ascii_Range) of Boolean;
    +   --  an entry should be True iff it should be painted in a stroke
    +
    +   function Zero return Block
    +   is
    +      --  just a vertical line in the middle
    +      ([for Row in Block'Range (1)
    +        => [for Col in Block'Range (2)
    +            => (if Col = 0 and then abs (Row) < Max + 1
    +                then True
    +                else False)]]);
    +
    +end Cistercian.Ascii;
    diff --git a/Task/Cistercian-numerals/Ada/cistercian-numerals-7.adb b/Task/Cistercian-numerals/Ada/cistercian-numerals-7.adb
    new file mode 100644
    index 0000000000..2bdc100450
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Ada/cistercian-numerals-7.adb
    @@ -0,0 +1,76 @@
    +--  cistercian-ascii.adb
    +
    +pragma Ada_2022;
    +
    +with Ada.Text_IO;
    +
    +with Cistercian.Motion;
    +
    +package body Cistercian.Ascii is
    +
    +   package IO renames Ada.Text_IO;
    +   package CM renames Cistercian.Motion;
    +
    +   function From (Value : Cistercian.Representation) return Block is
    +      --  converts the representation to an ASCII block
    +
    +      Result : Block := Zero;
    +
    +      --  the extreme values for rows and columns,
    +      --  as determine by where you want to start and which quadrant you're in
    +
    +      Row_Extremes :
    +        constant array (CM.Start_Enum, Quadrant) of Cistercian_Ascii_Range :=
    +          [CM.Far  => [Ones | Tens => -Max, Hundreds | Thousands => Max],
    +           CM.Near => [Ones | Tens => -1, Hundreds | Thousands => 1]];
    +      Col_Extremes :
    +        constant array (CM.Start_Enum, Quadrant) of Cistercian_Ascii_Range :=
    +          [CM.Far  => [Ones | Hundreds => Max, Tens | Thousands => -Max],
    +           CM.Near => [Ones | Hundreds => 1, Tens | Thousands => -1]];
    +
    +      Row_Pos, Col_Pos     : Cistercian_Ascii_Range;
    +      Row_Delta, Col_Delta : CM.Motion_Delta;
    +
    +   begin
    +
    +      for Place in Quadrant loop
    +         for Stroke in Cistercian.Strokes_Enum when Value (Place) (Stroke) loop
    +
    +            --  obtain position and motion information
    +            Row_Pos :=
    +              Row_Extremes
    +                (CM.Stroke_Arrangement (Place, Stroke).Row_Start, Place);
    +            Col_Pos :=
    +              Col_Extremes
    +                (CM.Stroke_Arrangement (Place, Stroke).Col_Start, Place);
    +            Row_Delta := CM.Stroke_Arrangement (Place, Stroke).Row_Delta;
    +            Col_Delta := CM.Stroke_Arrangement (Place, Stroke).Col_Delta;
    +
    +            --  make the stroke
    +            for Ith in 1 .. Max loop
    +               Result (Row_Pos, Col_Pos) := True;
    +               Row_Pos := @ + Row_Delta;
    +               Col_Pos := @ + Col_Delta;
    +            end loop;
    +
    +         end loop;
    +      end loop;
    +
    +      return Result;
    +
    +   end From;
    +
    +   procedure Put (Value : Cistercian.Representation) is
    +      --  writes Value to standard output
    +      X_At : constant Block := From (Value);
    +   begin
    +
    +      for Row in X_At'Range (1) loop
    +         for Col in X_At'Range (2) loop
    +            IO.Put ((if X_At (Row, Col) then 'X' else ' '));
    +         end loop;
    +         IO.New_Line;
    +      end loop;
    +   end Put;
    +
    +end Cistercian.Ascii;
    diff --git a/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy b/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy
    index d9241a64d1..4e9edb5a4d 100644
    --- a/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy
    +++ b/Task/Cistercian-numerals/EasyLang/cistercian-numerals.easy
    @@ -46,7 +46,7 @@ for n in [ 0 1 20 300 4000 5555 6789 2025 ]
     .
     x = 8
     for i to 8
    -   n = random 10000 - 1
    +   n = random 0 9999
        cist x 44 n
        gtext x - 2 32 n
        x += 12
    diff --git a/Task/Cistercian-numerals/Haskell/cistercian-numerals.hs b/Task/Cistercian-numerals/Haskell/cistercian-numerals.hs
    new file mode 100644
    index 0000000000..6fa4c78239
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Haskell/cistercian-numerals.hs
    @@ -0,0 +1,41 @@
    +import Data.Bits
    +import Data.Char
    +
    +bitflip :: Int -> Int
    +bitflip x = sum [bit (5 - i) | i <- [0 .. 5], testBit x i]
    +
    +digits :: [[Int]]
    +digits =
    + [ [0,0,0,0,0]      -- 0
    + , [1,1,1,1,1]      -- 1
    + , [16,16,16,16,16] -- 2
    + , [1,2,4,8,16]     -- 3
    + , [16,8,4,2,1]     -- 4
    + , [17,9,5,3,1]     -- 5
    + , [0,0,0,0,31]     -- 6
    + , [1,1,1,1,31]     -- 7
    + , [16,16,16,16,31] -- 8
    + , [17,17,17,17,31] -- 9
    + ]
    +
    +digits10   = map reverse digits
    +digits100  = map (map bitflip) digits
    +digits1000 = map reverse digits100
    +
    +showCisterian :: Int -> IO ()
    +showCisterian x =
    +  do
    +    putStr "\27Pq\"3;1;12;33"
    +    body $ digits10 !! d1
    +    body $ [63]
    +    body $ digits !! d0
    +    putChar '-'
    +    body $ digits1000 !! d3
    +    body $ [63]
    +    body $ digits100 !! d2
    +    putStrLn "\27\\\n\n"
    +  where
    +    [d3,d2,d1,d0] = map digitToInt $ tail $ show (x + 10000)
    +    body = putStr . concatMap (replicate 3 . toEnum . (0x3f +))
    +
    +main = mapM_ (\x -> print x >> showCisterian x) [0,1,20,300,4000,5555,6789,3579]
    diff --git a/Task/Cistercian-numerals/Python/cistercian-numerals.py b/Task/Cistercian-numerals/Python/cistercian-numerals-1.py
    similarity index 100%
    rename from Task/Cistercian-numerals/Python/cistercian-numerals.py
    rename to Task/Cistercian-numerals/Python/cistercian-numerals-1.py
    diff --git a/Task/Cistercian-numerals/Python/cistercian-numerals-2.py b/Task/Cistercian-numerals/Python/cistercian-numerals-2.py
    new file mode 100644
    index 0000000000..688c962535
    --- /dev/null
    +++ b/Task/Cistercian-numerals/Python/cistercian-numerals-2.py
    @@ -0,0 +1,68 @@
    +import turtle
    +turtle.setup(startx=0,starty=0)
    +t=turtle.Turtle()
    +screen=turtle.Screen()
    +screen.bgcolor("black")
    +digitsunitones=[
    +    lambda t:None,
    +    lambda t:[t.right(90),t.forward(100)],
    +    lambda t:[t.right(180),t.forward(100),t.right(270),t.forward(100)],
    +    lambda t:[t.right(135),t.forward(141)],
    +    lambda t:[t.right(180),t.forward(100),t.right(225),t.forward(141)],
    +    lambda t:[t.right(180),t.forward(100),t.right(225),t.forward(141),t.right(225),t.forward(100)],
    +    lambda t:[t.right(90),t.up(),t.forward(100),t.right(90),t.down(),t.forward(100)],
    +    lambda t:[t.right(90),t.forward(100),t.right(90),t.forward(100)],
    +    lambda t:[t.right(180),t.forward(100),t.right(270),t.forward(100),t.right(270),t.forward(100)],
    +    lambda t:[t.right(90),t.forward(100),t.right(90),t.forward(100),t.right(90),t.forward(100)]
    +    ]
    +digitsunittens=[
    +    lambda t:None,
    +    lambda t:[t.left(90),t.forward(100)],
    +    lambda t:[t.left(180),t.forward(100),t.left(270),t.forward(100)],
    +    lambda t:[t.left(135),t.forward(141)],
    +    lambda t:[t.left(180),t.forward(100),t.left(225),t.forward(141)],
    +    lambda t:[t.left(180),t.forward(100),t.left(225),t.forward(141),t.left(225),t.forward(100)],
    +    lambda t:[t.left(90),t.up(),t.forward(100),t.left(90),t.down(),t.forward(100)],
    +    lambda t:[t.left(90),t.forward(100),t.left(90),t.forward(100)],
    +    lambda t:[t.left(180),t.forward(100),t.left(270),t.forward(100),t.left(270),t.forward(100)],
    +    lambda t:[t.left(90),t.forward(100),t.left(90),t.forward(100),t.left(90),t.forward(100)]
    +    ]
    +def cistercianinput():
    +    number=input("Input number: ")[:4]
    +    cistercian(number)
    +def cistercian(number):
    +    t.color("white")
    +    t.pensize(5)
    +    t.right(90)
    +    t.up()
    +    t.forward(200)
    +    t.right(180)
    +    t.down()
    +    t.forward(400)
    +    while len(str(number))!=4:
    +        number="0"+number
    +    ones=int(number[3])
    +    tens=int(number[2])
    +    hundreds=int(number[1])
    +    thousands=int(number[0])
    +    digitsunitones[ones](t)
    +    t.up()
    +    t.goto(0,200)
    +    t.seth(90)
    +    t.down()
    +    digitsunittens[tens](t)
    +    t.up()
    +    t.goto(0,-200)
    +    t.seth(270)
    +    t.down()
    +    digitsunittens[hundreds](t)
    +    t.up()
    +    t.goto(0,-200)
    +    t.seth(270)
    +    t.down()
    +    digitsunitones[thousands](t)
    +    t.hideturtle()
    +while True:
    +    cistercianinput()
    +    input("Continue? ")
    +    t.reset()
    diff --git a/Task/Classes/Ada/classes-1.adb b/Task/Classes/Ada/classes-1.adb
    new file mode 100644
    index 0000000000..784995ecb7
    --- /dev/null
    +++ b/Task/Classes/Ada/classes-1.adb
    @@ -0,0 +1,9 @@
    +package My_Package is
    +   type My_Type is tagged private;
    +   procedure Some_Procedure(Item : out My_Type);
    +    function Set(Value : in Integer) return My_Type;
    +private
    +   type My_Type is tagged record
    +      Variable : Integer := -12;
    +   end record;
    +end My_Package;
    diff --git a/Task/Classes/Ada/classes-2.adb b/Task/Classes/Ada/classes-2.adb
    new file mode 100644
    index 0000000000..c67913211f
    --- /dev/null
    +++ b/Task/Classes/Ada/classes-2.adb
    @@ -0,0 +1,13 @@
    + package body My_Package is
    +    procedure Some_Procedure(Item : out My_Type) is
    +    begin
    +       Item := 2 * Item;
    +    end Some_Procedure;
    +
    +    function Set(Value : Integer) return My_Type is
    +       Temp : My_Type;
    +    begin
    +       Temp.Variable := Value;
    +       return Temp;
    +    end Set;
    +end My_Package;
    diff --git a/Task/Classes/Ada/classes-3.adb b/Task/Classes/Ada/classes-3.adb
    new file mode 100644
    index 0000000000..283518b0da
    --- /dev/null
    +++ b/Task/Classes/Ada/classes-3.adb
    @@ -0,0 +1,8 @@
    +with My_Package; use My_Package;
    +
    +procedure Main is
    +   Foo : My_Type; -- Foo is created and initialized to -12
    +begin
    +   Some_Procedure(Foo); -- Foo is doubled
    +   Foo := Set(2007); -- Foo.Variable is set to 2007
    +end Main;
    diff --git a/Task/Classes/COBOL/classes.cob b/Task/Classes/COBOL/classes.cob
    new file mode 100644
    index 0000000000..83440efd2b
    --- /dev/null
    +++ b/Task/Classes/COBOL/classes.cob
    @@ -0,0 +1,66 @@
    +       IDENTIFICATION DIVISION.
    +       CLASS-ID. my-class INHERITS base.
    +
    +       *> The 'INHERITS base' and the following ENVIRONMENT DIVISION
    +       *> are optional (in Visual COBOL).
    +       ENVIRONMENT DIVISION.
    +       CONFIGURATION SECTION.
    +       REPOSITORY.
    +           CLASS base.
    +
    +           *> There is no way (as far as I can tell) of creating a
    +           *> constructor. However, you could wrap it with another
    +           *> method to achieve the desired effect.
    +           *>...
    +
    +           OBJECT.
    +               *> Instance data
    +               DATA DIVISION.
    +               WORKING-STORAGE SECTION.
    +               01  instance-variable PIC 9(8).
    +
    +               *> Properties can have getters and setters automatically
    +               *> generated.
    +               01  a-property        PIC 9(8) PROPERTY.
    +
    +               PROCEDURE DIVISION.
    +
    +               METHOD-ID. some-method.
    +               PROCEDURE DIVISION.
    +                   *> ...
    +               END METHOD some-method.
    +           END OBJECT.
    +       END CLASS my-class.
    +
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. example-class-use.
    +
    +       ENVIRONMENT DIVISION.
    +       CONFIGURATION SECTION.
    +       REPOSITORY.
    +           *> These declarations brings the class and property into
    +           *> scope.
    +           CLASS my-class
    +           PROPERTY a-property.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       *> Declaring a my-class reference variable.
    +       01  instance USAGE OBJECT REFERENCE my-class.
    +
    +       PROCEDURE DIVISION.
    +
    +           *> Invoking a static method or (in this case) a constructor.
    +           INVOKE my-class "new" RETURNING instance
    +
    +           *> Invoking an instance method.
    +           INVOKE instance "some-method"
    +
    +           *> Using the setter and getter of a-property.
    +           MOVE 5 TO a-property OF instance
    +           DISPLAY a-property OF instance
    +
    +           GOBACK
    +           .
    +
    +       END PROGRAM example-class-use.
    diff --git a/Task/Classes/Haxe/classes-1.hx b/Task/Classes/Haxe/classes-1.hx
    new file mode 100644
    index 0000000000..37ec6fbcdf
    --- /dev/null
    +++ b/Task/Classes/Haxe/classes-1.hx
    @@ -0,0 +1,14 @@
    +class BasicClass {
    +    public function basicMethod():Void {
    +        return;
    +    }
    +
    +    public function new() {}
    +}
    +
    +class Main {
    +    static public function main():Void {
    +        var basic_object = new BasicClass();
    +        $type(basic_object);
    +    }
    +}
    diff --git a/Task/Classes/Haxe/classes-2.hx b/Task/Classes/Haxe/classes-2.hx
    new file mode 100644
    index 0000000000..cc84477fdb
    --- /dev/null
    +++ b/Task/Classes/Haxe/classes-2.hx
    @@ -0,0 +1,21 @@
    +class Example (x) # 'x' is a field in class
    +
    +  # method definition
    +  method double ()
    +    return 2 * x
    +  end
    +
    +  # 'initially' block is called on instance construction
    +  initially (x)
    +    if /x # if x is null (not given), then set field to 0
    +      then self.x := 0
    +      else self.x := x
    +end
    +
    +procedure main ()
    +  x1 := Example ()  # new instance with default value of x
    +  x2 := Example (2) # new instance with given value of x
    +  write (x1.x)
    +  write (x2.x)
    +  write (x2.double ()) # call a method
    +end
    diff --git a/Task/Classes/Pluto/classes.pluto b/Task/Classes/Pluto/classes.pluto
    new file mode 100644
    index 0000000000..ad1b02ee3f
    --- /dev/null
    +++ b/Task/Classes/Pluto/classes.pluto
    @@ -0,0 +1,22 @@
    +class bear
    +    -- Constructs a Bear instance passing it a name
    +    -- which is stored in a private field to avoid external mutation.
    +    function __construct(private name) end
    +
    +    -- Property to get the name
    +    function name() return self.name end
    +
    +    -- Method to make a noise.
    +    function make_noise()
    +        print("Growl!")
    +    end
    +end
    +
    +-- Create a new bear instance and assign a reference to it
    +-- to the variable b.
    +local b = new bear("Bruno")
    +
    +-- Print the bear's name.
    +print($"The bear is called {b:name()}.")
    +-- Make a noise.
    +b:make_noise()
    diff --git a/Task/Classes/PowerShell/classes-1.ps1 b/Task/Classes/PowerShell/classes-1.ps1
    new file mode 100644
    index 0000000000..230aa874c2
    --- /dev/null
    +++ b/Task/Classes/PowerShell/classes-1.ps1
    @@ -0,0 +1,28 @@
    +Add-Type -Language CSharp -TypeDefinition @'
    +public class MyClass
    +{
    +    public MyClass()
    +    {
    +    }
    +    public void SomeMethod()
    +    {
    +    }
    +    private int _variable;
    +    public int Variable
    +    {
    +        get { return _variable; }
    +        set { _variable = value; }
    +    }
    +    public static void Main()
    +    {
    +        // instantiate it
    +        MyClass instance = new MyClass();
    +        // invoke the method
    +        instance.SomeMethod();
    +        // set the variable
    +        instance.Variable = 99;
    +        // get the variable
    +        System.Console.WriteLine( "Variable=" + instance.Variable.ToString() );
    +    }
    +}
    +'@
    diff --git a/Task/Classes/PowerShell/classes-2.ps1 b/Task/Classes/PowerShell/classes-2.ps1
    new file mode 100644
    index 0000000000..9c46f92862
    --- /dev/null
    +++ b/Task/Classes/PowerShell/classes-2.ps1
    @@ -0,0 +1,17 @@
    +class MyClass
    +{
    +[type]$MyProperty1
    +[type]$MyProperty2 = "Default value"
    +
    +    # Constructor
    +    MyClass( [type]$MyParameter1, [type]$MyParameter2 )
    +    {
    +    # Code
    +    }
    +
    +    # Method ( [returntype] defaults to [void] )
    +    [returntype] MyMethod( [type]$MyParameter3, [type]$MyParameter4 )
    +    {
    +    # Code
    +    }
    +}
    diff --git a/Task/Classes/PowerShell/classes-3.ps1 b/Task/Classes/PowerShell/classes-3.ps1
    new file mode 100644
    index 0000000000..c87f17b3a8
    --- /dev/null
    +++ b/Task/Classes/PowerShell/classes-3.ps1
    @@ -0,0 +1,33 @@
    +class Banana
    +{
    +# Properties
    +[string]$Color
    +[boolean]$Peeled
    +
    +# Default constructor
    +Banana()
    +    {
    +    $This.Color = "Green"
    +    }
    +
    +# Constructor
    +Banana( [boolean]$Peeled )
    +    {
    +    $This.Color = "Green"
    +    $This.Peeled = $Peeled
    +    }
    +
    +# Method
    +Ripen()
    +    {
    +    If ( $This.Color -eq "Green" ) { $This.Color = "Yellow" }
    +    Else { $This.Color = "Brown" }
    +    }
    +
    +# Method
    +[boolean] IsReadyToEat()
    +    {
    +    If ( $This.Color -eq "Yellow" -and $This.Peeled ) { return $True }
    +    Else { return $False }
    +    }
    +}
    diff --git a/Task/Classes/PowerShell/classes-4.ps1 b/Task/Classes/PowerShell/classes-4.ps1
    new file mode 100644
    index 0000000000..1e021efa64
    --- /dev/null
    +++ b/Task/Classes/PowerShell/classes-4.ps1
    @@ -0,0 +1,5 @@
    +$MyBanana   = [banana]::New()
    +$YourBanana = [banana]::New( $True )
    +$YourBanana.Ripen()
    +If ( -not $MyBanana.IsReadyToEat() -and $YourBanana.IsReadyToEat() )
    +    { $MySecondBanana = $YourBanana }
    diff --git a/Task/Classes/Rebol/classes.rebol b/Task/Classes/Rebol/classes.rebol
    new file mode 100644
    index 0000000000..8b13f49fd0
    --- /dev/null
    +++ b/Task/Classes/Rebol/classes.rebol
    @@ -0,0 +1,39 @@
    +Rebol [
    +    Title: "Classes"
    +    URL: http://rosettacode.org/wiki/Classes
    +]
    +
    +; Objects are derived from the base 'object!' type. Rebol uses a
    +; prototyping object system, so any object can be treated as a class,
    +; from which to derive others.
    +
    +cowboy: make object! [
    +	name: "Tex"  ; Instance variable.
    +	hi: does [   ; Method.
    +		print [self/name ": Howdy!"]]
    +]
    +
    +; I create two instances of the 'cowboy' class.
    +
    +tex: make cowboy []
    +roy: make cowboy [
    +	name: "Roy"  ; Override 'name' property.
    +]
    +
    +print "Say 'hello', boys:"  tex/hi  roy/hi
    +print ""
    +
    +; Now I'll subclass 'cowboy'. Subclassing looks a lot like instantiation:
    +
    +legend: make cowboy [
    +	deed: "..."
    +	boast: does [
    +		print [self/name ": I once" self/deed "!"]]
    +]
    +
    +; Instancing the legend:
    +
    +pecos: make legend [name: "Pecos Bill"  deed: "lassoed a twister"]
    +
    +print "Howdy, Pecos!"  pecos/hi
    +print "Tell us about yourself?"  pecos/boast
    diff --git a/Task/Classes/Red/classes.red b/Task/Classes/Red/classes.red
    new file mode 100644
    index 0000000000..113f042331
    --- /dev/null
    +++ b/Task/Classes/Red/classes.red
    @@ -0,0 +1,30 @@
    +bike: object [
    +	frame-material: "aluminium"
    +	wheel-size: 29
    +	color: "black"
    +	set-color: func [value][color: value]
    +]
    +
    +e-bike: make bike [
    +	motor-type: "brushless"
    +]
    +print ["e-bike/frame-material : " e-bike/frame-material]
    +print ["e-bike/motor-type     : " e-bike/motor-type]
    +
    +
    +mountain-bike: make bike [
    +	fork-stroke: 150
    +]
    +
    +green-mountain-bike: copy mountain-bike
    +green-mountain-bike/set-color "green"
    +
    +print ["green-mountain-bike/wheel-size  : " green-mountain-bike/wheel-size]
    +print ["green-mountain-bike/fork-stroke : " green-mountain-bike/fork-stroke]
    +print ["green-mountain-bike/color       : " green-mountain-bike/color]
    +
    +default-mountain-bike: copy mountain-bike
    +
    +print ["default-mountain-bike/wheel-size  : " default-mountain-bike/wheel-size]
    +print ["default-mountain-bike/fork-stroke : " default-mountain-bike/fork-stroke]
    +print ["default-mountain-bike/color       : " default-mountain-bike/color]
    diff --git a/Task/Classes/V-(Vlang)/classes-4.v b/Task/Classes/V-(Vlang)/classes-4.v
    index 565fbd7f31..4f7637f4ae 100644
    --- a/Task/Classes/V-(Vlang)/classes-4.v
    +++ b/Task/Classes/V-(Vlang)/classes-4.v
    @@ -1,8 +1,10 @@
    -// 'pub'
    +// all fields below 'pub mut:' would be public and mutable, while those above it, would not
     
     pub struct Public {
    -	pub:
    -	data string
    +	data_1 string = "Hello" // other modules can not change
    +	pub mut:
    +	data_2 string // other modules can change
    +	data_3 string // other modules can change
     }
     
     struct Private {
    @@ -19,8 +21,8 @@ module sample
     
     @[noinit]
     pub struct Information {
    -pub:
    -	data string
    +	pub:
    +	data string = "Mike"
     }
     
     // factory function
    diff --git a/Task/Closest-pair-problem/Ada/closest-pair-problem.adb b/Task/Closest-pair-problem/Ada/closest-pair-problem.adb
    new file mode 100644
    index 0000000000..9bd7f30bbc
    --- /dev/null
    +++ b/Task/Closest-pair-problem/Ada/closest-pair-problem.adb
    @@ -0,0 +1,67 @@
    +with Ada.Numerics.Generic_Elementary_Functions;
    +with Ada.Text_IO;
    +
    +procedure Closest is
    +   package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);
    +
    +   Dimension : constant := 2;
    +   type Vector is array (1 .. Dimension) of Float;
    +   type Matrix is array (Positive range <>) of Vector;
    +
    +   -- calculate the distance of two points
    +   function Distance (Left, Right : Vector) return Float is
    +      Result : Float := 0.0;
    +      Offset : Natural := 0;
    +   begin
    +      loop
    +         Result := Result + (Left(Left'First + Offset) - Right(Right'First + Offset))**2;
    +         Offset := Offset + 1;
    +         exit when Offset >= Left'Length;
    +      end loop;
    +      return Math.Sqrt (Result);
    +   end Distance;
    +
    +   -- determine the two closest points inside a cloud of vectors
    +   function Get_Closest_Points (Cloud : Matrix) return Matrix is
    +      Result : Matrix (1..2);
    +      Min_Distance : Float;
    +   begin
    +      if Cloud'Length(1) < 2 then
    +         raise Constraint_Error;
    +      end if;
    +      Result := (Cloud (Cloud'First), Cloud (Cloud'First + 1));
    +      Min_Distance := Distance (Cloud (Cloud'First), Cloud (Cloud'First + 1));
    +      for I in Cloud'First (1) .. Cloud'Last(1) - 1 loop
    +         for J in I + 1 .. Cloud'Last(1) loop
    +            if Distance (Cloud (I), Cloud (J)) < Min_Distance then
    +               Min_Distance := Distance (Cloud (I), Cloud (J));
    +               Result := (Cloud (I), Cloud (J));
    +            end if;
    +         end loop;
    +      end loop;
    +      return Result;
    +   end Get_Closest_Points;
    +
    +   Test_Cloud : constant Matrix (1 .. 10) := ( (5.0, 9.0),  (9.0, 3.0),
    +                                               (2.0, 0.0),  (8.0, 4.0),
    +                                               (7.0, 4.0),  (9.0, 10.0),
    +                                               (1.0, 9.0),  (8.0, 2.0),
    +                                               (0.0, 10.0), (9.0, 6.0));
    +   Closest_Points : Matrix := Get_Closest_Points (Test_Cloud);
    +
    +   Second_Test : constant Matrix (1 .. 10) := ( (0.654682, 0.925557), (0.409382, 0.619391),
    +                                                (0.891663, 0.888594), (0.716629,   0.9962),
    +                                                (0.477721, 0.946355), (0.925092,  0.81822),
    +                                                (0.624291, 0.142924), (0.211332, 0.221507),
    +                                                (0.293786, 0.691701), (0.839186,  0.72826));
    +   Second_Points : Matrix := Get_Closest_Points (Second_Test);
    +begin
    +   Ada.Text_IO.Put_Line ("Closest Points:");
    +   Ada.Text_IO.Put_Line ("P1: " & Float'Image (Closest_Points (1) (1)) & " " & Float'Image (Closest_Points (1) (2)));
    +   Ada.Text_IO.Put_Line ("P2: " & Float'Image (Closest_Points (2) (1)) & " " & Float'Image (Closest_Points (2) (2)));
    +   Ada.Text_IO.Put_Line ("Distance: " & Float'Image (Distance (Closest_Points (1), Closest_Points (2))));
    +   Ada.Text_IO.Put_Line ("Closest Points 2:");
    +   Ada.Text_IO.Put_Line ("P1: " & Float'Image (Second_Points (1) (1)) & " " & Float'Image (Second_Points (1) (2)));
    +   Ada.Text_IO.Put_Line ("P2: " & Float'Image (Second_Points (2) (1)) & " " & Float'Image (Second_Points (2) (2)));
    +   Ada.Text_IO.Put_Line ("Distance: " & Float'Image (Distance (Second_Points (1), Second_Points (2))));
    +end Closest;
    diff --git a/Task/Closest-pair-problem/Phix/closest-pair-problem.phix b/Task/Closest-pair-problem/Phix/closest-pair-problem.phix
    index 65465bd058..fac3c948bc 100644
    --- a/Task/Closest-pair-problem/Phix/closest-pair-problem.phix
    +++ b/Task/Closest-pair-problem/Phix/closest-pair-problem.phix
    @@ -1,100 +1,90 @@
    -(phixonline)-->
    - with javascript_semantics
    - function bruteForceClosestPair(sequence s)
    -     atom {x1,y1} = s[1], {x2,y2} = s[2],
    -          dx = x1-x2, dy = y1-y2,
    -          mind = dx*dx+dy*dy
    -     sequence minp = s[1..2]
    -     for i=1 to length(s)-1 do
    -         {x1,y1} = s[i]
    -         for j=i+1 to length(s) do
    -             {x2,y2} = s[j]
    -             dx = x1-x2
    -             dx = dx*dx
    -             if dx<mind then
    -                 dy = y1-y2
    -                 dx += dy*dy
    -                 if dx<mind then
    -                     mind = dx
    -                     minp = {s[i],s[j]}
    -                 end if
    -             end if
    -         end for
    -     end for
    -     return {sqrt(mind),minp}
    - end function
    +with javascript_semantics
    +function bruteForceClosestPair(sequence s)
    +    atom {x1,y1} = s[1], {x2,y2} = s[2],
    +         dx = x1-x2, dy = y1-y2,
    +         mind = dx*dx+dy*dy
    +    sequence minp = s[1..2]
    +    for i,si in s to length(s)-1 do
    +        {x1,y1} = si
    +        for sj in s from i+1 do
    +            {x2,y2} = sj
    +            dx = x1-x2
    +            dx = dx*dx
    +            if dxsequence testset = sq_rnd(repeat({1,1},10000))
    - atom t0 = time()
    - {atom d, sequence points} = bruteForceClosestPair(testset)
    - -- (Sorting the final point pair makes brute/dc more likely to tally. Note however
    - --  when >1 equidistant pairs exist, brute and dc may well return different pairs;
    - --  it is only a problem if they decide to return different minimum distances.)
    - atom {{x1,y1},{x2,y2}} = sort(deep_copy(points))
    - printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0})
    +sequence testset = sq_rnd(repeat({1,1},10000))
    +atom t0 = time()
    +atom {d, {{x1,y1},{x2,y2}}} = bruteForceClosestPair(testset)
    +-- (Sorting the final point pair makes brute/dc more likely to tally. Note however
    +--  when >1 equidistant pairs exist, brute and dc may well return different pairs;
    +--  it is only a problem if they decide to return different minimum distances.)
    +printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0})
     
    - t0 = time()
    - constant X = 1, Y = 2
    - sequence xP = sort(deep_copy(testset))
    +t0 = time()
    +constant X = 1, Y = 2
    +sequence xP = sort(deep_copy(testset)),
    +         yP = sort_columns(deep_copy(testset),{Y})
     
    - function byY(sequence p1, p2)
    -     return compare(p1[Y],p2[Y])
    - end function
    - sequence yP = custom_sort(routine_id("byY"),deep_copy(testset))
    +function distsq(sequence p1,p2)
    +    atom {x1,y1} = p1, {x2,y2} = p2
    +    x1 -= x2
    +    y1 -= y2
    +    return x1*x1 + y1*y1
    +end function
     
    - function distsq(sequence p1,p2)
    -     atom {x1,y1} = p1, {x2,y2} = p2
    -     x1 -= x2
    -     y1 -= y2
    -     return x1*x1 + y1*y1
    - end function
    +function closestPair(sequence xP, yP)
    +-- where xP is P(1) .. P(N) sorted by x coordinate, and
    +--       yP is P(1) .. P(N) sorted by y coordinate (ascending order)
    +    integer N = length(xP),
    +         midN = floor(N/2)
    +    assert(length(yP)=N)
    +    if N<=3 then
    +        return bruteForceClosestPair(xP)
    +    end if
    +    sequence xL = xP[1..midN],
    +             xR = xP[midN+1..N],
    +             yL = {},
    +             yR = {}
    +    atom xm = xP[midN][X]
    +    for yi in yP do
    +        if yi[X]<=xm then
    +            yL = append(yL,yi)
    +        else
    +            yR = append(yR,yi)
    +        end if
    +    end for
    +    {atom dmin, sequence pairMin} = min(closestPair(xL, yL),
    +                                        closestPair(xR, yR))
    +    sequence yS = {}
    +    for yi in yP do
    +        if abs(xm-yi[X])=dmin then exit end if
    +            d = distsq(yk,yi)
    +            if dfunction closestPair(sequence xP, yP)
    - -- where xP is P(1) .. P(N) sorted by x coordinate, and
    - --       yP is P(1) .. P(N) sorted by y coordinate (ascending order)
    -     integer N = length(xP),
    -          midN = floor(N/2)
    -     assert(length(yP)=N)
    -     if N<=3 then
    -         return bruteForceClosestPair(xP)
    -     end if
    -     sequence xL = xP[1..midN],
    -              xR = xP[midN+1..N],
    -              yL = {},
    -              yR = {}
    -     atom xm = xP[midN][X]
    -     for i=1 to N do
    -         if yP[i][X]<=xm then
    -             yL = append(yL,yP[i])
    -         else
    -             yR = append(yR,yP[i])
    -         end if
    -     end for
    -     {atom dL, sequence pairL} = closestPair(xL, yL)
    -     {atom dR, sequence pairR} = closestPair(xR, yR)
    -     {atom dmin, sequence pairMin} = min({dL, pairL},{dR, pairR})
    -     sequence yS = {}
    -     for i=1 to length(yP) do
    -         if abs(xm-yP[i][X])<dmin then
    -             yS = append(yS,yP[i])
    -         end if
    -     end for
    -     integer nS = length(yS)
    -     {atom closest, sequence cPair} = {dmin*dmin, pairMin}
    -     for i=1 to nS-1 do
    -         integer k = i + 1
    -         while k<=nS and (yS[k][Y]-yS[i][Y])<dmin do
    -             d = distsq(yS[k],yS[i])
    -             if d<closest then
    -                 {closest, cPair} = {d, {yS[k], yS[i]}}
    -             end if
    -             k += 1
    -         end while
    -     end for
    -     return {sqrt(closest), cPair}
    - end function
    -
    - {d,points} = closestPair(xP,yP)
    - {{x1,y1},{x2,y2}} = sort(deep_copy(points)) -- (see note above)
    - printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0})
    -
    - with javascript_semantics
    - function decrat(string s)
    -     integer nom = 0,
    -             denom = 1
    -     assert(s[1..2]="0.")
    -     for i=3 to length(s) do
    -         integer ch = s[i]
    -         assert(ch>='0' and ch<='9')
    -         nom = nom*10 + ch-'0'
    -         denom *= 10
    -     end for
    -     return sq_div({nom,denom},gcd(nom,denom))
    - end function
    +with javascript_semantics
    +function decrat(string s)
    +    integer nom = 0,
    +            denom = 1
    +    assert(s[1..2]="0.")
    +    for i=3 to length(s) do
    +        integer ch = s[i]
    +        assert(ch>='0' and ch<='9')
    +        nom = nom*10 + ch-'0'
    +        denom *= 10
    +    end for
    +    return sq_div({nom,denom},gcd(nom,denom))
    +end function
     
    - ?decrat("0.9054054")
    - ?decrat("0.518518")
    - ?decrat("0.75")
    -
    - with javascript_semantics
    - ?elapsed(7259)
    - ?elapsed(86400)
    - ?elapsed(6000000)
    -
    - with javascript_semantics
    - include timedate.e
    - ?elapsed(6000000-timedelta(days:=6,hours:=10))
    - stable
    +					all [s = 0  n = 3] [00.00.127]	; new birth
    +					true [black]					; barren
    +				]
    +				xy: map-to-pixels x y
    +				append draws compose [fill-pen (color) circle (xy) (rad)]	
    +				
    +				; process next generation
    +				nxt/:x/:y: either any [
    +					all [mat/:x/:y = 1  n > 1  n < 4] ; lives on
    +					all [mat/:x/:y = 0  n = 3]		  ; birth
    +				][1][0]
    +			]
    +		]
    +		; swap matrix
    +		t: mat  mat: nxt  nxt: t
    +		if (gen: gen + 1) > maxgen [init]
    +	] ; changer
    +]
    +
    +matrix-rand: func [a b][collect [loop a [keep/only collect [loop b [keep random/only [0 1]]]]]]
    +matrix-zero: func [a b][collect [loop a [keep/only collect [loop b [keep 0]]]]]
    +
    +; neighbour counting in a wrapped world!
    +nb: func [x y][
    +	xm1: x - 1  if xm1 < 1    [xm1: xmax]
    +	xp1: x + 1  if xp1 > xmax [xp1: 1]
    +	ym1: y - 1  if ym1 < 1    [ym1: ymax]
    +	yp1: y + 1  if yp1 > ymax [yp1: 1]
    +	mat/:xm1/:ym1 + mat/:xm1/:y + mat/:xm1/:yp1 +
    +	mat/:x/:ym1   +               mat/:x/:yp1   +
    +	mat/:xp1/:ym1 + mat/:xp1/:y + mat/:xp1/:yp1
    +]
    +
    +xmax: 100 ; number of cells, horiz
    +ymax: 100 ; vert
    +dispx: xmax * 10 ; display size for 10 pixels cell size
    +dispy: ymax * 10 ; vert
    +rad: 0 ; radial size for cells (calculated)
    +
    +; matrixes for generations:
    +mat: matrix-rand xmax ymax
    +nxt: matrix-zero xmax ymax
    +
    +; counters:
    +gen: 0
    +maxgen: 500
    +
    +init: does [
    +	mat: matrix-rand xmax ymax
    +	nxt: matrix-zero xmax ymax
    +	gen: 0
    +]
    +
    +main: func [/local p][
    +	p: make plotter []
    +	p/header "Conway's Game of Life"
    +	p/display-size: to-pair reduce [dispx dispy] ; display size regardless for x and y range
    +	p/x1: 1  p/x2: xmax
    +	p/y1: 1  p/y2: ymax
    +	p/fn: func [x][x] ; dummy, not used
    +	rad: (min (dispx / xmax) (dispy / ymax)) / 2
    +	p/draw ; generate drawing
    +	p/draws/line-width: 0
    +	;p/draws/pen: white
    +	p/show ; display it
    +]	
    +main
    diff --git a/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-1.scm b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-1.scm
    new file mode 100644
    index 0000000000..81c4614591
    --- /dev/null
    +++ b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-1.scm
    @@ -0,0 +1,89 @@
    +;;An R6RS Scheme implementation of Conway's Game of Life --- assumes
    +;;all cells outside the defined grid are dead
    +
    +;if n is outside bounds of list, return 0 else value at n
    +(define (nth n lst)
    +  (cond ((> n (length lst)) 0)
    +        ((< n 1) 0)
    +        ((= n 1) (car lst))
    +        (else (nth (- n 1) (cdr lst)))))
    +
    +;return the next state of the supplied universe
    +(define (next-universe universe)
    +  ;value at (x, y)
    +  (define (cell x y)
    +    (if (list? (nth y universe))
    +        (nth x (nth y universe))
    +        0))
    +  ;sum of the values of the cells surrounding (x, y)
    +  (define (neighbor-sum x y)
    +    (+ (cell (- x 1) (- y 1))
    +       (cell (- x 1) y)
    +       (cell (- x 1) (+ y 1))
    +       (cell x (- y 1))
    +       (cell x (+ y 1))
    +       (cell (+ x 1) (- y 1))
    +       (cell (+ x 1) y)
    +       (cell (+ x 1) (+ y 1))))
    +  ;next state of the cell at (x, y)
    +  (define (next-cell x y)
    +    (let ((cur (cell x y))
    +          (ns (neighbor-sum x y)))
    +      (cond ((and (= cur 1)
    +                  (or (< ns 2) (> ns 3)))
    +             0)
    +            ((and (= cur 0) (= ns 3))
    +             1)
    +            (else cur))))
    +  ;next state of row n
    +  (define (row n out)
    +    (let ((w (length (car universe))))
    +      (if (= (length out) w)
    +          out
    +          (row n
    +               (cons (next-cell (- w (length out)) n)
    +                     out)))))
    +  ;a range of ints from bot to top
    +  (define (int-range bot top)
    +    (if (> bot top) '()
    +        (cons bot (int-range (+ bot 1) top))))
    +  (map (lambda (n)
    +         (row n '()))
    +       (int-range 1 (length universe))))
    +
    +;represent the universe as a string
    +(define (universe->string universe)
    +  (define (prettify row)
    +    (apply string-append
    +           (map (lambda (b)
    +                  (if (= b 1) "#" "-"))
    +                row)))
    +  (if (null? universe)
    +      ""
    +      (string-append (prettify (car universe))
    +                     "\n"
    +                     (universe->string (cdr universe)))))
    +
    +;starting with seed, show reps states of the universe
    +(define (conway seed reps)
    +  (when (> reps 0)
    +    (display (universe->string seed))
    +    (newline)
    +    (conway (next-universe seed) (- reps 1))))
    +
    +;; --- Example Universes --- ;;
    +
    +;blinker in a 3x3 universe
    +(conway '((0 1 0)
    +          (0 1 0)
    +          (0 1 0)) 5)
    +
    +;glider in an 8x8 universe
    +(conway '((0 0 1 0 0 0 0 0)
    +          (0 0 0 1 0 0 0 0)
    +          (0 1 1 1 0 0 0 0)
    +          (0 0 0 0 0 0 0 0)
    +          (0 0 0 0 0 0 0 0)
    +          (0 0 0 0 0 0 0 0)
    +          (0 0 0 0 0 0 0 0)
    +          (0 0 0 0 0 0 0 0)) 30)
    diff --git a/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-2.scm b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-2.scm
    new file mode 100644
    index 0000000000..b692b693b0
    --- /dev/null
    +++ b/Task/Conways-Game-of-Life/Scheme/conways-game-of-life-2.scm
    @@ -0,0 +1,62 @@
    +(import (srfi 231))
    +
    +(define (pad-array-with-zeros a N)
    +
    +  ;; Pad two-dimensional array with N rows and columns of zeros,
    +  ;; top and bottom, left and right.
    +  ;; Assumes that the domain of a has zero lower bounds.
    +
    +  (let* ((domain (array-domain a))
    +         (m      (interval-upper-bound domain 0))
    +         (n      (interval-upper-bound domain 1))
    +         (a_     (array-getter a)))
    +    (make-array (interval-dilate domain (vector (- N) (- N)) (vector N N))
    +                (lambda (i j)
    +                  (or (and (< -1 i m) (< -1 j n) (a_ i j))
    +                      0)))))
    +
    +(define (neighbor-count a)
    +
    +  ;; Returns a generalized array that contains the number
    +  ;; of 1s in the 8 cells surrounding each cell in the original array.
    +
    +  (let* ((big-a      (array-copy! (pad-array-with-zeros a 1)
    +                                  (array-storage-class a)))
    +         (domain     (array-domain a))
    +         (translates (map (lambda (translation)
    +                            (array-extract (array-translate big-a translation) domain))
    +                          '(#(1 0) #(0 1) #(-1 0) #(0 -1)
    +                            #(1 1) #(1 -1) #(-1 1) #(-1 -1)))))
    +    (apply array-map + translates)))
    +
    +(define (game-rules a neighbor-count)
    +
    +  ;; a is the value in a single cell, neighbor-count is the count of 1s in
    +  ;; its 8 neighboring cells.
    +
    +  (if (zero? a)
    +      (if (eqv? neighbor-count 3) 1 0)
    +      (if (<= 2 neighbor-count 3) 1 0)))
    +
    +(define (advance a)
    +  (array-copy! (array-map game-rules a (neighbor-count a))
    +               (array-storage-class a)))
    +
    +(define life-storage-class u1-storage-class)
    +
    +(define glider
    +  (list*->array
    +   2
    +   '((0 0 0 0 0 0)
    +     (0 0 1 0 0 0)
    +     (0 0 0 1 0 0)
    +     (0 1 1 1 0 0)
    +     (0 0 0 0 0 0)
    +     (0 0 0 0 0 0))
    +   life-storage-class))
    +
    +(do ((i 0 (+ i 1))
    +     (pattern glider (advance pattern)))
    +    ((= i 5))
    +  (pretty-print (array->list* pattern))
    +  (newline))
    diff --git a/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua b/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua
    index 6f79a3931c..fe9d89fede 100644
    --- a/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua
    +++ b/Task/Conways-Game-of-Life/Uiua/conways-game-of-life.uiua
    @@ -1,4 +1,4 @@
    -Life ← ↥⊙↧∩=3:⊙.2-:⊙./+≡↻♭₂-1⇡3_3¤.
    +Life ← ↥⊙↧∩=3⊃⋅∘⊙∘2⊸˜-/+≡↻♭₂-1⇡3_3⊸¤
     ⁅×0.6 ≡₀⋅⚂ ↯⟜⊚ 50 # Init
     ⇌◌⍥(⟜⊂Life)300⟜¤  # Run
     ≡(▽⟜≡▽4)          # Upscale
    diff --git a/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vbs b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vbs
    new file mode 100644
    index 0000000000..66315d235d
    --- /dev/null
    +++ b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-1.vbs
    @@ -0,0 +1,85 @@
    +option explicit
    +const tlcr=3, tlcc=3
    +const maxdim=15
    +
    +dim a(15,15)
    +dim b(15,15)
    +dim ans0:ans0=chr(27)&"["
    +dim gen,n
    +
    +erase a
    +'glider
    +a(0,1)=true:a(1,2)=true:a(2,0)=true:a(2,1)=true:a(2,2)=true
    +'blinker
    +a(3,13)=true:a(4,13)=true:a(5,13)=true
    +'beacon
    +a(11,1)=true:a(11,2)=true: a(12,1)=true:a(12,2)=true
    +a(13,3)=true:a(13,4)=true: a(14,3)=true:a(14,4)=true
    +
    +gen=0
    +doframe
    +
    +do
    +  display
    +  wscript.sleep(100)
    +  n=newgen
    +loop until n=0
    +display
    +
    +sub cls()  wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub 'hide cursor too
    +sub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & ";" & c & "f"  & s :end sub
    +function iif(a,b,c) if a then iif=b else iif=c end if :end function
    +
    +sub doframe
    +  dim r,c,s
    +   const frame="@"
    +   cls
    +   toxy 1,tlcc-1, "Conway's Game of Life"
    +   toxy tlcr-1,tlcc-1,string(maxdim+3,frame)
    +   s=frame&space(maxdim+1)&frame
    +   for r=0 to maxdim
    +      toxy tlcr+r,tlcc-1,s
    +   next
    +   toxy tlcr+maxdim+1,tlcc-1,string(maxdim+3,frame)
    +end sub
    +
    +sub display
    +dim r,c
    +const pix="#"
    +for r=0 to maxdim
    +   for c=0 to maxdim
    +      toxy tlcr+r,tlcc+c,iif (a(r,c),pix," ")
    +    next
    +next
    +toxy tlcr+maxdim+2,tlcc-1,gen & " " & n
    +toxy tlcr+maxdim+3,tlcc-1,""
    +gen=gen+1
    +end sub
    +
    +function newgen
    +  dim r,c,cnt,cp,cm,rp,rm
    +   for r=0 to maxdim
    +     for c=0 to maxdim
    +         cp=(c+1) and maxdim    'wrap around
    +         cm=(c-1) and maxdim
    +         rp=(r+1) and maxdim
    +         rm=(r-1) and maxdim
    +         cnt=0
    +         cnt=- a(rp,cp) - a(rp,c) - a(rp,cm)  'true =-1
    +         cnt=cnt- a(r,cp)-  a(r,cm)
    +         cnt=cnt- a(rm,cp)- a(rm,c) - a(rm,cm)
    +
    +         if a(r,c) then
    +            b(r,c)=iif (cnt=2 or cnt=3,true,false)
    +         else
    +            b(r,c)=iif (cnt=3,true,false)
    +         end if
    +     next
    +   next
    +   for r=0 to maxdim
    +     for c=0 to maxdim
    +        a(r,c)=b(r,c)
    +        newgen=newgen- b(r,c)
    +     next
    +   next
    +end function
    diff --git a/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vbs b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vbs
    new file mode 100644
    index 0000000000..880d9c38ad
    --- /dev/null
    +++ b/Task/Conways-Game-of-Life/VBScript/conways-game-of-life-2.vbs
    @@ -0,0 +1,105 @@
    +option explicit
    +const pix="##"
    +const cl_on=16
    +const cl_mnum=15
    +randomize timer
    +const tlcr=2, tlcc=2
    +const maxdim =31
    +settitle "Conway's game of life"
    +
    +dim a(31,31)
    +
    +dim ans0:ans0=chr(27)&"["
    +dim gen,n
    +gen=0
    +paintframe
    +'init1      'objects
    +init2 400   'random
    +
    +do
    +  n=nextgen
    +  toxy tlcr-1,tlcc+maxdim*2+4,gen & " " & n
    +  toxy tlcr,tlcc+maxdim*2+3,""
    +  gen=gen+1
    +loop until n=0
    +
    +sub pause() wscript.stdout.write vbcrlf & "Press Enter":wscript.stdin.readline: end sub
    +sub settitle(s)  wscript.StdOut.Write chr(27)&"]0;"& s &chr(7):end sub
    +sub cls()  wscript.StdOut.Write ans0 &"2J"&ans0 &"?25l":end sub
    +sub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & ";" & c & "f"  & s :end sub
    +function iif(a,b,c) if a then iif=b else iif=c end if :end function
    +
    +sub init1
    +dim x
    +update 0,1,1,x:update 1,2,1,x:update 2,0,1,x:update 2,1,1,x:update 2,2,1,x
    +update 3,13,1,x:update 4,13,1,x:update 5,13,1,x
    +update 11,1,1,x:update 11,2,1,x: update 12,1,1,x:update 12,2,1,x
    +update 13,3,1,x:update 13,4,1,x: update 14,3,1,x:update 14,4,1,x
    +end sub
    +
    +sub init2 (n)
    +dim i,r,c,x
    +for i=1 to n
    +   do
    +     r=cint(rnd*maxdim)
    +     c=cint(rnd*maxdim)
    +   loop until (a(r,c) and cl_on)=0
    +   update r,c,1,x
    +next
    +end sub
    +
    +sub paintframe
    +  dim r,c,s
    +  const frame="@"
    +  cls
    +  'toxy 1,tlcc-1, "Conway's Game of Life"
    +  toxy tlcr-1,tlcc-1,string(maxdim*2+4,frame)
    +  s=frame&space(maxdim*2+2)&frame
    +  for r=0 to maxdim
    +    toxy tlcr+r,tlcc-1,s
    +  next
    +  toxy tlcr+maxdim+1,tlcc-1,string(maxdim*2+4,frame)
    +end sub
    +
    +function nextgen()
    +  dim r,c,pre,cnt,a1,onoff,chg
    +  nextgen=0
    +  a1=a                                 'does a hard a copy of a
    +  for r=0 to maxdim
    +    for c=0 to maxdim
    +      if a1(r,c)then                'check only cells alive or having neighbors
    +        pre=a1(r,c) and cl_on
    +        cnt=a1(r,c) and cl_mnum
    +        'check life condition and update cell
    +        if pre<>0  and  (cnt<2 or cnt>3)  then
    +          update r,c,0,nextgen
    +        elseif pre=0  and cnt=3 then
    +          update r,c,1,nextgen
    +        end if
    +      end if
    +    next
    +   next
    +end function
    +
    +sub update(r,c,onoff,nextgen)
    +'displays cell and update neighbors count in neighbors
    +dim cp,cm,rp,rm,inc,mask
    +   mask=iif(onoff,cl_on,0)
    +   a(r,c)= (a(r,c) and cl_mnum) or mask       'update cell
    +   toxy tlcr+r,tlcc+c*2,iif (onoff,pix,"  ")  'display cell
    +   cp=(c+1) and maxdim                 'wrap around
    +   cm=(c-1) and maxdim
    +   rp=(r+1) and maxdim
    +   rm=(r-1) and maxdim
    +   if onoff then inc=1 else inc=-1
    +   'update count in neighbors
    +   a(rp,cp)=(a(rp,cp) and cl_on) or ((a(rp,cp) and cl_mnum)+inc)
    +   a(rp,c)=(a(rp,c) and cl_on) or ((a(rp,c) and cl_mnum)+inc)
    +   a(rp,cm)=(a(rp,cm) and cl_on) or ((a(rp,cm) and cl_mnum)+inc)
    +   a(r,cp)=(a(r,cp) and cl_on) or ((a(r,cp) and cl_mnum)+inc)
    +   a(r,cm)=(a(r,cm) and cl_on) or ((a(r,cm) and cl_mnum)+inc)
    +   a(rm,cp)=(a(rm,cp) and cl_on) or ((a(rm,cp) and cl_mnum)+inc)
    +   a(rm,c)=(a(rm,c) and cl_on) or ((a(rm,c) and cl_mnum)+inc)
    +   a(rm,cm)=(a(rm,cm) and cl_on) or ((a(rm,cm) and cl_mnum)+inc)
    +   nextgen=nextgen+1
    +end sub
    diff --git a/Task/Copy-a-string/Ada/copy-a-string-1.adb b/Task/Copy-a-string/Ada/copy-a-string-1.adb
    new file mode 100644
    index 0000000000..45c6d81f92
    --- /dev/null
    +++ b/Task/Copy-a-string/Ada/copy-a-string-1.adb
    @@ -0,0 +1,2 @@
    +Src : String := "Hello";
    +Dest : String := Src;
    diff --git a/Task/Copy-a-string/Ada/copy-a-string-2.adb b/Task/Copy-a-string/Ada/copy-a-string-2.adb
    new file mode 100644
    index 0000000000..dd7081031a
    --- /dev/null
    +++ b/Task/Copy-a-string/Ada/copy-a-string-2.adb
    @@ -0,0 +1,3 @@
    +Src : String := "Rosetta Stone";
    +Dest : String := Src(1..7); -- Assigns "Rosetta" to Dest
    +Dest2 : String := Src(9..13); -- Assigns "Stone" to Dest2
    diff --git a/Task/Copy-a-string/Ada/copy-a-string-3.adb b/Task/Copy-a-string/Ada/copy-a-string-3.adb
    new file mode 100644
    index 0000000000..3c40dd4ae0
    --- /dev/null
    +++ b/Task/Copy-a-string/Ada/copy-a-string-3.adb
    @@ -0,0 +1,6 @@
    +-- Instantiate the generic package Ada.Strings.Bounded.Generic_Bounded_Length with a maximum length of 80 characters
    +package Flexible_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80);
    +use Flexible_String;
    +
    +Src : Bounded_String := To_Bounded_String("Hello");
    +Dest : Bounded_String := Src;
    diff --git a/Task/Copy-a-string/Ada/copy-a-string-4.adb b/Task/Copy-a-string/Ada/copy-a-string-4.adb
    new file mode 100644
    index 0000000000..3e4431a025
    --- /dev/null
    +++ b/Task/Copy-a-string/Ada/copy-a-string-4.adb
    @@ -0,0 +1,3 @@
    +-- The package Ada.Strings.Unbounded contains the definition of the Unbounded_String type and all its methods
    +Src : Unbounded_String := To_Unbounded_String("Hello");
    +Dest : Unbounded_String := Src;
    diff --git a/Task/Copy-a-string/BaCon/copy-a-string-1.bacon b/Task/Copy-a-string/Applesoft-BASIC/copy-a-string-4.basic
    similarity index 100%
    rename from Task/Copy-a-string/BaCon/copy-a-string-1.bacon
    rename to Task/Copy-a-string/Applesoft-BASIC/copy-a-string-4.basic
    diff --git a/Task/Copy-a-string/BaCon/copy-a-string-2.bacon b/Task/Copy-a-string/Applesoft-BASIC/copy-a-string-5.basic
    similarity index 100%
    rename from Task/Copy-a-string/BaCon/copy-a-string-2.bacon
    rename to Task/Copy-a-string/Applesoft-BASIC/copy-a-string-5.basic
    diff --git a/Task/Copy-a-string/AutoIt/copy-a-string.au3 b/Task/Copy-a-string/AutoIt/copy-a-string.au3
    new file mode 100644
    index 0000000000..21d288ca03
    --- /dev/null
    +++ b/Task/Copy-a-string/AutoIt/copy-a-string.au3
    @@ -0,0 +1,2 @@
    +$Src= "Hello"
    +$dest = $Src
    diff --git a/Task/Copy-a-string/Ballerina/copy-a-string.ballerina b/Task/Copy-a-string/Ballerina/copy-a-string.ballerina
    new file mode 100644
    index 0000000000..ed5f916660
    --- /dev/null
    +++ b/Task/Copy-a-string/Ballerina/copy-a-string.ballerina
    @@ -0,0 +1,7 @@
    +import ballerina/io;
    +
    +public function main() {
    +    string s = "ballerina";
    +    string t = s;
    +    io:println(`Are s and t equal? ${t == s}`);
    +}
    diff --git a/Task/Copy-a-string/COBOL/copy-a-string.cob b/Task/Copy-a-string/COBOL/copy-a-string.cob
    new file mode 100644
    index 0000000000..e309ffeadb
    --- /dev/null
    +++ b/Task/Copy-a-string/COBOL/copy-a-string.cob
    @@ -0,0 +1,2 @@
    +MOVE "Hello" TO src
    +MOVE src TO dst
    diff --git a/Task/Copy-a-string/Emacs-Lisp/copy-a-string.el b/Task/Copy-a-string/Emacs-Lisp/copy-a-string.el
    new file mode 100644
    index 0000000000..e0914ed576
    --- /dev/null
    +++ b/Task/Copy-a-string/Emacs-Lisp/copy-a-string.el
    @@ -0,0 +1,7 @@
    +(let* ((str1 "hi")
    +       (str1-ref str1)
    +       (str2 (copy-sequence str1)))
    +  (eq str1 str1-ref) ;=> t
    +  (eq str1 str2) ;=> nil
    +  (equal str1 str1-ref) ;=> t
    +  (equal str1 str2)) ;=> t
    diff --git a/Task/Copy-a-string/Euphoria/copy-a-string.eu b/Task/Copy-a-string/Euphoria/copy-a-string.eu
    new file mode 100644
    index 0000000000..e29173ed2d
    --- /dev/null
    +++ b/Task/Copy-a-string/Euphoria/copy-a-string.eu
    @@ -0,0 +1,2 @@
    +sequence first = "ABC"
    +sequence newOne = first
    diff --git a/Task/Copy-a-string/Gleam/copy-a-string.gleam b/Task/Copy-a-string/Gleam/copy-a-string.gleam
    new file mode 100644
    index 0000000000..cfe412774e
    --- /dev/null
    +++ b/Task/Copy-a-string/Gleam/copy-a-string.gleam
    @@ -0,0 +1,2 @@
    +let src = "Hello"
    +let dest = src
    diff --git a/Task/Copy-a-string/LOLCODE/copy-a-string.lol b/Task/Copy-a-string/LOLCODE/copy-a-string.lol
    new file mode 100644
    index 0000000000..eaa7cf013b
    --- /dev/null
    +++ b/Task/Copy-a-string/LOLCODE/copy-a-string.lol
    @@ -0,0 +1,10 @@
    +HAI 1.3
    +
    +    I HAS A FRANK ITZ "Hello,"
    +    I HAS A PAUL ITZ "World!"
    +    VISIBLE FRANK " " PAUL
    +
    +    FRANK R PAUL
    +    VISIBLE FRANK " " PAUL
    +
    +KTHXBYE
    diff --git a/Task/Copy-a-string/PowerShell/copy-a-string-1.ps1 b/Task/Copy-a-string/PowerShell/copy-a-string-1.ps1
    new file mode 100644
    index 0000000000..91177b9261
    --- /dev/null
    +++ b/Task/Copy-a-string/PowerShell/copy-a-string-1.ps1
    @@ -0,0 +1,2 @@
    +$str = "foo"
    +$dup = $str
    diff --git a/Task/Copy-a-string/PowerShell/copy-a-string-2.ps1 b/Task/Copy-a-string/PowerShell/copy-a-string-2.ps1
    new file mode 100644
    index 0000000000..e29eed72c8
    --- /dev/null
    +++ b/Task/Copy-a-string/PowerShell/copy-a-string-2.ps1
    @@ -0,0 +1 @@
    +$dup = $str.Clone()
    diff --git a/Task/Copy-a-string/Rebol/copy-a-string.rebol b/Task/Copy-a-string/Rebol/copy-a-string.rebol
    new file mode 100644
    index 0000000000..02d96fc778
    --- /dev/null
    +++ b/Task/Copy-a-string/Rebol/copy-a-string.rebol
    @@ -0,0 +1,21 @@
    +Rebol [
    +    Title: "String Copy"
    +    URL: http://rosettacode.org/wiki/Copy_a_string
    +]
    +
    +x: y: "Testing."
    +y/2: #"X"
    +print ["Both variables reference same string:" mold x "," mold y]
    +
    +x: "Slackeriffic!"
    +print ["Now reference different strings:" mold x "," mold y]
    +
    +y: copy x        ; String copy here!
    +y/3: #"X"        ; Modify string.
    +print ["x copied to y, then modified:" mold x "," mold y]
    +
    +y: copy/part x 7 ; Copy only the first part of y to x.
    +print ["Partial copy:" mold x "," mold y]
    +
    +y: copy/part  skip x 2  3
    +print ["Partial copy from offset:" mold x "," mold y]
    diff --git a/Task/Copy-a-string/Rye/copy-a-string.rye b/Task/Copy-a-string/Rye/copy-a-string.rye
    new file mode 100644
    index 0000000000..39ec8eac96
    --- /dev/null
    +++ b/Task/Copy-a-string/Rye/copy-a-string.rye
    @@ -0,0 +1,8 @@
    +str:: "Hello"
    +;Returns [String: Hello]
    +str2:: str
    +;Returns [String: Hello]
    +str:: "World"
    +;Returns [String: World]
    +str2
    +;Returns [String: Hello]
    diff --git a/Task/Copy-a-string/Tcl/copy-a-string-1.tcl b/Task/Copy-a-string/Tcl/copy-a-string-1.tcl
    new file mode 100644
    index 0000000000..bab1d7bf37
    --- /dev/null
    +++ b/Task/Copy-a-string/Tcl/copy-a-string-1.tcl
    @@ -0,0 +1,2 @@
    +set src "Rosetta Code"
    +set dst $src
    diff --git a/Task/Copy-a-string/Tcl/copy-a-string-2.tcl b/Task/Copy-a-string/Tcl/copy-a-string-2.tcl
    new file mode 100644
    index 0000000000..2b6c1980c5
    --- /dev/null
    +++ b/Task/Copy-a-string/Tcl/copy-a-string-2.tcl
    @@ -0,0 +1,28 @@
    +set A  "a string"
    +
    +set B $A   ; # B is a reference to the string
    +
    +Set C "$A" ; # a new string is created
    +
    +set D "This is $C"  ; # the string bound to C is copied into a new string.
    +
    +
    +# the append command is internally optimized
    +# for adding to the end of a string or list
    +# as is string index for returning a letter
    +
    +# reverse a string
    +proc reverse {s} {
    +  set len [string length $s]
    +  set r ""
    +  for { set i $len} { $i >= 0} {incr i -1} {
    +        append r [string index $s $i]
    +  }
    +  return $r
    +}
    +
    +set a 12345
    +
    +set b [reverse $a]
    +
    +puts stdout "b: $b"
    diff --git a/Task/Copy-a-string/Tcl/copy-a-string-3.tcl b/Task/Copy-a-string/Tcl/copy-a-string-3.tcl
    new file mode 100644
    index 0000000000..cfbdcf9402
    --- /dev/null
    +++ b/Task/Copy-a-string/Tcl/copy-a-string-3.tcl
    @@ -0,0 +1,4 @@
    +# replace substrings in a string
    +
    +set rep [string map {"apple" "orange"} "I like apples."]
    +puts stdout $rep
    diff --git a/Task/Copy-a-string/Uiua/copy-a-string.uiua b/Task/Copy-a-string/Uiua/copy-a-string.uiua
    new file mode 100644
    index 0000000000..be6db2389c
    --- /dev/null
    +++ b/Task/Copy-a-string/Uiua/copy-a-string.uiua
    @@ -0,0 +1,2 @@
    +."hello"
    +first
    diff --git a/Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.adb b/Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.adb
    new file mode 100644
    index 0000000000..3e78e58b05
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Ada/copy-stdin-to-stdout.adb
    @@ -0,0 +1,11 @@
    +with Ada.Text_IO;
    +
    +procedure Copy_Stdin_To_Stdout is
    +   use Ada.Text_IO;
    +   C : Character;
    +begin
    +   while not End_Of_File loop
    +      Get_Immediate (C);
    +      Put (C);
    +   end loop;
    +end Copy_Stdin_To_Stdout;
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-1.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-1.bat
    new file mode 100644
    index 0000000000..c395545bf5
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-1.bat
    @@ -0,0 +1 @@
    +findstr ^^
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-2.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-2.bat
    new file mode 100644
    index 0000000000..4993fe87a3
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-2.bat
    @@ -0,0 +1 @@
    +findstr "^"
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-3.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-3.bat
    new file mode 100644
    index 0000000000..b4d82224f4
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-3.bat
    @@ -0,0 +1 @@
    +findstr $
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-4.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-4.bat
    new file mode 100644
    index 0000000000..e45275e17e
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-4.bat
    @@ -0,0 +1 @@
    +find/v ""
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-5.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-5.bat
    new file mode 100644
    index 0000000000..ef49dd86a6
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-5.bat
    @@ -0,0 +1 @@
    +more
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-6.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-6.bat
    new file mode 100644
    index 0000000000..6482121afa
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-6.bat
    @@ -0,0 +1 @@
    +copy con[:] con[:]
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-7.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-7.bat
    new file mode 100644
    index 0000000000..bd13d6aad4
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-7.bat
    @@ -0,0 +1 @@
    +type con[:]
    diff --git a/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-8.bat b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-8.bat
    new file mode 100644
    index 0000000000..2cc3128981
    --- /dev/null
    +++ b/Task/Copy-stdin-to-stdout/Batch-File/copy-stdin-to-stdout-8.bat
    @@ -0,0 +1,2 @@
    +@setlocal enabledelayedexpansion
    +@ Natural, Zero => 0, One => 1, Two => 2); use Prime_Nums;
    +
    +   procedure Put (List : Number_List) is
    +   begin
    +      for Index in List'Range loop
    +         Ada.Text_IO.Put (Integer'Image (List (Index)));
    +         if Index /= List'Last then
    +            Ada.Text_IO.Put (" x");
    +         end if;
    +      end loop;
    +   end Put;
    +
    +   N     : Natural := 1;
    +   Max_N : Natural := 15; -- the default for Max_N
    +begin
    +   if Ada.Command_Line.Argument_Count = 1 then -- read Max_N from command line
    +      Max_N := Integer'Value (Ada.Command_Line.Argument (1));
    +   end if; -- else use the default
    +   loop
    +      Ada.Text_IO.Put (Integer'Image (N) & ": ");
    +      Put (Decompose (N));
    +      Ada.Text_IO.New_Line;
    +      N := N + 1;
    +      exit when N > Max_N;
    +   end loop;
    +end Count;
    diff --git a/Task/Count-in-factors/Euphoria/count-in-factors.eu b/Task/Count-in-factors/Euphoria/count-in-factors.eu
    new file mode 100644
    index 0000000000..a2f83d9e8f
    --- /dev/null
    +++ b/Task/Count-in-factors/Euphoria/count-in-factors.eu
    @@ -0,0 +1,28 @@
    +function factorize(integer n)
    +    sequence result
    +    integer k
    +    if n = 1 then
    +        return {1}
    +    else
    +        k = 2
    +        result = {}
    +        while n > 1 do
    +            while remainder(n, k) = 0 do
    +                result &= k
    +                n /= k
    +            end while
    +            k += 1
    +        end while
    +        return result
    +    end if
    +end function
    +
    +sequence factors
    +for i = 1 to 22 do
    +    printf(1, "%d: ", i)
    +    factors = factorize(i)
    +    for j = 1 to length(factors)-1 do
    +        printf(1, "%d * ", factors[j])
    +    end for
    +    printf(1, "%d\n", factors[$])
    +end for
    diff --git a/Task/Count-in-factors/MiniScript/count-in-factors.mini b/Task/Count-in-factors/MiniScript/count-in-factors.mini
    new file mode 100644
    index 0000000000..e1fc4ba5f3
    --- /dev/null
    +++ b/Task/Count-in-factors/MiniScript/count-in-factors.mini
    @@ -0,0 +1,20 @@
    +factorize = function( n )
    +    if n == 1 then return [1] end if
    +
    +    k = 2
    +    res = []
    +    while n > 1
    +        while n % k == 0
    +            res.push( k )
    +            n /= k
    +        end while
    +        k += 1
    +    end while
    +    return res
    +end function
    +
    +for i in range( 1, 22 )
    +    iStr = str( i )
    +    if i < 10 then iStr = " " + iStr end if
    +    print iStr + ": " + factorize( i ).join( " * " )
    +end for
    diff --git a/Task/Count-in-factors/Oberon-07/count-in-factors.oberon b/Task/Count-in-factors/Oberon-07/count-in-factors.oberon
    new file mode 100644
    index 0000000000..f13299e96e
    --- /dev/null
    +++ b/Task/Count-in-factors/Oberon-07/count-in-factors.oberon
    @@ -0,0 +1,50 @@
    +MODULE CountInFactors; (* show the factors of some integers *)
    +  IMPORT Out;
    +
    +  CONST  maxFactors = 32;
    +
    +  PROCEDURE getFactors( n: INTEGER; VAR factors : ARRAY OF INTEGER );
    +      VAR   v, f : INTEGER;
    +      BEGIN
    +         IF n < 0 THEN
    +            getFactors( - n, factors )
    +         ELSIF n = 1 THEN
    +            factors[ 0 ] := 1;
    +            factors[ 1 ] := 1
    +         ELSE
    +            factors[ 0 ] := 0;
    +            v := n;
    +            f := 2;
    +            WHILE v > 1 DO
    +               WHILE v MOD f = 0 DO
    +                  v := v DIV f;
    +                  INC( factors[ 0 ] );
    +                  factors[ factors[ 0 ] ] := f
    +               END;
    +               IF f = 2 THEN f := 3 ELSE INC( f, 2 ) END
    +            END
    +         END
    +      END getFactors;
    +
    +   PROCEDURE printFactors( fFrom, fTo : INTEGER );
    +      VAR    i, fPos  : INTEGER;
    +             factors  : ARRAY maxFactors + 1 OF INTEGER;
    +      BEGIN
    +         FOR i := fFrom TO fTo DO
    +            getFactors( i, factors );
    +            Out.Int( i, 4 );Out.String( ":" );
    +            IF factors[ 0 ] > 0 THEN
    +               Out.String( " " );Out.Int( factors[ 1 ], 1 );
    +               FOR fPos := 2 TO factors[ 0 ] DO
    +                  Out.String( " x " );Out.Int( factors[ fPos ], 1 )
    +               END
    +            END;
    +            Out.Ln
    +         END
    +      END printFactors;
    +
    +BEGIN
    +   printFactors(    1,   32 );
    +   Out.String( " ..." );Out.Ln;
    +   printFactors( 2140, 2160 )
    +END CountInFactors.
    diff --git a/Task/Count-in-factors/Pluto/count-in-factors.pluto b/Task/Count-in-factors/Pluto/count-in-factors.pluto
    new file mode 100644
    index 0000000000..3598cbad8e
    --- /dev/null
    +++ b/Task/Count-in-factors/Pluto/count-in-factors.pluto
    @@ -0,0 +1,17 @@
    +local function factorize( n )
    +    if n == 1 then return {1} end
    +
    +    local k, res = 2, {}
    +    while n > 1 do
    +        while n % k == 0 do
    +            res[#res+1] = k
    +            n /= k
    +        end
    +        k += 1
    +    end
    +    return res
    +end
    +
    +for i = 1, 22 do
    +    print( $'{string.format( "%2d", i )}: {table.concat( factorize( i ), " * " )}' )
    +end
    diff --git a/Task/Count-in-factors/PowerShell/count-in-factors.ps1 b/Task/Count-in-factors/PowerShell/count-in-factors.ps1
    new file mode 100644
    index 0000000000..5bbb00031d
    --- /dev/null
    +++ b/Task/Count-in-factors/PowerShell/count-in-factors.ps1
    @@ -0,0 +1,32 @@
    +function eratosthenes ($n) {
    +    if($n -ge 1){
    +        $prime = @(1..($n+1) | foreach{$true})
    +        $prime[1] = $false
    +        $m = [Math]::Floor([Math]::Sqrt($n))
    +        for($i = 2; $i -le $m; $i++) {
    +            if($prime[$i]) {
    +                for($j = $i*$i; $j -le $n; $j += $i) {
    +                    $prime[$j] = $false
    +                }
    +            }
    +        }
    +        1..$n | where{$prime[$_]}
    +    } else {
    +        "$n must be equal or greater than 1"
    +    }
    +}
    +function prime-decomposition ($n) {
    +    $array = eratosthenes $n
    +    $prime = @()
    +    foreach($p in $array) {
    +        while($n%$p -eq 0) {
    +            $n /= $p
    +            $prime += @($p)
    +        }
    +    }
    +    $prime
    +}
    +$OFS = " x "
    +"$(prime-decomposition  2144)"
    +"$(prime-decomposition  100)"
    +"$(prime-decomposition  12)"
    diff --git a/Task/Count-in-factors/Uiua/count-in-factors.uiua b/Task/Count-in-factors/Uiua/count-in-factors.uiua
    new file mode 100644
    index 0000000000..687a7f1955
    --- /dev/null
    +++ b/Task/Count-in-factors/Uiua/count-in-factors.uiua
    @@ -0,0 +1,2 @@
    +&p"1:\t1"
    +≡(&p$"_:\t_"⟜(/$"_ x _"°/×))↘2⇡21
    diff --git a/Task/Count-in-factors/VBScript/count-in-factors.vbs b/Task/Count-in-factors/VBScript/count-in-factors.vbs
    new file mode 100644
    index 0000000000..bd322e473b
    --- /dev/null
    +++ b/Task/Count-in-factors/VBScript/count-in-factors.vbs
    @@ -0,0 +1,59 @@
    +Function CountFactors(n)
    +	If n = 1 Then
    +		CountFactors = 1
    +	Else
    +		arrP = Split(ListPrimes(n)," ")
    +		Set arrList = CreateObject("System.Collections.ArrayList")
    +		divnum = n
    +		Do Until divnum = 1
    +			'The -1 is to account for the null element of arrP
    +			For i = 0 To UBound(arrP)-1
    +				If divnum = 1 Then
    +					Exit For
    +				ElseIf divnum Mod arrP(i) = 0 Then
    +					divnum = divnum/arrP(i)
    +					arrList.Add arrP(i)
    +				End If
    +			Next
    +		Loop
    +		arrList.Sort
    +		For i = 0 To arrList.Count - 1
    +			If i = arrList.Count - 1 Then
    +				CountFactors = CountFactors & arrList(i)
    +			Else
    +				CountFactors = CountFactors & arrList(i) & " * "
    +			End If
    +		Next
    +	End If
    +End Function
    +
    +Function IsPrime(n)
    +	If n = 2 Then
    +		IsPrime = True
    +	ElseIf n <= 1 Or n Mod 2 = 0 Then
    +		IsPrime = False
    +	Else
    +		IsPrime = True
    +		For i = 3 To Int(Sqr(n)) Step 2
    +			If n Mod i = 0 Then
    +				IsPrime = False
    +				Exit For
    +			End If
    +		Next
    +	End If
    +End Function
    +
    +Function ListPrimes(n)
    +	ListPrimes = ""
    +	For i = 1 To n
    +		If IsPrime(i) Then
    +			ListPrimes = ListPrimes & i & " "
    +		End If
    +	Next
    +End Function
    +
    +'Testing the fucntions.
    +WScript.StdOut.Write "2 = " & CountFactors(2)
    +WScript.StdOut.WriteLine
    +WScript.StdOut.Write "2144 = " & CountFactors(2144)
    +WScript.StdOut.WriteLine
    diff --git a/Task/Count-in-octal/Ada/count-in-octal.adb b/Task/Count-in-octal/Ada/count-in-octal.adb
    new file mode 100644
    index 0000000000..614daf64dc
    --- /dev/null
    +++ b/Task/Count-in-octal/Ada/count-in-octal.adb
    @@ -0,0 +1,10 @@
    +with Ada.Text_IO;
    +
    +procedure Octal is
    +   package IIO is new Ada.Text_IO.Integer_IO(Integer);
    +begin
    +   for I in 0 .. Integer'Last loop
    +      IIO.Put(I, Base => 8);
    +      Ada.Text_IO.New_Line;
    +   end loop;
    +end Octal;
    diff --git a/Task/Count-in-octal/COBOL/count-in-octal.cob b/Task/Count-in-octal/COBOL/count-in-octal.cob
    new file mode 100644
    index 0000000000..b024da8205
    --- /dev/null
    +++ b/Task/Count-in-octal/COBOL/count-in-octal.cob
    @@ -0,0 +1,44 @@
    +       >>SOURCE FREE
    +IDENTIFICATION DIVISION.
    +PROGRAM-ID. count-in-octal.
    +
    +ENVIRONMENT DIVISION.
    +CONFIGURATION SECTION.
    +REPOSITORY.
    +    FUNCTION dec-to-oct
    +    .
    +DATA DIVISION.
    +WORKING-STORAGE SECTION.
    +01  i                                   PIC 9(18).
    +
    +PROCEDURE DIVISION.
    +    PERFORM VARYING i FROM 1 BY 1 UNTIL i = 0
    +        DISPLAY FUNCTION dec-to-oct(i)
    +    END-PERFORM
    +    .
    +END PROGRAM count-in-octal.
    +
    +
    +IDENTIFICATION DIVISION.
    +FUNCTION-ID. dec-to-oct.
    +
    +DATA DIVISION.
    +LOCAL-STORAGE SECTION.
    +01  rem                                 PIC 9.
    +
    +01  dec                                 PIC 9(18).
    +
    +LINKAGE SECTION.
    +01  dec-arg                             PIC 9(18).
    +
    +01  oct                                 PIC 9(18).
    +
    +PROCEDURE DIVISION USING dec-arg RETURNING oct.
    +    MOVE dec-arg TO dec *> Copy is made to avoid modifying reference arg.
    +    PERFORM WITH TEST AFTER UNTIL dec = 0
    +        MOVE FUNCTION REM(dec, 8) TO rem
    +        STRING rem, oct DELIMITED BY SPACES INTO oct
    +        DIVIDE 8 INTO dec
    +    END-PERFORM
    +    .
    +END FUNCTION dec-to-oct.
    diff --git a/Task/Count-in-octal/Emacs-Lisp/count-in-octal.el b/Task/Count-in-octal/Emacs-Lisp/count-in-octal.el
    new file mode 100644
    index 0000000000..f6dfcac92d
    --- /dev/null
    +++ b/Task/Count-in-octal/Emacs-Lisp/count-in-octal.el
    @@ -0,0 +1,2 @@
    +(dotimes (i most-positive-fixnum) ;; starting from 0
    +  (message "%o" i))
    diff --git a/Task/Count-in-octal/Euphoria/count-in-octal.eu b/Task/Count-in-octal/Euphoria/count-in-octal.eu
    new file mode 100644
    index 0000000000..871cba5486
    --- /dev/null
    +++ b/Task/Count-in-octal/Euphoria/count-in-octal.eu
    @@ -0,0 +1,6 @@
    +integer i
    +i = 0
    +while 1 do
    +    printf(1,"%o\n",i)
    +    i += 1
    +end while
    diff --git a/Task/Count-in-octal/Gleam/count-in-octal-1.gleam b/Task/Count-in-octal/Gleam/count-in-octal-1.gleam
    new file mode 100644
    index 0000000000..0ac5ac72d1
    --- /dev/null
    +++ b/Task/Count-in-octal/Gleam/count-in-octal-1.gleam
    @@ -0,0 +1,11 @@
    +import gleam/int
    +import gleam/io
    +
    +pub fn main() {
    +  count_octal(from: 1)
    +}
    +
    +fn count_octal(from n: Int) -> Nil {
    +  n |> int.to_base8 |> io.println
    +  count_octal(n + 1)
    +}
    diff --git a/Task/Count-in-octal/Gleam/count-in-octal-2.gleam b/Task/Count-in-octal/Gleam/count-in-octal-2.gleam
    new file mode 100644
    index 0000000000..4e0f73711c
    --- /dev/null
    +++ b/Task/Count-in-octal/Gleam/count-in-octal-2.gleam
    @@ -0,0 +1,24 @@
    +import gleam/int
    +import gleam/io
    +import gleam/string
    +
    +pub fn main() {
    +  count_octal(from: 1)
    +}
    +
    +fn count_octal(from n: Int) -> Nil {
    +  n |> to_octal |> io.println
    +  count_octal(n + 1)
    +}
    +
    +fn to_octal(n: Int) -> String {
    +  to_octal_loop(n, [])
    +}
    +
    +fn to_octal_loop(n: Int, digits: List(String)) -> String {
    +  case n, digits {
    +    0, [] -> "0"
    +    0, _ -> string.concat(digits)
    +    _, _ -> to_octal_loop(n / 8, [n % 8 |> int.to_string, ..digits])
    +  }
    +}
    diff --git a/Task/Count-in-octal/PowerShell/count-in-octal.ps1 b/Task/Count-in-octal/PowerShell/count-in-octal.ps1
    new file mode 100644
    index 0000000000..de995eb443
    --- /dev/null
    +++ b/Task/Count-in-octal/PowerShell/count-in-octal.ps1
    @@ -0,0 +1,5 @@
    +[int64]$i = 0
    +While ( $True )
    +    {
    +    [Convert]::ToString( ++$i, 8 )
    +    }
    diff --git a/Task/Count-in-octal/R/count-in-octal.r b/Task/Count-in-octal/R/count-in-octal.r
    new file mode 100644
    index 0000000000..cc8db74b6d
    --- /dev/null
    +++ b/Task/Count-in-octal/R/count-in-octal.r
    @@ -0,0 +1 @@
    +for(i in seq_len(.Machine$integer.max)) print(as.octmode(i))
    diff --git a/Task/Count-in-octal/RISC-V-Assembly/count-in-octal.asm b/Task/Count-in-octal/RISC-V-Assembly/count-in-octal.asm
    new file mode 100644
    index 0000000000..5dcd680a38
    --- /dev/null
    +++ b/Task/Count-in-octal/RISC-V-Assembly/count-in-octal.asm
    @@ -0,0 +1,118 @@
    +# riscv assembly raspberry pico2 rp2350
    +# program cptoctal.s
    +# connexion putty com3
    +/*********************************************/
    +/*           CONSTANTES                      */
    +/********************************************/
    +/* for this file see risc-v task include a file */
    +.include "../../../constantesRiscv.inc"
    +/****************************************************/
    +/* MACROS                   */
    +/****************************************************/
    +#.include "../ficmacrosriscv.inc"             # only for debugging
    +/*******************************************/
    +/* INITIALED DATAS                    */
    +/*******************************************/
    +.data
    +szMessStart:         .asciz "Program riscv start.\r\n"
    +szMessEndOk:         .asciz "Program riscv end OK.\r\n"
    +szCariageReturn:     .asciz "\r\n"
    +szMessResult:        .asciz "Octal = "       # message result
    +
    +
    +.align 2
    +/*******************************************/
    +/*  UNINITIALED DATA                    */
    +/*******************************************/
    +.bss
    +sConvArea:         .skip 24
    +
    +.align 2
    +/**********************************************/
    +/* SECTION CODE                              */
    +/**********************************************/
    +.text
    +.global main
    +
    +main:
    +    call stdio_init_all        # général init
    +1:                             # start loop connexion
    +    li a0,0                    # raz argument register
    +    call tud_cdc_n_connected   # waiting for USB connection
    +    beqz a0,1b                 # return code = zero ? yes -> loop
    +	
    +    la a0,szMessStart          # message address
    +    call writeString           # display message
    +	
    +    li s0,0                    # loop indice
    +	li s1,64
    +1:	
    +	mv a0,s0
    +    la a1,sConvArea
    +    call conversion8           # conversion octal
    +
    +
    +    la a0,szMessResult
    +    call writeString           # display message
    +	la a0,sConvArea
    +	call writeString
    +	la a0,szCariageReturn
    +	call writeString
    +	
    +	addi s0,s0,1
    +	ble s0,s1,1b
    +	
    +
    + 	
    +    la a0,szMessEndOk          # message address
    +    call writeString           # display message
    +    call getchar
    +100:                           # final loop
    +    j 100b
    +/**************************************************/
    +/*     conversion octal                    */
    +/**************************************************/
    +.equ LGZONECAL,   10
    +/* a0 value               */
    +/* a1 conversion area     */
    +conversion8:                # INFO: conversion8
    +    addi    sp, sp, -4
    +    sw      ra, 0(sp)
    +    mv t3,a1
    +    li t2,LGZONECAL
    +
    +1:                          # start loop
    +    mv t1,a0
    +    srli a0,a0,3            # / by 8
    +	slli t4,a0,3            # * by 8
    +	sub t1,t1,t4            # compute remainder t1 - (a0 * 8)
    +	addi t1,t1,48           # digit
    +    add t4,t3,t2
    +    sb t1,(t4)              # store digit on area
    +	beqz a0,2f              # stop if quotient = 0
    +	addi t2,t2,-1           # else previous position
    +	j 1b                    # and loop
    +2:
    +    li t1,0                 # and move digit from left of area
    +    li t5,LGZONECAL
    +3:
    +    add t4,t3,t2
    +	lbu t0,(t4)
    +	add t4,t3,t1
    +    sb  t0,(t4)
    +    addi t2,t2,1
    +    addi t1,t1,1
    +	ble t2,t5,3b
    +	add t4,t3,t1
    +    sb x0,(t4)              # zero final	
    +    mv a0,t1
    +	
    +100:
    +    lw      ra, 0(sp)
    +    addi    sp, sp, 4
    +    ret
    +/************************************/
    +/*     file include  Fonctions      */
    +/***********************************/
    +/* for this file see risc-v task include a file */
    +.include "../../../includeFunctions.s"
    diff --git a/Task/Count-in-octal/Uiua/count-in-octal.uiua b/Task/Count-in-octal/Uiua/count-in-octal.uiua
    new file mode 100644
    index 0000000000..afaf6107cd
    --- /dev/null
    +++ b/Task/Count-in-octal/Uiua/count-in-octal.uiua
    @@ -0,0 +1 @@
    +≡(&p⇌)⊥₈⇡10000
    diff --git a/Task/Count-in-octal/VBScript/count-in-octal.vbs b/Task/Count-in-octal/VBScript/count-in-octal.vbs
    new file mode 100644
    index 0000000000..9a6359e2a2
    --- /dev/null
    +++ b/Task/Count-in-octal/VBScript/count-in-octal.vbs
    @@ -0,0 +1,3 @@
    +For i = 0 To 20
    +	WScript.StdOut.WriteLine Oct(i)
    +Next
    diff --git a/Task/Count-occurrences-of-a-substring/Ada/count-occurrences-of-a-substring.adb b/Task/Count-occurrences-of-a-substring/Ada/count-occurrences-of-a-substring.adb
    new file mode 100644
    index 0000000000..1b89563491
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/Ada/count-occurrences-of-a-substring.adb
    @@ -0,0 +1,9 @@
    +with Ada.Strings.Fixed, Ada.Integer_Text_IO;
    +
    +procedure Substrings is
    +begin
    +   Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source  => "the three truths",
    +                                                     Pattern => "th"));
    +   Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source  => "ababababab",
    +                                                     Pattern => "abab"));
    +end Substrings;
    diff --git a/Task/Count-occurrences-of-a-substring/ArkScript/count-occurrences-of-a-substring.ark b/Task/Count-occurrences-of-a-substring/ArkScript/count-occurrences-of-a-substring.ark
    new file mode 100644
    index 0000000000..4d3fa4d47e
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/ArkScript/count-occurrences-of-a-substring.ark
    @@ -0,0 +1,12 @@
    +(import std.String)
    +
    +(let count (fun (str word) {
    +  (mut total 0)
    +  (mut next (string:find str word))
    +  (while (!= -1 next) {
    +    (set total (+ 1 total))
    +    (set next (string:findAfter str word (+ next (len word)))) })
    +  total }))
    +
    +(print (count "the three truths" "th"))
    +(print (count "ababababab" "abab"))
    diff --git a/Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cob b/Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cob
    new file mode 100644
    index 0000000000..bca9280178
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/COBOL/count-occurrences-of-a-substring.cob
    @@ -0,0 +1,22 @@
    +       IDENTIFICATION DIVISION.
    +       PROGRAM-ID. testing.
    +
    +       DATA DIVISION.
    +       WORKING-STORAGE SECTION.
    +       01  occurrences             PIC 99.
    +
    +       PROCEDURE DIVISION.
    +           INSPECT "the three truths" TALLYING occurrences FOR ALL "th"
    +           DISPLAY occurrences
    +
    +           MOVE 0 TO occurrences
    +           INSPECT "ababababab" TALLYING occurrences FOR ALL "abab"
    +           DISPLAY occurrences
    +
    +           MOVE 0 TO occurrences
    +           INSPECT "abaabba*bbaba*bbab" TALLYING occurrences
    +               FOR ALL "a*b"
    +           DISPLAY occurrences
    +
    +           GOBACK
    +           .
    diff --git a/Task/Count-occurrences-of-a-substring/Crystal/count-occurrences-of-a-substring.cr b/Task/Count-occurrences-of-a-substring/Crystal/count-occurrences-of-a-substring.cr
    new file mode 100644
    index 0000000000..00a43746fc
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/Crystal/count-occurrences-of-a-substring.cr
    @@ -0,0 +1,13 @@
    +def count_substring (haystack, needle)
    +  count = 0
    +  needle_size = needle.size
    +  i = 0
    +  while i = haystack.index(needle, i)
    +    i += needle_size
    +    count += 1
    +  end
    +  count
    +end
    +
    +p count_substring "the three truths", "th"
    +p count_substring "ababababab", "abab"
    diff --git a/Task/Count-occurrences-of-a-substring/EasyLang/count-occurrences-of-a-substring.easy b/Task/Count-occurrences-of-a-substring/EasyLang/count-occurrences-of-a-substring.easy
    index 043840b00d..a0e6229259 100644
    --- a/Task/Count-occurrences-of-a-substring/EasyLang/count-occurrences-of-a-substring.easy
    +++ b/Task/Count-occurrences-of-a-substring/EasyLang/count-occurrences-of-a-substring.easy
    @@ -1,9 +1,10 @@
     func count str$ pat$ .
        ind = 1
    -   while ind + len pat$ - 1 <= len str$
    -      if substr str$ ind len pat$ = pat$
    +   lp = len pat$
    +   while ind - 1 + lp <= len str$
    +      if substr str$ ind lp = pat$
              cnt += 1
    -         ind += len pat$
    +         ind += lp
           else
              ind += 1
           .
    diff --git a/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.el b/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.el
    new file mode 100644
    index 0000000000..0789fc7e91
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/Emacs-Lisp/count-occurrences-of-a-substring.el
    @@ -0,0 +1,20 @@
    +;; version 1, which takes advantage of the how-many function,
    +;; which runs only in a buffer
    +
    +(defun count-substrings (text substring)
    + "Count non-overlapping occurrences of SUBSTRING in TEXT."
    +    (with-temp-buffer          ; create a temporary buffer, which will be deleted when function finishes
    +      (insert text)            ; insert TEXT into the empty buffer
    +      (goto-char (point-min))  ; go to the beginning of the buffer
    +      (how-many substring)))   ; count how many occurrences of SUBSTRING
    +
    +
    +;; version 2, which operates on a string
    +
    +(defun count-substrings (text substring)
    +  "Count non-overlapping occurences of SUBSTRING in TEXT."
    +  (let ((substrings))                               ; empty list to add occurrences of SUBSTRING as we find them
    +    (while (string-match substring text)            ; as long as we can find SUBSTRING in TEXT
    +      (push (match-string 0 text) substrings)       ; add the SUBSTRING we found to the list of substrings
    +      (setq text (replace-match "" nil nil text)))  ; remove SUBSTRING from text, and repeat while loop
    +    (length substrings)))                           ; count number of items in substrings list
    diff --git a/Task/Count-occurrences-of-a-substring/Euphoria/count-occurrences-of-a-substring.eu b/Task/Count-occurrences-of-a-substring/Euphoria/count-occurrences-of-a-substring.eu
    new file mode 100644
    index 0000000000..fcfb05f0aa
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/Euphoria/count-occurrences-of-a-substring.eu
    @@ -0,0 +1,17 @@
    +function countSubstring(sequence s, sequence sub)
    +    integer from,count
    +    count = 0
    +    from = 1
    +    while 1 do
    +        from = match_from(sub,s,from)
    +        if not from then
    +            exit
    +        end if
    +        from += length(sub)
    +        count += 1
    +    end while
    +    return count
    +end function
    +
    +? countSubstring("the three truths","th")
    +? countSubstring("ababababab","abab")
    diff --git a/Task/Count-occurrences-of-a-substring/Pluto/count-occurrences-of-a-substring.pluto b/Task/Count-occurrences-of-a-substring/Pluto/count-occurrences-of-a-substring.pluto
    new file mode 100644
    index 0000000000..c879295f6a
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/Pluto/count-occurrences-of-a-substring.pluto
    @@ -0,0 +1,23 @@
    +local fmt = require "fmt"
    +
    +local function count_substring(str, sub)
    +    -- Escape any 'magic' characters used in patterns.
    +    local magic = "^$()%.[]*+-?":split("")
    +    for magic as m do sub = sub:replace(m, "%" .. m) end
    +    local count = 0
    +    for _ in str:gmatch(sub) do count += 1 end
    +    return count
    +end
    +
    +local tests = {
    +    {"the three truths", "th"},
    +    {"ababababab", "abab"},
    +    {"abaabba*bbaba*bbab", "a*b"},
    +    {"aaaaaaaaaaaaaa", "aa"},
    +    {"aaaaaaaaaaaaaa", "b"}
    +}
    +
    +for tests as test do
    +    local count = count_substring(test[1], test[2])
    +    fmt.print("%6s occurs %d times in %q.", string.format("%q", test[2]), count, test[1])
    +end
    diff --git a/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.ps1 b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.ps1
    new file mode 100644
    index 0000000000..8312af449c
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.ps1
    @@ -0,0 +1 @@
    +[regex]::Matches("the three truths", "th").count
    diff --git a/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.ps1 b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.ps1
    new file mode 100644
    index 0000000000..ac20bd15a5
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.ps1
    @@ -0,0 +1 @@
    +[regex]::Matches("ababababab","abab").count
    diff --git a/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-1.vbs b/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-1.vbs
    new file mode 100644
    index 0000000000..f0406be57b
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-1.vbs
    @@ -0,0 +1,16 @@
    +Function CountSubstring(str,substr)
    +	CountSubstring = 0
    +	For i = 1 To Len(str)
    +		If Len(str) >= Len(substr) Then
    +			If InStr(i,str,substr) Then
    +				CountSubstring = CountSubstring + 1
    +				i = InStr(i,str,substr) + Len(substr) - 1
    +			End If
    +		Else
    +			Exit For
    +		End If
    +	Next
    +End Function
    +
    +WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf
    +WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf
    diff --git a/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-2.vbs b/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-2.vbs
    new file mode 100644
    index 0000000000..fbc9239196
    --- /dev/null
    +++ b/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring-2.vbs
    @@ -0,0 +1,10 @@
    +function CountSubstring(str,substr)
    +  with new regexp
    +     .pattern=substr
    +     .global=true
    +     set m=.execute(str)
    +  end with
    +  CountSubstring =m.count
    +end function
    +WScript.StdOut.Writeline CountSubstring("the three truths","th")
    +WScript.StdOut.Writeline CountSubstring("ababababab","abab")
    diff --git a/Task/Count-the-coins/Ada/count-the-coins-1.adb b/Task/Count-the-coins/Ada/count-the-coins-1.adb
    new file mode 100644
    index 0000000000..307a6c5ac4
    --- /dev/null
    +++ b/Task/Count-the-coins/Ada/count-the-coins-1.adb
    @@ -0,0 +1,32 @@
    +with Ada.Text_IO;
    +
    +procedure Count_The_Coins is
    +
    +   type Counter_Type is range 0 .. 2**63-1; -- works with gnat
    +   type Coin_List is array(Positive range <>) of Positive;
    +
    +   function Count(Goal: Natural; Coins: Coin_List) return Counter_Type is
    +      Cnt: array(0 .. Goal) of Counter_Type := (0 => 1, others => 0);
    +      -- 0 => we already know one way to choose (no) coins that sum up to zero
    +      -- 1 .. Goal => we do not (yet) other ways to choose coins
    +   begin
    +      for C in Coins'Range loop
    +         for Amount in 1 .. Cnt'Last loop
    +            if Coins(C) <= Amount then
    +               Cnt(Amount) := Cnt(Amount) + Cnt(Amount-Coins(C));
    +               -- Amount-Coins(C) plus Coins(C) sums up to Amount;
    +            end if;
    +         end loop;
    +      end loop;
    +      return Cnt(Goal);
    +   end Count;
    +
    +   procedure Print(C: Counter_Type) is
    +   begin
    +      Ada.Text_IO.Put_Line(Counter_Type'Image(C));
    +   end Print;
    +
    +begin
    +   Print(Count(   1_00,          (25, 10, 5, 1)));
    +   Print(Count(1000_00, (100, 50, 25, 10, 5, 1)));
    +end Count_The_Coins;
    diff --git a/Task/Count-the-coins/Ada/count-the-coins-2.adb b/Task/Count-the-coins/Ada/count-the-coins-2.adb
    new file mode 100644
    index 0000000000..41b7305e62
    --- /dev/null
    +++ b/Task/Count-the-coins/Ada/count-the-coins-2.adb
    @@ -0,0 +1,26 @@
    +with Ada.Text_IO; use Ada.Text_IO;
    +
    +procedure Main is
    +   count: Integer;
    +begin
    +   count := 0;
    +   for penny in 0 .. 100 loop
    +      for nickel in 0 .. 20 loop
    +        for dime in 0 .. 10 loop
    +           for quarter in 0 .. 4 loop
    +              if (penny + 5 * nickel + 10 * dime + 25 * quarter = 100)
    +              then
    +                 Put_Line(Integer'Image(count+1) & ": " &
    +                          Integer'Image(penny)   & " pennies, " &
    +                          Integer'Image(nickel)  & " nickels, " &
    +                          Integer'Image(dime)    & " dimes, "   &
    +                          Integer'Image(quarter) & " quarters");
    +                 count := count + 1;
    +              end if;
    +           end loop;
    +        end loop;
    +      end loop;
    +   end loop;
    +
    +  Put_Line("The number of ways to make change for a dollar is: " &  Integer'Image(count));
    +end Main;
    diff --git a/Task/Count-the-coins/COBOL/count-the-coins.cob b/Task/Count-the-coins/COBOL/count-the-coins.cob
    new file mode 100644
    index 0000000000..3a083ed90f
    --- /dev/null
    +++ b/Task/Count-the-coins/COBOL/count-the-coins.cob
    @@ -0,0 +1,31 @@
    +       identification division.
    +       program-id. CountCoins.
    +
    +       data division.
    +       working-storage section.
    +       77  i                      pic 9(3).
    +       77  j                      pic 9(3).
    +       77  m                      pic 9(3) value 4.
    +       77  n                      pic 9(3) value 100.
    +       77  edited-value           pic z(18).
    +       01  coins-table            value "01051025".
    +           05 coin                pic 9(2) occurs 4.
    +       01  ways-table.
    +           05 way                 pic 9(18) occurs 100.
    +
    +       procedure division.
    +       main.
    +           perform calc-count
    +           move way(n) to edited-value
    +           display function trim(edited-value)
    +           stop run
    +           .
    +       calc-count.
    +           initialize ways-table
    +           move 1 to way(1)
    +           perform varying i from 1 by 1 until i > m
    +              perform varying j from coin(i) by 1 until j > n
    +                 add way(j - coin(i)) to way(j)
    +              end-perform
    +           end-perform
    +           .
    diff --git a/Task/Count-the-coins/Fortran/count-the-coins.f b/Task/Count-the-coins/Fortran/count-the-coins.f
    new file mode 100644
    index 0000000000..fb1081ce81
    --- /dev/null
    +++ b/Task/Count-the-coins/Fortran/count-the-coins.f
    @@ -0,0 +1,61 @@
    +!
    +! Count the coins
    +! ---------------
    +! tested with Intel ifx (IFX) 2025.2.1 20250806             on Kubuntu 25.10
    +!             GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0   on Kubuntu 25.10
    +!             VSI Fortran x86-64 V8.6-001                   on OpenVMS x86_64 V9.2-3
    +!
    +! No non-standard Fortran extensions have been used. It should compile and run using
    +! any fairly recent Fortran compiler.
    +! U.B., December 2025
    +!==============================================================================
    +
    +
    +program coins
    +
    +! Note that gfortran (but only gfortran) can handle integer (kind=16) and do
    +! the calculation for larger examples within reasonable time. Only up to longI = 8
    +! is portable.
    +
    +integer, parameter :: longI=8
    +
    +! Print results for the two examples of the task description
    +print *, countWays (     100, [1,5,10,25], 4)
    +print *, countWays (  100000, [1,5,10,25,50,100],6)
    +
    +contains
    +
    +! ========================================================================
    +! Count the number of ways an amount of money (in Cent) can be paid using
    +! coins from a given set of con values.
    +! This is a standard example for Dynamic Programming, to be found in every
    +! text book on Algorithmics .
    +! ========================================================================
    +
    +function countWays (amount, coinset, nCoins) result (cnt)
    +integer, intent(in) :: amount             ! in Cents
    +integer, intent(in) :: coinset(*)         ! the different coins that can be used
    +integer, intent(in) :: nCoins             ! number of different available coins
    +integer (kind=longI) cnt                  ! Result
    +
    +integer (kind=longI)    DP (0:amount+1)   ! Array for Dynamic Programming (sub problems)
    +integer :: ii, jj                         ! Two Loop indices
    +
    +! Initialize DP
    +DP(0) = 1                                 ! 1 way to give zero dollars.
    +do ii=1, amount+1                         ! prepare the rest
    +  DP(ii) =  0
    +end do
    +
    +! Dynamic programming: accumulate sub-problems from smallest up to 'amount'
    +do ii=1, nCoins
    +  do jj=coinset(ii), amount
    +    DP(jj) = DP(jj) + DP(jj-coinset(ii))
    +  enddo
    +enddo
    +
    +cnt = DP(amount)
    +
    +end function countWays
    +
    +end program coins
    diff --git a/Task/Count-the-coins/Uiua/count-the-coins.uiua b/Task/Count-the-coins/Uiua/count-the-coins.uiua
    new file mode 100644
    index 0000000000..af2bbb1de3
    --- /dev/null
    +++ b/Task/Count-the-coins/Uiua/count-the-coins.uiua
    @@ -0,0 +1,3 @@
    +Count ← ⊣∧(∧(+⬚0↻)⊙¤⊙(⟜˙-)¯×⟜(⇡⌈÷)⊙⊸⧻)⊙(⊂1˜↯0)
    +Count [1 5 10 25] 100
    +Count [1 5 10 25 50 100] 100000
    diff --git a/Task/Count-the-coins/VBScript/count-the-coins.vbs b/Task/Count-the-coins/VBScript/count-the-coins.vbs
    new file mode 100644
    index 0000000000..409c376f09
    --- /dev/null
    +++ b/Task/Count-the-coins/VBScript/count-the-coins.vbs
    @@ -0,0 +1,20 @@
    +Function count(coins,m,n)
    +	ReDim table(n+1)
    +	table(0) = 1
    +	i = 0
    +	Do While i < m
    +		j = coins(i)
    +		Do While j <= n
    +			table(j) = table(j) + table(j - coins(i))
    +			j = j + 1
    +		Loop
    +		i = i + 1
    +	Loop
    +	count = table(n)
    +End Function
    +
    +'testing
    +arr = Array(1,5,10,25)
    +m = UBound(arr) + 1
    +n = 100
    +WScript.StdOut.WriteLine count(arr,m,n)
    diff --git a/Task/Cramers-rule/Ada/cramers-rule.adb b/Task/Cramers-rule/Ada/cramers-rule.adb
    new file mode 100644
    index 0000000000..c9e1550bb1
    --- /dev/null
    +++ b/Task/Cramers-rule/Ada/cramers-rule.adb
    @@ -0,0 +1,70 @@
    +with Ada.Text_IO;
    +with Ada.Numerics.Generic_Real_Arrays;
    +
    +procedure Cramers_Rules is
    +
    +   type Real is new Float;
    +   --  This is the type we want to use in the matrix and vector
    +
    +   package Real_Arrays is
    +      new Ada.Numerics.Generic_Real_Arrays (Real);
    +
    +   use Real_Arrays;
    +
    +   function Solve_Cramer (M : in Real_Matrix;
    +                          V : in Real_Vector)
    +                         return Real_Vector
    +   is
    +      Denominator : Real;
    +      Nom_Matrix  : Real_Matrix (M'Range (1),
    +                                 M'Range (2));
    +      Numerator   : Real;
    +      Result      : Real_Vector (M'Range (1));
    +   begin
    +      if
    +        M'Length (2) /= V'Length or
    +        M'Length (1) /= M'Length (2)
    +      then
    +         raise Constraint_Error with "Dimensions does not match";
    +      end if;
    +
    +      Denominator := Determinant (M);
    +
    +      for Col in V'Range loop
    +         Nom_Matrix := M;
    +
    +         --  Substitute column
    +         for Row in V'Range loop
    +            Nom_Matrix (Row, Col) := V (Row);
    +         end loop;
    +
    +         Numerator    := Determinant (Nom_Matrix);
    +         Result (Col) := Numerator / Denominator;
    +      end loop;
    +
    +      return Result;
    +   end Solve_Cramer;
    +
    +   procedure Put (V : Real_Vector) is
    +      use Ada.Text_IO;
    +      package Real_IO is
    +         new Ada.Text_IO.Float_IO (Real);
    +   begin
    +      Put ("[");
    +      for E of V loop
    +         Real_IO.Put (E, Exp => 0, Aft => 2);
    +         Put (" ");
    +      end loop;
    +      Put ("]");
    +      New_Line;
    +   end Put;
    +
    +   M : constant Real_Matrix := ((2.0, -1.0,  5.0,  1.0),
    +                                (3.0,  2.0,  2.0, -6.0),
    +                                (1.0,  3.0,  3.0, -1.0),
    +                                (5.0, -2.0, -3.0,  3.0));
    +   V : constant Real_Vector := (-3.0, -32.0, -47.0, 49.0);
    +   R : constant Real_Vector := Solve_Cramer (M, V);
    +begin
    +   Put (R);
    +end Cramers_Rules;
    diff --git a/Task/Cramers-rule/Pluto/cramers-rule.pluto b/Task/Cramers-rule/Pluto/cramers-rule.pluto
    new file mode 100644
    index 0000000000..e563d325c6
    --- /dev/null
    +++ b/Task/Cramers-rule/Pluto/cramers-rule.pluto
    @@ -0,0 +1,31 @@
    +require "matrix"
    +local fmt = require "fmt"
    +
    +local function cramer(a, d)
    +    local n = a:numrows()
    +    local x = {}
    +    local ad = a:det()
    +    for c = 1, n do
    +        local aa = a:copy()
    +        for r = 1, n do aa:set(r, c, d:get(r, 1)) end
    +        x[c] = aa:det() / ad
    +    end
    +    return x
    +end
    +
    +local a = matrix.from({
    +    {2, -1,  5,  1},
    +    {3,  2,  2, -6},
    +    {1,  3,  3, -1},
    +    {5, -2, -3,  3}
    +})
    +
    +local d = matrix.from({
    +    { -3},
    +    {-32},
    +    {-47},
    +    { 49}
    +})
    +
    +local x = cramer(a, d)
    +fmt.print("Solution is %s", fmt.swrite(x))
    diff --git a/Task/Cramers-rule/Uiua/cramers-rule.uiua b/Task/Cramers-rule/Uiua/cramers-rule.uiua
    new file mode 100644
    index 0000000000..a4eeac028c
    --- /dev/null
    +++ b/Task/Cramers-rule/Uiua/cramers-rule.uiua
    @@ -0,0 +1,7 @@
    +# Experimental!
    +Math ~ "git: github.com/Omnikar/uiua-math"
    +A    ← [[2 ¯1 5 1] [3 2 2 ¯6] [1 3 3 ¯1] [5 ¯2 ¯3 3]]
    +B    ← [¯3 ¯32 ¯47 49]
    +DetA ← Math~MDet A
    +°⊏A
    +⁅÷DetA≡(Math~MDet⍉⍜⊡⋅B⊙⍉)⊙¤
    diff --git a/Task/Create-a-file-on-magnetic-tape/COBOL/create-a-file-on-magnetic-tape.cob b/Task/Create-a-file-on-magnetic-tape/COBOL/create-a-file-on-magnetic-tape.cob
    new file mode 100644
    index 0000000000..c478ce5800
    --- /dev/null
    +++ b/Task/Create-a-file-on-magnetic-tape/COBOL/create-a-file-on-magnetic-tape.cob
    @@ -0,0 +1,26 @@
    +       >>SOURCE FORMAT IS FREE
    +IDENTIFICATION DIVISION.
    +PROGRAM-ID. MAKE-TAPE-FILE.
    +
    +ENVIRONMENT DIVISION.
    +INPUT-OUTPUT SECTION.
    +FILE-CONTROL.
    +    SELECT TAPE-FILE
    +        ASSIGN TO "./TAPE.FILE"
    +        ORGANIZATION IS SEQUENTIAL
    +        ACCESS MODE IS SEQUENTIAL.
    +
    +DATA DIVISION.
    +FILE SECTION.
    +FD  TAPE-FILE RECORD CONTAINS 51 CHARACTERS.
    +01  TAPE-FILE-RECORD PICTURE IS X(51).
    +
    +PROCEDURE DIVISION.
    +    OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE
    +    WRITE TAPE-FILE-RECORD
    +        FROM "COBOL treats tape files and text files identically."
    +    END-WRITE
    +    CLOSE TAPE-FILE
    +    STOP RUN.
    +
    +END PROGRAM MAKE-TAPE-FILE.
    diff --git a/Task/Create-a-file/Ada/create-a-file.adb b/Task/Create-a-file/Ada/create-a-file.adb
    new file mode 100644
    index 0000000000..a887e79eaa
    --- /dev/null
    +++ b/Task/Create-a-file/Ada/create-a-file.adb
    @@ -0,0 +1,17 @@
    +with Ada.Streams.Stream_IO, Ada.Directories;
    +use  Ada.Streams.Stream_IO, Ada.Directories;
    +
    +procedure File_Creation is
    +
    +   File_Handle : File_Type;
    +
    +begin
    +
    +   Create (File_Handle, Out_File, "output.txt");
    +   Close (File_Handle);
    +   Create_Directory("docs");
    +   Create (File_Handle, Out_File, "/output.txt");
    +   Close (File_Handle);
    +   Create_Directory("/docs");
    +
    +end File_Creation;
    diff --git a/Task/Create-a-file/Batch-File/create-a-file-3.bat b/Task/Create-a-file/Batch-File/create-a-file-3.bat
    new file mode 100644
    index 0000000000..df1cc37f73
    --- /dev/null
    +++ b/Task/Create-a-file/Batch-File/create-a-file-3.bat
    @@ -0,0 +1,2 @@
    +mkdir docs
    +mkdir \docs
    diff --git a/Task/Create-a-file/Batch-File/create-a-file-4.bat b/Task/Create-a-file/Batch-File/create-a-file-4.bat
    new file mode 100644
    index 0000000000..a1ca232ff6
    --- /dev/null
    +++ b/Task/Create-a-file/Batch-File/create-a-file-4.bat
    @@ -0,0 +1,2 @@
    +md docs
    +md \docs
    diff --git a/Task/Create-a-file/COBOL/create-a-file.cob b/Task/Create-a-file/COBOL/create-a-file.cob
    new file mode 100644
    index 0000000000..b8da29eeea
    --- /dev/null
    +++ b/Task/Create-a-file/COBOL/create-a-file.cob
    @@ -0,0 +1,41 @@
    +       identification division.
    +       program-id. create-a-file.
    +
    +       data division.
    +       working-storage section.
    +       01 skip                 pic 9 value 2.
    +       01 file-name.
    +          05 value "/output.txt".
    +       01 dir-name.
    +          05 value "/docs".
    +       01 file-handle          usage binary-long.
    +
    +       procedure division.
    +       files-main.
    +
    +      *> create in current working directory
    +       perform create-file-and-dir
    +
    +      *> create in root of file system, will fail without privilege
    +       move 1 to skip
    +       perform create-file-and-dir
    +
    +       goback.
    +
    +       create-file-and-dir.
    +      *> create file in current working dir, for read/write
    +       call "CBL_CREATE_FILE" using file-name(skip:) 3 0 0 file-handle
    +       if return-code not equal 0 then
    +           display "error: CBL_CREATE_FILE " file-name(skip:) ": "
    +                   file-handle ", " return-code upon syserr
    +       end-if
    +
    +      *> create dir below current working dir, owner/group read/write
    +       call "CBL_CREATE_DIR" using dir-name(skip:)
    +       if return-code not equal 0 then
    +           display "error: CBL_CREATE_DIR " dir-name(skip:) ": "
    +                   return-code upon syserr
    +       end-if
    +       .
    +
    +       end program create-a-file.
    diff --git a/Task/Create-a-file/Emacs-Lisp/create-a-file.el b/Task/Create-a-file/Emacs-Lisp/create-a-file.el
    new file mode 100644
    index 0000000000..4b98bdd600
    --- /dev/null
    +++ b/Task/Create-a-file/Emacs-Lisp/create-a-file.el
    @@ -0,0 +1,4 @@
    +(make-empty-file "output.txt")
    +(make-directory "docs")
    +(make-empty-file "/output.txt")
    +(make-directory "/docs")
    diff --git a/Task/Create-a-file/Euphoria/create-a-file.eu b/Task/Create-a-file/Euphoria/create-a-file.eu
    new file mode 100644
    index 0000000000..d34ca677f6
    --- /dev/null
    +++ b/Task/Create-a-file/Euphoria/create-a-file.eu
    @@ -0,0 +1,11 @@
    +integer fn
    +
    +-- In the current working directory
    +system("mkdir docs",2)
    +fn = open("output.txt","w")
    +close(fn)
    +
    +-- In the filesystem root
    +system("mkdir \\docs",2)
    +fn = open("\\output.txt","w")
    +close(fn)
    diff --git a/Task/Create-a-file/PowerShell/create-a-file.ps1 b/Task/Create-a-file/PowerShell/create-a-file.ps1
    new file mode 100644
    index 0000000000..366d66cad6
    --- /dev/null
    +++ b/Task/Create-a-file/PowerShell/create-a-file.ps1
    @@ -0,0 +1,4 @@
    +New-Item output.txt -ItemType File
    +New-Item \output.txt -ItemType File
    +New-Item docs -ItemType Directory
    +New-Item \docs -ItemType Directory
    diff --git a/Task/Create-a-file/Rebol/create-a-file.rebol b/Task/Create-a-file/Rebol/create-a-file.rebol
    new file mode 100644
    index 0000000000..87ca418884
    --- /dev/null
    +++ b/Task/Create-a-file/Rebol/create-a-file.rebol
    @@ -0,0 +1,9 @@
    +; Creating in current directory:
    +
    +write %output.txt ""
    +make-dir %docs/
    +
    +; Creating in root directory:
    +
    +write %/output.txt ""
    +make-dir %/docs/
    diff --git a/Task/Create-a-file/Rye/create-a-file.rye b/Task/Create-a-file/Rye/create-a-file.rye
    new file mode 100644
    index 0000000000..da8ee1ef6b
    --- /dev/null
    +++ b/Task/Create-a-file/Rye/create-a-file.rye
    @@ -0,0 +1,5 @@
    +cc os
    +mkdir %docs
    +Create %output.txt
    +mkdir %/docs
    +Create %/docs/output.txt
    diff --git a/Task/Create-a-file/VBScript/create-a-file.vbs b/Task/Create-a-file/VBScript/create-a-file.vbs
    new file mode 100644
    index 0000000000..3dca9a5df6
    --- /dev/null
    +++ b/Task/Create-a-file/VBScript/create-a-file.vbs
    @@ -0,0 +1,9 @@
    +Set objFSO = CreateObject("Scripting.FileSystemObject")
    +
    +'current directory
    +objFSO.CreateFolder(".\docs")
    +objFSO.CreateTextFile(".\docs\output.txt")
    +
    +'root directory
    +objFSO.CreateFolder("\docs")
    +objFSO.CreateTextFile("\docs\output.txt")
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Ada/create-a-two-dimensional-array-at-runtime.adb b/Task/Create-a-two-dimensional-array-at-runtime/Ada/create-a-two-dimensional-array-at-runtime.adb
    new file mode 100644
    index 0000000000..e419aa5c69
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/Ada/create-a-two-dimensional-array-at-runtime.adb
    @@ -0,0 +1,21 @@
    +with Ada.Text_Io;
    +with Ada.Float_Text_Io;
    +with Ada.Integer_Text_Io;
    +
    +procedure Two_Dimensional_Arrays is
    +   type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
    +   Dim_1 : Positive;
    +   Dim_2 : Positive;
    +begin
    +   Ada.Integer_Text_Io.Get(Item => Dim_1);
    +   Ada.Integer_Text_Io.Get(Item => Dim_2);
    +   -- Create an inner block with the correctly sized array
    +   declare
    +      Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
    +   begin
    +      Matrix(1, Dim_2) := 3.14159;
    +      Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
    +      Ada.Text_Io.New_Line;
    +   end;
    +   -- The variable Matrix is popped off the stack automatically
    +end Two_Dimensional_Arrays;
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/AutoIt/create-a-two-dimensional-array-at-runtime.au3 b/Task/Create-a-two-dimensional-array-at-runtime/AutoIt/create-a-two-dimensional-array-at-runtime.au3
    new file mode 100644
    index 0000000000..7ca80ae9e8
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/AutoIt/create-a-two-dimensional-array-at-runtime.au3
    @@ -0,0 +1,12 @@
    +; == get dimensions from user input
    +$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. "5,3"')
    +$aDimension = StringSplit($sInput, ',', 2)
    +
    +; == create array
    +Dim $a2D[ $aDimension[0] ][ $aDimension[1] ]
    +
    +; == write value to last row/last column
    +$a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] = 'test string'
    +
    +; == output this value to MsgBox
    +MsgBox(0, 'Output', 'row[' & UBound($a2D) -1 & '], col[' & UBound($a2D, 2) -1 & ']' & @CRLF & '= ' & $a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] )
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Euphoria/create-a-two-dimensional-array-at-runtime.eu b/Task/Create-a-two-dimensional-array-at-runtime/Euphoria/create-a-two-dimensional-array-at-runtime.eu
    new file mode 100644
    index 0000000000..c9db5fda0a
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/Euphoria/create-a-two-dimensional-array-at-runtime.eu
    @@ -0,0 +1,15 @@
    +include get.e
    +
    +sequence array
    +integer height,width,i,j
    +
    +height = floor(prompt_number("Enter height: ",{}))
    +width = floor(prompt_number("Enter width: ",{}))
    +
    +array = repeat(repeat(0,width),height)
    +
    +i = floor(height/2+0.5)
    +j = floor(width/2+0.5)
    +array[i][j] = height + width
    +
    +printf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]})
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Pluto/create-a-two-dimensional-array-at-runtime.pluto b/Task/Create-a-two-dimensional-array-at-runtime/Pluto/create-a-two-dimensional-array-at-runtime.pluto
    new file mode 100644
    index 0000000000..c942cbfb95
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/Pluto/create-a-two-dimensional-array-at-runtime.pluto
    @@ -0,0 +1,11 @@
    +require "io2"
    +require "table2"
    +
    +print("Enter the dimensions of the array:")
    +local x = io.readInt("  First dimension  : ", 1)
    +local y = io.readInt("  Second dimension : ", 1)
    +local a = table.create(x)
    +for i = 1, x do a[i] = table.rep(y, 0) end
    +a[x][y] = 42
    +print($"\na[{x}][{y}] = {a[x][y]}")
    +a = nil
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-1.ps1 b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-1.ps1
    new file mode 100644
    index 0000000000..533ef37692
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-1.ps1
    @@ -0,0 +1,22 @@
    +function Read-ArrayIndex ([string]$Prompt = "Enter an integer greater than zero")
    +{
    +    [int]$inputAsInteger = 0
    +
    +    while (-not [Int]::TryParse(([string]$inputString = Read-Host $Prompt), [ref]$inputAsInteger))
    +    {
    +        $inputString = Read-Host "Enter an integer greater than zero"
    +    }
    +
    +    if ($inputAsInteger -gt 0) {return $inputAsInteger} else {return 1}
    +}
    +
    +$x = $y = $null
    +
    +do
    +{
    +    if ($x -eq $null) {$x = Read-ArrayIndex -Prompt "Enter two dimensional array index X"}
    +    if ($y -eq $null) {$y = Read-ArrayIndex -Prompt "Enter two dimensional array index Y"}
    +}
    +until (($x -ne $null) -and ($y -ne $null))
    +
    +$array2d = New-Object -TypeName 'System.Object[,]' -ArgumentList $x, $y
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-2.ps1 b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-2.ps1
    new file mode 100644
    index 0000000000..62a06feb59
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-2.ps1
    @@ -0,0 +1,6 @@
    +[int]$k = 1
    +
    +for ($i = 0; $i -lt 6; $i++)
    +{
    +    0..5 | ForEach-Object -Begin {$k += 10} -Process {$array2d[$i,$_] = $k + $_}
    +}
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-3.ps1 b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-3.ps1
    new file mode 100644
    index 0000000000..3ac520bb6b
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-3.ps1
    @@ -0,0 +1,4 @@
    +for ($i = 0; $i -lt 6; $i++)
    +{
    +    "{0}`t{1}`t{2}`t{3}`t{4}`t{5}" -f (0..5 | ForEach-Object {$array2d[$i,$_]})
    +}
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-4.ps1 b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-4.ps1
    new file mode 100644
    index 0000000000..592b870ff1
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/PowerShell/create-a-two-dimensional-array-at-runtime-4.ps1
    @@ -0,0 +1 @@
    +$array2d[2,2]
    diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Rebol/create-a-two-dimensional-array-at-runtime.rebol b/Task/Create-a-two-dimensional-array-at-runtime/Rebol/create-a-two-dimensional-array-at-runtime.rebol
    new file mode 100644
    index 0000000000..65bda94deb
    --- /dev/null
    +++ b/Task/Create-a-two-dimensional-array-at-runtime/Rebol/create-a-two-dimensional-array-at-runtime.rebol
    @@ -0,0 +1,6 @@
    +matrix: array/initial [5 3] 0 ;; 5 rows, 3 cols
    +matrix/1/1: 1
    +matrix/3/3: 2
    +?? matrix
    +print ""
    +foreach row matrix [ probe row ]
    diff --git a/Task/Create-an-HTML-table/Ada/create-an-html-table-1.adb b/Task/Create-an-HTML-table/Ada/create-an-html-table-1.adb
    new file mode 100644
    index 0000000000..a5a00c6abb
    --- /dev/null
    +++ b/Task/Create-an-HTML-table/Ada/create-an-html-table-1.adb
    @@ -0,0 +1,19 @@
    +with Ada.Strings.Unbounded;
    +
    +generic
    +   type Item_Type is private;
    +   with function To_String(Item: Item_Type) return String is <>;
    +   with procedure Put(S: String) is <>;
    +   with procedure Put_Line(Line: String) is <>;
    +package HTML_Table is
    +
    +   subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
    +   function Convert(S: String) return U_String renames
    +     Ada.Strings.Unbounded.To_Unbounded_String;
    +
    +   type Item_Array is array(Positive range <>, Positive range <>) of Item_Type;
    +   type Header_Array is array(Positive range <>) of U_String;
    +
    +   procedure Print(Items: Item_Array; Column_Heads: Header_Array);
    +
    +end HTML_Table;
    diff --git a/Task/Create-an-HTML-table/Ada/create-an-html-table-2.adb b/Task/Create-an-HTML-table/Ada/create-an-html-table-2.adb
    new file mode 100644
    index 0000000000..3ae2008131
    --- /dev/null
    +++ b/Task/Create-an-HTML-table/Ada/create-an-html-table-2.adb
    @@ -0,0 +1,56 @@
    +package body HTML_Table is
    +
    +   procedure Print(Items: Item_Array; Column_Heads: Header_Array) is
    +
    +      function Blanks(N: Natural) return String is
    +         -- indention for better readable HTML
    +      begin
    +         if N=0 then
    +            return "";
    +         else
    +            return " " & Blanks(N-1);
    +         end if;
    +      end Blanks;
    +
    +      procedure Print_Row(Row_Number: Positive) is
    +      begin
    +         Put(Blanks(4) & "" & Positive'Image(Row_Number) & "");
    +         for I in Items'Range(2) loop
    +            Put("" & To_String(Items(Row_Number, I)) & "");
    +                end loop;
    +            Put_Line("");
    +      end Print_Row;
    +
    +      procedure Print_Body is
    +      begin
    +         Put_Line(Blanks(2)&"");
    +         for I in Items'Range(1) loop
    +            Print_Row(I);
    +         end loop;
    +         Put_Line(Blanks(2)&"");
    +      end Print_Body;
    +
    +      procedure Print_Header is
    +         function To_Str(U: U_String) return String renames
    +           Ada.Strings.Unbounded.To_String;
    +      begin
    +         Put_Line(Blanks(2) & "");
    +         Put(Blanks(4) & "");
    +         for I in Column_Heads'Range loop
    +            Put("" & To_Str(Column_Heads(I)) & "");
    +         end loop;
    +         Put_Line("");
    +         Put_Line(Blanks(2) & "");
    +      end Print_Header;
    +
    +   begin
    +      if Items'Length(2) /= Column_Heads'Length then
    +         raise Constraint_Error with "number of headers /= number of columns";
    +      end if;
    +      Put_Line("");
    +      Print_Header;
    +      Print_Body;
    +      Put_Line("
    "); + end Print; + +end HTML_Table; diff --git a/Task/Create-an-HTML-table/Ada/create-an-html-table-3.adb b/Task/Create-an-HTML-table/Ada/create-an-html-table-3.adb new file mode 100644 index 0000000000..a904c858e5 --- /dev/null +++ b/Task/Create-an-HTML-table/Ada/create-an-html-table-3.adb @@ -0,0 +1,32 @@ +with Ada.Text_IO, Ada.Numerics.Discrete_Random, HTML_Table; + +procedure Test_HTML_Table is + + -- define the Item_Type and the random generator + type Four_Digits is mod 10_000; + package Rand is new Ada.Numerics.Discrete_Random(Four_Digits); + Gen: Rand.Generator; + + -- now we instantiate the generic package HTML_Table + package T is new HTML_Table + (Item_Type => Four_Digits, + To_String => Four_Digits'Image, + Put => Ada.Text_IO.Put, + Put_Line => Ada.Text_IO.Put_Line); + + -- define the object that will the values that the table contains + The_Table: T.Item_Array(1 .. 4, 1..3); + +begin + -- fill The_Table with random values + Rand.Reset(Gen); + for Rows in The_Table'Range(1) loop + for Cols in The_Table'Range(2) loop + The_Table(Rows, Cols) := Rand.Random(Gen); + end loop; + end loop; + + -- output The_Table + T.Print(Items => The_Table, + Column_Heads => (T.Convert("X"), T.Convert("Y"), T.Convert("Z"))); +end Test_HTML_Table; diff --git a/Task/Create-an-HTML-table/Ada/create-an-html-table-4.adb b/Task/Create-an-HTML-table/Ada/create-an-html-table-4.adb new file mode 100644 index 0000000000..a3587d5967 --- /dev/null +++ b/Task/Create-an-HTML-table/Ada/create-an-html-table-4.adb @@ -0,0 +1,11 @@ + + + + + + + + + + +
    XYZ
    1 7255 3014 9436
    2 554 3314 8765
    3 4832 129 2048
    4 31 6897 8265
    diff --git a/Task/Create-an-HTML-table/AppleScript/create-an-html-table.applescript b/Task/Create-an-HTML-table/AppleScript/create-an-html-table.applescript new file mode 100644 index 0000000000..1f7a286b5c --- /dev/null +++ b/Task/Create-an-HTML-table/AppleScript/create-an-html-table.applescript @@ -0,0 +1,31 @@ +on pad_table(s, char2) + set opener to "" + set closer to "" + repeat with i from 1 to length of s + set x to item i of s + set item i of s to opener & x & closer + end repeat + return "" & s & "" +end pad_table + +on gen_row(n, ncols) + set row to {n} + repeat ncols times + set row to row & (random number from 1 to 9999) + end repeat + return row +end gen_row + +on html_table(headings, nrows) + set ncols to length of headings + set theader to pad_table({""} & headings, "h") + set tbody to {} + repeat with i from 1 to nrows + set tbody to tbody & pad_table(gen_row(i, ncols), "d") + end repeat + set out to {""} & theader & tbody & {"
    "} + set AppleScript's text item delimiters to linefeed + return out as text +end html_table + +html_table({"X", "Y", "Z"}, 3) diff --git a/Task/Create-an-HTML-table/COBOL/create-an-html-table.cob b/Task/Create-an-HTML-table/COBOL/create-an-html-table.cob new file mode 100644 index 0000000000..392e157394 --- /dev/null +++ b/Task/Create-an-HTML-table/COBOL/create-an-html-table.cob @@ -0,0 +1,115 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Table. + AUTHOR. Bill Gunshannon. + INSTALLATION. Home. + DATE-WRITTEN. 1 January 2022. + ************************************************************ + ** Program Abstract: + ** Data values are hardcoded in this example but they + ** could come from anywhere. Computed, read from a + ** file, input from the keyboard. + ************************************************************ + + ENVIRONMENT DIVISION. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT Table-File ASSIGN TO "index.html" + ORGANIZATION IS LINE SEQUENTIAL. + + DATA DIVISION. + + FILE SECTION. + + FD Table-File + DATA RECORD IS Table-Record. + 01 Table-Record. + 05 Field1 PIC X(80). + + WORKING-STORAGE SECTION. + + 01 Table-Data. + 05 Line3. + 10 Line3-Value1 PIC S9(4) VALUE 1234. + 10 Line3-Value2 PIC S9(4) VALUE 23. + 10 Line3-Value3 PIC S9(4) VALUE -123. + 05 Line4. + 10 Line4-Value1 PIC S9(4) VALUE 123. + 10 Line4-Value2 PIC S9(4) VALUE 12. + 10 Line4-Value3 PIC S9(4) VALUE -1234. + 05 Line5. + 10 Line5-Value1 PIC S9(4) VALUE 567. + 10 Line5-Value2 PIC S9(4) VALUE 6789. + 10 Line5-Value3 PIC S9(4) VALUE 3. + + + 01 Table-HTML. + 05 Line1 PIC X(16) VALUE + "". + 05 Line2 PIC X(40) VALUE + "". + 05 Line3. + 10 Line3-Field1 PIC X(31) VALUE + "". + 05 Line4. + 10 Line4-Field1 PIC X(31) VALUE + "". + 05 Line5. + 10 Line5-Field1 PIC X(31) VALUE + "". + 05 Line6 PIC X(8) VALUE + "
    XYZ
    1". + 10 Line3-Value1 PIC -ZZZ9. + 10 Line3-Field3 PIC X(9) VALUE + "". + 10 Line3-Value2 PIC -ZZZ9. + 10 Line3-Field5 PIC X(9) VALUE + "". + 10 Line3-Value3 PIC -ZZZ9. + 10 Line3-Field5 PIC X(10) VALUE + "
    2". + 10 Line4-Value1 PIC -ZZZ9. + 10 Line4-Field3 PIC X(9) VALUE + "". + 10 Line4-Value2 PIC -ZZZ9. + 10 Line4-Field5 PIC X(9) VALUE + "". + 10 Line4-Value3 PIC -ZZZ9. + 10 Line4-Field5 PIC X(10) VALUE + "
    3". + 10 Line5-Value1 PIC -ZZZ9. + 10 Line5-Field3 PIC X(9) VALUE + "". + 10 Line5-Value2 PIC -ZZZ9. + 10 Line5-Field5 PIC X(9) VALUE + "". + 10 Line5-Value3 PIC -ZZZ9. + 10 Line5-Field5 PIC X(10) VALUE + "
    ". + + PROCEDURE DIVISION. + + Main-Program. + OPEN OUTPUT Table-File. + MOVE CORRESPONDING Table-Data TO Table-HTML. + PERFORM Write-Table. + CLOSE Table-File. + STOP RUN. + + + Write-Table. + WRITE Table-Record FROM Line1 OF Table-HTML + AFTER ADVANCING 1 LINE. + WRITE Table-Record FROM Line2 OF Table-HTML + AFTER ADVANCING 1 LINE. + WRITE Table-Record FROM Line3 OF Table-HTML + AFTER ADVANCING 1 LINE. + WRITE Table-Record FROM Line4 OF Table-HTML + AFTER ADVANCING 1 LINE. + WRITE Table-Record FROM Line5 OF Table-HTML + AFTER ADVANCING 1 LINE. + WRITE Table-Record FROM Line6 OF Table-HTML + AFTER ADVANCING 1 LINE. + + + END-PROGRAM. diff --git a/Task/Create-an-HTML-table/EasyLang/create-an-html-table.easy b/Task/Create-an-HTML-table/EasyLang/create-an-html-table.easy index 48a0bfe022..88af54f0df 100644 --- a/Task/Create-an-HTML-table/EasyLang/create-an-html-table.easy +++ b/Task/Create-an-HTML-table/EasyLang/create-an-html-table.easy @@ -7,8 +7,8 @@ print "" for r to 3 write "" & r for c to 3 - write "" & random 200 + write "" & random 1 200 . print "" . -print "" +print "" diff --git a/Task/Create-an-HTML-table/Euphoria/create-an-html-table-1.eu b/Task/Create-an-HTML-table/Euphoria/create-an-html-table-1.eu new file mode 100644 index 0000000000..0954bcaab4 --- /dev/null +++ b/Task/Create-an-HTML-table/Euphoria/create-an-html-table-1.eu @@ -0,0 +1,10 @@ +puts(1,"\n") +puts(1," \n") +for i = 1 to 3 do + printf(1," ",i) + for j = 1 to 3 do + printf(1,"",rand(10000)) + end for + puts(1,"\n") +end for +puts(1,"
    XYZ
    %d%d
    ") diff --git a/Task/Create-an-HTML-table/Euphoria/create-an-html-table-2.eu b/Task/Create-an-HTML-table/Euphoria/create-an-html-table-2.eu new file mode 100644 index 0000000000..8738f86a91 --- /dev/null +++ b/Task/Create-an-HTML-table/Euphoria/create-an-html-table-2.eu @@ -0,0 +1,6 @@ + + + + + +
    XYZ
    1797873762382
    2363219478900
    3409815632762
    diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.ps1 b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.ps1 new file mode 100644 index 0000000000..d440a0c603 --- /dev/null +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.ps1 @@ -0,0 +1,10 @@ +# Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser. +ConvertTo-Html -inputobject (Get-Date) + +# Create a PowerShell object using a HashTable +$object = [PSCustomObject]@{ + 'A'=(Get-Random -Minimum 0 -Maximum 10); + 'B'=(Get-Random -Minimum 0 -Maximum 10); + 'C'=(Get-Random -Minimum 0 -Maximum 10)} + +$object | ConvertTo-Html diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.ps1 b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.ps1 new file mode 100644 index 0000000000..ae0821366c --- /dev/null +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.ps1 @@ -0,0 +1,25 @@ + + + +HTML TABLE + + + + + +
    DisplayHintDateTimeDateDayDayOfWeekDayOfYearHourKindMilliseco +ndMinuteMonthSecondTicksTimeOfDayYear
    DateTimeSunday, October 26, 2014 2:32:31 PM10/26/2014 12:00:00 AM26Sunday29914< +/td>Local56332103163549930751563463814:32:31.56346382014
    + + + + + +HTML TABLE + + + + + +
    CBA
    873
    + diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.ps1 b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.ps1 new file mode 100644 index 0000000000..5f5cf4f5a1 --- /dev/null +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.ps1 @@ -0,0 +1 @@ +$object | ConvertTo-Html | Out-File -FilePath $env:temp\test.html ; invoke-item $env:temp\test.html diff --git a/Task/Create-an-HTML-table/R/create-an-html-table.r b/Task/Create-an-HTML-table/R/create-an-html-table.r new file mode 100644 index 0000000000..4818c382a0 --- /dev/null +++ b/Task/Create-an-HTML-table/R/create-an-html-table.r @@ -0,0 +1,15 @@ +html_table <- function(headings, nrows){ + ncols <- length(headings) + pad_table <- function(s, char2="d"){ + pad <- paste0("", s, "", collapse="") + paste0("", pad, "", collapse="") + } + theader <- pad_table(c("", headings), char2="h") + gen_row <- function(n) c(n, sample(9999, ncols)) + tbody <- lapply(1:nrows, gen_row) |> sapply(pad_table) + cat("", theader, sep="\n") + writeLines(tbody) + cat("
    \n") +} + +html_table(c("X", "Y", "Z"), 3) diff --git a/Task/Create-an-HTML-table/Rebol/create-an-html-table-1.rebol b/Task/Create-an-HTML-table/Rebol/create-an-html-table-1.rebol new file mode 100644 index 0000000000..6460883556 --- /dev/null +++ b/Task/Create-an-HTML-table/Rebol/create-an-html-table-1.rebol @@ -0,0 +1,37 @@ +Rebol [ + title: "Rosetta code: Create an HTML table" + file: %Create_an_HTML_table.r3 + url: https://rosettacode.org/wiki/Create_an_HTML_table + note: "Based on Red language implementation!" +] +table-rows: func [][rejoin [ + first-tr newline + rand-tr 1 newline + rand-tr 2 newline + rand-tr 3 newline + rand-tr 4 newline + rand-tr 5 newline +]] +td-data: does [999 + random 9000] +rand-td: does [form-tag 'td td-data] +rand-tr: func [i][rejoin [ + form-tag 'tr + rejoin [(form-tag 'td i) rand-td rand-td rand-td] +]] +first-tr: func[][rejoin [ + form-tag 'tr rejoin [ + form-tag 'th "" + form-tag 'th "X" + form-tag 'th "Y" + form-tag 'th "Z" + ] +]] +form-tag: func [tag contents /attr a][ + ajoin [ + "<" tag (if attr [ajoin [" " a/1 "=" {"} a/2 {"}]]) ">" + contents + "" + ] +] + +print form-tag 'table table-rows diff --git a/Task/Create-an-HTML-table/Rebol/create-an-html-table-2.rebol b/Task/Create-an-HTML-table/Rebol/create-an-html-table-2.rebol new file mode 100644 index 0000000000..c3c7cbc8af --- /dev/null +++ b/Task/Create-an-HTML-table/Rebol/create-an-html-table-2.rebol @@ -0,0 +1,7 @@ + + + + + + +
    XYZ
    1209634429408
    2967939177056
    3215143569440
    4274197384967
    5237771907304
    diff --git a/Task/Create-an-HTML-table/VBScript/create-an-html-table.vbs b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vbs new file mode 100644 index 0000000000..488b88273f --- /dev/null +++ b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vbs @@ -0,0 +1,40 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +'Open the input csv file for reading. The file is in the same folder as the script. +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\in.csv",1) + +'Create the output html file. +Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\out.html",2,True) + +'Write the html opening tags. +objOutHTML.Write "" & vbCrLf + +'Declare table properties. +objOutHTML.Write "" & vbCrLf + +'Write column headers. +objOutHTML.Write "" & vbCrLf + +'Go through each line of the input csv file and write to the html output file. +n = 1 +Do Until objInFile.AtEndOfStream + line = objInFile.ReadLine + If Len(line) > 0 Then + token = Split(line,",") + objOutHTML.Write "" + For i = 0 To UBound(token) + objOutHTML.Write "" + Next + objOutHTML.Write "" & vbCrLf + End If + n = n + 1 +Loop + +'Write the html closing tags. +objOutHTML.Write "
    XYZ
    " & n & "" & token(i) & "
    " + +objInFile.Close +objOutHTML.Close +Set objFSO = Nothing diff --git a/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.adb b/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.adb new file mode 100644 index 0000000000..eaf521cd44 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-1.adb @@ -0,0 +1,3 @@ +type IO_Port is mod 2**8; -- One byte +Device_Port : type IO_Port; +for Device_Port'Address use 16#FFFF_F000#; diff --git a/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.adb b/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.adb new file mode 100644 index 0000000000..18e6cab1c8 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/Ada/create-an-object-at-a-given-address-2.adb @@ -0,0 +1,13 @@ +with Ada.Text_IO; use Ada.Text_IO; +with System.Storage_Elements; use System.Storage_Elements; + +procedure Test_Address is + X : Integer := 123; + Y : Integer; + for Y'Address use X'Address; +begin + Put_Line ("At address:" & Integer_Address'Image (To_Integer (Y'Address))); + Put_Line (Integer'Image (Y)); + X := 456; + Put_Line (Integer'Image (Y)); +end Test_Address; diff --git a/Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cob b/Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cob new file mode 100644 index 0000000000..b785bd467c --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/COBOL/create-an-object-at-a-given-address.cob @@ -0,0 +1,18 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. object-address-test. +DATA DIVISION. +LOCAL-STORAGE SECTION. +77 int-space PICTURE IS 9(5) VALUE IS 12345. +77 addr PICTURE IS 9(5) BASED VALUE IS ZERO. +77 point USAGE IS POINTER. +PROCEDURE DIVISION. + DISPLAY "Value of integer object : " int-space + SET point TO ADDRESS OF int-space + DISPLAY "Machine address of object : " point + SET ADDRESS OF addr TO point + DISPLAY "Value of referent object : " addr + MOVE 65535 TO int-space + DISPLAY "New value of original : " addr + DISPLAY "New value of reference : " int-space + GOBACK. +END PROGRAM object-address-test. diff --git a/Task/Create-an-object-at-a-given-address/V-(Vlang)/create-an-object-at-a-given-address.v b/Task/Create-an-object-at-a-given-address/V-(Vlang)/create-an-object-at-a-given-address.v new file mode 100644 index 0000000000..f0895f2e33 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/V-(Vlang)/create-an-object-at-a-given-address.v @@ -0,0 +1,22 @@ +fn main() { + // create an integer object + + mut target := 42 + mut target_ref := &target + + println("Here is an integer: ${target}") + + // print the machine address of the object + + println("And its reference is: ${target_ref}") + + // take the address of the object and create another integer object at this address + + unsafe{(*target_ref) = 69} + + println("Newly assigned value is: ${*target_ref}") + + // print the value of this object to verify that it is same as one of the origin + + println("Compared with referent: ${target}") +} diff --git a/Task/Cuban-primes/AWK/cuban-primes.awk b/Task/Cuban-primes/AWK/cuban-primes.awk new file mode 100644 index 0000000000..93acddba9e --- /dev/null +++ b/Task/Cuban-primes/AWK/cuban-primes.awk @@ -0,0 +1,28 @@ +# syntax: GAWK -f CUBAN_PRIMES.AWK +# converted from EasyLang +BEGIN { + limit = 200 + printf("The first %d cuban primes are:\n",limit) + while (count < 10000 ) { + i++ + di = 3 * i * (i + 1) + 1 + if (is_prime(di) == 1) { + if (++count <= limit) { + printf("%8d%s",di,count%10?"":"\n") + } + } + } + printf("\ncuban prime # %d is: %'d\n",count,di) + exit(0) +} +function is_prime(x, i) { + if (x <= 1) { + return(0) + } + for (i=2; i<=int(sqrt(x)); i++) { + if (x % i == 0) { + return(0) + } + } + return(1) +} diff --git a/Task/Cuban-primes/Ada/cuban-primes.adb b/Task/Cuban-primes/Ada/cuban-primes.adb new file mode 100644 index 0000000000..d824856bc4 --- /dev/null +++ b/Task/Cuban-primes/Ada/cuban-primes.adb @@ -0,0 +1,136 @@ +-- Rosetta Code Task written in Ada +-- Cuban primes (related to "Cubes", not "Cubans") +-- https://rosettacode.org/wiki/Cuban_primes +-- July 2024, R. B. E. + +-- Using this Cuban Primes Definition: primes of the form: n^3 - (n-1)^3. + +-- ToDo: +-- Commatize the results (an advanced subtask) +-- Could replace the "activity dots" generated during the big calculations with a spinner + +-- NOTE: Using GNAT Big_Numbers package. +-- Takes a very long time to generate the 100_000th cuban prime: about 75 minutes on a M1 Mac Mini. + +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; +with Ada.Strings; use Ada.Strings; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +with Ada.Strings.Maps; use Ada.Strings.Maps; +with Ada.Real_Time; use Ada.Real_Time; + +procedure Cuban_Primes is + + function Is_Prime (A : Positive) return Boolean is + D : Positive; + begin + if A < 2 then + return False; + end if; + if A in 2 .. 3 then + return True; + end if; + if A mod 2 = 0 then + return False; + end if; + if A mod 3 = 0 then + return False; + end if; + D := 5; + while D * D <= A loop + if A mod D = 0 then + return False; + end if; + D := D + 2; + if A mod D = 0 then + return False; + end if; + D := D + 4; + end loop; + return True; + end Is_Prime; + + function Is_Prime (A : Big_Natural) return Boolean is + D : Big_Natural; + B0 : constant Big_Natural := To_Big_Integer (0); + B1 : constant Big_Natural := To_Big_Integer (1); + B2 : constant Big_Natural := To_Big_Integer (2); + B3 : constant Big_Natural := To_Big_Integer (3); + B4 : constant Big_Natural := To_Big_Integer (4); + B5 : constant Big_Natural := To_Big_Integer (5); + begin + if A < B2 then + return False; + end if; + if (A = B2) or (A = B3) then + return True; + end if; + if A mod B2 = B0 then + return False; + end if; + if A mod B3 = B0 then + return False; + end if; + D := B5; + while D * D <= A loop + if A mod D = B0 then + return False; + end if; + D := D + B2; + if A mod D = B0 then + return False; + end if; + D := D + B4; + end loop; + return True; + end Is_Prime; + + Cuban_Count : Natural := 1; + Candidate : Natural; + Big_Candidate : Big_Natural; + Max_Cuban_for_the_Table : constant Integer := 200; + Max_Cuban_below_the_Table : constant Integer := 100_000; + Start_Time, Stop_Time : Time; + Elapsed_Time : Time_Span; + +begin + Put ("The first "); + Put (Max_Cuban_for_the_Table, 1); + Put_Line (" Cuban Primes..."); + for I in 1 .. Integer'Last loop + Candidate := ((I + 1) ** 3) - (I ** 3); + if Is_Prime (Candidate) then + Put (Candidate, 8); + if ((Cuban_Count rem 14) = 0) then + New_Line; + end if; + Cuban_Count := Cuban_Count + 1; + end if; + exit when Cuban_Count > Max_Cuban_for_the_Table; + end loop; + New_Line (2); + Cuban_Count := 1; + Start_Time := Clock; + Put ("The "); + Put (Max_Cuban_below_the_Table, 1); + Put ("th Cuban Prime is: "); + for I in 1 .. Integer'Last loop + Big_Candidate := (((To_Big_Integer (I) + 1) ** 3) - (To_Big_Integer (I) ** 3)); + if Is_Prime (Big_Candidate) then + Cuban_Count := Cuban_Count + 1; + if (Cuban_Count rem 10_000) = 0 then + Put ("."); + end if; + end if; + exit when Cuban_Count = Max_Cuban_below_the_Table; + end loop; + New_Line; + Put (Trim (To_String (Big_Candidate), Right)); + Stop_Time := Clock; + Elapsed_Time := Stop_Time - Start_Time; + New_Line; + Put_Line ("Elapsed time to calculate: " & Duration'Image (To_Duration (Elapsed_Time)) & " seconds"); +end Cuban_Primes; diff --git a/Task/Cuban-primes/Fortran/cuban-primes.f b/Task/Cuban-primes/Fortran/cuban-primes.f new file mode 100644 index 0000000000..d2dcee4458 --- /dev/null +++ b/Task/Cuban-primes/Fortran/cuban-primes.f @@ -0,0 +1,201 @@ +! Cuban Prime Numbers +! tested with GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! +! Note that both intel ifx and VSI Fortran do not compile this code because they do not +! support 16-byte-integers. +! +! U.B., September 2025 +! + +program CubanPrimes + implicit none + + integer, parameter :: llint=16 + integer, parameter ::strLen = 20 + + integer (kind=llint) :: nc = 0, i=0, di + character (len=strLen) :: sdi ! for formatted output of di + + write (*, *) 'The first 200 cuban prime numbers are:' + do while (nc .lt. 100001) + di = diff_cubes(i) + if (isprime(di)) then + nc = nc + 1 + if (nc .le. 200) then + sdi = GroupedDigits (di, 10) + write (*, '(A10)', advance='no') sdi + if (mod (nc,10) .eq. 0 ) then + write (*,*) + end if + end if + if (nc .eq. 100000) then + sdi = GroupedDigits (di, 18) + write (*,'(//"The 100000th cuban prime number is: ", A)') sdi + exit + end if + end if + i = i + 1 + end do + + + contains + + !------------------------------------------------ + ! Calculate difference (n+1)³ - n³ = 3n² + 3n + 1 + !------------------------------------------------ + function diff_cubes( n ) result (n3) + integer (kind=llint),intent(in) ::n + integer (kind=llint) :: n3 + n3 = 3*n*(n+1) + 1 + end function + + + ! ---------------------------------------------------------------- + ! Fortran does not have a way to use locales for output. + ! Manual insert of separating commas such as 1,345,678 for 1345678 + ! ---------------------------------------------------------------- + function GroupedDigits (n, width) result (outStr) + integer(kind=llint), intent (in) :: n + integer :: width + character (len=width) :: outStr + character (len=2*strLen) :: workStr + integer :: ii, jj, cnt, trueLen + + + ! Write n into a string, then copy the digits to a second string, + ! inserting separater after every 3 digits. + write (workStr, '(i0)') n + ! Adjust left, then cutoff trailing blanks + workstr = adjustl (workstr) + trueLen = len_trim (workStr) + + outStr = ' ' + jj = width + cnt = 0 + do ii=trueLen, 1, -1 ! Copy backwards for correct grouping. + outStr (jj:jj) = workStr (ii:ii) + jj = jj -1 + cnt = cnt + 1 + ! Insert comma after 3 digits, but only if more digits follow. + if (mod (cnt, 3) .eq. 0 .and. ii .gt. 1 .and. workStr(ii-1:ii-1) .ne. ' ') then + outStr (jj:jj) = ',' + jj = jj - 1 + endif + end do + + end function GroupedDigits + + + + + + + ! ---------------------------------------- + ! Miller-Rabin test if n is a prime number + ! ---------------------------------------- + function isPrime(n) result (YN) + + integer(kind=llint), intent(in) ::n + logical :: YN + integer (kind=llint) :: ar (5), i + + ! Early return in most trivial cases + if (n .le. 1) then ! Too small + YN=.false. + return + endif + if (n .eq. 2) then ! 2 is prime + YN=.true. + return + endif + if (mod (n , 2) .eq. 0) then ! all other even number are not prime + YN=.false. + return + endif + if (n .lt. 9) then ! all odd numbers < 9 are prime + YN=.true. + return + endif + if (mod (n , 3) .eq. 0) then ! multiples of 3 aren't prime + YN=.false. + return + endif + if (mod (n , 5) .eq. 0) then ! multiples of 5 aren't prime + YN=.false. + return + endif + + ! these 5 bases are required and sufficient to test numbers up to 2,152,302,898,747 + ar(1) = 2 + ar(2) = 3 + ar(3) = 5 + ar(4) = 7 + ar(5) = 11 + do i = 1, 5 + if (Witness(ar(i), n)) then + YN=.false. ! Not prime + return + endif + end do + YN= .true. ! prime + + end function isPrime + + ! ------------------------------------- + ! helper function for Miller Rabin test + ! ------------------------------------- + function Witness(a, n) result (YN) + + integer (kind=llint) , intent(in) :: a + integer (kind=llint) , intent(in) :: n + + + integer (kind=llint) :: t, u, i + logical :: YN + integer (kind=llint) :: xi1, xi2 + + t = 0 + u = n - 1 + do while (iand(u , 1_llint) .eq. 0) + t = t + 1 + u = u / 2 + end do + + xi1 = ModularExp(a, u, n); + do i = 0, t-1 + xi2 = mod (xi1 * xi1 , n) + if ((xi2 .eq. 1) .and. (xi1 .ne. 1) .and. (xi1 .ne. (n - 1))) then + YN = .true. + return + endif + xi1 = xi2 + end do + if (xi1 .ne. 1) then + YN=.true. + else + YN = .false. + endif + end function Witness + + ! ------------------------------------- + ! helper function for Miller Rabin test + ! ------------------------------------- + function ModularExp(a, b, n) result(d) + + integer(kind=llint) , intent(in) :: a,b,n + integer (kind=llint) :: d + integer (kind=llint) :: i, k + d = 1 + k = 0 + do while (ishft (b, -k) .gt. 0) + k = k + 1 + end do + do i = k - 1, 0, -1 + d = mod (d*d, n) + if (iand (ishft (b, -i) , 1_llint) .gt. 0) d = mod (d*a ,n); + end do + + end function ModularExp + + +end program diff --git a/Task/Cuban-primes/FutureBasic/cuban-primes.basic b/Task/Cuban-primes/FutureBasic/cuban-primes.basic new file mode 100644 index 0000000000..3bbad2af09 --- /dev/null +++ b/Task/Cuban-primes/FutureBasic/cuban-primes.basic @@ -0,0 +1,40 @@ +BBOOL local fn IsPrime( p as UInt64 ) + if ( p < 2 ) then return NO + if ( p % 2 == 0 ) then return ( p == 2 ) + UInt64 limit = fn sqrt( (double)p ) + for UInt64 i = 3 to limit step 2 + if ( p % i == 0 ) then return NO + next +end fn = YES + +local fn CubanPrimes( howMany as NSUInteger ) + CFMutableArrayRef cubanPrimes = fn MutableArrayNew + UInt64 n = 1 + + while ( fn ArrayCount( cubanPrimes ) < howMany ) + UInt64 p = 3 * n * n + 3 * n + 1 + if ( fn IsPrime( p ) ) + MutableArrayAddObject( cubanPrimes, @(p) ) + end if + n++ + wend + + printf @"\nFirst 200 Cuban primes:\n" + for NSUInteger i = 0 to fn ArrayCount( cubanPrimes ) - 1 + printf @"%7lu\b", fn NumberUnsignedLongValue( cubanPrimes[i] ) + if ( i < fn ArrayCount( cubanPrimes ) - 1 ) + if ( i % 8 == 7 ) + print + else + print @"\t" + end if + end if + next + print +end fn + +window 1, @"cuban Primes", ( 0, 0, 630, 440 ) + +fn CubanPrimes( 200 ) + +HandleEvents diff --git a/Task/Cuban-primes/JavaScript/cuban-primes.js b/Task/Cuban-primes/JavaScript/cuban-primes.js new file mode 100644 index 0000000000..86fd7b9358 --- /dev/null +++ b/Task/Cuban-primes/JavaScript/cuban-primes.js @@ -0,0 +1,68 @@ +const MAX = 1400000; +const primes = new Array(MAX); + +function preCompute() { + // Initialize sieve + for (let i = 2; i < MAX; i++) { + primes[i] = true; + } + + // Sieve of Eratosthenes + for (let i = 2; i < MAX; i++) { + if (primes[i]) { + for (let j = 2 * i; j < MAX; j += i) { + primes[j] = false; + } + } + } +} + +function isPrime(n) { + if (n < MAX) { + return primes[n]; + } + const max = Math.floor(Math.sqrt(n)); + for (let i = 3; i <= max; i++) { + if (primes[i] && n % i === 0) { + return false; + } + } + return true; +} + +function cubanPrime(n, display) { + let count = 0; + let result = 0; + let output = ''; + + for (let i = 0; count < n; i++) { + const test = 1 + 3 * i * (i + 1); + if (isPrime(test)) { + count++; + result = test; + if (display) { + const formatted = test.toLocaleString('en-US').padStart(10); + output += formatted + (count % 10 === 0 ? '\n' : ''); + } + } + } + + if (display) { + console.log(output); + } + return result; +} + +// Main execution +preCompute(); + +// First 200 Cuban primes +cubanPrime(200, true); +console.log(); + +// Specific Cuban primes +for (let i = 1; i <= 5; i++) { + const max = Math.pow(10, i); + const prime = cubanPrime(max, false); + console.log(`${max.toLocaleString('en-US')}-th cuban prime = ${prime.toLocaleString('en-US')}`); +} diff --git a/Task/Cuban-primes/Pluto/cuban-primes.pluto b/Task/Cuban-primes/Pluto/cuban-primes.pluto new file mode 100644 index 0000000000..27d28ef959 --- /dev/null +++ b/Task/Cuban-primes/Pluto/cuban-primes.pluto @@ -0,0 +1,55 @@ +local fmt = require "fmt" + +local primes = {3, 5} +local cutoff = 200 +local bigone = 100_000 +local cubans = {} +local big_cuban = "" +local c = 0 +local show_each = true +local u = 0 +local v = 1 + +for i = 1, (1 << 20) - 1 do + local found = false + u += 6 + v += u + local mx = math.floor(math.sqrt(v)) + for primes as item do + if item > mx then break end + if v % item == 0 then + found = true + break + end + end + if !found then + c += 1 + if show_each then + local z = primes:back() + while z <= v - 2 do + z += 2 + local fnd = false + for primes as item do + if item > mx then break end + if z % item == 0 then + fnd = true + break + end + end + if !fnd then primes:insert(z) end + end + primes:insert(v) + cubans:insert(fmt.int(v)) + if c == cutoff then show_each = false end + end + if c == bigone then + big_cuban = fmt.int(v) + break + end + end +end + +print("The first 200 cuban primes are:-") +fmt.tprint("%10s", cubans:slice(1, 200), 10) + +print($"\nThe 100,000th cuban prime is {big_cuban}") diff --git a/Task/Cuban-primes/Uiua/cuban-primes.uiua b/Task/Cuban-primes/Uiua/cuban-primes.uiua new file mode 100644 index 0000000000..106acb7bf4 --- /dev/null +++ b/Task/Cuban-primes/Uiua/cuban-primes.uiua @@ -0,0 +1,5 @@ +B ~ "git:github.com/mykdavies/uiua-bigint/" ~ Add Big One Pow Sub +IsP ← memo(=⊣⊸°/×) +C ← ▽⊸≡IsP⧈-ⁿ3↘1⇡ +↯∞_10↙200C800 +⊡99999▽⊸≡IsP⧈(°Big Sub)⬚0≡(Pow3Big)↘1⇡800000 diff --git a/Task/Cullen-and-Woodall-numbers/COBOL/cullen-and-woodall-numbers.cob b/Task/Cullen-and-Woodall-numbers/COBOL/cullen-and-woodall-numbers.cob new file mode 100644 index 0000000000..f24eca1b5f --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/COBOL/cullen-and-woodall-numbers.cob @@ -0,0 +1,29 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. CullenWoodallNumbers. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 n PIC 9(4) COMP-5 VALUE 1. + 01 num PIC 9(8) COMP-5. + 01 i PIC 9(4) COMP-5 VALUE 1. + + PROCEDURE DIVISION. + DISPLAY "First 20 Cullen numbers:". + + PERFORM VARYING i FROM 1 BY 1 UNTIL i > 20 + COMPUTE num = i * (2 ** i) + 1 + DISPLAY num WITH NO ADVANCING + DISPLAY " " WITH NO ADVANCING + END-PERFORM. + + DISPLAY " ". + + DISPLAY "First 20 Woodall numbers:". + + PERFORM VARYING i FROM 1 BY 1 UNTIL i > 20 + COMPUTE num = i * (2 ** i) - 1 + DISPLAY num WITH NO ADVANCING + DISPLAY " " WITH NO ADVANCING + END-PERFORM. + + STOP RUN. diff --git a/Task/Cullen-and-Woodall-numbers/Crystal/cullen-and-woodall-numbers.cr b/Task/Cullen-and-Woodall-numbers/Crystal/cullen-and-woodall-numbers.cr new file mode 100644 index 0000000000..c98b747407 --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/Crystal/cullen-and-woodall-numbers.cr @@ -0,0 +1,12 @@ +require "big" + +def cullen_numbers + (1..).each.map {|n| (2.to_big_i ** n) * n + 1 } +end + +def woodall_numbers + (1..).each.map {|n| (2.to_big_i ** n) * n - 1 } +end + +puts cullen_numbers.first(20).to_a +puts woodall_numbers.first(20).to_a diff --git a/Task/Cullen-and-Woodall-numbers/Fortran/cullen-and-woodall-numbers.f b/Task/Cullen-and-Woodall-numbers/Fortran/cullen-and-woodall-numbers.f new file mode 100644 index 0000000000..03889b2171 --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/Fortran/cullen-and-woodall-numbers.f @@ -0,0 +1,27 @@ +! +! Cullen and Woodall numbers +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! + +program CullenWoodall + + implicit none + + integer :: power + + integer ::ii, Cullen + integer, parameter :: nNum=20 + + power = 1 + write (6, '(" n Cullen Woodall")') + write (6, '(" ----------------------")') + do ii=1, nNum + power = power * 2 + cullen = ii * power + 1 + write (6, '(x, i2, ": ", I9, x, i9 )' ) ii, cullen, cullen-2 + end do + + +end program CullenWoodall diff --git a/Task/Cullen-and-Woodall-numbers/JavaScript/cullen-and-woodall-numbers.js b/Task/Cullen-and-Woodall-numbers/JavaScript/cullen-and-woodall-numbers.js new file mode 100644 index 0000000000..a749d8fe7b --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/JavaScript/cullen-and-woodall-numbers.js @@ -0,0 +1,59 @@ +const bigInt = require('big-integer'); +class CullenAndWoodhall { + static main() { + this.numberSequence(20, NumberType.Cullen); + this.numberSequence(20, NumberType.Woodhall); + this.primeSequence(5, NumberType.Cullen); + this.primeSequence(12, NumberType.Woodhall); + } + static numberSequence(aCount, aNumberType) { + console.log(); + console.log(`The first ${aCount} ${aNumberType} numbers are:`); + this.numberInitialise(); + for (let index = 1; index <= aCount; index++) { + process.stdout.write(this.nextNumber(aNumberType).toString() + " "); + } + console.log(); + } + static primeSequence(aCount, aNumberType) { + console.log(); + console.log(`The indexes of the first ${aCount} ${aNumberType} primes are:`); + this.primeInitialise(); + while (this.count < aCount) { + if (this.nextNumber(aNumberType).isProbablePrime(20)) { + process.stdout.write(this.primeIndex + " "); + this.count += 1; + } + this.primeIndex += 1; + } + console.log(); + } + static nextNumber(aNumberType) { + this.number = this.number.add(1); + this.power = this.power.shiftLeft(1); + if (aNumberType === NumberType.Cullen) { + return this.number.multiply(this.power).add(1); + } else { + return this.number.multiply(this.power).subtract(1); + } + } + static numberInitialise() { + this.number = bigInt(0); + this.power = bigInt(1); + } + static primeInitialise() { + this.count = 0; + this.primeIndex = 1; + this.numberInitialise(); + } + static number = bigInt(0); + static power = bigInt(1); + static count = 0; + static primeIndex = 0; + static CERTAINTY = 20; +} +const NumberType = { + Cullen: "Cullen", + Woodhall: "Woodhall" +}; +CullenAndWoodhall.main(); diff --git a/Task/Cullen-and-Woodall-numbers/Pluto/cullen-and-woodall-numbers.pluto b/Task/Cullen-and-Woodall-numbers/Pluto/cullen-and-woodall-numbers.pluto new file mode 100644 index 0000000000..7d43ffc079 --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/Pluto/cullen-and-woodall-numbers.pluto @@ -0,0 +1,38 @@ +require "bignum" + +mpz.init() -- use GMP binding + +local function cullen(n) return mpz.shl(bigint.one, n) * n + 1 end + +local function woodall(n) return cullen(n) - 2 end + +print("First 20 Cullen numbers (n * 2^n + 1):") +for n = 1, 20 do io.write($"{cullen(n):tostring()} ") end + +print("\n\nFirst 20 Woodall numbers (n * 2^n - 1):") +for n = 1, 20 do io.write($"{woodall(n):tostring()} ") end + +print("\n\nFirst 5 Cullen primes (in terms of n):") +local count = 0 +local n = 1 +while count < 5 do + local cn = cullen(n) + if mpz.isprobableprime(cn, 15) then + io.write($"{n} ") + count += 1 + end + n += 1 +end + +print("\n\nFirst 12 Woodall primes (in terms of n):") +count = 0 +n = 1 +while count < 12 do + local wn = woodall(n) + if mpz.isprobableprime(wn, 15) then + io.write($"{n} ") + count += 1 + end + n += 1 +end +print() diff --git a/Task/Cumulative-standard-deviation/ANSI-BASIC/cumulative-standard-deviation.basic b/Task/Cumulative-standard-deviation/ANSI-BASIC/cumulative-standard-deviation.basic new file mode 100644 index 0000000000..9359f72cf1 --- /dev/null +++ b/Task/Cumulative-standard-deviation/ANSI-BASIC/cumulative-standard-deviation.basic @@ -0,0 +1,37 @@ +100 REM Cumulative standard deviation +110 DECLARE EXTERNAL SUB Init +120 DECLARE EXTERNAL SUB Add +130 DECLARE EXTERNAL FUNCTION Deviation +140 DIM TestData(1 TO 8) +150 FOR I = 1 TO 8 +160 READ TestData(I) +170 NEXT I +180 DATA 2, 4, 4, 4, 5, 5, 7, 9 +190 CALL Init(N, Sum, SumOfSquares) +200 PRINT "N ITEM AVG STDDEV" +210 FOR I = LBOUND(TestData) TO UBOUND(TestData) +220 CALL Add(N, Sum, SumOfSquares, TestData(I)) +230 PRINT USING "# ": I; +240 PRINT USING " # ": TestData(I); +250 PRINT USING "#.### ": Sum / I; +260 PRINT USING " #.###": Deviation(N, Sum, SumOfSquares) +270 NEXT I +280 END +290 ! +300 EXTERNAL SUB Init(N, Sum, SumOfSquares) +310 REM The parameters N, Sum, SumOfSquares are passed by reference. So, the arguments must be variables. +320 LET N = 0 +330 LET Sum = 0.0 +340 LET SumOfSquares = 0.0 +350 END SUB +360 ! +370 EXTERNAL SUB Add(N, Sum, SumOfSquares, P) +380 REM The parameters N, Sum, SumOfSquares are passed by reference. So, the arguments must be variables. +390 LET N = N + 1 +400 LET Sum = Sum + P +410 LET SumOfSquares = SumOfSquares + P ^ 2 +420 END SUB +430 ! +440 EXTERNAL FUNCTION Deviation (N, Sum, SumOfSquares) +450 LET Deviation = SQR(SumOfSquares / N - (Sum / N) ^ 2) +460 END FUNCTION diff --git a/Task/Cumulative-standard-deviation/Ada/cumulative-standard-deviation.adb b/Task/Cumulative-standard-deviation/Ada/cumulative-standard-deviation.adb new file mode 100644 index 0000000000..b6b91eb78e --- /dev/null +++ b/Task/Cumulative-standard-deviation/Ada/cumulative-standard-deviation.adb @@ -0,0 +1,35 @@ +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; + +procedure Test_Deviation is + type Sample is record + N : Natural := 0; + Sum : Float := 0.0; + SumOfSquares : Float := 0.0; + end record; + procedure Add (Data : in out Sample; Point : Float) is + begin + Data.N := Data.N + 1; + Data.Sum := Data.Sum + Point; + Data.SumOfSquares := Data.SumOfSquares + Point ** 2; + end Add; + function Deviation (Data : Sample) return Float is + begin + return Sqrt (Data.SumOfSquares / Float (Data.N) - (Data.Sum / Float (Data.N)) ** 2); + end Deviation; + + Data : Sample; + Test : array (1..8) of Integer := (2, 4, 4, 4, 5, 5, 7, 9); +begin + for Index in Test'Range loop + Add (Data, Float(Test(Index))); + Put("N="); Put(Item => Index, Width => 1); + Put(" ITEM="); Put(Item => Test(Index), Width => 1); + Put(" AVG="); Put(Item => Float(Data.Sum)/Float(Index), Fore => 1, Aft => 3, Exp => 0); + Put(" STDDEV="); Put(Item => Deviation (Data), Fore => 1, Aft => 3, Exp => 0); + New_line; + end loop; +end Test_Deviation; diff --git a/Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-1.cob b/Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-1.cob new file mode 100644 index 0000000000..88dbe30c94 --- /dev/null +++ b/Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-1.cob @@ -0,0 +1,71 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. run-stddev. +environment division. +input-output section. +file-control. + select input-file assign to "input.txt" + organization is line sequential. +data division. +file section. +fd input-file. + 01 inp-record. + 03 inp-fld pic 9(03). +working-storage section. +01 filler pic 9(01) value 0. + 88 no-more-input value 1. +01 ws-tb-data. + 03 ws-tb-size pic 9(03). + 03 ws-tb-table. + 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times + depending on ws-tb-size. +01 ws-stddev pic s9(05)v9999 comp-3. +PROCEDURE DIVISION. + move 0 to ws-tb-size + open input input-file + read input-file + at end + set no-more-input to true + end-read + perform + test after + until no-more-input + add 1 to ws-tb-size + move inp-fld to ws-tb-fld (ws-tb-size) + call 'stddev' using by reference ws-tb-data + ws-stddev + display 'inp=' inp-fld ' stddev=' ws-stddev + read input-file at end set no-more-input to true end-read + end-perform + close input-file + stop run. +end program run-stddev. +IDENTIFICATION DIVISION. +PROGRAM-ID. stddev. +data division. +working-storage section. +01 ws-tbx pic s9(03) comp. +01 ws-tb-work. + 03 ws-sum pic s9(05)v9999 comp-3 value +0. + 03 ws-sumsq pic s9(05)v9999 comp-3 value +0. + 03 ws-avg pic s9(05)v9999 comp-3 value +0. +linkage section. +01 ws-tb-data. + 03 ws-tb-size pic 9(03). + 03 ws-tb-table. + 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times + depending on ws-tb-size. +01 ws-stddev pic s9(05)v9999 comp-3. +PROCEDURE DIVISION using ws-tb-data ws-stddev. + compute ws-sum = 0 + perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size + compute ws-sum = ws-sum + ws-tb-fld (ws-tbx) + end-perform + compute ws-avg rounded = ws-sum / ws-tb-size + compute ws-sumsq = 0 + perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size + compute ws-sumsq = ws-sumsq + + (ws-tb-fld (ws-tbx) - ws-avg) ** 2.0 + end-perform + compute ws-stddev = ( ws-sumsq / ws-tb-size) ** 0.5 + goback. +end program stddev. diff --git a/Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-2.cob b/Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-2.cob new file mode 100644 index 0000000000..b52f8d5aaf --- /dev/null +++ b/Task/Cumulative-standard-deviation/COBOL/cumulative-standard-deviation-2.cob @@ -0,0 +1,9 @@ +sample output: +inp=002 stddev=+00000.0000 +inp=004 stddev=+00001.0000 +inp=004 stddev=+00000.9427 +inp=004 stddev=+00000.8660 +inp=005 stddev=+00000.9797 +inp=005 stddev=+00001.0000 +inp=007 stddev=+00001.3996 +inp=009 stddev=+00002.0000 diff --git a/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-1.el b/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-1.el new file mode 100644 index 0000000000..a297cfb3d2 --- /dev/null +++ b/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-1.el @@ -0,0 +1,16 @@ +(defun running-std (items) + (let ((running-sum 0) + (running-len 0) + (running-squared-sum 0) + (result 0)) + (dolist (item items) + (setq running-sum (+ running-sum item)) + (setq running-len (1+ running-len)) + (setq running-squared-sum (+ running-squared-sum (* item item))) + (setq result (sqrt (- (/ running-squared-sum (float running-len)) + (/ (* running-sum running-sum) + (float (* running-len running-len)))))) + (message "%f" result)) + result)) + +(running-std '(2 4 4 4 5 5 7 9)) diff --git a/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-2.el b/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-2.el new file mode 100644 index 0000000000..0261a96d2c --- /dev/null +++ b/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-2.el @@ -0,0 +1,2 @@ +(let ((x '(2 4 4 4 5 5 7 9))) + (string-to-number (calc-eval "sqrt(vpvar($1))" nil (append '(vec) x)))) diff --git a/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-3.el b/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-3.el new file mode 100644 index 0000000000..5db8d9a4e9 --- /dev/null +++ b/Task/Cumulative-standard-deviation/Emacs-Lisp/cumulative-standard-deviation-3.el @@ -0,0 +1,24 @@ +;; lexical-binding: t +(require 'generator) + +(iter-defun std-dev-gen (lst) + (let ((sum 0) + (avg 0) + (tmp '()) + (std 0)) + (dolist (i lst) + (setq i (float i)) + (push i tmp) + (setq sum (+ sum i)) + (setq avg (/ sum (length tmp))) + (setq std 0) + (dolist (j tmp) + (setq std (+ std (expt (- j avg) 2)))) + (setq std (/ std (length tmp))) + (setq std (sqrt std)) + (iter-yield std)))) + +(let* ((test-data '(2 4 4 4 5 5 7 9)) + (generator (std-dev-gen test-data))) + (dolist (i test-data) + (message "with %d: %f" i (iter-next generator)))) diff --git a/Task/Cumulative-standard-deviation/Haxe/cumulative-standard-deviation.hx b/Task/Cumulative-standard-deviation/Haxe/cumulative-standard-deviation.hx new file mode 100644 index 0000000000..47fe74bf6f --- /dev/null +++ b/Task/Cumulative-standard-deviation/Haxe/cumulative-standard-deviation.hx @@ -0,0 +1,23 @@ +using Lambda; + +class Main { + static function main():Void { + var nums = [2, 4, 4, 4, 5, 5, 7, 9]; + for (i in 1...nums.length+1) + Sys.println(sdev(nums.slice(0, i))); + } + + static function average(nums:Array):Float { + return nums.fold(function(n, t) return n + t, 0) / nums.length; + } + + static function sdev(nums:Array):Float { + var store = []; + var avg = average(nums); + for (n in nums) { + store.push((n - avg) * (n - avg)); + } + + return Math.sqrt(average(store)); + } +} diff --git a/Task/Cumulative-standard-deviation/Loglan82/cumulative-standard-deviation.loglan82 b/Task/Cumulative-standard-deviation/Loglan82/cumulative-standard-deviation.loglan82 new file mode 100644 index 0000000000..e0783964c9 --- /dev/null +++ b/Task/Cumulative-standard-deviation/Loglan82/cumulative-standard-deviation.loglan82 @@ -0,0 +1,50 @@ +program CumulDev; +(* Cumulative standard deviation *) + + unit SAMPLE: class; + var + n: integer, + sum: real, + sum_of_squares: real; + + unit add: procedure (p: real); + begin + n := n + 1; + sum := sum + p; + sum_of_squares := sum_of_squares + p * p + end add; + + begin (* constructor *) + n := 0; + sum := 0.0; + sum_of_squares := 0.0 + end; + +var + test: arrayof real, + s: SAMPLE, + i: integer; + + unit deviation: function (s: SAMPLE): real; + var + quot: real; + begin + quot := s.sum / s.n; + result := sqrt(s.sum_of_squares / s.n - quot * quot) + end deviation; + +begin + array test dim (1 : 8); + test(1) := 2; test(2) := 4; test(3) := 4; test(4) := 4; + test(5) := 5; test(6) := 5; test(7) := 7; test(8) := 9; + s := new SAMPLE; + writeln("N ITEM AVG STDDEV"); + for i := 1 to upper(test) + do + call s.add(test(i)); + write(i: 1, " ", test(i): 3: 1, " "); + write(s.sum / i: 5: 3, " "); + writeln(deviation(s): 5: 3); + od; + kill(s); +end CumulDev. diff --git a/Task/Cumulative-standard-deviation/Modula-2/cumulative-standard-deviation.mod2 b/Task/Cumulative-standard-deviation/Modula-2/cumulative-standard-deviation.mod2 new file mode 100644 index 0000000000..688235369e --- /dev/null +++ b/Task/Cumulative-standard-deviation/Modula-2/cumulative-standard-deviation.mod2 @@ -0,0 +1,70 @@ +MODULE CumulDev; +(* Cumulative standard deviation *) +FROM RealMath IMPORT + sqrt; +FROM SRealIO IMPORT + WriteFixed; +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +TYPE + TSample = RECORD + N: CARDINAL; + Sum: REAL; + SumOfSquares: REAL + END; + + TData = ARRAY [1 .. 8] OF REAL; + +VAR + Test: TData; + S: TSample; + I: CARDINAL; + +PROCEDURE Init(VAR OUT S: TSample); +BEGIN + WITH S DO + N := 0; + Sum := 0.0; + SumOfSquares := 0.0 + END; +END Init; + +PROCEDURE Add(VAR INOUT S: TSample; P: REAL); +BEGIN + WITH S DO + N := N + 1; + Sum := Sum + P; + SumOfSquares := SumOfSquares + P * P + END +END Add; + +PROCEDURE Deviation (S: TSample): REAL; +VAR + Quot: REAL; +BEGIN + WITH S DO + Quot := Sum / FLOAT(N); + RETURN sqrt(SumOfSquares / FLOAT(N) - Quot * Quot) + END; +END Deviation; + +BEGIN + Test := TData{2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0}; + Init(S); + WriteString("N ITEM AVG STDDEV"); + WriteLn; + FOR I := 1 TO HIGH(Test) DO + Add(S, Test[I]); + WriteInt(I, 1); + WriteString(" "); + WriteFixed(Test[I], 1, 3); + WriteString(" "); + WriteFixed(S.Sum / FLOAT(I), 3, 5); + WriteString(" "); + WriteFixed(Deviation(S), 3, 5); + WriteLn + END; +END CumulDev. diff --git a/Task/Cumulative-standard-deviation/Oberon-07/cumulative-standard-deviation.oberon b/Task/Cumulative-standard-deviation/Oberon-07/cumulative-standard-deviation.oberon new file mode 100644 index 0000000000..f0f08e67bf --- /dev/null +++ b/Task/Cumulative-standard-deviation/Oberon-07/cumulative-standard-deviation.oberon @@ -0,0 +1,60 @@ +MODULE CumulativeStandardDeviation; + IMPORT Math, Out; + + TYPE CSD* = POINTER TO CSDStruct; + CSDStruct + = RECORD + sum, sum2, sd : REAL; + n : INTEGER + END; + + PROCEDURE sample*( sd : CSD ; x : REAL ) : REAL; + VAR r, sum, sum2 : REAL; + BEGIN + sum := sd.sum + x; + sum2 := sd.sum2 + ( x * x );; + INC( sd.n ); + r := FLT( sd.n ); + IF sd.n = 0 THEN + sd.sd := 0.0 + ELSE + sd.sd := Math.sqrt( sum2 / r - sum * sum / r / r ) + END; + sd.sum := sum; + sd.sum2 := sum2 + RETURN sd.sd + END sample; + + PROCEDURE NewCSD*() : CSD ; + VAR sd : CSD; + BEGIN + NEW( sd ); + sd.n := 0; + sd.sum := 0.0; + sd.sum2 := 0.0; + sd.sd := 0.0 + RETURN sd + END NewCSD ; + + PROCEDURE showSampleEffect( sd : CSD; x : REAL ); + VAR dev : REAL; + BEGIN + dev := sample( sd, x ); + Out.Int( sd.n, 6 );Out.String( ": " );Out.Real( x, 10 ); + Out.String( " -> " );Out.Real( dev, 10 );Out.Ln + END showSampleEffect; + + PROCEDURE test; + VAR sd : CSD; + BEGIN + sd := NewCSD(); + showSampleEffect( sd, 2.0 ); + showSampleEffect( sd, 4.0 );showSampleEffect( sd, 4.0 );showSampleEffect( sd, 4.0 ); + showSampleEffect( sd, 5.0 );showSampleEffect( sd, 5.0 ); + showSampleEffect( sd, 7.0 ); + showSampleEffect( sd, 9.0 ) + END test; + +BEGIN + test; +END CumulativeStandardDeviation. diff --git a/Task/Cumulative-standard-deviation/Oberon/cumulative-standard-deviation.oberon b/Task/Cumulative-standard-deviation/Oberon/cumulative-standard-deviation.oberon new file mode 100644 index 0000000000..6a7b40f001 --- /dev/null +++ b/Task/Cumulative-standard-deviation/Oberon/cumulative-standard-deviation.oberon @@ -0,0 +1,60 @@ +MODULE CumulativeStandardDeviation; + IMPORT Math, Out; + + TYPE CSD* = POINTER TO CSDStruct; + CSDStruct* + = RECORD + sum, sum2, sd : REAL; + n : INTEGER; + END; + + PROCEDURE ( sd : CSD ) sample*( x : REAL ) : REAL; + VAR r, sum, sum2 : REAL; + BEGIN + sum := sd.sum + x; + sum2 := sd.sum2 + ( x * x );; + INC( sd.n ); + r := sd.n; + IF sd.n = 0 THEN + sd.sd := 0.0 + ELSE + sd.sd := Math.sqrt( sum2 / r - sum * sum / r / r ) + END; + sd.sum := sum; + sd.sum2 := sum2; + RETURN sd.sd + END sample; + + PROCEDURE NewCSD*() : CSD ; + VAR sd : CSD; + BEGIN + NEW( sd ); + sd.n := 0; + sd.sum := 0.0; + sd.sum2 := 0.0; + sd.sd := 0.0; + RETURN sd + END NewCSD ; + + PROCEDURE ( sd : CSD ) showSampleEffect( x : REAL ); + VAR dev : REAL; + BEGIN + dev := sd.sample( x ); + Out.Int( sd.n, 6 );Out.String( ": " );Out.Real( x, 15 ); + Out.String( " -> " );Out.Real( dev, 15 );Out.Ln + END showSampleEffect; + + PROCEDURE test; + VAR sd : CSD; + BEGIN + sd := NewCSD(); + sd.showSampleEffect( 2.0 ); + sd.showSampleEffect( 4.0 ); sd.showSampleEffect( 4.0 ); sd.showSampleEffect( 4.0 ); + sd.showSampleEffect( 5.0 ); sd.showSampleEffect( 5.0 ); + sd.showSampleEffect( 7.0 ); + sd.showSampleEffect( 9.0 ) + END test; + +BEGIN + test; +END CumulativeStandardDeviation. diff --git a/Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation-1.phix b/Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation-1.phix new file mode 100644 index 0000000000..a0b187fd32 --- /dev/null +++ b/Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation-1.phix @@ -0,0 +1,26 @@ +with javascript_semantics + +atom sdn = 0, sdsum = 0, sdsumsq = 0 + +procedure sdadd(atom n) + sdn += 1 + sdsum += n + sdsumsq += n*n +end procedure + +function sdavg() + return sdsum/sdn +end function + +function sddev() + return sqrt(sdsumsq/sdn - power(sdsum/sdn,2)) +end function + +--test code: +constant testset = {2, 4, 4, 4, 5, 5, 7, 9} +integer ti +for i=1 to length(testset) do + ti = testset[i] + sdadd(ti) + printf(1,"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n",{i,ti,sdavg(),sddev()}) +end for diff --git a/Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation-2.phix b/Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation-2.phix new file mode 100644 index 0000000000..50c98f30ba --- /dev/null +++ b/Task/Cumulative-standard-deviation/Phix/cumulative-standard-deviation-2.phix @@ -0,0 +1,6 @@ +with javascript_semantics +constant testset = {2, 4, 4, 4, 5, 5, 7, 9} +for i,t in testset do + sequence test = testset[1..i] + printf(1,"N=%d Item=%d Avg=%5.3f StdDev=%5.3f\n",{i,t,average(test),std_dev(test)}) +end for diff --git a/Task/Cumulative-standard-deviation/Pluto/cumulative-standard-deviation.pluto b/Task/Cumulative-standard-deviation/Pluto/cumulative-standard-deviation.pluto new file mode 100644 index 0000000000..cb996e5c98 --- /dev/null +++ b/Task/Cumulative-standard-deviation/Pluto/cumulative-standard-deviation.pluto @@ -0,0 +1,18 @@ +require "table2" +local fmt = require "fmt" + +local function cum_std_dev(a) + for i = 1, #a do + local b = a:slice(1, i) + fmt.print("Values : %,s", b) + coroutine.yield(b:stddev()) + end +end + +local a = {2, 4, 4, 4, 5, 5, 7, 9} +local co = coroutine.create(cum_std_dev) +while true do + local _, sd = coroutine.resume(co, a) + if !sd then break end + fmt.print("Std Dev : %10.8f\n", sd) +end diff --git a/Task/Cumulative-standard-deviation/PowerShell/cumulative-standard-deviation.ps1 b/Task/Cumulative-standard-deviation/PowerShell/cumulative-standard-deviation.ps1 new file mode 100644 index 0000000000..b95d6fffc2 --- /dev/null +++ b/Task/Cumulative-standard-deviation/PowerShell/cumulative-standard-deviation.ps1 @@ -0,0 +1,13 @@ +function Get-StandardDeviation { + begin { + $avg = 0 + $nums = @() + } + process { + $nums += $_ + $avg = ($nums | Measure-Object -Average).Average + $sum = 0; + $nums | ForEach-Object { $sum += ($avg - $_) * ($avg - $_) } + [Math]::Sqrt($sum / $nums.Length) + } +} diff --git a/Task/Cumulative-standard-deviation/QuickBASIC/cumulative-standard-deviation.basic b/Task/Cumulative-standard-deviation/QuickBASIC/cumulative-standard-deviation.basic new file mode 100644 index 0000000000..8ddbd59b8a --- /dev/null +++ b/Task/Cumulative-standard-deviation/QuickBASIC/cumulative-standard-deviation.basic @@ -0,0 +1,43 @@ +' Cumulative standard deviation + +TYPE Sample + N AS INTEGER + Sum AS SINGLE + SumOfSquares AS SINGLE +END TYPE + +DECLARE SUB Init (S AS Sample) +DECLARE SUB Add (S AS Sample, BYVAL P AS SINGLE) +DECLARE FUNCTION Deviation! (S AS Sample) +DIM Test(1 TO 8) AS SINGLE +DIM S AS Sample +FOR I = 1 TO 8 + READ Test(I) +NEXT I +DATA 2, 4, 4, 4, 5, 5, 7, 9 +CALL Init(S) +PRINT "N ITEM AVG STDDEV" +FOR I = LBOUND(Test) TO UBOUND(Test) + CALL Add(S, Test(I)) + PRINT USING "# "; I; + PRINT USING " # "; Test(I); + PRINT USING "#.### "; S.Sum / I; + PRINT USING " #.###"; Deviation!(S) +NEXT I +END + +SUB Add (S AS Sample, BYVAL P AS SINGLE) + S.N = S.N + 1 + S.Sum = S.Sum + P + S.SumOfSquares = S.SumOfSquares + P ^ 2 +END SUB + +FUNCTION Deviation! (S AS Sample) + Deviation! = SQR(S.SumOfSquares / S.N - (S.Sum / S.N) ^ 2) +END FUNCTION + +SUB Init (S AS Sample) + S.N = 0 + S.Sum = 0! + S.SumOfSquares = 0! +END SUB diff --git a/Task/Cumulative-standard-deviation/VBScript/cumulative-standard-deviation.vbs b/Task/Cumulative-standard-deviation/VBScript/cumulative-standard-deviation.vbs new file mode 100644 index 0000000000..237a6d559a --- /dev/null +++ b/Task/Cumulative-standard-deviation/VBScript/cumulative-standard-deviation.vbs @@ -0,0 +1,21 @@ +data = Array(2,4,4,4,5,5,7,9) + +For i = 0 To UBound(data) + WScript.StdOut.Write "value = " & data(i) &_ + " running sd = " & sd(data,i) + WScript.StdOut.WriteLine +Next + +Function sd(arr,n) + mean = 0 + variance = 0 + For j = 0 To n + mean = mean + arr(j) + Next + mean = mean/(n+1) + For k = 0 To n + variance = variance + ((arr(k)-mean)^2) + Next + variance = variance/(n+1) + sd = FormatNumber(Sqr(variance),6) +End Function diff --git a/Task/Currency/Ada/currency.adb b/Task/Currency/Ada/currency.adb new file mode 100644 index 0000000000..45be1ba862 --- /dev/null +++ b/Task/Currency/Ada/currency.adb @@ -0,0 +1,26 @@ +with Ada.Text_IO; + +procedure Currency is + type Dollar is delta 0.01 range 0.0 .. 24_000_000_000_000_000.0; + package Dollar_IO is new Ada.Text_IO.Fixed_IO(Dollar); + + hamburger_cost : constant := 5.50; + milkshake_cost : constant := 2.86; + tax_rate : constant := 0.0765; + + total_cost : constant := hamburger_cost * 4_000_000_000_000_000.0 + milkshake_cost * 2; + total_tax : constant := total_cost * tax_rate; + total_with_tax : constant := total_cost + total_tax; +begin + Ada.Text_IO.Put("Price before tax:"); + Dollar_IO.Put(total_cost); + Ada.Text_IO.New_Line; + + Ada.Text_IO.Put("Tax: "); + Dollar_IO.Put(total_tax); + Ada.Text_IO.New_Line; + + Ada.Text_IO.Put("Total: "); + Dollar_IO.Put(total_with_tax); + Ada.Text_IO.New_Line; +end Currency; diff --git a/Task/Currency/COBOL/currency.cob b/Task/Currency/COBOL/currency.cob new file mode 100644 index 0000000000..d55da3fefc --- /dev/null +++ b/Task/Currency/COBOL/currency.cob @@ -0,0 +1,28 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. currency-example. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 Burger-Price CONSTANT 5.50. +01 Milkshake-Price CONSTANT 2.86. +01 num-burgers PIC 9(18) VALUE 4000000000000000. +01 num-milkshakes PIC 9(18) VALUE 2. +01 tax PIC 9(18)V99. +01 tax-edited PIC $(17)9.99. +01 Tax-Rate CONSTANT 7.65. +01 total PIC 9(18)V99. +01 total-edited PIC $(17)9.99. + +PROCEDURE DIVISION. + COMPUTE total rounded, total-edited rounded = + num-burgers * Burger-Price + num-milkshakes * Milkshake-Price + DISPLAY "Total before tax: " total-edited + + COMPUTE tax rounded, tax-edited rounded = total * (Tax-Rate / 100) + DISPLAY " Tax: " tax-edited + + ADD tax TO total GIVING total-edited rounded + DISPLAY " Total with tax: " total-edited + . +END PROGRAM currency-example. diff --git a/Task/Currency/Crystal/currency.cr b/Task/Currency/Crystal/currency.cr new file mode 100644 index 0000000000..aae2438c2c --- /dev/null +++ b/Task/Currency/Crystal/currency.cr @@ -0,0 +1,28 @@ +require "big" + +def f (n, d=2); n.format(decimal_places: d) end + +check = <<-EOC.lines.map(&.split).map {|(desc, price, qty)| { desc, price.to_big_d, qty.to_big_d } } + Hamburger 5.50 4000000000000000 + Milkshake 2.86 2 + EOC + +tax_rate = 0.0765 + +fmt = "%-10s %8s %23s %27s\n" + +printf fmt, %w(Item Price Quantity Amount) + +subtotal = check.sum {|item, price, quant| + amount = price * quant + printf fmt, item, f(price), f(quant, 0), f(amount.round(2)) + amount +} +printf fmt, "", "", "", "-------------------------" +printf fmt, "", "", "Subtotal ", f(subtotal) + +tax = (subtotal * tax_rate).round(2) +printf fmt, "", "", "Tax ", f(tax) + +total = subtotal + tax +printf fmt, "", "", "Total ", f(total) diff --git a/Task/Currency/Fortran/currency.f b/Task/Currency/Fortran/currency.f new file mode 100644 index 0000000000..c86c4fff8d --- /dev/null +++ b/Task/Currency/Fortran/currency.f @@ -0,0 +1,86 @@ +! +program Currency +implicit none + +! Store all money amounts in units of 1/10 Cent. (Cents only can result in rounding errors in Tax) +! Store Tax rate in PPM not in % for controlled, sufficient precision in integer calculation +! +! Use integer(kind=16) for internal represenation. This can carry up to 38 digits which +! gives a pretty amount of money, enough for most purposes. +! To display an amount V of money in terms of real xxx.yy $ rounded to nearest full cent, +! divide the V by moneyFactor to give the full Dollars, and +! calculate Cents as nearest Integer nint ( mod (V,moneyFactor) / CentFactor) +! Similarly, we represent Tax percentage in units of ppm, again using Integerr(kind=16) +! To obtain the Tax, multiply value V with TaxPPM, then divide by PPMFactor + +! Define constants here to avoid magic numbers within code +integer, parameter :: int_kind = 16 ! Will not work with smaller int_kind +integer, parameter :: float_kind = 8 + +integer, parameter :: moneyFactor = 1000 +real(kind=float_kind) :: CentFactor = 10.0 +integer (kind=int_kind), parameter :: PPMFactor = 1000000 ! 1 ppm = 1/1000000 +integer (kind=int_kind), parameter :: percentToPPM = 10000 ! 1 % = 10000 ppm + +integer (kind=int_kind) :: N_Hamburgers +integer (kind=int_kind) :: N_Milkshake +integer (kind=int_kind) :: Price_Hamburger +integer (kind=int_kind) :: Price_Milkshake +integer (kind=int_kind) :: Tax_Rate_PPM +integer (kind=int_kind) :: Price_AllHamburgers, Price_AllMilkshakes, PriceBeforeTax, Tax, TotalWithTax + +! Amounts, Prices and Tax Rate as in Task description +N_Hamburgers = 4000000000000000_int_kind ! pure number +N_Milkshake = 2 ! pure number +Price_Hamburger = nint (5.50 * MoneyFactor) ! $ 5.50 in 1/10 cent, see above +Price_Milkshake = nint(2.86*MoneyFactor) ! $2.86 in 1/10 cent +Tax_rate_PPM = nint (7.65*percentToPPM) ! 7.65% converted to ppm + +! Very elementary math, additions and multiplication by integer values are exact unless overflow ocurs +Price_AllHamburgers = N_Hamburgers * Price_Hamburger +Price_AllMilkshakes = N_Milkshake * Price_Milkshake +PriceBeforeTax = Price_AllHamburgers + Price_AllMilkshakes + +! Multiplication by (percentage value * percentToPPM (=10000)) +! and subsequent division by PPMFactor (=1000000) cuts off +! less than 0.1 cents from the exact result +! +Tax = (Tax_rate_PPM * PriceBeforeTax) / PPMFactor + +! Addition is exact again. +TotalWithTax = PriceBeforeTax + Tax + +! Display the results rounded to closest Dollar amount values +! with 2 decimal digits +! +! Spacing selected to display the expected result. +! More general solution for pretty-print required. +! +call printAsDollars ('Hamburgers : $ ', Price_AllHamburgers) +call printAsDollars ('Milk Shakes : $ ', Price_AllMilkshakes) +call printAsDollars ('Total Price Before Tax: $ ', PriceBeforeTax) +call printAsDollars ('Tax : $ ', Tax) +call printAsDollars ('Total : $ ', TotalWithTax) + +contains + + + subroutine printAsDollars (text, amount) + + character (len=*), intent(in) :: text + integer (kind = int_kind) :: amount + + integer (kind = int_kind) :: fullDollars, Cents + + fullDollars = amount / moneyFactor + Cents = nint (mod (amount, moneyFactor)/CentFactor) + ! rounding with nint() might result in exactly 100 cents, which is 1 Dollar. + if (Cents .eq. 100) then + fullDollars = fullDollars + 1 + Cents = 0 + endif + write (6,'(A, i0,".",i2.2)') text, fullDollars, Cents + end subroutine printAsDollars + + +end program Currency diff --git a/Task/Currency/Langur/currency.langur b/Task/Currency/Langur/currency.langur new file mode 100644 index 0000000000..d42b71c231 --- /dev/null +++ b/Task/Currency/Langur/currency.langur @@ -0,0 +1,19 @@ +# use banker's rounding +mode rounding = _round'halfeven + +val hamburgers = 4000000000000000 +val milkshakes = 2 + +val price_hb = 5.50 +val price_ms = 2.86 +val taxrate = 7.65 + +val pretax = hamburgers * price_hb + + milkshakes * price_ms + +val tax = round(pretax * taxrate / 100, places=2) +val total = pretax + tax + +writeln "before tax: $", pretax +writeln " tax: $", tax +writeln " total: $", total diff --git a/Task/Currency/Pluto/currency.pluto b/Task/Currency/Pluto/currency.pluto new file mode 100644 index 0000000000..660fbc7649 --- /dev/null +++ b/Task/Currency/Pluto/currency.pluto @@ -0,0 +1,15 @@ +require "bignum" +local fmt = require "fmt" + +local hamburgers = bigdec.of("4000000000000000") +local milkshakes = bigdec.of(2) +local price1 = bigdec.of(5.5) +local price2 = bigdec.of(2.86) +local tax_pc = bigdec.of(0.0765) +local total_pre_tax = hamburgers * price1 + milkshakes * price2 +local total_tax = tax_pc * total_pre_tax +local total_after_tax = total_pre_tax + total_tax + +fmt.print("Total price before tax : %20s", total_pre_tax:tostring(2)) +fmt.print("Tax : %20s", total_tax:tostring(2)) +fmt.print("Total price after tax : %20s", total_after_tax:tostring(2)) diff --git a/Task/Currency/Rebol/currency.rebol b/Task/Currency/Rebol/currency.rebol new file mode 100644 index 0000000000..1231a914f8 --- /dev/null +++ b/Task/Currency/Rebol/currency.rebol @@ -0,0 +1,20 @@ +Rebol [ + title: "Rosetta code: Currency" + file: %Currency.r3 + url: https://rosettacode.org/wiki/Currency + needs: 3.0.0 +] + +hamburgers: 4'000'000'000'000'000 +hamburger-price: $5.50 +milkshakes: 2 +milkshake-price: $2.86 +tax-rate: 7.65% + +total-price: (hamburgers * hamburger-price) + (milkshakes * milkshake-price) +tax: total-price * tax-rate +total: total-price + tax + +print ["Total price before tax :" round/to total-price $0.01] +print ["Tax :" round/to tax $0.01] +print ["Total price after tax :" round/to total $0.01] diff --git a/Task/Currying/Ada/currying-1.adb b/Task/Currying/Ada/currying-1.adb new file mode 100644 index 0000000000..77dab5ad74 --- /dev/null +++ b/Task/Currying/Ada/currying-1.adb @@ -0,0 +1,30 @@ +generic + type Argument_1 (<>) is limited private; + type Argument_2 (<>) is limited private; + type Argument_3 (<>) is limited private; + type Return_Value (<>) is limited private; + + with function Func + (A : in Argument_1; + B : in Argument_2; + C : in Argument_3) + return Return_Value; +package Curry_3 is + + generic + First : in Argument_1; + package Apply_1 is + + generic + Second : in Argument_2; + package Apply_2 is + + function Apply_3 + (Third : in Argument_3) + return Return_Value; + + end Apply_2; + + end Apply_1; + +end Curry_3; diff --git a/Task/Currying/Ada/currying-2.adb b/Task/Currying/Ada/currying-2.adb new file mode 100644 index 0000000000..92d7cfc1aa --- /dev/null +++ b/Task/Currying/Ada/currying-2.adb @@ -0,0 +1,18 @@ +package body Curry_3 is + + package body Apply_1 is + + package body Apply_2 is + + function Apply_3 + (Third : in Argument_3) + return Return_Value is + begin + return Func (First, Second, Third); + end Apply_3; + + end Apply_2; + + end Apply_1; + +end Curry_3; diff --git a/Task/Currying/Ada/currying-3.adb b/Task/Currying/Ada/currying-3.adb new file mode 100644 index 0000000000..c412e7a918 --- /dev/null +++ b/Task/Currying/Ada/currying-3.adb @@ -0,0 +1,27 @@ +with Curry_3, Ada.Text_IO; + +procedure Curry_Test is + + function Sum + (X, Y, Z : in Integer) + return Integer is + begin + return X + Y + Z; + end Sum; + + package Curried is new Curry_3 + (Argument_1 => Integer, + Argument_2 => Integer, + Argument_3 => Integer, + Return_Value => Integer, + Func => Sum); + + package Sum_5 is new Curried.Apply_1 (5); + package Sum_5_7 is new Sum_5.Apply_2 (7); + Result : Integer := Sum_5_7.Apply_3 (3); + +begin + + Ada.Text_IO.Put_Line ("Five plus seven plus three is" & Integer'Image (Result)); + +end Curry_Test; diff --git a/Task/Currying/PowerShell/currying-1.ps1 b/Task/Currying/PowerShell/currying-1.ps1 new file mode 100644 index 0000000000..4c9d645de5 --- /dev/null +++ b/Task/Currying/PowerShell/currying-1.ps1 @@ -0,0 +1 @@ +function Add($x) { return { param($y) return $y + $x }.GetNewClosure() } diff --git a/Task/Currying/PowerShell/currying-2.ps1 b/Task/Currying/PowerShell/currying-2.ps1 new file mode 100644 index 0000000000..dbe310f289 --- /dev/null +++ b/Task/Currying/PowerShell/currying-2.ps1 @@ -0,0 +1 @@ +& (Add 1) 2 diff --git a/Task/Currying/PowerShell/currying-3.ps1 b/Task/Currying/PowerShell/currying-3.ps1 new file mode 100644 index 0000000000..1768c3d21d --- /dev/null +++ b/Task/Currying/PowerShell/currying-3.ps1 @@ -0,0 +1 @@ +(4,9,16,25 | ForEach-Object { & (add $_) ([Math]::Sqrt($_)) }) -join ", " diff --git a/Task/Currying/Rebol/currying.rebol b/Task/Currying/Rebol/currying.rebol new file mode 100644 index 0000000000..5c62106262 --- /dev/null +++ b/Task/Currying/Rebol/currying.rebol @@ -0,0 +1,19 @@ +;; Based on the Red language solution bellow. +make-curry: func[ + "Define a custome simple currying function" + 'fn [word!] + x +][ + do compose/deep [ + func [ + (reform ["currying function:" form fn x "y"]) + y + ][ do compose [(get fn) (x) y]] + ] +] +add2: make-curry add 2 +add3: make-curry add 3 +print add2 7 +print add3 7 +print "^/Help output:" +help add3 diff --git a/Task/Curzon-numbers/Ada/curzon-numbers.adb b/Task/Curzon-numbers/Ada/curzon-numbers.adb new file mode 100644 index 0000000000..31133f80d5 --- /dev/null +++ b/Task/Curzon-numbers/Ada/curzon-numbers.adb @@ -0,0 +1,57 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Long_Long_Integer_Text_IO; use Ada.Long_Long_Integer_Text_IO; + +procedure Curzon is + + function Mod_Pow(Base, Exp, Modulo : Long_Long_Integer) return Long_Long_Integer is + Result : Long_Long_Integer := 1; + B : Long_Long_Integer := Base mod Modulo; + E : Long_Long_Integer := Exp; + begin + if Modulo = 1 then return 0; end if; + + while E > 0 loop + if (E mod 2) = 1 then + Result := (Result * B) mod Modulo; + end if; + B := (B * B) mod Modulo; + E := E / 2; + end loop; + + return Result; + end Mod_Pow; + + function Curzon_Check(K, N : Long_Long_Integer) return Boolean is + R : Long_Long_Integer := K * N; + begin + return Mod_Pow(K, N, R + 1) = R; + end Curzon_Check; + + N : Long_Long_Integer; + Count : Integer; + +begin + for K in Long_Long_Integer range 2..10 when K mod 2 = 0 loop + Put("The first 50 Curzon numbers of base "); Put(K, 1); Put(":"); New_Line; + N := 1; + Count := 1; + while Count <= 1000 loop + if Curzon_Check(K, N) then + if Count <= 50 then + Put(N, 4); + if Count mod 10 = 0 then + New_Line; + else + Put(" "); + end if; + end if; + if Count = 1000 then + Put("The 1000th Curzon number of base "); Put(K, 1); Put(": "); Put(N, 5); + New_Line(2); + end if; + Count := @ + 1; + end if; + N := @ + 1; + end loop; + end loop; +end Curzon; diff --git a/Task/Curzon-numbers/Fortran/curzon-numbers.f b/Task/Curzon-numbers/Fortran/curzon-numbers.f new file mode 100644 index 0000000000..7f03146a4a --- /dev/null +++ b/Task/Curzon-numbers/Fortran/curzon-numbers.f @@ -0,0 +1,72 @@ +! +! Curzon Numbers +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! U.B., September 2025 +! +program Curzon + + implicit none + + integer, parameter :: kint = 8 ! 8-byte-integers are big enough, 4 bytes is insufficient. + + integer (kind=kint) :: base, num, count + + do base=2,10,2 + print ("( 'Curzon numbers with base ', i2,':')"), base + count = 0 + num = 1 + do while (count .lt. 50) + if (isCurzon (num, base)) then + count = count + 1 + write (*, '(i5)', advance='no') num + if (mod (count, 10) .eq. 0 ) write (*,*) ! EOL + end if + num = num + 1 + end do + do + if (isCurzon (num,base)) then + count = count + 1 + if (count .eq. 1000) exit + endif + num = num + 1 + end do + print ("('1000th Curzon number with base ', i0, ': ', i0/)") , base, num + + end do + + contains + + + function isCurzon (n, k) result (YN) + + integer(kind=kint), intent(in) :: n,k + integer(kind=kint) :: m, p + logical :: YN + + m = k*n+1 + p = ModularExp (k,n,m) + 1 + YN = m .eq. p + + end function isCurzon + + function ModularExp(a, b, n) result(d) + + integer(kind=kint) , intent(in) :: a,b,n + integer (kind=kint) :: d + integer (kind=kint) :: i, k + d = 1 + k = 0 + do while (ishft (b, -k) .gt. 0) + k = k + 1 + end do + do i = k - 1, 0, -1 + d = mod (d*d, n) + if (iand (ishft (b, -i) , 1_kint) .gt. 0) d = mod (d*a ,n); + end do + + end function ModularExp + +end program Curzon diff --git a/Task/Curzon-numbers/Icon/curzon-numbers.icon b/Task/Curzon-numbers/Icon/curzon-numbers.icon new file mode 100644 index 0000000000..6b7af7dfe8 --- /dev/null +++ b/Task/Curzon-numbers/Icon/curzon-numbers.icon @@ -0,0 +1,18 @@ +procedure main(A) + limit := \A[1] | 50 + every b := 2 to 10 by 2 do { + writes("Base integer ",b,":") + every (cnt := 0, n := curzon(b)\1000, cnt +:= 1) do + if cnt <= 50 then writes(" ",n) + write("\n\t1000th Curzon number is ",n) + write("\n") + } +end + +procedure curzon(b) + every n := seq() do { + x := b^n+1 + y := b*n+1 + suspend ((x/y)*y = x, n) + } +end diff --git a/Task/Curzon-numbers/JavaScript/curzon-numbers.js b/Task/Curzon-numbers/JavaScript/curzon-numbers.js new file mode 100644 index 0000000000..d267fa088f --- /dev/null +++ b/Task/Curzon-numbers/JavaScript/curzon-numbers.js @@ -0,0 +1,68 @@ +/** + * Curzon Numbers + * + * A generalized Curzon number is a positive integer n such that: + * k^n + 1 is divisible by (k * n + 1) + * For k = 2, this gives the classic definition of Curzon numbers + */ + +function isGeneralisedCurzonNumber(aK, aN) { + const r = aK * aN; + return modulusPower(aK, aN, r + 1) === r; +} + +function modulusPower(aBase, aExponent, aModulus) { + if (aModulus === 1) { + return 0; + } + + aBase %= aModulus; + let result = 1; + while (aExponent > 0) { + if ((aExponent & 1) === 1) { + result = (result * aBase) % aModulus; + } + aBase = (aBase * aBase) % aModulus; + aExponent >>= 1; + } + return result; +} + +function main() { + for (let k = 2; k <= 10; k += 2) { + console.log(`Generalised Curzon numbers with base ${k}:`); + + let n = 1; + let count = 0; + const results = []; + + // Find the first 50 Curzon numbers + while (count < 50) { + if (isGeneralisedCurzonNumber(k, n)) { + results.push(n); + count++; + } + n++; + } + + // Print in rows of 10 + for (let i = 0; i < results.length; i++) { + const lineEnd = (i + 1) % 10 === 0 ? '\n' : ' '; + process.stdout.write(`${results[i].toString().padStart(4)}${lineEnd}`); + } + + // Reset and find the 1000th Curzon number + count = 0; + while (count < 1000) { + if (isGeneralisedCurzonNumber(k, n)) { + count++; + } + n++; + } + + console.log(`1,000th Generalised Curzon number with base ${k}: ${n - 1}`); + console.log(); + } +} + +main(); diff --git a/Task/Curzon-numbers/Pluto/curzon-numbers.pluto b/Task/Curzon-numbers/Pluto/curzon-numbers.pluto new file mode 100644 index 0000000000..4f3877ba38 --- /dev/null +++ b/Task/Curzon-numbers/Pluto/curzon-numbers.pluto @@ -0,0 +1,27 @@ +local int = require "int" +local fmt = require "fmt" + +local function is_curzon(n, k) + local r = k * n + return int.modpow(k, n, r+1) == r +end + +for k = 2, 10, 2 do + print($"The first 50 Curzon numbers with base {k}:") + local n = 1 + local count = 0 + while count < 50 do + if is_curzon(n, k) then + fmt.write("%4d ", n) + count += 1 + if count % 10 == 0 then print() end + end + n += 1 + end + while true do + if is_curzon(n, k) then count += 1 end + if count == 1000 then break end + n += 1 + end + fmt.print("\nOne thousandth: %s\n", fmt.int(n)) +end diff --git a/Task/Cut-a-rectangle/Pluto/cut-a-rectangle.pluto b/Task/Cut-a-rectangle/Pluto/cut-a-rectangle.pluto new file mode 100644 index 0000000000..cbb8e6370a --- /dev/null +++ b/Task/Cut-a-rectangle/Pluto/cut-a-rectangle.pluto @@ -0,0 +1,68 @@ +require "table2" +local fmt = require "fmt" + +local count = {0} +local dir = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}} + +local function walk(y, x, h, w, grid, len, nxt) + if y == 0 or y == h or x == 0 or x == w then + count[1] += 2 + return + end + local t = y * (w + 1) + x + grid[t + 1] += 1 + grid[len - t + 1] += 1 + for i = 1, 4 do + if grid[t + nxt[i] + 1] == 0 then + walk(y + dir[i][1], x + dir[i][2], h, w, grid, len, nxt) + end + end + grid[t + 1] -= 1 + grid[len - t + 1] -= 1 +end + +local function cutrectangle(hh, ww, recur) + local h, w + if hh % 2 != 0 then + h, w = ww, hh + else + h, w = hh, ww + end + if h % 2 != 0 then + return 0 + elseif w == 1 then + return 1 + elseif w == 2 then + return h + elseif h == 2 then + return w + end + local cy = h // 2 + local cx = w // 2 + local len = (h + 1) * (w + 1) + local grid = table.rep(len, 0) + len -= 1 + local nxt = {-1, -w - 1, 1, w + 1} + if recur then count[1] = 0 end + for x = cx + 1, w - 1 do + local t = cy * (w + 1) + x + grid[t + 1] = 1 + grid[len - t + 1] = 1 + walk(cy - 1, x, h, w, grid, len, nxt) + end + count[1] += 1 + if h == w then + count[1] *= 2 + elseif w % 2 == 0 and recur then + cutrectangle(w, h, false) + end + return count[1] +end + +for y = 1, 10 do + for x = 1, y do + if x % 2 == 0 or y % 2 == 0 then + fmt.print($"%2d x %2d: %d", y, x, cutrectangle(y, x, true)) + end + end +end diff --git a/Task/Cut-a-rectangle/Uiua/cut-a-rectangle.uiua b/Task/Cut-a-rectangle/Uiua/cut-a-rectangle.uiua new file mode 100644 index 0000000000..8244367fdb --- /dev/null +++ b/Task/Cut-a-rectangle/Uiua/cut-a-rectangle.uiua @@ -0,0 +1,6 @@ +Set ← ⍜⊡⋅2++¯1ׯ1⊙⊸△ ⟜⍜⊡⋅1 +HasSpace ← >0/+♭⌕0 +N₄ ← [1_0 0_1 ¯1_0 0_¯1] +Nexts ← ◴≡⌟Set▽=0◡⬚¯1⊡♭₂⊞+N₄⊚⊸⌕1 +Cuts ← ◴≡⊣path(□◴/◇⊂≡(□Nexts)°□|¬HasSpace°□) □[Set 0_0] ↯⊙0 +≡(&s&p⊸⧻°□⊢Cuts) [2_3 3_4 4_5] diff --git a/Task/Cyclops-numbers/Fortran/cyclops-numbers.f b/Task/Cyclops-numbers/Fortran/cyclops-numbers.f new file mode 100644 index 0000000000..161c8af7aa --- /dev/null +++ b/Task/Cyclops-numbers/Fortran/cyclops-numbers.f @@ -0,0 +1,615 @@ +! +! Cyclops Numbers +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! Original Pascal code converted to Fortran +! U.B., October 2025 +!============================================================================== + +module CyclopsNumbers + implicit none + +! Constants + integer, parameter :: BIGLIMIT = 10000000 ! Upper limit for number search + integer, parameter :: MAX_DIGITS = 10 ! Maximum digits in base-9 representation + + ! Type for numbers in base-9 representation + type Num9 + integer :: nmdgts(0:MAX_DIGITS) ! Digits in base-9 (0-8) + integer :: nmMaxDgtIdx ! Highest digit index used + integer(kind=8) :: nmNum ! Actual numerical value + end type Num9 + + ! Type for cyclops numbers (left + zero + right parts) + type CyclopsNum + type(Num9) :: cnRight, cnLeft ! Right and left parts around zero + integer(kind=8) :: cnNum ! Complete cyclops number + integer :: cndigits ! Number of digits in each side + integer :: cnIdx ! Index of cyclops number + end type CyclopsNum + + ! Global arrays for precomputed values + integer(kind=8) :: cnMin(0:15) ! Minimum values for digit counts + integer(kind=8) :: cnPow10Shift(0:15) ! Powers of 10 for shifting + integer(kind=8) :: cnPow9(0:15) ! Powers of 9 for indexing + + ! Dynamic array to store found cyclops numbers + integer(kind=8), allocatable :: Cyclops(:) + +contains + + !============================================================================ + ! Initialize precomputed arrays for minimum values and powers + ! cnMin: (0, 1, 11, 111, 1111, ...) - minimum values for n-digit numbers + ! cnPow10Shift: (100, 1000, 10000, ...) - powers of 10 for position shifting + ! cnPow9: (1, 9, 81, 729, ...) - powers of 9 for base conversion + !============================================================================ + subroutine InitCnMinPow() + integer :: i + integer(kind=8) :: min_val, pow, pow9 + + min_val = 0 + pow = 100 + pow9 = 1 + + do i = 0, 15 + cnMin(i) = min_val + min_val = 10 * min_val + 1 ! Build numbers like 1, 11, 111, ... + cnPow10Shift(i) = pow + pow = pow * 10 ! Next power of 10 + cnPow9(i) = pow9 + pow9 = pow9 * 9 ! Next power of 9 + end do + end subroutine InitCnMinPow + + !============================================================================ + ! Reset a Num9 type to minimum value for given digit count + ! @param tn: Num9 object to clear + ! @param idx: Digit count index + !============================================================================ + subroutine ClearNum9 (tn, idx) + type(Num9), intent(out) :: tn + integer, intent(in) :: idx + integer :: i + + tn%nmdgts = 0 ! Clear all digits + tn%nmMaxDgtIdx = 0 ! Reset max digit index + tn%nmNum = cnMin(idx + 1) ! Set to minimum value + end subroutine ClearNum9 + + !============================================================================ + ! Initialize a cyclops number to starting state + ! @param cn: CyclopsNum object to initialize + !============================================================================ + subroutine InitCycNum(cn) + type(CyclopsNum), intent(out) :: cn + + cn%cndigits = 0 ! Start with 0 digits each side + call ClearNum9(cn%cnLeft, 0) ! Clear left part + call ClearNum9(cn%cnRight, 0) ! Clear right part + cn%cnNum = 0 ! Zero value + cn%cnIdx = 0 ! Start index + end subroutine InitCycNum + + !============================================================================ + ! Increment a base-9 number, handling carry-over + ! @param tn: Num9 object to increment + !============================================================================ + subroutine IncNum9(tn) + type(Num9), intent(inout) :: tn + integer :: idx, fac, n, i + + idx = 0 + fac = 1 + n = tn%nmdgts(0) + 1 ! Increment least significant digit + tn%nmNum = tn%nmNum + 1 ! Increment numerical value + + ! Handle carry-over propagation + do + if (n < 9) exit ! No carry-over needed + + ! Carry-over occurs + tn%nmNum = tn%nmNum + fac ! Adjust numerical value + tn%nmdgts(idx) = 0 ! Reset current digit + idx = idx + 1 ! Move to next digit + fac = fac * 10 ! Increase factor for numerical adjustment + + if (idx > MAX_DIGITS) exit ! Check bounds + n = tn%nmdgts(idx) + 1 ! Get next digit + 1 + end do + + ! Store final digit value + if (idx <= MAX_DIGITS) then + tn%nmdgts(idx) = n + if (tn%nmMaxDgtIdx < idx) then + tn%nmMaxDgtIdx = idx ! Update max digit index if needed + end if + end if + end subroutine IncNum9 + + !============================================================================ + ! Generate the next cyclops number in sequence + ! @param cycnum: Current cyclops number to advance + !============================================================================ + subroutine NextCycNum(cycnum) + type(CyclopsNum), intent(inout) :: cycnum + + if (cycnum%cnIdx /= 0) then + ! Normal case: increment from previous number + call IncNum9(cycnum%cnRight) ! Increment right part + + ! Check if right part overflowed (needs more digits) + if (cycnum%cnRight%nmMaxDgtIdx > cycnum%cndigits) then + call ClearNum9(cycnum%cnRight, cycnum%cndigits) ! Reset right to minimum + call IncNum9(cycnum%cnLeft) ! Increment left part + + ! Check if left part overflowed (needs more digits) + if (cycnum%cnLeft%nmMaxDgtIdx > cycnum%cndigits) then + cycnum%cndigits = cycnum%cndigits + 1 ! Increase digit count + call ClearNum9(cycnum%cnLeft, cycnum%cndigits) ! Reset left + call ClearNum9(cycnum%cnRight, cycnum%cndigits) ! Reset right + if (cycnum%cndigits > MAX_DIGITS) then + cycnum%cndigits = MAX_DIGITS ! Enforce maximum + end if + end if + end if + + ! Reconstruct complete cyclops number: left * 10^(digits+1) + right + cycnum%cnNum = cycnum%cnLeft%nmNum * cnPow10Shift(cycnum%cndigits) + cycnum%cnRight%nmNum + cycnum%cnIdx = cycnum%cnIdx + 1 + else + ! Special case: first cyclops number + cycnum%cnNum = 101 + cycnum%cnIdx = 1 + end if + end subroutine NextCycNum + + + !============================================================================ + ! Make a complete Palindromic Cyclops number when left half is already setup. + ! Argument is already initialized to have its left half setup as needed. + ! Fill digits of right half in reversed order. + ! @param cycnum: half-filled Cyclops number to be completed as palindrome. + !============================================================================ + + subroutine MakePalinCycNum (cycnum) + type(CyclopsNum), intent(inout) :: cycnum + + ! make right to have reversed digits of left + integer :: n,dgt + integer :: i,j + + n = 0 + i = 0 + do j = cycnum%cnDigits, 0 , -1 + dgt = cycnum%cnLeft%nmdgts(i) + cycnum%cnRight%nmdgts(j) = dgt + n = 10*n+(dgt+1) + i = i + 1 + end do + cycnum%cnRight%nmNum = n + cycnum%cnNum = cycnum%cnLeft%nmNum*cnPow10Shift(cycnum%cndigits)+n + end subroutine MakePalinCycNum + + + + !============================================================================ + ! Increment left half of a Cyclops number, handling carry-over + !============================================================================ + + subroutine IncLeftCn( cn ) + + type(CyclopsNum), intent(inout) :: cn + + ! set right digits to minimum + call ClearNum9 (cn%cnRight,cn%cndigits) + ! increment left digits + call IncNum9 (cn%cnLeft) + ! One more digit in left half? + if (cn%cnLeft%nmMaxDgtIdx > cn%cndigits) then ! left has more digits than before? + cn%cndigits = cn%cndigits + 1 ! Increment for entire Cyclops number + call ClearNum9(cn%cnLeft,cn%cndigits) ! Set left to minimum for new number of digits + call ClearNum9(cn%cnRight,cn%cndigits) ! Set right to minimum for new number of digits + if (cn%cndigits>MAX_DIGITS) then + cn%cndigits = MAX_DIGITS + endif + endif + cn%cnNum = cn%cnLeft%nmNum*cnPow10Shift(cn%cndigits)+cn%cnRight%nmNUm + end subroutine IncLeftCn + + !============================================================================ + ! Convert a zero-based index to the corresponding cyclops number + ! Uses combinatorial counting based on digit positions in base-9 + ! @param n: Zero-based index + ! @return: Corresponding cyclops number + !============================================================================ + function IndexToCyclops(n) result(result_cn) + integer(kind=8), intent(in) :: n + type(CyclopsNum) :: result_cn + integer :: dgtCnt, i + integer(kind=8) :: p9, q, num, local_n + + call InitCycNum(result_cn) + if (n == 0) return ! Index 0 returns initialized (0) + + result_cn%cnIdx = n + dgtCnt = 0 + local_n = n + + ! Determine number of digits needed + do + p9 = cnPow9(dgtCnt) * cnPow9(dgtCnt) ! Combinations for dgtCnt digits + if (local_n < p9) exit ! Found correct digit count + local_n = local_n - p9 ! Subtract counted combinations + dgtCnt = dgtCnt + 1 ! Try next digit count + if (dgtCnt > 10) exit ! Safety limit + end do + + dgtCnt = dgtCnt - 1 ! Adjust to actual digit count + + ! Process right digits (convert from base-9 to base-10) + result_cn%cnRight%nmMaxDgtIdx = dgtCnt + do i = 0, dgtCnt + q = local_n / 9 ! Integer division + result_cn%cnRight%nmdgts(i) = local_n - 9 * q ! Remainder gives base-9 digit + local_n = q ! Continue with quotient + end do + + ! Convert base-9 digits to base-10 number (adding 1 to each digit) + num = 0 + do i = dgtCnt, 0, -1 ! Most significant digit first + num = num * 10 + result_cn%cnRight%nmdgts(i) + 1 + end do + result_cn%cnRight%nmNum = num + result_cn%cnNum = num ! Temporary: only right part + + ! Process left digits (same algorithm) + result_cn%cnLeft%nmMaxDgtIdx = dgtCnt + do i = 0, dgtCnt + q = local_n / 9 + result_cn%cnLeft%nmdgts(i) = local_n - 9 * q + local_n = q + end do + + ! Convert left digits to base-10 number + num = 0 + do i = dgtCnt, 0, -1 + num = num * 10 + result_cn%cnLeft%nmdgts(i) + 1 + end do + result_cn%cnLeft%nmNum = num + + ! Combine left and right with zero in middle: left * 10^(dgtCnt+1) + right + result_cn%cnNum = result_cn%cnNum + num * cnPow10Shift(dgtCnt) + result_cn%cndigits = dgtCnt + end function IndexToCyclops + + !============================================================================ + ! Display cyclops numbers in formatted columns + ! @param cl: Array of cyclops numbers + ! @param colw: Column width for formatting + ! @param colc: Number of columns per row + !============================================================================ + subroutine Out_Cyclops(cl, colw, colc) + integer(kind=8), intent(in) :: cl(:) + integer, intent(in) :: colw, colc + integer :: i, n + character (len=50) :: colFormat + + n = size(cl) + if (n > 100) n = 100 + + ! Create suitable format string to nicely printout columns using colw as width + write (colformat, '("(I", I0, " )" )') colw + + ! Print all "n=size(cl)" Numbers of array cl + do i = 1, n + write(*, colformat, advance='no') cl(i) ! Print number using calculated format string + if (mod(i, colc) == 0) then + write(*, *) ! New line after colc numbers + else + write(*, '(A)', advance='no') ' ' ! Space between numbers + end if + end do + + ! Terminate line if incomplete + if (mod(i, colc) /= 0) write(*, *) + end subroutine Out_Cyclops + + !============================================================================ + ! Check if a number is prime (simple trial division) + ! @param n: Number to check + ! @return: .true. if prime, .false. otherwise + !============================================================================ + logical function isPrime(n) + integer(kind=8), intent(in) :: n + integer(kind=8) :: p, q + + ! Handle small numbers and simple cases + if (n <= 1) then + isPrime = .false. + return + end if + + if (n == 2 .or. n == 3 .or. n == 5) then + isPrime = .true. + return + end if + + ! Even numbers and multiples of 3 + if (mod(n, 2) == 0 .or. mod(n, 3) == 0) then + isPrime = .false. + return + end if + + ! Trial division for remaining numbers + p = 5 + do + q = n / p + if (n - q * p == 0) then ! Divisible by p + isPrime = .false. + return + end if + p = p + 2 ! Next odd number + + q = n / p + if (n - q * p == 0) then ! Divisible by p+2 + isPrime = .false. + return + end if + + if (q < p) exit ! No need to check further + p = p + 4 ! Skip to next candidate + end do + + isPrime = .true. ! No divisors found + end function isPrime + + !============================================================================ + ! Generate the first 'cnt' basic cyclops numbers + ! @param cnt: Number of cyclops numbers to generate + ! @return: Last cyclops number generated (for continuation) + !============================================================================ + function FirstCyclops(cnt) result(result_cn) + integer, intent(in) :: cnt + type(CyclopsNum) :: result_cn + integer :: i + + ! Allocate storage for results + if (allocated(Cyclops)) deallocate(Cyclops) + allocate(Cyclops(cnt)) + + i = 1 + call InitCycNum(result_cn) + + ! Generate requested number of cyclops numbers + do while (i <= cnt) + Cyclops(i) = result_cn%cnNum + i = i + 1 + call NextCycNum(result_cn) + end do + + ! Continue until beyond BIGLIMIT for reporting + do while (result_cn%cnNum <= BIGLIMIT) + call NextCycNum(result_cn) + end do + end function FirstCyclops + + !============================================================================ + ! Generate the first 'cnt' prime cyclops numbers + ! @param cnt: Number of prime cyclops numbers to generate + ! @return: Last prime cyclops number with updated index + ! Algorithm as in function FirstCyclops, but check for each generated + ! Cyclops number if its prime. + !============================================================================ + function FirstPrimeCyclops(cnt) result(result_cn) + integer, intent(in) :: cnt + type(CyclopsNum) :: result_cn + integer :: i + + if (allocated(Cyclops)) deallocate(Cyclops) + allocate(Cyclops(cnt)) + + i = 1 + call InitCycNum(result_cn) + + do while (i <= cnt) + if (isPrime(result_cn%cnNum)) then ! only consider prime Cyclops numbers + Cyclops(i) = result_cn%cnNum + i = i + 1 + end if + call NextCycNum(result_cn) + end do + + + ! Continue until prime Cyclops number is beyond BIGLIMIT for reporting + do + if (isPrime(result_cn%cnNum)) then + result_cn%cnIdx = i ! result_cn%cnIdx + 1 + if (result_cn%cnNum .gt. BIGLIMIT) exit + i = i + 1 + end if + call NextCycNum(result_cn) + end do + end function FirstPrimeCyclops + + + + !============================================================================ + ! Generate the first 'cnt' prime blind cyclops numbers + ! @param cnt: Number of prime cyclops numbers to generate + ! @return: Last prime cyclops number with updated index + ! Algorithm as in function FirstCyclops, but check for each generated + ! Cyclops number if its prime, then construct blind number from this, and + ! check again if result is prime as well. + !============================================================================ + function FirstPrimeBlindCyclops(cnt) result(result_cn) + integer, intent(in) :: cnt + type(CyclopsNum) :: result_cn + integer :: i + integer (kind=8) :: n + + if (allocated(Cyclops)) deallocate(Cyclops) + allocate(Cyclops(cnt)) + + i = 1 + call InitCycNum(result_cn) + + do while (i <= cnt) + if (isPrime(result_cn%cnNum)) then + + n = result_cn%cnRight%nmnum + if (result_cn%cndigits .gt. 0) then + n = n + result_cn%cnLeft%nmnum*cnPow10Shift(result_cn%cndigits-1) + else + n = n + result_cn%cnLeft%nmnum*10 + endif + if (isPrime (n)) then + Cyclops(i) =result_cn%cnNum + i = i + 1 + endif + end if + call NextCycNum(result_cn) + end do + + do + if (isPrime(result_cn%cnNum)) then + n = result_cn%cnRight%nmnum + if (result_cn%cndigits .gt. 0) then + n = n + result_cn%cnLeft%nmnum*cnPow10Shift(result_cn%cndigits-1) + else + n = n + result_cn%cnLeft%nmnum*10 + endif + if (isPrime (n)) then + result_cn%cnIdx = i + if (result_cn%cnNum .gt. BIGLIMIT) exit + i = i + 1 + end if + end if + call NextCycNum(result_cn) + end do + end function FirstPrimeBlindCyclops + + !============================================================================ + ! Generate the first 'cnt' prime palindromic cyclops numbers + ! @param cnt: Number of prime palindromic cyclops numbers to generate + ! @return: Last prime cyclops number with updated index + ! Algorithm: directly create palindromic cyclops numbers and look for primes. + !============================================================================ + function FirstPrimePalindromicCyclops(cnt) result(result_cn) + integer, intent(in) :: cnt + type(CyclopsNum) :: result_cn + integer :: i + integer (kind=8) :: n + + if (allocated(Cyclops)) deallocate(Cyclops) + allocate(Cyclops(cnt)) + + i = 1 + call InitCycNum(result_cn) + + do while (i <= cnt) + call MakePalinCycNum (result_cn) ! Complete prepare Cyclops number to a palindrome + if (isPrime(result_cn%cnNum)) then ! Consider only if its prime. + Cyclops(i) =result_cn%cnNum + i = i + 1 + end if + call IncLeftCn (result_cn) ! Next one. + + ! Last digit cannot be even because we need only prime numbers + do while (result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 1 .AND. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 3 .and. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 5 .and. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 7 .and. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 9) + call IncLeftCn(result_cn) + end do + end do + + do + call MakePalinCycNum (result_cn) + if (isPrime(result_cn%cnNum)) then + result_cn%cnIdx = i + if (result_cn%cnNum .gt. BIGLIMIT) exit + i = i + 1 + end if + call IncLeftCn (result_cn) + + do while (result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 1 .AND. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 3 .and. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 5 .and. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 7 .and. & + result_cn%cnLeft%nmdgts(result_cn%cnDigits)+1 .ne. 9) + call IncLeftCn(result_cn) + end do + end do + + end function FirstPrimePalindromicCyclops + +end module CyclopsNumbers + +program main + use CyclopsNumbers + implicit none + + type(CyclopsNum) :: cycnum + integer :: cnt + integer(kind=8) :: i, large_cnt + + call InitCnMinPow() + + ! First 50 cyclops numbers + cnt = 50 + write(*, "( 'The first ', I0, ' cyclops numbers are:')") cnt + cycnum = FirstCyclops(cnt) + call Out_Cyclops(Cyclops, 5, 10) + write(*, "('First cyclops number > ', I0, ' is ', I0, ' at 1-based index ', I0, / )") BIGLIMIT, cycnum%cnNum, cycnum%cnIdx + + ! First 50 prime cyclops numbers + cnt = 50 + write(*, "('The first ', I0, ' prime cyclops numbers are:')") cnt + cycnum = FirstPrimeCyclops(cnt) + call Out_Cyclops(Cyclops, 7, 10) + write(*, "('First prime cyclops number > ', I0, ' is ', I0, ' at 1-based index ', I0, / )") BIGLIMIT, cycnum%cnNum, cycnum%cnIdx + write(*, *) + + +! First 50 prime blind cyclops numbers + cnt = 50 + write(*, "('The first ', I0, ' prime blind cyclops numbers are:')") cnt + cycnum = FirstPrimeBlindCyclops(cnt) + call Out_Cyclops(Cyclops, 7, 10) + write(*, "('First prime blind cyclops number > ', I0, ' is ', I0, ' at 1-based index ', I0, / )") BIGLIMIT, cycnum%cnNum, cycnum%cnIdx + +! First 50 prime palindromic cyclops numbers + cnt = 50 + write(*, "( 'The first ', I0, ' prime palindromic cyclops numbers are:')") cnt + cycnum = FirstPrimePalindromicCyclops(cnt) + call Out_Cyclops(Cyclops, 7, 10) + write(*, "('First palindromic prime cyclops number > ', I0, ' is ', I0, ' at 1-based index ', I0, / )") BIGLIMIT, cycnum%cnNum, cycnum%cnIdx + + + + + ! Additional test cases for large indices + write(*, '(A/)') 'Demonstrating Cyclops calculation for large indices:' + write(*, '(A)') ' Index Cyclop Number Calculated Cyclop Number ' + large_cnt = 100 + do while (large_cnt <= 1000000000000000_8) + write(*, '(I17, A)', advance='no') large_cnt, ' ' + if (large_cnt <= 10000) then ! For small index values evaluate Cyclops number sequentially + call InitCycNum(cycnum) + do i = 1, large_cnt-1 ! at index 1 we have 0, is already there by initialisation + call NextCycNum(cycnum) ! hence we need only (large_cnt-1) next sequence elements + end do + write(*, '(I7)', advance='no') cycnum%cnNum + else + write (*, '(" ")', advance='no') + end if + cycnum = IndexToCyclops(large_cnt-1) ! direct calculation, for comparison when index is small + write(*, *) ' ', cycnum%cnNum + large_cnt = large_cnt * 10 ! next order of magnitude + end do + +end program main diff --git a/Task/Cyclops-numbers/JavaScript/cyclops-numbers.js b/Task/Cyclops-numbers/JavaScript/cyclops-numbers.js new file mode 100644 index 0000000000..d252c63019 --- /dev/null +++ b/Task/Cyclops-numbers/JavaScript/cyclops-numbers.js @@ -0,0 +1,136 @@ +// Cyclops Numbers - JavaScript implementation + +function main() { + const cyclops = []; + const primeCyclops = []; + const blindPrimeCyclops = []; + const palindromicPrimeCyclops = []; + + const ranges = [ + [0, 0], + [101, 909], + [11011, 99099], + [1110111, 9990999], + [111101111, 119101111] + ]; + + for (const range of ranges) { + for (let i = range[0]; i <= range[1]; i++) { + const value = String(i); + if (isCyclopsNumber(value)) { + cyclops.push(i); + if (isPrime(i)) { + primeCyclops.push(i); + if (isBlind(value)) { + blindPrimeCyclops.push(i); + } + if (isPalindromic(value)) { + palindromicPrimeCyclops.push(i); + } + } + } + } + } + + console.log("The first 50 Cyclops numbers:"); + for (let i = 0; i < 50; i++) { + process.stdout.write(String(cyclops[i]).padStart(6) + (i % 10 === 9 ? "\n" : "")); + } + console.log(); + let idx = firstIndex(cyclops); + console.log("The first cyclops number greater than ten million is " + + cyclops[idx] + " at zero based index " + idx); + console.log(); + + console.log("The first 50 prime Cyclops numbers:"); + for (let i = 0; i < 50; i++) { + process.stdout.write(String(primeCyclops[i]).padStart(7) + (i % 10 === 9 ? "\n" : "")); + } + console.log(); + idx = firstIndex(primeCyclops); + console.log("The first prime cyclops number greater than ten million is " + + primeCyclops[idx] + " at zero based index " + idx); + console.log(); + + console.log("The first 50 blind prime Cyclops numbers:"); + for (let i = 0; i < 50; i++) { + process.stdout.write(String(blindPrimeCyclops[i]).padStart(7) + (i % 10 === 9 ? "\n" : "")); + } + console.log(); + idx = firstIndex(blindPrimeCyclops); + console.log("The first blind prime cyclops number greater than ten million is " + + blindPrimeCyclops[idx] + " at zero based index " + idx); + console.log(); + + console.log("The first 50 palindromic prime Cyclops numbers:"); + for (let i = 0; i < 50; i++) { + process.stdout.write(String(palindromicPrimeCyclops[i]).padStart(9) + (i % 10 === 9 ? "\n" : "")); + } + console.log(); + idx = firstIndex(palindromicPrimeCyclops); + console.log("The first palindromic prime cyclops number greater than ten million is " + + palindromicPrimeCyclops[idx] + " at zero based index " + idx); + console.log(); +} + +function firstIndex(numbers) { + let start = 0; + let end = numbers.length - 1; + + while (start <= end) { + const mid = start + Math.floor((end - start) / 2); + if (numbers[mid] <= 10000000) { + start = mid + 1; + } else { + end = mid - 1; + } + } + return start; +} + +function isCyclopsNumber(text) { + const middleIndex = Math.floor(text.length / 2); + return text[middleIndex] === '0' && text.indexOf('0') === text.lastIndexOf('0'); +} + +function isPalindromic(text) { + for (let i = 0; i < Math.floor(text.length / 2); i++) { + if (text[i] !== text[text.length - 1 - i]) { + return false; + } + } + return true; +} + +function isBlind(text) { + const middle = Math.floor(text.length / 2); + const withoutZero = text.substring(0, middle) + text.substring(middle + 1); + return isPrime(parseInt(withoutZero, 10)); +} + +function isPrime(number) { + if (number < 2) { + return false; + } + if (number % 2 === 0) { + return number === 2; + } + if (number % 3 === 0) { + return number === 3; + } + let k = 5; + while (k * k <= number) { + if (number % k === 0) { + return false; + } + k += 2; + if (number % k === 0) { + return false; + } + k += 4; + } + return true; +} + +// Run the main function +main(); diff --git a/Task/Cyclops-numbers/Pluto/cyclops-numbers.pluto b/Task/Cyclops-numbers/Pluto/cyclops-numbers.pluto new file mode 100644 index 0000000000..1c19a3444b --- /dev/null +++ b/Task/Cyclops-numbers/Pluto/cyclops-numbers.pluto @@ -0,0 +1,63 @@ +local int = require "int" +local fmt = require "fmt" +require "table2" + +local function find_first(list) + for i, n in list do + if n > 1e7 then return n, i end + end +end + +local ranges = { + range(0, 0), + range(101, 909), + range(11011, 99099), + range(1110111, 9990999), + range(111101111, 119101111) +} +local cyclops = {} +for ranges as r do + local num_digits = #tostring(r[1]) + local center = num_digits // 2 + for r as i do + local digits = int.digits(i, 10. false, false) + if digits[center + 1] == 0 and digits:count(|d| -> d == 0) == 1 then + cyclops:insert(i) + end + end +end + +print("The first 50 cyclops numbers are:") +local candidates = cyclops:slice(1, 50) +local n, i = find_first(cyclops) +fmt.tprint("%,6s", candidates, 10) +fmt.print("\nFirst such number > 10 million is %,s at one-based index %,s", n, i) + +print("\n\nThe first 50 prime cyclops numbers are:") +local primes = cyclops:filter(|c| -> int.isprime(c)):reorder() +candidates = primes:slice(1, 50) +n, i = find_first(primes) +fmt.tprint("%,6s", candidates, 10) +fmt.print("\nFirst such number > 10 million is %,s at one-based index %,s", n, i) + +print("\n\nThe first 50 blind prime cyclops numbers are:") +local bpcyclops = {} +local ppcyclops = {} +for primes as p do + local ps = tostring(p) + local num_digits = #ps + local center = num_digits // 2 + local no_middle = tonumber(ps:sub(1, center) .. ps:sub(center + 2)) + if int.isprime(no_middle) then bpcyclops:insert(p) end + if ps == ps:reverse() then ppcyclops:insert(p) end +end +candidates = bpcyclops:slice(1, 50) +n, i = find_first(bpcyclops) +fmt.tprint("%,6s", candidates, 10) +fmt.print("\nFirst such number > 10 million is %,s at one-based index %,s", n, i) + +print("\n\nThe first 50 palindromic prime cyclops numbers are:") +candidates = ppcyclops:slice(1, 50) +n, i = find_first(ppcyclops) +fmt.tprint("%,9s", candidates, 8) +fmt.print("\nFirst such number > 10 million is %,s at one-based index %,s", n, i) diff --git a/Task/DNS-query/Ada/dns-query-1.adb b/Task/DNS-query/Ada/dns-query-1.adb new file mode 100644 index 0000000000..bf03d08eb4 --- /dev/null +++ b/Task/DNS-query/Ada/dns-query-1.adb @@ -0,0 +1,13 @@ +with Ada.Text_IO; use Ada.Text_IO; +with GNAT.Sockets; use GNAT.Sockets; + +procedure DNSQuerying is + + Host : Host_Entry_Type (1, 1); + Inet_Addr_V4 : Inet_Addr_Type (Family_Inet); +begin + + Host := Get_Host_By_Name (Name => "www.kame.net"); + Inet_Addr_V4 := Addresses (Host); + Put ("IPv4: " & Image (Value => Inet_Addr_V4)); +end DNSQuerying; diff --git a/Task/DNS-query/Ada/dns-query-2.adb b/Task/DNS-query/Ada/dns-query-2.adb new file mode 100644 index 0000000000..cac296431f --- /dev/null +++ b/Task/DNS-query/Ada/dns-query-2.adb @@ -0,0 +1,14 @@ +with Ada.Text_IO; use Ada.Text_IO; +with GNAT.Sockets; use Gnat.Sockets; +procedure DNSQuerying is + procedure Print_Address_Info (Host, Serv : String; Family : Family_Type := Family_Unspec) is + Addresses : Address_Info_Array := Get_Address_Info (Host, Serv, Family, Passive => False, Numeric_Host => False); + Inet_Addr_V6: Inet_Addr_Type(Family_Inet6); + begin + Sort (Addresses, IPv6_TCP_Preferred'Access); + Inet_Addr_V6 := Addresses(1).Addr.Addr; + Put_Line("IPv6: " & Image(Value => Inet_Addr_V6)); + end Print_Address_Info; +begin + Print_Address_Info ("ipv6.google.com", "https", Family_Inet6); +end DNSQuerying; diff --git a/Task/DNS-query/Batch-File/dns-query-1.bat b/Task/DNS-query/Batch-File/dns-query-1.bat new file mode 100644 index 0000000000..b3f4e193c0 --- /dev/null +++ b/Task/DNS-query/Batch-File/dns-query-1.bat @@ -0,0 +1,38 @@ +:: DNS Query Task from Rosetta Code Wiki +:: Batch File Implementation + +@echo off + +set "domain=www.kame.net" +echo DOMAIN: "%domain%" +echo( +call :DNS_Lookup "%domain%" +pause +exit /b + +::Main Procedure +::Uses NSLOOKUP Command. Also uses a dirty "parsing" to detect IP addresses. +:DNS_Lookup [domain] + +::Define Variables and the TAB Character +set "dom=%~1" +set "record=" +set "reccnt=0" +for /f "delims=" %%T in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do set "TAB=%%T" + +setlocal enabledelayedexpansion +for /f "tokens=1* delims=:" %%x in ('nslookup "!dom!" 2^>nul') do ( + set "line=%%x" + if /i "!line:~0,4!"=="Name" set "record=yes" + if /i "!line:~0,5!"=="Alias" set "record=" + if "!record!"=="yes" ( + set /a reccnt+=1 + if "%%y"=="" (set "catch_!reccnt!=%%x") else (set "catch_!reccnt!=%%x:%%y") + ) +) +for /l %%c in (1,1,%reccnt%) do ( + if /i "!catch_%%c:~0,7!"=="Address" echo(!catch_%%c:*s: =! + if /i "!catch_%%c:~0,1!"=="%TAB%" echo(!catch_%%c:%TAB% =! +) +endlocal +goto :EOF diff --git a/Task/DNS-query/Batch-File/dns-query-2.bat b/Task/DNS-query/Batch-File/dns-query-2.bat new file mode 100644 index 0000000000..fa20a4ced6 --- /dev/null +++ b/Task/DNS-query/Batch-File/dns-query-2.bat @@ -0,0 +1,11 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +set catch= +for /f "skip=4 tokens=*" %%g in ('nslookup www.kame.net 2^>nul') do ( + set "a=%%g" + if defined catch echo %%g + if "!a:~0,7!" equ "Address" ( + for /f "tokens=2" %%h in ('echo %%g') do echo %%h + set catch=1 + ) +) diff --git a/Task/DNS-query/Batch-File/dns-query-3.bat b/Task/DNS-query/Batch-File/dns-query-3.bat new file mode 100644 index 0000000000..2bfef6a987 --- /dev/null +++ b/Task/DNS-query/Batch-File/dns-query-3.bat @@ -0,0 +1,14 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +call :getdns -4 +call :getdns -6 +goto :eof +:getdns +for /f "tokens=*" %%g in ('ping %1 -n 1 www.kame.net') do ( + set a=%%g + if "!a:~0,15!" equ "Ping statistics" ( + echo !a:~20,-1! + goto :eof + ) +) +goto :eof diff --git a/Task/DNS-query/Pluto/dns-query.pluto b/Task/DNS-query/Pluto/dns-query.pluto new file mode 100644 index 0000000000..0d8024de71 --- /dev/null +++ b/Task/DNS-query/Pluto/dns-query.pluto @@ -0,0 +1,6 @@ +local url = "www.kame.net" +print(url) +print("\nIPv4:") +for os.dnsresolve("A", url) as record do print(record.data) end +print("\nIPv6:") +for os.dnsresolve("AAAA", url) as record do print(record.data) end diff --git a/Task/DNS-query/PowerShell/dns-query.ps1 b/Task/DNS-query/PowerShell/dns-query.ps1 new file mode 100644 index 0000000000..fa8a8c6225 --- /dev/null +++ b/Task/DNS-query/PowerShell/dns-query.ps1 @@ -0,0 +1,2 @@ +$DNS = Resolve-DnsName -Name www.kame.net +Write-Host "IPv4:" $DNS.IP4Address "`nIPv6:" $DNS.IP6Address diff --git a/Task/DNS-query/Rye/dns-query.rye b/Task/DNS-query/Rye/dns-query.rye new file mode 100644 index 0000000000..7cc6f0511b --- /dev/null +++ b/Task/DNS-query/Rye/dns-query.rye @@ -0,0 +1 @@ +print lookup-ip "www.kame.net" diff --git a/Task/DNS-query/VBScript/dns-query.vbs b/Task/DNS-query/VBScript/dns-query.vbs new file mode 100644 index 0000000000..2636f7ad2b --- /dev/null +++ b/Task/DNS-query/VBScript/dns-query.vbs @@ -0,0 +1,16 @@ +Function dns_query(url,ver) + Set r = New RegExp + r.Pattern = "Pinging.+?\[(.+?)\].+" + Set objshell = CreateObject("WScript.Shell") + Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) + WScript.StdOut.WriteLine "URL: " & url + Do Until objexec.StdOut.AtEndOfStream + line = objexec.StdOut.ReadLine + If r.Test(line) Then + WScript.StdOut.WriteLine "IP Version " &_ + ver & ": " & r.Replace(line,"$1") + End If + Loop +End Function + +Call dns_query(WScript.Arguments(0),WScript.Arguments(1)) diff --git a/Task/Damm-algorithm/Ada/damm-algorithm.adb b/Task/Damm-algorithm/Ada/damm-algorithm.adb new file mode 100644 index 0000000000..49e20cde4f --- /dev/null +++ b/Task/Damm-algorithm/Ada/damm-algorithm.adb @@ -0,0 +1,39 @@ +with Ada.Text_IO; + +procedure Damm_Algorithm is + + function Damm (Input : in String) return Boolean + is + subtype Digit is Character range '0' .. '9'; + + Table : constant array (Digit, Digit) of Digit := + (('0', '3', '1', '7', '5', '9', '8', '6', '4', '2'), + ('7', '0', '9', '2', '1', '5', '4', '8', '6', '3'), + ('4', '2', '0', '6', '8', '7', '1', '3', '5', '9'), + ('1', '7', '5', '0', '9', '8', '3', '4', '2', '6'), + ('6', '1', '2', '3', '0', '4', '5', '9', '7', '8'), + ('3', '6', '7', '4', '2', '0', '9', '5', '8', '1'), + ('5', '8', '6', '9', '7', '2', '0', '1', '3', '4'), + ('8', '9', '4', '5', '3', '6', '2', '0', '1', '7'), + ('9', '4', '3', '8', '6', '1', '7', '2', '0', '5'), + ('2', '5', '8', '1', '4', '3', '6', '7', '9', '0')); + Intern : Digit := '0'; + begin + for D of Input loop + Intern := Table (Intern, D); + end loop; + return Intern = '0'; + end Damm; + + procedure Put_Damm (Input : in String) is + use Ada.Text_IO; + begin + Put_Line ("Damm of " & Input & " validates as " & Damm (Input)'Image); + end Put_Damm; + +begin + Put_Damm ("5724"); + Put_Damm ("5727"); + Put_Damm ("112946"); + Put_Damm ("112949"); +end Damm_Algorithm; diff --git a/Task/Damm-algorithm/Agena/damm-algorithm.agena b/Task/Damm-algorithm/Agena/damm-algorithm.agena new file mode 100644 index 0000000000..c046ba9494 --- /dev/null +++ b/Task/Damm-algorithm/Agena/damm-algorithm.agena @@ -0,0 +1,43 @@ +scope # Damm Algorithm + + # returns true if the check digit of s is correct according to the Damm algorithm, + # false otherwise # + local proc hasValidDammCheckDigit( s :: string ) :: boolean + + local constant operationTable + := seq( (/ 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 \) # as per wikipedia example + , (/ 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 \) + , (/ 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 \) + , (/ 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 \) + , (/ 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 \) + , (/ 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 \) + , (/ 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 \) + , (/ 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 \) + , (/ 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 \) + , (/ 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 \) + ); + local interimDigit := 0; + for sPos to size s do + local constant nextDigit := abs s[ sPos ] - abs "0"; + if 0 <= nextDigit and nextDigit <= 9 then + interimDigit := operationTable[ interimDigit + 1, nextDigit + 1 ] + else + error( "Invalid Damm digit: [" & s[ sPos ] & "]" ) + fi + od; + return interimDigit = 0 + end; + + local proc testDammAlgorithm( s :: string, expectedResult :: boolean ) + local constant isValid := hasValidDammCheckDigit( s ); + printf( "check digit of %s is %s%s\n", s + , if isValid then "valid" else "invalid" fi + , if isValid == expectedResult then "" else " *** NOT AS EXPECTED" fi + ) + end; + + # test cases + testDammAlgorithm( "5724", true ); + testDammAlgorithm( "5727", false ); + testDammAlgorithm( "112946", true ) +end diff --git a/Task/Damm-algorithm/COBOL/damm-algorithm.cob b/Task/Damm-algorithm/COBOL/damm-algorithm.cob new file mode 100644 index 0000000000..e8e8995622 --- /dev/null +++ b/Task/Damm-algorithm/COBOL/damm-algorithm.cob @@ -0,0 +1,197 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. DAMM-ALGORITHM. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + *> Damm quasi-group table (10x10) + 01 DAMM-TABLE. + 05 ROW-0. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 2. + 05 ROW-1. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 3. + 05 ROW-2. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 9. + 05 ROW-3. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 6. + 05 ROW-4. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 8. + 05 ROW-5. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 1. + 05 ROW-6. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 4. + 05 ROW-7. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 7. + 05 ROW-8. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 0. + 10 FILLER PIC 9 VALUE 5. + 05 ROW-9. + 10 FILLER PIC 9 VALUE 2. + 10 FILLER PIC 9 VALUE 5. + 10 FILLER PIC 9 VALUE 8. + 10 FILLER PIC 9 VALUE 1. + 10 FILLER PIC 9 VALUE 4. + 10 FILLER PIC 9 VALUE 3. + 10 FILLER PIC 9 VALUE 6. + 10 FILLER PIC 9 VALUE 7. + 10 FILLER PIC 9 VALUE 9. + 10 FILLER PIC 9 VALUE 0. + + *> Redefine table as a 2D array for indexed access + 01 DAMM-TABLE-R REDEFINES DAMM-TABLE. + 05 DAMM-ROW OCCURS 10 TIMES. + 10 DAMM-CELL OCCURS 10 TIMES PIC 9. + + *> Test numbers + 01 TEST-NUMBERS. + 05 TEST-NUM PIC 9(6) VALUE 005724. + 05 TEST-NUM PIC 9(6) VALUE 005727. + 05 TEST-NUM PIC 9(6) VALUE 112946. + 05 TEST-NUM PIC 9(6) VALUE 112949. + + 01 TEST-NUMBERS-R REDEFINES TEST-NUMBERS. + 05 TEST-ENTRY OCCURS 4 TIMES PIC 9(6). + + *> Working variables + 01 WS-NUMBER-STR PIC X(6). + 01 WS-INTERIM PIC 9 VALUE 0. + 01 WS-DIGIT PIC 9. + 01 WS-ROW-IDX PIC 99. + 01 WS-COL-IDX PIC 99. + 01 WS-CHAR-POS PIC 9. + 01 WS-STR-LEN PIC 9. + 01 WS-LOOP-IDX PIC 9. + 01 WS-NUM-IDX PIC 9. + 01 WS-IS-VALID PIC X VALUE 'N'. + 01 WS-DISPLAY-NUM PIC Z(5)9. + + PROCEDURE DIVISION. + + MAIN-PARA. + PERFORM VARYING WS-NUM-IDX FROM 1 BY 1 + UNTIL WS-NUM-IDX > 4 + + MOVE TEST-ENTRY(WS-NUM-IDX) TO WS-DISPLAY-NUM + MOVE TEST-ENTRY(WS-NUM-IDX) TO WS-NUMBER-STR + + *> Strip leading zeros to get actual digit string + MOVE FUNCTION TRIM(WS-NUMBER-STR LEADING) + TO WS-NUMBER-STR + MOVE FUNCTION LENGTH( + FUNCTION TRIM(WS-NUMBER-STR TRAILING)) + TO WS-STR-LEN + + PERFORM DAMM-CHECK + + IF WS-IS-VALID = 'Y' + DISPLAY WS-DISPLAY-NUM " is valid" + ELSE + DISPLAY WS-DISPLAY-NUM " is invalid" + END-IF + + END-PERFORM + + STOP RUN. + + DAMM-CHECK. + MOVE 0 TO WS-INTERIM + + PERFORM VARYING WS-CHAR-POS FROM 1 BY 1 + UNTIL WS-CHAR-POS > WS-STR-LEN + + MOVE WS-NUMBER-STR(WS-CHAR-POS:1) TO WS-DIGIT + + *> Table is 1-indexed in COBOL, so add 1 to row/col + COMPUTE WS-ROW-IDX = WS-INTERIM + 1 + COMPUTE WS-COL-IDX = WS-DIGIT + 1 + + MOVE DAMM-CELL(WS-ROW-IDX, WS-COL-IDX) + TO WS-INTERIM + + END-PERFORM + + IF WS-INTERIM = 0 + MOVE 'Y' TO WS-IS-VALID + ELSE + MOVE 'N' TO WS-IS-VALID + END-IF. diff --git a/Task/Damm-algorithm/Icon/damm-algorithm.icon b/Task/Damm-algorithm/Icon/damm-algorithm.icon new file mode 100644 index 0000000000..33595e1420 --- /dev/null +++ b/Task/Damm-algorithm/Icon/damm-algorithm.icon @@ -0,0 +1,21 @@ +procedure main(A) + \A | stop("You must give one or more numeric values") + every n := !A do write(n," is ",(damm(n),"valid")|"not valid") +end + +procedure damm(n) + static grid + initial grid := [[0, 3, 1, 7, 5, 9, 8, 6, 4, 2], + [7, 0, 9, 2, 1, 5, 4, 8, 6, 3], + [4, 2, 0, 6, 8, 7, 1, 3, 5, 9], + [1, 7, 5, 0, 9, 8, 3, 4, 2, 6], + [6, 1, 2, 3, 0, 4, 5, 9, 7, 8], + [3, 6, 7, 4, 2, 0, 9, 5, 8, 1], + [5, 8, 6, 9, 7, 2, 0, 1, 3, 4], + [8, 9, 4, 5, 3, 6, 2, 0, 1, 7], + [9, 4, 3, 8, 6, 1, 7, 2, 0, 5], + [2, 5, 8, 1, 4, 3, 6, 7, 9, 0]] + interim := 0 + every d := !n do interim := grid[interim+1][d+1] + return 0 = interim +end diff --git a/Task/Damm-algorithm/Pluto/damm-algorithm.pluto b/Task/Damm-algorithm/Pluto/damm-algorithm.pluto new file mode 100644 index 0000000000..34ef6aaffb --- /dev/null +++ b/Task/Damm-algorithm/Pluto/damm-algorithm.pluto @@ -0,0 +1,42 @@ +do -- Damm Algorithm + + -- returns true if the check digit of s is correct according to the Damm algorithm, + -- false otherwise # + local function hasValidDammCheckDigit( s : string ) : boolean + + local operationTable = { { 0, 3, 1, 7, 5, 9, 8, 6, 4, 2 } -- as per wikipedia example + , { 7, 0, 9, 2, 1, 5, 4, 8, 6, 3 } + , { 4, 2, 0, 6, 8, 7, 1, 3, 5, 9 } + , { 1, 7, 5, 0, 9, 8, 3, 4, 2, 6 } + , { 6, 1, 2, 3, 0, 4, 5, 9, 7, 8 } + , { 3, 6, 7, 4, 2, 0, 9, 5, 8, 1 } + , { 5, 8, 6, 9, 7, 2, 0, 1, 3, 4 } + , { 8, 9, 4, 5, 3, 6, 2, 0, 1, 7 } + , { 9, 4, 3, 8, 6, 1, 7, 2, 0, 5 } + , { 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 } + } + local interimDigit = 0 + for sPos = 1, # s do + local nextDigit = string.byte( s[ sPos ] ) - string.byte( "0" ) + if 0 <= nextDigit <= 9 then + interimDigit = operationTable[ interimDigit + 1 ][ nextDigit + 1 ] + else + error( $"Invalid Damm digit: [{s[ sPos ]}]" ) + end + end + return interimDigit == 0 + end + + local function testDammAlgorithm( s : string, expectedResult : boolean ) : void + local isValid = hasValidDammCheckDigit( s ) + print( $"check digit of {s} is " + .. if isValid then "valid" else "invalid" end + .. if isValid == expectedResult then "" else " *** NOT AS EXPECTED" end + ) + end + + -- test cases + testDammAlgorithm( "5724", true ) + testDammAlgorithm( "5727", false ) + testDammAlgorithm( "112946", true ) +end diff --git a/Task/Damm-algorithm/PowerShell/damm-algorithm.ps1 b/Task/Damm-algorithm/PowerShell/damm-algorithm.ps1 new file mode 100644 index 0000000000..c13e20107e --- /dev/null +++ b/Task/Damm-algorithm/PowerShell/damm-algorithm.ps1 @@ -0,0 +1,25 @@ +$table = ( + (0, 3, 1, 7, 5, 9, 8, 6, 4, 2), + (7, 0, 9, 2, 1, 5, 4, 8, 6, 3), + (4, 2, 0, 6, 8, 7, 1, 3, 5, 9), + (1, 7, 5, 0, 9, 8, 3, 4, 2, 6), + (6, 1, 2, 3, 0, 4, 5, 9, 7, 8), + (3, 6, 7, 4, 2, 0, 9, 5, 8, 1), + (5, 8, 6, 9, 7, 2, 0, 1, 3, 4), + (8, 9, 4, 5, 3, 6, 2, 0, 1, 7), + (9, 4, 3, 8, 6, 1, 7, 2, 0, 5), + (2, 5, 8, 1, 4, 3, 6, 7, 9, 0) +) + +function Test-Damm([string]$s) { + $interim = 0 + foreach ($c in $s.ToCharArray()) { + $interim = $table[$interim][[int]$c - [int][char]'0'] + } + return $interim -eq 0 +} + +foreach ($number in 5724, 5727, 112946, 112949) { + $validity = if (Test-Damm $number) {'valid'} else {'invalid'} + '{0,6} is {1}' -f $number, $validity +} diff --git a/Task/Date-format/Ada/date-format.adb b/Task/Date-format/Ada/date-format.adb new file mode 100644 index 0000000000..c7fc5f8aa9 --- /dev/null +++ b/Task/Date-format/Ada/date-format.adb @@ -0,0 +1,44 @@ +with Ada.Calendar; use Ada.Calendar; +with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Date_Format is + function Image (Month : Month_Number) return String is + begin + case Month is + when 1 => return "January"; + when 2 => return "February"; + when 3 => return "March"; + when 4 => return "April"; + when 5 => return "May"; + when 6 => return "June"; + when 7 => return "July"; + when 8 => return "August"; + when 9 => return "September"; + when 10 => return "October"; + when 11 => return "November"; + when 12 => return "December"; + end case; + end Image; + function Image (Day : Day_Name) return String is + begin + case Day is + when Monday => return "Monday"; + when Tuesday => return "Tuesday"; + when Wednesday => return "Wednesday"; + when Thursday => return "Thursday"; + when Friday => return "Friday"; + when Saturday => return "Saturday"; + when Sunday => return "Sunday"; + end case; + end Image; + Today : Time := Clock; +begin + Put_Line (Image (Today) (1..10)); + Put_Line + ( Image (Day_Of_Week (Today)) & ", " + & Image (Ada.Calendar.Month (Today)) + & Day_Number'Image (Ada.Calendar.Day (Today)) & "," + & Year_Number'Image (Ada.Calendar.Year (Today)) + ); +end Date_Format; diff --git a/Task/Date-format/AutoIt/date-format.au3 b/Task/Date-format/AutoIt/date-format.au3 new file mode 100644 index 0000000000..7f83e3d9d9 --- /dev/null +++ b/Task/Date-format/AutoIt/date-format.au3 @@ -0,0 +1,31 @@ +#include + +$iYear = 2007 +$iMonth = 11 +$iDay = 10 + +ConsoleWrite(StringFormat('%4d-%02d-%02d', $iYear, $iMonth, $iDay) & @LF) + +$iWeekDay = _DateToDayOfWeekISO($iYear, $iMonth, $iDay) +ConsoleWrite(StringFormat('%s, %s %02d, %4d', _GetLongDayLocale($iWeekDay), _GetLongMonthLocale($iMonth), $iDay, $iYear) & @LF) + + +Func _GetLongDayLocale($_iWeekDay) ; 1..7 Monday=1 + Local $aDayName[8] = [0, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30] + Return GetLocaleInfo($aDayName[$_iWeekDay]) +EndFunc + +Func _GetLongMonthLocale($_iMonth) ; 1..12 January=1 + Local $aMonthName[13] = [0, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43] + Return GetLocaleInfo($aMonthName[$_iMonth]) +EndFunc + +Func GetLocaleInfo($_LCType) + Local $ret, $LCID, $sBuffer, $iLen + $ret = DllCall('kernel32', 'long', 'GetSystemDefaultLCID') + $LCID = $ret[0] + $ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', 0) + $iLen = $ret[0] + $ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', $iLen) + Return $ret[3] +EndFunc diff --git a/Task/Date-format/COBOL/date-format.cob b/Task/Date-format/COBOL/date-format.cob new file mode 100644 index 0000000000..76c554f613 --- /dev/null +++ b/Task/Date-format/COBOL/date-format.cob @@ -0,0 +1,64 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Date-Format. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 Days-Area. + 03 Days-Data. + 05 FILLER PIC X(9) VALUE "Monday". + 05 FILLER PIC X(9) VALUE "Tuesday". + 05 FILLER PIC X(9) VALUE "Wednesday". + 05 FILLER PIC X(9) VALUE "Thursday". + 05 FILLER PIC X(9) VALUE "Friday". + 05 FILLER PIC X(9) VALUE "Saturday". + 05 FILLER PIC X(9) VALUE "Sunday". + + 03 Days-Values REDEFINES Days-Data. + 05 Days-Table PIC X(9) OCCURS 7 TIMES. + + 01 Months-Area. + 03 Months-Data. + 05 FILLER PIC X(9) VALUE "January". + 05 FILLER PIC X(9) VALUE "February". + 05 FILLER PIC X(9) VALUE "March". + 05 FILLER PIC X(9) VALUE "April". + 05 FILLER PIC X(9) VALUE "May". + 05 FILLER PIC X(9) VALUE "June". + 05 FILLER PIC X(9) VALUE "July". + 05 FILLER PIC X(9) VALUE "August". + 05 FILLER PIC X(9) VALUE "September". + 05 FILLER PIC X(9) VALUE "October". + 05 FILLER PIC X(9) VALUE "November". + 05 FILLER PIC X(9) VALUE "December". + + 03 Months-Values REDEFINES Months-Data. + 05 Months-Table PIC X(9) OCCURS 12 TIMES. + + 01 Current-Date-Str. + 03 Current-Year PIC X(4). + 03 Current-Month PIC X(2). + 03 Current-Day PIC X(2). + + 01 Current-Day-Of-Week PIC 9. + + PROCEDURE DIVISION. + MOVE FUNCTION CURRENT-DATE (1:8) TO Current-Date-Str + + DISPLAY Current-Year "-" Current-Month "-" Current-Day + + ACCEPT Current-Day-Of-Week FROM DAY-OF-WEEK + DISPLAY + FUNCTION TRIM( + Days-Table (FUNCTION NUMVAL(Current-Day-Of-Week))) + ", " + FUNCTION TRIM( + Months-Table (FUNCTION NUMVAL(Current-Month))) + " " + Current-Day + ", " + Current-Year + END-DISPLAY + + GOBACK + . diff --git a/Task/Date-format/Emacs-Lisp/date-format.el b/Task/Date-format/Emacs-Lisp/date-format.el new file mode 100644 index 0000000000..a07b29dd9f --- /dev/null +++ b/Task/Date-format/Emacs-Lisp/date-format.el @@ -0,0 +1,6 @@ +(format-time-string "%Y-%m-%d") +(format-time-string "%F") ;; new in Emacs 24 +;; => "2015-11-08" + +(format-time-string "%A, %B %e, %Y") +;; => "Sunday, November 8, 2015" diff --git a/Task/Date-format/Euphoria/date-format.eu b/Task/Date-format/Euphoria/date-format.eu new file mode 100644 index 0000000000..9c1c8fb8d7 --- /dev/null +++ b/Task/Date-format/Euphoria/date-format.eu @@ -0,0 +1,11 @@ +constant days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"} +constant months = {"January","February","March","April","May","June", + "July","August","September","October","November","December"} + +sequence now + +now = date() +now[1] += 1900 + +printf(1,"%d-%02d-%02d\n",now[1..3]) +printf(1,"%s, %s %d, %d\n",{days[now[7]],months[now[2]],now[3],now[1]}) diff --git a/Task/Date-format/Gleam/date-format.gleam b/Task/Date-format/Gleam/date-format.gleam new file mode 100644 index 0000000000..93e508637b --- /dev/null +++ b/Task/Date-format/Gleam/date-format.gleam @@ -0,0 +1,10 @@ +import birl as date +import dateformat +import gleam/io + +pub fn main() { + let now = date.now() + now |> date.to_naive_date_string |> io.println + let assert Ok(s) = dateformat.format("dddd, MMMM D, YYYY", now) + io.println(s) +} diff --git a/Task/Date-format/M2000-Interpreter/date-format.m2000 b/Task/Date-format/M2000-Interpreter/date-format.m2000 index 25e0430297..67e153d36c 100644 --- a/Task/Date-format/M2000-Interpreter/date-format.m2000 +++ b/Task/Date-format/M2000-Interpreter/date-format.m2000 @@ -1,2 +1,9 @@ -Print str$(today, "yyyy-mm-dd") -Print str$(today, "dddd, mmm, dd, yyyy") +open "output.txt" for wide output as # +Print #f, date$(today,1033) +Print #f, date$(today, 1033,"Long Date") + +Print #f, date$(today,1048) +Print #f, date$(today, 1048,"Long Date") +close #f +Print #-2, eval$(buffer(dir$+"output.txt")) +win dir$+"output.txt" ' or Win "notepad", dir$+"output.txt" diff --git a/Task/Date-format/Odin/date-format.odin b/Task/Date-format/Odin/date-format.odin new file mode 100644 index 0000000000..099d825537 --- /dev/null +++ b/Task/Date-format/Odin/date-format.odin @@ -0,0 +1,14 @@ +package main + +import "core:fmt" +import "core:time" + +main :: proc() { + now := time.now() + year, month, day := time.date(now) + + weekday := time.weekday(now) + + fmt.printfln("%d-%2d-%2d", year, month, day) + fmt.printfln("%s, %s %2d, %d", weekday, month, day, year) +} diff --git a/Task/Date-format/Pluto/date-format.pluto b/Task/Date-format/Pluto/date-format.pluto new file mode 100644 index 0000000000..6f058b48a3 --- /dev/null +++ b/Task/Date-format/Pluto/date-format.pluto @@ -0,0 +1,2 @@ +print(os.date("%F")) +print(os.date("%A, %B %e, %Y")) diff --git a/Task/Date-format/PowerShell/date-format.ps1 b/Task/Date-format/PowerShell/date-format.ps1 new file mode 100644 index 0000000000..ac0f1483db --- /dev/null +++ b/Task/Date-format/PowerShell/date-format.ps1 @@ -0,0 +1,5 @@ +"{0:yyyy-MM-dd}" -f (Get-Date) +"{0:dddd, MMMM d, yyyy}" -f (Get-Date) +# or +(Get-Date).ToString("yyyy-MM-dd") +(Get-Date).ToString("dddd, MMMM d, yyyy") diff --git a/Task/Date-format/REXX/date-format.rexx b/Task/Date-format/REXX/date-format.rexx new file mode 100644 index 0000000000..cc6d2abbdf --- /dev/null +++ b/Task/Date-format/REXX/date-format.rexx @@ -0,0 +1,36 @@ +-- 24 Sep 2025 +include Setting +numeric digits 20 + +say 'DATE FORMAT' +say version +say +say 'Below examples may be coded with full option or only first letter.' +say 'Both uppercase and lowercase are accepted.' +say 'Not shown here, but the Date() function also supports conversions.' +say +w=18 +say 'Date function...' +say 'Default ' Left(Date(),w) 'same as Normal' +say 'Base ' Left(Date('B'),w) 'days since Jan 1, 0001' +say 'Days ' Left(Date('D'),w) 'days since Jan 1, this year' +say 'European ' Left(Date('E'),w) 'dd/mm/yy' +if Pos('ooRexx',version) > 0 then + say 'Full ' Left(Date('F'),w) 'microsecs since Jan 1, 0001, 00:00:00 (ooRexx)' +say 'ISO ' Left(Date('I'),w) 'yyyy-mm-dd' +if Pos('ooRexx',version) > 0 then + say 'Language ' Left(Date('L'),w) 'dd month yyyy (ooRexx NL)' +say 'Month ' Left(Date('M'),w) 'Month name' +say 'Normal ' Left(Date('N'),w) 'dd Mmm yyyy' +say 'Ordered ' Left(Date('O'),w) 'yy/mm/dd' +say 'Standard ' Left(Date('S'),w) 'yyyymmdd' +say 'Ticks ' Left(Date('T'),w) 'seconds since Jan 1, 1970, 00:00:00' +say 'USA ' Left(Date('U'),w) 'mm/dd/yy' +say 'Weekday ' Left(Date('W'),w) 'Day of week' +say +say 'Task...' +say Date('I') +say Date('W')',' Date('M') Right(Date('S'),2)/1',' Left(Date('S'),4) +exit + +include Abend diff --git a/Task/Date-format/Rebol/date-format-1.rebol b/Task/Date-format/Rebol/date-format-1.rebol new file mode 100644 index 0000000000..5e950355d9 --- /dev/null +++ b/Task/Date-format/Rebol/date-format-1.rebol @@ -0,0 +1,23 @@ +REBOL [ + Title: "Date Formatting" + URL: http://rosettacode.org/wiki/Date_format +] + +; REBOL has no built-in pictured output. + +zeropad: func [pad n][ + n: to-string n + insert/dup n "0" (pad - length? n) + n +] +d02: func [n][zeropad 2 n] + +print now ; Native formatting. + +print rejoin [now/year "-" d02 now/month "-" d02 now/day] + +print rejoin [ + pick system/locale/days now/weekday ", " + pick system/locale/months now/month " " + now/day ", " now/year +] diff --git a/Task/Date-format/Rebol/date-format-2.rebol b/Task/Date-format/Rebol/date-format-2.rebol new file mode 100644 index 0000000000..93bee55d69 --- /dev/null +++ b/Task/Date-format/Rebol/date-format-2.rebol @@ -0,0 +1 @@ +print format-date-time now "dddd, mmmm d, yyyy" diff --git a/Task/Date-format/Rye/date-format.rye b/Task/Date-format/Rye/date-format.rye new file mode 100644 index 0000000000..ea4727d74f --- /dev/null +++ b/Task/Date-format/Rye/date-format.rye @@ -0,0 +1,2 @@ +now |format-date "Monday, January 2, 2006" +now |format-date "2006-1-2" diff --git a/Task/Date-format/VBScript/date-format.vbs b/Task/Date-format/VBScript/date-format.vbs new file mode 100644 index 0000000000..039fb4d00a --- /dev/null +++ b/Task/Date-format/VBScript/date-format.vbs @@ -0,0 +1,5 @@ +'YYYY-MM-DD format +WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2) + +'Weekday_Name, Month_Name DD, YYYY format +WScript.StdOut.WriteLine FormatDateTime(Now,1) diff --git a/Task/Date-manipulation/Ada/date-manipulation.adb b/Task/Date-manipulation/Ada/date-manipulation.adb new file mode 100644 index 0000000000..d2e3e6ecc3 --- /dev/null +++ b/Task/Date-manipulation/Ada/date-manipulation.adb @@ -0,0 +1,97 @@ +with Ada.Calendar; +with Ada.Calendar.Formatting; +with Ada.Calendar.Time_Zones; +with Ada.Integer_Text_IO; +with Ada.Text_IO; + +procedure Date_Manipulation is + + type Month_Name_T is + (January, February, March, April, May, June, + July, August, September, October, November, December); + + type Time_Zone_Name_T is (EST, Lisbon); + + type Period_T is (AM, PM); + + package TZ renames Ada.Calendar.Time_Zones; + use type TZ.Time_Offset; + + Time_Zone_Offset : array (Time_Zone_Name_T) of TZ.Time_Offset := + (EST => -5 * 60, + Lisbon => 0); + + Period_Offset : array (Period_T) of Natural := + (AM => 0, + PM => 12); + + package Month_Name_IO is + new Ada.Text_IO.Enumeration_IO (Month_Name_T); + + package Time_Zone_Name_IO is + new Ada.Text_IO.Enumeration_IO (Time_Zone_Name_T); + + package Period_IO is + new Ada.Text_IO.Enumeration_IO (Period_T); + + package Std renames Ada.Calendar; + use type Std.Time; + + package Fmt renames Std.Formatting; + + function To_Number (Name : Month_Name_T) return Std.Month_Number is + begin + return Std.Month_Number (Month_Name_T'Pos (Name) + 1); + end; + + function To_Time (S : String) return Std.Time is + Month : Month_Name_T; + Day : Std.Day_Number; + Year : Std.Year_Number; + Hour : Fmt.Hour_Number; + Minute : Fmt.Minute_Number; + Period : Period_T; + Time_Zone : Time_Zone_Name_T; + I : Natural; + begin + Month_Name_IO.Get + (From => S, Item => Month, Last => I); + Ada.Integer_Text_IO.Get + (From => S (I + 1 .. S'Last), Item => Day, Last => I); + Ada.Integer_Text_IO.Get + (From => S (I + 1 .. S'Last), Item => Year, Last => I); + Ada.Integer_Text_IO.Get + (From => S (I + 1 .. S'Last), Item => Hour, Last => I); + Ada.Integer_Text_IO.Get + (From => S (I + 2 .. S'Last), Item => Minute, Last => I); + -- here we start 2 chars down to skip the ':' + Period_IO.Get + (From => S (I + 1 .. S'Last), Item => Period, Last => I); + Time_Zone_Name_IO.Get + (From => S (I + 1 .. S'Last), Item => Time_Zone, Last => I); + return Fmt.Time_Of + (Year => Year, + Month => To_Number (Month), + Day => Day, + Hour => Hour + Period_Offset (Period), + Minute => Minute, + Second => 0, + Time_Zone => Time_Zone_Offset (Time_Zone)); + end; + + function Img + (Date : Std.Time; Zone : Time_Zone_Name_T) return String is + begin + return + Fmt.Image (Date => Date, Time_Zone => Time_Zone_Offset (Zone)) & + " " & Time_Zone_Name_T'Image (Zone); + end; + + T1, T2 : Std.Time; + use Ada.Text_IO; +begin + T1 := To_Time ("March 7 2009 7:30pm EST"); + T2 := T1 + 12.0 * 60.0 * 60.0; + Put_Line ("T1 => " & Img (T1, EST) & " = " & Img (T1, Lisbon)); + Put_Line ("T2 => " & Img (T2, EST) & " = " & Img (T2, Lisbon)); +end; diff --git a/Task/Date-manipulation/COBOL/date-manipulation.cob b/Task/Date-manipulation/COBOL/date-manipulation.cob new file mode 100644 index 0000000000..372e4c8594 --- /dev/null +++ b/Task/Date-manipulation/COBOL/date-manipulation.cob @@ -0,0 +1,121 @@ + identification division. + program-id. date-manipulation. + + environment division. + configuration section. + repository. + function all intrinsic. + + data division. + working-storage section. + 01 given-date. + 05 filler value z"March 7 2009 7:30pm EST". + 01 date-spec. + 05 filler value z"%B %d %Y %I:%M%p %Z". + + 01 time-struct. + 05 tm-sec usage binary-long. + 05 tm-min usage binary-long. + 05 tm-hour usage binary-long. + 05 tm-mday usage binary-long. + 05 tm-mon usage binary-long. + 05 tm-year usage binary-long. + 05 tm-wday usage binary-long. + 05 tm-yday usage binary-long. + 05 tm-isdst usage binary-long. + 05 tm-gmtoff usage binary-c-long. + 05 tm-zone usage pointer. + 01 scan-index usage pointer. + + 01 time-t usage binary-c-long. + 01 time-tm usage pointer. + + 01 reform-buffer pic x(64). + 01 reform-length usage binary-long. + + 01 current-locale usage pointer. + + 01 iso-spec constant as "YYYY-MM-DDThh:mm:ss+hh:mm". + 01 iso-date constant as "2009-03-07T19:30:00-05:00". + 01 date-integer pic 9(9). + 01 time-integer pic 9(9). + + procedure division. + + call "strptime" using + by reference given-date + by reference date-spec + by reference time-struct + returning scan-index + on exception + display "error calling strptime" upon syserr + end-call + display "Given: " given-date + + if scan-index not equal null then + *> add 12 hours, and reform as local + call "mktime" using time-struct returning time-t + add 43200 to time-t + perform form-datetime + + *> reformat as Pacific time + set environment "TZ" to "PST8PDT" + call "tzset" returning omitted + perform form-datetime + + *> reformat as Greenwich mean + set environment "TZ" to "GMT" + call "tzset" returning omitted + perform form-datetime + + + *> reformat for Tokyo time, as seen in Hong Kong + set environment "TZ" to "Japan" + call "tzset" returning omitted + call "setlocale" using by value 6 by content z"en_HK.utf8" + returning current-locale + on exception + display "error with setlocale" upon syserr + end-call + move z"%c" to date-spec + perform form-datetime + else + display "date parse error" upon syserr + end-if + + *> A more standard COBOL approach, based on ISO8601 + display "Given: " iso-date + move integer-of-formatted-date(iso-spec, iso-date) + to date-integer + + move seconds-from-formatted-time(iso-spec, iso-date) + to time-integer + + add 43200 to time-integer + if time-integer greater than 86400 then + subtract 86400 from time-integer + add 1 to date-integer + end-if + display " " substitute(formatted-datetime(iso-spec + date-integer, time-integer, -300), "T", "/") + + goback. + + form-datetime. + call "localtime" using time-t returning time-tm + call "strftime" using + by reference reform-buffer + by value length(reform-buffer) + by reference date-spec + by value time-tm + returning reform-length + on exception + display "error calling strftime" upon syserr + end-call + if reform-length > 0 and <= length(reform-buffer) then + display " " reform-buffer(1 : reform-length) + else + display "date format error" upon syserr + end-if + . + end program date-manipulation. diff --git a/Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.el b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.el new file mode 100644 index 0000000000..ead4f0f34d --- /dev/null +++ b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-1.el @@ -0,0 +1,40 @@ +(defun fix-time-string (calendar-string) + "If CALENDAR-STRING has no space between time and am/a.m./pm/p.m., add a space. + Return string with space between time and am/a.m./pm/p.m." + (replace-regexp-in-string "\\([[:digit:]]\\)\\([ap]\\)" "\\1 \\2" calendar-string)) + +(defun is-pm (calendar-string) + "Test if CALENDAR-STRING has PM/pm/P.M/p.m in it." + (string-match-p "[Pp][.]?[Mm]" calendar-string)) + +(defun is-hour-1-to-11 (a-calendar-list) + "Test if hour in A-CALENDAR-LIST is between 1 and 11." + (let ((hour-value)) + (setq hour-value (nth 2 a-calendar-list)) + (and (>= hour-value 1) (<= hour-value 11)))) + +(defun adjust-if-pm (time-as-string) + "If TIME-AS-STRING includes pm/PM, and hour is 1 to 11, add 12 hours. + Return CALENDAR-LIST modified if date is pm and hour is 1-11; otherwise + return CALENDAR-LIST of original TIME-AS-STRING." + (let ((calendar-list)) + (setq calendar-list (parse-time-string time-as-string)) + (if (and (is-pm time-as-string) (is-hour-1-to-11 calendar-list)) + (decoded-time-add calendar-list (make-decoded-time :hour 12)) + calendar-list))) + +(defun add-hours (calendar-list number-of-hours) + "Add NUMBER-OF-HOURS to CALENDAR-LIST." + (decoded-time-add calendar-list (make-decoded-time :hour number-of-hours))) + +(defun calc-future-time (string-calendar-date number-of-hours-in-future) + "Calculate future time by adding NUMBER-OF-HOURS-IN-FUTURE to STRING-CALENDAR-DATE ." + (let ((fixed-calendar-string) + (24-hour-calendar-list) + (calendar-list-future-time) + (coded-future-time)) + (setq fixed-calendar-string (fix-time-string string-calendar-date)) + (setq 24-hour-calendar-list (adjust-if-pm fixed-calendar-string)) + (setq calendar-list-future-time (add-hours 24-hour-calendar-list number-of-hours-in-future)) + (setq coded-future-time (encode-time calendar-list-future-time)) + (format-time-string "%B %e %Y %R %p %Z" coded-future-time))) diff --git a/Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.el b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.el new file mode 100644 index 0000000000..5ebd017876 --- /dev/null +++ b/Task/Date-manipulation/Emacs-Lisp/date-manipulation-2.el @@ -0,0 +1,41 @@ +(defun fix-time-string (calendar-string) + "If CALENDAR-STRING has no space between time and a.m./p.m., add a space." + (replace-regexp-in-string "\\([[:digit:]]\\)\\([ap]\\)" "\\1 \\2" calendar-string)) + +(defun is-pm (calendar-string) + "Test if CALENDAR-STRING has PM/pm in it." + (string-match-p "[Pp][Mm]" time-as-string)) + +(defun is-hour-1-to-11 (a-calendar-list) + "Test if hour in A-CALENDAR-LIST is between 1 and 11." + (let ((hour-value)) + (setq hour-value (nth 2 a-calendar-list)) + (and (>= hour-value 1) (<= hour-value 11)))) + +(defun adjust-if-pm (time-as-string) + "If TIME-AS-STRING includes pm/PM, and hour is 1 to 11, add 12 hours. + Return time as integer of seconds past the epoch." + (let ((calendar-list) + (temp-time-stamp) + (time-stamp-as-integer)) + (setq calendar-list (parse-time-string time-as-string)) + (setq temp-time-stamp (encode-time calendar-list)) + (setq time-stamp-as-integer (time-convert temp-time-stamp 'integer)) + (if (and (is-pm time-as-string) (is-hour-1-to-11 calendar-list)) + (+ time-stamp-as-integer (* 12 60 60)) ; return time + 12 hours, so that hour is 13-23 + time-stamp-as-integer))) ; return time unchanged, leaving hour 0-12 + +(defun add-seconds (start-time-stamp-integer number-of-seconds) + "Add NUMBER-OF-HOURS to START-TIME-STAMP-INTEGER." + (+ start-time-stamp-integer number-of-seconds)) + +(defun calc-future-time (string-calendar-date number-of-seconds-in-future) + "Calculate future time by adding NUMBER-OF-SECONDS-IN-FUTURE to STRING-CALENDAR-DATE ." + (let ((fixed-calendar-string) + (time-stamp-as-integer) + (coded-current-time) + (future-time-as-integer)) + (setq fixed-calendar-string (fix-time-string string-calendar-date)) + (setq time-stamp-as-integer (adjust-if-pm fixed-calendar-string)) + (setq future-time-as-integer (add-seconds time-stamp-as-integer number-of-seconds-in-future)) + (format-time-string "%B %e %Y %R %p %Z" future-time-as-integer))) diff --git a/Task/Date-manipulation/Euphoria/date-manipulation.eu b/Task/Date-manipulation/Euphoria/date-manipulation.eu new file mode 100644 index 0000000000..9a07fcc4c3 --- /dev/null +++ b/Task/Date-manipulation/Euphoria/date-manipulation.eu @@ -0,0 +1,10 @@ +--Date Manipulation task from Rosetta Code wiki +--User:Lnettnay + +include std/datetime.e + +datetime dt + +dt = new(2009, 3, 7, 19, 30) +dt = add(dt, 12, HOURS) +printf(1, "%s EST\n", {format(dt, "%B %d %Y %I:%M %p")}) diff --git a/Task/Date-manipulation/Pluto/date-manipulation.pluto b/Task/Date-manipulation/Pluto/date-manipulation.pluto new file mode 100644 index 0000000000..538d6d4061 --- /dev/null +++ b/Task/Date-manipulation/Pluto/date-manipulation.pluto @@ -0,0 +1,34 @@ +local function format_date(y, mo, d, h, mi, tz) + local f = "%B %d %Y %I:%M%p " .. tz + local tm = os.time({year = y, month = mo, day = d, hour = h, min = mi}) + return os.date(f, tm):replace(" 0", " "):replace("AM", "am"):replace("PM", "pm") +end + +local months = { + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" +} + +local date = "March 7 2009 7:30pm EST" +print($"Original date/time : {date}") + +local fields = date:split(" ") +local fields2 = fields[4]:split(":") + +local mo = months:findindex(|m| -> fields[1] == m , 1, true) +local d = tonumber(fields[2]) +local y = tonumber(fields[3]) +local h = tonumber(fields2[1]) +local mi = tonumber(fields2[2]:sub(1, 2)) +local ap = fields2[2]:sub(3, 4) +local tz = fields[5] +if ap == "pm" then h += 12 end +if h == 12 or h == 24 then h -= 12 end + +-- Time and date 12 hours later +local date2 = format_date(y, mo, d, h + 12, mi, tz) +print($"12 hours later : {date2}") + +-- Switch to MST time zone which is 2 hours earlier than EST. +local date3 = format_date(y, mo, d, h + 10, mi, "MST") +print($"Adjusted to MST : {date3}") diff --git a/Task/Date-manipulation/PowerShell/date-manipulation.ps1 b/Task/Date-manipulation/PowerShell/date-manipulation.ps1 new file mode 100644 index 0000000000..8c626e26c3 --- /dev/null +++ b/Task/Date-manipulation/PowerShell/date-manipulation.ps1 @@ -0,0 +1,4 @@ +$date = [DateTime]::Parse("March 7 2009 7:30pm -5" ) +write-host $date +write-host $date.AddHours(12) +write-host [TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($date.AddHours(12),"Vladivostok Standard Time") diff --git a/Task/Date-manipulation/Rebol/date-manipulation-1.rebol b/Task/Date-manipulation/Rebol/date-manipulation-1.rebol new file mode 100644 index 0000000000..02dfe80f1b --- /dev/null +++ b/Task/Date-manipulation/Rebol/date-manipulation-1.rebol @@ -0,0 +1,24 @@ +Rebol [ + Title: "Date Manipulation" + URL: http://rosettacode.org/wiki/Date_Manipulation +] + +; Only North American zones here -- feel free to extend for your area. + +zones: [ + NST -3:30 NDT -2:30 AST -4:00 ADT -3:00 EST -5:00 EDT -4:00 + CST -6:00 CDT -5:00 MST -7:00 MDT -6:00 PST -8:00 PDT -7:00 + AKST -9:00 AKDT -8:00 HAST -10:00 HADT -9:00] + +read-time: func [ + text + /local m d y t z +][ + parse load text [ + set m word! (m: index? find system/locale/months to-string m) + set d integer! set y integer! + set t time! set tz word!] + to-date reduce [y m d t zones/:tz] +] + +print 12:00 + read-time "March 7 2009 7:30pm EST" diff --git a/Task/Date-manipulation/Rebol/date-manipulation-2.rebol b/Task/Date-manipulation/Rebol/date-manipulation-2.rebol new file mode 100644 index 0000000000..f3f80546e9 --- /dev/null +++ b/Task/Date-manipulation/Rebol/date-manipulation-2.rebol @@ -0,0 +1,43 @@ +put system/catalog 'time-zones make map! [ + NST -3:30 NDT -2:30 AST -4:00 ADT -3:00 EST -5:00 EDT -4:00 + CST -6:00 CDT -5:00 MST -7:00 MDT -6:00 PST -8:00 PDT -7:00 + AKST -9:00 AKDT -8:00 HAST -10:00 HADT -9:00 +] +to-date: function/with [ + "Converts to date! value." + value [any-type!] "May be also a standard Internet date string/binary" + /utc "Returns the date with UTC zone" +][ + if all [ + any [string? value binary? value] + parse value [ + 5 skip + copy day: 1 2 numeric sp + copy month: 3 alpha sp + copy year: 1 4 numeric sp + copy time: to sp sp + [copy zone: [plus-minus 4 numeric] | no-case "GMT" (zone: "+0")] + to end ; ignore the rest (like comments in mime fields)! + | + copy day: 1 2 numeric #"-" + copy month: 1 2 numeric #"-" + copy year: 1 4 numeric sp + copy time: [1 2 numeric #":" 1 2 numeric opt [#":" 1 2 numeric]] + to end + | + copy month: some alpha sp + copy day: 1 2 numeric sp + copy year: 1 4 numeric sp + copy time: [1 2 numeric #":" 1 2 numeric opt [#":" 1 2 numeric]] + opt ["pm" (time: 12:00 + to time! time) | "am"] sp + copy zone: 3 4 alpha (zone: select system/catalog/time-zones to word! zone) + ] + ][ + value: to string! rejoin [day "-" month "-" year "/" time any [zone ""]] + ] + if all [value: to date! value utc] [ value/timezone: 0 ] + value +] system/catalog/bitsets + +probe 12:00 + to-date "March 7 2009 7:30pm EST" +probe 12:00 + to-date "Sat, 7 Mar 2009 19:30:00 -0500" diff --git a/Task/Date-manipulation/Rye/date-manipulation.rye b/Task/Date-manipulation/Rye/date-manipulation.rye new file mode 100644 index 0000000000..a35304ac82 --- /dev/null +++ b/Task/Date-manipulation/Rye/date-manipulation.rye @@ -0,0 +1,4 @@ +t: datetime "2009-03-07T07:30:00" + ; returns [Time: 2009-03-07 07:30:00] +t + 12 .hours + ; returns [Time: 2009-03-07 19:30:00] diff --git a/Task/Day-of-the-week/Ada/day-of-the-week.adb b/Task/Day-of-the-week/Ada/day-of-the-week.adb new file mode 100644 index 0000000000..968e671457 --- /dev/null +++ b/Task/Day-of-the-week/Ada/day-of-the-week.adb @@ -0,0 +1,11 @@ +with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Yuletide is +begin + for Year in 2008..2121 loop + if Day_Of_Week (Time_Of (Year, 12, 25)) = Sunday then + Put_Line (Image (Time_Of (Year, 12, 25))); + end if; + end loop; +end Yuletide; diff --git a/Task/Day-of-the-week/Agena/day-of-the-week.agena b/Task/Day-of-the-week/Agena/day-of-the-week.agena new file mode 100644 index 0000000000..e1ea7151d2 --- /dev/null +++ b/Task/Day-of-the-week/Agena/day-of-the-week.agena @@ -0,0 +1,19 @@ +# Day of the week +proc dayofweek(y, m, d) is + # Sunday = 0, Saturday = 6 + if m < 3 then + y -:= 1; + m +:= 12 + fi; + z := y + (y \ 4) - (y \ 100) + (y \ 400); + return (z + d + (153 * m + 8) \ 5) symmod 7 +end; + +scope + for y from 2007 to 2122 do + if dayofweek(y, 12, 25) = 0 then + printf("%d ", y) + fi + od + print() +epocs diff --git a/Task/Day-of-the-week/AutoIt/day-of-the-week.au3 b/Task/Day-of-the-week/AutoIt/day-of-the-week.au3 new file mode 100644 index 0000000000..5e6f5eaf10 --- /dev/null +++ b/Task/Day-of-the-week/AutoIt/day-of-the-week.au3 @@ -0,0 +1,7 @@ +#include +Const $iSunday = 1 +For $iYear = 2008 To 2121 Step 1 + If $iSunday = _DateToDayOfWeek($iYear, 12, 25) Then + ConsoleWrite(StringFormat($iYear & "\n")) + EndIf +Next diff --git a/Task/Day-of-the-week/COBOL/day-of-the-week-1.cob b/Task/Day-of-the-week/COBOL/day-of-the-week-1.cob new file mode 100644 index 0000000000..079336abaf --- /dev/null +++ b/Task/Day-of-the-week/COBOL/day-of-the-week-1.cob @@ -0,0 +1,22 @@ + program-id. dec25. + data division. + working-storage section. + 1 work-date. + 2 yr pic 9(4) value 2008. + 2 mo-da pic 9(4) value 1225. *> Dec 25 + 1 wk-date redefines work-date pic 9(8). + 1 binary. + 2 int-date pic 9(8). + 2 dow pic 9(4). + procedure division. + perform varying yr from 2008 by 1 + until yr > 2121 + compute int-date = function integer-of-date (wk-date) + compute dow = function mod ((int-date - 1) 7) + 1 + if dow = 7 *> Sunday = 7 per ISO 8601 and ISO 1989 + display yr + end-if + end-perform + stop run + . + end program dec25. diff --git a/Task/Day-of-the-week/COBOL/day-of-the-week-2.cob b/Task/Day-of-the-week/COBOL/day-of-the-week-2.cob new file mode 100644 index 0000000000..b02dc59752 --- /dev/null +++ b/Task/Day-of-the-week/COBOL/day-of-the-week-2.cob @@ -0,0 +1,68 @@ + identification division. + program-id. dowtest. + data division. + working-storage section. + 01 ws-inp-date pic x(08). + 01 filler redefines ws-inp-date. + 03 ws-inp-year pic 9(04). + 01 ws-dow pic 9(05). + procedure division. + move '00001225' to ws-inp-date + perform test before + varying ws-inp-year from 2008 by +1 + until ws-inp-year > 2121 + call "todow" using + by reference ws-inp-date + by reference ws-dow + if ws-dow = 1 then + display 'year=' ws-inp-year + end-if + end-perform + stop run. + + end program dowtest. + + identification division. + program-id. todow. + environment division. + input-output section. + file-control. + data division. + file section. + working-storage section. + 01 tally pic 9(05). + 01 wms-work-area. + 03 wms-year pic 9(04). + 03 wms-month pic 9(02). + 03 wms-csys pic 9(01) value 1. + 03 wms-sum pic 9(05). + linkage section. + 01 lkip-date. + 03 lkip-date-year pic 9(04). + 03 lkip-date-month pic 9(02). + 03 lkip-date-day pic 9(02). + 01 lkop-dow pic 9(05). + 88 lkop-sunday value 1. + procedure division using + by reference lkip-date + by reference lkop-dow + . + + if lkip-date-month < 3 + compute wms-month = lkip-date-month + 12 + compute wms-year = lkip-date-year - 1 + else + compute wms-month = lkip-date-month + compute wms-year = lkip-date-year + end-if + + compute wms-sum = + ( lkip-date-day + 2 * wms-month + wms-year + + function integer (6 * (wms-month + 1) / 10) + + function integer ( wms-year / 4 ) + - function integer ( wms-year / 100 ) + + function integer ( wms-year / 400 ) + + wms-csys ) + compute lkop-dow = function mod (wms-sum, 7) + 1 + . + end program todow. diff --git a/Task/Day-of-the-week/Crystal/day-of-the-week.cr b/Task/Day-of-the-week/Crystal/day-of-the-week.cr new file mode 100644 index 0000000000..4daab98fc0 --- /dev/null +++ b/Task/Day-of-the-week/Crystal/day-of-the-week.cr @@ -0,0 +1 @@ +p (2008..2121).select { |year| Time.utc(year, 12, 25).sunday? } diff --git a/Task/Day-of-the-week/Emacs-Lisp/day-of-the-week.el b/Task/Day-of-the-week/Emacs-Lisp/day-of-the-week.el new file mode 100644 index 0000000000..84e03a382f --- /dev/null +++ b/Task/Day-of-the-week/Emacs-Lisp/day-of-the-week.el @@ -0,0 +1,11 @@ +(require 'calendar) + +(defun sunday-p (y) + "Is Dec 25th a Sunday in this year?" + (= (calendar-day-of-week (list 12 25 y)) 0)) + +(defun xmas-sunday (a b) + "In which years in the range a, b is Dec 25th a Sunday?" + (seq-filter #'sunday-p (number-sequence a b))) + +(print (xmas-sunday 2008 2121)) diff --git a/Task/Day-of-the-week/Euphoria/day-of-the-week.eu b/Task/Day-of-the-week/Euphoria/day-of-the-week.eu new file mode 100644 index 0000000000..8175e51836 --- /dev/null +++ b/Task/Day-of-the-week/Euphoria/day-of-the-week.eu @@ -0,0 +1,15 @@ +--Day of the week task from Rosetta Code wiki +--User:Lnettnay + +--In what years between 2008 and 2121 will the 25th of December be a Sunday + +include std/datetime.e + +datetime dt + +for year = 2008 to 2121 do + dt = new(year, 12, 25) + if weeks_day(dt) = 1 then -- Sunday = 1 + ? year + end if +end for diff --git a/Task/Day-of-the-week/Loglan82/day-of-the-week.loglan82 b/Task/Day-of-the-week/Loglan82/day-of-the-week.loglan82 new file mode 100644 index 0000000000..35196c62f8 --- /dev/null +++ b/Task/Day-of-the-week/Loglan82/day-of-the-week.loglan82 @@ -0,0 +1,24 @@ +(* Day of the week *) + +block +var + y: integer; + + unit day_of_week: function (y, m, d: integer): integer; + begin + (* Sunday = 0, Saturday = 6 *) + if m < 3 + then + y := y - 1; + m := m + 12 + fi; + result := (y + y div 4 - y div 100 + y div 400 + d + (153 * m + 8) div 5) mod 7; + end day_of_week; + +begin + for y := 2007 to 2122 + do + if day_of_week(y, 12, 25) = 0 then write(y: 5) fi + od; + writeln; +end; diff --git a/Task/Day-of-the-week/Modula-2/day-of-the-week.mod2 b/Task/Day-of-the-week/Modula-2/day-of-the-week.mod2 new file mode 100644 index 0000000000..b1307ae0a8 --- /dev/null +++ b/Task/Day-of-the-week/Modula-2/day-of-the-week.mod2 @@ -0,0 +1,32 @@ +MODULE DayOfTheWeek; + +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +VAR + Y: CARDINAL; + +PROCEDURE DayOfWeek(Y, M, D: CARDINAL): CARDINAL; + (* Sunday = 0, Saturday = 6 *) +VAR + Z: CARDINAL; +BEGIN + IF M < 3 THEN + Y := Y - 1; + M := M + 12 + END; + Z := Y + (Y DIV 4) - (Y DIV 100) + (Y DIV 400); + RETURN (Z + D + (153 * M + 8) DIV 5) MOD 7 +END DayOfWeek; + +BEGIN + FOR Y := 2007 TO 2122 DO + IF DayOfWeek(Y, 12, 25) = 0 THEN + WriteInt(Y, 1); + WriteString(" ") + END + END; + WriteLn +END DayOfTheWeek. diff --git a/Task/Day-of-the-week/MoonRock/day-of-the-week.moonrock b/Task/Day-of-the-week/MoonRock/day-of-the-week.moonrock new file mode 100644 index 0000000000..c39fcfe4d2 --- /dev/null +++ b/Task/Day-of-the-week/MoonRock/day-of-the-week.moonrock @@ -0,0 +1,36 @@ +' Day of the week +BEGIN DEF +pointer byte ZPtr~ +SUB CalcDayOfWeek(Y%, M%, D%, ZPtr~) + +BEGIN CODE +FOR Y% = 2007 TO 2122 + CALL CalcDayOfWeek(Y%, 12, 25, VARPTR(Z@)) + IF Z@ = 0 THEN + PRINT Y% + " " + ENDIF +NEXT +PRINT "\n" +END + +SUB CalcDayOfWeek(Y%, M%, D%, ZPtr~) +' Sunday = 0, Saturday = 6 +IF M% < 3 THEN + Y% = Y% - 1 + M% = M% + 12 +ENDIF +Result% = Y% +YDiv% = Y% \ 4 +Result% = Result% + YDiv% +YDiv% = Y% \ 100 +Result% = Result% - YDiv% +YDiv% = Y% \ 400 +Result% = Result% + YDiv% +DPlus% = 153 * M% +DPlus% = DPlus% + 8 +DPlus% = DPlus% \ 5 +Result% = Result% + D% +Result% = Result% + DPlus% +Result% = Result% MOD 7 +[ZPtr~] = Result% +END SUB diff --git a/Task/Day-of-the-week/Pascal-P/day-of-the-week.pas b/Task/Day-of-the-week/Pascal-P/day-of-the-week.pas new file mode 100644 index 0000000000..71e53b6fda --- /dev/null +++ b/Task/Day-of-the-week/Pascal-P/day-of-the-week.pas @@ -0,0 +1,25 @@ +program dayoftheweek(output); + +var + y: integer; + + function dayofweek(y, m, d: integer): integer; + (* Sunday = 0, Saturday = 6 *) + var + z: integer; + begin + if m < 3 then + begin + y := y - 1; + m := m + 12; + end; + z := y + (y div 4) - (y div 100) + (y div 400); + dayofweek := (z + d + (153 * m + 8) div 5) mod 7; + end; + +begin + for y := 2007 to 2122 do + if dayofweek(y, 12, 25) = 0 then + write(y); + writeln +end. diff --git a/Task/Day-of-the-week/Pluto/day-of-the-week.pluto b/Task/Day-of-the-week/Pluto/day-of-the-week.pluto new file mode 100644 index 0000000000..ab1ed7e6b9 --- /dev/null +++ b/Task/Day-of-the-week/Pluto/day-of-the-week.pluto @@ -0,0 +1,9 @@ +local fmt = require "fmt" + +print("Years between 2008 and 2121 when 25th December falls on Sunday:") +local years = {} +for year = 2008, 2121 do + local day = os.date("%A", os.time({year = year, month = 12, day = 25})) + if day == "Sunday" then years:insert(year) end +end +fmt.lprint(years) diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-1.ps1 b/Task/Day-of-the-week/PowerShell/day-of-the-week-1.ps1 new file mode 100644 index 0000000000..44187d014f --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-1.ps1 @@ -0,0 +1 @@ +2008..2121 | Where-Object { (Get-Date $_-12-25).DayOfWeek -eq "Sunday" } diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-2.ps1 b/Task/Day-of-the-week/PowerShell/day-of-the-week-2.ps1 new file mode 100644 index 0000000000..5042dfcdc4 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-2.ps1 @@ -0,0 +1,34 @@ +function Get-ChristmasHoliday +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$false, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [ValidateRange(1,9999)] + [int[]] + $Year = (Get-Date).Year + ) + + Process + { + [datetime]$christmas = Get-Date $Year/12/25 + + switch ($christmas.DayOfWeek) + { + "Sunday" {[datetime[]]$dates = 1..5 | ForEach-Object {$christmas.AddDays($_)}} + "Monday" {[datetime[]]$dates = $christmas, $christmas.AddDays(1)} + "Saturday" {[datetime[]]$dates = $christmas.AddDays(-2), $christmas.AddDays(-1)} + Default {[datetime[]]$dates = $christmas.AddDays(-1), $christmas} + } + + $dates | Group-Object -Property Year | + Select-Object -Property @{Name="Year" ; Expression={$_.Name}}, + @{Name="DayOfWeek"; Expression={$christmas.DayOfWeek}}, + @{Name="Christmas"; Expression={$christmas.ToString("MM/dd/yyyy")}}, + @{Name="DaysOff" ; Expression={$_.Group | ForEach-Object {$_.ToString("MM/dd/yyyy")}}} + } +} diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-3.ps1 b/Task/Day-of-the-week/PowerShell/day-of-the-week-3.ps1 new file mode 100644 index 0000000000..6a846e95d6 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-3.ps1 @@ -0,0 +1 @@ +2008..2121 | Get-ChristmasHoliday | where DayOfWeek -match Su diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-4.ps1 b/Task/Day-of-the-week/PowerShell/day-of-the-week-4.ps1 new file mode 100644 index 0000000000..0da0d11191 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-4.ps1 @@ -0,0 +1 @@ +Get-ChristmasHoliday -Year (2008..2121 | Get-Random) diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-5.ps1 b/Task/Day-of-the-week/PowerShell/day-of-the-week-5.ps1 new file mode 100644 index 0000000000..6272f2c52a --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-5.ps1 @@ -0,0 +1 @@ +(Get-Date | Get-ChristmasHoliday).DaysOff diff --git a/Task/Day-of-the-week/PowerShell/day-of-the-week-6.ps1 b/Task/Day-of-the-week/PowerShell/day-of-the-week-6.ps1 new file mode 100644 index 0000000000..d5e7086412 --- /dev/null +++ b/Task/Day-of-the-week/PowerShell/day-of-the-week-6.ps1 @@ -0,0 +1 @@ +(Get-Date | Get-ChristmasHoliday).DaysOff | Get-Date diff --git a/Task/Day-of-the-week/Rebol/day-of-the-week.rebol b/Task/Day-of-the-week/Rebol/day-of-the-week.rebol new file mode 100644 index 0000000000..5dc752f1cb --- /dev/null +++ b/Task/Day-of-the-week/Rebol/day-of-the-week.rebol @@ -0,0 +1,9 @@ +Rebol [ + Title: "Yuletide Holiday" + URL: http://rosettacode.org/wiki/Yuletide_Holiday +] + +for y 2008 2121 1 [ + d: to date! reduce [y 12 25] + if 7 = d/weekday [prin [y ""]] +] diff --git a/Task/Day-of-the-week/Rye/day-of-the-week.rye b/Task/Day-of-the-week/Rye/day-of-the-week.rye new file mode 100644 index 0000000000..51e020317a --- /dev/null +++ b/Task/Day-of-the-week/Rye/day-of-the-week.rye @@ -0,0 +1,3 @@ +range 2008 2121 +|filter { ++ "-12-25" |date |weekday? = 0 } +|print diff --git a/Task/Day-of-the-week/Uiua/day-of-the-week.uiua b/Task/Day-of-the-week/Uiua/day-of-the-week.uiua new file mode 100644 index 0000000000..951d619d36 --- /dev/null +++ b/Task/Day-of-the-week/Uiua/day-of-the-week.uiua @@ -0,0 +1,4 @@ +# https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Sakamoto.27s_methods +# Adjust y if m<3, change m no to ix, y + y~/4 - y~/100 + y~/400 + m + d +Sakamoto ← °□˜⊡Days◿7++/+[⊃(∘|⌊÷4|¯⌊÷100|⌊÷400)] ⊙-₁⍥-₁◡⋅<₃ +▽=□"Sunday"⊸≡⍚(Sakamoto⊙12⊙25) ↘2008⇡ 2122 diff --git a/Task/Day-of-the-week/VBScript/day-of-the-week.vbs b/Task/Day-of-the-week/VBScript/day-of-the-week.vbs new file mode 100644 index 0000000000..9842fa8eb4 --- /dev/null +++ b/Task/Day-of-the-week/VBScript/day-of-the-week.vbs @@ -0,0 +1,5 @@ +For year = 2008 To 2121 + If Weekday(DateSerial(year, 12, 25)) = 1 Then + WScript.Echo year + End If +Next diff --git a/Task/De-Bruijn-sequences/Ada/de-bruijn-sequences.adb b/Task/De-Bruijn-sequences/Ada/de-bruijn-sequences.adb new file mode 100644 index 0000000000..8afb75bbb7 --- /dev/null +++ b/Task/De-Bruijn-sequences/Ada/de-bruijn-sequences.adb @@ -0,0 +1,126 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Fixed; use Ada.Strings; +with Ada.Strings.Unbounded; + +procedure De_Bruijn_Sequences is + + function De_Bruijn (K, N : Positive) return String + is + use Ada.Strings.Unbounded; + + Alphabet : constant String := "0123456789"; + + subtype Decimal is Integer range 0 .. 9; + type Decimal_Array is array (Natural range <>) of Decimal; + + A : Decimal_Array (0 .. K * N - 1) := (others => 0); + Seq : Unbounded_String; + + procedure Db (T, P : Positive) is + begin + if T > N then + if N mod P = 0 then + for E of A (1 .. P) loop + Append (Seq, Alphabet (Alphabet'First + E)); + end loop; + end if; + else + A (T) := A (T - P); + Db (T + 1, P); + for J in A (T - P) + 1 .. K - 1 loop + A (T) := J; + Db (T + 1, T); + end loop; + end if; + end Db; + + begin + Db (1, 1); + return To_String (Seq) & Slice (Seq, 1, N - 1); + end De_Bruijn; + + function Image (Value : Integer) return String + is (Fixed.Trim (Value'Image, Left)); + + function PIN_Image (Value : Integer) return String + is (Fixed.Tail (Image (Value), Count => 4, Pad => '0')); + + procedure Validate (Db : String) + is + Found : array (0 .. 9_999) of Natural := (others => 0); + Errors : Natural := 0; + begin + + -- Check all strings of 4 consecutive digits within 'db' + -- to see if all 10,000 combinations occur without duplication. + for A in Db'First .. Db'Last - 3 loop + declare + PIN : String renames Db (A .. A + 4 - 1); + begin + if (for all Char of PIN => Char in '0' .. '9') then + declare + N : constant Integer := Integer'Value (PIN); + F : Natural renames Found (N); + begin + F := F + 1; + end; + end if; + end; + end loop; + + for I in 0_000 .. 9_999 loop + if Found (I) = 0 then + Put_Line (" PIN number " & PIN_Image (I) & " missing"); + Errors := Errors + 1; + elsif Found (I) > 1 then + Put_Line (" PIN number " & PIN_Image (I) & " occurs " + & Image (Found (I)) & " times"); + Errors := Errors + 1; + end if; + end loop; + + case Errors is + when 0 => Put_Line (" No errors found"); + when 1 => Put_Line (" 1 error found"); + when others => + Put_Line (" " & Image (Errors) & " errors found"); + end case; + end Validate; + + function Backwards (S : String) return String is + R : String (S'Range); + begin + for A in 0 .. S'Length - 1 loop + R (R'Last - A) := S (S'First + A); + end loop; + return R; + end Backwards; + + DB : constant String := De_Bruijn (K => 10, N => 4); + Rev : constant String := Backwards (DB); + Ovl : String := DB; +begin + Put_Line ("The length of the de Bruijn sequence is " & DB'Length'Image); + New_Line; + + Put_Line ("The first 130 digits of the de Bruijn sequence are: "); + Put_Line (" " & Fixed.Head (DB, 130)); + New_Line; + + Put_Line ("The last 130 digits of the de Bruijn sequence are: "); + Put_Line (" " & Fixed.Tail (DB, 130)); + New_Line; + + Put_Line ("Validating the deBruijn sequence:"); + Validate (DB); + New_Line; + + Put_Line ("Validating the reversed deBruijn sequence:"); + Validate (Rev); + New_Line; + + Ovl (4444) := '.'; + Put_Line ("Validating the overlaid deBruijn sequence:"); + Validate (Ovl); + New_Line; +end De_Bruijn_Sequences; diff --git a/Task/De-Bruijn-sequences/COBOL/de-bruijn-sequences.cob b/Task/De-Bruijn-sequences/COBOL/de-bruijn-sequences.cob new file mode 100644 index 0000000000..6f9dd8b812 --- /dev/null +++ b/Task/De-Bruijn-sequences/COBOL/de-bruijn-sequences.cob @@ -0,0 +1,362 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. DEBRUIJN-PROGRAM. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + *>--------------------------------------------------------- + *> Constants + *>--------------------------------------------------------- + 01 C-K PIC 9(2) VALUE 10. + 01 C-N PIC 9(2) VALUE 4. + + *>--------------------------------------------------------- + *> Array A for de Bruijn generation + *> COBOL index I corresponds to JS index I - 1 + *>--------------------------------------------------------- + 01 WS-A-TABLE. + 05 WS-A PIC 9 OCCURS 41 TIMES. + + *>--------------------------------------------------------- + *> Sequence accumulator + *>--------------------------------------------------------- + 01 WS-SEQ-TABLE. + 05 WS-SEQ PIC 9 OCCURS 10000 TIMES. + 01 WS-SEQ-LEN PIC 9(5) VALUE 0. + + *>--------------------------------------------------------- + *> Explicit stack for simulating recursion + *> State 0 = fresh entry + *> State 1 = returned from db(t+1, p) + *> State 2 = returned from db(t+1, t) in loop + *>--------------------------------------------------------- + 01 WS-STACK-SIZE PIC 9(4) VALUE 0. + 01 WS-STACK-TABLE. + 05 WS-STACK-ENTRY OCCURS 50 TIMES. + 10 STK-T PIC 9(4). + 10 STK-P PIC 9(4). + 10 STK-STATE PIC 9. + 10 STK-J PIC 9(4). + + *>--------------------------------------------------------- + *> String buffers + *>--------------------------------------------------------- + 01 WS-DB-STRING PIC X(10004) VALUE SPACES. + 01 WS-DB-LEN PIC 9(5) VALUE 0. + 01 WS-VAL-STRING PIC X(10004) VALUE SPACES. + 01 WS-VAL-LEN PIC 9(5) VALUE 0. + 01 WS-RDB-STRING PIC X(10004) VALUE SPACES. + 01 WS-OVL-STRING PIC X(10004) VALUE SPACES. + + *>--------------------------------------------------------- + *> Validation: found array for PINs 0000-9999 + *>--------------------------------------------------------- + 01 WS-FOUND-TABLE. + 05 WS-FOUND PIC 9(4) OCCURS 10000 TIMES. + + *>--------------------------------------------------------- + *> Working variables + *>--------------------------------------------------------- + 01 WS-I PIC 9(5). + 01 WS-I2 PIC 9(5). + 01 WS-T PIC 9(4). + 01 WS-P PIC 9(4). + 01 WS-CUR-STATE PIC 9. + 01 WS-CUR-J PIC 9(4). + 01 WS-REMAINDER PIC 9(5). + 01 WS-SUBSTR4 PIC X(4). + 01 WS-NUM PIC 9(4). + 01 WS-NUM-IDX PIC 9(5). + 01 WS-ERR-COUNT PIC 9(5) VALUE 0. + 01 WS-CHAR PIC X. + 01 WS-ALL-DIGITS-FLAG PIC 9 VALUE 1. + 01 WS-TEMP PIC 9(5). + 01 WS-A-IDX PIC 9(4). + 01 WS-A-IDX2 PIC 9(4). + 01 WS-LOOP-LIMIT PIC 9(5). + 01 WS-START-POS PIC 9(5). + + *>--------------------------------------------------------- + *> Display fields + *>--------------------------------------------------------- + 01 WS-LEN-DISPLAY PIC Z(4)9. + 01 WS-ERR-DISPLAY PIC Z(4)9. + 01 WS-PIN-DISPLAY PIC 9(4). + 01 WS-CNT-DISPLAY PIC Z(3)9. + 01 WS-FIRST130 PIC X(130). + 01 WS-LAST130 PIC X(130). + + PROCEDURE DIVISION. + + *>= ======================================================== + MAIN-PARAGRAPH. + *>= ======================================================== + PERFORM GENERATE-DEBRUIJN + + MOVE WS-DB-LEN TO WS-LEN-DISPLAY + DISPLAY "The length of the de Bruijn sequence" + " is " WS-LEN-DISPLAY + DISPLAY SPACE + + MOVE WS-DB-STRING(1:130) TO WS-FIRST130 + DISPLAY "The first 130 digits of the de Bruijn" + " sequence are:" + DISPLAY WS-FIRST130 + + COMPUTE WS-START-POS = WS-DB-LEN - 129 + MOVE WS-DB-STRING(WS-START-POS:130) + TO WS-LAST130 + DISPLAY SPACE + DISPLAY "The last 130 digits of the de Bruijn" + " sequence are:" + DISPLAY WS-LAST130 + DISPLAY SPACE + + DISPLAY "Validating the de Bruijn sequence:" + MOVE WS-DB-STRING TO WS-VAL-STRING + MOVE WS-DB-LEN TO WS-VAL-LEN + PERFORM VALIDATE-SEQUENCE + + DISPLAY SPACE + DISPLAY "Validating the reversed de Bruijn" + " sequence:" + PERFORM REVERSE-DB-STRING + MOVE WS-RDB-STRING TO WS-VAL-STRING + MOVE WS-DB-LEN TO WS-VAL-LEN + PERFORM VALIDATE-SEQUENCE + + DISPLAY SPACE + DISPLAY "Validating the overlaid de Bruijn" + " sequence:" + MOVE WS-DB-STRING TO WS-OVL-STRING + MOVE '.' TO WS-OVL-STRING(4444:1) + MOVE WS-OVL-STRING TO WS-VAL-STRING + MOVE WS-DB-LEN TO WS-VAL-LEN + PERFORM VALIDATE-SEQUENCE + + STOP RUN + . + + *>= ======================================================== + GENERATE-DEBRUIJN. + *>= ======================================================== + INITIALIZE WS-A-TABLE + MOVE 0 TO WS-SEQ-LEN + + *> Push initial call: db(1, 1) + MOVE 0 TO WS-STACK-SIZE + ADD 1 TO WS-STACK-SIZE + MOVE 1 TO STK-T(WS-STACK-SIZE) + MOVE 1 TO STK-P(WS-STACK-SIZE) + MOVE 0 TO STK-STATE(WS-STACK-SIZE) + MOVE 0 TO STK-J(WS-STACK-SIZE) + + *> Process stack until empty + PERFORM PROCESS-STACK + UNTIL WS-STACK-SIZE = 0 + + *> Build output string from sequence digits + MOVE SPACES TO WS-DB-STRING + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-SEQ-LEN + MOVE WS-SEQ(WS-I) + TO WS-DB-STRING(WS-I:1) + END-PERFORM + + *> Append first n-1 chars for wrap-around + COMPUTE WS-TEMP = WS-SEQ-LEN + 1 + MOVE WS-DB-STRING(1:3) + TO WS-DB-STRING(WS-TEMP:3) + COMPUTE WS-DB-LEN = WS-SEQ-LEN + 3 + . + + *>= ======================================================== + PROCESS-STACK. + *> Read current top-of-stack and dispatch by state + *>= ======================================================== + MOVE STK-T(WS-STACK-SIZE) TO WS-T + MOVE STK-P(WS-STACK-SIZE) TO WS-P + MOVE STK-STATE(WS-STACK-SIZE) TO WS-CUR-STATE + MOVE STK-J(WS-STACK-SIZE) TO WS-CUR-J + + EVALUATE WS-CUR-STATE + WHEN 0 + PERFORM STACK-STATE-0 + WHEN 1 + PERFORM STACK-STATE-1 + WHEN 2 + PERFORM STACK-STATE-2 + END-EVALUATE + . + + *>= ======================================================== + STACK-STATE-0. + *> Fresh entry for db(t, p) + *>= ======================================================== + IF WS-T > C-N + *> Base case: t > n + COMPUTE WS-REMAINDER = + FUNCTION MOD(C-N, WS-P) + IF WS-REMAINDER = 0 + *> Append a[1..p] to seq + *> JS a[i] = COBOL WS-A(i + 1) + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-P + ADD 1 TO WS-SEQ-LEN + COMPUTE WS-A-IDX = WS-I + 1 + MOVE WS-A(WS-A-IDX) + TO WS-SEQ(WS-SEQ-LEN) + END-PERFORM + END-IF + *> Return (pop) + SUBTRACT 1 FROM WS-STACK-SIZE + ELSE + *> a[t] = a[t - p] + COMPUTE WS-A-IDX = WS-T + 1 + COMPUTE WS-A-IDX2 = WS-T - WS-P + 1 + MOVE WS-A(WS-A-IDX2) + TO WS-A(WS-A-IDX) + + *> Mark state 1 for return, push db(t+1,p) + MOVE 1 TO STK-STATE(WS-STACK-SIZE) + ADD 1 TO WS-STACK-SIZE + COMPUTE STK-T(WS-STACK-SIZE) = + WS-T + 1 + MOVE WS-P TO STK-P(WS-STACK-SIZE) + MOVE 0 TO STK-STATE(WS-STACK-SIZE) + MOVE 0 TO STK-J(WS-STACK-SIZE) + END-IF + . + + *>= ======================================================== + STACK-STATE-1. + *> Returned from db(t+1, p); init loop j = a[t-p]+1 + *>= ======================================================== + COMPUTE WS-A-IDX2 = WS-T - WS-P + 1 + COMPUTE WS-CUR-J = WS-A(WS-A-IDX2) + 1 + PERFORM STACK-LOOP-CHECK + . + + *>= ======================================================== + STACK-STATE-2. + *> Returned from db(t+1, t) in loop; increment j + *>= ======================================================== + ADD 1 TO WS-CUR-J + PERFORM STACK-LOOP-CHECK + . + + *>= ======================================================== + STACK-LOOP-CHECK. + *> If j < k, set a[t] = j, push db(t+1, t) + *> Otherwise pop (loop finished) + *>= ======================================================== + IF WS-CUR-J < C-K + COMPUTE WS-A-IDX = WS-T + 1 + MOVE WS-CUR-J TO WS-A(WS-A-IDX) + + MOVE WS-CUR-J + TO STK-J(WS-STACK-SIZE) + MOVE 2 TO STK-STATE(WS-STACK-SIZE) + + ADD 1 TO WS-STACK-SIZE + COMPUTE STK-T(WS-STACK-SIZE) = + WS-T + 1 + MOVE WS-T TO STK-P(WS-STACK-SIZE) + MOVE 0 TO STK-STATE(WS-STACK-SIZE) + MOVE 0 TO STK-J(WS-STACK-SIZE) + ELSE + SUBTRACT 1 FROM WS-STACK-SIZE + END-IF + . + + *>= ======================================================== + VALIDATE-SEQUENCE. + *>= ======================================================== + INITIALIZE WS-FOUND-TABLE + MOVE 0 TO WS-ERR-COUNT + + *> Scan all 4-character substrings + COMPUTE WS-LOOP-LIMIT = WS-VAL-LEN - 3 + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-LOOP-LIMIT + MOVE WS-VAL-STRING(WS-I:4) + TO WS-SUBSTR4 + + *> Check if all 4 chars are digits + MOVE 1 TO WS-ALL-DIGITS-FLAG + PERFORM VARYING WS-I2 FROM 1 BY 1 + UNTIL WS-I2 > 4 + MOVE WS-SUBSTR4(WS-I2:1) + TO WS-CHAR + IF WS-CHAR < '0' OR WS-CHAR > '9' + MOVE 0 TO WS-ALL-DIGITS-FLAG + END-IF + END-PERFORM + + IF WS-ALL-DIGITS-FLAG = 1 + MOVE WS-SUBSTR4 TO WS-NUM + COMPUTE WS-NUM-IDX = WS-NUM + 1 + ADD 1 TO WS-FOUND(WS-NUM-IDX) + END-IF + END-PERFORM + + *> Count errors + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > 10000 + IF WS-FOUND(WS-I) NOT = 1 + ADD 1 TO WS-ERR-COUNT + END-IF + END-PERFORM + + *> Display results + IF WS-ERR-COUNT = 0 + DISPLAY " No errors found" + ELSE + MOVE WS-ERR-COUNT TO WS-ERR-DISPLAY + IF WS-ERR-COUNT = 1 + DISPLAY " " WS-ERR-DISPLAY + " error found:" + ELSE + DISPLAY " " WS-ERR-DISPLAY + " errors found:" + END-IF + + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > 10000 + COMPUTE WS-TEMP = WS-I - 1 + IF WS-FOUND(WS-I) = 0 + MOVE WS-TEMP TO WS-PIN-DISPLAY + DISPLAY + " PIN number " + WS-PIN-DISPLAY + " missing" + ELSE + IF WS-FOUND(WS-I) > 1 + MOVE WS-TEMP + TO WS-PIN-DISPLAY + MOVE WS-FOUND(WS-I) + TO WS-CNT-DISPLAY + DISPLAY + " PIN number " + WS-PIN-DISPLAY + " occurs " + WS-CNT-DISPLAY + " times" + END-IF + END-IF + END-PERFORM + END-IF + . + + *>= ======================================================== + REVERSE-DB-STRING. + *>= ======================================================== + MOVE SPACES TO WS-RDB-STRING + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WS-DB-LEN + COMPUTE WS-TEMP = + WS-DB-LEN - WS-I + 1 + MOVE WS-DB-STRING(WS-TEMP:1) + TO WS-RDB-STRING(WS-I:1) + END-PERFORM + . diff --git a/Task/De-Bruijn-sequences/Dart/de-bruijn-sequences.dart b/Task/De-Bruijn-sequences/Dart/de-bruijn-sequences.dart new file mode 100644 index 0000000000..83c44b1819 --- /dev/null +++ b/Task/De-Bruijn-sequences/Dart/de-bruijn-sequences.dart @@ -0,0 +1,95 @@ +import 'dart:math'; + +String deBruijn(int k, int n) { + List a = List.filled(k * n, 0); + List seq = []; + + void db(int t, int p) { + if (t > n) { + if (n % p == 0) { + for (int i = 1; i < p + 1; i++) { + seq.add(a[i]); + } + } + } else { + a[t] = a[t - p]; + db(t + 1, p); + int j = a[t - p] + 1; + while (j < k) { + a[t] = j; + db(t + 1, t); + j++; + } + } + } + + db(1, 1); + + StringBuffer buf = StringBuffer(); + for (int i in seq) { + buf.write(String.fromCharCode(i + '0'.codeUnitAt(0))); + } + String result = buf.toString() + buf.toString().substring(0, n - 1); + return result; +} + +bool allDigits(String s) { + for (int i = 0; i < s.length; i++) { + if (s.codeUnitAt(i) < '0'.codeUnitAt(0) || s.codeUnitAt(i) > '9'.codeUnitAt(0)) { + return false; + } + } + return true; +} + +void validate(String db) { + int le = db.length; + List found = List.filled(10000, 0); + List errs = []; + + for (int i = 0; i < le - 3; i++) { + String s = db.substring(i, i + 4); + if (allDigits(s)) { + int n = int.parse(s); + found[n]++; + } + } + + for (int i = 0; i < 10000; i++) { + if (found[i] == 0) { + errs.add(" PIN number $i missing"); + } else if (found[i] > 1) { + errs.add(" PIN number $i occurs ${found[i]} times"); + } + } + + if (errs.isEmpty) { + print(" No errors found"); + } else { + String pl = (errs.length == 1) ? "" : "s"; + print(" ${errs.length} error$pl found:"); + for (String e in errs) { + print(e); + } + } +} + +void main() { + String db = deBruijn(10, 4); + print("The length of the de Bruijn sequence is ${db.length}\n"); + + print("The first 130 digits of the de Bruijn sequence are: ${db.substring(0, 130)}"); + print("\nThe last 130 digits of the de Bruijn sequence are: ${db.substring(db.length - 130)}"); + + print("\nValidating the de Bruijn sequence:"); + validate(db); + + print("\nValidating the reversed de Bruijn sequence:"); + String rdb = db.split('').reversed.join(); + validate(rdb); + + String by = db; + by = by.substring(0, 4443) + '.' + by.substring(4444); + print("\nValidating the overlaid de Bruijn sequence:"); + validate(by); +} diff --git a/Task/De-Bruijn-sequences/Pluto/de-bruijn-sequences.pluto b/Task/De-Bruijn-sequences/Pluto/de-bruijn-sequences.pluto new file mode 100644 index 0000000000..e2faeebf94 --- /dev/null +++ b/Task/De-Bruijn-sequences/Pluto/de-bruijn-sequences.pluto @@ -0,0 +1,59 @@ +require "table2" +local fmt = require "fmt" + +local deBruijn = "" +for n = 0, 99 do + local a = fmt.lpad(n, 2, "0") + local a1 = a[1]:byte() + local a2 = a[2]:byte() + if a2 >= a1 then + deBruijn ..= (a1 == a2) ? string.char(a1) : a + local m = n + 1 + while m <= 99 do + local ms = fmt.lpad(m, 2, "0") + if ms[2]:byte() > a1 then deBruijn ..= a .. ms end + m += 1 + end + end +end + +deBruijn ..= "000" +print($"de Bruijn sequence length: {#deBruijn}\n") +print($"First 130 characters:\n{deBruijn:sub(1, 130)}\n") +print($"Last 130 characters:\n{deBruijn:sub(-130, -1)}\n") + +local function check(text) + local res = {} + local found = table.rep(10000, 0) + local k = 0 + for i = 1, #text - 3 do + local s = text:sub(i, i + 3) + if s:split(""):checkall(|c| -> "0" <= c <= "9") then + k = tonumber(s) + found[k + 1] += 1 + end + end + for i = 1, 10000 do + k = found[i] + if k != 1 then + local e = $" Pin number {fmt.lpad(i - 1, 4, "0")} " + e ..= (k == 0) ? "missing" : $"occurs {k} times" + res:insert(e) + end + end + k = #res + if k == 0 then + res = "No errors found" + else + local s = (k == 1) ? "" : "s" + res = $"{k} error{s} found:\n" .. res:concat("\n") + end + return res +end + +print($"Missing 4 digit PINs in this sequence: {check(deBruijn)}") +print($"Missing 4 digit PINs in the reversed sequence: {check(deBruijn:reverse())}") + +print($"\n4,444th digit in the sequence: '{deBruijn[4444]}' (setting it to '.')") +deBruijn = deBruijn:sub(1, 4443) .. "." .. deBruijn:sub(4445) +print($"Re-running checks: {check(deBruijn)}") diff --git a/Task/De-Bruijn-sequences/R/de-bruijn-sequences.r b/Task/De-Bruijn-sequences/R/de-bruijn-sequences.r new file mode 100644 index 0000000000..361dad1074 --- /dev/null +++ b/Task/De-Bruijn-sequences/R/de-bruijn-sequences.r @@ -0,0 +1,70 @@ +# De Bruijn sequence generator and verifier in R + +debruijn <- function(k, n) { + alphabet <- c(0:9, letters)[1:k] + a <- integer(k * n) + seq <- c() + + db <- function(t, p) { + if (t > n) { + if (n %% p == 0) { + seq <<- c(seq, a[2:(p + 1)]) + } + } else { + a[t + 1] <<- a[t - p + 1] + db(t + 1, p) + + if (a[t - p + 1] + 1 <= k - 1) { + for (j in (a[t - p + 1] + 1):(k - 1)) { + a[t + 1] <<- j + db(t + 1, t) + } + } + } + } + + db(1, 1) + + # Convert to string using alphabet + result_indices <- c(seq, seq[1:(n-1)]) + result_chars <- alphabet[result_indices + 1] + return(paste(result_chars, collapse = "")) +} + +verifyallPIN <- function(str, k, n, deltaposition = 0) { + if (deltaposition != 0) { + str_chars <- strsplit(str, "")[[1]] + str_chars[deltaposition] <- "." + str <- paste(str_chars, collapse = "") + } + + result <- TRUE + + for (i in 0:(k^n - 1)) { + pin <- sprintf(paste0("%0", n, "d"), i) + if (!grepl(pin, str, fixed = TRUE)) { + cat("PIN", pin, "does not occur in the sequence.\n") + result <- FALSE + } + } + + cat("The sequence does", if(result) "" else "not", "contain all PINs.\n") + return(result) +} + +# Main execution +s <- debruijn(10, 4) +cat("The length of the sequence is", nchar(s), ". The first 130 digits are:\n") +cat(substr(s, 1, 130), "\n") +cat("and the last 130 digits are:\n") +cat(substr(s, nchar(s) - 129, nchar(s)), "\n") + +cat("Testing sequence: ") +verifyallPIN(s, 10, 4) + +cat("Testing the reversed sequence: ") +reversed_s <- paste(rev(strsplit(s, "")[[1]]), collapse = "") +verifyallPIN(reversed_s, 10, 4) + +cat("\nAfter replacing 4444th digit with '.':\n") +verifyallPIN(s, 10, 4, 4444) diff --git a/Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences-1.rb b/Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences-1.rb new file mode 100644 index 0000000000..03ee557bbf --- /dev/null +++ b/Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences-1.rb @@ -0,0 +1,73 @@ +def deBruijn(k, n) + alphabet = "0123456789" + @a = Array.new(k * n, 0) + @seq = [] + + def db(k, n, t, p) + if t > n then + if n % p == 0 then + temp = @a[1 .. p] + @seq.concat temp + end + else + @a[t] = @a[t - p] + db(k, n, t + 1, p) + j = @a[t - p] + 1 + while j < k do + @a[t] = j # & 0xFF + db(k, n, t + 1, t) + j = j + 1 + end + end + end + db(k, n, 1, 1) + + buf = "" + for i in @seq + buf <<= alphabet[i] + end + return buf + buf[0 .. n-2] +end + +def validate(db) + le = db.length + found = Array.new(10000, 0) + errs = [] + # Check all strings of 4 consecutive digits within 'db' + # to see if all 10,000 combinations occur without duplication. + for i in 0 .. le-4 + s = db[i .. i+3] + if s.scan(/\D/).empty? then + found[s.to_i] += 1 + end + end + for i in 0 .. found.length - 1 + if found[i] == 0 then + errs <<= (" PIN number %04d missing" % [i]) + elsif found[i] > 1 then + errs <<= (" PIN number %04d occurs %d times" % [i, found[i]]) + end + end + if errs.length == 0 then + print " No errors found\n" + else + pl = (errs.length == 1) ? "" : "s" + print " ", errs.length, " error", pl, " found:\n" + for err in errs + print err, "\n" + end + end +end + +db = deBruijn(10, 4) +print "The length of the de Bruijn sequence is ", db.length, "\n\n" +print "The first 130 digits of the de Bruijn sequence are: ", db[0 .. 129], "\n\n" +print "The last 130 digits of the de Bruijn sequence are: ", db[-130 .. db.length], "\n\n" + +print "Validating the de Bruijn sequence:\n" +validate(db) +print "\n" + +db[4443] = '.' +print "Validating the overlaid de Bruijn sequence:\n" +validate(db) diff --git a/Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences-2.rb b/Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences-2.rb new file mode 100644 index 0000000000..c757ee2d21 --- /dev/null +++ b/Task/De-Bruijn-sequences/Ruby/de-bruijn-sequences-2.rb @@ -0,0 +1,72 @@ +def de_bruijn(k, n) + # de Bruijn sequence for alphabet k and subsequences of length n + alphabet = if k.is_a?(Integer) + (0...k).map(&:to_s) + else + k.chars + end + k = alphabet.size + a = Array.new(k * n, 0) + sequence = [] + + def db(t, p, a, k, n, sequence) + if t > n + sequence.concat(a[1..p]) if n % p == 0 + else + a[t] = a[t - p] + db(t + 1, p, a, k, n, sequence) + (a[t - p] + 1...k).each do |j| + a[t] = j + db(t + 1, t, a, k, n, sequence) + end + end + end + + db(1, 1, a, k, n, sequence) + sequence.map { |i| alphabet[i] }.join +end + +def validate(db) + dbwithwrap = db + db[0, 3] + digits = '0123456789' + errorstrings = [] + + digits.chars.each do |d1| + digits.chars.each do |d2| + digits.chars.each do |d3| + digits.chars.each do |d4| + teststring = d1 + d2 + d3 + d4 + errorstrings << teststring unless dbwithwrap.include?(teststring) + end + end + end + end + + if errorstrings.any? + puts " #{errorstrings.size} errors found:" + errorstrings.each { |e| puts " PIN number #{e} missing" } + else + puts " No errors found" + end +end + +db = de_bruijn(10, 4) +puts "" +puts "The length of the de Bruijn sequence is #{db.length}" +puts "" +puts "The first 130 digits of the de Bruijn sequence are: #{db[0, 130]}" +puts "" +puts "The last 130 digits of the de Bruijn sequence are: #{db[-130..-1]}" +puts "" +puts "Validating the deBruijn sequence:" +validate(db) + +dbreversed = db.reverse +puts "" +puts "Validating the reversed deBruijn sequence:" +validate(dbreversed) + +dboverlaid = db[0, 4443] + '.' + db[4444..-1] +puts "" +puts "Validating the overlaid deBruijn sequence:" +validate(dboverlaid) diff --git a/Task/De-Bruijn-sequences/Swift/de-bruijn-sequences.swift b/Task/De-Bruijn-sequences/Swift/de-bruijn-sequences.swift new file mode 100644 index 0000000000..f8d2ad8e10 --- /dev/null +++ b/Task/De-Bruijn-sequences/Swift/de-bruijn-sequences.swift @@ -0,0 +1,103 @@ +import Foundation + +typealias Byte = UInt8 + +func deBruijn(_ k: Int, _ n: Int) -> String { + var a = Array(repeating: Byte(0), count: k * n) + var seq: [Byte] = [] + + func db(_ t: Int, _ p: Int) { + if t > n { + if n % p == 0 { + for i in 1..

    Bool { + for c in s { + if c < "0" || "9" < c { + return false + } + } + return true +} + +func validate(_ db: String) { + let le = db.count + var found = Array(repeating: 0, count: 10000) + var errs: [String] = [] + + // Check all strings of 4 consecutive digits within 'db' + // to see if all 10,000 combinations occur without duplication. + for i in 0..<(le - 3) { + let startIndex = db.index(db.startIndex, offsetBy: i) + let endIndex = db.index(startIndex, offsetBy: 4) + let s = String(db[startIndex.. 1 { + errs.append(" PIN number \(i) occurs \(found[i]) times") + } + } + + if errs.isEmpty { + print(" No errors found") + } else { + let pl = (errs.count == 1) ? "" : "s" + print(" \(errs.count) error\(pl) found:") + for e in errs { + print(e) + } + } +} + +func main() { + let db = deBruijn(10, 4) + + print("The length of the de Bruijn sequence is \(db.count)\n") + print("The first 130 digits of the de Bruijn sequence are: \(String(db.prefix(130)))\n") + print("The last 130 digits of the de Bruijn sequence are: \(String(db.suffix(130)))") + + print("\nValidating the de Bruijn sequence:") + validate(db) + + print("\nValidating the reversed de Bruijn sequence:") + let rdb = String(db.reversed()) + validate(rdb) + + var by = Array(db) + by[4443] = "." + let overlaidDb = String(by) + print("\nValidating the overlaid de Bruijn sequence:") + validate(overlaidDb) +} + +main() diff --git a/Task/De-Bruijn-sequences/Tcl/de-bruijn-sequences.tcl b/Task/De-Bruijn-sequences/Tcl/de-bruijn-sequences.tcl new file mode 100644 index 0000000000..cbdd8bd85f --- /dev/null +++ b/Task/De-Bruijn-sequences/Tcl/de-bruijn-sequences.tcl @@ -0,0 +1,90 @@ +proc de_bruijn {k n} { + # de Bruijn sequence for alphabet k and subsequences of length n. + if {[string is integer -strict $k]} { + set alphabet {} + for {set i 0} {$i < $k} {incr i} { + lappend alphabet $i + } + } else { + set alphabet $k + set k [llength $alphabet] + } + + set a [lrepeat [expr {$k * $n}] 0] + set sequence {} + + proc db {a k n t p sequence_var} { + upvar 1 $sequence_var sequence + + if {$t > $n} { + if {$n % $p == 0} { + set sequence [concat $sequence [lrange $a 1 [expr {$p}]]] + } + } else { + lset a $t [lindex $a [expr {$t - $p}]] + db $a $k $n [expr {$t + 1}] $p sequence + for {set j [expr {[lindex $a [expr {$t - $p}]] + 1}]} {$j < $k} {incr j} { + lset a $t $j + db $a $k $n [expr {$t + 1}] $t sequence + } + } + } + + db $a $k $n 1 1 sequence + set result {} + foreach i $sequence { + append result [lindex $alphabet $i] + } + return $result +} + +proc validate {db} { + # Check that all combinations are present in De Bruijn string db. + set dbwithwrap ${db}[string range $db 0 2] + set digits {0 1 2 3 4 5 6 7 8 9} + set errorstrings {} + + foreach d1 $digits { + foreach d2 $digits { + foreach d3 $digits { + foreach d4 $digits { + set teststring ${d1}${d2}${d3}${d4} + if {[string first $teststring $dbwithwrap] == -1} { + lappend errorstrings $teststring + } + } + } + } + } + + set err_count [llength $errorstrings] + if {$err_count > 0} { + puts " $err_count errors found:" + foreach e $errorstrings { + puts " PIN number $e missing" + } + } else { + puts " No errors found" + } +} + +set db [de_bruijn 10 4] +puts "" +puts "The length of the de Bruijn sequence is [string length $db]" +puts "" +puts "The first 130 digits of the de Bruijn sequence are: [string range $db 0 129]" +puts "" +puts "The last 130 digits of the de Bruijn sequence are: [string range $db end-129 end]" +puts "" +puts "Validating the deBruijn sequence:" +validate $db + +set dbreversed [string reverse $db] +puts "" +puts "Validating the reversed deBruijn sequence:" +validate $dbreversed + +set dboverlaid [string range $db 0 4442].[string range $db 4444 end] +puts "" +puts "Validating the overlaid deBruijn sequence:" +validate $dboverlaid diff --git a/Task/De-Bruijn-sequences/V-(Vlang)/de-bruijn-sequences.v b/Task/De-Bruijn-sequences/V-(Vlang)/de-bruijn-sequences.v new file mode 100644 index 0000000000..912a374a47 --- /dev/null +++ b/Task/De-Bruijn-sequences/V-(Vlang)/de-bruijn-sequences.v @@ -0,0 +1,92 @@ +const digits = "0123456789" + +struct DeBruijn { + mut: + ay []u8 + seq []u8 + kir int + nir int + alpha string +} + +fn (mut db DeBruijn) generate(tir int, pir int) { + mut jir := 0 + if tir > db.nir { + if db.nir % pir == 0 { db.seq << db.ay[1..pir + 1] } + } + else { + db.ay[tir] = db.ay[tir - pir] + db.generate(tir + 1, pir) + jir = int(db.ay[tir - pir]) + 1 + for jir < db.kir { + db.ay[tir] = u8(jir & 0xFF) + db.generate(tir + 1, tir) + jir++ + } + } +} + +fn de_bruijn(kir int, nir int) string { + mut buf := "" + mut db := DeBruijn{ + kir: kir + nir: nir + ay: []u8{len: kir * nir} + seq: []u8{} + alpha: digits[0..kir] + } + db.generate(1, 1) + for ial in db.seq { + buf += db.alpha[ial].ascii_str() + } + return buf + buf[0..nir-1] +} + +fn all_digits(sg string) bool { + for cal in sg { + if cal < `0` || cal > `9` { return false } + } + return true +} + +fn validate(db string) { + le := db.len + mut found := [10000]int{} + mut errs := []string{} + for ial in 0 .. le - 3 { + sg := db[ial..ial + 4] + if all_digits(sg) { + nir := sg.int() + found[nir]++ + } + } + for ial in 0 .. 10000 { + if found[ial] == 0 { errs << " PIN number ${ial:04d} missing" } + if found[ial] > 1 { errs << " PIN number ${ial:04d} occurs ${found[ial]} times" } + } + if errs.len == 0 { println(" No errors found") } + else { + pl := if errs.len == 1 { "" } else { "s" } + println(" ${errs.len} error${pl} found:") + for err in errs { + println(err) + } + } +} + +fn main() { + db := de_bruijn(10, 4) + mut by := db.clone() + println("The length of the de Bruijn sequence is $db.len\n") + println("The first 130 digits of the de Bruijn sequence are: ${db[..130]}") + println("\nThe last 130 digits of the de Bruijn sequence are: ${db[db.len - 130..]}") + println("\nValidating the deBruijn sequence:") + validate(db) + + println("\nValidating the reversed deBruijn sequence:") + validate(db.reverse()) + + by = by[..4443] + "." + by[4444..] + println("\nValidating the overlaid deBruijn sequence:") + validate(by) +} diff --git a/Task/Deal-cards-for-FreeCell/Ada/deal-cards-for-freecell.adb b/Task/Deal-cards-for-FreeCell/Ada/deal-cards-for-freecell.adb new file mode 100644 index 0000000000..72b1382b05 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Ada/deal-cards-for-freecell.adb @@ -0,0 +1,38 @@ +with Ada.Text_IO; use Ada.Text_IO; +procedure FreeCell is + type State is mod 2**31; + type Deck is array (0..51) of String(1..2); + + package Random is + procedure Init(Seed: State); + function Rand return State; + end Random; + package body Random is + S : State := State'First; + procedure Init(Seed: State) is begin S := Seed; end Init; + function Rand return State is begin + S := S * 214013 + 2531011; return S / 2**16; + end Rand; + end Random; + + procedure Deal (num : State) is + thedeck : Deck; pick : State; + Chars : constant String := "A23456789TJQKCDHS"; + begin + for i in thedeck'Range loop + thedeck(i):= Chars(i/4+1) & Chars(i mod 4 + 14); + end loop; + Random.Init(num); + for i in 0..51 loop + pick := Random.Rand mod State(52-i); + Put(thedeck(Natural(pick))&' '); + if (i+1) mod 8 = 0 then New_Line; end if; + thedeck(Natural(pick)) := thedeck(51-i); + end loop; New_Line; + end Deal; + +begin + Deal(1); + New_Line; + Deal(617); +end FreeCell; diff --git a/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk b/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk index 2759a7a4a9..790c73d195 100644 --- a/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk +++ b/Task/Deal-cards-for-FreeCell/AutoHotkey/deal-cards-for-freecell-1.ahk @@ -1,24 +1,24 @@ FreeCell(num){ - cards := "A23456789TJQK", suits := "♣♦♥♠", card := [], Counter := 0 - loop, parse, cards - { - ThisCard := A_LoopField - loop, parse, suits - Card[Counter++] := ThisCard . A_LoopField - } - loop, 52 - { - a := MS(num) - num:=a[1] - MyCardNo := mod(a[2],53-A_Index) - MyCard := Card[MyCardNo] - Card[MyCardNo] := Card[52-A_Index] - Card.Remove(52-A_Index) - Res .= MyCard (Mod(A_Index,8)?" ":"`n") - } - return Res + cards := "A23456789TJQK", suits := "♣♦♥♠", card := [], Counter := 0 + loop, parse, cards + { + ThisCard := A_LoopField + loop, parse, suits + Card[Counter++] := ThisCard . A_LoopField + } + loop, 52 + { + a := MS(num) + num:=a[1] + MyCardNo := mod(a[2],53-A_Index) + MyCard := Card[MyCardNo] + Card[MyCardNo] := Card[52-A_Index] + Card.Remove(52-A_Index) + Res .= MyCard (Mod(A_Index,8)?" ":"`n") + } + return Res } MS(Seed) { - Seed := Mod(214013 * Seed + 2531011, 2147483648) - return, [Seed, Seed // 65536] + Seed := Mod(214013 * Seed + 2531011, 2147483648) + return, [Seed, Seed // 65536] } diff --git a/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp index d49d13b962..54860626b1 100644 --- a/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp +++ b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell-1.cpp @@ -10,49 +10,49 @@ class fc_dealer public: void deal( int game ) { - _gn = game; - fillDeck(); - shuffle(); - display(); + _gn = game; + fillDeck(); + shuffle(); + display(); } private: void fillDeck() { - int p = 0; - for( int c = 0; c < 13; c++ ) - for( int s = 0; s < 4; s++ ) - _cards[p++] = c | s << 4; + int p = 0; + for( int c = 0; c < 13; c++ ) + for( int s = 0; s < 4; s++ ) + _cards[p++] = c | s << 4; } void shuffle() { - srand( _gn ); - int cc = 52, nc, lc; - while( cc ) - { - nc = rand() % cc; - lc = _cards[--cc]; - _cards[cc] = _cards[nc]; - _cards[nc] = lc; - } + srand( _gn ); + int cc = 52, nc, lc; + while( cc ) + { + nc = rand() % cc; + lc = _cards[--cc]; + _cards[cc] = _cards[nc]; + _cards[nc] = lc; + } } void display() { - char* suit = "CDHS"; - char* symb = "A23456789TJQK"; - int z = 0; - cout << "GAME #" << _gn << endl << "=======================" << endl; - for( int c = 51; c >= 0; c-- ) - { - cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; - if( ++z >= 8 ) - { - cout << endl; - z = 0; - } - } + char* suit = "CDHS"; + char* symb = "A23456789TJQK"; + int z = 0; + cout << "GAME #" << _gn << endl << "=======================" << endl; + for( int c = 51; c >= 0; c-- ) + { + cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; + if( ++z >= 8 ) + { + cout << endl; + z = 0; + } + } } int _cards[52], _gn; @@ -64,12 +64,12 @@ int main( int argc, char* argv[] ) int gn; while( true ) { - cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; - if( !gn ) break; + cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; + if( !gn ) break; - system( "cls" ); - dealer.deal( gn ); - cout << endl << endl; + system( "cls" ); + dealer.deal( gn ); + cout << endl << endl; } return 0; } diff --git a/Task/Deal-cards-for-FreeCell/C-sharp/deal-cards-for-freecell-2.cs b/Task/Deal-cards-for-FreeCell/C-sharp/deal-cards-for-freecell-2.cs index 138efa25f8..0c81d3ca17 100644 --- a/Task/Deal-cards-for-FreeCell/C-sharp/deal-cards-for-freecell-2.cs +++ b/Task/Deal-cards-for-FreeCell/C-sharp/deal-cards-for-freecell-2.cs @@ -3,57 +3,57 @@ using System.Text; namespace FreeCellConsole { - public class Rand { - long _seed; - public Rand(int seed=1) { - _seed = seed; - } - public int Next() { - return (int) ((_seed = (_seed * 214013 + 2531011) & int.MaxValue) >> 16); - } - } - - public class Card { - private static readonly string kSuits = "♣♦♥♠"; - private static readonly string kValues = "A23456789TJQK"; - public int Value { get; set; } - public int Suit { get; set; } - public Card(int rawvalue=0) : this(rawvalue / 4, rawvalue % 4) { - } - public Card(int value, int suit) { - Value = value; Suit = suit; - } - public override string ToString() { - return string.Format("{0}{1}", kValues[Value], kSuits[Suit]); - } - } - - public class Deck { - public Card[] Cards; - public Deck(int seed) { - var r = new Rand(seed); - Cards = new Card[52]; - for (int i=0; i < 52; i++) - Cards[i] = new Card(51 - i); - for (int i=0; i < 51; i++) { - int j = 51 - r.Next() % (52 - i); - Card tmp = Cards[i]; Cards[i] = Cards[j]; Cards[j] = tmp; - } - } - public override string ToString() { - var sb = new StringBuilder(); - for (int i=0; i < Cards.Length; i++) { - sb.Append(Cards[i].ToString()); - sb.Append(i % 8 == 7 ? "\n" : " "); - } - return sb.ToString(); - } - } - - class Program { - public static void Main(string[] args) { - Console.WriteLine("Deck 1\n{0}\n", new Deck(1)); - Console.WriteLine("Deck 617\n{0}\n", new Deck(617)); - } - } + public class Rand { + long _seed; + public Rand(int seed=1) { + _seed = seed; + } + public int Next() { + return (int) ((_seed = (_seed * 214013 + 2531011) & int.MaxValue) >> 16); + } + } + + public class Card { + private static readonly string kSuits = "♣♦♥♠"; + private static readonly string kValues = "A23456789TJQK"; + public int Value { get; set; } + public int Suit { get; set; } + public Card(int rawvalue=0) : this(rawvalue / 4, rawvalue % 4) { + } + public Card(int value, int suit) { + Value = value; Suit = suit; + } + public override string ToString() { + return string.Format("{0}{1}", kValues[Value], kSuits[Suit]); + } + } + + public class Deck { + public Card[] Cards; + public Deck(int seed) { + var r = new Rand(seed); + Cards = new Card[52]; + for (int i=0; i < 52; i++) + Cards[i] = new Card(51 - i); + for (int i=0; i < 51; i++) { + int j = 51 - r.Next() % (52 - i); + Card tmp = Cards[i]; Cards[i] = Cards[j]; Cards[j] = tmp; + } + } + public override string ToString() { + var sb = new StringBuilder(); + for (int i=0; i < Cards.Length; i++) { + sb.Append(Cards[i].ToString()); + sb.Append(i % 8 == 7 ? "\n" : " "); + } + return sb.ToString(); + } + } + + class Program { + public static void Main(string[] args) { + Console.WriteLine("Deck 1\n{0}\n", new Deck(1)); + Console.WriteLine("Deck 617\n{0}\n", new Deck(617)); + } + } } diff --git a/Task/Deal-cards-for-FreeCell/C/deal-cards-for-freecell.c b/Task/Deal-cards-for-FreeCell/C/deal-cards-for-freecell.c index 15fdac85d2..d0eeb3b34a 100644 --- a/Task/Deal-cards-for-FreeCell/C/deal-cards-for-freecell.c +++ b/Task/Deal-cards-for-FreeCell/C/deal-cards-for-freecell.c @@ -11,36 +11,36 @@ void srnd(int x) { seed = x; } void show(const int *c) { - int i; - for (i = 0; i < 52; c++) { - printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, - s_suits[*c % 4], s_nums[*c / 4]); - if (!(++i % 8) || i == 52) putchar('\n'); - } + int i; + for (i = 0; i < 52; c++) { + printf(" \033[%dm%lc\033[m%lc", 32 - (1 + *c) % 4 / 2, + s_suits[*c % 4], s_nums[*c / 4]); + if (!(++i % 8) || i == 52) putchar('\n'); + } } void deal(int s, int *t) { - int i, j; - srnd(s); + int i, j; + srnd(s); - for (i = 0; i < 52; i++) t[i] = 51 - i; - for (i = 0; i < 51; i++) { - j = 51 - rnd() % (52 - i); - s = t[i], t[i] = t[j], t[j] = s; - } + for (i = 0; i < 52; i++) t[i] = 51 - i; + for (i = 0; i < 51; i++) { + j = 51 - rnd() % (52 - i); + s = t[i], t[i] = t[j], t[j] = s; + } } int main(int c, char **v) { - int s, card[52]; - if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; + int s, card[52]; + if (c < 2 || (s = atoi(v[1])) <= 0) s = 11982; - setlocale(LC_ALL, ""); + setlocale(LC_ALL, ""); - deal(s, card); - printf("Hand %d\n", s); - show(card); + deal(s, card); + printf("Hand %d\n", s); + show(card); - return 0; + return 0; } diff --git a/Task/Deal-cards-for-FreeCell/Ceylon/deal-cards-for-freecell.ceylon b/Task/Deal-cards-for-FreeCell/Ceylon/deal-cards-for-freecell.ceylon index 01051310dd..c0fb11689b 100644 --- a/Task/Deal-cards-for-FreeCell/Ceylon/deal-cards-for-freecell.ceylon +++ b/Task/Deal-cards-for-FreeCell/Ceylon/deal-cards-for-freecell.ceylon @@ -1,33 +1,33 @@ shared void freeCellDeal() { - //a function that returns a random number generating function - function createRNG(variable Integer state) => - () => (state = (214_013 * state + 2_531_011) % 2^31) / 2^16; - - void deal(Integer num) { - // create an array with a list comprehension - variable value deck = Array { - for(rank in "A23456789TJQK") - for(suit in "CDHS") - "``rank````suit``" - }; - value rng = createRNG(num); - for(i in 1..52) { - value index = rng() % deck.size; - assert(exists lastIndex = deck.lastIndex); - //swap the random card with the last one - deck.swap(index, lastIndex); - //print the last one - process.write("``deck.last else "missing card"`` " ); - if(i % 8 == 0) { - print(""); - } - //and shrink the array to remove the last card - deck = deck[...lastIndex - 1]; - } - } - - deal(1); - print("\n"); - deal(617); + //a function that returns a random number generating function + function createRNG(variable Integer state) => + () => (state = (214_013 * state + 2_531_011) % 2^31) / 2^16; + + void deal(Integer num) { + // create an array with a list comprehension + variable value deck = Array { + for(rank in "A23456789TJQK") + for(suit in "CDHS") + "``rank````suit``" + }; + value rng = createRNG(num); + for(i in 1..52) { + value index = rng() % deck.size; + assert(exists lastIndex = deck.lastIndex); + //swap the random card with the last one + deck.swap(index, lastIndex); + //print the last one + process.write("``deck.last else "missing card"`` " ); + if(i % 8 == 0) { + print(""); + } + //and shrink the array to remove the last card + deck = deck[...lastIndex - 1]; + } + } + + deal(1); + print("\n"); + deal(617); } diff --git a/Task/Deal-cards-for-FreeCell/Common-Lisp/deal-cards-for-freecell.lisp b/Task/Deal-cards-for-FreeCell/Common-Lisp/deal-cards-for-freecell.lisp index 387a31235a..5fb4c67200 100644 --- a/Task/Deal-cards-for-FreeCell/Common-Lisp/deal-cards-for-freecell.lisp +++ b/Task/Deal-cards-for-FreeCell/Common-Lisp/deal-cards-for-freecell.lisp @@ -1,18 +1,18 @@ (defun make-rng (seed) #'(lambda () - (ash (setf seed (mod (+ (* 214013 seed) 2531011) (expt 2 31))) -16))) + (ash (setf seed (mod (+ (* 214013 seed) 2531011) (expt 2 31))) -16))) (defun split (s) (map 'list #'string s)) (defun make-deck (seed) (let ((hand (make-array 52 :fill-pointer 0)) - (rng (make-rng seed))) + (rng (make-rng seed))) (dolist (d (split "A23456789TJQK")) (dolist (s (split "♣♦♥♠")) - (vector-push (concatenate 'string d s) hand))) + (vector-push (concatenate 'string d s) hand))) (dotimes (i 52) - (rotatef (aref hand (- 51 i)) - (aref hand (mod (funcall rng) (- 52 i))))) + (rotatef (aref hand (- 51 i)) + (aref hand (mod (funcall rng) (- 52 i))))) (nreverse hand))) (defun show-deck (seed) diff --git a/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java b/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java index e9cd0afa03..497a8bf0ce 100644 --- a/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java +++ b/Task/Deal-cards-for-FreeCell/Java/deal-cards-for-freecell.java @@ -1,62 +1,62 @@ import java.util.Arrays; public class Shuffler { - - private int seed; - - private String[] deck = { - "AC", "AD", "AH", "AS", - "2C", "2D", "2H", "2S", - "3C", "3D", "3H", "3S", - "4C", "4D", "4H", "4S", - "5C", "5D", "5H", "5S", - "6C", "6D", "6H", "6S", - "7C", "7D", "7H", "7S", - "8C", "8D", "8H", "8S", - "9C", "9D", "9H", "9S", - "TC", "TD", "TH", "TS", - "JC", "JD", "JH", "JS", - "QC", "QD", "QH", "QS", - "KC", "KD", "KH", "KS", - }; - - private int random() { - seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; - return seed >> 16; - } - - //shuffled cards go to the end - private String[] getShuffledDeck() { - String[] deck = Arrays.copyOf(this.deck, this.deck.length); - for(int i = deck.length - 1; i > 0; i--) { - int r = random() % (i + 1); - String card = deck[r]; - deck[r] = deck[i]; - deck[i] = card; - } - return deck; - } - - //deal from end first - public void dealGame(int seed) { - this.seed = seed; - String[] shuffledDeck = getShuffledDeck(); - for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { - System.out.print(shuffledDeck[i]); - if(count % 8 == 0) { - System.out.println(); - } else { - System.out.print(" "); - } - } - System.out.println(); - } - - public static void main(String[] args) { - Shuffler s = new Shuffler(); - s.dealGame(1); - System.out.println(); - s.dealGame(617); - } - + + private int seed; + + private String[] deck = { + "AC", "AD", "AH", "AS", + "2C", "2D", "2H", "2S", + "3C", "3D", "3H", "3S", + "4C", "4D", "4H", "4S", + "5C", "5D", "5H", "5S", + "6C", "6D", "6H", "6S", + "7C", "7D", "7H", "7S", + "8C", "8D", "8H", "8S", + "9C", "9D", "9H", "9S", + "TC", "TD", "TH", "TS", + "JC", "JD", "JH", "JS", + "QC", "QD", "QH", "QS", + "KC", "KD", "KH", "KS", + }; + + private int random() { + seed = (214013 * seed + 2531011) & Integer.MAX_VALUE; + return seed >> 16; + } + + //shuffled cards go to the end + private String[] getShuffledDeck() { + String[] deck = Arrays.copyOf(this.deck, this.deck.length); + for(int i = deck.length - 1; i > 0; i--) { + int r = random() % (i + 1); + String card = deck[r]; + deck[r] = deck[i]; + deck[i] = card; + } + return deck; + } + + //deal from end first + public void dealGame(int seed) { + this.seed = seed; + String[] shuffledDeck = getShuffledDeck(); + for(int count = 1, i = shuffledDeck.length - 1; i >= 0; count++, i--) { + System.out.print(shuffledDeck[i]); + if(count % 8 == 0) { + System.out.println(); + } else { + System.out.print(" "); + } + } + System.out.println(); + } + + public static void main(String[] args) { + Shuffler s = new Shuffler(); + s.dealGame(1); + System.out.println(); + s.dealGame(617); + } + } diff --git a/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 b/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 index 6c81a3e2b7..3e0a0cb545 100644 --- a/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 +++ b/Task/Deal-cards-for-FreeCell/M2000-Interpreter/deal-cards-for-freecell.m2000 @@ -1,45 +1,45 @@ Module FreeCellDeal { - deal = lambda ->{ - ms_lcg = lambda ms_state=0# (seed As currency = -1) ->{ - If seed <> -1 Then - ms_state = seed Mod 2 ^ 31 - Else - ms_state = (214013 * ms_state + 2531011) Mod 2 ^ 31 - End If - = binary.shift(ms_state, -16) - } - fillbytes = lambda n=0ud ->{=n:n++} - dim cards(52) as byte< { - call void ms_lcg(game) - dim ncards() - ncards()=cards() - for i = 51 to 0 - c = ms_lcg() Mod (i +1) - Swap ncards(i), ncards(c) - next - =ncards() - } - }() ' execute now - dim dealcards() - string suit = "CDHS", value = "A23456789TJQK" - aList=(1, 617) - nList=each(alist) - while nList - Print "Game:"+array(nList) - dealcards() = deal(array(nlist)) - CardDis$ = lambda$ dealcards(), suit, value (c)-> { - s = dealcards(51 - c) Mod 4 + 1 - v = dealcards(51 - c) div 4 + 1 - =Mid$(value,v, 1)+Mid$(suit,s, 1) - } - c=0 - Do - Print CardDis$(c); - if c mod 8 < 7 then ? " "; Else ? - c++ - until c>51 - ? : ? - end while + deal = lambda ->{ + ms_lcg = lambda ms_state=0# (seed As currency = -1) ->{ + If seed <> -1 Then + ms_state = seed Mod 2 ^ 31 + Else + ms_state = (214013 * ms_state + 2531011) Mod 2 ^ 31 + End If + = binary.shift(ms_state, -16) + } + fillbytes = lambda n=0ud ->{=n:n++} + dim cards(52) as byte< { + call void ms_lcg(game) + dim ncards() + ncards()=cards() + for i = 51 to 0 + c = ms_lcg() Mod (i +1) + Swap ncards(i), ncards(c) + next + =ncards() + } + }() ' execute now + dim dealcards() + string suit = "CDHS", value = "A23456789TJQK" + aList=(1, 617) + nList=each(alist) + while nList + Print "Game:"+array(nList) + dealcards() = deal(array(nlist)) + CardDis$ = lambda$ dealcards(), suit, value (c)-> { + s = dealcards(51 - c) Mod 4 + 1 + v = dealcards(51 - c) div 4 + 1 + =Mid$(value,v, 1)+Mid$(suit,s, 1) + } + c=0 + Do + Print CardDis$(c); + if c mod 8 < 7 then ? " "; Else ? + c++ + until c>51 + ? : ? + end while } FreeCellDeal diff --git a/Task/Deal-cards-for-FreeCell/Rebol/deal-cards-for-freecell.rebol b/Task/Deal-cards-for-FreeCell/Rebol/deal-cards-for-freecell.rebol new file mode 100644 index 0000000000..2a23ed925a --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Rebol/deal-cards-for-freecell.rebol @@ -0,0 +1,37 @@ +Rebol [ + title: "Rosetta code: Deal cards for FreeCell" + file: %Deal_cards_for_FreeCell.r3 + url: https://rosettacode.org/wiki/Deal_cards_for_FreeCell +] + +deal-FreeCell: function/with [ + "Deal a FreeCell game by number" + num [integer!] +][ + deck: copy ordered-deck + state: num ; seed the MSLCG + print ["^/Game:" as-green num] + len: length? deck + while [len > 0] [ + ;; pick random remaining card and swap to end + choice: rng % len + 1 + swap (at deck choice) (at deck len) + prin [" " take/last deck] + -- len + if 4 == mod len 8 [prin "^/"] + ] + print "" +][ + ordered-deck: [] + foreach r "A23456789TJQK" [foreach s "♣♦♥♠" [ append ordered-deck ajoin [r s] ] ] + ;; Microsoft linear congruential generator + state: 0 + rng: does [ + state: (state * 214013 + 2531011) & 0#7fffffff + state >> 16 + ] +] + +deal-FreeCell 1 +deal-FreeCell 617 +deal-FreeCell 1 + random 32000 diff --git a/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.basic b/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.basic index 22303022fe..118b197ef2 100644 --- a/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.basic +++ b/Task/Deal-cards-for-FreeCell/Run-BASIC/deal-cards-for-freecell.basic @@ -1,13 +1,13 @@ -projectDir$ = "a_project" ' project directory -imageDir$ = DefaultDir$ + "\projects\" + projectDir$ + "\image\" ' directory of deck images -imagePath$ = "../";projectDir$;"/image/" ' path of deck images +projectDir$ = "a_project" ' project directory +imageDir$ = DefaultDir$ + "\projects\" + projectDir$ + "\image\" ' directory of deck images +imagePath$ = "../";projectDir$;"/image/" ' path of deck images suite$ = "C,D,H,S" ' Club,Diamond,Heart,Spades card$ = "A,2,3,4,5,6,7,8,9,T,J,Q,K" ' Cards Ace to King dim n(55) ' make ordered deck for i = 1 to 52 ' of 52 cards - n(i) = i + n(i) = i next i for i = 1 to 52 * 3 ' shuffle deck 3 times diff --git a/Task/Deal-cards-for-FreeCell/Tcl/deal-cards-for-freecell.tcl b/Task/Deal-cards-for-FreeCell/Tcl/deal-cards-for-freecell.tcl index b7f3813278..1a720c5101 100644 --- a/Task/Deal-cards-for-FreeCell/Tcl/deal-cards-for-freecell.tcl +++ b/Task/Deal-cards-for-FreeCell/Tcl/deal-cards-for-freecell.tcl @@ -6,19 +6,19 @@ proc show cards { set suits {\u2663 \u2666 \u2665 \u2660} set values {A 2 3 4 5 6 7 8 9 T J Q K} for {set i 0} {$i < 52} {incr i} { - set c [lindex $cards $i] - puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ - [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] - if {($i&7)==7 || $i==51} {puts ""} + set c [lindex $cards $i] + puts -nonewline [format " \033\[%dm%s\033\[m%s" [expr {32-(1+$c)%4/2}] \ + [lindex $suits [expr {$c % 4}]] [lindex $values [expr {$c / 4}]]] + if {($i&7)==7 || $i==51} {puts ""} } } proc deal {seed} { for {set i 0} {$i < 52} {incr i} {lappend cards [expr {51 - $i}]} for {set i 0} {$i < 51} {incr i} { - set j [expr {51 - [rnd]%(52-$i)}] - set tmp [lindex $cards $i] - lset cards $i [lindex $cards $j] - lset cards $j $tmp + set j [expr {51 - [rnd]%(52-$i)}] + set tmp [lindex $cards $i] + lset cards $i [lindex $cards $j] + lset cards $j $tmp } return $cards } diff --git a/Task/Deal-cards-for-FreeCell/UNIX-Shell/deal-cards-for-freecell.sh b/Task/Deal-cards-for-FreeCell/UNIX-Shell/deal-cards-for-freecell.sh index 99294c2331..66ce8c7fcd 100644 --- a/Task/Deal-cards-for-FreeCell/UNIX-Shell/deal-cards-for-freecell.sh +++ b/Task/Deal-cards-for-FreeCell/UNIX-Shell/deal-cards-for-freecell.sh @@ -1,22 +1,22 @@ test $# -gt 0 || set -- $((RANDOM % 32000)) for seed; do - print Game $seed: + print Game $seed: - # Shuffle deck. - deck=({A,{2..9},T,J,Q,K}{C,D,H,S}) - for i in {52..1}; do - ((seed = (214013 * seed + 2531011) & 0x7fffffff)) - ((j = (seed >> 16) % i + 1)) - t=$deck[$i] - deck[$i]=$deck[$j] - deck[$j]=$t - done + # Shuffle deck. + deck=({A,{2..9},T,J,Q,K}{C,D,H,S}) + for i in {52..1}; do + ((seed = (214013 * seed + 2531011) & 0x7fffffff)) + ((j = (seed >> 16) % i + 1)) + t=$deck[$i] + deck[$i]=$deck[$j] + deck[$j]=$t + done - # Deal cards. - print -n ' ' - for i in {52..1}; do - print -n ' '$deck[$i] - ((i % 8 == 5)) && print -n $'\n ' - done - print + # Deal cards. + print -n ' ' + for i in {52..1}; do + print -n ' '$deck[$i] + ((i % 8 == 5)) && print -n $'\n ' + done + print done diff --git a/Task/Death-Star/Ada/death-star.adb b/Task/Death-Star/Ada/death-star.adb new file mode 100644 index 0000000000..f18567ff9d --- /dev/null +++ b/Task/Death-Star/Ada/death-star.adb @@ -0,0 +1,143 @@ +with Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Generic_Real_Arrays; + +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Video.Palettes; +with SDL.Events.Events; + +procedure Death_Star is + + Width : constant := 400; + Height : constant := 400; + + package Float_Arrays is + new Ada.Numerics.Generic_Real_Arrays (Float); + use Ada.Numerics.Elementary_Functions; + use Float_Arrays; + + Window : SDL.Video.Windows.Window; + Renderer : SDL.Video.Renderers.Renderer; + + subtype Vector_3 is Real_Vector (1 .. 3); + + type Sphere_Type is record + Cx, Cy, Cz : Integer; + R : Integer; + end record; + + function Normalize (V : Vector_3) return Vector_3 is + (V / Sqrt (V * V)); + + procedure Hit (S : Sphere_Type; + X, Y : Integer; + Z1, Z2 : out Float; + Is_Hit : out Boolean) + is + NX : constant Integer := X - S.Cx; + NY : constant Integer := Y - S.Cy; + Zsq : constant Integer := S.R * S.R - (NX * NX + NY * NY); + Zsqrt : Float; + begin + if Zsq >= 0 then + Zsqrt := Sqrt (Float (Zsq)); + Z1 := Float (S.Cz) - Zsqrt; + Z2 := Float (S.Cz) + Zsqrt; + Is_Hit := True; + return; + end if; + Z1 := 0.0; + Z2 := 0.0; + Is_Hit := False; + end Hit; + + procedure Draw_Death_Star (Pos, Neg : Sphere_Type; + K, Amb : Float; + Dir : Vector_3) + is + Vec : Vector_3; + ZB1, ZB2 : Float; + ZS1, ZS2 : Float; + Is_Hit : Boolean; + S : Float; + Lum : Integer; + begin + for Y in Pos.Cy - Pos.R .. Pos.Cy + Pos.R loop + for X in Pos.Cx - Pos.R .. Pos.Cx + Pos.R loop + Hit (Pos, X, Y, ZB1, ZB2, Is_Hit); + if not Is_Hit then + goto Continue; + end if; + Hit (Neg, X, Y, ZS1, ZS2, Is_Hit); + if Is_Hit then + if ZS1 > ZB1 then + Is_Hit := False; + elsif ZS2 > ZB2 then + goto Continue; + end if; + end if; + + if Is_Hit then + Vec := (Float (Neg.Cx - X), + Float (Neg.Cy - Y), + Float (Neg.Cz) - ZS2); + else + Vec := (Float (X - Pos.Cx), + Float (Y - Pos.Cy), + ZB1 - Float (Pos.Cz)); + end if; + S := Float'Max (0.0, Dir * Normalize (Vec)); + + Lum := Integer (255.0 * (S ** K + Amb) / (1.0 + Amb)); + Lum := Integer'Max (0, Lum); + Lum := Integer'Min (Lum, 255); + + Renderer.Set_Draw_Colour ((SDL.Video.Palettes.Colour_Component (Lum), + SDL.Video.Palettes.Colour_Component (Lum), + SDL.Video.Palettes.Colour_Component (Lum), + 255)); + Renderer.Draw (Point => (SDL.C.int (X + Width / 2), + SDL.C.int (Y + Height / 2))); + <> + end loop; + end loop; + end Draw_Death_Star; + + procedure Wait is + use type SDL.Events.Event_Types; + Event : SDL.Events.Events.Events; + begin + loop + while SDL.Events.Events.Poll (Event) loop + if Event.Common.Event_Type = SDL.Events.Quit then + return; + end if; + end loop; + delay 0.100; + end loop; + end Wait; + + Direction : constant Vector_3 := Normalize ((20.0, -40.0, -10.0)); + Positive : constant Sphere_Type := (0, 0, 0, 120); + Negative : constant Sphere_Type := (-90, -90, -30, 100); +begin + if not SDL.Initialise (Flags => SDL.Enable_Screen) then + return; + end if; + + SDL.Video.Windows.Makers.Create (Win => Window, + Title => "Death star", + Position => SDL.Natural_Coordinates'(X => 10, Y => 10), + Size => SDL.Positive_Sizes'(Width, Height), + Flags => 0); + SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); + Renderer.Set_Draw_Colour ((0, 0, 0, 255)); + Renderer.Fill (Rectangle => (0, 0, Width, Height)); + + Draw_Death_Star (Positive, Negative, 1.5, 0.2, Direction); + Window.Update_Surface; + + Wait; + Window.Finalize; + SDL.Finalise; +end Death_Star; diff --git a/Task/Death-Star/V-(Vlang)/death-star.v b/Task/Death-Star/V-(Vlang)/death-star.v new file mode 100644 index 0000000000..255675b459 --- /dev/null +++ b/Task/Death-Star/V-(Vlang)/death-star.v @@ -0,0 +1,106 @@ +import math + +enum Axis { + x_ + y_ + z_ + r_ +} + +fn clamp(x f64, b f64, t f64) f64 { + if x < b { return b } + else if x > t { return t } + else { return x } +} + +fn dot(v []f64, w []f64) f64 { + return v[int(Axis.x_)] * w[int(Axis.x_)] + + v[int(Axis.y_)] * w[int(Axis.y_)] + + v[int(Axis.z_)] * w[int(Axis.z_)] +} + +fn normal(v []f64, mut result []f64) { + ilen := 1.0 / f64(math.sqrt(dot(v, v))) + result[int(Axis.x_)] = v[int(Axis.x_)] * ilen + result[int(Axis.y_)] = v[int(Axis.y_)] * ilen + result[int(Axis.z_)] = v[int(Axis.z_)] * ilen +} + +fn hit_test(s []f64, x f64, y f64, mut result []f64) bool { + mut z := s[int(Axis.r_)] * s[int(Axis.r_)] - (x - s[int(Axis.x_)]) * (x - s[int(Axis.x_)]) - + (y - s[int(Axis.y_)]) * (y - s[int(Axis.y_)]) + if z >= 0 { + z = math.sqrt(z) + result[0] = s[int(Axis.z_)] - z + result[1] = s[int(Axis.z_)] + z + return true + } + else { return false } +} + +fn death_star(posic []f64, neg []f64, sun []f64, k f64, amb f64) { + mut xx, mut temp1, mut temp2 := []f64{len: 3}, []f64{len: 3}, []f64{len: 3} + mut hp, mut hn := []f64{len: 2}, []f64{len: 2} + mut result_val, mut shade := 0, -1 + shades := [' ', '.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'] + y_start := int(posic[int(Axis.y_)] - posic[int(Axis.r_)] - 0.5) + y_end := int(posic[int(Axis.y_)] + posic[int(Axis.r_)] + 0.5) + x_start := int(posic[int(Axis.x_)] - posic[int(Axis.r_)] - 0.5) + x_end := int(posic[int(Axis.x_)] + posic[int(Axis.r_)] + 0.5) + for y in y_start .. y_end + 1 { + mut line := '' + for x in x_start .. x_end + 1 { + result_val = 0 + if !hit_test(posic, f64(x), f64(y), mut hp) { result_val = 0 } + else if !hit_test(neg, f64(x), f64(y), mut hn) { result_val = 1 } + else if hn[0] > hp[0] { result_val = 1 } + else if hn[1] > hp[1] { result_val = 0 } + else if hn[1] > hp[0] { result_val = 2 } + else { result_val = 1 } + shade = -1 + match result_val { + 0 { + shade = 0 + } + 1 { + temp1[int(Axis.x_)] = f64(x) - posic[int(Axis.x_)] + temp1[int(Axis.y_)] = f64(y) - posic[int(Axis.y_)] + temp1[int(Axis.z_)] = hp[0] - posic[int(Axis.z_)] + normal(temp1, mut xx) + } + 2 { + temp2[int(Axis.x_)] = neg[int(Axis.x_)] - f64(x) + temp2[int(Axis.y_)] = neg[int(Axis.y_)] - f64(y) + temp2[int(Axis.z_)] = neg[int(Axis.z_)] - hn[1] + normal(temp2, mut xx) + } + else {} + } + + if shade != 0 { + b := math.pow(dot(sun, xx), k) + amb + shade = int(clamp((1.0 - b) * f64(shades.len - 1), 1, f64(shades.len - 1))) + } + line += shades[shade].str() + } + println(line) + } +} + +fn main() { + mut posic, mut neg := []f64{len: 4}, []f64{len: 4} + mut temp3, mut sun := []f64{len: 3}, []f64{len: 3} + posic[int(Axis.x_)] = 20 + posic[int(Axis.y_)] = 20 + posic[int(Axis.z_)] = 0 + posic[int(Axis.r_)] = 20 + neg[int(Axis.x_)] = 10 + neg[int(Axis.y_)] = 10 + neg[int(Axis.z_)] = -15 + neg[int(Axis.r_)] = 10 + temp3[0] = -2 + temp3[1] = 1 + temp3[2] = 3 + normal(temp3, mut sun) + death_star(posic, neg, sun, 2, 0.1) +} diff --git a/Task/Death-Star/VBScript/death-star.vbs b/Task/Death-Star/VBScript/death-star.vbs new file mode 100644 index 0000000000..84f38f79e2 --- /dev/null +++ b/Task/Death-Star/VBScript/death-star.vbs @@ -0,0 +1,81 @@ +'deathstar ascii graphics + +option explicit + +const x_=0 +const y_=1 +const z_=2 +const r_=3 + +function clamp(x,b,t) + if xt then + clamp =t + else + clamp=x + end if +end function + +function dot(v,w) dot=v(x_)*w(x_)+v(y_)*w(y_)+v(z_)*w(z_): end function + +function normal (byval v) + dim ilen:ilen=1/sqr(dot(v,v)): + v(x_)=v(x_)*ilen: v(y_)=v(y_)*ilen: v(z_)=v(z_)*ilen: + normal=v: +end function + +function hittest(s,x,y) + dim z + z = s(r_)^2 - (x-s(x_))^2 - (y-s(y_))^2 + if z>=0 then + z=sqr(z) + hittest=array(s(z_)-z,s(z_)+z) + else + hittest=0 + end if +end function + +sub deathstar(pos, neg, sun, k, amb) + dim x,y,shades,result,shade,hp,hn,xx,b + shades=array(" ",".",":","!","*","o","e","&","#","%","@") + for y = pos(y_)-pos(r_)-0.5 to pos(y_)+pos(r_)+0.5 + for x = pos(x_)-pos(r_)-0.5 to pos(x_)+pos(r_)+.5 + hp=hittest (pos, x, y) + hn=hittest(neg,x,y) + if not isarray(hp) then + result=0 + elseif not isarray(hn) then + result=1 + elseif hn(0)>hp(0) then + result=1 + elseif hn(1)>hp(1) then + result=0 + elseif hn(1)>hp(0) then + result=2 + else + result=1 + end if + + shade=-1 + select case result + case 0 + shade=0 + case 1 + xx=normal(array(x-pos(x_),y-pos(y_),hp(0)-pos(z_))) + 'shade=clamp(1-dot(sun,xx)^k+amb,1,ubound(shades)) + case 2 + xx=normal(array(neg(x_)-x,neg(y_)-y,neg(z_)-hn(1))) + 'shade=clamp(1-dot(sun,xx)^k+amb,1,ubound(shades)) + end select + if shade <>0 then + b=dot(sun,xx)^k+amb + shade=clamp((1-b) *ubound(shades),1,ubound(shades)) + end if + wscript.stdout.write string(2,shades(shade)) + next + wscript.stdout.write vbcrlf + next +end sub + +deathstar array(20, 20, 0, 20),array(10,10,-15,10), normal(array(-2,1,3)), 2, 0.1 diff --git a/Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers-1.pas b/Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers-1.pas new file mode 100644 index 0000000000..24956c1e24 --- /dev/null +++ b/Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers-1.pas @@ -0,0 +1,117 @@ +program DeceptiveNumbers; +{$IfDef FPC} {$Optimization ON,ALL} {$ENDIF} +{$IfDef Windows} {$APPTYPE CONSOLE} {$ENDIF} +uses + sysutils; +const + LIMIT = 100000;//1E6 at home takes over (5 min) now 1m10s + RepInitLen = 13; //Uint64 19 decimal digits -> max 6 digits divisor + DecimalDigits = 10*1000*1000*1000*1000;//1E13 + RepLimit = (DecimalDigits-1)DIV 9;//RepInitLen '1' + +type + tmyUint64 = array[0..Limit DIV RepInitLen+1] of Uint64; +var + {$Align 32} + K: tmyUint64; + {$Align 32} + MaxKIdx : Int32; + +procedure OutK(const K:tmyUint64); +var + i : Uint32; +begin + For i := MaxKidx downto 0 do + begin + write(k[i]:13); + end; + writeln; +end; + +function isPrime(n: UInt64):boolean; +var + p: Uint64; +begin + if n in [2,3,5,7,11,13,17,19,23,29] then + EXIT(true); + + if Not ODD(n) OR ( n MOD 3 = 0) then + EXIT(false); + p := 5; + repeat + if (n mod p=0)or(n mod(p+2)=0) then + EXIT(false); + p +=6; + until p*p>n; + Exit(true); +end; + +procedure ExtendRep(var K:tmyUint64;n:NativeUint); +var + q : Uint64; + i : Int32; +begin + n -= MaxKidx*RepInitLen; + i := MaxKidx; + while RepInitLen<=n do + begin + K[i] := RepLimit; + inc(i); + dec(n,RepInitLen); + end; + if n = 0 then + Exit; + MaxKidx := i; + q := 1; + while n LIMIT then + BREAK; + idx35 := (idx35+1) AND 7; + if isprime(i) then + continue; + ExtendRep(k,i-1); + IF GetModK(K,i)=0 then + Begin + inc(cnt); + write(i:6,','); + if cnt Mod 10 = 0 then + writeln; + end; + until false; + {$IfDef Windows} + readln; + {$ENDIF} +END. diff --git a/Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers-2.pas b/Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers-2.pas new file mode 100644 index 0000000000..2a598322af --- /dev/null +++ b/Task/Deceptive-numbers/Free-Pascal-Lazarus/deceptive-numbers-2.pas @@ -0,0 +1,67 @@ +program DeceptiveNumbers; +{$IfDef FPC} {$MODE DELPHI}{$Optimization ON,ALL} {$ENDIF} +{$IfDef Windows} {$APPTYPE CONSOLE} {$ENDIF} +uses + sysutils; +const + LIMIT = 1000; + +function OutN(n,count:Uint64):Uint64; +begin + result := count; + If result mod 8 = 0 then + write(#13#10,count:6); + write(n:10); + inc(result); +end; + +function isPrime(n: UInt64):boolean; +var + p: Uint64; +begin + if n <32 then + if n in [2,3,5,7,11,13,17,19,23,29,31] then + EXIT(true); + + if Not ODD(n) OR ( n MOD 3 = 0) then + EXIT(false); + p := 5; + repeat + if (n mod p=0)or(n mod(p+2)=0) then + EXIT(false); + p +=6; + until p*p>n; + Exit(true); +end; + +function powMod(n,pow,rest: Uint64): Uint64; +begin + result := 1; + while pow > 0 do + begin + if pow mod 2 <> 0 then + result := (result * n) mod rest; + pow := pow div 2; + n := sqr(n) mod rest; + end; +end; + +const + NextNotMulOf235 : array[0..7] of Uint32 = (6,4,2,4,2,4,6,2); +var + n,count,idx235:Uint64; +begin + idx235 := 0; + n := 1; + count := 0; + writeln(' count +1 2 3 4 5 6 7 8'); + repeat + //simple isprime takes mostly more time than powMod + if (powMod(10, n-1, n) = 1) AND Not(isPrime(n)) then + count := OutN(n,count); + inc(n,NextNotMulOf235[idx235]); + idx235 :=(idx235+1) AND 7; + until count >=LIMIT; + + writeln; +END. diff --git a/Task/Deceptive-numbers/FutureBasic/deceptive-numbers.basic b/Task/Deceptive-numbers/FutureBasic/deceptive-numbers.basic new file mode 100644 index 0000000000..7bcd7c556c --- /dev/null +++ b/Task/Deceptive-numbers/FutureBasic/deceptive-numbers.basic @@ -0,0 +1,84 @@ +// ------------------------------------------------------------ +// Deceptive numbers +// Using FutureBasic 7.0.36 +// November 2025, R.W. +// +// A composite n such that n | R_{n-1}, where +// R_k = (10^k - 1) / 9 is the k-digit repunit. +// ------------------------------------------------------------ + +include "gmp.incl" + +_kPrimeReps = 25 // Miller–Rabin rounds for mpz_probab_prime_p +_kDeceptiveLimit = 152 //should fit in the window +CFTimeInterval t + +// ------------------------------------------------------------ +// Probable prime test using GMP +// Returns _true if n is (probably) prime, _false otherwise. +// ------------------------------------------------------------ +local fn IsProbablePrime( n as UInt32 ) as Boolean + mpz_t z + int r + if n < 2 then RETURN _false + mpz_init( z ) + fn mpz_set_ui( z, n ) + r = fn mpz_probab_prime_p( z, _kPrimeReps ) + mpz_clear( z ) + if r > 0 then RETURN _true +end fn = _false + +// ------------------------------------------------------------ +// Find and print the first `limit` deceptive numbers +// ------------------------------------------------------------ +local fn PrintDeceptiveNumbers( limit as Int ) + mpz_t repunit + long n + int count + mpz_init( repunit ) + fn mpz_set_ui( repunit, 0 ) + n = 1 + count = 0 + print @"\nThe first "; limit; @" deceptive numbers are:\n" + t = fn CACurrentMediaTime + + while (count < limit) + // Only odd n; repunit holds R_{n-1} + n = n + 2 + // repunit = repunit * 100 + 11 + // This appends two '1' digits each step: + // 0 → 11 → 1111 → 111111 → ... + fn mpz_mul_ui( repunit, repunit, 100 ) + fn mpz_add_ui( repunit, repunit, 11 ) + + // Skip all multiples of 3 or 5. + + if ( (n MOD 3) != 0 ) && ( (n MOD 5) != 0 ) + // We want composite n, so reject primes. + if fn IsProbablePrime( n ) == _false + // Check if repunit is divisible by n + if fn mpz_divisible_ui_p( repunit, n ) != 0 + count = count + 1 + CFStringRef s = fn CFStringCreateWithFormat¬ + ( _kCFAllocatorDefault, 0, @"%8ld ", n ) + print s; + CFRelease( s ) + if (count MOD 8) == 0 then print + end if + end if + end if + wend + // Tidy final newline if the last row wasn't complete + if (count MOD 8) != 0 then print + printf @"\nElapsed time: %.3f secs", (fn CACurrentMediaTime-t) + mpz_clear( repunit ) +end fn + +// ------------------------------------------------------------ +// Main +// ------------------------------------------------------------ +Window 1,@"Deceptive Numbers" + +fn PrintDeceptiveNumbers( _kDeceptiveLimit ) + +HandleEvents diff --git a/Task/Deceptive-numbers/Haskell/deceptive-numbers.hs b/Task/Deceptive-numbers/Haskell/deceptive-numbers.hs new file mode 100644 index 0000000000..9f48b64a53 --- /dev/null +++ b/Task/Deceptive-numbers/Haskell/deceptive-numbers.hs @@ -0,0 +1,24 @@ +import Data.Numbers.Primes +import Data.List + +-- Translation of Wren ver1 +deceptives1 :: [Int] +deceptives1 = + [ n + | (n, r) <- zip [17, 19 ..] (iterate ((11 +) . (100 *)) 1111111111111111) + , not $ isPrime n, mod n 3 /= 0, mod n 5 /= 0, mod r (fromIntegral n) == 0 + ] + +-- Translation of Wren ver2 +deceptives2 :: [Int] +deceptives2 = + [ n + | n <- [49, 51 ..], mod n 3 /= 0, mod n 5 /= 0 + , not $ isPrime n, modPower (9 * n) 10 (pred n) == 1] + +modPower :: Int -> Int -> Int -> Int +modPower base a b = foldl' mul 1 [p | (True, p) <- zip bs ps] + where + mul x y = mod (x * y) base + bs = map odd $ takeWhile (0 <) $ iterate (flip div 2) b + ps = iterate (\x -> mul x x) a diff --git a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur index 615ec14669..456016e51d 100644 --- a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur +++ b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur @@ -1,6 +1,6 @@ -val isPrime = fn(i) { +val isPrime = fn(i number) { i == 2 or i > 2 and - not any(series(2 .. i ^/ 2, asconly=true), by=fn x:i div x) + not any(series(2 .. i ^/ 2, asconly=true), by=fn(x) { i div x }) } var nums = [] diff --git a/Task/Deceptive-numbers/Pluto/deceptive-numbers.pluto b/Task/Deceptive-numbers/Pluto/deceptive-numbers.pluto new file mode 100644 index 0000000000..d6c6725526 --- /dev/null +++ b/Task/Deceptive-numbers/Pluto/deceptive-numbers.pluto @@ -0,0 +1,16 @@ +local int = require "int" +local fmt = require "fmt" + +local count = 0 +local limit = 62 +local n = 49 +local deceptive = {} +while count < limit do + if !int.isprime(n) and n % 3 != 0 and n % 5 != 0 and int.modpow(10, n-1, n) == 1 then + deceptive:insert(n) + count += 1 + end + n += 2 +end +print($"The first {limit} deceptive numbers are:") +fmt.tprint("%5d ", deceptive, 9) diff --git a/Task/Deceptive-numbers/R/deceptive-numbers.r b/Task/Deceptive-numbers/R/deceptive-numbers.r new file mode 100644 index 0000000000..ed5f0d4818 --- /dev/null +++ b/Task/Deceptive-numbers/R/deceptive-numbers.r @@ -0,0 +1,15 @@ +library(gmp) + +repunit <- function(n) as.bigz(strrep("1", n)) + +n <- 9 +count <- 0 +while(count<50){ + if(repunit(n-1)%%n==0){ + if(isprime(n)==0){ + count <- count+1 + cat(n, "", rep("\n", count%%10==0)) + } + } + n <- n+2 +} diff --git a/Task/Deceptive-numbers/REXX/deceptive-numbers.rexx b/Task/Deceptive-numbers/REXX/deceptive-numbers.rexx new file mode 100644 index 0000000000..6175bfe63b --- /dev/null +++ b/Task/Deceptive-numbers/REXX/deceptive-numbers.rexx @@ -0,0 +1,60 @@ +/* REXX */ +Numeric Digits 100 +count=0 +ol='' +Call Time 'R' +Do n=7 by 1 While count<200 + if isDeceptive(n) Then Do + count+=1 + Call o n + End + End +Say ol time('E') 'seconds' +exit + +isDeceptive: procedure expose count + Parse Arg n + If n//2>0 & n//3>0 & n//5>0 Then Do + If modulusPower(10,N-1,N)=1 Then Do + Do divisor=7 By 6 while divisor*divisor<=n + If n//divisor=0 | n//(divisor+4)=0 Then Do + Return 1 + End + End + End + Return 0 + End + Return 0 + +modulusPower: Procedure + Parse Arg Base,Exponent,Modulus + Call dbg 'ModP Base='Base 'Exponent='Exponent 'Modulus='Modulus + If Modulus=1 Then + Return 0 + Base=Base//Modulus + Call dbg 'Base='Base + res=1 + Do While Exponent>0 + If exponent//2>0 Then Do + res=res*base//modulus + Call dbg 'result='res + End + Call dbg 'base='base 'modulus='modulus + base=(base*base)//modulus + Call dbg 'base='base + exponent=exponent%2 + Call dbg 'exponent='exponent + End + Call dbg 'result='res + Return res + +o: +ol=ol right(arg(1),6) +If count//10=0 Then Do + Say substr(ol,2) + ol='' + End +Return + +dbg: +Return diff --git a/Task/Deceptive-numbers/Unicon/deceptive-numbers.unicon b/Task/Deceptive-numbers/Unicon/deceptive-numbers.unicon new file mode 100644 index 0000000000..4f089ccf9e --- /dev/null +++ b/Task/Deceptive-numbers/Unicon/deceptive-numbers.unicon @@ -0,0 +1,21 @@ +link fastprime + +procedure main(A) + limit := \A[1] | 10 + every writes(" ",deceptive()\limit) + write() +end + +procedure deceptive() + every n := seq(2) do { + if not is_prime(n) then { + r := repunit(10,n-1) + if (r/n*n) = r then suspend n + } + } +end + +procedure repunit(b,n) + every (r := 0) +:= b^(0 to n-1) + return r +end diff --git a/Task/Deconvolution-1D/Ada/deconvolution-1d.adb b/Task/Deconvolution-1D/Ada/deconvolution-1d.adb new file mode 100644 index 0000000000..ee058294bd --- /dev/null +++ b/Task/Deconvolution-1D/Ada/deconvolution-1d.adb @@ -0,0 +1,53 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Main is + package real_io is new Float_IO (Long_Float); + use real_io; + + type Vector is array (Natural range <>) of Long_Float; + + function deconv (g, f : Vector) return Vector is + len : Positive := + Integer'Max ((g'Length - f'length), (f'length - g'length)); + h : Vector (0 .. len); + Lower : Natural := 0; + begin + for n in h'range loop + h (n) := g (n); + if n >= f'length then + Lower := n - f'length + 1; + end if; + for i in Lower .. n - 1 loop + h (n) := h (n) - (h (i) * f (n - i)); + end loop; + h (n) := h (n) / f (0); + end loop; + return h; + end deconv; + + procedure print (v : Vector) is + begin + Put ("("); + for I in v'range loop + Put (Item => v (I), Fore => 1, Aft => 1, Exp => 0); + if I < v'Last then + Put (" "); + else + Put_Line (")"); + end if; + end loop; + end print; + + h : Vector := (-8.0, -9.0, -3.0, -1.0, -6.0, 7.0); + f : Vector := + (-3.0, -6.0, -1.0, 8.0, -6.0, 3.0, -1.0, -9.0, -9.0, 3.0, -2.0, 5.0, 2.0, + -2.0, -7.0, -1.0); + g : Vector := + (24.0, 75.0, 71.0, -34.0, 3.0, 22.0, -45.0, 23.0, 245.0, 25.0, 52.0, 25.0, + -67.0, -96.0, 96.0, 31.0, 55.0, 36.0, 29.0, -43.0, -7.0); +begin + print (h); + print (deconv (g, f)); + print (f); + print (deconv (g, h)); +end Main; diff --git a/Task/Deepcopy/Ada/deepcopy.adb b/Task/Deepcopy/Ada/deepcopy.adb new file mode 100644 index 0000000000..3c60136c46 --- /dev/null +++ b/Task/Deepcopy/Ada/deepcopy.adb @@ -0,0 +1,16 @@ +with Ada.Containers.Doubly_Linked_Lists; +with Ada.Text_IO; + +procedure Deepcopy is + package List is new Ada.Containers.Doubly_Linked_Lists (Integer); + L1, L2 : List.List; +begin + L1 := List.Empty_List; + L1.Append (1); + L1.Append (2); + L2 := L1; + L2.Append (3); + + Ada.Text_IO.Put_Line + ("L1.Length = " & L1.Length'Image & " L2.Length = " & L2.Length'Image); +end Deepcopy; diff --git a/Task/Deepcopy/Pluto/deepcopy.pluto b/Task/Deepcopy/Pluto/deepcopy.pluto new file mode 100644 index 0000000000..4357a2c90d --- /dev/null +++ b/Task/Deepcopy/Pluto/deepcopy.pluto @@ -0,0 +1,12 @@ +local t = { + a = { + b = { + c = {} + } + } +} +local t1 = t:clone(1) +assert(t1.a == t.a) -- depth 1 does not copy nested tables +local t2 = t:clone(2) +assert(t2.a != t.a) -- 'a' is cloned +assert(t2.a.b == t.a.b) -- but 'b' is shared diff --git a/Task/Deepcopy/R/deepcopy.r b/Task/Deepcopy/R/deepcopy.r new file mode 100644 index 0000000000..c924abb187 --- /dev/null +++ b/Task/Deepcopy/R/deepcopy.r @@ -0,0 +1,5 @@ +a <- list(matrix(1:4, 2, 2), women, list(month.abb, pi), exp) +b <- a +b[[3]][[2]][1] <- 3.2 +print(a) +print(b) diff --git a/Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-1.adb b/Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-1.adb new file mode 100644 index 0000000000..9f9f165eff --- /dev/null +++ b/Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-1.adb @@ -0,0 +1 @@ +type My_Type is range 1..10; diff --git a/Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-2.adb b/Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-2.adb new file mode 100644 index 0000000000..d7bbcfc1ac --- /dev/null +++ b/Task/Define-a-primitive-data-type/Ada/define-a-primitive-data-type-2.adb @@ -0,0 +1,2 @@ +A : My_Type := 3; +B : My_Type := A; diff --git a/Task/Define-a-primitive-data-type/Euphoria/define-a-primitive-data-type.eu b/Task/Define-a-primitive-data-type/Euphoria/define-a-primitive-data-type.eu new file mode 100644 index 0000000000..9113cb3e37 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Euphoria/define-a-primitive-data-type.eu @@ -0,0 +1,3 @@ +type My_Type(integer i) + return i >= 1 and i <= 10 +end type diff --git a/Task/Define-a-primitive-data-type/F-Sharp/define-a-primitive-data-type.fs b/Task/Define-a-primitive-data-type/F-Sharp/define-a-primitive-data-type.fs new file mode 100644 index 0000000000..b246d69660 --- /dev/null +++ b/Task/Define-a-primitive-data-type/F-Sharp/define-a-primitive-data-type.fs @@ -0,0 +1,14 @@ +exception Out_of_bounds +type 'a bounds = { min: 'a; max: 'a } +type 'a bounded = { value: 'a; bounds: 'a bounds } +let mk_bounds min max = { min=min; max=max } +let check_bounds value bounds = if value < bounds.min || value > bounds.max then raise Out_of_bounds +let mk_bounded value bounds = check_bounds value bounds; { value=value; bounds=bounds } +let op f a b = + if a.bounds <> b.bounds then raise(System.Exception "different bounds") + let res = f a.value b.value in check_bounds res a.bounds + (mk_bounded res a.bounds) +let range = mk_bounds 1 10 +let a,b=mk_bounded 2 range,mk_bounded 6 range +printfn "%A" (op ( + ) a b) +try printfn "%A" (op ( * ) a b) with ex->printfn "%s" (ex.ToString()) diff --git a/Task/Define-a-primitive-data-type/PowerShell/define-a-primitive-data-type.ps1 b/Task/Define-a-primitive-data-type/PowerShell/define-a-primitive-data-type.ps1 new file mode 100644 index 0000000000..8b78144b4c --- /dev/null +++ b/Task/Define-a-primitive-data-type/PowerShell/define-a-primitive-data-type.ps1 @@ -0,0 +1 @@ +[Int][ValidateRange(1,10)]$n = 3 # $n can only accept integers between 1 and 10 diff --git a/Task/Delegates/Ada/delegates.adb b/Task/Delegates/Ada/delegates.adb new file mode 100644 index 0000000000..2982a78c8c --- /dev/null +++ b/Task/Delegates/Ada/delegates.adb @@ -0,0 +1,48 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Delegation is + package Things is + -- We need a common root for our stuff + type Object is tagged null record; + type Object_Ptr is access all Object'Class; + + -- Objects that have operation thing + type Substantial is new Object with null record; + function Thing (X : Substantial) return String; + + -- Delegator objects + type Delegator is new Object with record + Delegate : Object_Ptr; + end record; + function Operation (X : Delegator) return String; + + No_Thing : aliased Object; -- Does not have thing + Has_Thing : aliased Substantial; -- Has one + end Things; + + package body Things is + function Thing (X : Substantial) return String is + begin + return "delegate implementation"; + end Thing; + + function Operation (X : Delegator) return String is + begin + if X.Delegate /= null and then X.Delegate.all in Substantial'Class then + return Thing (Substantial'Class (X.Delegate.all)); + else + return "default implementation"; + end if; + end Operation; + end Things; + + use Things; + + A : Delegator; -- Without a delegate +begin + Put_Line (A.Operation); + A.Delegate := No_Thing'Access; -- Set no thing + Put_Line (A.Operation); + A.Delegate := Has_Thing'Access; -- Set a thing + Put_Line (A.Operation); +end Delegation; diff --git a/Task/Delegates/Pluto/delegates.pluto b/Task/Delegates/Pluto/delegates.pluto new file mode 100644 index 0000000000..0d3b9ce9ce --- /dev/null +++ b/Task/Delegates/Pluto/delegates.pluto @@ -0,0 +1,40 @@ +class thingable + function thing() end +end + +-- Delegate that doesn't implement thingable. +class delegate + function __construct() end +end + +-- Delegate that implements thingable. +class delegate2 extends thingable + function __construct() end + + function thing() return "delegate implementation" end +end + +class delegator + function __construct() + self.delegate = nil + end + + function operation() + if !self.delegate or !(self.delegate instanceof thingable) then + return "default implementation" + end + return self.delegate:thing() + end +end + +-- Without a delegate. +local d = new delegator() +print(d:operation()) + +-- With a delegate that doesn't implement thingable. +d.delegate = new delegate() +print(d:operation()) + +-- With a delegate that does implement thingable. +d.delegate = new delegate2() +print(d:operation()) diff --git a/Task/Delete-a-file/Ada/delete-a-file-1.adb b/Task/Delete-a-file/Ada/delete-a-file-1.adb new file mode 100644 index 0000000000..e815e40331 --- /dev/null +++ b/Task/Delete-a-file/Ada/delete-a-file-1.adb @@ -0,0 +1 @@ +with Ada.Directories; use Ada.Directories; diff --git a/Task/Delete-a-file/Ada/delete-a-file-2.adb b/Task/Delete-a-file/Ada/delete-a-file-2.adb new file mode 100644 index 0000000000..78bb0709fc --- /dev/null +++ b/Task/Delete-a-file/Ada/delete-a-file-2.adb @@ -0,0 +1,4 @@ +Delete_File ("input.txt"); +Delete_File ("/input.txt"); +Delete_Tree ("docs"); +Delete_Tree ("/docs"); diff --git a/Task/Delete-a-file/COBOL/delete-a-file-1.cob b/Task/Delete-a-file/COBOL/delete-a-file-1.cob new file mode 100644 index 0000000000..5c4fc1105e --- /dev/null +++ b/Task/Delete-a-file/COBOL/delete-a-file-1.cob @@ -0,0 +1,22 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Delete-Files. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT Local-File ASSIGN TO "input.txt". + SELECT Root-File ASSIGN TO "/input.txt". + + DATA DIVISION. + FILE SECTION. + FD Local-File. + 01 Local-Record PIC X. + FD Root-File. + 01 Root-Record PIC X. + + PROCEDURE DIVISION. + DELETE FILE Local-File + DELETE FILE Root-File + GOBACK. + + END PROGRAM Delete-Files. diff --git a/Task/Delete-a-file/COBOL/delete-a-file-2.cob b/Task/Delete-a-file/COBOL/delete-a-file-2.cob new file mode 100644 index 0000000000..6c69dd0a47 --- /dev/null +++ b/Task/Delete-a-file/COBOL/delete-a-file-2.cob @@ -0,0 +1,12 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Delete-Files. + + PROCEDURE DIVISION. + CALL "CBL_DELETE_FILE" USING "input.txt" + CALL "CBL_DELETE_DIR" USING "docs" + CALL "CBL_DELETE_FILE" USING "/input.txt" + CALL "CBL_DELETE_DIR" USING "/docs" + + GOBACK. + + END PROGRAM Delete-Files. diff --git a/Task/Delete-a-file/Emacs-Lisp/delete-a-file.el b/Task/Delete-a-file/Emacs-Lisp/delete-a-file.el new file mode 100644 index 0000000000..3b85c608b6 --- /dev/null +++ b/Task/Delete-a-file/Emacs-Lisp/delete-a-file.el @@ -0,0 +1,4 @@ +(delete-file "input.txt") +(delete-directory "docs") +(delete-file "/input.txt") +(delete-directory "/docs") diff --git a/Task/Delete-a-file/Gleam/delete-a-file.gleam b/Task/Delete-a-file/Gleam/delete-a-file.gleam new file mode 100644 index 0000000000..d6a4fd0962 --- /dev/null +++ b/Task/Delete-a-file/Gleam/delete-a-file.gleam @@ -0,0 +1,9 @@ +import simplifile + +pub fn main() { + // simplifile.delete function deletes a file or directory. + let assert Ok(_) = simplifile.delete("docs") + let assert Ok(_) = simplifile.delete("input.txt") + let assert Ok(_) = simplifile.delete("/docs") + let assert Ok(_) = simplifile.delete("/input.txt") +} diff --git a/Task/Delete-a-file/PowerShell/delete-a-file.ps1 b/Task/Delete-a-file/PowerShell/delete-a-file.ps1 new file mode 100644 index 0000000000..2ff0e5ae32 --- /dev/null +++ b/Task/Delete-a-file/PowerShell/delete-a-file.ps1 @@ -0,0 +1,6 @@ +# possible aliases for Remove-Item: rm, del, ri +Remove-Item input.txt +Remove-Item \input.txt # file system root + +Remove-Item -Recurse docs # recurse for deleting folders including content +Remove-Item -Recurse \docs diff --git a/Task/Delete-a-file/Rebol/delete-a-file.rebol b/Task/Delete-a-file/Rebol/delete-a-file.rebol new file mode 100644 index 0000000000..42b1466d1e --- /dev/null +++ b/Task/Delete-a-file/Rebol/delete-a-file.rebol @@ -0,0 +1,7 @@ +; Local. +delete %input.txt +delete-dir %docs/ + +; Root. +delete %/input.txt +delete-dir %/docs/ diff --git a/Task/Delete-a-file/Rye/delete-a-file.rye b/Task/Delete-a-file/Rye/delete-a-file.rye new file mode 100644 index 0000000000..2f026f3100 --- /dev/null +++ b/Task/Delete-a-file/Rye/delete-a-file.rye @@ -0,0 +1,5 @@ +rm %input.txt +rmdir %docs + +rm %/input.txt +rmdir %/docs diff --git a/Task/Delete-a-file/Uiua/delete-a-file.uiua b/Task/Delete-a-file/Uiua/delete-a-file.uiua new file mode 100644 index 0000000000..84b53379da --- /dev/null +++ b/Task/Delete-a-file/Uiua/delete-a-file.uiua @@ -0,0 +1,2 @@ +&fde "example.txt" # delete +&ftr "example.txt" # move to trash diff --git a/Task/Delete-a-file/VBScript/delete-a-file.vbs b/Task/Delete-a-file/VBScript/delete-a-file.vbs new file mode 100644 index 0000000000..a18a05092f --- /dev/null +++ b/Task/Delete-a-file/VBScript/delete-a-file.vbs @@ -0,0 +1,21 @@ +Set oFSO = CreateObject( "Scripting.FileSystemObject" ) + +oFSO.DeleteFile "input.txt" +oFSO.DeleteFolder "docs" + +oFSO.DeleteFile "\input.txt" +oFSO.DeleteFolder "\docs" + +'Using Delete on file and folder objects + +dim fil, fld + +set fil = oFSO.GetFile( "input.txt" ) +fil.Delete +set fld = oFSO.GetFolder( "docs" ) +fld.Delete + +set fil = oFSO.GetFile( "\input.txt" ) +fil.Delete +set fld = oFSO.GetFolder( "\docs" ) +fld.Delete diff --git a/Task/Demings-funnel/Ada/demings-funnel.adb b/Task/Demings-funnel/Ada/demings-funnel.adb new file mode 100644 index 0000000000..d04a53cd8b --- /dev/null +++ b/Task/Demings-funnel/Ada/demings-funnel.adb @@ -0,0 +1,105 @@ +with Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; + +procedure Demings_Funnel is + + type Float_List is array (Positive range <>) of Float; + + Dxs : constant Float_List := + (-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); + + Dys : constant Float_List := + ( 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); + + type Rule_Access is access function (Z, Dz : Float) return Float; + + function Funnel (List : in Float_List; + Rule : in Rule_Access) + return Float_List + is + Correc : Float := 0.0; + Result : Float_List (List'Range); + begin + for I in List'Range loop + Result (I) := Correc + List (I); + Correc := Rule (Correc, List (I)); + end loop; + return Result; + end Funnel; + + function Mean (List : in Float_List) + return Float + is + Sum : Float := 0.0; + begin + for Value of List loop + Sum := Sum + Value; + end loop; + return Sum / Float (List'Length); + end Mean; + + function Stddev (List : in Float_List) + return Float + is + use Ada.Numerics.Elementary_Functions; + M : constant Float := Mean (List); + Sum : Float := 0.0; + begin + for F of List loop + Sum := Sum + (F - M) * (F - M); + end loop; + return Sqrt (Sum / Float (List'Length)); + end Stddev; + + procedure Experiment (Label : in String; + Rule : in Rule_Access) + is + package Float_IO is new Ada.Text_IO.Float_IO (Float); + use Ada.Text_IO; + use Float_IO; + Rxs : constant Float_List := Funnel (Dxs, Rule); + Rys : constant Float_List := Funnel (Dys, Rule); + begin + Default_Exp := 0; + Default_Fore := 4; + Default_Aft := 4; + Put_Line (Label & " : x y"); + Put ("Mean: "); Put (Mean (Rxs)); Put (Mean (Rys)); New_Line; + Put ("StdDev: "); Put (Stddev (Rxs)); Put (Stddev (Rys)); New_Line; + New_Line; + end Experiment; + + function Rule_1 (Z, Dz : Float) return Float is (0.0); + function Rule_2 (Z, Dz : Float) return Float is (-Dz); + function Rule_3 (Z, Dz : Float) return Float is (-Z - Dz); + function Rule_4 (Z, Dz : Float) return Float is (Z + Dz); +begin + Experiment ("Rule 1", Rule_1'Access); + Experiment ("Rule 2", Rule_2'Access); + Experiment ("Rule 3", Rule_3'Access); + Experiment ("Rule 4", Rule_4'Access); +end Demings_Funnel; diff --git a/Task/Demings-funnel/Fortran/demings-funnel.f b/Task/Demings-funnel/Fortran/demings-funnel.f new file mode 100644 index 0000000000..8e5a1182a8 --- /dev/null +++ b/Task/Demings-funnel/Fortran/demings-funnel.f @@ -0,0 +1,236 @@ +! +! Deming's funnel +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran V8.6-001 does not/not yet compile this code +! because it cannot initialize variables using intrinsic functions +! U.B., December 2025 +!============================================================================== +program DemingsFunnel + +implicit none + +real, parameter :: dx(*) = & + [-0.533, 0.27, 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.15, 0.001, -0.382, 0.161, 0.915, & + 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, & + 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -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.17, 0.054, -0.553, -0.024, -0.181, -0.7, -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.31, 0.171, 0.0, 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],& + dy(*) = & + [0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, & + -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, & + -0.742, -0.01, 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.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, & + -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, & + -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -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.65, -1.103, 0.154, -1.72, 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] + + + integer, parameter :: NGenerate = 100 ! number of random pairs to generate + + real :: dyndx (NGenerate), dyndy(NGenerate) + + interface ! describe the 4 Rule functions + pure function rule1 (z,dz) result (retv) + real , intent(in) :: z, dz + real :: retv + end function rule1 + pure function rule2 (z,dz) result (retv) + real , intent(in) :: z, dz + real :: retv + end function rule2 + pure function rule3 (z,dz) result (retv) + real , intent(in) :: z, dz + real :: retv + end function rule3 + pure function rule4 (z,dz) result (retv) + real , intent(in) :: z, dz + real :: retv + end function rule4 + end interface + + + write ( *, "( 'With test data as in the Racket solution as suggested in the task description:',/)") + + call simulation (dx, dy, size(dx), rule1) + call simulation (dx, dy, size(dx), rule2) + call simulation (dx, dy, size(dx), rule3) + call simulation (dx, dy, size(dx), rule4) + + + call random_seed () ! Initialize random number generator + call fillRandom (dyndx, dyndy, NGenerate) + + write ( *, "( 'With randomly generated displacements:',/)") + + call simulation (dyndx, dyndy, NGenerate, rule1) + call simulation (dyndx, dyndy, NGenerate, rule2) + call simulation (dyndx, dyndy, NGenerate, rule3) + call simulation (dyndx, dyndy, NGenerate, rule4) + +end program DemingsFunnel + + +! ================================================================ +! Do the simulation: drop the balls through the funnel and correct +! funnel position according to the applied rule +! ================================================================ +subroutine simulation (ddx, ddy, sizddx, rule) + +implicit none + +real, intent(in) :: ddx(*), ddy(*) +integer, intent(in) :: sizddx +real, external :: stddev + +interface ! describe the Rule function + pure function rule (z,dz) result (retv) + real , intent(in) :: z, dz + real :: retv + end function rule +end interface + +real :: allX (sizddx) ! Array with x position of impact +real :: allY (sizddx) ! ... same, y positions. +real :: x, y ! The funnel's position +real :: rx, ry ! The actual impact position +real :: avx, avy ! Averaged impact position, calculate it here +real :: sigmaX, sigmaY ! The resultant standard deviation of the impact positions +integer :: ii ! loop index +integer :: ruleno=1 ! Which rule is applied to "improve" the outcome. + +print '("Rule ", I0, ":")', ruleno +ruleno = mod(ruleno,4) + 1 ! 1,2,3,4,1,2,3,4..., knowing there are 4 rules only. + +x=0 ! Start values +y=0 +avx = 0 +avy = 0 +do ii=1, sizddx + rx = x + ddx(ii) ! Impact position is funnel pos + offset + ry = y + ddy(ii) + x = rule (x,ddx(ii)) ! New funnel position according to rule 1,2,3, or 4 + y = rule (y,ddy(ii)) + avx = avx + rx ! Add up impact positions to calculate average + avy = avy + ry + allx(ii) = rx ! Store impact positions to calculate standard deviation + ally(ii) = ry +end do +avx = avx / sizddx +avy = avy / sizddx + +sigmaX = stddev (allx, avx, sizddx) +sigmaY = stddev (ally, avy, sizddx) + +write (*,'("Mean x, y: ", 2F12.4)') avx, avy +write (*,'("Std dev x, y:", 2F12.4,//)') sigmaX, sigmaY + +end subroutine simulation + +! The 4 rules how to move the funnel after a shot + +pure function rule1 (z,dz) result (retv) ! funnel always above (0,0) + real, intent(in) :: z, dz + real :: retv + retv = z ! avoid compiler warning "unused dummy argument" + retv = dz + retv = 0 +end function rule1 + +pure function rule2 (z,dz) result (retv) ! "correct" for last deviation from aim + real , intent(in) :: z, dz + real :: retv + retv = z ! avoid compiler warning "unused dummy argument" + retv = -dz +end function rule2 + +pure function rule3 (z,dz) result (retv) ! Move funnel back to (0,0), then correct for last dev + real , intent(in) :: z, dz + real :: retv + retv = -(z+dz) +end function rule3 + +pure function rule4 (z,dz) result (retv) ! funnel over last drop + real , intent(in) :: z, dz + real :: retv + retv = z+dz +end function rule4 + + +! =================================================================== +! Calculate the standard deviation of the values in the array "allz" +! the mean value of these values is allz, and the third argument is +! the size of the array. +! =================================================================== +function stddev (allz, avz, sizddx) result (sz) + +implicit none + +integer, intent(in) :: sizddx +real , intent(in) :: allz (sizddx) +real , intent(in) :: avz + +real :: sqsum +real :: sz + +integer :: ii +sqsum = 0. + +do ii=1, sizddx + sqsum = sqsum + (allz(ii)-avz)**2 +end do +sz = sqrt (sqsum / sizddx) +end function stddev + +! ======================================================================================= +! Fill arrays x and y with gaussian distributed random numbers +! x and y are cartesian coordinates of points. Transformed to cylinder coordinates, +! the radius is gaussian distributed with standard deviation of 1.0, and the polar angle +! phi is uniformly distributed between 0 and 2.0*PI +! ======================================================================================= +subroutine fillRandom (x,y,n) + +implicit none + +real, parameter :: sigma = sqrt(2.) / 2. ! Forces sigma of radius of (x,y) to be 1.0 +integer, intent(in) :: n ! Dimension of arrays x and y +real, intent(out) :: x(n),y(n) ! the arrays to fill +integer :: ii ! Loop index +do ii=1, n + call normrand(x(ii),y(ii), sigma) +enddo +end subroutine fillRandom + + +! ========================================================================================== +! Generate a pair of gaussian distributed pseudo-randum numbers (in cartesian coordinates), +! each with a mean value = 0 and standard deviation of sigma +! ========================================================================================== +subroutine normrand(x,y, sigma) + +implicit none + +! Using Box-Muller method as described in Wikipedia, +! and the formulae therein + +real, intent(out) :: x,y ! the two variables to be filled with pseudo random numbers +real, intent(in) :: sigma ! standard deviation of the distribution in x and y +real, parameter :: twopi = 2.*acos(-1.) +real :: u(2), radius, phi + +call random_number(u) ! n.b.: this sets both elements of u to random in [0...1] + +radius = sigma * sqrt(-2 * log(u(1))) ! norm distribution in radius +phi = twopi*u(2) ! Uniform distribution in angle +x = radius * cos(phi) ! to cartesian coordinates +y = radius * sin(phi) + +end subroutine normrand diff --git a/Task/Demings-funnel/JavaScript/demings-funnel.js b/Task/Demings-funnel/JavaScript/demings-funnel.js new file mode 100644 index 0000000000..71206ee35a --- /dev/null +++ b/Task/Demings-funnel/JavaScript/demings-funnel.js @@ -0,0 +1,67 @@ +const dxs = [ + -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 dys = [ + 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 +]; + +function funnel(input, rule) { + let x = 0; + const result = []; + + for (let i = 0; i < input.length; i++) { + const rx = x + input[i]; + x = rule(x, input[i]); + result.push(rx); + } + return result; +} + +function mean(xs) { + return xs.reduce((sum, x) => sum + x, 0) / xs.length; +} + +function stdDev(xs) { + const m = mean(xs); + return Math.sqrt(xs.reduce((sum, x) => sum + Math.pow(x - m, 2), 0) / xs.length); +} + +function experiment(label, dxs, dys, rule) { + const resx = funnel(dxs, rule); + const resy = funnel(dys, rule); + console.log(label); + console.log(`Mean x, y: ${mean(resx).toFixed(4)}, ${mean(resy).toFixed(4)}`); + console.log(`Std dev x, y: ${stdDev(resx).toFixed(4)}, ${stdDev(resy).toFixed(4)}`); + console.log(); +} + +// Run experiments +experiment("Rule 1:", dxs, dys, (z, dz) => 0.0); +experiment("Rule 2:", dxs, dys, (z, dz) => -dz); +experiment("Rule 3:", dxs, dys, (z, dz) => -(z + dz)); +experiment("Rule 4:", dxs, dys, (z, dz) => z + dz); diff --git a/Task/Demings-funnel/Lua/demings-funnel.lua b/Task/Demings-funnel/Lua/demings-funnel.lua new file mode 100644 index 0000000000..67d4e1911a --- /dev/null +++ b/Task/Demings-funnel/Lua/demings-funnel.lua @@ -0,0 +1,101 @@ +-- Import the `moses` library, which provides utility functions for functional +-- programming and list operations. +local moses = require("moses") + +-- Define a list of x-direction displacements (dx values) used in the experiment. +-- These represent random perturbations or changes applied to a position over time. +local dxs = { + -0.533, 0.27, 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.15, 0.001, -0.382, 0.161, 0.915, + 2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, + 0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -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.17, 0.054, -0.553, -0.024, -0.181, -0.7, -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.31, 0.171, 0.0, 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 +} +-- Define a list of y-direction displacements (dy values), analogous to `dxs`. +local dys = { + 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, 0.49, -0.682, + -0.065, 0.242, -0.288, 0.658, 0.459, 0.0, 0.426, 0.205, -0.765, -2.188, + -0.742, -0.01, 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.79, 0.723, 0.881, -0.508, 0.393, -0.226, 0.71, 0.038, + -0.217, 0.831, 0.48, 0.407, 0.447, -0.295, 1.126, 0.38, 0.549, -0.445, + -0.046, 0.428, -0.074, 0.217, -0.822, 0.491, 1.347, -0.141, 1.23, -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.65, -1.103, 0.154, -1.72, 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 +} + +-- Simulates a "funnel" process: applies a sequence of displacements (`dxs`) using +-- a given update rule to track a state variable `x`. + +-- At each step: +-- - The current output position is recorded as `x + dx` +-- - The internal state `x` is updated via `rule(x, dx)` + +-- Returns the list of observed positions (`rxs`). +local function funnel(dxs, rule) + local x = 0 -- Initial state (e.g., current position or error) + local rxs = {} -- Table to store resulting positions + for i, dx in ipairs(dxs) do + rxs[i] = x + dx -- Observed value = current state + displacement + x = rule(x, dx) -- Update internal state using the provided rule + end + return rxs +end + +-- Computes the sample standard deviation of a list of numbers. +-- Uses the formula: `sqrt( sum((x_i - mean)^2) / N )` + +-- Note: This uses population standard deviation (divides by N, not N-1). +local function stddev(xs) + local m = moses.mean(xs) -- Compute mean of the input list + -- Map each element to squared deviation from mean, sum them, divide by count, then + -- sqrt + return math.sqrt(moses.sum(moses.map(xs, function (x) + return (x - m) ^ 2 + end))/(#xs)) +end + +-- Runs an experiment using a specific update rule. + +-- Applies the funnel process independently to `dxs` and `dys`, then prints the +-- mean and standard deviation of the resulting `x` and `y` positions. +local function experiment(label, rule) + local rxs, rys = funnel(dxs, rule), funnel(dys, rule) + print(label) + print("Mean of (x, y): "..string.format("%.8f, %.8f", moses.mean(rxs), moses.mean(rys))) + print("Standard derivation of (x, y): "..string.format("%.8f, %.8f", stddev(rxs), stddev(rys))) +end + +-- Run four experiments with different feedback rules: + +-- Rule 1: Reset state to 0 after every step (no memory). +-- This simulates independent measurements with no correction. + +-- Rule 2: Set next state to negative of the displacement. +-- Equivalent to: x_{n+1} = -dx_n + +-- Rule 3: Next state = -(current state + displacement) +-- This introduces strong negative feedback (over-correction). + +-- Rule 4: Next state = current state + displacement (accumulate errors) +-- This is a random walk: x_{n+1} = x_n + dx_n + +experiment("Rule 1", function (z, dz) + return 0 +end) +experiment("Rule 2", function (z, dz) + return -dz +end) +experiment("Rule 3", function (z, dz) + return -z - dz +end) +experiment("Rule 4", function (z, dz) + return z + dz +end) diff --git a/Task/Demings-funnel/Pluto/demings-funnel.pluto b/Task/Demings-funnel/Pluto/demings-funnel.pluto new file mode 100644 index 0000000000..18f893e2e4 --- /dev/null +++ b/Task/Demings-funnel/Pluto/demings-funnel.pluto @@ -0,0 +1,59 @@ +require "table2" +local fmt = require "fmt" + +local dxs = { + -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 +} + +local dys = { + 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 +} + +local function funnel(fa, r) + local x = 0 + local res = table.rep(#fa, 0) + for i = 1, #fa do + local f = fa[i] + res[i] = x + f + x = r(x, f) + end + return res +end + +local function experiment(label, r) + local rxs = funnel(dxs, r) + local rys = funnel(dys, r) + print($"{label} : x y") + fmt.print("Mean : %7.4f, %7.4f", rxs:mean(), rys:mean()) + fmt.print("Std Dev : %7.4f, %7.4f", rxs:stddev(), rys:stddev()) + print() +end + +experiment("Rule 1", |_, __| -> 0) +experiment("Rule 2", |_, dz| -> -dz) +experiment("Rule 3", |z, dz| -> -(z + dz)) +experiment("Rule 4", |z, dz| -> z + dz) diff --git a/Task/Demings-funnel/R/demings-funnel.r b/Task/Demings-funnel/R/demings-funnel.r new file mode 100644 index 0000000000..1c21602359 --- /dev/null +++ b/Task/Demings-funnel/R/demings-funnel.r @@ -0,0 +1,70 @@ +#Provided data +dxs <- c(-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) + +dys <- c(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) + +#Generating data instead +drs <- rnorm(100) +dthetas <- runif(100, 0, 2*pi) +dxs <- drs*cos(dthetas) +dys <- drs*sin(dthetas) + +#Main task solution +funnel <- function(dks, rule) { + k <- 0 + rks <- numeric(0) + for(dk in dks) { + rks <- c(rks, k+dk) + k <- rule(k, dk) + } + rks +} + +rules <- c(function(z, dz) 0, + function(z, dz) -dz, + function(z, dz) -(z+dz), + function(z, dz) z+dz) + +experiment <- function(rule) { + stat <- function(f) sapply(list(dxs, dys), function(v) f(funnel(v, rule))) + means <- setNames(stat(mean), c("Mean x", "Mean y")) + sds <- setNames(stat(sd), c("SD x", "SD y")) + c(means, sds) +} + +setNames(lapply(rules, experiment), paste("Rule", 1:4)) + +#Scatter plots +png("DemingFunnel-R.png", 1000, 1000) +op <- par(mfrow = c(2, 2)) +for(i in 1:4) plot(funnel(dxs, rules[[i]]), + funnel(dys, rules[[i]]), + main = paste("Rule", i), + xlab = NA, + ylab = NA) +par(op) +dev.off() diff --git a/Task/Department-numbers/ANSI-BASIC/department-numbers.basic b/Task/Department-numbers/ANSI-BASIC/department-numbers.basic new file mode 100644 index 0000000000..755177f9ec --- /dev/null +++ b/Task/Department-numbers/ANSI-BASIC/department-numbers.basic @@ -0,0 +1,13 @@ +100 REM Department numbars +110 PRINT "POLICE SANITATION FIRE" +120 FOR P = 2 TO 7 STEP 2 +130 FOR S = 1 TO 7 +140 IF S <> P THEN +150 LET F = 12 - P - S +160 IF F <> S AND F <> P AND F >= 1 AND F <= 7 THEN +170 PRINT USING " # # #": P, S, F +180 END IF +190 END IF +200 NEXT S +210 NEXT P +220 END diff --git a/Task/Department-numbers/Ada/department-numbers.adb b/Task/Department-numbers/Ada/department-numbers.adb new file mode 100644 index 0000000000..b4ab68ee99 --- /dev/null +++ b/Task/Department-numbers/Ada/department-numbers.adb @@ -0,0 +1,22 @@ +with Ada.Text_IO; + +procedure Department_Numbers is + use Ada.Text_IO; +begin + Put_Line (" P S F"); + for Police in 2 .. 6 loop + for Sanitation in 1 .. 7 loop + for Fire in 1 .. 7 loop + if + Police mod 2 = 0 and + Police + Sanitation + Fire = 12 and + Sanitation /= Police and + Sanitation /= Fire and + Police /= Fire + then + Put_Line (Police'Image & Sanitation'Image & Fire'Image); + end if; + end loop; + end loop; + end loop; +end Department_Numbers; diff --git a/Task/Department-numbers/Agena/department-numbers.agena b/Task/Department-numbers/Agena/department-numbers.agena new file mode 100644 index 0000000000..7f03c70889 --- /dev/null +++ b/Task/Department-numbers/Agena/department-numbers.agena @@ -0,0 +1,14 @@ +# Department numbers +scope + print('POLICE SANITATION FIRE'); + for p from 2 to 7 by 2 do + for s to 7 do + if s <> p then + f := 12 - p - s + if f <> s and f <> p and f >= 1 and f <= 7 then + printf(" %1d %1d %1d\n", p, s, f) + fi + fi + od + od +epocs diff --git a/Task/Department-numbers/COBOL/department-numbers.cob b/Task/Department-numbers/COBOL/department-numbers.cob new file mode 100644 index 0000000000..4fcd9321db --- /dev/null +++ b/Task/Department-numbers/COBOL/department-numbers.cob @@ -0,0 +1,37 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. DEPARTMENT-NUMBERS. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE". + 01 COMBINATION. + 03 FILLER PIC X(5) VALUE SPACES. + 03 POLICE PIC 9. + 03 FILLER PIC X(11) VALUE SPACES. + 03 SANITATION PIC 9. + 03 FILLER PIC X(5) VALUE SPACES. + 03 FIRE PIC 9. + 01 TOTAL PIC 99. + + PROCEDURE DIVISION. + BEGIN. + DISPLAY BANNER. + PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2 + UNTIL POLICE IS GREATER THAN 6. + STOP RUN. + + POLICE-LOOP. + PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1 + UNTIL SANITATION IS GREATER THAN 7. + + SANITATION-LOOP. + PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1 + UNTIL FIRE IS GREATER THAN 7. + + FIRE-LOOP. + ADD POLICE, SANITATION, FIRE GIVING TOTAL. + IF POLICE IS NOT EQUAL TO SANITATION + AND POLICE IS NOT EQUAL TO FIRE + AND SANITATION IS NOT EQUAL TO FIRE + AND TOTAL IS EQUAL TO 12, + DISPLAY COMBINATION. diff --git a/Task/Department-numbers/Icon/department-numbers.icon b/Task/Department-numbers/Icon/department-numbers.icon new file mode 100644 index 0000000000..0b8ead45cd --- /dev/null +++ b/Task/Department-numbers/Icon/department-numbers.icon @@ -0,0 +1,5 @@ +procedure main() + every writes(center("police"|"sanitation"|"fire",12)|"\n") + every ((p:=2|4|6)~=(s := 1 to 7)~=(f := 1 to 7),p+s+f=12) do + every writes(center(p|s|f,12)|"\n") +end diff --git a/Task/Department-numbers/Oberon-07/department-numbers.oberon b/Task/Department-numbers/Oberon-07/department-numbers.oberon new file mode 100644 index 0000000000..67887a2055 --- /dev/null +++ b/Task/Department-numbers/Oberon-07/department-numbers.oberon @@ -0,0 +1,27 @@ +MODULE DepartmentNumbers; + (* show possible department number allocations for police, sanitation and fire departments *) + (* the police department number must be even, all department numbers in the range 1 .. 7 *) + (* the sum of the department numbers must be 12 *) + + IMPORT Out; + + CONST maxDepartmentNumber = 7; + departmentSum = 12; + VAR police, sanitation, fire : INTEGER; + +BEGIN + Out.String( "police sanitation fire" );Out.Ln; + FOR police := 2 TO maxDepartmentNumber BY 2 DO + FOR sanitation := 1 TO maxDepartmentNumber DO + IF sanitation # police THEN + fire := ( departmentSum - police ) - sanitation; + IF ( fire > 0 ) & ( fire <= maxDepartmentNumber ) + & ( fire # sanitation ) + & ( fire # police ) + THEN + Out.Int( police, 6 );Out.Int( sanitation, 11 );Out.Int( fire, 5 );Out.Ln + END + END + END + END +END DepartmentNumbers. diff --git a/Task/Department-numbers/Pluto/department-numbers.pluto b/Task/Department-numbers/Pluto/department-numbers.pluto new file mode 100644 index 0000000000..f4b9908115 --- /dev/null +++ b/Task/Department-numbers/Pluto/department-numbers.pluto @@ -0,0 +1,17 @@ +print("Police Sanitation Fire") +print("------ ---------- ----") +local count = 0 +for h = 1, 3 do + local i = h * 2 + for j = 1, 7 do + if j != i then + for k = 1, 7 do + if k != i and k != j and i + j + k == 12 then + print($" {i} {j} {k}") + ++count + end + end + end + end +end +print($"\n{count} valid combinations") diff --git a/Task/Department-numbers/PowerShell/department-numbers.ps1 b/Task/Department-numbers/PowerShell/department-numbers.ps1 new file mode 100644 index 0000000000..f5c20e4d52 --- /dev/null +++ b/Task/Department-numbers/PowerShell/department-numbers.ps1 @@ -0,0 +1,13 @@ +# Department numbers + +Write-Output "POLICE SANITATION FIRE" +for ($p = 2; $p -le 7; $p += 2) { + for ($s = 1; $s -le 7; $s++) { + if ($s -ne $p) { + $f = 12 - $p - $s + if (($f -ne $s) -and ($f -ne $p) -and ($f -ge 1) -and ($f -le 7)) { + Write-Output " $p $s $f" + } + } + } +} diff --git a/Task/Department-numbers/Uiua/department-numbers.uiua b/Task/Department-numbers/Uiua/department-numbers.uiua new file mode 100644 index 0000000000..be407e35d8 --- /dev/null +++ b/Task/Department-numbers/Uiua/department-numbers.uiua @@ -0,0 +1 @@ +▽=0◿2⊸≡⊢▽=12⊸≡/+⧅≠3 +1⇡7 diff --git a/Task/Descending-primes/Ada/descending-primes.adb b/Task/Descending-primes/Ada/descending-primes.adb new file mode 100644 index 0000000000..e027fecc58 --- /dev/null +++ b/Task/Descending-primes/Ada/descending-primes.adb @@ -0,0 +1,33 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; +with Strings_Edit.Integers; use Strings_Edit.Integers; + +procedure Descending_Primes is + use Strings_Edit; + Line : String (1..90); + Pointer : Integer := 1; + + procedure Check (Value, Digit : Half_Word; Length : Natural) is + This : constant Half_Word := Value * 10; + begin + if Length = 0 then + if Value > 1 and then Is_Prime (Value) = Prime then + Put (Line, Pointer, Integer (Value), 10, False, 9, Right); + if Pointer > 80 then + Put_Line (Line (1..Pointer - 1)); + Pointer := 1; + end if; + end if; + else + for Next in 1..Digit - 1 loop + Check (This + Next, Next, Length - 1); + end loop; + end if; + end Check; +begin + for Length in 1..9 loop + Check (0, 10, Length); + end loop; + Put_Line (Line (1..Pointer - 1)); +end Descending_Primes; diff --git a/Task/Descending-primes/Agena/descending-primes.agena b/Task/Descending-primes/Agena/descending-primes.agena new file mode 100644 index 0000000000..608849f73c --- /dev/null +++ b/Task/Descending-primes/Agena/descending-primes.agena @@ -0,0 +1,20 @@ +scope # generate primes with strictly descending digits + + local proc ascending_primes() + local constant digits, candidates, primes := seq( 9, 8, 7, 6, 5, 4, 3, 2, 1 ), seq( 0 ), []; + for i to size digits do + for j to size candidates do + local constant value := candidates[ j ] * 10 + digits[ i ]; + if numtheory.isprime( value ) then primes[ size primes + 1 ] := value fi + candidates[ size candidates + 1 ] := value + od + od; + sort( primes ) + return primes + end; + + for n, v in ipairs( ascending_primes() ) do + printf( "%10d" & if n mod 10 = 0 then "\n" else "" fi, v ) + od + +epocs diff --git a/Task/Descending-primes/Fennel/descending-primes.fennel b/Task/Descending-primes/Fennel/descending-primes.fennel new file mode 100644 index 0000000000..ea422476b0 --- /dev/null +++ b/Task/Descending-primes/Fennel/descending-primes.fennel @@ -0,0 +1,33 @@ +(do ;;; generate primes with strictly descending digits + + (fn is-prime [p] + (if (or (<= p 1) (= 0 (% p 2))) + (= p 2) + ;else + (do (var (prime i root-p) (values true 3 (math.floor (math.sqrt p)))) + (while (and (<= i root-p) prime) + (set (prime i) (values (not= 0 (% p i)) (+ i 1))) + ) + prime + ) + ) + ) + + (fn ascending-primes [] + (local (digits candidates primes) (values [ 9 8 7 6 5 4 3 2 1 ] [ 0 ] [])) + (for [i 1 (length digits)] + (for [j 1 (length candidates)] + (local value (+ (* 10 (. candidates j)) (. digits i))) + (when (is-prime value) (tset primes (+ 1 (length primes)) value)) + (tset candidates (+ 1 (length candidates)) value) + ) + ) + (table.sort primes) + primes + ) + + (each [n v (ipairs (ascending-primes))] + (io.write (string.format (.. "%10d" (if (= 0 (% n 10)) "\n" "")) v)) + ) + +) diff --git a/Task/Descending-primes/Haskell/descending-primes.hs b/Task/Descending-primes/Haskell/descending-primes.hs new file mode 100644 index 0000000000..9d46f6462c --- /dev/null +++ b/Task/Descending-primes/Haskell/descending-primes.hs @@ -0,0 +1,18 @@ +import Data.List (sort, subsequences) + +isPrime :: Integer -> Bool +isPrime n + | n < 2 = False + | n == 2 = True + | otherwise = 0 == length [i | i <- [2..floor(sqrt (fromIntegral n))], n `mod` i == 0] + +isDescending :: [Integer] -> Bool +isDescending [] = True +isDescending [x] = True +isDescending (x:xs) = (if x <= (head xs) then False else isDescending xs) + +getInt :: [Integer] -> Integer +getInt = foldl (\acc x -> acc * 10 + x) 0 + +descendingInts = sort [getInt xs | xs <- subsequences([9,8..1]), 0 < length xs, isDescending xs] +main = print [n | n <- descendingInts, isPrime n] diff --git a/Task/Descending-primes/Icon/descending-primes.icon b/Task/Descending-primes/Icon/descending-primes.icon new file mode 100644 index 0000000000..cc20cad634 --- /dev/null +++ b/Task/Descending-primes/Icon/descending-primes.icon @@ -0,0 +1,22 @@ +link factors + +procedure main(A) + every writes(" ",descprimes()) + write() +end + +# Blatantly stolen from Lua example.. +procedure descprimes() + primes := [] + digits := [: 9 to 1 by -1 :] + candidates := [0] + + every i := 1 to *digits do + every j := 1 to *candidates do { + value := 10*candidates[j] + digits[i] + put(primes, (isprime(value),value)) + put(candidates, value) + } + + suspend !sort(primes) +end diff --git a/Task/Descending-primes/K/descending-primes.k b/Task/Descending-primes/K/descending-primes.k new file mode 100644 index 0000000000..d99dd04edc --- /dev/null +++ b/Task/Descending-primes/K/descending-primes.k @@ -0,0 +1,4 @@ +isprime: {(x>1)&&/(`pri 1+_%x)!'x} + +nums: (10/|1+&|2\)'!512 +primes: {x@ - with javascript_semantics - function descending_primes(sequence res, atom p=0, max_digit=9) - for d=1 to max_digit do - atom np = p*10+d - if odd(d) and is_prime(np) then res &= np end if - res = descending_primes(res,np,d-1) - end for - return res - end function +with javascript_semantics +function descending_primes(sequence res, atom p=0, max_digit=9) + for d=1 to max_digit do + atom np = p*10+d + if odd(d) and is_prime(np) then res &= np end if + res = descending_primes(res,np,d-1) + end for + return res +end function - sequence r = sort(descending_primes({2})), - --sequence r = descending_primes({2}), - j = join_by(r,1,11," ","\n","%8d") - printf(1,"There are %,d descending primes:\n%s\n",{length(r),j}) - - with javascript_semantics - function descending_primes() - sequence powerset = tagset(9), - res = {} - while length(powerset) do - res &= filter(powerset,is_prime) - sequence next = {} - for i=1 to length(powerset) do - for d=1 to remainder(powerset[i],10)-1 do - next &= powerset[i]*10+d - end for - end for - powerset = next - end while - return res - end function +with javascript_semantics +function descending_primes() + sequence powerset = tagset(9), res = {} + do + res &= filter(powerset,is_prime) + sequence next = {} + for p in powerset do + for d=1 to remainder(p,10)-1 do + next &= p*10+d + end for + end for + powerset = next + until length(powerset)=0 + return res +end function - sequence r = descending_primes(), - j = join_by(r,1,11," ","\n","%8d") - printf(1,"There are %,d descending primes:\n%s\n",{length(r),j}) - - with javascript_semantics - sequence rfs = {1} -- reverse factorial(1) in base 1000 +with javascript_semantics +sequence rfs = {1} -- reverse factorial(1) in base 1000 - function init_zc() - sequence zc = repeat(0,999) - for x=1 to 9 do - zc[x] = 2 -- 00x - zc[10*x] = 2 -- 0x0 - zc[100*x] = 2 -- x00 - for y=10 to 90 by 10 do - zc[y+x] = 1 -- 0yx - zc[10*y+x] = 1 -- y0x - zc[10*(y+x)] = 1 -- yx0 - end for - end for - return zc - end function - constant zc = init_zc() +function init_zc() + sequence zc = repeat(0,999) + for x=1 to 9 do + zc[x] = 2 -- 00x + zc[10*x] = 2 -- 0x0 + zc[100*x] = 2 -- x00 + for y=10 to 90 by 10 do + zc[y+x] = 1 -- 0yx + zc[10*y+x] = 1 -- y0x + zc[10*(y+x)] = 1 -- yx0 + end for + end for + return zc +end function +constant zc = init_zc() - atom t0 = time(), - total = 0 - integer trail = 1, - first = 0 - for f=2 to iff(platform()=JS?10000:50000) do - integer carry = 0, d999, - zeroes = (trail-1)*3, - j = trail, l = length(rfs) - while j<=l or carry do - if j<=l then - carry = (rfs[j])*f+carry - end if - d999 = remainder(carry,1000) - if j<=l then - rfs[j] = d999 - else - rfs &= d999 - end if - zeroes += iff(d999=0?3:zc[d999]) - carry = floor(carry/1000) - j += 1 - end while - while rfs[trail]=0 do trail += 1 end while - -- d999 := quick correction for length and zeroes: - d999 = rfs[$] - d999 = iff(d999<100?iff(d999<10?2:1):0) - zeroes -= d999 - integer digits = length(rfs)*3-d999 +atom t0 = time(), + total = 0 +integer trail = 1, + first = 0 +for f=2 to iff(platform()=JS?10000:50000) do + integer carry = 0, d999, + zeroes = (trail-1)*3, + j = trail, l = length(rfs) + while j<=l or carry do + if j<=l then + carry = (rfs[j])*f+carry + end if + d999 = remainder(carry,1000) + if j<=l then + rfs[j] = d999 + else + rfs &= d999 + end if + zeroes += iff(d999=0?3:zc[d999]) + carry = floor(carry/1000) + j += 1 + end while + while rfs[trail]=0 do trail += 1 end while + -- d999 := quick correction for length and zeroes: + d999 = rfs[$] + d999 = iff(d999<100?iff(d999<10?2:1):0) + zeroes -= d999 + integer digits = length(rfs)*3-d999 - total += zeroes/digits - atom ratio = total/f - if ratio>=0.16 then - first = 0 - elsif first=0 then - first = f - end if - if find(f,{100,1000,10000}) then - string e = elapsed(time()-t0) - printf(1,"Mean proportion of zero digits in factorials to %d is %.10f (%s)\n",{f,ratio,e}) - end if - end for - if platform()!=JS then - string e = elapsed(time()-t0) - printf(1,"The mean proportion dips permanently below 0.16 at %d. (%s)\n",{first,e}) - end if - - with javascript_semantics - atom t0 = time(), - f10 = log10(1), - total = 0 - integer first = 0 - for f=2 to 50000 do - f10 += log10(f) - integer digits = ceil(f10), - zeroes = 0, - v = 5 - while v<=f do - zeroes += floor(f/v) - v *= 5 - end while - total += zeroes/digits - atom ratio = total/f - if ratio>=0.07 then - first = 0 - elsif first=0 then - first = f - end if - if find(f,{100,1000,10000}) then - printf(1,"Mean proportion of trailing zeroes in factorials to %d is %f\n",{f,ratio}) - end if - end for - string e = elapsed(time()-t0) - printf(1,"The mean proportion dips permanently below 0.07 at %d. (%s)\n",{first,e}) - - with javascript_semantics - sequence escache = {} +with javascript_semantics +sequence escache = {} - function es_cat(integer p) - if p>length(escache) and platform()!=JS then - escache &= repeat(0,p-length(escache)) - end if - integer category = escache[p] - if not category then - sequence f = filter(prime_factors(p+1,false,-1),">",3) - category = 1 - if length(f) then - category += max(apply(f,es_cat)) - end if - escache[p] = category - end if - return category - end function +function es_cat(integer p) + if p>length(escache) and platform()!=JS then + escache &= repeat(0,p-length(escache)) + end if + integer category = escache[p] + if not category then + sequence f = filter(prime_factors(p+1,false,-1),">",3) + category = 1 + if length(f) then + category += max(apply(f,es_cat)) + end if + escache[p] = category + end if + return category +end function - procedure categorise(integer n) - sequence p = get_primes(n) - printf(1,"First %,d primes:\n",n) - atom t1 = time() - sequence es = {} - for i=1 to n do - if time()>t1 then - progress("categorising %d/%d...",{i,n}) - t1 = time()+1 - end if - integer category = es_cat(p[i]) - while length(es)<category do - es = append(es,{}) - end while - es[category] &= p[i] - end for - progress("") - for c=1 to length(es) do - sequence e = es[c] - if n=200 then - printf(1,"Category %d: %s\n",{c,join(shorten(e,"primes",5,"%d"),",")}) - else - printf(1,"Category %2d: %7d .. %-8d Count: %d\n",{c,e[1],e[$],length(e)}) - end if - end for - printf(1,"\n") - end procedure +procedure categorise(integer n) + sequence p = get_primes(n) + printf(1,"First %,d primes:\n",n) + atom t1 = time() + sequence es = {} + for i=1 to n do + if time()>t1 then + progress("categorising %d/%d...",{i,n}) + t1 = time()+1 + end if + integer category = es_cat(p[i]) + while length(es)atom t0 = time() - categorise(200) - categorise(1e6) - ?elapsed(time()-t0) - - -- demo\rosetta\Eulers_constant.exw - with javascript_semantics - constant C = sum(sq_div(1,tagset(1e6)))-log(1e6) - printf(1,"gamma %.12f (max 12d.p. of accuracy)\n",C) - - without js -- no mpfr_get_d_2exp() in mpfr.js as yet - requires("1.0.2") -- mpfr_get_d_2exp(), mpfr_addmul_si() - include mpfr.e - mpfr u, v, k2; - integer e, e10, e2 - atom f +without js -- no mpfr_get_d_2exp() in mpfr.js as yet +requires("1.0.2") -- mpfr_get_d_2exp(), mpfr_addmul_si() +include mpfr.e +mpfr u, v, k2; +integer e, e10, e2 +atom f - //log(x/y) with the Taylor series for atanh(x-y/x+y) - procedure ln(mpfr s, integer x, y) - mpfr d = u, q = v; - assert((x-y)==1) - mpfr_set_si(s, x+y) - mpfr_si_div(s, 1, s) // s = 1 / (x + y) - mpfr_mul(k2, s, s) // k2 = s * s - mpfr_set(d, s) - integer k = 1 - while true do - k += 2; - mpfr_mul(d, d, k2) // d *= k2 - mpfr_div_si(q, d, k) // q = d / k - mpfr_add(s, s, q) // s += q - {f,e} = mpfr_get_d_2exp(q) - if abs(e)>=e2 then exit end if - end while - mpfr_mul_si(s, s, 2) //s *= 2 - end procedure +//log(x/y) with the Taylor series for atanh(x-y/x+y) +procedure ln(mpfr s, integer x, y) + mpfr d = u, q = v; + assert((x-y)==1) + mpfr_set_si(s, x+y) + mpfr_si_div(s, 1, s) // s = 1 / (x + y) + mpfr_mul(k2, s, s) // k2 = s * s + mpfr_set(d, s) + integer k = 1 + while true do + k += 2; + mpfr_mul(d, d, k2) // d *= k2 + mpfr_div_si(q, d, k) // q = d / k + mpfr_add(s, s, q) // s += q + {f,e} = mpfr_get_d_2exp(q) + if abs(e)>=e2 then exit end if + end while + mpfr_mul_si(s, s, 2) //s *= 2 +end procedure - mpfr a, b - integer k, - n = 60, -- (required precision in decimal dp *6/10) - n2, - r = 41, - s = 30, - t = 18; +mpfr a, b +integer k, + n = 60, -- (required precision in decimal dp *6/10) + n2, + r = 41, + s = 30, + t = 18; - // n = 2^i * 3^j * 5^k +// n = 2^i * 3^j * 5^k - // log(n) = r * log(16/15) + s * log(25/24) + t * log(81/80) +// log(n) = r * log(16/15) + s * log(25/24) + t * log(81/80) - // solve linear system for r, s, t - // 4 -3 -4| i - // -1 -1 4| j - // -1 2 -1| k +// solve linear system for r, s, t +// 4 -3 -4| i +// -1 -1 4| j +// -1 2 -1| k - //decimal precision - e10 = floor(n/0.6) - //binary precision - e2 = floor((1 + e10) / 0.30103) +//decimal precision +e10 = floor(n/0.6) +//binary precision +e2 = floor((1 + e10) / 0.30103) - mpfr_set_default_precision(e2) - {a, b, u, v, k2} = mpfr_inits(5) +mpfr_set_default_precision(e2) +{a, b, u, v, k2} = mpfr_inits(5) - //Compute log terms - ln(b, 16, 15) mpfr_mul_si(a, b, r) // a = r * b - ln(b, 25, 24) mpfr_addmul_si(a, b, s) // a += s * b - ln(b, 81, 80) mpfr_addmul_si(a, b, t) // a += t * b +//Compute log terms +ln(b, 16, 15) mpfr_mul_si(a, b, r) // a = r * b +ln(b, 25, 24) mpfr_addmul_si(a, b, s) // a += s * b +ln(b, 81, 80) mpfr_addmul_si(a, b, t) // a += t * b - mpfr_neg(a, a) // a = -a - mpfr_set_si(b, 1) // b = 1 - mpfr_set (u, a) - mpfr_set (v, b) +mpfr_neg(a, a) // a = -a +mpfr_set_si(b, 1) // b = 1 +mpfr_set (u, a) +mpfr_set (v, b) - k = 0; - n2 = n * n; - mpfr_set_si(k2, 0) // k2 = k * k (as below) - while true do - mpfr_add_si(k2, k2, k*2+1) // k2 += 2k + 1 - k += 1; +k = 0; +n2 = n * n; +mpfr_set_si(k2, 0) // k2 = k * k (as below) +while true do + mpfr_add_si(k2, k2, k*2+1) // k2 += 2k + 1 + k += 1; - mpfr_div(b, b, k2) - mpfr_mul_si(b, b, n2) // b = b * n2 / k2 + mpfr_div(b, b, k2) + mpfr_mul_si(b, b, n2) // b = b * n2 / k2 - mpfr_div_si(a, a, k) - mpfr_mul_si(a, a, n2) - mpfr_add (a, a, b) - mpfr_div_si(a, a, k) // a = (a * n2 / k + b) / k + mpfr_div_si(a, a, k) + mpfr_mul_si(a, a, n2) + mpfr_add (a, a, b) + mpfr_div_si(a, a, k) // a = (a * n2 / k + b) / k - mpfr_add(u, u, a) // u += a - mpfr_add(v, v, b) // v += b + mpfr_add(u, u, a) // u += a + mpfr_add(v, v, b) // v += b - {f,e} = mpfr_get_d_2exp (a) - if abs(e)>=e2 then exit end if - end while + {f,e} = mpfr_get_d_2exp (a) + if abs(e)>=e2 then exit end if +end while - mpfr_div(u, u, v) - string su = mpfr_get_fixed(u,e10) - printf(1,"gamma %s (maxerr. 1e-%d)\n", {su, e10}) - - without js -- no mpfr_const_euler() in mpfr.js as yet - requires("1.0.1") -- mpfr_const_euler() - include mpfr.e - mpfr gamma = mpfr_init(0,-100) - mpfr_const_euler(gamma) - printf(1,"gamma %s (mpfr_const_euler)\n",{mpfr_get_fixed(gamma,100)}) - - with javascript_semantics - function powir(atom b, integer i) - atom res = 1 - if i<0 then {b,i} = {1/b,abs(i)} end if - while i do - if and_bits(i,1) then res *= b end if - b *= b - i = floor(i/2) - end while - return res - end function - ?powir(-3,-5) - ?power(-3,-5) - - for x=-5 to 5 by 10 do - for p=2 to 3 do - printf(1,"x = %2d, p = %d, power(-x,p) = %4d, -power(x,p) = %4d\n",{x,p,power(-x,p),-power(x,p)}) - end for - end for - - with javascript_semantics - if platform()!=JS then free_console() end if - sequence primes = {2,3,5,7} - atom sieved = 10 +with javascript_semantics +sequence primes = {2,3,5,7} +atom sieved = 10 - procedure add_block() - integer N = min((sieved-1)*sieved,400000) - sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved - for i=2 to length(primes) do -- (evens filtered on output) - atom p = primes[i], p2 = p*p - if p2>sieved+N then exit end if - if p2<sieved+1 then - p2 += ceil((sieved+1-p2)/p)*p - end if - p2 -= sieved - if and_bits(p2,1)=0 then p2 += p end if - -- if sieve[p2] then -- dang! - for k=p2 to N by p*2 do - sieve[k] = 0 - end for - -- end if - end for - for i=1 to N by 2 do - if sieve[i] then - primes &= i+sieved - end if - end for - sieved += N - end procedure +procedure add_block() + integer N = min((sieved-1)*sieved,400000) + sequence sieve = repeat(1,N) -- sieve[i] is really i+sieved + for i=2 to length(primes) do -- (evens filtered on output) + atom p = primes[i], p2 = p*p + if p2>sieved+N then exit end if + if p2function is_prime2(integer n) - while sieved<n do - add_block() - end while - return binary_search(n,primes)>0 - end function - - atom t0 = time() - while length(primes)<20 do add_block() end while - printf(1,"The first 20 primes are: ") ?primes[1..20] - while sieved<150 do add_block() end while - sequence s = {} - for k=abs(binary_search(100,primes)) to length(primes) do - integer p = primes[k] - if p>150 then exit end if - s &= p - end for - printf(1,"The primes between 100 and 150 are: ") ?s - s = {} - for i=7700 to 8000 do - if is_prime2(i) then s&=i end if - end for - printf(1,"There are %d primes between 7700 and 8000.\n",length(s)) - for i=1 to iff(platform()=JS?7:8) do - integer k = power(10,i) - while length(primes)<k do - add_block() - end while - printf(1,"The %,dth prime is : %d\n",{k,primes[k]}) - end for - ?time()-t0 - if platform()!=JS then {} = wait_key() end if - - with javascript_semantics - atom t0 = time() - printf(1,"The first 20 primes are: %v\n",{get_primes(-20)}) - sequence s = get_primes_le(150)[length(get_primes_le(100))+1..$] - printf(1,"The primes between 100 and 150 are: %v\n",{s}) - integer n7700to8000 = length(get_primes_le(8000))-length(get_primes_le(7700)) - printf(1,"There are %d primes between 7700 and 8000.\n",n7700to8000) - for i=1 to iff(platform()=JS?7:8) do - integer k = power(10,i) - printf(1,"The %,dth prime is : %d\n",{k,get_prime(k)}) - end for - ?time()-t0 - if platform()!=JS then {} = wait_key() end if - " + rotated.join(' ')); + increment(factoradic); + } + console.log(); + + // Part 2 + console.log("Part 2: Permutations of 11 digits"); + console.log("=".repeat(50)); + + const limit = factorial(11); + elements = convertToVectorOfInteger("0.1.2.3.4.5.6.7.8.9.10"); + factoradic = convertToVectorOfInteger("0.0.0.0.0.0.0.0.0.0"); + + for (let i = 0; i < limit; i++) { + const rotated = permutation(elements, factoradic); + if (i < 3 || i > limit - 4) { + console.log(toStringArray(factoradic, '.') + " --> " + rotated.join(' ')); + } else if (i === 3) { + console.log(" [ ... ] "); + } + increment(factoradic); + } + console.log("Number of permutations is 11! = " + limit); + console.log(); + + // Part 3 + console.log("Part 3: Card shuffling with factoradic representation"); + console.log("=".repeat(50)); + + const codes = [ + "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", + "51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1" + ]; + + const suits = ['♠', '♥', '♦', '♣']; + const ranks = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']; + + const cards = []; + for (const suit of suits) { + for (const rank of ranks) { + cards.push(rank + suit); + } + } + + console.log("Original deck of cards:"); + console.log(cards.join(' ')); + console.log(); + + console.log("Task shuffles:"); + for (const code of codes) { + console.log(code + " --> "); + factoradic = convertToVectorOfInteger(code); + const shuffled = permutation(cards, factoradic); + console.log(shuffled.join(' ')); + console.log(); + } + + console.log("Random shuffle:"); + factoradic = []; + for (let i = 0; i < cards.length - 1; i++) { + const randomIndex = Math.floor(Math.random() * (cards.length - i)); + factoradic.push(randomIndex); + } + + console.log(toStringArray(factoradic, '.') + " --> "); + const randomShuffled = permutation(cards, factoradic); + console.log(randomShuffled.join(' ')); +} + +// Run the program +main(); diff --git a/Task/Factorial-primes/Ada/factorial-primes.adb b/Task/Factorial-primes/Ada/factorial-primes.adb new file mode 100644 index 0000000000..f264eb9d50 --- /dev/null +++ b/Task/Factorial-primes/Ada/factorial-primes.adb @@ -0,0 +1,95 @@ +-- Rosetta Code Task written in Ada +-- Factorial primes +-- https://rosettacode.org/wiki/Factorial_primes +-- August 2024, R. B. E. +-- Using GNAT Big Integers, GNAT version 14.1, MacOS 14.6.1, M1 chip + +pragma Ada_2022; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Numerics.Big_Numbers.Big_Integers; use Ada.Numerics.Big_Numbers.Big_Integers; + +procedure Factorial_Primes is + + function Is_Prime (N : in Big_Integer) return Boolean is + Big_0 : Big_Natural := To_Big_Integer (0); + Big_2 : Big_Natural := To_Big_Integer (2); + Big_3 : Big_Natural := To_Big_Integer (3); + Big_Temp : Big_Natural := To_Big_Integer (5); + begin + if N < Big_2 then + return False; + end if; + if N mod Big_2 = Big_0 then + return N = Big_2; + end if; + if N mod Big_3 = Big_0 then + return N = Big_3; + end if; + while Big_Temp * Big_Temp <= N loop + if N mod Big_Temp = Big_0 then + return False; + end if; + Big_Temp := Big_Temp + Big_2; + if N mod Big_Temp = Big_0 then + return False; + end if; + Big_Temp := Big_Temp + 4; + end loop; + return True; + end Is_Prime; + + function Factorial (N : Positive) return Big_Integer is + type Factorial_Array is array (1..12) of Big_Integer; + First12_Facts : Factorial_Array; + Result : Big_Integer; + begin + First12_Facts (1) := To_Big_Integer (1); + for I in 2..12 loop + First12_Facts (I) := First12_Facts (I-1) * To_Big_Integer (I); + end loop; + if (N <= 12) then + return First12_Facts (N); + else + Result := First12_Facts (12); + for I in 13..N loop + Result := Result * To_Big_Integer (I); + end loop; + end if; + return Result; + end Factorial; + + Fact : Big_Integer; + Fact_Plus_One : Big_Integer; + Fact_Minus_One : Big_Integer; + Big_One : constant Big_Integer := To_Big_Integer (1); + I, Count : Natural := 0; + Limit : constant Positive := 10; + +begin + loop + I := I + 1; + Fact := Factorial (I); + if (is_Prime (Fact - Big_One)) then + Count := Count + 1; + Put (Count, 3); + Put (": "); + Put (I, 5); + Put ("! - 1 "); + Fact_Minus_One := Fact - Big_One; + Put (To_String (Arg => Fact_Minus_One, Width => 40)); + New_Line; + end if; + if (is_Prime (Fact + Big_One)) then + Count := Count + 1; + Put (Count, 3); + Put (": "); + Put (I, 5); + Put ("! + 1 "); + Fact_Plus_One := Fact + Big_One; + Put (To_String (Arg => Fact_Plus_One, Width => 40)); + New_Line; + end if; + exit when Count >= Limit; + end loop; +end Factorial_Primes; diff --git a/Task/Factorial-primes/Frink/factorial-primes.frink b/Task/Factorial-primes/Frink/factorial-primes.frink new file mode 100644 index 0000000000..e8941229fe --- /dev/null +++ b/Task/Factorial-primes/Frink/factorial-primes.frink @@ -0,0 +1,36 @@ +isFactorialPrime[x] := +{ + if isPrime[x!+1] + return +1 + if x>=2 and isPrime[x!-1] + return -1 + return 0 +} + +count = 0 +n = 1 +res = new array +do +{ + f = isFactorialPrime[n] + if f != 0 + { + count = count + 1 + line = ["$count:", "$n!", f<0 ? "-" : "+", 1, "="] + line.pushAll[formatFac[n!+f]] + res.push[line] + } + n = n + 1 +} until count == 30 + +println[formatTable[res, "right"]] + +formatFac[n] := +{ + s = toString[n] + len = length[s] + if len > 40 + return [left[s,20] + "..." + right[s,20], " ($len digits)"] + else + return [s] +} diff --git a/Task/Factorial-primes/Haskell/factorial-primes.hs b/Task/Factorial-primes/Haskell/factorial-primes.hs new file mode 100644 index 0000000000..9d2d00ea68 --- /dev/null +++ b/Task/Factorial-primes/Haskell/factorial-primes.hs @@ -0,0 +1,26 @@ +isPrime :: Integer -> Bool +isPrime n + | n < 2 = False + | n == 2 = True + | otherwise = 0 == length [i | i <- [2..floor(sqrt (fromIntegral n))], n `mod` i == 0] + +data Op = SubtractOne | AddOne + deriving (Show) + +data Prime = Prime + { fact :: Integer, + prime :: Integer, + op :: Op +} deriving (Show) + +getFactorialPrimes :: Integer -> [Prime] +getFactorialPrimes n + | isPrime (f - 2) = Prime {fact = n, prime = f - 2, op = SubtractOne} : + (if isPrime f then [Prime {fact = n, prime = f, op = AddOne}] else []) + | otherwise = (if isPrime f then [Prime {fact = n, prime = f, op = AddOne}] else []) + where + factorial n = product[1..n] + f = factorial n + 1 + +factorialPrimes = concat $ map getFactorialPrimes [1..] +main = mapM_ print $ take 10 factorialPrimes diff --git a/Task/Factorial-primes/Unicon/factorial-primes.unicon b/Task/Factorial-primes/Unicon/factorial-primes.unicon new file mode 100644 index 0000000000..4de95546a3 --- /dev/null +++ b/Task/Factorial-primes/Unicon/factorial-primes.unicon @@ -0,0 +1,11 @@ +link fastprime + +procedure main(A) + limit := \A[1] | 10 + every f := gfactorial(n := seq()) do { + if (x := (is_prime(y := f-1),n||"!-1")) then + (write(" (",x,",",y,")"), if 0 = (limit -:= 1) then break) + if (x := (is_prime(y := f+1),n||"!+1")) then + (write(" (",x,",",y,")"), if 0 = (limit -:= 1) then break) + } +end diff --git a/Task/Factorial/8th/factorial.8th b/Task/Factorial/8th/factorial.8th new file mode 100644 index 0000000000..d385be5c27 --- /dev/null +++ b/Task/Factorial/8th/factorial.8th @@ -0,0 +1,2 @@ +: factorial \ n -- n! + 1 swap ' n:* 1 rot loop ; diff --git a/Task/Factorial/Ada/factorial-1.adb b/Task/Factorial/Ada/factorial-1.adb new file mode 100644 index 0000000000..96e1766756 --- /dev/null +++ b/Task/Factorial/Ada/factorial-1.adb @@ -0,0 +1,9 @@ +function Factorial (N : Positive) return Positive is + Result : Positive := N; + Counter : Natural := N - 1; +begin + for I in reverse 1..Counter loop + Result := Result * I; + end loop; + return Result; +end Factorial; diff --git a/Task/Factorial/Ada/factorial-2.adb b/Task/Factorial/Ada/factorial-2.adb new file mode 100644 index 0000000000..4891867ed4 --- /dev/null +++ b/Task/Factorial/Ada/factorial-2.adb @@ -0,0 +1,8 @@ +function Factorial(N : Positive) return Positive is + Result : Positive := 1; +begin + if N > 1 then + Result := N * Factorial(N - 1); + end if; + return Result; +end Factorial; diff --git a/Task/Factorial/Ada/factorial-3.adb b/Task/Factorial/Ada/factorial-3.adb new file mode 100644 index 0000000000..a0b5d00151 --- /dev/null +++ b/Task/Factorial/Ada/factorial-3.adb @@ -0,0 +1,62 @@ +with Ada.Numerics.Generic_Complex_Types; +with Ada.Numerics.Generic_Complex_Elementary_Functions; +with Ada.Numerics.Generic_Elementary_Functions; +with Ada.Text_IO.Complex_Io; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Factorial_Numeric_Approximation is + type Real is digits 15; + package Complex_Pck is new Ada.Numerics.Generic_Complex_Types(Real); + use Complex_Pck; + package Complex_Io is new Ada.Text_Io.Complex_Io(Complex_Pck); + use Complex_IO; + package Cmplx_Elem_Funcs is new Ada.Numerics.Generic_Complex_Elementary_Functions(Complex_Pck); + use Cmplx_Elem_Funcs; + + function Gamma(X : Complex) return Complex is + package Elem_Funcs is new Ada.Numerics.Generic_Elementary_Functions(Real); + use Elem_Funcs; + use Ada.Numerics; + -- Coefficients used by the GNU Scientific Library + G : Natural := 7; + P : constant array (Natural range 0..G + 1) of Real := ( + 0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7); + Z : Complex := X; + Cx : Complex; + Ct : Complex; + begin + if Re(Z) < 0.5 then + return Pi / (Sin(Pi * Z) * Gamma(1.0 - Z)); + else + Z := Z - 1.0; + Set_Re(Cx, P(0)); + Set_Im(Cx, 0.0); + for I in 1..P'Last loop + Cx := Cx + (P(I) / (Z + Real(I))); + end loop; + Ct := Z + Real(G) + 0.5; + return Sqrt(2.0 * Pi) * Ct**(Z + 0.5) * Exp(-Ct) * Cx; + end if; + end Gamma; + + function Factorial(N : Complex) return Complex is + begin + return Gamma(N + 1.0); + end Factorial; + Arg : Complex; +begin + Put("factorial(-0.5)**2.0 = "); + Set_Re(Arg, -0.5); + Set_Im(Arg, 0.0); + Put(Item => Factorial(Arg) **2.0, Fore => 1, Aft => 8, Exp => 0); + New_Line; + for I in 0..9 loop + Set_Re(Arg, Real(I)); + Set_Im(Arg, 0.0); + Put("factorial(" & Integer'Image(I) & ") = "); + Put(Item => Factorial(Arg), Fore => 6, Aft => 8, Exp => 0); + New_Line; + end loop; +end Factorial_Numeric_Approximation; diff --git a/Task/Factorial/ArkScript/factorial.ark b/Task/Factorial/ArkScript/factorial.ark new file mode 100644 index 0000000000..41607c70ad --- /dev/null +++ b/Task/Factorial/ArkScript/factorial.ark @@ -0,0 +1,13 @@ +(let factorial (fun (n) { + (mut result 1) + (mut i 2) + (while (< i n) { + (set result (* result i)) + (set i (+ 1 i)) }) + result })) + +(import std.List) + +(list:forEach + (list:iota 0 8) + (fun (n) (print n "\t" (factorial n)))) diff --git a/Task/Factorial/AutoIt/factorial-1.au3 b/Task/Factorial/AutoIt/factorial-1.au3 new file mode 100644 index 0000000000..db1aad047b --- /dev/null +++ b/Task/Factorial/AutoIt/factorial-1.au3 @@ -0,0 +1,12 @@ +;AutoIt Version: 3.2.10.0 +MsgBox (0,"Factorial",factorial(6)) +Func factorial($int) + If $int < 0 Then + Return 0 + EndIf + $fact = 1 + For $i = 1 To $int + $fact = $fact * $i + Next + Return $fact +EndFunc diff --git a/Task/Factorial/AutoIt/factorial-2.au3 b/Task/Factorial/AutoIt/factorial-2.au3 new file mode 100644 index 0000000000..21e756fb1c --- /dev/null +++ b/Task/Factorial/AutoIt/factorial-2.au3 @@ -0,0 +1,10 @@ +;AutoIt Version: 3.2.10.0 +MsgBox (0,"Factorial",factorial(6)) +Func factorial($int) + if $int < 0 Then + return 0 + Elseif $int == 0 Then + return 1 + EndIf + return $int * factorial($int - 1) +EndFunc diff --git a/Task/Factorial/COBOL/factorial-1.cob b/Task/Factorial/COBOL/factorial-1.cob new file mode 100644 index 0000000000..9fac6bb118 --- /dev/null +++ b/Task/Factorial/COBOL/factorial-1.cob @@ -0,0 +1 @@ +MOVE FUNCTION FACTORIAL(num) TO result diff --git a/Task/Factorial/COBOL/factorial-2.cob b/Task/Factorial/COBOL/factorial-2.cob new file mode 100644 index 0000000000..2fe7b7a083 --- /dev/null +++ b/Task/Factorial/COBOL/factorial-2.cob @@ -0,0 +1,21 @@ + IDENTIFICATION DIVISION. + FUNCTION-ID. factorial_iterative. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 i PIC 9(38). + + LINKAGE SECTION. + 01 n PIC 9(38). + 01 ret PIC 9(38). + + PROCEDURE DIVISION USING BY VALUE n RETURNING ret. + MOVE 1 TO ret + + PERFORM VARYING i FROM 2 BY 1 UNTIL n < i + MULTIPLY i BY ret + END-PERFORM + + GOBACK. + + END FUNCTION factorial_iterative. diff --git a/Task/Factorial/COBOL/factorial-3.cob b/Task/Factorial/COBOL/factorial-3.cob new file mode 100644 index 0000000000..0393d1b01c --- /dev/null +++ b/Task/Factorial/COBOL/factorial-3.cob @@ -0,0 +1,22 @@ + IDENTIFICATION DIVISION. + FUNCTION-ID. factorial_recursive. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 prev-n PIC 9(38). + + LINKAGE SECTION. + 01 n PIC 9(38). + 01 ret PIC 9(38). + + PROCEDURE DIVISION USING BY VALUE n RETURNING ret. + IF n = 0 + MOVE 1 TO ret + ELSE + SUBTRACT 1 FROM n GIVING prev-n + MULTIPLY n BY factorial_recursive(prev-n) GIVING ret + END-IF + + GOBACK. + + END FUNCTION factorial_recursive. diff --git a/Task/Factorial/COBOL/factorial-4.cob b/Task/Factorial/COBOL/factorial-4.cob new file mode 100644 index 0000000000..1d57ebaa17 --- /dev/null +++ b/Task/Factorial/COBOL/factorial-4.cob @@ -0,0 +1,34 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. factorial_test. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION factorial_iterative + FUNCTION factorial_recursive. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 i PIC 9(38). + + PROCEDURE DIVISION. + DISPLAY + "i = " + WITH NO ADVANCING + END-DISPLAY. + ACCEPT i END-ACCEPT. + DISPLAY SPACE END-DISPLAY. + + DISPLAY + "factorial_iterative(i) = " + factorial_iterative(i) + END-DISPLAY. + + DISPLAY + "factorial_recursive(i) = " + factorial_recursive(i) + END-DISPLAY. + + GOBACK. + + END PROGRAM factorial_test. diff --git a/Task/Factorial/Chapel/factorial.chpl b/Task/Factorial/Chapel/factorial.chpl new file mode 100644 index 0000000000..4326198f58 --- /dev/null +++ b/Task/Factorial/Chapel/factorial.chpl @@ -0,0 +1,7 @@ +proc fac(n) { + var r = 1; + for i in 1..n do + r *= i; + + return r; +} diff --git a/Task/Factorial/Emacs-Lisp/factorial-1.el b/Task/Factorial/Emacs-Lisp/factorial-1.el new file mode 100644 index 0000000000..13de301a95 --- /dev/null +++ b/Task/Factorial/Emacs-Lisp/factorial-1.el @@ -0,0 +1,11 @@ +;; Functional (most elegant and best suited to Lisp dialects): +(defun fact (n) + "Return the factorial of integer N, which require to be positive or 0." + ;; Elisp won't do any type checking automatically, so + ;; good practice would be doing that ourselves: + (if (not (and (integerp n) (>= n 0))) + (error "Function fact (N): Not a natural number or 0: %S" n)) + ;; But the actual code is very short: + (apply '* (number-sequence 1 n))) + ;; (For N = 0, number-sequence returns the empty list, resp. nil, + ;; and the * function works with zero arguments, returning 1.) diff --git a/Task/Factorial/Emacs-Lisp/factorial-2.el b/Task/Factorial/Emacs-Lisp/factorial-2.el new file mode 100644 index 0000000000..aa44449526 --- /dev/null +++ b/Task/Factorial/Emacs-Lisp/factorial-2.el @@ -0,0 +1,8 @@ +;; Recursive: +(defun fact (n) + "Return the factorial of integer N, which require to be positive or 0." + (if (not (and (integerp n) (>= n 0))) ; see above + (error "Function fact (N): Not a natural number or 0: %S" n)) + (cond ; (or use an (if ...) with an else part) + ((or (= n 0) (= n 1)) 1) + (t (* n (fact (1- n)))))) diff --git a/Task/Factorial/Emacs-Lisp/factorial-3.el b/Task/Factorial/Emacs-Lisp/factorial-3.el new file mode 100644 index 0000000000..b7d69a4dfa --- /dev/null +++ b/Task/Factorial/Emacs-Lisp/factorial-3.el @@ -0,0 +1,4 @@ +(require 'calc) +(calc-eval "fact(30)") +=> +"265252859812191058636308480000000" diff --git a/Task/Factorial/Euphoria/factorial-1.eu b/Task/Factorial/Euphoria/factorial-1.eu new file mode 100644 index 0000000000..f36ea675c6 --- /dev/null +++ b/Task/Factorial/Euphoria/factorial-1.eu @@ -0,0 +1,9 @@ +function factorial(integer n) + atom f = 1 + while n > 1 do + f *= n + n -= 1 + end while + + return f +end function diff --git a/Task/Factorial/Euphoria/factorial-2.eu b/Task/Factorial/Euphoria/factorial-2.eu new file mode 100644 index 0000000000..df1332ec75 --- /dev/null +++ b/Task/Factorial/Euphoria/factorial-2.eu @@ -0,0 +1,7 @@ +function factorial(integer n) + if n > 1 then + return factorial(n-1) * n + else + return 1 + end if +end function diff --git a/Task/Factorial/Euphoria/factorial-3.eu b/Task/Factorial/Euphoria/factorial-3.eu new file mode 100644 index 0000000000..e32d25e6da --- /dev/null +++ b/Task/Factorial/Euphoria/factorial-3.eu @@ -0,0 +1,7 @@ +function factorial(integer n, integer acc = 1) + if n <= 0 then + return acc + else + return factorial(n-1, n*acc) + end if +end function diff --git a/Task/Factorial/Euphoria/factorial-4.eu b/Task/Factorial/Euphoria/factorial-4.eu new file mode 100644 index 0000000000..0ef293f577 --- /dev/null +++ b/Task/Factorial/Euphoria/factorial-4.eu @@ -0,0 +1,106 @@ +include std/mathcons.e + +enum MUL_LLL, + TESTEQ_LIL, + TESTLT_LIL, + TRUEGO_LL, + MOVE_LL, + INCR_L, + TESTGT_LLL, + GOTO_L, + OUT_LI, + OUT_II, + STOP + +global sequence tape = { + 1, + 1, + 0, + 0, + 0, + {TESTLT_LIL, 5, 0, 4}, + {TRUEGO_LL, 4, 22}, + {TESTEQ_LIL, 5, 0, 4}, + {TRUEGO_LL, 4, 20}, + {MUL_LLL, 1, 2, 3}, + {TESTEQ_LIL, 3, PINF, 4}, + {TRUEGO_LL, 4, 18}, + {MOVE_LL, 3, 1}, + {INCR_L, 2}, + {TESTGT_LLL, 2, 5, 4 }, + {TRUEGO_LL, 4, 18}, + {GOTO_L, 10}, + {OUT_LI, 3, "%.0f\n"}, + {STOP}, + {OUT_II, 1, "%.0f\n"}, + {STOP}, + {OUT_II, "Negative argument", "%s\n"}, + {STOP} +} + +global integer ip = 1 + +procedure eval( sequence cmd ) + atom i = 1 + while i <= length( cmd ) do + switch cmd[ i ] do + case MUL_LLL then -- multiply location location giving location + tape[ cmd[ i + 3 ] ] = tape[ cmd[ i + 1 ] ] * tape[ cmd[ i + 2 ] ] + i += 3 + case TESTEQ_LIL then -- test if location eq value giving location + tape[ cmd[ i + 3 ]] = ( tape[ cmd[ i + 1 ] ] = cmd[ i + 2 ] ) + i += 3 + case TESTLT_LIL then -- test if location eq value giving location + tape[ cmd[ i + 3 ]] = ( tape[ cmd[ i + 1 ] ] < cmd[ i + 2 ] ) + i += 3 + case TRUEGO_LL then -- if true in location, goto location + if tape[ cmd[ i + 1 ] ] then + ip = cmd[ i + 2 ] - 1 + end if + i += 2 + case MOVE_LL then -- move value at location to location + tape[ cmd[ i + 2 ] ] = tape[ cmd[ i + 1 ] ] + i += 2 + case INCR_L then -- increment value at location + tape[ cmd[ i + 1 ] ] += 1 + i += 1 + case TESTGT_LLL then -- test if location gt location giving location + tape[ cmd[ i + 3 ]] = ( tape[ cmd[ i + 1 ] ] > tape[ cmd[ i + 2 ] ] ) + i += 3 + case GOTO_L then -- goto location + ip = cmd[ i + 1 ] - 1 + i += 1 + case OUT_LI then -- output location using format + printf( 1, cmd[ i + 2], tape[ cmd[ i + 1 ] ] ) + i += 2 + case OUT_II then -- output immediate using format + if sequence( cmd[ i + 1 ] ) then + printf( 1, cmd[ i + 2], { cmd[ i + 1 ] } ) + else + printf( 1, cmd[ i + 2], cmd[ i + 1 ] ) + end if + i += 2 + case STOP then -- stop + abort(0) + end switch + i += 1 + end while +end procedure + +include std/convert.e + +sequence cmd = command_line() +if length( cmd ) > 2 then + puts( 1, cmd[ 3 ] & "! = " ) + tape[ 5 ] = to_number(cmd[3]) +else + puts( 1, "eui fact.ex \n" ) + abort(1) +end if + +while 1 do + if sequence( tape[ ip ] ) then + eval( tape[ ip ] ) + end if + ip += 1 +end while diff --git a/Task/Factorial/Gleam/factorial-1.gleam b/Task/Factorial/Gleam/factorial-1.gleam new file mode 100644 index 0000000000..6521eeb481 --- /dev/null +++ b/Task/Factorial/Gleam/factorial-1.gleam @@ -0,0 +1 @@ +list.fold(int.range(1, n + 1, [], list.prepend), 1, int.multiply) diff --git a/Task/Factorial/Gleam/factorial-2.gleam b/Task/Factorial/Gleam/factorial-2.gleam new file mode 100644 index 0000000000..dbab0f45f6 --- /dev/null +++ b/Task/Factorial/Gleam/factorial-2.gleam @@ -0,0 +1,6 @@ +pub fn fac(n: Int) -> Int { + case n { + 1 -> 1 + n -> n * fac(n - 1) + } +} diff --git a/Task/Factorial/Gleam/factorial-3.gleam b/Task/Factorial/Gleam/factorial-3.gleam new file mode 100644 index 0000000000..dbc03d5750 --- /dev/null +++ b/Task/Factorial/Gleam/factorial-3.gleam @@ -0,0 +1,10 @@ +pub fn fac(n: Int) -> Int { + fac_helper(n, n - 1) +} + +fn fac_helper(n: Int, acc: Int) -> Int { + case n, acc { + n, 1 -> n + n, i -> fac_helper(n * i, i - 1) + } +} diff --git a/Task/Factorial/Haxe/factorial-1.hx b/Task/Factorial/Haxe/factorial-1.hx new file mode 100644 index 0000000000..20d705e6a3 --- /dev/null +++ b/Task/Factorial/Haxe/factorial-1.hx @@ -0,0 +1,6 @@ +static function factorial(n:Int):Int { + var result = 1; + while (1 0 then call Recursive 10, '1 13 71 450 3249 25206 205022' else call Recursive 10, '1 13 71 450 3249' -call Imperative 1E5,'1 13 71 450 3249 25206' +call Imperative 100000,'1 13 71 450 3249 25206' call Timer exit @@ -24,10 +24,10 @@ say return Imperative: -call ResetMemo +Memo.='' call Time('R') arg d,p -numeric digits d; Fact. = 0 +numeric digits d say 'Imperative in' d 'digits precision...' do i = 1 to Words(p) call Time('r'); f = Word(p,i); h = Fact(f) @@ -41,10 +41,10 @@ say return Recursive: -call ResetMemo +Memo.='' call Time('R') arg d,p -numeric digits d; Fact. = 0 +numeric digits d say 'Recursive in' d 'digits precision...' do i = 1 to Words(p) call Time('r'); f = Word(p,i); h = Recurs(f) diff --git a/Task/Factorial/RISC-V-Assembly/factorial.asm b/Task/Factorial/RISC-V-Assembly/factorial.asm new file mode 100644 index 0000000000..f3139a188e --- /dev/null +++ b/Task/Factorial/RISC-V-Assembly/factorial.asm @@ -0,0 +1,131 @@ +# riscv assembly raspberry pico2 rp2350 +# program factorial.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessLargeNumber: .asciz "Number N to large. \n" +szMessNegNumber: .asciz "Number N is negative. \n" + +szMessResult: .ascii "Resultat = " # message result + +.align 2 + + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + li a0,-10 + call factorial # + li a0,0 + call factorial # + li a0,10 + call factorial # + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* compute factorial */ +/**********************************************/ +/* a0 value */ +factorial: # INFO: factorial + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + bltz a0,99f # is negative ? + li t0,1 + ble a0,t0,1f # is 0 or 1 + call computeFactorial + li t0,-1 # error overflow ? + beq a0,t0,98f +1: # display result + la a1,sConvArea + call conversion10 + la a0,szMessResult + call writeString + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + j 100f +98: + la a0,szMessLargeNumber + call writeString + j 100f +99: + la a0,szMessNegNumber + call writeString + j 100f +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* compute factorial */ +/**********************************************/ +/* a0 value */ +computeFactorial: # INFO:computeFactorial + addi sp,sp, -8 # reserve stack + sw ra,0(sp) + sw s0,4(sp) + li t0,1 + beq a0,t0,100f # if n = 1 return + mv s0,a0 + addi a0,a0,-1 + call computeFactorial + li t0,-1 # error overflow ? + beq a0,t0,100f + mulh t0,a0,s0 # compute half high 32 bits + beqz t0,1f # is ok if result is zero + li a0,-1 # error overflow + j 100f +1: + mul a0,a0,s0 # multiplication +100: + lw ra,0(sp) + lw s0,4(sp) + addi sp,sp, 8 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Factorial/Rebol/factorial.rebol b/Task/Factorial/Rebol/factorial.rebol new file mode 100644 index 0000000000..feb9d5d6c4 --- /dev/null +++ b/Task/Factorial/Rebol/factorial.rebol @@ -0,0 +1,56 @@ +Rebol [ + Title: "Factorial" + URL: http://rosettacode.org/wiki/Factorial_function +] + +;; Standard recursive implementation. +factorial: func [n][ + either n > 1 [n * factorial n - 1] [1] +] + +;; Iteration. +ifactorial: func [n][ + f: 1 + for i 2 n 1 [f: f * i] + f +] + +either system/version < 3.0.0 [ + ; Automatic memoization. + ; I'm just going to say up front that this is a stunt. However, you've + ; got to admit it's pretty nifty. Note that the 'memo' function + ; works with an unlimited number of arguments (although the expected + ; gains decrease as the argument count increases). + memo: func [ + "Defines memoizing function -- keeps arguments/results for later use." + args [block!] "Function arguments. Just specify variable names." + body [block!] "The body block of the function." + /local m-args m-r + ][ + do compose/deep [ + func [ + (args) + /dump "Dump memory." + ][ + m-args: [] + if dump [return m-args] + + if m-r: select/only m-args reduce [(args)] [return m-r] + + m-r: do [(body)] + append m-args reduce [reduce [(args)] m-r] + m-r + ] + ] + ] + + mfactorial: memo [n][ + either n > 1 [n * mfactorial n - 1] [1] + ] +][ + ;; Above hack is not supported in Rebol3 + mfactorial: func[i][none] +] + +;; Test them on numbers zero to ten. +for i 0 10 1 [print [i ":" factorial i ifactorial i mfactorial i]] diff --git a/Task/Factorial/Rocq/factorial.rocq b/Task/Factorial/Rocq/factorial.rocq new file mode 100644 index 0000000000..c5656f2507 --- /dev/null +++ b/Task/Factorial/Rocq/factorial.rocq @@ -0,0 +1,5 @@ +Fixpoint factorial (n : nat) : nat := + match n with + | 0 => 1 + | S k => (S k) * (factorial k) + end. diff --git a/Task/Factorial/Tcl/factorial-8.tcl b/Task/Factorial/Tcl/factorial-8.tcl new file mode 100644 index 0000000000..46e5e0fcab --- /dev/null +++ b/Task/Factorial/Tcl/factorial-8.tcl @@ -0,0 +1,5 @@ +package require math::special + +proc gfact n { + expr {round([::math::special::Gamma [expr {$n+1}]])} +} diff --git a/Task/Factorial/VBScript/factorial.vbs b/Task/Factorial/VBScript/factorial.vbs new file mode 100644 index 0000000000..f241cf1c40 --- /dev/null +++ b/Task/Factorial/VBScript/factorial.vbs @@ -0,0 +1,41 @@ +Dim lookupTable(170), returnTable(170), currentPosition, input +currentPosition = 0 + +Do While True + input = InputBox("Please type a number (-1 to quit):") + MsgBox "The factorial of " & input & " is " & factorial(CDbl(input)) +Loop + +Function factorial (x) + If x = -1 Then + WScript.Quit 0 + End If + Dim temp + temp = lookup(x) + If x <= 1 Then + factorial = 1 + ElseIf temp <> 0 Then + factorial = temp + Else + temp = factorial(x - 1) * x + store x, temp + factorial = temp + End If +End Function + +Function lookup (x) + Dim i + For i = 0 To currentPosition - 1 + If lookupTable(i) = x Then + lookup = returnTable(i) + Exit Function + End If + Next + lookup = 0 +End Function + +Function store (x, y) + lookupTable(currentPosition) = x + returnTable(currentPosition) = y + currentPosition = currentPosition + 1 +End Function diff --git a/Task/Factorial/VHDL/factorial.vhd b/Task/Factorial/VHDL/factorial.vhd new file mode 100644 index 0000000000..d10cd76000 --- /dev/null +++ b/Task/Factorial/VHDL/factorial.vhd @@ -0,0 +1,74 @@ +LIBRARY ieee; +USE ieee.std_logic_1164.ALL; +USE ieee.numeric_std.ALL; + +ENTITY Factorial IS + GENERIC ( + Nbin : INTEGER := 3 ; -- number of bit to input number + Nbou : INTEGER := 13) ; -- number of bit to output factorial + + PORT ( + clk : IN STD_LOGIC ; -- clock of circuit + sr : IN STD_LOGIC_VECTOR(1 DOWNTO 0); -- set and reset + N : IN STD_LOGIC_VECTOR(Nbin-1 DOWNTO 0) ; -- max number + Fn : OUT STD_LOGIC_VECTOR(Nbou-1 DOWNTO 0)); -- factorial of "n" + +END Factorial ; + +ARCHITECTURE Behavior OF Factorial IS +---------------------- Program Multiplication -------------------------------- + FUNCTION Mult ( CONSTANT MFa : IN UNSIGNED ; + CONSTANT MI : IN UNSIGNED ) RETURN UNSIGNED IS + VARIABLE Z : UNSIGNED(MFa'RANGE) ; + VARIABLE U : UNSIGNED(MI'RANGE) ; + BEGIN + Z := TO_UNSIGNED(0, MFa'LENGTH) ; -- to obtain the multiplication + U := MI ; -- regressive counter + LOOP + Z := Z + MFa ; -- make multiplication + U := U - 1 ; + EXIT WHEN U = 0 ; + END LOOP ; + RETURN Z ; + END Mult ; +-------------------Program Factorial --------------------------------------- + FUNCTION Fact (CONSTANT Nx : IN NATURAL ) RETURN UNSIGNED IS + VARIABLE C : NATURAL RANGE 0 TO 2**Nbin-1 ; + VARIABLE I : UNSIGNED(Nbin-1 DOWNTO 0) ; + VARIABLE Fa : UNSIGNED(Nbou-1 DOWNTO 0) ; + BEGIN + C := 0 ; -- counter + I := TO_UNSIGNED(1, Nbin) ; + Fa := TO_UNSIGNED(1, Nbou) ; + LOOP + EXIT WHEN C = Nx ; -- end loop + C := C + 1 ; -- progressive couter + Fa := Mult (Fa , I ); -- call function to make a multiplication + I := I + 1 ; -- + END LOOP ; + RETURN Fa ; + END Fact ; +--------------------- Program TO Call Factorial Function ------------------------------------------------------ + TYPE Table IS ARRAY (0 TO 2**Nbin-1) OF UNSIGNED(Nbou-1 DOWNTO 0) ; + FUNCTION Call_Fact RETURN Table IS + VARIABLE Fc : Table ; + BEGIN + FOR c IN 0 TO 2**Nbin-1 LOOP + Fc(c) := Fact(c) ; + END LOOP ; + RETURN Fc ; + END FUNCTION Call_Fact; + + CONSTANT Result : Table := Call_Fact ; + ------------------------------------------------------------------------------------------------------------ +SIGNAL Nin : STD_LOGIC_VECTOR(N'RANGE) ; +BEGIN -- start of architecture + + +Nin <= N WHEN RISING_EDGE(clk) AND sr = "10" ELSE + (OTHERS => '0') WHEN RISING_EDGE(clk) AND sr = "01" ELSE + UNAFFECTED; + +Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ; + +END Behavior ; diff --git a/Task/Factorions/Ada/factorions.adb b/Task/Factorions/Ada/factorions.adb new file mode 100644 index 0000000000..a8d21fb554 --- /dev/null +++ b/Task/Factorions/Ada/factorions.adb @@ -0,0 +1,64 @@ +with Ada.Text_IO; + +procedure Factorions is + subtype Factorial_Domain is Natural range 0 .. 11; + subtype Log_Base is Positive range 2 .. Positive'Last; + type Result_Table is array (Factorial_Domain) of Positive; + + Factorial : Result_Table; + Search_Limit : Positive := 1_500_000; + + procedure Precompute_Factorials is + begin + Factorial (0) := 1; + + for I in 1 .. Factorial'Last loop + Factorial (I) := I * Factorial (I - 1); + end loop; + end Precompute_Factorials; + + function Floor_Log (Number : Positive; Base : Log_Base) return Natural is + Remaining : Natural := Number; + Floor_Log : Natural := 0; + begin + while Remaining > Base loop + Remaining := Remaining / Base; + Floor_Log := Floor_Log + 1; + end loop; + + return Floor_Log; + end Floor_Log; + + function Digit (Number, Index : Natural; Base : Log_Base) return Natural is + begin + return (Number / (Base ** Index)) mod Base; + end Digit; + + function Is_Factorion (Number : Positive; Base : Log_Base) return Boolean is + Digit_Sum : Natural := 0; + begin + for I in 0 .. Floor_Log (Number, Base) loop + Digit_Sum := Digit_Sum + Factorial (Digit (Number, I, Base)); + end loop; + + return Digit_Sum = Number; + end Is_Factorion; + + procedure Show_Factorions (Base : Log_Base) is + begin + Ada.Text_IO.Put_Line ("Search Base " & Base'Image); + for I in 1 .. Search_Limit loop + if Is_Factorion (I, Base) then + Ada.Text_IO.Put_Line (I'Image); + end if; + end loop; + Ada.Text_IO.Put_Line ("Done Base " & Base'Image); + end Show_Factorions; + +begin + Precompute_Factorials; + Show_Factorions (9); + Show_Factorions (10); + Show_Factorions (11); + Show_Factorions (12); +end Factorions; diff --git a/Task/Factorions/EasyLang/factorions.easy b/Task/Factorions/EasyLang/factorions.easy index 0e6f41446e..014c445c4c 100644 --- a/Task/Factorions/EasyLang/factorions.easy +++ b/Task/Factorions/EasyLang/factorions.easy @@ -1,5 +1,4 @@ len fact[] 12 -arrbase fact[] 0 # fact[0] = 1 for n = 1 to 11 diff --git a/Task/Factorions/Fortran/factorions.f b/Task/Factorions/Fortran/factorions.f new file mode 100644 index 0000000000..a142cc2e4a --- /dev/null +++ b/Task/Factorions/Fortran/factorions.f @@ -0,0 +1,52 @@ +! Factorions +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +program Factorions +integer, parameter :: minBase=9, maxBase = 12 ! minumum and maximum base used in this little program +integer, parameter :: factLim=1499999 ! Maximum factorial Number for all bases that are used here +integer, dimension(0:maxBase-1) :: fact ! Stored factorials for numbers 0...12 + +integer :: ii, jj, base + +! Prepare cached factorial function +fact = 1 +do ii=1, maxBase-1 + do jj= 2, ii + fact(ii) = fact(ii) * jj + enddo +end do + +! +! Brute force: for all bases, for all numbers 1...max tes each number and print if its a factorion. +! +do base=minBase, maxBase + write (*, '("The factorions in base ", i0, " are:")') base + do ii=1, factLim + if (isFactorion (ii, base)) write (*, '(1x,i0)', advance='no') ii + enddo + write (*,'(/)') +end do + +contains + +! +! Separate digits d of number n in base b, sum up d!, and compare result with n. +! +function isFactorion (n,b) result (YN) +integer, intent (in) :: n, b +logical :: YN +integer :: dig, nn, facts_sum + +nn = N +facts_sum = 0 +do while (nn .ne. 0) + dig = mod (nn, b) + nn = nn / b + + facts_sum = facts_sum + fact(dig) +enddo +yn = facts_sum .eq. n + +end function isFactorion +end program Factorions diff --git a/Task/Factorions/JavaScript/factorions.js b/Task/Factorions/JavaScript/factorions.js new file mode 100644 index 0000000000..a9a3f2c3ae --- /dev/null +++ b/Task/Factorions/JavaScript/factorions.js @@ -0,0 +1,25 @@ +function factorial(n) { + if (n <= 1) { + return 1; + } + let a = [...Array(n + 1).keys()]; + a.shift(); + return a.reduce((x, y) => x * y); +} + +function fact_digsum(n, b) { + if (n > b - 1) { + return factorial(n % b) + fact_digsum(Math.floor(n / b), b); + } + return factorial(n); +} + +for (let i = 9; i <= 12; i++) { + console.log(`Factorions in base ${i}:`); + for (let j = 1; j < 1499999; j++) { + if (j == fact_digsum(j, i)) { + console.log(j); + } + } + console.log(); +} diff --git a/Task/Factorions/R/factorions.r b/Task/Factorions/R/factorions.r index 52a5664ef8..9f1c569b7e 100644 --- a/Task/Factorions/R/factorions.r +++ b/Task/Factorions/R/factorions.r @@ -1,12 +1,12 @@ -fact_digsum <- function(n, b){ - if(n>b-1){ +fact_digsum <- function(n, b) { + if(n > b-1) { factorial(n%%b)+fact_digsum(n%/%b, b) } else factorial(n) } -for(i in 9:12){ +for(i in 9:12) { cat("\nFactorions in base ", i, ":\n", sep="") - for(j in 1:1499999){ - if(j==fact_digsum(j, i)) cat(j, "") + for(j in 1:1499999) { + if(j == fact_digsum(j, i)) cat(j, "") } } diff --git a/Task/Factorions/VBScript/factorions.vbs b/Task/Factorions/VBScript/factorions.vbs new file mode 100644 index 0000000000..5a7aa8e13b --- /dev/null +++ b/Task/Factorions/VBScript/factorions.vbs @@ -0,0 +1,23 @@ +' Factorions - VBScript - PG - 26/04/2020 + Dim fact() + nn1=9 : nn2=12 + lim=1499999 + ReDim fact(nn2) + fact(0)=1 + For i=1 To nn2 + fact(i)=fact(i-1)*i + Next + For base=nn1 To nn2 + list="" + For i=1 To lim + s=0 + t=i + Do While t<>0 + d=t Mod base + s=s+fact(d) + t=t\base + Loop + If s=i Then list=list &" "& i + Next + Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list + Next diff --git a/Task/Factorions/Vyxal/factorions.vyxal b/Task/Factorions/Vyxal/factorions.vyxal new file mode 100644 index 0000000000..bf2fb337c6 --- /dev/null +++ b/Task/Factorions/Vyxal/factorions.vyxal @@ -0,0 +1,7 @@ +λ2|→B:←Bτƛ¡}∑$_-¬}£ # check whether factorion +⟨9|10|11|12⟩(`Base `₴n:₴\:,→b + 1500000 ( + n 1000 ≠[ + ←b n¥†[n,]] + ) +) diff --git a/Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.adb b/Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.adb new file mode 100644 index 0000000000..3a8772ee0c --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Ada/factors-of-a-mersenne-number.adb @@ -0,0 +1,68 @@ +with Ada.Text_IO; +-- reuse Is_Prime from [[Primality by Trial Division]] +with Is_Prime; + +procedure Mersenne is + function Is_Set (Number : Natural; Bit : Positive) return Boolean is + begin + return Number / 2 ** (Bit - 1) mod 2 = 1; + end Is_Set; + + function Get_Max_Bit (Number : Natural) return Natural is + Test : Natural := 0; + begin + while 2 ** Test <= Number loop + Test := Test + 1; + end loop; + return Test; + end Get_Max_Bit; + + function Modular_Power (Base, Exponent, Modulus : Positive) return Natural is + Maximum_Bit : constant Natural := Get_Max_Bit (Exponent); + Square : Natural := 1; + begin + for Bit in reverse 1 .. Maximum_Bit loop + Square := Square ** 2; + if Is_Set (Exponent, Bit) then + Square := Square * Base; + end if; + Square := Square mod Modulus; + end loop; + return Square; + end Modular_Power; + + Not_A_Prime_Exponent : exception; + + function Get_Factor (Exponent : Positive) return Natural is + Factor : Positive; + begin + if not Is_Prime (Exponent) then + raise Not_A_Prime_Exponent; + end if; + for K in 1 .. 16384 / Exponent loop + Factor := 2 * K * Exponent + 1; + if Factor mod 8 = 1 or else Factor mod 8 = 7 then + if Is_Prime (Factor) and then Modular_Power (2, Exponent, Factor) = 1 then + return Factor; + end if; + end if; + end loop; + return 0; + end Get_Factor; + + To_Test : constant Positive := 929; + Factor : Natural; +begin + Ada.Text_IO.Put ("2 **" & Integer'Image (To_Test) & " - 1 "); + begin + Factor := Get_Factor (To_Test); + if Factor = 0 then + Ada.Text_IO.Put_Line ("is prime."); + else + Ada.Text_IO.Put_Line ("has factor" & Integer'Image (Factor)); + end if; + exception + when Not_A_Prime_Exponent => + Ada.Text_IO.Put_Line ("is not a Mersenne number"); + end; +end Mersenne; diff --git a/Task/Factors-of-a-Mersenne-number/FutureBasic/factors-of-a-mersenne-number.basic b/Task/Factors-of-a-Mersenne-number/FutureBasic/factors-of-a-mersenne-number.basic new file mode 100644 index 0000000000..2552a45c70 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/FutureBasic/factors-of-a-mersenne-number.basic @@ -0,0 +1,108 @@ +// +// Factors of Mersenne number +// +// Using FutureBasic 7.0.36 +// October 2025, R.W. + +include "gmp.incl" + +_scanMax = 2000000 // max k scan set at 2 million + +// ------------------------------------------------------------ +// Exponent primality using GMP (mpz_probab_prime_p) +// Returns _true if p is (probably) prime; _false otherwise. + +local fn IsPrimeP_mpz( p as UInt32 ) as BOOL + mpz_t z + int res + if p < 2 then return _false + mpz_init( z ) + mpz_set_ui( z, p ) + // Miller–Rabin reps = 18 is sufficient + // res 0 = composite, 1 = probable, 2 = definite + res = fn mpz_probab_prime_p( z, 18 ) + mpz_clear( z ) + if res == 0 then return _false + // res 1 or 2 → treat as prime for gating +end fn = _True + +// ------------------------------------------------------------ +// Find first prime factor q of M_p = 2^p - 1 +// Scans q = 2 * k * p + 1 for k = 1..maxK. Returns 0 if none found. +// Precondition: caller ensures p is (probably) prime and p ≥ 2. +// +local fn FindMersenneFactor( p as UInt32, maxK as UInt64 ) as UInt64 + mpz_t qz, rz + UInt64 k, qCandidate + int isPrime + // Eliminate the obvious + if p < 2 then return 0 + if p == 2 then return 0 // M2 = 3 is prime + + mpz_init( qz ) + mpz_init( rz ) + k = 1 + while k <= maxK + // q = 2 * k * p + 1 (candidates with q ≡ 1 (mod 2p)) + qCandidate = (UInt64)2 * (UInt64)p * k + 1ULL + // primality screen for q + mpz_set_ui( qz, qCandidate ) + // Miller–Rabin reps = 18 is sufficient + isPrime = fn mpz_probab_prime_p( qz, 18 ) + if isPrime > 0 + // Test 2^p ≡ 1 (mod q) + mpz_set_ui( rz, 2 ) + mpz_powm_ui( rz, rz, p, qz ) + if fn mpz_cmp_ui( rz, 1 ) == 0 + mpz_clear( rz ) + mpz_clear( qz ) + return qCandidate + end if + end if + k = k + 1 + wend + mpz_clear( rz ) + mpz_clear( qz ) +end fn = 0 + +// ------------------------------------------------------------ +// M_p gating/message +// +local fn ReportMersenne( p as UInt32, maxK as UInt64 ) + UInt64 q + // Gate on exponent primality first + if fn IsPrimeP_mpz( p ) == _false + print @"M"; p; @" = 2^"; p; @" - 1 exponent is not prime" + exit fn + end if + // p is (probably) prime: try to find a factor of M_p + q = fn FindMersenneFactor( p, maxK ) + if q == 0 + // No factor found in scan range → either prime or factor > search bound + print @"M"; p; @" = 2^"; p; @" - 1 is prime (no factor found in range)" + else + print @"M"; p; @" = 2^"; p; @" - 1 is composite with factor "; q + end if +end fn + + +// Main + +window 1 + +UInt32 p +p = 929 // Rosetta Task requirement + +// start the clock +CFTimeInterval t +t = fn CACurrentMediaTime + +// note, if you need a range, just do a loop +// like: +// for p = 900 to 930 +fn ReportMersenne( p, _scanMax ) // 2 million k scans +// next p + +printf @"\nElapsed time: %.3f ms", (fn CACurrentMediaTime-t)*1000 + +HandleEvents diff --git a/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number.parigp b/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number.parigp new file mode 100644 index 0000000000..e5c3a4da90 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/PARI-GP/factors-of-a-mersenne-number.parigp @@ -0,0 +1,7 @@ +factorMersenne(p)={ + forstep(q=2*p+1,sqrt(2)<<(p\2),2*p, + [1,0,0,0,0,0,1][q%8] && Mod(2, q)^p==1 && return(q) + ); + 1<0){ + square <- square^2 + if(as.logical(exp_bin[1])) square <- square*base + exp_bin <- exp_bin[-1] + square <- square%%mod + } + return(square) +} + +k <- 1 +repeat{ + q <- 2*929*k+1 + if(!(q%%8 %in% c(1, 7))){ + k <- k+1 + next + } + if(mod_pow(2, 929, q)==1){ + cat("Found factor of M929:", q) + break + } + k <- k+1 +} diff --git a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx index ceb25887db..d137a271b5 100644 --- a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx +++ b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx @@ -1,4 +1,4 @@ --- 23 Aug 2025 +-- 25 Apr 2026 include Setting say 'FACTORS OF A MERSENNE NUMBER' @@ -44,4 +44,5 @@ if c <> 1 then say a 'is prime' return +-- Timer; Primes; Isqrt include Math diff --git a/Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vbs b/Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vbs new file mode 100644 index 0000000000..ebd698dd12 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vbs @@ -0,0 +1,63 @@ +' Factors of a Mersenne number + for i=1 to 59 + z=i + if z=59 then z=929 ':) 61 turns into 929. + if isPrime(z) then + r=testM(z) + zz=left("M" & z & space(4),4) + if r=0 then + Wscript.echo zz & " prime." + else + Wscript.echo zz & " not prime, a factor: " & r + end if + end if + next + +function modPow(base,n,div) + dim i,y,z + i = n : y = 1 : z = base + do while i + if i and 1 then y = (y * z) mod div + z = (z * z) mod div + i = i \ 2 + loop + modPow= y +end function + +function isPrime(x) + dim i + if x=2 or x=3 or _ + x=5 or x=7 _ + then isPrime=1: exit function + if x<11 then isPrime=0: exit function + if x mod 2=0 then isPrime=0: exit function + if x mod 3=0 then isPrime=0: exit function + i=5 + do + if (x mod i) =0 or _ + (x mod (i+2)) =0 _ + then isPrime=0: exit function + if i*i>x then isPrime=1: exit function + i=i+6 + loop +end function + +function testM(x) + dim sqroot,k,q + sqroot=Sqr(2^x) + k=1 + do + q=2*k*x+1 + if q>sqroot then exit do + if (q and 7)=1 or (q and 7)=7 then + if isPrime(q) then + if modPow(2,x,q)=1 then + testM=q + exit function + end if + end if + end if + k=k+1 + loop + testM=0 +end function diff --git a/Task/Factors-of-an-integer/ANSI-BASIC/factors-of-an-integer.basic b/Task/Factors-of-an-integer/ANSI-BASIC/factors-of-an-integer.basic new file mode 100644 index 0000000000..d1ae6a7993 --- /dev/null +++ b/Task/Factors-of-an-integer/ANSI-BASIC/factors-of-an-integer.basic @@ -0,0 +1,18 @@ +100 REM Factors of an integer +110 DECLARE EXTERNAL SUB PrintFactors +120 CALL PrintFactors(11) +130 CALL PrintFactors(21) +140 CALL PrintFactors(32) +150 CALL PrintFactors(45) +160 CALL PrintFactors(67) +170 CALL PrintFactors(96) +180 END +190 ! +200 EXTERNAL SUB PrintFactors(N) +210 PRINT N; "=>"; +220 LET N = ABS(N) +230 FOR I = 1 TO INT(N / 2) +240 IF MOD(N, I) = 0 THEN PRINT I; +250 NEXT I +260 PRINT N +270 END SUB diff --git a/Task/Factors-of-an-integer/Ada/factors-of-an-integer.adb b/Task/Factors-of-an-integer/Ada/factors-of-an-integer.adb new file mode 100644 index 0000000000..4212998a28 --- /dev/null +++ b/Task/Factors-of-an-integer/Ada/factors-of-an-integer.adb @@ -0,0 +1,22 @@ +with Ada.Text_IO; +with Ada.Command_Line; +procedure Factors is + Number : Positive; + Test_Nr : Positive := 1; +begin + if Ada.Command_Line.Argument_Count /= 1 then + Ada.Text_IO.Put (Ada.Text_IO.Standard_Error, "Missing argument!"); + Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); + return; + end if; + Number := Positive'Value (Ada.Command_Line.Argument (1)); + Ada.Text_IO.Put ("Factors of" & Positive'Image (Number) & ": "); + loop + if Number mod Test_Nr = 0 then + Ada.Text_IO.Put (Positive'Image (Test_Nr) & ","); + end if; + exit when Test_Nr ** 2 >= Number; + Test_Nr := Test_Nr + 1; + end loop; + Ada.Text_IO.Put_Line (Positive'Image (Number) & "."); +end Factors; diff --git a/Task/Factors-of-an-integer/AutoIt/factors-of-an-integer.au3 b/Task/Factors-of-an-integer/AutoIt/factors-of-an-integer.au3 new file mode 100644 index 0000000000..24d556fd64 --- /dev/null +++ b/Task/Factors-of-an-integer/AutoIt/factors-of-an-integer.au3 @@ -0,0 +1,13 @@ +;AutoIt Version: 3.2.10.0 +$num = 45 +MsgBox (0,"Factors", "Factors of " & $num & " are: " & factors($num)) +consolewrite ("Factors of " & $num & " are: " & factors($num)) +Func factors($intg) + $ls_factors="" + For $i = 1 to $intg/2 + if ($intg/$i - int($intg/$i))=0 Then + $ls_factors=$ls_factors&$i &", " + EndIf + Next + Return $ls_factors&$intg +EndFunc diff --git a/Task/Factors-of-an-integer/Ballerina/factors-of-an-integer.ballerina b/Task/Factors-of-an-integer/Ballerina/factors-of-an-integer.ballerina new file mode 100644 index 0000000000..94a19fcc82 --- /dev/null +++ b/Task/Factors-of-an-integer/Ballerina/factors-of-an-integer.ballerina @@ -0,0 +1,24 @@ +// https://rosettacode.org/wiki/Factors_of_an_integer +// https://rosettacode.org/wiki/Factors_of_an_integer +import ballerina/io; + +function factors(int n) returns int[] { + int[] f = [1, n]; + int i = 2; + while i*i <= n { + if n % i == 0 { + f.push(i); + if i*i != n { + f.push(n / i); + } + } + i += 1; + } + return f.sort(); +} + +public function main() { + foreach int i in [45, 53, 64] { + io:println(factors(i)); + } +} diff --git a/Task/Factors-of-an-integer/COBOL/factors-of-an-integer.cob b/Task/Factors-of-an-integer/COBOL/factors-of-an-integer.cob new file mode 100644 index 0000000000..107623e3fa --- /dev/null +++ b/Task/Factors-of-an-integer/COBOL/factors-of-an-integer.cob @@ -0,0 +1,40 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. FACTORS. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 CALCULATING. + 03 NUM USAGE BINARY-LONG VALUE ZERO. + 03 LIM USAGE BINARY-LONG VALUE ZERO. + 03 CNT USAGE BINARY-LONG VALUE ZERO. + 03 DIV USAGE BINARY-LONG VALUE ZERO. + 03 REM USAGE BINARY-LONG VALUE ZERO. + 03 ZRS USAGE BINARY-SHORT VALUE ZERO. + + 01 DISPLAYING. + 03 DIS PIC 9(10) USAGE DISPLAY. + + PROCEDURE DIVISION. + MAIN-PROCEDURE. + DISPLAY "Factors of? " WITH NO ADVANCING + ACCEPT NUM + DIVIDE NUM BY 2 GIVING LIM. + + PERFORM VARYING CNT FROM 1 BY 1 UNTIL CNT > LIM + DIVIDE NUM BY CNT GIVING DIV REMAINDER REM + IF REM = 0 + MOVE CNT TO DIS + PERFORM SHODIS + END-IF + END-PERFORM. + + MOVE NUM TO DIS. + PERFORM SHODIS. + STOP RUN. + + SHODIS. + MOVE ZERO TO ZRS. + INSPECT DIS TALLYING ZRS FOR LEADING ZERO. + DISPLAY DIS(ZRS + 1:) + EXIT PARAGRAPH. + + END PROGRAM FACTORS. diff --git a/Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chpl b/Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chpl new file mode 100644 index 0000000000..cd2c758b67 --- /dev/null +++ b/Task/Factors-of-an-integer/Chapel/factors-of-an-integer.chpl @@ -0,0 +1,8 @@ +iter factors(n) { + for i in 1..floor(sqrt(n)):int { + if n % i == 0 then { + yield i; + yield n / i; + } + } +} diff --git a/Task/Factors-of-an-integer/EMal/factors-of-an-integer.emal b/Task/Factors-of-an-integer/EMal/factors-of-an-integer.emal index 82cf5d4000..0b09fd7d4f 100644 --- a/Task/Factors-of-an-integer/EMal/factors-of-an-integer.emal +++ b/Task/Factors-of-an-integer/EMal/factors-of-an-integer.emal @@ -1,13 +1,13 @@ -fun factors = List by int n - List result = int[1] +fun factors ← List by int n + List result ← int[1] for each int i in range(2, n) - if n % i == 0 do result.append(i) end + if n % i æ 0 do result.append(i) end end result.append(n) return result end -fun main = int by List args - int n = when(args.length == 0, ask(int, "Enter the number to factor please "), int!args[0]) +fun main ← int by List args + int n ← when(args.length æ 0, ask(int, "Enter the number to factor please: "), int!args[0]) writeLine(factors(n)) return 0 end diff --git a/Task/Factors-of-an-integer/Loglan82/factors-of-an-integer.loglan82 b/Task/Factors-of-an-integer/Loglan82/factors-of-an-integer.loglan82 new file mode 100644 index 0000000000..3b1d7a58f6 --- /dev/null +++ b/Task/Factors-of-an-integer/Loglan82/factors-of-an-integer.loglan82 @@ -0,0 +1,25 @@ +(* Factors of an integer *) + +block + + unit write_factors: procedure (n: integer); + var + i: integer; + begin + write(n, " => "); + n := abs(n); + for i := 1 to n div 2 + do + if n mod i = 0 then write(i: 1, " ") fi + od; + writeln(n: 1); + end; + +begin + call write_factors(11); + call write_factors(21); + call write_factors(32); + call write_factors(45); + call write_factors(67); + call write_factors(96); +end; diff --git a/Task/Factors-of-an-integer/Modula-2/factors-of-an-integer.mod2 b/Task/Factors-of-an-integer/Modula-2/factors-of-an-integer.mod2 new file mode 100644 index 0000000000..6153345ff3 --- /dev/null +++ b/Task/Factors-of-an-integer/Modula-2/factors-of-an-integer.mod2 @@ -0,0 +1,33 @@ +MODULE FactOfInt; +(* Factors of an integer *) + +FROM SWholeIO IMPORT + WriteInt; +FROM STextIO IMPORT + WriteLn, WriteString; + +PROCEDURE WriteFactors(N: INTEGER); +VAR + I: INTEGER; +BEGIN + WriteInt(N, 1); + WriteString(" => "); + N := ABS(N); + FOR I := 1 TO N DIV 2 DO + IF N MOD I = 0 THEN + WriteInt(I, 1); + WriteString(" ") + END + END; + WriteInt(N, 1); + WriteLn +END WriteFactors; + +BEGIN + WriteFactors(11); + WriteFactors(21); + WriteFactors(32); + WriteFactors(45); + WriteFactors(67); + WriteFactors(96) +END FactOfInt. diff --git a/Task/Factors-of-an-integer/MoonRock/factors-of-an-integer.moonrock b/Task/Factors-of-an-integer/MoonRock/factors-of-an-integer.moonrock new file mode 100644 index 0000000000..bd4f263893 --- /dev/null +++ b/Task/Factors-of-an-integer/MoonRock/factors-of-an-integer.moonrock @@ -0,0 +1,25 @@ +' Factors of an integer +BEGIN DEF +SUB PrintFactors(N%) + +BEGIN CODE +CALL PrintFactors(11) +CALL PrintFactors(21) +CALL PrintFactors(32) +CALL PrintFactors(45) +CALL PrintFactors(67) +CALL PrintFactors(96) +END + +SUB PrintFactors(N%) +PRINT N% + " => " +NA% = ABS(N%) +NDiv2% = NA% \ 2 +FOR I% = 1 TO NDiv2% + NModI% = NA% MOD I% + IF NModI% = 0 THEN + PRINT I% + " " + ENDIF +NEXT +PRINT NA% + "\n" +END SUB diff --git a/Task/Factors-of-an-integer/Nu/factors-of-an-integer-1.nu b/Task/Factors-of-an-integer/Nu/factors-of-an-integer-1.nu new file mode 100644 index 0000000000..abc186b30f --- /dev/null +++ b/Task/Factors-of-an-integer/Nu/factors-of-an-integer-1.nu @@ -0,0 +1,5 @@ +let n = 24 + 1..($n | math sqrt | math floor) | + where { |$f| $n mod $f == 0 } | + each { |$f| [$f (($n / $f) | into int) ] } | + sort | grid -w 80 diff --git a/Task/Factors-of-an-integer/Nu/factors-of-an-integer-2.nu b/Task/Factors-of-an-integer/Nu/factors-of-an-integer-2.nu new file mode 100644 index 0000000000..b7031ce2fd --- /dev/null +++ b/Task/Factors-of-an-integer/Nu/factors-of-an-integer-2.nu @@ -0,0 +1,5 @@ +let n = 120_643_200 + 1..($n | math sqrt | math floor) | + where { |$f| $n mod $f == 0 } | + each { |$f| [$f (($n / $f) | into int) ] } | + sort | grid -w 80 diff --git a/Task/Factors-of-an-integer/OPL/factors-of-an-integer.opl b/Task/Factors-of-an-integer/OPL/factors-of-an-integer.opl new file mode 100644 index 0000000000..47fd3d4a3b --- /dev/null +++ b/Task/Factors-of-an-integer/OPL/factors-of-an-integer.opl @@ -0,0 +1,16 @@ +PROC main: + LOCAL n%,na%,i% + WHILE n%=0 + PRINT "Please enter an integer." + INPUT n% + ENDWH + na%=ABS(n%) + DO + i%=i%+1 + IF na%=INT(na%/i%)*i% + PRINT i%, + ENDIF + UNTIL i%=INT(na%/2) + PRINT na% + GET +ENDP diff --git a/Task/Factors-of-an-integer/Pascal-P/factors-of-an-integer.pas b/Task/Factors-of-an-integer/Pascal-P/factors-of-an-integer.pas new file mode 100644 index 0000000000..5b812bac3e --- /dev/null +++ b/Task/Factors-of-an-integer/Pascal-P/factors-of-an-integer.pas @@ -0,0 +1,25 @@ +program factint(output); + + (* Factors of an integer *) + + procedure writefactors(n: integer); + var + i: integer; + begin + write(n, ' => '); + n := abs(n); + for i := 1 to n div 2 do + if n mod i = 0 then + write(i: 1, ' '); + writeln(n: 1); + end; + +begin + writefactors(11); + writefactors(21); + writefactors(32); + writefactors(45); + writefactors(67); + writefactors(96); + (* readln; *) +end. diff --git a/Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-1.ps1 b/Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-1.ps1 new file mode 100644 index 0000000000..68cc80a7a7 --- /dev/null +++ b/Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-1.ps1 @@ -0,0 +1,3 @@ +function Get-Factor ($a) { + 1..$a | Where-Object { $a % $_ -eq 0 } +} diff --git a/Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-2.ps1 b/Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-2.ps1 new file mode 100644 index 0000000000..52f9c4af1b --- /dev/null +++ b/Task/Factors-of-an-integer/PowerShell/factors-of-an-integer-2.ps1 @@ -0,0 +1,6 @@ +function Get-Factor ($a) { + 1..[Math]::Sqrt($a) ` + | Where-Object { $a % $_ -eq 0 } ` + | ForEach-Object { $_; $a / $_ } ` + | Sort-Object -Unique +} diff --git a/Task/Factors-of-an-integer/RISC-V-Assembly/factors-of-an-integer.asm b/Task/Factors-of-an-integer/RISC-V-Assembly/factors-of-an-integer.asm new file mode 100644 index 0000000000..417d442a78 --- /dev/null +++ b/Task/Factors-of-an-integer/RISC-V-Assembly/factors-of-an-integer.asm @@ -0,0 +1,113 @@ +# riscv assembly raspberry pico2 rp2350 +# program factor.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +.equ BUFFERSIZE, 80 +/*******************************************/ +/* INITIALIZED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szMessNumber: .asciz "Number :\r\n" +szMessFactor: .asciz "Factors:\r\n" + +.align 2 + +/*******************************************/ +/* UNINITIALIZED DATAS */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +/***********************************...-..--***/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main # INFO: main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + li a0,100 + call factors + + li a0,97 + call factors + + li a0,32767 + call factors + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/***************************************************/ +/* number display */ +/***************************************************/ +# a0 contains number +# a0 return length +displayresult: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + la a1,sConvArea + call conversion10S # call decimal conversion + la a0,sConvArea # display result message + call writeString + la a0,szCariageReturn + call writeString + lw ra, 0(sp) + addi sp, sp, 4 + ret +/******************************************************************/ +/* calcul factors of number */ +/******************************************************************/ +/* a0 contains the number */ +factors: + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + mv s0,a0 + la a0,szMessNumber # display title + call writeString + mv a0,s0 + call displayresult + la a0,szMessFactor + call writeString + + mv a0,s0 # number + li s1,1 # counter loop +1: # loop + rem t0,s0,s1 + bnez t0,2f # remainder = zero ? + mv a0,s1 # yes -> display factor + call displayresult +2: + addi s1,s1,1 # add 1 to loop counter + ble s1,s0,1b # <= number ? + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Factors-of-an-integer/Rebol/factors-of-an-integer.rebol b/Task/Factors-of-an-integer/Rebol/factors-of-an-integer.rebol new file mode 100644 index 0000000000..4d685b443d --- /dev/null +++ b/Task/Factors-of-an-integer/Rebol/factors-of-an-integer.rebol @@ -0,0 +1,13 @@ +factors: function [n [integer!]] [ + n: absolute n ;; work with a non-negative value for factorization + collect [ ;; build and return a block of factors + repeat i (sq: square-root n) - 1 [ ;; test divisors from 1 up to floor(sqrt(n)) - 1 + if n % i = 0 [ ;; if i divides n + keep i ;; keep the small factor i + keep n / i ;; and its complementary factor n/i + ] + ] + ;; If n is a perfect square, include the square root once (to avoid duplication) + if sq = sq: to integer! sq [keep sq] + ] +] diff --git a/Task/Fairshare-between-two-and-more/Comal/fairshare-between-two-and-more.comal b/Task/Fairshare-between-two-and-more/Comal/fairshare-between-two-and-more.comal new file mode 100644 index 0000000000..42ab541d88 --- /dev/null +++ b/Task/Fairshare-between-two-and-more/Comal/fairshare-between-two-and-more.comal @@ -0,0 +1,16 @@ +0010 FUNC fair'share#(n#,base#) CLOSED +0020 sum#:=0 +0030 WHILE n#>0 DO sum#:+n# MOD base#;n#:=n# DIV base# +0040 RETURN sum# MOD base# +0050 ENDFUNC fair'share# +0060 // +0070 REPEAT +0080 READ base# +0090 ZONE 4 +0100 PRINT STR$(base#)+":", +0110 ZONE 3 +0120 FOR n#:=0 TO 24 DO PRINT fair'share#(n#,base#), +0130 PRINT +0140 UNTIL EOD +0150 END +0160 DATA 2,3,5,11 diff --git a/Task/Fairshare-between-two-and-more/PL-I/fairshare-between-two-and-more.pli b/Task/Fairshare-between-two-and-more/PL-I/fairshare-between-two-and-more.pli new file mode 100644 index 0000000000..01b1c2e9f6 --- /dev/null +++ b/Task/Fairshare-between-two-and-more/PL-I/fairshare-between-two-and-more.pli @@ -0,0 +1,19 @@ +fairshareBetweenTwoAndMore: procedure options(main); + fairshare: procedure(nn, base) returns(fixed); + declare (n, nn, base, s) fixed; + s = 0; + do n=nn repeat(n/base) while(n>0); + s = s + mod(n, base); + end; + return(mod(s, base)); + end fairshare; + + declare bases(4) fixed static initial(2, 3, 5, 11); + declare (base, n) fixed; + do base=1 to 4; + put skip edit(bases(base), ': ') (F(2),A(2)); + do n=0 to 24; + put edit(fairshare(n, bases(base))) (F(3)); + end; + end; +end fairshareBetweenTwoAndMore; diff --git a/Task/Fairshare-between-two-and-more/Pluto/fairshare-between-two-and-more.pluto b/Task/Fairshare-between-two-and-more/Pluto/fairshare-between-two-and-more.pluto new file mode 100644 index 0000000000..ce7394769d --- /dev/null +++ b/Task/Fairshare-between-two-and-more/Pluto/fairshare-between-two-and-more.pluto @@ -0,0 +1,59 @@ +local fmt = require "fmt" + +local function fairshare(n, base) + local res = table.create(n) + for i = 1, n do + local j = i - 1 + local sum = 0 + while j > 0 do + sum += j % base + j //= base + end + res[i] = sum % base + end + return res +end + +local function turns(n, fss) + local m = {} + for fss as fs do + local k = m[fs] + if !k then + m[fs] = 1 + else + m[fs] = k + 1 + end + end + local m2 = {} + for m:keys() as k do + local v = m[k] + local k2 = m2[v] + if !k2 then + m2[v] = 1 + else + m2[v] = k2 + 1 + end + end + local res = {} + local sum = 0 + for m2:keys() as k do + local v = m2[k] + sum += v + res:insert(k) + end + if sum != n then return $"only {sum} have a turn" end + res:sort() + local res2 = table.create(#res) + for i = 1, #res do res2[i] = tostring(res[i]) end + return res2:concat(" or ") +end + +for {2, 3, 5, 11} as base do + fmt.write("%2d : ", base) + fmt.tprint("%2d", fairshare(25, base), 25) +end +print("\nHow many times does each get a turn in 50,000 iterations?") +for {191, 1377, 49999, 50000, 50001} as base do + local t = turns(base, fairshare(50000, base)) + fmt.print(" With %5d people: %s", base, t) +end diff --git a/Task/Farey-sequence/COBOL/farey-sequence.cob b/Task/Farey-sequence/COBOL/farey-sequence.cob new file mode 100644 index 0000000000..707ce00231 --- /dev/null +++ b/Task/Farey-sequence/COBOL/farey-sequence.cob @@ -0,0 +1,213 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. FAREY-SEQUENCE. + + ENVIRONMENT DIVISION. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + *> Fraction storage + 01 WS-MAX-FRACS PIC 9(6) VALUE 600000. + 01 WS-FRAC-TABLE. + 05 WS-FRAC OCCURS 600000 TIMES. + 10 WS-NUM PIC 9(6). + 10 WS-DEN PIC 9(6). + 10 WS-VAL PIC S9(6)V9(9) COMP-3. + + *> Dedup value table (parallel arrays for map simulation) + 01 WS-SEEN-TABLE. + 05 WS-SEEN OCCURS 600000 TIMES. + 10 WS-SEEN-VAL PIC S9(6)V9(9) COMP-3. + 10 WS-SEEN-USED PIC X VALUE 'N'. + + 01 WS-FRAC-COUNT PIC 9(6) VALUE 0. + 01 WS-SEEN-COUNT PIC 9(6) VALUE 0. + + *> Loop counters (renamed to avoid ambiguity with table fields) + 01 WS-I PIC 9(4). + 01 WS-LOOP-DEN PIC 9(4). + 01 WS-LOOP-NUM PIC 9(4). + 01 WS-K PIC 9(6). + 01 WS-J PIC 9(6). + + *> Computed value + 01 WS-CURR-VAL PIC S9(6)V9(9) COMP-3. + 01 WS-FOUND PIC X VALUE 'N'. + + *> Sorting temporaries + 01 WS-TEMP-NUM PIC 9(6). + 01 WS-TEMP-DEN PIC 9(6). + 01 WS-TEMP-VAL PIC S9(6)V9(9) COMP-3. + + *> Output + 01 WS-OUT-LINE PIC X(2000). + 01 WS-FRAC-STR PIC X(20). + + *> Numeric editing + 01 WS-EDIT-NUM PIC Z(5)9. + 01 WS-EDIT-I PIC Z(3)9. + 01 WS-EDIT-CNT PIC Z(5)9. + + *> Pointer for STRING + 01 WS-POS PIC 9(4). + + PROCEDURE DIVISION. + + MAIN-PARA. + *> Print F1 through F11 + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > 11 + PERFORM GEN-FAREY + PERFORM PRINT-FAREY-LIST + END-PERFORM + + *> Print counts for F100 to F1000 by 100 + PERFORM VARYING WS-I FROM 100 BY 100 + UNTIL WS-I > 1000 + PERFORM GEN-FAREY + PERFORM PRINT-FAREY-COUNT + END-PERFORM + + STOP RUN. + + *>- ----------------------------------------------------------- + *> GEN-FAREY: builds sorted unique fraction list for order WS-I + *>- ----------------------------------------------------------- + GEN-FAREY. + MOVE 0 TO WS-FRAC-COUNT + MOVE 0 TO WS-SEEN-COUNT + + *> Clear seen flags + PERFORM VARYING WS-K FROM 1 BY 1 + UNTIL WS-K > 600000 + MOVE 'N' TO WS-SEEN-USED(WS-K) + END-PERFORM + + *> Generate fractions + PERFORM VARYING WS-LOOP-DEN FROM 1 BY 1 + UNTIL WS-LOOP-DEN > WS-I + PERFORM VARYING WS-LOOP-NUM FROM 0 BY 1 + UNTIL WS-LOOP-NUM > WS-LOOP-DEN + + COMPUTE WS-CURR-VAL = + WS-LOOP-NUM / WS-LOOP-DEN + + PERFORM CHECK-SEEN + IF WS-FOUND = 'N' + ADD 1 TO WS-FRAC-COUNT + MOVE WS-LOOP-NUM TO WS-NUM(WS-FRAC-COUNT) + MOVE WS-LOOP-DEN TO WS-DEN(WS-FRAC-COUNT) + MOVE WS-CURR-VAL TO WS-VAL(WS-FRAC-COUNT) + ADD 1 TO WS-SEEN-COUNT + MOVE WS-CURR-VAL + TO WS-SEEN-VAL(WS-SEEN-COUNT) + MOVE 'Y' + TO WS-SEEN-USED(WS-SEEN-COUNT) + END-IF + + END-PERFORM + END-PERFORM + + *> Bubble sort by value + PERFORM VARYING WS-K FROM 1 BY 1 + UNTIL WS-K >= WS-FRAC-COUNT + PERFORM VARYING WS-J FROM 1 BY 1 + UNTIL WS-J >= WS-FRAC-COUNT - WS-K + 1 + IF WS-VAL(WS-J) > WS-VAL(WS-J + 1) + MOVE WS-NUM(WS-J) TO WS-TEMP-NUM + MOVE WS-DEN(WS-J) TO WS-TEMP-DEN + MOVE WS-VAL(WS-J) TO WS-TEMP-VAL + MOVE WS-NUM(WS-J + 1) TO WS-NUM(WS-J) + MOVE WS-DEN(WS-J + 1) TO WS-DEN(WS-J) + MOVE WS-VAL(WS-J + 1) TO WS-VAL(WS-J) + MOVE WS-TEMP-NUM TO WS-NUM(WS-J + 1) + MOVE WS-TEMP-DEN TO WS-DEN(WS-J + 1) + MOVE WS-TEMP-VAL TO WS-VAL(WS-J + 1) + END-IF + END-PERFORM + END-PERFORM. + + *>- ----------------------------------------------------------- + *> CHECK-SEEN: sets WS-FOUND = 'Y' if WS-CURR-VAL already seen + *>- ----------------------------------------------------------- + CHECK-SEEN. + MOVE 'N' TO WS-FOUND + PERFORM VARYING WS-K FROM 1 BY 1 + UNTIL WS-K > WS-SEEN-COUNT + IF WS-SEEN-USED(WS-K) = 'Y' AND + WS-SEEN-VAL(WS-K) = WS-CURR-VAL + MOVE 'Y' TO WS-FOUND + MOVE WS-SEEN-COUNT TO WS-K + END-IF + END-PERFORM. + + *>- ----------------------------------------------------------- + *> PRINT-FAREY-LIST: outputs "Fi: [a/b, c/d, ...]" + *>- ----------------------------------------------------------- + PRINT-FAREY-LIST. + MOVE SPACES TO WS-OUT-LINE + MOVE 1 TO WS-POS + + MOVE WS-I TO WS-EDIT-I + STRING 'F' DELIMITED SIZE + FUNCTION TRIM(WS-EDIT-I LEADING) DELIMITED SIZE + ': [' DELIMITED SIZE + INTO WS-OUT-LINE + WITH POINTER WS-POS + END-STRING + + PERFORM VARYING WS-K FROM 1 BY 1 + UNTIL WS-K > WS-FRAC-COUNT + + MOVE SPACES TO WS-FRAC-STR + MOVE WS-NUM(WS-K) TO WS-EDIT-NUM + STRING + FUNCTION TRIM(WS-EDIT-NUM LEADING) DELIMITED SIZE + '/' DELIMITED SIZE + INTO WS-FRAC-STR + END-STRING + MOVE WS-DEN(WS-K) TO WS-EDIT-NUM + STRING + FUNCTION TRIM(WS-FRAC-STR TRAILING) DELIMITED SIZE + FUNCTION TRIM(WS-EDIT-NUM LEADING) DELIMITED SIZE + INTO WS-FRAC-STR + END-STRING + + IF WS-K < WS-FRAC-COUNT + STRING + FUNCTION TRIM(WS-FRAC-STR TRAILING) DELIMITED + SIZE + ', ' DELIMITED + SIZE + INTO WS-OUT-LINE + WITH POINTER WS-POS + END-STRING + ELSE + STRING + FUNCTION TRIM(WS-FRAC-STR TRAILING) DELIMITED + SIZE + INTO WS-OUT-LINE + WITH POINTER WS-POS + END-STRING + END-IF + + END-PERFORM + + STRING ']' DELIMITED SIZE + INTO WS-OUT-LINE + WITH POINTER WS-POS + END-STRING + + DISPLAY FUNCTION TRIM(WS-OUT-LINE TRAILING). + + *>- ----------------------------------------------------------- + *> PRINT-FAREY-COUNT: outputs "Fi: N members" + *>- ----------------------------------------------------------- + PRINT-FAREY-COUNT. + MOVE WS-I TO WS-EDIT-I + MOVE WS-FRAC-COUNT TO WS-EDIT-CNT + DISPLAY 'F' + FUNCTION TRIM(WS-EDIT-I LEADING) + ': ' + FUNCTION TRIM(WS-EDIT-CNT LEADING) + ' members'. diff --git a/Task/Farey-sequence/Fortran/farey-sequence.f b/Task/Farey-sequence/Fortran/farey-sequence.f new file mode 100644 index 0000000000..b647c2567b --- /dev/null +++ b/Task/Farey-sequence/Fortran/farey-sequence.f @@ -0,0 +1,100 @@ +! Farey Sequence +! +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +! U.B., March 2026 +! +program Farey + +implicit none + +! These variables are used in "contained" subtoutines and functions +integer :: n,a,b,c,d ! Order, and current 2 terms of a Farey Sequence + +! Local variables here in Main program: +integer :: ii, count ! Loop index, counter for terms in sequence + +! compute and show the Farey sequence for orders 1 through 11 (inclusive). + +do ii=1, 11 + call startNew (ii) + write (*, '(I2, ": ")', advance='no') n ! Advance 'no' to print all in 1 line + count = 0 + do + count = count + 1 ! Count to limit line length + write (*,'(i0, "/",i0)', advance='no') a, b ! Advance 'no' to print them in 1 line + if (.not. expectNext()) Exit ! Finish when sequence complete + write (*, '(", ")', advance='no') ! more is coming - print separator + if (count .eq. 10) then ! By default, OpenVMS does not like + count = 0 ! long output lines and produces a run-time + write (*,'(/,4x)', advance='no') ! error when line length exceeds 132 + endif + call next() ! Calculate next term + enddo + write (*, *) ! Terminate line +enddo + +! compute and display the number of fractions in the Farey sequence for order 100 through 1,000 inclusive) by hundreds. +write (*,*) ! empty line +do ii=100, 1000, 100 + count = 0 + call startNew (ii) + write (*, '(I4, ": ")', advance='no') n + do + count = count + 1 ! Dont print the terms, just count them + if (.not. expectNext()) Exit + call next() + enddo + write (*, '(I0)') count + end do +contains + + +! ========================================= +! Start a new Farey Sequence or order newN +! ========================================= +subroutine startNew(newN) +integer, intent(in) :: newN + +n = newN +a = 0 ! 1st term is a/b=0/1 +b = 1 +c = 1 ! 2nd term is c/d=(1/n) +d = n + +end subroutine startNew + +! ================================================= +! Calculate next term in the current Farey Sequence +! ================================================= +subroutine next() +! +! The algorithm to calculate next term a/b of the sequence is +! described in Wikipedia, https://en.wikipedia.org/wiki/Farey_sequence + +integer :: fact, nextC, nextD + +fact = (n+b) / d +nextC = fact*c - a +nextD = fact*d - b + +a = c +b = d +c = nextC +d = nextD + +end subroutine next + +! ========================================================== +! Say Yes if more terms in current sequence can be expected +! ========================================================== +function expectNext() result (YN) + +! The end is reached when the last term (1/1) is encountered. +logical :: YN + +YN = a .ne. 1 .or. b .ne. 1 +end function expectNext + +end program Farey diff --git a/Task/Farey-sequence/JavaScript/farey-sequence.js b/Task/Farey-sequence/JavaScript/farey-sequence.js new file mode 100644 index 0000000000..5c7f77a667 --- /dev/null +++ b/Task/Farey-sequence/JavaScript/farey-sequence.js @@ -0,0 +1,44 @@ +class Frac { + constructor(num, den) { + this.num = num; + this.den = den; + } + + toString() { + return `${this.num}/${this.den}`; + } + + valueOf() { + return this.num / this.den; + } +} + +function genFarey(i) { + const farey = new Set(); + const fracMap = new Map(); + + for (let den = 1; den <= i; den++) { + for (let num = 0; num <= den; num++) { + const value = num / den; + // Only add if this exact value hasn't been added yet + if (!fracMap.has(value)) { + const frac = new Frac(num, den); + fracMap.set(value, frac); + farey.add(frac); + } + } + } + + // Sort fractions by their value + return Array.from(farey).sort((a, b) => a.valueOf() - b.valueOf()); +} + +// Main execution +for (let i = 1; i <= 11; i++) { + const farey = genFarey(i); + console.log(`F${i}: [${farey.join(', ')}]`); +} + +for (let i = 100; i <= 1000; i += 100) { + console.log(`F${i}: ${genFarey(i).length} members`); +} diff --git a/Task/Farey-sequence/Langur/farey-sequence.langur b/Task/Farey-sequence/Langur/farey-sequence.langur index 775e32d212..4128c68ca9 100644 --- a/Task/Farey-sequence/Langur/farey-sequence.langur +++ b/Task/Farey-sequence/Langur/farey-sequence.langur @@ -10,7 +10,7 @@ val farey = fn(n number) { val testFarey = fn*() { writeln "Farey sequence for orders 1 through 11" for i of 11 { - writeln "{{i:2}}: ", join(map(farey(i), by=fn f: "{{f[1]}}/{{f[2]}}"), delim=" ") + writeln "{{i:2}}: ", join(map(farey(i), by=fn(f) { "{{f[1]}}/{{f[2]}}" }), delim=" ") } } diff --git a/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-1.adb b/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-1.adb new file mode 100644 index 0000000000..24c6ce5d03 --- /dev/null +++ b/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-1.adb @@ -0,0 +1,7 @@ +with Ada.Numerics.Generic_Complex_Arrays; + +generic + with package Complex_Arrays is + new Ada.Numerics.Generic_Complex_Arrays (<>); + use Complex_Arrays; +function Generic_FFT (X : Complex_Vector) return Complex_Vector; diff --git a/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-2.adb b/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-2.adb new file mode 100644 index 0000000000..578137caca --- /dev/null +++ b/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-2.adb @@ -0,0 +1,39 @@ +with Ada.Numerics; +with Ada.Numerics.Generic_Complex_Elementary_Functions; + +function Generic_FFT (X : Complex_Vector) return Complex_Vector is + + package Complex_Elementary_Functions is + new Ada.Numerics.Generic_Complex_Elementary_Functions + (Complex_Arrays.Complex_Types); + + use Ada.Numerics; + use Complex_Elementary_Functions; + use Complex_Arrays.Complex_Types; + + function FFT (X : Complex_Vector; N, S : Positive) + return Complex_Vector is + begin + if N = 1 then + return (1..1 => X (X'First)); + else + declare + F : constant Complex := exp (Pi * j / Real_Arrays.Real (N/2)); + Even : Complex_Vector := FFT (X, N/2, 2*S); + Odd : Complex_Vector := FFT (X (X'First + S..X'Last), N/2, 2*S); + begin + for K in 0..N/2 - 1 loop + declare + T : constant Complex := Odd (Odd'First + K) / F ** K; + begin + Odd (Odd'First + K) := Even (Even'First + K) - T; + Even (Even'First + K) := Even (Even'First + K) + T; + end; + end loop; + return Even & Odd; + end; + end if; + end FFT; +begin + return FFT (X, X'Length, 1); +end Generic_FFT; diff --git a/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-3.adb b/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-3.adb new file mode 100644 index 0000000000..97309d3333 --- /dev/null +++ b/Task/Fast-Fourier-transform/Ada/fast-fourier-transform-3.adb @@ -0,0 +1,20 @@ +with Ada.Numerics.Complex_Arrays; use Ada.Numerics.Complex_Arrays; +with Ada.Complex_Text_IO; use Ada.Complex_Text_IO; +with Ada.Text_IO; use Ada.Text_IO; + +with Ada.Numerics.Complex_Elementary_Functions; +with Generic_FFT; + +procedure Example is + function FFT is new Generic_FFT (Ada.Numerics.Complex_Arrays); + X : Complex_Vector := (1..4 => (1.0, 0.0), 5..8 => (0.0, 0.0)); + Y : Complex_Vector := FFT (X); +begin + Put_Line (" X FFT X "); + for I in Y'Range loop + Put (X (I - Y'First + X'First), Aft => 3, Exp => 0); + Put (" "); + Put (Y (I), Aft => 3, Exp => 0); + New_Line; + end loop; +end; diff --git a/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 b/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 index aeb97fb834..1821a2fd86 100644 --- a/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 +++ b/Task/Fast-Fourier-transform/M2000-Interpreter/fast-fourier-transform-2.m2000 @@ -17,3 +17,49 @@ module FFT { End Sub } FFT +' FFT run on newer M2000 Interpreter's versions also. +' Version using Complex type (from Version 13 of M2000 Interpreter) +' locale 1033 display dot for decimal point. +module FFT2 { + ' print $("0.000", 16) ' #1 (use #1, #2, #3 for 4 decimals for printing numbers ) + locale 1033 + open "output.txt" for wide output as #F + complex buf[7], out[7] + buf[0]|r = 1: buf[1]|r = 1: buf[2]|r = 1: buf[3] = (1, 0i) + showArr(buf, "Input") + FFT(out, buf, 0, 1, 8) + ShowArr(out, "Output") + ' print $("") ' #2 + close #F + print #-2, eval$(buffer(dir$+"output.txt")) + Sub ShowArr(m, mes as string) + local n, mx=len(m) + print #F, mes;": (real imag abs)" + while n 1) { + nn = Math.floor(nn / g); + dd = Math.floor(dd / g); + } + this.num = nn; + this.denom = dd; + } + + plus(rhs) { + return new Frac(this.num * rhs.denom + this.denom * rhs.num, rhs.denom * this.denom); + } + + unaryMinus() { + return new Frac(-this.num, this.denom); + } + + minus(rhs) { + return this.plus(rhs.unaryMinus()); + } + + times(rhs) { + return new Frac(this.num * rhs.num, this.denom * rhs.denom); + } + + compareTo(o) { + const diff = this.toDouble() - o.toDouble(); + return Math.sign(diff); + } + + equals(obj) { + return obj !== null && obj instanceof Frac && this.compareTo(obj) === 0; + } + + toString() { + if (this.denom === 1) { + return this.num.toString(); + } + return `${this.num}/${this.denom}`; + } + + toDouble() { + return this.num / this.denom; + } +} + +Frac.ZERO = new Frac(0, 1); +Frac.ONE = new Frac(1, 1); + +function bernoulli(n) { + if (n < 0) throw new Error("n may not be negative or zero"); + const a = new Array(n + 1).fill(null).map(() => Frac.ZERO); + for (let m = 0; m <= n; m++) { + a[m] = new Frac(1, m + 1); + for (let j = m; j >= 1; j--) { + a[j - 1] = a[j - 1].minus(a[j]).times(new Frac(j, 1)); + } + } + // returns 'first' Bernoulli number + if (n !== 1) return a[0]; + return a[0].unaryMinus(); +} + +function binomial(n, k) { + if (n < 0 || k < 0 || n < k) throw new Error("Invalid arguments"); + if (n === 0 || k === 0) return 1; + + let num = 1; + for (let i = k + 1; i <= n; i++) { + num *= i; + } + + let den = 1; + for (let i = 2; i <= n - k; i++) { + den *= i; + } + + return Math.floor(num / den); +} + +function faulhaber(p) { + let output = `${p} : `; + const q = new Frac(1, p + 1); + let sign = -1; + + for (let j = 0; j <= p; j++) { + sign *= -1; + const coeff = q.times(new Frac(sign, 1)) + .times(new Frac(binomial(p + 1, j), 1)) + .times(bernoulli(j)); + + if (Frac.ZERO.equals(coeff)) continue; + + if (j === 0) { + if (!Frac.ONE.equals(coeff)) { + if (Frac.ONE.unaryMinus().equals(coeff)) { + output += "-"; + } else { + output += coeff.toString(); + } + } + } else { + if (Frac.ONE.equals(coeff)) { + output += " + "; + } else if (Frac.ONE.unaryMinus().equals(coeff)) { + output += " - "; + } else if (coeff.compareTo(Frac.ZERO) > 0) { + output += ` + ${coeff.toString()}`; + } else { + output += ` - ${coeff.unaryMinus().toString()}`; + } + } + + const pwr = p + 1 - j; + if (pwr > 1) { + output += `n^${pwr}`; + } else { + output += "n"; + } + } + + console.log(output); +} + +// Main execution +for (let i = 0; i <= 9; i++) { + faulhaber(i); +} diff --git a/Task/Feigenbaum-constant-calculation/Ada/feigenbaum-constant-calculation.adb b/Task/Feigenbaum-constant-calculation/Ada/feigenbaum-constant-calculation.adb new file mode 100644 index 0000000000..b3641cf585 --- /dev/null +++ b/Task/Feigenbaum-constant-calculation/Ada/feigenbaum-constant-calculation.adb @@ -0,0 +1,46 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; + +procedure Main is + procedure feigenbaum is + subtype i_range is Integer range 2 .. 13; + subtype j_range is Integer range 1 .. 10; + + -- the number of digits in type Real is reduced to 15 to produce the + -- results reported by C, C++, C# and Ring. Increasing the number of + -- digits in type Real produces the results reported by D. + + type Real is digits 15; + package Real_Io is new Float_IO (Real); + use Real_Io; + + a, x, y, d : Real; + a1 : Real := 1.0; + a2 : Real := 0.0; + d1 : Real := 3.2; + begin + Put_Line (" i d"); + for i in i_range loop + a := a1 + (a1 - a2) / d1; + for j in j_range loop + x := 0.0; + y := 0.0; + for k in 1 .. 2**i loop + y := 1.0 - 2.0 * x * y; + x := a - x * x; + end loop; + a := a - x / y; + end loop; + d := (a1 - a2) / (a - a1); + Put (Item => i, Width => 2); + Put (Item => d, Fore => 5, Aft => 8, Exp => 0); + New_Line; + d1 := d; + a2 := a1; + a1 := a; + end loop; + end feigenbaum; + +begin + feigenbaum; +end Main; diff --git a/Task/Fermat-numbers/Ada/fermat-numbers.adb b/Task/Fermat-numbers/Ada/fermat-numbers.adb new file mode 100644 index 0000000000..2896833f11 --- /dev/null +++ b/Task/Fermat-numbers/Ada/fermat-numbers.adb @@ -0,0 +1,20 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit.Integers; use Strings_Edit.Integers; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Fermat_Numbers is + P : Unbounded_Unsigned; +begin + for N in 0..10 loop + P := Power_Of_Two (2 ** N) + 1; + Put ("F(" & Image (N) & ") = " & Image (P)); + if Is_Prime (P, 10) = Prime then + Put (" is prime"); + end if; + New_Line; + end loop; +end Fermat_Numbers; diff --git a/Task/Fermat-numbers/EasyLang/fermat-numbers.easy b/Task/Fermat-numbers/EasyLang/fermat-numbers.easy new file mode 100644 index 0000000000..6aa7d01174 --- /dev/null +++ b/Task/Fermat-numbers/EasyLang/fermat-numbers.easy @@ -0,0 +1,227 @@ +func[] bn s$ . + i = len s$ - 7 + 1 + while i >= -5 + r[] &= number substr s$ i 7 + i -= 7 + . + return r[] +. +func$ str bn[] . + s$ = bn[$] + for i = len bn[] - 1 downto 1 + h$ = bn[i] + s$ &= substr "0000000" 1 (7 - len h$) & h$ + . + return s$ +. +func[] bnmul a[] b[] . + len r[] len a[] + len b[] + if len a[] > len b[] : swap a[] b[] + for ia = 1 to len a[] + h = 0 + for ib = 1 to len b[] + h += r[ia + ib - 1] + b[ib] * a[ia] + r[ia + ib - 1] = h mod 10000000 + h = h div 10000000 + . + r[ia + ib - 1] += h + . + while r[$] = 0 and len r[] > 1 : len r[] -1 + return r[] +. +func[] bnadd a[] b[] . + if len b[] > len a[] : swap a[] b[] + len r[] len a[] + for i = 1 to len r[] + v = 0 + if i <= len b[] : v = b[i] + h += a[i] + v + r[i] = h mod 10000000 + h = h div 10000000 + . + if h > 0 : r[] &= h + while len r[] > 1 and r[$] = 0 : len r[] -1 + return r[] +. +func[] bnadds a[] h . + len r[] len a[] + for i = 1 to len r[] + h += a[i] + r[i] = h mod 10000000 + h = h div 10000000 + . + if h > 0 : r[] &= h + return r[] +. +func bncmp a[] b[] . + if len a[] > len b[] : return 1 + if len a[] < len b[] : return -1 + for i = len a[] downto 1 + if a[i] > b[i] : return 1 + if a[i] < b[i] : return -1 + . + return 0 +. +func[] bnsub a[] b[] . + len r[] len a[] + for i = 1 to len r[] + v = 0 + if i <= len b[] : v = b[i] + h = a[i] - v - h + if h < 0 + r[i] = h + 10000000 + h = 1 + else + r[i] = h + h = 0 + . + . + while r[$] = 0 and len r[] > 1 : len r[] -1 + return r[] +. +func[][] bndivmod a[] b[] . + if bncmp a[] b[] < 0 : return [ [ 0 ] a[] ] + lb = len b[] + d = 10000000 div (b[lb] + 1) + if d > 1 + for i = 1 to lb + carry += b[i] * d + b[i] = carry mod 10000000 + carry = carry div 10000000 + . + for i = 1 to len a[] + carry += a[i] * d + a[i] = carry mod 10000000 + carry = carry div 10000000 + . + . + a[] &= carry + # + len q[] len a[] - lb + v1 = b[lb] + if lb >= 2 : v2 = b[lb - 1] + for j = len q[] downto 1 + u0 = a[j + lb] + u1 = a[j + lb - 1] + u2 = 0 + if j + lb >= 2 : u2 = a[j + lb - 2] + if u0 = v1 + qhat = 9999999 + rhat = u1 + v1 + else + h = u0 * 10000000 + u1 + qhat = h div v1 + rhat = h mod v1 + . + while rhat < 10000000 and qhat * v2 > 10000000 * rhat + u2 + qhat -= 1 + rhat += v1 + . + k = 0 + for i = 1 to lb + p = qhat * b[i] + k + k = p div 10000000 + t = a[j + i - 1] - (p mod 10000000) + if t < 0 + t += 10000000 + k += 1 + . + a[j + i - 1] = t + . + t = a[j + lb] - k + if t < 0 + qhat -= 1 + k = 0 + for i = 1 to lb + t = a[j + i - 1] + b[i] + k + a[j + i - 1] = t mod 10000000 + k = t div 10000000 + . + a[j + lb] = t + k + else + a[j + lb] = t + . + q[j] = qhat + . + if d > 1 + k = 0 + for i = lb downto 1 + t = k * 10000000 + a[i] + a[i] = t div d + k = t mod d + . + . + len a[] lb + while len q[] > 1 and q[len q[]] = 0 : len q[] len q[] - 1 + while len a[] > 1 and a[len a[]] = 0 : len a[] len a[] - 1 + return [ q[] a[] ] +. +func[] bnmod a[] n[] . + result[][] = bndivmod a[] n[] + return result[2][] +. +func[] facts n . + sqrtn = sqrt n + f = 3 + while f <= sqrtn + if n mod f = 0 + f[] &= f + n = n div f + sqrtn = sqrt n + else + f += 2 + . + . + f[] &= n + return f[] +. +func[] bnsqrt n[] . + len x[] (len n[] + 1) div 2 + x[$] = 1000000 + lastx[] = [ 0 ] + while bncmp x[] lastx[] <> 0 + lastx[] = x[] + res[][] = bndivmod n[] x[] + sum[] = bnadd x[] res[1][] + h = 0 + for i = len sum[] downto 1 + h = h * 10000000 + sum[i] + sum[i] = h div 2 + h = h mod 2 + . + while len sum[] > 1 and sum[$] = 0 : len sum[] -1 + swap x[] sum[] + if bncmp x[] lastx[] >= 0 : return lastx[] + . + return x[] +. +func[] fermat n . + ex[] = [ 2 ] + for i to n : ex[] = bnmul ex[] ex[] + return bnadds ex[] 1 +. +func[][] factors fn[] . + q[] = [ 3 ] + lim[] = bnsqrt fn[] + while bncmp q[] lim[] <= 0 + res[][] = bndivmod fn[] q[] + if res[2][] = [ 0 ] + f[][] &= q[] + swap fn[] res[1][] + lim[] = bnsqrt fn[] + . + q[] = bnadds q[] 2 + . + if len f[][] >= 1 : f[][] &= fn[] + return f[][] +. +for i = 0 to 10 + print "F(" & i & ") = " & str fermat i +. +print "" +for n = 5 to 6 + f[][] = factors fermat n + write "Factors F(" & n & "): " + for f[] in f[][] : write str f[] & " " + print "" +. diff --git a/Task/Fermat-numbers/FutureBasic/fermat-numbers.basic b/Task/Fermat-numbers/FutureBasic/fermat-numbers.basic new file mode 100644 index 0000000000..3617ea145f --- /dev/null +++ b/Task/Fermat-numbers/FutureBasic/fermat-numbers.basic @@ -0,0 +1,640 @@ +// ------------------------------------------------------------ +// Fermat numbers with factorization +// +// Using FutureBasic 7.0.36 +// November 2025, R.W. +// +// This code is larger than I originally imagined but this is +// simply because my original coding idea was to use +// Pollard-Rho to do the factorization until I realize, it +// can be a very long time for factors of F[9] and above using +// PR and it may still returns nothing. So I did a pseudo ECM +// reasonably small but works faster. +// ------------------------------------------------------------ + +include "gmp.incl" + +CFTimeInterval tim + +// Global mpz_t bigints reused for speed +mpz_t fm // work +mpz_t num, den, inv, t1, t2, g + +// Limit is set at 15 since anything greater than 14 most +// likely will exceed the 'under 5 minutes' Rosetta task limit +mpz_t gF(15) // Fermat numbers F0..F15 + +mpz_t gFactors(31) // factor buffer +int gFactorCount + +long gFN // next Fermat index for factoring +int gDidFactorHeader // print header once + +// ----------------------------------------------------------- +// Helper: CFString "F0", "F1", ... +// ----------------------------------------------------------- +local fn FermatLabel( n as long ) as CFStringRef + CFStringRef out + out = @"\nF" + out = concat( out, str( n ) ) +end fn = out + +// ----------------------------------------------------------- +// Helper: Abbreviate big numeric CFString: head...tail +// ----------------------------------------------------------- +local fn AbbrevString( s as CFStringRef, head as int, ¬ + tail as int ) as CFStringRef + + if s == 0 then RETURN @"" + CFStringRef a, b, out + int nLen + nLen = len( s ) + if nLen <= head + tail then RETURN s + a = left( s, head ) + b = right( s, tail ) + out = @"" + out = concat( a, @"...", b ) +end fn = out + +// ----------------------------------------------------------- +// Helper: Get mpz_t result and abbreviate if > 53 digits +// ----------------------------------------------------------- +local fn Abbrev( ts as mpz_t ) as CFStringRef + CFStringRef result + result = fn mpz_cf2( ts ) // FB wrapper mpz_t to CFString + int nLen + nLen = len( result ) + if nLen <= 53 then RETURN result + result = fn AbbrevString( result, 25, 25 ) +end fn = result + +// ----------------------------------------------------------- +// Helper: Is n probably prime? +// ----------------------------------------------------------- +local fn IsProbablePrime( n as mpz_t ) as boolean + int r + r = fn mpz_probab_prime_p( n, 25 ) // 25 reps should be sufficient + // r = 0 (composite), 1 (probable prime), 2 (definite prime) + if r > 0 then RETURN _true +end fn = _false + +// ----------------------------------------------------------- +// Helper: Simple 32-bit primality test for Stage 1 ECM +// ----------------------------------------------------------- +local fn IsSmallPrime32( p as UInt32 ) as boolean + if p < 2 then return _false + if p = 2 then return _true + if (p AND 1) == 0 then return _false + + UInt32 d + d = 3 + while d * d <= p + if (p MOD d) == 0 then return _false + d = d + 2 + wend + +end fn = _true + +// Clear global mpz +void local fn clear_MPZ + mpz_clear( num ) + mpz_clear( den ) + mpz_clear( inv ) + mpz_clear( t1 ) + mpz_clear( t2 ) + mpz_clear( g ) +end fn + +// Init global mpz +void local fn Init_MPZ + mpz_init( num ) + mpz_init( den ) + mpz_init( inv ) + mpz_init( t1 ) + mpz_init( t2 ) + mpz_init( g ) +end fn + +// --------------------------------------------------------------- +// ECM_PointDouble +// Point doubling: P = (x,y) → 2P on y^2 = x^3 + a x + b (MOD n) +// Returns _true if a nontrivial factor found (in 'factor'), +// else _false. +// On success, 'factor' holds GCD > 1, < n, and x,y are undefined +// On normal completion, x,y are updated to 2P. +// --------------------------------------------------------------- + +local fn ECM_PointDouble( n as mpz_t, a as mpz_t, ¬ + x as mpz_t, y as mpz_t, factor as mpz_t ) as boolean + + fn Init_MPZ + + mpz_mul( t1, x, x ) // num = 3 * x^2 + a (MOD n) + mpz_mod( t1, t1, n ) // t1 = x^2 + mpz_mul_ui( num, t1, 3 ) // num = 3*x^2 + mpz_add( num, num, a ) + mpz_mod( num, num, n ) + + mpz_mul_ui( den, y, 2 ) // den = 2*y (MOD n) + mpz_mod( den, den, n ) + + if fn mpz_invert( inv, den, n ) == 0 // try to invert den + // inversion failed -> GCD(den, n) may give a factor? + // do you feel lucky, punk? + mpz_GCD( g, den, n ) + if (fn mpz_cmp_ui( g, 1 ) > 0) && (fn mpz_cmp( g, n ) < 0) + mpz_set( factor, g ) + fn Clear_MPZ + return _true + end if + // GCD == 1 or GCD == n -> useless curve (sigh) + fn Clear_MPZ + return _false + end if + + mpz_mul( t1, num, inv ) // lambda = num * inv (MOD n) + mpz_mod( t1, t1, n ) // t1 = lambda + + // x3 = lambda^2 - 2 * x (MOD n) + mpz_mul( t2, t1, t1 ) // lambda^2 + mpz_mod( t2, t2, n ) + mpz_mul_ui( num, x, 2 ) // 2x + mpz_mod( num, num, n ) + mpz_sub( t2, t2, num ) + mpz_mod( t2, t2, n ) // t2 = x3 + + // y3 = lambda * (x - x3) - y (MOD n) + mpz_sub( num, x, t2 ) // x - x3 + mpz_mod( num, num, n ) + mpz_mul( num, t1, num ) // lambda * (x - x3) + mpz_mod( num, num, n ) + mpz_sub( num, num, y ) // lambda * (x - x3) - y + mpz_mod( num, num, n ) // num = y3 + + mpz_set( x, t2 ) // update P ← (x3, y3) + mpz_set( y, num ) + + fn Clear_MPZ +end fn = _false + +// ----------------------------------------------------------- +// ECM_PointAdd +// Point addition: P1 = (x1,y1) ← P1 + P2, with P2 = (x2,y2) +// Curve: y^2 = x^3 + a x + b (MOD n) +// Returns _true if a factor found (in 'factor'), else _false. +// ----------------------------------------------------------- +local fn ECM_PointAdd( n as mpz_t, a as mpz_t, x1 as mpz_t, ¬ + y1 as mpz_t, x2 as mpz_t, y2 as mpz_t, factor as mpz_t ) as boolean + + fn Init_MPZ + + mpz_sub( t1, n, y2 ) // t1 = -y2 MOD n + mpz_mod( t1, t1, n ) + // If x1 == x2 and y1 == -y2, point is infinity + // For our purposes, treat this as a useless -> just return _false. + if (fn mpz_cmp( x1, x2 ) == 0) && (fn mpz_cmp( y1, t1 )== 0) + fn Clear_MPZ + return _false + end if + + mpz_sub( num, y2, y1 ) // num = y2 - y1 (MOD n) + mpz_mod( num, num, n ) + + mpz_sub( den, x2, x1 ) // den = x2 - x1 (MOD n) + mpz_mod( den, den, n ) + + // try to invert den + if fn mpz_invert( inv, den, n ) == 0 + mpz_GCD( g, den, n ) + if (fn mpz_cmp_ui( g, 1 ) > 0) && (fn mpz_cmp( g, n ) < 0) + mpz_set( factor, g ) + fn Clear_MPZ + return _true + end if + fn Clear_MPZ + return _false + end if + + mpz_mul( t1, num, inv ) // lambda = num * inv (MOD n) + mpz_mod( t1, t1, n ) // t1 = lambda + + // x3 = lambda^2 - x1 - x2 (MOD n) + mpz_mul( t2, t1, t1 ) // lambda^2 + mpz_mod( t2, t2, n ) + mpz_sub( t2, t2, x1 ) + mpz_sub( t2, t2, x2 ) + mpz_mod( t2, t2, n ) // t2 = x3 + + // y3 = lambda * (x1 - x3) - y1 (MOD n) + mpz_sub( num, x1, t2 ) // x1 - x3 + mpz_mod( num, num, n ) + mpz_mul( num, t1, num ) + mpz_mod( num, num, n ) + mpz_sub( num, num, y1 ) + mpz_mod( num, num, n ) // num = y3 + + mpz_set( x1, t2 ) + mpz_set( y1, num ) + + fn Clear_MPZ + +end fn = _false + +// ------------------------------------------------------------ +// ECM_ScalarMul +// Scalar multiply P = (x,y) by k: P ← k * P +// Uses binary double-and-add. Returns _true if a factor found. +// ------------------------------------------------------------ + +local fn ECM_ScalarMul( n as mpz_t, a as mpz_t, x as mpz_t, ¬ + y as mpz_t, k as UInt64, factor as mpz_t ) as boolean + + if k <= 1 then return _false + + mpz_t rx, ry, qx, qy + mpz_init( rx ) + mpz_init( ry ) + mpz_init( qx ) + mpz_init( qy ) + + int hasR + hasR = _false // R (result) is "not set" yet + + mpz_set( qx, x ) // Q = P (base) + mpz_set( qy, y ) + + // find highest bit of k + int sbit + sbit = 63 + while (sbit > 0) && ((k AND (1ULL << sbit)) = 0) + sbit -- // decrement bit + wend + + // process bits from MSB down to 0 + while sbit >= 0 + if hasR + // R = 2R + if fn ECM_PointDouble( n, a, rx, ry, factor ) + // factor found + mpz_clear( rx ) + mpz_clear( ry ) + mpz_clear( qx ) + mpz_clear( qy ) + return _true + end if + end if + + if (k AND (1ULL << sbit)) != 0 + if hasR = _false + // first 1 bit: R = Q + mpz_set( rx, qx ) + mpz_set( ry, qy ) + hasR = _true + else + // R = R + Q + if fn ECM_PointAdd( n, a, rx, ry, qx, qy, factor ) + mpz_clear( rx ) + mpz_clear( ry ) + mpz_clear( qx ) + mpz_clear( qy ) + return _true + end if + end if + end if + + sbit -- // decrement bit + wend + + if hasR + mpz_set( x, rx ) + mpz_set( y, ry ) + end if + + mpz_clear( rx ) + mpz_clear( ry ) + mpz_clear( qx ) + mpz_clear( qy ) +end fn = _false + + +// ---------------------------------------------------------------- +// ECM_Stage1Curve +// Stage-1 ECM on one curve determined by 'sigma' +// Curve: y^2 = x^3 + a x + b (MOD n) with (x,y) chosen from sigma. +// B1: first-stage bound, e.g. 10000. +// Returns _true and sets 'factor' if a factor was +// found, else _false. +// ---------------------------------------------------------------- + +local fn ECM_Stage1Curve( n as mpz_t, factor as mpz_t, ¬ + B1 as UInt32, sigma as UInt32 ) as boolean + + mpz_t a, b, x, y, tmp + mpz_init( a ) + mpz_init( b ) + mpz_init( x ) + mpz_init( y ) + mpz_init( tmp ) + + mpz_set_ui( x, sigma ) // x = sigma (MOD n) + mpz_mod( x, x, n ) + + mpz_set_ui( y, sigma + 1 ) // y = sigma + 1 (MOD n) + mpz_mod( y, y, n ) + + mpz_set_ui( a, sigma + 2 ) // a = sigma + 2 (MOD n) + mpz_mod( a, a, n ) + + // b = y^2 - x^3 - a*x (MOD n) + mpz_mul( b, y, y ) // y^2 + mpz_mod( b, b, n ) + + mpz_mul( tmp, x, x ) // x^2 + mpz_mod( tmp, tmp, n ) + mpz_mul( tmp, tmp, x ) // x^3 + mpz_mod( tmp, tmp, n ) + mpz_sub( b, b, tmp ) // y^2 - x^3 + + mpz_mul( tmp, a, x ) // a * x + mpz_mod( tmp, tmp, n ) + mpz_sub( b, b, tmp ) // y^2 - x^3 - a*x + mpz_mod( b, b, n ) + + // Multiply P by prime powers p^e with p <= B1 + UInt32 p, pe + p = 2 + + while p <= B1 + if fn IsSmallPrime32( p ) + // pe = p^e <= B1 + pe = p + while (pe * p) <= B1 + pe = pe * p + wend + + if fn ECM_ScalarMul( n, a, x, y, pe, factor ) + // factor found + mpz_clear( a ) + mpz_clear( b ) + mpz_clear( x ) + mpz_clear( y ) + mpz_clear( tmp ) + return _true + end if + end if + + if p == 2 then p = 3 else p = p + 2 + wend + + mpz_clear( a ) + mpz_clear( b ) + mpz_clear( x ) + mpz_clear( y ) + mpz_clear( tmp ) +end fn = _false + +// ----------------------------------------------------------- +// ECM_FindFactor +// Try several Stage-1 ECM curves with increasing sigma. +// Returns _true and sets 'factor' if a factor is found. +// ----------------------------------------------------------- + +local fn ECM_FindFactor( n as mpz_t, factor as mpz_t ) as boolean + UInt32 B1, sigma + int curves + int i + B1 = 10000 // bound (bigger = slower) + curves = 20 // number of different curves to try + sigma = 2 + i = 0 + while i < curves + if fn ECM_Stage1Curve( n, factor, B1, sigma ) + return _true + end if + sigma ++ + i ++ + wend +end fn = _false + +// Safely divide mpz_t + +local fn SafeMpzDiv( z as mpz_t, x as mpz_t, y as mpz_t ) as boolean + if ( fn mpz_sgn( y ) == 0 ) // div by zero? + mpz_set_ui( z, 0) + return _false + end if + // Call GMP division (truncate toward zero) + mpz_tdiv_q( z, x, y ) +end fn = _true + +// ----------------------------------------------------------- +// Recursive factorization using trial division + ECM Stage 1 +// Results go into global gFactors() / gFactorCount +// ----------------------------------------------------------- +void local fn FactorRec( n as mpz_t ) + // if n == 1 → nothing + if fn mpz_cmp_ui( n, 1 ) = 0 then RETURN + // if prime, store it + if fn IsProbablePrime( n ) + mpz_set( gFactors(gFactorCount), n ) + gFactorCount = gFactorCount + 1 + RETURN + end if + + mpz_t d, q + mpz_init( d ) + mpz_init( q ) + + Boolean got = _False + + got = fn ECM_FindFactor( n, d ) + + if got == _false + // ECM did not find a nontrivial factor; treat n as a "final" factor + mpz_set( gFactors(gFactorCount), n ) + gFactorCount = gFactorCount + 1 + mpz_clear( d ) + mpz_clear( q ) + RETURN + end if + + if fn SafeMpzDiv( q, n, d) // q = n / d + // recurse on d and q + fn FactorRec( d ) + fn FactorRec( q ) + end if + + mpz_clear( d ) + mpz_clear( q ) +end fn + + +// ----------------------------------------------------------- +// Init Fermat numbers F0..F9 +// F_n = 2^(2^n) + 1 +// ----------------------------------------------------------- +local fn InitFermat + int i, expPow + // init working bigint + mpz_init( fm ) + // init Fermat array + i = 0 + while i <= 15 + mpz_init( gF(i) ) + i = i + 1 + wend + // init factor buffer mpz_t + i = 0 + while i <= 30 + mpz_init( gFactors(i) ) + i = i + 1 + wend + // compute F0..F15 once + i = 0 + while i <= 15 + expPow = 1 + // expPow = 2^i + int k + k = 0 + while k < i + expPow = expPow * 2 + k = k + 1 + wend + // fm = 2^(2^i) + 1 + mpz_ui_pow_ui( fm, 2, expPow ) + mpz_add_ui( fm, fm, 1 ) + mpz_set( gF(i), fm ) + i ++ + wend + gFN = 0 + gDidFactorHeader = 0 +end fn + +// ----------------------------------------------------------- +// Print first 10 Fermat numbers +// ----------------------------------------------------------- +local fn Main + CFStringRef lineStr, fStr + int i + print @"\nThe first 10 Fermat numbers are:" + tim = fn CACurrentMediaTime + + i = 0 + while i <= 9 + fStr = fn Abbrev( gF(i) ) + lineStr = @"" + lineStr = concat( lineStr, fn FermatLabel( i ) ) + lineStr = concat( lineStr, @" = " ) + lineStr = concat( lineStr, fStr ) + print lineStr; + i ++ + wend + + printf @"\nElapsed time: %.3f ms", (fn CACurrentMediaTime - tim) * 1000 + print @"\nClick [Next] to display factors of Fermat numbers.\n" +end fn + +// ----------------------------------------------------------- +// Show next Fermat factors (one F_n per click) +// Calculation time displayed if greater than 1 sec +// ----------------------------------------------------------- +void local fn Factor_More + long td + CFStringRef lineStr, factStr + + if gDidFactorHeader == 0 + print @"Factors of Fermat numbers + product if multiple factors found:" + gDidFactorHeader = 1 + end if + + tim = fn CACurrentMediaTime + + // factor current Fermat number gF(gFN) + gFactorCount = 0 + + mpz_t nCopy + mpz_init( nCopy ) + mpz_set( nCopy, gF(gFN) ) + fn FactorRec( nCopy ) + mpz_clear( nCopy ) + // Fk = [f1, f2, ...] + int j + lineStr = @"" + lineStr = concat( lineStr, fn FermatLabel( gFN ) ) + lineStr = concat( lineStr, @" = [" ) + j = 0 + while j < gFactorCount + if j > 0 + lineStr = concat( lineStr, @", " ) + end if + factStr = fn Abbrev( gFactors(j) ) + lineStr = concat( lineStr, factStr ) + j = j + 1 + wend + + lineStr = concat( lineStr, @"]" ) + print lineStr; + // if >= 2 factors, second line = product line + if gFactorCount >= 2 + lineStr = @"" + lineStr = concat( lineStr, fn FermatLabel( gFN ) ) + lineStr = concat( lineStr, @" = " ) + CFStringRef fAbbrev + fAbbrev = fn Abbrev( gF(gFN) ) + lineStr = @"\n " + lineStr = concat( lineStr, fAbbrev ) + print lineStr; + end if + + td = fn CACurrentMediaTime - tim + if td > 1 + lineStr = fn StringWithFormat (@" (%.3f secs)", (fn CACurrentMediaTime - tim)) + print @lineStr; + end if + gFN = gFN + 1 + // Rosetta task sets a limit to under 5 minutes + // so kill the next button + if gFN > 14 then button 2, NO +end fn + +// ------------------------------------------------------------ +// Dialog handler +// ------------------------------------------------------------ +void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef ) + select ( ev ) + case _btnClick + select ( tag ) + case 2 + fn Factor_More + end select + + case _windowShouldClose + // clear any uncleared mpz + int i + mpz_clear( fm ) + i = 0 + while i <= 15 + mpz_clear( gF(i) ) + i ++ + wend + i = 0 + while i <= 30 + mpz_clear( gFactors(i) ) + i ++ + wend + end + end select +end fn + +on dialog fn DoDialog + +// ------------------------------------------------------------ +// Main +// ------------------------------------------------------------ +window 1, @"Fermat numbers", (0,0,700,540) +button 2, YES,, @"Next", (580,20,100,20),,, 1 + +fn InitFermat +fn Main + +HandleEvents diff --git a/Task/Fermat-numbers/JavaScript/fermat-numbers.js b/Task/Fermat-numbers/JavaScript/fermat-numbers.js new file mode 100644 index 0000000000..84d92d755f --- /dev/null +++ b/Task/Fermat-numbers/JavaScript/fermat-numbers.js @@ -0,0 +1,172 @@ +// Fermat Numbers Calculator and Factorizer + +const TWO = 2n; + +// Calculate Fermat number F[n] = 2^(2^n) + 1 +function fermat(n) { + return TWO ** (2n ** BigInt(n)) + 1n; +} + +// Pollard's Rho algorithm helper function +function pollardRhoG(x, n) { + return (x * x + 1n) % n; +} + +// Fast variant of Pollard's Rho algorithm +// Performs 100 multiplications before computing GCD +function pollardRhoFast(n) { + const start = Date.now(); + let x = 2n; + let y = 2n; + let d = 1n; + let count = 0; + let z = 1n; + + while (true) { + x = pollardRhoG(x, n); + y = pollardRhoG(pollardRhoG(y, n), n); + d = (x - y > 0n ? x - y : y - x); + z = (z * d) % n; + count++; + + if (count === 100) { + d = gcd(z, n); + if (d !== 1n) { + break; + } + z = 1n; + count = 0; + } + } + + const end = Date.now(); + console.log(` Pollard rho try factor ${n} elapsed time = ${end - start} ms (factor = ${d}).`); + + if (d === n) { + return 0n; + } + return d; +} + +// Calculate GCD using Euclidean algorithm +function gcd(a, b) { + a = a > 0n ? a : -a; + b = b > 0n ? b : -b; + while (b !== 0n) { + const temp = b; + b = a % b; + a = temp; + } + return a; +} + +// Miller-Rabin primality test +function isProbablePrime(n, iterations = 100) { + if (n < 2n) return false; + if (n === 2n || n === 3n) return true; + if (n % 2n === 0n) return false; + + // Write n-1 as 2^r * d + let d = n - 1n; + let r = 0n; + while (d % 2n === 0n) { + d /= 2n; + r++; + } + + // Witness loop + const witnesses = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n]; + for (let i = 0; i < Math.min(iterations, witnesses.length); i++) { + const a = witnesses[i]; + if (a >= n) continue; + + let x = modPow(a, d, n); + if (x === 1n || x === n - 1n) continue; + + let continueWitnessLoop = false; + for (let j = 0n; j < r - 1n; j++) { + x = (x * x) % n; + if (x === n - 1n) { + continueWitnessLoop = true; + break; + } + } + if (!continueWitnessLoop) return false; + } + return true; +} + +// Modular exponentiation +function modPow(base, exp, mod) { + let result = 1n; + base = base % mod; + while (exp > 0n) { + if (exp % 2n === 1n) { + result = (result * base) % mod; + } + exp = exp / 2n; + base = (base * base) % mod; + } + return result; +} + +// Known composite prefixes for large Fermat numbers +const COMPOSITE = { + 9: "5529", + 10: "6078", + 11: "1037", + 12: "5488", + 13: "2884" +}; + +// Factor a Fermat number +function getFactors(fermatIndex, n) { + const factors = []; + + while (true) { + if (isProbablePrime(n)) { + factors.push(n); + break; + } else { + if (COMPOSITE[fermatIndex]) { + const stop = COMPOSITE[fermatIndex]; + if (n.toString().startsWith(stop)) { + factors.push(-BigInt(n.toString().length)); + break; + } + } + const factor = pollardRhoFast(n); + if (factor === 0n) { + factors.push(n); + break; + } else { + factors.push(factor); + n = n / factor; + } + } + } + + return factors; +} + +// Format factors as a string +function getString(factors) { + if (factors.length === 1) { + return `${factors[0]} (PRIME)`; + } + return factors.map(v => { + const s = v.toString(); + return s.startsWith('-') ? `(C${s.substring(1)})` : s; + }).join(' * '); +} + +// Main execution +console.log("First 10 Fermat numbers:"); +for (let i = 0; i < 10; i++) { + console.log(`F[${i}] = ${fermat(i)}`); +} + +console.log("\nFirst 12 Fermat numbers factored:"); +for (let i = 0; i < 13; i++) { + console.log(`F[${i}] = ${getString(getFactors(i, fermat(i)))}`); +} diff --git a/Task/Fermat-numbers/Langur/fermat-numbers.langur b/Task/Fermat-numbers/Langur/fermat-numbers.langur index c530d67ef7..ac4b1b97ee 100644 --- a/Task/Fermat-numbers/Langur/fermat-numbers.langur +++ b/Task/Fermat-numbers/Langur/fermat-numbers.langur @@ -1,4 +1,4 @@ -val fermat = fn i: 2 ^ 2 ^ i + 1 +val fermat = fn(i) { 2 ^ 2 ^ i + 1 } val sz = '\u2080' # small zero code point val factors = fn(var x) { diff --git a/Task/Fermat-numbers/Maxima/fermat-numbers.maxima b/Task/Fermat-numbers/Maxima/fermat-numbers.maxima new file mode 100644 index 0000000000..05f21dcd4d --- /dev/null +++ b/Task/Fermat-numbers/Maxima/fermat-numbers.maxima @@ -0,0 +1,3 @@ +fermats(n) := makelist(2^(2^i)+1, i, 0, n)$ +fermats(9); +map(ifactors, fermats(7)); diff --git a/Task/Fermat-numbers/Pluto/fermat-numbers.pluto b/Task/Fermat-numbers/Pluto/fermat-numbers.pluto new file mode 100644 index 0000000000..7fbd518fcb --- /dev/null +++ b/Task/Fermat-numbers/Pluto/fermat-numbers.pluto @@ -0,0 +1,37 @@ +require "bignum" +local fmt = require "fmt" + +local one = bigint.one +local two = bigint.two + +local function fermat(n) return (two ^ (two ^ n)) + one end + +local fns = {} +print("The first 10 fermat numbers are:") +for i = 0, 9 do + fns[i + 1] = fermat(i) + print($"F{fmt.sub(i)} = {fns[i + 1]}") +end + +print("\nFactors of the first 9 Fermat numbers:") +mpz.init() +for i = 0, 8 do + io.write($"F{fmt.sub(i)} = ") + local factors + if i < 7 then + factors = bigint.factors(fns[i + 1]) + else + factors = mpz.factors(fns[i + 1]) + end + fmt.lwrite(factors) + if #factors == 1 then + print(" (prime)") + elseif !factors[1]:isprobableprime(10) then + print(" (second factor is composite)") + else + print() + end +end + +local f = bigint.pollard(fns[10]) +print($"\nThe smallest factor of F₉ is: {f}") diff --git a/Task/Fermat-numbers/R/fermat-numbers.r b/Task/Fermat-numbers/R/fermat-numbers.r new file mode 100644 index 0000000000..fd7d6ca3e1 --- /dev/null +++ b/Task/Fermat-numbers/R/fermat-numbers.r @@ -0,0 +1,5 @@ +library(gmp) + +fermat <- function(n) 1+2^(2^as.bigz(n)) +print(fermat(0:9), initLine=FALSE) +print(lapply(fermat(0:7), factorize), initLine=FALSE) diff --git a/Task/Fermat-numbers/Unicon/fermat-numbers.unicon b/Task/Fermat-numbers/Unicon/fermat-numbers.unicon new file mode 100644 index 0000000000..c73c71bdcf --- /dev/null +++ b/Task/Fermat-numbers/Unicon/fermat-numbers.unicon @@ -0,0 +1,21 @@ +link fastprime + +procedure main(A) + limit := \A[1] | 10 + limit2 := \A[2] | 6 + write("First ",limit," Fermat numbers:") + cnt := 0 + every f := fermat()\limit do { + if cnt > limit2 then write(right(cnt,3)," ",f) + else { + if (g := f/(x := getfactor(f))) = 1 then s := " is prime" + else s := " factors: ["||x||" x "||(f/x)||"]" + write(right(cnt,3)," ",f,s) + } + cnt +:= 1 + } +end + +procedure fermat() + suspend 2^2^seq(0)+1 +end diff --git a/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-1.adb b/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-1.adb new file mode 100644 index 0000000000..7284d33835 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-1.adb @@ -0,0 +1,11 @@ +package Bonacci is + + type Sequence is array(Positive range <>) of Positive; + + function Generate(Start: Sequence; Length: Positive := 10) return Sequence; + + Start_Fibonacci: constant Sequence := (1, 1); + Start_Tribonacci: constant Sequence := (1, 1, 2); + Start_Tetranacci: constant Sequence := (1, 1, 2, 4); + Start_Lucas: constant Sequence := (2, 1); +end Bonacci; diff --git a/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-2.adb b/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-2.adb new file mode 100644 index 0000000000..c1c4709cff --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-2.adb @@ -0,0 +1,20 @@ +package body Bonacci is + + function Generate(Start: Sequence; Length: Positive := 10) return Sequence is + begin + if Length <= Start'Length then + return Start(Start'First .. Start'First+Length-1); + else + declare + Sum: Natural := 0; + begin + for I in Start'Range loop + Sum := Sum + Start(I); + end loop; + return Start(Start'First) + & Generate(Start(Start'First+1 .. Start'Last) & Sum, Length-1); + end; + end if; + end Generate; + +end Bonacci; diff --git a/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-3.adb b/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-3.adb new file mode 100644 index 0000000000..9e069f09a5 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Ada/fibonacci-n-step-number-sequences-3.adb @@ -0,0 +1,21 @@ +with Ada.Text_IO, Bonacci; + +procedure Test_Bonacci is + + procedure Print(Name: String; S: Bonacci.Sequence) is + begin + Ada.Text_IO.Put(Name & "("); + for I in S'First .. S'Last-1 loop + Ada.Text_IO.Put(Integer'Image(S(I)) & ","); + end loop; + Ada.Text_IO.Put_Line(Integer'Image(S(S'Last)) & " )"); + end Print; + +begin + Print("Fibonacci: ", Bonacci.Generate(Bonacci.Start_Fibonacci)); + Print("Tribonacci: ", Bonacci.Generate(Bonacci.Start_Tribonacci)); + Print("Tetranacci: ", Bonacci.Generate(Bonacci.Start_Tetranacci)); + Print("Lucas: ", Bonacci.Generate(Bonacci.Start_Lucas)); + Print("Decanacci: ", + Bonacci.Generate((1, 1, 2, 4, 8, 16, 32, 64, 128, 256), 15)); +end Test_Bonacci; diff --git a/Task/Fibonacci-n-step-number-sequences/FutureBasic/fibonacci-n-step-number-sequences.basic b/Task/Fibonacci-n-step-number-sequences/FutureBasic/fibonacci-n-step-number-sequences.basic new file mode 100644 index 0000000000..2f4cec55f5 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/FutureBasic/fibonacci-n-step-number-sequences.basic @@ -0,0 +1,26 @@ +include "NSLog.incl" + +CFStringRef local fn FibonacciSequences( type as CFStringRef, startSequence as CFArrayRef, count as NSInteger ) + CFMutableArrayRef result = fn MutableArrayWithArray( startSequence ) + NSInteger n = fn ArrayCount( startSequence ) + + while ( fn ArrayCount( result ) < count ) + CFArrayRef lastNElements = fn ArraySubarrayWithRange( result, fn RangeMake( fn ArrayCount( result ) - n, n ) ) + CFNumberRef sumNumber = (CFNumberRef)fn ObjectValueForKeyPath( lastNElements, @"@sum.self" ) + NSInteger sum = fn NumberIntegerValue( sumNumber ) + MutableArrayAddObject( result, @(sum) ) + wend + return fn StringWithFormat( @"%10s: [%@]", fn StringUTF8String( type ), fn ArrayComponentsJoinedByString( result, @", " ) ) +end fn = NULL + +NSLog( @"%@", fn FibonacciSequences( @"lucas", @[@1,@1], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"tribonacci", @[@1,@1,@2], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"tetranacci", @[@1,@1,@2,@4], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"pentanacci", @[@1,@1,@2,@4,@8], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"hexanacci", @[@1,@1,@2,@4,@8,@16], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"heptanacci", @[@1,@1,@2,@4,@8,@16,@32], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"octonacci", @[@1,@1,@2,@4,@8,@16,@32,@64], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"nonanacci", @[@1,@1,@2,@4,@8,@16,@32,@64,@128], 15 ) ) +NSLog( @"%@", fn FibonacciSequences( @"decanacci", @[@1,@1,@2,@4,@8,@16,@32,@64,@128,@256], 15 ) ) + +HandleEvents diff --git a/Task/Fibonacci-n-step-number-sequences/Pluto/fibonacci-n-step-number-sequences.pluto b/Task/Fibonacci-n-step-number-sequences/Pluto/fibonacci-n-step-number-sequences.pluto new file mode 100644 index 0000000000..4501bc62f7 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Pluto/fibonacci-n-step-number-sequences.pluto @@ -0,0 +1,31 @@ +local fmt = require "fmt" +require "table2" + +local function fib_n(initial, num_terms) + local n = #initial + if n < 2 or num_terms < 0 then error("Invalid argument(s).") end + if num_terms <= n then return initial:clone() end + local fibs = table.rep(num_terms, 0) + for i = 1, n do fibs[i] = initial[i] end + for i = n + 1, num_terms do + local sum = 0 + for j = i - n, i do sum += fibs[j] end + fibs[i] = sum + end + return fibs +end + +local names = { + "fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci", + "heptanacci", "octonacci", "nonanacci", "decanacci" +} +local initial = {1, 1, 2, 4, 8, 16, 32, 64, 128, 256} +print(" n name values") +local values = fib_n({2, 1}, 15) +fmt.write("%2d %-10s", 2, "lucas") +fmt.tprint("%4d", values, #values) +for i = 1, 9 do + values = fib_n(initial:slice(1, i + 1), 15) + fmt.write("%2d %-10s", i + 1, names[i]) + fmt.tprint("%4d", values, #values) +end diff --git a/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.ps1 b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.ps1 new file mode 100644 index 0000000000..a062d172a9 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-1.ps1 @@ -0,0 +1,17 @@ +#Create generator of extended fibonaci +Function Get-ExtendedFibonaciGenerator($InitialValues ){ + $Values = $InitialValues + { + #exhaust initial values first before calculating next values by summation + if ($InitialValues.Length -gt 0) { + $NextValue = $InitialValues[0] + $Script:InitialValues = $InitialValues | Select -Skip 1 + return $NextValue + } + + $NextValue = $Values | Measure-Object -Sum | Select -ExpandProperty Sum + $Script:Values = @($Values | Select-Object -Skip 1) + @($NextValue) + + $NextValue + }.GetNewClosure() +} diff --git a/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.ps1 b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.ps1 new file mode 100644 index 0000000000..5b4c7f0141 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/PowerShell/fibonacci-n-step-number-sequences-2.ps1 @@ -0,0 +1,10 @@ +$Name = 'fibo tribo tetra penta hexa hepta octo nona deca'.Split() +0..($Name.Length-1) | foreach { $Index = $_ + $InitialValues = @(1) + @(foreach ($I In 0..$Index) { [Math]::Pow(2,$I) }) + $Generator = Get-ExtendedFibonaciGenerator $InitialValues + [PSCustomObject] @{ + n = $InitialValues.Length; + Name = "$($Name[$Index])naci"; + Sequence = 1..15 | foreach { & $Generator } | Join-String -Separator ',' + } +} | Format-Table -AutoSize diff --git a/Task/Fibonacci-n-step-number-sequences/R/fibonacci-n-step-number-sequences.r b/Task/Fibonacci-n-step-number-sequences/R/fibonacci-n-step-number-sequences.r index 1762d42436..1c2a1e6974 100644 --- a/Task/Fibonacci-n-step-number-sequences/R/fibonacci-n-step-number-sequences.r +++ b/Task/Fibonacci-n-step-number-sequences/R/fibonacci-n-step-number-sequences.r @@ -1,34 +1,38 @@ #First define matrix exponentiation (R doesn't natively have this) -`%^%` <- function(mat,n) Reduce(`%*%`, rep(list(mat), n)) +`%^%` <- function(mat, n) Reduce(`%*%`, rep(list(mat), n)) #For the nth Fibonacci-like sequence Fn, this function generates the matrix #that will transform the vector (Fn_k, Fn_k-1, ..., Fn_k-n) to the vector #(Fn_k+1, Fn_k, ..., Fn_k-n+1) i.e. determine the next member of the sequence -gen_nfibmat <- function(n){ +fibmat <- function(n) { id <- diag(1, n-1, n-1) - nfibmat <- rbind(rep(1,n-1),id) - nfibmat <- cbind(nfibmat, c(1, rep(0,n-1))) - return(nfibmat) + mat <- rbind(rep(1, n-1), id) + cbind(mat, c(1, rep(0, n-1))) } #This function generates a vector of initial values (which, you will notice from #looking at the sequences, are always 1 followed by the first n-1 powers of 2) -gen_init <- function(n) rev(c(1, 2^(0:(n-2)))) +gen_init <- function(n) rev(c(1, 2^(2:n-2))) #Now it's easy to define any Fibonacci-like n-step sequence -fiblike <- function(n,k){ - if(k<=n) rev(gen_init(n))[k] - else ((gen_nfibmat(n)%^%(k-n))%*%gen_init(n))[1] +fiblike <- function(n) function(t) { + if (t <= n) { + rev(gen_init(n))[t] + } else { + (fibmat(n) %^% (t-n) %*% gen_init(n))[1] + } } -fibonacci <- function(k) fiblike(2,k) -tribonacci <- function(k) fiblike(3,k) -tetrabonacci <- function(k) fiblike(4,k) - lucas <- function(k){ - if(k<=2) c(2,1)[k] - else ((gen_nfibmat(2)%^%(k-2))%*%c(1,2))[1] + if (k <= 2) { + c(2, 1)[k] + } else { + (fibmat(2) %^% (k-2) %*% c(1, 2))[1] + } } -seqnames <- c("fibonacci","tribonacci","tetrabonacci","lucas") -setNames(lapply(str2expression(seqnames), function(f) sapply(1:15, f)), seqnames) +seqnames <- c("fibo", "tribo", "tetra", "penta", "hexa", + "hepta", "octa", "nona", "deca") |> paste0("nacci") + +for (i in 2:10) cat(seqnames[i-1], "|", sapply(1:15, fiblike(i)), "\n") +cat("lucas |", sapply(1:15, lucas), "\n") diff --git a/Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vbs b/Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vbs new file mode 100644 index 0000000000..1cbcceb740 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vbs @@ -0,0 +1,31 @@ +'function arguments: +'init - initial series of the sequence(e.g. "1,1") +'rep - how many times the sequence repeats - init +Function generate_seq(init,rep) + token = Split(init,",") + step_count = UBound(token) + rep = rep - (UBound(token) + 1) + out = init + For i = 1 To rep + sum = 0 + n = step_count + Do While n >= 0 + sum = sum + token(UBound(token)-n) + n = n - 1 + Loop + 'add the next number to the sequence + ReDim Preserve token(UBound(token) + 1) + token(UBound(token)) = sum + out = out & "," & sum + Next + generate_seq = out +End Function + +WScript.StdOut.Write "fibonacci: " & generate_seq("1,1",15) +WScript.StdOut.WriteLine +WScript.StdOut.Write "tribonacci: " & generate_seq("1,1,2",15) +WScript.StdOut.WriteLine +WScript.StdOut.Write "tetranacci: " & generate_seq("1,1,2,4",15) +WScript.StdOut.WriteLine +WScript.StdOut.Write "lucas: " & generate_seq("2,1",15) +WScript.StdOut.WriteLine diff --git a/Task/Fibonacci-sequence/68000-Assembly/fibonacci-sequence.68000 b/Task/Fibonacci-sequence/68000-Assembly/fibonacci-sequence.68000 index 9e11c9c4eb..56d4f34eb5 100644 --- a/Task/Fibonacci-sequence/68000-Assembly/fibonacci-sequence.68000 +++ b/Task/Fibonacci-sequence/68000-Assembly/fibonacci-sequence.68000 @@ -1,20 +1,20 @@ fib: - MOVEM.L D4-D5,-(SP) - MOVE.L D0,D4 - MOVEQ #0,D5 - CMP.L #2,D0 - BCS .bar - MOVEQ #0,D5 + MOVEM.L D4-D5,-(SP) + MOVE.L D0,D4 + MOVEQ #0,D5 + CMP.L #2,D0 + BCS .bar + MOVEQ #0,D5 .foo: - MOVE.L D4,D0 - SUBQ.L #1,D0 - JSR fib - SUBQ.L #2,D4 - ADD.L D0,D5 - CMP.L #1,D4 - BHI .foo + MOVE.L D4,D0 + SUBQ.L #1,D0 + JSR fib + SUBQ.L #2,D4 + ADD.L D0,D5 + CMP.L #1,D4 + BHI .foo .bar: - MOVE.L D5,D0 - ADD.L D4,D0 - MOVEM.L (SP)+,D4-D5 - RTS + MOVE.L D5,D0 + ADD.L D4,D0 + MOVEM.L (SP)+,D4-D5 + RTS diff --git a/Task/Fibonacci-sequence/8080-Assembly/fibonacci-sequence-2.8080 b/Task/Fibonacci-sequence/8080-Assembly/fibonacci-sequence-2.8080 index 618b5d80d1..be8e1ae7fb 100644 --- a/Task/Fibonacci-sequence/8080-Assembly/fibonacci-sequence-2.8080 +++ b/Task/Fibonacci-sequence/8080-Assembly/fibonacci-sequence-2.8080 @@ -1,100 +1,100 @@ - ;------------------------------------------------------- - ; useful equates - ;------------------------------------------------------- -bdos equ 5 ; BDOS entry -cr equ 13 ; ASCII carriage return -lf equ 10 ; ASCII line feed -space equ 32 ; ASCII space char -conout equ 2 ; BDOS console output function -putstr equ 9 ; BDOS print string function -nterms equ 20 ; number of terms (max=24) to display - ;------------------------------------------------------- - ; main code begins here - ;------------------------------------------------------- - org 100h - lxi h,0 ; save CP/M's stack - dad sp - shld oldstk - lxi sp,stack ; set our own stack - lxi d,signon ; print signon message - mvi c,putstr - call bdos - mvi a,0 ; start with Fib(0) -mloop: push a ; save our count - call fib - call putdec - mvi a,space ; separate the numbers - call putchr - pop a ; get our count back - inr a ; increment it - cpi nterms+1 ; have we reached our limit? - jnz mloop ; no, keep going - lhld oldstk ; all done; get CP/M's stack back - sphl ; restore it - ret ; back to command processor - ;------------------------------------------------------- - ; calculate nth Fibonacci number (max n = 24) - ; entry: A = n - ; exit: HL = Fib(n) - ;------------------------------------------------------- -fib: mov c,a ; C holds n - lxi d,0 ; DE holds Fib(n-2) - lxi h,1 ; HL holds Fib(n-1) - ana a ; Fib(0) is a special case - jnz fib2 ; n > 0 so calculate normally - xchg ; otherwise return with HL=0 - ret -fib2: dcr c - jz fib3 ; we're done - push h ; save Fib(n-1) - dad d ; HL = Fib(n), soon to be Fib(n-1) - pop d ; DE = old F(n-1), now Fib(n-2) - jmp fib2 ; ready for next pass -fib3: ret - ;------------------------------------------------------- - ; console output of char in A register - ;------------------------------------------------------- -putchr: push h - push d - push b - mov e,a - mvi c,conout - call bdos - pop b - pop d - pop h - ret - ;--------------------------------------------------------- - ; Output decimal number to console - ; HL holds 16-bit unsigned binary number to print - ;--------------------------------------------------------- -putdec: push b - push d - push h - lxi b,-10 - lxi d,-1 + ;------------------------------------------------------- + ; useful equates + ;------------------------------------------------------- +bdos equ 5 ; BDOS entry +cr equ 13 ; ASCII carriage return +lf equ 10 ; ASCII line feed +space equ 32 ; ASCII space char +conout equ 2 ; BDOS console output function +putstr equ 9 ; BDOS print string function +nterms equ 20 ; number of terms (max=24) to display + ;------------------------------------------------------- + ; main code begins here + ;------------------------------------------------------- + org 100h + lxi h,0 ; save CP/M's stack + dad sp + shld oldstk + lxi sp,stack ; set our own stack + lxi d,signon ; print signon message + mvi c,putstr + call bdos + mvi a,0 ; start with Fib(0) +mloop: push a ; save our count + call fib + call putdec + mvi a,space ; separate the numbers + call putchr + pop a ; get our count back + inr a ; increment it + cpi nterms+1 ; have we reached our limit? + jnz mloop ; no, keep going + lhld oldstk ; all done; get CP/M's stack back + sphl ; restore it + ret ; back to command processor + ;------------------------------------------------------- + ; calculate nth Fibonacci number (max n = 24) + ; entry: A = n + ; exit: HL = Fib(n) + ;------------------------------------------------------- +fib: mov c,a ; C holds n + lxi d,0 ; DE holds Fib(n-2) + lxi h,1 ; HL holds Fib(n-1) + ana a ; Fib(0) is a special case + jnz fib2 ; n > 0 so calculate normally + xchg ; otherwise return with HL=0 + ret +fib2: dcr c + jz fib3 ; we're done + push h ; save Fib(n-1) + dad d ; HL = Fib(n), soon to be Fib(n-1) + pop d ; DE = old F(n-1), now Fib(n-2) + jmp fib2 ; ready for next pass +fib3: ret + ;------------------------------------------------------- + ; console output of char in A register + ;------------------------------------------------------- +putchr: push h + push d + push b + mov e,a + mvi c,conout + call bdos + pop b + pop d + pop h + ret + ;--------------------------------------------------------- + ; Output decimal number to console + ; HL holds 16-bit unsigned binary number to print + ;--------------------------------------------------------- +putdec: push b + push d + push h + lxi b,-10 + lxi d,-1 putdec2: - dad b - inx d - jc putdec2 - lxi b,10 - dad b - xchg - mov a,h - ora l - cnz putdec ; recursive call - mov a,e - adi '0' - call putchr - pop h - pop d - pop b - ret - ;------------------------------------------------------- - ; data area - ;------------------------------------------------------- -signon: db 'Fibonacci number sequence:',cr,lf,'$' -oldstk: dw 0 -stack equ $+128 ; 64-level stack - ; - end + dad b + inx d + jc putdec2 + lxi b,10 + dad b + xchg + mov a,h + ora l + cnz putdec ; recursive call + mov a,e + adi '0' + call putchr + pop h + pop d + pop b + ret + ;------------------------------------------------------- + ; data area + ;------------------------------------------------------- +signon: db 'Fibonacci number sequence:',cr,lf,'$' +oldstk: dw 0 +stack equ $+128 ; 64-level stack + ; + end diff --git a/Task/Fibonacci-sequence/8086-Assembly/fibonacci-sequence-1.8086 b/Task/Fibonacci-sequence/8086-Assembly/fibonacci-sequence-1.8086 index bfc6f6adc4..a5f26d870d 100644 --- a/Task/Fibonacci-sequence/8086-Assembly/fibonacci-sequence-1.8086 +++ b/Task/Fibonacci-sequence/8086-Assembly/fibonacci-sequence-1.8086 @@ -1,30 +1,30 @@ fib: -; WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86 -; INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR. -; OUTPUTS TO AX +; WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86 +; INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR. +; OUTPUTS TO AX push BP push BX push AX - mov BX, DI ;COPY INPUT TO BX - xor AX, AX ;MOV AX,0 - test BX, BX ;SET FLAGS ACCORDING TO BX - je LBB0_4 ;IF BX == 0 RETURN 0 - cmp BX, 1 ;IF BX == 1 RETURN 1 + mov BX, DI ;COPY INPUT TO BX + xor AX, AX ;MOV AX,0 + test BX, BX ;SET FLAGS ACCORDING TO BX + je LBB0_4 ;IF BX == 0 RETURN 0 + cmp BX, 1 ;IF BX == 1 RETURN 1 jne LBB0_3 - mov AX, 1 ;ELSE, SET AX = 1 AND RETURN + mov AX, 1 ;ELSE, SET AX = 1 AND RETURN jmp LBB0_4 LBB0_3: lea DI, WORD PTR [BX - 1] ;DI = BX - 1 - call fib ;RETURN FIB(BX-1) - mov BP, AX ;STORE THIS IN BP + call fib ;RETURN FIB(BX-1) + mov BP, AX ;STORE THIS IN BP add BX, -2 - mov DI, BX - call fib ;GET FIB(DI - 2) - add AX, BP ;RETURN FIB(DI - 1) + FIB(DI - 2) + mov DI, BX + call fib ;GET FIB(DI - 2) + add AX, BP ;RETURN FIB(DI - 1) + FIB(DI - 2) LBB0_4: - add sp,2 + add sp,2 pop BX pop BP ret diff --git a/Task/Fibonacci-sequence/ANSI-BASIC/fibonacci-sequence.basic b/Task/Fibonacci-sequence/ANSI-BASIC/fibonacci-sequence.basic new file mode 100644 index 0000000000..97e2cf499e --- /dev/null +++ b/Task/Fibonacci-sequence/ANSI-BASIC/fibonacci-sequence.basic @@ -0,0 +1,22 @@ +100 REM Fibonacci sequence +110 DECLARE EXTERNAL FUNCTION Fib +120 INPUT PROMPT "Enter n for fib(n): ": N +130 PRINT Fib(N) +140 END +150 REM *** +160 EXTERNAL FUNCTION Fib(N) +170 IF N = 0 THEN +180 LET Fib = 0 +190 ELSEIF N = 1 THEN +200 LET Fib = 1 +210 ELSE +220 LET Prev = 0 +230 LET Curr = 1 +240 FOR I = 2 TO N +250 LET T = Curr +260 LET Curr = Prev + Curr +270 LET Prev = T +280 NEXT I +290 LET Fib = Curr +300 END IF +310 END FUNCTION diff --git a/Task/Fibonacci-sequence/Ada/fibonacci-sequence-1.adb b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-1.adb new file mode 100644 index 0000000000..7e4e9f8563 --- /dev/null +++ b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-1.adb @@ -0,0 +1,19 @@ +with Ada.Text_IO, Ada.Command_Line; + +procedure Fib is + + X: Positive := Positive'Value(Ada.Command_Line.Argument(1)); + + function Fib(P: Positive) return Positive is + begin + if P <= 2 then + return 1; + else + return Fib(P-1) + Fib(P-2); + end if; + end Fib; + +begin + Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = "); + Ada.Text_IO.Put_Line(Integer'Image(Fib(X))); +end Fib; diff --git a/Task/Fibonacci-sequence/Ada/fibonacci-sequence-2.adb b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-2.adb new file mode 100644 index 0000000000..63f969409b --- /dev/null +++ b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-2.adb @@ -0,0 +1,20 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Fibonacci is + function Fibonacci (N : Natural) return Natural is + This : Natural := 0; + That : Natural := 1; + Sum : Natural; + begin + for I in 1..N loop + Sum := This + That; + That := This; + This := Sum; + end loop; + return This; + end Fibonacci; +begin + for N in 0..10 loop + Put_Line (Positive'Image (Fibonacci (N))); + end loop; +end Test_Fibonacci; diff --git a/Task/Fibonacci-sequence/Ada/fibonacci-sequence-3.adb b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-3.adb new file mode 100644 index 0000000000..1bab08c378 --- /dev/null +++ b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-3.adb @@ -0,0 +1,33 @@ +with Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers; + +procedure Fibonacci is + + X: Positive := Positive'Value(Ada.Command_Line.Argument(1)); + + Bit_Length: Positive := 1 + (696 * X) / 1000; + -- that number of bits is sufficient to store the full result. + + package LN is new Crypto.Types.Big_Numbers + (Bit_Length + (32 - Bit_Length mod 32)); + -- the actual number of bits has to be a multiple of 32 + use LN; + + function Fib(P: Positive) return Big_Unsigned is + Previous: Big_Unsigned := Big_Unsigned_Zero; + Result: Big_Unsigned := Big_Unsigned_One; + Tmp: Big_Unsigned; + begin + -- Result = 1 = Fibonacci(1) + for I in 1 .. P-1 loop + Tmp := Result; + Result := Previous + Result; + Previous := Tmp; + -- Result = Fibonacci(I+1)) + end loop; + return Result; + end Fib; + +begin + Ada.Text_IO.Put("Fibonacci(" & Integer'Image(X) & " ) = "); + Ada.Text_IO.Put_Line(LN.Utils.To_String(Fib(X))); +end Fibonacci; diff --git a/Task/Fibonacci-sequence/Ada/fibonacci-sequence-4.adb b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-4.adb new file mode 100644 index 0000000000..1e221a27a2 --- /dev/null +++ b/Task/Fibonacci-sequence/Ada/fibonacci-sequence-4.adb @@ -0,0 +1,49 @@ +with ada.text_io; +use ada.text_io; + +procedure fast_fibo is + -- We work with biggest natural integers in a 64 bits machine + type Big_Int is mod 2**64; + + -- We provide an index type for accessing the fibonacci sequence terms + type Index is new Big_Int; + + -- fibo is a generic function that needs a modulus type since it will return + -- the n'th term of the fibonacci sequence modulus this type (use Big_Int to get the + -- expected behaviour in this particular task) + generic + type ring_element is mod <>; + with function "*" (a, b : ring_element) return ring_element is <>; + function fibo (n : Index) return ring_element; + function fibo (n : Index) return ring_element is + + type matrix is array (1 .. 2, 1 .. 2) of ring_element; + + -- f is the matrix you apply to a column containing (F_n, F_{n+1}) to get + -- the next one containing (F_{n+1},F_{n+2}) + -- could be a more general matrix (given as a generic parameter) to deal with + -- other linear sequences of order 2 + f : constant matrix := (1 => (0, 1), 2 => (1, 1)); + + function "*" (a, b : matrix) return matrix is + (1 => (a(1,1)*b(1,1)+a(1,2)*b(2,1), a(1,1)*b(1,2)+a(1,2)*b(2,2)), + 2 => (a(2,1)*b(1,1)+a(2,2)*b(2,1), a(2,1)*b(1,2)+a(2,2)*b(2,2))); + + function square (m : matrix) return matrix is (m * m); + + -- Fast_Pow could be non recursive but it doesn't really matter since + -- the number of calls is bounded up by the size (in bits) of Big_Int (e.g 64) + function fast_pow (m : matrix; n : Index) return matrix is + (if n = 0 then (1 => (1, 0), 2 => (0, 1)) -- = identity matrix + elsif n mod 2 = 0 then square (fast_pow (m, n / 2)) + else m * square (fast_pow (m, n / 2))); + + begin + return fast_pow (f, n)(2, 1); + end fibo; + + function Big_Int_Fibo is new fibo (Big_Int); +begin + -- calculate instantly F_n with n=10^15 (modulus 2^64 ) + put_line (Big_Int_Fibo (10**15)'img); +end fast_fibo; diff --git a/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-1.applescript b/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-1.applescript index 4aaa24a506..aeb7909bad 100644 --- a/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-1.applescript +++ b/Task/Fibonacci-sequence/AppleScript/fibonacci-sequence-1.applescript @@ -2,10 +2,10 @@ set fibs to {} set x to (text returned of (display dialog "What fibbonaci number do you want?" default answer "3")) set x to x as integer repeat with y from 1 to x - if (y = 1 or y = 2) then - copy 1 to the end of fibs - else - copy ((item (y - 1) of fibs) + (item (y - 2) of fibs)) to the end of fibs - end if + if (y = 1 or y = 2) then + copy 1 to the end of fibs + else + copy ((item (y - 1) of fibs) + (item (y - 2) of fibs)) to the end of fibs + end if end repeat return item x of fibs diff --git a/Task/Fibonacci-sequence/Applesoft-BASIC/fibonacci-sequence-1.basic b/Task/Fibonacci-sequence/Applesoft-BASIC/fibonacci-sequence-1.basic new file mode 100644 index 0000000000..0eae65927b --- /dev/null +++ b/Task/Fibonacci-sequence/Applesoft-BASIC/fibonacci-sequence-1.basic @@ -0,0 +1,2 @@ + 0 DEF FN F(N) = INT ((((1 + SQR (5)) / 2) ^ N - ((1 - SQR (5)) / 2) ^ N) / SQR (5) + 0.5) + 1 S = - 38: FOR I = S TO - S: PRINT MID$ (" ",(I = S) + 1) FN F(I);: NEXT diff --git a/Task/Fibonacci-sequence/Applesoft-BASIC/fibonacci-sequence-2.basic b/Task/Fibonacci-sequence/Applesoft-BASIC/fibonacci-sequence-2.basic new file mode 100644 index 0000000000..4b57ff9423 --- /dev/null +++ b/Task/Fibonacci-sequence/Applesoft-BASIC/fibonacci-sequence-2.basic @@ -0,0 +1 @@ +? FN F(39)" " FN F(45)" " FN F(183) diff --git a/Task/Fibonacci-sequence/Arturo/fibonacci-sequence-1.arturo b/Task/Fibonacci-sequence/Arturo/fibonacci-sequence-1.arturo new file mode 100644 index 0000000000..ec25e22ede --- /dev/null +++ b/Task/Fibonacci-sequence/Arturo/fibonacci-sequence-1.arturo @@ -0,0 +1,8 @@ +fib: $[x][ + switch x<2 -> 1 + -> (fib x-1) + (fib x-2) +] + +loop 1..25 [x][ + print ["Fibonacci of" x "=" fib x] +] diff --git a/Task/Fibonacci-sequence/Arturo/fibonacci-sequence-2.arturo b/Task/Fibonacci-sequence/Arturo/fibonacci-sequence-2.arturo new file mode 100644 index 0000000000..9adf41f8be --- /dev/null +++ b/Task/Fibonacci-sequence/Arturo/fibonacci-sequence-2.arturo @@ -0,0 +1,18 @@ +fib: function [n][ + if n < 2 -> return 1 + + a: 1 + b: 1 + + loop 2..n 'x [ + tmp: a + b + a: b + b: tmp + ] + + return b +] + +loop 1..25 'x [ + print ["Fibonacci of" x "=" fib x] +] diff --git a/Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-1.au3 b/Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-1.au3 new file mode 100644 index 0000000000..33e8dadbe5 --- /dev/null +++ b/Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-1.au3 @@ -0,0 +1,27 @@ +#AutoIt Version: 3.2.10.0 +$n0 = 0 +$n1 = 1 +$n = 10 +MsgBox (0,"Iterative Fibonacci ", it_febo($n0,$n1,$n)) + +Func it_febo($n_0,$n_1,$N) + $first = $n_0 + $second = $n_1 + $next = $first + $second + $febo = 0 + For $i = 1 To $N-3 + $first = $second + $second = $next + $next = $first + $second + Next + if $n==0 Then + $febo = 0 + ElseIf $n==1 Then + $febo = $n_0 + ElseIf $n==2 Then + $febo = $n_1 + Else + $febo = $next + EndIf + Return $febo +EndFunc diff --git a/Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-2.au3 b/Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-2.au3 new file mode 100644 index 0000000000..25e5457531 --- /dev/null +++ b/Task/Fibonacci-sequence/AutoIt/fibonacci-sequence-2.au3 @@ -0,0 +1,19 @@ +#AutoIt Version: 3.2.10.0 +$n0 = 0 +$n1 = 1 +$n = 10 +MsgBox (0,"Recursive Fibonacci ", rec_febo($n0,$n1,$n)) +Func rec_febo($r_0,$r_1,$R) + if $R<3 Then + if $R==2 Then + Return $r_1 + ElseIf $R==1 Then + Return $r_0 + ElseIf $R==0 Then + Return 0 + EndIf + Return $R + Else + Return rec_febo($r_0,$r_1,$R-1) + rec_febo($r_0,$r_1,$R-2) + EndIf +EndFunc diff --git a/Task/Fibonacci-sequence/Ballerina/fibonacci-sequence.ballerina b/Task/Fibonacci-sequence/Ballerina/fibonacci-sequence.ballerina new file mode 100644 index 0000000000..98a7beae89 --- /dev/null +++ b/Task/Fibonacci-sequence/Ballerina/fibonacci-sequence.ballerina @@ -0,0 +1,22 @@ +// https://rosettacode.org/wiki/Fibonacci_sequence +import ballerina/io; +function fib_iter(int n) returns int { + if (n < 2) { + return n; + } + int fib_prev = 1; + int fib = 1; + int temp = 0; + foreach int _ in int:range(2, n, 1) { + temp = fib; + fib = fib_prev + fib; + fib_prev = temp; + } + return fib; +} + +public function main() { + foreach int i in int:range(1, 21, 1) { + io:println(fib_iter(i)); + } +} diff --git a/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-1.bf b/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-1.bf index e8a3408a96..67c92ec7a4 100644 --- a/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-1.bf +++ b/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-1.bf @@ -1,2 +1,16 @@ ++++++++++ >>+<<[->[->+>+<<]>[-<+>]>[-<+>]<<<] + +Print the number +>>[-]<[->+<]> + +>+ +[[-]< + [->+< + [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+< + [->[-]>>+>+<<<] + ]]]]]]]]< + ]>>[>]++++++[-<++++++++>]>> +]<<<[.[-]<<<] + +<+++++++++++++.---. diff --git a/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-2.bf b/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-2.bf index ab977a3e10..2d2882d94f 100644 --- a/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-2.bf +++ b/Task/Fibonacci-sequence/Brainf---/fibonacci-sequence-2.bf @@ -1,37 +1,37 @@ -+++++ +++++ #0 set to n ->> + Init #2 to 1 ++++++ +++++ #0 set to n +>> + Init #2 to 1 << [ - - #Decrement counter in #0 - >>. Notice: This doesn't print it in ascii - To look at results you can pipe into a file and look with a hex editor - - Copying sequence to save #2 in #4 using #5 as restore space - >>[-] Move to #4 and clear - >[-] Clear #5 - <<< #2 - [ Move loop - - >> + > + <<< Subtract #2 and add #4 and #5 - ] - >>> - [ Restore loop - - <<< + >>> Subtract from #5 and add to #2 - ] + - #Decrement counter in #0 + >>. Notice: This doesn't print it in ascii + To look at results you can pipe into a file and look with a hex editor - <<<< Back to #1 - Non destructive add sequence using #3 as restore value - [ Loop to add - - > + > + << Subtract #1 and add to value #2 and restore space #3 - ] - >> - [ Loop to restore #1 from #3 - - << + >> Subtract from restore space #3 and add in #1 - ] - - << [-] Clear #1 - >>> - [ Loop to move #4 to #1 - - <<< + >>> Subtract from #4 and add to #1 - ] - <<<< Back to #0 + Copying sequence to save #2 in #4 using #5 as restore space + >>[-] Move to #4 and clear + >[-] Clear #5 + <<< #2 + [ Move loop + - >> + > + <<< Subtract #2 and add #4 and #5 + ] + >>> + [ Restore loop + - <<< + >>> Subtract from #5 and add to #2 + ] + + <<<< Back to #1 + Non destructive add sequence using #3 as restore value + [ Loop to add + - > + > + << Subtract #1 and add to value #2 and restore space #3 + ] + >> + [ Loop to restore #1 from #3 + - << + >> Subtract from restore space #3 and add in #1 + ] + + << [-] Clear #1 + >>> + [ Loop to move #4 to #1 + - <<< + >>> Subtract from #4 and add to #1 + ] + <<<< Back to #0 ] diff --git a/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn b/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn index d2e4752aa5..bed250b14f 100644 --- a/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn +++ b/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn @@ -9,12 +9,12 @@ fib-unary [0 [[[2 0 [2 (1 0)]]]] k i] # ternary fibonacci using infinite list iteration (very fast) fib-list \index fibs - fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1))) + fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1))) :test (fib-list (+6)) ((+8)) # recursive fib (very slow) fib-rec y [[0 0){ - tempf = fnow + fnext; - fnow = fnext; - fnext = tempf; - } - return fnext; + int fnow = 0, fnext = 1, tempf; + while(--n>0){ + tempf = fnow + fnext; + fnow = fnext; + fnext = tempf; + } + return fnext; } diff --git a/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c b/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c index 13ecb81d98..142598ac07 100644 --- a/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c +++ b/Task/Fibonacci-sequence/C/fibonacci-sequence-5.c @@ -4,9 +4,9 @@ typedef struct node node; struct node { - int n; - mpz_t v; - node *next; + int n; + mpz_t v; + node *next; }; #define CSIZE 37 @@ -15,60 +15,60 @@ node *cache[CSIZE]; // very primitive linked hash table node * find_cache(int n) { - int idx = n % CSIZE; - node *p; + int idx = n % CSIZE; + node *p; - for (p = cache[idx]; p && p->n != n; p = p->next); - if (p) return p; + for (p = cache[idx]; p && p->n != n; p = p->next); + if (p) return p; - p = malloc(sizeof(node)); - p->next = cache[idx]; - cache[idx] = p; + p = malloc(sizeof(node)); + p->next = cache[idx]; + cache[idx] = p; - if (n < 2) { - p->n = n; - mpz_init_set_ui(p->v, 1); - } else { - p->n = -1; // -1: value not computed yet - mpz_init(p->v); - } - return p; + if (n < 2) { + p->n = n; + mpz_init_set_ui(p->v, 1); + } else { + p->n = -1; // -1: value not computed yet + mpz_init(p->v); + } + return p; } mpz_t tmp1, tmp2; mpz_t *fib(int n) { - int x; - node *p = find_cache(n); + int x; + node *p = find_cache(n); - if (p->n < 0) { - p->n = n; - x = n / 2; + if (p->n < 0) { + p->n = n; + x = n / 2; - mpz_mul(tmp1, *fib(x-1), *fib(n - x - 1)); - mpz_mul(tmp2, *fib(x), *fib(n - x)); - mpz_add(p->v, tmp1, tmp2); - } - return &p->v; + mpz_mul(tmp1, *fib(x-1), *fib(n - x - 1)); + mpz_mul(tmp2, *fib(x), *fib(n - x)); + mpz_add(p->v, tmp1, tmp2); + } + return &p->v; } int main(int argc, char **argv) { - int i, n; - if (argc < 2) return 1; + int i, n; + if (argc < 2) return 1; - mpz_init(tmp1); - mpz_init(tmp2); + mpz_init(tmp1); + mpz_init(tmp2); - for (i = 1; i < argc; i++) { - n = atoi(argv[i]); - if (n < 0) { - printf("bad input: %s\n", argv[i]); - continue; - } + for (i = 1; i < argc; i++) { + n = atoi(argv[i]); + if (n < 0) { + printf("bad input: %s\n", argv[i]); + continue; + } - // about 75% of time is spent in printing - gmp_printf("%Zd\n", *fib(n)); - } - return 0; + // about 75% of time is spent in printing + gmp_printf("%Zd\n", *fib(n)); + } + return 0; } diff --git a/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cob b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cob new file mode 100644 index 0000000000..4c4c1900c2 --- /dev/null +++ b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-1.cob @@ -0,0 +1,40 @@ +Program-ID. Fibonacci-Sequence. +Data Division. +Working-Storage Section. + 01 FIBONACCI-PROCESSING. + 05 FIBONACCI-NUMBER PIC 9(36) VALUE 0. + 05 FIB-ONE PIC 9(36) VALUE 0. + 05 FIB-TWO PIC 9(36) VALUE 1. + 01 DESIRED-COUNT PIC 9(4). + 01 FORMATTING. + 05 INTERM-RESULT PIC Z(35)9. + 05 FORMATTED-RESULT PIC X(36). + 05 FORMATTED-SPACE PIC x(35). +Procedure Division. + 000-START-PROGRAM. + Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing. + Accept DESIRED-COUNT. + If DESIRED-COUNT is less than 1 + Stop run. + If DESIRED-COUNT is less than 2 + Move FIBONACCI-NUMBER to INTERM-RESULT + Move INTERM-RESULT to FORMATTED-RESULT + Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT + Display FORMATTED-RESULT + Stop run. + Subtract 1 from DESIRED-COUNT. + Move FIBONACCI-NUMBER to INTERM-RESULT. + Move INTERM-RESULT to FORMATTED-RESULT. + Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT. + Display FORMATTED-RESULT. + Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero. + Stop run. + 100-COMPUTE-FIBONACCI. + Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO. + Move FIB-TWO to FIB-ONE. + Move FIBONACCI-NUMBER to FIB-TWO. + Subtract 1 from DESIRED-COUNT. + Move FIBONACCI-NUMBER to INTERM-RESULT. + Move INTERM-RESULT to FORMATTED-RESULT. + Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT. + Display FORMATTED-RESULT. diff --git a/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cob b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cob new file mode 100644 index 0000000000..05204bf137 --- /dev/null +++ b/Task/Fibonacci-sequence/COBOL/fibonacci-sequence-2.cob @@ -0,0 +1,45 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. fibonacci-main. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 num PIC 9(6) COMP. +01 fib-num PIC 9(6) COMP. + +PROCEDURE DIVISION. + ACCEPT num + CALL "fibonacci" USING CONTENT num RETURNING fib-num + DISPLAY fib-num + . +END PROGRAM fibonacci-main. + +IDENTIFICATION DIVISION. +PROGRAM-ID. fibonacci RECURSIVE. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 1-before PIC 9(6) COMP. +01 2-before PIC 9(6) COMP. + +LINKAGE SECTION. +01 num PIC 9(6) COMP. + +01 fib-num PIC 9(6) COMP BASED. + +PROCEDURE DIVISION USING num RETURNING fib-num. + ALLOCATE fib-num + EVALUATE num + WHEN 0 + MOVE 0 TO fib-num + WHEN 1 + MOVE 1 TO fib-num + WHEN OTHER + SUBTRACT 1 FROM num + CALL "fibonacci" USING CONTENT num RETURNING 1-before + SUBTRACT 1 FROM num + CALL "fibonacci" USING CONTENT num RETURNING 2-before + ADD 1-before TO 2-before GIVING fib-num + END-EVALUATE + . +END PROGRAM fibonacci. diff --git a/Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chpl b/Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chpl new file mode 100644 index 0000000000..82b9ca6952 --- /dev/null +++ b/Task/Fibonacci-sequence/Chapel/fibonacci-sequence.chpl @@ -0,0 +1,8 @@ +iter fib() { + var a = 0, b = 1; + + while true { + yield a; + (a, b) = (b, b + a); + } +} diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp index 75b857ae65..3aaef5f24d 100644 --- a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-2.lisp @@ -1,7 +1,7 @@ (defun fibonacci (n) (let ((a 0) (b 1) (c n)) (loop for i from 2 to n do - (setq c (+ a b) - a b - b c)) + (setq c (+ a b) + a b + b c)) c)) diff --git a/Task/Fibonacci-sequence/Craft-Basic/fibonacci-sequence.basic b/Task/Fibonacci-sequence/Craft-Basic/fibonacci-sequence.basic index c079bb3e42..3428c89a67 100644 --- a/Task/Fibonacci-sequence/Craft-Basic/fibonacci-sequence.basic +++ b/Task/Fibonacci-sequence/Craft-Basic/fibonacci-sequence.basic @@ -5,10 +5,10 @@ print "Fibonacci Sequence" for i = 0 to 20 - let s = a + b - let a = b - let b = s + let s = a + b + let a = b + let b = s - print s + print s next i diff --git a/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.pas b/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.pas index 641e0d65d1..ee7af2d9f0 100644 --- a/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.pas +++ b/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.pas @@ -1,7 +1,7 @@ function fib(n: Int64): Int64; type TFibMat = array[0..1] of array[0..1] of Int64; - + function FibMatMul(a,b: TFibMat): TFibMat; var i,j,k: integer; tmp: TFibMat; @@ -9,12 +9,12 @@ function fib(n: Int64): Int64; for i := 0 to 1 do for j := 0 to 1 do begin - tmp[i,j] := 0; - for k := 0 to 1 do tmp[i,j] := tmp[i,j] + a[i,k] * b[k,j]; + tmp[i,j] := 0; + for k := 0 to 1 do tmp[i,j] := tmp[i,j] + a[i,k] * b[k,j]; end; FibMatMul := tmp; end; - + function FibMatExp(a: TFibMat; n: Int64): TFibmat; begin if n <= 1 then fibmatexp := a @@ -24,7 +24,7 @@ function fib(n: Int64): Int64; var matrix: TFibMat; - + begin matrix[0,0] := 1; matrix[0,1] := 1; diff --git a/Task/Fibonacci-sequence/ECL/fibonacci-sequence.ecl b/Task/Fibonacci-sequence/ECL/fibonacci-sequence.ecl index a7fba60bfc..908ae516a1 100644 --- a/Task/Fibonacci-sequence/ECL/fibonacci-sequence.ecl +++ b/Task/Fibonacci-sequence/ECL/fibonacci-sequence.ecl @@ -2,12 +2,12 @@ FibFunction(UNSIGNED2 n) := FUNCTION - REAL Sqrt5 := Sqrt(5); - REAL Phi := (1+Sqrt(5))/2; - REAL Phi_Inv := 1/Phi; - UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5); - RETURN FibValue; - END; + REAL Sqrt5 := Sqrt(5); + REAL Phi := (1+Sqrt(5))/2; + REAL Phi_Inv := 1/Phi; + UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5); + RETURN FibValue; + END; FibSeries(UNSIGNED2 n) := FUNCTION diff --git a/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e b/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e index 9ff0549473..bc3f81698d 100644 --- a/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e +++ b/Task/Fibonacci-sequence/Eiffel/fibonacci-sequence.e @@ -1,50 +1,50 @@ class - APPLICATION + APPLICATION create - make + make feature - fibonacci (n: INTEGER): INTEGER - require - non_negative: n >= 0 - local - i, n2, n1, tmp: INTEGER - do - n2 := 0 - n1 := 1 - from - i := 1 - until - i >= n - loop - tmp := n1 - n1 := n2 + n1 - n2 := tmp - i := i + 1 - end - Result := n1 - if n = 0 then - Result := 0 - end - end + fibonacci (n: INTEGER): INTEGER + require + non_negative: n >= 0 + local + i, n2, n1, tmp: INTEGER + do + n2 := 0 + n1 := 1 + from + i := 1 + until + i >= n + loop + tmp := n1 + n1 := n2 + n1 + n2 := tmp + i := i + 1 + end + Result := n1 + if n = 0 then + Result := 0 + end + end feature {NONE} -- Initialization - make - -- Run application. - do - print (fibonacci (0)) - print (" ") - print (fibonacci (1)) - print (" ") - print (fibonacci (2)) - print (" ") - print (fibonacci (3)) - print (" ") - print (fibonacci (4)) - print ("%N") - end + make + -- Run application. + do + print (fibonacci (0)) + print (" ") + print (fibonacci (1)) + print (" ") + print (fibonacci (2)) + print (" ") + print (fibonacci (3)) + print (" ") + print (fibonacci (4)) + print ("%N") + end end diff --git a/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.el b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.el new file mode 100644 index 0000000000..eaf59a9036 --- /dev/null +++ b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.el @@ -0,0 +1,10 @@ +(defun fib (n a b c) + (cond + ((< c n) (fib n b (+ a b) (+ 1 c))) + ((= c n) b) + (t a))) + +(defun fibonacci (n) + (if (< n 2) + n + (fib n 0 1 1))) diff --git a/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.el b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.el new file mode 100644 index 0000000000..f9f7504a0e --- /dev/null +++ b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.el @@ -0,0 +1,15 @@ +(defun fibonacci (n) + (let (vec i j k) + (if (< n 2) + n + (setq vec (make-vector (+ n 1) 0) + i 0 + j 1 + k 2) + (setf (aref vec 1) 1) + (while (<= k n) + (setf (aref vec k) (+ (elt vec i) (elt vec j))) + (setq i (1+ i) + j (1+ j) + k (1+ k))) + (elt vec n)))) diff --git a/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.el b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.el new file mode 100644 index 0000000000..0d5209f5ef --- /dev/null +++ b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.el @@ -0,0 +1,3 @@ +(insert + (mapconcat (lambda (n) (format "%d" (fibonacci n))) + (number-sequence 0 15) " ")) diff --git a/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-1.eu b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-1.eu new file mode 100644 index 0000000000..2001ada169 --- /dev/null +++ b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-1.eu @@ -0,0 +1,4 @@ +function fibor(integer n) + if n<2 then return n end if + return fibor(n-1)+fibor(n-2) +end function diff --git a/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-2.eu b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-2.eu new file mode 100644 index 0000000000..5a4e4b3164 --- /dev/null +++ b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-2.eu @@ -0,0 +1,10 @@ +function fiboi(integer n) +integer f0=0, f1=1, f + if n<2 then return n end if + for i=2 to n do + f=f0+f1 + f0=f1 + f1=f + end for + return f +end function diff --git a/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-3.eu b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-3.eu new file mode 100644 index 0000000000..56d70e8d47 --- /dev/null +++ b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-3.eu @@ -0,0 +1,10 @@ +function fibot(integer n, integer u = 1, integer s = 0) + if n < 1 then + return s + else + return fibot(n-1,u+s,u) + end if +end function + +-- example: +? fibot(10) -- says 55 diff --git a/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-4.eu b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-4.eu new file mode 100644 index 0000000000..420cf11216 --- /dev/null +++ b/Task/Fibonacci-sequence/Euphoria/fibonacci-sequence-4.eu @@ -0,0 +1,78 @@ +include std/mathcons.e -- for PINF constant + +enum ADD, MOVE, GOTO, OUT, TEST, TRUETO + +global sequence tape = { 0, + 1, + { ADD, 2, 1 }, + { TEST, 1, PINF }, + { TRUETO, 0 }, + { OUT, 1, "%.0f\n" }, + { MOVE, 2, 1 }, + { MOVE, 0, 2 }, + { GOTO, 3 } } + +global integer ip +global integer test +global atom accum + +procedure eval( sequence cmd ) + atom i = 1 + while i <= length( cmd ) do + switch cmd[ i ] do + case ADD then + accum = tape[ cmd[ i + 1 ] ] + tape[ cmd[ i + 2 ] ] + i += 2 + + case OUT then + printf( 1, cmd[ i + 2], tape[ cmd[ i + 1 ] ] ) + i += 2 + + case MOVE then + if cmd[ i + 1 ] = 0 then + tape[ cmd[ i + 2 ] ] = accum + else + tape[ cmd[ i + 2 ] ] = tape[ cmd[ i + 1 ] ] + end if + i += 2 + + case GOTO then + ip = cmd[ i + 1 ] - 1 -- due to ip += 1 in main loop + i += 1 + + case TEST then + if tape[ cmd[ i + 1 ] ] = cmd[ i + 2 ] then + test = 1 + else + test = 0 + end if + i += 2 + + case TRUETO then + if test then + if cmd[ i + 1 ] = 0 then + abort(0) + else + ip = cmd[ i + 1 ] - 1 + end if + end if + + end switch + i += 1 + end while +end procedure + +test = 0 +accum = 0 +ip = 1 + +while 1 do + + -- embedded sequences (assumed to be code) are evaluated + -- atoms (assumed to be data) are ignored + + if sequence( tape[ ip ] ) then + eval( tape[ ip ] ) + end if + ip += 1 +end while diff --git a/Task/Fibonacci-sequence/FTCBASIC/fibonacci-sequence.basic b/Task/Fibonacci-sequence/FTCBASIC/fibonacci-sequence.basic index 12c8d3cb65..cf5ef1590a 100644 --- a/Task/Fibonacci-sequence/FTCBASIC/fibonacci-sequence.basic +++ b/Task/Fibonacci-sequence/FTCBASIC/fibonacci-sequence.basic @@ -6,12 +6,12 @@ print "Fibonacci Sequence" do - let s = a + b - let a = b - let b = s - +1 i + let s = a + b + let a = b + let b = s + +1 i - print s + print s loop i < 20 diff --git a/Task/Fibonacci-sequence/Free-Pascal-Lazarus/fibonacci-sequence.pas b/Task/Fibonacci-sequence/Free-Pascal-Lazarus/fibonacci-sequence.pas index c26b55f4b3..de6b585496 100644 --- a/Task/Fibonacci-sequence/Free-Pascal-Lazarus/fibonacci-sequence.pas +++ b/Task/Fibonacci-sequence/Free-Pascal-Lazarus/fibonacci-sequence.pas @@ -1,40 +1,40 @@ type - /// domain for Fibonacci function - /// where result is within nativeUInt - // You can not name it fibonacciDomain, - // since the Fibonacci function itself - // is defined for all whole numbers - // but the result beyond F(n) exceeds high(nativeUInt). - fibonacciLeftInverseRange = - {$ifdef CPU64} 0..93 {$else} 0..47 {$endif}; + /// domain for Fibonacci function + /// where result is within nativeUInt + // You can not name it fibonacciDomain, + // since the Fibonacci function itself + // is defined for all whole numbers + // but the result beyond F(n) exceeds high(nativeUInt). + fibonacciLeftInverseRange = + {$ifdef CPU64} 0..93 {$else} 0..47 {$endif}; {** - implements Fibonacci sequence iteratively - - \param n the index of the Fibonacci number to calculate - \returns the Fibonacci value at n + implements Fibonacci sequence iteratively + + \param n the index of the Fibonacci number to calculate + \returns the Fibonacci value at n } function fibonacci(const n: fibonacciLeftInverseRange): nativeUInt; type - /// more meaningful identifiers than simple integers - relativePosition = (previous, current, next); + /// more meaningful identifiers than simple integers + relativePosition = (previous, current, next); var - /// temporary iterator variable - i: longword; - /// holds preceding fibonacci values - f: array[relativePosition] of nativeUInt; + /// temporary iterator variable + i: longword; + /// holds preceding fibonacci values + f: array[relativePosition] of nativeUInt; begin - f[previous] := 0; - f[current] := 1; - - // note, in Pascal for-loop-limits are inclusive - for i := 1 to n do - begin - f[next] := f[previous] + f[current]; - f[previous] := f[current]; - f[current] := f[next]; - end; - - // assign to previous, bc f[current] = f[next] for next iteration - fibonacci := f[previous]; + f[previous] := 0; + f[current] := 1; + + // note, in Pascal for-loop-limits are inclusive + for i := 1 to n do + begin + f[next] := f[previous] + f[current]; + f[previous] := f[current]; + f[current] := f[next]; + end; + + // assign to previous, bc f[current] = f[next] for next iteration + fibonacci := f[previous]; end; diff --git a/Task/Fibonacci-sequence/Gleam/fibonacci-sequence-1.gleam b/Task/Fibonacci-sequence/Gleam/fibonacci-sequence-1.gleam new file mode 100644 index 0000000000..b9c685d368 --- /dev/null +++ b/Task/Fibonacci-sequence/Gleam/fibonacci-sequence-1.gleam @@ -0,0 +1,7 @@ +pub fn fib(n: Int) -> Int { + case n { + 0 -> 0 + 1 -> 1 + n -> fib(n - 1) + fib(n - 2) + } +} diff --git a/Task/Fibonacci-sequence/Gleam/fibonacci-sequence-2.gleam b/Task/Fibonacci-sequence/Gleam/fibonacci-sequence-2.gleam new file mode 100644 index 0000000000..a441614810 --- /dev/null +++ b/Task/Fibonacci-sequence/Gleam/fibonacci-sequence-2.gleam @@ -0,0 +1,10 @@ +pub fn fib(n: Int) -> Int { + fib_helper(n, 0, 1) +} + +fn fib_helper(n: Int, res: Int, next: Int) -> Int { + case n, res, next { + 0, res, _ -> res + iter, res, next -> fib_helper(iter - 1, next, res + next) + } +} diff --git a/Task/Fibonacci-sequence/Go/fibonacci-sequence-2.go b/Task/Fibonacci-sequence/Go/fibonacci-sequence-2.go index fb11aac274..08ef7ec02a 100644 --- a/Task/Fibonacci-sequence/Go/fibonacci-sequence-2.go +++ b/Task/Fibonacci-sequence/Go/fibonacci-sequence-2.go @@ -1,15 +1,15 @@ import ( - "math/big" + "math/big" ) func fib(n uint64) *big.Int { - if n < 2 { - return big.NewInt(int64(n)) - } - a, b := big.NewInt(0), big.NewInt(1) - for n--; n > 0; n-- { - a.Add(a, b) - a, b = b, a - } - return b + if n < 2 { + return big.NewInt(int64(n)) + } + a, b := big.NewInt(0), big.NewInt(1) + for n--; n > 0; n-- { + a.Add(a, b) + a, b = b, a + } + return b } diff --git a/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go b/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go index c9bcd60eff..d64fae3ca8 100644 --- a/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go +++ b/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go @@ -1,16 +1,16 @@ func fibNumber() func() int { - fib1, fib2 := 0, 1 - return func() int { - fib1, fib2 = fib2, fib1 + fib2 - return fib1 - } + fib1, fib2 := 0, 1 + return func() int { + fib1, fib2 = fib2, fib1 + fib2 + return fib1 + } } func fibSequence(n int) int { - f := fibNumber() - fib := 0 - for i := 0; i < n; i++ { - fib = f() - } - return fib + f := fibNumber() + fib := 0 + for i := 0; i < n; i++ { + fib = f() + } + return fib } diff --git a/Task/Fibonacci-sequence/Go/fibonacci-sequence-4.go b/Task/Fibonacci-sequence/Go/fibonacci-sequence-4.go index 3e809ed283..394c294d23 100644 --- a/Task/Fibonacci-sequence/Go/fibonacci-sequence-4.go +++ b/Task/Fibonacci-sequence/Go/fibonacci-sequence-4.go @@ -1,15 +1,15 @@ func fib(c chan int) { - a, b := 0, 1 - for { - c <- a - a, b = b, a+b - } + a, b := 0, 1 + for { + c <- a + a, b = b, a+b + } } func main() { - c := make(chan int) - go fib(c) - for i := 0; i < 10; i++ { - fmt.Println(<-c) - } + c := make(chan int) + go fib(c) + for i := 0; i < 10; i++ { + fmt.Println(<-c) + } } diff --git a/Task/Fibonacci-sequence/Harbour/fibonacci-sequence-2.harbour b/Task/Fibonacci-sequence/Harbour/fibonacci-sequence-2.harbour index 6b737b746a..828f253ef4 100644 --- a/Task/Fibonacci-sequence/Harbour/fibonacci-sequence-2.harbour +++ b/Task/Fibonacci-sequence/Harbour/fibonacci-sequence-2.harbour @@ -1,9 +1,9 @@ #include "harbour.ch" Function fibb(n) - local fnow:=0, fnext:=1, tempf - while (--n>0) - tempf:=fnow+fnext - fnow:=fnext - fnext:=tempf - end while -return(fnext) + local fnow:=0, fnext:=1, tempf + while (--n>0) + tempf:=fnow+fnext + fnow:=fnext + fnext:=tempf + end while +return(fnext) diff --git a/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-1.hx b/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-1.hx new file mode 100644 index 0000000000..0aa79aa722 --- /dev/null +++ b/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-1.hx @@ -0,0 +1,15 @@ +static function fib(steps:Int, handler:Int->Void) +{ + var current = 0; + var next = 1; + + for (i in 1...steps) + { + handler(current); + + var temp = current + next; + current = next; + next = temp; + } + handler(current); +} diff --git a/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-2.hx b/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-2.hx new file mode 100644 index 0000000000..dc6c2d7ebe --- /dev/null +++ b/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-2.hx @@ -0,0 +1,19 @@ +class FibIter +{ + private var current = 0; + private var nextItem = 1; + private var limit:Int; + + public function new(limit) this.limit = limit; + + public function hasNext() return limit > 0; + + public function next() { + limit--; + var ret = current; + var temp = current + nextItem; + current = nextItem; + nextItem = temp; + return ret; + } +} diff --git a/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-3.hx b/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-3.hx new file mode 100644 index 0000000000..41f2871d38 --- /dev/null +++ b/Task/Fibonacci-sequence/Haxe/fibonacci-sequence-3.hx @@ -0,0 +1,2 @@ +for (i in new FibIter(10)) + Sys.println(i); diff --git a/Task/Fibonacci-sequence/Jactl/fibonacci-sequence.jactl b/Task/Fibonacci-sequence/Jactl/fibonacci-sequence.jactl new file mode 100644 index 0000000000..459428be6c --- /dev/null +++ b/Task/Fibonacci-sequence/Jactl/fibonacci-sequence.jactl @@ -0,0 +1 @@ +long fib(int n) { n <= 2 ? 1 : fib(n-1) + fib(n-2) } diff --git a/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java b/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java index 91240d8318..e546e2d901 100644 --- a/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java +++ b/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java @@ -3,22 +3,22 @@ */ public static long fib(long n) { if (n <= 0) - return 0; + return 0; long i = (int) (n - 1); long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2; while (i > 0) { - if (i % 2 != 0) { + if (i % 2 != 0) { tmp1 = d * b + c * a; - tmp2 = d * (b + a) + c * b; - a = tmp1; - b = tmp2; - } + tmp2 = d * (b + a) + c * b; + a = tmp1; + b = tmp2; + } tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2)); tmp2 = d * (2 * c + d); - + c = tmp1; d = tmp2; diff --git a/Task/Fibonacci-sequence/Kabap/fibonacci-sequence.kabap b/Task/Fibonacci-sequence/Kabap/fibonacci-sequence.kabap index 6f8f1dde80..e2c4fa2237 100644 --- a/Task/Fibonacci-sequence/Kabap/fibonacci-sequence.kabap +++ b/Task/Fibonacci-sequence/Kabap/fibonacci-sequence.kabap @@ -13,20 +13,20 @@ $sequence = ""; // Prepare a loop $i = 0; :calcnextnumber; - $i = $i++; + $i = $i++; - // Do the calculation for this loop iteration - $b = $a + $b; - $a = $b - $a; + // Do the calculation for this loop iteration + $b = $a + $b; + $a = $b - $a; - // Add the result to the sequence - $sequence = $sequence << $a; + // Add the result to the sequence + $sequence = $sequence << $a; - // Make the loop run a fixed number of times - if $i < $n; { - $sequence = $sequence << ", "; - goto calcnextnumber; - } + // Make the loop run a fixed number of times + if $i < $n; { + $sequence = $sequence << ", "; + goto calcnextnumber; + } // Use the loop counter as the placeholder $i--; diff --git a/Task/Fibonacci-sequence/LSL/fibonacci-sequence.lsl b/Task/Fibonacci-sequence/LSL/fibonacci-sequence.lsl index 3b96c6b595..df0c15ceff 100644 --- a/Task/Fibonacci-sequence/LSL/fibonacci-sequence.lsl +++ b/Task/Fibonacci-sequence/LSL/fibonacci-sequence.lsl @@ -1,15 +1,15 @@ integer Fibonacci(integer n) { - if(n<2) { - return n; - } else { - return Fibonacci(n-1)+Fibonacci(n-2); - } + if(n<2) { + return n; + } else { + return Fibonacci(n-1)+Fibonacci(n-2); + } } default { - state_entry() { - integer x = 0; - for(x=0 ; x<35 ; x++) { - llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x)); - } - } + state_entry() { + integer x = 0; + for(x=0 ; x<35 ; x++) { + llOwnerSay("Fibonacci("+(string)x+")="+(string)Fibonacci(x)); + } + } } diff --git a/Task/Fibonacci-sequence/Lang/fibonacci-sequence-1.lang b/Task/Fibonacci-sequence/Lang/fibonacci-sequence-1.lang index b1fe7d40d3..fdf619ee35 100644 --- a/Task/Fibonacci-sequence/Lang/fibonacci-sequence-1.lang +++ b/Task/Fibonacci-sequence/Lang/fibonacci-sequence-1.lang @@ -1,18 +1,18 @@ fp.fib = ($n) -> { - if($n < 2) { - return $n - } - - $prev = 1 - $cur = 1 - $i = 2 - while($i < $n) { - $tmp = $cur - $cur += $prev - $prev = $tmp - - $i += 1 - } - - return $cur + if($n < 2) { + return $n + } + + $prev = 1 + $cur = 1 + $i = 2 + while($i < $n) { + $tmp = $cur + $cur += $prev + $prev = $tmp + + $i += 1 + } + + return $cur } diff --git a/Task/Fibonacci-sequence/Lang/fibonacci-sequence-2.lang b/Task/Fibonacci-sequence/Lang/fibonacci-sequence-2.lang index f3678330f2..c48fd8dd05 100644 --- a/Task/Fibonacci-sequence/Lang/fibonacci-sequence-2.lang +++ b/Task/Fibonacci-sequence/Lang/fibonacci-sequence-2.lang @@ -1,7 +1,7 @@ fp.fib = ($n) -> { - if($n < 2) { - return $n - } - - return parser.op(fp.fib($n - 1) + fp.fib($n - 2)) + if($n < 2) { + return $n + } + + return parser.op(fp.fib($n - 1) + fp.fib($n - 2)) } diff --git a/Task/Fibonacci-sequence/Langur/fibonacci-sequence-1.langur b/Task/Fibonacci-sequence/Langur/fibonacci-sequence-1.langur new file mode 100644 index 0000000000..dc342270b5 --- /dev/null +++ b/Task/Fibonacci-sequence/Langur/fibonacci-sequence-1.langur @@ -0,0 +1,3 @@ +val fibonacci = fn(x number) { if(x < 2: x ; fn((x - 1)) + fn((x - 2))) } + +writeln map(0..20, by=fibonacci) diff --git a/Task/Fibonacci-sequence/Langur/fibonacci-sequence-2.langur b/Task/Fibonacci-sequence/Langur/fibonacci-sequence-2.langur new file mode 100644 index 0000000000..34a0a4bdc3 --- /dev/null +++ b/Task/Fibonacci-sequence/Langur/fibonacci-sequence-2.langur @@ -0,0 +1,7 @@ +val fibonacci = fn(x number) { + for[f=[0, 1]] of x-1 { + f ~= [f[-1]+f[-2]] + } +} + +writeln fibonacci(20) diff --git a/Task/Fibonacci-sequence/Lasso/fibonacci-sequence.lasso b/Task/Fibonacci-sequence/Lasso/fibonacci-sequence.lasso index f16a4d6143..11791689b7 100644 --- a/Task/Fibonacci-sequence/Lasso/fibonacci-sequence.lasso +++ b/Task/Fibonacci-sequence/Lasso/fibonacci-sequence.lasso @@ -1,19 +1,19 @@ define fibonacci(n::integer) => { - #n < 1 ? return false + #n < 1 ? return false - local( - swap = 0, - n1 = 0, - n2 = 1 - ) + local( + swap = 0, + n1 = 0, + n2 = 1 + ) - loop(#n) => { + loop(#n) => { #swap = #n1 + #n2; #n2 = #n1; #n1 = #swap; - } - return #n1 + } + return #n1 } diff --git a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m index ae02da25a9..45b5f5855b 100644 --- a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m +++ b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m @@ -1,6 +1,6 @@ function f = fib(n) - - f = [1 1 ; 1 0]^(n-1); - f = f(1,1); - + + f = [1 1 ; 1 0]^(n-1); + f = f(1,1); + end diff --git a/Task/Fibonacci-sequence/MIPS-Assembly/fibonacci-sequence.mips b/Task/Fibonacci-sequence/MIPS-Assembly/fibonacci-sequence.mips index 2af84b424d..2d03058ae9 100644 --- a/Task/Fibonacci-sequence/MIPS-Assembly/fibonacci-sequence.mips +++ b/Task/Fibonacci-sequence/MIPS-Assembly/fibonacci-sequence.mips @@ -1,43 +1,43 @@ - .text -main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0 - syscall - - beq $v0, 0, is1 - beq $v0, 1, is1 - - li $s4, 1 # the counter which has to equal to $v0 - - li $s0, 1 - li $s1, 1 + .text +main: li $v0, 5 # read integer from input. The read integer will be stroed in $v0 + syscall -loop: add $s2, $s0, $s1 - addi $s4, $s4, 1 - beq $v0, $s4, iss2 - - add $s0, $s1, $s2 - addi $s4, $s4, 1 - beq $v0, $s4, iss0 - - add $s1, $s2, $s0 - addi $s4, $s4, 1 - beq $v0, $s4, iss1 + beq $v0, 0, is1 + beq $v0, 1, is1 - b loop + li $s4, 1 # the counter which has to equal to $v0 -iss0: move $a0, $s0 - b print + li $s0, 1 + li $s1, 1 -iss1: move $a0, $s1 - b print +loop: add $s2, $s0, $s1 + addi $s4, $s4, 1 + beq $v0, $s4, iss2 -iss2: move $a0, $s2 - b print - - -is1: li $a0, 1 - b print - -print: li $v0, 1 - syscall - li $v0, 10 - syscall + add $s0, $s1, $s2 + addi $s4, $s4, 1 + beq $v0, $s4, iss0 + + add $s1, $s2, $s0 + addi $s4, $s4, 1 + beq $v0, $s4, iss1 + + b loop + +iss0: move $a0, $s0 + b print + +iss1: move $a0, $s1 + b print + +iss2: move $a0, $s2 + b print + + +is1: li $a0, 1 + b print + +print: li $v0, 1 + syscall + li $v0, 10 + syscall diff --git a/Task/Fibonacci-sequence/MoonRock/fibonacci-sequence.moonrock b/Task/Fibonacci-sequence/MoonRock/fibonacci-sequence.moonrock new file mode 100644 index 0000000000..7075c7865b --- /dev/null +++ b/Task/Fibonacci-sequence/MoonRock/fibonacci-sequence.moonrock @@ -0,0 +1,33 @@ +' Fibonacci sequence + +BEGIN DEF +pointer dword FibPtr~ ' Why "pointer dword" must be in lower case? +SUB CalcFib(N%, FibPtr~) + +BEGIN CODE +PRINT "Enter n for fib(n): " +INPUT SN$ +N% = VAL(SN$) +PRINT "\n" +CALL CalcFib(N%, VARPTR(Fib&)) +PRINT Fib& + "\n" +END + +SUB CalcFib(N%, FibPtr~) +IF N% = 0 THEN + Fib& = 0 +ELSE + IF N% = 1 THEN + Fib& = 1 + ELSE + Prev& = 0 + Fib& = 1 + FOR I% = 2 TO N% + T& = Fib& + Fib& = Prev& + Fib& + Prev& = T& + NEXT + ENDIF +ENDIF +[FibPtr~] = Fib& +END SUB diff --git a/Task/Fibonacci-sequence/NGS/fibonacci-sequence.ngs b/Task/Fibonacci-sequence/NGS/fibonacci-sequence.ngs index e16999c8dc..de28b49cc2 100644 --- a/Task/Fibonacci-sequence/NGS/fibonacci-sequence.ngs +++ b/Task/Fibonacci-sequence/NGS/fibonacci-sequence.ngs @@ -1,11 +1,11 @@ F fib(n:Int) { - n < 2 returns n - local a = 1, b = 1 - # i is automatically local because of for() - for(i=2; i u128 { diff --git a/Task/Fibonacci-sequence/Oz/fibonacci-sequence-3.oz b/Task/Fibonacci-sequence/Oz/fibonacci-sequence-3.oz index dffcb8b604..6b922645c2 100644 --- a/Task/Fibonacci-sequence/Oz/fibonacci-sequence-3.oz +++ b/Task/Fibonacci-sequence/Oz/fibonacci-sequence-3.oz @@ -1,9 +1,9 @@ fun{Fib N} fun{Loop N A B} if N == 0 then - B + B else - {Loop N-1 A+B A} + {Loop N-1 A+B A} end end in diff --git a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pas b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pas index 2778140af7..142085ccca 100644 --- a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pas +++ b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pas @@ -9,9 +9,47 @@ Program FastFibonacciGMP; // AI Assistant: DeepSeek // Description: Multiple Fibonacci algorithms with arbitrary precision // AI translated from my own 2016 python app ( the hybrid part ) -// License: Public Domain for Rosetta Code contribution +// +// LICENSE & ATTRIBUTION: +// ---------------------------------------------------------------------------- +// 1. This Pascal source file (`FastFibonacciGMP.pas`) is released to the +// PUBLIC DOMAIN for Rosetta Code contribution. Author waives all copyright. +// +// 2. This program uses the Free Pascal `GMP` unit, which is a binding to the +// GNU MP Library (GMP). The `GMP` unit is part of Free Pascal's RTL-extra +// package, licensed under the GNU Lesser General Public License (LGPL) +// with a static linking exception. +// +// 3. The underlying GNU MP Library (libgmp) itself is licensed under: +// - GNU Lesser General Public License version 3 or later (LGPLv3+), OR +// - GNU General Public License version 2 or later (GPLv2+). +// +// 4. When compiled, this program links to the external GMP C library. +// For license compliance, users must have access to the GMP library +// source code (available at https://gmplib.org/). // ============================================================================ - +// MATHEMATICAL FOUNDATION ATTRIBUTION: +// ---------------------------------------------------------------------------- +// 1. Fast Doubling Formulas (Fibonacci Squaring): +// F(2k) = F(k) × [2×F(k+1) - F(k)] +// F(2k+1) = F(k+1)² + F(k)² +// Derived from Cassini's identity (1680) and Catalan's identity (1879). +// Modern algorithmic presentation: Dijkstra (1978), Cohn (1963). +// +// 2. Fibonacci Tripling Formulas: +// F(3k) = 5×F(k)³ + 3×(-1)ᵏ×F(k) +// F(3k+1) = F(k+1)³ + 3×F(k+1)×F(k)² - F(k)³ +// Derived from Binet's formula (1843). +// Algorithmic optimization: Various number theory sources. +// +// 3. Hybrid Decomposition Algorithm: +// Recursive decomposition using factors 2 and 3 based on divisibility. +// Original implementation concept: jpd (2016 Python implementation). +// Ported to Pascal with algorithmic corrections: DeepSeek AI (2025). +// +// NOTE: These mathematical identities are in the public domain. +// This specific implementation is original work. +// ---------------------------------------------------------------------------- Uses SysUtils, DateUtils, diff --git a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-6.pas b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-6.pas index 144e54e50c..66cd6b9cbb 100644 --- a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-6.pas +++ b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-6.pas @@ -6,11 +6,11 @@ function Fibo_BigInt(n: integer): string; //maXbox tbig2:= TInteger.create(0); //result (a) tbig3:= Tinteger.create(1); //b for it:= 1 to n do begin - tbig1.assign(tbig2) - tbig2.assign(tbig3); - tbig1.add(tbig3); - tbig3.assign(tbig1); - end; + tbig1.assign(tbig2) + tbig2.assign(tbig3); + tbig1.add(tbig3); + tbig3.assign(tbig1); + end; result:= tbig2.toString(false) tbig3.free; tbig2.free; diff --git a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-7.pas b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-7.pas new file mode 100644 index 0000000000..d0a65dc81f --- /dev/null +++ b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-7.pas @@ -0,0 +1,62 @@ +program Fibonacci_console; + +{$mode objfpc}{$H+} + +uses SysUtils; + +function Fibonacci( n : word) : uint64; +{ +Starts with the pair F[0],F[1]. At each iteration, uses the doubling formulae +to pass from F[k],F[k+1] to F[2k],F[2k+1]. If the current bit of n (starting +from the high end) is 1, there is a further step to F[2k+1],F[2k+2]. +} +var + marker, half_n : word; + f, g : uint64; // pair of consecutive Fibonacci numbers + t, u : uint64; // -----"----- +begin + // The values of F[0], F[1], F[2] are assumed to be known + case n of + 0 : result := 0; + 1, 2 : result := 1; + else begin + half_n := n shr 1; + marker := 1; + while marker <= half_n do marker := marker shl 1; + + // First time: current bit is 1 by construction, + // so go straight from F[0],F[1] to F[1],F[2]. + f := 1; // = F[1] + g := 1; // = F[2] + marker := marker shr 1; + + while marker > 1 do begin + t := f*(2*g - f); + u := f*f + g*g; + if (n and marker = 0) then begin + f := t; + g := u; + end + else begin + f := u; + g := t + u; + end; + marker := marker shr 1; + end; + + // Last time: we need only one of the pair. + if (n and marker = 0) then + result := f*(2*g - f) + else + result := f*f + g*g; + end; // end else (i.e. n > 2) + end; // end case +end; + +// Main program +var + n : word; +begin + for n := 0 to 93 do + WriteLn( SysUtils.Format( 'F[%2u] = %20u', [n, Fibonacci(n)])); +end. diff --git a/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-1.ps1 b/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-1.ps1 new file mode 100644 index 0000000000..1751cbad42 --- /dev/null +++ b/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-1.ps1 @@ -0,0 +1,9 @@ +function FibonacciNumber ( $count ) +{ + $answer = @(0,1) + while ($answer.Length -le $count) + { + $answer += $answer[-1] + $answer[-2] + } + return $answer +} diff --git a/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-2.ps1 b/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-2.ps1 new file mode 100644 index 0000000000..59dc348a5b --- /dev/null +++ b/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-2.ps1 @@ -0,0 +1,4 @@ +$count = 8 +$answer = @(0,1) +0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] } +$answer diff --git a/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-3.ps1 b/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-3.ps1 new file mode 100644 index 0000000000..cdaad2c70b --- /dev/null +++ b/Task/Fibonacci-sequence/PowerShell/fibonacci-sequence-3.ps1 @@ -0,0 +1,8 @@ +function fib($n) { + switch ($n) { + 0 { return 0 } + 1 { return 1 } + { $_ -lt 0 } { return [Math]::Pow(-1, -$n + 1) * (fib (-$n)) } + default { return (fib ($n - 1)) + (fib ($n - 2)) } + } +} diff --git a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-5.pro b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-5.pro index 1150125a8a..43409d2871 100644 --- a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-5.pro +++ b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-5.pro @@ -43,9 +43,9 @@ fib(2, 1) :- !. fib(1, 1) :- !. fib(0, 0) :- !. fib(A, D) :- - B is A+ -1, - fib(B, E), - C is A+ -2, - fib(C, F), - D is E+F, - asserta((fib(A, D):-!)). + B is A+ -1, + fib(B, E), + C is A+ -2, + fib(C, F), + D is E+F, + asserta((fib(A, D):-!)). diff --git a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-6.pro b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-6.pro index a7075b9d2e..68e2e6133e 100644 --- a/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-6.pro +++ b/Task/Fibonacci-sequence/Prolog/fibonacci-sequence-6.pro @@ -1,13 +1,13 @@ :- use_module(lambda). fib(N, FN) :- - cont_fib(N, _, FN, \_^Y^_^U^(U = Y)). + cont_fib(N, _, FN, \_^Y^_^U^(U = Y)). cont_fib(N, FN1, FN, Pred) :- - ( N < 2 -> - call(Pred, 0, 1, FN1, FN) - ; - N1 is N - 1, - P = \X^Y^Y^U^(U is X + Y), - cont_fib(N1, FNA, FNB, P), - call(Pred, FNA, FNB, FN1, FN) - ). + ( N < 2 -> + call(Pred, 0, 1, FN1, FN) + ; + N1 is N - 1, + P = \X^Y^Y^U^(U is X + Y), + cont_fib(N1, FNA, FNB, P), + call(Pred, FNA, FNB, FN1, FN) + ). diff --git a/Task/Fibonacci-sequence/PureBasic/fibonacci-sequence-1.basic b/Task/Fibonacci-sequence/PureBasic/fibonacci-sequence-1.basic index 5fa01e2eba..85d61bb8f7 100644 --- a/Task/Fibonacci-sequence/PureBasic/fibonacci-sequence-1.basic +++ b/Task/Fibonacci-sequence/PureBasic/fibonacci-sequence-1.basic @@ -1,3 +1,3 @@ Macro Fibonacci (n) - Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5)) + Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5)) EndMacro diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-18.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-18.py new file mode 100644 index 0000000000..77ba6a3cd2 --- /dev/null +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-18.py @@ -0,0 +1,6 @@ +fibseq = [1,1,] +fiblength = 21 +for x in range(1,fiblength-1): + xcount = fibseq[x-1] + fibseq[x] + fibseq.append(xcount) +print(xcount) diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-2.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-2.py index e0b43f44f0..1362a70208 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-2.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-2.py @@ -1,11 +1,11 @@ def analytic_fibonacci91(m): - """ - Binet's algebraic formula for the nth Fibonacci number. - Good for up to n=91 - Uses numpy longdoubles: + """ + Binet's algebraic formula for the nth Fibonacci number. + Good for up to n=91 + Uses numpy longdoubles: - See: https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula - """ + See: https://artofproblemsolving.com/wiki/index.php/Binet%27s_Formula + """ import numpy as np assert isinstance(m,int), "parameter must be an integer." diff --git a/Task/Fibonacci-sequence/QBasic/fibonacci-sequence-3.basic b/Task/Fibonacci-sequence/QBasic/fibonacci-sequence-3.basic index 3ab578dd8c..108e26bd8e 100644 --- a/Task/Fibonacci-sequence/QBasic/fibonacci-sequence-3.basic +++ b/Task/Fibonacci-sequence/QBasic/fibonacci-sequence-3.basic @@ -1,7 +1,7 @@ FUNCTION recFib (n) IF (n < 2) THEN - recFib = n + recFib = n ELSE - recFib = recFib(n - 1) + recFib(n - 2) + recFib = recFib(n - 1) + recFib(n - 2) END IF END FUNCTION diff --git a/Task/Fibonacci-sequence/Ra/fibonacci-sequence.ra b/Task/Fibonacci-sequence/Ra/fibonacci-sequence.ra index d6ad197a64..d4337cbf34 100644 --- a/Task/Fibonacci-sequence/Ra/fibonacci-sequence.ra +++ b/Task/Fibonacci-sequence/Ra/fibonacci-sequence.ra @@ -1,45 +1,45 @@ class FibonacciSequence - **Prints the nth fibonacci number** - - on start - - args := program arguments - - if args empty - print .fibonacci(8) - - else - - try - print .fibonacci(integer.parse(args[0])) - - catch FormatException - print to Console.error made !, "Input must be an integer" - exit program with error code - - catch OverflowException - print to Console.error made !, "Number too large" - exit program with error code - - define fibonacci(n as integer) as integer is shared - **Returns the nth fibonacci number** - - test - assert fibonacci(0) = 0 - assert fibonacci(1) = 1 - assert fibonacci(2) = 1 - assert fibonacci(3) = 2 - assert fibonacci(4) = 3 - assert fibonacci(5) = 5 - assert fibonacci(6) = 8 - assert fibonacci(7) = 13 - assert fibonacci(8) = 21 + **Prints the nth fibonacci number** - - body - a, b := 0, 1 - - for n - a, b := b, a + b - - return a + on start + + args := program arguments + + if args empty + print .fibonacci(8) + + else + + try + print .fibonacci(integer.parse(args[0])) + + catch FormatException + print to Console.error made !, "Input must be an integer" + exit program with error code + + catch OverflowException + print to Console.error made !, "Number too large" + exit program with error code + + define fibonacci(n as integer) as integer is shared + **Returns the nth fibonacci number** + + test + assert fibonacci(0) = 0 + assert fibonacci(1) = 1 + assert fibonacci(2) = 1 + assert fibonacci(3) = 2 + assert fibonacci(4) = 3 + assert fibonacci(5) = 5 + assert fibonacci(6) = 8 + assert fibonacci(7) = 13 + assert fibonacci(8) = 21 + + + body + a, b := 0, 1 + + for n + a, b := b, a + b + + return a diff --git a/Task/Fibonacci-sequence/Rebol/fibonacci-sequence.rebol b/Task/Fibonacci-sequence/Rebol/fibonacci-sequence.rebol new file mode 100644 index 0000000000..79fbbe4550 --- /dev/null +++ b/Task/Fibonacci-sequence/Rebol/fibonacci-sequence.rebol @@ -0,0 +1,20 @@ +Rebol [ + title: "Rosetta code: Fibonacci sequence" + file: %Fibonacci_sequence.r3 + url: https://rosettacode.org/wiki/Fibonacci_sequence +] + +fibonacci: function/with [ + {Return the Nth Fibonacci number using iterative state advancement. + Uses a shared block to swap fn and fn-1 in a single expression.} + number [integer!] "which Fibonacci number to compute (0-indexed)" +][ + fn-1: 0 ;; F(0) + fn: 1 ;; F(1) + loop number advance-fibonacci +][ + fn: fn-1: 0 + advance-fibonacci: [ fn: fn-1 + fn-1: fn ] ;; simultaneously: new fn = old fn + old fn-1 +] + +probe collect [repeat i 18 [keep fibonacci i]] diff --git a/Task/Fibonacci-sequence/Red/fibonacci-sequence.red b/Task/Fibonacci-sequence/Red/fibonacci-sequence.red index 36df2205f1..418dbc3ad6 100644 --- a/Task/Fibonacci-sequence/Red/fibonacci-sequence.red +++ b/Task/Fibonacci-sequence/Red/fibonacci-sequence.red @@ -2,7 +2,7 @@ Red [] palindrome: [fn: fn-1 + fn-1: fn] fibonacci: func [n][ - fn-1: 0 - fn: 1 - loop n palindrome + fn-1: 0 + fn: 1 + loop n palindrome ] diff --git a/Task/Fibonacci-sequence/Rocq/fibonacci-sequence.rocq b/Task/Fibonacci-sequence/Rocq/fibonacci-sequence.rocq new file mode 100644 index 0000000000..dd67f5d48a --- /dev/null +++ b/Task/Fibonacci-sequence/Rocq/fibonacci-sequence.rocq @@ -0,0 +1,8 @@ +Fixpoint rec_fib (m : nat) (a : nat) (b : nat) : nat := + match m with + | 0 => a + | S k => rec_fib k b (a + b) + end. + +Definition fib (n : nat) : nat := + rec_fib n 0 1 . diff --git a/Task/Fibonacci-sequence/SNOBOL4/fibonacci-sequence-1.sno b/Task/Fibonacci-sequence/SNOBOL4/fibonacci-sequence-1.sno index 08d14abe87..527e9eeabc 100644 --- a/Task/Fibonacci-sequence/SNOBOL4/fibonacci-sequence-1.sno +++ b/Task/Fibonacci-sequence/SNOBOL4/fibonacci-sequence-1.sno @@ -1,8 +1,8 @@ - define("fib(a)") :(fib_end) -fib fib = lt(a,2) a :s(return) - fib = fib(a - 1) + fib(a - 2) :(return) + define("fib(a)") :(fib_end) +fib fib = lt(a,2) a :s(return) + fib = fib(a - 1) + fib(a - 2) :(return) fib_end -while a = trim(input) :f(end) - output = a " " fib(a) :(while) +while a = trim(input) :f(end) + output = a " " fib(a) :(while) end diff --git a/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-6.scm b/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-6.scm new file mode 100644 index 0000000000..f65866f281 --- /dev/null +++ b/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-6.scm @@ -0,0 +1,29 @@ +(define (fast-fib-pair n) + ;; By Arnold Schönhage, personal communication, 2004 + ;; returns f_n f_{n+1} + (case n + ((1) (values 1 1)) + ((2) (values 1 2)) + (else + (let ((m (quotient n 2))) + (call-with-values + (lambda () (fast-fib-pair m)) + (lambda (f_m f_m+1) + (let ((f_m^2 (square f_m)) + (f_m+1^2 (square f_m+1))) + (if (even? n) + (values (- (* 2 f_m+1^2) + (* 3 f_m^2) + (if (odd? m) -2 2)) + (+ f_m^2 f_m+1^2)) + (values (+ f_m^2 f_m+1^2) + (- (* 3 f_m+1^2) + (* 2 f_m^2) + (if (odd? m) -2 2))))))))))) + +(call-with-values + (lambda () + (fast-fib-pair 100000000)) + (lambda (f_n f_n+1) + (display (list (modulo f_n 100000) (modulo f_n+1 100000))) + (newline))) diff --git a/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-1.sequencel b/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-1.sequencel index 6953f57002..7dec53fe65 100644 --- a/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-1.sequencel +++ b/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-1.sequencel @@ -1,4 +1,4 @@ fibonacci(n) := - n when n < 2 - else - fibonacci(n - 1) + fibonacci(n - 2); + n when n < 2 + else + fibonacci(n - 1) + fibonacci(n - 2); diff --git a/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-2.sequencel b/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-2.sequencel index 490c89a8a4..ce1f89a329 100644 --- a/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-2.sequencel +++ b/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-2.sequencel @@ -1,8 +1,8 @@ fibonacci(n) := fibonacciHelper(0, 1, n); - + fibonacciHelper(prev, next, n) := - prev when n < 1 - else - next when n = 1 - else - fibonacciHelper(next, next + prev, n - 1); + prev when n < 1 + else + next when n = 1 + else + fibonacciHelper(next, next + prev, n - 1); diff --git a/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-3.sequencel b/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-3.sequencel index 9b94830856..68db36fcfc 100644 --- a/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-3.sequencel +++ b/Task/Fibonacci-sequence/SequenceL/fibonacci-sequence-3.sequencel @@ -1,11 +1,11 @@ fibonacci(n) := fibonacciHelper([[1,0],[0,1]], n); fibonacciHelper(M(2), n) := - let - N := [[1,1],[1,0]]; - in - M[1,1] when n <= 1 - else - fibonacciHelper(matmul(M, N), n - 1); + let + N := [[1,1],[1,0]]; + in + M[1,1] when n <= 1 + else + fibonacciHelper(matmul(M, N), n - 1); matmul(A(2), B(2)) [i,j] := sum( A[i,all] * B[all,j] ); diff --git a/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence-1.ml b/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence-1.ml index 3eb1a6a1f9..84b7d6f71e 100644 --- a/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence-1.ml +++ b/Task/Fibonacci-sequence/Standard-ML/fibonacci-sequence-1.ml @@ -1,7 +1,7 @@ fun fib n = let - fun fib' (0,a,b) = a - | fib' (n,a,b) = fib' (n-1,a+b,a) + fun fib' (0,a,b) = a + | fib' (n,a,b) = fib' (n-1,a+b,a) in - fib' (n,0,1) + fib' (n,0,1) end diff --git a/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata index dc6c807168..b4805991dd 100644 --- a/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata +++ b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata @@ -4,7 +4,7 @@ clear qui set obs `n' qui gen a=. dyngen { - update a=a[_n-1]+a[_n-2], missval(1) + update a=a[_n-1]+a[_n-2], missval(1) } end diff --git a/Task/Fibonacci-sequence/SuperCollider/fibonacci-sequence-3.sc b/Task/Fibonacci-sequence/SuperCollider/fibonacci-sequence-3.sc index 3786922f2c..e296245e40 100644 --- a/Task/Fibonacci-sequence/SuperCollider/fibonacci-sequence-3.sc +++ b/Task/Fibonacci-sequence/SuperCollider/fibonacci-sequence-3.sc @@ -1,9 +1,9 @@ ( - f = { |n| - var sqrt5 = sqrt(5); - var p = (1 + sqrt5) / 2; - var q = reciprocal(p); - ((p ** n) + (q ** n) / sqrt5 + 0.5).trunc - }; - (0..20).collect(f) + f = { |n| + var sqrt5 = sqrt(5); + var p = (1 + sqrt5) / 2; + var q = reciprocal(p); + ((p ** n) + (q ** n) / sqrt5 + 0.5).trunc + }; + (0..20).collect(f) ) diff --git a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.basic b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.basic index 16478ad3ec..04802aabb7 100644 --- a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.basic +++ b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.basic @@ -3,18 +3,18 @@ nMin=0 u(n)=u(n-1)+u(n-2) u(nMin)={1,0} [TABLE] -n u(n) -------- ------- -0 0 -1 1 -2 1 -3 2 -4 3 -5 5 -6 8 -7 13 -8 21 -9 34 -10 55 -11 89 -12 144 +n u(n) +------- ------- +0 0 +1 1 +2 1 +3 2 +4 3 +5 5 +6 8 +7 13 +8 21 +9 34 +10 55 +11 89 +12 144 diff --git a/Task/Fibonacci-sequence/Uiua/fibonacci-sequence-1.uiua b/Task/Fibonacci-sequence/Uiua/fibonacci-sequence-1.uiua new file mode 100644 index 0000000000..eeecbcc0f7 --- /dev/null +++ b/Task/Fibonacci-sequence/Uiua/fibonacci-sequence-1.uiua @@ -0,0 +1,2 @@ +F ← |1 memo⟨+⊃(F-1)(F-2)|∘⟩<2. +F ⇡20 diff --git a/Task/Fibonacci-sequence/Uiua/fibonacci-sequence-2.uiua b/Task/Fibonacci-sequence/Uiua/fibonacci-sequence-2.uiua new file mode 100644 index 0000000000..32442a16ea --- /dev/null +++ b/Task/Fibonacci-sequence/Uiua/fibonacci-sequence-2.uiua @@ -0,0 +1,3 @@ +15 # length of final array +[1 1] # starting two values in the sequence +⊙◌⍢(⊂/+⊸↙2|>⧻) # do iteration while less than desired length diff --git a/Task/Fibonacci-sequence/Ursa/fibonacci-sequence.ursa b/Task/Fibonacci-sequence/Ursa/fibonacci-sequence.ursa index 0bef08d178..7e764cb41c 100644 --- a/Task/Fibonacci-sequence/Ursa/fibonacci-sequence.ursa +++ b/Task/Fibonacci-sequence/Ursa/fibonacci-sequence.ursa @@ -1,12 +1,12 @@ def fibIter (int n) - if (< n 2) - return n - end if - decl int fib fibPrev num - set fib (set fibPrev 1) - for (set num 2) (< num n) (inc num) - set fib (+ fib fibPrev) - set fibPrev (- fib fibPrev) - end for - return fib + if (< n 2) + return n + end if + decl int fib fibPrev num + set fib (set fibPrev 1) + for (set num 2) (< num n) (inc num) + set fib (+ fib fibPrev) + set fibPrev (- fib fibPrev) + end for + return fib end diff --git a/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl b/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl index cf6cfb7837..966e06d4b4 100644 --- a/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl +++ b/Task/Fibonacci-sequence/Uxntal/fibonacci-sequence.uxnatl @@ -6,8 +6,8 @@ #1400 &loop - DUP #00 SWP fibonacci print/dec newline - INC GTHk ?&loop + DUP #00 SWP fibonacci print/dec newline + INC GTHk ?&loop POP2 BRK @@ -18,14 +18,14 @@ BRK DUP2 #0001 SUB2 fibonacci STH2 #0002 SUB2 fibonacci STH2r ADD2 - JMP2r + JMP2r @print/dec ( short* -- ) - #000a SWP2 [ LITr ff ] - &get ( -- ) - SWP2k DIV2k MUL2 SUB2 STH - POP OVR2 DIV2 ORAk ?&get - POP2 POP2 - &put ( -- ) - STHr INCk ?{ POP JMP2r } - [ LIT "0 ] ADD .Console/write DEO !&put + #000a SWP2 [ LITr ff ] + &get ( -- ) + SWP2k DIV2k MUL2 SUB2 STH + POP OVR2 DIV2 ORAk ?&get + POP2 POP2 + &put ( -- ) + STHr INCk ?{ POP JMP2r } + [ LIT "0 ] ADD .Console/write DEO !&put diff --git a/Task/Fibonacci-sequence/VAX-Assembly/fibonacci-sequence.vax b/Task/Fibonacci-sequence/VAX-Assembly/fibonacci-sequence.vax index ca0e37bb1b..f3a1a0d0ce 100644 --- a/Task/Fibonacci-sequence/VAX-Assembly/fibonacci-sequence.vax +++ b/Task/Fibonacci-sequence/VAX-Assembly/fibonacci-sequence.vax @@ -1,23 +1,23 @@ - 0000 0000 1 .entry main,0 - 7E 7CFD 0002 2 clro -(sp) ;result buffer - 5E DD 0005 3 pushl sp ;pointer to buffer - 10 DD 0007 4 pushl #16 ;descriptor: len of buffer - 5B 5E D0 0009 5 movl sp, r11 ;-> descriptor + 0000 0000 1 .entry main,0 + 7E 7CFD 0002 2 clro -(sp) ;result buffer + 5E DD 0005 3 pushl sp ;pointer to buffer + 10 DD 0007 4 pushl #16 ;descriptor: len of buffer + 5B 5E D0 0009 5 movl sp, r11 ;-> descriptor 000C 6 - 7E 01 7D 000C 7 movq #1, -(sp) ;init 0,1 + 7E 01 7D 000C 7 movq #1, -(sp) ;init 0,1 000F 8 loop: - 7E 6E 04 AE C1 000F 9 addl3 4(sp), (sp), -(sp) ;next element on stack - 17 1D 0014 10 bvs ret ;vs - overflow set, exit + 7E 6E 04 AE C1 000F 9 addl3 4(sp), (sp), -(sp) ;next element on stack + 17 1D 0014 10 bvs ret ;vs - overflow set, exit 0016 11 - 5B DD 0016 12 pushl r11 ;-> descriptor by ref - 04 AE DF 0018 13 pushal 4(sp) ;-> fib on stack by ref - 00000000'GF 02 FB 001B 14 calls #2, g^ots$cvt_l_ti ;convert integer to string - 5B DD 0022 15 pushl r11 ; - 00000000'GF 01 FB 0024 16 calls #1, g^lib$put_output ;show result - E2 11 002B 17 brb loop + 5B DD 0016 12 pushl r11 ;-> descriptor by ref + 04 AE DF 0018 13 pushal 4(sp) ;-> fib on stack by ref + 00000000'GF 02 FB 001B 14 calls #2, g^ots$cvt_l_ti ;convert integer to string + 5B DD 0022 15 pushl r11 ; + 00000000'GF 01 FB 0024 16 calls #1, g^lib$put_output ;show result + E2 11 002B 17 brb loop 002D 18 ret: - 04 002D 19 ret - 002E 20 .end main + 04 002D 19 ret + 002E 20 .end main $ run fib ... 14930352 diff --git a/Task/Fibonacci-sequence/VBScript/fibonacci-sequence-1.vbs b/Task/Fibonacci-sequence/VBScript/fibonacci-sequence-1.vbs new file mode 100644 index 0000000000..3298d5b395 --- /dev/null +++ b/Task/Fibonacci-sequence/VBScript/fibonacci-sequence-1.vbs @@ -0,0 +1,44 @@ +class generator + dim t1 + dim t2 + dim tn + dim cur_overflow + + Private Sub Class_Initialize + cur_overflow = false + t1 = ccur(0) + t2 = ccur(1) + tn = ccur(t1 + t2) + end sub + + public default property get generated + on error resume next + + generated = ccur(tn) + if err.number <> 0 then + generated = cdbl(tn) + cur_overflow = true + end if + t1 = ccur(t2) + if err.number <> 0 then + t1 = cdbl(t2) + cur_overflow = true + end if + t2 = ccur(tn) + if err.number <> 0 then + t2 = cdbl(tn) + cur_overflow = true + end if + tn = ccur(t1+ t2) + if err.number <> 0 then + tn = cdbl(t1) + cdbl(t2) + cur_overflow = true + end if + on error goto 0 + end property + + public property get overflow + overflow = cur_overflow + end property + +end class diff --git a/Task/Fibonacci-sequence/VBScript/fibonacci-sequence-2.vbs b/Task/Fibonacci-sequence/VBScript/fibonacci-sequence-2.vbs new file mode 100644 index 0000000000..39c1d534d6 --- /dev/null +++ b/Task/Fibonacci-sequence/VBScript/fibonacci-sequence-2.vbs @@ -0,0 +1,10 @@ +dim fib +set fib = new generator +dim i +for i = 1 to 100 + wscript.stdout.write " " & fib + if fib.overflow then + wscript.echo + exit for + end if +next diff --git a/Task/Fibonacci-sequence/Vala/fibonacci-sequence-1.vala b/Task/Fibonacci-sequence/Vala/fibonacci-sequence-1.vala index b218d3eb8f..4ddda4154d 100644 --- a/Task/Fibonacci-sequence/Vala/fibonacci-sequence-1.vala +++ b/Task/Fibonacci-sequence/Vala/fibonacci-sequence-1.vala @@ -1,6 +1,6 @@ int fibRec(int n){ - if (n < 2) - return n; - else - return fibRec(n - 1) + fibRec(n - 2); + if (n < 2) + return n; + else + return fibRec(n - 1) + fibRec(n - 2); } diff --git a/Task/Fibonacci-sequence/Vala/fibonacci-sequence-2.vala b/Task/Fibonacci-sequence/Vala/fibonacci-sequence-2.vala index 6a6a478692..4852a28bf5 100644 --- a/Task/Fibonacci-sequence/Vala/fibonacci-sequence-2.vala +++ b/Task/Fibonacci-sequence/Vala/fibonacci-sequence-2.vala @@ -1,16 +1,16 @@ int fibIter(int n){ - if (n < 2) - return n; - - int last = 0; - int cur = 1; - int next; - - for (int i = 1; i < n; ++i){ - next = last + cur; - last = cur; - cur = next; - } - - return cur; + if (n < 2) + return n; + + int last = 0; + int cur = 1; + int next; + + for (int i = 1; i < n; ++i){ + next = last + cur; + last = cur; + cur = next; + } + + return cur; } diff --git a/Task/Fibonacci-sequence/Vedit-macro-language/fibonacci-sequence-2.vedit b/Task/Fibonacci-sequence/Vedit-macro-language/fibonacci-sequence-2.vedit index ff3421ad9c..9e069467eb 100644 --- a/Task/Fibonacci-sequence/Vedit-macro-language/fibonacci-sequence-2.vedit +++ b/Task/Fibonacci-sequence/Vedit-macro-language/fibonacci-sequence-2.vedit @@ -12,38 +12,38 @@ if (#1 < 2) { IC('1') IN #10 = #1 While (#10 > 1) { - #12 = 0 // carry out - #15 = 1 // column (ones, tens, hundreds...) - Repeat (ALL) { // Sum all columns - Line(-1) // n-1 - Goto_col(#15) - if (At_EOL) { // all digits added - break - } - #11 = Cur_Char - '0' + #12 // digit of (n-1) + carry - Line(-1) // n-2 - Goto_Col(#15) - if (!At_EOL) { // may contain fewer digits than n-1 - #11 += Cur_Char - '0' - } - Goto_Line(3) // sum - EOL - #12 = #11 / 10 // carry out - Ins_Char((#11 % 10) + '0') - #15++ // next column - } - if (#12) { - Goto_Line(3) - EOL - Ins_Char(#12 + '0') // any extra digit from carry + #12 = 0 // carry out + #15 = 1 // column (ones, tens, hundreds...) + Repeat (ALL) { // Sum all columns + Line(-1) // n-1 + Goto_col(#15) + if (At_EOL) { // all digits added + break + } + #11 = Cur_Char - '0' + #12 // digit of (n-1) + carry + Line(-1) // n-2 + Goto_Col(#15) + if (!At_EOL) { // may contain fewer digits than n-1 + #11 += Cur_Char - '0' + } + Goto_Line(3) // sum + EOL + #12 = #11 / 10 // carry out + Ins_Char((#11 % 10) + '0') + #15++ // next column + } + if (#12) { + Goto_Line(3) + EOL + Ins_Char(#12 + '0') // any extra digit from carry } - BOF - Del_Line(1) // Next n - Line(1) EOL - Ins_Newline - #10-- + BOF + Del_Line(1) // Next n + Line(1) EOL + Ins_Newline + #10-- } - Goto_Line(2) // Results on line 2 + Goto_Line(2) // Results on line 2 } // Copy the results to text register 10 in reverse order Reg_Empty(10) diff --git a/Task/Fibonacci-sequence/WDTE/fibonacci-sequence-2.wdte b/Task/Fibonacci-sequence/WDTE/fibonacci-sequence-2.wdte index 008ed82523..9ec27b3d39 100644 --- a/Task/Fibonacci-sequence/WDTE/fibonacci-sequence-2.wdte +++ b/Task/Fibonacci-sequence/WDTE/fibonacci-sequence-2.wdte @@ -2,9 +2,9 @@ let s => import 'stream'; let a => import 'arrays'; let fib n => ( - let reducer p n => [a.at p 1; + (a.at p 0) (a.at p 1)]; - s.range 1 n - -> s.reduce [0; 1] reducer - -> a.at 1 - ; + let reducer p n => [a.at p 1; + (a.at p 0) (a.at p 1)]; + s.range 1 n + -> s.reduce [0; 1] reducer + -> a.at 1 + ; ); diff --git a/Task/Fibonacci-sequence/Whitespace/fibonacci-sequence-3.ws b/Task/Fibonacci-sequence/Whitespace/fibonacci-sequence-3.ws index 09c0ba967e..e69de29bb2 100644 --- a/Task/Fibonacci-sequence/Whitespace/fibonacci-sequence-3.ws +++ b/Task/Fibonacci-sequence/Whitespace/fibonacci-sequence-3.ws @@ -1 +0,0 @@ - diff --git a/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 b/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 index a9714a1f6e..5dbe562c9b 100644 --- a/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 +++ b/Task/Fibonacci-sequence/X86-Assembly/fibonacci-sequence.x86 @@ -1,4 +1,4 @@ -TITLE i hate visual studio 4 (Fibs.asm) +TITLE i hate visual studio 4 (Fibs.asm) ; __ __/--------\ ; >__ \ / | |\ ; \ \___/ @ \ / \__________________ @@ -16,36 +16,36 @@ TITLE i hate visual studio 4 (Fibs.asm) INCLUDE Irvine32.inc .data - BEERCOUNT = 48; - Fibs dd 0, 1, BEERCOUNT DUP(0); + BEERCOUNT = 48; + Fibs dd 0, 1, BEERCOUNT DUP(0); .code main PROC ; I am not responsible for this code. ; They made me write it, against my will. - ;Here be dragons - mov esi, offset Fibs; offset array; ;;were to start (start) - mov ecx, BEERCOUNT; ;;count of items (how many) - mov ebx, 4; ;;size (in number of bytes) - call DumpMem; - - mov ecx, BEERCOUNT; ;//http://www.wolframalpha.com/input/?i=F ib%5B47%5D+%3E+4294967295 - mov esi, offset Fibs - NextPlease:; - mov eax, [esi]; ;//Get me the data from location at ESI - add eax, [esi+4]; ;//add into the eax the data at esi + another double (next mem loc) - mov [esi+8], eax; ;//Move that data into the memory location after the second number - add esi, 4; ;//Update the pointer - loop NextPlease; ;//Thank you sir, may I have another? - - - ;Here be dragons - mov esi, offset Fibs; offset array; ;;were to start (start) - mov ecx, BEERCOUNT; ;;count of items (how many) - mov ebx, 4; ;;size (in number of bytes) - call DumpMem; + ;Here be dragons + mov esi, offset Fibs; offset array; ;;were to start (start) + mov ecx, BEERCOUNT; ;;count of items (how many) + mov ebx, 4; ;;size (in number of bytes) + call DumpMem; - exit ; exit to operating system + mov ecx, BEERCOUNT; ;//http://www.wolframalpha.com/input/?i=F ib%5B47%5D+%3E+4294967295 + mov esi, offset Fibs + NextPlease:; + mov eax, [esi]; ;//Get me the data from location at ESI + add eax, [esi+4]; ;//add into the eax the data at esi + another double (next mem loc) + mov [esi+8], eax; ;//Move that data into the memory location after the second number + add esi, 4; ;//Update the pointer + loop NextPlease; ;//Thank you sir, may I have another? + + + ;Here be dragons + mov esi, offset Fibs; offset array; ;;were to start (start) + mov ecx, BEERCOUNT; ;;count of items (how many) + mov ebx, 4; ;;size (in number of bytes) + call DumpMem; + + exit ; exit to operating system main ENDP END main diff --git a/Task/Fibonacci-sequence/Xojo/fibonacci-sequence.xojo b/Task/Fibonacci-sequence/Xojo/fibonacci-sequence.xojo index dee6ab4829..8e52143529 100644 --- a/Task/Fibonacci-sequence/Xojo/fibonacci-sequence.xojo +++ b/Task/Fibonacci-sequence/Xojo/fibonacci-sequence.xojo @@ -1,7 +1,7 @@ Function fibo(n As Integer) As UInt64 Dim noOne As UInt64 = 1 - Dim noTwo As UInt64 = 1 + Dim noTwo As UInt64 = 1 Dim sum As UInt64 For i As Integer = 3 To n diff --git a/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-1.z80 b/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-1.z80 index f3e4a1a2bc..7318addd2f 100644 --- a/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-1.z80 +++ b/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-1.z80 @@ -2,17 +2,17 @@ ; IN : a = n (n <= 13, otherwise overflows) ; OUT: a = FIB(n) -fib8: cp 2 - ret c ; if n < 2 then done +fib8: cp 2 + ret c ; if n < 2 then done - ld b,a - dec b ; b = n - 1 - ld c,0 ; F0 - ld a,1 ; F1 + ld b,a + dec b ; b = n - 1 + ld c,0 ; F0 + ld a,1 ; F1 -f8_l: ld d,a - add a,c - ld c,d - djnz f8_l +f8_l: ld d,a + add a,c + ld c,d + djnz f8_l - ret + ret diff --git a/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-2.z80 b/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-2.z80 index e46867e503..554543bcff 100644 --- a/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-2.z80 +++ b/Task/Fibonacci-sequence/Z80-Assembly/fibonacci-sequence-2.z80 @@ -2,33 +2,33 @@ ; IN : a = n (n <= 47, otherwise overflows) ; OUT: hlh'l' = FIB(n) -fib32: ld l,a ; lower bytes in the alt set - ld h,0 - exx ; now in regular set - ld hl,0 - cp 2 - ret c ; if n < 2 then done +fib32: ld l,a ; lower bytes in the alt set + ld h,0 + exx ; now in regular set + ld hl,0 + cp 2 + ret c ; if n < 2 then done - dec a ; loopcount = n - 1 - ld bc,0 - exx ; now in alt set - ld bc,0 - ld hl,1 + dec a ; loopcount = n - 1 + ld bc,0 + exx ; now in alt set + ld bc,0 + ld hl,1 -f32_l: ld d,h - ld e,l - add hl,bc - ld b,d - ld c,e - exx ; now in reg set - ld d,h - ld e,l - adc hl,bc - ld b,d - ld c,e - exx ; now in alt set - dec a - jr nz,f32_l +f32_l: ld d,h + ld e,l + add hl,bc + ld b,d + ld c,e + exx ; now in reg set + ld d,h + ld e,l + adc hl,bc + ld b,d + ld c,e + exx ; now in alt set + dec a + jr nz,f32_l - exx ; now in reg set - ret + exx ; now in reg set + ret diff --git a/Task/Fibonacci-word/Ada/fibonacci-word.adb b/Task/Fibonacci-word/Ada/fibonacci-word.adb new file mode 100644 index 0000000000..85eea4237c --- /dev/null +++ b/Task/Fibonacci-word/Ada/fibonacci-word.adb @@ -0,0 +1,56 @@ +with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded, + Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions, + Ada.Long_Float_Text_IO; +use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Strings.Unbounded, + Ada.Strings.Unbounded.Text_IO, Ada.Numerics.Long_Elementary_Functions, + Ada.Long_Float_Text_IO; + +procedure Fibonacci_Words is + + function Entropy (S : Unbounded_String) return Long_Float is + CF : array (Character) of Natural := (others => 0); + Len : constant Natural := Length (S); + H : Long_Float := 0.0; + Ratio : Long_Float; + begin + for I in 1 .. Len loop + CF (Element (S, I)) := CF (Element (S, I)) + 1; + end loop; + for C in Character loop + Ratio := Long_Float (CF (C)) / Long_Float (Len); + if Ratio /= 0.0 then + H := H - Ratio * Log (Ratio, 2.0); + end if; + end loop; + return H; + end Entropy; + + procedure Print_Line (Word : Unbounded_String; Number : Integer) is + begin + Put (Number, 4); + Put (Length (Word), 10); + Put (Entropy (Word), 2, 15, 0); + if Length (Word) < 35 then + Put (" " & Word); + end if; + New_Line; + end Print_Line; + + First, Second, Result : Unbounded_String; + +begin + Set_Col (4); Put ("N"); + Set_Col (9); Put ("Length"); + Set_Col (16); Put ("Entropy"); + Set_Col (35); Put_Line ("Word"); + First := To_Unbounded_String ("1"); + Print_Line (First, 1); + Second := To_Unbounded_String ("0"); + Print_Line (Second, 2); + for N in 3 .. 37 loop + Result := Second & First; + Print_Line (Result, N); + First := Second; + Second := Result; + end loop; +end Fibonacci_Words; diff --git a/Task/Fibonacci-word/Fortran/fibonacci-word.f b/Task/Fibonacci-word/Fortran/fibonacci-word.f new file mode 100644 index 0000000000..fbd309c3a6 --- /dev/null +++ b/Task/Fibonacci-word/Fortran/fibonacci-word.f @@ -0,0 +1,91 @@ +! Fibonacci word +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU gfortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! but not VSI Fortran x86-64 V8.7-001 because that compiler does not accept +! allocatable character variables +! + +program FibonacciWord + +character (len=:), allocatable :: fw1,fw2,fw3 +integer :: i, j, ones, zeros + +fw1 = '1' +fw2 = '0' + +i = 2 + +! Print top line and first 2 lines that aren't within the do-loop +print *, 'N Length Entropy Fibword' +call printLine (1,fw1) +call printLine (2,fw2) + +! Print lines 3 through 37 as requested in the task descrtiption +do j=3,37 + ! + ! Use rotating index i instead of moving long strings around: + ! calculate fw(i) as concatenation of the two other fw's in the correct order. + ! + i = i+1 + if (i .gt.3) i=1 + select case (i) + case (1) + fw1 = fw3 // fw2 + call printLine (j, fw1) + case (2) + fw2 = fw1 // fw3 + call printLine (j, fw2) + case (3) + fw3 = fw2 // fw1 + call printLine (j, fw3) + end select +enddo + +contains + +! ================================================================================================= +! Print 1 output line: N, the Length of the FibWord, its Entropy, and the word unless it's too long +! ================================================================================================= +subroutine printLine (ii, txt) +integer, intent(in) :: ii ! Line number +character (len=*),intent(in) :: txt ! The FibWord to print +integer :: l, i ! Length, loop index + +real (kind=8) :: count_0,count_1,tot ! Count 0's and 1's in txt +real (kind=8) :: Entropy ! Resulting entropy + +count_1 = 0 +count_0 = 0 +l = len(txt) +do i=1,l + if (txt(i:i) .eq. '0') then + count_0 = count_0 + 1_8 + else + count_1 = count_1 + 1_8 + endif +end do +tot = count_1+count_0 + +if (count_1 .eq. 0 .or. count_0 .eq. 0) then ! Calc log(0) is undefined. Use 0 + Entropy =0.0_8 +else + Entropy = - count_1 / tot * log2( count_1 / tot); + Entropy = Entropy - count_0 / tot * log2( count_0 / tot); +endif +if (l .lt. 60) then + write (6,'(i2,X, i8, X, F10.8, X, A )') ii, l, Entropy, txt +else + write (6,'(i2,X, i8, X, F10.8, X, A )') ii, l, Entropy, '(...)' +endif +end subroutine printLine + +! ================================================= +! Helper, Fortran knows LOG and LOG10 but not LOG2. +! Just a trivial base change +! ================================================= +function log2 (x) result (r) +real (kind=8), intent(in) ::x +real (kind=8) ::r +r = log(x) / log(2.) +end function log2 +end program FibonacciWord diff --git a/Task/Fibonacci-word/Julia/fibonacci-word.jl b/Task/Fibonacci-word/Julia/fibonacci-word.jl index e5f7436b3b..2688eecaec 100644 --- a/Task/Fibonacci-word/Julia/fibonacci-word.jl +++ b/Task/Fibonacci-word/Julia/fibonacci-word.jl @@ -1,9 +1,10 @@ -using DataStructures +using DataStructures, Printf + entropy(s::AbstractString) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s))) function fibboword(n::Int64) # Initialize the result - r = Array{String}(n) + r = fill("", n) # First element r[1] = "0" # If more than 2, set the second element @@ -17,10 +18,9 @@ end function testfibbo(n::Integer) fib = fibboword(n) - for i in 1:length(fib) + for i in eachindex(fib) @printf("%3d%9d%12.6f\n", i, length(fib[i]), entropy(fib[i])) end - return 0 end println(" n\tlength\tentropy") diff --git a/Task/Fibonacci-word/Pluto/fibonacci-word.pluto b/Task/Fibonacci-word/Pluto/fibonacci-word.pluto new file mode 100644 index 0000000000..8ff1b51d83 --- /dev/null +++ b/Task/Fibonacci-word/Pluto/fibonacci-word.pluto @@ -0,0 +1,36 @@ +local fmt = require "fmt" + +local function entropy(s) + local m = {} + for i = 1, #s do + local c = s[i] + local d = m[c] + m[c] = (d) ? d + 1 : 1 + end + local hm = 0 + for m:keys() as k do + local c = m[k] + hm += c * math.log(c, 2) + end + local l = #s + return math.log(l, 2) - hm / l +end + +local function fibword(n) + if n < 2 then return tostring(n) end + local a = "1" + local b = "0" + local i = 3 + while i <= n do + local c = b .. a + a, b = b, c + i += 1 + end + return b +end + +fmt.print("%2s %10s %10s %s", "n", "Length", " Entropy ", "Fib word") +for i = 1, 37 do + local fw = fibword(i) + fmt.print("%2d %10s %0.8f %s", i, fmt.int(#fw), entropy(fw), fmt.abridge(fw, 20)) +end diff --git a/Task/Fibonacci-word/Zig/fibonacci-word.zig b/Task/Fibonacci-word/Zig/fibonacci-word.zig new file mode 100644 index 0000000000..7a0b53fdf8 --- /dev/null +++ b/Task/Fibonacci-word/Zig/fibonacci-word.zig @@ -0,0 +1,76 @@ +const std = @import("std"); + +fn findEntropy(fiboword: []const u8) f64 { + // Instead of using a hash map (like std::map in C++), using a flat + // array is extremely fast for mapping bytes to frequency counts. + var frequencies = [_]usize{0} ** 256; + for (fiboword) |c| { + frequencies[c] += 1; + } + + const numlen: f64 = @floatFromInt(fiboword.len); + var infocontent: f64 = 0; + + for (frequencies) |count| { + if (count > 0) { + const freq = @as(f64, @floatFromInt(count)) / numlen; + infocontent += freq * std.math.log2(freq); + } + } + + // Multiply by -1 as in the original code + // Use `+ 0.0` trick to avoid negative zero (-0.0) if infocontent is 0 + return -infocontent + 0.0; +} + +fn printLine(writer: anytype, fiboword: []const u8, n: u32) !void { + const entropy = findEntropy(fiboword); + + // Formatting equivalents: + // {d:<5} -> std::setw(5) << std::left << n + // {d:>12} -> std::setw(12) << std::right << fiboword.size() + // {d:<16.13} -> std::setw(16) << std::setprecision(13) << std::left << entropy + try writer.print("{d:<5}{d:>12} {d:<16.13}\n", .{ n, fiboword.len, entropy }); +} + +pub fn main() !void { + // A GeneralPurposeAllocator works perfectly for the large strings we will generate. + // Fib(37) string length expands to ~24 Megabytes. + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const stdout = std.io.getStdOut().writer(); + + // Print header + try stdout.print("{s:<5}{s:>12} {s:<16}\n", .{ "N", "length", "entropy" }); + + // We start off by allocating the base strings on the heap so they + // can be naturally freed in the memory cycle below without compiler complaints. + var first: []const u8 = try allocator.dupe(u8, "1"); + var n: u32 = 1; + try printLine(stdout, first, n); + + var second: []const u8 = try allocator.dupe(u8, "0"); + n += 1; + try printLine(stdout, second, n); + + while (n < 37) { + // Concatenate `first` and `second` into a new allocated string + const result = try std.mem.concat(allocator, u8, &.{ first, second }); + + // C++ uses `.assign()`, which copies the string's characters. + // Here we can simply free the oldest string, step the slice references + // forward, and save execution time avoiding memory copy overhead! + allocator.free(first); + first = second; + second = result; + + n += 1; + try printLine(stdout, result, n); + } + + // Clean up our remaining two string references + allocator.free(first); + allocator.free(second); +} diff --git a/Task/File-extension-is-in-extensions-list/Ada/file-extension-is-in-extensions-list.adb b/Task/File-extension-is-in-extensions-list/Ada/file-extension-is-in-extensions-list.adb new file mode 100644 index 0000000000..e99e710448 --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/Ada/file-extension-is-in-extensions-list.adb @@ -0,0 +1,42 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Fixed.Equal_Case_Insensitive; use Ada.Strings.Fixed; +with Ada.Strings.Bounded; + +procedure Main is + + package B_String is new Ada.Strings.Bounded.Generic_Bounded_Length (30); + use B_String; + function is_equal (left, right : String) return Boolean renames + Ada.Strings.Fixed.Equal_Case_Insensitive; + + type extension_list is array (Positive range <>) of Bounded_String; + Ext_List : extension_list := + (To_Bounded_String ("zip"), To_Bounded_String ("rar"), + To_Bounded_String ("7z"), To_Bounded_String ("gz"), + To_Bounded_String ("archive"), To_Bounded_String ("A##"), + To_Bounded_String ("tar.bz2")); + type filename_list is array (Positive range <>) of Bounded_String; + fnames : filename_list := + (To_Bounded_String ("MyData.a##"), To_Bounded_String ("MyData.tar.Gz"), + To_Bounded_String ("MyData.gzip"), To_Bounded_String ("MyData..."), + To_Bounded_String ("Mydata"), To_Bounded_String ("MyData_V1.0.tar.bz2"), + To_Bounded_String ("MyData_v1.0.bz2")); + Valid_Extension : Boolean; +begin + for name of fnames loop + Valid_Extension := False; + Put (To_String (name)); + for ext of Ext_List loop + declare + S : String := "." & To_String (ext); + T : String := Tail (Source => To_String (name), Count => S'Length); + begin + if is_equal (S, T) then + Valid_Extension := True; + end if; + end; + end loop; + Set_Col (22); + Put_Line (": " & Valid_Extension'Image); + end loop; +end Main; diff --git a/Task/File-extension-is-in-extensions-list/Crystal/file-extension-is-in-extensions-list.cr b/Task/File-extension-is-in-extensions-list/Crystal/file-extension-is-in-extensions-list.cr new file mode 100644 index 0000000000..2dfb39c8f8 --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/Crystal/file-extension-is-in-extensions-list.cr @@ -0,0 +1,11 @@ +extensions = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"] + +filenames = ["MyData.a##", "MyData.tar.Gz", "MyData.gzip", "MyData.7z.backup", + "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2"] + +width = filenames.max_of &.size + +filenames.each do |fn| + printf "%-#{width}s %s\n", fn, + extensions.map(&.downcase.ensure_prefix ".").any? {|ext| fn.downcase.ends_with? ext } +end diff --git a/Task/File-extension-is-in-extensions-list/Pluto/file-extension-is-in-extensions-list.pluto b/Task/File-extension-is-in-extensions-list/Pluto/file-extension-is-in-extensions-list.pluto new file mode 100644 index 0000000000..243caeff8f --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/Pluto/file-extension-is-in-extensions-list.pluto @@ -0,0 +1,22 @@ +local fmt = require "fmt" + +local exts = {"zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"} +local uc_exts = exts:mapped(|e| -> "." .. e:upper()) + +local tests = { + "MyData.a##", "MyData.tar.Gz", "MyData.gzip" , "MyData.7z.backup", + "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2" +} + +for tests as test do + local uc_test = test:upper() + local has_ext = false + for i, ext in uc_exts do + has_ext = uc_test:endswith(ext) + if has_ext then + fmt.print("%-20s %s (extension: %s)", test, has_ext, exts[i]) + break + end + end + if !has_ext then fmt.print("%-20s %-5s", test, has_ext) end +end diff --git a/Task/File-extension-is-in-extensions-list/R/file-extension-is-in-extensions-list.r b/Task/File-extension-is-in-extensions-list/R/file-extension-is-in-extensions-list.r new file mode 100644 index 0000000000..667b8bc1f8 --- /dev/null +++ b/Task/File-extension-is-in-extensions-list/R/file-extension-is-in-extensions-list.r @@ -0,0 +1,20 @@ +test_files <- c("MyData.a##", + "MyData.tar.Gz", + "MyData.gzip", + "MyData.7z.backup", + "MyData...", + "MyData", + "MyData_v1.0.tar.bz2", + "MyData_v1.0.bz2") + +extensions <- c("zip", "rar", "7z", "gz", "archive", "a##", "tar.bz2") + +has_ext <- function(file, exts){ + file_lower <- tolower(file) + for(ext in exts){ + if(endsWith(file_lower, paste0(".", ext))) return(TRUE) + } + return(FALSE) +} + +sapply(test_files, function(file) has_ext(file, extensions)) diff --git a/Task/File-input-output/Ada/file-input-output-1.adb b/Task/File-input-output/Ada/file-input-output-1.adb new file mode 100644 index 0000000000..626f1b2565 --- /dev/null +++ b/Task/File-input-output/Ada/file-input-output-1.adb @@ -0,0 +1,30 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Read_And_Write_File_Line_By_Line is + Input, Output : File_Type; +begin + Open (File => Input, + Mode => In_File, + Name => "input.txt"); + Create (File => Output, + Mode => Out_File, + Name => "output.txt"); + loop + declare + Line : String := Get_Line (Input); + begin + -- You can process the contents of Line here. + Put_Line (Output, Line); + end; + end loop; + Close (Input); + Close (Output); +exception + when End_Error => + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; +end Read_And_Write_File_Line_By_Line; diff --git a/Task/File-input-output/Ada/file-input-output-2.adb b/Task/File-input-output/Ada/file-input-output-2.adb new file mode 100644 index 0000000000..1c60a9b0e9 --- /dev/null +++ b/Task/File-input-output/Ada/file-input-output-2.adb @@ -0,0 +1,51 @@ +with Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO; + +procedure Read_And_Write_File_Line_By_Line is + Read_From : constant String := "input.txt"; + Write_To : constant String := "output.txt"; + + Input, Output : File_Type; +begin + begin + Open (File => Input, + Mode => In_File, + Name => Read_From); + exception + when others => + Put_Line (Standard_Error, + "Can not open the file '" & Read_From & "'. Does it exist?"); + Set_Exit_Status (Failure); + return; + end; + + begin + Create (File => Output, + Mode => Out_File, + Name => Write_To); + exception + when others => + Put_Line (Standard_Error, + "Can not create a file named '" & Write_To & "'."); + Set_Exit_Status (Failure); + return; + end; + + loop + declare + Line : String := Get_Line (Input); + begin + -- You can process the contents of Line here. + Put_Line (Output, Line); + end; + end loop; + Close (Input); + Close (Output); +exception + when End_Error => + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; +end Read_And_Write_File_Line_By_Line; diff --git a/Task/File-input-output/Ada/file-input-output-3.adb b/Task/File-input-output/Ada/file-input-output-3.adb new file mode 100644 index 0000000000..2ad4edd6a8 --- /dev/null +++ b/Task/File-input-output/Ada/file-input-output-3.adb @@ -0,0 +1,26 @@ +with Ada.Sequential_IO; + +procedure Read_And_Write_File_Character_By_Character is + package Char_IO is new Ada.Sequential_IO (Character); + use Char_IO; + + Input, Output : File_Type; + Buffer : Character; +begin + Open (File => Input, Mode => In_File, Name => "input.txt"); + Create (File => Output, Mode => Out_File, Name => "output.txt"); + loop + Read (File => Input, Item => Buffer); + Write (File => Output, Item => Buffer); + end loop; + Close (Input); + Close (Output); +exception + when End_Error => + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; +end Read_And_Write_File_Character_By_Character; diff --git a/Task/File-input-output/Ada/file-input-output-4.adb b/Task/File-input-output/Ada/file-input-output-4.adb new file mode 100644 index 0000000000..61ad4cf3ea --- /dev/null +++ b/Task/File-input-output/Ada/file-input-output-4.adb @@ -0,0 +1,24 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams; + +procedure Using_Text_Streams is + Input, Output : File_Type; + Buffer : Character; +begin + Open (File => Input, Mode => In_File, Name => "input.txt"); + Create (File => Output, Mode => Out_File, Name => "output.txt"); + loop + Buffer := Character'Input (Stream (Input)); + Character'Write (Stream (Output), Buffer); + end loop; + Close (Input); + Close (Output); +exception + when End_Error => + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; +end Using_Text_Streams; diff --git a/Task/File-input-output/ArkScript/file-input-output.ark b/Task/File-input-output/ArkScript/file-input-output.ark new file mode 100644 index 0000000000..6d6018c3b4 --- /dev/null +++ b/Task/File-input-output/ArkScript/file-input-output.ark @@ -0,0 +1,4 @@ +(import std.IO) + +(let file_content (io:readFile "input.txt")) +(io:writeFile "output.txt" file_content) diff --git a/Task/File-input-output/Batch-File/file-input-output-4.bat b/Task/File-input-output/Batch-File/file-input-output-4.bat new file mode 100644 index 0000000000..3a984b30d3 --- /dev/null +++ b/Task/File-input-output/Batch-File/file-input-output-4.bat @@ -0,0 +1 @@ +echo(!buffer:~0,-2!>output.txt diff --git a/Task/File-input-output/Batch-File/file-input-output-5.bat b/Task/File-input-output/Batch-File/file-input-output-5.bat new file mode 100644 index 0000000000..99d248176d --- /dev/null +++ b/Task/File-input-output/Batch-File/file-input-output-5.bat @@ -0,0 +1 @@ + Originally from ACUCOBOL-GT +CALL "C$COPY" USING "input.txt", "output.txt", 0 diff --git a/Task/File-input-output/COBOL/file-input-output-4.cob b/Task/File-input-output/COBOL/file-input-output-4.cob new file mode 100644 index 0000000000..453cebf36a --- /dev/null +++ b/Task/File-input-output/COBOL/file-input-output-4.cob @@ -0,0 +1,2 @@ +*> Originally from Micro Focus COBOL +CALL "CBL_COPY_FILE" USING "input.txt", "output.txt" diff --git a/Task/File-input-output/Emacs-Lisp/file-input-output.el b/Task/File-input-output/Emacs-Lisp/file-input-output.el new file mode 100644 index 0000000000..99bdf9e557 --- /dev/null +++ b/Task/File-input-output/Emacs-Lisp/file-input-output.el @@ -0,0 +1,6 @@ +(defvar input (with-temp-buffer + (insert-file-contents "input.txt") + (buffer-string))) + +(with-temp-file "output.txt" + (insert input)) diff --git a/Task/File-input-output/Euphoria/file-input-output-1.eu b/Task/File-input-output/Euphoria/file-input-output-1.eu new file mode 100644 index 0000000000..d036b75847 --- /dev/null +++ b/Task/File-input-output/Euphoria/file-input-output-1.eu @@ -0,0 +1,2 @@ +include std/io.e +write_lines("output.txt", read_lines("input.txt")) diff --git a/Task/File-input-output/Euphoria/file-input-output-2.eu b/Task/File-input-output/Euphoria/file-input-output-2.eu new file mode 100644 index 0000000000..fcd89422f0 --- /dev/null +++ b/Task/File-input-output/Euphoria/file-input-output-2.eu @@ -0,0 +1,16 @@ +integer in,out +object line + +in = open("input.txt","r") +out = open("output.txt","w") + +while 1 do + line = gets(in) + if atom(line) then -- EOF reached + exit + end if + puts(out,line) +end while + +close(out) +close(in) diff --git a/Task/File-input-output/PowerShell/file-input-output-1.ps1 b/Task/File-input-output/PowerShell/file-input-output-1.ps1 new file mode 100644 index 0000000000..f8323369c2 --- /dev/null +++ b/Task/File-input-output/PowerShell/file-input-output-1.ps1 @@ -0,0 +1 @@ +Get-Content $PWD\input.txt | Out-File $PWD\output.txt diff --git a/Task/File-input-output/PowerShell/file-input-output-2.ps1 b/Task/File-input-output/PowerShell/file-input-output-2.ps1 new file mode 100644 index 0000000000..81543f814b --- /dev/null +++ b/Task/File-input-output/PowerShell/file-input-output-2.ps1 @@ -0,0 +1 @@ +Get-Content $PWD\input.txt | Set-Content $PWD\output.txt diff --git a/Task/File-input-output/Rebol/file-input-output.rebol b/Task/File-input-output/Rebol/file-input-output.rebol new file mode 100644 index 0000000000..f35e436d3e --- /dev/null +++ b/Task/File-input-output/Rebol/file-input-output.rebol @@ -0,0 +1,7 @@ +write %output.txt read %input.txt + +; No line translations: +write/binary %output.txt read/binary %input.txt + +; Save a web page: +write %output.html read http://example.com diff --git a/Task/File-input-output/Rye/file-input-output.rye b/Task/File-input-output/Rye/file-input-output.rye new file mode 100644 index 0000000000..280d663f85 --- /dev/null +++ b/Task/File-input-output/Rye/file-input-output.rye @@ -0,0 +1,7 @@ +str: Read %output.txt +Write %input.txt str +Close Open %output.txt +Close Open %input.txt + +cc os +cp %output.txt %input.txt diff --git a/Task/File-input-output/VBScript/file-input-output.vbs b/Task/File-input-output/VBScript/file-input-output.vbs new file mode 100644 index 0000000000..762549235c --- /dev/null +++ b/Task/File-input-output/VBScript/file-input-output.vbs @@ -0,0 +1 @@ +CreateObject("Scripting.FileSystemObject").OpenTextFile("output.txt",2,-2).Write CreateObject("Scripting.FileSystemObject").OpenTextFile("input.txt", 1, -2).ReadAll diff --git a/Task/File-modification-time/Ada/file-modification-time.adb b/Task/File-modification-time/Ada/file-modification-time.adb new file mode 100644 index 0000000000..3aab748a55 --- /dev/null +++ b/Task/File-modification-time/Ada/file-modification-time.adb @@ -0,0 +1,8 @@ +with Ada.Directories; use Ada.Directories; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; + +procedure File_Time_Test is +begin + Put_Line (Image (Modification_Time ("file_time_test.adb"))); +end File_Time_Test; diff --git a/Task/File-modification-time/Crystal/file-modification-time.cr b/Task/File-modification-time/Crystal/file-modification-time.cr new file mode 100644 index 0000000000..8a529ac063 --- /dev/null +++ b/Task/File-modification-time/Crystal/file-modification-time.cr @@ -0,0 +1,6 @@ +# get +mtime = File.info(filename).modification_time + +# set +File.touch(filename) # default: now; or +File.touch(filename, time) diff --git a/Task/File-modification-time/Emacs-Lisp/file-modification-time.el b/Task/File-modification-time/Emacs-Lisp/file-modification-time.el new file mode 100644 index 0000000000..7ab9cd122b --- /dev/null +++ b/Task/File-modification-time/Emacs-Lisp/file-modification-time.el @@ -0,0 +1,5 @@ +(nth 5 (file-attributes "input.txt")) ;; mod date+time + +(set-file-times "input.txt") ;; to current-time +(set-file-times "input.txt" + (encode-time 0 0 0 1 1 2014)) ;; to given date+time diff --git a/Task/File-modification-time/Pluto/file-modification-time.pluto b/Task/File-modification-time/Pluto/file-modification-time.pluto new file mode 100644 index 0000000000..b6e5fb51d8 --- /dev/null +++ b/Task/File-modification-time/Pluto/file-modification-time.pluto @@ -0,0 +1,10 @@ +-- Get previous write time. +local t = io.writetime("input.txt") +print(os.date("%c", t)) + +-- Add an hour. +io.writetime("input.txt", t + 3600) + +-- Retrieve the new time. +t = io.writetime("input.txt") +print(os.date("%c", t)) diff --git a/Task/File-modification-time/PowerShell/file-modification-time.ps1 b/Task/File-modification-time/PowerShell/file-modification-time.ps1 new file mode 100644 index 0000000000..57db0b0526 --- /dev/null +++ b/Task/File-modification-time/PowerShell/file-modification-time.ps1 @@ -0,0 +1,8 @@ +$modificationTime = (Get-ChildItem file.txt).LastWriteTime +Set-ItemProperty file.txt LastWriteTime (Get-Date) + +$LastReadTime = (Get-ChildItem file.txt).LastAccessTime +Set-ItemProperty file.txt LastAccessTime(Get-Date) + +$CreationTime = (Get-ChildItem file.txt).CreationTime +Set-ItemProperty file.txt CreationTime(Get-Date) diff --git a/Task/File-modification-time/VBScript/file-modification-time.vbs b/Task/File-modification-time/VBScript/file-modification-time.vbs new file mode 100644 index 0000000000..ea77a468e3 --- /dev/null +++ b/Task/File-modification-time/VBScript/file-modification-time.vbs @@ -0,0 +1 @@ +WScript.Echo CreateObject("Scripting.FileSystemObject").GetFile("input.txt").DateLastModified diff --git a/Task/File-size-distribution/Ada/file-size-distribution.adb b/Task/File-size-distribution/Ada/file-size-distribution.adb new file mode 100644 index 0000000000..208f6bf839 --- /dev/null +++ b/Task/File-size-distribution/Ada/file-size-distribution.adb @@ -0,0 +1,59 @@ +with Ada.Numerics.Elementary_Functions; +with Ada.Directories; use Ada.Directories; +with Ada.Strings.Fixed; use Ada.Strings; +with Ada.Command_Line; use Ada.Command_Line; +with Ada.Text_IO; use Ada.Text_IO; + +with Dir_Iterators.Recursive; + +procedure File_Size_Distribution is + + type Exponent_Type is range 0 .. 18; + type File_Count is range 0 .. Long_Integer'Last; + Counts : array (Exponent_Type) of File_Count := (others => 0); + Non_Zero_Index : Exponent_Type := 0; + Directory_Name : constant String := (if Argument_Count = 0 + then "." + else Argument (1)); + Directory_Walker : Dir_Iterators.Recursive.Recursive_Dir_Walk + := Dir_Iterators.Recursive.Walk (Directory_Name); +begin + if not Exists (Directory_Name) or else Kind (Directory_Name) /= Directory then + Put_Line ("Directory does not exist"); + return; + end if; + + for Directory_Entry of Directory_Walker loop + declare + use Ada.Numerics.Elementary_Functions; + Size_Of_File : File_Size; + Exponent : Exponent_Type; + begin + if Kind (Directory_Entry) = Ordinary_File then + Size_Of_File := Size (Directory_Entry); + if Size_Of_File = 0 then + Counts (0) := Counts (0) + 1; + else + Exponent := Exponent_Type (Float'Ceiling (Log (Float (Size_Of_File), + Base => 10.0))); + Counts (Exponent) := Counts (Exponent) + 1; + end if; + end if; + end; + end loop; + + for I in reverse Counts'Range loop + if Counts (I) /= 0 then + Non_Zero_Index := I; + exit; + end if; + end loop; + + for I in Counts'First .. Non_Zero_Index loop + Put ("Less than 10**"); + Put (Fixed.Trim (Exponent_Type'Image (I), Side => Left)); + Put (": "); + Put (File_Count'Image (Counts (I))); + New_Line; + end loop; +end File_Size_Distribution; diff --git a/Task/File-size-distribution/Euphoria/file-size-distribution.eu b/Task/File-size-distribution/Euphoria/file-size-distribution.eu new file mode 100644 index 0000000000..438431e9e1 --- /dev/null +++ b/Task/File-size-distribution/Euphoria/file-size-distribution.eu @@ -0,0 +1,44 @@ +include std/console.e +include std/filesys.e + +constant UNITS = {"B","KB","MB","GB","TB"} + +sequence files_by_category = {0,0,0,0,0} + +function category(atom bytes) -- Returns file size category + for i = 4 to 1 by -1 do + atom a = power(1024,i) + if bytes >= a then + return i + 1 + end if + end for + return 1 +end function + +procedure categorize(sequence rootdir) + object x = dir(rootdir & "\\*.*") -- Get DIR information of all files + if sequence(x) then -- Exclude forbidden DIRs + for i = 1 to length(x) do -- Loop through DIR content + sequence s = x[i] + if find('d',s[D_ATTRIBUTES]) then -- Skip SubDIRs + if not (equal(s[D_NAME],".") or equal(s[D_NAME],"..")) then + categorize(rootdir & "\\" & s[D_NAME]) + end if + else + integer cat = category(s[D_SIZE]) -- Categorize file size + files_by_category[cat] += 1 + end if + end for + end if +end procedure + +sequence rootdir = prompt_string("Folder name: ") +puts(1, "Cat\tNumber\n") +if length(rootdir)>0 then + categorize(rootdir) + for i = 1 to 5 do + printf(1, "%s\t%d\n", {UNITS[i], files_by_category[i]}) + end for +end if + +maybe_any_key() diff --git a/Task/File-size/Ada/file-size.adb b/Task/File-size/Ada/file-size.adb new file mode 100644 index 0000000000..f845ee30ce --- /dev/null +++ b/Task/File-size/Ada/file-size.adb @@ -0,0 +1,8 @@ +with Ada.Directories; use Ada.Directories; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_File_Size is +begin + Put_Line (File_Size'Image (Size ("input.txt")) & " bytes"); + Put_Line (File_Size'Image (Size ("/input.txt")) & " bytes"); +end Test_File_Size; diff --git a/Task/File-size/Batch-File/file-size-1.bat b/Task/File-size/Batch-File/file-size-1.bat new file mode 100644 index 0000000000..58ab437c16 --- /dev/null +++ b/Task/File-size/Batch-File/file-size-1.bat @@ -0,0 +1,12 @@ +@echo off +call :filesize input.txt +echo Size of file input.txt: %res% +call :filesize \input.txt +echo Size of file \input.txt: %res% +goto:eof + +:filesize +2>nul ( +for %%i in ("%~1") do set /a res=%%~zi +) || set /a res=-1 +goto:eof diff --git a/Task/File-size/Batch-File/file-size-2.bat b/Task/File-size/Batch-File/file-size-2.bat new file mode 100644 index 0000000000..f957ea7a1f --- /dev/null +++ b/Task/File-size/Batch-File/file-size-2.bat @@ -0,0 +1,2 @@ +@echo off +dir /a-d input.txt \input.txt diff --git a/Task/File-size/COBOL/file-size.cob b/Task/File-size/COBOL/file-size.cob new file mode 100644 index 0000000000..0d9249c031 --- /dev/null +++ b/Task/File-size/COBOL/file-size.cob @@ -0,0 +1,42 @@ + identification division. + program-id. FileInfo. + + data division. + working-storage section. + 01 file-name pic x(256). + 01 file-size-edited pic zzz,zzz,zzz. + 01 file-details. + 05 file-size pic x(8) comp-x. + 05 file-date. + 10 file-day pic x comp-x. + 10 file-month pic x comp-x. + 10 file-year pic xx comp-x. + 05 file-time. + 10 file-hour pic x comp-x. + 10 file-minute pic x comp-x. + 10 file-second pic x comp-x. + 10 file-hundredths pic x comp-x. + + procedure division. + main. + move "input.txt" to file-name + perform file-info + + move "\input.txt" to file-name + perform file-info + + stop run + . + + file-info. + call "CBL_CHECK_FILE_EXIST" + using file-name, file-details + returning return-code + if return-code = 0 + move file-size to file-size-edited + display function trim(file-name) " " + function trim(file-size-edited) " Bytes" + else + display function trim(file-name) " not found!" + end-if + . diff --git a/Task/File-size/Crystal/file-size.cr b/Task/File-size/Crystal/file-size.cr new file mode 100644 index 0000000000..66a68e792d --- /dev/null +++ b/Task/File-size/Crystal/file-size.cr @@ -0,0 +1,2 @@ +size1 = File.size("input.txt") +size2 = File.size("/input.txt") diff --git a/Task/File-size/Emacs-Lisp/file-size.el b/Task/File-size/Emacs-Lisp/file-size.el new file mode 100644 index 0000000000..07cd024bd0 --- /dev/null +++ b/Task/File-size/Emacs-Lisp/file-size.el @@ -0,0 +1,3 @@ +(message "sizes are %s and %s" + (nth 7 (file-attributes "input.txt")) + (nth 7 (file-attributes "/input.txt"))) diff --git a/Task/File-size/Euphoria/file-size.eu b/Task/File-size/Euphoria/file-size.eu new file mode 100644 index 0000000000..307dfa9741 --- /dev/null +++ b/Task/File-size/Euphoria/file-size.eu @@ -0,0 +1,24 @@ +include file.e + +function file_size(sequence file_name) + object x + x = dir(file_name) + if sequence(x) and length(x) = 1 then + return x[1][D_SIZE] + else + return -1 -- the file does not exist + end if +end function + +procedure test(sequence file_name) + integer size + size = file_size(file_name) + if size < 0 then + printf(1,"%s file does not exist.\n",{file_name}) + else + printf(1,"%s size is %d.\n",{file_name,size}) + end if +end procedure + +test("input.txt") -- in the current working directory +test("/input.txt") -- in the file system root diff --git a/Task/File-size/Pluto/file-size.pluto b/Task/File-size/Pluto/file-size.pluto new file mode 100644 index 0000000000..e759923adc --- /dev/null +++ b/Task/File-size/Pluto/file-size.pluto @@ -0,0 +1,3 @@ +for {"input.txt", "/input.txt"} as filename do + print(io.filesize(filename)) +end diff --git a/Task/File-size/PowerShell/file-size.ps1 b/Task/File-size/PowerShell/file-size.ps1 new file mode 100644 index 0000000000..9d99df383c --- /dev/null +++ b/Task/File-size/PowerShell/file-size.ps1 @@ -0,0 +1,2 @@ +Get-ChildItem input.txt | Select-Object Name,Length +Get-ChildItem \input.txt | Select-Object Name,Length diff --git a/Task/File-size/Rebol/file-size.rebol b/Task/File-size/Rebol/file-size.rebol new file mode 100644 index 0000000000..68a4673f47 --- /dev/null +++ b/Task/File-size/Rebol/file-size.rebol @@ -0,0 +1,4 @@ +size? %info.txt +size? %/info.txt +size? ftp://username:password@ftp.site.com/info.txt +size? http://rosettacode.org diff --git a/Task/File-size/Rye/file-size.rye b/Task/File-size/Rye/file-size.rye new file mode 100644 index 0000000000..783e1ffb26 --- /dev/null +++ b/Task/File-size/Rye/file-size.rye @@ -0,0 +1,2 @@ +cc os +file-info? %input.txt |print diff --git a/Task/File-size/VBScript/file-size.vbs b/Task/File-size/VBScript/file-size.vbs new file mode 100644 index 0000000000..288b9e4a29 --- /dev/null +++ b/Task/File-size/VBScript/file-size.vbs @@ -0,0 +1,4 @@ +With CreateObject("Scripting.FileSystemObject") + WScript.Echo .GetFile("input.txt").Size + WScript.Echo .GetFile("\input.txt").Size +End With diff --git a/Task/Filter/Ada/filter-1.adb b/Task/Filter/Ada/filter-1.adb new file mode 100644 index 0000000000..3c72c5c6c0 --- /dev/null +++ b/Task/Filter/Ada/filter-1.adb @@ -0,0 +1,32 @@ +with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Array_Selection is + type Array_Type is array (Positive range <>) of Integer; + Null_Array : Array_Type(1..0); + + function Evens (Item : Array_Type) return Array_Type is + begin + if Item'Length > 0 then + if Item(Item'First) mod 2 = 0 then + return Item(Item'First) & Evens(Item((Item'First + 1)..Item'Last)); + else + return Evens(Item((Item'First + 1)..Item'Last)); + end if; + else + return Null_Array; + end if; + end Evens; + + procedure Print(Item : Array_Type) is + begin + for I in Item'range loop + Put(Item(I)); + New_Line; + end loop; + end Print; + + Foo : Array_Type := (1,2,3,4,5,6,7,8,9,10); +begin + Print(Evens(Foo)); +end Array_Selection; diff --git a/Task/Filter/Ada/filter-2.adb b/Task/Filter/Ada/filter-2.adb new file mode 100644 index 0000000000..b031a1ddd2 --- /dev/null +++ b/Task/Filter/Ada/filter-2.adb @@ -0,0 +1,28 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Array_Selection is + type Array_Type is array (Positive range <>) of Integer; + + function Evens (Item : Array_Type) return Array_Type is + Result : Array_Type (1..Item'Length); + Index : Positive := 1; + begin + for I in Item'Range loop + if Item (I) mod 2 = 0 then + Result (Index) := Item (I); + Index := Index + 1; + end if; + end loop; + return Result (1..Index - 1); + end Evens; + + procedure Put (Item : Array_Type) is + begin + for I in Item'range loop + Put (Integer'Image (Item (I))); + end loop; + end Put; +begin + Put (Evens ((1,2,3,4,5,6,7,8,9,10))); + New_Line; +end Array_Selection; diff --git a/Task/Filter/ArkScript/filter.ark b/Task/Filter/ArkScript/filter.ark new file mode 100644 index 0000000000..a3fc2017a6 --- /dev/null +++ b/Task/Filter/ArkScript/filter.ark @@ -0,0 +1,6 @@ +(import std.List) +(import std.Math :even) + +(let nums (list:iota 0 10)) +(let even-numbers (list:filter nums even)) +(print even-numbers) diff --git a/Task/Filter/BQN/filter-3.bqn b/Task/Filter/BQN/filter-3.bqn new file mode 100644 index 0000000000..c08536b5ad --- /dev/null +++ b/Task/Filter/BQN/filter-3.bqn @@ -0,0 +1 @@ +2⊸|⊸/ 1‿2‿3‿4‿5 diff --git a/Task/Filter/BQN/filter-4.bqn b/Task/Filter/BQN/filter-4.bqn new file mode 100644 index 0000000000..31fdec5fa0 --- /dev/null +++ b/Task/Filter/BQN/filter-4.bqn @@ -0,0 +1 @@ +⟨ 1 3 5 ⟩ diff --git a/Task/Filter/Ballerina/filter.ballerina b/Task/Filter/Ballerina/filter.ballerina new file mode 100644 index 0000000000..907cfb2f64 --- /dev/null +++ b/Task/Filter/Ballerina/filter.ballerina @@ -0,0 +1,6 @@ +import ballerina/io; + +public function main() { + int[] a = from int i in 1...10 select i*i; + io:println(a.filter(n => n % 2 == 0)); +} diff --git a/Task/Filter/Crystal/filter.cr b/Task/Filter/Crystal/filter.cr new file mode 100644 index 0000000000..1c781bfcba --- /dev/null +++ b/Task/Filter/Crystal/filter.cr @@ -0,0 +1,17 @@ +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +puts "1. arr = #{arr}" + +evens = arr.select {|element| element.even? } +# short form: +evens = arr.select &.even? + +puts " select evens: #{evens}" +puts " arr = #{arr}" +puts +puts "2. arr = #{arr}" + +arr.select! &.even? + +puts " select evens (destructively)" +puts " arr = #{arr}" diff --git a/Task/Filter/EMal/filter.emal b/Task/Filter/EMal/filter.emal index b82a0b0f18..2c3dd534bd 100644 --- a/Task/Filter/EMal/filter.emal +++ b/Task/Filter/EMal/filter.emal @@ -1 +1 @@ -writeLine(range(1, 11).filter( list.filter(fn(x) { x % 2 == 0 }) + |> echo +} diff --git a/Task/Filter/OPL/filter-1.opl b/Task/Filter/OPL/filter-1.opl new file mode 100644 index 0000000000..f631db0826 --- /dev/null +++ b/Task/Filter/OPL/filter-1.opl @@ -0,0 +1,25 @@ +PROC main: + LOCAL array1%(10),array2%(10),i% + RANDOMIZE MINUTE*SECOND + i%=1 + WHILE i%<>11 + array1%(i%)=100+INT(RND*900) + i%=i%+1 + ENDWH + i%=1 + WHILE i%<>11 + IF array1%(i%)=array1%(i%)/2*2 + array2%(i%)=array1%(i%) + ELSE + array2%(i%)=0 + ENDIF + i%=i%+1 + ENDWH + PRINT "Array 1: Array 2:" + i%=1 + WHILE i%<>11 + PRINT array1%(i%)," ",array2%(i%) + i%=i%+1 + ENDWH + GET +ENDP diff --git a/Task/Filter/OPL/filter-2.opl b/Task/Filter/OPL/filter-2.opl new file mode 100644 index 0000000000..69998dff46 --- /dev/null +++ b/Task/Filter/OPL/filter-2.opl @@ -0,0 +1,23 @@ +PROC main: + LOCAL array%(10),i% + RANDOMIZE MINUTE*SECOND + PRINT "Before:", + i%=1 + WHILE i%<>11 + array%(i%)=100+INT(RND*900) + PRINT array%(i%), + i%=i%+1 + ENDWH + PRINT + PRINT "After: ", + i%=1 + WHILE i%<>11 + IF array%(i%)<>array%(i%)/2*2 + array%(i%)=0 + PRINT " ", + ENDIF + PRINT array%(i%), + i%=i%+1 + ENDWH + GET +ENDP diff --git a/Task/Filter/PowerShell/filter.ps1 b/Task/Filter/PowerShell/filter.ps1 new file mode 100644 index 0000000000..dbb7f1fe2e --- /dev/null +++ b/Task/Filter/PowerShell/filter.ps1 @@ -0,0 +1,2 @@ +$array = -15..37 +$array | Where-Object { $_ % 2 -eq 0 } diff --git a/Task/Filter/Rebol/filter.rebol b/Task/Filter/Rebol/filter.rebol new file mode 100644 index 0000000000..46c7b6f1ac --- /dev/null +++ b/Task/Filter/Rebol/filter.rebol @@ -0,0 +1,7 @@ +data: [] evens: [] +repeat i 20 [append data i] ; Build and load array. + +foreach element data [if even? element [append evens element]] +probe evens +remove-each element evens [zero? element % 10] +probe evens diff --git a/Task/Filter/Rye/filter.rye b/Task/Filter/Rye/filter.rye new file mode 100644 index 0000000000..d5303f4c88 --- /dev/null +++ b/Task/Filter/Rye/filter.rye @@ -0,0 +1,2 @@ +newarr: filter { 1 2 3 4 5 6 7 } { .is-even } +print newarr diff --git a/Task/Filter/VBScript/filter.vbs b/Task/Filter/VBScript/filter.vbs new file mode 100644 index 0000000000..68981a6f51 --- /dev/null +++ b/Task/Filter/VBScript/filter.vbs @@ -0,0 +1,47 @@ +test_arr_1 = Array(1,2,3,4,5,6,7,8,9,10) +test_arr_2 = Array(1,2,3,4,5,6,7,8,9,10) + +WScript.StdOut.Write "Scenario 1: Create a new array" +WScript.StdOut.WriteLine +WScript.StdOut.Write "Input: " & Join(test_arr_1,",") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Output: " & filter_create(test_arr_1) +WScript.StdOut.WriteBlankLines(2) + +WScript.StdOut.Write "Scenario 2: Destructive approach" +WScript.StdOut.WriteLine +WScript.StdOut.Write "Input: " & Join(test_arr_2,",") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Output: " & filter_destruct(test_arr_2) +WScript.StdOut.WriteBlankLines(2) + +Function filter_create(arr) + ReDim arr_new(0) + For i = 0 To UBound(arr) + If arr(i) Mod 2 = 0 Then + If arr_new(0) = "" Then + arr_new(0) = arr(i) + Else + ReDim Preserve arr_new(UBound(arr_new)+1) + arr_new(UBound(arr_new)) = arr(i) + End If + End If + Next + filter_create = Join(arr_new,",") +End Function + +Function filter_destruct(arr) + count = 0 + For i = 0 To UBound(arr) + If arr(i) Mod 2 <> 0 Then + count = count + 1 + For j = i To UBound(arr) + If j + 1 <= UBound(arr) Then + arr(j) = arr(j+1) + End If + Next + End If + Next + ReDim Preserve arr(UBound(arr)-count) + filter_destruct = Join(arr,",") +End Function diff --git a/Task/Find-Chess960-starting-position-identifier/Fortran/find-chess960-starting-position-identifier.f b/Task/Find-Chess960-starting-position-identifier/Fortran/find-chess960-starting-position-identifier.f new file mode 100644 index 0000000000..e1c49c3441 --- /dev/null +++ b/Task/Find-Chess960-starting-position-identifier/Fortran/find-chess960-starting-position-identifier.f @@ -0,0 +1,102 @@ +! Find Chess960 starting position identifier +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! U.B., February 2026 +!========================================================================================= +program Chess960 +implicit none + +! The four starting positions mentioned in the task description. +! +character (len=8), dimension(4), parameter :: SamplePos = ['QNRBBNKR', 'RNBQKBNR', 'RQNBBKRN', 'RNQBBKRN'] + +integer :: i, id ! Loop index, result SP-ID + +do i=1,4 + id = SpId (SamplePos(i)) + write (*,'("Position ", A, " has Chess960 SP-ID = ", i0)') SamplePos (i), id +end do + +contains + +! ==================================================== +! Calculate Start Position Id for a given position pos. +! The code strictly follows the algorithm described in +! the Task description, Steps 1...3 +! No effort is taken to catch invalid input positions. +! ==================================================== +pure function SpId (pos) result (id) + +character (len=*), intent(in) :: pos ! The input position +integer :: id ! The result + +integer :: pN(2), nn, ii, p ! Positions of the 2 knights, knight number, loop index, position +integer :: N, Q, D, L ! Intermediate digits Knight, Queen, Dark and Light Knight + +! Initialise knight table using reshape to make gfortran happy. Intel ifx accepts it without the reshape. +integer, dimension(2, 10),parameter :: knight_table = reshape((/1,2, & ! 1-based positions of the Knights + 1,3, & + 1,4, & + 1,5, & + 2,3, & + 2,4, & + 2,5, & + 3,4, & + 3,5, & + 4,5/), (/2,10/)) +id = 0 +! 1. Ignoring the Queen and Bishops, find the positions of the Knights +! -------------------------------------------------------------------- +nn = 0 +p = 0 ! All positions and indices here and below are 1-based ! +do ii=1, 8 + if (pos(ii:ii) .eq. 'Q' .or. pos(ii:ii) .eq. 'B') then + cycle ! we ignore the Queen and the Bishops and go to the next position + endif + p = p + 1 ! Valid: this is a position in pos if there is no Q and no B + if (pos(ii:ii) .eq. 'N') then + nn = nn + 1 + pN(nn) = p + end if +end do +! Estimate digit N from positions of the 2 knights, using the table +do ii=1, 10 + if (pN(1) .eq. knight_table (1,ii) .and. pN(2) .eq. knight_table (2,ii)) then + N = ii-1 ! N is 0...9 not 1...10 + exit + end if +end do + +! 2. Still ignoring the Bishops, find the position of the Queen in the remaining 6 spaces +! ---------------------------------------------------------------------------------------- +p = 0 +do ii=1,8 + if (pos(ii:ii) .eq. 'B') then + ! we ignore all Bishops: + cycle + endif + p = p + 1 + if (pos(ii:ii) .eq. 'Q') then + Q = p-1 ! Q is 0...6 + end if +end do + +! 3. Finally, find the positions of the two bishops within their respective sets of four like-colored squares +! ----------------------------------------------------------------------------------------------------------- +do ii=1,7,2 + ! Dark: + if (pos(ii:ii) .eq. 'B') then + D = ii/2 ! gives 0,1,2,3 + endif + ! Light: + if (pos(ii+1:ii+1) .eq. 'B') then + L = ii/2 ! also gives 0,1,2,3 + endif +end do + +id = 4*(4*(6*N+Q)+D)+L +end function SpId + +end program Chess960 diff --git a/Task/Find-Chess960-starting-position-identifier/V-(Vlang)/find-chess960-starting-position-identifier.v b/Task/Find-Chess960-starting-position-identifier/V-(Vlang)/find-chess960-starting-position-identifier.v new file mode 100644 index 0000000000..d5bff6c36c --- /dev/null +++ b/Task/Find-Chess960-starting-position-identifier/V-(Vlang)/find-chess960-starting-position-identifier.v @@ -0,0 +1,98 @@ +struct ChessPosition { + mut: + q []int + k []int + b []int + n []int + r []int + err string +} + +fn spid(s string) int { + mut pos := ChessPosition{} + mut idx, mut n2, mut n1, mut n := 1, 0, 0, 0 + mut light_bishop, mut dark_bishop, mut knights_index, mut q_val := 0, 0, 0, 0 + for i := 0; i < s.len; i++ { + ch := s[i] + match ch { + `Q` { pos.q << idx } + `K` { pos.k << idx } + `B` { pos.b << idx } + `N` { pos.n << idx } + `R` { pos.r << idx } + else { + println("Illegal piece: ${ch.ascii_str()}") + return 0 + } + } + idx++ + } + if pos.k.len != 1 { pos.err += "There must be exactly one King. " } + if pos.q.len != 1 { pos.err += "There must be exactly one Queen. " } + if pos.b.len != 2 { pos.err += "There must be exactly two Bishops. " } + if pos.n.len != 2 { pos.err += "There must be exactly two Knights. " } + if pos.r.len != 2 { pos.err += "There must be exactly two Rooks. " } + if pos.k.len == 1 && pos.r.len == 2 { + if pos.k[0] < pos.r[0] || pos.k[0] > pos.r[1] { + pos.err += "King must be between the Rooks." + } + } + if pos.b.len == 2 { + if (pos.b[0] - pos.b[1]) % 2 == 0 { + pos.err += "Bishops must be on opposite colors." + } + } + if pos.err != "" { + println(pos.err) + return 0 + } + for i_knight := 0; i_knight < 2; i_knight++ { + orig_n := pos.n[i_knight] + n = orig_n + if orig_n > pos.q[0] { n -= 1 } + for j_bishop := 0; j_bishop < 2; j_bishop++ { + if orig_n > pos.b[j_bishop] { n -= 1 } + } + pos.n[i_knight] = n + } + pos.n[0] -= 1 + pos.n[1] -= 1 + if pos.n[0] > pos.n[1] { pos.n[0], pos.n[1] = pos.n[1], pos.n[0] } + n1 = 0 + n2 = 1 + knights_index = -1 + for idx_pair := 0; idx_pair < 10; idx_pair++ { + if n1 == pos.n[0] && n2 == pos.n[1] { + knights_index = idx_pair + break + } + n2++ + if n2 > 4 { + n1++ + n2 = n1 + 1 + } + } + if knights_index == -1 { + println("Error: knights pair not found") + return 0 + } + q_val = pos.q[0] - 1 + for i_bishop := 0; i_bishop < 2; i_bishop++ { + if q_val >= pos.b[i_bishop] - 1 { + q_val -= 1 + } + } + for i_bishop2 := 0; i_bishop2 < 2; i_bishop2++ { + b_val := pos.b[i_bishop2] - 1 + if b_val & 1 == 1 { light_bishop = b_val / 2 } + else { dark_bishop = b_val / 2 } + } + return 96 * knights_index + 16 * q_val + 4 * dark_bishop + light_bishop +} +fn main() { + positions := ["QNRBBNKR", "RNBQKBNR", "RQNBBKRN", "RNQBBKRN"] + for i := 0; i < positions.len; i++ { + pos := positions[i] + println("$pos -> ${spid(pos)}") + } +} diff --git a/Task/Find-common-directory-path/Ada/find-common-directory-path.adb b/Task/Find-common-directory-path/Ada/find-common-directory-path.adb new file mode 100644 index 0000000000..2e5e27c7c6 --- /dev/null +++ b/Task/Find-common-directory-path/Ada/find-common-directory-path.adb @@ -0,0 +1,37 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Common_Path is + function "rem" (A, B : String) return String is + Slash : Integer := A'First; -- At the last slash seen in A + At_A : Integer := A'first; + At_B : Integer := B'first; + begin + loop + if At_A > A'Last then + if At_B > B'Last or else B (At_B) = '/' then + return A; + else + return A (A'First..Slash - 1); + end if; + elsif At_B > B'Last then + if A (At_A) = '/' then -- A cannot be shorter than B here + return B; + else + return A (A'First..Slash - 1); + end if; + elsif A (At_A) /= B (At_B) then + return A (A'First..Slash - 1); + elsif A (At_A) = '/' then + Slash := At_A; + end if; + At_A := At_A + 1; + At_B := At_B + 1; + end loop; + end "rem"; +begin + Put_Line + ( "/home/user1/tmp/coverage/test" rem + "/home/user1/tmp/covert/operator" rem + "/home/user1/tmp/coven/members" + ); +end Test_Common_Path; diff --git a/Task/Find-common-directory-path/Fortran/find-common-directory-path.f b/Task/Find-common-directory-path/Fortran/find-common-directory-path.f new file mode 100644 index 0000000000..79061527c6 --- /dev/null +++ b/Task/Find-common-directory-path/Fortran/find-common-directory-path.f @@ -0,0 +1,147 @@ +! Find common directory path +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.7-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! U.B., January 2026 +!========================================================================================= +program commonDirPath + +implicit none + +! The longest path string in these little examples has a length 31 characters. +! The test data listed in the task description has three path strings +integer, parameter :: longestP = 31, nStrings=3 + +! We handle the test data set listed in the task description, and some extra to cover more special cases +character (len=longestP) , dimension(nStrings) :: names +integer :: i + +! expect /home/user1/tmp +! This is the test case in the task description + !.........1.........2.........3. ! gfortran does not accept differnt lengths here +names = ["/home/user1/tmp/coverage/test/ ", & + "/home/user1/tmp/covert/operator", & + "/home/user1/tmp/coven/members " ] + +! Print the used names, the expected common directory path, and the actual result +write (*, '(" Input: ", A, 2(/, " ",A))') (names(i),i=1,nStrings) +write (*, '(" expect: /home/user1/tmp")') +call printCommonDirPath (names, longestP, nStrings) + +! expect /home/user2 +! Special case: 1st path ends with '/', second does not. But both describe the same path + !.........1.........2.........3. ! gfortran does not accept differnt lengths here +names = ['/home/user2/ ', & + '/home/user2 ', & + '/home/user2/bubu '] +write (*, '(" Input: ", A, 2(/, " ",A))') (names(i),i=1,nStrings) +write (*, '(" expect: /home/user2")') +call printCommonDirPath (names, longestP, 3) + +! expect / +! Special case: 1st character is the '/', all following text is diffent in all 3 names. + !.........1.........2.........3. ! gfortran does not accept differnt lengths here +names = ['/ ', & + '/hugo/ ', & + '/etc '] +write (*, '(" Input: ", A, 2(/, " ",A))') (names(i),i=1,nStrings) +write (*, '(" expect: /")' ) +call printCommonDirPath (names, longestP, 3) + +! expect nothing +! SPecial case: no common path + !.........1.........2.........3. ! gfortran does not accept differnt lengths here +names = ['/ ', & + 'hugo/ ', & + '/etc '] +write (*, '(" Input: ", A, 2(/, " ",A))') (names(i),i=1,nStrings) +print *, 'expect: (No common path)' +call printCommonDirPath (names, longestP, 3) + + +contains + +! ===================================================================== +! Find common directory path in the of path names and print the result +! ===================================================================== +subroutine printCommonDirPath (argNames, argLen, argN) + +integer , intent(in) :: argLen, argN ! Path length, and array size +character (len=argLen), dimension(argN), intent(inout) :: argNames +integer :: commonLength, ii + +commonLength = calcCommonLength(argNames, argLen, argN) + +if (commonLength .gt. 0) then + write (*,'(" Result: ", A,/)') names(1)(:commonLength) +else + write (*, '(" Result: (No common Path)",/)') +endif + +end subroutine printCommonDirPath + + +! ===================================================================================== +! Find common directory path in the of path names and return the length of the result. +! ====================================================================================== +function calcCommonLength (argNames, argLen, argN) result (cl) + +integer , intent(in) :: argLen, argN +character (len=argLen), dimension(argN), intent(inout) :: argNames +integer :: cl + +integer, dimension(argN) :: lengths +integer :: shortestLength +character, parameter :: direcDelim = '/' +integer :: ii, jj, kk + +! Find lengths of all path strings, memoize shortest +shortestLength = longestP ! initialize largest possible value to find minimum +do ii=1, argN + lengths(ii) = len_trim (argNames(ii)) + if (lengths(ii) .gt.1 .and. argNames(ii)(lengths(ii):lengths(ii)) .ne. direcDelim) then + ! This path is not only '/' but the string does not end with '/': Pretend it does. + lengths(ii) = lengths(ii) + 1 + argNames(ii)(lengths(ii):lengths(ii)) = direcDelim + end if + shortestLength = min (shortestLength, lengths(ii)) +end do + +outer: do + kk = 1 ! to be set 0 upon first mismatch + inner: do ii=2, argN ! compare 2nd ff with 1st string + if (argNames (ii)(:shortestLength) .ne. argNames(1)(:shortestLength)) then ! Mismatch found + ! Not all paths up to the commonm minimum length are equal. + kk = 0 + ! Special case: shortest path has only 1 character, and at least 1 other path is different + if (shortestLength .eq. 1) then + cl = 0 + exit outer + end if + + ! Standard case: + ! Go back to ne next earlier delimiter and compare the paths up to there + do jj=shortestLength-1, 1, -1 + if (argNames(1)(jj:jj) .eq. direcDelim) then + shortestLength = jj + exit inner ! but continue cycling outer + endif + end do + ! here if no further delimiter found left of the previuos one. + if (shortestLength .lt. 1 ) then + cl = 0 + exit outer + end if + exit inner ! Quit comparing strings when 1st mismatch found + endif ! Mismatch found + enddo inner ! ENd loop comparing strings + + if (kk .eq. 1) then ! No mismatch found: finish. + cl = max(shortestLength-1, 1) ! forget about the last '/' unless its the only common character. + exit outer ! All done. + end if +enddo outer + +end function calcCommonLength +end program commonDirPath diff --git a/Task/Find-common-directory-path/PowerShell/find-common-directory-path-1.ps1 b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-1.ps1 new file mode 100644 index 0000000000..0d1490b290 --- /dev/null +++ b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-1.ps1 @@ -0,0 +1,27 @@ +<# +.Synopsis + Finds the deepest common directory path of files passed through the pipeline. +.Parameter File + PowerShell file object. +#> +function Get-CommonPath { +[CmdletBinding()] + param ( + [Parameter(Mandatory=$true, ValueFromPipeline=$true)] + [System.IO.FileInfo] $File + ) + process { + # Get the current file's path list + $PathList = $File.FullName -split "\$([IO.Path]::DirectorySeparatorChar)" + # Get the most common path list + if ($CommonPathList) { + $CommonPathList = (Compare-Object -ReferenceObject $CommonPathList -DifferenceObject $PathList -IncludeEqual ` + -ExcludeDifferent -SyncWindow 0).InputObject + } else { + $CommonPathList = $PathList + } + } + end { + $CommonPathList -join [IO.Path]::DirectorySeparatorChar + } +} diff --git a/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.ps1 b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.ps1 new file mode 100644 index 0000000000..8aa11bb8de --- /dev/null +++ b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.ps1 @@ -0,0 +1,2 @@ +"C:\a\b\c\d\e","C:\a\b\e\f","C:\a\b\c\d\x" | Get-CommonPath +C:\a\b diff --git a/Task/Find-common-directory-path/VBScript/find-common-directory-path.vbs b/Task/Find-common-directory-path/VBScript/find-common-directory-path.vbs new file mode 100644 index 0000000000..853cc31e65 --- /dev/null +++ b/Task/Find-common-directory-path/VBScript/find-common-directory-path.vbs @@ -0,0 +1,31 @@ +' Read the list of paths (newline-separated) into an array... +strPaths = Split(WScript.StdIn.ReadAll, vbCrLf) + +' Split each path by the delimiter (/)... +For i = 0 To UBound(strPaths) + strPaths(i) = Split(strPaths(i), "/") +Next + +With CreateObject("Scripting.FileSystemObject") + + ' Test each path segment... + For j = 0 To UBound(strPaths(0)) + + ' Test each successive path against the first... + For i = 1 To UBound(strPaths) + If strPaths(0)(j) <> strPaths(i)(j) Then Exit For + Next + + ' If we didn't make it all the way through, exit the block... + If i <= UBound(strPaths) Then Exit For + + ' Make sure this path exists... + If Not .FolderExists(strPath & strPaths(0)(j) & "/") Then Exit For + strPath = strPath & strPaths(0)(j) & "/" + + Next + +End With + +' Remove the final "/"... +WScript.Echo Left(strPath, Len(strPath) - 1) diff --git a/Task/Find-duplicate-files/Ada/find-duplicate-files.adb b/Task/Find-duplicate-files/Ada/find-duplicate-files.adb new file mode 100644 index 0000000000..7507b46ea2 --- /dev/null +++ b/Task/Find-duplicate-files/Ada/find-duplicate-files.adb @@ -0,0 +1,128 @@ +with Ada.Command_Line; +with Ada.Containers; +with Ada.Containers.Ordered_Maps; +with Ada.Containers.Indefinite_Vectors; +with Ada.Directories; +with Ada.Streams.Stream_IO; +with Ada.Text_IO; + +with GNAT.MD5; + +procedure Find_Duplicates is + + Root_Dir : constant String := Ada.Command_Line.Argument (1); + Size_Limit : constant Ada.Directories.File_Size := + Ada.Directories.File_Size'Value (Ada.Command_Line.Argument (2)); + Pattern : constant String := "*"; + Filter : constant Ada.Directories.Filter_Type := + ( + Ada.Directories.Directory => True, + Ada.Directories.Ordinary_File => True, + others => False + ); + + type File_Data is + record + Hash : GNAT.MD5.Message_Digest; + Size : Ada.Directories.File_Size; + end record; + + type File_Name is new String; + + function File_Order (Left, Right : File_Data) return Boolean is + (Ada.Directories."<" (Right.Size, Left.Size)); + + package Dir_Vectors is new Ada.Containers.Indefinite_Vectors + (Index_Type => Positive, Element_Type => File_Name); + package Dir_Maps is new Ada.Containers.Ordered_Maps + (Key_Type => File_Data, Element_Type => Dir_Vectors.Vector, + "<" => File_Order, "=" => Dir_Vectors."="); + + function File_Hash (Name : String) return GNAT.MD5.Message_Digest is + File : Ada.Streams.Stream_IO.File_Type; + Context : GNAT.MD5.Context := GNAT.MD5.Initial_Context; + Items : Ada.Streams.Stream_Element_Array + (1 .. 4096); + Last : Ada.Streams.Stream_Element_Offset := 0; + begin + Ada.Streams.Stream_IO.Open (File, Ada.Streams.Stream_IO.In_File, Name); + + while not Ada.Streams.Stream_IO.End_Of_File (File) loop + Ada.Streams.Stream_IO.Read (File, Items, Last); + + if Ada.Streams."<" (Last, Items'Last) then + GNAT.MD5.Update (Context, Items (Items'First .. Last)); + else + GNAT.MD5.Update (Context, Items); + end if; + end loop; + + return GNAT.MD5.Digest (Context); + end; + + Dir_Map : Dir_Maps.Map := Dir_Maps.Empty_Map; + + procedure Insert (Name : String) is + Hash : constant GNAT.MD5.Message_Digest := File_Hash (Name); + Size : constant Ada.Directories.File_Size := Ada.Directories.Size (Name); + Data : constant File_Data := (Hash, Size); + Pos : Dir_Maps.Cursor; + Ins : Boolean; + procedure Append_Name (K : File_Data; V : in out Dir_Vectors.Vector) is + begin + V.Append (File_Name (Name)); + end Append_Name; + begin + Dir_Map.Insert (Data, Dir_Vectors.Empty_Vector, Pos, Ins); + -- We can update whether we inserted a new element or not. + Dir_Map.Update_Element (Pos, Append_Name'Access); + end Insert; + + procedure Walk (Dir_Ent : Ada.Directories.Directory_Entry_Type) is + Name : constant String := Ada.Directories.Full_Name (Dir_Ent); + SName : constant String := Ada.Directories.Simple_Name (Dir_Ent); + Size : Ada.Directories.File_Size; + begin + if SName = "." or else SName = ".." then + return; + end if; + + case Ada.Directories.Kind (Dir_Ent) is + when Ada.Directories.Ordinary_File => + Size := Ada.Directories.Size (Name); + if Ada.Directories.">=" (Size, Size_Limit) then + Insert (Name); + end if; + when Ada.Directories.Directory => + Ada.Directories.Search + (Name, Pattern, Filter, Walk'Access); + when others => raise Constraint_Error; + end case; + end Walk; + + procedure Show_Duplicates is + Count : Ada.Containers.Count_Type; + K : File_Data; + Dv : Dir_Vectors.Vector; + begin + for Pos in Dir_Map.Iterate loop + Dv := Dir_Map.Constant_Reference (Pos); + Count := Dv.Length; + + if Ada.Containers.">"(Count, 1) then + K := Dir_Maps.Key (Pos); + Ada.Text_IO.Put_Line + ("Found " & Count'Image & " files matching Size => " + & K.Size'Image & ", MD5 => " & K.Hash); + + for E of Dv loop + Ada.Text_IO.Put_Line (String (E)); + end loop; + end if; + end loop; + end Show_Duplicates; +begin + Ada.Directories.Search + (Root_Dir, Pattern, Filter, Walk'Access); + Show_Duplicates; +end Find_Duplicates; diff --git a/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-1.adb b/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-1.adb new file mode 100644 index 0000000000..e361c91392 --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-1.adb @@ -0,0 +1,34 @@ +-- triangle.ads +generic + type Dimension is private; + Zero, Two: Dimension; + with function "*"(Left, Right: in Dimension) return Dimension is <>; + with function "/"(Left, Right: in Dimension) return Dimension is <>; + with function "+"(Left, Right: in Dimension) return Dimension is <>; + with function "-"(Left, Right: in Dimension) return Dimension is <>; + with function ">"(Left, Right: in Dimension) return Boolean is <>; + with function "="(Left, Right: in Dimension) return Boolean is <>; + with function Image(D: in Dimension) return String is <>; +package Triangle is + + type Point is record + X: Dimension; + Y: Dimension; + end record; + + type Triangle_T is record + A,B,C: Point; + end record; + + function Area(T: in Triangle_T) return Dimension; + + function IsPointInTriangle(P: Point; T: Triangle_T) return Boolean; + + function Image(P: Point) return String is + ("(X="&Image(P.X)&", Y="&Image(P.Y)&")") + with Inline; + + function Image(T: Triangle_T) return String is + ("(A="&Image(T.A)&", B="&Image(T.B)&", C="&Image(T.C)&")") + with Inline; +end; diff --git a/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-2.adb b/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-2.adb new file mode 100644 index 0000000000..3addab4319 --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-2.adb @@ -0,0 +1,21 @@ +-- triangle.adb + +package body Triangle is + function Area(T: in Triangle_T) return Dimension + is + tmp: Dimension; + begin + tmp:=((T.B.X*T.C.Y-T.C.X*T.B.Y)-(T.A.X*T.C.Y-T.C.X*T.A.Y)+(T.A.X*T.B.Y-T.B.X*T.A.Y))/Two; + if tmp>Zero then + return tmp; + else + return Zero-tmp; + end if; + end Area; + + function IsPointInTriangle(P: Point; T: Triangle_T) return Boolean + is + begin + return Area(T)=Area((T.A,T.B,P))+Area((T.A,P,T.C))+Area((P,T.B,T.C)); + end IsPointInTriangle; +end; diff --git a/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-3.adb b/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-3.adb new file mode 100644 index 0000000000..38c8b2fa4f --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Ada/find-if-a-point-is-within-a-triangle-3.adb @@ -0,0 +1,16 @@ +-- test_triangle.adb +with Ada.Text_IO; +use Ada.Text_IO; +with Triangle; + +procedure test_triangle +is + package affine_tri is new Triangle(Dimension=>Integer, Zero=>0,Two=>2, Image=>Integer'Image); + use affine_tri; + tri1: Triangle_T:=((1,0),(2,0),(0,2)); + tri2: Triangle_T:=((-1,0),(-1,-1),(2,2)); + origin: Point:=(0,0); +begin + Put_Line("IsPointInTriangle("&Image(origin)&", "&Image(tri1)&") yields "&IsPointInTriangle(origin,tri1)'Image); + Put_Line("IsPointInTriangle("&Image(origin)&", "&Image(tri2)&") yields "&IsPointInTriangle(origin,tri2)'Image); +end test_triangle; diff --git a/Task/Find-if-a-point-is-within-a-triangle/Crystal/find-if-a-point-is-within-a-triangle.cr b/Task/Find-if-a-point-is-within-a-triangle/Crystal/find-if-a-point-is-within-a-triangle.cr new file mode 100644 index 0000000000..86a3e51be3 --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Crystal/find-if-a-point-is-within-a-triangle.cr @@ -0,0 +1,13 @@ +def point_inside_triangle (p, a, b, c) + side_of_line(p, a, b) == side_of_line(p, b, c) == side_of_line(p, c, a) +end + +def side_of_line (p, a, b) + ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])).sign +end + +p! point_inside_triangle({0, 0}, {1.5, 2.4}, {5.1, -3.1}, {-3.8, 1.2}), + point_inside_triangle({0, 1}, {1.5, 2.4}, {5.1, -3.1}, {-3.8, 1.2}), + point_inside_triangle({3, 1}, {1.5, 2.4}, {5.1, -3.1}, {-3.8, 1.2}), + point_inside_triangle({5.414286, 14.349206}, {0.1, 0.111111}, {12.5, 33.333333}, {25.0, 11.111111}), + point_inside_triangle({5.414286, 14.349206}, {0.1, 0.111111}, {12.5, 33.333333}, {-12.5, 16.666667}) diff --git a/Task/Find-if-a-point-is-within-a-triangle/Pluto/find-if-a-point-is-within-a-triangle.pluto b/Task/Find-if-a-point-is-within-a-triangle/Pluto/find-if-a-point-is-within-a-triangle.pluto new file mode 100644 index 0000000000..3fb987fc64 --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Pluto/find-if-a-point-is-within-a-triangle.pluto @@ -0,0 +1,84 @@ +local fmt = require "fmt" + +$define EPS = 0.001 +$define EPS_SQUARE = EPS * EPS + +local function side(x1, y1, x2, y2, x, y) + return (y2 - y1) * (x - x1) + (-x2 + x1) * (y - y1) +end + +local function naive_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) + local check_side1 = side(x1, y1, x2, y2, x, y) >= 0 + local check_side2 = side(x2, y2, x3, y3, x, y) >= 0 + local check_side3 = side(x3, y3, x1, y1, x, y) >= 0 + return check_side1 and check_side2 and check_side3 +end + +local function point_in_triangle_bounding_box(x1, y1, x2, y2, x3, y3, x, y) + local xmin = math.min(x1, x2, x3) - EPS + local xmax = math.max(x1, x2, x3) + EPS + local ymin = math.min(y1, y2, y3) - EPS + local ymax = math.max(y1, y2, y3) + EPS + return !(x < xmin or xmax < x or y < ymin or ymax < y) +end + +local function distance_square_point_to_segment(x1, y1, x2, y2, x, y) + local p1_p2_square_length = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + local dot_product = ((x - x1) * (x2 - x1) + (y - y1) * (y2 - y1)) / p1_p2_square_length + if dot_product < 0 then + return (x - x1) * (x - x1) + (y - y1) * (y - y1) + elseif dot_product <= 1 then + local p_p1_square_length = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y) + return p_p1_square_length - dot_product * dot_product * p1_p2_square_length + else + return (x - x2) * (x - x2) + (y - y2) * (y - y2) + end +end + +local function accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) + if !point_in_triangle_bounding_box(x1, y1, x2, y2, x3, y3, x, y) then return false end + if naive_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) then return true end + if distance_square_point_to_segment(x1, y1, x2, y2, x, y) <= EPS_SQUARE then return true end + if distance_square_point_to_segment(x2, y2, x3, y3, x, y) <= EPS_SQUARE then return true end + if distance_square_point_to_segment(x3, y3, x1, y1, x, y) <= EPS_SQUARE then return true end + return false +end + +local pts = { {0, 0}, {0, 1}, {3, 1} } +local tri = { {3/2, 12/5}, {51/10, -31/10}, {-19/5, 1.2} } +fmt.print($"Triangle is {fmt.swrite(tri)}") +local x1 = tri[1][1] +local y1 = tri[1][2] +local x2 = tri[2][1] +local y2 = tri[2][2] +local x3 = tri[3][1] +local y3 = tri[3][2] + +for pts as pt do + local x, y = pt[1], pt[2] + local within = accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) + fmt.print($"{fmt.swrite(pt)} is within triangle ? {within}") +end +print() + +tri = { {1/10, 1/9}, {100/8, 100/3}, {100/4, 100/9} } +fmt.print($"Triangle is {fmt.swrite(tri)}") +x1 = tri[1][1] +y1 = tri[1][2] +x2 = tri[2][1] +y2 = tri[2][2] +x3 = tri[3][1] +y3 = tri[3][2] +local x = x1 + (3/7) * (x2 - x1) +local y = y1 + (3/7) * (y2 - y1) +local pt = {x, y} +local within = accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) +fmt.print($"{fmt.swrite(pt)} is within triangle ? {within}") +print() + +tri = { {1/10, 1/9}, {100/8, 100/3}, {-100/8, 100/6} } +fmt.print($"Triangle is {fmt.swrite(tri)}") +x3 = tri[3][1] +y3 = tri[3][2] +within = accurate_point_in_triangle(x1, y1, x2, y2, x3, y3, x, y) +fmt.print($"{fmt.swrite(pt)} is within triangle ? {within}") diff --git a/Task/Find-if-a-point-is-within-a-triangle/Tcl/find-if-a-point-is-within-a-triangle.tcl b/Task/Find-if-a-point-is-within-a-triangle/Tcl/find-if-a-point-is-within-a-triangle.tcl new file mode 100644 index 0000000000..7751eb12ef --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Tcl/find-if-a-point-is-within-a-triangle.tcl @@ -0,0 +1,117 @@ +#!/usr/bin/env tclsh + +proc point {x {y ""}} { + + if { [llength $x] eq 2 } { + set y [lindex $x 1] + set x [lindex $x 0] + } + + try { + set p [list [expr {double($x)}] [expr {double($y)}] ] + } on error {err} { + puts stderr "invalid point $x $y" + puts stderr "error: \t $::errorInfo" + exit 1 + } + return $p +} + +proc triangle {a b c} { + + try { + set A [point [lindex $a 0] [lindex $a 1]] + set B [point [lindex $b 0] [lindex $b 1]] + set C [point [lindex $c 0] [lindex $c 1]] + } on error { err } { + puts stderr "invalid triangle $a $b $c" + puts stderr "error: \t $::errorInfo" + exit 1 + } + + return [list $A $B $C] +} + + +proc in_bounding_box {t p} { + + lassign $t A B C + + lassign $A x1 y1 + lassign $B x2 y2 + lassign $C x3 y3 + lassign $p x y + + set xmin [expr { min( $x1, $x2, $x3) } ] + set xmax [expr { max( $x1, $x2, $x3) } ] + + set ymin [expr { min( $y1, $y2 ,$y3) } ] + set ymax [expr { max( $y1, $y2 ,$y3) } ] + + set P1 [expr { $x < $xmin}] + set P2 [expr { $x > $xmax}] + set P3 [expr { $y < $ymin}] + set P4 [expr { $y > $xmax}] + + set in_box [expr { !($P1 || $P2 || $P3 || $P4) }] + + return $in_box +} + + +proc in_triangle { t p } { + + lassign $t A B C + + lassign $A x1 y1 + lassign $B x2 y2 + lassign $C x3 y3 + lassign $p x y + + # inner proc + proc side { p1 p2 p } { + + lassign $p1 x1 y1 + lassign $p2 x2 y2 + lassign $p x y + + set res [expr { (($y2 - $y1) * ($x - $x1)) + + (($x1 - $x2) * ($y - $y1)) }] + return $res + } + + set side1 [side $A $B $p] + set side2 [side $B $C $p] + set side3 [side $C $A $p] + + set X [expr {$side1 >= 0}] + set Y [expr {$side2 >= 0}] + set Z [expr {$side3 >= 0}] + + return [expr {$X && $Y && $Z}] +} + +# processing starts here + +set tp1 [point 1.5 2.4 ] +set tp2 [point 5.1 -3.1 ] +set tp3 [point -3.8 1.2 ] +set t [triangle $tp1 $tp2 $tp3] + +set p1 [point 0.0 0.0] +set p2 [point 0.0 1.0] +set p3 [point 3.0 1.0] + +foreach p [list $p1 $p2 $p3] { + set bb [in_bounding_box $t $p] + + if {$bb} { + set it [in_triangle $t $p] + + if {$it} { + puts stdout "point ($p) is inside of triangle ($t)" + } else { + puts stdout "point ($p) is not inside of triangle ($t)" + } + } +} diff --git a/Task/Find-limit-of-recursion/Ada/find-limit-of-recursion.adb b/Task/Find-limit-of-recursion/Ada/find-limit-of-recursion.adb new file mode 100644 index 0000000000..e8e1c4609e --- /dev/null +++ b/Task/Find-limit-of-recursion/Ada/find-limit-of-recursion.adb @@ -0,0 +1,13 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Recursion_Depth is + function Recursion (Depth : Positive) return Positive is + begin + return Recursion (Depth + 1); + exception + when Storage_Error => + return Depth; + end Recursion; +begin + Put_Line ("Recursion depth on this system is" & Integer'Image (Recursion (1))); +end Test_Recursion_Depth; diff --git a/Task/Find-limit-of-recursion/AutoIt/find-limit-of-recursion.au3 b/Task/Find-limit-of-recursion/AutoIt/find-limit-of-recursion.au3 new file mode 100644 index 0000000000..bee56a0e4b --- /dev/null +++ b/Task/Find-limit-of-recursion/AutoIt/find-limit-of-recursion.au3 @@ -0,0 +1,7 @@ +;AutoIt Version: 3.2.10.0 +$depth=0 +recurse($depth) +Func recurse($depth) + ConsoleWrite($depth&@CRLF) + Return recurse($depth+1) +EndFunc diff --git a/Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-1.cob b/Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-1.cob new file mode 100644 index 0000000000..a619c8d846 --- /dev/null +++ b/Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-1.cob @@ -0,0 +1,50 @@ +identification division. +program-id. recurse. +data division. +working-storage section. +01 depth-counter pic 9(3). +01 install-address usage is procedure-pointer. +01 install-flag pic x comp-x value 0. +01 status-code pic x(2) comp-5. +01 ind pic s9(9) comp-5. + + +linkage section. +01 err-msg pic x(325). + +procedure division. +100-main. + + set install-address to entry "300-err". + + call "CBL_ERROR_PROC" using install-flag + install-address + returning status-code. + + if status-code not = 0 + display "ERROR INSTALLING ERROR PROC" + stop run + end-if + + move 0 to depth-counter. + display 'Mung until no good.'. + perform 200-mung. + display 'No good.'. + stop run. + +200-mung. + add 1 to depth-counter. + display depth-counter. + perform 200-mung. +300-err. + entry "300-err" using err-msg. + perform varying ind from 1 by 1 + until (err-msg(ind:1) = x"00") or (ind = length of err-msg) + continue + end-perform + + display err-msg(1:ind). + +*> room for a better-than-abrupt death here. + + exit program. diff --git a/Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-2.cob b/Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-2.cob new file mode 100644 index 0000000000..c72adb6338 --- /dev/null +++ b/Task/Find-limit-of-recursion/COBOL/find-limit-of-recursion-2.cob @@ -0,0 +1,25 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. recurse RECURSIVE. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Starter PIC S9(8) VALUE 1. + PROCEDURE DIVISION. + Program-Recurse. + CALL "recurse-sub" USING Starter + STOP RUN. + + IDENTIFICATION DIVISION. + PROGRAM-ID. recurse-sub. + DATA DIVISION. + WORKING-STORAGE SECTION. + LINKAGE SECTION. + 01 Countr PIC S9(8). + PROCEDURE DIVISION USING Countr. + Program-Recursive. + DISPLAY Countr + ADD 1 TO Countr + CALL "recurse-sub" USING Countr + + EXIT PROGRAM. + END PROGRAM recurse-sub. + END PROGRAM recurse. diff --git a/Task/Find-limit-of-recursion/Emacs-Lisp/find-limit-of-recursion.el b/Task/Find-limit-of-recursion/Emacs-Lisp/find-limit-of-recursion.el new file mode 100644 index 0000000000..52984aef0c --- /dev/null +++ b/Task/Find-limit-of-recursion/Emacs-Lisp/find-limit-of-recursion.el @@ -0,0 +1,6 @@ +(defun my-recurse (n) + (my-recurse (1+ n))) +(my-recurse 1) +=> +enters debugger at (my-recurse 595), +per the default max-lisp-eval-depth 600 in Emacs 24.1 diff --git a/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion.ps1 b/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion.ps1 new file mode 100644 index 0000000000..100d62f3af --- /dev/null +++ b/Task/Find-limit-of-recursion/PowerShell/find-limit-of-recursion.ps1 @@ -0,0 +1,15 @@ +function TestDepth ( $N ) + { + $N + TestDepth ( $N + 1 ) + } + +try + { + TestDepth 1 | ForEach { $Depth = $_ } + } +catch + { + "Exception message: " + $_.Exception.Message + } +"Last level before error: " + $Depth diff --git a/Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-1.vbs b/Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-1.vbs new file mode 100644 index 0000000000..c0bfb458b2 --- /dev/null +++ b/Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-1.vbs @@ -0,0 +1,13 @@ +'mung.vbs +option explicit + +dim c +if wscript.arguments.count = 1 then + c = wscript.arguments(0) + c = c + 1 +else + c = 0 +end if +wscript.echo "[Depth",c & "] Mung until no good." +CreateObject("WScript.Shell").Run "cscript Mung.vbs " & c, 1, true +wscript.echo "[Depth",c & "] no good." diff --git a/Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-2.vbs b/Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-2.vbs new file mode 100644 index 0000000000..95763f070e --- /dev/null +++ b/Task/Find-limit-of-recursion/VBScript/find-limit-of-recursion-2.vbs @@ -0,0 +1,14 @@ +'mung.vbs +option explicit + +sub mung(c) + dim n + n=c+1 + wscript.echo "[Level",n & "] Mung until no good" + on error resume next + mung n + on error goto 0 + wscript.echo "[Level",n & "] no good" +end sub + +mung 0 diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-1.adb b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-1.adb new file mode 100644 index 0000000000..dfb4ccb26e --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-1.adb @@ -0,0 +1,27 @@ +with Ada.Text_IO, Base_Conversion; + +procedure Brute is + + type Long is range 0 .. 2**63-1; + package BC is new Base_Conversion(Long); + + function Palindrome (S : String) return Boolean is + (if S'Length < 2 then True + elsif S(S'First) /= S(S'Last) then False + else Palindrome(S(S'First+1 .. S'Last-1))); + + function Palindrome(N: Long; Base: Natural) return Boolean is + (Palindrome(BC.Image(N, Base =>Base))); + + package IIO is new Ada.Text_IO.Integer_IO(Long); + +begin + for I in Long(1) .. 10**8 loop + if Palindrome(I, 3) and then Palindrome(I, 2) then + IIO.Put(I, Width => 12); -- prints I (Base 10) + Ada.Text_IO.Put_Line(": " & BC.Image(I, Base => 2) & "(2)" & + ", " & BC.Image(I, Base => 3) & "(3)"); + -- prints I (Base 2 and Base 3) + end if; + end loop; +end Brute; diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.adb b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.adb new file mode 100644 index 0000000000..8108f669c5 --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Ada/find-palindromic-numbers-in-both-binary-and-ternary-bases-2.adb @@ -0,0 +1,49 @@ +with Ada.Text_IO, Ada.Unchecked_Conversion;use Ada.Text_IO; +procedure Palindromic is + type Int is mod 2**64; -- the size of the unsigned values we will test doesn't exceed 64 bits + + type Bits is array (0..63) of Boolean; + for Bits'Component_Size use 1; + + -- This function allows us to get the i'th bit of an Int k by writing Int_To_Bits(k)(i) + function Int_To_Bits is new Ada.Unchecked_Conversion(Int,Bits); + + -- an inline function to test if k is palindromic in a very efficient way since we leave the loop + -- as soon as two bits are not symmetric). Number_Of_Digits is the number of digits (in base 2) of k minus 1 + function Is_Pal2 (k : Int;Number_Of_Digits : Natural) return Boolean is + (for all i in 0..Number_Of_Digits=>Int_To_Bits(k)(i)=Int_To_Bits(k)(Number_Of_Digits-i)); + + function Reverse_Number (k : Int) return Int is --returns the symmetric representation of k (base-3) + n : Int := 0; + p : Int := k; + begin + while 0

    2, Width=>65); Put (n, Base=>3, Width=>45); put_line (" " & n'Img); + end Print; + + p3, n, bound, count_pal: Int := 1; +begin + Print (0); -- because 0 is the special case asked to be treated, that is why count_pal=1 + Process_Each_Power_Of_4 : for p in 0..31 loop -- because 4^p < 2^64 + -- adjust the 3-power of the number to test so that the palindrome built with it has an odd number of digits in base-2 + while (3*p3+1)*p3 < 2**(2*p) loop p3 := 3*p3;end loop; + bound := 2**(2*p)/(3*p3); + for k in Int range Int'Max(p3/3, bound) .. Int'Min (2*bound,p3-1) loop + n := (3*k+1)*p3 + Reverse_Number (k); -- n is a 2p+1 digits number in base 2 and is a palindrome in base 3. + if Is_Pal2 (n, 2*p) then + Print (n); + count_pal := count_pal + 1; + exit Process_Each_Power_Of_4 when count_pal = 7; + end if; + end loop; + end loop Process_Each_Power_Of_4; +end Palindromic; diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Emacs-Lisp/find-palindromic-numbers-in-both-binary-and-ternary-bases.el b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Emacs-Lisp/find-palindromic-numbers-in-both-binary-and-ternary-bases.el new file mode 100644 index 0000000000..0fa8cb6bb6 --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Emacs-Lisp/find-palindromic-numbers-in-both-binary-and-ternary-bases.el @@ -0,0 +1,52 @@ +(require 'calc-bin) + +(defun is-palindrome-p (str) + "Test if STR is a palindrome." + (equal str (reverse str))) + +(defun ends-in-zero-p (str) + "Test if STR ends in zero (0)." + (string-match-p "0\\'" str)) + +(defun base-3-to-base-2 (str) + "Convert STR from base 3 to base 2. +STR must be a string containing only digits 0-2." + (let ((calc-number-radix 2) + (base-10-number (string-to-number str 3))) + ;; return string of base 2 number + (format "%s" (math-format-radix base-10-number)))) + +(defun base-3-to-base-10 (str) + "Convert STR from base 3 to base 10. +STR must be a string containing only digits 0-2." + (let ((calc-number-radix 10) + (base-10-number (string-to-number str 3))) + ;; return string of base 10 number + (format "%s" (number-to-string base-10-number)))) + +(defun find-palindromes (number) + "Find NUMBER of pairs of palindrome numbers. +The pair consists of one number which is a palindrome in +base 3 and a base 2 number of the same value that is +also a palindrome in base 2." + (let ((calc-number-radix 3) + (base-3-partial-string) + (base-3-partial-number 0) + (base-3-string) + (base-2-string) + (base-10-string) + (count 2)) + (insert (format "\n%12s %23s %37s" "Base_10" "Base_3" "Base_2")) + (insert "\n----------------------------------------------------------------------------") + (insert (format "\n%12s %23s %37s" "0" "0" "0")) + (insert (format "\n%12s %23s %37s" "1" "1" "1")) + (while (< count number) + (setq base-3-partial-number (1+ base-3-partial-number)) + (setq base-3-partial-string (format "%s" (math-format-radix base-3-partial-number))) + (setq base-3-string (concat base-3-partial-string "1" (reverse base-3-partial-string))) + (unless (ends-in-zero-p base-3-string) + (setq base-2-string (base-3-to-base-2 base-3-string)) + (when (is-palindrome-p base-2-string) + (setq count (1+ count)) + (setq base-10-string (base-3-to-base-10 base-3-string)) + (insert (format "\n%12s %23s %37s" base-10-string base-3-string base-2-string))))))) diff --git a/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Frink/find-palindromic-numbers-in-both-binary-and-ternary-bases.frink b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Frink/find-palindromic-numbers-in-both-binary-and-ternary-bases.frink new file mode 100644 index 0000000000..967fc4b633 --- /dev/null +++ b/Task/Find-palindromic-numbers-in-both-binary-and-ternary-bases/Frink/find-palindromic-numbers-in-both-binary-and-ternary-bases.frink @@ -0,0 +1,22 @@ +count = 0 +n = 0 +do +{ + half = base2[n] + nns = half + reverse[left[half, -1]] + nn = parseInt[nns, 2] + + if isPalindrome[nn, 3] + { + println[nn] + count = count + 1 + } + n = n +1 +} until count == 6 + +// Returns true if the given number is a palindrome in the specified base. +isPalindrome[num, base] := +{ + str = base[num, base] + return reverse[str] == str +} diff --git a/Task/Find-the-intersection-of-a-line-with-a-plane/Ada/find-the-intersection-of-a-line-with-a-plane.adb b/Task/Find-the-intersection-of-a-line-with-a-plane/Ada/find-the-intersection-of-a-line-with-a-plane.adb new file mode 100644 index 0000000000..c33d00d8bb --- /dev/null +++ b/Task/Find-the-intersection-of-a-line-with-a-plane/Ada/find-the-intersection-of-a-line-with-a-plane.adb @@ -0,0 +1,56 @@ +with Ada.Numerics.Generic_Real_Arrays; +with Ada.Text_IO; + +procedure Intersection is + + type Real is new Long_Float; + + package Real_Arrays is + new Ada.Numerics.Generic_Real_Arrays (Real => Real); + use Real_Arrays; + + package Real_IO is + new Ada.Text_IO.Float_IO (Num => Real); + + subtype Vector_3D is Real_Vector (1 .. 3); + + function Line_Plane_Intersection (Line_Vector : in Vector_3D; + Line_Point : in Vector_3D; + Plane_Normal : in Vector_3D; + Plane_Point : in Vector_3D) + return Vector_3D + is + Diff : constant Vector_3D := Line_Point - Plane_Point; + Denom : constant Real := Line_Vector * Plane_Normal; + begin + if Denom = 0.0 then + raise Constraint_Error with "Line does not intersect plane"; + end if; + declare + Scale : constant Real := + -Real'(Diff * Plane_Normal) / Denom; + Point : constant Vector_3D := + Diff + Plane_Point + Scale * Line_Vector; + begin + return Point; + end; + end Line_Plane_Intersection; + + procedure Put (V : in Vector_3D) is + use Ada.Text_IO, Real_IO; + begin + Put ("("); + Put (V (1)); Put (","); + Put (V (2)); Put (","); + Put (V (3)); Put (")"); + end Put; + +begin + Real_IO.Default_Exp := 0; + Real_IO.Default_Aft := 3; + + Put (Line_Plane_Intersection (Line_Vector => (0.0, -1.0, -1.0), + Line_Point => (0.0, 0.0, 10.0), + Plane_Normal => (0.0, 0.0, 1.0), + Plane_Point => (0.0, 0.0, 5.0))); +end Intersection; diff --git a/Task/Find-the-intersection-of-a-line-with-a-plane/Fortran/find-the-intersection-of-a-line-with-a-plane.f b/Task/Find-the-intersection-of-a-line-with-a-plane/Fortran/find-the-intersection-of-a-line-with-a-plane.f new file mode 100644 index 0000000000..969674c0d2 --- /dev/null +++ b/Task/Find-the-intersection-of-a-line-with-a-plane/Fortran/find-the-intersection-of-a-line-with-a-plane.f @@ -0,0 +1,76 @@ +! +! Find the intersection of a line with a plane +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 26.04 +! GNU gfortran (Ubuntu 15.2.0-16ubuntu1) 15.2.0 on Kubuntu 26.04 +! VSI Fortran x86-64 V8.7-001 on OpenVMS V9.2-3 +! U.B., April 2026 +! +program LinePlaneIntersecion + +integer, parameter :: tReal8 = 8 + +real (kind=tReal8), dimension(3) :: LineDirec, LinePoint +real (kind=tReal8), dimension(3) :: PlaneNormalVec, PlanePoint + +! Case 1: Values from Task description +LineDirec = [0,-1,-1] +LinePoint = [0,0,10] +PlaneNormalVec = [0,0,1] +PlanePoint = [0,0,5] + +call CalcIntersectionPoint() + +! Line is on/in plane +LineDirec = [1,1,0] +LinePoint = [1,1,0] +PlaneNormalVec = [0,0,1] +PlanePoint = [5,1,0] + +call CalcIntersectionPoint() + +! Line is parallel to plane +LineDirec = [1,1,0] +LinePoint = [1,1,1] +PlaneNormalVec = [0,0,1] +PlanePoint = [5,1,0] + +call CalcIntersectionPoint() + +contains + + +! ================================================================================================================= +! Calculate and print the coordinates of the intersection point of the line and the plane as given in main program. +! The method is described in a wikipedia article, see +! https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection#Algebraic_form +! If line and plane are parallel, or if th line is contained in the plane, do not print the coordinates but +! print just that as a statement. +! ================================================================================================================= +subroutine CalcIntersectionPoint() + +real (kind=tReal8) :: d, prod12, prod2 +real (kind=tReal8), dimension(3) :: result + +prod1 = dot_product (PlanePoint - LinePoint, PlaneNormalVec) +prod2 = dot_product (LineDirec, PlaneNormalVec) + + +if (prod1 .eq. 0) then + write (*, '("Line is contained in the Plane.")') + return +endif +if (prod2 .eq. 0 ) then + write (*, '("Line and Plane are parallel.")') + return +endif + +d = prod1 / prod2 +result = LinePoint + d*LineDirec + +write (*, '("The line intersects the plane at ")', advance='no') +write (*,'("(", 2(F5.2,x), F5.2, ")")', advance='no') Result(1),Result(2),Result(3) +write (*, *) + +end subroutine CalcIntersectionPoint + +end program LinePlaneIntersecion diff --git a/Task/Find-the-intersection-of-two-lines/Ada/find-the-intersection-of-two-lines.adb b/Task/Find-the-intersection-of-two-lines/Ada/find-the-intersection-of-two-lines.adb new file mode 100644 index 0000000000..a0c91d3cdb --- /dev/null +++ b/Task/Find-the-intersection-of-two-lines/Ada/find-the-intersection-of-two-lines.adb @@ -0,0 +1,44 @@ +with Ada.Text_IO; + +procedure Intersection_Of_Two_Lines +is + Do_Not_Intersect : exception; + + type Line is record + a : Float; + b : Float; + end record; + + type Point is record + x : Float; + y : Float; + end record; + + function To_Line(p1, p2 : in Point) return Line + is + a : constant Float := (p1.y - p2.y) / (p1.x - p2.x); + b : constant Float := p1.y - (a * p1.x); + begin + return (a,b); + end To_Line; + + function Intersection(Left, Right : in Line) return Point is + begin + if Left.a = Right.a then + raise Do_Not_Intersect with "The two lines do not intersect."; + end if; + + declare + b : constant Float := (Right.b - Left.b) / (Left.a - Right.a); + begin + return (b, Left.a * b + Left.b); + end; + end Intersection; + + A1 : constant Line := To_Line((4.0, 0.0), (6.0, 10.0)); + A2 : constant Line := To_Line((0.0, 3.0), (10.0, 7.0)); + p : constant Point := Intersection(A1, A2); +begin + Ada.Text_IO.Put(p.x'Img); + Ada.Text_IO.Put_Line(p.y'Img); +end Intersection_Of_Two_Lines; diff --git a/Task/Find-the-intersection-of-two-lines/EMal/find-the-intersection-of-two-lines.emal b/Task/Find-the-intersection-of-two-lines/EMal/find-the-intersection-of-two-lines.emal index 8a74f2f41a..efa1ddd660 100644 --- a/Task/Find-the-intersection-of-two-lines/EMal/find-the-intersection-of-two-lines.emal +++ b/Task/Find-the-intersection-of-two-lines/EMal/find-the-intersection-of-two-lines.emal @@ -1,32 +1,32 @@ type Intersection model Point point - fun asText = <|when(me.point == null, "No intersection", me.point.asText()) + fun asText ← <|when(me.point æ null, "No intersection", me.point.asText()) end type Point model real x, y - fun asText = <|"(" + me.x + "," + me.y + ")" + fun asText ← <|"(" + me.x + "," + me.y + ")" end type Line model Point s,e end type Main -fun getIntersectionByLines = Intersection by Line n1, Line n2 - real a1 = n1.e.y - n1.s.y - real b1 = n1.s.x - n1.e.x - real c1 = a1 * n1.s.x + b1 * n1.s.y - real a2 = n2.e.y - n2.s.y - real b2 = n2.s.x - n2.e.x - real c2 = a2 * n2.s.x + b2 * n2.s.y - real delta = a1 * b2 - a2 * b1 - if delta == 0 do return Intersection() end +fun getIntersectionByLines ← Intersection by Line n1, Line n2 + real a1 ← n1.e.y - n1.s.y + real b1 ← n1.s.x - n1.e.x + real c1 ← a1 * n1.s.x + b1 * n1.s.y + real a2 ← n2.e.y - n2.s.y + real b2 ← n2.s.x - n2.e.x + real c2 ← a2 * n2.s.x + b2 * n2.s.y + real delta ← a1 * b2 - a2 * b1 + if delta æ 0 do return Intersection() end return Intersection(Point((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)) end -Line n1 = Line(Point(4, 0), Point(6, 10)) -Line n2 = Line(Point(0, 3), Point(10, 7)) +Line n1 ← Line(Point(4, 0), Point(6, 10)) +Line n2 ← Line(Point(0, 3), Point(10, 7)) writeLine(getIntersectionByLines(n1, n2)) -n1 = Line(Point(0, 0), Point(1, 1)) -n2 = Line(Point(1, 2), Point(4, 5)) +n1 ← Line(Point(0, 0), Point(1, 1)) +n2 ← Line(Point(1, 2), Point(4, 5)) writeLine(getIntersectionByLines(n1, n2)) diff --git a/Task/Find-the-intersection-of-two-lines/Emacs-Lisp/find-the-intersection-of-two-lines.el b/Task/Find-the-intersection-of-two-lines/Emacs-Lisp/find-the-intersection-of-two-lines.el new file mode 100644 index 0000000000..03c8913ada --- /dev/null +++ b/Task/Find-the-intersection-of-two-lines/Emacs-Lisp/find-the-intersection-of-two-lines.el @@ -0,0 +1,26 @@ +;; y = a*x + b +(let () + (defun line-prop (p1 p2) + (let* ((prop-a (/ (- (plist-get p2 'y) (plist-get p1 'y)) + (- (plist-get p2 'x) (plist-get p1 'x)))) + (prop-b (- (plist-get p1 'y) (* prop-a (plist-get p1 'x))))) + + (list 'a prop-a 'b prop-b) ) ) + + (defun calculate-intersection (line1 line2) + (if (= (plist-get line1 'a) (plist-get line2 'a)) + (progn (error "The two lines don't have any intersection.") nil) + (progn + (let (int-x int-y) + (setq int-x (/ (- (plist-get line2 'b) (plist-get line1 'b)) + (- (plist-get line1 'a) (plist-get line2 'a)))) + (setq int-y (+ (* (plist-get line1 'a) int-x) (plist-get line1 'b))) + (list 'x int-x 'y int-y) ) ) ) ) + + (let ((p1 '(x 4.0 y 0.0)) (p2 '(x 6.0 y 10.0)) + (p3 '(x 0.0 y 3.0)) (p4 '(x 10.0 y 7.0))) + (let ((line1 (line-prop p1 p2)) + (line2 (line-prop p3 p4))) + (message "%s" (calculate-intersection line1 line2)) ) ) + + ) diff --git a/Task/Find-the-intersection-of-two-lines/SNOBOL4/find-the-intersection-of-two-lines.sno b/Task/Find-the-intersection-of-two-lines/SNOBOL4/find-the-intersection-of-two-lines.sno new file mode 100644 index 0000000000..791ecc1a7f --- /dev/null +++ b/Task/Find-the-intersection-of-two-lines/SNOBOL4/find-the-intersection-of-two-lines.sno @@ -0,0 +1,14 @@ + DEFINE("findInter(l1x1,l1y1,l1x2,l1y2,l2x1,l2y1,l2x2,l2y2)") + ret = ARRAY("2") :(findInter_END) +findInter l1m = (l1y1 - l1y2) / (l1x1 - l1x2) * 1.0 + l2m = (l2y1 - l2y2) / (l2x1 - l2x2) * 1.0 +*Multiply 1.0 to convert it to float + EQ(l1m,l2m) :F(not_parallel) + findInter = "No intersection(parallel)" :(RETURN) +not_parallel ret<1> = (l2m * l2x1 - l1m * l1x1 + l1y1 - l2y1) / (l2m - l1m) + ret<2> = l1m * (ret<1> - l1x1) + l1y1 + findInter = "(" ret<1> "," ret<2> ")" :(RETURN) +findInter_END + + OUTPUT = findInter(4,0,6,10,0,3,10,7) +END diff --git a/Task/Find-the-last-Sunday-of-each-month/COBOL/find-the-last-sunday-of-each-month.cob b/Task/Find-the-last-Sunday-of-each-month/COBOL/find-the-last-sunday-of-each-month.cob new file mode 100644 index 0000000000..11207b5f57 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/COBOL/find-the-last-sunday-of-each-month.cob @@ -0,0 +1,48 @@ + program-id. last-sun. + data division. + working-storage section. + 1 wk-date. + 2 yr pic 9999. + 2 mo pic 99 value 1. + 2 da pic 99 value 1. + 1 rd-date redefines wk-date pic 9(8). + 1 binary. + 2 int-date pic 9(8). + 2 dow pic 9(4). + 2 sunday pic 9(4) value 7. + procedure division. + display "Enter a calendar year (1601 thru 9999): " + with no advancing + accept yr + if yr >= 1601 and <= 9999 + continue + else + display "Invalid year" + stop run + end-if + perform 12 times + move 1 to da + add 1 to mo + if mo > 12 *> to avoid y10k in 9999 + move 12 to mo + move 31 to da + end-if + compute int-date = function + integer-of-date (rd-date) + if mo =12 and da = 31 *> to avoid y10k in 9999 + continue + else + subtract 1 from int-date + end-if + compute rd-date = function + date-of-integer (int-date) + compute dow = function mod + ((int-date - 1) 7) + 1 + compute dow = function mod ((dow - sunday) 7) + subtract dow from da + display yr "-" mo "-" da + add 1 to mo + end-perform + stop run + . + end program last-sun. diff --git a/Task/Find-the-last-Sunday-of-each-month/Crystal/find-the-last-sunday-of-each-month.cr b/Task/Find-the-last-Sunday-of-each-month/Crystal/find-the-last-sunday-of-each-month.cr new file mode 100644 index 0000000000..81598d4544 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Crystal/find-the-last-sunday-of-each-month.cr @@ -0,0 +1,10 @@ +def last_sundays_in_year (year) + (1..12).map { |month| + last_day = Time.utc(year, month, Time.days_in_month(year, month)) + last_day - (last_day.day_of_week.value % 7).days + } +end + +last_sundays_in_year(2013).each do |t| + puts t.to_s("%Y-%m-%d") +end diff --git a/Task/Find-the-last-Sunday-of-each-month/Emacs-Lisp/find-the-last-sunday-of-each-month.el b/Task/Find-the-last-Sunday-of-each-month/Emacs-Lisp/find-the-last-sunday-of-each-month.el new file mode 100644 index 0000000000..11dcc96b4b --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Emacs-Lisp/find-the-last-sunday-of-each-month.el @@ -0,0 +1,14 @@ +(require 'calendar) + +(defun last-sunday (year) + "Print the last Sunday in each month of year" + (mapcar (lambda (month) + (let* + ((days (number-sequence 1 (calendar-last-day-of-month month year))) + (mdy (mapcar (lambda (x) (list month x year)) days)) + (weekdays (mapcar #'calendar-day-of-week mdy)) + (lastsunday (1+ (cl-position 0 weekdays :from-end t)))) + (insert (format "%i-%02i-%02i \n" year month lastsunday)))) + (number-sequence 1 12))) + +(last-sunday 2013) diff --git a/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-1.f b/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-1.f index 6f38545665..1fe539acb0 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-1.f +++ b/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-1.f @@ -1,2 +1,102 @@ - D = DAYNUM(Y,M,D) !Daynumber from date. - DAYNUM(Y,M,D) = D !Date parts from a day number. +! last_sundays.f90 +! +! Prints the last Sunday of every month for a given year. +! The year is supplied as a command-line argument. +! +! Usage: +! ./last_sundays +! +! Example: +! ./last_sundays 2013 +! 2013-01-27 +! ... +! +! Algorithm overview: +! For each month, determine its last calendar day, then use +! the Tomohiko Sakamoto day-of-week formula to find what +! weekday that day falls on. Subtract that offset (0 for +! Sunday, 1 for Monday, ..., 6 for Saturday) to step back +! to the nearest Sunday on or before the last day. + +program last_sundays + implicit none + + ! ---------------------------------------------------------------- + ! Variable declarations + ! ---------------------------------------------------------------- + integer :: year ! The year supplied by the user + integer :: month ! Loop counter: 1 (Jan) .. 12 (Dec) + integer :: last_day ! Last calendar day of the current month + integer :: dow ! Day-of-week of last_day (0=Sun .. 6=Sat) + integer :: diff ! Days to subtract to reach the last Sunday + integer :: y ! Year adjusted for the Sakamoto formula + + ! Sakamoto month-offset table. + ! These constants encode the cumulative day-of-week shift + ! introduced by each month's length. January and February are + ! treated as months 13 and 14 of the *previous* year inside the + ! formula, which is why the caller decrements y when month < 3. + integer :: t(12) = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4] + + ! Days in each month for a normal (non-leap) year. + ! Element 2 (February) is updated to 29 when the year is a leap year. + integer :: days(12) + + ! Buffer to receive the raw command-line text for the year + character(len=20) :: arg + + ! ---------------------------------------------------------------- + ! Read the year from the first command-line argument + ! ---------------------------------------------------------------- + call get_command_argument(1, arg) ! Fetch raw text + read(arg, *) year ! Parse it as an integer + + ! ---------------------------------------------------------------- + ! Initialise month lengths for a standard year + ! ---------------------------------------------------------------- + days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + ! Leap-year rule: + ! Divisible by 4 -> leap year candidate + ! Divisible by 100 -> NOT a leap year (century exception) + ! Divisible by 400 -> IS a leap year (override century rule) + if ((mod(year,4)==0 .and. mod(year,100)/=0) .or. mod(year,400)==0) & + days(2) = 29 ! February gets an extra day in a leap year + + ! ---------------------------------------------------------------- + ! Main loop: find the last Sunday of each month + ! ---------------------------------------------------------------- + do month = 1, 12 + + last_day = days(month) ! Last calendar day of this month + + ! The Sakamoto formula needs the year adjusted so that + ! January and February belong to the previous year. + y = year + if (month < 3) y = y - 1 + + ! Tomohiko Sakamoto's day-of-week formula (1993). + ! Returns 0 for Sunday, 1 for Monday, ..., 6 for Saturday. + ! The formula combines: + ! y - base year contribution + ! y/4 - one extra day every 4 years (leap years) + ! -y/100 - remove the century non-leap correction + ! +y/400 - restore the 400-year leap override + ! t(month) - month-specific offset from the lookup table + ! last_day - the actual day number within the month + ! The whole sum mod 7 gives the weekday. + dow = mod(y + y/4 - y/100 + y/400 + t(month) + last_day, 7) + + ! 'dow' is already the number of days we must step backwards: + ! dow=0 -> last_day is already Sunday, subtract 0 + ! dow=1 -> last_day is Monday, subtract 1 to reach Sunday + ! ... + ! dow=6 -> last_day is Saturday, subtract 6 to reach Sunday + diff = dow + + ! Print the result in ISO-8601 format (YYYY-MM-DD) + write(*, '(I4, "-", I2.2, "-", I2.2)') year, month, last_day - diff + + end do + +end program last_sundays diff --git a/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-2.f b/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-2.f index 29a7951e7e..6f38545665 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-2.f +++ b/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-2.f @@ -1,256 +1,2 @@ - MODULE DATEGNASH -C Calculate conforming to complex calendarical contortions. -C Astronomer Simon Newcomb determined that the tropical year of 1900 -c contained 31556925.9747 seconds, or 365.24219879 days. -c Subsequent definitions involve "no measurable differences", -c whereas in 45BC (when the Julian calendar was adopted), the year was -c 365.24232 days long, going by modern calculations. -c The "tropical" year is the time between the same equinoxes, and thus -c contains the effect of the precession of the Earth's axis, which would -c otherwise cause the seasons to likewise precess around the "fixed star" -c year, that being the time for midnight to point in the same direction -c amongst the "fixed" stars. Specifically, the vernal equinox -c (the northern hemisphere's spring equinox: cultural colonialism) -c is meant to hover around the 21'st of March, although it may fall -c within the 19'th or 20'th, which last has been the most popular in -c the 20'th century, until the leap year of 2000 resynchronised -c the civil calendar. -C By contrast, the computations of astrologers are still based on the -c constellations as oriented in Babylonian times... - -c So, to add .24219879 to 365 days... -c Adjustment per year Nett Discrepancy remaining. -c +1/4 +.25 +.25 -.00780121 5h 48m 45.98s -c -1/100 -.01 .24 +.00219879 -11m 14.02s -c +1/400 +.0025 .2425 -.00030121 -26.02s -c -1/4000 -.00025 .24225 -.00005121 -4.42s -c -c The remnant of -.00005121 (meaning that the calendar year is too long) -c amounts to needing to drop one day on 19,527 years, and while this could be -c accommodated nicely enough by -1/20000 to give a calendar year of -c 365.24420 days with a remaining discrepancy of -.00000121 or -.01sec/year, -c there is a problem. The Earth's spin is slowing by a similar amount. -c Similar to leap years and leap days are the leap seconds that since the -c development of clocks based on atomic oscillations, have been added or -c sometimes removed to keep clock time aligned with astronomical observations. -c This additional confusion is not further considered. - - TYPE DateBag !Pack three parts into one. - INTEGER DAY,MONTH,YEAR !The usual suspects. - END TYPE DateBag !Simple enough. - - CHARACTER*9 MONTHNAME(12),DAYNAME(0:6) !Re-interpretations. - PARAMETER (MONTHNAME = (/"January","February","March","April", - 1 "May","June","July","August","September","October","November", - 2 "December"/)) - PARAMETER (DAYNAME = (/"Sunday","Monday","Tuesday","Wednesday", - 1 "Thursday","Friday","Saturday"/)) !Index this array with DayNum mod 7. - CHARACTER*3 MTHNAME(12) !The standard abbreviations. - PARAMETER (MTHNAME = (/"JAN","FEB","MAR","APR","MAY","JUN", - 1 "JUL","AUG","SEP","OCT","NOV","DEC"/)) - - INTEGER*4 JDAYSHIFT !INTEGER*2 just isn't enough. - PARAMETER (JDAYSHIFT = 2415020) !Thus shall 31/12/1899 give 0, a Sunday, via DAYNUM. - DOUBLE PRECISION DAYSINYEAR !A real ache. - PARAMETER (DAYSINYEAR = 365.24219879D0) !The "D0" demands DOUBLE PRECISION precision. - INTEGER*4 SECONDSINDAY !This has its uses. - PARAMETER (SECONDSINDAY = 24*60*60) !86400. Disregarding "leap" seconds. - INTEGER NOTADAYNUMBER !Might as well settle on one value. - PARAMETER (NOTADAYNUMBER = -2147483648) !And everyone use it. - - PARAMETER NZBASEPLACE = "Mt. Cook Trig, Wellington." !Name the place. - DOUBLE PRECISION NZBASELAT,NZBASELONG !Alas, DATA statements do not allow arithmetic expressions. - PARAMETER (NZBASELAT = -((59.3 D0/60 + 17)/60 + 41)) !Degrees South, thus negative. - PARAMETER (NZBASELONG = ((34.65D0/60 + 46)/60 + 174)) !Degrees East are oriented as positive: left to right with N up. -C Seconds Minutes Degrees. -C This is the location of the Mt. Cook trigonometrical base point for New Zealand. -C (It's in the foyer of what used to be the Dominion Museum, Wellington) -C Determined by Henry Jackson, chief surveyor, in 1870. - - TYPE Terroir !Collate the attributes of location, as so far needed. - CHARACTER*28 PLACENAME !Name the location. - DOUBLE PRECISION LATITUDE,LONGITUDE !Locate the location. - DOUBLE PRECISION ZONETIME !The time zone of its civil clock, not necessarily a whole hour. - END TYPE Terroir !The nature of the climate, soil, etc. is not yet involved. - TYPE(Terroir) BASE !Righto, let's have one of them. - DATA BASE/Terroir("Mt. Cook Trig, Wellington.", !The compiler bungles if NZBASEPLACE is used here. - 1 NZBASELAT,NZBASELONG,+12.0)/ !Where it's at. +12 hours ahead = +180 degrees Eastward of Greenwhich. -Careful! New Zealand is not centred on longitude 180, but its civil clock's time zone is. - DOUBLE PRECISION SINBASELAT,COSBASELAT !Calculated in SOLARDIRECTION and ZAPME. - - CONTAINS !Let the madness begin. - - INTEGER*4 FUNCTION DAYNUM(YY,M,D) !Computes (JDayN - JDayShift), not JDayN. -C Conversion from a Gregorian calendar date to a Julian day number, JDayN. -C Valid for any Gregorian calendar date producing a Julian day number -C greater than zero, though remember that the Gregorian calendar -C was not used before y1582m10d15 and often, not after that either. -C thus in England (et al) when Wednesday 2'nd September 1752 (Julian style) -C was followed by Thursday the 14'th, occasioning the Eleven Day riots -C because creditors demanded a full month's payment instead of 19/30'ths. -C The zero of the Julian day number corresponds to the first of January -C 4713BC on the *Julian* calendar's naming scheme, as extended backwards -C with current usage into epochs when it did not exist: the proleptic Julian calendar. -c This function employs the naming scheme of the *Gregorian* calendar, -c and if extended backwards into epochs when it did not exist (thus the -c proleptic Gregorian calendar) it would compute a zero for y-4713m11d24 *if* -c it is supposed there was a year zero between 1BC and 1AD (as is convenient -c for modern mathematics and astronomers and their simple calculations), *but* -c 1BC immediately precedes 1AD without any year zero in between (and is a leap year) -c thus the adjustment below so that the date is y-4714m11d24 or 4714BCm11d24, -c not that this name was in use at the time... -c Although the Julian calendar (introduced by himself in what we would call 45BC, -c which was what the Romans occasionally called 709AUC) was provoked by the -c "years of confusion" resulting from arbitrary application of the rules -c for the existing Roman calendar, other confusions remain unresolved, -c so precise dating remains uncertain despite apparently precise specifications -c (and much later, Dennis the Short chose wrongly for the birth of Christ) -c and the Roman practice of inclusive reckoning meant that every four years -c was interpreted as every third (by our exclusive reckoning) so that the -c leap years were not as we now interpret them. This was resolved by Augustus -c but exactly when (and what date name is assigned) and whose writings used -c which system at the time of writing is a matter of more confusion, -c and this has continued for centuries. -C Accordingly, although an algorithm may give a regular sequence of date names, -c that does not mean that those date names were used at the time even if the -c calendar existed then, because the interpretation of the algorithm varied. -c This in turn means that a date given as being on the Julian calendar -c prior to about 10AD is not as definite as it may appear and its alignment -c with the astronomical day number is uncertain even though the calculation -c is quite definite. -c -C Computationally, year 1 is preceded by year 0, in a smooth progression. -C But there was never a year zero despite what astronomers like to say, -C so the formula's year 0 corresponds to 1BC, year -1 to 2BC, and so on back. -C Thus y-4713 in this counting would be 4714BC on the Gregorian calendar, -C were it to have existed then which it didn't. -C To conform to the civil usage, the incoming YY, presumed a proper BC (negative) -C and AD (positive) year is converted into the computational counting sequence, Y, -C and used in the formula. If a YY = 0 is (improperly) offered, it will manifest -C as 1AD. Thus YY = -4714 will lead to calculations with Y = -4713. -C Thus, 1BC is a leap year on the proleptic Gregorian calendar. -C For their convenience, astronomers decreed that a day starts at noon, so that -C in Europe, observations through the night all have the same day number. -C The current Western civil calendar however has the day starting just after midnight -C and that day's number lasts until the following midnight. -C -C There is no constraint on the values of D, which is just added as it stands. -C This means that if D = 0, the daynumber will be that of the last day of the -C previous month. Likewise, M = 0 or M = 13 will wrap around so that Y,M + 1,0 -C will give the last day of month M (whatever its length) as one day before -C the first day of the next month. -C -C Example: Y = 1970, M = 1, D = 1; JDAYN = 2440588, a Thursday but MOD(2440588,7) = 3. -C and with the adjustment JDAYSHIFT, DAYNUM = 25568; mod 7 = 4 and DAYNAME(4) = "Thursday". -C The Julian Day number 2440588.0 is for NOON that Thursday, 2440588.5 is twelve hours later. -C And Julian Day number 2440587.625 is for three a.m. Thursday. -C -C DAYNUM and MUNYAD are the infamous routines of H. F. Fliegel and T.C. van Flandern, -C presented in Communications of the ACM, Vol. 11, No. 10 (October, 1968). -Carefully typed in again by R.N.McLean (whom God preserve) December XXMMIIX. -C Though I remain puzzled as to why they used I,J,K for Y,M,D, -C given that the variables were named in the INTEGER statement anyway. - INTEGER*4 JDAYN !Without rebasing, this won't fit in INTEGER*2. - INTEGER YY,Y,M,MM,D !NB! Full year number, so 1970, not 70. -Caution: integer division in Fortran does not produce fractional results. -C The fractional part is discarded so that 4/3 gives 1 and -4/3 gives -1. -C Thus 4/3 might be Trunc(4/3) or 4 div 3 in other languages. Beware of negative numbers! - Y = YY !I can fiddle this copy without damaging the original's value. - IF (Y.LT.1) Y = Y + 1 !Thus YY = -2=2BC, -1=1BC, +1=1AD, ... becomes Y = -1, 0, 1, ... - MM = (M - 14)/12 !Calculate once. Note that this is integer division, truncating. - JDAYN = D - 32075 !This is the proper astronomer's Julian Day Number. - a + 1461*(Y + 4800 + MM)/4 - b + 367*(M - 2 - MM*12)/12 - c - 3*((Y + 4900 + MM)/100)/4 - DAYNUM = JDAYN - JDAYSHIFT !Thus, *NOT* the actual *Julian* Day Number. - END FUNCTION DAYNUM !But one such that Mod(n,7) gives day names. - -Could compute the day of the year somewhat as follows... -c DN:=D + (61*Month + (Month div 8)) div 2 - 30 -c + if Month > 2 then FebLength - 30 else 0; - - TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM) !Oh for palindromic programming! -Conversion from a Julian day number to a Gregorian calendar date. See JDAYN/DAYNUM. - INTEGER*4 DAYNUM,JDAYN !Without rebasing, this won't fit in INTEGER*2. - INTEGER Y,M,D,L,N !Y will be a full year number: 1950 not 50. - JDAYN = DAYNUM + JDAYSHIFT !Revert to a proper Julian day number. - L = JDAYN + 68569 !Further machinations of H. F. Fliegel and T.C. van Flandern. - N = 4*L/146097 - L = L - (146097*N + 3)/4 - Y = 4000*(L + 1)/1461001 - L = L - 1461*Y/4 + 31 - M = 80*L/2447 - D = L - 2447*M/80 - L = M/11 - M = M + 2 - 12*L - Y = 100*(N - 49) + Y + L - IF (Y.LT.1) Y = Y - 1 !The other side of conformity to BC/AD, as in DAYNUM. - MUNYAD%YEAR = Y !Now place for the world to see. - MUNYAD%MONTH = M - MUNYAD%DAY = D - END FUNCTION MUNYAD !A year has 365.2421988 days... - - CHARACTER*10 FUNCTION SLASHDATE(DAYNUM) !This is relatively innocent. -Caution! The Gregorian calendar did not exist prior to 15/10/1582! -Confine expected operation to four-digit years, since fixed-field sizes are in mind. -Can use this function in WRITE statements with FORMAT, since this function does not use them. -Compilers of lesser merit can concoct code that bungles such double usage otherwise. - INTEGER*4 DAYNUM !-32768 to 32767 is just not adequate. - TYPE(DATEBAG) D !Though these numbers are more restrained. - INTEGER N,L !Workers. - IF (DAYNUM.EQ.NOTADAYNUMBER) THEN !Perhaps some work can be dodged. - SLASHDATE = " Undated!!" !No proper day number has been placed. - RETURN !So give up, rather than show odd results. - END IF !So much for confusion. - D = MUNYAD(DAYNUM) !Get the pieces. - IF (D%DAY.GT.9) THEN !Here we go. - SLASHDATE(1:1) = CHAR(D%DAY/10 + ICHAR("0")) !Faster than a table look-up? - ELSE !Even if not, - SLASHDATE(1:1) = " " !This should be quick. - END IF !So much for the tens digit. - SLASHDATE(2:2) = CHAR(MOD(D%DAY,10) + ICHAR("0")) !The units digit. - SLASHDATE(3:3) = "/" !Enough of the day number. The separator. - IF (D%MONTH.GT.9) THEN !Now for the month. - SLASHDATE(4:4) = CHAR(D%MONTH/10 + ICHAR("0")) !The tens digit. - ELSE !Not so often used. A table beckons... - SLASHDATE(4:4) = " " !Some might desire leading zeroes here. - END IF !Enough of October, November and December. - SLASHDATE(5:5) = CHAR(MOD(D%MONTH,10) + ICHAR("0")) !The units digit. - SLASHDATE(6:6) = "/" !Enough of the month number. The separator. - L = 10 !The year value deserves a loop, it having four digits. - N = ABS(D%YEAR) !Should never be zero. 1BC is year -1 and 1AD is year = +1. - 1 SLASHDATE(L:L) = CHAR(MOD(N,10) + ICHAR("0")) !But if it is, this will place a zero. - N = N/10 !Drop a power of ten. - L = L - 1 !Step back for the next digit. - IF (L.GT.6) GO TO 1 !Thus always four digits, even if they lead with zero. - IF (N.GT.0) SLASHDATE(7:7) = "?" !Y > 9999? Might as well do something. - IF (D%YEAR.LT.0) SLASHDATE(7:7) = "-" !Years BC? Rather than give no indication. -c WRITE (SLASHDATE,1) D%DAY,D%MONTH,D%YEAR !Some compilers will bungle this. -c 1 FORMAT (I2,"/",I2,"/",I4) !If so, a local variable must be used. - RETURN !Enough. !As when SLASHDATE is invoked in a WRITE statement. - END FUNCTION SLASHDATE !Simple enough. - END MODULE DATEGNASH - - PROGRAM LASTSUNDAY - USE DATEGNASH - INTEGER D,W,M,Y - WRITE (6,1) - 1 FORMAT ("Employs the Gregorian calendar pattern.",/, - 1 "You specify a day of the week, then nominate a year.",/, - 2 "For each month of that year, this calculates the date ", - 3 "of the last such day.",// - 4 "So, what day (0 = Sunday, 6 = Saturday):",$) - READ (5,*) W - IF (W.LT.0 .OR. W.GT.6) STOP "Not a good week day number!" - - 10 WRITE (6,11) - 11 FORMAT ("What year (non-positive to quit):",$) - READ (5,*) Y - IF (Y.LE.0) STOP - DO M = 1,12 - D = DAYNUM(Y,M + 1,0) !Zeroth day = last day of previous month. - D = D - MOD(MOD(D - W,7) + 7,7) !Protect against MOD(D,7) giving negative values for D < 0. - WRITE (6,*) SLASHDATE(D)," : ",DAYNAME(MOD(D,7)) - END DO - GO TO 10 - END + D = DAYNUM(Y,M,D) !Daynumber from date. + DAYNUM(Y,M,D) = D !Date parts from a day number. diff --git a/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-3.f b/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-3.f new file mode 100644 index 0000000000..29a7951e7e --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Fortran/find-the-last-sunday-of-each-month-3.f @@ -0,0 +1,256 @@ + MODULE DATEGNASH +C Calculate conforming to complex calendarical contortions. +C Astronomer Simon Newcomb determined that the tropical year of 1900 +c contained 31556925.9747 seconds, or 365.24219879 days. +c Subsequent definitions involve "no measurable differences", +c whereas in 45BC (when the Julian calendar was adopted), the year was +c 365.24232 days long, going by modern calculations. +c The "tropical" year is the time between the same equinoxes, and thus +c contains the effect of the precession of the Earth's axis, which would +c otherwise cause the seasons to likewise precess around the "fixed star" +c year, that being the time for midnight to point in the same direction +c amongst the "fixed" stars. Specifically, the vernal equinox +c (the northern hemisphere's spring equinox: cultural colonialism) +c is meant to hover around the 21'st of March, although it may fall +c within the 19'th or 20'th, which last has been the most popular in +c the 20'th century, until the leap year of 2000 resynchronised +c the civil calendar. +C By contrast, the computations of astrologers are still based on the +c constellations as oriented in Babylonian times... + +c So, to add .24219879 to 365 days... +c Adjustment per year Nett Discrepancy remaining. +c +1/4 +.25 +.25 -.00780121 5h 48m 45.98s +c -1/100 -.01 .24 +.00219879 -11m 14.02s +c +1/400 +.0025 .2425 -.00030121 -26.02s +c -1/4000 -.00025 .24225 -.00005121 -4.42s +c +c The remnant of -.00005121 (meaning that the calendar year is too long) +c amounts to needing to drop one day on 19,527 years, and while this could be +c accommodated nicely enough by -1/20000 to give a calendar year of +c 365.24420 days with a remaining discrepancy of -.00000121 or -.01sec/year, +c there is a problem. The Earth's spin is slowing by a similar amount. +c Similar to leap years and leap days are the leap seconds that since the +c development of clocks based on atomic oscillations, have been added or +c sometimes removed to keep clock time aligned with astronomical observations. +c This additional confusion is not further considered. + + TYPE DateBag !Pack three parts into one. + INTEGER DAY,MONTH,YEAR !The usual suspects. + END TYPE DateBag !Simple enough. + + CHARACTER*9 MONTHNAME(12),DAYNAME(0:6) !Re-interpretations. + PARAMETER (MONTHNAME = (/"January","February","March","April", + 1 "May","June","July","August","September","October","November", + 2 "December"/)) + PARAMETER (DAYNAME = (/"Sunday","Monday","Tuesday","Wednesday", + 1 "Thursday","Friday","Saturday"/)) !Index this array with DayNum mod 7. + CHARACTER*3 MTHNAME(12) !The standard abbreviations. + PARAMETER (MTHNAME = (/"JAN","FEB","MAR","APR","MAY","JUN", + 1 "JUL","AUG","SEP","OCT","NOV","DEC"/)) + + INTEGER*4 JDAYSHIFT !INTEGER*2 just isn't enough. + PARAMETER (JDAYSHIFT = 2415020) !Thus shall 31/12/1899 give 0, a Sunday, via DAYNUM. + DOUBLE PRECISION DAYSINYEAR !A real ache. + PARAMETER (DAYSINYEAR = 365.24219879D0) !The "D0" demands DOUBLE PRECISION precision. + INTEGER*4 SECONDSINDAY !This has its uses. + PARAMETER (SECONDSINDAY = 24*60*60) !86400. Disregarding "leap" seconds. + INTEGER NOTADAYNUMBER !Might as well settle on one value. + PARAMETER (NOTADAYNUMBER = -2147483648) !And everyone use it. + + PARAMETER NZBASEPLACE = "Mt. Cook Trig, Wellington." !Name the place. + DOUBLE PRECISION NZBASELAT,NZBASELONG !Alas, DATA statements do not allow arithmetic expressions. + PARAMETER (NZBASELAT = -((59.3 D0/60 + 17)/60 + 41)) !Degrees South, thus negative. + PARAMETER (NZBASELONG = ((34.65D0/60 + 46)/60 + 174)) !Degrees East are oriented as positive: left to right with N up. +C Seconds Minutes Degrees. +C This is the location of the Mt. Cook trigonometrical base point for New Zealand. +C (It's in the foyer of what used to be the Dominion Museum, Wellington) +C Determined by Henry Jackson, chief surveyor, in 1870. + + TYPE Terroir !Collate the attributes of location, as so far needed. + CHARACTER*28 PLACENAME !Name the location. + DOUBLE PRECISION LATITUDE,LONGITUDE !Locate the location. + DOUBLE PRECISION ZONETIME !The time zone of its civil clock, not necessarily a whole hour. + END TYPE Terroir !The nature of the climate, soil, etc. is not yet involved. + TYPE(Terroir) BASE !Righto, let's have one of them. + DATA BASE/Terroir("Mt. Cook Trig, Wellington.", !The compiler bungles if NZBASEPLACE is used here. + 1 NZBASELAT,NZBASELONG,+12.0)/ !Where it's at. +12 hours ahead = +180 degrees Eastward of Greenwhich. +Careful! New Zealand is not centred on longitude 180, but its civil clock's time zone is. + DOUBLE PRECISION SINBASELAT,COSBASELAT !Calculated in SOLARDIRECTION and ZAPME. + + CONTAINS !Let the madness begin. + + INTEGER*4 FUNCTION DAYNUM(YY,M,D) !Computes (JDayN - JDayShift), not JDayN. +C Conversion from a Gregorian calendar date to a Julian day number, JDayN. +C Valid for any Gregorian calendar date producing a Julian day number +C greater than zero, though remember that the Gregorian calendar +C was not used before y1582m10d15 and often, not after that either. +C thus in England (et al) when Wednesday 2'nd September 1752 (Julian style) +C was followed by Thursday the 14'th, occasioning the Eleven Day riots +C because creditors demanded a full month's payment instead of 19/30'ths. +C The zero of the Julian day number corresponds to the first of January +C 4713BC on the *Julian* calendar's naming scheme, as extended backwards +C with current usage into epochs when it did not exist: the proleptic Julian calendar. +c This function employs the naming scheme of the *Gregorian* calendar, +c and if extended backwards into epochs when it did not exist (thus the +c proleptic Gregorian calendar) it would compute a zero for y-4713m11d24 *if* +c it is supposed there was a year zero between 1BC and 1AD (as is convenient +c for modern mathematics and astronomers and their simple calculations), *but* +c 1BC immediately precedes 1AD without any year zero in between (and is a leap year) +c thus the adjustment below so that the date is y-4714m11d24 or 4714BCm11d24, +c not that this name was in use at the time... +c Although the Julian calendar (introduced by himself in what we would call 45BC, +c which was what the Romans occasionally called 709AUC) was provoked by the +c "years of confusion" resulting from arbitrary application of the rules +c for the existing Roman calendar, other confusions remain unresolved, +c so precise dating remains uncertain despite apparently precise specifications +c (and much later, Dennis the Short chose wrongly for the birth of Christ) +c and the Roman practice of inclusive reckoning meant that every four years +c was interpreted as every third (by our exclusive reckoning) so that the +c leap years were not as we now interpret them. This was resolved by Augustus +c but exactly when (and what date name is assigned) and whose writings used +c which system at the time of writing is a matter of more confusion, +c and this has continued for centuries. +C Accordingly, although an algorithm may give a regular sequence of date names, +c that does not mean that those date names were used at the time even if the +c calendar existed then, because the interpretation of the algorithm varied. +c This in turn means that a date given as being on the Julian calendar +c prior to about 10AD is not as definite as it may appear and its alignment +c with the astronomical day number is uncertain even though the calculation +c is quite definite. +c +C Computationally, year 1 is preceded by year 0, in a smooth progression. +C But there was never a year zero despite what astronomers like to say, +C so the formula's year 0 corresponds to 1BC, year -1 to 2BC, and so on back. +C Thus y-4713 in this counting would be 4714BC on the Gregorian calendar, +C were it to have existed then which it didn't. +C To conform to the civil usage, the incoming YY, presumed a proper BC (negative) +C and AD (positive) year is converted into the computational counting sequence, Y, +C and used in the formula. If a YY = 0 is (improperly) offered, it will manifest +C as 1AD. Thus YY = -4714 will lead to calculations with Y = -4713. +C Thus, 1BC is a leap year on the proleptic Gregorian calendar. +C For their convenience, astronomers decreed that a day starts at noon, so that +C in Europe, observations through the night all have the same day number. +C The current Western civil calendar however has the day starting just after midnight +C and that day's number lasts until the following midnight. +C +C There is no constraint on the values of D, which is just added as it stands. +C This means that if D = 0, the daynumber will be that of the last day of the +C previous month. Likewise, M = 0 or M = 13 will wrap around so that Y,M + 1,0 +C will give the last day of month M (whatever its length) as one day before +C the first day of the next month. +C +C Example: Y = 1970, M = 1, D = 1; JDAYN = 2440588, a Thursday but MOD(2440588,7) = 3. +C and with the adjustment JDAYSHIFT, DAYNUM = 25568; mod 7 = 4 and DAYNAME(4) = "Thursday". +C The Julian Day number 2440588.0 is for NOON that Thursday, 2440588.5 is twelve hours later. +C And Julian Day number 2440587.625 is for three a.m. Thursday. +C +C DAYNUM and MUNYAD are the infamous routines of H. F. Fliegel and T.C. van Flandern, +C presented in Communications of the ACM, Vol. 11, No. 10 (October, 1968). +Carefully typed in again by R.N.McLean (whom God preserve) December XXMMIIX. +C Though I remain puzzled as to why they used I,J,K for Y,M,D, +C given that the variables were named in the INTEGER statement anyway. + INTEGER*4 JDAYN !Without rebasing, this won't fit in INTEGER*2. + INTEGER YY,Y,M,MM,D !NB! Full year number, so 1970, not 70. +Caution: integer division in Fortran does not produce fractional results. +C The fractional part is discarded so that 4/3 gives 1 and -4/3 gives -1. +C Thus 4/3 might be Trunc(4/3) or 4 div 3 in other languages. Beware of negative numbers! + Y = YY !I can fiddle this copy without damaging the original's value. + IF (Y.LT.1) Y = Y + 1 !Thus YY = -2=2BC, -1=1BC, +1=1AD, ... becomes Y = -1, 0, 1, ... + MM = (M - 14)/12 !Calculate once. Note that this is integer division, truncating. + JDAYN = D - 32075 !This is the proper astronomer's Julian Day Number. + a + 1461*(Y + 4800 + MM)/4 + b + 367*(M - 2 - MM*12)/12 + c - 3*((Y + 4900 + MM)/100)/4 + DAYNUM = JDAYN - JDAYSHIFT !Thus, *NOT* the actual *Julian* Day Number. + END FUNCTION DAYNUM !But one such that Mod(n,7) gives day names. + +Could compute the day of the year somewhat as follows... +c DN:=D + (61*Month + (Month div 8)) div 2 - 30 +c + if Month > 2 then FebLength - 30 else 0; + + TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM) !Oh for palindromic programming! +Conversion from a Julian day number to a Gregorian calendar date. See JDAYN/DAYNUM. + INTEGER*4 DAYNUM,JDAYN !Without rebasing, this won't fit in INTEGER*2. + INTEGER Y,M,D,L,N !Y will be a full year number: 1950 not 50. + JDAYN = DAYNUM + JDAYSHIFT !Revert to a proper Julian day number. + L = JDAYN + 68569 !Further machinations of H. F. Fliegel and T.C. van Flandern. + N = 4*L/146097 + L = L - (146097*N + 3)/4 + Y = 4000*(L + 1)/1461001 + L = L - 1461*Y/4 + 31 + M = 80*L/2447 + D = L - 2447*M/80 + L = M/11 + M = M + 2 - 12*L + Y = 100*(N - 49) + Y + L + IF (Y.LT.1) Y = Y - 1 !The other side of conformity to BC/AD, as in DAYNUM. + MUNYAD%YEAR = Y !Now place for the world to see. + MUNYAD%MONTH = M + MUNYAD%DAY = D + END FUNCTION MUNYAD !A year has 365.2421988 days... + + CHARACTER*10 FUNCTION SLASHDATE(DAYNUM) !This is relatively innocent. +Caution! The Gregorian calendar did not exist prior to 15/10/1582! +Confine expected operation to four-digit years, since fixed-field sizes are in mind. +Can use this function in WRITE statements with FORMAT, since this function does not use them. +Compilers of lesser merit can concoct code that bungles such double usage otherwise. + INTEGER*4 DAYNUM !-32768 to 32767 is just not adequate. + TYPE(DATEBAG) D !Though these numbers are more restrained. + INTEGER N,L !Workers. + IF (DAYNUM.EQ.NOTADAYNUMBER) THEN !Perhaps some work can be dodged. + SLASHDATE = " Undated!!" !No proper day number has been placed. + RETURN !So give up, rather than show odd results. + END IF !So much for confusion. + D = MUNYAD(DAYNUM) !Get the pieces. + IF (D%DAY.GT.9) THEN !Here we go. + SLASHDATE(1:1) = CHAR(D%DAY/10 + ICHAR("0")) !Faster than a table look-up? + ELSE !Even if not, + SLASHDATE(1:1) = " " !This should be quick. + END IF !So much for the tens digit. + SLASHDATE(2:2) = CHAR(MOD(D%DAY,10) + ICHAR("0")) !The units digit. + SLASHDATE(3:3) = "/" !Enough of the day number. The separator. + IF (D%MONTH.GT.9) THEN !Now for the month. + SLASHDATE(4:4) = CHAR(D%MONTH/10 + ICHAR("0")) !The tens digit. + ELSE !Not so often used. A table beckons... + SLASHDATE(4:4) = " " !Some might desire leading zeroes here. + END IF !Enough of October, November and December. + SLASHDATE(5:5) = CHAR(MOD(D%MONTH,10) + ICHAR("0")) !The units digit. + SLASHDATE(6:6) = "/" !Enough of the month number. The separator. + L = 10 !The year value deserves a loop, it having four digits. + N = ABS(D%YEAR) !Should never be zero. 1BC is year -1 and 1AD is year = +1. + 1 SLASHDATE(L:L) = CHAR(MOD(N,10) + ICHAR("0")) !But if it is, this will place a zero. + N = N/10 !Drop a power of ten. + L = L - 1 !Step back for the next digit. + IF (L.GT.6) GO TO 1 !Thus always four digits, even if they lead with zero. + IF (N.GT.0) SLASHDATE(7:7) = "?" !Y > 9999? Might as well do something. + IF (D%YEAR.LT.0) SLASHDATE(7:7) = "-" !Years BC? Rather than give no indication. +c WRITE (SLASHDATE,1) D%DAY,D%MONTH,D%YEAR !Some compilers will bungle this. +c 1 FORMAT (I2,"/",I2,"/",I4) !If so, a local variable must be used. + RETURN !Enough. !As when SLASHDATE is invoked in a WRITE statement. + END FUNCTION SLASHDATE !Simple enough. + END MODULE DATEGNASH + + PROGRAM LASTSUNDAY + USE DATEGNASH + INTEGER D,W,M,Y + WRITE (6,1) + 1 FORMAT ("Employs the Gregorian calendar pattern.",/, + 1 "You specify a day of the week, then nominate a year.",/, + 2 "For each month of that year, this calculates the date ", + 3 "of the last such day.",// + 4 "So, what day (0 = Sunday, 6 = Saturday):",$) + READ (5,*) W + IF (W.LT.0 .OR. W.GT.6) STOP "Not a good week day number!" + + 10 WRITE (6,11) + 11 FORMAT ("What year (non-positive to quit):",$) + READ (5,*) Y + IF (Y.LE.0) STOP + DO M = 1,12 + D = DAYNUM(Y,M + 1,0) !Zeroth day = last day of previous month. + D = D - MOD(MOD(D - W,7) + 7,7) !Protect against MOD(D,7) giving negative values for D < 0. + WRITE (6,*) SLASHDATE(D)," : ",DAYNAME(MOD(D,7)) + END DO + GO TO 10 + END diff --git a/Task/Find-the-last-Sunday-of-each-month/MATLAB/find-the-last-sunday-of-each-month.m b/Task/Find-the-last-Sunday-of-each-month/MATLAB/find-the-last-sunday-of-each-month.m new file mode 100644 index 0000000000..3f84aa9450 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/MATLAB/find-the-last-sunday-of-each-month.m @@ -0,0 +1,5 @@ +y = 2025 +mprintf('last sundays in %u \n', y) +for m = 1:12 + mprintf('%02u.%02u.%4u\n', max(calendar(y,m)(3)(:,$)), m, y) +end diff --git a/Task/Find-the-last-Sunday-of-each-month/Pluto/find-the-last-sunday-of-each-month.pluto b/Task/Find-the-last-Sunday-of-each-month/Pluto/find-the-last-sunday-of-each-month.pluto new file mode 100644 index 0000000000..01bbeb61e5 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Pluto/find-the-last-sunday-of-each-month.pluto @@ -0,0 +1,12 @@ +local fmt = require "fmt" + +assert(#arg == 1, "Please pass just the year to be processed.") +local year = arg[1] +print($"The dates of the last Sundays in the month for {year} are:") +for m = 1, 12 do + local d = fmt.month(m, year) + local t = os.time({year = year, month = m, day = d}) + local wd = tonumber(os.date("%u", t)) + if wd < 7 then t -= 86400 * wd end + print(os.date("%F", t)) +end diff --git a/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-1.ps1 b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-1.ps1 new file mode 100644 index 0000000000..0f7a15656c --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-1.ps1 @@ -0,0 +1,13 @@ +function last-dayofweek { + param( + [Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year, + [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek + ) + $date = (Get-Date -Year $year -Month 1 -Day 1) + while($date.DayOfWeek -ne $dayofweek) {$date = $date.AddDays(1)} + while($date.year -eq $year) { + if($date.Month -ne $date.AddDays(7).Month) {$date.ToString("yyyy-dd-MM")} + $date = $date.AddDays(7) + } +} +last-dayofweek 2013 "Sunday" diff --git a/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-2.ps1 b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-2.ps1 new file mode 100644 index 0000000000..303610c8ea --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-2.ps1 @@ -0,0 +1,97 @@ +function Get-Date0fDayOfWeek +{ + [CmdletBinding(DefaultParameterSetName="None")] + [OutputType([datetime])] + Param + ( + [Parameter(Mandatory=$false, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [ValidateRange(1,12)] + [int] + $Month = (Get-Date).Month, + + [Parameter(Mandatory=$false, + ValueFromPipelineByPropertyName=$true, + Position=1)] + [ValidateRange(1,9999)] + [int] + $Year = (Get-Date).Year, + + [Parameter(Mandatory=$true, ParameterSetName="Sunday")] + [switch] + $Sunday, + + [Parameter(Mandatory=$true, ParameterSetName="Monday")] + [switch] + $Monday, + + [Parameter(Mandatory=$true, ParameterSetName="Tuesday")] + [switch] + $Tuesday, + + [Parameter(Mandatory=$true, ParameterSetName="Wednesday")] + [switch] + $Wednesday, + + [Parameter(Mandatory=$true, ParameterSetName="Thursday")] + [switch] + $Thursday, + + [Parameter(Mandatory=$true, ParameterSetName="Friday")] + [switch] + $Friday, + + [Parameter(Mandatory=$true, ParameterSetName="Saturday")] + [switch] + $Saturday, + + [switch] + $First, + + [switch] + $Last, + + [switch] + $AsString, + + [Parameter(Mandatory=$false)] + [ValidateNotNullOrEmpty()] + [string] + $Format = "dd-MMM-yyyy" + ) + + Process + { + [datetime[]]$dates = 1..[DateTime]::DaysInMonth($Year,$Month) | ForEach-Object { + Get-Date -Year $Year -Month $Month -Day $_ -Hour 0 -Minute 0 -Second 0 | + Where-Object -Property DayOfWeek -Match $PSCmdlet.ParameterSetName + } + + if ($First -or $Last) + { + if ($AsString) + { + if ($First) {$dates[0].ToString($Format)} + if ($Last) {$dates[-1].ToString($Format)} + } + else + { + if ($First) {$dates[0]} + if ($Last) {$dates[-1]} + } + } + else + { + if ($AsString) + { + $dates | ForEach-Object {$_.ToString($Format)} + } + else + { + $dates + } + } + } +} diff --git a/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-3.ps1 b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-3.ps1 new file mode 100644 index 0000000000..5c795b34d7 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-3.ps1 @@ -0,0 +1 @@ +1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday diff --git a/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-4.ps1 b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-4.ps1 new file mode 100644 index 0000000000..8f9f685714 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-4.ps1 @@ -0,0 +1 @@ +1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString diff --git a/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-5.ps1 b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-5.ps1 new file mode 100644 index 0000000000..14cd7511db --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/PowerShell/find-the-last-sunday-of-each-month-5.ps1 @@ -0,0 +1 @@ +1..12 | Get-Date0fDayOfWeek -Year 2013 -Last -Sunday -AsString -Format yyyy-MM-dd diff --git a/Task/Find-the-last-Sunday-of-each-month/Rebol/find-the-last-sunday-of-each-month.rebol b/Task/Find-the-last-Sunday-of-each-month/Rebol/find-the-last-sunday-of-each-month.rebol new file mode 100644 index 0000000000..fcc225b877 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Rebol/find-the-last-sunday-of-each-month.rebol @@ -0,0 +1,17 @@ +#!/usr/bin/env rebol +last-sundays-of-year: function [ + "Return series of last sunday (date!) for each month of the year" + year [integer!] "which year?" + ][ + d: to date! reduce [1 1 year] ; start with first day of year + collect [ + repeat month 12 [ + d/month: month + 1 ; move to start of next month + keep d - d/weekday ; calculate last sunday & keep + ] + ] +] + +foreach sunday last-sundays-of-year to-integer any [system/script/args now/year][ + print sunday +] diff --git a/Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vbs b/Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vbs new file mode 100644 index 0000000000..b129959f41 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/VBScript/find-the-last-sunday-of-each-month.vbs @@ -0,0 +1,6 @@ +strYear = WScript.StdIn.ReadLine + +For i = 1 To 12 + d = DateSerial(strYear, i + 1, 1) - 1 + WScript.Echo d - Weekday(d) + 1 +Next diff --git a/Task/Find-the-missing-permutation/Ada/find-the-missing-permutation.adb b/Task/Find-the-missing-permutation/Ada/find-the-missing-permutation.adb new file mode 100644 index 0000000000..0e9e809a6c --- /dev/null +++ b/Task/Find-the-missing-permutation/Ada/find-the-missing-permutation.adb @@ -0,0 +1,51 @@ +with Ada.Text_IO; +procedure Missing_Permutations is + subtype Permutation_Character is Character range 'A' .. 'D'; + + Character_Count : constant := + 1 + Permutation_Character'Pos (Permutation_Character'Last) + - Permutation_Character'Pos (Permutation_Character'First); + + type Permutation_String is + array (1 .. Character_Count) of Permutation_Character; + + procedure Put (Item : Permutation_String) is + begin + for I in Item'Range loop + Ada.Text_IO.Put (Item (I)); + end loop; + end Put; + + Given_Permutations : array (Positive range <>) of Permutation_String := + ("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", + "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", + "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", + "BADC", "BDAC", "CBDA", "DBCA", "DCAB"); + + Count : array (Permutation_Character, 1 .. Character_Count) of Natural + := (others => (others => 0)); + Max_Count : Positive := 1; + + Missing_Permutation : Permutation_String; +begin + for I in Given_Permutations'Range loop + for Pos in 1 .. Character_Count loop + Count (Given_Permutations (I) (Pos), Pos) := + Count (Given_Permutations (I) (Pos), Pos) + 1; + if Count (Given_Permutations (I) (Pos), Pos) > Max_Count then + Max_Count := Count (Given_Permutations (I) (Pos), Pos); + end if; + end loop; + end loop; + + for Char in Permutation_Character loop + for Pos in 1 .. Character_Count loop + if Count (Char, Pos) < Max_Count then + Missing_Permutation (Pos) := Char; + end if; + end loop; + end loop; + + Ada.Text_IO.Put_Line ("Missing Permutation:"); + Put (Missing_Permutation); +end Missing_Permutations; diff --git a/Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.ps1 b/Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.ps1 new file mode 100644 index 0000000000..22c6bcf55c --- /dev/null +++ b/Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.ps1 @@ -0,0 +1,56 @@ +function permutation ($array) { + function generate($n, $array, $A) { + if($n -eq 1) { + $array[$A] -join '' + } + else{ + for( $i = 0; $i -lt ($n - 1); $i += 1) { + generate ($n - 1) $array $A + if($n % 2 -eq 0){ + $i1, $i2 = $i, ($n-1) + $temp = $A[$i1] + $A[$i1] = $A[$i2] + $A[$i2] = $temp + } + else{ + $i1, $i2 = 0, ($n-1) + $temp = $A[$i1] + $A[$i1] = $A[$i2] + $A[$i2] = $temp + } + } + generate ($n - 1) $array $A + } + } + $n = $array.Count + if($n -gt 0) { + (generate $n $array (0..($n-1))) + } else {$array} +} +$perm = permutation @('A','B','C', 'D') +$find = @( +"ABCD" +"CABD" +"ACDB" +"DACB" +"BCDA" +"ACBD" +"ADCB" +"CDAB" +"DABC" +"BCAD" +"CADB" +"CDBA" +"CBAD" +"ABDC" +"ADBC" +"BDCA" +"DCBA" +"BACD" +"BADC" +"BDAC" +"CBDA" +"DBCA" +"DCAB" +) +$perm | where{-not $find.Contains($_)} diff --git a/Task/Find-the-missing-permutation/VBScript/find-the-missing-permutation.vbs b/Task/Find-the-missing-permutation/VBScript/find-the-missing-permutation.vbs new file mode 100644 index 0000000000..3837b728dd --- /dev/null +++ b/Task/Find-the-missing-permutation/VBScript/find-the-missing-permutation.vbs @@ -0,0 +1,24 @@ +arrp = Array("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",_ + "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",_ + "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",_ + "BADC", "BDAC", "CBDA", "DBCA", "DCAB") + +Dim col(4) + +'supposes that a complete column have 6 of each letter. +target = (6*Asc("A")) + (6*Asc("B")) + (6*Asc("C")) + (6*Asc("D")) + +missing = "" + +For i = 0 To UBound(arrp) + For j = 1 To 4 + col(j) = col(j) + Asc(Mid(arrp(i),j,1)) + Next +Next + +For k = 1 To 4 + n = target - col(k) + missing = missing & Chr(n) +Next + +WScript.StdOut.WriteLine missing diff --git a/Task/First-class-functions-Use-numbers-analogously/Ada/first-class-functions-use-numbers-analogously.adb b/Task/First-class-functions-Use-numbers-analogously/Ada/first-class-functions-use-numbers-analogously.adb new file mode 100644 index 0000000000..7f8cfa89ec --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Ada/first-class-functions-use-numbers-analogously.adb @@ -0,0 +1,22 @@ +with Ada.Text_IO; +procedure Firstclass is + generic + n1, n2 : Float; + function Multiplier (m : Float) return Float; + function Multiplier (m : Float) return Float is + begin + return n1 * n2 * m; + end Multiplier; + + num, inv : array (1 .. 3) of Float; +begin + num := (2.0, 4.0, 6.0); + inv := (1.0/2.0, 1.0/4.0, 1.0/6.0); + for i in num'Range loop + declare + function new_function is new Multiplier (num (i), inv (i)); + begin + Ada.Text_IO.Put_Line (Float'Image (new_function (0.5))); + end; + end loop; +end Firstclass; diff --git a/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl b/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl index cd1b9c158a..b4f623cf67 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl +++ b/Task/First-class-functions-Use-numbers-analogously/Erlang/first-class-functions-use-numbers-analogously.erl @@ -3,10 +3,10 @@ -export( [task/0] ). task() -> - X = 2.0, Xi = 0.5, Y = 4.0, Yi = 0.25, Z = X + Y, Zi = 1.0 / (X + Y), - As = [X, Y, Z], - Bs = [Xi, Yi, Zi], - [io:fwrite( "Value: 2.5 Result: ~p~n", [(multiplier(A, B))(2.5)]) || {A, B} <- lists:zip(As, Bs)]. + X = 2.0, Xi = 0.5, Y = 4.0, Yi = 0.25, Z = X + Y, Zi = 1.0 / (X + Y), + As = [X, Y, Z], + Bs = [Xi, Yi, Zi], + [io:fwrite( "Value: 2.5 Result: ~p~n", [(multiplier(A, B))(2.5)]) || {A, B} <- lists:zip(As, Bs)]. diff --git a/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java b/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java index 69c063ad4d..9444b5b58d 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java +++ b/Task/First-class-functions-Use-numbers-analogously/Java/first-class-functions-use-numbers-analogously.java @@ -4,21 +4,21 @@ import java.util.function.Function; public final class FirstClassFunctionsUseNumbersAnalogously { - public static void main(String[] args) { - final double x = 2.0, xi = 0.5, - y = 4.0, yi = 0.25, - z = x + y, zi = 1.0 / ( x + y ); + public static void main(String[] args) { + final double x = 2.0, xi = 0.5, + y = 4.0, yi = 0.25, + z = x + y, zi = 1.0 / ( x + y ); - List list = List.of( x, y, z ); - List inverseList = List.of( xi, yi, zi ); - - BiFunction> multiplier = (a, b) -> product -> a * b * product; - - for ( int i = 0; i < list.size(); i++ ) { - Function multiply = multiplier.apply(list.get(i), inverseList.get(i)); - final double argument = (double) ( i + 1 ); - System.out.println(multiply.apply(argument)); - } - } + List list = List.of( x, y, z ); + List inverseList = List.of( xi, yi, zi ); + + BiFunction> multiplier = (a, b) -> product -> a * b * product; + + for ( int i = 0; i < list.size(); i++ ) { + Function multiply = multiplier.apply(list.get(i), inverseList.get(i)); + final double argument = (double) ( i + 1 ); + System.out.println(multiply.apply(argument)); + } + } } diff --git a/Task/First-class-functions-Use-numbers-analogously/Phix/first-class-functions-use-numbers-analogously-1.phix b/Task/First-class-functions-Use-numbers-analogously/Phix/first-class-functions-use-numbers-analogously-1.phix index e2c3580a16..7558210000 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Phix/first-class-functions-use-numbers-analogously-1.phix +++ b/Task/First-class-functions-Use-numbers-analogously/Phix/first-class-functions-use-numbers-analogously-1.phix @@ -1,25 +1,23 @@ -(phixonline)--> - with javascript_semantics - sequence mtable = {} +with javascript_semantics +sequence mtable = {} - function multiplier(atom n1, atom n2) - mtable = append(mtable,{n1,n2}) - return length(mtable) - end function +function multiplier(atom n1, atom n2) + mtable = append(mtable,{n1,n2}) + return length(mtable) +end function - function call_multiplier(integer f, atom m) - atom {n1,n2} = mtable[f] - return n1*n2*m - end function +function call_multiplier(integer f, atom m) + atom {n1,n2} = mtable[f] + return n1*n2*m +end function - constant x = 2, - xi = 0.5, - y = 4, - yi = 0.25, - z = x + y, - zi = 1 / ( x + y ) +constant x = 2, + xi = 0.5, + y = 4, + yi = 0.25, + z = x + y, + zi = 1 / ( x + y ) - ?call_multiplier(multiplier(x,xi),0.5) - ?call_multiplier(multiplier(y,yi),0.5) - ?call_multiplier(multiplier(z,zi),0.5) - - with javascript_semantics - sequence ctable = {} +with javascript_semantics +sequence ctable = {} - function compose(integer f, g) - ctable = append(ctable,{f,g}) - integer cdx = length(ctable) - return cdx - end function +function compose(integer f, g) + ctable = append(ctable,{f,g}) + integer cdx = length(ctable) + return cdx +end function - function call_composite(integer cdx, atom x) - integer {f,g} = ctable[cdx] - return f(g(x)) - end function +function call_composite(integer cdx, atom x) + integer {f,g} = ctable[cdx] + return f(g(x)) +end function - function plus1(atom x) - return x+1 - end function +function plus1(atom x) + return x+1 +end function - function halve(atom x) - return x/2 - end function +function halve(atom x) + return x/2 +end function - constant m = compose(halve,plus1) +constant m = compose(halve,plus1) - ?call_composite(m,1) -- displays 1 - ?call_composite(m,4) -- displays 2.5 - - sequence ctable = {} +sequence ctable = {} - function compose(integer f, g) - ctable = append(ctable,{f,g}) - integer cdx = length(ctable) - return cdx - end function +function compose(integer f, g) + ctable = append(ctable,{f,g}) + integer cdx = length(ctable) + return cdx +end function - function call_composite(integer cdx, atom x) - integer {f,g} = ctable[cdx] - return f(g(x)) - end function +function call_composite(integer cdx, atom x) + integer {f,g} = ctable[cdx] + return f(g(x)) +end function - function plus1(atom x) - return x+1 - end function +function plus1(atom x) + return x+1 +end function - function halve(atom x) - return x/2 - end function +function halve(atom x) + return x/2 +end function - constant m = compose(halve,plus1) +constant m = compose(halve,plus1) - ?call_composite(m,1) -- displays 1 - ?call_composite(m,4) -- displays 2.5 - - printf(1,"%09.3f\n",7.125) - - with javascript_semantics - function fwd_diff_n(sequence s, integer order) - assert(order<length(s)) - s = deep_copy(s) - for i=1 to order do - for j=1 to length(s)-1 do - s[j] = s[j+1]-s[j] - end for - s = s[1..-2] - end for - return s - end function +with javascript_semantics +function fwd_diff_n(sequence s, integer order) + assert(orderconstant s = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73} - for i=1 to 9 do - ?fwd_diff_n(s,i) - end for - %d/%d (removed %d)".fmt(xn,xd,yn,yd,k+1)); - } - } + foreach k in ([0..8]){ + yn,yd := rn[k],rd[k]; + if(yn!=0 and yd!=0 and + xn.toFloat()/xd.toFloat() == yn.toFloat()/yd.toFloat()){ + count+=1; + omitted[k]+=1; + if(count<=12) + println("%d/%d --> %d/%d (removed %d)".fmt(xn,xd,yn,yd,k+1)); + } + } } } println("%d-digit fractions found: %d, omitted %s\n" diff --git a/Task/Fractran/Ada/fractran.adb b/Task/Fractran/Ada/fractran.adb new file mode 100644 index 0000000000..b80338cfca --- /dev/null +++ b/Task/Fractran/Ada/fractran.adb @@ -0,0 +1,43 @@ +with Ada.Text_IO; + +procedure Fractan is + + type Fraction is record Nom: Natural; Denom: Positive; end record; + type Frac_Arr is array(Positive range <>) of Fraction; + + function "/" (N: Natural; D: Positive) return Fraction is + Frac: Fraction := (Nom => N, Denom => D); + begin + return Frac; + end "/"; + + procedure F(List: Frac_Arr; Start: Positive; Max_Steps: Natural) is + N: Positive := Start; + J: Positive; + begin + Ada.Text_IO.Put(" 0:" & Integer'Image(N) & " "); + for I in 1 .. Max_Steps loop + J := List'First; + loop + if N mod List(J).Denom = 0 then + N := (N/List(J).Denom) * List(J).Nom; + exit; -- found fraction + elsif J >= List'Last then + return; -- did try out all fractions + else + J := J + 1; -- try the next fraction + end if; + end loop; + Ada.Text_IO.Put(Integer'Image(I) & ":" & Integer'Image(N) & " "); + end loop; + end F; + +begin + -- F((2/3, 7/2, 1/5, 1/7, 1/9, 1/4, 1/8), 2, 100); + -- output would be "0: 2 1: 7 2: 1" and then terminate + + F((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, 15); + -- output is "0: 2 1: 15 2: 825 3: 725 ... 14: 132 15: 116" +end Fractan; diff --git a/Task/Fractran/Batch-File/fractran.bat b/Task/Fractran/Batch-File/fractran.bat index 956eee44cc..75fe098b0a 100644 --- a/Task/Fractran/Batch-File/fractran.bat +++ b/Task/Fractran/Batch-File/fractran.bat @@ -1,41 +1,41 @@ @echo off setlocal enabledelayedexpansion - ::Set the inputs + ::Set the inputs set "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" set "n=2" - ::Basic validation of code + ::Basic validation of code for %%. in (!code!) do ( - echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code + echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code ) - ::Validate the input + ::Validate the input set /a "tst=1*!n!" 2>nul if !tst! lss 0 goto error_input if !tst! equ 0 (if not "!n!"=="0" (goto error_input)) - ::Set the limit outputs - set limit=20 + ::Set the limit outputs + set limit=20 - ::Execute the code + ::Execute the code echo.Input: -echo. !n! +echo. !n! echo.Output: for /l %%? in (1,1,!limit!) do ( - set shouldwehalt=1 - for %%A in (!code!) do ( - for /f "tokens=1,2 delims=/" %%B in ("%%A") do ( - set /a "tst=!n! %% %%C" - if !tst! equ 0 ( - if !shouldwehalt! equ 1 ( - set shouldwehalt=0 - set /a "n=n*%%B/%%C" - echo. !n! - ) - ) - ) - ) - if !shouldwehalt! equ 1 goto halt + set shouldwehalt=1 + for %%A in (!code!) do ( + for /f "tokens=1,2 delims=/" %%B in ("%%A") do ( + set /a "tst=!n! %% %%C" + if !tst! equ 0 ( + if !shouldwehalt! equ 1 ( + set shouldwehalt=0 + set /a "n=n*%%B/%%C" + echo. !n! + ) + ) + ) + ) + if !shouldwehalt! equ 1 goto halt ) :halt diff --git a/Task/Fractran/C++/fractran.cpp b/Task/Fractran/C++/fractran.cpp index 0f68fa192b..a3d5f34195 100644 --- a/Task/Fractran/C++/fractran.cpp +++ b/Task/Fractran/C++/fractran.cpp @@ -16,44 +16,44 @@ public: copy( istream_iterator( iss ), istream_iterator(), back_inserter >( tmp ) ); string item; vector< pair > v; - pair a; - for( vector::iterator i = tmp.begin(); i != tmp.end(); i++ ) - { - string::size_type pos = ( *i ).find( '/', 0 ); - if( pos != std::string::npos ) - { - a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); - v.push_back( a ); - } - } - - exec( &v ); + pair a; + for( vector::iterator i = tmp.begin(); i != tmp.end(); i++ ) + { + string::size_type pos = ( *i ).find( '/', 0 ); + if( pos != std::string::npos ) + { + a = make_pair( atof( ( ( *i ).substr( 0, pos ) ).c_str() ), atof( ( ( *i ).substr( pos + 1 ) ).c_str() ) ); + v.push_back( a ); + } + } + + exec( &v ); } private: void exec( vector< pair >* v ) { - int cnt = 0; - while( cnt < limit ) - { - cout << cnt << " : " << start << "\n"; - cnt++; - vector< pair >::iterator it = v->begin(); - bool found = false; float r; - while( it != v->end() ) - { - r = start * ( ( *it ).first / ( *it ).second ); - if( r == floor( r ) ) - { - found = true; - break; - } - ++it; - } + int cnt = 0; + while( cnt < limit ) + { + cout << cnt << " : " << start << "\n"; + cnt++; + vector< pair >::iterator it = v->begin(); + bool found = false; float r; + while( it != v->end() ) + { + r = start * ( ( *it ).first / ( *it ).second ); + if( r == floor( r ) ) + { + found = true; + break; + } + ++it; + } - if( found ) start = ( int )r; - else break; - } + if( found ) start = ( int )r; + else break; + } } int start, limit; }; diff --git a/Task/Fractran/C/fractran.c b/Task/Fractran/C/fractran.c index 6931d47852..1119b05a77 100644 --- a/Task/Fractran/C/fractran.c +++ b/Task/Fractran/C/fractran.c @@ -4,62 +4,62 @@ typedef struct frac_s *frac; struct frac_s { - int n, d; - frac next; + int n, d; + frac next; }; frac parse(char *s) { - int offset = 0; - struct frac_s h = {0}, *p = &h; + int offset = 0; + struct frac_s h = {0}, *p = &h; - while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { - s += offset; - p = p->next = malloc(sizeof *p); - *p = h; - p->next = 0; - } + while (2 == sscanf(s, "%d/%d%n", &h.n, &h.d, &offset)) { + s += offset; + p = p->next = malloc(sizeof *p); + *p = h; + p->next = 0; + } - return h.next; + return h.next; } int run(int v, char *s) { - frac n, p = parse(s); - mpz_t val; - mpz_init_set_ui(val, v); + frac n, p = parse(s); + mpz_t val; + mpz_init_set_ui(val, v); -loop: n = p; - if (mpz_popcount(val) == 1) - gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); - else - gmp_printf(" %Zd", val); +loop: n = p; + if (mpz_popcount(val) == 1) + gmp_printf("\n[2^%d = %Zd]", mpz_scan1(val, 0), val); + else + gmp_printf(" %Zd", val); - for (n = p; n; n = n->next) { - // assuming the fractions are not reducible - if (!mpz_divisible_ui_p(val, n->d)) continue; + for (n = p; n; n = n->next) { + // assuming the fractions are not reducible + if (!mpz_divisible_ui_p(val, n->d)) continue; - mpz_divexact_ui(val, val, n->d); - mpz_mul_ui(val, val, n->n); - goto loop; - } + mpz_divexact_ui(val, val, n->d); + mpz_mul_ui(val, val, n->n); + goto loop; + } - gmp_printf("\nhalt: %Zd has no divisors\n", val); + gmp_printf("\nhalt: %Zd has no divisors\n", val); - mpz_clear(val); - while (p) { - n = p->next; - free(p); - p = n; - } + mpz_clear(val); + while (p) { + n = p->next; + free(p); + p = n; + } - return 0; + return 0; } int main(void) { - run(2, "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"); + run(2, "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"); - return 0; + return 0; } diff --git a/Task/Fractran/Fortran/fractran-2.f b/Task/Fractran/Fortran/fractran-2.f index 6a079ed26a..0422be02be 100644 --- a/Task/Fractran/Fortran/fractran-2.f +++ b/Task/Fractran/Fortran/fractran-2.f @@ -1,49 +1,49 @@ - INTEGER FUNCTION FRACTRAN(N,P,Q,M) !Notion devised by J. H. Conway. + INTEGER FUNCTION FRACTRAN(N,P,Q,M) !Notion devised by J. H. Conway. Careful: the rule is N*P/Q being integer. N*6/3 is integer always because this is N*2/1, but 3 may not divide N. Could check GCD(P,Q), dividing out the common denominator so MOD(N,Q) works. - INTEGER*8 N !The work variable. Modified! - INTEGER M !The number of fractions supplied. + INTEGER*8 N !The work variable. Modified! + INTEGER M !The number of fractions supplied. INTEGER P(M),Q(M)!The terms of the fractions. - INTEGER I !A stepper. - DO I = 1,M !Search the supplied fractions, P(i)/Q(i). - IF (MOD(N,Q(I)).EQ.0) THEN !Does the denominator divide N? - N = N/Q(I)*P(I) !Yes, compute N*P/Q but trying to dodge overflow. - FRACTRAN = I !Report the hit. - RETURN !Done! - END IF !Otherwise, - END DO !Try the next fraction in the order supplied. - FRACTRAN = 0 !No hit. - END FUNCTION FRACTRAN !That's it! Even so, "Turing complete"... + INTEGER I !A stepper. + DO I = 1,M !Search the supplied fractions, P(i)/Q(i). + IF (MOD(N,Q(I)).EQ.0) THEN !Does the denominator divide N? + N = N/Q(I)*P(I) !Yes, compute N*P/Q but trying to dodge overflow. + FRACTRAN = I !Report the hit. + RETURN !Done! + END IF !Otherwise, + END DO !Try the next fraction in the order supplied. + FRACTRAN = 0 !No hit. + END FUNCTION FRACTRAN !That's it! Even so, "Turing complete"... PROGRAM POKE - INTEGER FRACTRAN !Not the default type of function. - INTEGER P(66),Q(66) !Holds the fractions as P(i)/Q(i). - INTEGER*8 N !The working number. - INTEGER I,IT,L,M !Assistants. + INTEGER FRACTRAN !Not the default type of function. + INTEGER P(66),Q(66) !Holds the fractions as P(i)/Q(i). + INTEGER*8 N !The working number. + INTEGER I,IT,L,M !Assistants. - WRITE (6,1) !Announce. + WRITE (6,1) !Announce. 1 FORMAT ("Interpreter for J.H. Conway's FRACTRAN language.") Chew into an example programme. - OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. - READ (10,*) L !I need to know this without having to scan the input. - WRITE (6,2) L !Reveal in case of trouble. - 2 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. - READ (10,*) (P(I),Q(I),I = 1,L) !Ask for the specified number of P,Q pairs. - WRITE (6,3) (P(I),Q(I),I = 1,L) !Show what turned up. - 3 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. - READ (10,*) N,M !The start value, and the step limit. - CLOSE (10) !Finished with input. - WRITE (6,4) N,M !Hopefully, all went well. + OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. + READ (10,*) L !I need to know this without having to scan the input. + WRITE (6,2) L !Reveal in case of trouble. + 2 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. + READ (10,*) (P(I),Q(I),I = 1,L) !Ask for the specified number of P,Q pairs. + WRITE (6,3) (P(I),Q(I),I = 1,L) !Show what turned up. + 3 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. + READ (10,*) N,M !The start value, and the step limit. + CLOSE (10) !Finished with input. + WRITE (6,4) N,M !Hopefully, all went well. 4 FORMAT ("Start with N = ",I0,", step limit ",I0) Commence. - WRITE (6,10) 0,N !Splat a heading. - 10 FORMAT (/," Step #F: N",/,I6,4X,": ",I0) !Matched FORMAT 11. - DO I = 1,M !Here we go! - IT = FRACTRAN(N,P,Q,L) !Do it! - WRITE (6,11) I,IT,N !Show it! - 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. - IF (IT.LE.0) EXIT !No hit, so quit. - END DO !The next step. - END !Whee! + WRITE (6,10) 0,N !Splat a heading. + 10 FORMAT (/," Step #F: N",/,I6,4X,": ",I0) !Matched FORMAT 11. + DO I = 1,M !Here we go! + IT = FRACTRAN(N,P,Q,L) !Do it! + WRITE (6,11) I,IT,N !Show it! + 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. + IF (IT.LE.0) EXIT !No hit, so quit. + END DO !The next step. + END !Whee! diff --git a/Task/Fractran/Fortran/fractran-3.f b/Task/Fractran/Fortran/fractran-3.f index 1a409a7c11..8fdab8dd61 100644 --- a/Task/Fractran/Fortran/fractran-3.f +++ b/Task/Fractran/Fortran/fractran-3.f @@ -1,11 +1,11 @@ - DO I = 1,M !Here we go! - IT = FRACTRAN(N,P,Q,L) !Do it! - IF (POPCNT(N).EQ.1) WRITE (6,11) I,IT,N !Show it! - 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. - IF (IT.LE.0) EXIT !No hit, so quit. - IF (N.LE.0) THEN !Otherwise, worry about overflow. - WRITE (6,*) "Integer overflow!" !Justified. The test is not certain. - WRITE (6,11) I,IT,N !Alas, the step failed. - EXIT !Give in. - END IF !So much for overflow. - END DO !The next step. + DO I = 1,M !Here we go! + IT = FRACTRAN(N,P,Q,L) !Do it! + IF (POPCNT(N).EQ.1) WRITE (6,11) I,IT,N !Show it! + 11 FORMAT (I6,I4,": ",I0) !N last, as it may be big. + IF (IT.LE.0) EXIT !No hit, so quit. + IF (N.LE.0) THEN !Otherwise, worry about overflow. + WRITE (6,*) "Integer overflow!" !Justified. The test is not certain. + WRITE (6,11) I,IT,N !Alas, the step failed. + EXIT !Give in. + END IF !So much for overflow. + END DO !The next step. diff --git a/Task/Fractran/Fortran/fractran-4.f b/Task/Fractran/Fortran/fractran-4.f index 367c6d7833..7e4093fbcd 100644 --- a/Task/Fractran/Fortran/fractran-4.f +++ b/Task/Fractran/Fortran/fractran-4.f @@ -1,187 +1,187 @@ - MODULE CONWAYSIDEA !Notion devised by J. H. Conway. - USE PRIMEBAG !This is a common need. - INTEGER LASTP,ENUFF !Some size allowances. - PARAMETER (LASTP = 66, ENUFF = 66) !Should suffice for the example in mind. - INTEGER NPPOW(1:LASTP) !Represent N as a collection of powers of prime numbers. - TYPE FACTORED !But represent P and Q of freaction = P/Q - INTEGER PNUM(0:LASTP) !As a list of prime number indices with PNUM(0) the count. - INTEGER PPOW(LASTP) !And the powers. for the fingered primes. - END TYPE FACTORED !Rather than as a simple number multiplied out. - TYPE(FACTORED) FP(ENUFF),FQ(ENUFF) !Thus represent a factored fraction, P(i)/Q(i). - INTEGER PLIVE(ENUFF),NL !Helps subroutine SHOWN display NPPOW. - CONTAINS !Now for the details. - SUBROUTINE SHOWFACTORS(N) !First, to show an internal data structure. - TYPE(FACTORED) N !It is supplied as a list of prime factors. - INTEGER I !A stepper. - DO I = 1,N.PNUM(0) !Step along the list. - IF (I.GT.1) WRITE (MSG,"('x',$)") !Append a glyph for "multiply". - WRITE (MSG,"(I0,$)") PRIME(N.PNUM(I)) !The prime fingered in the list. - IF (N.PPOW(I).GT.1) WRITE (MSG,"('^',I0,$)") N.PPOW(I) !With an interesting power? - END DO !On to the next element in the list. - WRITE (MSG,1) N.PNUM(0) !End the line - 1 FORMAT (": Factor count ",I0) !With a count of prime factors. - END SUBROUTINE SHOWFACTORS !Hopefully, this will not be needed often. + MODULE CONWAYSIDEA !Notion devised by J. H. Conway. + USE PRIMEBAG !This is a common need. + INTEGER LASTP,ENUFF !Some size allowances. + PARAMETER (LASTP = 66, ENUFF = 66) !Should suffice for the example in mind. + INTEGER NPPOW(1:LASTP) !Represent N as a collection of powers of prime numbers. + TYPE FACTORED !But represent P and Q of freaction = P/Q + INTEGER PNUM(0:LASTP) !As a list of prime number indices with PNUM(0) the count. + INTEGER PPOW(LASTP) !And the powers. for the fingered primes. + END TYPE FACTORED !Rather than as a simple number multiplied out. + TYPE(FACTORED) FP(ENUFF),FQ(ENUFF) !Thus represent a factored fraction, P(i)/Q(i). + INTEGER PLIVE(ENUFF),NL !Helps subroutine SHOWN display NPPOW. + CONTAINS !Now for the details. + SUBROUTINE SHOWFACTORS(N) !First, to show an internal data structure. + TYPE(FACTORED) N !It is supplied as a list of prime factors. + INTEGER I !A stepper. + DO I = 1,N.PNUM(0) !Step along the list. + IF (I.GT.1) WRITE (MSG,"('x',$)") !Append a glyph for "multiply". + WRITE (MSG,"(I0,$)") PRIME(N.PNUM(I)) !The prime fingered in the list. + IF (N.PPOW(I).GT.1) WRITE (MSG,"('^',I0,$)") N.PPOW(I) !With an interesting power? + END DO !On to the next element in the list. + WRITE (MSG,1) N.PNUM(0) !End the line + 1 FORMAT (": Factor count ",I0) !With a count of prime factors. + END SUBROUTINE SHOWFACTORS !Hopefully, this will not be needed often. - TYPE(FACTORED) FUNCTION FACTOR(IT) !Into a list of primes and their powers. - INTEGER IT,N !The number and a copy to damage. - INTEGER P,POW !A stepper and a power. - INTEGER F,NF !A factor and a counter. - IF (IT.LE.0) STOP "Factor only positive numbers!" !Or else... - N = IT !A copy I can damage. - NF = 0 !No factors found. - P = 0 !Because no primes have been tried. - PP:DO WHILE (N.GT.1) !Step through the possibilities. - P = P + 1 !Another prime impends. - F = PRIME(P) !Grab a possible factor. - POW = 0 !It has no power yet. - FP:DO WHILE(MOD(N,F).EQ.0) !Well? - POW = POW + 1 !Count a factor.. - N = N/F !Reduce the number. - END DO FP !The P'th prime's power's produced. - IF (POW.GT.0) THEN !So, was it a factor? - IF (NF.GE.LASTP) THEN !Yes. Have I room in the list? - WRITE (MSG,1) IT,LASTP !Alas. + TYPE(FACTORED) FUNCTION FACTOR(IT) !Into a list of primes and their powers. + INTEGER IT,N !The number and a copy to damage. + INTEGER P,POW !A stepper and a power. + INTEGER F,NF !A factor and a counter. + IF (IT.LE.0) STOP "Factor only positive numbers!" !Or else... + N = IT !A copy I can damage. + NF = 0 !No factors found. + P = 0 !Because no primes have been tried. + PP:DO WHILE (N.GT.1) !Step through the possibilities. + P = P + 1 !Another prime impends. + F = PRIME(P) !Grab a possible factor. + POW = 0 !It has no power yet. + FP:DO WHILE(MOD(N,F).EQ.0) !Well? + POW = POW + 1 !Count a factor.. + N = N/F !Reduce the number. + END DO FP !The P'th prime's power's produced. + IF (POW.GT.0) THEN !So, was it a factor? + IF (NF.GE.LASTP) THEN !Yes. Have I room in the list? + WRITE (MSG,1) IT,LASTP !Alas. 1 FORMAT ("Factoring ",I0," but with provision for only ", 1 I0," prime factors!") - FACTOR.PNUM(0) = NF !Place the count so far, + FACTOR.PNUM(0) = NF !Place the count so far, CALL SHOWFACTORS(FACTOR)!So this can be invoked. - STOP "Not enough storage!" !Quite. - END IF !But normally, - NF = NF + 1 !Admit another factor. - FACTOR.PNUM(NF) = P !Identify the prime. NOT the prime itself. - FACTOR.PPOW(NF) = POW !Place its power. - END IF !So much for that factor. - END DO PP !Try another prime, if N > 1 still. - FACTOR.PNUM(0) = NF !Place the count. - END FUNCTION FACTOR !Thus, a list of primes and their powers. + STOP "Not enough storage!" !Quite. + END IF !But normally, + NF = NF + 1 !Admit another factor. + FACTOR.PNUM(NF) = P !Identify the prime. NOT the prime itself. + FACTOR.PPOW(NF) = POW !Place its power. + END IF !So much for that factor. + END DO PP !Try another prime, if N > 1 still. + FACTOR.PNUM(0) = NF !Place the count. + END FUNCTION FACTOR !Thus, a list of primes and their powers. - INTEGER FUNCTION GCD(I,J) !Greatest common divisor. - INTEGER I,J !Of these two integers. - INTEGER N,M,R !Workers. - N = MAX(I,J) !Since I don't want to damage I or J, - M = MIN(I,J) !These copies might as well be the right way around. - 1 R = MOD(N,M) !Divide N by M to get the remainder R. - IF (R.GT.0) THEN !Remainder zero? - N = M !No. Descend a level. - M = R !M-multiplicity has been removed from N. - IF (R .GT. 1) GO TO 1 !No point dividing by one. - END IF !If R = 0, M divides N. - GCD = M !There we are. - END FUNCTION GCD !Euclid lives on! + INTEGER FUNCTION GCD(I,J) !Greatest common divisor. + INTEGER I,J !Of these two integers. + INTEGER N,M,R !Workers. + N = MAX(I,J) !Since I don't want to damage I or J, + M = MIN(I,J) !These copies might as well be the right way around. + 1 R = MOD(N,M) !Divide N by M to get the remainder R. + IF (R.GT.0) THEN !Remainder zero? + N = M !No. Descend a level. + M = R !M-multiplicity has been removed from N. + IF (R .GT. 1) GO TO 1 !No point dividing by one. + END IF !If R = 0, M divides N. + GCD = M !There we are. + END FUNCTION GCD !Euclid lives on! - INTEGER FUNCTION FRACTRAN(L) !Applies Conway's idea to a list of fractions. + INTEGER FUNCTION FRACTRAN(L) !Applies Conway's idea to a list of fractions. Could abandon all parameters since global variables have the details... - INTEGER L !The last fraction to consider. - INTEGER I,NF !Assistants. - DO I = 1,L !Step through the fractions in the order they were given. - NF = FQ(I).PNUM(0) !How many factors are listed in FQ(I)? - IF (ALL(NPPOW(FQ(I).PNUM(1:NF)) !Can N (as NPPOW) be divided by Q (as FQ)? - 1 .GE. FQ(I).PPOW(1:NF))) THEN !By comparing the supplies of prime factors. - FRACTRAN = I !Yes! - NPPOW(FQ(I).PNUM(1:NF)) = NPPOW(FQ(I).PNUM(1:NF)) !Remove prime powers from N - 1 - FQ(I).PPOW(1:NF) !Corresponding to Q. - NF = FP(I).PNUM(0) !Add powers to N - NPPOW(FP(I).PNUM(1:NF)) = NPPOW(FP(I).PNUM(1:NF)) !Corresponding to P. - 1 + FP(I).PPOW(1:NF) !Thus, N = N/Q*P. - RETURN !That's all it takes! No multiplies nor divides! - END IF !So much for that fraction. - END DO !This relies on ALL(zero tests) yielding true, as when Q = 1. - FRACTRAN = 0 !No hit. - END FUNCTION FRACTRAN !No massive multi-precision arithmetic! + INTEGER L !The last fraction to consider. + INTEGER I,NF !Assistants. + DO I = 1,L !Step through the fractions in the order they were given. + NF = FQ(I).PNUM(0) !How many factors are listed in FQ(I)? + IF (ALL(NPPOW(FQ(I).PNUM(1:NF)) !Can N (as NPPOW) be divided by Q (as FQ)? + 1 .GE. FQ(I).PPOW(1:NF))) THEN !By comparing the supplies of prime factors. + FRACTRAN = I !Yes! + NPPOW(FQ(I).PNUM(1:NF)) = NPPOW(FQ(I).PNUM(1:NF)) !Remove prime powers from N + 1 - FQ(I).PPOW(1:NF) !Corresponding to Q. + NF = FP(I).PNUM(0) !Add powers to N + NPPOW(FP(I).PNUM(1:NF)) = NPPOW(FP(I).PNUM(1:NF)) !Corresponding to P. + 1 + FP(I).PPOW(1:NF) !Thus, N = N/Q*P. + RETURN !That's all it takes! No multiplies nor divides! + END IF !So much for that fraction. + END DO !This relies on ALL(zero tests) yielding true, as when Q = 1. + FRACTRAN = 0 !No hit. + END FUNCTION FRACTRAN !No massive multi-precision arithmetic! - SUBROUTINE SHOWN(S,F) !Service routine to show the state after a step is calculated. + SUBROUTINE SHOWN(S,F) !Service routine to show the state after a step is calculated. Could imaging a function I6FMT(23) that returns " 23" and " " for non-positive numbers. Can't do it, as if this were invoked via a WRITE statement, re-entrant use of WRITE usually fails. - INTEGER S,F !Step number, Fraction number. - INTEGER I !A stepper. - CHARACTER*(9+4+1 + NL*6) ALINE !A scratchpad matching FORMAT 103. - WRITE (ALINE,103) S,F,NPPOW(PLIVE(1:NL)) !Show it! - 103 FORMAT (I9,I4,":",I6) !As a sequence of powers of primes. - IF (F.LE.0) ALINE(10:13) = "" !Scrub when no fraction is fingered. - DO I = 1,NL !Step along the live primes. - IF (NPPOW(PLIVE(I)).GT.0) CYCLE !Ignoring the empowered ones. - ALINE(15 + (I - 1)*6:14 + I*6) = "" !Blank out zero powers. - END DO !On to the next. - WRITE (MSG,"(A)") ALINE !Reveal at last. - END SUBROUTINE SHOWN !A struggle. - END MODULE CONWAYSIDEA !Simple... + INTEGER S,F !Step number, Fraction number. + INTEGER I !A stepper. + CHARACTER*(9+4+1 + NL*6) ALINE !A scratchpad matching FORMAT 103. + WRITE (ALINE,103) S,F,NPPOW(PLIVE(1:NL)) !Show it! + 103 FORMAT (I9,I4,":",I6) !As a sequence of powers of primes. + IF (F.LE.0) ALINE(10:13) = "" !Scrub when no fraction is fingered. + DO I = 1,NL !Step along the live primes. + IF (NPPOW(PLIVE(I)).GT.0) CYCLE !Ignoring the empowered ones. + ALINE(15 + (I - 1)*6:14 + I*6) = "" !Blank out zero powers. + END DO !On to the next. + WRITE (MSG,"(A)") ALINE !Reveal at last. + END SUBROUTINE SHOWN !A struggle. + END MODULE CONWAYSIDEA !Simple... PROGRAM POKE - USE CONWAYSIDEA !But, where does he get his ideas from? - INTEGER P(ENUFF),Q(ENUFF) !Holds the fractions as P(i)/Q(i). - INTEGER N !The working number. - INTEGER LF !Last fraction given. - INTEGER LP !Last prime needed. - INTEGER MS !Maximum number of steps. - INTEGER I,IT !Assistants. - LOGICAL*1 PUSED(ENUFF) !Track the usage of prime numbers, + USE CONWAYSIDEA !But, where does he get his ideas from? + INTEGER P(ENUFF),Q(ENUFF) !Holds the fractions as P(i)/Q(i). + INTEGER N !The working number. + INTEGER LF !Last fraction given. + INTEGER LP !Last prime needed. + INTEGER MS !Maximum number of steps. + INTEGER I,IT !Assistants. + LOGICAL*1 PUSED(ENUFF) !Track the usage of prime numbers, - MSG = 6 !Standard output. - WRITE (6,1) !Announce. + MSG = 6 !Standard output. + WRITE (6,1) !Announce. 1 FORMAT ("Interpreter for J. H. Conway's FRACTRAN language.") Chew into an example programme. - 10 OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. - READ (10,*) LF !I need to know this without having to scan the input. - WRITE (MSG,11) LF !Reveal in case of trouble. - 11 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. - READ (10,*) (P(I),Q(I),I = 1,LF) !Ask for the specified number of P,Q pairs. - WRITE (MSG,12) (P(I),Q(I),I = 1,LF) !Show what turned up. - 12 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. - READ (10,*) N,MS !The start value, and the step limit. - CLOSE (10) !Finished with input. - WRITE (MSG,13) N,MS !Hopefully, all went well. + 10 OPEN (10,FILE = "Fractran.txt",STATUS="OLD",ACTION="READ") !Rather than compiled-in stuff. + READ (10,*) LF !I need to know this without having to scan the input. + WRITE (MSG,11) LF !Reveal in case of trouble. + 11 FORMAT (I0," fractions, as follow:") !Should the input evoke problems. + READ (10,*) (P(I),Q(I),I = 1,LF) !Ask for the specified number of P,Q pairs. + WRITE (MSG,12) (P(I),Q(I),I = 1,LF) !Show what turned up. + 12 FORMAT (24(I0,"/",I0:", ")) !As P(i)/Q(i) pairs. The colon means that there will be no trailing comma. + READ (10,*) N,MS !The start value, and the step limit. + CLOSE (10) !Finished with input. + WRITE (MSG,13) N,MS !Hopefully, all went well. 13 FORMAT ("Start with N = ",I0,", step limit ",I0) - IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file of primes!" !Attempt in hope. + IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file of primes!" !Attempt in hope. Convert the starting number to a more convenient form, an array of powers of successive prime numbers. - 20 FP(1) = FACTOR(N) !Borrow one of the factor list variables. - NPPOW = 0 !Clear all prime factor counts. - DO I = 1,FP(1).PNUM(0) !Now find what they are. - NPPOW(FP(1).PNUM(I)) = FP(1).PPOW(I) !Convert from a variable-length list - END DO !To a fixed-length random-access array. - PUSED = NPPOW.GT.0 !Note which primes have been used. - LP = FP(1).PNUM(FP(1).PNUM(0)) !Recall the last prime required. More later. + 20 FP(1) = FACTOR(N) !Borrow one of the factor list variables. + NPPOW = 0 !Clear all prime factor counts. + DO I = 1,FP(1).PNUM(0) !Now find what they are. + NPPOW(FP(1).PNUM(I)) = FP(1).PPOW(I) !Convert from a variable-length list + END DO !To a fixed-length random-access array. + PUSED = NPPOW.GT.0 !Note which primes have been used. + LP = FP(1).PNUM(FP(1).PNUM(0)) !Recall the last prime required. More later. Convert the supplied P(i)/Q(i) fractions to lists of prime number factors and powers in FP(i) and FQ(i). - DO I = 1,LF !Step through the fractions. - IT = GCD(P(I),Q(I)) !Suspicion. - IF (IT.GT.1) THEN !Justified? - WRITE (MSG,21) I,P(I),Q(I),IT !Alas. Complain. The rule is N*(P/Q) being integer. + DO I = 1,LF !Step through the fractions. + IT = GCD(P(I),Q(I)) !Suspicion. + IF (IT.GT.1) THEN !Justified? + WRITE (MSG,21) I,P(I),Q(I),IT !Alas. Complain. The rule is N*(P/Q) being integer. 21 FORMAT ("Fraction ",I3,", ",I0,"/",I0,!N*6/3 is integer always because this is N*2/1, but 3 may not divide N. - 1 " has common factor ",I0,"!") !By removing IT, - P(I) = P(I)/IT !The test need merely check if N is divisible by Q. - Q(I) = Q(I)/IT !And, as N is factorised in NPPOW - END IF !And Q in FQ, subtractions of powers only is needed. - FP(I) = FACTOR(P(I)) !Righto, form the factor list for P. - PUSED(FP(I).PNUM(1:FP(I).PNUM(0))) = .TRUE. !Mark which primes it fingers. - LP = MAX(LP,FP(I).PNUM(FP(I).PNUM(0))) !One has no prime factors: PNUM(0) = 0. - FQ(I) = FACTOR(Q(I)) !And likewise for Q. - PUSED(FQ(I).PNUM(1:FQ(I).PNUM(0))) = .TRUE. !Some primes may be omitted. - LP = MAX(LP,FQ(I).PNUM(FQ(I).PNUM(0))) !If no prime factors, PNUM(0) fingers element zero, which is zero. - END DO !All this messing about saves on multiplication and division. + 1 " has common factor ",I0,"!") !By removing IT, + P(I) = P(I)/IT !The test need merely check if N is divisible by Q. + Q(I) = Q(I)/IT !And, as N is factorised in NPPOW + END IF !And Q in FQ, subtractions of powers only is needed. + FP(I) = FACTOR(P(I)) !Righto, form the factor list for P. + PUSED(FP(I).PNUM(1:FP(I).PNUM(0))) = .TRUE. !Mark which primes it fingers. + LP = MAX(LP,FP(I).PNUM(FP(I).PNUM(0))) !One has no prime factors: PNUM(0) = 0. + FQ(I) = FACTOR(Q(I)) !And likewise for Q. + PUSED(FQ(I).PNUM(1:FQ(I).PNUM(0))) = .TRUE. !Some primes may be omitted. + LP = MAX(LP,FQ(I).PNUM(FQ(I).PNUM(0))) !If no prime factors, PNUM(0) fingers element zero, which is zero. + END DO !All this messing about saves on multiplication and division. Check which primes are in use, preparing an index of live primes.. - NL = 0 !No live primes. - DO I = 1,LP !Check up to the last prime. - IF (PUSED(I)) THEN !This one used? - NL = NL + 1 !Yes. Another. - PLIVE(NL) = I !Fingered. - END IF !So much for that prime. - END DO !On to the next. - WRITE (MSG,22) NL,LP,PRIME(LP) !Remark on usage. - 22 FORMAT ("Require ",I0," primes only, up to Prime(",I0,") = ",I0) !Presume always more than one prime. + NL = 0 !No live primes. + DO I = 1,LP !Check up to the last prime. + IF (PUSED(I)) THEN !This one used? + NL = NL + 1 !Yes. Another. + PLIVE(NL) = I !Fingered. + END IF !So much for that prime. + END DO !On to the next. + WRITE (MSG,22) NL,LP,PRIME(LP) !Remark on usage. + 22 FORMAT ("Require ",I0," primes only, up to Prime(",I0,") = ",I0) !Presume always more than one prime. IF (LP.GT.LASTP) STOP "But, that's too many for array NPPOW!" Cast forth a heading. - 100 WRITE (MSG,101) (PRIME(PLIVE(I)), I = 1,NL) !Splat a heading. - 101 FORMAT (/,14X,"N as powers of prime factors",/, !The prime heading, - 1 5X,"Step F#:",I6) !With primes beneath. - CALL SHOWN(0,0) !Initial state of N as NPPOW. Step zero, no fraction. + 100 WRITE (MSG,101) (PRIME(PLIVE(I)), I = 1,NL) !Splat a heading. + 101 FORMAT (/,14X,"N as powers of prime factors",/, !The prime heading, + 1 5X,"Step F#:",I6) !With primes beneath. + CALL SHOWN(0,0) !Initial state of N as NPPOW. Step zero, no fraction. Commence! - DO I = 1,MS !Here we go! - IT = FRACTRAN(LF) !Do it! - CALL SHOWN(I,IT) !Show it! - IF (IT.LE.0) EXIT !Quit it? - END DO !The next step. + DO I = 1,MS !Here we go! + IT = FRACTRAN(LF) !Do it! + CALL SHOWN(I,IT) !Show it! + IF (IT.LE.0) EXIT !Quit it? + END DO !The next step. Complete! - END !Whee! + END !Whee! diff --git a/Task/Fractran/Fortran/fractran-5.f b/Task/Fractran/Fortran/fractran-5.f index 65e4304ded..8bf75352db 100644 --- a/Task/Fractran/Fortran/fractran-5.f +++ b/Task/Fractran/Fortran/fractran-5.f @@ -1,5 +1,5 @@ - DO I = 1,MS !Here we go! - IT = FRACTRAN(LF) !Do it! - IF (ALL(NPPOW(2:LP).EQ.0)) CALL SHOWN(I,IT) !Show it! - IF (IT.LE.0) EXIT !Quit it? - END DO !The next step. + DO I = 1,MS !Here we go! + IT = FRACTRAN(LF) !Do it! + IF (ALL(NPPOW(2:LP).EQ.0)) CALL SHOWN(I,IT) !Show it! + IF (IT.LE.0) EXIT !Quit it? + END DO !The next step. diff --git a/Task/Fractran/Odin/fractran.odin b/Task/Fractran/Odin/fractran.odin index bae9287c2f..118e1b4333 100644 --- a/Task/Fractran/Odin/fractran.odin +++ b/Task/Fractran/Odin/fractran.odin @@ -25,7 +25,7 @@ main :: proc() { ss := strings.split(string(data), " ") defer delete(ss) - + a: [dynamic]string dummy:[]string diff --git a/Task/Fractran/Perl/fractran.pl b/Task/Fractran/Perl/fractran.pl index abf777dd2c..038f8cf912 100644 --- a/Task/Fractran/Perl/fractran.pl +++ b/Task/Fractran/Perl/fractran.pl @@ -8,24 +8,24 @@ my ($n, @P) = map Math::BigRat->new($_), qw{ $|=1; MAIN: for( 1 .. 5000 ) { - print " " if $_ > 1; - my ($pow, $rest) = (0, $n->copy); - until( $rest->is_odd ) { - ++$pow; - $rest->bdiv(2); - } - if( $rest->is_one ) { - print "2**$pow"; - } else { - #print $n; - } - for my $f_i (@P) { - my $nf_i = $n * $f_i; - next unless $nf_i->is_int; - $n = $nf_i; - next MAIN; - } - last; + print " " if $_ > 1; + my ($pow, $rest) = (0, $n->copy); + until( $rest->is_odd ) { + ++$pow; + $rest->bdiv(2); + } + if( $rest->is_one ) { + print "2**$pow"; + } else { + #print $n; + } + for my $f_i (@P) { + my $nf_i = $n * $f_i; + next unless $nf_i->is_int; + $n = $nf_i; + next MAIN; + } + last; } print "\n"; diff --git a/Task/Fractran/Rebol/fractran.rebol b/Task/Fractran/Rebol/fractran.rebol new file mode 100644 index 0000000000..33b17b69b8 --- /dev/null +++ b/Task/Fractran/Rebol/fractran.rebol @@ -0,0 +1,41 @@ +Rebol [ + title: "Rosetta code: Fractran" + file: %Fractran.r3 + url: https://rosettacode.org/wiki/Fractran +] + +fractran: function/with [ + input [string! file! url!] + start [integer!] + terms [integer!] +][ + unless string? input [ input: read/string input ] + ;; --- parse fractions into [numerator denominator] pairs --- + fractions: parse input [collect [fraction some [separator fraction]]] + ;; --- interpreter loop --- + out: append copy [] n: start + while [terms > length? out] [ + forall fractions [ + frac: fractions/1 + if zero? mod n frac/y [ ;; fraction applies: n is divisible + n: n / frac/y * frac/x ;; advance: multiply n by fraction + append out to integer! n ;; keep the result + fractions: head fractions ;; restart from first fraction + break + ] + if tail? fractions [return out] ;; no fraction applied: halt + ] + ] + out +][ + digit: charset "0123456789" + fraction: [copy p [some digit] #"/" copy q [some digit] keep (as-pair to integer! p to integer! q)] + separator: [some #" "] +] + +print "First 100 terms of the sequence:" +out: fractran "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 100 +forall out [ + prin pad out/1 9 + if zero? mod index? out 10 [print ""] +] diff --git a/Task/Fractran/Red/fractran.red b/Task/Fractran/Red/fractran.red index a61ef88f55..44fb51eabe 100644 --- a/Task/Fractran/Red/fractran.red +++ b/Task/Fractran/Red/fractran.red @@ -5,20 +5,20 @@ if exists? inpf: to-file inp [inp: read inpf] digit: charset "0123456789" frac: [copy p [some digit] #"/" copy q [some digit] - keep (as-pair to-integer p to-integer q)] + keep (as-pair to-integer p to-integer q)] code: parse inp [collect [frac some [[some " "] frac]]] n: to-integer ask "please enter starting number n: " x: to-integer ask "please enter the number of terms, hit return for no limit: " l: length? code loop x [ - forall code [ - c: code/1 - if n % c/y = 0 [ - print n: n / c/y * c/x - code: head code - break - ] - if l = index? code [halt] - ] + forall code [ + c: code/1 + if n % c/y = 0 [ + print n: n / c/y * c/x + code: head code + break + ] + if l = index? code [halt] + ] ] diff --git a/Task/Fractran/TI-83-BASIC/fractran.basic b/Task/Fractran/TI-83-BASIC/fractran.basic index 3c39e388a9..c501d5df6a 100644 --- a/Task/Fractran/TI-83-BASIC/fractran.basic +++ b/Task/Fractran/TI-83-BASIC/fractran.basic @@ -5,15 +5,15 @@ Dim(LA)->U T->Dim(LC) For(I,1,T) - 1->J: 1->F - While J<=U and F=1 - If remainder(N,LB(J))=0 - Then - Disp N - N->LC(I) - iPart(N/LB(J))*LA(J)->N - 0->F - End - J+1->J - End + 1->J: 1->F + While J<=U and F=1 + If remainder(N,LB(J))=0 + Then + Disp N + N->LC(I) + iPart(N/LB(J))*LA(J)->N + 0->F + End + J+1->J + End End diff --git a/Task/Fractran/Tcl/fractran-1.tcl b/Task/Fractran/Tcl/fractran-1.tcl index 50932aaba5..6a0acc52ec 100644 --- a/Task/Fractran/Tcl/fractran-1.tcl +++ b/Task/Fractran/Tcl/fractran-1.tcl @@ -3,42 +3,42 @@ package require Tcl 8.6 oo::class create Fractran { variable fracs nco constructor {fractions} { - set fracs {} - foreach frac $fractions { - if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} { - lappend fracs $num $denom - } else { - return -code error "$frac is not a supported fraction" - } - } - if {![llength $fracs]} { - return -code error "need at least one fraction" - } + set fracs {} + foreach frac $fractions { + if {[regexp {^(\d+)/(\d+),?$} $frac -> num denom]} { + lappend fracs $num $denom + } else { + return -code error "$frac is not a supported fraction" + } + } + if {![llength $fracs]} { + return -code error "need at least one fraction" + } } method execute {n {steps 15}} { - set co [coroutine [incr nco] my Generate $n] - for {set i 0} {$i < $steps} {incr i} { - lappend result [$co] - } - catch {rename $co ""} - return $result + set co [coroutine [incr nco] my Generate $n] + for {set i 0} {$i < $steps} {incr i} { + lappend result [$co] + } + catch {rename $co ""} + return $result } method Step {n} { - foreach {num den} $fracs { - if {$n % $den} continue - return [expr {$n * $num / $den}] - } - return -code break + foreach {num den} $fracs { + if {$n % $den} continue + return [expr {$n * $num / $den}] + } + return -code break } method Generate {n} { - yield [info coroutine] - while 1 { - yield $n - set n [my Step $n] - } - return -code break + yield [info coroutine] + while 1 { + yield $n + set n [my Step $n] + } + return -code break } } diff --git a/Task/Fractran/Tcl/fractran-2.tcl b/Task/Fractran/Tcl/fractran-2.tcl index a61af1865b..21da1ffe97 100644 --- a/Task/Fractran/Tcl/fractran-2.tcl +++ b/Task/Fractran/Tcl/fractran-2.tcl @@ -2,10 +2,10 @@ oo::objdefine $ft method pow2 {n} { set co [coroutine [incr nco] my Generate 2] set pows {} while {[llength $pows] < $n} { - set item [$co] - if {($item & ($item-1)) == 0} { - lappend pows $item - } + set item [$co] + if {($item & ($item-1)) == 0} { + lappend pows $item + } } return $pows } diff --git a/Task/Fractran/UNIX-Shell/fractran.sh b/Task/Fractran/UNIX-Shell/fractran.sh index 916bfce39b..bf28e57eb8 100644 --- a/Task/Fractran/UNIX-Shell/fractran.sh +++ b/Task/Fractran/UNIX-Shell/fractran.sh @@ -10,10 +10,10 @@ t=0 n=72 echo "steps of computation" > steps.csv while [ $t -le 6 ]; do - if [ $(($n*${ns[$t]}%${ds[$t]})) -eq 0 ]; then - let "n=$(($n*${ns[$t]}/${ds[$t]}))" - let "t=0" - factor $n >> steps.csv - fi - let "t=$t+1" + if [ $(($n*${ns[$t]}%${ds[$t]})) -eq 0 ]; then + let "n=$(($n*${ns[$t]}/${ds[$t]}))" + let "t=0" + factor $n >> steps.csv + fi + let "t=$t+1" done diff --git a/Task/Fractran/Zkl/fractran-1.zkl b/Task/Fractran/Zkl/fractran-1.zkl index ab1e3d8182..ca49aa5d7d 100644 --- a/Task/Fractran/Zkl/fractran-1.zkl +++ b/Task/Fractran/Zkl/fractran-1.zkl @@ -2,14 +2,14 @@ var fracs="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"; fcn fractranW(n,fracsAsOneBigString){ //-->Walker (iterator) fracs:=(fracsAsOneBigString-" ").split(",").apply( - fcn(frac){ frac.split("/").apply("toInt") }); //( (n,d), (n,d), ...) + fcn(frac){ frac.split("/").apply("toInt") }); //( (n,d), (n,d), ...) Walker(fcn(rn,fracs){ n:=rn.value; foreach a,b in (fracs){ - if(n*a%b == 0){ - rn.set(n*a/b); - return(n); - } + if(n*a%b == 0){ + rn.set(n*a/b); + return(n); + } } }.fp(Ref(n),fracs)) } diff --git a/Task/Fractran/Zkl/fractran-3.zkl b/Task/Fractran/Zkl/fractran-3.zkl index 00de8a061b..718365473b 100644 --- a/Task/Fractran/Zkl/fractran-3.zkl +++ b/Task/Fractran/Zkl/fractran-3.zkl @@ -2,9 +2,9 @@ var [const] BN=Import("zklBigNum"); // libGMP fcn fractranPrimes{ foreach n,fr in ([1..].zip(fractranW(BN(2),fracs))){ if(fr.num1s==1){ - p:=(fr.toString(2) - "1").len(); // count zeros - if(p>1) - println("Prime %3d from the nth Fractran(%8d): %d".fmt(p,n,fr)); + p:=(fr.toString(2) - "1").len(); // count zeros + if(p>1) + println("Prime %3d from the nth Fractran(%8d): %d".fmt(p,n,fr)); } } } diff --git a/Task/French-Republican-calendar/JavaScript/french-republican-calendar.js b/Task/French-Republican-calendar/JavaScript/french-republican-calendar.js new file mode 100644 index 0000000000..5abfc4a5ff --- /dev/null +++ b/Task/French-Republican-calendar/JavaScript/french-republican-calendar.js @@ -0,0 +1,130 @@ +class FrenchRCDate { + constructor(year, month, day) { + this.year = year; + this.month = month; + this.day = day; + } + + static INTRODUCTION_DATE = new Date(Date.UTC(1792, 8, 22)); // Months are zero-indexed in JS + static TERMINATION_DATE = new Date(Date.UTC(1805, 11, 31)); + + static MONTHS = [ + "Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", + "Germinal", "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor" + ]; + + static SANSCULOTTIDES = [ + "Fête de la vertu", "Fête du génie", "Fête du travail", + "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution" + ]; + + toGregorianDate() { + const days = (this.year - 1) * 365 + FrenchRCDate.additionalDaysForYear(this.year) + + (this.month - 1) * 30 + this.day - 1; + + const gregorian = new Date(FrenchRCDate.INTRODUCTION_DATE); + gregorian.setUTCDate(gregorian.getUTCDate() + days); + return gregorian; + } + + toString() { + if (this.month < 13) { + return `${this.day} ${FrenchRCDate.MONTHS[this.month - 1]} ${this.year}`; + } else { + return `${FrenchRCDate.SANSCULOTTIDES[this.day - 1]} ${this.year}`; + } + } + + static additionalDaysForYear(year) { + return year > 11 ? 3 : year > 7 ? 2 : year > 3 ? 1 : 0; + } + + static toFrenchRCDate(gregorianDate) { + const daysAfter = Math.floor((gregorianDate - FrenchRCDate.INTRODUCTION_DATE) / (1000 * 60 * 60 * 24)); + const daysBefore = Math.floor((FrenchRCDate.TERMINATION_DATE - gregorianDate) / (1000 * 60 * 60 * 24)); + + if (daysAfter < 0 || daysBefore < 0) { + throw new Error("French Republican Calendar date out of range."); + } + + let year = Math.floor((daysAfter + 366) / 365); + let days = (daysAfter + 366) % 365 - FrenchRCDate.additionalDaysForYear(year); + + if (days < 1) { + year -= 1; + days += 366; + } + + if (days < 361) { + const month = Math.floor(days / 30) + 1; + const day = days % 30 || 30; + return new FrenchRCDate(year, month, day); + } else { + const day = days - 360; + return new FrenchRCDate(year, 13, day); + } + } + + static parse(frenchRCDateString) { + const parts = frenchRCDateString.trim().split(/\s+/); + if (parts.length === 3) { + const [dayStr, monthStr, yearStr] = parts; + const year = parseInt(yearStr, 10); + const month = FrenchRCDate.MONTHS.indexOf(monthStr) + 1; + const day = parseInt(dayStr, 10); + return new FrenchRCDate(year, month, day); + } else { + const yearStr = parts[parts.length - 1]; + const year = parseInt(yearStr, 10); + const sansculottideName = parts.slice(0, -1).join(" "); + const day = FrenchRCDate.SANSCULOTTIDES.indexOf(sansculottideName) + 1; + return new FrenchRCDate(year, 13, day); + } + } +} + +// Helper to format dates like "d MMMM yyyy" +function formatDate(date) { + const months = [ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" + ]; + const day = date.getUTCDate(); + const month = months[date.getUTCMonth()]; + const year = date.getUTCFullYear(); + return `${day} ${month} ${year}`; +} + +// Main logic +const gregorianStrings = [ + "22 September 1792", + "20 May 1795", + "15 July 1799", + "23 September 1803", + "31 December 1805" +]; + +const frenchRCStrings = []; + +for (const gregorianString of gregorianStrings) { + // Parse into JS Date object + const [day, month, year] = gregorianString.split(" "); + const monthIndex = [ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" + ].indexOf(month); + const gregorianDate = new Date(Date.UTC(parseInt(year), monthIndex, parseInt(day))); + + const frenchRCDate = FrenchRCDate.toFrenchRCDate(gregorianDate); + const frenchRCString = frenchRCDate.toString(); + frenchRCStrings.push(frenchRCString); + console.log(`${gregorianString} => ${frenchRCString}`); +} + +console.log(); + +for (const frenchRCString of frenchRCStrings) { + const frenchRCDate = FrenchRCDate.parse(frenchRCString); + const gregorianDate = frenchRCDate.toGregorianDate(); + console.log(`${frenchRCString} => ${formatDate(gregorianDate)}`); +} diff --git a/Task/French-Republican-calendar/Rust/french-republican-calendar.rs b/Task/French-Republican-calendar/Rust/french-republican-calendar.rs new file mode 100644 index 0000000000..873b6c090d --- /dev/null +++ b/Task/French-Republican-calendar/Rust/french-republican-calendar.rs @@ -0,0 +1,177 @@ +use chrono::{Datelike, Duration, NaiveDate}; + +const MONTHS: [&str; 13] = [ + "Vendemiaire", "Brumaire", "Frimaire", "Nivose", "Pluviose", "Ventose", "Germinal", + "Floreal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide", +]; + +const SANSCULOTTIDES: [&str; 6] = [ + "Fete de la vertu", "Fete du genie", "Fete du travail", + "Fete de l'opinion", "Fete des recompenses", "Fete de la Revolution", +]; + +const GREGORIAN_MONTHS: [&str; 12] = [ + "January", "February", "March", "April", "May", "June", "July", "August", + "September", "October", "November", "December", +]; + +const INTRODUCTION_DATE: NaiveDate = match NaiveDate::from_ymd_opt(1792, 9, 22) { + Some(date) => date, + None => panic!("Invalid introduction date"), +}; + +const TERMINATION_DATE: NaiveDate = match NaiveDate::from_ymd_opt(1805, 12, 31) { + Some(date) => date, + None => panic!("Invalid termination date"), +}; + +#[derive(Debug, Clone, Copy)] +struct FrenchRcDate { + year: u32, + month: u32, + day: u32, +} + +fn split_string(text: &str, delimiter: char) -> Vec<&str> { + text.split(delimiter).collect() +} + +fn index_of(vec: &[&str], element: &str) -> u32 { + vec.iter() + .position(|&x| x == element) + .map(|i| i as u32) + .unwrap_or_else(|| panic!("Element not found: {}", element)) +} + +fn additional_days_for_year(year: u32) -> u32 { + if year > 11 { + 3 + } else if year > 7 { + 2 + } else if year > 3 { + 1 + } else { + 0 + } +} + +fn to_french_rc_date_string(french_rc_date: FrenchRcDate) -> String { + if french_rc_date.month < 13 { + format!( + "{} {} {}", + french_rc_date.day, MONTHS[(french_rc_date.month - 1) as usize], french_rc_date.year + ) + } else { + format!( + "{} {}", + SANSCULOTTIDES[(french_rc_date.day - 1) as usize], french_rc_date.year + ) + } +} + +fn to_gregorian_date_string(gregorian_date: NaiveDate) -> String { + let year = gregorian_date.year(); + let month = gregorian_date.month() as usize; + let day = gregorian_date.day(); + let month_string = GREGORIAN_MONTHS[month - 1]; + format!("{} {} {}", day, month_string, year) +} + +fn parse_gregorian_date(gregorian_string: &str) -> NaiveDate { + let splits: Vec<&str> = split_string(gregorian_string, ' '); + let day: u32 = splits[0].parse().expect("Invalid day"); + let month = index_of(&GREGORIAN_MONTHS, splits[1]) + 1; + let year: i32 = splits[2].parse().expect("Invalid year"); + + NaiveDate::from_ymd_opt(year, month, day) + .unwrap_or_else(|| panic!("Invalid Gregorian date: {}", gregorian_string)) +} + +fn parse_french_rc_date(french_rc_date: &str) -> FrenchRcDate { + let splits: Vec<&str> = split_string(french_rc_date, ' '); + if splits.len() == 3 { + let day: u32 = splits[0].parse().expect("Invalid day"); + let month = index_of(&MONTHS, splits[1]) + 1; + let year: u32 = splits[2].parse().expect("Invalid year"); + FrenchRcDate { year, month, day } + } else { + let year_string = splits[splits.len() - 1]; + let year: u32 = year_string.parse().expect("Invalid year"); + let sansculottides_day = &french_rc_date[..french_rc_date.len() - year_string.len() - 1]; + let day = index_of(&SANSCULOTTIDES, sansculottides_day) + 1; + FrenchRcDate { + year, + month: 13, + day, + } + } +} + +fn to_french_rc_date(gregorian_date: NaiveDate) -> FrenchRcDate { + let days_after = (gregorian_date - INTRODUCTION_DATE).num_days(); + let days_before = (TERMINATION_DATE - gregorian_date).num_days(); + + if days_after < 0 || days_before < 0 { + panic!("French Republican Calendar date out of range."); + } + + let mut year = (days_after + 366) / 365; + let mut days = (days_after + 366) % 365 - additional_days_for_year(year as u32) as i64; + + if days == 0 { + year -= 1; + days += 366; + } + + if days < 361 { + FrenchRcDate { + year: year as u32, + month: (days / 30 + 1) as u32, + day: (days % 30) as u32, + } + } else { + FrenchRcDate { + year: year as u32, + month: 13, + day: (days - 360) as u32, + } + } +} + +fn to_gregorian_date(french_rc_date: FrenchRcDate) -> NaiveDate { + let days = (french_rc_date.year - 1) * 365 + + additional_days_for_year(french_rc_date.year) + + (french_rc_date.month - 1) * 30 + + french_rc_date.day + - 1; + INTRODUCTION_DATE + Duration::days(days as i64) +} + +fn main() { + let gregorian_strings = vec![ + "22 September 1792", + "20 May 1795", + "15 July 1799", + "23 September 1803", + "31 December 1805", + ]; + + let mut french_rc_strings = Vec::new(); + + for gregorian_string in &gregorian_strings { + let gregorian_date = parse_gregorian_date(gregorian_string); + let french_rc_date = to_french_rc_date(gregorian_date); + let french_rc_date_string = to_french_rc_date_string(french_rc_date); + french_rc_strings.push(french_rc_date_string.clone()); + println!("{} => {}", gregorian_string, french_rc_date_string); + } + + println!(); + + for french_rc_string in &french_rc_strings { + let french_rc_date = parse_french_rc_date(french_rc_string); + let gregorian_date = to_gregorian_date(french_rc_date); + let gregorian_date_string = to_gregorian_date_string(gregorian_date); + println!("{} => {}", french_rc_string, gregorian_date_string); + } +} diff --git a/Task/French-Republican-calendar/Scheme/french-republican-calendar.scm b/Task/French-Republican-calendar/Scheme/french-republican-calendar.scm new file mode 100644 index 0000000000..a60062f8fd --- /dev/null +++ b/Task/French-Republican-calendar/Scheme/french-republican-calendar.scm @@ -0,0 +1,234 @@ +; version 1 (11 Frimaire 234) +; inspired by BBC Basic +; see https://rosettacode.org/wiki/French_Republican_calendar + +(import (scheme base) (scheme char)) + +; ex: (date->jour-mois-annee '(2025 12 1)) -> 1 12 2025 +(define (date->jour-mois-annee date) + (values (list-ref date 2) (list-ref date 1) (list-ref date 0))) + +; ex: (jours-bissextiles 1900) -> 460 +(define (jours-bissextiles annee) + (- (+ (quotient annee 4) (quotient annee 400)) (quotient annee 100))) + +; ex: (bissextile? 1900) -> #f +(define (bissextile? annee) + (and (zero? (remainder annee 4)) + (or (zero? (remainder annee 400)) (positive? (remainder annee 100))))) + +; ex: (jour-bissextile 1900) -> 0 +(define (jour-bissextile annee) + (if (bissextile? annee) 1 0)) + +; ex: (gregorien->jours '(1792 9 22)) -> 1 +; ex: (gregorien->jours '(2025 12 1)) -> 85172 +(define (gregorien->jours date) + (let*-values (((jour mois annee) (date->jour-mois-annee date)) + ((mois annee) (if (< mois 3) + (values (+ mois 12) (- annee 1)) + (values mois annee)))) + (- (+ (* annee 365) + (jours-bissextiles annee) + (exact (floor (* 30.6 (+ mois 1)))) + jour) + 654842))) + +; ex: (republicain->jours '(1 1 1)) -> 1 +; ex: (republicain->jours '(2025 12 1)) -> 85172 +(define (republicain->jours date) + (let*-values (((jour mois annee) (date->jour-mois-annee date)) + ((mois jour) (if (= mois 13) + (values 12 (+ jour 30)) + (values mois jour)))) + (- (+ (* annee 365) + (* 30 mois) + (jours-bissextiles (+ annee 1)) + jour) + (jour-bissextile (+ annee 1)) + 395))) + +; ex: (jours->gregorien 1) -> (1792 9 22) +; ex: (jours->gregorien 85172) -> (2025 12 1) +(define (jours->gregorien jours) + (let* ((annee (exact (floor (/ jours 365.25)))) + (jour (+ (- jours (exact (floor (* annee 365.25)))) 21)) + (annee (+ annee 1792)) + (jour (- (+ jour (exact (quotient annee 100))) (exact (quotient annee 400)) 13))) + (let boucle ((jour jour)(mois 8)(annee annee)) + (let* ((duree-mois (vector-ref #(31 28 31 30 31 30 31 31 30 31 30 31) mois)) + (duree-mois (+ duree-mois (if (and (= mois 1) (bissextile? annee)) 1 0)))) + (if (<= jour duree-mois) + (list annee (+ mois 1) jour) + (let ((jour (- jour duree-mois)) + (mois (+ mois 1))) + (if (= mois 12) + (boucle jour 0 (+ annee 1)) + (boucle jour mois annee)))))))) + +; ex: (jours->republicain 1) -> (1 1 1) +; ex: (jours->republicain 85172) -> (234 3 11) +(define (jours->republicain jours) + (let* ((annee (exact (floor (/ jours 365.25)))) + (annee (- annee (jour-bissextile (+ annee 1)))) + (jour (- jours (exact (floor (* annee 365.25))))) + (annee (+ annee 1)) + (jour (- (+ jour (exact (quotient annee 100))) (exact (quotient annee 400))))) + (let boucle ((jour jour)(mois 1)(annee annee)) + (let ((duree-mois (if (< mois 13) 30 (+ 5 (jour-bissextile (+ annee 1)))))) + (if (<= jour duree-mois) + (list annee mois jour) + (let ((jour (- jour duree-mois)) + (mois (+ mois 1))) + (if (= mois 14) + (boucle jour 1 (+ annee 1)) + (boucle jour mois annee)))))))) + +; ex: (normalise-caractere #\E) -> #\e +; ex: (normalise-caractere #\ê) -> #\e +(define (normalise-caractere caractere) + (let* ((caractere (char-downcase caractere)) + (autre (assoc caractere '((#\é . #\e) (#\ê . #\e) (#\ô . #\o))))) + (if autre + (cdr autre) + caractere))) + +; ex: (normalise-texte "Ventôse") -> "ventose" +(define (normalise-texte texte) + (string-map normalise-caractere texte)) + +; ex: (normalise-texte '("Ventôse" "Germinal")) -> ("ventose" "germinal") +(define (normalise-liste liste) + (map normalise-texte liste)) + +(define mois-republicains '( + "Vendémiaire" "Brumaire" "Frimaire" "Nivôse" "Pluviôse" "Ventôse" + "Germinal" "Floréal" "Prairial" "Messidor" "Thermidor" "Fructidor" + "Sansculottide")) + +(define sansculottides '( + "Fête de la vertu" "Fête du génie" "Fête du travail" + "Fête de l'opinion" "Fête des récompenses" "Fête de la Révolution" )) + +(define mois-gregoriens '( + "January" "February" "March" "April" "May" "June" + "July" "August" "September" "October" "November" "December" )) + +(define mois-republicains-normal (normalise-liste mois-republicains)) + +(define sansculottides-normal (normalise-liste sansculottides)) + +(define mois-gregoriens-normal (normalise-liste mois-gregoriens)) + +; ex: (gregorien->texte '(2025 12 1)) -> "1 December 2025)" +(define (gregorien->texte date) + (string-append + (number->string (list-ref date 2)) + " " + (list-ref mois-gregoriens (- (list-ref date 1) 1)) + " " + (number->string (list-ref date 0)))) + +; ex: (republicain->texte '(2025 12 1)) -> "1 Fructidor 2025)" +; ex: (republicain->texte '(2025 13 1)) -> "Fête de la vertu 2025)" +(define (republicain->texte date) + (if (= (list-ref date 1) 13) + (string-append + (list-ref sansculottides (- (list-ref date 2) 1)) + " " + (number->string (list-ref date 0))) + (string-append + (number->string (list-ref date 2)) + " " + (list-ref mois-republicains (- (list-ref date 1) 1)) + " " + (number->string (list-ref date 0))))) + +; ex: (decompose "34 toto 78 zorro louarn 9") -> (9 "zorro louarn" 78 "toto" 34) +; ex: (decompose "10 Vendémiaire 1") -> (1 "Vendémiaire" 10) +(define (decompose texte) + (let ((texte (normalise-texte texte))) + (let boucle ((index 0)(resultat '())) + (if (>= index (string-length texte)) + resultat + (let ((caractere (string-ref texte index)) + (index (+ index 1))) + (cond + ((char-whitespace? caractere) + (boucle index resultat)) + ((char-numeric? caractere) + (let lit-nombre ((index index)(valeur (digit-value caractere))) + (let ((caractere (if (>= index (string-length texte)) + #\space + (string-ref texte index)))) + (if (char-numeric? caractere) + (lit-nombre (+ index 1) (+ (* 10 valeur) (digit-value caractere))) + (boucle index (cons valeur resultat)))))) + (else + (let lit-texte ((index index)(valeur (list caractere))) + (let ((caractere (if (>= index (string-length texte)) + #\0 + (string-ref texte index)))) + (if (char-numeric? caractere) + (let retire-espace ((valeur valeur)) + (if (char-whitespace? (car valeur)) + (retire-espace (cdr valeur)) + (boucle index (cons (list->string (reverse valeur)) resultat)))) + (lit-texte (+ index 1) (cons caractere valeur)))))))))))) + +; ex: (index-texte '("a" "b" "c") "b") -> 2 +; ex: (index-texte '("a" "b" "c") "x") -> #f +(define (index-texte liste texte) + (let ((tete (member texte liste))) + (and tete (+ 1 (- (length liste) (length tete)))))) + +; ex: (decode-date "22 September 1792") -> (gregorien 1792 9 22) +; ex: (decode-date "Fête de la Révolution 11") -> (republicain 11 13 6) +(define (decode-date texte) + (let ((decomposition (decompose texte))) + (case (length decomposition) + ((2) + (let* ((annee (list-ref decomposition 0)) + (fete (list-ref decomposition 1)) + (jour (index-texte sansculottides-normal fete))) + (and jour (number? annee) (list 'republicain annee 13 jour)))) + ((3) + (let* ((annee (list-ref decomposition 0)) + (mois (list-ref decomposition 1)) + (jour (list-ref decomposition 2)) + (mois-gregorien (index-texte mois-gregoriens-normal mois)) + (mois-republicain (index-texte mois-republicains-normal mois))) + (and (number? annee) (number? jour) + (or (and mois-gregorien (list 'gregorien annee mois-gregorien jour)) + (and mois-republicain (list 'republicain annee mois-republicain jour)))))) + (else + #f)))) + +; ex: (decode-date "22 September 1792") -> "1 Vendémiaire 1" +; ex: (decode-date "Fête de la Révolution 11") -> "23 September 1803" +(define (converti-date texte) + (let ((decodage (decode-date texte))) + (and decodage + (case (car decodage) + ((gregorien) + (republicain->texte (jours->republicain (gregorien->jours (cdr decodage))))) + ((republicain) + (gregorien->texte (jours->gregorien (republicain->jours (cdr decodage))))) + (else + #f))))) + +; validation +(for-each + (lambda (texte) + (display texte) + (display " = ") + (display (converti-date texte)) + (newline)) + '( + "1 Vendémiaire 1" "22 September 1792" + "1 Prairial 3" "20 May 1795" + "27 Messidor 7" "15 July 1799" + "Fête de la Révolution 11" "23 September 1803" + "10 Nivôse 14" "31 December 1805" + "11 Frimaire 234" "1 December 2025" + )) diff --git a/Task/Function-composition/00-META.yaml b/Task/Function-composition/00-META.yaml index bd45864d57..483655d1d4 100644 --- a/Task/Function-composition/00-META.yaml +++ b/Task/Function-composition/00-META.yaml @@ -1,3 +1,2 @@ --- from: http://rosettacode.org/wiki/Function_composition -note: Higher-order functions diff --git a/Task/Function-composition/00-TASK.txt b/Task/Function-composition/00-TASK.txt index 44f6ada3f0..8b13789179 100644 --- a/Task/Function-composition/00-TASK.txt +++ b/Task/Function-composition/00-TASK.txt @@ -1,16 +1 @@ -;Task: -Create a function, compose,   whose two arguments   ''f''   and   ''g'',   are both functions with one argument. - - -The result of compose is to be a function of one argument, (lets call the argument   ''x''),   which works like applying function   ''f''   to the result of applying function   ''g''   to   ''x''. - - -;Example: - compose(''f'', ''g'') (''x'') = ''f''(''g''(''x'')) - - -Reference: [[wp:Function composition (computer science)|Function composition]] - -Hint: In some languages, implementing compose correctly requires creating a [[wp:Closure (computer science)|closure]]. -

    diff --git a/Task/Function-composition/Ada/function-composition-1.adb b/Task/Function-composition/Ada/function-composition-1.adb new file mode 100644 index 0000000000..2241acbfe6 --- /dev/null +++ b/Task/Function-composition/Ada/function-composition-1.adb @@ -0,0 +1,13 @@ +generic + type Argument is private; +package Functions is + type Primitive_Operation is not null + access function (Value : Argument) return Argument; + type Func (<>) is private; + function "*" (Left : Func; Right : Argument) return Argument; + function "*" (Left : Func; Right : Primitive_Operation) return Func; + function "*" (Left, Right : Primitive_Operation) return Func; + function "*" (Left, Right : Func) return Func; +private + type Func is array (Positive range <>) of Primitive_Operation; +end Functions; diff --git a/Task/Function-composition/Ada/function-composition-2.adb b/Task/Function-composition/Ada/function-composition-2.adb new file mode 100644 index 0000000000..d841a9d408 --- /dev/null +++ b/Task/Function-composition/Ada/function-composition-2.adb @@ -0,0 +1,25 @@ +package body Functions is + function "*" (Left : Func; Right : Argument) return Argument is + Result : Argument := Right; + begin + for I in reverse Left'Range loop + Result := Left (I) (Result); + end loop; + return Result; + end "*"; + + function "*" (Left, Right : Func) return Func is + begin + return Left & Right; + end "*"; + + function "*" (Left : Func; Right : Primitive_Operation) return Func is + begin + return Left & (1 => Right); + end "*"; + + function "*" (Left, Right : Primitive_Operation) return Func is + begin + return (Left, Right); + end "*"; +end Functions; diff --git a/Task/Function-composition/Ada/function-composition-3.adb b/Task/Function-composition/Ada/function-composition-3.adb new file mode 100644 index 0000000000..8f0533961e --- /dev/null +++ b/Task/Function-composition/Ada/function-composition-3.adb @@ -0,0 +1,12 @@ +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; +with Functions; + +procedure Test_Compose is + package Float_Functions is new Functions (Float); + use Float_Functions; + + Sin_Arcsin : Func := Sin'Access * Arcsin'Access; +begin + Put_Line (Float'Image (Sin_Arcsin * 0.5)); +end Test_Compose; diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-1.el b/Task/Function-composition/Emacs-Lisp/function-composition-1.el new file mode 100644 index 0000000000..5ed721ad7b --- /dev/null +++ b/Task/Function-composition/Emacs-Lisp/function-composition-1.el @@ -0,0 +1,7 @@ +;; lexical-binding: t +(defun compose (f g) + (lambda (x) + (funcall f (funcall g x)))) + +(let ((func (compose '1+ '1+))) + (funcall func 5)) ;=> 7 diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-2.el b/Task/Function-composition/Emacs-Lisp/function-composition-2.el new file mode 100644 index 0000000000..be148ccd28 --- /dev/null +++ b/Task/Function-composition/Emacs-Lisp/function-composition-2.el @@ -0,0 +1,5 @@ +(defun compose (f g) + `(lambda (x) (,f (,g x)))) + +(let ((func (compose '1+ '1+))) + (funcall func 5)) ;=> 7 diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-3.el b/Task/Function-composition/Emacs-Lisp/function-composition-3.el new file mode 100644 index 0000000000..4f8d8016ad --- /dev/null +++ b/Task/Function-composition/Emacs-Lisp/function-composition-3.el @@ -0,0 +1,5 @@ +(defmacro compose (f g) + `(lambda (x) (,f (,g x)))) + +(let ((func (compose 1+ 1+))) + (funcall func 5)) ;=> 7 diff --git a/Task/Function-composition/Odin/function-composition.odin b/Task/Function-composition/Odin/function-composition.odin new file mode 100644 index 0000000000..bda638fa4b --- /dev/null +++ b/Task/Function-composition/Odin/function-composition.odin @@ -0,0 +1,25 @@ +package main + +import "core:fmt" +import "core:math" + +Compositor :: struct($ARG, $INTER, $RET: typeid) { + func1: #type proc "contextless" (_: ARG) -> INTER, + func2: #type proc "contextless" (_: INTER) -> RET, +} + +compose :: proc( + f: #type proc "contextless" (_: $INTER) -> $RET, + g: #type proc "contextless" (_: $ARG) -> INTER, +) -> Compositor(ARG, RET, INTER) { + return {g, f} +} + +call :: proc(c: Compositor($ARG, $INTER, $RET), arg: ARG) -> RET { + return c.func1(c.func2(arg)) +} + +main :: proc() { + comp := compose(math.sin_f64, math.asin_f64) // have to use specific functions. Odin's polymorphism doesn't play nice with procedure groups + fmt.println(call(comp, 0.5)) // prints 0.5 +} diff --git a/Task/Function-composition/Pluto/function-composition.pluto b/Task/Function-composition/Pluto/function-composition.pluto new file mode 100644 index 0000000000..6bbdea1daa --- /dev/null +++ b/Task/Function-composition/Pluto/function-composition.pluto @@ -0,0 +1,7 @@ +local function compose(f, g) return |x| -> f(g(x)) end + +local function double(x) return 2 * x end + +local function add_one(x) return x + 1 end + +print(compose(double, add_one)(3)) diff --git a/Task/Function-composition/PowerShell/function-composition-1.ps1 b/Task/Function-composition/PowerShell/function-composition-1.ps1 new file mode 100644 index 0000000000..e6196e8576 --- /dev/null +++ b/Task/Function-composition/PowerShell/function-composition-1.ps1 @@ -0,0 +1,7 @@ +function g ($x) { + $x + $x +} +function f ($x) { + $x*$x*$x +} +f (g 1) diff --git a/Task/Function-composition/PowerShell/function-composition-2.ps1 b/Task/Function-composition/PowerShell/function-composition-2.ps1 new file mode 100644 index 0000000000..5cbf753f3f --- /dev/null +++ b/Task/Function-composition/PowerShell/function-composition-2.ps1 @@ -0,0 +1,4 @@ +function fg (${function:f}, ${function:g}, $x) { + f (g $x) +} +fg f g 1 diff --git a/Task/Function-composition/Rebol/function-composition-1.rebol b/Task/Function-composition/Rebol/function-composition-1.rebol new file mode 100644 index 0000000000..ef233a55ac --- /dev/null +++ b/Task/Function-composition/Rebol/function-composition-1.rebol @@ -0,0 +1,14 @@ +Rebol [ + Title: "Functional Composition" + URL: http://rosettacode.org/wiki/Functional_Composition +] + +; "compose" means something else in Rebol, therefore I use a 'compose-functions name. + +compose-functions: func [ + {compose the given functions F and G} + f [any-function!] + g [any-function!] +] [ + func [x] compose [(:f) (:g) x] +] diff --git a/Task/Function-composition/Rebol/function-composition-2.rebol b/Task/Function-composition/Rebol/function-composition-2.rebol new file mode 100644 index 0000000000..133162f3d1 --- /dev/null +++ b/Task/Function-composition/Rebol/function-composition-2.rebol @@ -0,0 +1,8 @@ +foo: func [x] [reform ["foo:" x]] +bar: func [x] [reform ["bar:" x]] + +foo-bar: compose-functions :foo :bar +print ["Composition of foo and bar:" mold foo-bar "test"] + +sin-asin: compose-functions :sine :arcsine +print [crlf "Composition of sine and arcsine:" sin-asin 0.5] diff --git a/Task/Function-composition/Red/function-composition.red b/Task/Function-composition/Red/function-composition.red new file mode 100644 index 0000000000..0f4331df21 --- /dev/null +++ b/Task/Function-composition/Red/function-composition.red @@ -0,0 +1,18 @@ +Red [ "Compose Two or Any Number of Functions - Hinjolicious" ] + +; to show the codes +demo: function [s b] [print ["^/==" s "==^/"] print mold/only b do b] + +demo "Compose two functions" [ +comp-func: function ['f 'g] [function [x] compose [(get f) (get g) x]] +sin-cos: comp-func sin cos +print sin-cos 0.5 +] + +demo "Compose any number of functions" [ +comp-funcs: function [ff] [ + function [x] compose append collect [foreach e ff [keep (get e)]] 'x +] +log-sin-cos: comp-funcs [log-e sin cos] +print log-sin-cos 0.5 +] diff --git a/Task/Function-composition/VBScript/function-composition-1.vbs b/Task/Function-composition/VBScript/function-composition-1.vbs new file mode 100644 index 0000000000..20bfafae3a --- /dev/null +++ b/Task/Function-composition/VBScript/function-composition-1.vbs @@ -0,0 +1,18 @@ +option explicit +class closure + + private composition + + sub compose( f1, f2 ) + composition = f2 & "(" & f1 & "(p1))" + end sub + + public default function apply( p1 ) + apply = eval( composition ) + end function + + public property get formula + formula = composition + end property + +end class diff --git a/Task/Function-composition/VBScript/function-composition-2.vbs b/Task/Function-composition/VBScript/function-composition-2.vbs new file mode 100644 index 0000000000..25fe4c08dc --- /dev/null +++ b/Task/Function-composition/VBScript/function-composition-2.vbs @@ -0,0 +1,26 @@ +dim c +set c = new closure + +c.compose "ucase", "lcase" +wscript.echo c.formula +wscript.echo c("dog") + +c.compose "log", "exp" +wscript.echo c.formula +wscript.echo c(12.3) + +function inc( n ) + inc = n + 1 +end function + +c.compose "inc", "inc" +wscript.echo c.formula +wscript.echo c(12.3) + +function twice( n ) + twice = n * 2 +end function + +c.compose "twice", "inc" +wscript.echo c.formula +wscript.echo c(12.3) diff --git a/Task/Function-definition/Ada/function-definition-1.adb b/Task/Function-definition/Ada/function-definition-1.adb new file mode 100644 index 0000000000..7b9a9915ba --- /dev/null +++ b/Task/Function-definition/Ada/function-definition-1.adb @@ -0,0 +1 @@ +function Multiply (A, B : Float) return Float; diff --git a/Task/Function-definition/Ada/function-definition-2.adb b/Task/Function-definition/Ada/function-definition-2.adb new file mode 100644 index 0000000000..5322430102 --- /dev/null +++ b/Task/Function-definition/Ada/function-definition-2.adb @@ -0,0 +1,4 @@ +function Multiply (A, B : Float) return Float is +begin + return A * B; +end Multiply; diff --git a/Task/Function-definition/Ada/function-definition-3.adb b/Task/Function-definition/Ada/function-definition-3.adb new file mode 100644 index 0000000000..557ff024e7 --- /dev/null +++ b/Task/Function-definition/Ada/function-definition-3.adb @@ -0,0 +1 @@ +function Multiply(A, B: Float) return Float is (A * B); diff --git a/Task/Function-definition/Ada/function-definition-4.adb b/Task/Function-definition/Ada/function-definition-4.adb new file mode 100644 index 0000000000..6d7e9b17f1 --- /dev/null +++ b/Task/Function-definition/Ada/function-definition-4.adb @@ -0,0 +1,3 @@ +generic + type Number is digits <>; +function Multiply (A, B : Number) return Number; diff --git a/Task/Function-definition/Ada/function-definition-5.adb b/Task/Function-definition/Ada/function-definition-5.adb new file mode 100644 index 0000000000..28d97ba934 --- /dev/null +++ b/Task/Function-definition/Ada/function-definition-5.adb @@ -0,0 +1,4 @@ +function Multiply (A, B : Number) return Number is +begin + return A * B; +end Multiply; diff --git a/Task/Function-definition/Ada/function-definition-6.adb b/Task/Function-definition/Ada/function-definition-6.adb new file mode 100644 index 0000000000..1bff1e4b18 --- /dev/null +++ b/Task/Function-definition/Ada/function-definition-6.adb @@ -0,0 +1,7 @@ +with Multiply; +... +function Multiply_Integer is new Multiply(Number => Integer); +use Multiply_Integer; -- If you must + +type My_Integer is Range -100..100; +function Multiply_My_Integer is new Multiply(My_Integer); diff --git a/Task/Function-definition/AutoIt/function-definition.au3 b/Task/Function-definition/AutoIt/function-definition.au3 new file mode 100644 index 0000000000..8f7aa326ad --- /dev/null +++ b/Task/Function-definition/AutoIt/function-definition.au3 @@ -0,0 +1,7 @@ +#AutoIt Version: 3.2.10.0 +$I=11 +$J=12 +MsgBox(0,"Multiply", $I &" * "& $J &" = " & product($I,$J)) +Func product($a,$b) + Return $a * $b +EndFunc diff --git a/Task/Function-definition/COBOL/function-definition-1.cob b/Task/Function-definition/COBOL/function-definition-1.cob new file mode 100644 index 0000000000..36b6fec7b7 --- /dev/null +++ b/Task/Function-definition/COBOL/function-definition-1.cob @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. myTest. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 x PICTURE IS 9(3) VALUE IS 3. + 01 y PICTURE IS 9(3) VALUE IS 2. + 01 z PICTURE IS 9(9). + PROCEDURE DIVISION. + CALL "myMultiply" USING + BY CONTENT x, BY CONTENT y, + BY REFERENCE z. + DISPLAY z. + STOP RUN. + END PROGRAM myTest. + + IDENTIFICATION DIVISION. + PROGRAM-ID. myMultiply. + DATA DIVISION. + LINKAGE SECTION. + 01 x PICTURE IS 9(3). + 01 y PICTURE IS 9(3). + 01 z PICTURE IS 9(9). + PROCEDURE DIVISION USING BY REFERENCE x, y, z. + MULTIPLY x BY y GIVING z. + EXIT PROGRAM. + END PROGRAM myMultiply. diff --git a/Task/Function-definition/COBOL/function-definition-2.cob b/Task/Function-definition/COBOL/function-definition-2.cob new file mode 100644 index 0000000000..45cb3574b1 --- /dev/null +++ b/Task/Function-definition/COBOL/function-definition-2.cob @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. myTest. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION myMultiply. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 x PICTURE IS 9(3) VALUE IS 3. + 01 y PICTURE IS 9(3) VALUE IS 2. + PROCEDURE DIVISION. + DISPLAY myMultiply(x, y). + STOP RUN. + END PROGRAM myTest. + + IDENTIFICATION DIVISION. + FUNCTION-ID. myMultiply. + DATA DIVISION. + LINKAGE SECTION. + 01 x PICTURE IS 9(3). + 01 y PICTURE IS 9(3). + 01 z PICTURE IS 9(9). + PROCEDURE DIVISION USING x, y RETURNING z. + MULTIPLY x BY y GIVING z. + GOBACK. + END FUNCTION myMultiply. diff --git a/Task/Function-definition/Chapel/function-definition-1.chpl b/Task/Function-definition/Chapel/function-definition-1.chpl new file mode 100644 index 0000000000..dce621a59f --- /dev/null +++ b/Task/Function-definition/Chapel/function-definition-1.chpl @@ -0,0 +1,4 @@ +proc multiply(a, b) +{ + return a * b; +} diff --git a/Task/Function-definition/Chapel/function-definition-2.chpl b/Task/Function-definition/Chapel/function-definition-2.chpl new file mode 100644 index 0000000000..cd4150861a --- /dev/null +++ b/Task/Function-definition/Chapel/function-definition-2.chpl @@ -0,0 +1,4 @@ +proc multiply(a : ?t ... 2) +{ + return a(0) * a(1) +} diff --git a/Task/Function-definition/Crystal/function-definition.cr b/Task/Function-definition/Crystal/function-definition.cr new file mode 100644 index 0000000000..9a6b44e375 --- /dev/null +++ b/Task/Function-definition/Crystal/function-definition.cr @@ -0,0 +1,16 @@ +def multiply (a, b) + a * b +end + +# with type restrictions: +def multiply (a : Int32, b : Int32) + print "(typed overload) " + a * b +end + +# proc (anonymous function) +m = ->(a : Int32, b : Int32) { a * b } + +p! multiply(2, 3), + multiply(2.0, 3.0), + m.call(2, 3) diff --git a/Task/Function-definition/Emacs-Lisp/function-definition-1.el b/Task/Function-definition/Emacs-Lisp/function-definition-1.el new file mode 100644 index 0000000000..1e5a8148c1 --- /dev/null +++ b/Task/Function-definition/Emacs-Lisp/function-definition-1.el @@ -0,0 +1,2 @@ +(defun multiply (x y) + (* x y)) diff --git a/Task/Function-definition/Emacs-Lisp/function-definition-2.el b/Task/Function-definition/Emacs-Lisp/function-definition-2.el new file mode 100644 index 0000000000..0eaa89d659 --- /dev/null +++ b/Task/Function-definition/Emacs-Lisp/function-definition-2.el @@ -0,0 +1,3 @@ +(defun multiply (x y) + "Return the product of X and Y." + (* x y)) diff --git a/Task/Function-definition/Euphoria/function-definition-1.eu b/Task/Function-definition/Euphoria/function-definition-1.eu new file mode 100644 index 0000000000..dbefbdbb00 --- /dev/null +++ b/Task/Function-definition/Euphoria/function-definition-1.eu @@ -0,0 +1,3 @@ +function multiply( atom a, atom b ) + return a * b +end function diff --git a/Task/Function-definition/Euphoria/function-definition-2.eu b/Task/Function-definition/Euphoria/function-definition-2.eu new file mode 100644 index 0000000000..c58bdd4f0e --- /dev/null +++ b/Task/Function-definition/Euphoria/function-definition-2.eu @@ -0,0 +1,12 @@ +function multiply( object a, object b ) + return a * b +end function + +sequence a = {1,2,3,4} +sequence b = {5,6,7,8} + +? multiply( 9, 9 ) +? multiply( 3.14159, 3.14159 ) +? multiply( a, b ) +? multiply( a, 7 ) +? multiply( 10.39564, b ) diff --git a/Task/Function-definition/Gleam/function-definition.gleam b/Task/Function-definition/Gleam/function-definition.gleam new file mode 100644 index 0000000000..45be9f932e --- /dev/null +++ b/Task/Function-definition/Gleam/function-definition.gleam @@ -0,0 +1,3 @@ +fn multiply(x: Int, y: Int) -> Int { + x * y +} diff --git a/Task/Function-definition/Haxe/function-definition.hx b/Task/Function-definition/Haxe/function-definition.hx new file mode 100644 index 0000000000..b52441485b --- /dev/null +++ b/Task/Function-definition/Haxe/function-definition.hx @@ -0,0 +1,3 @@ +function multiply(x:Float, y:Float):Float{ + return x * y; +} diff --git a/Task/Function-definition/LOLCODE/function-definition.lol b/Task/Function-definition/LOLCODE/function-definition.lol new file mode 100644 index 0000000000..8d50259103 --- /dev/null +++ b/Task/Function-definition/LOLCODE/function-definition.lol @@ -0,0 +1,9 @@ +HAI 1.3 + +HOW IZ I MULTIPLY YR X AN YR Y + FOUND YR PRODUKT OF X AN Y +IF U SAY SO + +VISIBLE I IZ MULTIPLY YR 2 AND YR 3 MKAY + +KTHXBYE diff --git a/Task/Function-definition/Langur/function-definition-1.langur b/Task/Function-definition/Langur/function-definition-1.langur index 5878a47bf8..0445f67e8d 100644 --- a/Task/Function-definition/Langur/function-definition-1.langur +++ b/Task/Function-definition/Langur/function-definition-1.langur @@ -1 +1 @@ -val multiply = fn{*} +val multiply = fn(a, b) { a * b } diff --git a/Task/Function-definition/Langur/function-definition-2.langur b/Task/Function-definition/Langur/function-definition-2.langur index cfdc4aa62b..5878a47bf8 100644 --- a/Task/Function-definition/Langur/function-definition-2.langur +++ b/Task/Function-definition/Langur/function-definition-2.langur @@ -1 +1 @@ -val multiply = fn a, b: a * b +val multiply = fn{*} diff --git a/Task/Function-definition/Langur/function-definition-3.langur b/Task/Function-definition/Langur/function-definition-3.langur index 0445f67e8d..e8a58c5239 100644 --- a/Task/Function-definition/Langur/function-definition-3.langur +++ b/Task/Function-definition/Langur/function-definition-3.langur @@ -1 +1 @@ -val multiply = fn(a, b) { a * b } +val timestwo = fn{*2} diff --git a/Task/Function-definition/Langur/function-definition-4.langur b/Task/Function-definition/Langur/function-definition-4.langur new file mode 100644 index 0000000000..64c16021ee --- /dev/null +++ b/Task/Function-definition/Langur/function-definition-4.langur @@ -0,0 +1 @@ +val factorial = fn(x) { if(x < 2: 1; x * fn((x - 1))) } diff --git a/Task/Function-definition/PowerShell/function-definition-1.ps1 b/Task/Function-definition/PowerShell/function-definition-1.ps1 new file mode 100644 index 0000000000..c60ee38cd9 --- /dev/null +++ b/Task/Function-definition/PowerShell/function-definition-1.ps1 @@ -0,0 +1,3 @@ +function multiply { + return $args[0] * $args[1] +} diff --git a/Task/Function-definition/PowerShell/function-definition-2.ps1 b/Task/Function-definition/PowerShell/function-definition-2.ps1 new file mode 100644 index 0000000000..3f8bc672e3 --- /dev/null +++ b/Task/Function-definition/PowerShell/function-definition-2.ps1 @@ -0,0 +1,3 @@ +function multiply { + $args[0] * $args[1] +} diff --git a/Task/Function-definition/PowerShell/function-definition-3.ps1 b/Task/Function-definition/PowerShell/function-definition-3.ps1 new file mode 100644 index 0000000000..191d3a9a96 --- /dev/null +++ b/Task/Function-definition/PowerShell/function-definition-3.ps1 @@ -0,0 +1,3 @@ +function multiply ($a, $b) { + return $a * $b +} diff --git a/Task/Function-definition/PowerShell/function-definition-4.ps1 b/Task/Function-definition/PowerShell/function-definition-4.ps1 new file mode 100644 index 0000000000..64fae44b8f --- /dev/null +++ b/Task/Function-definition/PowerShell/function-definition-4.ps1 @@ -0,0 +1,4 @@ +function multiply { + param ($a, $b) + return $a * $b +} diff --git a/Task/Function-definition/PowerShell/function-definition-5.ps1 b/Task/Function-definition/PowerShell/function-definition-5.ps1 new file mode 100644 index 0000000000..db297620cd --- /dev/null +++ b/Task/Function-definition/PowerShell/function-definition-5.ps1 @@ -0,0 +1,3 @@ +function multiply ([int] $a, [int] $b) { + return $a * $b +} diff --git a/Task/Function-definition/REXX/function-definition.rexx b/Task/Function-definition/REXX/function-definition.rexx new file mode 100644 index 0000000000..1d6fc424e5 --- /dev/null +++ b/Task/Function-definition/REXX/function-definition.rexx @@ -0,0 +1,34 @@ +-- 11 Sep 2025 +include Setting + +say 'FUNCTION DEFINITION' +say version +say +xx=0; yy=0; rr=0 +say 'xx =' xx 'yy =' yy 'rr =' rr +say 'Multiply1(2,3)' '=' Multiply1(2,3) +say 'xx =' xx 'yy =' yy 'rr =' rr +say 'Multiply2(3,5)' '=' Multiply2(3,5) +say 'xx =' xx 'yy =' yy 'rr =' rr +xx=5; yy=7 +say 'xx =' xx 'yy =' yy 'rr =' rr +say 'Multiply3(5,7)' '=' Multiply3() +say 'xx =' xx 'yy =' yy 'rr =' rr +exit + +Multiply1: +procedure +arg xx,yy +rr=xx*yy +return rr + +Multiply2: +arg xx,yy +rr=xx*yy +return rr + +Multiply3: +rr=xx*yy +return rr + +include Math diff --git a/Task/Function-definition/Rebol/function-definition.rebol b/Task/Function-definition/Rebol/function-definition.rebol new file mode 100644 index 0000000000..2f644d424c --- /dev/null +++ b/Task/Function-definition/Rebol/function-definition.rebol @@ -0,0 +1 @@ +multiply: func [a b][a * b] diff --git a/Task/Function-definition/Rye/function-definition-1.rye b/Task/Function-definition/Rye/function-definition-1.rye new file mode 100644 index 0000000000..944dd8c78b --- /dev/null +++ b/Task/Function-definition/Rye/function-definition-1.rye @@ -0,0 +1 @@ +multiply: fn { a b } { a * b } diff --git a/Task/Function-definition/Rye/function-definition-2.rye b/Task/Function-definition/Rye/function-definition-2.rye new file mode 100644 index 0000000000..2f2cc5ea24 --- /dev/null +++ b/Task/Function-definition/Rye/function-definition-2.rye @@ -0,0 +1 @@ +multiply: fn { a b } { * b } diff --git a/Task/Function-definition/Rye/function-definition-3.rye b/Task/Function-definition/Rye/function-definition-3.rye new file mode 100644 index 0000000000..ca8885cbcf --- /dev/null +++ b/Task/Function-definition/Rye/function-definition-3.rye @@ -0,0 +1 @@ +multiply: pfn { a b } { a * b } diff --git a/Task/Function-definition/SIL/function-definition.sil b/Task/Function-definition/SIL/function-definition.sil new file mode 100644 index 0000000000..21bfbe3c19 --- /dev/null +++ b/Task/Function-definition/SIL/function-definition.sil @@ -0,0 +1,3 @@ +funcmultiply +r = x * y +return diff --git a/Task/Function-definition/VBScript/function-definition-1.vbs b/Task/Function-definition/VBScript/function-definition-1.vbs new file mode 100644 index 0000000000..dddc595cb6 --- /dev/null +++ b/Task/Function-definition/VBScript/function-definition-1.vbs @@ -0,0 +1,3 @@ +function multiply( multiplicand, multiplier ) + multiply = multiplicand * multiplier +end function diff --git a/Task/Function-definition/VBScript/function-definition-2.vbs b/Task/Function-definition/VBScript/function-definition-2.vbs new file mode 100644 index 0000000000..bcc9a28c95 --- /dev/null +++ b/Task/Function-definition/VBScript/function-definition-2.vbs @@ -0,0 +1,2 @@ +dim twosquared +twosquared = multiply(2, 2) diff --git a/Task/Function-frequency/REXX/function-frequency-3.rexx b/Task/Function-frequency/REXX/function-frequency-3.rexx new file mode 100644 index 0000000000..05ffecf5c2 --- /dev/null +++ b/Task/Function-frequency/REXX/function-frequency-3.rexx @@ -0,0 +1,138 @@ +-- 21 Feb 2026 +include Setting +parse arg program + +say 'FUNCTION FREQUENCY' +say version +call ReadSource +call CleanSource +call CollectInvokes +call SortSt 'invo.' +call ReportInvokes +call Timer +exit + +ReadSource: +-- Read all lines in a stem +if program='' then + program='FuncFreq.rex' +else + program=program'.rex' +say 'Invoke frequencies for program' program +say +call Stream program,'c','open read' +srce.=0; n=0 +do while Lines(program) + record=LineIn(program) + n=n+1; srce.n=record +end +srce.0=n +call Stream program,'c','close' +return + +CleanSource: +-- Erase all characters that are (in this order): +-- within a '' literal or a "" literal +-- within a /*...*/ comment block +-- after -- ... comment +-- not allowed in names +cleanc=0 +p1=0; q1=0 +do i = 1 to srce.0 + cleanl=0 + s=srce.i; k=Length(s) + do j = 1 to k +-- Substring for literals + p1=SubStr(s,j,1) +-- Erase literal + if p1 = "'" | p1 = '"' then do + if cleanl then do + s=Overlay(' ',s,j) + if p1 = q1 then + cleanl=0 + end + else do + q1=p1; cleanl=1 + end + end + if cleanl then + s=Overlay(' ',s,j) + end j +-- Substring for comments + p2=SubStr(s,j,2) +-- Erase block /*...*/ comment + if p2 = '/*' then + cleanc=1 + else do + if p2 = '*/' then do + s=Overlay(' ',s,j,2) + cleanc=0 + end + end + if cleanc then do + s=Overlay(' ',s,j) + iterate j + end +-- Erase -- ... comment + if p2 = '--' then do + s=Overlay(' ',s,j,k) + leave j + end +-- Erase all characters not allowed in names + s=Translate(s,' ','+-*|<>,;=/\%)') + srce.i=s +end i +return + +CollectInvokes: +-- Collect invocations 'Name()' or 'call Name' +invo.=0; v=0 +do i = 1 to srce.0 + s=srce.i +-- Parse words + wrds.=0; n=0 + do until s = '' + n=n+1; parse var s wrds.n s + end +-- Find invocations + wrds.0=n + do j = 1 to wrds.0 + w=wrds.j +-- Call Name + if Upper(w) = 'CALL' then do + k=j+1; v=v+1; invo.v=wrds.k + end +-- Name() + else do + p1=1; p2=Pos('(',w) + do while p2 > 0 + a=SubStr(w,p1,p2-p1) + if a <> '' then do + v=v+1; invo.v=SubStr(w,p1,p2-p1) + end + p1=p2+1; p2=Pos('(',w,p1) + end + end + end j +end i +invo.0=v +return + +ReportInvokes: +-- Aggregate and report +p=invo.1; n=1 +do i = 2 to invo.0 + v = invo.i + if v = p then + n=n+1 + else do + say Right(n,3) p + p=v; n=1 + end +end i +say Right(n,3) p +say +return + +-- SortSt; Timer +include Math diff --git a/Task/Function-prototype/Ada/function-prototype-1.adb b/Task/Function-prototype/Ada/function-prototype-1.adb new file mode 100644 index 0000000000..06fb630bb4 --- /dev/null +++ b/Task/Function-prototype/Ada/function-prototype-1.adb @@ -0,0 +1,6 @@ +function noargs return Integer; +function twoargs (a, b : Integer) return Integer; +-- varargs do not exist +function optionalargs (a, b : Integer := 0) return Integer; +-- all parameters are always named, only calling by name differs +procedure dostuff (a : Integer); diff --git a/Task/Function-prototype/Ada/function-prototype-2.adb b/Task/Function-prototype/Ada/function-prototype-2.adb new file mode 100644 index 0000000000..9d68054fa6 --- /dev/null +++ b/Task/Function-prototype/Ada/function-prototype-2.adb @@ -0,0 +1,5 @@ +type Box; -- tell Ada a box exists (undefined yet) +type accBox is access Box; -- define a pointer to a box +type Box is record -- later define what a box is + next : accBox; -- including that a box holds access to other boxes +end record; diff --git a/Task/Function-prototype/Ada/function-prototype-3.adb b/Task/Function-prototype/Ada/function-prototype-3.adb new file mode 100644 index 0000000000..43e971a85f --- /dev/null +++ b/Task/Function-prototype/Ada/function-prototype-3.adb @@ -0,0 +1,4 @@ +package Stack is + procedure Push(Object:Integer); + function Pull return Integer; +end Stack; diff --git a/Task/Function-prototype/Ada/function-prototype-4.adb b/Task/Function-prototype/Ada/function-prototype-4.adb new file mode 100644 index 0000000000..070d9a600a --- /dev/null +++ b/Task/Function-prototype/Ada/function-prototype-4.adb @@ -0,0 +1,13 @@ +package body Stack is + + procedure Push(Object:Integer) is + begin + -- implementation goes here + end; + + function Pull return Integer; + begin + -- implementation goes here + end; + +end Stack; diff --git a/Task/Function-prototype/Ada/function-prototype-5.adb b/Task/Function-prototype/Ada/function-prototype-5.adb new file mode 100644 index 0000000000..8709c94fd0 --- /dev/null +++ b/Task/Function-prototype/Ada/function-prototype-5.adb @@ -0,0 +1,8 @@ +with Stack; +procedure Main is + N:integer:=5; +begin + Push(N); + ... + N := Pull; +end Main; diff --git a/Task/Function-prototype/COBOL/function-prototype.cob b/Task/Function-prototype/COBOL/function-prototype.cob new file mode 100644 index 0000000000..e483b4e7f3 --- /dev/null +++ b/Task/Function-prototype/COBOL/function-prototype.cob @@ -0,0 +1,39 @@ + *> A subprogram taking no arguments and returning nothing. + PROGRAM-ID. no-args PROTOTYPE. + END PROGRAM no-args. + + *> A subprogram taking two 8-digit numbers as arguments, and returning + *> an 8-digit number. + PROGRAM-ID. two-args PROTOTYPE. + DATA DIVISION. + LINKAGE SECTION. + 01 arg-1 PIC 9(8). + 01 arg-2 PIC 9(8). + 01 ret PIC 9(8). + PROCEDURE DIVISION USING arg-1, arg-2 RETURNING ret. + END PROGRAM two-args. + + *> A subprogram taking two optional arguments which are 8-digit + *> numbers (passed by reference (the default and compulsory for + *> optional arguments)). + PROGRAM-ID. optional-args PROTOTYPE. + DATA DIVISION. + LINKAGE SECTION. + 01 arg-1 PIC 9(8). + 01 arg-2 PIC 9(8). + PROCEDURE DIVISION USING OPTIONAL arg-1, OPTIONAL arg-2. + END PROGRAM optional-args. + + *> Standard COBOL does not support varargs or named parameters. + + *> A function from another language, taking a 32-bit integer by + *> value and returning a 32-bit integer (in Visual COBOL). + PROGRAM-ID. foreign-func PROTOTYPE. + OPTIONS. + ENTRY-CONVENTION some-langauge. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 arg PIC S9(9) USAGE COMP-5. + 01 ret PIC S9(9) USAGE COMP-5. + PROCEDURE DIVISION USING arg RETURNING ret. + END PROGRAM foreign-func. diff --git a/Task/Fusc-sequence/Ada/fusc-sequence.adb b/Task/Fusc-sequence/Ada/fusc-sequence.adb new file mode 100644 index 0000000000..5c4c2e404c --- /dev/null +++ b/Task/Fusc-sequence/Ada/fusc-sequence.adb @@ -0,0 +1,96 @@ +with Ada.Text_IO; +with Ada.Integer_Text_IO; + +procedure Show_Fusc is + + generic + Precalculate : Natural; + package Fusc_Sequences is + function Fusc (N : in Natural) return Natural; + end Fusc_Sequences; + + package body Fusc_Sequences is + + Precalculated_Fusc : array (0 .. Precalculate) of Natural; + + function Fusc_Slow (N : in Natural) return Natural is + begin + if N = 0 or N = 1 then + return N; + elsif N mod 2 = 0 then + return Fusc_Slow (N / 2); + else + return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2); + end if; + end Fusc_Slow; + + function Fusc (N : in Natural) return Natural is + begin + if N <= Precalculate then + return Precalculated_Fusc (N); + elsif N mod 2 = 0 then + return Fusc (N / 2); + else + return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2); + end if; + end Fusc; + + begin + for N in Precalculated_Fusc'Range loop + Precalculated_Fusc (N) := Fusc_Slow (N); + end loop; + end Fusc_Sequences; + + + package Fusc_Sequence is + new Fusc_Sequences (Precalculate => 200_000); + + function Fusc (N : in Natural) return Natural + renames Fusc_Sequence.Fusc; + + + procedure Print_Small_Fuscs is + use Ada.Text_IO; + begin + Put_Line ("First 61 numbers in the fusc sequence:"); + for N in 0 .. 60 loop + Put (Fusc (N)'Image); + Put (" "); + end loop; + New_Line; + end Print_Small_Fuscs; + + + procedure Print_Large_Fuscs (High : in Natural) is + use Ada.Text_IO; + use Ada.Integer_Text_IO; + subtype N_Range is Natural range Natural'First .. High; + F : Natural; + Len : Natural; + Max_Len : Natural := 0; + Placeholder : String := " n fusc(n)"; + Image_N : String renames Placeholder (1 .. 8); + Image_Fusc : String renames Placeholder (10 .. Placeholder'Last); + begin + New_Line; + Put_Line ("Printing all largest Fusc numbers upto " & High'Image); + Put_Line (Placeholder); + + for N in N_Range loop + F := Fusc (N); + Len := F'Image'Length; + + if Len > Max_Len then + Max_Len := Len; + Put (Image_N, N); + Put (Image_Fusc, F); + Put (Placeholder); + New_Line; + end if; + end loop; + end Print_Large_Fuscs; + +begin + Print_Small_Fuscs; + Print_Large_Fuscs (High => 20_000_000); +end Show_Fusc; diff --git a/Task/Fusc-sequence/COBOL/fusc-sequence.cob b/Task/Fusc-sequence/COBOL/fusc-sequence.cob new file mode 100644 index 0000000000..79f12919f3 --- /dev/null +++ b/Task/Fusc-sequence/COBOL/fusc-sequence.cob @@ -0,0 +1,110 @@ +IDENTIFICATION DIVISION. + PROGRAM-ID. FUSC-SEQUENCE. + + ENVIRONMENT DIVISION. + + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 FUSC-MAX PIC 9(8) COMP VALUE 2000. + 01 FUSC-TABLE. + 05 FUSC-VAL OCCURS 2000 TIMES + PIC 9(8) COMP. + + 01 WS-N PIC 9(8) COMP. + 01 WS-I PIC 9(2) COMP. + 01 WS-J PIC 9(8) COMP. + 01 WS-START PIC 9(8) COMP. + 01 WS-VAL PIC S9(8) COMP. + 01 WS-HALF PIC 9(8) COMP. + 01 WS-HALF-MINUS PIC 9(8) COMP. + 01 WS-HALF-PLUS PIC 9(8) COMP. + 01 WS-POWER PIC 9(8) COMP. + 01 WS-IDX PIC 9(8) COMP. + 01 WS-FOUND PIC X VALUE 'N'. + 01 WS-DISPLAY-IDX PIC Z(7)9. + 01 WS-DISPLAY-VAL PIC Z(7)9. + + PROCEDURE DIVISION. + + 000-MAIN SECTION. + MAIN-PARA. + PERFORM 100-INIT-FUSC + PERFORM 200-DISPLAY-FIRST-61 + PERFORM 300-DISPLAY-LENGTH-RECORDS + STOP RUN. + + *>---------------------------------------------------------------- + *> Initialize the FUSC array + *>---------------------------------------------------------------- + 100-INIT-FUSC SECTION. + MOVE 0 TO FUSC-VAL(1) + MOVE 1 TO FUSC-VAL(2) + PERFORM VARYING WS-N FROM 3 BY 1 + UNTIL WS-N > FUSC-MAX + EVALUATE TRUE + WHEN FUNCTION MOD(WS-N - 1, 2) = 0 + COMPUTE WS-HALF = (WS-N - 1) / 2 + 1 + MOVE FUSC-VAL(WS-HALF) TO FUSC-VAL(WS-N) + WHEN OTHER + COMPUTE WS-HALF-MINUS = + (WS-N - 2) / 2 + 1 + COMPUTE WS-HALF-PLUS = + WS-N / 2 + 1 + COMPUTE FUSC-VAL(WS-N) = + FUSC-VAL(WS-HALF-MINUS) + + FUSC-VAL(WS-HALF-PLUS) + END-EVALUATE + END-PERFORM. + + *>---------------------------------------------------------------- + *> Display first 61 fusc numbers (0-based index 0..60) + *>---------------------------------------------------------------- + 200-DISPLAY-FIRST-61 SECTION. + DISPLAY "Show the first 61 fusc numbers " + "(starting at zero) in a horizontal format" + PERFORM VARYING WS-N FROM 1 BY 1 + UNTIL WS-N > 61 + MOVE FUSC-VAL(WS-N) TO WS-DISPLAY-VAL + DISPLAY FUNCTION TRIM(WS-DISPLAY-VAL + LEADING) " " WITH NO ADVANCING + END-PERFORM + DISPLAY " ". + + *>---------------------------------------------------------------- + *> Display fusc numbers whose value first exceeds 10^i + *>---------------------------------------------------------------- + 300-DISPLAY-LENGTH-RECORDS SECTION. + DISPLAY " " + DISPLAY "Show the fusc number (and its index) whose " + "length is greater than any previous fusc number length." + MOVE 1 TO WS-START + PERFORM VARYING WS-I FROM 0 BY 1 + UNTIL WS-I > 5 + EVALUATE WS-I + WHEN 0 + MOVE -1 TO WS-VAL + WHEN OTHER + MOVE 1 TO WS-POWER + PERFORM VARYING WS-IDX FROM 1 BY 1 + UNTIL WS-IDX > WS-I + MULTIPLY 10 BY WS-POWER + END-PERFORM + MOVE WS-POWER TO WS-VAL + END-EVALUATE + MOVE 'N' TO WS-FOUND + PERFORM VARYING WS-J FROM WS-START BY 1 + UNTIL WS-J > FUSC-MAX OR WS-FOUND = 'Y' + IF FUSC-VAL(WS-J) > WS-VAL + COMPUTE WS-N = WS-J - 1 + MOVE WS-N TO WS-DISPLAY-IDX + MOVE FUSC-VAL(WS-J) TO WS-DISPLAY-VAL + DISPLAY "fusc[" + FUNCTION TRIM(WS-DISPLAY-IDX LEADING) + "] = " + FUNCTION TRIM(WS-DISPLAY-VAL LEADING) + MOVE WS-J TO WS-START + MOVE 'Y' TO WS-FOUND + END-IF + END-PERFORM + END-PERFORM. diff --git a/Task/Fusc-sequence/Fortran/fusc-sequence.f b/Task/Fusc-sequence/Fortran/fusc-sequence.f new file mode 100644 index 0000000000..4d5c8c0f53 --- /dev/null +++ b/Task/Fusc-sequence/Fortran/fusc-sequence.f @@ -0,0 +1,185 @@ +! +! Fusc sequence +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.04 +! GNU Fortran (Ubuntu 14.2.0-19ubuntu2) 14.2.0 on Kubuntu 25.04 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! U.B., September 2025 + +program FuscNumbers + + implicit none + + integer, parameter :: kInt = 4 + integer, parameter :: maxdigs = 6 + integer, parameter :: strLen = 20 + + integer (kind=kInt), allocatable :: fuscMem(:) + + integer :: capacity, content ! usage of above container + + integer (kind=kInt) :: w,c,t + integer (kind=kINt) :: i, f + integer :: d=0, n=61, digs=1 + + character (len=strLen) :: sNum(2) ! for formatted output of integer numbers + + content = 0 + capacity = 1024 + call resize (fuscMem, capacity) + + call push (0) + call push (1) + + w = -1 + c = 0 + n = 61 + write ( *, '("First " , i0, " numbers in the fusc sequence:" )') n + + i = 0 + do while (i .lt. 61) + f = fusc(i) + if (mod (i, 20) .ne. 0) then + write (*, '(i2, x)', advance='no' ) f + else + write (*, '(i2,x)') f + endif + i = i + 1 + end do + + write (*, '(/"Fusc numbers with more digits than any previous (1 to 6 digits):")') + write (*, '( " Index Value")') + i = 0 + do while (digs <= maxdigs) + f = fusc (i) + if (f .ge. d) then + ! show all numbers with commas (if appropriate). + snum(1) = GroupedDigits(i, 10) + snum(2) = GroupedDigits(f,10) + if (digs .gt.1) then + write (*,'(i2, " digits: ", A10,x,A )' ) digs, snum(1), snum(2) + else + write (*,'(i2, " digit : ", A10,x,A )' ) digs, snum(1), snum(2) + endif + if (d .eq. 0) then + d = 10 + else + d = d * 10 + endif + digs = digs + 1 + if (digs .gt. 6) exit + end if + i = i + 1 + end do + + + contains + + function fusc (n) result (ret) + integer (kind=kint), intent(in) :: n + integer (kind=kInt) ret + + + if (n .lt. content) then + ret = fuscMem (1+n) + else + if (iand (n,1_kint) .eq. 0) then ! Even n has bit 0 = zero + ret = fuscMem(1+n/2) + call push (ret) ! Store for future use. + else ! Else its odd. + ret = fuscMem(1+(n-1)/2) + fuscMem(1+(n+2)/2) + call push (ret) + end if + end if + + end function fusc + + ! --------------------- + ! memoize another value + ! --------------------- + subroutine push (k) + integer (kind=kint), intent (in) :: k + + content = content+1 + + ! If we would exceed capacity of array 'Words', we need to increment capacity + if (content .gt. capacity) then + capacity = 2*capacity + call resize (fuscMem, capacity) + end if + fuscMem(content) = k + end subroutine push + + + ! ---------------------------------------------- + ! Increase allocated size of dynamic array 'var' + ! ---------------------------------------------- + subroutine resize(var, newSize) + integer (kind=kint), allocatable, intent(inout) :: var(:) ! The array to be increased + integer, intent(in) :: newSize ! The new size of var + integer (kind=kint), allocatable :: tmp(:) ! Temporary storage + integer :: oldSize ! Current array size + integer :: ii ! Loop index + + ! Copy allocated values to temporary, then allocate var with + ! new size and copy back saved values. + ! Could be done with move_alloc but this would not be portable to OpenVMS Fortran + + if (allocated(var)) then + oldSize = size(var) + else + oldSize = 0 + end if + + if (newSize .gt. oldSize) then ! only increment + if (oldSize .gt.0) then + allocate(tmp (oldSize)) + tmp(:oldSize) = var(:oldSize) + deallocate (var) + end if + allocate(var(newSize)) + if (allocated(tmp) .and. allocated (var) ) then + oldSize = min(size(tmp, 1), size(var, 1)) + var(:oldSize) = tmp(:oldSize) + deallocate (tmp) + end if + end if +end subroutine resize + + +! ---------------------------------------------------------------- + ! Fortran does not have a way to use locales for output. + ! Manual insert of separating commas such as 1,345,678 for 1345678 + ! ---------------------------------------------------------------- + function GroupedDigits (n, width) result (outStr) + integer(kind=kint), intent (in) :: n + integer :: width + character (len=width) :: outStr + character (len=2*strLen) :: workStr + integer :: ii, jj, cnt, trueLen + + + ! Write n into a string, then copy the digits to a second string, + ! inserting separater after every 3 digits. + write (workStr, '(i0)') n + ! Adjust left, then cutoff trailing blanks + workstr = adjustl (workstr) + trueLen = len_trim (workStr) + + outStr = ' ' + jj = width + cnt = 0 + do ii=trueLen, 1, -1 ! Copy backwards for correct grouping. + outStr (jj:jj) = workStr (ii:ii) + jj = jj -1 + cnt = cnt + 1 + ! Insert comma after 3 digits, but only if more digits follow. + if (mod (cnt, 3) .eq. 0 .and. ii .gt. 1 .and. workStr(ii-1:ii-1) .ne. ' ') then + outStr (jj:jj) = ',' + jj = jj - 1 + endif + end do + + end function GroupedDigits + + end program FuscNumbers diff --git a/Task/Fusc-sequence/Pluto/fusc-sequence.pluto b/Task/Fusc-sequence/Pluto/fusc-sequence.pluto new file mode 100644 index 0000000000..b05612a503 --- /dev/null +++ b/Task/Fusc-sequence/Pluto/fusc-sequence.pluto @@ -0,0 +1,27 @@ +local fmt = require "fmt" + +print("The first 61 numbers in the fusc sequence are:") +local fusc = {0, 1} +local fusc2 = {{0, 0}} +local max_len = 1 +local n = 2 +while n < 20e6 do -- limit to indices under 20 million say + local f = (n % 2 == 0) ? fusc[n/2 + 1] : fusc[(n - 1)/2 + 1] + fusc[(n+1)/2 + 1] + fusc:insert(f) + local len = #tostring(f) + if len > max_len then + max_len = len + if n <= 60 then + fusc2:insert({n, f}) + else + fmt.print("%10s %s", fmt.int(n), fmt.int(f)) + end + end + if n == 60 then + for fusc as e do io.write($"{e} ") end + print("\n\nFirst terms longer than any previous ones for indices < 20,000,000:") + print(" Index Value") + for fusc2 as iv do fmt.print("%10d %d", iv[1], iv[2]) end + end + n += 1 +end diff --git a/Task/GUI-Maximum-window-dimensions/Ada/gui-maximum-window-dimensions.adb b/Task/GUI-Maximum-window-dimensions/Ada/gui-maximum-window-dimensions.adb new file mode 100644 index 0000000000..bba418fc82 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Ada/gui-maximum-window-dimensions.adb @@ -0,0 +1,27 @@ +with Gtk.Main; +with Glib; +with Gtk.Window; use Gtk.Window; +with Gtk.Enums; use Gtk.Enums; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Max_Size is + + Win : Gtk_Window; + Win_W, Win_H : Glib.Gint; + package Int_Io is new Integer_IO (Glib.Gint); + Hid : Gtk.Main.Quit_Handler_Id; + +begin + Gtk.Main.Init; + Gtk_New (Win); + Initialize (Win, Window_Toplevel); + Maximize (Win); + Show (Win); + Get_Size (Win, Win_W, Win_H); + Put ("Maximum dimensions of window : W "); + Int_Io.Put (Win_W, Width => 4); + Put (" x H "); + Int_Io.Put (Win_H, Width => 4); + New_Line; + Hid := Gtk.Main.Quit_Add_Destroy (0, Win); +end Max_Size; diff --git a/Task/GUI-component-interaction/Ada/gui-component-interaction.adb b/Task/GUI-component-interaction/Ada/gui-component-interaction.adb new file mode 100644 index 0000000000..152d546473 --- /dev/null +++ b/Task/GUI-component-interaction/Ada/gui-component-interaction.adb @@ -0,0 +1,158 @@ +with Ada.Numerics.Discrete_Random; +with Ada.Strings.Fixed; +with Gtk.Main; +with Gtk.Handlers; +with Gtk.Button; +with Gtk.Window; +with Gtk.GEntry; +with Gtk.Editable; +with Gtk.Box; +with Gtk.Widget; +with Glib.Values; +with Gtkada.Dialogs; + +procedure Interaction is + + The_Value : Natural := 0; + + package Natural_Random is new Ada.Numerics.Discrete_Random (Natural); + RNG : Natural_Random.Generator; + + Main_Window : Gtk.Window.Gtk_Window; + Content : Gtk.Box.Gtk_Vbox; + Increment_Button : Gtk.Button.Gtk_Button; + Random_Button : Gtk.Button.Gtk_Button; + Entry_Field : Gtk.GEntry.Gtk_Entry; + + package Entry_Callbacks is new Gtk.Handlers.Callback + (Gtk.GEntry.Gtk_Entry_Record); + + package Button_Callbacks is new Gtk.Handlers.Callback + (Gtk.Button.Gtk_Button_Record); + + package Window_Callbacks is new Gtk.Handlers.Return_Callback + (Gtk.Window.Gtk_Window_Record, Boolean); + + -- update displayed text + procedure Update_Entry is + begin + Gtk.GEntry.Set_Text + (The_Entry => Entry_Field, + Text => + Ada.Strings.Fixed.Trim + (Source => Natural'Image (The_Value), + Side => Ada.Strings.Both)); + end Update_Entry; + + -- read from text entry + procedure Update_Value is + begin + The_Value := Natural'Value (Gtk.GEntry.Get_Text (Entry_Field)); + exception + when Constraint_Error => + The_Value := 0; + end Update_Value; + + -- make sure that only numbers are entered + procedure On_Insert_Text + (Object : access Gtk.GEntry.Gtk_Entry_Record'Class; + Params : Glib.Values.GValues) + is + Length : constant Glib.Gint := + Glib.Values.Get_Int (Glib.Values.Nth (Params, 2)); + Text : constant String := + Glib.Values.Get_String (Glib.Values.Nth (Params, 1), Length); + begin + declare + Number : Natural; + begin + Number := Natural'Value (Text); + exception + when Constraint_Error => + -- refuse values that are not parsable + Gtk.Handlers.Emit_Stop_By_Name + (Object => Object, + Name => Gtk.Editable.Signal_Insert_Text); + end; + end On_Insert_Text; + + -- Callback for click event + procedure On_Increment_Click + (Object : access Gtk.Button.Gtk_Button_Record'Class) + is + begin + Update_Value; + The_Value := The_Value + 1; + Update_Entry; + end On_Increment_Click; + + -- Callback for click event + procedure On_Random_Click + (Object : access Gtk.Button.Gtk_Button_Record'Class) + is + use type Gtkada.Dialogs.Message_Dialog_Buttons; + begin + if Gtkada.Dialogs.Message_Dialog + (Msg => "Really reset to random value?", + Dialog_Type => Gtkada.Dialogs.Confirmation, + Buttons => Gtkada.Dialogs.Button_Yes or + Gtkada.Dialogs.Button_No, + Default_Button => Gtkada.Dialogs.Button_Yes) = + Gtkada.Dialogs.Button_Yes + then + The_Value := Natural_Random.Random (RNG); + Update_Entry; + end if; + end On_Random_Click; + + -- Callback for delete event + function On_Main_Window_Delete + (Object : access Gtk.Window.Gtk_Window_Record'Class) + return Boolean + is + begin + Gtk.Main.Main_Quit; + return True; + end On_Main_Window_Delete; + +begin + -- initialize random number generator + Natural_Random.Reset (RNG); + + Gtk.Main.Init; + + Gtk.GEntry.Gtk_New (Widget => Entry_Field); + Update_Entry; + Entry_Callbacks.Connect + (Widget => Entry_Field, + Name => Gtk.Editable.Signal_Insert_Text, + Cb => On_Insert_Text'Access); + + Gtk.Button.Gtk_New (Button => Increment_Button, Label => "Increment"); + Gtk.Button.Gtk_New (Button => Random_Button, Label => "Random"); + + Button_Callbacks.Connect + (Widget => Increment_Button, + Name => Gtk.Button.Signal_Clicked, + Marsh => Button_Callbacks.To_Marshaller (On_Increment_Click'Access)); + Button_Callbacks.Connect + (Widget => Random_Button, + Name => Gtk.Button.Signal_Clicked, + Marsh => Button_Callbacks.To_Marshaller (On_Random_Click'Access)); + + Gtk.Box.Gtk_New_Vbox (Box => Content); + Gtk.Box.Add (Container => Content, Widget => Entry_Field); + Gtk.Box.Add (Container => Content, Widget => Increment_Button); + Gtk.Box.Add (Container => Content, Widget => Random_Button); + + Gtk.Window.Gtk_New (Window => Main_Window); + Gtk.Window.Add (Container => Main_Window, Widget => Content); + + Window_Callbacks.Connect + (Widget => Main_Window, + Name => Gtk.Widget.Signal_Delete_Event, + Cb => On_Main_Window_Delete'Access); + Gtk.Window.Show_All (Widget => Main_Window); + + Gtk.Main.Main; +end Interaction; diff --git a/Task/GUI-component-interaction/Euphoria/gui-component-interaction.eu b/Task/GUI-component-interaction/Euphoria/gui-component-interaction.eu new file mode 100644 index 0000000000..bf27a4fb40 --- /dev/null +++ b/Task/GUI-component-interaction/Euphoria/gui-component-interaction.eu @@ -0,0 +1,42 @@ +include GtkEngine.e -- see OpenEuphoria.org + +constant -- interface + win = create(GtkWindow,"title=GUI Component Interaction;size=200x100;border=10;$destroy=Quit"), + pan = create(GtkBox,"orientation=vertical;spacing=10"), + inp = create(GtkEntry,"name=Input;text=0;$activate=Validate"), + box = create(GtkButtonBox), + btn1 = create(GtkButton,"gtk-add#_Increment","Increment"), + btn2 = create(GtkButton,"gtk-help#_Random","Random") + +add(win,pan) +add(pan,inp) +add(box,{btn1,btn2}) +pack(pan,-box) + +show_all(win) +main() + +----------------------------- +global function Validate() -- warns about invalid entry, does not prevent it; +----------------------------- +if not t_digit(trim_head(get("Input.text"),"- ")) then + return Warn(win,"Validate","This is not a valid number","Try again!") +end if +return 1 +end function + +--------------------------- +global function Increment() +--------------------------- +set("Input.value",get("Input.value")+1) +return 1 +end function + +------------------------ +global function Random() +------------------------ +if Question(win,"Random","Click OK for a random number",,GTK_BUTTONS_OK_CANCEL) = MB_OK then + set("Input.value",rand(1000)) +end if +return 1 +end function diff --git a/Task/GUI-component-interaction/Lua/gui-component-interaction.lua b/Task/GUI-component-interaction/Lua/gui-component-interaction.lua new file mode 100644 index 0000000000..531433f70a --- /dev/null +++ b/Task/GUI-component-interaction/Lua/gui-component-interaction.lua @@ -0,0 +1,25 @@ +local ui = require "ui" +math.randomseed(os.time()) + +local win = ui.Window("GUI component interaction", 320, 200) + +local entry = ui.Entry(win, 0, 124, 40) +entry.enabled = false + +ui.Button(win, "Increment", 105, 90).onClick = function (self) + entry.text = entry.text + 1 +end + +ui.Button(win, "Random", 110, 130).onClick = function (self) + if ui.confirm("Set the field to a random number?") == "yes" then + entry.text = math.random(100) + end + +end + +win:show() +-- update the user interface until the user closes the Window +repeat + sleep(1) + ui.update() +until not win.visible diff --git a/Task/GUI-component-interaction/PowerShell/gui-component-interaction.ps1 b/Task/GUI-component-interaction/PowerShell/gui-component-interaction.ps1 new file mode 100644 index 0000000000..d94ddd3010 --- /dev/null +++ b/Task/GUI-component-interaction/PowerShell/gui-component-interaction.ps1 @@ -0,0 +1,25 @@ +[xml]$XML = @" + + + +

    Clicks: 0

    + + + diff --git a/Task/Simple-windowed-application/JavaScript/simple-windowed-application-2.js b/Task/Simple-windowed-application/JavaScript/simple-windowed-application-2.js new file mode 100644 index 0000000000..29df8bcc16 --- /dev/null +++ b/Task/Simple-windowed-application/JavaScript/simple-windowed-application-2.js @@ -0,0 +1 @@ +WScript.CreateObject("Shell.Application").ShellExecute("mshta", "\"about:Simple windowed application

    There have been no clicks yet

    \""); diff --git a/Task/Simple-windowed-application/Microsoft-Small-Basic/simple-windowed-application.basic b/Task/Simple-windowed-application/Microsoft-Small-Basic/simple-windowed-application.basic new file mode 100644 index 0000000000..47f3b4c2f4 --- /dev/null +++ b/Task/Simple-windowed-application/Microsoft-Small-Basic/simple-windowed-application.basic @@ -0,0 +1,22 @@ +GraphicsWindow.Width = 180 +GraphicsWindow.Height = 80 +' Make it look like a native Windows application +GraphicsWindow.BackgroundColor = "#F0F0F0" +GraphicsWindow.BrushColor = "#000000" +GraphicsWindow.FontName = "Segoe UI" +GraphicsWindow.FontBold = 0 + +GraphicsWindow.DrawText(10, 10, "There have been no clicks yet") +Controls.AddButton("click me", 65, 40) +Controls.ButtonClicked = CountClick + +Sub CountClick + clicks = clicks + 1 + GraphicsWindow.Clear() + If clicks = 1 Then + GraphicsWindow.DrawText(10, 10, "There has been 1 click") + Else + GraphicsWindow.DrawText(10, 10, "There have been " + clicks + " clicks") + EndIf + Controls.AddButton("click me", 65, 40) +EndSub diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.ps1 b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.ps1 new file mode 100644 index 0000000000..6e9eee80f9 --- /dev/null +++ b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-1.ps1 @@ -0,0 +1,20 @@ +$Label1 = [System.Windows.Forms.Label]@{ + Text = 'There have been no clicks yet' + Size = '200, 20' } +$Button1 = [System.Windows.Forms.Button]@{ + Text = 'Click me' + Location = '0, 20' } + +$Button1.Add_Click( + { + $Script:Clicks++ + If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" } + Else { $Label1.Text = "There have been $Clicks clicks" } + } ) + +$Form1 = New-Object System.Windows.Forms.Form +$Form1.Controls.AddRange( @( $Label1, $Button1 ) ) + +$Clicks = 0 + +$Result = $Form1.ShowDialog() diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.ps1 b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.ps1 new file mode 100644 index 0000000000..75c42bc50b --- /dev/null +++ b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-2.ps1 @@ -0,0 +1,23 @@ +Add-Type -AssemblyName System.Windows.Forms + +$Label1 = New-Object System.Windows.Forms.Label +$Label1.Text = 'There have been no clicks yet' +$Label1.Size = '200, 20' + +$Button1 = New-Object System.Windows.Forms.Button +$Button1.Text = 'Click me' +$Button1.Location = '0, 20' + +$Button1.Add_Click( + { + $Script:Clicks++ + If ( $Clicks -eq 1 ) { $Label1.Text = "There has been 1 click" } + Else { $Label1.Text = "There have been $Clicks clicks" } + } ) + +$Form1 = New-Object System.Windows.Forms.Form +$Form1.Controls.AddRange( @( $Label1, $Button1 ) ) + +$Clicks = 0 + +$Result = $Form1.ShowDialog() diff --git a/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.ps1 b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.ps1 new file mode 100644 index 0000000000..3f3ed52bdb --- /dev/null +++ b/Task/Simple-windowed-application/PowerShell/simple-windowed-application-3.ps1 @@ -0,0 +1,38 @@ +[xml]$Xaml = @" + + +
    """ diff --git a/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.au3 b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.au3 new file mode 100644 index 0000000000..2702377cfb --- /dev/null +++ b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-1.au3 @@ -0,0 +1,3 @@ +Run("notepad") +WinWaitActive("Untitled - Notepad") +Send("The answer is 42") diff --git a/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.au3 b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.au3 new file mode 100644 index 0000000000..88943c1e58 --- /dev/null +++ b/Task/Simulate-input-Keyboard/AutoIt/simulate-input-keyboard-2.au3 @@ -0,0 +1,3 @@ +$name="type your name here" +$name = InputBox("Name","Your name please ?",$name) +MsgBox(0,"Name","Your name is: "&$name) diff --git a/Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.ps1 b/Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.ps1 new file mode 100644 index 0000000000..d1e3a0f5a8 --- /dev/null +++ b/Task/Simulate-input-Keyboard/PowerShell/simulate-input-keyboard.ps1 @@ -0,0 +1,6 @@ +Add-Type -AssemblyName Microsoft.VisualBasic +Add-Type -AssemblyName System.Windows.Forms +calc.exe +Start-Sleep -Milliseconds 300 +[Microsoft.VisualBasic.Interaction]::AppActivate(“Calc”) +[System.Windows.Forms.SendKeys]::SendWait(“2{ADD}2=”) diff --git a/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbs b/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbs new file mode 100644 index 0000000000..8b17d7601f --- /dev/null +++ b/Task/Simulate-input-Keyboard/VBScript/simulate-input-keyboard.vbs @@ -0,0 +1,5 @@ +Dim WshShell +Set WshShell = WScript.CreateObject("WScript.Shell") +WshShell.SendKeys "{Down}{F2}" +WScript.Sleep 1000 ' one-second delay +WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter diff --git a/Task/Singleton/Ada/singleton-1.adb b/Task/Singleton/Ada/singleton-1.adb new file mode 100644 index 0000000000..26b7570502 --- /dev/null +++ b/Task/Singleton/Ada/singleton-1.adb @@ -0,0 +1,10 @@ +package Global_Singleton is + procedure Set_Data (Value : Integer); + function Get_Data return Integer; +private + type Instance_Type is record + -- Define instance data elements + Data : Integer := 0; + end record; + Instance : Instance_Type; +end Global_Singleton; diff --git a/Task/Singleton/Ada/singleton-2.adb b/Task/Singleton/Ada/singleton-2.adb new file mode 100644 index 0000000000..346b248e61 --- /dev/null +++ b/Task/Singleton/Ada/singleton-2.adb @@ -0,0 +1,21 @@ +package body Global_Singleton is + + -------------- + -- Set_Data -- + -------------- + + procedure Set_Data (Value : Integer) is + begin + Instance.Data := Value; + end Set_Data; + + -------------- + -- Get_Data -- + -------------- + + function Get_Data return Integer is + begin + return Instance.Data; + end Get_Data; + +end Global_Singleton; diff --git a/Task/Singleton/Ada/singleton-3.adb b/Task/Singleton/Ada/singleton-3.adb new file mode 100644 index 0000000000..d4d73a121b --- /dev/null +++ b/Task/Singleton/Ada/singleton-3.adb @@ -0,0 +1,11 @@ +package Protected_Singleton is + procedure Set_Data (Value : Integer); + function Get_Data return Integer; +private + protected Instance is + procedure Set(Value : Integer); + function Get return Integer; + private + Data : Integer := 0; + end Instance_Type; +end Protected_Singleton; diff --git a/Task/Singleton/Ada/singleton-4.adb b/Task/Singleton/Ada/singleton-4.adb new file mode 100644 index 0000000000..6475ab6e72 --- /dev/null +++ b/Task/Singleton/Ada/singleton-4.adb @@ -0,0 +1,47 @@ +package body Protected_Singleton is + + -------------- + -- Set_Data -- + -------------- + + procedure Set_Data (Value : Integer) is + begin + Instance.Set(Value); + end Set_Data; + + -------------- + -- Get_Data -- + -------------- + + function Get_Data return Integer is + begin + return Instance.Get; + end Get_Data; + + -------------- + -- Instance -- + -------------- + + protected body Instance is + + --------- + -- Set -- + --------- + + procedure Set (Value : Integer) is + begin + Data := Value; + end Set; + + --------- + -- Get -- + --------- + + function Get return Integer is + begin + return Data; + end Get; + + end Instance; + +end Protected_Singleton; diff --git a/Task/Singleton/EMal/singleton.emal b/Task/Singleton/EMal/singleton.emal index ca04f8507d..f726ff7927 100644 --- a/Task/Singleton/EMal/singleton.emal +++ b/Task/Singleton/EMal/singleton.emal @@ -1,17 +1,17 @@ type Singleton model text greeting - fun speak = void by block do writeLine(me.greeting + " I'm a singleton") end + fun speak ← void by block do writeLine(me.greeting + " I'm a singleton") end end Singleton instance -fun getInstance = Singleton by block - if instance == null do instance = Singleton() end +fun getInstance ← Singleton by block + if instance æ null do instance ← Singleton() end return instance end type SomeOtherType -Singleton s1 = Singleton.getInstance() -s1.greeting = "Hello" -Singleton s2 = Singleton.getInstance() +Singleton s1 ← Singleton.getInstance() +s1.greeting ← "Hello" +Singleton s2 ← Singleton.getInstance() s2.greeting.append(", World!") -writeLine(s1 + " and " + s2 + " are the same object: " + (s1 == s2) + ", s2: " + s2.greeting) +writeLine(s1 + " and " + s2 + " are the same object: " + (s1 æ s2) + ", s2: " + s2.greeting) s1.speak() # call instance method diff --git a/Task/Singleton/Pluto/singleton-1.pluto b/Task/Singleton/Pluto/singleton-1.pluto new file mode 100644 index 0000000000..147be60993 --- /dev/null +++ b/Task/Singleton/Pluto/singleton-1.pluto @@ -0,0 +1,19 @@ +-- Singleton.pluto -- + +local instance = nil + +class singleton + static function getInstance() + if !instance then new singleton() end + return instance + end + + function __construct() + assert(!instance, "The singleton instance already exists.") + instance = self + end + + function print() + print("Hello, I'm a singleton.") + end +end diff --git a/Task/Singleton/Pluto/singleton-2.pluto b/Task/Singleton/Pluto/singleton-2.pluto new file mode 100644 index 0000000000..c5aa68ad22 --- /dev/null +++ b/Task/Singleton/Pluto/singleton-2.pluto @@ -0,0 +1,12 @@ +-- Singleton_user.pluto -- + +require "Singleton" + +local s = singleton.getInstance() +s:print() +local t = singleton.getInstance() +t:print() +print(s == t) -- true, as same object +print(instance) -- nil +local u = new singleton() -- throws an error +u:print() -- not executed diff --git a/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.adb b/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.adb new file mode 100644 index 0000000000..bb04c45935 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Ada/singly-linked-list-element-definition.adb @@ -0,0 +1,6 @@ +type Link; +type Link_Access is access Link; +type Link is record + Next : Link_Access := null; + Data : Integer; +end record; diff --git a/Task/Singly-linked-list-Element-definition/RISC-V-Assembly/singly-linked-list-element-definition.asm b/Task/Singly-linked-list-Element-definition/RISC-V-Assembly/singly-linked-list-element-definition.asm new file mode 100644 index 0000000000..029277af0a --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/RISC-V-Assembly/singly-linked-list-element-definition.asm @@ -0,0 +1,87 @@ +# riscv assembly raspberry pico2 rp2350 +# program linkedlist.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ NBELEMENTS, 100 # list size +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure linkedlist*/ + .struct 0 +llist_next: # next element + .struct llist_next + 4 +llist_value: # element value + .struct llist_value + 4 +llist_fin: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szMessNum: .asciz "Prime : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +lList1: .skip llist_fin * NBELEMENTS # list memory place + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,lList1 # list address + call initLinkedList + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* initialisation linkedlist */ +/**********************************************/ +/* a0 linked list address */ +initLinkedList: # INFO: initLinkedList + addi sp, sp, -4 + sw ra, 0(sp) + sw x0,llist_value(a0) + sw x0,llist_next(a0) + + lw ra, 0(sp) + addi sp, sp, 4 + ret + + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Singly-linked-list-Element-definition/V-(Vlang)/singly-linked-list-element-definition.v b/Task/Singly-linked-list-Element-definition/V-(Vlang)/singly-linked-list-element-definition.v new file mode 100644 index 0000000000..7f230ea728 --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/V-(Vlang)/singly-linked-list-element-definition.v @@ -0,0 +1,21 @@ +struct Node[T] { + mut: + data T + next ?&Node[T] +} + +// method override of built-in `str()` +fn (n Node[T]) str() string { + mut result := n.data.str() + mut current := n.next + for current != none { + result += " -> ${current or {continue}.data.str()}" + current = current or {continue}.next + } + return result +} + +fn main() { + n := Node{1, ?&Node{2, ?&Node{3, none}}} + println(n.str()) +} diff --git a/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.adb b/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.adb new file mode 100644 index 0000000000..2c62228df8 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Ada/singly-linked-list-element-insertion.adb @@ -0,0 +1,34 @@ +with Ada.Unchecked_Deallocation; +-- Define the link type +procedure Singly_Linked is + + type Link; + type Link_Access is access Link; + type Link is record + Data : Integer; + Next : Link_Access := null; + end record; + -- Instantiate the generic deallocator for the link type + procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access); + + -- Define the procedure + procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is + begin + if Anchor /= null and Newbie /= null then + Newbie.Next := Anchor.Next; + Anchor.Next := Newbie; + end if; + end Insert_Append; + + -- Create the link elements + A : Link_Access := new Link'(1, null); + B : Link_Access := new Link'(2, null); + C : Link_Access := new Link'(3, null); +-- Execute the program +begin + Insert_Append(A, B); + Insert_Append(A, C); + Free(A); + Free(B); + Free(C); +end Singly_Linked; diff --git a/Task/Singly-linked-list-Element-insertion/RISC-V-Assembly/singly-linked-list-element-insertion.asm b/Task/Singly-linked-list-Element-insertion/RISC-V-Assembly/singly-linked-list-element-insertion.asm new file mode 100644 index 0000000000..5ab85fe11a --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/RISC-V-Assembly/singly-linked-list-element-insertion.asm @@ -0,0 +1,165 @@ +# riscv assembly raspberry pico2 rp2350 +# program linkedlist1.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ NBELEMENTS, 100 # list size +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure linkedlist*/ + .struct 0 +llist_next: # next element + .struct llist_next + 4 +llist_value: # element value + .struct llist_value + 4 +llist_fin: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +/* datas error display */ +szMessErreur: .asciz "Error detected.\n" +/* datas message display */ +szMessResult: .asciz "Element No :" +szMessResultValue: .asciz " value : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +lList1: .skip llist_fin * NBELEMENTS # list memory place + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,lList1 # list address + call initLinkedList + + la a0,lList1 # list address + li a1,5 # value to insert + call insertElement # insertion + bgez a0,2f # error ? + la a0,szMessErreur + call writeString + j 10f +2: + la a0,lList1 # list address + li a1,11 # value to insert + call insertElement + bgez a0,3f + la a0,szMessErreur + call writeString + j 10f +3: + la s0,lList1 # list address + li s1,1 # n0 element +4: + lw s2,llist_next(s0) # load pointer + beqz s2,10f # end list ? + la a0,szMessResult + call writeString + mv a0,s1 # conversion and display N° element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szMessResultValue + call writeString + lw a0,llist_value(s0) # conversion and display value element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + addi s1,s1,1 + mv s0,s2 # new pointer + j 4b # and loop + +10: + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* initialisation linkedlist */ +/**********************************************/ +/* a0 linked list address */ +initLinkedList: # INFO: initLinkedList + addi sp, sp, -4 + sw ra, 0(sp) + sw x0,llist_value(a0) # raz value + sw x0,llist_next(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion element in linked list */ +/**********************************************/ +/* a0 linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -4 + sw ra, 0(sp) + li t0,llist_fin * NBELEMENTS + add t0,t0,a0 # compute address end list + mv t1,a0 +1: + lw t3,llist_next(t1) # load next pointer + beqz t3,2f # end list ? + mv t1,t3 # no -> loop with pointer + j 1b +2: + addi t3,t1,llist_fin # yes -> compute next free address + blt t3,t0,3f # < list end -> ok + li a0,-1 + j 100f +3: + sw t3,llist_next(t1) # store next address in current pointer + sw a1,llist_value(t1) # store element value + sw x0,llist_value(t3) # init new eleùent + sw x0,llist_next(t3) + mv a0,t1 +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.adb b/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.adb new file mode 100644 index 0000000000..ae9652df0a --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Ada/singly-linked-list-traversal.adb @@ -0,0 +1,18 @@ +with Ada.Containers.Doubly_Linked_Lists; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Traversal_Example is + package Int_List is new Ada.Containers.Doubly_Linked_Lists(Integer); + use Int_List; + procedure Print(Position : Cursor) is + begin + Put_Line(Integer'Image(Element(Position))); + end Print; + The_List : List; +begin + for I in 1..10 loop + The_List.Append(I); + end loop; + -- Traverse the list, calling Print for each value + The_List.Iterate(Print'access); +end traversal_example; diff --git a/Task/Singly-linked-list-Traversal/Crystal/singly-linked-list-traversal.cr b/Task/Singly-linked-list-Traversal/Crystal/singly-linked-list-traversal.cr new file mode 100644 index 0000000000..3b1ee68b1f --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Crystal/singly-linked-list-traversal.cr @@ -0,0 +1,23 @@ +class Node (T) + include Enumerable(T) + + property data : T + property next : Node(T)? + + def initialize (@data, @next = nil) + end + + def each + node = self + while node + yield node.data + node = node.next + end + end +end + +list = Node.new('A', Node.new('B', Node.new('C'))) + +list.each_with_index do |ch, i| + puts "#{i}. #{ch}" +end diff --git a/Task/Singly-linked-list-Traversal/RISC-V-Assembly/singly-linked-list-traversal.asm b/Task/Singly-linked-list-Traversal/RISC-V-Assembly/singly-linked-list-traversal.asm new file mode 100644 index 0000000000..902ac3fdb5 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/RISC-V-Assembly/singly-linked-list-traversal.asm @@ -0,0 +1,174 @@ +# riscv assembly raspberry pico2 rp2350 +# program linkedlist2.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" +.equ NBELEMENTS, 100 # list size +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # only for debugging + +/*******************************************/ +/* STRUCTURE */ +/*******************************************/ +/* structure linkedlist*/ + .struct 0 +llist_next: # next element + .struct llist_next + 4 +llist_value: # element value + .struct llist_value + 4 +llist_fin: +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" +/* datas error display */ +szMessErreur: .asciz "Error detected.\n" +/* datas message display */ +szMessResult: .asciz "Element No :" +szMessResultValue: .asciz " value : " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 +lList1: .skip llist_fin * NBELEMENTS # list memory place + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? yes -> loop + + la a0,szMessStart # message address + call writeString # display message + + la a0,lList1 # list address + call initLinkedList + + la a0,lList1 # list address + li a1,5000 # value to insert + call insertElement # insertion + bgez a0,2f # error ? + la a0,szMessErreur + call writeString + j 10f +2: + la a0,lList1 # list address + li a1,1234567 # value to insert + call insertElement + bgez a0,3f + la a0,szMessErreur + call writeString + j 10f +3: + la a0,lList1 # list address + li a1,88888 # value to insert + call insertElement + bgez a0,4f + la a0,szMessErreur + call writeString + j 10f +4: + + la s0,lList1 # list address + li s1,1 # n0 element +5: + lw s2,llist_next(s0) # load pointer + beqz s2,10f # end list ? + la a0,szMessResult + call writeString + mv a0,s1 # conversion and display N° element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + + la a0,szMessResultValue + call writeString + lw a0,llist_value(s0) # conversion and display value element + la a1,sConvArea + call conversion10 + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + addi s1,s1,1 + mv s0,s2 # new pointer + j 5b # and loop + +10: + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/**********************************************/ +/* initialisation linkedlist */ +/**********************************************/ +/* a0 linked list address */ +initLinkedList: # INFO: initLinkedList + addi sp, sp, -4 + sw ra, 0(sp) + sw x0,llist_value(a0) # raz value + sw x0,llist_next(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion element in linked list */ +/**********************************************/ +/* a0 linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -4 + sw ra, 0(sp) + li t0,llist_fin * NBELEMENTS + add t0,t0,a0 # compute address end list + mv t1,a0 +1: + lw t3,llist_next(t1) # load next pointer + beqz t3,2f # end list ? + mv t1,t3 # no -> loop with pointer + j 1b +2: + addi t3,t1,llist_fin # yes -> compute next free address + blt t3,t0,3f # < list end -> ok + li a0,-1 + j 100f +3: + sw t3,llist_next(t1) # store next address in current pointer + sw a1,llist_value(t1) # store element value + sw x0,llist_value(t3) # init new eleùent + sw x0,llist_next(t3) + mv a0,t1 +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Singular-value-decomposition/Mathematica/singular-value-decomposition.math b/Task/Singular-value-decomposition/Mathematica/singular-value-decomposition.math new file mode 100644 index 0000000000..15212c9730 --- /dev/null +++ b/Task/Singular-value-decomposition/Mathematica/singular-value-decomposition.math @@ -0,0 +1,15 @@ +(* Define the matrix *) +matrix = {{3, 0}, {4, 5}}; + +(* Perform singular value decomposition *) +{u, s, v} = SingularValueDecomposition[matrix]; + +(* Display results with 10 decimal places *) +Print["U matrix:"] +N[u, {Infinity, 10}] //Print + +Print["S matrix:"] +N[s, {Infinity, 10}] //Print + +Print["V matrix:"] +N[v, {Infinity, 10}] //Print diff --git a/Task/Sisyphus-sequence/JavaScript/sisyphus-sequence.js b/Task/Sisyphus-sequence/JavaScript/sisyphus-sequence.js new file mode 100644 index 0000000000..1b6e22afc5 --- /dev/null +++ b/Task/Sisyphus-sequence/JavaScript/sisyphus-sequence.js @@ -0,0 +1,144 @@ +class SegmentedPrimeIterator { + constructor(limit) { + this.squareRoot = Math.floor(Math.sqrt(limit)); + this.low = 0; + this.high = this.squareRoot; + this.index = 0; + this.primes = []; + this.smallPrimes = []; + this.smallSieve(this.squareRoot); + } + + next() { + if (this.index === this.primes.length) { + this.index = 0; + this.segmentedSieve(); + } + return this.primes[this.index++]; + } + + segmentedSieve() { + this.low += this.squareRoot; + this.high += this.squareRoot; + + const markedPrime = new Array(this.squareRoot).fill(true); + + for (let i = 0; i < this.smallPrimes.length; i++) { + let lowLimit = Math.floor(this.low / this.smallPrimes[i]) * this.smallPrimes[i]; + if (lowLimit < this.low) { + lowLimit += this.smallPrimes[i]; + } + + for (let j = lowLimit; j < this.high; j += this.smallPrimes[i]) { + markedPrime[j - this.low] = false; + } + } + + this.primes = []; + for (let i = this.low; i < this.high; i++) { + if (markedPrime[i - this.low]) { + this.primes.push(i); + } + } + } + + smallSieve(squareRoot) { + const markedPrime = new Array(squareRoot + 1).fill(true); + + for (let p = 2; p * p <= squareRoot; p++) { + if (markedPrime[p]) { + for (let i = p * p; i <= squareRoot; i += p) { + markedPrime[i] = false; + } + } + } + + for (let p = 2; p <= squareRoot; p++) { + if (markedPrime[p]) { + this.primes.push(p); + } + } + this.smallPrimes = [...this.primes]; + } +} + +class SisyphusIterator { + constructor(limit) { + this.previous = 2; + this.prime = 0; + this.primeIterator = new SegmentedPrimeIterator(limit); + } + + next() { + if ((this.previous & 1) === 0) { + this.previous >>= 1; + } else { + this.prime = this.primeIterator.next(); + this.previous += this.prime; + } + return this.previous; + } + + getPrime() { + return this.prime; + } +} + +function display(found, search, target, prefix, suffix) { + console.log(); + console.log(prefix + target + " terms:"); + const results = []; + for (let i = 1; i < found.length; i++) { + if (found[i] === search) { + results.push(i); + } + } + console.log(results.join(" ") + (suffix ? " " + suffix : "")); +} + +function main() { + const limit = 100_000_000; + const iterator = new SisyphusIterator(1_000_000_000_000); + + console.log("The first 100 members of the Sisyphus sequence are:"); + const found = new Array(250).fill(0); + let next = 0; + let count = 0; + let target = 1_000; + + while (target <= limit) { + count += 1; + next = iterator.next(); + + if (next < 250) { + found[next]++; + } + + if (count <= 100) { + process.stdout.write(next.toString().padStart(3) + (count % 10 === 0 ? "\n" : " ")); + if (count === 100) { + console.log(); + } + } else if (count === target) { + target *= 10; + console.log(`${target.toString().padStart(11)}th member is ${next.toString().padStart(11)} and highest prime needed is ${iterator.getPrime().toString().padStart(10)}`); + } + } + + display(found, 0, target, "These numbers under 250 occur the most in the first ", ""); + + const max = Math.max(...found); + display(found, max, target, + "These numbers under 250 occur the most in the first ", + "all occur " + max + " times"); + + while (next !== 36) { + count += 1; + next = iterator.next(); + } + + console.log(); + console.log(count + "th member is " + next + " and highest prime needed is " + iterator.getPrime()); +} + +main(); diff --git a/Task/Sleep/Ada/sleep.adb b/Task/Sleep/Ada/sleep.adb new file mode 100644 index 0000000000..d18964f8df --- /dev/null +++ b/Task/Sleep/Ada/sleep.adb @@ -0,0 +1,11 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Float_Text_Io; use Ada.Float_Text_Io; + +procedure Sleep is + In_Val : Float; +begin + Get(In_Val); + Put_Line("Sleeping..."); + delay Duration(In_Val); + Put_Line("Awake!"); +end Sleep; diff --git a/Task/Sleep/AutoIt/sleep.au3 b/Task/Sleep/AutoIt/sleep.au3 new file mode 100644 index 0000000000..94eda9c289 --- /dev/null +++ b/Task/Sleep/AutoIt/sleep.au3 @@ -0,0 +1,6 @@ +#AutoIt Version: 3.2.10.0 +$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0) +Dim $sleep_millisec=$sleep_me*1000 +MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec") +sleep ($sleep_millisec) +MsgBox(0,"Awake","... Awaking") diff --git a/Task/Sleep/COBOL/sleep-1.cob b/Task/Sleep/COBOL/sleep-1.cob new file mode 100644 index 0000000000..b0a4a7f4a8 --- /dev/null +++ b/Task/Sleep/COBOL/sleep-1.cob @@ -0,0 +1,15 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Sleep-In-Seconds. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Seconds-To-Sleep USAGE IS FLOAT-LONG. + + PROCEDURE DIVISION. + ACCEPT Seconds-To-Sleep + DISPLAY "Sleeping..." + CONTINUE AFTER Seconds-To-Sleep SECONDS + DISPLAY "Awake!" + GOBACK. + + END PROGRAM Sleep-In-Seconds. diff --git a/Task/Sleep/COBOL/sleep-2.cob b/Task/Sleep/COBOL/sleep-2.cob new file mode 100644 index 0000000000..a05e3ac70d --- /dev/null +++ b/Task/Sleep/COBOL/sleep-2.cob @@ -0,0 +1,18 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Sleep-In-Seconds. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Seconds-To-Sleep USAGE IS COMP-2. + *> Note: COMP-2, while supported on most implementations, is + *> non-standard. FLOAT-SHORT is the proper USAGE for Native + *> IEEE 754 Binary64 Floating-point data items. + + PROCEDURE DIVISION. + ACCEPT Seconds-To-Sleep + DISPLAY "Sleeping..." + CALL "C$SLEEP" USING BY CONTENT Seconds-To-Sleep + DISPLAY "Awake!" + GOBACK. + + END PROGRAM Sleep-In-Seconds. diff --git a/Task/Sleep/COBOL/sleep-3.cob b/Task/Sleep/COBOL/sleep-3.cob new file mode 100644 index 0000000000..2fb906f732 --- /dev/null +++ b/Task/Sleep/COBOL/sleep-3.cob @@ -0,0 +1,26 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Sleep-In-Nanoseconds. + OPTIONS. + DEFAULT ROUNDED MODE IS NEAREST-AWAY-FROM-ZERO. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Seconds-To-Sleep USAGE IS FLOAT-LONG. + 01 Nanoseconds-To-Sleep USAGE IS FLOAT-LONG. + 01 Nanoseconds-Per-Second CONSTANT AS 1000000000. + + PROCEDURE DIVISION. + ACCEPT Seconds-To-Sleep + COMPUTE Nanoseconds-To-Sleep + = Seconds-To-Sleep * Nanoseconds-Per-Second + END-COMPUTE + + DISPLAY "Sleeping..." + CALL "CBL_OC_NANOSLEEP" + USING BY CONTENT Nanoseconds-To-Sleep + END-CALL + + DISPLAY "Awake!" + GOBACK. + + END PROGRAM Sleep-In-Nanoseconds. diff --git a/Task/Sleep/Crystal/sleep.cr b/Task/Sleep/Crystal/sleep.cr new file mode 100644 index 0000000000..2e21d672cb --- /dev/null +++ b/Task/Sleep/Crystal/sleep.cr @@ -0,0 +1,5 @@ +print "Seconds to sleep: " +duration = gets.not_nil!.to_f.seconds +puts "Sleeping..." +sleep duration +puts "Awake!" diff --git a/Task/Sleep/EMal/sleep.emal b/Task/Sleep/EMal/sleep.emal index c608b053d6..bfb9cac6a1 100644 --- a/Task/Sleep/EMal/sleep.emal +++ b/Task/Sleep/EMal/sleep.emal @@ -1,9 +1,9 @@ ^|The pause command takes milliseconds, we adjust to seconds|^ -fun main = int by List args +fun main ← int by List args int seconds - if args.length == 1 do seconds = int!args[0] end - if seconds == 0 - seconds = ask(int, "Enter number of seconds to sleep: ") + if args.length æ 1 do seconds ← int!args[0] end + if seconds æ 0 + seconds ← ask(int, "Enter number of seconds to sleep: ") end writeLine("Sleeping...") pause(1000 * seconds) diff --git a/Task/Sleep/Emacs-Lisp/sleep.el b/Task/Sleep/Emacs-Lisp/sleep.el new file mode 100644 index 0000000000..0fed6fe7c1 --- /dev/null +++ b/Task/Sleep/Emacs-Lisp/sleep.el @@ -0,0 +1,4 @@ +(let ((seconds (read-number "Time in seconds: "))) + (message "Sleeping ...") + (sleep-for seconds) + (message "Awake!")) diff --git a/Task/Sleep/PowerShell/sleep.ps1 b/Task/Sleep/PowerShell/sleep.ps1 new file mode 100644 index 0000000000..15dec5125e --- /dev/null +++ b/Task/Sleep/PowerShell/sleep.ps1 @@ -0,0 +1,4 @@ +$d = [int] (Read-Host Duration in seconds) +Write-Host Sleeping ... +Start-Sleep $d +Write-Host Awake! diff --git a/Task/Sleep/Rebol/sleep.rebol b/Task/Sleep/Rebol/sleep.rebol new file mode 100644 index 0000000000..d955cd3b04 --- /dev/null +++ b/Task/Sleep/Rebol/sleep.rebol @@ -0,0 +1,9 @@ +Rebol [ + Title: "Sleep Main Thread" + URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread +] + +naptime: to-integer ask "Please enter sleep time in seconds: " +print "Sleeping..." +wait naptime +print "Awake!" diff --git a/Task/Sleep/Rye/sleep.rye b/Task/Sleep/Rye/sleep.rye new file mode 100644 index 0000000000..08f202092a --- /dev/null +++ b/Task/Sleep/Rye/sleep.rye @@ -0,0 +1,4 @@ +time: 3000 ;milliseconds +print "Asleep" +sleep time +print "Awake now!" diff --git a/Task/Sleep/VBScript/sleep.vbs b/Task/Sleep/VBScript/sleep.vbs new file mode 100644 index 0000000000..8b7fb15908 --- /dev/null +++ b/Task/Sleep/VBScript/sleep.vbs @@ -0,0 +1,4 @@ +iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org") +WScript.Echo "Sleeping..." +WScript.Sleep iSeconds*1000 'Sleep is done in Milli-Seconds +WScript.Echo "Awake!" diff --git a/Task/Sleeping-Beauty-problem/ALGOL-W/sleeping-beauty-problem.alg b/Task/Sleeping-Beauty-problem/ALGOL-W/sleeping-beauty-problem.alg new file mode 100644 index 0000000000..5a2ea9271e --- /dev/null +++ b/Task/Sleeping-Beauty-problem/ALGOL-W/sleeping-beauty-problem.alg @@ -0,0 +1,35 @@ +begin % sleeping beauty problem - translated from the Wren sample, via Agena % + + integer seed; % seed for random number generation % + + % returns the next middle-square random number in [0..1) % + real procedure random ; + begin + if seed = 0 then seed := time( -1 ) rem 10000; + seed := ( ( seed * seed ) div 100 ) rem 10000; + seed / 10000 + end random ; + + real procedure sleepingBeauty( integer value reps ) ; + begin + integer wakings, heads; + wakings := heads := 0; + for i := 1 until reps do begin + wakings := wakings + 1; + if random < 0.5 then begin + heads := 1 + heads % [0..0.5) = heads % + end else begin + wakings := 1 + wakings % [0.5..1) = tails % + end if__random_lt_500000__ + end for_i ; + write( i_w := 1, s_w := 0, "Wakings over ", reps, " repetitions = ", wakings ); + ( heads / wakings ) * 100 + end sleepingBeauty ; + + begin + real pc; + seed := 0; % initialise the random number generator % + pc := sleepingBeauty( 1000000 ); + write( s_w := 0, "Percentage probability of heads on waking = ", pc, "%" ) + end +end. diff --git a/Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.adb b/Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.adb new file mode 100644 index 0000000000..3131c73bd0 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Ada/sleeping-beauty-problem.adb @@ -0,0 +1,32 @@ +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Sleeping_Beauty is + type Coin is (Heads, Tails); + package Random_Coin is new Ada.Numerics.Discrete_Random (Coin); use Random_Coin; + package FIO is new Float_IO (Float); + Tosser : Generator; + Probability : Float; + + function Experiment (Tosses : Integer) return Float is + Awakenings, Heads_Count : Integer := 0; + begin + for Iteration in 1 .. Tosses loop + case Random (Tosser) is + when Heads => + Awakenings := Awakenings + 1; + Heads_Count := Heads_Count + 1; + when Tails => + Awakenings := Awakenings + 2; + end case; + end loop; + Put_Line ("Awakenings over" & Tosses'Image & " iterations:" & Awakenings'Image); + return Float (Heads_Count) / Float (Awakenings) * 100.0; + end Experiment; + +begin + Reset (Tosser); + Probability := Experiment (1_000_000); + Put ("Percentage probability of heads on waking:"); + FIO.Put (Probability, 3, 5, 0); +end Sleeping_Beauty; diff --git a/Task/Sleeping-Beauty-problem/Agena/sleeping-beauty-problem.agena b/Task/Sleeping-Beauty-problem/Agena/sleeping-beauty-problem.agena new file mode 100644 index 0000000000..d235047788 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/Agena/sleeping-beauty-problem.agena @@ -0,0 +1,18 @@ +scope # sleeping beauty problem - translated from the Wren sample, via Algol 68 + + local proc sleepingBeauty( reps :: number ) :: number + local wakings, heads := 0, 0; + to reps do + wakings +:= 1; + if math.random() < 0.5 then # default range is [0..1) + heads +:= 1 # [0..0.5) = heads + else + wakings +:= 1 # [0.5..1.0) = tails + fi + od; + printf( "Wakings over %d repetitions = %d\n", reps, wakings ); + return ( heads / wakings ) * 100 + end; + + printf( "Percentage probability of heads on waking = %10.6f%%\n", sleepingBeauty( 1_000_000 ) ) +epocs diff --git a/Task/Sleeping-Beauty-problem/C/sleeping-beauty-problem.c b/Task/Sleeping-Beauty-problem/C/sleeping-beauty-problem.c new file mode 100644 index 0000000000..08436446f1 --- /dev/null +++ b/Task/Sleeping-Beauty-problem/C/sleeping-beauty-problem.c @@ -0,0 +1,36 @@ +#include +#include +#include + +#define N 1000000 + +bool coin_toss() { + return rand() & 1; +} + +double run_experiment(int amount) { + int wakings = 0; + int wakings_heads = 0; + + for (int i=0; i 0 + RETURN _false + end if + next +end fn = _true + +// ------------------------------------------------------------ +// Main +// ------------------------------------------------------------ +void local fn Main + + UInt32 k + int count + fn mpz_init( gZ ) // init global big integer + k = 1 + count = 0 + CFTimeInterval t + t = fn CACurrentMediaTime + + while count < 5 + if fn IsAK( k ) + print @k; + if count < 4 then print @", "; + count ++ + end if + // only test odd k + k = k + 2 + wend + + // clean up + fn mpz_clear( gZ ) + printf @"\n\nElapsed time: %.3f secs", (fn CACurrentMediaTime-t) +end fn + +window 1, @"Smallest number k such that k+2^m is composite for all m less than k" +print @ +fn Main +handleEvents diff --git a/Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Pluto/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.pluto b/Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Pluto/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.pluto new file mode 100644 index 0000000000..7bef2fc71c --- /dev/null +++ b/Task/Smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k/Pluto/smallest-number-k-such-that-k+2^m-is-composite-for-all-m-less-than-k.pluto @@ -0,0 +1,24 @@ +require "bignum" + +mpz.init() -- use GMP + +-- Returns true if k is a sequence member, false otherwise. +local function a(k) + if k == 1 then return false end + for m = 1, k - 1 do + local n = mpz.shl(1, m) + k + if mpz.isprobableprime(n, 15) then return false end + end + return true +end + +local count = 0 +local k = 1 +while count < 5 do + if a(k) then + io.write($"{k} ") + count += 1 + end + k += 2 +end +print() diff --git a/Task/Smarandache-Wellin-primes/FutureBasic/smarandache-wellin-primes.basic b/Task/Smarandache-Wellin-primes/FutureBasic/smarandache-wellin-primes.basic new file mode 100644 index 0000000000..b2798adda6 --- /dev/null +++ b/Task/Smarandache-Wellin-primes/FutureBasic/smarandache-wellin-primes.basic @@ -0,0 +1,328 @@ +// ------------------------------------------------------------ +// Smarandache-Wellin primes +// +// Using FutureBasic 7.0.37 +// November 2025, R.W. +// ------------------------------------------------------------ + +include "gmp.incl" + +_kPrimeLimit = 12000 // sieve limit for prime values +_kMaxPrimes = 2000 // max # of primes we store +_kPrimeReps = 25 // Miller–Rabin repetitions +_kFirstSWP = 8 // all room we have before idx > limit +_kDerivedBatch = 10 // how many derived S-W per [Next] click + +// our clock +CFTimeInterval tim + +// Global mpz_t bigints reused for speed +mpz_t gSW // current Smarandache–Wellin number +mpz_t gDSW // current derived S-W candidate + +// Prime table +long gPrimes( _kMaxPrimes - 1 ) +long gPrimeCount + +// Derived S-W state +long gN // next prime index (0-based) for derived S-W loop +long gDerivedSoFar // how many derived S-W primes have been found +UInt32 gFreq( 9 ) // digit frequencies 0..9 over concatenated primes + +// ----------------------------------------------------------- +// Helper: Abbreviate big numeric CFString: head...tail +// ----------------------------------------------------------- +local fn AbbrevString( s as CFStringRef, head as int, ¬ + tail as int ) as CFStringRef + + if s == 0 then RETURN @"" + CFStringRef a, b, out + int nLen + nLen = len( s ) + if nLen <= head + tail then RETURN s + a = left( s, head ) + b = right( s, tail ) + out = @"" + out = concat( a, @"...", b ) +end fn = out + +// ----------------------------------------------------------- +// Helper: Get mpz_t result and abbreviate if > ~43 digits +// ----------------------------------------------------------- +local fn Abbrev( ts as mpz_t ) as CFStringRef + CFStringRef result + result = fn mpz_cf2( ts ) // FB wrapper mpz_t to CFString + int nLen + nLen = len( result ) + if nLen <= 43 then RETURN result + result = fn AbbrevString( result, 20, 20 ) +end fn = result + +// ------------------------------------------------------------ +// Helper: decimal digits of unsigned integer (0 -> 1 digit) +// ------------------------------------------------------------ +local fn UIntDigits( x as UInt32 ) as UInt32 + UInt32 n, tmp + if x == 0 then RETURN 1 + n = 0 + tmp = x + while tmp > 0 + n ++ + tmp = tmp / 10 + wend +end fn = n + +// ------------------------------------------------------------ +// Helper: decimal digits of mpz_t, with mpz_sizeinbase fix +// ------------------------------------------------------------ +local fn MPZDecimalDigits( x as mpz_t ) as long + long s + mpz_t pow10 + + if fn mpz_sgn( x ) == 0 then RETURN 1 + s = fn mpz_sizeinbase( x, 10 ) + // Sometimes mpz_sizeinbase gives one digit too many, so check + // (see GMP 6.3.0 manual page 45) + mpz_init( pow10 ) + fn mpz_ui_pow_ui( pow10, 10, s - 1 ) + if fn mpz_cmp( x, pow10 ) < 0 then s-- // decrement + mpz_clear( pow10 ) +end fn = s + +// ------------------------------------------------------------ +// Helper: Ordinal string ( n ) -> CFStringRef +// ------------------------------------------------------------ +local fn Ordinal( n as long ) as CFStringRef + CFStringRef s = @"" + CFSTringRef pad = @"" + CFStringRef suf = @"th" + long mod100, mod10 + mod100 = n MOD 100 + mod10 = n MOD 10 + // if not 11th, 12th, 13th + if (mod100 < 11) || (mod100 > 13) + if mod10 == 1 then suf = @"st" + if mod10 == 2 then suf = @"nd" + if mod10 == 3 then suf = @"rd" + end if + if n < 10 then pad = @" " + s = concat( pad, s, mid(str(n),1), suf ) +end fn = s + +// ------------------------------------------------------------ +// Helper: fill prime table up to _kPrimeLimit +// ------------------------------------------------------------ +local fn InitPrimes + Boolean isComposite( _kPrimeLimit ) + long i, j + long count + + for i = 0 to _kPrimeLimit + isComposite(i) = _false + next + isComposite(0) = _true + isComposite(1) = _true + count = 0 + for i = 2 to _kPrimeLimit + if isComposite(i) == _false + if count < _kMaxPrimes then gPrimes(count) = i + count ++ + j = i + i + while j <= _kPrimeLimit + isComposite(j) = _true + j = j + i + wend + end if + next + if count > _kMaxPrimes then count = _kMaxPrimes + gPrimeCount = count +end fn + +// ------------------------------------------------------------ +// Helper: append prime p (in base 10) onto S-W number sw +// sw := sw * 10^{digits(p)} + p +// ------------------------------------------------------------ +local fn AppendPrimeToSW( p as long, sw as mpz_t ) + UInt32 tmp, digits, pow10, j + tmp = p + digits = 0 + while tmp > 0 + digits ++ + tmp = tmp / 10 + wend + if digits == 0 then digits = 1 + + pow10 = 1 + for j = 1 to digits + pow10 = pow10 * 10 + next + + fn mpz_mul_ui( sw, sw, pow10 ) + fn mpz_add_ui( sw, sw, p ) +end fn + +// ------------------------------------------------------------ +// Helper: build derived S-W mpz from current digit freqs +// DSW = concat_dec(freq[k],...,freq[9]) where k is first +// index with freq[k] > 0 (trim leading 0 blocks). +// ------------------------------------------------------------ +void local fn BuildDerivedDSW( result as mpz_t ) + long d, startD + UInt32 x, digitsX, j, pow10 + + mpz_set_ui( result, 0 ) + // find first non-zero frequency + startD = 0 + while (startD < 10) && (gFreq(startD) == 0) + startD ++ + wend + if startD >= 10 then RETURN // all 0 -> DSW remains 0 + // initial block + mpz_set_ui( result, gFreq(startD) ) + // append remaining blocks + d = startD + 1 + while d < 10 + x = gFreq(d) + // number of decimal digits for x (0 -> "0") + digitsX = fn UIntDigits( x ) + pow10 = 1 + for j = 1 to digitsX + pow10 = pow10 * 10 + next + fn mpz_mul_ui( result, result, pow10 ) + fn mpz_add_ui( result, result, x ) + d ++ + wend +end fn + +// ------------------------------------------------------------ +// More_SWP +// Show the next _kDerivedBatch derived S-W primes +// ------------------------------------------------------------ +void local fn More_SWP + CFStringRef ordStr, primeStr + long found + long idx + long p + UInt32 tmp, digit + + if gPrimeCount == 0 then fn InitPrimes + if gDerivedSoFar < 1 + print @"\nThe Derived Smarandache-Wellin primes are:\n" + end if + + tim = fn CACurrentMediaTime + found = 0 + idx = gN + + while (found < _kDerivedBatch) && (idx < gPrimeCount) + p = gPrimes(idx) + // update digit frequencies from decimal digits of p + tmp = p + if tmp == 0 + gFreq(0) = gFreq(0) + 1 + else + while tmp > 0 + digit = tmp mod 10 + gFreq(digit) = gFreq(digit) + 1 + tmp = tmp / 10 + wend + end if + // build derived S-W number from current freqs + fn BuildDerivedDSW( gDSW ) + // primality test + if fn mpz_probab_prime_p( gDSW, _kPrimeReps ) > 0 + // 0 = composite, 1 = probable prime, 1 = definite prime + gDerivedSoFar = gDerivedSoFar + 1 + found ++ + ordStr = fn Ordinal( gDerivedSoFar ) + primeStr = fn mpz_cf2( gDSW ) + printf @"%4@: idx %4ld p = %@", ordStr, idx + 1, primeStr + end if + idx ++ + wend + + gN = idx + if gN > 1100 then button 2, NO // no more room + printf @"\nElapsed time: %.3f secs\n", (fn CACurrentMediaTime - tim) +end fn + +// ------------------------------------------------------------ +// Main — compute the first _kFirstSWP S-W primes +// ------------------------------------------------------------ +local fn Main + CFStringRef ordStr, swStr + long i, p + long count + long digitsSW + + // init primes and bigints once + fn InitPrimes + mpz_init( gSW ) + mpz_init( gDSW ) + mpz_set_ui( gSW, 0 ) + mpz_set_ui( gDSW, 0 ) + + // reset derived-state globals + gN = 0 + gDerivedSoFar = 0 + for i = 0 to 9 + gFreq(i) = 0 + next + + print @"\nThe first 8 known Smarandache-Wellin primes are:\n" + + tim = fn CACurrentMediaTime + count = 0 + i = 0 + + while (count < _kFirstSWP) && (i < gPrimeCount) + p = gPrimes(i) + // build next S-W number + fn AppendPrimeToSW( p, gSW ) + // probabilistic primality test + if fn mpz_probab_prime_p( gSW, _kPrimeReps ) > 0 + count ++ + digitsSW = fn MPZDecimalDigits( gSW ) + ordStr = fn Ordinal( count ) + swStr = fn Abbrev( gSW ) + printf @"%4@: idx %4ld last p = %5ld length = %4ld -> %@", ¬ + ordStr, i + 1, p, digitsSW, swStr + end if + i ++ + wend + + printf @"\nElapsed time: %.3f secs", (fn CACurrentMediaTime - tim) + print @"Click [next] for Derived Smarandache-Wellin primes." +end fn + +// ------------------------------------------------------------ +// Dialog handler +// ------------------------------------------------------------ +void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef ) + select ev + case _btnClick + select tag + case 2 + fn More_SWP + end select + + case _windowShouldClose + // clear any mpz_t we initialised + mpz_clear( gSW ) + mpz_clear( gDSW ) + end + end select +end fn + +on dialog fn DoDialog + +// ------------------------------------------------------------ +// Main +// ------------------------------------------------------------ +window 1, @"Smarandache-Wellin primes", (0,0,700,500) +button 2, YES,, @"Next", (580,20,100,20),,, 1 + +fn Main + +HandleEvents diff --git a/Task/Smarandache-Wellin-primes/Pluto/smarandache-wellin-primes.pluto b/Task/Smarandache-Wellin-primes/Pluto/smarandache-wellin-primes.pluto new file mode 100644 index 0000000000..8213249be9 --- /dev/null +++ b/Task/Smarandache-Wellin-primes/Pluto/smarandache-wellin-primes.pluto @@ -0,0 +1,41 @@ +require "bignum" +local int = require "int" +local fmt = require "fmt" + +local primes = int.primes(12000) +local sw = "" +local c = 0 +local i = 1 +local n +mpz.init() +print("The known Smarandache-Wellin primes are:") +while c < 8 do + sw ..= primes[i] + n = bigint.new(sw) + if mpz.isprobableprime(n, 15) then + c += 1 + local ns = fmt.abridge(sw, 20) + fmt.print("%s: index %4d digits %4d last prime %5d -> %s", fmt.ord(c), i, #sw, primes[i], ns) + end + i += 1 +end + +print("\nThe first 20 Derived Smarandache-Wellin primes are:") +local freqs = {} +for j = 1, 10 do freqs[j] = 0 end +c = 0 +i = 1 +while c < 20 do + local p = tostring(primes[i]) + for j = 1, #p do + local d = tonumber(p[j]) + freqs[d + 1] += 1 + end + local dsw = freqs:concat(""):lstrip("0") + n = bigint.new(dsw) + if mpz.isprobableprime(n, 15) then + c += 1 + fmt.print("%4s: index %4d prime %s", fmt.ord(c), i, n:tostring()) + end + i += 1 +end diff --git a/Task/Smarandache-Wellin-primes/Python/smarandache-wellin-primes.py b/Task/Smarandache-Wellin-primes/Python/smarandache-wellin-primes.py new file mode 100644 index 0000000000..08919b73a4 --- /dev/null +++ b/Task/Smarandache-Wellin-primes/Python/smarandache-wellin-primes.py @@ -0,0 +1,42 @@ +from itertools import islice +from typing import Iterator + +import primesieve +from gmpy2 import mpz + + +def primes() -> Iterator[int]: + it = primesieve.Iterator() + while True: + yield it.next_prime() + + +def smarandache_wellin_primes() -> Iterator[tuple[str, int, int]]: + acc: str = "" + for i, p in enumerate(primes()): + acc += str(p) + if mpz(acc).is_prime(): + yield (acc, p, i) + + +def derived_smarandache_wellin_primes() -> Iterator[tuple[str, int]]: + freq = [0] * 10 + for i, p in enumerate(primes()): + for ch in str(p): + freq[int(ch)] += 1 + + concat = "".join(str(j) for j in freq) + if mpz(concat).is_prime(): + yield (concat, i) + + +print("The known Smarandache-Wellin primes are:") +for i, (swp, p, ip) in enumerate(islice(smarandache_wellin_primes(), 8)): + trunc = f"{swp[:20]}...{swp[-20:]}" if len(swp) > 40 else swp + print( + f"{i + 1}: index {ip + 1:>4} digits {len(swp):>4} last prime {p:>5} -> {trunc} " + ) + +print("\nThe first 20 Derived Smarandache-Wellin primes are:") +for i, (dswp, ip) in enumerate(islice(derived_smarandache_wellin_primes(), 20)): + print(f"{i + 1:>2}: index {ip + 1:>4} prime {dswp}") diff --git a/Task/Smarandache-prime-digital-sequence/JavaScript/smarandache-prime-digital-sequence.js b/Task/Smarandache-prime-digital-sequence/JavaScript/smarandache-prime-digital-sequence.js new file mode 100644 index 0000000000..440c1c7846 --- /dev/null +++ b/Task/Smarandache-prime-digital-sequence/JavaScript/smarandache-prime-digital-sequence.js @@ -0,0 +1,79 @@ +function getSmarandachePrime(n) { + if (n < 10) { + switch (n) { + case 1: return 2; + case 2: return 3; + case 3: return 5; + case 4: return 7; + } + } + let s = getNextSmarandache(7); + let result = 0; + for (let count = 1; count <= n - 4; s = getNextSmarandache(s)) { + if (isPrime(s)) { + count++; + result = s; + } + } + return result; +} + +function isPrime(test) { + if (test % 2 === 0) return false; + for (let i = 3; i <= Math.sqrt(test); i += 2) { + if (test % i === 0) { + return false; + } + } + return true; +} + +function getNextSmarandache(n) { + // If 3, next is 7 + if (n % 10 === 3) { + return n + 4; + } + let retVal = n - 4; + + // Last digit 7. k = largest position from right where we have a 7. + let k = 0; + while (n % 10 === 7) { + k++; + n = Math.floor(n / 10); + } + + // Determine first digit from right where digit != 7. + const digit = n % 10; + + // Digit is 2, 3, or 5. 3-2 = 1, 5-3 = 2, 7-5 = 2, so digit = 2, coefficient = 1, otherwise 2. + const coeff = (digit === 2 ? 1 : 2); + + // Compute next value + retVal += coeff * Math.pow(10, k); + + // Subtract values for digit = 7. + while (k > 1) { + retVal -= 5 * Math.pow(10, k - 1); + k--; + } + + // Even works for 777..777 --> 2222...223 + return retVal; +} + +// Main execution +let s = getNextSmarandache(7); +console.log("First 25 Smarandache prime-digital sequence numbers:"); +process.stdout.write("2 3 5 7 "); +for (let count = 1; count <= 21; s = getNextSmarandache(s)) { + if (isPrime(s)) { + process.stdout.write(`${s} `); + count++; + } +} +console.log("\n"); + +for (let i = 2; i <= 5; i++) { + const n = Math.pow(10, i); + console.log(`${n.toLocaleString()}th Smarandache prime-digital sequence number = ${getSmarandachePrime(n)}`); +} diff --git a/Task/Smith-numbers/Ada/smith-numbers.adb b/Task/Smith-numbers/Ada/smith-numbers.adb new file mode 100644 index 0000000000..0e10848b7b --- /dev/null +++ b/Task/Smith-numbers/Ada/smith-numbers.adb @@ -0,0 +1,27 @@ +with Ada.Text_IO; + +procedure smith is + type Vector is array (natural range <>) of Positive; + empty_vector : constant Vector(1..0):= (others=>1); + + function digits_sum (n : Positive) return Positive is + (if n < 10 then n else n mod 10 + digits_sum (n / 10)); + + function prime_factors (n : Positive; d : Positive := 2) return Vector is + (if n = 1 then empty_vector elsif n mod d = 0 then prime_factors (n / d, d) & d + else prime_factors (n, d + (if d=2 then 1 else 2))); + + function vector_digits_sum (v : Vector) return Natural is + (if v'Length = 0 then 0 else digits_sum (v(v'First)) + vector_digits_sum (v(v'First+1..v'Last))); + +begin + for n in 1..10000 loop + declare + primes : Vector := prime_factors (n); + begin + if primes'Length > 1 and then vector_digits_sum (primes) = digits_sum (n) then + Ada.Text_IO.put (n'img); + end if; + end; + end loop; +end smith; diff --git a/Task/Smith-numbers/Frink/smith-numbers.frink b/Task/Smith-numbers/Frink/smith-numbers.frink new file mode 100644 index 0000000000..2f0c378749 --- /dev/null +++ b/Task/Smith-numbers/Frink/smith-numbers.frink @@ -0,0 +1,23 @@ +/** Solver for the Rosetta Code problem Smith numbers + + https://rosettacode.org/wiki/Smith_numbers +*/ +for n = 2 to 10000 + if isSmith[n] + print["$n "] + +println[] + +isSmith[n] := +{ + if isPrime[n] + return false + sn = sumDigits[n] + ss = 0 + for [b,p] = factor[n] + ss = ss + sumDigits[b] * p + + return sn == ss +} + +sumDigits[n] := sum[integerDigits[n]] diff --git a/Task/Smith-numbers/Uiua/smith-numbers-1.uiua b/Task/Smith-numbers/Uiua/smith-numbers-1.uiua index 1dc00589f4..c7ab69d6e2 100644 --- a/Task/Smith-numbers/Uiua/smith-numbers-1.uiua +++ b/Task/Smith-numbers/Uiua/smith-numbers-1.uiua @@ -1,7 +1,7 @@ -N ← 10000 -Primes ← ⇌◌⍢(⊃(▽≠0◿⊢..|⊂⊢)|>0⧻)⊙[]↘2⇡N -Candidates ← ▽¬∊:Primes.↘2⇡ # Exclude primes -SumD ← /+≡⋕°⋕ -PrimeDivisors ← ◌◌⍢(⟜(÷/×)⟜(⊙⊂:)▽:⟜(=0◿)⊙.|⋅(>1))Primes ⊙[] -Smith ← ▽⊸≡(=⊃(SumD|/+≡SumD PrimeDivisors)) +N ← 10000 +Primes ← ⇌◌⍢(⊃(▽≠0◿⊸⊸⊢|⊂⊢)|>0⧻)⊙[]↘2⇡N +Candidates ← ▽¬⊸∊Primes↘2⇡ # Exclude primes +SumD ← /+≡⋕°⋕ +PrimeDivisors ← ◌◌⍢(⟜(÷/×)⟜(⊙⊂⊃⋅∘∘)˜▽⟜(=0◿)⊙⟜∘|⋅>₁)Primes ⊙[] +Smith ← ▽⊸≡(=⊃(SumD|/+≡SumD PrimeDivisors)) ⟜⧻ Smith Candidates N diff --git a/Task/Snake/Ada/snake.adb b/Task/Snake/Ada/snake.adb new file mode 100644 index 0000000000..5654a47ca5 --- /dev/null +++ b/Task/Snake/Ada/snake.adb @@ -0,0 +1,288 @@ +-- This code is a basic implementation of snake in Ada using the command prompt +-- feel free to improve it! + +-- Snake.ads +with Ada.Containers; use Ada.Containers; +with Ada.Containers.Vectors; + +package Snake is + + -- copy from 2048 game ( + -- Keyboard management + type directions is (Up, Down, Right, Left, Quit, Restart, Invalid); + + -- Redefining this standard procedure as function to allow Get_Keystroke as an expression function + function Get_Immediate return Character; + + Arrow_Prefix : constant Character := Character'Val(224); -- works for windows + + function Get_Keystroke return directions; + -- ) + + -- The container for game data + type gameBoard is array (Natural range <>, Natural range <>) of Character; + + -- Initilize the board + procedure init; + + -- Run the game + procedure run; + + -- Displaying the board + procedure Display_Board; + -- Clear the board from content + procedure ClearBoard; + + -- coordinates data structure + type coord is tagged record + X,Y : Integer; + end record; + + -- list of coordinate (one coordinate for each body part of the snake) + package snakeBody is new Ada.Containers.Vectors (Natural, coord); + use snakeBody; + + -- update snake's part depending on the snakeDirection and checking colicion (with borders and snak's part) + function moveSnake return Boolean; + + -- generate food if it was eaten + procedure generateFood; + + -- Add snake and food to the board + procedure addDataToBoard; + + -- generate random integer between 1 and upperBound to generate random food position + function getRandomInteger(upperBound : Integer) return Integer; + +private + + width, height : Positive := 10; + board : gameBoard := (0 .. (width+1) => (0 .. (height+1) => ' ')); + snake : Vector := (1,1) & (2,1) & (3,1); + snakeDirection : directions := Right; + + food : coord := (5,5); + +end Snake; + + +-- Snake.adb + +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Discrete_Random; + +package body Snake is + + ----------------------------------------------------------------------------- + -- Redefining this standard procedure as function to allow Get_Keystroke as an expression function (copy from 2048 game) + function Get_Immediate return Character is + begin + return Answer : Character do Ada.Text_IO.Get_Immediate(Answer); + end return; + end Get_Immediate; + + ----------------------------------------------------------------------------- + -- (copy from 2048 game) + function Get_Keystroke return directions is + (case Get_Immediate is + when 'Q' | 'q' => Quit, + when 'R' | 'r' => Restart, + when 'W' | 'w' => Left, + when 'A' | 'a' => Up, + when 'S' | 's' => Down, + when 'D' | 'd' => Right, + -- Windows terminal + when Arrow_Prefix => (case Character'Pos(Get_Immediate) is + when 72 => Up, + when 75 => Left, + when 77 => Right, + when 80 => Down, + when others => Invalid), + -- Unix escape sequences + when ASCII.ESC => (case Get_Immediate is + when '[' => (case Get_Immediate is + when 'A' => Up, + when 'B' => Down, + when 'C' => Right, + when 'D' => Left, + when others => Invalid), + when others => Invalid), + when others => Invalid); + + ----------------------------------------------------------------------------- + procedure init is + begin + + for Row in 0 .. width+1 loop + for Column in 0 .. height+1 loop + + if Row = 0 or Row = width+1 then + board(Row,Column) := '#'; + -- Insert(board(Row,0), Column, '#'); + else + if Column = 0 or Column = height+1 then + board(Row,Column) := '#'; + -- Insert(board, board(Row, Column), "#"); + else + board(Row,Column) := ' '; + -- Insert(board, board(Row, Column), " "); + end if; + end if; + + end loop; + end loop; + end; + + ----------------------------------------------------------------------------- + procedure run is + + task T; + task body T is + begin + loop + snakeDirection := Get_Keystroke; + end loop; + end T; + + begin + + init; + loop + exit when snakeDirection = Quit; + + if moveSnake = False then + Put_Line("GAME OVER!!!"); + Put_Line("Your score is:" & Length(snake)'Image); + exit; + end if; + + + Display_Board; + delay 0.7; + + end loop; + end run; + + ----------------------------------------------------------------------------- + procedure Display_Board is + begin + + for Row in 0 .. width+1 loop + for Column in 0 .. height+1 loop + Put(board(Row, Column)); + end loop; + New_Line; + end loop; + + end Display_Board; + + ----------------------------------------------------------------------------- + procedure ClearBoard is + begin + + for Row in 1 .. width loop + for Column in 1 .. height loop + board(Row, Column) := ' '; + end loop; + end loop; + + end ClearBoard; + + ----------------------------------------------------------------------------- + function moveSnake return Boolean is + colision : Boolean := False; + headCoord : coord := Snake.First_Element; + addSnakePart : Boolean := False; + begin + + case snakeDirection is + when Up => headCoord.X := headCoord.X - 1; + when Down => headCoord.X := headCoord.X + 1; + when Right => headCoord.Y := headCoord.Y + 1; + when Left => headCoord.Y := headCoord.Y - 1; + when others => null; + end case; + + if headCoord.Y = height+1 then + return False; + end if; + + if headCoord.Y = 0 then + return False; + end if; + + if headCoord.X = width+1 then + return False; + end if; + + if headCoord.X = 0 then + return False; + end if; + + for index in snake.Iterate loop + if headCoord = snake(To_Index(index)) then + return False; + end if; + end loop; + + snake.Prepend(headCoord); + + if headCoord /= food then + snake.Delete_Last; + else + food := (0,0); + generateFood; + end if; + + addDataToBoard; + + return True; + end moveSnake; + + ----------------------------------------------------------------------------- + procedure generateFood is + begin + if food.X = 0 or food.Y = 0 then + food := (getRandomInteger(width), getRandomInteger(height)); + end if; + end generateFood; + + ----------------------------------------------------------------------------- + procedure addDataToBoard is + begin + ClearBoard; + + board(food.X, food.Y) := '*'; + + for index in snake.Iterate loop + board(snake(To_Index(index)).X, snake(To_Index(index)).Y) := 'o'; + end loop; + + end addDataToBoard; + + ----------------------------------------------------------------------------- + function getRandomInteger(upperBound : Integer) return Integer is + + subtype Random_Range is Integer range 1 .. upperBound; + + package R is new + Ada.Numerics.Discrete_Random (Random_Range); + use R; + + G : Generator; + begin + Reset (G); + return Random (G); + end getRandomInteger; + +end Snake; + + +-- main.adb + +with Snake; + +procedure Main is +begin + Snake.run; +end; diff --git a/Task/Snake/EasyLang/snake.easy b/Task/Snake/EasyLang/snake.easy index 79fe0072b8..5277c626d3 100644 --- a/Task/Snake/EasyLang/snake.easy +++ b/Task/Snake/EasyLang/snake.easy @@ -1,13 +1,13 @@ subr fruit - rx = (random 20 - 1) * 5 + 2.5 - ry = (random 20 - 1) * 5 + 2.5 + rx = (random 0 19) * 5 + 2.5 + ry = (random 0 19) * 5 + 2.5 . subr start fruit game = 1 sx[] = [ 52.5 0 0 0 0 ] sy[] = [ 52.5 0 0 0 0 ] - dir = random 4 + dir = random 1 4 timer 0 . gbackground 242 diff --git a/Task/Snake/Emacs-Lisp/snake.el b/Task/Snake/Emacs-Lisp/snake.el new file mode 100644 index 0000000000..127dbc0b2c --- /dev/null +++ b/Task/Snake/Emacs-Lisp/snake.el @@ -0,0 +1 @@ +M-x snake diff --git a/Task/Sockets/Ada/sockets.adb b/Task/Sockets/Ada/sockets.adb new file mode 100644 index 0000000000..0457700969 --- /dev/null +++ b/Task/Sockets/Ada/sockets.adb @@ -0,0 +1,14 @@ +with GNAT.Sockets; use GNAT.Sockets; + +procedure Socket_Send is + Client : Socket_Type; +begin + Initialize; + Create_Socket (Socket => Client); + Connect_Socket (Socket => Client, + Server => (Family => Family_Inet, + Addr => Inet_Addr ("127.0.0.1"), + Port => 256)); + String'Write (Stream (Client), "hello socket world"); + Close_Socket (Client); +end Socket_Send; diff --git a/Task/Sockets/AutoIt/sockets.au3 b/Task/Sockets/AutoIt/sockets.au3 new file mode 100644 index 0000000000..4125b1cbec --- /dev/null +++ b/Task/Sockets/AutoIt/sockets.au3 @@ -0,0 +1,7 @@ +Func _HelloWorldSocket() + TCPStartup() + $Socket = TCPConnect("127.0.0.1", 256) + TCPSend($Socket, "Hello World") + TCPCloseSocket($Socket) + TCPShutdown() +EndFunc diff --git a/Task/Sockets/C/sockets-1.c b/Task/Sockets/C/sockets-1.c new file mode 100644 index 0000000000..3358a23a45 --- /dev/null +++ b/Task/Sockets/C/sockets-1.c @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include +#include + +const char *msg = "hello socket world"; + +int main() +{ + int i, sock, len, slen; + + struct addrinfo hints, *addrs; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + if (0 == getaddrinfo("localhost", "256", &hints, &addrs)) + { + sock = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol); + if ( sock >= 0 ) + { + if ( connect(sock, addrs->ai_addr, addrs->ai_addrlen) >= 0 ) + { + const char *pm = msg; + do + { + len = strlen(pm); + slen = send(sock, pm, len, 0); + pm += slen; + } while ((0 <= slen) && (slen < len)); + } + close(sock); + } + freeaddrinfo(addrs); + } +} diff --git a/Task/Sockets/C/sockets-2.c b/Task/Sockets/C/sockets-2.c new file mode 100644 index 0000000000..809fe3ba31 --- /dev/null +++ b/Task/Sockets/C/sockets-2.c @@ -0,0 +1,26 @@ +#include +#include + +// link winsock (MSVC extension. Ignored by MinGW) +#pragma comment(lib, "ws2_32.lib") + +const char MESSAGE[] = "hello socket world"; + +int main() { + WSADATA wsa; + WSAStartup(MAKEWORD(2, 2), &wsa); + SOCKET s = socket(AF_INET, SOCK_STREAM, 0); + + struct sockaddr_in server = { + .sin_family = AF_INET, + .sin_port = htons(256), + .sin_addr.s_addr = inet_addr("127.0.0.1") + }; + + assert(connect(s, (struct sockaddr *)&server, sizeof(server)) == 0); + send(s, MESSAGE, sizeof(MESSAGE) / sizeof(char), 0); + + closesocket(s); + WSACleanup(); + return 0; +} diff --git a/Task/Sockets/Emacs-Lisp/sockets.el b/Task/Sockets/Emacs-Lisp/sockets.el new file mode 100644 index 0000000000..d48d8d2d9d --- /dev/null +++ b/Task/Sockets/Emacs-Lisp/sockets.el @@ -0,0 +1,5 @@ +(let ((proc (make-network-process :name "my sock" + :host 'local ;; or hostname string + :service 256))) + (process-send-string proc "hello socket world") + (delete-process proc)) diff --git a/Task/Sockets/F-Sharp/sockets.fs b/Task/Sockets/F-Sharp/sockets.fs new file mode 100644 index 0000000000..a8e662b289 --- /dev/null +++ b/Task/Sockets/F-Sharp/sockets.fs @@ -0,0 +1,8 @@ +open System.Text +open System.Net.Sockets + +let sock = + new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) +sock.Connect("127.0.0.1", 256) +sock.Send(Encoding.UTF8.GetBytes "hello socket world") +sock.Close diff --git a/Task/Sockets/Odin/sockets.odin b/Task/Sockets/Odin/sockets.odin new file mode 100644 index 0000000000..20d80e3ba8 --- /dev/null +++ b/Task/Sockets/Odin/sockets.odin @@ -0,0 +1,14 @@ +package main + +import "core:fmt" +import "core:net" + +MSG: string : "hello socket world" + +main :: proc() { + sock, err := net.dial_tcp("127.0.0.1:256") + if err != nil do fmt.panicf("Connection failed: %v", err) + + _, err = net.send(sock, transmute([]u8)MSG) + if err != nil do fmt.panicf("Error sending: %v", err) +} diff --git a/Task/Sockets/Pluto/sockets.pluto b/Task/Sockets/Pluto/sockets.pluto new file mode 100644 index 0000000000..c19390b0c8 --- /dev/null +++ b/Task/Sockets/Pluto/sockets.pluto @@ -0,0 +1,9 @@ +local socket = require "pluto:socket" +local host, port, transport = "localhost", 256, "udp" +local s = socket.connect(host, port, transport) +if s then + s:send("hello socket world") + s:close() +else + print($"Unable to connect to '{host}' on port: {port} using {transport}") +end diff --git a/Task/Sokoban/FreeBASIC/sokoban.basic b/Task/Sokoban/FreeBASIC/sokoban.basic new file mode 100644 index 0000000000..bce308bf16 --- /dev/null +++ b/Task/Sokoban/FreeBASIC/sokoban.basic @@ -0,0 +1,233 @@ +Const NULL As Any Ptr = 0 + +' HashTable with open addressing +Type HashTable + Dim As Integer size + Dim As String entries(Any) +End Type + +Sub HashInit(Byref ht As HashTable, sz As Integer) + ht.size = sz + Redim ht.entries(0 To sz-1) + For i As Integer = 0 To sz-1 + ht.entries(i) = "" ' empty slot marker + Next +End Sub + +Function HashString(s As String, tableSize As Integer) As Integer + Dim As Uinteger h = 5381 + For i As Integer = 0 To Len(s)-1 + h = ((h Shl 5) + h) + Asc(Mid(s,i+1,1)) ' h*33 + c + Next + Return h Mod tableSize +End Function + +Sub HashAdd(Byref ht As HashTable, s As String) + Dim As Integer idx = HashString(s, ht.size) + While ht.entries(idx) <> "" And ht.entries(idx) <> s + idx = (idx + 1) Mod ht.size + Wend + ht.entries(idx) = s +End Sub + +Function HashContains(Byref ht As HashTable, s As String) As Boolean + Dim As Integer idx = HashString(s, ht.size) + While ht.entries(idx) <> "" + If ht.entries(idx) = s Then Return True + idx = (idx + 1) Mod ht.size + Wend + Return False +End Function + +' Sokoban solver +Type State + board As String + moves As String + posic As Integer +End Type + +Type DirType + moveStr As String + pushStr As String + dPos As Integer +End Type + +Function getChar(s As String, lug As Integer) As String + If lug < 0 Or lug >= Len(s) Then Return "#" + Return Mid(s, lug + 1, 1) +End Function + +Function setChar(s As String, lug As Integer, c As String) As String + If lug < 0 Or lug >= Len(s) Then Return s + Return Left(s, lug) & c & Mid(s, lug + 2) +End Function + +Function isWall(c As String) As Boolean + Return c = "#" Or c = Chr(10) Or c = "" +End Function + +' --- Corner deadlock pruning (discard states where a box is stuck in a non-goal corner) --- +Function isDeadlock(board As String, ancho As Integer) As Boolean + For i As Integer = 0 To Len(board)-1 + Dim c As String = Mid(board, i+1, 1) + If c = "$" Then + ' Read neighbor cells around the box + Dim izda As String = getChar(board, i-1) + Dim dcha As String = getChar(board, i+1) + Dim up As String = getChar(board, i-(ancho+1)) + Dim down As String = getChar(board, i+(ancho+1)) + If (isWall(izda) Or isWall(dcha)) And (isWall(up) Or isWall(down)) Then + If getChar(board, i) <> "." Then Return True + End If + End If + Next + Return False +End Function + +Function Move(s As State Ptr, dPos As Integer) As String + Dim As Integer newPos = s->posic + dPos + If newPos < 0 Or newPos >= Len(s->board) Then Return "" + + Dim As String targetChar = getChar(s->board, newPos) + If isWall(targetChar) Then Return "" + If targetChar <> " " And targetChar <> "." Then Return "" + + Dim As String tmp = s->board + Dim As Integer lug = s->posic + Dim As String currentChar = getChar(tmp, lug) + + tmp = Iif(currentChar = "@", setChar(tmp, lug, " "), setChar(tmp, lug, ".")) + tmp = setChar(tmp, newPos, Iif(targetChar = " ", "@", "+")) + Return tmp +End Function + +Function Push(s As State Ptr, dPos As Integer) As String + Dim As Integer newPos = s->posic + dPos + Dim As Integer boxPos = newPos + dPos + If newPos < 0 Or boxPos < 0 Or boxPos >= Len(s->board) Then Return "" + + Dim As String boxChar = getChar(s->board, newPos) + Dim As String targetChar = getChar(s->board, boxPos) + + If boxChar <> "$" And boxChar <> "*" Then Return "" + If isWall(targetChar) Then Return "" + If targetChar <> " " And targetChar <> "." Then Return "" + + Dim As String tmp = s->board + Dim As Integer lug = s->posic + Dim As String currentChar = getChar(tmp, lug) + + tmp = Iif(currentChar = "@", setChar(tmp, lug, " "), setChar(tmp, lug, ".")) + tmp = setChar(tmp, newPos, Iif(boxChar = "$", "@", "+")) + tmp = setChar(tmp, boxPos, Iif(targetChar = " ", "$", "*")) + Return tmp +End Function + +Function isComplete(board As String) As Boolean + Return Instr(board, ".") = 0 And Instr(board, "$") = 0 +End Function + +Function Solve(board As String) As String + Dim As Integer boardLen = Len(board) + Dim As Integer ancho = Instr(board, Chr(10)) - 1 + If ancho <= 0 Then Return "Invalid board" + + Dim As DirType dirs(3) + dirs(0).moveStr = "u": dirs(0).pushStr = "U": dirs(0).dPos = -ancho-1 + dirs(1).moveStr = "r": dirs(1).pushStr = "R": dirs(1).dPos = 1 + dirs(2).moveStr = "d": dirs(2).pushStr = "D": dirs(2).dPos = ancho+1 + dirs(3).moveStr = "l": dirs(3).pushStr = "L": dirs(3).dPos = -1 + + Dim As HashTable visited + HashInit(visited, 200000) ' initial size (tune for fewer collisions) + + HashAdd(visited, board) + + Dim As Integer playerPos = Instr(board, "@") - 1 + If playerPos < 0 Then playerPos = Instr(board, "+") - 1 + If playerPos < 0 Then Return "No player" + + Dim As State Ptr openStates = Callocate(100000, Sizeof(State)) + Dim As Integer head = 0, tail = 0, capacity = 100000 + + openStates[tail].board = board + openStates[tail].moves = "" + openStates[tail].posic = playerPos + tail += 1 + + While head < tail + If tail > 1000000 Then + Deallocate(openStates) + Return "Too complex" + End If + + Dim As State current = openStates[head] + head += 1 + + For i As Integer = 0 To 3 + Dim As DirType currentDir = dirs(i) + Dim As Integer newPos = current.posic + currentDir.dPos + + If newPos < 0 Or newPos >= boardLen Then Continue For + Dim As String targetChar = getChar(current.board, newPos) + If isWall(targetChar) Then Continue For + + Dim As String newBoard = "" + Dim As String newSol = current.moves + + If targetChar = "$" Or targetChar = "*" Then + newBoard = Push(@current, currentDir.dPos) + If Len(newBoard) > 0 Then newSol += currentDir.pushStr + Elseif targetChar = " " Or targetChar = "." Then + newBoard = Move(@current, currentDir.dPos) + If Len(newBoard) > 0 Then newSol += currentDir.moveStr + End If + + If Len(newBoard) > 0 Andalso newBoard <> current.board Then + If isDeadlock(newBoard, ancho) Then Continue For + + If isComplete(newBoard) Then + Deallocate(openStates) + Return newSol + End If + If Not HashContains(visited, newBoard) Then + HashAdd(visited, newBoard) + If tail >= capacity Then + capacity += 50000 + Dim As State Ptr tmpPtr = Reallocate(openStates, capacity * Sizeof(State)) + If tmpPtr = NULL Then + Deallocate(openStates) + Return "Out of memory" + End If + openStates = tmpPtr + End If + openStates[tail].board = newBoard + openStates[tail].moves = newSol + Dim As Integer np = Instr(newBoard, "@") - 1 + If np < 0 Then np = Instr(newBoard, "+") - 1 + openStates[tail].posic = np + tail += 1 + End If + End If + Next + Wend + + Deallocate(openStates) + Return "No solution" +End Function + +' Main program +Dim level As String = _ +"#######" & Chr(10) & _ +"# #" & Chr(10) & _ +"# #" & Chr(10) & _ +"#. # #" & Chr(10) & _ +"#. $$ #" & Chr(10) & _ +"#.$$ #" & Chr(10) & _ +"#.# @#" & Chr(10) & _ +"#######" + +Print "level:" & Chr(10) & level +Print "Solution:" & Chr(10) & Solve(level) + +Sleep diff --git a/Task/Sokoban/Pluto/sokoban.pluto b/Task/Sokoban/Pluto/sokoban.pluto new file mode 100644 index 0000000000..0de64650e0 --- /dev/null +++ b/Task/Sokoban/Pluto/sokoban.pluto @@ -0,0 +1,108 @@ +require "map" +require "list" + +class board + function __construct(public cur, public sol, public x, public y) end +end + +class sokoban + function __construct(brd) + self.dest_board = "" + self.curr_board = "" + self.ncols = #brd[1] + self.player_x = 0 + self.player_y = 0 + for r = 1, #brd do + for c = 1, self.ncols do + local ch = brd[r][c] + self.dest_board ..= (ch != "$" and ch != "@") ? ch : " " + self.curr_board ..= (ch != ".") ? ch : " " + if ch == "@" then + self.player_x = c - 1 + self.player_y = r - 1 + end + end + end + end + + function move(x, y, dx, dy, trial_board) + local new_player_pos = (y + dy) * self.ncols + x + dx + 1 + if trial_board[new_player_pos] != " " then return "" end + local trial = trial_board:split("") + trial[y * self.ncols + x + 1] = " " + trial[new_player_pos] = "@" + return trial:concat("") + end + + function push(x, y, dx, dy, trial_board) + local new_box_pos = (y + 2 * dy) * self.ncols + x + 2 * dx + 1 + if trial_board[new_box_pos] != " " then return "" end + local trial = trial_board:split("") + trial[y * self.ncols + x + 1] = " " + trial[(y + dy) * self.ncols + x + dx + 1] = "@" + trial[new_box_pos] = "$" + return trial:concat("") + end + + function is_solved(trial_board) + for i = 1, #trial_board do + if (self.dest_board[i] == ".") != (trial_board[i] == "$") then return false end + end + return true + end + + function solve() + local dir_labels = { {"u", "U"}, {"r", "R"}, {"d", "D"}, {"l", "L"} } + local dirs = { {0, -1}, {1, 0}, {0, 1}, {-1, 0} } + local history = new set() + history:add(self.curr_board) + local open = new dlist() + open:push(new board(self.curr_board, "", self.player_x, self.player_y)) + + while !open:empty() do + local b = open:remove(1) + for i = 1, #dirs do + local trial = b.cur + local dx = dirs[i][1] + local dy = dirs[i][2] + + -- Are we standing next to a box ? + if trial[(b.y + dy) * self.ncols + b.x + dx + 1] == "$" then + -- Can we push it ? + trial = self:push(b.x, b.y, dx, dy, trial) + if trial != "" then + -- Or did we already try this one ? + if !history:contains(trial) then + local newsol = b.sol .. dir_labels[i][2] + if self:is_solved(trial) then return newsol end + open:push(new board(trial, newsol, b.x + dx, b.y + dy)) + history:add(trial) + end + end + else -- otherwise try changing position + trial = self:move(b.x, b.y, dx, dy, trial) + if trial != "" and !history:contains(trial) then + local newsol = b.sol .. dir_labels[i][1] + open:push(new board(trial, newsol, b.x + dx, b.y + dy)) + history:add(trial) + end + end + end + end + return "No solution" + end +end + +local level = { + "#######", + "# #", + "# #", + "#. # #", + "#. $$ #", + "#.$$ #", + "#.# @#", + "#######" +} +print(level:concat("\n")) +print() +print(new sokoban(level):solve()) diff --git a/Task/Sokoban/V-(Vlang)/sokoban.v b/Task/Sokoban/V-(Vlang)/sokoban.v new file mode 100644 index 0000000000..a750fbf394 --- /dev/null +++ b/Task/Sokoban/V-(Vlang)/sokoban.v @@ -0,0 +1,175 @@ +struct Board { + cur string + sol string + xir int + yir int +} + +struct Direction { + dxir int + dyir int +} + +struct Queue { + mut: + data []Board +} + +fn (mut que Queue) push(brd Board) { + que.data << brd +} + +fn (mut que Queue) pop() ?Board { + if que.data.len == 0 { return none } + item := que.data[0] + que.data = que.data[1..] + return item +} + +fn (que Queue) is_empty() bool { + return que.data.len == 0 +} + +struct Sokoban { + n_cols int + dest_board string + curr_board string + player_x int + player_y int +} + +fn new_sokoban(board []string) Sokoban { + n_cols := board[0].len + mut dest_buf := []u8{} + mut curr_buf := []u8{} + mut player_x := 0 + mut player_y := 0 + for ral in 0 .. board.len { + for cal in 0 .. n_cols { + ch := board[ral][cal] + dest_buf << if ch != `$` && ch != `@` { ch } else { ` ` } + curr_buf << if ch != `.` { ch } else { ` ` } + if ch == `@` { + player_x = cal + player_y = ral + } + } + } + + return Sokoban{ + n_cols: n_cols + dest_board: dest_buf.bytestr() + curr_board: curr_buf.bytestr() + player_x: player_x + player_y: player_y + } +} + +fn (skn Sokoban) move(xir int, yir int, dxir int, dyir int, trial_board string) string { + new_pos := (yir + dyir) * skn.n_cols + xir + dxir + if trial_board[new_pos] != ` ` { return "" } + mut trial := trial_board.bytes() + trial[yir * skn.n_cols + xir] = ` ` + trial[new_pos] = `@` + return trial.bytestr() +} + +fn (skn Sokoban) push(xir int, yir int, dxir int, dyir int, trial_board string) string { + new_box_pos := (yir + 2 * dyir) * skn.n_cols + xir + 2 * dxir + if trial_board[new_box_pos] != ` ` { return "" } + mut trial := trial_board.bytes() + trial[yir * skn.n_cols + xir] = ` ` + trial[(yir + dyir) * skn.n_cols + xir + dxir] = `@` + trial[new_box_pos] = `$` + return trial.bytestr() +} + +fn (skn Sokoban) is_solved(trial_board string) bool { + for ial in 0 .. trial_board.len { + if (skn.dest_board[ial] == `.`) != (trial_board[ial] == `$`) { return false } + } + return true +} + +fn (skn Sokoban) solve() string { + dir_labels := [`u`, `r`, `d`, `l`] + dir_labels_caps := [`U`, `R`, `D`, `L`] + dirs := [ + Direction{dxir: 0, dyir: -1}, + Direction{dxir: 1, dyir: 0}, + Direction{dxir: 0, dyir: 1}, + Direction{dxir: -1, dyir: 0}, + ] + mut trial := "" + mut open := Queue{} + mut history := map[string]bool{} + history[skn.curr_board] = true + open.push(Board{ + cur: skn.curr_board + sol: "" + xir: skn.player_x + yir: skn.player_y + }) + for !open.is_empty() { + cur_board := open.pop() or { break } + cur := cur_board.cur + sol := cur_board.sol + xir := cur_board.xir + yir := cur_board.yir + + for i in 0 .. dirs.len { + dxir := dirs[i].dxir + dyir := dirs[i].dyir + trial = cur + if trial[(yir + dyir) * skn.n_cols + xir + dxir] == `$` { + trial = skn.push(xir, yir, dxir, dyir, trial) + if trial != "" && !history[trial] { + new_sol := sol + dir_labels_caps[i].str() + if skn.is_solved(trial) { return new_sol } + open.push(Board{ + cur: trial + sol: new_sol + xir: xir + dxir + yir: yir + dyir + }) + history[trial] = true + } + } + else + { + trial = skn.move(xir, yir, dxir, dyir, trial) + if trial != "" && !history[trial] { + new_sol := sol + dir_labels[i].str() + open.push(Board{ + cur: trial + sol: new_sol + xir: xir + dxir + yir: yir + dyir + }) + history[trial] = true + } + } + } + } + return "No solution" +} + +fn main() { + level := [ + "#######", + "# #", + "# #", + "#. # #", + "#. $$ #", + "#.$$ #", + "#.# @#", + "#######", + ] + + for line in level { + println(line) + } + println("") + sokoban := new_sokoban(level) + println(sokoban.solve()) +} diff --git a/Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.adb b/Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.adb new file mode 100644 index 0000000000..926f044bb2 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/Ada/soloways-recurring-rainfall.adb @@ -0,0 +1,48 @@ +with Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; +with Ada.Strings.Unbounded; +with Ada.Integer_Text_IO; +with Ada.IO_Exceptions; + +procedure RecurringRainfall is + Current_Average : Float := 0.0; + Current_Count : Integer := 0; + Input_Integer : Integer; + + -- Recursively attempt to get a new integer + function Get_Next_Input return Integer is + Input_Integer : Integer; + Clear_String : Ada.Strings.Unbounded.Unbounded_String; + begin + Ada.Text_IO.Put("Enter rainfall int, 99999 to quit: "); + Ada.Integer_Text_IO.Get(Input_Integer); + return Input_Integer; + exception + when Ada.IO_Exceptions.Data_Error => + Ada.Text_IO.Put_Line("Invalid input"); + -- We need to call Get_Line to make sure we flush the kb buffer + -- The pragma is to ignore the fact that we are not using the result + pragma Warnings (Off, Clear_String); + Clear_String := Ada.Text_IO.Unbounded_IO.Get_Line; + -- Recursively call self -- it'll break when valid input is hit + -- We disable the infinite recursion because we're intentionally + -- doing this. It will "break" when the user inputs valid input + -- or kills the program + pragma Warnings (Off, "infinite recursion"); + return Get_Next_Input; + pragma Warnings (On, "infinite recursion"); + end Get_Next_Input; + +begin + loop + Input_Integer := Get_Next_Input; + exit when Input_Integer = 99999; + + Current_Count := Current_Count + 1; + Current_Average := Current_Average + (Float(1) / Float(Current_Count))*Float(Input_Integer) - (Float(1) / Float(Current_Count))*Current_Average; + + Ada.Text_IO.Put("New Average: "); + Ada.Text_IO.Put_Line(Float'image(Current_Average)); + + end loop; +end RecurringRainfall; diff --git a/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cob b/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cob new file mode 100644 index 0000000000..94fe0c07b8 --- /dev/null +++ b/Task/Soloways-recurring-rainfall/COBOL/soloways-recurring-rainfall.cob @@ -0,0 +1,22 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. SOLOWAY. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 AVERAGE PIC 9(9)V9(9) VALUE ZERO. + 01 AMOUNT PIC 9(9) VALUE ZERO. + 01 CURRENT PIC 9(9). + 01 OUTPUT-VAL PIC Z(8)9.9(9). + + PROCEDURE DIVISION. + READ-VALUE. + ACCEPT CURRENT. + IF CURRENT IS EQUAL TO 99999, GO TO DONE. + ADD 1 TO AMOUNT. + COMPUTE AVERAGE = + AVERAGE * (AMOUNT - 1) / AMOUNT + CURRENT / AMOUNT. + GO TO READ-VALUE. + DONE. + MOVE AVERAGE TO OUTPUT-VAL. + DISPLAY OUTPUT-VAL. + STOP RUN. diff --git a/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.adb b/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.adb new file mode 100644 index 0000000000..11e7e51328 --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/Ada/solve-a-holy-knights-tour.adb @@ -0,0 +1,36 @@ +with Knights_Tour, Ada.Text_IO, Ada.Command_Line; + +procedure Holy_Knight is + + Size: Positive := Positive'Value(Ada.Command_Line.Argument(1)); + package KT is new Knights_Tour(Size => Size); + Board: KT.Tour := (others => (others => Natural'Last)); + + Start_X, Start_Y: KT.Index:= 1; -- default start place (1,1) + S: String(KT.Index); + I: Positive := KT.Index'First; +begin + -- read the board from standard input + while not Ada.Text_IO.End_Of_File and I <= Size loop + S := Ada.Text_IO.Get_Line; + for J in KT.Index loop + if S(J) = ' ' or S(J) = '-' then + Board(I,J) := Natural'Last; + elsif S(J) = '1' then + Start_X := I; Start_Y := J; Board(I,J) := 1; + else Board(I,J) := 0; + end if; + end loop; + I := I + 1; + end loop; + + -- print the board + Ada.Text_IO.Put_Line("Start Configuration (Length:" + & Natural'Image(KT.Count_Moves(Board)) & "):"); + KT.Tour_IO(Board, Width => 1); + Ada.Text_IO.New_Line; + + -- search for the tour and print it + Ada.Text_IO.Put_Line("Tour:"); + KT.Tour_IO(KT.Warnsdorff_Get_Tour(Start_X, Start_Y, Board)); +end Holy_Knight; diff --git a/Task/Solve-a-Holy-Knights-tour/V-(Vlang)/solve-a-holy-knights-tour.v b/Task/Solve-a-Holy-Knights-tour/V-(Vlang)/solve-a-holy-knights-tour.v new file mode 100644 index 0000000000..f06c8d1d5a --- /dev/null +++ b/Task/Solve-a-Holy-Knights-tour/V-(Vlang)/solve-a-holy-knights-tour.v @@ -0,0 +1,83 @@ +const moves = [ + [-1, -2], [1, -2], [-1, 2], [1, 2], + [-2, -1], [-2, 1], [2, -1], [2, 1], +] + +const board1 = + " xxx " + + " x xx " + + " xxxxxxx" + + "xxx x x" + + "x x xxx" + + "sxxxxxx " + + " xx x " + + " xxx " + +const board2 = + ".....s.x....." + + ".....x.x....." + + "....xxxxx...." + + ".....xxx....." + + "..x..x.x..x.." + + "xxxxx...xxxxx" + + "..xx.....xx.." + + "xxxxx...xxxxx" + + "..x..x.x..x.." + + ".....xxx....." + + "....xxxxx...." + + ".....x.x....." + + ".....x.x....." + +fn solve(mut pz [][]int, sz int, sx int, sy int, idx int, cnt int) bool { + if idx > cnt { return true } + for move in moves { + x := sx + move[0] + y := sy + move[1] + if x >= 0 && x < sz && y >= 0 && y < sz && pz[x][y] == 0 { + pz[x][y] = idx + if solve(mut pz, sz, x, y, idx + 1, cnt) { return true } + pz[x][y] = 0 + } + } + return false +} + +fn find_solution(b string, sz int) { + mut pz := [][]int{len: sz, init: []int{len: sz, init: -1}} + mut x := 0 + mut y := 0 + mut idx := 0 + mut cnt := 0 + for j in 0 .. sz { + for i in 0 .. sz { + ch := b[idx] + if ch == `x` { + pz[i][j] = 0 + cnt++ + } else if ch == `s` { + pz[i][j] = 1 + cnt++ + x = i + y = j + } + idx++ + } + } + + if solve(mut pz, sz, x, y, 2, cnt) { + for j in 0 .. sz { + for i in 0 .. sz { + if pz[i][j] != -1 { print("${pz[i][j]:02d} ") } + else { print("-- ") } + } + println("") + } + } + else { println("Cannot solve this puzzle!") } +} + +fn main() { + find_solution(board1, 8) + println("") + find_solution(board2, 13) +} diff --git a/Task/Solve-a-Hopido-puzzle/Fortran/solve-a-hopido-puzzle.f b/Task/Solve-a-Hopido-puzzle/Fortran/solve-a-hopido-puzzle.f new file mode 100644 index 0000000000..02ffe3bd4b --- /dev/null +++ b/Task/Solve-a-Hopido-puzzle/Fortran/solve-a-hopido-puzzle.f @@ -0,0 +1,129 @@ +program pathfinding + implicit none + + ! Shared variables with zero-based indexing + integer, dimension(0:7, 0:1) :: neighbours + integer :: cnt + integer :: pwid + integer :: phei + integer, dimension(:, :), allocatable :: pa + integer :: t1, t2, rate + + ! Main program + character(len=42) :: pz + logical :: r + ! Initialize neighbours array + neighbours = reshape([ 2, 2, -2, 2, 2, -2, -2, -2, 3, 0, 0, 3, -3, 0, 0, -3 ], [8, 2], order=[2, 1]) + !Dim Shared As Integer neighbours(7, 1) => {{2, 2}, {-2, 2}, {2, -2}, {-2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}} + call system_clock(t1, rate) + pz = '011011011111111111111011111000111000001000' + r = solve(pz, 7, 6) + call system_clock(t2) + if (r) then + call printsolution(7, 6) + else + print *, 'No solution!' + end if + call system_clock(t2) + + print '(A,1x,i0,1x,A)', 'Time taken =', t2 - t1, 'milliseconds' + +contains + + function isvalid(a, b) result(res) + integer, intent(in) :: a, b + logical :: res + res = (a > -1 .and. a < pwid .and. b > -1 .and. b < phei) + end function isvalid + + recursive function iterate(pa, x, y, v) result(res) + integer, dimension(0:, 0:), intent(inout) :: pa + integer, intent(in) :: x, y, v + integer :: res + integer :: i, a, b, r + + if (v > cnt) then + res = 1 + return + end if + + res = 0 + do i = 0, 7 + a = x + neighbours(i, 0) + b = y + neighbours(i, 1) + if (isvalid(a, b))then + if (pa(a, b) /= 0) cycle + pa(a, b) = v + r = iterate(pa, a, b, v + 1) + if (r == 1) then + res = r + return + end if + pa(a, b) = 0 + end if + end do + end function iterate + + function solve(pz, w, h) result(res) + character(len=*), intent(in) :: pz + integer, intent(in) :: w, h + logical :: res + integer :: f, x, y + + ! Allocate and initialize pa array (zero-based indexing) + if (allocated(pa)) deallocate(pa) + allocate(pa(0:w - 1, 0:h - 1)) + pa = 0 + cnt = 0 + pwid = w + phei = h + f = 0 + + ! Initialize the grid + do y = 0, h - 1 + do x = 0, w - 1 + if (pz(f + 1:f + 1) == '1') then + pa(x, y) = 0 + cnt = cnt + 1 + else + pa(x, y) = -1 + end if + f = f + 1 + end do + end do + + ! Try to find a solution + res = .false. + do y = 0, h - 1 + do x = 0, w - 1 + if (pa(x, y) == 0) then + pa(x, y) = 1 + if (iterate(pa, x, y, 2) == 1) then + res = .true. + return + end if + pa(x, y) = 0 + end if + end do + end do + end function solve + + subroutine printsolution(w, h) + integer, intent(in) :: w, h + integer :: i, j + character(len=3) :: fmt + + do j = 0, h - 1 + do i = 0, w - 1 + if (pa(i, j) == -1) then + write(*, '(A)', advance='no') ' ' + else + write(fmt, '(I2.2)') pa(i, j) + write(*, '(A)', advance='no') adjustl(fmt) + end if + end do + write(*,*) + end do + end subroutine printsolution + +end program pathfinding diff --git a/Task/Solve-a-Numbrix-puzzle/Pluto/solve-a-numbrix-puzzle.pluto b/Task/Solve-a-Numbrix-puzzle/Pluto/solve-a-numbrix-puzzle.pluto new file mode 100644 index 0000000000..b605c8a2a8 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Pluto/solve-a-numbrix-puzzle.pluto @@ -0,0 +1,86 @@ +local fmt = require "fmt" +require "table2" + +local example1 = { + "00,00,00,00,00,00,00,00,00", + "00,00,46,45,00,55,74,00,00", + "00,38,00,00,43,00,00,78,00", + "00,35,00,00,00,00,00,71,00", + "00,00,33,00,00,00,59,00,00", + "00,17,00,00,00,00,00,67,00", + "00,18,00,00,11,00,00,64,00", + "00,00,24,21,00,01,02,00,00", + "00,00,00,00,00,00,00,00,00" +} + +local example2 = { + "00,00,00,00,00,00,00,00,00", + "00,11,12,15,18,21,62,61,00", + "00,06,00,00,00,00,00,60,00", + "00,33,00,00,00,00,00,57,00", + "00,32,00,00,00,00,00,56,00", + "00,37,00,01,00,00,00,73,00", + "00,38,00,00,00,00,00,72,00", + "00,43,44,47,48,51,76,77,00", + "00,00,00,00,00,00,00,00,00" +} + +local moves = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} } + +local board, grid, clues +local total_to_fill = 0 + +local function solve(r, c, count, next_clue) + if count > total_to_fill then return true end + local back = grid[r][c] + if back != 0 and back != count then return false end + if back == 0 and next_clue <= #clues and clues[next_clue] == count then + return false + end + if back == count then next_clue += 1 end + grid[r][c] = count + for moves as m do + if solve(r + m[2], c + m[1], count + 1, next_clue) then return true end + end + grid[r][c] = back + return false +end + +local function print_result(n) + print($"Solution for example {n}:") + for grid as row do + for row as i do + if i != -1 then fmt.write("%2d ", i) end + end + print() + end +end + +for n, ex in {example1, example2} do + board = ex + local nrows = #board + 2 + local ncols = #board[1]:split(",") + 2 + local startrow = 1 + local startcol = 1 + grid = table.create(nrows) + for i = 1, nrows do grid[i] = table.rep(ncols, -1) end + total_to_fill = (nrows - 2) * (ncols - 2) + local lst = {} + for r = 1, nrows do + if r >= 2 and r < nrows then + local row = board[r - 1]:split(",") + for c = 2, ncols - 1 do + local value = tonumber(row[c - 1]) + if value > 0 then lst:insert(value) end + if value == 1 then + startrow = r + startcol = c + end + grid[r][c] = value + end + end + end + lst:sort() + clues = lst + if solve(startrow, startcol, 1, 1) then print_result(n) end +end diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.adb b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.adb new file mode 100644 index 0000000000..3185c07cd6 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-1.adb @@ -0,0 +1,10 @@ +With +Ada.Text_IO, +Connection_Types, +Connection_Combinations; + +procedure main is + Result : Connection_Types.Partial_Board renames Connection_Combinations; +begin + Ada.Text_IO.Put_Line( Connection_Types.Image(Result) ); +end; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.adb b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.adb new file mode 100644 index 0000000000..bcc1dc83b4 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-2.adb @@ -0,0 +1,47 @@ +Pragma Ada_2012; + +Package Connection_Types with Pure is + + -- Name of the nodes. + Type Node is (A, B, C, D, E, F, G, H); + + -- Type for indicating if a node is connected. + Type Connection_List is array(Node) of Boolean + with Size => 8, Object_Size => 8, Pack; + + Function "&"( Left : Connection_List; Right : Node ) return Connection_List; + + -- The actual map of the network connections. + Network : Constant Array (Node) of Connection_List:= + ( + A => (C|D|E => True, others => False), + B => (D|E|F => True, others => False), + C => (A|D|G => True, others => False), + D => (C|A|B|E|H|G => True, others => False), + E => (D|A|B|F|H|G => True, others => False), + F => (B|E|H => True, others => False), + G => (C|D|E => True, others => False), + H => (D|E|F => True, others => False) + ); + + -- Values of the nodes. + Type Peg is range 1..8; + + -- Indicator for which values have been assigned. + Type Used_Peg is array(Peg) of Boolean + with Size => 8, Object_Size => 8, Pack; + + Function "&"( Left : Used_Peg; Right : Peg ) return Used_Peg; + + + -- Type describing the layout of the network. + Type Partial_Board is array(Node range <>) of Peg; + Subtype Board is Partial_Board(Node); + + -- Determines if the given board is a solution or partial-solution. + Function Is_Solution ( Input : Partial_Board ) return Boolean; + + -- Displays the board as text. + Function Image ( Input : Partial_Board ) Return String; + +End Connection_Types; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.adb b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.adb new file mode 100644 index 0000000000..50128f6547 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-3.adb @@ -0,0 +1,6 @@ +Pragma Ada_2012; + +with Connection_Types; +use Connection_Types; + +Function Connection_Combinations return Partial_Board; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.adb b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.adb new file mode 100644 index 0000000000..97c698b187 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-4.adb @@ -0,0 +1,73 @@ +Pragma Ada_2012; + +Package Body Connection_Types is + + New_Line : Constant String := ASCII.CR & ASCII.LF; + + --------------------- + -- Solution Test -- + --------------------- + + Function Is_Solution( Input : Partial_Board ) return Boolean is + (for all Index in Input'Range => + (for all Connection in Node'Range => + (if Network(Index)(Connection) and Connection in Input'Range + then abs (Input(Index) - Input(Connection)) > 1 + ) + ) + ); + + ------------------------ + -- Concat Operators -- + ------------------------ + + Function "&"( Left : Used_Peg; Right : Peg ) return Used_Peg is + begin + return Result : Used_Peg := Left do + Result(Right):= True; + end return; + end "&"; + + Function "&"(Left : Connection_List; Right : Node) return Connection_List is + begin + Return Result : Connection_List := Left do + Result(Right):= True; + end return; + end "&"; + + ----------------------- + -- IMAGE FUNCTIONS -- + ----------------------- + + Function Image(Input : Peg) Return Character is + ( Peg'Image(Input)(2) ); + + Function Image(Input : Peg) Return String is + ( 1 => Image(Input) ); + + Function Image(Input : Partial_Board; Item : Node) Return String is + ( 1 => (if Item not in Input'Range then '*' else Image(Input(Item)) )); + + Function Image( Input : Partial_Board ) Return String is + A : String renames Image(Input, Connection_Types.A); + B : String renames Image(Input, Connection_Types.B); + C : String renames Image(Input, Connection_Types.C); + D : String renames Image(Input, Connection_Types.D); + E : String renames Image(Input, Connection_Types.E); + F : String renames Image(Input, Connection_Types.F); + G : String renames Image(Input, Connection_Types.G); + H : String renames Image(Input, Connection_Types.H); + begin + return + " "&A&" "&B & New_Line & + " /|\ /|\" & New_Line & + " / | X | \" & New_Line & + " / |/ \| \" & New_Line & + " "&C&" - "&D&" - "&E&" - "&F & New_Line & + " \ |\ /| /" & New_Line & + " \ | X | /" & New_Line & + " \|/ \|/" & New_Line & + " "&G&" "&H & New_Line; + end Image; + +End Connection_Types; diff --git a/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.adb b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.adb new file mode 100644 index 0000000000..2454f29c06 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Ada/solve-the-no-connection-puzzle-5.adb @@ -0,0 +1,73 @@ +Function Connection_Combinations return Partial_Board is + +begin + Return Result : Board do + declare + + -- The Generate task takes two parameters + -- (1) a list of pegs already in use, and + -- (2) a partial-board + -- and, if the state given is a viable yet incomplete solution, it + -- takes a peg and adds it to the state creating a new task with + -- that peg in its used list. + -- + -- When a complete solution is found it is copied into result. + task type Generate( + Pegs : not null access Used_Peg:= new Used_Peg'(others => False); + State : not null access Partial_Board:= new Partial_Board'(Node'Last..Node'First => <>) + ) is + end Generate; + + -- An access to Generate and array thereof, for creating the + -- children tasks. + type Generator is access all Generate; + type Generators is array(Peg range <>) of Generator; + + -- Gen handles the actual creation of a new task and state. + Function Gen(P : Peg; G : not null access Generate) return Generator is + begin + return (if G.Pegs(P) then null + else new Generate( + Pegs => new Used_Peg'(G.Pegs.all & P), + State => New Partial_Board'(G.All.State.All & P) + ) + ); + end; + + task body Generate is + begin + if Is_Solution(State.All) then + -- If the state is a partial board, we make children to + -- complete the calculations. + if State'Length <= Node'Pos(Node'Last) then + declare + Subtasks : Constant Generators:= + ( + Gen(1, Generate'Access), + Gen(2, Generate'Access), + Gen(3, Generate'Access), + Gen(4, Generate'Access), + Gen(5, Generate'Access), + Gen(6, Generate'Access), + Gen(7, Generate'Access), + Gen(8, Generate'Access) + ); + begin + null; + end; + else + Result:= State.All; + end if; + else + -- The current state is not a solution, so we do not continue it. + Null; + end if; + + end Generate; + + Master : Generate; + begin + null; + end; + End return; +End Connection_Combinations; diff --git a/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chpl b/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chpl new file mode 100644 index 0000000000..2bf1bc26c7 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chpl @@ -0,0 +1,78 @@ +type hole = int; +param A : hole = 1; +param B : hole = A+1; +param C : hole = B+1; +param D : hole = C+1; +param E : hole = D+1; +param F : hole = E+1; +param G : hole = F+1; +param H : hole = G+1; +param starting : int = 0; +const holes : domain(hole) = { A,B,C,D,E,F,G,H }; +const graph : [holes] domain(hole) = [ A => { C,D,E }, + B => { D,E,F }, + C => { A,D,G }, + D => { A,B,C,E,G,H }, + E => { A,B,D,F,G,H }, + F => { B,E,H }, + G => { C,D,E }, + H => { D,E,F } + ]; + +proc check( configuration : [] int, idx : hole ) : bool { + var good = true; + for adj in graph[idx] { + if adj >= idx then continue; + if abs( configuration[idx] - configuration[adj] ) <= 1 { + good = false; + break; + } + } + + return good; +} + +proc solve( configuration : [] int, pegs : domain(int), idx : hole = A ) : bool { + for value in pegs { + configuration[idx] = value; + if check( configuration, idx ) { + if idx < holes.size { + var prePegs = pegs; + if solve( configuration, prePegs - value, idx + 1 ){ + return true; + } + } else { + return true; + } + } + } + configuration[idx] = starting; + return false; +} + +proc printBoard( configuration : [] int ){ +return +"\n " + configuration[A] + " " + configuration[B]+ "\n" + +" /|\\ /|\\ \n"+ +" / | X | \\ \n"+ +" / |/ \\| \\ \n"+ +" " + configuration[C] +" - " + configuration[D] + " - " + configuration[E] + " - " + configuration[F] + " \n"+ +" \\ |\\ /| / \n"+ +" \\ | X | / \n"+ +" \\|/ \\|/ \n"+ +" " + configuration[G] + " " + configuration[H]+ "\n"; + +} + + + +proc main(){ + var configuration : [holes] int; + for idx in holes do configuration[idx] = starting; + + var pegs : domain(int) = {1,2,3,4,5,6,7,8}; + solve( configuration, pegs ); + + writeln( printBoard( configuration ) ); + +} diff --git a/Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.adb b/Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.adb new file mode 100644 index 0000000000..f6d1b0bd04 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Ada/sort-a-list-of-object-identifiers.adb @@ -0,0 +1,51 @@ +with Ada.Containers.Generic_Array_Sort; +with Ada.Strings.Fixed; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; +with Ada.Unchecked_Deallocation; + +procedure Sort_List_Identifiers is + type Natural_Array is array (Positive range <>) of Natural; + type Unbounded_String_Array is array(Positive range <>) of Unbounded_String; + + function To_Natural_Array(input : in String) return Natural_Array + is + target : Natural_Array(1 .. Ada.Strings.Fixed.Count(input, ".") + 1); + from : Natural := input'First; + to : Natural := Ada.Strings.Fixed.Index(input, "."); + index : Positive := target'First; + begin + while to /= 0 loop + target(index) := Natural'Value(input(from .. to - 1)); + from := to + 1; + index := index + 1; + to := Ada.Strings.Fixed.Index(input, ".", from); + end loop; + target(index) := Natural'Value(input(from .. input'Last)); + return target; + end To_Natural_Array; + + function Lesser(Left, Right : in Unbounded_String) return Boolean is + begin + return To_Natural_Array(To_String(Left)) < To_Natural_Array(To_String(Right)); + end Lesser; + + procedure Sort is new Ada.Containers.Generic_Array_Sort + (Index_Type => Positive, + Element_Type => Unbounded_String, + Array_Type => Unbounded_String_Array, + "<" => Lesser); + + table : Unbounded_String_Array := + (To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.10"), + To_Unbounded_String("1.3.6.1.4.1.11.2.17.5.2.0.79"), + To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.4"), + To_Unbounded_String("1.3.6.1.4.1.11150.3.4.0.1"), + To_Unbounded_String("1.3.6.1.4.1.11.2.17.19.3.4.0.1"), + To_Unbounded_String("1.3.6.1.4.1.11150.3.4.0")); +begin + Sort(table); + for element of table loop + Ada.Text_IO.Put_Line(To_String(element)); + end loop; +end Sort_List_Identifiers; diff --git a/Task/Sort-a-list-of-object-identifiers/Crystal/sort-a-list-of-object-identifiers.cr b/Task/Sort-a-list-of-object-identifiers/Crystal/sort-a-list-of-object-identifiers.cr new file mode 100644 index 0000000000..568d3e6ad9 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Crystal/sort-a-list-of-object-identifiers.cr @@ -0,0 +1,6 @@ +pp %w(1.3.6.1.4.1.11.2.17.19.3.4.0.10 + 1.3.6.1.4.1.11.2.17.5.2.0.79 + 1.3.6.1.4.1.11.2.17.19.3.4.0.4 + 1.3.6.1.4.1.11150.3.4.0.1 + 1.3.6.1.4.1.11.2.17.19.3.4.0.1 + 1.3.6.1.4.1.11150.3.4.0).sort_by {|oid| oid.split('.').map &.to_i } diff --git a/Task/Sort-a-list-of-object-identifiers/F-Sharp/sort-a-list-of-object-identifiers.fs b/Task/Sort-a-list-of-object-identifiers/F-Sharp/sort-a-list-of-object-identifiers.fs new file mode 100644 index 0000000000..00b5afa088 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/F-Sharp/sort-a-list-of-object-identifiers.fs @@ -0,0 +1,8 @@ +//Sort a list of object identifiers. Nigel Galloway: March 9th., 2026 +let inD=["1.3.6.1.4.1.11.2.17.19.3.4.0.10"; + "1.3.6.1.4.1.11.2.17.5.2.0.79"; + "1.3.6.1.4.1.11.2.17.19.3.4.0.4"; + "1.3.6.1.4.1.11150.3.4.0.1"; + "1.3.6.1.4.1.11.2.17.19.3.4.0.1"; + "1.3.6.1.4.1.11150.3.4.0"] +inD|>List.sortBy(fun n->n.Split('.')|>Array.map(int)|>List.ofArray)|>List.iter(printfn "%s") diff --git a/Task/Sort-a-list-of-object-identifiers/Pluto/sort-a-list-of-object-identifiers.pluto b/Task/Sort-a-list-of-object-identifiers/Pluto/sort-a-list-of-object-identifiers.pluto new file mode 100644 index 0000000000..69cb7f68a4 --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/Pluto/sort-a-list-of-object-identifiers.pluto @@ -0,0 +1,13 @@ +local oids = { + "1.3.6.1.4.1.11.2.17.19.3.4.0.10", + "1.3.6.1.4.1.11.2.17.5.2.0.79", + "1.3.6.1.4.1.11.2.17.19.3.4.0.4", + "1.3.6.1.4.1.11150.3.4.0.1", + "1.3.6.1.4.1.11.2.17.19.3.4.0.1", + "1.3.6.1.4.1.11150.3.4.0" +} + +oids = oids:map(|oid| -> oid:split("."):map(|e| -> string.format("%5s", e)):concat(".")) +oids:sort() +oids:map(|e| -> e:replace(" ", "")) +print(oids:concat("\n")) diff --git a/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx b/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx index 06164a4a33..fed2bff0d8 100644 --- a/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx +++ b/Task/Sort-a-list-of-object-identifiers/REXX/sort-a-list-of-object-identifiers.rexx @@ -1,4 +1,4 @@ --- 20 Jan 2026 +-- 4 Mar 2026 include Setting say 'SORT A LIST OF OBJECT IDENTIFIERS' @@ -7,7 +7,7 @@ say call Prepare call Show 'BEFORE' -- Sort key while syncing data (string compare) -call Stemsort 'stem.key.','stem.data.' +call SortSt 'stem.key.','stem.data.' call Show 'AFTER' exit @@ -54,5 +54,5 @@ end say return --- Stemsort +-- SortSt include Math diff --git a/Task/Sort-a-list-of-object-identifiers/V-(Vlang)/sort-a-list-of-object-identifiers.v b/Task/Sort-a-list-of-object-identifiers/V-(Vlang)/sort-a-list-of-object-identifiers.v new file mode 100644 index 0000000000..43125c825d --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/V-(Vlang)/sort-a-list-of-object-identifiers.v @@ -0,0 +1,37 @@ +struct Oid { + id string +} + +fn (a Oid) str() string { + return a.id +} + +fn (a Oid) compare_to(b Oid) int { + splits1 := a.id.split(".") + splits2 := b.id.split(".") + min_size := if splits1.len < splits2.len { splits1.len } else { splits2.len } + for i in 0 .. min_size { + val1 := splits1[i].int() + val2 := splits2[i].int() + if val1 < val2 { return -1 } + else if val1 > val2 { return 1 } + } + // compare by length if all parts are equal + return if splits1.len < splits2.len { -1 } else if splits1.len > splits2.len { 1 } else { 0 } +} + +fn main() { + mut oids := [ + Oid{"1.3.6.1.4.1.11.2.17.19.3.4.0.10"}, + Oid{"1.3.6.1.4.1.11.2.17.5.2.0.79"}, + Oid{"1.3.6.1.4.1.11.2.17.19.3.4.0.4"}, + Oid{"1.3.6.1.4.1.11150.3.4.0.1"}, + Oid{"1.3.6.1.4.1.11.2.17.19.3.4.0.1"}, + Oid{"1.3.6.1.4.1.11150.3.4.0"}, + ] + // sorted using builtin comparator for arrays + oids.sort_with_compare(fn (a &Oid, b &Oid) int { + return a.compare_to(*b) + }) + for oid in oids { println(oid.str()) } +} diff --git a/Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vbs b/Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vbs new file mode 100644 index 0000000000..21948dec3b --- /dev/null +++ b/Task/Sort-a-list-of-object-identifiers/VBScript/sort-a-list-of-object-identifiers.vbs @@ -0,0 +1,41 @@ +' Sort a list of object identifiers - VBScript +function myCompare(x,y) + dim i,b + sx=split(x,".") + sy=split(y,".") + b=false + for i=0 to ubound(sx) + if i > ubound(sy) then b=true: exit for + select case sgn(int(sx(i))-int(sy(i))) + case 1: b=true: exit for + case -1: b=false: exit for + end select + next + myCompare=b +end function + +function bubbleSort(t) + dim i,n + n=ubound(t) + do + changed=false + n= n-1 + for i=0 to n + if myCompare(t(i),t(i+1)) then + tmp=t(i): t(i)=t(i+1): t(i+1)=tmp + changed=true + end if + next + loop until not changed + bubbleSort=t +end function + +a=array( _ + "1.3.6.1.4.1.11.2.17.19.3.4.0.10", _ + "1.3.6.1.4.1.11.2.17.5.2.0.79", _ + "1.3.6.1.4.1.11.2.17.19.3.4.0.4", _ + "1.3.6.1.4.1.11150.3.4.0.1", _ + "1.3.6.1.4.1.11.2.17.19.3.4.0.1", _ + "1.3.6.1.4.1.11150.3.4.0") +bubbleSort a +wscript.echo join(a,vbCrlf) diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.adb b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.adb new file mode 100644 index 0000000000..d6cfc6e0b8 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-1.adb @@ -0,0 +1,41 @@ +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; + +with Ada.Containers.Generic_Array_Sort; + +procedure Demo_Array_Sort is + + function "+" (S : String) return Unbounded_String renames To_Unbounded_String; + + type A_Composite is + record + Name : Unbounded_String; + Value : Unbounded_String; + end record; + + function "<" (L, R : A_Composite) return Boolean is + begin + return L.Name < R.Name; + end "<"; + + procedure Put_Line (C : A_Composite) is + begin + Put_Line (To_String (C.Name) & " " & To_String (C.Value)); + end Put_Line; + + type An_Array is array (Natural range <>) of A_Composite; + + procedure Sort is new Ada.Containers.Generic_Array_Sort (Natural, A_Composite, An_Array); + + Data : An_Array := (1 => (Name => +"Joe", Value => +"5531"), + 2 => (Name => +"Adam", Value => +"2341"), + 3 => (Name => +"Bernie", Value => +"122"), + 4 => (Name => +"Walter", Value => +"1234"), + 5 => (Name => +"David", Value => +"19")); + +begin + Sort (Data); + for I in Data'Range loop + Put_Line (Data (I)); + end loop; +end Demo_Array_Sort; diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.adb b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.adb new file mode 100644 index 0000000000..a00776cd45 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-2.adb @@ -0,0 +1,42 @@ +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; + +with Ada.Containers.Ordered_Sets; + +procedure Sort_Composites is + + function "+" (S : String) return Unbounded_String renames To_Unbounded_String; + + type A_Composite is + record + Name : Unbounded_String; + Value : Unbounded_String; + end record; + + function "<" (L, R : A_Composite) return Boolean is + begin + return L.Name < R.Name; + end "<"; + + procedure Put_Line (C : A_Composite) is + begin + Put_Line (To_String (C.Name) & " " & To_String (C.Value)); + end Put_Line; + + package Composite_Sets is new Ada.Containers.Ordered_Sets (A_Composite); + + procedure Put_Line (C : Composite_Sets.Cursor) is + begin + Put_Line (Composite_Sets.Element (C)); + end Put_Line; + + Data : Composite_Sets.Set; + +begin + Data.Insert (New_Item => (Name => +"Joe", Value => +"5531")); + Data.Insert (New_Item => (Name => +"Adam", Value => +"2341")); + Data.Insert (New_Item => (Name => +"Bernie", Value => +"122")); + Data.Insert (New_Item => (Name => +"Walter", Value => +"1234")); + Data.Insert (New_Item => (Name => +"David", Value => +"19")); + Data.Iterate (Put_Line'Access); +end Sort_Composites; diff --git a/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.adb b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.adb new file mode 100644 index 0000000000..52e1a81aac --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Ada/sort-an-array-of-composite-structures-3.adb @@ -0,0 +1,54 @@ +with Ada.Text_Io; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; + +procedure Sort_Composite is + type Composite_Record is record + Name : Unbounded_String; + Value : Unbounded_String; + end record; + + type Pairs_Array is array(Positive range <>) of Composite_Record; + + procedure Swap(Left, Right : in out Composite_Record) is + Temp : Composite_Record := Left; + begin + Left := Right; + Right := Temp; + end Swap; + + -- Sort_Names uses a bubble sort + + procedure Sort_Name(Pairs : in out Pairs_Array) is + Swap_Performed : Boolean := True; + begin + while Swap_Performed loop + Swap_Performed := False; + for I in Pairs'First..(Pairs'Last - 1) loop + if Pairs(I).Name > Pairs(I + 1).Name then + Swap (Pairs(I), Pairs(I + 1)); + Swap_Performed := True; + end if; + end loop; + end loop; + end Sort_Name; + + procedure Print(Item : Pairs_Array) is + begin + for I in Item'range loop + Ada.Text_Io.Put_Line(To_String(Item(I).Name) & ", " & + to_String(Item(I).Value)); + end loop; + end Print; + type Names is (Fred, Barney, Wilma, Betty, Pebbles); + type Values is (Home, Work, Cook, Eat, Bowl); + My_Pairs : Pairs_Array(1..5); +begin + for I in My_Pairs'range loop + My_Pairs(I).Name := To_Unbounded_String(Names'Image(Names'Val(Integer(I - 1)))); + My_Pairs(I).Value := To_Unbounded_String(Values'Image(Values'Val(Integer(I - 1)))); + end loop; + Print(My_Pairs); + Ada.Text_Io.Put_Line("========================="); + Sort_Name(My_Pairs); + Print(My_Pairs); +end Sort_Composite; diff --git a/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.eu b/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.eu new file mode 100644 index 0000000000..c8fa245a6f --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Euphoria/sort-an-array-of-composite-structures.eu @@ -0,0 +1,15 @@ +include sort.e +include misc.e + +constant NAME = 1 +function compare_names(sequence a, sequence b) + return compare(a[NAME],b[NAME]) +end function + +sequence s +s = { { "grass", "green" }, + { "snow", "white" }, + { "sky", "blue" }, + { "cherry", "red" } } + +pretty_print(1,custom_sort(routine_id("compare_names"),s),{2}) diff --git a/Task/Sort-an-array-of-composite-structures/Pluto/sort-an-array-of-composite-structures.pluto b/Task/Sort-an-array-of-composite-structures/Pluto/sort-an-array-of-composite-structures.pluto new file mode 100644 index 0000000000..8687483361 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Pluto/sort-an-array-of-composite-structures.pluto @@ -0,0 +1,20 @@ +class pair + function __construct(public name, public value) end + + function __lt(other) return self.name < other.name end + + function __tostring() return $"\{{self.name}, {self.value}}" end +end + +local pairs = { + new pair("grass", "green"), + new pair("snow", "white"), + new pair("sky", "blue"), + new pair("cherry", "red") +} + +print("Before sorting:") +print(" " .. pairs:mapped(|p| -> tostring(p)):concat("\n ")) +pairs:sort() +print("\nAfter sorting:") +print(" " .. pairs:mapped(|p| -> tostring(p)):concat("\n ")) diff --git a/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.ps1 b/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.ps1 new file mode 100644 index 0000000000..267f005feb --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.ps1 @@ -0,0 +1,9 @@ +$list = @{ +"def" = "one" +"abc" = "two" +"jkl" = "three" +"abcdef" = "four" +"ghi" = "five" +"ghijkl" = "six" + } + $list.GetEnumerator() | sort {-($PSItem.Name).length}, Name diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx index a3741ce705..4fc85d9f84 100644 --- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx +++ b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures-2.rexx @@ -1,14 +1,14 @@ --- 19 Jan 2026 +-- 4 Mar 2026 include Setting say 'SORT COMPOSITE ARRAY' say version say -call Stemread 'States.txt','states.state. states.city. states.pop.' +call ReadSt 'states.state. states.city. states.pop.','States.txt' call Show 'Not ordered','A' -call Stemsort 'states.state. states.city.','states.pop.' +call SortSt 'states.state. states.city.','states.pop.' call Show 'By state and city','A' -call Stemsort 'states.pop.','states.state. states.city.' +call SortSt 'states.pop.','states.state. states.city.' call Show 'By pop (desc)','D' exit @@ -29,4 +29,5 @@ end say return +-- ReadSt; SortSt include Math diff --git a/Task/Sort-an-integer-array/Ada/sort-an-integer-array.adb b/Task/Sort-an-integer-array/Ada/sort-an-integer-array.adb new file mode 100644 index 0000000000..62d31a1df1 --- /dev/null +++ b/Task/Sort-an-integer-array/Ada/sort-an-integer-array.adb @@ -0,0 +1,43 @@ +with Gnat.Heap_Sort_G; + +procedure Integer_Sort is + -- Heap sort package requires data to be in index values starting at + -- 1 while index value 0 is used as temporary storage + type Int_Array is array(Natural range <>) of Integer; + Values : Int_Array := (0,1,8,2,7,3,6,4,5); + + -- define move and less than subprograms for use by the heap sort package + procedure Move_Int(From : Natural; To : Natural) is + begin + Values(To) := Values(From); + end Move_Int; + + function Lt_Int(Left, Right : Natural) return Boolean is + begin + return Values(Left) < Values (Right); + end Lt_Int; + + -- Instantiate the generic heap sort package + package Heap_Sort is new Gnat.Heap_Sort_G(Move_Int, Lt_Int); + +begin + Heap_Sort.Sort(8); +end Integer_Sort; + +requires an Ada05 compiler, e.g GNAT GPL 2007 +with Ada.Containers.Generic_Array_Sort; + +procedure Integer_Sort is + -- + type Int_Array is array(Natural range <>) of Integer; + Values : Int_Array := (0,1,8,2,7,3,6,4,5); + + -- Instantiate the generic sort package from the standard Ada library + procedure Sort is new Ada.Containers.Generic_Array_Sort + (Index_Type => Natural, + Element_Type => Integer, + Array_Type => Int_Array); + +begin + Sort(Values); +end Integer_Sort; diff --git a/Task/Sort-an-integer-array/Batch-File/sort-an-integer-array.bat b/Task/Sort-an-integer-array/Batch-File/sort-an-integer-array.bat new file mode 100644 index 0000000000..488952199c --- /dev/null +++ b/Task/Sort-an-integer-array/Batch-File/sort-an-integer-array.bat @@ -0,0 +1,20 @@ +@if defined doSort goto sort +@echo off +setlocal enabledelayedexpansion +(set lf=^ + +) +set doSort=1 +set nums=!lf!765!lf!1232!lf!457615!lf!29681!lf!20932 +echo Before: +set nums | more +1 +echo After: +for /f %%i in ('cmd /q /v:on /e:on /d /c "%~f0" ^| sort') do echo/%%i +goto:eof +:sort +for /f %%i in ("!nums!") do ( + REM 12 leading spaces: + set "Z= %%i" + REM take last 12 digits: + echo !Z:~-12! +) diff --git a/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cob b/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cob new file mode 100644 index 0000000000..412b188b58 --- /dev/null +++ b/Task/Sort-an-integer-array/COBOL/sort-an-integer-array.cob @@ -0,0 +1,22 @@ + PROGRAM-ID. sort-ints. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 array-area VALUE "54321". + 03 array PIC 9 OCCURS 5 TIMES. + 01 i PIC 9. + + PROCEDURE DIVISION. + main-line. + PERFORM display-array + SORT array ASCENDING array + PERFORM display-array + + GOBACK + . + display-array. + PERFORM VARYING i FROM 1 BY 1 UNTIL 5 < i + DISPLAY array (i) " " NO ADVANCING + END-PERFORM + DISPLAY SPACE + . diff --git a/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.eu b/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.eu new file mode 100644 index 0000000000..0ca4d6f97b --- /dev/null +++ b/Task/Sort-an-integer-array/Euphoria/sort-an-integer-array.eu @@ -0,0 +1,2 @@ +include sort.e +print(1,sort({20, 7, 65, 10, 3, 0, 8, -60})) diff --git a/Task/Sort-an-integer-array/GW-BASIC/sort-an-integer-array.basic b/Task/Sort-an-integer-array/GW-BASIC/sort-an-integer-array.basic new file mode 100644 index 0000000000..1a3b933f9f --- /dev/null +++ b/Task/Sort-an-integer-array/GW-BASIC/sort-an-integer-array.basic @@ -0,0 +1,31 @@ +20 DEFINT A-Z +30 ARRAYSIZE = 10 +40 DIM NUMBERS(ARRAYSIZE) +50 PRINT "Unsorted:"; +60 FOR I = 1 TO ARRAYSIZE +70 NUMBERS(I) = INT(RND * 100) + 1 +80 PRINT NUMBERS(I); +90 NEXT I +100 PRINT +110 REM ascending sort using Shell sort +120 GAP = INT(ARRAYSIZE / 2) +130 IF GAP = 0 THEN 270 +140 FOR I = GAP + 1 TO ARRAYSIZE +150 J = I - GAP +160 WHILE J > 0 +170 K = J + GAP +180 IF NUMBERS(J) <= NUMBERS(K) THEN J = 0: GOTO 220 +190 TEMP = NUMBERS(J) +200 NUMBERS(J) = NUMBERS(K) +210 NUMBERS(K) = TEMP +220 J = J - GAP +230 WEND +240 NEXT I +250 GAP = INT(GAP / 2) +260 GOTO 130 +270 PRINT "Sorted :"; +280 FOR I = 1 TO ARRAYSIZE +290 PRINT NUMBERS(I); +300 NEXT +310 PRINT +320 END diff --git a/Task/Sort-an-integer-array/Gleam/sort-an-integer-array.gleam b/Task/Sort-an-integer-array/Gleam/sort-an-integer-array.gleam new file mode 100644 index 0000000000..f468a730b3 --- /dev/null +++ b/Task/Sort-an-integer-array/Gleam/sort-an-integer-array.gleam @@ -0,0 +1,12 @@ +import gleam/int +import gleam/io +import gleam/list +import gleam/string + +pub fn main() { + [2, 1, 5, 3, 4] + |> list.sort(int.compare) + |> list.map(int.to_string) + |> string.join(" ") + |> io.println +} diff --git a/Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.ps1 b/Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.ps1 new file mode 100644 index 0000000000..b96b0f309c --- /dev/null +++ b/Task/Sort-an-integer-array/PowerShell/sort-an-integer-array.ps1 @@ -0,0 +1 @@ +34,12,23,56,1,129,4,2,73 | Sort-Object diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array.rexx new file mode 100644 index 0000000000..be09153bfd --- /dev/null +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array.rexx @@ -0,0 +1,18 @@ +-- 31 Mar 2026 +include Setting + +say 'SORT AN INTEGER ARRAY' +say version +say +-- Generate a demo stem, 100 items, random whole numbers +call MakeSt 'stem.','Z',100 +-- Show original, 5 wide per item +call ShowSt 'stem.','random whole numbers',,5 +-- Sort with (standard) numeric comparator (quicksort) +call SortSt 'stem.' +-- Show sorted +call ShowSt 'stem.','sorted!',,5 +exit + +-- MakeSt; ShowSt; SortSt +include Math diff --git a/Task/Sort-an-integer-array/Rebol/sort-an-integer-array.rebol b/Task/Sort-an-integer-array/Rebol/sort-an-integer-array.rebol new file mode 100644 index 0000000000..7fe4f3be3c --- /dev/null +++ b/Task/Sort-an-integer-array/Rebol/sort-an-integer-array.rebol @@ -0,0 +1 @@ +sort [2 4 3 1 2] diff --git a/Task/Sort-an-integer-array/Rye/sort-an-integer-array.rye b/Task/Sort-an-integer-array/Rye/sort-an-integer-array.rye new file mode 100644 index 0000000000..b24addc6d1 --- /dev/null +++ b/Task/Sort-an-integer-array/Rye/sort-an-integer-array.rye @@ -0,0 +1 @@ +print sort nums: { 2 7 3 10 1 50 } diff --git a/Task/Sort-an-integer-array/S-BASIC/sort-an-integer-array.basic b/Task/Sort-an-integer-array/S-BASIC/sort-an-integer-array.basic new file mode 100644 index 0000000000..1d452efe8c --- /dev/null +++ b/Task/Sort-an-integer-array/S-BASIC/sort-an-integer-array.basic @@ -0,0 +1,46 @@ +$constant ARRAY_SIZE = 10 +var i, j, k, gap, temp = integer +dim integer numbers(ARRAY_SIZE) + +comment + populate array with random integers in + range 1..100 +end +print "Unsorted:"; +for i=1 to ARRAY_SIZE + numbers(i) = int(rnd(1) * 100)+1) + print numbers(i); +next i +print + +rem put in ascending order using Shell sort +gap = ARRAY_SIZE / 2 +while gap > 0 do + begin + for i = gap+1 to ARRAY_SIZE + j = i - gap + while j > 0 do + begin + k = j + gap + if numbers(j) <= numbers(k) then + j = 0 + else + begin + temp = numbers(j) + numbers(j) = numbers(k) + numbers(k) = temp + end + j = j - gap + end while + next i + gap = gap / 2 + end while + +rem show result +print "Sorted :"; +for i = 1 to ARRAY_SIZE + print numbers(i); +next i +print + +end diff --git a/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.adb b/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.adb new file mode 100644 index 0000000000..42ff836abb --- /dev/null +++ b/Task/Sort-disjoint-sublist/Ada/sort-disjoint-sublist.adb @@ -0,0 +1,57 @@ +with Ada.Text_IO, GNAT.Bubble_Sort; +use Ada.Text_IO; + +procedure DisjointSort is + + package Int_Io is new Integer_IO (Integer); + + subtype Index_Range is Natural range 1 .. 8; + Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0); + + subtype Subindex_Range is Natural range 1 .. 3; + type Sub_Arrays is array (Subindex_Range) of Integer; + + Sub_Index : Sub_Arrays := (7, 2, 8); + Sub_Array : Sub_Arrays; + + -- reuse of the somehow generic GNAT.Bubble_Sort (for Ada05) + + procedure Sort (Work_Array : in out Sub_Arrays) is + procedure Exchange (Op1, Op2 : Natural) is + Temp : Integer; + begin + Temp := Work_Array (Op1); + Work_Array (Op1) := Work_Array (Op2); + Work_Array (Op2) := Temp; + end Exchange; + + function Lt (Op1, Op2 : Natural) return Boolean is + begin + return (Work_Array (Op1) < Work_Array (Op2)); + end Lt; + begin + GNAT.Bubble_Sort.Sort + (N => Subindex_Range'Last, + Xchg => Exchange'Unrestricted_Access, + Lt => Lt'Unrestricted_Access); + end Sort; + +begin + -- as the positions are not ordered, first sort the positions + Sort (Sub_Index); + -- extract the values to be sorted + for I in Subindex_Range loop + Sub_Array (I) := Input_Array (Sub_Index (I)); + end loop; + Sort (Sub_Array); + -- put the sorted values at the right place + for I in Subindex_Range loop + Input_Array (Sub_Index (I)) := Sub_Array (I); + end loop; + + for I in Index_Range loop + Int_Io.Put (Input_Array (I), Width => 2); + end loop; + New_Line; + +end DisjointSort; diff --git a/Task/Sort-disjoint-sublist/Crystal/sort-disjoint-sublist.cr b/Task/Sort-disjoint-sublist/Crystal/sort-disjoint-sublist.cr new file mode 100644 index 0000000000..b2162a1d4b --- /dev/null +++ b/Task/Sort-disjoint-sublist/Crystal/sort-disjoint-sublist.cr @@ -0,0 +1,12 @@ +module Indexable::Mutable + def sort_at! (indices) + indices = indices.sort + indices.map {|idx| self[idx] }.sort.zip(indices) {|v, idx| self[idx] = v } + self + end +end + +values = [7, 6, 5, 4, 3, 2, 1, 0] +indices = [6, 1, 7] + +p! values, values.sort_at!(indices) diff --git a/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.eu b/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.eu new file mode 100644 index 0000000000..ba44a01256 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Euphoria/sort-disjoint-sublist.eu @@ -0,0 +1,29 @@ +include sort.e + +function uniq(sequence s) + sequence out + out = s[1..1] + for i = 2 to length(s) do + if not find(s[i], out) then + out = append(out, s[i]) + end if + end for + return out +end function + +function disjointSort(sequence s, sequence idx) + sequence values + idx = uniq(sort(idx)) + values = repeat(0, length(idx)) + for i = 1 to length(idx) do + values[i] = s[idx[i]] + end for + values = sort(values) + for i = 1 to length(idx) do + s[idx[i]] = values[i] + end for + return s +end function + +constant data = {7, 6, 5, 4, 3, 2, 1, 0} +constant indexes = {7, 2, 8} diff --git a/Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist.phix b/Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist.phix new file mode 100644 index 0000000000..fbba30543c --- /dev/null +++ b/Task/Sort-disjoint-sublist/Phix/sort-disjoint-sublist.phix @@ -0,0 +1,7 @@ +with javascript_semantics +function disjoint_sort(sequence s, idx) + idx = unique(idx) + return reinstate(s,idx,sort(extract(s,idx))) +end function + +?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8}) diff --git a/Task/Sort-disjoint-sublist/Pluto/sort-disjoint-sublist.pluto b/Task/Sort-disjoint-sublist/Pluto/sort-disjoint-sublist.pluto new file mode 100644 index 0000000000..cba89e821f --- /dev/null +++ b/Task/Sort-disjoint-sublist/Pluto/sort-disjoint-sublist.pluto @@ -0,0 +1,16 @@ +-- Sorts values in place, leaves indices unsorted. +local function sort_disjoint(values, indices) + local sublist = indices:mapped(|ix| -> values[ix]):sort() + local i = 1 + local indices2 = indices:clone():sort() + for indices2 as ix do + values[ix] = sublist[i] + i += 1 + end +end + +local values = {7, 6, 5, 4, 3, 2, 1, 0} +local indices = {7, 2, 8} -- 1-based indexing +print($"Initial: {values:concat(", ")}") +sort_disjoint(values, indices) +print($"Sorted : {values:concat(", ")}") diff --git a/Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.ps1 b/Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.ps1 new file mode 100644 index 0000000000..373109e071 --- /dev/null +++ b/Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.ps1 @@ -0,0 +1,9 @@ +function sublistsort($values, $indices) { + $indices = $indices | sort + $sub, $i = ($values[$indices] | sort), 0 + $indices | foreach { $values[$_] = $sub[$i++] } + $values +} +$values = 7, 6, 5, 4, 3, 2, 1, 0 +$indices = 6, 1, 7 +"$(sublistsort $values $indices)" diff --git a/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx b/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx index 28f2d83f4d..8626e49a3c 100644 --- a/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx +++ b/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx @@ -1,45 +1,44 @@ --- 21 Jan 2026 +-- 31 Mar 2026 include Setting say 'SORT DISJOINT SUBLIST' say version say -call Prepare -say 'INPUT' -call Stemshow 'vals. inds.idx.',3 --- Order by index, sync value -call Stemsort 'inds.idx.','inds.val.' --- Order by value, don't sync index -call Stemsort 'inds.val.' --- Put ordered values back in list +call Struct2stem 'val1.','7 6 5 4 3 2 1 0' +call Struct2stem 'indx.','7 2 8' +call Collect +call ShowSt 'val1.','value1 before',,3 +call ShowSt 'indx.','index before',,3 +call ShowSt 'val2.','value2 before',,3 +-- 1 Order by index, sync value +call SortSt 'indx.','val2.' +call ShowSt 'indx.','index after sort1',,3 +call ShowSt 'val2.','value2 after sort1',,3 +-- 2 Order by value, leave index in place +call SortSt 'val2.' +call ShowSt 'indx.','index after sort2',,3 +call ShowSt 'val2.','value2 after sort2',,3 +-- 3 Put ordered values back in list call Update -say 'OUTPUT' -call Stemshow 'vals.',3 +call ShowSt 'val1.','value1 result',,3 exit -Prepare: -procedure expose vals. inds. --- Save values -values=7 6 5 4 3 2 1 0; n=Words(values) -do i=1 to n - vals.i=Word(values,i) +Collect: +procedure expose val1. indx. val2. +-- Collect values requested indices +do i=1 to indx.0 + j=indx.i; val2.i=val1.j end -vals.0=n --- Save 1-based indices and their values -indices=7 2 8; n=Words(indices) -do i=1 to n - index=Word(indices,i); inds.val.i=vals.index; inds.idx.i=index -end -inds.0=n +val2.0=indx.0 return Update: -procedure expose vals. inds. +procedure expose val1. indx. val2. -- Restore sorted values -do i=1 to inds.0 - index=inds.idx.i; vals.index=inds.val.i +do i=1 to indx.0 + j=indx.i; val1.j=val2.i end return --- Stemshow Stemsort +-- ShowSt; SortSt; Struct2stem include Math diff --git a/Task/Sort-numbers-lexicographically/Ada/sort-numbers-lexicographically.adb b/Task/Sort-numbers-lexicographically/Ada/sort-numbers-lexicographically.adb new file mode 100644 index 0000000000..38414aef1f --- /dev/null +++ b/Task/Sort-numbers-lexicographically/Ada/sort-numbers-lexicographically.adb @@ -0,0 +1,19 @@ +WITH Ada.Containers.Generic_Array_Sort, Ada.Text_IO; +USE Ada.Text_IO; +PROCEDURE Main IS + TYPE Natural_Array IS ARRAY (Positive RANGE <>) OF Natural; + FUNCTION Less (L, R : Natural) RETURN Boolean IS (L'Img < R'Img); + PROCEDURE Sort_Naturals IS NEW Ada.Containers.Generic_Array_Sort + (Positive, Natural, Natural_Array, Less); + PROCEDURE Show (Last : Natural) IS + A : Natural_Array (1 .. Last); + BEGIN + FOR I IN A'Range LOOP A (I) := I; END LOOP; + Sort_Naturals (A); + FOR I IN A'Range LOOP Put (A (I)'Img); END LOOP; + New_Line; + END Show; +BEGIN + Show (13); + Show (21); +END Main; diff --git a/Task/Sort-numbers-lexicographically/COBOL/sort-numbers-lexicographically.cob b/Task/Sort-numbers-lexicographically/COBOL/sort-numbers-lexicographically.cob new file mode 100644 index 0000000000..c1bb5a7935 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/COBOL/sort-numbers-lexicographically.cob @@ -0,0 +1,36 @@ + identification division. + program-id. LexicographicalNumbers. + + data division. + working-storage section. + 78 MAX-NUMBERS value 21. + 77 i pic 9(2). + 77 edited-number pic z(2). + + 01 lex-table. + 05 table-itms occurs MAX-NUMBERS. + 10 number-lex pic x(2). + + procedure division. + main. + *>-> Load numbers + perform varying i from 1 by 1 until i > MAX-NUMBERS + move i to edited-number + move edited-number to number-lex(i) + call "C$JUSTIFY" using number-lex(i), "Left" + end-perform + + *>-> Sort in lexicographic order + sort table-itms ascending number-lex + + *>-> Show ordered numbers + display "[" no advancing + perform varying i from 1 by 1 until i > MAX-NUMBERS + display function trim(number-lex(i)) no advancing + if i < MAX-NUMBERS + display ", " no advancing + end-if + end-perform + display "]" + stop run + . diff --git a/Task/Sort-numbers-lexicographically/F-Sharp/sort-numbers-lexicographically.fs b/Task/Sort-numbers-lexicographically/F-Sharp/sort-numbers-lexicographically.fs new file mode 100644 index 0000000000..d4e3dea7d1 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/F-Sharp/sort-numbers-lexicographically.fs @@ -0,0 +1 @@ +printfn "%A" ([1..20]|>List.sortBy(string)) diff --git a/Task/Sort-numbers-lexicographically/JavaScript/sort-numbers-lexicographically.js b/Task/Sort-numbers-lexicographically/JavaScript/sort-numbers-lexicographically.js new file mode 100644 index 0000000000..ea307d5e4c --- /dev/null +++ b/Task/Sort-numbers-lexicographically/JavaScript/sort-numbers-lexicographically.js @@ -0,0 +1,10 @@ +function lex_sort(n) { + let a = []; + const lims = n > 0 ? [1, n] : [n, 1]; + for (let i = lims[0]; i <= lims[1]; i++) { + a.push(i); + } + return a.toSorted(); +} + +console.log(lex_sort(13)); diff --git a/Task/Sort-numbers-lexicographically/Pluto/sort-numbers-lexicographically.pluto b/Task/Sort-numbers-lexicographically/Pluto/sort-numbers-lexicographically.pluto new file mode 100644 index 0000000000..9afd995c71 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/Pluto/sort-numbers-lexicographically.pluto @@ -0,0 +1,2 @@ +local a = range(1, 13):map(|i| -> tostring(i)):sort():concat(", ") +print(a) diff --git a/Task/Sort-numbers-lexicographically/V-(Vlang)/sort-numbers-lexicographically.v b/Task/Sort-numbers-lexicographically/V-(Vlang)/sort-numbers-lexicographically.v new file mode 100644 index 0000000000..d80d625870 --- /dev/null +++ b/Task/Sort-numbers-lexicographically/V-(Vlang)/sort-numbers-lexicographically.v @@ -0,0 +1,15 @@ +fn lex_order(nir int) []int { + mut first, mut last := 1, nir + mut numbers := []string{} + if nir < 1 { + first = nir + last = 1 + } + for ial in first .. last + 1 { numbers << ial.str() } + return numbers.sorted().map(it.int()) +} + +fn main() { + println("In lexicographical order:\n") + for nal in [0, 5, 13, 21, -22] { println("${nal:3d}: ${lex_order(nal)}") } +} diff --git a/Task/Sort-stability/Rebol/sort-stability.rebol b/Task/Sort-stability/Rebol/sort-stability.rebol new file mode 100644 index 0000000000..7379d03961 --- /dev/null +++ b/Task/Sort-stability/Rebol/sort-stability.rebol @@ -0,0 +1,18 @@ +; Rebol's sort function is not stable by default. You need to use a custom comparator to make it so. + +blk: [ + [UK London] + [US New-York] + [US Birmingham] + [UK Birmingham] +] +sort/compare blk func [a b] [either a/2 < b/2 [-1] [either a/2 > b/2 [1] [0]]] + +; Note that you can also do a stable sort without nested blocks. +blk: [ + UK London + US New-York + US Birmingham + UK Birmingham +] +sort/skip/compare blk 2 func [a b] [either a < b [-1] [either a > b [1] [0]]] diff --git a/Task/Sort-three-variables/Ada/sort-three-variables.adb b/Task/Sort-three-variables/Ada/sort-three-variables.adb new file mode 100644 index 0000000000..0aef9a2200 --- /dev/null +++ b/Task/Sort-three-variables/Ada/sort-three-variables.adb @@ -0,0 +1,64 @@ +with Ada.Text_IO; +with Ada.Strings.Unbounded; + +procedure Sort_Three is + + generic + type Element_Type is private; + with function "<" (Left, Right : in Element_Type) return Boolean; + procedure Generic_Sort (X, Y, Z : in out Element_Type); + + procedure Generic_Sort (X, Y, Z : in out Element_Type) + is + procedure Swap (Left, Right : in out Element_Type) is + T : constant Element_Type := Left; + begin + Left := Right; + Right := T; + end Swap; + begin + if Y < X then Swap (X, Y); end if; + if Z < Y then Swap (Y, Z); end if; + if Y < X then Swap (X, Y); end if; + end Generic_Sort; + + procedure Test_Unbounded_Sort is + use Ada.Text_IO; + use Ada.Strings.Unbounded; + + X : Unbounded_String := To_Unbounded_String ("lions, tigers, and"); + Y : Unbounded_String := To_Unbounded_String ("bears, oh my!"); + Z : Unbounded_String := To_Unbounded_String ("(from the ""Wizard of OZ"")"); + + procedure Sort is + new Generic_Sort (Unbounded_String, "<"); + begin + Sort (X, Y, Z); + Put_Line (To_String (X)); + Put_Line (To_String (Y)); + Put_Line (To_String (Z)); + New_Line; + End Test_Unbounded_Sort; + + procedure Test_Integer_Sort is + + use Ada.Text_IO; + + procedure Sort is + new Generic_Sort (Integer, "<"); + + X : Integer := 77444; + Y : Integer := -12; + Z : Integer := 0; + begin + Sort (X, Y, Z); + Put_Line (X'Image); + Put_Line (Y'Image); + Put_Line (Z'Image); + New_Line; + end Test_Integer_Sort; + +begin + Test_Unbounded_Sort; + Test_Integer_Sort; +end Sort_Three; diff --git a/Task/Sort-three-variables/COBOL/sort-three-variables.cob b/Task/Sort-three-variables/COBOL/sort-three-variables.cob new file mode 100644 index 0000000000..3a376d048b --- /dev/null +++ b/Task/Sort-three-variables/COBOL/sort-three-variables.cob @@ -0,0 +1,43 @@ + program-id. 3var. + data division. + working-storage section. + 1 n binary pic 9(4). + 1 num pic -(7)9. + 1 a1 pic x(32) value "lions, tigers, and". + 1 a2 pic x(32) value "bears, oh my!". + 1 a3 pic x(32) value "(from the ""Wizard of OZ"")". + 1 n1 pic x(8) value "77444". + 1 n2 pic x(8) value "-12". + 1 n3 pic x(8) value "0". + 1 alpha-table. + 2 alpha-entry occurs 3 pic x(32). + 1 numeric-table. + 2 numeric-entry occurs 3 pic s9(8). + 1 filler value "x = y = z = ". + 2 lead-in occurs 3 pic x(4). + procedure division. + begin. + move a1 to alpha-entry (1) + move a2 to alpha-entry (2) + move a3 to alpha-entry (3) + sort alpha-entry ascending alpha-entry + perform varying n from 1 by 1 + until n > 3 + display lead-in (n) alpha-entry (n) + end-perform + + display space + + compute numeric-entry (1) = function numval (n1) + compute numeric-entry (2) = function numval (n2) + compute numeric-entry (3) = function numval (n3) + sort numeric-entry ascending numeric-entry + perform varying n from 1 by 1 + until n > 3 + move numeric-entry (n) to num + display lead-in (n) num + end-perform + + stop run + . + end program 3var. diff --git a/Task/Sort-three-variables/Logo/sort-three-variables.logo b/Task/Sort-three-variables/Logo/sort-three-variables.logo new file mode 100644 index 0000000000..9869f29563 --- /dev/null +++ b/Task/Sort-three-variables/Logo/sort-three-variables.logo @@ -0,0 +1,31 @@ +;;; Sort 3 variables + +to gt? :a :b + if (and word? :a word? :b) [output before? :b :a] + if (and number? :a number? :b) [output :a > :b] + throw "ERROR +end + +to swap :v1 :v2 ; swaps the values of the variables whose names are :v1 and :v2 + make "t thing :v1 + make :v1 thing :v2 + make :v2 :t +end + +to sort3 :v1 :v2 :v3 ; sorts the variables whose names are :v1, :v2 and :v3 + if gt? thing :v1 thing :v2 [swap :v1 :v2] + if gt? thing :v1 thing :v3 [swap :v1 :v3] + if gt? thing :v2 thing :v3 [swap :v2 :v3] +end + +make "a "lions,\ tigers,\ and +make "b "bears,\ oh\ my! +make "c "\(from\ the\ \"Wizard\ of\ OZ\"\) +sort3 "a "b "c +print :a print :b print :c + +make "a 77444 +make "b -12 +make "c 0 +sort3 "a "b "c +print :a print :b print :c diff --git a/Task/Sort-three-variables/R/sort-three-variables.r b/Task/Sort-three-variables/R/sort-three-variables.r new file mode 100644 index 0000000000..3a3c2997ab --- /dev/null +++ b/Task/Sort-three-variables/R/sort-three-variables.r @@ -0,0 +1,14 @@ +assignVec <- Vectorize("assign", c("x", "value")) +`%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv)) # define multiple global assignments operator + +x <- 'lions, tigers, and' +y <- 'bears, oh my!' +z <- '(from the "Wizard of OZ")' + +c("x", "y", "z") %<<-% sort(c(x, y, z)) + +x <- 77444 +y <- -12 +z <- 0 + +c("x", "y", "z") %<<-% sort(c(x, y, z)) diff --git a/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.adb b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.adb new file mode 100644 index 0000000000..d9846c6c08 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.adb @@ -0,0 +1,108 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Gnat.Heap_Sort_G; + +procedure Custom_Compare is + + type StringArrayType is array (Natural range <>) of Unbounded_String; + + Strings : StringArrayType := (Null_Unbounded_String, + To_Unbounded_String("this"), + To_Unbounded_String("is"), + To_Unbounded_String("a"), + To_Unbounded_String("set"), + To_Unbounded_String("of"), + To_Unbounded_String("strings"), + To_Unbounded_String("to"), + To_Unbounded_String("sort"), + To_Unbounded_String("This"), + To_Unbounded_String("Is"), + To_Unbounded_String("A"), + To_Unbounded_String("Set"), + To_Unbounded_String("Of"), + To_Unbounded_String("Strings"), + To_Unbounded_String("To"), + To_Unbounded_String("Sort")); + + procedure Move (From, To : in Natural) is + + begin + Strings(To) := Strings(From); + end Move; + + function UpCase (Char : in Character) return Character is + Temp : Character; + begin + if Char >= 'a' and Char <= 'z' then + Temp := Character'Val(Character'Pos(Char) + - Character'Pos('a') + + Character'Pos('A')); + else + Temp := Char; + end if; + return Temp; + end UpCase; + + function Lt (Op1, Op2 : Natural) + return Boolean is + Temp, Len : Natural; + begin + Len := Length(Strings(Op1)); + Temp := Length(Strings(Op2)); + if Len < Temp then + return False; + elsif Len > Temp then + return True; + end if; + + declare + S1, S2 : String(1..Len); + begin + S1 := To_String(Strings(Op1)); + S2 := To_String(Strings(Op2)); + Put("Same size: "); + Put(S1); + Put(" "); + Put(S2); + Put(" "); + for I in S1'Range loop + Put(UpCase(S1(I))); + Put(UpCase(S2(I))); + if UpCase(S1(I)) = UpCase(S2(I)) then + null; + elsif UpCase(S1(I)) < UpCase(S2(I)) then + Put(" LT"); + New_Line; + return True; + else + return False; + end if; + end loop; + Put(" GTE"); + New_Line; + return False; + end; + end Lt; + + procedure Put (Arr : in StringArrayType) is + begin + for I in 1..Arr'Length-1 loop + Put(To_String(Arr(I))); + New_Line; + end loop; + end Put; + + package Heap is new Gnat.Heap_Sort_G(Move, + Lt); + use Heap; + + +begin + Put_Line("Unsorted list:"); + Put(Strings); + New_Line; + Sort(16); + New_Line; + Put_Line("Sorted list:"); + Put(Strings); +end Custom_Compare; diff --git a/Task/Sort-using-a-custom-comparator/Crystal/sort-using-a-custom-comparator.cr b/Task/Sort-using-a-custom-comparator/Crystal/sort-using-a-custom-comparator.cr new file mode 100644 index 0000000000..22573350d0 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Crystal/sort-using-a-custom-comparator.cr @@ -0,0 +1,4 @@ +words = ("Sort an array (or list) of strings in order of descending length, " + + "and in ascending lexicographic order for strings of equal length.").scan(/\w+/).map &.to_s + +p words.sort_by {|word| { -word.size, word.downcase } } diff --git a/Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.eu b/Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.eu new file mode 100644 index 0000000000..fc889cc54f --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Euphoria/sort-using-a-custom-comparator.eu @@ -0,0 +1,20 @@ +include sort.e +include wildcard.e +include misc.e + +function my_compare(sequence a, sequence b) + if length(a)!=length(b) then + return -compare(length(a),length(b)) + else + return compare(lower(a),lower(b)) + end if +end function + +sequence strings +strings = reverse({ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" }) + +puts(1,"Unsorted:\n") +pretty_print(1,strings,{2}) + +puts(1,"\n\nSorted:\n") +pretty_print(1,custom_sort(routine_id("my_compare"),strings),{2}) diff --git a/Task/Sort-using-a-custom-comparator/Pluto/sort-using-a-custom-comparator.pluto b/Task/Sort-using-a-custom-comparator/Pluto/sort-using-a-custom-comparator.pluto new file mode 100644 index 0000000000..933e3c8c68 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Pluto/sort-using-a-custom-comparator.pluto @@ -0,0 +1,11 @@ +local fmt = require "fmt" + +local function comp(s, t) + if #s == #t then return s:lower() < t:lower() end + return #s > #t +end + +local strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"} +fmt.print("Unsorted: %,s", strings) +strings:sort(comp) +fmt.print("Sorted : %,s", strings) diff --git a/Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.ps1 b/Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.ps1 new file mode 100644 index 0000000000..b4e63cb3c3 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/PowerShell/sort-using-a-custom-comparator.ps1 @@ -0,0 +1,2 @@ +$list = "Here", "are", "some", "sample", "strings", "to", "be", "sorted" +$list | Sort-Object {-$_.Length},{$_} diff --git a/Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cob b/Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cob new file mode 100644 index 0000000000..0b95bcd41d --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/COBOL/sorting-algorithms-bead-sort.cob @@ -0,0 +1,98 @@ + >>SOURCE FORMAT FREE +*> This code is dedicated to the public domain +*> This is GNUCOBOL 2.0 +identification division. +program-id. beadsort. +environment division. +configuration section. +repository. function all intrinsic. +data division. +working-storage section. +01 filler. + 03 row occurs 9 pic x(9). + 03 r pic 99. + 03 r1 pic 99. + 03 r2 pic 99. + 03 pole pic 99. + 03 a-lim pic 99 value 9. + 03 a pic 99. + 03 array occurs 9 pic 9. +01 NL pic x value x'0A'. +procedure division. +start-beadsort. + + *> fill the array + compute a = random(seconds-past-midnight) + perform varying a from 1 by 1 until a > a-lim + compute array(a) = random() * 10 + end-perform + + perform display-array + display space 'initial array' + + *> distribute the beads + perform varying r from 1 by 1 until r > a-lim + move all '.' to row(r) + perform varying pole from 1 by 1 until pole > array(r) + move 'o' to row(r)(pole:1) + end-perform + end-perform + display NL 'initial beads' + perform display-beads + + *> drop the beads + perform varying pole from 1 by 1 until pole > a-lim + move a-lim to r2 + perform find-opening + compute r1 = r2 - 1 + perform find-bead + perform until r1 = 0 *> no bead or no opening + *> drop the bead + move '.' to row(r1)(pole:1) + move 'o' to row(r2)(pole:1) + *> continue up the pole + compute r2 = r2 - 1 + perform find-opening + compute r1 = r2 - 1 + perform find-bead + end-perform + end-perform + display NL 'dropped beads' + perform display-beads + + *> count the beads in each row + perform varying r from 1 by 1 until r > a-lim + move 0 to array(r) + inspect row(r) tallying array(r) + for all 'o' before initial '.' + end-perform + + perform display-array + display space 'sorted array' + + stop run + . +find-opening. + perform varying r2 from r2 by -1 + until r2 = 1 or row(r2)(pole:1) = '.' + continue + end-perform + . +find-bead. + perform varying r1 from r1 by -1 + until r1 = 0 or row(r1)(pole:1) = 'o' + continue + end-perform + . +display-array. + display space + perform varying a from 1 by 1 until a > a-lim + display space array(a) with no advancing + end-perform + . +display-beads. + perform varying r from 1 by 1 until r > a-lim + display row(r) + end-perform + . +end program beadsort. diff --git a/Task/Sorting-algorithms-Bead-sort/EasyLang/sorting-algorithms-bead-sort.easy b/Task/Sorting-algorithms-Bead-sort/EasyLang/sorting-algorithms-bead-sort.easy new file mode 100644 index 0000000000..f2c6de77da --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/EasyLang/sorting-algorithms-bead-sort.easy @@ -0,0 +1,21 @@ +proc beadSort &a[] . + for i to len a[] : max = higher max a[i] + len beads[][] len a[] + for i to len a[] + len beads[i][] max + for j to a[i] : beads[i][j] = 1 + . + for j to max + sum = 0 + for i = 1 to len a[] + sum += beads[i][j] + beads[i][j] = 0 + . + for i = len a[] downto len a[] - sum + 1 + a[i] = j + . + . +. +a[] = [ 4 38 100 1 25 69 69 16 8 59 71 53 33 ] +beadSort a[] +print a[] diff --git a/Task/Sorting-algorithms-Bead-sort/Pluto/sorting-algorithms-bead-sort.pluto b/Task/Sorting-algorithms-Bead-sort/Pluto/sorting-algorithms-bead-sort.pluto new file mode 100644 index 0000000000..4c14655867 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Pluto/sorting-algorithms-bead-sort.pluto @@ -0,0 +1,23 @@ +require "table2" + +local function bead_sort(a) + local res = {} + local max = a:max() + local trans = table.rep(max, 0) + for a as i do + for n = 1, i do trans[n] += 1 end + end + for a as _ do + res:insert(trans:count(|n| -> n > 0)) + for n = 1, #trans do trans[n] -= 1 end + end + return res:reverse() -- return in ascending order +end + +local array = { {4, 65, 2, 31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + local b = bead_sort(a) + print($"After : \{{b:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.ps1 b/Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.ps1 new file mode 100644 index 0000000000..f37bb2a524 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PowerShell/sorting-algorithms-bead-sort.ps1 @@ -0,0 +1,40 @@ +Function BeadSort ( [Int64[]] $indata ) +{ + if( $indata.length -gt 1 ) + { + $min = $indata[ 0 ] + $max = $indata[ 0 ] + for( $i = 1; $i -lt $indata.length; $i++ ) + { + if( $indata[ $i ] -lt $min ) + { + $min = $indata[ $i ] + } + if( $indata[ $i ] -gt $max ) { + $max = $indata[ $i ] + } + } #Find the min & max + $poles = New-Object 'UInt64[]' ( $max - $min + 1 ) + $indata | ForEach-Object { + $min..$_ | ForEach-Object { + $poles[ $_ - $min ] += 1 + } + } #Add Beads to the poles, already moved to the bottom + $min..( $max - 1 ) | ForEach-Object { + $i = $_ - $min + if( $poles[ $i ] -gt $poles[ $i + 1 ] ) + { #No special case needed for min, since there will always be at least 1 = min + ( $poles[ $i ] )..( $poles[ $i + 1 ] + 1 ) | ForEach-Object { + Write-Output ( $i + $min ) + } + } + } #Output the results in pipeline fashion + 1..( $poles[ $max - $min ] ) | ForEach-Object { + Write-Output $max #No special case needed for max, since there will always be at least 1 = max + } + } else { + Write-Output $indata + } +} + +$l = 100; BeadSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Bead-sort/R/sorting-algorithms-bead-sort.r b/Task/Sorting-algorithms-Bead-sort/R/sorting-algorithms-bead-sort.r new file mode 100644 index 0000000000..6f62c826c5 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/R/sorting-algorithms-bead-sort.r @@ -0,0 +1,12 @@ +gen_abacus <- function(v){ + nmax <- max(v) + gen_col <- function(n) c(rep(1, n), rep(0, nmax-n)) + sapply(v, gen_col) +} + +beadsort <- function(v){ + flip <- function(v) gen_abacus(v) |> apply(1, sum) + v |> flip() |> flip() |> rev() +} + +beadsort(c(2, 4, 1, 3, 3)) diff --git a/Task/Sorting-algorithms-Bead-sort/Ring/sorting-algorithms-bead-sort.ring b/Task/Sorting-algorithms-Bead-sort/Ring/sorting-algorithms-bead-sort.ring new file mode 100644 index 0000000000..4a1ca5f836 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Ring/sorting-algorithms-bead-sort.ring @@ -0,0 +1,63 @@ +# Bead Sort algorithm in Ring language +aList = [5, 3, 1, 7, 4, 1, 1, 20] +see "Original list: " + nl +showList(aList) + +aList = beadSort(aList) + +see "Sorted list: " + nl +showList(aList) + +func beadSort aData + nLen = len(aData) + if nLen = 0 return aData ok + + # Find largest element (number of columns) + nMax = aData[1] + for x in aData + if x > nMax nMax = x ok + next + + # Initialize a matrix of beads (rows x columns) + # In Ring, the lists are indexed from 1 + beads = list(nLen) + for i = 1 to nLen + beads[i] = list(nMax) + for j = 1 to nMax + if j <= aData[i] + beads[i][j] = 1 + else + beads[i][j] = 0 + ok + next + next + + # Simulate gravity: column-wise summation and redistribution + for j = 1 to nMax + sum = 0 + for i = 1 to nLen + sum += beads[i][j] + beads[i][j] = 0 + next + + # The beads "fall" to the bottom + for i = nLen-sum+1 to nLen + beads[i][j] = 1 + next + next + + # Extract result from matrix + aResult = list(nLen) + for i = 1 to nLen + rowSum = 0 + for j = 1 to nMax + rowSum += beads[i][j] + next + aResult[i] = rowSum + next + + return aResult + +func showList aList + for x in aList see "" + x + " " next + see nl diff --git a/Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.adb b/Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.adb new file mode 100644 index 0000000000..46f938f8ee --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Ada/sorting-algorithms-bogosort.adb @@ -0,0 +1,50 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Numerics.Discrete_Random; + +procedure Test_Bogosort is + generic + type Ordered is private; + type List is array (Positive range <>) of Ordered; + with function "<" (L, R : Ordered) return Boolean is <>; + procedure Bogosort (Data : in out List); + + procedure Bogosort (Data : in out List) is + function Sorted return Boolean is + begin + for I in Data'First..Data'Last - 1 loop + if not (Data (I) < Data (I + 1)) then + return False; + end if; + end loop; + return True; + end Sorted; + subtype Index is Integer range Data'Range; + package Dices is new Ada.Numerics.Discrete_Random (Index); + use Dices; + Dice : Generator; + procedure Shuffle is + J : Index; + Temp : Ordered; + begin + for I in Data'Range loop + J := Random (Dice); + Temp := Data (I); + Data (I) := Data (J); + Data (J) := Temp; + end loop; + end Shuffle; + begin + while not Sorted loop + Shuffle; + end loop; + end Bogosort; + + type List is array (Positive range <>) of Integer; + procedure Integer_Bogosort is new Bogosort (Integer, List); + Sequence : List := (7,6,3,9); +begin + Integer_Bogosort (Sequence); + for I in Sequence'Range loop + Put (Integer'Image (Sequence (I))); + end loop; +end Test_Bogosort; diff --git a/Task/Sorting-algorithms-Bogosort/COBOL/sorting-algorithms-bogosort.cob b/Task/Sorting-algorithms-Bogosort/COBOL/sorting-algorithms-bogosort.cob new file mode 100644 index 0000000000..5a8e971e8a --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/COBOL/sorting-algorithms-bogosort.cob @@ -0,0 +1,65 @@ +identification division. +program-id. bogo-sort-program. +data division. +working-storage section. +01 array-to-sort. + 05 item-table. + 10 item pic 999 + occurs 10 times. +01 randomization. + 05 random-seed pic 9(8). + 05 random-index pic 9. +01 flags-counters-etc. + 05 array-index pic 99. + 05 adjusted-index pic 99. + 05 temporary-storage pic 999. + 05 shuffles pic 9(8) + value zero. + 05 sorted pic 9. +01 numbers-without-leading-zeros. + 05 item-no-zeros pic z(4). + 05 shuffles-no-zeros pic z(8). +procedure division. +control-paragraph. + accept random-seed from time. + move function random(random-seed) to item(1). + perform random-item-paragraph varying array-index from 2 by 1 + until array-index is greater than 10. + display 'BEFORE SORT:' with no advancing. + perform show-array-paragraph varying array-index from 1 by 1 + until array-index is greater than 10. + display ''. + perform shuffle-paragraph through is-it-sorted-paragraph + until sorted is equal to 1. + display 'AFTER SORT: ' with no advancing. + perform show-array-paragraph varying array-index from 1 by 1 + until array-index is greater than 10. + display ''. + move shuffles to shuffles-no-zeros. + display shuffles-no-zeros ' SHUFFLES PERFORMED.' + stop run. +random-item-paragraph. + move function random to item(array-index). +show-array-paragraph. + move item(array-index) to item-no-zeros. + display item-no-zeros with no advancing. +shuffle-paragraph. + perform shuffle-items-paragraph, + varying array-index from 1 by 1 + until array-index is greater than 10. + add 1 to shuffles. +is-it-sorted-paragraph. + move 1 to sorted. + perform item-in-order-paragraph varying array-index from 1 by 1, + until sorted is equal to zero + or array-index is equal to 10. +shuffle-items-paragraph. + move function random to random-index. + add 1 to random-index giving adjusted-index. + move item(array-index) to temporary-storage. + move item(adjusted-index) to item(array-index). + move temporary-storage to item(adjusted-index). +item-in-order-paragraph. + add 1 to array-index giving adjusted-index. + if item(array-index) is greater than item(adjusted-index) + then move zero to sorted. diff --git a/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy b/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy index 527e5afa4d..56070f0cf1 100644 --- a/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy +++ b/Task/Sorting-algorithms-Bogosort/EasyLang/sorting-algorithms-bogosort.easy @@ -1,6 +1,6 @@ proc shuffle &l[] . for i = len l[] downto 2 - r = random i + r = random 1 i swap l[i] l[r] . . diff --git a/Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.eu b/Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.eu new file mode 100644 index 0000000000..cc02012539 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Euphoria/sorting-algorithms-bogosort.eu @@ -0,0 +1,32 @@ +function shuffle(sequence s) + object temp + integer j + for i = length(s) to 1 by -1 do + j = rand(i) + if i != j then + temp = s[i] + s[i] = s[j] + s[j] = temp + end if + end for + return s +end function + +function inOrder(sequence s) + for i = 1 to length(s)-1 do + if compare(s[i],s[i+1]) > 0 then + return 0 + end if + end for + return 1 +end function + +function bogosort(sequence s) + while not inOrder(s) do + ? s + s = shuffle(s) + end while + return s +end function + +? bogosort(shuffle({1,2,3,4,5,6})) diff --git a/Task/Sorting-algorithms-Bogosort/Pluto/sorting-algorithms-bogosort.pluto b/Task/Sorting-algorithms-Bogosort/Pluto/sorting-algorithms-bogosort.pluto new file mode 100644 index 0000000000..9f0dc8c557 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Pluto/sorting-algorithms-bogosort.pluto @@ -0,0 +1,17 @@ +require "table2" + +local function is_sorted(a) + for i = 1, #a - 1 do + if a[i] > a[i + 1] then return false end + end + return true +end + +local function bogosort(a) + while not is_sorted(a) do a:shuffle() end +end + +local a = {31, 41, 59, 26, 53, 58, 97, 93, 23, 84} +print($"Before: \{{a:concat(", ")}}") +bogosort(a) +print($"After : \{{a:concat(", ")}}") diff --git a/Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.ps1 b/Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.ps1 new file mode 100644 index 0000000000..a7332933b0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PowerShell/sorting-algorithms-bogosort.ps1 @@ -0,0 +1,29 @@ +function shuffle ($a) { + $c = $a.Clone() # make copy to avoid clobbering $a + 1..($c.Length - 1) | ForEach-Object { + $i = Get-Random -Minimum $_ -Maximum $c.Length + $c[$_-1],$c[$i] = $c[$i],$c[$_-1] + $c[$_-1] # return newly-shuffled value + } + $c[-1] # last value +} + +function isSorted( [Array] $data ) +{ + $sorted = $true + for( $i = 1; ( $i -lt $data.length ) -and $sorted; $i++ ) + { + $sorted = $data[ $i - 1 ] -le $data[ $i ] + } + $sorted +} + +function BogoSort ( [Array] $indata ) { + $data = $indata.Clone() + while( -not ( isSorted $data ) ) { + $data = shuffle $indata + } + $data +} + +$l = 7; BogoSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Bogosort/V-(Vlang)/sorting-algorithms-bogosort.v b/Task/Sorting-algorithms-Bogosort/V-(Vlang)/sorting-algorithms-bogosort.v index db81586657..6a31469e12 100644 --- a/Task/Sorting-algorithms-Bogosort/V-(Vlang)/sorting-algorithms-bogosort.v +++ b/Task/Sorting-algorithms-Bogosort/V-(Vlang)/sorting-algorithms-bogosort.v @@ -1,8 +1,8 @@ import rand -fn shuffle_array(mut arr []int) { +fn shuffle_array(mut arr []int)! { for i := arr.len - 1; i >= 0; i-- { - j := rand.intn(i + 1) + j := rand.intn(i + 1)! arr[i], arr[j] = arr[j], arr[i] } } @@ -16,9 +16,9 @@ fn is_sorted(arr []int) bool { return true } -fn sort_array(mut arr []int) { +fn sort_array(mut arr []int)! { for !is_sorted(arr) { - shuffle_array(mut arr) + shuffle_array(mut arr)! println('After Shuffle: $arr') } } @@ -26,6 +26,6 @@ fn sort_array(mut arr []int) { fn main() { mut array := [6, 9, 1, 4] println('Input: $array') - sort_array(mut array) + sort_array(mut array)! println('Output: $array') } diff --git a/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vbs b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vbs new file mode 100644 index 0000000000..17f2e3921f --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-1.vbs @@ -0,0 +1,30 @@ +sub swap( byref a, byref b ) + dim tmp + tmp = a + a = b + b = tmp +end sub + +'knuth shuffle (I think) +function shuffle( a ) + dim i + dim r + randomize timer + for i = lbound( a ) to ubound( a ) + r = int( rnd * ( ubound( a ) + 1 ) ) + if r <> i then + swap a(i), a(r) + end if + next + shuffle = a +end function + +function inOrder( a ) + dim res + dim i + for i = 0 to ubound( a ) - 1 + res = ( a(i) <= a(i+1) ) + if res = false then exit for + next + inOrder = res +end function diff --git a/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vbs b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vbs new file mode 100644 index 0000000000..c40320164b --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/VBScript/sorting-algorithms-bogosort-2.vbs @@ -0,0 +1,10 @@ +dim a +a = array(11, 1, 2, 3, 4, 4, 6, 7, 8) + +dim t +t = timer +while not inorder( a ) + shuffle a +wend +wscript.echo timer-t, "seconds" +wscript.echo join( a, ", " ) diff --git a/Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.adb b/Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.adb new file mode 100644 index 0000000000..fb60bad2d8 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Ada/sorting-algorithms-bubble-sort.adb @@ -0,0 +1,44 @@ +generic + type Element is private; + with function "=" (E1, E2 : Element) return Boolean is <>; + with function "<" (E1, E2 : Element) return Boolean is <>; + type Index is (<>); + type Arr is array (Index range <>) of Element; +procedure Bubble_Sort (A : in out Arr); + +procedure Bubble_Sort (A : in out Arr) is + Finished : Boolean; + Temp : Element; +begin + loop + Finished := True; + for J in A'First .. Index'Pred (A'Last) loop + if A (Index'Succ (J)) < A (J) then + Finished := False; + Temp := A (Index'Succ (J)); + A (Index'Succ (J)) := A (J); + A (J) := Temp; + end if; + end loop; + exit when Finished; + end loop; +end Bubble_Sort; + +-- Example of usage: +with Ada.Text_IO; use Ada.Text_IO; +with Bubble_Sort; +procedure Main is + type Arr is array (Positive range <>) of Integer; + procedure Sort is new + Bubble_Sort + (Element => Integer, + Index => Positive, + Arr => Arr); + A : Arr := (1, 3, 256, 0, 3, 4, -1); +begin + Sort (A); + for J in A'Range loop + Put (Integer'Image (A (J))); + end loop; + New_Line; +end Main; diff --git a/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-1.cob b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-1.cob new file mode 100644 index 0000000000..8944734d50 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-1.cob @@ -0,0 +1,145 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. BUBBLESORT. + AUTHOR. DAVE STRATFORD. + DATE-WRITTEN. MARCH 2010. + INSTALLATION. HEXAGON SYSTEMS LIMITED. + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + SOURCE-COMPUTER. ICL VME. + OBJECT-COMPUTER. ICL VME. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT FA-INPUT-FILE ASSIGN FL01. + SELECT FB-OUTPUT-FILE ASSIGN FL02. + + DATA DIVISION. + FILE SECTION. + + FD FA-INPUT-FILE. + 01 FA-INPUT-REC. + 03 FA-DATA PIC S9(6). + + FD FB-OUTPUT-FILE. + 01 FB-OUTPUT-REC PIC S9(6). + + WORKING-STORAGE SECTION. + 01 WA-IDENTITY. + 03 WA-PROGNAME PIC X(10) VALUE "BUBBLESORT". + 03 WA-VERSION PIC X(6) VALUE "000001". + + 01 WB-TABLE. + 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 + INDEXED BY WB-IX-1. + + 01 WC-VARS. + 03 WC-SIZE PIC S9(8) COMP SYNC. + 03 WC-TEMP PIC S9(8) COMP SYNC. + 03 WC-END PIC S9(8) COMP SYNC. + 03 WC-LAST-CHANGE PIC S9(8) COMP SYNC. + + 01 WF-CONDITION-FLAGS. + 03 WF-EOF-FLAG PIC X. + 88 END-OF-FILE VALUE "Y". + 03 WF-EMPTY-FILE-FLAG PIC X. + 88 EMPTY-FILE VALUE "Y". + + PROCEDURE DIVISION. + A-MAIN SECTION. + A-000. + PERFORM B-INITIALISE. + IF NOT EMPTY-FILE + PERFORM C-SORT. + PERFORM D-FINISH. + + A-999. + STOP RUN. + + B-INITIALISE SECTION. + B-000. + DISPLAY "*** " WA-PROGNAME " VERSION " + WA-VERSION " STARTING ***". + + MOVE ALL "N" TO WF-CONDITION-FLAGS. + OPEN INPUT FA-INPUT-FILE. + SET WB-IX-1 TO 0. + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG + WF-EMPTY-FILE-FLAG. + + PERFORM BA-READ-INPUT UNTIL END-OF-FILE. + + CLOSE FA-INPUT-FILE. + + SET WC-SIZE TO WB-IX-1. + + B-999. + EXIT. + + BA-READ-INPUT SECTION. + BA-000. + SET WB-IX-1 UP BY 1. + MOVE FA-DATA TO WB-ENTRY(WB-IX-1). + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG. + + BA-999. + EXIT. + + C-SORT SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE WC-SIZE TO WC-END. + PERFORM E-BUBBLE UNTIL WC-END = 1. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + D-FINISH SECTION. + D-000. + OPEN OUTPUT FB-OUTPUT-FILE. + SET WB-IX-1 TO 1. + + PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE. + + CLOSE FB-OUTPUT-FILE. + + DISPLAY "*** " WA-PROGNAME " FINISHED ***". + + D-999. + EXIT. + + DA-WRITE-OUTPUT SECTION. + DA-000. + WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). + SET WB-IX-1 UP BY 1. + + DA-999. + EXIT. + + E-BUBBLE SECTION. + E-000. + MOVE 1 TO WC-LAST-CHANGE. + + PERFORM F-PASS VARYING WB-IX-1 FROM 1 BY 1 + UNTIL WB-IX-1 = WC-END. + + MOVE WC-LAST-CHANGE TO WC-END. + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + IF WB-ENTRY(WB-IX-1) > WB-ENTRY(WB-IX-1 + 1) + SET WC-LAST-CHANGE TO WB-IX-1 + MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1 + 1) TO WB-ENTRY(WB-IX-1) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1 + 1). + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-2.cob b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-2.cob new file mode 100644 index 0000000000..ec1be92241 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-2.cob @@ -0,0 +1,54 @@ + identification division. + program-id. BUBBLSRT. + data division. + working-storage section. + 01 changed-flag pic x. + 88 hasChanged value 'Y'. + 88 hasNOTChanged value 'N'. + 01 itemCount pic 99. + 01 tempItem pic 99. + 01 itemArray. + 03 itemArrayCount pic 99. + 03 item pic 99 occurs 99 times + indexed by itemIndex. + * + procedure division. + main. + * place the values to sort into itemArray + move 10 to itemArrayCount + move 28 to item (1) + move 44 to item (2) + move 46 to item (3) + move 24 to item (4) + move 19 to item (5) + move 2 to item (6) + move 17 to item (7) + move 11 to item (8) + move 24 to item (9) + move 4 to item (10) + * store the starting count in itemCount and perform the sort + move itemArrayCount to itemCount + perform bubble-sort + * output the results + perform varying itemIndex from 1 by 1 + until itemIndex > itemArrayCount + display item (itemIndex) ';' with no advancing + end-perform + * thats it! + stop run. + * + bubble-sort. + perform with test after until hasNOTchanged + set hasNOTChanged to true + subtract 1 from itemCount + perform varying itemIndex from 1 by 1 + until itemIndex > itemCount + if item (itemIndex) > item (itemIndex + 1) + move item (itemIndex) to tempItem + move item (itemIndex + 1) to item (itemIndex) + move tempItem to item (itemIndex + 1) + set hasChanged to true + end-if + end-perform + end-perform + . diff --git a/Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.eu b/Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.eu new file mode 100644 index 0000000000..f9ff6454ad --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Euphoria/sorting-algorithms-bubble-sort.eu @@ -0,0 +1,27 @@ +function bubble_sort(sequence s) + object tmp + integer changed + for j = length(s) to 1 by -1 do + changed = 0 + for i = 1 to j-1 do + if compare(s[i], s[i+1]) > 0 then + tmp = s[i] + s[i] = s[i+1] + s[i+1] = tmp + changed = 1 + end if + end for + if not changed then + exit + end if + end for + return s +end function + +include misc.e +constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1} + +puts(1,"Before: ") +pretty_print(1,s,{2}) +puts(1,"\nAfter: ") +pretty_print(1,bubble_sort(s),{2}) diff --git a/Task/Sorting-algorithms-Bubble-sort/Haxe/sorting-algorithms-bubble-sort.hx b/Task/Sorting-algorithms-Bubble-sort/Haxe/sorting-algorithms-bubble-sort.hx new file mode 100644 index 0000000000..a07e52f9c1 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Haxe/sorting-algorithms-bubble-sort.hx @@ -0,0 +1,39 @@ +class BubbleSort { + @:generic + public static function sort(arr:Array) { + var madeChanges = false; + var itemCount = arr.length; + do { + madeChanges = false; + itemCount--; + for (i in 0...itemCount) { + if (Reflect.compare(arr[i], arr[i + 1]) > 0) { + var temp = arr[i + 1]; + arr[i + 1] = arr[i]; + arr[i] = temp; + madeChanges = true; + } + } + } while (madeChanges); + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + BubbleSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + BubbleSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + BubbleSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Pluto/sorting-algorithms-bubble-sort.pluto b/Task/Sorting-algorithms-Bubble-sort/Pluto/sorting-algorithms-bubble-sort.pluto new file mode 100644 index 0000000000..fa6f0ae152 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Pluto/sorting-algorithms-bubble-sort.pluto @@ -0,0 +1,21 @@ +local function bubble_sort(a) + local n = #a + if n < 2 then return end + repeat + local swapped = false + for i = 2, n do + if a[i-1] > a[i] then + a[i], a[i-1] = a[i - 1], a[i] + swapped = true + end + end + until !swapped +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + bubble_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.ps1 b/Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.ps1 new file mode 100644 index 0000000000..b9ab2c724d --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/PowerShell/sorting-algorithms-bubble-sort.ps1 @@ -0,0 +1,14 @@ +function bubblesort ($a) { + $l = $a.Length + $hasChanged = $true + while ($hasChanged) { + $hasChanged = $false + $l-- + for ($i = 0; $i -lt $l; $i++) { + if ($a[$i] -gt $a[$i+1]) { + $a[$i], $a[$i+1] = $a[$i+1], $a[$i] + $hasChanged = $true + } + } + } +} diff --git a/Task/Sorting-algorithms-Bubble-sort/RISC-V-Assembly/sorting-algorithms-bubble-sort.asm b/Task/Sorting-algorithms-Bubble-sort/RISC-V-Assembly/sorting-algorithms-bubble-sort.asm new file mode 100644 index 0000000000..38482fe790 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/RISC-V-Assembly/sorting-algorithms-bubble-sort.asm @@ -0,0 +1,194 @@ +# riscv assembly raspberry pico2 rp2350 +# program bubblesort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,11,1,4,10,6 +#tabNumber: .int 11,10,9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call bubbleSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* sort control */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* bubble sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the last element */ +bubbleSort: + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + addi t1,a1,1 +1: # start loop 1 + mv t0,a1 # start index + li t3,0 # top table sorted + addi t4,a2,-1 +2: # start loop 2 + addi t5,t0,1 + sh2add t6,t0,a0 + lw s0,(t6) + sh2add s1,t5,a0 + lw t2,(s1) + bge t2,s0,3f + sw t2,(t6) # swap value + sw s0,(s1) + li t3,1 # top table not sorted +3: + addi t0,t0,1 + ble t0,t4,2b # end ? no -> loop 2 + beqz t3,100f # table sorted ? -> end + addi a2,a2,-1 # decrement i + bge a2,t1,1b # end ? no -> loop 1 + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + addi sp, sp, 12 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vbs b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vbs new file mode 100644 index 0000000000..0d42fe27d6 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-1.vbs @@ -0,0 +1,31 @@ +sub decr( byref n ) + n = n - 1 +end sub + +sub incr( byref n ) + n = n + 1 +end sub + +sub swap( byref a, byref b) + dim tmp + tmp = a + a = b + b = tmp +end sub + +function bubbleSort( a ) + dim changed + dim itemCount + itemCount = ubound(a) + do + changed = false + decr itemCount + for i = 0 to itemCount + if a(i) > a(i+1) then + swap a(i), a(i+1) + changed = true + end if + next + loop until not changed + bubbleSort = a +end function diff --git a/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vbs b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vbs new file mode 100644 index 0000000000..20e2e5ac96 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/VBScript/sorting-algorithms-bubble-sort-2.vbs @@ -0,0 +1,5 @@ +dim a +a = array( "great eastern", "roe", "stirling", "albany", "leach") +wscript.echo join(a,", ") +bubbleSort a +wscript.echo join(a,", ") diff --git a/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Ada/sorting-algorithms-cocktail-sort-with-shifting-bounds.adb b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Ada/sorting-algorithms-cocktail-sort-with-shifting-bounds.adb new file mode 100644 index 0000000000..464ce3833f --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Ada/sorting-algorithms-cocktail-sort-with-shifting-bounds.adb @@ -0,0 +1,74 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Show_Cocktail_Sort is + generic + type T is private; + procedure Swap (A, B : in out T); + + procedure Swap (A, B : in out T) is + Tmp : constant T := A; + begin + A := B; + B := Tmp; + end Swap; + + generic + type T is private; + type Index is (<>); + type T_Array_Type is array (Index range <>) of T; + with function ">" (Left, Right : T) return Boolean; + procedure Cocktail_Sort (T_Array : in out T_Array_Type); + + procedure Cocktail_Sort (T_Array : in out T_Array_Type) is + procedure Swap_T is new Swap (T => T); + Low_Index : Index := T_Array'First; + High_Index : Index := Index'Pred (T_Array'Last); + New_Low_Index : Index; + New_High_Index : Index; + begin + while Low_Index <= High_Index loop + New_Low_Index := High_Index; + New_High_Index := Low_Index; + for I in Low_Index .. High_Index loop + if T_Array (I) > T_Array (Index'Succ (I)) then + Swap_T (T_Array (I), T_Array (Index'Succ (I))); + New_High_Index := I; + end if; + end loop; + High_Index := Index'Pred (New_High_Index); + for I in reverse Low_Index .. High_Index loop + if T_Array (I) > T_Array (Index'Succ (I)) then + Swap_T (T_Array (I), T_Array (Index'Succ (I))); + New_Low_Index := I; + end if; + end loop; + Low_Index := Index'Succ (New_Low_Index); + end loop; + end Cocktail_Sort; + + subtype Index is Positive range 1 .. 10; + type Positive_Array_Type is array (Positive range <>) of Positive; + Positive_Array : Positive_Array_Type (Index) := + (6, 10, 3, 1, 5, 8, 4, 9, 2, 7); + + procedure Print_Positive_Array is + begin + Put ("Example array:"); + for I in Index loop + Put (Positive'Image (Positive_Array (I))); + end loop; + New_Line; + end Print_Positive_Array; + + procedure Sort_Positive_Array is new + Cocktail_Sort + (T => Positive, + Index => Positive, + T_Array_Type => Positive_Array_Type, + ">" => Standard.">"); +begin + Print_Positive_Array; + Sort_Positive_Array (Positive_Array); + Put_Line ("Sorted"); + Print_Positive_Array; +end Show_Cocktail_Sort; diff --git a/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/EasyLang/sorting-algorithms-cocktail-sort-with-shifting-bounds.easy b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/EasyLang/sorting-algorithms-cocktail-sort-with-shifting-bounds.easy new file mode 100644 index 0000000000..7fb4ff6c04 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/EasyLang/sorting-algorithms-cocktail-sort-with-shifting-bounds.easy @@ -0,0 +1,25 @@ +proc cktlShakerSort &a[] . + a = 1 + b = len a[] - 1 + while a <= b + an = b + bn = a + for i = a to b + if a[i] > a[i + 1] + swap a[i] a[i + 1] + bn = i + . + . + b = bn - 1 + for i = b downto a + if a[i] > a[i + 1] + swap a[i] a[i + 1] + an = i + . + . + a = an + 1 + . +. +a[] = [ 4 38 100 1 25 69 69 16 8 59 71 53 33 ] +cktlShakerSort a[] +print a[] diff --git a/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Fortran/sorting-algorithms-cocktail-sort-with-shifting-bounds.f b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Fortran/sorting-algorithms-cocktail-sort-with-shifting-bounds.f new file mode 100644 index 0000000000..eac30fddaf --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Fortran/sorting-algorithms-cocktail-sort-with-shifting-bounds.f @@ -0,0 +1,104 @@ +program cocktail_sort_demo + implicit none + integer, parameter :: n = 12 + integer :: arr(n) + integer :: i +! + call system_clock(count=i) ! Get a value we can use as a seed + call srand(i) ! Set random number seed + do i = 1,n + arr(i) = irand(0) ! Fill with random integers + end do + print *, "Original array:" + print *, arr + + call cocktail_sort(arr, n) + + print *, "Sorted array:" + print *, arr + +contains + +!=========================================================== +! Subroutine: cocktail_sort +! Purpose : Sort an integer array using the Cocktail Sort +! algorithm (also known as bidirectional bubble sort). +! This algorithm repeatedly traverses the array in +! both directions, bubbling the largest element to +! the end and the smallest element to the beginning. +!=========================================================== +subroutine cocktail_sort(A, n) + ! Input: n = number of elements in the array + ! InOut: A = integer array to be sorted in ascending order + + integer, intent(in) :: n ! size of the array + integer, intent(inout) :: A(n) ! array to be sorted + integer :: beginIdx ! current left boundary of unsorted region + integer :: endIdx ! current right boundary of unsorted region + integer :: newBeginIdx ! updated left boundary after backward pass + integer :: newEndIdx ! updated right boundary after forward pass + integer :: i ! loop index + integer :: temp ! temporary variable for swapping + + ! Initialize boundaries: + ! beginIdx starts at the first element (index 1 in Fortran arrays). + ! endIdx starts at the last element (index n-1, since we compare A(i) with A(i+1)). + beginIdx = 1 + endIdx = n - 1 + + ! Outer loop: continue until the left boundary crosses the right boundary. + ! Each iteration performs one forward pass and one backward pass. + do while (beginIdx <= endIdx) + + ! Reset new boundaries for this iteration. + ! These will track the last swap positions to shrink the unsorted region. + newBeginIdx = endIdx + newEndIdx = beginIdx + + !--------------------------------------------------- + ! Forward pass: move left to right. + ! Compare each pair A(i), A(i+1) and swap if out of order. + ! This bubbles the largest element toward the right end. + !--------------------------------------------------- + do i = beginIdx, endIdx + if (A(i) > A(i+1)) then + ! Swap elements A(i) and A(i+1) + temp = A(i) + A(i) = A(i+1) + A(i+1) = temp + + ! Track the last index where a swap occurred. + ! This helps reduce the range for the next pass. + newEndIdx = i + end if + end do + + ! After forward pass, update right boundary. + ! Elements beyond newEndIdx are already in correct position. + endIdx = newEndIdx - 1 + + !--------------------------------------------------- + ! Backward pass: move right to left. + ! Compare each pair A(i), A(i+1) and swap if out of order. + ! This bubbles the smallest element toward the left end. + !--------------------------------------------------- + do i = endIdx, beginIdx, -1 + if (A(i) > A(i+1)) then + ! Swap elements A(i) and A(i+1) + temp = A(i) + A(i) = A(i+1) + A(i+1) = temp + + ! Track the last index where a swap occurred. + ! This helps reduce the range for the next pass. + newBeginIdx = i + end if + end do + + ! After backward pass, update left boundary. + ! Elements before newBeginIdx are already in correct position. + beginIdx = newBeginIdx + 1 + + end do +end subroutine cocktail_sort +end program cocktail_sort_demo diff --git a/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Pluto/sorting-algorithms-cocktail-sort-with-shifting-bounds.pluto b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Pluto/sorting-algorithms-cocktail-sort-with-shifting-bounds.pluto new file mode 100644 index 0000000000..506962b434 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/Pluto/sorting-algorithms-cocktail-sort-with-shifting-bounds.pluto @@ -0,0 +1,91 @@ +local fmt = require "fmt" + +-- Translation of pseudo-code. +local function cocktail_shaker_sort(a) + local start = 1 + local finish = #a - 1 + while start <= finish do + local newstart = finish + local newfinish = start + for i = start, finish do + if a[i] > a[i+1] then + a[i], a[i + 1] = a[i + 1], a[i] + newfinish = i + end + end + finish = newfinish - 1 + if finish >= start then + for i = finish, start, -1 do + if a[i] > a[i+1] then + a[i], a[i + 1] = a[i + 1], a[i] + newstart = i + end + end + end + start = newstart + 1 + end +end + +-- From the RC Cocktail sort task (no optimizations). +local function cocktail_sort(a) + local last = #a + while true do + local swapped = false + for i = 1, last - 1 do + if a[i] > a[i + 1] then + a[i], a[i + 1] = a[i + 1], a[i] + swapped = true + end + end + if !swapped then return end + swapped = false + if last >= 1 then + for i = last - 1, 1, -1 do + if a[i] > a[i + 1] then + a[i], a[i + 1] = a[i + 1], a[i] + swapped = true + end + end + end + if !swapped then return end + end +end + +-- First make sure the routines are working correctly. +local a = {21, 4, -9, 62, -7, 107, -62, 4, 0, -170} +fmt.print("Original array: %,s", a) +local b = a:clone() -- make copy as sorts mutate array in place +cocktail_sort(a) +fmt.print("Cocktail sort : %,s", a) +cocktail_shaker_sort(b) +fmt.print("C/Shaker sort : %,s", b) + +-- Timing comparison code. +print("\nRelative speed of the two sorts") +print(" N x faster (CSS v CS)") +print("----- -------------------") +local runs = 5 -- average over 5 runs say +for {1000, 2000, 4000, 8000, 10000, 20000} as n do + local sum = 0 + for i = 1, runs do + -- Get 'n' random numbers in range [0, 99,999] + -- with every other number being negated. + local nums = table.create(n) + for j = 1, n do + local rn = math.random(1, 99_999) + if j % 2 == 0 then rn = -rn end + nums[j] = rn + end + -- Copy the array + local nums2 = nums:clone() + + local start = os.clock() + cocktail_sort(nums) + local elapsed = os.clock() - start + local start2 = os.clock() + cocktail_shaker_sort(nums2) + local elapsed2 = os.clock() - start2 + sum += elapsed/elapsed2 + end + fmt.print(" %2dk %0.3f", n // 1000, sum / runs) +end diff --git a/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/VBScript/sorting-algorithms-cocktail-sort-with-shifting-bounds.vbs b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/VBScript/sorting-algorithms-cocktail-sort-with-shifting-bounds.vbs new file mode 100644 index 0000000000..db20c54f18 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort-with-shifting-bounds/VBScript/sorting-algorithms-cocktail-sort-with-shifting-bounds.vbs @@ -0,0 +1,31 @@ +' Sorting algorithms/Cocktail sort with shifting bounds - VBScript + +Function cocktailShakerSort(ByVal A) + beginIdx = Lbound(A) + endIdx = Ubound(A)-1 + Do While beginIdx <= endIdx + newBeginIdx = endIdx + newEndIdx = beginIdx + For ii = beginIdx To endIdx + If A(ii) > A(ii+1) Then + tmp=A(ii) : A(ii)=A(ii+1) : A(ii+1)=tmp + newEndIdx = ii + End If + Next + endIdx = newEndIdx - 1 + For ii = endIdx To beginIdx Step -1 + If A(ii) > A(ii+1) Then + tmp=A(ii) : A(ii)=A(ii+1) : A(ii+1)=tmp + newBeginIdx = ii + End If + Next + beginIdx = newBeginIdx+1 + Loop + cocktailShakerSort=A +End Function 'cocktailShakerSort + +Dim B(20) +For i=Lbound(B) To Ubound(B) + B(i)=Int(Rnd()*100) +Next +Wscript.Echo Join(cocktailShakerSort(B)," ") diff --git a/Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.adb b/Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.adb new file mode 100644 index 0000000000..bd33bcc41c --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Ada/sorting-algorithms-cocktail-sort.adb @@ -0,0 +1,37 @@ +with Ada.Text_Io; use Ada.Text_Io; + +procedure Cocktail_Sort_Test is + procedure Cocktail_Sort (Item : in out String) is + procedure Swap(Left, Right : in out Character) is + Temp : Character := Left; + begin + Left := Right; + Right := Temp; + end Swap; + Swapped : Boolean := False; + begin + loop + for I in 1..Item'Last - 1 loop + if Item(I) > Item(I + 1) then + Swap(Item(I), Item(I + 1)); + Swapped := True; + end if; + end loop; + if not Swapped then + for I in reverse 1..Item'Last - 1 loop + if Item(I) > Item(I + 1) then + Swap(Item(I), Item(I + 1)); + Swapped := True; + end if; + end loop; + end if; + exit when not Swapped; + Swapped := False; + end loop; + end Cocktail_Sort; + Data : String := "big fjords vex quick waltz nymph"; +begin + Put_Line(Data); + Cocktail_Sort(Data); + Put_Line(Data); +end Cocktail_Sort_Test; diff --git a/Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cob b/Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cob new file mode 100644 index 0000000000..2570807cb1 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/COBOL/sorting-algorithms-cocktail-sort.cob @@ -0,0 +1,38 @@ + C-SORT SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE 2 TO WC-START + MOVE WC-SIZE TO WC-END. + MOVE 1 TO WC-DIRECTION + WC-LAST-CHANGE. + PERFORM E-SHAKER UNTIL WC-END * WC-DIRECTION < + WC-START * WC-DIRECTION. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + E-SHAKER SECTION. + E-000. + PERFORM F-PASS VARYING WB-IX-1 FROM WC-START BY WC-DIRECTION + UNTIL WB-IX-1 = WC-END + WC-DIRECTION. + + MOVE WC-START TO WC-END. + SUBTRACT WC-DIRECTION FROM WC-LAST-CHANGE GIVING WC-START. + MULTIPLY WC-DIRECTION BY -1 GIVING WC-DIRECTION. + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + IF WB-ENTRY(WB-IX-1 - 1) > WB-ENTRY(WB-IX-1) + SET WC-LAST-CHANGE TO WB-IX-1 + MOVE WB-ENTRY(WB-IX-1 - 1) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WB-IX-1 - 1) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1). + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.eu b/Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.eu new file mode 100644 index 0000000000..4f66fcf1e2 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Euphoria/sorting-algorithms-cocktail-sort.eu @@ -0,0 +1,25 @@ +function cocktail_sort(sequence s) + integer swapped, d + object temp + sequence fromto + fromto = {1,length(s)-1} + swapped = 1 + d = 1 + while swapped do + swapped = 0 + for i = fromto[(1-d)/2+1] to fromto[(1+d)/2+1] by d do + if compare(s[i],s[i+1])>0 then + temp = s[i] + s[i] = s[i+1] + s[i+1] = temp + swapped = 1 + end if + end for + d = -d + end while + return s +end function + +constant s = rand(repeat(1000,10)) +? s +? cocktail_sort(s) diff --git a/Task/Sorting-algorithms-Cocktail-sort/Haxe/sorting-algorithms-cocktail-sort.hx b/Task/Sorting-algorithms-Cocktail-sort/Haxe/sorting-algorithms-cocktail-sort.hx new file mode 100644 index 0000000000..a3a2da92c6 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Haxe/sorting-algorithms-cocktail-sort.hx @@ -0,0 +1,49 @@ +class CocktailSort { + @:generic + public static function sort(arr:Array) { + var swapped = false; + do { + swapped = false; + for (i in 0...(arr.length - 1)) { + if (Reflect.compare(arr[i], arr[i + 1]) > 0) { + var temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + swapped = true; + } + } + if (!swapped) break; + swapped = false; + var i = arr.length - 2; + while (i >= 0) { + if (Reflect.compare(arr[i], arr[i + 1]) > 0) { + var temp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = temp; + swapped = true; + } + i--; + } + } while (swapped); + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + CocktailSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + CocktailSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + CocktailSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Pluto/sorting-algorithms-cocktail-sort.pluto b/Task/Sorting-algorithms-Cocktail-sort/Pluto/sorting-algorithms-cocktail-sort.pluto new file mode 100644 index 0000000000..9f48887684 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Pluto/sorting-algorithms-cocktail-sort.pluto @@ -0,0 +1,28 @@ +local function cocktail_sort(a) + local last = #a + while true do + local swapped = false + for i = 1, last - 1 do + if a[i] > a[i + 1] then + a[i], a[i + 1] = a[i + 1], a[i] + swapped = true + end + end + if !swapped then return end + swapped = false + if last >= 1 then + for i = last - 1, 1, -1 do + if a[i] > a[i + 1] then + a[i], a[i + 1] = a[i + 1], a[i] + swapped = true + end + end + end + if !swapped then return end + end +end + +local a = {170, 45, 75, -90, -802, 24, 2, 66} +print($"Before: \{{a:concat(", ")}}") +cocktail_sort(a) +print($"After : \{{a:concat(", ")}}") diff --git a/Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.ps1 b/Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.ps1 new file mode 100644 index 0000000000..85140cd374 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/PowerShell/sorting-algorithms-cocktail-sort.ps1 @@ -0,0 +1,32 @@ +function CocktailSort ($a) { + $l = $a.Length + $m = 0 + if( $l -gt 1 ) + { + $hasChanged = $true + :outer while ($hasChanged) { + $hasChanged = $false + $l-- + for ($i = $m; $i -lt $l; $i++) { + if ($a[$i] -gt $a[$i+1]) { + $a[$i], $a[$i+1] = $a[$i+1], $a[$i] + $hasChanged = $true + } + } + if(-not $hasChanged) { + break outer + } + $hasChanged = $false + for ($i = $l; $i -gt $m; $i--) { + if ($a[$i-1] -gt $a[$i]) { + $a[$i-1], $a[$i] = $a[$i], $a[$i-1] + $hasChanged = $true + } + } + $m++ + } + } + $a +} + +$l = 10; CocktailSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vbs b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vbs new file mode 100644 index 0000000000..738a59bf44 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-1.vbs @@ -0,0 +1,30 @@ +function cocktailSort( byval a ) + dim swapped + dim i + do + swapped = false + for i = 0 to ubound( a ) - 1 + if a(i) > a(i+1) then + swap a(i), a(i+1) + swapped = true + end if + next + if not swapped then exit do + swapped = false + for i = ubound( a ) - 1 to 0 step -1 + if a(i) > a( i+1) then + swap a(i), a(i+1) + swapped = true + end if + next + if not swapped then exit do + loop + cocktailSort = a +end function + +sub swap( byref a, byref b) + dim tmp + tmp = a + a = b + b = tmp +end sub diff --git a/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vbs b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vbs new file mode 100644 index 0000000000..f2e232b4ef --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/VBScript/sorting-algorithms-cocktail-sort-2.vbs @@ -0,0 +1,7 @@ +dim a +a = array( "portcullis", "redoubt", "palissade", "turret", "collins", "the parapet", "the quarterdeck") +wscript.echo join( a, ", ") + +dim b +b = cocktailSort( a ) +wscript.echo join( b, ", ") diff --git a/Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.adb b/Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.adb new file mode 100644 index 0000000000..36c60270b0 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Ada/sorting-algorithms-comb-sort.adb @@ -0,0 +1,47 @@ +with Ada.Text_IO; +procedure Comb_Sort is + generic + type Element_Type is private; + type Index_Type is range <>; + type Array_Type is array (Index_Type range <>) of Element_Type; + with function ">" (Left, Right : Element_Type) return Boolean is <>; + with function "+" (Left : Index_Type; Right : Natural) return Index_Type is <>; + with function "-" (Left : Index_Type; Right : Natural) return Index_Type is <>; + procedure Comb_Sort (Data: in out Array_Type); + + procedure Comb_Sort (Data: in out Array_Type) is + procedure Swap (Left, Right : in Index_Type) is + Temp : Element_Type := Data(Left); + begin + Data(Left) := Data(Right); + Data(Right) := Temp; + end Swap; + Gap : Natural := Data'Length; + Swap_Occured : Boolean; + begin + loop + Gap := Natural (Float(Gap) / 1.25 - 0.5); + if Gap < 1 then + Gap := 1; + end if; + Swap_Occured := False; + for I in Data'First .. Data'Last - Gap loop + if Data (I) > Data (I+Gap) then + Swap (I, I+Gap); + Swap_Occured := True; + end if; + end loop; + exit when Gap = 1 and not Swap_Occured; + end loop; + end Comb_Sort; + + type Integer_Array is array (Positive range <>) of Integer; + procedure Int_Comb_Sort is new Comb_Sort (Integer, Positive, Integer_Array); + Test_Array : Integer_Array := (1, 3, 256, 0, 3, 4, -1); +begin + Int_Comb_Sort (Test_Array); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + end loop; + Ada.Text_IO.New_Line; +end Comb_Sort; diff --git a/Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cob b/Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cob new file mode 100644 index 0000000000..73cd5b516b --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/COBOL/sorting-algorithms-comb-sort.cob @@ -0,0 +1,41 @@ + C-PROCESS SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE WC-SIZE TO WC-GAP. + + PERFORM E-COMB UNTIL WC-GAP = 1 AND FINISHED. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + E-COMB SECTION. + E-000. + IF WC-GAP > 1 + DIVIDE WC-GAP BY 1.3 GIVING WC-GAP + IF WC-GAP = 9 OR 10 + MOVE 11 TO WC-GAP. + + MOVE 1 TO WC-SUB-1. + MOVE "Y" TO WF-FINISHED. + + PERFORM F-SCAN UNTIL WC-SUB-1 + WC-GAP > WC-SIZE. + + E-999. + EXIT. + + F-SCAN SECTION. + F-000. + ADD WC-SUB-1 WC-GAP GIVING WC-SUB-2. + IF WB-ENTRY(WC-SUB-1) > WB-ENTRY(WC-SUB-2) + MOVE WB-ENTRY(WC-SUB-1) TO WC-TEMP + MOVE WB-ENTRY(WC-SUB-2) TO WB-ENTRY(WC-SUB-1) + MOVE WC-TEMP TO WB-ENTRY(WC-SUB-2) + MOVE "N" TO WF-FINISHED. + + ADD 1 TO WC-SUB-1. + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Comb-sort/Haxe/sorting-algorithms-comb-sort.hx b/Task/Sorting-algorithms-Comb-sort/Haxe/sorting-algorithms-comb-sort.hx new file mode 100644 index 0000000000..b396c03c4c --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Haxe/sorting-algorithms-comb-sort.hx @@ -0,0 +1,43 @@ +class CombSort { + @:generic + public static function sort(arr:Array) { + var gap:Float = arr.length; + var swaps = true; + while (gap > 1 || swaps) { + gap /= 1.247330950103979; + if (gap < 1) gap = 1.0; + var i = 0; + swaps = false; + while (i + gap < arr.length) { + var igap = i + Std.int(gap); + if (Reflect.compare(arr[i], arr[igap]) > 0) { + var temp = arr[i]; + arr[i] = arr[igap]; + arr[igap] = temp; + swaps = true; + } + i++; + } + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + CombSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + CombSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + CombSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Comb-sort/Pluto/sorting-algorithms-comb-sort.pluto b/Task/Sorting-algorithms-Comb-sort/Pluto/sorting-algorithms-comb-sort.pluto new file mode 100644 index 0000000000..3851a1c1b0 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Pluto/sorting-algorithms-comb-sort.pluto @@ -0,0 +1,26 @@ +local function comb_sort(a) + local gap = #a + while true do + gap //= 1.25 + if gap < 1 then gap = 1 end + local i = 1 + local swaps = false + while true do + if a[i] > a[i + gap] then + a[i], a[i + gap] = a[i + gap], a[i] + swaps = true + end + i += 1 + if i + gap > #a then break end + end + if gap == 1 and !swaps then return end + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + comb_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.ps1 b/Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.ps1 new file mode 100644 index 0000000000..11f8cd92b8 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/PowerShell/sorting-algorithms-comb-sort.ps1 @@ -0,0 +1,31 @@ +function CombSort ($a) { + $l = $a.Length + $gap = 11 + while( $gap -lt $l ) + { + $gap = [Math]::Floor( $gap*1.3 ) + } + if( $l -gt 1 ) + { + $hasChanged = $true + :outer while ($hasChanged -or ( $gap -gt 1 ) ) { + $count = 0 + $hasChanged = $false + if( $gap -gt 1 ) { + $gap = [Math]::Floor( $gap/1.3 ) + } else { + $l-- + } + for ($i = 0; $i -lt ( $l - $gap ); $i++) { + if ($a[$i] -gt $a[$i+$gap]) { + $a[$i], $a[$i+$gap] = $a[$i+$gap], $a[$i] + $hasChanged = $true + $count++ + } + } + } + } + $a +} + +$l = 100; CombSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.adb b/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.adb new file mode 100644 index 0000000000..c969d8080b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.adb @@ -0,0 +1,49 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; + +procedure Counting_Sort is + type Data is array (Integer range <>) of Natural; + procedure Sort(Item : in out Data) is + minValue, maxValue: Natural; + begin + minValue := Item(Item'First); maxValue := Item(Item'First); + for I in Item'Range loop + if Item(I) < minValue then minValue := Item(I); end if; + if Item(I) > maxValue then maxValue := Item(I); end if; + end loop; + declare + Count : Data(minValue .. maxValue); + itemPos : Integer range Item'First - 1 .. Item'Last; + begin + for I in Count'Range loop + Count(I) := 0; + end loop; + for I in Item'Range loop + Count(Item(I)) := Count(Item(I)) + 1; + end loop; + itemPos := 0; + for I in Count'Range loop + for J in 1..Count(I) loop + itemPos := itemPos + 1; + Item(itemPos) := I; + end loop; + end loop; + end; + end Sort; + Stuff : Data(1..30); + Seed : Generator; +begin + Put("Before: "); + for I in Stuff'Range loop + Stuff(I) := Integer( Float'Truncation( Random( seed ) * 100.0 ) ); + Put(Natural'Image(Stuff(I))); + end loop; + New_Line; + Sort(Stuff); + Put("After : "); + for I in Stuff'range loop + Put(Natural'Image(Stuff(I))); + end loop; + New_Line; +end Counting_Sort; diff --git a/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy b/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy index 6468fbe2dc..4cdad1f8ce 100644 --- a/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy +++ b/Task/Sorting-algorithms-Counting-sort/EasyLang/sorting-algorithms-counting-sort.easy @@ -10,8 +10,6 @@ proc countsort min max &d[] . . . . -for i = 1 to 100 - d[] &= random 1000 -. +for i = 1 to 50 : d[] &= random 0 999 countsort 1 1000 d[] print d[] diff --git a/Task/Sorting-algorithms-Counting-sort/Haxe/sorting-algorithms-counting-sort.hx b/Task/Sorting-algorithms-Counting-sort/Haxe/sorting-algorithms-counting-sort.hx new file mode 100644 index 0000000000..669947f246 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Haxe/sorting-algorithms-counting-sort.hx @@ -0,0 +1,33 @@ +class CountingSort { + public static function sort(arr:Array) { + var min = arr[0], max = arr[0]; + for (i in 1...arr.length) { + if (arr[i] < min) + min = arr[i]; + else if (arr[i] > max) + max = arr[i]; + } + + var range = max - min + 1; + var count = new Array(); + count.resize(range * arr.length); + + for (i in 0...range) count[i] = 0; + for (i in 0...arr.length) count[arr[i] - min]++; + + var z = 0; + for (i in min...(max + 1)) { + for (j in 0...count[i - min]) + arr[z++] = i; + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + Sys.println('Unsorted Integers: ' + integerArray); + CountingSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + } +} diff --git a/Task/Sorting-algorithms-Counting-sort/Maxima/sorting-algorithms-counting-sort.maxima b/Task/Sorting-algorithms-Counting-sort/Maxima/sorting-algorithms-counting-sort.maxima new file mode 100644 index 0000000000..0e5a378401 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Maxima/sorting-algorithms-counting-sort.maxima @@ -0,0 +1,19 @@ +counting_sort(list) := block( + low: lmin(list), high: lmax(list), + for i in list do(count[i]: 0), + for i in list do(count[i]: count[i]+1), + z: 1, + for i from low thru high do( + if numberp(count[i]) then while count[i]>0 do( + list[z]: i, + z: z+1, + count[i]: count[i]-1 + ) + ), + kill(count), + list +)$ + +test_list: makelist(random(10), 10); + +counting_sort(test_list); diff --git a/Task/Sorting-algorithms-Counting-sort/Pluto/sorting-algorithms-counting-sort.pluto b/Task/Sorting-algorithms-Counting-sort/Pluto/sorting-algorithms-counting-sort.pluto new file mode 100644 index 0000000000..053a4480b1 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Pluto/sorting-algorithms-counting-sort.pluto @@ -0,0 +1,19 @@ +require "table2" + +local function counting_sort(a, min, max) + local count = table.rep(max - min + 1, 0) + for a as n do count[n - min + 1] += 1 end + local z = 1 + for i = min, max do + while count[i - min + 1] > 0 do + a[z] = i + z += 1 + count[i - min + 1] -= 1 + end + end +end + +local a = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1} +print($"Unsorted: \{{a:concat(", ")}") +counting_sort(a, a:min(), a:max()) +print($"Sorted: \{{a:concat(", ")}") diff --git a/Task/Sorting-algorithms-Counting-sort/PowerShell/sorting-algorithms-counting-sort.ps1 b/Task/Sorting-algorithms-Counting-sort/PowerShell/sorting-algorithms-counting-sort.ps1 new file mode 100644 index 0000000000..3aed650f13 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/PowerShell/sorting-algorithms-counting-sort.ps1 @@ -0,0 +1,21 @@ +function countingSort($array) { + $minmax = $array | Measure-Object -Minimum -Maximum + $min, $max = $minmax.Minimum, $minmax.Maximum + $count = @(0) * ($max - $min + 1) + foreach ($number in $array) { + $count[$number - $min] = $count[$number - $min] + 1 + } + $z = 0 + foreach ($i in $min..$max) { + while (0 -lt $count[$i - $min]) { + $array[$z] = $i + $z = $z+1 + $count[$i - $min] = $count[$i - $min] - 1 + } + } + $array +} + +$array = foreach ($i in 1..50) {Get-Random -Minimum 0 -Maximum 26} +"$array" +"$(countingSort $array)" diff --git a/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vbs b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vbs new file mode 100644 index 0000000000..64fbb3f7ef --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-1.vbs @@ -0,0 +1,42 @@ +function findMax( a ) + dim num + dim max + max = 0 + for each num in a + if num > max then max = num + next + findMax = max +end function + +function findMin( a ) + dim num + dim min + min = 0 + for each num in a + if num < min then min = num + next + findMin = min +end function + +'the function returns the sorted array, but the fact is that VBScript passes the array by reference anyway +function countingSort( a ) + dim count() + dim min, max + min = findMin(a) + max = findMax(a) + redim count( max - min + 1 ) + dim i + dim z + for i = 0 to ubound( a ) + count( a(i) - min ) = count( a( i ) - min ) + 1 + next + z = 0 + for i = min to max + while count( i - min) > 0 + a(z) = i + z = z + 1 + count( i - min ) = count( i - min ) - 1 + wend + next + countingSort = a +end function diff --git a/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vbs b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vbs new file mode 100644 index 0000000000..0cfb7c0c15 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/VBScript/sorting-algorithms-counting-sort-2.vbs @@ -0,0 +1,5 @@ +dim a +a = array(300, 1, -2, 3, -4, 5, -6, 7, -8, 100, 11 ) +wscript.echo join( a, ", " ) +countingSort a +wscript.echo join( a, ", " ) diff --git a/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as b/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as index 29b9fa5799..ae8bd0a686 100644 --- a/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as +++ b/Task/Sorting-algorithms-Gnome-sort/ActionScript/sorting-algorithms-gnome-sort.as @@ -1,17 +1,17 @@ function gnomeSort(array:Array) { - var pos:uint = 0; - while(pos < array.length) - { - if(pos == 0 || array[pos] >= array[pos-1]) - pos++; - else - { - var tmp = array[pos]; - array[pos] = array[pos-1]; - array[pos-1] = tmp; - pos--; - } - } - return array; + var pos:uint = 0; + while(pos < array.length) + { + if(pos == 0 || array[pos] >= array[pos-1]) + pos++; + else + { + var tmp = array[pos]; + array[pos] = array[pos-1]; + array[pos-1] = tmp; + pos--; + } + } + return array; } diff --git a/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.adb b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.adb new file mode 100644 index 0000000000..67dd45795e --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-1.adb @@ -0,0 +1,6 @@ +generic + type Element_Type is private; + type Index is (<>); + type Collection is array(Index) of Element_Type; + with function "<=" (Left, Right : Element_Type) return Boolean is <>; +procedure Gnome_Sort(Item : in out Collection); diff --git a/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.adb b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.adb new file mode 100644 index 0000000000..17a41086e2 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-2.adb @@ -0,0 +1,25 @@ +procedure Gnome_Sort(Item : in out Collection) is + procedure Swap(Left, Right : in out Element_Type) is + Temp : Element_Type := Left; + begin + Left := Right; + Right := Temp; + end Swap; + + I : Integer := Index'Pos(Index'Succ(Index'First)); + J : Integer := I + 1; +begin + while I <= Index'Pos(Index'Last) loop + if Item(Index'Val(I - 1)) <= Item(Index'Val(I)) then + I := J; + J := J + 1; + else + Swap(Item(Index'Val(I - 1)), Item(Index'Val(I))); + I := I - 1; + if I = Index'Pos(Index'First) then + I := J; + J := J + 1; + end if; + end if; + end loop; +end Gnome_Sort; diff --git a/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.adb b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.adb new file mode 100644 index 0000000000..f0a95d6bdf --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Ada/sorting-algorithms-gnome-sort-3.adb @@ -0,0 +1,19 @@ +with Gnome_Sort; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Gnome_Sort_Test is + type Index is range 0..9; + type Buf is array(Index) of Integer; + procedure Sort is new Gnome_Sort(Integer, Index, Buf); + A : Buf := (900, 700, 800, 600, 400, 500, 200, 100, 300, 0); +begin + for I in A'range loop + Put(Integer'Image(A(I))); + end loop; + New_Line; + Sort(A); + for I in A'range loop + Put(Integer'Image(A(I))); + end loop; + New_Line; +end Gnome_Sort_Test; diff --git a/Task/Sorting-algorithms-Gnome-sort/BASIC256/sorting-algorithms-gnome-sort.basic b/Task/Sorting-algorithms-Gnome-sort/BASIC256/sorting-algorithms-gnome-sort.basic index fbb680e046..4c31e79f34 100644 --- a/Task/Sorting-algorithms-Gnome-sort/BASIC256/sorting-algorithms-gnome-sort.basic +++ b/Task/Sorting-algorithms-Gnome-sort/BASIC256/sorting-algorithms-gnome-sort.basic @@ -4,38 +4,38 @@ dim array(15) a = array[?,] b = array[?] for i = a to b - array[i] = int(rand * 100) + array[i] = int(rand * 100) next i print "unsort "; for i = a to b - print rjust(array[i], 4); + print rjust(array[i], 4); next i call gnomeSort(array) print chr(10); " sort "; for i = a to b - print rjust(array[i], 4); + print rjust(array[i], 4); next i end subroutine gnomeSort (array) - i = array[?,] + 1 - j = i + 1 - while i <= array[?] - if array[i - 1] <= array[i] then - i = j - j += 1 - else - temp = array[i - 1] - array[i - 1] = array[i] - array[i] = temp - i -= 1 - if i = array[?,] then - i = j - j += 1 - end if - end if - end while + i = array[?,] + 1 + j = i + 1 + while i <= array[?] + if array[i - 1] <= array[i] then + i = j + j += 1 + else + temp = array[i - 1] + array[i - 1] = array[i] + array[i] = temp + i -= 1 + if i = array[?,] then + i = j + j += 1 + end if + end if + end while end subroutine diff --git a/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat b/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat index edf095005f..be18772455 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat +++ b/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat @@ -9,8 +9,8 @@ SET /A tmpElements=%numElements% - 1 :: Create array of random numbers and output to file. ECHO GnomeSort Random Input 0 to %tmpElements%:>%~n0.txt FOR /L %%X IN (0, 1, %tmpElements%) DO ( - SET array[%%X]=!RANDOM! - ECHO !array[%%X]!>>%~n0.txt + SET array[%%X]=!RANDOM! + ECHO !array[%%X]!>>%~n0.txt ) :GnomeSort @@ -28,26 +28,26 @@ TITLE GnomeSort:[%gs1%][%gsTmp%] of %tmpElements% :: pseudo code supplied by Rosetta Code. I had to add an additional :: pointer to represent i-1, because of limitations in WinNT Batch. IF %gs2% LSS %numElements% ( - REM if i-1 <= i advance pointers to next unchecked element, then loop. - IF !array[%gs1%]! LEQ !array[%gs2%]! ( - SET /A gs1=%gs3% - 1 - SET /A gs2=%gs3% - SET /A gs3=%gs3% + 1 - ) ELSE ( - REM ... else swap i-1 and i, decrement pointers to check previous element, then loop. - SET gsTmp=!array[%gs1%]! - SET array[%gs1%]=!array[%gs2%]! - SET array[%gs2%]=!gsTmp! - SET /A gs1-=1 - SET /A gs2-=1 - REM if first element has been reached, set pointers to next unchecked element. - IF !gs2! EQU 0 ( - SET /A gs1=%gs3% - 1 - SET /A gs2=%gs3% - SET /A gs3=%gs3% + 1 - ) - ) - GOTO :GS_Loop + REM if i-1 <= i advance pointers to next unchecked element, then loop. + IF !array[%gs1%]! LEQ !array[%gs2%]! ( + SET /A gs1=%gs3% - 1 + SET /A gs2=%gs3% + SET /A gs3=%gs3% + 1 + ) ELSE ( + REM ... else swap i-1 and i, decrement pointers to check previous element, then loop. + SET gsTmp=!array[%gs1%]! + SET array[%gs1%]=!array[%gs2%]! + SET array[%gs2%]=!gsTmp! + SET /A gs1-=1 + SET /A gs2-=1 + REM if first element has been reached, set pointers to next unchecked element. + IF !gs2! EQU 0 ( + SET /A gs1=%gs3% - 1 + SET /A gs2=%gs3% + SET /A gs3=%gs3% + 1 + ) + ) + GOTO :GS_Loop ) TITLE GnomeSort:[%gs1%][%gsTmp%] - Done! diff --git a/Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cob b/Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cob new file mode 100644 index 0000000000..c81cf91821 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/COBOL/sorting-algorithms-gnome-sort.cob @@ -0,0 +1,30 @@ + C-SORT SECTION. + C-000. + DISPLAY "SORT STARTING". + + SET WB-IX-1 TO 2. + MOVE 1 TO WC-NEXT-POSN. + + PERFORM E-GNOME UNTIL WC-NEXT-POSN > WC-SIZE. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + E-GNOME SECTION. + E-000. + IF WB-ENTRY(WB-IX-1 - 1) NOT > WB-ENTRY(WB-IX-1) + ADD 1 TO WC-NEXT-POSN + SET WB-IX-1 TO WC-NEXT-POSN + ELSE + MOVE WB-ENTRY(WB-IX-1 - 1) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WB-IX-1 - 1) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1) + SET WB-IX-1 DOWN BY 1 + IF WB-IX-1 = 1 + ADD 1 TO WC-NEXT-POSN + SET WB-IX-1 TO WC-NEXT-POSN. + + E-999. + EXIT. diff --git a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e index 8ce12de4b6..da6913b261 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e +++ b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e @@ -1,63 +1,63 @@ class - GNOME_SORT [G -> COMPARABLE] + GNOME_SORT [G -> COMPARABLE] feature - sort (ar: ARRAY [G]): ARRAY [G] - -- Sorted array in ascending order. - require - array_not_void: ar /= Void - local - i, j: INTEGER - ith: G - do - create Result.make_empty - Result.deep_copy (ar) - from - i := 2 - j := 3 - until - i > Result.count - loop - if Result [i - 1] <= Result [i] then - i := j - j := j + 1 - else - ith := Result [i - 1] - Result [i - 1] := Result [i] - Result [i] := ith - i := i - 1 - if i = 1 then - i := j - j := j + 1 - end - end - end - ensure - Same_length: ar.count = Result.count - Result_is_sorted: is_sorted (Result) - end + sort (ar: ARRAY [G]): ARRAY [G] + -- Sorted array in ascending order. + require + array_not_void: ar /= Void + local + i, j: INTEGER + ith: G + do + create Result.make_empty + Result.deep_copy (ar) + from + i := 2 + j := 3 + until + i > Result.count + loop + if Result [i - 1] <= Result [i] then + i := j + j := j + 1 + else + ith := Result [i - 1] + Result [i - 1] := Result [i] + Result [i] := ith + i := i - 1 + if i = 1 then + i := j + j := j + 1 + end + end + end + ensure + Same_length: ar.count = Result.count + Result_is_sorted: is_sorted (Result) + end feature {NONE} - is_sorted (ar: ARRAY [G]): BOOLEAN - --- Is 'ar' sorted in ascending order? - require - ar_not_empty: ar.is_empty = False - local - i: INTEGER - do - Result := True - from - i := ar.lower - until - i = ar.upper - loop - if ar [i] > ar [i + 1] then - Result := False - end - i := i + 1 - end - end + is_sorted (ar: ARRAY [G]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end + end end diff --git a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e index bdb8fd203f..4408fa73e3 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e +++ b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e @@ -1,33 +1,33 @@ class - APPLICATION + APPLICATION create - make + make feature - make - do - test := <<7, 99, -7, 1, 0, 25, -10>> - io.put_string ("unsorted:%N") - across - test as ar - loop - io.put_string (ar.item.out + "%T") - end - io.new_line - io.put_string ("sorted:%N") - create gnome - test := gnome.sort (test) - across - test as ar - loop - io.put_string (ar.item.out + "%T") - end - end + make + do + test := <<7, 99, -7, 1, 0, 25, -10>> + io.put_string ("unsorted:%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + io.new_line + io.put_string ("sorted:%N") + create gnome + test := gnome.sort (test) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end - test: ARRAY [INTEGER] + test: ARRAY [INTEGER] - gnome: GNOME_SORT [INTEGER] + gnome: GNOME_SORT [INTEGER] end diff --git a/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl b/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl index 65797e854e..6483ea0fa7 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl +++ b/Task/Sorting-algorithms-Gnome-sort/Erlang/sorting-algorithms-gnome-sort-1.erl @@ -3,7 +3,7 @@ gnome(L, []) -> L; gnome([Prev|P], [Next|N]) when Next > Prev -> - gnome(P, [Next|[Prev|N]]); + gnome(P, [Next|[Prev|N]]); gnome(P, [Next|N]) -> - gnome([Next|P], N). + gnome([Next|P], N). gnome([H|T]) -> gnome([H], T). diff --git a/Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.eu b/Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.eu new file mode 100644 index 0000000000..17ddf7876a --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Euphoria/sorting-algorithms-gnome-sort.eu @@ -0,0 +1,22 @@ +function gnomeSort(sequence s) + integer i,j + object temp + i = 1 + j = 2 + while i < length(s) do + if compare(s[i], s[i+1]) <= 0 then + i = j + j += 1 + else + temp = s[i] + s[i] = s[i+1] + s[i+1] = temp + i -= 1 + if i = 0 then + i = j + j += 1 + end if + end if + end while + return s +end function diff --git a/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs b/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs index 16334bd5d1..2d4c8d7dbd 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs +++ b/Task/Sorting-algorithms-Gnome-sort/Haskell/sorting-algorithms-gnome-sort.hs @@ -1,9 +1,9 @@ gnomeSort [] = [] gnomeSort (x:xs) = gs [x] xs where - gs vv@(v:vs) (w:ws) - | v<=w = gs (w:vv) ws - | otherwise = gs vs (w:v:ws) - gs [] (y:ys) = gs [y] ys - gs xs [] = reverse xs + gs vv@(v:vs) (w:ws) + | v<=w = gs (w:vv) ws + | otherwise = gs vs (w:v:ws) + gs [] (y:ys) = gs [y] ys + gs xs [] = reverse xs -- keeping the first argument of gs in reverse order avoids the deterioration into cubic behaviour diff --git a/Task/Sorting-algorithms-Gnome-sort/Haxe/sorting-algorithms-gnome-sort.hx b/Task/Sorting-algorithms-Gnome-sort/Haxe/sorting-algorithms-gnome-sort.hx new file mode 100644 index 0000000000..180b2064ac --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Haxe/sorting-algorithms-gnome-sort.hx @@ -0,0 +1,39 @@ +class GnomeSort { + @:generic + public static function sort(arr:Array) { + var i = 1; + var j = 2; + while (i < arr.length) { + if (Reflect.compare(arr[i - 1], arr[i]) <= 0) { + i = j++; + } else { + var temp = arr[i]; + arr[i] = arr[i - 1]; + arr[i - 1] = temp; + if (--i == 0) { + i = j++; + } + } + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + GnomeSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + GnomeSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + GnomeSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max b/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max index 4a5c144f17..b9fa1cf3eb 100644 --- a/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max +++ b/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max @@ -1,24 +1,24 @@ fn gnomeSort arr = ( - local i = 2 - local j = 3 - while i <= arr.count do - ( - if arr[i-1] <= arr[i] then - ( - i = j - j += 1 - ) - else - ( - swap arr[i-1] arr[i] - i -= 1 - if i == 1 then - ( - i = j - j += 1 - ) - ) - ) - return arr + local i = 2 + local j = 3 + while i <= arr.count do + ( + if arr[i-1] <= arr[i] then + ( + i = j + j += 1 + ) + else + ( + swap arr[i-1] arr[i] + i -= 1 + if i == 1 then + ( + i = j + j += 1 + ) + ) + ) + return arr ) diff --git a/Task/Sorting-algorithms-Gnome-sort/Maple/sorting-algorithms-gnome-sort.maple b/Task/Sorting-algorithms-Gnome-sort/Maple/sorting-algorithms-gnome-sort.maple index cbc3ca9116..aeb6f40799 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Maple/sorting-algorithms-gnome-sort.maple +++ b/Task/Sorting-algorithms-Gnome-sort/Maple/sorting-algorithms-gnome-sort.maple @@ -2,13 +2,13 @@ arr := Array([17,3,72,0,36,2,3,8,40,0]): len := numelems(arr): i := 2: while (i <= len) do - if (i=1 or arr[i] >= arr[i-1]) then - i++: - else - temp:= arr[i]: - arr[i] := arr[i-1]: - arr[i-1] := temp: - i--: - end if: + if (i=1 or arr[i] >= arr[i-1]) then + i++: + else + temp:= arr[i]: + arr[i] := arr[i-1]: + arr[i-1] := temp: + i--: + end if: end do: arr; diff --git a/Task/Sorting-algorithms-Gnome-sort/MiniScript/sorting-algorithms-gnome-sort.mini b/Task/Sorting-algorithms-Gnome-sort/MiniScript/sorting-algorithms-gnome-sort.mini index 3a12650457..0dc6c76908 100644 --- a/Task/Sorting-algorithms-Gnome-sort/MiniScript/sorting-algorithms-gnome-sort.mini +++ b/Task/Sorting-algorithms-Gnome-sort/MiniScript/sorting-algorithms-gnome-sort.mini @@ -1,21 +1,21 @@ gnomesort = function(a) - i = 1 - j = 2 - while i < a.len - if a[i-1] <= a[i] then - i = j - j = j + 1 - else - k = a[i-1] - a[i-1] = a[i] - a[i] = k - i = i - 1 - if i == 0 then - i = j - j = j + 1 - end if - end if - end while + i = 1 + j = 2 + while i < a.len + if a[i-1] <= a[i] then + i = j + j = j + 1 + else + k = a[i-1] + a[i-1] = a[i] + a[i] = k + i = i - 1 + if i == 0 then + i = j + j = j + 1 + end if + end if + end while end function a = [3, 7, 4, 2, 5, 1, 6] gnomesort(a) diff --git a/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave b/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave index ea6e2489f7..84c1b6e992 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave +++ b/Task/Sorting-algorithms-Gnome-sort/Octave/sorting-algorithms-gnome-sort-1.octave @@ -10,8 +10,8 @@ function s = gnomesort(v) v(i) = t; i--; if ( i == 1 ) - i = j; - j++; + i = j; + j++; endif endif endwhile diff --git a/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php b/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php index aad8d19c92..881f372419 100644 --- a/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php +++ b/Task/Sorting-algorithms-Gnome-sort/PHP/sorting-algorithms-gnome-sort.php @@ -1,20 +1,20 @@ function gnomeSort($arr){ - $i = 1; - $j = 2; - while($i < count($arr)){ - if ($arr[$i-1] <= $arr[$i]){ - $i = $j; - $j++; - }else{ - list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); - $i--; - if($i == 0){ - $i = $j; - $j++; - } - } - } - return $arr; + $i = 1; + $j = 2; + while($i < count($arr)){ + if ($arr[$i-1] <= $arr[$i]){ + $i = $j; + $j++; + }else{ + list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); + $i--; + if($i == 0){ + $i = $j; + $j++; + } + } + } + return $arr; } $arr = array(3,1,6,2,9,4,7,8,5); echo implode(',',gnomeSort($arr)); diff --git a/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pas b/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pas index 03af33f9b8..5f1ae3eef7 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pas +++ b/Task/Sorting-algorithms-Gnome-sort/Pascal/sorting-algorithms-gnome-sort.pas @@ -1,24 +1,24 @@ procedure gnomesort(var arr : Array of Integer; size : Integer); var - i, j, t : Integer; + i, j, t : Integer; begin i := 1; j := 2; while i < size do begin if arr[i-1] <= arr[i] then begin - i := j; - j := j + 1 + i := j; + j := j + 1 end else begin - t := arr[i-1]; - arr[i-1] := arr[i]; - arr[i] := t; - i := i - 1; - if i = 0 then begin - i := j; - j := j + 1 - end + t := arr[i-1]; + arr[i-1] := arr[i]; + arr[i] := t; + i := i - 1; + if i = 0 then begin + i := j; + j := j + 1 + end end end; end; diff --git a/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl b/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl index 61f1b5d675..24a436b76b 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl +++ b/Task/Sorting-algorithms-Gnome-sort/Perl/sorting-algorithms-gnome-sort-1.pl @@ -8,17 +8,17 @@ sub gnome_sort my $i = 1; my $j = 2; while($i < $size) { - if ( $a[$i-1] <= $a[$i] ) { - $i = $j; - $j++; - } else { - @a[$i, $i-1] = @a[$i-1, $i]; - $i--; - if ($i == 0) { - $i = $j; - $j++; - } - } + if ( $a[$i-1] <= $a[$i] ) { + $i = $j; + $j++; + } else { + @a[$i, $i-1] = @a[$i-1, $i]; + $i--; + if ($i == 0) { + $i = $j; + $j++; + } + } } return @a; } diff --git a/Task/Sorting-algorithms-Gnome-sort/Pluto/sorting-algorithms-gnome-sort.pluto b/Task/Sorting-algorithms-Gnome-sort/Pluto/sorting-algorithms-gnome-sort.pluto new file mode 100644 index 0000000000..bd48763c44 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Pluto/sorting-algorithms-gnome-sort.pluto @@ -0,0 +1,30 @@ +local function gnome_sort(a, asc) + local size = #a + local i = 2 + local j = 3 + while i <= size do + if (asc and a[i - 1] <= a[i]) or (!asc and a[i - 1] >= a[i]) then + i = j + j += 1 + else + a[i], a[i - 1] = a[i - 1], a[i] + i -= 1 + if i == 1 then + i = j + j += 1 + end + end + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for {true, false} as asc do + print($"Sorting in {asc ? "ascending" : "descending"} order:\n") + for array as a do + local b = asc ? a : (a:clone()) + print($"Before: \{{b:concat(", ")}}") + gnome_sort(b, asc) + print($"After : \{{b:concat(", ")}}") + print() + end +end diff --git a/Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.ps1 b/Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.ps1 new file mode 100644 index 0000000000..590eb7ff12 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.ps1 @@ -0,0 +1,20 @@ +function gnomesort($a) { + $size, $i, $j = $a.Count, 1, 2 + while($i -lt $size) { + if ($a[$i-1] -le $a[$i]) { + $i = $j + $j++ + } + else { + $a[$i-1], $a[$i] = $a[$i], $a[$i-1] + $i-- + if($i -eq 0) { + $i = $j + $j++ + } + } + } + $a +} +$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) +"$(gnomesort $array)" diff --git a/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py b/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py index accd86a4b7..fac771d273 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py +++ b/Task/Sorting-algorithms-Gnome-sort/Python/sorting-algorithms-gnome-sort.py @@ -1,14 +1,14 @@ >>> def gnomesort(a): - i,j,size = 1,2,len(a) - while i < size: - if a[i-1] <= a[i]: - i,j = j, j+1 - else: - a[i-1],a[i] = a[i],a[i-1] - i -= 1 - if i == 0: - i,j = j, j+1 - return a + i,j,size = 1,2,len(a) + while i < size: + if a[i-1] <= a[i]: + i,j = j, j+1 + else: + a[i-1],a[i] = a[i],a[i-1] + i -= 1 + if i == 0: + i,j = j, j+1 + return a >>> gnomesort([3,4,2,5,1,6]) [1, 2, 3, 4, 5, 6] diff --git a/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal b/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal index c63813d26d..d36a71f9cf 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal +++ b/Task/Sorting-algorithms-Gnome-sort/Rascal/sorting-algorithms-gnome-sort-1.rascal @@ -1,19 +1,19 @@ import List; public list[int] gnomeSort(a){ - i = 1; - j = 2; - while(i < size(a)){ - if(a[i-1] <= a[i]){ - i = j; - j += 1;} - else{ - temp = a[i-1]; - a[i-1] = a[i]; - a[i] = temp; - i = i - 1; - if(i == 0){ - i = j; - j += 1;}}} - return a; + i = 1; + j = 2; + while(i < size(a)){ + if(a[i-1] <= a[i]){ + i = j; + j += 1;} + else{ + temp = a[i-1]; + a[i-1] = a[i]; + a[i] = temp; + i = i - 1; + if(i == 0){ + i = j; + j += 1;}}} + return a; } diff --git a/Task/Sorting-algorithms-Gnome-sort/Rebol/sorting-algorithms-gnome-sort.rebol b/Task/Sorting-algorithms-Gnome-sort/Rebol/sorting-algorithms-gnome-sort.rebol new file mode 100644 index 0000000000..3063f77799 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Rebol/sorting-algorithms-gnome-sort.rebol @@ -0,0 +1,25 @@ +Rebol [ + title: "Rosetta code: Sorting algorithms/Gnome sort" + file: %Sorting_algorithms-Gnome_sort.r3 + url: https://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort +] + +gnome-sort: function [ + "In-place gnome sort: steps forward when order is correct, swaps and steps back when not" + items [series!] +][ + n: length? items + i: 2 ;; start at second element, comparing i-1 and i + while [i <= n][ + either items/(i - 1) <= items/:i [ ;; pair is in order + ++ i ;; advance + ][ ;; pair is out of order + swap at items (i - 1) at items i ;; swap + if i > 2 [-- i] ;; and step back if not already at start + ] + ] + items +] + +probe gnome-sort [3 1 2 8 5 7 9 4 6] +probe gnome-sort "Hello Gnome" diff --git a/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vbs b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vbs new file mode 100644 index 0000000000..85bc22d5e2 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-1.vbs @@ -0,0 +1,27 @@ +function gnomeSort( a ) + dim i + dim j + i = 1 + j = 2 + do while i < ubound( a ) + 1 + if a(i-1) <= a(i) then + i = j + j = j + 1 + else + swap a(i-1), a(i) + i = i - 1 + if i = 0 then + i = j + j = j + 1 + end if + end if + loop + gnomeSort = a +end function + +sub swap( byref x, byref y ) + dim temp + temp = x + x = y + y = temp +end sub diff --git a/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vbs b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vbs new file mode 100644 index 0000000000..85d3386c21 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-2.vbs @@ -0,0 +1,22 @@ +dim a +dim b + +a = array( "zanzibar", "aardvark","ampicillin","zulu","gogodala", "wolverhampton") +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( 234,567,345,568,2345,89,547,23,649,5769,456,456,567) +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( true, false, true, true, false, false, true, false) +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( 1,2,2,4,67789,-3,-45.99) +b = gnomeSort( a ) +wscript.echo join(a, ", ") + +a = array( now(), now()-1,now()+2) +b = gnomeSort( a ) +wscript.echo join(a, ", ") diff --git a/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vbs b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vbs new file mode 100644 index 0000000000..fd68203cfb --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/VBScript/sorting-algorithms-gnome-sort-3.vbs @@ -0,0 +1,5 @@ +aardvark, ampicillin, gogodala, wolverhampton, zanzibar, zulu +23, 89, 234, 345, 456, 456, 547, 567, 567, 568, 649, 2345, 5769 +True, True, True, True, False, False, False, False +-45.99, -3, 1, 2, 2, 4, 67789 +2/02/2010 10:19:51 AM, 3/02/2010 10:19:51 AM, 5/02/2010 10:19:51 AM diff --git a/Task/Sorting-algorithms-Gnome-sort/Yabasic/sorting-algorithms-gnome-sort.basic b/Task/Sorting-algorithms-Gnome-sort/Yabasic/sorting-algorithms-gnome-sort.basic index 41c9ad059e..4488eb14b6 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Yabasic/sorting-algorithms-gnome-sort.basic +++ b/Task/Sorting-algorithms-Gnome-sort/Yabasic/sorting-algorithms-gnome-sort.basic @@ -19,24 +19,24 @@ end sub gnomeSort(array()) local ub, ul, i, j, temp - - lb = 0 : ub = arraysize(array(),1) - i = lb +1 : j = lb +2 - while i <= ub - // replace "<=" with ">=" for downwards sort - if array(i -1) <= array(i) then - i = j - j = j + 1 - else - temp = array(i -1) - array(i -1) = array(i) - array(i) = temp - i = i - 1 - if i = lb then - i = j - j = j + 1 - fi - fi - wend + lb = 0 : ub = arraysize(array(),1) + i = lb +1 : j = lb +2 + + while i <= ub + // replace "<=" with ">=" for downwards sort + if array(i -1) <= array(i) then + i = j + j = j + 1 + else + temp = array(i -1) + array(i -1) = array(i) + array(i) = temp + i = i - 1 + if i = lb then + i = j + j = j + 1 + fi + fi + wend end sub diff --git a/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl b/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl index 63cc17f0a6..3b87a6b190 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl +++ b/Task/Sorting-algorithms-Gnome-sort/Zkl/sorting-algorithms-gnome-sort-1.zkl @@ -2,9 +2,9 @@ fcn gnomeSort(a){ i,j,size := 1,2,a.len(); while(i < size){ if(a[i-1] > a[i]){ // for descending sort, use < for comparison - a.swap(i-1,i); - i = i - 1; - if(i) continue; + a.swap(i-1,i); + i = i - 1; + if(i) continue; } i = j; j = j + 1; diff --git a/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.adb b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.adb new file mode 100644 index 0000000000..4812e25a02 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-1.adb @@ -0,0 +1,6 @@ +generic + type Element_Type is private; + type Index_Type is (<>); + type Collection is array(Index_Type range <>) of Element_Type; + with function "<" (Left, right : element_type) return boolean is <>; +procedure Generic_Heapsort(Item : in out Collection); diff --git a/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.adb b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.adb new file mode 100644 index 0000000000..a2e5bf62df --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-2.adb @@ -0,0 +1,50 @@ +procedure Generic_Heapsort(Item : in out Collection) is + procedure Swap(Left : in out Element_Type; Right : in out Element_Type) is + Temp : Element_Type := Left; + begin + Left := Right; + Right := Temp; + end Swap; + procedure Sift_Down(Item : in out Collection) is + Root : Integer := Index_Type'Pos(Item'First); + Child : Integer := Index_Type'Pos(Item'Last); + Last : Integer := Index_Type'Pos(Item'Last); + begin + while Root * 2 + 1 <= Last loop + Child := Root * 2 + 1; + if Child + 1 <= Last and then Item(index_Type'Val(Child)) < Item(Index_Type'Val(Child + 1)) then + Child := Child + 1; + end if; + if Item(Index_Type'Val(Root)) < Item(Index_Type'Val(Child)) then + Swap(Item(Index_Type'Val(Root)), Item(Index_Type'Val(Child))); + Root := Child; + else + exit; + end if; + end loop; + end Sift_Down; + + procedure Heapify(Item : in out Collection) is + First_Pos : Integer := Index_Type'Pos(Index_Type'First); + Last_Pos : Integer := Index_Type'Pos(Index_type'Last); + Start : Index_type := Index_Type'Val((Last_Pos - First_Pos + 1) / 2); + begin + loop + Sift_Down(Item(Start..Item'Last)); + if Start > Index_Type'First then + Start := Index_Type'Pred(Start); + else + exit; + end if; + end loop; + end Heapify; + Last_Index : Index_Type := Index_Type'Last; +begin + Heapify(Item); + while Last_Index > Index_Type'First loop + Swap(Item(Last_Index), Item(Item'First)); + Last_Index := Index_Type'Pred(Last_Index); + Sift_Down(Item(Item'First..Last_Index)); + end loop; + +end Generic_Heapsort; diff --git a/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.adb b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.adb new file mode 100644 index 0000000000..33ab0c550c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Ada/sorting-algorithms-heapsort-3.adb @@ -0,0 +1,19 @@ +with Generic_Heapsort; +with Ada.Text_Io; use Ada.Text_Io; + +procedure Test_Generic_Heapsort is + type Days is (Sun, Mon, Tue, Wed, Thu, Fri, Sat); + type Days_Col is array(Days range <>) of Natural; + procedure Sort is new Generic_Heapsort(Natural, Days, Days_Col); + Week : Days_Col := (5, 2, 7, 3, 4, 9, 1); +begin + for I in Week'range loop + Put(Days'Image(I) & ":" & Natural'Image(Week(I)) & " "); + end loop; + New_Line; + Sort(Week); + for I in Week'range loop + Put(Days'Image(I) & ":" & Natural'Image(Week(I))& " "); + end loop; + New_Line; +end Test_Generic_Heapsort; diff --git a/Task/Sorting-algorithms-Heapsort/COBOL/sorting-algorithms-heapsort.cob b/Task/Sorting-algorithms-Heapsort/COBOL/sorting-algorithms-heapsort.cob new file mode 100644 index 0000000000..7969acbbb5 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/COBOL/sorting-algorithms-heapsort.cob @@ -0,0 +1,81 @@ + >>SOURCE FORMAT FREE +*> This code is dedicated to the public domain +*> This is GNUCOBOL 2.0 +identification division. +program-id. heapsort. +environment division. +configuration section. +repository. function all intrinsic. +data division. +working-storage section. +01 filler. + 03 a pic 99. + 03 a-start pic 99. + 03 a-end pic 99. + 03 a-parent pic 99. + 03 a-child pic 99. + 03 a-sibling pic 99. + 03 a-lim pic 99 value 10. + 03 array-swap pic 99. + 03 array occurs 10 pic 99. +procedure division. +start-heapsort. + + *> fill the array + compute a = random(seconds-past-midnight) + perform varying a from 1 by 1 until a > a-lim + compute array(a) = random() * 100 + end-perform + + perform display-array + display space 'initial array' + + *>heapify the array + move a-lim to a-end + compute a-start = (a-lim + 1) / 2 + perform sift-down varying a-start from a-start by -1 until a-start = 0 + + perform display-array + display space 'heapified' + + *> sort the array + move 1 to a-start + move a-lim to a-end + perform until a-end = a-start + move array(a-end) to array-swap + move array(a-start) to array(a-end) + move array-swap to array(a-start) + subtract 1 from a-end + perform sift-down + end-perform + + perform display-array + display space 'sorted' + + stop run + . +sift-down. + move a-start to a-parent + perform until a-parent * 2 > a-end + compute a-child = a-parent * 2 + compute a-sibling = a-child + 1 + if a-sibling <= a-end and array(a-child) < array(a-sibling) + *> take the greater of the two + move a-sibling to a-child + end-if + if a-child <= a-end and array(a-parent) < array(a-child) + *> the child is greater than the parent + move array(a-child) to array-swap + move array(a-parent) to array(a-child) + move array-swap to array(a-parent) + end-if + *> continue down the tree + move a-child to a-parent + end-perform + . +display-array. + perform varying a from 1 by 1 until a > a-lim + display space array(a) with no advancing + end-perform + . +end program heapsort. diff --git a/Task/Sorting-algorithms-Heapsort/Haxe/sorting-algorithms-heapsort.hx b/Task/Sorting-algorithms-Heapsort/Haxe/sorting-algorithms-heapsort.hx new file mode 100644 index 0000000000..984d9e79f7 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Haxe/sorting-algorithms-heapsort.hx @@ -0,0 +1,60 @@ +class HeapSort { + @:generic + private static function siftDown(arr: Array, start:Int, end:Int) { + var root = start; + while (root * 2 + 1 <= end) { + var child = root * 2 + 1; + if (child + 1 <= end && Reflect.compare(arr[child], arr[child + 1]) < 0) + child++; + if (Reflect.compare(arr[root], arr[child]) < 0) { + var temp = arr[root]; + arr[root] = arr[child]; + arr[child] = temp; + root = child; + } else { + break; + } + } + } + + @:generic + public static function sort(arr:Array) { + if (arr.length > 1) + { + var start = (arr.length - 2) >> 1; + while (start > 0) { + siftDown(arr, start - 1, arr.length - 1); + start--; + } + } + + var end = arr.length - 1; + while (end > 0) { + var temp = arr[end]; + arr[end] = arr[0]; + arr[0] = temp; + siftDown(arr, 0, end - 1); + end--; + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + HeapSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + HeapSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + HeapSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Heapsort/Pluto/sorting-algorithms-heapsort.pluto b/Task/Sorting-algorithms-Heapsort/Pluto/sorting-algorithms-heapsort.pluto new file mode 100644 index 0000000000..e5b51082d0 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Pluto/sorting-algorithms-heapsort.pluto @@ -0,0 +1,39 @@ +local function sift_down(a, start, last) + local root = start + while root * 2 <= last do + local child = root * 2 + if child < last and a[child] < a[child + 1] then child += 1 end + if a[root] < a[child] then + a[root], a[child] = a[child], a[root] + root = child + else + return + end + end +end + +local function heapify(a, count) + local start = count // 2 + while start > 0 do + sift_down(a, start, count) + start -= 1 + end +end + +local function heap_sort(a) + local last = #a + heapify(a, last) + while last > 1 do + a[1], a[last] = a[last], a[1] + last -= 1 + sift_down(a, 1, last) + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + heap_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.ps1 b/Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.ps1 new file mode 100644 index 0000000000..2128561424 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.ps1 @@ -0,0 +1,35 @@ +function heapsort($a, $count) { + $a = heapify $a $count + $end = $count - 1 + while( $end -gt 0) { + $a[$end], $a[0] = $a[0], $a[$end] + $end-- + $a = siftDown $a 0 $end + } + $a +} +function heapify($a, $count) { + $start = [Math]::Floor(($count - 2) / 2) + while($start -ge 0) { + $a = siftDown $a $start ($count-1) + $start-- + } + $a +} +function siftdown($a, $start, $end) { + $b, $root = $true, $start + while(( ($root * 2 + 1) -le $end) -and $b) { + $child = $root * 2 + 1 + if( ($child + 1 -le $end) -and ($a[$child] -lt $a[$child + 1]) ) { + $child++ + } + if($a[$root] -lt $a[$child]) { + $a[$root], $a[$child] = $a[$child], $a[$root] + $root = $child + } + else { $b = $false} + } + $a +} +$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) +"$(heapsort $array $array.Count)" diff --git a/Task/Sorting-algorithms-Heapsort/RISC-V-Assembly/sorting-algorithms-heapsort.asm b/Task/Sorting-algorithms-Heapsort/RISC-V-Assembly/sorting-algorithms-heapsort.asm new file mode 100644 index 0000000000..080b54d8cb --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/RISC-V-Assembly/sorting-algorithms-heapsort.asm @@ -0,0 +1,268 @@ +# riscv assembly raspberry pico2 rp2350 +# program heapsort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +#tabNumber: .int 9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,NBTABNUMBER + li s2,0 +2: # item loop + sh2add t3,s2,s0 # compute item address + lw a0,(t3) + call displayResultD + add s2,s2,1 + blt s2,s1,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # array address + mv a1,s1 # array size + call heapSort # sort + mv a0,s0 # number array address + mv a1,s1 # array size + call isSorted + + la a0,szLibSort + call writeString + + li s2,0 +3: # item loop + sh2add t3,s2,s0 # compute item address + lw a0,(t3) + call displayResultD + add s2,s2,1 + blt s2,s1,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* sort control */ +/**********************************************/ +/* a0 array address */ +/* a1 array size */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + li t0,0 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + blt t0,a1,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* merge sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains array size */ +heapSort: + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + mv s0,a1 + addi s0,s0,-1 # last element + call heapify # first place table in max-heap order +1: + blez s0,100f + li a1,0 # + mv a2,s0 + call swapElement + addi s0,s0,-1 # decrement indice + li a1,0 # + mv a2,s0 + call siftDown + j 1b + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* place array in max-heap order */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 element number */ + +heapify: # INFO: heapify + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + mv s0,a1 # init + addi t1,a1,-2 + srli s1,t1,1 # / by 2 +1: + bltz s1,100f + mv a1,s1 + addi a2,s0,-1 + call siftDown + addi s1,s1,-1 + j 1b + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + addi sp, sp, 12 + ret + +/******************************************************************/ +/* put the heap back in max-heap order */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first index */ +/* a2 contains the last index */ +siftDown: # INFO: siftDown + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + mv s1,a2 # init +1: + slli s0,a1,1 + addi s0,s0,1 + bgt s0,s1,100f + addi t1,s0,1 + bgt t1,s1,2f + sh2add t2,s0,a0 + lw t3,(t2) + sh2add t2,t1,a0 + lw t4,(t2) + bge t3,t4,2f + mv s0,t1 +2: + sh2add t2,s0,a0 # compare elements on the table + lw t3,(t2) + sh2add t2,a1,a0 # root + lw t4,(t2) + bge t4,t3,100f + mv a2,s0 + call swapElement + mv a1,s0 # root = child + j 1b + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + addi sp, sp, 12 + ret +/******************************************************************/ +/* swap values in array */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 first indice */ +/* a2 second indice */ +swapElement: # INFO: swapElement + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + sh2add t0,a1,a0 + lw t1,(t0) + sh2add t2,a2,a0 + lw t3,(t2) # swap values + sw t3,(t0) + sw t1,(t2) +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.adb b/Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.adb new file mode 100644 index 0000000000..c3237f2ce6 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Ada/sorting-algorithms-insertion-sort.adb @@ -0,0 +1,18 @@ +type Data_Array is array(Natural range <>) of Integer; + +procedure Insertion_Sort(Item : in out Data_Array) is + First : Natural := Item'First; + Last : Natural := Item'Last; + Value : Integer; + J : Integer; +begin + for I in (First + 1)..Last loop + Value := Item(I); + J := I - 1; + while J in Item'range and then Item(J) > Value loop + Item(J + 1) := Item(J); + J := J - 1; + end loop; + Item(J + 1) := Value; + end loop; +end Insertion_Sort; diff --git a/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-1.cob b/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-1.cob new file mode 100644 index 0000000000..5be2a4c227 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-1.cob @@ -0,0 +1,27 @@ + C-PROCESS SECTION. + PERFORM E-INSERTION VARYING WB-IX-1 FROM 1 BY 1 + UNTIL WB-IX-1 > WC-SIZE. + +... + + E-INSERTION SECTION. + E-000. + MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP. + SET WB-IX-2 TO WB-IX-1. + + PERFORM F-PASS UNTIL WB-IX-2 NOT > 1 OR + WC-TEMP NOT < WB-ENTRY(WB-IX-2 - 1). + + IF WB-IX-1 NOT = WB-IX-2 + MOVE WC-TEMP TO WB-ENTRY(WB-IX-2). + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + MOVE WB-ENTRY(WB-IX-2 - 1) TO WB-ENTRY(WB-IX-2). + SET WB-IX-2 DOWN BY 1. + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-2.cob b/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-2.cob new file mode 100644 index 0000000000..ab1eecd2df --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/COBOL/sorting-algorithms-insertion-sort-2.cob @@ -0,0 +1,70 @@ + >>SOURCE FORMAT FREE +*> This code is dedicated to the public domain +*> This is GNUCOBOL 2.0 +identification division. +program-id. insertionsort. +environment division. +configuration section. +repository. function all intrinsic. +data division. +working-storage section. +01 filler. + 03 a pic 99. + 03 a-lim pic 99 value 10. + 03 array occurs 10 pic 99. + +01 filler. + 03 s pic 99. + 03 o pic 99. + 03 o1 pic 99. + 03 sorted-len pic 99. + 03 sorted-lim pic 99 value 10. + 03 sorted-array occurs 10 pic 99. + +procedure division. +start-insertionsort. + + *> fill the array + compute a = random(seconds-past-midnight) + perform varying a from 1 by 1 until a > a-lim + compute array(a) = random() * 100 + end-perform + + *> display the array + perform varying a from 1 by 1 until a > a-lim + display space array(a) with no advancing + end-perform + display space 'initial array' + + *> sort the array + move 0 to sorted-len + perform varying a from 1 by 1 until a > a-lim + *> find the insertion point + perform varying s from 1 by 1 + until s > sorted-len + or array(a) <= sorted-array(s) + continue + end-perform + + *>open the insertion point + perform varying o from sorted-len by -1 + until o < s + compute o1 = o + 1 + move sorted-array(o) to sorted-array(o1) + end-perform + + *> move the array-entry to the insertion point + move array(a) to sorted-array(s) + + add 1 to sorted-len + end-perform + + *> display the sorted array + perform varying s from 1 by 1 until s > sorted-lim + display space sorted-array(s) with no advancing + end-perform + display space 'sorted array' + + stop run + . +end program insertionsort. diff --git a/Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.el b/Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.el new file mode 100644 index 0000000000..1d63650f0b --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Emacs-Lisp/sorting-algorithms-insertion-sort.el @@ -0,0 +1,30 @@ +(defun min-or-max-of-a-list (numbers comparator) + "Return minimum or maximum of NUMBERS using COMPARATOR." + (let ((extremum (car numbers))) + (dolist (n (cdr numbers)) + (when (funcall comparator n extremum) + (setq extremum n))) + extremum)) + +(defun remove-number-from-list (numbers n) + "Return NUMBERS without N. +If n is present twice or more, it will be removed only once." + (let (result) + (while numbers + (let ((number (pop numbers))) + (if (= number n) + (while numbers + (push (pop numbers) result)) + (push number result)))) + (nreverse result))) + +(defun insertion-sort (numbers comparator) + "Return sorted list of NUMBERS using COMPARATOR." + (if numbers + (let ((extremum (min-or-max-of-a-list numbers comparator))) + (cons extremum + (insertion-sort (remove-number-from-list numbers extremum) + comparator))) + nil)) + +(insertion-sort '(1 2 3 9 8 7 25 12 3 2 1) #'>) diff --git a/Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.eu b/Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.eu new file mode 100644 index 0000000000..33f8e96f1e --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Euphoria/sorting-algorithms-insertion-sort.eu @@ -0,0 +1,22 @@ +function insertion_sort(sequence s) + object temp + integer j + for i = 2 to length(s) do + temp = s[i] + j = i-1 + while j >= 1 and compare(s[j],temp) > 0 do + s[j+1] = s[j] + j -= 1 + end while + s[j+1] = temp + end for + return s +end function + +include misc.e +constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1} + +puts(1,"Before: ") +pretty_print(1,s,{2}) +puts(1,"\nAfter: ") +pretty_print(1,insertion_sort(s),{2}) diff --git a/Task/Sorting-algorithms-Insertion-sort/Haxe/sorting-algorithms-insertion-sort.hx b/Task/Sorting-algorithms-Insertion-sort/Haxe/sorting-algorithms-insertion-sort.hx new file mode 100644 index 0000000000..98f1de5978 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Haxe/sorting-algorithms-insertion-sort.hx @@ -0,0 +1,33 @@ +class InsertionSort { + @:generic + public static function sort(arr:Array) { + for (i in 1...arr.length) { + var value = arr[i]; + var j = i - 1; + while (j >= 0 && Reflect.compare(arr[j], value) > 0) { + arr[j + 1] = arr[j--]; + } + arr[j + 1] = value; + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + InsertionSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + InsertionSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + InsertionSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/Pluto/sorting-algorithms-insertion-sort.pluto b/Task/Sorting-algorithms-Insertion-sort/Pluto/sorting-algorithms-insertion-sort.pluto new file mode 100644 index 0000000000..525645b5fb --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Pluto/sorting-algorithms-insertion-sort.pluto @@ -0,0 +1,19 @@ +local function insertion_sort(a) + for i = 2, #a do + local v = a[i] + local j = i - 1 + while j >= 1 and a[j] > v do + a[j + 1] = a[j] + j -= 1 + end + a[j + 1] = v + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + insertion_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.ps1 b/Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.ps1 new file mode 100644 index 0000000000..a67a0cb3e1 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.ps1 @@ -0,0 +1,15 @@ +function insertionSort($arr){ + for($i=0;$i -lt $arr.length;$i++){ + $val = $arr[$i] + $j = $i-1 + while($j -ge 0 -and $arr[$j] -gt $val){ + $arr[$j+1] = $arr[$j] + $j-- + } + $arr[$j+1] = $val + } +} + +$arr = @(4,2,1,6,9,3,8,7) +insertionSort($arr) +$arr -join "," diff --git a/Task/Sorting-algorithms-Insertion-sort/RISC-V-Assembly/sorting-algorithms-insertion-sort.asm b/Task/Sorting-algorithms-Insertion-sort/RISC-V-Assembly/sorting-algorithms-insertion-sort.asm new file mode 100644 index 0000000000..06a6bb62cb --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/RISC-V-Assembly/sorting-algorithms-insertion-sort.asm @@ -0,0 +1,143 @@ +# riscv assembly raspberry pico2 rp2350 +# program insertionsort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + mv a2,s2 # item size + call insertionSort # sort + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + + +/******************************************************************/ +/* insertion sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the number of element */ +insertionSort: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + addi t1,a1,1 # start index i +1: # start loop + sh2add t2,t1,a0 + lw t3,(t2) # load value A[i] + addi t5,t1,-1 # index j +2: + sh2add t2,t5,a0 + lw t6,(t2) # load value A[j] + ble t6,t3,3f # compare value A[i] and A[j] + + addi t5,t5,1 # increment index j + sh2add t2,t5,a0 + sw t6,(t2) # store value A[j+1] + + addi t5,t5,-2 # j = i - 1 + bge t5,a1,2b # loop if j >= first item +3: + addi t5,t5,1 + sh2add t2,t5,a0 + sw t3,(t2) # store value A[i] in A[j+1] + addi t1,t1,1 # increment index i + blt t1,a2,1b # end ? +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Insertion-sort/Rebol/sorting-algorithms-insertion-sort.rebol b/Task/Sorting-algorithms-Insertion-sort/Rebol/sorting-algorithms-insertion-sort.rebol new file mode 100644 index 0000000000..48e9115f22 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Rebol/sorting-algorithms-insertion-sort.rebol @@ -0,0 +1,39 @@ +; This program works with Rebol version R2 and R3, to make it work with Red +; change the word func to function +insertion-sort: func [ + a [block!] + /local i [integer!] j [integer!] n [integer!] + value [integer! string! date!] +][ + i: 2 + n: length? a + + while [i <= n][ + value: a/:i + j: i + while [ all [ 1 < j + value < a/(j - 1) ]][ + + a/:j: a/(j - 1) + j: j - 1 + ] + a/:j: value + i: i + 1 + ] + a +] + +probe insertion-sort [4 2 1 6 9 3 8 7] + +probe insertion-sort [ "---Monday's Child Is Fair of Face (by Mother Goose)---" + "Monday's child is fair of face;" + "Tuesday's child is full of grace;" + "Wednesday's child is full of woe;" + "Thursday's child has far to go;" + "Friday's child is loving and giving;" + "Saturday's child works hard for a living;" + "But the child that is born on the Sabbath day" + "Is blithe and bonny, good and gay."] + +; just by adding the date! type to the local variable value the same function can sort dates. +probe insertion-sort [12-Jan-2015 11-Jan-2015 11-Jan-2016 12-Jan-2014] diff --git a/Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vbs b/Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vbs new file mode 100644 index 0000000000..ec90898861 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/VBScript/sorting-algorithms-insertion-sort.vbs @@ -0,0 +1,36 @@ +Randomize +Dim n(9) 'nine is the upperbound. + 'since VBS arrays are 0-based, it will have 10 elements. +For L = 0 to 9 + n(L) = Int(Rnd * 32768) +Next + +WScript.StdOut.Write "ORIGINAL : " +For L = 0 to 9 + WScript.StdOut.Write n(L) & ";" +Next + +InsertionSort n + +WScript.StdOut.Write vbCrLf & " SORTED : " +For L = 0 to 9 + WScript.StdOut.Write n(L) & ";" +Next + +'the function +Sub InsertionSort(theList) + For insertionElementIndex = 1 To UBound(theList) + insertionElement = theList(insertionElementIndex) + j = insertionElementIndex - 1 + Do While j >= 0 + 'necessary for BASICs without short-circuit evaluation + If insertionElement < theList(j) Then + theList(j + 1) = theList(j) + j = j - 1 + Else + Exit Do + End If + Loop + theList(j + 1) = insertionElement + Next +End Sub diff --git a/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.adb b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.adb new file mode 100644 index 0000000000..c51250af0e --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-1.adb @@ -0,0 +1,9 @@ +generic + type Element_Type is private; + type Index_Type is (<>); + type Collection_Type is array(Index_Type range <>) of Element_Type; + with function "<"(Left, Right : Element_Type) return Boolean is <>; + +package Mergesort is + function Sort(Item : Collection_Type) return Collection_Type; +end MergeSort; diff --git a/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.adb b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.adb new file mode 100644 index 0000000000..e06335272b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-2.adb @@ -0,0 +1,62 @@ +package body Mergesort is + + ----------- + -- Merge -- + ----------- + + function Merge(Left, Right : Collection_Type) return Collection_Type is + Result : Collection_Type(Left'First..Right'Last); + Left_Index : Index_Type := Left'First; + Right_Index : Index_Type := Right'First; + Result_Index : Index_Type := Result'First; + begin + while Left_Index <= Left'Last and Right_Index <= Right'Last loop + if Left(Left_Index) <= Right(Right_Index) then + Result(Result_Index) := Left(Left_Index); + Left_Index := Index_Type'Succ(Left_Index); -- increment Left_Index + else + Result(Result_Index) := Right(Right_Index); + Right_Index := Index_Type'Succ(Right_Index); -- increment Right_Index + end if; + Result_Index := Index_Type'Succ(Result_Index); -- increment Result_Index + end loop; + if Left_Index <= Left'Last then + Result(Result_Index..Result'Last) := Left(Left_Index..Left'Last); + end if; + if Right_Index <= Right'Last then + Result(Result_Index..Result'Last) := Right(Right_Index..Right'Last); + end if; + return Result; + end Merge; + + ---------- + -- Sort -- + ---------- + + function Sort (Item : Collection_Type) return Collection_Type is + Result : Collection_Type(Item'range); + Middle : Index_Type; + begin + if Item'Length <= 1 then + return Item; + else + Middle := Index_Type'Val((Item'Length / 2) + Index_Type'Pos(Item'First)); + declare + Left : Collection_Type(Item'First..Index_Type'Pred(Middle)); + Right : Collection_Type(Middle..Item'Last); + begin + for I in Left'range loop + Left(I) := Item(I); + end loop; + for I in Right'range loop + Right(I) := Item(I); + end loop; + Left := Sort(Left); + Right := Sort(Right); + Result := Merge(Left, Right); + end; + return Result; + end if; + end Sort; + +end Mergesort; diff --git a/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.adb b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.adb new file mode 100644 index 0000000000..892aab5fee --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Ada/sorting-algorithms-merge-sort-3.adb @@ -0,0 +1,19 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Mergesort; + +procedure Mergesort_Test is + type List_Type is array(Positive range <>) of Integer; + package List_Sort is new Mergesort(Integer, Positive, List_Type); + procedure Print(Item : List_Type) is + begin + for I in Item'range loop + Put(Integer'Image(Item(I))); + end loop; + New_Line; + end Print; + + List : List_Type := (1, 5, 2, 7, 3, 9, 4, 6); +begin + Print(List); + Print(List_Sort.Sort(List)); +end Mergesort_Test; diff --git a/Task/Sorting-algorithms-Merge-sort/Binary-Lambda-Calculus/sorting-algorithms-merge-sort.blc b/Task/Sorting-algorithms-Merge-sort/Binary-Lambda-Calculus/sorting-algorithms-merge-sort.blc new file mode 100644 index 0000000000..0a0ae36ba0 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Binary-Lambda-Calculus/sorting-algorithms-merge-sort.blc @@ -0,0 +1,19 @@ +(let ((fixpoint-combinator + (lambda (g) + (let ((inner (lambda (x) (g (x x))))) + (inner inner)))) + (sortmerge (lambda (list pred x) + (list + (fixpoint-combinator + (lambda (recur head tail x) + ((pred head (x t)) + ;; these (lambda (p) ...) are inlined cons calls + (lambda (p) (p head (tail recur x))) + (lambda (p) (p (x t) (lambda (p) (p head tail))))))) + (lambda (p) (p x nil)))))) + (lambda (pred list) + (list + (fixpoint-combinator + (lambda (recur head tail z) + (sortmerge (tail recur z) pred head))) + nil))) diff --git a/Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cob b/Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cob new file mode 100644 index 0000000000..1d25525857 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/COBOL/sorting-algorithms-merge-sort.cob @@ -0,0 +1,293 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. MERGESORT. + AUTHOR. DAVE STRATFORD. + DATE-WRITTEN. APRIL 2010. + INSTALLATION. HEXAGON SYSTEMS LIMITED. + ****************************************************************** + * MERGE SORT * + * The Merge sort uses a completely different paradigm, one of * + * divide and conquer, to many of the other sorts. The data set * + * is split into smaller sub sets upon which are sorted and then * + * merged together to form the final sorted data set. * + * This version uses the recursive method. Split the data set in * + * half and perform a merge sort on each half. This in turn splits* + * each half again and again until each set is just one or 2 items* + * long. A set of one item is already sorted so is ignored, a set * + * of two is compared and swapped as necessary. The smaller data * + * sets are then repeatedly merged together to eventually form the* + * full, sorted, set. * + * Since cobol cannot do recursion this module only simulates it * + * so is not as fast as a normal recursive version would be. * + * Scales very well to larger data sets, its relative complexity * + * means it is not suited to sorting smaller data sets: use an * + * Insertion sort instead as the Merge sort is a stable sort. * + ****************************************************************** + + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + SOURCE-COMPUTER. ICL VME. + OBJECT-COMPUTER. ICL VME. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT FA-INPUT-FILE ASSIGN FL01. + SELECT FB-OUTPUT-FILE ASSIGN FL02. + + DATA DIVISION. + FILE SECTION. + FD FA-INPUT-FILE. + 01 FA-INPUT-REC. + 03 FA-DATA PIC 9(6). + + FD FB-OUTPUT-FILE. + 01 FB-OUTPUT-REC PIC 9(6). + + WORKING-STORAGE SECTION. + 01 WA-IDENTITY. + 03 WA-PROGNAME PIC X(10) VALUE "MERGESORT". + 03 WA-VERSION PIC X(6) VALUE "000001". + + 01 WB-TABLE. + 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 + INDEXED BY WB-IX-1 + WB-IX-2. + + 01 WC-VARS. + 03 WC-SIZE PIC S9(8) COMP SYNC. + 03 WC-TEMP PIC S9(8) COMP SYNC. + 03 WC-START PIC S9(8) COMP SYNC. + 03 WC-MIDDLE PIC S9(8) COMP SYNC. + 03 WC-END PIC S9(8) COMP SYNC. + + 01 WD-FIRST-HALF. + 03 WD-FH-MAX PIC S9(8) COMP SYNC. + 03 WD-ENTRY PIC 9(8) COMP SYNC OCCURS 50000 + INDEXED BY WD-IX. + + 01 WF-CONDITION-FLAGS. + 03 WF-EOF-FLAG PIC X. + 88 END-OF-FILE VALUE "Y". + 03 WF-EMPTY-FILE-FLAG PIC X. + 88 EMPTY-FILE VALUE "Y". + + 01 WS-STACK. + * This stack is big enough to sort a list of 1million items. + 03 WS-STACK-ENTRY OCCURS 20 INDEXED BY WS-STACK-TOP. + 05 WS-START PIC S9(8) COMP SYNC. + 05 WS-MIDDLE PIC S9(8) COMP SYNC. + 05 WS-END PIC S9(8) COMP SYNC. + 05 WS-FS-FLAG PIC X. + 88 FIRST-HALF VALUE "F". + 88 SECOND-HALF VALUE "S". + 88 WS-ALL VALUE "A". + 05 WS-IO-FLAG PIC X. + 88 WS-IN VALUE "I". + 88 WS-OUT VALUE "O". + + PROCEDURE DIVISION. + A-MAIN SECTION. + A-000. + PERFORM B-INITIALISE. + + IF NOT EMPTY-FILE + PERFORM C-PROCESS. + + PERFORM D-FINISH. + + A-999. + STOP RUN. + + B-INITIALISE SECTION. + B-000. + DISPLAY "*** " WA-PROGNAME " VERSION " + WA-VERSION " STARTING ***". + + MOVE ALL "N" TO WF-CONDITION-FLAGS. + OPEN INPUT FA-INPUT-FILE. + SET WB-IX-1 TO 0. + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG + WF-EMPTY-FILE-FLAG. + + PERFORM BA-READ-INPUT UNTIL END-OF-FILE. + + CLOSE FA-INPUT-FILE. + + SET WC-SIZE TO WB-IX-1. + + B-999. + EXIT. + + BA-READ-INPUT SECTION. + BA-000. + SET WB-IX-1 UP BY 1. + MOVE FA-DATA TO WB-ENTRY(WB-IX-1). + + READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG. + + BA-999. + EXIT. + + C-PROCESS SECTION. + C-000. + DISPLAY "SORT STARTING". + + MOVE 1 TO WS-START(1). + MOVE WC-SIZE TO WS-END(1). + MOVE "F" TO WS-FS-FLAG(1). + MOVE "I" TO WS-IO-FLAG(1). + SET WS-STACK-TOP TO 2. + + PERFORM E-MERGE-SORT UNTIL WS-OUT(1). + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + D-FINISH SECTION. + D-000. + OPEN OUTPUT FB-OUTPUT-FILE. + SET WB-IX-1 TO 1. + + PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE. + + CLOSE FB-OUTPUT-FILE. + + DISPLAY "*** " WA-PROGNAME " FINISHED ***". + + D-999. + EXIT. + + DA-WRITE-OUTPUT SECTION. + DA-000. + WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). + SET WB-IX-1 UP BY 1. + + DA-999. + EXIT. + + ****************************************************************** + E-MERGE-SORT SECTION. + *===================== * + * This section controls the simulated recursion. * + ****************************************************************** + E-000. + IF WS-OUT(WS-STACK-TOP - 1) + GO TO E-010. + + MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. + MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. + + * First check size of part we are dealing with. + IF WC-END - WC-START = 0 + * Only 1 number in range, so simply set for output, and move on + MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1) + GO TO E-010. + + IF WC-END - WC-START = 1 + * 2 numbers, so compare and swap as necessary. Set for output + MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1) + IF WB-ENTRY(WC-START) > WB-ENTRY(WC-END) + MOVE WB-ENTRY(WC-START) TO WC-TEMP + MOVE WB-ENTRY(WC-END) TO WB-ENTRY(WC-START) + MOVE WC-TEMP TO WB-ENTRY(WC-END) + GO TO E-010 + ELSE + GO TO E-010. + + * More than 2, so split and carry on down + COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2. + + MOVE WC-START TO WS-START(WS-STACK-TOP). + MOVE WC-MIDDLE TO WS-END(WS-STACK-TOP). + MOVE "F" TO WS-FS-FLAG(WS-STACK-TOP). + MOVE "I" TO WS-IO-FLAG(WS-STACK-TOP). + SET WS-STACK-TOP UP BY 1. + + GO TO E-999. + + E-010. + SET WS-STACK-TOP DOWN BY 1. + + IF SECOND-HALF(WS-STACK-TOP) + GO TO E-020. + + MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. + MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. + COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2 + 1. + + MOVE WC-MIDDLE TO WS-START(WS-STACK-TOP). + MOVE WC-END TO WS-END(WS-STACK-TOP). + MOVE "S" TO WS-FS-FLAG(WS-STACK-TOP). + MOVE "I" TO WS-IO-FLAG(WS-STACK-TOP). + SET WS-STACK-TOP UP BY 1. + + GO TO E-999. + + E-020. + MOVE WS-START(WS-STACK-TOP - 1) TO WC-START. + MOVE WS-END(WS-STACK-TOP - 1) TO WC-END. + COMPUTE WC-MIDDLE = ( WC-START + WC-END ) / 2. + PERFORM H-PROCESS-MERGE. + MOVE "O" TO WS-IO-FLAG(WS-STACK-TOP - 1). + + E-999. + EXIT. + + ****************************************************************** + H-PROCESS-MERGE SECTION. + *======================== * + * This section identifies which data is to be merged, and then * + * merges the two data streams into a single larger data stream. * + ****************************************************************** + H-000. + INITIALISE WD-FIRST-HALF. + COMPUTE WD-FH-MAX = WC-MIDDLE - WC-START + 1. + SET WD-IX TO 1. + + PERFORM HA-COPY-OUT VARYING WB-IX-1 FROM WC-START BY 1 + UNTIL WB-IX-1 > WC-MIDDLE. + + SET WB-IX-1 TO WC-START. + SET WB-IX-2 TO WC-MIDDLE. + SET WB-IX-2 UP BY 1. + SET WD-IX TO 1. + + PERFORM HB-MERGE UNTIL WD-IX > WD-FH-MAX OR WB-IX-2 > WC-END. + + PERFORM HC-COPY-BACK UNTIL WD-IX > WD-FH-MAX. + + H-999. + EXIT. + + HA-COPY-OUT SECTION. + HA-000. + MOVE WB-ENTRY(WB-IX-1) TO WD-ENTRY(WD-IX). + SET WD-IX UP BY 1. + + HA-999. + EXIT. + + HB-MERGE SECTION. + HB-000. + IF WB-ENTRY(WB-IX-2) < WD-ENTRY(WD-IX) + MOVE WB-ENTRY(WB-IX-2) TO WB-ENTRY(WB-IX-1) + SET WB-IX-2 UP BY 1 + ELSE + MOVE WD-ENTRY(WD-IX) TO WB-ENTRY(WB-IX-1) + SET WD-IX UP BY 1. + + SET WB-IX-1 UP BY 1. + + HB-999. + EXIT. + + HC-COPY-BACK SECTION. + HC-000. + MOVE WD-ENTRY(WD-IX) TO WB-ENTRY(WB-IX-1). + SET WD-IX UP BY 1. + SET WB-IX-1 UP BY 1. + + HC-999. + EXIT. diff --git a/Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.eu b/Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.eu new file mode 100644 index 0000000000..2eb77e9949 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Euphoria/sorting-algorithms-merge-sort.eu @@ -0,0 +1,37 @@ +function merge(sequence left, sequence right) + sequence result + result = {} + while length(left) > 0 and length(right) > 0 do + if compare(left[1], right[1]) <= 0 then + result = append(result, left[1]) + left = left[2..$] + else + result = append(result, right[1]) + right = right[2..$] + end if + end while + return result & left & right +end function + +function mergesort(sequence m) + sequence left, right + integer middle + if length(m) <= 1 then + return m + else + middle = floor(length(m)/2) + left = mergesort(m[1..middle]) + right = mergesort(m[middle+1..$]) + if compare(left[$], right[1]) <= 0 then + return left & right + elsif compare(right[$], left[1]) <= 0 then + return right & left + else + return merge(left, right) + end if + end if +end function + +constant s = rand(repeat(1000,10)) +? s +? mergesort(s) diff --git a/Task/Sorting-algorithms-Merge-sort/Jactl/sorting-algorithms-merge-sort.jactl b/Task/Sorting-algorithms-Merge-sort/Jactl/sorting-algorithms-merge-sort.jactl new file mode 100644 index 0000000000..7020494c1d --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Jactl/sorting-algorithms-merge-sort.jactl @@ -0,0 +1,19 @@ +def mergesort(x) { + return x if x.size() <= 1 + def left = mergesort(x.subList(0,x.size()/2)) + def right = mergesort(x.subList(x.size()/2)) + return left + right if left[-1] <= right[0] + return merge(left, right) +} + +def merge(left, right) { + def result = [] + while (left.size() > 0 && right.size() > 0) { + [result <<= left[0], left = left.subList(1)] and continue if left[0] < right[0] + [result <<= right[0], right = right.subList(1)] + } + result += left; result += right +} + +def numbers = 10.map{ random(20) } +println "Numbers: $numbers, sorted: ${mergesort(numbers)}" diff --git a/Task/Sorting-algorithms-Merge-sort/Pluto/sorting-algorithms-merge-sort.pluto b/Task/Sorting-algorithms-Merge-sort/Pluto/sorting-algorithms-merge-sort.pluto new file mode 100644 index 0000000000..705835950b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Pluto/sorting-algorithms-merge-sort.pluto @@ -0,0 +1,37 @@ +require "table2" + +local function merge(left, right) + local result = {} + while #left > 0 and #right > 0 do + if left[1] <= right[1] then + result:insert(left[1]) + left = left:slice(2) + else + result:insert(right[1]) + right = right:slice(2) + end + end + if #left > 0 then result:join(left) end + if #right > 0 then result:join(right) end + return result +end + +local function merge_sort(m) + local len = #m + if len <= 1 then return m end + local middle = len // 2 + local left = m:slice(1, middle) + local right = m:slice(middle + 1) + left = merge_sort(left) + right = merge_sort(right) + if left:back() <= right[1] then return left:join(right) end + return merge(left, right) +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + a = merge_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.ps1 b/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.ps1 new file mode 100644 index 0000000000..4a34367b5b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.ps1 @@ -0,0 +1,36 @@ +function MergeSort([object[]] $SortInput) +{ + # The base case exits for minimal lists that are sorted by definition + if ($SortInput.Length -le 1) {return $SortInput} + + # Divide and conquer + [int] $midPoint = $SortInput.Length/2 + # The @() operators ensure a single result remains typed as an array + [object[]] $left = @(MergeSort @($SortInput[0..($midPoint-1)])) + [object[]] $right = @(MergeSort @($SortInput[$midPoint..($SortInput.Length-1)])) + + # Merge + [object[]] $result = @() + while (($left.Length -gt 0) -and ($right.Length -gt 0)) + { + if ($left[0] -lt $right[0]) + { + $result += $left[0] + # Use an if/else rather than accessing the array range as $array[1..0] + if ($left.Length -gt 1){$left = $left[1..$($left.Length-1)]} + else {$left = @()} + } + else + { + $result += $right[0] + # Without the if/else, $array[1..0] would return the whole array when $array.Length == 1 + if ($right.Length -gt 1){$right = $right[1..$($right.Length-1)]} + else {$right = @()} + } + } + + # If we get here, either $left or $right is an empty array (or both are empty!). Since the + # rest of the unmerged array is already sorted, we can simply string together what we have. + # This line outputs the concatenated result. An explicit 'return' statement is not needed. + $result + $left + $right +} diff --git a/Task/Sorting-algorithms-Merge-sort/RISC-V-Assembly/sorting-algorithms-merge-sort.asm b/Task/Sorting-algorithms-Merge-sort/RISC-V-Assembly/sorting-algorithms-merge-sort.asm new file mode 100644 index 0000000000..2242f83925 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/RISC-V-Assembly/sorting-algorithms-merge-sort.asm @@ -0,0 +1,245 @@ +# riscv assembly raspberry pico2 rp2350 +# program mergesort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +#tabNumber: .int 9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call mergeSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* sort control */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* merge sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the last element */ +mergeSort: + addi sp, sp, -20 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + sw s3, 16(sp) + li t0,1 + blt a2,t0,100f # end < 1 -> end + ble a2,a1,100f # first > last ? -> end + srli t0,a2,1 # number of element of each subset + bge t0,a1,1f + mv t0,a1 +1: + mv s0,a0 # save address area + mv s1,a1 # save first indice + mv s2,a2 # save last indice + mv s3,t0 # save last indice + mv a2,t0 # sort set 1 + call mergeSort # + addi a1,s3,1 # index set 2 + mv a2,s2 # index end + mv a0,s0 # array address + call mergeSort # sort lower part + mv a1,s1 # fist index set 1 + mv a2,s3 # last index set 1 + addi a2,a2,1 # start index set 2 + mv a3,s2 # last index set 2 + mv a0,s0 # array address + call merge # merge two sets + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + lw s3, 16(sp) + addi sp, sp, 20 + ret +/******************************************************************/ +/* merge */ +/******************************************************************/ +/* a0 contains the address of table */ +/* a1 contains first start index */ +/* a2 contains second start index */ +/* a3 contains the last index */ +merge: # INFO: merge + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + mv t0,a2 # init with second index +1: + sh2add t2,a1,a0 + lw t3,(t2) # load value first index + sh2add t4,t0,a0 + lw t5,(t4) # load value second index + ble t3,t5,4f # <= -> location first section OK + + sw t5,(t2) # store value second section in first section + addi t1,t0,1 + ble t1,a3,2f # end section 2 ? + sw t3,(t4) # store element section 1 in section 2 + j 4f +2: # loop insert element part 1 into part 2 + addi t6,t1,-1 + sh2add t4,t1,a0 + lw t5,(t4) # load value second set + bge t3,t5,3f # compare value set 1 value set 2 + sh2add t4,t6,a0 # < + sw t3,(t4) # store value 1 + j 4f # and loop +3: # value 1 > value 2 + sh2add t4,t6,a0 + sw t5,(t4) # store value 2 + addi t1,t1,1 # increment indice + ble t1,a3,2b # end set 2 ? no - > loop + addi t1,t1,-1 # + sh2add t4,t1,a0 + sw t3,(t4) # store value set 1 in last post +4: + addi a1,a1,1 + ble a1,a2,1b # end first section ? +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Merge-sort/Rebol/sorting-algorithms-merge-sort.rebol b/Task/Sorting-algorithms-Merge-sort/Rebol/sorting-algorithms-merge-sort.rebol new file mode 100644 index 0000000000..cb224d8840 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Rebol/sorting-algorithms-merge-sort.rebol @@ -0,0 +1,43 @@ +msort: function [a compare] [msort-do merge] [ + if (length? a) < 2 [return a] + ; define a recursive Msort-do function + msort-do: function [a b l] [mid] [ + either l < 4 [ + if l = 3 [msort-do next b next a 2] + merge a b 1 next b l - 1 + ] [ + mid: make integer! l / 2 + msort-do b a mid + msort-do skip b mid skip a mid l - mid + merge a b mid skip b mid l - mid + ] + ] + ; function Merge is the key part of the algorithm + merge: func [a b lb c lc] [ + until [ + either (compare first b first c) [ + change/only a first b + b: next b + a: next a + zero? lb: lb - 1 + ] [ + change/only a first c + c: next c + a: next a + zero? lc: lc - 1 + ] + ] + loop lb [ + change/only a first b + b: next b + a: next a + ] + loop lc [ + change/only a first c + c: next c + a: next a + ] + ] + msort-do a copy a length? a + a +] diff --git a/Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.adb b/Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.adb new file mode 100644 index 0000000000..7f48fb8b75 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Ada/sorting-algorithms-pancake-sort.adb @@ -0,0 +1,45 @@ +with Ada.Text_IO; +procedure Pancake_Sort is + generic + type Element_Type is private; + type Index_Type is range <>; + type Array_Type is array (Index_Type range <>) of Element_Type; + with function ">" (Left, Right : Element_Type) return Boolean is <>; + procedure Pancake_Sort (Data: in out Array_Type); + + procedure Pancake_Sort (Data: in out Array_Type) is + procedure Flip (Up_To : in Index_Type) is + Temp : constant Array_Type := Data (Data'First .. Up_To); + begin + for I in Temp'Range loop + Data (I) := Temp (Temp'First + Up_To - I); + end loop; + end Flip; + Max_Index : Index_Type; + begin + for I in reverse Data'First + 1 .. Data'Last loop + Max_Index := Data'First; + for A in Data'First + 1 .. I loop + if Data(A) > Data (Max_Index) then + Max_Index := A; + end if; + end loop; + if Max_Index /= I then + if Max_Index > Data'First then + Flip (Max_Index); + end if; + Flip (I); + end if; + end loop; + end Pancake_Sort; + + type Integer_Array is array (Positive range <>) of Integer; + procedure Int_Pancake_Sort is new Pancake_Sort (Integer, Positive, Integer_Array); + Test_Array : Integer_Array := (3, 14, 1, 5, 9, 2, 6, 3); +begin + Int_Pancake_Sort (Test_Array); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + end loop; + Ada.Text_IO.New_Line; +end Pancake_Sort; diff --git a/Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.eu b/Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.eu new file mode 100644 index 0000000000..e5c473bf40 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Euphoria/sorting-algorithms-pancake-sort.eu @@ -0,0 +1,34 @@ +function flip(sequence s, integer n) + object temp + for i = 1 to n/2 do + temp = s[i] + s[i] = s[n-i+1] + s[n-i+1] = temp + end for + return s +end function + +function pancake_sort(sequence s) + integer m + for i = length(s) to 2 by -1 do + m = 1 + for j = 2 to i do + if compare(s[j], s[m]) > 0 then + m = j + end if + end for + + if m < i then + if m > 1 then + s = flip(s,m) + end if + s = flip(s,i) + end if + end for + return s +end function + +constant s = rand(repeat(100,10)) + +? s +? pancake_sort(s) diff --git a/Task/Sorting-algorithms-Pancake-sort/Haxe/sorting-algorithms-pancake-sort.hx b/Task/Sorting-algorithms-Pancake-sort/Haxe/sorting-algorithms-pancake-sort.hx new file mode 100644 index 0000000000..8ddfd306c9 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Haxe/sorting-algorithms-pancake-sort.hx @@ -0,0 +1,48 @@ +class PancakeSort { + @:generic + inline private static function flip(arr:Array, num:Int) { + var i = 0; + while (i < --num) { + var temp = arr[i]; + arr[i++] = arr[num]; + arr[num] = temp; + } + } + + @:generic + public static function sort(arr:Array) { + if (arr.length < 2) return; + + var i = arr.length; + while (i > 1) { + var maxNumPos = 0; + for (a in 0...i) { + if (Reflect.compare(arr[a], arr[maxNumPos]) > 0) + maxNumPos = a; + } + if (maxNumPos == i - 1) i--; + if (maxNumPos > 0) flip(arr, maxNumPos + 1); + flip(arr, i--); + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + PancakeSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + PancakeSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + PancakeSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Pancake-sort/Pluto/sorting-algorithms-pancake-sort.pluto b/Task/Sorting-algorithms-Pancake-sort/Pluto/sorting-algorithms-pancake-sort.pluto new file mode 100644 index 0000000000..0bc5b531d6 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Pluto/sorting-algorithms-pancake-sort.pluto @@ -0,0 +1,22 @@ +local function flip(a, r) + local l = 1 + while l <= r do + a[r], a[l] = a[l], a[r] + l += 1 + r -= 1 + end +end + +local function pancake_sort(a) + for uns = #a, 2, -1 do + local lg = a:slice(1, uns):max() + local lx = a:findindex(|e| -> e == lg) + flip(a, lx) + flip(a, uns) + end +end + +local a = {31, 41, 59, 26, 53, 58, 97, 93, 23, 84} +print($"Before: \{{a:concat(", ")}}") +pancake_sort(a) +print($"After : \{{a:concat(", ")}}") diff --git a/Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.ps1 b/Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.ps1 new file mode 100644 index 0000000000..bad94a0fa7 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/PowerShell/sorting-algorithms-pancake-sort.ps1 @@ -0,0 +1,38 @@ +Function FlipPancake( [Object[]] $indata, $index = 1 ) +{ + $data=$indata.Clone() + $datal = $data.length - 1 + if( $index -gt 0 ) + { + if( $datal -gt $index ) + { + $first = $data[ $index..0 ] + $last = $data[ ( $index + 1 )..$datal ] + $data = $first + $last + } else { + $data = $data[ $index..0 ] + } + } + $data +} + +Function MaxIdx( [Object[]] $data ) +{ + $data | ForEach-Object { $max = $data[ 0 ]; $i = 0; $maxi = 0 } { if( $_ -gt $max ) { $max = $_; $maxi = $i }; $i++ } { $maxi } +} + +Function PancakeSort( [Object[]] $data, $index = 0 ) +{ + "unsorted - $data" + $datal = $data.length - 1 + if( $datal -gt 0 ) + { + for( $i = $datal; $i -gt 0; $i-- ) + { + $data = FlipPancake ( FlipPancake $data ( MaxIdx $data[ 0..$i ] ) ) $i + } + } + "sorted - $data" +} + +$l = 100; PancakeSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Patience-sort/Ada/sorting-algorithms-patience-sort.adb b/Task/Sorting-algorithms-Patience-sort/Ada/sorting-algorithms-patience-sort.adb new file mode 100644 index 0000000000..8a516df3ff --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/Ada/sorting-algorithms-patience-sort.adb @@ -0,0 +1,288 @@ +---------------------------------------------------------------------- + +with Ada.Text_IO; + +procedure patience_sort_task is + use Ada.Text_IO; + + function next_power_of_two + (n : in Natural) + return Positive is + -- This need not be a fast implementation. + pow2 : Positive; + begin + pow2 := 1; + while pow2 < n loop + pow2 := pow2 + pow2; + end loop; + return pow2; + end next_power_of_two; + + generic + type t is private; + type t_array is array (Integer range <>) of t; + type sorted_t_indices is array (Integer range <>) of Integer; + procedure patience_sort + (less : access function + (x, y : t) + return Boolean; + ifirst : in Integer; + ilast : in Integer; + arr : in t_array; + sorted : out sorted_t_indices); + + procedure patience_sort + (less : access function + (x, y : t) + return Boolean; + ifirst : in Integer; + ilast : in Integer; + arr : in t_array; + sorted : out sorted_t_indices) is + + num_piles : Integer; + piles : array (1 .. ilast - ifirst + 1) of Integer := + (others => 0); + links : array (1 .. ilast - ifirst + 1) of Integer := + (others => 0); + + function find_pile + (q : in Positive) + return Positive is + -- + -- Bottenbruch search for the leftmost pile whose top is greater + -- than or equal to some element x. Return an index such that: + -- + -- * if x is greater than the top element at the far right, then + -- the index returned will be num-piles. + -- + -- * otherwise, x is greater than every top element to the left + -- of index, and less than or equal to the top elements at + -- index and to the right of index. + -- + -- References: + -- + -- * H. Bottenbruch, "Structure and use of ALGOL 60", Journal of + -- the ACM, Volume 9, Issue 2, April 1962, pp.161-221. + -- https://doi.org/10.1145/321119.321120 + -- + -- The general algorithm is described on pages 214 and 215. + -- + -- * https://en.wikipedia.org/w/index.php?title=Binary_search_algorithm&oldid=1062988272#Alternative_procedure + -- + index : Positive; + i, j, k : Natural; + begin + if num_piles = 0 then + index := 1; + else + j := 0; + k := num_piles - 1; + while j /= k loop + i := (j + k) / 2; + if less + (arr (piles (j + 1) + ifirst - 1), arr (q + ifirst - 1)) + then + j := i + 1; + else + k := i; + end if; + end loop; + if j = num_piles - 1 then + if less + (arr (piles (j + 1) + ifirst - 1), arr (q + ifirst - 1)) + then + -- A new pile is needed. + j := j + 1; + end if; + end if; + index := j + 1; + end if; + return index; + end find_pile; + + procedure deal is + i : Positive; + begin + for q in links'range loop + i := find_pile (q); + links (q) := piles (i); + piles (i) := q; + num_piles := Integer'max (num_piles, i); + end loop; + end deal; + + procedure k_way_merge is + -- + -- k-way merge by tournament tree. + -- + -- See Knuth, volume 3, and also + -- https://en.wikipedia.org/w/index.php?title=K-way_merge_algorithm&oldid=1047851465#Tournament_Tree + -- + -- However, I store a winners tree instead of the recommended + -- losers tree. If the tree were stored as linked nodes, it + -- would probably be more efficient to store a losers + -- tree. However, I am storing the tree as an array, and one + -- can find an opponent quickly by simply toggling the least + -- significant bit of a competitor's array index. + -- + total_external_nodes : Positive; + total_nodes : Positive; + begin + + total_external_nodes := next_power_of_two (num_piles); + total_nodes := (2 * total_external_nodes) - 1; + + declare + + -- In Fortran I had the length-2 dimension come first, to + -- take some small advantage of column-major order. The + -- recommendation for Ada compilers, however, is to use + -- row-major order. So I have reversed the order. + winners : array (1 .. total_nodes, 1 .. 2) of Integer := + (others => (0, 0)); + + function find_opponent + (i : Natural) + return Natural is + begin + return (if i rem 2 = 0 then i + 1 else i - 1); + end find_opponent; + + function play_game + (i : Positive) + return Positive is + j, iwinner : Positive; + begin + j := find_opponent (i); + if winners (i, 1) = 0 then + iwinner := j; + elsif winners (j, 1) = 0 then + iwinner := i; + elsif less + (arr (winners (j, 1) + ifirst - 1), + arr (winners (i, 1) + ifirst - 1)) + then + iwinner := j; + else + iwinner := i; + end if; + return iwinner; + end play_game; + + procedure replay_games + (i : Positive) is + j, iwinner : Positive; + begin + j := i; + while j /= 1 loop + iwinner := play_game (j); + j := j / 2; + winners (j, 1) := winners (iwinner, 1); + winners (j, 2) := winners (iwinner, 2); + end loop; + end replay_games; + + procedure build_tree is + istart, i, iwinner : Positive; + begin + for i in 1 .. total_external_nodes loop + -- Record which pile a winner will have come from. + winners (total_external_nodes - 1 + i, 2) := i; + end loop; + + for i in 1 .. num_piles loop + -- The top of each pile becomes a starting competitor. + winners (total_external_nodes + i - 1, 1) := piles (i); + end loop; + + for i in 1 .. num_piles loop + -- Discard the top of each pile + piles (i) := links (piles (i)); + end loop; + + istart := total_external_nodes; + while istart /= 1 loop + i := istart; + while i <= (2 * istart) - 1 loop + iwinner := play_game (i); + winners (i / 2, 1) := winners (iwinner, 1); + winners (i / 2, 2) := winners (iwinner, 2); + i := i + 2; + end loop; + istart := istart / 2; + end loop; + end build_tree; + + isorted, i, next : Integer; + + begin + build_tree; + isorted := 0; + while winners (1, 1) /= 0 loop + sorted (sorted'first + isorted) := + winners (1, 1) + ifirst - 1; + isorted := isorted + 1; + i := winners (1, 2); + next := piles (i); -- The next top of pile i. + if next /= 0 then + piles (i) := links (next); -- Drop that top. + end if; + i := (total_nodes / 2) + i; + winners (i, 1) := next; + replay_games (i); + end loop; + end; + + end k_way_merge; + + begin + deal; + k_way_merge; + end patience_sort; + +begin + + -- A demonstration. + + declare + + type integer_array is array (Integer range <>) of Integer; + procedure integer_patience_sort is new patience_sort + (Integer, integer_array, integer_array); + + subtype int25_array is integer_array (1 .. 25); + + example_numbers : constant int25_array := + (22, 15, 98, 82, 22, 4, 58, 70, 80, 38, 49, 48, 46, 54, 93, 8, + 54, 2, 72, 84, 86, 76, 53, 37, 90); + + sorted_numbers : int25_array := (others => 0); + + function less + (x, y : Integer) + return Boolean is + begin + return (x < y); + end less; + + begin + integer_patience_sort + (less'access, example_numbers'first, example_numbers'last, + example_numbers, sorted_numbers); + + Put ("unsorted "); + for i of example_numbers loop + Put (Integer'image (i)); + end loop; + Put_Line (""); + Put ("sorted "); + for i of sorted_numbers loop + Put (Integer'image (example_numbers (i))); + end loop; + Put_Line (""); + end; + +end patience_sort_task; + +---------------------------------------------------------------------- diff --git a/Task/Sorting-algorithms-Patience-sort/Pluto/sorting-algorithms-patience-sort.pluto b/Task/Sorting-algorithms-Patience-sort/Pluto/sorting-algorithms-patience-sort.pluto new file mode 100644 index 0000000000..a75252e19b --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/Pluto/sorting-algorithms-patience-sort.pluto @@ -0,0 +1,44 @@ +local fmt = require "fmt" + +local function patience_sort(a) + local size = #a + if size < 2 then return end + local piles = {} + for a as e do + local outer = false + for piles as pile do + if pile:back() > e then + pile:insert(e) + outer = true + break + end + end + if !outer then piles:insert({e}) end + end + for i = 1, size do + local min = piles[1]:back() + local min_pile_index = 1 + for j = 2, #piles do + if piles[j]:back() < min then + min = piles[j]:back() + min_pile_index = j + end + end + a[i] = min + local min_pile = piles[min_pile_index] + min_pile:remove() + if #min_pile == 0 then piles:remove(min_pile_index) end + end +end + +local ia = {4, 65, 2, -31, 0, 99, 83, 782, 1} +patience_sort(ia) +fmt.lprint(ia) + +local ca = {"n", "o", "n", "z", "e", "r", "o", "s", "u", "m"} +patience_sort(ca) +fmt.lprint(ca) + +local sa = {"dog", "cow", "cat", "ape", "ant", "man", "pig", "ass", "gnu"} +patience_sort(sa) +fmt.lprint(sa) diff --git a/Task/Sorting-algorithms-Patience-sort/R/sorting-algorithms-patience-sort.r b/Task/Sorting-algorithms-Patience-sort/R/sorting-algorithms-patience-sort.r new file mode 100644 index 0000000000..cf905f5f16 --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/R/sorting-algorithms-patience-sort.r @@ -0,0 +1,37 @@ +patiencesort <- function(list) { + piles <- list() + for (n in list) { + # Find the first pile where the last element is >= n + i <- sapply(piles, function(pile) n <= tail(pile, 1)) + if (length(piles) == 0 || !any(i)) { + piles <- append(piles, list(n)) + } else { + # Find the index of the first TRUE in i + idx <- which(i)[1] + piles[[idx]] <- c(piles[[idx]], n) + } + } + mergesorted(piles) +} + +mergesorted <- function(vecvec) { + allsum <- sum(sapply(vecvec, length)) + sorted <- vector("numeric", allsum) + for (i in 1:allsum) { + # Find the pile with the smallest last element + last_elements <- sapply(vecvec, tail, 1) + idx <- which.min(last_elements) + sorted[i] <- tail(vecvec[[idx]], 1) + vecvec[[idx]] <- head(vecvec[[idx]], -1) + # Remove empty piles + if (length(vecvec[[idx]]) == 0) { + vecvec <- vecvec[-idx] + } + } + sorted +} + +# Example usage +set.seed(123) +random_list <- sample(1:1000, 12) +print(patiencesort(random_list)) diff --git a/Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly/sorting-algorithms-patience-sort.asm b/Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly/sorting-algorithms-patience-sort.asm new file mode 100644 index 0000000000..e1659efad1 --- /dev/null +++ b/Task/Sorting-algorithms-Patience-sort/RISC-V-Assembly/sorting-algorithms-patience-sort.asm @@ -0,0 +1,400 @@ +# riscv assembly raspberry pico2 rp2350 +# program patiencesort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure Doublylinkedlist*/ + .struct 0 +dllist_head: # head node + .struct dllist_head + 4 +dllist_tail: # tail node + .struct dllist_tail + 4 +dllist_end: +/* structure Node Doublylinked List*/ + .struct 0 +NDlist_next: # next element + .struct NDlist_next + 4 +NDlist_prev: # previous element + .struct NDlist_prev + 4 +NDlist_value: # element value or key + .struct NDlist_value + 4 +NDlist_end: + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +#tabNumber: .int 9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number +ptHeapReserve: .int heapReserve +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +heapReserve: .skip HEAPSIZE +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + mv a2,s2 + call patienceSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* sort control */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* patience sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the array size */ +patienceSort: + addi sp, sp, -48 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + sw s3, 16(sp) + sw s4, 20(sp) + sw s5, 24(sp) + sw s6, 28(sp) + sw s7, 32(sp) + sw s8, 36(sp) + sw s9, 40(sp) + sw s10, 44(sp) + slli s0,a2,1 + slli s9,s0,3 + mv s2,a0 # save table address + mv s3,a2 # save array size + sub sp,sp,s9 # reserve on stacm + mv s10,sp + li s8,0 +1: + sh2add t0,s8,s10 + sw x0,(t0) # init piles area + addi s8,s8,1 # increment index + blt s8,s0,1b + li s8,0 # index value + li s1,0 # counter first pile +2: + sh2add t0,s8,s2 # compute array address + lw a1,(t0) # load value + sh3add a0,s1,s10 # stack address + lw t0,dllist_head(a0) + bnez t0,3f # empty stack + call insertHead # insert value a1 + blez a0,100f + j 5f + +3: + lw t5,dllist_head(a0) + lw t5,NDlist_value(t5) # load first list value + blt a1,t5,4f + call insertHead + blez a0,100f + j 5f +4: # value is smaller créate a new pile + addi s1,s1,1 + sh3add a0,s1,s10 # new stack address + call insertHead # insert value r1 + blez a0,100f +5: + addi s8,s8,1 # increment index value + blt s8,s3,2b # end ? no -> loop + li s7,0 # init index value table +6: + li s8,0 # stack index + li s5,1<<30 # minimum + +7: # search minimum + sh3add a0,s8,s10 # stack address + lw a0,dllist_head(a0) + beqz a0,8f # empty stack + call searchMinList + bge a0,s5,8f # compare min global + mv s5,a0 # smaller -> store new min + mv s4,a1 # and pointer to min + sh3add s6,s8,s10 # and head list +8: + addi s8,s8,1 # next stack + ble s8,s1,7b # end ? no -> loop + sh2add t0,s7,s2 + sw s5,(t0) # store min to table value + mv a0,s6 + mv a1,s4 + call suppressNode + addi s7,s7,1 + blt s7,s3,6b # end ? no -> loop +100: + add sp,sp,s9 # stack alignement + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + lw s3, 16(sp) + lw s4, 20(sp) + lw s5, 24(sp) + lw s6, 28(sp) + lw s7, 32(sp) + lw s8, 36(sp) + lw s9, 40(sp) + lw s10, 44(sp) + addi sp, sp, 48 + ret + +/**********************************************/ +/* create new double linked list */ +/**********************************************/ +/* a0 linked list address */ +newDList: # INFO: newDList + addi sp, sp, -4 + sw ra, 0(sp) + + sw x0,dllist_tail(a0) # raz pointer + sw x0,dllist_head(a0) # raz pointer + + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* insertion value in head */ +/**********************************************/ +/* a0 double linked list address */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertHead: # INFO: insertTail + addi sp, sp, -8 + sw ra, 0(sp) + sw s0, 4(sp) + mv s0,a0 # save address + mv a0,a1 # value + call createNode # create new node + blez a0,100f # error ? + + lw t0,dllist_head(s0) # load address first node + sw t0,NDlist_next(a0) # store in next pointer on new node + sw x0,NDlist_prev(a0) # store null on prev pointer + sw a0,dllist_head(s0) # store address new node on list head + beqz t0,1f # address last node is null ? + sw a0,NDlist_prev(t0) # no store address new node in next pointer + j 2f +1: + sw a0,dllist_tail(s0) # else store in head list +2: + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/**********************************************/ +/* search value minimum */ +/**********************************************/ +/* a0 contains the address of the list structure */ +/* a0 return min */ +/* a1 return node address */ +searchMinList: # INFO: searchMinList + addi sp, sp, -4 + sw ra, 0(sp) + mv t0,a0 + li t3,1<<30 + li a1,0 # init node address +1: + bnez t0,2f # equal zero ? + mv a0,t3 # yes -> end + j 100f +2: + lw t1,NDlist_value(t0) # load node value + bge t1,t3,3f # < ? + mv t3,t1 # yes -> min = new value + mv a1,t0 +3: + lw t0,NDlist_next(t0) # load address next node + j 1b # and loop + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* create node on heap */ +/**********************************************/ +/* a0 value */ +/* a0 return node address or -1 if error */ +createNode: # INFO: createNode + addi sp, sp, -4 + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + addi t2,t1,NDlist_end # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 + blt t2,t3,2f + li a0,-1 + j 100f +2: + sw t2,(t0) # save new value heap used + sw a0,NDlist_value(t1) # store value on heap + sw x0,NDlist_next(t1) # raz pointer next + sw x0,NDlist_prev(t1) # raz pointer previous + mv a0,t1 # return node address +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/**********************************************/ +/* suppress node on list */ +/**********************************************/ +/* a0 contains the address of the list structure */ +/* a1 contains the address to node to suppress */ +suppressNode: # INFO: suppressNode + addi sp, sp, -4 + sw ra, 0(sp) + lw t0,NDlist_next(a1) # load addresse next node + lw t1,NDlist_prev(a1) # load addresse prev node + beqz t1,1f + sw t0,NDlist_next(t1) + j 2f +1: + sw t1,NDlist_next(a0) +2: + beqz t0,3f + sw t1,NDlist_prev(t0) + j 100f +3: + sw t0,NDlist_prev(a0) +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.adb b/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.adb new file mode 100644 index 0000000000..bb2a8889c7 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Ada/sorting-algorithms-permutation-sort.adb @@ -0,0 +1,39 @@ +-- Permutation sort +-- J. Carter 2024 Jun +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Permutations; + +procedure Slow_Sort is + package Char_Perms is new PragmARC.Permutations (Element => Character); + + procedure Put (Item : in Char_Perms.Sequence); + -- Outputs all the Characters in Item to standard output, followed by a line terminator + + procedure Process (Seq : in Char_Perms.Sequence; Stop : in out Boolean); + -- If Seq is sorted, outputs it and sets Stop to True + + procedure Put (Item : in Char_Perms.Sequence) is + -- Empty + begin -- Put + All_Chars : for C of Item loop + Ada.Text_IO.Put (Item => C); + end loop All_Chars; + + Ada.Text_IO.New_Line; + end Put; + + procedure Process (Seq : in Char_Perms.Sequence; Stop : in out Boolean) is + -- Empty + begin -- Process + if (for all J in 1 .. Seq'Last - 1 => Seq (J) <= Seq (J + 1) ) then -- Sorted + Put (Item => Seq); + Stop := True; + end if; + end Process; + + Test : constant Char_Perms.Sequence := "kjihgfedcba"; +begin -- Slow_Sort + Char_Perms.Generate (Initial => Test, Process => Process'Access); +end Slow_Sort; diff --git a/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal b/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal index 051eeeb95b..302d637914 100644 --- a/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal +++ b/Task/Sorting-algorithms-Permutation-sort/EMal/sorting-algorithms-permutation-sort.emal @@ -1,29 +1,29 @@ type PermutationSort -fun isSorted = logic by List a - for int i = 1; i < a.length; ++i +fun isSorted ← logic by List a + for int i ← 1; i < a.length; ++i if a[i - 1] > a[i] do return false end end return true end -fun permute = void by List a, int n, List lists - if n == 1 - List b = int[] - for int i = 0; i < a.length; ++i +fun permute ← void by List a, int n, List lists + if n æ 1 + List b ← int[] + for int i ← 0; i < a.length; ++i b.append(a[i]) end lists.append(b) return end - int i = 0 + int i ← 0 while i < n a.swap(i, n - 1) permute(a, n - 1, lists) a.swap(i, n - 1) - i = i + 1 + i ← i + 1 end end -fun sort = List by List a - List lists = List[] +fun sort ← List by List a + List lists ← List[] permute(a, a.length, lists) for each List list in lists if isSorted(list) do return list end @@ -31,7 +31,7 @@ fun sort = List by List a return a end type Main -List a = int[3,2,1,8,9,4,6] +List a ← int[3,2,1,8,9,4,6] writeLine("Unsorted: " + a) -a = PermutationSort.sort(a) +a ← PermutationSort.sort(a) writeLine(" Sorted: " + a) diff --git a/Task/Sorting-algorithms-Permutation-sort/Pluto/sorting-algorithms-permutation-sort.pluto b/Task/Sorting-algorithms-Permutation-sort/Pluto/sorting-algorithms-permutation-sort.pluto new file mode 100644 index 0000000000..cd684c15c1 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/Pluto/sorting-algorithms-permutation-sort.pluto @@ -0,0 +1,24 @@ +local function is_sorted(a) + for i = 1, #a - 1 do + if a[i] > a[i + 1] then return false end + end + return true +end + +local a = {170, 45, 75, -90, -802, 24, 2, 66} + +-- Recursive permutation generator. +local function recurse(last) + if last <= 1 then return is_sorted(a) end + for i = 1, last do + a[i], a[last] = a[last], a[i] + if recurse(last - 1) then return true end + a[i], a[last] = a[last], a[i] + end + return false +end + +print($"Unsorted: \{{a:concat(", ")}}") +local c = #a +if c > 1 and !recurse(c) then error("Sorted permutation not found!") end +print($"Sorted : \{{a:concat(", ")}}") diff --git a/Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.ps1 b/Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.ps1 new file mode 100644 index 0000000000..cb541e38e9 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/PowerShell/sorting-algorithms-permutation-sort.ps1 @@ -0,0 +1,40 @@ +Function PermutationSort( [Object[]] $indata, $index = 0, $k = 0 ) +{ + $data = $indata.Clone() + $datal = $data.length - 1 + if( $datal -gt 0 ) { + for( $j = $index; $j -lt $datal; $j++ ) + { + $sorted = ( PermutationSort $data ( $index + 1 ) $j )[0] + if( -not $sorted ) + { + $temp = $data[ $index ] + $data[ $index ] = $data[ $j + 1 ] + $data[ $j + 1 ] = $temp + } + } + if( $index -lt ( $datal - 1 ) ) + { + PermutationSort $data ( $index + 1 ) $j + } else { + $sorted = $true + for( $i = 0; ( $i -lt $datal ) -and $sorted; $i++ ) + { + $sorted = ( $data[ $i ] -le $data[ $i + 1 ] ) + } + $sorted + $data + } + } +} + +0..4 | ForEach-Object { $a = $_; 0..4 | Where-Object { -not ( $_ -match "$a" ) } | + ForEach-Object { $b = $_; 0..4 | Where-Object { -not ( $_ -match "$a|$b" ) } | + ForEach-Object { $c = $_; 0..4 | Where-Object { -not ( $_ -match "$a|$b|$c" ) } | + ForEach-Object { $d = $_; 0..4 | Where-Object { -not ( $_ -match "$a|$b|$c|$d" ) } | + ForEach-Object { $e=$_; "$( PermutationSort ( $a, $b, $c, $d, $e ) )" } + } + } + } +} +$l = 8; PermutationSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.adb b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.adb new file mode 100644 index 0000000000..a07dfe1094 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-1.adb @@ -0,0 +1,9 @@ +----------------------------------------------------------------------- +-- Generic Quick_Sort procedure +----------------------------------------------------------------------- +generic + type Element is private; + type Index is (<>); + type Element_Array is array(Index range <>) of Element; + with function "<" (Left, Right : Element) return Boolean is <>; +procedure Quick_Sort(A : in out Element_Array); diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.adb b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.adb new file mode 100644 index 0000000000..c907133fb7 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.adb @@ -0,0 +1,44 @@ +----------------------------------------------------------------------- +-- Generic Quick_Sort procedure +----------------------------------------------------------------------- + +procedure Quick_Sort (A : in out Element_Array) is + + procedure Swap(Left, Right : Index) is + Temp : Element := A (Left); + begin + A (Left) := A (Right); + A (Right) := Temp; + end Swap; + +begin + if A'Length > 1 then + declare + Pivot_Value : Element := A (A'First); + Right : Index := A'Last; + Left : Index := A'First; + begin + loop + while Left < Right and not (Pivot_Value < A (Left)) loop + Left := Index'Succ (Left); + end loop; + while Pivot_Value < A (Right) loop + Right := Index'Pred (Right); + end loop; + exit when Right <= Left; + Swap (Left, Right); + Left := Index'Succ (Left); + Right := Index'Pred (Right); + end loop; + if Right = A'Last then + Right := Index'Pred (Right); + Swap (A'First, A'Last); + end if; + if Left = A'First then + Left := Index'Succ (Left); + end if; + Quick_Sort (A (A'First .. Right)); + Quick_Sort (A (Left .. A'Last)); + end; + end if; +end Quick_Sort; diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.adb b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.adb new file mode 100644 index 0000000000..fe4cef6141 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-3.adb @@ -0,0 +1,32 @@ +with Ada.Text_Io; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Quick_Sort; + +procedure Sort_Test is + type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun); + type Sales is array (Days range <>) of Float; + procedure Sort_Days is new Quick_Sort(Float, Days, Sales); + + procedure Print (Item : Sales) is + begin + for I in Item'range loop + Put(Item => Item(I), Fore => 5, Aft => 2, Exp => 0); + end loop; + end Print; + + Weekly_Sales : Sales := (Mon => 300.0, + Tue => 700.0, + Wed => 800.0, + Thu => 500.0, + Fri => 200.0, + Sat => 100.0, + Sun => 900.0); + +begin + + Print(Weekly_Sales); + Ada.Text_Io.New_Line(2); + Sort_Days(Weekly_Sales); + Print(Weekly_Sales); + +end Sort_Test; diff --git a/Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cob b/Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cob new file mode 100644 index 0000000000..2f3b16e9ee --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/COBOL/sorting-algorithms-quicksort.cob @@ -0,0 +1,66 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. quicksort RECURSIVE. + + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 temp PIC S9(8). + + 01 pivot PIC S9(8). + + 01 left-most-idx PIC 9(5). + 01 right-most-idx PIC 9(5). + + 01 left-idx PIC 9(5). + 01 right-idx PIC 9(5). + + LINKAGE SECTION. + 78 Arr-Length VALUE 50. + + 01 arr-area. + 03 arr PIC S9(8) OCCURS Arr-Length TIMES. + + 01 left-val PIC 9(5). + 01 right-val PIC 9(5). + + PROCEDURE DIVISION USING REFERENCE arr-area, OPTIONAL left-val, + OPTIONAL right-val. + IF left-val IS OMITTED OR right-val IS OMITTED + MOVE 1 TO left-most-idx, left-idx + MOVE Arr-Length TO right-most-idx, right-idx + ELSE + MOVE left-val TO left-most-idx, left-idx + MOVE right-val TO right-most-idx, right-idx + END-IF + + IF right-most-idx - left-most-idx < 1 + GOBACK + END-IF + + COMPUTE pivot = arr ((left-most-idx + right-most-idx) / 2) + + PERFORM UNTIL left-idx > right-idx + PERFORM VARYING left-idx FROM left-idx BY 1 + UNTIL arr (left-idx) >= pivot + END-PERFORM + + PERFORM VARYING right-idx FROM right-idx BY -1 + UNTIL arr (right-idx) <= pivot + END-PERFORM + + IF left-idx <= right-idx + MOVE arr (left-idx) TO temp + MOVE arr (right-idx) TO arr (left-idx) + MOVE temp TO arr (right-idx) + + ADD 1 TO left-idx + SUBTRACT 1 FROM right-idx + END-IF + END-PERFORM + + CALL "quicksort" USING REFERENCE arr-area, + CONTENT left-most-idx, right-idx + CALL "quicksort" USING REFERENCE arr-area, CONTENT left-idx, + right-most-idx + + GOBACK + . diff --git a/Task/Sorting-algorithms-Quicksort/Emacs-Lisp/sorting-algorithms-quicksort.el b/Task/Sorting-algorithms-Quicksort/Emacs-Lisp/sorting-algorithms-quicksort.el new file mode 100644 index 0000000000..78a041071c --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Emacs-Lisp/sorting-algorithms-quicksort.el @@ -0,0 +1,10 @@ +(require 'seq) + +(defun quicksort (xs) + (if (null xs) + () + (let* ((head (car xs)) + (tail (cdr xs)) + (lower-part (quicksort (seq-filter (lambda (x) (<= x head)) tail))) + (higher-part (quicksort (seq-filter (lambda (x) (> x head)) tail)))) + (append lower-part (list head) higher-part)))) diff --git a/Task/Sorting-algorithms-Quicksort/Gleam/sorting-algorithms-quicksort.gleam b/Task/Sorting-algorithms-Quicksort/Gleam/sorting-algorithms-quicksort.gleam new file mode 100644 index 0000000000..b6e7e683c3 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Gleam/sorting-algorithms-quicksort.gleam @@ -0,0 +1,19 @@ +import gleam/int +import gleam/list +import gleam/order.{type Order, Lt} + +pub fn quick_sort(xs: List(a), compare: fn(a, a) -> Order) -> List(a) { + case xs { + [] -> [] + [x, ..xs] -> { + let #(left, right) = list.partition(xs, fn(y) { compare(y, x) == Lt }) + let ql = quick_sort(left, compare) + let qr = quick_sort(right, compare) + list.append(list.append(ql, [x]), qr) + } + } +} + +pub fn main() { + [31, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8] |> quick_sort(int.compare) |> echo +} diff --git a/Task/Sorting-algorithms-Quicksort/Jactl/sorting-algorithms-quicksort.jactl b/Task/Sorting-algorithms-Quicksort/Jactl/sorting-algorithms-quicksort.jactl new file mode 100644 index 0000000000..83eb183a09 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Jactl/sorting-algorithms-quicksort.jactl @@ -0,0 +1,9 @@ +def qsort(x) { + switch(x) { + [],[_] -> x + [h,*t] -> qsort(t.filter{it <= h}) + [h] + qsort(t.filter{it > h}) + } +} + +def list = 10.map{ random(20) } +println qsort(list) diff --git a/Task/Sorting-algorithms-Quicksort/Pluto/sorting-algorithms-quicksort.pluto b/Task/Sorting-algorithms-Quicksort/Pluto/sorting-algorithms-quicksort.pluto new file mode 100644 index 0000000000..3990792d29 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Pluto/sorting-algorithms-quicksort.pluto @@ -0,0 +1,12 @@ +local array = { + {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, + {7, 5, 2, 6, 1, 4, 2, 6, 3}, + {"echo", "lima", "charlie", "whiskey", "golf", "papa", "alfa", "india", "foxtrot", "kilo"} +} + +for array as a do + print($"Before: \{{a:concat(", ")}}") + a:sort() + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-1.ps1 b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-1.ps1 new file mode 100644 index 0000000000..44bcd433dc --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-1.ps1 @@ -0,0 +1,52 @@ +Function SortThree( [Array] $data ) +{ + if( $data[ 0 ] -gt $data[ 1 ] ) + { + if( $data[ 0 ] -lt $data[ 2 ] ) + { + $data = $data[ 1, 0, 2 ] + } elseif ( $data[ 1 ] -lt $data[ 2 ] ){ + $data = $data[ 1, 2, 0 ] + } else { + $data = $data[ 2, 1, 0 ] + } + } else { + if( $data[ 0 ] -gt $data[ 2 ] ) + { + $data = $data[ 2, 0, 1 ] + } elseif( $data[ 1 ] -gt $data[ 2 ] ) { + $data = $data[ 0, 2, 1 ] + } + } + $data +} + +Function QuickSort( [Array] $data, $rand = ( New-Object Random ) ) +{ + $datal = $data.length + if( $datal -gt 3 ) + { + [void] $datal-- + $median = ( SortThree $data[ 0, ( $rand.Next( 1, $datal - 1 ) ), -1 ] )[ 1 ] + $lt = @() + $eq = @() + $gt = @() + $data | ForEach-Object { if( $_ -lt $median ) { $lt += $_ } elseif( $_ -eq $median ) { $eq += $_ } else { $gt += $_ } } + $lt = ( QuickSort $lt $rand ) + $gt = ( QuickSort $gt $rand ) + $data = @($lt) + $eq + $gt + } elseif( $datal -eq 3 ) { + $data = SortThree( $data ) + } elseif( $datal -eq 2 ) { + if( $data[ 0 ] -gt $data[ 1 ] ) + { + $data = $data[ 1, 0 ] + } + } + $data +} + +QuickSort 5,3,1,2,4 +QuickSort 'e','c','a','b','d' +QuickSort 0.5,0.3,0.1,0.2,0.4 +$l = 100; QuickSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.ps1 b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.ps1 new file mode 100644 index 0000000000..e6d08dae43 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.ps1 @@ -0,0 +1,15 @@ +function quicksort($array) { + $less, $equal, $greater = @(), @(), @() + if( $array.Count -gt 1 ) { + $pivot = $array[0] + foreach( $x in $array) { + if($x -lt $pivot) { $less += @($x) } + elseif ($x -eq $pivot) { $equal += @($x)} + else { $greater += @($x) } + } + $array = (@(quicksort $less) + @($equal) + @(quicksort $greater)) + } + $array +} +$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) +"$(quicksort $array)" diff --git a/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-3.ps1 b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-3.ps1 new file mode 100644 index 0000000000..b228e6cdce --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-3.ps1 @@ -0,0 +1,15 @@ +function quicksort($in) { + $n = $in.count + switch ($n) { + 0 {} + 1 { $in[0] } + 2 { if ($in[0] -lt $in[1]) {$in[0], $in[1]} else {$in[1], $in[0]} } + default { + $pivot = $in | get-random + $lt = $in | ? {$_ -lt $pivot} + $eq = $in | ? {$_ -eq $pivot} + $gt = $in | ? {$_ -gt $pivot} + @(quicksort $lt) + @($eq) + @(quicksort $gt) + } + } +} diff --git a/Task/Sorting-algorithms-Quicksort/RISC-V-Assembly/sorting-algorithms-quicksort.asm b/Task/Sorting-algorithms-Quicksort/RISC-V-Assembly/sorting-algorithms-quicksort.asm new file mode 100644 index 0000000000..58f1ce3836 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/RISC-V-Assembly/sorting-algorithms-quicksort.asm @@ -0,0 +1,227 @@ +# riscv assembly raspberry pico2 rp2350 +# program quicksort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +#tabNumber: .int 9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call quickSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* quick sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the last element */ +quickSort: + addi sp, sp, -16 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + bge a1,a2,100f # first > last ? -> end + mv s0,a0 # save address area + mv s1,a1 # save first indice + mv s2,a2 # save last indice + call partition # partitioning + addi a2,a0,-1 # index partition - 1 + mv a1,s1 # move first index + mv s1,a0 # save partition index + mv a0,s0 # array address + call quickSort # sort lower part + addi a1,s1,1 # partition index + 1 + mv a2,s2 # last index + mv a0,s0 + call quickSort # sort higter part + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + addi sp, sp, 16 + ret +/******************************************************************/ +/* shell sort */ +/******************************************************************/ +/* a0 contains the address of table */ +/* a1 contains index of first item */ +/* a2 contains index of last item */ +partition: # INFO: partition + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + mv t0,a1 # init with first index + mv t1,a1 # init with first index + sh2add t2,a2,a0 + lw t3,(t2) # load value last index +1: # begin loop + sh2add t2,t1,a0 + lw t4,(t2) # load value + bge t4,t3,2f # compare value 2 + sh2add t2,t0,a0 # if value2 < value 1 -> swap values + lw t5,(t2) + sh2add t2,t0,a0 + sw t4,(t2) + sh2add t2,t1,a0 + sw t5,(t2) + addi t0,t0,1 # increment index +2: + addi t1,t1,1 # increment index 2 + blt t1,a2,1b # < maxi -> loop + sh2add t2,t0,a0 # else swap value + lw t5,(t2) + sh2add t2,t0,a0 + sw t3,(t2) + sh2add t2,a2,a0 + sw t5,(t2) + mv a0,t0 # return index partition + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku b/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku index 5287953494..5353fcd21b 100644 --- a/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku +++ b/Task/Sorting-algorithms-Quicksort/Raku/sorting-algorithms-quicksort-5.raku @@ -1,5 +1,7 @@ -say "x" x 11 ~ " Benchmarking " ~ "x" x 11; +# run in a terminal: "zef install Benchmark" to install from https://raku.land use Benchmark; + +say "x" x 11 ~ " Benchmarking " ~ "x" x 11; my $runs = 5; my $elems = 10 * Kernel.cpu-cores * 2**10; my @unsorted of Str = ('a'..'z').roll(8).join xx $elems; @@ -22,7 +24,7 @@ my %results = timethese $runs, { my @metrics = ; my $msg-row = "%.4f\t" x @metrics.elems ~ '%s'; -say @metrics.join("\t"); -for %results.kv -> $name, %m { - say sprintf($msg-row, %m{@metrics}, $name); +for %results.sort( *.value ) { + once say @metrics.join("\t"); # header + say sprintf($msg-row, .value{@metrics}, .key) } diff --git a/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vbs b/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vbs new file mode 100644 index 0000000000..d08ff7f7a4 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vbs @@ -0,0 +1,35 @@ +Function quicksort(arr,s,n) + If n < 2 Then + Exit Function + End If + t = s + n - 1 + l = s + r = t + p = arr(Int((l + r)/2)) + Do Until l > r + Do While arr(l) < p + l = l + 1 + Loop + Do While arr(r) > p + r = r -1 + Loop + If l <= r Then + tmp = arr(l) + arr(l) = arr(r) + arr(r) = tmp + l = l + 1 + r = r - 1 + End If + Loop + If s < r Then + Call quicksort(arr,s,r-s+1) + End If + If l < t Then + Call quicksort(arr,l,t-l+1) + End If + quicksort = arr +End Function + +myarray=Array(9,8,7,6,5,5,4,3,2,1,0,-1) +m = quicksort(myarray,0,12) +WScript.Echo Join(m,",") diff --git a/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.adb b/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.adb new file mode 100644 index 0000000000..c9e849b58b --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Ada/sorting-algorithms-radix-sort.adb @@ -0,0 +1,83 @@ +with Ada.Text_IO; +procedure Radix_Sort is + type Integer_Array is array (Positive range <>) of Integer; + + procedure Least_Significant_Radix_Sort (Data : in out Integer_Array; Base : Positive := 10) is + type Bucket is record + Count : Natural := 0; + Content : Integer_Array (Data'Range); + end record; + + subtype Bucket_Index is Integer range -Base + 1 .. Base - 1; + type Bucket_Array is array (Bucket_Index) of Bucket; + + procedure Append (To : in out Bucket; Item : Integer) is + begin + To.Count := To.Count + 1; + To.Content (To.Count) := Item; + end Append; + + function Get_Nth_Digit (Value : Integer; N : Positive) return Integer is + Result : Integer := (Value / (Base ** (N - 1))) mod Base; + begin + if Value < 0 then + Result := -Result; + end if; + return Result; + end Get_Nth_Digit; + + function Get_Maximum return Natural is + Result : Natural := 0; + begin + for I in Data'Range loop + if abs (Data (I)) > Result then + Result := abs (Data (I)); + end if; + end loop; + return Result; + end Get_Maximum; + + function Split (Pass : Positive) return Bucket_Array is + Buckets : Bucket_Array; + begin + for I in Data'Range loop + Append (To => Buckets (Get_Nth_Digit (Data (I), Pass)), + Item => Data (I)); + end loop; + return Buckets; + end Split; + + function Merge (Buckets : Bucket_Array) return Integer_Array is + Result : Integer_Array (Data'Range); + Current_Index : Positive := 1; + begin + for Sublist in Buckets'Range loop + for Item in 1 .. Buckets (Sublist).Count loop + Result (Current_Index) := Buckets (Sublist).Content (Item); + Current_Index := Current_Index + 1; + end loop; + end loop; + return Result; + end Merge; + + Max_Number : Natural := Get_Maximum; + Digit_Count : Positive := 1; + begin + -- count digits of biggest number + while Max_Number > Base loop + Digit_Count := Digit_Count + 1; + Max_Number := Max_Number / Base; + end loop; + for Pass in 1 .. Digit_Count loop + Data := Merge (Split (Pass)); + end loop; + end Least_Significant_Radix_Sort; + + Test_Array : Integer_Array := (170, 45, 75, -90, -802, 24, 2, 66); +begin + Least_Significant_Radix_Sort (Test_Array, 4); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + end loop; + Ada.Text_IO.New_Line; +end Radix_Sort; diff --git a/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-1.c b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-1.c new file mode 100644 index 0000000000..0f837315f6 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-1.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +// Get size of statically allocated array +#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) +// Generate random number in the interval [M,N] +#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); + +static void swap(unsigned *a, unsigned *b) { + unsigned tmp = *a; + *a = *b; + *b = tmp; +} + +/* sort unsigned ints */ +static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) +{ + if (!bit || to < from + 1) return; + + unsigned *ll = from, *rr = to - 1; + for (;;) { + /* find left most with bit, and right most without bit, swap */ + while (ll < rr && !(*ll & bit)) ll++; + while (ll < rr && (*rr & bit)) rr--; + if (ll >= rr) break; + swap(ll, rr); + } + + if (!(bit & *ll) && ll < to) ll++; + bit >>= 1; + + rad_sort_u(from, ll, bit); + rad_sort_u(ll, to, bit); +} + +/* sort signed ints: flip highest bit, sort as unsigned, flip back */ +static void radix_sort(int *a, const size_t len) +{ + size_t i; + unsigned *x = (unsigned*) a; + + for (i = 0; i < len; i++) + x[i] ^= INT_MIN; + + rad_sort_u(x, x + len, INT_MIN); + + for (i = 0; i < len; i++) + x[i] ^= INT_MIN; +} + +int main(void) +{ + + srand(time(NULL)); + int x[16]; + + for (size_t i = 0; i < ARR_LEN(x); i++) + x[i] = RAND_RNG(-128,127) + + radix_sort(x, ARR_LEN(x)); + + for (size_t i = 0; i < ARR_LEN(x); i++) + printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); +} diff --git a/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-2.c b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-2.c new file mode 100644 index 0000000000..84d49f1453 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/C/sorting-algorithms-radix-sort-2.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include + +// Get size of statically allocated array +#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) +// Generate random number in the interval [M,N] +#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); + +void radix_sort(const size_t n, int *array) { + int *bit0_nums = (int*)malloc(n*sizeof(int)); + int *bit1_nums = (int*)malloc(n*sizeof(int)); + for (size_t ibit=0; ibit<8*sizeof(int)-1; ibit++) { + size_t nbit0 = 0; + size_t nbit1 = 0; + for (size_t i=0; i>ibit)&0b1; + if (bit == 1) { + bit1_nums[nbit1] = array[i]; + nbit1++; + } else { + bit0_nums[nbit0] = array[i]; + nbit0++; + } + } + for (size_t i=0; i>ibit)&0b1; + if (bit == 1) { + bit1_nums[nbit1] = array[i]; + nbit1++; + } else { + bit0_nums[nbit0] = array[i]; + nbit0++; + } + } + for (size_t i=0; i +#include +#include +#include + +// Get size of statically allocated array +#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR) +// Generate random number in the interval [M,N] +#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1)); + +void radix_sort(const size_t n, int *array) { + int *nums = (int*)malloc(2*n*sizeof(int)); + for (size_t ibit=0; ibit<8*sizeof(int)-1; ibit++) { + size_t nnums[2] = {0, 0}; + for (size_t i=0; i>ibit)&0b1; + nums[bit*n+nnums[bit]] = array[i]; + nnums[bit]++; + } + // To make it easily extendable to more buckets + size_t offset = 0; + for (int ibuck=0; ibuck<2; ibuck++) { + for (size_t i=0; i>ibit)&0b1; + nums[bit*n+nnums[bit]] = array[i]; + nnums[bit]++; + } + // To make it easily extendable to more buckets + size_t offset = 0; + for (int ibuck=1; ibuck<2; ibuck++) { + for (size_t i=0; i 0 do + count_sort(a, exp) + exp *= 10 + end + -- If there were negative elements, reduce all elements by -min. + if min < 0 then + for i = 1, #a do a[i] += min end + end +end + +local aa = {{4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {170, 45, 75, 90, 2, 24, -802, -66}} +for aa as a do + print($"Before: \{{a:concat(", ")}}") + radix_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.adb b/Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.adb new file mode 100644 index 0000000000..cce8d3a3a8 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Ada/sorting-algorithms-selection-sort.adb @@ -0,0 +1,31 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Selection_Sort is + + type Integer_Array is array (Positive range <>) of Integer; + procedure Sort (A : in out Integer_Array) is + Min : Positive; + Temp : Integer; + begin + for I in A'First..A'Last - 1 loop + Min := I; + for J in I + 1..A'Last loop + if A (Min) > A (J) then + Min := J; + end if; + end loop; + if Min /= I then + Temp := A (I); + A (I) := A (Min); + A (Min) := Temp; + end if; + end loop; + end Sort; + + A : Integer_Array := (4, 9, 3, -2, 0, 7, -5, 1, 6, 8); +begin + Sort (A); + for I in A'Range loop + Put (Integer'Image (A (I)) & " "); + end loop; +end Test_Selection_Sort; diff --git a/Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cob b/Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cob new file mode 100644 index 0000000000..46bcb31363 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/COBOL/sorting-algorithms-selection-sort.cob @@ -0,0 +1,28 @@ + PERFORM E-SELECTION VARYING WB-IX-1 FROM 1 BY 1 + UNTIL WB-IX-1 = WC-SIZE. + +... + + E-SELECTION SECTION. + E-000. + SET WC-LOWEST TO WB-IX-1. + ADD 1 WC-LOWEST GIVING WC-START + + PERFORM F-PASS VARYING WB-IX-2 FROM WC-START BY 1 + UNTIL WB-IX-2 > WC-SIZE. + + IF WB-IX-1 NOT = WC-LOWEST + MOVE WB-ENTRY(WC-LOWEST) TO WC-TEMP + MOVE WB-ENTRY(WB-IX-1) TO WB-ENTRY(WC-LOWEST) + MOVE WC-TEMP TO WB-ENTRY(WB-IX-1). + + E-999. + EXIT. + + F-PASS SECTION. + F-000. + IF WB-ENTRY(WB-IX-2) < WB-ENTRY(WC-LOWEST) + SET WC-LOWEST TO WB-IX-2. + + F-999. + EXIT. diff --git a/Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.eu b/Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.eu new file mode 100644 index 0000000000..177b2bb0ac --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Euphoria/sorting-algorithms-selection-sort.eu @@ -0,0 +1,24 @@ +function selection_sort(sequence s) + object tmp + integer m + for i = 1 to length(s) do + m = i + for j = i+1 to length(s) do + if compare(s[j],s[m]) < 0 then + m = j + end if + end for + tmp = s[i] + s[i] = s[m] + s[m] = tmp + end for + return s +end function + +include misc.e +constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1} + +puts(1,"Before: ") +pretty_print(1,s,{2}) +puts(1,"\nAfter: ") +pretty_print(1,selection_sort(s),{2}) diff --git a/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-1.hs similarity index 100% rename from Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs rename to Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-1.hs diff --git a/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-2.hs b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-2.hs new file mode 100644 index 0000000000..01bab22efc --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-2.hs @@ -0,0 +1,21 @@ +import Data.List (delete) + +-- Sub-Function +selectionSort :: Ord a => [a] -> [a] +selectionSort [] = [] +selectionSort xs = + smallest : selectionSort (delete smallest xs) + where smallest = minimum XS + +-- Main test driver +main :: IO () +main = do + let list_of_items = [ 'A', 'S', 'O', 'R', 'I', 'N', 'G', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] + + putStrLn "Original list:" + print list_of_items + + let sorted_list_of_items = selectionSort list_of_items + + putStrLn "Sorted list:" + print sorted_list_of_items diff --git a/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-3.hs b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-3.hs new file mode 100644 index 0000000000..fe19d545ca --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort-3.hs @@ -0,0 +1,42 @@ +-- The main sorting function +selectionSort :: Ord a => [a] -> [a] +selectionSort [] = [] +selectionSort unsortedList = + smallestElement : selectionSort remainingElements + where + -- Find the smallest element in the list + smallestElement = findSmallest unsortedList + + -- Remove the first occurrence of that smallest element + remainingElements = removeFirst smallestElement unsortedList + + +-- Function to find the smallest element in a list +-- Uses recursion to compare elements +findSmallest :: Ord a => [a] -> a +findSmallest [singleElement] = singleElement +findSmallest (firstElement:restOfList) = + min firstElement (findSmallest restOfList) + + +-- Removes the first occurrence of a value from a list +-- This function is pure and returns a new list +removeFirst :: Eq a => a -> [a] -> [a] +removeFirst _ [] = [] +removeFirst target (current:rest) + | target == current = rest + | otherwise = current : removeFirst target rest + + +-- Example usage +main :: IO () +main = do + let list_of_items = [ 'A', 'S', 'O', 'R', 'I', 'N', 'G', 'E', 'X', 'A', 'M', 'P', 'L', 'E'] + + putStrLn "Original list:" + print list_of_items + + let sorted_list_of_items = selectionSort list_of_items + + putStrLn "Sorted list:" + print sorted_list_of_items diff --git a/Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.hx b/Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.hx new file mode 100644 index 0000000000..b733f4a4a2 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Haxe/sorting-algorithms-selection-sort.hx @@ -0,0 +1,38 @@ +class SelectionSort { + @:generic + public static function sort(arr:Array) { + var len = arr.length; + for (index in 0...len) { + var minIndex = index; + for (remainingIndex in (index+1)...len) { + if (Reflect.compare(arr[minIndex], arr[remainingIndex]) > 0) + minIndex = remainingIndex; + } + if (index != minIndex) { + var temp = arr[index]; + arr[index] = arr[minIndex]; + arr[minIndex] = temp; + } + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers:' + integerArray); + SelectionSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + SelectionSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + SelectionSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Selection-sort/Pluto/sorting-algorithms-selection-sort.pluto b/Task/Sorting-algorithms-Selection-sort/Pluto/sorting-algorithms-selection-sort.pluto new file mode 100644 index 0000000000..f301b40291 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Pluto/sorting-algorithms-selection-sort.pluto @@ -0,0 +1,21 @@ +local function selection_sort(a) + for i = 1, #a- 1 do + local amin = a[i] + local imin = i + for j = i + 1, #a do + if a[j] < amin then + amin = a[j] + imin = j + end + end + a[i], a[imin] = amin, a[i] + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + selection_sort(a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.ps1 b/Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.ps1 new file mode 100644 index 0000000000..e5e878a874 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/PowerShell/sorting-algorithms-selection-sort.ps1 @@ -0,0 +1,20 @@ +Function SelectionSort( [Array] $data ) +{ + $datal=$data.length-1 + 0..( $datal - 1 ) | ForEach-Object { + $min = $data[ $_ ] + $mini = $_ + ( $_ + 1 )..$datal | ForEach-Object { + if( $data[ $_ ] -lt $min ) { + $min = $data[ $_ ] + $mini = $_ + } + } + $temp = $data[ $_ ] + $data[ $_ ] = $min + $data[ $mini ] = $temp + } + $data +} + +$l = 100; SelectionSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) ) diff --git a/Task/Sorting-algorithms-Selection-sort/RISC-V-Assembly/sorting-algorithms-selection-sort.asm b/Task/Sorting-algorithms-Selection-sort/RISC-V-Assembly/sorting-algorithms-selection-sort.asm new file mode 100644 index 0000000000..fa4dc24756 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/RISC-V-Assembly/sorting-algorithms-selection-sort.asm @@ -0,0 +1,197 @@ +# riscv assembly raspberry pico2 rp2350 +# program selectionsort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,11,1,4,10,6 +#tabNumber: .int 11,10,9,8,7,6,5,4,3,2,1 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call selectionSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* sort control */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* selection sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the last element */ +selectionSort: + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) # save registers + sw s0, 4(sp) + sw s1, 8(sp) + mv t1,a1 +1: # start loop 1 + mv t0,t1 # start index + addi t4,t0,1 +2: # start loop 2 + sh2add t6,t0,a0 + lw s0,(t6) + sh2add s1,t4,a0 + lw t2,(s1) + bge t2,s0,3f + mv t0,t4 +3: + addi t4,t4,1 + ble t4,a2,2b + beq t0,t1,4f + sh2add t6,t0,a0 + lw s0,(t6) + sh2add s1,t1,a0 + lw t2,(s1) + sw t2,(t6) # swap value + sw s0,(s1) +4: + addi t1,t1,1 + ble t1,a2,1b # end ? no -> loop 1 + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + addi sp, sp, 12 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vbs b/Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vbs new file mode 100644 index 0000000000..d7460f747e --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vbs @@ -0,0 +1,19 @@ +Function Selection_Sort(s) + arr = Split(s,",") + For i = 0 To UBound(arr) + For j = i To UBound(arr) + temp = arr(i) + If arr(j) < arr(i) Then + arr(i) = arr(j) + arr(j) = temp + End If + Next + Next + Selection_Sort = (Join(arr,",")) +End Function + +WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" +WScript.StdOut.WriteLine +WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") +WScript.StdOut.WriteLine +WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d") diff --git a/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.adb b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.adb new file mode 100644 index 0000000000..fbcc30e0ee --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-1.adb @@ -0,0 +1,7 @@ +generic + type Element_Type is digits <>; + type Index_Type is (<>); + type Array_Type is array(Index_Type range <>) of Element_Type; +package Shell_Sort is + procedure Sort(Item : in out Array_Type); +end Shell_Sort; diff --git a/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.adb b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.adb new file mode 100644 index 0000000000..6a2af6e13b --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Ada/sorting-algorithms-shell-sort-2.adb @@ -0,0 +1,30 @@ +package body Shell_Sort is + + ---------- + -- Sort -- + ---------- + + procedure Sort (Item : in out Array_Type) is + Increment : Natural := Index_Type'Pos(Item'Last) / 2; + J : Index_Type; + Temp : Element_Type; + begin + while Increment > 0 loop + for I in Index_Type'Val(Increment) .. Item'Last loop + J := I; + Temp := Item(I); + while J > Index_Type'val(Increment) and then Item (Index_Type'Val(Index_Type'Pos(J) - Increment)) > Temp loop + Item(J) := Item (Index_Type'Val(Index_Type'Pos(J) - Increment)); + J := Index_Type'Val(Index_Type'Pos(J) - Increment); + end loop; + Item(J) := Temp; + end loop; + if Increment = 2 then + Increment := 1; + else + Increment := Increment * 5 / 11; + end if; + end loop; + end Sort; + +end Shell_Sort; diff --git a/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cob b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cob new file mode 100644 index 0000000000..864b59a804 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-1.cob @@ -0,0 +1,100 @@ + ******************************************************* + IDENTIFICATION DIVISION. + ******************************************************* + PROGRAM-ID. SHELLSRT. + ************************************************************ + *** SHELLSORT **** + ************************************************************ + ENVIRONMENT DIVISION. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 II PIC S9(008) COMP-5. + 01 IJ PIC S9(008) COMP-5. + 01 IZ PIC S9(008) COMP-5. + 01 IA PIC S9(008) COMP-5. + 01 STRT1 PIC S9(008) COMP-5. + 01 STRT2 PIC S9(008) COMP-5. + 01 LGT PIC S9(008) COMP-5. + 01 ORG PIC S9(008) COMP-5. + 01 DST PIC S9(008) COMP-5. + * + 01 GAP PIC S9(008) COMP-5. + 01 NEGAP PIC S9(008) COMP-5. + 01 TEMP PIC X(32768). + 77 KEY-RESULT PIC X. + * + LINKAGE SECTION. + 01 SRT-ARRAY PIC X(1000000). + 01 NUM-ITEM PIC 9(008) COMP-5. + 01 SRT-DATA. + 03 LGT-ITEM PIC 9(004) COMP-5. + 03 SRT-KEYS. + 05 SRT-KEY OCCURS 10. + 07 K-START PIC S9(004) COMP-5. + 07 K-LENGTH PIC S9(004) COMP-5. + 07 K-ASC PIC X. + * + * P R O C E D U R E D I V I S I O N + * + PROCEDURE DIVISION USING SRT-ARRAY NUM-ITEM SRT-DATA. + + COMPUTE GAP = NUM-ITEM / 2. + PERFORM UNTIL GAP < 1 + COMPUTE NEGAP = GAP * -1 + PERFORM VARYING II FROM GAP BY 1 + UNTIL II GREATER NUM-ITEM + MOVE ' ' TO KEY-RESULT + COMPUTE ORG = (II - 1) * LGT-ITEM + 1 + MOVE SRT-ARRAY(ORG:LGT-ITEM) TO TEMP(1:LGT-ITEM) + PERFORM VARYING IJ FROM II BY NEGAP + UNTIL IJ NOT GREATER GAP + OR (KEY-RESULT NOT EQUAL '<' AND ' ') + COMPUTE IA = IJ - GAP + IF IA < 1 + MOVE 1 TO IA + END-IF + PERFORM COMPARE-KEYS + IF KEY-RESULT = '<' + COMPUTE ORG = (IA - 1) * LGT-ITEM + 1 + COMPUTE DST = (IJ - 1) * LGT-ITEM + 1 + MOVE SRT-ARRAY(ORG:LGT-ITEM) + TO SRT-ARRAY(DST:LGT-ITEM) + COMPUTE DST = (IA - 1) * LGT-ITEM + 1 + MOVE TEMP(1:LGT-ITEM) TO SRT-ARRAY(DST:LGT-ITEM) + END-IF + END-PERFORM + END-PERFORM + IF GAP = 2 + MOVE 1 TO GAP + ELSE + COMPUTE GAP = GAP / 2.2 + END-IF + END-PERFORM. + GOBACK. + * + COMPARE-KEYS. + MOVE ' ' TO KEY-RESULT + PERFORM VARYING IZ FROM 1 BY 1 + UNTIL IZ GREATER 10 + OR (KEY-RESULT NOT EQUAL '=' AND ' ') + IF SRT-KEY(IZ) GREATER LOW-VALUES + COMPUTE STRT1 = (IJ - 1) * LGT-ITEM + K-START(IZ) + COMPUTE STRT2 = (IA - 1) * LGT-ITEM + K-START(IZ) + MOVE K-LENGTH(IZ) TO LGT + IF SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'A' + OR SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'D' + MOVE '>' TO KEY-RESULT + END-IF + IF SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'A' + OR SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND + K-ASC(IZ) EQUAL 'D' + MOVE '<' TO KEY-RESULT + END-IF + END-IF + END-PERFORM. + IF KEY-RESULT = ' ' + MOVE '=' TO KEY-RESULT + END-IF. diff --git a/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-2.cob b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-2.cob new file mode 100644 index 0000000000..cd22b51835 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/COBOL/sorting-algorithms-shell-sort-2.cob @@ -0,0 +1,55 @@ + C-PROCESS SECTION. + C-000. + DISPLAY "SORT STARTING". + + DIVIDE WC-SIZE BY 2 GIVING WC-GAP. + + PERFORM E-PROCESS-GAP UNTIL WC-GAP = 0. + + DISPLAY "SORT FINISHED". + + C-999. + EXIT. + + + E-PROCESS-GAP SECTION. + E-000. + PERFORM F-SELECTION VARYING WB-IX-1 FROM WC-GAP BY 1 + UNTIL WB-IX-1 > WC-SIZE. + + DIVIDE WC-GAP BY 2.2 GIVING WC-GAP. + + E-999. + EXIT. + + F-SELECTION SECTION. + F-000. + SET WB-IX-2 TO WB-IX-1. + MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP. + + SET WB-IX-3 TO WB-IX-2. + SET WB-IX-3 DOWN BY WC-GAP. + PERFORM G-PASS UNTIL WB-IX-2 NOT > WC-GAP + * The next line logically reads : + * or wb-entry(wb-ix-2 - wc-gap) not > wc-temp. + OR WB-ENTRY(WB-IX-3) NOT > WC-TEMP. + + IF WB-IX-1 NOT = WB-IX-2 + MOVE WC-TEMP TO WB-ENTRY(WB-IX-2). + + F-999. + EXIT. + + G-PASS SECTION. + * Note that WB-IX-3 is WC-GAP less than WB-IX-2. + * Logically this should be : + * move wb-entry(wb-ix-2 - wc-gap) to wb-entry(wb-ix-2). + * set wb-ix-2 down by wc-gap. + * Unfortunately wb-entry(wb-ix-2 - wc-gap) is not legal in C2 cobol + G-000. + MOVE WB-ENTRY(WB-IX-3) TO WB-ENTRY(WB-IX-2). + SET WB-IX-2 DOWN BY WC-GAP. + SET WB-IX-3 DOWN BY WC-GAP. + + G-999. + EXIT. diff --git a/Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.eu b/Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.eu new file mode 100644 index 0000000000..9ef6454c66 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Euphoria/sorting-algorithms-shell-sort.eu @@ -0,0 +1,24 @@ +function shell_sort(sequence s) + integer gap,j + object temp + gap = floor(length(s)/2) + while gap > 0 do + for i = gap to length(s) do + temp = s[i] + j=i-gap + while j >= 1 and compare(temp, s[j]) <= 0 do + s[j+gap]=s[j] + j -= gap + end while + s[j+gap] = temp + end for + gap = floor(gap/2) + end while + return s +end function + +constant s = rand(repeat(1000,10)) +puts(1,"Before: ") +? s +puts(1,"After: ") +? shell_sort(s) diff --git a/Task/Sorting-algorithms-Shell-sort/Haxe/sorting-algorithms-shell-sort.hx b/Task/Sorting-algorithms-Shell-sort/Haxe/sorting-algorithms-shell-sort.hx new file mode 100644 index 0000000000..8ed221fc32 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Haxe/sorting-algorithms-shell-sort.hx @@ -0,0 +1,38 @@ +class ShellSort { + @:generic + public static function sort(arr:Array) { + var h = arr.length; + while (h > 0) { + h >>= 1; + for (i in h...arr.length) { + var k = arr[i]; + var j = i; + while (j >= h && Reflect.compare(k, arr[j - h]) < 0) { + arr[j] = arr[j - h]; + j -= h; + } + arr[j] = k; + } + } + } +} + +class Main { + static function main() { + var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]; + var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, + 3.5, 0.0, -4.1, -9.5]; + var stringArray = ['We', 'hold', 'these', 'truths', 'to', + 'be', 'self-evident', 'that', 'all', + 'men', 'are', 'created', 'equal']; + Sys.println('Unsorted Integers: ' + integerArray); + ShellSort.sort(integerArray); + Sys.println('Sorted Integers: ' + integerArray); + Sys.println('Unsorted Floats: ' + floatArray); + ShellSort.sort(floatArray); + Sys.println('Sorted Floats: ' + floatArray); + Sys.println('Unsorted Strings: ' + stringArray); + ShellSort.sort(stringArray); + Sys.println('Sorted Strings: ' + stringArray); + } +} diff --git a/Task/Sorting-algorithms-Shell-sort/Pluto/sorting-algorithms-shell-sort.pluto b/Task/Sorting-algorithms-Shell-sort/Pluto/sorting-algorithms-shell-sort.pluto new file mode 100644 index 0000000000..7d6f880b45 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Pluto/sorting-algorithms-shell-sort.pluto @@ -0,0 +1,27 @@ +local fmt = require "fmt" + +local function shell_sort(a) + local n = #a + local gaps = {701, 301, 132, 57, 23, 10, 4, 1} + for gaps as gap do + if gap < n then + for i = gap + 1, n do + local t = a[i] + local j = i + while j > gap and a[j - gap] > t do + a[j] = a[j - gap] + j -= gap + end + a[j] = t + end + end + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + fmt.print("Before: %,s", a) + shell_sort(a) + fmt.print("After : %,s", a) + print() +end diff --git a/Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.ps1 b/Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.ps1 new file mode 100644 index 0000000000..58cd3d5f80 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/PowerShell/sorting-algorithms-shell-sort.ps1 @@ -0,0 +1,26 @@ +Function ShellSort( [Array] $data ) +{ + # http://oeis.org/A108870 + $A108870 = [Int64[]] ( 1, 4, 9, 20, 46, 103, 233, 525, 1182, 2660, 5985, 13467, 30301, 68178, 153401, 345152, 776591, 1747331, 3931496, 8845866, 19903198, 44782196, 100759940, 226709866, 510097200, 1147718700, 2582367076, 5810325920, 13073233321, 29414774973 ) + $datal = $data.length - 1 + $inci = [Array]::BinarySearch( $A108870, [Int64] ( [Math]::Floor( $datal / 2 ) ) ) + if( $inci -lt 0 ) + { + $inci = ( $inci -bxor -1 ) - 1 + } + $A108870[ $inci..0 ] | ForEach-Object { + $inc = $_ + $_..$datal | ForEach-Object { + $temp = $data[ $_ ] + $j = $_ + for( ; ( $j -ge $inc ) -and ( $data[ $j - $inc ] -gt $temp ); $j -= $inc ) + { + $data[ $j ] = $data[ $j - $inc ] + } + $data[ $j ] = $temp + } + } + $data +} + +$l = 10000; ShellSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) ) diff --git a/Task/Sorting-algorithms-Shell-sort/RISC-V-Assembly/sorting-algorithms-shell-sort.asm b/Task/Sorting-algorithms-Shell-sort/RISC-V-Assembly/sorting-algorithms-shell-sort.asm new file mode 100644 index 0000000000..79ba5fbb20 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/RISC-V-Assembly/sorting-algorithms-shell-sort.asm @@ -0,0 +1,188 @@ +# riscv assembly raspberry pico2 rp2350 +# program shellsort.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessSortOk: .asciz "Area sorted.\n" +szMessSortNok: .asciz "Area not sorted !!!!!.\n" +szLibSort: .asciz "\nAfter sort\n" +szSpace: .asciz " " + +.align 2 +tabNumber: .int 5,7,8,3,2,9,1,4,6 +.equ NBTABNUMBER1, . - tabNumber +.equ NBTABNUMBER, NBTABNUMBER1 / 4 # compute items number + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la s0,tabNumber # number array address + li s1,0 + li s2,NBTABNUMBER +2: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,2b + la a0,szCariageReturn + call writeString + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call shellSort # sort + mv a0,s0 # number array address + li a1,0 # first item + addi a2,s2,-1 # last item + call isSorted + + la a0,szLibSort + call writeString + + li s1,0 +3: # item loop + sh2add t3,s1,s0 # compute item address + lw a0,(t3) + call displayResultD + add s1,s1,1 + blt s1,s2,3b + la a0,szCariageReturn + call writeString + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/**********************************************/ +/* display Result décimal */ +/**********************************************/ +/* a0 value */ +.equ LGZONECONV, 20 +displayResultD: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + la a1,sConvArea # conversion result address + call conversion10 # binary conversion + la a0,sConvArea # message address + call writeString # display message + la a0,szSpace + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/**********************************************/ +/* */ +/**********************************************/ +/* a0 area address */ +/* a1 first element */ +/* a2 last element */ +.equ LGZONECONV, 20 +isSorted: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) + mv t0,a1 + sh2add t1,t0,a0 + lw t2,(t1) # load first element +1: + addi t0,t0,1 + ble t0,a2,2f # end indice ? + la a0,szMessSortOk + call writeString + li a0,1 # yes -> area is sorted + j 100f +2: + sh2add t1,t0,a0 + lw t3,(t1) # load next element + bge t3,t2,3f # >= ? + la a0,szMessSortNok + call writeString + li a0,0 # no -> area is not sorted + j 100f +3: + mv t2,t3 + j 1b +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/******************************************************************/ +/* shell sort */ +/******************************************************************/ +/* a0 contains array address */ +/* a1 contains the first element */ +/* a2 contains the last element */ +shellSort: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers + sub t0,a2,a1 # init gap + addi t0,t0,1 +1: # start loop 1 + srli t0,t0,1 # gap = gap / 2 + beqz t0,100f # if gap = 0 -> end + mv t3,t0 # init indice loop 1 + add t3,t3,a1 # add first indice +2: # start loop 2 + sh2add t2,t3,a0 + lw t4,(t2) # load value A[i] + mv t5,t3 # index j +3: # start loop 3 + sub t1,t5,a1 # - first indice + blt t1,t0,4f # indice < gap + sub t6,t5,t0 # index = indice - gap + sh2add t2,t6,a0 + lw t6,(t2) # load value A[j] + bge t4,t6,4f # compare value A[i] and A[j] + sh2add t2,t5,a0 + sw t6,(t2) # store value A[j+1] + sub t5,t5,t0 # index = indice - gap + j 3b # and loop 3 +4: + sh2add t2,t5,a0 + sw t4,(t2) # store value A[i] in A[j+1] + addi t3,t3,1 # increment index i + ble t3,a2,2b # end ? no -> loop 2 + j 1b # loop 1 +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../../includeFunctions.s" diff --git a/Task/Sorting-algorithms-Shell-sort/V-(Vlang)/sorting-algorithms-shell-sort.v b/Task/Sorting-algorithms-Shell-sort/V-(Vlang)/sorting-algorithms-shell-sort.v index a64b623108..4e5190b6dd 100644 --- a/Task/Sorting-algorithms-Shell-sort/V-(Vlang)/sorting-algorithms-shell-sort.v +++ b/Task/Sorting-algorithms-Shell-sort/V-(Vlang)/sorting-algorithms-shell-sort.v @@ -1,6 +1,6 @@ fn shell(mut arr []int, n int) { mut j := 0 - for h := n; h /= 2; { + for h := n; h > 0; h /= 2 { for i := h; i < n; i++ { t := arr[i] for j = i; j >= h && t < arr[j - h]; j -= h { diff --git a/Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.adb b/Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.adb new file mode 100644 index 0000000000..e541508ed1 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Ada/sorting-algorithms-sleep-sort.adb @@ -0,0 +1,15 @@ +with Ada.Text_IO; +with Ada.Command_Line; use Ada.Command_Line; +procedure SleepSort is + task type PrintTask (num : Integer); + task body PrintTask is begin + delay Duration (num) / 100.0; + Ada.Text_IO.Put(num'Img); + end PrintTask; + type TaskAcc is access PrintTask; + TaskList : array (1 .. Argument_Count) of TaskAcc; +begin + for i in TaskList'Range loop + TaskList(i) := new PrintTask(Integer'Value(Argument(i))); + end loop; +end SleepSort; diff --git a/Task/Sorting-algorithms-Sleep-sort/Assembly/sorting-algorithms-sleep-sort.asm b/Task/Sorting-algorithms-Sleep-sort/Assembly/sorting-algorithms-sleep-sort.asm new file mode 100644 index 0000000000..b17443dfee --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Assembly/sorting-algorithms-sleep-sort.asm @@ -0,0 +1,113 @@ + format ELF64 executable 3 + entry start + +; parameters: argc, argv[] on stack +start: + mov r12, [rsp] ; get argc + mov r13, 1 ; skip argv[0] + +.getargv: + cmp r13, r12 ; check completion of args + je .wait + mov rdi, [rsp+8+8*r13] ; get argv[n] + inc r13 + + mov rax, 57 ; sys_fork + syscall + + cmp rax, 0 ; continue loop in main process + jnz .getargv + + push rdi ; save pointer to sort item text + + call atoi_simple ; convert text to integer + test rax, rax ; throw out bad input + js .done + + sub rsp, 16 ; stack space for timespec + mov [rsp], rax ; seconds + mov qword [rsp+8], 0 ; nanoseconds + + lea rdi, [rsp] + xor rsi, rsi + mov rax, 35 ; sys_nanosleep + syscall + + add rsp, 16 + + pop rdi ; retrieve item text + call strlen_simple + + mov rsi, rdi + mov byte [rsi+rax], ' ' + mov rdi, 1 + mov rdx, rax + inc rdx + mov rax, 1 ; sys_write + syscall + + jmp .done + +.wait: + dec r12 ; wait for each child process + jz .done + mov rdi, 0 ; any pid + mov rsi, 0 + mov rdx, 0 + mov r10, 4 ; that has terminated + mov rax, 247 ; sys_waitid + syscall + + jmp .wait + +.done: + xor rdi, rdi + mov rax, 60 ; sys_exit + syscall + +; parameter: rdi = string pointer +; return: rax = integer conversion +atoi_simple: + push rdi + push rsi + + xor rax, rax + +.convert: + movzx rsi, byte [rdi] + test rsi, rsi ; check for null + jz .done + + cmp rsi, '0' + jl .baddigit + cmp rsi, '9' + jg .baddigit + sub rsi, 48 ; get ascii code for digit + + imul rax, 10 ; radix 10 + add rax, rsi ; add current digit to total + + inc rdi + jmp .convert + +.baddigit: + mov rax, -1 ; return error code on failed conversion + +.done: + pop rsi + pop rdi + ret ; return integer value + +; parameter: rdi = string pointer +; return: rax = length +strlen_simple: + xor rax, rax + +.compare: + cmp byte [rdi+rax], 0 + je .done + inc rax + jmp .compare + +.done: + ret diff --git a/Task/Sorting-algorithms-Sleep-sort/Emacs-Lisp/sorting-algorithms-sleep-sort.el b/Task/Sorting-algorithms-Sleep-sort/Emacs-Lisp/sorting-algorithms-sleep-sort.el new file mode 100644 index 0000000000..631d0ef092 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Emacs-Lisp/sorting-algorithms-sleep-sort.el @@ -0,0 +1,2 @@ +(dolist (i '(3 1 4 1 5 92 65 3 5 89 79 3)) + (run-with-timer (* i 0.001) nil 'message "%d" i)) diff --git a/Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.eu b/Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.eu new file mode 100644 index 0000000000..f27918ee4c --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Euphoria/sorting-algorithms-sleep-sort.eu @@ -0,0 +1,31 @@ +include get.e + +integer count + +procedure sleeper(integer key) + ? key + count -= 1 +end procedure + +sequence s, val +atom task + +s = command_line() +s = s[3..$] +if length(s)=0 then + puts(1,"Nothing to sort.\n") +else + count = 0 + for i = 1 to length(s) do + val = value(s[i]) + if val[1] = GET_SUCCESS then + task = task_create(routine_id("sleeper"),{val[2]}) + task_schedule(task,{val[2],val[2]}/10) + count += 1 + end if + end for + + while count do + task_yield() + end while +end if diff --git a/Task/Sorting-algorithms-Sleep-sort/Pluto/sorting-algorithms-sleep-sort.pluto b/Task/Sorting-algorithms-Sleep-sort/Pluto/sorting-algorithms-sleep-sort.pluto new file mode 100644 index 0000000000..a7c9d1554a --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Pluto/sorting-algorithms-sleep-sort.pluto @@ -0,0 +1,26 @@ +local n = #arg +assert(n >= 2, "There must be at least two arguments passed.") +local list = arg:mapped(|a| -> tonumber(a)):reorder() +if #list != n or !list:checkall(|e| -> math.round(e) == e and e >= 0) then + error("All arguments must be non-negative integers.") +end +local max = list:max() +local cos = table.create(max + 1) +print($"Before: {list:concat(" ")}") +for list as i do + local function sleep_sort(j) + os.sleep(1000) + coroutine.yield(j) + end + cos[i + 1] = coroutine.create(sleep_sort) +end +io.write("After : ") +for i = 0, max do + local co = cos[i + 1] + if co then + local _, v = coroutine.resume(co, i) + io.write($"{v} ") + io.output():flush() + end +end +print() diff --git a/Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.adb b/Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.adb new file mode 100644 index 0000000000..22d8bdd6ff --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Ada/sorting-algorithms-stooge-sort.adb @@ -0,0 +1,32 @@ +with Ada.Text_IO; +procedure Stooge is + type Integer_Array is array (Positive range <>) of Integer; + procedure Swap (Left, Right : in out Integer) is + Temp : Integer := Left; + begin + Left := Right; + Right := Temp; + end Swap; + procedure Stooge_Sort (List : in out Integer_Array) is + T : Natural := List'Length / 3; + begin + if List (List'Last) < List (List'First) then + Swap (List (List'Last), List (List'First)); + end if; + if List'Length > 2 then + Stooge_Sort (List (List'First .. List'Last - T)); + Stooge_Sort (List (List'First + T .. List'Last)); + Stooge_Sort (List (List'First .. List'Last - T)); + end if; + end Stooge_Sort; + Test_Array : Integer_Array := (1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7); +begin + Stooge_Sort (Test_Array); + for I in Test_Array'Range loop + Ada.Text_IO.Put (Integer'Image (Test_Array (I))); + if I /= Test_Array'Last then + Ada.Text_IO.Put (", "); + end if; + end loop; + Ada.Text_IO.New_Line; +end Stooge; diff --git a/Task/Sorting-algorithms-Stooge-sort/AppleScript/sorting-algorithms-stooge-sort.applescript b/Task/Sorting-algorithms-Stooge-sort/AppleScript/sorting-algorithms-stooge-sort.applescript new file mode 100644 index 0000000000..2b51638b7e --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/AppleScript/sorting-algorithms-stooge-sort.applescript @@ -0,0 +1,26 @@ +on stoogesort(lst, i, j) + if item j of lst < item i of lst then + set a to item j of lst + set b to item i of lst + set item i of lst to a + set item j of lst to b + end if + if j - i > 1 then + set t to (j - i + 1) / 3 as integer + stoogesort(lst, i, j - t) + stoogesort(lst, i + t, j) + stoogesort(lst, i, j - t) + end if + return lst +end stoogesort + +on stooge(lst) + return stoogesort(lst, 1, length of lst) +end stooge + +set test_list to {} +repeat 20 times + set test_list to test_list & (random number from 1 to 20) +end repeat + +stooge(test_list) diff --git a/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-1.ahk b/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-1.ahk index 841c0f752c..1c1440d75b 100644 --- a/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-1.ahk +++ b/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-1.ahk @@ -1,16 +1,16 @@ StoogeSort(L, i:=1, j:=""){ - if !j - j := L.MaxIndex() - if (L[j] < L[i]){ - temp := L[i] - L[i] := L[j] - L[j] := temp - } - if (j - i > 1){ - t := floor((j - i + 1)/3) - StoogeSort(L, i, j-t) - StoogeSort(L, i+t, j) - StoogeSort(L, i, j-t) - } - return L + if !j + j := L.MaxIndex() + if (L[j] < L[i]){ + temp := L[i] + L[i] := L[j] + L[j] := temp + } + if (j - i > 1){ + t := floor((j - i + 1)/3) + StoogeSort(L, i, j-t) + StoogeSort(L, i+t, j) + StoogeSort(L, i, j-t) + } + return L } diff --git a/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-2.ahk b/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-2.ahk index cc3c33fadd..9f6fd72401 100644 --- a/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-2.ahk +++ b/Task/Sorting-algorithms-Stooge-sort/AutoHotkey/sorting-algorithms-stooge-sort-2.ahk @@ -2,7 +2,7 @@ MsgBox % map(StoogeSort([123,51,6,73,3,-12,0])) return map(obj){ - for k, v in obj - res .= v "," - return trim(res, ",") + for k, v in obj + res .= v "," + return trim(res, ",") } diff --git a/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp b/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp index b21039abe9..7956aff96e 100644 --- a/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp +++ b/Task/Sorting-algorithms-Stooge-sort/C++/sorting-algorithms-stooge-sort.cpp @@ -11,10 +11,10 @@ public: void sort( int* arr, int start, int end ) { if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] ); - int n = end - start; if( n > 2 ) - { - n /= 3; sort( arr, start, end - n ); - sort( arr, start + n, end ); sort( arr, start, end - n ); + int n = end - start; if( n > 2 ) + { + n /= 3; sort( arr, start, end - n ); + sort( arr, start + n, end ); sort( arr, start, end - n ); } } }; diff --git a/Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cob b/Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cob new file mode 100644 index 0000000000..747422d413 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/COBOL/sorting-algorithms-stooge-sort.cob @@ -0,0 +1,80 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. stooge-sort-test. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 Arr-Len CONSTANT 7. + +01 arr-area VALUE "00004001000020000005000230000000000". + 03 arr-elt PIC 9(5) OCCURS Arr-Len TIMES + INDEXED BY arr-idx. + +PROCEDURE DIVISION. + DISPLAY "Unsorted: " NO ADVANCING + PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx + DISPLAY arr-elt (arr-idx) " " NO ADVANCING + END-PERFORM + DISPLAY SPACE + + CALL "stooge-sort" USING arr-area, OMITTED, OMITTED + + DISPLAY "Sorted: " NO ADVANCING + PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx + DISPLAY arr-elt (arr-idx) " " NO ADVANCING + END-PERFORM + DISPLAY SPACE + . +END PROGRAM stooge-sort-test. + + +IDENTIFICATION DIVISION. +PROGRAM-ID. stooge-sort RECURSIVE. + +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 Arr-Len CONSTANT 7. + +01 i PIC 99 COMP. +01 j PIC 99 COMP. + +01 temp PIC 9(5). + +01 t PIC 99 COMP. + +LINKAGE SECTION. +01 arr-area. + 03 arr-elt PIC 9(5) OCCURS Arr-Len TIMES. + +01 i-val PIC 99 COMP. +01 j-val PIC 99 COMP. + +PROCEDURE DIVISION USING arr-area, OPTIONAL i-val, OPTIONAL j-val. + IF i-val IS OMITTED + MOVE 1 TO i + ELSE + MOVE i-val TO i + END-IF + IF j-val IS OMITTED + MOVE Arr-Len TO j + ELSE + MOVE j-val TO j + END-IF + + IF arr-elt (j) < arr-elt (i) + MOVE arr-elt (i) TO temp + MOVE arr-elt (j) TO arr-elt (i) + MOVE temp TO arr-elt (j) + END-IF + + IF j - i + 1 >= 3 + COMPUTE t = (j - i + 1) / 3 + SUBTRACT t FROM j + CALL "stooge-sort" USING arr-area, CONTENT i, j + ADD t TO i, j + CALL "stooge-sort" USING arr-area, CONTENT i, j + SUBTRACT t FROM i, j + CALL "stooge-sort" USING arr-area, CONTENT i, j + END-IF + . +END PROGRAM stooge-sort. diff --git a/Task/Sorting-algorithms-Stooge-sort/Crystal/sorting-algorithms-stooge-sort.cr b/Task/Sorting-algorithms-Stooge-sort/Crystal/sorting-algorithms-stooge-sort.cr new file mode 100644 index 0000000000..0c597adf0b --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Crystal/sorting-algorithms-stooge-sort.cr @@ -0,0 +1,20 @@ +module Indexable::Mutable + def stooge_sort! + stooge_sort_impl 0, size-1 + self + end + + private def stooge_sort_impl (i, j) + swap(i, j) if self[i] > self[j] + if j - i + 1 > 2 + t = (j - i + 1) // 3 + stooge_sort_impl i, j-t + stooge_sort_impl i+t, j + stooge_sort_impl i, j-t + end + end +end + +arr = Array(Int32).new(15) { (-50..100).sample } +puts "before: #{arr}" +puts "after: #{arr.stooge_sort!}" diff --git a/Task/Sorting-algorithms-Stooge-sort/Delphi/sorting-algorithms-stooge-sort.pas b/Task/Sorting-algorithms-Stooge-sort/Delphi/sorting-algorithms-stooge-sort.pas index cbef16b53c..77bc98703e 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Delphi/sorting-algorithms-stooge-sort.pas +++ b/Task/Sorting-algorithms-Stooge-sort/Delphi/sorting-algorithms-stooge-sort.pas @@ -2,18 +2,18 @@ procedure StoogeSort(var L: array of integer; I,J: integer); var T,M: integer; begin if L[j] < L[i] then - begin - M:=L[I]; - L[I]:=L[J]; - L[J]:=M; - end; + begin + M:=L[I]; + L[I]:=L[J]; + L[J]:=M; + end; if (J - I) > 1 then - begin - T:=(J - I + 1) div 3; - StoogeSort(L, I, J-T); - StoogeSort(L, I+T, J); - StoogeSort(L, I, J-T); - end; + begin + T:=(J - I + 1) div 3; + StoogeSort(L, I, J-T); + StoogeSort(L, I+T, J); + StoogeSort(L, I, J-T); + end; end; @@ -31,10 +31,10 @@ var I: integer; begin Result:='['; for I:=0 to High(IA) do - begin - if I>0 then Result:=Result+' '; - Result:=Result+Format('%3d',[IA[I]]); - end; + begin + if I>0 then Result:=Result+' '; + Result:=Result+Format('%3d',[IA[I]]); + end; Result:=Result+']'; end; diff --git a/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy b/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy index cd0b4f10d6..0f62ebf422 100644 --- a/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy +++ b/Task/Sorting-algorithms-Stooge-sort/EasyLang/sorting-algorithms-stooge-sort.easy @@ -7,6 +7,6 @@ proc stsort left right &d[] . stsort left right - t d[] . . -for i = 1 to 100 : d[] &= random 1000 +for i = 1 to 50 : d[] &= random 0 999 stsort 1 len d[] d[] print d[] diff --git a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e index 6c4d571b4d..4444e2e016 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e +++ b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e @@ -1,29 +1,29 @@ class - STOOGE_SORT + STOOGE_SORT feature - stoogesort (ar: ARRAY[INTEGER]; i,j: INTEGER) + stoogesort (ar: ARRAY[INTEGER]; i,j: INTEGER) -- Sorted array in ascending order. - require - ar_not_empty: ar.count >= 0 - i_in_range: i>=1 - j_in_range: j <= ar.count - boundary_set: i<=j - local - t: REAL_64 - third: INTEGER - swap: INTEGER - do - if ar[j]< ar[i] then - swap:= ar[i] - ar[i]:=ar[j] - ar[j]:= swap - end - if j-i >1 then - t:= (j-i+1)/3 - third:= t.floor - stoogesort(ar, i, j-third) - stoogesort(ar, i+third, j) - stoogesort(ar, i, j-third) - end - end + require + ar_not_empty: ar.count >= 0 + i_in_range: i>=1 + j_in_range: j <= ar.count + boundary_set: i<=j + local + t: REAL_64 + third: INTEGER + swap: INTEGER + do + if ar[j]< ar[i] then + swap:= ar[i] + ar[i]:=ar[j] + ar[j]:= swap + end + if j-i >1 then + t:= (j-i+1)/3 + third:= t.floor + stoogesort(ar, i, j-third) + stoogesort(ar, i+third, j) + stoogesort(ar, i, j-third) + end + end end diff --git a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e index 2277afa5b9..9e406b1460 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e +++ b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e @@ -1,32 +1,32 @@ class - APPLICATION + APPLICATION create - make + make feature - make - do - test := <<2, 5, 66, -2, 0, 7>> - io.put_string ("%Nunsorted:%N") - across - test as ar - loop - io.put_string (ar.item.out + "%T") - end - create stoogesort - stoogesort.stoogesort (test, 1, test.count) - io.put_string ("%Nsorted:%N") - across - test as ar - loop - io.put_string (ar.item.out + "%T") - end - end + make + do + test := <<2, 5, 66, -2, 0, 7>> + io.put_string ("%Nunsorted:%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + create stoogesort + stoogesort.stoogesort (test, 1, test.count) + io.put_string ("%Nsorted:%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end - test: ARRAY [INTEGER] + test: ARRAY [INTEGER] - stoogesort: STOOGE_SORT + stoogesort: STOOGE_SORT end diff --git a/Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.eu b/Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.eu new file mode 100644 index 0000000000..de61faef71 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Euphoria/sorting-algorithms-stooge-sort.eu @@ -0,0 +1,25 @@ +function stooge(sequence s, integer i, integer j) + object temp + integer t + if compare(s[j], s[i]) < 0 then + temp = s[i] + s[i] = s[j] + s[j] = temp + end if + if j - i > 1 then + t = floor((j - i + 1)/3) + s = stooge(s, i , j-t) + s = stooge(s, i+t, j ) + s = stooge(s, i , j-t) + end if + return s +end function + +function stoogesort(sequence s) + return stooge(s,1,length(s)) +end function + +constant s = rand(repeat(1000,10)) + +? s +? stoogesort(s) diff --git a/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs b/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs index ff49580f1f..a9aa2b4c7b 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs +++ b/Task/Sorting-algorithms-Stooge-sort/Haskell/sorting-algorithms-stooge-sort-1.hs @@ -6,7 +6,7 @@ insertAt e k = uncurry(++).second ((e:).drop 1). splitAt k swapElems :: [a] -> Int -> Int -> [a] swapElems xs i j = insertAt (xs!!j) i $ insertAt (xs!!i) j xs - + stoogeSort [] = [] stoogeSort [x] = [x] stoogeSort xs = doss 0 (length xs - 1) xs @@ -15,6 +15,6 @@ doss i j xs | j-i>1 = doss i (j-t) $ doss (i+t) j $ doss i (j-t) xs' | otherwise = xs' where t = (j-i+1)`div`3 - xs' - | xs!!j < xs!!i = swapElems xs i j - | otherwise = xs + xs' + | xs!!j < xs!!i = swapElems xs i j + | otherwise = xs diff --git a/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-1.jq b/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-1.jq index 285004b04c..ea52b7980d 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-1.jq +++ b/Task/Sorting-algorithms-Stooge-sort/Jq/sorting-algorithms-stooge-sort-1.jq @@ -9,8 +9,8 @@ def stoogesort: | if $j - $i > 1 then (($j - $i + 1) / 3 | floor) as $t | [., $i, $j-$t] | ss - | [., $i+$t, $j] | ss - | [., $i, $j-$t] | ss + | [., $i+$t, $j] | ss + | [., $i, $j-$t] | ss else . end; diff --git a/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max b/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max index cfd35c1508..371f9a3ba3 100644 --- a/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max +++ b/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max @@ -1,18 +1,18 @@ fn stoogeSort arr i: j: = ( - if i == unsupplied do i = 1 - if j == unsupplied do j = arr.count - - if arr[j] < arr[i] do - ( - swap arr[j] arr[i] - ) - if j - i > 1 do - ( - local t = (j - i+1)/3 - arr = stoogeSort arr i:i j:(j-t) - arr = stoogeSort arr i:(i+t) j:j - arr = stoogeSort arr i:i j:(j-t) - ) - return arr + if i == unsupplied do i = 1 + if j == unsupplied do j = arr.count + + if arr[j] < arr[i] do + ( + swap arr[j] arr[i] + ) + if j - i > 1 do + ( + local t = (j - i+1)/3 + arr = stoogeSort arr i:i j:(j-t) + arr = stoogeSort arr i:(i+t) j:j + arr = stoogeSort arr i:i j:(j-t) + ) + return arr ) diff --git a/Task/Sorting-algorithms-Stooge-sort/Maple/sorting-algorithms-stooge-sort.maple b/Task/Sorting-algorithms-Stooge-sort/Maple/sorting-algorithms-stooge-sort.maple index 3ada0a7543..02927e5fc2 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Maple/sorting-algorithms-stooge-sort.maple +++ b/Task/Sorting-algorithms-Stooge-sort/Maple/sorting-algorithms-stooge-sort.maple @@ -1,23 +1,23 @@ swap := proc(arr, a, b) - local temp := arr[a]; - arr[a] := arr[b]; - arr[b] := temp; + local temp := arr[a]; + arr[a] := arr[b]; + arr[b] := temp; end proc: stoogesort:= proc(arr, start_index, end_index) - local cur; - if (arr[end_index] < arr[start_index]) then - swap(arr, start_index, end_index); - end if; - - if end_index - start_index > 1 then - cur := trunc((end_index - start_index + 1)/3); - stoogesort(arr, start_index, end_index - cur); - stoogesort(arr, start_index + cur, end_index); - stoogesort(arr, start_index, end_index - cur); - end if; - - return arr; + local cur; + if (arr[end_index] < arr[start_index]) then + swap(arr, start_index, end_index); + end if; + + if end_index - start_index > 1 then + cur := trunc((end_index - start_index + 1)/3); + stoogesort(arr, start_index, end_index - cur); + stoogesort(arr, start_index + cur, end_index); + stoogesort(arr, start_index, end_index - cur); + end if; + + return arr; end proc: diff --git a/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php b/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php index e40e271d7c..23f4e969df 100644 --- a/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php +++ b/Task/Sorting-algorithms-Stooge-sort/PHP/sorting-algorithms-stooge-sort.php @@ -1,14 +1,14 @@ function stoogeSort(&$arr, $i, $j) { - if($arr[$j] < $arr[$i]) - { - list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); - } - if(($j - $i) > 1) - { - $t = ($j - $i + 1) / 3; - stoogesort($arr, $i, $j - $t); - stoogesort($arr, $i + $t, $j); - stoogesort($arr, $i, $j - $t); - } + if($arr[$j] < $arr[$i]) + { + list($arr[$j],$arr[$i]) = array($arr[$i], $arr[$j]); + } + if(($j - $i) > 1) + { + $t = ($j - $i + 1) / 3; + stoogesort($arr, $i, $j - $t); + stoogesort($arr, $i + $t, $j); + stoogesort($arr, $i, $j - $t); + } } diff --git a/Task/Sorting-algorithms-Stooge-sort/Pluto/sorting-algorithms-stooge-sort.pluto b/Task/Sorting-algorithms-Stooge-sort/Pluto/sorting-algorithms-stooge-sort.pluto new file mode 100644 index 0000000000..7de0645d99 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Pluto/sorting-algorithms-stooge-sort.pluto @@ -0,0 +1,19 @@ +local function stooge_sort(a, i, j) + if a[j] < a[i] then + a[i], a[j] = a[j], a[i] + end + if j - i > 1 then + local t = (j - i + 1) // 3 + stooge_sort(a, i, j - t) + stooge_sort(a, i + t, j) + stooge_sort(a, i, j - t) + end +end + +local array = { {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}, {7, 5, 2, 6, 1, 4, 2, 6, 3} } +for array as a do + print($"Before: \{{a:concat(", ")}}") + stooge_sort(a, 1, #a) + print($"After : \{{a:concat(", ")}}") + print() +end diff --git a/Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.ps1 b/Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.ps1 new file mode 100644 index 0000000000..763baa5f63 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/PowerShell/sorting-algorithms-stooge-sort.ps1 @@ -0,0 +1,22 @@ +Function StoogeSort( [Int32[]] $L ) +{ + $i = 0 + $j = $L.length-1 + if( $L[$j] -lt $L[$i] ) + { + $L[$i] = $L[$i] -bxor $L[$j] + $L[$j] = $L[$i] -bxor $L[$j] + $L[$i] = $L[$i] -bxor $L[$j] + } + if( $j -gt 1 ) + { + $t = [int] ( ( $j + 1 ) / 3 ) + $k = $j - $t + 1 + [Array]::Copy( [Int32[]] ( StoogeSort( $L[0..( $j - $t ) ] ) ), $L, $k ) + [Array]::ConstrainedCopy( [Int32[]] ( StoogeSort( $L[$t..$j ] ) ), 0, $L, $t, $k ) + [Array]::Copy( [Int32[]] ( StoogeSort( $L[0..( $j - $t ) ] ) ), $L, $k ) + } + $L +} + +StoogeSort 9, 7, 5, 3, 1, 2, 4, 6, 8 diff --git a/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py index a2cfc8b70c..faef9de4cb 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py +++ b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-1.py @@ -1,15 +1,15 @@ >>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] >>> def stoogesort(L, i=0, j=None): - if j is None: - j = len(L) - 1 - if L[j] < L[i]: - L[i], L[j] = L[j], L[i] - if j - i > 1: - t = (j - i + 1) // 3 - stoogesort(L, i , j-t) - stoogesort(L, i+t, j ) - stoogesort(L, i , j-t) - return L + if j is None: + j = len(L) - 1 + if L[j] < L[i]: + L[i], L[j] = L[j], L[i] + if j - i > 1: + t = (j - i + 1) // 3 + stoogesort(L, i , j-t) + stoogesort(L, i+t, j ) + stoogesort(L, i , j-t) + return L >>> stoogesort(data) [-6, -5, -3, -2, 1, 3, 3, 4, 5, 5, 7, 7, 7, 9, 10] diff --git a/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py index ff797d404c..a5a83d4da5 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py +++ b/Task/Sorting-algorithms-Stooge-sort/Python/sorting-algorithms-stooge-sort-2.py @@ -1,12 +1,12 @@ >>> def stoogesort(L, i, j): - if L[j] < L[i]: - L[i], L[j] = L[j], L[i] - if j - i > 1: - t = (j - i + 1) // 3 - stoogesort(L, i , j-t) - stoogesort(L, i+t, j ) - stoogesort(L, i , j-t) - return L + if L[j] < L[i]: + L[i], L[j] = L[j], L[i] + if j - i > 1: + t = (j - i + 1) // 3 + stoogesort(L, i , j-t) + stoogesort(L, i+t, j ) + stoogesort(L, i , j-t) + return L >>> def stooge(L): return stoogesort(L, 0, len(L) - 1) diff --git a/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r b/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r index 3386c265a7..72aedeeef9 100644 --- a/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r +++ b/Task/Sorting-algorithms-Stooge-sort/R/sorting-algorithms-stooge-sort.r @@ -1,14 +1,14 @@ stoogesort = function(vect) { - i <- 1 - j <- length(vect) - if(vect[j] < vect[i]) vect[c(j, i)] <- vect[c(i, j)] - if(j - i > 1) { - t <- (j - i + 1) %/% 3 - vect[i:(j - t)] <- stoogesort(vect[i:(j - t)]) - vect[(i + t):j] <- stoogesort(vect[(i + t):j]) - vect[i:(j - t)] <- stoogesort(vect[i:(j - t)]) - } - vect + i <- 1 + j <- length(vect) + if(vect[j] < vect[i]) vect[c(j, i)] <- vect[c(i, j)] + if(j - i > 1) { + t <- (j - i + 1) %/% 3 + vect[i:(j - t)] <- stoogesort(vect[i:(j - t)]) + vect[(i + t):j] <- stoogesort(vect[(i + t):j]) + vect[i:(j - t)] <- stoogesort(vect[i:(j - t)]) + } + vect } v <- print(sample(21, 20)) diff --git a/Task/Sorting-algorithms-Stooge-sort/Rebol/sorting-algorithms-stooge-sort.rebol b/Task/Sorting-algorithms-Stooge-sort/Rebol/sorting-algorithms-stooge-sort.rebol new file mode 100644 index 0000000000..4635d2234e --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Rebol/sorting-algorithms-stooge-sort.rebol @@ -0,0 +1,36 @@ +Rebol [ + title: "Rosetta code: Sorting algorithms/Stooge sort" + file: %Sorting_algorithms-Stooge_sort.r3 + url: https://rosettacode.org/wiki/Sorting_algorithms-Stooge_sort +] + +stooge-sort: function/with [ + "Recursively sort a block in-place using the Stooge Sort algorithm" + data [block!] "The block to sort" +][ + ;; Public entry point: delegate to the private helper with full index range + stoogesort data 1 length? data +][ + ;; --- private context: defined once, shared across all calls to stooge-sort --- + stoogesort: function [ + L [block! ] ;; The block to sort + i [integer!] ;; Start index (1-based) + j [integer!] ;; End index (1-based) + ][ + ;; Swap endpoints if out of order + if L/:j < L/:i [ swap at L j at L i ] + ;; Recurse only if the subrange contains more than 2 elements + if j - i > 1 [ + ;; Divide the range into thirds; integer-truncate to get whole steps + t: to integer! ((j - i + 1) / 3) + stoogesort L i j - t ;; Sort first two-thirds + stoogesort L i + t j ;; Sort last two-thirds + stoogesort L i j - t ;; Sort first two-thirds again + ] + L ;; Return the (now sorted) block + ] +] + +; --- example usage --- +print ["Input: " mold data: [1 4 5 3 -6 3 7 10 -2 -5 7 5 9 -3 7]] +print ["Sorted:" mold stooge-sort data] diff --git a/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort-1.st b/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort-1.st index 2de18c5d9d..2178f11c35 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort-1.st +++ b/Task/Sorting-algorithms-Stooge-sort/Smalltalk/sorting-algorithms-stooge-sort-1.st @@ -1,20 +1,20 @@ OrderedCollection extend [ stoogeSortFrom: i to: j [ - (self at: j) < (self at: i) - ifTrue: [ self swapElement: i with: j ]. - j - i > 1 + (self at: j) < (self at: i) + ifTrue: [ self swapElement: i with: j ]. + j - i > 1 ifTrue: [ - |t| t := (j - i + 1)//3. - self stoogeSortFrom: i to: (j-t). - self stoogeSortFrom: (i+t) to: j. - self stoogeSortFrom: i to: (j-t) + |t| t := (j - i + 1)//3. + self stoogeSortFrom: i to: (j-t). + self stoogeSortFrom: (i+t) to: j. + self stoogeSortFrom: i to: (j-t) ] ] stoogeSort [ self stoogeSortFrom: 1 to: (self size) ] swapElement: i with: j [ - |t| t := self at: i. + |t| t := self at: i. self at: i put: (self at: j). - self at: j put: t + self at: j put: t ] ]. diff --git a/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic b/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic index fb592eb1bf..10a7d95cbc 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic +++ b/Task/Sorting-algorithms-Stooge-sort/Yabasic/sorting-algorithms-stooge-sort.basic @@ -8,8 +8,8 @@ next i print "unsort "; for i = a to b - print array(i) using("####"); - if i = b then print ""; else print ", "; : fi + print array(i) using("####"); + if i = b then print ""; else print ", "; : fi next i stoogeSort(array(), a, b) // ordenar el array diff --git a/Task/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.eu b/Task/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.eu new file mode 100644 index 0000000000..cc33d5f53b --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Euphoria/sorting-algorithms-strand-sort.eu @@ -0,0 +1,43 @@ +function merge(sequence left, sequence right) + sequence result + result = {} + while length(left) > 0 and length(right) > 0 do + if left[$] <= right[1] then + exit + elsif right[$] <= left[1] then + return result & right & left + elsif left[1] < right[1] then + result = append(result,left[1]) + left = left[2..$] + else + result = append(result,right[1]) + right = right[2..$] + end if + end while + return result & left & right +end function + +function strand_sort(sequence s) + integer j + sequence result + result = {} + while length(s) > 0 do + j = length(s) + for i = 1 to length(s)-1 do + if s[i] > s[i+1] then + j = i + exit + end if + end for + + result = merge(result,s[1..j]) + s = s[j+1..$] + end while + return result +end function + +constant s = rand(repeat(1000,10)) +puts(1,"Before: ") +? s +puts(1,"After: ") +? strand_sort(s) diff --git a/Task/Sorting-algorithms-Strand-sort/Pluto/sorting-algorithms-strand-sort.pluto b/Task/Sorting-algorithms-Strand-sort/Pluto/sorting-algorithms-strand-sort.pluto new file mode 100644 index 0000000000..53f448a6ba --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Pluto/sorting-algorithms-strand-sort.pluto @@ -0,0 +1,40 @@ +local function merge(left, right) + local res = {} + while #left > 0 and #right > 0 do + if left[1] <= right[1] then + res:insert(left[1]) + left:remove(1) + else + res:insert(right[1]) + right:remove(1) + end + end + table.move(left, 1, #left, #res + 1, res) + table.move(right, 1, #right, #res + 1, res) + return res +end + +local function strand_sort(a) + local list = a:clone() + local res = {} + while #list > 0 do + local sorted = {list[1]} + list:remove(1) + local leftover = {} + for list as item do + if sorted:back() <= item then + sorted:insert(item) + else + leftover:insert(item) + end + end + res = merge(sorted, res) + list = leftover + end + return res +end + +local a = {-2, 0, -2, 5, 5, 3, -1, -3, 5, 5, 0, 2, -4, 4, 2} +print($"Unsorted: \{{a:concat(", ")}}") +a = strand_sort(a) +print($"Sorted : \{{a:concat(", ")}}") diff --git a/Task/Sorting-algorithms-Strand-sort/R/sorting-algorithms-strand-sort.r b/Task/Sorting-algorithms-Strand-sort/R/sorting-algorithms-strand-sort.r new file mode 100644 index 0000000000..5aa2c45094 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/R/sorting-algorithms-strand-sort.r @@ -0,0 +1,41 @@ +merge_vec <- function(left, right){ + result <- numeric(0) + while(length(left)>0&&length(right)>0){ + if(left[1]<=right[1]){ + result <- c(result, left[1]) + left <- left[-1] + } + else { + result <- c(result, right[1]) + right <- right[-1] + } + } + if(length(left) > 0) result <- c(result, left) + if(length(right) > 0) result <- c(result, right) + return(result) +} + +strandsort <- function(v){ + if(length(v)==0) stop("input vector cannot be empty") + strand <- v[1] + v <- v[-1] + sorted <- numeric(0) + while(length(v)>0){ + k <- length(strand) + for(i in seq_along(v)){ + if(v[i]>strand[k]){ + strand <- c(strand, v[i]) + v <- v[-i] + break + } + } + if(length(strand)==k){ + sorted <- merge_vec(sorted, strand) + strand <- v[1] + v <- v[-1] + } + } + return(sorted) +} + +strandsort(c(5,1,4,2,0,9,6,3,8,7)) diff --git a/Task/Soundex/Ada/soundex.adb b/Task/Soundex/Ada/soundex.adb new file mode 100644 index 0000000000..e3199e5b29 --- /dev/null +++ b/Task/Soundex/Ada/soundex.adb @@ -0,0 +1,42 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Characters.Handling; use Ada.Characters.Handling; +procedure Soundex is + type UStrings is array(Natural range <>) of Unbounded_String; + function "+"(S:String) return Unbounded_String renames To_Unbounded_String; + + function toSoundex (instr : String) return String is + str : String := To_Upper(instr); + output : String := "0000"; + spos : Integer := str'First+1; opos : Positive := 2; + map : array(0..255) of Character := (others => ' '); + last : Integer := str'First; + begin + map(65..90) := " 123 12- 22455 12623 1-2 2"; + for i in str'Range loop str(i) := map(Character'Pos(str(i))); end loop; + output(1) := str(str'First); + while (opos <= 4 and spos <= str'Last) loop + if str(spos) /= '-' and str(spos) /= ' ' then + if (str(spos-1) = '-' and last = spos-2) and then + (str(spos) = str(spos-2)) then null; + elsif (str(spos) = output(opos-1) and last = spos-1) then last := spos; + else output(opos) := str(spos); opos := opos + 1; last := spos; + end if; + end if; + spos := spos + 1; + end loop; + output(1) := To_Upper(instr(instr'First)); + return output; + end toSoundex; + + cases : constant UStrings := (+"Soundex", +"Example", +"Sownteks", + +"Ekzampul", +"Euler", +"Gauss", +"Hilbert", +"Knuth", +"Lloyd", + +"Lukasiewicz", +"Ellery", +"Ghosh", +"Heilbronn", +"Kant", + +"Ladd", +"Lissajous", +"Wheaton", +"Burroughs", +"Burrows", + +"O'Hara", +"Washington", +"Lee", +"Gutierrez", +"Pfister", + +"Jackson", +"Tymczak", +"VanDeusen", +"Ashcraft"); +begin + for i in cases'Range loop + Put_Line(To_String(cases(i))&" = "&toSoundex(To_String(cases(i)))); + end loop; +end Soundex; diff --git a/Task/Soundex/COBOL/soundex.cob b/Task/Soundex/COBOL/soundex.cob new file mode 100644 index 0000000000..721d5cacf3 --- /dev/null +++ b/Task/Soundex/COBOL/soundex.cob @@ -0,0 +1,149 @@ + **** sndxtest ********************************************* + * Demonstrate the soundex encoding functions. + *************************************************************** + Identification division. + Program-id. sndxtest. + + Data division. + Working-storage section. + 01 sample-word-list. + 05 sample-words. + 10 filler pic x(15) value "soundex". + 10 filler pic x(15) value "example". + 10 filler pic x(15) value "sownteks". + 10 filler pic x(15) value "ekzampul". + 10 filler pic x(15) value "Euler". + 10 filler pic x(15) value "Gauss". + 10 filler pic x(15) value "Hilbert". + 10 filler pic x(15) value "Knuth". + 10 filler pic x(15) value "Lloyd". + 10 filler pic x(15) value "Lukasiewicz". + 10 filler pic x(15) value "Ellery". + 10 filler pic x(15) value "ghosh". + 10 filler pic x(15) value "Heilbronn". + 10 filler pic x(15) value "Kand". + 10 filler pic x(15) value "Ladd". + 10 filler pic x(15) value "lissajous". + 10 filler pic x(15) value "Wheaton". + 10 filler pic x(15) value "Burroughs". + 10 filler pic x(15) value "burrows". + 10 filler pic x(15) value "O'Hara". + 10 filler pic x(15) value "Washington". + 10 filler pic x(15) value "lee". + 10 filler pic x(15) value "Gutierrez". + 10 filler pic x(15) value "Phister". + 10 filler pic x(15) value "Jackson". + 10 filler pic x(15) value "tymczak". + 10 filler pic x(15) value "Vandeusen". + 10 filler pic x(15) value "Ashcraft". + 05 sample-word redefines sample-words + pic x(15) occurs 28 times indexed by wrd-idx. + 01 wrd-code pic x999. + + Procedure division. + Perform varying wrd-idx from 1 by 1 + until wrd-idx greater than 28 + call "sndxenc" using + by reference sample-word(wrd-idx) + by reference wrd-code + display wrd-code " " sample-word(wrd-idx) + end-perform. + Stop run. + + End program sndxtest. + + *** sndxenc ******************************************** + * Given a string return its soundex encoding. + *************************************************************** + Identification division. + Program-id. sndxenc. + + Data division. + Local-storage section. + 01 str-idx pic 99. + 01 let-code pic 9. + 01 prv-let-code pic 9. + 01 sdx-idx pic 9 value 1. + + Linkage section. + 01 str-to-encode. + 05 str-first-let pic x. + 05 str-rest-let pic x occurs 14 times. + 01 sdx-code. + 05 sdx-first-let pic x. + 05 sdx-nums pic 9 occurs 3 times. + + Procedure division using + by reference str-to-encode + by reference sdx-code. + Perform encode-start thru encode-done. + Goback. + + Encode-start. + Move zeros to sdx-code. + Move function upper-case(str-first-let) to sdx-first-let. + Call "sndxchar" using + by reference str-first-let + by reference let-code. + Move let-code to prv-let-code. + + Encode-string. + Perform varying str-idx from 1 by 1 + until str-idx greater than 15 + or str-rest-let(str-idx) = space + or sdx-idx greater than 3 + call "sndxchar" using + by reference str-rest-let(str-idx) + by reference let-code + if let-code not equal 7 then + if let-code not equal 0 + and let-code not equal prv-let-code + move let-code to sdx-nums(sdx-idx) + add 1 to sdx-idx + end-if + move let-code to prv-let-code + end-if + end-perform. + + Encode-done. + continue. + End program sndxenc. + + + *** sndxchar ********************************************** + * Given a character, return its soundex encoding. + * Code 7 is for h or w, which an encoder should ignore when + * either one separates double letters. + *************************************************************** + Identification division. + Program-id. sndxchar. + + Data division. + Local-storage section. + 01 lc-chr pic x. + 88 code1 value "b", "f", "p", "v". + 88 code2 value "c", "g", "j", "k", "q", "s", "x", "z". + 88 code3 value "d", "t". + 88 code4 value "l". + 88 code5 value "m", "n". + 88 code6 value "r". + 88 code7 value "h", "w". + + Linkage section. + 01 char-to-encode pic x. + 01 char-sdx-code pic 9. + + Procedure division using + by reference char-to-encode + by reference char-sdx-code. + Move function lower-case(char-to-encode) to lc-chr. + If code1 then move 1 to char-sdx-code + else if code2 then move 2 to char-sdx-code + else if code3 then move 3 to char-sdx-code + else if code4 then move 4 to char-sdx-code + else if code5 then move 5 to char-sdx-code + else if code6 then move 6 to char-sdx-code + else if code7 then move 7 to char-sdx-code + else move 0 to char-sdx-code + end-if. + End program sndxchar. diff --git a/Task/Soundex/Emacs-Lisp/soundex.el b/Task/Soundex/Emacs-Lisp/soundex.el new file mode 100644 index 0000000000..215b71f264 --- /dev/null +++ b/Task/Soundex/Emacs-Lisp/soundex.el @@ -0,0 +1,108 @@ +(defconst articulation-1 '("b" "f" "p" "v" "B" "F" "P" "V")) + +(defconst articulation-2 '("c" "g" "j" "k" "q" "s" "x" "z" "C" "G" "J" "K" "Q" "S" "X" "Z")) + +(defconst articulation-3 '("d" "t" "D" "T")) + +(defconst articulation-4 '("l" "L")) + +(defconst articulation-5 '("m" "n" "M" "N")) + +(defconst articulation-6 '("r" "R")) + +(defconst vowel '("a" "e" "i" "o" "u" "A" "E" "I" "O" "U")) + +(defconst semi-vowels '("h" "w" "y" "H" "W" "Y")) + +(defun drop-vowels (str) + "Keep first letter, drop a, e, i, o, u." + (let ((first-letter (substring str 0 1)) + (string-minus-first-letter (substring str 1))) + (concat first-letter (replace-regexp-in-string "[aeiou]" "" string-minus-first-letter)))) + +(defun drop-semi-vowels (str) + "Keep first letter, drop h, w, y." + (let ((first-letter (substring str 0 1)) + (string-minus-first-letter (substring str 1))) + (concat first-letter (replace-regexp-in-string "[hwy]" "" string-minus-first-letter)))) + +(defun drop-repeated-adjacent-consonants (str) + "Drop repeated adjacent consonants with same Soundex number." + (let ((current-letter) + (next-letter) + (current-soundex-number) + (next-soundex-number) + (modified-word str) + (position-in-word 0)) + (condition-case nil + (while (substring modified-word position-in-word (+ 2 position-in-word)) + (setq current-letter (substring modified-word position-in-word (1+ position-in-word))) + (setq next-letter (substring modified-word (1+ position-in-word) (+ position-in-word 2))) + (setq current-soundex-number (get-soundex-number current-letter)) + (setq next-soundex-number (get-soundex-number next-letter)) + (when (and + (equal current-soundex-number next-soundex-number) + (member current-soundex-number '("1" "2" "3" "4" "5"))) + (setq modified-word (replace-regexp-in-string (concat current-letter next-letter) current-letter modified-word))) + (setq position-in-word (1+ position-in-word))) + (error nil)) + modified-word)) + +(defun get-soundex-number (letter) + "Get the Soundex number of LETTER. +LETTER should be a string of just one letter. +Soundex numbers are numbers 1-6. +If the letter is a vowel or y, h, or w, there is +no Soundex number, so get an 8 for a vowel or a 9 +for y, y, or w." + (cond ((member letter articulation-1) "1") + ((member letter articulation-2) "2") + ((member letter articulation-3) "3") + ((member letter articulation-4) "4") + ((member letter articulation-5) "5") + ((member letter articulation-6) "6") + ((member letter vowel) "8") + ((member letter semi-vowel) "9"))) + +(defun soundex-all-but-first-letter (str) + "Converts STR to Soundex except for first letter. +For this function to work correctly, vowels and +h, w, and y must have already been removed. +Also, certain consonants must have already been +removed per the Soundex processing rules." + (let ((word-position 0) + (current-letter) + (converted-word "") + (converted-character "") + (word-length (length str))) + (while (< word-position word-length) + (setq current-letter (substring str word-position (1+ word-position))) + (if (> word-position 0) + (setq converted-character (get-soundex-number current-letter)) + (setq converted-character current-letter)) + (setq word-position (1+ word-position)) + (setq converted-word (concat converted-character converted-word))) + (setq converted-word (reverse converted-word)) + (setq word-length (length converted-word)) + (cond ((= word-length 4) + converted-word) + ((> word-length 4) + (substring converted-word 0 4)) + ((< word-length 4) + (let* ((difference (- 4 word-length)) + (pad "")) + (dotimes (_ difference) + (setq pad (concat "0" pad))) + (concat converted-word pad)))))) + +(defun soundex-word (str) + "Code STR to Soundex. +This function applies all the steps needed +to code STR into the correct Soundex code." + (let ((converted-word str)) + (setq converted-word (drop-repeated-adjacent-consonants converted-word)) + (setq converted-word (drop-semi-vowels converted-word)) + (setq converted-word (drop-repeated-adjacent-consonants converted-word)) + (setq converted-word (drop-vowels converted-word)) + (setq converted-word (soundex-all-but-first-letter converted-word)) + converted-word)) diff --git a/Task/Soundex/PowerShell/soundex-1.ps1 b/Task/Soundex/PowerShell/soundex-1.ps1 new file mode 100644 index 0000000000..53cdc26192 --- /dev/null +++ b/Task/Soundex/PowerShell/soundex-1.ps1 @@ -0,0 +1,81 @@ +function Get-Soundex +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [string[]] + $InputObject + ) + + Begin + { + $characterGroup = [PSCustomObject]@{ + 1 = @('B','F','P','V') + 2 = @('C','G','J','K','Q','S','X','Z') + 3 = @('D','T') + 4 = @('L') + 5 = @('M','N') + 6 = @('R') + } + + function ConvertTo-SoundexDigit ([char]$Character) + { + switch ($Character) + { + {$_ -in $characterGroup.1} {return 1} + {$_ -in $characterGroup.2} {return 2} + {$_ -in $characterGroup.3} {return 3} + {$_ -in $characterGroup.4} {return 4} + {$_ -in $characterGroup.5} {return 5} + {$_ -in $characterGroup.6} {return 6} + Default {return 0} + } + } + } + Process + { + foreach ($String in $InputObject) + { + $originalString = $String + $String = $String.ToUpper() + $isHorWcharacter = $false + $soundex = New-Object -TypeName System.Text.StringBuilder + + $soundex.Append($String[0]) | Out-Null + + for ($i = 1; $i -lt $String.Length; $i++) + { + $currentCharacterDigit = ConvertTo-SoundexDigit $String[$i] + + if ($currentCharacterDigit -ne 0) + { + if ($i -eq (ConvertTo-SoundexDigit $String[$i-1])) + { + continue + } + + if (($i -gt 2) -and ($isHorWcharacter) -and ($currentCharacterDigit -eq (ConvertTo-SoundexDigit $String[$i-2]))) + { + continue + } + + $soundex.Append($currentCharacterDigit) | Out-Null + } + + $isHorWcharacter = $String[$i] -in @('H','W') + } + + $soundexTail = ($soundex.ToString().Substring(1)).TrimStart((ConvertTo-SoundexDigit $String[0]).ToString()) + + [PSCustomObject]@{ + String = $originalString + Soundex = ($soundex[0] + $soundexTail).PadRight(4,"0").Substring(0,4) + } + } + } +} diff --git a/Task/Soundex/PowerShell/soundex-2.ps1 b/Task/Soundex/PowerShell/soundex-2.ps1 new file mode 100644 index 0000000000..8742eb8620 --- /dev/null +++ b/Task/Soundex/PowerShell/soundex-2.ps1 @@ -0,0 +1,2 @@ +"Ashcraft", "Ashcroft", "Gauss", "Ghosh", "Hilbert", "Heilbronn", "Lee", "Lloyd", +"Moses", "Pfister", "Robert", "Rupert", "Rubin", "Tymczak", "Soundex", "Example" | Get-Soundex diff --git a/Task/Soundex/PowerShell/soundex-3.ps1 b/Task/Soundex/PowerShell/soundex-3.ps1 new file mode 100644 index 0000000000..5ec68cc768 --- /dev/null +++ b/Task/Soundex/PowerShell/soundex-3.ps1 @@ -0,0 +1,18 @@ +# script Soundex.ps1 +Param([string]$Phrase) +Process { + $src = $Phrase.ToUpper().Trim() + $coded = $src[0..($src.Length - 1)] | %{ + if('BFPV'.Contains($_)) { '1' } + elseif('CGJKQSXZ'.Contains($_)) { '2' } + elseif('DT'.Contains($_)) { '3' } + elseif('L'.Contains($_)) { '4' } + elseif('MN'.Contains($_)) { '5' } + elseif('R'.Contains($_)) { '6' } + elseif('AEIOU'.Contains($_)) { 'v' } + else { '.' } + } | Where { $_ -ne '.'} + $coded2 = 0..($coded.Length - 1) | %{ if ($_ -eq 0 -or $coded[$_] -ne $coded[$_ - 1]) { $coded[$_] } else { '' } } + $coded2 = if ($coded[0] -eq 'v' -or $coded2[0] -ne $coded[0]) { $coded2 } else { $coded2[1..($coded2.Length - 1)] } + $src[0] + ((-join $($coded2 | Where { $_ -ne 'v'})) + "000").Substring(0,3) +} diff --git a/Task/Soundex/PowerShell/soundex-4.ps1 b/Task/Soundex/PowerShell/soundex-4.ps1 new file mode 100644 index 0000000000..eb0daf4fe5 --- /dev/null +++ b/Task/Soundex/PowerShell/soundex-4.ps1 @@ -0,0 +1,15 @@ + Function t([string]$value, [string]$expect) { + $result = .\Soundex.ps1 -Phrase $value + New-Object –TypeName PSObject –Prop @{ "Value"=$value; "Expect"=$expect; "Result"=$result; "Pass"=$($expect -eq $result) } +} +@( +(t "Ashcraft" "A261"); (t "Ashcroft" "A261"); (t "Burroughs" "B620"); (t "Burrows" "B620"); +(t "Ekzampul" "E251"); (t "Example" "E251"); (t "Ellery" "E460"); (t "Euler" "E460"); +(t "Ghosh" "G200"); (t "Gauss" "G200"); (t "Gutierrez" "G362"); (t "Heilbronn" "H416"); +(t "Hilbert" "H416"); (t "Jackson" "J250"); (t "Kant" "K530"); (t "Knuth" "K530"); +(t "Lee" "L000"); (t "Lukasiewicz" "L222"); (t "Lissajous" "L222"); (t "Ladd" "L300"); +(t "Lloyd" "L300"); (t "Moses" "M220"); (t "O'Hara" "O600"); (t "Pfister" "P236"); +(t "Rubin" "R150"); (t "Robert" "R163"); (t "Rupert" "R163"); (t "Soundex" "S532"); +(t "Sownteks" "S532"); (t "Tymczak" "T522"); (t "VanDeusen" "V532"); (t "Washington" "W252"); +(t "Wheaton" "W350"); +) | Format-Table -Property Value,Expect,Result,Pass diff --git a/Task/Soundex/VBScript/soundex.vbs b/Task/Soundex/VBScript/soundex.vbs new file mode 100644 index 0000000000..26cab7e98d --- /dev/null +++ b/Task/Soundex/VBScript/soundex.vbs @@ -0,0 +1,43 @@ +' Soundex + tt=array( _ + "Ashcraft","Ashcroft","Gauss","Ghosh","Hilbert","Heilbronn","Lee","Lloyd", _ + "Moses","Pfister","Robert","Rupert","Rubin","Tymczak","Soundex","Example") + tv=array( _ + "A261","A261","G200","G200","H416","H416","L000","L300", _ + "M220","P236","R163","R163","R150","T522","S532","E251") + For i=lbound(tt) To ubound(tt) + ts=soundex(tt(i)) + If ts<>tv(i) Then ok=" KO "& tv(i) Else ok="" + Wscript.echo right(" "& i ,2) & " " & left( tt(i) &space(12),12) & " " & ts & ok + Next 'i + +Function getCode(c) + Select Case c + Case "B", "F", "P", "V" + getCode = "1" + Case "C", "G", "J", "K", "Q", "S", "X", "Z" + getCode = "2" + Case "D", "T" + getCode = "3" + Case "L" + getCode = "4" + Case "M", "N" + getCode = "5" + Case "R" + getCode = "6" + Case "W","H" + getCode = "-" + End Select +End Function 'getCode + +Function soundex(s) + Dim code, previous, i + code = UCase(Mid(s, 1, 1)) + previous = getCode(UCase(Mid(s, 1, 1))) + For i = 2 To Len(s) + current = getCode(UCase(Mid(s, i, 1))) + If current <> "" And current <> "-" And current <> previous Then code = code & current + If current <> "-" Then previous = current + Next 'i + soundex = Mid(code & "000", 1, 4) +End Function 'soundex diff --git a/Task/Sparkline-in-unicode/Crystal/sparkline-in-unicode.cr b/Task/Sparkline-in-unicode/Crystal/sparkline-in-unicode.cr new file mode 100644 index 0000000000..19ec0d782a --- /dev/null +++ b/Task/Sparkline-in-unicode/Crystal/sparkline-in-unicode.cr @@ -0,0 +1,9 @@ +bar = ('▁'..'█').to_a +loop do + print "Numbers please separated by space/commas: " + numbers = gets.not_nil!.split(/[\s,]+/).map(&.to_f) + min, max = numbers.minmax + puts "min: %5f; max: %5f" % [min, max] + div = (max - min) / (bar.size - 1) + puts min == max ? bar.last.to_s*numbers.size : numbers.map{|num| bar[((num - min) / div).to_i]}.join +end diff --git a/Task/Sparkline-in-unicode/EasyLang/sparkline-in-unicode.easy b/Task/Sparkline-in-unicode/EasyLang/sparkline-in-unicode.easy new file mode 100644 index 0000000000..2f5aceb598 --- /dev/null +++ b/Task/Sparkline-in-unicode/EasyLang/sparkline-in-unicode.easy @@ -0,0 +1,19 @@ +bars$[] = strchars "▁▂▃▄▅▆▇█" +func$ sparkline a[] . + for v in a[] : max = higher max v + num = len bars$[] + max += 1e-15 * max + for v in a[] + r$ &= bars$[floor (v / max * num) + 1] + . + return r$ +. +proc show arr[] . + print arr[] + print sparkline arr[] + print "" +. +show [ 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 ] +show [ 1.5 0.5 3.5 2.5 5.5 4.5 7.5 6.5 ] +show [ 0 1 19 20 ] +show [ 0 999 4000 4999 7000 7999 ] diff --git a/Task/Sparkline-in-unicode/Pluto/sparkline-in-unicode.pluto b/Task/Sparkline-in-unicode/Pluto/sparkline-in-unicode.pluto new file mode 100644 index 0000000000..be61890dc6 --- /dev/null +++ b/Task/Sparkline-in-unicode/Pluto/sparkline-in-unicode.pluto @@ -0,0 +1,53 @@ +require "io2" + +-- Split a string using one or more whitespace or comma characters as the separator. +local function split2(s) + -- Replace all commas with spaces. + s = s:replace(",", " ") + -- Split on spaces and remove empty entries. + return s:split(" "):filter(|e| -> #e > 0):reorder() +end + +local function spark(s0) + local ss = split2(s0) + local n = #ss + local vs = table.create(n) + local min = math.huge + local max = -min + for i, s in ss do + local v = tonumber(s) + if math.isnan(v) or v == math.huge or v == -math.huge then + error("Infinities and NaN not supported.") + end + if v < min then min = v end + if v > max then max = v end + vs[i] = v + end + local sp + if min == max then + sp = string.rep("▄", n) + else + local rs = table.create(n) + local f = 8 / (max - min) + for j, v in vs do + local i = math.floor(f * (v - min)) + if i > 7 then i = 7 end + rs[j] = utf8.char(0x2581 + i) + end + sp = rs:concat() + end + return sp, n, min, max +end + +while true do + local numbers = io.readStr("Numbers please separated by spaces/commas or q to quit:\n", 1) + if !numbers then break end + local s, n, min, max = spark(numbers) + if n == 1 then + print($"1 value = {min}") + else + print($"{n} values. Min: {min} Max: {max}") + end + print(s) + print() +end diff --git a/Task/Sparkline-in-unicode/VBScript/sparkline-in-unicode.vbs b/Task/Sparkline-in-unicode/VBScript/sparkline-in-unicode.vbs new file mode 100644 index 0000000000..6074f8491b --- /dev/null +++ b/Task/Sparkline-in-unicode/VBScript/sparkline-in-unicode.vbs @@ -0,0 +1,71 @@ +'Sparkline + +sub ensure_cscript() +if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then + createobject("wscript.shell").run "CSCRIPT //nologo """ &_ + WScript.ScriptFullName &"""" ,,0 + wscript.quit + end if +end sub + +class bargraph + private bar,mn,mx,nn,cnt + + Private sub class_initialize() + bar=chrw(&h2581)&chrw(&h2582)&chrw(&h2583)&chrw(&h2584)&chrw(&h2585)&_ + chrw(&h2586)&chrw(&h2587)&chrw(&h2588) + nn=8 + end sub + + + public function bg (s) + a=split(replace(replace(s,","," ")," "," ")," ") + + mn=999999:mx=-999999:cnt=ubound(a)+1 + for i=0 to ubound(a) + a(i)=cdbl(trim(a(i))) + if a(i)>mx then mx=a(i) + if a(i)=mx then + scale=nn + else + scale=int(nn* (x-mn)/(mx-mn)+1) + end if + end function + +end class + +ensure_cscript + +set b=new bargraph +wscript.stdout.writeblanklines 2 +wscript.echo b.bg("1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1") +wscript.echo b.bg("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") +wscript.echo b.bg("0, 1, 19, 20") +wscript.echo b.bg("0, 999, 4000, 4999, 7000, 7999") +set b=nothing + +wscript.echo "If bars don't display correctly please set the the console " & _ +"font to DejaVu Sans Mono or any other that has the bargrph characters" & _ +vbcrlf + +wscript.stdout.write "Press any key.." : wscript.stdin.read 1 diff --git a/Task/Special-characters/Ada/special-characters-1.adb b/Task/Special-characters/Ada/special-characters-1.adb new file mode 100644 index 0000000000..8fe75ee77d --- /dev/null +++ b/Task/Special-characters/Ada/special-characters-1.adb @@ -0,0 +1,6 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test is +begin + Put ("Quote """ & ''' & """" & Character'Val (10)); +end Test; diff --git a/Task/Special-characters/Ada/special-characters-2.adb b/Task/Special-characters/Ada/special-characters-2.adb new file mode 100644 index 0000000000..69b0b57c80 --- /dev/null +++ b/Task/Special-characters/Ada/special-characters-2.adb @@ -0,0 +1,6 @@ +with Ada.Wide_Wide_Text_IO; use Ada.Wide_Wide_Text_IO; + +procedure Test is +begin + Put ("Unicode """ & ''' & """" & Wide_Wide_Character'Val (10)); +end Test; diff --git a/Task/Special-variables/PowerShell/special-variables-1.ps1 b/Task/Special-variables/PowerShell/special-variables-1.ps1 new file mode 100644 index 0000000000..44a7dd9e01 --- /dev/null +++ b/Task/Special-variables/PowerShell/special-variables-1.ps1 @@ -0,0 +1,40 @@ +<# + $$ + $? + $^ + $_ + $Args + $ConsoleFileName + $Error + $Event + $EventSubscriber + $ExecutionContext + $False + $ForEach + $Home + $Host + $Input + $LastExitCode + $Matches + $MyInvocation + $NestedPromptLevel + $NULL + $PID + $Profile + $PSBoundParameters + $PsCmdlet + $PsCulture + $PSDebugContext + $PsHome + $PSitem + $PSScriptRoot + $PsUICulture + $PsVersionTable + $Pwd + $Sender + $ShellID + $SourceArgs + $SourceEventArgs + $This + $True +#> diff --git a/Task/Special-variables/PowerShell/special-variables-2.ps1 b/Task/Special-variables/PowerShell/special-variables-2.ps1 new file mode 100644 index 0000000000..335b86e89d --- /dev/null +++ b/Task/Special-variables/PowerShell/special-variables-2.ps1 @@ -0,0 +1 @@ +help about_automatic_variables diff --git a/Task/Speech-synthesis/AutoIt/speech-synthesis.au3 b/Task/Speech-synthesis/AutoIt/speech-synthesis.au3 new file mode 100644 index 0000000000..8ef5135033 --- /dev/null +++ b/Task/Speech-synthesis/AutoIt/speech-synthesis.au3 @@ -0,0 +1,2 @@ +$voice = ObjCreate("SAPI.SpVoice") +$voice.Speak("This is an example of speech synthesis.") diff --git a/Task/Speech-synthesis/PowerShell/speech-synthesis.ps1 b/Task/Speech-synthesis/PowerShell/speech-synthesis.ps1 new file mode 100644 index 0000000000..4aeaa91897 --- /dev/null +++ b/Task/Speech-synthesis/PowerShell/speech-synthesis.ps1 @@ -0,0 +1,6 @@ +Add-Type -AssemblyName System.Speech + +$anna = New-Object System.Speech.Synthesis.SpeechSynthesizer + +$anna.Speak("I'm sorry Dave, I'm afraid I can't do that.") +$anna.Dispose() diff --git a/Task/Speech-synthesis/VBScript/speech-synthesis.vbs b/Task/Speech-synthesis/VBScript/speech-synthesis.vbs new file mode 100644 index 0000000000..8f8ef001b5 --- /dev/null +++ b/Task/Speech-synthesis/VBScript/speech-synthesis.vbs @@ -0,0 +1,4 @@ +Dim message, sapi +message = "This is an example of speech synthesis." +Set sapi = CreateObject("sapi.spvoice") +sapi.Speak message diff --git a/Task/Spelling-of-ordinal-numbers/Crystal/spelling-of-ordinal-numbers.cr b/Task/Spelling-of-ordinal-numbers/Crystal/spelling-of-ordinal-numbers.cr new file mode 100644 index 0000000000..e11949a941 --- /dev/null +++ b/Task/Spelling-of-ordinal-numbers/Crystal/spelling-of-ordinal-numbers.cr @@ -0,0 +1,54 @@ +struct Int + THOU_PREFIXES = %w(undec dec non oct sept sext quint quadr tr b m) + .map(&.+("illion")) + ["thousand", ""] + TENS = ["", ""] + %w(twen thir for fif six seven eigh nine).map &.+("ty") + ONES = [""] + %w(one two three four five six seven eight nine ten) + + %w(eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen) + def to_words + raise "Number to big to express in words" unless self.abs <= Int128::MAX + return "zero" if self == 0 + String.build do |s| + n = self + if n < 0 + s << "negative " + n = n.abs + end + ths = Array(Int128).new(THOU_PREFIXES.size, 0) + (0...ths.size).reverse_each do |idx| + n, ths[idx] = n.divmod(1000) + end + ths.zip(THOU_PREFIXES).each do |th, pref| + next if th == 0 + hundreds, rest = th.divmod 100 + s << ONES[hundreds] << " hundred " if hundreds > 0 + if rest < 20 + s << ONES[rest] << " " if rest > 0 + else + tens, ones = rest.divmod 10 + s << TENS[tens] + s << "-" << ONES[ones] if ones > 0 + s << " " + end + s << pref << " " if pref != "" + end + s.chomp! 32u8 + end + end + + ORDINALS = { "one" => "first", "two" => "second", "three" => "third", + "five" => "fifth", "eight" => "eighth", "nine" => "ninth", + "twelve" => "twelfth", "ty" => "tieth" } + def to_ordinal + result = to_words + if rule = ORDINALS.find {|ending, _| result.ends_with? ending } + ending, replacement = rule + result.chomp(ending) + replacement + else + result + "th" + end + end +end + +[1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003].each do |n| + print " ", n, ": ", n.to_ordinal, "\n" +end diff --git a/Task/Spelling-of-ordinal-numbers/EasyLang/spelling-of-ordinal-numbers.easy b/Task/Spelling-of-ordinal-numbers/EasyLang/spelling-of-ordinal-numbers.easy new file mode 100644 index 0000000000..b2ef772a6b --- /dev/null +++ b/Task/Spelling-of-ordinal-numbers/EasyLang/spelling-of-ordinal-numbers.easy @@ -0,0 +1,64 @@ +small$[] = [ "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen" "fourteen" "fifteen" "sixteen" "seventeen" "eighteen" "nineteen" ] +tens$[] = [ "" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety" ] +illions$[] = [ "" " thousand" " million" " billion" " trillion" " quadrillion" " quintillion" ] +func$ say n . + if n < 0 + t$ = "negative " + n = -n + . + if n < 20 + t$ &= small$[n + 1] + elif n < 100 + t$ &= tens$[n div 10 + 1] + s = n mod 10 + if s > 0 + t$ &= "-" & small$[s + 1] + . + elif n < 1000 + t$ &= small$[n div 100 + 1] & " hundred" + s = n mod 100 + if s > 0 + t$ &= " " & say s + . + else + i = 1 + while n > 0 + p = n mod 1000 + n = n div 1000 + if p > 0 + ix$ = say p & illions$[i] + if sx$ <> "" + ix$ &= " " & sx$ + . + sx$ = ix$ + . + i += 1 + . + t$ &= sx$ + . + return t$ +. +irregularOrds$[] = [ "one" "first" "two" "second" "three" "third" "five" "fifth" "eight" "eighth" "nine" "ninth" "twelve" "twelfth" ] +func$ sayOrdinal n . + s$ = say n + s$[] = strchars s$ + for i = len s$[] downto 1 + if s$[i] = "-" or s$[i] = " " : break 1 + . + s1$ = substr s$ 1 i + s2$ = substr s$ (i + 1) 99999999 + for i = 1 step 2 to len irregularOrds$[] + if irregularOrds$[i] = s2$ : break 1 + . + if i < len irregularOrds$[] + s$ = s1$ & irregularOrds$[i + 1] + elif s$[$] = "y" + s$ = substr s$ 1 (len s$[] - 1) & "ieth" + else + s$ &= "th" + . + return s$ +. +for n in [ 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 ] + print sayOrdinal n +. diff --git a/Task/Spelling-of-ordinal-numbers/Pluto/spelling-of-ordinal-numbers.pluto b/Task/Spelling-of-ordinal-numbers/Pluto/spelling-of-ordinal-numbers.pluto new file mode 100644 index 0000000000..839ba08179 --- /dev/null +++ b/Task/Spelling-of-ordinal-numbers/Pluto/spelling-of-ordinal-numbers.pluto @@ -0,0 +1,12 @@ +local fmt = require "fmt" + +local tests = {0, 1, 7, 10, 18, 22, 67, 99, 100, 105, 123, "00123.0", "1.23e2", 999, -1056, 1000005000, 2074000000, 1234000000745003, math.mininteger} +local isuk = {false, true} +local langs = {"US", "UK"} +for i = 1, 2 do + print($"{langs[i]} English:") + for tests as test do + fmt.print("%20s -> %s", tostring(test), fmt.spell(test, true, isuk[i])) + end + print() +end diff --git a/Task/Sphenic-numbers/EasyLang/sphenic-numbers.easy b/Task/Sphenic-numbers/EasyLang/sphenic-numbers.easy new file mode 100644 index 0000000000..4ad2a3c4d2 --- /dev/null +++ b/Task/Sphenic-numbers/EasyLang/sphenic-numbers.easy @@ -0,0 +1,36 @@ +func sphenic n . + l = sqrt n + f = 2 + while f <= n + if n mod f = 0 + nfacts += 1 + n = n div f + if n mod f = 0 : return 0 + else + f += 1 + if f > l + nfacts += 1 + break 1 + . + . + . + return if nfacts = 3 +. +print "Sphenic numbers less than 1000:" +for n = 1 to 999 + if sphenic n = 1 + cnt += 1 + write n & " " + if cnt mod 15 = 0 : print "" + . +. +print "" +# +print "Sphenic triplets less than 10000:" +for n = 1 to 9990 + if sphenic n = 1 and sphenic (n + 1) = 1 and sphenic (n + 2) = 1 + cnt += 1 + write "[" & n & "-" & n + 2 & "] " + if cnt mod 3 = 0 : print "" + . +. diff --git a/Task/Spinning-rod-animation-Text/Ada/spinning-rod-animation-text.adb b/Task/Spinning-rod-animation-Text/Ada/spinning-rod-animation-text.adb new file mode 100644 index 0000000000..0a70e690ff --- /dev/null +++ b/Task/Spinning-rod-animation-Text/Ada/spinning-rod-animation-text.adb @@ -0,0 +1,23 @@ +with Ada.Text_IO; + +procedure Spinning_Rod is + use Ada.Text_IO; + + type Index_Type is mod 4; + Rod : constant array (Index_Type) of Character := ('|', '/', '-', '\'); + Index : Index_Type := 0; + Char : Character; + Avail : Boolean; +begin + Put (ASCII.ESC & "[?25l"); -- Hide the cursor + loop + Put (ASCII.ESC & "[2J"); -- Clear Terminal + Put (ASCII.ESC & "[0;0H"); -- Place Cursor at Top Left Corner + Get_Immediate (Char, Avail); + exit when Avail; + Put (Rod (Index)); + Index := Index_Type'Succ (Index); + delay 0.250; + end loop; + Put (ASCII.ESC & "[?25h"); -- Restore the cursor +end Spinning_Rod; diff --git a/Task/Spinning-rod-animation-Text/Emacs-Lisp/spinning-rod-animation-text.el b/Task/Spinning-rod-animation-Text/Emacs-Lisp/spinning-rod-animation-text.el new file mode 100644 index 0000000000..76e1dbb365 --- /dev/null +++ b/Task/Spinning-rod-animation-Text/Emacs-Lisp/spinning-rod-animation-text.el @@ -0,0 +1,4 @@ +(while t + (dolist (char (string-to-list "\\|/-")) + (message "%c" char) + (sit-for 0.25))) diff --git a/Task/Spinning-rod-animation-Text/R/spinning-rod-animation-text.r b/Task/Spinning-rod-animation-Text/R/spinning-rod-animation-text.r new file mode 100644 index 0000000000..c7479f89fd --- /dev/null +++ b/Task/Spinning-rod-animation-Text/R/spinning-rod-animation-text.r @@ -0,0 +1,14 @@ +throbber <- function(phases){ + repeat{ + for(char in phases){ + cat(char, "\r") + Sys.sleep(0.25) + } + } +} + +throbber(c("\\", "|", "/", "-")) +#R supports Unicode characters, so this works also +throbber(c("⬍", "⬈", "➞", "⬊", "⬍", "⬋", "⬅", "⬉")) +#Or even this! +throbber(c("🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘")) diff --git a/Task/Spiral-matrix/Ada/spiral-matrix-1.adb b/Task/Spiral-matrix/Ada/spiral-matrix-1.adb new file mode 100644 index 0000000000..b87535521b --- /dev/null +++ b/Task/Spiral-matrix/Ada/spiral-matrix-1.adb @@ -0,0 +1,67 @@ +-- Spiral Square +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; + +procedure Spiral_Square is + type Array_Type is array(Positive range <>, Positive range <>) of Natural; + + function Spiral (N : Positive) return Array_Type is + Result : Array_Type(1..N, 1..N); + Row : Natural := 1; + Col : Natural := 1; + Max_Row : Natural := N; + Max_Col : Natural := N; + Min_Row : Natural := 1; + Min_Col : Natural := 1; + begin + for I in 0..N**2 - 1 loop + Result(Row, Col) := I; + if Row = Min_Row then + Col := Col + 1; + if Col > Max_Col then + Col := Max_Col; + Row := Row + 1; + end if; + elsif Col = Max_Col then + Row := Row + 1; + if Row > Max_Row then + Row := Max_Row; + Col := Col - 1; + end if; + elsif Row = Max_Row then + Col := Col - 1; + if Col < Min_Col then + Col := Min_Col; + Row := Row - 1; + end if; + elsif Col = Min_Col then + Row := Row - 1; + if Row = Min_Row then -- Reduce spiral + Min_Row := Min_Row + 1; + Max_Row := Max_Row - 1; + Row := Min_Row; + Min_Col := Min_Col + 1; + Max_Col := Max_Col - 1; + Col := Min_Col; + end if; + end if; + end loop; + return Result; + end Spiral; + + procedure Print(Item : Array_Type) is + Num_Digits : constant Float := Log(X => Float(Item'Length(1)**2), Base => 10.0); + Spacing : constant Positive := Integer(Num_Digits) + 2; + begin + for I in Item'range(1) loop + for J in Item'range(2) loop + Put(Item => Item(I,J), Width => Spacing); + end loop; + New_Line; + end loop; + end Print; + +begin + Print(Spiral(5)); +end Spiral_Square; diff --git a/Task/Spiral-matrix/Ada/spiral-matrix-2.adb b/Task/Spiral-matrix/Ada/spiral-matrix-2.adb new file mode 100644 index 0000000000..edee29745e --- /dev/null +++ b/Task/Spiral-matrix/Ada/spiral-matrix-2.adb @@ -0,0 +1,33 @@ +function Spiral (N : Positive) return Array_Type is + Result : Array_Type (1..N, 1..N); + Left : Positive := 1; + Right : Positive := N; + Top : Positive := 1; + Bottom : Positive := N; + Index : Natural := 0; +begin + while Left < Right loop + for I in Left..Right - 1 loop + Result (Top, I) := Index; + Index := Index + 1; + end loop; + for J in Top..Bottom - 1 loop + Result (J, Right) := Index; + Index := Index + 1; + end loop; + for I in reverse Left + 1..Right loop + Result (Bottom, I) := Index; + Index := Index + 1; + end loop; + for J in reverse Top + 1..Bottom loop + Result (J, Left) := Index; + Index := Index + 1; + end loop; + Left := Left + 1; + Right := Right - 1; + Top := Top + 1; + Bottom := Bottom - 1; + end loop; + Result (Top, Left) := Index; + return Result; +end Spiral; diff --git a/Task/Spiral-matrix/Euphoria/spiral-matrix.eu b/Task/Spiral-matrix/Euphoria/spiral-matrix.eu new file mode 100644 index 0000000000..9a9bf115cc --- /dev/null +++ b/Task/Spiral-matrix/Euphoria/spiral-matrix.eu @@ -0,0 +1,29 @@ +function spiral(integer dimension) + integer side, curr, curr2 + sequence s + s = repeat(repeat(0,dimension),dimension) + side = dimension + curr = 0 + for i = 0 to floor(dimension/2) do + for j = 1 to side-1 do + s[i+1][i+j] = curr -- top + curr2 = curr + side-1 + s[i+j][i+side] = curr2 -- right + curr2 += side-1 + s[i+side][i+side-j+1] = curr2 -- bottom + curr2 += side-1 + s[i+side-j+1][i+1] = curr2 -- left + curr += 1 + end for + curr = curr2 + 1 + side -= 2 + end for + + if remainder(dimension,2) then + s[floor(dimension/2)+1][floor(dimension/2)+1] = curr + end if + + return s +end function + +? spiral(5) diff --git a/Task/Spiral-matrix/Pluto/spiral-matrix.pluto b/Task/Spiral-matrix/Pluto/spiral-matrix.pluto new file mode 100644 index 0000000000..5b9571dfef --- /dev/null +++ b/Task/Spiral-matrix/Pluto/spiral-matrix.pluto @@ -0,0 +1,20 @@ +require "table2" +local fmt = require "fmt" + +local function spiral_matrix(n) + local m = table.create(n) + for i = 1, n do m[i] = table.rep(n, 0) end + local dx, dy = {0, 1, 0, -1}, {1, 0, -1, 0} + local x, y, c = 0, -1, 1 + for i = 0, n + n - 2 do + for j = 0, (n + n - i) // 2 - 1 do + x += dx[i % 4 + 1] + y += dy[i % 4 + 1] + m[x + 1][y + 1] = c + c += 1 + end + end + return m +end + +for spiral_matrix(5) as a do fmt.tprint("%2d", a, #a) end diff --git a/Task/Spiral-matrix/PowerShell/spiral-matrix.ps1 b/Task/Spiral-matrix/PowerShell/spiral-matrix.ps1 new file mode 100644 index 0000000000..3798502bd8 --- /dev/null +++ b/Task/Spiral-matrix/PowerShell/spiral-matrix.ps1 @@ -0,0 +1,36 @@ +function Spiral-Matrix ( [int]$N ) + { + # Initialize variables + $X = 0 + $Y = -1 + $i = 0 + $Sign = 1 + + # Intialize array + $A = New-Object 'int[,]' $N, $N + + # Set top row + 1..$N | ForEach { $Y += $Sign; $A[$X,$Y] = ++$i } + + # For each remaining half spiral... + ForEach ( $M in ($N-1)..1 ) + { + # Set the vertical quarter spiral + 1..$M | ForEach { $X += $Sign; $A[$X,$Y] = ++$i } + + # Curve the spiral + $Sign = -$Sign + + # Set the horizontal quarter spiral + 1..$M | ForEach { $Y += $Sign; $A[$X,$Y] = ++$i } + } + + # Convert the array to text output + $Spiral = ForEach ( $X in 1..$N ) { ( 1..$N | ForEach { $A[($X-1),($_-1)] } ) -join "`t" } + + return $Spiral + } + +Spiral-Matrix 5 +"" +Spiral-Matrix 7 diff --git a/Task/Spiral-matrix/Rebol/spiral-matrix.rebol b/Task/Spiral-matrix/Rebol/spiral-matrix.rebol new file mode 100644 index 0000000000..7f404ebb39 --- /dev/null +++ b/Task/Spiral-matrix/Rebol/spiral-matrix.rebol @@ -0,0 +1,40 @@ +Rebol [ + title: "Rosetta code: Spiral matrix" + file: %Spiral_matrix.r3 + url: https://rosettacode.org/wiki/Spiral_matrix +] + +spiral-matrix: function [size [integer!]] [ + matrix: array/initial size * size 0 ;; Flat array, row-major + x: y: 1 ;; Current (x, y) position (1-based indexing) + dx: 1 dy: 0 ;; Initial direction: move right + n: 0 ;; Next value to insert + loop size * size [ ;; Number of values to insert + pos: (y - 1) * size + x ;; Map 2D (x, y) to 1D flat array index + matrix/:pos: n: n + 1 ;; Fill value + ;; Calculate next position + nx: x + dx + ny: y + dy + ;; If out of bounds or already filled, turn direction (right -> down -> left -> up) + if any [ + nx < 1 + nx > size + ny < 1 + ny > size + matrix/((ny - 1) * size + nx) <> 0 + ][ + ny: dx + dx: negate dy + dy: ny + nx: x + dx + ny: y + dy + ] + x: nx + y: ny + ] + new-line/skip matrix true size + matrix +] + +;; Example usage: +probe spiral-matrix 5 diff --git a/Task/Spiral-matrix/V-(Vlang)/spiral-matrix.v b/Task/Spiral-matrix/V-(Vlang)/spiral-matrix.v new file mode 100644 index 0000000000..849494e56a --- /dev/null +++ b/Task/Spiral-matrix/V-(Vlang)/spiral-matrix.v @@ -0,0 +1,39 @@ +type Vector = []int +type Matrix = [][]int + +fn spiral_matrix(n int) Matrix { + mut result := [][]int{len: n, init: []int{len: n}} + mut pos, mut sum := 0, -1 + mut count, mut value := n, -n + for count > 0 { + value = -value / n + for _ in 0 .. count { + sum += value + result[sum / n][sum % n] = pos + pos++ + } + value *= n + count-- + for _ in 0 .. count { + sum += value + result[sum / n][sum % n] = pos + pos++ + } + } + return result +} + +fn print_matrix(m Matrix) { + for i := 0; i < m.len; i++ { + for j := 0; j < m[i].len; j++ { + print("${m[i][j]:2d} ") + } + println("") + } + println("") +} + +fn main() { + print_matrix(spiral_matrix(5)) + print_matrix(spiral_matrix(10)) +} diff --git a/Task/Spiral-matrix/VBScript/spiral-matrix.vbs b/Task/Spiral-matrix/VBScript/spiral-matrix.vbs new file mode 100644 index 0000000000..c536658d45 --- /dev/null +++ b/Task/Spiral-matrix/VBScript/spiral-matrix.vbs @@ -0,0 +1,47 @@ +Function build_spiral(n) + botcol = 0 : topcol = n - 1 + botrow = 0 : toprow = n - 1 + 'declare a two dimensional array + Dim matrix() + ReDim matrix(topcol,toprow) + dir = 0 : col = 0 : row = 0 + 'populate the array + For i = 0 To n*n-1 + matrix(col,row) = i + Select Case dir + Case 0 + If col < topcol Then + col = col + 1 + Else + dir = 1 : row = row + 1 : botrow = botrow + 1 + End If + Case 1 + If row < toprow Then + row = row + 1 + Else + dir = 2 : col = col - 1 : topcol = topcol - 1 + End If + Case 2 + If col > botcol Then + col = col - 1 + Else + dir = 3 : row = row - 1 : toprow = toprow - 1 + End If + Case 3 + If row > botrow Then + row = row - 1 + Else + dir = 0 : col = col + 1 : botcol = botcol + 1 + End If + End Select + Next + 'print the array + For y = 0 To n-1 + For x = 0 To n-1 + WScript.StdOut.Write matrix(x,y) & vbTab + Next + WScript.StdOut.WriteLine + Next +End Function + +build_spiral(CInt(WScript.Arguments(0))) diff --git a/Task/Split-a-character-string-based-on-change-of-character/Ada/split-a-character-string-based-on-change-of-character.adb b/Task/Split-a-character-string-based-on-change-of-character/Ada/split-a-character-string-based-on-change-of-character.adb new file mode 100644 index 0000000000..be8c2f7ca7 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Ada/split-a-character-string-based-on-change-of-character.adb @@ -0,0 +1,16 @@ +with Ada.Text_IO; +procedure Split is + procedure Print_Tokens (s : String) is + i, j : Integer := s'First; + begin + loop + while j<=s'Last and then s(j)=s(i) loop j := j + 1; end loop; + if i/=s'first then Ada.Text_IO.Put (", "); end if; + Ada.Text_IO.Put (s(i..j-1)); + i := j; + exit when j>s'last; + end loop; + end Print_Tokens; +begin + Print_Tokens ("gHHH5YY+++"); +end split; diff --git a/Task/Split-a-character-string-based-on-change-of-character/COBOL/split-a-character-string-based-on-change-of-character.cob b/Task/Split-a-character-string-based-on-change-of-character/COBOL/split-a-character-string-based-on-change-of-character.cob new file mode 100644 index 0000000000..f63c5d7c3a --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/COBOL/split-a-character-string-based-on-change-of-character.cob @@ -0,0 +1,61 @@ + identification division. + program-id. split-ch. + data division. + 1 split-str pic x(30) value space. + 88 str-1 value "gHHH5YY++///\". + 88 str-2 value "gHHH5 ))YY++,,,///\". + 1 binary. + 2 ptr pic 9(4) value 1. + 2 str-start pic 9(4) value 1. + 2 delim-len pic 9(4) value 1. + 2 split-str-len pic 9(4) value 0. + 2 trash-9 pic 9(4) value 0. + 1 delim-char pic x value space. + 1 delim-str pic x(6) value space. + 1 trash-x pic x. + procedure division. + display "Requested string" + set str-1 to true + perform split-init-and-go + display space + display "With spaces and commas" + set str-2 to true + perform split-init-and-go + stop run + . + + split-init-and-go. + move 1 to ptr + move 0 to split-str-len + perform split + . + + split. + perform get-split-str-len + display split-str (1:split-str-len) + perform until ptr > split-str-len + move ptr to str-start + move split-str (ptr:1) to delim-char + unstring split-str (1:split-str-len) + delimited all delim-char + into trash-x delimiter delim-str + pointer ptr + end-unstring + subtract str-start from ptr giving delim-len + move split-str (str-start:delim-len) + to delim-str (1:delim-len) + display delim-str (1:delim-len) with no advancing + if ptr <= split-str-len + display ", " with no advancing + end-if + end-perform + display space + . + + get-split-str-len. + inspect function reverse (split-str) tallying + trash-9 for leading space + split-str-len for characters after space + . + + end program split-ch. diff --git a/Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.el b/Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.el new file mode 100644 index 0000000000..9f040ca42e --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/Emacs-Lisp/split-a-character-string-based-on-change-of-character.el @@ -0,0 +1,29 @@ +(defun get-char-values () + "List ascii values of chars in buffer named test-string." + (let ((my-chars) + (current-point 1)) + (with-current-buffer "test-string" + (while (char-after current-point) + (push (char-after current-point) my-chars) + (setq current-point (1+ current-point))) + (nreverse my-chars)))) + + (defun show-chars (ascii-values) + "Show characters from VALUES." + (let* ((first-char (nth 0 ascii-values)) + (current-char) + (current-position 1) + (first-element t) + (separator ", ")) + (when first-element + (setq first-element nil) + (setq previous-char first-char) + (insert first-char)) + (while (< current-position (length ascii-values)) + (setq current-char (nth current-position ascii-values)) + (if (equal current-char previous-char) + (insert current-char) + (insert separator) + (insert current-char)) + (setq previous-char current-char) + (setq current-position (1+ current-position))))) diff --git a/Task/Split-a-character-string-based-on-change-of-character/LOLCODE/split-a-character-string-based-on-change-of-character.lol b/Task/Split-a-character-string-based-on-change-of-character/LOLCODE/split-a-character-string-based-on-change-of-character.lol new file mode 100644 index 0000000000..8c75ba2572 --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/LOLCODE/split-a-character-string-based-on-change-of-character.lol @@ -0,0 +1,21 @@ +HAI 1.4 + +CAN HAS STRING? + +HOW IZ I SPLITBYCHAR YR S + I HAS A L ITZ STRING IZ LEN YR S MKAY + I HAS A PREV + IM IN YR LOOP UPPIN YR N TIL BOTH SAEM N AN L + I HAS A CURR ITZ STRING IZ AT YR S AN YR N MKAY + EITHER OF BOTH SAEM N AN 0 AN BOTH SAEM CURR AN PREV, O RLY? + YA RLY, VISIBLE CURR! + NO WAI, VISIBLE ", " CURR! + OIC + PREV R CURR + IM OUTTA YR LOOP + VISIBLE "" +IF U SAY SO + +I IZ SPLITBYCHAR YR "gHHH5YY++///\ ,," MKAY + +KTHXBYE diff --git a/Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-1.ps1 b/Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-1.ps1 new file mode 100644 index 0000000000..16ec0b67cb --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-1.ps1 @@ -0,0 +1,20 @@ +function Split-String ([string]$String) +{ + [string]$c = $String.Substring(0,1) + [string]$splitString = $c + + for ($i = 1; $i -lt $String.Length; $i++) + { + [string]$d = $String.Substring($i,1) + + if ($d -ne $c) + { + $splitString += ", " + $c = $d + } + + $splitString += $d + } + + $splitString +} diff --git a/Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-2.ps1 b/Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-2.ps1 new file mode 100644 index 0000000000..53ebaa8a4d --- /dev/null +++ b/Task/Split-a-character-string-based-on-change-of-character/PowerShell/split-a-character-string-based-on-change-of-character-2.ps1 @@ -0,0 +1 @@ +Split-String "gHHH5YY++///\" diff --git a/Task/Square-but-not-cube/ALGOL-W/square-but-not-cube.alg b/Task/Square-but-not-cube/ALGOL-W/square-but-not-cube.alg new file mode 100644 index 0000000000..1e97e92a8b --- /dev/null +++ b/Task/Square-but-not-cube/ALGOL-W/square-but-not-cube.alg @@ -0,0 +1,22 @@ +begin % list the first 30 numbers that are squares but not cubes % + % also indicate the numbers that are both squares and cubes % + + integer count, c, c3, s, sq; + + count := sq := 0; + c := c3 := 1; + + while count < 30 do begin + s := s + 1; + sq := s * s; + while c3 < sq do begin + c := c + 1; + c3 := c * c * c + end while_c3_lt_sq ; + writeon( i_w := 4, s_w := 0, " ", sq ); + if c3 = sq then writeon( i_w := 1, s_w := 0, " is also the cube of ", c ) + else count := count + 1 + ; + write() + end while_count_lt_30 +end. diff --git a/Task/Square-but-not-cube/Ada/square-but-not-cube.adb b/Task/Square-but-not-cube/Ada/square-but-not-cube.adb new file mode 100644 index 0000000000..68232cea9e --- /dev/null +++ b/Task/Square-but-not-cube/Ada/square-but-not-cube.adb @@ -0,0 +1,35 @@ +with Ada.Text_IO; + +procedure Square_But_Not_Cube is + + function Is_Cube (N : in Positive) return Boolean is + Cube : Positive; + begin + for I in Positive loop + Cube := I**3; + if Cube = N then return True; + elsif Cube > N then return False; + end if; + end loop; + raise Program_Error; + end Is_Cube; + + procedure Show (Limit : in Natural) is + Count : Natural := 0; + Square : Natural; + use Ada.Text_IO; + begin + for N in Positive loop + Square := N**2; + if not Is_Cube (Square) then + Count := Count + 1; + Put (Square'Image); + exit when Count = Limit; + end if; + end loop; + New_Line; + end Show; + +begin + Show (Limit => 30); +end Square_But_Not_Cube; diff --git a/Task/Square-but-not-cube/Agena/square-but-not-cube.agena b/Task/Square-but-not-cube/Agena/square-but-not-cube.agena new file mode 100644 index 0000000000..5dcf12392b --- /dev/null +++ b/Task/Square-but-not-cube/Agena/square-but-not-cube.agena @@ -0,0 +1,22 @@ +scope # list the first 30 numbers that are squares but not cubes + # also indicate the numbers that are both squares and cubes + + local constant maxCount := 30; + local count, c, c3, s, sq := 0, 1, 1, 0; + + while count < maxCount do + s +:= 1; + sq := s * s; + while c3 < sq do + c +:= 1; + c3 := c * c * c + od; + printf( "%5d", sq ); + if c3 = sq then + printf( " is also the cube of %d", c ) + else + count +:= 1 + fi; + print() + od +epocs diff --git a/Task/Square-but-not-cube/COBOL/square-but-not-cube.cob b/Task/Square-but-not-cube/COBOL/square-but-not-cube.cob new file mode 100644 index 0000000000..1b69014738 --- /dev/null +++ b/Task/Square-but-not-cube/COBOL/square-but-not-cube.cob @@ -0,0 +1,29 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. SQUARE-NOT-CUBE. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 COMPUTATION. + 02 SQ-ROOT PIC 9999 COMP VALUE 1. + 02 CUBE-ROOT PIC 9999 COMP VALUE 1. + 02 SQUARE PIC 9999 COMP VALUE 1. + 02 CUBE PIC 9999 COMP VALUE 1. + 02 SEEN PIC 99 COMP VALUE 0. + 01 OUTPUT-FORMAT. + 02 OUT-NUM PIC ZZZ9. + + PROCEDURE DIVISION. + SQUARE-STEP. + COMPUTE SQUARE = SQ-ROOT ** 2. + CUBE-STEP. + IF SQUARE IS GREATER THAN CUBE + ADD 1 TO CUBE-ROOT + COMPUTE CUBE = CUBE-ROOT ** 3 + GO TO CUBE-STEP. + IF SQUARE IS NOT EQUAL TO CUBE + ADD 1 TO SEEN + MOVE SQUARE TO OUT-NUM + DISPLAY OUT-NUM. + ADD 1 TO SQ-ROOT. + IF SEEN IS LESS THAN 30 GO TO SQUARE-STEP. + STOP RUN. diff --git a/Task/Square-but-not-cube/Fennel/square-but-not-cube.fennel b/Task/Square-but-not-cube/Fennel/square-but-not-cube.fennel new file mode 100644 index 0000000000..bc227827d7 --- /dev/null +++ b/Task/Square-but-not-cube/Fennel/square-but-not-cube.fennel @@ -0,0 +1,22 @@ +(do ;;; list the first 30 numbers that are squares but not cubes + ;;; also indicate the numbers that are both squares and cubes + + (local maxCount 30) + (var (count c c3 s sq) (values 0 1 1 0)) + + (while (< count maxCount) + (set s (+ s 1)) + (set sq (* s s)) + (while (< c3 sq) + (set c (+ c 1)) + (set c3 (* c c c)) + ) + (io.write (string.format "%5d" sq)) + (if (= c3 sq) + (io.write (.. " is also the cube of " c)) + ;else + (set count (+ count 1)) + ) + (io.write "\n") + ) +) diff --git a/Task/Square-but-not-cube/Fortran/square-but-not-cube.f b/Task/Square-but-not-cube/Fortran/square-but-not-cube.f new file mode 100644 index 0000000000..df69ab768c --- /dev/null +++ b/Task/Square-but-not-cube/Fortran/square-but-not-cube.f @@ -0,0 +1,31 @@ +! +! Square but not cube +! tested with Intel ifx (IFX) 2025.2.1 20250806 on Kubuntu 25.10 +! GNU Fortran (Ubuntu 15.2.0-4ubuntu4) 15.2.0 on Kubuntu 25.10 +! VSI Fortran x86-64 V8.6-001 on OpenVMS x86_64 V9.2-3 +! No Non-standard features used, should compile on any fairly recent Fortran. +! Original C code converted to Fortran +! U.B., December 2025 +!============================================================================== +program SquareNotCube + +implicit none + +integer :: n=0 ! base number to square +integer :: square ! The base number squared +integer :: cubicRoot ! Int of 3rd root of square +integer :: count=0 ! counts squares that are not cubes + +do while (count .lt. 30) ! Loop until 30 squares but not cubes found + n = n + 1 + square = n*n + cubicRoot = int (square ** (1./3.)) ! is ok here because square is always positive. + if (cubicRoot*cubicRoot*cubicRoot .ne. square) then ! Square is not cubic number + count = count + 1 + write (*, '(I4)') square + else ! square is also cubic number + write (*, '(I4, " is square and cube." )') square + end if +end do + +end program SquareNotCube diff --git a/Task/Square-but-not-cube/Lua/square-but-not-cube-1.lua b/Task/Square-but-not-cube/Lua/square-but-not-cube-1.lua new file mode 100644 index 0000000000..7ad1d27307 --- /dev/null +++ b/Task/Square-but-not-cube/Lua/square-but-not-cube-1.lua @@ -0,0 +1,21 @@ +function nthroot (x, n) + local r = 1 + for i = 1, 16 do + r = (((n - 1) * r) + x / (r ^ (n - 1))) / n + end + return r +end + +local i, count, sq, cbrt = 0, 0 +while count < 30 do + i = i + 1 + sq = i * i + -- The next line should say nthroot(sq, 3), right? But this works. Maths, eh? + cbrt = nthroot(i, 3) + if cbrt == math.floor(cbrt) then + print(sq .. " is square and cube") + else + print(sq) + count = count + 1 + end +end diff --git a/Task/Square-but-not-cube/Lua/square-but-not-cube-2.lua b/Task/Square-but-not-cube/Lua/square-but-not-cube-2.lua new file mode 100644 index 0000000000..70d903443f --- /dev/null +++ b/Task/Square-but-not-cube/Lua/square-but-not-cube-2.lua @@ -0,0 +1,22 @@ +do -- list the first 30 numbers that are squares but not cubes + -- also indicate the numbers that are both squares and cubes + + local maxCount = 30 + local count, c, c3, s, sq = 0, 1, 1, 0 + + while count < maxCount do + s = s + 1 + sq = s * s + while c3 < sq do + c = c + 1 + c3 = c * c * c + end + io.write( string.format( "%5d", sq ) ) + if c3 == sq then + io.write( " is also the cube of " .. c ) + else + count = count + 1 + end + io.write( "\n" ) + end +end diff --git a/Task/Square-but-not-cube/Oberon-07/square-but-not-cube.oberon b/Task/Square-but-not-cube/Oberon-07/square-but-not-cube.oberon new file mode 100644 index 0000000000..6984a82c7f --- /dev/null +++ b/Task/Square-but-not-cube/Oberon-07/square-but-not-cube.oberon @@ -0,0 +1,29 @@ +MODULE SquareButNotCube; (* list the first 30 numbers that are squares but not cubes *) + IMPORT Out; (* also indicate the numbers that are both squares and cubes *) + + CONST maxCount = 30; + VAR count, c, c3, s, sq : INTEGER; + +BEGIN + count := 0; + c := 1; + c3 := 1; + s := 0; + WHILE count < maxCount DO + INC( s ); + sq := s * s; + WHILE c3 < sq DO + INC( c ); + c3 := c * c * c + END; + Out.Int( sq, 5 ); + IF c3 = sq THEN + (* the square is also a cube *) + Out.String( " is also the cube of " );Out.Int( c, 5 ) + ELSE + (* square only *) + INC( count ) + END; + Out.Ln + END +END SquareButNotCube. diff --git a/Task/Square-but-not-cube/Pluto/square-but-not-cube.pluto b/Task/Square-but-not-cube/Pluto/square-but-not-cube.pluto new file mode 100644 index 0000000000..dd30b4ae63 --- /dev/null +++ b/Task/Square-but-not-cube/Pluto/square-but-not-cube.pluto @@ -0,0 +1,22 @@ +do -- list the first 30 numbers that are squares but not cubes + -- also indicate the numbers that are both squares and cubes + + local maxCount = 30 + local count, c, c3, s, sq = 0, 1, 1, 0 + + while count < maxCount do + s += 1 + sq = s * s + while c3 < sq do + c += 1 + c3 = c * c * c + end + io.write( string.format( "%5d", sq ) ) + if c3 == sq then + io.write( $" is also the cube of {c}" ) + else + count += 1 + end + io.write( "\n" ) + end +end diff --git a/Task/Square-form-factorization/REXX/square-form-factorization.rexx b/Task/Square-form-factorization/REXX/square-form-factorization.rexx index 7a7a2666e4..69e7cffa3c 100644 --- a/Task/Square-form-factorization/REXX/square-form-factorization.rexx +++ b/Task/Square-form-factorization/REXX/square-form-factorization.rexx @@ -1,6 +1,7 @@ --- 15 Nov 2025 +-- 25 Apr 2026 include Setting numeric digits 40 +Memo.cache=0 say 'SQUARE FORM FACTORIZATION' say version @@ -59,11 +60,10 @@ procedure expose Mult. Memo. say 'Find a factor for 30 random numbers...' x=1 do until x=30 - n='' - do 30 + n='';d=Random(4,24) + do d n||=Random(9) end - n%=10**Random(25) if Right(n,1)=5 | Even(n) | Digitsum(n)//3=0 then iterate call Time('r') @@ -91,11 +91,5 @@ end say return --- Even (is even?) --- Xpon (get exponent) -include Basic --- Sfufof (find a factor by square forms factorization) --- Pollardrho (find a factor by Pollard's rho algorithm) --- Trialdiv (find a factor by trial division) --- Digitsum (calculate sum of digits) -include Ntheory +-- Even; Xpon; Squfof; Pollardrho; Trialdiv; Digitsum +include Math diff --git a/Task/Square-free-integers/ANSI-BASIC/square-free-integers.basic b/Task/Square-free-integers/ANSI-BASIC/square-free-integers.basic new file mode 100644 index 0000000000..3d2541ed1a --- /dev/null +++ b/Task/Square-free-integers/ANSI-BASIC/square-free-integers.basic @@ -0,0 +1,48 @@ +100 REM Square-free integers +110 DECLARE EXTERNAL FUNCTION SqFree +120 DECLARE EXTERNAL SUB Report +130 LET C = 0 +140 PRINT "Square free integers up to 145:" +150 FOR I = 1 TO 145 +160 IF SqFree(I) <> 0 THEN +170 PRINT USING "####": I; +180 LET C = C + 1 +190 IF MOD(C, 10) = 0 THEN PRINT +200 END IF +210 NEXT I +220 PRINT C; "were found." +230 PRINT +240 CALL Report(100) +250 CALL Report(1000) +260 CALL Report(10000) +270 CALL Report(100000) +280 END +290 ! +300 REM return nonzero if N has no square divisors other than 1 +310 EXTERNAL FUNCTION SqFree(N) +320 REM quick exit for most common square +330 LET Result = MOD(N, 4) ! Non-zero if MOD(N, 4) <> 0 +340 LET I = 3 +350 LET Sq = I * I +360 DO WHILE Sq <= N AND Result <> 0 +370 IF MOD(N, Sq) = 0 THEN +380 LET Result = 0 +390 ELSE +400 LET I = I + 2 +410 LET Sq = I * I +420 END IF +430 LOOP +440 LET SqFree = Result +450 END FUNCTION +460 ! +470 REM Report number of square-free integers up to Limit +480 EXTERNAL SUB Report(Limit) +490 PRINT "Square-free integers up to "; +500 PRINT USING "######: ": LIMIT; +510 LET C = 0 +520 FOR I = 1 TO LIMIT +530 IF SqFree(I) <> 0 THEN LET C = C + 1 +540 NEXT I +550 PRINT USING "#####": C; +560 PRINT " were found." +570 END SUB diff --git a/Task/Square-free-integers/C-sharp/square-free-integers.cs b/Task/Square-free-integers/C-sharp/square-free-integers.cs new file mode 100644 index 0000000000..aff0ebb2b4 --- /dev/null +++ b/Task/Square-free-integers/C-sharp/square-free-integers.cs @@ -0,0 +1,56 @@ +// Square-free integers +using System; + +class Program +{ + // Return true if n has no square divisors other than 1 + static bool SqFree(uint n) + { + // quick exit for most common square + bool result = (n % 4 != 0); + uint i = 3; + uint sq = i * i; + while (sq <= n && result) + { + if (n % sq == 0) + result = false; + else + { + i += 2; + sq = i * i; + } + } + return result; + } + + // Report number of square-free integers up to limit + static void Report(uint limit) + { + Console.Write("Square-free integers up to {0,6}: ", limit); + uint c = 0; + for (uint i = 1; i <= limit; i++) + if (SqFree(i)) + c++; + Console.WriteLine("{0,5} were found.", c); + } + + static void Main() + { + uint c = 0; + Console.WriteLine("Square free integers up to 145:"); + for (uint i = 1; i <= 145; i++) + if (SqFree(i)) + { + Console.Write("{0,4}", i); + c++; + if (c % 10 == 0) + Console.WriteLine(); + } + Console.WriteLine("{0} were found.", c); + Console.WriteLine(); + Report(100); + Report(1000); + Report(10000); + Report(100000); + } +} diff --git a/Task/Square-free-integers/Free-Pascal-Lazarus/square-free-integers.pas b/Task/Square-free-integers/Free-Pascal-Lazarus/square-free-integers.pas new file mode 100644 index 0000000000..31ff4be462 --- /dev/null +++ b/Task/Square-free-integers/Free-Pascal-Lazarus/square-free-integers.pas @@ -0,0 +1,162 @@ +program SquareFree; +{$IFDEF FPC} + {$MODE DELPHI} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +const + //needs 1e10 Byte = 10 Gb maybe someone got 128 Gb :-) nearly linear time + BigLimit = 10*1000*1000*1000; + TRILLION = 1000*1000*1000*1000; + primeLmt = trunc(sqrt(TRILLION+150)); + +var + primes : array of byte; + sieve : array of byte; + +procedure initPrimes; +var + i,lmt,dp :NativeInt; +Begin + setlength(primes,80000); + setlength(sieve,primeLmt); + sieve[0] := 1; + sieve[1] := 1; + i := 2; + repeat + IF sieve[i] = 0 then + Begin + lmt:= i*i; + while lmt=primeLmt; + //extract difference of primes + i := 0; + lmt := 0; + dp := 0; + repeat + IF sieve[i] = 0 then + Begin + primes[lmt] := dp; + dp := 0; + inc(lmt); + end; + inc(dp); + inc(i); + until i >primeLmt; + setlength(sieve,0); + setlength(Primes,lmt+1); +end; + +procedure SieveSquares; +//mark all powers >=2 of prime => all powers = 2 is sufficient +var + pSieve : pByte; + i,sq,k,prime : NativeInt; +Begin + pSieve := @sieve[0]; + prime := 0; + For i := 0 to High(primes) do + Begin + prime := prime+primes[i]; + sq := prime*prime; + k := sq; + if sq > BigLimit then + break; + repeat + pSieve[k] := 1; + inc(k,sq); + until k> BigLimit; + end; +end; + +procedure Count_x10; +var + pSieve : pByte; + i,lmt,cnt: NativeInt; +begin + writeln(' square free count'); + writeln('[1 to limit]'); + + pSieve := @sieve[0]; + lmt := 10; + i := 1; + cnt := 0; + repeat + while i <= lmt do + Begin + inc(cnt,ORD(pSieve[i] = 0)); + inc(i); + end; + writeln(lmt:12,' ',cnt:12); + IF lmt >= BigLimit then + BREAK; + lmt := lmt*10; + IF lmt >BigLimit then + lmt := BigLimit; + until false; +end; + +function TestSquarefree(N:Uint64):boolean; +var + i,prime,sq : NativeUint; +Begin + prime := 0; + result := false; + For i := 0 to High(primes) do + Begin + prime := prime+primes[i]; + sq := sqr(prime); + IF sq> N then + BREAK; + IF N MOD sq = 0 then + EXIT; + end; + result := true; +end; +var + i,k : NativeInt; +Begin + InitPrimes; + setlength(sieve,BigLimit+1); + SieveSquares; + + writeln('Square free numbers from 1 to 145'); + k := 80 div 4; + For i := 1 to 145 do + If sieve[i] = 0 then + Begin + write(i:4); + dec(k); + IF k = 0 then + Begin + writeln; + k := 80 div 4; + end; + end; + writeln;writeln; + + writeln('Square free numbers from ',TRILLION,' to ',TRILLION+145); + k := 4; + For i := TRILLION to TRILLION+145 do + Begin + if TestSquarefree(i) then + Begin + write(i:20); + dec(k); + IF k = 0 then + Begin + writeln; + k := 4; + end; + end; + end; + writeln;writeln; + + Count_x10; +end. diff --git a/Task/Square-free-integers/Frink/square-free-integers.frink b/Task/Square-free-integers/Frink/square-free-integers.frink new file mode 100644 index 0000000000..ca60597bbb --- /dev/null +++ b/Task/Square-free-integers/Frink/square-free-integers.frink @@ -0,0 +1,14 @@ +sf = {|x| last[last[sort[factor[x], byColumn[1]]]] <2 } + +println["From 1 to 145:"] +println[select[1 to 145, sf]] + +println["\nFrom 1 trillion to 1 trillion + 145:"] +println[select[1 trillion to 1 trillion + 145, sf]] + +res = new array +for n = [one hundred, one thousand, ten thousand, one hundred thousand, one million] + res.push[["From 1 to" , n, length[select[1 to n, sf]]]] + +println["\nNumber of square-free integers:"] +println[formatTable[res,"right"]] diff --git a/Task/Square-free-integers/FutureBasic/square-free-integers.basic b/Task/Square-free-integers/FutureBasic/square-free-integers.basic new file mode 100644 index 0000000000..ac8cfbb0b5 --- /dev/null +++ b/Task/Square-free-integers/FutureBasic/square-free-integers.basic @@ -0,0 +1,64 @@ +_max = 1000001 +uint32 primeList( 80000 ) + +clear local fn makePrimeList + // Creates list of primes using Sieve of Eratosthenes + // with a bitmap of odd integers + uint8 primeBits( 62500 ) // Bits for 500000 odd integers + uint64 i, n, count = 1 + for n = 3 to _max step 2 + if primeBits(n >> 4) & bit((n & 15) >> 1) then continue + primeList( count++ ) = n + i = n * n + while i < _max + primeBits(i >> 4) |= bit((i & 15) >> 1) + i += n << 1 + wend + next +end fn + +bool local fn squareFree( n as uint64 ) +// Determines whether n is square-free +// by checking each squared prime +uint64 i = 1, square = 4 +while square <= n + if !(n % square) then return no + square = primeList(i++)^2 +wend +end fn = yes + +local fn printList( n as uint64, tgt as uint64 ) + int wid = len(str(tgt))+1, cols = 64 /wid, count = 0 + CFStringRef form = concat( @"%",mid(str(wid),1),@"ld\b") + printf @"\n square-free numbers from %ld to %ld:", n, tgt + while n <= tgt + if fn squareFree( n ) + print fn StringWithFormat( form, n ) + count++ + if !( count % cols ) then print + end if + n++ + wend + print @"\n" +end fn + + +window 1, @"square-free integers",(0, 0, 455, 640) +CFtimeInterval t : t = fn CACurrentMediatime + +fn makePrimeList +fn printList(1, 145) +fn printList(1000000000000, 1000000000145) + +uint32 tgt = 10, count = 0, i +do + tgt *= 10 + for i = 1 to tgt + count += fn squareFree( i ) + next + printf @" square-free numbers <= %7d: %d", tgt, count +until tgt >= 1000000 + +printf @"\n Calc time: %.3fsec", fn CACurrentMediatime - t + +HandleEvents diff --git a/Task/Square-free-integers/JavaScript/square-free-integers.js b/Task/Square-free-integers/JavaScript/square-free-integers.js new file mode 100644 index 0000000000..5e6a19a04d --- /dev/null +++ b/Task/Square-free-integers/JavaScript/square-free-integers.js @@ -0,0 +1,21 @@ +function is_squarefree(n) { + for (let i = 2; i <= Math.sqrt(n); i++) { + if (Number.isInteger(n / (i ** 2))) { + return false; + } + } + return true; +} + +for (const n of [1, 10 ** 12 + 1]) { + console.log([...Array(145).keys()].map(x => x + n).filter(is_squarefree).join(" ")); +} + +let sqf = []; +for (let i = 1; i <= 1000000; i++) { + if (is_squarefree(i)) { + sqf.push(i); + } else if (Number.isInteger(Math.log10(i))) { + console.log(`There are ${sqf.length} square-free integers <=${i}`); + } +} diff --git a/Task/Square-free-integers/K/square-free-integers.k b/Task/Square-free-integers/K/square-free-integers.k new file mode 100644 index 0000000000..ee839aebba --- /dev/null +++ b/Task/Square-free-integers/K/square-free-integers.k @@ -0,0 +1,22 @@ +Trillion: */12#10 +Limit: Trillion + 145 +p: `pri 1+_%Limit + +sqf: { + a: 1+_%x + &/ ~0= ({x*x}' (1+p'a)#p) !' x} + +pm: { /print matrix + fw: -(3 + _(|/`ln x) % `ln 10) + `0: (,/fw$$)'(0N;y) # x} + +`0: "The square free numbers up to 145:" +pm[1+&sqf'1_!146; 15] + +`0: "" +`0: "The square free numbers from 1e12 - 1e12+145" +pm[Trillion + &sqf'Trillion + !146; 5] + +`0: "" +`0: "Counts of square free numbers <= 100, 1000, ... 1e6" +`0: $1_+\#'.=(#$)' 1+&sqf'1_!1000001 diff --git a/Task/Square-free-integers/PHP/square-free-integers.php b/Task/Square-free-integers/PHP/square-free-integers.php new file mode 100644 index 0000000000..49b640f591 --- /dev/null +++ b/Task/Square-free-integers/PHP/square-free-integers.php @@ -0,0 +1,47 @@ + diff --git a/Task/Square-free-integers/Pascal-P/square-free-integers.pas b/Task/Square-free-integers/Pascal-P/square-free-integers.pas new file mode 100644 index 0000000000..9f14f61645 --- /dev/null +++ b/Task/Square-free-integers/Pascal-P/square-free-integers.pas @@ -0,0 +1,58 @@ +program sqfreeints(output); + (* Square-free integers *) +var + i, c: integer; + + (* Return true if n has no square divisors other than 1 *) + function sqfree(n: integer): boolean; + var + i, sq: integer; + sqf: boolean; + begin + (* quick exit for most common square *) + sqf := (n mod 4 <> 0); + i := 3; + sq := i * i; + while (sq <= n) and sqf do + if n mod sq = 0 then + sqf := false + else + begin + i := i + 2; + sq := i * i; + end; + sqfree := sqf; + end; + + (* Report number of square-free integers up to limit *) + procedure report(limit: integer); + var + i, c: integer; + begin + write('Square-free integers up to ', limit: 6, ': '); + c := 0; + for i := 1 to limit do + if sqfree(i) then + c := c + 1; + writeln(c: 5, ' were found.'); + end; + +begin + c := 0; + writeln('Square free integers up to 145:'); + for i := 1 to 145 do + if sqfree(i) then + begin + write(i: 4); + c := c + 1; + if c mod 10 = 0 then + writeln; + end; + writeln(c: 1, ' were found.'); + writeln; + report(100); + report(1000); + report(10000); + report(100000); + (* readln; *) +end. diff --git a/Task/Square-free-integers/Pluto/square-free-integers.pluto b/Task/Square-free-integers/Pluto/square-free-integers.pluto new file mode 100644 index 0000000000..4da924e3dc --- /dev/null +++ b/Task/Square-free-integers/Pluto/square-free-integers.pluto @@ -0,0 +1,36 @@ +local fmt = require "fmt" + +local function is_square_free(n) + local i = 2 + while i * i <= n do + if n % (i * i) == 0 then return false end + i = (i > 2) ? i + 2 : i + 1 + end + return true +end + +local ranges = { range(1, 145), range(1e12, 1e12 + 145) } +local params = { {3, 20}, {12, 5} } +for i = 1, #ranges do + local r = ranges[i] + print($"The square-free integers between {r[1]} and {r:back()} inclusive are:") + local count = 0 + for r as j do + if is_square_free(j) then + ++count + fmt.write($"%{params[i][1]}d ", j) + if count % params[i][2] == 0 then print() end + end + end + print("\n") +end + +print("Counts of square-free integers:") +local count = 0 +local lims = {0, 100, 1000, 1e4, 1e5, 1e6} +for i = 2, #lims do + for j = lims[i - 1] + 1, lims[i] do + if is_square_free(j) then ++count end + end + fmt.print(" from 1 to (inclusive) %-7d = %d", lims[i], count) +end diff --git a/Task/Square-free-integers/R/square-free-integers.r b/Task/Square-free-integers/R/square-free-integers.r new file mode 100644 index 0000000000..0986fa2ad1 --- /dev/null +++ b/Task/Square-free-integers/R/square-free-integers.r @@ -0,0 +1,14 @@ +is_squarefree <- function(n){ + limit <- floor(sqrt(n)) + squares <- if(limit>1) (2:limit)^2 else 4 + !(0 %in% (n%%squares)) +} + +list_squarefree <- function(n1, n2) Filter(is_squarefree, n1:n2) + +list_squarefree(1, 145) +print(list_squarefree(10^12, 145+10^12), digits=13) + +count_squarefree <- function(n1, n2) length(list_squarefree(n1, n2)) +test_ranges <- lapply(2:6, function(n) list(1, 10^n)) +sapply(test_ranges, function(l) do.call(count_squarefree, l)) diff --git a/Task/Stable-marriage-problem/Fortran/stable-marriage-problem.f b/Task/Stable-marriage-problem/Fortran/stable-marriage-problem.f new file mode 100644 index 0000000000..7bdae8ac2c --- /dev/null +++ b/Task/Stable-marriage-problem/Fortran/stable-marriage-problem.f @@ -0,0 +1,142 @@ +program stable_marriage + implicit none + integer, parameter :: n = 10 + integer :: mens_pref(n, n), womens_pref(n, n) + integer :: mens_rank(n, n), womens_rank(n, n) + integer :: wife(n), husband(n), next_prop(n) + logical :: free_men(n) + character(len=4) :: men_names(n), women_names(n) + integer :: m, w, p, h, i, curr_w, w1, w2 + logical :: is_stable + + ! Names + men_names = ['abe ', 'bob ', 'col ', 'dan ', 'ed ', 'fred', 'gav ', 'hal ', 'ian ', 'jon '] + women_names = ['abi ', 'bea ', 'cath', 'dee ', 'eve ', 'fay ', 'gay ', 'hope', 'ivy ', 'jan '] + + ! Men's preferences + mens_pref(1, :) = [1, 5, 3, 9, 10, 4, 6, 2, 8, 7] + mens_pref(2, :) = [3, 8, 1, 4, 5, 6, 2, 10, 9, 7] + mens_pref(3, :) = [8, 5, 1, 4, 2, 6, 9, 7, 3, 10] + mens_pref(4, :) = [9, 6, 4, 7, 8, 5, 10, 2, 3, 1] + mens_pref(5, :) = [10, 4, 2, 3, 6, 5, 1, 9, 8, 7] + mens_pref(6, :) = [2, 1, 4, 7, 5, 9, 3, 10, 8, 6] + mens_pref(7, :) = [7, 5, 9, 2, 3, 1, 4, 8, 10, 6] + mens_pref(8, :) = [1, 5, 8, 6, 9, 3, 10, 2, 7, 4] + mens_pref(9, :) = [8, 3, 4, 7, 2, 1, 6, 9, 10, 5] + mens_pref(10, :) = [1, 6, 10, 7, 5, 2, 4, 3, 9, 8] + + ! Women's preferences + womens_pref(1, :) = [2, 6, 10, 7, 9, 1, 4, 5, 3, 8] + womens_pref(2, :) = [2, 1, 3, 6, 7, 4, 9, 5, 10, 8] + womens_pref(3, :) = [6, 2, 5, 7, 8, 3, 9, 1, 4, 10] + womens_pref(4, :) = [6, 10, 3, 1, 9, 8, 7, 4, 2, 5] + womens_pref(5, :) = [10, 8, 6, 4, 1, 7, 3, 5, 9, 2] + womens_pref(6, :) = [2, 1, 5, 9, 10, 4, 6, 7, 3, 8] + womens_pref(7, :) = [10, 7, 8, 6, 2, 1, 3, 5, 4, 9] + womens_pref(8, :) = [7, 10, 2, 1, 9, 4, 8, 5, 3, 6] + womens_pref(9, :) = [9, 3, 8, 7, 6, 2, 1, 5, 10, 4] + womens_pref(10, :) = [5, 8, 7, 1, 2, 10, 3, 9, 6, 4] + + ! Build rank matrices + mens_rank = 0 + do m = 1, n + do p = 1, n + w = mens_pref(m, p) + mens_rank(m, w) = p + end do + end do + womens_rank = 0 + do w = 1, n + do p = 1, n + m = womens_pref(w, p) + womens_rank(w, m) = p + end do + end do + + ! Gale-Shapley algorithm + wife = 0 + husband = 0 + next_prop = 1 + free_men = .true. + do while (any(free_men)) + do m = 1, n + if (.not. free_men(m)) cycle + if (next_prop(m) > n) cycle + w = mens_pref(m, next_prop(m)) + next_prop(m) = next_prop(m) + 1 + if (husband(w) == 0) then + husband(w) = m + wife(m) = w + free_men(m) = .false. + else + h = husband(w) + if (womens_rank(w, m) < womens_rank(w, h)) then + husband(w) = m + wife(m) = w + free_men(m) = .false. + wife(h) = 0 + free_men(h) = .true. + end if + end if + end do + end do + + ! Print stable matching + print *, 'Stable matching:' + do m = 1, n + print *, trim(men_names(m)), ' - ', trim(women_names(wife(m))) + end do + + ! Check stability of stable matching + is_stable = .true. + do m = 1, n + curr_w = wife(m) + do i = 1, mens_rank(m, curr_w) - 1 + w = mens_pref(m, i) + h = husband(w) + if (womens_rank(w, m) < womens_rank(w, h)) then + is_stable = .false. + end if + end do + end do + if (is_stable) then + print *, 'The matching is stable.' + else + print *, 'The matching is not stable.' + end if + + ! Perturb the matching (swap abe and bob's partners) + w1 = wife(1) + w2 = wife(2) + wife(1) = w2 + wife(2) = w1 + husband(w1) = 2 + husband(w2) = 1 + + ! Print perturbed matching + print *, '' + print *, 'Perturbed matching: (swap abe and bob''s partners)' + do m = 1, n + print *, trim(men_names(m)), ' - ', trim(women_names(wife(m))) + end do + + ! Check stability of perturbed matching + is_stable = .true. + check_loop: do m = 1, n + curr_w = wife(m) + do i = 1, mens_rank(m, curr_w) - 1 + w = mens_pref(m, i) + h = husband(w) + if (womens_rank(w, m) < womens_rank(w, h)) then + is_stable = .false. + print *, 'Unstable because ', trim(men_names(m)), ' and ', trim(women_names(w)), & + ' prefer each other while ', trim(men_names(h)), ' and ', trim(women_names(curr_w)), ' prefer each other' + exit check_loop ! Show one blocking pair + end if + end do + end do check_loop + if (is_stable) then + print *, 'The perturbed matching is stable.' + end if + +end program stable_marriage diff --git a/Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.ps1 b/Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.ps1 new file mode 100644 index 0000000000..18e26901db --- /dev/null +++ b/Task/Stable-marriage-problem/PowerShell/stable-marriage-problem.ps1 @@ -0,0 +1,136 @@ +using namespace System.Collections.Generic +$ErrorActionPreference = 'Stop' +class Person{ + #private + hidden [int] $_candidateIndex; + [string] $Name + #[System.Collections.Generic.List[Person]] $Prefs + [List[Person]] $Prefs + [Person] $Fiance + + Person([string] $name) { + $this.Name = $name; + $this.Prefs = $null; + $this.Fiance = $null; + $this._candidateIndex = 0; + } + [bool] Prefers([Person] $p) { + return $this.Prefs.FindIndex({ param($o) $o -eq $p }) -lt $this.Prefs.FindIndex({ param($o) $o -eq $this.Fiance }); + } + + [Person] NextCandidateNotYetProposedTo() { + if ($this._candidateIndex -ge $this.Prefs.Count) {return $null;} + return $this.Prefs[$this._candidateIndex++]; + } + + [void] EngageTo([Person] $p) { + if ($p.Fiance -ne $null) {$p.Fiance.Fiance = $null}; + $p.Fiance = $this; + if ($this.Fiance -ne $null){$this.Fiance.Fiance = $null}; + $this.Fiance = $p; + } + + + } + + + class MainClass + { + static [bool] IsStable([List[Person]] $men) { + [List[Person]] $women = $men[0].Prefs; + foreach ($guy in $men){ + foreach ($gal in $women) { + if ($guy.Prefers($gal) -and $gal.Prefers($guy)) + {return $false}; + } + } + return $true; + } + + static [void] DoMarriage() { + [Person] $abe = [Person]::new("abe"); + [Person] $bob = [Person]::new("bob"); + [Person] $col = [Person]::new("col"); + [Person] $dan = [Person]::new("dan"); + [Person] $ed = [Person]::new("ed"); + [Person] $fred = [Person]::new("fred"); + [Person] $gav = [Person]::new("gav"); + [Person] $hal = [Person]::new("hal"); + [Person] $ian = [Person]::new("ian"); + [Person] $jon = [Person]::new("jon"); + [Person] $abi = [Person]::new("abi"); + [Person] $bea = [Person]::new("bea"); + [Person] $cath = [Person]::new("cath"); + [Person] $dee = [Person]::new("dee"); + [Person] $eve = [Person]::new("eve"); + [Person] $fay = [Person]::new("fay"); + [Person] $gay = [Person]::new("gay"); + [Person] $hope = [Person]::new("hope"); + [Person] $ivy = [Person]::new("ivy"); + [Person] $jan = [Person]::new("jan"); + + $abe.Prefs =[Person[]]@($abi, $eve, $cath, $ivy, $jan, $dee, $fay, $bea, $hope, $gay) + $bob.Prefs = [Person[]] @($cath, $hope, $abi, $dee, $eve, $fay, $bea, $jan, $ivy, $gay); + $col.Prefs = [Person[]] @($hope, $eve, $abi, $dee, $bea, $fay, $ivy, $gay, $cath, $jan); + $dan.Prefs = [Person[]] @($ivy, $fay, $dee, $gay, $hope, $eve, $jan, $bea, $cath, $abi); + $ed.Prefs = [Person[]] @($jan, $dee, $bea, $cath, $fay, $eve, $abi, $ivy, $hope, $gay); + $fred.Prefs = [Person[]] @($bea, $abi, $dee, $gay, $eve, $ivy, $cath, $jan, $hope, $fay); + $gav.Prefs = [Person[]] @($gay, $eve, $ivy, $bea, $cath, $abi, $dee, $hope, $jan, $fay); + $hal.Prefs = [Person[]] @($abi, $eve, $hope, $fay, $ivy, $cath, $jan, $bea, $gay, $dee); + $ian.Prefs = [Person[]] @($hope, $cath, $dee, $gay, $bea, $abi, $fay, $ivy, $jan, $eve); + $jon.Prefs = [Person[]] @($abi, $fay, $jan, $gay, $eve, $bea, $dee, $cath, $ivy, $hope); + $abi.Prefs = [Person[]] @($bob, $fred, $jon, $gav, $ian, $abe, $dan, $ed, $col, $hal); + $bea.Prefs = [Person[]] @($bob, $abe, $col, $fred, $gav, $dan, $ian, $ed, $jon, $hal); + $cath.Prefs = [Person[]] @($fred, $bob, $ed, $gav, $hal, $col, $ian, $abe, $dan, $jon); + $dee.Prefs = [Person[]] @($fred, $jon, $col, $abe, $ian, $hal, $gav, $dan, $bob, $ed); + $eve.Prefs = [Person[]] @($jon, $hal, $fred, $dan, $abe, $gav, $col, $ed, $ian, $bob); + $fay.Prefs = [Person[]] @($bob, $abe, $ed, $ian, $jon, $dan, $fred, $gav, $col, $hal); + $gay.Prefs = [Person[]] @($jon, $gav, $hal, $fred, $bob, $abe, $col, $ed, $dan, $ian); + $hope.Prefs = [Person[]] @($gav, $jon, $bob, $abe, $ian, $dan, $hal, $ed, $col, $fred); + $ivy.Prefs = [Person[]] @($ian, $col, $hal, $gav, $fred, $bob, $abe, $ed, $jon, $dan); + $jan.Prefs = [Person[]] @($ed, $hal, $gav, $abe, $bob, $jon, $col, $ian, $fred, $dan); + + [List[Person]] $men = [List[Person]]::new($abi.Prefs); + + [int] $freeMenCount = $men.Count; + while ($freeMenCount -gt 0) { + foreach ($guy in $men) { + if ($guy.Fiance -eq $null) { + [Person]$gal = $guy.NextCandidateNotYetProposedTo(); + if ($gal.Fiance -eq $null) { + $guy.EngageTo($gal); + $freeMenCount--; + } + else{ + if ($gal.Prefers($guy)) { + $guy.EngageTo($gal); + } + } + + } + } + } + + foreach ($guy in $men) { + write-host $guy.Name " is engaged to " $guy.Fiance.Name + + } + write-host "Stable = " ([MainClass]::IsStable($men)) + + write-host "Switching fred & jon's partners"; + [Person] $jonsFiance = $jon.Fiance; + [Person] $fredsFiance = $fred.Fiance; + $fred.EngageTo($jonsFiance); + $jon.EngageTo($fredsFiance); + write-host "Stable = " ([MainClass]::IsStable($men)); + + } + static [void] Main([string[]] $args) + { + [MainClass]::DoMarriage(); + } + + + } + +[MainClass]::DoMarriage() diff --git a/Task/Stack-traces/Ada/stack-traces.adb b/Task/Stack-traces/Ada/stack-traces.adb new file mode 100644 index 0000000000..a80d4a1852 --- /dev/null +++ b/Task/Stack-traces/Ada/stack-traces.adb @@ -0,0 +1,31 @@ +with Ada.Text_IO; use Ada.Text_IO; +with GNAT.Traceback; +with GNAT.Traceback.Symbolic; + +procedure Test_Stack_Trace is + procedure Call_Stack is + Trace : GNAT.Traceback.Tracebacks_Array (1..1_000); + Length : Natural; + begin + GNAT.Traceback.Call_Chain (Trace, Length); + Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (Trace (1..Length))); + end Call_Stack; + + procedure Inner (K : Integer) is + begin + Call_Stack; + end Inner; + + procedure Middle (X, Y : Integer) is + begin + Inner (X * Y); + end Middle; + + procedure Outer (A, B, C : Integer) is + begin + Middle (A + B, B + C); + end Outer; + +begin + Outer (2,3,5); +end Test_Stack_Trace; diff --git a/Task/Stack/Ada/stack-1.adb b/Task/Stack/Ada/stack-1.adb new file mode 100644 index 0000000000..156951b693 --- /dev/null +++ b/Task/Stack/Ada/stack-1.adb @@ -0,0 +1,16 @@ +generic + type Element_Type is private; +package Generic_Stack is + type Stack is private; + procedure Push (Item : Element_Type; Onto : in out Stack); + procedure Pop (Item : out Element_Type; From : in out Stack); + function Create return Stack; + Stack_Empty_Error : exception; +private + type Node; + type Stack is access Node; + type Node is record + Element : Element_Type; + Next : Stack := null; + end record; +end Generic_Stack; diff --git a/Task/Stack/Ada/stack-2.adb b/Task/Stack/Ada/stack-2.adb new file mode 100644 index 0000000000..628f998b00 --- /dev/null +++ b/Task/Stack/Ada/stack-2.adb @@ -0,0 +1,42 @@ +with Ada.Unchecked_Deallocation; + +package body Generic_Stack is + + ------------ + -- Create -- + ------------ + + function Create return Stack is + begin + return (null); + end Create; + + ---------- + -- Push -- + ---------- + + procedure Push(Item : Element_Type; Onto : in out Stack) is + Temp : Stack := new Node; + begin + Temp.Element := Item; + Temp.Next := Onto; + Onto := Temp; + end Push; + + --------- + -- Pop -- + --------- + + procedure Pop(Item : out Element_Type; From : in out Stack) is + procedure Free is new Ada.Unchecked_Deallocation(Node, Stack); + Temp : Stack := From; + begin + if Temp = null then + raise Stack_Empty_Error; + end if; + Item := Temp.Element; + From := Temp.Next; + Free(Temp); + end Pop; + +end Generic_Stack; diff --git a/Task/Stack/ArkScript/stack.ark b/Task/Stack/ArkScript/stack.ark new file mode 100644 index 0000000000..d199ce5f2e --- /dev/null +++ b/Task/Stack/ArkScript/stack.ark @@ -0,0 +1,26 @@ +(let stack (fun () { + (mut data []) + + (let push (fun (value) (set data (concat [value] data)))) + (let popTop (fun () { + (let res (head data)) + (pop! data 0) + res })) + (let isEmpty? (fun () (empty? data))) + + (fun (&data &push &popTop &isEmpty?) ()) })) + +(let myStack (stack)) +(myStack.push 1) +(myStack.push 2) +(myStack.push 3) + +(print myStack.data) + +(print "top: " (myStack.popTop)) +(print myStack.data) + +(print "empty: " (myStack.isEmpty?)) +(myStack.popTop) +(myStack.popTop) +(print "empty: " (myStack.isEmpty?)) diff --git a/Task/Stack/Batch-File/stack-1.bat b/Task/Stack/Batch-File/stack-1.bat new file mode 100644 index 0000000000..99f8f80f57 --- /dev/null +++ b/Task/Stack/Batch-File/stack-1.bat @@ -0,0 +1,69 @@ +@echo off +setlocal enableDelayedExpansion + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: LIFO stack usage + +:: Define the stack +call :newStack myStack + +:: Push some values onto the stack +for %%A in (value1 value2 value3) do call :pushStack myStack %%A + +:: Test if stack is empty by examining the top "attribute" +if myStack.top==0 (echo myStack is empty) else (echo myStack is NOT empty) + +:: Peek at the top stack value +call:peekStack myStack val && echo a peek at the top of myStack shows !val! + +:: Pop the top stack value +call :popStack myStack val && echo popped myStack value=!val! + +:: Push some more values onto the stack +for %%A in (value4 value5 value6) do call :pushStack myStack %%A + +:: Process the remainder of the stack +:processStack +call :popStack myStack val || goto :stackEmpty +echo popped myStack value=!val! +goto :processStack +:stackEmpty + +:: Test if stack is empty using the empty "method"/"macro". Use of the +:: second IF statement serves to demonstrate the negation of the empty +:: "method". A single IF could have been used with an ELSE clause instead. +if %myStack.empty% echo myStack is empty +if not %myStack.empty% echo myStack is NOT empty +exit /b + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: LIFO stack definition + +:newStack stackName +set /a %~1.top=0 +:: Define an empty "method" for this stack as a sort of macro +set "%~1.empty=^!%~1.top^! == 0" +exit /b + +:pushStack stackName value +set /a %~1.top+=1 +set %~1.!%~1.top!=%2 +exit /b + +:popStack stackName returnVar +:: Sets errorlevel to 0 if success +:: Sets errorlevel to 1 if failure because stack was empty +if !%~1.top! equ 0 exit /b 1 +for %%N in (!%~1.top!) do ( + set %~2=!%~1.%%N! + set %~1.%%N= +) +set /a %~1.top-=1 +exit /b 0 + +:peekStack stackName returnVar +:: Sets errorlevel to 0 if success +:: Sets errorlevel to 1 if failure because stack was empty +if !%~1.top! equ 0 exit /b 1 +for %%N in (!%~1.top!) do set %~2=!%~1.%%N! +exit /b 0 diff --git a/Task/Stack/Batch-File/stack-2.bat b/Task/Stack/Batch-File/stack-2.bat new file mode 100644 index 0000000000..6d54baa760 --- /dev/null +++ b/Task/Stack/Batch-File/stack-2.bat @@ -0,0 +1,22 @@ +@echo off +setlocal enabledelayedexpansion +(set lf=^ + +) +(set stack= +set stack.push=set "stack=#^!lf^!^!stack^!" +set stack.pop=for %%l in ("^!lf^!"^) do set "stack=^!stack:*%%~l=^!" +set stack.empty=(call;^&if defined stack call^) +set stack.top=echo:^^!stack^^! ^| (set /p _=^& call echo:%%_%%^)) +:: ^ stack.top : https://stackoverflow.com/a/14965458 +%stack.push:#=1% +%stack.push:#=2% +%stack.top% +for %%l in ("!lf!") do echo:"!stack:%%~l= !" +%stack.pop% +for %%l in ("!lf!") do echo:"!stack:%%~l= !" +%stack.empty% && echo empty: true || echo empty: false +%stack.pop% +for %%l in ("!lf!") do echo:"!stack:%%~l= !" +%stack.empty% && echo empty: true || echo empty: false +goto:eof diff --git a/Task/Stack/COBOL/stack-1.cob b/Task/Stack/COBOL/stack-1.cob new file mode 100644 index 0000000000..55ba57711f --- /dev/null +++ b/Task/Stack/COBOL/stack-1.cob @@ -0,0 +1,2 @@ + 01 stack. + 05 head USAGE IS POINTER VALUE NULL. diff --git a/Task/Stack/COBOL/stack-2.cob b/Task/Stack/COBOL/stack-2.cob new file mode 100644 index 0000000000..56bfae0a1c --- /dev/null +++ b/Task/Stack/COBOL/stack-2.cob @@ -0,0 +1,5 @@ + 01 node BASED. + COPY node-info REPLACING + 01 BY 05 + node-info BY info. + 05 link USAGE IS POINTER VALUE NULL. diff --git a/Task/Stack/COBOL/stack-3.cob b/Task/Stack/COBOL/stack-3.cob new file mode 100644 index 0000000000..5f8f3d29ec --- /dev/null +++ b/Task/Stack/COBOL/stack-3.cob @@ -0,0 +1 @@ + 01 node-info PICTURE X(10) VALUE SPACES. diff --git a/Task/Stack/COBOL/stack-4.cob b/Task/Stack/COBOL/stack-4.cob new file mode 100644 index 0000000000..2da7f657c6 --- /dev/null +++ b/Task/Stack/COBOL/stack-4.cob @@ -0,0 +1,3 @@ + 01 p PICTURE 9. + 88 nil VALUE ZERO WHEN SET TO FALSE IS 1. + 88 t VALUE 1 WHEN SET TO FALSE IS ZERO. diff --git a/Task/Stack/COBOL/stack-5.cob b/Task/Stack/COBOL/stack-5.cob new file mode 100644 index 0000000000..65feb75713 --- /dev/null +++ b/Task/Stack/COBOL/stack-5.cob @@ -0,0 +1,247 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. push. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node. + LINKAGE SECTION. + COPY stack. + 01 node-info-any PICTURE X ANY LENGTH. + PROCEDURE DIVISION USING stack node-info-any. + ALLOCATE node + CALL "pointerp" USING + BY REFERENCE ADDRESS OF node + BY REFERENCE p + END-CALL + IF nil + CALL "stack-overflow-error" END-CALL + ELSE + MOVE node-info-any TO info OF node + SET link OF node TO head OF stack + SET head OF stack TO ADDRESS OF node + END-IF + GOBACK. + END PROGRAM push. + + IDENTIFICATION DIVISION. + PROGRAM-ID. pop. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node. + LINKAGE SECTION. + COPY stack. + COPY node-info. + PROCEDURE DIVISION USING stack node-info. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF t + CALL "stack-underflow-error" END-CALL + ELSE + SET ADDRESS OF node TO head OF stack + SET head OF stack TO link OF node + MOVE info OF node TO node-info + END-IF + FREE ADDRESS OF node + GOBACK. + END PROGRAM pop. + + IDENTIFICATION DIVISION. + PROGRAM-ID. empty. + DATA DIVISION. + LOCAL-STORAGE SECTION. + LINKAGE SECTION. + COPY stack. + COPY p. + PROCEDURE DIVISION USING stack p. + CALL "pointerp" USING + BY CONTENT head OF stack + BY REFERENCE p + END-CALL + IF t + SET t TO FALSE + ELSE + SET t TO TRUE + END-IF + GOBACK. + END PROGRAM empty. + + IDENTIFICATION DIVISION. + PROGRAM-ID. head. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node. + LINKAGE SECTION. + COPY stack. + COPY node-info. + PROCEDURE DIVISION USING stack node-info. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF t + CALL "stack-underflow-error" END-CALL + ELSE + SET ADDRESS OF node TO head OF stack + MOVE info OF node TO node-info + END-IF + GOBACK. + END PROGRAM head. + + IDENTIFICATION DIVISION. + PROGRAM-ID. peek. + DATA DIVISION. + LOCAL-STORAGE SECTION. + LINKAGE SECTION. + COPY stack. + COPY node-info. + PROCEDURE DIVISION USING stack node-info. + CALL "head" USING + BY CONTENT stack + BY REFERENCE node-info + END-CALL + GOBACK. + END PROGRAM peek. + + IDENTIFICATION DIVISION. + PROGRAM-ID. pointerp. + DATA DIVISION. + LINKAGE SECTION. + 01 test-pointer USAGE IS POINTER. + COPY p. + PROCEDURE DIVISION USING test-pointer p. + IF test-pointer EQUAL NULL + SET nil TO TRUE + ELSE + SET t TO TRUE + END-IF + GOBACK. + END PROGRAM pointerp. + + IDENTIFICATION DIVISION. + PROGRAM-ID. stack-overflow-error. + PROCEDURE DIVISION. + DISPLAY "stack-overflow-error" END-DISPLAY + STOP RUN. + END PROGRAM stack-overflow-error. + + IDENTIFICATION DIVISION. + PROGRAM-ID. stack-underflow-error. + PROCEDURE DIVISION. + DISPLAY "stack-underflow-error" END-DISPLAY + STOP RUN. + END PROGRAM stack-underflow-error. + + IDENTIFICATION DIVISION. + PROGRAM-ID. copy-stack. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node-info. + LINKAGE SECTION. + COPY stack. + COPY stack REPLACING stack BY new-stack. + PROCEDURE DIVISION USING stack new-stack. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF nil + CALL "pop" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + CALL "copy-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "push" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + CALL "push" USING + BY REFERENCE new-stack + BY REFERENCE node-info + END-CALL + END-IF + GOBACK. + END PROGRAM copy-stack. + + IDENTIFICATION DIVISION. + PROGRAM-ID. reverse-stack. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node-info. + LINKAGE SECTION. + COPY stack. + COPY stack REPLACING stack BY new-stack. + PROCEDURE DIVISION USING stack new-stack. + CALL "empty" USING + BY REFERENCE stack + BY REFERENCE p + END-CALL + IF nil + CALL "pop" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + CALL "push" USING + BY REFERENCE new-stack + BY REFERENCE node-info + END-CALL + CALL "reverse-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "push" USING + BY REFERENCE stack + BY REFERENCE node-info + END-CALL + END-IF + GOBACK. + END PROGRAM reverse-stack. + + IDENTIFICATION DIVISION. + PROGRAM-ID. traverse-stack. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY p. + COPY node-info. + COPY stack REPLACING stack BY new-stack. + LINKAGE SECTION. + COPY stack. + PROCEDURE DIVISION USING stack. + CALL "copy-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "empty" USING + BY REFERENCE new-stack + BY REFERENCE p + END-CALL + IF nil + CALL "head" USING + BY CONTENT new-stack + BY REFERENCE node-info + END-CALL + DISPLAY node-info END-DISPLAY + CALL "peek" USING + BY CONTENT new-stack + BY REFERENCE node-info + END-CALL + DISPLAY node-info END-DISPLAY + CALL "pop" USING + BY REFERENCE new-stack + BY REFERENCE node-info + END-CALL + DISPLAY node-info END-DISPLAY + CALL "traverse-stack" USING + BY REFERENCE new-stack + END-CALL + END-IF + GOBACK. + END PROGRAM traverse-stack. diff --git a/Task/Stack/COBOL/stack-6.cob b/Task/Stack/COBOL/stack-6.cob new file mode 100644 index 0000000000..e3059b6834 --- /dev/null +++ b/Task/Stack/COBOL/stack-6.cob @@ -0,0 +1,37 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. stack-test. + DATA DIVISION. + LOCAL-STORAGE SECTION. + COPY stack. + COPY stack REPLACING stack BY new-stack. + PROCEDURE DIVISION. + CALL "push" USING + BY REFERENCE stack + BY CONTENT "daleth" + END-CALL + CALL "push" USING + BY REFERENCE stack + BY CONTENT "gimel" + END-CALL + CALL "push" USING + BY REFERENCE stack + BY CONTENT "beth" + END-CALL + CALL "push" USING + BY REFERENCE stack + BY CONTENT "aleph" + END-CALL + CALL "traverse-stack" USING + BY REFERENCE stack + END-CALL + CALL "reverse-stack" USING + BY REFERENCE stack + BY REFERENCE new-stack + END-CALL + CALL "traverse-stack" USING + BY REFERENCE new-stack + END-CALL + STOP RUN. + END PROGRAM stack-test. + + COPY stack-utilities. diff --git a/Task/Stack/Gleam/stack.gleam b/Task/Stack/Gleam/stack.gleam new file mode 100644 index 0000000000..f5f536eef9 --- /dev/null +++ b/Task/Stack/Gleam/stack.gleam @@ -0,0 +1,38 @@ +import gleam/option.{type Option, None, Some} + +/// Stack(a) is just an alias for a List(a) +pub type Stack(a) = + List(a) + +/// An empty stack is an empty list. +pub const empty = [] + +/// is_empty(s) checks if the stack s is empty. +pub fn is_empty(stack: Stack(a)) -> Bool { + case stack { + [] -> True + _ -> False + } +} + +/// push(s,x) pushes the element x onto the stack s. +pub fn push(stack: Stack(a), x: a) -> Stack(a) { + [x, ..stack] +} + +/// peek(s) returns the TOS. +pub fn peek(stack: Stack(a)) -> Result(a, Nil) { + case stack { + [] -> Error(Nil) + [h, ..] -> Ok(h) + } +} + +/// pop(s) pops an element from the TOS, and returns that +/// and the modified stack. +pub fn pop(stack: Stack(a)) -> Result(#(a, Stack(a)), Nil) { + case stack { + [h, ..tl] -> Ok(#(h, tl)) + _ -> Error(Nil) + } +} diff --git a/Task/Stack/Oberon-07/stack-1.oberon b/Task/Stack/Oberon-07/stack-1.oberon new file mode 100644 index 0000000000..d9d5566df1 --- /dev/null +++ b/Task/Stack/Oberon-07/stack-1.oberon @@ -0,0 +1,43 @@ +MODULE StackOfInteger; + + TYPE T = INTEGER; + Element = RECORD value : T; next : POINTER TO Element END; + StackRecord = RECORD top : POINTER TO Element END; + Stack* = POINTER TO StackRecord; + + PROCEDURE push*( s : Stack; v : T ); + VAR newElement : POINTER TO Element; + BEGIN + NEW( newElement ); + newElement.value := v; + newElement.next := s.top; + s.top := newElement + END push; + + PROCEDURE peek*( s : Stack ) : T; + BEGIN + RETURN s.top.value + END peek; + + PROCEDURE pop*( s : Stack ) : T; + VAR v : T; + BEGIN + v := peek( s ); + s.top := s.top.next + RETURN v + END pop; + + PROCEDURE empty*( s : Stack ) : BOOLEAN; + BEGIN + RETURN s.top = NIL + END empty; + + PROCEDURE newStack*() : Stack; + VAR s : Stack; + BEGIN + NEW( s ); + s.top := NIL; + RETURN s + END newStack; + +END StackOfInteger. diff --git a/Task/Stack/Oberon-07/stack-2.oberon b/Task/Stack/Oberon-07/stack-2.oberon new file mode 100644 index 0000000000..95e7f40725 --- /dev/null +++ b/Task/Stack/Oberon-07/stack-2.oberon @@ -0,0 +1,26 @@ +MODULE UseStack; (* use the StackOfInteger module *) + IMPORT Out, SI := StackOfInteger; (* imports StackOfInteger under the name "SI" *) + + VAR st : SI.Stack; + v, sum : INTEGER; + +BEGIN + + st := SI.newStack(); (* create a stack *) + + SI.push( st, 1 ); (* add some items *) + SI.push( st, 23 ); + SI.push( st, 456 ); + + WHILE ~ SI.empty( st ) DO (* unstack, sum and print the items *) + v := SI.pop( st ); + INC( sum, v ); + Out.Int( v, 0 ); + IF ~ SI.empty( st ) THEN + Out.String( " (" );Out.Int( SI.peek( st ), 0 );Out.String( ")" ) + END; + Out.Ln + END; + Out.String( "sum: " );Out.Int( sum, 0 );Out.Ln + +END UseStack. diff --git a/Task/Stack/PowerShell/stack-1.ps1 b/Task/Stack/PowerShell/stack-1.ps1 new file mode 100644 index 0000000000..f83362b615 --- /dev/null +++ b/Task/Stack/PowerShell/stack-1.ps1 @@ -0,0 +1,3 @@ +$stack = New-Object -TypeName System.Collections.Stack +# or +$stack = [System.Collections.Stack] @() diff --git a/Task/Stack/PowerShell/stack-2.ps1 b/Task/Stack/PowerShell/stack-2.ps1 new file mode 100644 index 0000000000..dbbecf2bf8 --- /dev/null +++ b/Task/Stack/PowerShell/stack-2.ps1 @@ -0,0 +1 @@ +1, 2, 3, 4 | ForEach-Object {$stack.Push($_)} diff --git a/Task/Stack/PowerShell/stack-3.ps1 b/Task/Stack/PowerShell/stack-3.ps1 new file mode 100644 index 0000000000..961f99291f --- /dev/null +++ b/Task/Stack/PowerShell/stack-3.ps1 @@ -0,0 +1 @@ +$stack -join ", " diff --git a/Task/Stack/PowerShell/stack-4.ps1 b/Task/Stack/PowerShell/stack-4.ps1 new file mode 100644 index 0000000000..ae007a839e --- /dev/null +++ b/Task/Stack/PowerShell/stack-4.ps1 @@ -0,0 +1 @@ +$stack.Pop() diff --git a/Task/Stack/PowerShell/stack-5.ps1 b/Task/Stack/PowerShell/stack-5.ps1 new file mode 100644 index 0000000000..961f99291f --- /dev/null +++ b/Task/Stack/PowerShell/stack-5.ps1 @@ -0,0 +1 @@ +$stack -join ", " diff --git a/Task/Stack/PowerShell/stack-6.ps1 b/Task/Stack/PowerShell/stack-6.ps1 new file mode 100644 index 0000000000..2bc6e4e5b1 --- /dev/null +++ b/Task/Stack/PowerShell/stack-6.ps1 @@ -0,0 +1 @@ +$stack.Peek() diff --git a/Task/Stack/PowerShell/stack-7.ps1 b/Task/Stack/PowerShell/stack-7.ps1 new file mode 100644 index 0000000000..a9af01c052 --- /dev/null +++ b/Task/Stack/PowerShell/stack-7.ps1 @@ -0,0 +1 @@ +$stack diff --git a/Task/Stack/Rebol/stack-1.rebol b/Task/Stack/Rebol/stack-1.rebol new file mode 100644 index 0000000000..ddf98d7f1d --- /dev/null +++ b/Task/Stack/Rebol/stack-1.rebol @@ -0,0 +1,6 @@ +stack: copy [] +append stack 1 ;== [1] +append stack 2 ;== [1 2] +take/last stack ;== 2 +take/last stack ;== 1 +empty? stack ;== true diff --git a/Task/Stack/Rebol/stack-2.rebol b/Task/Stack/Rebol/stack-2.rebol new file mode 100644 index 0000000000..ccc8859d2f --- /dev/null +++ b/Task/Stack/Rebol/stack-2.rebol @@ -0,0 +1,34 @@ +Rebol [ + Title: "Stack" + URL: http://rosettacode.org/wiki/Stack +] + +stack: make object! [ + data: copy [] + + push: func [x][append data x] + pop: func [/local x][x: last data remove back tail data x] + empty: does [empty? data] + + peek: does [last data] +] + +; Teeny Tiny Test Suite + +assert: func [code][print [either do code [" ok"]["FAIL"] mold code]] + +print "Simple integers:" +s: make stack [] s/push 1 s/push 2 ; Initialize. + +assert [2 = s/peek] +assert [2 = s/pop] +assert [1 = s/pop] +assert [s/empty] + +print [lf "Symbolic data on stack:"] +v: make stack [data: [this is a test]] ; Initialize on instance. + +assert ['test = v/peek] +assert ['test = v/pop] +assert ['a = v/pop] +assert [not v/empty] diff --git a/Task/Stack/VBScript/stack-1.vbs b/Task/Stack/VBScript/stack-1.vbs new file mode 100644 index 0000000000..d775f8912a --- /dev/null +++ b/Task/Stack/VBScript/stack-1.vbs @@ -0,0 +1,56 @@ +class stack + dim tos + dim stack() + dim stacksize + + private sub class_initialize + stacksize = 100 + redim stack( stacksize ) + tos = 0 + end sub + + public sub push( x ) + stack(tos) = x + tos = tos + 1 + end sub + + public property get stackempty + stackempty = ( tos = 0 ) + end property + + public property get stackfull + stackfull = ( tos > stacksize ) + end property + + public property get stackroom + stackroom = stacksize - tos + end property + + public function pop() + pop = stack( tos - 1 ) + tos = tos - 1 + end function + + public sub resizestack( n ) + redim preserve stack( n ) + stacksize = n + if tos > stacksize then + tos = stacksize + end if + end sub +end class + +dim s +set s = new stack +s.resizestack 10 +wscript.echo s.stackempty +dim i +for i = 1 to 10 + s.push rnd + wscript.echo s.stackroom + if s.stackroom = 0 then exit for +next +for i = 1 to 10 + wscript.echo s.pop + if s.stackempty then exit for +next diff --git a/Task/Stack/VBScript/stack-2.vbs b/Task/Stack/VBScript/stack-2.vbs new file mode 100644 index 0000000000..a93ebbd9e6 --- /dev/null +++ b/Task/Stack/VBScript/stack-2.vbs @@ -0,0 +1,39 @@ +' Stack Definition - VBScript + +Option Explicit + +Dim stack, i, x +Set stack = CreateObject("System.Collections.ArrayList") +If Not empty_(stack) Then Wscript.Echo stack.Count +push stack, "Banana" +push stack, "Apple" +push stack, "Pear" +push stack, "Strawberry" +Wscript.Echo "Count=" & stack.Count ' --> Count=4 +Wscript.Echo pop(stack) & " - Count=" & stack.Count ' --> Strawberry - Count=3 +Wscript.Echo "Tail=" & stack.Item(0) ' --> Tail=Banana +Wscript.Echo "Head=" & stack.Item(stack.Count-1) ' --> Head=Pear +Wscript.Echo stack.IndexOf("Apple", 0) ' --> 1 +For i=1 To stack.Count + Wscript.Echo join(stack.ToArray(), ", ") + x = pop(stack) +Next 'i + +Sub push(s, what) + s.Add what +End Sub 'push + +Function pop(s) + Dim what + If s.Count > 0 Then + what = s(s.Count-1) + s.RemoveAt s.Count-1 + Else + what = "" + End If + pop = what +End Function 'pop + +Function empty_(s) + empty_ = s.Count = 0 +End Function 'empty_ diff --git a/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.adb b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.adb new file mode 100644 index 0000000000..5550b287c3 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-1.adb @@ -0,0 +1,6 @@ +procedure Step_Up is +begin + while not Step loop + Step_Up; + end loop; +end Step_Up; diff --git a/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.adb b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.adb new file mode 100644 index 0000000000..dca8a1471f --- /dev/null +++ b/Task/Stair-climbing-puzzle/Ada/stair-climbing-puzzle-2.adb @@ -0,0 +1,32 @@ +with Ada.Numerics.Discrete_Random; +with Ada.Text_IO; + +procedure Scaffolding is + package Try is new Ada.Numerics.Discrete_Random (Boolean); + use Try; + Dice : Generator; + Level : Integer := 0; + + function Step return Boolean is + begin + if Random (Dice) then + Level := Level + 1; + Ada.Text_IO.Put_Line ("Climbed up to" & Integer'Image (Level)); + return True; + else + Level := Level - 1; + Ada.Text_IO.Put_Line ("Fell down to" & Integer'Image (Level)); + return False; + end if; + end Step; + + procedure Step_Up is + begin + while not Step loop + Step_Up; + end loop; + end Step_Up; +begin + Reset (Dice); + Step_Up; +end Scaffolding; diff --git a/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy index bbec793fc5..e662530544 100644 --- a/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy +++ b/Task/Stair-climbing-puzzle/EasyLang/stair-climbing-puzzle.easy @@ -1,5 +1,5 @@ func step . - if random 2 = 2 + if random 1 2 = 2 print "climbed up" return 1 else @@ -8,8 +8,6 @@ func step . . . proc step_up . - while step = 0 - step_up - . + while step = 0 : step_up . step_up diff --git a/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.eu b/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.eu new file mode 100644 index 0000000000..7f6e4646a7 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Euphoria/stair-climbing-puzzle.eu @@ -0,0 +1,6 @@ +procedure step_up() + if not step() then + step_up() + step_up() + end if +end procedure diff --git a/Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.ps1 b/Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.ps1 new file mode 100644 index 0000000000..f41bd6a8d3 --- /dev/null +++ b/Task/Stair-climbing-puzzle/PowerShell/stair-climbing-puzzle.ps1 @@ -0,0 +1,28 @@ +function StepUp + { + If ( -not ( Step ) ) + { + StepUp + StepUp + } + } + +# Step simulator for testing +function Step + { + If ( Get-Random 0,1 ) + { + $Success = $True + Write-Verbose "Up one step" + } + Else + { + $Success = $False + Write-Verbose "Fell one step" + } + return $Success + } + +# Test +$VerbosePreference = 'Continue' +StepUp diff --git a/Task/Stair-climbing-puzzle/Rebol/stair-climbing-puzzle.rebol b/Task/Stair-climbing-puzzle/Rebol/stair-climbing-puzzle.rebol new file mode 100644 index 0000000000..7d0877d2cf --- /dev/null +++ b/Task/Stair-climbing-puzzle/Rebol/stair-climbing-puzzle.rebol @@ -0,0 +1,39 @@ +Rebol [ + Title: "Stair Climber" + URL: http://rosettacode.org/wiki/Stair_Climbing +] + +random/seed now + +step: does [random/only reduce [yes no]] + +; Iterative solution with symbol stack. No numbers, draws a nifty +; diagram of number of steps to go. This is intended more to +; demonstrate a correct solution: + +step_up: func [/steps s] [ + either not steps [ + print "Starting up..." + step_up/steps copy [|] + ][ + while [not empty? s][ + print [" Steps left:" s] + either step [remove s][append s '|] + ] + ] +] + +step_up print ["Success!" crlf] + +; Recursive solution. No numbers, no variables. "R" means a recover +; step, "+" means a step up. + +step_upr: does [if not step [prin "R " step_upr prin "+ " step_upr]] + +step_upr print ["Success!" crlf] + +; Small recursive solution, no monitoring: + +step_upt: does [if not step [step_upt step_upt]] + +step_upt print "Success!" diff --git a/Task/Stair-climbing-puzzle/V-(Vlang)/stair-climbing-puzzle.v b/Task/Stair-climbing-puzzle/V-(Vlang)/stair-climbing-puzzle.v new file mode 100644 index 0000000000..110deebf3f --- /dev/null +++ b/Task/Stair-climbing-puzzle/V-(Vlang)/stair-climbing-puzzle.v @@ -0,0 +1,32 @@ +import rand +import rand.seed + +struct Walker { + mut: + position int +} + +fn (mut wr Walker) step() bool { + rm := rand.u32() > (max_u32 / 2) + if rm { + wr.position += 1 + println("Climbed up to ${wr.position}") + } else { + wr.position -= 1 + println("Fell down to ${wr.position}") + } + return rm +} + +fn (mut wr Walker) step_up() { + for !wr.step() { + wr.step_up() + } +} + +fn main() { + seeds := seed.time_seed_array(2) + rand.seed(seeds) + mut walker := Walker{0} + walker.step_up() +} diff --git a/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.adb b/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.adb new file mode 100644 index 0000000000..b515644a80 --- /dev/null +++ b/Task/Start-from-a-main-routine/Ada/start-from-a-main-routine.adb @@ -0,0 +1,5 @@ +with Ada.Text_IO; +procedure Foo is +begin + Ada.Text_IO.Put_Line("Bar"); +end Foo; diff --git a/Task/Start-from-a-main-routine/FutureBasic/start-from-a-main-routine.basic b/Task/Start-from-a-main-routine/FutureBasic/start-from-a-main-routine.basic new file mode 100644 index 0000000000..3a73ad4cc5 --- /dev/null +++ b/Task/Start-from-a-main-routine/FutureBasic/start-from-a-main-routine.basic @@ -0,0 +1,7 @@ +void local fn Start + printf @"Hello, World!" +end fn + +fn Start + +HandleEvents diff --git a/Task/Start-from-a-main-routine/Pluto/start-from-a-main-routine.pluto b/Task/Start-from-a-main-routine/Pluto/start-from-a-main-routine.pluto new file mode 100644 index 0000000000..625f8c2207 --- /dev/null +++ b/Task/Start-from-a-main-routine/Pluto/start-from-a-main-routine.pluto @@ -0,0 +1,5 @@ +local function main() + print("Hello from the main function.") +end + +main() diff --git a/Task/Start-from-a-main-routine/Python/start-from-a-main-routine.py b/Task/Start-from-a-main-routine/Python/start-from-a-main-routine.py new file mode 100644 index 0000000000..73c6bec2ff --- /dev/null +++ b/Task/Start-from-a-main-routine/Python/start-from-a-main-routine.py @@ -0,0 +1,5 @@ +def main(): + print("Hello, World!") + +if __name__ == "__main__": + main() diff --git a/Task/Start-from-a-main-routine/R/start-from-a-main-routine-1.r b/Task/Start-from-a-main-routine/R/start-from-a-main-routine-1.r new file mode 100644 index 0000000000..f68ca1bc2f --- /dev/null +++ b/Task/Start-from-a-main-routine/R/start-from-a-main-routine-1.r @@ -0,0 +1,4 @@ +library(usethis) +edit_r_profile() +#Put the below line in .Rprofile +.First <- cat("This runs whenever you start R.\n") diff --git a/Task/Start-from-a-main-routine/R/start-from-a-main-routine-2.r b/Task/Start-from-a-main-routine/R/start-from-a-main-routine-2.r new file mode 100644 index 0000000000..2bad47addc --- /dev/null +++ b/Task/Start-from-a-main-routine/R/start-from-a-main-routine-2.r @@ -0,0 +1 @@ +.First <- source(file="main.R") diff --git a/Task/Statistics-Basic/ANSI-BASIC/statistics-basic.basic b/Task/Statistics-Basic/ANSI-BASIC/statistics-basic.basic new file mode 100644 index 0000000000..96741f4182 --- /dev/null +++ b/Task/Statistics-Basic/ANSI-BASIC/statistics-basic.basic @@ -0,0 +1,60 @@ +100 REM Statistics/Basic +110 DECLARE EXTERNAL SUB BasicStats +120 CALL BasicStats(100) +130 PRINT +140 CALL BasicStats(1000) +150 PRINT +160 CALL BasicStats(10000) +170 PRINT +180 END +190 REM *** +200 EXTERNAL SUB BasicStats (SampleSize) +210 IF SampleSize < 1 THEN EXIT SUB +220 DIM R(1 TO 10000) +230 LET MaxSampleSize = UBOUND(R) +240 IF SampleSize > MaxSampleSize THEN +250 PRINT "Sample size too large" +260 STOP +270 END IF +280 RANDOMIZE +290 DIM H(0 TO 9) ! all zero by default +300 LET Sum = 0 +310 LET HSum = 0 +320 REM Gener!ate 'SampleSize' random numbers in the interval [0, 1) +330 REM calculate their Sum +340 REM and in which box they will fall when drawing the histogram +350 FOR I = 1 TO SampleSize +360 LET R(I) = RND +370 LET Sum = Sum + R(I) +380 LET H(INT(R(I) * 10)) = H(INT(R(I) * 10)) + 1 +390 NEXT I +400 FOR I = 0 TO 9 +410 LET HSum = HSum + H(I) +420 NEXT I +430 REM adjust one of the H() values if necessary to ensure HSum = SampleSize +440 LET Adj = SampleSize - HSum +450 IF Adj <> 0 THEN +460 FOR I = 0 TO 9 +470 LET H(I) = H(I) + Adj +480 IF H(I) >= 0 THEN EXIT FOR +490 LET H(I) = H(I) - Adj +500 NEXT I +510 END IF +520 LET Mean = Sum / SampleSize +530 LET Sum = 0 +540 REM Now calculate their standard deviation +550 FOR I = 1 TO SampleSize +560 LET Sum = Sum + (R(I) - Mean) ^ 2 +570 NEXT I +580 LET Sd = SQR(Sum / SampleSize) +590 REM Draw a histogram of the data with interval 0.1 +600 REM If sample size > 500 then normalize histogram to 500 +610 LET Scale = 1 +620 IF SampleSize > 500 THEN LET Scale = 500 / SampleSize +630 PRINT "Sample size"; SampleSize +640 PRINT USING " Mean #.###### SD #.######": Mean, Sd +650 FOR I = 0 TO 9 +660 PRINT USING " #.## : ##### ": I / 10, H(I); +670 PRINT REPEAT$("*", ROUND(H(I) * Scale, 0)) +680 NEXT I +690 END SUB diff --git a/Task/Statistics-Basic/Ada/statistics-basic-1.adb b/Task/Statistics-Basic/Ada/statistics-basic-1.adb new file mode 100644 index 0000000000..d48ed0a579 --- /dev/null +++ b/Task/Statistics-Basic/Ada/statistics-basic-1.adb @@ -0,0 +1,63 @@ +with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random, + Ada.Numerics.Generic_Elementary_Functions; + +procedure Basic_Stat is + + package FRG renames Ada.Numerics.Float_Random; + package TIO renames Ada.Text_IO; + + type Counter is range 0 .. 2**31-1; + type Result_Array is array(Natural range <>) of Counter; + + package FIO is new TIO.Float_IO(Float); + + procedure Put_Histogram(R: Result_Array; Scale, Full: Counter) is + begin + for I in R'Range loop + FIO.Put(Float'Max(0.0, Float(I)/10.0 - 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(".."); + FIO.Put(Float'Min(1.0, Float(I)/10.0 + 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(": "); + for J in 1 .. (R(I)* Scale)/Full loop + Ada.Text_IO.Put("X"); + end loop; + Ada.Text_IO.New_Line; + end loop; + end Put_Histogram; + + procedure Put_Mean_Et_Al(Sample_Size: Counter; + Val_Sum, Square_Sum: Float) is + Mean: constant Float := Val_Sum / Float(Sample_Size); + package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); + begin + TIO.Put("Mean: "); + FIO.Put(Mean, Fore => 1, Aft => 5, Exp => 0); + TIO.Put(", Standard Deviation: "); + FIO.Put(Math.Sqrt(abs(Square_Sum / Float(Sample_Size) + - (Mean * Mean))), Fore => 1, Aft => 5, Exp => 0); + TIO.New_Line; + end Put_Mean_Et_Al; + + N: Counter := Counter'Value(Ada.Command_Line.Argument(1)); + Gen: FRG.Generator; + Results: Result_Array(0 .. 10) := (others => 0); + X: Float; + Val_Sum, Squ_Sum: Float := 0.0; + +begin + FRG.Reset(Gen); + for I in 1 .. N loop + X := FRG.Random(Gen); + Val_Sum := Val_Sum + X; + Squ_Sum := Squ_Sum + X*X; + declare + Index: Integer := Integer(X*10.0); + begin + Results(Index) := Results(Index) + 1; + end; + end loop; + TIO.Put_Line("After sampling" & Counter'Image(N) & " random numnbers: "); + Put_Histogram(Results, Scale => 600, Full => N); + TIO.New_Line; + Put_Mean_Et_Al(Sample_Size => N, Val_Sum => Val_Sum, Square_Sum => Squ_Sum); +end Basic_Stat; diff --git a/Task/Statistics-Basic/Ada/statistics-basic-2.adb b/Task/Statistics-Basic/Ada/statistics-basic-2.adb new file mode 100644 index 0000000000..407ad5d551 --- /dev/null +++ b/Task/Statistics-Basic/Ada/statistics-basic-2.adb @@ -0,0 +1,77 @@ +with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random, + Ada.Numerics.Generic_Elementary_Functions; + +procedure Long_Basic_Stat is + + package FRG renames Ada.Numerics.Float_Random; + package TIO renames Ada.Text_IO; + + type Counter is range 0 .. 2**63-1; + type Result_Array is array(Natural range <>) of Counter; + type High_Precision is digits 15; + + package FIO is new TIO.Float_IO(Float); + + procedure Put_Histogram(R: Result_Array; Scale, Full: Counter) is + begin + for I in R'Range loop + FIO.Put(Float'Max(0.0, Float(I)/10.0 - 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(".."); + FIO.Put(Float'Min(1.0, Float(I)/10.0 + 0.05), + Fore => 1, Aft => 2, Exp => 0); TIO.Put(": "); + for J in 1 .. (R(I)* Scale)/Full loop + Ada.Text_IO.Put("X"); + end loop; + Ada.Text_IO.New_Line; + end loop; + end Put_Histogram; + + procedure Put_Mean_Et_Al(Sample_Size: Counter; + Val_Sum, Square_Sum: Float) is + Mean: constant Float := Val_Sum / Float(Sample_Size); + package Math is new Ada.Numerics.Generic_Elementary_Functions(Float); + begin + TIO.Put("Mean: "); + FIO.Put(Mean, Fore => 1, Aft => 5, Exp => 0); + TIO.Put(", Standard Deviation: "); + FIO.Put(Math.Sqrt(abs(Square_Sum / Float(Sample_Size) + - (Mean * Mean))), Fore => 1, Aft => 5, Exp => 0); + TIO.New_Line; + end Put_Mean_Et_Al; + + N: Counter := Counter'Value(Ada.Command_Line.Argument(1)); + Gen: FRG.Generator; + Results: Result_Array(0 .. 10) := (others => 0); + X: Float; + Val_Sum, Squ_Sum: High_Precision := 0.0; + +begin + FRG.Reset(Gen); + for Outer in 1 .. 1000 loop + for I in 1 .. N/1000 loop + X := FRG.Random(Gen); + Val_Sum := Val_Sum + High_Precision(X); + Squ_Sum := Squ_Sum + High_Precision(X)*High_Precision(X); + declare + Index: Integer := Integer(X*10.0); + begin + Results(Index) := Results(Index) + 1; + end; + end loop; + if Outer mod 50 = 0 then + TIO.New_Line(1); + TIO.Put_Line(Integer'Image(Outer/10) &"% done; current results:"); + Put_Mean_Et_Al(Sample_Size => (Counter(Outer)*N)/1000, + Val_Sum => Float(Val_Sum), + Square_Sum => Float(Squ_Sum)); + else + Ada.Text_IO.Put("."); + end if; + end loop; + TIO.New_Line(4); + TIO.Put_Line("After sampling" & Counter'Image(N) & " random numnbers: "); + Put_Histogram(Results, Scale => 600, Full => N); + TIO.New_Line; + Put_Mean_Et_Al(Sample_Size => N, + Val_Sum => Float(Val_Sum), Square_Sum => Float(Squ_Sum)); +end Long_Basic_Stat; diff --git a/Task/Statistics-Basic/Loglan82/statistics-basic.loglan82 b/Task/Statistics-Basic/Loglan82/statistics-basic.loglan82 new file mode 100644 index 0000000000..9dc28751a4 --- /dev/null +++ b/Task/Statistics-Basic/Loglan82/statistics-basic.loglan82 @@ -0,0 +1,71 @@ +(* Statistics/Basic *) + +block + + unit basic_stats: procedure (sample_size: integer); + var + r: arrayof real, + sum, scale, mean, diff, sd: real, + h: arrayof integer, + h_sum, i, j, adj: integer; + begin + if sample_size < 1 then return fi; + + array r dim (1 : sample_size); + array h dim (0 : 9); (* all zero by default *) + sum := 0.0; + h_sum := 0; + (* Generate 'sample_size' random numbers in the interval [0, 1). + Calculate their sum and in which box they will fall when drawing + the histogram *) + for i := 1 to sample_size + do + r(i) := random; + sum := sum + r(i); + h(entier(r(i) * 10)) := h(entier(r(i) * 10)) + 1 + od; + for i := 0 to 9 do h_sum := h_sum + h(i) od; + (* Adjust one of the h() values if necessary to ensure h_sum = sample_size *) + adj := sample_size - h_sum; + if adj =/= 0 + then + for i := 0 to 9 + do + h(i) := h(i) + adj; + if h(i) >= 0 then exit fi; + h(i) := h(i) - adj + od; + fi; + mean := sum / sample_size; + + sum := 0.0; + (* Now calculate their standard deviation *) + for i := 1 to sample_size + do + diff := r(i) - mean; + sum := sum + diff * diff + od; + sd := sqrt(sum / sample_size); + + (* Draw a histogram of the data with interval 0.1. + If sample size > 500 then normalize histogram to 500. *) + scale := 1.0; + if sample_size > 500 then scale := 500.0 / sample_size fi; + writeln("Sample size", sample_size); + writeln(" Mean ", mean: 8: 6, " SD ", sd: 8: 6); + for i := 0 to 9 + do + write(" ", i / 10.0: 4: 2, " : ", h(i): 5, " "); + for j := 1 to entier(h(i) * scale + .5) do write("*") od; + writeln + od; + end basic_stats; + +begin + call basic_stats(100); + writeln; + call basic_stats(1000); + writeln; + call basic_stats(10000); + writeln; +end; diff --git a/Task/Statistics-Basic/PHP/statistics-basic.php b/Task/Statistics-Basic/PHP/statistics-basic.php new file mode 100644 index 0000000000..97d34f80cb --- /dev/null +++ b/Task/Statistics-Basic/PHP/statistics-basic.php @@ -0,0 +1,67 @@ += 0) break; + $h[$i] -= $adj; + } + } + $mean = $sum / $sample_size; + + $sum = 0.0; + // Now calculate their standard deviation + foreach ($r as $r_item) + $sum += pow($r_item - $mean, 2); + $sd = sqrt($sum / $sample_size); + + // Draw a histogram of the data with interval 0.1 + // If sample size > 300 then normalize histogram to 300 + $scale = 1.0; + if ($sample_size > 500) + $scale = 500.0 / $sample_size; + echo 'Sample size '.$sample_size.PHP_EOL; + echo ' Mean '. + str_pad(number_format($mean, 6, '.', ''), 8, ' ', STR_PAD_LEFT). + ' SD '. + str_pad(number_format($sd, 6, '.', ''), 8, ' ', STR_PAD_LEFT).PHP_EOL; + $i = 0; + foreach ($h as $h_item) { + echo ' '. + str_pad(number_format($i / 10.0, 2, '.', ''), 4, ' ', STR_PAD_LEFT). + ' : '; + echo str_pad($h_item, 5, ' ', STR_PAD_LEFT).' '. + str_repeat('*', round($h_item * $scale)).PHP_EOL; + $i++; + } +} +?> diff --git a/Task/Statistics-Basic/Pluto/statistics-basic.pluto b/Task/Statistics-Basic/Pluto/statistics-basic.pluto new file mode 100644 index 0000000000..69aa3d2d9e --- /dev/null +++ b/Task/Statistics-Basic/Pluto/statistics-basic.pluto @@ -0,0 +1,22 @@ +require "table2" + +for {100, 1000, 10000} as i do + local a = table.create(i) + for j = 1, i do a[j] = math.random() end + print($"For {i} random numbers:") + print($" mean = {a:mean()}") + print($" std/dev = {a:stddev()}") + local scale = math.round(i / 100) + print($" scale = {scale} per asterisk") + local sums = table.rep(10, 0) + for a as e do + local f = math.floor(e * 10) + sums[f + 1] += 1 + end + for j = 1, 9 do + sums[j] = math.round(sums[j] / scale) + print($" 0.{j - 1} - 0.{j}: {string.rep("*", sums[j])}") + end + sums[10] = 100 - sums:slice(1, 9):sum() + print($" 0.9 - 1.0: {string.rep("*", sums[10])}\n") +end diff --git a/Task/Statistics-Basic/PowerShell/statistics-basic.ps1 b/Task/Statistics-Basic/PowerShell/statistics-basic.ps1 new file mode 100644 index 0000000000..2a63dc0a5d --- /dev/null +++ b/Task/Statistics-Basic/PowerShell/statistics-basic.ps1 @@ -0,0 +1,68 @@ +# Statistics/Basic + +function Write-BasicStats { + param ([uint32]$SampleSize) + if ($SampleSize -lt 1) { + return + } + + $r = [double[]]::new($SampleSize) + $h = [uint32[]]::new(10) # all zero by default + $sum = 0.0 + $hSum = 0 + + # Generate '$SampleSize' random numbers in the interval [0, 1) + # calculate their $sum + # and in which box they will fall when drawing the histogram + $iTo = $SampleSize - 1 + foreach ($i in 0..$iTo) { + $r[$i] = (Get-Random -Maximum 1.0) + $sum += $r[$i] + $h[[Math]::floor($r[$i] * 10)]++ + } + foreach ($hItem in $h) { + $hSum += $hItem + } + # adjust one of the $h[] values if necessary to ensure $hSum = $SampleSize + $adj = $SampleSize - $hSum + if ($adj -ne 0) { + $iTo = $h.Length - 1 + foreach ($i in 0..$iTo) { + $h[$i] += $adj + if ($h[$i] -ge 0) { + break + } + $h[$i] -= $adj + } + } + $mean = $sum / $SampleSize + + $sum = 0.0 + # Now calculate their standard deviation + foreach ($rItem in $r) { + $sum += [Math]::Pow($rItem - $mean, 2) + } + $sd = [Math]::Sqrt($sum / $SampleSize) + + # Draw a histogram of the data with interval 0.1 + # If sample size > 500 then normalize histogram to 500 + [double]$scale = 1.0 + if ($SampleSize -gt 500) { + $scale = 500.0 / $SampleSize + } + Write-Output "Sample size $SampleSize" + Write-Output (' Mean {0,8:N6} SD {1,8:N6}' -f $mean, $sd) + $i = 0 + foreach ($hItem in $h) { + $out = ' {0,4:N2} : {1,5} ' -f ($i / 10.0), $hItem + Write-Output ($out + ('*' * [Math]::Round($hItem * $scale))) + $i++ + } +} + +Write-BasicStats 100 +Write-Output "" +Write-BasicStats 1000 +Write-Output "" +Write-BasicStats 10000 +Write-Output "" diff --git a/Task/Statistics-Normal-distribution/ANSI-BASIC/statistics-normal-distribution.basic b/Task/Statistics-Normal-distribution/ANSI-BASIC/statistics-normal-distribution.basic new file mode 100644 index 0000000000..57057c7416 --- /dev/null +++ b/Task/Statistics-Normal-distribution/ANSI-BASIC/statistics-normal-distribution.basic @@ -0,0 +1,74 @@ +100 REM Statistics/Normal distribution +110 DECLARE EXTERNAL SUB NormalStats +120 CALL NormalStats(100) +130 PRINT +140 CALL NormalStats(1000) +150 PRINT +160 CALL NormalStats(10000) +170 PRINT +180 END +190 REM *** +200 EXTERNAL SUB NormalStats (SampleSize) +210 IF SampleSize < 1 THEN EXIT SUB +220 DIM R(1 TO 10000) +230 LET MaxSampleSize = UBOUND(R) +240 IF SampleSize > MaxSampleSize THEN +250 PRINT "Sample size too large" +260 STOP +270 END IF +280 RANDOMIZE +290 DIM H(-1 TO 10) ! all zero by default +300 LET Sum = 0 +310 LET HSum = 0 +320 REM Gener!ate 'SampleSize' normally distributed random numbers with Mean 0.5 and standard deviation 0.25 +330 REM calculate their Sum +340 REM and in which box they will fall when drawing the histogram +350 FOR I = 1 TO SampleSize +360 LET RandomNormal = COS(2 * PI * RND) * SQR(-2 * LOG(RND)) +370 LET R(I) = .5 + RandomNormal / 4 +380 LET Sum = Sum + R(I) +390 IF R(I) < 0 THEN +400 LET H(-1) = H(-1) + 1 +410 ELSEIF R(I) >= 1 THEN +420 LET H(10) = H(10) + 1 +430 ELSE +440 LET H(INT(R(I) * 10)) = H(INT(R(I) * 10)) + 1 +450 END IF +460 NEXT I +470 FOR I = -1 TO 10 +480 LET HSum = HSum + H(I) +490 NEXT I +500 REM adjust one of the H() values if necessary to ensure HSum = SampleSize +510 LET Adj = SampleSize - HSum +520 IF Adj <> 0 THEN +530 FOR I = -1 TO 10 +540 LET H(I) = H(I) + Adj +550 IF H(I) >= 0 THEN EXIT FOR +560 LET H(I) = H(I) - Adj +570 NEXT I +580 END IF +590 LET Mean = Sum / SampleSize +600 LET Sum = 0 +610 REM Now calculate their standard deviation +620 FOR I = 1 TO SampleSize +630 LET Sum = Sum + (R(I) - Mean) ^ 2 +640 NEXT I +650 LET Sd = SQR(Sum / SampleSize) +660 REM Draw a histogram of the data with interval 0.1 +670 REM If sample size > 300 then normalize histogram to 300 +680 LET Scale = 1 +690 IF SampleSize > 300 THEN LET Scale = 300 / SampleSize +700 PRINT "Sample size "; SampleSize +710 PRINT USING " Mean #.###### SD #.######": Mean, Sd +720 FOR I = -1 TO 10 +730 IF I = -1 THEN +740 PRINT "< 0.00 : "; +750 ELSEIF I = 10 THEN +760 PRINT ">=1.00 : "; +770 ELSE +780 PRINT USING " #.## : ": I / 10; +790 END IF +800 PRINT USING "##### ": H(I); +810 PRINT REPEAT$("*", ROUND(H(I) * Scale, 0)) +820 NEXT I +830 END SUB diff --git a/Task/Statistics-Normal-distribution/EasyLang/statistics-normal-distribution.easy b/Task/Statistics-Normal-distribution/EasyLang/statistics-normal-distribution.easy new file mode 100644 index 0000000000..3575170455 --- /dev/null +++ b/Task/Statistics-Normal-distribution/EasyLang/statistics-normal-distribution.easy @@ -0,0 +1,51 @@ +func logn n . + return log n 0 +. +func randnorm . + return cos (360 * randomf) * sqrt (-2 * logn randomf) +. +global smpl[] . +func mean . + for v in smpl[] : sum += v + return sum / len smpl[] +. +func stddev . + avg = mean + for v in smpl[] : squares += (avg - v) * (avg - v) + return sqrt (squares / len smpl[]) +. +proc mksmpl n . + smpl[] = [ ] + for i to n + v = 100 + randnorm * 15 + smpl[] &= v + . +. +proc histo . + len count[] 199 + for v in smpl[] + ind = floor (v + 0.5) + ind = higher 1 ind + ind = lower 199 ind + count[ind] += 1 + . + n = len smpl[] + for i = 40 to 160 + v = count[i] + h = floor (v * 1500 / n) + s$ = "" + for j to h : s$ &= "*" + print i & " " & v & " " & s$ + . +. +numfmt 5 4 +proc stats size . + mksmpl size + print "Size: " & size + print "Mean: " & mean + print "Stddev: " & stddev + print "" + histo + print "" +. +stats 1000000 diff --git a/Task/Statistics-Normal-distribution/Loglan82/statistics-normal-distribution.loglan82 b/Task/Statistics-Normal-distribution/Loglan82/statistics-normal-distribution.loglan82 new file mode 100644 index 0000000000..56e91bdde5 --- /dev/null +++ b/Task/Statistics-Normal-distribution/Loglan82/statistics-normal-distribution.loglan82 @@ -0,0 +1,96 @@ +(* Statistics/Normal distribution *) + +block + + (* Generates normally distributed random numbers with mean 0 and standard deviation 1 *) + unit random_normal: function: real; + const + pi = 3.14159265358979; + begin + result := cos(2.0 * pi * random) * sqrt(-2.0 * ln(random)) + end random_normal; + + unit normal_stats: procedure (sample_size: integer); + var + r: arrayof real, + sum, mean, diff, scale, sd: real, + h: arrayof integer, + h_sum, adj, i, j: integer; + begin + if sample_size < 1 then return fi; + + array r dim (1 : sample_size); + array h dim (-1 : 10); (* all zero by default *) + sum := 0.0; + h_sum := 0; + + (* Generate 'sample_size' normally distributed random numbers with mean 0.5 + and standard deviation 0.25. + Calculate their sum and in which box they will fall when drawing + the histogram. *) + for i := 1 to sample_size + do + r(i) := .5 + random_normal / 4.0; + sum := sum + r(i); + if r(i) < 0.0 + then h(-1) := h(-1) + 1 + else + if r(i) >= 1.0 + then h(10) := h(10) + 1 + else h(entier(r(i) * 10)) := h(entier(r(i) * 10)) + 1 + fi + fi + od; + + for i := -1 to 10 do h_sum := h_sum + h(i) od; + (* Adjust one of the h() values if necessary to ensure h_sum = sample_size *) + adj := sample_size - h_sum; + if adj =/= 0 + then + for i := -1 to 10 + do + h(i) := h(i) + adj; + if h(i) >= 0 then exit fi; + h(i) := h(i) - adj + od + fi; + mean := sum / sample_size; + + (* Now calculate their standard deviation *) + sum := 0.0; + for i := 1 to sample_size + do + diff := r(i) - mean; + sum := sum + diff * diff + od; + sd := sqrt(sum / sample_size); + + (* Draw a histogram of the data with interval 0.1 + If sample size > 300 then normalize histogram to 300 *) + scale := 1.0; + if sample_size > 300 then scale := 300.0 / sample_size fi; + writeln("Sample size ", sample_size); + writeln(" Mean ", mean: 8: 6, " SD ", sd: 8: 6); + for i := -1 to 10 + do + if i = -1 then write("< 0.00 : ") + else + if i = 10 + then write(">=1.00 : ") + else write(" ", i / 10.0 : 4: 2, " : ") + fi + fi; + write(h(i): 5, " "); + for j := 1 to entier(h(i) * scale + .5) do write("*") od; + writeln + od; + end normal_stats; + +begin + call normal_stats(100); + writeln; + call normal_stats(1000); + writeln; + call normal_stats(10000); + writeln; +end; diff --git a/Task/Statistics-Normal-distribution/PHP/statistics-normal-distribution.php b/Task/Statistics-Normal-distribution/PHP/statistics-normal-distribution.php new file mode 100644 index 0000000000..d9a08f7fa9 --- /dev/null +++ b/Task/Statistics-Normal-distribution/PHP/statistics-normal-distribution.php @@ -0,0 +1,83 @@ += 1.0) + $h[11]++; + else + $h[ceil($r[$i] * 10)]++; + } + + foreach ($h as $h_item) + $h_sum += $h_item; + // adjust one of the $h values if necessary to ensure $h_sum = $sample_size + $adj = $sample_size - $h_sum; + if ($adj != 0) { + for ($i = 0; $i <= 11; $i++) { + $h[$i] += $adj; + if ($h[$i] >= 0) break; + $h[$i] -= $adj; + } + } + $mean = $sum / $sample_size; + + $sum = 0.0; + // Now calculate their standard deviation + foreach ($r as $r_item) + $sum += pow($r_item - $mean, 2); + $sd = sqrt($sum / $sample_size); + + // Draw a histogram of the data with interval 0.1 + // If sample size > 300 then normalize histogram to 300 + $scale = 1.0; + if ($sample_size > 300) + $scale = 300.0 / $sample_size; + echo 'Sample size '.$sample_size.PHP_EOL; + echo ' Mean '. + str_pad(number_format($mean, 6, '.', ''), 8, ' ', STR_PAD_LEFT). + ' SD '. + str_pad(number_format($sd, 6, '.', ''), 8, ' ', STR_PAD_LEFT).PHP_EOL; + $i = -1; + foreach ($h as $h_item) { + if ($i == -1) + echo '< 0.00 : '; + else if ($i == 10) + echo '>=1.00 : '; + else + echo ' '. + str_pad(number_format($i / 10.0, 2, '.', ''), 4, ' ', STR_PAD_LEFT). + ' : '; + echo str_pad($h_item, 5, ' ', STR_PAD_LEFT).' '. + str_repeat('*', round($h_item * $scale)).PHP_EOL; + $i++; + } +} +?> diff --git a/Task/Statistics-Normal-distribution/Pluto/statistics-normal-distribution.pluto b/Task/Statistics-Normal-distribution/Pluto/statistics-normal-distribution.pluto new file mode 100644 index 0000000000..41f19af534 --- /dev/null +++ b/Task/Statistics-Normal-distribution/Pluto/statistics-normal-distribution.pluto @@ -0,0 +1,59 @@ +require "table2" +require "io2" +local fmt = require "fmt" + +-- Box-Muller method from Wikipedia. +local function normal(mu, sigma) + local u1 = math.random() + local u2 = math.random() + local mag = sigma * math.sqrt(-2 * math.log(u1)) + local z0 = mag * math.cos(2 * math.pi * u2) + mu + local z1 = mag * math.sin(2 * math.pi * u2) + mu + return {z0, z1} +end + +local N = 100_000 +local NUM_BINS = 12 + +local bins = table.rep(NUM_BINS, 0) +local binSize = 0.1 +local samples = table.rep(N, 0) +local mu = 0.5 +local sigma = 0.25 +for i = 0, N / 2 - 1 do + local rns = normal(mu, sigma) + for j = 0, 1 do + local rn = rns[j + 1] + local bn + if rn < 0 then + bn = 0 + elseif rn >= 1 then + bn = 11 + else + bn = rn // binSize + 1 + end + bins[bn + 1] += 1 + samples[i * 2 + j + 1] = rn + end +end + +local labels = table.rep(NUM_BINS, "") +for i = 1, NUM_BINS do + if i == 1 then + labels[i] = "-inf ..< 0.00 " + elseif i < NUM_BINS then + labels[i] = string.format("%4.2f ..< %4.2f ", binSize * (i-1), binSize * i) + else + labels[i] = "1.00 ... +inf " + end +end + +fmt.print("Normal distribution with mean %0.2f and S/D %0.2f for %,s samples:\n", mu, sigma, N) +local title = " Range Number of samples within that range" +io.barchart(title, 85, labels, bins, true, true) + +local m = samples:mean() +fmt.print("\nActual mean for these samples : %0.5f", m) +local c = #samples +local v = (samples:sqsum() - m * m * c) / (c - 1) +fmt.print("Actual S/D for these samples : %0.5f", math.sqrt(v)) diff --git a/Task/Statistics-Normal-distribution/PowerShell/statistics-normal-distribution.ps1 b/Task/Statistics-Normal-distribution/PowerShell/statistics-normal-distribution.ps1 new file mode 100644 index 0000000000..ea2bf5855e --- /dev/null +++ b/Task/Statistics-Normal-distribution/PowerShell/statistics-normal-distribution.ps1 @@ -0,0 +1,86 @@ +# Statistics/Normal distribution + +# Generates normally distributed random numbers with $mean 0 and standard deviation 1 +function Get-RandomNormal { + return [Math]::Cos(2.0 * [Math]::PI * (Get-Random -Maximum 1.0)) * [Math]::Sqrt(-2.0 * [Math]::Log((Get-Random -Maximum 1.0))) +} + +function Write-NormalStats { + param ([uint32]$SampleSize) + if ($SampleSize -lt 1) { + return + } + $r = [double[]]::new($SampleSize) + $h = [uint32[]]::new(12) # all zero by default + $sum = 0.0 + $hSum = 0 + + # Generate '$SampleSize' normally distributed random numbers with $mean 0.5 and standard deviation 0.25 + # calculate their $sum + # and in which box they will fall when drawing the histogram + $iTo = $SampleSize - 1 + foreach ($i in 0..$iTo) { + $r[$i] = .5 + $(Get-RandomNormal) / 4.0 + $sum += $r[$i] + if ($r[$i] -lt 0.0) { + $h[0]++ + } elseif ($r[$i] -ge 1.0) { + $h[11]++ + } else { + $h[[Math]::Ceiling($r[$i] * 10)]++ + } + } + + foreach ($hItem in $h) { + $hSum += $hItem + } + # adjust one of the $h[] values if necessary to ensure $hSum = $SampleSize + $adj = $SampleSize - $hSum + if ($adj -ne 0) { + $iTo = $h.Length - 1 + foreach ($i in 0..$iTo) { + $h[$i] += $adj + if ($h[$i] -ge 0) { + break + } + $h[$i] -= $adj + } + } + $mean = $sum / $SampleSize + + $sum = 0.0 + # Now calculate their standard deviation + foreach ($rItem in $r) { + $sum += [Math]::Pow($rItem - $mean, 2) + } + $sd = [Math]::Sqrt($sum / $SampleSize) + + # Draw a histogram of the data with interval 0.1 + # If sample size > 300 then normalize histogram to 300 + $scale = 1.0 + if ($SampleSize -gt 300) { + $scale = 300.0 / $SampleSize + } + Write-Output "Sample size $SampleSize" + Write-Output (' Mean {0,8:N6} SD {1,8:N6}' -f $mean, $sd) + $i = -1 + foreach ($hItem in $h) { + if ($i -eq -1) { + $out = '< 0.00 : ' + } elseif ($i -eq 10) { + $out = '>=1.00 : ' + } else { + $out = ' {0,4:N2} : ' -f ($i / 10.0) + } + $out += ('{0,5} ' -f $hItem) + Write-Output ($out + ('*' * [Math]::Round($hItem * $scale))) + $i++ + } +} + +Write-NormalStats 100 +Write-Output "" +Write-NormalStats 1000 +Write-Output "" +Write-NormalStats 10000 +Write-Output "" diff --git a/Task/Statistics-Normal-distribution/QBasic/statistics-normal-distribution.basic b/Task/Statistics-Normal-distribution/QBasic/statistics-normal-distribution.basic new file mode 100644 index 0000000000..0ded89572b --- /dev/null +++ b/Task/Statistics-Normal-distribution/QBasic/statistics-normal-distribution.basic @@ -0,0 +1,92 @@ +DECLARE FUNCTION randomNormal! () +DECLARE SUB normalStats (sampleSize) + +CONST pi = 3.141592653589793# +RANDOMIZE TIMER + +CLS +CALL normalStats(100) +PRINT +CALL normalStats(1000) +PRINT +CALL normalStats(10000) +PRINT +CALL normalStats(100000) +PRINT "Press any key to quit" +END + +SUB normalStats (sampleSize) + IF sampleSize < 1 THEN EXIT SUB + + DIM r(1 TO sampleSize) AS SINGLE + DIM h(-1 TO 10) AS INTEGER + DIM sum AS DOUBLE: sum = 0! + DIM hSum AS INTEGER: hSum = 0 + DIM i AS INTEGER + + ' Generate samples: mean 0.5, std 0.25 + FOR i = 1 TO sampleSize + r(i) = .5 + randomNormal! / 4! + sum = sum + r(i) + + IF r(i) < 0! THEN + h(-1) = h(-1) + 1 + ELSEIF r(i) >= 1! THEN + h(10) = h(10) + 1 + ELSE + h(INT(r(i) * 10)) = h(INT(r(i) * 10)) + 1 + END IF + NEXT i + + FOR i = -1 TO 10 + hSum = hSum + h(i) + NEXT i + + ' Adjust if necessary (rounding error) + DIM adj AS INTEGER: adj = sampleSize - hSum + IF adj <> 0 THEN + FOR i = -1 TO 10 + h(i) = h(i) + adj + IF h(i) >= 0 THEN EXIT FOR + h(i) = h(i) - adj + NEXT i + END IF + + DIM mean AS DOUBLE: mean = sum / sampleSize + + ' Standard deviation + sum = 0! + FOR i = 1 TO sampleSize + sum = sum + (r(i) - mean) ^ 2! + NEXT i + DIM sd AS DOUBLE: sd = SQR(sum / sampleSize) + + PRINT "Sample size"; sampleSize + PRINT + PRINT USING " Mean #.######"; mean; + PRINT USING " SD #.######"; sd + PRINT + + ' Histogram (scale large samples) + DIM numStars AS INTEGER + DIM scale AS DOUBLE: scale = 1! + IF sampleSize > 300 THEN scale = 300 / sampleSize + + FOR i = -1 TO 10 + IF i = -1 THEN + PRINT "< 0.00 : "; + ELSEIF i = 10 THEN + PRINT ">=1.00 : "; + ELSE + PRINT USING " #.## : "; i / 10; + END IF + + PRINT USING "##### "; h(i); + numStars = INT(h(i) * scale + .5) + PRINT STRING$(numStars, "*") + NEXT i +END SUB + +FUNCTION randomNormal! + randomNormal! = COS(2 * pi * RND) * SQR(-2 * LOG(RND)) +END FUNCTION diff --git a/Task/Statistics-Normal-distribution/Rebol/statistics-normal-distribution.rebol b/Task/Statistics-Normal-distribution/Rebol/statistics-normal-distribution.rebol new file mode 100644 index 0000000000..b6965a237d --- /dev/null +++ b/Task/Statistics-Normal-distribution/Rebol/statistics-normal-distribution.rebol @@ -0,0 +1,82 @@ +Rebol [ + title: "Rosetta code: Statistics/Normal_distribution" + file: %Statistics-Normal_distribution.r3 + url: https://rosettacode.org/wiki/Statistics/Normal_distribution + author: @ldci + needs: 3.19.0 +] + +random/seed 1 +randMax: 2147483647 ;; max integer value +nMax: 500000 ;; number of random values, can be modified + +;; Normal random numbers generator using Marsaglia algorithm. +;; Generates 2 independent series of random values in the range [-1.0, 1.0]. +generate: function [ + n [integer!] ;; number of pairs to generate +][ + m: n * 2 + values: make vector! [f64! :m] ;; vector to hold generated values + for i 1 m 2 [ + rsq: 0.0 + ;; Repeat while radius squared is outside the unit circle or zero + while [any [(rsq >= 1.0) (rsq == 0.0)]] [ + x: (2.0 * random randMax) / randMax - 1.0 + y: (2.0 * random randMax) / randMax - 1.0 + rsq: (x * x) + (y * y) + ] + f: sqrt ((-2.0 * log-e rsq) / rsq) + values/(i): x * f + values/(i + 1): y * f + ] + values +] + +;; Show histogram of the values vector +printHistogram: function [ + values [vector!] +][ + width: 50.0 ;; width of histogram bars + low: -3.0 ;; lower bound of histogram + high: 3.0 ;; upper bound of histogram + delta: 0.1 ;; bin width + n: values/length ;; length of data + nbins: to integer! ((high - low) / delta) ;; number of bins (60) + bins: make vector! [i32! :nbins] ;; initialize bins vector + repeat i n [ + j: to integer! ((values/:i - low) / delta) + if all [(j >= 1) (j <= nbins)] [ + bins/:j: bins/:j + 1 ;; increment bin counter + ] + ] + maxi: bins/maximum ;; max count in any bin + repeat j nbins [ + lbin: round/to (low + j * delta - high + 0.25) 0.01 ;; low limit for bin + hbin: round/to (low + j + 1 * delta - high + 0.25) 0.01 ;; high limit for bin + s: ajoin ["[" lbin " " hbin "] "] ;; bin label string + pad s -15 ;; pad string left for alignment + k: width * bins/:j / maxi ;; number of block characters to print + while [k > 0] [ + append s to-char 9609 ;; append block character (unicode 9609) + k: k - 1 + ] + append s ajoin [" " round/to (bins/:j * 100 / n) 0.01 "%"] ;; append percentage + print s + ] +] + +;;********************** Main *********************** + +print "Be patient! Generating Data and Gaussian Histogram..." +print-horizontal-line + +time: dt [ + values: generate nMax ;; generate nMax pairs of random values + printHistogram values ;; print histogram of generated values +] + +print-horizontal-line +print [nMax * 2 "Values processed in:" round/to third time 0.01 "sec"] +print ["Mean: " values/mean] +print ["STD : " values/sample-deviation] +print-horizontal-line diff --git a/Task/Statistics-Normal-distribution/Yabasic/statistics-normal-distribution.basic b/Task/Statistics-Normal-distribution/Yabasic/statistics-normal-distribution.basic new file mode 100644 index 0000000000..0f5daa4869 --- /dev/null +++ b/Task/Statistics-Normal-distribution/Yabasic/statistics-normal-distribution.basic @@ -0,0 +1,73 @@ +normalStats(100) +print +normalStats(1000) +print +normalStats(10000) +print +normalStats(100000) +end + +sub randomNormal() + local u1, u2 + u1 = ran() + u2 = ran() + return cos(2 * pi * u1) * sqrt(-2 * log(u2)) +end sub + +sub normalStats(n) + local r(n), h(11) + local i, sum, hSum, mean, sd, scale, stars + sum = 0 + hSum = 0 + + // Generate samples: mean 0.5, std 0.25 + for i = 1 to n + r(i) = 0.5 + randomNormal() / 4 + sum = sum + r(i) + + if r(i) < 0 then + h(0) = h(0) + 1 + elsif r(i) >= 1 then + h(11) = h(11) + 1 + else + h(int(r(i)*10)+1) = h(int(r(i)*10)+1) + 1 + fi + next i + + for i = 0 to 11 + hSum = hSum + h(i) + next i + + mean = sum / n + + // Standard deviation + sum = 0 + for i = 1 to n + sum = sum + (r(i) - mean)^2 + next i + sd = sqrt(sum / n) + + print "Sample size ", n + print + print " Mean ", mean using("#.######"); + print " SD ", sd using("#.######") + print + + // Histogram (scale for large samples) + scale = 1 + if n > 300 scale = 300 / n + + for i = 0 to 11 + if i = 0 then + print "< 0.00 : ", h(0) using("#####"), " "; + elsif i = 11 then + print ">=1.00 : ", h(1) using("#####"); + else + //print using(" #.## : ##### ", (i-1)/10); h(i); + print " ", (i-1)/10 using("#.##"), " : ", h(i) using("#####"), " "; + fi + + stars = int(h(i) * scale + 0.5) + print string$(stars, "*") + next i +end sub diff --git a/Task/Steffensens-method/Haxe/steffensens-method.hx b/Task/Steffensens-method/Haxe/steffensens-method.hx new file mode 100644 index 0000000000..125654693d --- /dev/null +++ b/Task/Steffensens-method/Haxe/steffensens-method.hx @@ -0,0 +1,94 @@ +// Steffensens's method - translated from the ATS sample via Algol 68 + +class OptionalReal +{ + public var v:Float; + public var hasValue:Bool; + public function new( value:Float, notNull:Bool ) + { + v = value; + hasValue = notNull; + }; +} + +class Main { + + // Aitken's extrapolation + static function aitken( f:Float->Float // function Float to Float + , p0:Float // initial fixed point estimate + ):Float + { + var p1 = f( p0 ); + var p2 = f( p1 ); + var p1m0 = p1 - p0; + return p0 - ( p1m0 * p1m0 ) / ( p2 - ( 2 * p1 ) + p0 ); + }; + + // finds fixed point p such that f(p) = p + static function steffensenAitken( f:Float->Float // function Float to Float + , pinit:Float // initial estimate + , tol:Float // tolerance + , maxiter:Float // maximum number of iterations + ):OptionalReal // return a Float, IF tolerance is met + { + var p0 = pinit; + var p = aitken( f, p0 ); // first iteration + var i = 1; + while( i < ( maxiter - 1 ) && Math.abs( p - p0 ) > tol ) { + p0 = p; + p = aitken( f, p0 ); + i += 1; + } + if( Math.abs( p - p0 ) > tol ) { + return new OptionalReal( 0, false ); + } else { + return new OptionalReal( p, true ); + } + }; + + static function deCasteljau( c0:Float // control point coordinates (one axis) + , c1:Float + , c2:Float + , t :Float // the indep}ent parameter + ) :Float // value of x(t) or y(t) + { + var s = 1 - t; + var c01 = ( s * c0 ) + ( t * c1 ); + var c12 = ( s * c1 ) + ( t * c2 ); + return ( s * c01 ) + ( t * c12 ); + }; + + static function xConvexLeftParabola( t:Float ):Float { return deCasteljau( 2, -8, 2, t ); } + static function yConvexLeftParabola( t:Float ):Float { return deCasteljau( 1, 2, 3, t ); } + + static function implicitEquation( x:Float, y:Float ):Float { return ( 5 * x * x ) + y - 5; } + + static function f( t:Float ):Float // find fixed points of this function + { + var x = xConvexLeftParabola( t ); + var y = yConvexLeftParabola( t ); + return implicitEquation( x, y ) + t; + }; + + static function main() + { + var t0:Float = 0; + for( i in 1...12 ) { + Sys.print( 't0 = $t0 : ' ); + var result = steffensenAitken( f, t0, 0.00000001, 1000 ); + if( ! result.hasValue ) { + Sys.println( 'no answer' ); + } else { + var x = xConvexLeftParabola( result.v ); + var y = yConvexLeftParabola( result.v ); + if( Math.abs( implicitEquation( x, y ) ) <= 0.000001 ) { + Sys.println( 'intersection at ($x, $y)' ); + } else { + Sys.println( 'spurious solution' ); + } + } + t0 += 0.1; + } + } + +} diff --git a/Task/Steffensens-method/JavaScript/steffensens-method.js b/Task/Steffensens-method/JavaScript/steffensens-method.js new file mode 100644 index 0000000000..123b07b329 --- /dev/null +++ b/Task/Steffensens-method/JavaScript/steffensens-method.js @@ -0,0 +1,69 @@ +class Steffensen { + static aitken(p0) { + const p1 = this.f(p0); + const p2 = this.f(p1); + const p1m0 = p1 - p0; + return p0 - p1m0 * p1m0 / (p2 - 2.0 * p1 + p0); + } + + static steffensenAitken(pinit, tol, maxiter) { + let p0 = pinit; + let p = this.aitken(p0); + let iter = 1; + while (Math.abs(p - p0) > tol && iter < maxiter) { + p0 = p; + p = this.aitken(p0); + iter++; + } + if (Math.abs(p - p0) > tol) return null; + return p; + } + + static deCasteljau(c0, c1, c2, t) { + const s = 1.0 - t; + const c01 = s * c0 + t * c1; + const c12 = s * c1 + t * c2; + return s * c01 + t * c12; + } + + static xConvexLeftParabola(t) { + return this.deCasteljau(2.0, -8.0, 2.0, t); + } + + static yConvexRightParabola(t) { + return this.deCasteljau(1.0, 2.0, 3.0, t); + } + + static implicitEquation(x, y) { + return 5.0 * x * x + y - 5.0; + } + + static f(t) { + const x = this.xConvexLeftParabola(t); + const y = this.yConvexRightParabola(t); + return this.implicitEquation(x, y) + t; + } + + static main() { + let t0 = 0.0; + for (let i = 0; i < 11; ++i) { + process.stdout.write(`t0 = ${t0.toFixed(1)} : `); + const t = this.steffensenAitken(t0, 0.00000001, 1000); + if (t === null) { + console.log("no answer"); + } else { + const x = this.xConvexLeftParabola(t); + const y = this.yConvexRightParabola(t); + if (Math.abs(this.implicitEquation(x, y)) <= 0.000001) { + console.log(`intersection at (${x}, ${y})`); + } else { + console.log("spurious solution"); + } + } + t0 += 0.1; + } + } +} + +// Run the main function +Steffensen.main(); diff --git a/Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.adb b/Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.adb new file mode 100644 index 0000000000..257817b3a5 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Ada/stem-and-leaf-plot.adb @@ -0,0 +1,40 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Gnat.Heap_Sort_G; +procedure stemleaf is + data : array(Natural Range <>) of Integer := ( + 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, + 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, + 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, + 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, + 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, + 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, + 31,116,146); -- Position 0 is used for storage during sorting, initialized as 0 + + procedure Move (from, to : in Natural) is + begin data(to) := data(from); + end Move; + + function Cmp (p1, p2 : Natural) return Boolean is + begin return data(p1)stemw); put(" |"); + Leaf_Loop: + while data(p)/10=stem loop + put(" "); put(data(p) mod 10,Width=>1); + exit Leaf_loop when p=data'Last; + p := p+1; + end loop Leaf_Loop; + new_line; + end loop; +end stemleaf; diff --git a/Task/Stem-and-leaf-plot/Erlang/stem-and-leaf-plot.erl b/Task/Stem-and-leaf-plot/Erlang/stem-and-leaf-plot.erl new file mode 100644 index 0000000000..4f8ad1db1b --- /dev/null +++ b/Task/Stem-and-leaf-plot/Erlang/stem-and-leaf-plot.erl @@ -0,0 +1,131 @@ +%%% ============================================================ +%%% Stem-and-Leaf Plot in Erlang +%%% ============================================================ +%%% - Pure functions +%%% - No mutation +%%% - Deterministic transformations +%%% - Explicit functional pipeline +%%% ============================================================ + +-module(stem_leaf). +-export([main/0]). + +%%% ============================================================ +%%% 1. Mathematical Helpers (Pure Functions) +%%% ============================================================ + +%% expand_number/1 +%% Conceptually expands single digit numbers to two-digit +%% (e.g., 7 -> 07). Numerically unchanged, but included +%% for semantic clarity. +expand_number(N) -> + N. + +%% stem/1 +%% Returns the stem (all but the last digit). +%% Example: 127 -> 12 +stem(N) -> + N div 10. + +%% leaf/1 +%% Returns the leaf (last digit). +%% Example: 127 -> 7 +leaf(N) -> + N rem 10. + +%% range/2 +%% Returns a list of integers from From to To (inclusive). +%% Used to guarantee stems 0..14 are always present. +range(From, To) when From =< To -> + lists:seq(From, To). + +%%% ============================================================ +%%% 2. Data Transformation Pipeline +%%% ============================================================ + +%% build_stem_leaf/1 +%% Takes raw data and returns a list of: +%% [{Stem, [SortedLeaves]}, ...] +%% +%% Steps: +%% 1. Expand numbers +%% 2. Sort entire dataset +%% 3. Generate all stems 0..14 +%% 4. Collect and sort leaves for each stem +build_stem_leaf(Data) -> + Expanded = [expand_number(N) || N <- Data], + Sorted = lists:sort(Expanded), + Stems = range(0, 14), + [{S, sorted_leaves(S, Sorted)} || S <- Stems]. + +%% sorted_leaves/2 +%% Filters all numbers matching a given stem +%% Extracts leaves +%% Sorts leaves +sorted_leaves(StemValue, Data) -> + Leaves = + [leaf(N) || N <- Data, stem(N) =:= StemValue], + lists:sort(Leaves). + +%%% ============================================================ +%%% 3. Formatting Functions (Pure Rendering Layer) +%%% ============================================================ + +%% format_stem/1 +%% Formats stem as two digits (leading zero if needed). +%% Example: 7 -> "07" +format_stem(S) -> + io_lib:format("~2..0B", [S]). + +%% format_leaves/1 +%% Converts list of integers into space-separated string. +%% Example: [1,3,7] -> "1 3 7" +format_leaves([]) -> + ""; +format_leaves(Leaves) -> + string:join([integer_to_list(L) || L <- Leaves], " "). + +%% render_line/1 +%% Converts {Stem, Leaves} into formatted line. +%% Example: +%% {12, [3,4,7]} -> "12 | 3 4 7" +render_line({StemValue, Leaves}) -> + lists:flatten( + io_lib:format("~s | ~s", + [format_stem(StemValue), format_leaves(Leaves)]) + ). + +%% render_plot/1 +%% Converts full stem-leaf structure into multi-line string. +render_plot(StemLeafPairs) -> + Lines = [render_line(Pair) || Pair <- StemLeafPairs], + string:join(Lines, "\n"). + +%%% ============================================================ +%%% 4. Program Entry Point +%%% ============================================================ + +main() -> + %% -------------------------------------------------------- + %% Raw Dataset + %% -------------------------------------------------------- + Data = [ + 12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48,127,36,29,31, + 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23, + 105,63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121, + 58,114,126,53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7, + 68,40,31,115,124,42,128,52,71,118,117,38,27,106,33,117,116,111, + 40,119,47,105,57,122,109,124,115,43,120,43,27,27,18,28,48,125, + 107,114,34,133,45,120,30,127,31,116,146 + ], + + %% -------------------------------------------------------- + %% Functional Processing Pipeline + %% -------------------------------------------------------- + StemLeafStructure = build_stem_leaf(Data), + Plot = render_plot(StemLeafStructure), + + %% -------------------------------------------------------- + %% Output + %% -------------------------------------------------------- + io:format("~s~n", [Plot]). diff --git a/Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.eu b/Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.eu new file mode 100644 index 0000000000..8d7f670418 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Euphoria/stem-and-leaf-plot.eu @@ -0,0 +1,28 @@ +include sort.e + +procedure leaf_plot(sequence s) + sequence stem + s = sort(s) + stem = repeat({},floor(s[$]/10)+1) + for i = 1 to length(s) do + stem[floor(s[i]/10)+1] &= remainder(s[i],10) + end for + for i = 1 to length(stem) do + printf(1, "%3d | ", i-1) + for j = 1 to length(stem[i]) do + printf(1, "%d ", stem[i][j]) + end for + puts(1,'\n') + end for +end procedure + +constant data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, + 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, + 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, + 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, + 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, + 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, + 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, + 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 } + +leaf_plot(data) diff --git a/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-4.pl b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-4.pl new file mode 100644 index 0000000000..e221945b37 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Perl/stem-and-leaf-plot-4.pl @@ -0,0 +1,17 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Stem-and-leaf_plot +use warnings; + +my @plot; +/(.*)(.)/, $plot[$1 || 0] .= " $2" for sort {$a <=> $b} map split, ; +printf "%3d |%s\n", $_, $plot[$_] // '' for 0 .. $#plot; + +__DATA__ +12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 +29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 +23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 +121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 +27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 +116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 +48 125 107 114 34 133 45 120 30 127 31 116 146 diff --git a/Task/Stem-and-leaf-plot/Pluto/stem-and-leaf-plot.pluto b/Task/Stem-and-leaf-plot/Pluto/stem-and-leaf-plot.pluto new file mode 100644 index 0000000000..684c2b6af1 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Pluto/stem-and-leaf-plot.pluto @@ -0,0 +1,28 @@ +local fmt = require "fmt" + +local function leaf_plot(x) + x:sort() + local i = x[1] // 10 - 1 + for j = 1, #x do + local d = x[j] // 10 + while (d > i) do + i += 1 + fmt.write("%s%3d |", (j != 1) ? "\n" : "", i) + end + io.write($" {x[j] % 10}") + end + print() +end + +local data = { + 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, + 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, + 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, + 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, + 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, + 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, + 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, + 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, + 34, 133, 45, 120, 30, 127, 31, 116, 146 +} +leaf_plot(data) diff --git a/Task/Stem-and-leaf-plot/PowerShell/stem-and-leaf-plot.ps1 b/Task/Stem-and-leaf-plot/PowerShell/stem-and-leaf-plot.ps1 new file mode 100644 index 0000000000..263bced4d5 --- /dev/null +++ b/Task/Stem-and-leaf-plot/PowerShell/stem-and-leaf-plot.ps1 @@ -0,0 +1,10 @@ +$Set = -split '12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146' + +$Data = $Set | Select @{ Label = 'Stem'; Expression = { [string][int]$_.Substring( 0, $_.Length - 1 ) } }, @{ Label = 'Leaf'; Expression = { [string]$_[-1] } } + +$StemStats = $Data | Measure-Object -Property Stem -Minimum -Maximum + +ForEach ( $Stem in $StemStats.Minimum..$StemStats.Maximum ) + { + @( $Stem.ToString().PadLeft( 2, " " ), '|' ) + ( ( $Data | Where Stem -eq $Stem ).Leaf | Sort ) -join " " + } diff --git a/Task/Stem-and-leaf-plot/Rust/stem-and-leaf-plot.rs b/Task/Stem-and-leaf-plot/Rust/stem-and-leaf-plot.rs new file mode 100644 index 0000000000..c3689b6f22 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Rust/stem-and-leaf-plot.rs @@ -0,0 +1,120 @@ +// ================================================================ : +// Advice: Rust with a functional approach +// : Treats single-digit numbers as having a leading zero (stem 0) +// : Uses the last digit as the leaf +// : Includes all stems from 0 to 14 +// : Uses a functional approach with pure functions +// : Produces monospaced plain text output +// ================================================================ + +use std::collections::BTreeMap; + +// ================================================================ +// Mathematical Helper Functions (Pure) +// ================================================================ + +// Conceptually expands single digit numbers. +// Numerically unchanged, included for semantic clarity. +fn expand_number(n: u32) -> u32 { + n +} + +// Returns the stem (all but the last digit). +// Example: 127 -> 12 +fn stem(n: u32) -> u32 { + n / 10 +} + +// Returns the leaf (last digit). +// Example: 127 -> 7 +fn leaf(n: u32) -> u32 { + n % 10 +} + +// ================================================================ +// Data Transformation Layer (Pure Functional Pipeline) +// ================================================================ + +// Builds the stem-leaf structure. +// Returns a BTreeMap so stems are automatically sorted. +// Ensures stems 0..14 always exist. +fn build_stem_leaf(data: &[u32]) -> BTreeMap> { + // Step 1: Expand and sort the data + let mut sorted: Vec = data.iter().map(|&n| expand_number(n)).collect(); + + sorted.sort(); + + // Step 2: Create all stems 0..14 + (0..=14) + .map(|s| { + // Collect and sort leaves belonging to this stem + let mut leaves: Vec = sorted + .iter() + .filter(|&&n| stem(n) == s) + .map(|&n| leaf(n)) + .collect(); + + leaves.sort(); + + (s, leaves) + }) + .collect() +} + +// ================================================================ +// Formatting Layer (Pure Rendering) +// ================================================================ + +// Formats a stem as two digits (leading zero if necessary). +// Example: 7 -> "07" +fn format_stem(s: u32) -> String { + format!("{:02}", s) +} + +// Formats leaves as space-separated digits. +// Example: [1,3,7] -> "1 3 7" +fn format_leaves(leaves: &[u32]) -> String { + leaves + .iter() + .map(|l| l.to_string()) + .collect::>() + .join(" ") +} + +// Renders the complete stem-and-leaf plot as multi-line string. +fn render_plot(stem_leaf: &BTreeMap>) -> String { + stem_leaf + .iter() + .map(|(s, leaves)| format!("{} | {}", format_stem(*s), format_leaves(leaves))) + .collect::>() + .join("\n") +} + +// ================================================================ +// Program Entry Point +// ================================================================ + +fn main() { + // ------------------------------------------------------------ + // Raw Dataset + // ------------------------------------------------------------ + let data: Vec = vec![ + 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, + 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, + 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, + 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, + 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, + 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146, + ]; + + // ------------------------------------------------------------ + // Functional Processing Pipeline + // ------------------------------------------------------------ + let stem_leaf_structure = build_stem_leaf(&data); + let plot = render_plot(&stem_leaf_structure); + + // ------------------------------------------------------------ + // Output (Monospaced Plain Text) + // ------------------------------------------------------------ + println!("{}", plot); +} diff --git a/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.adb b/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.adb new file mode 100644 index 0000000000..71b516b13d --- /dev/null +++ b/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.adb @@ -0,0 +1,94 @@ +with Ada.Text_IO, Ada.Containers.Vectors; + +procedure Sequence is + + package Vectors is new + Ada.Containers.Vectors(Index_Type => Positive, Element_Type => Positive); + use type Vectors.Vector; + + type Sequence is record + List: Vectors.Vector; + Index: Positive; + -- This implements some form of "lazy evaluation": + -- + List holds the elements computed, so far, it is extended + -- if the user tries to "Get" an element not yet computed; + -- + Index is the location of the next element under consideration + end record; + + function Initialize return Sequence is + (List => (Vectors.Empty_Vector & 1 & 1), Index => 2); + + function Get(Seq: in out Sequence; Location: Positive) return Positive is + -- returns the Location'th element of the sequence + -- extends Seq.List (and then increases Seq.Index) if neccessary + That: Positive := Seq.List.Element(Seq.Index); + This: Positive := That + Seq.List.Element(Seq.Index-1); + begin + while Seq.List.Last_Index < Location loop + Seq.List := Seq.List & This & That; + Seq.Index := Seq.Index + 1; + end loop; + return Seq.List.Element(Location); + end Get; + + S: Sequence := Initialize; + J: Positive; + + use Ada.Text_IO; + +begin + -- show first fifteen members + Put("First 15:"); + for I in 1 .. 15 loop + Put(Integer'Image(Get(S, I))); + end loop; + New_Line; + + -- show the index where 1, 2, 3, ... first appear in the sequence + for I in 1 .. 10 loop + J := 1; + while Get(S, J) /= I loop + J := J + 1; + end loop; + Put("First" & Integer'Image(I) & " at" & Integer'Image(J) & "; "); + if I mod 4 = 0 then + New_Line; -- otherwise, the output gets a bit too ugly + end if; + end loop; + + -- show the index where 100 first appears in the sequence + J := 1; + while Get(S, J) /= 100 loop + J := J + 1; + end loop; + Put_Line("First 100 at" & Integer'Image(J) & "."); + + -- check GCDs + declare + function GCD (A, B : Integer) return Integer is + M : Integer := A; + N : Integer := B; + T : Integer; + begin + while N /= 0 loop + T := M; + M := N; + N := T mod N; + end loop; + return M; + end GCD; + + A, B: Positive; + begin + for I in 1 .. 999 loop + A := Get(S, I); + B := Get(S, I+1); + if GCD(A, B) /= 1 then + raise Constraint_Error; + end if; + end loop; + Put_Line("Correct: The first 999 consecutive pairs are relative prime!"); + exception + when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ; + end; +end Sequence; diff --git a/Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.ps1 b/Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.ps1 new file mode 100644 index 0000000000..fee4cfee48 --- /dev/null +++ b/Task/Stern-Brocot-sequence/PowerShell/stern-brocot-sequence.ps1 @@ -0,0 +1,28 @@ +# An iterative approach +function iter_sb($count = 2000) +{ + # Taken from RosettaCode GCD challenge + function Get-GCD ($x, $y) + { + if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) } + } + + $answer = @(1,1) + $index = 1 + while ($answer.Length -le $count) + { + $answer += $answer[$index] + $answer[$index - 1] + $answer += $answer[$index] + $index++ + } + + 0..14 | foreach {$answer[$_]} + + 1..10 | foreach {'Index of {0}: {1}' -f $_, ($answer.IndexOf($_) + 1)} + + 'Index of 100: {0}' -f ($answer.IndexOf(100) + 1) + + [bool] $gcd = $true + 1..999 | foreach {$gcd = $gcd -and ((Get-GCD $answer[$_] $answer[$_ - 1]) -eq 1)} + 'GCD = 1 for first 1000 members: {0}' -f $gcd +} diff --git a/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vbs b/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vbs new file mode 100644 index 0000000000..e9f69e83f3 --- /dev/null +++ b/Task/Stern-Brocot-sequence/VBScript/stern-brocot-sequence.vbs @@ -0,0 +1,40 @@ +sb = Array(1,1) +i = 1 'considered +j = 2 'precedent +n = 0 'loop counter +Do + ReDim Preserve sb(UBound(sb) + 1) + sb(UBound(sb)) = sb(UBound(sb) - i) + sb(UBound(sb) - j) + ReDim Preserve sb(UBound(sb) + 1) + sb(UBound(sb)) = sb(UBound(sb) - j) + i = i + 1 + j = j + 1 + n = n + 1 +Loop Until n = 2000 + +WScript.Echo "First 15: " & DisplayElements(15) + +For k = 1 To 10 + WScript.Echo "The first instance of " & k & " is in #" & ShowFirstInstance(k) & "." +Next + +WScript.Echo "The first instance of " & 100 & " is in #" & ShowFirstInstance(100) & "." + +Function DisplayElements(n) + For i = 0 To n - 1 + If i < n - 1 Then + DisplayElements = DisplayElements & sb(i) & ", " + Else + DisplayElements = DisplayElements & sb(i) + End If + Next +End Function + +Function ShowFirstInstance(n) + For i = 0 To UBound(sb) + If sb(i) = n Then + ShowFirstInstance = i + 1 + Exit For + End If + Next +End Function diff --git a/Task/Stirling-numbers-of-the-first-kind/Crystal/stirling-numbers-of-the-first-kind.cr b/Task/Stirling-numbers-of-the-first-kind/Crystal/stirling-numbers-of-the-first-kind.cr new file mode 100644 index 0000000000..5248bf09ac --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Crystal/stirling-numbers-of-the-first-kind.cr @@ -0,0 +1,27 @@ +require "big" + +CACHE = {} of {Int32, Int32, Bool} => BigInt + +def s1 (n, k, signed=false) + return CACHE[{n, k, signed}] if CACHE.has_key?({n, k, signed}) + case + when n == k == 0 then return 1.to_big_i + when n > 0 && k == 0 then return 0.to_big_i + when k > n then return 0.to_big_i + end + result = if signed + s1(n-1, k-1) - (n-1) * s1(n-1, k) + else + s1(n-1, k-1) + (n-1) * s1(n-1, k) + end + CACHE[{n, k, signed}] = result +end + +puts "S1(n, k) (unsigned) for n in 1..12:" +puts "n\\k" + (1..12).map {|k| " %10d" % k }.join +(1..12).each do |n| + puts ("%2d " % n) + (1..n).map {|k| " %10d" % s1(n, k) }.join +end +puts +puts "Maximum value of S1(n, k) (unsigned) where n = 100:" +puts (1..100).max_of {|k| s1(100, k) } diff --git a/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy b/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy index 9b5db0730b..320d00d7ea 100644 --- a/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy +++ b/Task/Stirling-numbers-of-the-first-kind/EasyLang/stirling-numbers-of-the-first-kind.easy @@ -1,6 +1,6 @@ print "Unsigned Stirling numbers of the first kind:" -len a[] 13 ; arrbase a[] 0 -len b[] 13 ; arrbase b[] 0 +len a[] 13 +len b[] 13 a[0] = 1 print 1 for n = 1 to 12 diff --git a/Task/Stirling-numbers-of-the-first-kind/Maxima/stirling-numbers-of-the-first-kind.maxima b/Task/Stirling-numbers-of-the-first-kind/Maxima/stirling-numbers-of-the-first-kind.maxima new file mode 100644 index 0000000000..f4a05dddc2 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Maxima/stirling-numbers-of-the-first-kind.maxima @@ -0,0 +1,9 @@ +block( + sprint("n | (k from 1 to n)"), + newline(), + for n from 1 thru 12 do( + sprint(n, "|"), + for k from 1 thru n do sprint(stirling1(n, k)), + newline() + ) +)$ diff --git a/Task/Stirling-numbers-of-the-first-kind/Oberon-07/stirling-numbers-of-the-first-kind.oberon b/Task/Stirling-numbers-of-the-first-kind/Oberon-07/stirling-numbers-of-the-first-kind.oberon new file mode 100644 index 0000000000..bb0a399048 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Oberon-07/stirling-numbers-of-the-first-kind.oberon @@ -0,0 +1,58 @@ +MODULE StirlingNumbersOfTheFirstKind; + (* show some (unsigned) Stirling numbers of the first kind *) + IMPORT Out; + + CONST maxStirling = 12; + VAR stirling : ARRAY maxStirling + 1, maxStirling + 1 OF INTEGER; + + (* sets s1 to a matrix of Stirling numbers; s1 must be square *) + PROCEDURE getStirling( VAR s1 : ARRAY OF ARRAY OF INTEGER ) ; + VAR maxN, n, k : INTEGER; + BEGIN + maxN := LEN( s1 ) - 1; + FOR n := 0 TO maxN DO + FOR k := 0 TO maxN DO s1[ n, k ] := 0 END + END; + s1[ 0, 0 ] := 1; + FOR n := 1 TO maxN DO + FOR k := 1 TO n DO + s1[ n, k ] := s1[ n - 1, k - 1 ] + + ( ( n - 1 ) * s1[ n - 1, k ] ) + END + END + END getStirling ; + + (* prints the Stirling numbers in s1 *) + PROCEDURE printStirling( s1 : ARRAY OF ARRAY OF INTEGER ) ; + VAR maxN, n, k : INTEGER; + + (* prints a Stirling number e in a width suitable for k... *) + (* assuming e is in a table of Stirling numbers with n <= 12 *) + PROCEDURE print1( e, k : INTEGER ) ; + BEGIN + IF k = 0 THEN Out.Int( e, 3 ) + ELSIF k < 5 THEN Out.Int( e, 10 ) + ELSIF k < 8 THEN Out.Int( e, 9 ) + ELSIF k < 11 THEN Out.Int( e, 7 ) + ELSE Out.Int( e, 4 ) + END + END print1 ; + + BEGIN + maxN := LEN( s1 ) - 1; + Out.String( "Unsigned Stirling numbers of the first kind:" );Out.Ln; + Out.String( " k" ); + FOR k := 0 TO maxN DO print1( k, k ) END; + Out.Ln; + Out.String( " n" );Out.Ln; + FOR n := 0 TO maxN DO + Out.Int( n, 2 ); + FOR k := 0 TO n DO print1( s1[ n, k ], k ) END; + Out.Ln + END + END printStirling ; + +BEGIN + getStirling( stirling ); + printStirling( stirling ) +END StirlingNumbersOfTheFirstKind. diff --git a/Task/Stirling-numbers-of-the-first-kind/Pluto/stirling-numbers-of-the-first-kind.pluto b/Task/Stirling-numbers-of-the-first-kind/Pluto/stirling-numbers-of-the-first-kind.pluto new file mode 100644 index 0000000000..254e4c0b67 --- /dev/null +++ b/Task/Stirling-numbers-of-the-first-kind/Pluto/stirling-numbers-of-the-first-kind.pluto @@ -0,0 +1,40 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" + +local zero = bigint.new(0) +local one = bigint.new(1) + +local computed = {} + +local function stirling1(n, k) + local key = $"{n},{k}" + if c := computed[key] then return c end + if n == 0 and k == 0 then return one end + if n > 0 and k == 0 then return zero end + if k > n then return zero end + local result = stirling1(n - 1, k - 1) + stirling1(n - 1, k) * (n - 1) + computed[key] = result + return result +end + +print("Unsigned Stirling numbers of the first kind:") +local max = 12 +io.write("n/k") +for n = 0, max do fmt.write("%10d", n) end +print("\n" .. string.rep("-", 133)) +for n = 0, max do + fmt.write("%-3d", n) + for k = 0, n do fmt.write("%10s", stirling1(n, k)) end + print() +end +print("\nThe maximum value of S1(100, k) =") +local previous = zero +for k = 1, 100 do + local current = stirling1(100, k) + if current > previous then + previous = current + else + fmt.print("%s\n(%d digits, k = %d)", previous, #previous:tostring(), k - 1) + break + end +end diff --git a/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy b/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy index 57809aa43c..09c9e9a609 100644 --- a/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy +++ b/Task/Stirling-numbers-of-the-second-kind/EasyLang/stirling-numbers-of-the-second-kind.easy @@ -1,4 +1,3 @@ -sysconf zero_based print "Unsigned Stirling numbers of the second kind:" len a[] 13 len b[] 13 diff --git a/Task/Stirling-numbers-of-the-second-kind/Maxima/stirling-numbers-of-the-second-kind.maxima b/Task/Stirling-numbers-of-the-second-kind/Maxima/stirling-numbers-of-the-second-kind.maxima new file mode 100644 index 0000000000..ec97586008 --- /dev/null +++ b/Task/Stirling-numbers-of-the-second-kind/Maxima/stirling-numbers-of-the-second-kind.maxima @@ -0,0 +1,9 @@ +block( + sprint("n | (k from 1 to n)"), + newline(), + for n from 1 thru 12 do( + sprint(n, "|"), + for k from 1 thru n do sprint(stirling2(n, k)), + newline() + ) +)$ diff --git a/Task/Stirling-numbers-of-the-second-kind/Pluto/stirling-numbers-of-the-second-kind.pluto b/Task/Stirling-numbers-of-the-second-kind/Pluto/stirling-numbers-of-the-second-kind.pluto new file mode 100644 index 0000000000..21497dca6b --- /dev/null +++ b/Task/Stirling-numbers-of-the-second-kind/Pluto/stirling-numbers-of-the-second-kind.pluto @@ -0,0 +1,40 @@ +local bigint = require "pluto:bigint" +local fmt = require "fmt" + +local zero = bigint.new(0) +local one = bigint.new(1) + +local computed = {} + +local function stirling2(n, k) + local key = $"{n},{k}" + if c := computed[key] then return c end + if n == 0 and k == 0 then return one end + if (n > 0 and k == 0) or (n == 0 and k > 0) then return zero end + if k == n then return one end + local result = stirling2(n - 1, k - 1) + stirling2(n - 1, k) * k + computed[key] = result + return result +end + +print("Unsigned Stirling numbers of the second kind:") +local max = 12 +io.write("n/k") +for n = 0, max do fmt.write("%10d", n) end +print("\n" .. string.rep("-", 133)) +for n = 0, max do + fmt.write("%-3d", n) + for k = 0, n do fmt.write("%10s", stirling2(n, k)) end + print() +end +print("\nThe maximum value of S2(100, k) =") +local previous = zero +for k = 1, 100 do + local current = stirling2(100, k) + if current > previous then + previous = current + else + fmt.print("%s\n(%d digits, k = %d)", previous, #previous:tostring(), k - 1) + break + end +end diff --git a/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk b/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk index 6f227a12f9..203db51611 100644 --- a/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk +++ b/Task/Straddling-checkerboard/AutoHotkey/straddling-checkerboard.ahk @@ -11,31 +11,31 @@ Num2 := InStr(board, A_Space) -1 Num3 := InStr(board, A_Space, true, Num1+1) -1 Loop Parse, Text { - char := A_LoopField - Loop Parse, board, `n - { - If (Pos := InStr(A_LoopField, char)) - out .= Num%A_Index% . Pos-1 - else if (Pos := InStr(A_LoopField, "/")) && InStr("0123456789", char) - out .= Num%A_Index% . Pos-1 . char - } + char := A_LoopField + Loop Parse, board, `n + { + If (Pos := InStr(A_LoopField, char)) + out .= Num%A_Index% . Pos-1 + else if (Pos := InStr(A_LoopField, "/")) && InStr("0123456789", char) + out .= Num%A_Index% . Pos-1 . char + } } MsgBox % out i := 0 While (LoopField := SubStr(out, ++i, 1)) <> "" { - If (LoopField = num2) or (LoopField = num3) - col := SubStr(out, ++i, 1) - else col := 0 - Loop Parse, board, `n - { - If !col && A_Index = 1 - dec .= SubStr(A_LoopField, LoopField+1, 1) - Else If (Num%A_Index% = LoopField) && col - dec .= SubStr(A_LoopField, col+1, 1) - If SubStr(dec, 0) = "/" - dec := SubStr(dec, 1, StrLen(dec)-1) . SubStr(out, ++i, 1) - } + If (LoopField = num2) or (LoopField = num3) + col := SubStr(out, ++i, 1) + else col := 0 + Loop Parse, board, `n + { + If !col && A_Index = 1 + dec .= SubStr(A_LoopField, LoopField+1, 1) + Else If (Num%A_Index% = LoopField) && col + dec .= SubStr(A_LoopField, col+1, 1) + If SubStr(dec, 0) = "/" + dec := SubStr(dec, 1, StrLen(dec)-1) . SubStr(out, ++i, 1) + } } MsgBox % dec diff --git a/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c b/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c index 8858bd680d..b313fd8c29 100644 --- a/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c +++ b/Task/Straddling-checkerboard/C/straddling-checkerboard-1.c @@ -79,7 +79,7 @@ GHashTable *create_table_from_array(const char *table[ROWS][COLS], bool is_encod numprefix_col = i; numprefix_row = j; has_numprefix = true; - break; + break; } } } @@ -92,21 +92,21 @@ GHashTable *create_table_from_array(const char *table[ROWS][COLS], bool is_encod if (table[i][j] == NULL) continue; if (strlen(table[i][j]) > 1) { - fprintf(stderr, "symbols must be 1 byte long\n"); - continue; // we continue just ignoring the issue + fprintf(stderr, "symbols must be 1 byte long\n"); + continue; // we continue just ignoring the issue } if (has_numprefix && i == (ROWS-1) && j == numprefix_col && i == numprefix_row) continue; if (has_numprefix && i == 0) { - snprintf(buf, sizeof(buf), "%s%s%s", table[0][selectors[SELNUM-1]], table[0][numprefix_col], table[0][j]); + snprintf(buf, sizeof(buf), "%s%s%s", table[0][selectors[SELNUM-1]], table[0][numprefix_col], table[0][j]); } else if (i == 1) { - snprintf(buf, sizeof(buf), "%s", table[0][j]); + snprintf(buf, sizeof(buf), "%s", table[0][j]); } else { - snprintf(buf, sizeof(buf), "%s%s", table[0][selectors[i-2]], table[0][j]); + snprintf(buf, sizeof(buf), "%s%s", table[0][selectors[i-2]], table[0][j]); } if (is_encoding) g_hash_table_insert(r, strdup(table[i][j]), strdup(buf)); else g_hash_table_insert(r, strdup(buf), strdup(table[i][j])); @@ -179,8 +179,8 @@ char *encode(GHashTable *et, const char *plaintext, int (*trasf)(int), bool comp else { fprintf(stderr, "char '%s' is not encodable%s\n", - isprint(buf[0]) ? buf : "?", - !compress_spaces ? ", replacing with a space" : ""); + isprint(buf[0]) ? buf : "?", + !compress_spaces ? ", replacing with a space" : ""); if (!compress_spaces) g_string_append_c(s, ' '); } } diff --git a/Task/Straddling-checkerboard/Crystal/straddling-checkerboard.cr b/Task/Straddling-checkerboard/Crystal/straddling-checkerboard.cr new file mode 100644 index 0000000000..39808905c1 --- /dev/null +++ b/Task/Straddling-checkerboard/Crystal/straddling-checkerboard.cr @@ -0,0 +1,49 @@ +def encrypt (board, message) + prefixes = [""] + board.first.chars.each.with_index.select {|ch, _| ch == ' ' }.map(&.last.to_s).to_a + encode_letter = ->(ch : Char) { + col = nil + row = board.index {|r| col = r.index ch} + raise "incomplete board" unless col && row + prefixes[row] + col.to_s + } + String.build do |s| + message.each_char do |ch| + if ch.ascii_number? + s << encode_letter['/'] << ch + else + ch = ch.ascii_letter? ? ch.upcase : '.' + s << encode_letter[ch] + end + end + end +end + +def decrypt (board, message) + prefixes = board.first.chars.each.with_index.select {|ch, _| ch == ' ' }.map {|ch, idx| '0' + idx}.to_a + message = message.chars + String.build do |s| + i = 0 + while i < message.size + row = prefixes.index(message[i]) + letter = if row + board[row+1][message[i+=1].to_i] + else + board[0][message[i].to_i] + end + if letter == '/' + s << message[i+=1] + else + s << letter + end + i += 1 + end + end +end + +board = ["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."] + +original = "One night-it was on the twentieth of March, 1888-I was returning" +coded = encrypt(board, original) +decoded = decrypt(board, coded) + +p! original, coded, decoded diff --git a/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy b/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy index 796a84f3f6..117f165017 100644 --- a/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy +++ b/Task/Straddling-checkerboard/EasyLang/straddling-checkerboard.easy @@ -1,8 +1,6 @@ board$ = "ET AON RISBCDFGHJKLMPQ/UVWXYZ." len encode[] 128 len decode$[] 128 -arrbase encode[] 0 -arrbase decode$[] 0 len row[] 2 proc init s$ . s$[] = strchars s$ diff --git a/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js b/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js index 320a1cc5bc..461fb5effa 100644 --- a/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js +++ b/Task/Straddling-checkerboard/JavaScript/straddling-checkerboard.js @@ -8,13 +8,13 @@ function straddle(message){ message=message.replace(/([0-9])/g,"/$1") // dumb way to escape numbers for(var i=0;inumbers, numbers1) - else.if n<20 then - n+=num0 - else.if n<30 then - n+=num10 - else - n+=num20 - end if - encoded$+=str$(n,"") - next - =encoded$ - } - function decrypt$(encoded$, alphabet) { - def num1, num2 - num1=instr(alphabet#val$(0)," ") - num2=instr(alphabet#val$(0)," ", num1+1)-1 - num1-- - escapenum=instr(alphabet#val$(2),"/")-1 - escapenum1=instr(alphabet#val$(2),".")-1 - def i=1, decoded$ - j=len(encoded$)+1 - while inumbers, numbers1) + else.if n<20 then + n+=num0 + else.if n<30 then + n+=num10 + else + n+=num20 + end if + encoded$+=str$(n,"") + next + =encoded$ + } + function decrypt$(encoded$, alphabet) { + def num1, num2 + num1=instr(alphabet#val$(0)," ") + num2=instr(alphabet#val$(0)," ", num1+1)-1 + num1-- + escapenum=instr(alphabet#val$(2),"/")-1 + escapenum1=instr(alphabet#val$(2),".")-1 + def i=1, decoded$ + j=len(encoded$)+1 + while i (c in board or c in digits) and !(c in " /")) + :reorder() + local sb = "" + for msg as c do + local idx = board:find(c, 1, true) + if idx then + idx -= 1 + local row = idx // 10 + local col = idx % 10 + sb ..= (row == 0) ? $"{col}" : $"{rows[row + 1]}{col}" + else + sb ..= $"{escape}{c}" + end + end + local enc = {sb:byte(1, #sb)} + local i = 0 + for enc as c do + local k = key[i % 4 + 1]:byte() - 48 + if k != 0 then + local j = c - 48 + enc[i + 1] = 48 + ((j + k) % 10) + end + i += 1 + end + + return enc:map(|b| -> string.char(b)):concat("") +end + +local function decrypt(encoded) + local enc = {encoded:byte(1, #encoded)} + local i = 0 + for enc as c do + local k = key[i % 4 + 1]:byte() - 48 + if k != 0 then + local j = c - 48 + enc[i + 1] = 48 + ((j >= k) ? (j - k) % 10 : (10 + j - k) % 10) + end + i += 1 + end + local len = #enc + local sb = "" + i = 0 + while i < len do + local c = enc[i + 1] + local idx = rows:find(tostring(c - 48), 1, true) + if !idx then + local idx2 = c - 48 + sb ..= board[idx2 + 1] + i += 1 + elseif $"{c - 48}{enc[i + 2] - 48}" == escape then + sb ..= tostring(enc[i + 3] - 48) + i += 3 + else + local idx2 = (idx - 1) * 10 + enc[i + 2] - 48 + sb ..= board[idx2 + 1] + i += 2 + end + end + return sb +end + +local messages = { + "Attack at dawn", + "One night-it was on the twentieth of March, 1888-I was returning", + "In the winter 1965/we were hungry/just barely alive", + "you have put on 7.5 pounds since I saw you.", + "The checkerboard cake recipe specifies 3 large eggs and 2.25 cups of flour." +} +for messages as message do + local encrypted = encrypt(message) + local decrypted = decrypt(encrypted) + print($"\nMessage : {message}") + print($"Encrypted : {encrypted}") + print($"Decrypted : {decrypted}") +end diff --git a/Task/Straddling-checkerboard/Rebol/straddling-checkerboard.rebol b/Task/Straddling-checkerboard/Rebol/straddling-checkerboard.rebol new file mode 100644 index 0000000000..e3e7686a5e --- /dev/null +++ b/Task/Straddling-checkerboard/Rebol/straddling-checkerboard.rebol @@ -0,0 +1,78 @@ +Rebol [ + title: "Rosetta code: Straddling checkerboard" + file: %Straddling_checkerboard.r3 + url: https://rosettacode.org/wiki/Straddling_checkerboard +] + +register-codec [ + name: 'straddle + type: 'cryptography + title: "Straddling checkerboard" + + T: [ + ["79" #"0" #"1" #"2" #"3" #"4" #"5" #"6" #"7" #"8" #"9"] + ["" #"H" #"O" #"L" "" #"M" #"E" #"S" "" #"R" #"T"] + [#"3" #"A" #"B" #"C" #"D" #"F" #"G" #"I" #"J" #"K" #"N"] + [#"7" #"P" #"Q" #"U" #"V" #"W" #"X" #"Y" #"Z" #"." #"/"] + ] + + header: T/1 ;; digit labels for each column + singles: T/2 ;; single-digit letters (H O L M E S R T) + row3: T/3 ;; two-digit letters starting with 3 + row4: T/4 ;; two-digit letters starting with 7 + + encode: function [ + {Encode plaintext using the straddling checkerboard. + Single-digit letters (row 2) encode to one digit; + all others encode to two digits (row prefix + column digit).} + plaintext [string!] + ][ + result: copy "" + foreach ch plaintext [ + foreach row (next T) [ ;; skip header row + if col: index? find row ch [ + repend result [row/1 header/:col] ;; row prefix ("" for singles) + column digit + break + ] + ] + ] + result + ] + + decode: function [ + {Decode a straddling checkerboard ciphertext back to plaintext. + Reads one digit at a time; if it matches a row prefix (3 or 7) + the next digit selects the column in that row.} + ciphertext [string!] + ][ + result: copy "" + pos: 1 + while [pos <= length? ciphertext] [ + digit: ciphertext/(++ pos) + append result case [ + digit == row3/1 [ ;; escape digit 3 -> read next for row3 + digit: ciphertext/(++ pos) + letter: row3/(2 + digit - #"0") + if letter == #"/" [++ pos] + letter + ] + digit == row4/1 [ ;; escape digit 7 -> read next for row4 + digit: ciphertext/(++ pos) + row4/(2 + digit - #"0") + ] + true [ ;; single-digit: look up in singles row + singles/(2 + digit - #"0") + ] + ] + ] + result + ] +] + +plaintext: "One night-it was on the twentieth of March, 1888-I was returning" +encoded: encode 'straddle plaintext +decoded: decode 'straddle encoded + +print ["Original:" plaintext] +print ["Encoded: " encoded ] +print ["Decoded: " decoded ] diff --git a/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl b/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl index 327abf9bb7..83f7c39ab0 100644 --- a/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl +++ b/Task/Straddling-checkerboard/Tcl/straddling-checkerboard-1.tcl @@ -3,34 +3,34 @@ package require Tcl 8.6 oo::class create StraddlingCheckerboardCypher { variable encmap decmap constructor table { - # Sanity check the table - foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} { - if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} { - error "bad checkerboard table" - } - } - # Synthesize the escaped number row - foreach row $table { - if {"/" ni $row} continue - set pfx [lindex $row 0][expr {[lsearch -exact $row "/"]-1}] - lappend table [list $pfx 0 1 2 3 4 5 6 7 8 9] - break - } - # Build the actual per-character mapping - foreach row $table { - foreach ch [lrange $row 1 end] n {0 1 2 3 4 5 6 7 8 9} { - if {$ch in {"" "/"}} continue; # Skip escape cases - lappend encmap $ch [lindex $row 0]$n - lappend decmap [lindex $row 0]$n $ch - } - } + # Sanity check the table + foreach ch [lindex $table 0] i {"" 0 1 2 3 4 5 6 7 8 9} { + if {$ch eq "" && $i ne "" && [lsearch -index 0 $table $i] < 1} { + error "bad checkerboard table" + } + } + # Synthesize the escaped number row + foreach row $table { + if {"/" ni $row} continue + set pfx [lindex $row 0][expr {[lsearch -exact $row "/"]-1}] + lappend table [list $pfx 0 1 2 3 4 5 6 7 8 9] + break + } + # Build the actual per-character mapping + foreach row $table { + foreach ch [lrange $row 1 end] n {0 1 2 3 4 5 6 7 8 9} { + if {$ch in {"" "/"}} continue; # Skip escape cases + lappend encmap $ch [lindex $row 0]$n + lappend decmap [lindex $row 0]$n $ch + } + } } # These methods just sanitize their input and apply the map method encode msg { - string map $encmap [regsub -all {[^A-Z0-9.]} [string toupper $msg] ""] + string map $encmap [regsub -all {[^A-Z0-9.]} [string toupper $msg] ""] } method decode msg { - string map $decmap [regsub -all {[^0-9]} $msg ""] + string map $decmap [regsub -all {[^0-9]} $msg ""] } } diff --git a/Task/Straddling-checkerboard/V-(Vlang)/straddling-checkerboard.v b/Task/Straddling-checkerboard/V-(Vlang)/straddling-checkerboard.v new file mode 100644 index 0000000000..0aa6c3c782 --- /dev/null +++ b/Task/Straddling-checkerboard/V-(Vlang)/straddling-checkerboard.v @@ -0,0 +1,75 @@ +const key = " + 8752390146 + ET AON RIS +5BC/FGHJKLM +0PQD.VWXYZU" + +const pnt = "you have put on 7.5 pounds since I saw you." + +fn main() { + println(pnt) + cnt := enc(key, pnt) + println(cnt) + println(dec(key, cnt)) +} + +fn enc(bsg string, psg string) string { + row := bsg.split("\n")[1..] + r2d := row[2][..1] + r3d := row[3][..1] + mut enc := map[byte]string{} + mut csg, mut dre, mut num := "", "", "" + for col := 1; col <= 10; col++ { + dre = row[0][col].ascii_str() + enc[row[1][col]] = dre + enc[row[2][col]] = r2d + dre + enc[row[3][col]] = r3d + dre + } + num = enc[`/`] + enc.delete(`/`) + enc.delete(` `) + for cal in psg.bytes() { + if cal >= `0` && cal <= `9` { csg += num + cal.ascii_str() } + else { + mut ch := cal + if ch >= `a` && ch <= `z` { ch -= `a` - `A` } + csg += enc[ch] or { "" } + } + } + return csg +} + +fn dec(bsg string, csg string) string { + row := bsg.split("\n")[1..] + r2d := row[2][0] - `0` + r3d := row[3][0] - `0` + mut cay := [10]int{} + mut psg := "" + mut dre, mut bre := rune(0), rune(0) + mut inr, mut rnr := 0, 0 + for idx in 1 .. 11 { + cay[int(row[0][idx]) - int(`0`)] = idx + } + for inr < csg.len { + dre = csg[inr] - `0` + rnr = 0 + match dre { + r2d { rnr = 2 } + r3d { rnr = 3 } + else { + psg += row[1][cay[int(dre)]].ascii_str() + inr++ + continue + } + } + inr++ + bre = row[rnr][cay[int(csg[inr] - `0`)]] + if bre == `/` { + inr++ + psg += csg[inr].ascii_str() + } + else { psg += bre.str() } + inr++ + } + return psg +} diff --git a/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vbs b/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vbs new file mode 100644 index 0000000000..22371d5bc6 --- /dev/null +++ b/Task/Straddling-checkerboard/VBScript/straddling-checkerboard.vbs @@ -0,0 +1,88 @@ +' Straddling checkerboard - VBScript - 19/04/2019 + +Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2) + Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." + Dim i, j, curChar, escChar, outText + Dim cipher 'Hash table + Set cipher = CreateObject("Scripting.Dictionary") + 'build cipher reference + alphabet = UCase(alphabet) : j = 0 + For i = 1 To 28 + curChar = Mid(alphabet, i, 1) + Select Case True + Case i>= 1 And i<= 8 + If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank + cipher.Add curChar, CStr(j) + j = j + 1 + Case i>= 9 And i<=18 + cipher.Add curChar, CStr(blank1) & CStr(i - 9) + Case i>=19 And i<=28 + cipher.Add curChar, CStr(blank2) & CStr(i - 19) + End Select 'i + If InStr(notEscape, curChar) = 0 Then + escChar = curChar + 'Wscript.Echo "escChar=" & escChar & " cipher(escChar)=" & cipher(escChar) + End If + Next 'i + For i = 0 To 9: cipher.Add CStr(i), cipher(escChar) & CStr(i): Next + 'encrypt each character + originalText = UCase(originalText) + For i = 1 To Len(originalText) + outText = outText & cipher(Mid(originalText, i, 1)) + Next + encrypt=outText +End Function 'encrypt + +Function decrypt(ByVal cipherText, ByVal alphabet, blank1, blank2) + Const notEscape = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ." + Dim i, j, curChar, escCipher, outText + Dim cipher 'Hash table + Set cipher = CreateObject("Scripting.Dictionary") + 'build decipher reference + alphabet = UCase(alphabet) : j = 0 + For i = 1 To 28 + curChar = Mid(alphabet, i, 1) + Select Case True + Case i>= 1 And i<= 8 + If j = blank1 Or j = blank2 Then j = j + 1 'adjust for blank + cipher.Add CStr(j),curChar + j = j + 1 + Case i>= 9 And i<=18 + cipher.Add CStr(blank1) & CStr(i - 9), curChar + Case i>=19 And i<=28 + cipher.Add CStr(blank2) & CStr(i - 19), curChar + End Select 'i + If InStr(notEscape, curChar) = 0 Then + 'the last element of cipher + arrayKeys=cipher.keys + escCipher = arrayKeys(cipher.count-1) + 'Wscript.Echo "escCipher=" & escCipher & " cipher(escCipher)=" & cipher(escCipher) + End If + Next 'i + For i = 0 To 9: cipher.Add escCipher & CStr(i), CStr(i): Next + 'decrypt each character + i = 1 + Do While i <= Len(cipherText) + curChar = Mid(cipherText, i, 1) + If curChar = CStr(blank1) Or curChar = CStr(blank2) Then + curChar = Mid(cipherText, i, 2) + If curChar = escCipher Then curChar = Mid(cipherText, i, 3) + End If + outText = outText & cipher(curChar) + i = i + Len(curChar) + Loop 'i + decrypt=outText +End Function 'decrypt + + message = "One night-it was on the twentieth of March, 1888-I was returning" + cipher = "HOLMESRTABCDFGIJKNPQUVWXYZ./" + '3 7 <=8 + 'HOL MES RT + 'ABCDFGIJKN + 'PQUVWXYZ./ + Buffer=Buffer & "Original: " & message & vbCrlf + encoded = encrypt(message, cipher, 3, 7) + Buffer=Buffer & "encoded: " & encoded & vbCrlf + decoded = decrypt(encoded, cipher, 3, 7) + Buffer=Buffer & "decoded: " & decoded & vbCrlf + Wscript.Echo Buffer diff --git a/Task/Strassens-algorithm/COBOL/strassens-algorithm.cob b/Task/Strassens-algorithm/COBOL/strassens-algorithm.cob new file mode 100644 index 0000000000..56dc949bdc --- /dev/null +++ b/Task/Strassens-algorithm/COBOL/strassens-algorithm.cob @@ -0,0 +1,367 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. StrassenAlgorithm. + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 MAT-A. 05 A-DIM PIC 9(4) COMP VALUE 2. 05 A-D OCCURS 16 USAGE COMP-2. + 01 MAT-B. 05 B-DIM PIC 9(4) COMP VALUE 2. 05 B-D OCCURS 16 USAGE COMP-2. + 01 MAT-C. 05 C-DIM PIC 9(4) COMP VALUE 4. 05 C-D OCCURS 16 USAGE COMP-2. + 01 MAT-D. 05 D-DIM PIC 9(4) COMP VALUE 4. 05 D-D OCCURS 16 USAGE COMP-2. + 01 MAT-E. 05 E-DIM PIC 9(4) COMP VALUE 4. 05 E-D OCCURS 16 USAGE COMP-2. + 01 MAT-F. 05 F-DIM PIC 9(4) COMP VALUE 4. 05 F-D OCCURS 16 USAGE COMP-2. + 01 MAT-RES. 05 R-DIM PIC 9(4) COMP. 05 R-D OCCURS 16 USAGE COMP-2. + + 01 FMT-NORMAL PIC 9 VALUE 1. + 01 FMT-PREC6 PIC 9 VALUE 6. + + PROCEDURE DIVISION. + MOVE 1.0 TO A-D(1). MOVE 2.0 TO A-D(2). + MOVE 3.0 TO A-D(3). MOVE 4.0 TO A-D(4). + + MOVE 5.0 TO B-D(1). MOVE 6.0 TO B-D(2). + MOVE 7.0 TO B-D(3). MOVE 8.0 TO B-D(4). + + MOVE 1.0 TO C-D(1). MOVE 1.0 TO C-D(2). MOVE 1.0 TO C-D(3). MOVE 1.0 TO C-D(4). + MOVE 2.0 TO C-D(5). MOVE 4.0 TO C-D(6). MOVE 8.0 TO C-D(7). MOVE 16.0 TO C-D(8). + MOVE 3.0 TO C-D(9). MOVE 9.0 TO C-D(10). MOVE 27.0 TO C-D(11). MOVE 81.0 TO C-D(12). + MOVE 4.0 TO C-D(13). MOVE 16.0 TO C-D(14). MOVE 64.0 TO C-D(15). MOVE 256.0 TO C-D(16). + + COMPUTE D-D(1) = 4.0. COMPUTE D-D(2) = -3.0. COMPUTE D-D(3) = 4.0 / 3.0. COMPUTE D-D(4) = -1.0 / 4.0. + COMPUTE D-D(5) = -13.0 / 3.0. COMPUTE D-D(6) = 19.0 / 4.0. COMPUTE D-D(7) = -7.0 / 3.0. COMPUTE D-D(8) = 11.0 / 24.0. + COMPUTE D-D(9) = 3.0 / 2.0. COMPUTE D-D(10) = -2.0. COMPUTE D-D(11) = 7.0 / 6.0. COMPUTE D-D(12) = -1.0 / 4.0. + COMPUTE D-D(13) = -1.0 / 6.0. COMPUTE D-D(14) = 1.0 / 4.0. COMPUTE D-D(15) = -1.0 / 6.0. COMPUTE D-D(16) = 1.0 / 24.0. + + MOVE 1.0 TO E-D(1). MOVE 2.0 TO E-D(2). MOVE 3.0 TO E-D(3). MOVE 4.0 TO E-D(4). + MOVE 5.0 TO E-D(5). MOVE 6.0 TO E-D(6). MOVE 7.0 TO E-D(7). MOVE 8.0 TO E-D(8). + MOVE 9.0 TO E-D(9). MOVE 10.0 TO E-D(10). MOVE 11.0 TO E-D(11). MOVE 12.0 TO E-D(12). + MOVE 13.0 TO E-D(13). MOVE 14.0 TO E-D(14). MOVE 15.0 TO E-D(15). MOVE 16.0 TO E-D(16). + + MOVE 1.0 TO F-D(1). MOVE 0.0 TO F-D(2). MOVE 0.0 TO F-D(3). MOVE 0.0 TO F-D(4). + MOVE 0.0 TO F-D(5). MOVE 1.0 TO F-D(6). MOVE 0.0 TO F-D(7). MOVE 0.0 TO F-D(8). + MOVE 0.0 TO F-D(9). MOVE 0.0 TO F-D(10). MOVE 1.0 TO F-D(11). MOVE 0.0 TO F-D(12). + MOVE 0.0 TO F-D(13). MOVE 0.0 TO F-D(14). MOVE 0.0 TO F-D(15). MOVE 1.0 TO F-D(16). + + DISPLAY "Using 'normal' matrix multiplication:". + DISPLAY " a * b = " WITH NO ADVANCING. + CALL "NORMAL-MULT" USING MAT-A, MAT-B, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + DISPLAY " c * d = " WITH NO ADVANCING. + CALL "NORMAL-MULT" USING MAT-C, MAT-D, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-PREC6. + + DISPLAY " e * f = " WITH NO ADVANCING. + CALL "NORMAL-MULT" USING MAT-E, MAT-F, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + DISPLAY "Using 'Strassen' matrix multiplication:". + DISPLAY " a * b = " WITH NO ADVANCING. + CALL "STRASSEN-MULT" USING MAT-A, MAT-B, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + DISPLAY " c * d = " WITH NO ADVANCING. + CALL "STRASSEN-MULT" USING MAT-C, MAT-D, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-PREC6. + + DISPLAY " e * f = " WITH NO ADVANCING. + CALL "STRASSEN-MULT" USING MAT-E, MAT-F, MAT-RES. + CALL "PRINT-MATRIX" USING MAT-RES, FMT-NORMAL. + + STOP RUN. + END PROGRAM StrassenAlgorithm. + + IDENTIFICATION DIVISION. + PROGRAM-ID. MATRIX-ADD. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 TOTAL-CELLS PIC 9(4) COMP. + LINKAGE SECTION. + 01 L-A. + 05 A-DIM PIC 9(4) COMP. + 05 A-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-B. + 05 B-DIM PIC 9(4) COMP. + 05 B-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-C. + 05 C-DIM PIC 9(4) COMP. + 05 C-DATA OCCURS 16 TIMES USAGE COMP-2. + PROCEDURE DIVISION USING L-A, L-B, L-C. + MOVE A-DIM TO C-DIM + COMPUTE TOTAL-CELLS = A-DIM * A-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > TOTAL-CELLS + COMPUTE C-DATA(I) = A-DATA(I) + B-DATA(I) + END-PERFORM + GOBACK. + END PROGRAM MATRIX-ADD. + + IDENTIFICATION DIVISION. + PROGRAM-ID. MATRIX-SUB. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 TOTAL-CELLS PIC 9(4) COMP. + LINKAGE SECTION. + 01 L-A. + 05 A-DIM PIC 9(4) COMP. + 05 A-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-B. + 05 B-DIM PIC 9(4) COMP. + 05 B-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-C. + 05 C-DIM PIC 9(4) COMP. + 05 C-DATA OCCURS 16 TIMES USAGE COMP-2. + PROCEDURE DIVISION USING L-A, L-B, L-C. + MOVE A-DIM TO C-DIM + COMPUTE TOTAL-CELLS = A-DIM * A-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > TOTAL-CELLS + COMPUTE C-DATA(I) = A-DATA(I) - B-DATA(I) + END-PERFORM + GOBACK. + END PROGRAM MATRIX-SUB. + + IDENTIFICATION DIVISION. + PROGRAM-ID. NORMAL-MULT. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 J PIC 9(4) COMP. + 01 K PIC 9(4) COMP. + 01 SUM-VAL USAGE COMP-2. + 01 A-IDX PIC 9(4) COMP. + 01 B-IDX PIC 9(4) COMP. + 01 C-IDX PIC 9(4) COMP. + LINKAGE SECTION. + 01 L-A. + 05 A-DIM PIC 9(4) COMP. + 05 A-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-B. + 05 B-DIM PIC 9(4) COMP. + 05 B-DATA OCCURS 16 TIMES USAGE COMP-2. + 01 L-C. + 05 C-DIM PIC 9(4) COMP. + 05 C-DATA OCCURS 16 TIMES USAGE COMP-2. + PROCEDURE DIVISION USING L-A, L-B, L-C. + MOVE A-DIM TO C-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > A-DIM + PERFORM VARYING J FROM 1 BY 1 UNTIL J > A-DIM + COMPUTE C-IDX = (I - 1) * A-DIM + J + MOVE 0 TO SUM-VAL + PERFORM VARYING K FROM 1 BY 1 UNTIL K > A-DIM + COMPUTE A-IDX = (I - 1) * A-DIM + K + COMPUTE B-IDX = (K - 1) * A-DIM + J + COMPUTE SUM-VAL = SUM-VAL + + A-DATA(A-IDX) * B-DATA(B-IDX) + END-PERFORM + MOVE SUM-VAL TO C-DATA(C-IDX) + END-PERFORM + END-PERFORM + GOBACK. + END PROGRAM NORMAL-MULT. + + IDENTIFICATION DIVISION. + PROGRAM-ID. PRINT-MATRIX. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 I PIC 9(4) COMP. + 01 J PIC 9(4) COMP. + 01 IDX PIC 9(4) COMP. + 01 FMT-VAL-1 PIC -(4)9.9. + 01 ZERO-VAL-1 PIC -(4)9.9 VALUE 0.0. + 01 FMT-VAL-6 PIC -(4)9.9(6). + 01 ZERO-VAL-6 PIC -(4)9.9(6) VALUE 0.000000. + 01 OUT-STR PIC X(80). + 01 PTR PIC 9(4) COMP. + 01 STR-VAL PIC X(20). + LINKAGE SECTION. + 01 L-M. + 05 M-DIM PIC 9(4) COMP. + 05 M-DATA OCCURS 16 USAGE COMP-2. + 01 L-FMT PIC 9. + PROCEDURE DIVISION USING L-M, L-FMT. + PERFORM VARYING I FROM 1 BY 1 UNTIL I > M-DIM + MOVE SPACES TO OUT-STR + MOVE "[" TO OUT-STR(1:1) + MOVE 2 TO PTR + + PERFORM VARYING J FROM 1 BY 1 UNTIL J > M-DIM + COMPUTE IDX = (I - 1) * M-DIM + J + IF L-FMT = 1 + IF M-DATA(IDX) > -0.05 AND M-DATA(IDX) < 0.05 + MOVE ZERO-VAL-1 TO FMT-VAL-1 + ELSE + IF M-DATA(IDX) > 0 + COMPUTE FMT-VAL-1 = M-DATA(IDX) + 0.05 + ELSE + COMPUTE FMT-VAL-1 = M-DATA(IDX) - 0.05 + END-IF + END-IF + MOVE FUNCTION TRIM(FMT-VAL-1) TO STR-VAL + ELSE + IF M-DATA(IDX) > -0.0000005 AND M-DATA(IDX) < 0.0000005 + MOVE ZERO-VAL-6 TO FMT-VAL-6 + ELSE + IF M-DATA(IDX) > 0 + COMPUTE FMT-VAL-6 = M-DATA(IDX) + 0.0000005 + ELSE + COMPUTE FMT-VAL-6 = M-DATA(IDX) - 0.0000005 + END-IF + END-IF + MOVE FUNCTION TRIM(FMT-VAL-6) TO STR-VAL + END-IF + + STRING FUNCTION TRIM(STR-VAL) DELIMITED BY SIZE + INTO OUT-STR WITH POINTER PTR + + IF J < M-DIM + STRING ", " DELIMITED BY SIZE + INTO OUT-STR WITH POINTER PTR + END-IF + END-PERFORM + + STRING "]" DELIMITED BY SIZE + INTO OUT-STR WITH POINTER PTR + DISPLAY FUNCTION TRIM(OUT-STR) + END-PERFORM + DISPLAY "". + GOBACK. + END PROGRAM PRINT-MATRIX. + + IDENTIFICATION DIVISION. + PROGRAM-ID. STRASSEN-MULT RECURSIVE. + DATA DIVISION. + LOCAL-STORAGE SECTION. + 01 HALF PIC 9(4) COMP. + 01 I PIC 9(4) COMP. + 01 J PIC 9(4) COMP. + 01 SRC-IDX PIC 9(4) COMP. + 01 DST-IDX PIC 9(4) COMP. + + 01 QA0. 05 DIM0 PIC 9(4) COMP. 05 D0 OCCURS 16 USAGE COMP-2. + 01 QA1. 05 DIM1 PIC 9(4) COMP. 05 D1 OCCURS 16 USAGE COMP-2. + 01 QA2. 05 DIM2 PIC 9(4) COMP. 05 D2 OCCURS 16 USAGE COMP-2. + 01 QA3. 05 DIM3 PIC 9(4) COMP. 05 D3 OCCURS 16 USAGE COMP-2. + + 01 QB0. 05 BDIM0 PIC 9(4) COMP. 05 BD0 OCCURS 16 USAGE COMP-2. + 01 QB1. 05 BDIM1 PIC 9(4) COMP. 05 BD1 OCCURS 16 USAGE COMP-2. + 01 QB2. 05 BDIM2 PIC 9(4) COMP. 05 BD2 OCCURS 16 USAGE COMP-2. + 01 QB3. 05 BDIM3 PIC 9(4) COMP. 05 BD3 OCCURS 16 USAGE COMP-2. + + 01 P1. 05 P1-DIM PIC 9(4) COMP. 05 P1-D OCCURS 16 USAGE COMP-2. + 01 P2. 05 P2-DIM PIC 9(4) COMP. 05 P2-D OCCURS 16 USAGE COMP-2. + 01 P3. 05 P3-DIM PIC 9(4) COMP. 05 P3-D OCCURS 16 USAGE COMP-2. + 01 P4. 05 P4-DIM PIC 9(4) COMP. 05 P4-D OCCURS 16 USAGE COMP-2. + 01 P5. 05 P5-DIM PIC 9(4) COMP. 05 P5-D OCCURS 16 USAGE COMP-2. + 01 P6. 05 P6-DIM PIC 9(4) COMP. 05 P6-D OCCURS 16 USAGE COMP-2. + 01 P7. 05 P7-DIM PIC 9(4) COMP. 05 P7-D OCCURS 16 USAGE COMP-2. + + 01 T1. 05 T1-DIM PIC 9(4) COMP. 05 T1-D OCCURS 16 USAGE COMP-2. + 01 T2. 05 T2-DIM PIC 9(4) COMP. 05 T2-D OCCURS 16 USAGE COMP-2. + + 01 Q0. 05 Q0-DIM PIC 9(4) COMP. 05 Q0-D OCCURS 16 USAGE COMP-2. + 01 Q1. 05 Q1-DIM PIC 9(4) COMP. 05 Q1-D OCCURS 16 USAGE COMP-2. + 01 Q2. 05 Q2-DIM PIC 9(4) COMP. 05 Q2-D OCCURS 16 USAGE COMP-2. + 01 Q3. 05 Q3-DIM PIC 9(4) COMP. 05 Q3-D OCCURS 16 USAGE COMP-2. + + LINKAGE SECTION. + 01 L-A. 05 L-A-DIM PIC 9(4) COMP. 05 L-A-D OCCURS 16 USAGE COMP-2. + 01 L-B. 05 L-B-DIM PIC 9(4) COMP. 05 L-B-D OCCURS 16 USAGE COMP-2. + 01 L-C. 05 L-C-DIM PIC 9(4) COMP. 05 L-C-D OCCURS 16 USAGE COMP-2. + + PROCEDURE DIVISION USING L-A, L-B, L-C. + IF L-A-DIM = 1 + MOVE 1 TO L-C-DIM + COMPUTE L-C-D(1) = L-A-D(1) * L-B-D(1) + GOBACK + END-IF. + + COMPUTE HALF = L-A-DIM / 2. + MOVE HALF TO DIM0, DIM1, DIM2, DIM3. + MOVE HALF TO BDIM0, BDIM1, BDIM2, BDIM3. + + PERFORM VARYING I FROM 1 BY 1 UNTIL I > HALF + PERFORM VARYING J FROM 1 BY 1 UNTIL J > HALF + COMPUTE DST-IDX = (I - 1) * HALF + J + + COMPUTE SRC-IDX = (I - 1) * L-A-DIM + J + MOVE L-A-D(SRC-IDX) TO D0(DST-IDX) + + COMPUTE SRC-IDX = (I - 1) * L-A-DIM + (J + HALF) + MOVE L-A-D(SRC-IDX) TO D1(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-A-DIM + J + MOVE L-A-D(SRC-IDX) TO D2(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-A-DIM + (J + HALF) + MOVE L-A-D(SRC-IDX) TO D3(DST-IDX) + + COMPUTE SRC-IDX = (I - 1) * L-B-DIM + J + MOVE L-B-D(SRC-IDX) TO BD0(DST-IDX) + + COMPUTE SRC-IDX = (I - 1) * L-B-DIM + (J + HALF) + MOVE L-B-D(SRC-IDX) TO BD1(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-B-DIM + J + MOVE L-B-D(SRC-IDX) TO BD2(DST-IDX) + + COMPUTE SRC-IDX = (I + HALF - 1) * L-B-DIM + (J + HALF) + MOVE L-B-D(SRC-IDX) TO BD3(DST-IDX) + END-PERFORM + END-PERFORM. + + CALL "MATRIX-SUB" USING QA1, QA3, T1 + CALL "MATRIX-ADD" USING QB2, QB3, T2 + CALL "STRASSEN-MULT" USING T1, T2, P1 + + CALL "MATRIX-ADD" USING QA0, QA3, T1 + CALL "MATRIX-ADD" USING QB0, QB3, T2 + CALL "STRASSEN-MULT" USING T1, T2, P2 + + CALL "MATRIX-SUB" USING QA0, QA2, T1 + CALL "MATRIX-ADD" USING QB0, QB1, T2 + CALL "STRASSEN-MULT" USING T1, T2, P3 + + CALL "MATRIX-ADD" USING QA0, QA1, T1 + CALL "STRASSEN-MULT" USING T1, QB3, P4 + + CALL "MATRIX-SUB" USING QB1, QB3, T2 + CALL "STRASSEN-MULT" USING QA0, T2, P5 + + CALL "MATRIX-SUB" USING QB2, QB0, T2 + CALL "STRASSEN-MULT" USING QA3, T2, P6 + + CALL "MATRIX-ADD" USING QA2, QA3, T1 + CALL "STRASSEN-MULT" USING T1, QB0, P7 + + CALL "MATRIX-ADD" USING P1, P2, T1 + CALL "MATRIX-SUB" USING T1, P4, T2 + CALL "MATRIX-ADD" USING T2, P6, Q0 + + CALL "MATRIX-ADD" USING P4, P5, Q1 + + CALL "MATRIX-ADD" USING P6, P7, Q2 + + CALL "MATRIX-SUB" USING P2, P3, T1 + CALL "MATRIX-ADD" USING T1, P5, T2 + CALL "MATRIX-SUB" USING T2, P7, Q3 + + MOVE L-A-DIM TO L-C-DIM + PERFORM VARYING I FROM 1 BY 1 UNTIL I > HALF + PERFORM VARYING J FROM 1 BY 1 UNTIL J > HALF + COMPUTE SRC-IDX = (I - 1) * HALF + J + + COMPUTE DST-IDX = (I - 1) * L-A-DIM + J + MOVE Q0-D(SRC-IDX) TO L-C-D(DST-IDX) + + COMPUTE DST-IDX = (I - 1) * L-A-DIM + (J + HALF) + MOVE Q1-D(SRC-IDX) TO L-C-D(DST-IDX) + + COMPUTE DST-IDX = (I + HALF - 1) * L-A-DIM + J + MOVE Q2-D(SRC-IDX) TO L-C-D(DST-IDX) + + COMPUTE DST-IDX = (I + HALF - 1) * L-A-DIM + (J + HALF) + MOVE Q3-D(SRC-IDX) TO L-C-D(DST-IDX) + END-PERFORM + END-PERFORM. + + GOBACK. + END PROGRAM STRASSEN-MULT. diff --git a/Task/Strassens-algorithm/Dart/strassens-algorithm.dart b/Task/Strassens-algorithm/Dart/strassens-algorithm.dart new file mode 100644 index 0000000000..853fc1e18f --- /dev/null +++ b/Task/Strassens-algorithm/Dart/strassens-algorithm.dart @@ -0,0 +1,282 @@ +// ----------------------------------------------------------------------------- +// matrix.dart +// Dart translation of the C++ Matrix/Strassen example +// ----------------------------------------------------------------------------- +import 'dart:math' as math; + +/// Simple matrix class that supports normal multiplication, Strassen +/// multiplication and pretty printing with a given precision. +class Matrix { + final List> data; + final int rows; + final int cols; + + // --------------------------------------------------------------------------- + // Construction & basic getters + // --------------------------------------------------------------------------- + Matrix(this.data) + : rows = data.length, + cols = data.isNotEmpty ? data[0].length : 0 { + // Ensure rectangular shape + for (final row in data) { + if (row.length != cols) { + throw ArgumentError('All rows must have the same number of columns.'); + } + } + } + + // --------------------------------------------------------------------------- + // Validation helpers (private) + // --------------------------------------------------------------------------- + void _validateDimensions(Matrix other) { + if (rows != other.rows || cols != other.cols) { + throw StateError('Matrices must have the same dimensions.'); + } + } + + void _validateMultiplication(Matrix other) { + if (cols != other.rows) { + throw StateError('Cannot multiply these matrices (inner dimensions differ).'); + } + } + + void _validateSquarePowerOfTwo() { + if (rows != cols) { + throw StateError('Matrix must be square.'); + } + if (rows == 0 || (rows & (rows - 1)) != 0) { + throw StateError('Size of matrix must be a power of two.'); + } + } + + // --------------------------------------------------------------------------- + // Basic arithmetic operators + // --------------------------------------------------------------------------- + Matrix operator +(Matrix other) { + _validateDimensions(other); + final result = List>.generate( + rows, + (i) => List.generate( + cols, (j) => data[i][j] + other.data[i][j], + growable: false), + growable: false); + return Matrix(result); + } + + Matrix operator -(Matrix other) { + _validateDimensions(other); + final result = List>.generate( + rows, + (i) => List.generate( + cols, (j) => data[i][j] - other.data[i][j], + growable: false), + growable: false); + return Matrix(result); + } + + Matrix operator *(Matrix other) { + _validateMultiplication(other); + final result = List>.generate( + rows, + (i) => List.filled(other.cols, 0.0, growable: false), + growable: false); + + for (var i = 0; i < rows; ++i) { + for (var j = 0; j < other.cols; ++j) { + double sum = 0.0; + for (var k = 0; k < cols; ++k) { + sum += data[i][k] * other.data[k][j]; + } + result[i][j] = sum; + } + } + return Matrix(result); + } + + // --------------------------------------------------------------------------- + // Pretty printing + // --------------------------------------------------------------------------- + @override + String toString() { + final sb = StringBuffer(); + for (final row in data) { + sb.writeln('[${row.join(', ')}]'); + } + return sb.toString(); + } + + /// Returns a string where each element is rounded to **[prec]** decimal + /// places (like the C++ `toStringWithPrecision`). The handling of “‑0” + /// → “0” mirrors the original implementation. + String toStringWithPrecision(int prec) { + final pow = math.pow(10.0, prec); + final sb = StringBuffer(); + + for (final row in data) { + sb.write('['); + for (var i = 0; i < row.length; ++i) { + // Round to the requested precision + var r = (row[i] * pow).round() / pow; + // Remove the negative zero representation + if (r == -0.0) r = 0.0; + final formatted = r.toStringAsFixed(prec); + sb.write(formatted); + if (i < row.length - 1) sb.write(', '); + } + sb.writeln(']'); + } + + return sb.toString(); + } + + // --------------------------------------------------------------------------- + // Strassen‑specific helpers (private) + // --------------------------------------------------------------------------- + /// Returns the 4‑parameter table that tells where each quarter starts + /// and how many rows/columns it occupies. + static List> _params(int r, int c) => [ + // r0, r1, c0, c1, dr, dc (dr/dc are offsets used while copying) + [0, r, 0, c, 0, 0], + [0, r, c, 2 * c, 0, c], + [r, 2 * r, 0, c, r, 0], + [r, 2 * r, c, 2 * c, r, c], + ]; + + /// Splits a square matrix (size = 2·r × 2·c) into its four quarters. + List _toQuarters() { + final r = rows ~/ 2; + final c = cols ~/ 2; + final p = _params(r, c); + final List quarters = List.filled(4, Matrix([])); + + for (var k = 0; k < 4; ++k) { + final qData = List>.generate( + r, (_) => List.filled(c, 0.0, growable: false), + growable: false); + for (var i = p[k][0]; i < p[k][1]; ++i) { + for (var j = p[k][2]; j < p[k][3]; ++j) { + qData[i - p[k][4]][j - p[k][5]] = data[i][j]; + } + } + quarters[k] = Matrix(qData); + } + return quarters; + } + + /// Reassembles a full matrix from four quarters. + static Matrix _fromQuarters(List q) { + final r = q[0].rows; + final c = q[0].cols; + final p = _params(r, c); + final rows = r * 2; + final cols = c * 2; + + final mData = List>.generate( + rows, (_) => List.filled(cols, 0.0, growable: false), + growable: false); + + for (var k = 0; k < 4; ++k) { + for (var i = p[k][0]; i < p[k][1]; ++i) { + for (var j = p[k][2]; j < p[k][3]; ++j) { + mData[i][j] = q[k].data[i - p[k][4]][j - p[k][5]]; + } + } + } + + return Matrix(mData); + } + + // --------------------------------------------------------------------------- + // Strassen multiplication (public) + // --------------------------------------------------------------------------- + Matrix strassen(Matrix other) { + _validateSquarePowerOfTwo(); + other._validateSquarePowerOfTwo(); + + if (rows != other.rows || cols != other.cols) { + throw StateError( + 'Matrices must be square and of equal size for Strassen multiplication.'); + } + + // Base case – 1×1 matrices are multiplied normally + if (rows == 1) { + return this * other; + } + + // Split both matrices into quarters + final a = _toQuarters(); + final b = other._toQuarters(); + + // Compute the seven products (recursively) + final p1 = (a[1] - a[3]).strassen(b[2] + b[3]); + final p2 = (a[0] + a[3]).strassen(b[0] + b[3]); + final p3 = (a[0] - a[2]).strassen(b[0] + b[1]); + final p4 = (a[0] + a[1]).strassen(b[3]); + final p5 = a[0].strassen(b[1] - b[3]); + final p6 = a[3].strassen(b[2] - b[0]); + final p7 = (a[2] + a[3]).strassen(b[0]); + + // Combine the products into the four result quadrants + final List q = List.filled( + 4, + Matrix( + List>.filled(0, [])), // placeholder – will be overwritten + growable: false); + + q[0] = p1 + p2 - p4 + p6; + q[1] = p4 + p5; + q[2] = p6 + p7; + q[3] = p2 - p3 + p5 - p7; + + // Re‑assemble the final matrix + return Matrix._fromQuarters(q); + } +} + +// ----------------------------------------------------------------------------- +// Demo (mirrors the original C++ main) +// ----------------------------------------------------------------------------- +void main() { + final a = Matrix([ + [1.0, 2.0], + [3.0, 4.0] + ]); + final b = Matrix([ + [5.0, 6.0], + [7.0, 8.0] + ]); + final c = Matrix([ + [1.0, 1.0, 1.0, 1.0], + [2.0, 4.0, 8.0, 16.0], + [3.0, 9.0, 27.0, 81.0], + [4.0, 16.0, 64.0, 256.0], + ]); + final d = Matrix([ + [4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0], + [-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0], + [3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0], + [-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0], + ]); + final e = Matrix([ + [1.0, 2.0, 3.0, 4.0], + [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0], + [13.0, 14.0, 15.0, 16.0], + ]); + final f = Matrix([ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ]); + + print("Using 'normal' matrix multiplication:"); + print(' a * b = ${a * b}'); + print(' c * d = ${ (c * d).toStringWithPrecision(6)}'); + print(' e * f = ${e * f}'); + + print('\nUsing \'Strassen\' matrix multiplication:'); + print(' a * b = ${a.strassen(b)}'); + print(' c * d = ${c.strassen(d).toStringWithPrecision(6)}'); + print(' e * f = ${e.strassen(f)}'); +} diff --git a/Task/Strassens-algorithm/Elixir/strassens-algorithm.ex b/Task/Strassens-algorithm/Elixir/strassens-algorithm.ex new file mode 100644 index 0000000000..b40ae5c42a --- /dev/null +++ b/Task/Strassens-algorithm/Elixir/strassens-algorithm.ex @@ -0,0 +1,293 @@ +defmodule Matrix do + @moduledoc """ + A matrix implementation with basic operations and Strassen multiplication. + """ + + use Bitwise + defstruct [:data, :rows, :cols] + + @doc """ + Creates a new matrix from the given data. + """ + def new(data) do + rows = length(data) + cols = case rows do + 0 -> 0 + _ -> length(hd(data)) + end + %Matrix{data: data, rows: rows, cols: cols} + end + + @doc """ + Gets the number of rows in the matrix. + """ + def get_rows(%Matrix{rows: rows}), do: rows + + @doc """ + Gets the number of columns in the matrix. + """ + def get_cols(%Matrix{cols: cols}), do: cols + + # Validation functions + defp validate_dimensions(m1, m2) do + unless get_rows(m1) == get_rows(m2) and get_cols(m1) == get_cols(m2) do + raise ArgumentError, "Matrices must have the same dimensions." + end + end + + defp validate_multiplication(m1, m2) do + unless get_cols(m1) == get_rows(m2) do + raise ArgumentError, "Cannot multiply these matrices." + end + end + + defp validate_square_power_of_two(m) do + rows = get_rows(m) + cols = get_cols(m) + + unless rows == cols do + raise ArgumentError, "Matrix must be square." + end + + unless rows > 0 and (rows &&& (rows - 1)) == 0 do + raise ArgumentError, "Size of matrix must be a power of two." + end + end + + @doc """ + Adds two matrices element-wise. + """ + def add(m1, m2) do + validate_dimensions(m1, m2) + data1 = m1.data + data2 = m2.data + result_data = add_rows(data1, data2) + new(result_data) + end + + defp add_rows([], []), do: [] + defp add_rows([row1 | rest1], [row2 | rest2]) do + [add_elements(row1, row2) | add_rows(rest1, rest2)] + end + + defp add_elements([], []), do: [] + defp add_elements([e1 | rest1], [e2 | rest2]) do + [e1 + e2 | add_elements(rest1, rest2)] + end + + @doc """ + Subtracts the second matrix from the first element-wise. + """ + def subtract(m1, m2) do + validate_dimensions(m1, m2) + data1 = m1.data + data2 = m2.data + result_data = subtract_rows(data1, data2) + new(result_data) + end + + defp subtract_rows([], []), do: [] + defp subtract_rows([row1 | rest1], [row2 | rest2]) do + [subtract_elements(row1, row2) | subtract_rows(rest1, rest2)] + end + + defp subtract_elements([], []), do: [] + defp subtract_elements([e1 | rest1], [e2 | rest2]) do + [e1 - e2 | subtract_elements(rest1, rest2)] + end + + @doc """ + Multiplies two matrices using standard algorithm. + """ + def multiply(m1, m2) do + validate_multiplication(m1, m2) + data1 = m1.data + data2 = m2.data + cols2 = get_cols(m2) + result_data = multiply_rows(data1, data2, cols2) + new(result_data) + end + + defp multiply_rows([], _data2, _cols2), do: [] + defp multiply_rows([row | rest], data2, cols2) do + result_row = multiply_row_with_matrix(row, data2, cols2) + [result_row | multiply_rows(rest, data2, cols2)] + end + + defp multiply_row_with_matrix(row, data2, cols2) do + for j <- 1..cols2 do + dot_product(row, get_column(data2, j)) + end + end + + defp get_column(data, col_index) do + for row <- data, do: Enum.at(row, col_index - 1) + end + + defp dot_product(list1, list2) do + Enum.zip(list1, list2) + |> Enum.map(fn {e1, e2} -> e1 * e2 end) + |> Enum.sum() + end + + @doc """ + Converts matrix to string representation. + """ + def to_matrix_string(m) do + data = m.data + rows_str = for row <- data, do: format_row(row) + Enum.join(rows_str, "\n") <> "\n" + end + + defp format_row(row) do + elements = for e <- row, do: format_element(e) + "[" <> Enum.join(elements, ", ") <> "]" + end + + defp format_element(e) do + "#{e}" + end + + @doc """ + Converts matrix to string with specified precision. + """ + def to_matrix_string_with_precision(m, precision) do + data = m.data + pow = :math.pow(10.0, precision) + rows_str = for row <- data, do: format_row_with_precision(row, pow, precision) + Enum.join(rows_str, "\n") <> "\n" + end + + defp format_row_with_precision(row, pow, precision) do + elements = for e <- row, do: format_element_with_precision(e, pow, precision) + "[" <> Enum.join(elements, ", ") <> "]" + end + + defp format_element_with_precision(e, pow, precision) do + rounded = round(e * pow) / pow + formatted = :io_lib.format("~.*f", [precision, rounded]) |> List.to_string() + + # Handle negative zero + zero_check = case precision do + 0 -> "0" + _ -> "0." <> String.duplicate("0", precision) + end + + case formatted do + "-" <> rest when rest == zero_check -> zero_check + _ -> formatted + end + end + + # Strassen multiplication helper functions + defp to_quarters(m) do + rows = get_rows(m) + r = div(rows, 2) + data = m.data + + # Extract quarters directly + top_half = Enum.take(data, r) + bottom_half = Enum.drop(data, r) + + # Q0: top-left, Q1: top-right, Q2: bottom-left, Q3: bottom-right + q0_data = for row <- top_half, do: Enum.take(row, r) + q1_data = for row <- top_half, do: Enum.drop(row, r) + q2_data = for row <- bottom_half, do: Enum.take(row, r) + q3_data = for row <- bottom_half, do: Enum.drop(row, r) + + [new(q0_data), new(q1_data), new(q2_data), new(q3_data)] + end + + defp from_quarters([q0, q1, q2, q3]) do + q0_data = q0.data + q1_data = q1.data + q2_data = q2.data + q3_data = q3.data + + # Combine quarters back into full matrix + top_half = Enum.zip(q0_data, q1_data) |> Enum.map(fn {row0, row1} -> row0 ++ row1 end) + bottom_half = Enum.zip(q2_data, q3_data) |> Enum.map(fn {row2, row3} -> row2 ++ row3 end) + + new(top_half ++ bottom_half) + end + + @doc """ + Multiplies two matrices using Strassen's algorithm. + Matrices must be square and have size that is a power of two. + """ + def strassen(m1, m2) do + validate_square_power_of_two(m1) + validate_square_power_of_two(m2) + + unless get_rows(m1) == get_rows(m2) and get_cols(m1) == get_cols(m2) do + raise ArgumentError, "Matrices must be square and of equal size for Strassen multiplication." + end + + strassen_impl(m1, m2) + end + + defp strassen_impl(m1, m2) do + case get_rows(m1) do + 1 -> multiply(m1, m2) + _ -> + [a11, a12, a21, a22] = to_quarters(m1) + [b11, b12, b21, b22] = to_quarters(m2) + + # Calculate the 7 products according to Strassen's algorithm + p1 = strassen_impl(a11, subtract(b12, b22)) + p2 = strassen_impl(add(a11, a12), b22) + p3 = strassen_impl(add(a21, a22), b11) + p4 = strassen_impl(a22, subtract(b21, b11)) + p5 = strassen_impl(add(a11, a22), add(b11, b22)) + p6 = strassen_impl(subtract(a12, a22), add(b21, b22)) + p7 = strassen_impl(subtract(a11, a21), add(b11, b12)) + + # Calculate result quarters + c11 = add(subtract(add(p5, p4), p2), p6) + c12 = add(p1, p2) + c21 = add(p3, p4) + c22 = subtract(subtract(add(p5, p1), p3), p7) + + from_quarters([c11, c12, c21, c22]) + end + end + + @doc """ + Main function for testing the matrix operations. + """ + def main(_args \\ []) do + a_data = [[1.0, 2.0], [3.0, 4.0]] + a = new(a_data) + + b_data = [[5.0, 6.0], [7.0, 8.0]] + b = new(b_data) + + c_data = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]] + c = new(c_data) + + d_data = [[4.0, -3.0, 4.0/3.0, -1.0/4.0], + [-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0], + [3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0], + [-1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0]] + d = new(d_data) + + e_data = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]] + e = new(e_data) + + f_data = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] + f = new(f_data) + + IO.puts("Using 'normal' matrix multiplication:") + IO.puts(" a * b = #{to_matrix_string(multiply(a, b))}") + IO.puts(" c * d = #{to_matrix_string_with_precision(multiply(c, d), 6)}") + IO.puts(" e * f = #{to_matrix_string(multiply(e, f))}") + + IO.puts("\nUsing 'Strassen' matrix multiplication:") + IO.puts(" a * b = #{to_matrix_string(strassen(a, b))}") + IO.puts(" c * d = #{to_matrix_string_with_precision(strassen(c, d), 6)}") + IO.puts(" e * f = #{to_matrix_string(strassen(e, f))}") + end +end + + +Matrix.main() diff --git a/Task/Strassens-algorithm/Erlang/strassens-algorithm.erl b/Task/Strassens-algorithm/Erlang/strassens-algorithm.erl new file mode 100644 index 0000000000..e2c05ae04d --- /dev/null +++ b/Task/Strassens-algorithm/Erlang/strassens-algorithm.erl @@ -0,0 +1,229 @@ +-module(matrix). +-export([new/1, get_rows/1, get_cols/1, add/2, subtract/2, multiply/2, + strassen/2, to_string/1, to_string_with_precision/2, main/1]). + +-record(matrix, {data, rows, cols}). + +% Constructor +new(Data) -> + Rows = length(Data), + Cols = case Rows of + 0 -> 0; + _ -> length(hd(Data)) + end, + #matrix{data = Data, rows = Rows, cols = Cols}. + +% Getters +get_rows(#matrix{rows = Rows}) -> Rows. +get_cols(#matrix{cols = Cols}) -> Cols. + +% Validation functions +validate_dimensions(M1, M2) -> + case get_rows(M1) =:= get_rows(M2) andalso get_cols(M1) =:= get_cols(M2) of + true -> ok; + false -> error("Matrices must have the same dimensions.") + end. + +validate_multiplication(M1, M2) -> + case get_cols(M1) =:= get_rows(M2) of + true -> ok; + false -> error("Cannot multiply these matrices.") + end. + +validate_square_power_of_two(M) -> + Rows = get_rows(M), + Cols = get_cols(M), + case Rows =:= Cols of + false -> error("Matrix must be square."); + true -> + case Rows =:= 0 orelse (Rows band (Rows - 1)) =/= 0 of + true -> error("Size of matrix must be a power of two."); + false -> ok + end + end. + +% Matrix operations +add(M1, M2) -> + validate_dimensions(M1, M2), + Data1 = M1#matrix.data, + Data2 = M2#matrix.data, + ResultData = add_rows(Data1, Data2), + new(ResultData). + +add_rows([], []) -> []; +add_rows([Row1|Rest1], [Row2|Rest2]) -> + [add_elements(Row1, Row2) | add_rows(Rest1, Rest2)]. + +add_elements([], []) -> []; +add_elements([E1|Rest1], [E2|Rest2]) -> + [E1 + E2 | add_elements(Rest1, Rest2)]. + +subtract(M1, M2) -> + validate_dimensions(M1, M2), + Data1 = M1#matrix.data, + Data2 = M2#matrix.data, + ResultData = subtract_rows(Data1, Data2), + new(ResultData). + +subtract_rows([], []) -> []; +subtract_rows([Row1|Rest1], [Row2|Rest2]) -> + [subtract_elements(Row1, Row2) | subtract_rows(Rest1, Rest2)]. + +subtract_elements([], []) -> []; +subtract_elements([E1|Rest1], [E2|Rest2]) -> + [E1 - E2 | subtract_elements(Rest1, Rest2)]. + +multiply(M1, M2) -> + validate_multiplication(M1, M2), + Data1 = M1#matrix.data, + Data2 = M2#matrix.data, + Cols2 = get_cols(M2), + ResultData = multiply_rows(Data1, Data2, Cols2), + new(ResultData). + +multiply_rows([], _Data2, _Cols2) -> []; +multiply_rows([Row|Rest], Data2, Cols2) -> + ResultRow = multiply_row_with_matrix(Row, Data2, Cols2), + [ResultRow | multiply_rows(Rest, Data2, Cols2)]. + +multiply_row_with_matrix(Row, Data2, Cols2) -> + [dot_product(Row, get_column(Data2, J)) || J <- lists:seq(1, Cols2)]. + +get_column(Data, ColIndex) -> + [lists:nth(ColIndex, Row) || Row <- Data]. + +dot_product(List1, List2) -> + lists:sum([E1 * E2 || {E1, E2} <- lists:zip(List1, List2)]). + +% String representation +to_string(M) -> + Data = M#matrix.data, + RowsStr = [format_row(Row) || Row <- Data], + string:join(RowsStr, "\n") ++ "\n". + +format_row(Row) -> + Elements = [format_element(E) || E <- Row], + "[" ++ string:join(Elements, ", ") ++ "]". + +format_element(E) -> + io_lib:format("~w", [E]). + +to_string_with_precision(M, P) -> + Data = M#matrix.data, + Pow = math:pow(10.0, P), + RowsStr = [format_row_with_precision(Row, Pow, P) || Row <- Data], + string:join(RowsStr, "\n") ++ "\n". + +format_row_with_precision(Row, Pow, P) -> + Elements = [format_element_with_precision(E, Pow, P) || E <- Row], + "[" ++ string:join(Elements, ", ") ++ "]". + +format_element_with_precision(E, Pow, P) -> + Rounded = round(E * Pow) / Pow, + Formatted = io_lib:format("~." ++ integer_to_list(P) ++ "f", [Rounded]), + FormattedStr = lists:flatten(Formatted), + % Handle negative zero + ZeroCheck = case P of + 0 -> "0"; + _ -> "0." ++ lists:duplicate(P, $0) + end, + case FormattedStr of + "-" ++ Rest when Rest =:= ZeroCheck -> ZeroCheck; + _ -> FormattedStr + end. + +% Strassen multiplication helper functions +to_quarters(M) -> + Rows = get_rows(M), + R = Rows div 2, + Data = M#matrix.data, + + % Extract quarters directly + TopHalf = lists:sublist(Data, R), + BottomHalf = lists:nthtail(R, Data), + + % Q0: top-left, Q1: top-right, Q2: bottom-left, Q3: bottom-right + Q0_Data = [lists:sublist(Row, R) || Row <- TopHalf], + Q1_Data = [lists:nthtail(R, Row) || Row <- TopHalf], + Q2_Data = [lists:sublist(Row, R) || Row <- BottomHalf], + Q3_Data = [lists:nthtail(R, Row) || Row <- BottomHalf], + + [new(Q0_Data), new(Q1_Data), new(Q2_Data), new(Q3_Data)]. + +from_quarters([Q0, Q1, Q2, Q3]) -> + Q0_Data = Q0#matrix.data, + Q1_Data = Q1#matrix.data, + Q2_Data = Q2#matrix.data, + Q3_Data = Q3#matrix.data, + + % Combine quarters back into full matrix + TopHalf = [Row0 ++ Row1 || {Row0, Row1} <- lists:zip(Q0_Data, Q1_Data)], + BottomHalf = [Row2 ++ Row3 || {Row2, Row3} <- lists:zip(Q2_Data, Q3_Data)], + + new(TopHalf ++ BottomHalf). + +strassen(M1, M2) -> + validate_square_power_of_two(M1), + validate_square_power_of_two(M2), + case get_rows(M1) =:= get_rows(M2) andalso get_cols(M1) =:= get_cols(M2) of + false -> error("Matrices must be square and of equal size for Strassen multiplication."); + true -> strassen_impl(M1, M2) + end. + +strassen_impl(M1, M2) -> + case get_rows(M1) of + 1 -> multiply(M1, M2); + _ -> + [A11, A12, A21, A22] = to_quarters(M1), + [B11, B12, B21, B22] = to_quarters(M2), + + % Calculate the 7 products according to Strassen's algorithm + P1 = strassen_impl(A11, subtract(B12, B22)), + P2 = strassen_impl(add(A11, A12), B22), + P3 = strassen_impl(add(A21, A22), B11), + P4 = strassen_impl(A22, subtract(B21, B11)), + P5 = strassen_impl(add(A11, A22), add(B11, B22)), + P6 = strassen_impl(subtract(A12, A22), add(B21, B22)), + P7 = strassen_impl(subtract(A11, A21), add(B11, B12)), + + % Calculate result quarters + C11 = add(subtract(add(P5, P4), P2), P6), + C12 = add(P1, P2), + C21 = add(P3, P4), + C22 = subtract(subtract(add(P5, P1), P3), P7), + + from_quarters([C11, C12, C21, C22]) + end. + +% Main function for testing +main(_) -> + AData = [[1.0, 2.0], [3.0, 4.0]], + A = new(AData), + + BData = [[5.0, 6.0], [7.0, 8.0]], + B = new(BData), + + CData = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]], + C = new(CData), + + DData = [[4.0, -3.0, 4.0/3.0, -1.0/4.0], + [-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0], + [3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0], + [-1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0]], + D = new(DData), + + EData = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]], + E = new(EData), + + FData = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + F = new(FData), + + io:format("Using 'normal' matrix multiplication:~n"), + io:format(" a * b = ~s~n", [to_string(multiply(A, B))]), + io:format(" c * d = ~s~n", [to_string_with_precision(multiply(C, D), 6)]), + io:format(" e * f = ~s~n", [to_string(multiply(E, F))]), + + io:format("~nUsing 'Strassen' matrix multiplication:~n"), + io:format(" a * b = ~s~n", [to_string(strassen(A, B))]), + io:format(" c * d = ~s~n", [to_string_with_precision(strassen(C, D), 6)]), + io:format(" e * f = ~s~n", [to_string(strassen(E, F))]). diff --git a/Task/Strassens-algorithm/Fortran/strassens-algorithm.f b/Task/Strassens-algorithm/Fortran/strassens-algorithm.f new file mode 100644 index 0000000000..fa0a1b78b3 --- /dev/null +++ b/Task/Strassens-algorithm/Fortran/strassens-algorithm.f @@ -0,0 +1,350 @@ +module matrix_operations + use, intrinsic :: iso_fortran_env, only: real64, int64 + implicit none + + type :: Matrix + real(real64), allocatable :: data(:, :) + integer :: rows = 0 + integer :: cols = 0 + contains + procedure :: getRows + procedure :: getCols + procedure :: validateDimensions + procedure :: validateMultiplication + procedure :: validateSquarePowerOfTwo + procedure :: add_matrices + procedure :: subtract_matrices + procedure :: multiply_matrices + procedure :: strassen + procedure :: toQuarters + procedure :: toStringWithPrecision + generic :: operator(+) => add_matrices + generic :: operator(-) => subtract_matrices + generic :: operator(*) => multiply_matrices + end type Matrix + + interface Matrix + procedure :: create_matrix + end interface Matrix + + type :: MatrixArray4 + type(Matrix) :: matrices(4) + end type MatrixArray4 + +contains + + function create_matrix(input_data) result(mat) + real(real64), intent(in) :: input_data(:, :) + type(Matrix) :: mat + + mat%rows = size(input_data, 1) + mat%cols = size(input_data, 2) + allocate(mat%data(mat%rows, mat%cols)) + mat%data = input_data + end function create_matrix + + function getRows(this) result(rows) + class(Matrix), intent(in) :: this + integer :: rows + rows = this%rows + end function getRows + + function getCols(this) result(cols) + class(Matrix), intent(in) :: this + integer :: cols + cols = this%cols + end function getCols + + subroutine validateDimensions(this, other) + class(Matrix), intent(in) :: this, other + if (this%getRows() /= other%getRows() .or. this%getCols() /= other%getCols()) then + error stop "Matrices must have the same dimensions." + end if + end subroutine validateDimensions + + subroutine validateMultiplication(this, other) + class(Matrix), intent(in) :: this, other + if (this%getCols() /= other%getRows()) then + error stop "Cannot multiply these matrices." + end if + end subroutine validateMultiplication + + subroutine validateSquarePowerOfTwo(this) + class(Matrix), intent(in) :: this + integer :: n + + if (this%getRows() /= this%getCols()) then + error stop "Matrix must be square." + end if + + n = this%getRows() + if (n == 0 .or. iand(n, n-1) /= 0) then + error stop "Size of matrix must be a power of two." + end if + end subroutine validateSquarePowerOfTwo + + function add_matrices(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + integer :: i, j + + call this%validateDimensions(other) + + result_mat%rows = this%rows + result_mat%cols = this%cols + allocate(result_mat%data(result_mat%rows, result_mat%cols)) + + do j = 1, result_mat%cols + do i = 1, result_mat%rows + result_mat%data(i, j) = this%data(i, j) + other%data(i, j) + end do + end do + end function add_matrices + + function subtract_matrices(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + integer :: i, j + + call this%validateDimensions(other) + + result_mat%rows = this%rows + result_mat%cols = this%cols + allocate(result_mat%data(result_mat%rows, result_mat%cols)) + + do j = 1, result_mat%cols + do i = 1, result_mat%rows + result_mat%data(i, j) = this%data(i, j) - other%data(i, j) + end do + end do + end function subtract_matrices + + function multiply_matrices(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + integer :: i, j, k + real(real64) :: sum_val + + call this%validateMultiplication(other) + + result_mat%rows = this%rows + result_mat%cols = other%cols + allocate(result_mat%data(result_mat%rows, result_mat%cols)) + + do i = 1, result_mat%rows + do j = 1, result_mat%cols + sum_val = 0.0_real64 + do k = 1, this%cols + sum_val = sum_val + this%data(i, k) * other%data(k, j) + end do + result_mat%data(i, j) = sum_val + end do + end do + end function multiply_matrices + + function params(r, c) result(p) + integer, intent(in) :: r, c + integer :: p(4, 6) + + p(1, :) = [1, r, 1, c, 1, 1] + p(2, :) = [1, r, c+1, 2*c, 1, c+1] + p(3, :) = [r+1, 2*r, 1, c, r+1, 1] + p(4, :) = [r+1, 2*r, c+1, 2*c, r+1, c+1] + end function params + + function toQuarters(this) result(quarters) + class(Matrix), intent(in) :: this + type(MatrixArray4) :: quarters + integer :: r, c, k, i, j + integer :: p(4, 6) + real(real64), allocatable :: q_data(:, :) + + r = this%getRows() / 2 + c = this%getCols() / 2 + p = params(r, c) + + do k = 1, 4 + allocate(q_data(r, c)) + do j = p(k, 3), p(k, 4) + do i = p(k, 1), p(k, 2) + q_data(i - p(k, 5) + 1, j - p(k, 6) + 1) = this%data(i, j) + end do + end do + quarters%matrices(k) = Matrix(q_data) + deallocate(q_data) + end do + end function toQuarters + + function fromQuarters(q) result(mat) + type(MatrixArray4), intent(in) :: q + type(Matrix) :: mat + integer :: r, c, k, i, j + integer :: p(4, 6) + real(real64), allocatable :: m_data(:, :) + + r = q%matrices(1)%getRows() + c = q%matrices(1)%getCols() + p = params(r, c) + + allocate(m_data(2*r, 2*c)) + m_data = 0.0_real64 + + do k = 1, 4 + do j = p(k, 3), p(k, 4) + do i = p(k, 1), p(k, 2) + m_data(i, j) = q%matrices(k)%data(i - p(k, 5) + 1, j - p(k, 6) + 1) + end do + end do + end do + + mat = Matrix(m_data) + deallocate(m_data) + end function fromQuarters + + function strassen(this, other) result(result_mat) + class(Matrix), intent(in) :: this, other + type(Matrix) :: result_mat + type(MatrixArray4) :: qa, qb, q + type(Matrix) :: p1, p2, p3, p4, p5, p6, p7 + integer :: r, i + + call this%validateSquarePowerOfTwo() + call other%validateSquarePowerOfTwo() + + if (this%getRows() /= other%getRows() .or. this%getCols() /= other%getCols()) then + error stop "Matrices must be square and of equal size for Strassen multiplication." + end if + + if (this%getRows() == 1) then + result_mat = this * other + return + end if + + qa = this%toQuarters() + qb = other%toQuarters() + + p1 = (qa%matrices(2) - qa%matrices(4)) * (qb%matrices(3) + qb%matrices(4)) + p2 = (qa%matrices(1) + qa%matrices(4)) * (qb%matrices(1) + qb%matrices(4)) + p3 = (qa%matrices(1) - qa%matrices(3)) * (qb%matrices(1) + qb%matrices(2)) + p4 = (qa%matrices(1) + qa%matrices(2)) * qb%matrices(4) + p5 = qa%matrices(1) * (qb%matrices(2) - qb%matrices(4)) + p6 = qa%matrices(4) * (qb%matrices(3) - qb%matrices(1)) + p7 = (qa%matrices(3) + qa%matrices(4)) * qb%matrices(1) + + q%matrices(1) = p1 + p2 - p4 + p6 + q%matrices(2) = p4 + p5 + q%matrices(3) = p6 + p7 + q%matrices(4) = p2 - p3 + p5 - p7 + + result_mat = fromQuarters(q) + end function strassen + + function toStringWithPrecision(this, p) result(str) + class(Matrix), intent(in) :: this + integer, intent(in) :: p + character(:), allocatable :: str + character(100) :: buffer + integer :: i, j + real(real64) :: rounded_val + + str = '' + do i = 1, this%rows + str = str // '[' + do j = 1, this%cols + write(buffer, '(F0.' // trim(adjustl(int2str(p))) // ')') this%data(i, j) + str = str // trim(adjustl(buffer)) + if (j < this%cols) then + str = str // ', ' + end if + end do + str = str // ']' // new_line('a') + end do + end function toStringWithPrecision + + function int2str(i) result(str) + integer, intent(in) :: i + character(20) :: str + write(str, *) i + str = adjustl(str) + end function int2str + +end module matrix_operations + +program main + use matrix_operations + implicit none + + type(Matrix) :: a, b, c, d, e, f, result + + ! Initialize matrices (Fortran is column-major, so we need to transpose) + a = Matrix(reshape([1.0_real64, 2.0_real64, 3.0_real64, 4.0_real64], [2, 2])) + b = Matrix(reshape([5.0_real64, 6.0_real64, 7.0_real64, 8.0_real64], [2, 2])) + c = Matrix(reshape([1.0_real64, 1.0_real64, 1.0_real64, 1.0_real64, & + 1.0_real64, 4.0_real64, 9.0_real64, 16.0_real64, & + 1.0_real64, 8.0_real64, 27.0_real64, 64.0_real64, & + 1.0_real64, 16.0_real64, 81.0_real64, 256.0_real64], [4, 4])) + d = Matrix(reshape([4.0_real64, -3.0_real64, 4.0_real64/3.0_real64, -1.0_real64/4.0_real64, & + -13.0_real64/3.0_real64, 19.0_real64/4.0_real64, -7.0_real64/3.0_real64, 11.0_real64/24.0_real64, & + 3.0_real64/2.0_real64, -2.0_real64, 7.0_real64/6.0_real64, -1.0_real64/4.0_real64, & + -1.0_real64/6.0_real64, 1.0_real64/4.0_real64, -1.0_real64/6.0_real64, 1.0_real64/24.0_real64], [4, 4])) + e = Matrix(reshape([1.0_real64, 2.0_real64, 3.0_real64, 4.0_real64, & + 5.0_real64, 6.0_real64, 7.0_real64, 8.0_real64, & + 9.0_real64, 10.0_real64, 11.0_real64, 12.0_real64, & + 13.0_real64, 14.0_real64, 15.0_real64, 16.0_real64], [4, 4])) + f = Matrix(reshape([1.0_real64, 0.0_real64, 0.0_real64, 0.0_real64, & + 0.0_real64, 1.0_real64, 0.0_real64, 0.0_real64, & + 0.0_real64, 0.0_real64, 1.0_real64, 0.0_real64, & + 0.0_real64, 0.0_real64, 0.0_real64, 1.0_real64], [4, 4])) + + print *, "Using 'normal' matrix multiplication:" + + result = a * b + print *, " a * b = " + call print_matrix(result) + print * + + result = c * d + print *, " c * d = " + print *, trim(result%toStringWithPrecision(6)) + print * + + result = e * f + print *, " e * f = " + call print_matrix(result) + print * + + print *, "Using 'Strassen' matrix multiplication:" + + result = a%strassen(b) + print *, " a * b = " + call print_matrix(result) + print * + + result = c%strassen(d) + print *, " c * d = " + print *, trim(result%toStringWithPrecision(6)) + print * + + result = e%strassen(f) + print *, " e * f = " + call print_matrix(result) + +contains + + subroutine print_matrix(mat) + type(Matrix), intent(in) :: mat + integer :: i, j + + do i = 1, mat%rows + write(*, '(A)', advance='no') '[' + do j = 1, mat%cols + write(*, '(G0.6)', advance='no') mat%data(i, j) + if (j < mat%cols) then + write(*, '(A)', advance='no') ', ' + end if + end do + write(*, '(A)') ']' + end do + end subroutine print_matrix + +end program main diff --git a/Task/Strassens-algorithm/Haskell/strassens-algorithm.hs b/Task/Strassens-algorithm/Haskell/strassens-algorithm.hs new file mode 100644 index 0000000000..7b72d56045 --- /dev/null +++ b/Task/Strassens-algorithm/Haskell/strassens-algorithm.hs @@ -0,0 +1,210 @@ +module Main where + +import Data.List (intercalate, transpose) +import Text.Printf (printf, PrintfArg) + +-- Matrix data type +data Matrix a = Matrix { matrixData :: [[a]] + , rows :: Int + , cols :: Int + } deriving (Eq) + +-- Constructor +new :: [[a]] -> Matrix a +new [] = Matrix [] 0 0 +new dat = Matrix dat (length dat) (length $ head dat) + +-- Getters +getRows :: Matrix a -> Int +getRows = rows + +getCols :: Matrix a -> Int +getCols = cols + +-- Validation functions +validateDimensions :: Matrix a -> Matrix a -> Either String () +validateDimensions m1 m2 + | getRows m1 == getRows m2 && getCols m1 == getCols m2 = Right () + | otherwise = Left "Matrices must have the same dimensions." + +validateMultiplication :: Matrix a -> Matrix a -> Either String () +validateMultiplication m1 m2 + | getCols m1 == getRows m2 = Right () + | otherwise = Left "Cannot multiply these matrices." + +validateSquarePowerOfTwo :: Matrix a -> Either String () +validateSquarePowerOfTwo m + | r /= c = Left "Matrix must be square." + | r == 0 || not (isPowerOfTwo r) = Left "Size of matrix must be a power of two." + | otherwise = Right () + where + r = getRows m + c = getCols m + isPowerOfTwo n = n > 0 && n == 2^(floor (logBase 2 (fromIntegral n))) + +-- Matrix operations +matrixAdd :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +matrixAdd m1 m2 = do + validateDimensions m1 m2 + let result = zipWith (zipWith (+)) (matrixData m1) (matrixData m2) + return $ new result + +matrixSubtract :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +matrixSubtract m1 m2 = do + validateDimensions m1 m2 + let result = zipWith (zipWith (-)) (matrixData m1) (matrixData m2) + return $ new result + +matrixMultiply :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +matrixMultiply m1 m2 = do + validateMultiplication m1 m2 + let data1 = matrixData m1 + data2 = matrixData m2 + cols2 = transpose data2 + result = [[sum $ zipWith (*) row col | col <- cols2] | row <- data1] + return $ new result + +-- String representation +matrixToString :: Show a => Matrix a -> String +matrixToString m = unlines $ map formatRow (matrixData m) + where + formatRow row = "[" ++ intercalate ", " (map show row) ++ "]" + +matrixToStringWithPrecision :: (RealFloat a, PrintfArg a) => Matrix a -> Int -> String +matrixToStringWithPrecision m p = unlines $ map (formatRowWithPrecision p) (matrixData m) + where + formatRowWithPrecision precision row = + "[" ++ intercalate ", " (map (formatElementWithPrecision precision) row) ++ "]" + + formatElementWithPrecision precision e = + let pow = 10.0 ^ precision + rounded = fromIntegral (round (e * pow)) / pow + formatted = printf ("%." ++ show precision ++ "f") rounded + zeroCheck = if precision == 0 then "0" else "0." ++ replicate precision '0' + in if formatted == ("-" ++ zeroCheck) then zeroCheck else formatted + +-- Strassen multiplication helper functions +toQuarters :: Matrix a -> [Matrix a] +toQuarters m = [new q0Data, new q1Data, new q2Data, new q3Data] + where + r = getRows m `div` 2 + dat = matrixData m + (topHalf, bottomHalf) = splitAt r dat + + q0Data = map (take r) topHalf + q1Data = map (drop r) topHalf + q2Data = map (take r) bottomHalf + q3Data = map (drop r) bottomHalf + +fromQuarters :: [Matrix a] -> Matrix a +fromQuarters [q0, q1, q2, q3] = new (topHalf ++ bottomHalf) + where + q0Data = matrixData q0 + q1Data = matrixData q1 + q2Data = matrixData q2 + q3Data = matrixData q3 + + topHalf = zipWith (++) q0Data q1Data + bottomHalf = zipWith (++) q2Data q3Data +fromQuarters _ = error "fromQuarters expects exactly 4 matrices" + +-- Safe matrix operations for Strassen (using Either for error handling) +safeAdd :: Num a => Matrix a -> Matrix a -> Matrix a +safeAdd m1 m2 = case matrixAdd m1 m2 of + Right result -> result + Left err -> error err + +safeSubtract :: Num a => Matrix a -> Matrix a -> Matrix a +safeSubtract m1 m2 = case matrixSubtract m1 m2 of + Right result -> result + Left err -> error err + +safeMultiply :: Num a => Matrix a -> Matrix a -> Matrix a +safeMultiply m1 m2 = case matrixMultiply m1 m2 of + Right result -> result + Left err -> error err + +-- Strassen multiplication +strassen :: Num a => Matrix a -> Matrix a -> Either String (Matrix a) +strassen m1 m2 = do + validateSquarePowerOfTwo m1 + validateSquarePowerOfTwo m2 + if getRows m1 /= getRows m2 || getCols m1 /= getCols m2 + then Left "Matrices must be square and of equal size for Strassen multiplication." + else Right $ strassenImpl m1 m2 + +strassenImpl :: Num a => Matrix a -> Matrix a -> Matrix a +strassenImpl m1 m2 + | getRows m1 == 1 = safeMultiply m1 m2 + | otherwise = fromQuarters [c11, c12, c21, c22] + where + [a11, a12, a21, a22] = toQuarters m1 + [b11, b12, b21, b22] = toQuarters m2 + + -- Calculate the 7 products according to Strassen's algorithm + p1 = strassenImpl a11 (safeSubtract b12 b22) + p2 = strassenImpl (safeAdd a11 a12) b22 + p3 = strassenImpl (safeAdd a21 a22) b11 + p4 = strassenImpl a22 (safeSubtract b21 b11) + p5 = strassenImpl (safeAdd a11 a22) (safeAdd b11 b22) + p6 = strassenImpl (safeSubtract a12 a22) (safeAdd b21 b22) + p7 = strassenImpl (safeSubtract a11 a21) (safeAdd b11 b12) + + -- Calculate result quarters + c11 = safeAdd (safeSubtract (safeAdd p5 p4) p2) p6 + c12 = safeAdd p1 p2 + c21 = safeAdd p3 p4 + c22 = safeSubtract (safeSubtract (safeAdd p5 p1) p3) p7 + +-- Main function for testing +main :: IO () +main = do + let aData = [[1.0, 2.0], [3.0, 4.0]] :: [[Double]] + a = new aData + + bData = [[5.0, 6.0], [7.0, 8.0]] :: [[Double]] + b = new bData + + cData = [[1.0, 1.0, 1.0, 1.0], [2.0, 4.0, 8.0, 16.0], + [3.0, 9.0, 27.0, 81.0], [4.0, 16.0, 64.0, 256.0]] :: [[Double]] + c = new cData + + dData = [[4.0, -3.0, 4.0/3.0, -1.0/4.0], + [-13.0/3.0, 19.0/4.0, -7.0/3.0, 11.0/24.0], + [3.0/2.0, -2.0, 7.0/6.0, -1.0/4.0], + [-1.0/6.0, 1.0/4.0, -1.0/6.0, 1.0/24.0]] :: [[Double]] + d = new dData + + eData = [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], + [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]] :: [[Double]] + e = new eData + + fData = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] :: [[Double]] + f = new fData + + putStrLn "Using 'normal' matrix multiplication:" + case matrixMultiply a b of + Right result -> putStrLn $ " a * b = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err + + case matrixMultiply c d of + Right result -> putStrLn $ " c * d = \n" ++ matrixToStringWithPrecision result 6 + Left err -> putStrLn $ "Error: " ++ err + + case matrixMultiply e f of + Right result -> putStrLn $ " e * f = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err + + putStrLn "\nUsing 'Strassen' matrix multiplication:" + case strassen a b of + Right result -> putStrLn $ " a * b = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err + + case strassen c d of + Right result -> putStrLn $ " c * d = \n" ++ matrixToStringWithPrecision result 6 + Left err -> putStrLn $ "Error: " ++ err + + case strassen e f of + Right result -> putStrLn $ " e * f = \n" ++ matrixToString result + Left err -> putStrLn $ "Error: " ++ err diff --git a/Task/Strassens-algorithm/Kotlin/strassens-algorithm.kts b/Task/Strassens-algorithm/Kotlin/strassens-algorithm.kts new file mode 100644 index 0000000000..be2e6d3921 --- /dev/null +++ b/Task/Strassens-algorithm/Kotlin/strassens-algorithm.kts @@ -0,0 +1,281 @@ +class Matrix(val data: List>) { + val rows: Int = data.size + val cols: Int = if (rows > 0) data[0].size else 0 + + // Remove the explicit getter methods since Kotlin generates them automatically + // fun getRows(): Int = rows // Remove this + // fun getCols(): Int = cols // Remove this + + fun validateDimensions(other: Matrix) { + if (rows != other.rows || cols != other.cols) { + throw RuntimeException("Matrices must have the same dimensions.") + } + } + + fun validateMultiplication(other: Matrix) { + if (cols != other.rows) { + throw RuntimeException("Cannot multiply these matrices.") + } + } + + fun validateSquarePowerOfTwo() { + if (rows != cols) { + throw RuntimeException("Matrix must be square.") + } + if (rows == 0 || (rows and (rows - 1)) != 0) { + throw RuntimeException("Size of matrix must be a power of two.") + } + } + + fun add(other: Matrix): Matrix { + validateDimensions(other) + + val resultData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until cols) { + row.add(data[i][j] + other.data[i][j]) + } + resultData.add(row) + } + + return Matrix(resultData) + } + + fun subtract(other: Matrix): Matrix { + validateDimensions(other) + + val resultData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until cols) { + row.add(data[i][j] - other.data[i][j]) + } + resultData.add(row) + } + + return Matrix(resultData) + } + + fun multiply(other: Matrix): Matrix { + validateMultiplication(other) + + val resultData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until other.cols) { + var sum = 0.0 + for (k in 0 until cols) { // Changed from other.rows to cols + sum += data[i][k] * other.data[k][j] + } + row.add(sum) + } + resultData.add(row) + } + + return Matrix(resultData) + } + + override fun toString(): String { + val sb = StringBuilder() + for (row in data) { + sb.append("[") + for (i in row.indices) { + sb.append(row[i]) + if (i < row.size - 1) { + sb.append(", ") + } + } + sb.append("]\n") + } + return sb.toString() + } + + fun toStringWithPrecision(p: Int): String { + val sb = StringBuilder() + val pow = Math.pow(10.0, p.toDouble()) + + for (row in data) { + sb.append("[") + for (i in row.indices) { + val r = Math.round(row[i] * pow) / pow + var formatted = String.format("%.${p}f", r) + + if (formatted == "-0${if (p > 0) "." + "0".repeat(p) else ""}") { + formatted = "0${if (p > 0) "." + "0".repeat(p) else ""}" + } + + sb.append(formatted) + + if (i < row.size - 1) { + sb.append(", ") + } + } + sb.append("]\n") + } + return sb.toString() + } + + companion object { + private fun getParams(r: Int, c: Int): Array { + return arrayOf( + intArrayOf(0, r, 0, c, 0, 0), + intArrayOf(0, r, c, 2 * c, 0, c), + intArrayOf(r, 2 * r, 0, c, r, 0), + intArrayOf(r, 2 * r, c, 2 * c, r, c) + ) + } + + fun fromQuarters(q: Array): Matrix { + val r = q[0].rows + val c = q[0].cols + val p = getParams(r, c) + val rows = r * 2 + val cols = c * 2 + + val mData = mutableListOf>() + for (i in 0 until rows) { + val row = mutableListOf() + for (j in 0 until cols) { + row.add(0.0) + } + mData.add(row) + } + + for (k in 0 until 4) { + for (i in p[k][0] until p[k][1]) { + for (j in p[k][2] until p[k][3]) { + mData[i][j] = q[k].data[i - p[k][4]][j - p[k][5]] + } + } + } + + return Matrix(mData) + } + } + + fun toQuarters(): Array { + val r = rows / 2 + val c = cols / 2 + val p = Companion.getParams(r, c) + val quarters = arrayOfNulls(4) + + for (k in 0 until 4) { + val qData = mutableListOf>() + for (i in 0 until r) { + val row = mutableListOf() + for (j in 0 until c) { + row.add(0.0) + } + qData.add(row) + } + + for (i in p[k][0] until p[k][1]) { + for (j in p[k][2] until p[k][3]) { + qData[i - p[k][4]][j - p[k][5]] = data[i][j] + } + } + quarters[k] = Matrix(qData) + } + + @Suppress("UNCHECKED_CAST") + return quarters as Array + } + + fun strassen(other: Matrix): Matrix { + validateSquarePowerOfTwo() + other.validateSquarePowerOfTwo() + if (rows != other.rows || cols != other.cols) { + throw RuntimeException("Matrices must be square and of equal size for Strassen multiplication.") + } + + if (rows == 1) { + return this.multiply(other) + } + + val qa = toQuarters() + val qb = other.toQuarters() + + val p1 = qa[1].subtract(qa[3]).strassen(qb[2].add(qb[3])) + val p2 = qa[0].add(qa[3]).strassen(qb[0].add(qb[3])) + val p3 = qa[0].subtract(qa[2]).strassen(qb[0].add(qb[1])) + val p4 = qa[0].add(qa[1]).strassen(qb[3]) + val p5 = qa[0].strassen(qb[1].subtract(qb[3])) + val p6 = qa[3].strassen(qb[2].subtract(qb[0])) + val p7 = qa[2].add(qa[3]).strassen(qb[0]) + + val q = arrayOfNulls(4) + + q[0] = p1.add(p2).subtract(p4).add(p6) + q[1] = p4.add(p5) + q[2] = p6.add(p7) + q[3] = p2.subtract(p3).add(p5).subtract(p7) + + @Suppress("UNCHECKED_CAST") + return Companion.fromQuarters(q as Array) + } +} + +fun main() { + val aData = listOf( + listOf(1.0, 2.0), + listOf(3.0, 4.0) + ) + val a = Matrix(aData) + + val bData = listOf( + listOf(5.0, 6.0), + listOf(7.0, 8.0) + ) + val b = Matrix(bData) + + val cData = listOf( + listOf(1.0, 1.0, 1.0, 1.0), + listOf(2.0, 4.0, 8.0, 16.0), + listOf(3.0, 9.0, 27.0, 81.0), + listOf(4.0, 16.0, 64.0, 256.0) + ) + val c = Matrix(cData) + + val dData = listOf( + listOf(4.0, -3.0, 4.0 / 3.0, -1.0 / 4.0), + listOf(-13.0 / 3.0, 19.0 / 4.0, -7.0 / 3.0, 11.0 / 24.0), + listOf(3.0 / 2.0, -2.0, 7.0 / 6.0, -1.0 / 4.0), + listOf(-1.0 / 6.0, 1.0 / 4.0, -1.0 / 6.0, 1.0 / 24.0) + ) + val d = Matrix(dData) + + val eData = listOf( + listOf(1.0, 2.0, 3.0, 4.0), + listOf(5.0, 6.0, 7.0, 8.0), + listOf(9.0, 10.0, 11.0, 12.0), + listOf(13.0, 14.0, 15.0, 16.0) + ) + val e = Matrix(eData) + + val fData = listOf( + listOf(1.0, 0.0, 0.0, 0.0), + listOf(0.0, 1.0, 0.0, 0.0), + listOf(0.0, 0.0, 1.0, 0.0), + listOf(0.0, 0.0, 0.0, 1.0) + ) + val f = Matrix(fData) + + println("Using 'normal' matrix multiplication:") + println(" a * b = ${a.multiply(b)}") + println("\nUsing 'Strassen' matrix multiplication:") + println(" a * b = ${a.strassen(b)}") + + + println("Using 'normal' matrix multiplication:") + println(" c * d = ${c.multiply(d).toStringWithPrecision(6)}") + println("\nUsing 'Strassen' matrix multiplication:") + println(" c * d = ${c.strassen(d).toStringWithPrecision(6)}") + + + println("Using 'normal' matrix multiplication:") + println(" e * f = ${e.multiply(f)}") + println("\nUsing 'Strassen' matrix multiplication:") + println(" e * f = ${e.strassen(f)}") + +} diff --git a/Task/Strassens-algorithm/Lua/strassens-algorithm.lua b/Task/Strassens-algorithm/Lua/strassens-algorithm.lua new file mode 100644 index 0000000000..45b8a3d8cf --- /dev/null +++ b/Task/Strassens-algorithm/Lua/strassens-algorithm.lua @@ -0,0 +1,241 @@ +-- Helper function to create a matrix from nested blocks +local function block_matrix(blocks) + local m = {} + local num_hblocks = #blocks + local num_vblocks = #blocks[1] + + -- Determine dimensions + local block_height = #blocks[1][1] + local block_widths = {} + for j = 1, num_vblocks do + block_widths[j] = #blocks[1][j][1] + end + + -- Build the resulting matrix + for i = 1, block_height * num_hblocks do + m[i] = {} + end + + for h = 1, num_hblocks do + local row_offset = (h - 1) * block_height + for i = 1, block_height do + local col_offset = 0 + for v = 1, num_vblocks do + local block = blocks[h][v] + for j = 1, block_widths[v] do + m[row_offset + i][col_offset + j] = block[i][j] + end + col_offset = col_offset + block_widths[v] + end + end + end + + return m +end + +-- Matrix multiplication (naive) +local function matrix_multiply(a, b) + local rows_a, cols_a = #a, #a[1] + local rows_b, cols_b = #b, #b[1] + + assert(cols_a == rows_b, "Incompatible matrix dimensions for multiplication") + + local result = {} + for i = 1, rows_a do + result[i] = {} + for j = 1, cols_b do + local sum = 0 + for k = 1, cols_a do + sum = sum + a[i][k] * b[k][j] + end + result[i][j] = sum + end + end + + return result +end + +-- Matrix addition +local function matrix_add(a, b) + local rows, cols = #a, #a[1] + assert(rows == #b and cols == #b[1], "Matrices must have the same dimensions") + + local result = {} + for i = 1, rows do + result[i] = {} + for j = 1, cols do + result[i][j] = a[i][j] + b[i][j] + end + end + + return result +end + +-- Matrix subtraction +local function matrix_subtract(a, b) + local rows, cols = #a, #a[1] + assert(rows == #b and cols == #b[1], "Matrices must have the same dimensions") + + local result = {} + for i = 1, rows do + result[i] = {} + for j = 1, cols do + result[i][j] = a[i][j] - b[i][j] + end + end + + return result +end + +-- Get submatrix +local function get_submatrix(m, start_row, end_row, start_col, end_col) + local result = {} + for i = start_row, end_row do + local row = {} + for j = start_col, end_col do + table.insert(row, m[i][j]) + end + table.insert(result, row) + end + return result +end + +-- Strassen's algorithm +local function strassen_multiply(a, b) + local n = #a + local m = #a[1] + + assert(n == m, "Matrix must be square") + assert(n == #b and n == #b[1], "Matrices must have the same dimensions") + + -- Check if size is a power of 2 + local temp = n + while temp > 1 do + assert(temp % 2 == 0, "Matrix dimension must be a power of 2") + temp = temp / 2 + end + + if n == 1 then + return {{a[1][1] * b[1][1]}} + end + + local half = n // 2 + + -- Partition matrices into quadrants + local a11 = get_submatrix(a, 1, half, 1, half) + local a12 = get_submatrix(a, 1, half, half+1, n) + local a21 = get_submatrix(a, half+1, n, 1, half) + local a22 = get_submatrix(a, half+1, n, half+1, n) + + local b11 = get_submatrix(b, 1, half, 1, half) + local b12 = get_submatrix(b, 1, half, half+1, n) + local b21 = get_submatrix(b, half+1, n, 1, half) + local b22 = get_submatrix(b, half+1, n, half+1, n) + + -- Calculate the seven products + local m1 = strassen_multiply(matrix_add(a11, a22), matrix_add(b11, b22)) + local m2 = strassen_multiply(matrix_add(a21, a22), b11) + local m3 = strassen_multiply(a11, matrix_subtract(b12, b22)) + local m4 = strassen_multiply(a22, matrix_subtract(b21, b11)) + local m5 = strassen_multiply(matrix_add(a11, a12), b22) + local m6 = strassen_multiply(matrix_subtract(a21, a11), matrix_add(b11, b12)) + local m7 = strassen_multiply(matrix_subtract(a12, a22), matrix_add(b21, b22)) + + -- Calculate the four quadrants of the result + local c11 = matrix_add(matrix_subtract(matrix_add(m1, m4), m5), m7) + local c12 = matrix_add(m3, m5) + local c21 = matrix_add(m2, m4) + local c22 = matrix_add(matrix_subtract(matrix_add(m1, m3), m2), m6) + + -- Combine quadrants into a single matrix + return block_matrix({{c11, c12}, {c21, c22}}) +end + +-- Round matrix values +local function matrix_round(m, digits) + local result = {} + local mult = 10^digits + + for i = 1, #m do + result[i] = {} + for j = 1, #m[1] do + if digits then + result[i][j] = math.floor(m[i][j] * mult + 0.5) / mult + else + result[i][j] = math.floor(m[i][j] + 0.5) + end + end + end + + return result +end + +-- Print matrix +local function print_matrix(name, m) + print(name .. " = {") + for i = 1, #m do + io.write(" {") + for j = 1, #m[1] do + io.write(m[i][j]) + if j < #m[1] then + io.write(", ") + end + end + print("}") + end + print("}") +end + +-- Examples +local function run_examples() + local a = { + {1, 2}, + {3, 4} + } + + local b = { + {5, 6}, + {7, 8} + } + + local c = { + {1, 1, 1, 1}, + {2, 4, 8, 16}, + {3, 9, 27, 81}, + {4, 16, 64, 256} + } + + local d = { + {4, -3, 4/3, -1/4}, + {-13/3, 19/4, -7/3, 11/24}, + {3/2, -2, 7/6, -1/4}, + {-1/6, 1/4, -1/6, 1/24} + } + + local e = { + {1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16} + } + + local f = { + {1, 0, 0, 0}, + {0, 1, 0, 0}, + {0, 0, 1, 0}, + {0, 0, 0, 1} + } + + print("Naive matrix multiplication:") + print_matrix(" a * b", matrix_multiply(a, b)) + print_matrix(" c * d", matrix_round(matrix_multiply(c, d), 0)) + print_matrix(" e * f", matrix_multiply(e, f)) + + print("\nStrassen's matrix multiplication:") + print_matrix(" a * b", strassen_multiply(a, b)) + print_matrix(" c * d", matrix_round(strassen_multiply(c, d), 0)) + print_matrix(" e * f", strassen_multiply(e, f)) +end + +-- Run examples +run_examples() diff --git a/Task/Strassens-algorithm/Mathematica/strassens-algorithm.math b/Task/Strassens-algorithm/Mathematica/strassens-algorithm.math new file mode 100644 index 0000000000..448d41e864 --- /dev/null +++ b/Task/Strassens-algorithm/Mathematica/strassens-algorithm.math @@ -0,0 +1,116 @@ +(* ::Package:: *) + +(* --------------------------------------------------------------- *) +(* Strassen matrix multiplication – Mathematica version *) +(* --------------------------------------------------------------- *) + +ClearAll[Strassen] + +Strassen[A_?MatrixQ, B_?MatrixQ] := + Module[{n = Length[A], + a11, a12, a21, a22, + b11, b12, b21, b22, + p1, p2, p3, p4, p5, p6, p7, + c11, c12, c21, c22}, + + (* Base case – 1×1 matrix (scalar) *) + If[n == 1, + Return[{{A[[1, 1]]*B[[1, 1]]}}]; + ]; + + (* ---------------------------------------------------------------- *) + (* 2‑level block‐view of the matrices (same as Julia's @views slicing) *) + (* ---------------------------------------------------------------- *) + a11 = A[[;; n/2, ;; n/2]]; + a12 = A[[;; n/2, n/2 + 1 ;;]]; + a21 = A[[n/2 + 1 ;;, ;; n/2]]; + a22 = A[[n/2 + 1 ;;, n/2 + 1 ;;]]; + + b11 = B[[;; n/2, ;; n/2]]; + b12 = B[[;; n/2, n/2 + 1 ;;]]; + b21 = B[[n/2 + 1 ;;, ;; n/2]]; + b22 = B[[n/2 + 1 ;;, n/2 + 1 ;;]]; + + (* --------------------------------------------------------------- *) + (* 7 recursive Strassen products *) + (* --------------------------------------------------------------- *) + p1 = Strassen[a12 - a22, b21 + b22]; + p2 = Strassen[a11 + a22, b11 + b22]; + p3 = Strassen[a11 - a21, b11 + b12]; + p4 = Strassen[a11 + a12, b22]; + p5 = Strassen[a11, b12 - b22]; + p6 = Strassen[a22, b21 - b11]; + p7 = Strassen[a21 + a22, b11]; + + (* --------------------------------------------------------------- *) + (* Assemble the four quadrants of the result *) + (* --------------------------------------------------------------- *) + c11 = p1 + p2 - p4 + p6; + c12 = p4 + p5; + c21 = p6 + p7; + c22 = p2 - p3 + p5 - p7; + + (* Join the four blocks back together *) + Join[ + Join[c11, c12, 2], + Join[c21, c22, 2], + 1 + ] + ]; + + +(* --------------------------------------------------------------- *) +(* Helper that mimics the Julia `intprint` *) +(* --------------------------------------------------------------- *) +ClearAll[intPrint] + +intPrint[title_String, mat_?MatrixQ] := + Module[{rounded}, + (* round each entry to 8 decimal digits, then coerce to an integer + when the rounded value is (numerically) an integer *) + rounded = Round[mat, 10^-8]; + Print[title, " ", rounded ]; + ] + +(* --------------------------------------------------------------- *) +(* Test data *) +(* --------------------------------------------------------------- *) + +varA = {{1, 2}, {3, 4}}; +varB = {{5, 6}, {7, 8}}; + +varC = {{1, 1, 1, 1}, + {2, 4, 8, 16}, + {3, 9, 27, 81}, + {4, 16, 64, 256}}; + +varD = {{4, -3, 4/3, -1/4}, + {-13/3, 19/4, -7/3, 11/24}, + {3/2, -2, 7/6, -1/4}, + {-1/6, 1/4, -1/6, 1/24}}; + +varE = {{1, 2, 3, 4}, + {5, 6, 7, 8}, + {9, 10, 11, 12}, + {13, 14, 15, 16}}; + +varF = IdentityMatrix[4]; + +r = Sqrt[2]/2; +R = {{r, r}, {-r, r}}; + +(* --------------------------------------------------------------- *) +(* Run the examples – compare ordinary (`.`) and Strassen results *) +(* --------------------------------------------------------------- *) + +intPrint["Regular multiply: ", Transpose[varA].Transpose[varB]]; +intPrint["Strassen multiply: ", Strassen[Transpose[varA], Transpose[varB]]]; + +intPrint["Regular multiply: ", varC . varD]; +intPrint["Strassen multiply: ", Strassen[varC, varD]]; + +intPrint["Regular multiply: ", varE . varF]; +intPrint["Strassen multiply: ", Strassen[varE, varF]]; + +intPrint["Regular multiply: ", R . R]; +intPrint["Strassen multiply: ", Strassen[R, R]]; diff --git a/Task/Strassens-algorithm/OCaml/strassens-algorithm.ml b/Task/Strassens-algorithm/OCaml/strassens-algorithm.ml new file mode 100644 index 0000000000..e818b7b857 --- /dev/null +++ b/Task/Strassens-algorithm/OCaml/strassens-algorithm.ml @@ -0,0 +1,214 @@ +(* Matrix multiplication using Strassen's algorithm in OCaml *) + +type matrix = float array array + +type shape = { + rows : int; + cols : int; +} + +(* Get the shape of a matrix *) +let shape m = + let rows = Array.length m in + let cols = if rows = 0 then 0 else Array.length m.(0) in + { rows; cols } + +(* Create a matrix from a list of lists *) +let matrix_of_lists lists = + Array.of_list (List.map Array.of_list lists) + +(* Convert matrix to list of lists for printing *) +let lists_of_matrix m = + Array.to_list (Array.map Array.to_list m) + +(* Matrix addition *) +let add_matrix a b = + let { rows; cols } = shape a in + let { rows = b_rows; cols = b_cols } = shape b in + assert (rows = b_rows && cols = b_cols); + Array.init rows (fun i -> + Array.init cols (fun j -> a.(i).(j) +. b.(i).(j))) + +(* Matrix subtraction *) +let sub_matrix a b = + let { rows; cols } = shape a in + let { rows = b_rows; cols = b_cols } = shape b in + assert (rows = b_rows && cols = b_cols); + Array.init rows (fun i -> + Array.init cols (fun j -> a.(i).(j) -. b.(i).(j))) + +(* Naive matrix multiplication *) +let dot_product a b = + let a_shape = shape a in + let b_shape = shape b in + assert (a_shape.cols = b_shape.rows); + + Array.init a_shape.rows (fun i -> + Array.init b_shape.cols (fun j -> + let sum = ref 0.0 in + for k = 0 to a_shape.cols - 1 do + sum := !sum +. (a.(i).(k) *. b.(k).(j)) + done; + !sum)) + +(* Extract a submatrix *) +let submatrix m start_row end_row start_col end_col = + Array.init (end_row - start_row) (fun i -> + Array.init (end_col - start_col) (fun j -> + m.(start_row + i).(start_col + j))) + +(* Combine four submatrices into a single matrix *) +let block_matrix c11 c12 c21 c22 = + let p = Array.length c11 in + let result = Array.make_matrix (2 * p) (2 * p) 0.0 in + + (* Copy c11 to top-left *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(i).(j) <- c11.(i).(j) + done + done; + + (* Copy c12 to top-right *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(i).(p + j) <- c12.(i).(j) + done + done; + + (* Copy c21 to bottom-left *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(p + i).(j) <- c21.(i).(j) + done + done; + + (* Copy c22 to bottom-right *) + for i = 0 to p - 1 do + for j = 0 to p - 1 do + result.(p + i).(p + j) <- c22.(i).(j) + done + done; + + result + +(* Check if a number is a power of 2 *) +let is_power_of_2 n = + n > 0 && (n land (n - 1)) = 0 + +(* Strassen's matrix multiplication *) +let rec strassen a b = + let a_shape = shape a in + let b_shape = shape b in + let rows = a_shape.rows in + let cols = a_shape.cols in + + assert (rows = cols); (* matrices must be square *) + assert (a_shape.rows = b_shape.rows && a_shape.cols = b_shape.cols); (* same shape *) + assert (is_power_of_2 rows); (* size must be power of 2 *) + + if rows = 1 then + dot_product a b + else + let p = rows / 2 in + + (* Partition matrix a *) + let a11 = submatrix a 0 p 0 p in + let a12 = submatrix a 0 p p rows in + let a21 = submatrix a p rows 0 p in + let a22 = submatrix a p rows p rows in + + (* Partition matrix b *) + let b11 = submatrix b 0 p 0 p in + let b12 = submatrix b 0 p p rows in + let b21 = submatrix b p rows 0 p in + let b22 = submatrix b p rows p rows in + + (* Compute the 7 products *) + let m1 = strassen (add_matrix a11 a22) (add_matrix b11 b22) in + let m2 = strassen (add_matrix a21 a22) b11 in + let m3 = strassen a11 (sub_matrix b12 b22) in + let m4 = strassen a22 (sub_matrix b21 b11) in + let m5 = strassen (add_matrix a11 a12) b22 in + let m6 = strassen (sub_matrix a21 a11) (add_matrix b11 b12) in + let m7 = strassen (sub_matrix a12 a22) (add_matrix b21 b22) in + + (* Compute the result submatrices *) + let c11 = add_matrix (sub_matrix (add_matrix m1 m4) m5) m7 in + let c12 = add_matrix m3 m5 in + let c21 = add_matrix m2 m4 in + let c22 = add_matrix (sub_matrix (add_matrix m1 m3) m2) m6 in + + block_matrix c11 c12 c21 c22 + +(* Round matrix elements to specified decimal places *) +let round_matrix ?(ndigits=0) m = + let factor = 10.0 ** (float_of_int ndigits) in + Array.map (Array.map (fun x -> + Float.round (x *. factor) /. factor)) m + +(* Pretty print a matrix *) +let print_matrix m = + let lists = lists_of_matrix m in + print_string "["; + List.iteri (fun i row -> + if i > 0 then print_string "; "; + print_string "["; + List.iteri (fun j x -> + if j > 0 then print_string "; "; + Printf.printf "%.6g" x) row; + print_string "]") lists; + print_endline "]" + +(* Example usage *) +let examples () = + let a = matrix_of_lists [ + [1.0; 2.0]; + [3.0; 4.0] + ] in + + let b = matrix_of_lists [ + [5.0; 6.0]; + [7.0; 8.0] + ] in + + let c = matrix_of_lists [ + [1.0; 1.0; 1.0; 1.0]; + [2.0; 4.0; 8.0; 16.0]; + [3.0; 9.0; 27.0; 81.0]; + [4.0; 16.0; 64.0; 256.0] + ] in + + let d = matrix_of_lists [ + [4.0; -3.0; 4.0/.3.0; -1.0/.4.0]; + [-13.0/.3.0; 19.0/.4.0; -7.0/.3.0; 11.0/.24.0]; + [3.0/.2.0; -2.0; 7.0/.6.0; -1.0/.4.0]; + [-1.0/.6.0; 1.0/.4.0; -1.0/.6.0; 1.0/.24.0] + ] in + + let e = matrix_of_lists [ + [1.0; 2.0; 3.0; 4.0]; + [5.0; 6.0; 7.0; 8.0]; + [9.0; 10.0; 11.0; 12.0]; + [13.0; 14.0; 15.0; 16.0] + ] in + + let f = matrix_of_lists [ + [1.0; 0.0; 0.0; 0.0]; + [0.0; 1.0; 0.0; 0.0]; + [0.0; 0.0; 1.0; 0.0]; + [0.0; 0.0; 0.0; 1.0] + ] in + + print_endline "Naive matrix multiplication:"; + print_string " a * b = "; print_matrix (dot_product a b); + print_string " c * d = "; print_matrix (round_matrix (dot_product c d)); + print_string " e * f = "; print_matrix (dot_product e f); + + print_endline "\nStrassen's matrix multiplication:"; + print_string " a * b = "; print_matrix (strassen a b); + print_string " c * d = "; print_matrix (round_matrix (strassen c d)); + print_string " e * f = "; print_matrix (strassen e f) + +(* Run examples when executed *) +let () = examples () diff --git a/Task/Strassens-algorithm/Perl/strassens-algorithm.pl b/Task/Strassens-algorithm/Perl/strassens-algorithm.pl new file mode 100644 index 0000000000..9b96cf4bb8 --- /dev/null +++ b/Task/Strassens-algorithm/Perl/strassens-algorithm.pl @@ -0,0 +1,256 @@ +#!/usr/bin/perl +use strict; +use warnings; +use List::Util qw(sum); + +# Matrix class implemented as array reference +package Matrix; + +# Constructor +sub new { + my ($class, $data) = @_; + my $self = defined $data ? $data : []; + bless $self, $class; + return $self; +} + +# Create matrix from nested blocks +sub block { + my ($class, $blocks) = @_; + my @result; + + # Get dimensions + my $num_rows = 0; + for my $hblock (@$blocks) { + $num_rows += @{$hblock->[0]}; + } + + # Process each horizontal block + my $row_offset = 0; + for my $hblock (@$blocks) { + my $block_height = @{$hblock->[0]}; + # Zip and concatenate rows + for my $i (0..$block_height-1) { + my @new_row; + for my $matrix (@$hblock) { + push @new_row, @{$matrix->[$i]}; + } + $result[$row_offset + $i] = \@new_row; + } + $row_offset += $block_height; + } + + return Matrix->new(\@result); +} + +# Matrix multiplication (naive) +sub dot { + my ($self, $b) = @_; + my ($rows_a, $cols_a) = $self->shape(); + my ($rows_b, $cols_b) = $b->shape(); + + die "Matrix dimensions don't match for multiplication" unless $cols_a == $rows_b; + + my @result; + for my $i (0..$rows_a-1) { + my @row; + for my $j (0..$cols_b-1) { + my $sum = 0; + for my $k (0..$cols_a-1) { + $sum += $self->[$i][$k] * $b->[$k][$j]; + } + push @row, $sum; + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Overload multiplication operator +use overload '*' => \˙ + +# Matrix addition +sub add { + my ($self, $b) = @_; + my ($rows, $cols) = $self->shape(); + my ($b_rows, $b_cols) = $b->shape(); + + die "Matrix dimensions don't match for addition" unless $rows == $b_rows && $cols == $b_cols; + + my @result; + for my $i (0..$rows-1) { + my @row; + for my $j (0..$cols-1) { + push @row, $self->[$i][$j] + $b->[$i][$j]; + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Matrix subtraction +sub subtract { + my ($self, $b) = @_; + my ($rows, $cols) = $self->shape(); + my ($b_rows, $b_cols) = $b->shape(); + + die "Matrix dimensions don't match for subtraction" unless $rows == $b_rows && $cols == $b_cols; + + my @result; + for my $i (0..$rows-1) { + my @row; + for my $j (0..$cols-1) { + push @row, $self->[$i][$j] - $b->[$i][$j]; + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Overload operators +use overload '+' => \&add; +use overload '-' => \&subtract; + +# Strassen's algorithm +sub strassen { + my ($self, $b) = @_; + my ($rows, $cols) = $self->shape(); + my ($b_rows, $b_cols) = $b->shape(); + + die "Matrices must be square" unless $rows == $cols && $b_rows == $b_cols; + die "Matrices must be the same shape" unless $rows == $b_rows; + die "Shape must be a power of 2" unless $rows > 0 && ($rows & ($rows - 1)) == 0; + + if ($rows == 1) { + return $self->dot($b); + } + + my $p = $rows / 2; + + # Partition matrices + my $a11 = Matrix->new([map { [ @{$self->[$_]}[0..$p-1] ] } 0..$p-1]); + my $a12 = Matrix->new([map { [ @{$self->[$_]}[$p..$rows-1] ] } 0..$p-1]); + my $a21 = Matrix->new([map { [ @{$self->[$_]}[0..$p-1] ] } $p..$rows-1]); + my $a22 = Matrix->new([map { [ @{$self->[$_]}[$p..$rows-1] ] } $p..$rows-1]); + + my $b11 = Matrix->new([map { [ @{$b->[$_]}[0..$p-1] ] } 0..$p-1]); + my $b12 = Matrix->new([map { [ @{$b->[$_]}[$p..$b_cols-1] ] } 0..$p-1]); + my $b21 = Matrix->new([map { [ @{$b->[$_]}[0..$p-1] ] } $p..$b_rows-1]); + my $b22 = Matrix->new([map { [ @{$b->[$_]}[$p..$b_cols-1] ] } $p..$b_rows-1]); + + # Calculate M1..M7 + my $m1 = ($a11 + $a22)->strassen($b11 + $b22); + my $m2 = ($a21 + $a22)->strassen($b11); + my $m3 = $a11->strassen($b12 - $b22); + my $m4 = $a22->strassen($b21 - $b11); + my $m5 = ($a11 + $a12)->strassen($b22); + my $m6 = ($a21 - $a11)->strassen($b11 + $b12); + my $m7 = ($a12 - $a22)->strassen($b21 + $b22); + + # Calculate C11..C22 + my $c11 = $m1 + $m4 - $m5 + $m7; + my $c12 = $m3 + $m5; + my $c21 = $m2 + $m4; + my $c22 = $m1 - $m2 + $m3 + $m6; + + return Matrix->block([[$c11, $c12], [$c21, $c22]]); +} + +# Round elements +sub round_matrix { + my ($self, $ndigits) = @_; + $ndigits = undef unless defined $ndigits; + + my @result; + for my $i (0..$#{$self}) { + my @row; + for my $j (0..$#{$self->[$i]}) { + my $val = $self->[$i][$j]; + if (defined $ndigits) { + push @row, sprintf("%.${ndigits}f", $val); + } else { + push @row, int($val + ($val >= 0 ? 0.5 : -0.5)); + } + } + push @result, \@row; + } + + return Matrix->new(\@result); +} + +# Get matrix shape +sub shape { + my ($self) = @_; + return (0, 0) unless @$self; + return (scalar @$self, scalar @{$self->[0]}); +} + +# String representation +sub stringify { + my ($self) = @_; + my @rows; + for my $row (@$self) { + push @rows, '[' . join(', ', @$row) . ']'; + } + return '[' . join(', ', @rows) . ']'; +} + +use overload '""' => \&stringify; + +# Examples +package main; + +sub examples { + my $a = Matrix->new([ + [1, 2], + [3, 4] + ]); + + my $b = Matrix->new([ + [5, 6], + [7, 8] + ]); + + my $c = Matrix->new([ + [1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256] + ]); + + my $d = Matrix->new([ + [4, -3, 4/3, -1/4], + [-13/3, 19/4, -7/3, 11/24], + [3/2, -2, 7/6, -1/4], + [-1/6, 1/4, -1/6, 1/24] + ]); + + my $e = Matrix->new([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16] + ]); + + my $f = Matrix->new([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]); + + print "Naive matrix multiplication:\n"; + print " a * b = " . ($a * $b) . "\n"; + print " c * d = " . $c->round_matrix(0) . "\n"; + print " e * f = " . ($e * $f) . "\n"; + + print "Strassen's matrix multiplication:\n"; + print " a * b = " . $a->strassen($b) . "\n"; + print " c * d = " . $c->strassen($d)->round_matrix(0) . "\n"; + print " e * f = " . $e->strassen($f) . "\n"; +} + +examples() if __FILE__ eq $0; diff --git a/Task/Strassens-algorithm/Pluto/strassens-algorithm.pluto b/Task/Strassens-algorithm/Pluto/strassens-algorithm.pluto new file mode 100644 index 0000000000..d7156e6c1f --- /dev/null +++ b/Task/Strassens-algorithm/Pluto/strassens-algorithm.pluto @@ -0,0 +1,70 @@ +require "matrix" +require "table2" +local fmt = require "fmt" + +local function strassen(a, b) + assert(a:issquare() and a:samesize(b), "matrices must be square and of equal size") + local n = a:numrows() + assert(n & (n - 1) == 0, "size of matrices must be a power of two") + if n == 1 then return a:matmul(b) end + local h = n // 2 + + local a11 = a:submatrix(1, h, 1, h) + local a12 = a:submatrix(1, h, h + 1, n) + local a21 = a:submatrix(h + 1, n, 1, h) + local a22 = a:submatrix(h + 1, n, h + 1, n) + + local b11 = b:submatrix(1, h, 1, h) + local b12 = b:submatrix(1, h, h + 1, n) + local b21 = b:submatrix(h + 1, n, 1, h) + local b22 = b:submatrix(h + 1, n, h + 1, n) + + local m1 = strassen(a11 + a22, b11 + b22) + local m2 = strassen(a21 + a22, b11 ) + local m3 = strassen(a11, b12 - b22) + local m4 = strassen(a22, b21 - b11) + local m5 = strassen(a11 + a12, b22 ) + local m6 = strassen(a21 - a11, b11 + b12) + local m7 = strassen(a12 - a22, b21 + b22) + + local c11 = m1 + m4 - m5 + m7 + local c12 = m3 + m5 + local c21 = m2 + m4 + local c22 = m1 - m2 + m3 + m6 + + local c = {} + for i = 1, n do c[i] = table.rep(n, 0) end + for i = 1, h do + for j = 1, h do + c[i][j] = c11:get(i, j) + c[i][j + h] = c12:get(i, j) + c[i + h][j] = c21:get(i, j) + c[i + h][j + h] = c22:get(i, j) + end + end + return matrix.from(c) +end + +-- Round numbers which differ from an integer by less than 'tol' to that integer. +local function round(n, tol = 1e-12) + if math.abs(n - math.round(n)) < tol then return math.round(n) end + return n +end + +local a = matrix.from({ {1, 2}, {3, 4} }) +local b = matrix.from({ {5, 6}, {7, 8} }) +local c = matrix.from({ {1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256} }) +local d = matrix.from({ {4, -3, 4/3, -1/4}, {-13/3, 19/4, -7/3, 11/24}, + {3/2, -2, 7/6, -1/4}, {-1/6, 1/4, -1/6, 1/24} }) +local e = matrix.from({ {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }) +local f = matrix.from({ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1} }) + +print("Using 'normal' matrix multiplication:") +fmt.print(" a x b = %s", fmt.swrite(a:matmul(b):toarray())) +fmt.print(" c x d = %s", fmt.swrite(c:matmul(d):map(round):toarray())) +fmt.print(" e x f = %s", fmt.swrite(e:matmul(f):toarray())) + +print("\nUsing 'Strassen' matrix multiplication:") +fmt.print(" a x b = %s", fmt.swrite(strassen(a, b):toarray())) +fmt.print(" c x d = %s", fmt.swrite(strassen(c, d):map(round):toarray())) +fmt.print(" e x f = %s", fmt.swrite(strassen(e, f):toarray())) diff --git a/Task/Strassens-algorithm/PowerShell/strassens-algorithm.ps1 b/Task/Strassens-algorithm/PowerShell/strassens-algorithm.ps1 new file mode 100644 index 0000000000..12d397321b --- /dev/null +++ b/Task/Strassens-algorithm/PowerShell/strassens-algorithm.ps1 @@ -0,0 +1,288 @@ +# Matrix class implemented as array reference +class Matrix { + [object[]]$data + + # Constructor + Matrix([object[]]$data) { + $this.data = $data + } + + # Create matrix from nested blocks + static [Matrix] Block([Matrix[][]]$blocks) { + $result = @() + + # Get dimensions + $num_rows = 0 + foreach ($hblock in $blocks) { + $num_rows += $hblock[0].data.Count + } + + # Process each horizontal block + $row_offset = 0 + foreach ($hblock in $blocks) { + $block_height = $hblock[0].data.Count + # Zip and concatenate rows + for ($i = 0; $i -lt $block_height; $i++) { + $new_row = @() + foreach ($matrix in $hblock) { + $new_row += $matrix.data[$i] + } + if ($row_offset + $i -ge $result.Count) { + $result += , @() + } + $result[$row_offset + $i] = $new_row + } + $row_offset += $block_height + } + + return [Matrix]::new($result) + } + + # Matrix multiplication (naive) + [Matrix] Dot([Matrix]$b) { + $rows_a = $this.data.Count + $cols_a = if ($rows_a -gt 0) { $this.data[0].Count } else { 0 } + $rows_b = $b.data.Count + $cols_b = if ($rows_b -gt 0) { $b.data[0].Count } else { 0 } + + if ($cols_a -ne $rows_b) { + throw "Matrix dimensions don't match for multiplication" + } + + $result = @() + for ($i = 0; $i -lt $rows_a; $i++) { + $row = @() + for ($j = 0; $j -lt $cols_b; $j++) { + $sum = 0 + for ($k = 0; $k -lt $cols_a; $k++) { + $sum += $this.data[$i][$k] * $b.data[$k][$j] + } + $row += $sum + } + $result += , $row + } + + return [Matrix]::new($result) + } + + # Matrix addition + [Matrix] Add([Matrix]$b) { + $rows = $this.data.Count + $cols = if ($rows -gt 0) { $this.data[0].Count } else { 0 } + $b_rows = $b.data.Count + $b_cols = if ($b_rows -gt 0) { $b.data[0].Count } else { 0 } + + if ($rows -ne $b_rows -or $cols -ne $b_cols) { + throw "Matrix dimensions don't match for addition" + } + + $result = @() + for ($i = 0; $i -lt $rows; $i++) { + $row = @() + for ($j = 0; $j -lt $cols; $j++) { + $row += $this.data[$i][$j] + $b.data[$i][$j] + } + $result += , $row + } + + return [Matrix]::new($result) + } + + # Matrix subtraction + [Matrix] Subtract([Matrix]$b) { + $rows = $this.data.Count + $cols = if ($rows -gt 0) { $this.data[0].Count } else { 0 } + $b_rows = $b.data.Count + $b_cols = if ($b_rows -gt 0) { $b.data[0].Count } else { 0 } + + if ($rows -ne $b_rows -or $cols -ne $b_cols) { + throw "Matrix dimensions don't match for subtraction" + } + + $result = @() + for ($i = 0; $i -lt $rows; $i++) { + $row = @() + for ($j = 0; $j -lt $cols; $j++) { + $row += $this.data[$i][$j] - $b.data[$i][$j] + } + $result += , $row + } + + return [Matrix]::new($result) + } + + # Strassen's algorithm + [Matrix] Strassen([Matrix]$b) { + $rows = $this.data.Count + $cols = if ($rows -gt 0) { $this.data[0].Count } else { 0 } + $b_rows = $b.data.Count + $b_cols = if ($b_rows -gt 0) { $b.data[0].Count } else { 0 } + + if ($rows -ne $cols -or $b_rows -ne $b_cols) { + throw "Matrices must be square" + } + if ($rows -ne $b_rows) { + throw "Matrices must be the same shape" + } + if ($rows -le 0 -or ($rows -band ($rows - 1)) -ne 0) { + throw "Shape must be a power of 2" + } + + if ($rows -eq 1) { + return $this.Dot($b) + } + + $p = [Math]::Floor($rows / 2) + + # Partition matrices + $a11_data = @() + $a12_data = @() + $a21_data = @() + $a22_data = @() + for ($i = 0; $i -lt $p; $i++) { + $a11_data += , @($this.data[$i][0..($p-1)]) + $a12_data += , @($this.data[$i][$p..($rows-1)]) + } + for ($i = $p; $i -lt $rows; $i++) { + $a21_data += , @($this.data[$i][0..($p-1)]) + $a22_data += , @($this.data[$i][$p..($rows-1)]) + } + + $b11_data = @() + $b12_data = @() + $b21_data = @() + $b22_data = @() + for ($i = 0; $i -lt $p; $i++) { + $b11_data += , @($b.data[$i][0..($p-1)]) + $b12_data += , @($b.data[$i][$p..($b_cols-1)]) + } + for ($i = $p; $i -lt $b_rows; $i++) { + $b21_data += , @($b.data[$i][0..($p-1)]) + $b22_data += , @($b.data[$i][$p..($b_rows-1)]) + } + + $a11 = [Matrix]::new($a11_data) + $a12 = [Matrix]::new($a12_data) + $a21 = [Matrix]::new($a21_data) + $a22 = [Matrix]::new($a22_data) + $b11 = [Matrix]::new($b11_data) + $b12 = [Matrix]::new($b12_data) + $b21 = [Matrix]::new($b21_data) + $b22 = [Matrix]::new($b22_data) + + # Calculate M1..M7 + $m1 = ($a11.Add($a22)).Strassen($b11.Add($b22)) + $m2 = ($a21.Add($a22)).Strassen($b11) + $m3 = $a11.Strassen($b12.Subtract($b22)) + $m4 = $a22.Strassen($b21.Subtract($b11)) + $m5 = ($a11.Add($a12)).Strassen($b22) + $m6 = ($a21.Subtract($a11)).Strassen($b11.Add($b12)) + $m7 = ($a12.Subtract($a22)).Strassen($b21.Add($b22)) + + # Calculate C11..C22 + $c11 = $m1.Add($m4).Subtract($m5).Add($m7) + $c12 = $m3.Add($m5) + $c21 = $m2.Add($m4) + $c22 = $m1.Subtract($m2).Add($m3).Add($m6) + + return [Matrix]::Block(@(@($c11, $c12), @($c21, $c22))) + } + + # Round elements + [Matrix] RoundMatrix([int]$ndigits) { + $result = @() + for ($i = 0; $i -lt $this.data.Count; $i++) { + $row = @() + for ($j = 0; $j -lt $this.data[$i].Count; $j++) { + $val = $this.data[$i][$j] + if ($ndigits -ne $null) { + $rounded = [Math]::Round($val, $ndigits) + $row += $rounded + } else { + $rounded = [Math]::Round($val) + $row += $rounded + } + } + $result += , $row + } + + return [Matrix]::new($result) + } + + [Matrix] RoundMatrix() { + return $this.RoundMatrix($null) + } + + # Get matrix shape + [object[]] Shape() { + if ($this.data.Count -eq 0) { + return @(0, 0) + } + return @($this.data.Count, $this.data[0].Count) + } + + # String representation + [string] ToString() { + $rows = @() + foreach ($row in $this.data) { + $rows += "[" + ($row -join ", ") + "]" + } + return "[" + ($rows -join ", ") + "]" + } +} + +# Operator overloading for PowerShell (using methods instead) +function Multiply-Matrix([Matrix]$a, [Matrix]$b) { + return $a.Dot($b) +} + +function Add-Matrix([Matrix]$a, [Matrix]$b) { + return $a.Add($b) +} + +function Subtract-Matrix([Matrix]$a, [Matrix]$b) { + return $a.Subtract($b) +} + +# Examples +function Examples() { + $a = [Matrix]::new(@(@(1, 2), @(3, 4))) + $b = [Matrix]::new(@(@(5, 6), @(7, 8))) + $c = [Matrix]::new(@( + @(1, 1, 1, 1), + @(2, 4, 8, 16), + @(3, 9, 27, 81), + @(4, 16, 64, 256) + )) + $d = [Matrix]::new(@( + @(4, -3, (4/3), (-1/4)), + @((-13/3), (19/4), (-7/3), (11/24)), + @((3/2), -2, (7/6), (-1/4)), + @((-1/6), (1/4), (-1/6), (1/24)) + )) + $e = [Matrix]::new(@( + @(1, 2, 3, 4), + @(5, 6, 7, 8), + @(9, 10, 11, 12), + @(13, 14, 15, 16) + )) + $f = [Matrix]::new(@( + @(1, 0, 0, 0), + @(0, 1, 0, 0), + @(0, 0, 1, 0), + @(0, 0, 0, 1) + )) + + Write-Host "Naive matrix multiplication:" + Write-Host " a * b = $($a.Dot($b))" + Write-Host " c * d = $($c.Dot($d).RoundMatrix(0))" + Write-Host " e * f = $($e.Dot($f))" + + Write-Host "Strassen's matrix multiplication:" + Write-Host " a * b = $($a.Strassen($b))" + Write-Host " c * d = $($c.Strassen($d).RoundMatrix(0))" + Write-Host " e * f = $($e.Strassen($f))" +} + +# Run examples if script is executed directly +Examples diff --git a/Task/Strassens-algorithm/R/strassens-algorithm.r b/Task/Strassens-algorithm/R/strassens-algorithm.r new file mode 100644 index 0000000000..c02e64c39b --- /dev/null +++ b/Task/Strassens-algorithm/R/strassens-algorithm.r @@ -0,0 +1,179 @@ +# --------------------------------------------------------------- +# Strassen matrix multiplication – R version (Corrected) +# --------------------------------------------------------------- + +# Helper function to pad matrix to next power of 2 +pad_to_power_of_2 <- function(mat) { + n <- nrow(mat) + m <- ncol(mat) + max_dim <- max(n, m) + new_dim <- 2^ceiling(log2(max_dim)) + + if (new_dim == n && new_dim == m) { + return(mat) + } + + padded <- matrix(0, nrow = new_dim, ncol = new_dim) + padded[1:n, 1:m] <- mat + return(padded) +} + +# Helper to split a matrix into quadrants +split_matrix <- function(X) { + n <- nrow(X) + mid <- n %/% 2 + + list( + X11 = X[1:mid, 1:mid, drop = FALSE], + X12 = X[1:mid, (mid + 1):n, drop = FALSE], + X21 = X[(mid + 1):n, 1:mid, drop = FALSE], + X22 = X[(mid + 1):n, (mid + 1):n, drop = FALSE] + ) +} + +# Join four submatrices into one matrix +join_matrices <- function(C11, C12, C21, C22) { + top <- cbind(C11, C12) + bottom <- cbind(C21, C22) + rbind(top, bottom) +} + +# Strassen Matrix Multiplication +strassen <- function(A, B) { + # Check if matrices are conformable for multiplication + if (ncol(A) != nrow(B)) { + stop("Matrices cannot be multiplied: incompatible dimensions") + } + + # Pad matrices to make them square and powers of 2 + orig_rows <- nrow(A) + orig_cols <- ncol(B) + + max_dim <- max(nrow(A), ncol(A), nrow(B), ncol(B)) + padded_dim <- 2^ceiling(log2(max_dim)) + + if (nrow(A) != padded_dim || ncol(A) != padded_dim) { + A_padded <- matrix(0, nrow = padded_dim, ncol = padded_dim) + A_padded[1:nrow(A), 1:ncol(A)] <- A + A <- A_padded + } + + if (nrow(B) != padded_dim || ncol(B) != padded_dim) { + B_padded <- matrix(0, nrow = padded_dim, ncol = padded_dim) + B_padded[1:nrow(B), 1:ncol(B)] <- B + B <- B_padded + } + + # Recursive helper function + strassen_recursive <- function(X, Y) { + n <- nrow(X) + + # Base case: 1x1 matrix + if (n == 1) { + return(matrix(X[1, 1] * Y[1, 1], nrow = 1, ncol = 1)) + } + + # Split matrices into quadrants + X_parts <- split_matrix(X) + Y_parts <- split_matrix(Y) + + x11 <- X_parts$X11 + x12 <- X_parts$X12 + x21 <- X_parts$X21 + x22 <- X_parts$X22 + + y11 <- Y_parts$X11 + y12 <- Y_parts$X12 + y21 <- Y_parts$X21 + y22 <- Y_parts$X22 + + # Compute the seven products recursively + p1 <- strassen_recursive(x12 - x22, y21 + y22) + p2 <- strassen_recursive(x11 + x22, y11 + y22) + p3 <- strassen_recursive(x11 - x21, y11 + y12) + p4 <- strassen_recursive(x11 + x12, y22) + p5 <- strassen_recursive(x11, y12 - y22) + p6 <- strassen_recursive(x22, y21 - y11) + p7 <- strassen_recursive(x21 + x22, y11) + + # Combine results into quadrants + c11 <- p1 + p2 - p4 + p6 + c12 <- p4 + p5 + c21 <- p6 + p7 + c22 <- p2 - p3 + p5 - p7 + + # Join and return final matrix + join_matrices(c11, c12, c21, c22) + } + + # Perform Strassen multiplication + result_padded <- strassen_recursive(A, B) + + # Extract the relevant portion + result <- result_padded[1:orig_rows, 1:orig_cols, drop = FALSE] + + return(result) +} + +# --------------------------------------------------------------- +# Helper that mimics the Julia `intprint` +# --------------------------------------------------------------- +int_print <- function(title, mat) { + # Round to 8 decimal places and convert near-integers to integers + rounded_mat <- round(mat, digits = 8) + cat(title, "\n") + print(rounded_mat) + cat("\n") +} + +# --------------------------------------------------------------- +# Test data +# --------------------------------------------------------------- +varA <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE) +varB <- matrix(c(5, 6, 7, 8), nrow = 2, byrow = TRUE) + +varC <- matrix(c( + 1, 1, 1, 1, + 2, 4, 8, 16, + 3, 9, 27, 81, + 4, 16, 64, 256 +), nrow = 4, byrow = TRUE) + +varD <- matrix(c( + 4, -3, 4/3, -1/4, + -13/3, 19/4, -7/3, 11/24, + 3/2, -2, 7/6, -1/4, + -1/6, 1/4, -1/6, 1/24 +), nrow = 4, byrow = TRUE) + +varE <- matrix(c( + 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12, + 13, 14, 15, 16 +), nrow = 4, byrow = TRUE) + +varF <- diag(4) + +r <- sqrt(2)/2 +R <- matrix(c(r, r, -r, r), nrow = 2, byrow = TRUE) + +# --------------------------------------------------------------- +# Run the examples – compare ordinary (%*%) and Strassen results +# --------------------------------------------------------------- + +# Example 1 +int_print("Regular multiply:", t(varA) %*% t(varB)) +int_print("Strassen multiply:", strassen(t(varA), t(varB))) + +# Example 2 +int_print("Regular multiply:", varC %*% varD) +int_print("Strassen multiply:", strassen(varC, varD)) + +# Example 3 +int_print("Regular multiply:", varE %*% varF) +int_print("Strassen multiply:", strassen(varE, varF)) + +# Example 4 +int_print("Regular multiply:", R %*% R) +int_print("Strassen multiply:", strassen(R, R)) diff --git a/Task/Strassens-algorithm/Racket/strassens-algorithm.rkt b/Task/Strassens-algorithm/Racket/strassens-algorithm.rkt new file mode 100644 index 0000000000..759d301d40 --- /dev/null +++ b/Task/Strassens-algorithm/Racket/strassens-algorithm.rkt @@ -0,0 +1,220 @@ +#lang racket + +(require racket/format) + +; Matrix structure +(struct matrix (data rows cols) #:transparent) + +; Constructor +(define (new-matrix data) + (let ([rows (length data)] + [cols (if (null? data) 0 (length (car data)))]) + (matrix data rows cols))) + +; Getters +(define (get-rows m) (matrix-rows m)) +(define (get-cols m) (matrix-cols m)) + +; Validation functions +(define (validate-dimensions m1 m2) + (unless (and (= (get-rows m1) (get-rows m2)) + (= (get-cols m1) (get-cols m2))) + (error "Matrices must have the same dimensions."))) + +(define (validate-multiplication m1 m2) + (unless (= (get-cols m1) (get-rows m2)) + (error "Cannot multiply these matrices."))) + +(define (validate-square-power-of-two m) + (let ([rows (get-rows m)] + [cols (get-cols m)]) + (unless (= rows cols) + (error "Matrix must be square.")) + (when (or (= rows 0) (not (= (bitwise-and rows (- rows 1)) 0))) + (error "Size of matrix must be a power of two.")))) + +; Helper functions for matrix operations +(define (add-elements row1 row2) + (map + row1 row2)) + +(define (subtract-elements row1 row2) + (map - row1 row2)) + +(define (add-rows data1 data2) + (map add-elements data1 data2)) + +(define (subtract-rows data1 data2) + (map subtract-elements data1 data2)) + +; Matrix operations +(define (matrix-add m1 m2) + (validate-dimensions m1 m2) + (let ([data1 (matrix-data m1)] + [data2 (matrix-data m2)]) + (new-matrix (add-rows data1 data2)))) + +(define (matrix-subtract m1 m2) + (validate-dimensions m1 m2) + (let ([data1 (matrix-data m1)] + [data2 (matrix-data m2)]) + (new-matrix (subtract-rows data1 data2)))) + +; Get column from matrix data +(define (get-column data col-index) + (map (lambda (row) (list-ref row col-index)) data)) + +; Dot product of two lists +(define (dot-product list1 list2) + (apply + (map * list1 list2))) + +; Multiply a row with entire matrix +(define (multiply-row-with-matrix row data2 cols2) + (map (lambda (j) (dot-product row (get-column data2 j))) + (range cols2))) + +; Multiply rows +(define (multiply-rows data1 data2 cols2) + (map (lambda (row) (multiply-row-with-matrix row data2 cols2)) + data1)) + +(define (matrix-multiply m1 m2) + (validate-multiplication m1 m2) + (let ([data1 (matrix-data m1)] + [data2 (matrix-data m2)] + [cols2 (get-cols m2)]) + (new-matrix (multiply-rows data1 data2 cols2)))) + +; String formatting functions +(define (format-element e) + (~a e)) + +(define (format-row row) + (string-append "[" (string-join (map format-element row) ", ") "]")) + +(define (matrix-to-string m) + (let ([data (matrix-data m)]) + (string-append (string-join (map format-row data) "\n") "\n"))) + +(define (format-element-with-precision e precision) + (let* ([pow (expt 10.0 precision)] + [rounded (/ (round (* e pow)) pow)] + [formatted (~r rounded #:precision precision)] + [zero-check (if (= precision 0) + "0" + (string-append "0." (make-string precision #\0)))]) + ; Handle negative zero + (if (and (string-prefix? formatted "-") + (string=? (substring formatted 1) zero-check)) + zero-check + formatted))) + +(define (format-row-with-precision row precision) + (string-append "[" + (string-join (map (lambda (e) (format-element-with-precision e precision)) row) ", ") + "]")) + +(define (matrix-to-string-with-precision m precision) + (let ([data (matrix-data m)]) + (string-append (string-join (map (lambda (row) (format-row-with-precision row precision)) data) "\n") "\n"))) + +; Strassen multiplication helper functions +(define (to-quarters m) + (let* ([rows (get-rows m)] + [r (quotient rows 2)] + [data (matrix-data m)] + [top-half (take data r)] + [bottom-half (drop data r)]) + (list + ; Q0: top-left + (new-matrix (map (lambda (row) (take row r)) top-half)) + ; Q1: top-right + (new-matrix (map (lambda (row) (drop row r)) top-half)) + ; Q2: bottom-left + (new-matrix (map (lambda (row) (take row r)) bottom-half)) + ; Q3: bottom-right + (new-matrix (map (lambda (row) (drop row r)) bottom-half))))) + +(define (from-quarters quarters) + (let ([q0 (first quarters)] + [q1 (second quarters)] + [q2 (third quarters)] + [q3 (fourth quarters)]) + (let ([q0-data (matrix-data q0)] + [q1-data (matrix-data q1)] + [q2-data (matrix-data q2)] + [q3-data (matrix-data q3)]) + (let ([top-half (map append q0-data q1-data)] + [bottom-half (map append q2-data q3-data)]) + (new-matrix (append top-half bottom-half)))))) + +(define (strassen-impl m1 m2) + (if (= (get-rows m1) 1) + (matrix-multiply m1 m2) + (let ([quarters-a (to-quarters m1)] + [quarters-b (to-quarters m2)]) + (let ([a11 (first quarters-a)] + [a12 (second quarters-a)] + [a21 (third quarters-a)] + [a22 (fourth quarters-a)] + [b11 (first quarters-b)] + [b12 (second quarters-b)] + [b21 (third quarters-b)] + [b22 (fourth quarters-b)]) + ; Calculate the 7 products according to Strassen's algorithm + (let ([p1 (strassen-impl a11 (matrix-subtract b12 b22))] + [p2 (strassen-impl (matrix-add a11 a12) b22)] + [p3 (strassen-impl (matrix-add a21 a22) b11)] + [p4 (strassen-impl a22 (matrix-subtract b21 b11))] + [p5 (strassen-impl (matrix-add a11 a22) (matrix-add b11 b22))] + [p6 (strassen-impl (matrix-subtract a12 a22) (matrix-add b21 b22))] + [p7 (strassen-impl (matrix-subtract a11 a21) (matrix-add b11 b12))]) + ; Calculate result quarters + (let ([c11 (matrix-add (matrix-subtract (matrix-add p5 p4) p2) p6)] + [c12 (matrix-add p1 p2)] + [c21 (matrix-add p3 p4)] + [c22 (matrix-subtract (matrix-subtract (matrix-add p5 p1) p3) p7)]) + (from-quarters (list c11 c12 c21 c22)))))))) + +(define (matrix-strassen m1 m2) + (validate-square-power-of-two m1) + (validate-square-power-of-two m2) + (unless (and (= (get-rows m1) (get-rows m2)) + (= (get-cols m1) (get-cols m2))) + (error "Matrices must be square and of equal size for Strassen multiplication.")) + (strassen-impl m1 m2)) + +; Main function for testing +(define (main) + (let* ([a-data '((1.0 2.0) (3.0 4.0))] + [a (new-matrix a-data)] + [b-data '((5.0 6.0) (7.0 8.0))] + [b (new-matrix b-data)] + [c-data '((1.0 1.0 1.0 1.0) (2.0 4.0 8.0 16.0) (3.0 9.0 27.0 81.0) (4.0 16.0 64.0 256.0))] + [c (new-matrix c-data)] + [d-data `((4.0 -3.0 ,(/ 4.0 3.0) ,(/ -1.0 4.0)) + (,(/ -13.0 3.0) ,(/ 19.0 4.0) ,(/ -7.0 3.0) ,(/ 11.0 24.0)) + (1.5 -2.0 ,(/ 7.0 6.0) -0.25) + (,(/ -1.0 6.0) 0.25 ,(/ -1.0 6.0) ,(/ 1.0 24.0)))] + [d (new-matrix d-data)] + [e-data '((1.0 2.0 3.0 4.0) (5.0 6.0 7.0 8.0) (9.0 10.0 11.0 12.0) (13.0 14.0 15.0 16.0))] + [e (new-matrix e-data)] + [f-data '((1.0 0.0 0.0 0.0) (0.0 1.0 0.0 0.0) (0.0 0.0 1.0 0.0) (0.0 0.0 0.0 1.0))] + [f (new-matrix f-data)]) + + (displayln "Using 'normal' matrix multiplication:") + (printf " a * b = ~a" (matrix-to-string (matrix-multiply a b))) + (printf " c * d = ~a" (matrix-to-string-with-precision (matrix-multiply c d) 6)) + (printf " e * f = ~a" (matrix-to-string (matrix-multiply e f))) + + (displayln "\nUsing 'Strassen' matrix multiplication:") + (printf " a * b = ~a" (matrix-to-string (matrix-strassen a b))) + (printf " c * d = ~a" (matrix-to-string-with-precision (matrix-strassen c d) 6)) + (printf " e * f = ~a" (matrix-to-string (matrix-strassen e f))))) + +; Export functions for use as a module +(provide new-matrix matrix? get-rows get-cols + matrix-add matrix-subtract matrix-multiply matrix-strassen + matrix-to-string matrix-to-string-with-precision main) + +; Run the main function if this file is executed directly +(main) diff --git a/Task/Strassens-algorithm/Ruby/strassens-algorithm.rb b/Task/Strassens-algorithm/Ruby/strassens-algorithm.rb new file mode 100644 index 0000000000..18e87a279c --- /dev/null +++ b/Task/Strassens-algorithm/Ruby/strassens-algorithm.rb @@ -0,0 +1,214 @@ +class Shape < Struct.new(:rows, :cols) +end + +class Matrix + attr_reader :data + + def initialize(data = []) + @data = data + end + + def self.block(blocks) + m = [] + # blocks is an array of arrays of Matrix objects + # Process horizontal blocks row by row + top_blocks = blocks[0] # [c11, c12] + bottom_blocks = blocks[1] # [c21, c22] + + # Combine top blocks horizontally + top_rows = [] + (0...top_blocks[0].rows).each do |i| + row = [] + top_blocks.each { |block| row.concat(block.data[i]) } + top_rows << row + end + + # Combine bottom blocks horizontally + bottom_rows = [] + (0...bottom_blocks[0].rows).each do |i| + row = [] + bottom_blocks.each { |block| row.concat(block.data[i]) } + bottom_rows << row + end + + # Combine all rows vertically + m = top_rows + bottom_rows + Matrix.new(m) + end + + def dot(b) + raise "Matrix dimensions don't match" unless self.cols == b.rows + + result = [] + @data.each do |row| + new_row = [] + b.cols.times do |c| + col = b.data.map { |r| r[c] } + new_row << row.zip(col).map { |x, y| x * y }.sum + end + result << new_row + end + Matrix.new(result) + end + + def *(b) + dot(b) + end + + def +(b) + raise "Matrix dimensions don't match" unless self.shape == b.shape + + rows, cols = self.rows, self.cols + result = [] + rows.times do |i| + new_row = [] + cols.times do |j| + new_row << @data[i][j] + b.data[i][j] + end + result << new_row + end + Matrix.new(result) + end + + def -(b) + raise "Matrix dimensions don't match" unless self.shape == b.shape + + rows, cols = self.rows, self.cols + result = [] + rows.times do |i| + new_row = [] + cols.times do |j| + new_row << @data[i][j] - b.data[i][j] + end + result << new_row + end + Matrix.new(result) + end + + def strassen(b) + rows, cols = self.rows, self.cols + + raise "Matrices must be square" unless rows == cols + raise "Matrices must be the same shape" unless self.shape == b.shape + raise "Shape must be a power of 2" unless rows > 0 && (rows & (rows - 1)) == 0 + + if rows == 1 + return self.dot(b) + end + + p = rows / 2 + + a11 = Matrix.new(@data[0...p].map { |row| row[0...p] }) + a12 = Matrix.new(@data[0...p].map { |row| row[p..-1] }) + a21 = Matrix.new(@data[p..-1].map { |row| row[0...p] }) + a22 = Matrix.new(@data[p..-1].map { |row| row[p..-1] }) + + b11 = Matrix.new(b.data[0...p].map { |row| row[0...p] }) + b12 = Matrix.new(b.data[0...p].map { |row| row[p..-1] }) + b21 = Matrix.new(b.data[p..-1].map { |row| row[0...p] }) + b22 = Matrix.new(b.data[p..-1].map { |row| row[p..-1] }) + + m1 = (a11 + a22).strassen(b11 + b22) + m2 = (a21 + a22).strassen(b11) + m3 = a11.strassen(b12 - b22) + m4 = a22.strassen(b21 - b11) + m5 = (a11 + a12).strassen(b22) + m6 = (a21 - a11).strassen(b11 + b12) + m7 = (a12 - a22).strassen(b21 + b22) + + c11 = m1 + m4 - m5 + m7 + c12 = m3 + m5 + c21 = m2 + m4 + c22 = m1 - m2 + m3 + m6 + + Matrix.block([[c11, c12], [c21, c22]]) + end + + def round(ndigits = nil) + rounded_data = @data.map do |row| + row.map do |element| + if ndigits + (element * (10 ** ndigits)).round / (10.0 ** ndigits) + else + element.round + end + end + end + Matrix.new(rounded_data) + end + + def shape + cols = @data.empty? ? 0 : @data[0].length + Shape.new(@data.length, cols) + end + + def rows + @data.length + end + + def cols + @data.empty? ? 0 : @data[0].length + end + + def to_s + @data.inspect + end + + def inspect + @data.inspect + end +end + +def examples + a = Matrix.new([ + [1, 2], + [3, 4] + ]) + + b = Matrix.new([ + [5, 6], + [7, 8] + ]) + + c = Matrix.new([ + [1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256] + ]) + + d = Matrix.new([ + [4, -3, 4.0/3, -1.0/4], + [-13.0/3, 19.0/4, -7.0/3, 11.0/24], + [3.0/2, -2, 7.0/6, -1.0/4], + [-1.0/6, 1.0/4, -1.0/6, 1.0/24] + ]) + + e = Matrix.new([ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16] + ]) + + f = Matrix.new([ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]) + + puts "Naive matrix multiplication:" + puts " a * b = #{a * b}" + puts " c * d = #{(c * d).round}" + puts " e * f = #{e * f}" + + puts "Strassen's matrix multiplication:" + puts " a * b = #{a.strassen(b)}" + puts " c * d = #{c.strassen(d).round}" + puts " e * f = #{e.strassen(f)}" +end + +if __FILE__ == $0 + examples +end diff --git a/Task/Strassens-algorithm/Tcl/strassens-algorithm.tcl b/Task/Strassens-algorithm/Tcl/strassens-algorithm.tcl new file mode 100644 index 0000000000..97c34a5539 --- /dev/null +++ b/Task/Strassens-algorithm/Tcl/strassens-algorithm.tcl @@ -0,0 +1,267 @@ +# Helper function to create a matrix from nested blocks +proc block_matrix {blocks} { + set m {} + set num_hblocks [llength $blocks] + set num_vblocks [llength [lindex $blocks 0]] + + # Determine dimensions + set block_height [llength [lindex [lindex $blocks 0] 0]] + set block_widths {} + for {set j 0} {$j < $num_vblocks} {incr j} { + lappend block_widths [llength [lindex [lindex [lindex $blocks 0] $j] 0]] + } + + # Build the resulting matrix + for {set i 0} {$i < [expr {$block_height * $num_hblocks}]} {incr i} { + lappend m {} + } + + for {set h 0} {$h < $num_hblocks} {incr h} { + set row_offset [expr {$h * $block_height}] + for {set i 0} {$i < $block_height} {incr i} { + set col_offset 0 + for {set v 0} {$v < $num_vblocks} {incr v} { + set block [lindex [lindex $blocks $h] $v] + set block_width [lindex $block_widths $v] + for {set j 0} {$j < $block_width} {incr j} { + set row_idx [expr {$row_offset + $i}] + set col_idx [expr {$col_offset + $j}] + set value [lindex [lindex $block $i] $j] + + # Extend row if needed + set current_row [lindex $m $row_idx] + while {[llength $current_row] <= $col_idx} { + lappend current_row 0 + } + set current_row [lreplace $current_row $col_idx $col_idx $value] + set m [lreplace $m $row_idx $row_idx $current_row] + } + incr col_offset $block_width + } + } + } + + return $m +} + +# Matrix multiplication (naive) +proc matrix_multiply {a b} { + set rows_a [llength $a] + set cols_a [llength [lindex $a 0]] + set rows_b [llength $b] + set cols_b [llength [lindex $b 0]] + + if {$cols_a != $rows_b} { + error "Incompatible matrix dimensions for multiplication" + } + + set result {} + for {set i 0} {$i < $rows_a} {incr i} { + set row {} + for {set j 0} {$j < $cols_b} {incr j} { + set sum 0 + for {set k 0} {$k < $cols_a} {incr k} { + set a_val [lindex [lindex $a $i] $k] + set b_val [lindex [lindex $b $k] $j] + set sum [expr {$sum + $a_val * $b_val}] + } + lappend row $sum + } + lappend result $row + } + + return $result +} + +# Matrix addition +proc matrix_add {a b} { + set rows [llength $a] + set cols [llength [lindex $a 0]] + + if {$rows != [llength $b] || $cols != [llength [lindex $b 0]]} { + error "Matrices must have the same dimensions" + } + + set result {} + for {set i 0} {$i < $rows} {incr i} { + set row {} + for {set j 0} {$j < $cols} {incr j} { + set a_val [lindex [lindex $a $i] $j] + set b_val [lindex [lindex $b $i] $j] + lappend row [expr {$a_val + $b_val}] + } + lappend result $row + } + + return $result +} + +# Matrix subtraction +proc matrix_subtract {a b} { + set rows [llength $a] + set cols [llength [lindex $a 0]] + + if {$rows != [llength $b] || $cols != [llength [lindex $b 0]]} { + error "Matrices must have the same dimensions" + } + + set result {} + for {set i 0} {$i < $rows} {incr i} { + set row {} + for {set j 0} {$j < $cols} {incr j} { + set a_val [lindex [lindex $a $i] $j] + set b_val [lindex [lindex $b $i] $j] + lappend row [expr {$a_val - $b_val}] + } + lappend result $row + } + + return $result +} + +# Get submatrix (using 0-based indexing internally, but interface expects 1-based) +proc get_submatrix {m start_row end_row start_col end_col} { + # Convert to 0-based indexing + incr start_row -1 + incr end_row -1 + incr start_col -1 + incr end_col -1 + + set result {} + for {set i $start_row} {$i <= $end_row} {incr i} { + set row {} + for {set j $start_col} {$j <= $end_col} {incr j} { + lappend row [lindex [lindex $m $i] $j] + } + lappend result $row + } + return $result +} + +# Check if number is power of 2 +proc is_power_of_2 {n} { + if {$n <= 0} {return 0} + return [expr {($n & ($n - 1)) == 0}] +} + +# Strassen's algorithm +proc strassen_multiply {a b} { + set n [llength $a] + set m [llength [lindex $a 0]] + + if {$n != $m} { + error "Matrix must be square" + } + if {$n != [llength $b] || $n != [llength [lindex $b 0]]} { + error "Matrices must have the same dimensions" + } + + # Check if size is a power of 2 + if {![is_power_of_2 $n]} { + error "Matrix dimension must be a power of 2" + } + + if {$n == 1} { + set val [expr {[lindex [lindex $a 0] 0] * [lindex [lindex $b 0] 0]}] + return [list [list $val]] + } + + set half [expr {$n / 2}] + + # Partition matrices into quadrants + set a11 [get_submatrix $a 1 $half 1 $half] + set a12 [get_submatrix $a 1 $half [expr {$half+1}] $n] + set a21 [get_submatrix $a [expr {$half+1}] $n 1 $half] + set a22 [get_submatrix $a [expr {$half+1}] $n [expr {$half+1}] $n] + + set b11 [get_submatrix $b 1 $half 1 $half] + set b12 [get_submatrix $b 1 $half [expr {$half+1}] $n] + set b21 [get_submatrix $b [expr {$half+1}] $n 1 $half] + set b22 [get_submatrix $b [expr {$half+1}] $n [expr {$half+1}] $n] + + # Calculate the seven products + set m1 [strassen_multiply [matrix_add $a11 $a22] [matrix_add $b11 $b22]] + set m2 [strassen_multiply [matrix_add $a21 $a22] $b11] + set m3 [strassen_multiply $a11 [matrix_subtract $b12 $b22]] + set m4 [strassen_multiply $a22 [matrix_subtract $b21 $b11]] + set m5 [strassen_multiply [matrix_add $a11 $a12] $b22] + set m6 [strassen_multiply [matrix_subtract $a21 $a11] [matrix_add $b11 $b12]] + set m7 [strassen_multiply [matrix_subtract $a12 $a22] [matrix_add $b21 $b22]] + + # Calculate the four quadrants of the result + set c11 [matrix_add [matrix_subtract [matrix_add $m1 $m4] $m5] $m7] + set c12 [matrix_add $m3 $m5] + set c21 [matrix_add $m2 $m4] + set c22 [matrix_add [matrix_subtract [matrix_add $m1 $m3] $m2] $m6] + + # Combine quadrants into a single matrix + return [block_matrix [list [list $c11 $c12] [list $c21 $c22]]] +} + +# Round matrix values +proc matrix_round {m {digits {}}} { + set result {} + + if {$digits ne ""} { + set mult [expr {pow(10, $digits)}] + } + + for {set i 0} {$i < [llength $m]} {incr i} { + set row {} + for {set j 0} {$j < [llength [lindex $m 0]]} {incr j} { + set val [lindex [lindex $m $i] $j] + if {$digits ne ""} { + set rounded [expr {floor($val * $mult + 0.5) / $mult}] + } else { + set rounded [expr {floor($val + 0.5)}] + } + lappend row $rounded + } + lappend result $row + } + + return $result +} + +# Print matrix +proc print_matrix {name m} { + puts "$name = \{" + for {set i 0} {$i < [llength $m]} {incr i} { + puts -nonewline " \{" + set row [lindex $m $i] + for {set j 0} {$j < [llength $row]} {incr j} { + puts -nonewline [lindex $row $j] + if {$j < [expr {[llength $row] - 1}]} { + puts -nonewline ", " + } + } + puts "\}" + } + puts "\}" +} + +# Examples +proc run_examples {} { + set a {{1 2} {3 4}} + set b {{5 6} {7 8}} + + set c {{1 1 1 1} {2 4 8 16} {3 9 27 81} {4 16 64 256}} + + set d {{4 -3 1.333333 -0.25} {-4.333333 4.75 -2.333333 0.458333} {1.5 -2 1.166667 -0.25} {-0.166667 0.25 -0.166667 0.041667}} + + set e {{1 2 3 4} {5 6 7 8} {9 10 11 12} {13 14 15 16}} + set f {{1 0 0 0} {0 1 0 0} {0 0 1 0} {0 0 0 1}} + + puts "Naive matrix multiplication:" + print_matrix " a * b" [matrix_multiply $a $b] + print_matrix " c * d" [matrix_round [matrix_multiply $c $d] 0] + print_matrix " e * f" [matrix_multiply $e $f] + + puts "\nStrassen's matrix multiplication:" + print_matrix " a * b" [strassen_multiply $a $b] + print_matrix " c * d" [matrix_round [strassen_multiply $c $d] 0] + print_matrix " e * f" [strassen_multiply $e $f] +} + +# Run examples +run_examples diff --git a/Task/Stream-merge/Ada/stream-merge.adb b/Task/Stream-merge/Ada/stream-merge.adb new file mode 100644 index 0000000000..18637450bc --- /dev/null +++ b/Task/Stream-merge/Ada/stream-merge.adb @@ -0,0 +1,72 @@ +with Ada.Text_Io; +with Ada.Command_Line; +with Ada.Containers.Indefinite_Holders; + +procedure Stream_Merge is + + package String_Holders + is new Ada.Containers.Indefinite_Holders (String); + + use Ada.Text_Io, String_Holders; + + type Stream_Type is + record + File : File_Type; + Value : Holder; + end record; + + subtype Index_Type is Positive range 1 .. Ada.Command_Line.Argument_Count; + Streams : array (Index_Type) of Stream_Type; + + procedure Fetch (Stream : in out Stream_Type) is + begin + Stream.Value := (if End_Of_File (Stream.File) + then Empty_Holder + else To_Holder (Get_Line (Stream.File))); + end Fetch; + + function Next_Stream return Index_Type is + Index : Index_Type := Index_Type'First; + Value : Holder; + begin + for I in Streams'Range loop + if Value.Is_Empty and not Streams (I).Value.Is_Empty then + Value := Streams (I).Value; + Index := I; + elsif not Streams (I).Value.Is_Empty and then Streams (I).Value.Element < Value.Element then + Value := Streams (I).Value; + Index := I; + end if; + end loop; + if Value.Is_Empty then + raise Program_Error; + end if; + return Index; + end Next_Stream; + + function More_Data return Boolean + is (for some Stream of Streams => not Stream.Value.Is_Empty); + +begin + + if Ada.Command_Line.Argument_Count = 0 then + Put_Line ("Usage: prog ..."); + Put_Line ("Merge the sorted files file1, file2..."); + return; + end if; + + for I in Streams'Range loop + Open (Streams (I).File, In_File, Ada.Command_Line.Argument (I)); + Fetch (Streams (I)); + end loop; + + while More_Data loop + declare + Stream : Stream_Type renames Streams (Next_Stream); + begin + Put_Line (Stream.Value.Element); + Fetch (Stream); + end; + end loop; + +end Stream_Merge; diff --git a/Task/Stream-merge/JavaScript/stream-merge.js b/Task/Stream-merge/JavaScript/stream-merge.js new file mode 100644 index 0000000000..d2d8885921 --- /dev/null +++ b/Task/Stream-merge/JavaScript/stream-merge.js @@ -0,0 +1,89 @@ +// ------------------------------------------------------------ +// Helper that prints a number followed by a space (like C++ `display`) +function display(num) { + process.stdout.write(num + ' '); +} + +// ------------------------------------------------------------ +// merge2 – merge two sorted collections and call `action` for each +// element in sorted order. +function merge2(c1, c2, action) { + let i1 = 0; // index into c1 + let i2 = 0; // index into c2 + + while (i1 < c1.length && i2 < c2.length) { + if (c1[i1] <= c2[i2]) { + action(c1[i1++]); + } else { + action(c2[i2++]); + } + } + + // copy the rest of c1 (if any) + while (i1 < c1.length) { + action(c1[i1++]); + } + + // copy the rest of c2 (if any) + while (i2 < c2.length) { + action(c2[i2++]); + } +} + +// ------------------------------------------------------------ +// mergeN – merge **any number** of sorted collections. +// `all` is an iterable (e.g. an array) that contains the +// collections to be merged. `action` is called for each value +// in global sorted order. +function mergeN(action, all) { + // Create a list of “ranges”: each entry keeps the source array + // and the current index inside that array. + const ranges = Array.from(all, col => ({ + arr: col, + pos: 0, // points to the next element to read + end: col.length + })); + + let done = false; + while (!done) { + done = true; + let least = null; // reference to the range that currently has the smallest element + + // Scan every range looking for the smallest next element. + for (const r of ranges) { + // skip exhausted ranges + if (r.pos >= r.end) continue; + + if (least === null || r.arr[r.pos] < least.arr[least.pos]) { + least = r; + } + } + + // If we found a non‑empty range, emit its element and advance it. + if (least !== null) { + done = false; + action(least.arr[least.pos]); + ++least.pos; + } + } +} + +// ------------------------------------------------------------ +// Demo – the same tests that the C++ `main` performed +(function main() { + const v1 = [0, 3, 6]; + const v2 = [1, 4, 7]; + const v3 = [2, 5, 8]; + + // merge2(v2, v1, display); + merge2(v2, v1, display); + console.log(); // newline + + // mergeN(display, { v1 }); + mergeN(display, [v1]); + console.log(); + + // mergeN(display, { v3, v2, v1 }); + mergeN(display, [v3, v2, v1]); + console.log(); +})(); diff --git a/Task/Stream-merge/Zig/stream-merge.zig b/Task/Stream-merge/Zig/stream-merge.zig new file mode 100644 index 0000000000..866ee718e8 --- /dev/null +++ b/Task/Stream-merge/Zig/stream-merge.zig @@ -0,0 +1,94 @@ +const std = @import("std"); +const print = std.debug.print; +const Order = std.math.Order; + +// Generic merge function for two sorted slices +fn merge2(comptime T: type, c1: []const T, c2: []const T, action: *const fn (T) void) void { + var idx1: usize = 0; + var idx2: usize = 0; + + while (idx1 < c1.len and idx2 < c2.len) { + if (std.math.order(c1[idx1], c2[idx2]) != .gt) { + action(c1[idx1]); + idx1 += 1; + } else { + action(c2[idx2]); + idx2 += 1; + } + } + + while (idx1 < c1.len) { + action(c1[idx1]); + idx1 += 1; + } + + while (idx2 < c2.len) { + action(c2[idx2]); + idx2 += 1; + } +} + +// Generic merge function for n sorted slices +fn mergeN(comptime T: type, action: *const fn (T) void, all: []const []const T, allocator: std.mem.Allocator) !void { + // Create iterator tracking (current_index, end_index) for each slice + var vit = try allocator.alloc(struct { start: usize, end: usize }, all.len); + defer allocator.free(vit); + + // Initialize iterators + for (all, 0..) |slice, i| { + vit[i] = .{ .start = 0, .end = slice.len }; + } + + while (true) { + var done = true; + var least: ?usize = null; + + // Find the slice with the smallest current element + for (vit, 0..) |*iter, i| { + if (iter.start < iter.end) { + if (least == null) { + least = i; + } else if (least) |l| { + if (std.math.order(all[i][iter.start], all[l][vit[l].start]) == .lt) { + least = i; + } + } + } + } + + if (least) |l| { + if (vit[l].start < vit[l].end) { + done = false; + action(all[l][vit[l].start]); + vit[l].start += 1; + } + } + + if (done) { + break; + } + } +} + +fn display(num: i32) void { + print("{d} ", .{num}); +} + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + const allocator = gpa.allocator(); + + const v1 = [_]i32{ 0, 3, 6 }; + const v2 = [_]i32{ 1, 4, 7 }; + const v3 = [_]i32{ 2, 5, 8 }; + + merge2(i32, &v2, &v1, display); + print("\n" , .{}); + + try mergeN(i32, display, &[_][]const i32{&v1}, allocator); + print("\n" , .{}); + + try mergeN(i32, display, &[_][]const i32{ &v3, &v2, &v1 }, allocator); + print("\n" , .{}); +} diff --git a/Task/String-append/Ada/string-append.adb b/Task/String-append/Ada/string-append.adb new file mode 100644 index 0000000000..3f67bfc071 --- /dev/null +++ b/Task/String-append/Ada/string-append.adb @@ -0,0 +1,9 @@ +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO.Unbounded_Io; use Ada.Text_IO.Unbounded_IO; + +procedure String_Append is + Str : Unbounded_String := To_Unbounded_String("Hello"); +begin + Append(Str, ", world!"); + Put_Line(Str); +end String_Append; diff --git a/Task/String-append/COBOL/string-append.cob b/Task/String-append/COBOL/string-append.cob new file mode 100644 index 0000000000..999aa42131 --- /dev/null +++ b/Task/String-append/COBOL/string-append.cob @@ -0,0 +1,23 @@ + identification division. + program-id. string-append. + + data division. + working-storage section. + 01 some-string. + 05 elements pic x occurs 0 to 80 times depending on limiter. + 01 limiter usage index value 7. + 01 current usage index. + + procedure division. + append-main. + + move "Hello, " to some-string + + *> extend the limit and move using reference modification + set current to length of some-string + set limiter up by 5 + move "world" to some-string(current + 1:) + display some-string + + goback. + end program string-append. diff --git a/Task/String-append/Crystal/string-append.cr b/Task/String-append/Crystal/string-append.cr new file mode 100644 index 0000000000..e3f7c817f5 --- /dev/null +++ b/Task/String-append/Crystal/string-append.cr @@ -0,0 +1,3 @@ +s = "hello" +s += " world!" +p s diff --git a/Task/String-append/Emacs-Lisp/string-append-1.el b/Task/String-append/Emacs-Lisp/string-append-1.el new file mode 100644 index 0000000000..3f6ff4c227 --- /dev/null +++ b/Task/String-append/Emacs-Lisp/string-append-1.el @@ -0,0 +1,3 @@ +(defvar str "foo") +(setq str (concat str "bar")) +str ;=> "foobar" diff --git a/Task/String-append/Emacs-Lisp/string-append-2.el b/Task/String-append/Emacs-Lisp/string-append-2.el new file mode 100644 index 0000000000..211d7f7008 --- /dev/null +++ b/Task/String-append/Emacs-Lisp/string-append-2.el @@ -0,0 +1,5 @@ +(require 'cl-lib) + +(defvar str "foo") +(cl-callf concat str "bar") +str ;=> "foobar" diff --git a/Task/String-append/Emacs-Lisp/string-append-3.el b/Task/String-append/Emacs-Lisp/string-append-3.el new file mode 100644 index 0000000000..d7195f6a21 --- /dev/null +++ b/Task/String-append/Emacs-Lisp/string-append-3.el @@ -0,0 +1,8 @@ +(let ((buf (get-buffer-create "*foo*"))) + (with-current-buffer buf + (insert "foo")) + (with-current-buffer buf + (goto-char (point-max)) + (insert "bar") + (buffer-string))) +;; => "foobar" diff --git a/Task/String-append/Euphoria/string-append.eu b/Task/String-append/Euphoria/string-append.eu new file mode 100644 index 0000000000..2e8a5be0f0 --- /dev/null +++ b/Task/String-append/Euphoria/string-append.eu @@ -0,0 +1,7 @@ +sequence string = "String" + +printf(1,"%s\n",{string}) + +string &= " is now longer\n" + +printf(1,"%s",{string}) diff --git a/Task/String-append/Gleam/string-append.gleam b/Task/String-append/Gleam/string-append.gleam new file mode 100644 index 0000000000..1ca6b27a8f --- /dev/null +++ b/Task/String-append/Gleam/string-append.gleam @@ -0,0 +1,2 @@ +let s = "Hello" + s <> " world" diff --git a/Task/String-append/M2000-Interpreter/string-append.m2000 b/Task/String-append/M2000-Interpreter/string-append.m2000 index 5048aa1da9..cbdc5cb547 100644 --- a/Task/String-append/M2000-Interpreter/string-append.m2000 +++ b/Task/String-append/M2000-Interpreter/string-append.m2000 @@ -7,6 +7,8 @@ a$+="(one)" Print a$ Document b$ +b$="1234" +Clear b$ ' use Clear to empty document b$="ok" b$="(one)" Print b$ diff --git a/Task/String-append/Pluto/string-append.pluto b/Task/String-append/Pluto/string-append.pluto new file mode 100644 index 0000000000..b2717be32b --- /dev/null +++ b/Task/String-append/Pluto/string-append.pluto @@ -0,0 +1,3 @@ +local s = "Rosetta" +s ..= " Code" +print(s) diff --git a/Task/String-append/PowerShell/string-append.ps1 b/Task/String-append/PowerShell/string-append.ps1 new file mode 100644 index 0000000000..ee546a310d --- /dev/null +++ b/Task/String-append/PowerShell/string-append.ps1 @@ -0,0 +1,3 @@ +$str = "Hello, " +$str += "World!" +$str diff --git a/Task/String-append/RISC-V-Assembly/string-append.asm b/Task/String-append/RISC-V-Assembly/string-append.asm new file mode 100644 index 0000000000..7106bc3a28 --- /dev/null +++ b/Task/String-append/RISC-V-Assembly/string-append.asm @@ -0,0 +1,115 @@ +# riscv assembly raspberry pico2 rp2350 +# program appstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 100 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessString: .asciz "String :\n" +szString1: .asciz "Alphabet : " +sComplement: .fill BUFFERSIZE,1,0 +szString2: .asciz "abcdefghijklmnopqrstuvwxyz" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szMessString # message address + call writeString # display message + la a0,szString1 # message address + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szMessString # message address + call writeString # display message + la a0,szString2 # message address + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szString1 + la a1,szString2 + call append + + la a0,szMessString # message address + call writeString # display message + la a0,szString1 # message address + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/*********************************************/ +/* add string to string */ +/*********************************************/ +/* no verfication size complement buffer */ +/* a0 contains address String 1 */ +/* a1 contains address String 2 */ +append: + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 # counter byte string 1 +1: + add t1,a0,t0 + lbu t2,(t1) # load byte string 1 + beqz t2,2f # zero final ? + addi t0,t0,1 # no -> increment counter + j 1b # loop +2: + li t3, 0 # counter byte string 2 +3: + add t4,a1,t3 + lbu t5,(t4) # load byte string 2 + add t1,a0,t0 + sb t5,(t1) # store byte string 1 + beqz t5,100f # zero final ? -> end + addi t3,t3,1 # increment counter + addi t0,t0,1 + j 3b # end loop + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-append/Rye/string-append.rye b/Task/String-append/Rye/string-append.rye new file mode 100644 index 0000000000..0a5d5fa843 --- /dev/null +++ b/Task/String-append/Rye/string-append.rye @@ -0,0 +1,2 @@ +var 's "hello" +append! " world" 's diff --git a/Task/String-append/VBScript/string-append.vbs b/Task/String-append/VBScript/string-append.vbs new file mode 100644 index 0000000000..2e742f3955 --- /dev/null +++ b/Task/String-append/VBScript/string-append.vbs @@ -0,0 +1,3 @@ +s = "Rosetta" +s = s & " Code" +WScript.StdOut.Write s diff --git a/Task/String-case/Ada/string-case.adb b/Task/String-case/Ada/string-case.adb new file mode 100644 index 0000000000..52e0234392 --- /dev/null +++ b/Task/String-case/Ada/string-case.adb @@ -0,0 +1,9 @@ +with Ada.Characters.Handling, Ada.Text_IO; +use Ada.Characters.Handling, Ada.Text_IO; + +procedure Upper_Case_String is + S : constant String := "alphaBETA"; +begin + Put_Line (To_Upper (S)); + Put_Line (To_Lower (S)); +end Upper_Case_String; diff --git a/Task/String-case/AutoIt/string-case.au3 b/Task/String-case/AutoIt/string-case.au3 new file mode 100644 index 0000000000..874adeedc6 --- /dev/null +++ b/Task/String-case/AutoIt/string-case.au3 @@ -0,0 +1,3 @@ +$sString = "alphaBETA" +$sUppercase = StringUpper($sString) ;"ALPHABETA" +$sLowercase = StringLower($sString) ;"alphabeta" diff --git a/Task/String-case/Ballerina/string-case.ballerina b/Task/String-case/Ballerina/string-case.ballerina new file mode 100644 index 0000000000..f84adad107 --- /dev/null +++ b/Task/String-case/Ballerina/string-case.ballerina @@ -0,0 +1,7 @@ +import ballerina/io; + +public function main() { + string s = "alphaBETA"; + io:println(s.toUpperAscii()); + io:println(s.toLowerAscii()); +} diff --git a/Task/String-case/COBOL/string-case-1.cob b/Task/String-case/COBOL/string-case-1.cob new file mode 100644 index 0000000000..c155a278b5 --- /dev/null +++ b/Task/String-case/COBOL/string-case-1.cob @@ -0,0 +1,30 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. string-case-85. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 example PIC X(9) VALUE "alphaBETA". + + 01 result PIC X(9). + + PROCEDURE DIVISION. + DISPLAY "Example: " example + + *> Using the intrinsic functions. + DISPLAY "Lower-case: " FUNCTION LOWER-CASE(example) + + DISPLAY "Upper-case: " FUNCTION UPPER-CASE(example) + + *> Using INSPECT + MOVE example TO result + INSPECT result CONVERTING "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + TO "abcdefghijklmnopqrstuvwxyz" + DISPLAY "Lower-case: " result + + MOVE example TO result + INSPECT result CONVERTING "abcdefghijklmnopqrstuvwxyz" + TO "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + DISPLAY "Upper-case: " result + + GOBACK + . diff --git a/Task/String-case/COBOL/string-case-2.cob b/Task/String-case/COBOL/string-case-2.cob new file mode 100644 index 0000000000..1e2eeb216d --- /dev/null +++ b/Task/String-case/COBOL/string-case-2.cob @@ -0,0 +1,32 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. string-case-extensions. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 78 example VALUE "alphaBETA". + + 01 result PIC X(9). + + PROCEDURE DIVISION. + DISPLAY "Example: " example + + *> ACUCOBOL-GT + MOVE example TO result + CALL "C$TOLOWER" USING result, BY VALUE 9 + DISPLAY "Lower-case: " result + + MOVE example TO result + CALL "C$TOUPPER" USING result, BY VALUE 9 + DISPLAY "Upper-case: " result + + *> Visual COBOL + MOVE example TO result + CALL "CBL_TOLOWER" USING result, BY VALUE 9 + DISPLAY "Lower-case: " result + + MOVE example TO result + CALL "CBL_TOUPPER" USING result BY VALUE 9 + DISPLAY "Upper-case: " result + + GOBACK + . diff --git a/Task/String-case/PowerShell/string-case.ps1 b/Task/String-case/PowerShell/string-case.ps1 new file mode 100644 index 0000000000..94f82e072e --- /dev/null +++ b/Task/String-case/PowerShell/string-case.ps1 @@ -0,0 +1,6 @@ +$string = 'alphaBETA' +$lower = $string.ToLower() +$upper = $string.ToUpper() +$title = (Get-Culture).TextInfo.ToTitleCase($string) + +$lower, $upper, $title diff --git a/Task/String-case/Python/string-case.py b/Task/String-case/Python/string-case.py new file mode 100644 index 0000000000..5cd86badaf --- /dev/null +++ b/Task/String-case/Python/string-case.py @@ -0,0 +1,20 @@ +import string + +EXAMPLE_STRINGS = [ + "alphaBETA", + "ação", + "o'hare O'HARE o’hare don't", + "Stroßbùrri", + "ĥåçýджк", + "DŽLjnj", +] + +for s in EXAMPLE_STRINGS: + print(f"original : {s}") + print(f"upper : {s.upper()}") + print(f"lower : {s.lower()}") + print(f"capitalize : {s.capitalize()}") + print(f"title : {s.title()}") + print(f"swapcase : {s.swapcase()}") + print(f"casefold : {s.casefold()}") + print(f"string.capwords : {string.capwords(s, sep=None)}\n") diff --git a/Task/String-case/Rebol/string-case.rebol b/Task/String-case/Rebol/string-case.rebol new file mode 100644 index 0000000000..12f3935da5 --- /dev/null +++ b/Task/String-case/Rebol/string-case.rebol @@ -0,0 +1,3 @@ +print ["Original: " original: "alphaBETA"] +print ["Uppercase:" uppercase original] +print ["Lowercase:" lowercase original] diff --git a/Task/String-case/Rye/string-case.rye b/Task/String-case/Rye/string-case.rye new file mode 100644 index 0000000000..b7d1e64585 --- /dev/null +++ b/Task/String-case/Rye/string-case.rye @@ -0,0 +1,2 @@ +upper "alphaBETA" +lower "alphaBETA" diff --git a/Task/String-case/VBScript/string-case.vbs b/Task/String-case/VBScript/string-case.vbs new file mode 100644 index 0000000000..08da4b0b63 --- /dev/null +++ b/Task/String-case/VBScript/string-case.vbs @@ -0,0 +1,3 @@ +Dim MyWord +MyWord = UCase("alphaBETA") ' Returns "ALPHABETA" +MyWord = LCase("alphaBETA") ' Returns "alphabeta" diff --git a/Task/String-comparison/Ada/string-comparison.adb b/Task/String-comparison/Ada/string-comparison.adb new file mode 100644 index 0000000000..113476e6e2 --- /dev/null +++ b/Task/String-comparison/Ada/string-comparison.adb @@ -0,0 +1,28 @@ +with Ada.Text_IO, Ada.Strings.Equal_Case_Insensitive; + +procedure String_Compare is + + procedure Print_Comparison (A, B : String) is + begin + Ada.Text_IO.Put_Line + ("""" & A & """ and """ & B & """: " & + (if A = B then + "equal, " + elsif Ada.Strings.Equal_Case_Insensitive (A, B) then + "case-insensitive-equal, " + else "not equal at all, ") & + (if A /= B then "/=, " else "") & + (if A < B then "before, " else "") & + (if A > B then "after, " else "") & + (if A <= B then "<=, " else "(not <=), ") & + (if A >= B then ">=. " else "(not >=).")); + end Print_Comparison; +begin + Print_Comparison ("this", "that"); + Print_Comparison ("that", "this"); + Print_Comparison ("THAT", "That"); + Print_Comparison ("this", "This"); + Print_Comparison ("this", "this"); + Print_Comparison ("the", "there"); + Print_Comparison ("there", "the"); +end String_Compare; diff --git a/Task/String-comparison/COBOL/string-comparison-1.cob b/Task/String-comparison/COBOL/string-comparison-1.cob new file mode 100644 index 0000000000..e08410a5f5 --- /dev/null +++ b/Task/String-comparison/COBOL/string-comparison-1.cob @@ -0,0 +1,3 @@ +"hello" = "hello" *> equality +"helloo" <> "hello" *> inequality +"aello" < "hello" *> lexical ordering diff --git a/Task/String-comparison/COBOL/string-comparison-2.cob b/Task/String-comparison/COBOL/string-comparison-2.cob new file mode 100644 index 0000000000..68a3142875 --- /dev/null +++ b/Task/String-comparison/COBOL/string-comparison-2.cob @@ -0,0 +1,3 @@ +FUNCTION STANDARD-COMPARE("hello", "hello") *> "=" +FUNCTION STANDARD-COMPARE("aello", "hello") *> "<" +FUNCTION STANDARD-COMPARE("hello", "aello") *> ">" diff --git a/Task/String-comparison/COBOL/string-comparison-3.cob b/Task/String-comparison/COBOL/string-comparison-3.cob new file mode 100644 index 0000000000..ac0365dfc4 --- /dev/null +++ b/Task/String-comparison/COBOL/string-comparison-3.cob @@ -0,0 +1,2 @@ +"hello " = "hello" *> True +X"00" > X"0000" *> True diff --git a/Task/String-comparison/PowerShell/string-comparison-1.ps1 b/Task/String-comparison/PowerShell/string-comparison-1.ps1 new file mode 100644 index 0000000000..e91e05eca5 --- /dev/null +++ b/Task/String-comparison/PowerShell/string-comparison-1.ps1 @@ -0,0 +1,6 @@ +"a" -lt "b" # lower than +"a" -eq "b" # equal +"a" -gt "b" # greater than +"a" -le "b" # lower than or equal +"a" -ne "b" # not equal +"a" -ge "b" # greater than or equal diff --git a/Task/String-comparison/PowerShell/string-comparison-2.ps1 b/Task/String-comparison/PowerShell/string-comparison-2.ps1 new file mode 100644 index 0000000000..029fb8a0ef --- /dev/null +++ b/Task/String-comparison/PowerShell/string-comparison-2.ps1 @@ -0,0 +1,2 @@ +"a" -eq "A" +"a" -ceq "A" diff --git a/Task/String-comparison/RISC-V-Assembly/string-comparison.asm b/Task/String-comparison/RISC-V-Assembly/string-comparison.asm new file mode 100644 index 0000000000..6dcc8491bb --- /dev/null +++ b/Task/String-comparison/RISC-V-Assembly/string-comparison.asm @@ -0,0 +1,191 @@ +# riscv assembly raspberry pico2 rp2350 +# program compstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szCariageReturn: .asciz "\r\n" +szMessStringEqu: .asciz "The strings are equals.\n" +szMessStringNotEqu: .asciz "The strings are not equals.\n" + +szString1: .asciz "ABCDE" +szString2: .asciz "ABCDE" +szString3: .asciz "ABCFG" +szString4: .asciz "ABC" +szString5: .asciz "abcde" +.align 2 + +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szString1 + la a1,szString2 + call Comparaison + + la a0,szString1 + la a1,szString3 + call Comparaison + + la a0,szString1 + la a1,szString4 + call Comparaison + + # case sensitive comparisons ABCDE et abcde + la a0,szString1 + la a1,szString5 + call Comparaison + + # case insensitive comparisons ABCDE et abcde + la a0,szString1 + la a1,szString5 + call comparStringsInsensitive + bnez a0,1f + la a0,szMessStringEqu + call writeString # display message + j 2f +1: + la a0,szMessStringNotEqu + call writeString # display message +2: + call getchar +100: # final loop + j 100b + +/*********************************************/ +/* comparaison */ +/*********************************************/ +/* a0 contains address String 1 */ +/* a1 contains address String 2 */ +Comparaison: + addi sp, sp, -4 + sw ra, 0(sp) + call comparStrings + bnez a0,1f + + la a0,szMessStringEqu + call writeString # display message + j 100f +1: + la a0,szMessStringNotEqu + call writeString # display message +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* Strings case sensitive comparisons */ +/************************************/ +/* a0 et ra1 contains the address of strings */ +/* return 0 in a0 if equals */ +/* return -1 if string a0 < string a1 */ +/* return 1 if string a0 > string a1 */ +comparStrings: # INFO: comparStrings + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 +1: + add t1,t0,a0 + lb t1,(t1) + add t2,t0,a1 + lb t2,(t2) + beq t1,t2,2f + bgt t1,t2,3f + blt t1,t2,4f +2: # egal + addi t0,t0,1 + bne t1,x0,1b # fin chaine + li a0,0 # egalité + j 100f +3: # plus haut + li a0,1 + j 100f +4: # plus bas + li a0,-1 + j 100f +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* Strings case insensitive comparisons */ +/************************************/ +/* a0 et a1 contains the address of strings */ +/* return 0 in a0 if equals */ +/* return -1 if string a0 < string a1 */ +/* return 1 if string a0 > string a1 */ +comparStringsInsensitive: # INFO: comparStringsInsensitive + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 +1: + add t1,t0,a0 + lb t1,(t1) + # majuscules --> minuscules byte string 1 + li t3,65 + blt t1,t3,2f + li t3,90 + bgt t1,t3,2f + addi t1,t1,32 +2: + add t2,t0,a1 + lb t2,(t2) + # majuscules --> minuscules byte string 2 + li t3,65 + blt t2,t3,3f + li t3,90 + bgt t2,t3,3f + addi t2,t2,32 +3: + + beq t1,t2,4f + bgt t1,t2,5f + blt t1,t2,6f +4: # egal + addi t0,t0,1 + bne t1,x0,1b # fin chaine + li a0,0 # egalité + j 100f +5: # plus haut + li a0,1 + j 100f +6: # plus bas + li a0,-1 + j 100f + +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-concatenation/Ada/string-concatenation.adb b/Task/String-concatenation/Ada/string-concatenation.adb new file mode 100644 index 0000000000..f6b26ba0c1 --- /dev/null +++ b/Task/String-concatenation/Ada/string-concatenation.adb @@ -0,0 +1,9 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure String_Concatenation is + S1 : constant String := "Hello"; + S2 : constant String := S1 & " literal"; +begin + Put_Line (S1); + Put_Line (S2); +end String_Concatenation; diff --git a/Task/String-concatenation/Ballerina/string-concatenation.ballerina b/Task/String-concatenation/Ballerina/string-concatenation.ballerina new file mode 100644 index 0000000000..a23d763a1a --- /dev/null +++ b/Task/String-concatenation/Ballerina/string-concatenation.ballerina @@ -0,0 +1,8 @@ +import ballerina/io; + +public function main() { + string s = "Hello, "; + string t = "world!"; + io:println(s); + io:println(s + t); +} diff --git a/Task/String-concatenation/COBOL/string-concatenation-1.cob b/Task/String-concatenation/COBOL/string-concatenation-1.cob new file mode 100644 index 0000000000..a6c8fd4930 --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation-1.cob @@ -0,0 +1,15 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Concat. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Str PIC X(7) VALUE "Hello, ". + 01 Str2 PIC X(15). + + PROCEDURE DIVISION. + DISPLAY "Str : " Str + STRING Str " World!" DELIMITED BY SIZE INTO Str2 + DISPLAY "Str2 : " Str2 + + GOBACK + . diff --git a/Task/String-concatenation/COBOL/string-concatenation-2.cob b/Task/String-concatenation/COBOL/string-concatenation-2.cob new file mode 100644 index 0000000000..e267fa2eaa --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation-2.cob @@ -0,0 +1,8 @@ + ... + PROCEDURE DIVISION. + DISPLAY "Str : " Str + MOVE FUNCTION CONCATENATE(Str, " World!") TO Str2 + DISPLAY "Str2 : " Str2 + + GOBACK + . diff --git a/Task/String-concatenation/COBOL/string-concatenation-3.cob b/Task/String-concatenation/COBOL/string-concatenation-3.cob new file mode 100644 index 0000000000..c4423f9874 --- /dev/null +++ b/Task/String-concatenation/COBOL/string-concatenation-3.cob @@ -0,0 +1,11 @@ +* *> Using a '&'. + 01 Long-Str-Val PIC X(200) VALUE "Lorem ipsum dolor sit " + & "amet, consectetuer adipiscing elit, sed diam nonummy " + & "nibh euismod tincidunt ut laoreet dolore magna aliquam " + & "erat volutpat.". + +* *> Using a '-' in column 7. Note the first two literals have no +* *> closing quotes. + 01 Another-Long-Str PIC X(200) VALUE " Ut wisi enim ad minim + - "veniam, quis nostrud exerci tation ullamcorper suscipit + - "lobortis nisl ut aliquip ex ea commodo consequat". diff --git a/Task/String-concatenation/Crystal/string-concatenation.cr b/Task/String-concatenation/Crystal/string-concatenation.cr new file mode 100644 index 0000000000..90d3c9a230 --- /dev/null +++ b/Task/String-concatenation/Crystal/string-concatenation.cr @@ -0,0 +1,5 @@ +s1 = "hello" +s2 = s1 + " world!" + +pp! s1 +pp! s2 diff --git a/Task/String-concatenation/Emacs-Lisp/string-concatenation.el b/Task/String-concatenation/Emacs-Lisp/string-concatenation.el new file mode 100644 index 0000000000..61f38f9b05 --- /dev/null +++ b/Task/String-concatenation/Emacs-Lisp/string-concatenation.el @@ -0,0 +1,4 @@ +(defvar foo "foo") +(defvar foobar (concat foo "bar")) +(message "%sbar" foo) +(message "%s" foobar) diff --git a/Task/String-concatenation/Euphoria/string-concatenation.eu b/Task/String-concatenation/Euphoria/string-concatenation.eu new file mode 100644 index 0000000000..173e5d301b --- /dev/null +++ b/Task/String-concatenation/Euphoria/string-concatenation.eu @@ -0,0 +1,7 @@ +sequence s, s1 +s = "hello" +puts(1, s & " literal") +puts(1,'\n') +s1 = s & " literal" +print (1, s1)) +puts(1,'\n') diff --git a/Task/String-concatenation/LOLCODE/string-concatenation.lol b/Task/String-concatenation/LOLCODE/string-concatenation.lol new file mode 100644 index 0000000000..5f1364e3ba --- /dev/null +++ b/Task/String-concatenation/LOLCODE/string-concatenation.lol @@ -0,0 +1,7 @@ +HAI 1.3 + +I HAS A S1 ITZ "O HAI" +I HAS A S2 ITZ SMOOSH S1 " THAR" MKAY +VISIBLE S2 + +KTHXBYE diff --git a/Task/String-concatenation/PowerShell/string-concatenation.ps1 b/Task/String-concatenation/PowerShell/string-concatenation.ps1 new file mode 100644 index 0000000000..75b4a227cf --- /dev/null +++ b/Task/String-concatenation/PowerShell/string-concatenation.ps1 @@ -0,0 +1,8 @@ +$s = "Hello" +Write-Host $s World. + +# alternative, using variable expansion in strings +Write-Host "$s World." + +$s2 = $s + " World." +Write-Host $s2 diff --git a/Task/String-concatenation/RISC-V-Assembly/string-concatenation.asm b/Task/String-concatenation/RISC-V-Assembly/string-concatenation.asm new file mode 100644 index 0000000000..c59c761585 --- /dev/null +++ b/Task/String-concatenation/RISC-V-Assembly/string-concatenation.asm @@ -0,0 +1,117 @@ +# riscv assembly raspberry pico2 rp2350 +# program concatstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 255 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessFinal: .asciz "The final string is \n" + +szString1: .asciz "Hello " +szString2: .asciz " the world. \n" + +szMessErrorSize: .asciz "Error : size final string too small\n" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +szFinalString: .skip BUFFERSIZE +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + + la a0,szString1 # adresse string 1 + la a1,szString2 # adresse string 2 + la a2,szFinalString # adresse string final + li a3,BUFFERSIZE # size area string final + call concatString # concat string + li t0,-1 + beq a0,t0,100f # error ? + + la a0,szMessFinal # message address + call writeString # display message + la a0,szFinalString + call writeString # display message + la a0,szCariageReturn # message address + call writeString # display message + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b + +/*********************************************/ +/* add string to string */ +/*********************************************/ +/* a0 contains address String 1 */ +/* a1 contains address String 2 */ +/* a2 contains address String final */ +/* a3 contains string final size */ +concatString: + addi sp, sp, -4 + sw ra, 0(sp) + li t0,0 # counter byte string 1 + +1: + add t1,a0,t0 + lbu t2,(t1) # load byte string 1 + add t1,a2,t0 + sb t2,(t1) # store byte final string + beqz t2,2f # zero final ? + addi t0,t0,1 # no -> increment counter + bge t0,a3,99f # size maxi ? + j 1b # loop +2: + li t3, 0 # counter byte string 2 +3: + add t4,a1,t3 + lbu t5,(t4) # load byte string 2 + add t1,a2,t0 + sb t5,(t1) # store byte string final + beqz t5,100f # zero final ? -> end + addi t3,t3,1 # increment counter + addi t0,t0,1 + bge t0,a3,99f # size maxi ? + j 3b # end loop +99: + la a0,szMessErrorSize + call writeString + li a0,-1 # return error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-concatenation/ReScript/string-concatenation.res b/Task/String-concatenation/ReScript/string-concatenation.res new file mode 100644 index 0000000000..8215e2e65a --- /dev/null +++ b/Task/String-concatenation/ReScript/string-concatenation.res @@ -0,0 +1,5 @@ +let s1 = "hello" +let s2 = s1 ++ " literal" + +Js.log(s1) +Js.log(s2) diff --git a/Task/String-concatenation/Rebol/string-concatenation.rebol b/Task/String-concatenation/Rebol/string-concatenation.rebol new file mode 100644 index 0000000000..dda3bbfa80 --- /dev/null +++ b/Task/String-concatenation/Rebol/string-concatenation.rebol @@ -0,0 +1,6 @@ +s: "hello" +print s1: rejoin [s " literal"] +; Or: +print s2: join s " literal" +; Or: +print s3: ajoin [s " literal"] diff --git a/Task/String-concatenation/Rye/string-concatenation.rye b/Task/String-concatenation/Rye/string-concatenation.rye new file mode 100644 index 0000000000..423bd3384b --- /dev/null +++ b/Task/String-concatenation/Rye/string-concatenation.rye @@ -0,0 +1,5 @@ +a: "Hello, " +b: a ++ "world!" + +print a +print b diff --git a/Task/String-concatenation/VBScript/string-concatenation.vbs b/Task/String-concatenation/VBScript/string-concatenation.vbs new file mode 100644 index 0000000000..6ca683dae3 --- /dev/null +++ b/Task/String-concatenation/VBScript/string-concatenation.vbs @@ -0,0 +1,3 @@ + s1="Hello" + s2=s1 & " World!" + WScript.Echo s2 diff --git a/Task/String-interpolation-included-/Ada/string-interpolation-included--1.adb b/Task/String-interpolation-included-/Ada/string-interpolation-included--1.adb new file mode 100644 index 0000000000..c38c188a13 --- /dev/null +++ b/Task/String-interpolation-included-/Ada/string-interpolation-included--1.adb @@ -0,0 +1,11 @@ +with Ada.Strings.Fixed, Ada.Text_IO; +use Ada.Strings, Ada.Text_IO; +procedure String_Replace is + Original : constant String := "Mary had a @__@ lamb."; + Tbr : constant String := "@__@"; + New_Str : constant String := "little"; + Index : Natural := Fixed.Index (Original, Tbr); +begin + Put_Line (Fixed.Replace_Slice ( + Original, Index, Index + Tbr'Length - 1, New_Str)); +end String_Replace; diff --git a/Task/String-interpolation-included-/Ada/string-interpolation-included--2.adb b/Task/String-interpolation-included-/Ada/string-interpolation-included--2.adb new file mode 100644 index 0000000000..04e2a49b06 --- /dev/null +++ b/Task/String-interpolation-included-/Ada/string-interpolation-included--2.adb @@ -0,0 +1 @@ +Put_Line ("Mary had a " & New_Str & " lamb."); diff --git a/Task/String-interpolation-included-/COBOL/string-interpolation-included-.cob b/Task/String-interpolation-included-/COBOL/string-interpolation-included-.cob new file mode 100644 index 0000000000..f432c93960 --- /dev/null +++ b/Task/String-interpolation-included-/COBOL/string-interpolation-included-.cob @@ -0,0 +1,12 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. interpolation-included. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 extra PIC X(6) VALUE "little". + + PROCEDURE DIVISION. + DISPLAY FUNCTION SUBSTITUTE("Mary had a X lamb.", "X", extra) + + GOBACK + . diff --git a/Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.el b/Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.el new file mode 100644 index 0000000000..b69ceccd74 --- /dev/null +++ b/Task/String-interpolation-included-/Emacs-Lisp/string-interpolation-included-.el @@ -0,0 +1,4 @@ +(let ((little "little")) + (format "Mary had a %s lamb." little) + ;; message takes a format string as argument + (message "Mary had a %s lamb." little)) diff --git a/Task/String-interpolation-included-/Euphoria/string-interpolation-included-.eu b/Task/String-interpolation-included-/Euphoria/string-interpolation-included-.eu new file mode 100644 index 0000000000..e856013030 --- /dev/null +++ b/Task/String-interpolation-included-/Euphoria/string-interpolation-included-.eu @@ -0,0 +1,4 @@ +constant lambType = "little" +sequence s +s = sprintf("Mary had a %s lamb.",{lambType}) +puts(1,s) diff --git a/Task/String-interpolation-included-/Haxe/string-interpolation-included-.hx b/Task/String-interpolation-included-/Haxe/string-interpolation-included-.hx new file mode 100644 index 0000000000..28712b0a34 --- /dev/null +++ b/Task/String-interpolation-included-/Haxe/string-interpolation-included-.hx @@ -0,0 +1,7 @@ +class Program { + static function main() { + var extra = 'little'; + var formatted = 'Mary had a $extra lamb.'; + Sys.println(formatted); + } +} diff --git a/Task/String-interpolation-included-/Jactl/string-interpolation-included--1.jactl b/Task/String-interpolation-included-/Jactl/string-interpolation-included--1.jactl new file mode 100644 index 0000000000..139b9f5883 --- /dev/null +++ b/Task/String-interpolation-included-/Jactl/string-interpolation-included--1.jactl @@ -0,0 +1,2 @@ +def x = 'little' +println "Mary had a $x lamb" diff --git a/Task/String-interpolation-included-/Jactl/string-interpolation-included--2.jactl b/Task/String-interpolation-included-/Jactl/string-interpolation-included--2.jactl new file mode 100644 index 0000000000..a01fd81a9d --- /dev/null +++ b/Task/String-interpolation-included-/Jactl/string-interpolation-included--2.jactl @@ -0,0 +1,4 @@ +def x = 'li' +def y = 't' +def z = 'le' +println "Mary had a ${x + y * 2 + z} lamb" diff --git a/Task/String-interpolation-included-/LOLCODE/string-interpolation-included-.lol b/Task/String-interpolation-included-/LOLCODE/string-interpolation-included-.lol new file mode 100644 index 0000000000..e200c6971b --- /dev/null +++ b/Task/String-interpolation-included-/LOLCODE/string-interpolation-included-.lol @@ -0,0 +1,6 @@ +HAI 1.3 + +I HAS A SIZE ITZ "little" +VISIBLE "Mary had a :{SIZE} lamb" + +KTHXBYE diff --git a/Task/String-interpolation-included-/Langur/string-interpolation-included--4.langur b/Task/String-interpolation-included-/Langur/string-interpolation-included--4.langur new file mode 100644 index 0000000000..e33ab6466f --- /dev/null +++ b/Task/String-interpolation-included-/Langur/string-interpolation-included--4.langur @@ -0,0 +1,2 @@ +writeln qs:ni"Lamb count: {{x : 7}}" +# will write "Lamb count: {{x : 7}}\n" to the console diff --git a/Task/String-interpolation-included-/PowerShell/string-interpolation-included--1.ps1 b/Task/String-interpolation-included-/PowerShell/string-interpolation-included--1.ps1 new file mode 100644 index 0000000000..525496b639 --- /dev/null +++ b/Task/String-interpolation-included-/PowerShell/string-interpolation-included--1.ps1 @@ -0,0 +1,2 @@ +$extra = "little" +"Mary had a {0} lamb." -f $extra diff --git a/Task/String-interpolation-included-/PowerShell/string-interpolation-included--2.ps1 b/Task/String-interpolation-included-/PowerShell/string-interpolation-included--2.ps1 new file mode 100644 index 0000000000..e886b9c307 --- /dev/null +++ b/Task/String-interpolation-included-/PowerShell/string-interpolation-included--2.ps1 @@ -0,0 +1,2 @@ +$extra = "little" +[console]::writeline("Mary had a {0} lamb.", $extra) diff --git a/Task/String-interpolation-included-/PowerShell/string-interpolation-included--3.ps1 b/Task/String-interpolation-included-/PowerShell/string-interpolation-included--3.ps1 new file mode 100644 index 0000000000..8ec008f067 --- /dev/null +++ b/Task/String-interpolation-included-/PowerShell/string-interpolation-included--3.ps1 @@ -0,0 +1,2 @@ +$extra = "little" +[string]::Format("Mary had a {0} lamb.", $extra) diff --git a/Task/String-interpolation-included-/RISC-V-Assembly/string-interpolation-included-.asm b/Task/String-interpolation-included-/RISC-V-Assembly/string-interpolation-included-.asm new file mode 100644 index 0000000000..8dba6b204b --- /dev/null +++ b/Task/String-interpolation-included-/RISC-V-Assembly/string-interpolation-included-.asm @@ -0,0 +1,260 @@ +# riscv assembly raspberry pico2 rp2350 +# program insstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 255 +.equ CHARPOS, '@' +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessString: .asciz "New string = " +szMessErrorSize: .asciz "Error buffer size !" + +szString: .asciz " string " +szString1: .asciz "insert" +szString2: .asciz "abcd@efg" +szString3: .asciz "abcdefg @" +szString4: .asciz "@ abcdefg" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +sBuffer: .skip BUFFERSIZE +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szString # string address + la a1,szString1 # string address + li a2,0 + la a3,sBuffer + li a4,BUFFERSIZE + call strInsert + + call displayResult + + la a0,szString # string address + la a1,szString1 # string address + li a2,5 + la a3,sBuffer + li a4,BUFFERSIZE + call strInsert + + call displayResult + + la a0,szString # string address + la a1,szString1 # string address + li a2,20 + la a3,sBuffer + li a4,BUFFERSIZE + call strInsert + + call displayResult + + la a0,szString2 # string address + la a1,szString # string address + li a2,CHARPOS # character insertion + la a3,sBuffer + li a4,BUFFERSIZE + call strInsertAtChar + + call displayResult + + la a0,szString3 # string address + la a1,szString # string address + li a2,CHARPOS # character insertion + la a3,sBuffer + li a4,BUFFERSIZE + call strInsertAtChar + + call displayResult + + la a0,szString4 # string address + la a1,szString # string address + li a2,CHARPOS # character insertion + la a3,sBuffer + li a4,BUFFERSIZE + call strInsertAtChar + + call displayResult + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b +/***************************************************/ +/* insertion string at position */ +/***************************************************/ +# a0 contains string1 +# a1 contains insert string +# a2 contains position +# a3 contains address buffer +# a4 contains buffer size +strInsert: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t1,0 # init counter + li t3,0 # init counter result string +1: # loop to copy string begin + beq t1,a2,2f # = position ? + add t0,a0,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,2f # zero final ? -> insertion at end + add t0,a3,t3 # compute byte address + sb t2,(t0) # store byte string + addi t1,t1,1 + addi t3,t3,1 + bge t3,a4,99f # error size ? + j 1b # loop + +2: + li t4,0 +3: + add t0,a1,t4 + lbu t5,(t0) + beqz t5,4f #end insertion string + add t0,a3,t3 # compute byte address + sb t5,(t0) + addi t4,t4,1 + addi t3,t3,1 + bge t3,a4,99f # error size ? + j 3b # loop +4: + beqz t2,6f # end string 1 ? +5: + add t0,a0,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,6f # zero final ? + add t0,a3,t3 # compute byte address + sb t2,(t0) # store byte string + addi t1,t1,1 + addi t3,t3,1 + bge t3,a4,99f # error size ? + j 5b # loop +6: + add t0,a3,t3 # compute byte address + sb x0,(t0) # store zero final + mv a0,t3 #return length + j 100f +99: + la a0,szMessErrorSize + call writeString # display message + li a0,-1 # error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/***************************************************/ +/* insertion string at character insertion */ +/***************************************************/ +# a0 contains string1 +# a1 contains insert string +# a2 contains character insertion +# a3 contains address buffer +# a4 contains buffer size + strInsertAtChar: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t1,0 # init counter + li t3,0 # init counter result string +1: # loop to copy string begin + add t0,a0,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,3f # zero final ? -> insertion at end + beq t2,a2,2f # character insertion + add t0,a3,t3 # compute byte address + sb t2,(t0) # store byte string + addi t1,t1,1 + addi t3,t3,1 + bge t3,a4,99f # error size ? + j 1b # loop +2: + addi t1,t1,1 # jump character insertion +3: + li t4,0 +4: + add t0,a1,t4 + lbu t5,(t0) + beqz t5,5f # end insertion string + add t0,a3,t3 # compute byte address + sb t5,(t0) + addi t4,t4,1 + addi t3,t3,1 + bge t3,a4,99f # error size ? + j 4b # loop +5: + beqz t2,7f # end string 1 ? +6: + add t0,a0,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,7f # zero final ? + add t0,a3,t3 # compute byte address + sb t2,(t0) # store byte string + addi t1,t1,1 + addi t3,t3,1 + bge t3,a4,99f # error size ? + j 6b # loop +7: + add t0,a3,t3 # compute byte address + sb x0,(t0) # store zero final + mv a0,t3 #return length + j 100f +99: + la a0,szMessErrorSize + call writeString # display message + li a0,-1 # error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/***************************************************/ +/* display result string length */ +/***************************************************/ +# a0 contains string e +# a0 return length +displayResult: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + la a0,szMessString + call writeString + la a0,sBuffer + call writeString + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-interpolation-included-/Rebol/string-interpolation-included-.rebol b/Task/String-interpolation-included-/Rebol/string-interpolation-included-.rebol new file mode 100644 index 0000000000..a9b2d64a29 --- /dev/null +++ b/Task/String-interpolation-included-/Rebol/string-interpolation-included-.rebol @@ -0,0 +1,7 @@ +str: "Mary had a <%size%> lamb" +size: "little" +build-markup str + +;REBOL3 also has the REWORD function +str: "Mary had a $size lamb" +reword str [size "little"] diff --git a/Task/String-interpolation-included-/Rye/string-interpolation-included-.rye b/Task/String-interpolation-included-/Rye/string-interpolation-included-.rye new file mode 100644 index 0000000000..5df851bb85 --- /dev/null +++ b/Task/String-interpolation-included-/Rye/string-interpolation-included-.rye @@ -0,0 +1,2 @@ +str: "little" +print "Mary had a " ++ str ++ " lamb" diff --git a/Task/String-length/Ada/string-length-1.adb b/Task/String-length/Ada/string-length-1.adb new file mode 100644 index 0000000000..a6926d9537 --- /dev/null +++ b/Task/String-length/Ada/string-length-1.adb @@ -0,0 +1,2 @@ +Str : String := "Hello World"; +Length : constant Natural := Str'Size / 8; diff --git a/Task/String-length/Ada/string-length-2.adb b/Task/String-length/Ada/string-length-2.adb new file mode 100644 index 0000000000..0fc57729a6 --- /dev/null +++ b/Task/String-length/Ada/string-length-2.adb @@ -0,0 +1,6 @@ +Latin_1_Str : String := "Hello World"; +UCS_16_Str : Wide_String := "Hello World"; +Unicode_Str : Wide_Wide_String := "Hello World"; +Latin_1_Length : constant Natural := Latin_1_Str'Length; +UCS_16_Length : constant Natural := UCS_16_Str'Length; +Unicode_Length : constant Natural := Unicode_Str'Length; diff --git a/Task/String-length/Ballerina/string-length-1.ballerina b/Task/String-length/Ballerina/string-length-1.ballerina new file mode 100644 index 0000000000..0b04d28fd2 --- /dev/null +++ b/Task/String-length/Ballerina/string-length-1.ballerina @@ -0,0 +1,6 @@ +import ballerina/io; + +public function main() { + string s = "møøse"; + io:println(s.length()); +} diff --git a/Task/String-length/Ballerina/string-length-2.ballerina b/Task/String-length/Ballerina/string-length-2.ballerina new file mode 100644 index 0000000000..1fc5cfc380 --- /dev/null +++ b/Task/String-length/Ballerina/string-length-2.ballerina @@ -0,0 +1,10 @@ +import ballerina/io; + +function byteLen(string s) returns int { + return s.toBytes().length(); +} + +public function main() { + string s = "møøse"; + io:println(byteLen(s)); +} diff --git a/Task/String-length/COBOL/string-length-1.cob b/Task/String-length/COBOL/string-length-1.cob new file mode 100644 index 0000000000..bcc3c28aa7 --- /dev/null +++ b/Task/String-length/COBOL/string-length-1.cob @@ -0,0 +1 @@ +FUNCTION BYTE-LENGTH(str) diff --git a/Task/String-length/COBOL/string-length-2.cob b/Task/String-length/COBOL/string-length-2.cob new file mode 100644 index 0000000000..cbad0021b5 --- /dev/null +++ b/Task/String-length/COBOL/string-length-2.cob @@ -0,0 +1 @@ +LENGTH OF str diff --git a/Task/String-length/COBOL/string-length-3.cob b/Task/String-length/COBOL/string-length-3.cob new file mode 100644 index 0000000000..b6ae88a20d --- /dev/null +++ b/Task/String-length/COBOL/string-length-3.cob @@ -0,0 +1 @@ +FUNCTION LENGTH-AN(str) diff --git a/Task/String-length/COBOL/string-length-4.cob b/Task/String-length/COBOL/string-length-4.cob new file mode 100644 index 0000000000..bf0be62e30 --- /dev/null +++ b/Task/String-length/COBOL/string-length-4.cob @@ -0,0 +1 @@ +FUNCTION LENGTH(str) diff --git a/Task/String-length/EMal/string-length-1.emal b/Task/String-length/EMal/string-length-1.emal index 2e2e7820a5..a99a576594 100644 --- a/Task/String-length/EMal/string-length-1.emal +++ b/Task/String-length/EMal/string-length-1.emal @@ -1,4 +1,4 @@ -text moose = "møøse" -text unicode = "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" -text jose = "J" + 0U0332 + "o" + 0U0332 + "s" + 0U0332 + "e" + 0U0301 + 0U0332 -text emoji = "𠇰😈🎶🔥é-" +text moose ← "møøse" +text unicode ← "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" +text jose ← "J" + 0U0332 + "o" + 0U0332 + "s" + 0U0332 + "e" + 0U0301 + 0U0332 +text emoji ← "𠇰😈🎶🔥é-" diff --git a/Task/String-length/Emacs-Lisp/string-length-1.el b/Task/String-length/Emacs-Lisp/string-length-1.el new file mode 100644 index 0000000000..104c6993bd --- /dev/null +++ b/Task/String-length/Emacs-Lisp/string-length-1.el @@ -0,0 +1,2 @@ +(length "hello") +;; => 5 diff --git a/Task/String-length/Emacs-Lisp/string-length-2.el b/Task/String-length/Emacs-Lisp/string-length-2.el new file mode 100644 index 0000000000..a97fc19646 --- /dev/null +++ b/Task/String-length/Emacs-Lisp/string-length-2.el @@ -0,0 +1,2 @@ +(string-bytes "\u1D518\u1D52B\u1D526") +;; => 12 diff --git a/Task/String-length/Emacs-Lisp/string-length-3.el b/Task/String-length/Emacs-Lisp/string-length-3.el new file mode 100644 index 0000000000..6ad818c884 --- /dev/null +++ b/Task/String-length/Emacs-Lisp/string-length-3.el @@ -0,0 +1,7 @@ +(let ((str (apply 'string + (mapcar (lambda (c) (decode-char 'ucs c)) + '(#x1112 #x1161 #x11ab #x1100 #x1173 #x11af))))) + (list (length str) + (string-bytes str) + (string-width str))) +;; => (6 18 4) ;; in emacs 23 up diff --git a/Task/String-length/Euphoria/string-length.eu b/Task/String-length/Euphoria/string-length.eu new file mode 100644 index 0000000000..bf4e4ba651 --- /dev/null +++ b/Task/String-length/Euphoria/string-length.eu @@ -0,0 +1 @@ +print(1,length("Hello World")) diff --git a/Task/String-length/Gleam/string-length.gleam b/Task/String-length/Gleam/string-length.gleam new file mode 100644 index 0000000000..29842ab374 --- /dev/null +++ b/Task/String-length/Gleam/string-length.gleam @@ -0,0 +1,3 @@ +pub fn main() { + echo string.length("𝔘𝔫𝔦𝔠𝔬𝔡𝔢") +} diff --git a/Task/String-length/M2000-Interpreter/string-length.m2000 b/Task/String-length/M2000-Interpreter/string-length.m2000 index 1ff912a758..6aa7e8fa35 100644 --- a/Task/String-length/M2000-Interpreter/string-length.m2000 +++ b/Task/String-length/M2000-Interpreter/string-length.m2000 @@ -3,26 +3,19 @@ module String_length { Print Len(A$) = 9 ' true Utf-16LE Print Len.Disp(A$) = 4 \\ display length Buffer Clear Mem as Byte*100 - \\ Write at memory at offset 0 or address Mem(0) - Return Mem, 0:=A$ - Print Eval$(Mem, 0, 18) - For i=0 to 17 step 2 - \\ print hex value and character - Hex Eval(Mem, i as integer), ChrCode$(Eval(Mem, i as integer)) + Buffer Mem2 as Integer*50 + Mem[0]=A$ + Print Eval$(Mem, 0, 18) ' 18 bytes from Mem[0] as a string + Mem2[0]=Mem + For i=0 to 8 + Hex Mem2[i], ChrCode$(Mem2[i]) Next i - Document B$=A$ - \\ encode to utf-8 with BOM (3 bytes 0xEF,0xBB,0xBF) - Save.Doc B$, "Checklen.doc", 2 - Print Filelen("Checklen.doc")=17 - \\ So length is 14 bytes + 3 the BOM - Mem=Buffer("Checklen.doc") - Print len(Mem)=17 // len works for buffers too - unit byte - // version 12 can handle strings without suffix $ - C=eval$(mem, 3, 14) // from 4th byte get 14 bytes in a string - Print len(C)*2=14 ' bytes // len()) for strings return double type of words (can return 0.5) - C=string$(C as utf8dec) ' decode bytes from utf8 to utf16LE - Print len(C)=9, C=A$, Len.Disp(C)=4 - Print C - Report 2, C // proportional print on console - for text center justified rendering (2 - center) + // Check as UTF8 (UTFEnc and UTF8Dec are selections for string$()) + Print len(string$(A$ as UTF8Enc))*2=14 ' bytes + Locale 1033 + // to ANSI and back to UTF16LE (destructive) + Print chr$(str$(A$))="J_o_s_e´_" ' true + Print A$;POS=4 ' J̲o̲s̲é̲True + Print String$(A$ as Json)="J\u0332o\u0332s\u0332e\u0301\u0332" ' True } String_length diff --git a/Task/String-length/OPL/string-length.opl b/Task/String-length/OPL/string-length.opl new file mode 100644 index 0000000000..a4766ae375 --- /dev/null +++ b/Task/String-length/OPL/string-length.opl @@ -0,0 +1,10 @@ +REM https://github.com/Eva-Broccoli/OPL-Rosetta-Code/blob/main/Strlngth.opl +REM Strings are stored with one character per byte, with a leading byte containing the string length, thus byte length is character length plus one byte. +PROC main: + LOCAL s$(100) + PRINT "Please enter a string." + INPUT s$ + PRINT "Character length:",LEN(s$) + PRINT "Byte length:",LEN(s$)+1 + GET +ENDP diff --git a/Task/String-length/PowerShell/string-length-1.ps1 b/Task/String-length/PowerShell/string-length-1.ps1 new file mode 100644 index 0000000000..22d79228aa --- /dev/null +++ b/Task/String-length/PowerShell/string-length-1.ps1 @@ -0,0 +1,2 @@ +$s = "Hëlló Wørłð" +$s.Length diff --git a/Task/String-length/PowerShell/string-length-2.ps1 b/Task/String-length/PowerShell/string-length-2.ps1 new file mode 100644 index 0000000000..e80243730b --- /dev/null +++ b/Task/String-length/PowerShell/string-length-2.ps1 @@ -0,0 +1,2 @@ +$s = "Hëlló Wørłð" +[System.Text.Encoding]::Unicode.GetByteCount($s) diff --git a/Task/String-length/PowerShell/string-length-3.ps1 b/Task/String-length/PowerShell/string-length-3.ps1 new file mode 100644 index 0000000000..3525924c98 --- /dev/null +++ b/Task/String-length/PowerShell/string-length-3.ps1 @@ -0,0 +1 @@ +[System.Text.Encoding]::UTF8.GetByteCount($s) diff --git a/Task/String-length/RISC-V-Assembly/string-length.asm b/Task/String-length/RISC-V-Assembly/string-length.asm new file mode 100644 index 0000000000..c920903a63 --- /dev/null +++ b/Task/String-length/RISC-V-Assembly/string-length.asm @@ -0,0 +1,110 @@ +# riscv assembly raspberry pico2 rp2350 +# program lenstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 255 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessLenString: .asciz "The lenght of string " +szMessLenString1: .asciz " is " + +szString1: .asciz "Apple" +szString2: .asciz "Orange" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + + la s0,szString1 # adresse string 1 + mv a0,s0 + call stringlength # len string + la a1,sConvArea + call conversion10 # call decimal conversion + la a0,szMessLenString + call writeString + mv a0,s0 + call writeString + la a0,szMessLenString1 + call writeString + la a0,sConvArea # display result message + call writeString + la a0,szCariageReturn + call writeString + + la s0,szString2 # adresse string 2 + mv a0,s0 + call stringlength # len string + la a1,sConvArea + call conversion10 # call decimal conversion + la a0,szMessLenString + call writeString + mv a0,s0 + call writeString + la a0,szMessLenString1 + call writeString + la a0,sConvArea # display result message + call writeString + la a0,szCariageReturn + call writeString + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b +/***************************************************/ +/* compute string length */ +/***************************************************/ +# a0 contains string e +# a0 return length +stringlength: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t1,-1 # init counter +1: # loop + addi t1,t1,1 # increment counter + add t0,a0,t1 # compute byte address + lbu t2,(t0) # load byte string + bnez t2,1b # zero final ? + mv a0,t1 #return length +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-length/ReScript/string-length.res b/Task/String-length/ReScript/string-length.res new file mode 100644 index 0000000000..3fe3146020 --- /dev/null +++ b/Task/String-length/ReScript/string-length.res @@ -0,0 +1 @@ +Js.String2.length("abcd") == 4 diff --git a/Task/String-length/Rebol/string-length-1.rebol b/Task/String-length/Rebol/string-length-1.rebol new file mode 100644 index 0000000000..0b5e813c21 --- /dev/null +++ b/Task/String-length/Rebol/string-length-1.rebol @@ -0,0 +1,5 @@ +;; r2 +length? "møøse" + +;; r3 +length? to-binary "møøse" diff --git a/Task/String-length/Rebol/string-length-2.rebol b/Task/String-length/Rebol/string-length-2.rebol new file mode 100644 index 0000000000..47fa893ed1 --- /dev/null +++ b/Task/String-length/Rebol/string-length-2.rebol @@ -0,0 +1,2 @@ +;; r3 +length? "møøse" diff --git a/Task/String-length/Rye/string-length.rye b/Task/String-length/Rye/string-length.rye new file mode 100644 index 0000000000..7cbe440a74 --- /dev/null +++ b/Task/String-length/Rye/string-length.rye @@ -0,0 +1 @@ +length? "Hello" diff --git a/Task/String-length/VBScript/string-length-1.vbs b/Task/String-length/VBScript/string-length-1.vbs new file mode 100644 index 0000000000..9785a4df61 --- /dev/null +++ b/Task/String-length/VBScript/string-length-1.vbs @@ -0,0 +1 @@ +LenB(string|varname) diff --git a/Task/String-length/VBScript/string-length-2.vbs b/Task/String-length/VBScript/string-length-2.vbs new file mode 100644 index 0000000000..6a30083885 --- /dev/null +++ b/Task/String-length/VBScript/string-length-2.vbs @@ -0,0 +1 @@ +Len(string|varname) diff --git a/Task/String-length/X86-64-Assembly/string-length-1.x86-64 b/Task/String-length/X86-64-Assembly/string-length-1.x86-64 new file mode 100644 index 0000000000..fff374f098 --- /dev/null +++ b/Task/String-length/X86-64-Assembly/string-length-1.x86-64 @@ -0,0 +1,60 @@ +%macro prolog 1 + push rbp + mov rbp, rsp + sub rsp, %1 +%endmacro + +%macro epilog 1 + add rsp, %1 + pop rbp +%endmacro + +%macro xcall 1 + call [rel %1 wrt ..got] +%endmacro + +%macro xlea 2 + lea %1, [rel %2] +%endmacro + +extern printf +extern exit + +section .text + global xstrlen + xstrlen: + push rbp + mov rbp, rsp + + mov rax, rdi ;; Change this to RCX and it works on windoze ABI. + mov rsi, rax + xor rbx, rbx + + __xlen_count: + cmp byte [rsi+rbx], 0 + je __xlen_exit + inc rbx + jne __xlen_count + + __xlen_exit: + mov rax, rbx + pop rbp + ret + + ;; This will not work on Windoze. Change the macro LEA and CALL maybe. + global main + main: + prolog 4*8 + xlea rdi, s1 + call xstrlen + xlea rsi, rax ;;RDX - windoze ABI + xlea rdi, p_tpl ;;RCX - windoze ABI + xcall printf + xor edi, edi + xcall exit + epilog 4*8 ;;Never gets here but w/e. + ret + +section .rodata + s1 db "Good luck getting the stuff below this to assemble.",13,10,0 + p_tpl db "len: %i",13,10,0 diff --git a/Task/String-length/X86-64-Assembly/string-length-2.x86-64 b/Task/String-length/X86-64-Assembly/string-length-2.x86-64 new file mode 100644 index 0000000000..049fb4745d --- /dev/null +++ b/Task/String-length/X86-64-Assembly/string-length-2.x86-64 @@ -0,0 +1,182 @@ +; compute string length +; assembly X86 window +; download and install visual studio 2022 free site microsoft +; search and open X64 native tools command prompt +; compil and link program with this command : +; ml64 lenString.asm /link /ENTRY:main /SUBSYSTEM:console kernel32.lib user32.lib Shell32.lib +; this program respects the 64-bit calling convention : +; registers arguments : rcx rdx r8 r9 and stack +; registers saved : rbx,rbp,rdi,rsi, r12-r15 +; ATTENTION les registres rax,rcx,rdx,r8-r11 peuvent être +; perdus lors d'un appel de fonction +;********************************* +; constantes +;********************************* +STD_OUTPUT_HANDLE equ -11 +BUFFERSIZE equ 200 +;********************************* +; macros +;********************************* +;for this file, see task include a file for X86-64 language +include macrosInclude.asm + +;********************************* +; user data +;********************************* +.data +szMesslength db "The lenght of string ",0 +LGMESSLEN equ $ - szMesslength - 1 +szMesslength1 db " is ",0 +LGMESSLEN1 equ $ - szMesslength1 - 1 + +szCarriageReturn db 10,0 + +szString1 db "Apple",0 +LGSTRING1 equ $ - szString1 - 1 +szString2 db "Orange",0 +LGSTRING2 equ $ - szString2 - 1 + +align 8 + +hConsole dq 0 +sConvArea db 24 dup (0) +sBuffer db BUFFERSIZE dup (' ') +;********************************* +; user code fonction principale +;********************************* +.code + +extern WriteFile : proc, GetStdHandle : proc, ExitProcess : proc +extern GetLastError : proc + +main PROC public + displayLib "Program X86-64 start." + + mov rcx, offset szMesslength + mov rdx,LGMESSLEN + call afficherConsole + mov rcx, offset szString1 + mov rdx,LGSTRING1 + call afficherConsole + mov rcx, offset szMesslength1 + mov rdx,LGMESSLEN1 + call afficherConsole + mov rcx, offset szString1 + call lenString ; compute length + mov rcx,rax + mov rdx, offset sConvArea + call conversion10 + mov rdx,rax ; result size + mov rcx, offset sConvArea + call afficherConsole + mov rcx, offset szCarriageReturn + mov rdx,1 + call afficherConsole + + mov rcx, offset szMesslength + mov rdx,LGMESSLEN + call afficherConsole + mov rcx, offset szString1 + mov rdx,LGSTRING1 + call afficherConsole + mov rcx, offset szMesslength1 + mov rdx,LGMESSLEN1 + call afficherConsole + mov rcx, offset szString1 + call lenString2 ; other compute methode + mov rcx,rax + mov rdx, offset sConvArea + call conversion10 + mov rdx,rax ; result size + mov rcx, offset sConvArea + call afficherConsole + mov rcx, offset szCarriageReturn + mov rdx,1 + call afficherConsole + + + mov rcx, offset szMesslength + mov rdx,LGMESSLEN + call afficherConsole + mov rcx, offset szString1 + mov rdx,LGSTRING1 + call afficherConsole + mov rcx, offset szMesslength1 + mov rdx,LGMESSLEN1 + call afficherConsole + mov rcx,LGSTRING1 ; direct value for static string + mov rdx, offset sConvArea + call conversion10 + mov rdx,rax ; result size + mov rcx, offset sConvArea + call afficherConsole + mov rcx, offset szCarriageReturn + mov rdx,1 + call afficherConsole + + mov rcx, offset szMesslength + mov rdx,LGMESSLEN + call afficherConsole + mov rcx, offset szString2 + mov rdx,LGSTRING2 + call afficherConsole + mov rcx, offset szMesslength1 + mov rdx,LGMESSLEN1 + call afficherConsole + mov rcx, offset szString2 + call lenString ; compute length + mov rcx,rax + mov rdx, offset sConvArea + call conversion10 + mov rdx,rax ; result size + mov rcx, offset sConvArea + call afficherConsole + mov rcx, offset szCarriageReturn + mov rdx,1 + call afficherConsole + +finProgramme: + displayLib "Program end." + sub rsp,28h + mov rcx,0 ; return code + call ExitProcess +main ENDP + +;*************************************************** +;compute string length +;**************************************************** +; rcx : string address +lenString PROC + mov rax,0 ; counter init +@B1: + mov dl,[rax+rcx] ; load one byte of string + cmp dl,0 ; zero final ? + je @B2 ; yes -> end + inc rax ; increment counter + jmp @B1 ; and loop +@B2: + ret +lenString ENDP +;*************************************************** +;compute string length other method +;**************************************************** +; rcx : string address +lenString2 PROC + push rdi + xor rax,rax ; raz rax + mov rdi,rcx ; move string address + mov rcx,-1 ; init rcx + cld ; direction flag to zero + repne scasb ; repeat comparaison one character + not rcx ; ??? + dec rcx ; ??? + mov rax,rcx ; return result + pop rdi + ret +lenString2 ENDP + + +;for this file, see task include a file for X86-64 language +include routinesInclude.asm + +end diff --git a/Task/String-matching/Ada/string-matching.adb b/Task/String-matching/Ada/string-matching.adb new file mode 100644 index 0000000000..58dd623b2d --- /dev/null +++ b/Task/String-matching/Ada/string-matching.adb @@ -0,0 +1,20 @@ +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Match_Strings is + S1 : constant String := "abcd"; + S2 : constant String := "abab"; + S3 : constant String := "ab"; +begin + if S1'Length >= S3'Length and then S1 (S1'First..S1'First + S3'Length - 1) = S3 then + Put_Line (''' & S1 & "' starts with '" & S3 & '''); + end if; + if S2'Length >= S3'Length and then S2 (S2'Last - S3'Length + 1..S2'Last) = S3 then + Put_Line (''' & S2 & "' ends with '" & S3 & '''); + end if; + Put_Line (''' & S3 & "' first appears in '" & S1 & "' at" & Integer'Image (Index (S1, S3))); + Put_Line + ( ''' & S3 & "' appears in '" & S2 & ''' & + Integer'Image (Ada.Strings.Fixed.Count (S2, S3)) & " times" + ); +end Match_Strings; diff --git a/Task/String-matching/AutoIt/string-matching.au3 b/Task/String-matching/AutoIt/string-matching.au3 new file mode 100644 index 0000000000..fa7682fa58 --- /dev/null +++ b/Task/String-matching/AutoIt/string-matching.au3 @@ -0,0 +1,29 @@ +$string1 = "arduinoardblobard" +$string2 = "ard" + +; == Determining if the first string starts with second string +If StringLeft($string1, StringLen($string2)) = $string2 Then + ConsoleWrite("1st string starts with 2nd string." & @CRLF) +Else + ConsoleWrite("1st string does'nt starts with 2nd string." & @CRLF) +EndIf + +; == Determining if the first string contains the second string at any location +; == Print the location of the match for part 2 +; == Handle multiple occurrences of a string for part 2 +$start = 1 +$count = 0 +$pos = StringInStr($string1, $string2) +While $pos + $count += 1 + ConsoleWrite("1st string contains 2nd string at position: " & $pos & @CRLF) + $pos = StringInStr($string1, $string2, 0, 1, $start + $pos + StringLen($string2)) +WEnd +If $count = 0 Then ConsoleWrite("1st string does'nt contain 2nd string." & @CRLF) + +; == Determining if the first string ends with the second string +If StringRight($string1, StringLen($string2)) = $string2 Then + ConsoleWrite("1st string ends with 2nd string." & @CRLF) +Else + ConsoleWrite("1st string does'nt ends with 2nd string." & @CRLF) +EndIf diff --git a/Task/String-matching/Batch-File/string-matching-1.bat b/Task/String-matching/Batch-File/string-matching-1.bat new file mode 100644 index 0000000000..509c12c672 --- /dev/null +++ b/Task/String-matching/Batch-File/string-matching-1.bat @@ -0,0 +1,70 @@ +::NOTE #1: This implementation might crash, or might not work properly if +::you put some of the CMD special characters (ex. %,!, etc) inside the strings. +:: +::NOTE #2: The comparisons here are case-SENSITIVE. +::NOTE #3: Spaces in strings are considered. + +@echo off +setlocal enabledelayedexpansion + +::The main things... +set "str1=qwertyuiop" +set "str2=qwerty" +call :str2_lngth +call :matchbegin + +set "str1=qweiuoiocghiioyiocxiisfguiioiuygvd" +set "str2=io" +call :str2_lngth +call :matchcontain + +set "str1=blablabla" +set "str2=bbla" +call :str2_lngth +call :matchend + +echo. +pause +exit /b 0 +::/The main things. + +::The functions... +:matchbegin +echo. +if "!str1:~0,%length%!"=="!str2!" ( + echo "%str1%" begins with "%str2%". +) else ( + echo "%str1%" does not begin with "%str2%". +) +goto :EOF + +:matchcontain +echo. +set curr=0&set exist=0 +:scanchrloop +if "!str1:~%curr%,%length%!"=="" ( + if !exist!==0 echo "%str1%" does not contain "%str2%". + goto :EOF +) +if "!str1:~%curr%,%length%!"=="!str2!" ( + echo "%str1%" contains "%str2%". ^(in Position %curr%^) + set exist=1 +) +set /a curr+=1&goto scanchrloop + +:matchend +echo. +if "!str1:~-%length%!"=="!str2!" ( + echo "%str1%" ends with "%str2%". +) else ( + echo "%str1%" does not end with "%str2%". +) +goto :EOF + +:str2_lngth +set length=0 +:loop +if "!str2:~%length%,1!"=="" goto :EOF +set /a length+=1 +goto loop +::/The functions. diff --git a/Task/String-matching/Batch-File/string-matching-2.bat b/Task/String-matching/Batch-File/string-matching-2.bat new file mode 100644 index 0000000000..29846d0685 --- /dev/null +++ b/Task/String-matching/Batch-File/string-matching-2.bat @@ -0,0 +1,12 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +set /p a= +set /p b= +set /a i=0 +for %%i in (^^%b% %b% %b%$) do ( +echo/%a% | findstr /rc:"%%i" >nul 2>nul && set contain.!i!=Yes|| set contain.!i!=No +set /a i+=1 +) +echo "%a%" starts with "%b%": %contain.0% +echo "%a%" ends with "%b%": %contain.1% +echo "%a%" contains "%b%": %contain.2% diff --git a/Task/String-matching/Batch-File/string-matching-3.bat b/Task/String-matching/Batch-File/string-matching-3.bat new file mode 100644 index 0000000000..3cc9e500f1 --- /dev/null +++ b/Task/String-matching/Batch-File/string-matching-3.bat @@ -0,0 +1,15 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +set /p a= +set /p b= +set "macroset=(set contain.M=Yes) else (set contain.M=No)" +:: https://ss64.com/nt/syntax-replace.html +call set "t=%%a:%b%=#%%" +if "#"=="%t:~0,1%" %macroset:M=0% +call set "t=%%a:*%b%=%%" +if ""=="%t%" %macroset:M=1% +call set "t=%%a:%b%=%%" +if not "%a%"=="%t%" %macroset:M=2% +echo "%a%" starts with "%b%": %contain.0% +echo "%a%" ends with "%b%": %contain.1% +echo "%a%" contains "%b%": %contain.2% diff --git a/Task/String-matching/Batch-File/string-matching-4.bat b/Task/String-matching/Batch-File/string-matching-4.bat new file mode 100644 index 0000000000..da10e75e97 --- /dev/null +++ b/Task/String-matching/Batch-File/string-matching-4.bat @@ -0,0 +1,16 @@ +@echo off +setlocal enableextensions enabledelayedexpansion +set /p a= +set /p b= +call :getres startsWith.bat "%a%" "%b%" +echo "%a%" starts with "%b%": %result% +call :getres endsWith.bat "%a%" "%b%" +echo "%a%" ends with "%b%": %result% +set idx= +call indexOf.bat "%a%" "%b%" idx +echo "%a%" contains "%b%" at: %idx% +goto:eof + +:getres +call %1 %2 %3 && set result=No||set result=Yes +goto:eof diff --git a/Task/String-matching/Crystal/string-matching.cr b/Task/String-matching/Crystal/string-matching.cr new file mode 100644 index 0000000000..6660844e25 --- /dev/null +++ b/Task/String-matching/Crystal/string-matching.cr @@ -0,0 +1,12 @@ +p "banana".starts_with? "ba" #=> true +p "banana".starts_with? "na" #=> false + +p "banana".includes? "an" #=> true +p "banana".includes? "xa" #=> false + +p "banana".ends_with? "na" #=> true +p "banana".ends_with? "ba" #=> false + +p "banana".index "na" #=> 2 +p "banana".index "na", 3 #=> 4 +p "banana".index "na", 5 #=> nil diff --git a/Task/String-matching/Emacs-Lisp/string-matching.el b/Task/String-matching/Emacs-Lisp/string-matching.el new file mode 100644 index 0000000000..1e2f57543b --- /dev/null +++ b/Task/String-matching/Emacs-Lisp/string-matching.el @@ -0,0 +1,14 @@ +(defun string-contains (needle haystack) + (string-match (regexp-quote needle) haystack)) + +(string-prefix-p "before" "before center after") ;=> t +(string-contains "before" "before center after") ;=> 0 +(string-suffix-p "before" "before center after") ;=> nil + +(string-prefix-p "center" "before center after") ;=> nil +(string-contains "center" "before center after") ;=> 7 +(string-suffix-p "center" "before center after") ;=> nil + +(string-prefix-p "after" "before center after") ;=> nil +(string-contains "after" "before center after") ;=> 14 +(string-suffix-p "after" "before center after") ;=> t diff --git a/Task/String-matching/Euphoria/string-matching.eu b/Task/String-matching/Euphoria/string-matching.eu new file mode 100644 index 0000000000..cc361a5961 --- /dev/null +++ b/Task/String-matching/Euphoria/string-matching.eu @@ -0,0 +1,30 @@ +sequence first, second +integer x + +first = "qwertyuiop" + +-- Determining if the first string starts with second string +second = "qwerty" +if match(second, first) = 1 then + printf(1, "'%s' starts with '%s'\n", {first, second}) +else + printf(1, "'%s' does not start with '%s'\n", {first, second}) +end if + +-- Determining if the first string contains the second string at any location +-- Print the location of the match for part 2 +second = "wert" +x = match(second, first) +if x then + printf(1, "'%s' contains '%s' at position %d\n", {first, second, x}) +else + printf(1, "'%s' does not contain '%s'\n", {first, second}) +end if + +-- Determining if the first string ends with the second string +second = "uio" +if length(second)<=length(first) and match_from(second, first, length(first)-length(second)+1) then + printf(1, "'%s' ends with '%s'\n", {first, second}) +else + printf(1, "'%s' does not end with '%s'\n", {first, second}) +end if diff --git a/Task/String-matching/Factor/string-matching.factor b/Task/String-matching/Factor/string-matching.factor new file mode 100644 index 0000000000..da85d62ed7 --- /dev/null +++ b/Task/String-matching/Factor/string-matching.factor @@ -0,0 +1,11 @@ +/* Does cheesecake start with cheese? */ +"cheesecake" "cheese" head? ! t +/* Does cheesecake contain sec at any location? */ +"sec" "cheesecake" subseq? ! t +/* Does cheesecake end with cake? */ +"cheesecake" "cake" tail? ! t +/* Where in cheesecake is the leftmost sec? */ +"sec" "cheesecake" subseq-start ! 4 +/* Where in Mississippi are all occurrences of iss? */ +USE: regexp +"Mississippi" "iss" all-matching-slices [ from>> ] map ! { 1 4 } diff --git a/Task/String-matching/Frink/string-matching.frink b/Task/String-matching/Frink/string-matching.frink new file mode 100644 index 0000000000..15ac6dbd5c --- /dev/null +++ b/Task/String-matching/Frink/string-matching.frink @@ -0,0 +1,20 @@ +s1 = "string" +s2 = "str" +s3 = "ing" +s4 = "xyz" + +println["$s1 starts with $s2: " + startsWith[s1, s2]] +println["$s1 starts with $s4: " + startsWith[s1, s4]] +println["$s1 ends with $s3: " + endsWith[s1, s3]] +println["$s1 ends with $s4: " + endsWith[s1, s4]] +position[s1, s2] +position[s1, s4] + +position[s1, s2] := +{ + pos = indexOf[s1,s2] + if pos == -1 + println["$s1 does not contain $s2"] + else + println["$s1 contains $s2 at position $pos"] +} diff --git a/Task/String-matching/M2000-Interpreter/string-matching.m2000 b/Task/String-matching/M2000-Interpreter/string-matching.m2000 new file mode 100644 index 0000000000..ed547713b1 --- /dev/null +++ b/Task/String-matching/M2000-Interpreter/string-matching.m2000 @@ -0,0 +1,15 @@ +Module StringMatch { + A$="Hello World" + Print A$ ~ "Hello*" + Print A$ ~ "*llo*" + p=Instr(A$, "llo") + Print p=3 + \\ Handle multiple occurance for "o" + p=Instr(A$, "o") + While p > 0 { + Print "position:";p;{ for "o"} + p=Instr(A$, "o", p+1) + } + Print A$ ~ "*orld" +} +StringMatch diff --git a/Task/String-matching/OCaml/string-matching.ml b/Task/String-matching/OCaml/string-matching.ml new file mode 100644 index 0000000000..46769d4d39 --- /dev/null +++ b/Task/String-matching/OCaml/string-matching.ml @@ -0,0 +1,86 @@ +let match1 s1 s2 = + let len1 = String.length s1 + and len2 = String.length s2 in + if len1 < len2 then false else + let sub = String.sub s1 0 len2 in + (sub = s2) + +(* testing in the top-level: + + # match1 "Hello" "Hello World!" ;; + - : bool = false + # match1 "Hello World!" "Hello" ;; + - : bool = true +*) + +let match2 s1 s2 = + let len1 = String.length s1 + and len2 = String.length s2 in + if len1 < len2 then false else + let rec aux i = + if i < 0 then false else + let sub = String.sub s1 i len2 in + if (sub = s2) then true else aux (pred i) + in + aux (len1 - len2) + +(* + # match2 "It's raining, Hello World!" "umbrella" ;; + - : bool = false + # match2 "It's raining, Hello World!" "Hello" ;; + - : bool = true +*) + +let match3 s1 s2 = + let len1 = String.length s1 + and len2 = String.length s2 in + if len1 < len2 then false else + let sub = String.sub s1 (len1 - len2) len2 in + (sub = s2) + +(* + # match3 "Hello World" "Hello" ;; + - : bool = false + # match3 "Hello World" "World" ;; + - : bool = true +*) + +let match2_loc s1 s2 = + let len1 = String.length s1 + and len2 = String.length s2 in + if len1 < len2 then (false, -1) else + let rec aux i = + if i < 0 then (false, -1) else + let sub = String.sub s1 i len2 in + if (sub = s2) then (true, i) else aux (pred i) + in + aux (len1 - len2) + +(* + # match2_loc "The sun's shining, Hello World!" "raining" ;; + - : bool * int = (false, -1) + # match2_loc "The sun's shining, Hello World!" "shining" ;; + - : bool * int = (true, 10) +*) + +let match2_num s1 s2 = + let len1 = String.length s1 + and len2 = String.length s2 in + if len1 < len2 then (false, 0) else + let rec aux i n = + if i < 0 then (n <> 0, n) else + let sub = String.sub s1 i len2 in + if (sub = s2) + then aux (pred i) (succ n) + else aux (pred i) (n) + in + aux (len1 - len2) 0 + +(* + # match2_num "This cloud looks like a camel, \ + that other cloud looks like a llama" "stone" ;; + - : bool * int = (false, 0) + # match2_num "This cloud looks like a camel, \ + that other cloud looks like a llama" "cloud" ;; + - : bool * int = (true, 2) +*) diff --git a/Task/String-matching/PL-I/string-matching.pli b/Task/String-matching/PL-I/string-matching.pli new file mode 100644 index 0000000000..685b86ba74 --- /dev/null +++ b/Task/String-matching/PL-I/string-matching.pli @@ -0,0 +1,32 @@ +/* Let s be one string, t be the other that might exist within s. */ + /* 8-1-2011 */ +k = index(s, t); +if k = 0 then put skip edit (t, ' is nowhere in sight') (a); +else if k = 1 then + put skip edit (t, ' starts at the beginning of ', s) (a); +else if k+length(t)-1 = length(s) then + put skip edit (t, ' is at the end of ', s) (a); +else put skip edit (t, ' is within ', s) (a); + +if k > 0 then put skip edit (t, ' starts at position ', k) (a); + +/* Optional extra: Handle multiple occurrences. */ + n = 1; + do forever; + k = index(s, t, n); + if k = 0 then + do; + if n = 1 then put skip list (t, ' is nowhere in sight'); + stop; + end; + else if k = 1 then + put skip edit ('<', t, '> starts at the beginning of ', s) (a); + else if k+length(t)-1 = length(s) then + put skip edit ('<', t, '> is at the end of ', s) (a); + else put skip edit ('<', t, '> is within ', s) (a); + n = k + length(t); + + if k > 0 then + put skip edit ('<', t, '> starts at position ', trim(k)) (a); + else stop; + end; diff --git a/Task/String-matching/Perl/string-matching.pl b/Task/String-matching/Perl/string-matching.pl new file mode 100644 index 0000000000..38bc98e5ce --- /dev/null +++ b/Task/String-matching/Perl/string-matching.pl @@ -0,0 +1,21 @@ +# Using regexes: + +$str1 =~ /^\Q$str2\E/ # true if $str1 starts with $str2 +$str1 =~ /\Q$str2\E/ # true if $str1 contains $str2 +$str1 =~ /\Q$str2\E$/ # true if $str1 ends with $str2 + +# Using index: + +index($str1, $str2) == 0 # true if $str1 starts with $str2 +index($str1, $str2) != -1 # true if $str1 contains $str2 +rindex($str1, $str2) == length($str1) - length($str2) # true if $str1 ends with $str2 + +# Using substr: + +substr($str1, 0, length($str2)) eq $str2 # true if $str1 starts with $str2 +substr($str1, - length($str2)) eq $str2 # true if $str1 ends with $str2 + +# Bonus task (printing all positions where $str2 appears in $str1): + +print $-[0], "\n" while $str1 =~ /\Q$str2\E/g; # using a regex +my $i = -1; print $i, "\n" while ($i = index $str1, $str2, $i + 1) != -1; # using index diff --git a/Task/String-matching/Pluto/string-matching.pluto b/Task/String-matching/Pluto/string-matching.pluto new file mode 100644 index 0000000000..3e63c2f1ed --- /dev/null +++ b/Task/String-matching/Pluto/string-matching.pluto @@ -0,0 +1,18 @@ +local s = "abracadabra" +local t = "abra" +local u = "ra" +local v = "cad" +print($"'{s}' starts with '{t}' is {s:startswith(t)}") +local indices = {} +local start = 1 +while true do + local ix = s:find(u, start, true) + if ix then + indices:insert(ix) + start = ix + #u + if start > #s then break end + else break end +end +local contained = #indices > 0 +print($"'{s}' contains '{u}' is {contained} {contained ? $"at indices {indices:concat(", ")}" : ""}") +print($"'{s}' ends with '{v}' is {s:endswith(v)}") diff --git a/Task/String-matching/PowerShell/string-matching.ps1 b/Task/String-matching/PowerShell/string-matching.ps1 new file mode 100644 index 0000000000..fd2cff175f --- /dev/null +++ b/Task/String-matching/PowerShell/string-matching.ps1 @@ -0,0 +1,5 @@ +"spicywiener".StartsWith("spicy") +"spicywiener".Contains("icy") +"spicywiener".EndsWith("wiener") +"spicywiener".IndexOf("icy") +[regex]::Matches("spicywiener", "i").count diff --git a/Task/String-matching/PureBasic/string-matching.basic b/Task/String-matching/PureBasic/string-matching.basic new file mode 100644 index 0000000000..6ecbd22bfc --- /dev/null +++ b/Task/String-matching/PureBasic/string-matching.basic @@ -0,0 +1,74 @@ +Procedure StartsWith(String1$, String2$) + Protected Result + If FindString(String1$, String2$, 1) =1 ; E.g Found in possition 1 + Result =CountString(String1$, String2$) + EndIf + ProcedureReturn Result +EndProcedure + +Procedure EndsWith(String1$, String2$) + Protected Result, dl=Len(String1$)-Len(String2$) + If dl>=0 And Right(String1$, Len(String2$))=String2$ + Result =CountString(String1$, String2$) + EndIf + ProcedureReturn Result +EndProcedure + +; And a verification + +If OpenConsole() + PrintN(Str(StartsWith("Rosettacode", "Rosetta"))) ; = 1 + PrintN(Str(StartsWith("Rosettacode", "code"))) ; = 0 + PrintN(Str(StartsWith("eleutherodactylus cruralis", "e"))) ; = 3 + PrintN(Str(EndsWith ("Rosettacode", "Rosetta"))) ; = 0 + PrintN(Str(EndsWith ("Rosettacode", "code"))) ; = 1 + PrintN(Str(EndsWith ("Rosettacode", "e"))) ; = 2 + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf + +; An alternate and more complete solution: + +Procedure startsWith(string1$, string2$) + ;returns one if string1$ starts with string2$, otherwise returns zero + If FindString(string1$, string2$, 1) = 1 + ProcedureReturn 1 + EndIf + ProcedureReturn 0 +EndProcedure + +Procedure contains(string1$, string2$, location = 0) + ;returns the location of the next occurrence of string2$ in string1$ starting from location, + ;or zero if no remaining occurrences of string2$ are found in string1$ + ProcedureReturn FindString(string1$, string2$, location + 1) +EndProcedure + +Procedure endsWith(string1$, string2$) + ;returns one if string1$ ends with string2$, otherwise returns zero + Protected ls = Len(string2$) + If Len(string1$) - ls >= 0 And Right(string1$, ls) = string2$ + ProcedureReturn 1 + EndIf + ProcedureReturn 0 +EndProcedure + +If OpenConsole() + PrintN(Str(startsWith("RosettaCode", "Rosetta"))) ; = 1, true + PrintN(Str(startsWith("RosettaCode", "Code"))) ; = 0, false + + PrintN("") + PrintN(Str(contains("RosettaCode", "luck"))) ; = 0, no occurrences + Define location + Repeat + location = contains("eleutherodactylus cruralis", "e", location) + PrintN(Str(location)) ;display each occurrence: 1, 3, 7, & 0 (no more occurrences) + Until location = 0 + + PrintN("") + PrintN(Str(endsWith ("RosettaCode", "Rosetta"))) ; = 0, false + PrintN(Str(endsWith ("RosettaCode", "Code"))) ; = 1, true + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/String-matching/RISC-V-Assembly/string-matching.asm b/Task/String-matching/RISC-V-Assembly/string-matching.asm new file mode 100644 index 0000000000..970a757a73 --- /dev/null +++ b/Task/String-matching/RISC-V-Assembly/string-matching.asm @@ -0,0 +1,271 @@ +# riscv assembly raspberry pico2 rp2350 +# program matchstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessErrorString: .asciz "Error search string empty " +szMessFound: .asciz "String found. \n" +szMessFoundPos: .asciz "String found at position " +szMessNotFound: .asciz "String not found. \n" +szString: .asciz "abcdefghijklmnopqrstuvwxyz" +szString2: .asciz "abc" +szStringStart: .asciz "abcd" +szStringEnd: .asciz "xyz" +szStringStart2: .asciz "abcd" +szStringEnd2: .asciz "xabc" +szString3: .asciz "abcdefddddehdezdedede" +szStringSer: .asciz "deh" +szCarriageReturn: .asciz "\n" + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sConvArea: .skip 24 +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szString # address input string + la a1,szStringStart # address search string + call searchStringDeb # Determining if the first string starts with second string + blez a0,1f + + la a0,szMessFound # display message + call writeString + j 2f +1: + la a0,szMessNotFound + call writeString +2: + + la a0,szString # address input string + la a1,szStringEnd # address search string + call searchStringEnd # Determining if the first string end with second string + blez a0,3f + + la a0,szMessFound # display message + call writeString + j 4f +3: + la a0,szMessNotFound + call writeString +4: + + la a0,szString # address input string + la a1,szStringEnd # address search string + call searchSubString # search string + bltz a0,5f # < 0 + + la a1,sConvArea + call conversion10 + la a0,szMessFoundPos # display message + call writeString + la a0,sConvArea # display position + call writeString + la a0,szCarriageReturn + call writeString + + j 6f +5: + la a0,szMessNotFound + call writeString +6: + + la a0,szString3 # address input string + la a1,szStringSer # address search string + call searchSubString # search string + bltz a0,7f # < 0 + + la a1,sConvArea + call conversion10 + la a0,szMessFoundPos # display message + call writeString + la a0,sConvArea # display position + call writeString + la a0,szCarriageReturn + call writeString + + j 8f +7: + la a0,szMessNotFound + call writeString +8: + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b +/***************************************************/ +/* search string at beguining */ +/***************************************************/ +# a0 contains string +# a1 contains search string +# a0 returns 1 if find or 0 if not or -1 if error +searchStringDeb: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t1,0 # init counter + add t0,a1,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,99f # empty string -> error +1: # loop to copy string begin + add t0,a0,t1 # compute byte address string 1 + lbu t3,(t0) # load byte string + beqz t3,2f # zero final ? -> not found + bne t3,t2,2f # not equal + addi t1,t1,1 + add t0,a1,t1 # compute byte address search string + lbu t2,(t0) # load byte string + bnez t2,1b # not end search string -> loop + li a0,1 # else string founded + j 100f +2: + li a0,0 + j 100f + +99: # error + la a0,szMessErrorString + call writeString # display message + li a0,-1 # error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/***************************************************/ +/* search string at end first string */ +/***************************************************/ +# a0 contains string +# a1 contains search string +# a0 returns 1 if find or 0 if not or -1 if error +searchStringEnd: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t1,0 # init counter +1: # loop to search end search string + add t0,a1,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,2f # zero final + addi t1,t1,1 # increment indice + j 1b # and loop +2: + beqz t1,99f # empty string -> error + li t3,0 +3: # loop to search end string + add t0,a0,t3 # compute byte address string 1 + lbu t4,(t0) # load byte string + beqz t4,4f # zero final ? + addi t3,t3,1 + j 3b +4: + beqz t3,7f # empty string -> not found +5: + addi t1,t1,-1 + bltz t1,6f # begin search string -> found + add t0,a1,t1 # compute byte address + lbu t2,(t0) # load byte string + addi t3,t3,-1 + bltz t3,7f # begin string -> not found + add t0,a0,t3 # compute byte address string 1 + lbu t4,(t0) # load byte string + bne t4,t2,7f # not equal + j 5b +6: + li a0,1 # string founded + j 100f +7: # string not found + li a0,0 + j 100f + +99: # error + la a0,szMessErrorString + call writeString # display message + li a0,-1 # error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/***************************************************/ +/* search string in string */ +/***************************************************/ +# a0 contains string +# a1 contains search string +# a0 returns 1 if find or 0 if not or -1 if error +searchSubString: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t3,0 +1: + li t5,-1 # indice find ok + li t1,0 # init counter + add t0,a1,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,99f # empty string -> error +2: # loop to copy string begin + add t0,a0,t3 # compute byte address string 1 + lbu t4,(t0) # load byte string + beqz t4,5f # zero final ? + bne t4,t2,3f # not equal + addi t5,t5,1 # increment indice find + addi t3,t3,1 # increment indice string + addi t1,t1,1 # increment indice search string + add t0,a1,t1 # compute byte address + lbu t2,(t0) # load byte string + beqz t2,6f # end search string -> found + j 2b # else loop +3: + bltz t5,4f # not characters precedent found ? + sub t3,t3,t5 # yes raz position search + #addi t3,t3,1 + j 1b # and restart search at begining +4: + addi t3,t3,1 # increment indice + j 2b # and loop other character +5: + li a0,-1 # not found + j 100f + +6: + sub a0,t3,t5 # string found + addi a0,a0,-1 + j 100f +99: # error + la a0,szMessErrorString + call writeString # display message + li a0,-2 # error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-matching/Raku/string-matching.raku b/Task/String-matching/Raku/string-matching.raku new file mode 100644 index 0000000000..b363ebe886 --- /dev/null +++ b/Task/String-matching/Raku/string-matching.raku @@ -0,0 +1,21 @@ +# Using string methods: + +$haystack.starts-with($needle) # True if $haystack starts with $needle +$haystack.contains($needle) # True if $haystack contains $needle +$haystack.ends-with($needle) # True if $haystack ends with $needle + +# Using regexes: + +so $haystack ~~ /^ $needle / # True if $haystack starts with $needle +so $haystack ~~ / $needle / # True if $haystack contains $needle +so $haystack ~~ / $needle $/ # True if $haystack ends with $needle + +# Using substr: + +substr($haystack, 0, $needle.chars) eq $needle # True if $haystack starts with $needle +substr($haystack, *-$needle.chars) eq $needle # True if $haystack ends with $needle + +# Bonus task: + +$haystack.match($needle, :g)».from; # List of all positions where $needle appears in $haystack +$haystack.indices($needle :overlap); # Also find any overlapping instances of $needle in $haystack diff --git a/Task/String-matching/Sed/string-matching.sed b/Task/String-matching/Sed/string-matching.sed new file mode 100644 index 0000000000..5768bd973b --- /dev/null +++ b/Task/String-matching/Sed/string-matching.sed @@ -0,0 +1,11 @@ +# 1. Determining if the first string starts with the second string: + +N;/^\(.*\).*\n\1$/!d;s/\n.*// + +# 2. Determining if the first string contains the second string at any location: + +N;/.*\(.*\).*\n\1$/!d;s/\n.*// + +# 3. Determining if the first string ends with the second string: + +N;/\(.*\)\n\1$/!d;s/\n.*// diff --git a/Task/String-matching/VBScript/string-matching.vbs b/Task/String-matching/VBScript/string-matching.vbs new file mode 100644 index 0000000000..9ce40a09c6 --- /dev/null +++ b/Task/String-matching/VBScript/string-matching.vbs @@ -0,0 +1,43 @@ +Function StartsWith(s1,s2) + StartsWith = False + If Left(s1,Len(s2)) = s2 Then + StartsWith = True + End If +End Function + +Function Contains(s1,s2) + Contains = False + If InStr(1,s1,s2) Then + Contains = True & " at positions " + j = 1 + Do Until InStr(j,s1,s2) = False + Contains = Contains & InStr(j,s1,s2) & ", " + If j = 1 Then + If Len(s2) = 1 Then + j = j + InStr(j,s1,s2) + Else + j = j + (InStr(j,s1,s2) + (Len(s2) - 1)) + End If + Else + If Len(s2) = 1 Then + j = j + ((InStr(j,s1,s2) - j) + 1) + Else + j = j + ((InStr(j,s1,s2) - j) + (Len(s2) - 1)) + End If + End If + Loop + End If +End Function + +Function EndsWith(s1,s2) + EndsWith = False + If Right(s1,Len(s2)) = s2 Then + EndsWith = True + End If +End Function + +WScript.StdOut.Write "Starts with test, 'foo' in 'foobar': " & StartsWith("foobar","foo") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Contains test, 'o' in 'fooooobar': " & Contains("fooooobar","o") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Ends with test, 'bar' in 'foobar': " & EndsWith("foobar","bar") diff --git a/Task/String-prepend/ARM-Assembly/string-prepend.arm b/Task/String-prepend/ARM-Assembly/string-prepend.arm new file mode 100644 index 0000000000..8720b43d90 --- /dev/null +++ b/Task/String-prepend/ARM-Assembly/string-prepend.arm @@ -0,0 +1,120 @@ +/* ARM assembly Raspberry PI */ +/* program preend.s */ +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ NBCARLIBEL, 45 +.equ BUFFERSIZE, 100 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szCarriageReturn: .asciz "\n" +szMessFinOK: .asciz "Program normal end. \n" +szMessString: .asciz "British Museum.\n" +szStringStart: .asciz "The rosetta stone is at " +szMessErrSize: .asciz "Buffer error size too small.\n" + +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 4 + +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess + + ldr r0,iAdrszMessString + ldr r1,iAdrszStringStart + ldr r2,iAdrsBuffer + mov r3,#BUFFERSIZE + bl prepend // preend string1 to string2 + cmp r0,#-1 + beq 100f + ldr r0,iAdrszMessString + bl affichageMess + + ldr r0,iAdrsBuffer + bl affichageMess + + ldr r0,iAdrszMessFinOK + bl affichageMess + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessString: .int szMessString +iAdrszStringStart: .int szStringStart +iAdrsBuffer: .int sBuffer + +/**************************************************/ +/* preend two strings */ +/**************************************************/ +/* r0 contains the address of the string1 */ +/* r1 contains the address of the string2 */ +/* r2 contains buffer */ +/* r3 contains buffer size */ +prepend: + push {r4-r6,fp,lr} + mov r4,#0 // counter byte string 2 + mov r5,#0 // result byte counter +1: // copy string 2 in result area + ldrb r6,[r1,r4] + cmp r6,#0 + beq 2f + strb r6,[r2,r5] + add r4,r4,#1 // increment indice + add r5,r5,#1 // increment indice + cmp r5,r3 + bge 99f // error size + + b 1b // and loop +2: + mov r4,#0 // counter byte string1 +3: + ldrb r6,[r0,r4] + strb r6,[r2,r5] + cmp r6,#0 + beq 4f + add r4,r4,#1 // increment indice + add r5,r5,#1 // increment indice + cmp r5,r3 + bge 99f // error size + b 3b // and loop +4: + mov r0,r5 + b 100f +99: + ldr r0,iAdrszMessErrSize + bl affichageMess + mov r0,#-1 // error +100: + pop {r4-r6,fp,pc} +iAdrszMessErrSize: .int szMessErrSize +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/String-prepend/Ada/string-prepend.adb b/Task/String-prepend/Ada/string-prepend.adb new file mode 100644 index 0000000000..c4207896f8 --- /dev/null +++ b/Task/String-prepend/Ada/string-prepend.adb @@ -0,0 +1,8 @@ +with Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; + +procedure Prepend_String is + S: Unbounded_String := To_Unbounded_String("World!"); +begin + S := "Hello " & S;-- this is the operation to prepend "Hello " to S. + Ada.Text_IO.Put_Line(To_String(S)); +end Prepend_String; diff --git a/Task/String-prepend/COBOL/string-prepend-1.cob b/Task/String-prepend/COBOL/string-prepend-1.cob new file mode 100644 index 0000000000..982b49e678 --- /dev/null +++ b/Task/String-prepend/COBOL/string-prepend-1.cob @@ -0,0 +1,25 @@ + identification division. + program-id. prepend. + data division. + working-storage section. + 1 str pic x(30) value "World!". + 1 binary. + 2 len pic 9(4) value 0. + 2 scratch pic 9(4) value 0. + procedure division. + begin. + perform rev-sub-str + move function reverse ("Hello ") to str (len + 1:) + perform rev-sub-str + display str + stop run + . + + rev-sub-str. + move 0 to len scratch + inspect function reverse (str) + tallying scratch for leading spaces + len for characters after space + move function reverse (str (1:len)) to str + . + end program prepend. diff --git a/Task/String-prepend/COBOL/string-prepend-2.cob b/Task/String-prepend/COBOL/string-prepend-2.cob new file mode 100644 index 0000000000..36409a5ec4 --- /dev/null +++ b/Task/String-prepend/COBOL/string-prepend-2.cob @@ -0,0 +1,12 @@ + >>SOURCE FREE +PROGRAM-ID. prepend. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 str PIC X(30) VALUE "world!". + +PROCEDURE DIVISION. + MOVE FUNCTION CONCATENATE("Hello, ", str) TO str + DISPLAY str + . +END PROGRAM prepend. diff --git a/Task/String-prepend/Emacs-Lisp/string-prepend-1.el b/Task/String-prepend/Emacs-Lisp/string-prepend-1.el new file mode 100644 index 0000000000..61a01f7059 --- /dev/null +++ b/Task/String-prepend/Emacs-Lisp/string-prepend-1.el @@ -0,0 +1,3 @@ +(defvar str "bar") +(setq str (concat "foo" str)) +str ;=> "foobar" diff --git a/Task/String-prepend/Emacs-Lisp/string-prepend-2.el b/Task/String-prepend/Emacs-Lisp/string-prepend-2.el new file mode 100644 index 0000000000..1850466457 --- /dev/null +++ b/Task/String-prepend/Emacs-Lisp/string-prepend-2.el @@ -0,0 +1,5 @@ +(require 'cl-lib) + +(defvar str "bar") +(cl-callf2 concat "foo" str) +str ;=> "foobar" diff --git a/Task/String-prepend/Emacs-Lisp/string-prepend-3.el b/Task/String-prepend/Emacs-Lisp/string-prepend-3.el new file mode 100644 index 0000000000..b30e079679 --- /dev/null +++ b/Task/String-prepend/Emacs-Lisp/string-prepend-3.el @@ -0,0 +1,8 @@ +(let ((buf (get-buffer-create "*foo*"))) + (with-current-buffer buf + (insert "bar")) + (with-current-buffer buf + (goto-char (point-min)) + (insert "foo") + (buffer-string))) +;; => "foobar" diff --git a/Task/String-prepend/Gleam/string-prepend.gleam b/Task/String-prepend/Gleam/string-prepend.gleam new file mode 100644 index 0000000000..a1fccef435 --- /dev/null +++ b/Task/String-prepend/Gleam/string-prepend.gleam @@ -0,0 +1,2 @@ +let s = "world" + "Hello " <> s diff --git a/Task/String-prepend/Pluto/string-prepend.pluto b/Task/String-prepend/Pluto/string-prepend.pluto new file mode 100644 index 0000000000..500ae2f84f --- /dev/null +++ b/Task/String-prepend/Pluto/string-prepend.pluto @@ -0,0 +1,3 @@ +local s = "Code" +s = "Rosetta " .. s +print(s) diff --git a/Task/String-prepend/PowerShell/string-prepend.ps1 b/Task/String-prepend/PowerShell/string-prepend.ps1 new file mode 100644 index 0000000000..88f8bb054d --- /dev/null +++ b/Task/String-prepend/PowerShell/string-prepend.ps1 @@ -0,0 +1,3 @@ +$str = "World!" +$str = "Hello, " + $str +$str diff --git a/Task/String-prepend/RISC-V-Assembly/string-prepend.asm b/Task/String-prepend/RISC-V-Assembly/string-prepend.asm new file mode 100644 index 0000000000..3f1c193ebb --- /dev/null +++ b/Task/String-prepend/RISC-V-Assembly/string-prepend.asm @@ -0,0 +1,114 @@ +# riscv assembly raspberry pico2 rp2350 +# program preendstring.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ BUFFERSIZE, 100 +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEndOk: .asciz "Program riscv end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessErrorString: .asciz "Error buffer size." +szString: .asciz "British Museum." +szStringPreend: .asciz "The rosetta stone is at " + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +sBuffer: .skip BUFFERSIZE +.align 2 + +/**********************************************/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + + la a0,szString + call writeString # display message + la a0,szCariageReturn + call writeString + + la a0,szString # address string 1 + la a1,szStringPreend # address string 2 + la a2,sBuffer # result buffer + li a3,BUFFERSIZE + call preendString # + + la a0,sBuffer # result buffer + call writeString # display message + la a0,szCariageReturn + call writeString + + la a0,szMessEndOk # message address + call writeString # display message + call getchar +100: # final loop + j 100b +/***************************************************/ +/* search string at beguining */ +/***************************************************/ +# a0 contains string +# a1 contains search string +# a0 returns 1 if find or 0 if not or -1 if error +preendString: + addi sp, sp, -4 # reserve stack + sw ra, 0(sp) # save registers @ save registers + li t1,0 # init counter + li t2,0 +1: # copy string2 to result + add t0,a1,t1 # compute byte address + lbu t3,(t0) # load byte string + beqz t3,2f # zero final + add t0,a2,t1 # compute byte address result + sb t3,(t0) # store byte + addi t1,t1,1 + bge t1,a3,99f + j 1b +2: # copy string 1 to result + add t0,a0,t2 # compute byte address + lbu t3,(t0) # load byte string + add t0,a2,t1 # compute byte address result + sb t3,(t0) # store byte + beqz t3,3f # zero final + addi t2,t2,1 + addi t1,t1,1 + bge t1,a3,99f + j 2b +3: + mv a0,t1 # return total length + j 100f + +99: # error + la a0,szMessErrorString + call writeString # display message + li a0,-1 # error +100: + lw ra, 0(sp) + addi sp, sp, 4 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/String-prepend/VBScript/string-prepend.vbs b/Task/String-prepend/VBScript/string-prepend.vbs new file mode 100644 index 0000000000..df8157a3dd --- /dev/null +++ b/Task/String-prepend/VBScript/string-prepend.vbs @@ -0,0 +1,3 @@ +s = "bar" +s = "foo" & s +WScript.Echo s diff --git a/Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.adb b/Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.adb new file mode 100644 index 0000000000..663ac8921a --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Ada/strip-a-set-of-characters-from-a-string.adb @@ -0,0 +1,27 @@ +with Ada.Text_IO; + +procedure Strip_Characters_From_String is + + function Strip(The_String: String; The_Characters: String) + return String is + Keep: array (Character) of Boolean := (others => True); + Result: String(The_String'Range); + Last: Natural := Result'First-1; + begin + for I in The_Characters'Range loop + Keep(The_Characters(I)) := False; + end loop; + for J in The_String'Range loop + if Keep(The_String(J)) then + Last := Last+1; + Result(Last) := The_String(J); + end if; + end loop; + return Result(Result'First .. Last); + end Strip; + + S: String := "She was a soul stripper. She took my heart!"; + +begin -- main + Ada.Text_IO.Put_Line(Strip(S, "aei")); +end Strip_Characters_From_String; diff --git a/Task/Strip-a-set-of-characters-from-a-string/Batch-File/strip-a-set-of-characters-from-a-string.bat b/Task/Strip-a-set-of-characters-from-a-string/Batch-File/strip-a-set-of-characters-from-a-string.bat new file mode 100644 index 0000000000..b72942dd4d --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Batch-File/strip-a-set-of-characters-from-a-string.bat @@ -0,0 +1,16 @@ +@echo off +:strip String StripSet OutVar +setlocal enableextensions +set "str=%~1" +set "stripset=%~2" +setlocal enabledelayedexpansion +::strlen4 from https://ss64.com/forum/strlen.html +set "tempFile=%temp%\strlen-strip.tmp" +echo(%stripset%>"%tempFile%" +for %%F in ("%tempFile%") do set /a len=%%~zF-3 +del "%tempFile%" +::call set is slow +for /l %%i in (0,1,%len%) do ( +for %%c in (!stripset:~%%i^,1!) do set str=!str:%%c=! +) +echo !str! diff --git a/Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cob b/Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cob new file mode 100644 index 0000000000..4907e822d2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/COBOL/strip-a-set-of-characters-from-a-string.cob @@ -0,0 +1,47 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Strip-Chars. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Str-Size CONSTANT 128. + + LOCAL-STORAGE SECTION. + 01 I PIC 999. + 01 Str-Pos PIC 999. + + 01 Offset PIC 999. + 01 New-Pos PIC 999. + + 01 Str-End PIC 999. + + LINKAGE SECTION. + 01 Str PIC X(Str-Size). + 01 Chars-To-Replace PIC X(256). + + PROCEDURE DIVISION USING Str BY VALUE Chars-To-Replace. + Main. + PERFORM VARYING I FROM 1 BY 1 + UNTIL Chars-To-Replace (I:1) = X"00" + + MOVE ZERO TO Offset + +* *> Overwrite the characters to remove by left-shifting +* *> following characters over them. + PERFORM VARYING Str-Pos FROM 1 BY 1 + UNTIL Str-Size < Str-Pos + IF Str (Str-Pos:1) = Chars-To-Replace (I:1) + ADD 1 TO Offset + ELSE IF Offset NOT = ZERO + COMPUTE New-Pos = Str-Pos - Offset + MOVE Str (Str-Pos:1) TO Str (New-Pos:1) + END-IF + END-PERFORM + +* *> Move spaces to characters at the end that have been +* *> shifted over. + COMPUTE Str-End = Str-Size - Offset + MOVE SPACES TO Str (Str-End:Offset) + END-PERFORM + + GOBACK + . diff --git a/Task/Strip-a-set-of-characters-from-a-string/Crystal/strip-a-set-of-characters-from-a-string.cr b/Task/Strip-a-set-of-characters-from-a-string/Crystal/strip-a-set-of-characters-from-a-string.cr new file mode 100644 index 0000000000..a8c44d31b2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Crystal/strip-a-set-of-characters-from-a-string.cr @@ -0,0 +1,4 @@ +string = "She was a soul stripper. She took my heart!" + +puts "With built-in #delete: " + string.delete("aei") +puts "With ad-hoc expression: " + string.chars.reject(&.in? "aei").join diff --git a/Task/Strip-a-set-of-characters-from-a-string/EasyLang/strip-a-set-of-characters-from-a-string.easy b/Task/Strip-a-set-of-characters-from-a-string/EasyLang/strip-a-set-of-characters-from-a-string.easy index 3d9a134f69..6fd75d05f9 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/EasyLang/strip-a-set-of-characters-from-a-string.easy +++ b/Task/Strip-a-set-of-characters-from-a-string/EasyLang/strip-a-set-of-characters-from-a-string.easy @@ -1,8 +1,6 @@ func$ strip s$ del$ . for c$ in strchars s$ - if strpos del$ c$ <> 0 - c$ = "" - . + if strpos del$ c$ <> 0 : c$ = "" r$ &= c$ . return r$ diff --git a/Task/Strip-a-set-of-characters-from-a-string/Emacs-Lisp/strip-a-set-of-characters-from-a-string.el b/Task/Strip-a-set-of-characters-from-a-string/Emacs-Lisp/strip-a-set-of-characters-from-a-string.el new file mode 100644 index 0000000000..8c259c9d96 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Emacs-Lisp/strip-a-set-of-characters-from-a-string.el @@ -0,0 +1,6 @@ +(defun stripchars (s chars) + (seq-into + (seq-filter (lambda (x) (not (seq-contains chars x))) s) + 'string)) + +(stripchars "She was a soul stripper. She took my heart!" "aei") diff --git a/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.eu b/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.eu new file mode 100644 index 0000000000..a64060a9db --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Euphoria/strip-a-set-of-characters-from-a-string.eu @@ -0,0 +1,8 @@ +include std\sequence.e +include std\console.e + +sequence originalString = "She was a soul stripper. She took my heart!" +puts(1,"Before : " & originalString & "\n") +originalString = transmute(originalString, {{} , "a", "e", "i"}, {{} , "", "", ""}) +puts(1,"After : " & originalString & "\n") +any_key() diff --git a/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string-1.odin b/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string-1.odin new file mode 100644 index 0000000000..4cbbfa2b01 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string-1.odin @@ -0,0 +1,17 @@ +package main +import "core:fmt" +import "core:strings" +import "core:unicode/utf8" + +main :: proc() { + input_string:="She was a soul stripper. She took my heart!" + filter_string:="aei" + + for i in filter_string{ + rune_array:=[]rune{i} + filter:=utf8.runes_to_string(rune_array) + input_string,_=strings.replace(input_string, filter, "", -1) + } + fmt.println(input_string) + +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string-2.odin b/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string-2.odin new file mode 100644 index 0000000000..ce06c4e0ac --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Odin/strip-a-set-of-characters-from-a-string-2.odin @@ -0,0 +1,27 @@ +package main + +import "core:fmt" +import "core:slice" +import "core:sys/windows" +import "core:unicode/utf8" + +filter::proc(x:u8)->bool{ + return x!='a' && x!='e' && x!='i' +} + + +main::proc(){ + + + str:="She was a soul stripper. She took my heart!" + // transmute to u8, enough in this case + u8_slice:=transmute([]u8)str + + // filtered with slice.filter; needs function that returns a boolean + filter_u8_slice:=slice.filter(u8_slice,filter) + // transmute slice to string + new_string:=transmute(string)filter_u8_slice + fmt.println(" New string ", new_string) + + +} diff --git a/Task/Strip-a-set-of-characters-from-a-string/Pluto/strip-a-set-of-characters-from-a-string.pluto b/Task/Strip-a-set-of-characters-from-a-string/Pluto/strip-a-set-of-characters-from-a-string.pluto new file mode 100644 index 0000000000..783b0c0066 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Pluto/strip-a-set-of-characters-from-a-string.pluto @@ -0,0 +1,11 @@ +require "uchar" + +local function strip_characters(s, t) + local u = uchar.of(s) + for i = u:len(), 1, -1 do + if u:get(i) in t then u:remove(i) end + end + return u:tostring() +end + +print(strip_characters("She was a soul stripper. She took my heart!", "aei")) diff --git a/Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.ps1 b/Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.ps1 new file mode 100644 index 0000000000..d765b358a5 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/PowerShell/strip-a-set-of-characters-from-a-string.ps1 @@ -0,0 +1,2 @@ +'She was a soul stripper. She took my heart!' -replace '[aei]', '' +Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/Rye/strip-a-set-of-characters-from-a-string.rye b/Task/Strip-a-set-of-characters-from-a-string/Rye/strip-a-set-of-characters-from-a-string.rye new file mode 100644 index 0000000000..7a6d769b2a --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Rye/strip-a-set-of-characters-from-a-string.rye @@ -0,0 +1,5 @@ +without: fn { phrase excluded } { + .split\many excluded |join +} + +print "She was a soul stripper. She took my heart!" .without "aei" diff --git a/Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vbs b/Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vbs new file mode 100644 index 0000000000..f712b473c2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vbs @@ -0,0 +1,10 @@ +Function stripchars(s1,s2) + For i = 1 To Len(s1) + If InStr(s2,Mid(s1,i,1)) Then + s1 = Replace(s1,Mid(s1,i,1),"") + End If + Next + stripchars = s1 +End Function + +WScript.StdOut.Write stripchars("She was a soul stripper. She took my heart!","aei") diff --git a/Task/Strip-block-comments/Ada/strip-block-comments.adb b/Task/Strip-block-comments/Ada/strip-block-comments.adb new file mode 100644 index 0000000000..a99b5cd779 --- /dev/null +++ b/Task/Strip-block-comments/Ada/strip-block-comments.adb @@ -0,0 +1,93 @@ +with Ada.Strings.Fixed; +with Ada.Strings.Unbounded; +with Ada.Text_IO; +with Ada.Command_Line; + +procedure Strip is + use Ada.Strings.Unbounded; + procedure Print_Usage is + begin + Ada.Text_IO.Put_Line ("Usage:"); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (" strip [ []]"); + Ada.Text_IO.New_Line; + Ada.Text_IO.Put_Line (" file: file to strip"); + Ada.Text_IO.Put_Line (" opening: string for opening comment"); + Ada.Text_IO.Put_Line (" closing: string for closing comment"); + Ada.Text_IO.New_Line; + end Print_Usage; + + Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*"); + Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/"); + Inside_Comment : Boolean := False; + + function Strip_Comments (From : String) return String is + use Ada.Strings.Fixed; + Opening_Index : Natural; + Closing_Index : Natural; + Start_Index : Natural := From'First; + begin + if Inside_Comment then + Start_Index := + Index (Source => From, Pattern => To_String (Closing_Pattern)); + if Start_Index < From'First then + return ""; + end if; + Inside_Comment := False; + Start_Index := Start_Index + Length (Closing_Pattern); + end if; + Opening_Index := + Index + (Source => From, + Pattern => To_String (Opening_Pattern), + From => Start_Index); + if Opening_Index < From'First then + return From (Start_Index .. From'Last); + else + Closing_Index := + Index + (Source => From, + Pattern => To_String (Closing_Pattern), + From => Opening_Index + Length (Opening_Pattern)); + if Closing_Index > 0 then + return From (Start_Index .. Opening_Index - 1) & + Strip_Comments + (From ( + Closing_Index + Length (Closing_Pattern) .. From'Last)); + else + Inside_Comment := True; + return From (Start_Index .. Opening_Index - 1); + end if; + end if; + end Strip_Comments; + + File : Ada.Text_IO.File_Type; +begin + if Ada.Command_Line.Argument_Count < 1 + or else Ada.Command_Line.Argument_Count > 3 + then + Print_Usage; + return; + end if; + if Ada.Command_Line.Argument_Count > 1 then + Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2)); + if Ada.Command_Line.Argument_Count > 2 then + Closing_Pattern := + To_Unbounded_String (Ada.Command_Line.Argument (3)); + else + Closing_Pattern := Opening_Pattern; + end if; + end if; + Ada.Text_IO.Open + (File => File, + Mode => Ada.Text_IO.In_File, + Name => Ada.Command_Line.Argument (1)); + while not Ada.Text_IO.End_Of_File (File => File) loop + declare + Line : constant String := Ada.Text_IO.Get_Line (File); + begin + Ada.Text_IO.Put_Line (Strip_Comments (Line)); + end; + end loop; + Ada.Text_IO.Close (File => File); +end Strip; diff --git a/Task/Strip-block-comments/Crystal/strip-block-comments.cr b/Task/Strip-block-comments/Crystal/strip-block-comments.cr new file mode 100644 index 0000000000..3247facbf1 --- /dev/null +++ b/Task/Strip-block-comments/Crystal/strip-block-comments.cr @@ -0,0 +1,22 @@ +def strip_comments (s, start_delim = "/*", end_delim = "*/") + s.gsub(/#{Regex.escape(start_delim)}.*?#{Regex.escape(end_delim)}/m, "") +end + +puts strip_comments <<-EOF +/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + } +EOF diff --git a/Task/Strip-block-comments/R/strip-block-comments.r b/Task/Strip-block-comments/R/strip-block-comments.r new file mode 100644 index 0000000000..47faa5ce35 --- /dev/null +++ b/Task/Strip-block-comments/R/strip-block-comments.r @@ -0,0 +1,30 @@ +test_code <- "/** + * Some comments + * longer comments here that we can parse. + * + * Rahoo + */ + function subroutine() { + a = /* inline comment */ b + c ; + } + /*/ <-- tricky comments */ + + /** + * Another comment. + */ + function something() { + }" + +#Backslashes need to be handled first, then other special regex characters +specialchars <- c("\\","*","^","+",".","!","?","(",")","[","]","{","}","$","|") + +strip_comments <- function(s, opener, closer){ + for(char in specialchars){ + opener <- gsub(char, paste0("\\", char), opener, fixed=TRUE) + closer <- gsub(char, paste0("\\", char), closer, fixed=TRUE) + } + regexp <- paste0(opener, ".*?", closer) + gsub(regexp, "", s) +} + +cat(strip_comments(test_code, "/*", "*/")) diff --git a/Task/Strip-comments-from-a-string/68000-Assembly/strip-comments-from-a-string.68000 b/Task/Strip-comments-from-a-string/68000-Assembly/strip-comments-from-a-string.68000 index dd17638fbb..087ad9e00a 100644 --- a/Task/Strip-comments-from-a-string/68000-Assembly/strip-comments-from-a-string.68000 +++ b/Task/Strip-comments-from-a-string/68000-Assembly/strip-comments-from-a-string.68000 @@ -1,61 +1,61 @@ StripComments: - ;prints a string but stops at the comment character - ;INPUT: D7 = comment character(s) of choice + ;prints a string but stops at the comment character + ;INPUT: D7 = comment character(s) of choice ;A0 = source address of string - ;up to four can be used, each takes up a different 8 bits of the register - ;to omit an argument, leave its bits as zero. + ;up to four can be used, each takes up a different 8 bits of the register + ;to omit an argument, leave its bits as zero. .loop: - MOVE.B (A0)+,D0 - CMP.B #0,D0 ;check for null terminator - beq .done - - CMP.B D7,D0 ;check the first comment char - beq .done - ROR.L #8,D7 - - CMP.B D7,D0 ;check the second comment char - beq .done - ROR.L #8,D7 - - CMP.B D7,D0 ;check the third comment char - beq .done - ROR.L #8,D7 - - CMP.B D7,D0 ;check the fourth comment char - beq .done - ROR.L #8,D7 - - CMP.B #' ',D0 - BNE dontCheckNext - MOVE.B (A0),D1 ;look ahead one character, if that character is a comment char or null terminator, stop here - - CMP.B #0,D1 - beq .done + MOVE.B (A0)+,D0 + CMP.B #0,D0 ;check for null terminator + beq .done + + CMP.B D7,D0 ;check the first comment char + beq .done + ROR.L #8,D7 + + CMP.B D7,D0 ;check the second comment char + beq .done + ROR.L #8,D7 + + CMP.B D7,D0 ;check the third comment char + beq .done + ROR.L #8,D7 + + CMP.B D7,D0 ;check the fourth comment char + beq .done + ROR.L #8,D7 + + CMP.B #' ',D0 + BNE dontCheckNext + MOVE.B (A0),D1 ;look ahead one character, if that character is a comment char or null terminator, stop here + + CMP.B #0,D1 + beq .done + + CMP.B D7,D1 + beq .done + ROR.L #8,D7 + + CMP.B D7,D1 + beq .done + ROR.L #8,D7 + + CMP.B D7,D1 + beq .done + ROR.L #8,D7 + + CMP.B D7,D1 + beq .done + ROR.L #8,D7 - CMP.B D7,D1 - beq .done - ROR.L #8,D7 - - CMP.B D7,D1 - beq .done - ROR.L #8,D7 - - CMP.B D7,D1 - beq .done - ROR.L #8,D7 - - CMP.B D7,D1 - beq .done - ROR.L #8,D7 - dontCheckNext: - jsr PrintChar - bra .loop - -.done: - rts + jsr PrintChar + bra .loop + +.done: + rts + - TestString: - dc.b "apples ; pears # and bananas",0 + dc.b "apples ; pears # and bananas",0 diff --git a/Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.adb b/Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.adb new file mode 100644 index 0000000000..03725c8b90 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Ada/strip-comments-from-a-string.adb @@ -0,0 +1,20 @@ +with Ada.Text_IO; +procedure Program is + Comment_Characters : String := "#;"; +begin + loop + declare + Line : String := Ada.Text_IO.Get_Line; + begin + exit when Line'Length = 0; + Outer_Loop : for I in Line'Range loop + for J in Comment_Characters'Range loop + if Comment_Characters(J) = Line(I) then + Ada.Text_IO.Put_Line(Line(Line'First .. I - 1)); + exit Outer_Loop; + end if; + end loop; + end loop Outer_Loop; + end; + end loop; +end Program; diff --git a/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.au3 b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.au3 new file mode 100644 index 0000000000..1dfd34c4ed --- /dev/null +++ b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-1.au3 @@ -0,0 +1,17 @@ +Dim $Line1 = "apples, pears # and bananas" +Dim $Line2 = "apples, pears ; and bananas" + +_StripAtMarker($Line1) +_StripAtMarker($Line2) + +Func _StripAtMarker($_Line, $sMarker='# ;') + Local $aMarker = StringSplit($sMarker, ' ') + Local $iPos + For $i = 1 To $aMarker[0] + $iPos = StringInStr($_Line, $aMarker[$i]) + If $iPos Then + ConsoleWrite($_Line & @CRLF) + ConsoleWrite( StringStripWS( StringLeft($_Line, $iPos -1), 2) & @CRLF) + EndIf + Next +EndFunc ;==>_StripAtMarker diff --git a/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.au3 b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.au3 new file mode 100644 index 0000000000..7249ad18c0 --- /dev/null +++ b/Task/Strip-comments-from-a-string/AutoIt/strip-comments-from-a-string-2.au3 @@ -0,0 +1,56 @@ +Dim $aLines[4] = _ +[ _ +"$a = $b + $c ; Comment line 1", _ +"Dim $s1 = 'some text; tiled with semicolon', $s2 = 'another text; also tiled with semicolon' ; Comment line 2 - semicolon as part of assignment", _ +"_SomeFunctionCall('string parameter with ;', $anotherParam) ; Comment line 3 - semicolon as part parameter in an function call", _ +"Func _AnotherFunction($param1=';', $param2=';', $param3=';') ; Comment line 4 - semicolon as default value in parameter of a function headline" _ +] + +For $i = 0 To 3 + ConsoleWrite('+> Line ' & $i+1 & ' full:' & @CRLF & '+>' & $aLines[$i] & @CRLF) + ConsoleWrite('!> without comment:' & @CRLF & '!>' & _LineStripComment($aLines[$i]) & @CRLF & @CRLF) +Next + + +Func _LineStripComment($_Line) + ; == tile line by all included comment marker + Local $aPartsWithMarker = StringSplit($_Line, ';') + Local $sNoComment + + ; == if no comment marker: return full line + If $aPartsWithMarker[0] = 0 Then Return $_Line + + ; == check if string in part, if is'nt: following part(s) are comment + For $i = 1 To $aPartsWithMarker[0] + If Not StringRegExp($aPartsWithMarker[$i], "('|\x22)") Then + If $i = 1 Then + Return StringStripWS($aPartsWithMarker[$i], 2) + Else + Return StringStripWS($sNoComment & $aPartsWithMarker[$i], 2) + EndIf + Else + ; == check if next leftside string delimiter has uneven count + Local $iLen = StringLen($aPartsWithMarker[$i]) + Local $fDetectDelim = False, $sStringDelim, $iDelimCount, $sCurr + For $j = $iLen To 1 Step -1 + $sCurr = StringMid($aPartsWithMarker[$i], $j, 1) + If Not $fDetectDelim Then + If $sCurr = "'" Or $sCurr = '"' Then + $sStringDelim = $sCurr + $iDelimCount += 1 + $fDetectDelim = True + EndIf + Else + If $sCurr = $sStringDelim Then $iDelimCount += 1 + EndIf + Next + If Mod($iDelimCount, 2) Then + ; == uneven count: so it masks the comment marker + $sNoComment &= $aPartsWithMarker[$i] & ';' + Else + ; == even count: all following is comment + Return StringStripWS($sNoComment & $aPartsWithMarker[$i], 2) + EndIf + EndIf + Next +EndFunc ;==>_LineStripComment diff --git a/Task/Strip-comments-from-a-string/BASIC256/strip-comments-from-a-string.basic b/Task/Strip-comments-from-a-string/BASIC256/strip-comments-from-a-string.basic index 6c0b9ecc27..d01dd7c806 100644 --- a/Task/Strip-comments-from-a-string/BASIC256/strip-comments-from-a-string.basic +++ b/Task/Strip-comments-from-a-string/BASIC256/strip-comments-from-a-string.basic @@ -6,16 +6,16 @@ s$[3] = "# this is a comment" s$[4] = " # this is a comment with leading whitespace" for i = 1 to 4 - call stripComment(s$[i], "#;") - print s$[i], " => Length = "; length(s$[i]) + call stripComment(s$[i], "#;") + print s$[i], " => Length = "; length(s$[i]) next i end subroutine stripComment(s$, commentMarkers$) - if s$ = "" then return - i = instr(s$, commentMarkers$) - if i > 0 then - s$ = left$(s$, i - 1) - s$ = trim(s$) # removes both leading and trailing whitespace - end if + if s$ = "" then return + i = instr(s$, commentMarkers$) + if i > 0 then + s$ = left$(s$, i - 1) + s$ = trim(s$) # removes both leading and trailing whitespace + end if end subroutine diff --git a/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c b/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c index 025ae111ba..101753a318 100644 --- a/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c +++ b/Task/Strip-comments-from-a-string/C/strip-comments-from-a-string.c @@ -2,25 +2,25 @@ int main() { - char ch, str[100]; - int i; - - do{ - printf("\nEnter the string :"); - fgets(str,100,stdin); - for(i=0;str[i]!=00;i++) - { - if(str[i]=='#'||str[i]==';') - { - str[i]=00; - break; - } - } - printf("\nThe modified string is : %s",str); - printf("\nDo you want to repeat (y/n): "); - scanf("%c",&ch); - fflush(stdin); - }while(ch=='y'||ch=='Y'); - - return 0; + char ch, str[100]; + int i; + + do{ + printf("\nEnter the string :"); + fgets(str,100,stdin); + for(i=0;str[i]!=00;i++) + { + if(str[i]=='#'||str[i]==';') + { + str[i]=00; + break; + } + } + printf("\nThe modified string is : %s",str); + printf("\nDo you want to repeat (y/n): "); + scanf("%c",&ch); + fflush(stdin); + }while(ch=='y'||ch=='Y'); + + return 0; } diff --git a/Task/Strip-comments-from-a-string/COBOL/strip-comments-from-a-string.cob b/Task/Strip-comments-from-a-string/COBOL/strip-comments-from-a-string.cob new file mode 100644 index 0000000000..d6482b1063 --- /dev/null +++ b/Task/Strip-comments-from-a-string/COBOL/strip-comments-from-a-string.cob @@ -0,0 +1,21 @@ + identification division. + program-id. StripComments. + + data division. + working-storage section. + 01 line-text pic x(64). + + procedure division. + main. + move "apples, pears # and bananas" to line-text + perform show-striped-text + + move "apples, pears ; and bananas" to line-text + perform show-striped-text + + stop run + . + show-striped-text. + unstring line-text delimited by "#" or ";" into line-text + display quote, function trim(line-text), quote + . diff --git a/Task/Strip-comments-from-a-string/Crystal/strip-comments-from-a-string.cr b/Task/Strip-comments-from-a-string/Crystal/strip-comments-from-a-string.cr new file mode 100644 index 0000000000..6ac8e8bdc2 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Crystal/strip-comments-from-a-string.cr @@ -0,0 +1,10 @@ +def strip_comments (s) + s.sub(/[#;].*$/, "").strip +end + +"apples, pears # and bananas +apples, pears ; and bananas + apples, pears # xxx + apples, pears ".each_line do |line| + puts strip_comments(line).inspect +end diff --git a/Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.el b/Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.el new file mode 100644 index 0000000000..8975cbf492 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Emacs-Lisp/strip-comments-from-a-string.el @@ -0,0 +1,5 @@ +(string-trim (string-trim-right " apples, pears # and bananas" "[#;].+")) + +(string-trim (string-trim-right " apples, pears ; and bananas" "[#;].+")) + +(string-trim (string-trim-right " apples, pears and bananas " "[#;].+")) diff --git a/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl b/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl index fb688ae1a4..d50ccab0f6 100644 --- a/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl +++ b/Task/Strip-comments-from-a-string/Erlang/strip-comments-from-a-string.erl @@ -9,7 +9,7 @@ task() -> -keep_until_comment( String ) -> lists:takewhile( fun not_comment/1, String ). +keep_until_comment( String ) -> lists:takewhile( fun not_comment/1, String ). not_comment( $# ) -> false; not_comment( $; ) -> false; diff --git a/Task/Strip-comments-from-a-string/Fortran/strip-comments-from-a-string.f b/Task/Strip-comments-from-a-string/Fortran/strip-comments-from-a-string.f index c07f88d76c..00a19d32e1 100644 --- a/Task/Strip-comments-from-a-string/Fortran/strip-comments-from-a-string.f +++ b/Task/Strip-comments-from-a-string/Fortran/strip-comments-from-a-string.f @@ -7,22 +7,22 @@ contains !**************************************************** - function strip_comments(str,c) result(str2) - implicit none - character(len=*),intent(in) :: str - character(len=1),intent(in) :: c !comment character - character(len=len(str)) :: str2 - - integer :: i - - i = index(str,c) - if (i>0) then - str2 = str(1:i-1) - else - str2 = str - end if - - end function strip_comments + function strip_comments(str,c) result(str2) + implicit none + character(len=*),intent(in) :: str + character(len=1),intent(in) :: c !comment character + character(len=len(str)) :: str2 + + integer :: i + + i = index(str,c) + if (i>0) then + str2 = str(1:i-1) + else + str2 = str + end if + + end function strip_comments !**************************************************** end module string_routines diff --git a/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go b/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go index 70635e7806..035a2d39fd 100644 --- a/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go +++ b/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go @@ -1,27 +1,27 @@ package main import ( - "fmt" - "strings" - "unicode" + "fmt" + "strings" + "unicode" ) const commentChars = "#;" func stripComment(source string) string { - if cut := strings.IndexAny(source, commentChars); cut >= 0 { - return strings.TrimRightFunc(source[:cut], unicode.IsSpace) - } - return source + if cut := strings.IndexAny(source, commentChars); cut >= 0 { + return strings.TrimRightFunc(source[:cut], unicode.IsSpace) + } + return source } func main() { - for _, s := range []string{ - "apples, pears # and bananas", - "apples, pears ; and bananas", - "no bananas", - } { - fmt.Printf("source: %q\n", s) - fmt.Printf("stripped: %q\n", stripComment(s)) - } + for _, s := range []string{ + "apples, pears # and bananas", + "apples, pears ; and bananas", + "no bananas", + } { + fmt.Printf("source: %q\n", s) + fmt.Printf("stripped: %q\n", stripComment(s)) + } } diff --git a/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf b/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf index 21a019bc1f..2361e4cfa6 100644 --- a/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf +++ b/Task/Strip-comments-from-a-string/Inform-7/strip-comments-from-a-string.inf @@ -1,11 +1,11 @@ Home is a room. When play begins: - strip comments from "apples, pears # and bananas"; - strip comments from "apples, pears ; and bananas"; - end the story. + strip comments from "apples, pears # and bananas"; + strip comments from "apples, pears ; and bananas"; + end the story. To strip comments from (T - indexed text): - say "[T] -> "; - replace the regular expression "<#;>.*$" in T with ""; - say "[T][line break]". + say "[T] -> "; + replace the regular expression "<#;>.*$" in T with ""; + say "[T][line break]". diff --git a/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java b/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java index 3c3ea6e8c7..c266712f76 100644 --- a/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java +++ b/Task/Strip-comments-from-a-string/Java/strip-comments-from-a-string.java @@ -2,22 +2,22 @@ import java.io.*; public class StripLineComments{ public static void main( String[] args ){ - if( args.length < 1 ){ - System.out.println("Usage: java StripLineComments StringToProcess"); - } - else{ - String inputFile = args[0]; - String input = ""; - try{ - BufferedReader reader = new BufferedReader( new FileReader( inputFile ) ); - String line = ""; - while((line = reader.readLine()) != null){ - System.out.println( line.split("[#;]")[0] ); - } - } - catch( Exception e ){ - e.printStackTrace(); - } - } + if( args.length < 1 ){ + System.out.println("Usage: java StripLineComments StringToProcess"); + } + else{ + String inputFile = args[0]; + String input = ""; + try{ + BufferedReader reader = new BufferedReader( new FileReader( inputFile ) ); + String line = ""; + while((line = reader.readLine()) != null){ + System.out.println( line.split("[#;]")[0] ); + } + } + catch( Exception e ){ + e.printStackTrace(); + } + } } } diff --git a/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m b/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m index c1de1a971e..4386fb45a2 100644 --- a/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m +++ b/Task/Strip-comments-from-a-string/MATLAB/strip-comments-from-a-string.m @@ -2,7 +2,7 @@ function line = stripcomment(line) e = min([find(line=='#',1),find(line==';',1)]); if ~isempty(e) e = e-1; - while isspace(line(e)) e = e - 1; end; + while isspace(line(e)) e = e - 1; end; line = line(1:e); - end; + end; end; diff --git a/Task/Strip-comments-from-a-string/Rebol/strip-comments-from-a-string.rebol b/Task/Strip-comments-from-a-string/Rebol/strip-comments-from-a-string.rebol new file mode 100644 index 0000000000..efbb38912c --- /dev/null +++ b/Task/Strip-comments-from-a-string/Rebol/strip-comments-from-a-string.rebol @@ -0,0 +1,9 @@ +remove-comments: func[line sep][ + parse line [to sep remove to end] + trim/tail line +] + +probe remove-comments "apples ; pears # and bananas" charset ";#" +probe remove-comments "apples ; pears # and bananas" #";" +probe remove-comments "apples ; pears # and bananas" #"#" +probe remove-comments "apples ; pears # and bananas" #"!" diff --git a/Task/Strip-comments-from-a-string/V-(Vlang)/strip-comments-from-a-string.v b/Task/Strip-comments-from-a-string/V-(Vlang)/strip-comments-from-a-string.v index b7f3b32185..5f8cfd7573 100644 --- a/Task/Strip-comments-from-a-string/V-(Vlang)/strip-comments-from-a-string.v +++ b/Task/Strip-comments-from-a-string/V-(Vlang)/strip-comments-from-a-string.v @@ -4,7 +4,7 @@ fn main() { s := [ "apples, pears # and bananas", "apples, pears ; and bananas", - "no bananas" + "no bananas" ] for element in s { println('source: $element') diff --git a/Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vbs b/Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vbs new file mode 100644 index 0000000000..00e801cc3e --- /dev/null +++ b/Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vbs @@ -0,0 +1,11 @@ +Function strip_comments(s,char) + If InStr(1,s,char) > 0 Then + arr = Split(s,char) + strip_comments = RTrim(arr(0)) + Else + strip_comments = s + End If +End Function + +WScript.StdOut.WriteLine strip_comments("apples, pears # and bananas","#") +WScript.StdOut.WriteLine strip_comments("apples, pears ; and bananas",";") diff --git a/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl index d50b5e0a5e..b3c3483bd7 100644 --- a/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl +++ b/Task/Strip-comments-from-a-string/Zkl/strip-comments-from-a-string-1.zkl @@ -1,6 +1,6 @@ fcn strip(text,c){ // if c in text, remove it and following text if (Void!=(n:=text.find(c))) text=text[0,n]; - text.strip() // remove leading and trailing white space + text.strip() // remove leading and trailing white space } fcn stripper(text,a,b,c,etc){ // strip a,b,c,etc from text foreach c in (vm.arglist[1,*]){ text=strip(text,c) } diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.adb b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.adb new file mode 100644 index 0000000000..990b5b0f1a --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ada/strip-control-codes-and-extended-characters-from-a-string.adb @@ -0,0 +1,35 @@ +with Ada.Text_IO; + +procedure Strip_ASCII is + + Full: String := 'a' & Character'Val(11) & 'b' & Character'Val(166) & + 'c' & Character'Val(127) & Character'Val(203) & + Character'Val(202) & "de"; + -- 5 ordinary characters ('a' .. 'e') + -- 2 control characters (11, 127); note that 11 is the "vertical tab" + -- 3 extended characters (166, 203, 202) + + function Filter(S: String; + From: Character := ' '; + To: Character := Character'Val(126); + Above: Character := Character'Val(127)) return String is + begin + if S'Length = 0 then + return ""; + elsif (S(S'First) >= From and then S(S'First) <= To) or else S(S'First) > Above then + return S(S'First) & Filter(S(S'First+1 .. S'Last), From, To, Above); + else + return Filter(S(S'First+1 .. S'Last), From, To, Above); + end if; + end Filter; + + procedure Put_Line(Text, S: String) is + begin + Ada.Text_IO.Put_Line(Text & " """ & S & """, Length:" & Integer'Image(S'Length)); + end Put_Line; + +begin + Put_Line("The full string :", Full); + Put_Line("No Control Chars:", Filter(Full)); -- default values for From, To, and Above + Put_Line("Neither_Extended:", Filter(Full, Above => Character'Last)); -- defaults for From and To +end Strip_ASCII; diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Crystal/strip-control-codes-and-extended-characters-from-a-string.cr b/Task/Strip-control-codes-and-extended-characters-from-a-string/Crystal/strip-control-codes-and-extended-characters-from-a-string.cr new file mode 100644 index 0000000000..9afd2fae56 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Crystal/strip-control-codes-and-extended-characters-from-a-string.cr @@ -0,0 +1,8 @@ +string = "abcd\t\n efgh\x00\x01\x7f áéíóú ijklm\n" + +no_control_codes = string.delete("\x00-\x1f\x7f") +nor_extended_chars = string.delete("^ -~") + +puts "original: #{string.inspect}" +puts "w/o control codes: #{no_control_codes.inspect}" +puts "w/o either: #{nor_extended_chars.inspect}" diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.ps1 b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.ps1 new file mode 100644 index 0000000000..1ef63cb353 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-1.ps1 @@ -0,0 +1,47 @@ +function Remove-Character +{ + [CmdletBinding(DefaultParameterSetName="Control and Extended")] + [OutputType([string])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [string] + $String, + + [Parameter(ParameterSetName="Control")] + [switch] + $Control, + + [Parameter(ParameterSetName="Extended")] + [switch] + $Extended + ) + + Begin + { + filter Remove-ControlCharacter + { + $_.ToCharArray() | ForEach-Object -Begin {$out = ""} -Process {if (-not [Char]::IsControl($_)) {$out += $_ }} -End {$out} + } + + filter Remove-ExtendedCharacter + { + $_.ToCharArray() | ForEach-Object -Begin {$out = ""} -Process {if ([int]$_ -lt 127) {$out += $_ }} -End {$out} + } + } + Process + { + foreach ($s in $String) + { + switch ($PSCmdlet.ParameterSetName) + { + "Control" {$s | Remove-ControlCharacter} + "Extended" {$s | Remove-ExtendedCharacter} + Default {$s | Remove-ExtendedCharacter | Remove-ControlCharacter} + } + } + } +} diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.ps1 b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.ps1 new file mode 100644 index 0000000000..562c68caab --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-2.ps1 @@ -0,0 +1,6 @@ +$test = "$([char]9)Français." + +"Original string : `"$test`"" +"Control characters stripped : `"$($test | Remove-Character -Control)`"" +"Extended characters stripped : `"$($test | Remove-Character -Extended)`"" +"Control & extended stripped : `"$($test | Remove-Character)`"" diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.ps1 b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.ps1 new file mode 100644 index 0000000000..e82ec4b553 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/PowerShell/strip-control-codes-and-extended-characters-from-a-string-3.ps1 @@ -0,0 +1 @@ +"Français", "Čeština" | Remove-Character -Extended diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/V-(Vlang)/strip-control-codes-and-extended-characters-from-a-string.v b/Task/Strip-control-codes-and-extended-characters-from-a-string/V-(Vlang)/strip-control-codes-and-extended-characters-from-a-string.v index b16bacd843..8f6d22b238 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/V-(Vlang)/strip-control-codes-and-extended-characters-from-a-string.v +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/V-(Vlang)/strip-control-codes-and-extended-characters-from-a-string.v @@ -1,5 +1,5 @@ fn main() { - println(stripped("\ba\x00b\n\rc\fd\xc3")) + println(stripped("\ba\x00b\n\rc\fd\u00c3")) } fn stripped(source string) string { diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vbs b/Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vbs new file mode 100644 index 0000000000..784b889462 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vbs @@ -0,0 +1,26 @@ +Function StripCtrlCodes(s) + tmp = "" + For i = 1 To Len(s) + n = Asc(Mid(s,i,1)) + If (n >= 32 And n <= 126) Or n >=128 Then + tmp = tmp & Mid(s,i,1) + End If + Next + StripCtrlCodes = tmp +End Function + +Function StripCtrlCodesExtChrs(s) + tmp = "" + For i = 1 To Len(s) + n = Asc(Mid(s,i,1)) + If n >= 32 And n <= 126 Then + tmp = tmp & Mid(s,i,1) + End If + Next + StripCtrlCodesExtChrs = tmp +End Function + +WScript.StdOut.Write "ab�cd�ef�gh�€" & " = " & StripCtrlCodes("ab�cd�ef�gh�€") +WScript.StdOut.WriteLine +WScript.StdOut.Write "ab�cd�ef�gh�ij†klð€" & " = " & StripCtrlCodesExtChrs("ab�cd�ef�gh�ij†klð€") +WScript.StdOut.WriteLine diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.adb b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.adb new file mode 100644 index 0000000000..81aa82446c --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Ada/strip-whitespace-from-a-string-top-and-tail.adb @@ -0,0 +1,10 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Strings; use Ada.Strings; +with Ada.Strings.Fixed; use Ada.Strings.Fixed; +procedure StripDemo is + str : String := " Jabberwocky "; +begin + Put_Line ("'" & Trim (str, Left) & "'"); + Put_Line ("'" & Trim (str, Right) & "'"); + Put_Line ("'" & Trim (str, Both) & "'"); +end StripDemo; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-1.cob b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-1.cob new file mode 100644 index 0000000000..b746c0692b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-1.cob @@ -0,0 +1,3 @@ +DISPLAY "'" FUNCTION TRIM(str, LEADING) "'" +DISPLAY "'" FUNCTION TRIM(str, TRAILING) "'" +DISPLAY "'" FUNCTION TRIM(str) "'" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cob b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cob new file mode 100644 index 0000000000..c138de4d0d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/COBOL/strip-whitespace-from-a-string-top-and-tail-2.cob @@ -0,0 +1,3 @@ +DISPLAY "'" FUNCTION TRIML(str) "'" +DISPLAY "'" FUNCTION TRIMR(str) "'" +DISPLAY "'" FUNCTION TRIM(str) "'" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.el b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.el new file mode 100644 index 0000000000..0882908ce1 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.el @@ -0,0 +1,3 @@ +(string-trim-left " left center right ") ;=> "left center right " +(string-trim-right " left center right ") ;=> " left center right" +(string-trim " left center right ") ;=> "left center right" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.el b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.el new file mode 100644 index 0000000000..46889e8514 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.el @@ -0,0 +1,8 @@ +(defun string-trim-left (str) + (replace-regexp-in-string "^[ \t\r\n]*" "" str)) + +(defun string-trim-right (str) + (replace-regexp-in-string "[ \t\r\n]*$" "" str)) + +(defun string-trim (str) + (string-trim-left (string-trim-right str))) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.eu b/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.eu new file mode 100644 index 0000000000..e36885b051 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Euphoria/strip-whitespace-from-a-string-top-and-tail.eu @@ -0,0 +1,17 @@ +include std/console.e +include std/text.e + +sequence removables = " \t\n\r\x05\u0234\" " +sequence extraSeq = " \x05\r \" A B C \n \t\t \u0234 \r\r \x05 " + +extraSeq = trim(extraSeq,removables) --the work is done by the trim function + +--only output programming next : +printf(1, "String Trimmed is now: %s \r\n", {extraSeq} ) --print the resulting string to screen + +for i = 1 to length(extraSeq) do --loop over each character in the sequence. + printf(1, "String element %d", i) --to look at more detail, + printf(1, " : %d\r\n", extraSeq[i])--print integer values(ascii) of the string. +end for + +any_key() diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Pluto/strip-whitespace-from-a-string-top-and-tail.pluto b/Task/Strip-whitespace-from-a-string-Top-and-tail/Pluto/strip-whitespace-from-a-string-top-and-tail.pluto new file mode 100644 index 0000000000..30cf7591c1 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Pluto/strip-whitespace-from-a-string-top-and-tail.pluto @@ -0,0 +1,8 @@ +local a = " \t\r\nString with leading whitespace removed" +local b = "String with trailing whitespace removed \t\r\n" +local c = " \t\r\nString with both leading and trailing whitespace removed \t\r\n" +local d = " \t\r\n\v\fString with leading whitespace and form feed removed" +print($"'{a:lstrip()}'") +print($"'{b:rstrip()}'") +print($"'{c:strip()}'") +print($"'{d:lstrip(" \t\r\n\v\f")}'") -- similar overloads of rstrip and strip exist diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.ps1 b/Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.ps1 new file mode 100644 index 0000000000..2aed20bdfb --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.ps1 @@ -0,0 +1,4 @@ +$var = " Hello World " +$var.TrimStart() # String with leading whitespace removed +$var.TrimEnd() # String with trailing whitespace removed +$var.Trim() # String with both leading and trailing whitespace removed diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rs b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rs index f33f00c23c..b1fa7e5365 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rs +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rs @@ -3,6 +3,6 @@ fn main() { let string_with_spaces = spaces.to_owned() + "String without spaces" + spaces; assert_eq!(string_with_spaces.trim(), "String without spaces"); - assert_eq!(string_with_spaces.trim_left(), "String without spaces".to_owned() + spaces); - assert_eq!(string_with_spaces.trim_right(), spaces.to_owned() + "String without spaces"); + assert_eq!(string_with_spaces.trim_start(), "String without spaces".to_owned() + spaces); + assert_eq!(string_with_spaces.trim_end(), spaces.to_owned() + "String without spaces"); } diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rye/strip-whitespace-from-a-string-top-and-tail.rye b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rye/strip-whitespace-from-a-string-top-and-tail.rye new file mode 100644 index 0000000000..98c38ffc89 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rye/strip-whitespace-from-a-string-top-and-tail.rye @@ -0,0 +1 @@ +trim " Hello " diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail-1.seed7 b/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail-1.seed7 new file mode 100644 index 0000000000..367dffeec5 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail-1.seed7 @@ -0,0 +1,10 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const string: testStri is " \t \r \n String with spaces \t \r \n "; + begin + writeln(ltrim(testStri)); + writeln(rtrim(testStri)); + writeln(trim(testStri)); + end func; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail-2.seed7 b/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail-2.seed7 new file mode 100644 index 0000000000..3922bce2f7 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Seed7/strip-whitespace-from-a-string-top-and-tail-2.seed7 @@ -0,0 +1,17 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var string: s is " \t \r \n String with spaces \t \r \n "; + begin + if trim(s) = "String with spaces" then + writeln("Test Passed: String is perfectly trimmed."); + else + writeln("Test Failed!"); + writeln("Actual value: " & literal(trim(s))); + end if; + + # Using literal() to see exactly what is left behind + writeln("Ltrim result: " & literal(ltrim(s))); + writeln("Rtrim result: " & literal(rtrim(s))); + end func; diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vbs b/Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vbs new file mode 100644 index 0000000000..81b032a62f --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vbs @@ -0,0 +1,28 @@ +Function LeftTrim(s) + Set regex = New RegExp + With regex + .Pattern = "^\s*" + If .Test(s) Then + LeftTrim = .Replace(s,"") + Else + LeftTrim = s + End If + End With +End Function + +Function RightTrim(s) + Set regex = New RegExp + With regex + .Pattern = "\s*$" + If .Test(s) Then + RightTrim = .Replace(s,"") + Else + RightTrim = s + End If + End With +End Function + +'testing the functions +WScript.StdOut.WriteLine LeftTrim(" RosettaCode") +WScript.StdOut.WriteLine RightTrim("RosettaCode ") +WScript.StdOut.WriteLine LeftTrim(RightTrim(" RosettaCode ")) diff --git a/Task/Subleq/Ada/subleq.adb b/Task/Subleq/Ada/subleq.adb new file mode 100644 index 0000000000..1c9ca15e68 --- /dev/null +++ b/Task/Subleq/Ada/subleq.adb @@ -0,0 +1,68 @@ +with Ada.Text_IO; + +procedure Subleq is + + Storage_Size: constant Positive := 2**8; -- increase or decrease memory + Steps: Natural := 999; -- "emergency exit" to stop endless loops + + subtype Address is Integer range -1 .. (Storage_Size-1); + subtype Memory_Location is Address range 0 .. Address'Last; + + type Storage is array(Memory_Location) of Integer; + + package TIO renames Ada.Text_IO; + package IIO is new TIO.Integer_IO(Integer); + + procedure Read_Program(Mem: out Storage) is + Idx: Memory_Location := 0; + begin + while not TIO.End_Of_Line loop + IIO.Get(Mem(Idx)); + Idx := Idx + 1; + end loop; + exception + when others => TIO.Put_Line("Reading program: Something went wrong!"); + end Read_Program; + + procedure Execute_Program(Mem: in out Storage) is + PC: Integer := 0; -- program counter + function Source return Integer is (Mem(PC)); + function Dest return Integer is (Mem(PC+1)); + function Branch return Integer is (Mem(PC+2)); + function Next return Integer is (PC+3); + begin + while PC >= 0 and Steps >= 0 loop + Steps := Steps -1; + if Source = -1 then -- read input + declare + Char: Character; + begin + TIO.Get (Char); + Mem(Dest) := Character'Pos (Char); + end; + PC := Next; + elsif Dest = -1 then -- write output + TIO.Put(Character'Val(Mem(Source))); + PC := Next; + else -- subtract and branch if less or equal + Mem(Dest) := Mem(Dest) - Mem(Source); + if Mem(Dest) <= 0 then + PC := Branch; + else + PC := Next; + end if; + end if; + end loop; + TIO.Put_Line(if PC >= 0 then "Emergency exit: program stopped!" else ""); + exception + when others => TIO.Put_Line("Failure when executing Program"); + end Execute_Program; + + Memory: Storage := (others => 0); -- no initial "junk" in memory! + +begin + + Read_Program(Memory); + Execute_Program(Memory); + +end Subleq; diff --git a/Task/Subleq/COBOL/subleq.cob b/Task/Subleq/COBOL/subleq.cob new file mode 100644 index 0000000000..54398163e2 --- /dev/null +++ b/Task/Subleq/COBOL/subleq.cob @@ -0,0 +1,81 @@ +identification division. +program-id. subleq-program. +data division. +working-storage section. +01 subleq-source-code. + 05 source-string pic x(2000). +01 subleq-virtual-machine. + 05 memory-table. + 10 memory pic s9999 + occurs 500 times. + 05 a pic s9999. + 05 b pic s9999. + 05 c pic s9999. + 05 instruction-pointer pic s9999. + 05 input-output-character pic x. +01 working-variables. + 05 loop-counter pic 9999. + 05 instruction-counter pic 9999. + 05 string-pointer pic 9999. + 05 adjusted-index-a pic 9999. + 05 adjusted-index-b pic 9999. + 05 output-character-code pic 9999. +procedure division. +read-source-paragraph. + accept source-string from console. + display 'READING SUBLEQ PROGRAM... ' with no advancing. + move 1 to string-pointer. + move 0 to instruction-counter. + perform split-source-paragraph varying loop-counter from 1 by 1 + until loop-counter is greater than 500 + or string-pointer is greater than 2000. + display instruction-counter with no advancing. + display ' WORDS READ.'. +execute-paragraph. + move 1 to instruction-pointer. + move 0 to instruction-counter. + display 'BEGINNING RUN... '. + display ''. + perform execute-instruction-paragraph + until instruction-pointer is negative. + display ''. + display 'HALTED AFTER ' instruction-counter ' INSTRUCTIONS.'. + stop run. +execute-instruction-paragraph. + add 1 to instruction-counter. + move memory(instruction-pointer) to a. + add 1 to instruction-pointer. + move memory(instruction-pointer) to b. + add 1 to instruction-pointer. + move memory(instruction-pointer) to c. + add 1 to instruction-pointer. + if a is equal to -1 then perform input-paragraph. + if b is equal to -1 then perform output-paragraph. + if a is not equal to -1 and b is not equal to -1 + then perform subtraction-paragraph. +split-source-paragraph. + unstring source-string delimited by all spaces + into memory(loop-counter) + with pointer string-pointer. + add 1 to instruction-counter. +input-paragraph. + display '> ' with no advancing. + accept input-output-character from console. + add 1 to b giving adjusted-index-b. + move function ord(input-output-character) + to memory(adjusted-index-b). + subtract 1 from memory(adjusted-index-b). +output-paragraph. + add 1 to a giving adjusted-index-a. + add 1 to memory(adjusted-index-a) giving output-character-code. + move function char(output-character-code) + to input-output-character. + display input-output-character with no advancing. +subtraction-paragraph. + add 1 to c. + add 1 to a giving adjusted-index-a. + add 1 to b giving adjusted-index-b. + subtract memory(adjusted-index-a) from memory(adjusted-index-b). + if memory(adjusted-index-b) is equal to zero + or memory(adjusted-index-b) is negative + then move c to instruction-pointer. diff --git a/Task/Subleq/EasyLang/subleq.easy b/Task/Subleq/EasyLang/subleq.easy index 2d996fb92c..8213881bc5 100644 --- a/Task/Subleq/EasyLang/subleq.easy +++ b/Task/Subleq/EasyLang/subleq.easy @@ -15,17 +15,17 @@ func inp . . proc subleq &mem[] . repeat - a = mem[p] - b = mem[p + 1] - c = mem[p + 2] + a = mem[p + 1] + b = mem[p + 2] + c = mem[p + 3] p += 3 if a = -1 - mem[b] = inp + mem[b + 1] = inp elif b = -1 - write strchar mem[a] + write strchar mem[a + 1] else - mem[b] -= mem[a] - if mem[b] <= 0 + mem[b + 1] -= mem[a + 1] + if mem[b + 1] <= 0 p = c . . @@ -33,8 +33,6 @@ proc subleq &mem[] . . . prog[] = [ 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 ] -arrbase prog[] 0 -# subleq prog[] # input_data diff --git a/Task/Subleq/JavaScript/subleq.js b/Task/Subleq/JavaScript/subleq.js new file mode 100644 index 0000000000..5bd34cc352 --- /dev/null +++ b/Task/Subleq/JavaScript/subleq.js @@ -0,0 +1,43 @@ +class Subleq { + static main() { + const mem = [ + 15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, + 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, + 119, 111, 114, 108, 100, 33, 10, 0 + ]; + const readline = require('readline').createInterface({ + input: process.stdin, + output: process.stdout + }); + + let instructionPointer = 0; + const loop = () => { + const a = mem[instructionPointer]; + const b = mem[instructionPointer + 1]; + + if (a === -1) { + readline.question('', (input) => { + mem[b] = parseInt(input, 10); + instructionPointer += 3; + loop(); + }); + } else if (b === -1) { + process.stdout.write(String.fromCharCode(mem[a])); + instructionPointer += 3; + loop(); + } else { + mem[b] -= mem[a]; + if (mem[b] < 1) { + instructionPointer = mem[instructionPointer + 2]; + } else { + instructionPointer += 3; + } + loop(); + } + }; + loop(); + } +} + +// Run the main function +Subleq.main(); diff --git a/Task/Subleq/Pluto/subleq.pluto b/Task/Subleq/Pluto/subleq.pluto new file mode 100644 index 0000000000..8f1bd99fd4 --- /dev/null +++ b/Task/Subleq/Pluto/subleq.pluto @@ -0,0 +1,26 @@ +require "io2" + +local function subleq(program) + local words = program:split(" "):map(|w| -> tonumber(w)) + local sb = "" + local ip = 0 + while true do + local a = words[ip + 1] + local b = words[ip + 2] + local c = words[ip + 3] + ip += 3 + if a < 0 then + words[b + 1] = tonumber(io.readStr("Enter a character : ", 1, 1)) + elseif b < 0 then + sb ..= string.char(words[a + 1]) + else + words[b + 1] -= words[a + 1] + if words[b + 1] <= 0 then ip = c end + if ip < 0 then break end + end + end + io.write(sb) +end + +local program = "15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0" +subleq(program) diff --git a/Task/Subleq/PowerShell/subleq-1.ps1 b/Task/Subleq/PowerShell/subleq-1.ps1 new file mode 100644 index 0000000000..36b44ea26f --- /dev/null +++ b/Task/Subleq/PowerShell/subleq-1.ps1 @@ -0,0 +1,37 @@ +function Invoke-Subleq ([int[]]$Program) +{ + [int]$ip, [string]$output = $null + + try + { + while ($ip -ge 0) + { + if ($Program[$ip] -eq -1) + { + $Program[$Program[$ip + 1]] = [int](Read-Host -Prompt SUBLEQ)[0] + } + elseif ($Program[$ip + 1] -eq -1) + { + $output += "$([char]$Program[$Program[$ip]])" + } + else + { + $Program[$Program[$ip + 1]] -= $Program[$Program[$ip]] + + if ($Program[$Program[$ip + 1]] -le 0) + { + $ip = $Program[$ip + 2] + continue + } + } + + $ip += 3 + } + + return $output + } + catch [IndexOutOfRangeException],[Exception] + { + Write-Host "$($Error[0].Exception.Message)" -ForegroundColor Red + } +} diff --git a/Task/Subleq/PowerShell/subleq-2.ps1 b/Task/Subleq/PowerShell/subleq-2.ps1 new file mode 100644 index 0000000000..5cc5b15580 --- /dev/null +++ b/Task/Subleq/PowerShell/subleq-2.ps1 @@ -0,0 +1 @@ +Invoke-Subleq -Program 15,17,-1,17,-1,-1,16,1,-1,16,3,-1,15,15,0,0,-1,72,101,108,108,111,44,32,119,111,114,108,100,33,10,0 diff --git a/Task/Substitution-cipher/Ada/substitution-cipher.adb b/Task/Substitution-cipher/Ada/substitution-cipher.adb new file mode 100644 index 0000000000..951d7867da --- /dev/null +++ b/Task/Substitution-cipher/Ada/substitution-cipher.adb @@ -0,0 +1,46 @@ +with Ada.Command_Line; use Ada.Command_Line; +with Ada.Sequential_IO; +with Ada.Strings.Maps; use Ada.Strings.Maps; +with Ada.Text_IO; + +procedure Cipher is + package Char_IO is new Ada.Sequential_IO (Character); + use Char_IO; + Alphabet: constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + Key : constant String := "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"; + My_Map : Character_Mapping; + Input, Output : File_Type; + Buffer : Character; +begin + declare + use Ada.Text_IO; + begin + if Argument_Count /= 1 then + Put_Line("Usage: " & Command_Name & " "); + else + if Argument(1) = "encode" then + My_Map := To_Mapping(From => Alphabet, To => Key); + elsif Argument(1) = "decode" then + My_Map := To_Mapping(From => Key, To => Alphabet); + else + Put_Line("Unrecognised Argument: " & Argument(1)); + return; + end if; + end if; + end; + Open (File => Input, Mode => In_File, Name => "input.txt"); + Create (File => Output, Mode => Out_File, Name => "output.txt"); + loop + Read (File => Input, Item => Buffer); + Buffer := Value(Map => My_Map, Element => Buffer); + Write (File => Output, Item => Buffer); + end loop; +exception + when Char_IO.End_Error => + if Is_Open(Input) then + Close (Input); + end if; + if Is_Open(Output) then + Close (Output); + end if; +end Cipher; diff --git a/Task/Substitution-cipher/Emacs-Lisp/substitution-cipher.el b/Task/Substitution-cipher/Emacs-Lisp/substitution-cipher.el new file mode 100644 index 0000000000..25e6295f10 --- /dev/null +++ b/Task/Substitution-cipher/Emacs-Lisp/substitution-cipher.el @@ -0,0 +1,41 @@ +(setq alphabet "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") +(setq code "odrmqbjnwzvueghlacyfpktisxODRMQBJNWZVUEGHLACYFPKTISX") + +(defun encode (text) + "Encode TEXT with simple substitution code. +Each letter is replaced with the a random letter. +A specific letter in the original will always be replaced +by the same coded letter." + (let* ((case-fold-search nil) + (text-length (length text)) + (encoded-text "") + (current-letter "") + (coded-letter "") + (alphabet-position)) + (dotimes (i text-length) + (setq current-letter (substring text i (+ 1 i))) ; find the next letter in TEXT + (if (not (string-match-p "[a-zA-Z]" current-letter)) ; IF it's not a letter + (setq coded-letter current-letter) ; pass the non-letter without change + (setq alphabet-position (string-match current-letter alphabet)) ; ELSE find where the letter is in ALPHABET + (setq coded-letter (substring code alphabet-position (+ 1 alphabet-position)))) ; AND pass the coded letter + (setq encoded-text (concat encoded-text coded-letter))) ; IN ANY CASE, add new letter to ENCODED-TEXT + encoded-text)) + +(defun decode (text) + "Decode TEXT encoded with simple substitution code. +Each coded letter is replaced with the corresponding +uncoded letter." + (let* ((case-fold-search nil) + (text-length (length text)) + (uncoded-text "") + (current-letter "") + (uncoded-letter "") + (code-position)) + (dotimes (i text-length) + (setq current-letter (substring text i (+ 1 i))) ; find the next letter in TEXT + (if (not (string-match-p "[a-zA-Z]" current-letter)) ; IF it's not a letter + (setq uncoded-letter current-letter) ; pass the non-letter without change + (setq code-position (string-match current-letter code)) ; ELSE find where the letter is in CODE + (setq uncoded-letter (substring alphabet code-position (+ 1 code-position)))) ; AND pass the uncoded letter + (setq uncoded-text (concat uncoded-text uncoded-letter))) ; IN ANY CASE, add new letter to UNCODED-TEXT + uncoded-text)) diff --git a/Task/Substitution-cipher/R/substitution-cipher.r b/Task/Substitution-cipher/R/substitution-cipher.r new file mode 100644 index 0000000000..05ccfa527d --- /dev/null +++ b/Task/Substitution-cipher/R/substitution-cipher.r @@ -0,0 +1,10 @@ +plain_chars <- c(letters, LETTERS) +cipher_chars <- sample(plain_chars, 52) +codex <- sapply(list(plain_chars, cipher_chars), + function(v) paste0(v, collapse="")) + +plaintext <- "The five boxing wizards jump quickly." +encode <- function(s) chartr(codex[1], codex[2], s) +decode <- function(s) chartr(codex[2], codex[1], s) +ciphertext <- plaintext |> encode() |> print() +ciphertext |> decode() diff --git a/Task/Substitution-cipher/VBScript/substitution-cipher.vbs b/Task/Substitution-cipher/VBScript/substitution-cipher.vbs new file mode 100644 index 0000000000..e96a552bd0 --- /dev/null +++ b/Task/Substitution-cipher/VBScript/substitution-cipher.vbs @@ -0,0 +1,55 @@ +option explicit +const maxk=94 +dim key(94) + +a="I'm working on modernizing Rosetta Code's infrastructure. Starting with communications."&_ +" Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)" + +sub gen 'swaps items not previusly affected by a swap + dim i,m,t + for i=0 to ubound(key) + key(i)=i+32 + next + for i=0 to ubound(key)-1 + if key(i)=i+32 then + m=i+int(rnd*(maxk-i)) + if key(m)=m+32 then + t=key(m):key(m)=key(i):key(i)=t + end if + end if + next +end sub + +function viewkey +dim i,b +b="" +for i=1 to ubound(key) + b=b&chr(key(i)) +next +viewkey=b +end function + +function iif(a,b,c) if a then iif=b else iif =c end if: end function + +function docode(a) + dim b,i,ch,n + n=maxk+32 + b="" + for i=1 to len(a) + ch=asc(mid(a,i,1)) + 'wscript.echo ch + b=b&chr(key(iif (ch>n or ch<32,0,ch-32))) + next + docode=b +end function + +randomize timer +dim a,b,c +gen +wscript.echo "Key: " & viewkey & vbcrlf +wscript.echo "Original: " & a & Vbcrlf +b=docode(a) +wscript.echo "Encoded: "& b & Vbcrlf +c=docode(b) +wscript.echo "Decoded: " & c & Vbcrlf +wscript.quit(0) diff --git a/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-1.adb b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-1.adb new file mode 100644 index 0000000000..875c71f5db --- /dev/null +++ b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-1.adb @@ -0,0 +1,11 @@ +with Ada.Text_IO; + +procedure Remove_Characters is + S: String := "upraisers"; + use Ada.Text_IO; +begin + Put_Line("Full String: """ & S & """"); + Put_Line("Without_First: """ & S(S'First+1 .. S'Last) & """"); + Put_Line("Without_Last: """ & S(S'First .. S'Last-1) & """"); + Put_Line("Without_Both: """ & S(S'First+1 .. S'Last-1) & """"); +end Remove_Characters; diff --git a/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.adb b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.adb new file mode 100644 index 0000000000..88cba96406 --- /dev/null +++ b/Task/Substring-Top-and-tail/Ada/substring-top-and-tail-2.adb @@ -0,0 +1,33 @@ +with Ada.Text_IO; +with Ada.Strings.UTF_Encoding.Wide_Strings; + +procedure Remove_Characters +is + use Ada.Text_IO; + use Ada.Strings.UTF_Encoding; + use Ada.Strings.UTF_Encoding.Wide_Strings; + + S : String := "upraisers"; + U : Wide_String := Decode (UTF_8_String'(S)); + + function To_String (X : Wide_String)return String + is + begin + return String (UTF_8_String'(Encode (X))); + end To_String; + +begin + Put_Line + (To_String + ("Full String: """ & U & """")); + Put_Line + (To_String + ("Without_First: """ & U (U'First + 1 .. U'Last) & """")); + Put_Line + (To_String + ("Without_Last: """ & U (U'First .. U'Last - 1) & """")); + Put_Line + (To_String + ("Without_Both: """ & U (U'First + 1 .. U'Last - 1) & """")); + +end Remove_Characters; diff --git a/Task/Substring-Top-and-tail/COBOL/substring-top-and-tail.cob b/Task/Substring-Top-and-tail/COBOL/substring-top-and-tail.cob new file mode 100644 index 0000000000..a2613e3a46 --- /dev/null +++ b/Task/Substring-Top-and-tail/COBOL/substring-top-and-tail.cob @@ -0,0 +1,17 @@ + identification division. + program-id. toptail. + + data division. + working-storage section. + 01 data-field. + 05 value "[this is a test]". + + procedure division. + sample-main. + display data-field + *> Using reference modification, which is (start-position:length) + display data-field(2:) + display data-field(1:length of data-field - 1) + display data-field(2:length of data-field - 2) + goback. + end program toptail. diff --git a/Task/Substring-Top-and-tail/Crystal/substring-top-and-tail.cr b/Task/Substring-Top-and-tail/Crystal/substring-top-and-tail.cr new file mode 100644 index 0000000000..3b2188e9bf --- /dev/null +++ b/Task/Substring-Top-and-tail/Crystal/substring-top-and-tail.cr @@ -0,0 +1,11 @@ +str = "abcde" +# String with first character removed +str[1..] #=> "bcde" +str.lchop #=> "bcde" + +# String with last character removed +str[..-2] #=> "abcd" +str.rchop #=> "abcd" + +# String with both the first and last characters removed +str[1..-2] #=> "bcd" diff --git a/Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.el b/Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.el new file mode 100644 index 0000000000..8f1d129618 --- /dev/null +++ b/Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.el @@ -0,0 +1,4 @@ +(let ((string "top and tail")) + (substring string 1) ;=> "op and tail" + (substring string 0 (1- (length string))) ;=> "top and tai" + (substring string 1 (1- (length string)))) ;=> "op and tai" diff --git a/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.eu b/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.eu new file mode 100644 index 0000000000..5b325e8784 --- /dev/null +++ b/Task/Substring-Top-and-tail/Euphoria/substring-top-and-tail.eu @@ -0,0 +1,15 @@ +function strip_first(sequence s) + return s[2..$] +end function + +function strip_last(sequence s) + return s[1..$-1] +end function + +function strip_both(sequence s) + return s[2..$-1] +end function + +puts(1, strip_first("knight")) -- strip first character +puts(1, strip_last("write")) -- strip last character +puts(1, strip_both("brooms")) -- strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Phix/substring-top-and-tail.phix b/Task/Substring-Top-and-tail/Phix/substring-top-and-tail.phix index 85467618c6..a6679e035e 100644 --- a/Task/Substring-Top-and-tail/Phix/substring-top-and-tail.phix +++ b/Task/Substring-Top-and-tail/Phix/substring-top-and-tail.phix @@ -1,6 +1,4 @@ ---> - constant s = "(test)" - ?s[2..-1] - ?s[1..-2] - ?s[2..-2] - - with javascript_semantics - constant primes = get_primes_le(1_000_000) - procedure test(sequence differences) - sequence res = {} - integer ld = length(differences) - for i=1 to length(primes)-ld do - integer pi = primes[i] - for j=1 to ld do - pi += differences[j] - if pi!=primes[i+j] then - pi = 0 - exit - end if - end for - if pi!=0 then - res = append(res,primes[i..i+ld]) - end if - end for - res = {differences,length(res),res[1],res[$]} - printf(1,"%8V : %8d %14V...%V\n",res) - end procedure +with javascript_semantics +constant primes = get_primes_le(1_000_000) +procedure test(sequence differences) + sequence res = {} + integer ld = length(differences) + for i=1 to length(primes)-ld do + integer pi = primes[i] + for j=1 to ld do + pi += differences[j] + if pi!=primes[i+j] then + pi = 0 + exit + end if + end for + if pi!=0 then + res = append(res,primes[i..i+ld]) + end if + end for + res = {differences,length(res),res[1],res[$]} + printf(1,"%8V : %8d %14V...%V\n",res) +end procedure - printf(1,"Differences Count First Last\n") - papply({{2},{1},{2,2},{2,4},{4,2},{6,4,2}},test) - - with javascript_semantics - string n = "000000" +with javascript_semantics +string n = "000000" - function incn() - for i=length(n) to 1 by -1 do - if n[i]='9' then - if i=1 then return false end if - n[i]='0' - else - n[i] += 1 - exit - end if - end for - return true - end function +function incn() + for i=length(n) to 1 by -1 do + if n[i]='9' then + if i=1 then return false end if + n[i]='0' + else + n[i] += 1 + exit + end if + end for + return true +end function - sequence res = {}, bestseen - integer maxcycle = 0 +sequence res = {}, bestseen +integer maxcycle = 0 - procedure srs() - sequence curr = n - while length(curr)>1 and curr[1]='0' do - curr = curr[2..$] - end while - integer ch = curr[1] - for i=2 to length(curr) do - if curr[i]>ch then return end if - ch = curr[i] - end for - sequence seen = {curr} - integer cycle = 1 - while true do - sequence digits = repeat(0,10) - for i=1 to length(curr) do - integer idx = curr[i]-'0'+1 - digits[idx] += 1 - end for - string next = "" - for i=length(digits) to 1 by -1 do - if digits[i]!=0 then - next &= sprint(digits[i]) - next &= i+'0'-1 - end if - end for - if find(next,seen) then exit end if - seen = append(seen,next) - curr = next - cycle += 1 - end while - if cycle>maxcycle then - res = {seen[1]} - maxcycle = cycle - bestseen = seen - elsif cycle=maxcycle then - res = append(res,seen[1]) - end if - end procedure +procedure srs() + sequence curr = n + while length(curr)>1 and curr[1]='0' do + curr = curr[2..$] + end while + integer ch = curr[1] + for i=2 to length(curr) do + if curr[i]>ch then return end if + ch = curr[i] + end for + sequence seen = {curr} + integer cycle = 1 + while true do + sequence digits = repeat(0,10) + for i=1 to length(curr) do + integer idx = curr[i]-'0'+1 + digits[idx] += 1 + end for + string next = "" + for i=length(digits) to 1 by -1 do + if digits[i]!=0 then + next &= sprint(digits[i]) + next &= i+'0'-1 + end if + end for + if find(next,seen) then exit end if + seen = append(seen,next) + curr = next + cycle += 1 + end while + if cycle>maxcycle then + res = {seen[1]} + maxcycle = cycle + bestseen = seen + elsif cycle=maxcycle then + res = append(res,seen[1]) + end if +end procedure - while true do - srs() - if not incn() then exit end if - end while +while true do + srs() + if not incn() then exit end if +end while - -- add non-leading-0 perms: - for i=length(res) to 1 by -1 do - string ri = res[i] - for p=1 to factorial(length(ri)) do - string pri = permute(p,ri) - if pri[1]!='0' and not find(pri,res) then - res = append(res,pri) - end if - end for - end for - ?res - puts(1,"cycle length is ") ?maxcycle - pp(bestseen,{pp_Nest,1}) - - for i=1 to 100 do - printf(1,"%3d",{length(factors(i,1))}) - if remainder(i,20)=0 then puts(1,"\n") end if - end for - - sequence r = apply(apply(true,factors,{tagset(100),{1}}),length) - puts(1,join_by(apply(true,sprintf,{{"%3d"},r}),1,20,"")) - - enum T, M, F - type ternary(integer t) return find(t,{T,M,F}) end type +enum T, M, F +type ternary(integer t) return find(t,{T,M,F}) end type - function t_not(ternary a) - return F+1-a - end function +function t_not(ternary a) + return F+1-a +end function - function t_and(ternary a, ternary b) - return iff(a=T and b=T?T:iff(a=F or b=F?F:M)) - end function +function t_and(ternary a, ternary b) + return iff(a=T and b=T?T:iff(a=F or b=F?F:M)) +end function - function t_or(ternary a, ternary b) - return iff(a=T or b=T?T:iff(a=F and b=F?F:M)) - end function +function t_or(ternary a, ternary b) + return iff(a=T or b=T?T:iff(a=F and b=F?F:M)) +end function - function t_xor(ternary a, ternary b) - return iff(a=M or b=M?M:iff(a=b?F:T)) - end function +function t_xor(ternary a, ternary b) + return iff(a=M or b=M?M:iff(a=b?F:T)) +end function - function t_implies(ternary a, ternary b) - return iff(a=F or b=T?T:iff(a=T and b=F?F:M)) - end function +function t_implies(ternary a, ternary b) + return iff(a=F or b=T?T:iff(a=T and b=F?F:M)) +end function - function t_equal(ternary a, ternary b) - return iff(a=M or b=M?M:iff(a=b?T:F)) - end function +function t_equal(ternary a, ternary b) + return iff(a=M or b=M?M:iff(a=b?T:F)) +end function - function t_string(ternary a) - return iff(a=T?"T":iff(a=M?"?":"F")) - end function +function t_string(ternary a) + return iff(a=T?"T":iff(a=M?"?":"F")) +end function - procedure show_truth_table(integer rid, integer unary, string name) - printf(1,"%-3s |%s\n",{name,iff(unary?"":" T | ? | F")}) - printf(1,"----+---%s\n",{iff(unary?"":"+---+---")}) - for x=T to F do - printf(1," %s ",{t_string(x)}) - if unary then - printf(1," | %s",{t_string(rid(x))}) - else - for y=T to F do - printf(1," | %s",{t_string(rid(x,y))}) - end for - end if - printf(1,"\n") - end for - printf(1,"\n") - end procedure +procedure show_truth_table(integer rid, integer unary, string name) + printf(1,"%-3s |%s\n",{name,iff(unary?"":" T | ? | F")}) + printf(1,"----+---%s\n",{iff(unary?"":"+---+---")}) + for x=T to F do + printf(1," %s ",{t_string(x)}) + if unary then + printf(1," | %s",{t_string(rid(x))}) + else + for y=T to F do + printf(1," | %s",{t_string(rid(x,y))}) + end for + end if + printf(1,"\n") + end for + printf(1,"\n") +end procedure - show_truth_table(t_not,1,"not") - show_truth_table(t_and,0,"and") - show_truth_table(t_or,0,"or") - show_truth_table(t_xor,0,"xor") - show_truth_table(t_implies,0,"imp") - show_truth_table(t_equal,0,"eq") - - with javascript_semantics - constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516}, - {-1.4944608174, 1.2077959613, 1.1039549836}, - { 0.6110294452, -0.6907087527, 0.9089162485}, - { 0.3844862411, 0.2923344616, 0.2375743054}, - {-0.2495892950, -0.3832854473, 1.0845181219}, - { 1.7813504266, 1.6178237031, 0.8162655711}, - {-0.1985249206, -0.8343333301, 0.0538864941}, - {-1.7011985145, -0.1263820964, 0.4776976918}, - {-0.4319462812, 1.4104420482, 0.7886291537}, - { 0.2178372997, -0.9499557344, 0.0357871187}, - {-0.6294854565, -1.3078893852, 0.7653357688}, - { 1.7952608455, 0.6281269104, 0.2727652452}, - { 1.4168575317, 1.0683357171, 1.1016025378}, - { 1.4637371396, 0.9463877418, 1.1846214562}, - {-0.5263668798, 1.7315156631, 1.4428514068}, - {-1.2197352481, 0.9144146579, 1.0727263474}, - {-0.1389358881, 0.1092805780, 0.7350208828}, - { 1.5293954595, 0.0030278255, 1.2472867347}, - {-0.5258728625, 1.3782633069, 1.3495508831}, - {-0.1403562064, 0.2437382535, 1.3804956588}, - { 0.8055826339, -0.0482092025, 0.3327165165}, - {-0.6311979224, 0.7184578971, 0.2491045282}, - { 1.4685857879, -0.8347049536, 1.3670667538}, - {-0.6855727502, 1.6465021616, 1.0593087096}, - { 0.0152957411, 0.0638919221, 0.9771215985}}, - {x,y,r} = columnize(circles), - r2 = sq_power(r,2) +with javascript_semantics +constant circles = {{ 1.6417233788, 1.6121789534, 0.0848270516}, + {-1.4944608174, 1.2077959613, 1.1039549836}, + { 0.6110294452, -0.6907087527, 0.9089162485}, + { 0.3844862411, 0.2923344616, 0.2375743054}, + {-0.2495892950, -0.3832854473, 1.0845181219}, + { 1.7813504266, 1.6178237031, 0.8162655711}, + {-0.1985249206, -0.8343333301, 0.0538864941}, + {-1.7011985145, -0.1263820964, 0.4776976918}, + {-0.4319462812, 1.4104420482, 0.7886291537}, + { 0.2178372997, -0.9499557344, 0.0357871187}, + {-0.6294854565, -1.3078893852, 0.7653357688}, + { 1.7952608455, 0.6281269104, 0.2727652452}, + { 1.4168575317, 1.0683357171, 1.1016025378}, + { 1.4637371396, 0.9463877418, 1.1846214562}, + {-0.5263668798, 1.7315156631, 1.4428514068}, + {-1.2197352481, 0.9144146579, 1.0727263474}, + {-0.1389358881, 0.1092805780, 0.7350208828}, + { 1.5293954595, 0.0030278255, 1.2472867347}, + {-0.5258728625, 1.3782633069, 1.3495508831}, + {-0.1403562064, 0.2437382535, 1.3804956588}, + { 0.8055826339, -0.0482092025, 0.3327165165}, + {-0.6311979224, 0.7184578971, 0.2491045282}, + { 1.4685857879, -0.8347049536, 1.3670667538}, + {-0.6855727502, 1.6465021616, 1.0593087096}, + { 0.0152957411, 0.0638919221, 0.9771215985}}, + {x,y,r} = columnize(circles), + r2 = sq_power(r,2) - atom xMin = min(sq_sub(x,r)), - xMax = max(sq_add(x,r)), - yMin = min(sq_sub(y,r)), - yMax = max(sq_add(y,r)), - boxSide = 500, - dx = (xMax - xMin) / boxSide, - dy = (yMax - yMin) / boxSide, - count = 0 - sequence cxs = {} - for s=1 to boxSide do - atom py = yMin + s * dy - sequence cy = sq_power(sq_sub(py,y),2) - for c=1 to boxSide do - if s=1 then - atom px = xMin + c * dx - cxs = append(cxs,sq_power(sq_sub(px,x),2)) - end if - sequence cx = cxs[c] - for i=1 to length(circles) do - if cx[i]+cy[i]<=r2[i] then count+=1 exit end if - end for - end for - end for - printf(1,"Approximate area = %.9f\n",{count * dx * dy}) -too large<--"); + end; + TIO.New_Line; + end loop; + +end Trabb_Pardo_Knuth; diff --git a/Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.au3 b/Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.au3 new file mode 100644 index 0000000000..dfad5694f6 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/AutoIt/trabb-pardo-knuth-algorithm.au3 @@ -0,0 +1,24 @@ +; Trabb Pardo–Knuth algorithm +; by James1337 (autoit.de) +; AutoIt Version: 3.3.8.1 + +Local $S, $i, $y + +Do + $S = InputBox("Trabb Pardo–Knuth algorithm", "Please enter 11 numbers:", "1 2 3 4 5 6 7 8 9 10 11") + If @error Then Exit + $S = StringSplit($S, " ") +Until ($S[0] = 11) + +For $i = 11 To 1 Step -1 + $y = f($S[$i]) + If ($y > 400) Then + ConsoleWrite("f(" & $S[$i] & ") = Overflow!" & @CRLF) + Else + ConsoleWrite("f(" & $S[$i] & ") = " & $y & @CRLF) + EndIf +Next + +Func f($x) + Return Sqrt(Abs($x)) + 5*$x^3 +EndFunc diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.ps1 b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.ps1 new file mode 100644 index 0000000000..f03504c148 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-1.ps1 @@ -0,0 +1,49 @@ +function Get-Tpk +{ + [CmdletBinding()] + [OutputType([PSCustomObject])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + ValueFromPipelineByPropertyName=$true, + Position=0)] + [double] + $Number + ) + + Begin + { + function Get-TpkFunction ([double]$Number) + { + [Math]::Pow([Math]::Abs($Number),(0.5)) + 5 * [Math]::Pow($Number,3) + } + + [object[]]$output = @() + } + Process + { + $Number | ForEach-Object { + $n = Get-TpkFunction $_ + + if ($n -le 400) + { + $result = $n + } + else + { + $result = "Overflow" + } + } + + $output += [PSCustomObject]@{ + Number = $Number + Result = $result + } + } + End + { + [Array]::Reverse($output) + $output + } +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.ps1 b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.ps1 new file mode 100644 index 0000000000..5611d61eb9 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-2.ps1 @@ -0,0 +1,2 @@ +$tpk = 1..11 | Get-Tpk +$tpk diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.ps1 b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.ps1 new file mode 100644 index 0000000000..7ce6994178 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PowerShell/trabb-pardo-knuth-algorithm-3.ps1 @@ -0,0 +1 @@ +$tpk | where result -ne overflow | sort number diff --git a/Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vbs b/Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vbs new file mode 100644 index 0000000000..8bb0e47935 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vbs @@ -0,0 +1,20 @@ +Function tpk(s) + arr = Split(s," ") + For i = UBound(arr) To 0 Step -1 + n = fx(CDbl(arr(i))) + If n > 400 Then + WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" + Else + WScript.StdOut.WriteLine arr(i) & " = " & n + End If + Next +End Function + +Function fx(x) + fx = Sqr(Abs(x))+5*x^3 +End Function + +'testing the function +WScript.StdOut.Write "Please enter a series of numbers:" +list = WScript.StdIn.ReadLine +tpk(list) diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Crystal/transliterate-english-text-using-the-greek-alphabet.cr b/Task/Transliterate-English-text-using-the-Greek-alphabet/Crystal/transliterate-english-text-using-the-greek-alphabet.cr new file mode 100644 index 0000000000..49a7319c52 --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Crystal/transliterate-english-text-using-the-greek-alphabet.cr @@ -0,0 +1,27 @@ +DICT = %w( α a . β b v . γ g . δ d . ε e . ζ z . η h ee . θ th . + ι i j . κ c k q ck . λ l . μ m . ν n . ξ x . ο o . π p . + ρ r rh . σ s . τ t . υ u y . φ f ph . χ ch kh . ψ ps . ω w oo) + .chunks(&.==(".")).each_step(2).map {|_, l| l[1..].map {|e| { e, l.first } } } + .flatten.to_h + +RE = Regex.union DICT.keys.sort_by {|k| -k.size}.map {|k| Regex.literal k, i: true } + +def transliterate (s) + s.gsub(RE) {|s| + replacement = DICT[s.downcase] + replacement = replacement.upcase if s[0].uppercase? + replacement + } + .gsub(/σ\b/, "ς") +end + +text = <<-EOT +I was looking at some rhododendrons in my back garden, +dressed in my khaki shorts, when the telephone rang. + +As I answered it, I cheerfully glimpsed that the July sun +caused a fragment of black pine wax to ooze on the velvet quilt +laying in my patio. +EOT + +puts transliterate(text) diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Java/transliterate-english-text-using-the-greek-alphabet.java b/Task/Transliterate-English-text-using-the-Greek-alphabet/Java/transliterate-english-text-using-the-greek-alphabet.java index ce63f65b55..7def6e8912 100644 --- a/Task/Transliterate-English-text-using-the-Greek-alphabet/Java/transliterate-english-text-using-the-greek-alphabet.java +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Java/transliterate-english-text-using-the-greek-alphabet.java @@ -2,46 +2,46 @@ import java.util.List; public final class TransliterateEnglishTextUsingTheGreekAlphabet { - public static void main(String[] args) { - List tests = List.of( - "The quick brown fox jumps over the lazy dog.", // Note: "jumps" not "jumped" - """ - I was looking at some rhododendrons in my back garden, - dressed in my khaki shorts, when the telephone rang. + public static void main(String[] args) { + List tests = List.of( + "The quick brown fox jumps over the lazy dog.", // Note: "jumps" not "jumped" + """ + I was looking at some rhododendrons in my back garden, + dressed in my khaki shorts, when the telephone rang. - As I answered it, I cheerfully glimpsed that the July sun - caused a fragment of black pine wax to ooze on the velvet quilt - laying in my patio.""", - "sphinx of black quartz, judge my vow."); - - String[][] pairs = new String[][] { - { "CH", "Χ" }, { "Ch", "Χ" }, { "ch", "χ" }, { "CK", "Κ" }, { "Ck", "Κ" }, { "ck", "κ" }, - { "EE", "Η" }, { "Ee", "Η" }, { "ee", "η" }, { "KH", "Χ" }, { "Kh", "Χ" }, { "kh", "χ" }, - { "OO", "Ω" }, { "Oo", "Ω" }, { "oo", "ω" }, { "PH", "Φ" }, { "Ph", "Φ" }, { "ph", "ϕ" }, - { "PS", "Ψ" }, { "Ps", "Ψ" }, { "ps", "ψ" }, { "RH", "Ρ" }, { "Rh", "Ρ" }, { "rh", "ρ" }, - { "TH", "Θ" }, { "Th", "Θ" }, { "th", "θ" }, { "A", "Α" }, { "a", "α" }, { "B", "Β" }, - { "b", "β" }, { "C", "Κ" }, { "c", "κ" }, { "D", "Δ" }, { "d", "δ" }, { "E", "Ε" }, { "e", "ε" }, - { "F", "Φ" }, { "f", "ϕ" }, { "G", "Γ" }, { "g", "γ" }, { "H", "Ε" }, { "h", "ε" }, { "I", "Ι" }, - { "i", "ι" }, { "J", "Ι" }, { "j", "ι" }, { "K", "Κ" }, { "k", "κ" }, { "L", "Λ" }, { "l", "λ" }, - { "M", "Μ" }, { "m", "μ" }, { "N", "Ν" }, { "n", "ν" }, { "O", "Ο" }, { "o", "ο" }, { "P", "Π" }, - { "p", "π" }, { "Q", "Κ" }, { "q", "κ" }, { "R", "Ρ" }, { "r", "ρ" }, { "S", "Σ" }, { "s", "σ" }, - { "T", "Τ" }, { "t", "τ" }, { "U", "Υ" }, { "u", "υ" }, { "V", "Β" }, { "v", "β" }, { "W", "Ω" }, - { "w", "ω" }, { "X", "Ξ" }, { "x", "ξ" }, { "Y", "Υ" }, { "y", "υ" }, { "Z", "Ζ" }, { "z", "ζ" } }; + As I answered it, I cheerfully glimpsed that the July sun + caused a fragment of black pine wax to ooze on the velvet quilt + laying in my patio.""", + "sphinx of black quartz, judge my vow."); - for ( String test : tests ) { - String greek = test; - for ( int i = 0; i < greek.length(); i++ ) { - if ( greek.charAt(i) == 's' && ! Character.isAlphabetic(greek.charAt(i + 1)) ) { - greek = greek.substring(0, i) + 'ς' + greek.substring(i + 1); - } - } - - for ( String[] pair : pairs ) { - greek = greek.replace(pair[0], pair[1]); - } - System.out.println(test + System.lineSeparator() + " =>" + System.lineSeparator() + greek); - System.out.println("=".repeat(65)); - } - } + String[][] pairs = new String[][] { + { "CH", "Χ" }, { "Ch", "Χ" }, { "ch", "χ" }, { "CK", "Κ" }, { "Ck", "Κ" }, { "ck", "κ" }, + { "EE", "Η" }, { "Ee", "Η" }, { "ee", "η" }, { "KH", "Χ" }, { "Kh", "Χ" }, { "kh", "χ" }, + { "OO", "Ω" }, { "Oo", "Ω" }, { "oo", "ω" }, { "PH", "Φ" }, { "Ph", "Φ" }, { "ph", "ϕ" }, + { "PS", "Ψ" }, { "Ps", "Ψ" }, { "ps", "ψ" }, { "RH", "Ρ" }, { "Rh", "Ρ" }, { "rh", "ρ" }, + { "TH", "Θ" }, { "Th", "Θ" }, { "th", "θ" }, { "A", "Α" }, { "a", "α" }, { "B", "Β" }, + { "b", "β" }, { "C", "Κ" }, { "c", "κ" }, { "D", "Δ" }, { "d", "δ" }, { "E", "Ε" }, { "e", "ε" }, + { "F", "Φ" }, { "f", "ϕ" }, { "G", "Γ" }, { "g", "γ" }, { "H", "Ε" }, { "h", "ε" }, { "I", "Ι" }, + { "i", "ι" }, { "J", "Ι" }, { "j", "ι" }, { "K", "Κ" }, { "k", "κ" }, { "L", "Λ" }, { "l", "λ" }, + { "M", "Μ" }, { "m", "μ" }, { "N", "Ν" }, { "n", "ν" }, { "O", "Ο" }, { "o", "ο" }, { "P", "Π" }, + { "p", "π" }, { "Q", "Κ" }, { "q", "κ" }, { "R", "Ρ" }, { "r", "ρ" }, { "S", "Σ" }, { "s", "σ" }, + { "T", "Τ" }, { "t", "τ" }, { "U", "Υ" }, { "u", "υ" }, { "V", "Β" }, { "v", "β" }, { "W", "Ω" }, + { "w", "ω" }, { "X", "Ξ" }, { "x", "ξ" }, { "Y", "Υ" }, { "y", "υ" }, { "Z", "Ζ" }, { "z", "ζ" } }; + + for ( String test : tests ) { + String greek = test; + for ( int i = 0; i < greek.length(); i++ ) { + if ( greek.charAt(i) == 's' && ! Character.isAlphabetic(greek.charAt(i + 1)) ) { + greek = greek.substring(0, i) + 'ς' + greek.substring(i + 1); + } + } + + for ( String[] pair : pairs ) { + greek = greek.replace(pair[0], pair[1]); + } + System.out.println(test + System.lineSeparator() + " =>" + System.lineSeparator() + greek); + System.out.println("=".repeat(65)); + } + } } diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/JavaScript/transliterate-english-text-using-the-greek-alphabet.js b/Task/Transliterate-English-text-using-the-Greek-alphabet/JavaScript/transliterate-english-text-using-the-greek-alphabet.js new file mode 100644 index 0000000000..bf3f2054de --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/JavaScript/transliterate-english-text-using-the-greek-alphabet.js @@ -0,0 +1,68 @@ +const regexps = {"\u0391": /A/g, + "\u0392": /[BV]/g, + "\u0393": /G/g, + "\u0394": /D/g, + "\u0395": /E(?!e)/g, + "\u0396": /Z/g, + "\u0397": /H|Ee/g, + "\u0398": /Th/g, + "\u0399": /[IJ]/g, + "\u039A": /(C|K)(?!h)|Q/g, + "\u039B": /L/g, + "\u039C": /M/g, + "\u039D": /N/g, + "\u039E": /X/g, + "\u039F": /O(?!o)/g, + "\u03A0": /P(?![hs])/g, + "\u03A1": /Rh|R/g, + "\u03A3": /S/g, + "\u03A4": /T(?!h)/g, + "\u03A5": /[UY]/g, + "\u03A6": /F|Ph/g, + "\u03A7": /(C|K)h/g, + "\u03A8": /Ps/g, + "\u03A9": /W|Oo/g, + "\u03B1": /a/g, + "\u03B2": /[bv]/g, + "\u03B3": /g/g, + "\u03B4": /d/g, + "\u03B5": /(? { - a=list:="ee":="η", "ch":="χ", "kh":="χ", "ph":="φ", "ps":="ψ", "th":="θ", "ck":="κ", "oo":="ω", "rh":="ρ" - b=list:="a":="α","b":="β","v":="β","g":="γ","d":="δ","e":="ε","z":="ζ","h":="η","i":="ι","j":="ι","c":="κ" - append b, "k":="κ","q":="κ","l":="λ","m":="μ","n":="ν","x":="ξ","o":="ο","p":="π","r":="ρ" - append b, "s":="σ","t":="τ","u":="υ","y":="υ","f":="φ","w":="ω" - =lambda a, b (s as string, no as integer) -> { - long i=1, j=len(s) - string r, rc, crlf={ - } - while i<=j - if exist(a, lcase$(mid$(s,i,2))) then - rc=eval$(a) - if mid$(s,i,1)<>left$(eval$(a!),1) then - r+=ucase$(left$(rc,1)) - else - r+=rc - end if - i+=2 - else.if exist(b,lcase$(mid$(s,i,1))) then - rc=eval$(b) // eval$(b!) is the key - if mid$(s,i,1)<>eval$(b!) then - r+=ucase$(rc) - else.if rc="σ" then - if exist(b,lcase$(mid$(s,i+1,1))) then - r+=rc - else - r+="ς" - end if - else - r+=rc - end if - i++ - else - r+=mid$(s,i,1) - i++ - end if - end while - =">>>> Text "+no+crlf+s+crlf+" =>"+crlf+r+crlf+crlf - } + a=list:="ee":="η", "ch":="χ", "kh":="χ", "ph":="φ", "ps":="ψ", "th":="θ", "ck":="κ", "oo":="ω", "rh":="ρ" + b=list:="a":="α","b":="β","v":="β","g":="γ","d":="δ","e":="ε","z":="ζ","h":="η","i":="ι","j":="ι","c":="κ" + append b, "k":="κ","q":="κ","l":="λ","m":="μ","n":="ν","x":="ξ","o":="ο","p":="π","r":="ρ" + append b, "s":="σ","t":="τ","u":="υ","y":="υ","f":="φ","w":="ω" + =lambda a, b (s as string, no as integer) -> { + long i=1, j=len(s) + string r, rc, crlf={ + } + while i<=j + if exist(a, lcase$(mid$(s,i,2))) then + rc=eval$(a) + if mid$(s,i,1)<>left$(eval$(a!),1) then + r+=ucase$(left$(rc,1)) + else + r+=rc + end if + i+=2 + else.if exist(b,lcase$(mid$(s,i,1))) then + rc=eval$(b) // eval$(b!) is the key + if mid$(s,i,1)<>eval$(b!) then + r+=ucase$(rc) + else.if rc="σ" then + if exist(b,lcase$(mid$(s,i+1,1))) then + r+=rc + else + r+="ς" + end if + else + r+=rc + end if + i++ + else + r+=mid$(s,i,1) + i++ + end if + end while + =">>>> Text "+no+crlf+s+crlf+" =>"+crlf+r+crlf+crlf + } } trans=process1() diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Mathematica/transliterate-english-text-using-the-greek-alphabet.math b/Task/Transliterate-English-text-using-the-Greek-alphabet/Mathematica/transliterate-english-text-using-the-greek-alphabet.math new file mode 100644 index 0000000000..ebbdbef8aa --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Mathematica/transliterate-english-text-using-the-greek-alphabet.math @@ -0,0 +1,16 @@ +replacements={"CH"->"Χ","Ch"->"Χ","ch"->"χ","CK"->"Κ","Ck"->"Κ","ck"->"κ","EE"->"Η","Ee"->"Η", + "ee"->"η","KH"->"Χ","Kh"->"Χ","kh"->"χ","OO"->"Ω","Oo"->"Ω","oo"->"ω","PH"->"Φ","Ph"->"Φ", + "ph"->"ϕ","PS"->"Ψ","Ps"->"Ψ","ps"->"ψ","RH"->"Ρ","Rh"->"Ρ","rh"->"ρ","TH"->"Θ","Th"->"Θ", + "th"->"θ","A"->"Α","a"->"α","B"->"Β","b"->"β","C"->"Κ","c"->"κ","D"->"Δ","d"->"δ","E"->"Ε", + "e"->"ε","F"->"Φ","f"->"ϕ","G"->"Γ","g"->"γ","H"->"Ε","h"->"ε","I"->"Ι","i"->"ι","J"->"Ι", + "j"->"ι","K"->"Κ","k"->"κ","L"->"Λ","l"->"λ","M"->"Μ","m"->"μ","N"->"Ν","n"->"ν","O"->"Ο", + "o"->"ο","P"->"Π","p"->"π","Q"->"Κ","q"->"κ","R"->"Ρ","r"->"ρ","S"->"Σ","s"~~WordBoundary->"ς", + "s"->"σ","T"->"Τ","t"->"τ","U"->"Υ","u"->"υ","V"->"Β","v"->"β","W"->"Ω","w"->"ω","X"->"Ξ", + "x"->"ξ","Y"->"Υ","y"->"υ","Z"->"Ζ","z"->"ζ"}; + +"I was looking at some rhododendrons in my back garden, +dressed in my khaki shorts, when the telephone rang. + +As I answered it, I cheerfully glimpsed that the July sun +caused a fragment of black pine wax to ooze on the velvet quilt +laying in my patio." // StringReplace[replacements] diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Microsoft-Small-Basic/transliterate-english-text-using-the-greek-alphabet.basic b/Task/Transliterate-English-text-using-the-Greek-alphabet/Microsoft-Small-Basic/transliterate-english-text-using-the-greek-alphabet.basic new file mode 100644 index 0000000000..eae7c31fe7 --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Microsoft-Small-Basic/transliterate-english-text-using-the-greek-alphabet.basic @@ -0,0 +1,59 @@ +' Double-letter replacements +replacements["ee"] = "" +replacements["ch"] = "" +replacements["kh"] = "" +replacements["ph"] = "" +replacements["rh"] = "" +replacements["th"] = "" +replacements["oo"] = "" +replacements["ps"] = "" +replacements["ck"] = "" +' Single-letter replacements +replacements["a"] = "" +replacements["b"] = "" +replacements["c"] = "" +replacements["d"] = "" +replacements["e"] = "" +replacements["f"] = "" +replacements["g"] = "" +replacements["h"] = "" +replacements["i"] = "" +replacements["j"] = "" +replacements["k"] = "" +replacements["l"] = "" +replacements["m"] = "" +replacements["n"] = "" +replacements["o"] = "" +replacements["p"] = "" +replacements["q"] = "" +replacements["r"] = "" +replacements["s"] = "" +replacements["t"] = "" +replacements["u"] = "" +replacements["v"] = "" +replacements["w"] = "" +replacements["x"] = "" +replacements["y"] = "" +replacements["z"] = "" + +Sub TransliterateToGreek + i = 1 + While i <= Text.GetLength(text) + doubleLetter = Text.GetSubText(text, i, 2) + singleLetter = text.GetSubText(text, i, 1) + If i < Text.GetLength(text) And Array.ContainsIndex(replacements, doubleLetter) Then + greekText = greekText + replacements[doubleLetter] + i = i + 2 + ElseIf Array.ContainsIndex(replacements, singleLetter) Then + greekText = greekText + replacements[singleLetter] + i = i + 1 + Else + greekText = greekText + singleLetter + i = i + 1 + EndIf + EndWhile +EndSub + +text = "sphinx of black quartz, judge my vow." +TransliterateToGreek() +TextWindow.WriteLine(greekText) diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Phix/transliterate-english-text-using-the-greek-alphabet.phix b/Task/Transliterate-English-text-using-the-Greek-alphabet/Phix/transliterate-english-text-using-the-greek-alphabet.phix index 3bdb464508..c8bea78828 100644 --- a/Task/Transliterate-English-text-using-the-Greek-alphabet/Phix/transliterate-english-text-using-the-greek-alphabet.phix +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Phix/transliterate-english-text-using-the-greek-alphabet.phix @@ -28,8 +28,8 @@ omega w or oo function rules() sequence replacements = split(task,"\n"), suborder = {{" ",49},{",",50},{".",51},{"\n",52}}, - {rs,ir} = columnize(suborder), - names = reinstate(repeat(0,52),ir,rs), + {rs,ir} = columnize(suborder), + names = reinstate(repeat(0,52),ir,rs), done = {} for i,s in replacements do s = substitute_all(s,{" or"," and"},{",",","}) @@ -41,9 +41,9 @@ function rules() s = s[1..k-2] end if s = split(substitute(s,",","")," ") - names[i] = "<" & proper(s[1]) & ">" - names[i+24] = "<" & s[1] & ">" - s = s[2..$] + names[i] = "<" & proper(s[1]) & ">" + names[i+24] = "<" & s[1] & ">" + s = s[2..$] k = max(apply(s¬s,length)) replacements[i] = {k,i,reverse(s),nots} end for @@ -55,7 +55,7 @@ function rules() missing += not find(s,done) end for if not missing then - integer g = replacements[i][2] + integer g = replacements[i][2] for s in replacements[i][3] do done = append(done,s) suborder &= {{s,g+24}} @@ -71,7 +71,7 @@ end function sequence {{sub,rep},names} = rules(), gulp = utf8_to_utf32("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"& - "αβγδεζηθικλμνξοπρστυφχψω ,.\n"), + "αβγδεζηθικλμνξοπρστυφχψω ,.\n"), text = """ The quick brown fox jumped over the lazy dog. diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Pluto/transliterate-english-text-using-the-greek-alphabet.pluto b/Task/Transliterate-English-text-using-the-Greek-alphabet/Pluto/transliterate-english-text-using-the-greek-alphabet.pluto new file mode 100644 index 0000000000..89edb90a9b --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Pluto/transliterate-english-text-using-the-greek-alphabet.pluto @@ -0,0 +1,105 @@ +require "uchar" + +local function english_to_greek(text) + -- Make appropriate substitutions using rarely used control characters + -- for Greek letters which have no single English letter equivalents. + local subs = { + {"v", "b"}, + {"j", "i"}, + {"y", "u"}, + {"ch", "\x01"}, -- chi (l/c) + {"kh", "\x01"}, -- chi (l/c) + {"ph", "f"}, + {"rh", "r"}, + {"th", "\x02"}, -- theta (l/c) + {"Ch", "\x04"}, -- chi (u/c) + {"Kh", "\x04"}, -- chi (u/c) + {"Ph", "F"}, + {"Rh", "R"}, + {"Th", "\x05"}, -- theta (u/c) + {"ee", "h"}, + {"ck", "q"}, + {"c", "q"}, + {"k", "q"}, + {"oo", "w"}, + {"ps", "\x03"}, -- psi(l/c) + {"Ps", "\x06"}, -- psi(u/c) + {"V", "B"}, + {"J", "I"}, + {"Y", "U"}, + {"CH", "\x04"}, -- chi (u/c) + {"KH", "\x04"}, -- chi (u/c) + {"PH", "F"}, + {"RH", "R"}, + {"TH", "\x05"}, -- theta (u/c) + {"EE", "H"}, + {"CK", "Q"}, + {"C", "Q"}, + {"K", "Q"}, + {"OO", "W"}, + {"PS", "\x06"} -- psi(u/c) + } + for subs as sub do text = text:replace(sub[1], sub[2]) end + + -- Now look for final English lower case 's' and use 'DEL' to substitute for that. + local letters = text:split("") + for i = 2, #letters do + local c = letters[i] + if (c:iswhitespace() or c:match("%p")) and letters[i-1] == "s" then + letters[i - 1] = "\x7f" + end + end + + -- Finally substitute the remaining English 'letters' with Greek ones. + -- Note that some of them look the same but are different codepoints. + local e2g = { + a = "α", b = "β", d = "δ", e = "ε", f = "φ", g = "γ", h = "η", + i = "ι", l = "λ", m = "μ", n = "ν", o = "ο", p = "π", q = "κ", + r = "ρ", s = "σ", t = "τ", u = "υ", w = "ω", x = "ξ", z = "ζ", + A = "Α", B = "Β", D = "Δ", E = "Ε", F = "Φ", G = "Γ", H = "Η", + I = "Ι", L = "Λ", M = "Μ", N = "Ν", O = "Ο", P = "Π", Q = "Κ", + R = "Ρ", S = "Σ", T = "Τ", U = "Υ", W = "Ω", X = "Ξ", Z = "Ζ", + ["\x01"] = "χ", ["\x02"] = "θ", ["\x03"] = "ψ", ["\x7f"] = "ς", + ["\x04"] = "Χ", ["\x05"] = "Θ", ["\x06"] = "Ψ" + } + + local grk = table.create(#letters) + for i, c in letters do + if c:iswhitespace() or c:match("%p") then + grk[i] = c + else + grk[i] = e2g[c] + end + end + return grk:concat("") +end + +local texts = { +"The quick brown fox jumped over the lazy dog.", +[[ +I was looking at some rhododendrons in my back garden, +dressed in my khaki shorts, when the telephone rang. + +As I answered it, I cheerfully glimpsed that the July sun +caused a fragment of black pine wax to ooze on the velvet quilt +laying in my patio.]], +"sphinx of black quartz, judge my vow." +} +for texts as text do + print(text) + print() + print(english_to_greek(text)) + print(string.rep("=", 65)) +end +print("The last example using the names of the Greek letters instead:") +local u = uchar.of(english_to_greek(texts[3])) +local s = "" +for i = 1, u:len() do + local g = u:get(i) + if g:iswhitespace() or g:match("%p") then + s ..= g + else + s ..= "<" .. greek[g] .. ">" + end +end +print(s) diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/R/transliterate-english-text-using-the-greek-alphabet.r b/Task/Transliterate-English-text-using-the-Greek-alphabet/R/transliterate-english-text-using-the-greek-alphabet.r new file mode 100644 index 0000000000..779aec1386 --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/R/transliterate-english-text-using-the-greek-alphabet.r @@ -0,0 +1,67 @@ +eng2greek <- function(s){ + regexps <- c("\U0391" = "A", + "\U0392" = "[BV]", + "\U0393" = "G", + "\U0394" = "D", + "\U0395" = "E(?!e)", + "\U0396" = "Z", + "\U0397" = "H|Ee", + "\U0398" = "Th", + "\U0399" = "[IJ]", + "\U039A" = "(C|K)(?!h)|Q", + "\U039B" = "L", + "\U039C" = "M", + "\U039D" = "N", + "\U039E" = "X", + "\U039F" = "O(?!o)", + "\U03A0" = "P(?![hs])", + "\U03A1" = "Rh|R", + "\U03A3" = "S", + "\U03A4" = "T(?!h)", + "\U03A5" = "[UY]", + "\U03A6" = "F|Ph", + "\U03A7" = "(C|K)h", + "\U03A8" = "Ps", + "\U03A9" = "W|Oo", + "\U03B1" = "a", + "\U03B2" = "[bv]", + "\U03B3" = "g", + "\U03B4" = "d", + "\U03B5" = "(? Indent tree conversion (pretty-print version) +!----------------------------------------------------------------------- +module tree_m + implicit none + + !-------------- nested (recursive) representation ------------------ + type :: nest_node + character(len=:), allocatable :: name + type(nest_node), allocatable :: children(:) + contains + procedure :: to_string => nest_to_string + procedure :: to_indent => nest_to_indent + procedure :: print_nest + end type nest_node + + !-------------- flat (indent-level) representation --------------- + type :: indent_node + integer :: level = 0 + character(len=:), allocatable :: name + end type indent_node + +contains + +!======================================================================= +! nest -> character string (compact bracket form) +!======================================================================= + recursive function nest_to_string(this) result(s) + class(nest_node), intent(in) :: this + character(len=:), allocatable :: s + integer :: i + s = trim(this%name) + if (allocated(this%children)) then + s = s // '(' + do i = 1, size(this%children) + s = s // trim(this%children(i)%to_string()) + if (i < size(this%children)) s = s // ',' + end do + s = s // ')' + end if + end function nest_to_string + +!======================================================================= +! pretty print nest tree in outline form +!======================================================================= + recursive subroutine print_nest(this, depth) + class(nest_node), intent(in) :: this + integer, intent(in), optional :: depth + integer :: d, i + d = 0; if (present(depth)) d = depth + print '(a)', repeat(' ',d) // trim(this%name) + if (allocated(this%children)) then + do i = 1, size(this%children) + call this%children(i)%print_nest(d+1) + end do + end if + end subroutine print_nest + +!======================================================================= +! nest -> list of indent_node (depth-first walk) +!======================================================================= + recursive subroutine nest_to_indent(this, list, depth) + class(nest_node), intent(in) :: this + type(indent_node), allocatable, intent(inout) :: list(:) + integer, intent(in), optional :: depth + integer :: d, n + d = 0; if (present(depth)) d = depth + if (.not. allocated(list)) allocate(list(0)) + n = size(list) + list = [list, indent_node(d, this%name)] + if (allocated(this%children)) then + do n = 1, size(this%children) + call this%children(n)%to_indent(list, d+1) + end do + end if + end subroutine nest_to_indent + +!======================================================================= +! indent list -> nest tree +!======================================================================= + function indent_to_nest(list) result(root) + type(indent_node), intent(in) :: list(:) + type(nest_node), pointer :: root + + type :: tagged + type(nest_node), allocatable :: node + integer :: level = 0 + end type tagged + + type(tagged), allocatable :: stack(:) + integer :: i, top + + top = 0 + allocate(stack(0)) + + do i = 1, size(list) + block + type(tagged),target :: fresh + allocate(fresh%node) + fresh%node%name = list(i)%name + fresh%level = list(i)%level + + do while (top > 0 .and. stack(top)%level >= list(i)%level) + top = top - 1 + end do + + if (top == 0) then + root => fresh%node + else + if (.not. allocated(stack(top)%node%children)) & + allocate(stack(top)%node%children(0)) + stack(top)%node%children = [stack(top)%node%children, fresh%node] + end if + + top = top + 1 + if (top > size(stack)) stack = [stack, fresh] + stack(top) = fresh + end block + end do + end function indent_to_nest + +!======================================================================= +! pretty print indent list +!======================================================================= + subroutine print_indent(list) + type(indent_node), intent(in) :: list(:) + integer :: i + do i = 1, size(list) + print '(i0,1x,a)', list(i)%level, list(i)%name + end do + end subroutine print_indent + +end module tree_m + +!####################################################################### +! Demonstration +!####################################################################### +program demo + use tree_m + implicit none + type(nest_node), pointer :: root, final + type(indent_node), allocatable :: flat(:) + + !------------------------------------------------------------------ + ! 1. Build the example tree by hand (nest form) + !------------------------------------------------------------------ + allocate(root) + root%name = "RosettaCode" + allocate(root%children(2)) + + root%children(1)%name = "rocks" + allocate(root%children(1)%children(3)) + root%children(1)%children(1)%name = "code" + root%children(1)%children(2)%name = "comparison" + root%children(1)%children(3)%name = "wiki" + + root%children(2)%name = "mocks" + allocate(root%children(2)%children(1)) + root%children(2)%children(1)%name = "trolling" + + !------------------------------------------------------------------ + ! 2. Initial nest form (outline) + !------------------------------------------------------------------ + print *, "==Nest form==" + call root%print_nest() + print * + + !------------------------------------------------------------------ + ! 3. Convert to indent form and display + !------------------------------------------------------------------ + call root%to_indent(flat) + print *, "==Indent form==" + call print_indent(flat) + print * + + !------------------------------------------------------------------ + ! 4. Convert back to nest form and display (outline) + !------------------------------------------------------------------ + final => indent_to_nest(flat) + print *, "==Nest form==" + call final%print_nest() + print * + print*, 'They are equal. There is only one data structure that is traversed differently' +end program demo diff --git a/Task/Tree-traversal/Ada/tree-traversal.adb b/Task/Tree-traversal/Ada/tree-traversal.adb new file mode 100644 index 0000000000..caad323193 --- /dev/null +++ b/Task/Tree-traversal/Ada/tree-traversal.adb @@ -0,0 +1,108 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Unchecked_Deallocation; +with Ada.Containers.Doubly_Linked_Lists; + +procedure Tree_Traversal is + type Node; + type Node_Access is access Node; + type Node is record + Left : Node_Access := null; + Right : Node_Access := null; + Data : Integer; + end record; + procedure Destroy_Tree(N : in out Node_Access) is + procedure free is new Ada.Unchecked_Deallocation(Node, Node_Access); + begin + if N.Left /= null then + Destroy_Tree(N.Left); + end if; + if N.Right /= null then + Destroy_Tree(N.Right); + end if; + Free(N); + end Destroy_Tree; + function Tree(Value : Integer; Left : Node_Access; Right : Node_Access) return Node_Access is + Temp : Node_Access := new Node; + begin + Temp.Data := Value; + Temp.Left := Left; + Temp.Right := Right; + return Temp; + end Tree; + procedure Preorder(N : Node_Access) is + begin + Put(Integer'Image(N.Data)); + if N.Left /= null then + Preorder(N.Left); + end if; + if N.Right /= null then + Preorder(N.Right); + end if; + end Preorder; + procedure Inorder(N : Node_Access) is + begin + if N.Left /= null then + Inorder(N.Left); + end if; + Put(Integer'Image(N.Data)); + if N.Right /= null then + Inorder(N.Right); + end if; + end Inorder; + procedure Postorder(N : Node_Access) is + begin + if N.Left /= null then + Postorder(N.Left); + end if; + if N.Right /= null then + Postorder(N.Right); + end if; + Put(Integer'Image(N.Data)); + end Postorder; + procedure Levelorder(N : Node_Access) is + package Queues is new Ada.Containers.Doubly_Linked_Lists(Node_Access); + use Queues; + Node_Queue : List; + Next : Node_Access; + begin + Node_Queue.Append(N); + while not Is_Empty(Node_Queue) loop + Next := First_Element(Node_Queue); + Delete_First(Node_Queue); + Put(Integer'Image(Next.Data)); + if Next.Left /= null then + Node_Queue.Append(Next.Left); + end if; + if Next.Right /= null then + Node_Queue.Append(Next.Right); + end if; + end loop; + end Levelorder; + N : Node_Access; +begin + N := Tree(1, + Tree(2, + Tree(4, + Tree(7, null, null), + null), + Tree(5, null, null)), + Tree(3, + Tree(6, + Tree(8, null, null), + Tree(9, null, null)), + null)); + + Put("preorder: "); + Preorder(N); + New_Line; + Put("inorder: "); + Inorder(N); + New_Line; + Put("postorder: "); + Postorder(N); + New_Line; + Put("level order: "); + Levelorder(N); + New_Line; + Destroy_Tree(N); +end Tree_traversal; diff --git a/Task/Tree-traversal/Euphoria/tree-traversal.eu b/Task/Tree-traversal/Euphoria/tree-traversal.eu new file mode 100644 index 0000000000..cf1c4e48ee --- /dev/null +++ b/Task/Tree-traversal/Euphoria/tree-traversal.eu @@ -0,0 +1,67 @@ +constant VALUE = 1, LEFT = 2, RIGHT = 3 + +constant tree = {1, + {2, + {4, + {7, 0, 0}, + 0}, + {5, 0, 0}}, + {3, + {6, + {8, 0, 0}, + {9, 0, 0}}, + 0}} + +procedure preorder(object tree) + if sequence(tree) then + printf(1,"%d ",{tree[VALUE]}) + preorder(tree[LEFT]) + preorder(tree[RIGHT]) + end if +end procedure + +procedure inorder(object tree) + if sequence(tree) then + inorder(tree[LEFT]) + printf(1,"%d ",{tree[VALUE]}) + inorder(tree[RIGHT]) + end if +end procedure + +procedure postorder(object tree) + if sequence(tree) then + postorder(tree[LEFT]) + postorder(tree[RIGHT]) + printf(1,"%d ",{tree[VALUE]}) + end if +end procedure + +procedure lo(object tree, sequence more) + if sequence(tree) then + more &= {tree[LEFT],tree[RIGHT]} + printf(1,"%d ",{tree[VALUE]}) + end if + if length(more) > 0 then + lo(more[1],more[2..$]) + end if +end procedure + +procedure level_order(object tree) + lo(tree,{}) +end procedure + +puts(1,"preorder: ") +preorder(tree) +puts(1,'\n') + +puts(1,"inorder: ") +inorder(tree) +puts(1,'\n') + +puts(1,"postorder: ") +postorder(tree) +puts(1,'\n') + +puts(1,"level-order: ") +level_order(tree) +puts(1,'\n') diff --git a/Task/Tree-traversal/Fortran/tree-traversal-4.f b/Task/Tree-traversal/Fortran/tree-traversal-4.f new file mode 100644 index 0000000000..d18251937c --- /dev/null +++ b/Task/Tree-traversal/Fortran/tree-traversal-4.f @@ -0,0 +1,223 @@ +! ============================================================================= +! tree_traversal.f90 +! +! Demonstrates four classic binary-tree traversal algorithms on the following +! hand-built nine-node tree: +! +! 1 +! / \ +! 2 3 +! / \ / +! 4 5 6 +! / / \ +! 7 8 9 +! +! Expected output: +! preorder: 1 2 4 7 5 3 6 8 9 +! inorder: 7 4 2 5 1 8 6 9 3 +! postorder: 7 4 5 2 8 9 6 3 1 +! level-order: 1 2 3 4 5 6 7 8 9 +! ============================================================================= +program tree_traversal + implicit none + + ! ------------------------------------------------------------------ + ! node -- one element of the binary tree. + ! val : the integer payload stored at this node + ! left : pointer to the left child (null => no left child) + ! right : pointer to the right child (null => no right child) + ! ------------------------------------------------------------------ + type :: node + integer :: val + type(node), pointer :: left => null() + type(node), pointer :: right => null() + end type node + + ! ------------------------------------------------------------------ + ! node_ptr -- thin wrapper that lets us build an array of pointers. + ! Fortran does not allow "type(node), pointer :: arr(n)" directly, so + ! we embed the pointer in a derived type and make an array of that. + ! Used only by level_order as a fixed-size FIFO queue. + ! ------------------------------------------------------------------ + type :: node_ptr + type(node), pointer :: p => null() + end type node_ptr + + ! root is the entry point to the whole tree + type(node), pointer :: root + + ! ------------------------------------------------------------------ + ! Build the tree by allocating nodes one at a time and wiring up the + ! parent/child pointer relationships. new_node() allocates a fresh + ! node, stores the value, and nullifies both child pointers. + ! + ! Visual layout of pointer assignments below: + ! + ! root (1) + ! +-- left --> (2) + ! | +-- left --> (4) + ! | | +-- left --> (7) [leaf] + ! | | +-- right --> [none] + ! | +-- right --> (5) [leaf] + ! +-- right --> (3) + ! +-- left --> (6) + ! | +-- left --> (8) [leaf] + ! | +-- right --> (9) [leaf] + ! +-- right --> [none] + ! ------------------------------------------------------------------ + root => new_node(1) ! tree root + root%left => new_node(2) ! depth 1, left subtree + root%right => new_node(3) ! depth 1, right subtree + root%left%left => new_node(4) ! depth 2 + root%left%right => new_node(5) ! depth 2, leaf + root%right%left => new_node(6) ! depth 2 + root%left%left%left => new_node(7) ! depth 3, leaf + root%right%left%left => new_node(8) ! depth 3, leaf + root%right%left%right => new_node(9) ! depth 3, leaf + + ! ------------------------------------------------------------------ + ! Preorder: root -> left subtree -> right subtree + ! Each node is visited BEFORE its children, so the root always + ! appears first and every subtree root appears before its descendants. + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'preorder: ' + call preorder(root) + write(*,*) ! newline after values + + ! ------------------------------------------------------------------ + ! Inorder: left subtree -> root -> right subtree + ! For a binary SEARCH tree this would yield sorted ascending order, + ! but this tree is not a BST -- it merely demonstrates the traversal. + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'inorder: ' + call inorder(root) + write(*,*) + + ! ------------------------------------------------------------------ + ! Postorder: left subtree -> right subtree -> root + ! Each node is visited AFTER both its children, so the root always + ! appears last. Useful for safely deallocating a tree (free children + ! before the parent). + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'postorder: ' + call postorder(root) + write(*,*) + + ! ------------------------------------------------------------------ + ! Level-order (breadth-first): visit every node at depth d before any + ! node at depth d+1, scanning left to right within each level. + ! Implemented iteratively with a FIFO queue rather than recursion. + ! ------------------------------------------------------------------ + write(*,'(a)', advance='no') 'level-order: ' + call level_order(root) + write(*,*) + +contains + + ! ------------------------------------------------------------------ + ! new_node(val) + ! Allocate a new tree node, store val, null both child pointers. + ! Returns a pointer to the newly allocated node. + ! ------------------------------------------------------------------ + function new_node(val) result(n) + integer, intent(in) :: val + type(node), pointer :: n + allocate(n) ! heap-allocate one node record + n%val = val + n%left => null() ! no left child yet + n%right => null() ! no right child yet + end function new_node + + ! ------------------------------------------------------------------ + ! preorder(n) -- recursive, depth-first + ! Visit pattern: SELF left right + ! Base case: if n is not associated (null pointer) do nothing. + ! ------------------------------------------------------------------ + recursive subroutine preorder(n) + type(node), pointer, intent(in) :: n + if (.not. associated(n)) return ! null pointer: nothing to do + write(*,'(i0," ")', advance='no') n%val ! print this node first + call preorder(n%left) ! then recurse into left child + call preorder(n%right) ! then recurse into right child + end subroutine preorder + + ! ------------------------------------------------------------------ + ! inorder(n) -- recursive, depth-first + ! Visit pattern: left SELF right + ! The left subtree is fully exhausted before the current node is + ! printed, and the right subtree is visited last. + ! ------------------------------------------------------------------ + recursive subroutine inorder(n) + type(node), pointer, intent(in) :: n + if (.not. associated(n)) return ! base case: null pointer + call inorder(n%left) ! recurse left first + write(*,'(i0," ")', advance='no') n%val ! print this node second + call inorder(n%right) ! recurse right last + end subroutine inorder + + ! ------------------------------------------------------------------ + ! postorder(n) -- recursive, depth-first + ! Visit pattern: left right SELF + ! Both subtrees are fully exhausted before the current node is + ! printed, so leaves always appear before their parents. + ! ------------------------------------------------------------------ + recursive subroutine postorder(n) + type(node), pointer, intent(in) :: n + if (.not. associated(n)) return ! base case: null pointer + call postorder(n%left) ! recurse left + call postorder(n%right) ! recurse right + write(*,'(i0," ")', advance='no') n%val ! print this node last + end subroutine postorder + + ! ------------------------------------------------------------------ + ! level_order(root_node) -- iterative, breadth-first + ! + ! Algorithm (standard BFS with a FIFO queue): + ! 1. Enqueue the root. + ! 2. While the queue is non-empty: + ! a. Dequeue the front node. + ! b. Print its value. + ! c. Enqueue its left child if it exists. + ! d. Enqueue its right child if it exists. + ! + ! Queue implementation: a fixed-size array of node_ptr wrappers. + ! head = index of the next item to dequeue (front of queue) + ! tail = index of the next free slot (back of queue) + ! The queue holds at most 100 pointers; plenty for this 9-node tree. + ! head < tail means the queue is non-empty. + ! ------------------------------------------------------------------ + subroutine level_order(root_node) + type(node), pointer, intent(in) :: root_node + type(node_ptr) :: queue(100) ! fixed-size array-based FIFO queue + type(node), pointer :: cur ! node being processed this iteration + integer :: head ! index of front element (next dequeue) + integer :: tail ! index of next free slot (next enqueue) + + ! Initialise queue with just the root + head = 1 + tail = 1 + queue(tail)%p => root_node ! enqueue root at position 1 + tail = tail + 1 ! tail now points to next free slot (2) + + ! Process until the queue is drained + do while (head < tail) ! head == tail means queue is empty + cur => queue(head)%p ! dequeue: read the front element + head = head + 1 ! advance head (slot is now "consumed") + + write(*,'(i0," ")', advance='no') cur%val ! visit: print value + + ! Enqueue left child if it exists + if (associated(cur%left)) then + queue(tail)%p => cur%left + tail = tail + 1 + end if + + ! Enqueue right child if it exists + if (associated(cur%right)) then + queue(tail)%p => cur%right + tail = tail + 1 + end if + end do + end subroutine level_order + +end program tree_traversal diff --git a/Task/Tree-traversal/Gleam/tree-traversal.gleam b/Task/Tree-traversal/Gleam/tree-traversal.gleam new file mode 100644 index 0000000000..d027a08ae2 --- /dev/null +++ b/Task/Tree-traversal/Gleam/tree-traversal.gleam @@ -0,0 +1,56 @@ +import gleam/list + +pub type Tree(a) { + Empty + Node(a, Tree(a), Tree(a)) +} + +pub fn preorder(t: Tree(a)) -> List(a) { + case t { + Empty -> [] + Node(v, l, r) -> [v, ..list.append(preorder(l), preorder(r))] + } +} + +pub fn inorder(t: Tree(a)) -> List(a) { + case t { + Empty -> [] + Node(v, l, r) -> list.append(list.append(inorder(l), [v]), inorder(r)) + } +} + +pub fn postorder(t: Tree(a)) -> List(a) { + case t { + Empty -> [] + Node(v, l, r) -> list.append(list.append(postorder(l), postorder(r)), [v]) + } +} + +pub fn levelorder(t: Tree(a)) -> List(a) { + levelorder_helper([t]) +} + +fn levelorder_helper(trees: List(Tree(a))) -> List(a) { + case trees { + [] -> [] + [Empty, ..rest] -> levelorder_helper(rest) + [Node(v, l, r), ..rest] -> [ + v, + ..levelorder_helper(list.append(rest, [l, r])) + ] + } +} + +pub fn main() -> Nil { + let example = + Node( + 1, + Node(2, Node(4, Node(7, Empty, Empty), Empty), Node(5, Empty, Empty)), + Node(3, Node(6, Node(8, Empty, Empty), Node(9, Empty, Empty)), Empty), + ) + echo preorder(example) + echo inorder(example) + echo postorder(example) + echo levelorder(example) + Nil +} diff --git a/Task/Tree-traversal/RISC-V-Assembly/tree-traversal.asm b/Task/Tree-traversal/RISC-V-Assembly/tree-traversal.asm new file mode 100644 index 0000000000..6a0d81d847 --- /dev/null +++ b/Task/Tree-traversal/RISC-V-Assembly/tree-traversal.asm @@ -0,0 +1,450 @@ +# riscv assembly raspberry pico2 rp2350 +# program treetrans.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +.equ NBVAL, 9 + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure tree */ + .struct 0 +tree_root: # root pointer + .struct tree_root + 4 +tree_size: # number of element of tree + .struct tree_size + 4 +tree_fin: +/* structure node tree */ + .struct 0 +node_left: # left pointer + .struct node_left + 4 +node_right: # right pointer + .struct node_right + 4 +node_value: # element value + .struct node_value + 4 +node_fin: +/* structure queue*/ + .struct 0 +queue_begin: # next pointer + .struct queue_begin + 4 +queue_end: # element value + .struct queue_end + 4 +queue_fin: +/* structure node queue */ + .struct 0 +queue_node_next: # next pointer + .struct queue_node_next + 4 +queue_node_value: # element value + .struct queue_node_value + 4 +queue_node_fin: + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" + +szMessInOrder: .asciz "inOrder :\n" +szMessPreOrder: .asciz "PreOrder :\n" +szMessPostOrder: .asciz "PostOrder :\n" +szMessLevelOrder: .asciz "LevelOrder :\n" + +szMessResult: .asciz "Element value : " +.align 2 +ptHeapReserve: .int heapReserve + + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +stTree: .skip tree_fin # place to structure tree +stQueue: .skip queue_fin # place to structure queue +heapReserve: .skip HEAPSIZE +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: # INFO: main + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + li s0,1 +1: + la a0,stTree + mv a1,s0 # value + call insertElement + li t0,-1 + beq a0,t0,100f + addi s0,s0,1 + li t0,NBVAL + ble s0,t0,1b + + + la a0,szMessPreOrder + call writeString + la a0,stTree # tree address + lw a0,tree_root(a0) # tree root + la a1,displayElement + call preOrder + + la a0,szMessInOrder + call writeString + la a0,stTree + lw a0,tree_root(a0) + la a1,displayElement + call inOrder + + la a0,szMessPostOrder + call writeString + la a0,stTree + lw a0,tree_root(a0) + la a1,displayElement + call postOrder + + la a0,szMessLevelOrder + call writeString + la a0,stTree + lw a0,tree_root(a0) + la a1,displayElement + call levelOrder + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* a0 contains the address of the tree structure */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -8 # save registres + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + li a0,node_fin # reservation place one element + call allocHeap + li t0,-1 + beq a0,t0,100f # allocation error + mv t0,a0 # save address + sw a1,node_value(t0) # store value in address heap + sw x0,node_left(t0) # init left pointer with zero + sw x0,node_right(t0) # init right pointer with zero + lw t1,tree_size(s0) # load tree size + bnez t1,1f # 0 element + sw t0,tree_root(s0) # yes -> store in root + j 4f +1: # else search free address in tree + lw t2,tree_root(s0) # start with address root + mv t5,a1 # value node + clz t3,t5 # compute zeroes left bits + addi t3,t3,1 # for sustract the first left bit + sll t5,t5,t3 # shift number in left +2: + slt t4,t5,x0 # is bit31 = 1 + slli t5,t5,1 + bnez t4,3f # is bit31 = 1 + lw t4,node_left(t2) # no store node address in left pointer + bnez t4,21f # equal zero ? + sw t0,node_left(t2) + j 4f +21: + mv t2,t4 # else loop with next node + j 2b +3: + lw t4,node_right(t2) # no store node address in right pointer + bnez t4,31f # equal zero ? + sw t0,node_right(t2) + j 4f +31: + mv t2,t4 # else loop with next node + j 2b # and loop +4: + addi t1,t1,1 + sw t1,tree_size(s0) + mv a0,t0 + +100: + lw ra, 0(sp) + lw s0,4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* a0 contains node address */ +displayElement: # INFO: displayElement + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + lw a0,node_value(a0) + la a1,sConvArea + call conversion10S + la a0,szMessResult + call writeString + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* dequeue node */ +/******************************************************************/ +/* a0 contains the address of the queue */ +/* a0 returns 0 if empty else 1 */ +isEmptyQueue1: # INFO: isEmptyQueue + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + lw a0,queue_begin(a0) + snez a0,a0 +100: + lw ra, 0(sp) + addi sp, sp, 8 +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* a0 contains the size to allocate */ +/* a0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: # INFO: allocHeap + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + add t2,t1,a0 # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 # compute heap end + blt t2,t3,1f # allocation address < heap end ? + li a0,-1 # allocation error + j 100f +1: + sw t2,(t0) # store new start free address heap + mv a0,t1 # return address +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret + +/******************************************************************/ +/* preOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +preOrder: # INFO: preOrder + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + sw s1,8(sp) + beqz a0,100f # tree address null ? + beqz a0,100f + mv s0,a0 + mv s1,a1 + jalr a1 # call function + lw a0,node_left(s0) + mv a1,s1 + call preOrder + lw a0,node_right(s0) + mv a1,s1 + call preOrder + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1,8(sp) + addi sp, sp, 12 + ret +/******************************************************************/ +/* inOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +inOrder: # INFO: inOrder + addi sp,sp, -12 # reserve stack + sw ra,0(sp) + sw s0,4(sp) + sw s1,8(sp) + beqz a0,100f + mv s0,a0 + mv s1,a1 + lw a0,node_left(s0) + call inOrder + mv a0,s0 + jalr s1 # call function + lw a0,node_right(s0) + mv a1,s1 + call inOrder +100: + lw ra,0(sp) + lw s0,4(sp) + lw s1,8(sp) + addi sp,sp, 12 + ret +/******************************************************************/ +/* postOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +postOrder: # INFO: postOrder + addi sp, sp, -12 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + sw s1,8(sp) + beqz a0,100f + mv s0,a0 + mv s1,a1 + lw a0,node_left(s0) + call postOrder + + lw a0,node_right(s0) + mv a1,s1 + call postOrder + mv a0,s0 + jalr s1 # call function +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1,8(sp) + addi sp, sp, 12 + ret +/******************************************************************/ +/* levelOrder */ +/******************************************************************/ +/* a0 contains the address of the node */ +/* a1 function address */ +levelOrder: # INFO: levelOrder + addi sp,sp, -16 # reserve stack + sw ra,0(sp) + sw s0,4(sp) + sw s1,8(sp) + sw s2,12(sp) + beqz a0,100f + mv s0,a0 + mv s1,a1 + la a0,stQueue # adresse queue + mv a1,s0 + call enqueueNode +1: + la a0,stQueue # adresse queue + lw a0,queue_begin(a0) + beqz a0,100f # is queue empty + la a0,stQueue + call dequeueNode + mv s2,a0 # save node + jalr s1 # call function + lw s0,node_left(s2) # left node ok ? + beqz s0,2f # no + la a0,stQueue + mv a1,s0 + call enqueueNode +2: + lw s0,node_right(s2) # right node ok ? + beqz s0,3f # no + la a0,stQueue + mv a1,s0 + call enqueueNode +3: + j 1b # and loop +100: + lw ra,0(sp) + lw s0,4(sp) + lw s1,8(sp) + lw s2,12(sp) + addi sp, sp, 16 + ret + +/******************************************************************/ +/* enqueue node */ +/******************************************************************/ +/* a0 contains the address of the queue */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +enqueueNode: # INFO: enqueueNode + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + li a0,queue_node_fin # reservation place one element + call allocHeap + li t0,-1 + beq a0,t0,100f # allocation error + mv t0,a0 # save address + sw a1,queue_node_value(t0) # store node value + sw x0,queue_node_next(t0) # init pointer next + lw t1,queue_end(s0) + beqz t1,1f + sw t0,queue_node_next(t1) + j 2f +1: + sw t0,queue_begin(s0) +2: + sw t0,queue_end(s0) + li a0,0 # ok + +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/******************************************************************/ +/* dequeue node */ +/******************************************************************/ +/* a0 contains the address of the queue */ +/* a0 returns address of element or - 1 if error */ +dequeueNode: # INFO: dequeueNode + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + lw t0,queue_begin(a0) + beqz t0,2f + lw t1,queue_node_value(t0) + lw t2,queue_node_next(t0) + sw t2,queue_begin(a0) + bnez t2,1f + sw t2,queue_end(a0) +1: + mv a0,t1 + j 100f +2: + li a0,-1 # empty queue +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Tree-traversal/Rebol/tree-traversal.rebol b/Task/Tree-traversal/Rebol/tree-traversal.rebol new file mode 100644 index 0000000000..d49bf19d19 --- /dev/null +++ b/Task/Tree-traversal/Rebol/tree-traversal.rebol @@ -0,0 +1,46 @@ +tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]] +; "compacted" version +tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]] + +visit: func [tree [block!]][prin rejoin [first tree " "]] +left: :second +right: :third + +preorder: func [tree [block!]][ + if not empty? tree [visit tree] + attempt [preorder left tree] + attempt [preorder right tree] +] +prin "preorder: " preorder tree +print "" + +inorder: func [tree [block!]][ + attempt [inorder left tree] + if not empty? tree [visit tree] + attempt [inorder right tree] +] +prin "inorder: " inorder tree +print "" + +postorder: func [tree [block!]][ + attempt [postorder left tree] + attempt [postorder right tree] + if not empty? tree [visit tree] +] +prin "postorder: " postorder tree +print "" + +queue: [] +enqueue: func [tree [block!]][append/only queue tree] +dequeue: func [queue [block!]][take queue] +level-order: func [tree [block!]][ + clear head queue + queue: enqueue tree + while [not empty? queue] [ + tree: dequeue queue + if not empty? tree [visit tree] + attempt [enqueue left tree] + attempt [enqueue right tree] + ] +] +prin "level-order: " level-order tree diff --git a/Task/Tree-traversal/Rocq/tree-traversal.rocq b/Task/Tree-traversal/Rocq/tree-traversal.rocq new file mode 100644 index 0000000000..a6ce33fcc2 --- /dev/null +++ b/Task/Tree-traversal/Rocq/tree-traversal.rocq @@ -0,0 +1,51 @@ +Require Import Utf8. +Require Import List. + +Unset Elimination Schemes. + +(* Rose tree, with numbers on nodes *) +Inductive tree := Tree { value : nat ; children : list tree }. + +Fixpoint height (t: tree) : nat := + 1 + fold_left (? n t, max n (height t)) (children t) 0. + +Example leaf n : tree := {| value := n ; children := nil |}. + +Example t2 : tree := {| value := 2 ; children := {| value := 4 ; children := leaf 7 :: nil |} :: leaf 5 :: nil |}. + +Example t3 : tree := {| value := 3 ; children := {| value := 6 ; children := leaf 8 :: leaf 9 :: nil |} :: nil |}. + +Example t9 : tree := {| value := 1 ; children := t2 :: t3 :: nil |}. + +Fixpoint preorder (t: tree) : list nat := + let '{| value := n ; children := c |} := t in + n :: flat_map preorder c. + +Fixpoint inorder (t: tree) : list nat := + let '{| value := n ; children := c |} := t in + match c with + | nil => n :: nil + | l :: r => inorder l ++ n :: flat_map inorder r + end. + +Fixpoint postorder (t: tree) : list nat := + let '{| value := n ; children := c |} := t in + flat_map postorder c ++ n :: nil. + +(* Auxiliary function for levelorder, which operates on forests *) +(* Since the recursion is tricky, it relies on a fuel parameter which obviously decreases. *) +Fixpoint levelorder_forest (fuel: nat) (f: list tree) : list nat:= + match fuel with + | O => nil + | S fuel' => + let '(p, f) := fold_right (? t r, let '(x, f) := r in (value t :: x, children t ++ f) ) (nil, nil) f in + p ++ levelorder_forest fuel' f + end. + +Definition levelorder (t: tree) : list nat := + levelorder_forest (height t) (t :: nil). + +Compute preorder t9. +Compute inorder t9. +Compute postorder t9. +Compute levelorder t9. diff --git a/Task/Tree-traversal/VBScript/tree-traversal.vbs b/Task/Tree-traversal/VBScript/tree-traversal.vbs new file mode 100644 index 0000000000..8ea3efa9e8 --- /dev/null +++ b/Task/Tree-traversal/VBScript/tree-traversal.vbs @@ -0,0 +1,60 @@ +' 1 +' / \ +' / \ +' / \ +' 2 3 +' / \ / +' 4 5 6 +' / / \ +' 7 8 9 +'with no pointers available, the binary tree has to be saved in an array +' root at index 1 +' parent index is i\2 +' children indexes are i*2 and i*2+1 +' a value of 0 denotes an empty branch + + Sub print(s): + On Error Resume Next + WScript.stdout.Write(s) + If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit + End Sub + + + Sub inorder(i) + If tree(i*2)<>0 Then inorder(i*2) + print tree(i)& vbtab + If tree(i*2+1)<>0 Then inorder(i*2+1) + End Sub + + + Sub preorder(i) + print tree(i)& vbtab + If tree(i*2)<>0 Then preorder(i*2) + If tree(i*2+1)<>0 Then preorder(i*2+1) + End Sub + + Sub postorder(i) + If tree(i*2)<>0 Then postorder(i*2) + If tree(i*2+1)<>0 Then postorder(i*2+1) + print tree(i)& vbTab + End Sub + + Sub levelorder(x) + Dim i + For i= 1 To UBound(tree) + If tree(i)<>0 Then print tree(i)& vbTab + Next + End sub + +Dim tree +' 1 2 3 4 5 6 7 8 9 1011121314151617181920212223242526 +' 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4 +tree=Array(0,1,2,3,4,5,6,0,7,0,0,0,8,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0) +print vbCrLf & "Preorder" & vbcrlf +preorder(1) +print vbCrLf & "Inorder" & vbcrlf +inorder(1) +print vbCrLf & "Postorder" & vbcrlf +postorder(1) +print vbCrLf & "Levelorder" & vbcrlf +levelorder(1) diff --git a/Task/Trigonometric-functions/Ada/trigonometric-functions.adb b/Task/Trigonometric-functions/Ada/trigonometric-functions.adb new file mode 100644 index 0000000000..b9094746c9 --- /dev/null +++ b/Task/Trigonometric-functions/Ada/trigonometric-functions.adb @@ -0,0 +1,35 @@ +with Ada.Numerics.Elementary_Functions; +use Ada.Numerics.Elementary_Functions; +with Ada.Float_Text_Io; use Ada.Float_Text_Io; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Trig is + Degrees_Cycle : constant Float := 360.0; + Radians_Cycle : constant Float := 2.0 * Ada.Numerics.Pi; + Angle_Degrees : constant Float := 45.0; + Angle_Radians : constant Float := Ada.Numerics.Pi / 4.0; + procedure Put (V1, V2 : Float) is + begin + Put (V1, Aft => 5, Exp => 0); + Put (" "); + Put (V2, Aft => 5, Exp => 0); + New_Line; + end Put; +begin + Put (Sin (Angle_Degrees, Degrees_Cycle), + Sin (Angle_Radians, Radians_Cycle)); + Put (Cos (Angle_Degrees, Degrees_Cycle), + Cos (Angle_Radians, Radians_Cycle)); + Put (Tan (Angle_Degrees, Degrees_Cycle), + Tan (Angle_Radians, Radians_Cycle)); + Put (Cot (Angle_Degrees, Degrees_Cycle), + Cot (Angle_Radians, Radians_Cycle)); + Put (ArcSin (Sin (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), + ArcSin (Sin (Angle_Radians, Radians_Cycle), Radians_Cycle)); + Put (Arccos (Cos (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), + Arccos (Cos (Angle_Radians, Radians_Cycle), Radians_Cycle)); + Put (Arctan (Y => Tan (Angle_Degrees, Degrees_Cycle)), + Arctan (Y => Tan (Angle_Radians, Radians_Cycle))); + Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), + Arccot (X => Cot (Angle_Degrees, Degrees_Cycle))); +end Trig; diff --git a/Task/Trigonometric-functions/AutoLISP/trigonometric-functions.lsp b/Task/Trigonometric-functions/AutoLISP/trigonometric-functions.lsp new file mode 100644 index 0000000000..38f65badb4 --- /dev/null +++ b/Task/Trigonometric-functions/AutoLISP/trigonometric-functions.lsp @@ -0,0 +1,25 @@ +(defun rad_to_deg (rad)(* 180.0 (/ rad PI))) +(defun deg_to_rad (deg)(* PI (/ deg 180.0))) + +(defun asin (x) + (cond + ((and(> x -1.0)(< x 1.0)) (atan (/ x (sqrt (- 1.0 (* x x)))))) + ((= x -1.0) (* -1.0 (/ pi 2))) + ((= x 1) (/ pi 2)) + ) +) + +(defun acos (x) + (cond + ((and(>= x -1.0)(<= x 1.0)) (-(* pi 0.5) (asin x))) + ) +) + +(list +(list "cos PI/6" (cos (/ pi 6)) "cos 30 deg" (cos (deg_to_rad 30))) +(list "sin PI/4" (sin (/ pi 4)) "sin 45 deg" (sin (deg_to_rad 45))) +(list "tan PI/3" (tan (/ pi 3))"tan 60 deg" (tan (deg_to_rad 60))) +(list "asin 1 rad" (asin 1.0) "asin 1 rad (deg)" (rad_to_deg (asin 1.0))) +(list "acos 1/2 rad" (acos (/ 1 2.0)) "acos 1/2 rad (deg)" (rad_to_deg (acos (/ 1 2.0)))) +(list "atan pi/12" (atan (/ pi 12)) "atan 15 deg" (rad_to_deg(atan(deg_to_rad 15)))) +) diff --git a/Task/Trigonometric-functions/COBOL/trigonometric-functions.cob b/Task/Trigonometric-functions/COBOL/trigonometric-functions.cob new file mode 100644 index 0000000000..5a2dff927e --- /dev/null +++ b/Task/Trigonometric-functions/COBOL/trigonometric-functions.cob @@ -0,0 +1,39 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Trig. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Pi-Third USAGE COMP-2. + 01 Degree USAGE COMP-2. + + 01 60-Degrees USAGE COMP-2. + + 01 Result USAGE COMP-2. + + PROCEDURE DIVISION. + COMPUTE Pi-Third = FUNCTION PI / 3 + + DISPLAY "Radians:" + DISPLAY " Sin(π / 3) = " FUNCTION SIN(Pi-Third) + DISPLAY " Cos(π / 3) = " FUNCTION COS(Pi-Third) + DISPLAY " Tan(π / 3) = " FUNCTION TAN(Pi-Third) + DISPLAY " Asin(0.5) = " FUNCTION ASIN(0.5) + DISPLAY " Acos(0.5) = " FUNCTION ACOS(0.5) + DISPLAY " Atan(0.5) = " FUNCTION ATAN(0.5) + + COMPUTE Degree = FUNCTION PI / 180 + COMPUTE 60-Degrees = Degree * 60 + + DISPLAY "Degrees:" + DISPLAY " Sin(60°) = " FUNCTION SIN(60-Degrees) + DISPLAY " Cos(60°) = " FUNCTION COS(60-Degrees) + DISPLAY " Tan(60°) = " FUNCTION TAN(60-Degrees) + COMPUTE Result = FUNCTION ASIN(0.5) / 60 + DISPLAY " Asin(0.5) = " Result + COMPUTE Result = FUNCTION ACOS(0.5) / 60 + DISPLAY " Acos(0.5) = " Result + COMPUTE Result = FUNCTION ATAN(0.5) / 60 + DISPLAY " Atan(0.5) = " Result + + GOBACK + . diff --git a/Task/Trigonometric-functions/Pluto/trigonometric-functions.pluto b/Task/Trigonometric-functions/Pluto/trigonometric-functions.pluto new file mode 100644 index 0000000000..fd9f4702dc --- /dev/null +++ b/Task/Trigonometric-functions/Pluto/trigonometric-functions.pluto @@ -0,0 +1,20 @@ +local fmt = require "fmt" + +local d = 30 +local r = d * math.pi / 180 +local s = 0.5 +local c = math.sqrt(3) / 2 +local t = 1 / math.sqrt(3) + +fmt.print("sin(%9.6f deg) = %f", d, math.sin(d * math.pi / 180)) +fmt.print("sin(%9.6f rad) = %f", r, math.sin(r)) +fmt.print("cos(%9.6f deg) = %f", d, math.cos(d * math.pi / 180)) +fmt.print("cos(%9.6f rad) = %f", r, math.cos(r)) +fmt.print("tan(%9.6f deg) = %f", d, math.tan(d * math.pi / 180)) +fmt.print("tan(%9.6f rad) = %f", r, math.tan(r)) +fmt.print("asin(%f) = %9.6f deg", s, math.asin(s) * 180 / math.pi) +fmt.print("asin(%f) = %9.6f rad", s, math.asin(s)) +fmt.print("acos(%f) = %9.6f deg", c, math.acos(c) * 180 / math.pi) +fmt.print("acos(%f) = %9.6f rad", c, math.acos(c)) +fmt.print("atan(%f) = %9.6f deg", t, math.atan(t) * 180 / math.pi) +fmt.print("atan(%f) = %9.6f rad", t, math.atan(t)) diff --git a/Task/Trigonometric-functions/PowerShell/trigonometric-functions-1.ps1 b/Task/Trigonometric-functions/PowerShell/trigonometric-functions-1.ps1 new file mode 100644 index 0000000000..09b882ef31 --- /dev/null +++ b/Task/Trigonometric-functions/PowerShell/trigonometric-functions-1.ps1 @@ -0,0 +1,12 @@ +$rad = [Math]::PI / 4 +$deg = 45 +'{0,10} {1,10}' -f 'Radians','Degrees' +'{0,10:N6} {1,10:N6}' -f [Math]::Sin($rad), [Math]::Sin($deg * [Math]::PI / 180) +'{0,10:N6} {1,10:N6}' -f [Math]::Cos($rad), [Math]::Cos($deg * [Math]::PI / 180) +'{0,10:N6} {1,10:N6}' -f [Math]::Tan($rad), [Math]::Tan($deg * [Math]::PI / 180) +$temp = [Math]::Asin([Math]::Sin($rad)) +'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) +$temp = [Math]::Acos([Math]::Cos($rad)) +'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) +$temp = [Math]::Atan([Math]::Tan($rad)) +'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) diff --git a/Task/Trigonometric-functions/PowerShell/trigonometric-functions-2.ps1 b/Task/Trigonometric-functions/PowerShell/trigonometric-functions-2.ps1 new file mode 100644 index 0000000000..45c5abde0a --- /dev/null +++ b/Task/Trigonometric-functions/PowerShell/trigonometric-functions-2.ps1 @@ -0,0 +1,15 @@ +$radians = [Math]::PI / 4 +$degrees = 45 + +[PSCustomObject]@{Radians=[Math]::Sin($radians); Degrees=[Math]::Sin($degrees * [Math]::PI / 180)} +[PSCustomObject]@{Radians=[Math]::Cos($radians); Degrees=[Math]::Cos($degrees * [Math]::PI / 180)} +[PSCustomObject]@{Radians=[Math]::Tan($radians); Degrees=[Math]::Tan($degrees * [Math]::PI / 180)} + +[double]$tempVar = [Math]::Asin([Math]::Sin($radians)) +[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI} + +[double]$tempVar = [Math]::Acos([Math]::Cos($radians)) +[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI} + +[double]$tempVar = [Math]::Atan([Math]::Tan($radians)) +[PSCustomObject]@{Radians=$tempVar; Degrees=$tempVar * 180 / [Math]::PI} diff --git a/Task/Trigonometric-functions/Rebol/trigonometric-functions-1.rebol b/Task/Trigonometric-functions/Rebol/trigonometric-functions-1.rebol new file mode 100644 index 0000000000..ccc7242084 --- /dev/null +++ b/Task/Trigonometric-functions/Rebol/trigonometric-functions-1.rebol @@ -0,0 +1,27 @@ +Rebol [ + Title: "Trigonometric Functions" + URL: http://rosettacode.org/wiki/Trigonometric_Functions +] + +radians: pi / 4 degrees: 45.0 + +; Unlike most languages, REBOL's trig functions work in degrees unless +; you specify differently. + +print [sine/radians radians sine degrees] +print [cosine/radians radians cosine degrees] +print [tangent/radians radians tangent degrees] + +d2r: func [ + "Convert degrees to radians." + d [number!] "Degrees" +][d * pi / 180] + +arcsin: arcsine sine degrees +print [d2r arcsin arcsin] + +arccos: arccosine cosine degrees +print [d2r arccos arccos] + +arctan: arctangent tangent degrees +print [d2r arctan arctan] diff --git a/Task/Trigonometric-functions/Rebol/trigonometric-functions-2.rebol b/Task/Trigonometric-functions/Rebol/trigonometric-functions-2.rebol new file mode 100644 index 0000000000..9901fc6d10 --- /dev/null +++ b/Task/Trigonometric-functions/Rebol/trigonometric-functions-2.rebol @@ -0,0 +1,4 @@ +radians: pi / 4 +print ["asin sin:" asin sin :radians] +print ["acos cos:" acos cos :radians] +print ["atan tan:" atan tan :radians] diff --git a/Task/Tropical-algebra-overloading/Mathematica/tropical-algebra-overloading.math b/Task/Tropical-algebra-overloading/Mathematica/tropical-algebra-overloading.math new file mode 100644 index 0000000000..739a21ee5a --- /dev/null +++ b/Task/Tropical-algebra-overloading/Mathematica/tropical-algebra-overloading.math @@ -0,0 +1,13 @@ +CirclePlus[x_, y_] := Max[x, y]; +CircleTimes[x_, y_] := x + y; +UpArrow[x_, y_Integer?Positive] := x * y; + +Print["2 ⊗ -2 = ", 2 ⊗ -2]; +Print["-0.001 ⊕ -∞ = ", -0.001 ⊕ -∞]; +Print["0 ⊗ -∞ = ", 0 ⊗ -∞]; +Print["1.5 ⊕ -1 = ", 1.5 ⊕ -1]; +Print["-0.5 ⊗ 0 = ", -0.5 ⊗ 0]; +Print["5 ↑ 7 = ", 5 ↑ 7]; +Print["5 ⊗ (8 ⊕ 7) = ", 5 ⊗ (8 ⊕ 7)]; +Print["5 ⊗ 8 ⊕ 5 ⊗ 7 = ", 5 ⊗ 8 ⊕ 5 ⊗ 7 ]; +Print["5 ⊗ (8 ⊕ 7) == 5 ⊗ 8 ⊕ 5 ⊗ 7 : ", 5 ⊗(8 ⊕ 7) == 5 ⊗ 8 ⊕ 5 ⊗ 7 ]; diff --git a/Task/Tropical-algebra-overloading/Perl/tropical-algebra-overloading.pl b/Task/Tropical-algebra-overloading/Perl/tropical-algebra-overloading.pl new file mode 100644 index 0000000000..d068cd922d --- /dev/null +++ b/Task/Tropical-algebra-overloading/Perl/tropical-algebra-overloading.pl @@ -0,0 +1,58 @@ +#!/usr/bin/perl + +use strict; # https://rosettacode.org/wiki/Tropical_algebra_overloading +use warnings; + +#Show that 2 * -2 is 0, -0.001 + -Inf is -0.001, 0 * -Inf is -Inf, 1.5 + -1 is 1.5, and -0.5 * 0 is -0.5. + +my $negativeinfinity = - 2 ** 2 ** 10; +print "negativeinfinity $negativeinfinity\n"; +printf "2 * -2 is %s\n", Tropical->new(2) * -2; +printf "-0.001 + -inf is %s\n", Tropical->new(0.001) + $negativeinfinity; +printf "0 * -inf is %s\n", Tropical->new(0) * $negativeinfinity; +printf "1.5 + -1 is %s\n", Tropical->new(1.5) + -1; +printf "-0.5 * 0 is %s\n", Tropical->new(-0.5) * 0; +printf "2 ** 3 is %s\n", Tropical->new(2) ** 3; +printf "2 ** 3 is %s\n", 2 ** Tropical->new(3); +printf "5 * ( 8 + 7) is %s\n", 5 * (Tropical->new(8) + 7); +printf "5 * 8 + 5 * 7 is %s\n", 5 * Tropical->new(8) + Tropical->new(5) * 7; + +package Tropical; +use overload qw( "" asstring + add ** power * mult ); +use List::Util qw( max ); + +sub new + { + my ( $class, $value ) = @_; + bless \$value, ref $class || $class; + } + +sub asstring + { + my ($self, $other, $swap) = @_; + $$self; + } + +sub add + { + my ($self, $other, $swap) = @_; + return $swap + ? bless \(max "$other", $$self), ref $self + : bless \(max $$self, "$other"), ref $self; + } + +sub mult + { + my ($self, $other, $swap) = @_; + return $swap + ? bless \("$other" + $$self), ref $self + : bless \($$self + "$other"), ref $self; + } + +sub power + { + my ($self, $other, $swap) = @_; + return $swap + ? bless \("$other" * $$self), ref $self + : bless \($$self * "$other"), ref $self; + } diff --git a/Task/Tropical-algebra-overloading/Phix/tropical-algebra-overloading.phix b/Task/Tropical-algebra-overloading/Phix/tropical-algebra-overloading.phix index 5a03e22ea9..bc28b94b1f 100644 --- a/Task/Tropical-algebra-overloading/Phix/tropical-algebra-overloading.phix +++ b/Task/Tropical-algebra-overloading/Phix/tropical-algebra-overloading.phix @@ -1,27 +1,25 @@ -(phixonline)--> - with javascript_semantics - requires("1.0.1") -- (minor/backportable bugfix rqd to handling of -inf in printf[1]) - constant tropicalAdd = max, - tropicalMul = sq_add, - tropicalExp = sq_mul, - inf = 1e300*1e300 +with javascript_semantics +requires("1.0.1") -- (minor/backportable bugfix rqd to handling of -inf in printf[1]) +constant tropicalAdd = max, + tropicalMul = sq_add, + tropicalExp = sq_mul, + inf = 1e300*1e300 - printf(1,"tropicalMul(2,-2) = %g\n", - {tropicalMul(2,-2)}) - printf(1,"tropicalAdd(-0.001,-inf) = %g\n", - {tropicalAdd(-0.001,-inf)}) - printf(1,"tropicalMul(0,-inf) = %g\n", - {tropicalMul(0,-inf)}) - printf(1,"tropicalAdd(1.5,-1) = %g\n", - {tropicalAdd(1.5,-1)}) - printf(1,"tropicalMul(-0.5,0) = %g\n", - {tropicalMul(-0.5,0)}) - printf(1,"tropicalExp(5,7) = %g\n", - {tropicalExp(5,7)}) - printf(1,"tropicalMul(5,tropicalAdd(8,7)) = %g\n", - {tropicalMul(5,tropicalAdd(8,7))}) - printf(1,"tropicalAdd(tropicalMul(5,8),tropicalMul(5,7)) = %g\n", - {tropicalAdd(tropicalMul(5,8),tropicalMul(5,7))}) - printf(1,"tropicalMul(5,tropicalAdd(8,7)) == tropicalAdd(tropicalMul(5,8),tropicalMul(5,7)) = %t\n", - {tropicalMul(5,tropicalAdd(8,7)) == tropicalAdd(tropicalMul(5,8),tropicalMul(5,7))}) - - with javascript_semantics - constant bFT = false -- true: use F/T, false: use 0/1, as next +with javascript_semantics +constant bFT = false -- true: use F/T, false: use 0/1, as next - function fmt(bool b) - return iff(bFT?{"F","T"}:{"0","1"})[b+1] - end function +function fmt(bool b) + return iff(bFT?{"F","T"}:{"0","1"})[b+1] +end function - sequence opstack = {} - object token, - op = 0 -- 0 = none - string s -- the expression being parsed - integer sidx, -- idx to "" - ch -- s[sidx] +sequence opstack = {} +object token, + op = 0 -- 0 = none +string s -- the expression being parsed +integer sidx, -- idx to "" + ch -- s[sidx] - procedure err(string msg) - printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) - {} = wait_key() - abort(0) - end procedure +procedure err(string msg) + printf(1,"%s\n%s^ %s\n\nPressEnter...",{s,repeat(' ',sidx-1),msg}) + {} = wait_key() + abort(0) +end procedure - procedure nxtch() - sidx += 1 - ch = iff(sidx>length(s)?-1:s[sidx]) - end procedure +procedure nxtch() + sidx += 1 + ch = iff(sidx>length(s)?-1:s[sidx]) +end procedure - procedure skipspaces() - while find(ch," \t\r\n")!=0 do nxtch() end while - end procedure +procedure skipspaces() + while find(ch," \t\r\n")!=0 do nxtch() end while +end procedure - procedure get_token() - skipspaces() - if find(ch,"()!") then - token = s[sidx..sidx] - nxtch() - else - integer tokstart = sidx - if ch=-1 then token = "eof" return end if - while 1 do - nxtch() - if ch<'A' then exit end if - end while - token = s[tokstart..sidx-1] - end if - end procedure +procedure get_token() + skipspaces() + if find(ch,"()!") then + token = s[sidx..sidx] + nxtch() + else + integer tokstart = sidx + if ch=-1 then token = "eof" return end if + while 1 do + nxtch() + if ch<'A' then exit end if + end while + token = s[tokstart..sidx-1] + end if +end procedure - procedure Match(string t) - if token!=t then err(t&" expected") end if - get_token() - end procedure +procedure Match(string t) + if token!=t then err(t&" expected") end if + get_token() +end procedure - procedure PopFactor() - object p2 = opstack[$] - if op="not" then - opstack[$] = {0,op,p2} - else - opstack = opstack[1..$-1] - opstack[$] = {opstack[$],op,p2} - end if - op = 0 - end procedure +procedure PopFactor() + object p2 = opstack[$] + if op="not" then + opstack[$] = {0,op,p2} + else + opstack = opstack[1..$-1] + opstack[$] = {opstack[$],op,p2} + end if + op = 0 +end procedure - sequence names, -- {"false","true",...} - flags -- { 0, 1, ,...} +sequence names, -- {"false","true",...} + flags -- { 0, 1, ,...} - procedure PushFactor(string t) - if op!=0 then PopFactor() end if - integer k = find(t,names) - if k=0 then - names = append(names,t) - k = length(names) - end if - opstack = append(opstack,k) - end procedure +procedure PushFactor(string t) + if op!=0 then PopFactor() end if + integer k = find(t,names) + if k=0 then + names = append(names,t) + k = length(names) + end if + opstack = append(opstack,k) +end procedure - procedure PushOp(string t) - if op!=0 then PopFactor() end if - op = t - end procedure +procedure PushOp(string t) + if op!=0 then PopFactor() end if + op = t +end procedure - forward procedure Expr(integer p) +forward procedure Expr(integer p) - procedure Factor() - if token="not" - or token="!" then - get_token() - Factor() - if op!=0 then PopFactor() end if - PushOp("not") - elsif token="(" then - get_token() - Expr(0) - Match(")") - elsif not find(token,{"and","or","xor"}) then - PushFactor(token) - if ch!=-1 then - get_token() - end if - else - err("syntax error") - end if - end procedure +procedure Factor() + if token="not" + or token="!" then + get_token() + Factor() + if op!=0 then PopFactor() end if + PushOp("not") + elsif token="(" then + get_token() + Expr(0) + Match(")") + elsif not find(token,{"and","or","xor"}) then + PushFactor(token) + if ch!=-1 then + get_token() + end if + else + err("syntax error") + end if +end procedure - constant {operators, - precedence} = columnize({{"not",6}, - {"and",5}, - {"xor",4}, - {"or",3}}) - procedure Expr(integer p) - Factor() - while 1 do - integer k = find(token,operators) - if k=0 then exit end if - integer thisp = precedence[k] - if thisp<p then exit end if - get_token() - Expr(thisp) - PushOp(operators[k]) - end while - end procedure +constant {operators, + precedence} = columnize({{"not",6}, + {"and",5}, + {"xor",4}, + {"or",3}}) +procedure Expr(integer p) + Factor() + while 1 do + integer k = find(token,operators) + if k=0 then exit end if + integer thisp = precedence[k] + if thisp

    function evaluate(object s) - if atom(s) then - if s>=1 then s = flags[s] end if - return s - end if - object {lhs,op,rhs} = s - lhs = evaluate(lhs) - rhs = evaluate(rhs) - if op="and" then - return lhs and rhs - elsif op="or" then - return lhs or rhs - elsif op="xor" then - return lhs xor rhs - elsif op="not" then - return not rhs - else - ?9/0 - end if - end function +function evaluate(object s) + if atom(s) then + if s>=1 then s = flags[s] end if + return s + end if + object {lhs,op,rhs} = s + lhs = evaluate(lhs) + rhs = evaluate(rhs) + if op="and" then + return lhs and rhs + elsif op="or" then + return lhs or rhs + elsif op="xor" then + return lhs xor rhs + elsif op="not" then + return not rhs + else + ?9/0 + end if +end function - function next_comb() - integer fdx = length(flags) - while flags[fdx]=1 do - flags[fdx] = 0 - fdx -= 1 - end while - if fdx<=2 then return false end if -- all done - flags[fdx] = 1 - return true - end function +function next_comb() + integer fdx = length(flags) + while flags[fdx]=1 do + flags[fdx] = 0 + fdx -= 1 + end while + if fdx<=2 then return false end if -- all done + flags[fdx] = 1 + return true +end function - procedure test(string expr) - opstack = {} - op = 0 - names = {"false","true"} - s = expr - sidx = 0 - nxtch() - get_token() - Expr(0) - if op!=0 then PopFactor() end if - if length(opstack)!=1 then err("some error") end if - flags = repeat(0,length(names)) - flags[2] = 1 -- set "true" true - printf(1,"%s %s\n",{join(names[3..$]),s}) - while 1 do - for i=3 to length(flags) do -- (skipping true&false) - printf(1,"%s%s",{fmt(flags[i]),repeat(' ',length(names[i]))}) - end for - printf(1," %s\n",{fmt(evaluate(opstack[1]))}) - if not next_comb() then exit end if - end while - puts(1,"\n") - end procedure +procedure test(string expr) + opstack = {} + op = 0 + names = {"false","true"} + s = expr + sidx = 0 + nxtch() + get_token() + Expr(0) + if op!=0 then PopFactor() end if + if length(opstack)!=1 then err("some error") end if + flags = repeat(0,length(names)) + flags[2] = 1 -- set "true" true + printf(1,"%s %s\n",{join(names[3..$]),s}) + while 1 do + for i=3 to length(flags) do -- (skipping true&false) + printf(1,"%s%s",{fmt(flags[i]),repeat(' ',length(names[i]))}) + end for + printf(1," %s\n",{fmt(evaluate(opstack[1]))}) + if not next_comb() then exit end if + end while + puts(1,"\n") +end procedure - test("young and not (ugly or poor)") - if platform()!=JS then -- (no gets(0) in a browser) - while 1 do - puts(1,"input expression:") - string t = trim(gets(0)) - puts(1,"\n") - if t="" then exit end if - test(t) - end while - end if - - function s1(string s) return length(s)=12 end function - function s2(string s) return sum(sq_eq(s[7..12],'1'))=3 end function - function s3(string s) return sum(sq_eq(extract(s,tagset(12,2,2)),'1'))=2 end function - function s4(string s) return s[5]='0' or s[6..7]="11" end function - function s5(string s) return s[2..4]="000" end function - function s6(string s) return sum(sq_eq(extract(s,tagset(12,1,2)),'1'))=4 end function - function s7(string s) return s[2]!=s[3] end function - function s8(string s) return s[7]='0' or s[5..6]="11" end function - function s9(string s) return sum(sq_eq(s[1..6],'1'))=3 end function - function s10(string s) return s[11..12]="11" end function - function s11(string s) return sum(sq_eq(s[7..9],'1'))=1 end function - function s12(string s) return sum(sq_eq(s[1..11],'1'))=4 end function +function s1(string s) return length(s)=12 end function +function s2(string s) return sum(sq_eq(s[7..12],'1'))=3 end function +function s3(string s) return sum(sq_eq(extract(s,tagset(12,2,2)),'1'))=2 end function +function s4(string s) return s[5]='0' or s[6..7]="11" end function +function s5(string s) return s[2..4]="000" end function +function s6(string s) return sum(sq_eq(extract(s,tagset(12,1,2)),'1'))=4 end function +function s7(string s) return s[2]!=s[3] end function +function s8(string s) return s[7]='0' or s[5..6]="11" end function +function s9(string s) return sum(sq_eq(s[1..6],'1'))=3 end function +function s10(string s) return s[11..12]="11" end function +function s11(string s) return sum(sq_eq(s[7..9],'1'))=1 end function +function s12(string s) return sum(sq_eq(s[1..11],'1'))=4 end function - sequence rtn = {s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12} - string misses = "\n" - for i=0 to power(2,12)-1 do - string s = sprintf("%012b",i) - sequence res = find_all('1',s) - integer t = 0, pass, fail - for b=1 to 12 do - pass = call_func(rtn[b],{s})=(s[b]='1') - if not pass then fail = b end if - t += pass - if b=12 and t=12 then printf(1,"Solution: %v\n",{res}) end if - end for - if t=11 then - misses &= sprintf("Near miss: %v, fail on %d\n",{res,fail}) - end if - end for - puts(1,misses) - - with javascript_semantics - constant numbers = {" ## #", -- 0 - " ## #", -- 1 - " # ##", -- 2 - " #### #", -- 3 - " # ##", -- 4 - " ## #", -- 5 - " # ####", -- 6 - " ### ##", -- 7 - " ## ###", -- 8 - " # ##"} -- 9 +with javascript_semantics +constant numbers = {" ## #", -- 0 + " ## #", -- 1 + " # ##", -- 2 + " #### #", -- 3 + " # ##", -- 4 + " ## #", -- 5 + " # ####", -- 6 + " ### ##", -- 7 + " ## ###", -- 8 + " # ##"} -- 9 +function flip(string s) + for i,ch in s do + s[i] = iff(ch='#'?' ':'#') + end for + return s +end function +constant numberf = apply(numbers,flip) - procedure decode(string bar_code) - bar_code = trim(bar_code) - if length(bar_code)=95 - and bar_code[1..3]="# #" - and bar_code[46..50]=" # # " - and bar_code[93..95]="# #" then - for reversed=false to true do - sequence r = {} - for i=1 to 12 do - integer st = iff(i<=6?i*7-3:i*7+2) - string number = bar_code[st..st+6] - if i>6 then number = substitute_all(number," #X","X #") end if - r &= find(number,numbers)-1 - end for - if not find(-1,r) then - if remainder(sum(sq_mul(r,{3,1,3,1,3,1,3,1,3,1,3,1})),10) then - printf(1,"invalid checksum\n") - else - printf(1,"%v%s\n",{r,iff(reversed?" (upside down)","")}) - end if - return - end if - bar_code = reverse(bar_code) - end for - end if - printf(1,"invalid\n") - end procedure +procedure decode(string bar_code) + bar_code = trim(bar_code) + if length(bar_code)=95 + and bar_code[1..3]="# #" + and bar_code[46..50]=" # # " + and bar_code[93..95]="# #" then + for reversed=false to true do + sequence r = {}, nums = numbers + integer st = 4, checksum = 0, k + for i=1 to 12 do + k = find(bar_code[st..st+6],nums)-1 + if k=-1 then exit end if + r &= k + checksum += iff(odd(i)?k*3:k) + st += 7 + if i=6 then + st += 5 + nums = numberf + end if + end for + if k!=-1 then + if remainder(checksum,10) then + printf(1,"invalid checksum\n") + else + printf(1,"%v%s\n",{r,iff(reversed?" (upside down)","")}) + end if + return + end if + bar_code = reverse(bar_code) + end for + end if + printf(1,"invalid\n") +end procedure - constant bar_codes = split(""" - # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # - # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # - # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # - # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # - # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # - # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # - # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # - # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # - # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # - # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # - ""","\n",true) - for i=1 to length(bar_codes) do - decode(bar_codes[i]) - end for - small ---------- + do window = min(max_window, n - 1), min_window, -1 + hash_table = 0 + head = 0 + do i = 1, entry_count + if (allocated(entries(i)%key)) deallocate(entries(i)%key) + end do + entry_count = 0 + substr_count = 0 + + ! ----- pre-compute base powers for rolling hash ----- + hbase(1) = 1 + do i = 2, window + hbase(i) = mod(hbase(i - 1) * 31_int64, hash_size) + end do + + ! ----- initialise rolling hash for first window ----- + h = 0 + do i = 1, window + h = mod(h * 31 + iachar(text(i:i)), hash_size) + end do + + ! ----- single left?right sweep ----- + do i = 1, n - window + 1 + hash_val = mod(h, hash_size) ! 0 … HASH_SIZE-1 + + ! ---- search bucket (1-based indices) ---- + idx = -1 + p = head(hash_val) ! p is 1-based now + do while (p > 0) ! 0 means end-of-chain + j = p ! already 1-based + if (len(entries(j)%key) == window .and. entries(j)%key == text(i:i + window - 1)) then + idx = j + exit + end if + p = next(p) ! p stays 1-based + end do + + if (idx > 0) then + entries(idx)%count = entries(idx)%count + 1 + else + ! insert new entry at head of bucket + entry_count = entry_count + 1 + allocate(character(len=window) :: entries(entry_count)%key) + entries(entry_count)%key = text(i:i + window - 1) + entries(entry_count)%start_pos = i + entries(entry_count)%count = 1 + next(entry_count) = head(hash_val) ! old head (1-based) + head(hash_val) = entry_count ! new head (1-based) + end if + + ! ---- advance rolling hash ---- + if (i < n - window + 1) then + h = mod(h - iachar(text(i:i)) * hbase(window), hash_size) + h = mod(h * 31 + iachar(text(i + window:i + window)), hash_size) + hash_size + h = mod(h, hash_size) + end if + end do ! i + + ! ---- build return array ---- + substr_count = count(entries(1:entry_count)%count >= 2) + if (substr_count > 0) then + allocate(results(substr_count)) + k = 0 + do i = 1, entry_count + if (entries(i)%count < 2) cycle + k = k + 1 + allocate(character(len=window) :: results(k)%substring) + results(k)%substring = entries(i)%key + results(k)%count = entries(i)%count + + ! collect ALL positions (single INDEX scan per substring) + allocate(positions(0)) + p = 1 + do + pc = index(text(p:), entries(i)%key) + if (pc == 0) exit + positions = [positions, p + pc - 2] ! 0-based absolute + p = p + pc + end do + allocate(results(k)%positions(size(positions))) + results(k)%positions = positions + 1 ! 1-based + deallocate(positions) + end do + exit ! longest length found + end if + end do ! window + + ! clean-up + do i = 1, entry_count + if (allocated(entries(i)%key)) deallocate(entries(i)%key) + end do + deallocate(entries, hash_table, head, next) + if (.not.allocated(results)) allocate(results(0)) + end function find_lrs +end module lrs_simple + +program lrs_main + use lrs_simple + implicit none + + type(lrs_result), allocatable :: results(:) + character(:), allocatable :: pi_digits + character(1100000) :: line ! Large enough for 100000 digits + integer :: unit, ios + integer(kind=8) :: start_count, end_count, clock_rate + integer, parameter :: limits(4) = [1000, 10000, 100000, 1000000] + integer :: k, limit, line_len + real :: ms + integer :: i, j + + ! Open file + open(newunit=unit, file='piDigits.txt', status='old', action='read', iostat=ios) + if (ios /= 0) stop "piDigits.txt not found!" + + ! Process each of the 3 lines + do k = 1, 4 + limit = limits(k) + + ! Read one complete line + read(unit, '(a)', iostat=ios) line + if (ios /= 0) then + print *, "Error reading line ", k + exit + end if + + ! Get actual length of line (trim trailing spaces) + line_len = len_trim(line) + pi_digits = trim(line) + + call system_clock(start_count, clock_rate) + + ! Find longest repeated substrings + results = find_lrs(pi_digits) + + call system_clock(end_count) + ms = real(end_count - start_count, kind=8) / clock_rate * 1000.0 + + print '(a,i0,a)', "First ", limit, " digits of pi has longest repeated substring(s):" + + ! Print results (sorted lexicographically) + if (size(results) > 0) then + ! Sort results by substring (bubble sort for simplicity) + call sort_results(results) + + do i = 1, size(results) + write(*, '(5a)', advance='no') " '", trim(results(i)%substring), & + "' starting at index " + + ! Print positions + do j = 1, results(i)%count + if (j > 1) write(*, '(a)', advance='no') " " + write(*, '(i0)', advance='no') results(i)%positions(j) + end do + print * + end do + else + print *, " No repeated substring found" + end if + + print '(a,f0.3,a)', "Time taken: ", ms, " milliseconds" + print * + end do + + close(unit) + + print *, "The timings show the performance characteristics of the implementation." + +contains + + ! Sort results lexicographically by substring + subroutine sort_results(results) + type(lrs_result), allocatable, intent(inout) :: results(:) + type(lrs_result) :: temp + integer :: i, j, n + logical :: swapped + + n = size(results) + if (n <= 1) return + + ! Bubble sort + do i = 1, n - 1 + swapped = .false. + do j = 1, n - i + if (results(j)%substring > results(j + 1)%substring) then + ! Swap + temp = results(j) + results(j) = results(j + 1) + results(j + 1) = temp + swapped = .true. + end if + end do + if (.not.swapped) exit + end do + end subroutine sort_results + +end program lrs_main diff --git a/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.adb b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.adb new file mode 100644 index 0000000000..7e56acbff7 --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--1.adb @@ -0,0 +1,19 @@ +generic + Size: Positive; + -- determines the size of the square + with function Represent(N: Natural) return String; + -- this turns a number into a string to be printed + -- the length of the output should not change + -- e.g., Represent(N) may return " #" if N is a prime + -- and " " else + with procedure Put_String(S: String); + -- outputs a string, no new line + with procedure New_Line; + -- the name says all +package Generic_Ulam is + + procedure Print_Spiral; + -- calls Put_String(Represent(I)) N^2 times + -- and New_Line N times + +end Generic_Ulam; diff --git a/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.adb b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.adb new file mode 100644 index 0000000000..e766ea957d --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--2.adb @@ -0,0 +1,36 @@ +package body Generic_Ulam is + + subtype Index is Natural range 0 .. Size-1; + subtype Number is Positive range 1 .. Size**2; + + function Cell(Row, Column: Index) return Number is + -- outputs the number at the given position in the square + -- taken from the Python solution + X: Integer := Column - (Size-1)/2; + Y: Integer := Row - Size/2; + MX: Natural := abs(X); + MY: Natural := abs(Y); + L: Natural := 2 * Natural'Max(MX, MY); + D: Integer; + begin + if Y >= X then + D := 3 * L + X + Y; + else + D := L - X - Y; + end if; + return (L-1) ** 2 + D; + end Cell; + + procedure Print_Spiral is + N: Number; + begin + for R in Index'Range loop + for C in Index'Range loop + N := Cell(R, C); + Put_String(Represent(N)); + end loop; + New_Line; + end loop; + end Print_Spiral; + +end Generic_Ulam; diff --git a/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.adb b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.adb new file mode 100644 index 0000000000..7207fc146e --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/Ada/ulam-spiral-for-primes--3.adb @@ -0,0 +1,27 @@ +with Generic_Ulam, Ada.Text_IO, Prime_Numbers; + +procedure Ulam is + + package P is new Prime_Numbers(Natural, 0, 1, 2); + + function Vis(N: Natural) return String is + (if P.Is_Prime(N) then " <>" else " "); + + function Num(N: Natural) return String is + (if P.Is_Prime(N) then + (if N < 10 then " " elsif N < 100 then " " else "") & Natural'Image(N) + else " ---"); + + procedure NL is + begin + Ada.Text_IO.New_Line; + end NL; + + package Numeric is new Generic_Ulam(29, Num, Ada.Text_IO.Put, NL); + package Visual is new Generic_Ulam(10, Vis, Ada.Text_IO.Put, NL); + +begin + Numeric.Print_Spiral; + NL; + Visual.Print_Spiral; +end Ulam; diff --git a/Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.ps1 b/Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.ps1 new file mode 100644 index 0000000000..344b1681d4 --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/PowerShell/ulam-spiral-for-primes-.ps1 @@ -0,0 +1,40 @@ +function New-UlamSpiral ( [int]$N ) + { + # Generate list of primes + $Primes = @( 2 ) + For ( $X = 3; $X -le $N*$N; $X += 2 ) + { + If ( -not ( $Primes | Where { $X % $_ -eq 0 } | Select -First 1 ) ) { $Primes += $X } + } + + # Initialize variables + $X = 0 + $Y = -1 + $i = $N * $N + 1 + $Sign = 1 + + # Intialize array + $A = New-Object 'boolean[,]' $N, $N + + # Set top row + 1..$N | ForEach { $Y += $Sign; $A[$X,$Y] = --$i -in $Primes } + + # For each remaining half spiral... + ForEach ( $M in ($N-1)..1 ) + { + # Set the vertical quarter spiral + 1..$M | ForEach { $X += $Sign; $A[$X,$Y] = --$i -in $Primes } + + # Curve the spiral + $Sign = -$Sign + + # Set the horizontal quarter spiral + 1..$M | ForEach { $Y += $Sign; $A[$X,$Y] = --$i -in $Primes } + } + + # Convert the array of booleans to text output of dots and spaces + $Spiral = ForEach ( $X in 1..$N ) { ( 1..$N | ForEach { ( ' ', '.' )[$A[($X-1),($_-1)]] } ) -join '' } + return $Spiral + } + +New-UlamSpiral 100 diff --git a/Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vbs b/Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vbs new file mode 100644 index 0000000000..7ea52764c1 --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/VBScript/ulam-spiral-for-primes-.vbs @@ -0,0 +1,80 @@ +Function build_spiral(n) + 'declare a two dimentional array + Dim matrix() + ReDim matrix(n-1,n-1) + 'determine starting point + x = (n-1)/2 : y = (n-1)/2 + 'set the initial iterations + x_max = 1 : y_max = 1 : count = 1 + 'set initial direction + dir = "R" + 'populate the array + For i = 1 To n*n + l = Len(n*n) + If IsPrime(i) Then + matrix(x,y) = Right("000" & i,l) + Else + matrix(x,y) = String(l,"-") + End If + Select Case dir + Case "R" + If x_max > 0 Then + x = x + 1 : x_max = x_max - 1 + Else + dir = "U" : y_max = count + y = y - 1 : y_max = y_max - 1 + End If + Case "U" + If y_max > 0 Then + y = y - 1 : y_max = y_max - 1 + Else + dir = "L" : count = count + 1 : x_max = count + x = x - 1 : x_max = x_max - 1 + End If + Case "L" + If x_max > 0 Then + x = x - 1 : x_max = x_max - 1 + Else + dir = "D" : y_max = count + y = y + 1 : y_max = y_max - 1 + End If + Case "D" + If y_max > 0 Then + y = y + 1 : y_max = y_max - 1 + Else + dir = "R" : count = count + 1 : x_max = count + x = x + 1 : x_max = x_max - 1 + End If + End Select + Next + 'print the matrix + For y = 0 To n - 1 + For x = 0 To n - 1 + If x = n - 1 Then + WScript.StdOut.Write matrix(x,y) + Else + WScript.StdOut.Write matrix(x,y) & vbTab + End If + Next + WScript.StdOut.WriteLine + Next +End Function + +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +'test with 9 +build_spiral(9) diff --git a/Task/Ultra-useful-primes/Ada/ultra-useful-primes.adb b/Task/Ultra-useful-primes/Ada/ultra-useful-primes.adb new file mode 100644 index 0000000000..d4ebf12414 --- /dev/null +++ b/Task/Ultra-useful-primes/Ada/ultra-useful-primes.adb @@ -0,0 +1,25 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; + +procedure Ultra_Useful_Primes is + Count : Integer := 16; + + function Find (N : Positive) return Positive is + P : Unbounded_Unsigned := Power_Of_Two (2 ** N); + begin + for K in 1..Positive'Last loop + Sub (P, 1); + if Is_Prime (P, 10) = Prime then + return K; + end if; + end loop; + return 1; -- Never get here + end Find; +begin + Put ("a(n):"); + for N in 1..10 loop + Put (Integer'Image (Find (N))); + end loop; + New_Line; +end Ultra_Useful_Primes; diff --git a/Task/Ultra-useful-primes/FutureBasic/ultra-useful-primes.basic b/Task/Ultra-useful-primes/FutureBasic/ultra-useful-primes.basic new file mode 100644 index 0000000000..00c426a4cd --- /dev/null +++ b/Task/Ultra-useful-primes/FutureBasic/ultra-useful-primes.basic @@ -0,0 +1,108 @@ +// ------------------------------------------------------------ +// Ultra-useful primes sequence +// Using FutureBasic 7.0.36 +// November 2025, R.W +// +// a(n) = smallest odd k such that 2^(2^n) - k +// is (probable) prime +// ------------------------------------------------------------ + +include "gmp.incl" + +_kPrimeReps = 25 +_kMaxExp = 32767 + +int gN +CFTimeInterval t + +// Abbreviate big numeric string +local fn AbbrevCFNumber( s as CFStringRef, head as int, tail as int ) as CFStringRef + if s = 0 then RETURN @"" + int n : n = len(s) + if n <= head + tail then RETURN s + CFStringRef a, b + a = left (s, head) + b = right(s, tail) + CFStringRef out = @"" + out = concat ( a , @"...", b) +end fn = out + + +// Compute a(n), print n, a(n), and abbreviated prime +void local fn ComputeAndPrint( n as Int ) + UInt32 mexp : mexp = 1 + int i + for i = 1 to n + mexp = mexp << 1 + next + + // Guard against overflow in 32-bit exp; once it explodes, bail + if mexp > _kMaxExp + print using "##";n;" ** exp beyond ";_kMaxExp + RETURN + end if + + mpz_t p + mpz_init(p) + + // p = 2^mexp - 1 + fn mpz_ui_pow_ui(p, 2, mexp) + fn mpz_sub_ui(p, p, 1) + + long k : k = 1 + while fn mpz_probab_prime_p(p, _kPrimeReps) = 0 + k = k + 2 + fn mpz_sub_ui(p, p, 2) + wend + + // Convert to string and abbreviate + CFStringRef pStr = fn mpz_cf2(p) + CFStringRef shortStr = fn AbbrevCFNumber(pStr, 36, 36) + print using "##";n; using "######"; k;" "; shortStr + mpz_clear(p) +end fn + +// Get next 5 sequence +local fn next5 + t = fn CACurrentMediaTime + for int n = gN to gN+4 + fn ComputeAndPrint(n) + next + printf @"\nElapsed time time: %.3f secs\n", (fn CACurrentMediaTime-t) + gN = n +end fn + + +void local fn DoDialog( ev as long, tag as long, wnd as long, obj as CFTypeRef ) + select ( ev ) + case _btnClick + select ( tag ) + case 2 + fn next5 + end select + end select +end fn + +on dialog fn DoDialog + +// Main + +window 1, @"Ultra-useful primes sequence", (60,60,640,520) +button 2,YES,,@"Next 5",(10,20,100,20),,,1 + +on dialog fn doDialog + +print @" n"; @"\t"; @"a(n)"; @"\t"; @"prime" +print string$(60, "-") + +// start the clock + +t = fn CACurrentMediaTime +int n +for n = 1 to 10 + fn ComputeAndPrint(n) +next +gN = n +printf @"\nElapsed time time: %.3f secs\n", (fn CACurrentMediaTime-t) + +HandleEvents diff --git a/Task/Ultra-useful-primes/Pluto/ultra-useful-primes.pluto b/Task/Ultra-useful-primes/Pluto/ultra-useful-primes.pluto new file mode 100644 index 0000000000..3be99821c3 --- /dev/null +++ b/Task/Ultra-useful-primes/Pluto/ultra-useful-primes.pluto @@ -0,0 +1,18 @@ +require "bignum" +local fmt = require "fmt" + +mpz.init() + +local function a(n) + local p = mpz.shl(bigint.one, 1 << n) - 1 + local k = 1 + while true do + if mpz.isprobableprime(p, 15) then return k end + p -= bigint.two + k += 2 + end +end + +print(" n k") +print("----------") +for n = 1, 13 do fmt.print("%2d %d", n, a(n)) end diff --git a/Task/Ultra-useful-primes/Unicon/ultra-useful-primes.unicon b/Task/Ultra-useful-primes/Unicon/ultra-useful-primes.unicon new file mode 100644 index 0000000000..cb795432f0 --- /dev/null +++ b/Task/Ultra-useful-primes/Unicon/ultra-useful-primes.unicon @@ -0,0 +1,11 @@ +link fastprime + +procedure main(A) + limit := \A[1] | 10 + cnt := 0 + every n := seq() do { + every (x := 2^2^n, k := seq(1,2)) do + if (is_prime(x-k), cnt +:= 1) then (write(" a(",n,") = ",k),break) + if cnt >= limit then break + } +end diff --git a/Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.adb b/Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.adb new file mode 100644 index 0000000000..0558de0003 --- /dev/null +++ b/Task/Unbias-a-random-generator/Ada/unbias-a-random-generator.adb @@ -0,0 +1,51 @@ +with Ada.Text_IO; with Ada.Numerics.Discrete_Random; + +procedure Bias_Unbias is + + Modulus: constant Integer := 60; -- lcm of {3,4,5,6} + type M is mod Modulus; + package Rand is new Ada.Numerics.Discrete_Random(M); + Gen: Rand.Generator; + + subtype Bit is Integer range 0 .. 1; + + function Biased_Bit(Bias_Base: Integer) return Bit is + begin + if (Integer(Rand.Random(Gen))* Bias_Base) / Modulus > 0 then + return 0; + else + return 1; + end if; + end Biased_Bit; + + function Unbiased_Bit(Bias_Base: Integer) return Bit is + A, B: Bit := 0; + begin + while A = B loop + A := Biased_Bit(Bias_Base); + B := Biased_Bit(Bias_Base); + end loop; + return A; + end Unbiased_Bit; + + package FIO is new Ada.Text_IO.Float_IO(Float); + + Counter_B, Counter_U: Natural; + Number_Of_Samples: constant Natural := 10_000; + +begin + Rand.Reset(Gen); + Ada.Text_IO.Put_Line(" I Biased% UnBiased%"); + for I in 3 .. 6 loop + Counter_B := 0; + Counter_U := 0; + for J in 1 .. Number_Of_Samples loop + Counter_B := Counter_B + Biased_Bit(I); + Counter_U := Counter_U + Unbiased_Bit(I); + end loop; + Ada.Text_IO.Put(Integer'Image(I)); + FIO.Put(100.0 * Float(Counter_B) / Float(Number_Of_Samples), 5, 2, 0); + FIO.Put(100.0 * Float(Counter_U) / Float(Number_Of_Samples), 5, 2, 0); + Ada.Text_IO.New_Line; + end loop; +end Bias_Unbias; diff --git a/Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.eu b/Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.eu new file mode 100644 index 0000000000..bac017f5a4 --- /dev/null +++ b/Task/Unbias-a-random-generator/Euphoria/unbias-a-random-generator.eu @@ -0,0 +1,25 @@ +function randN(integer N) + return rand(N) = 1 +end function + +function unbiased(integer N) + integer a + while 1 do + a = randN(N) + if a != randN(N) then + return a + end if + end while +end function + +constant n = 10000 +integer cb, cu +for b = 3 to 6 do + cb = 0 + cu = 0 + for i = 1 to n do + cb += randN(b) + cu += unbiased(b) + end for + printf(1, "%d: %5.2f%% %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n}) +end for diff --git a/Task/Unbias-a-random-generator/JavaScript/unbias-a-random-generator.js b/Task/Unbias-a-random-generator/JavaScript/unbias-a-random-generator.js new file mode 100644 index 0000000000..ed21433948 --- /dev/null +++ b/Task/Unbias-a-random-generator/JavaScript/unbias-a-random-generator.js @@ -0,0 +1,20 @@ +const randN = N => () => Math.floor(Math.random() * N) === 0; + +function unbiased(f) { + let x, y; + do { + x = f(), y = f(); + } while (x === y); + return x; +} + +for (let i = 3; i <= 6; i++) { + const biased = randN(i); + let b = [], ub = []; + for (let j = 0; j < 10000; j++) { + b.push(biased()); + ub.push(unbiased(biased)); + } + const onecounts = [b, ub].map(a => a.filter(x => x).length / 100); + console.log(`N = ${i}: biased ${onecounts[0]}% ones, unbiased ${onecounts[1]}% ones`); +} diff --git a/Task/Unbias-a-random-generator/Pluto/unbias-a-random-generator.pluto b/Task/Unbias-a-random-generator/Pluto/unbias-a-random-generator.pluto new file mode 100644 index 0000000000..f8144eef75 --- /dev/null +++ b/Task/Unbias-a-random-generator/Pluto/unbias-a-random-generator.pluto @@ -0,0 +1,22 @@ +local fmt = require "fmt" + +local biased = |n| -> math.random() < 1 / n + +local function unbiased(n) + while true do + local a = biased(n) + local b = biased(n) + if a != b then return a end + end +end + +local m = 50_000 +local f = "%d: %2.2f%% %2.2f%%" +for n = 3, 6 do + local c1, c2 = 0, 0 + for _ = 1, m do + if biased(n) then c1 += 1 end + if unbiased(n) then c2 += 1 end + end + fmt.print(f, n, 100 * c1 / m, 100 * c2 / m) +end diff --git a/Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-1.ps1 b/Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-1.ps1 new file mode 100644 index 0000000000..86e6355137 --- /dev/null +++ b/Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-1.ps1 @@ -0,0 +1,15 @@ +function randN ( [int]$N ) + { + [int]( ( Get-Random -Maximum $N ) -eq 0 ) + } + +function unbiased ( [int]$N ) + { + do { + $X = randN $N + $Y = randN $N + } + While ( $X -eq $Y ) + + return $X + } diff --git a/Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-2.ps1 b/Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-2.ps1 new file mode 100644 index 0000000000..d95cd1dec3 --- /dev/null +++ b/Task/Unbias-a-random-generator/PowerShell/unbias-a-random-generator-2.ps1 @@ -0,0 +1,15 @@ +$Tests = 1000 +ForEach ( $N in 3..6 ) + { + $Biased = 0 + $Unbiased = 0 + + ForEach ( $Test in 1..$Tests ) + { + $Biased += randN $N + $Unbiased += unbiased $N + } + [pscustomobject]@{ N = $N + "Biased Ones out of $Test" = $Biased + "Unbiased Ones out of $Test" = $Unbiased } + } diff --git a/Task/Undefined-values/Ada/undefined-values.adb b/Task/Undefined-values/Ada/undefined-values.adb new file mode 100644 index 0000000000..11930c3ddf --- /dev/null +++ b/Task/Undefined-values/Ada/undefined-values.adb @@ -0,0 +1,23 @@ +pragma Initialize_Scalars; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Invalid_Value is + type Color is (Red, Green, Blue); + X : Float; + Y : Color; +begin + if not X'Valid then + Put_Line ("X is not valid"); + end if; + X := 1.0; + if X'Valid then + Put_Line ("X is" & Float'Image (X)); + end if; + if not Y'Valid then + Put_Line ("Y is not valid"); + end if; + Y := Green; + if Y'Valid then + Put_Line ("Y is " & Color'Image (Y)); + end if; +end Invalid_Value; diff --git a/Task/Undefined-values/PowerShell/undefined-values-1.ps1 b/Task/Undefined-values/PowerShell/undefined-values-1.ps1 new file mode 100644 index 0000000000..5628ee69ae --- /dev/null +++ b/Task/Undefined-values/PowerShell/undefined-values-1.ps1 @@ -0,0 +1,8 @@ +if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue) +{ + $true +} +else +{ + $false +} diff --git a/Task/Undefined-values/PowerShell/undefined-values-2.ps1 b/Task/Undefined-values/PowerShell/undefined-values-2.ps1 new file mode 100644 index 0000000000..3804bb5313 --- /dev/null +++ b/Task/Undefined-values/PowerShell/undefined-values-2.ps1 @@ -0,0 +1 @@ +Get-PSProvider diff --git a/Task/Undefined-values/PowerShell/undefined-values-3.ps1 b/Task/Undefined-values/PowerShell/undefined-values-3.ps1 new file mode 100644 index 0000000000..f7bdf3f02b --- /dev/null +++ b/Task/Undefined-values/PowerShell/undefined-values-3.ps1 @@ -0,0 +1 @@ +Test-Path Variable:\noSuchVariable diff --git a/Task/Undefined-values/PowerShell/undefined-values-4.ps1 b/Task/Undefined-values/PowerShell/undefined-values-4.ps1 new file mode 100644 index 0000000000..4146802ccf --- /dev/null +++ b/Task/Undefined-values/PowerShell/undefined-values-4.ps1 @@ -0,0 +1 @@ +$noSuchVariable -eq $null diff --git a/Task/Unicode-strings/FutureBasic/unicode-strings.basic b/Task/Unicode-strings/FutureBasic/unicode-strings.basic new file mode 100644 index 0000000000..348cfa85f3 --- /dev/null +++ b/Task/Unicode-strings/FutureBasic/unicode-strings.basic @@ -0,0 +1,48 @@ +_window = 1 +begin enum output 1 + _scrollView + _textView +end enum + +void local fn BuildWindow + CGRect r = fn CGRectMake( 0, 0, 550, 400 ) + window _window, @"Unicode Characters in FutureBasic", r + + scrollview _scrollView, r + ViewSetAutoresizingMask( _scrollView, NSViewWidthSizable + NSViewHeightSizable ) + textview _textView,, _scrollView + + CFMutableStringRef testStr = fn MutableStringWithCapacity( 0 ) + + MutableStringAppendString( testStr, @"\U0001F34C" ) + MutableStringAppendString( testStr, @"\U0001F444" ) + MutableStringAppendString( testStr, @"\U0001F41E" ) + MutableStringAppendString( testStr, @"\U0001F37A" ) + MutableStringAppendString( testStr, @"\U0001F41D" ) + MutableStringAppendString( testStr, @"\U0001F48A" ) + MutableStringAppendString( testStr, @"☎️" ) + MutableStringAppendString( testStr, @"\U0001F4A1" ) + MutableStringAppendString( testStr, @"🍎" ) + MutableStringAppendString( testStr, @"⚽️" ) + MutableStringAppendString( testStr, @"🚁" ) + MutableStringAppendString( testStr, @"⏰" ) + MutableStringAppendString( testStr, @"\u2699\uFE0F" ) + MutableStringAppendString( testStr, @"\U0001F69C" ) + MutableStringAppendString( testStr, @"\U0001F333" ) + MutableStringAppendString( testStr, @"\U0001F413" ) + MutableStringAppendString( testStr, @"\U0001F6A3" ) + MutableStringAppendString( testStr, @"\U0001F6C1" ) + + TextSetString( _textView, testStr ) + + CFMutableAttributedStringRef storage = (CFMutableAttributedStringRef)fn TextViewTextStorage( _textView ) + MutableAttributedStringSetFontWithName( storage, @"Menlo", 110 ) + + WindowMakeFirstResponder( _window, _textView ) +end fn + +editmenu 1 + +fn BuildWindow + +HandleEvents diff --git a/Task/Unicode-strings/JavaScript/unicode-strings.js b/Task/Unicode-strings/JavaScript/unicode-strings.js new file mode 100644 index 0000000000..b89b310e0f --- /dev/null +++ b/Task/Unicode-strings/JavaScript/unicode-strings.js @@ -0,0 +1 @@ +console.log([..."🇺🇳🇺🇸"]); diff --git a/Task/Unicode-strings/PowerShell/unicode-strings.ps1 b/Task/Unicode-strings/PowerShell/unicode-strings.ps1 new file mode 100644 index 0000000000..09f17161a5 --- /dev/null +++ b/Task/Unicode-strings/PowerShell/unicode-strings.ps1 @@ -0,0 +1,2 @@ +# `u{x} +"I`u{0307}" # => İ diff --git a/Task/Unicode-variable-names/Ada/unicode-variable-names.adb b/Task/Unicode-variable-names/Ada/unicode-variable-names.adb new file mode 100644 index 0000000000..e98ea6c2a1 --- /dev/null +++ b/Task/Unicode-variable-names/Ada/unicode-variable-names.adb @@ -0,0 +1,8 @@ +with Ada.Text_IO; +procedure main is + Δ : Integer; +begin + Δ := 41; + Δ := Δ + 1; + Ada.Text_IO.Put_Line (Δ'Img); +end main; diff --git a/Task/Unicode-variable-names/Batch-File/unicode-variable-names.bat b/Task/Unicode-variable-names/Batch-File/unicode-variable-names.bat new file mode 100644 index 0000000000..7838869331 --- /dev/null +++ b/Task/Unicode-variable-names/Batch-File/unicode-variable-names.bat @@ -0,0 +1,6 @@ +@echo off +setlocal +chcp 65001 +set Δ=1 +set /a Δ+=1 +set Δ diff --git a/Task/Unicode-variable-names/Emacs-Lisp/unicode-variable-names.el b/Task/Unicode-variable-names/Emacs-Lisp/unicode-variable-names.el new file mode 100644 index 0000000000..7c353ea26f --- /dev/null +++ b/Task/Unicode-variable-names/Emacs-Lisp/unicode-variable-names.el @@ -0,0 +1,3 @@ +(setq Δ 1) +(setq Δ (1+ Δ)) +(message "Δ is %d" Δ) diff --git a/Task/Unicode-variable-names/Maxima/unicode-variable-names.maxima b/Task/Unicode-variable-names/Maxima/unicode-variable-names.maxima new file mode 100644 index 0000000000..3e0476fb80 --- /dev/null +++ b/Task/Unicode-variable-names/Maxima/unicode-variable-names.maxima @@ -0,0 +1,3 @@ +Δ: 1$ +Δ: Δ+1$ +sconcat("Δ = ", Δ); diff --git a/Task/Unicode-variable-names/PowerShell/unicode-variable-names.ps1 b/Task/Unicode-variable-names/PowerShell/unicode-variable-names.ps1 new file mode 100644 index 0000000000..631a0cdbf1 --- /dev/null +++ b/Task/Unicode-variable-names/PowerShell/unicode-variable-names.ps1 @@ -0,0 +1,3 @@ +$Δ = 2 +$π = 3.14 +$π*$Δ diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-1.adb b/Task/Universal-Turing-machine/Ada/universal-turing-machine-1.adb new file mode 100644 index 0000000000..d61152cc6d --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-1.adb @@ -0,0 +1,54 @@ +private with Ada.Containers.Doubly_Linked_Lists; + +generic + type State is (<>); -- State'First is starting state + type Symbol is (<>); -- Symbol'First is blank +package Turing is + + Start: constant State := State'First; + Halt: constant State := State'Last; + subtype Action_State is State range Start .. State'Pred(Halt); + + Blank: constant Symbol := Symbol'First; + + type Movement is (Left, Stay, Right); + + type Action is record + New_State: State; + Move_To: Movement; + New_Symbol: Symbol; + end record; + + type Rules_Type is array(Action_State, Symbol) of Action; + + type Tape_Type is limited private; + + type Symbol_Map is array(Symbol) of Character; + + function To_String(Tape: Tape_Type; Map: Symbol_Map) return String; + function Position_To_String(Tape: Tape_Type; Marker: Character := '^') + return String; + function To_Tape(Str: String; Map: Symbol_Map) return Tape_Type; + + procedure Single_Step(Current: in out State; + Tape: in out Tape_Type; + Rules: Rules_Type); + + procedure Run(The_Tape: in out Tape_Type; + Rules: Rules_Type; + Max_Steps: Natural := Natural'Last; + Print: access procedure(Tape: Tape_Type; Current: State)); + -- runs from Start State until either Halt or # Steps exceeds Max_Steps + -- if # of steps exceeds Max_Steps, Constrained_Error is raised; + -- if Print is not null, Print is called at the beginning of each step + +private + package Symbol_Lists is new Ada.Containers.Doubly_Linked_Lists(Symbol); + subtype List is Symbol_Lists.List; + + type Tape_Type is record + Left: List; + Here: Symbol; + Right: List; + end record; +end Turing; diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-2.adb b/Task/Universal-Turing-machine/Ada/universal-turing-machine-2.adb new file mode 100644 index 0000000000..05e3b3cea5 --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-2.adb @@ -0,0 +1,98 @@ +package body Turing is + + function List_To_String(L: List; Map: Symbol_Map) return String is + LL: List := L; + use type List; + begin + if L = Symbol_Lists.Empty_List then + return ""; + else + LL.Delete_First; + return Map(L.First_Element) & List_To_String(LL, Map); + end if; + end List_To_String; + + function To_String(Tape: Tape_Type; Map: Symbol_Map) return String is + + begin + return List_To_String(Tape.Left, Map) & Map(Tape.Here) & + List_To_String(Tape.Right, Map); + end To_String; + + function Position_To_String(Tape: Tape_Type; Marker: Character := '^') + return String is + Blank_Map: Symbol_Map := (others => ' '); + begin + return List_To_String(Tape.Left, Blank_Map) & Marker & + List_To_String(Tape.Right, Blank_Map); + end Position_To_String; + + function To_Tape(Str: String; Map: Symbol_Map) return Tape_Type is + Char_Map: array(Character) of Symbol := (others => Blank); + Tape: Tape_Type; + begin + if Str = "" then + Tape.Here := Blank; + else + for S in Symbol loop + Char_Map(Map(S)) := S; + end loop; + Tape.Here := Char_Map(Str(Str'First)); + for I in Str'First+1 .. Str'Last loop + Tape.Right.Append(Char_Map(Str(I))); + end loop; + end if; + return Tape; + end To_Tape; + + procedure Single_Step(Current: in out State; + Tape: in out Tape_Type; + Rules: Rules_Type) is + Act: Action := Rules(Current, Tape.Here); + use type List; -- needed to compare Tape.Left/Right to the Empty_List + begin + Current := Act.New_State; -- 1. update State + Tape.Here := Act.New_Symbol; -- 2. write Symbol to Tape + case Act.Move_To is -- 3. move Tape to the Left/Right or Stay + when Left => + Tape.Right.Prepend(Tape.Here); + if Tape.Left /= Symbol_Lists.Empty_List then + Tape.Here := Tape.Left.Last_Element; + Tape.Left.Delete_Last; + else + Tape.Here := Blank; + end if; + when Stay => + null; -- Stay where you are! + when Right => + Tape.Left.Append(Tape.Here); + if Tape.Right /= Symbol_Lists.Empty_List then + Tape.Here := Tape.Right.First_Element; + Tape.Right.Delete_First; + else + Tape.Here := Blank; + end if; + end case; + end Single_Step; + + procedure Run(The_Tape: in out Tape_Type; + Rules: Rules_Type; + Max_Steps: Natural := Natural'Last; + Print: access procedure (Tape: Tape_Type; Current: State)) is + The_State: State := Start; + Steps: Natural := 0; + begin + Steps := 0; + while (Steps <= Max_Steps) and (The_State /= Halt) loop + if Print /= null then + Print(The_Tape, The_State); + end if; + Steps := Steps + 1; + Single_Step(The_State, The_Tape, Rules); + end loop; + if The_State /= Halt then + raise Constraint_Error; + end if; + end Run; + +end Turing; diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-3.adb b/Task/Universal-Turing-machine/Ada/universal-turing-machine-3.adb new file mode 100644 index 0000000000..a1b85343f7 --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-3.adb @@ -0,0 +1,27 @@ +with Ada.Text_IO, Turing; + +procedure Simple_Incrementer is + + type States is (Start, Stop); + type Symbols is (Blank, One); + + package UTM is new Turing(States, Symbols); + use UTM; + + Map: Symbol_Map := (One => '1', Blank => '_'); + + Rules: Rules_Type := + (Start => (One => (Start, Right, One), + Blank => (Stop, Stay, One))); + Tape: Tape_Type := To_Tape("111", Map); + + procedure Put_Tape(Tape: Tape_Type; Current: States) is + begin + Ada.Text_IO.Put_Line(To_String(Tape, Map) & " " & States'Image(Current)); + Ada.Text_IO.Put_Line(Position_To_String(Tape)); + end Put_Tape; + +begin + Run(Tape, Rules, 20, null); -- don't print the configuration during running + Put_Tape(Tape, Stop); -- print the final configuration +end Simple_Incrementer; diff --git a/Task/Universal-Turing-machine/Ada/universal-turing-machine-4.adb b/Task/Universal-Turing-machine/Ada/universal-turing-machine-4.adb new file mode 100644 index 0000000000..42ca413380 --- /dev/null +++ b/Task/Universal-Turing-machine/Ada/universal-turing-machine-4.adb @@ -0,0 +1,31 @@ +with Ada.Text_IO, Turing; + +procedure Busy_Beaver_3 is + + type States is (A, B, C, Stop); + type Symbols is range 0 .. 1; + package UTM is new Turing(States, Symbols); use UTM; + + Map: Symbol_Map := (1 => '1', 0 => '0'); + + Rules: Rules_Type := + (A => (0 => (New_State => B, Move_To => Right, New_Symbol => 1), + 1 => (New_State => C, Move_To => Left, New_Symbol => 1)), + B => (0 => (New_State => A, Move_To => Left, New_Symbol => 1), + 1 => (New_State => B, Move_To => Right, New_Symbol => 1)), + C => (0 => (New_State => B, Move_To => Left, New_Symbol => 1), + 1 => (New_State => Stop, Move_To => Stay, New_Symbol => 1))); + + Tape: Tape_Type := To_Tape("", Map); + + procedure Put_Tape(Tape: Tape_Type; Current: States) is + begin + Ada.Text_IO.Put_Line(To_String(Tape, Map) & " " & + States'Image(Current)); + Ada.Text_IO.Put_Line(Position_To_String(Tape)); + end Put_Tape; + +begin + Run(Tape, Rules, 20, Put_Tape'Access); -- print configuration before each step + Put_Tape(Tape, Stop); -- and print the final configuration +end Busy_Beaver_3; diff --git a/Task/Universal-Turing-machine/Ring/universal-turing-machine.ring b/Task/Universal-Turing-machine/Ring/universal-turing-machine.ring new file mode 100644 index 0000000000..3072144152 --- /dev/null +++ b/Task/Universal-Turing-machine/Ring/universal-turing-machine.ring @@ -0,0 +1,192 @@ +# Author: Gal Zsolt (CalmoSoft) +load "guilib.ring" +load "stdlib.ring" + +# --- Global Variables --- +cTape = "110100" +nHeadPos = 1 +cCurrentState = "q0" +nSpeed = 500 +# Rules format: [State, Read, [NewState, Write, Move]] +aRules = [ + ["q0", "1", ["q0", "0", "R"]], + ["q0", "0", ["q1", "1", "L"]], + ["q1", "1", ["q1", "1", "R"]], + ["q1", "0", ["halt", "1", "N"]] +] + +# GUI Objects +winEdit = NULL +txtEdit = NULL + +app = new qApp { + win = new qWidget() { + setWindowTitle("Turing Machine - CalmoSoft") + resize(800, 650) + setStyleSheet("QWidget { background-color: #1a1a1a; color: white; font-family: Arial; }") + + lblTape = new qLabel(win) { + move(50, 30) resize(700, 120) setAlignment(132) + setStyleSheet("border: 3px solid #00ffcc; border-radius: 15px; background: #262626;") + setText(updateTapeView()) + } + + lblSpeed = new qLabel(win) { move(50, 160) setText("Speed (ms):") } + + sldSpeed = new qSlider(win) { + move(50, 180) resize(250, 30) setOrientation(1) + setRange(50, 2000) setValue(nSpeed) + setValueChangedEvent("updateSpeed()") + } + + timer = new qTimer(win) { setInterval(nSpeed) setTimeoutEvent("stepTuring()") } + + cmbRules = new qComboBox(win) { + move(50, 230) resize(700, 45) + # Item size and font increase via StyleSheet + setStyleSheet(" + QComboBox { + background-color: #333; color: #00ffcc; border: 1px solid #444; font-size: 16px; padding-left: 10px; + } + QComboBox QAbstractItemView { + background-color: #222; color: #00ffcc; selection-background-color: #444; font-size: 16px; + } + QComboBox QAbstractItemView::item { + min-height: 40px; + } + ") + } + fillCombo() + + btnStep = new qPushButton(win) { + move(50, 300) resize(170, 50) setText("STEP") + setStyleSheet("background-color: #00ffcc; color: black; font-weight: bold;") + setClickEvent("stepTuring()") + } + + btnAuto = new qPushButton(win) { + move(230, 300) resize(170, 50) setText("START / STOP") + setStyleSheet("background-color: #f1c40f; color: black; font-weight: bold;") + setClickEvent("toggleAuto()") + } + + btnEdit = new qPushButton(win) { + move(410, 300) resize(170, 50) setText("EDIT RULES") + setStyleSheet("background-color: #3498db; color: white; font-weight: bold;") + setClickEvent("openEditor()") + } + + btnReset = new qPushButton(win) { + move(590, 300) resize(160, 50) setText("RESET") + setStyleSheet("background-color: #e74c3c; color: white;") + setClickEvent("resetMachine()") + } + + lblStatus = new qLabel(win) { + move(50, 400) resize(700, 50) setAlignment(132) + setStyleSheet("font-size: 22px; color: #00ffcc; font-weight: bold;") + setText("State: " + cCurrentState) + } + win.show() + } + exec() +} + +func updateTapeView + cHTML = "

    " + for i = 1 to len(cTape) + char = cTape[i] + if i = nHeadPos + cHTML += " " + char + " " + else + cHTML += " " + char + " " + ok + next + return cHTML + "
    " + +func fillCombo + cmbRules.clear() + for r in aRules + cmbRules.addItem("IF "+r[1]+","+r[2]+" -> GO "+r[3][1]+", WRITE "+r[3][2]+", MOVE "+r[3][3], 0) + next + +func toggleAuto + if timer.isActive() timer.stop() else timer.start() ok + +func updateSpeed + nSpeed = sldSpeed.value() + timer.setInterval(nSpeed) + +func stepTuring + if cCurrentState = "halt" timer.stop() return ok + char = "" + cTape[nHeadPos] + found = 0 + for nIdx = 1 to len(aRules) + r = aRules[nIdx] + if r[1] = cCurrentState AND r[2] = char + found = 1 + cmbRules.setCurrentIndex(nIdx-1) + cCurrentState = r[3][1] + cTape[nHeadPos] = "" + r[3][2] + if r[3][3] = "R" nHeadPos++ elseif r[3][3] = "L" nHeadPos-- ok + exit + ok + next + # Infinite tape handling + if nHeadPos < 1 + cTape = "0" + cTape nHeadPos = 1 + elseif nHeadPos > len(cTape) + cTape = cTape + "0" + ok + + if found = 0 or cCurrentState = "halt" + cCurrentState = "halt" timer.stop() + lblStatus.setText("FINISHED: HALTED") + else + lblStatus.setText("State: " + cCurrentState + " | Position: " + nHeadPos) + ok + lblTape.setText(updateTapeView()) + +func openEditor + winEdit = new qWidget() { + setWindowTitle("Rule Editor") + resize(450, 450) + setStyleSheet("background-color: #222; color: white;") + txtEdit = new qTextEdit(winEdit) { + move(10, 10) resize(430, 340) + setStyleSheet("background-color: #333; color: white; font-family: monospace; font-size: 14px;") + cContent = "" + for r in aRules + cContent += r[1] + "," + r[2] + "," + r[3][1] + "," + r[3][2] + "," + r[3][3] + nl + next + setText(cContent) + } + btnSave = new qPushButton(winEdit) { + move(10, 370) resize(430, 50) setText("SAVE & APPLY") + setStyleSheet("background-color: #00ffcc; color: black; font-weight: bold;") + setClickEvent("saveRules()") + } + winEdit.show() + } + +func saveRules + cRaw = txtEdit.toPlainText() + aLines = split(cRaw, nl) + aNewRules = [] + for line in aLines + line = trim(line) + if line = "" loop ok + parts = split(line, ",") + if len(parts) < 5 loop ok + add(aNewRules, [ parts[1], parts[2], [parts[3], parts[4], parts[5]] ]) + next + aRules = aNewRules + fillCombo() + resetMachine() + winEdit.close() + +func resetMachine + cTape = "110100" nHeadPos = 1 cCurrentState = "q0" + timer.stop() + lblStatus.setText("State: q0") + lblTape.setText(updateTapeView()) diff --git a/Task/Unix-ls/Ada/unix-ls.adb b/Task/Unix-ls/Ada/unix-ls.adb new file mode 100644 index 0000000000..f9f341e76d --- /dev/null +++ b/Task/Unix-ls/Ada/unix-ls.adb @@ -0,0 +1,32 @@ +with Ada.Text_IO, Ada.Directories, Ada.Containers.Indefinite_Vectors; + +procedure Directory_List is + + use Ada.Directories, Ada.Text_IO; + Search: Search_Type; Found: Directory_Entry_Type; + package SV is new Ada.Containers.Indefinite_Vectors(Natural, String); + Result: SV.Vector; + package Sorting is new SV.Generic_Sorting; use Sorting; + function SName return String is (Simple_Name(Found)); + +begin + -- search directory and store it in Result, a vector of strings + Start_Search(Search, Directory => ".", Pattern =>""); + while More_Entries(Search) loop + Get_Next_Entry(Search, Found); + declare + Name: String := Simple_Name(Found); + begin + if Name(Name'First) /= '.' then + Result.Append(Name); + end if; -- ingnore filenames beginning with "." + end; + end loop; -- Result holds the entire directory in arbitrary order + + Sort(Result); -- Result holds the directory in proper order + + -- print Result + for I in Result.First_Index .. Result.Last_Index loop + Put_Line(Result.Element(I)); + end loop; +end Directory_List; diff --git a/Task/Unix-ls/Batch-File/unix-ls-1.bat b/Task/Unix-ls/Batch-File/unix-ls-1.bat new file mode 100644 index 0000000000..a73fb637b3 --- /dev/null +++ b/Task/Unix-ls/Batch-File/unix-ls-1.bat @@ -0,0 +1,4 @@ +@echo off +setlocal +pushd %1 +for %%a in (*) do @echo:%%a diff --git a/Task/Unix-ls/Batch-File/unix-ls-2.bat b/Task/Unix-ls/Batch-File/unix-ls-2.bat new file mode 100644 index 0000000000..142e3dd048 --- /dev/null +++ b/Task/Unix-ls/Batch-File/unix-ls-2.bat @@ -0,0 +1 @@ +for %a in (*) do @echo:%a diff --git a/Task/Unix-ls/Icon/unix-ls.icon b/Task/Unix-ls/Icon/unix-ls.icon new file mode 100644 index 0000000000..4cb3e50fab --- /dev/null +++ b/Task/Unix-ls/Icon/unix-ls.icon @@ -0,0 +1,4 @@ +procedure main() + every (a := [], put(a,!(f := open(".")))|close(f)) + every write(!sort(a)) +end diff --git a/Task/Unix-ls/PowerShell/unix-ls.ps1 b/Task/Unix-ls/PowerShell/unix-ls.ps1 new file mode 100644 index 0000000000..e3a521eebf --- /dev/null +++ b/Task/Unix-ls/PowerShell/unix-ls.ps1 @@ -0,0 +1,5 @@ +# Prints Name, Length, Mode, and LastWriteTime +Get-ChildItem | Sort-Object Name | Write-Output + +# Prints only the name of each file in the directory +Get-ChildItem | Sort-Object Name | ForEach-Object Name | Write-Output diff --git a/Task/Unix-ls/Unicon/unix-ls.unicon b/Task/Unix-ls/Unicon/unix-ls.unicon new file mode 100644 index 0000000000..578066f9c7 --- /dev/null +++ b/Task/Unix-ls/Unicon/unix-ls.unicon @@ -0,0 +1,3 @@ +procedure main() + every write(!sort([: !(f := open(".")) :])) | close(f) +end diff --git a/Task/Unprimeable-numbers/Fortran/unprimeable-numbers.f b/Task/Unprimeable-numbers/Fortran/unprimeable-numbers.f new file mode 100644 index 0000000000..0161f12684 --- /dev/null +++ b/Task/Unprimeable-numbers/Fortran/unprimeable-numbers.f @@ -0,0 +1,237 @@ +! Full Fortran program using an efficient sieve-based unprimeable number finder +! with packed bit array and digit changing, printing first 35, 600th, and lowest per digit unprimeables. + +module bitarray_mod + implicit none + private + public :: bit_array, bit_array_create, bit_array_destroy, bit_array_set, bit_array_get + + type :: bit_array + integer :: size ! number of bits + integer, allocatable :: array(:) ! integer array storing bits + end type bit_array + +contains + + function bit_array_create(size) result(b) + integer, intent(in) :: size + type(bit_array) :: b + integer :: nwords + + nwords = shiftr(size + 31, 5)! / 32 + allocate(b%array(nwords)) + b%array = 0 + b%size = size + end function bit_array_create + + subroutine bit_array_destroy(b) + type(bit_array), intent(inout) :: b + if (allocated(b%array)) deallocate(b%array) + b%size = 0 + end subroutine bit_array_destroy + + subroutine bit_array_set(b, index, value) + type(bit_array), intent(inout) :: b + integer, intent(in) :: index + logical, intent(in) :: value + integer :: word, bitpos + + word = shiftr(index, 5) + 1 + bitpos = iand(index, 31) + if (value) then + b%array(word) = ibset(b%array(word), bitpos) + else + b%array(word) = ibclr(b%array(word), bitpos) + end if + end subroutine bit_array_set + + logical function bit_array_get(b, index) + type(bit_array), intent(in) :: b + integer, intent(in) :: index + integer :: word, bitpos + + word = shiftr(index, 5) + 1 + bitpos = iand(index, 31) + bit_array_get = btest(b%array(word), bitpos) + end function bit_array_get + +end module bitarray_mod + +program unprimeable_numbers + use bitarray_mod + implicit none + integer, parameter :: limit = 10000000 + type(bit_array) :: sieve + integer :: n, i, count, found, digit + integer, dimension(0:9) :: lowest = 0 + character(len=20) :: outstr + + call sieve_create(sieve, limit) + + print *, "First 35 unprimeable numbers:" + count = 0 + found = 0 + n = 100 + do while ((found < 10 .or. count < 600) .and. n < limit) + if (unprimeable(sieve, n)) then + count = count + 1 + if (count <= 35) then + if (count > 1) write(*, '(A)', advance='no') ", " + call format_with_commas(n, outstr) + write(*, '(A)', advance='no') trim(outstr) + end if + if (count == 600) then + print * + call format_with_commas(n, outstr) + print *, "600th unprimeable number: ", trim(outstr) + end if + digit = mod(n, 10) + if (lowest(digit) == 0) then + lowest(digit) = n + found = found + 1 + end if + end if + n = n + 1 + end do + print * + print *, "Lowest unprimeable numbers ending in each digit:" + do i = 0, 9 + if (lowest(i) == 0) then + print "(A,I1,A)", "Digit ", i, ": none found" + else + call format_with_commas(lowest(i), outstr) + print "(A,I1,A,A)", "Digit ", i, ": ", trim(outstr) + end if + end do + + call sieve_destroy(sieve) + +contains + + subroutine sieve_create(s, lim) + type(bit_array), intent(out) :: s + integer, intent(in) :: lim + integer :: sqrtn, p, inc, q, idx + + s = bit_array_create(lim / 2) + sqrtn = int(sqrt(real(lim))) + do p = 3, sqrtn, 2 + idx = shiftr(p, 1) - 1 + if (.not.bit_array_get(s, idx)) then + inc = shiftl(p, 1) + q = p * p + do while (q <= lim) + call bit_array_set(s, shiftr(q, 1) - 1, .true.) + q = q + inc + end do + end if + end do + end subroutine sieve_create + + subroutine sieve_destroy(s) + type(bit_array), intent(inout) :: s + call bit_array_destroy(s) + end subroutine sieve_destroy + + logical function is_prime(s, num) + type(bit_array), intent(in) :: s + integer, intent(in) :: num + if (num == 2) then + is_prime = .true. + else if (num < 2 .or. iand(num, 1) == 0) then + is_prime = .false. + else + is_prime = .not.bit_array_get(s, shiftr(num, 1) - 1) + end if + end function is_prime + + function count_digits(n) result(d) + integer, intent(in) :: n + integer :: d + if (n <= 0) then + d = 1 + else + d = int(log10(real(n))) + 1 + end if + end function count_digits + + function change_digit(n, index, new_digit) result(res) + integer, intent(in) :: n ! Input integer (assumed non-negative) + integer, intent(in) :: index ! Zero-based index from the right (0 = least significant digit) + integer, intent(in) :: new_digit ! Digit to insert (should be 0–9) + integer :: res ! Resulting integer after digit replacement + integer :: pow10 ! 10^index (position multiplier) + integer :: old_digit ! Digit currently at the target position + + ! Guard against invalid index (e.g., negative) + if (index < 0) then + res = n + return + end if + + ! Compute 10^index to isolate the target digit + pow10 = 10**index + + ! Extract the digit currently at the target position + old_digit = mod(n / pow10, 10) + + ! Subtract the old digit's contribution and add the new digit's contribution + res = n - old_digit * pow10 + new_digit * pow10 + end function change_digit + + logical function unprimeable(s, n) + type(bit_array), intent(in) :: s + integer, intent(in) :: n + integer :: d, i, j, m + logical :: prime_found + + if (is_prime(s, n)) then + unprimeable = .false. + return + end if + + d = count_digits(n) + prime_found = .false. + do i = 0, d - 1 + do j = 0, 9 + m = change_digit(n, i, j) + if (m /= n .and. is_prime(s, m)) then + prime_found = .true. + exit + end if + end do + if (prime_found) exit + end do + unprimeable = .not.prime_found + end function unprimeable + + subroutine format_with_commas(n, s) + integer, intent(in) :: n + character(len=*), intent(out) :: s + character(len=20) :: t + integer :: len_t, i, j, comma_pos, len_s + + write(t, '(I0)') n + len_t = len_trim(t) + s = '' + len_s = 0 + comma_pos = 0 + do i = len_t, 1, -1 + len_s = len_s + 1 + s(len_s:len_s) = t(i:i) + comma_pos = comma_pos + 1 + if (mod(comma_pos, 3) == 0 .and. i > 1) then + len_s = len_s + 1 + s(len_s:len_s) = ',' + end if + end do + ! Reverse string s to get correct order + do i = 1, len_s / 2 + j = iachar(s(i:i)) + s(i:i) = s(len_s - i + 1:len_s - i + 1) + s(len_s - i + 1:len_s - i + 1) = char(j) + end do + s = adjustl(s(1:len_s)) + end subroutine format_with_commas + +end program unprimeable_numbers diff --git a/Task/Unprimeable-numbers/Uiua/unprimeable-numbers.uiua b/Task/Unprimeable-numbers/Uiua/unprimeable-numbers.uiua new file mode 100644 index 0000000000..7a2a667c48 --- /dev/null +++ b/Task/Unprimeable-numbers/Uiua/unprimeable-numbers.uiua @@ -0,0 +1,18 @@ +IsP ← ⨬(=⊣⊸°/×|0)⊸<₂ +# IsUnp ← ¬/↥IsP°⊥₁₀/⊂≡(≡(⍜⊡⋅)⊙⊙(⇡10)∩¤)⇡⊃⧻¤⊥₁₀ # Not needed. + +Lim ← 1210000 +Primes ← ▽=⊸≡(⊣⊸°/×)↘2⇡Lim +# Swap out each digit of the primes to eliminate non-Unprimeables. +Swaps ← °⊥₁₀/⊂≡(≡(⍜⊡⋅)⊙⊙(⇡10)∩¤)⇡⊃⧻¤⊥₁₀ + +Specials ← ♭≡([⊃(+₂|+₃|+₅|+₇)])˜ⁿ10↘2⇡7 # catch 1007 etc +# Swap out first digit of the specials to catch 1007 etc +Swaps₁ ← °⊥₁₀/⊂≡(≡(⍜⊡⋅)⊙⊙(⇡10)∩¤)[-1∘]⊃⧻¤⊥₁₀ + +˜▽°⊏↙Lim¬°⊚◴ ⊂/◇⊂≡⍚Swaps Primes /◇⊂≡⍚Swaps₁ Specials +# Larger numbers will have swaps bigger than our limit. +# Check these manually. +FirstGood ← ⊢▽¬⊸≡(/↥≡IsP Swaps₁)⬚190↙₁₀ # 190 is Unp, so neutral. + +⊃(&p⊕FirstGood⊸◿₁₀|&p⊡599|&p↙35) diff --git a/Task/Untouchable-numbers/Java/untouchable-numbers.java b/Task/Untouchable-numbers/Java/untouchable-numbers.java new file mode 100644 index 0000000000..fb04917437 --- /dev/null +++ b/Task/Untouchable-numbers/Java/untouchable-numbers.java @@ -0,0 +1,114 @@ +import java.util.*; +import java.io.*; + +public class UntouchableNumbers { + + static int sumDivisors(int n) { + int sum = 1; + int k = 2; + if (n % 2 == 0) { + k = 1; + } + for (int i = 1 + k; (long) i * i <= n; i += k) { + if (n % i == 0) { + sum += i; + int j = n / i; + if (j != i) { + sum += j; + } + } + } + return sum; + } + + // Marks as true the integers that appear as a proper-divisor sum of some i (6..n+1). + static boolean[] sieve(int n) { + int m = n + 1; // mirror the Go code's n++ trick + boolean[] s = new boolean[m + 1]; // all false by default + for (int i = 6; i <= m; i++) { + int sd = sumDivisors(i); + if (sd <= m) { + s[sd] = true; + } + } + return s; + } + + // True = composite, False = prime (like the Go version) + static boolean[] primeSieve(int limit) { + int lim = limit + 1; + boolean[] c = new boolean[lim]; + c[0] = true; + c[1] = true; + int p = 3; + while (true) { + long p2 = (long) p * p; + if (p2 >= lim) break; + for (int i = (int) p2; i < lim; i += 2 * p) { + c[i] = true; + } + while (true) { + p += 2; + if (p >= lim || !c[p]) break; + } + if (p >= lim) break; + } + return c; + } + + static String commatize(long n) { + boolean neg = n < 0; + String s = Long.toString(Math.abs(n)); + StringBuilder sb = new StringBuilder(); + int le = s.length(); + int first = le % 3; + if (first == 0 && le > 0) first = 3; + sb.append(s, 0, first); + for (int i = first; i < le; i += 3) { + if (sb.length() > 0) sb.append(','); + sb.append(s, i, i + 3); + } + return neg ? "-" + sb : sb.toString(); + } + + public static void main(String[] args) { + final int limit = 10_000; + + boolean[] composite = primeSieve(limit); + boolean[] sumsSeen = sieve(63 * limit); + + List untouchable = new ArrayList<>(); + untouchable.add(2); + untouchable.add(5); + + for (int n = 6; n <= limit; n += 2) { + if (!sumsSeen[n] && composite[n - 1] && composite[n - 3]) { + untouchable.add(n); + } + } + + System.out.println("List of untouchable numbers <= 2,000:"); + int count = 0; + for (int i = 0; i < untouchable.size() && untouchable.get(i) <= 2000; i++) { + System.out.printf("%6s", commatize(untouchable.get(i))); + if ((i + 1) % 10 == 0) System.out.println(); + count++; + } + System.out.printf("%n%n%7s untouchable numbers were found <= 2,000%n", commatize(count)); + + int p = 10; + count = 0; + for (int n : untouchable) { + count++; + if (n > p) { + System.out.printf("%7s untouchable numbers were found <= %9s%n", + commatize(count - 1), commatize(p)); + p *= 10; + if (p == limit) break; + } + } + + System.out.printf("%7s untouchable numbers were found <= %s%n", + commatize(untouchable.size()), commatize(limit)); + } +} diff --git a/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx b/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx index cb60dd0684..7a7c0904dd 100644 --- a/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx +++ b/Task/Untouchable-numbers/REXX/untouchable-numbers.rexx @@ -1,4 +1,4 @@ --- 24 Aug 2025 +-- 4 Mar 2026 include Setting say 'UNTOUCHABLE NUMBERS' @@ -16,7 +16,7 @@ call Timer exit GetPrimes: -procedure expose prim. flag. +procedure expose prim. flag. memo. arg yy say 'Get primes below' yy'...' say Primes(yy) 'found' @@ -24,7 +24,7 @@ say return MarkTouchables: -procedure expose touc. prim. flag. +procedure expose touc. prim. flag. memo. arg xx,yy say 'Mark touchable numbers below' xx'...' touc. = 0 @@ -80,4 +80,5 @@ end say return +-- Primes; Timer include Math diff --git a/Task/Update-a-configuration-file/C++/update-a-configuration-file.cpp b/Task/Update-a-configuration-file/C++/update-a-configuration-file.cpp new file mode 100644 index 0000000000..9b8cf85516 --- /dev/null +++ b/Task/Update-a-configuration-file/C++/update-a-configuration-file.cpp @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include + +class ConfigData { +public: + std::string favourite_fruit; + bool needs_peeling; + bool seeds_removed; + uint32_t number_bananas; + uint32_t number_strawberries; +}; + +std::string to_upper_case(const std::string& text) { + std::string result = text; + std::transform(result.begin(), result.end(), result.begin(), + [](const char& ch) { return std::toupper(ch); }); + return result; +} + +void read_config_file(const std::string& read_file, const ConfigData& data) { + std::ifstream read_stream; + read_stream.open(read_file); + const std::string write_file = "../temp_config.txt"; + std::ofstream write_stream; + write_stream.open(write_file); + if ( ! read_stream.is_open() || ! write_stream.is_open() ) { + std::cout << "Unable to open files" << std::endl; + } + + bool done_fruit = false; + bool done_peeling = false; + bool done_seeds = false; + bool done_bananas = false; + bool done_strawberries = false; + std::string line; + while ( std::getline(read_stream, line) ) { + if ( line.empty() || line[0] == '#' ) { + write_stream << line << "\n"; + continue; + } + + const std::string words = ( line.substr(0, 2) == "; " ) ? + to_upper_case(line.substr(2)) : to_upper_case(line); + + if ( words.empty() ) { continue; } + if ( words.substr(0, 14) == "FAVOURITEFRUIT" ) { + if ( done_fruit ) { continue; } + done_fruit = true; + write_stream << "FAVOURITEFRUIT " << data.favourite_fruit << "\n"; + } else if ( words.substr(0, 12) == "NEEDSPEELING" ) { + if ( done_peeling ) { continue; } + done_peeling = true; + if ( data.needs_peeling ) { + write_stream << "NEEDSPEELING" << "\n"; + } else { + write_stream << "; NEEDSPEELING" << "\n"; + } + } else if ( words.substr(0, 12) == "SEEDSREMOVED" ) { + if ( done_seeds ) { continue; } + done_seeds = true; + if ( data.seeds_removed ) { + write_stream << "SEEDSREMOVED" << "\n"; + } else { + write_stream << "; SEEDSREMOVED" << "\n"; + } + } else if( words.substr(0, 15) == "NUMBEROFBANANAS" ) { + if ( done_bananas ) { continue; } + done_bananas = true; + write_stream << "NUMBEROFBANANAS " << data.number_bananas << "\n"; + } else if( words.substr(0, 20) == "NUMBEROFSTRAWBERRIES" ) { + if ( done_strawberries ) { continue; } + done_strawberries = true; + write_stream << "NUMBEROFSTRAWBERRIES " << data.number_strawberries << "\n"; + } + } + + // Insert statements if they were absent from the original file "config.txt" + if ( ! done_fruit ) { + write_stream << "FAVOURITEFRUIT " + data.favourite_fruit << "\n"; + } + + if ( ! done_peeling ) { + if ( data.needs_peeling ) { + write_stream << "NEEDSPEELING" << "\n"; + } else { + write_stream << "; NEEDSPEELING" << "\n"; + } + } + + if ( ! done_seeds ) { + if ( data.seeds_removed ) { + write_stream << "SEEDSREMOVED" << "\n"; + } else { + write_stream << "; SEEDSREMOVED" << "\n"; + } + } + + if ( ! done_bananas ) { + write_stream << "NUMBEROFBANANAS "<< data.number_bananas << "\n"; + } + + if ( ! done_strawberries ) { + write_stream << "NUMBEROFSTRAWBERRIES " << data.number_strawberries << "\n"; + } + + read_stream.close(); + write_stream.close(); + + std::filesystem::remove(read_file); + std::filesystem::rename(write_file, read_file); +} + +int main() { + const std::string read_file = "../config.txt"; + ConfigData configData("banana", false, true, 1024, 62000); + read_config_file(read_file, configData); +} diff --git a/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.ps1 b/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.ps1 new file mode 100644 index 0000000000..101d67c157 --- /dev/null +++ b/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-1.ps1 @@ -0,0 +1,107 @@ +function Update-ConfigurationFile +{ + [CmdletBinding()] + Param + ( + [Parameter(Mandatory=$false, + Position=0)] + [ValidateScript({Test-Path $_})] + [string] + $Path = ".\config.txt", + + [Parameter(Mandatory=$false)] + [string] + $FavouriteFruit, + + [Parameter(Mandatory=$false)] + [int] + $NumberOfBananas, + + [Parameter(Mandatory=$false)] + [int] + $NumberOfStrawberries, + + [Parameter(Mandatory=$false)] + [ValidateSet("On", "Off")] + [string] + $NeedsPeeling, + + [Parameter(Mandatory=$false)] + [ValidateSet("On", "Off")] + [string] + $SeedsRemoved + ) + + [string[]]$lines = Get-Content $Path + + Clear-Content $Path + + if (-not ($lines | Select-String -Pattern "^\s*NumberOfStrawberries" -Quiet)) + { + "", "# How many strawberries we have", "NumberOfStrawberries 0" | ForEach-Object {$lines += $_} + } + + foreach ($line in $lines) + { + $line = $line -replace "^\s*","" ## Strip leading whitespace + + if ($line -match "[;].*\s*") {continue} ## Strip semicolons + + switch -Regex ($line) + { + "(^$)|(^#\s.*)" ## Blank line or comment + { + $line = $line + } + "^FavouriteFruit\s*.*" ## Parameter FavouriteFruit + { + if ($FavouriteFruit) + { + $line = "FAVOURITEFRUIT $FavouriteFruit" + } + } + "^NumberOfBananas\s*.*" ## Parameter NumberOfBananas + { + if ($NumberOfBananas) + { + $line = "NUMBEROFBANANAS $NumberOfBananas" + } + } + "^NumberOfStrawberries\s*.*" ## Parameter NumberOfStrawberries + { + if ($NumberOfStrawberries) + { + $line = "NUMBEROFSTRAWBERRIES $NumberOfStrawberries" + } + } + ".*NeedsPeeling\s*.*" ## Parameter NeedsPeeling + { + if ($NeedsPeeling -eq "On") + { + $line = "NEEDSPEELING" + } + elseif ($NeedsPeeling -eq "Off") + { + $line = "; NEEDSPEELING" + } + } + ".*SeedsRemoved\s*.*" ## Parameter SeedsRemoved + { + if ($SeedsRemoved -eq "On") + { + $line = "SEEDSREMOVED" + } + elseif ($SeedsRemoved -eq "Off") + { + $line = "; SEEDSREMOVED" + } + } + Default ## Whatever... + { + $line = $line + } + } + + Add-Content $Path -Value $line -Force + } +} diff --git a/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.ps1 b/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.ps1 new file mode 100644 index 0000000000..417ba7c22b --- /dev/null +++ b/Task/Update-a-configuration-file/PowerShell/update-a-configuration-file-2.ps1 @@ -0,0 +1,3 @@ +Update-ConfigurationFile -NumberOfStrawberries 62000 -NumberOfBananas 1024 -SeedsRemoved On -NeedsPeeling Off + +Invoke-Item -Path ".\config.txt" diff --git a/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vbs b/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vbs new file mode 100644 index 0000000000..653bd3fd27 --- /dev/null +++ b/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vbs @@ -0,0 +1,57 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +'Paramater lookups +Set objParamLookup = CreateObject("Scripting.Dictionary") +With objParamLookup + .Add "FAVOURITEFRUIT", "banana" + .Add "NEEDSPEELING", "" + .Add "SEEDSREMOVED", "" + .Add "NUMBEROFBANANAS", "1024" + .Add "NUMBEROFSTRAWBERRIES", "62000" +End With + +'Open the config file for reading. +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\IN_config.txt",1) +'Initialize output. +Output = "" +Isnumberofstrawberries = False +With objInFile + Do Until .AtEndOfStream + line = .ReadLine + If Left(line,1) = "#" Or line = "" Then + Output = Output & line & vbCrLf + ElseIf Left(line,1) = " " And InStr(line,"#") Then + Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf + ElseIf Replace(Replace(line,";","")," ","") <> "" Then + If InStr(1,line,"FAVOURITEFRUIT",1) Then + Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf + ElseIf InStr(1,line,"NEEDSPEELING",1) Then + Output = Output & "; " & "NEEDSPEELING" & vbCrLf + ElseIf InStr(1,line,"SEEDSREMOVED",1) Then + Output = Output & "SEEDSREMOVED" & vbCrLf + ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then + Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf + ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then + Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf + Isnumberofstrawberries = True + End If + End If + Loop + If Isnumberofstrawberries = False Then + Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf + Isnumberofstrawberries = True + End If + .Close +End With + +'Create a new config file. +Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\OUT_config.txt",2,True) +With objOutFile + .Write Output + .Close +End With + +Set objFSO = Nothing +Set objParamLookup = Nothing diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.adb b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.adb new file mode 100644 index 0000000000..b8e500de2a --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-1.adb @@ -0,0 +1,8 @@ +with Interfaces.C; use Interfaces.C; +with Interfaces.C.Strings; use Interfaces.C.Strings; + +package Exported is + function Query (Data : chars_ptr; Size : access size_t) + return int; + pragma Export (C, Query, "Query"); +end Exported; diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.adb b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.adb new file mode 100644 index 0000000000..6f6dda465e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-2.adb @@ -0,0 +1,14 @@ +package body Exported is + function Query (Data : chars_ptr; Size : access size_t) + return int is + Result : char_array := "Here am I"; + begin + if Size.all < Result'Length then + return 0; + else + Update (Data, 0, Result); + Size.all := Result'Length; + return 1; + end if; + end Query; +end Exported; diff --git a/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.adb b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.adb new file mode 100644 index 0000000000..1e55d5dd28 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Ada/use-another-language-to-call-a-function-3.adb @@ -0,0 +1,4 @@ +gcc -c main.c +gnatmake -c exported.adb +gnatbind -n exported.ali +gnatlink exported.ali main.o -o main diff --git a/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cob b/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cob new file mode 100644 index 0000000000..907784f8cc --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/COBOL/use-another-language-to-call-a-function.cob @@ -0,0 +1,33 @@ + identification division. + program-id. Query. + + environment division. + configuration section. + special-names. + call-convention 0 is extern. + + repository. + function all intrinsic. + + data division. + working-storage section. + 01 query-result. + 05 filler value "Here I am". + + linkage section. + 01 data-reference. + 05 data-buffer pic x occurs 0 to 8192 times + depending on length-reference. + 01 length-reference usage binary-long. + + procedure division extern using data-reference length-reference. + + if length(query-result) less than or equal to length-reference + and length-reference less than 8193 then + move query-result to data-reference + move length(query-result) to length-reference + move 1 to return-code + end-if + + goback. + end program Query. diff --git a/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.hx b/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.hx new file mode 100644 index 0000000000..a135ea7374 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Haxe/use-another-language-to-call-a-function.hx @@ -0,0 +1 @@ +untyped __call__("functionName", args); diff --git a/Task/User-input-Graphical/Ada/user-input-graphical.adb b/Task/User-input-Graphical/Ada/user-input-graphical.adb new file mode 100644 index 0000000000..ecbd1f8290 --- /dev/null +++ b/Task/User-input-Graphical/Ada/user-input-graphical.adb @@ -0,0 +1,80 @@ +with Gtk.Button; use Gtk.Button; +with Gtk.GEntry; use Gtk.GEntry; +with Gtk.Label; use Gtk.Label; +with Gtk.Window; use Gtk.Window; +with Gtk.Widget; use Gtk.Widget; +with Gtk.Table; use Gtk.Table; + +with Gtk.Handlers; +with Gtk.Main; + +procedure Graphic_Input is + Window : Gtk_Window; + Grid : Gtk_Tnetable; + Label : Gtk_Label; + Message : Gtk_Label; + Edit : Gtk_GEntry; + Button : Gtk_Button; + + package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); + package Return_Handlers is + new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean); + + function Delete_Event (Widget : access Gtk_Widget_Record'Class) + return Boolean is + begin + return False; + end Delete_Event; + + procedure Destroy (Widget : access Gtk_Widget_Record'Class) is + begin + Gtk.Main.Main_Quit; + end Destroy; + + procedure Clicked (Widget : access Gtk_Widget_Record'Class) is + begin + if Get_Text (Label) = "Enter integer:" then + Set_Text (Message, "Entered:" & Integer'Image (Integer'Value (Get_Text (Edit)))); + Set_Sensitive (Button, False); + else + Set_Text (Message, "Entered:" & Get_Text (Edit)); + Set_Text (Label, "Enter integer:"); + end if; + exception + when Constraint_Error => + Set_Text (Message, "Error integer input"); + end Clicked; + +begin + Gtk.Main.Init; + Gtk.Window.Gtk_New (Window); + Gtk_New (Grid, 2, 3, False); + Add (Window, Grid); + Gtk_New (Label, "Enter string:"); + Attach (Grid, Label, 0, 1, 0, 1); + Gtk_New (Edit); + Attach (Grid, Edit, 1, 2, 0, 1); + Gtk_New (Button, "OK"); + Attach (Grid, Button, 2, 3, 0, 1); + Gtk_New (Message); + Attach (Grid, Message, 0, 3, 1, 2); + Return_Handlers.Connect + ( Window, + "delete_event", + Return_Handlers.To_Marshaller (Delete_Event'Access) + ); + Handlers.Connect + ( Window, + "destroy", + Handlers.To_Marshaller (Destroy'Access) + ); + Handlers.Connect + ( Button, + "clicked", + Handlers.To_Marshaller (Clicked'Access) + ); + Show_All (Grid); + Show (Window); + + Gtk.Main.Main; +end Graphic_Input; diff --git a/Task/User-input-Graphical/PowerShell/user-input-graphical.ps1 b/Task/User-input-Graphical/PowerShell/user-input-graphical.ps1 new file mode 100644 index 0000000000..d575c87c1a --- /dev/null +++ b/Task/User-input-Graphical/PowerShell/user-input-graphical.ps1 @@ -0,0 +1,98 @@ +#region Define the Windows Form +[Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") + +$Form1 = New-Object System.Windows.Forms.Form +$label1 = New-Object System.Windows.Forms.Label +$label2 = New-Object System.Windows.Forms.Label +$txtInputText = New-Object System.Windows.Forms.TextBox +$txtInputNumber = New-Object System.Windows.Forms.TextBox +$btnAccept = New-Object System.Windows.Forms.Button +$label3 = New-Object System.Windows.Forms.Label +$btnCancel = New-Object System.Windows.Forms.Button +$SuspendLayout +# +# label1 +# +$label1.AutoSize = $true +$label1.Location = New-Object System.Drawing.Point(23, 36) +$label1.Name = "label1" +$label1.Size = New-Object System.Drawing.Size(34, 13) +$label1.TabIndex = 0 +$label1.Text = "String" +# +# label2 +# +$label2.AutoSize = $true +$label2.Location = New-Object System.Drawing.Point(13, 62) +$label2.Name = "label2" +$label2.Size = New-Object System.Drawing.Size(44, 13) +$label2.TabIndex = 1 +$label2.Text = "Number" +# +# txtInputText +# +$txtInputText.Location = New-Object System.Drawing.Point(63, 33) +$txtInputText.Name = "txtInputText" +$txtInputText.Size = New-Object System.Drawing.Size(100, 20) +$txtInputText.TabIndex = 0 +# +# txtInputNumber +# +$txtInputNumber.Location = New-Object System.Drawing.Point(63, 59) +$txtInputNumber.Name = "txtInputNumber" +$txtInputNumber.Size = New-Object System.Drawing.Size(100, 20) +$txtInputNumber.TabIndex = 1 +$txtInputNumber.Text = "75000" +# +# btnAccept +# +$btnAccept.DialogResult = [System.Windows.Forms.DialogResult]::OK +$btnAccept.Location = New-Object System.Drawing.Point(16, 94) +$btnAccept.Name = "btnAccept" +$btnAccept.Size = New-Object System.Drawing.Size(75, 23) +$btnAccept.TabIndex = 2 +$btnAccept.Text = "Accept" +$btnAccept.UseVisualStyleBackColor = $true +$btnAccept.add_Click({$rc="Accept"; $Form1.Close()}) +# +# label3 +# +$label3.AutoSize = $true +$label3.Location = New-Object System.Drawing.Point(13, 9) +$label3.Name = "label3" +$label3.Size = New-Object System.Drawing.Size(173, 13) +$label3.TabIndex = 5 +$label3.Text = "Please input a string and a number:" +# +# btnCancel +# +$btnCancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel +$btnCancel.Location = New-Object System.Drawing.Point(97, 94) +$btnCancel.Name = "btnCancel" +$btnCancel.Size = New-Object System.Drawing.Size(75, 23) +$btnCancel.TabIndex = 3 +$btnCancel.Text = "Cancel" +$btnCancel.UseVisualStyleBackColor = $true +# +# Form1 +# +$Form1.AcceptButton = $btnAccept +$Form1.CancelButton = $btnCancel +$Form1.ClientSize = New-Object System.Drawing.Size(196, 129) +$Form1.ControlBox = $false +$Form1.Controls.Add($btnCancel) +$Form1.Controls.Add($label3) +$Form1.Controls.Add($btnAccept) +$Form1.Controls.Add($txtInputNumber) +$Form1.Controls.Add($txtInputText) +$Form1.Controls.Add($label2) +$Form1.Controls.Add($label1) +$Form1.Name = "Form1" +$Form1.Text = "RosettaCode" + +#endregion Define the Windows Form + +### Show the input form +$f = $Form1.ShowDialog() +if ( $f -eq [System.Windows.Forms.DialogResult]::Cancel ) { "User selected Cancel" } +else { "User entered `"{0}`" for the text and {1} for the number" -f $txtInputText.Text, $txtInputNumber.Text } diff --git a/Task/User-input-Graphical/Rebol/user-input-graphical.rebol b/Task/User-input-Graphical/Rebol/user-input-graphical.rebol new file mode 100644 index 0000000000..9779270024 --- /dev/null +++ b/Task/User-input-Graphical/Rebol/user-input-graphical.rebol @@ -0,0 +1,58 @@ +Rebol [ + Title: "Graphical User Input" + URL: http://rosettacode.org/wiki/User_Input_-_graphical +] + +; Simple GUI's can be defined with 'layout', a special purpose dialect +; for specifying interfaces. In this case, I describe a gradient +; background with an instruction label, followed by the input fields +; and a validation button. It's possible to check dynamically as the +; user types but I wanted to keep this example as clear as possible. + +view layout [ + +; You can define new widget styles. Here I create a padded label style +; (so that everything will line up) and a simple indicator light to +; show if there's a problem with an input field. + + style label vtext 60 "unlabeled" + style indicator box maroon 24x24 + + backdrop effect [gradient 0x1 black coal] + + vtext "Please enter a string, and the number 75000:" + +; By default, GUI widgets are arranged top down. The 'across' word +; starts stacking widgets from left to right. 'return' starts a new +; line -- just like on a typewriter! + + across + +; Notice I'm using my new label and indicator styles here. Widgets +; that I need to access later (the input field and the indicator) are +; assigned to variables. + + label "string:" s: field 240 si: indicator return + + label "number:" n: field 50 ni: indicator return + + pad 66 + button "validate" [ + +; The user may have entered bogus values, so I reset the indicators: + + si/color: ni/color: maroon + +; Now I check to see if the values are correct. For the string, I just +; care that there is one. For the integer, I make sure that it +; evaluates to an integer and that it's value is 75000. Because I've +; already set the indicator colour, I don't care the integer +; conversion raises an error or not, so I ignore it if anything goes +; wrong. + + if 0 < length? get-face s [si/color: green] + error? try [if 75000 = to-integer get-face n [ni/color: green]] + + show [si ni] ; Repainting multiple objects at once. + ] +] diff --git a/Task/User-input-Graphical/VBScript/user-input-graphical.vbs b/Task/User-input-Graphical/VBScript/user-input-graphical.vbs new file mode 100644 index 0000000000..fa8d10b3d0 --- /dev/null +++ b/Task/User-input-Graphical/VBScript/user-input-graphical.vbs @@ -0,0 +1,8 @@ +strUserIn = InputBox("Enter Data") +Wscript.Echo strUserIn +On Error Resume Next +If CLng(InputBox("Input integer 75000")) <> 75000 Then + WScript.Echo "Input is not 75000" +Else + WScript.Echo "Input is 75000" +End If diff --git a/Task/User-input-Text/Ada/user-input-text-1.adb b/Task/User-input-Text/Ada/user-input-text-1.adb new file mode 100644 index 0000000000..fa98fc4e5f --- /dev/null +++ b/Task/User-input-Text/Ada/user-input-text-1.adb @@ -0,0 +1,14 @@ +function Get_String return String is + Line : String (1 .. 1_000); + Last : Natural; +begin + Get_Line (Line, Last); + return Line (1 .. Last); +end Get_String; + +function Get_Integer return Integer is + S : constant String := Get_String; +begin + return Integer'Value (S); + -- may raise exception Constraint_Error if value entered is not a well-formed integer +end Get_Integer; diff --git a/Task/User-input-Text/Ada/user-input-text-2.adb b/Task/User-input-Text/Ada/user-input-text-2.adb new file mode 100644 index 0000000000..18a90e3a3e --- /dev/null +++ b/Task/User-input-Text/Ada/user-input-text-2.adb @@ -0,0 +1,2 @@ +My_String : String := Get_String; +My_Integer : Integer := Get_Integer; diff --git a/Task/User-input-Text/Ada/user-input-text-3.adb b/Task/User-input-Text/Ada/user-input-text-3.adb new file mode 100644 index 0000000000..5acd579b0a --- /dev/null +++ b/Task/User-input-Text/Ada/user-input-text-3.adb @@ -0,0 +1,15 @@ +with Ada.Text_IO, Ada.Integer_Text_IO; + +procedure User_Input is + I : Integer; +begin + Ada.Text_IO.Put ("Enter a string: "); + declare + S : String := Ada.Text_IO.Get_Line; + begin + Ada.Text_IO.Put_Line (S); + end; + Ada.Text_IO.Put ("Enter an integer: "); + Ada.Integer_Text_IO.Get(I); + Ada.Text_IO.Put_Line (Integer'Image(I)); +end User_Input; diff --git a/Task/User-input-Text/Ada/user-input-text-4.adb b/Task/User-input-Text/Ada/user-input-text-4.adb new file mode 100644 index 0000000000..608186c7a5 --- /dev/null +++ b/Task/User-input-Text/Ada/user-input-text-4.adb @@ -0,0 +1,18 @@ +with + Ada.Text_IO, + Ada.Integer_Text_IO, + Ada.Strings.Unbounded, + Ada.Text_IO.Unbounded_IO; + +procedure User_Input2 is + S : Ada.Strings.Unbounded.Unbounded_String; + I : Integer; +begin + Ada.Text_IO.Put("Enter a string: "); + S := Ada.Strings.Unbounded.To_Unbounded_String(Ada.Text_IO.Get_Line); + Ada.Text_IO.Put_Line(Ada.Strings.Unbounded.To_String(S)); + Ada.Text_IO.Unbounded_IO.Put_Line(S); + Ada.Text_IO.Put("Enter an integer: "); + Ada.Integer_Text_IO.Get(I); + Ada.Text_IO.Put_Line(Integer'Image(I)); +end User_Input2; diff --git a/Task/User-input-Text/COBOL/user-input-text.cob b/Task/User-input-Text/COBOL/user-input-text.cob new file mode 100644 index 0000000000..1a192739d6 --- /dev/null +++ b/Task/User-input-Text/COBOL/user-input-text.cob @@ -0,0 +1,17 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Get-Input. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Input-String PIC X(30). + 01 Input-Int PIC 9(5). + + PROCEDURE DIVISION. + DISPLAY "Enter a string:" + ACCEPT Input-String + + DISPLAY "Enter a number:" + ACCEPT Input-Int + + GOBACK + . diff --git a/Task/User-input-Text/Euphoria/user-input-text.eu b/Task/User-input-Text/Euphoria/user-input-text.eu new file mode 100644 index 0000000000..4cd7988cd3 --- /dev/null +++ b/Task/User-input-Text/Euphoria/user-input-text.eu @@ -0,0 +1,9 @@ +include get.e + +sequence s +atom n + +s = prompt_string("Enter a string:") +puts(1, s & '\n') +n = prompt_number("Enter a number:",{}) +printf(1, "%d", n) diff --git a/Task/User-input-Text/PowerShell/user-input-text.ps1 b/Task/User-input-Text/PowerShell/user-input-text.ps1 new file mode 100644 index 0000000000..9d904a3244 --- /dev/null +++ b/Task/User-input-Text/PowerShell/user-input-text.ps1 @@ -0,0 +1,2 @@ +$string = Read-Host "Input a string" +[int]$number = Read-Host "Input a number" diff --git a/Task/User-input-Text/Rebol/user-input-text.rebol b/Task/User-input-Text/Rebol/user-input-text.rebol new file mode 100644 index 0000000000..d5af91e2c7 --- /dev/null +++ b/Task/User-input-Text/Rebol/user-input-text.rebol @@ -0,0 +1,27 @@ +Rebol [ + Title: "Textual User Input" + URL: http://rosettacode.org/wiki/User_Input_-_text +] + +s: n: "" + +; Because I have several things to check for, I've made a function to +; handle it. Note the question mark in the function name, this convention +; is often used in Forth to indicate test of some sort. + +valid?: func [s n][ + error? try [n: to-integer n] ; Ignore error if conversion fails. + all [0 < length? s 75000 = n]] + +; I don't want to give up until I've gotten something useful, so I +; loop until the user enters valid data. + +while [not valid? s n][ + print "Please enter a string, and the number 75000:" + s: ask "string: " + n: ask "number: " +] + +; It always pays to be polite... + +print rejoin [ "Thank you. Your string was '" s "'."] diff --git a/Task/User-input-Text/Rye/user-input-text.rye b/Task/User-input-Text/Rye/user-input-text.rye new file mode 100644 index 0000000000..f71190388a --- /dev/null +++ b/Task/User-input-Text/Rye/user-input-text.rye @@ -0,0 +1,2 @@ +num: integer input "Number " +str: input "String " diff --git a/Task/Validate-International-Securities-Identification-Number/ALGOL-W/validate-international-securities-identification-number.alg b/Task/Validate-International-Securities-Identification-Number/ALGOL-W/validate-international-securities-identification-number.alg index 56617b628e..2f4a612bab 100644 --- a/Task/Validate-International-Securities-Identification-Number/ALGOL-W/validate-international-securities-identification-number.alg +++ b/Task/Validate-International-Securities-Identification-Number/ALGOL-W/validate-international-securities-identification-number.alg @@ -66,10 +66,10 @@ begin end testIsin ; testIsIsin( "US0378331005", true ); - testIsIsin( "US0373831005", false ); + testIsIsin( "US0373831005", false ); testIsIsin( "U50378331005", false ); testIsIsin( "US03378331005", false ); - testIsIsin( "AU0000XVGZA3", true ); - testIsIsin( "AU0000VXGZA3", true ); - testIsIsin( "FR0000988040", true ); + testIsIsin( "AU0000XVGZA3", true ); + testIsIsin( "AU0000VXGZA3", true ); + testIsIsin( "FR0000988040", true ); end. diff --git a/Task/Validate-International-Securities-Identification-Number/Ada/validate-international-securities-identification-number.adb b/Task/Validate-International-Securities-Identification-Number/Ada/validate-international-securities-identification-number.adb new file mode 100644 index 0000000000..56d8831d33 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/Ada/validate-international-securities-identification-number.adb @@ -0,0 +1,74 @@ +procedure ISIN is + -- Luhn_Test copied from other Task + function Luhn_Test (Number: String) return Boolean is + Sum : Natural := 0; + Odd : Boolean := True; + Digit: Natural range 0 .. 9; + begin + for p in reverse Number'Range loop + Digit := Integer'Value (Number (p..p)); + if Odd then + Sum := Sum + Digit; + else + Sum := Sum + (Digit*2 mod 10) + (Digit / 5); + end if; + Odd := not Odd; + end loop; + return (Sum mod 10) = 0; + end Luhn_Test; + + subtype Decimal is Character range '0' .. '9'; + subtype Letter is Character range 'A' .. 'Z'; + subtype ISIN_Type is String(1..12); + + -- converts a string of decimals and letters into a string of decimals + function To_Digits(S: String) return String is + -- Character'Pos('A')-Offset=10, Character'Pos('B')-Offset=11, ... + Offset: constant Integer := Character'Pos('A')-10; + + Invalid_Character: exception; + begin + if S = "" then + return ""; + elsif S(S'First) = ' ' then -- skip blanks + return To_Digits(S(S'First+1 .. S'Last)); + elsif S(S'First) in Decimal then + return S(S'First) & To_Digits(S(S'First+1 .. S'Last)); + elsif S(S'First) in Letter then + return To_Digits(Integer'Image(Character'Pos(S(S'First))-Offset)) + & To_Digits(S(S'First+1 .. S'Last)); + else + raise Invalid_Character; + end if; + end To_Digits; + + function Is_Valid_ISIN(S: ISIN_Type) return Boolean is + Number : String := To_Digits(S); + begin + return S(S'First) in Letter and + S(S'First+1) in Letter and + S(S'Last) in Decimal and + Luhn_Test(Number); + end Is_Valid_ISIN; + + Test_Cases : constant Array(1..6) of ISIN_Type := + ("US0378331005", + "US0373831005", + "U50378331005", + -- excluded by type with fixed length + -- "US03378331005", + "AU0000XVGZA3", + "AU0000VXGZA3", + "FR0000988040"); +begin + for I in Test_Cases'Range loop + Ada.Text_IO.Put_Line(Test_Cases(I) & ":" & + Boolean'Image(Is_Valid_ISIN(Test_Cases(I)))); + end loop; + -- using wrong length will result in an exception: + Ada.Text_IO.Put("US03378331005:"); + Ada.Text_IO.Put_Line(Boolean'Image(Is_Valid_Isin("US03378331005"))); +exception + when others => + Ada.Text_IO.Put_Line("Exception occured"); +end ISIN; diff --git a/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic b/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic index d3fdd3f879..8d69e2fbcc 100644 --- a/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic +++ b/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic @@ -4,51 +4,51 @@ dim test_set$(7) test_set$ = {"US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"} for i = 1 to test_set$[?] - test_str$ = "" - l = length(test_set$[i]) - if l <> 12 then - print test_set$[i]; " Invalid, length <> 12 char." - continue for - end if - if asc(mid(test_set$[i], 1, 1)) < asc("A") or asc(mid(test_set$[i], 2, 1)) < asc("A") then - print test_set$[i]; " Invalid, number needs to start with 2 characters" - continue for - end if - for n = 1 to l - x = asc(mid(test_set$[i], n, 1)) - asc("0") - if x > 9 then x -= 7 - if x < 10 then - test_str$ += string(x) - else # two digest number - test_str$ += string(x \ 10) + string(x mod 10) - end if - next - print test_set$[i]; " "; - if luhntest(test_str$) = 1 then - print "Invalid, checksum error" - else - print "Valid" - end if + test_str$ = "" + l = length(test_set$[i]) + if l <> 12 then + print test_set$[i]; " Invalid, length <> 12 char." + continue for + end if + if asc(mid(test_set$[i], 1, 1)) < asc("A") or asc(mid(test_set$[i], 2, 1)) < asc("A") then + print test_set$[i]; " Invalid, number needs to start with 2 characters" + continue for + end if + for n = 1 to l + x = asc(mid(test_set$[i], n, 1)) - asc("0") + if x > 9 then x -= 7 + if x < 10 then + test_str$ += string(x) + else # two digest number + test_str$ += string(x \ 10) + string(x mod 10) + end if + next + print test_set$[i]; " "; + if luhntest(test_str$) = 1 then + print "Invalid, checksum error" + else + print "Valid" + end if next end function luhntest(cardnr$) - cardnr$ = trim(cardnr$) # remove spaces - l = length(cardnr$) - s1 = 0 - s2 = 0 + cardnr$ = trim(cardnr$) # remove spaces + l = length(cardnr$) + s1 = 0 + s2 = 0 - # sum odd numbers - for i = 1 to l step 2 - s1 += fromradix(asc(mid(cardnr$, i, 1)), 10) - next - # sum even numbers - for i = 2 to l step 2 - j = fromradix(asc(mid(cardnr$, i, 1)), 10) - j *= 2 - if j > 9 then j = (j mod 10) + 1 - s2 += j - next + # sum odd numbers + for i = 1 to l step 2 + s1 += fromradix(asc(mid(cardnr$, i, 1)), 10) + next + # sum even numbers + for i = 2 to l step 2 + j = fromradix(asc(mid(cardnr$, i, 1)), 10) + j *= 2 + if j > 9 then j = (j mod 10) + 1 + s2 += j + next - return (s1 + s2) mod 10 = 0 + return (s1 + s2) mod 10 = 0 end function diff --git a/Task/Validate-International-Securities-Identification-Number/Bruijn/validate-international-securities-identification-number.bruijn b/Task/Validate-International-Securities-Identification-Number/Bruijn/validate-international-securities-identification-number.bruijn index 7608ed5181..94f42e10ce 100644 --- a/Task/Validate-International-Securities-Identification-Number/Bruijn/validate-international-securities-identification-number.bruijn +++ b/Task/Validate-International-Securities-Identification-Number/Bruijn/validate-international-securities-identification-number.bruijn @@ -9,14 +9,14 @@ # verifies ISIN format format? [len ⋀? country ⋀? security ⋀? checksum] - len (length 0) =? (+12) - country all? uppercase? (take (+2) 0) - security all? (φ or? uppercase? numeric?) (take (+9) (drop (+2) 0)) - checksum numeric? _0 + len (length 0) =? (+12) + country all? uppercase? (take (+2) 0) + security all? (φ or? uppercase? numeric?) (take (+9) (drop (+2) 0)) + checksum numeric? _0 # performs luhn test checksum? (map (from-base36 → number→string)) → concat → string→number → luhn - from-base36 binary→ternary → [(0 - (0 ≥? (+65) ((+65) - (+10)) (+48)))] + from-base36 binary→ternary → [(0 - (0 ≥? (+65) ((+65) - (+10)) (+48)))] # performs format and checksum test validate φ and? format? checksum? diff --git a/Task/Validate-International-Securities-Identification-Number/C++/validate-international-securities-identification-number.cpp b/Task/Validate-International-Securities-Identification-Number/C++/validate-international-securities-identification-number.cpp index bb346f31f6..96c2c8e3f8 100644 --- a/Task/Validate-International-Securities-Identification-Number/C++/validate-international-securities-identification-number.cpp +++ b/Task/Validate-International-Securities-Identification-Number/C++/validate-international-securities-identification-number.cpp @@ -6,40 +6,40 @@ bool CheckFormat(const std::string& isin) { - std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])"); - std::smatch match; - return std::regex_match(isin, match, isinRegEpx); + std::regex isinRegEpx(R"([A-Z]{2}[A-Z0-9]{9}[0-9])"); + std::smatch match; + return std::regex_match(isin, match, isinRegEpx); } std::string CodeISIN(const std::string& isin) { - std::string coded; - int offset = 'A' - 10; - for (auto ch : isin) - { - if (ch >= 'A' && ch <= 'Z') - { - std::stringstream ss; - ss << static_cast(ch) - offset; - coded += ss.str(); - } - else - { - coded.push_back(ch); - } - } + std::string coded; + int offset = 'A' - 10; + for (auto ch : isin) + { + if (ch >= 'A' && ch <= 'Z') + { + std::stringstream ss; + ss << static_cast(ch) - offset; + coded += ss.str(); + } + else + { + coded.push_back(ch); + } + } - return std::move(coded); + return std::move(coded); } bool CkeckISIN(const std::string& isin) { - if (!CheckFormat(isin)) - return false; + if (!CheckFormat(isin)) + return false; - std::string coded = CodeISIN(isin); + std::string coded = CodeISIN(isin); // from http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#C.2B.2B11 - return luhn(coded); + return luhn(coded); } @@ -48,12 +48,12 @@ bool CkeckISIN(const std::string& isin) int main() { - std::string isins[] = { "US0378331005", "US0373831005", "U50378331005", - "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", - "FR0000988040" }; - for (const auto& isin : isins) - { - std::cout << isin << std::boolalpha << " - " << CkeckISIN(isin) <>SOURCE FORMAT FREE +*> this is gnucobol 2.0 +identification division. +program-id. callISINtest. +data division. +working-storage section. +01 ISINtest-result binary-int. +procedure division. +start-callISINtest. + display 'should be valid ' with no advancing + call 'ISINtest' using 'US0378331005' ISINtest-result + perform display-ISINtest-result + display 'should not be valid ' with no advancing + call 'ISINtest' using 'US0373831005' ISINtest-result + perform display-ISINtest-result + display 'should not be valid ' with no advancing + call 'ISINtest' using 'U50378331005' ISINtest-result + perform display-ISINtest-result + display 'should not be valid ' with no advancing + call 'ISINtest' using 'US03378331005' ISINtest-result + perform display-ISINtest-result + display 'should be valid ' with no advancing + call 'ISINtest' using 'AU0000XVGZA3' ISINtest-result + perform display-ISINtest-result + display 'should be valid ' with no advancing + call 'ISINtest' using 'AU0000VXGZA3' ISINtest-result + perform display-ISINtest-result + display 'should be valid ' with no advancing + call 'ISINtest' using 'FR0000988040' ISINtest-result + perform display-ISINtest-result + stop run + . +display-ISINtest-result. + evaluate ISINtest-result + when 0 + display ' is valid' + when -1 + display ' invalid length ' + when -2 + display ' invalid countrycode ' + when -3 + display ' invalid base36 digit ' + when -4 + display ' luhn test failed' + when other + display ' invalid return code ' ISINtest-result + end-evaluate + . +end program callISINtest. + +identification division. +program-id. ISINtest. +data division. +working-storage section. +01 country-code-values value + 'ADAEAFAGAIALAMAOAQARASATAUAWAXAZBABBBDBEBFBGBHBIBJBLBMBNBOBQBRBS' +& 'BTBVBWBYBZCACCCDCFCGCHCICKCLCMCNCOCRCUCVCWCXCYCZDEDJDKDMDODZECEE' +& 'EGEHERESETFIFJFKFMFOFRGAGBGDGEGFGGGHGIGLGMGNGPGQGRGSGTGUGWGYHKHM' +& 'HNHRHTHUIDIEILIMINIOIQIRISITJEJMJOJPKEKGKHKIKMKNKPKRKWKYKZLALBLC' +& 'LILKLRLSLTLULVLYMAMCMDMEMFMGMHMKMLMMMNMOMPMQMRMSMTMUMVMWMXMYMZNA' +& 'NCNENFNGNINLNONPNRNUNZOMPAPEPFPGPHPKPLPMPNPRPSPTPWPYQARERORSRURW' +& 'SASBSCSDSESGSHSISJSKSLSMSNSOSRSSSTSVSXSYSZTCTDTFTGTHTJTKTLTMTNTO' +& 'TRTTTVTWTZUAUGUMUSUYUZVAVCVEVGVIVNVUWFWSYEYTZAZMZW'. + 03 country-codes occurs 249 + ascending key country-code + indexed by cc-idx. + 05 country-code pic xx. + +01 b pic 99. +01 base36-digits pic x(36) value + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + +01 i pic 99. +01 p pic 99. +01 luhn-number pic x(20). +01 luhntest-result binary-int. + +linkage section. +01 test-number any length. +01 ISINtest-result binary-int. + +procedure division using test-number ISINtest-result. +start-ISINtest. + display space test-number with no advancing + + *> format test + if function length(test-number) <> 12 + move -1 to ISINtest-result + goback + end-if + + *> countrycode test + search all country-codes + at end + move -2 to ISINtest-result + goback + when test-number(1:2) = country-code(cc-idx) + continue + end-search + + *> convert each character from base 36 to base 10 + *> and add to the luhn-number + move 0 to p + perform varying i from 1 by 1 until i > 12 + if test-number(i:1) >= '0' and <= '9' + move test-number(i:1) to luhn-number(p + 1:1) + add 1 to p + else + perform varying b from 9 by 1 until b > 35 + or base36-digits(b + 1:1) = test-number(i:1) + continue + end-perform + if b > 35 + move -3 to ISINtest-result + goback + end-if + move b to luhn-number(p + 1:2) + add 2 to p + end-if + end-perform + + call 'luhntest' using luhn-number(1:p) luhntest-result + if luhntest-result <> 0 + move -4 to ISINtest-result + goback + end-if + + move 0 to ISINtest-result + goback + . +end program ISINtest. + +identification division. +program-id. luhntest. +data division. +working-storage section. +01 i pic S99. +01 check-sum pic 999. +linkage section. +01 test-number any length. +01 luhntest-result binary-int. +procedure division using test-number luhntest-result. +start-luhntest. + display space test-number with no advancing + move 0 to check-sum + + *> right to left sum the odd numbered digits + compute i = function length(test-number) + perform varying i from i by -2 until i < 1 + add function numval(test-number(i:1)) to check-sum + end-perform + display space check-sum with no advancing + + *> right to left double sum the even numbered digits + compute i = function length(test-number) - 1 + perform varying i from i by -2 until i < 1 + add function numval(test-number(i:1)) to check-sum + add function numval(test-number(i:1)) to check-sum + *> convert a two-digit double sum number to a single digit + if test-number(i:1) >= '5' + subtract 9 from check-sum + end-if + end-perform + display space check-sum with no advancing + + if function mod(check-sum,10) = 0 + move 0 to luhntest-result *> success + else + move -1 to luhntest-result *> failure + end-if + goback + . +end program luhntest. diff --git a/Task/Validate-International-Securities-Identification-Number/Delphi/validate-international-securities-identification-number.pas b/Task/Validate-International-Securities-Identification-Number/Delphi/validate-international-securities-identification-number.pas index 3e6984259b..a1113c8e51 100644 --- a/Task/Validate-International-Securities-Identification-Number/Delphi/validate-international-securities-identification-number.pas +++ b/Task/Validate-International-Securities-Identification-Number/Delphi/validate-international-securities-identification-number.pas @@ -5,24 +5,24 @@ function StrToBase10(S: string): TByteDynArray; var I: Integer; var B: byte; - procedure StoreByte(B: byte); - begin - SetLength(Result,Length(Result)+1); - Result[High(Result)]:=B; - end; + procedure StoreByte(B: byte); + begin + SetLength(Result,Length(Result)+1); + Result[High(Result)]:=B; + end; begin SetLength(Result,0); for I:=1 to Length(S) do - begin - if S[I] in ['0'..'9'] then StoreByte(Byte(S[I])-$30) - else - begin - B:=(Byte(S[I])-$41)+10; - StoreByte(B div 10); - StoreByte(B mod 10); - end; - end; + begin + if S[I] in ['0'..'9'] then StoreByte(Byte(S[I])-$30) + else + begin + B:=(Byte(S[I])-$41)+10; + StoreByte(B div 10); + StoreByte(B mod 10); + end; + end; end; {Simplifies cases where we have to sum a two digit number} @@ -71,15 +71,15 @@ BA:=StrToBase10(IDStr); LT:=LuhnTest(BA); if LT and (SE=seNone) then Memo.Lines.Add(IDStr+': Valid') else - begin - S:=IDStr+': Invalid'; - if not LT then S:=S+', Luhn Error'; - case SE of - seLength: S:=S+', Length Error'; - seCountry: S:=S+', Country Code Error'; - end; - Memo.Lines.Add(S); - end; + begin + S:=IDStr+': Invalid'; + if not LT then S:=S+', Luhn Error'; + case SE of + seLength: S:=S+', Length Error'; + seCountry: S:=S+', Country Code Error'; + end; + Memo.Lines.Add(S); + end; end; diff --git a/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-1.go b/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-1.go index f36c9beeeb..435a74b46a 100644 --- a/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-1.go +++ b/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-1.go @@ -5,26 +5,26 @@ import "regexp" var r = regexp.MustCompile(`^[A-Z]{2}[A-Z0-9]{9}\d$`) var inc = [2][10]int{ - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, - {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, + {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}, } func ValidISIN(n string) bool { - if !r.MatchString(n) { - return false - } - var sum, p int - for i := 10; i >= 0; i-- { - p = 1 - p - if d := n[i]; d < 'A' { - sum += inc[p][d-'0'] - } else { - d -= 'A' - sum += inc[p][d%10] - p = 1 - p - sum += inc[p][d/10+1] - } - } - sum += int(n[11] - '0') - return sum%10 == 0 + if !r.MatchString(n) { + return false + } + var sum, p int + for i := 10; i >= 0; i-- { + p = 1 - p + if d := n[i]; d < 'A' { + sum += inc[p][d-'0'] + } else { + d -= 'A' + sum += inc[p][d%10] + p = 1 - p + sum += inc[p][d/10+1] + } + } + sum += int(n[11] - '0') + return sum%10 == 0 } diff --git a/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-2.go b/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-2.go index 1bef6c75aa..b4d5e57777 100644 --- a/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-2.go +++ b/Task/Validate-International-Securities-Identification-Number/Go/validate-international-securities-identification-number-2.go @@ -3,24 +3,24 @@ package main import "testing" func TestValidISIN(t *testing.T) { - testcases := []struct { - isin string - valid bool - }{ - {"US0378331005", true}, - {"US0373831005", false}, - {"U50378331005", false}, - {"US03378331005", false}, - {"AU0000XVGZA3", true}, - {"AU0000VXGZA3", true}, - {"FR0000988040", true}, - } + testcases := []struct { + isin string + valid bool + }{ + {"US0378331005", true}, + {"US0373831005", false}, + {"U50378331005", false}, + {"US03378331005", false}, + {"AU0000XVGZA3", true}, + {"AU0000VXGZA3", true}, + {"FR0000988040", true}, + } - for _, testcase := range testcases { - actual := ValidISIN(testcase.isin) - if actual != testcase.valid { - t.Errorf("expected %v for %q, got %v", - testcase.valid, testcase.isin, actual) - } - } + for _, testcase := range testcases { + actual := ValidISIN(testcase.isin) + if actual != testcase.valid { + t.Errorf("expected %v for %q, got %v", + testcase.valid, testcase.isin, actual) + } + } } diff --git a/Task/Validate-International-Securities-Identification-Number/Langur/validate-international-securities-identification-number.langur b/Task/Validate-International-Securities-Identification-Number/Langur/validate-international-securities-identification-number.langur index 9ad6f7c5c0..b6c6429b4e 100644 --- a/Task/Validate-International-Securities-Identification-Number/Langur/validate-international-securities-identification-number.langur +++ b/Task/Validate-International-Securities-Identification-Number/Langur/validate-international-securities-identification-number.langur @@ -5,9 +5,9 @@ val luhntest = fn(s) { for[=0] i of numbers { _for += if i rem 2 == oddeven { - numbers[i] + numbers[i] } else { - t[numbers[i]+1] + t[numbers[i]+1] } } div 10 } diff --git a/Task/Validate-International-Securities-Identification-Number/Perl/validate-international-securities-identification-number.pl b/Task/Validate-International-Securities-Identification-Number/Perl/validate-international-securities-identification-number.pl index 3af93a98e8..1685c9cb3b 100644 --- a/Task/Validate-International-Securities-Identification-Number/Perl/validate-international-securities-identification-number.pl +++ b/Task/Validate-International-Securities-Identification-Number/Perl/validate-international-securities-identification-number.pl @@ -3,13 +3,13 @@ use English; use POSIX; use Test::Simple tests => 7; -ok( validate_isin('US0378331005'), 'Test 1'); +ok( validate_isin('US0378331005'), 'Test 1'); ok( ! validate_isin('US0373831005'), 'Test 2'); ok( ! validate_isin('U50378331005'), 'Test 3'); ok( ! validate_isin('US03378331005'), 'Test 4'); -ok( validate_isin('AU0000XVGZA3'), 'Test 5'); +ok( validate_isin('AU0000XVGZA3'), 'Test 5'); ok( validate_isin('AU0000VXGZA3'), 'Test 6'); -ok( validate_isin('FR0000988040'), 'Test 7'); +ok( validate_isin('FR0000988040'), 'Test 7'); exit 0; sub validate_isin { diff --git a/Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-1.ps1 b/Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-1.ps1 new file mode 100644 index 0000000000..2f2dde7626 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-1.ps1 @@ -0,0 +1,63 @@ +function Test-ISIN +{ + [CmdletBinding()] + [OutputType([bool])] + Param + ( + [Parameter(Mandatory=$true, Position=0)] + [ValidatePattern("[A-Z]{2}\w{9}\d")] + [ValidateScript({$_.Length -eq 12})] + [string] + $Number + ) + + function Split-Array + { + $array = @(), @() + $input | ForEach-Object {$array[($index = -not $index)] += $_} + $array[1], $array[0] + } + + filter ConvertTo-Digit + { + if ($_ -gt 9) + { + $_.ToString().ToCharArray() | ForEach-Object -Begin {$n = 0} -Process {$n += [Char]::GetNumericValue($_)} -End {$n} + } + else + { + $_ + } + } + + + $checkDigit = $Number[-1] + + $digits = ($Number -replace ".$").ToCharArray() | ForEach-Object { + if ([Char]::IsDigit($_)) + { + [Char]::GetNumericValue($_) + } + else + { + [int][char]$_ - 55 + } + } + + $odds, $evens = ($digits -join "").ToCharArray() | Split-Array + + if ($odds.Count -gt $evens.Count) + { + $odds = $odds | ForEach-Object {[Char]::GetNumericValue($_) * 2} | ConvertTo-Digit + $evens = $evens | ForEach-Object {[Char]::GetNumericValue($_)} + } + else + { + $odds = $odds | ForEach-Object {[Char]::GetNumericValue($_)} + $evens = $evens | ForEach-Object {[Char]::GetNumericValue($_) * 2} | ConvertTo-Digit + } + + $sum = ($odds | Measure-Object -Sum).Sum + ($evens | Measure-Object -Sum).Sum + + (10 - ($sum % 10)) % 10 -match $checkDigit +} diff --git a/Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-2.ps1 b/Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-2.ps1 new file mode 100644 index 0000000000..3b11800103 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/PowerShell/validate-international-securities-identification-number-2.ps1 @@ -0,0 +1,6 @@ +"US0378331005","US0373831005","US0337833103","AU0000XVGZA3","AU0000VXGZA3","FR0000988040" | ForEach-Object { + [PSCustomObject]@{ + ISIN = $_ + IsValid = Test-ISIN -Number $_ + } +} diff --git a/Task/Validate-International-Securities-Identification-Number/Rebol/validate-international-securities-identification-number.rebol b/Task/Validate-International-Securities-Identification-Number/Rebol/validate-international-securities-identification-number.rebol new file mode 100644 index 0000000000..c0b4bc24d2 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/Rebol/validate-international-securities-identification-number.rebol @@ -0,0 +1,49 @@ +Rebol [ + title: "Rosetta code: Validate International Securities Identification Number" + file: %Validate_International_Securities_Identification_Number.r3 + url: https://rosettacode.org/wiki/Validate_International_Securities_Identification_Number +] + +valid-isin?: function/with [ + "International Securities Identification Number (ISIN) validator." + code [string!] +][ + ;; Format validation: + unless parse code [2 alpha 9 alpha-numeric 1 numeric][ return false ] + ;; Convert to number: + str: clear "" + foreach c code [ + append str case [ + c >= #"a" [-87 + c] + c >= #"A" [-55 + c] + 'else [c] + ] + ] + ;; Luhn validation: + sum: 0 + parse reverse str [ + some [ + set num: numeric ( + sum: sum + num - #"0" + ) + opt [set num: numeric ( + num: 2 * (num - #"0") + if num > 9 [num: num - 9] + sum: sum + num + )] + ] + ] + zero? sum % 10 +] :system/catalog/bitsets + +foreach [code expected] [ + "US0378331005" #(true) + "US0373831005" #(false) ; The transposition typo is caught by the checksum constraint. + "U50378331005" #(false) ; The substitution typo is caught by the format constraint. + "US03378331005" #(false) ; The duplication typo is caught by the format constraint. + "AU0000XVGZA3" #(true) + "AU0000VXGZA3" #(true) ; Unfortunately, not all transposition typos are caught by the checksum constraint. + "FR0000988040" #(true) +][ + print [code valid-isin? code] +] diff --git a/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb b/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb index 2ed11d3cbd..d6cab7b1da 100644 --- a/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb +++ b/Task/Validate-International-Securities-Identification-Number/Ruby/validate-international-securities-identification-number.rb @@ -11,6 +11,6 @@ U50378331005 US03378331005 AU0000XVGZA3 AU0000VXGZA3 -FR0000988040).map{|tc| valid_isin?(tc) } +FR0000988040).map{|tc| valid_isin?(tc) } # => [true, false, false, false, true, true, true] diff --git a/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql b/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql index 72e6909706..9873bce73a 100644 --- a/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql +++ b/Task/Validate-International-Securities-Identification-Number/Transact-SQL/validate-international-securities-identification-number-1.sql @@ -3,39 +3,39 @@ RETURNS bit AS BEGIN --*** Test an ISIN code and return 1 if it is valid, 0 if invalid. -DECLARE @bValid bit; +DECLARE @bValid bit; SET @bValid = CASE WHEN @strISIN LIKE '[A-Z][A-Z][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][A-Z,0-9][0-9]' THEN 1 ELSE 0 END IF @bValid = 1 - BEGIN - DECLARE @strTest VarChar(40) = ''; - DECLARE @strAdd VarChar(2); - DECLARE @p INT = 0; - WHILE @p < LEN(@strISIN) - BEGIN - SET @p = @p+1; - SET @strAdd = SUBSTRING(@strISIN,@p,1); - IF @strAdd LIKE '[A-Z]' SET @strAdd = CONVERT(VarChar(2),ASCII(UPPER(@strAdd))-55); - SET @strTest = @strTest + @strAdd; - END; + BEGIN + DECLARE @strTest VarChar(40) = ''; + DECLARE @strAdd VarChar(2); + DECLARE @p INT = 0; + WHILE @p < LEN(@strISIN) + BEGIN + SET @p = @p+1; + SET @strAdd = SUBSTRING(@strISIN,@p,1); + IF @strAdd LIKE '[A-Z]' SET @strAdd = CONVERT(VarChar(2),ASCII(UPPER(@strAdd))-55); + SET @strTest = @strTest + @strAdd; + END; - -- Proceed with Luhn test - DECLARE @strLuhn VarChar(40) = REVERSE(@strTest); -- usage: set once, never changed - DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values - SET @p = 0; -- reset loop counter - DECLARE @intValue INT; - DECLARE @intSum INT = 0; - -- loop through the reversed string, get the value (even-positioned digits are mapped) and add it to @intSum - WHILE @p < LEN(@strLuhn) - BEGIN - SET @p = @p+1; - SET @intValue = CONVERT(INT, SUBSTRING(@strLuhn,@p,1) ) -- value of the digit at position @p in the string - IF @p % 2 = 0 SET @intValue = CONVERT(INT,SUBSTRING(@strS2Values,@intValue+1,1)) - SET @intSum = @intSum + @intValue - END - -- If the of the digits' mapped values ends in 0 (modulo 10 = 0) then the Luhn test succeeds - SET @bValid = CASE WHEN @intSum % 10 = 0 THEN 1 ELSE 0 END - END; + -- Proceed with Luhn test + DECLARE @strLuhn VarChar(40) = REVERSE(@strTest); -- usage: set once, never changed + DECLARE @strS2Values VarChar(10) = '0246813579'; -- constant: maps digits to their S2 summed values + SET @p = 0; -- reset loop counter + DECLARE @intValue INT; + DECLARE @intSum INT = 0; + -- loop through the reversed string, get the value (even-positioned digits are mapped) and add it to @intSum + WHILE @p < LEN(@strLuhn) + BEGIN + SET @p = @p+1; + SET @intValue = CONVERT(INT, SUBSTRING(@strLuhn,@p,1) ) -- value of the digit at position @p in the string + IF @p % 2 = 0 SET @intValue = CONVERT(INT,SUBSTRING(@strS2Values,@intValue+1,1)) + SET @intSum = @intSum + @intValue + END + -- If the of the digits' mapped values ends in 0 (modulo 10 = 0) then the Luhn test succeeds + SET @bValid = CASE WHEN @intSum % 10 = 0 THEN 1 ELSE 0 END + END; RETURN @bValid END diff --git a/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v b/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v index 097f268234..650b054e60 100644 --- a/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v +++ b/Task/Validate-International-Securities-Identification-Number/V-(Vlang)/validate-international-securities-identification-number.v @@ -1,55 +1,53 @@ import regex -const ( - inc = [ - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], - [0, 2, 4, 6, 8, 1, 3, 5, 7, 9], - ] -) +const inc = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [0, 2, 4, 6, 8, 1, 3, 5, 7, 9], +] fn valid_isin(n string) bool { - mut r,_,_ := regex.regex_base('^[A-Z]{2}[A-Z0-9]{9}\d$') - if !r.matches_string(n) { - return false - } - mut sum := 0 - mut p := 0 - for i := 10; i >= 0; i-- { - p = 1 - p - mut d := n[i..i+1].int() - if d < 'A'.int() { - sum += inc[p][d-'0'.int()] - } else { - d -= 'A'.int() - sum += inc[p][d%10] - p = 1 - p - sum += inc[p][d/10+1] - } - } - sum += n[11..12].int() - '0'.int() - return sum%10 == 0 + mut r, _, _ := regex.regex_base('^[A-Z]{2}[A-Z0-9]{9}\\d$') + if !r.matches_string(n) { + return false + } + mut sum := 0 + mut p := 0 + for i := 10; i >= 0; i-- { + p = 1 - p + mut d := n[i..i + 1].int() + if d < 'A'.int() { + sum += inc[p][d - '0'.int()] + } else { + d -= 'A'.int() + sum += inc[p][d % 10] + p = 1 - p + sum += inc[p][d / 10 + 1] + } + } + sum += n[11..12].int() - '0'.int() + return sum % 10 == 0 } struct Testcases { - isin string - valid bool + isin string + valid bool } -fn main(){ - testcases := [ - Testcases{"US0378331005", true}, - Testcases{"US0373831005", false}, - Testcases{"U50378331005", false}, - Testcases{"US03378331005", false}, - Testcases{"AU0000XVGZA3", true}, - Testcases{"AU0000VXGZA3", true}, - Testcases{"FR0000988040", true}, - ] +fn main() { + testcases := [ + Testcases{'US0378331005', true}, + Testcases{'US0373831005', false}, + Testcases{'U50378331005', false}, + Testcases{'US03378331005', false}, + Testcases{'AU0000XVGZA3', true}, + Testcases{'AU0000VXGZA3', true}, + Testcases{'FR0000988040', true}, + ] - for testcase in testcases { - actual := valid_isin(testcase.isin) - if actual != testcase.valid { - println("expected ${testcase.valid} for ${testcase.isin}, got $actual") - } - } + for testcase in testcases { + actual := valid_isin(testcase.isin) + if actual != testcase.valid { + println('expected ${testcase.valid} for ${testcase.isin}, got ${actual}') + } + } } diff --git a/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vbs b/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vbs new file mode 100644 index 0000000000..9730c62cc8 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/VBScript/validate-international-securities-identification-number.vbs @@ -0,0 +1,47 @@ +' Validate International Securities Identification Number - 03/03/2019 + +buf=buf&test("US0378331005")&vbCrLf +buf=buf&test("US0373831005")&vbCrLf +buf=buf&test("U50378331005")&vbCrLf +buf=buf&test("US03378331005")&vbCrLf +buf=buf&test("AU0000XVGZA3")&vbCrLf +buf=buf&test("AU0000VXGZA3")&vbCrLf +buf=buf&test("FR0000988040")&vbCrLf +msgbox buf,,"Validate International Securities Identification Number" + +function test(cc) + dim err,c,r,s,i1,i2 + if len(cc)=12 then + for i=1 to len(cc) + p=instr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1)) + if p<>0 then c=c&(p-1) else err=1 + next 'i + for i=1 to 2 + if instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",mid(cc,i,1))=0 then err=1 + next 'i + if err=0 then + for i=len(c) to 1 step -1 + r=r&mid(c,i,1) + next 'i + for i=1 to len(r) step 2 + i1=i1+cint(mid(r,i,1)) + next 'i + for i=2 to len(r) step 2 + ii=cint(mid(r,i,1))*2 + if ii>=10 then ii=ii-9 + i2=i2+ii + next 'i + s=cstr(i1+i2) + if mid(s,len(s),1)="0" then + msg="valid" + else + msg="invalid ??1" + end if + else + msg="invalid ??2" + end if + else + msg="invalid ??3" + end if + test=cc&" "&msg +end function 'test diff --git a/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl b/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl index e055e43291..70a0c93e10 100644 --- a/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl +++ b/Task/Validate-International-Securities-Identification-Number/Zkl/validate-international-securities-identification-number-2.zkl @@ -1,5 +1,5 @@ println(" ISIN Valid?"); foreach isin in (T("US0378331005","US0373831005","U50378331005", - "US03378331005","AU0000XVGZA3","AU0000VXGZA3","FR0000988040")){ + "US03378331005","AU0000XVGZA3","AU0000VXGZA3","FR0000988040")){ println(isin," --> ",validateISIN(isin)); } diff --git a/Task/Vampire-number/Fortran/vampire-number.f b/Task/Vampire-number/Fortran/vampire-number.f new file mode 100644 index 0000000000..f97b799d20 --- /dev/null +++ b/Task/Vampire-number/Fortran/vampire-number.f @@ -0,0 +1,105 @@ +program vampire_numbers + implicit none + integer :: count, i, n_digits + integer(kind=8) :: num, test_nums(3) +! logical :: is_vampire + + ! Initialize test numbers + test_nums = [16758243290880_8, 24959017348650_8, 14593825548650_8] + + ! Print first 25 vampire numbers + print *, 'First 25 vampire numbers and their fangs:' + count = 0 + num = 1000 + do while (count < 25) + if (is_vampire(num)) then + count = count + 1 + end if + num = num + 1 + end do + + ! Check specific test numbers + print *, '' + print *, 'Checking specific numbers:' + do i = 1, 3 + if (is_vampire(test_nums(i))) then + continue ! Output handled in is_vampire + else + print *, test_nums(i), ' is not a vampire number.' + end if + end do + +contains + + logical function is_vampire(num) + integer(kind=8), intent(in) :: num + integer(kind=8) :: a, b, start_a, end_a + integer :: num_digits, half_digits + character(len=20) :: num_str, a_str, b_str + + ! Get number of digits + num_digits = floor(log10(real(num))) + 1 + if (mod(num_digits, 2) /= 0) then + is_vampire = .false. + return + end if + half_digits = num_digits / 2 + + ! Calculate range for factor a + start_a = max(10**(half_digits-1), num / (10**half_digits)) + end_a = min(num / 10**(half_digits-1), floor(sqrt(real(num)))) + + is_vampire = .false. + do a = start_a, end_a + if (mod(num, a) /= 0) cycle + b = num / a + + ! Check if b has correct number of digits + if (b < 10**(half_digits-1) .or. b >= 10**half_digits) cycle + + ! Check trailing zeros + if (mod(a, 10_8) == 0 .and. mod(b, 10_8) == 0) cycle + + ! Check if digits match + write(num_str, '(I0)') num + write(a_str, '(I0)') a + write(b_str, '(I0)') b + if (len_trim(a_str) == half_digits .and. len_trim(b_str) == half_digits) then + if (same_digits(num_str, a_str, b_str)) then + is_vampire = .true. + print '(I0, " : (", I0, ", ", I0, ")")', num, a, b + end if + end if + end do + end function is_vampire + + logical function same_digits(num_str, a_str, b_str) + character(len=*), intent(in) :: num_str, a_str, b_str + integer :: digits_num(0:9), digits_ab(0:9), i + character(len=1) :: c + + digits_num = 0 + digits_ab = 0 + + ! Count digits in num + do i = 1, len_trim(num_str) + read(num_str(i:i), '(A)') c + digits_num(ichar(c) - ichar('0')) = digits_num(ichar(c) - ichar('0')) + 1 + end do + + ! Count digits in a + do i = 1, len_trim(a_str) + read(a_str(i:i), '(A)') c + digits_ab(ichar(c) - ichar('0')) = digits_ab(ichar(c) - ichar('0')) + 1 + end do + + ! Count digits in b + do i = 1, len_trim(b_str) + read(b_str(i:i), '(A)') c + digits_ab(ichar(c) - ichar('0')) = digits_ab(ichar(c) - ichar('0')) + 1 + end do + + same_digits = all(digits_num == digits_ab) + end function same_digits + +end program vampire_numbers diff --git a/Task/Vampire-number/Julia/vampire-number-3.jl b/Task/Vampire-number/Julia/vampire-number-3.jl new file mode 100644 index 0000000000..33b0f82b5e --- /dev/null +++ b/Task/Vampire-number/Julia/vampire-number-3.jl @@ -0,0 +1,69 @@ +const TENS = [UInt(10)^i for i in 0:19] + +function dtally(x::UInt) + t = UInt(0) + while x > 0 + t += UInt(1) << ((x % 10) * 6) + x ÷= 10 + end + return t +end + +function fangs(x::UInt) + f = UInt[] + nd = ndigits(x) + nd & 1 != 0 && return f + nd ÷= 2 + + lo = max(TENS[nd], (x + TENS[nd+1] - 2) ÷ (TENS[nd+1] - 1)) + hi = min(x ÷ lo, floor(UInt, sqrt(x))) + + t = dtally(x) + for a in lo:hi + b = x ÷ a + if a * b == x && ((a % 10) != 0 || (b % 10) != 0) && t == dtally(a) + dtally(b) + push!(f, a) + end + end + + return f +end + +function show_fangs(x::UInt, f::Vector{UInt}) + print(x) + for fang in f + print(" = ", fang, " x ", x ÷ fang) + end + println() +end + +function testfangs() + bigs = UInt[16758243290880, 24959017348650, 14593825548650] + + # Find first 25 vampire numbers + x = UInt(1) + n = 0 + while n < 25 + f = fangs(x) + if !isempty(f) + n += 1 + print(lpad(n, 2), ": ") + show_fangs(x, f) + end + x += 1 + end + + println() + + # Check big numbers + for b in bigs + f = fangs(b) + if !isempty(f) + show_fangs(b, f) + else + println(b, " is not vampiric") + end + end +end + +testfangs() diff --git a/Task/Vampire-number/Pluto/vampire-number.pluto b/Task/Vampire-number/Pluto/vampire-number.pluto new file mode 100644 index 0000000000..1790c1c98f --- /dev/null +++ b/Task/Vampire-number/Pluto/vampire-number.pluto @@ -0,0 +1,75 @@ +local fmt = require "fmt" +require "table2" + +local function ndigits(x) + local n = 0 + while x > 0 do + n += 1 + x //= 10 + end + return n +end + +local function dtally(x) + local t = 0 + while x > 0 do + t += 2 ** ((x % 10) * 6) + x //= 10 + end + return t +end + +local tens = table.rep(15, 0) + +local function init() + tens[1] = 1 + for i = 2, 15 do tens[i] = tens[i - 1] * 10 end +end + +local function fangs(x) + local f = {} + local nd = ndigits(x) + if nd & 1 == 1 then return f end + nd //= 2 + local lo = math.max(tens[nd], (x + tens[nd + 1] - 2) // (tens[nd + 1] - 1)) + local hi = math.min(x // lo, math.floor(math.sqrt(x))) + local t = dtally(x) + local a = lo + while a <= hi do + local b = x // a + local t2 = dtally(a) + dtally(b) + if a * b == x and ((a % 10) > 0 or (b % 10) > 0) and t == t2 then + f:insert(a) + end + a += 1 + end + return f +end + +local function showfangs(x, f) + fmt.write("%6d", x) + if #f > 1 then print() end + for f as a do fmt.print(" = %3d x %3d", a, x // a) end +end + +init() +local x = 1 +local n = 0 +while n < 25 do + local f = fangs(x) + if #f > 0 then + n += 1 + fmt.write("%2d: ", n) + showfangs(x, f) + end + x += 1 +end +print() +for {16758243290880, 24959017348650, 14593825548650} as y do + local f = fangs(y) + if #f > 0 then + showfangs(y, f) + else + fmt.print("%d is not vampiric", y) + end +end diff --git a/Task/Vampire-number/SuperCollider/vampire-number.sc b/Task/Vampire-number/SuperCollider/vampire-number.sc new file mode 100644 index 0000000000..624c25d028 --- /dev/null +++ b/Task/Vampire-number/SuperCollider/vampire-number.sc @@ -0,0 +1,85 @@ +( +// Usage: ~extract_fangs.(n), where n is a positive integer +// +// Return a list made of all the fangs of n. If n isn't a vampire, +// then an empty list is returned. +// n can be a floating point number as long as its fractional part +// is equal to 0. +~extract_fangs = { + arg n; var out = List[], f, is_fang, f1, f2, i = 0, + nd = [], nr, n_cp = n, k; + + // Convert n to an array made of its digits + // > fast method used when n is a 32-bit int or float + nr = n_cp % 1e9; + nd = nr.asInteger.asDigits ++ nd; + n_cp = n_cp - nr; + + // > slower method used when n is a 64-bit float + if(n_cp > 0){ + n_cp = n; nd = []; + while{n_cp - (10**(i + 1)) > 0}{i = i + 1}; + for(0, i){ + arg j; k = i - j; + nr = floor(n_cp / (10**k)); + nd = nd ++ [nr]; + n_cp = n_cp - (nr * (10**k)); + }; + }; + + // Even number of digits + if(nd.size % 2 == 1){}{ + + for(1, floor(sqrt(n))){ + arg i; is_fang = true; f = []; + if(n % i == 0){ + f = [i, n/i]; + }{is_fang = false}; + + if(is_fang){ + f1 = f[0].asInteger.asDigits; + f2 = f[1].asInteger.asDigits; + + // Each fang has the same number of digits + if((f1.size != (nd.size/2)) || + (f2.size != (nd.size/2))){is_fang = false}{ + + // At most one has a trailing zero + if((f1[f1.size - 1] == 0) && + (f2[f2.size - 1] == 0)){is_fang = false}{ + + if((f1 ++ f2).sort != nd.sort) + {is_fang = false}{}; + }; + + }; + + if(is_fang){out.add(f)}{}; + }{}; + }; + }; + out +}; + + +~goal = 25; ~i = 0; ~f; +"25 first vampire numbers +-------------------------------".postln; +while{~goal > 0}{ + if((~f = ~extract_fangs.(~i = ~i + 1)) == List[]){}{ + ~goal = ~goal - 1; + ("n°" ++ (25 - ~goal).asString ++ " is " ++ + ~i.asString ++ "; fangs: ").post; + ~f.postln; + }; +}; + +"\nIndividual tests +-------------------------------".postln; +[16758243290880.0, 24959017348650.0, 14593825548650.0].do{ + arg n; n.asString.post; + if((~f = ~extract_fangs.(n)) == List[]) + {" isn't a vampire number.".postln;} + {" is a vampire number; fangs: ".post; ~f.postln;}; +}; +) diff --git a/Task/Van-Eck-sequence/Ada/van-eck-sequence.adb b/Task/Van-Eck-sequence/Ada/van-eck-sequence.adb new file mode 100644 index 0000000000..5eb3e28a34 --- /dev/null +++ b/Task/Van-Eck-sequence/Ada/van-eck-sequence.adb @@ -0,0 +1,35 @@ +with Ada.Text_IO; + +procedure Van_Eck_Sequence is + + Sequence : array (Natural range 1 .. 1_000) of Natural; + + procedure Calculate_Sequence is + begin + Sequence (Sequence'First) := 0; + for Index in Sequence'First .. Sequence'Last - 1 loop + Sequence (Index + 1) := 0; + for I in reverse Sequence'First .. Index - 1 loop + if Sequence (I) = Sequence (Index) then + Sequence (Index + 1) := Index - I; + exit; + end if; + end loop; + end loop; + end Calculate_Sequence; + + procedure Show (First, Last : in Positive) is + use Ada.Text_IO; + begin + Put ("Element" & First'Image & " .." & Last'Image & " of Van Eck sequence: "); + for I in First .. Last loop + Put (Sequence (I)'Image); + end loop; + New_Line; + end Show; + +begin + Calculate_Sequence; + Show (First => 1, Last => 10); + Show (First => 991, Last => 1_000); +end Van_Eck_Sequence; diff --git a/Task/Van-Eck-sequence/COBOL/van-eck-sequence.cob b/Task/Van-Eck-sequence/COBOL/van-eck-sequence.cob new file mode 100644 index 0000000000..3c5b4c0c2e --- /dev/null +++ b/Task/Van-Eck-sequence/COBOL/van-eck-sequence.cob @@ -0,0 +1,46 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. VAN-ECK. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 CALCULATION. + 02 ECK PIC 999 OCCURS 1000 TIMES. + 02 I PIC 9999. + 02 J PIC 9999. + 01 OUTPUT-FORMAT. + 02 ITEM PIC ZZ9. + 02 IDX PIC ZZZ9. + + PROCEDURE DIVISION. + B. PERFORM GENERATE-ECK. + PERFORM SHOW VARYING I FROM 1 BY 1 UNTIL I = 11. + PERFORM SHOW VARYING I FROM 991 BY 1 UNTIL I = 1001. + STOP RUN. + + SHOW. + MOVE I TO IDX. + MOVE ECK(I) TO ITEM. + DISPLAY 'ECK(' IDX ') = ' ITEM. + + GENERATE-ECK SECTION. + B. SET ECK(1) TO 0. + SET I TO 1. + PERFORM GENERATE-TERM + VARYING I FROM 2 BY 1 UNTIL I = 1001. + + GENERATE-TERM SECTION. + B. SUBTRACT 2 FROM I GIVING J. + LOOP. + IF J IS LESS THAN 1 GO TO TERM-IS-NEW. + IF ECK(J) = ECK(I - 1) GO TO TERM-IS-OLD. + SUBTRACT 1 FROM J. + GO TO LOOP. + + TERM-IS-NEW. + SET ECK(I) TO 0. + GO TO DONE. + + TERM-IS-OLD. + COMPUTE ECK(I) = (I - J) - 1. + + DONE. EXIT. diff --git a/Task/Van-Eck-sequence/EMal/van-eck-sequence.emal b/Task/Van-Eck-sequence/EMal/van-eck-sequence.emal new file mode 100644 index 0000000000..85dea22a67 --- /dev/null +++ b/Task/Van-Eck-sequence/EMal/van-eck-sequence.emal @@ -0,0 +1,27 @@ +fun vanEck ← void by int firstIndex, int lastIndex + logic isFirst ← true + Map map ← int%int[] + int last ← 0 + write("[") + if firstIndex æ 1 + write("0") + isFirst ← false + end + for int n ← 2 ; n ≤ lastIndex ; ++n + int v ← when(map.has(last), n - map[last], 0) + map[last] ← n + last ← v + if n ≥ firstIndex + write(when(isFirst, Text.EMPTY, ",") + v) + isFirst ← false + end + end + writeLine("]") +end +Pair[int%int(1 ⇒ 10), int%int(991 ⇒ 1000)].list( +void by var pair + writeLine("Terms " + pair.key + " to " + + pair.value + " of the sequence are:") + vanEck(pair.key, pair.value) + writeLine() +end) diff --git a/Task/Van-Eck-sequence/Oberon-07/van-eck-sequence.oberon b/Task/Van-Eck-sequence/Oberon-07/van-eck-sequence.oberon new file mode 100644 index 0000000000..e05b5cc014 --- /dev/null +++ b/Task/Van-Eck-sequence/Oberon-07/van-eck-sequence.oberon @@ -0,0 +1,36 @@ +MODULE VanEck; (* find elements of the Van Eck Sequence - first term is 0, following *) + (* terms are 0 if the previous was the first appearance of the element *) + (* or how far back in the sequence the last element appeared *) + IMPORT Out; + + VAR vSeq, vPos : ARRAY 1001 OF INTEGER; + i : INTEGER; + + (* Stores the first LEN( seq ) - 1 elements of the Van Eck sequence into seq *) + (* ( element 0 is not used ), pos must be the same length as seq and is used as a *) + (* temporary work array *) + PROCEDURE getVanEck( VAR seq, pos : ARRAY OF INTEGER ); + VAR i, j, n, prev : INTEGER; + BEGIN + n := LEN( seq ) - 1; + FOR i := 0 TO n DO seq[ i ] := 0; pos[ i ] := 0 END; + FOR i := 2 TO n DO + j := i - 1; + prev := seq[ j ]; + IF pos[ prev ] # 0 THEN (* not a new element *) + seq[ i ] := j - pos[ prev ] + END; + pos[ prev ] := j + END + END getVanEck; + +BEGIN + + (* construct the first 1000 terms of the sequence *) + getVanEck( vSeq, vPos ); + + (* show the first and last 10 elements *) + FOR i := 1 TO 10 DO Out.String( " " );Out.Int( vSeq[ i ], 0 ) END;Out.Ln; + FOR i := LEN( vSeq ) - 10 TO LEN( vSeq ) - 1 DO Out.String( " " );Out.Int( vSeq[ i ], 0 ) END;Out.Ln + +END VanEck. diff --git a/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.adb b/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.adb new file mode 100644 index 0000000000..41b511f3d0 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Ada/van-der-corput-sequence.adb @@ -0,0 +1,27 @@ +with Ada.Text_IO; + +procedure Main is + package Float_IO is new Ada.Text_IO.Float_IO (Float); + function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is + Value : Natural := N; + Result : Float := 0.0; + Exponent : Positive := 1; + begin + while Value > 0 loop + Result := Result + + Float (Value mod Base) / Float (Base ** Exponent); + Value := Value / Base; + Exponent := Exponent + 1; + end loop; + return Result; + end Van_Der_Corput; +begin + for Base in 2 .. 5 loop + Ada.Text_IO.Put ("Base" & Integer'Image (Base) & ":"); + for N in 1 .. 10 loop + Ada.Text_IO.Put (' '); + Float_IO.Put (Item => Van_Der_Corput (N, Base), Exp => 0); + end loop; + Ada.Text_IO.New_Line; + end loop; +end Main; diff --git a/Task/Van-der-Corput-sequence/Crystal/van-der-corput-sequence.cr b/Task/Van-der-Corput-sequence/Crystal/van-der-corput-sequence.cr new file mode 100644 index 0000000000..cdef0eda41 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Crystal/van-der-corput-sequence.cr @@ -0,0 +1,8 @@ +def vdc (n, base=2) + str = n.to_s(base).reverse + str.to_i(base) / (base ** str.size) +end + +(2..5).each do |base| + puts "Base #{base}: " + Array.new(10){|i| vdc(i,base)}.join(", ") +end diff --git a/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.eu b/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.eu new file mode 100644 index 0000000000..f07bcd283c --- /dev/null +++ b/Task/Van-der-Corput-sequence/Euphoria/van-der-corput-sequence.eu @@ -0,0 +1,20 @@ +function vdc(integer n, atom base) + atom vdc, denom, rem + vdc = 0 + denom = 1 + while n do + denom *= base + rem = remainder(n,base) + n = floor(n/base) + vdc += rem / denom + end while + return vdc +end function + +for i = 2 to 5 do + printf(1,"Base %d\n",i) + for j = 0 to 9 do + printf(1,"%g ",vdc(j,i)) + end for + puts(1,"\n\n") +end for diff --git a/Task/Van-der-Corput-sequence/JavaScript/van-der-corput-sequence.js b/Task/Van-der-Corput-sequence/JavaScript/van-der-corput-sequence.js new file mode 100644 index 0000000000..d98cbfd6ac --- /dev/null +++ b/Task/Van-der-Corput-sequence/JavaScript/van-der-corput-sequence.js @@ -0,0 +1,11 @@ +function vdc(n) { + const bits = [...n.toString(2)].toReversed(); + const exps = [...Array(bits.length).keys()].map(x => -x); + let res = 0; + for (let i = 0; i < bits.length; i++) { + res += bits[i] * 2 ** (exps[i] - 1); + } + return res; +} + +console.log([...Array(10).keys()].map(vdc).join(" ")); diff --git a/Task/Van-der-Corput-sequence/Oberon-07/van-der-corput-sequence.oberon b/Task/Van-der-Corput-sequence/Oberon-07/van-der-corput-sequence.oberon new file mode 100644 index 0000000000..432f3d38f3 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Oberon-07/van-der-corput-sequence.oberon @@ -0,0 +1,53 @@ +MODULE VanDerCorput; (* show members of the van der Corput sequence *) + (* in various bases - translated from the C sample *) + IMPORT Out; + + (* returns the gcd of a and b *) + PROCEDURE gcd( a, b : INTEGER ) : INTEGER; + VAR n, p, q : INTEGER; + BEGIN + p := a; + q := b; + WHILE p # 0 DO n := p; p := q MOD p; q := n END + RETURN q + END gcd ; + + (* returns the numerator and denominator of the nth member of *) + (* the van der Corput sequence in the specified base *) + PROCEDURE vc( nth, base : INTEGER; VAR n, d : INTEGER ); + VAR p, q, g : INTEGER; + BEGIN + p := 0; q := 1; n := nth; + WHILE n # 0 DO + p := p * base; + INC( p, n MOD base ); + q := q * base; + n := n DIV base + END; + (* return the numerator and denominator reduced by their gcd *) + g := gcd( p, q ); + n := p DIV g; + d := q DIV g + END vc; + + PROCEDURE task; + VAR i, b, n, d : INTEGER; + BEGIN + FOR b := 2 TO 5 DO + Out.String( "base " );Out.Int( b, 0 );Out.String( ":" ); + FOR i := 0 TO 9 DO + vc( i, b, n, d ); + IF n = 0 THEN + Out.String( " 0" ) + ELSE + Out.String( " " );Out.Int( n, 0 ); + Out.String( "/" );Out.Int( d, 0 ) + END + END; + Out.Ln + END + END task ; + +BEGIN + task +END VanDerCorput. diff --git a/Task/Van-der-Corput-sequence/R/van-der-corput-sequence.r b/Task/Van-der-Corput-sequence/R/van-der-corput-sequence.r new file mode 100644 index 0000000000..ce390b388e --- /dev/null +++ b/Task/Van-der-Corput-sequence/R/van-der-corput-sequence.r @@ -0,0 +1,12 @@ +num_bits <- function(n) ifelse(log2(n)%%1==0, + 1+log2(n), + ceiling(log2(n))) + +vdc <- function(n){ + if(n==0) return(0) + inds <- 1:num_bits(n) + vdc_raw <- intToBits(n)[inds] + sum(as.numeric(vdc_raw)*(2^-inds)) +} + +sapply(0:9, vdc) diff --git a/Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vbs b/Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vbs new file mode 100644 index 0000000000..1f38db8a79 --- /dev/null +++ b/Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vbs @@ -0,0 +1,48 @@ +'http://rosettacode.org/wiki/Van_der_Corput_sequence +'Van der Corput Sequence fucntion call = VanVanDerCorput(number,base) + +Base2 = "0" : Base3 = "0" : Base4 = "0" : Base5 = "0" +Base6 = "0" : Base7 = "0" : Base8 = "0" : Base9 = "0" + +l = 1 +h = 1 +Do Until l = 9 + 'Set h to the value of l after each function call + 'as it sets it to 0 - see lines 37 to 40. + Base2 = Base2 & ", " & VanDerCorput(h,2) : h = l + Base3 = Base3 & ", " & VanDerCorput(h,3) : h = l + Base4 = Base4 & ", " & VanDerCorput(h,4) : h = l + Base5 = Base5 & ", " & VanDerCorput(h,5) : h = l + Base6 = Base6 & ", " & VanDerCorput(h,6) : h = l + l = l + 1 +Loop + +WScript.Echo "Base 2: " & Base2 +WScript.Echo "Base 3: " & Base3 +WScript.Echo "Base 4: " & Base4 +WScript.Echo "Base 5: " & Base5 +WScript.Echo "Base 6: " & Base6 + +'Van der Corput Sequence +Function VanDerCorput(n,b) + k = RevString(Dec2BaseN(n,b)) + For i = 1 To Len(k) + VanDerCorput = VanDerCorput + (CLng(Mid(k,i,1)) * b^-i) + Next +End Function + +'Decimal to Base N Conversion +Function Dec2BaseN(q,c) + Dec2BaseN = "" + Do Until q = 0 + Dec2BaseN = CStr(q Mod c) & Dec2BaseN + q = Int(q / c) + Loop +End Function + +'Reverse String +Function RevString(s) + For j = Len(s) To 1 Step -1 + RevString = RevString & Mid(s,j,1) + Next +End Function diff --git a/Task/Variable-declaration-reset/AppleScript/variable-declaration-reset.applescript b/Task/Variable-declaration-reset/AppleScript/variable-declaration-reset.applescript new file mode 100644 index 0000000000..23f6e18e0c --- /dev/null +++ b/Task/Variable-declaration-reset/AppleScript/variable-declaration-reset.applescript @@ -0,0 +1,7 @@ +set s to {1, 2, 2, 3, 4, 4, 5} + +repeat with i from 1 to 7 + set curr to item i of s + if i > 1 and curr = prev then log i + set prev to curr +end repeat diff --git a/Task/Variable-declaration-reset/LOLCODE/variable-declaration-reset.lol b/Task/Variable-declaration-reset/LOLCODE/variable-declaration-reset.lol new file mode 100644 index 0000000000..5704ba3367 --- /dev/null +++ b/Task/Variable-declaration-reset/LOLCODE/variable-declaration-reset.lol @@ -0,0 +1,21 @@ +HAI 1.3 + +I HAS A s ITZ A BUKKIT +s HAS A SRS 0 ITZ 1 +s HAS A SRS 1 ITZ 2 +s HAS A SRS 2 ITZ 2 +s HAS A SRS 3 ITZ 3 +s HAS A SRS 4 ITZ 4 +s HAS A SRS 5 ITZ 4 +s HAS A SRS 6 ITZ 5 + +IM IN YR LOOP UPPIN YR i TIL BOTH SAEM i AN 7 + I HAS A prev + I HAS A curr ITZ s'Z SRS i + BOTH OF DIFFRINT i AN SMALLR OF i AN 0 AN BOTH SAEM prev AN curr, O RLY? + YA RLY, VISIBLE i + OIC + prev R curr +IM OUTTA YR LOOP + +KTHXBYE diff --git a/Task/Variable-declaration-reset/Maxima/variable-declaration-reset.maxima b/Task/Variable-declaration-reset/Maxima/variable-declaration-reset.maxima new file mode 100644 index 0000000000..e0fdb74d71 --- /dev/null +++ b/Task/Variable-declaration-reset/Maxima/variable-declaration-reset.maxima @@ -0,0 +1,7 @@ +s: [1, 2, 2, 3, 4, 4, 5]$ + +for i from 1 thru 7 do( + curr: s[i], + if i>1 and curr=prev then print(i), + prev: curr +); diff --git a/Task/Variable-declaration-reset/Pluto/variable-declaration-reset.pluto b/Task/Variable-declaration-reset/Pluto/variable-declaration-reset.pluto new file mode 100644 index 0000000000..11e4ef6515 --- /dev/null +++ b/Task/Variable-declaration-reset/Pluto/variable-declaration-reset.pluto @@ -0,0 +1,19 @@ +local s = {1, 2, 2, 3, 4, 4, 5} + +-- There is no output as 'prev' is created anew each time +-- around the loop and set implicitly to nil. +for i = 1, #s do + local curr = s[i] + local prev + if i > 1 and curr == prev then print(i) end + prev = curr +end + +-- Now 'prev' is created only once and reassigned +-- each time around the loop producing the desired output. +local prev +for i = 1, #s do + local curr = s[i] + if i > 1 and curr == prev then print(i) end + prev = curr +end diff --git a/Task/Variable-declaration-reset/R/variable-declaration-reset.r b/Task/Variable-declaration-reset/R/variable-declaration-reset.r new file mode 100644 index 0000000000..ca0e551278 --- /dev/null +++ b/Task/Variable-declaration-reset/R/variable-declaration-reset.r @@ -0,0 +1,7 @@ +s <- c(1, 2, 2, 3, 4, 4, 5) + +for(i in 1:7){ + curr <- s[i] + if(i>1 && curr==prev) print(i) + prev <- curr +} diff --git a/Task/Variable-declaration-reset/Ruby/variable-declaration-reset-1.rb b/Task/Variable-declaration-reset/Ruby/variable-declaration-reset-1.rb new file mode 100644 index 0000000000..85eb60dbe4 --- /dev/null +++ b/Task/Variable-declaration-reset/Ruby/variable-declaration-reset-1.rb @@ -0,0 +1,10 @@ +s = [1, 2, 2, 3, 4, 4, 5] + +for i in 0..6 + curr = s[i] + prev = prev + if i>0 and curr==prev then + puts i + end + prev = curr +end diff --git a/Task/Variable-declaration-reset/Ruby/variable-declaration-reset-2.rb b/Task/Variable-declaration-reset/Ruby/variable-declaration-reset-2.rb new file mode 100644 index 0000000000..6dc3ba64f8 --- /dev/null +++ b/Task/Variable-declaration-reset/Ruby/variable-declaration-reset-2.rb @@ -0,0 +1,10 @@ +s = [1, 2, 2, 3, 4, 4, 5] + +for i in 0..6 + curr = s[i] + $prev + if i>0 and curr==$prev then + puts i + end + $prev = curr +end diff --git a/Task/Variable-length-quantity/Ada/variable-length-quantity.adb b/Task/Variable-length-quantity/Ada/variable-length-quantity.adb new file mode 100644 index 0000000000..7855d1a0fa --- /dev/null +++ b/Task/Variable-length-quantity/Ada/variable-length-quantity.adb @@ -0,0 +1,92 @@ +with Ada.Containers.Vectors; +with Ada.Text_IO; +with Ada.Unchecked_Conversion; + +procedure VLQ is + + package Nat_IO is new Ada.Text_IO.Integer_IO (Natural); + + type Byte is mod 2**8; + + package Byte_IO is new Ada.Text_IO.Modular_IO (Byte); + + type Int7 is mod 2**7; + + package Int7_IO is new Ada.Text_IO.Modular_IO (Int7); + + type VLQ_Octet is record + Value : Int7 := 0; + Next : Boolean := True; + end record; + pragma Pack (VLQ_Octet); + for VLQ_Octet'Size use 8; + + function VLQ_To_Byte is new Ada.Unchecked_Conversion (VLQ_Octet, Byte); + function Byte_To_VLQ is new Ada.Unchecked_Conversion (Byte, VLQ_Octet); + + package VLQ_Vectors is new Ada.Containers.Vectors (Natural, VLQ_Octet); + + procedure Hex_Print (Position : in VLQ_Vectors.Cursor) is + Value : Byte := VLQ_To_Byte (VLQ_Vectors.Element (Position)); + begin + Ada.Text_IO.Put (':'); + Byte_IO.Put (Item => Value, Width => 6, Base => 16); + end Hex_Print; + + procedure Print (X : VLQ_Vectors.Vector) is + begin + X.Iterate (Hex_Print'Access); + Ada.Text_IO.New_Line; + end Print; + + function To_VLQ (From : Natural) return VLQ_Vectors.Vector is + Result : VLQ_Vectors.Vector; + Current : Natural := From; + Element : VLQ_Octet; + begin + loop + Element.Value := Int7 (Current mod 2**7); + Result.Prepend (Element); + Current := Current / 2**7; + exit when Current = 0; + end loop; + Element := Result.Last_Element; + Element.Next := False; + VLQ_Vectors.Replace_Element (Result, Result.Last, Element); + return Result; + end To_VLQ; + + function To_Int (From : VLQ_Vectors.Vector) return Natural is + use type VLQ_Vectors.Cursor; + Result : Natural := 0; + Iterator : VLQ_Vectors.Cursor := From.First; + begin + while Iterator /= VLQ_Vectors.No_Element loop + Result := Result * 2**7; + Result := Result + Natural(VLQ_Vectors.Element (Iterator).Value); + VLQ_Vectors.Next (Iterator); + end loop; + return Result; + end To_Int; + + Test : VLQ_Vectors.Vector; +begin + Test := To_VLQ (16#7f#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#4000#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#0#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#3FFFFE#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#1FFFFF#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); + Test := To_VLQ (16#200000#); + Nat_IO.Put (To_Int (Test), 10, 16); Ada.Text_IO.Put (" = "); + Print (Test); +end VLQ; diff --git a/Task/Variable-length-quantity/Crystal/variable-length-quantity.cr b/Task/Variable-length-quantity/Crystal/variable-length-quantity.cr new file mode 100644 index 0000000000..fde2952070 --- /dev/null +++ b/Task/Variable-length-quantity/Crystal/variable-length-quantity.cr @@ -0,0 +1,23 @@ +def vl_encode (n) + raise "negative numbers aren't vl-encodeable" unless n >= 0 + bytes_needed = n == 0 ? 1 : (n.bit_length - 1) // 7 + 1 + bytes = Bytes.new(bytes_needed) + (0...bytes_needed).reverse_each do |i| + bytes[i] = (n & 127).to_u8 | 128 + n >>= 7 + end + bytes[-1] &= 127 + bytes +end + +def vl_decode (bytes) + size = (bytes.size - 1) * 7 + (bytes[0] & 127).bit_length + n = size > 63 ? 0.to_i128 : size > 31 ? 0.to_i64 : 0 + bytes.reduce(n) {|result, byte| (result << 7) + (byte & 127) } +end + +[0x200000, 0x1fffff].each do |n| + encoded = vl_encode(n) + decoded = vl_decode(encoded) + puts "%8d %12s %8d" % { n, encoded.map {|b| "%02x" % b }.join(":"), decoded } +end diff --git a/Task/Variable-length-quantity/D/variable-length-quantity.d b/Task/Variable-length-quantity/D/variable-length-quantity.d index 732ac78796..793f87e114 100644 --- a/Task/Variable-length-quantity/D/variable-length-quantity.d +++ b/Task/Variable-length-quantity/D/variable-length-quantity.d @@ -21,8 +21,8 @@ struct VLQ { "Too large for ulong or invalid format."); else value = (t << 7) | v[idx]; - return idx + 1; - } + return cast(uint) idx + 1; + } VLQ from(in ubyte[] v) pure { extract(v); @@ -54,7 +54,6 @@ struct VLQ { } } - void main() { // VLQ demo code. VLQ a = VLQ(0x7f), b = VLQ(0x4000), diff --git a/Task/Variable-length-quantity/Euphoria/variable-length-quantity.eu b/Task/Variable-length-quantity/Euphoria/variable-length-quantity.eu new file mode 100644 index 0000000000..3a8c22f055 --- /dev/null +++ b/Task/Variable-length-quantity/Euphoria/variable-length-quantity.eu @@ -0,0 +1,41 @@ +function vlq_encode(integer n) + sequence s + s = {} + while n > 0 do + s = prepend(s, #80 * (length(s) > 0) + and_bits(n, #7F)) + n = floor(n / #80) + end while + if length(s) = 0 then + s = {0} + end if + return s +end function + +function vlq_decode(sequence s) + integer n + n = 0 + for i = 1 to length(s) do + n *= #80 + n += and_bits(s[i], #7F) + if not and_bits(s[i], #80) then + exit + end if + end for + return n +end function + +function svlg(sequence s) + sequence out + out = "" + for i = 1 to length(s) do + out &= sprintf("#%02x:", {s[i]}) + end for + return out[1..$-1] +end function + +constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 } +sequence s +for i = 1 to length(testNumbers) do + s = vlq_encode(testNumbers[i]) + printf(1, "#%02x -> %s -> #%02x\n", {testNumbers[i], svlg(s), vlq_decode(s)}) +end for diff --git a/Task/Variable-length-quantity/F-Sharp/variable-length-quantity.fs b/Task/Variable-length-quantity/F-Sharp/variable-length-quantity.fs new file mode 100644 index 0000000000..d42e52a3c2 --- /dev/null +++ b/Task/Variable-length-quantity/F-Sharp/variable-length-quantity.fs @@ -0,0 +1,17 @@ +let to_vlq n = + let a, b = n >>> 7, n &&& 0x7F + let rec aux n acc = + let x,xs = (n &&& 0x7F) ||| 0x80, n >>> 7 + if xs > 0 then aux xs (x::acc) else x::acc + aux a [b] + +let to_num = List.fold (fun n x -> (n <<< 7) + (x &&& 0x7F)) 0 + +let v_rep n = + let seq = to_vlq n + printf "%d ->" n + List.iter (printf " 0x%02X") seq + printfn " -> %d" (to_num seq) + +v_rep 0x200000 +v_rep 0x1FFFFF diff --git a/Task/Variable-length-quantity/Julia/variable-length-quantity.jl b/Task/Variable-length-quantity/Julia/variable-length-quantity.jl index a85b89efc3..9c18daf601 100644 --- a/Task/Variable-length-quantity/Julia/variable-length-quantity.jl +++ b/Task/Variable-length-quantity/Julia/variable-length-quantity.jl @@ -1,33 +1,35 @@ using Printf mutable struct VLQ - quant::Vector{UInt8} + quant::Vector{UInt8} end function VLQ(n::T) where T <: Integer - quant = UInt8.(digits(n, 128)) - @inbounds for i in 2:length(quant) quant[i] |= 0x80 end - VLQ(reverse(quant)) + quant = UInt8.(digits(n, base = 128)) + @inbounds for i in 2:lastindex(quant) + quant[i] |= 0x80 + end + VLQ(reverse(quant)) end import Base.UInt64 function Base.UInt64(vlq::VLQ) - quant = reverse(vlq.quant) - n = shift!(quant) - p = one(UInt64) - for i in quant - p *= 0x80 - n += p * ( i & 0x7f) - end - return n + quant = reverse(vlq.quant) + n = popfirst!(quant) + p = one(UInt64) + for i in quant + p *= 0x80 + n += p * (i & 0x7f) + end + return n end const test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f, - 0x00000080, 0x00002000, 0x00003fff, 0x00004000, - 0x08000000, 0x0fffffff] + 0x00000080, 0x00002000, 0x00003fff, 0x00004000, + 0x08000000, 0x0fffffff] for i in test - vlq = VLQ(i) - j = UInt(vlq) - @printf "0x%-8x => [%-25s] => 0x%x\n" i join(("0x" * hex(r, 2) for r in vlq.quant), ", ") j + vlq = VLQ(i) + j = UInt(vlq) + @printf "0x%-8x => [%-25s] => 0x%x\n" i join(("0x" * string(r, base = 16, pad = 2) for r in vlq.quant), ", ") j end diff --git a/Task/Variable-length-quantity/Phix/variable-length-quantity.phix b/Task/Variable-length-quantity/Phix/variable-length-quantity.phix index 181c4aed19..7b0cd84d8d 100644 --- a/Task/Variable-length-quantity/Phix/variable-length-quantity.phix +++ b/Task/Variable-length-quantity/Phix/variable-length-quantity.phix @@ -1,43 +1,38 @@ ---> - function vlq_encode(sequence s) - sequence res = {} - for i=length(s) to 1 by -1 do - integer n = s[i], msb = 0 - if n<0 then crash("unsigned integers only!") end if - while 1 do - res = prepend(res,msb+and_bits(n,#7F)) - n = floor(n/#80) - if n=0 then exit end if - msb = #80 - end while - end for - return res - end function +with javascript_semantics - function vlq_decode(sequence s) - sequence res = {} - for i=1 to length(s) do - integer si = s[i], - n = n*#80+and_bits(byte,#7F) - if not and_bits(si,#80) then - res = append(res,n) - n = 0 - end if - end for - return res - end function +function vlq_encode(sequence s) + sequence res = {} + for i=length(s) to 1 by -1 do + integer n = s[i], msb = 0 + if n<0 then crash("unsigned integers only!") end if + while 1 do + res = prepend(res,msb+and_bits(n,#7F)) + n = floor(n/#80) + if n=0 then exit end if + msb = #80 + end while + end for + return res +end function - function svlg(sequence s) - string res = "" - for i=1 to length(s) do - res &= sprintf("#%02x:",{s[i]}) - end for - return res[1..$-1] - end function +function vlq_decode(sequence s) + sequence res = {} + integer n = 0 + for si in s do + n = n*#80+and_bits(si,#7F) + if not and_bits(si,#80) then + res = append(res,n) + n = 0 + end if + end for + return res +end function - constant testNumbers = { #200000, #1FFFFF, 1, 127, 128 } - sequence s = vlq_encode(testNumbers), - decoded = vlq_decode(s) - printf(1,"%s -> %s -> %s\n",{svlg(testNumbers),svlg(s),svlg(decoded)}) - if decoded!=testNumbers then crash("something wrong") end if -" +szIndent1: .asciz "| " +.align 4 +ptHeapReserve: .quad heapReserve +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss // INFO: bss +.align 4 +sConvArea: .skip 24 +stTree: .skip tree_fin // place to structure tree +heapReserve: .skip HEAPSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: // INFO: main + ldr x0,qAdrszMessDebutPgm + bl affichageMess + mov x1,1 // node tree value +1: + ldr x0,qAdrstTree // structure tree address + bl insertElement // add element value x1 + cmp x0,-1 + beq 99f + add x1,x1,1 // increment value + cmp x1,NBVAL // end ? + ble 1b // no -> loop + + ldr x0,qAdrszMessDisplayTree + bl affichageMess + ldr x3,qAdrstTree // tree root address (begin structure) + ldr x0,[x3,#tree_root] + mov x1,0 // level + bl displayTree + + ldr x0,qAdrszMessFinOK + bl affichageMess + b 100f +99: // display error + ldr x0,qAdrszMessErreur + bl affichageMess +100: // standard end of the program + mov x8,EXIT // request to exit program + svc 0 // perform system call +qAdrszMessDebutPgm: .quad szMessDebutPgm +qAdrszMessFinOK: .quad szMessFinOK +qAdrszMessDisplayTree: .quad szMessDisplayTree +qAdrszMessErreur: .quad szMessErreur +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrstTree: .quad stTree +qAdrdisplayElement: .quad displayElement +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* x0 contains the address of the tree structure */ +/* x1 contains the value of element */ +/* x0 returns address of element or - 1 if error */ +insertElement: // INFO: insertElement + stp x1,lr,[sp,-16]! // save registers + mov x4,x0 + mov x0,node_fin // reservation place one element + bl allocHeap + cmp x0,-1 // allocation error + beq 100f + mov x5,x0 + str x1,[x5,node_value] // store value in address heap + mov x1,0 + str x1,[x5,node_left] // init left pointer with zero + str x1,[x5,node_right] // init right pointer with zero + ldr x2,[x4,tree_size] // load tree size + cbnz x2,1f // 0 element ? + str x5,[x4,tree_root] // yes -> store in root + b 6f +1: // else search free address in tree + ldr x3,[x4,tree_root] // start with address root + add x6,x2,1 // increment tree size + clz x7,x6 // compute zeroes left bits + add x7,x7,1 // for sustract the first left bit + lsl x6,x6,x7 // shift number in left +2: + tst x6,1<<63 // test left bit + lsl x6,x6,1 // shift left bit + bne 3f // bit at one + ldr x1,[x3,node_left] // no store node address in left pointer + cbz x1,4f // if equal zero + mov x3,x1 // else loop with next node + b 2b +3: // yes + ldr x1,[x3,node_right] // store node address in right pointer + cbz x1,5f // if equal zero + mov x3,x1 // else loop with next node + b 2b +4: + str x5,[x3,node_left] + b 6f +5: + str x5,[x3,node_right] +6: + add x2,x2,1 // increment tree size + str x2,[x4,tree_size] +100: + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +/******************************************************************/ +/* display tree */ +/******************************************************************/ +/* x0 contains the address of the tree */ +/* x1 level */ +displayTree: + stp x2,lr,[sp,-16]! // save registers + stp x3,x4,[sp,-16]! // save registers + stp x5,x6,[sp,-16]! + cmp x0,#-1 + beq 100f + mov x4,x0 + mov x5,x1 + mov x2,#0 + ldr x3,qAdrszIndent1 +1: + cmp x2,x1 + bge 2f + mov x0,x3 + bl affichageMess + add x2,x2,#1 + b 1b +2: + ldr x0,qAdrszIndent + bl affichageMess + ldr x0,[x4,#node_value] + ldr x1,qAdrsConvArea + bl conversion10S + // ldr x0,qAdrsConvArea + // bl shiftResult + ldr x0,qAdrsConvArea + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + ldr x0,[x4,#node_left] + cmp x0,#0 + beq 3f + add x1,x5,#1 // increment level + bl displayTree +3: + ldr x0,[x4,#node_right] + cmp x0,#0 + beq 4f + add x1,x5,#1 // increment level + bl displayTree + b 100f +4: + mov x0,#-1 +100: + ldp x5,x6,[sp],16 + ldp x3,x4,[sp],16 // restaur 2 registers + ldp x2,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrszIndent: .quad szIndent +qAdrszIndent1: .quad szIndent1 +qAdrsConvArea: .quad sConvArea +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* x0 contains node address */ +displayElement: + stp x1,lr,[sp,-16]! // save registers + ldr x0,[x0,#node_value] + ldr x1,qAdrsConvArea + bl conversion10S + ldr x0,qAdrszMessResult + ldr x1,qAdrsConvArea + bl strInsertAtCharInc // insert result at @ character + bl affichageMess +100: + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrszMessResult: .quad szMessResult + +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* x0 contains the size to allocate */ +/* x0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: // INFO: allocHeap + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + // allocation + ldr x1,qAdrptHeapReserve + ldr x2,[x1] // free heap address + add x3,x2,x0 // reserve area on heap + ldr x4,qAdrheapReserve + mov x0,#HEAPSIZE + add x4,x4,x0 // compute heap end + cmp x3,x4 + blt 1f // allocation address < heap end ? + mov x0,#-1 // allocation error + b 100f +1: + str x3,[x1] // store new start free address heap + mov x0,x2 // return address +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrptHeapReserve: .quad ptHeapReserve +qAdrheapReserve: .quad heapReserve +/***********************************************/ +/* File Include fonctions */ +/********************************************************/ +/* for this file see task include a file in language AArch64 assembly */ +.include "../includeARM64.inc" diff --git a/Task/Visualize-a-tree/ARM-Assembly/visualize-a-tree.arm b/Task/Visualize-a-tree/ARM-Assembly/visualize-a-tree.arm new file mode 100644 index 0000000000..63f6ab171a --- /dev/null +++ b/Task/Visualize-a-tree/ARM-Assembly/visualize-a-tree.arm @@ -0,0 +1,283 @@ +/* ARM assembly Raspberry PI */ +/* program displaytree.s */ +/* REMARK 1 : this program use routines in a include file + see task Include a file language arm assembly + for the routine affichageMess conversion10 + see at end of this program the instruction include */ + +/*******************************************/ +/* Constantes */ +/*******************************************/ +.include "../constantes.inc" +.equ HEAPSIZE, 50000 +.equ NBVAL, 9 +/*******************************************/ +/* Macros */ +/*******************************************/ +//.include "../../ficmacros32.inc" @ for developer debugging + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure tree */ + .struct 0 +tree_root: @ root pointer + .struct tree_root + 4 +tree_size: @ number of element of tree + .struct tree_size + 4 +tree_fin: +/* structure node tree */ + .struct 0 +node_left: @ left pointer + .struct node_left + 4 +node_right: @ right pointer + .struct node_right + 4 +node_value: @ element value + .struct node_value + 4 +node_fin: + +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessDebutPgm: .asciz "Program 32 bits start. \n" +szMessFinOK: .asciz "Program normal end. \n" +szMessDisplayTree: .asciz "Tree display :\n" +szCarriageReturn: .asciz "\n" +/* datas error display */ +szMessErreur: .asciz "Error detected.\n" +/* datas message display */ +szMessResult: .ascii "Element value :" +sValue: .space 12,' ' + .asciz "\n" +szIndent: .asciz "|-->" +szIndent1: .asciz "| " +.align 2 +ptHeapReserve: .int heapReserve +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +sConvArea: .skip 24 +stTree: .skip tree_fin @ place to structure tree +heapReserve: .skip HEAPSIZE +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: + ldr r0,iAdrszMessDebutPgm + bl affichageMess + mov r1,#1 @ node tree value +1: + ldr r0,iAdrstTree @ structure tree address + bl insertElement @ add element value r1 + cmp r0,#-1 + beq 99f + add r1,#1 @ increment value + cmp r1,#NBVAL @ end ? + ble 1b @ no -> loop + + ldr r0,iAdrszMessDisplayTree + bl affichageMess + ldr r3,iAdrstTree @ tree root address (begin structure) + ldr r0,[r3,#tree_root] + mov r1,#0 + bl displayTree + + ldr r0,iAdrszMessFinOK + bl affichageMess + b 100f +99: @ display error + ldr r0,iAdrszMessErreur + bl affichageMess +100: @ standard end of the program + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessDebutPgm: .int szMessDebutPgm +iAdrszMessFinOK: .int szMessFinOK +iAdrszMessDisplayTree: .int szMessDisplayTree +iAdrszMessErreur: .int szMessErreur +iAdrszCarriageReturn: .int szCarriageReturn +iAdrstTree: .int stTree +iAdrdisplayElement: .int displayElement +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* r0 contains the address of the tree structure */ +/* r1 contains the value of element */ +/* r0 returns address of element or - 1 if error */ +insertElement: + push {r1-r7,lr} @ save registers + mov r4,r0 + mov r0,#node_fin @ reservation place one element + bl allocHeap + cmp r0,#-1 @ allocation error + beq 100f + mov r5,r0 + str r1,[r5,#node_value] @ store value in address heap + mov r1,#0 + str r1,[r5,#node_left] @ init left pointer with zero + str r1,[r5,#node_right] @ init right pointer with zero + ldr r2,[r4,#tree_size] @ load tree size + cmp r2,#0 @ 0 element ? + bne 1f + str r5,[r4,#tree_root] @ yes -> store in root + b 4f +1: @ else search free address in tree + ldr r3,[r4,#tree_root] @ start with address root + add r6,r2,#1 @ increment tree size + clz r7,r6 @ compute zeroes left bits + add r7,#1 @ for sustract the first left bit + lsl r6,r7 @ shift number in left +2: + lsls r6,#1 @ read left bit + bcs 3f @ is 1 ? + ldr r1,[r3,#node_left] @ no store node address in left pointer + cmp r1,#0 @ if equal zero + streq r5,[r3,#node_left] + beq 4f + mov r3,r1 @ else loop with next node + b 2b +3: @ yes + ldr r1,[r3,#node_right] @ store node address in right pointer + cmp r1,#0 @ if equal zero + streq r5,[r3,#node_right] + beq 4f + mov r3,r1 @ else loop with next node + b 2b +4: + add r2,#1 @ increment tree size + str r2,[r4,#tree_size] +100: + pop {r1-r7,pc} @ restaur registers + +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* r0 contains node address */ +displayElement: + push {r1,lr} @ save registers + ldr r0,[r0,#node_value] + ldr r1,iAdrsValue + bl conversion10S + ldr r0,iAdrszMessResult + bl affichageMess +100: + pop {r1,pc} @ restaur registers +iAdrszMessResult: .int szMessResult +iAdrsValue: .int sValue +/******************************************************************/ +/* shift result to left */ +/******************************************************************/ +/* r0 contains conversion area */ +shiftResult: @ INFO: shiftResult + push {r1-r3,lr} @ save registers + mov r2,#0 +1: + ldrb r1,[r0,r2] @ load one char + cmp r1,#0 @ zero -> end + beq 100f + cmp r1,#' ' @ not space ? + bne 2f + add r2,r2,#1 @ else loop + b 1b +2: + mov r3,#0 @ store indice +3: + strb r1,[r0,r3] @ store char in area begin + cmp r1,#0 @ zero -> end + beq 100f + add r2,r2,#1 @ increment indices + add r3,r3,#1 + ldrb r1,[r0,r2] @ load char + b 3b @ and loop + +100: + pop {r1-r3,pc} @ restaur registers +/******************************************************************/ +/* display tree */ +/******************************************************************/ +/* r0 contains node address */ +/* r1 contains level */ + +displayTree: + push {r2-r5,lr} @ save registers + cmp r0,#-1 + beq 100f + mov r4,r0 + mov r5,r1 + mov r2,#0 + ldr r3,iAdrszIndent1 +1: + cmp r2,r1 + bge 2f + mov r0,r3 + bl affichageMess + add r2,r2,#1 + b 1b +2: + ldr r0,iAdrszIndent + bl affichageMess + ldr r0,[r4,#node_value] + ldr r1,iAdrsConvArea + bl conversion10S + ldr r0,iAdrsConvArea + bl shiftResult + ldr r0,iAdrsConvArea + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + ldr r0,[r4,#node_left] + cmp r0,#0 + beq 3f + add r1,r5,#1 @ increment level + bl displayTree +3: + ldr r0,[r4,#node_right] + cmp r0,#0 + beq 4f + add r1,r5,#1 @ increment level + bl displayTree + b 100f +4: + mov r0,#-1 + +100: + pop {r2-r5,pc} @ restaur registers +iAdrszIndent: .int szIndent +iAdrszIndent1: .int szIndent1 +iAdrsConvArea: .int sConvArea +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* r0 contains the size to allocate */ +/* r0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: + push {r1-r4,lr} @ save registers + @ allocation + ldr r1,iAdrptHeapReserve + ldr r2,[r1] @ free heap address + add r3,r2,r0 @ reserve area on heap + ldr r4,iAdrheapReserve + mov r0,#HEAPSIZE + add r4,r4,r0 @ compute heap end + cmp r3,r4 + blt 1f @ allocation address < heap end ? + mov r0,#-1 @ allocation error + b 100f +1: + str r3,[r1] @ store new start free address heap + mov r0,r2 @ return address +100: + pop {r1-r4,pc} @ restaur registers +.align 2 +iAdrptHeapReserve: .int ptHeapReserve +iAdrheapReserve: .int heapReserve + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/Visualize-a-tree/Ada/visualize-a-tree.adb b/Task/Visualize-a-tree/Ada/visualize-a-tree.adb new file mode 100644 index 0000000000..f6afc11509 --- /dev/null +++ b/Task/Visualize-a-tree/Ada/visualize-a-tree.adb @@ -0,0 +1,36 @@ +with Ada.Text_IO, Ada.Directories; + +procedure Directory_Tree is + + procedure Print_Tree(Current: String; Indention: Natural := 0) is + + function Spaces(N: Natural) return String is + (if N= 0 then "" else " " & Spaces(N-1)); + + use Ada.Directories; + Search: Search_Type; + Found: Directory_Entry_Type; + + begin + Start_Search(Search, Current, ""); + while More_Entries(Search) loop + Get_Next_Entry(Search, Found); + declare + Name: String := Simple_Name(Found); + Dir: Boolean := Kind(Found) = Directory; + begin + if Name(Name'First) /= '.' then + -- skip all files who's names start with ".", namely "." and ".." + Ada.Text_IO.Put_Line(Spaces(2*Indention) & Simple_Name(Found) + & (if Dir then " (dir)" else "")); + if Dir then + Print_Tree(Full_Name(Found), Indention + 1); + end if; + end if; + end; + end loop; + end Print_Tree; + +begin + Print_Tree(Ada.Directories.Current_Directory); +end Directory_Tree; diff --git a/Task/Visualize-a-tree/RISC-V-Assembly/visualize-a-tree.asm b/Task/Visualize-a-tree/RISC-V-Assembly/visualize-a-tree.asm new file mode 100644 index 0000000000..5e94ff67e3 --- /dev/null +++ b/Task/Visualize-a-tree/RISC-V-Assembly/visualize-a-tree.asm @@ -0,0 +1,270 @@ +# riscv assembly raspberry pico2 rp2350 +# program displaytree.s +# connexion putty com3 +/*********************************************/ +/* CONSTANTES */ +/********************************************/ +/* for this file see risc-v task include a file */ +.include "../../constantesRiscv.inc" +.equ HEAPSIZE, 50000 +.equ NBVAL, 9 + +/****************************************************/ +/* MACROS */ +/****************************************************/ +#.include "../ficmacrosriscv.inc" # for debugging only + +/*******************************************/ +/* Structures */ +/********************************************/ +/* structure tree */ + .struct 0 +tree_root: # root pointer + .struct tree_root + 4 +tree_size: # number of element of tree + .struct tree_size + 4 +tree_fin: +/* structure node tree */ + .struct 0 +node_left: # left pointer + .struct node_left + 4 +node_right: # right pointer + .struct node_right + 4 +node_value: # element value + .struct node_value + 4 +node_fin: + + +/*******************************************/ +/* INITIALED DATAS */ +/*******************************************/ +.data +szMessStart: .asciz "Program riscv start.\r\n" +szMessEnd: .asciz "\nProgram end OK.\r\n" +szCariageReturn: .asciz "\r\n" +szIndent: .asciz "|-->" +szIndent1: .asciz "| " + +szMessDisplayTree: .asciz "Tree display :\n" + +szMessResult: .asciz "Element value : " +.align 2 +ptHeapReserve: .int heapReserve + + +.align 2 +/*******************************************/ +/* UNINITIALED DATA */ +/*******************************************/ +.bss +.align 2 +sConvArea: .skip 24 +stTree: .skip tree_fin # place to structure tree +heapReserve: .skip HEAPSIZE +/********************************...-..--*****/ +/* SECTION CODE */ +/**********************************************/ +.text +.global main + +main: # INFO: main + call stdio_init_all # général init +1: # start loop connexion + li a0,0 # raz argument register + call tud_cdc_n_connected # waiting for USB connection + beqz a0,1b # return code = zero ? + + la a0,szMessStart # message address + call writeString # display message + li s0,1 +1: + la a0,stTree + mv a1,s0 # value + call insertElement + li t0,-1 + beq a0,t0,100f + addi s0,s0,1 + li t0,NBVAL + ble s0,t0,1b + + la a0,szMessDisplayTree + call writeString + + la a0,stTree + lw a0,tree_root(a0) + li a1,0 + call displayTree + + la a0,szMessEnd + call writeString + call getchar +100: # final loop + j 100b +/******************************************************************/ +/* insert element in the tree */ +/******************************************************************/ +/* a0 contains the address of the tree structure */ +/* a1 contains the value of element */ +/* a0 returns address of element or - 1 if error */ +insertElement: # INFO: insertElement + addi sp, sp, -8 # save registres + sw ra, 0(sp) + sw s0,4(sp) + mv s0,a0 + li a0,node_fin # reservation place one element + call allocHeap + li t0,-1 + beq a0,t0,100f # allocation error + mv t0,a0 # save address + sw a1,node_value(t0) # store value in address heap + sw x0,node_left(t0) # init left pointer with zero + sw x0,node_right(t0) # init right pointer with zero + lw t1,tree_size(s0) # load tree size + bnez t1,1f # 0 element + sw t0,tree_root(s0) # yes -> store in root + j 4f +1: # else search free address in tree + lw t2,tree_root(s0) # start with address root + mv t5,a1 # value node + clz t3,t5 # compute zeroes left bits + addi t3,t3,1 # for sustract the first left bit + sll t5,t5,t3 # shift number in left +2: + slt t4,t5,x0 # is bit31 = 1 + slli t5,t5,1 + bnez t4,3f # is bit31 = 1 + lw t4,node_left(t2) # no store node address in left pointer + bnez t4,21f # equal zero ? + sw t0,node_left(t2) + j 4f +21: + mv t2,t4 # else loop with next node + j 2b +3: + lw t4,node_right(t2) # no store node address in right pointer + bnez t4,31f # equal zero ? + sw t0,node_right(t2) + j 4f +31: + mv t2,t4 # else loop with next node + j 2b # and loop +4: + addi t1,t1,1 + sw t1,tree_size(s0) + mv a0,t0 + +100: + lw ra, 0(sp) + lw s0,4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* display node */ +/******************************************************************/ +/* a0 contains node address */ +displayElement: # INFO: displayElement + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + sw s0,4(sp) + lw a0,node_value(a0) + la a1,sConvArea + call conversion10S + la a0,szMessResult + call writeString + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString +100: + lw ra, 0(sp) + lw s0, 4(sp) + addi sp, sp, 8 + ret +/******************************************************************/ +/* Display tree */ +/******************************************************************/ +/* a0 contains tree address */ +/* a1 level */ +/* a0 returns 0 if empty else 1 */ +displayTree: # INFO: displayTree + addi sp, sp, -20 # reserve stack + sw ra, 0(sp) + sw s0, 4(sp) + sw s1, 8(sp) + sw s2, 12(sp) + sw s3, 16(sp) + li t0,-1 + beq a0,t0,100f + mv s0,a0 + mv s1,a1 + li s2,0 + la s3,szIndent1 +1: # display indentation loop + bge s2,s1,2f + mv a0,s3 + call writeString + addi s2,s2,1 + j 1b +2: + la a0,szIndent + call writeString + # affregtit debut1 + lw a0,node_value(s0) + la a1,sConvArea + call conversion10S + la a0,sConvArea + call writeString + la a0,szCariageReturn + call writeString + + lw a0,node_left(s0) + beqz a0,3f + addi a1,s1,1 + call displayTree +3: + lw a0,node_right(s0) + beqz a0,4f + addi a1,s1,1 + call displayTree + j 100f +4: + li a0,-1 + +100: + lw ra, 0(sp) + lw s0, 4(sp) + lw s1, 8(sp) + lw s2, 12(sp) + lw s3, 16(sp) + addi sp, sp, 20 +/******************************************************************/ +/* memory allocation on the heap */ +/******************************************************************/ +/* a0 contains the size to allocate */ +/* a0 returns address of memory heap or - 1 if error */ +/* CAUTION : The size of the allowance must be a multiple of 4 */ +allocHeap: # INFO: allocHeap + addi sp, sp, -8 # reserve stack + sw ra, 0(sp) + la t0,ptHeapReserve + lw t1,(t0) # free heap address + add t2,t1,a0 # reserve area on heap + la t3,heapReserve + li t4,HEAPSIZE + add t3,t3,t4 # compute heap end + blt t2,t3,1f # allocation address < heap end ? + li a0,-1 # allocation error + j 100f +1: + sw t2,(t0) # store new start free address heap + mv a0,t1 # return address +100: + lw ra, 0(sp) + addi sp, sp, 8 + ret + +/************************************/ +/* file include Fonctions */ +/***********************************/ +/* for this file see risc-v task include a file */ +.include "../../includeFunctions.s" diff --git a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy index 55184002d9..791ccadb21 100644 --- a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy +++ b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy @@ -3,9 +3,9 @@ func hypo a b . . nsites = 25 for i to nsites - nx[] &= random 1001 - 1 - ny[] &= random 1001 - 1 - nc[] &= random 1000 - 1 + nx[] &= random 0 999 + ny[] &= random 0 999 + nc[] &= random 0 999 . for y = 0 to 1000 for x = 0 to 1000 diff --git a/Task/Voronoi-diagram/Pluto/voronoi-diagram.pluto b/Task/Voronoi-diagram/Pluto/voronoi-diagram.pluto new file mode 100644 index 0000000000..cc96a68653 --- /dev/null +++ b/Task/Voronoi-diagram/Pluto/voronoi-diagram.pluto @@ -0,0 +1,42 @@ +require "bitmap" + +local rand = math.random +local distsq = bitmap.distanceSquared + +local function clamp(v, size) + size -= 1 + if v < 2 then return v + 2 end + if v > size - 2 then return size - 2 end + return v +end + +local function voronoi(bmp, cells, size) + local px = {} + local py = {} + local cl = {} + for i = 1, cells do + px[i] = rand(0, size - 1) + py[i] = rand(0, size - 1) + cl[i] = bitmap.rgbColor(rand(0, 255), rand(0, 255), rand(0, 255)) + end + for x = 0, size - 1 do + for y = 0, size - 1 do + local n = 1 + for i = 1, cells do + if distsq(px[i], py[i], x, y) < distsq(px[n], py[n], x, y) then + n = i + end + end + bmp:set(x, y, cl[n]) + end + end + for i = 1, cells do + bmp:circle(clamp(px[i], size), clamp(py[i], size), 1, color.black) + end +end + +local cells = 70 +local size = 700 +local bmp = bitmap.of(size, size, color.black, "Voronoi_diagram") +voronoi(bmp, cells, size) +bmp:view() diff --git a/Task/Voronoi-diagram/ReScript/voronoi-diagram.res b/Task/Voronoi-diagram/ReScript/voronoi-diagram.res new file mode 100644 index 0000000000..d2f77ef25d --- /dev/null +++ b/Task/Voronoi-diagram/ReScript/voronoi-diagram.res @@ -0,0 +1,66 @@ +let n_sites = 60 + +let size_x = 640 +let size_y = 480 + +let rand_int_range = (a, b) => a + Random.int(b - a + 1) + +let dist_euclidean = (x, y) => { (x * x + y * y) } +let dist_minkowski = (x, y) => { (x * x * x + y * y * y) } +let dist_taxicab = (x, y) => { abs(x) + abs(y) } + +let dist_f = dist_euclidean +let dist_f = dist_minkowski +let dist_f = dist_taxicab + +let nearest_site = (site, x, y) => { + let ret = ref(0) + let dist = ref(0) + Js.Array2.forEachi(site, ((sx, sy), k) => { + let d = dist_f((x - sx), (y - sy)) + if (k == 0 || d < dist.contents) { + dist.contents = d + ret.contents = k + } + }) + ret.contents +} + +let gen_map = (site, rgb) => { + let nearest = Belt.Array.make((size_x * size_y), 0) + let buf = Belt.Array.make((3 * size_x * size_y), 0) + + for y in 0 to size_y - 1 { + for x in 0 to size_x - 1 { + nearest[y * size_x + x] = nearest_site(site, x, y) + } + } + + for i in 0 to (size_y * size_x) - 1 { + let j = i * 3 + let (r, g, b) = rgb[nearest[i]] + buf[j+0] = r + buf[j+1] = g + buf[j+2] = b + } + + Printf.printf("P3\n%d %d\n255\n", size_x, size_y) + Js.Array2.forEach(buf, (d) => Printf.printf("%d\n", d)) +} + +{ + Random.self_init (); + let site = + Belt.Array.makeBy(n_sites, (i) => { + (Random.int(size_x), + Random.int(size_y)) + }) + + let rgb = + Belt.Array.makeBy(n_sites, (i) => { + (rand_int_range( 50, 120), + rand_int_range( 80, 180), + rand_int_range(140, 240)) + }) + gen_map(site, rgb) +} diff --git a/Task/Voronoi-diagram/Uiua/voronoi-diagram.uiua b/Task/Voronoi-diagram/Uiua/voronoi-diagram.uiua new file mode 100644 index 0000000000..4a09efa4a6 --- /dev/null +++ b/Task/Voronoi-diagram/Uiua/voronoi-diagram.uiua @@ -0,0 +1,7 @@ +N ← 50 +Cs ← ≡°hsv⍥(÷10˜⊂8_8×60⚂)300 # Generate some colours. +↯∞_2⍥⟜(⌊×⚂)×2N⟜∘300 # N random centres in grid. +⊃⊙∘∘ # Copy centres for later. +≡(˜⨂⊸/↧√≡/+ⁿ2˜-⊙¤)¤⊙(♭₂˙⊞⊟⇡) # Find nearest centres. +↯⇌[3 ⟜∘ ∘]√⊸⧻≡⌞˜⊡Cs # Colour grid. +˜∧⍜⊡⋅1_1_1 # Add in centres. diff --git a/Task/Wagstaff-primes/AWK/wagstaff-primes.awk b/Task/Wagstaff-primes/AWK/wagstaff-primes.awk new file mode 100644 index 0000000000..d938dbc045 --- /dev/null +++ b/Task/Wagstaff-primes/AWK/wagstaff-primes.awk @@ -0,0 +1,25 @@ +# syntax: GAWK -f WAGSTAFF_PRIMES.AWK +BEGIN { + p = 1 + while (count < 10) { + p += 2 + if (is_prime(p)) { + w = (2^p+1) / 3 + if (is_prime(w)) { + printf("%2d: %3d %14d\n",++count,p,w) + } + } + } + exit(0) +} +function is_prime(x, i) { + if (x <= 1) { + return(0) + } + for (i=2; i<=int(sqrt(x)); i++) { + if (x % i == 0) { + return(0) + } + } + return(1) +} diff --git a/Task/Wagstaff-primes/Ada/wagstaff-primes.adb b/Task/Wagstaff-primes/Ada/wagstaff-primes.adb new file mode 100644 index 0000000000..92d3590f3a --- /dev/null +++ b/Task/Wagstaff-primes/Ada/wagstaff-primes.adb @@ -0,0 +1,34 @@ +with Ada.Text_IO; use Ada.Text_IO; + +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Wagstaff is + M : Unbounded_Unsigned; + Count : Integer := 16; + + procedure Check (P : Half_Word) is + begin + if Is_Prime (P) = Prime then + M := (Power_Of_Two (Bit_Count (P)) + 1) / 3; + if Is_Prime (M, 10) = Prime then + Count := Count - 1; + Put_Line + ( "p =" & Half_Word'Image (P) & Character'Val (9) + & " m = " & Image (M) + ); + end if; + end if; + end Check; +begin + Check (3); + for N in Half_Word range 1..Half_Word'Last loop + Check (N * 6 - 1); + exit when Count <= 0; + Check (N * 6 + 1); + exit when Count <= 0; + end loop; +end Wagstaff; diff --git a/Task/Wagstaff-primes/Crystal/wagstaff-primes.cr b/Task/Wagstaff-primes/Crystal/wagstaff-primes.cr new file mode 100644 index 0000000000..e941f07daf --- /dev/null +++ b/Task/Wagstaff-primes/Crystal/wagstaff-primes.cr @@ -0,0 +1,22 @@ +struct Int + def prime? # P3 Prime Generator primality test + return self | 1 == 3 if self < 5 + return false if self.gcd(6) != 1 + sqrt_n = Math.isqrt(self) + pc = typeof(self).new(5) + while pc <= sqrt_n + return false if self % pc == 0 || self % (pc + 2) == 0 + pc += 6 + end + true + end +end + +(3i64..).each.compact_map {|p| + if p.prime? + w = (2i64**p + 1) // 3 + { p, w } if w.prime? + end +}.first(10).each do |p, w| + printf "%3d: %d\n", p, w +end diff --git a/Task/Wagstaff-primes/FutureBasic/wagstaff-primes.basic b/Task/Wagstaff-primes/FutureBasic/wagstaff-primes.basic new file mode 100644 index 0000000000..793ad7b4d3 --- /dev/null +++ b/Task/Wagstaff-primes/FutureBasic/wagstaff-primes.basic @@ -0,0 +1,149 @@ +// ----------------------------------------------- +// Wagstaff primes +// Using FutureBasic 7.0.36 +// +// November 2025, R.W +// +// ----------------------------------------------- + +include "gmp.incl" + +_kPrimeReps = 25 +_kNeedFirst = 10 +_kNeedMore = 14 + +// mpz_sizeinbase sometimes would return one digit too many especially +// when the value is close to the edge of power of 10. This helper +// accounts for that and adjusts. + +local fn mpz_digits10( z as mpz_t ) as int + int d + mpz_t pow10 + d = fn mpz_sizeinbase( z, 10 ) + if d <= 1 then RETURN d + mpz_init( pow10 ) + // pow10 = 10^(d-1) + fn mpz_ui_pow_ui( pow10, 10, d - 1 ) + // If z < 10^(d-1) then mpz_sizeinbase returned one too many + if fn mpz_cmp( z, pow10 ) < 0 then d = d - 1 //if so -> decrement + mpz_clear( pow10 ) +end fn = d + +local fn IsSmallPrime( n as UInt32 ) as boolean + if n < 2 then RETURN _false + if n = 2 then RETURN _true + if (n AND 1) == 0 then RETURN _false + mpz_t t + mpz_init( t ) + fn mpz_set_ui( t, n ) + int r : r = fn mpz_probab_prime_p( t, _kPrimeReps ) + mpz_clear( t ) + if r > 0 then RETURN _true +end fn = _false + +// Find the next upstream prime + +local fn NextPrimeAfter( startN as UInt32 ) as UInt32 + UInt32 p + if startN < 2 then RETURN 2 + p = startN + 1 + if (p AND 1) = 0 then p = p + 1 + while _true + if fn IsSmallPrime( p ) then RETURN p + p = p + 2 + wend +end fn = 0 + +// Abbreviate long strings + +local fn AbbrevLongStr( longStr as CFStringRef ) as CFStringRef + CFStringRef outStr, leftStr,rightStr + CFIndex strlen + outStr = @"" + strlen = len(longStr) + if strlen < 60 then return longStr + leftStr = left(longStr, 27 ) + rightStr = right(longStr, 28 ) + outStr = concat( leftStr, @"...", rightStr) +end fn = outStr + +// WagStaff_P = (2^p + 1) / 3 → outW + +local fn WagstaffFromExponent( p as UInt32, outW as mpz_t ) as boolean + mpz_t N + mpz_init( N ) + fn mpz_ui_pow_ui( N, 2, p ) + fn mpz_add_ui( N, N, 1 ) + unsigned long remd + remd = fn mpz_fdiv_q_ui( outW, N, 3 ) + mpz_clear( N ) + if remd != 0 then RETURN _false +end fn = _true + +// Use GMP probable prime function with 25 reps +// sufficient to determine a large prime + +local fn IsWagstaffPrime( p as UInt32, outW as mpz_t ) as boolean + if fn WagstaffFromExponent( p, outW ) = _false then RETURN _false + int res : res = fn mpz_probab_prime_p( outW, _kPrimeReps ) + // 0 = composite, 1 = probable, 3 = positive + if res > 0 then RETURN _true +end fn = _false + +// MAIN +// +local fn Main + UInt32 p + UInt32 foundFirst, foundMore + foundFirst = 0 : foundMore = 0 + CFStringRef s2 + + CFTimeInterval t0, t1 + t0 = fn CACurrentMediaTime + + // Rosetta requirement for 10 Wagstaff primes + print @"First 10 Wagstaff primes:\n" + p = fn NextPrimeAfter( 1 ) + while foundFirst < _kNeedFirst + mpz_t W + mpz_init( W ) + if fn IsWagstaffPrime( p, W ) + foundFirst = foundFirst + 1 + // FB has a handy wrapper to obtain CFString from mpz_t output + // toolbox fn mpz_cf2( mpz_t op ) = CFStringRef // mpz_t → CFString (base 10) + CFStringRef s = fn mpz_cf2( W ) + printf @"%4lu: %@", p,s + end if + mpz_clear( W ) + p = fn NextPrimeAfter( p ) + wend + t1 = fn CACurrentMediaTime + printf @"\nElapsed time: %.3f ms\n\n", (t1 - t0) * 1000.0 + + // Rosetta additional task + + print @"Wagstaff next 14:\n" + + CFTimeInterval t2 = fn CACurrentMediaTime + foundMore = 0 + while foundMore < _kNeedMore + mpz_t W2 + mpz_init( W2 ) + if fn IsWagstaffPrime( p, W2 ) + foundMore = foundMore + 1 + int digits : digits = fn mpz_digits10( W2 ) + s2 = fn mpz_cf2( W2 ) //mpz_cf2 is an FB wrapper + s2 = fn AbbrevLongStr(s2) + printf @"%4lu: %@ (%d digits)", p, s2, digits + end if + mpz_clear( W2 ) + p = fn NextPrimeAfter( p ) + wend + + CFTimeInterval t3 = fn CACurrentMediaTime + printf @"\nElapsed time: %.3f secs\n", (t3 - t2) +end fn + +Window 1,@"Wagstaff Primes",(0,0,640,540) +fn Main +HandleEvents diff --git a/Task/Wagstaff-primes/Maxima/wagstaff-primes.maxima b/Task/Wagstaff-primes/Maxima/wagstaff-primes.maxima new file mode 100644 index 0000000000..fb1fb9fb2b --- /dev/null +++ b/Task/Wagstaff-primes/Maxima/wagstaff-primes.maxima @@ -0,0 +1,11 @@ +block( + p: 3, count: 0, while count < 10 do( + m: (2^p+1)/3, + if primep(m) then block( + sprint("p =", p, "m =", m), + newline(), + count: count+1 + ), + p: next_prime(p) + ) +)$ diff --git a/Task/Wagstaff-primes/Phix/wagstaff-primes-1.phix b/Task/Wagstaff-primes/Phix/wagstaff-primes-1.phix new file mode 100644 index 0000000000..77dd80f28c --- /dev/null +++ b/Task/Wagstaff-primes/Phix/wagstaff-primes-1.phix @@ -0,0 +1,49 @@ +with javascript_semantics +atom t0 = time() +include mpfr.e + +function isWagstaff(integer p) + mpz w = mpz_init() + mpz_ui_pow_ui(w,2,p) + mpz_add_si(w,w,1) + assert(mpz_fdiv_q_ui(w,w,3)=0) + return iff(mpz_prime(w)?w:NULL) +end function + +integer p, pdx = 2, extra = 0 +sequence wagstaff = {} +while length(wagstaff)<10 do + p = get_prime(pdx) + atom res = isWagstaff(p) + if res then + string s = mpz_get_str(res,comma_fill:=true) + wagstaff &= {{p,s}} + end if + pdx += 1 +end while +printf(1,"First 10 Wagstaff primes for the values of 'p' shown:\n") +papply(true,printf,{1,{"%2d: %s\n"},wagstaff}) +printf(1,"\nTook %s\n\n",elapsed(time()-t0)) + +printf(1,"Wagstaff primes that we can find in 6 seconds:\n") +while time()> p */ + mpz_sub(s,low,high) /* s:=low-high (gives reduction mod (2^p+1)) */ + /* normalize s to 0..modulus-1 (a single add/subtract suffices) */ + if mpz_sign(s)<0 then + mpz_add(s,s,modulus) + elsif mpz_cmp(s,modulus)>=0 then + mpz_sub(s,s,modulus) + end if + end for + /* check s==25 (mod modulus) ie s is 25 in canonical rep 0..modulus-1 */ + is_ok = (mpz_cmp_si(s,25)==0) + {s,low,high,modulus} = mpz_free({s,low,high,modulus}) + end if + if is_ok then + mpz w = mpz_init() + mpz_ui_pow_ui(w,2,p) + mpz_add_si(w,w,1) + assert(mpz_fdiv_q_ui(w,w,3)=0) + return w + end if + return NULL +end function + +integer p, pdx = 2, count = 0 +printf(1,"Some Wagstaff primes:\n") +--while count<30 do +while count<29 do + p = get_prime(pdx) + atom res = wprp(p) + if res then + count += 1 + string th = ord(count) + if count<=10 then + string s = mpz_get_str(res,comma_fill:=true) + printf(1,"The %2d%s is %5d: %s\n",{count,th,p,s}) + else + integer l = mpz_sizeinbase(res,10) + string e = elapsed(time()-t0,0.2,", %s") + printf(1,"The %d%s is %5d (%,d digits%s)\n",{count,th,p,l,e}) + end if + elsif time()>t1 then +-- progress("%d (%.2f%%)\r",{p,p/42737*100}) + progress("%d (%.2f%%)\r",{p,p/14479*100}) + t1 = time()+1 + end if + pdx += 1 +end while diff --git a/Task/Wagstaff-primes/Unicon/wagstaff-primes.unicon b/Task/Wagstaff-primes/Unicon/wagstaff-primes.unicon new file mode 100644 index 0000000000..9d4445547e --- /dev/null +++ b/Task/Wagstaff-primes/Unicon/wagstaff-primes.unicon @@ -0,0 +1,12 @@ +link fastprime + +procedure main(A) + limit := \A[1] | 24 + write("The first ",limit," Wagstaff primes:") + every (cnt := 0, n := is_wagstaff(p := genprimes(3))\limit, cnt +:= 1) do + write(" (2^",p,"+1)/3",if cnt <= 10 then " = "||n else "") +end + +procedure is_wagstaff(p) + return is_prime((2^p+1)/3) +end diff --git a/Task/Walk-a-directory-Non-recursively/8080-Assembly/walk-a-directory-non-recursively.8080 b/Task/Walk-a-directory-Non-recursively/8080-Assembly/walk-a-directory-non-recursively.8080 index 809da0c075..8023bf40c3 100644 --- a/Task/Walk-a-directory-Non-recursively/8080-Assembly/walk-a-directory-non-recursively.8080 +++ b/Task/Walk-a-directory-Non-recursively/8080-Assembly/walk-a-directory-non-recursively.8080 @@ -1,44 +1,44 @@ -exit: equ 0 ; CP/M syscall to exit -puts: equ 9 ; CP/M syscall to print a string -sfirst: equ 17 ; 'Find First' CP/M syscall -snext: equ 18 ; 'Find Next' CP/M syscall -FCB: equ 5Ch ; Location of FCB for file given on command line - org 100h - lxi d,FCB ; CP/M parses the command line for us automatically - mvi c,sfirst; and prepares an FCB which we can pass to SFIRST - call 5 ; immediately. - lxi d,emsg ; If SFIRST returns an error, there is no file, - mvi c,puts ; so we should print an error message. -loop: inr a ; A=FF = error - jz 5 - dcr a ; If we _do_ have a file, the directory entry - rrc ; is located at DTA (80h) + A * 32. 0<=A<=3. - rrc ; Rotate right twice, moving low bits into high bits, - stc ; then finally rotate a 1 bit into the top bit. - rar ; The effect is 000000AB -> 1AB00000. - inr a ; Finally the filename is at offset 1 in the dirent. - mvi h,0 ; Set HL = pointer to the filename - mov l,a - lxi d,fname ; The filename is stored as 'FILENAMEEXT', but let's - mvi b,8 ; be nice and print 'FILENAME.EXT\r\n'. - call memcpy ; Copy filename (wihtout extension) into placeholder - inx d ; Skip the '.' in the placeholder - mvi b,3 ; Then copy the extension - call memcpy - lxi d,fname ; Then print the formatted filename - mvi c,puts - call 5 - lxi d,FCB ; Find the next file matching the pattern in the FCB - mvi c,snext ; The result is the same as for SFIRST, so we can - call 5 ; loop back here, except FF means no more files. - mvi c,exit ; Arrange for the error routine to instead exit cleanly - jmp loop -memcpy: mov a,m ; Copy B bytes from HL to DE - stax d - inx h - inx d - dcr b - jnz memcpy - ret -emsg: db 'Not Found$' -fname: db 'XXXXXXXX.XXX',13,10,'$' ; Filename placeholder +exit: equ 0 ; CP/M syscall to exit +puts: equ 9 ; CP/M syscall to print a string +sfirst: equ 17 ; 'Find First' CP/M syscall +snext: equ 18 ; 'Find Next' CP/M syscall +FCB: equ 5Ch ; Location of FCB for file given on command line + org 100h + lxi d,FCB ; CP/M parses the command line for us automatically + mvi c,sfirst; and prepares an FCB which we can pass to SFIRST + call 5 ; immediately. + lxi d,emsg ; If SFIRST returns an error, there is no file, + mvi c,puts ; so we should print an error message. +loop: inr a ; A=FF = error + jz 5 + dcr a ; If we _do_ have a file, the directory entry + rrc ; is located at DTA (80h) + A * 32. 0<=A<=3. + rrc ; Rotate right twice, moving low bits into high bits, + stc ; then finally rotate a 1 bit into the top bit. + rar ; The effect is 000000AB -> 1AB00000. + inr a ; Finally the filename is at offset 1 in the dirent. + mvi h,0 ; Set HL = pointer to the filename + mov l,a + lxi d,fname ; The filename is stored as 'FILENAMEEXT', but let's + mvi b,8 ; be nice and print 'FILENAME.EXT\r\n'. + call memcpy ; Copy filename (wihtout extension) into placeholder + inx d ; Skip the '.' in the placeholder + mvi b,3 ; Then copy the extension + call memcpy + lxi d,fname ; Then print the formatted filename + mvi c,puts + call 5 + lxi d,FCB ; Find the next file matching the pattern in the FCB + mvi c,snext ; The result is the same as for SFIRST, so we can + call 5 ; loop back here, except FF means no more files. + mvi c,exit ; Arrange for the error routine to instead exit cleanly + jmp loop +memcpy: mov a,m ; Copy B bytes from HL to DE + stax d + inx h + inx d + dcr b + jnz memcpy + ret +emsg: db 'Not Found$' +fname: db 'XXXXXXXX.XXX',13,10,'$' ; Filename placeholder diff --git a/Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.adb b/Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.adb new file mode 100644 index 0000000000..c243ea48e5 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Ada/walk-a-directory-non-recursively.adb @@ -0,0 +1,19 @@ +with Ada.Directories; use Ada.Directories; +with Ada.Text_IO; use Ada.Text_IO; + +procedure Walk_Directory + (Directory : in String := "."; + Pattern : in String := "") -- empty pattern = all file names/subdirectory names +is + Search : Search_Type; + Dir_Ent : Directory_Entry_Type; +begin + Start_Search (Search, Directory, Pattern); + + while More_Entries (Search) loop + Get_Next_Entry (Search, Dir_Ent); + Put_Line (Simple_Name (Dir_Ent)); + end loop; + + End_Search (Search); +end Walk_Directory; diff --git a/Task/Walk-a-directory-Non-recursively/BASIC256/walk-a-directory-non-recursively.basic b/Task/Walk-a-directory-Non-recursively/BASIC256/walk-a-directory-non-recursively.basic index 4d3d818164..01d7bc91b9 100644 --- a/Task/Walk-a-directory-Non-recursively/BASIC256/walk-a-directory-non-recursively.basic +++ b/Task/Walk-a-directory-Non-recursively/BASIC256/walk-a-directory-non-recursively.basic @@ -2,9 +2,9 @@ call show ("c:\") end subroutine show (pattern$) - f$ = dir(pattern$) - while length(f$) - print f$ - f$ = dir - end while + f$ = dir(pattern$) + while length(f$) + print f$ + f$ = dir + end while end subroutine diff --git a/Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.el b/Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.el new file mode 100644 index 0000000000..3a058d336d --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Emacs-Lisp/walk-a-directory-non-recursively.el @@ -0,0 +1,5 @@ +(directory-files "/some/dir/name" + nil ;; just the filenames, not full paths + "\\.c\\'" ;; regexp + t) ;; don't sort the filenames +;;=> ("foo.c" "bar.c" ...) diff --git a/Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.eu b/Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.eu new file mode 100644 index 0000000000..ddaf437fc9 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Euphoria/walk-a-directory-non-recursively.eu @@ -0,0 +1,12 @@ +include file.e + +procedure show(sequence pattern) + sequence f + f = dir(pattern) + for i = 1 to length(f) do + puts(1,f[i][D_NAME]) + puts(1,'\n') + end for +end procedure + +show("*.*") diff --git a/Task/Walk-a-directory-Non-recursively/Hare/walk-a-directory-non-recursively.hare b/Task/Walk-a-directory-Non-recursively/Hare/walk-a-directory-non-recursively.hare index a3b939791a..b0f118a576 100644 --- a/Task/Walk-a-directory-Non-recursively/Hare/walk-a-directory-non-recursively.hare +++ b/Task/Walk-a-directory-Non-recursively/Hare/walk-a-directory-non-recursively.hare @@ -2,18 +2,18 @@ use fmt; use glob; export fn main() void = { - ls("/etc/*.conf"); + ls("/etc/*.conf"); }; fn ls(pattern: str) void = { - let gen = glob::glob(pattern, glob::flags::NONE); - defer glob::finish(&gen); - for (true) match (glob::next(&gen)) { - case void => - break; - case glob::failure => - continue; - case let s: str => - fmt::printfln("{}", s)!; - }; + let gen = glob::glob(pattern, glob::flags::NONE); + defer glob::finish(&gen); + for (true) match (glob::next(&gen)) { + case void => + break; + case glob::failure => + continue; + case let s: str => + fmt::printfln("{}", s)!; + }; }; diff --git a/Task/Walk-a-directory-Non-recursively/Nanoquery/walk-a-directory-non-recursively.nanoquery b/Task/Walk-a-directory-Non-recursively/Nanoquery/walk-a-directory-non-recursively.nanoquery index b753731d6f..d885303cc4 100644 --- a/Task/Walk-a-directory-Non-recursively/Nanoquery/walk-a-directory-non-recursively.nanoquery +++ b/Task/Walk-a-directory-Non-recursively/Nanoquery/walk-a-directory-non-recursively.nanoquery @@ -1,7 +1,7 @@ import Nanoquery.IO for fname in new(File).listDir("/foo/bar") - if lower(new(File, fname).getExtension()) = ".mp3" - println filename - end + if lower(new(File, fname).getExtension()) = ".mp3" + println filename + end end diff --git a/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.ps1 b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.ps1 new file mode 100644 index 0000000000..5379f1124a --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-1.ps1 @@ -0,0 +1,2 @@ +Get-ChildItem *.txt -Name +Get-ChildItem f* -Name diff --git a/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.ps1 b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.ps1 new file mode 100644 index 0000000000..e12b551711 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/PowerShell/walk-a-directory-non-recursively-2.ps1 @@ -0,0 +1 @@ +Get-ChildItem -Name | Where-Object { $_ -match '[aeiou]' } diff --git a/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal b/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal index 83a15892f5..7971264c35 100644 --- a/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal +++ b/Task/Walk-a-directory-Non-recursively/Rascal/walk-a-directory-non-recursively.rascal @@ -1,5 +1,5 @@ import IO; public void Walk(loc a, str pattern){ - for (entry <- listEntries(a)) - endsWith(entry, pattern) ? println(entry); + for (entry <- listEntries(a)) + endsWith(entry, pattern) ? println(entry); } diff --git a/Task/Walk-a-directory-Non-recursively/Rebol/walk-a-directory-non-recursively.rebol b/Task/Walk-a-directory-Non-recursively/Rebol/walk-a-directory-non-recursively.rebol new file mode 100644 index 0000000000..c34f264c1e --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Rebol/walk-a-directory-non-recursively.rebol @@ -0,0 +1,21 @@ +Rebol [ + title: "Rosetta code: Walk a directory/Non-recursively" + file: %Walk_a_directory-Non-recursively.r3 + url: https://rosettacode.org/wiki/Walk_a_directory-Non-recursively +] + +for-each-file: function [ + {Walk a directory, evaluating body for each file.} + directory [file!] "directory to use" + body [block!] "block evaluated for each matched file" +][ + unless exists? directory: to-real-file directory [exit] + foreach file read directory [ + try bind body 'file + ] +] + +;; Count number of bytes of all %.r3 files in the current directory +bytes: 0 +for-each-file %./ [ if %.r3 == suffix? file [bytes: bytes + size? file] ] +print ["Total bytes:" bytes] diff --git a/Task/Walk-a-directory-Non-recursively/Run-BASIC/walk-a-directory-non-recursively.basic b/Task/Walk-a-directory-Non-recursively/Run-BASIC/walk-a-directory-non-recursively.basic index 7ef5c15f00..b6324b0faf 100644 --- a/Task/Walk-a-directory-Non-recursively/Run-BASIC/walk-a-directory-non-recursively.basic +++ b/Task/Walk-a-directory-Non-recursively/Run-BASIC/walk-a-directory-non-recursively.basic @@ -1,12 +1,12 @@ files #g, DefaultDir$ + "\*.jpg" ' find all jpg files if #g HASANSWER() then - count = #g rowcount() ' get count of files - for i = 1 to count - if #g hasanswer() then 'retrieve info for next file - #g nextfile$() 'print name of file - print #g NAME$() - end if - next + count = #g rowcount() ' get count of files + for i = 1 to count + if #g hasanswer() then 'retrieve info for next file + #g nextfile$() 'print name of file + print #g NAME$() + end if + next end if wait diff --git a/Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vbs b/Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vbs new file mode 100644 index 0000000000..ddb82ba1ba --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vbs @@ -0,0 +1,10 @@ +Sub show_files(folder_path,pattern) + Set objfso = CreateObject("Scripting.FileSystemObject") + For Each file In objfso.GetFolder(folder_path).Files + If InStr(file.Name,pattern) Then + WScript.StdOut.WriteLine file.Name + End If + Next +End Sub + +Call show_files("C:\Windows",".exe") diff --git a/Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.adb b/Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.adb new file mode 100644 index 0000000000..f866c6c9c4 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Ada/walk-a-directory-recursively.adb @@ -0,0 +1,24 @@ +with Ada.Directories; use Ada.Directories; +with Ada.Text_IO; + +procedure Test_Directory_Walk is + procedure Walk (Name : String; Pattern : String) is + procedure Print (Item : Directory_Entry_Type) is + begin + Ada.Text_IO.Put_Line (Full_Name (Item)); + end Print; + procedure Walk (Item : Directory_Entry_Type) is + begin + if Simple_Name (Item) /= "." and then Simple_Name (Item) /= ".." then + Walk (Full_Name (Item), Pattern); + end if; + exception + when Name_Error => null; + end Walk; + begin + Search (Name, Pattern, (others => True), Print'Access); + Search (Name, "", (Directory => True, others => False), Walk'Access); + end Walk; +begin + Walk (".", "*.adb"); +end Test_Directory_Walk; diff --git a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c index 1b7a904885..e26c3ff119 100644 --- a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c +++ b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-1.c @@ -9,95 +9,95 @@ #include enum { - WALK_OK = 0, - WALK_BADPATTERN, - WALK_NAMETOOLONG, - WALK_BADIO, + WALK_OK = 0, + WALK_BADPATTERN, + WALK_NAMETOOLONG, + WALK_BADIO, }; -#define WS_NONE 0 -#define WS_RECURSIVE (1 << 0) -#define WS_DEFAULT WS_RECURSIVE -#define WS_FOLLOWLINK (1 << 1) /* follow symlinks */ -#define WS_DOTFILES (1 << 2) /* per unix convention, .file is hidden */ -#define WS_MATCHDIRS (1 << 3) /* if pattern is used on dir names too */ +#define WS_NONE 0 +#define WS_RECURSIVE (1 << 0) +#define WS_DEFAULT WS_RECURSIVE +#define WS_FOLLOWLINK (1 << 1) /* follow symlinks */ +#define WS_DOTFILES (1 << 2) /* per unix convention, .file is hidden */ +#define WS_MATCHDIRS (1 << 3) /* if pattern is used on dir names too */ int walk_recur(char *dname, regex_t *reg, int spec) { - struct dirent *dent; - DIR *dir; - struct stat st; - char fn[FILENAME_MAX]; - int res = WALK_OK; - int len = strlen(dname); - if (len >= FILENAME_MAX - 1) - return WALK_NAMETOOLONG; + struct dirent *dent; + DIR *dir; + struct stat st; + char fn[FILENAME_MAX]; + int res = WALK_OK; + int len = strlen(dname); + if (len >= FILENAME_MAX - 1) + return WALK_NAMETOOLONG; - strcpy(fn, dname); - fn[len++] = '/'; + strcpy(fn, dname); + fn[len++] = '/'; - if (!(dir = opendir(dname))) { - warn("can't open %s", dname); - return WALK_BADIO; - } + if (!(dir = opendir(dname))) { + warn("can't open %s", dname); + return WALK_BADIO; + } - errno = 0; - while ((dent = readdir(dir))) { - if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') - continue; - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) - continue; + errno = 0; + while ((dent = readdir(dir))) { + if (!(spec & WS_DOTFILES) && dent->d_name[0] == '.') + continue; + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + continue; - strncpy(fn + len, dent->d_name, FILENAME_MAX - len); - if (lstat(fn, &st) == -1) { - warn("Can't stat %s", fn); - res = WALK_BADIO; - continue; - } + strncpy(fn + len, dent->d_name, FILENAME_MAX - len); + if (lstat(fn, &st) == -1) { + warn("Can't stat %s", fn); + res = WALK_BADIO; + continue; + } - /* don't follow symlink unless told so */ - if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) - continue; + /* don't follow symlink unless told so */ + if (S_ISLNK(st.st_mode) && !(spec & WS_FOLLOWLINK)) + continue; - /* will be false for symlinked dirs */ - if (S_ISDIR(st.st_mode)) { - /* recursively follow dirs */ - if ((spec & WS_RECURSIVE)) - walk_recur(fn, reg, spec); + /* will be false for symlinked dirs */ + if (S_ISDIR(st.st_mode)) { + /* recursively follow dirs */ + if ((spec & WS_RECURSIVE)) + walk_recur(fn, reg, spec); - if (!(spec & WS_MATCHDIRS)) continue; - } + if (!(spec & WS_MATCHDIRS)) continue; + } - /* pattern match */ - if (!regexec(reg, fn, 0, 0, 0)) puts(fn); - } + /* pattern match */ + if (!regexec(reg, fn, 0, 0, 0)) puts(fn); + } - if (dir) closedir(dir); - return res ? res : errno ? WALK_BADIO : WALK_OK; + if (dir) closedir(dir); + return res ? res : errno ? WALK_BADIO : WALK_OK; } int walk_dir(char *dname, char *pattern, int spec) { - regex_t r; - int res; - if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) - return WALK_BADPATTERN; - res = walk_recur(dname, &r, spec); - regfree(&r); + regex_t r; + int res; + if (regcomp(&r, pattern, REG_EXTENDED | REG_NOSUB)) + return WALK_BADPATTERN; + res = walk_recur(dname, &r, spec); + regfree(&r); - return res; + return res; } int main() { - int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); - switch(r) { - case WALK_OK: break; - case WALK_BADIO: err(1, "IO error"); - case WALK_BADPATTERN: err(1, "Bad pattern"); - case WALK_NAMETOOLONG: err(1, "Filename too long"); - default: - err(1, "Unknown error?"); - } - return 0; + int r = walk_dir(".", ".\\.c$", WS_DEFAULT|WS_MATCHDIRS); + switch(r) { + case WALK_OK: break; + case WALK_BADIO: err(1, "IO error"); + case WALK_BADPATTERN: err(1, "Bad pattern"); + case WALK_NAMETOOLONG: err(1, "Filename too long"); + default: + err(1, "Unknown error?"); + } + return 0; } diff --git a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c index 986febb68a..2898a6314d 100644 --- a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c +++ b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-2.c @@ -10,7 +10,7 @@ int entcmp(const FTSENT **a, const FTSENT **b) { - return strcmp((*a)->fts_name, (*b)->fts_name); + return strcmp((*a)->fts_name, (*b)->fts_name); } /* @@ -20,65 +20,65 @@ entcmp(const FTSENT **a, const FTSENT **b) void pmatch(char *dir, const char *pattern) { - FTS *tree; - FTSENT *f; - char *argv[] = { dir, NULL }; + FTS *tree; + FTSENT *f; + char *argv[] = { dir, NULL }; - /* - * FTS_LOGICAL follows symbolic links, including links to other - * directories. It detects cycles, so we never have an infinite - * loop. FTS_NOSTAT is because we never use f->statp. It uses - * our entcmp() to sort files by name. - */ - tree = fts_open(argv, FTS_LOGICAL | FTS_NOSTAT, entcmp); - if (tree == NULL) - err(1, "fts_open"); + /* + * FTS_LOGICAL follows symbolic links, including links to other + * directories. It detects cycles, so we never have an infinite + * loop. FTS_NOSTAT is because we never use f->statp. It uses + * our entcmp() to sort files by name. + */ + tree = fts_open(argv, FTS_LOGICAL | FTS_NOSTAT, entcmp); + if (tree == NULL) + err(1, "fts_open"); - /* - * Iterate files in tree. This iteration always skips - * "." and ".." because we never use FTS_SEEDOT. - */ - while ((f = fts_read(tree))) { - switch (f->fts_info) { - case FTS_DNR: /* Cannot read directory */ - case FTS_ERR: /* Miscellaneous error */ - case FTS_NS: /* stat() error */ - /* Show error, then continue to next files. */ - warn("%s", f->fts_path); - continue; - case FTS_DP: - /* Ignore post-order visit to directory. */ - continue; - } + /* + * Iterate files in tree. This iteration always skips + * "." and ".." because we never use FTS_SEEDOT. + */ + while ((f = fts_read(tree))) { + switch (f->fts_info) { + case FTS_DNR: /* Cannot read directory */ + case FTS_ERR: /* Miscellaneous error */ + case FTS_NS: /* stat() error */ + /* Show error, then continue to next files. */ + warn("%s", f->fts_path); + continue; + case FTS_DP: + /* Ignore post-order visit to directory. */ + continue; + } - /* - * Check if name matches pattern. If so, then print - * path. This check uses FNM_PERIOD, so "*.c" will not - * match ".invisible.c". - */ - if (fnmatch(pattern, f->fts_name, FNM_PERIOD) == 0) - puts(f->fts_path); + /* + * Check if name matches pattern. If so, then print + * path. This check uses FNM_PERIOD, so "*.c" will not + * match ".invisible.c". + */ + if (fnmatch(pattern, f->fts_name, FNM_PERIOD) == 0) + puts(f->fts_path); - /* - * A cycle happens when a symbolic link (or perhaps a - * hard link) puts a directory inside itself. Tell user - * when this happens. - */ - if (f->fts_info == FTS_DC) - warnx("%s: cycle in directory tree", f->fts_path); - } + /* + * A cycle happens when a symbolic link (or perhaps a + * hard link) puts a directory inside itself. Tell user + * when this happens. + */ + if (f->fts_info == FTS_DC) + warnx("%s: cycle in directory tree", f->fts_path); + } - /* fts_read() sets errno = 0 unless it has error. */ - if (errno != 0) - err(1, "fts_read"); + /* fts_read() sets errno = 0 unless it has error. */ + if (errno != 0) + err(1, "fts_read"); - if (fts_close(tree) < 0) - err(1, "fts_close"); + if (fts_close(tree) < 0) + err(1, "fts_close"); } int main() { - pmatch(".", "*.c"); - return 0; + pmatch(".", "*.c"); + return 0; } diff --git a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c index 5bd6c16362..65218fc111 100644 --- a/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c +++ b/Task/Walk-a-directory-Recursively/C/walk-a-directory-recursively-3.c @@ -7,23 +7,23 @@ void oops(const wchar_t *message) { - wchar_t *buf; - DWORD error; + wchar_t *buf; + DWORD error; - buf = NULL; - error = GetLastError(); - FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, error, 0, (wchar_t *)&buf, 0, NULL); + buf = NULL; + error = GetLastError(); + FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, error, 0, (wchar_t *)&buf, 0, NULL); - if (buf) { - fwprintf(stderr, L"%ls: %ls", message, buf); - LocalFree(buf); - } else { - /* FormatMessageW failed. */ - fwprintf(stderr, L"%ls: unknown error 0x%x\n", - message, error); - } + if (buf) { + fwprintf(stderr, L"%ls: %ls", message, buf); + LocalFree(buf); + } else { + /* FormatMessageW failed. */ + fwprintf(stderr, L"%ls: unknown error 0x%x\n", + message, error); + } } /* @@ -33,206 +33,206 @@ oops(const wchar_t *message) int main() { - struct stack { - wchar_t *path; - size_t pathlen; - size_t slashlen; - HANDLE ffh; - WIN32_FIND_DATAW ffd; - struct stack *next; - } *dir, dir0, *ndir; - size_t patternlen; - int argc; - wchar_t **argv, *buf, c, *pattern; + struct stack { + wchar_t *path; + size_t pathlen; + size_t slashlen; + HANDLE ffh; + WIN32_FIND_DATAW ffd; + struct stack *next; + } *dir, dir0, *ndir; + size_t patternlen; + int argc; + wchar_t **argv, *buf, c, *pattern; - /* MinGW never provides wmain(argc, argv). */ - argv = CommandLineToArgvW(GetCommandLineW(), &argc); - if (argv == NULL) { - oops(L"CommandLineToArgvW"); - exit(1); - } + /* MinGW never provides wmain(argc, argv). */ + argv = CommandLineToArgvW(GetCommandLineW(), &argc); + if (argv == NULL) { + oops(L"CommandLineToArgvW"); + exit(1); + } - if (argc != 3) { - fwprintf(stderr, L"usage: %ls dir pattern\n", argv[0]); - exit(1); - } + if (argc != 3) { + fwprintf(stderr, L"usage: %ls dir pattern\n", argv[0]); + exit(1); + } - dir0.path = argv[1]; - dir0.pathlen = wcslen(dir0.path); - pattern = argv[2]; - patternlen = wcslen(pattern); + dir0.path = argv[1]; + dir0.pathlen = wcslen(dir0.path); + pattern = argv[2]; + patternlen = wcslen(pattern); - if (patternlen == 0 || - wcscmp(pattern, L".") == 0 || - wcscmp(pattern, L"..") == 0 || - wcschr(pattern, L'/') || - wcschr(pattern, L'\\')) { - fwprintf(stderr, L"%ls: invalid pattern\n", pattern); - exit(1); - } + if (patternlen == 0 || + wcscmp(pattern, L".") == 0 || + wcscmp(pattern, L"..") == 0 || + wcschr(pattern, L'/') || + wcschr(pattern, L'\\')) { + fwprintf(stderr, L"%ls: invalid pattern\n", pattern); + exit(1); + } - /* - * Must put backslash between path and pattern, unless - * last character of path is slash or colon. - * - * 'dir' => 'dir\*' - * 'dir\' => 'dir\*' - * 'dir/' => 'dir/*' - * 'c:' => 'c:*' - * - * 'c:*' and 'c:\*' are different files! - */ - c = dir0.path[dir0.pathlen - 1]; - if (c == ':' || c == '/' || c == '\\') - dir0.slashlen = dir0.pathlen; - else - dir0.slashlen = dir0.pathlen + 1; + /* + * Must put backslash between path and pattern, unless + * last character of path is slash or colon. + * + * 'dir' => 'dir\*' + * 'dir\' => 'dir\*' + * 'dir/' => 'dir/*' + * 'c:' => 'c:*' + * + * 'c:*' and 'c:\*' are different files! + */ + c = dir0.path[dir0.pathlen - 1]; + if (c == ':' || c == '/' || c == '\\') + dir0.slashlen = dir0.pathlen; + else + dir0.slashlen = dir0.pathlen + 1; - /* Allocate space for path + backslash + pattern + \0. */ - buf = calloc(dir0.slashlen + patternlen + 1, sizeof buf[0]); - if (buf == NULL) { - perror("calloc"); - exit(1); - } - dir0.path = wmemcpy(buf, dir0.path, dir0.pathlen + 1); + /* Allocate space for path + backslash + pattern + \0. */ + buf = calloc(dir0.slashlen + patternlen + 1, sizeof buf[0]); + if (buf == NULL) { + perror("calloc"); + exit(1); + } + dir0.path = wmemcpy(buf, dir0.path, dir0.pathlen + 1); - dir0.ffh = INVALID_HANDLE_VALUE; - dir0.next = NULL; - dir = &dir0; + dir0.ffh = INVALID_HANDLE_VALUE; + dir0.next = NULL; + dir = &dir0; - /* Loop for each directory in linked list. */ + /* Loop for each directory in linked list. */ loop: - while (dir) { - /* - * At first visit to directory: - * Print the matching files. Then, begin to find - * subdirectories. - * - * At later visit: - * dir->ffh is the handle to find subdirectories. - * Continue to find them. - */ - if (dir->ffh == INVALID_HANDLE_VALUE) { - /* Append backslash + pattern + \0 to path. */ - dir->path[dir->pathlen] = '\\'; - wmemcpy(dir->path + dir->slashlen, - pattern, patternlen + 1); + while (dir) { + /* + * At first visit to directory: + * Print the matching files. Then, begin to find + * subdirectories. + * + * At later visit: + * dir->ffh is the handle to find subdirectories. + * Continue to find them. + */ + if (dir->ffh == INVALID_HANDLE_VALUE) { + /* Append backslash + pattern + \0 to path. */ + dir->path[dir->pathlen] = '\\'; + wmemcpy(dir->path + dir->slashlen, + pattern, patternlen + 1); - /* Find all files to match pattern. */ - dir->ffh = FindFirstFileW(dir->path, &dir->ffd); - if (dir->ffh == INVALID_HANDLE_VALUE) { - /* Check if no files match pattern. */ - if (GetLastError() == ERROR_FILE_NOT_FOUND) - goto subdirs; + /* Find all files to match pattern. */ + dir->ffh = FindFirstFileW(dir->path, &dir->ffd); + if (dir->ffh == INVALID_HANDLE_VALUE) { + /* Check if no files match pattern. */ + if (GetLastError() == ERROR_FILE_NOT_FOUND) + goto subdirs; - /* Bail out from other errors. */ - dir->path[dir->pathlen] = '\0'; - oops(dir->path); - goto popdir; - } + /* Bail out from other errors. */ + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + goto popdir; + } - /* Remove pattern from path; keep backslash. */ - dir->path[dir->slashlen] = '\0'; + /* Remove pattern from path; keep backslash. */ + dir->path[dir->slashlen] = '\0'; - /* Print all files to match pattern. */ - do { - wprintf(L"%ls%ls\n", - dir->path, dir->ffd.cFileName); - } while (FindNextFileW(dir->ffh, &dir->ffd) != 0); - if (GetLastError() != ERROR_NO_MORE_FILES) { - dir->path[dir->pathlen] = '\0'; - oops(dir->path); - } - FindClose(dir->ffh); + /* Print all files to match pattern. */ + do { + wprintf(L"%ls%ls\n", + dir->path, dir->ffd.cFileName); + } while (FindNextFileW(dir->ffh, &dir->ffd) != 0); + if (GetLastError() != ERROR_NO_MORE_FILES) { + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + } + FindClose(dir->ffh); subdirs: - /* Append * + \0 to path. */ - dir->path[dir->slashlen] = '*'; - dir->path[dir->slashlen + 1] = '\0'; + /* Append * + \0 to path. */ + dir->path[dir->slashlen] = '*'; + dir->path[dir->slashlen + 1] = '\0'; - /* Find first possible subdirectory. */ - dir->ffh = FindFirstFileExW(dir->path, - FindExInfoStandard, &dir->ffd, - FindExSearchLimitToDirectories, NULL, 0); - if (dir->ffh == INVALID_HANDLE_VALUE) { - dir->path[dir->pathlen] = '\0'; - oops(dir->path); - goto popdir; - } - } else { - /* Find next possible subdirectory. */ - if (FindNextFileW(dir->ffh, &dir->ffd) == 0) - goto closeffh; - } + /* Find first possible subdirectory. */ + dir->ffh = FindFirstFileExW(dir->path, + FindExInfoStandard, &dir->ffd, + FindExSearchLimitToDirectories, NULL, 0); + if (dir->ffh == INVALID_HANDLE_VALUE) { + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + goto popdir; + } + } else { + /* Find next possible subdirectory. */ + if (FindNextFileW(dir->ffh, &dir->ffd) == 0) + goto closeffh; + } - /* Enter subdirectories. */ - do { - const wchar_t *fn = dir->ffd.cFileName; - const DWORD attr = dir->ffd.dwFileAttributes; - size_t buflen, fnlen; + /* Enter subdirectories. */ + do { + const wchar_t *fn = dir->ffd.cFileName; + const DWORD attr = dir->ffd.dwFileAttributes; + size_t buflen, fnlen; - /* - * Skip '.' and '..', because they are links to - * the current and parent directories, so they - * are not subdirectories. - * - * Skip any file that is not a directory. - * - * Skip all reparse points, because they might - * be symbolic links. They might form a cycle, - * with a directory inside itself. - */ - if (wcscmp(fn, L".") == 0 || - wcscmp(fn, L"..") == 0 || - (attr & FILE_ATTRIBUTE_DIRECTORY) == 0 || - (attr & FILE_ATTRIBUTE_REPARSE_POINT)) - continue; + /* + * Skip '.' and '..', because they are links to + * the current and parent directories, so they + * are not subdirectories. + * + * Skip any file that is not a directory. + * + * Skip all reparse points, because they might + * be symbolic links. They might form a cycle, + * with a directory inside itself. + */ + if (wcscmp(fn, L".") == 0 || + wcscmp(fn, L"..") == 0 || + (attr & FILE_ATTRIBUTE_DIRECTORY) == 0 || + (attr & FILE_ATTRIBUTE_REPARSE_POINT)) + continue; - ndir = malloc(sizeof *ndir); - if (ndir == NULL) { - perror("malloc"); - exit(1); - } + ndir = malloc(sizeof *ndir); + if (ndir == NULL) { + perror("malloc"); + exit(1); + } - /* - * Allocate space for path + backslash + - * fn + backslash + pattern + \0. - */ - fnlen = wcslen(fn); - buflen = dir->slashlen + fnlen + patternlen + 2; - buf = calloc(buflen, sizeof buf[0]); - if (buf == NULL) { - perror("malloc"); - exit(1); - } + /* + * Allocate space for path + backslash + + * fn + backslash + pattern + \0. + */ + fnlen = wcslen(fn); + buflen = dir->slashlen + fnlen + patternlen + 2; + buf = calloc(buflen, sizeof buf[0]); + if (buf == NULL) { + perror("malloc"); + exit(1); + } - /* Copy path + backslash + fn + \0. */ - wmemcpy(buf, dir->path, dir->slashlen); - wmemcpy(buf + dir->slashlen, fn, fnlen + 1); + /* Copy path + backslash + fn + \0. */ + wmemcpy(buf, dir->path, dir->slashlen); + wmemcpy(buf + dir->slashlen, fn, fnlen + 1); - /* Push dir to list. Enter dir. */ - ndir->path = buf; - ndir->pathlen = dir->slashlen + fnlen; - ndir->slashlen = ndir->pathlen + 1; - ndir->ffh = INVALID_HANDLE_VALUE; - ndir->next = dir; - dir = ndir; - goto loop; /* Continue outer loop. */ - } while (FindNextFileW(dir->ffh, &dir->ffd) != 0); + /* Push dir to list. Enter dir. */ + ndir->path = buf; + ndir->pathlen = dir->slashlen + fnlen; + ndir->slashlen = ndir->pathlen + 1; + ndir->ffh = INVALID_HANDLE_VALUE; + ndir->next = dir; + dir = ndir; + goto loop; /* Continue outer loop. */ + } while (FindNextFileW(dir->ffh, &dir->ffd) != 0); closeffh: - if (GetLastError() != ERROR_NO_MORE_FILES) { - dir->path[dir->pathlen] = '\0'; - oops(dir->path); - } - FindClose(dir->ffh); + if (GetLastError() != ERROR_NO_MORE_FILES) { + dir->path[dir->pathlen] = '\0'; + oops(dir->path); + } + FindClose(dir->ffh); popdir: - /* Pop dir from list, free dir, but never free dir0. */ - free(dir->path); - if (ndir = dir->next) - free(dir); - dir = ndir; - } + /* Pop dir from list, free dir, but never free dir0. */ + free(dir->path); + if (ndir = dir->next) + free(dir); + dir = ndir; + } - return 0; + return 0; } diff --git a/Task/Walk-a-directory-Recursively/Emacs-Lisp/walk-a-directory-recursively.el b/Task/Walk-a-directory-Recursively/Emacs-Lisp/walk-a-directory-recursively.el new file mode 100644 index 0000000000..e87b7d552c --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Emacs-Lisp/walk-a-directory-recursively.el @@ -0,0 +1,2 @@ +ELISP> (directory-files-recursively "/tmp/el" "\\.el$") +("/tmp/el/1/c.el" "/tmp/el/a.el" "/tmp/el/b.el") diff --git a/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap b/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap index f0a3a38c0c..a55e531f12 100644 --- a/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap +++ b/Task/Walk-a-directory-Recursively/GAP/walk-a-directory-recursively.gap @@ -1,16 +1,16 @@ Walk := function(name, op) - local dir, file, e; - dir := Directory(name); - for e in SortedList(DirectoryContents(name)) do - file := Filename(dir, e); - if IsDirectoryPath(file) then - if not (e in [".", ".."]) then - Walk(file, op); - fi; - else - op(file); - fi; - od; + local dir, file, e; + dir := Directory(name); + for e in SortedList(DirectoryContents(name)) do + file := Filename(dir, e); + if IsDirectoryPath(file) then + if not (e in [".", ".."]) then + Walk(file, op); + fi; + else + op(file); + fi; + od; end; # This will print filenames diff --git a/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-2.java b/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-2.java index 23facd2045..d92871842a 100644 --- a/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-2.java +++ b/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-2.java @@ -3,17 +3,17 @@ import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; public class WalkTree { - public static void main(String[] args) throws IOException { - Path start = FileSystems.getDefault().getPath("/path/to/file"); - Files.walkFileTree(start, new SimpleFileVisitor() { - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attrs) throws IOException { - if (file.toString().endsWith(".mp3")) { - System.out.println(file); - } - return FileVisitResult.CONTINUE; - } - }); - } + public static void main(String[] args) throws IOException { + Path start = FileSystems.getDefault().getPath("/path/to/file"); + Files.walkFileTree(start, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) throws IOException { + if (file.toString().endsWith(".mp3")) { + System.out.println(file); + } + return FileVisitResult.CONTINUE; + } + }); + } } diff --git a/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-3.java b/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-3.java index 309b4a448d..f312bd2670 100644 --- a/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-3.java +++ b/Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-3.java @@ -2,11 +2,11 @@ import java.io.IOException; import java.nio.file.*; public class WalkTree { - public static void main(String[] args) throws IOException { - Path start = FileSystems.getDefault().getPath("/path/to/file"); - Files.walk(start) - .filter( path -> path.toFile().isFile()) - .filter( path -> path.toString().endsWith(".mp3")) - .forEach( System.out::println ); - } + public static void main(String[] args) throws IOException { + Path start = FileSystems.getDefault().getPath("/path/to/file"); + Files.walk(start) + .filter( path -> path.toFile().isFile()) + .filter( path -> path.toString().endsWith(".mp3")) + .forEach( System.out::println ); + } } diff --git a/Task/Walk-a-directory-Recursively/Lasso/walk-a-directory-recursively.lasso b/Task/Walk-a-directory-Recursively/Lasso/walk-a-directory-recursively.lasso index 6a5a2368db..904bfb6b95 100644 --- a/Task/Walk-a-directory-Recursively/Lasso/walk-a-directory-recursively.lasso +++ b/Task/Walk-a-directory-Recursively/Lasso/walk-a-directory-recursively.lasso @@ -1,23 +1,23 @@ // care only about visible files and filter out any directories define dir -> eachVisibleFilePath() => { - return with name in self -> eachEntry where #name -> second != io_dir_dt_dir where not(#name -> first -> beginswith('.')) select .makeFullPath(#name -> first) + return with name in self -> eachEntry where #name -> second != io_dir_dt_dir where not(#name -> first -> beginswith('.')) select .makeFullPath(#name -> first) } // care only about visible directories and filter out any files define dir -> eachVisibleDir() => { - return with name in self -> eachEntry where #name -> second == io_dir_dt_dir where not(#name -> first -> beginswith('.')) select dir(.makeFullPath(#name -> first + '/')) + return with name in self -> eachEntry where #name -> second == io_dir_dt_dir where not(#name -> first -> beginswith('.')) select dir(.makeFullPath(#name -> first + '/')) } // Recursively walk the directory tree and find all files and directories // return only paths to files define dir -> eachVisibleFilePathRecursive(-dirFilter = void) => { - local(files = .eachVisibleFilePath) - with dir in .eachVisibleDir - where !#dirFilter || #dirFilter(#dir -> realPath) - do { - #files = tie(#files, #dir -> eachVisibleFilePathRecursive(-dirFilter = #dirFilter)) - } - return #files + local(files = .eachVisibleFilePath) + with dir in .eachVisibleDir + where !#dirFilter || #dirFilter(#dir -> realPath) + do { + #files = tie(#files, #dir -> eachVisibleFilePathRecursive(-dirFilter = #dirFilter)) + } + return #files } local(matchingfilenames = array) diff --git a/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m b/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m index df461bd93b..87c247a380 100644 --- a/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m +++ b/Task/Walk-a-directory-Recursively/MATLAB/walk-a-directory-recursively.m @@ -1,14 +1,14 @@ function walk_a_directory_recursively(d, pattern) - f = dir(fullfile(d,pattern)); - for k = 1:length(f) - fprintf('%s\n',fullfile(d,f(k).name)); - end; + f = dir(fullfile(d,pattern)); + for k = 1:length(f) + fprintf('%s\n',fullfile(d,f(k).name)); + end; - f = dir(d); - n = find([f.isdir]); - for k=n(:)' - if any(f(k).name~='.') - walk_a_directory_recursively(fullfile(d,f(k).name), pattern); - end; - end; + f = dir(d); + n = find([f.isdir]); + for k=n(:)' + if any(f(k).name~='.') + walk_a_directory_recursively(fullfile(d,f(k).name), pattern); + end; + end; end; diff --git a/Task/Walk-a-directory-Recursively/Nanoquery/walk-a-directory-recursively.nanoquery b/Task/Walk-a-directory-Recursively/Nanoquery/walk-a-directory-recursively.nanoquery index 4bc966394d..bb6e9d1041 100644 --- a/Task/Walk-a-directory-Recursively/Nanoquery/walk-a-directory-recursively.nanoquery +++ b/Task/Walk-a-directory-Recursively/Nanoquery/walk-a-directory-recursively.nanoquery @@ -1,26 +1,26 @@ import Nanoquery.IO def get_files(dirname) - local_filenames = new(File).listDir(dirname) + local_filenames = new(File).listDir(dirname) - filenames = {} + filenames = {} - for i in range(0, len(local_filenames) - 1) - if len(local_filenames) > 0 - if not new(File, local_filenames[i]).isDir() - filenames.append(local_filenames[i]) - else - filenames += get_files(local_filenames[i]) - end - end - end + for i in range(0, len(local_filenames) - 1) + if len(local_filenames) > 0 + if not new(File, local_filenames[i]).isDir() + filenames.append(local_filenames[i]) + else + filenames += get_files(local_filenames[i]) + end + end + end - return filenames + return filenames end f = new(File) for file in get_files("/") - if lower(f.getExtension(file)) = ".mp3" - println file - end + if lower(f.getExtension(file)) = ".mp3" + println file + end end diff --git a/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php b/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php index c6947bb59f..163b97bc5a 100644 --- a/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php +++ b/Task/Walk-a-directory-Recursively/PHP/walk-a-directory-recursively-2.php @@ -1,89 +1,89 @@ /* - This script performs a BFS search with recursion protection - it is often faster to search using this method across a - filesystem due to a few reasons: + This script performs a BFS search with recursion protection + it is often faster to search using this method across a + filesystem due to a few reasons: - * filesystem is accessed in native node order - * a recursive function is not required allowing infinate depth - * multiple directory handles are not required - * the file being searched for is often not that deep in the fs + * filesystem is accessed in native node order + * a recursive function is not required allowing infinate depth + * multiple directory handles are not required + * the file being searched for is often not that deep in the fs - This method also leverages PHP array hashing to speed up loop - detection while minimizing the amount of RAM used to track the - search history. + This method also leverages PHP array hashing to speed up loop + detection while minimizing the amount of RAM used to track the + search history. - -Geoffrey McRae - Released as open license for any use. + -Geoffrey McRae + Released as open license for any use. */ if ($_SERVER['argc'] < 3) { - printf( - "\n" . - "Usage: %s (path) (search) [stop]\n" . - " path the path to search\n" . - " search the filename to search for\n" . - " stop stop when file found, default 1\n" . - "\n" - , $_SERVER['argv'][0]); - exit(1); + printf( + "\n" . + "Usage: %s (path) (search) [stop]\n" . + " path the path to search\n" . + " search the filename to search for\n" . + " stop stop when file found, default 1\n" . + "\n" + , $_SERVER['argv'][0]); + exit(1); } $path = $_SERVER['argv'][1]; $search = $_SERVER['argv'][2]; if ($_SERVER['argc'] > 3) - $stop = $_SERVER['argv'][3] == 1; -else $stop = true; + $stop = $_SERVER['argv'][3] == 1; +else $stop = true; /* get the absolute path and ensure it has a trailing slash */ $path = realpath($path); if (substr($path, -1) !== DIRECTORY_SEPARATOR) - $path .= DIRECTORY_SEPARATOR; + $path .= DIRECTORY_SEPARATOR; $queue = array($path => 1); $done = array(); $index = 0; while(!empty($queue)) { - /* get one element from the queue */ - foreach($queue as $path => $unused) { - unset($queue[$path]); - $done[$path] = null; - break; - } - unset($unused); + /* get one element from the queue */ + foreach($queue as $path => $unused) { + unset($queue[$path]); + $done[$path] = null; + break; + } + unset($unused); - $dh = @opendir($path); - if (!$dh) continue; - while(($filename = readdir($dh)) !== false) { - /* dont recurse back up levels */ - if ($filename == '.' || $filename == '..') - continue; + $dh = @opendir($path); + if (!$dh) continue; + while(($filename = readdir($dh)) !== false) { + /* dont recurse back up levels */ + if ($filename == '.' || $filename == '..') + continue; - /* check if the filename matches the search term */ - if ($filename == $search) { - echo "$path$filename\n"; - if ($stop) - break 2; - } + /* check if the filename matches the search term */ + if ($filename == $search) { + echo "$path$filename\n"; + if ($stop) + break 2; + } - /* get the full path */ - $filename = $path . $filename; + /* get the full path */ + $filename = $path . $filename; - /* resolve symlinks to their real path */ - if (is_link($filename)) - $filename = realpath($filename); + /* resolve symlinks to their real path */ + if (is_link($filename)) + $filename = realpath($filename); - /* queue directories for later search */ - if (is_dir($filename)) { - /* ensure the path has a trailing slash */ - if (substr($filename, -1) !== DIRECTORY_SEPARATOR) - $filename .= DIRECTORY_SEPARATOR; + /* queue directories for later search */ + if (is_dir($filename)) { + /* ensure the path has a trailing slash */ + if (substr($filename, -1) !== DIRECTORY_SEPARATOR) + $filename .= DIRECTORY_SEPARATOR; - /* check if we have already queued this path, or have done it */ - if (array_key_exists($filename, $queue) || array_key_exists($filename, $done)) - continue; + /* check if we have already queued this path, or have done it */ + if (array_key_exists($filename, $queue) || array_key_exists($filename, $done)) + continue; - /* queue the file */ - $queue[$filename] = null; - } - } - closedir($dh); + /* queue the file */ + $queue[$filename] = null; + } + } + closedir($dh); } diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.ps1 b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.ps1 new file mode 100644 index 0000000000..5cdab70b97 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-1.ps1 @@ -0,0 +1 @@ +Get-ChildItem -Recurse -Include *.mp3 diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.ps1 b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.ps1 new file mode 100644 index 0000000000..d801adf5db --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-2.ps1 @@ -0,0 +1,2 @@ +Get-ChildItem -Recurse | + Where-Object { $_.Name -match 'foo[0-9]' -and $_.Length -gt 5MB } diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.ps1 b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.ps1 new file mode 100644 index 0000000000..e44087b21d --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-3.ps1 @@ -0,0 +1,3 @@ +Get-ChildItem -Recurse | + Where-Object { $_.Name -match 'foo[0-9]' } | + ForEach-Object { ... } diff --git a/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.ps1 b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.ps1 new file mode 100644 index 0000000000..82f5b8e122 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/PowerShell/walk-a-directory-recursively-4.ps1 @@ -0,0 +1 @@ +| Where-Object { !$_.PSIsContainer } diff --git a/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal b/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal index 5c63b00191..b38c4561e2 100644 --- a/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal +++ b/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal @@ -3,9 +3,9 @@ module Walk import String; import IO; public void Walk(loc a, str pattern){ - for (entry <- listEntries(a)) - if (endsWith(entry, pattern)) - println(entry); - elseif (isDirectory(a+entry)) - Walk(a+entry, pattern); + for (entry <- listEntries(a)) + if (endsWith(entry, pattern)) + println(entry); + elseif (isDirectory(a+entry)) + Walk(a+entry, pattern); } diff --git a/Task/Walk-a-directory-Recursively/Rebol/walk-a-directory-recursively.rebol b/Task/Walk-a-directory-Recursively/Rebol/walk-a-directory-recursively.rebol new file mode 100644 index 0000000000..9da71d48d7 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Rebol/walk-a-directory-recursively.rebol @@ -0,0 +1,29 @@ +Rebol [ + title: "Rosetta code: Walk a directory/Recursively" + file: %Walk_a_directory-Recursively.r3 + url: https://rosettacode.org/wiki/Walk_a_directory-Recursively +] + +walk: function [ + {Walk a directory tree recursively, evaluating body for each file. + The word is set to the absolute file path before each evaluation. + Use the /where refinement to filter files by a parse rule.} + 'word "receives the absolute path of each visited file" + directory [file!] "root directory to start from" + body [block!] "block evaluated for each matched file" + /where + rules [block!] "parse rules defining which filenames to include" +][ + unless exists? directory: to-real-file directory [exit] + foreach file read directory [ + either dir? file: rejoin [directory file] [ + walk/:where 'item file body rules ;; recurse into subdirectory + ][ + if where [ unless parse/case file rules [ continue ] ] + set :word file ;; bind word to current file path + try body + ] + ] +] + +walk/where item %../ [ print item ] [any [thru #"/"] "Audio" thru ".r3" end] diff --git a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.scm b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.scm index acad7b2726..055d7fa515 100644 --- a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.scm +++ b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-1.scm @@ -6,11 +6,11 @@ (for-each (lambda (ENTRY) (cond ((not (null? ENTRY)) - (let ((MYPATH (make-pathname PATH ENTRY))) + (let ((MYPATH (make-pathname PATH ENTRY))) - (cond ((directory-exists? MYPATH) - (walk FN MYPATH) )) + (cond ((directory-exists? MYPATH) + (walk FN MYPATH) )) - (FN MYPATH) )))) (directory PATH #t) )) + (FN MYPATH) )))) (directory PATH #t) )) (walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/") diff --git a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.scm b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.scm index a8af30f152..1a71069b7f 100644 --- a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.scm +++ b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-2.scm @@ -4,11 +4,11 @@ (define (walk FN PATH) (for-each (lambda (ENTRY) (cond ((not (null? ENTRY)) - (let ((MYPATH ENTRY)) + (let ((MYPATH ENTRY)) - (cond ((file-is-directory? MYPATH) - (walk FN MYPATH) )) - - (FN MYPATH) )))) (directory-list PATH :add-path? #t :children? #t ) )) + (cond ((file-is-directory? MYPATH) + (walk FN MYPATH) )) + + (FN MYPATH) )))) (directory-list PATH :add-path? #t :children? #t ) )) (walk (lambda (X) (cond ((string-suffix? ".scm" X) (display X)(newline) ))) "/home/user/") diff --git a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.scm b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.scm index 9e93907967..06261708fa 100644 --- a/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.scm +++ b/Task/Walk-a-directory-Recursively/Scheme/walk-a-directory-recursively-3.scm @@ -6,11 +6,11 @@ (for-each (lambda (ENTRY) (cond ((not (null? ENTRY)) - (let ((MYPATH (build-path PATH ENTRY))) + (let ((MYPATH (build-path PATH ENTRY))) - (cond ((directory-exists? MYPATH) - (walk FN MYPATH) )) - - (FN MYPATH) )))) (directory-list PATH))) + (cond ((directory-exists? MYPATH) + (walk FN MYPATH) )) + + (FN MYPATH) )))) (directory-list PATH))) (walk (lambda (X) (cond ((string-suffix? ".scm" (path->string X)) (display X)(newline) ))) "/home/user/") diff --git a/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st b/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st index 4185e2386a..ac2572c7a8 100644 --- a/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st +++ b/Task/Walk-a-directory-Recursively/Smalltalk/walk-a-directory-recursively-1.st @@ -13,7 +13,7 @@ Directory extend [ ((File name: fn) isDirectory) ifTrue: [ twoBlock value: (n, ps) value: l. - (Directory name: fn) wholeContent: aPattern withLevel: (l+1) do: twoBlock. + (Directory name: fn) wholeContent: aPattern withLevel: (l+1) do: twoBlock. ] ifFalse: [ ( n =~ aPattern ) diff --git a/Task/Walk-a-directory-Recursively/Swift/walk-a-directory-recursively.swift b/Task/Walk-a-directory-Recursively/Swift/walk-a-directory-recursively.swift index 33b7813f06..0fcb3a7e19 100644 --- a/Task/Walk-a-directory-Recursively/Swift/walk-a-directory-recursively.swift +++ b/Task/Walk-a-directory-Recursively/Swift/walk-a-directory-recursively.swift @@ -6,14 +6,14 @@ let rootPath = "/" // Enumerate the directory tree (which likely recurses internally)... if let fsTree = fileSystem.enumerator(atPath: rootPath) { - + while let fsNodeName = fsTree.nextObject() as? NSString { - + let fullPath = "\(rootPath)/\(fsNodeName)" - + var isDir: ObjCBool = false fileSystem.fileExists(atPath: fullPath, isDirectory: &isDir) - + if !isDir.boolValue && fsNodeName.pathExtension == "txt" { print(fsNodeName) } diff --git a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh index d377f8015c..e89f409405 100644 --- a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh +++ b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-3.sh @@ -3,7 +3,7 @@ indent_print() { for((i=0; i < $1; i++)); do - echo -ne "\t" + echo -ne "\t" done echo "$2" } @@ -12,13 +12,13 @@ walk_tree() { local oldifs bn lev pr pmat if [[ $# -lt 3 ]]; then - if [[ $# -lt 2 ]]; then - pmat=".*" - else - pmat="$2" - fi - walk_tree "$1" "$pmat" 0 - return + if [[ $# -lt 2 ]]; then + pmat=".*" + else + pmat="$2" + fi + walk_tree "$1" "$pmat" 0 + return fi lev=$3 [ -d "$1" ] || return @@ -26,16 +26,16 @@ walk_tree() IFS=" " for el in $1/*; do - bn=$(basename "$el") - if [[ -d "$el" ]]; then - indent_print $lev "$bn/" - pr=$( walk_tree "$el" "$2" $(( lev + 1)) ) - echo "$pr" - else - if [[ "$bn" =~ $2 ]]; then - indent_print $lev "$bn" - fi - fi + bn=$(basename "$el") + if [[ -d "$el" ]]; then + indent_print $lev "$bn/" + pr=$( walk_tree "$el" "$2" $(( lev + 1)) ) + echo "$pr" + else + if [[ "$bn" =~ $2 ]]; then + indent_print $lev "$bn" + fi + fi done IFS=$oldifs } diff --git a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh index db0740262e..406f0c0f30 100644 --- a/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh +++ b/Task/Walk-a-directory-Recursively/UNIX-Shell/walk-a-directory-recursively-4.sh @@ -1,14 +1,14 @@ #! /usr/bin/env bash walk_tree() { - ls "$1" | while IFS= read i; do - if [ -d "$1/$i" ]; then - echo "$i/" - walk_tree "$1/$i" "$2" | sed -r 's/^/\t/' - else - echo "$i" | grep -E "$2" - fi - done + ls "$1" | while IFS= read i; do + if [ -d "$1/$i" ]; then + echo "$i/" + walk_tree "$1/$i" "$2" | sed -r 's/^/\t/' + else + echo "$i" | grep -E "$2" + fi + done } walk_tree "$1" "\.sh$" diff --git a/Task/Walk-a-directory-Recursively/Unicon/walk-a-directory-recursively.unicon b/Task/Walk-a-directory-Recursively/Unicon/walk-a-directory-recursively.unicon index 77e5c0865b..cda86adec3 100644 --- a/Task/Walk-a-directory-Recursively/Unicon/walk-a-directory-recursively.unicon +++ b/Task/Walk-a-directory-Recursively/Unicon/walk-a-directory-recursively.unicon @@ -33,12 +33,12 @@ procedure main(argv) target := argv[1] | stop("Usage: tdir [dir name] [#threads]. #threads default to 2* the number of cores in the machine.") tot_threads := n := 1 maxT := ( integer(argv[2])| - (&features? if ="CPU cores " then cores := integer(tab(0)) * 2) | # available cores * 2 - 4) # default to 4 threads + (&features? if ="CPU cores " then cores := integer(tab(0)) * 2) | # available cores * 2 + 4) # default to 4 threads t := milliseconds() L := getdirs(target) # writes out all directories from the current directory down write((*\L)| 0, " directories in ", milliseconds() - t, - " ms using ", maxT, "-concurrent/", tot_threads, "-total threads" ) + " ms using ", maxT, "-concurrent/", tot_threads, "-total threads" ) end procedure getdirs(s) # return a list of directories beneath the directory 's' @@ -51,20 +51,20 @@ if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then { if n>=maxT then # max thread count reached D |||:= getdirs(s || "/" ||f) else # spawn a new thread for this directory - {/thrd:=[]; n +:= 1; put(thrd, thread getdirs(s || "/" ||f))} + {/thrd:=[]; n +:= 1; put(thrd, thread getdirs(s || "/" ||f))} close(d) if \thrd then{ # If I have threads, collect their results tot_threads +:= *thrd n -:= 1 # allow new threads to be spawned while I'm waiting/collecting results - every wait(th := !thrd) do { # wait for the thread to finish - n -:= 1 - D |||:= <@th # If the thread produced a result, it is going to be - # stored in its "outbox", <@th in this case serves as - # a deferred return since the thread was created by - # thread getdirs(s || "/" ||f) - # this is similar to co-expression activation semantics + every wait(th := !thrd) do { # wait for the thread to finish + n -:= 1 + D |||:= <@th # If the thread produced a result, it is going to be + # stored in its "outbox", <@th in this case serves as + # a deferred return since the thread was created by + # thread getdirs(s || "/" ||f) + # this is similar to co-expression activation semantics } n +:= 1 } diff --git a/Task/War-card-game/Ada/war-card-game.adb b/Task/War-card-game/Ada/war-card-game.adb new file mode 100644 index 0000000000..ad8c89f727 --- /dev/null +++ b/Task/War-card-game/Ada/war-card-game.adb @@ -0,0 +1,146 @@ +-- Play the card game War +-- J. Carter 2024 Jul +-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC) + +with Ada.Text_IO; +with PragmARC.Ansi_Tty_Control; +with PragmARC.Cards.Decks.US; +with PragmARC.Cards.US; + +procedure War is + package Ansi renames PragmARC.Ansi_Tty_Control; + package Cards renames PragmARC.Cards.US; + package Decks renames PragmARC.Cards.Decks.US; + + use type Cards.Rank_Id; + + procedure Display (Hand1 : in Decks.Deck_52; Hand2 : in Decks.Deck_52); + -- Display the state of the game represented by the 2 hands + + function ">" (Left : in Cards.Card_Info; Right : in Cards.Card_Info) return Boolean is + (if Left.Rank = Cards.Ace then + Right.Rank /= Cards.Ace + elsif Right.Rank = Cards.Ace then + False + else + Left.Rank > Right.Rank); + + procedure Display (Hand1 : in Decks.Deck_52; Hand2 : in Decks.Deck_52) is + function Image (Card : in Cards.Card_Info) return Character is + (Cards.Image (Card) (1) ); + + procedure Display (Hand : in Decks.Deck_52); + -- Puts the ranks of the cards in Hand in a row + + procedure Display (Hand : in Decks.Deck_52) is + -- Empty + begin -- Display + All_Cards : for I in 1 .. Hand.Size loop + Ada.Text_IO.Put (Item => Image (Hand.Value (I) ) ); + end loop All_Cards; + end Display; + begin -- Display + Ada.Text_IO.Put (Item => Ansi.Clear_Screen); + Display (Hand => Hand1); + Ada.Text_IO.Put (Item => Ansi.Position (2, 1) ); + Display (Hand => Hand2); + Ada.Text_IO.Put (Item => Ansi.Position (3, 1) ); + end Display; + + Hand1 : Decks.Deck_52; -- Player 1 + Hand2 : Decks.Deck_52; -- Player 2 + Card1 : Cards.Card_Info; -- Player 1 + Card2 : Cards.Card_Info; -- Player 2 + War1 : Decks.Deck_52; -- Player 1 + War2 : Decks.Deck_52; -- Player 2 +begin -- War + Decks.Standard_Deck (Item => Hand1); + Hand1.Shuffle; + + Deal : for I in 1 .. Hand1.Size / 2 loop -- Each player gets half the deck + Hand1.Deal (To => Card1); + Hand2.Add (Item => Card1); + end loop Deal; + + Play : loop + Display (Hand1 => Hand1, Hand2 => Hand2); + + exit Play when Hand1.Size = 0 or Hand2.Size = 0; + + delay 0.5; + + Hand1.Deal (To => Card1); + Hand2.Deal (To => Card2); + + if Card1.Rank /= Card2.Rank then + if Card1 > Card2 then + Hand1.Add (Item => Card1); + Hand1.Add (Item => Card2); + else + Hand2.Add (Item => Card2); + Hand2.Add (Item => Card1); + end if; + else -- War! + War1.Add (Item => Card1); + War2.Add (Item => Card2); + + All_Tries : loop + Ada.Text_IO.Put (Item => "W^^"); + + delay 0.5; + + Deal1 : for I in 1 .. 2 loop + exit Deal1 when Hand1.Is_Empty; + + Hand1.Deal (To => Card1); + War1.Add (Item => Card1); + end loop Deal1; + + Deal2 : for I in 1 .. 2 loop + exit Deal2 when Hand2.Is_Empty; + + Hand2.Deal (To => Card2); + War2.Add (Item => Card2); + end loop Deal2; + + if War1.Value (War1.Size) > War2.Value (War2.Size) then -- 1 wins + Deal11 : loop + exit Deal11 when War1.Is_Empty; + + War1.Deal (To => Card1); + Hand1.Add (Item => Card1); + end loop Deal11; + + Deal12 : loop + exit Deal12 when War2.Is_Empty; + + War2.Deal (To => Card1); + Hand1.Add (Item => Card1); + end loop Deal12; + + exit All_Tries; + elsif War2.Value (War2.Size) > War1.Value (War1.Size) then -- 2 Wins + Deal22 : loop + exit Deal22 when War2.Is_Empty; + + War2.Deal (To => Card2); + Hand2.Add (Item => Card2); + end loop Deal22; + + Deal21 : loop + exit Deal21 when War1.Is_Empty; + + War1.Deal (To => Card2); + Hand2.Add (Item => Card2); + end loop Deal21; + + exit All_Tries; + else + null; -- The war continues + end if; + end loop All_Tries; + end if; + end loop Play; + + Ada.Text_IO.Put (Item => "Player " & (if Hand1.Size = 0 then '2' else '1') & " wins"); +end War; diff --git a/Task/War-card-game/AutoHotkey/war-card-game.ahk b/Task/War-card-game/AutoHotkey/war-card-game.ahk index 8dc5348510..27e816de5b 100644 --- a/Task/War-card-game/AutoHotkey/war-card-game.ahk +++ b/Task/War-card-game/AutoHotkey/war-card-game.ahk @@ -2,64 +2,64 @@ suits := ["♠", "♦", "♥", "♣"] faces := [2,3,4,5,6,7,8,9,10,"J","Q","K","A"] deck := [], p1 := [], p2 := [] for i, s in suits - for j, v in faces - deck.Push(v s) + for j, v in faces + deck.Push(v s) deck := shuffle(deck) deal := deal(deck, p1, p2) p1 := deal.1, p2 := deal.2 for i, v in p2 { - if InStr(v, "A") - p2[i] := p1[i], p1[i] := v - if InStr(v, "K") - p2[i] := p1[i], p1[i] := v - if InStr(v, "Q") - p2[i] := p1[i], p1[i] := v - if InStr(v, "J") - p2[i] := p1[i], p1[i] := v + if InStr(v, "A") + p2[i] := p1[i], p1[i] := v + if InStr(v, "K") + p2[i] := p1[i], p1[i] := v + if InStr(v, "Q") + p2[i] := p1[i], p1[i] := v + if InStr(v, "J") + p2[i] := p1[i], p1[i] := v } MsgBox % war(p1, p2) return war(p1, p2){ - J:=11, Q:=11, K:=11, A:=12, stack := [], cntr := 0 - output := "------------------------------------------" - . "`nRound# Deal Winner P1 P1" - . "`n------------------------------------------" - . "`nround0 26 26" + J:=11, Q:=11, K:=11, A:=12, stack := [], cntr := 0 + output := "------------------------------------------" + . "`nRound# Deal Winner P1 P1" + . "`n------------------------------------------" + . "`nround0 26 26" - while (p1.Count() && p2.Count()) { - cntr++ - stack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1)) - r1:=SubStr(c1,1,-1) ,r2:=SubStr(c2,1,-1) - v1:=r1<11?r1:%r1% ,v2:=r2<11?r2:%r2% - output .= "`nround# " cntr "`t" SubStr(c1 " n", 1, 4) "vs " SubStr(c2 " ", 1, 4) - if (v1 > v2){ - loop % stack.Count() - p1.Push(stack.RemoveAt(1)) - output .= "`t`tP1 wins" - } - else if (v1 < v2){ - loop % stack.Count() - p2.Push(stack.RemoveAt(1)) - output .= "`t`tP2 wins" - } - if (v1 = v2){ - output .= "`t`t**WAR**`t" P1.Count() "`t" P2.Count() - stack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1)) - if !(p1.Count() && p2.Count()) - break - output .= "`nround# " ++cntr "`t(" SubStr(c1 " ", 1, 3) ") - (" SubStr(c2 " ", 1, 3) ")" - output .= "`tFace Dn" - } - output .= "`t" P1.Count() "`t" P2.Count() - if !Mod(cntr, 20) - { - MsgBox % output - output := "" - } - } - output .= "`n" (P1.Count() ? "P1 Wins" : "P2 Wins") - output := StrReplace(output, " )", ") ") - output := StrReplace(output, " -", " -") - return output + while (p1.Count() && p2.Count()) { + cntr++ + stack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1)) + r1:=SubStr(c1,1,-1) ,r2:=SubStr(c2,1,-1) + v1:=r1<11?r1:%r1% ,v2:=r2<11?r2:%r2% + output .= "`nround# " cntr "`t" SubStr(c1 " n", 1, 4) "vs " SubStr(c2 " ", 1, 4) + if (v1 > v2){ + loop % stack.Count() + p1.Push(stack.RemoveAt(1)) + output .= "`t`tP1 wins" + } + else if (v1 < v2){ + loop % stack.Count() + p2.Push(stack.RemoveAt(1)) + output .= "`t`tP2 wins" + } + if (v1 = v2){ + output .= "`t`t**WAR**`t" P1.Count() "`t" P2.Count() + stack.Push(c1:=p1.RemoveAt(1)), stack.Push(c2:=p2.RemoveAt(1)) + if !(p1.Count() && p2.Count()) + break + output .= "`nround# " ++cntr "`t(" SubStr(c1 " ", 1, 3) ") - (" SubStr(c2 " ", 1, 3) ")" + output .= "`tFace Dn" + } + output .= "`t" P1.Count() "`t" P2.Count() + if !Mod(cntr, 20) + { + MsgBox % output + output := "" + } + } + output .= "`n" (P1.Count() ? "P1 Wins" : "P2 Wins") + output := StrReplace(output, " )", ") ") + output := StrReplace(output, " -", " -") + return output diff --git a/Task/War-card-game/C++/war-card-game.cpp b/Task/War-card-game/C++/war-card-game.cpp index 2de81fba82..15ffaa57ad 100644 --- a/Task/War-card-game/C++/war-card-game.cpp +++ b/Task/War-card-game/C++/war-card-game.cpp @@ -4,95 +4,95 @@ class war_game { public: - war_game() { - for ( char suit : SUITS ) { - for ( char pip : PIPS ) { - deck.emplace_back(card(suit, pip)); - } - } - std::random_shuffle(deck.begin(), deck.end()); + war_game() { + for ( char suit : SUITS ) { + for ( char pip : PIPS ) { + deck.emplace_back(card(suit, pip)); + } + } + std::random_shuffle(deck.begin(), deck.end()); - handA = { deck.begin(), deck.begin() + 26 }; - handB = { deck.begin() + 26, deck.end() }; - } + handA = { deck.begin(), deck.begin() + 26 }; + handB = { deck.begin() + 26, deck.end() }; + } - void next_turn() { - card cardA = handA.front(); handA.erase(handA.begin()); - card cardB = handB.front(); handB.erase(handB.begin()); - tabledCards.emplace_back(cardA); - tabledCards.emplace_back(cardB); - int32_t rankA = getRank(cardA.pip); - int32_t rankB = getRank(cardB.pip); - std::cout << cardA.pip << cardA.suit << " " << cardB.pip << cardB.suit << std::endl; + void next_turn() { + card cardA = handA.front(); handA.erase(handA.begin()); + card cardB = handB.front(); handB.erase(handB.begin()); + tabledCards.emplace_back(cardA); + tabledCards.emplace_back(cardB); + int32_t rankA = getRank(cardA.pip); + int32_t rankB = getRank(cardB.pip); + std::cout << cardA.pip << cardA.suit << " " << cardB.pip << cardB.suit << std::endl; - if ( rankA > rankB ) { - std::cout << " Player A takes the cards" << std::endl; - std::random_shuffle(tabledCards.begin(), tabledCards.end()); - handA.insert(handA.end(), tabledCards.begin(), tabledCards.end()); - tabledCards.clear(); - } else if ( rankA < rankB ) { - std::cout << " Player B takes the cards" << std::endl; - std::random_shuffle(tabledCards.begin(), tabledCards.end()); - handB.insert(handB.end(), tabledCards.begin(), tabledCards.end());; - tabledCards.clear(); - } else { - std::cout << " War!" << std::endl; - if ( game_over() ) { - return; - } + if ( rankA > rankB ) { + std::cout << " Player A takes the cards" << std::endl; + std::random_shuffle(tabledCards.begin(), tabledCards.end()); + handA.insert(handA.end(), tabledCards.begin(), tabledCards.end()); + tabledCards.clear(); + } else if ( rankA < rankB ) { + std::cout << " Player B takes the cards" << std::endl; + std::random_shuffle(tabledCards.begin(), tabledCards.end()); + handB.insert(handB.end(), tabledCards.begin(), tabledCards.end());; + tabledCards.clear(); + } else { + std::cout << " War!" << std::endl; + if ( game_over() ) { + return; + } - card cardAA = handA.front(); handA.erase(handA.begin()); - card cardBB = handB.front(); handB.erase(handB.begin()); - tabledCards.emplace_back(cardAA); - tabledCards.emplace_back(cardBB); - std::cout << "? ? Cards are face down" << std::endl; - if ( game_over() ) { - return; - } + card cardAA = handA.front(); handA.erase(handA.begin()); + card cardBB = handB.front(); handB.erase(handB.begin()); + tabledCards.emplace_back(cardAA); + tabledCards.emplace_back(cardBB); + std::cout << "? ? Cards are face down" << std::endl; + if ( game_over() ) { + return; + } - next_turn(); - } - } + next_turn(); + } + } - bool game_over() const { - return handA.size() == 0 || handB.size() == 0; - } + bool game_over() const { + return handA.size() == 0 || handB.size() == 0; + } - void declare_winner() const { - if ( handA.size() == 0 && handB.size() == 0 ) { - std::cout << "The game ended in a tie" << std::endl; - } else if ( handA.size() == 0 ) { - std::cout << "Player B has won the game" << std::endl; - } else { - std::cout << "Player A has won the game" << std::endl; - } - } + void declare_winner() const { + if ( handA.size() == 0 && handB.size() == 0 ) { + std::cout << "The game ended in a tie" << std::endl; + } else if ( handA.size() == 0 ) { + std::cout << "Player B has won the game" << std::endl; + } else { + std::cout << "Player A has won the game" << std::endl; + } + } private: - class card { - public: - card(const char suit, const char pip) : suit(suit), pip(pip) {}; - char suit, pip; - }; + class card { + public: + card(const char suit, const char pip) : suit(suit), pip(pip) {}; + char suit, pip; + }; - int32_t getRank(const char ch) const { - auto it = find(PIPS.begin(), PIPS.end(), ch); - if ( it != PIPS.end() ) { - return it - PIPS.begin(); - } - return -1; - } + int32_t getRank(const char ch) const { + auto it = find(PIPS.begin(), PIPS.end(), ch); + if ( it != PIPS.end() ) { + return it - PIPS.begin(); + } + return -1; + } - std::vector deck, handA, handB, tabledCards; - inline static const std::vector PIPS = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' }; - inline static const std::vector SUITS = { 'C', 'D', 'H', 'S' }; + std::vector deck, handA, handB, tabledCards; + inline static const std::vector PIPS = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' }; + inline static const std::vector SUITS = { 'C', 'D', 'H', 'S' }; }; int main() { - war_game wargame; + war_game wargame; srand((unsigned) time(NULL)); - while ( ! wargame.game_over() ) { - wargame.next_turn(); - } + while ( ! wargame.game_over() ) { + wargame.next_turn(); + } - wargame.declare_winner(); + wargame.declare_winner(); } diff --git a/Task/War-card-game/EasyLang/war-card-game.easy b/Task/War-card-game/EasyLang/war-card-game.easy new file mode 100644 index 0000000000..e1ef499075 --- /dev/null +++ b/Task/War-card-game/EasyLang/war-card-game.easy @@ -0,0 +1,79 @@ +suits$[] = [ "♣" "♦" "♥" "♠" ] +faces$[] = [ "2" "3" "4" "5" "6" "7" "8" "9" "T" "J" "Q" "K" "A" ] +# +func rank card . + return card mod1 13 +. +func$ name card . + return faces$[card mod1 13] & suits$[card div1 13] +. +proc take &card &hand[] . + card = hand[1] + for i to len hand[] - 1 : hand[i] = hand[i + 1] + len hand[] -1 +. +proc append &hand[] &cards[] . + for c in cards[] : hand[] &= c + cards[] = [ ] +. +proc war . + for i to 52 : deck[] &= i + for i = len deck[] downto 2 + r = random 1 i + swap deck[r] deck[i] + . + for i to 26 + hand1[] &= deck[2 * i - 1] + hand2[] &= deck[2 * i] + . + while len hand1[] > 0 and len hand2[] > 0 + take card1 hand1[] + take card2 hand2[] + played1[] = [ card1 ] + played2[] = [ card2 ] + repeat + write name card1 & " " & name card2 & " " + if rank card1 > rank card2 + write "Player 1 takes the " & len played1[] * 2 & " cards." + append hand1[] played1[] + append hand1[] played2[] + print " Now has " & len hand1[] & "." + elif rank card1 < rank card2 + write "Player 2 takes the " & len played1[] * 2 & " cards." + append hand2[] played2[] + append hand2[] played1[] + print " Now has " & len hand2[] & "." + else + print "War!" + if len hand1[] < 2 + print "Player 1 has insufficient cards left." + append hand2[] played2[] + append hand2[] played1[] + append hand2[] hand1[] + elif len hand2[] < 2 + print "Player 2 has insufficient cards left." + append hand1[] played1[] + append hand1[] played2[] + append hand1[] hand2[] + else + take faceDown1 hand1[] + take card1 hand1[] + played1[] &= faceDown1 + played1[] &= card1 + take faceDown2 hand2[] + take card2 hand2[] + played2[] &= faceDown2 + played2[] &= card2 + print "? ? Face down cards." + . + . + until len played1[] = 0 + . + . + if len hand1[] = 52 + print "Player 1 wins the game!" + else + print "Player 2 wins the game!" + . +. +war diff --git a/Task/War-card-game/Java/war-card-game.java b/Task/War-card-game/Java/war-card-game.java index ad2ba94b16..90f7537ede 100644 --- a/Task/War-card-game/Java/war-card-game.java +++ b/Task/War-card-game/Java/war-card-game.java @@ -5,22 +5,22 @@ import java.util.List; public final class WarCardGame { - public static void main(String[] args) { - WarGame warGame = new WarGame(); - - while ( ! warGame.gameOver() ) { - warGame.nextTurn(); - } - - warGame.declareWinner(); - } - + public static void main(String[] args) { + WarGame warGame = new WarGame(); + + while ( ! warGame.gameOver() ) { + warGame.nextTurn(); + } + + warGame.declareWinner(); + } + } final class WarGame { - - public WarGame() { - deck = new ArrayList(52); + + public WarGame() { + deck = new ArrayList(52); for ( Character suit : SUITS ) { for ( Character pip : PIPS ) { deck.add( new Card(suit, pip) ); @@ -31,29 +31,29 @@ final class WarGame { handA = new ArrayList(deck.subList(0, 26)); handB = new ArrayList(deck.subList(26, 52)); tabledCards = new ArrayList(); - } - - public void nextTurn() { - Card cardA = handA.remove(0); - Card cardB = handB.remove(0); - tabledCards.add(cardA); - tabledCards.add(cardB); - int rankA = PIPS.indexOf(cardA.pip); - int rankB = PIPS.indexOf(cardB.pip); - - System.out.print(cardA + " " + cardB); - if ( rankA > rankB ) { + } + + public void nextTurn() { + Card cardA = handA.remove(0); + Card cardB = handB.remove(0); + tabledCards.add(cardA); + tabledCards.add(cardB); + int rankA = PIPS.indexOf(cardA.pip); + int rankB = PIPS.indexOf(cardB.pip); + + System.out.print(cardA + " " + cardB); + if ( rankA > rankB ) { System.out.println(" Player A takes the cards"); Collections.shuffle(tabledCards); handA.addAll(tabledCards); tabledCards.clear(); - } else if ( rankA < rankB ) { + } else if ( rankA < rankB ) { System.out.println(" Player B takes the cards"); Collections.shuffle(tabledCards); handB.addAll(tabledCards); tabledCards.clear(); - } else { - System.out.println(" War!"); + } else { + System.out.println(" War!"); if ( gameOver() ) { return; } @@ -61,43 +61,43 @@ final class WarGame { Card cardAA = handA.remove(0); Card cardBB = handB.remove(0); tabledCards.add(cardAA); - tabledCards.add(cardBB); - System.out.println("? ? Cards are face down"); - if ( gameOver() ) { + tabledCards.add(cardBB); + System.out.println("? ? Cards are face down"); + if ( gameOver() ) { return; } - - nextTurn(); - } - } - - public boolean gameOver() { - return handA.size() == 0 || handB.size() == 0; - } - public void declareWinner() { + nextTurn(); + } + } + + public boolean gameOver() { + return handA.size() == 0 || handB.size() == 0; + } + + public void declareWinner() { if ( handA.size() == 0 && handB.size() == 0 ) { - System.out.println("The game ended in a tie"); + System.out.println("The game ended in a tie"); } else if ( handA.size() == 0 ) { - System.out.println("Player B has won the game"); + System.out.println("Player B has won the game"); } else { System.out.println("Player A has won the game"); } } private record Card(Character suit, Character pip) { - - @Override - public String toString() { - return "" + pip + suit; - } - + + @Override + public String toString() { + return "" + pip + suit; + } + } - - private List deck, handA, handB, tabledCards; - - private static final List PIPS = - Arrays.asList( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); - private static final List SUITS = List.of( 'C', 'D', 'H', 'S' ); - + + private List deck, handA, handB, tabledCards; + + private static final List PIPS = + Arrays.asList( '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' ); + private static final List SUITS = List.of( 'C', 'D', 'H', 'S' ); + } diff --git a/Task/War-card-game/Lua/war-card-game.lua b/Task/War-card-game/Lua/war-card-game.lua index 5cf7046e16..fca73c1e5f 100644 --- a/Task/War-card-game/Lua/war-card-game.lua +++ b/Task/War-card-game/Lua/war-card-game.lua @@ -1,130 +1,130 @@ -- main.lua function newGame () - -- new deck - local deck = {} - for iSuit = 1, #CardSuits do - for iRank = 1, #CardRanks do - local card = { - iSuit = iSuit, - iRank = iRank, - suit = CardSuits[iSuit], - rank = iRank, - name = CardRanks[iRank] .. CardSuits[iSuit] - } - local i = math.random (#deck + 1) - table.insert (deck, i, card) - end - end - - -- new deal - Players = { - {index = 1, cards = {}}, - {index = 2, cards = {}}, - } - for i = 1, #deck/#Players do - for iPlayer = 1, #Players do - table.insert (Players[iPlayer].cards, table.remove(deck)) - end - end - WarCards = {} - Turn = 1 - Statistics = {} + -- new deck + local deck = {} + for iSuit = 1, #CardSuits do + for iRank = 1, #CardRanks do + local card = { + iSuit = iSuit, + iRank = iRank, + suit = CardSuits[iSuit], + rank = iRank, + name = CardRanks[iRank] .. CardSuits[iSuit] + } + local i = math.random (#deck + 1) + table.insert (deck, i, card) + end + end + + -- new deal + Players = { + {index = 1, cards = {}}, + {index = 2, cards = {}}, + } + for i = 1, #deck/#Players do + for iPlayer = 1, #Players do + table.insert (Players[iPlayer].cards, table.remove(deck)) + end + end + WarCards = {} + Turn = 1 + Statistics = {} end function getHigherCard (cardA, cardB) - if cardA.rank > cardB.rank then - return cardA, 1 - elseif cardA.rank < cardB.rank then - return cardB, 2 - else - return nil - end + if cardA.rank > cardB.rank then + return cardA, 1 + elseif cardA.rank < cardB.rank then + return cardB, 2 + else + return nil + end end function love.load() - -- there is no card suits in the standard font - CardSuits = {"@", "#", "$", "%"} - CardRanks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "V", "Q", "K", "A"} - - newGame () + -- there is no card suits in the standard font + CardSuits = {"@", "#", "$", "%"} + CardRanks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "V", "Q", "K", "A"} + + newGame () end function love.draw() - for iPlayer = 1, #Players do - local player = Players[iPlayer] - love.graphics.print ('Player '..player.index, 50*(iPlayer-1), 0) - for iCard, card in ipairs (player.cards) do - love.graphics.print (card.name, 50*(iPlayer-1), 14*iCard) - end - end - for i = 1, math.min(40, #Statistics) do - local str = Statistics[i] - love.graphics.print (str, 150, 20+(i-1)*14) - end - + for iPlayer = 1, #Players do + local player = Players[iPlayer] + love.graphics.print ('Player '..player.index, 50*(iPlayer-1), 0) + for iCard, card in ipairs (player.cards) do + love.graphics.print (card.name, 50*(iPlayer-1), 14*iCard) + end + end + for i = 1, math.min(40, #Statistics) do + local str = Statistics[i] + love.graphics.print (str, 150, 20+(i-1)*14) + end + end function makeTurn () - local card1 = table.remove (Players[1].cards) - local card2 = table.remove (Players[2].cards) - if card1 and card2 then - table.insert (WarCards, 1, card1) - table.insert (WarCards, math.random (1, 2), card2) - local winCard, index = getHigherCard (card1, card2) - if winCard then - table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' get ' .. #WarCards .. ' cards: ' .. card1.name .. ' vs ' .. card2.name) - - for iCard = #WarCards, 1, -1 do - table.insert (Players[index].cards, 1, table.remove (WarCards)) - end - elseif (#Players[1].cards > 0) and (#Players[2].cards > 0) then - -- start war - table.insert (Statistics, 1, Turn .. ' War: ' .. card1.name .. ' vs ' .. card2.name) - table.insert (WarCards, table.remove (Players[1].cards)) - table.insert (WarCards, table.remove (Players[2].cards)) - else - local index = 2 - if #Players[1].cards == 0 then index = 1 end - table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' has no cards for this war.') --- GameOver = true - end - Turn = Turn + 1 - elseif GameOver then - GameOver = false - newGame () - else - local index = 2 - if #Players[1].cards > #Players[2].cards then index = 1 end - table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' wins the game!') - GameOver = true - end + local card1 = table.remove (Players[1].cards) + local card2 = table.remove (Players[2].cards) + if card1 and card2 then + table.insert (WarCards, 1, card1) + table.insert (WarCards, math.random (1, 2), card2) + local winCard, index = getHigherCard (card1, card2) + if winCard then + table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' get ' .. #WarCards .. ' cards: ' .. card1.name .. ' vs ' .. card2.name) + + for iCard = #WarCards, 1, -1 do + table.insert (Players[index].cards, 1, table.remove (WarCards)) + end + elseif (#Players[1].cards > 0) and (#Players[2].cards > 0) then + -- start war + table.insert (Statistics, 1, Turn .. ' War: ' .. card1.name .. ' vs ' .. card2.name) + table.insert (WarCards, table.remove (Players[1].cards)) + table.insert (WarCards, table.remove (Players[2].cards)) + else + local index = 2 + if #Players[1].cards == 0 then index = 1 end + table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' has no cards for this war.') +-- GameOver = true + end + Turn = Turn + 1 + elseif GameOver then + GameOver = false + newGame () + else + local index = 2 + if #Players[1].cards > #Players[2].cards then index = 1 end + table.insert (Statistics, 1, Turn .. ' Player ' .. index .. ' wins the game!') + GameOver = true + end end function love.keypressed(key, scancode, isrepeat) - if false then - elseif key == "space" then - makeTurn () - elseif scancode == "n" then - GameOver = false - newGame () - elseif scancode == "q" then - local lastTurn = Turn - while not (GameOver or (Turn > lastTurn + 10000-1)) do - makeTurn () - end - elseif key == "escape" then - love.event.quit() - end - if #Statistics > 40 then - local i = #Statistics, 40, -1 do - table.remove (Statistics, i) - end - end + if false then + elseif key == "space" then + makeTurn () + elseif scancode == "n" then + GameOver = false + newGame () + elseif scancode == "q" then + local lastTurn = Turn + while not (GameOver or (Turn > lastTurn + 10000-1)) do + makeTurn () + end + elseif key == "escape" then + love.event.quit() + end + if #Statistics > 40 then + local i = #Statistics, 40, -1 do + table.remove (Statistics, i) + end + end end function love.mousepressed( x, y, button, istouch, presses ) - if button == 1 then -- left mouse button - makeTurn () - elseif button == 2 then -- right mouse button - end + if button == 1 then -- left mouse button + makeTurn () + elseif button == 2 then -- right mouse button + end end diff --git a/Task/War-card-game/Rebol/war-card-game.rebol b/Task/War-card-game/Rebol/war-card-game.rebol new file mode 100644 index 0000000000..71a15c53c8 --- /dev/null +++ b/Task/War-card-game/Rebol/war-card-game.rebol @@ -0,0 +1,80 @@ +Rebol [ + title: "Rosetta code: War card game" + file: %War_card_game.r3 + url: https://rosettacode.org/wiki/War_card_game +] + +war-card-game: function/with [ + "Play a game of War" +][ + ;; shuffle and deal alternating cards to each player + deck: fisher-yates-shuffle copy ordered-deck + clear deck1 + clear deck2 + foreach [a b] deck [ + append deck1 a + append deck2 b + ] + ;; play turns until someone runs out of cards + pending: copy [] + n: 1 + while [not any [empty? deck1 empty? deck2]][ + ;; flip top card from each deck + r1: rank? c1: take deck1 + r2: rank? c2: take deck2 + prin format [5 5 5] reduce [++ n c1 c2] + case [ + r1 > r2 [ + ;; player 1 wins: takes both cards plus any pending + print as-yellow "Player 1 takes the cards." + repend deck1 [c1 c2] + append deck1 take/all pending + ] + r1 < r2 [ + ;; player 2 wins: takes both cards plus any pending + print as-blue "Player 2 takes the cards." + repend deck2 [c2 c1] + append deck2 take/all pending + ] + true [ + ;; tie: hold cards face-down, continue to next turn + print as-red "This is a war!" + if any [empty? deck1 empty? deck2][ break ] + c3: take deck1 + c4: take deck2 + printf [5 5 5 "Cards are face down."] reduce [++ n #"?" #"?"] + repend pending [c1 c2 c3 c4] + ] + ] + ;wait-for-key + ] + ;; announce winner + print "========================================" + print case [ + all [empty? deck1 empty? deck2] ["Game ends as a tie."] + empty? deck2 ["Player 1 wins the game."] + true ["Player 2 wins the game."] + ] + exit +][ + deck: none + deck1: [] deck2: [] ordered-deck: [] + ;; build ordered deck: suits vary fastest, ranks slowest + foreach s "♣♦♥♠" [ foreach r "23456789TJQKA" [ append ordered-deck ajoin [r s] ] ] + probe ordered-deck + ;; rank lookup + rank-modifiers: #[ + #"A" 130 #"K" 120 #"Q" 110 #"J" 100 #"T" 90 + #"9" 80 #"8" 70 #"7" 60 #"6" 50 #"5" 40 + #"4" 30 #"3" 20 #"2" 10 + ] + rank?: func [card] [ rank-modifiers/(card/1) ] + ;; standard Fisher-Yates in-place shuffle + fisher-yates-shuffle: function [list [block!]] [ + len: length? list + repeat i len [ swap at list i at list (i + random (len - i)) ] + list + ] +] + +war-card-game diff --git a/Task/War-card-game/Rust/war-card-game.rs b/Task/War-card-game/Rust/war-card-game.rs index a128b9e6a1..9d6145bed8 100644 --- a/Task/War-card-game/Rust/war-card-game.rs +++ b/Task/War-card-game/Rust/war-card-game.rs @@ -1,5 +1,7 @@ +// rand@0.10.0 + use rand::seq::SliceRandom; -use rand::thread_rng; +use rand::rng; const SUITS: [&str; 4] = ["♣", "♦", "♥", "♠"]; const FACES: [&str; 13] = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]; @@ -23,7 +25,7 @@ impl Card { fn war() { // Create and shuffle deck let mut deck: Vec = (0..52).collect(); - deck.shuffle(&mut thread_rng()); + deck.shuffle(&mut rng()); // Deal cards to players (reversing order to match Go implementation) let mut hand1: Vec = Vec::with_capacity(52); diff --git a/Task/War-card-game/V-(Vlang)/war-card-game.v b/Task/War-card-game/V-(Vlang)/war-card-game.v new file mode 100644 index 0000000000..a3b0a360e6 --- /dev/null +++ b/Task/War-card-game/V-(Vlang)/war-card-game.v @@ -0,0 +1,101 @@ +import rand +import rand.seed + +const suits = ["♣", "♦", "♥", "♠"] +const faces = ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"] + +fn build_cards_and_ranks() ([]string, []int) { + mut cards := []string{len: 52} + mut ranks := []int{len: 52} + for i in 0 .. 52 { + cards[i] = faces[i % 13] + suits[i / 13] + ranks[i] = i % 13 + } + return cards, ranks +} + +fn war() { + cards, ranks := build_cards_and_ranks() + mut deck := []int{len: 52} + mut hand1 := []int{cap: 52} + mut hand2 := []int{cap: 52} + mut played1, mut played2 := []int{}, []int{} + mut card1, mut card2, mut num_played := 0, 0, 0 + for ial in 0 .. 52 { + deck[ial] = ial + } + rand.shuffle(mut deck) or { panic("shuffle failed") } + // distribute cards + for i in 0 .. 26 { + hand1.insert(0, deck[2 * i]) + hand2.insert(0, deck[2 * i + 1]) + } + for hand1.len > 0 && hand2.len > 0 { + card1 = hand1[0] + hand1.delete(0) + card2 = hand2[0] + hand2.delete(0) + played1 = [card1] + played2 = [card2] + num_played = 2 + for { + print("${cards[card1]}\t${cards[card2]}\t") + if ranks[card1] > ranks[card2] { + hand1 << played1 + hand1 << played2 + println("Player 1 takes the $num_played cards. Now has ${hand1.len}.") + break + } + else if ranks[card1] < ranks[card2] { + hand2 << played2 + hand2 << played1 + println("Player 2 takes the $num_played cards. Now has ${hand2.len}.") + break + } + else { + println("War!") + if hand1.len < 2 { + println("Player 1 has insufficient cards left.") + hand2 << played2 + hand2 << played1 + hand2 << hand1 + hand1.clear() + break + } + if hand2.len < 2 { + println("Player 2 has insufficient cards left.") + hand1 << played1 + hand1 << played2 + hand1 << hand2 + hand2.clear() + break + } + fd_card1 := hand1[0] // face down card + card1 = hand1[1] // face up card + hand1.delete(0) + hand1.delete(0) + played1 << fd_card1 + played1 << card1 + // do again for other + fd_card2 := hand2[0] // face down card + card2 = hand2[1] // face up card + hand2.delete(0) + hand2.delete(0) + played2 << fd_card2 + played2 << card2 + // other finished + num_played += 4 + println("? \t? \tFace down cards.") + } + } + } + + if hand1.len == 52 { println("Player 1 wins the game!") } + else { println("Player 2 wins the game!") } +} + +fn main() { + seeds := seed.time_seed_array(2) + rand.seed(seeds) + war() +} diff --git a/Task/Water-collected-between-towers/Ada/water-collected-between-towers.adb b/Task/Water-collected-between-towers/Ada/water-collected-between-towers.adb new file mode 100644 index 0000000000..d726e9c327 --- /dev/null +++ b/Task/Water-collected-between-towers/Ada/water-collected-between-towers.adb @@ -0,0 +1,74 @@ +with Ada.Text_IO; + +procedure Water_Collected is + + type Bar_Index is new Positive; + type Natural_Array is array (Bar_Index range <>) of Natural; + + subtype Bar_Array is Natural_Array; + subtype Water_Array is Natural_Array; + + function Flood (Bars : Bar_Array; Forward : Boolean) return Water_Array is + R : Water_Array (Bars'Range); + H : Natural := 0; + begin + if Forward then + for A in R'Range loop + H := Natural'Max (H, Bars (A)); + R (A) := H - Bars (A); + end loop; + else + for A in reverse R'Range loop + H := Natural'Max (H, Bars (A)); + R (A) := H - Bars (A); + end loop; + end if; + return R; + end Flood; + + function Fold (Left, Right : Water_Array) return Water_Array is + R : Water_Array (Left'Range); + begin + for A in R'Range loop + R (A) := Natural'Min (Left (A), Right (A)); + end loop; + return R; + end Fold; + + function Fill (Bars : Bar_Array) return Water_Array + is (Fold (Flood (Bars, Forward => True), + Flood (Bars, Forward => False))); + + function Sum_Of (Bars : Natural_Array) return Natural is + Sum : Natural := 0; + begin + for Bar of Bars loop + Sum := Sum + Bar; + end loop; + return Sum; + end Sum_Of; + + procedure Show (Bars : Bar_Array) is + use Ada.Text_IO; + Water : constant Water_Array := Fill (Bars); + begin + Put ("The series: ["); + for Bar of Bars loop + Put (Bar'Image); + Put (" "); + end loop; + Put ("] holds "); + Put (Sum_Of (Water)'Image); + Put (" units of water."); + New_Line; + end Show; + +begin + Show ((1, 5, 3, 7, 2)); + Show ((5, 3, 7, 2, 6, 4, 5, 9, 1, 2)); + Show ((2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1)); + Show ((5, 5, 5, 5)); + Show ((5, 6, 7, 8)); + Show ((8, 7, 7, 6)); + Show ((6, 7, 10, 7, 6)); +end Water_Collected; diff --git a/Task/Water-collected-between-towers/Gleam/water-collected-between-towers.gleam b/Task/Water-collected-between-towers/Gleam/water-collected-between-towers.gleam new file mode 100644 index 0000000000..ef8d698e90 --- /dev/null +++ b/Task/Water-collected-between-towers/Gleam/water-collected-between-towers.gleam @@ -0,0 +1,28 @@ +import gleam/int +import gleam/io +import gleam/list + +pub fn main() { + let cases = [ + [1, 5, 3, 7, 2], + [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], + [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], + [5, 5, 5, 5], + [5, 6, 7, 8], + [8, 7, 7, 6], + [6, 7, 10, 7, 6], + ] + use towers <- list.each(cases) + towers |> water_area |> int.to_string |> io.println +} + +pub fn water_area(towers: List(Int)) -> Int { + towers + |> list.scan(0, int.max) + |> list.map2( + towers |> list.reverse |> list.scan(0, int.max) |> list.reverse, + int.min, + ) + |> list.map2(towers, int.subtract) + |> int.sum +} diff --git a/Task/Water-collected-between-towers/Pluto/water-collected-between-towers.pluto b/Task/Water-collected-between-towers/Pluto/water-collected-between-towers.pluto new file mode 100644 index 0000000000..0336d0c375 --- /dev/null +++ b/Task/Water-collected-between-towers/Pluto/water-collected-between-towers.pluto @@ -0,0 +1,23 @@ +require "table2" +local fmt = require "fmt" + +local function water_collected(tower) + local n = #tower + local high_left = range(2, n):map(|i| -> tower:slice(1, i - 1):max()) + high_left:insert(1, 0) + local high_right = range(2, n):map(|i| -> tower:slice(i):max()) + high_right:insert(0) + local t = range(1, n):map(|i| -> {{high_left[i], high_right[i]}:min() - tower[i], 0}:max()) + return t:sum() +end + +local towers = { + {1, 5, 3, 7, 2}, + {5, 3, 7, 2, 6, 4, 5, 9, 1, 2}, + {2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1}, + {5, 5, 5, 5}, + {5, 6, 7, 8}, + {8, 7, 7, 6}, + {6, 7, 10, 7, 6} +} +for towers as tower do fmt.print("%2d from %,s", water_collected(tower), tower) end diff --git a/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua b/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua index ecaabaff75..f11898932e 100644 --- a/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua +++ b/Task/Water-collected-between-towers/Uiua/water-collected-between-towers.uiua @@ -1,10 +1,10 @@ -Area ← /+-:↧⍜⇌\↥⟜\↥. +Area ← /+˜-↧⍜⇌\↥⟜⊸\↥ -{[1 5 3 7 2] - [5 3 7 2 6 4 5 9 1 2] - [2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1] - [5 5 5 5] - [5 6 7 8] - [8 7 7 6] - [6 7 10 7 6]} -∵◇Area +{ [1 5 3 7 2] + [5 3 7 2 6 4 5 9 1 2] + [2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1] + [5 5 5 5] + [5 6 7 8] + [8 7 7 6] + [6 7 10 7 6]} +≡◇Area diff --git a/Task/Web-scraping/Ada/web-scraping.adb b/Task/Web-scraping/Ada/web-scraping.adb new file mode 100644 index 0000000000..776c41856f --- /dev/null +++ b/Task/Web-scraping/Ada/web-scraping.adb @@ -0,0 +1,34 @@ +with AWS.Client, AWS.Response, AWS.Resources, AWS.Messages; +with Ada.Text_IO, Ada.Strings.Fixed; +use Ada, AWS, AWS.Resources, AWS.Messages; + +procedure Get_UTC_Time is + + Page : Response.Data; + File : Resources.File_Type; + Buffer : String (1 .. 1024); + Position, Last : Natural := 0; + S : Messages.Status_Code; +begin + Page := Client.Get ("http://tycho.usno.navy.mil/cgi-bin/timer.pl"); + S := Response.Status_Code (Page); + if S not in Success then + Text_IO.Put_Line + ("Unable to retrieve data => Status Code :" & Image (S) & + " Reason :" & Reason_Phrase (S)); + return; + end if; + + Response.Message_Body (Page, File); + while not End_Of_File (File) loop + Resources.Get_Line (File, Buffer, Last); + Position := + Strings.Fixed.Index + (Source => Buffer (Buffer'First .. Last), + Pattern => "UTC"); + if Position > 0 then + Text_IO.Put_Line (Buffer (5 .. Position + 2)); + return; + end if; + end loop; +end Get_UTC_Time; diff --git a/Task/Web-scraping/FreeBASIC/web-scraping.basic b/Task/Web-scraping/FreeBASIC/web-scraping.basic new file mode 100644 index 0000000000..587228fb7f --- /dev/null +++ b/Task/Web-scraping/FreeBASIC/web-scraping.basic @@ -0,0 +1,52 @@ +' Linux: fbc programa.bas +' Windows: install wget (winget install GnuWin32.WGet) & fbc programa.bas + +Dim As String sContent, sUTC, sRFC850, tmpFile, cmd + +' Detect system and use temporary folder +#Ifdef __FB_WIN32__ + tmpFile = Environ("TEMP") & "\utctime.html" + cmd = "wget -q -O """ & tmpFile & """ https://www.utctime.net" +#Else + tmpFile = "/tmp/utctime.html" + cmd = "wget -q -O " & tmpFile & " https://www.utctime.net" +#EndIf + +Shell cmd + +Dim As Integer ff = Freefile +If Open(tmpFile For Input As #ff) <> 0 Then + Print "Error: wget failed or file is not accessible." + Sleep: End +End If + +' Read full content +sContent = "" +While Not Eof(ff) + Dim As String linea + Line Input #ff, linea + sContent &= linea & Chr(10) +Wend +Close #ff + +' Extract UTC and RFC 850 +Dim As Integer utcStart = Instr(sContent, "UTC") +If utcStart > 0 Then + utcStart += 12 + Dim As Integer utcEnd = Instr(utcStart, sContent, "") + If utcEnd > 0 Then sUTC = Rtrim(Mid(sContent, utcStart, utcEnd - utcStart)) +End If + +Dim As Integer rfcStart = Instr(sContent, "RFC 850") +If rfcStart > 0 Then + rfcStart += 16 + Dim As Integer rfcEnd = Instr(rfcStart, sContent, "") + If rfcEnd > 0 Then sRFC850 = Rtrim(Mid(sContent, rfcStart, rfcEnd - rfcStart)) +End If + +Kill tmpFile + +If sUTC <> "" Then Print "UTC: " & sUTC +If sRFC850 <> "" Then Print "RFC 850: " & sRFC850 + +Sleep diff --git a/Task/Web-scraping/PowerShell/web-scraping-1.ps1 b/Task/Web-scraping/PowerShell/web-scraping-1.ps1 new file mode 100644 index 0000000000..31ae4c5319 --- /dev/null +++ b/Task/Web-scraping/PowerShell/web-scraping-1.ps1 @@ -0,0 +1,4 @@ +$wc = New-Object Net.WebClient +$html = $wc.DownloadString('http://tycho.usno.navy.mil/cgi-bin/timer.pl') +$html -match ', (.*) UTC' | Out-Null +Write-Host $Matches[1] diff --git a/Task/Web-scraping/PowerShell/web-scraping-2.ps1 b/Task/Web-scraping/PowerShell/web-scraping-2.ps1 new file mode 100644 index 0000000000..8562941d22 --- /dev/null +++ b/Task/Web-scraping/PowerShell/web-scraping-2.ps1 @@ -0,0 +1 @@ +[System.DateTime]::UtcNow diff --git a/Task/Web-scraping/PowerShell/web-scraping-3.ps1 b/Task/Web-scraping/PowerShell/web-scraping-3.ps1 new file mode 100644 index 0000000000..90bbbe6bb0 --- /dev/null +++ b/Task/Web-scraping/PowerShell/web-scraping-3.ps1 @@ -0,0 +1 @@ +[System.DateTime]::Now diff --git a/Task/Web-scraping/QB64/web-scraping.qb64 b/Task/Web-scraping/QB64/web-scraping.qb64 new file mode 100644 index 0000000000..359feff376 --- /dev/null +++ b/Task/Web-scraping/QB64/web-scraping.qb64 @@ -0,0 +1,38 @@ +' Assuming WGET is installed +Dim sContent$, sUTC$, sRFC850$, tmpFile$, cmd$, linea$ + +tmpFile$ = Environ$("TEMP") + "\utctime.html" +cmd$ = "wget -q -O " + tmpFile$ + " https://www.utctime.net" + +Print "Download with wget..." +Shell _Hide cmd$ + +' Read file +If _FileExists(tmpFile$) Then + Open tmpFile$ For Input As #1 + sContent$ = "" + While Not EOF(1) + Line Input #1, linea$ + sContent$ = sContent$ + linea$ + Chr$(10) + Wend + Close #1 + Kill tmpFile$ +End If + +' Extract UTC and RFC 850 +utcStart = InStr(sContent$, "UTC") +If utcStart > 0 Then + utcStart = utcStart + 12 + utcEnd = InStr(utcStart, sContent$, "") + If utcEnd > 0 Then sUTC$ = RTrim$(Mid$(sContent$, utcStart, utcEnd - utcStart)) +End If + +rfcStart = InStr(sContent$, "RFC 850") +If rfcStart > 0 Then + rfcStart = rfcStart + 16 + rfcEnd = InStr(rfcStart, sContent$, "") + If rfcEnd > 0 Then sRFC850$ = RTrim$(Mid$(sContent$, rfcStart, rfcEnd - rfcStart)) +End If + +Print "UTC: "; sUTC$ +Print "RFC 850: "; sRFC850$ diff --git a/Task/Web-scraping/REXX/web-scraping.rexx b/Task/Web-scraping/REXX/web-scraping.rexx new file mode 100644 index 0000000000..160a719957 --- /dev/null +++ b/Task/Web-scraping/REXX/web-scraping.rexx @@ -0,0 +1,30 @@ +-- 23 Oct 2025 +include Setting +signal off notready + +say 'WEB SCRAPING' +say version +say +call Task +exit + +Task: +procedure +-- Get page from web (curl is pre-installed on Windows 10/11, Unix and MacOS) +out='Web.html' +'curl https://rosettacode.org/wiki/Talk:Web_scraping --ssl-no-revoke --silent --output' out +-- Read file +file=Charin(out,1,100000) +-- Extract all time stamps +p=Pos('(UTC)',file) +do while p>0 + p2=p-2 + do p1=p2 by -1 until Substr(file,p1,1)=':' + end + p1-=2 + say Substr(file,p1,p2-p1+1) + p=Pos('(UTC)',file,p+1) +end +return + +include Abend diff --git a/Task/Web-scraping/Rebol/web-scraping.rebol b/Task/Web-scraping/Rebol/web-scraping.rebol new file mode 100644 index 0000000000..d8290431d1 --- /dev/null +++ b/Task/Web-scraping/Rebol/web-scraping.rebol @@ -0,0 +1,25 @@ +Rebol [ + Title: "Web Scraping" + URL: http://rosettacode.org/wiki/Web_Scraping +] + +; Notice that REBOL understands unquoted URL's: + +service: http://tycho.usno.navy.mil/cgi-bin/timer.pl + +; The 'read' function can read from any data scheme that REBOL knows +; about, which includes web URLs. NOTE: Depending on your security +; settings, REBOL may ask you for permission to contact the service. + +html: read service + +; I parse the HTML to find the first
    (note the unquoted HTML tag +; -- REBOL understands those too), then copy the current time from +; there to the "UTC" terminator. + +; I have the "to end" in the parse rule so the parse will succeed. +; Not strictly necessary once I've got the time, but good practice. + +parse html [thru
    copy current thru "UTC" to end] + +print ["Current UTC time:" current] diff --git a/Task/Web-scraping/VBScript/web-scraping.vbs b/Task/Web-scraping/VBScript/web-scraping.vbs new file mode 100644 index 0000000000..57dfb77722 --- /dev/null +++ b/Task/Web-scraping/VBScript/web-scraping.vbs @@ -0,0 +1,30 @@ +Function GetUTC() As String + Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + With CreateObject("MSXML2.XMLHTTP.6.0") + .Open "GET", Url, False + .send + arrt = Split(.responseText, vbLf) + End With + For Each t In arrt + If InStr(t, "UTC") Then + GetUTC = StripHttpTags(t) + + Exit For + End If + Next +End Function + +Function StripHttpTags(s) + With New RegExp + .Global = True + .Pattern = "\<.+?\>" + If .Test(s) Then + StripHttpTags = .Replace(s, "") + Else + StripHttpTags = s + End If + End With +End Function + +WScript.StdOut.Write GetUTC +WScript.StdOut.WriteLine diff --git a/Task/Web-scraping/Yabasic/web-scraping-1.basic b/Task/Web-scraping/Yabasic/web-scraping-1.basic new file mode 100644 index 0000000000..99381df23e --- /dev/null +++ b/Task/Web-scraping/Yabasic/web-scraping-1.basic @@ -0,0 +1,3 @@ +cd /d c:\Yabasic +wget -q -O utctime.html https://www.utctime.net +yabasic webscraping.yab diff --git a/Task/Web-scraping/Yabasic/web-scraping-2.basic b/Task/Web-scraping/Yabasic/web-scraping-2.basic new file mode 100644 index 0000000000..4d28281c0b --- /dev/null +++ b/Task/Web-scraping/Yabasic/web-scraping-2.basic @@ -0,0 +1,25 @@ +// Read file line by line +open "utctime.html" for reading as #1 +sContent$ = "" +while not eof(1) + line input #1 linea$ + sContent$ = sContent$ + linea$ + chr$(10) +wend +close #1 + +utcStart = instr(sContent$, "UTC") +if utcStart > 0 then + utcStart = utcStart + 12 + utcEnd = instr(sContent$, "", utcStart) + if utcEnd > 0 sUTC$ = trim$(mid$(sContent$, utcStart, utcEnd - utcStart)) +end if + +rfcStart = instr(sContent$, "RFC 850") +if rfcStart > 0 then + rfcStart = rfcStart + 16 + rfcEnd = instr(sContent$, "", rfcStart) + if rfcEnd > 0 sRFC850$ = trim$(mid$(sContent$, rfcStart, rfcEnd - rfcStart)) +end if + +print "UTC: ", sUTC$ +print "RFC 850: ", sRFC850$ diff --git a/Task/Weird-numbers/Ada/weird-numbers-1.adb b/Task/Weird-numbers/Ada/weird-numbers-1.adb new file mode 100644 index 0000000000..906371dcc6 --- /dev/null +++ b/Task/Weird-numbers/Ada/weird-numbers-1.adb @@ -0,0 +1,109 @@ +pragma Ada_2022; + +with Ada.Text_IO; +with Ada.Containers.Vectors; +with Ada.Containers.Ordered_Sets; + +procedure Weird_Numbers is + package IO renames Ada.Text_IO; + -- allows us to type "IO.Put_Line" instead of "Ada.Text_IO.Put_Line" + + package IntVecs is new Ada.Containers.Vectors + (Index_Type => Positive, Element_Type => Natural); + subtype IntVec is IntVecs.Vector; +-- use all type IntVec; + + Factor_Cache : IntVec; + -- used to keep track of the factors on each iteration + + package Intsets is new Ada.Containers.Ordered_Sets + (Element_Type => Positive); + subtype Intset is Intsets.Set; + Semiperfect_Cache : Intset; + Not_Abundant_Cache : Intset; + + function Proper_Divisors (Value : Positive) return IntVec is + Cofactors : IntVec; + begin + Factor_Cache.Clear; + begin + Factor_Cache.Append (1); + for Factor in 2 .. Value / 2 loop + if Value rem Factor = 0 then + Factor_Cache.Append (Factor); + end if; + end loop; + return Factor_Cache; + end; + end Proper_Divisors; + + function Is_Abundant (Value : Positive) return Boolean is + begin + if Not_Abundant_Cache.Contains (Value) + or else Semiperfect_Cache.Contains (Value) + then + return False; + end if; + if Proper_Divisors (Value)'Reduce ("+", 0) > Value then + return True; + end if; + Not_Abundant_Cache.Insert (Value); + return False; + end Is_Abundant; + + function Subset_Of (Factors : IntVec; Ith : Positive) return IntVec is + -- returns the Ith subset of Factors + -- if Factors has N elements, then there are 2**N possibilities + -- this maps Ith to one of these possibilities using its binary representation + Result : IntVec; + Index : Natural := 1; + Ith_Remainder : Natural := Ith; + begin + while Ith_Remainder /= 0 loop + if Ith_Remainder rem 2 = 1 then + Result.Append (Factors (Index)); + Ith_Remainder := @ - 1; + end if; + Ith_Remainder := @ / 2; + Index := @ + 1; + end loop; + return Result; + end Subset_Of; + + function Is_Semiperfect (Value : Positive) return Boolean is + Factors : constant IntVec := Factor_Cache; + Subset : IntVec; + Sum : Natural; + begin + if (for some Previous of Semiperfect_Cache => Value rem Previous = 0) + then + return True; + end if; + for Ith in reverse 1 .. (2**Positive (Factors.Length) - 1) loop + Subset := Subset_Of (Factors, Positive (Ith)); + Sum := Subset'Reduce ("+", 0); + if Sum = Value then + Semiperfect_Cache.Insert (Value); + return True; + end if; + end loop; + return False; + end Is_Semiperfect; + + function Is_Weird (Value : Positive) return Boolean is + (Is_Abundant (Value) and then not Is_Semiperfect (Value)); + + Current : Positive := 2; + Number_Found : Natural := 0; + +begin + IO.Put ("The first 25 weird numbers are"); + while Number_Found < 25 loop + if Is_Weird (Current * 2) then + IO.Put (Integer'Image (Current * 2)); + Number_Found := @ + 1; + end if; + Current := @ + 1; + end loop; + IO.New_Line; +end Weird_Numbers; diff --git a/Task/Weird-numbers/Ada/weird-numbers-2.adb b/Task/Weird-numbers/Ada/weird-numbers-2.adb new file mode 100644 index 0000000000..f1a649cfab --- /dev/null +++ b/Task/Weird-numbers/Ada/weird-numbers-2.adb @@ -0,0 +1,105 @@ +pragma Ada_2022; + +with Ada.Text_IO; +with Ada.Containers.Vectors; +with Ada.Containers.Ordered_Sets; + +procedure Weird_Numbers is + package IO renames Ada.Text_IO; + + package IntVecs is new Ada.Containers.Vectors + (Index_Type => Positive, Element_Type => Positive); + subtype IntVec is IntVecs.Vector; + use all type IntVec; + + Factor_Cache : IntVec; + + package Intsets is new Ada.Containers.Ordered_Sets + (Element_Type => Positive); + subtype Intset is Intsets.Set; + Semiperfect_Cache : Intset; + Not_Abundant_Cache : Intset; + + function Proper_Divisors (Value : Positive) return IntVec is + Cofactors : IntVec; + begin + Factor_Cache.Clear; + begin + Factor_Cache.Append (1); + for Factor in 2 .. Value / 2 loop + if Factor * Factor > Value then + exit; + end if; + if Value rem Factor = 0 then + Factor_Cache.Append (Factor); + if Factor * Factor /= Value then + Cofactors.Append (Value / Factor); + end if; + end if; + end loop; + Factor_Cache.Prepend_Vector (Cofactors); + -- this ordering is REALLY curious + -- for instance, the factors of 12 are ordered as 6, 4, 1, 2, 3 + -- AND THIS MATTERS + -- both strictly ascending and strictly descending orders are much slower + return Factor_Cache; + end; + end Proper_Divisors; + + function Is_Abundant (Value : Positive) return Boolean is + begin + if Not_Abundant_Cache.Contains (Value) + or else Semiperfect_Cache.Contains (Value) + then + return False; + end if; + if Proper_Divisors (Value)'Reduce ("+", 0) > Value then + return True; + end if; + Not_Abundant_Cache.Insert (Value); + return False; + end Is_Abundant; + + function Alternate_Semiperfect (Value : Positive) return Boolean is + function Reroute + (Value : Positive; First : Positive) return Boolean + is + Head : Positive; + begin + if Factor_Cache.Last_Index >= First then + Head := Factor_Cache (First); + if Value < Head then + return Reroute (Value, First + 1); + else + return + Value = Head + or else Reroute (Value - Head, First + 1) + or else Reroute (Value, First + 1); + end if; + else + return False; + end if; + end Reroute; + begin + return + Reroute + (Value, Factor_Cache.First_Index); + end Alternate_Semiperfect; + + function Is_Weird (Value : Positive) return Boolean is + (Is_Abundant (Value) and then not Alternate_Semiperfect (Value)); + + Current : Positive := 2; + Number_Found : Natural := 0; + +begin + IO.Put ("The first 25 weird numbers are"); + while Number_Found < 25 loop + if Is_Weird (Current * 2) then + IO.Put (Integer'Image (Current * 2)); + Number_Found := @ + 1; + end if; + Current := @ + 1; + end loop; + IO.New_Line; +end Weird_Numbers; diff --git a/Task/Weird-numbers/Uiua/weird-numbers.uiua b/Task/Weird-numbers/Uiua/weird-numbers.uiua new file mode 100644 index 0000000000..13a5f19c88 --- /dev/null +++ b/Task/Weird-numbers/Uiua/weird-numbers.uiua @@ -0,0 +1,16 @@ +Or! ←^ /$"swi(_|1)below(_)" # Code macro for shortcutting `or` +S ← |2 memo⨬(⨬(Or!(S⊙◌|S˜-|=)|0)◡>⊙°⊂|0)=0⊃⋅⧻⊙∘ # subset sum? + +ADx ← |1 ⨬(◴⊂⊂⊃(⊙∘|/⊂⊞×)\×°□⊙ADx°⊂|[1])=0⊸⧻ +ADs ← ⍆ADx⊕□⊸⊛°/× # All divisors including 1, n. +PDs ← ↘¯1ADs # Proper Divisors. +Abundant ← 1 ) + q = ( 2 * q ) % p2 + p = p - 1 + wend + if ( q == 1 ) then return YES else return NO +end fn = NO + +void local fn FindWieferichs + printf @"Wieferich primes less than 5,000:" + for NSUInteger i = 1 to 5000 + if fn IsWieferichPrime(i) then printf @"\t%lu\t\b", i + next +end fn + +fn FindWieferichs + +HandleEvents diff --git a/Task/Wieferich-primes/Maxima/wieferich-primes.maxima b/Task/Wieferich-primes/Maxima/wieferich-primes.maxima new file mode 100644 index 0000000000..bfa8a5bdca --- /dev/null +++ b/Task/Wieferich-primes/Maxima/wieferich-primes.maxima @@ -0,0 +1,2 @@ +is_wieferich(p) := mod(2^(p-1)-1, p^2)=0$ +sublist(primes(1, 5000), is_wieferich); diff --git a/Task/Wieferich-primes/Uiua/wieferich-primes.uiua b/Task/Wieferich-primes/Uiua/wieferich-primes.uiua new file mode 100644 index 0000000000..13c2291a7d --- /dev/null +++ b/Task/Wieferich-primes/Uiua/wieferich-primes.uiua @@ -0,0 +1,2 @@ +Powmod ← ⊙◌∧(⊸˜◿×⊙˙×)⊙1+1×-1⊙(⇌⋯) +▽=1⊸≡(Powmod⊃(⋅2|-1|ⁿ2))▽⊸(=⊣⊸°/×)+2⇡5000 diff --git a/Task/Wilson-primes-of-order-n/AWK/wilson-primes-of-order-n.awk b/Task/Wilson-primes-of-order-n/AWK/wilson-primes-of-order-n.awk new file mode 100644 index 0000000000..06df7bdc6b --- /dev/null +++ b/Task/Wilson-primes-of-order-n/AWK/wilson-primes-of-order-n.awk @@ -0,0 +1,47 @@ +# syntax: GAWK -f WILSON_PRIMES_OF_ORDER_N.AWK +# converted from FreeBASIC +# +# This excludes the trivial case p=n=2 as does: +# Ada, EasyLang, FreeBasic, FutureBasic, Maxima, PARI/GP +BEGIN { + print(" n Wilson primes") + print("-- -------------") + for (n=1; n<=11; n++) { + printf("%2d ",n) + for (p=3; p<11000; p+=2) { + if (is_prime(p)) { + if (is_wilson_prime(n,p)) { + printf(" %d",p) + } + } + } + printf("\n") + } + exit(0) +} +function is_prime(n, d) { + d = 5 + if (n < 2) { return(0) } + if (n % 2 == 0) { return(n == 2) } + if (n % 3 == 0) { return(n == 3) } + while (d*d <= n) { + if (n % d == 0) { return(0) } + d += 2 + if (n % d == 0) { return(0) } + d += 4 + } + return(1) +} +function is_wilson_prime(n,p, i,prod,p2) { + if (p < n) { return(0) } + prod = 1 + p2 = p^2 + for (i=1; i<=n-1; i++) { + prod = (prod*i) % p2 + } + for (i=1; i<=p-n; i++) { + prod = (prod*i) % p2 + } + prod = (p2 + prod - (-1)^n) % p2 + return(prod == 0) +} diff --git a/Task/Wilson-primes-of-order-n/Ada/wilson-primes-of-order-n.adb b/Task/Wilson-primes-of-order-n/Ada/wilson-primes-of-order-n.adb new file mode 100644 index 0000000000..e555bad79f --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Ada/wilson-primes-of-order-n.adb @@ -0,0 +1,62 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Strings_Edit.Integers; use Strings_Edit.Integers; +with Unbounded_Unsigneds; use Unbounded_Unsigneds; +with Unbounded_Unsigneds.Primes; use Unbounded_Unsigneds.Primes; + +with Strings_Edit.Unbounded_Unsigned_Edit; +use Strings_Edit.Unbounded_Unsigned_Edit; + +procedure Wilson_Primes is + + function Factorial (N : Half_Word) return Unbounded_Unsigned is + Result : Unbounded_Unsigned := One; + begin + for I in 2..N loop + Mul (Result, I); + end loop; + return Result; + end Factorial; + + L : String (1..100) := (others => ' '); + I : Integer := 1; + + procedure Check (P : Half_Word) is + W : Unbounded_Unsigned := From_Half_Word (P); + begin + if Is_Prime (W, 10) = Prime then + W := Square (W); + for N in Half_Word range 1..11 loop + if P >= N then + if (Factorial (N - 1) * Factorial (P - N) + 2 * (N mod 2) - 1) + mod W = 0 + then + I := Integer (N - 1) * 5 + 1; + Put + ( Destination => L, + Pointer => I, + Value => Integer (P), + Field => 5, + Justify => Strings_Edit.Right, + Fill => ' ' + ); + end if; + end if; + end loop; + if I > 1 then + Put_Line (L (1..I - 1)); + for J in 1..I loop + L (J) := ' '; + I := 1; + end loop; + end if; + end if; + end Check; +begin + Put_Line (" 1 2 3 4 5 6 7 8 9 10 11"); + Put_Line ("-------------------------------------------------------"); + for I in Half_Word range 1..Half_Word'Last loop + Check (I * 6 - 1); + Check (I * 6 + 1); + exit when I > 1834; + end loop; +end Wilson_Primes; diff --git a/Task/Wilson-primes-of-order-n/Agena/wilson-primes-of-order-n.agena b/Task/Wilson-primes-of-order-n/Agena/wilson-primes-of-order-n.agena new file mode 100644 index 0000000000..ea8bd3a70a --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Agena/wilson-primes-of-order-n.agena @@ -0,0 +1,37 @@ +scope # find some Wilson primes of order n, primes p such that + # ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 + + local constant maxPrime := 11_000; + + # returns true if p is an nth order Wilson prime, false otherwise + local proc isWilson( n :: integer, p :: integer ) :: boolean + local result := false; + if p >= n then + local p2, prod := p * p, 1; + for i to n - 1 do # prod := ( n - 1 )! mod p2 + prod := ( prod * i ) mod p2 + od; + for i to p - n do # prod := ( ( p - n )! * ( n - 1 )! ) mod p2 + prod := ( prod * i ) mod p2 + od; + result := 0 = ( p2 + prod + if odd n then 1 else -1 fi ) mod p2 + fi; + return result + end; + + scope # find the Wilson primes + print( " n: Wilson primes" ); + print( "-----------------" ); + for n to 11 do + printf( "%2d:", n ); + if isWilson( n, 2 ) then printf( " 2" ) fi; + for p from 3 to maxPrime by 2 do + if numtheory.isprime( p ) then + if isWilson( n, p ) then printf( " %d", p ) fi + fi + od; + print() + od + epocs + +epocs diff --git a/Task/Wilson-primes-of-order-n/Fennel/wilson-primes-of-order-n.fennel b/Task/Wilson-primes-of-order-n/Fennel/wilson-primes-of-order-n.fennel new file mode 100644 index 0000000000..16ba9e4c45 --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Fennel/wilson-primes-of-order-n.fennel @@ -0,0 +1,59 @@ +(do ;;; find some Wilson primes of order n, primes p such that + ;;; ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 + + (local max-prime 11_000) + + (fn wilson-prime? [n p] ; returns true if p is an nth order Wilson prime, false otherwise + (var result false) + (when (>= p n) + (var (p2 prod) (values (* p p) 1)) + (for [i 1 (- n 1)] ; prod = ( n - 1 )! % p2 + (set prod (% (* prod i) p2)) + ) + (for [i 1 (- p n)] ; prod = ( ( p - n )! * ( n - 1 )! ) % p2 + (set prod (% (* prod i) p2)) + ) + (set result (= 0 (% (+ p2 prod (if (= (band n 1) 1) + 1 + ;else + -1 + ) + ) + p2 + ) + ) + ) + ) + result + ) + + (fn prime? [p] ; returns true if p is prime, false otherwise + (if (or (<= p 2) (= 0 (% p 2))) + (= p 2) + ;else + (do (var (prime i) (values true 3)) + (local root-p (math.floor (math.sqrt p))) + (while (and (<= i root-p) prime) + (set (prime i) (values (not= 0 (% p i)) (+ i 1))) + ) + prime + ) + ) + ) + + (do ; find the Wilson primes + (io.write " n: Wilson primes\n" ) + (io.write "-----------------\n" ) + (for [n 1 11] + (io.write (string.format "%2d:" n)) + (when (wilson-prime? n 2) (io.write " 2")) + (for [p 3 max-prime 2] + (when (prime? p) + (when (wilson-prime? n p) (io.write (.. " " p))) + ) + ) + (io.write "\n") + ) + ) + +) diff --git a/Task/Wilson-primes-of-order-n/FutureBasic/wilson-primes-of-order-n.basic b/Task/Wilson-primes-of-order-n/FutureBasic/wilson-primes-of-order-n.basic new file mode 100644 index 0000000000..5e98a30b52 --- /dev/null +++ b/Task/Wilson-primes-of-order-n/FutureBasic/wilson-primes-of-order-n.basic @@ -0,0 +1,44 @@ +BOOL local fn IsPrime( n as NSUInteger ) + if n < 2 then exit fn = NO + if n = 2 then exit fn = YES + if n % 2 == 0 then exit fn = NO + for NSUInteger i = 3 to int(n^.5) step 2 + if n % i == 0 then exit fn = NO + next +end fn = YES + +BOOL local fn IsWilson( n as NSUInteger, p as NSUInteger ) + if ( p < n ) then return NO + NSUInteger i, prod = 1, p2 = p^2 + + for i = 1 to n - 1 + prod = ( prod * i ) % p2 + next + + for i = 1 to p - n + prod = ( prod * i ) % p2 + next + + prod = ( p2 + prod - (-1) ^ n ) % p2 + if ( prod == 0 ) then return YES else return NO +end fn = NO + +local fn WilsonPrimes + CFStringRef lines = fn StringByPaddingToLength( @"", 27, @"-", 0 ) + printf lines + printf @" n: Wilson primes" + printf lines + + for int n = 1 to 11 + printf @"%2d :\t\b", n + for int p = 3 to 10099 step 2 + if fn IsPrime(p) && fn IsWilson( n, p ) then printf @"%-5d\b", p + next + print + next + printf lines +end fn + +fn WilsonPrimes + +HandleEvents diff --git a/Task/Wilson-primes-of-order-n/Lua/wilson-primes-of-order-n.lua b/Task/Wilson-primes-of-order-n/Lua/wilson-primes-of-order-n.lua new file mode 100644 index 0000000000..90afb9cef7 --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Lua/wilson-primes-of-order-n.lua @@ -0,0 +1,50 @@ +do -- find some Wilson primes of order n, primes p such that + -- ( ( n - 1 )! x ( p - n )! - (-1)^n ) mod p^2 = 0 + + local maxPrime = 11000 + + -- returns true if p is an nth order Wilson prime, false otherwise + local function isWilson( n, p ) + local result = false + if p >= n then + local p2, prod = p * p, 1 + for i = 1, n - 1 do -- prod = ( n - 1 )! % p2 + prod = ( prod * i ) % p2 + end + for i = 1, p - n do -- prod = ( ( p - n )! * ( n - 1 )! ) % p2 + prod = ( prod * i ) % p2 + end + result = 0 == ( p2 + prod + ( n & 1 == 1 and 1 or -1 ) ) % p2 + end + return result + end + + local function isprime( p ) + if p <= 2 or p % 2 == 0 then + return p == 2 + else + local prime, i = true, 3 + local rootP = math.floor( math.sqrt( p ) ) + while i <= rootP and prime do + prime, i = p % i ~= 0, i + 1 + end + return prime + end + end + + do -- find the Wilson primes + io.write( " n: Wilson primes\n" ) + io.write( "-----------------\n" ) + for n = 1, 11 do + io.write( string.format( "%2d:", n ) ) + if isWilson( n, 2 ) then io.write( " 2" ) end + for p = 3, maxPrime, 2 do + if isprime( p ) then + if isWilson( n, p ) then io.write( " " .. p ) end + end + end + io.write( "\n" ) + end + end + +end diff --git a/Task/Wilson-primes-of-order-n/Maxima/wilson-primes-of-order-n.maxima b/Task/Wilson-primes-of-order-n/Maxima/wilson-primes-of-order-n.maxima new file mode 100644 index 0000000000..f5084c901d --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Maxima/wilson-primes-of-order-n.maxima @@ -0,0 +1,7 @@ +wilson(p, n) := if p>n then (n-1)!*(p-n)!-(-1)^n else (-1)^(n+1)$ + +is_wilson(p, n) := integerp(wilson(p, n)/p^2)$ + +wilsons(n) := sublist(primes(2, 11000), lambda([p], is_wilson(p, n)))$ + +makelist(wilsons(i), i, 1, 11); diff --git a/Task/Wilson-primes-of-order-n/Pluto/wilson-primes-of-order-n.pluto b/Task/Wilson-primes-of-order-n/Pluto/wilson-primes-of-order-n.pluto new file mode 100644 index 0000000000..b37f630388 --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Pluto/wilson-primes-of-order-n.pluto @@ -0,0 +1,23 @@ +local int = require "int" +local bigint = require "bigint" +local fmt = require "fmt" + +local limit = 11000 +local primes = int.primes(limit) +local facts = {} +facts[0] = bigint.new(1) +for i = 1, limit - 1 do facts[i] = facts[i - 1] * bigint.new(i) end +local sign = bigint.new(1) +local zero = bigint.new(0) +print(" n: Wilson primes") +print("--------------------") +for n = 1, 11 do + fmt.write("%2d: ", n) + sign = zero - sign + for primes as p do + if p < n then continue end + local f = facts[n - 1] * facts[p - n] - sign + if f % bigint.new(p * p) == zero then io.write($"{p} ") end + end + print() +end diff --git a/Task/Wilson-primes-of-order-n/R/wilson-primes-of-order-n.r b/Task/Wilson-primes-of-order-n/R/wilson-primes-of-order-n.r new file mode 100644 index 0000000000..42860b256c --- /dev/null +++ b/Task/Wilson-primes-of-order-n/R/wilson-primes-of-order-n.r @@ -0,0 +1,8 @@ +library(gmp) + +wilson <- function(p, n) factorialZ(n-1)*factorialZ(p-n)-(-1)^n +is_wilson <- function(p, n) denominator(as.bigq(wilson(p, n), p^2))==1 +primes <- Filter(function(n) isprime(n)!=0, 1:11000) +wilsons <- lapply(1:11, function(n) Filter(function(p) is_wilson(p, n), primes)) +for(i in 1:11) if(length(wilsons[[i]])==0) wilsons[[i]] <- "None" +print(wilsons, quote=FALSE) diff --git a/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx index e98e78b0e7..588a381a9a 100644 --- a/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx +++ b/Task/Wilson-primes-of-order-n/REXX/wilson-primes-of-order-n-1.rexx @@ -1,9 +1,9 @@ --- 24 Aug 2025 +-- 10 Mar 2026 include Setting numeric digits 40000 arg xx -if xx = '' then - xx = 11000 +if xx='' then + xx=11000 say 'WILSON PRIMES OF ORDER N' say version @@ -27,7 +27,8 @@ GetFactorials: procedure expose fcto. arg xx say 'Get factorials...' -say Factorials(xx) 'found' +call Factorials xx +say xx+1 'found' say return @@ -36,20 +37,21 @@ procedure expose prim. fcto. arg xx say ' n: Wilson primes' say '--------------------' -mo = 1 -do n = 1 to 11 - a = Right(n,3)':'; n1 = n-1; n1 = fcto.n1; mo = -mo - do i = 1 to prim.0 - p = prim.i - if p < n then +mo=1 +do n=1 to 11 + a=Right(n,3)':'; n1=n-1; n1=fcto.n1; mo=-mo + do i=1 to prim.0 + p=prim.i + if p GnuCOBOL does not evaluate C macros, need to peek at opaque + *> data from Xlib.h + *> some padding is added, due to this comment in the header + *> "there is more to this structure, but it is private to Xlib" + 01 x-display-private based. + 05 x-ext-data usage pointer sync. + 05 private1 usage pointer. + 05 x-fd usage binary-long. + 05 private2 usage binary-long. + 05 proto-major-version usage binary-long. + 05 proto-minor-version usage binary-long. + 05 vendor usage pointer sync. + 05 private3 usage pointer. + 05 private4 usage pointer. + 05 private5 usage pointer. + 05 private6 usage binary-long. + 05 allocator usage program-pointer sync. + 05 byte-order usage binary-long. + 05 bitmap-unit usage binary-long. + 05 bitmap-pad usage binary-long. + 05 bitmap-bit-order usage binary-long. + 05 nformats usage binary-long. + 05 screen-format usage pointer sync. + 05 private8 usage binary-long. + 05 x-release usage binary-long. + 05 private9 usage pointer sync. + 05 private10 usage pointer sync. + 05 qlen usage binary-long. + 05 last-request-read usage binary-c-long unsigned sync. + 05 request usage binary-c-long unsigned sync. + 05 private11 usage pointer sync. + 05 private12 usage pointer. + 05 private13 usage pointer. + 05 private14 usage pointer. + 05 max-request-size usage binary-long unsigned. + 05 x-db usage pointer sync. + 05 private15 usage program-pointer sync. + 05 display-name usage pointer. + 05 default-screen usage binary-long. + 05 nscreens usage binary-long. + 05 screens usage pointer sync. + 05 motion-buffer usage binary-c-long unsigned. + 05 private16 usage binary-c-long unsigned. + 05 min-keycode usage binary-long. + 05 max-keycode usage binary-long. + 05 private17 usage pointer sync. + 05 private18 usage pointer. + 05 private19 usage binary-long. + 05 x-defaults usage pointer sync. + 05 filler pic x(256). + + 01 x-screen-private based. + 05 scr-ext-data usage pointer sync. + 05 display-back usage pointer. + 05 root usage binary-c-long. + 05 x-width usage binary-long. + 05 x-height usage binary-long. + 05 m-width usage binary-long. + 05 m-height usage binary-long. + 05 x-ndepths usage binary-long. + 05 depths usage pointer sync. + 05 root-depth usage binary-long. + 05 root-visual usage pointer sync. + 05 default-gc usage pointer. + 05 cmap usage pointer. + 05 white-pixel usage binary-c-long unsigned sync. + 05 black-pixel usage binary-c-long unsigned. + 05 max-maps usage binary-long. + 05 min-maps usage binary-long. + 05 backing-store usage binary-long. + 05 save_unders usage binary-char. + 05 root-input-mask usage binary-c-long sync. + 05 filler pic x(256). + + 01 event. + 05 e-type usage binary-long. + 05 filler pic x(188). + 05 filler pic x(256). + 01 Expose constant as 12. + 01 KeyPress constant as 2. + + *> ExposureMask or-ed with KeyPressMask, from X.h + 01 event-mask usage binary-c-long value 32769. + + *> make the box around the message wide enough for the font + 01 x-char-struct. + 05 lbearing usage binary-short. + 05 rbearing usage binary-short. + 05 string-width usage binary-short. + 05 ascent usage binary-short. + 05 descent usage binary-short. + 05 attributes usage binary-short unsigned. + 01 font-direction usage binary-long. + 01 font-ascent usage binary-long. + 01 font-descent usage binary-long. + + 01 XGContext usage binary-c-long. + 01 box-width usage binary-long. + 01 box-height usage binary-long. + + *> *************************************************************** + procedure division. + + call "XOpenDisplay" using by reference null returning x-display + on exception + display function module-id " Error: " + "no XOpenDisplay linkage, requires libX11" + upon syserr + stop run returning 1 + end-call + if x-display equal null then + display function module-id " Error: " + "XOpenDisplay returned null" upon syserr + stop run returning 1 + end-if + set address of x-display-private to x-display + + if screens equal null then + display function module-id " Error: " + "XOpenDisplay associated screen null" upon syserr + stop run returning 1 + end-if + set address of x-screen-private to screens + + call "XCreateSimpleWindow" using + by value x-display root 10 10 200 50 1 + black-pixel white-pixel + returning x-window + call "XStoreName" using + by value x-display x-window by reference msg + + call "XSelectInput" using by value x-display x-window event-mask + + call "XMapWindow" using by value x-display x-window + + call "XGContextFromGC" using by value default-gc + returning XGContext + call "XQueryTextExtents" using by value x-display XGContext + by reference msg by value msg-len + by reference font-direction font-ascent font-descent + x-char-struct + compute box-width = string-width + 8 + compute box-height = font-ascent + font-descent + 8 + + perform forever + call "XNextEvent" using by value x-display by reference event + if e-type equal Expose then + call "XDrawRectangle" using + by value x-display x-window default-gc 5 5 + box-width box-height + call "XDrawString" using + by value x-display x-window default-gc 10 20 + by reference msg by value msg-len + end-if + if e-type equal KeyPress then exit perform end-if + end-perform + + call "XCloseDisplay" using by value x-display + + goback. + end program x11-hello. diff --git a/Task/Window-creation/Ada/window-creation.adb b/Task/Window-creation/Ada/window-creation.adb new file mode 100644 index 0000000000..485b9a41b3 --- /dev/null +++ b/Task/Window-creation/Ada/window-creation.adb @@ -0,0 +1,41 @@ +with Gtk.Window; use Gtk.Window; +with Gtk.Widget; use Gtk.Widget; + +with Gtk.Handlers; +with Gtk.Main; + +procedure Windowed_Application is + Window : Gtk_Window; + + package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record); + package Return_Handlers is + new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean); + + function Delete_Event (Widget : access Gtk_Widget_Record'Class) + return Boolean is + begin + return False; + end Delete_Event; + + procedure Destroy (Widget : access Gtk_Widget_Record'Class) is + begin + Gtk.Main.Main_Quit; + end Destroy; + +begin + Gtk.Main.Init; + Gtk.Window.Gtk_New (Window); + Return_Handlers.Connect + ( Window, + "delete_event", + Return_Handlers.To_Marshaller (Delete_Event'Access) + ); + Handlers.Connect + ( Window, + "destroy", + Handlers.To_Marshaller (Destroy'Access) + ); + Show (Window); + + Gtk.Main.Main; +end Windowed_Application; diff --git a/Task/Window-creation/AutoIt/window-creation.au3 b/Task/Window-creation/AutoIt/window-creation.au3 new file mode 100644 index 0000000000..31354b386f --- /dev/null +++ b/Task/Window-creation/AutoIt/window-creation.au3 @@ -0,0 +1,9 @@ +GUICreate("Test") +GUISetState(@SW_SHOW) + +Do + Switch GUIGetMsg() + Case -3 ; $GUI_EVENT_CLOSE + Exit + EndSwitch +Until False diff --git a/Task/Window-creation/Batch-File/window-creation-1.bat b/Task/Window-creation/Batch-File/window-creation-1.bat new file mode 100644 index 0000000000..b49579d833 --- /dev/null +++ b/Task/Window-creation/Batch-File/window-creation-1.bat @@ -0,0 +1 @@ +mshta javascript:void(0) diff --git a/Task/Window-creation/Batch-File/window-creation-2.bat b/Task/Window-creation/Batch-File/window-creation-2.bat new file mode 100644 index 0000000000..bedc407c8f --- /dev/null +++ b/Task/Window-creation/Batch-File/window-creation-2.bat @@ -0,0 +1 @@ +mshta vbscript:Execute("") diff --git a/Task/Window-creation/Emacs-Lisp/window-creation.el b/Task/Window-creation/Emacs-Lisp/window-creation.el new file mode 100644 index 0000000000..bfed15ab6d --- /dev/null +++ b/Task/Window-creation/Emacs-Lisp/window-creation.el @@ -0,0 +1 @@ +(make-frame) diff --git a/Task/Window-creation/Euphoria/window-creation-1.eu b/Task/Window-creation/Euphoria/window-creation-1.eu new file mode 100644 index 0000000000..e169fcdeff --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-1.eu @@ -0,0 +1,5 @@ +include arwen.ew + +constant win = create(Window, "ARWEN window", 0, 0,100,100,640,480,{0,0}) + +WinMain(win, SW_NORMAL) diff --git a/Task/Window-creation/Euphoria/window-creation-2.eu b/Task/Window-creation/Euphoria/window-creation-2.eu new file mode 100644 index 0000000000..c050b21227 --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-2.eu @@ -0,0 +1,6 @@ +include GtkEngine.e + +constant win = create(GtkWindow,"title=EuGTK Window;size=640x480;border=10;$destroy=Quit") + +show_all(win) +main() diff --git a/Task/Window-creation/Euphoria/window-creation-3.eu b/Task/Window-creation/Euphoria/window-creation-3.eu new file mode 100644 index 0000000000..20de3dab1a --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-3.eu @@ -0,0 +1,10 @@ +include EuWinGUI.ew + +Window("EuWinGUI window",100,100,640,480) + +-- Event loop +while True do + WaitEvent() +end while + +CloseApp(0) diff --git a/Task/Window-creation/Euphoria/window-creation-4.eu b/Task/Window-creation/Euphoria/window-creation-4.eu new file mode 100644 index 0000000000..1a956e1cb9 --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-4.eu @@ -0,0 +1,5 @@ +include Win32Lib.ew + +constant win = createEx( Window, "Win32Lib", 0, Default, Default, 640, 480, 0, 0 ) + +WinMain( win, Normal ) diff --git a/Task/Window-creation/Euphoria/window-creation-5.eu b/Task/Window-creation/Euphoria/window-creation-5.eu new file mode 100644 index 0000000000..4b34d874b3 --- /dev/null +++ b/Task/Window-creation/Euphoria/window-creation-5.eu @@ -0,0 +1,5 @@ +include wxeu/wxeud.e + +constant win = create( wxFrame, {0, -1, "wxEuphoria window", -1, -1, 640, 480} ) + +wxMain( win ) diff --git a/Task/Window-creation/Microsoft-Small-Basic/window-creation.basic b/Task/Window-creation/Microsoft-Small-Basic/window-creation.basic new file mode 100644 index 0000000000..85f304aa67 --- /dev/null +++ b/Task/Window-creation/Microsoft-Small-Basic/window-creation.basic @@ -0,0 +1 @@ +GraphicsWindow.Show() diff --git a/Task/Window-creation/PowerShell/window-creation-1.ps1 b/Task/Window-creation/PowerShell/window-creation-1.ps1 new file mode 100644 index 0000000000..1a9a3340fe --- /dev/null +++ b/Task/Window-creation/PowerShell/window-creation-1.ps1 @@ -0,0 +1 @@ +New-Window -Show diff --git a/Task/Window-creation/PowerShell/window-creation-2.ps1 b/Task/Window-creation/PowerShell/window-creation-2.ps1 new file mode 100644 index 0000000000..e3d999deb5 --- /dev/null +++ b/Task/Window-creation/PowerShell/window-creation-2.ps1 @@ -0,0 +1,4 @@ +$form = New-Object Windows.Forms.Form +$form.Text = "A Window" +$form.Size = New-Object Drawing.Size(150,150) +$form.ShowDialog() | Out-Null diff --git a/Task/Window-creation/Rebol/window-creation.rebol b/Task/Window-creation/Rebol/window-creation.rebol new file mode 100644 index 0000000000..242c1c09d8 --- /dev/null +++ b/Task/Window-creation/Rebol/window-creation.rebol @@ -0,0 +1 @@ +view layout [size 100x100] diff --git a/Task/Window-creation/Rye/window-creation.rye b/Task/Window-creation/Rye/window-creation.rye new file mode 100644 index 0000000000..54ec8d510c --- /dev/null +++ b/Task/Window-creation/Rye/window-creation.rye @@ -0,0 +1,6 @@ +fyne: import\go "fyne" +app: import\go "fyne/app" +widget: import\go "fyne/widget" +a: app/new +w: a .window "hello" +w .show-and-run diff --git a/Task/Wireworld/Ada/wireworld.adb b/Task/Wireworld/Ada/wireworld.adb new file mode 100644 index 0000000000..d01fb1c126 --- /dev/null +++ b/Task/Wireworld/Ada/wireworld.adb @@ -0,0 +1,66 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Test_Wireworld is + type Cell is (' ', 'H', 't', '.'); + type Board is array (Positive range <>, Positive range <>) of Cell; + -- Perform one transition of the cellular automation + procedure Wireworld (State : in out Board) is + function "abs" (Left : Cell) return Natural is + begin + if Left = 'H' then + return 1; + else + return 0; + end if; + end "abs"; + Above : array (State'Range (2)) of Cell := (others => ' '); + Left : Cell := ' '; + Current : Cell; + begin + for I in State'First (1) + 1..State'Last (1) - 1 loop + for J in State'First (2) + 1..State'Last (2) - 1 loop + Current := State (I, J); + case Current is + when ' ' => + null; + when 'H' => + State (I, J) := 't'; + when 't' => + State (I, J) := '.'; + when '.' => + if abs Above ( J - 1) + abs Above ( J) + abs Above ( J + 1) + + abs Left + abs State (I, J + 1) + + abs State (I + 1, J - 1) + abs State (I + 1, J) + abs State (I + 1, J + 1) + in 1..2 then + State (I, J) := 'H'; + else + State (I, J) := '.'; + end if; + end case; + Above (J - 1) := Left; + Left := Current; + end loop; + end loop; + end Wireworld; + -- Print state of the automation + procedure Put (State : Board) is + begin + for I in State'First (1) + 1..State'Last (1) - 1 loop + for J in State'First (2) + 1..State'Last (2) - 1 loop + case State (I, J) is + when ' ' => Put (' '); + when 'H' => Put ('H'); + when 't' => Put ('t'); + when '.' => Put ('.'); + end case; + end loop; + New_Line; + end loop; + end Put; + Oscillator : Board := (" ", " tH ", " . .... ", " .. ", " "); +begin + for Step in 0..9 loop + Put_Line ("Step" & Integer'Image (Step) & " ---------"); Put (Oscillator); + Wireworld (Oscillator); + end loop; +end Test_Wireworld; diff --git a/Task/Wireworld/AutoIt/wireworld.au3 b/Task/Wireworld/AutoIt/wireworld.au3 new file mode 100644 index 0000000000..161ddf7a22 --- /dev/null +++ b/Task/Wireworld/AutoIt/wireworld.au3 @@ -0,0 +1,102 @@ +$ww = "" +$ww &= "tH........." & @CR +$ww &= ". . " & @CR +$ww &= " ... " & @CR +$ww &= ". . " & @CR +$ww &= "Ht.. ......" +$rows = StringSplit($ww, @CR) +$cols = StringSplit($rows[1], "") +Global $Wireworldarray[$rows[0]][$cols[0]] +For $I = 1 To $rows[0] + $cols = StringSplit($rows[$I], "") + For $k = 1 To $cols[0] + $Wireworldarray[$I - 1][$k - 1] = $cols[$k] + Next +Next +Wireworld($Wireworldarray) +Func Wireworld($array) + Local $labelarray = $array + Local $Top = 0, $Left = 0 + $hFui = GUICreate("Wireworld", UBound($array, 2) * 25, UBound($array) * 25) + For $I = 0 To UBound($array) - 1 + For $k = 0 To UBound($array, 2) - 1 + Switch $array[$I][$k] + Case "t" ; Tail + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000) + Case "h" ; Head + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF) + Case "." ; Conductor + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00) + Case " " ; Empty + $labelarray[$I][$k] = GUICtrlCreateButton("", $Left, $Top, 25, 25) + GUICtrlSetBkColor($labelarray[$I][$k], 0x000000) + EndSwitch + $Left += 25 + Next + $Left = 0 + $Top += 25 + Next + GUISetState() + Local $nextsteparray = $array + While 1 + $msg = GUIGetMsg() + $array = $nextsteparray + Sleep(250) + For $I = 0 To UBound($array) - 1 + For $k = 0 To UBound($array, 2) - 1 + If $array[$I][$k] = " " Then ContinueLoop + If $array[$I][$k] = "h" Then $nextsteparray[$I][$k] = "t" + If $array[$I][$k] = "t" Then $nextsteparray[$I][$k] = "." + If $array[$I][$k] = "." Then + $counter = 0 + If $I - 1 >= 0 Then ; Top + If $array[$I - 1][$k] = "h" Then $counter += 1 + EndIf + If $k - 1 >= 0 Then ; left + If $array[$I][$k - 1] = "h" Then $counter += 1 + EndIf + If $I + 1 <= UBound($array) - 1 Then ; Bottom + If $array[$I + 1][$k] = "h" Then $counter += 1 + EndIf + If $k + 1 <= UBound($array, 2) - 1 Then ;Right + If $array[$I][$k + 1] = "h" Then $counter += 1 + EndIf + If $I - 1 >= 0 And $k - 1 >= 0 Then ; left Top + If $array[$I - 1][$k - 1] = "h" Then $counter += 1 + EndIf + If $I + 1 <= UBound($array) - 1 And $k + 1 <= UBound($array, 2) - 1 Then ; Right Bottom + If $array[$I + 1][$k + 1] = "h" Then $counter += 1 + EndIf + If $I + 1 <= UBound($array) - 1 And $k - 1 >= 0 Then ;Left Bottom + If $array[$I + 1][$k - 1] = "h" Then $counter += 1 + EndIf + If $I - 1 >= 0 And $k + 1 <= UBound($array, 2) - 1 Then ; Top Right + If $array[$I - 1][$k + 1] = "h" Then $counter += 1 + EndIf + If $counter = 1 Or $counter = 2 Then $nextsteparray[$I][$k] = "h" + EndIf + Next + Next + For $I = 0 To UBound($nextsteparray) - 1 + For $k = 0 To UBound($nextsteparray, 2) - 1 + Switch $nextsteparray[$I][$k] + Case "t" ; Tail + GUICtrlSetBkColor($labelarray[$I][$k], 0xFF0000) + Case "h" ; Head + GUICtrlSetBkColor($labelarray[$I][$k], 0x0000FF) + Case "." ; Conductor + GUICtrlSetBkColor($labelarray[$I][$k], 0xFFFF00) + Case " " ; Empty + GUICtrlSetBkColor($labelarray[$I][$k], 0x000000) + EndSwitch + $Left += 25 + Next + $Left = 0 + $Top += 25 + Next + If $msg = -3 Then Exit + WEnd +EndFunc ;==>Wireworld diff --git a/Task/Wireworld/Pluto/wireworld.pluto b/Task/Wireworld/Pluto/wireworld.pluto new file mode 100644 index 0000000000..3630e258b1 --- /dev/null +++ b/Task/Wireworld/Pluto/wireworld.pluto @@ -0,0 +1,68 @@ +local fmt = require "fmt" +require "table2" + +local rows, cols = 0, 0 -- extent of input configuration +local rx, cx = 0, 0 -- grid extent (includes border) +local mn = {} -- offsets of Moore neighborhood + +local function gprint(grid) + print(string.rep("__", cols)) + print() + for r = 1, rows do + for c = 1, cols do fmt.write(" %s", grid[r * cx + c + 1]) end + print() + end +end + +local function step(dst, src) + for r = 1, rows do + for c = 1, cols do + local x = r * cx + c + 1 + dst[x] = src[x] + if dst[x] == "H" then + dst[x] = "t" + elseif dst[x] == "t" then + dst[x] = "." + elseif dst[x] == "." then + local nn = 0 + for mn as n do + if src[x + n] == "H" then nn += 1 end + end + if nn == 1 or nn == 2 then dst[x] = "H" end + end + end + end +end + +local nl = os.platform == "windows" ? "\r\n" : "\n" +local src_rows = io.contents("ww.config"):rstrip():split(nl) +rows = #src_rows +for src_rows as r do + if #r > cols then cols = #r end +end +rx = rows + 2 +cx = cols + 2 +mn = {-cx - 1, -cx, -cx + 1, -1, 1, cx - 1, cx, cx + 1} + +-- Allocate two grids and copy input into first grid. +local odd = table.rep(rx * cx, " ") +local even = table.rep(rx * cx, " ") + +local ri = 0 +for src_rows as r do + for i = 0, #r - 1 do + odd[(ri + 1) * cx + 2 + i] = r[i + 1] + end + ri += 1 +end + +-- Run. +while true do + gprint(odd) + step(even, odd) + io.read() -- wait for enter to be pressed + + gprint(even) + step(odd, even) + io.read() -- ditto +end diff --git a/Task/Wireworld/Uiua/wireworld.uiua b/Task/Wireworld/Uiua/wireworld.uiua new file mode 100644 index 0000000000..e6aaa67498 --- /dev/null +++ b/Task/Wireworld/Uiua/wireworld.uiua @@ -0,0 +1,6 @@ +"tH.........\n. .\n ...\n. .\nHt.. ......" +CanBeHead ← ⍥₂(⍉↘¯1↘1)⬚@\s⧈(↥⊃=₁=₂/+=@H⍜⊡₄⋅@./⊂)3_3 +Successor ← ⍣(@\s◌ °@\s|@t◌ °@H|@.◌ °@t|@H °1◌|@.) +Step ← ≡₋₂Successor⟜CanBeHead +⍥⊸Step20 ⬚@\s⊜∘⊸≠@\n +▽10≡▽₂20≡₋₃(⍣(0_0_0 °@\s|1_0_0 °@H|0.9_0.7_0 °@t|÷3 1_1_1)) diff --git a/Task/Word-frequency/Ada/word-frequency.adb b/Task/Word-frequency/Ada/word-frequency.adb new file mode 100644 index 0000000000..26e178a98a --- /dev/null +++ b/Task/Word-frequency/Ada/word-frequency.adb @@ -0,0 +1,87 @@ +with Ada.Command_Line; +with Ada.Text_IO; +with Ada.Integer_Text_IO; +with Ada.Strings.Maps; +with Ada.Strings.Fixed; +with Ada.Characters.Handling; +with Ada.Containers.Indefinite_Ordered_Maps; +with Ada.Containers.Indefinite_Ordered_Sets; +with Ada.Containers.Ordered_Maps; + +procedure Word_Frequency is + package TIO renames Ada.Text_IO; + + package String_Counters is new Ada.Containers.Indefinite_Ordered_Maps(String, Natural); + package String_Sets is new Ada.Containers.Indefinite_Ordered_Sets(String); + package Sorted_Counters is new Ada.Containers.Ordered_Maps + (Natural, + String_Sets.Set, + "=" => String_Sets."=", + "<" => ">"); + -- for sorting by decreasing number of occurrences and ascending lexical order + + procedure Increment(Key : in String; Element : in out Natural) is + begin + Element := Element + 1; + end Increment; + + path : constant String := Ada.Command_Line.Argument(1); + how_many : Natural := 10; + set : constant Ada.Strings.Maps.Character_Set := Ada.Strings.Maps.To_Set(ranges => (('a', 'z'), ('0', '9'))); + F : TIO.File_Type; + first : Positive; + last : Natural; + from : Positive; + counter : String_Counters.Map; + sorted_counts : Sorted_Counters.Map; + C1 : String_Counters.Cursor; + C2 : Sorted_Counters.Cursor; + tmp_set : String_Sets.Set; +begin + -- read file and count words + TIO.Open(F, name => path, mode => TIO.In_File); + while not TIO.End_Of_File(F) loop + declare + line : constant String := Ada.Characters.Handling.To_Lower(TIO.Get_Line(F)); + begin + from := line'First; + loop + Ada.Strings.Fixed.Find_Token(line(from .. line'Last), set, Ada.Strings.Inside, first, last); + exit when last < First; + C1 := counter.Find(line(first .. last)); + if String_Counters.Has_Element(C1) then + counter.Update_Element(C1, Increment'Access); + else + counter.Insert(line(first .. last), 1); + end if; + from := last + 1; + end loop; + end; + end loop; + TIO.Close(F); + + -- fill Natural -> StringSet Map + C1 := counter.First; + while String_Counters.Has_Element(C1) loop + if sorted_counts.Contains(String_Counters.Element(C1)) then + tmp_set := sorted_counts.Element(String_Counters.Element(C1)); + tmp_set.Include(String_Counters.Key(C1)); + else + sorted_counts.Include(String_Counters.Element(C1), String_Sets.To_Set(String_Counters.Key(C1))); + end if; + String_Counters.Next(C1); + end loop; + + -- output + C2 := sorted_counts.First; + while Sorted_Counters.Has_Element(C2) loop + for Item of Sorted_Counters.Element(C2) loop + Ada.Integer_Text_IO.Put(TIO.Standard_Output, Sorted_Counters.Key(C2), width => 9); + TIO.Put(TIO.Standard_Output, " "); + TIO.Put_Line(Item); + end loop; + Sorted_Counters.Next(C2); + how_many := how_many - 1; + exit when how_many = 0; + end loop; +end Word_Frequency; diff --git a/Task/Word-frequency/AppleScript/word-frequency-2.applescript b/Task/Word-frequency/AppleScript/word-frequency-2.applescript index c582a62e50..de203a6c70 100644 --- a/Task/Word-frequency/AppleScript/word-frequency-2.applescript +++ b/Task/Word-frequency/AppleScript/word-frequency-2.applescript @@ -1,11 +1,11 @@ "The 10 most frequently occurring words in the file are: -The: 41092 -Of: 19954 -And: 14943 -A: 14545 -To: 13953 -In: 11219 -He: 9649 -Was: 8622 -That: 7924 -It: 6661" +The: 41092 +Of: 19954 +And: 14943 +A: 14545 +To: 13953 +In: 11219 +He: 9649 +Was: 8622 +That: 7924 +It: 6661" diff --git a/Task/Word-frequency/AutoHotkey/word-frequency.ahk b/Task/Word-frequency/AutoHotkey/word-frequency.ahk index 45db355ab6..9ddc424b5d 100644 --- a/Task/Word-frequency/AutoHotkey/word-frequency.ahk +++ b/Task/Word-frequency/AutoHotkey/word-frequency.ahk @@ -3,15 +3,15 @@ FileRead, H, % A_temp "\tempfile.txt" FileDelete, % A_temp "\tempfile.txt" words := [] while pos := RegExMatch(H, "\b[[:alpha:]]+\b", m, A_Index=1?1:pos+StrLen(m)) - words[m] := words[m] ? words[m] + 1 : 1 + words[m] := words[m] ? words[m] + 1 : 1 for word, count in words - list .= count "`t" word "`r`n" + list .= count "`t" word "`r`n" Sort, list, RN loop, parse, list, `n, `r { - result .= A_LoopField "`r`n" - if A_Index = 10 - break + result .= A_LoopField "`r`n" + if A_Index = 10 + break } MsgBox % "Freq`tWord`n" result return diff --git a/Task/Word-frequency/Batch-File/word-frequency.bat b/Task/Word-frequency/Batch-File/word-frequency.bat index bfdc70a525..6350d907a2 100644 --- a/Task/Word-frequency/Batch-File/word-frequency.bat +++ b/Task/Word-frequency/Batch-File/word-frequency.bat @@ -11,35 +11,34 @@ setlocal enabledelayedexpansion set word=100000 set line=0 for /f "delims=" %%i in (input.txt) do ( - set /a line+=1 - for %%j in (%%i) do ( - if not !skip%%j!==true ( - echo line !line! ^| word !word:~-5! - "%%~j" - - type input.txt | find /i /c "%%~j" > count.tmp - set /p tmpvar= count.tmp + set /p tmpvar= FUNCTION STORED-CHAR-LENGTH(Input-Record) + + + UNSTRING Input-Record DELIMITED BY SPACE INTO Word1 + WITH POINTER Pos TALLYING IN Cnt + MOVE FUNCTION TRIM(FUNCTION LOWER-CASE(Word1)) TO Word-Record + + IF Word-Record NOT EQUAL SPACES AND Word-Record IS ALPHABETIC + THEN WRITE Word-Record + END-IF + + END-PERFORM. + + Collect-Totals. + MOVE 'F' to Eof + OPEN INPUT Word-File + OPEN OUTPUT Output-File + READ Word-File + MOVE Input-Word TO Current-Word + MOVE 1 to Current-Word-Cnt + PERFORM UNTIL Eof = 'T' + READ Word-File + AT END MOVE 'T' TO Eof + END-READ + + IF FUNCTION TRIM(Word-Record) + EQUAL + FUNCTION TRIM(Current-Word) + THEN + ADD 1 to Current-Word-Cnt + ELSE + MOVE Current-Word TO Output-Rec-Word + MOVE Current-Word-Cnt TO Output-Rec-Word-Cnt + WRITE Output-Rec + MOVE 1 to Current-Word-Cnt + MOVE Word-Record TO Current-Word + MOVE SPACES TO Input-Record + END-IF + + END-PERFORM. + CLOSE Word-File Output-File. + END-PROGRAM. diff --git a/Task/Word-frequency/Emacs-Lisp/word-frequency.el b/Task/Word-frequency/Emacs-Lisp/word-frequency.el new file mode 100644 index 0000000000..3d6cb2a16e --- /dev/null +++ b/Task/Word-frequency/Emacs-Lisp/word-frequency.el @@ -0,0 +1,28 @@ +(defun prepare-text (str) + "Prepare STR for word frequency work." + (sort (split-string (downcase str) "[\s\f\t\n\r\v[:punct:]]+" :OMIT-NULLS) #'string<)) + +(defun get-unique-words (str) + "Get a list of lowercase unique words in STR." + (seq-uniq (prepare-text str))) + +(defun count-word-frequency (buffer-name number-requested) + "List top NUMBER-REQUESTED word frequencies in BUFFER-NAME." + (let* ((str) + (unique-words) + (words-and-count (make-hash-table :test 'equal)) + (count-of-duplicates) + (matches)) + (with-current-buffer buffer-name + (setq str (buffer-string)) + (setq unique-words (get-unique-words str)) + (dolist (one-unique-word unique-words) + (setq count-of-duplicates (count-matches (format "\\b%s\\b" one-unique-word) (point-min) (point-max))) + (puthash one-unique-word count-of-duplicates words-and-count))) + (maphash (lambda (key value) + (push (cons key value) matches)) + words-and-count) + (setq matches (sort matches (lambda (a b) (> (cdr a) (cdr b))))) + (setq matches (seq-take matches number-requested)) + (dolist (match matches) + (insert (format "\n%s %s" (car match) (cdr match)))))) diff --git a/Task/Word-frequency/FreeBASIC/word-frequency.basic b/Task/Word-frequency/FreeBASIC/word-frequency.basic index b32ac726fb..76772db244 100644 --- a/Task/Word-frequency/FreeBASIC/word-frequency.basic +++ b/Task/Word-frequency/FreeBASIC/word-frequency.basic @@ -30,7 +30,7 @@ Sub tallysort(array() As tally,begin As Long,Finish As long) Function loadfile(file As String) As String - If Fileexists(file)=0 Then Print file;" not found":Sleep:End + If Fileexists(file)=0 Then Print file;" not found":Sleep:End Dim As Long f=Freefile Open file For Binary Access Read As #f Dim As String text diff --git a/Task/Word-frequency/Icon/word-frequency.icon b/Task/Word-frequency/Icon/word-frequency.icon new file mode 100644 index 0000000000..65ad14faeb --- /dev/null +++ b/Task/Word-frequency/Icon/word-frequency.icon @@ -0,0 +1,8 @@ +procedure main(A) + WC := &letters++&digits + n := \A[1] | 10 + wt := table(0) + write("The ",n," most common words are:") + every !&input ? while tab(upto(WC)) do wt[map(tab(many(WC)))] +:= 1 + every p := !reverse(sort(wt,2))\n do write(right(p[2],8),": ",p[1]) +end diff --git a/Task/Word-frequency/KAP/word-frequency.kap b/Task/Word-frequency/KAP/word-frequency.kap index e6ae9967bb..8d795e3c63 100644 --- a/Task/Word-frequency/KAP/word-frequency.kap +++ b/Task/Word-frequency/KAP/word-frequency.kap @@ -1,7 +1,7 @@ ∇ stats (file) { - content ← "[\\h,.\"'\n-]+" regex:split unicode:toLower io:readFile file - sorted ← (⍋⊇⊢) content - selection ← 1,2≢/sorted - words ← selection / sorted - {⍵[10↑⍒⍵[;1];]} words ,[0.5] ≢¨ sorted ⊂⍨ +\selection + content ← "[\\h,.\"'\n-]+" regex:split unicode:toLower io:readFile file + sorted ← (⍋⊇⊢) content + selection ← 1,2≢/sorted + words ← selection / sorted + {⍵[10↑⍒⍵[;1];]} words ,[0.5] ≢¨ sorted ⊂⍨ +\selection } diff --git a/Task/Word-frequency/Lua/word-frequency.lua b/Task/Word-frequency/Lua/word-frequency.lua index 533d6bedb2..83e648322e 100644 --- a/Task/Word-frequency/Lua/word-frequency.lua +++ b/Task/Word-frequency/Lua/word-frequency.lua @@ -5,24 +5,24 @@ -- in freq, each key is a word and each value is its count local freq = {} for line in io.lines(arg[1]) do - -- %a stands for any letter - for word in string.gmatch(string.lower(line), "%a+") do - if not freq[word] then - freq[word] = 1 - else - freq[word] = freq[word] + 1 - end - end + -- %a stands for any letter + for word in string.gmatch(string.lower(line), "%a+") do + if not freq[word] then + freq[word] = 1 + else + freq[word] = freq[word] + 1 + end + end end -- in array, each entry is an array whose first value is the count and whose -- second value is the word local array = {} for word, count in pairs(freq) do - table.insert(array, {count, word}) + table.insert(array, {count, word}) end table.sort(array, function (a, b) return a[1] > b[1] end) for i = 1, arg[2] or 10 do - io.write(string.format('%7d %s\n', array[i][1] , array[i][2])) + io.write(string.format('%7d %s\n', array[i][1] , array[i][2])) end diff --git a/Task/Word-frequency/R/word-frequency-2.r b/Task/Word-frequency/R/word-frequency-2.r index a8363ac6cf..4bb606d6a3 100644 --- a/Task/Word-frequency/R/word-frequency-2.r +++ b/Task/Word-frequency/R/word-frequency-2.r @@ -1,5 +1,5 @@ word_frequency_pipeline <- function(file=NULL, n=10) { - + file |> vroom::vroom_lines() |> stringi::stri_split_boundaries(type="word", skip_word_none=T, skip_word_number=T) |> @@ -9,5 +9,5 @@ word_frequency_pipeline <- function(file=NULL, n=10) { sort(decreasing = T) |> (\(.) .[1:n])() |> data.frame() - + } diff --git a/Task/Word-frequency/REXX/word-frequency-2.rexx b/Task/Word-frequency/REXX/word-frequency-2.rexx index 8b64988fa2..4d1bbad7ee 100644 --- a/Task/Word-frequency/REXX/word-frequency-2.rexx +++ b/Task/Word-frequency/REXX/word-frequency-2.rexx @@ -1,4 +1,4 @@ --- 9 Nov 2025 +-- 10 Mar 2026 include Setting arg file top if file='' | file='.' then @@ -9,10 +9,10 @@ if top='' then say 'WORD FREQUENCY' say version say -call CountWords(file) +call CountWords file call SaveCount -call ShowCount(top) -call ShowWord(top) +call ShowCount top +call ShowWord top call Timer exit @@ -36,7 +36,7 @@ do while Lines(file) Dict.w+=1 end i end -List.Dict.0=n; List.Count.0=n +List.0=n say n 'different words found' say return @@ -44,7 +44,7 @@ return SaveCount: procedure expose Dict. List. -- Move counts to list -do i=1 to List.Dict.0 +do i=1 to List.0 w=List.Dict.i; List.Count.i=Dict.w end return @@ -52,34 +52,34 @@ return ShowCount: procedure expose List. arg top -call Sort 'List.Count.','List.Dict.' +call SortSt 'List.Count.','List.Dict.' say 'Frequency by count' say 'word rank count' say '---------------------------' n=0 -do i=List.Dict.0 by -1 to 1 +do i=List.0 by -1 to 1 n+=1 if n<=top then say Left(List.Dict.i,15) Right(n,5) Right(List.Count.i,5) List.Rank.i=n end +say '...' say return ShowWord: procedure expose List. arg top -call Sort 'List.Dict.','List.Rank. List.Count.' +call SortSt 'List.Dict.','List.Rank. List.Count.' say 'Frequency by word' say 'word rank count' say '---------------------------' do i=1 to top say Left(List.Dict.i,15) Right(List.Rank.i,5) Right(List.Count.i,5) end +say '...' say return --- Timer -include Timer --- Sort -include Utility +-- SortSt; Timer +include Math diff --git a/Task/Word-frequency/Raku/word-frequency.raku b/Task/Word-frequency/Raku/word-frequency.raku index 82faa4afed..4077ef2f75 100644 --- a/Task/Word-frequency/Raku/word-frequency.raku +++ b/Task/Word-frequency/Raku/word-frequency.raku @@ -8,8 +8,8 @@ sub MAIN ($filename, UInt $top = 10) { ; for @matcher -> $reg { say "\nTop $top using regex: ", $reg.raku; - my @words = $file.comb($reg).Bag.sort(-*.value)[^$top]; - my $length = max @words».key».chars; + my @words = $file.comb($reg).Bag.sort(-*.value)[^$top]; + my $length = max @words».key».chars; printf "%-{$length}s %d\n", .key, .value for @words; } } diff --git a/Task/Word-frequency/Rebol/word-frequency.rebol b/Task/Word-frequency/Rebol/word-frequency.rebol new file mode 100644 index 0000000000..7cf6d0e451 --- /dev/null +++ b/Task/Word-frequency/Rebol/word-frequency.rebol @@ -0,0 +1,36 @@ +Rebol [ + title: "Rosetta code: Word frequency" + file: %Word_frequency.r3 + url: https://rosettacode.org/wiki/Word_frequency +] + +word-frequency: function/with [ + text [string! file! url!] +][ + dict: make map! 1000 + unless string? text [text: read/string text] + parse text [ + any [ + copy word: some word-chars ( + word: lowercase word ;; normalize + dict/:word: either n: dict/:word [n + 1][1] + ) + | some skip-chars + ] + ] + data: sort/reverse/skip/compare to block! dict 2 2 + new-line/skip data true 2 +][ + word-chars: system/catalog/bitsets/alpha + skip-chars: complement word-chars +] + +;; Example: +unless exists? %135-0.txt [ + print "Downloading the test file: 135-0.txt" + ;; Update timeout in case of slow connection. + system/schemes/https/spec/timeout: 60 + write %135-0.txt read https://www.gutenberg.org/files/135/135-0.txt +] + +probe copy/part word-frequency %135-0.txt 20 diff --git a/Task/Word-frequency/Red/word-frequency.red b/Task/Word-frequency/Red/word-frequency.red new file mode 100644 index 0000000000..68b59559f1 --- /dev/null +++ b/Task/Word-frequency/Red/word-frequency.red @@ -0,0 +1,14 @@ +Red [ "Word frequency - hinjolicious" ] + +word-freq: function [file n][ + word-chars: charset "abcdefghijklmnopqrstuvwxyz" + words: parse lowercase read file [collect [any [keep [some word-chars] | skip]]] + freq: make map! [] + foreach w words [freq/:w: either none? freq/:w [1][freq/:w + 1]] + sorted: sort/reverse collect [foreach [w c] freq [keep/only reduce [c w]]] +] + +sorted: word-freq %135-0.txt 10 + +print "Top 10 word frequency:" +repeat i 10 [w: sorted/:i print [pad w/2 10 w/1]] diff --git a/Task/Word-frequency/Smalltalk/word-frequency-1.st b/Task/Word-frequency/Smalltalk/word-frequency-1.st index 6d91dd04ce..f420e02c56 100644 --- a/Task/Word-frequency/Smalltalk/word-frequency-1.st +++ b/Task/Word-frequency/Smalltalk/word-frequency-1.st @@ -1,2 +1,2 @@ (StandardFileStream new open: 'lesms10.txt' forWrite: false) - contents asLowercase substrings asBag sortedCounts first: 10. + contents asLowercase substrings asBag sortedCounts first: 10. diff --git a/Task/Word-frequency/Smalltalk/word-frequency-2.st b/Task/Word-frequency/Smalltalk/word-frequency-2.st index 3097e245fa..1ccabe1e3f 100644 --- a/Task/Word-frequency/Smalltalk/word-frequency-2.st +++ b/Task/Word-frequency/Smalltalk/word-frequency-2.st @@ -1,2 +1,2 @@ (StandardFileStream readOnlyFileNamed: 'lesms10.txt') - contents asLowercase substrings asBag sortedCounts first: 10. + contents asLowercase substrings asBag sortedCounts first: 10. diff --git a/Task/Word-frequency/Uiua/word-frequency.uiua b/Task/Word-frequency/Uiua/word-frequency.uiua new file mode 100644 index 0000000000..e4505a857e --- /dev/null +++ b/Task/Word-frequency/Uiua/word-frequency.uiua @@ -0,0 +1,3 @@ +&fras"RosettaCode/les-miserables.txt" +⊜□⊸(↧⊃(≥@a|≤@z))+×32↧⊸⊃(≥@A|≤@Z) # Lowercase, split on non-letter. +↙10⊏⍖⊸≡⊣⊕[⊃⊢⧻]⊸⊸⊛ # Group, count, sort, take 10. diff --git a/Task/Word-frequency/V-(Vlang)/word-frequency.v b/Task/Word-frequency/V-(Vlang)/word-frequency.v index 4a06ce5116..2b02cd731f 100644 --- a/Task/Word-frequency/V-(Vlang)/word-frequency.v +++ b/Task/Word-frequency/V-(Vlang)/word-frequency.v @@ -2,24 +2,24 @@ import os import maps fn main() { - mis := os.read_file("./135-0.txt") or {panic("Error reading file")} - mut grp, mut rgrp := map[string]int, map[int]string - mut keys := []int{} - mut result := "" - mut count := 1 - for line in mis.split_into_lines() { - for word in line.split("\x20") { - if !word.is_blank() {grp[word.to_lower()]++} - } - } - rgrp = maps.invert(grp) - keys = rgrp.keys() - keys.sort(a > b) - for key in keys { - result += "${count++:2} " + "${rgrp[key]} " + "${key}" + "\n" - if count > 10 {break} - } - println("Rank Word Frequency") - println("==== ==== =========") - println(result) + mis := os.read_file("./135-0.txt") or {panic("Error reading file")} + mut grp, mut rgrp := map[string]int, map[int]string + mut keys := []int{} + mut result := "" + mut count := 1 + for line in mis.split_into_lines() { + for word in line.split("\x20") { + if !word.is_blank() {grp[word.to_lower()]++} + } + } + rgrp = maps.invert(grp) + keys = rgrp.keys() + keys.sort(a > b) + for key in keys { + result += "${count++:2} " + "${rgrp[key]} " + "${key}" + "\n" + if count > 10 {break} + } + println("Rank Word Frequency") + println("==== ==== =========") + println(result) } diff --git a/Task/Word-frequency/Zkl/word-frequency.zkl b/Task/Word-frequency/Zkl/word-frequency.zkl index 7923fea37a..b069630aae 100644 --- a/Task/Word-frequency/Zkl/word-frequency.zkl +++ b/Task/Word-frequency/Zkl/word-frequency.zkl @@ -1,4 +1,4 @@ -fname,count := vm.arglist; // grab cammand line args +fname,count := vm.arglist; // grab cammand line args // words may have leading or trailing "_", ie "the" and "_the" File(fname).pump(Void,"toLower", // read the file line by line and hash words diff --git a/Task/Word-ladder/Ada/word-ladder.adb b/Task/Word-ladder/Ada/word-ladder.adb new file mode 100644 index 0000000000..1baca530f6 --- /dev/null +++ b/Task/Word-ladder/Ada/word-ladder.adb @@ -0,0 +1,146 @@ +pragma Ada_2022; +with Ada.Containers.Multiway_Trees; +with Ada.Containers.Vectors; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; +procedure Word_Ladder is + + DICT_FILENAME : constant String := "unixdict.txt"; + MAX_DEPTH : constant Positive := 50; + + subtype LC_Chars is Character range 'a' .. 'z'; + + type Word_Node_T is record + Level : Positive; + Word : Unbounded_String; + end record; + + package Word_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + package Dict_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + + package Word_Trees is new Ada.Containers.Multiway_Trees (Word_Node_T); + use Word_Trees; + Word_Tree : Tree; + Solved : Boolean; + Solution : Cursor; + + function Load_Candidate_Words (Dict_Filename : String; Word_Len : Positive) + return Dict_Vectors.Vector is + Dict_File : File_Type; + Read_Word : Unbounded_String; + Cands : Dict_Vectors.Vector; + Valid : Boolean; + C : Character; + begin + Open (File => Dict_File, Mode => In_File, Name => Dict_Filename); + while not End_Of_File (Dict_File) loop + Read_Word := Get_Line (Dict_File); + if Length (Read_Word) = Word_Len then + Valid := True; + for Ix in 1 .. Word_Len loop + C := Element (Read_Word, Ix); + Valid := C in LC_Chars; + exit when not Valid; + end loop; + if Valid then Cands.Append (Read_Word); end if; + end if; + end loop; + Close (Dict_File); + return Cands; + end Load_Candidate_Words; + + function Mutate (Word : Unbounded_String; Dict : in out Dict_Vectors.Vector) + return Word_Vectors.Vector is + Mutations : Word_Vectors.Vector; + Poss_Word : Unbounded_String; + begin + for Ix in 1 .. Length (Word) loop + for Letter in LC_Chars loop + if Letter /= Element (Word, Ix) then + Poss_Word := Word; + Replace_Element (Poss_Word, Ix, Letter); + if Dict.Contains (Poss_Word) then + Mutations.Append (Poss_Word); + Dict.Delete (Dict.Find_Index (Poss_Word)); + end if; + end if; + end loop; + end loop; + return Mutations; + end Mutate; + + procedure Recurse_Tree (Start_Pos : Cursor; + Level : Positive; + Target : Unbounded_String; + Dict : in out Dict_Vectors.Vector) is + Pos : Cursor := Start_Pos; + Mutations : Word_Vectors.Vector; + New_Node : Word_Node_T; + begin + while not Solved and then Pos /= No_Element loop + if Element (Pos).Level = Level then + Mutations := Mutate (Element (Pos).Word, Dict); + if not Word_Vectors.Is_Empty (Mutations) then + for Word of Mutations loop + New_Node.Level := Level + 1; + New_Node.Word := Word; + Append_Child (Word_Tree, Pos, New_Node); + if Word = Target then + Solved := True; + Solution := Pos; + end if; + end loop; + end if; + end if; + if not Solved then + Recurse_Tree (First_Child (Pos), Level, Target, Dict); + end if; + Pos := Next_Sibling (Pos); + end loop; + end Recurse_Tree; + + procedure Ladder (Start_S, Target_S : String) is + Dictionary : Dict_Vectors.Vector; + Level : Positive := 1; + Word_Node : Word_Node_T; + Start, Target : Unbounded_String; + Start_Pos : Cursor; + Output : Unbounded_String; + begin + if Start_S'Length /= Target_S'Length then + Put_Line ("ERROR: Start and Target words must be same length."); + return; + end if; + Dictionary := Load_Candidate_Words (DICT_FILENAME, Start_S'Length); + Start := To_Unbounded_String (Start_S); + Target := To_Unbounded_String (Target_S); + Solved := False; + Word_Node.Level := 1; + Word_Node.Word := Start; + Word_Tree := Empty_Tree; + Word_Tree.Insert_Child (Word_Tree.Root, No_Element, Word_Node); + Start_Pos := Find (Word_Tree, Word_Node); + while Level <= MAX_DEPTH and then not Solved loop + Recurse_Tree (Start_Pos, Level, Target, Dictionary); + Level := @ + 1; + end loop; + if not Solved then + Put_Line (Start & " -> " & Target & " - No solution found at depth" & MAX_DEPTH'Image); + else + while not Is_Root (Solution) loop + Word_Node := Element (Solution); + Output := Word_Node.Word & " -> " & Output; + Solution := Parent (Solution); + end loop; + Put_Line (Output & Target); + end if; + end Ladder; +begin + Ladder ("boy", "man"); + Ladder ("girl", "lady"); + Ladder ("jane", "john"); + Ladder ("child", "adult"); + Ladder ("ada", "god"); + Ladder ("rust", "hell"); +end Word_Ladder; diff --git a/Task/Word-ladder/JavaScript/word-ladder.js b/Task/Word-ladder/JavaScript/word-ladder.js new file mode 100644 index 0000000000..9d4d2a94b7 --- /dev/null +++ b/Task/Word-ladder/JavaScript/word-ladder.js @@ -0,0 +1,73 @@ +// Returns true if strings s1 and s2 differ by one character. +function oneAway(s1, s2) { + if (s1.length !== s2.length) return false; + let diff = 0; + for (let i = 0; i < s1.length; i++) { + if (s1[i] !== s2[i]) { + if (diff) return false; + diff++; + } + } + return diff === 1; +} + +// Join a sequence of strings into a single string using the given separator. +function join(arr, separator) { + return arr.join(separator); +} + +// If possible, print the shortest chain of single-character modifications that +// leads from "from" to "to", with each intermediate step being a valid word. +// This is an application of breadth-first search. +function wordLadder(words, from, to) { + const poss = words.get(from.length); + if (poss) { + const queue = [[from]]; + while (queue.length) { + const curr = queue.shift(); + for (let i = 0; i < poss.length; i++) { + const word = poss[i]; + if (!oneAway(word, curr[curr.length - 1])) continue; + if (word === to) { + console.log(join(curr.concat(to), " -> ")); + return true; + } + queue.push(curr.concat(word)); + poss.splice(i, 1); + i--; + } + } + } + console.log(`${from} into ${to} cannot be done.`); + return false; +} + +// Main logic +async function main() { + const words = new Map(); + // Assuming unixdict.txt is available as a text file + // In a real Node.js environment, you would use fs.readFileSync or similar + // For browser, you would fetch the file + // Here, we simulate loading the dictionary + const dictionary = [ + "boy", "man", "girl", "lady", "john", "jane", "child", "adult", + "cat", "cot", "dot", "dog", "lead", "load", "goad", "gold", + "white", "whale", "black", "blake", "bubble", "bubbly", "rubble", "tickle" + ]; + for (const word of dictionary) { + if (!words.has(word.length)) words.set(word.length, []); + words.get(word.length).push(word); + } + + wordLadder(words, "boy", "man"); + wordLadder(words, "girl", "lady"); + wordLadder(words, "john", "jane"); + wordLadder(words, "child", "adult"); + wordLadder(words, "cat", "dog"); + wordLadder(words, "lead", "gold"); + wordLadder(words, "white", "black"); + wordLadder(words, "bubble", "tickle"); +} + +// Uncomment to run in a Node.js environment +main(); diff --git a/Task/Word-search/Ada/word-search.adb b/Task/Word-search/Ada/word-search.adb new file mode 100644 index 0000000000..712854b9c1 --- /dev/null +++ b/Task/Word-search/Ada/word-search.adb @@ -0,0 +1,259 @@ +pragma Ada_2022; +with Ada.Containers; use Ada.Containers; +with Ada.Containers.Vectors; +with Ada.Numerics.Discrete_Random; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; + +procedure Word_Search is + + MIN_WORDS : constant Positive := 25; + MIN_WORD_LEN : constant Positive := 3; + MAX_WORD_LEN : constant Positive := 9; + SIDE_LEN : constant Positive := 10; + MESSAGE : constant String := "ROSETTACODE"; + DICT_FILENAME : constant String := "unixdict.txt"; + + type Directions is (N, NE, E, SE, S, SW, W, NW); + type Move is record + DX, DY : Integer; + end record; + type Moves_Arr is array (Directions) of Move; + Moves : constant Moves_Arr := [ + N => (0, -1), NE => (1, -1), E => (1, 0), SE => (1, 1), + S => (0, 1), SW => (-1, 1), W => (-1, 0), NW => (-1, -1) + ]; + subtype Grid_Dimension is Positive range 1 .. SIDE_LEN; + type Matrix is array (Grid_Dimension, Grid_Dimension) of Character; + subtype LC_Chars is Character range 'a' .. 'z'; + subtype Valid_Lengths is Positive range MIN_WORD_LEN .. MAX_WORD_LEN; + + package Word_Vectors is new Ada.Containers.Vectors (Positive, Unbounded_String); + type Dictionary is array (Valid_Lengths) of Word_Vectors.Vector; + Dict : Dictionary; + + type Placement is record + Word : Unbounded_String; + Start : Unbounded_String; + end record; + package Placement_Vectors is new Ada.Containers.Vectors (Positive, Placement); + Placings : Placement_Vectors.Vector; + + subtype Ten_K is Positive range 1 .. 10000; + package Rand_Dimension is new Ada.Numerics.Discrete_Random (Grid_Dimension); + package Rand_Dir is new Ada.Numerics.Discrete_Random (Directions); + package Rand_Len is new Ada.Numerics.Discrete_Random (Valid_Lengths); + package Rand_10k is new Ada.Numerics.Discrete_Random (Ten_K); + Dimension_Gen : Rand_Dimension.Generator; + Dir_Gen : Rand_Dir.Generator; + Len_Gen : Rand_Len.Generator; + Ten_K_Gen : Rand_10k.Generator; + + procedure Load_Dictionary (Filename : String) is + Dict_File : File_Type; + Dict_Word : Unbounded_String; + Dict_Word_Len : Positive; + Word_OK : Boolean; + begin + Open (File => Dict_File, Mode => In_File, Name => Filename); + while not End_Of_File (Dict_File) loop + Dict_Word := Get_Line (Dict_File); + Dict_Word_Len := Length (Dict_Word); + if Dict_Word_Len >= MIN_WORD_LEN and then + Dict_Word_Len <= MAX_WORD_LEN + then + Word_OK := True; + for C of To_String (Dict_Word) loop + if C not in LC_Chars then + Word_OK := False; + exit; + end if; + end loop; + if Word_OK then + Dict (Dict_Word_Len).Append (Dict_Word); + end if; + end if; + end loop; + end Load_Dictionary; + + function Pick_Random_Word return Unbounded_String is + Word_Length : Positive := Rand_Len.Random (Len_Gen); + Rand : constant Natural := Rand_10k.Random (Ten_K_Gen); + Word_Ix : Positive; + begin + Word_Length := Rand_Len.Random (Len_Gen); + if Word_Length > 4 then -- Reduce number of words > 4 chars + Word_Length := Rand_Len.Random (Len_Gen); + end if; + Word_Ix := Positive (Rand) mod (Positive (Dict (Word_Length).Length) - 1) + 1; + return Dict (Word_Length) (Word_Ix); + end Pick_Random_Word; + + function Not_Too_Long (X, Y : Grid_Dimension; Len : Positive; Dir : Directions) return Boolean is + begin + case Dir is + when N => return Y - Len > 0; + when S => return Y + Len <= SIDE_LEN; + when E => return X + Len <= SIDE_LEN; + when W => return X - Len > 0; + when NE => return X + Len <= SIDE_LEN and then Y - Len > 0; + when SW => return Y + Len <= SIDE_LEN and then X - Len > 0; + when SE => return Y + Len <= SIDE_LEN and then X + Len <= SIDE_LEN; + when NW => return Y - Len > 0 and then X - Len > 0; + end case; + end Not_Too_Long; + + function Is_Empty (G : Matrix; Row, Col : Positive) return Boolean is + (G (Row, Col) = ' '); + + function Count_Empties (G : Matrix) return Natural is + Count : Natural := 0; + begin + for Row in Grid_Dimension loop + for Col in Grid_Dimension loop + Count := Count + (if Is_Empty (G, Row, Col) then 1 else 0); + end loop; + end loop; + return Count; + end Count_Empties; + + function Can_Place (G : Matrix; X, Y : Grid_Dimension; Word : Unbounded_String; Dir : Directions) + return Boolean is + GX : Grid_Dimension := X; + GY : Grid_Dimension := Y; + Len : constant Positive := Length (Word); + begin + for C in 1 .. Len loop + if not Is_Empty (G, GX, GY) and then + G (GX, GY) /= Element (Word, C) + then + return False; + else + GX := GX + Moves (Dir).DX; + GY := GY + Moves (Dir).DY; + end if; + end loop; + return True; + end Can_Place; + + procedure Insert_Word (G : in out Matrix; + X, Y : Grid_Dimension; + Dir : Directions; + Word : Unbounded_String) is + -- We assume it fits. You've checked first haven't you! + GX : Grid_Dimension := X; + GY : Grid_Dimension := Y; + begin + for C in 1 .. Length (Word) loop + G (GX, GY) := Element (Word, C); + GX := GX + Moves (Dir).DX; + GY := GY + Moves (Dir).DY; + end loop; + end Insert_Word; + + function Try_To_Place_Word (G : in out Matrix; Word : Unbounded_String; Max_Tries : Positive) + return Boolean is + -- Attempt to place the given word in the grid, return success or failure. + X1, Y1 : Grid_Dimension; + Dir : Directions; + Try : Positive := 1; + Place : Placement; + begin + while Try <= Max_Tries loop + X1 := Rand_Dimension.Random (Dimension_Gen); + Y1 := Rand_Dimension.Random (Dimension_Gen); + Dir := Rand_Dir.Random (Dir_Gen); + if Not_Too_Long (X1, Y1, Length (Word), Dir) and then + Can_Place (G, X1, Y1, Word, Dir) + then + Insert_Word (G, X1, Y1, Dir, Word); + Place.Word := Word; + Place.Start := To_Unbounded_String (X1'Image & LC_Chars'Val (Integer (Y1) + 64)); + Placings.Append (Place); + return True; + end if; + Try := Try + 1; + end loop; + return False; + end Try_To_Place_Word; + + procedure Print_Matrix (M : Matrix) is + begin + Put_Line (" A B C D E F G H I J"); New_Line; + for Row in Grid_Dimension loop + Put (Row'Image); + Set_Col (6); + for Col in Grid_Dimension loop + Put (M (Row, Col) & " "); + end loop; + New_Line; + end loop; + New_Line; + end Print_Matrix; + + function Place_Message (G : in out Matrix; Msg : String) return Boolean is + -- Attempt to put message in grid, return False if unable. + Msg_Posn : Positive := 1; + begin + for Row in Grid_Dimension loop + for Col in Grid_Dimension loop + if Is_Empty (G, Row, Col) then + G (Row, Col) := Msg (Msg_Posn); + if Msg_Posn = Msg'Length then + return True; + else + Msg_Posn := Msg_Posn + 1; + end if; + end if; + end loop; + end loop; + return False; + end Place_Message; + + Grid : Matrix; + Words_Placed : Natural; + Message_Placed : Boolean; + A_Word : Unbounded_String; + Attempt : Positive; + Col : Positive_Count := 1; +begin + Load_Dictionary (DICT_FILENAME); + Rand_Dimension.Reset (Dimension_Gen); + Rand_Dir.Reset (Dir_Gen); + Rand_Len.Reset (Len_Gen); + Rand_10k.Reset (Ten_K_Gen); + loop + Grid := [others => [others => ' ']]; + Words_Placed := 0; Message_Placed := False; Placings.Clear; + Attempt := 1; + Builder : + loop + A_Word := Pick_Random_Word; + if Try_To_Place_Word (Grid, A_Word, 50) then + Words_Placed := @ + 1; + end if; + if Count_Empties (Grid) = MESSAGE'Length then + if Place_Message (Grid, MESSAGE) then + Message_Placed := True; + exit Builder; + end if; + elsif Count_Empties (Grid) < MESSAGE'Length then + -- Put_Line ("No room for message, giving up."); + exit Builder; + elsif Attempt > 1000 then + Put_Line ("Giving up after 1000 tries."); + exit Builder; + end if; + Attempt := Attempt + 1; + end loop Builder; + exit when Words_Placed >= MIN_WORDS and then Message_Placed; + end loop; + Print_Matrix (Grid); + Put_Line ("Words placed:" & Words_Placed'Image); + for P of Placings loop + Set_Col (Col); Put (P.Word); + Set_Col (Col + 9); Put (P.Start); + Col := (if Col < 61 then Col + 20 else 1); + end loop; +end Word_Search; diff --git a/Task/Word-search/Dart/word-search.dart b/Task/Word-search/Dart/word-search.dart new file mode 100644 index 0000000000..03806a7acc --- /dev/null +++ b/Task/Word-search/Dart/word-search.dart @@ -0,0 +1,79 @@ +import 'dart:io'; +import 'package:more/more.dart'; + +var words = RegExp(r'^[a-z]*$'); +const n8 = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + [1, 1], + [1, -1], + [-1, 1], + [-1, -1] +]; + +main() { + var text = File('bin/_other/unixdict.txt') + .readAsLinesSync() + .where((e) => words.hasMatch(e)) + .where((e) => e.length > 2); + + var done = false; + while (!done) { + var square = List.generate(10, (e) => "..........".split('')); + var used = []; + var starts = >[]; + var ends = >[]; + + getNexts() => [ + for (var r in square.indexed()) + for (var c in r.value.indexed()) + if (c.value == '.') [r.index, c.index] + ]; + var nexts = getNexts(); + while (nexts.length > 11) { + // Pick a start and a direction, then fit longest allowed word or loop. + var here = nexts.atRandom(); + var dir = n8.atRandom(); + var len = 1; + var target = square[here.first][here.last]; + while (inBounds( + [here.first + len * dir.first, here.last + len * dir.last])) { + target += + square[here.first + len * dir.first][here.last + len * dir.last]; + len += 1; + } + if (len >= 7) continue; // Stop the grid getting too full. + if (len <= 3) continue; + var reg = RegExp('^$target\$'); + var cands = text.where((e) => reg.hasMatch(e)); + if (cands.isEmpty) continue; + + var cand = cands.atRandom(); + for (var i in 0.to(cand.length)) { + square[here.first + i * dir.first][here.last + i * dir.last] = cand[i]; + } + used.add(cand); + starts.add(here); + ends.add([ + here.first + (len - 1) * dir.first, + here.last + (len - 1) * dir.last + ]); + nexts = getNexts(); + } + if (nexts.length < 11) continue; + if (used.length < 25) continue; + var filler = 'ROSETTACODE'.split(''); + for (var n in nexts.indexed()) { + square[n.value.first][n.value.last] = filler[n.index]; + } + square.forEach(print); + for (var i in 0.to(used.length)) { + print('${used[i]}\t ${starts[i]}\t${ends[i]}'); + } + done = true; + } +} + +inBounds(List pos) => pos.first.between(0, 9) && pos.last.between(0, 9); diff --git a/Task/Word-search/Fortran/word-search.f b/Task/Word-search/Fortran/word-search.f new file mode 100644 index 0000000000..0e2d7be6dd --- /dev/null +++ b/Task/Word-search/Fortran/word-search.f @@ -0,0 +1,509 @@ +program word_search_rosetta_complete + implicit none + + integer, parameter :: GRID_SIZE = 10 + integer, parameter :: MAX_WORDS = 5000 + integer, parameter :: MAX_WORD_LEN = 20 + integer, parameter :: MIN_PLACED = 25 + + character(len=1) :: grid(GRID_SIZE, GRID_SIZE) + character(len=MAX_WORD_LEN) :: words(MAX_WORDS), original_words(MAX_WORDS) + integer :: word_lens(MAX_WORDS), original_lens(MAX_WORDS) + integer :: num_words + integer :: length_limits(3:10) + + type :: word_placement + character(len=MAX_WORD_LEN) :: word + integer :: row, col + integer :: dx, dy + end type + + type(word_placement) :: placed(200), all_found(500) + integer :: num_placed, num_found + + integer :: attempt + + call init_random_seed() + call load_words(original_words, original_lens, num_words) + print '(A,I0,A)', "Loaded ", num_words, " valid words" + + ! Try to create puzzle + do attempt = 1, 10 + words = original_words + word_lens = original_lens + + call create_puzzle(words, word_lens, num_words, grid, placed, num_placed) + + ! VB stops when we have 25+ words (success!) + if (num_placed >= MIN_PLACED) then + print '(A,I0)', "Success on attempt ", attempt + + ! Find ALL words embedded in the final grid + call find_all_words(original_words, original_lens, num_words, grid, all_found, num_found) + + call print_results(grid, placed, num_placed, all_found, num_found) + exit + end if + + print '(A,I0,A,I0,A)', "Attempt ", attempt, " placed ", num_placed, " words, retrying..." + end do + +contains + + subroutine init_random_seed() + integer :: seed_size, clock, i + integer, allocatable :: seed(:) + + call random_seed(size=seed_size) + allocate(seed(seed_size)) + call system_clock(count=clock) + seed = clock + 37 * [(i, i=1, seed_size)] + call random_seed(put=seed) + deallocate(seed) + end subroutine + + subroutine load_words(words, word_lens, num_words) + character(len=*), intent(out) :: words(:) + integer, intent(out) :: word_lens(:) + integer, intent(out) :: num_words + character(len=MAX_WORD_LEN) :: word + integer :: ios, i + logical :: valid + + num_words = 0 + + open(10, file='unixdict.txt', status='old', action='read', iostat=ios) + if (ios /= 0) then + print *, "Error opening unixdict.txt" + stop + end if + + do + read(10, '(A)', iostat=ios) word + if (ios /= 0) exit + + word = trim(word) + if (len_trim(word) <= 2 .or. len_trim(word) > 10) cycle + + valid = .true. + do i = 1, len_trim(word) + if (word(i:i) < 'a' .or. word(i:i) > 'z') then + valid = .false. + exit + end if + end do + + if (valid) then + num_words = num_words + 1 + if (num_words > MAX_WORDS) exit + words(num_words) = trim(word) + word_lens(num_words) = len_trim(word) + end if + end do + + close(10) + end subroutine + + subroutine shuffle_words(words, word_lens, num_words) + character(len=*), intent(inout) :: words(:) + integer, intent(inout) :: word_lens(:) + integer, intent(in) :: num_words + integer :: i, r, temp_len + character(len=MAX_WORD_LEN) :: temp_word + real :: rr + + do i = num_words, 2, -1 + call random_number(rr) + r = int(rr * i) + 1 + + temp_word = words(i) + words(i) = words(r) + words(r) = temp_word + + temp_len = word_lens(i) + word_lens(i) = word_lens(r) + word_lens(r) = temp_len + end do + end subroutine + + function count_spaces(grid) result(count) + character(len=1), intent(in) :: grid(:,:) + integer :: count, i, j + + count = 0 + do i = 1, GRID_SIZE + do j = 1, GRID_SIZE + if (grid(j, i) == ' ') count = count + 1 + end do + end do + end function + + subroutine create_puzzle(words, word_lens, num_words, grid, placed, num_placed) + character(len=*), intent(inout) :: words(:) + integer, intent(inout) :: word_lens(:) + integer, intent(in) :: num_words + character(len=1), intent(out) :: grid(:,:) + type(word_placement), intent(out) :: placed(:) + integer, intent(out) :: num_placed + + integer :: i + real :: r + + ! Initialize grid + grid = ' ' + num_placed = 0 + + ! Pre-seed ROSETTACODE letters (VB strategy) + call random_number(r) + grid(int(r * 5) + 6, 1) = 'R' + + call random_number(r) + grid(int(r * 9) + 2, 2) = 'O' + + call random_number(r) + grid(int(r * 9) + 2, 3) = 'S' + + call random_number(r) + grid(int(r * 9) + 2, 4) = 'E' + + grid(2, 5) = 'T' + grid(10, 5) = 'T' + + call random_number(r) + grid(int(r * 10) + 1, 6) = 'A' + + call random_number(r) + grid(int(r * 10) + 1, 7) = 'C' + + call random_number(r) + grid(int(r * 10) + 1, 8) = 'O' + + call random_number(r) + grid(int(r * 10) + 1, 9) = 'D' + + call random_number(r) + grid(int(r * 10) + 1, 10) = 'E' + + ! Set length limits (pack the grid EXTREMELY full like VB) + length_limits(3) = 500 ! VB had 200 - go even higher + length_limits(4) = 100 + length_limits(5) = 50 + length_limits(6) = 30 + length_limits(7) = 20 + length_limits(8) = 10 + length_limits(9) = 5 + length_limits(10) = 3 + + ! Shuffle words + call shuffle_words(words, word_lens, num_words) + + ! Place words systematically (VB strategy - FILL THE GRID!) + do i = 1, num_words + ! VB stops when grid is completely full + if (count_spaces(grid) == 0) exit + + ! Check length limit + if (word_lens(i) >= 3 .and. word_lens(i) <= 10) then + if (length_limits(word_lens(i)) > 0) then + if (place_word_systematic(words(i), word_lens(i), grid, placed, num_placed)) then + length_limits(word_lens(i)) = length_limits(word_lens(i)) - 1 + end if + end if + end if + end do + + ! Fill remaining spaces with random lowercase + call fill_remaining(grid) + end subroutine + + logical function place_word_systematic(word, word_len, grid, placed, num_placed) + character(len=*), intent(in) :: word + integer, intent(in) :: word_len + character(len=1), intent(inout) :: grid(:,:) + type(word_placement), intent(inout) :: placed(:) + integer, intent(inout) :: num_placed + + integer :: start_pos, test_num, spot, x, y, d, dir_test + integer :: dx(0:7), dy(0:7) + integer :: rdir, rdd + real :: r + + ! Direction arrays + dx = [1, 1, 0, -1, -1, -1, 0, 1] + dy = [0, 1, 1, 1, 0, -1, -1, -1] + + place_word_systematic = .false. + + ! Random starting position + call random_number(r) + start_pos = int(r * 100) + + ! Random direction to traverse grid + call random_number(r) + if (r < 0.5) then + rdir = -1 + else + rdir = 1 + end if + + ! Try all 100 positions + do test_num = 0, 99 + spot = mod(start_pos + test_num * rdir + 100, 100) + y = spot / 10 + 1 + x = mod(spot, 10) + 1 + + ! If first letter matches or space is empty + if (grid(x, y) == word(1:1) .or. grid(x, y) == ' ' .or. & + (grid(x, y) >= 'A' .and. grid(x, y) <= 'Z' .and. & + char(ichar(grid(x, y)) + 32) == word(1:1))) then + + ! Try all 8 directions + call random_number(r) + d = int(r * 8) + call random_number(r) + if (r < 0.5) then + rdd = -1 + else + rdd = 1 + end if + + do dir_test = 0, 7 + d = mod(d + dir_test * rdd + 8, 8) + + if (can_place_vb(word, word_len, x, y, dx(d), dy(d), grid)) then + call place_word_vb(word, word_len, x, y, dx(d), dy(d), grid) + num_placed = num_placed + 1 + placed(num_placed)%word = trim(word) + placed(num_placed)%col = x + placed(num_placed)%row = y + placed(num_placed)%dx = dx(d) + placed(num_placed)%dy = dy(d) + place_word_systematic = .true. + return + end if + end do + end if + end do + end function + + logical function can_place_vb(word, word_len, x, y, dx, dy, grid) + character(len=*), intent(in) :: word + integer, intent(in) :: word_len, x, y, dx, dy + character(len=1), intent(in) :: grid(:,:) + + integer :: i, cx, cy + logical :: fills_something + character(len=1) :: grid_char + + can_place_vb = .false. + fills_something = .false. + + ! Check bounds + do i = 0, word_len - 1 + cx = x + i * dx + cy = y + i * dy + if (cx < 1 .or. cx > GRID_SIZE .or. cy < 1 .or. cy > GRID_SIZE) return + end do + + ! Check if can place and if fills at least one space + do i = 0, word_len - 1 + cx = x + i * dx + cy = y + i * dy + grid_char = grid(cx, cy) + + if (grid_char == ' ') then + fills_something = .true. + else if (grid_char /= word(i+1:i+1)) then + ! Allow uppercase match + if (grid_char >= 'A' .and. grid_char <= 'Z') then + if (char(ichar(grid_char) + 32) /= word(i+1:i+1)) return + else + return + end if + end if + end do + + can_place_vb = fills_something + end function + + subroutine place_word_vb(word, word_len, x, y, dx, dy, grid) + character(len=*), intent(in) :: word + integer, intent(in) :: word_len, x, y, dx, dy + character(len=1), intent(inout) :: grid(:,:) + + integer :: i, cx, cy + + do i = 0, word_len - 1 + cx = x + i * dx + cy = y + i * dy + ! Only place lowercase if empty or already matches + if (grid(cx, cy) == ' ' .or. grid(cx, cy) == word(i+1:i+1)) then + grid(cx, cy) = word(i+1:i+1) + end if + end do + end subroutine + + subroutine fill_remaining(grid) + character(len=1), intent(inout) :: grid(:,:) + integer :: i, j + real :: r + + do i = 1, GRID_SIZE + do j = 1, GRID_SIZE + if (grid(j, i) == ' ') then + call random_number(r) + grid(j, i) = char(int(r * 26) + ichar('a')) + end if + end do + end do + end subroutine + + subroutine find_all_words(words, word_lens, num_words, grid, all_found, num_found) + character(len=*), intent(in) :: words(:) + integer, intent(in) :: word_lens(:) + integer, intent(in) :: num_words + character(len=1), intent(in) :: grid(:,:) + type(word_placement), intent(out) :: all_found(:) + integer, intent(out) :: num_found + + integer :: i, x, y, d, j, cx, cy + integer :: dx(0:7), dy(0:7) + character(len=MAX_WORD_LEN) :: template + logical :: matches + + dx = [1, 1, 0, -1, -1, -1, 0, 1] + dy = [0, 1, 1, 1, 0, -1, -1, -1] + + num_found = 0 + + do i = 1, num_words + do y = 1, GRID_SIZE + do x = 1, GRID_SIZE + ! Check if first letter matches (case-insensitive) + if (grid(x, y) /= words(i)(1:1) .and. & + char(ichar(grid(x, y)) - 32) /= char(ichar(words(i)(1:1)) - 32)) cycle + + do d = 0, 7 + ! Check bounds + cx = x + (word_lens(i) - 1) * dx(d) + cy = y + (word_lens(i) - 1) * dy(d) + if (cx < 1 .or. cx > GRID_SIZE .or. cy < 1 .or. cy > GRID_SIZE) cycle + + ! Build template + template = '' + do j = 0, word_lens(i) - 1 + cx = x + j * dx(d) + cy = y + j * dy(d) + template(j+1:j+1) = grid(cx, cy) + end do + + ! Check match (case-insensitive) + matches = .true. + do j = 1, word_lens(i) + if (template(j:j) /= words(i)(j:j) .and. & + char(ichar(template(j:j)) - 32) /= char(ichar(words(i)(j:j)) - 32)) then + matches = .false. + exit + end if + end do + + if (matches) then + num_found = num_found + 1 + if (num_found > 500) return + all_found(num_found)%word = trim(words(i)) + all_found(num_found)%col = x + all_found(num_found)%row = y + all_found(num_found)%dx = dx(d) + all_found(num_found)%dy = dy(d) + end if + end do + end do + end do + end do + end subroutine + + subroutine print_results(grid, placed, num_placed, all_found, num_found) + character(len=1), intent(in) :: grid(:,:) + type(word_placement), intent(in) :: placed(:), all_found(:) + integer, intent(in) :: num_placed, num_found + + integer :: i, j, uppercase_count + character(len=20) :: dir_name + + print * + print *, "Word Search Puzzle (10x10)" + print *, "==========================" + print * + + write(*, '(A)', advance='no') " " + do j = 0, 9 + write(*, '(I2)', advance='no') j + end do + print * + print * + + do i = 1, GRID_SIZE + write(*, '(I3,A)', advance='no') i-1, " " + do j = 1, GRID_SIZE + write(*, '(A2)', advance='no') grid(j, i) + end do + print * + end do + + uppercase_count = 0 + do i = 1, GRID_SIZE + do j = 1, GRID_SIZE + if (grid(j, i) >= 'A' .and. grid(j, i) <= 'Z') uppercase_count = uppercase_count + 1 + end do + end do + + print * + print '(A,I0)', "ROSETTACODE letters: ", uppercase_count + print * + print '(A,I0,A)', "Words placed: ", num_placed + print '(A,I0,A)', "Total words found embedded: ", num_found, " (including overlaps)" + print *, "==========================" + print * + + print *, "Placed words:" + do i = 1, min(num_placed, 50) + dir_name = get_direction_name(placed(i)%dx, placed(i)%dy) + write(*, '(I3,A,A12,A,I2,A,I2,A,A)') & + i, '. ', trim(placed(i)%word), & + ' (', placed(i)%col-1, ',', placed(i)%row-1, ') ', trim(dir_name) + end do + + print * + print *, "All words found in grid:" + do i = 1, min(num_found, 100) + dir_name = get_direction_name(all_found(i)%dx, all_found(i)%dy) + write(*, '(I3,A,A12,A,I2,A,I2,A,A)') & + i, '. ', trim(all_found(i)%word), & + ' (', all_found(i)%col-1, ',', all_found(i)%row-1, ') ', trim(dir_name) + end do + end subroutine + + function get_direction_name(dx, dy) result(name) + integer, intent(in) :: dx, dy + character(len=20) :: name + + if (dy == 0 .and. dx > 0) then + name = "E" + else if (dy == 0 .and. dx < 0) then + name = "W" + else if (dx == 0 .and. dy > 0) then + name = "S" + else if (dx == 0 .and. dy < 0) then + name = "N" + else if (dx > 0 .and. dy > 0) then + name = "SE" + else if (dx > 0 .and. dy < 0) then + name = "NE" + else if (dx < 0 .and. dy > 0) then + name = "SW" + else if (dx < 0 .and. dy < 0) then + name = "NW" + end if + end function + +end program word_search_rosetta_complete diff --git a/Task/Word-wheel/Ada/word-wheel.adb b/Task/Word-wheel/Ada/word-wheel.adb new file mode 100644 index 0000000000..73db7574e6 --- /dev/null +++ b/Task/Word-wheel/Ada/word-wheel.adb @@ -0,0 +1,56 @@ +with Ada.Characters.Handling; use Ada.Characters.Handling; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO; +procedure Wordwheel is + Compulsory_Ix : constant Positive := 5; + Min_Length : constant Positive := 3; + + function Char_Posn (Str : Unbounded_String; C : Character) return Natural is + begin + for Ix in 1 .. Length (Str) loop + if Element (Str, Ix) = C then + return Ix; + end if; + end loop; + return 0; + end Char_Posn; + + procedure Search (Dict_Filename : String; Wheel : String) is + Dict_File : File_Type; + Allowed : constant String := To_Lower (Wheel); + Required_Char : constant String (1 .. 1) := "" & Allowed (Compulsory_Ix); + Available, Dict_Word : Unbounded_String; + Dict_Word_Len : Positive; + Matched : Boolean; + Posn : Natural; + begin + Open (File => Dict_File, Mode => In_File, Name => Dict_Filename); + while not End_Of_File (Dict_File) loop + Dict_Word := Get_Line (Dict_File); + Dict_Word_Len := Length (Dict_Word); + if Dict_Word_Len >= Min_Length and then + Dict_Word_Len <= Wheel'Length and then + Ada.Strings.Unbounded.Count (Dict_Word, Required_Char) > 0 + then + Available := To_Unbounded_String (Allowed); + Matched := True; + for i in 1 .. Dict_Word_Len loop + Posn := Char_Posn (Available, Element (Dict_Word, i)); + if Posn > 0 then + Delete (Source => Available, From => Posn, Through => Posn); + else + Matched := False; + exit; + end if; + end loop; + if Matched then + Put_Line (Dict_Word); + end if; + end if; + end loop; + Close (Dict_File); + end Search; +begin + Search ("unixdict.txt", "ndeokgelw"); +end Wordwheel; diff --git a/Task/Word-wheel/Pluto/word-wheel.pluto b/Task/Word-wheel/Pluto/word-wheel.pluto new file mode 100644 index 0000000000..37b6b805f7 --- /dev/null +++ b/Task/Word-wheel/Pluto/word-wheel.pluto @@ -0,0 +1,70 @@ +local letters = {"d", "e", "e", "g", "k", "l", "n", "o","w"} +local word_list = "unixdict.txt" -- local copy +local nl = os.platform == "windows" ? "\r\n" : "\n" +local words = io.contents(word_list):rstrip():split(nl) +-- Get rid of words under 3 letters or over 9 letters. +words = words:filter(|w| -> 2 < #w < 10):reorder() +local found = {} +for words as word do + if "k" in word then + local lets = letters:clone() + local ok = true + for i = 1, #word do + local c = word[i] + local ix = lets:findindex(|e| -> e == c) + if !ix then + ok = false + break + end + lets:remove(ix) + end + if ok then found:insert(word) end + end +end + +print($"The following {#found} words are the solutions to the puzzle:") +print(found:concat(nl)) + +-- Optional extra. +local most_found = 0 +local most_words9 = {} +local most_letters = {} +-- Iterate through all 9 letter words in the dictionary. +for words:filtered(|w| -> #w == 9) as word9 do + letters = word9:split(""):sort() + -- Get distinct letters. + local distinct_letters = letters:dedup():reorder() + -- Place each distinct letter in the middle and see what we can do with the rest. + for distinct_letters as letter do + found = 0 + for words as word do + if word:find(letter, 1, true) then + local lets = letters:clone() + local ok = true + for i = 1, #word do + local c = word[i] + local ix = lets:findindex(|e| -> e == c) + if !ix then + ok = false + break + end + lets:remove(ix) + end + if ok then found += 1 end + end + end + if found > most_found then + most_found = found + most_words9 = {word9} + most_letters = {letter} + elseif found == most_found then + most_words9:insert(word9) + most_letters:insert(letter) + end + end +end +print($"\nMost words found = {most_found}") +print("Nine letter words producing this total:") +for i = 1, #most_words9 do + print($"{most_words9[i]} with central letter '{most_letters[i]}'") +end diff --git a/Task/Word-wheel/Uiua/word-wheel-1.uiua b/Task/Word-wheel/Uiua/word-wheel-1.uiua new file mode 100644 index 0000000000..83d86fdfa2 --- /dev/null +++ b/Task/Word-wheel/Uiua/word-wheel-1.uiua @@ -0,0 +1,6 @@ +Words ← ▽⊸(≥3≡◇⧻)⊜□⊸≠@\n&fras"RosettaCode/unixdict.txt" +Grid ← "kndeogelw" +Counts ← ⊕⧻⊸⨂◴Grid +GridCounts ← Counts Grid +IsValid ← ↧⊃(/↧≥₀⬚0˜-GridCounts|>0⊢) Counts +⊏⍖⊸≡◇⧻▽⊸≡◇IsValid Words # Valid answers, by falling length. diff --git a/Task/Word-wheel/Uiua/word-wheel-2.uiua b/Task/Word-wheel/Uiua/word-wheel-2.uiua new file mode 100644 index 0000000000..40e269938e --- /dev/null +++ b/Task/Word-wheel/Uiua/word-wheel-2.uiua @@ -0,0 +1,22 @@ +Words ← ▽⊸(≥3≡◇⧻)⊜□⊸≠@\n&fras"RosettaCode/unixdict.txt" +# +KeepNice ← ▽⊸(↧⊃(≥0|≤26)≡◇(-@a⊢))▽⊸(≤9≡◇⧻)▽⊸(≥3≡◇⧻) +Words ← KeepNice⊜□⊸≠@\n&fras"RosettaCode/unixdict.txt" + +Alpha ← "abcdefghijklmnopqrstuvwxyz" +Mask ← /+≡˜⌕¤Alpha # Mask against alphabet. +Masks ← ≡◇(/+≡⌕)Words¤¤Alpha # Masks for all words. +CanMake ← /↧≥0-Mask # Does each letter in cand appear <= each letter in target? +HaveCore ← ▽⊸≡◇˜∊¤⊢ # Keep cands which have the central letter. +Matches ← ˜⊏Words⊚≡(/↧≥0-)Masks ¤Mask # Words that be spelt using target. +Answers ← ⊏⍖⊸≡◇⧻HaveCore⟜Matches # Keep cands which lead with core letter. +&p$"Part 1: _" Answers "kndeogelw" + +Words₉ ← ▽⊸≡◇(=9⧻)Words +# Find all matches for a word, check which letters are used and +# their counts, choose the best -> [count best_letter] +CountFor ← ⟜˜⨂⊸/↥/+≡◇(>0Mask)Matches + +˜⊡Words₉⟜⊡˜⨂⊸(/↥)⊸≡⊢⍉⊟≡◇CountFor Words₉ +&p$"Part 2 - best word '_': _ matches with '_' at centre" °□⊙⊙(˜⊡Alpha)⊙°⊟ +&p$"Confirmation - _ answers: _" ⊸⧻ Answers "etrminals" diff --git a/Task/Word-wheel/VBScript/word-wheel.vbs b/Task/Word-wheel/VBScript/word-wheel.vbs new file mode 100644 index 0000000000..dfc4534d41 --- /dev/null +++ b/Task/Word-wheel/VBScript/word-wheel.vbs @@ -0,0 +1,74 @@ +Const wheel="ndeokgelw" + +Sub print(s): + On Error Resume Next + WScript.stdout.WriteLine (s) + If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit +End Sub + +Dim oDic +Set oDic = WScript.CreateObject("scripting.dictionary") +Dim cnt(127) +Dim fso +Set fso = WScript.CreateObject("Scripting.Filesystemobject") +Set ff=fso.OpenTextFile("unixdict.txt") +i=0 +print "reading words of 3 or more letters" +While Not ff.AtEndOfStream + x=LCase(ff.ReadLine) + If Len(x)>=3 Then + If Not odic.exists(x) Then oDic.Add x,0 + End If +Wend +print "remaining words: "& oDic.Count & vbcrlf +ff.Close +Set ff=Nothing +Set fso=Nothing + +Set re=New RegExp +print "removing words with chars not in the wheel" +re.pattern="[^"& wheel &"]" +For Each w In oDic.Keys + If re.test(w) Then oDic.remove(w) +Next +print "remaining words: "& oDic.Count & vbcrlf + +print "ensuring the mandatory letter "& Mid(wheel,5,1) & " is present" +re.Pattern=Mid(wheel,5,1) +For Each w In oDic.Keys + If Not re.test(w) Then oDic.remove(w) +Next +print "remaining words: "& oDic.Count & vbcrlf + +print "checking number of chars" + +Dim nDic +Set nDic = WScript.CreateObject("scripting.dictionary") +For i=1 To Len(wheel) + x=Mid(wheel,i,1) + If nDic.Exists(x) Then + a=nDic(x) + nDic(x)=Array(a(0)+1,0) + Else + nDic.add x,Array(1,0) + End If +Next + +For Each w In oDic.Keys + For Each c In nDic.Keys + ndic(c)=Array(nDic(c)(0),0) + Next + For ii = 1 To len(w) + c=Mid(w,ii,1) + a=nDic(c) + If (a(0)=a(1)) Then + oDic.Remove(w):Exit For + End If + nDic(c)=Array(a(0),a(1)+1) + Next +Next + +print "Remaining words "& oDic.count +For Each w In oDic.Keys + print w +Next diff --git a/Task/Word-wrap/Ada/word-wrap-1.adb b/Task/Word-wrap/Ada/word-wrap-1.adb new file mode 100644 index 0000000000..a716ee751b --- /dev/null +++ b/Task/Word-wrap/Ada/word-wrap-1.adb @@ -0,0 +1,18 @@ +generic + with procedure Put_Line(Line: String); +package Word_Wrap is + + type Basic(Length_Of_Output_Line: Positive) is tagged private; + + procedure Push_Word(State: in out Basic; Word: String); + procedure New_Paragraph(State: in out Basic); + procedure Finish(State: in out Basic); + +private + type Basic(Length_Of_Output_Line: Positive) is tagged record + Line: String(1 .. Length_Of_Output_Line); + Size: Natural := 0; -- Line(1 .. Size) is relevant + Top_Of_Paragraph: Boolean := True; + end record; + +end Word_Wrap; diff --git a/Task/Word-wrap/Ada/word-wrap-2.adb b/Task/Word-wrap/Ada/word-wrap-2.adb new file mode 100644 index 0000000000..e1c6fb4675 --- /dev/null +++ b/Task/Word-wrap/Ada/word-wrap-2.adb @@ -0,0 +1,36 @@ +package body Word_Wrap is + + procedure Push_Word(State: in out Basic; Word: String) is + begin + if Word'Length + State.Size >= State.Length_Of_Output_Line then + Put_Line(State.Line(1 .. State.Size)); + State.Line(1 .. Word'Length) := Word; -- may raise CE if Word too long + State.Size := Word'Length; + elsif State.Size > 0 then + State.Line(State.Size+1 .. State.Size+1+Word'Length) := ' ' & Word; + State.Size := State.Size + 1 + Word'Length; + else + State.Line(1 .. Word'Length) := Word; + State.Size := Word'Length; + end if; + State.Top_Of_Paragraph := False; + end Push_Word; + + procedure New_Paragraph(State: in out Basic) is + begin + Finish(State); + if not State.Top_Of_Paragraph then + Put_Line(""); + State.Top_Of_Paragraph := True; + end if; + end New_Paragraph; + + procedure Finish(State: in out Basic) is + begin + if State.Size > 0 then + Put_Line(State.Line(1 .. State.Size)); + State.Size := 0; + end if; + end Finish; + +end Word_Wrap; diff --git a/Task/Word-wrap/Ada/word-wrap-3.adb b/Task/Word-wrap/Ada/word-wrap-3.adb new file mode 100644 index 0000000000..f3e2fe48cb --- /dev/null +++ b/Task/Word-wrap/Ada/word-wrap-3.adb @@ -0,0 +1,62 @@ +with Ada.Text_IO, Word_Wrap, Ada.Strings.Unbounded, Ada.Command_Line; + +procedure Wrap is + + use Ada.Strings.Unbounded; + + Line: Unbounded_String; + Word: Unbounded_String; + + function "+"(S: String) return Unbounded_String renames To_Unbounded_String; + function "-"(U: Unbounded_String) return String renames To_String; + + package IO renames Ada.Text_IO; + + procedure Split(S: Unbounded_String; First, Rest: out Unbounded_String) is + + function Skip_Leading_Spaces(S: String) return String is + begin + if S="" then return ""; + elsif S(S'First) = ' ' then return S(S'First+1 .. S'Last); + else return S; + end if; + end Skip_Leading_Spaces; + + Str: String := Skip_Leading_Spaces(-S); + I: Positive := Str'First; + J: Natural; + begin + -- read nonspaces for First output param + J := I-1; + while J < Str'Last and then Str(J+1) /= ' ' loop + J := J + 1; + end loop; + First := + Str(I .. J); + + -- write output param Rest + Rest := + Skip_Leading_Spaces(Str(J+1 .. Str'Last)); + end Split; + + procedure Print(S: String) is + begin + IO.Put_Line(S); + end Print; + + package WW is new Word_Wrap(Print); + + Wrapper: WW.Basic(Integer'Value(Ada.Command_Line.Argument(1))); + +begin + while not IO.End_Of_File loop + Line := +IO.Get_Line; + if Line = +"" then + Wrapper.New_Paragraph; + Line := +IO.Get_Line; + end if; + while Line /= +"" loop + Split(Line, First => Word, Rest => Line); + Wrapper.Push_Word(-Word); + end loop; + end loop; + Wrapper.Finish; +end Wrap; diff --git a/Task/Word-wrap/PowerShell/word-wrap-1.ps1 b/Task/Word-wrap/PowerShell/word-wrap-1.ps1 new file mode 100644 index 0000000000..0e8c3fa88f --- /dev/null +++ b/Task/Word-wrap/PowerShell/word-wrap-1.ps1 @@ -0,0 +1,29 @@ +function wrap{ +$divide=$args[0] -split " " +$width=$args[1] +$spaceleft=$width + +foreach($word in $divide){ + if($word.length+1 -gt $spaceleft){ + $output+="`n$word " + $spaceleft=$width-($word.length+1) + } else { + $output+="$word " + $spaceleft-=$word.length+1 + } +} + +return "$output`n" +} + +### The Main Thing... + +$paragraph="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur." + +"`nLine width:30`n" +wrap $paragraph 30 +"=========================================================" +"Line width:100`n" +wrap $paragraph 100 + +### End script diff --git a/Task/Word-wrap/PowerShell/word-wrap-2.ps1 b/Task/Word-wrap/PowerShell/word-wrap-2.ps1 new file mode 100644 index 0000000000..b865a3df40 --- /dev/null +++ b/Task/Word-wrap/PowerShell/word-wrap-2.ps1 @@ -0,0 +1,52 @@ +function Out-WordWrap +{ + [CmdletBinding()] + [OutputType([string])] + Param + ( + [Parameter(Mandatory=$true, + ValueFromPipeline=$true, + Position=0)] + [string] + $Text, + + [Parameter(Mandatory=$false, + Position=1)] + [ValidateRange(16,160)] + [int] + $Width = 80 + ) + + Begin + { + function New-WordWrap ([string]$Text, [int]$Width) + { + [string[]]$words = $Text.Split() + [string]$output = "" + [int]$remaining = $Width + + foreach ($word in $words) + { + if($word.Length + 1 -gt $remaining) + { + $output += "`n$word " + $remaining = $Width - ($word.Length + 1) + } + else + { + $output += "$word " + $remaining -= $word.Length + 1 + } + } + + return "$output`n" + } + } + Process + { + foreach ($paragraph in $Text) + { + New-WordWrap -Text $paragraph -Width $Width + } + } +} diff --git a/Task/Word-wrap/PowerShell/word-wrap-3.ps1 b/Task/Word-wrap/PowerShell/word-wrap-3.ps1 new file mode 100644 index 0000000000..2d2c8e832c --- /dev/null +++ b/Task/Word-wrap/PowerShell/word-wrap-3.ps1 @@ -0,0 +1,12 @@ +[string[]]$paragraphs = "Rebum everti delicata an vel, quo ut temporibus interpretaris, mea debet mnesarchum disputando ad. Id has dolorum contentiones, mel ea noster adipisci. Id persius appareat eos, aeque dolorum fastidii eam in. Partem assentior contentiones ut mea. Cu augue facilis fabellas cum, vix eu sanctus denique imperdiet, appareat percipit qui ex.", + "Nihil discere phaedrum at duo, no eum adhuc autem error. Quo aliquam delicata contentiones et, in sed ferri legimus sententiae, nihil solet docendi id eum. Ius ut meliore vulputate adipiscing, sea cu virtute praesent. Euripidis instructior est eu. Veri cotidieque ex vel, aliquam eruditi nusquam sea ne, eu wisi ubique ullamcorper est. Qui doctus epicuri ei. Cum esse detracto concludaturque ea, veri erant per ad, vide ancillae principes ius id.", + "Id disputando signiferumque nam, mei illud aeterno ut. Facilisis evertitur mei at. Qui in wisi fugit, eirmod comprehensam duo ei. Ea mel omnium nusquam, causae consequat appellantur per te.", + "Denique deseruisse ea his. Mundi scripta adolescens te ius, cum error persius cotidieque cu. Nobis apeirian ad his. Ius omnes gloriatur at, has eu tamquam inciderint, ubique commodo pro ad. Ex veri ceteros quo, duo an labores adolescens. Sed id quod verterem prodesset, magna eloquentiam ea eum.", + "Qui sanctus oportere quaerendum ex, usu vivendo accusamus posidonium an. Quo cu graece reprimique. Ea cum purto quando referrentur, tritani perfecto ne sit. Ne sit iusto ludus, ea ius eruditi dissentiunt, fabellas disputando eu vix. Te vim eripuit debitis tincidunt, in vim nonumes consetetur.", + "Affert exerci aperiri pri ea. Ut dicant essent corrumpit sit. Sea saepe nullam referrentur ut, vis dolores perfecto cu. At nam inimicus evertitur vulputate.", + "Dolor volutpat praesent vix ne, at soluta oblique admodum eum. Duis adipisci mea in, nam ut tota choro theophrastus. Ex scripta definitiones mei, augue doctus ne sed, munere posidonium eum id. Ad graeco audire per.", + "Sale salutatus et mei, mea elit illud adipiscing ei, cum ea sumo melius forensibus. Eu inani iusto oporteat eum, ei vix iisque saperet detraxit. Fabulas perpetua similique eam ne, noster corpora dissentiet qui ex, et qui integre graecis. Eripuit nonumes deterruisset an pro, ei ferri similique cum. Odio dolores inciderint ei vim, an est dolorum delicata temporibus, eu mea quis accumsan. Vel stet affert option at.", + "In gubergren voluptaria reprimique pro, option fuisset id est. Rebum delicata ad sea, ex vidit errem vis, mei at duis dicam sensibus. Nibh debet iudicabit has no, vim te dicit libris possim. Debet viderer consequuntur ea pro. Ex dicat iriure scripta pro.", + "An dicat diceret eligendi duo. Est cu equidem deterruisset, usu ad regione equidem, vim amet vero possim ex. Theophrastus conclusionemque ad quo, inimicus deseruisse voluptatibus eum et. Duis delectus mandamus an mei, usu timeam nostrum suscipiantur id." + +$paragraphs | Out-WordWrap -Width 100 diff --git a/Task/Word-wrap/VBScript/word-wrap.vbs b/Task/Word-wrap/VBScript/word-wrap.vbs new file mode 100644 index 0000000000..c4016c7a9f --- /dev/null +++ b/Task/Word-wrap/VBScript/word-wrap.vbs @@ -0,0 +1,30 @@ +column = 60 +text = "In olden times when wishing still helped one, there lived a king " &_ + "whose daughters were all beautiful, but the youngest was so beautiful "&_ + "that the sun itself, which has seen so much, was astonished whenever "&_ + "it shone-in-her-face. Close-by-the-king's castle lay a great dark "&_ + "forest, and under an old lime-tree in the forest was a well, and when "&_ + "the day was very warm, the king's child went out into the forest and "&_ + "sat down by the side of the cool-fountain, and when she was bored she "&_ + "took a golden ball, and threw it up on high and caught it, and this "&_ + "ball was her favorite plaything." + +Call wordwrap(text,column) + +Sub wordwrap(s,n) + word = Split(s," ") + row = "" + For i = 0 To UBound(word) + If Len(row) = 0 Then + row = row & word(i) + ElseIf Len(row & " " & word(i)) <= n Then + row = row & " " & word(i) + Else + WScript.StdOut.WriteLine row + row = word(i) + End If + Next + If Len(row) > 0 Then + WScript.StdOut.WriteLine row + End If +End Sub diff --git a/Task/Wordiff/Crystal/wordiff.cr b/Task/Wordiff/Crystal/wordiff.cr new file mode 100644 index 0000000000..e23d8d185d --- /dev/null +++ b/Task/Wordiff/Crystal/wordiff.cr @@ -0,0 +1,40 @@ +require "levenshtein" + +words = File.read_lines("unixdict.txt").to_set + +print "Enter player names separated by spaces: " +players = gets.not_nil!.split + +current = words.select { |w| 3 <= w.size <= 4 }.sample +used = Set.new [current] + +puts "Starting word is '#{current}'!" + +players.cycle.skip(players.size-1).each_cons_pair do |previous, player| + print "#{player}, give me a wordiff from '#{current}': " + guess = gets.not_nil! + if guess.in?(words) && !guess.in?(used) && (dist = Levenshtein.distance(current, guess)) == 1 + puts "Good!" + used << guess + current = guess + else + possible = words.select {|w| + !w.in?(used) && (w.size - guess.size).abs <= 1 && Levenshtein.distance(current, w) == 1 + } + if !guess.in? words + puts "That word isn't in the dictionary." + elsif guess.in? used + puts "That word was already used." + else + puts "That word isn't a wordiff from '#{guess}'." + end + puts "You LOSE, #{player}!" + if possible.size > 0 + puts "You could have entered: #{possible.sort.join(", ")}" + else + puts "(But you didn't have any word left to enter. Brilliant move by #{previous}!)" + end + puts "#{previous} WINS!" + break + end +end diff --git a/Task/World-Cup-group-stage/EasyLang/world-cup-group-stage.easy b/Task/World-Cup-group-stage/EasyLang/world-cup-group-stage.easy new file mode 100644 index 0000000000..847a9f5de3 --- /dev/null +++ b/Task/World-Cup-group-stage/EasyLang/world-cup-group-stage.easy @@ -0,0 +1,54 @@ +games$[] = [ "12" "13" "14" "23" "24" "34" ] +results$ = "000000" +# +proc sort &d[] . + for i = 1 to len d[] - 1 : for j = i + 1 to len d[] + if d[j] < d[i] : swap d[j] d[i] + . +. +func tonum s$ b . + for c$ in strchars s$ : r = r * b + number c$ + return r +. +func$ tostr ndig n b . + for i to ndig + d = n mod b + n = n div b + r$ = d & r$ + . + return r$ +. +func nextResult . + if results$ = "222222" : return 0 + res = tonum results$ 3 + results$ = tostr 6 (res + 1) 3 + return 1 +. +len points[][] 4 +for i to 4 : len points[i][] 10 +repeat + results$[] = strchars results$ + records[] = [ 0 0 0 0 ] + for i to 6 + if results$[i] = "2" + records[strcode substr games$[i] 1 1 - 48] += 3 + elif results$[i] = "1" + records[strcode substr games$[i] 1 1 - 48] += 1 + records[strcode substr games$[i] 2 1 - 48] += 1 + elif results$[i] = "0" + records[strcode substr games$[i] 2 1 - 48] += 3 + . + . + sort records[] + for i to 4 : points[i][records[i] + 1] += 1 + until nextResult = 0 +. +print "POINTS 0 1 2 3 4 5 6 7 8 9" +print "--------------------------------------------------" +places$[] = [ "1st" "2nd" "3rd" "4th" ] +numfmt 4 0 +for i to 4 + write places$[i] & " place " + for j to 10 : write points[5 - i][j] + print "" +. diff --git a/Task/World-Cup-group-stage/Mathematica/world-cup-group-stage.math b/Task/World-Cup-group-stage/Mathematica/world-cup-group-stage.math new file mode 100644 index 0000000000..93420469bc --- /dev/null +++ b/Task/World-Cup-group-stage/Mathematica/world-cup-group-stage.math @@ -0,0 +1,10 @@ +scoring[1] = 3; scoring[0] = 1; scoring[-1] = 0; +scoreTable[results_] := Module[{s = {0, 0, 0, 0}, pairs = Subsets[Range[4], {2}]}, + MapThread[( + s[[First@#2]] += scoring[#1]; + s[[Last@#2]] += scoring[-#1]) &, + {results, pairs}]; + ReverseSort[s]]; + +allScoreTables = Map[scoreTable, Tuples[{-1, 0, 1}, 6]]; +Table[BinCounts[allScoreTables[[All, i]], {0, 10}], {i, 4}] // TableForm diff --git a/Task/World-Cup-group-stage/Pluto/world-cup-group-stage.pluto b/Task/World-Cup-group-stage/Pluto/world-cup-group-stage.pluto new file mode 100644 index 0000000000..636ab946bb --- /dev/null +++ b/Task/World-Cup-group-stage/Pluto/world-cup-group-stage.pluto @@ -0,0 +1,42 @@ +require "table2" +local fmt = require "fmt" + +local games = {"12", "13", "14", "23", "24", "34"} +local results = "000000" + +local function next_result() + if results == "222222" then return false end + local res = tonumber(results, 3) + 1 + results = fmt.lpad(fmt.itoa(res, 3), 6, "0") + return true +end + +local points = table.create(4) +for i = 1, 4 do points[i] = table.rep(10, 0) end +while true do + local records = table.rep(4, 0) + for i = 1, 6 do + local g1 = tonumber(games[i][1]) + local g2 = tonumber(games[i][2]) + if results[i] == "2" then + records[g1] += 3 + elseif results[i] == "1" then + records[g1] += 1 + records[g2] += 1 + elseif results[i] == "0" then + records[g2] += 3 + end + end + records:sort() + for i = 1, 4 do points[i][records[i] + 1] += 1 end + if !next_result() then break end +end +print("POINTS 0 1 2 3 4 5 6 7 8 9") +print("---------------------------------------------------------------") +for i = 0, 3 do + fmt.write("%s place ", fmt.ord(i + 1)) + points[4 - i]:foreach(|p| -> do + fmt.write("%5d", p) + end) + print() +end diff --git a/Task/Write-entire-file/Ada/write-entire-file.adb b/Task/Write-entire-file/Ada/write-entire-file.adb new file mode 100644 index 0000000000..4af5b32e54 --- /dev/null +++ b/Task/Write-entire-file/Ada/write-entire-file.adb @@ -0,0 +1,18 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Write_Whole_File is + File_Name : constant String := "the_file.txt"; + + F : File_Type; +begin + begin + Open (F, Mode => Out_File, Name => File_Name); + exception + when Name_Error => Create (F, Mode => Out_File, Name => File_Name); + end; + + Put (F, "(Over)write a file so that it contains a string. " & + "The reverse of Read entire file—for when you want to update or " & + "create a file which you would read in its entirety all at once."); + Close (F); +end Write_Whole_File; diff --git a/Task/Write-entire-file/AppleScript/write-entire-file.applescript b/Task/Write-entire-file/AppleScript/write-entire-file.applescript new file mode 100644 index 0000000000..566279d9d5 --- /dev/null +++ b/Task/Write-entire-file/AppleScript/write-entire-file.applescript @@ -0,0 +1,6 @@ +on overwrite(filepath, str) + set fp to open for access file filepath with write permission + set eof of fp to 0 + write str to fp + close access fp +end overwrite diff --git a/Task/Write-entire-file/Batch-File/write-entire-file-1.bat b/Task/Write-entire-file/Batch-File/write-entire-file-1.bat new file mode 100644 index 0000000000..3813689275 --- /dev/null +++ b/Task/Write-entire-file/Batch-File/write-entire-file-1.bat @@ -0,0 +1,3 @@ +@echo off +setlocal enableextensions +type con>%1 || goto:eof %= exit at error =% diff --git a/Task/Write-entire-file/Batch-File/write-entire-file-2.bat b/Task/Write-entire-file/Batch-File/write-entire-file-2.bat new file mode 100644 index 0000000000..be8b31bf14 --- /dev/null +++ b/Task/Write-entire-file/Batch-File/write-entire-file-2.bat @@ -0,0 +1,5 @@ +@echo off +setlocal enableextensions +type nul>%1 || goto:eof +::don't ignore blank lines +for /f tokens^=1*^ delims^=]^ eol^= %%a in ('find /n /v ""') do echo(%%b>>%1 diff --git a/Task/Write-entire-file/COBOL/write-entire-file.cob b/Task/Write-entire-file/COBOL/write-entire-file.cob new file mode 100644 index 0000000000..5da2bccac4 --- /dev/null +++ b/Task/Write-entire-file/COBOL/write-entire-file.cob @@ -0,0 +1,41 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. Overwrite. + AUTHOR. Bill Gunshannon. + INSTALLATION. Home. + DATE-WRITTEN. 31 December 2021. + ************************************************************ + ** Program Abstract: + ** Simple COBOL task. Open file for output. Write + ** data to file. Close file. Done... + ************************************************************ + + ENVIRONMENT DIVISION. + + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT File-Name ASSIGN TO "File.txt" + ORGANIZATION IS LINE SEQUENTIAL. + DATA DIVISION. + + FILE SECTION. + + FD File-Name + DATA RECORD IS Record-Name. + 01 Record-Name. + 02 Field1 PIC X(80). + + WORKING-STORAGE SECTION. + + 01 New-Val PIC X(80) + VALUE 'Hello World'. + + + PROCEDURE DIVISION. + + Main-Program. + OPEN OUTPUT File-Name. + WRITE Record-Name FROM New-Val. + CLOSE File-Name. + STOP RUN. + + END-PROGRAM. diff --git a/Task/Write-entire-file/Crystal/write-entire-file.cr b/Task/Write-entire-file/Crystal/write-entire-file.cr new file mode 100644 index 0000000000..51a30dc094 --- /dev/null +++ b/Task/Write-entire-file/Crystal/write-entire-file.cr @@ -0,0 +1 @@ +File.write "filename", "An arbitrary string" diff --git a/Task/Write-entire-file/Icon/write-entire-file.icon b/Task/Write-entire-file/Icon/write-entire-file.icon new file mode 100644 index 0000000000..2dd1952e44 --- /dev/null +++ b/Task/Write-entire-file/Icon/write-entire-file.icon @@ -0,0 +1,3 @@ +procedure main(A) + write(open(\A[1]|"afile","w"),"a string") +end diff --git a/Task/Write-entire-file/Pluto/write-entire-file.pluto b/Task/Write-entire-file/Pluto/write-entire-file.pluto new file mode 100644 index 0000000000..a6ee27d209 --- /dev/null +++ b/Task/Write-entire-file/Pluto/write-entire-file.pluto @@ -0,0 +1,11 @@ +-- Create a text file. +io.contents("hello.txt", "hello") + +-- Check it worked. +print(io.contents("hello.txt")) + +-- Overwrite it by 'creating' the file again. +io.contents("hello.txt", "goodbye") + +-- Check it worked. +print(io.contents("hello.txt")) diff --git a/Task/Write-entire-file/PowerShell/write-entire-file.ps1 b/Task/Write-entire-file/PowerShell/write-entire-file.ps1 new file mode 100644 index 0000000000..0d1164edc8 --- /dev/null +++ b/Task/Write-entire-file/PowerShell/write-entire-file.ps1 @@ -0,0 +1 @@ +Get-Process | Out-File -FilePath .\ProcessList.txt diff --git a/Task/Write-entire-file/Rye/write-entire-file.rye b/Task/Write-entire-file/Rye/write-entire-file.rye new file mode 100644 index 0000000000..7b41c2396b --- /dev/null +++ b/Task/Write-entire-file/Rye/write-entire-file.rye @@ -0,0 +1 @@ +Write %output.txt "Hello World" diff --git a/Task/Write-entire-file/VBScript/write-entire-file.vbs b/Task/Write-entire-file/VBScript/write-entire-file.vbs new file mode 100644 index 0000000000..55419ee7eb --- /dev/null +++ b/Task/Write-entire-file/VBScript/write-entire-file.vbs @@ -0,0 +1,12 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +SourceFile = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\out.txt" +Content = "(Over)write a file so that it contains a string." & vbCrLf &_ + "The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once." + +With objFSO.OpenTextFile(SourceFile,2,True,0) + .Write Content + .Close +End With + +Set objFSO = Nothing diff --git a/Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.adb b/Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.adb new file mode 100644 index 0000000000..6202639d1d --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Ada/write-float-arrays-to-a-text-file.adb @@ -0,0 +1,34 @@ +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; + +procedure Write_Float_Array is + type Float_Array is array (1..4) of Float; + procedure Write_Columns + ( File : File_Type; + X : Float_Array; + Y : Float_Array; + X_Pres : Natural := 3; + Y_Pres : Natural := 5 + ) is + begin + for I in Float_Array'range loop + Put (File => File, Item => X(I), Fore => 1, Aft => X_Pres - 1); + Put (File, " "); + Put (File => File, Item => Y(I), Fore => 1, Aft => Y_Pres - 1); + New_Line (File); + end loop; + end Write_Columns; + + File : File_Type; + X : Float_Array := (1.0, 2.0, 3.0, 1.0e11); + Y : Float_Array; +begin + Put ("Tell us the file name to write:"); + Create (File, Out_File, Get_Line); + for I in Float_Array'range loop + Y(I) := Sqrt (X (I)); + end loop; + Write_columns (File, X, Y); + Close (File); +end Write_Float_Array; diff --git a/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cob b/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cob new file mode 100644 index 0000000000..7b484f6bac --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cob @@ -0,0 +1,42 @@ + identification division. + program-id. wr-float. + environment division. + input-output section. + file-control. + select report-file assign "float.txt" + organization sequential. + data division. + file section. + fd report-file + report is floats. + working-storage section. + 1 i binary pic 9(4). + 1 x-values comp-2. + 2 value 1.0. + 2 value 2.0. + 2 value 3.0. + 2 value 1.0e11. + 1 redefines x-values comp-2. + 2 x occurs 4. + 1 comp-2. + 2 y occurs 4. + report section. + rd floats. + 1 float-line type de. + 2 line plus 1. + 3 column 1 pic -9.99e+99 source x(i). + 2 column 12 pic -9.9999e+99 source y(i). + procedure division. + begin. + open output report-file + initiate floats + perform varying i from 1 by 1 + until i > 4 + compute y(i) = function sqrt (x(i)) + generate float-line + end-perform + terminate floats + close report-file + stop run + . + end program wr-float. diff --git a/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.eu b/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.eu new file mode 100644 index 0000000000..3533c25c7a --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Euphoria/write-float-arrays-to-a-text-file.eu @@ -0,0 +1,10 @@ +constant x = {1, 2, 3, 1e11}, + y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} + +integer fn + +fn = open("filename","w") +for n = 1 to length(x) do + printf(fn,"%.3g\t%.5g\n",{x[n],y[n]}) +end for +close(fn) diff --git a/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix b/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix index 40eaa6fb1e..760139fbc0 100644 --- a/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix +++ b/Task/Write-float-arrays-to-a-text-file/Phix/write-float-arrays-to-a-text-file.phix @@ -1,10 +1,8 @@ ---> - constant x = {1, 2, 3, 1e11}, - y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} +constant x = {1, 2, 3, 1e11}, + y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791} - integer fn = open("filename","w") - for i=1 to length(x) do - printf(fn,"%.3g\t%.5g\n",{x[i],y[i]}) - end for - close(fn) -